diff --git a/.gitignore b/.gitignore index c5c9445..1d6ee28 100644 --- a/.gitignore +++ b/.gitignore @@ -176,4 +176,6 @@ out # FFL resource files FFLRes*.dat -AFLRes*.dat \ No newline at end of file +AFLRes*.dat + +mii-creator-server \ No newline at end of file diff --git a/.prettierrc b/.prettierrc index f522b85..caebf27 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,7 +1,7 @@ { "arrowParens": "always", "bracketSameLine": false, - "endOfLine": "lf", + "endOfLine": "auto", "singleQuote": false, "semi": true, "trailingComma": "none", diff --git a/build.ts b/build.ts index 715213a..0628de2 100644 --- a/build.ts +++ b/build.ts @@ -1,3 +1,5 @@ +import { stripDebug } from "@namchee/bun-plugin-strip-debug"; + /** * Builds a TypeScript file to a directory. * @param filePath The file path. @@ -15,11 +17,13 @@ export async function compile( splitting: false, emitDCEAnnotations: true, sourcemap: "none", - minify: { - identifiers: true, - syntax: true, - whitespace: true, - }, + // Only apply when building for prod !! + // minify: { + // identifiers: true, + // syntax: true, + // whitespace: true + // } + // plugins: [stripDebug({ exclude: ["warn"] })] }).catch((e) => { console.error("Failed to build:", e); })) as BuildOutput; @@ -39,7 +43,7 @@ import type { BuildOutput } from "bun"; async function build() { try { await compile( - ["./src/main.ts", "./src/api.ts", "./src/worker.ts"], + ["./src/main.ts", "./src/helper.ts", "./src/popup.ts", "./src/worker.ts"], "./public/dist/" ); } catch (e) { diff --git a/bun.lockb b/bun.lockb old mode 100755 new mode 100644 index 4302566..38b2f6c Binary files a/bun.lockb and b/bun.lockb differ diff --git a/gettext.ts b/gettext.ts new file mode 100644 index 0000000..e2a6e2f --- /dev/null +++ b/gettext.ts @@ -0,0 +1,26 @@ +import { GettextExtractor, JsExtractors } from "gettext-extractor"; + +let extractor = new GettextExtractor(); + +extractor + .createJsParser([ + JsExtractors.callExpression("__", { + arguments: { + text: 0, + context: 1 + }, + comments: { otherLineLeading: true } + }), + JsExtractors.callExpression("ngettext", { + arguments: { + text: 1, + textPlural: 2, + context: 3 + } + }) + ]) + .parseFilesGlob("./src/**/*.@(ts|js|tsx|jsx)"); + +extractor.savePotFile("./src/i18n/template.pot"); + +extractor.printStats(); diff --git a/package.json b/package.json index 68060b1..323d89b 100644 --- a/package.json +++ b/package.json @@ -3,25 +3,31 @@ "module": "build.ts", "type": "module", "scripts": { - "build-ts": "bun build.ts", - "serve": "bunx serve -l 3000 -C ./public" + "dev": "bun build.ts", + "serve": "bunx serve -l 3000 -C ./public", + "server": "cd mii-creator-server && bun ." }, "devDependencies": { - "@types/bun": "latest" + "@namchee/bun-plugin-strip-debug": "^1.0.4", + "@types/bun": "latest", + "po2json": "^0.3.0" }, "peerDependencies": { - "typescript": "^5.0.0" + "typescript": "^5.8.2" }, "dependencies": { "@datkat21/html": "^1.2.0", "@sentry/browser": "^8.53.0", "@types/assert": "^1.5.10", + "@types/gettext.js": "^1.0.3", "@types/gsap": "^3.0.0", "@types/md5": "^2.3.5", "@types/three": "^0.173.0", "assert": "^2.1.0", "buffer": "^6.0.3", "camera-controls": "^2.9.0", + "gettext-extractor": "^3.8.0", + "gettext.js": "^2.0.3", "iconv-lite": "^0.6.3", "jszip": "^3.10.1", "kaitai-struct": "^0.10.0", diff --git a/public/assets/audio/miiMakerU.zip b/public/assets/audio/miiMakerU.zip index ec5af46..d947293 100644 Binary files a/public/assets/audio/miiMakerU.zip and b/public/assets/audio/miiMakerU.zip differ diff --git a/public/assets/audio/miiSelector.zip b/public/assets/audio/miiSelector.zip new file mode 100644 index 0000000..de9b0cd Binary files /dev/null and b/public/assets/audio/miiSelector.zip differ diff --git a/public/assets/images/favicon.ico b/public/assets/images/favicon.ico index faff58d..1214626 100644 Binary files a/public/assets/images/favicon.ico and b/public/assets/images/favicon.ico differ diff --git a/public/assets/images/mii_clothes_textures_bundle.zip b/public/assets/images/mii_clothes_textures_bundle.zip new file mode 100644 index 0000000..8fc1b5e Binary files /dev/null and b/public/assets/images/mii_clothes_textures_bundle.zip differ diff --git a/public/assets/images/poses/miitomo/01.png b/public/assets/images/poses/miitomo/01.png index 102d025..3822fb9 100644 Binary files a/public/assets/images/poses/miitomo/01.png and b/public/assets/images/poses/miitomo/01.png differ diff --git a/public/assets/images/poses/miitomo/02.png b/public/assets/images/poses/miitomo/02.png index 944d655..d6263ef 100644 Binary files a/public/assets/images/poses/miitomo/02.png and b/public/assets/images/poses/miitomo/02.png differ diff --git a/public/assets/images/poses/miitomo/03.png b/public/assets/images/poses/miitomo/03.png index 8fe6196..3ed516c 100644 Binary files a/public/assets/images/poses/miitomo/03.png and b/public/assets/images/poses/miitomo/03.png differ diff --git a/public/assets/images/poses/miitomo/04.png b/public/assets/images/poses/miitomo/04.png index d6f0027..6a1617f 100644 Binary files a/public/assets/images/poses/miitomo/04.png and b/public/assets/images/poses/miitomo/04.png differ diff --git a/public/assets/images/poses/miitomo/05.png b/public/assets/images/poses/miitomo/05.png index d6ed564..8a5cfb1 100644 Binary files a/public/assets/images/poses/miitomo/05.png and b/public/assets/images/poses/miitomo/05.png differ diff --git a/public/assets/images/poses/miitomo/06.png b/public/assets/images/poses/miitomo/06.png index b329868..993c890 100644 Binary files a/public/assets/images/poses/miitomo/06.png and b/public/assets/images/poses/miitomo/06.png differ diff --git a/public/assets/images/poses/miitomo/07.png b/public/assets/images/poses/miitomo/07.png index d25762d..a30d09a 100644 Binary files a/public/assets/images/poses/miitomo/07.png and b/public/assets/images/poses/miitomo/07.png differ diff --git a/public/assets/images/poses/miitomo/08.png b/public/assets/images/poses/miitomo/08.png index 2a0ed33..9761306 100644 Binary files a/public/assets/images/poses/miitomo/08.png and b/public/assets/images/poses/miitomo/08.png differ diff --git a/public/assets/images/poses/miitomo/09.png b/public/assets/images/poses/miitomo/09.png index a67fbc8..90d662f 100644 Binary files a/public/assets/images/poses/miitomo/09.png and b/public/assets/images/poses/miitomo/09.png differ diff --git a/public/assets/images/poses/miitomo/10.png b/public/assets/images/poses/miitomo/10.png index de8612c..5670bcd 100644 Binary files a/public/assets/images/poses/miitomo/10.png and b/public/assets/images/poses/miitomo/10.png differ diff --git a/public/assets/images/poses/miitomo/11.png b/public/assets/images/poses/miitomo/11.png index 5e3e08c..7608321 100644 Binary files a/public/assets/images/poses/miitomo/11.png and b/public/assets/images/poses/miitomo/11.png differ diff --git a/public/assets/images/poses/miitomo/12.png b/public/assets/images/poses/miitomo/12.png index 013c4d4..872ed9c 100644 Binary files a/public/assets/images/poses/miitomo/12.png and b/public/assets/images/poses/miitomo/12.png differ diff --git a/public/assets/images/poses/miitomo/13.png b/public/assets/images/poses/miitomo/13.png index 41ab5b1..85e6fac 100644 Binary files a/public/assets/images/poses/miitomo/13.png and b/public/assets/images/poses/miitomo/13.png differ diff --git a/public/assets/images/poses/miitomo/14.png b/public/assets/images/poses/miitomo/14.png index 31b9649..bb8e4d8 100644 Binary files a/public/assets/images/poses/miitomo/14.png and b/public/assets/images/poses/miitomo/14.png differ diff --git a/public/assets/images/poses/miitomo/15.png b/public/assets/images/poses/miitomo/15.png index e84f109..ba396cd 100644 Binary files a/public/assets/images/poses/miitomo/15.png and b/public/assets/images/poses/miitomo/15.png differ diff --git a/public/assets/images/poses/miitomo/16.png b/public/assets/images/poses/miitomo/16.png index 8e8bd95..c6238ec 100644 Binary files a/public/assets/images/poses/miitomo/16.png and b/public/assets/images/poses/miitomo/16.png differ diff --git a/public/assets/images/update_notice/update_notice_image_01.png b/public/assets/images/update_notice/update_notice_image_01.png index 7366e89..526e498 100644 Binary files a/public/assets/images/update_notice/update_notice_image_01.png and b/public/assets/images/update_notice/update_notice_image_01.png differ diff --git a/public/assets/models/miiBodyF_streetpass.glb b/public/assets/models/miiBodyF_streetpass.glb new file mode 100644 index 0000000..8ad7bb2 Binary files /dev/null and b/public/assets/models/miiBodyF_streetpass.glb differ diff --git a/public/assets/models/miiBodyF_wiiu.glb b/public/assets/models/miiBodyF_wiiu.glb index 6093644..2777543 100644 Binary files a/public/assets/models/miiBodyF_wiiu.glb and b/public/assets/models/miiBodyF_wiiu.glb differ diff --git a/public/assets/models/miiBodyM_streetpass.glb b/public/assets/models/miiBodyM_streetpass.glb new file mode 100644 index 0000000..6ef70a8 Binary files /dev/null and b/public/assets/models/miiBodyM_streetpass.glb differ diff --git a/public/assets/models/miiBodyM_wiiu.glb b/public/assets/models/miiBodyM_wiiu.glb index 09125cb..911484b 100644 Binary files a/public/assets/models/miiBodyM_wiiu.glb and b/public/assets/models/miiBodyM_wiiu.glb differ diff --git a/public/dist/api.js b/public/dist/api.js index 4dbe344..c925af7 100644 --- a/public/dist/api.js +++ b/public/dist/api.js @@ -1 +1 @@ -var y=Object.create;var{getPrototypeOf:g,defineProperty:d,getOwnPropertyNames:l,getOwnPropertyDescriptor:p}=Object,u=Object.prototype.hasOwnProperty;var f=(A,e,t)=>{t=A!=null?y(g(A)):{};let i=e||!A||!A.__esModule?d(t,"default",{value:A,enumerable:!0}):t;for(let n of l(A))if(!u.call(i,n))d(i,n,{get:()=>A[n],enumerable:!0});return i},c=/*@__PURE__*/new WeakMap,h=(A)=>{var e=c.get(A),t;if(e)return e;if(e=d({},"__esModule",{value:!0}),A&&typeof A==="object"||typeof A==="function")l(A).map((i)=>!u.call(e,i)&&d(e,i,{get:()=>A[i],enumerable:!(t=p(A,i))||t.enumerable}));return c.set(A,e),e},E=(A,e)=>()=>(e||A((e={exports:{}}).exports,e),e.exports);var v=(A,e)=>{for(var t in e)d(A,t,{get:e[t],enumerable:!0,configurable:!0,set:(i)=>e[t]=()=>i})};var k=(A,e)=>()=>(A&&(e=A(A=0)),e);var Q=/*@__PURE__*/((A)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(A,{get:(e,t)=>(typeof require!=="undefined"?require:e)[t]}):A)(function(A){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+A+'" is not supported')});function w(A,e){let t=document.createElement("iframe");if(e)t.style.width="100%",t.style.height="100%",t.style.top="0",t.style.left="0",t.style.border="0",t.style.position="fixed",t.style.zIndex="99999",document.body.appendChild(t);return t.src=`${import.meta.url.replace("dist/api.js","")}?${A}`,t}var b={configuration:{music:!0},async editMii(A="AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn",e=!0,t=["headshot"]){return new Promise((i,n)=>{let a=w(`data=${encodeURIComponent(A)}&renderTypes=${t.map((s)=>encodeURIComponent(s)).join(",")}&origin=${encodeURIComponent(location.origin)}`,e);function r(){if(e)a.style.width=`${window.innerWidth}px`,a.style.height=`${window.innerHeight}px`}function o(s){let m=s;if(m.data===void 0)return;if(m.data.type===void 0)return;if(m.data.type!=="miic-data-finalize")return;a.style.transition="opacity 0.5s linear",a.style.opacity="0",setTimeout(()=>{a.remove(),window.removeEventListener("resize",r),window.removeEventListener("onmessage",o),i(m.data)},500)}window.addEventListener("resize",r),window.addEventListener("message",o)})},async selectMii(A=!0,e=["headshot"]){return new Promise((t,i)=>{let n=w(`select=yes&renderTypes=${e.map((o)=>encodeURIComponent(o)).join(",")}`,A);function a(){if(A)n.style.width=`${window.innerWidth}px`,n.style.height=`${window.innerHeight}px`}function r(o){let s=o;if(s.data===void 0)return;if(s.data.type===void 0)return;if(s.data.type!=="miic-select")return;n.style.transition="opacity 0.5s linear",n.style.opacity="0",setTimeout(()=>{n.remove(),window.removeEventListener("resize",a),window.removeEventListener("onmessage",r),t(s.data)},500)}window.addEventListener("resize",a),window.addEventListener("message",r)})},newMii(A="male"){switch(A){case"male":return this.editMii("AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn");case"female":return this.editMii("AwEAAAAAAAAAAAAAgN8ZmgAAAAAAAAAAAQBNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAMAQRoQxggNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFik")}},configure(A){if(A.music!==void 0&&typeof A.music==="boolean")this.configuration.music=A.music}};export{b as default}; +var y=Object.create;var{getPrototypeOf:g,defineProperty:d,getOwnPropertyNames:l,getOwnPropertyDescriptor:p}=Object,u=Object.prototype.hasOwnProperty;var f=(A,e,t)=>{t=A!=null?y(g(A)):{};let i=e||!A||!A.__esModule?d(t,"default",{value:A,enumerable:!0}):t;for(let n of l(A))if(!u.call(i,n))d(i,n,{get:()=>A[n],enumerable:!0});return i},c=/*@__PURE__*/new WeakMap,h=(A)=>{var e=c.get(A),t;if(e)return e;if(e=d({},"__esModule",{value:!0}),A&&typeof A==="object"||typeof A==="function")l(A).map((i)=>!u.call(e,i)&&d(e,i,{get:()=>A[i],enumerable:!(t=p(A,i))||t.enumerable}));return c.set(A,e),e},E=(A,e)=>()=>(e||A((e={exports:{}}).exports,e),e.exports);var v=(A,e)=>{for(var t in e)d(A,t,{get:e[t],enumerable:!0,configurable:!0,set:(i)=>e[t]=()=>i})};var k=(A,e)=>()=>(A&&(e=A(A=0)),e);var Q=/*@__PURE__*/((A)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(A,{get:(e,t)=>(typeof require!=="undefined"?require:e)[t]}):A)(function(A){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+A+'" is not supported')});function w(A,e){let t=document.createElement("iframe");if(e)t.style.width="100%",t.style.height="100%",t.style.top="0",t.style.left="0",t.style.border="0",t.style.position="fixed",t.style.zIndex="99999",document.body.appendChild(t);return t.src=`${import.meta.url.replace("dist/api.js","")}?${A}`,t}var b={configuration:{music:!0},async editMii(A="AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn",e=!0,t=["headshot"]){return new Promise((i,n)=>{let a=w(`data=${encodeURIComponent(A)}&renderTypes=${t.map((s)=>encodeURIComponent(s)).join(",")}&origin=${encodeURIComponent(location.origin)}`,e);function r(){if(e)a.style.width=`${window.innerWidth}px`,a.style.height=`${window.innerHeight}px`}function o(s){let m=s;if(m.data===void 0)return;if(m.data.type===void 0)return;if(m.data.type!=="miic-data-finalize")return;a.style.transition="opacity 0.5s linear",a.style.opacity="0",setTimeout(()=>{a.remove(),window.removeEventListener("resize",r),window.removeEventListener("onmessage",o),i(m.data)},500)}window.addEventListener("resize",r),window.addEventListener("message",o)})},async selectMii(A=!0,e=["headshot"]){return new Promise((t,i)=>{let n=w(`select=yes&renderTypes=${e.map((o)=>encodeURIComponent(o)).join(",")}`,A);function a(){if(A)n.style.width=`${window.innerWidth}px`,n.style.height=`${window.innerHeight}px`}function r(o){let s=o;if(s.data===void 0)return;if(s.data.type===void 0)return;if(s.data.type!=="miic-select")return;n.style.transition="opacity 0.5s linear",n.style.opacity="0",setTimeout(()=>{n.remove(),window.removeEventListener("resize",a),window.removeEventListener("onmessage",r),t(s.data)},500)}window.addEventListener("resize",a),window.addEventListener("message",r)})},newMii(A="male"){switch(A){case"male":return this.editMii("AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn");case"female":return this.editMii("AwEAAAAAAAAAAAAAgN8ZmgAAAAAAAAAAAQBNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAMAQRoQxggNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFik")}},configure(A){if(A.music!==void 0&&typeof A.music==="boolean")this.configuration.music=A.music}};export{b as default}; diff --git a/public/dist/ffl-emscripten.wasm b/public/dist/ffl-emscripten.wasm old mode 100644 new mode 100755 index 421b74e..5e277db Binary files a/public/dist/ffl-emscripten.wasm and b/public/dist/ffl-emscripten.wasm differ diff --git a/public/dist/helper.js b/public/dist/helper.js new file mode 100644 index 0000000..9578e8d --- /dev/null +++ b/public/dist/helper.js @@ -0,0 +1,147125 @@ +var __create = Object.create; +var __getProtoOf = Object.getPrototypeOf; +var __defProp = Object.defineProperty; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __toESM = (mod2, isNodeMode, target) => { + target = mod2 != null ? __create(__getProtoOf(mod2)) : {}; + const to = isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target; + for (let key2 of __getOwnPropNames(mod2)) + if (!__hasOwnProp.call(to, key2)) + __defProp(to, key2, { + get: () => mod2[key2], + enumerable: true + }); + return to; +}; +var __moduleCache = /* @__PURE__ */ new WeakMap; +var __toCommonJS = (from) => { + var entry = __moduleCache.get(from), desc; + if (entry) + return entry; + entry = __defProp({}, "__esModule", { value: true }); + if (from && typeof from === "object" || typeof from === "function") + __getOwnPropNames(from).map((key2) => !__hasOwnProp.call(entry, key2) && __defProp(entry, key2, { + get: () => from[key2], + enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable + })); + __moduleCache.set(from, entry); + return entry; +}; +var __commonJS = (cb, mod2) => () => (mod2 || cb((mod2 = { exports: {} }).exports, mod2), mod2.exports); +var __export = (target, all) => { + for (var name2 in all) + __defProp(target, name2, { + get: all[name2], + enumerable: true, + configurable: true, + set: (newValue) => all[name2] = () => newValue + }); +}; +var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res); +var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] +}) : x)(function(x) { + if (typeof require !== "undefined") + return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); +}); + +// src/external/ffl.js/struct-fu.js +var require_struct_fu = __commonJS((exports2, module2) => { + /*! + * struct-fu library: https://github.com/natevw/struct-fu + * forked by ariankordi: https://github.com/ariankordi/struct-fu + * @author Nathan Vander Wilt + * @license Apache-2.0 + * @license BSD-2-Clause + */ + (function(root, factory) { + if (typeof define === "function" && define.amd) { + define([], factory); + } else if (typeof module2 === "object" && module2.exports) { + module2.exports = factory(globalThis.TextEncoder, globalThis.TextDecoder); + } else { + root._ = factory(root.TextEncoder, root.TextDecoder); + } + })(typeof self !== "undefined" ? self : exports2, function(_TextEncoder, _TextDecoder) { + var _ = {}; + if (!("bind" in Function.prototype)) { + Function.prototype.bind = function(owner) { + var that = this; + if (arguments.length <= 1) { + return function() { + return that.apply(owner, arguments); + }; + } + var args = Array.prototype.slice.call(arguments, 1); + return function() { + return that.apply(owner, arguments.length === 0 ? args : args.concat(Array.prototype.slice.call(arguments))); + }; + }; + } + function newBuffer(size) { + return new Uint8Array(new ArrayBuffer(size)); + } + function extend(obj) { + var args = Array.prototype.slice.call(arguments, 1); + args.forEach(function(ext) { + Object.keys(ext).forEach(function(key2) { + obj[key2] = ext[key2]; + }); + }); + return obj; + } + function addField(ctr, f) { + if ("width" in f && typeof f.width === "number") { + ctr.bits = (ctr.bits || 0) + f.width; + while ((ctr.bits || 0) > 7) { + ctr.bytes += 1; + ctr.bits -= 8; + } + } else if (!ctr.bits) { + ctr.bytes += f.size || 0; + } else { + throw Error("Improperly aligned bitfield before field: " + (f.name || "")); + } + return ctr; + } + function arrayizeField(f, count) { + var field = typeof count === "number" ? extend({ + name: f.name, + field: f, + unpack: function(buf, off) { + off || (off = { bytes: 0, bits: 0 }); + var arr = new Array(count); + for (var idx = 0, len = arr.length;idx < len; idx += 1) { + arr[idx] = f.unpack(buf, off); + } + return arr; + }, + pack: function(arr, buf, off) { + arr || (arr = new Array(count)); + buf || (buf = newBuffer(this.size)); + off || (off = { bytes: 0, bits: 0 }); + for (var idx = 0, len = Math.min(arr.length, count);idx < len; idx += 1) { + f.pack(arr[idx], buf, off); + } + while (idx++ < count) + addField(off, f); + return buf; + } + }, f.width !== undefined ? { width: f.width * count } : { size: f.size * count }) : f; + return field; + } + _.struct = function(name2, fields, count) { + var structName; + var fieldDefs; + if (typeof name2 !== "string") { + count = fields; + fieldDefs = name2; + } else { + structName = name2; + fieldDefs = fields; + } + var _size = { bytes: 0, bits: 0 }; + var _padsById = Object.create(null); + function reduceFunc(obj, f) { + if ("_padTo" in f) { + var padField = f; + if (!padField._id) { + padField._id = "id" + Math.random().toFixed(20).slice(2); + } + var neededPadBytes = padField._padTo - _size.bytes; + if (_size.bits) { + var bitsNeeded = 8 * neededPadBytes - _size.bits; + if (bitsNeeded < 0) { + throw Error("Invalid .padTo(" + padField._padTo + ") field, struct is already " + _size.bytes + " byte(s) and " + _size.bits + " bits!"); + } + _padsById[padField._id] = { width: bitsNeeded }; + f.width = bitsNeeded; + } else { + if (neededPadBytes < 0) { + throw Error("Invalid .padTo(" + padField._padTo + ") field, struct is already " + _size.bytes + " bytes!"); + } + _padsById[padField._id] = { size: neededPadBytes }; + f.size = neededPadBytes; + } + } + if (f._hoistFields) { + var hoistFields = f._hoistFields; + Object.keys(hoistFields).forEach(function(subName) { + var _f = Object.create(hoistFields[subName]); + if ("width" in _f && typeof _f.width === "number") { + _f.offset = { bytes: _f.offset.bytes + _size.bytes, bits: _f.offset.bits }; + } else { + _f.offset = _f.offset + _size.bytes; + } + obj[subName] = _f; + }); + } else if (f.name) { + var localCopy = Object.create(f); + if ("width" in localCopy && typeof localCopy.width === "number") { + localCopy.offset = { bytes: _size.bytes, bits: _size.bits }; + } else { + localCopy.offset = _size.bytes; + } + obj[f.name] = localCopy; + } + addField(_size, f); + return obj; + } + var fieldsObj = fieldDefs.reduce(reduceFunc, {}); + if (_size.bits) { + throw Error("Improperly aligned bitfield at end of struct: " + (structName || "")); + } + var structField = { + unpack: function(buf, off) { + off = off || { bytes: 0, bits: 0 }; + var obj = {}; + fieldDefs.forEach(function(f) { + if ("_padTo" in f && f._id !== undefined) { + addField(off, _padsById[f._id]); + return; + } + var value2 = f.unpack(buf, off); + if (f.name) { + obj[f.name] = value2; + } else if (typeof value2 === "object") { + extend(obj, value2); + } + }); + return obj; + }, + pack: function(obj, buf, off) { + obj = obj || {}; + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0, bits: 0 }; + fieldDefs.forEach(function(f) { + if ("_padTo" in f && f._id !== undefined) { + addField(off, _padsById[f._id]); + return; + } + var value2 = f.name ? obj[f.name] : obj; + f.pack(value2, buf, off); + }); + return buf; + }, + _hoistFields: structName ? null : fieldsObj, + fields: fieldsObj, + size: _size.bytes, + name: structName + }; + return arrayizeField(structField, count); + }; + function truncatedReadUInt32(buffer, offset, littleEndian) { + var bytes = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : buffer; + var availableBytes = bytes.length - offset; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + if (availableBytes >= 4) { + return view.getUint32(offset, littleEndian); + } else if (availableBytes === 3) { + var first2 = view.getUint16(offset, littleEndian); + var second = view.getUint8(offset + 2); + return littleEndian ? (second << 16) + first2 >>> 0 : (first2 << 8) + second << 8 >>> 0; + } else if (availableBytes === 2) { + return view.getUint16(offset, littleEndian) << (littleEndian ? 0 : 16) >>> 0; + } else if (availableBytes === 1) { + return view.getUint8(offset) << (littleEndian ? 0 : 24) >>> 0; + } + return 0; + } + function truncatedWriteUInt32(buffer, offset, data2, littleEndian) { + var bytes = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : buffer; + var availableBytes = bytes.length - offset; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + if (availableBytes >= 4) { + view.setUint32(offset, data2, littleEndian); + } else if (availableBytes === 3) { + if (littleEndian) { + view.setUint8(offset, data2 & 255); + view.setUint16(offset + 1, data2 >>> 8, littleEndian); + } else { + view.setUint16(offset, data2 >>> 16, littleEndian); + view.setUint8(offset + 2, data2 >>> 8 & 255); + } + } else if (availableBytes === 2) { + view.setUint16(offset, littleEndian ? data2 & 65535 : data2 >>> 16, littleEndian); + } else if (availableBytes === 1) { + view.setUint8(offset, littleEndian ? data2 & 255 : data2 >>> 24); + } + } + _.padTo = function(off) { + var field = { + _padTo: off, + size: 0, + unpack: function() { + return null; + }, + pack: function() { + return newBuffer(0); + } + }; + return field; + }; + var FULL = 4294967295; + function bitfield(name2, width2, count) { + if (width2 === undefined) { + width2 = 1; + } + if (width2 > 24) { + throw Error("Bitfields support a maximum width of 24 bits."); + } + var mask2 = FULL >>> 32 - width2; + var littleEndian = this.littleEndian; + if (littleEndian) { + mask2 >>>= 0; + } + var impl = this; + return arrayizeField({ + unpack: function(buf, off) { + off = off || { bytes: 0, bits: 0 }; + var over; + var end; + var word; + if (littleEndian) { + end = off.bits || 0; + word = truncatedReadUInt32(buf, off.bytes, true) >>> 0; + over = word >>> end; + } else { + end = (off.bits || 0) + width2; + word = truncatedReadUInt32(buf, off.bytes, false) || 0; + over = word >>> 32 - end; + } + addField(off, this); + return impl.b2v.call(this, over & mask2); + }, + pack: function(val2, buf, off) { + val2 = impl.v2b.call(this, val2 || 0); + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0, bits: 0 }; + var word; + var zero; + var over; + if (littleEndian) { + word = truncatedReadUInt32(buf, off.bytes, true) >>> 0; + var shift = off.bits || 0; + zero = mask2 << shift >>> 0; + word &= ~zero; + over = (val2 & mask2) << shift; + word = (word | over) >>> 0; + truncatedWriteUInt32(buf, off.bytes, word, true); + } else { + var end = (off.bits || 0) + width2; + word = truncatedReadUInt32(buf, off.bytes, false) || 0; + zero = mask2 << 32 - end; + over = (val2 & mask2) << 32 - end; + word &= ~zero; + word = (word | over) >>> 0; + truncatedWriteUInt32(buf, off.bytes, word, false); + } + addField(off, this); + return new Uint8Array(buf); + }, + width: width2, + size: 0, + name: name2 + }, count); + } + _.bool = function(name2, count) { + return bitfield.call({ + b2v: function(b) { + return Boolean(b); + }, + v2b: function(v) { + return v ? FULL : 0; + } + }, name2, 1, count); + }; + _.ubit = bitfield.bind({ + b2v: function(b) { + return b; + }, + v2b: function(v) { + return Number(v); + } + }); + _.ubitLE = bitfield.bind({ + b2v: function(b) { + return b; + }, + v2b: function(v) { + return Number(v); + }, + littleEndian: true + }); + _.sbit = bitfield.bind({ + b2v: function(b) { + var m = 1 << (this.width || 1) - 1; + var s = b & m; + return s ? -(b &= ~m) : b; + }, + v2b: function(v) { + v = Number(v); + var m = 1 << (this.width || 1) - 1; + var s = v < 0; + return s ? -v | m : v; + } + }); + function bytefield(name2, size, count) { + var fieldName; + var fieldSize = 1; + if (typeof name2 === "string") { + fieldName = name2; + if (typeof size === "number") { + fieldSize = size; + } + } else { + fieldSize = name2; + count = size; + } + var impl = this; + return arrayizeField({ + name: fieldName, + size: fieldSize, + unpack: function(buf, off) { + off = off || { bytes: 0, bits: 0 }; + var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; + var val2 = bytes.subarray(off.bytes, off.bytes + this.size); + addField(off, this); + return impl.b2v.call(this, val2); + }, + pack: function(val2, buf, off) { + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0, bits: 0 }; + var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; + var blk = bytes.subarray(off.bytes, off.bytes + this.size); + impl.vTb.call(this, val2, blk); + addField(off, this); + return buf; + }, + b2v: function(b) { + return b; + }, + vTb: function(v, b) { + if (!v) + return 0; + var src = new Uint8Array(v); + b.set(src.subarray(0, b.length)); + return b.length; + } + }, count); + } + function swapBytesPairs(fromBuffer, toBuffer) { + toBuffer = toBuffer || fromBuffer; + var l = fromBuffer.length; + for (var i = 1;i < l; i += 2) { + var a = fromBuffer[i - 1]; + toBuffer[i - 1] = fromBuffer[i]; + toBuffer[i] = a; + } + return toBuffer; + } + _.byte = bytefield.bind({ + b2v: function(b) { + return new Uint8Array(b); + }, + vTb: function(v, b) { + if (!v) + return 0; + b.set(new Uint8Array(v)); + return v.byteLength; + } + }); + _.char = bytefield.bind({ + b2v: function(b) { + var decoder; + if (typeof _TextDecoder !== "undefined" && _TextDecoder) { + decoder = new _TextDecoder("utf-8"); + } else { + decoder = { + decode: function(buf) { + var bytes = new Uint8Array(buf); + var str = ""; + for (var i = 0;i < bytes.length; i++) { + str += String.fromCharCode(bytes[i]); + } + return str; + } + }; + } + var v = decoder.decode(b); + var z = v.indexOf("\x00"); + return ~z ? v.slice(0, z) : v; + }, + vTb: function(v, b) { + v || (v = ""); + var encoder; + if (typeof _TextEncoder !== "undefined" && _TextEncoder) { + encoder = new _TextEncoder; + } else { + encoder = { + encode: function(str) { + var arr = new Uint8Array(str.length); + for (var i2 = 0;i2 < str.length; i2++) { + arr[i2] = str.charCodeAt(i2) & 255; + } + return arr; + } + }; + } + var encoded = encoder.encode(v); + for (var i = 0;i < encoded.length && i < b.length; i++) { + b[i] = encoded[i]; + } + return encoded.length; + } + }); + _.char16le = bytefield.bind({ + b2v: function(b) { + var decoder; + if (typeof _TextDecoder !== "undefined" && _TextDecoder) { + decoder = new _TextDecoder("utf-16le"); + } else { + decoder = { + decode: function(buf) { + var bytes = new Uint8Array(buf); + var str = ""; + for (var i = 0;i < bytes.length; i += 2) { + var charCode = bytes[i] | bytes[i + 1] << 8; + str += String.fromCharCode(charCode); + } + return str; + } + }; + } + var v = decoder.decode(b); + var z = v.indexOf("\x00"); + return ~z ? v.slice(0, z) : v; + }, + vTb: function(v, b) { + v || (v = ""); + var bytesWritten = 0; + for (var i = 0;i < v.length && bytesWritten + 1 < b.length; i++) { + var charCode = v.charCodeAt(i); + b[bytesWritten++] = charCode & 255; + b[bytesWritten++] = charCode >> 8 & 255; + } + return bytesWritten; + } + }); + _.char16be = bytefield.bind({ + b2v: function(b) { + var temp = new Uint8Array(b); + swapBytesPairs(temp); + var decoder; + if (typeof _TextDecoder !== "undefined" && _TextDecoder) { + decoder = new _TextDecoder("utf-16le"); + } else { + decoder = { + decode: function(buf) { + var bytes = new Uint8Array(buf); + var str = ""; + for (var i = 0;i < bytes.length; i += 2) { + var charCode = bytes[i] | bytes[i + 1] << 8; + str += String.fromCharCode(charCode); + } + return str; + } + }; + } + var v = decoder.decode(temp.buffer); + var z = v.indexOf("\x00"); + return ~z ? v.slice(0, z) : v; + }, + vTb: function(v, b) { + v || (v = ""); + var temp = new Uint8Array(b.length); + var bytesWritten = 0; + for (var i = 0;i < v.length && bytesWritten + 1 < temp.length; i++) { + var charCode = v.charCodeAt(i); + temp[bytesWritten++] = charCode & 255; + temp[bytesWritten++] = charCode >> 8 & 255; + } + swapBytesPairs(temp, b); + return bytesWritten; + } + }); + function dataViewField(getFn, setFn, size, littleEndian) { + var func = function(name2, count) { + var fieldName; + if (typeof name2 === "string") { + fieldName = name2; + } else { + count = name2; + } + return arrayizeField({ + name: fieldName, + size, + unpack: function(buf, off) { + off = off || { bytes: 0 }; + var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + var val2 = getFn.call(view, off.bytes, littleEndian); + addField(off, this); + return val2; + }, + pack: function(val2, buf, off) { + if (val2 === undefined || val2 === null) { + val2 = 0; + } + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0 }; + var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + setFn.call(view, off.bytes, val2, littleEndian); + addField(off, this); + return new Uint8Array(buf); + } + }, count); + }; + return func; + } + var DV = DataView.prototype; + _.uint8 = dataViewField(DV.getUint8, DV.setUint8, 1, false); + _.uint16 = dataViewField(DV.getUint16, DV.setUint16, 2, false); + _.uint32 = dataViewField(DV.getUint32, DV.setUint32, 4, false); + _.uint16le = dataViewField(DV.getUint16, DV.setUint16, 2, true); + _.uint32le = dataViewField(DV.getUint32, DV.setUint32, 4, true); + _.int8 = dataViewField(DV.getInt8, DV.setInt8, 1, false); + _.int16 = dataViewField(DV.getInt16, DV.setInt16, 2, false); + _.int32 = dataViewField(DV.getInt32, DV.setInt32, 4, false); + _.int16le = dataViewField(DV.getInt16, DV.setInt16, 2, true); + _.int32le = dataViewField(DV.getInt32, DV.setInt32, 4, true); + _.float32 = dataViewField(DV.getFloat32, DV.setFloat32, 4, false); + _.float64 = dataViewField(DV.getFloat64, DV.setFloat64, 8, false); + _.float32le = dataViewField(DV.getFloat32, DV.setFloat32, 4, true); + _.float64le = dataViewField(DV.getFloat64, DV.setFloat64, 8, true); + _.derive = function(orig, pack, unpack) { + var func = function(name2, count) { + var fieldName = null; + if (typeof name2 === "string") { + fieldName = name2; + } else { + count = name2; + } + var derived = extend({ + unpack: function(buf, off) { + var rawVal = orig.unpack(buf, off); + return unpack(rawVal); + }, + pack: function(val2, buf, off) { + var packed = pack(val2); + return orig.pack(packed, buf, off); + }, + name: fieldName + }, "width" in orig ? { width: orig.width } : { size: orig.size }); + return arrayizeField(derived, count); + }; + return func; + }; + return _; + }); +}); + +// node_modules/three/build/three.cjs +var require_three = __commonJS((exports2) => { + var REVISION2 = "173"; + var MOUSE2 = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; + var TOUCH2 = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; + var CullFaceNone2 = 0; + var CullFaceBack2 = 1; + var CullFaceFront2 = 2; + var CullFaceFrontBack2 = 3; + var BasicShadowMap2 = 0; + var PCFShadowMap2 = 1; + var PCFSoftShadowMap2 = 2; + var VSMShadowMap2 = 3; + var FrontSide2 = 0; + var BackSide2 = 1; + var DoubleSide2 = 2; + var NoBlending2 = 0; + var NormalBlending2 = 1; + var AdditiveBlending2 = 2; + var SubtractiveBlending2 = 3; + var MultiplyBlending2 = 4; + var CustomBlending2 = 5; + var AddEquation2 = 100; + var SubtractEquation2 = 101; + var ReverseSubtractEquation2 = 102; + var MinEquation2 = 103; + var MaxEquation2 = 104; + var ZeroFactor2 = 200; + var OneFactor2 = 201; + var SrcColorFactor2 = 202; + var OneMinusSrcColorFactor2 = 203; + var SrcAlphaFactor2 = 204; + var OneMinusSrcAlphaFactor2 = 205; + var DstAlphaFactor2 = 206; + var OneMinusDstAlphaFactor2 = 207; + var DstColorFactor2 = 208; + var OneMinusDstColorFactor2 = 209; + var SrcAlphaSaturateFactor2 = 210; + var ConstantColorFactor2 = 211; + var OneMinusConstantColorFactor2 = 212; + var ConstantAlphaFactor2 = 213; + var OneMinusConstantAlphaFactor2 = 214; + var NeverDepth2 = 0; + var AlwaysDepth2 = 1; + var LessDepth2 = 2; + var LessEqualDepth2 = 3; + var EqualDepth2 = 4; + var GreaterEqualDepth2 = 5; + var GreaterDepth2 = 6; + var NotEqualDepth2 = 7; + var MultiplyOperation2 = 0; + var MixOperation2 = 1; + var AddOperation2 = 2; + var NoToneMapping2 = 0; + var LinearToneMapping2 = 1; + var ReinhardToneMapping2 = 2; + var CineonToneMapping2 = 3; + var ACESFilmicToneMapping2 = 4; + var CustomToneMapping2 = 5; + var AgXToneMapping2 = 6; + var NeutralToneMapping2 = 7; + var AttachedBindMode2 = "attached"; + var DetachedBindMode2 = "detached"; + var UVMapping2 = 300; + var CubeReflectionMapping2 = 301; + var CubeRefractionMapping2 = 302; + var EquirectangularReflectionMapping2 = 303; + var EquirectangularRefractionMapping2 = 304; + var CubeUVReflectionMapping2 = 306; + var RepeatWrapping2 = 1000; + var ClampToEdgeWrapping2 = 1001; + var MirroredRepeatWrapping2 = 1002; + var NearestFilter2 = 1003; + var NearestMipmapNearestFilter2 = 1004; + var NearestMipMapNearestFilter2 = 1004; + var NearestMipmapLinearFilter2 = 1005; + var NearestMipMapLinearFilter2 = 1005; + var LinearFilter2 = 1006; + var LinearMipmapNearestFilter2 = 1007; + var LinearMipMapNearestFilter2 = 1007; + var LinearMipmapLinearFilter2 = 1008; + var LinearMipMapLinearFilter2 = 1008; + var UnsignedByteType2 = 1009; + var ByteType2 = 1010; + var ShortType2 = 1011; + var UnsignedShortType2 = 1012; + var IntType2 = 1013; + var UnsignedIntType2 = 1014; + var FloatType2 = 1015; + var HalfFloatType2 = 1016; + var UnsignedShort4444Type2 = 1017; + var UnsignedShort5551Type2 = 1018; + var UnsignedInt248Type2 = 1020; + var UnsignedInt5999Type2 = 35902; + var AlphaFormat2 = 1021; + var RGBFormat2 = 1022; + var RGBAFormat2 = 1023; + var LuminanceFormat2 = 1024; + var LuminanceAlphaFormat2 = 1025; + var DepthFormat2 = 1026; + var DepthStencilFormat2 = 1027; + var RedFormat2 = 1028; + var RedIntegerFormat2 = 1029; + var RGFormat2 = 1030; + var RGIntegerFormat2 = 1031; + var RGBIntegerFormat2 = 1032; + var RGBAIntegerFormat2 = 1033; + var RGB_S3TC_DXT1_Format2 = 33776; + var RGBA_S3TC_DXT1_Format2 = 33777; + var RGBA_S3TC_DXT3_Format2 = 33778; + var RGBA_S3TC_DXT5_Format2 = 33779; + var RGB_PVRTC_4BPPV1_Format2 = 35840; + var RGB_PVRTC_2BPPV1_Format2 = 35841; + var RGBA_PVRTC_4BPPV1_Format2 = 35842; + var RGBA_PVRTC_2BPPV1_Format2 = 35843; + var RGB_ETC1_Format2 = 36196; + var RGB_ETC2_Format2 = 37492; + var RGBA_ETC2_EAC_Format2 = 37496; + var RGBA_ASTC_4x4_Format2 = 37808; + var RGBA_ASTC_5x4_Format2 = 37809; + var RGBA_ASTC_5x5_Format2 = 37810; + var RGBA_ASTC_6x5_Format2 = 37811; + var RGBA_ASTC_6x6_Format2 = 37812; + var RGBA_ASTC_8x5_Format2 = 37813; + var RGBA_ASTC_8x6_Format2 = 37814; + var RGBA_ASTC_8x8_Format2 = 37815; + var RGBA_ASTC_10x5_Format2 = 37816; + var RGBA_ASTC_10x6_Format2 = 37817; + var RGBA_ASTC_10x8_Format2 = 37818; + var RGBA_ASTC_10x10_Format2 = 37819; + var RGBA_ASTC_12x10_Format2 = 37820; + var RGBA_ASTC_12x12_Format2 = 37821; + var RGBA_BPTC_Format2 = 36492; + var RGB_BPTC_SIGNED_Format2 = 36494; + var RGB_BPTC_UNSIGNED_Format2 = 36495; + var RED_RGTC1_Format2 = 36283; + var SIGNED_RED_RGTC1_Format2 = 36284; + var RED_GREEN_RGTC2_Format2 = 36285; + var SIGNED_RED_GREEN_RGTC2_Format2 = 36286; + var LoopOnce2 = 2200; + var LoopRepeat2 = 2201; + var LoopPingPong2 = 2202; + var InterpolateDiscrete2 = 2300; + var InterpolateLinear2 = 2301; + var InterpolateSmooth2 = 2302; + var ZeroCurvatureEnding2 = 2400; + var ZeroSlopeEnding2 = 2401; + var WrapAroundEnding2 = 2402; + var NormalAnimationBlendMode2 = 2500; + var AdditiveAnimationBlendMode2 = 2501; + var TrianglesDrawMode2 = 0; + var TriangleStripDrawMode2 = 1; + var TriangleFanDrawMode2 = 2; + var BasicDepthPacking2 = 3200; + var RGBADepthPacking2 = 3201; + var RGBDepthPacking2 = 3202; + var RGDepthPacking2 = 3203; + var TangentSpaceNormalMap2 = 0; + var ObjectSpaceNormalMap2 = 1; + var NoColorSpace2 = ""; + var SRGBColorSpace2 = "srgb"; + var LinearSRGBColorSpace2 = "srgb-linear"; + var LinearTransfer2 = "linear"; + var SRGBTransfer2 = "srgb"; + var ZeroStencilOp2 = 0; + var KeepStencilOp2 = 7680; + var ReplaceStencilOp2 = 7681; + var IncrementStencilOp2 = 7682; + var DecrementStencilOp2 = 7683; + var IncrementWrapStencilOp2 = 34055; + var DecrementWrapStencilOp2 = 34056; + var InvertStencilOp2 = 5386; + var NeverStencilFunc2 = 512; + var LessStencilFunc2 = 513; + var EqualStencilFunc2 = 514; + var LessEqualStencilFunc2 = 515; + var GreaterStencilFunc2 = 516; + var NotEqualStencilFunc2 = 517; + var GreaterEqualStencilFunc2 = 518; + var AlwaysStencilFunc2 = 519; + var NeverCompare2 = 512; + var LessCompare2 = 513; + var EqualCompare2 = 514; + var LessEqualCompare2 = 515; + var GreaterCompare2 = 516; + var NotEqualCompare2 = 517; + var GreaterEqualCompare2 = 518; + var AlwaysCompare2 = 519; + var StaticDrawUsage2 = 35044; + var DynamicDrawUsage2 = 35048; + var StreamDrawUsage2 = 35040; + var StaticReadUsage2 = 35045; + var DynamicReadUsage2 = 35049; + var StreamReadUsage2 = 35041; + var StaticCopyUsage2 = 35046; + var DynamicCopyUsage2 = 35050; + var StreamCopyUsage2 = 35042; + var GLSL12 = "100"; + var GLSL32 = "300 es"; + var WebGLCoordinateSystem2 = 2000; + var WebGPUCoordinateSystem2 = 2001; + var TimestampQuery2 = { + COMPUTE: "compute", + RENDER: "render" + }; + + class EventDispatcher2 { + addEventListener(type, listener) { + if (this._listeners === undefined) + this._listeners = {}; + const listeners = this._listeners; + if (listeners[type] === undefined) { + listeners[type] = []; + } + if (listeners[type].indexOf(listener) === -1) { + listeners[type].push(listener); + } + } + hasEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === undefined) + return false; + return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1; + } + removeEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === undefined) + return; + const listenerArray = listeners[type]; + if (listenerArray !== undefined) { + const index2 = listenerArray.indexOf(listener); + if (index2 !== -1) { + listenerArray.splice(index2, 1); + } + } + } + dispatchEvent(event) { + const listeners = this._listeners; + if (listeners === undefined) + return; + const listenerArray = listeners[event.type]; + if (listenerArray !== undefined) { + event.target = this; + const array = listenerArray.slice(0); + for (let i = 0, l = array.length;i < l; i++) { + array[i].call(this, event); + } + event.target = null; + } + } + } + var _lut2 = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"]; + var _seed2 = 1234567; + var DEG2RAD2 = Math.PI / 180; + var RAD2DEG2 = 180 / Math.PI; + function generateUUID2() { + const d0 = Math.random() * 4294967295 | 0; + const d1 = Math.random() * 4294967295 | 0; + const d2 = Math.random() * 4294967295 | 0; + const d3 = Math.random() * 4294967295 | 0; + const uuid = _lut2[d0 & 255] + _lut2[d0 >> 8 & 255] + _lut2[d0 >> 16 & 255] + _lut2[d0 >> 24 & 255] + "-" + _lut2[d1 & 255] + _lut2[d1 >> 8 & 255] + "-" + _lut2[d1 >> 16 & 15 | 64] + _lut2[d1 >> 24 & 255] + "-" + _lut2[d2 & 63 | 128] + _lut2[d2 >> 8 & 255] + "-" + _lut2[d2 >> 16 & 255] + _lut2[d2 >> 24 & 255] + _lut2[d3 & 255] + _lut2[d3 >> 8 & 255] + _lut2[d3 >> 16 & 255] + _lut2[d3 >> 24 & 255]; + return uuid.toLowerCase(); + } + function clamp3(value2, min, max) { + return Math.max(min, Math.min(max, value2)); + } + function euclideanModulo2(n, m) { + return (n % m + m) % m; + } + function mapLinear2(x, a1, a2, b1, b2) { + return b1 + (x - a1) * (b2 - b1) / (a2 - a1); + } + function inverseLerp2(x, y, value2) { + if (x !== y) { + return (value2 - x) / (y - x); + } else { + return 0; + } + } + function lerp2(x, y, t) { + return (1 - t) * x + t * y; + } + function damp2(x, y, lambda, dt) { + return lerp2(x, y, 1 - Math.exp(-lambda * dt)); + } + function pingpong2(x, length2 = 1) { + return length2 - Math.abs(euclideanModulo2(x, length2 * 2) - length2); + } + function smoothstep2(x, min, max) { + if (x <= min) + return 0; + if (x >= max) + return 1; + x = (x - min) / (max - min); + return x * x * (3 - 2 * x); + } + function smootherstep2(x, min, max) { + if (x <= min) + return 0; + if (x >= max) + return 1; + x = (x - min) / (max - min); + return x * x * x * (x * (x * 6 - 15) + 10); + } + function randInt2(low, high) { + return low + Math.floor(Math.random() * (high - low + 1)); + } + function randFloat2(low, high) { + return low + Math.random() * (high - low); + } + function randFloatSpread2(range) { + return range * (0.5 - Math.random()); + } + function seededRandom2(s) { + if (s !== undefined) + _seed2 = s; + let t = _seed2 += 1831565813; + t = Math.imul(t ^ t >>> 15, t | 1); + t ^= t + Math.imul(t ^ t >>> 7, t | 61); + return ((t ^ t >>> 14) >>> 0) / 4294967296; + } + function degToRad2(degrees) { + return degrees * DEG2RAD2; + } + function radToDeg2(radians) { + return radians * RAD2DEG2; + } + function isPowerOfTwo2(value2) { + return (value2 & value2 - 1) === 0 && value2 !== 0; + } + function ceilPowerOfTwo2(value2) { + return Math.pow(2, Math.ceil(Math.log(value2) / Math.LN2)); + } + function floorPowerOfTwo2(value2) { + return Math.pow(2, Math.floor(Math.log(value2) / Math.LN2)); + } + function setQuaternionFromProperEuler2(q, a, b, c, order) { + const cos = Math.cos; + const sin = Math.sin; + const c2 = cos(b / 2); + const s2 = sin(b / 2); + const c13 = cos((a + c) / 2); + const s13 = sin((a + c) / 2); + const c1_3 = cos((a - c) / 2); + const s1_3 = sin((a - c) / 2); + const c3_1 = cos((c - a) / 2); + const s3_1 = sin((c - a) / 2); + switch (order) { + case "XYX": + q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13); + break; + case "YZY": + q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13); + break; + case "ZXZ": + q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13); + break; + case "XZX": + q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13); + break; + case "YXY": + q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13); + break; + case "ZYZ": + q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13); + break; + default: + console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + order); + } + } + function denormalize2(value2, array) { + switch (array.constructor) { + case Float32Array: + return value2; + case Uint32Array: + return value2 / 4294967295; + case Uint16Array: + return value2 / 65535; + case Uint8Array: + return value2 / 255; + case Int32Array: + return Math.max(value2 / 2147483647, -1); + case Int16Array: + return Math.max(value2 / 32767, -1); + case Int8Array: + return Math.max(value2 / 127, -1); + default: + throw new Error("Invalid component type."); + } + } + function normalize3(value2, array) { + switch (array.constructor) { + case Float32Array: + return value2; + case Uint32Array: + return Math.round(value2 * 4294967295); + case Uint16Array: + return Math.round(value2 * 65535); + case Uint8Array: + return Math.round(value2 * 255); + case Int32Array: + return Math.round(value2 * 2147483647); + case Int16Array: + return Math.round(value2 * 32767); + case Int8Array: + return Math.round(value2 * 127); + default: + throw new Error("Invalid component type."); + } + } + var MathUtils2 = { + DEG2RAD: DEG2RAD2, + RAD2DEG: RAD2DEG2, + generateUUID: generateUUID2, + clamp: clamp3, + euclideanModulo: euclideanModulo2, + mapLinear: mapLinear2, + inverseLerp: inverseLerp2, + lerp: lerp2, + damp: damp2, + pingpong: pingpong2, + smoothstep: smoothstep2, + smootherstep: smootherstep2, + randInt: randInt2, + randFloat: randFloat2, + randFloatSpread: randFloatSpread2, + seededRandom: seededRandom2, + degToRad: degToRad2, + radToDeg: radToDeg2, + isPowerOfTwo: isPowerOfTwo2, + ceilPowerOfTwo: ceilPowerOfTwo2, + floorPowerOfTwo: floorPowerOfTwo2, + setQuaternionFromProperEuler: setQuaternionFromProperEuler2, + normalize: normalize3, + denormalize: denormalize2 + }; + + class Vector22 { + constructor(x = 0, y = 0) { + Vector22.prototype.isVector2 = true; + this.x = x; + this.y = y; + } + get width() { + return this.x; + } + set width(value2) { + this.x = value2; + } + get height() { + return this.y; + } + set height(value2) { + this.y = value2; + } + set(x, y) { + this.x = x; + this.y = y; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y); + } + copy(v) { + this.x = v.x; + this.y = v.y; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + applyMatrix3(m) { + const x = this.x, y = this.y; + const e = m.elements; + this.x = e[0] * x + e[3] * y + e[6]; + this.y = e[1] * x + e[4] * y + e[7]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + return this; + } + clamp(min, max) { + this.x = clamp3(this.x, min.x, max.x); + this.y = clamp3(this.y, min.y, max.y); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp3(this.x, minVal, maxVal); + this.y = clamp3(this.y, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp3(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y; + } + cross(v) { + return this.x * v.y - this.y * v.x; + } + lengthSq() { + return this.x * this.x + this.y * this.y; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + angle() { + const angle = Math.atan2(-this.y, -this.x) + Math.PI; + return angle; + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) + return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp3(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + return this; + } + rotateAround(center, angle) { + const c = Math.cos(angle), s = Math.sin(angle); + const x = this.x - center.x; + const y = this.y - center.y; + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + } + } + + class Matrix32 { + constructor(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + Matrix32.prototype.isMatrix3 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n13, n21, n22, n23, n31, n32, n33); + } + } + set(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + const te = this.elements; + te[0] = n11; + te[1] = n21; + te[2] = n31; + te[3] = n12; + te[4] = n22; + te[5] = n32; + te[6] = n13; + te[7] = n23; + te[8] = n33; + return this; + } + identity() { + this.set(1, 0, 0, 0, 1, 0, 0, 0, 1); + return this; + } + copy(m) { + const te = this.elements; + const me = m.elements; + te[0] = me[0]; + te[1] = me[1]; + te[2] = me[2]; + te[3] = me[3]; + te[4] = me[4]; + te[5] = me[5]; + te[6] = me[6]; + te[7] = me[7]; + te[8] = me[8]; + return this; + } + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrix3Column(this, 0); + yAxis.setFromMatrix3Column(this, 1); + zAxis.setFromMatrix3Column(this, 2); + return this; + } + setFromMatrix4(m) { + const me = m.elements; + this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]); + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a, b) { + const ae = a.elements; + const be = b.elements; + const te = this.elements; + const a11 = ae[0], a12 = ae[3], a13 = ae[6]; + const a21 = ae[1], a22 = ae[4], a23 = ae[7]; + const a31 = ae[2], a32 = ae[5], a33 = ae[8]; + const b11 = be[0], b12 = be[3], b13 = be[6]; + const b21 = be[1], b22 = be[4], b23 = be[7]; + const b31 = be[2], b32 = be[5], b33 = be[8]; + te[0] = a11 * b11 + a12 * b21 + a13 * b31; + te[3] = a11 * b12 + a12 * b22 + a13 * b32; + te[6] = a11 * b13 + a12 * b23 + a13 * b33; + te[1] = a21 * b11 + a22 * b21 + a23 * b31; + te[4] = a21 * b12 + a22 * b22 + a23 * b32; + te[7] = a21 * b13 + a22 * b23 + a23 * b33; + te[2] = a31 * b11 + a32 * b21 + a33 * b31; + te[5] = a31 * b12 + a32 * b22 + a33 * b32; + te[8] = a31 * b13 + a32 * b23 + a33 * b33; + return this; + } + multiplyScalar(s) { + const te = this.elements; + te[0] *= s; + te[3] *= s; + te[6] *= s; + te[1] *= s; + te[4] *= s; + te[7] *= s; + te[2] *= s; + te[5] *= s; + te[8] *= s; + return this; + } + determinant() { + const te = this.elements; + const a = te[0], b = te[1], c = te[2], d = te[3], e = te[4], f = te[5], g = te[6], h = te[7], i = te[8]; + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + } + invert() { + const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n12 = te[3], n22 = te[4], n32 = te[5], n13 = te[6], n23 = te[7], n33 = te[8], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13; + if (det === 0) + return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te[0] = t11 * detInv; + te[1] = (n31 * n23 - n33 * n21) * detInv; + te[2] = (n32 * n21 - n31 * n22) * detInv; + te[3] = t12 * detInv; + te[4] = (n33 * n11 - n31 * n13) * detInv; + te[5] = (n31 * n12 - n32 * n11) * detInv; + te[6] = t13 * detInv; + te[7] = (n21 * n13 - n23 * n11) * detInv; + te[8] = (n22 * n11 - n21 * n12) * detInv; + return this; + } + transpose() { + let tmp3; + const m = this.elements; + tmp3 = m[1]; + m[1] = m[3]; + m[3] = tmp3; + tmp3 = m[2]; + m[2] = m[6]; + m[6] = tmp3; + tmp3 = m[5]; + m[5] = m[7]; + m[7] = tmp3; + return this; + } + getNormalMatrix(matrix4) { + return this.setFromMatrix4(matrix4).invert().transpose(); + } + transposeIntoArray(r) { + const m = this.elements; + r[0] = m[0]; + r[1] = m[3]; + r[2] = m[6]; + r[3] = m[1]; + r[4] = m[4]; + r[5] = m[7]; + r[6] = m[2]; + r[7] = m[5]; + r[8] = m[8]; + return this; + } + setUvTransform(tx, ty, sx, sy, rotation2, cx, cy) { + const c = Math.cos(rotation2); + const s = Math.sin(rotation2); + this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1); + return this; + } + scale(sx, sy) { + this.premultiply(_m32.makeScale(sx, sy)); + return this; + } + rotate(theta) { + this.premultiply(_m32.makeRotation(-theta)); + return this; + } + translate(tx, ty) { + this.premultiply(_m32.makeTranslation(tx, ty)); + return this; + } + makeTranslation(x, y) { + if (x.isVector2) { + this.set(1, 0, x.x, 0, 1, x.y, 0, 0, 1); + } else { + this.set(1, 0, x, 0, 1, y, 0, 0, 1); + } + return this; + } + makeRotation(theta) { + const c = Math.cos(theta); + const s = Math.sin(theta); + this.set(c, -s, 0, s, c, 0, 0, 0, 1); + return this; + } + makeScale(x, y) { + this.set(x, 0, 0, 0, y, 0, 0, 0, 1); + return this; + } + equals(matrix) { + const te = this.elements; + const me = matrix.elements; + for (let i = 0;i < 9; i++) { + if (te[i] !== me[i]) + return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 9; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te = this.elements; + array[offset] = te[0]; + array[offset + 1] = te[1]; + array[offset + 2] = te[2]; + array[offset + 3] = te[3]; + array[offset + 4] = te[4]; + array[offset + 5] = te[5]; + array[offset + 6] = te[6]; + array[offset + 7] = te[7]; + array[offset + 8] = te[8]; + return array; + } + clone() { + return new this.constructor().fromArray(this.elements); + } + } + var _m32 = /* @__PURE__ */ new Matrix32; + function arrayNeedsUint322(array) { + for (let i = array.length - 1;i >= 0; --i) { + if (array[i] >= 65535) + return true; + } + return false; + } + var TYPED_ARRAYS2 = { + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array + }; + function getTypedArray2(type, buffer) { + return new TYPED_ARRAYS2[type](buffer); + } + function createElementNS2(name2) { + return document.createElementNS("http://www.w3.org/1999/xhtml", name2); + } + function createCanvasElement2() { + const canvas = createElementNS2("canvas"); + canvas.style.display = "block"; + return canvas; + } + var _cache2 = {}; + function warnOnce2(message) { + if (message in _cache2) + return; + _cache2[message] = true; + console.warn(message); + } + function probeAsync2(gl, sync, interval) { + return new Promise(function(resolve, reject2) { + function probe() { + switch (gl.clientWaitSync(sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0)) { + case gl.WAIT_FAILED: + reject2(); + break; + case gl.TIMEOUT_EXPIRED: + setTimeout(probe, interval); + break; + default: + resolve(); + } + } + setTimeout(probe, interval); + }); + } + function toNormalizedProjectionMatrix2(projectionMatrix) { + const m = projectionMatrix.elements; + m[2] = 0.5 * m[2] + 0.5 * m[3]; + m[6] = 0.5 * m[6] + 0.5 * m[7]; + m[10] = 0.5 * m[10] + 0.5 * m[11]; + m[14] = 0.5 * m[14] + 0.5 * m[15]; + } + function toReversedProjectionMatrix2(projectionMatrix) { + const m = projectionMatrix.elements; + const isPerspectiveMatrix = m[11] === -1; + if (isPerspectiveMatrix) { + m[10] = -m[10] - 1; + m[14] = -m[14]; + } else { + m[10] = -m[10]; + m[14] = -m[14] + 1; + } + } + var LINEAR_REC709_TO_XYZ2 = /* @__PURE__ */ new Matrix32().set(0.4123908, 0.3575843, 0.1804808, 0.212639, 0.7151687, 0.0721923, 0.0193308, 0.1191948, 0.9505322); + var XYZ_TO_LINEAR_REC7092 = /* @__PURE__ */ new Matrix32().set(3.2409699, -1.5373832, -0.4986108, -0.9692436, 1.8759675, 0.0415551, 0.0556301, -0.203977, 1.0569715); + function createColorManagement2() { + const ColorManagement3 = { + enabled: true, + workingColorSpace: LinearSRGBColorSpace2, + spaces: {}, + convert: function(color, sourceColorSpace, targetColorSpace) { + if (this.enabled === false || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) { + return color; + } + if (this.spaces[sourceColorSpace].transfer === SRGBTransfer2) { + color.r = SRGBToLinear2(color.r); + color.g = SRGBToLinear2(color.g); + color.b = SRGBToLinear2(color.b); + } + if (this.spaces[sourceColorSpace].primaries !== this.spaces[targetColorSpace].primaries) { + color.applyMatrix3(this.spaces[sourceColorSpace].toXYZ); + color.applyMatrix3(this.spaces[targetColorSpace].fromXYZ); + } + if (this.spaces[targetColorSpace].transfer === SRGBTransfer2) { + color.r = LinearToSRGB2(color.r); + color.g = LinearToSRGB2(color.g); + color.b = LinearToSRGB2(color.b); + } + return color; + }, + fromWorkingColorSpace: function(color, targetColorSpace) { + return this.convert(color, this.workingColorSpace, targetColorSpace); + }, + toWorkingColorSpace: function(color, sourceColorSpace) { + return this.convert(color, sourceColorSpace, this.workingColorSpace); + }, + getPrimaries: function(colorSpace) { + return this.spaces[colorSpace].primaries; + }, + getTransfer: function(colorSpace) { + if (colorSpace === NoColorSpace2) + return LinearTransfer2; + return this.spaces[colorSpace].transfer; + }, + getLuminanceCoefficients: function(target, colorSpace = this.workingColorSpace) { + return target.fromArray(this.spaces[colorSpace].luminanceCoefficients); + }, + define: function(colorSpaces) { + Object.assign(this.spaces, colorSpaces); + }, + _getMatrix: function(targetMatrix, sourceColorSpace, targetColorSpace) { + return targetMatrix.copy(this.spaces[sourceColorSpace].toXYZ).multiply(this.spaces[targetColorSpace].fromXYZ); + }, + _getDrawingBufferColorSpace: function(colorSpace) { + return this.spaces[colorSpace].outputColorSpaceConfig.drawingBufferColorSpace; + }, + _getUnpackColorSpace: function(colorSpace = this.workingColorSpace) { + return this.spaces[colorSpace].workingColorSpaceConfig.unpackColorSpace; + } + }; + const REC709_PRIMARIES = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06]; + const REC709_LUMINANCE_COEFFICIENTS = [0.2126, 0.7152, 0.0722]; + const D65 = [0.3127, 0.329]; + ColorManagement3.define({ + [LinearSRGBColorSpace2]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: LinearTransfer2, + toXYZ: LINEAR_REC709_TO_XYZ2, + fromXYZ: XYZ_TO_LINEAR_REC7092, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace2 }, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace2 } + }, + [SRGBColorSpace2]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: SRGBTransfer2, + toXYZ: LINEAR_REC709_TO_XYZ2, + fromXYZ: XYZ_TO_LINEAR_REC7092, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace2 } + } + }); + return ColorManagement3; + } + var ColorManagement2 = /* @__PURE__ */ createColorManagement2(); + function SRGBToLinear2(c) { + return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); + } + function LinearToSRGB2(c) { + return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055; + } + var _canvas2; + + class ImageUtils2 { + static getDataURL(image) { + if (/^data:/i.test(image.src)) { + return image.src; + } + if (typeof HTMLCanvasElement === "undefined") { + return image.src; + } + let canvas; + if (image instanceof HTMLCanvasElement) { + canvas = image; + } else { + if (_canvas2 === undefined) + _canvas2 = createElementNS2("canvas"); + _canvas2.width = image.width; + _canvas2.height = image.height; + const context = _canvas2.getContext("2d"); + if (image instanceof ImageData) { + context.putImageData(image, 0, 0); + } else { + context.drawImage(image, 0, 0, image.width, image.height); + } + canvas = _canvas2; + } + return canvas.toDataURL("image/png"); + } + static sRGBToLinear(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + const canvas = createElementNS2("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, image.width, image.height); + const imageData = context.getImageData(0, 0, image.width, image.height); + const data2 = imageData.data; + for (let i = 0;i < data2.length; i++) { + data2[i] = SRGBToLinear2(data2[i] / 255) * 255; + } + context.putImageData(imageData, 0, 0); + return canvas; + } else if (image.data) { + const data2 = image.data.slice(0); + for (let i = 0;i < data2.length; i++) { + if (data2 instanceof Uint8Array || data2 instanceof Uint8ClampedArray) { + data2[i] = Math.floor(SRGBToLinear2(data2[i] / 255) * 255); + } else { + data2[i] = SRGBToLinear2(data2[i]); + } + } + return { + data: data2, + width: image.width, + height: image.height + }; + } else { + console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."); + return image; + } + } + } + var _sourceId2 = 0; + + class Source2 { + constructor(data2 = null) { + this.isSource = true; + Object.defineProperty(this, "id", { value: _sourceId2++ }); + this.uuid = generateUUID2(); + this.data = data2; + this.dataReady = true; + this.version = 0; + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + if (!isRootObject && meta.images[this.uuid] !== undefined) { + return meta.images[this.uuid]; + } + const output = { + uuid: this.uuid, + url: "" + }; + const data2 = this.data; + if (data2 !== null) { + let url; + if (Array.isArray(data2)) { + url = []; + for (let i = 0, l = data2.length;i < l; i++) { + if (data2[i].isDataTexture) { + url.push(serializeImage2(data2[i].image)); + } else { + url.push(serializeImage2(data2[i])); + } + } + } else { + url = serializeImage2(data2); + } + output.url = url; + } + if (!isRootObject) { + meta.images[this.uuid] = output; + } + return output; + } + } + function serializeImage2(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + return ImageUtils2.getDataURL(image); + } else { + if (image.data) { + return { + data: Array.from(image.data), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; + } else { + console.warn("THREE.Texture: Unable to serialize Texture."); + return {}; + } + } + } + var _textureId2 = 0; + + class Texture2 extends EventDispatcher2 { + constructor(image = Texture2.DEFAULT_IMAGE, mapping = Texture2.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping2, wrapT = ClampToEdgeWrapping2, magFilter = LinearFilter2, minFilter = LinearMipmapLinearFilter2, format = RGBAFormat2, type = UnsignedByteType2, anisotropy = Texture2.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace2) { + super(); + this.isTexture = true; + Object.defineProperty(this, "id", { value: _textureId2++ }); + this.uuid = generateUUID2(); + this.name = ""; + this.source = new Source2(image); + this.mipmaps = []; + this.mapping = mapping; + this.channel = 0; + this.wrapS = wrapS; + this.wrapT = wrapT; + this.magFilter = magFilter; + this.minFilter = minFilter; + this.anisotropy = anisotropy; + this.format = format; + this.internalFormat = null; + this.type = type; + this.offset = new Vector22(0, 0); + this.repeat = new Vector22(1, 1); + this.center = new Vector22(0, 0); + this.rotation = 0; + this.matrixAutoUpdate = true; + this.matrix = new Matrix32; + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; + this.colorSpace = colorSpace; + this.userData = {}; + this.version = 0; + this.onUpdate = null; + this.renderTarget = null; + this.isRenderTargetTexture = false; + this.pmremVersion = 0; + } + get image() { + return this.source.data; + } + set image(value2 = null) { + this.source.data = value2; + } + updateMatrix() { + this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.source = source.source; + this.mipmaps = source.mipmaps.slice(0); + this.mapping = source.mapping; + this.channel = source.channel; + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + this.anisotropy = source.anisotropy; + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + this.offset.copy(source.offset); + this.repeat.copy(source.repeat); + this.center.copy(source.center); + this.rotation = source.rotation; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy(source.matrix); + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.colorSpace = source.colorSpace; + this.renderTarget = source.renderTarget; + this.isRenderTargetTexture = source.isRenderTargetTexture; + this.userData = JSON.parse(JSON.stringify(source.userData)); + this.needsUpdate = true; + return this; + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + if (!isRootObject && meta.textures[this.uuid] !== undefined) { + return meta.textures[this.uuid]; + } + const output = { + metadata: { + version: 4.6, + type: "Texture", + generator: "Texture.toJSON" + }, + uuid: this.uuid, + name: this.name, + image: this.source.toJSON(meta).uuid, + mapping: this.mapping, + channel: this.channel, + repeat: [this.repeat.x, this.repeat.y], + offset: [this.offset.x, this.offset.y], + center: [this.center.x, this.center.y], + rotation: this.rotation, + wrap: [this.wrapS, this.wrapT], + format: this.format, + internalFormat: this.internalFormat, + type: this.type, + colorSpace: this.colorSpace, + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + flipY: this.flipY, + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + }; + if (Object.keys(this.userData).length > 0) + output.userData = this.userData; + if (!isRootObject) { + meta.textures[this.uuid] = output; + } + return output; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + transformUv(uv) { + if (this.mapping !== UVMapping2) + return uv; + uv.applyMatrix3(this.matrix); + if (uv.x < 0 || uv.x > 1) { + switch (this.wrapS) { + case RepeatWrapping2: + uv.x = uv.x - Math.floor(uv.x); + break; + case ClampToEdgeWrapping2: + uv.x = uv.x < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping2: + if (Math.abs(Math.floor(uv.x) % 2) === 1) { + uv.x = Math.ceil(uv.x) - uv.x; + } else { + uv.x = uv.x - Math.floor(uv.x); + } + break; + } + } + if (uv.y < 0 || uv.y > 1) { + switch (this.wrapT) { + case RepeatWrapping2: + uv.y = uv.y - Math.floor(uv.y); + break; + case ClampToEdgeWrapping2: + uv.y = uv.y < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping2: + if (Math.abs(Math.floor(uv.y) % 2) === 1) { + uv.y = Math.ceil(uv.y) - uv.y; + } else { + uv.y = uv.y - Math.floor(uv.y); + } + break; + } + } + if (this.flipY) { + uv.y = 1 - uv.y; + } + return uv; + } + set needsUpdate(value2) { + if (value2 === true) { + this.version++; + this.source.needsUpdate = true; + } + } + set needsPMREMUpdate(value2) { + if (value2 === true) { + this.pmremVersion++; + } + } + } + Texture2.DEFAULT_IMAGE = null; + Texture2.DEFAULT_MAPPING = UVMapping2; + Texture2.DEFAULT_ANISOTROPY = 1; + + class Vector42 { + constructor(x = 0, y = 0, z = 0, w = 1) { + Vector42.prototype.isVector4 = true; + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + get width() { + return this.z; + } + set width(value2) { + this.z = value2; + } + get height() { + return this.w; + } + set height(value2) { + this.w = value2; + } + set(x, y, z, w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setZ(z) { + this.z = z; + return this; + } + setW(w) { + this.w = w; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + case 2: + this.z = value2; + break; + case 3: + this.w = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + case 3: + return this.w; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z, this.w); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = v.w !== undefined ? v.w : 1; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + this.w += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + return this; + } + applyMatrix4(m) { + const x = this.x, y = this.y, z = this.z, w = this.w; + const e = m.elements; + this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w; + this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w; + this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w; + this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + this.w /= v.w; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + setAxisAngleFromQuaternion(q) { + this.w = 2 * Math.acos(q.w); + const s = Math.sqrt(1 - q.w * q.w); + if (s < 0.0001) { + this.x = 1; + this.y = 0; + this.z = 0; + } else { + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; + } + return this; + } + setAxisAngleFromRotationMatrix(m) { + let angle, x, y, z; + const epsilon = 0.01, epsilon2 = 0.1, te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10]; + if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) { + if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) { + this.set(1, 0, 0, 0); + return this; + } + angle = Math.PI; + const xx = (m11 + 1) / 2; + const yy = (m22 + 1) / 2; + const zz = (m33 + 1) / 2; + const xy = (m12 + m21) / 4; + const xz = (m13 + m31) / 4; + const yz = (m23 + m32) / 4; + if (xx > yy && xx > zz) { + if (xx < epsilon) { + x = 0; + y = 0.707106781; + z = 0.707106781; + } else { + x = Math.sqrt(xx); + y = xy / x; + z = xz / x; + } + } else if (yy > zz) { + if (yy < epsilon) { + x = 0.707106781; + y = 0; + z = 0.707106781; + } else { + y = Math.sqrt(yy); + x = xy / y; + z = yz / y; + } + } else { + if (zz < epsilon) { + x = 0.707106781; + y = 0.707106781; + z = 0; + } else { + z = Math.sqrt(zz); + x = xz / z; + y = yz / z; + } + } + this.set(x, y, z, angle); + return this; + } + let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); + if (Math.abs(s) < 0.001) + s = 1; + this.x = (m32 - m23) / s; + this.y = (m13 - m31) / s; + this.z = (m21 - m12) / s; + this.w = Math.acos((m11 + m22 + m33 - 1) / 2); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + this.w = e[15]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + this.w = Math.min(this.w, v.w); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + this.w = Math.max(this.w, v.w); + return this; + } + clamp(min, max) { + this.x = clamp3(this.x, min.x, max.x); + this.y = clamp3(this.y, min.y, max.y); + this.z = clamp3(this.z, min.z, max.z); + this.w = clamp3(this.w, min.w, max.w); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp3(this.x, minVal, maxVal); + this.y = clamp3(this.y, minVal, maxVal); + this.z = clamp3(this.z, minVal, maxVal); + this.w = clamp3(this.w, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp3(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + this.w = Math.floor(this.w); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + this.w = Math.ceil(this.w); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + this.w = Math.round(this.w); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + this.w = Math.trunc(this.w); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + this.w += (v.w - this.w) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + this.w = v1.w + (v2.w - v1.w) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + this.w = array[offset + 3]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + array[offset + 3] = this.w; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + this.z = attribute.getZ(index2); + this.w = attribute.getW(index2); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + yield this.w; + } + } + + class RenderTarget2 extends EventDispatcher2 { + constructor(width2 = 1, height2 = 1, options = {}) { + super(); + this.isRenderTarget = true; + this.width = width2; + this.height = height2; + this.depth = 1; + this.scissor = new Vector42(0, 0, width2, height2); + this.scissorTest = false; + this.viewport = new Vector42(0, 0, width2, height2); + const image = { width: width2, height: height2, depth: 1 }; + options = Object.assign({ + generateMipmaps: false, + internalFormat: null, + minFilter: LinearFilter2, + depthBuffer: true, + stencilBuffer: false, + resolveDepthBuffer: true, + resolveStencilBuffer: true, + depthTexture: null, + samples: 0, + count: 1 + }, options); + const texture = new Texture2(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + texture.flipY = false; + texture.generateMipmaps = options.generateMipmaps; + texture.internalFormat = options.internalFormat; + this.textures = []; + const count = options.count; + for (let i = 0;i < count; i++) { + this.textures[i] = texture.clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + } + this.depthBuffer = options.depthBuffer; + this.stencilBuffer = options.stencilBuffer; + this.resolveDepthBuffer = options.resolveDepthBuffer; + this.resolveStencilBuffer = options.resolveStencilBuffer; + this._depthTexture = null; + this.depthTexture = options.depthTexture; + this.samples = options.samples; + } + get texture() { + return this.textures[0]; + } + set texture(value2) { + this.textures[0] = value2; + } + set depthTexture(current) { + if (this._depthTexture !== null) + this._depthTexture.renderTarget = null; + if (current !== null) + current.renderTarget = this; + this._depthTexture = current; + } + get depthTexture() { + return this._depthTexture; + } + setSize(width2, height2, depth = 1) { + if (this.width !== width2 || this.height !== height2 || this.depth !== depth) { + this.width = width2; + this.height = height2; + this.depth = depth; + for (let i = 0, il = this.textures.length;i < il; i++) { + this.textures[i].image.width = width2; + this.textures[i].image.height = height2; + this.textures[i].image.depth = depth; + } + this.dispose(); + } + this.viewport.set(0, 0, width2, height2); + this.scissor.set(0, 0, width2, height2); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + this.scissor.copy(source.scissor); + this.scissorTest = source.scissorTest; + this.viewport.copy(source.viewport); + this.textures.length = 0; + for (let i = 0, il = source.textures.length;i < il; i++) { + this.textures[i] = source.textures[i].clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + } + const image = Object.assign({}, source.texture.image); + this.texture.source = new Source2(image); + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.resolveDepthBuffer = source.resolveDepthBuffer; + this.resolveStencilBuffer = source.resolveStencilBuffer; + if (source.depthTexture !== null) + this.depthTexture = source.depthTexture.clone(); + this.samples = source.samples; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + } + + class WebGLRenderTarget2 extends RenderTarget2 { + constructor(width2 = 1, height2 = 1, options = {}) { + super(width2, height2, options); + this.isWebGLRenderTarget = true; + } + } + + class DataArrayTexture2 extends Texture2 { + constructor(data2 = null, width2 = 1, height2 = 1, depth = 1) { + super(null); + this.isDataArrayTexture = true; + this.image = { data: data2, width: width2, height: height2, depth }; + this.magFilter = NearestFilter2; + this.minFilter = NearestFilter2; + this.wrapR = ClampToEdgeWrapping2; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + this.layerUpdates = new Set; + } + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + clearLayerUpdates() { + this.layerUpdates.clear(); + } + } + + class WebGLArrayRenderTarget2 extends WebGLRenderTarget2 { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isWebGLArrayRenderTarget = true; + this.depth = depth; + this.texture = new DataArrayTexture2(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } + } + + class Data3DTexture2 extends Texture2 { + constructor(data2 = null, width2 = 1, height2 = 1, depth = 1) { + super(null); + this.isData3DTexture = true; + this.image = { data: data2, width: width2, height: height2, depth }; + this.magFilter = NearestFilter2; + this.minFilter = NearestFilter2; + this.wrapR = ClampToEdgeWrapping2; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } + } + + class WebGL3DRenderTarget2 extends WebGLRenderTarget2 { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isWebGL3DRenderTarget = true; + this.depth = depth; + this.texture = new Data3DTexture2(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } + } + + class Quaternion2 { + constructor(x = 0, y = 0, z = 0, w = 1) { + this.isQuaternion = true; + this._x = x; + this._y = y; + this._z = z; + this._w = w; + } + static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) { + let x0 = src0[srcOffset0 + 0], y0 = src0[srcOffset0 + 1], z0 = src0[srcOffset0 + 2], w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1 + 0], y1 = src1[srcOffset1 + 1], z1 = src1[srcOffset1 + 2], w1 = src1[srcOffset1 + 3]; + if (t === 0) { + dst[dstOffset + 0] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + return; + } + if (t === 1) { + dst[dstOffset + 0] = x1; + dst[dstOffset + 1] = y1; + dst[dstOffset + 2] = z1; + dst[dstOffset + 3] = w1; + return; + } + if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) { + let s = 1 - t; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, dir = cos >= 0 ? 1 : -1, sqrSin = 1 - cos * cos; + if (sqrSin > Number.EPSILON) { + const sin = Math.sqrt(sqrSin), len = Math.atan2(sin, cos * dir); + s = Math.sin(s * len) / sin; + t = Math.sin(t * len) / sin; + } + const tDir = t * dir; + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; + if (s === 1 - t) { + const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0); + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; + } + } + dst[dstOffset] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + } + static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) { + const x0 = src0[srcOffset0]; + const y0 = src0[srcOffset0 + 1]; + const z0 = src0[srcOffset0 + 2]; + const w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1]; + const y1 = src1[srcOffset1 + 1]; + const z1 = src1[srcOffset1 + 2]; + const w1 = src1[srcOffset1 + 3]; + dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + return dst; + } + get x() { + return this._x; + } + set x(value2) { + this._x = value2; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value2) { + this._y = value2; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value2) { + this._z = value2; + this._onChangeCallback(); + } + get w() { + return this._w; + } + set w(value2) { + this._w = value2; + this._onChangeCallback(); + } + set(x, y, z, w) { + this._x = x; + this._y = y; + this._z = z; + this._w = w; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._w); + } + copy(quaternion) { + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + this._onChangeCallback(); + return this; + } + setFromEuler(euler, update = true) { + const { _x: x, _y: y, _z: z, _order: order } = euler; + const cos = Math.cos; + const sin = Math.sin; + const c1 = cos(x / 2); + const c2 = cos(y / 2); + const c3 = cos(z / 2); + const s1 = sin(x / 2); + const s2 = sin(y / 2); + const s3 = sin(z / 2); + switch (order) { + case "XYZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "YXZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "ZXY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "ZYX": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "YZX": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "XZY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + default: + console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + order); + } + if (update === true) + this._onChangeCallback(); + return this; + } + setFromAxisAngle(axis, angle) { + const halfAngle = angle / 2, s = Math.sin(halfAngle); + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos(halfAngle); + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m) { + const te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10], trace = m11 + m22 + m33; + if (trace > 0) { + const s = 0.5 / Math.sqrt(trace + 1); + this._w = 0.25 / s; + this._x = (m32 - m23) * s; + this._y = (m13 - m31) * s; + this._z = (m21 - m12) * s; + } else if (m11 > m22 && m11 > m33) { + const s = 2 * Math.sqrt(1 + m11 - m22 - m33); + this._w = (m32 - m23) / s; + this._x = 0.25 * s; + this._y = (m12 + m21) / s; + this._z = (m13 + m31) / s; + } else if (m22 > m33) { + const s = 2 * Math.sqrt(1 + m22 - m11 - m33); + this._w = (m13 - m31) / s; + this._x = (m12 + m21) / s; + this._y = 0.25 * s; + this._z = (m23 + m32) / s; + } else { + const s = 2 * Math.sqrt(1 + m33 - m11 - m22); + this._w = (m21 - m12) / s; + this._x = (m13 + m31) / s; + this._y = (m23 + m32) / s; + this._z = 0.25 * s; + } + this._onChangeCallback(); + return this; + } + setFromUnitVectors(vFrom, vTo) { + let r = vFrom.dot(vTo) + 1; + if (r < Number.EPSILON) { + r = 0; + if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) { + this._x = -vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + } else { + this._x = 0; + this._y = -vFrom.z; + this._z = vFrom.y; + this._w = r; + } + } else { + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + } + return this.normalize(); + } + angleTo(q) { + return 2 * Math.acos(Math.abs(clamp3(this.dot(q), -1, 1))); + } + rotateTowards(q, step) { + const angle = this.angleTo(q); + if (angle === 0) + return this; + const t = Math.min(1, step / angle); + this.slerp(q, t); + return this; + } + identity() { + return this.set(0, 0, 0, 1); + } + invert() { + return this.conjugate(); + } + conjugate() { + this._x *= -1; + this._y *= -1; + this._z *= -1; + this._onChangeCallback(); + return this; + } + dot(v) { + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + } + lengthSq() { + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + } + length() { + return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); + } + normalize() { + let l = this.length(); + if (l === 0) { + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + } else { + l = 1 / l; + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; + } + this._onChangeCallback(); + return this; + } + multiply(q) { + return this.multiplyQuaternions(this, q); + } + premultiply(q) { + return this.multiplyQuaternions(q, this); + } + multiplyQuaternions(a, b) { + const { _x: qax, _y: qay, _z: qaz, _w: qaw } = a; + const { _x: qbx, _y: qby, _z: qbz, _w: qbw } = b; + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + this._onChangeCallback(); + return this; + } + slerp(qb, t) { + if (t === 0) + return this; + if (t === 1) + return this.copy(qb); + const x = this._x, y = this._y, z = this._z, w = this._w; + let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + if (cosHalfTheta < 0) { + this._w = -qb._w; + this._x = -qb._x; + this._y = -qb._y; + this._z = -qb._z; + cosHalfTheta = -cosHalfTheta; + } else { + this.copy(qb); + } + if (cosHalfTheta >= 1) { + this._w = w; + this._x = x; + this._y = y; + this._z = z; + return this; + } + const sqrSinHalfTheta = 1 - cosHalfTheta * cosHalfTheta; + if (sqrSinHalfTheta <= Number.EPSILON) { + const s = 1 - t; + this._w = s * w + t * this._w; + this._x = s * x + t * this._x; + this._y = s * y + t * this._y; + this._z = s * z + t * this._z; + this.normalize(); + return this; + } + const sinHalfTheta = Math.sqrt(sqrSinHalfTheta); + const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta); + const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta, ratioB = Math.sin(t * halfTheta) / sinHalfTheta; + this._w = w * ratioA + this._w * ratioB; + this._x = x * ratioA + this._x * ratioB; + this._y = y * ratioA + this._y * ratioB; + this._z = z * ratioA + this._z * ratioB; + this._onChangeCallback(); + return this; + } + slerpQuaternions(qa, qb, t) { + return this.copy(qa).slerp(qb, t); + } + random() { + const theta1 = 2 * Math.PI * Math.random(); + const theta2 = 2 * Math.PI * Math.random(); + const x0 = Math.random(); + const r1 = Math.sqrt(1 - x0); + const r2 = Math.sqrt(x0); + return this.set(r1 * Math.sin(theta1), r1 * Math.cos(theta1), r2 * Math.sin(theta2), r2 * Math.cos(theta2)); + } + equals(quaternion) { + return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w; + } + fromArray(array, offset = 0) { + this._x = array[offset]; + this._y = array[offset + 1]; + this._z = array[offset + 2]; + this._w = array[offset + 3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._w; + return array; + } + fromBufferAttribute(attribute, index2) { + this._x = attribute.getX(index2); + this._y = attribute.getY(index2); + this._z = attribute.getZ(index2); + this._w = attribute.getW(index2); + this._onChangeCallback(); + return this; + } + toJSON() { + return this.toArray(); + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._w; + } + } + + class Vector32 { + constructor(x = 0, y = 0, z = 0) { + Vector32.prototype.isVector3 = true; + this.x = x; + this.y = y; + this.z = z; + } + set(x, y, z) { + if (z === undefined) + z = this.z; + this.x = x; + this.y = y; + this.z = z; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setZ(z) { + this.z = z; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + case 2: + this.z = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + return this; + } + multiplyVectors(a, b) { + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; + return this; + } + applyEuler(euler) { + return this.applyQuaternion(_quaternion$42.setFromEuler(euler)); + } + applyAxisAngle(axis, angle) { + return this.applyQuaternion(_quaternion$42.setFromAxisAngle(axis, angle)); + } + applyMatrix3(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + this.x = e[0] * x + e[3] * y + e[6] * z; + this.y = e[1] * x + e[4] * y + e[7] * z; + this.z = e[2] * x + e[5] * y + e[8] * z; + return this; + } + applyNormalMatrix(m) { + return this.applyMatrix3(m).normalize(); + } + applyMatrix4(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]); + this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w; + this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w; + this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w; + return this; + } + applyQuaternion(q) { + const vx = this.x, vy = this.y, vz = this.z; + const { x: qx, y: qy, z: qz, w: qw } = q; + const tx = 2 * (qy * vz - qz * vy); + const ty = 2 * (qz * vx - qx * vz); + const tz = 2 * (qx * vy - qy * vx); + this.x = vx + qw * tx + qy * tz - qz * ty; + this.y = vy + qw * ty + qz * tx - qx * tz; + this.z = vz + qw * tz + qx * ty - qy * tx; + return this; + } + project(camera) { + return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix); + } + unproject(camera) { + return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld); + } + transformDirection(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + this.x = e[0] * x + e[4] * y + e[8] * z; + this.y = e[1] * x + e[5] * y + e[9] * z; + this.z = e[2] * x + e[6] * y + e[10] * z; + return this.normalize(); + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + return this; + } + clamp(min, max) { + this.x = clamp3(this.x, min.x, max.x); + this.y = clamp3(this.y, min.y, max.y); + this.z = clamp3(this.z, min.z, max.z); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp3(this.x, minVal, maxVal); + this.y = clamp3(this.y, minVal, maxVal); + this.z = clamp3(this.z, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp3(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + return this; + } + cross(v) { + return this.crossVectors(this, v); + } + crossVectors(a, b) { + const { x: ax, y: ay, z: az } = a; + const { x: bx, y: by, z: bz } = b; + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + return this; + } + projectOnVector(v) { + const denominator = v.lengthSq(); + if (denominator === 0) + return this.set(0, 0, 0); + const scalar = v.dot(this) / denominator; + return this.copy(v).multiplyScalar(scalar); + } + projectOnPlane(planeNormal) { + _vector$c2.copy(this).projectOnVector(planeNormal); + return this.sub(_vector$c2); + } + reflect(normal) { + return this.sub(_vector$c2.copy(normal).multiplyScalar(2 * this.dot(normal))); + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) + return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp3(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + return dx * dx + dy * dy + dz * dz; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z); + } + setFromSpherical(s) { + return this.setFromSphericalCoords(s.radius, s.phi, s.theta); + } + setFromSphericalCoords(radius, phi, theta) { + const sinPhiRadius = Math.sin(phi) * radius; + this.x = sinPhiRadius * Math.sin(theta); + this.y = Math.cos(phi) * radius; + this.z = sinPhiRadius * Math.cos(theta); + return this; + } + setFromCylindrical(c) { + return this.setFromCylindricalCoords(c.radius, c.theta, c.y); + } + setFromCylindricalCoords(radius, theta, y) { + this.x = radius * Math.sin(theta); + this.y = y; + this.z = radius * Math.cos(theta); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + return this; + } + setFromMatrixScale(m) { + const sx = this.setFromMatrixColumn(m, 0).length(); + const sy = this.setFromMatrixColumn(m, 1).length(); + const sz = this.setFromMatrixColumn(m, 2).length(); + this.x = sx; + this.y = sy; + this.z = sz; + return this; + } + setFromMatrixColumn(m, index2) { + return this.fromArray(m.elements, index2 * 4); + } + setFromMatrix3Column(m, index2) { + return this.fromArray(m.elements, index2 * 3); + } + setFromEuler(e) { + this.x = e._x; + this.y = e._y; + this.z = e._z; + return this; + } + setFromColor(c) { + this.x = c.r; + this.y = c.g; + this.z = c.b; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + this.z = attribute.getZ(index2); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + return this; + } + randomDirection() { + const theta = Math.random() * Math.PI * 2; + const u = Math.random() * 2 - 1; + const c = Math.sqrt(1 - u * u); + this.x = c * Math.cos(theta); + this.y = u; + this.z = c * Math.sin(theta); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + } + } + var _vector$c2 = /* @__PURE__ */ new Vector32; + var _quaternion$42 = /* @__PURE__ */ new Quaternion2; + + class Box32 { + constructor(min = new Vector32(Infinity, Infinity, Infinity), max = new Vector32(-Infinity, -Infinity, -Infinity)) { + this.isBox3 = true; + this.min = min; + this.max = max; + } + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + setFromArray(array) { + this.makeEmpty(); + for (let i = 0, il = array.length;i < il; i += 3) { + this.expandByPoint(_vector$b2.fromArray(array, i)); + } + return this; + } + setFromBufferAttribute(attribute) { + this.makeEmpty(); + for (let i = 0, il = attribute.count;i < il; i++) { + this.expandByPoint(_vector$b2.fromBufferAttribute(attribute, i)); + } + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length;i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size) { + const halfSize = _vector$b2.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + setFromObject(object, precise = false) { + this.makeEmpty(); + return this.expandByObject(object, precise); + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = this.min.z = Infinity; + this.max.x = this.max.y = this.max.z = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + expandByObject(object, precise = false) { + object.updateWorldMatrix(false, false); + const geometry = object.geometry; + if (geometry !== undefined) { + const positionAttribute = geometry.getAttribute("position"); + if (precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true) { + for (let i = 0, l = positionAttribute.count;i < l; i++) { + if (object.isMesh === true) { + object.getVertexPosition(i, _vector$b2); + } else { + _vector$b2.fromBufferAttribute(positionAttribute, i); + } + _vector$b2.applyMatrix4(object.matrixWorld); + this.expandByPoint(_vector$b2); + } + } else { + if (object.boundingBox !== undefined) { + if (object.boundingBox === null) { + object.computeBoundingBox(); + } + _box$42.copy(object.boundingBox); + } else { + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + _box$42.copy(geometry.boundingBox); + } + _box$42.applyMatrix4(object.matrixWorld); + this.union(_box$42); + } + } + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + this.expandByObject(children[i], precise); + } + return this; + } + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y && point.z >= this.min.z && point.z <= this.max.z; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z; + } + getParameter(point, target) { + return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z)); + } + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y && box.max.z >= this.min.z && box.min.z <= this.max.z; + } + intersectsSphere(sphere) { + this.clampPoint(sphere.center, _vector$b2); + return _vector$b2.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; + } + intersectsPlane(plane) { + let min, max; + if (plane.normal.x > 0) { + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + } else { + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + } + if (plane.normal.y > 0) { + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + } else { + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + } + if (plane.normal.z > 0) { + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + } else { + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + } + return min <= -plane.constant && max >= -plane.constant; + } + intersectsTriangle(triangle) { + if (this.isEmpty()) { + return false; + } + this.getCenter(_center2); + _extents2.subVectors(this.max, _center2); + _v0$3.subVectors(triangle.a, _center2); + _v1$72.subVectors(triangle.b, _center2); + _v2$42.subVectors(triangle.c, _center2); + _f02.subVectors(_v1$72, _v0$3); + _f12.subVectors(_v2$42, _v1$72); + _f22.subVectors(_v0$3, _v2$42); + let axes = [ + 0, + -_f02.z, + _f02.y, + 0, + -_f12.z, + _f12.y, + 0, + -_f22.z, + _f22.y, + _f02.z, + 0, + -_f02.x, + _f12.z, + 0, + -_f12.x, + _f22.z, + 0, + -_f22.x, + -_f02.y, + _f02.x, + 0, + -_f12.y, + _f12.x, + 0, + -_f22.y, + _f22.x, + 0 + ]; + if (!satForAxes2(axes, _v0$3, _v1$72, _v2$42, _extents2)) { + return false; + } + axes = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + if (!satForAxes2(axes, _v0$3, _v1$72, _v2$42, _extents2)) { + return false; + } + _triangleNormal2.crossVectors(_f02, _f12); + axes = [_triangleNormal2.x, _triangleNormal2.y, _triangleNormal2.z]; + return satForAxes2(axes, _v0$3, _v1$72, _v2$42, _extents2); + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$b2).distanceTo(point); + } + getBoundingSphere(target) { + if (this.isEmpty()) { + target.makeEmpty(); + } else { + this.getCenter(target.center); + target.radius = this.getSize(_vector$b2).length() * 0.5; + } + return target; + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) + this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + applyMatrix4(matrix) { + if (this.isEmpty()) + return this; + _points2[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points2[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points2[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points2[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); + _points2[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points2[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points2[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points2[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); + this.setFromPoints(_points2); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } + } + var _points2 = [ + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32 + ]; + var _vector$b2 = /* @__PURE__ */ new Vector32; + var _box$42 = /* @__PURE__ */ new Box32; + var _v0$3 = /* @__PURE__ */ new Vector32; + var _v1$72 = /* @__PURE__ */ new Vector32; + var _v2$42 = /* @__PURE__ */ new Vector32; + var _f02 = /* @__PURE__ */ new Vector32; + var _f12 = /* @__PURE__ */ new Vector32; + var _f22 = /* @__PURE__ */ new Vector32; + var _center2 = /* @__PURE__ */ new Vector32; + var _extents2 = /* @__PURE__ */ new Vector32; + var _triangleNormal2 = /* @__PURE__ */ new Vector32; + var _testAxis2 = /* @__PURE__ */ new Vector32; + function satForAxes2(axes, v0, v1, v2, extents) { + for (let i = 0, j = axes.length - 3;i <= j; i += 3) { + _testAxis2.fromArray(axes, i); + const r = extents.x * Math.abs(_testAxis2.x) + extents.y * Math.abs(_testAxis2.y) + extents.z * Math.abs(_testAxis2.z); + const p0 = v0.dot(_testAxis2); + const p1 = v1.dot(_testAxis2); + const p2 = v2.dot(_testAxis2); + if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) { + return false; + } + } + return true; + } + var _box$32 = /* @__PURE__ */ new Box32; + var _v1$62 = /* @__PURE__ */ new Vector32; + var _v2$32 = /* @__PURE__ */ new Vector32; + + class Sphere2 { + constructor(center = new Vector32, radius = -1) { + this.isSphere = true; + this.center = center; + this.radius = radius; + } + set(center, radius) { + this.center.copy(center); + this.radius = radius; + return this; + } + setFromPoints(points, optionalCenter) { + const center = this.center; + if (optionalCenter !== undefined) { + center.copy(optionalCenter); + } else { + _box$32.setFromPoints(points).getCenter(center); + } + let maxRadiusSq = 0; + for (let i = 0, il = points.length;i < il; i++) { + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i])); + } + this.radius = Math.sqrt(maxRadiusSq); + return this; + } + copy(sphere) { + this.center.copy(sphere.center); + this.radius = sphere.radius; + return this; + } + isEmpty() { + return this.radius < 0; + } + makeEmpty() { + this.center.set(0, 0, 0); + this.radius = -1; + return this; + } + containsPoint(point) { + return point.distanceToSquared(this.center) <= this.radius * this.radius; + } + distanceToPoint(point) { + return point.distanceTo(this.center) - this.radius; + } + intersectsSphere(sphere) { + const radiusSum = this.radius + sphere.radius; + return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum; + } + intersectsBox(box) { + return box.intersectsSphere(this); + } + intersectsPlane(plane) { + return Math.abs(plane.distanceToPoint(this.center)) <= this.radius; + } + clampPoint(point, target) { + const deltaLengthSq = this.center.distanceToSquared(point); + target.copy(point); + if (deltaLengthSq > this.radius * this.radius) { + target.sub(this.center).normalize(); + target.multiplyScalar(this.radius).add(this.center); + } + return target; + } + getBoundingBox(target) { + if (this.isEmpty()) { + target.makeEmpty(); + return target; + } + target.set(this.center, this.center); + target.expandByScalar(this.radius); + return target; + } + applyMatrix4(matrix) { + this.center.applyMatrix4(matrix); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); + return this; + } + translate(offset) { + this.center.add(offset); + return this; + } + expandByPoint(point) { + if (this.isEmpty()) { + this.center.copy(point); + this.radius = 0; + return this; + } + _v1$62.subVectors(point, this.center); + const lengthSq = _v1$62.lengthSq(); + if (lengthSq > this.radius * this.radius) { + const length2 = Math.sqrt(lengthSq); + const delta = (length2 - this.radius) * 0.5; + this.center.addScaledVector(_v1$62, delta / length2); + this.radius += delta; + } + return this; + } + union(sphere) { + if (sphere.isEmpty()) { + return this; + } + if (this.isEmpty()) { + this.copy(sphere); + return this; + } + if (this.center.equals(sphere.center) === true) { + this.radius = Math.max(this.radius, sphere.radius); + } else { + _v2$32.subVectors(sphere.center, this.center).setLength(sphere.radius); + this.expandByPoint(_v1$62.copy(sphere.center).add(_v2$32)); + this.expandByPoint(_v1$62.copy(sphere.center).sub(_v2$32)); + } + return this; + } + equals(sphere) { + return sphere.center.equals(this.center) && sphere.radius === this.radius; + } + clone() { + return new this.constructor().copy(this); + } + } + var _vector$a2 = /* @__PURE__ */ new Vector32; + var _segCenter2 = /* @__PURE__ */ new Vector32; + var _segDir2 = /* @__PURE__ */ new Vector32; + var _diff2 = /* @__PURE__ */ new Vector32; + var _edge12 = /* @__PURE__ */ new Vector32; + var _edge22 = /* @__PURE__ */ new Vector32; + var _normal$12 = /* @__PURE__ */ new Vector32; + + class Ray2 { + constructor(origin = new Vector32, direction = new Vector32(0, 0, -1)) { + this.origin = origin; + this.direction = direction; + } + set(origin, direction) { + this.origin.copy(origin); + this.direction.copy(direction); + return this; + } + copy(ray) { + this.origin.copy(ray.origin); + this.direction.copy(ray.direction); + return this; + } + at(t, target) { + return target.copy(this.origin).addScaledVector(this.direction, t); + } + lookAt(v) { + this.direction.copy(v).sub(this.origin).normalize(); + return this; + } + recast(t) { + this.origin.copy(this.at(t, _vector$a2)); + return this; + } + closestPointToPoint(point, target) { + target.subVectors(point, this.origin); + const directionDistance = target.dot(this.direction); + if (directionDistance < 0) { + return target.copy(this.origin); + } + return target.copy(this.origin).addScaledVector(this.direction, directionDistance); + } + distanceToPoint(point) { + return Math.sqrt(this.distanceSqToPoint(point)); + } + distanceSqToPoint(point) { + const directionDistance = _vector$a2.subVectors(point, this.origin).dot(this.direction); + if (directionDistance < 0) { + return this.origin.distanceToSquared(point); + } + _vector$a2.copy(this.origin).addScaledVector(this.direction, directionDistance); + return _vector$a2.distanceToSquared(point); + } + distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) { + _segCenter2.copy(v0).add(v1).multiplyScalar(0.5); + _segDir2.copy(v1).sub(v0).normalize(); + _diff2.copy(this.origin).sub(_segCenter2); + const segExtent = v0.distanceTo(v1) * 0.5; + const a01 = -this.direction.dot(_segDir2); + const b0 = _diff2.dot(this.direction); + const b1 = -_diff2.dot(_segDir2); + const c = _diff2.lengthSq(); + const det = Math.abs(1 - a01 * a01); + let s0, s1, sqrDist, extDet; + if (det > 0) { + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + if (s0 >= 0) { + if (s1 >= -extDet) { + if (s1 <= extDet) { + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c; + } else { + s1 = segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } else { + s1 = -segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } else { + if (s1 <= -extDet) { + s0 = Math.max(0, -(-a01 * segExtent + b0)); + s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } else if (s1 <= extDet) { + s0 = 0; + s1 = Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = s1 * (s1 + 2 * b1) + c; + } else { + s0 = Math.max(0, -(a01 * segExtent + b0)); + s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } + } else { + s1 = a01 > 0 ? -segExtent : segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + if (optionalPointOnRay) { + optionalPointOnRay.copy(this.origin).addScaledVector(this.direction, s0); + } + if (optionalPointOnSegment) { + optionalPointOnSegment.copy(_segCenter2).addScaledVector(_segDir2, s1); + } + return sqrDist; + } + intersectSphere(sphere, target) { + _vector$a2.subVectors(sphere.center, this.origin); + const tca = _vector$a2.dot(this.direction); + const d2 = _vector$a2.dot(_vector$a2) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + if (d2 > radius2) + return null; + const thc = Math.sqrt(radius2 - d2); + const t0 = tca - thc; + const t1 = tca + thc; + if (t1 < 0) + return null; + if (t0 < 0) + return this.at(t1, target); + return this.at(t0, target); + } + intersectsSphere(sphere) { + return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius; + } + distanceToPlane(plane) { + const denominator = plane.normal.dot(this.direction); + if (denominator === 0) { + if (plane.distanceToPoint(this.origin) === 0) { + return 0; + } + return null; + } + const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; + return t >= 0 ? t : null; + } + intersectPlane(plane, target) { + const t = this.distanceToPlane(plane); + if (t === null) { + return null; + } + return this.at(t, target); + } + intersectsPlane(plane) { + const distToPoint = plane.distanceToPoint(this.origin); + if (distToPoint === 0) { + return true; + } + const denominator = plane.normal.dot(this.direction); + if (denominator * distToPoint < 0) { + return true; + } + return false; + } + intersectBox(box, target) { + let tmin, tmax, tymin, tymax, tzmin, tzmax; + const invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z; + const origin = this.origin; + if (invdirx >= 0) { + tmin = (box.min.x - origin.x) * invdirx; + tmax = (box.max.x - origin.x) * invdirx; + } else { + tmin = (box.max.x - origin.x) * invdirx; + tmax = (box.min.x - origin.x) * invdirx; + } + if (invdiry >= 0) { + tymin = (box.min.y - origin.y) * invdiry; + tymax = (box.max.y - origin.y) * invdiry; + } else { + tymin = (box.max.y - origin.y) * invdiry; + tymax = (box.min.y - origin.y) * invdiry; + } + if (tmin > tymax || tymin > tmax) + return null; + if (tymin > tmin || isNaN(tmin)) + tmin = tymin; + if (tymax < tmax || isNaN(tmax)) + tmax = tymax; + if (invdirz >= 0) { + tzmin = (box.min.z - origin.z) * invdirz; + tzmax = (box.max.z - origin.z) * invdirz; + } else { + tzmin = (box.max.z - origin.z) * invdirz; + tzmax = (box.min.z - origin.z) * invdirz; + } + if (tmin > tzmax || tzmin > tmax) + return null; + if (tzmin > tmin || tmin !== tmin) + tmin = tzmin; + if (tzmax < tmax || tmax !== tmax) + tmax = tzmax; + if (tmax < 0) + return null; + return this.at(tmin >= 0 ? tmin : tmax, target); + } + intersectsBox(box) { + return this.intersectBox(box, _vector$a2) !== null; + } + intersectTriangle(a, b, c, backfaceCulling, target) { + _edge12.subVectors(b, a); + _edge22.subVectors(c, a); + _normal$12.crossVectors(_edge12, _edge22); + let DdN = this.direction.dot(_normal$12); + let sign3; + if (DdN > 0) { + if (backfaceCulling) + return null; + sign3 = 1; + } else if (DdN < 0) { + sign3 = -1; + DdN = -DdN; + } else { + return null; + } + _diff2.subVectors(this.origin, a); + const DdQxE2 = sign3 * this.direction.dot(_edge22.crossVectors(_diff2, _edge22)); + if (DdQxE2 < 0) { + return null; + } + const DdE1xQ = sign3 * this.direction.dot(_edge12.cross(_diff2)); + if (DdE1xQ < 0) { + return null; + } + if (DdQxE2 + DdE1xQ > DdN) { + return null; + } + const QdN = -sign3 * _diff2.dot(_normal$12); + if (QdN < 0) { + return null; + } + return this.at(QdN / DdN, target); + } + applyMatrix4(matrix4) { + this.origin.applyMatrix4(matrix4); + this.direction.transformDirection(matrix4); + return this; + } + equals(ray) { + return ray.origin.equals(this.origin) && ray.direction.equals(this.direction); + } + clone() { + return new this.constructor().copy(this); + } + } + + class Matrix42 { + constructor(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + Matrix42.prototype.isMatrix4 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44); + } + } + set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + const te = this.elements; + te[0] = n11; + te[4] = n12; + te[8] = n13; + te[12] = n14; + te[1] = n21; + te[5] = n22; + te[9] = n23; + te[13] = n24; + te[2] = n31; + te[6] = n32; + te[10] = n33; + te[14] = n34; + te[3] = n41; + te[7] = n42; + te[11] = n43; + te[15] = n44; + return this; + } + identity() { + this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return this; + } + clone() { + return new Matrix42().fromArray(this.elements); + } + copy(m) { + const te = this.elements; + const me = m.elements; + te[0] = me[0]; + te[1] = me[1]; + te[2] = me[2]; + te[3] = me[3]; + te[4] = me[4]; + te[5] = me[5]; + te[6] = me[6]; + te[7] = me[7]; + te[8] = me[8]; + te[9] = me[9]; + te[10] = me[10]; + te[11] = me[11]; + te[12] = me[12]; + te[13] = me[13]; + te[14] = me[14]; + te[15] = me[15]; + return this; + } + copyPosition(m) { + const te = this.elements, me = m.elements; + te[12] = me[12]; + te[13] = me[13]; + te[14] = me[14]; + return this; + } + setFromMatrix3(m) { + const me = m.elements; + this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1); + return this; + } + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrixColumn(this, 0); + yAxis.setFromMatrixColumn(this, 1); + zAxis.setFromMatrixColumn(this, 2); + return this; + } + makeBasis(xAxis, yAxis, zAxis) { + this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1); + return this; + } + extractRotation(m) { + const te = this.elements; + const me = m.elements; + const scaleX = 1 / _v1$52.setFromMatrixColumn(m, 0).length(); + const scaleY = 1 / _v1$52.setFromMatrixColumn(m, 1).length(); + const scaleZ = 1 / _v1$52.setFromMatrixColumn(m, 2).length(); + te[0] = me[0] * scaleX; + te[1] = me[1] * scaleX; + te[2] = me[2] * scaleX; + te[3] = 0; + te[4] = me[4] * scaleY; + te[5] = me[5] * scaleY; + te[6] = me[6] * scaleY; + te[7] = 0; + te[8] = me[8] * scaleZ; + te[9] = me[9] * scaleZ; + te[10] = me[10] * scaleZ; + te[11] = 0; + te[12] = 0; + te[13] = 0; + te[14] = 0; + te[15] = 1; + return this; + } + makeRotationFromEuler(euler) { + const te = this.elements; + const { x, y, z } = euler; + const a = Math.cos(x), b = Math.sin(x); + const c = Math.cos(y), d = Math.sin(y); + const e = Math.cos(z), f = Math.sin(z); + if (euler.order === "XYZ") { + const ae = a * e, af = a * f, be = b * e, bf = b * f; + te[0] = c * e; + te[4] = -c * f; + te[8] = d; + te[1] = af + be * d; + te[5] = ae - bf * d; + te[9] = -b * c; + te[2] = bf - ae * d; + te[6] = be + af * d; + te[10] = a * c; + } else if (euler.order === "YXZ") { + const ce = c * e, cf = c * f, de = d * e, df = d * f; + te[0] = ce + df * b; + te[4] = de * b - cf; + te[8] = a * d; + te[1] = a * f; + te[5] = a * e; + te[9] = -b; + te[2] = cf * b - de; + te[6] = df + ce * b; + te[10] = a * c; + } else if (euler.order === "ZXY") { + const ce = c * e, cf = c * f, de = d * e, df = d * f; + te[0] = ce - df * b; + te[4] = -a * f; + te[8] = de + cf * b; + te[1] = cf + de * b; + te[5] = a * e; + te[9] = df - ce * b; + te[2] = -a * d; + te[6] = b; + te[10] = a * c; + } else if (euler.order === "ZYX") { + const ae = a * e, af = a * f, be = b * e, bf = b * f; + te[0] = c * e; + te[4] = be * d - af; + te[8] = ae * d + bf; + te[1] = c * f; + te[5] = bf * d + ae; + te[9] = af * d - be; + te[2] = -d; + te[6] = b * c; + te[10] = a * c; + } else if (euler.order === "YZX") { + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + te[0] = c * e; + te[4] = bd - ac * f; + te[8] = bc * f + ad; + te[1] = f; + te[5] = a * e; + te[9] = -b * e; + te[2] = -d * e; + te[6] = ad * f + bc; + te[10] = ac - bd * f; + } else if (euler.order === "XZY") { + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + te[0] = c * e; + te[4] = -f; + te[8] = d * e; + te[1] = ac * f + bd; + te[5] = a * e; + te[9] = ad * f - bc; + te[2] = bc * f - ad; + te[6] = b * e; + te[10] = bd * f + ac; + } + te[3] = 0; + te[7] = 0; + te[11] = 0; + te[12] = 0; + te[13] = 0; + te[14] = 0; + te[15] = 1; + return this; + } + makeRotationFromQuaternion(q) { + return this.compose(_zero2, q, _one2); + } + lookAt(eye, target, up) { + const te = this.elements; + _z2.subVectors(eye, target); + if (_z2.lengthSq() === 0) { + _z2.z = 1; + } + _z2.normalize(); + _x2.crossVectors(up, _z2); + if (_x2.lengthSq() === 0) { + if (Math.abs(up.z) === 1) { + _z2.x += 0.0001; + } else { + _z2.z += 0.0001; + } + _z2.normalize(); + _x2.crossVectors(up, _z2); + } + _x2.normalize(); + _y2.crossVectors(_z2, _x2); + te[0] = _x2.x; + te[4] = _y2.x; + te[8] = _z2.x; + te[1] = _x2.y; + te[5] = _y2.y; + te[9] = _z2.y; + te[2] = _x2.z; + te[6] = _y2.z; + te[10] = _z2.z; + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a, b) { + const ae = a.elements; + const be = b.elements; + const te = this.elements; + const a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12]; + const a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13]; + const a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14]; + const a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15]; + const b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; + const b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; + const b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; + const b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; + te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + return this; + } + multiplyScalar(s) { + const te = this.elements; + te[0] *= s; + te[4] *= s; + te[8] *= s; + te[12] *= s; + te[1] *= s; + te[5] *= s; + te[9] *= s; + te[13] *= s; + te[2] *= s; + te[6] *= s; + te[10] *= s; + te[14] *= s; + te[3] *= s; + te[7] *= s; + te[11] *= s; + te[15] *= s; + return this; + } + determinant() { + const te = this.elements; + const n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12]; + const n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13]; + const n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14]; + const n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15]; + return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31); + } + transpose() { + const te = this.elements; + let tmp3; + tmp3 = te[1]; + te[1] = te[4]; + te[4] = tmp3; + tmp3 = te[2]; + te[2] = te[8]; + te[8] = tmp3; + tmp3 = te[6]; + te[6] = te[9]; + te[9] = tmp3; + tmp3 = te[3]; + te[3] = te[12]; + te[12] = tmp3; + tmp3 = te[7]; + te[7] = te[13]; + te[13] = tmp3; + tmp3 = te[11]; + te[11] = te[14]; + te[14] = tmp3; + return this; + } + setPosition(x, y, z) { + const te = this.elements; + if (x.isVector3) { + te[12] = x.x; + te[13] = x.y; + te[14] = x.z; + } else { + te[12] = x; + te[13] = y; + te[14] = z; + } + return this; + } + invert() { + const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n41 = te[3], n12 = te[4], n22 = te[5], n32 = te[6], n42 = te[7], n13 = te[8], n23 = te[9], n33 = te[10], n43 = te[11], n14 = te[12], n24 = te[13], n34 = te[14], n44 = te[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + if (det === 0) + return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te[0] = t11 * detInv; + te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; + te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; + te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; + te[4] = t12 * detInv; + te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; + te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; + te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; + te[8] = t13 * detInv; + te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; + te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; + te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; + te[12] = t14 * detInv; + te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; + te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; + te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; + return this; + } + scale(v) { + const te = this.elements; + const { x, y, z } = v; + te[0] *= x; + te[4] *= y; + te[8] *= z; + te[1] *= x; + te[5] *= y; + te[9] *= z; + te[2] *= x; + te[6] *= y; + te[10] *= z; + te[3] *= x; + te[7] *= y; + te[11] *= z; + return this; + } + getMaxScaleOnAxis() { + const te = this.elements; + const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2]; + const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6]; + const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10]; + return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); + } + makeTranslation(x, y, z) { + if (x.isVector3) { + this.set(1, 0, 0, x.x, 0, 1, 0, x.y, 0, 0, 1, x.z, 0, 0, 0, 1); + } else { + this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1); + } + return this; + } + makeRotationX(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1); + return this; + } + makeRotationY(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1); + return this; + } + makeRotationZ(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return this; + } + makeRotationAxis(axis, angle) { + const c = Math.cos(angle); + const s = Math.sin(angle); + const t = 1 - c; + const { x, y, z } = axis; + const tx = t * x, ty = t * y; + this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1); + return this; + } + makeScale(x, y, z) { + this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); + return this; + } + makeShear(xy, xz, yx, yz, zx, zy) { + this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1); + return this; + } + compose(position2, quaternion, scale2) { + const te = this.elements; + const { _x: x, _y: y, _z: z, _w: w } = quaternion; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; + const { x: sx, y: sy, z: sz } = scale2; + te[0] = (1 - (yy + zz)) * sx; + te[1] = (xy + wz) * sx; + te[2] = (xz - wy) * sx; + te[3] = 0; + te[4] = (xy - wz) * sy; + te[5] = (1 - (xx + zz)) * sy; + te[6] = (yz + wx) * sy; + te[7] = 0; + te[8] = (xz + wy) * sz; + te[9] = (yz - wx) * sz; + te[10] = (1 - (xx + yy)) * sz; + te[11] = 0; + te[12] = position2.x; + te[13] = position2.y; + te[14] = position2.z; + te[15] = 1; + return this; + } + decompose(position2, quaternion, scale2) { + const te = this.elements; + let sx = _v1$52.set(te[0], te[1], te[2]).length(); + const sy = _v1$52.set(te[4], te[5], te[6]).length(); + const sz = _v1$52.set(te[8], te[9], te[10]).length(); + const det = this.determinant(); + if (det < 0) + sx = -sx; + position2.x = te[12]; + position2.y = te[13]; + position2.z = te[14]; + _m1$4.copy(this); + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + _m1$4.elements[0] *= invSX; + _m1$4.elements[1] *= invSX; + _m1$4.elements[2] *= invSX; + _m1$4.elements[4] *= invSY; + _m1$4.elements[5] *= invSY; + _m1$4.elements[6] *= invSY; + _m1$4.elements[8] *= invSZ; + _m1$4.elements[9] *= invSZ; + _m1$4.elements[10] *= invSZ; + quaternion.setFromRotationMatrix(_m1$4); + scale2.x = sx; + scale2.y = sy; + scale2.z = sz; + return this; + } + makePerspective(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem2) { + const te = this.elements; + const x = 2 * near / (right - left); + const y = 2 * near / (top - bottom); + const a = (right + left) / (right - left); + const b = (top + bottom) / (top - bottom); + let c, d; + if (coordinateSystem === WebGLCoordinateSystem2) { + c = -(far + near) / (far - near); + d = -2 * far * near / (far - near); + } else if (coordinateSystem === WebGPUCoordinateSystem2) { + c = -far / (far - near); + d = -far * near / (far - near); + } else { + throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + coordinateSystem); + } + te[0] = x; + te[4] = 0; + te[8] = a; + te[12] = 0; + te[1] = 0; + te[5] = y; + te[9] = b; + te[13] = 0; + te[2] = 0; + te[6] = 0; + te[10] = c; + te[14] = d; + te[3] = 0; + te[7] = 0; + te[11] = -1; + te[15] = 0; + return this; + } + makeOrthographic(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem2) { + const te = this.elements; + const w = 1 / (right - left); + const h = 1 / (top - bottom); + const p = 1 / (far - near); + const x = (right + left) * w; + const y = (top + bottom) * h; + let z, zInv; + if (coordinateSystem === WebGLCoordinateSystem2) { + z = (far + near) * p; + zInv = -2 * p; + } else if (coordinateSystem === WebGPUCoordinateSystem2) { + z = near * p; + zInv = -1 * p; + } else { + throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + coordinateSystem); + } + te[0] = 2 * w; + te[4] = 0; + te[8] = 0; + te[12] = -x; + te[1] = 0; + te[5] = 2 * h; + te[9] = 0; + te[13] = -y; + te[2] = 0; + te[6] = 0; + te[10] = zInv; + te[14] = -z; + te[3] = 0; + te[7] = 0; + te[11] = 0; + te[15] = 1; + return this; + } + equals(matrix) { + const te = this.elements; + const me = matrix.elements; + for (let i = 0;i < 16; i++) { + if (te[i] !== me[i]) + return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 16; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te = this.elements; + array[offset] = te[0]; + array[offset + 1] = te[1]; + array[offset + 2] = te[2]; + array[offset + 3] = te[3]; + array[offset + 4] = te[4]; + array[offset + 5] = te[5]; + array[offset + 6] = te[6]; + array[offset + 7] = te[7]; + array[offset + 8] = te[8]; + array[offset + 9] = te[9]; + array[offset + 10] = te[10]; + array[offset + 11] = te[11]; + array[offset + 12] = te[12]; + array[offset + 13] = te[13]; + array[offset + 14] = te[14]; + array[offset + 15] = te[15]; + return array; + } + } + var _v1$52 = /* @__PURE__ */ new Vector32; + var _m1$4 = /* @__PURE__ */ new Matrix42; + var _zero2 = /* @__PURE__ */ new Vector32(0, 0, 0); + var _one2 = /* @__PURE__ */ new Vector32(1, 1, 1); + var _x2 = /* @__PURE__ */ new Vector32; + var _y2 = /* @__PURE__ */ new Vector32; + var _z2 = /* @__PURE__ */ new Vector32; + var _matrix$22 = /* @__PURE__ */ new Matrix42; + var _quaternion$32 = /* @__PURE__ */ new Quaternion2; + + class Euler2 { + constructor(x = 0, y = 0, z = 0, order = Euler2.DEFAULT_ORDER) { + this.isEuler = true; + this._x = x; + this._y = y; + this._z = z; + this._order = order; + } + get x() { + return this._x; + } + set x(value2) { + this._x = value2; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value2) { + this._y = value2; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value2) { + this._z = value2; + this._onChangeCallback(); + } + get order() { + return this._order; + } + set order(value2) { + this._order = value2; + this._onChangeCallback(); + } + set(x, y, z, order = this._order) { + this._x = x; + this._y = y; + this._z = z; + this._order = order; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._order); + } + copy(euler) { + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m, order = this._order, update = true) { + const te = m.elements; + const m11 = te[0], m12 = te[4], m13 = te[8]; + const m21 = te[1], m22 = te[5], m23 = te[9]; + const m31 = te[2], m32 = te[6], m33 = te[10]; + switch (order) { + case "XYZ": + this._y = Math.asin(clamp3(m13, -1, 1)); + if (Math.abs(m13) < 0.9999999) { + this._x = Math.atan2(-m23, m33); + this._z = Math.atan2(-m12, m11); + } else { + this._x = Math.atan2(m32, m22); + this._z = 0; + } + break; + case "YXZ": + this._x = Math.asin(-clamp3(m23, -1, 1)); + if (Math.abs(m23) < 0.9999999) { + this._y = Math.atan2(m13, m33); + this._z = Math.atan2(m21, m22); + } else { + this._y = Math.atan2(-m31, m11); + this._z = 0; + } + break; + case "ZXY": + this._x = Math.asin(clamp3(m32, -1, 1)); + if (Math.abs(m32) < 0.9999999) { + this._y = Math.atan2(-m31, m33); + this._z = Math.atan2(-m12, m22); + } else { + this._y = 0; + this._z = Math.atan2(m21, m11); + } + break; + case "ZYX": + this._y = Math.asin(-clamp3(m31, -1, 1)); + if (Math.abs(m31) < 0.9999999) { + this._x = Math.atan2(m32, m33); + this._z = Math.atan2(m21, m11); + } else { + this._x = 0; + this._z = Math.atan2(-m12, m22); + } + break; + case "YZX": + this._z = Math.asin(clamp3(m21, -1, 1)); + if (Math.abs(m21) < 0.9999999) { + this._x = Math.atan2(-m23, m22); + this._y = Math.atan2(-m31, m11); + } else { + this._x = 0; + this._y = Math.atan2(m13, m33); + } + break; + case "XZY": + this._z = Math.asin(-clamp3(m12, -1, 1)); + if (Math.abs(m12) < 0.9999999) { + this._x = Math.atan2(m32, m22); + this._y = Math.atan2(m13, m11); + } else { + this._x = Math.atan2(-m23, m33); + this._y = 0; + } + break; + default: + console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + order); + } + this._order = order; + if (update === true) + this._onChangeCallback(); + return this; + } + setFromQuaternion(q, order, update) { + _matrix$22.makeRotationFromQuaternion(q); + return this.setFromRotationMatrix(_matrix$22, order, update); + } + setFromVector3(v, order = this._order) { + return this.set(v.x, v.y, v.z, order); + } + reorder(newOrder) { + _quaternion$32.setFromEuler(this); + return this.setFromQuaternion(_quaternion$32, newOrder); + } + equals(euler) { + return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order; + } + fromArray(array) { + this._x = array[0]; + this._y = array[1]; + this._z = array[2]; + if (array[3] !== undefined) + this._order = array[3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._order; + return array; + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._order; + } + } + Euler2.DEFAULT_ORDER = "XYZ"; + + class Layers2 { + constructor() { + this.mask = 1 | 0; + } + set(channel) { + this.mask = (1 << channel | 0) >>> 0; + } + enable(channel) { + this.mask |= 1 << channel | 0; + } + enableAll() { + this.mask = 4294967295 | 0; + } + toggle(channel) { + this.mask ^= 1 << channel | 0; + } + disable(channel) { + this.mask &= ~(1 << channel | 0); + } + disableAll() { + this.mask = 0; + } + test(layers) { + return (this.mask & layers.mask) !== 0; + } + isEnabled(channel) { + return (this.mask & (1 << channel | 0)) !== 0; + } + } + var _object3DId2 = 0; + var _v1$42 = /* @__PURE__ */ new Vector32; + var _q12 = /* @__PURE__ */ new Quaternion2; + var _m1$3 = /* @__PURE__ */ new Matrix42; + var _target2 = /* @__PURE__ */ new Vector32; + var _position$32 = /* @__PURE__ */ new Vector32; + var _scale$22 = /* @__PURE__ */ new Vector32; + var _quaternion$22 = /* @__PURE__ */ new Quaternion2; + var _xAxis2 = /* @__PURE__ */ new Vector32(1, 0, 0); + var _yAxis2 = /* @__PURE__ */ new Vector32(0, 1, 0); + var _zAxis2 = /* @__PURE__ */ new Vector32(0, 0, 1); + var _addedEvent2 = { type: "added" }; + var _removedEvent2 = { type: "removed" }; + var _childaddedEvent2 = { type: "childadded", child: null }; + var _childremovedEvent2 = { type: "childremoved", child: null }; + + class Object3D2 extends EventDispatcher2 { + constructor() { + super(); + this.isObject3D = true; + Object.defineProperty(this, "id", { value: _object3DId2++ }); + this.uuid = generateUUID2(); + this.name = ""; + this.type = "Object3D"; + this.parent = null; + this.children = []; + this.up = Object3D2.DEFAULT_UP.clone(); + const position2 = new Vector32; + const rotation2 = new Euler2; + const quaternion = new Quaternion2; + const scale2 = new Vector32(1, 1, 1); + function onRotationChange() { + quaternion.setFromEuler(rotation2, false); + } + function onQuaternionChange() { + rotation2.setFromQuaternion(quaternion, undefined, false); + } + rotation2._onChange(onRotationChange); + quaternion._onChange(onQuaternionChange); + Object.defineProperties(this, { + position: { + configurable: true, + enumerable: true, + value: position2 + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation2 + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale2 + }, + modelViewMatrix: { + value: new Matrix42 + }, + normalMatrix: { + value: new Matrix32 + } + }); + this.matrix = new Matrix42; + this.matrixWorld = new Matrix42; + this.matrixAutoUpdate = Object3D2.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldAutoUpdate = Object3D2.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + this.layers = new Layers2; + this.visible = true; + this.castShadow = false; + this.receiveShadow = false; + this.frustumCulled = true; + this.renderOrder = 0; + this.animations = []; + this.userData = {}; + } + onBeforeShadow() { + } + onAfterShadow() { + } + onBeforeRender() { + } + onAfterRender() { + } + applyMatrix4(matrix) { + if (this.matrixAutoUpdate) + this.updateMatrix(); + this.matrix.premultiply(matrix); + this.matrix.decompose(this.position, this.quaternion, this.scale); + } + applyQuaternion(q) { + this.quaternion.premultiply(q); + return this; + } + setRotationFromAxisAngle(axis, angle) { + this.quaternion.setFromAxisAngle(axis, angle); + } + setRotationFromEuler(euler) { + this.quaternion.setFromEuler(euler, true); + } + setRotationFromMatrix(m) { + this.quaternion.setFromRotationMatrix(m); + } + setRotationFromQuaternion(q) { + this.quaternion.copy(q); + } + rotateOnAxis(axis, angle) { + _q12.setFromAxisAngle(axis, angle); + this.quaternion.multiply(_q12); + return this; + } + rotateOnWorldAxis(axis, angle) { + _q12.setFromAxisAngle(axis, angle); + this.quaternion.premultiply(_q12); + return this; + } + rotateX(angle) { + return this.rotateOnAxis(_xAxis2, angle); + } + rotateY(angle) { + return this.rotateOnAxis(_yAxis2, angle); + } + rotateZ(angle) { + return this.rotateOnAxis(_zAxis2, angle); + } + translateOnAxis(axis, distance) { + _v1$42.copy(axis).applyQuaternion(this.quaternion); + this.position.add(_v1$42.multiplyScalar(distance)); + return this; + } + translateX(distance) { + return this.translateOnAxis(_xAxis2, distance); + } + translateY(distance) { + return this.translateOnAxis(_yAxis2, distance); + } + translateZ(distance) { + return this.translateOnAxis(_zAxis2, distance); + } + localToWorld(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(this.matrixWorld); + } + worldToLocal(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(_m1$3.copy(this.matrixWorld).invert()); + } + lookAt(x, y, z) { + if (x.isVector3) { + _target2.copy(x); + } else { + _target2.set(x, y, z); + } + const parent2 = this.parent; + this.updateWorldMatrix(true, false); + _position$32.setFromMatrixPosition(this.matrixWorld); + if (this.isCamera || this.isLight) { + _m1$3.lookAt(_position$32, _target2, this.up); + } else { + _m1$3.lookAt(_target2, _position$32, this.up); + } + this.quaternion.setFromRotationMatrix(_m1$3); + if (parent2) { + _m1$3.extractRotation(parent2.matrixWorld); + _q12.setFromRotationMatrix(_m1$3); + this.quaternion.premultiply(_q12.invert()); + } + } + add(object) { + if (arguments.length > 1) { + for (let i = 0;i < arguments.length; i++) { + this.add(arguments[i]); + } + return this; + } + if (object === this) { + console.error("THREE.Object3D.add: object can't be added as a child of itself.", object); + return this; + } + if (object && object.isObject3D) { + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.dispatchEvent(_addedEvent2); + _childaddedEvent2.child = object; + this.dispatchEvent(_childaddedEvent2); + _childaddedEvent2.child = null; + } else { + console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object); + } + return this; + } + remove(object) { + if (arguments.length > 1) { + for (let i = 0;i < arguments.length; i++) { + this.remove(arguments[i]); + } + return this; + } + const index2 = this.children.indexOf(object); + if (index2 !== -1) { + object.parent = null; + this.children.splice(index2, 1); + object.dispatchEvent(_removedEvent2); + _childremovedEvent2.child = object; + this.dispatchEvent(_childremovedEvent2); + _childremovedEvent2.child = null; + } + return this; + } + removeFromParent() { + const parent2 = this.parent; + if (parent2 !== null) { + parent2.remove(this); + } + return this; + } + clear() { + return this.remove(...this.children); + } + attach(object) { + this.updateWorldMatrix(true, false); + _m1$3.copy(this.matrixWorld).invert(); + if (object.parent !== null) { + object.parent.updateWorldMatrix(true, false); + _m1$3.multiply(object.parent.matrixWorld); + } + object.applyMatrix4(_m1$3); + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.updateWorldMatrix(false, true); + object.dispatchEvent(_addedEvent2); + _childaddedEvent2.child = object; + this.dispatchEvent(_childaddedEvent2); + _childaddedEvent2.child = null; + return this; + } + getObjectById(id) { + return this.getObjectByProperty("id", id); + } + getObjectByName(name2) { + return this.getObjectByProperty("name", name2); + } + getObjectByProperty(name2, value2) { + if (this[name2] === value2) + return this; + for (let i = 0, l = this.children.length;i < l; i++) { + const child = this.children[i]; + const object = child.getObjectByProperty(name2, value2); + if (object !== undefined) { + return object; + } + } + return; + } + getObjectsByProperty(name2, value2, result = []) { + if (this[name2] === value2) + result.push(this); + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + children[i].getObjectsByProperty(name2, value2, result); + } + return result; + } + getWorldPosition(target) { + this.updateWorldMatrix(true, false); + return target.setFromMatrixPosition(this.matrixWorld); + } + getWorldQuaternion(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$32, target, _scale$22); + return target; + } + getWorldScale(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$32, _quaternion$22, target); + return target; + } + getWorldDirection(target) { + this.updateWorldMatrix(true, false); + const e = this.matrixWorld.elements; + return target.set(e[8], e[9], e[10]).normalize(); + } + raycast() { + } + traverse(callback) { + callback(this); + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + children[i].traverse(callback); + } + } + traverseVisible(callback) { + if (this.visible === false) + return; + callback(this); + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + children[i].traverseVisible(callback); + } + } + traverseAncestors(callback) { + const parent2 = this.parent; + if (parent2 !== null) { + callback(parent2); + parent2.traverseAncestors(callback); + } + } + updateMatrix() { + this.matrix.compose(this.position, this.quaternion, this.scale); + this.matrixWorldNeedsUpdate = true; + } + updateMatrixWorld(force) { + if (this.matrixAutoUpdate) + this.updateMatrix(); + if (this.matrixWorldNeedsUpdate || force) { + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + this.matrixWorldNeedsUpdate = false; + force = true; + } + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + const child = children[i]; + child.updateMatrixWorld(force); + } + } + updateWorldMatrix(updateParents, updateChildren) { + const parent2 = this.parent; + if (updateParents === true && parent2 !== null) { + parent2.updateWorldMatrix(true, false); + } + if (this.matrixAutoUpdate) + this.updateMatrix(); + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + if (updateChildren === true) { + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + const child = children[i]; + child.updateWorldMatrix(false, true); + } + } + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + const output = {}; + if (isRootObject) { + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + output.metadata = { + version: 4.6, + type: "Object", + generator: "Object3D.toJSON" + }; + } + const object = {}; + object.uuid = this.uuid; + object.type = this.type; + if (this.name !== "") + object.name = this.name; + if (this.castShadow === true) + object.castShadow = true; + if (this.receiveShadow === true) + object.receiveShadow = true; + if (this.visible === false) + object.visible = false; + if (this.frustumCulled === false) + object.frustumCulled = false; + if (this.renderOrder !== 0) + object.renderOrder = this.renderOrder; + if (Object.keys(this.userData).length > 0) + object.userData = this.userData; + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + object.up = this.up.toArray(); + if (this.matrixAutoUpdate === false) + object.matrixAutoUpdate = false; + if (this.isInstancedMesh) { + object.type = "InstancedMesh"; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if (this.instanceColor !== null) + object.instanceColor = this.instanceColor.toJSON(); + } + if (this.isBatchedMesh) { + object.type = "BatchedMesh"; + object.perObjectFrustumCulled = this.perObjectFrustumCulled; + object.sortObjects = this.sortObjects; + object.drawRanges = this._drawRanges; + object.reservedRanges = this._reservedRanges; + object.visibility = this._visibility; + object.active = this._active; + object.bounds = this._bounds.map((bound) => ({ + boxInitialized: bound.boxInitialized, + boxMin: bound.box.min.toArray(), + boxMax: bound.box.max.toArray(), + sphereInitialized: bound.sphereInitialized, + sphereRadius: bound.sphere.radius, + sphereCenter: bound.sphere.center.toArray() + })); + object.maxInstanceCount = this._maxInstanceCount; + object.maxVertexCount = this._maxVertexCount; + object.maxIndexCount = this._maxIndexCount; + object.geometryInitialized = this._geometryInitialized; + object.geometryCount = this._geometryCount; + object.matricesTexture = this._matricesTexture.toJSON(meta); + if (this._colorsTexture !== null) + object.colorsTexture = this._colorsTexture.toJSON(meta); + if (this.boundingSphere !== null) { + object.boundingSphere = { + center: object.boundingSphere.center.toArray(), + radius: object.boundingSphere.radius + }; + } + if (this.boundingBox !== null) { + object.boundingBox = { + min: object.boundingBox.min.toArray(), + max: object.boundingBox.max.toArray() + }; + } + } + function serialize(library, element) { + if (library[element.uuid] === undefined) { + library[element.uuid] = element.toJSON(meta); + } + return element.uuid; + } + if (this.isScene) { + if (this.background) { + if (this.background.isColor) { + object.background = this.background.toJSON(); + } else if (this.background.isTexture) { + object.background = this.background.toJSON(meta).uuid; + } + } + if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) { + object.environment = this.environment.toJSON(meta).uuid; + } + } else if (this.isMesh || this.isLine || this.isPoints) { + object.geometry = serialize(meta.geometries, this.geometry); + const parameters = this.geometry.parameters; + if (parameters !== undefined && parameters.shapes !== undefined) { + const shapes = parameters.shapes; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + serialize(meta.shapes, shape); + } + } else { + serialize(meta.shapes, shapes); + } + } + } + if (this.isSkinnedMesh) { + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + if (this.skeleton !== undefined) { + serialize(meta.skeletons, this.skeleton); + object.skeleton = this.skeleton.uuid; + } + } + if (this.material !== undefined) { + if (Array.isArray(this.material)) { + const uuids = []; + for (let i = 0, l = this.material.length;i < l; i++) { + uuids.push(serialize(meta.materials, this.material[i])); + } + object.material = uuids; + } else { + object.material = serialize(meta.materials, this.material); + } + } + if (this.children.length > 0) { + object.children = []; + for (let i = 0;i < this.children.length; i++) { + object.children.push(this.children[i].toJSON(meta).object); + } + } + if (this.animations.length > 0) { + object.animations = []; + for (let i = 0;i < this.animations.length; i++) { + const animation = this.animations[i]; + object.animations.push(serialize(meta.animations, animation)); + } + } + if (isRootObject) { + const geometries = extractFromCache(meta.geometries); + const materials = extractFromCache(meta.materials); + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + const shapes = extractFromCache(meta.shapes); + const skeletons = extractFromCache(meta.skeletons); + const animations = extractFromCache(meta.animations); + const nodes = extractFromCache(meta.nodes); + if (geometries.length > 0) + output.geometries = geometries; + if (materials.length > 0) + output.materials = materials; + if (textures.length > 0) + output.textures = textures; + if (images.length > 0) + output.images = images; + if (shapes.length > 0) + output.shapes = shapes; + if (skeletons.length > 0) + output.skeletons = skeletons; + if (animations.length > 0) + output.animations = animations; + if (nodes.length > 0) + output.nodes = nodes; + } + output.object = object; + return output; + function extractFromCache(cache) { + const values2 = []; + for (const key2 in cache) { + const data2 = cache[key2]; + delete data2.metadata; + values2.push(data2); + } + return values2; + } + } + clone(recursive) { + return new this.constructor().copy(this, recursive); + } + copy(source, recursive = true) { + this.name = source.name; + this.up.copy(source.up); + this.position.copy(source.position); + this.rotation.order = source.rotation.order; + this.quaternion.copy(source.quaternion); + this.scale.copy(source.scale); + this.matrix.copy(source.matrix); + this.matrixWorld.copy(source.matrixWorld); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + this.layers.mask = source.layers.mask; + this.visible = source.visible; + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + this.animations = source.animations.slice(); + this.userData = JSON.parse(JSON.stringify(source.userData)); + if (recursive === true) { + for (let i = 0;i < source.children.length; i++) { + const child = source.children[i]; + this.add(child.clone()); + } + } + return this; + } + } + Object3D2.DEFAULT_UP = /* @__PURE__ */ new Vector32(0, 1, 0); + Object3D2.DEFAULT_MATRIX_AUTO_UPDATE = true; + Object3D2.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; + var _v0$22 = /* @__PURE__ */ new Vector32; + var _v1$32 = /* @__PURE__ */ new Vector32; + var _v2$22 = /* @__PURE__ */ new Vector32; + var _v3$22 = /* @__PURE__ */ new Vector32; + var _vab2 = /* @__PURE__ */ new Vector32; + var _vac2 = /* @__PURE__ */ new Vector32; + var _vbc2 = /* @__PURE__ */ new Vector32; + var _vap2 = /* @__PURE__ */ new Vector32; + var _vbp2 = /* @__PURE__ */ new Vector32; + var _vcp2 = /* @__PURE__ */ new Vector32; + var _v402 = /* @__PURE__ */ new Vector42; + var _v412 = /* @__PURE__ */ new Vector42; + var _v422 = /* @__PURE__ */ new Vector42; + + class Triangle2 { + constructor(a = new Vector32, b = new Vector32, c = new Vector32) { + this.a = a; + this.b = b; + this.c = c; + } + static getNormal(a, b, c, target) { + target.subVectors(c, b); + _v0$22.subVectors(a, b); + target.cross(_v0$22); + const targetLengthSq = target.lengthSq(); + if (targetLengthSq > 0) { + return target.multiplyScalar(1 / Math.sqrt(targetLengthSq)); + } + return target.set(0, 0, 0); + } + static getBarycoord(point, a, b, c, target) { + _v0$22.subVectors(c, a); + _v1$32.subVectors(b, a); + _v2$22.subVectors(point, a); + const dot00 = _v0$22.dot(_v0$22); + const dot01 = _v0$22.dot(_v1$32); + const dot02 = _v0$22.dot(_v2$22); + const dot11 = _v1$32.dot(_v1$32); + const dot12 = _v1$32.dot(_v2$22); + const denom = dot00 * dot11 - dot01 * dot01; + if (denom === 0) { + target.set(0, 0, 0); + return null; + } + const invDenom = 1 / denom; + const u = (dot11 * dot02 - dot01 * dot12) * invDenom; + const v = (dot00 * dot12 - dot01 * dot02) * invDenom; + return target.set(1 - u - v, v, u); + } + static containsPoint(point, a, b, c) { + if (this.getBarycoord(point, a, b, c, _v3$22) === null) { + return false; + } + return _v3$22.x >= 0 && _v3$22.y >= 0 && _v3$22.x + _v3$22.y <= 1; + } + static getInterpolation(point, p1, p2, p3, v1, v2, v3, target) { + if (this.getBarycoord(point, p1, p2, p3, _v3$22) === null) { + target.x = 0; + target.y = 0; + if ("z" in target) + target.z = 0; + if ("w" in target) + target.w = 0; + return null; + } + target.setScalar(0); + target.addScaledVector(v1, _v3$22.x); + target.addScaledVector(v2, _v3$22.y); + target.addScaledVector(v3, _v3$22.z); + return target; + } + static getInterpolatedAttribute(attr, i1, i2, i3, barycoord, target) { + _v402.setScalar(0); + _v412.setScalar(0); + _v422.setScalar(0); + _v402.fromBufferAttribute(attr, i1); + _v412.fromBufferAttribute(attr, i2); + _v422.fromBufferAttribute(attr, i3); + target.setScalar(0); + target.addScaledVector(_v402, barycoord.x); + target.addScaledVector(_v412, barycoord.y); + target.addScaledVector(_v422, barycoord.z); + return target; + } + static isFrontFacing(a, b, c, direction) { + _v0$22.subVectors(c, b); + _v1$32.subVectors(a, b); + return _v0$22.cross(_v1$32).dot(direction) < 0 ? true : false; + } + set(a, b, c) { + this.a.copy(a); + this.b.copy(b); + this.c.copy(c); + return this; + } + setFromPointsAndIndices(points, i0, i1, i2) { + this.a.copy(points[i0]); + this.b.copy(points[i1]); + this.c.copy(points[i2]); + return this; + } + setFromAttributeAndIndices(attribute, i0, i1, i2) { + this.a.fromBufferAttribute(attribute, i0); + this.b.fromBufferAttribute(attribute, i1); + this.c.fromBufferAttribute(attribute, i2); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(triangle) { + this.a.copy(triangle.a); + this.b.copy(triangle.b); + this.c.copy(triangle.c); + return this; + } + getArea() { + _v0$22.subVectors(this.c, this.b); + _v1$32.subVectors(this.a, this.b); + return _v0$22.cross(_v1$32).length() * 0.5; + } + getMidpoint(target) { + return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); + } + getNormal(target) { + return Triangle2.getNormal(this.a, this.b, this.c, target); + } + getPlane(target) { + return target.setFromCoplanarPoints(this.a, this.b, this.c); + } + getBarycoord(point, target) { + return Triangle2.getBarycoord(point, this.a, this.b, this.c, target); + } + getInterpolation(point, v1, v2, v3, target) { + return Triangle2.getInterpolation(point, this.a, this.b, this.c, v1, v2, v3, target); + } + containsPoint(point) { + return Triangle2.containsPoint(point, this.a, this.b, this.c); + } + isFrontFacing(direction) { + return Triangle2.isFrontFacing(this.a, this.b, this.c, direction); + } + intersectsBox(box) { + return box.intersectsTriangle(this); + } + closestPointToPoint(p, target) { + const a = this.a, b = this.b, c = this.c; + let v, w; + _vab2.subVectors(b, a); + _vac2.subVectors(c, a); + _vap2.subVectors(p, a); + const d1 = _vab2.dot(_vap2); + const d2 = _vac2.dot(_vap2); + if (d1 <= 0 && d2 <= 0) { + return target.copy(a); + } + _vbp2.subVectors(p, b); + const d3 = _vab2.dot(_vbp2); + const d4 = _vac2.dot(_vbp2); + if (d3 >= 0 && d4 <= d3) { + return target.copy(b); + } + const vc = d1 * d4 - d3 * d2; + if (vc <= 0 && d1 >= 0 && d3 <= 0) { + v = d1 / (d1 - d3); + return target.copy(a).addScaledVector(_vab2, v); + } + _vcp2.subVectors(p, c); + const d5 = _vab2.dot(_vcp2); + const d6 = _vac2.dot(_vcp2); + if (d6 >= 0 && d5 <= d6) { + return target.copy(c); + } + const vb = d5 * d2 - d1 * d6; + if (vb <= 0 && d2 >= 0 && d6 <= 0) { + w = d2 / (d2 - d6); + return target.copy(a).addScaledVector(_vac2, w); + } + const va = d3 * d6 - d5 * d4; + if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { + _vbc2.subVectors(c, b); + w = (d4 - d3) / (d4 - d3 + (d5 - d6)); + return target.copy(b).addScaledVector(_vbc2, w); + } + const denom = 1 / (va + vb + vc); + v = vb * denom; + w = vc * denom; + return target.copy(a).addScaledVector(_vab2, v).addScaledVector(_vac2, w); + } + equals(triangle) { + return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c); + } + } + var _colorKeywords2 = { + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + rebeccapurple: 6697881, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 + }; + var _hslA2 = { h: 0, s: 0, l: 0 }; + var _hslB2 = { h: 0, s: 0, l: 0 }; + function hue2rgb3(p, q, t) { + if (t < 0) + t += 1; + if (t > 1) + t -= 1; + if (t < 1 / 6) + return p + (q - p) * 6 * t; + if (t < 1 / 2) + return q; + if (t < 2 / 3) + return p + (q - p) * 6 * (2 / 3 - t); + return p; + } + + class Color2 { + constructor(r, g, b) { + this.isColor = true; + this.r = 1; + this.g = 1; + this.b = 1; + return this.set(r, g, b); + } + set(r, g, b) { + if (g === undefined && b === undefined) { + const value2 = r; + if (value2 && value2.isColor) { + this.copy(value2); + } else if (typeof value2 === "number") { + this.setHex(value2); + } else if (typeof value2 === "string") { + this.setStyle(value2); + } + } else { + this.setRGB(r, g, b); + } + return this; + } + setScalar(scalar) { + this.r = scalar; + this.g = scalar; + this.b = scalar; + return this; + } + setHex(hex, colorSpace = SRGBColorSpace2) { + hex = Math.floor(hex); + this.r = (hex >> 16 & 255) / 255; + this.g = (hex >> 8 & 255) / 255; + this.b = (hex & 255) / 255; + ColorManagement2.toWorkingColorSpace(this, colorSpace); + return this; + } + setRGB(r, g, b, colorSpace = ColorManagement2.workingColorSpace) { + this.r = r; + this.g = g; + this.b = b; + ColorManagement2.toWorkingColorSpace(this, colorSpace); + return this; + } + setHSL(h, s, l, colorSpace = ColorManagement2.workingColorSpace) { + h = euclideanModulo2(h, 1); + s = clamp3(s, 0, 1); + l = clamp3(l, 0, 1); + if (s === 0) { + this.r = this.g = this.b = l; + } else { + const p = l <= 0.5 ? l * (1 + s) : l + s - l * s; + const q = 2 * l - p; + this.r = hue2rgb3(q, p, h + 1 / 3); + this.g = hue2rgb3(q, p, h); + this.b = hue2rgb3(q, p, h - 1 / 3); + } + ColorManagement2.toWorkingColorSpace(this, colorSpace); + return this; + } + setStyle(style, colorSpace = SRGBColorSpace2) { + function handleAlpha(string) { + if (string === undefined) + return; + if (parseFloat(string) < 1) { + console.warn("THREE.Color: Alpha component of " + style + " will be ignored."); + } + } + let m; + if (m = /^(\w+)\(([^\)]*)\)/.exec(style)) { + let color; + const name2 = m[1]; + const components = m[2]; + switch (name2) { + case "rgb": + case "rgba": + if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB(Math.min(255, parseInt(color[1], 10)) / 255, Math.min(255, parseInt(color[2], 10)) / 255, Math.min(255, parseInt(color[3], 10)) / 255, colorSpace); + } + if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB(Math.min(100, parseInt(color[1], 10)) / 100, Math.min(100, parseInt(color[2], 10)) / 100, Math.min(100, parseInt(color[3], 10)) / 100, colorSpace); + } + break; + case "hsl": + case "hsla": + if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setHSL(parseFloat(color[1]) / 360, parseFloat(color[2]) / 100, parseFloat(color[3]) / 100, colorSpace); + } + break; + default: + console.warn("THREE.Color: Unknown color model " + style); + } + } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) { + const hex = m[1]; + const size = hex.length; + if (size === 3) { + return this.setRGB(parseInt(hex.charAt(0), 16) / 15, parseInt(hex.charAt(1), 16) / 15, parseInt(hex.charAt(2), 16) / 15, colorSpace); + } else if (size === 6) { + return this.setHex(parseInt(hex, 16), colorSpace); + } else { + console.warn("THREE.Color: Invalid hex color " + style); + } + } else if (style && style.length > 0) { + return this.setColorName(style, colorSpace); + } + return this; + } + setColorName(style, colorSpace = SRGBColorSpace2) { + const hex = _colorKeywords2[style.toLowerCase()]; + if (hex !== undefined) { + this.setHex(hex, colorSpace); + } else { + console.warn("THREE.Color: Unknown color " + style); + } + return this; + } + clone() { + return new this.constructor(this.r, this.g, this.b); + } + copy(color) { + this.r = color.r; + this.g = color.g; + this.b = color.b; + return this; + } + copySRGBToLinear(color) { + this.r = SRGBToLinear2(color.r); + this.g = SRGBToLinear2(color.g); + this.b = SRGBToLinear2(color.b); + return this; + } + copyLinearToSRGB(color) { + this.r = LinearToSRGB2(color.r); + this.g = LinearToSRGB2(color.g); + this.b = LinearToSRGB2(color.b); + return this; + } + convertSRGBToLinear() { + this.copySRGBToLinear(this); + return this; + } + convertLinearToSRGB() { + this.copyLinearToSRGB(this); + return this; + } + getHex(colorSpace = SRGBColorSpace2) { + ColorManagement2.fromWorkingColorSpace(_color3.copy(this), colorSpace); + return Math.round(clamp3(_color3.r * 255, 0, 255)) * 65536 + Math.round(clamp3(_color3.g * 255, 0, 255)) * 256 + Math.round(clamp3(_color3.b * 255, 0, 255)); + } + getHexString(colorSpace = SRGBColorSpace2) { + return ("000000" + this.getHex(colorSpace).toString(16)).slice(-6); + } + getHSL(target, colorSpace = ColorManagement2.workingColorSpace) { + ColorManagement2.fromWorkingColorSpace(_color3.copy(this), colorSpace); + const { r, g, b } = _color3; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + let hue, saturation; + const lightness = (min + max) / 2; + if (min === max) { + hue = 0; + saturation = 0; + } else { + const delta = max - min; + saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min); + switch (max) { + case r: + hue = (g - b) / delta + (g < b ? 6 : 0); + break; + case g: + hue = (b - r) / delta + 2; + break; + case b: + hue = (r - g) / delta + 4; + break; + } + hue /= 6; + } + target.h = hue; + target.s = saturation; + target.l = lightness; + return target; + } + getRGB(target, colorSpace = ColorManagement2.workingColorSpace) { + ColorManagement2.fromWorkingColorSpace(_color3.copy(this), colorSpace); + target.r = _color3.r; + target.g = _color3.g; + target.b = _color3.b; + return target; + } + getStyle(colorSpace = SRGBColorSpace2) { + ColorManagement2.fromWorkingColorSpace(_color3.copy(this), colorSpace); + const { r, g, b } = _color3; + if (colorSpace !== SRGBColorSpace2) { + return `color(${colorSpace} ${r.toFixed(3)} ${g.toFixed(3)} ${b.toFixed(3)})`; + } + return `rgb(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)})`; + } + offsetHSL(h, s, l) { + this.getHSL(_hslA2); + return this.setHSL(_hslA2.h + h, _hslA2.s + s, _hslA2.l + l); + } + add(color) { + this.r += color.r; + this.g += color.g; + this.b += color.b; + return this; + } + addColors(color1, color2) { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + return this; + } + addScalar(s) { + this.r += s; + this.g += s; + this.b += s; + return this; + } + sub(color) { + this.r = Math.max(0, this.r - color.r); + this.g = Math.max(0, this.g - color.g); + this.b = Math.max(0, this.b - color.b); + return this; + } + multiply(color) { + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + return this; + } + multiplyScalar(s) { + this.r *= s; + this.g *= s; + this.b *= s; + return this; + } + lerp(color, alpha) { + this.r += (color.r - this.r) * alpha; + this.g += (color.g - this.g) * alpha; + this.b += (color.b - this.b) * alpha; + return this; + } + lerpColors(color1, color2, alpha) { + this.r = color1.r + (color2.r - color1.r) * alpha; + this.g = color1.g + (color2.g - color1.g) * alpha; + this.b = color1.b + (color2.b - color1.b) * alpha; + return this; + } + lerpHSL(color, alpha) { + this.getHSL(_hslA2); + color.getHSL(_hslB2); + const h = lerp2(_hslA2.h, _hslB2.h, alpha); + const s = lerp2(_hslA2.s, _hslB2.s, alpha); + const l = lerp2(_hslA2.l, _hslB2.l, alpha); + this.setHSL(h, s, l); + return this; + } + setFromVector3(v) { + this.r = v.x; + this.g = v.y; + this.b = v.z; + return this; + } + applyMatrix3(m) { + const r = this.r, g = this.g, b = this.b; + const e = m.elements; + this.r = e[0] * r + e[3] * g + e[6] * b; + this.g = e[1] * r + e[4] * g + e[7] * b; + this.b = e[2] * r + e[5] * g + e[8] * b; + return this; + } + equals(c) { + return c.r === this.r && c.g === this.g && c.b === this.b; + } + fromArray(array, offset = 0) { + this.r = array[offset]; + this.g = array[offset + 1]; + this.b = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.r; + array[offset + 1] = this.g; + array[offset + 2] = this.b; + return array; + } + fromBufferAttribute(attribute, index2) { + this.r = attribute.getX(index2); + this.g = attribute.getY(index2); + this.b = attribute.getZ(index2); + return this; + } + toJSON() { + return this.getHex(); + } + *[Symbol.iterator]() { + yield this.r; + yield this.g; + yield this.b; + } + } + var _color3 = /* @__PURE__ */ new Color2; + Color2.NAMES = _colorKeywords2; + var _materialId2 = 0; + + class Material2 extends EventDispatcher2 { + constructor() { + super(); + this.isMaterial = true; + Object.defineProperty(this, "id", { value: _materialId2++ }); + this.uuid = generateUUID2(); + this.name = ""; + this.type = "Material"; + this.blending = NormalBlending2; + this.side = FrontSide2; + this.vertexColors = false; + this.opacity = 1; + this.transparent = false; + this.alphaHash = false; + this.blendSrc = SrcAlphaFactor2; + this.blendDst = OneMinusSrcAlphaFactor2; + this.blendEquation = AddEquation2; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; + this.blendColor = new Color2(0, 0, 0); + this.blendAlpha = 0; + this.depthFunc = LessEqualDepth2; + this.depthTest = true; + this.depthWrite = true; + this.stencilWriteMask = 255; + this.stencilFunc = AlwaysStencilFunc2; + this.stencilRef = 0; + this.stencilFuncMask = 255; + this.stencilFail = KeepStencilOp2; + this.stencilZFail = KeepStencilOp2; + this.stencilZPass = KeepStencilOp2; + this.stencilWrite = false; + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + this.shadowSide = null; + this.colorWrite = true; + this.precision = null; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + this.dithering = false; + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + this.forceSinglePass = false; + this.visible = true; + this.toneMapped = true; + this.userData = {}; + this.version = 0; + this._alphaTest = 0; + } + get alphaTest() { + return this._alphaTest; + } + set alphaTest(value2) { + if (this._alphaTest > 0 !== value2 > 0) { + this.version++; + } + this._alphaTest = value2; + } + onBeforeRender() { + } + onBeforeCompile() { + } + customProgramCacheKey() { + return this.onBeforeCompile.toString(); + } + setValues(values2) { + if (values2 === undefined) + return; + for (const key2 in values2) { + const newValue = values2[key2]; + if (newValue === undefined) { + console.warn(`THREE.Material: parameter '${key2}' has value of undefined.`); + continue; + } + const currentValue = this[key2]; + if (currentValue === undefined) { + console.warn(`THREE.Material: '${key2}' is not a property of THREE.${this.type}.`); + continue; + } + if (currentValue && currentValue.isColor) { + currentValue.set(newValue); + } else if (currentValue && currentValue.isVector3 && (newValue && newValue.isVector3)) { + currentValue.copy(newValue); + } else { + this[key2] = newValue; + } + } + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + if (isRootObject) { + meta = { + textures: {}, + images: {} + }; + } + const data2 = { + metadata: { + version: 4.6, + type: "Material", + generator: "Material.toJSON" + } + }; + data2.uuid = this.uuid; + data2.type = this.type; + if (this.name !== "") + data2.name = this.name; + if (this.color && this.color.isColor) + data2.color = this.color.getHex(); + if (this.roughness !== undefined) + data2.roughness = this.roughness; + if (this.metalness !== undefined) + data2.metalness = this.metalness; + if (this.sheen !== undefined) + data2.sheen = this.sheen; + if (this.sheenColor && this.sheenColor.isColor) + data2.sheenColor = this.sheenColor.getHex(); + if (this.sheenRoughness !== undefined) + data2.sheenRoughness = this.sheenRoughness; + if (this.emissive && this.emissive.isColor) + data2.emissive = this.emissive.getHex(); + if (this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1) + data2.emissiveIntensity = this.emissiveIntensity; + if (this.specular && this.specular.isColor) + data2.specular = this.specular.getHex(); + if (this.specularIntensity !== undefined) + data2.specularIntensity = this.specularIntensity; + if (this.specularColor && this.specularColor.isColor) + data2.specularColor = this.specularColor.getHex(); + if (this.shininess !== undefined) + data2.shininess = this.shininess; + if (this.clearcoat !== undefined) + data2.clearcoat = this.clearcoat; + if (this.clearcoatRoughness !== undefined) + data2.clearcoatRoughness = this.clearcoatRoughness; + if (this.clearcoatMap && this.clearcoatMap.isTexture) { + data2.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid; + } + if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) { + data2.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid; + } + if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) { + data2.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid; + data2.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + } + if (this.dispersion !== undefined) + data2.dispersion = this.dispersion; + if (this.iridescence !== undefined) + data2.iridescence = this.iridescence; + if (this.iridescenceIOR !== undefined) + data2.iridescenceIOR = this.iridescenceIOR; + if (this.iridescenceThicknessRange !== undefined) + data2.iridescenceThicknessRange = this.iridescenceThicknessRange; + if (this.iridescenceMap && this.iridescenceMap.isTexture) { + data2.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid; + } + if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) { + data2.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid; + } + if (this.anisotropy !== undefined) + data2.anisotropy = this.anisotropy; + if (this.anisotropyRotation !== undefined) + data2.anisotropyRotation = this.anisotropyRotation; + if (this.anisotropyMap && this.anisotropyMap.isTexture) { + data2.anisotropyMap = this.anisotropyMap.toJSON(meta).uuid; + } + if (this.map && this.map.isTexture) + data2.map = this.map.toJSON(meta).uuid; + if (this.matcap && this.matcap.isTexture) + data2.matcap = this.matcap.toJSON(meta).uuid; + if (this.alphaMap && this.alphaMap.isTexture) + data2.alphaMap = this.alphaMap.toJSON(meta).uuid; + if (this.lightMap && this.lightMap.isTexture) { + data2.lightMap = this.lightMap.toJSON(meta).uuid; + data2.lightMapIntensity = this.lightMapIntensity; + } + if (this.aoMap && this.aoMap.isTexture) { + data2.aoMap = this.aoMap.toJSON(meta).uuid; + data2.aoMapIntensity = this.aoMapIntensity; + } + if (this.bumpMap && this.bumpMap.isTexture) { + data2.bumpMap = this.bumpMap.toJSON(meta).uuid; + data2.bumpScale = this.bumpScale; + } + if (this.normalMap && this.normalMap.isTexture) { + data2.normalMap = this.normalMap.toJSON(meta).uuid; + data2.normalMapType = this.normalMapType; + data2.normalScale = this.normalScale.toArray(); + } + if (this.displacementMap && this.displacementMap.isTexture) { + data2.displacementMap = this.displacementMap.toJSON(meta).uuid; + data2.displacementScale = this.displacementScale; + data2.displacementBias = this.displacementBias; + } + if (this.roughnessMap && this.roughnessMap.isTexture) + data2.roughnessMap = this.roughnessMap.toJSON(meta).uuid; + if (this.metalnessMap && this.metalnessMap.isTexture) + data2.metalnessMap = this.metalnessMap.toJSON(meta).uuid; + if (this.emissiveMap && this.emissiveMap.isTexture) + data2.emissiveMap = this.emissiveMap.toJSON(meta).uuid; + if (this.specularMap && this.specularMap.isTexture) + data2.specularMap = this.specularMap.toJSON(meta).uuid; + if (this.specularIntensityMap && this.specularIntensityMap.isTexture) + data2.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid; + if (this.specularColorMap && this.specularColorMap.isTexture) + data2.specularColorMap = this.specularColorMap.toJSON(meta).uuid; + if (this.envMap && this.envMap.isTexture) { + data2.envMap = this.envMap.toJSON(meta).uuid; + if (this.combine !== undefined) + data2.combine = this.combine; + } + if (this.envMapRotation !== undefined) + data2.envMapRotation = this.envMapRotation.toArray(); + if (this.envMapIntensity !== undefined) + data2.envMapIntensity = this.envMapIntensity; + if (this.reflectivity !== undefined) + data2.reflectivity = this.reflectivity; + if (this.refractionRatio !== undefined) + data2.refractionRatio = this.refractionRatio; + if (this.gradientMap && this.gradientMap.isTexture) { + data2.gradientMap = this.gradientMap.toJSON(meta).uuid; + } + if (this.transmission !== undefined) + data2.transmission = this.transmission; + if (this.transmissionMap && this.transmissionMap.isTexture) + data2.transmissionMap = this.transmissionMap.toJSON(meta).uuid; + if (this.thickness !== undefined) + data2.thickness = this.thickness; + if (this.thicknessMap && this.thicknessMap.isTexture) + data2.thicknessMap = this.thicknessMap.toJSON(meta).uuid; + if (this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity) + data2.attenuationDistance = this.attenuationDistance; + if (this.attenuationColor !== undefined) + data2.attenuationColor = this.attenuationColor.getHex(); + if (this.size !== undefined) + data2.size = this.size; + if (this.shadowSide !== null) + data2.shadowSide = this.shadowSide; + if (this.sizeAttenuation !== undefined) + data2.sizeAttenuation = this.sizeAttenuation; + if (this.blending !== NormalBlending2) + data2.blending = this.blending; + if (this.side !== FrontSide2) + data2.side = this.side; + if (this.vertexColors === true) + data2.vertexColors = true; + if (this.opacity < 1) + data2.opacity = this.opacity; + if (this.transparent === true) + data2.transparent = true; + if (this.blendSrc !== SrcAlphaFactor2) + data2.blendSrc = this.blendSrc; + if (this.blendDst !== OneMinusSrcAlphaFactor2) + data2.blendDst = this.blendDst; + if (this.blendEquation !== AddEquation2) + data2.blendEquation = this.blendEquation; + if (this.blendSrcAlpha !== null) + data2.blendSrcAlpha = this.blendSrcAlpha; + if (this.blendDstAlpha !== null) + data2.blendDstAlpha = this.blendDstAlpha; + if (this.blendEquationAlpha !== null) + data2.blendEquationAlpha = this.blendEquationAlpha; + if (this.blendColor && this.blendColor.isColor) + data2.blendColor = this.blendColor.getHex(); + if (this.blendAlpha !== 0) + data2.blendAlpha = this.blendAlpha; + if (this.depthFunc !== LessEqualDepth2) + data2.depthFunc = this.depthFunc; + if (this.depthTest === false) + data2.depthTest = this.depthTest; + if (this.depthWrite === false) + data2.depthWrite = this.depthWrite; + if (this.colorWrite === false) + data2.colorWrite = this.colorWrite; + if (this.stencilWriteMask !== 255) + data2.stencilWriteMask = this.stencilWriteMask; + if (this.stencilFunc !== AlwaysStencilFunc2) + data2.stencilFunc = this.stencilFunc; + if (this.stencilRef !== 0) + data2.stencilRef = this.stencilRef; + if (this.stencilFuncMask !== 255) + data2.stencilFuncMask = this.stencilFuncMask; + if (this.stencilFail !== KeepStencilOp2) + data2.stencilFail = this.stencilFail; + if (this.stencilZFail !== KeepStencilOp2) + data2.stencilZFail = this.stencilZFail; + if (this.stencilZPass !== KeepStencilOp2) + data2.stencilZPass = this.stencilZPass; + if (this.stencilWrite === true) + data2.stencilWrite = this.stencilWrite; + if (this.rotation !== undefined && this.rotation !== 0) + data2.rotation = this.rotation; + if (this.polygonOffset === true) + data2.polygonOffset = true; + if (this.polygonOffsetFactor !== 0) + data2.polygonOffsetFactor = this.polygonOffsetFactor; + if (this.polygonOffsetUnits !== 0) + data2.polygonOffsetUnits = this.polygonOffsetUnits; + if (this.linewidth !== undefined && this.linewidth !== 1) + data2.linewidth = this.linewidth; + if (this.dashSize !== undefined) + data2.dashSize = this.dashSize; + if (this.gapSize !== undefined) + data2.gapSize = this.gapSize; + if (this.scale !== undefined) + data2.scale = this.scale; + if (this.dithering === true) + data2.dithering = true; + if (this.alphaTest > 0) + data2.alphaTest = this.alphaTest; + if (this.alphaHash === true) + data2.alphaHash = true; + if (this.alphaToCoverage === true) + data2.alphaToCoverage = true; + if (this.premultipliedAlpha === true) + data2.premultipliedAlpha = true; + if (this.forceSinglePass === true) + data2.forceSinglePass = true; + if (this.wireframe === true) + data2.wireframe = true; + if (this.wireframeLinewidth > 1) + data2.wireframeLinewidth = this.wireframeLinewidth; + if (this.wireframeLinecap !== "round") + data2.wireframeLinecap = this.wireframeLinecap; + if (this.wireframeLinejoin !== "round") + data2.wireframeLinejoin = this.wireframeLinejoin; + if (this.flatShading === true) + data2.flatShading = true; + if (this.visible === false) + data2.visible = false; + if (this.toneMapped === false) + data2.toneMapped = false; + if (this.fog === false) + data2.fog = false; + if (Object.keys(this.userData).length > 0) + data2.userData = this.userData; + function extractFromCache(cache) { + const values2 = []; + for (const key2 in cache) { + const data3 = cache[key2]; + delete data3.metadata; + values2.push(data3); + } + return values2; + } + if (isRootObject) { + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + if (textures.length > 0) + data2.textures = textures; + if (images.length > 0) + data2.images = images; + } + return data2; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + this.opacity = source.opacity; + this.transparent = source.transparent; + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + this.blendColor.copy(source.blendColor); + this.blendAlpha = source.blendAlpha; + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + if (srcPlanes !== null) { + const n = srcPlanes.length; + dstPlanes = new Array(n); + for (let i = 0;i !== n; ++i) { + dstPlanes[i] = srcPlanes[i].clone(); + } + } + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + this.shadowSide = source.shadowSide; + this.colorWrite = source.colorWrite; + this.precision = source.precision; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + this.dithering = source.dithering; + this.alphaTest = source.alphaTest; + this.alphaHash = source.alphaHash; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + this.forceSinglePass = source.forceSinglePass; + this.visible = source.visible; + this.toneMapped = source.toneMapped; + this.userData = JSON.parse(JSON.stringify(source.userData)); + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + onBuild() { + console.warn("Material: onBuild() has been removed."); + } + } + + class MeshBasicMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshBasicMaterial = true; + this.type = "MeshBasicMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler2; + this.combine = MultiplyOperation2; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } + } + var _tables2 = /* @__PURE__ */ _generateTables2(); + function _generateTables2() { + const buffer = new ArrayBuffer(4); + const floatView = new Float32Array(buffer); + const uint32View = new Uint32Array(buffer); + const baseTable = new Uint32Array(512); + const shiftTable = new Uint32Array(512); + for (let i = 0;i < 256; ++i) { + const e = i - 127; + if (e < -27) { + baseTable[i] = 0; + baseTable[i | 256] = 32768; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else if (e < -14) { + baseTable[i] = 1024 >> -e - 14; + baseTable[i | 256] = 1024 >> -e - 14 | 32768; + shiftTable[i] = -e - 1; + shiftTable[i | 256] = -e - 1; + } else if (e <= 15) { + baseTable[i] = e + 15 << 10; + baseTable[i | 256] = e + 15 << 10 | 32768; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } else if (e < 128) { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } + } + const mantissaTable = new Uint32Array(2048); + const exponentTable = new Uint32Array(64); + const offsetTable = new Uint32Array(64); + for (let i = 1;i < 1024; ++i) { + let m = i << 13; + let e = 0; + while ((m & 8388608) === 0) { + m <<= 1; + e -= 8388608; + } + m &= ~8388608; + e += 947912704; + mantissaTable[i] = m | e; + } + for (let i = 1024;i < 2048; ++i) { + mantissaTable[i] = 939524096 + (i - 1024 << 13); + } + for (let i = 1;i < 31; ++i) { + exponentTable[i] = i << 23; + } + exponentTable[31] = 1199570944; + exponentTable[32] = 2147483648; + for (let i = 33;i < 63; ++i) { + exponentTable[i] = 2147483648 + (i - 32 << 23); + } + exponentTable[63] = 3347054592; + for (let i = 1;i < 64; ++i) { + if (i !== 32) { + offsetTable[i] = 1024; + } + } + return { + floatView, + uint32View, + baseTable, + shiftTable, + mantissaTable, + exponentTable, + offsetTable + }; + } + function toHalfFloat2(val2) { + if (Math.abs(val2) > 65504) + console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."); + val2 = clamp3(val2, -65504, 65504); + _tables2.floatView[0] = val2; + const f = _tables2.uint32View[0]; + const e = f >> 23 & 511; + return _tables2.baseTable[e] + ((f & 8388607) >> _tables2.shiftTable[e]); + } + function fromHalfFloat2(val2) { + const m = val2 >> 10; + _tables2.uint32View[0] = _tables2.mantissaTable[_tables2.offsetTable[m] + (val2 & 1023)] + _tables2.exponentTable[m]; + return _tables2.floatView[0]; + } + var DataUtils2 = { + toHalfFloat: toHalfFloat2, + fromHalfFloat: fromHalfFloat2 + }; + var _vector$92 = /* @__PURE__ */ new Vector32; + var _vector2$12 = /* @__PURE__ */ new Vector22; + var _id$3 = 0; + + class BufferAttribute2 { + constructor(array, itemSize, normalized = false) { + if (Array.isArray(array)) { + throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); + } + this.isBufferAttribute = true; + Object.defineProperty(this, "id", { value: _id$3++ }); + this.name = ""; + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized; + this.usage = StaticDrawUsage2; + this.updateRanges = []; + this.gpuType = FloatType2; + this.version = 0; + } + onUploadCallback() { + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setUsage(value2) { + this.usage = value2; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.name = source.name; + this.array = new source.array.constructor(source.array); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + this.usage = source.usage; + this.gpuType = source.gpuType; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.itemSize; + index2 *= attribute.itemSize; + for (let i = 0, l = this.itemSize;i < l; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + copyArray(array) { + this.array.set(array); + return this; + } + applyMatrix3(m) { + if (this.itemSize === 2) { + for (let i = 0, l = this.count;i < l; i++) { + _vector2$12.fromBufferAttribute(this, i); + _vector2$12.applyMatrix3(m); + this.setXY(i, _vector2$12.x, _vector2$12.y); + } + } else if (this.itemSize === 3) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$92.fromBufferAttribute(this, i); + _vector$92.applyMatrix3(m); + this.setXYZ(i, _vector$92.x, _vector$92.y, _vector$92.z); + } + } + return this; + } + applyMatrix4(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$92.fromBufferAttribute(this, i); + _vector$92.applyMatrix4(m); + this.setXYZ(i, _vector$92.x, _vector$92.y, _vector$92.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$92.fromBufferAttribute(this, i); + _vector$92.applyNormalMatrix(m); + this.setXYZ(i, _vector$92.x, _vector$92.y, _vector$92.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$92.fromBufferAttribute(this, i); + _vector$92.transformDirection(m); + this.setXYZ(i, _vector$92.x, _vector$92.y, _vector$92.z); + } + return this; + } + set(value2, offset = 0) { + this.array.set(value2, offset); + return this; + } + getComponent(index2, component) { + let value2 = this.array[index2 * this.itemSize + component]; + if (this.normalized) + value2 = denormalize2(value2, this.array); + return value2; + } + setComponent(index2, component, value2) { + if (this.normalized) + value2 = normalize3(value2, this.array); + this.array[index2 * this.itemSize + component] = value2; + return this; + } + getX(index2) { + let x = this.array[index2 * this.itemSize]; + if (this.normalized) + x = denormalize2(x, this.array); + return x; + } + setX(index2, x) { + if (this.normalized) + x = normalize3(x, this.array); + this.array[index2 * this.itemSize] = x; + return this; + } + getY(index2) { + let y = this.array[index2 * this.itemSize + 1]; + if (this.normalized) + y = denormalize2(y, this.array); + return y; + } + setY(index2, y) { + if (this.normalized) + y = normalize3(y, this.array); + this.array[index2 * this.itemSize + 1] = y; + return this; + } + getZ(index2) { + let z = this.array[index2 * this.itemSize + 2]; + if (this.normalized) + z = denormalize2(z, this.array); + return z; + } + setZ(index2, z) { + if (this.normalized) + z = normalize3(z, this.array); + this.array[index2 * this.itemSize + 2] = z; + return this; + } + getW(index2) { + let w = this.array[index2 * this.itemSize + 3]; + if (this.normalized) + w = denormalize2(w, this.array); + return w; + } + setW(index2, w) { + if (this.normalized) + w = normalize3(w, this.array); + this.array[index2 * this.itemSize + 3] = w; + return this; + } + setXY(index2, x, y) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize3(x, this.array); + y = normalize3(y, this.array); + } + this.array[index2 + 0] = x; + this.array[index2 + 1] = y; + return this; + } + setXYZ(index2, x, y, z) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize3(x, this.array); + y = normalize3(y, this.array); + z = normalize3(z, this.array); + } + this.array[index2 + 0] = x; + this.array[index2 + 1] = y; + this.array[index2 + 2] = z; + return this; + } + setXYZW(index2, x, y, z, w) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize3(x, this.array); + y = normalize3(y, this.array); + z = normalize3(z, this.array); + w = normalize3(w, this.array); + } + this.array[index2 + 0] = x; + this.array[index2 + 1] = y; + this.array[index2 + 2] = z; + this.array[index2 + 3] = w; + return this; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + clone() { + return new this.constructor(this.array, this.itemSize).copy(this); + } + toJSON() { + const data2 = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from(this.array), + normalized: this.normalized + }; + if (this.name !== "") + data2.name = this.name; + if (this.usage !== StaticDrawUsage2) + data2.usage = this.usage; + return data2; + } + } + + class Int8BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Int8Array(array), itemSize, normalized); + } + } + + class Uint8BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint8Array(array), itemSize, normalized); + } + } + + class Uint8ClampedBufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint8ClampedArray(array), itemSize, normalized); + } + } + + class Int16BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Int16Array(array), itemSize, normalized); + } + } + + class Uint16BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + } + } + + class Int32BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Int32Array(array), itemSize, normalized); + } + } + + class Uint32BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint32Array(array), itemSize, normalized); + } + } + + class Float16BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + this.isFloat16BufferAttribute = true; + } + getX(index2) { + let x = fromHalfFloat2(this.array[index2 * this.itemSize]); + if (this.normalized) + x = denormalize2(x, this.array); + return x; + } + setX(index2, x) { + if (this.normalized) + x = normalize3(x, this.array); + this.array[index2 * this.itemSize] = toHalfFloat2(x); + return this; + } + getY(index2) { + let y = fromHalfFloat2(this.array[index2 * this.itemSize + 1]); + if (this.normalized) + y = denormalize2(y, this.array); + return y; + } + setY(index2, y) { + if (this.normalized) + y = normalize3(y, this.array); + this.array[index2 * this.itemSize + 1] = toHalfFloat2(y); + return this; + } + getZ(index2) { + let z = fromHalfFloat2(this.array[index2 * this.itemSize + 2]); + if (this.normalized) + z = denormalize2(z, this.array); + return z; + } + setZ(index2, z) { + if (this.normalized) + z = normalize3(z, this.array); + this.array[index2 * this.itemSize + 2] = toHalfFloat2(z); + return this; + } + getW(index2) { + let w = fromHalfFloat2(this.array[index2 * this.itemSize + 3]); + if (this.normalized) + w = denormalize2(w, this.array); + return w; + } + setW(index2, w) { + if (this.normalized) + w = normalize3(w, this.array); + this.array[index2 * this.itemSize + 3] = toHalfFloat2(w); + return this; + } + setXY(index2, x, y) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize3(x, this.array); + y = normalize3(y, this.array); + } + this.array[index2 + 0] = toHalfFloat2(x); + this.array[index2 + 1] = toHalfFloat2(y); + return this; + } + setXYZ(index2, x, y, z) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize3(x, this.array); + y = normalize3(y, this.array); + z = normalize3(z, this.array); + } + this.array[index2 + 0] = toHalfFloat2(x); + this.array[index2 + 1] = toHalfFloat2(y); + this.array[index2 + 2] = toHalfFloat2(z); + return this; + } + setXYZW(index2, x, y, z, w) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize3(x, this.array); + y = normalize3(y, this.array); + z = normalize3(z, this.array); + w = normalize3(w, this.array); + } + this.array[index2 + 0] = toHalfFloat2(x); + this.array[index2 + 1] = toHalfFloat2(y); + this.array[index2 + 2] = toHalfFloat2(z); + this.array[index2 + 3] = toHalfFloat2(w); + return this; + } + } + + class Float32BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Float32Array(array), itemSize, normalized); + } + } + var _id$22 = 0; + var _m1$22 = /* @__PURE__ */ new Matrix42; + var _obj2 = /* @__PURE__ */ new Object3D2; + var _offset2 = /* @__PURE__ */ new Vector32; + var _box$22 = /* @__PURE__ */ new Box32; + var _boxMorphTargets2 = /* @__PURE__ */ new Box32; + var _vector$82 = /* @__PURE__ */ new Vector32; + + class BufferGeometry2 extends EventDispatcher2 { + constructor() { + super(); + this.isBufferGeometry = true; + Object.defineProperty(this, "id", { value: _id$22++ }); + this.uuid = generateUUID2(); + this.name = ""; + this.type = "BufferGeometry"; + this.index = null; + this.indirect = null; + this.attributes = {}; + this.morphAttributes = {}; + this.morphTargetsRelative = false; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + this.drawRange = { start: 0, count: Infinity }; + this.userData = {}; + } + getIndex() { + return this.index; + } + setIndex(index2) { + if (Array.isArray(index2)) { + this.index = new ((arrayNeedsUint322(index2)) ? Uint32BufferAttribute2 : Uint16BufferAttribute2)(index2, 1); + } else { + this.index = index2; + } + return this; + } + setIndirect(indirect) { + this.indirect = indirect; + return this; + } + getIndirect() { + return this.indirect; + } + getAttribute(name2) { + return this.attributes[name2]; + } + setAttribute(name2, attribute) { + this.attributes[name2] = attribute; + return this; + } + deleteAttribute(name2) { + delete this.attributes[name2]; + return this; + } + hasAttribute(name2) { + return this.attributes[name2] !== undefined; + } + addGroup(start, count, materialIndex = 0) { + this.groups.push({ + start, + count, + materialIndex + }); + } + clearGroups() { + this.groups = []; + } + setDrawRange(start, count) { + this.drawRange.start = start; + this.drawRange.count = count; + } + applyMatrix4(matrix) { + const position2 = this.attributes.position; + if (position2 !== undefined) { + position2.applyMatrix4(matrix); + position2.needsUpdate = true; + } + const normal = this.attributes.normal; + if (normal !== undefined) { + const normalMatrix = new Matrix32().getNormalMatrix(matrix); + normal.applyNormalMatrix(normalMatrix); + normal.needsUpdate = true; + } + const tangent = this.attributes.tangent; + if (tangent !== undefined) { + tangent.transformDirection(matrix); + tangent.needsUpdate = true; + } + if (this.boundingBox !== null) { + this.computeBoundingBox(); + } + if (this.boundingSphere !== null) { + this.computeBoundingSphere(); + } + return this; + } + applyQuaternion(q) { + _m1$22.makeRotationFromQuaternion(q); + this.applyMatrix4(_m1$22); + return this; + } + rotateX(angle) { + _m1$22.makeRotationX(angle); + this.applyMatrix4(_m1$22); + return this; + } + rotateY(angle) { + _m1$22.makeRotationY(angle); + this.applyMatrix4(_m1$22); + return this; + } + rotateZ(angle) { + _m1$22.makeRotationZ(angle); + this.applyMatrix4(_m1$22); + return this; + } + translate(x, y, z) { + _m1$22.makeTranslation(x, y, z); + this.applyMatrix4(_m1$22); + return this; + } + scale(x, y, z) { + _m1$22.makeScale(x, y, z); + this.applyMatrix4(_m1$22); + return this; + } + lookAt(vector) { + _obj2.lookAt(vector); + _obj2.updateMatrix(); + this.applyMatrix4(_obj2.matrix); + return this; + } + center() { + this.computeBoundingBox(); + this.boundingBox.getCenter(_offset2).negate(); + this.translate(_offset2.x, _offset2.y, _offset2.z); + return this; + } + setFromPoints(points) { + const positionAttribute = this.getAttribute("position"); + if (positionAttribute === undefined) { + const position2 = []; + for (let i = 0, l = points.length;i < l; i++) { + const point = points[i]; + position2.push(point.x, point.y, point.z || 0); + } + this.setAttribute("position", new Float32BufferAttribute2(position2, 3)); + } else { + const l = Math.min(points.length, positionAttribute.count); + for (let i = 0;i < l; i++) { + const point = points[i]; + positionAttribute.setXYZ(i, point.x, point.y, point.z || 0); + } + if (points.length > positionAttribute.count) { + console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."); + } + positionAttribute.needsUpdate = true; + } + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box32; + } + const position2 = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position2 && position2.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this); + this.boundingBox.set(new Vector32(-Infinity, -Infinity, -Infinity), new Vector32(Infinity, Infinity, Infinity)); + return; + } + if (position2 !== undefined) { + this.boundingBox.setFromBufferAttribute(position2); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _box$22.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$82.addVectors(this.boundingBox.min, _box$22.min); + this.boundingBox.expandByPoint(_vector$82); + _vector$82.addVectors(this.boundingBox.max, _box$22.max); + this.boundingBox.expandByPoint(_vector$82); + } else { + this.boundingBox.expandByPoint(_box$22.min); + this.boundingBox.expandByPoint(_box$22.max); + } + } + } + } else { + this.boundingBox.makeEmpty(); + } + if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) { + console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere2; + } + const position2 = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position2 && position2.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this); + this.boundingSphere.set(new Vector32, Infinity); + return; + } + if (position2) { + const center = this.boundingSphere.center; + _box$22.setFromBufferAttribute(position2); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _boxMorphTargets2.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$82.addVectors(_box$22.min, _boxMorphTargets2.min); + _box$22.expandByPoint(_vector$82); + _vector$82.addVectors(_box$22.max, _boxMorphTargets2.max); + _box$22.expandByPoint(_vector$82); + } else { + _box$22.expandByPoint(_boxMorphTargets2.min); + _box$22.expandByPoint(_boxMorphTargets2.max); + } + } + } + _box$22.getCenter(center); + let maxRadiusSq = 0; + for (let i = 0, il = position2.count;i < il; i++) { + _vector$82.fromBufferAttribute(position2, i); + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$82)); + } + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + const morphTargetsRelative = this.morphTargetsRelative; + for (let j = 0, jl = morphAttribute.count;j < jl; j++) { + _vector$82.fromBufferAttribute(morphAttribute, j); + if (morphTargetsRelative) { + _offset2.fromBufferAttribute(position2, j); + _vector$82.add(_offset2); + } + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$82)); + } + } + } + this.boundingSphere.radius = Math.sqrt(maxRadiusSq); + if (isNaN(this.boundingSphere.radius)) { + console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); + } + } + } + computeTangents() { + const index2 = this.index; + const attributes = this.attributes; + if (index2 === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) { + console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); + return; + } + const positionAttribute = attributes.position; + const normalAttribute = attributes.normal; + const uvAttribute = attributes.uv; + if (this.hasAttribute("tangent") === false) { + this.setAttribute("tangent", new BufferAttribute2(new Float32Array(4 * positionAttribute.count), 4)); + } + const tangentAttribute = this.getAttribute("tangent"); + const tan1 = [], tan2 = []; + for (let i = 0;i < positionAttribute.count; i++) { + tan1[i] = new Vector32; + tan2[i] = new Vector32; + } + const vA = new Vector32, vB = new Vector32, vC = new Vector32, uvA = new Vector22, uvB = new Vector22, uvC = new Vector22, sdir = new Vector32, tdir = new Vector32; + function handleTriangle(a, b, c) { + vA.fromBufferAttribute(positionAttribute, a); + vB.fromBufferAttribute(positionAttribute, b); + vC.fromBufferAttribute(positionAttribute, c); + uvA.fromBufferAttribute(uvAttribute, a); + uvB.fromBufferAttribute(uvAttribute, b); + uvC.fromBufferAttribute(uvAttribute, c); + vB.sub(vA); + vC.sub(vA); + uvB.sub(uvA); + uvC.sub(uvA); + const r = 1 / (uvB.x * uvC.y - uvC.x * uvB.y); + if (!isFinite(r)) + return; + sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r); + tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r); + tan1[a].add(sdir); + tan1[b].add(sdir); + tan1[c].add(sdir); + tan2[a].add(tdir); + tan2[b].add(tdir); + tan2[c].add(tdir); + } + let groups = this.groups; + if (groups.length === 0) { + groups = [{ + start: 0, + count: index2.count + }]; + } + for (let i = 0, il = groups.length;i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j = start, jl = start + count;j < jl; j += 3) { + handleTriangle(index2.getX(j + 0), index2.getX(j + 1), index2.getX(j + 2)); + } + } + const tmp3 = new Vector32, tmp22 = new Vector32; + const n = new Vector32, n2 = new Vector32; + function handleVertex(v) { + n.fromBufferAttribute(normalAttribute, v); + n2.copy(n); + const t = tan1[v]; + tmp3.copy(t); + tmp3.sub(n.multiplyScalar(n.dot(t))).normalize(); + tmp22.crossVectors(n2, t); + const test = tmp22.dot(tan2[v]); + const w = test < 0 ? -1 : 1; + tangentAttribute.setXYZW(v, tmp3.x, tmp3.y, tmp3.z, w); + } + for (let i = 0, il = groups.length;i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j = start, jl = start + count;j < jl; j += 3) { + handleVertex(index2.getX(j + 0)); + handleVertex(index2.getX(j + 1)); + handleVertex(index2.getX(j + 2)); + } + } + } + computeVertexNormals() { + const index2 = this.index; + const positionAttribute = this.getAttribute("position"); + if (positionAttribute !== undefined) { + let normalAttribute = this.getAttribute("normal"); + if (normalAttribute === undefined) { + normalAttribute = new BufferAttribute2(new Float32Array(positionAttribute.count * 3), 3); + this.setAttribute("normal", normalAttribute); + } else { + for (let i = 0, il = normalAttribute.count;i < il; i++) { + normalAttribute.setXYZ(i, 0, 0, 0); + } + } + const pA = new Vector32, pB = new Vector32, pC = new Vector32; + const nA = new Vector32, nB = new Vector32, nC = new Vector32; + const cb = new Vector32, ab = new Vector32; + if (index2) { + for (let i = 0, il = index2.count;i < il; i += 3) { + const vA = index2.getX(i + 0); + const vB = index2.getX(i + 1); + const vC = index2.getX(i + 2); + pA.fromBufferAttribute(positionAttribute, vA); + pB.fromBufferAttribute(positionAttribute, vB); + pC.fromBufferAttribute(positionAttribute, vC); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + nA.fromBufferAttribute(normalAttribute, vA); + nB.fromBufferAttribute(normalAttribute, vB); + nC.fromBufferAttribute(normalAttribute, vC); + nA.add(cb); + nB.add(cb); + nC.add(cb); + normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z); + normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z); + normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z); + } + } else { + for (let i = 0, il = positionAttribute.count;i < il; i += 3) { + pA.fromBufferAttribute(positionAttribute, i + 0); + pB.fromBufferAttribute(positionAttribute, i + 1); + pC.fromBufferAttribute(positionAttribute, i + 2); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z); + } + } + this.normalizeNormals(); + normalAttribute.needsUpdate = true; + } + } + normalizeNormals() { + const normals = this.attributes.normal; + for (let i = 0, il = normals.count;i < il; i++) { + _vector$82.fromBufferAttribute(normals, i); + _vector$82.normalize(); + normals.setXYZ(i, _vector$82.x, _vector$82.y, _vector$82.z); + } + } + toNonIndexed() { + function convertBufferAttribute(attribute, indices2) { + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + const array2 = new array.constructor(indices2.length * itemSize); + let index2 = 0, index22 = 0; + for (let i = 0, l = indices2.length;i < l; i++) { + if (attribute.isInterleavedBufferAttribute) { + index2 = indices2[i] * attribute.data.stride + attribute.offset; + } else { + index2 = indices2[i] * itemSize; + } + for (let j = 0;j < itemSize; j++) { + array2[index22++] = array[index2++]; + } + } + return new BufferAttribute2(array2, itemSize, normalized); + } + if (this.index === null) { + console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."); + return this; + } + const geometry2 = new BufferGeometry2; + const indices = this.index.array; + const attributes = this.attributes; + for (const name2 in attributes) { + const attribute = attributes[name2]; + const newAttribute = convertBufferAttribute(attribute, indices); + geometry2.setAttribute(name2, newAttribute); + } + const morphAttributes = this.morphAttributes; + for (const name2 in morphAttributes) { + const morphArray = []; + const morphAttribute = morphAttributes[name2]; + for (let i = 0, il = morphAttribute.length;i < il; i++) { + const attribute = morphAttribute[i]; + const newAttribute = convertBufferAttribute(attribute, indices); + morphArray.push(newAttribute); + } + geometry2.morphAttributes[name2] = morphArray; + } + geometry2.morphTargetsRelative = this.morphTargetsRelative; + const groups = this.groups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + geometry2.addGroup(group.start, group.count, group.materialIndex); + } + return geometry2; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "BufferGeometry", + generator: "BufferGeometry.toJSON" + } + }; + data2.uuid = this.uuid; + data2.type = this.type; + if (this.name !== "") + data2.name = this.name; + if (Object.keys(this.userData).length > 0) + data2.userData = this.userData; + if (this.parameters !== undefined) { + const parameters = this.parameters; + for (const key2 in parameters) { + if (parameters[key2] !== undefined) + data2[key2] = parameters[key2]; + } + return data2; + } + data2.data = { attributes: {} }; + const index2 = this.index; + if (index2 !== null) { + data2.data.index = { + type: index2.array.constructor.name, + array: Array.prototype.slice.call(index2.array) + }; + } + const attributes = this.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + data2.data.attributes[key2] = attribute.toJSON(data2.data); + } + const morphAttributes = {}; + let hasMorphAttributes = false; + for (const key2 in this.morphAttributes) { + const attributeArray = this.morphAttributes[key2]; + const array = []; + for (let i = 0, il = attributeArray.length;i < il; i++) { + const attribute = attributeArray[i]; + array.push(attribute.toJSON(data2.data)); + } + if (array.length > 0) { + morphAttributes[key2] = array; + hasMorphAttributes = true; + } + } + if (hasMorphAttributes) { + data2.data.morphAttributes = morphAttributes; + data2.data.morphTargetsRelative = this.morphTargetsRelative; + } + const groups = this.groups; + if (groups.length > 0) { + data2.data.groups = JSON.parse(JSON.stringify(groups)); + } + const boundingSphere = this.boundingSphere; + if (boundingSphere !== null) { + data2.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; + } + return data2; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + const data2 = {}; + this.name = source.name; + const index2 = source.index; + if (index2 !== null) { + this.setIndex(index2.clone(data2)); + } + const attributes = source.attributes; + for (const name2 in attributes) { + const attribute = attributes[name2]; + this.setAttribute(name2, attribute.clone(data2)); + } + const morphAttributes = source.morphAttributes; + for (const name2 in morphAttributes) { + const array = []; + const morphAttribute = morphAttributes[name2]; + for (let i = 0, l = morphAttribute.length;i < l; i++) { + array.push(morphAttribute[i].clone(data2)); + } + this.morphAttributes[name2] = array; + } + this.morphTargetsRelative = source.morphTargetsRelative; + const groups = source.groups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + this.addGroup(group.start, group.count, group.materialIndex); + } + const boundingBox = source.boundingBox; + if (boundingBox !== null) { + this.boundingBox = boundingBox.clone(); + } + const boundingSphere = source.boundingSphere; + if (boundingSphere !== null) { + this.boundingSphere = boundingSphere.clone(); + } + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + this.userData = source.userData; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + } + var _inverseMatrix$32 = /* @__PURE__ */ new Matrix42; + var _ray$32 = /* @__PURE__ */ new Ray2; + var _sphere$62 = /* @__PURE__ */ new Sphere2; + var _sphereHitAt2 = /* @__PURE__ */ new Vector32; + var _vA$12 = /* @__PURE__ */ new Vector32; + var _vB$12 = /* @__PURE__ */ new Vector32; + var _vC$12 = /* @__PURE__ */ new Vector32; + var _tempA2 = /* @__PURE__ */ new Vector32; + var _morphA2 = /* @__PURE__ */ new Vector32; + var _intersectionPoint2 = /* @__PURE__ */ new Vector32; + var _intersectionPointWorld2 = /* @__PURE__ */ new Vector32; + + class Mesh2 extends Object3D2 { + constructor(geometry = new BufferGeometry2, material = new MeshBasicMaterial2) { + super(); + this.isMesh = true; + this.type = "Mesh"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.morphTargetInfluences !== undefined) { + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + } + if (source.morphTargetDictionary !== undefined) { + this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary); + } + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } + getVertexPosition(index2, target) { + const geometry = this.geometry; + const position2 = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + target.fromBufferAttribute(position2, index2); + const morphInfluences = this.morphTargetInfluences; + if (morphPosition && morphInfluences) { + _morphA2.set(0, 0, 0); + for (let i = 0, il = morphPosition.length;i < il; i++) { + const influence = morphInfluences[i]; + const morphAttribute = morphPosition[i]; + if (influence === 0) + continue; + _tempA2.fromBufferAttribute(morphAttribute, index2); + if (morphTargetsRelative) { + _morphA2.addScaledVector(_tempA2, influence); + } else { + _morphA2.addScaledVector(_tempA2.sub(target), influence); + } + } + target.add(_morphA2); + } + return target; + } + raycast(raycaster, intersects3) { + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === undefined) + return; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$62.copy(geometry.boundingSphere); + _sphere$62.applyMatrix4(matrixWorld); + _ray$32.copy(raycaster.ray).recast(raycaster.near); + if (_sphere$62.containsPoint(_ray$32.origin) === false) { + if (_ray$32.intersectSphere(_sphere$62, _sphereHitAt2) === null) + return; + if (_ray$32.origin.distanceToSquared(_sphereHitAt2) > (raycaster.far - raycaster.near) ** 2) + return; + } + _inverseMatrix$32.copy(matrixWorld).invert(); + _ray$32.copy(raycaster.ray).applyMatrix4(_inverseMatrix$32); + if (geometry.boundingBox !== null) { + if (_ray$32.intersectsBox(geometry.boundingBox) === false) + return; + } + this._computeIntersections(raycaster, intersects3, _ray$32); + } + _computeIntersections(raycaster, intersects3, rayLocalSpace) { + let intersection; + const geometry = this.geometry; + const material = this.material; + const index2 = geometry.index; + const position2 = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv1 = geometry.attributes.uv1; + const normal = geometry.attributes.normal; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + if (index2 !== null) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length;i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(index2.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j = start, jl = end;j < jl; j += 3) { + const a = index2.getX(j); + const b = index2.getX(j + 1); + const c = index2.getX(j + 2); + intersection = checkGeometryIntersection2(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(j / 3); + intersection.face.materialIndex = group.materialIndex; + intersects3.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i += 3) { + const a = index2.getX(i); + const b = index2.getX(i + 1); + const c = index2.getX(i + 2); + intersection = checkGeometryIntersection2(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects3.push(intersection); + } + } + } + } else if (position2 !== undefined) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length;i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(position2.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j = start, jl = end;j < jl; j += 3) { + const a = j; + const b = j + 1; + const c = j + 2; + intersection = checkGeometryIntersection2(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(j / 3); + intersection.face.materialIndex = group.materialIndex; + intersects3.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(position2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i += 3) { + const a = i; + const b = i + 1; + const c = i + 2; + intersection = checkGeometryIntersection2(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects3.push(intersection); + } + } + } + } + } + } + function checkIntersection$12(object, material, raycaster, ray, pA, pB, pC, point) { + let intersect3; + if (material.side === BackSide2) { + intersect3 = ray.intersectTriangle(pC, pB, pA, true, point); + } else { + intersect3 = ray.intersectTriangle(pA, pB, pC, material.side === FrontSide2, point); + } + if (intersect3 === null) + return null; + _intersectionPointWorld2.copy(point); + _intersectionPointWorld2.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld2); + if (distance < raycaster.near || distance > raycaster.far) + return null; + return { + distance, + point: _intersectionPointWorld2.clone(), + object + }; + } + function checkGeometryIntersection2(object, material, raycaster, ray, uv, uv1, normal, a, b, c) { + object.getVertexPosition(a, _vA$12); + object.getVertexPosition(b, _vB$12); + object.getVertexPosition(c, _vC$12); + const intersection = checkIntersection$12(object, material, raycaster, ray, _vA$12, _vB$12, _vC$12, _intersectionPoint2); + if (intersection) { + const barycoord = new Vector32; + Triangle2.getBarycoord(_intersectionPoint2, _vA$12, _vB$12, _vC$12, barycoord); + if (uv) { + intersection.uv = Triangle2.getInterpolatedAttribute(uv, a, b, c, barycoord, new Vector22); + } + if (uv1) { + intersection.uv1 = Triangle2.getInterpolatedAttribute(uv1, a, b, c, barycoord, new Vector22); + } + if (normal) { + intersection.normal = Triangle2.getInterpolatedAttribute(normal, a, b, c, barycoord, new Vector32); + if (intersection.normal.dot(ray.direction) > 0) { + intersection.normal.multiplyScalar(-1); + } + } + const face = { + a, + b, + c, + normal: new Vector32, + materialIndex: 0 + }; + Triangle2.getNormal(_vA$12, _vB$12, _vC$12, face.normal); + intersection.face = face; + intersection.barycoord = barycoord; + } + return intersection; + } + + class BoxGeometry2 extends BufferGeometry2 { + constructor(width2 = 1, height2 = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) { + super(); + this.type = "BoxGeometry"; + this.parameters = { + width: width2, + height: height2, + depth, + widthSegments, + heightSegments, + depthSegments + }; + const scope = this; + widthSegments = Math.floor(widthSegments); + heightSegments = Math.floor(heightSegments); + depthSegments = Math.floor(depthSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let numberOfVertices = 0; + let groupStart = 0; + buildPlane("z", "y", "x", -1, -1, depth, height2, width2, depthSegments, heightSegments, 0); + buildPlane("z", "y", "x", 1, -1, depth, height2, -width2, depthSegments, heightSegments, 1); + buildPlane("x", "z", "y", 1, 1, width2, depth, height2, widthSegments, depthSegments, 2); + buildPlane("x", "z", "y", 1, -1, width2, depth, -height2, widthSegments, depthSegments, 3); + buildPlane("x", "y", "z", 1, -1, width2, height2, depth, widthSegments, heightSegments, 4); + buildPlane("x", "y", "z", -1, -1, width2, height2, -depth, widthSegments, heightSegments, 5); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function buildPlane(u, v, w, udir, vdir, width3, height3, depth2, gridX, gridY, materialIndex) { + const segmentWidth = width3 / gridX; + const segmentHeight = height3 / gridY; + const widthHalf = width3 / 2; + const heightHalf = height3 / 2; + const depthHalf = depth2 / 2; + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + let vertexCounter = 0; + let groupCount = 0; + const vector = new Vector32; + for (let iy = 0;iy < gridY1; iy++) { + const y = iy * segmentHeight - heightHalf; + for (let ix = 0;ix < gridX1; ix++) { + const x = ix * segmentWidth - widthHalf; + vector[u] = x * udir; + vector[v] = y * vdir; + vector[w] = depthHalf; + vertices.push(vector.x, vector.y, vector.z); + vector[u] = 0; + vector[v] = 0; + vector[w] = depth2 > 0 ? 1 : -1; + normals.push(vector.x, vector.y, vector.z); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + vertexCounter += 1; + } + } + for (let iy = 0;iy < gridY; iy++) { + for (let ix = 0;ix < gridX; ix++) { + const a = numberOfVertices + ix + gridX1 * iy; + const b = numberOfVertices + ix + gridX1 * (iy + 1); + const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1); + const d = numberOfVertices + (ix + 1) + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + groupCount += 6; + } + } + scope.addGroup(groupStart, groupCount, materialIndex); + groupStart += groupCount; + numberOfVertices += vertexCounter; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new BoxGeometry2(data2.width, data2.height, data2.depth, data2.widthSegments, data2.heightSegments, data2.depthSegments); + } + } + function cloneUniforms2(src) { + const dst = {}; + for (const u in src) { + dst[u] = {}; + for (const p in src[u]) { + const property2 = src[u][p]; + if (property2 && (property2.isColor || property2.isMatrix3 || property2.isMatrix4 || property2.isVector2 || property2.isVector3 || property2.isVector4 || property2.isTexture || property2.isQuaternion)) { + if (property2.isRenderTargetTexture) { + console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."); + dst[u][p] = null; + } else { + dst[u][p] = property2.clone(); + } + } else if (Array.isArray(property2)) { + dst[u][p] = property2.slice(); + } else { + dst[u][p] = property2; + } + } + } + return dst; + } + function mergeUniforms2(uniforms) { + const merged = {}; + for (let u = 0;u < uniforms.length; u++) { + const tmp3 = cloneUniforms2(uniforms[u]); + for (const p in tmp3) { + merged[p] = tmp3[p]; + } + } + return merged; + } + function cloneUniformsGroups2(src) { + const dst = []; + for (let u = 0;u < src.length; u++) { + dst.push(src[u].clone()); + } + return dst; + } + function getUnlitUniformColorSpace2(renderer2) { + const currentRenderTarget = renderer2.getRenderTarget(); + if (currentRenderTarget === null) { + return renderer2.outputColorSpace; + } + if (currentRenderTarget.isXRRenderTarget === true) { + return currentRenderTarget.texture.colorSpace; + } + return ColorManagement2.workingColorSpace; + } + var UniformsUtils2 = { clone: cloneUniforms2, merge: mergeUniforms2 }; + var default_vertex2 = `void main() { + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); +}`; + var default_fragment2 = `void main() { + gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); +}`; + + class ShaderMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isShaderMaterial = true; + this.type = "ShaderMaterial"; + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + this.vertexShader = default_vertex2; + this.fragmentShader = default_fragment2; + this.linewidth = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.fog = false; + this.lights = false; + this.clipping = false; + this.forceSinglePass = true; + this.extensions = { + clipCullDistance: false, + multiDraw: false + }; + this.defaultAttributeValues = { + color: [1, 1, 1], + uv: [0, 0], + uv1: [0, 0] + }; + this.index0AttributeName = undefined; + this.uniformsNeedUpdate = false; + this.glslVersion = null; + if (parameters !== undefined) { + this.setValues(parameters); + } + } + copy(source) { + super.copy(source); + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + this.uniforms = cloneUniforms2(source.uniforms); + this.uniformsGroups = cloneUniformsGroups2(source.uniformsGroups); + this.defines = Object.assign({}, source.defines); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + this.extensions = Object.assign({}, source.extensions); + this.glslVersion = source.glslVersion; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.glslVersion = this.glslVersion; + data2.uniforms = {}; + for (const name2 in this.uniforms) { + const uniform = this.uniforms[name2]; + const value2 = uniform.value; + if (value2 && value2.isTexture) { + data2.uniforms[name2] = { + type: "t", + value: value2.toJSON(meta).uuid + }; + } else if (value2 && value2.isColor) { + data2.uniforms[name2] = { + type: "c", + value: value2.getHex() + }; + } else if (value2 && value2.isVector2) { + data2.uniforms[name2] = { + type: "v2", + value: value2.toArray() + }; + } else if (value2 && value2.isVector3) { + data2.uniforms[name2] = { + type: "v3", + value: value2.toArray() + }; + } else if (value2 && value2.isVector4) { + data2.uniforms[name2] = { + type: "v4", + value: value2.toArray() + }; + } else if (value2 && value2.isMatrix3) { + data2.uniforms[name2] = { + type: "m3", + value: value2.toArray() + }; + } else if (value2 && value2.isMatrix4) { + data2.uniforms[name2] = { + type: "m4", + value: value2.toArray() + }; + } else { + data2.uniforms[name2] = { + value: value2 + }; + } + } + if (Object.keys(this.defines).length > 0) + data2.defines = this.defines; + data2.vertexShader = this.vertexShader; + data2.fragmentShader = this.fragmentShader; + data2.lights = this.lights; + data2.clipping = this.clipping; + const extensions = {}; + for (const key2 in this.extensions) { + if (this.extensions[key2] === true) + extensions[key2] = true; + } + if (Object.keys(extensions).length > 0) + data2.extensions = extensions; + return data2; + } + } + + class Camera2 extends Object3D2 { + constructor() { + super(); + this.isCamera = true; + this.type = "Camera"; + this.matrixWorldInverse = new Matrix42; + this.projectionMatrix = new Matrix42; + this.projectionMatrixInverse = new Matrix42; + this.coordinateSystem = WebGLCoordinateSystem2; + } + copy(source, recursive) { + super.copy(source, recursive); + this.matrixWorldInverse.copy(source.matrixWorldInverse); + this.projectionMatrix.copy(source.projectionMatrix); + this.projectionMatrixInverse.copy(source.projectionMatrixInverse); + this.coordinateSystem = source.coordinateSystem; + return this; + } + getWorldDirection(target) { + return super.getWorldDirection(target).negate(); + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + updateWorldMatrix(updateParents, updateChildren) { + super.updateWorldMatrix(updateParents, updateChildren); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + clone() { + return new this.constructor().copy(this); + } + } + var _v3$12 = /* @__PURE__ */ new Vector32; + var _minTarget2 = /* @__PURE__ */ new Vector22; + var _maxTarget2 = /* @__PURE__ */ new Vector22; + + class PerspectiveCamera2 extends Camera2 { + constructor(fov3 = 50, aspect3 = 1, near = 0.1, far = 2000) { + super(); + this.isPerspectiveCamera = true; + this.type = "PerspectiveCamera"; + this.fov = fov3; + this.zoom = 1; + this.near = near; + this.far = far; + this.focus = 10; + this.aspect = aspect3; + this.view = null; + this.filmGauge = 35; + this.filmOffset = 0; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.fov = source.fov; + this.zoom = source.zoom; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign({}, source.view); + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + return this; + } + setFocalLength(focalLength) { + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + this.fov = RAD2DEG2 * 2 * Math.atan(vExtentSlope); + this.updateProjectionMatrix(); + } + getFocalLength() { + const vExtentSlope = Math.tan(DEG2RAD2 * 0.5 * this.fov); + return 0.5 * this.getFilmHeight() / vExtentSlope; + } + getEffectiveFOV() { + return RAD2DEG2 * 2 * Math.atan(Math.tan(DEG2RAD2 * 0.5 * this.fov) / this.zoom); + } + getFilmWidth() { + return this.filmGauge * Math.min(this.aspect, 1); + } + getFilmHeight() { + return this.filmGauge / Math.max(this.aspect, 1); + } + getViewBounds(distance, minTarget, maxTarget) { + _v3$12.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse); + minTarget.set(_v3$12.x, _v3$12.y).multiplyScalar(-distance / _v3$12.z); + _v3$12.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse); + maxTarget.set(_v3$12.x, _v3$12.y).multiplyScalar(-distance / _v3$12.z); + } + getViewSize(distance, target) { + this.getViewBounds(distance, _minTarget2, _maxTarget2); + return target.subVectors(_maxTarget2, _minTarget2); + } + setViewOffset(fullWidth, fullHeight, x, y, width2, height2) { + this.aspect = fullWidth / fullHeight; + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width2; + this.view.height = height2; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const near = this.near; + let top = near * Math.tan(DEG2RAD2 * 0.5 * this.fov) / this.zoom; + let height2 = 2 * top; + let width2 = this.aspect * height2; + let left = -0.5 * width2; + const view = this.view; + if (this.view !== null && this.view.enabled) { + const { fullWidth, fullHeight } = view; + left += view.offsetX * width2 / fullWidth; + top -= view.offsetY * height2 / fullHeight; + width2 *= view.width / fullWidth; + height2 *= view.height / fullHeight; + } + const skew = this.filmOffset; + if (skew !== 0) + left += near * skew / this.getFilmWidth(); + this.projectionMatrix.makePerspective(left, left + width2, top, top - height2, near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.fov = this.fov; + data2.object.zoom = this.zoom; + data2.object.near = this.near; + data2.object.far = this.far; + data2.object.focus = this.focus; + data2.object.aspect = this.aspect; + if (this.view !== null) + data2.object.view = Object.assign({}, this.view); + data2.object.filmGauge = this.filmGauge; + data2.object.filmOffset = this.filmOffset; + return data2; + } + } + var fov2 = -90; + var aspect2 = 1; + + class CubeCamera2 extends Object3D2 { + constructor(near, far, renderTarget) { + super(); + this.type = "CubeCamera"; + this.renderTarget = renderTarget; + this.coordinateSystem = null; + this.activeMipmapLevel = 0; + const cameraPX = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraPX.layers = this.layers; + this.add(cameraPX); + const cameraNX = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraNX.layers = this.layers; + this.add(cameraNX); + const cameraPY = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraPY.layers = this.layers; + this.add(cameraPY); + const cameraNY = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraNY.layers = this.layers; + this.add(cameraNY); + const cameraPZ = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraPZ.layers = this.layers; + this.add(cameraPZ); + const cameraNZ = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraNZ.layers = this.layers; + this.add(cameraNZ); + } + updateCoordinateSystem() { + const coordinateSystem = this.coordinateSystem; + const cameras = this.children.concat(); + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = cameras; + for (const camera of cameras) + this.remove(camera); + if (coordinateSystem === WebGLCoordinateSystem2) { + cameraPX.up.set(0, 1, 0); + cameraPX.lookAt(1, 0, 0); + cameraNX.up.set(0, 1, 0); + cameraNX.lookAt(-1, 0, 0); + cameraPY.up.set(0, 0, -1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, 1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, 1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, 1, 0); + cameraNZ.lookAt(0, 0, -1); + } else if (coordinateSystem === WebGPUCoordinateSystem2) { + cameraPX.up.set(0, -1, 0); + cameraPX.lookAt(-1, 0, 0); + cameraNX.up.set(0, -1, 0); + cameraNX.lookAt(1, 0, 0); + cameraPY.up.set(0, 0, 1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, -1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, -1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, -1, 0); + cameraNZ.lookAt(0, 0, -1); + } else { + throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + coordinateSystem); + } + for (const camera of cameras) { + this.add(camera); + camera.updateMatrixWorld(); + } + } + update(renderer2, scene) { + if (this.parent === null) + this.updateMatrixWorld(); + const { renderTarget, activeMipmapLevel } = this; + if (this.coordinateSystem !== renderer2.coordinateSystem) { + this.coordinateSystem = renderer2.coordinateSystem; + this.updateCoordinateSystem(); + } + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children; + const currentRenderTarget = renderer2.getRenderTarget(); + const currentActiveCubeFace = renderer2.getActiveCubeFace(); + const currentActiveMipmapLevel = renderer2.getActiveMipmapLevel(); + const currentXrEnabled = renderer2.xr.enabled; + renderer2.xr.enabled = false; + const generateMipmaps = renderTarget.texture.generateMipmaps; + renderTarget.texture.generateMipmaps = false; + renderer2.setRenderTarget(renderTarget, 0, activeMipmapLevel); + renderer2.render(scene, cameraPX); + renderer2.setRenderTarget(renderTarget, 1, activeMipmapLevel); + renderer2.render(scene, cameraNX); + renderer2.setRenderTarget(renderTarget, 2, activeMipmapLevel); + renderer2.render(scene, cameraPY); + renderer2.setRenderTarget(renderTarget, 3, activeMipmapLevel); + renderer2.render(scene, cameraNY); + renderer2.setRenderTarget(renderTarget, 4, activeMipmapLevel); + renderer2.render(scene, cameraPZ); + renderTarget.texture.generateMipmaps = generateMipmaps; + renderer2.setRenderTarget(renderTarget, 5, activeMipmapLevel); + renderer2.render(scene, cameraNZ); + renderer2.setRenderTarget(currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel); + renderer2.xr.enabled = currentXrEnabled; + renderTarget.texture.needsPMREMUpdate = true; + } + } + + class CubeTexture2 extends Texture2 { + constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace) { + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping2; + super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCubeTexture = true; + this.flipY = false; + } + get images() { + return this.image; + } + set images(value2) { + this.image = value2; + } + } + + class WebGLCubeRenderTarget2 extends WebGLRenderTarget2 { + constructor(size = 1, options = {}) { + super(size, size, options); + this.isWebGLCubeRenderTarget = true; + const image = { width: size, height: size, depth: 1 }; + const images = [image, image, image, image, image, image]; + this.texture = new CubeTexture2(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + this.texture.isRenderTargetTexture = true; + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter2; + } + fromEquirectangularTexture(renderer2, texture) { + this.texture.type = texture.type; + this.texture.colorSpace = texture.colorSpace; + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + const shader = { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `, + fragmentShader: ` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + }; + const geometry = new BoxGeometry2(5, 5, 5); + const material = new ShaderMaterial2({ + name: "CubemapFromEquirect", + uniforms: cloneUniforms2(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide2, + blending: NoBlending2 + }); + material.uniforms.tEquirect.value = texture; + const mesh = new Mesh2(geometry, material); + const currentMinFilter = texture.minFilter; + if (texture.minFilter === LinearMipmapLinearFilter2) + texture.minFilter = LinearFilter2; + const camera = new CubeCamera2(1, 10, this); + camera.update(renderer2, mesh); + texture.minFilter = currentMinFilter; + mesh.geometry.dispose(); + mesh.material.dispose(); + return this; + } + clear(renderer2, color, depth, stencil) { + const currentRenderTarget = renderer2.getRenderTarget(); + for (let i = 0;i < 6; i++) { + renderer2.setRenderTarget(this, i); + renderer2.clear(color, depth, stencil); + } + renderer2.setRenderTarget(currentRenderTarget); + } + } + + class Group2 extends Object3D2 { + constructor() { + super(); + this.isGroup = true; + this.type = "Group"; + } + } + var _moveEvent2 = { type: "move" }; + + class WebXRController2 { + constructor() { + this._targetRay = null; + this._grip = null; + this._hand = null; + } + getHandSpace() { + if (this._hand === null) { + this._hand = new Group2; + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + } + return this._hand; + } + getTargetRaySpace() { + if (this._targetRay === null) { + this._targetRay = new Group2; + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector32; + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector32; + } + return this._targetRay; + } + getGripSpace() { + if (this._grip === null) { + this._grip = new Group2; + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector32; + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector32; + } + return this._grip; + } + dispatchEvent(event) { + if (this._targetRay !== null) { + this._targetRay.dispatchEvent(event); + } + if (this._grip !== null) { + this._grip.dispatchEvent(event); + } + if (this._hand !== null) { + this._hand.dispatchEvent(event); + } + return this; + } + connect(inputSource) { + if (inputSource && inputSource.hand) { + const hand = this._hand; + if (hand) { + for (const inputjoint of inputSource.hand.values()) { + this._getHandJoint(hand, inputjoint); + } + } + } + this.dispatchEvent({ type: "connected", data: inputSource }); + return this; + } + disconnect(inputSource) { + this.dispatchEvent({ type: "disconnected", data: inputSource }); + if (this._targetRay !== null) { + this._targetRay.visible = false; + } + if (this._grip !== null) { + this._grip.visible = false; + } + if (this._hand !== null) { + this._hand.visible = false; + } + return this; + } + update(inputSource, frame, referenceSpace) { + let inputPose = null; + let gripPose = null; + let handPose = null; + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + if (inputSource && frame.session.visibilityState !== "visible-blurred") { + if (hand && inputSource.hand) { + handPose = true; + for (const inputjoint of inputSource.hand.values()) { + const jointPose = frame.getJointPose(inputjoint, referenceSpace); + const joint = this._getHandJoint(hand, inputjoint); + if (jointPose !== null) { + joint.matrix.fromArray(jointPose.transform.matrix); + joint.matrix.decompose(joint.position, joint.rotation, joint.scale); + joint.matrixWorldNeedsUpdate = true; + joint.jointRadius = jointPose.radius; + } + joint.visible = jointPose !== null; + } + const indexTip = hand.joints["index-finger-tip"]; + const thumbTip = hand.joints["thumb-tip"]; + const distance = indexTip.position.distanceTo(thumbTip.position); + const distanceToPinch = 0.02; + const threshold = 0.005; + if (hand.inputState.pinching && distance > distanceToPinch + threshold) { + hand.inputState.pinching = false; + this.dispatchEvent({ + type: "pinchend", + handedness: inputSource.handedness, + target: this + }); + } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) { + hand.inputState.pinching = true; + this.dispatchEvent({ + type: "pinchstart", + handedness: inputSource.handedness, + target: this + }); + } + } else { + if (grip !== null && inputSource.gripSpace) { + gripPose = frame.getPose(inputSource.gripSpace, referenceSpace); + if (gripPose !== null) { + grip.matrix.fromArray(gripPose.transform.matrix); + grip.matrix.decompose(grip.position, grip.rotation, grip.scale); + grip.matrixWorldNeedsUpdate = true; + if (gripPose.linearVelocity) { + grip.hasLinearVelocity = true; + grip.linearVelocity.copy(gripPose.linearVelocity); + } else { + grip.hasLinearVelocity = false; + } + if (gripPose.angularVelocity) { + grip.hasAngularVelocity = true; + grip.angularVelocity.copy(gripPose.angularVelocity); + } else { + grip.hasAngularVelocity = false; + } + } + } + } + if (targetRay !== null) { + inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); + if (inputPose === null && gripPose !== null) { + inputPose = gripPose; + } + if (inputPose !== null) { + targetRay.matrix.fromArray(inputPose.transform.matrix); + targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale); + targetRay.matrixWorldNeedsUpdate = true; + if (inputPose.linearVelocity) { + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy(inputPose.linearVelocity); + } else { + targetRay.hasLinearVelocity = false; + } + if (inputPose.angularVelocity) { + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy(inputPose.angularVelocity); + } else { + targetRay.hasAngularVelocity = false; + } + this.dispatchEvent(_moveEvent2); + } + } + } + if (targetRay !== null) { + targetRay.visible = inputPose !== null; + } + if (grip !== null) { + grip.visible = gripPose !== null; + } + if (hand !== null) { + hand.visible = handPose !== null; + } + return this; + } + _getHandJoint(hand, inputjoint) { + if (hand.joints[inputjoint.jointName] === undefined) { + const joint = new Group2; + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[inputjoint.jointName] = joint; + hand.add(joint); + } + return hand.joints[inputjoint.jointName]; + } + } + + class FogExp22 { + constructor(color, density = 0.00025) { + this.isFogExp2 = true; + this.name = ""; + this.color = new Color2(color); + this.density = density; + } + clone() { + return new FogExp22(this.color, this.density); + } + toJSON() { + return { + type: "FogExp2", + name: this.name, + color: this.color.getHex(), + density: this.density + }; + } + } + + class Fog2 { + constructor(color, near = 1, far = 1000) { + this.isFog = true; + this.name = ""; + this.color = new Color2(color); + this.near = near; + this.far = far; + } + clone() { + return new Fog2(this.color, this.near, this.far); + } + toJSON() { + return { + type: "Fog", + name: this.name, + color: this.color.getHex(), + near: this.near, + far: this.far + }; + } + } + + class Scene2 extends Object3D2 { + constructor() { + super(); + this.isScene = true; + this.type = "Scene"; + this.background = null; + this.environment = null; + this.fog = null; + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + this.backgroundRotation = new Euler2; + this.environmentIntensity = 1; + this.environmentRotation = new Euler2; + this.overrideMaterial = null; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.background !== null) + this.background = source.background.clone(); + if (source.environment !== null) + this.environment = source.environment.clone(); + if (source.fog !== null) + this.fog = source.fog.clone(); + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + this.backgroundRotation.copy(source.backgroundRotation); + this.environmentIntensity = source.environmentIntensity; + this.environmentRotation.copy(source.environmentRotation); + if (source.overrideMaterial !== null) + this.overrideMaterial = source.overrideMaterial.clone(); + this.matrixAutoUpdate = source.matrixAutoUpdate; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + if (this.fog !== null) + data2.object.fog = this.fog.toJSON(); + if (this.backgroundBlurriness > 0) + data2.object.backgroundBlurriness = this.backgroundBlurriness; + if (this.backgroundIntensity !== 1) + data2.object.backgroundIntensity = this.backgroundIntensity; + data2.object.backgroundRotation = this.backgroundRotation.toArray(); + if (this.environmentIntensity !== 1) + data2.object.environmentIntensity = this.environmentIntensity; + data2.object.environmentRotation = this.environmentRotation.toArray(); + return data2; + } + } + + class InterleavedBuffer2 { + constructor(array, stride) { + this.isInterleavedBuffer = true; + this.array = array; + this.stride = stride; + this.count = array !== undefined ? array.length / stride : 0; + this.usage = StaticDrawUsage2; + this.updateRanges = []; + this.version = 0; + this.uuid = generateUUID2(); + } + onUploadCallback() { + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setUsage(value2) { + this.usage = value2; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.array = new source.array.constructor(source.array); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.stride; + index2 *= attribute.stride; + for (let i = 0, l = this.stride;i < l; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + set(value2, offset = 0) { + this.array.set(value2, offset); + return this; + } + clone(data2) { + if (data2.arrayBuffers === undefined) { + data2.arrayBuffers = {}; + } + if (this.array.buffer._uuid === undefined) { + this.array.buffer._uuid = generateUUID2(); + } + if (data2.arrayBuffers[this.array.buffer._uuid] === undefined) { + data2.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer; + } + const array = new this.array.constructor(data2.arrayBuffers[this.array.buffer._uuid]); + const ib = new this.constructor(array, this.stride); + ib.setUsage(this.usage); + return ib; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + toJSON(data2) { + if (data2.arrayBuffers === undefined) { + data2.arrayBuffers = {}; + } + if (this.array.buffer._uuid === undefined) { + this.array.buffer._uuid = generateUUID2(); + } + if (data2.arrayBuffers[this.array.buffer._uuid] === undefined) { + data2.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer)); + } + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; + } + } + var _vector$72 = /* @__PURE__ */ new Vector32; + + class InterleavedBufferAttribute2 { + constructor(interleavedBuffer, itemSize, offset, normalized = false) { + this.isInterleavedBufferAttribute = true; + this.name = ""; + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; + this.normalized = normalized; + } + get count() { + return this.data.count; + } + get array() { + return this.data.array; + } + set needsUpdate(value2) { + this.data.needsUpdate = value2; + } + applyMatrix4(m) { + for (let i = 0, l = this.data.count;i < l; i++) { + _vector$72.fromBufferAttribute(this, i); + _vector$72.applyMatrix4(m); + this.setXYZ(i, _vector$72.x, _vector$72.y, _vector$72.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$72.fromBufferAttribute(this, i); + _vector$72.applyNormalMatrix(m); + this.setXYZ(i, _vector$72.x, _vector$72.y, _vector$72.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$72.fromBufferAttribute(this, i); + _vector$72.transformDirection(m); + this.setXYZ(i, _vector$72.x, _vector$72.y, _vector$72.z); + } + return this; + } + getComponent(index2, component) { + let value2 = this.array[index2 * this.data.stride + this.offset + component]; + if (this.normalized) + value2 = denormalize2(value2, this.array); + return value2; + } + setComponent(index2, component, value2) { + if (this.normalized) + value2 = normalize3(value2, this.array); + this.data.array[index2 * this.data.stride + this.offset + component] = value2; + return this; + } + setX(index2, x) { + if (this.normalized) + x = normalize3(x, this.array); + this.data.array[index2 * this.data.stride + this.offset] = x; + return this; + } + setY(index2, y) { + if (this.normalized) + y = normalize3(y, this.array); + this.data.array[index2 * this.data.stride + this.offset + 1] = y; + return this; + } + setZ(index2, z) { + if (this.normalized) + z = normalize3(z, this.array); + this.data.array[index2 * this.data.stride + this.offset + 2] = z; + return this; + } + setW(index2, w) { + if (this.normalized) + w = normalize3(w, this.array); + this.data.array[index2 * this.data.stride + this.offset + 3] = w; + return this; + } + getX(index2) { + let x = this.data.array[index2 * this.data.stride + this.offset]; + if (this.normalized) + x = denormalize2(x, this.array); + return x; + } + getY(index2) { + let y = this.data.array[index2 * this.data.stride + this.offset + 1]; + if (this.normalized) + y = denormalize2(y, this.array); + return y; + } + getZ(index2) { + let z = this.data.array[index2 * this.data.stride + this.offset + 2]; + if (this.normalized) + z = denormalize2(z, this.array); + return z; + } + getW(index2) { + let w = this.data.array[index2 * this.data.stride + this.offset + 3]; + if (this.normalized) + w = denormalize2(w, this.array); + return w; + } + setXY(index2, x, y) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x = normalize3(x, this.array); + y = normalize3(y, this.array); + } + this.data.array[index2 + 0] = x; + this.data.array[index2 + 1] = y; + return this; + } + setXYZ(index2, x, y, z) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x = normalize3(x, this.array); + y = normalize3(y, this.array); + z = normalize3(z, this.array); + } + this.data.array[index2 + 0] = x; + this.data.array[index2 + 1] = y; + this.data.array[index2 + 2] = z; + return this; + } + setXYZW(index2, x, y, z, w) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x = normalize3(x, this.array); + y = normalize3(y, this.array); + z = normalize3(z, this.array); + w = normalize3(w, this.array); + } + this.data.array[index2 + 0] = x; + this.data.array[index2 + 1] = y; + this.data.array[index2 + 2] = z; + this.data.array[index2 + 3] = w; + return this; + } + clone(data2) { + if (data2 === undefined) { + console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0;i < this.count; i++) { + const index2 = i * this.data.stride + this.offset; + for (let j = 0;j < this.itemSize; j++) { + array.push(this.data.array[index2 + j]); + } + } + return new BufferAttribute2(new this.array.constructor(array), this.itemSize, this.normalized); + } else { + if (data2.interleavedBuffers === undefined) { + data2.interleavedBuffers = {}; + } + if (data2.interleavedBuffers[this.data.uuid] === undefined) { + data2.interleavedBuffers[this.data.uuid] = this.data.clone(data2); + } + return new InterleavedBufferAttribute2(data2.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized); + } + } + toJSON(data2) { + if (data2 === undefined) { + console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0;i < this.count; i++) { + const index2 = i * this.data.stride + this.offset; + for (let j = 0;j < this.itemSize; j++) { + array.push(this.data.array[index2 + j]); + } + } + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array, + normalized: this.normalized + }; + } else { + if (data2.interleavedBuffers === undefined) { + data2.interleavedBuffers = {}; + } + if (data2.interleavedBuffers[this.data.uuid] === undefined) { + data2.interleavedBuffers[this.data.uuid] = this.data.toJSON(data2); + } + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + } + } + } + + class SpriteMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isSpriteMaterial = true; + this.type = "SpriteMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.alphaMap = null; + this.rotation = 0; + this.sizeAttenuation = true; + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.rotation = source.rotation; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } + } + var _geometry2; + var _intersectPoint2 = /* @__PURE__ */ new Vector32; + var _worldScale2 = /* @__PURE__ */ new Vector32; + var _mvPosition2 = /* @__PURE__ */ new Vector32; + var _alignedPosition2 = /* @__PURE__ */ new Vector22; + var _rotatedPosition2 = /* @__PURE__ */ new Vector22; + var _viewWorldMatrix2 = /* @__PURE__ */ new Matrix42; + var _vA2 = /* @__PURE__ */ new Vector32; + var _vB2 = /* @__PURE__ */ new Vector32; + var _vC2 = /* @__PURE__ */ new Vector32; + var _uvA2 = /* @__PURE__ */ new Vector22; + var _uvB2 = /* @__PURE__ */ new Vector22; + var _uvC2 = /* @__PURE__ */ new Vector22; + + class Sprite2 extends Object3D2 { + constructor(material = new SpriteMaterial2) { + super(); + this.isSprite = true; + this.type = "Sprite"; + if (_geometry2 === undefined) { + _geometry2 = new BufferGeometry2; + const float32Array = new Float32Array([ + -0.5, + -0.5, + 0, + 0, + 0, + 0.5, + -0.5, + 0, + 1, + 0, + 0.5, + 0.5, + 0, + 1, + 1, + -0.5, + 0.5, + 0, + 0, + 1 + ]); + const interleavedBuffer = new InterleavedBuffer2(float32Array, 5); + _geometry2.setIndex([0, 1, 2, 0, 2, 3]); + _geometry2.setAttribute("position", new InterleavedBufferAttribute2(interleavedBuffer, 3, 0, false)); + _geometry2.setAttribute("uv", new InterleavedBufferAttribute2(interleavedBuffer, 2, 3, false)); + } + this.geometry = _geometry2; + this.material = material; + this.center = new Vector22(0.5, 0.5); + } + raycast(raycaster, intersects3) { + if (raycaster.camera === null) { + console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'); + } + _worldScale2.setFromMatrixScale(this.matrixWorld); + _viewWorldMatrix2.copy(raycaster.camera.matrixWorld); + this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld); + _mvPosition2.setFromMatrixPosition(this.modelViewMatrix); + if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) { + _worldScale2.multiplyScalar(-_mvPosition2.z); + } + const rotation2 = this.material.rotation; + let sin, cos; + if (rotation2 !== 0) { + cos = Math.cos(rotation2); + sin = Math.sin(rotation2); + } + const center = this.center; + transformVertex2(_vA2.set(-0.5, -0.5, 0), _mvPosition2, center, _worldScale2, sin, cos); + transformVertex2(_vB2.set(0.5, -0.5, 0), _mvPosition2, center, _worldScale2, sin, cos); + transformVertex2(_vC2.set(0.5, 0.5, 0), _mvPosition2, center, _worldScale2, sin, cos); + _uvA2.set(0, 0); + _uvB2.set(1, 0); + _uvC2.set(1, 1); + let intersect3 = raycaster.ray.intersectTriangle(_vA2, _vB2, _vC2, false, _intersectPoint2); + if (intersect3 === null) { + transformVertex2(_vB2.set(-0.5, 0.5, 0), _mvPosition2, center, _worldScale2, sin, cos); + _uvB2.set(0, 1); + intersect3 = raycaster.ray.intersectTriangle(_vA2, _vC2, _vB2, false, _intersectPoint2); + if (intersect3 === null) { + return; + } + } + const distance = raycaster.ray.origin.distanceTo(_intersectPoint2); + if (distance < raycaster.near || distance > raycaster.far) + return; + intersects3.push({ + distance, + point: _intersectPoint2.clone(), + uv: Triangle2.getInterpolation(_intersectPoint2, _vA2, _vB2, _vC2, _uvA2, _uvB2, _uvC2, new Vector22), + face: null, + object: this + }); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.center !== undefined) + this.center.copy(source.center); + this.material = source.material; + return this; + } + } + function transformVertex2(vertexPosition, mvPosition, center, scale2, sin, cos) { + _alignedPosition2.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale2); + if (sin !== undefined) { + _rotatedPosition2.x = cos * _alignedPosition2.x - sin * _alignedPosition2.y; + _rotatedPosition2.y = sin * _alignedPosition2.x + cos * _alignedPosition2.y; + } else { + _rotatedPosition2.copy(_alignedPosition2); + } + vertexPosition.copy(mvPosition); + vertexPosition.x += _rotatedPosition2.x; + vertexPosition.y += _rotatedPosition2.y; + vertexPosition.applyMatrix4(_viewWorldMatrix2); + } + var _v1$22 = /* @__PURE__ */ new Vector32; + var _v2$12 = /* @__PURE__ */ new Vector32; + + class LOD2 extends Object3D2 { + constructor() { + super(); + this._currentLevel = 0; + this.type = "LOD"; + Object.defineProperties(this, { + levels: { + enumerable: true, + value: [] + }, + isLOD: { + value: true + } + }); + this.autoUpdate = true; + } + copy(source) { + super.copy(source, false); + const levels = source.levels; + for (let i = 0, l = levels.length;i < l; i++) { + const level = levels[i]; + this.addLevel(level.object.clone(), level.distance, level.hysteresis); + } + this.autoUpdate = source.autoUpdate; + return this; + } + addLevel(object, distance = 0, hysteresis = 0) { + distance = Math.abs(distance); + const levels = this.levels; + let l; + for (l = 0;l < levels.length; l++) { + if (distance < levels[l].distance) { + break; + } + } + levels.splice(l, 0, { distance, hysteresis, object }); + this.add(object); + return this; + } + removeLevel(distance) { + const levels = this.levels; + for (let i = 0;i < levels.length; i++) { + if (levels[i].distance === distance) { + const removedElements = levels.splice(i, 1); + this.remove(removedElements[0].object); + return true; + } + } + return false; + } + getCurrentLevel() { + return this._currentLevel; + } + getObjectForDistance(distance) { + const levels = this.levels; + if (levels.length > 0) { + let i, l; + for (i = 1, l = levels.length;i < l; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance < levelDistance) { + break; + } + } + return levels[i - 1].object; + } + return null; + } + raycast(raycaster, intersects3) { + const levels = this.levels; + if (levels.length > 0) { + _v1$22.setFromMatrixPosition(this.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_v1$22); + this.getObjectForDistance(distance).raycast(raycaster, intersects3); + } + } + update(camera) { + const levels = this.levels; + if (levels.length > 1) { + _v1$22.setFromMatrixPosition(camera.matrixWorld); + _v2$12.setFromMatrixPosition(this.matrixWorld); + const distance = _v1$22.distanceTo(_v2$12) / camera.zoom; + levels[0].object.visible = true; + let i, l; + for (i = 1, l = levels.length;i < l; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance >= levelDistance) { + levels[i - 1].object.visible = false; + levels[i].object.visible = true; + } else { + break; + } + } + this._currentLevel = i - 1; + for (;i < l; i++) { + levels[i].object.visible = false; + } + } + } + toJSON(meta) { + const data2 = super.toJSON(meta); + if (this.autoUpdate === false) + data2.object.autoUpdate = false; + data2.object.levels = []; + const levels = this.levels; + for (let i = 0, l = levels.length;i < l; i++) { + const level = levels[i]; + data2.object.levels.push({ + object: level.object.uuid, + distance: level.distance, + hysteresis: level.hysteresis + }); + } + return data2; + } + } + var _basePosition2 = /* @__PURE__ */ new Vector32; + var _skinIndex2 = /* @__PURE__ */ new Vector42; + var _skinWeight2 = /* @__PURE__ */ new Vector42; + var _vector32 = /* @__PURE__ */ new Vector32; + var _matrix42 = /* @__PURE__ */ new Matrix42; + var _vertex2 = /* @__PURE__ */ new Vector32; + var _sphere$52 = /* @__PURE__ */ new Sphere2; + var _inverseMatrix$22 = /* @__PURE__ */ new Matrix42; + var _ray$22 = /* @__PURE__ */ new Ray2; + + class SkinnedMesh2 extends Mesh2 { + constructor(geometry, material) { + super(geometry, material); + this.isSkinnedMesh = true; + this.type = "SkinnedMesh"; + this.bindMode = AttachedBindMode2; + this.bindMatrix = new Matrix42; + this.bindMatrixInverse = new Matrix42; + this.boundingBox = null; + this.boundingSphere = null; + } + computeBoundingBox() { + const geometry = this.geometry; + if (this.boundingBox === null) { + this.boundingBox = new Box32; + } + this.boundingBox.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0;i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex2); + this.boundingBox.expandByPoint(_vertex2); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere2; + } + this.boundingSphere.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0;i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex2); + this.boundingSphere.expandByPoint(_vertex2); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.bindMode = source.bindMode; + this.bindMatrix.copy(source.bindMatrix); + this.bindMatrixInverse.copy(source.bindMatrixInverse); + this.skeleton = source.skeleton; + if (source.boundingBox !== null) + this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) + this.boundingSphere = source.boundingSphere.clone(); + return this; + } + raycast(raycaster, intersects3) { + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === undefined) + return; + if (this.boundingSphere === null) + this.computeBoundingSphere(); + _sphere$52.copy(this.boundingSphere); + _sphere$52.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$52) === false) + return; + _inverseMatrix$22.copy(matrixWorld).invert(); + _ray$22.copy(raycaster.ray).applyMatrix4(_inverseMatrix$22); + if (this.boundingBox !== null) { + if (_ray$22.intersectsBox(this.boundingBox) === false) + return; + } + this._computeIntersections(raycaster, intersects3, _ray$22); + } + getVertexPosition(index2, target) { + super.getVertexPosition(index2, target); + this.applyBoneTransform(index2, target); + return target; + } + bind(skeleton, bindMatrix) { + this.skeleton = skeleton; + if (bindMatrix === undefined) { + this.updateMatrixWorld(true); + this.skeleton.calculateInverses(); + bindMatrix = this.matrixWorld; + } + this.bindMatrix.copy(bindMatrix); + this.bindMatrixInverse.copy(bindMatrix).invert(); + } + pose() { + this.skeleton.pose(); + } + normalizeSkinWeights() { + const vector = new Vector42; + const skinWeight = this.geometry.attributes.skinWeight; + for (let i = 0, l = skinWeight.count;i < l; i++) { + vector.fromBufferAttribute(skinWeight, i); + const scale2 = 1 / vector.manhattanLength(); + if (scale2 !== Infinity) { + vector.multiplyScalar(scale2); + } else { + vector.set(1, 0, 0, 0); + } + skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w); + } + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.bindMode === AttachedBindMode2) { + this.bindMatrixInverse.copy(this.matrixWorld).invert(); + } else if (this.bindMode === DetachedBindMode2) { + this.bindMatrixInverse.copy(this.bindMatrix).invert(); + } else { + console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode); + } + } + applyBoneTransform(index2, vector) { + const skeleton = this.skeleton; + const geometry = this.geometry; + _skinIndex2.fromBufferAttribute(geometry.attributes.skinIndex, index2); + _skinWeight2.fromBufferAttribute(geometry.attributes.skinWeight, index2); + _basePosition2.copy(vector).applyMatrix4(this.bindMatrix); + vector.set(0, 0, 0); + for (let i = 0;i < 4; i++) { + const weight = _skinWeight2.getComponent(i); + if (weight !== 0) { + const boneIndex = _skinIndex2.getComponent(i); + _matrix42.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]); + vector.addScaledVector(_vector32.copy(_basePosition2).applyMatrix4(_matrix42), weight); + } + } + return vector.applyMatrix4(this.bindMatrixInverse); + } + } + + class Bone2 extends Object3D2 { + constructor() { + super(); + this.isBone = true; + this.type = "Bone"; + } + } + + class DataTexture2 extends Texture2 { + constructor(data2 = null, width2 = 1, height2 = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter2, minFilter = NearestFilter2, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isDataTexture = true; + this.image = { data: data2, width: width2, height: height2 }; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } + } + var _offsetMatrix2 = /* @__PURE__ */ new Matrix42; + var _identityMatrix2 = /* @__PURE__ */ new Matrix42; + + class Skeleton2 { + constructor(bones = [], boneInverses = []) { + this.uuid = generateUUID2(); + this.bones = bones.slice(0); + this.boneInverses = boneInverses; + this.boneMatrices = null; + this.boneTexture = null; + this.init(); + } + init() { + const bones = this.bones; + const boneInverses = this.boneInverses; + this.boneMatrices = new Float32Array(bones.length * 16); + if (boneInverses.length === 0) { + this.calculateInverses(); + } else { + if (bones.length !== boneInverses.length) { + console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."); + this.boneInverses = []; + for (let i = 0, il = this.bones.length;i < il; i++) { + this.boneInverses.push(new Matrix42); + } + } + } + } + calculateInverses() { + this.boneInverses.length = 0; + for (let i = 0, il = this.bones.length;i < il; i++) { + const inverse = new Matrix42; + if (this.bones[i]) { + inverse.copy(this.bones[i].matrixWorld).invert(); + } + this.boneInverses.push(inverse); + } + } + pose() { + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone) { + bone.matrixWorld.copy(this.boneInverses[i]).invert(); + } + } + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone) { + if (bone.parent && bone.parent.isBone) { + bone.matrix.copy(bone.parent.matrixWorld).invert(); + bone.matrix.multiply(bone.matrixWorld); + } else { + bone.matrix.copy(bone.matrixWorld); + } + bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); + } + } + } + update() { + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; + for (let i = 0, il = bones.length;i < il; i++) { + const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix2; + _offsetMatrix2.multiplyMatrices(matrix, boneInverses[i]); + _offsetMatrix2.toArray(boneMatrices, i * 16); + } + if (boneTexture !== null) { + boneTexture.needsUpdate = true; + } + } + clone() { + return new Skeleton2(this.bones, this.boneInverses); + } + computeBoneTexture() { + let size = Math.sqrt(this.bones.length * 4); + size = Math.ceil(size / 4) * 4; + size = Math.max(size, 4); + const boneMatrices = new Float32Array(size * size * 4); + boneMatrices.set(this.boneMatrices); + const boneTexture = new DataTexture2(boneMatrices, size, size, RGBAFormat2, FloatType2); + boneTexture.needsUpdate = true; + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + return this; + } + getBoneByName(name2) { + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone.name === name2) { + return bone; + } + } + return; + } + dispose() { + if (this.boneTexture !== null) { + this.boneTexture.dispose(); + this.boneTexture = null; + } + } + fromJSON(json, bones) { + this.uuid = json.uuid; + for (let i = 0, l = json.bones.length;i < l; i++) { + const uuid = json.bones[i]; + let bone = bones[uuid]; + if (bone === undefined) { + console.warn("THREE.Skeleton: No bone found with UUID:", uuid); + bone = new Bone2; + } + this.bones.push(bone); + this.boneInverses.push(new Matrix42().fromArray(json.boneInverses[i])); + } + this.init(); + return this; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "Skeleton", + generator: "Skeleton.toJSON" + }, + bones: [], + boneInverses: [] + }; + data2.uuid = this.uuid; + const bones = this.bones; + const boneInverses = this.boneInverses; + for (let i = 0, l = bones.length;i < l; i++) { + const bone = bones[i]; + data2.bones.push(bone.uuid); + const boneInverse = boneInverses[i]; + data2.boneInverses.push(boneInverse.toArray()); + } + return data2; + } + } + + class InstancedBufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized, meshPerAttribute = 1) { + super(array, itemSize, normalized); + this.isInstancedBufferAttribute = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.meshPerAttribute = this.meshPerAttribute; + data2.isInstancedBufferAttribute = true; + return data2; + } + } + var _instanceLocalMatrix2 = /* @__PURE__ */ new Matrix42; + var _instanceWorldMatrix2 = /* @__PURE__ */ new Matrix42; + var _instanceIntersects2 = []; + var _box32 = /* @__PURE__ */ new Box32; + var _identity2 = /* @__PURE__ */ new Matrix42; + var _mesh$12 = /* @__PURE__ */ new Mesh2; + var _sphere$42 = /* @__PURE__ */ new Sphere2; + + class InstancedMesh2 extends Mesh2 { + constructor(geometry, material, count) { + super(geometry, material); + this.isInstancedMesh = true; + this.instanceMatrix = new InstancedBufferAttribute2(new Float32Array(count * 16), 16); + this.instanceColor = null; + this.morphTexture = null; + this.count = count; + this.boundingBox = null; + this.boundingSphere = null; + for (let i = 0;i < count; i++) { + this.setMatrixAt(i, _identity2); + } + } + computeBoundingBox() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingBox === null) { + this.boundingBox = new Box32; + } + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + this.boundingBox.makeEmpty(); + for (let i = 0;i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix2); + _box32.copy(geometry.boundingBox).applyMatrix4(_instanceLocalMatrix2); + this.boundingBox.union(_box32); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere2; + } + if (geometry.boundingSphere === null) { + geometry.computeBoundingSphere(); + } + this.boundingSphere.makeEmpty(); + for (let i = 0;i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix2); + _sphere$42.copy(geometry.boundingSphere).applyMatrix4(_instanceLocalMatrix2); + this.boundingSphere.union(_sphere$42); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.instanceMatrix.copy(source.instanceMatrix); + if (source.morphTexture !== null) + this.morphTexture = source.morphTexture.clone(); + if (source.instanceColor !== null) + this.instanceColor = source.instanceColor.clone(); + this.count = source.count; + if (source.boundingBox !== null) + this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) + this.boundingSphere = source.boundingSphere.clone(); + return this; + } + getColorAt(index2, color) { + color.fromArray(this.instanceColor.array, index2 * 3); + } + getMatrixAt(index2, matrix) { + matrix.fromArray(this.instanceMatrix.array, index2 * 16); + } + getMorphAt(index2, object) { + const objectInfluences = object.morphTargetInfluences; + const array = this.morphTexture.source.data.data; + const len = objectInfluences.length + 1; + const dataIndex = index2 * len + 1; + for (let i = 0;i < objectInfluences.length; i++) { + objectInfluences[i] = array[dataIndex + i]; + } + } + raycast(raycaster, intersects3) { + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + _mesh$12.geometry = this.geometry; + _mesh$12.material = this.material; + if (_mesh$12.material === undefined) + return; + if (this.boundingSphere === null) + this.computeBoundingSphere(); + _sphere$42.copy(this.boundingSphere); + _sphere$42.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$42) === false) + return; + for (let instanceId = 0;instanceId < raycastTimes; instanceId++) { + this.getMatrixAt(instanceId, _instanceLocalMatrix2); + _instanceWorldMatrix2.multiplyMatrices(matrixWorld, _instanceLocalMatrix2); + _mesh$12.matrixWorld = _instanceWorldMatrix2; + _mesh$12.raycast(raycaster, _instanceIntersects2); + for (let i = 0, l = _instanceIntersects2.length;i < l; i++) { + const intersect3 = _instanceIntersects2[i]; + intersect3.instanceId = instanceId; + intersect3.object = this; + intersects3.push(intersect3); + } + _instanceIntersects2.length = 0; + } + } + setColorAt(index2, color) { + if (this.instanceColor === null) { + this.instanceColor = new InstancedBufferAttribute2(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3); + } + color.toArray(this.instanceColor.array, index2 * 3); + } + setMatrixAt(index2, matrix) { + matrix.toArray(this.instanceMatrix.array, index2 * 16); + } + setMorphAt(index2, object) { + const objectInfluences = object.morphTargetInfluences; + const len = objectInfluences.length + 1; + if (this.morphTexture === null) { + this.morphTexture = new DataTexture2(new Float32Array(len * this.count), len, this.count, RedFormat2, FloatType2); + } + const array = this.morphTexture.source.data.data; + let morphInfluencesSum = 0; + for (let i = 0;i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + const dataIndex = len * index2; + array[dataIndex] = morphBaseInfluence; + array.set(objectInfluences, dataIndex + 1); + } + updateMorphTargets() { + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + if (this.morphTexture !== null) { + this.morphTexture.dispose(); + this.morphTexture = null; + } + return this; + } + } + var _vector12 = /* @__PURE__ */ new Vector32; + var _vector22 = /* @__PURE__ */ new Vector32; + var _normalMatrix2 = /* @__PURE__ */ new Matrix32; + + class Plane2 { + constructor(normal = new Vector32(1, 0, 0), constant = 0) { + this.isPlane = true; + this.normal = normal; + this.constant = constant; + } + set(normal, constant) { + this.normal.copy(normal); + this.constant = constant; + return this; + } + setComponents(x, y, z, w) { + this.normal.set(x, y, z); + this.constant = w; + return this; + } + setFromNormalAndCoplanarPoint(normal, point) { + this.normal.copy(normal); + this.constant = -point.dot(this.normal); + return this; + } + setFromCoplanarPoints(a, b, c) { + const normal = _vector12.subVectors(c, b).cross(_vector22.subVectors(a, b)).normalize(); + this.setFromNormalAndCoplanarPoint(normal, a); + return this; + } + copy(plane) { + this.normal.copy(plane.normal); + this.constant = plane.constant; + return this; + } + normalize() { + const inverseNormalLength = 1 / this.normal.length(); + this.normal.multiplyScalar(inverseNormalLength); + this.constant *= inverseNormalLength; + return this; + } + negate() { + this.constant *= -1; + this.normal.negate(); + return this; + } + distanceToPoint(point) { + return this.normal.dot(point) + this.constant; + } + distanceToSphere(sphere) { + return this.distanceToPoint(sphere.center) - sphere.radius; + } + projectPoint(point, target) { + return target.copy(point).addScaledVector(this.normal, -this.distanceToPoint(point)); + } + intersectLine(line, target) { + const direction = line.delta(_vector12); + const denominator = this.normal.dot(direction); + if (denominator === 0) { + if (this.distanceToPoint(line.start) === 0) { + return target.copy(line.start); + } + return null; + } + const t = -(line.start.dot(this.normal) + this.constant) / denominator; + if (t < 0 || t > 1) { + return null; + } + return target.copy(line.start).addScaledVector(direction, t); + } + intersectsLine(line) { + const startSign = this.distanceToPoint(line.start); + const endSign = this.distanceToPoint(line.end); + return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0; + } + intersectsBox(box) { + return box.intersectsPlane(this); + } + intersectsSphere(sphere) { + return sphere.intersectsPlane(this); + } + coplanarPoint(target) { + return target.copy(this.normal).multiplyScalar(-this.constant); + } + applyMatrix4(matrix, optionalNormalMatrix) { + const normalMatrix = optionalNormalMatrix || _normalMatrix2.getNormalMatrix(matrix); + const referencePoint = this.coplanarPoint(_vector12).applyMatrix4(matrix); + const normal = this.normal.applyMatrix3(normalMatrix).normalize(); + this.constant = -referencePoint.dot(normal); + return this; + } + translate(offset) { + this.constant -= offset.dot(this.normal); + return this; + } + equals(plane) { + return plane.normal.equals(this.normal) && plane.constant === this.constant; + } + clone() { + return new this.constructor().copy(this); + } + } + var _sphere$32 = /* @__PURE__ */ new Sphere2; + var _vector$62 = /* @__PURE__ */ new Vector32; + + class Frustum2 { + constructor(p0 = new Plane2, p1 = new Plane2, p2 = new Plane2, p3 = new Plane2, p4 = new Plane2, p5 = new Plane2) { + this.planes = [p0, p1, p2, p3, p4, p5]; + } + set(p0, p1, p2, p3, p4, p5) { + const planes = this.planes; + planes[0].copy(p0); + planes[1].copy(p1); + planes[2].copy(p2); + planes[3].copy(p3); + planes[4].copy(p4); + planes[5].copy(p5); + return this; + } + copy(frustum) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + planes[i].copy(frustum.planes[i]); + } + return this; + } + setFromProjectionMatrix(m, coordinateSystem = WebGLCoordinateSystem2) { + const planes = this.planes; + const me = m.elements; + const me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3]; + const me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7]; + const me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11]; + const me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15]; + planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize(); + planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize(); + planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize(); + planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize(); + planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); + if (coordinateSystem === WebGLCoordinateSystem2) { + planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize(); + } else if (coordinateSystem === WebGPUCoordinateSystem2) { + planes[5].setComponents(me2, me6, me10, me14).normalize(); + } else { + throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + coordinateSystem); + } + return this; + } + intersectsObject(object) { + if (object.boundingSphere !== undefined) { + if (object.boundingSphere === null) + object.computeBoundingSphere(); + _sphere$32.copy(object.boundingSphere).applyMatrix4(object.matrixWorld); + } else { + const geometry = object.geometry; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$32.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld); + } + return this.intersectsSphere(_sphere$32); + } + intersectsSprite(sprite) { + _sphere$32.center.set(0, 0, 0); + _sphere$32.radius = 0.7071067811865476; + _sphere$32.applyMatrix4(sprite.matrixWorld); + return this.intersectsSphere(_sphere$32); + } + intersectsSphere(sphere) { + const planes = this.planes; + const center = sphere.center; + const negRadius = -sphere.radius; + for (let i = 0;i < 6; i++) { + const distance = planes[i].distanceToPoint(center); + if (distance < negRadius) { + return false; + } + } + return true; + } + intersectsBox(box) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + const plane = planes[i]; + _vector$62.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$62.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$62.z = plane.normal.z > 0 ? box.max.z : box.min.z; + if (plane.distanceToPoint(_vector$62) < 0) { + return false; + } + } + return true; + } + containsPoint(point) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + if (planes[i].distanceToPoint(point) < 0) { + return false; + } + } + return true; + } + clone() { + return new this.constructor().copy(this); + } + } + function ascIdSort2(a, b) { + return a - b; + } + function sortOpaque2(a, b) { + return a.z - b.z; + } + function sortTransparent2(a, b) { + return b.z - a.z; + } + + class MultiDrawRenderList2 { + constructor() { + this.index = 0; + this.pool = []; + this.list = []; + } + push(start, count, z, index2) { + const pool = this.pool; + const list = this.list; + if (this.index >= pool.length) { + pool.push({ + start: -1, + count: -1, + z: -1, + index: -1 + }); + } + const item = pool[this.index]; + list.push(item); + this.index++; + item.start = start; + item.count = count; + item.z = z; + item.index = index2; + } + reset() { + this.list.length = 0; + this.index = 0; + } + } + var _matrix$12 = /* @__PURE__ */ new Matrix42; + var _whiteColor2 = /* @__PURE__ */ new Color2(1, 1, 1); + var _frustum2 = /* @__PURE__ */ new Frustum2; + var _box$12 = /* @__PURE__ */ new Box32; + var _sphere$22 = /* @__PURE__ */ new Sphere2; + var _vector$52 = /* @__PURE__ */ new Vector32; + var _forward2 = /* @__PURE__ */ new Vector32; + var _temp2 = /* @__PURE__ */ new Vector32; + var _renderList2 = /* @__PURE__ */ new MultiDrawRenderList2; + var _mesh2 = /* @__PURE__ */ new Mesh2; + var _batchIntersects2 = []; + function copyAttributeData2(src, target, targetOffset = 0) { + const itemSize = target.itemSize; + if (src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor) { + const vertexCount = src.count; + for (let i = 0;i < vertexCount; i++) { + for (let c = 0;c < itemSize; c++) { + target.setComponent(i + targetOffset, c, src.getComponent(i, c)); + } + } + } else { + target.array.set(src.array, targetOffset * itemSize); + } + target.needsUpdate = true; + } + function copyArrayContents2(src, target) { + if (src.constructor !== target.constructor) { + const len = Math.min(src.length, target.length); + for (let i = 0;i < len; i++) { + target[i] = src[i]; + } + } else { + const len = Math.min(src.length, target.length); + target.set(new src.constructor(src.buffer, 0, len)); + } + } + + class BatchedMesh2 extends Mesh2 { + get maxInstanceCount() { + return this._maxInstanceCount; + } + get instanceCount() { + return this._instanceInfo.length - this._availableInstanceIds.length; + } + get unusedVertexCount() { + return this._maxVertexCount - this._nextVertexStart; + } + get unusedIndexCount() { + return this._maxIndexCount - this._nextIndexStart; + } + constructor(maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material) { + super(new BufferGeometry2, material); + this.isBatchedMesh = true; + this.perObjectFrustumCulled = true; + this.sortObjects = true; + this.boundingBox = null; + this.boundingSphere = null; + this.customSort = null; + this._instanceInfo = []; + this._geometryInfo = []; + this._availableInstanceIds = []; + this._availableGeometryIds = []; + this._nextIndexStart = 0; + this._nextVertexStart = 0; + this._geometryCount = 0; + this._visibilityChanged = true; + this._geometryInitialized = false; + this._maxInstanceCount = maxInstanceCount; + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + this._multiDrawCounts = new Int32Array(maxInstanceCount); + this._multiDrawStarts = new Int32Array(maxInstanceCount); + this._multiDrawCount = 0; + this._multiDrawInstances = null; + this._matricesTexture = null; + this._indirectTexture = null; + this._colorsTexture = null; + this._initMatricesTexture(); + this._initIndirectTexture(); + } + _initMatricesTexture() { + let size = Math.sqrt(this._maxInstanceCount * 4); + size = Math.ceil(size / 4) * 4; + size = Math.max(size, 4); + const matricesArray = new Float32Array(size * size * 4); + const matricesTexture = new DataTexture2(matricesArray, size, size, RGBAFormat2, FloatType2); + this._matricesTexture = matricesTexture; + } + _initIndirectTexture() { + let size = Math.sqrt(this._maxInstanceCount); + size = Math.ceil(size); + const indirectArray = new Uint32Array(size * size); + const indirectTexture = new DataTexture2(indirectArray, size, size, RedIntegerFormat2, UnsignedIntType2); + this._indirectTexture = indirectTexture; + } + _initColorsTexture() { + let size = Math.sqrt(this._maxInstanceCount); + size = Math.ceil(size); + const colorsArray = new Float32Array(size * size * 4).fill(1); + const colorsTexture = new DataTexture2(colorsArray, size, size, RGBAFormat2, FloatType2); + colorsTexture.colorSpace = ColorManagement2.workingColorSpace; + this._colorsTexture = colorsTexture; + } + _initializeGeometry(reference) { + const geometry = this.geometry; + const maxVertexCount = this._maxVertexCount; + const maxIndexCount = this._maxIndexCount; + if (this._geometryInitialized === false) { + for (const attributeName in reference.attributes) { + const srcAttribute = reference.getAttribute(attributeName); + const { array, itemSize, normalized } = srcAttribute; + const dstArray = new array.constructor(maxVertexCount * itemSize); + const dstAttribute = new BufferAttribute2(dstArray, itemSize, normalized); + geometry.setAttribute(attributeName, dstAttribute); + } + if (reference.getIndex() !== null) { + const indexArray = maxVertexCount > 65535 ? new Uint32Array(maxIndexCount) : new Uint16Array(maxIndexCount); + geometry.setIndex(new BufferAttribute2(indexArray, 1)); + } + this._geometryInitialized = true; + } + } + _validateGeometry(geometry) { + const batchGeometry = this.geometry; + if (Boolean(geometry.getIndex()) !== Boolean(batchGeometry.getIndex())) { + throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".'); + } + for (const attributeName in batchGeometry.attributes) { + if (!geometry.hasAttribute(attributeName)) { + throw new Error(`THREE.BatchedMesh: Added geometry missing "${attributeName}". All geometries must have consistent attributes.`); + } + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + if (srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized) { + throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value."); + } + } + } + validateInstanceId(instanceId) { + const instanceInfo = this._instanceInfo; + if (instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[instanceId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.`); + } + } + validateGeometryId(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.`); + } + } + setCustomSort(func) { + this.customSort = func; + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box32; + } + const boundingBox = this.boundingBox; + const instanceInfo = this._instanceInfo; + boundingBox.makeEmpty(); + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].active === false) + continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$12); + this.getBoundingBoxAt(geometryId, _box$12).applyMatrix4(_matrix$12); + boundingBox.union(_box$12); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere2; + } + const boundingSphere = this.boundingSphere; + const instanceInfo = this._instanceInfo; + boundingSphere.makeEmpty(); + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].active === false) + continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$12); + this.getBoundingSphereAt(geometryId, _sphere$22).applyMatrix4(_matrix$12); + boundingSphere.union(_sphere$22); + } + } + addInstance(geometryId) { + const atCapacity = this._instanceInfo.length >= this.maxInstanceCount; + if (atCapacity && this._availableInstanceIds.length === 0) { + throw new Error("THREE.BatchedMesh: Maximum item count reached."); + } + const instanceInfo = { + visible: true, + active: true, + geometryIndex: geometryId + }; + let drawId = null; + if (this._availableInstanceIds.length > 0) { + this._availableInstanceIds.sort(ascIdSort2); + drawId = this._availableInstanceIds.shift(); + this._instanceInfo[drawId] = instanceInfo; + } else { + drawId = this._instanceInfo.length; + this._instanceInfo.push(instanceInfo); + } + const matricesTexture = this._matricesTexture; + _matrix$12.identity().toArray(matricesTexture.image.data, drawId * 16); + matricesTexture.needsUpdate = true; + const colorsTexture = this._colorsTexture; + if (colorsTexture) { + _whiteColor2.toArray(colorsTexture.image.data, drawId * 4); + colorsTexture.needsUpdate = true; + } + this._visibilityChanged = true; + return drawId; + } + addGeometry(geometry, reservedVertexCount = -1, reservedIndexCount = -1) { + this._initializeGeometry(geometry); + this._validateGeometry(geometry); + const geometryInfo = { + vertexStart: -1, + vertexCount: -1, + reservedVertexCount: -1, + indexStart: -1, + indexCount: -1, + reservedIndexCount: -1, + start: -1, + count: -1, + boundingBox: null, + boundingSphere: null, + active: true + }; + const geometryInfoList = this._geometryInfo; + geometryInfo.vertexStart = this._nextVertexStart; + geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute("position").count : reservedVertexCount; + const index2 = geometry.getIndex(); + const hasIndex = index2 !== null; + if (hasIndex) { + geometryInfo.indexStart = this._nextIndexStart; + geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index2.count : reservedIndexCount; + } + if (geometryInfo.indexStart !== -1 && geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount || geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size."); + } + let geometryId; + if (this._availableGeometryIds.length > 0) { + this._availableGeometryIds.sort(ascIdSort2); + geometryId = this._availableGeometryIds.shift(); + geometryInfoList[geometryId] = geometryInfo; + } else { + geometryId = this._geometryCount; + this._geometryCount++; + geometryInfoList.push(geometryInfo); + } + this.setGeometryAt(geometryId, geometry); + this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + return geometryId; + } + setGeometryAt(geometryId, geometry) { + if (geometryId >= this._geometryCount) { + throw new Error("THREE.BatchedMesh: Maximum geometry count reached."); + } + this._validateGeometry(geometry); + const batchGeometry = this.geometry; + const hasIndex = batchGeometry.getIndex() !== null; + const dstIndex = batchGeometry.getIndex(); + const srcIndex = geometry.getIndex(); + const geometryInfo = this._geometryInfo[geometryId]; + if (hasIndex && srcIndex.count > geometryInfo.reservedIndexCount || geometry.attributes.position.count > geometryInfo.reservedVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry."); + } + const vertexStart = geometryInfo.vertexStart; + const reservedVertexCount = geometryInfo.reservedVertexCount; + geometryInfo.vertexCount = geometry.getAttribute("position").count; + for (const attributeName in batchGeometry.attributes) { + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + copyAttributeData2(srcAttribute, dstAttribute, vertexStart); + const itemSize = srcAttribute.itemSize; + for (let i = srcAttribute.count, l = reservedVertexCount;i < l; i++) { + const index2 = vertexStart + i; + for (let c = 0;c < itemSize; c++) { + dstAttribute.setComponent(index2, c, 0); + } + } + dstAttribute.needsUpdate = true; + dstAttribute.addUpdateRange(vertexStart * itemSize, reservedVertexCount * itemSize); + } + if (hasIndex) { + const indexStart = geometryInfo.indexStart; + const reservedIndexCount = geometryInfo.reservedIndexCount; + geometryInfo.indexCount = geometry.getIndex().count; + for (let i = 0;i < srcIndex.count; i++) { + dstIndex.setX(indexStart + i, vertexStart + srcIndex.getX(i)); + } + for (let i = srcIndex.count, l = reservedIndexCount;i < l; i++) { + dstIndex.setX(indexStart + i, vertexStart); + } + dstIndex.needsUpdate = true; + dstIndex.addUpdateRange(indexStart, geometryInfo.reservedIndexCount); + } + geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart; + geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount; + geometryInfo.boundingBox = null; + if (geometry.boundingBox !== null) { + geometryInfo.boundingBox = geometry.boundingBox.clone(); + } + geometryInfo.boundingSphere = null; + if (geometry.boundingSphere !== null) { + geometryInfo.boundingSphere = geometry.boundingSphere.clone(); + } + this._visibilityChanged = true; + return geometryId; + } + deleteGeometry(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + return this; + } + const instanceInfo = this._instanceInfo; + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].active && instanceInfo[i].geometryIndex === geometryId) { + this.deleteInstance(i); + } + } + geometryInfoList[geometryId].active = false; + this._availableGeometryIds.push(geometryId); + this._visibilityChanged = true; + return this; + } + deleteInstance(instanceId) { + this.validateInstanceId(instanceId); + this._instanceInfo[instanceId].active = false; + this._availableInstanceIds.push(instanceId); + this._visibilityChanged = true; + return this; + } + optimize() { + let nextVertexStart = 0; + let nextIndexStart = 0; + const geometryInfoList = this._geometryInfo; + const indices = geometryInfoList.map((e, i) => i).sort((a, b) => { + return geometryInfoList[a].vertexStart - geometryInfoList[b].vertexStart; + }); + const geometry = this.geometry; + for (let i = 0, l = geometryInfoList.length;i < l; i++) { + const index2 = indices[i]; + const geometryInfo = geometryInfoList[index2]; + if (geometryInfo.active === false) { + continue; + } + if (geometry.index !== null) { + if (geometryInfo.indexStart !== nextIndexStart) { + const { indexStart, vertexStart, reservedIndexCount } = geometryInfo; + const index3 = geometry.index; + const array = index3.array; + const elementDelta = nextVertexStart - vertexStart; + for (let j = indexStart;j < indexStart + reservedIndexCount; j++) { + array[j] = array[j] + elementDelta; + } + index3.array.copyWithin(nextIndexStart, indexStart, indexStart + reservedIndexCount); + index3.addUpdateRange(nextIndexStart, reservedIndexCount); + geometryInfo.indexStart = nextIndexStart; + } + nextIndexStart += geometryInfo.reservedIndexCount; + } + if (geometryInfo.vertexStart !== nextVertexStart) { + const { vertexStart, reservedVertexCount } = geometryInfo; + const attributes = geometry.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + const { array, itemSize } = attribute; + array.copyWithin(nextVertexStart * itemSize, vertexStart * itemSize, (vertexStart + reservedVertexCount) * itemSize); + attribute.addUpdateRange(nextVertexStart * itemSize, reservedVertexCount * itemSize); + } + geometryInfo.vertexStart = nextVertexStart; + } + nextVertexStart += geometryInfo.reservedVertexCount; + geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart; + this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + } + return this; + } + getBoundingBoxAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingBox === null) { + const box = new Box32; + const index2 = geometry.index; + const position2 = geometry.attributes.position; + for (let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count;i < l; i++) { + let iv = i; + if (index2) { + iv = index2.getX(iv); + } + box.expandByPoint(_vector$52.fromBufferAttribute(position2, iv)); + } + geometryInfo.boundingBox = box; + } + target.copy(geometryInfo.boundingBox); + return target; + } + getBoundingSphereAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingSphere === null) { + const sphere = new Sphere2; + this.getBoundingBoxAt(geometryId, _box$12); + _box$12.getCenter(sphere.center); + const index2 = geometry.index; + const position2 = geometry.attributes.position; + let maxRadiusSq = 0; + for (let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count;i < l; i++) { + let iv = i; + if (index2) { + iv = index2.getX(iv); + } + _vector$52.fromBufferAttribute(position2, iv); + maxRadiusSq = Math.max(maxRadiusSq, sphere.center.distanceToSquared(_vector$52)); + } + sphere.radius = Math.sqrt(maxRadiusSq); + geometryInfo.boundingSphere = sphere; + } + target.copy(geometryInfo.boundingSphere); + return target; + } + setMatrixAt(instanceId, matrix) { + this.validateInstanceId(instanceId); + const matricesTexture = this._matricesTexture; + const matricesArray = this._matricesTexture.image.data; + matrix.toArray(matricesArray, instanceId * 16); + matricesTexture.needsUpdate = true; + return this; + } + getMatrixAt(instanceId, matrix) { + this.validateInstanceId(instanceId); + return matrix.fromArray(this._matricesTexture.image.data, instanceId * 16); + } + setColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + if (this._colorsTexture === null) { + this._initColorsTexture(); + } + color.toArray(this._colorsTexture.image.data, instanceId * 4); + this._colorsTexture.needsUpdate = true; + return this; + } + getColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + return color.fromArray(this._colorsTexture.image.data, instanceId * 4); + } + setVisibleAt(instanceId, value2) { + this.validateInstanceId(instanceId); + if (this._instanceInfo[instanceId].visible === value2) { + return this; + } + this._instanceInfo[instanceId].visible = value2; + this._visibilityChanged = true; + return this; + } + getVisibleAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].visible; + } + setGeometryIdAt(instanceId, geometryId) { + this.validateInstanceId(instanceId); + this.validateGeometryId(geometryId); + this._instanceInfo[instanceId].geometryIndex = geometryId; + return this; + } + getGeometryIdAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].geometryIndex; + } + getGeometryRangeAt(geometryId, target = {}) { + this.validateGeometryId(geometryId); + const geometryInfo = this._geometryInfo[geometryId]; + target.vertexStart = geometryInfo.vertexStart; + target.vertexCount = geometryInfo.vertexCount; + target.reservedVertexCount = geometryInfo.reservedVertexCount; + target.indexStart = geometryInfo.indexStart; + target.indexCount = geometryInfo.indexCount; + target.reservedIndexCount = geometryInfo.reservedIndexCount; + target.start = geometryInfo.start; + target.count = geometryInfo.count; + return target; + } + setInstanceCount(maxInstanceCount) { + const availableInstanceIds = this._availableInstanceIds; + const instanceInfo = this._instanceInfo; + availableInstanceIds.sort(ascIdSort2); + while (availableInstanceIds[availableInstanceIds.length - 1] === instanceInfo.length) { + instanceInfo.pop(); + availableInstanceIds.pop(); + } + if (maxInstanceCount < instanceInfo.length) { + throw new Error(`BatchedMesh: Instance ids outside the range ${maxInstanceCount} are being used. Cannot shrink instance count.`); + } + const multiDrawCounts = new Int32Array(maxInstanceCount); + const multiDrawStarts = new Int32Array(maxInstanceCount); + copyArrayContents2(this._multiDrawCounts, multiDrawCounts); + copyArrayContents2(this._multiDrawStarts, multiDrawStarts); + this._multiDrawCounts = multiDrawCounts; + this._multiDrawStarts = multiDrawStarts; + this._maxInstanceCount = maxInstanceCount; + const indirectTexture = this._indirectTexture; + const matricesTexture = this._matricesTexture; + const colorsTexture = this._colorsTexture; + indirectTexture.dispose(); + this._initIndirectTexture(); + copyArrayContents2(indirectTexture.image.data, this._indirectTexture.image.data); + matricesTexture.dispose(); + this._initMatricesTexture(); + copyArrayContents2(matricesTexture.image.data, this._matricesTexture.image.data); + if (colorsTexture) { + colorsTexture.dispose(); + this._initColorsTexture(); + copyArrayContents2(colorsTexture.image.data, this._colorsTexture.image.data); + } + } + setGeometrySize(maxVertexCount, maxIndexCount) { + const validRanges = [...this._geometryInfo].filter((info) => info.active); + const requiredVertexLength = Math.max(...validRanges.map((range) => range.vertexStart + range.reservedVertexCount)); + if (requiredVertexLength > maxVertexCount) { + throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + if (this.geometry.index) { + const requiredIndexLength = Math.max(...validRanges.map((range) => range.indexStart + range.reservedIndexCount)); + if (requiredIndexLength > maxIndexCount) { + throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + } + const oldGeometry = this.geometry; + oldGeometry.dispose(); + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + if (this._geometryInitialized) { + this._geometryInitialized = false; + this.geometry = new BufferGeometry2; + this._initializeGeometry(oldGeometry); + } + const geometry = this.geometry; + if (oldGeometry.index) { + copyArrayContents2(oldGeometry.index.array, geometry.index.array); + } + for (const key2 in oldGeometry.attributes) { + copyArrayContents2(oldGeometry.attributes[key2].array, geometry.attributes[key2].array); + } + } + raycast(raycaster, intersects3) { + const instanceInfo = this._instanceInfo; + const geometryInfoList = this._geometryInfo; + const matrixWorld = this.matrixWorld; + const batchGeometry = this.geometry; + _mesh2.material = this.material; + _mesh2.geometry.index = batchGeometry.index; + _mesh2.geometry.attributes = batchGeometry.attributes; + if (_mesh2.geometry.boundingBox === null) { + _mesh2.geometry.boundingBox = new Box32; + } + if (_mesh2.geometry.boundingSphere === null) { + _mesh2.geometry.boundingSphere = new Sphere2; + } + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (!instanceInfo[i].visible || !instanceInfo[i].active) { + continue; + } + const geometryId = instanceInfo[i].geometryIndex; + const geometryInfo = geometryInfoList[geometryId]; + _mesh2.geometry.setDrawRange(geometryInfo.start, geometryInfo.count); + this.getMatrixAt(i, _mesh2.matrixWorld).premultiply(matrixWorld); + this.getBoundingBoxAt(geometryId, _mesh2.geometry.boundingBox); + this.getBoundingSphereAt(geometryId, _mesh2.geometry.boundingSphere); + _mesh2.raycast(raycaster, _batchIntersects2); + for (let j = 0, l2 = _batchIntersects2.length;j < l2; j++) { + const intersect3 = _batchIntersects2[j]; + intersect3.object = this; + intersect3.batchId = i; + intersects3.push(intersect3); + } + _batchIntersects2.length = 0; + } + _mesh2.material = null; + _mesh2.geometry.index = null; + _mesh2.geometry.attributes = {}; + _mesh2.geometry.setDrawRange(0, Infinity); + } + copy(source) { + super.copy(source); + this.geometry = source.geometry.clone(); + this.perObjectFrustumCulled = source.perObjectFrustumCulled; + this.sortObjects = source.sortObjects; + this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null; + this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null; + this._geometryInfo = source._geometryInfo.map((info) => ({ + ...info, + boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null, + boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null + })); + this._instanceInfo = source._instanceInfo.map((info) => ({ ...info })); + this._maxInstanceCount = source._maxInstanceCount; + this._maxVertexCount = source._maxVertexCount; + this._maxIndexCount = source._maxIndexCount; + this._geometryInitialized = source._geometryInitialized; + this._geometryCount = source._geometryCount; + this._multiDrawCounts = source._multiDrawCounts.slice(); + this._multiDrawStarts = source._multiDrawStarts.slice(); + this._matricesTexture = source._matricesTexture.clone(); + this._matricesTexture.image.data = this._matricesTexture.image.data.slice(); + if (this._colorsTexture !== null) { + this._colorsTexture = source._colorsTexture.clone(); + this._colorsTexture.image.data = this._colorsTexture.image.data.slice(); + } + return this; + } + dispose() { + this.geometry.dispose(); + this._matricesTexture.dispose(); + this._matricesTexture = null; + this._indirectTexture.dispose(); + this._indirectTexture = null; + if (this._colorsTexture !== null) { + this._colorsTexture.dispose(); + this._colorsTexture = null; + } + return this; + } + onBeforeRender(renderer2, scene, camera, geometry, material) { + if (!this._visibilityChanged && !this.perObjectFrustumCulled && !this.sortObjects) { + return; + } + const index2 = geometry.getIndex(); + const bytesPerElement = index2 === null ? 1 : index2.array.BYTES_PER_ELEMENT; + const instanceInfo = this._instanceInfo; + const multiDrawStarts = this._multiDrawStarts; + const multiDrawCounts = this._multiDrawCounts; + const geometryInfoList = this._geometryInfo; + const perObjectFrustumCulled = this.perObjectFrustumCulled; + const indirectTexture = this._indirectTexture; + const indirectArray = indirectTexture.image.data; + if (perObjectFrustumCulled) { + _matrix$12.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).multiply(this.matrixWorld); + _frustum2.setFromProjectionMatrix(_matrix$12, renderer2.coordinateSystem); + } + let multiDrawCount = 0; + if (this.sortObjects) { + _matrix$12.copy(this.matrixWorld).invert(); + _vector$52.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(_matrix$12); + _forward2.set(0, 0, -1).transformDirection(camera.matrixWorld).transformDirection(_matrix$12); + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$12); + this.getBoundingSphereAt(geometryId, _sphere$22).applyMatrix4(_matrix$12); + let culled = false; + if (perObjectFrustumCulled) { + culled = !_frustum2.intersectsSphere(_sphere$22); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + const z = _temp2.subVectors(_sphere$22.center, _vector$52).dot(_forward2); + _renderList2.push(geometryInfo.start, geometryInfo.count, z, i); + } + } + } + const list = _renderList2.list; + const customSort = this.customSort; + if (customSort === null) { + list.sort(material.transparent ? sortTransparent2 : sortOpaque2); + } else { + customSort.call(this, list, camera); + } + for (let i = 0, l = list.length;i < l; i++) { + const item = list[i]; + multiDrawStarts[multiDrawCount] = item.start * bytesPerElement; + multiDrawCounts[multiDrawCount] = item.count; + indirectArray[multiDrawCount] = item.index; + multiDrawCount++; + } + _renderList2.reset(); + } else { + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + let culled = false; + if (perObjectFrustumCulled) { + this.getMatrixAt(i, _matrix$12); + this.getBoundingSphereAt(geometryId, _sphere$22).applyMatrix4(_matrix$12); + culled = !_frustum2.intersectsSphere(_sphere$22); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + multiDrawStarts[multiDrawCount] = geometryInfo.start * bytesPerElement; + multiDrawCounts[multiDrawCount] = geometryInfo.count; + indirectArray[multiDrawCount] = i; + multiDrawCount++; + } + } + } + } + indirectTexture.needsUpdate = true; + this._multiDrawCount = multiDrawCount; + this._visibilityChanged = false; + } + onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial) { + this.onBeforeRender(renderer2, null, shadowCamera, geometry, depthMaterial); + } + } + + class LineBasicMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isLineBasicMaterial = true; + this.type = "LineBasicMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.linewidth = 1; + this.linecap = "round"; + this.linejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + this.fog = source.fog; + return this; + } + } + var _vStart2 = /* @__PURE__ */ new Vector32; + var _vEnd2 = /* @__PURE__ */ new Vector32; + var _inverseMatrix$12 = /* @__PURE__ */ new Matrix42; + var _ray$12 = /* @__PURE__ */ new Ray2; + var _sphere$12 = /* @__PURE__ */ new Sphere2; + var _intersectPointOnRay2 = /* @__PURE__ */ new Vector32; + var _intersectPointOnSegment2 = /* @__PURE__ */ new Vector32; + + class Line2 extends Object3D2 { + constructor(geometry = new BufferGeometry2, material = new LineBasicMaterial2) { + super(); + this.isLine = true; + this.type = "Line"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = [0]; + for (let i = 1, l = positionAttribute.count;i < l; i++) { + _vStart2.fromBufferAttribute(positionAttribute, i - 1); + _vEnd2.fromBufferAttribute(positionAttribute, i); + lineDistances[i] = lineDistances[i - 1]; + lineDistances[i] += _vStart2.distanceTo(_vEnd2); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute2(lineDistances, 1)); + } else { + console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + raycast(raycaster, intersects3) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$12.copy(geometry.boundingSphere); + _sphere$12.applyMatrix4(matrixWorld); + _sphere$12.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere$12) === false) + return; + _inverseMatrix$12.copy(matrixWorld).invert(); + _ray$12.copy(raycaster.ray).applyMatrix4(_inverseMatrix$12); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const step = this.isLineSegments ? 2 : 1; + const index2 = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index2 !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, l = end - 1;i < l; i += step) { + const a = index2.getX(i); + const b = index2.getX(i + 1); + const intersect3 = checkIntersection2(this, raycaster, _ray$12, localThresholdSq, a, b, i); + if (intersect3) { + intersects3.push(intersect3); + } + } + if (this.isLineLoop) { + const a = index2.getX(end - 1); + const b = index2.getX(start); + const intersect3 = checkIntersection2(this, raycaster, _ray$12, localThresholdSq, a, b, end - 1); + if (intersect3) { + intersects3.push(intersect3); + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l = end - 1;i < l; i += step) { + const intersect3 = checkIntersection2(this, raycaster, _ray$12, localThresholdSq, i, i + 1, i); + if (intersect3) { + intersects3.push(intersect3); + } + } + if (this.isLineLoop) { + const intersect3 = checkIntersection2(this, raycaster, _ray$12, localThresholdSq, end - 1, start, end - 1); + if (intersect3) { + intersects3.push(intersect3); + } + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } + } + function checkIntersection2(object, raycaster, ray, thresholdSq, a, b, i) { + const positionAttribute = object.geometry.attributes.position; + _vStart2.fromBufferAttribute(positionAttribute, a); + _vEnd2.fromBufferAttribute(positionAttribute, b); + const distSq = ray.distanceSqToSegment(_vStart2, _vEnd2, _intersectPointOnRay2, _intersectPointOnSegment2); + if (distSq > thresholdSq) + return; + _intersectPointOnRay2.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectPointOnRay2); + if (distance < raycaster.near || distance > raycaster.far) + return; + return { + distance, + point: _intersectPointOnSegment2.clone().applyMatrix4(object.matrixWorld), + index: i, + face: null, + faceIndex: null, + barycoord: null, + object + }; + } + var _start2 = /* @__PURE__ */ new Vector32; + var _end2 = /* @__PURE__ */ new Vector32; + + class LineSegments2 extends Line2 { + constructor(geometry, material) { + super(geometry, material); + this.isLineSegments = true; + this.type = "LineSegments"; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + for (let i = 0, l = positionAttribute.count;i < l; i += 2) { + _start2.fromBufferAttribute(positionAttribute, i); + _end2.fromBufferAttribute(positionAttribute, i + 1); + lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1]; + lineDistances[i + 1] = lineDistances[i] + _start2.distanceTo(_end2); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute2(lineDistances, 1)); + } else { + console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + } + + class LineLoop2 extends Line2 { + constructor(geometry, material) { + super(geometry, material); + this.isLineLoop = true; + this.type = "LineLoop"; + } + } + + class PointsMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isPointsMaterial = true; + this.type = "PointsMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.alphaMap = null; + this.size = 1; + this.sizeAttenuation = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } + } + var _inverseMatrix2 = /* @__PURE__ */ new Matrix42; + var _ray2 = /* @__PURE__ */ new Ray2; + var _sphere2 = /* @__PURE__ */ new Sphere2; + var _position$22 = /* @__PURE__ */ new Vector32; + + class Points2 extends Object3D2 { + constructor(geometry = new BufferGeometry2, material = new PointsMaterial2) { + super(); + this.isPoints = true; + this.type = "Points"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + raycast(raycaster, intersects3) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere2.copy(geometry.boundingSphere); + _sphere2.applyMatrix4(matrixWorld); + _sphere2.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere2) === false) + return; + _inverseMatrix2.copy(matrixWorld).invert(); + _ray2.copy(raycaster.ray).applyMatrix4(_inverseMatrix2); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const index2 = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index2 !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i++) { + const a = index2.getX(i); + _position$22.fromBufferAttribute(positionAttribute, a); + testPoint2(_position$22, a, localThresholdSq, matrixWorld, raycaster, intersects3, this); + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l = end;i < l; i++) { + _position$22.fromBufferAttribute(positionAttribute, i); + testPoint2(_position$22, i, localThresholdSq, matrixWorld, raycaster, intersects3, this); + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } + } + function testPoint2(point, index2, localThresholdSq, matrixWorld, raycaster, intersects3, object) { + const rayPointDistanceSq = _ray2.distanceSqToPoint(point); + if (rayPointDistanceSq < localThresholdSq) { + const intersectPoint = new Vector32; + _ray2.closestPointToPoint(point, intersectPoint); + intersectPoint.applyMatrix4(matrixWorld); + const distance = raycaster.ray.origin.distanceTo(intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) + return; + intersects3.push({ + distance, + distanceToRay: Math.sqrt(rayPointDistanceSq), + point: intersectPoint, + index: index2, + face: null, + faceIndex: null, + barycoord: null, + object + }); + } + } + + class VideoTexture2 extends Texture2 { + constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoTexture = true; + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter2; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter2; + this.generateMipmaps = false; + const scope = this; + function updateVideo() { + scope.needsUpdate = true; + video.requestVideoFrameCallback(updateVideo); + } + if ("requestVideoFrameCallback" in video) { + video.requestVideoFrameCallback(updateVideo); + } + } + clone() { + return new this.constructor(this.image).copy(this); + } + update() { + const video = this.image; + const hasVideoFrameCallback = "requestVideoFrameCallback" in video; + if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) { + this.needsUpdate = true; + } + } + } + + class VideoFrameTexture2 extends VideoTexture2 { + constructor(mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super({}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoFrameTexture = true; + } + update() { + } + clone() { + return new this.constructor().copy(this); + } + setFrame(frame) { + this.image = frame; + this.needsUpdate = true; + } + } + + class FramebufferTexture2 extends Texture2 { + constructor(width2, height2) { + super({ width: width2, height: height2 }); + this.isFramebufferTexture = true; + this.magFilter = NearestFilter2; + this.minFilter = NearestFilter2; + this.generateMipmaps = false; + this.needsUpdate = true; + } + } + + class CompressedTexture2 extends Texture2 { + constructor(mipmaps, width2, height2, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCompressedTexture = true; + this.image = { width: width2, height: height2 }; + this.mipmaps = mipmaps; + this.flipY = false; + this.generateMipmaps = false; + } + } + + class CompressedArrayTexture2 extends CompressedTexture2 { + constructor(mipmaps, width2, height2, depth, format, type) { + super(mipmaps, width2, height2, format, type); + this.isCompressedArrayTexture = true; + this.image.depth = depth; + this.wrapR = ClampToEdgeWrapping2; + this.layerUpdates = new Set; + } + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + clearLayerUpdates() { + this.layerUpdates.clear(); + } + } + + class CompressedCubeTexture2 extends CompressedTexture2 { + constructor(images, format, type) { + super(undefined, images[0].width, images[0].height, format, type, CubeReflectionMapping2); + this.isCompressedCubeTexture = true; + this.isCubeTexture = true; + this.image = images; + } + } + + class CanvasTexture2 extends Texture2 { + constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isCanvasTexture = true; + this.needsUpdate = true; + } + } + + class DepthTexture2 extends Texture2 { + constructor(width2, height2, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat2) { + if (format !== DepthFormat2 && format !== DepthStencilFormat2) { + throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); + } + if (type === undefined && format === DepthFormat2) + type = UnsignedIntType2; + if (type === undefined && format === DepthStencilFormat2) + type = UnsignedInt248Type2; + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isDepthTexture = true; + this.image = { width: width2, height: height2 }; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter2; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter2; + this.flipY = false; + this.generateMipmaps = false; + this.compareFunction = null; + } + copy(source) { + super.copy(source); + this.compareFunction = source.compareFunction; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + if (this.compareFunction !== null) + data2.compareFunction = this.compareFunction; + return data2; + } + } + + class Curve2 { + constructor() { + this.type = "Curve"; + this.arcLengthDivisions = 200; + } + getPoint() { + console.warn("THREE.Curve: .getPoint() not implemented."); + return null; + } + getPointAt(u, optionalTarget) { + const t = this.getUtoTmapping(u); + return this.getPoint(t, optionalTarget); + } + getPoints(divisions = 5) { + const points = []; + for (let d = 0;d <= divisions; d++) { + points.push(this.getPoint(d / divisions)); + } + return points; + } + getSpacedPoints(divisions = 5) { + const points = []; + for (let d = 0;d <= divisions; d++) { + points.push(this.getPointAt(d / divisions)); + } + return points; + } + getLength() { + const lengths = this.getLengths(); + return lengths[lengths.length - 1]; + } + getLengths(divisions = this.arcLengthDivisions) { + if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) { + return this.cacheArcLengths; + } + this.needsUpdate = false; + const cache = []; + let current, last2 = this.getPoint(0); + let sum2 = 0; + cache.push(0); + for (let p = 1;p <= divisions; p++) { + current = this.getPoint(p / divisions); + sum2 += current.distanceTo(last2); + cache.push(sum2); + last2 = current; + } + this.cacheArcLengths = cache; + return cache; + } + updateArcLengths() { + this.needsUpdate = true; + this.getLengths(); + } + getUtoTmapping(u, distance) { + const arcLengths = this.getLengths(); + let i = 0; + const il = arcLengths.length; + let targetArcLength; + if (distance) { + targetArcLength = distance; + } else { + targetArcLength = u * arcLengths[il - 1]; + } + let low = 0, high = il - 1, comparison; + while (low <= high) { + i = Math.floor(low + (high - low) / 2); + comparison = arcLengths[i] - targetArcLength; + if (comparison < 0) { + low = i + 1; + } else if (comparison > 0) { + high = i - 1; + } else { + high = i; + break; + } + } + i = high; + if (arcLengths[i] === targetArcLength) { + return i / (il - 1); + } + const lengthBefore = arcLengths[i]; + const lengthAfter = arcLengths[i + 1]; + const segmentLength = lengthAfter - lengthBefore; + const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; + const t = (i + segmentFraction) / (il - 1); + return t; + } + getTangent(t, optionalTarget) { + const delta = 0.0001; + let t1 = t - delta; + let t2 = t + delta; + if (t1 < 0) + t1 = 0; + if (t2 > 1) + t2 = 1; + const pt1 = this.getPoint(t1); + const pt2 = this.getPoint(t2); + const tangent = optionalTarget || (pt1.isVector2 ? new Vector22 : new Vector32); + tangent.copy(pt2).sub(pt1).normalize(); + return tangent; + } + getTangentAt(u, optionalTarget) { + const t = this.getUtoTmapping(u); + return this.getTangent(t, optionalTarget); + } + computeFrenetFrames(segments, closed) { + const normal = new Vector32; + const tangents = []; + const normals = []; + const binormals = []; + const vec = new Vector32; + const mat = new Matrix42; + for (let i = 0;i <= segments; i++) { + const u = i / segments; + tangents[i] = this.getTangentAt(u, new Vector32); + } + normals[0] = new Vector32; + binormals[0] = new Vector32; + let min = Number.MAX_VALUE; + const tx = Math.abs(tangents[0].x); + const ty = Math.abs(tangents[0].y); + const tz = Math.abs(tangents[0].z); + if (tx <= min) { + min = tx; + normal.set(1, 0, 0); + } + if (ty <= min) { + min = ty; + normal.set(0, 1, 0); + } + if (tz <= min) { + normal.set(0, 0, 1); + } + vec.crossVectors(tangents[0], normal).normalize(); + normals[0].crossVectors(tangents[0], vec); + binormals[0].crossVectors(tangents[0], normals[0]); + for (let i = 1;i <= segments; i++) { + normals[i] = normals[i - 1].clone(); + binormals[i] = binormals[i - 1].clone(); + vec.crossVectors(tangents[i - 1], tangents[i]); + if (vec.length() > Number.EPSILON) { + vec.normalize(); + const theta = Math.acos(clamp3(tangents[i - 1].dot(tangents[i]), -1, 1)); + normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta)); + } + binormals[i].crossVectors(tangents[i], normals[i]); + } + if (closed === true) { + let theta = Math.acos(clamp3(normals[0].dot(normals[segments]), -1, 1)); + theta /= segments; + if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) { + theta = -theta; + } + for (let i = 1;i <= segments; i++) { + normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i)); + binormals[i].crossVectors(tangents[i], normals[i]); + } + } + return { + tangents, + normals, + binormals + }; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.arcLengthDivisions = source.arcLengthDivisions; + return this; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "Curve", + generator: "Curve.toJSON" + } + }; + data2.arcLengthDivisions = this.arcLengthDivisions; + data2.type = this.type; + return data2; + } + fromJSON(json) { + this.arcLengthDivisions = json.arcLengthDivisions; + return this; + } + } + + class EllipseCurve2 extends Curve2 { + constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) { + super(); + this.isEllipseCurve = true; + this.type = "EllipseCurve"; + this.aX = aX; + this.aY = aY; + this.xRadius = xRadius; + this.yRadius = yRadius; + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; + this.aClockwise = aClockwise; + this.aRotation = aRotation; + } + getPoint(t, optionalTarget = new Vector22) { + const point = optionalTarget; + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs(deltaAngle) < Number.EPSILON; + while (deltaAngle < 0) + deltaAngle += twoPi; + while (deltaAngle > twoPi) + deltaAngle -= twoPi; + if (deltaAngle < Number.EPSILON) { + if (samePoints) { + deltaAngle = 0; + } else { + deltaAngle = twoPi; + } + } + if (this.aClockwise === true && !samePoints) { + if (deltaAngle === twoPi) { + deltaAngle = -twoPi; + } else { + deltaAngle = deltaAngle - twoPi; + } + } + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos(angle); + let y = this.aY + this.yRadius * Math.sin(angle); + if (this.aRotation !== 0) { + const cos = Math.cos(this.aRotation); + const sin = Math.sin(this.aRotation); + const tx = x - this.aX; + const ty = y - this.aY; + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; + } + return point.set(x, y); + } + copy(source) { + super.copy(source); + this.aX = source.aX; + this.aY = source.aY; + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + this.aClockwise = source.aClockwise; + this.aRotation = source.aRotation; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.aX = this.aX; + data2.aY = this.aY; + data2.xRadius = this.xRadius; + data2.yRadius = this.yRadius; + data2.aStartAngle = this.aStartAngle; + data2.aEndAngle = this.aEndAngle; + data2.aClockwise = this.aClockwise; + data2.aRotation = this.aRotation; + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.aX = json.aX; + this.aY = json.aY; + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + this.aClockwise = json.aClockwise; + this.aRotation = json.aRotation; + return this; + } + } + + class ArcCurve2 extends EllipseCurve2 { + constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + this.isArcCurve = true; + this.type = "ArcCurve"; + } + } + function CubicPoly2() { + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + function init(x0, x1, t0, t1) { + c0 = x0; + c1 = t0; + c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + } + return { + initCatmullRom: function(x0, x1, x2, x3, tension) { + init(x1, x2, tension * (x2 - x0), tension * (x3 - x1)); + }, + initNonuniformCatmullRom: function(x0, x1, x2, x3, dt0, dt1, dt2) { + let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1; + let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; + t1 *= dt1; + t2 *= dt1; + init(x1, x2, t1, t2); + }, + calc: function(t) { + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; + } + }; + } + var tmp2 = /* @__PURE__ */ new Vector32; + var px2 = /* @__PURE__ */ new CubicPoly2; + var py2 = /* @__PURE__ */ new CubicPoly2; + var pz2 = /* @__PURE__ */ new CubicPoly2; + + class CatmullRomCurve32 extends Curve2 { + constructor(points = [], closed = false, curveType = "centripetal", tension = 0.5) { + super(); + this.isCatmullRomCurve3 = true; + this.type = "CatmullRomCurve3"; + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + } + getPoint(t, optionalTarget = new Vector32) { + const point = optionalTarget; + const points = this.points; + const l = points.length; + const p = (l - (this.closed ? 0 : 1)) * t; + let intPoint = Math.floor(p); + let weight = p - intPoint; + if (this.closed) { + intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l; + } else if (weight === 0 && intPoint === l - 1) { + intPoint = l - 2; + weight = 1; + } + let p0, p3; + if (this.closed || intPoint > 0) { + p0 = points[(intPoint - 1) % l]; + } else { + tmp2.subVectors(points[0], points[1]).add(points[0]); + p0 = tmp2; + } + const p1 = points[intPoint % l]; + const p2 = points[(intPoint + 1) % l]; + if (this.closed || intPoint + 2 < l) { + p3 = points[(intPoint + 2) % l]; + } else { + tmp2.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]); + p3 = tmp2; + } + if (this.curveType === "centripetal" || this.curveType === "chordal") { + const pow = this.curveType === "chordal" ? 0.5 : 0.25; + let dt0 = Math.pow(p0.distanceToSquared(p1), pow); + let dt1 = Math.pow(p1.distanceToSquared(p2), pow); + let dt2 = Math.pow(p2.distanceToSquared(p3), pow); + if (dt1 < 0.0001) + dt1 = 1; + if (dt0 < 0.0001) + dt0 = dt1; + if (dt2 < 0.0001) + dt2 = dt1; + px2.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2); + py2.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2); + pz2.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2); + } else if (this.curveType === "catmullrom") { + px2.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension); + py2.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension); + pz2.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension); + } + point.set(px2.calc(weight), py2.calc(weight), pz2.calc(weight)); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l = source.points.length;i < l; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.points = []; + for (let i = 0, l = this.points.length;i < l; i++) { + const point = this.points[i]; + data2.points.push(point.toArray()); + } + data2.closed = this.closed; + data2.curveType = this.curveType; + data2.tension = this.tension; + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l = json.points.length;i < l; i++) { + const point = json.points[i]; + this.points.push(new Vector32().fromArray(point)); + } + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + return this; + } + } + function CatmullRom2(t, p0, p1, p2, p3) { + const v0 = (p2 - p0) * 0.5; + const v1 = (p3 - p1) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + } + function QuadraticBezierP02(t, p) { + const k = 1 - t; + return k * k * p; + } + function QuadraticBezierP12(t, p) { + return 2 * (1 - t) * t * p; + } + function QuadraticBezierP22(t, p) { + return t * t * p; + } + function QuadraticBezier2(t, p0, p1, p2) { + return QuadraticBezierP02(t, p0) + QuadraticBezierP12(t, p1) + QuadraticBezierP22(t, p2); + } + function CubicBezierP02(t, p) { + const k = 1 - t; + return k * k * k * p; + } + function CubicBezierP12(t, p) { + const k = 1 - t; + return 3 * k * k * t * p; + } + function CubicBezierP22(t, p) { + return 3 * (1 - t) * t * t * p; + } + function CubicBezierP32(t, p) { + return t * t * t * p; + } + function CubicBezier2(t, p0, p1, p2, p3) { + return CubicBezierP02(t, p0) + CubicBezierP12(t, p1) + CubicBezierP22(t, p2) + CubicBezierP32(t, p3); + } + + class CubicBezierCurve2 extends Curve2 { + constructor(v0 = new Vector22, v1 = new Vector22, v2 = new Vector22, v3 = new Vector22) { + super(); + this.isCubicBezierCurve = true; + this.type = "CubicBezierCurve"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + } + getPoint(t, optionalTarget = new Vector22) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + point.set(CubicBezier2(t, v0.x, v1.x, v2.x, v3.x), CubicBezier2(t, v0.y, v1.y, v2.y, v3.y)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + data2.v3 = this.v3.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } + } + + class CubicBezierCurve32 extends Curve2 { + constructor(v0 = new Vector32, v1 = new Vector32, v2 = new Vector32, v3 = new Vector32) { + super(); + this.isCubicBezierCurve3 = true; + this.type = "CubicBezierCurve3"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + } + getPoint(t, optionalTarget = new Vector32) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + point.set(CubicBezier2(t, v0.x, v1.x, v2.x, v3.x), CubicBezier2(t, v0.y, v1.y, v2.y, v3.y), CubicBezier2(t, v0.z, v1.z, v2.z, v3.z)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + data2.v3 = this.v3.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } + } + + class LineCurve2 extends Curve2 { + constructor(v1 = new Vector22, v2 = new Vector22) { + super(); + this.isLineCurve = true; + this.type = "LineCurve"; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector22) { + const point = optionalTarget; + if (t === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t).add(this.v1); + } + return point; + } + getPointAt(u, optionalTarget) { + return this.getPoint(u, optionalTarget); + } + getTangent(t, optionalTarget = new Vector22) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u, optionalTarget) { + return this.getTangent(u, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + + class LineCurve32 extends Curve2 { + constructor(v1 = new Vector32, v2 = new Vector32) { + super(); + this.isLineCurve3 = true; + this.type = "LineCurve3"; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector32) { + const point = optionalTarget; + if (t === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t).add(this.v1); + } + return point; + } + getPointAt(u, optionalTarget) { + return this.getPoint(u, optionalTarget); + } + getTangent(t, optionalTarget = new Vector32) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u, optionalTarget) { + return this.getTangent(u, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + + class QuadraticBezierCurve2 extends Curve2 { + constructor(v0 = new Vector22, v1 = new Vector22, v2 = new Vector22) { + super(); + this.isQuadraticBezierCurve = true; + this.type = "QuadraticBezierCurve"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector22) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + point.set(QuadraticBezier2(t, v0.x, v1.x, v2.x), QuadraticBezier2(t, v0.y, v1.y, v2.y)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + + class QuadraticBezierCurve32 extends Curve2 { + constructor(v0 = new Vector32, v1 = new Vector32, v2 = new Vector32) { + super(); + this.isQuadraticBezierCurve3 = true; + this.type = "QuadraticBezierCurve3"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector32) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + point.set(QuadraticBezier2(t, v0.x, v1.x, v2.x), QuadraticBezier2(t, v0.y, v1.y, v2.y), QuadraticBezier2(t, v0.z, v1.z, v2.z)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + + class SplineCurve2 extends Curve2 { + constructor(points = []) { + super(); + this.isSplineCurve = true; + this.type = "SplineCurve"; + this.points = points; + } + getPoint(t, optionalTarget = new Vector22) { + const point = optionalTarget; + const points = this.points; + const p = (points.length - 1) * t; + const intPoint = Math.floor(p); + const weight = p - intPoint; + const p0 = points[intPoint === 0 ? intPoint : intPoint - 1]; + const p1 = points[intPoint]; + const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1]; + const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2]; + point.set(CatmullRom2(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom2(weight, p0.y, p1.y, p2.y, p3.y)); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l = source.points.length;i < l; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.points = []; + for (let i = 0, l = this.points.length;i < l; i++) { + const point = this.points[i]; + data2.points.push(point.toArray()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l = json.points.length;i < l; i++) { + const point = json.points[i]; + this.points.push(new Vector22().fromArray(point)); + } + return this; + } + } + var Curves2 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ArcCurve: ArcCurve2, + CatmullRomCurve3: CatmullRomCurve32, + CubicBezierCurve: CubicBezierCurve2, + CubicBezierCurve3: CubicBezierCurve32, + EllipseCurve: EllipseCurve2, + LineCurve: LineCurve2, + LineCurve3: LineCurve32, + QuadraticBezierCurve: QuadraticBezierCurve2, + QuadraticBezierCurve3: QuadraticBezierCurve32, + SplineCurve: SplineCurve2 + }); + + class CurvePath2 extends Curve2 { + constructor() { + super(); + this.type = "CurvePath"; + this.curves = []; + this.autoClose = false; + } + add(curve) { + this.curves.push(curve); + } + closePath() { + const startPoint = this.curves[0].getPoint(0); + const endPoint = this.curves[this.curves.length - 1].getPoint(1); + if (!startPoint.equals(endPoint)) { + const lineType = startPoint.isVector2 === true ? "LineCurve" : "LineCurve3"; + this.curves.push(new Curves2[lineType](endPoint, startPoint)); + } + return this; + } + getPoint(t, optionalTarget) { + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + while (i < curveLengths.length) { + if (curveLengths[i] >= d) { + const diff = curveLengths[i] - d; + const curve = this.curves[i]; + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + return curve.getPointAt(u, optionalTarget); + } + i++; + } + return null; + } + getLength() { + const lens = this.getCurveLengths(); + return lens[lens.length - 1]; + } + updateArcLengths() { + this.needsUpdate = true; + this.cacheLengths = null; + this.getCurveLengths(); + } + getCurveLengths() { + if (this.cacheLengths && this.cacheLengths.length === this.curves.length) { + return this.cacheLengths; + } + const lengths = []; + let sums = 0; + for (let i = 0, l = this.curves.length;i < l; i++) { + sums += this.curves[i].getLength(); + lengths.push(sums); + } + this.cacheLengths = lengths; + return lengths; + } + getSpacedPoints(divisions = 40) { + const points = []; + for (let i = 0;i <= divisions; i++) { + points.push(this.getPoint(i / divisions)); + } + if (this.autoClose) { + points.push(points[0]); + } + return points; + } + getPoints(divisions = 12) { + const points = []; + let last2; + for (let i = 0, curves = this.curves;i < curves.length; i++) { + const curve = curves[i]; + const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions; + const pts = curve.getPoints(resolution); + for (let j = 0;j < pts.length; j++) { + const point = pts[j]; + if (last2 && last2.equals(point)) + continue; + points.push(point); + last2 = point; + } + } + if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) { + points.push(points[0]); + } + return points; + } + copy(source) { + super.copy(source); + this.curves = []; + for (let i = 0, l = source.curves.length;i < l; i++) { + const curve = source.curves[i]; + this.curves.push(curve.clone()); + } + this.autoClose = source.autoClose; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.autoClose = this.autoClose; + data2.curves = []; + for (let i = 0, l = this.curves.length;i < l; i++) { + const curve = this.curves[i]; + data2.curves.push(curve.toJSON()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.autoClose = json.autoClose; + this.curves = []; + for (let i = 0, l = json.curves.length;i < l; i++) { + const curve = json.curves[i]; + this.curves.push(new Curves2[curve.type]().fromJSON(curve)); + } + return this; + } + } + + class Path2 extends CurvePath2 { + constructor(points) { + super(); + this.type = "Path"; + this.currentPoint = new Vector22; + if (points) { + this.setFromPoints(points); + } + } + setFromPoints(points) { + this.moveTo(points[0].x, points[0].y); + for (let i = 1, l = points.length;i < l; i++) { + this.lineTo(points[i].x, points[i].y); + } + return this; + } + moveTo(x, y) { + this.currentPoint.set(x, y); + return this; + } + lineTo(x, y) { + const curve = new LineCurve2(this.currentPoint.clone(), new Vector22(x, y)); + this.curves.push(curve); + this.currentPoint.set(x, y); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + const curve = new QuadraticBezierCurve2(this.currentPoint.clone(), new Vector22(aCPx, aCPy), new Vector22(aX, aY)); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + const curve = new CubicBezierCurve2(this.currentPoint.clone(), new Vector22(aCP1x, aCP1y), new Vector22(aCP2x, aCP2y), new Vector22(aX, aY)); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + splineThru(pts) { + const npts = [this.currentPoint.clone()].concat(pts); + const curve = new SplineCurve2(npts); + this.curves.push(curve); + this.currentPoint.copy(pts[pts.length - 1]); + return this; + } + arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + return this; + } + absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const curve = new EllipseCurve2(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + if (this.curves.length > 0) { + const firstPoint = curve.getPoint(0); + if (!firstPoint.equals(this.currentPoint)) { + this.lineTo(firstPoint.x, firstPoint.y); + } + } + this.curves.push(curve); + const lastPoint = curve.getPoint(1); + this.currentPoint.copy(lastPoint); + return this; + } + copy(source) { + super.copy(source); + this.currentPoint.copy(source.currentPoint); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.currentPoint = this.currentPoint.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.currentPoint.fromArray(json.currentPoint); + return this; + } + } + + class LatheGeometry2 extends BufferGeometry2 { + constructor(points = [new Vector22(0, -0.5), new Vector22(0.5, 0), new Vector22(0, 0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) { + super(); + this.type = "LatheGeometry"; + this.parameters = { + points, + segments, + phiStart, + phiLength + }; + segments = Math.floor(segments); + phiLength = clamp3(phiLength, 0, Math.PI * 2); + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; + const inverseSegments = 1 / segments; + const vertex3 = new Vector32; + const uv = new Vector22; + const normal = new Vector32; + const curNormal = new Vector32; + const prevNormal = new Vector32; + let dx = 0; + let dy = 0; + for (let j = 0;j <= points.length - 1; j++) { + switch (j) { + case 0: + dx = points[j + 1].x - points[j].x; + dy = points[j + 1].y - points[j].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + prevNormal.copy(normal); + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + break; + case points.length - 1: + initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z); + break; + default: + dx = points[j + 1].x - points[j].x; + dy = points[j + 1].y - points[j].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + curNormal.copy(normal); + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + prevNormal.copy(curNormal); + } + } + for (let i = 0;i <= segments; i++) { + const phi = phiStart + i * inverseSegments * phiLength; + const sin = Math.sin(phi); + const cos = Math.cos(phi); + for (let j = 0;j <= points.length - 1; j++) { + vertex3.x = points[j].x * sin; + vertex3.y = points[j].y; + vertex3.z = points[j].x * cos; + vertices.push(vertex3.x, vertex3.y, vertex3.z); + uv.x = i / segments; + uv.y = j / (points.length - 1); + uvs.push(uv.x, uv.y); + const x = initNormals[3 * j + 0] * sin; + const y = initNormals[3 * j + 1]; + const z = initNormals[3 * j + 0] * cos; + normals.push(x, y, z); + } + } + for (let i = 0;i < segments; i++) { + for (let j = 0;j < points.length - 1; j++) { + const base = j + i * points.length; + const a = base; + const b = base + points.length; + const c = base + points.length + 1; + const d = base + 1; + indices.push(a, b, d); + indices.push(c, d, b); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new LatheGeometry2(data2.points, data2.segments, data2.phiStart, data2.phiLength); + } + } + + class CapsuleGeometry2 extends LatheGeometry2 { + constructor(radius = 1, length2 = 1, capSegments = 4, radialSegments = 8) { + const path = new Path2; + path.absarc(0, -length2 / 2, radius, Math.PI * 1.5, 0); + path.absarc(0, length2 / 2, radius, 0, Math.PI * 0.5); + super(path.getPoints(capSegments), radialSegments); + this.type = "CapsuleGeometry"; + this.parameters = { + radius, + length: length2, + capSegments, + radialSegments + }; + } + static fromJSON(data2) { + return new CapsuleGeometry2(data2.radius, data2.length, data2.capSegments, data2.radialSegments); + } + } + + class CircleGeometry2 extends BufferGeometry2 { + constructor(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CircleGeometry"; + this.parameters = { + radius, + segments, + thetaStart, + thetaLength + }; + segments = Math.max(3, segments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex3 = new Vector32; + const uv = new Vector22; + vertices.push(0, 0, 0); + normals.push(0, 0, 1); + uvs.push(0.5, 0.5); + for (let s = 0, i = 3;s <= segments; s++, i += 3) { + const segment = thetaStart + s / segments * thetaLength; + vertex3.x = radius * Math.cos(segment); + vertex3.y = radius * Math.sin(segment); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normals.push(0, 0, 1); + uv.x = (vertices[i] / radius + 1) / 2; + uv.y = (vertices[i + 1] / radius + 1) / 2; + uvs.push(uv.x, uv.y); + } + for (let i = 1;i <= segments; i++) { + indices.push(i, i + 1, 0); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new CircleGeometry2(data2.radius, data2.segments, data2.thetaStart, data2.thetaLength); + } + } + + class CylinderGeometry2 extends BufferGeometry2 { + constructor(radiusTop = 1, radiusBottom = 1, height2 = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CylinderGeometry"; + this.parameters = { + radiusTop, + radiusBottom, + height: height2, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + const scope = this; + radialSegments = Math.floor(radialSegments); + heightSegments = Math.floor(heightSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let index2 = 0; + const indexArray = []; + const halfHeight = height2 / 2; + let groupStart = 0; + generateTorso(); + if (openEnded === false) { + if (radiusTop > 0) + generateCap(true); + if (radiusBottom > 0) + generateCap(false); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function generateTorso() { + const normal = new Vector32; + const vertex3 = new Vector32; + let groupCount = 0; + const slope = (radiusBottom - radiusTop) / height2; + for (let y = 0;y <= heightSegments; y++) { + const indexRow = []; + const v = y / heightSegments; + const radius = v * (radiusBottom - radiusTop) + radiusTop; + for (let x = 0;x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const sinTheta = Math.sin(theta); + const cosTheta = Math.cos(theta); + vertex3.x = radius * sinTheta; + vertex3.y = -v * height2 + halfHeight; + vertex3.z = radius * cosTheta; + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normal.set(sinTheta, slope, cosTheta).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u, 1 - v); + indexRow.push(index2++); + } + indexArray.push(indexRow); + } + for (let x = 0;x < radialSegments; x++) { + for (let y = 0;y < heightSegments; y++) { + const a = indexArray[y][x]; + const b = indexArray[y + 1][x]; + const c = indexArray[y + 1][x + 1]; + const d = indexArray[y][x + 1]; + if (radiusTop > 0 || y !== 0) { + indices.push(a, b, d); + groupCount += 3; + } + if (radiusBottom > 0 || y !== heightSegments - 1) { + indices.push(b, c, d); + groupCount += 3; + } + } + } + scope.addGroup(groupStart, groupCount, 0); + groupStart += groupCount; + } + function generateCap(top) { + const centerIndexStart = index2; + const uv = new Vector22; + const vertex3 = new Vector32; + let groupCount = 0; + const radius = top === true ? radiusTop : radiusBottom; + const sign3 = top === true ? 1 : -1; + for (let x = 1;x <= radialSegments; x++) { + vertices.push(0, halfHeight * sign3, 0); + normals.push(0, sign3, 0); + uvs.push(0.5, 0.5); + index2++; + } + const centerIndexEnd = index2; + for (let x = 0;x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const cosTheta = Math.cos(theta); + const sinTheta = Math.sin(theta); + vertex3.x = radius * sinTheta; + vertex3.y = halfHeight * sign3; + vertex3.z = radius * cosTheta; + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normals.push(0, sign3, 0); + uv.x = cosTheta * 0.5 + 0.5; + uv.y = sinTheta * 0.5 * sign3 + 0.5; + uvs.push(uv.x, uv.y); + index2++; + } + for (let x = 0;x < radialSegments; x++) { + const c = centerIndexStart + x; + const i = centerIndexEnd + x; + if (top === true) { + indices.push(i, i + 1, c); + } else { + indices.push(i + 1, i, c); + } + groupCount += 3; + } + scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); + groupStart += groupCount; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new CylinderGeometry2(data2.radiusTop, data2.radiusBottom, data2.height, data2.radialSegments, data2.heightSegments, data2.openEnded, data2.thetaStart, data2.thetaLength); + } + } + + class ConeGeometry2 extends CylinderGeometry2 { + constructor(radius = 1, height2 = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(0, radius, height2, radialSegments, heightSegments, openEnded, thetaStart, thetaLength); + this.type = "ConeGeometry"; + this.parameters = { + radius, + height: height2, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + } + static fromJSON(data2) { + return new ConeGeometry2(data2.radius, data2.height, data2.radialSegments, data2.heightSegments, data2.openEnded, data2.thetaStart, data2.thetaLength); + } + } + + class PolyhedronGeometry2 extends BufferGeometry2 { + constructor(vertices = [], indices = [], radius = 1, detail = 0) { + super(); + this.type = "PolyhedronGeometry"; + this.parameters = { + vertices, + indices, + radius, + detail + }; + const vertexBuffer = []; + const uvBuffer = []; + subdivide(detail); + applyRadius(radius); + generateUVs(); + this.setAttribute("position", new Float32BufferAttribute2(vertexBuffer, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(vertexBuffer.slice(), 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvBuffer, 2)); + if (detail === 0) { + this.computeVertexNormals(); + } else { + this.normalizeNormals(); + } + function subdivide(detail2) { + const a = new Vector32; + const b = new Vector32; + const c = new Vector32; + for (let i = 0;i < indices.length; i += 3) { + getVertexByIndex(indices[i + 0], a); + getVertexByIndex(indices[i + 1], b); + getVertexByIndex(indices[i + 2], c); + subdivideFace(a, b, c, detail2); + } + } + function subdivideFace(a, b, c, detail2) { + const cols = detail2 + 1; + const v = []; + for (let i = 0;i <= cols; i++) { + v[i] = []; + const aj = a.clone().lerp(c, i / cols); + const bj = b.clone().lerp(c, i / cols); + const rows = cols - i; + for (let j = 0;j <= rows; j++) { + if (j === 0 && i === cols) { + v[i][j] = aj; + } else { + v[i][j] = aj.clone().lerp(bj, j / rows); + } + } + } + for (let i = 0;i < cols; i++) { + for (let j = 0;j < 2 * (cols - i) - 1; j++) { + const k = Math.floor(j / 2); + if (j % 2 === 0) { + pushVertex(v[i][k + 1]); + pushVertex(v[i + 1][k]); + pushVertex(v[i][k]); + } else { + pushVertex(v[i][k + 1]); + pushVertex(v[i + 1][k + 1]); + pushVertex(v[i + 1][k]); + } + } + } + } + function applyRadius(radius2) { + const vertex3 = new Vector32; + for (let i = 0;i < vertexBuffer.length; i += 3) { + vertex3.x = vertexBuffer[i + 0]; + vertex3.y = vertexBuffer[i + 1]; + vertex3.z = vertexBuffer[i + 2]; + vertex3.normalize().multiplyScalar(radius2); + vertexBuffer[i + 0] = vertex3.x; + vertexBuffer[i + 1] = vertex3.y; + vertexBuffer[i + 2] = vertex3.z; + } + } + function generateUVs() { + const vertex3 = new Vector32; + for (let i = 0;i < vertexBuffer.length; i += 3) { + vertex3.x = vertexBuffer[i + 0]; + vertex3.y = vertexBuffer[i + 1]; + vertex3.z = vertexBuffer[i + 2]; + const u = azimuth(vertex3) / 2 / Math.PI + 0.5; + const v = inclination(vertex3) / Math.PI + 0.5; + uvBuffer.push(u, 1 - v); + } + correctUVs(); + correctSeam(); + } + function correctSeam() { + for (let i = 0;i < uvBuffer.length; i += 6) { + const x0 = uvBuffer[i + 0]; + const x1 = uvBuffer[i + 2]; + const x2 = uvBuffer[i + 4]; + const max = Math.max(x0, x1, x2); + const min = Math.min(x0, x1, x2); + if (max > 0.9 && min < 0.1) { + if (x0 < 0.2) + uvBuffer[i + 0] += 1; + if (x1 < 0.2) + uvBuffer[i + 2] += 1; + if (x2 < 0.2) + uvBuffer[i + 4] += 1; + } + } + } + function pushVertex(vertex3) { + vertexBuffer.push(vertex3.x, vertex3.y, vertex3.z); + } + function getVertexByIndex(index2, vertex3) { + const stride = index2 * 3; + vertex3.x = vertices[stride + 0]; + vertex3.y = vertices[stride + 1]; + vertex3.z = vertices[stride + 2]; + } + function correctUVs() { + const a = new Vector32; + const b = new Vector32; + const c = new Vector32; + const centroid = new Vector32; + const uvA = new Vector22; + const uvB = new Vector22; + const uvC = new Vector22; + for (let i = 0, j = 0;i < vertexBuffer.length; i += 9, j += 6) { + a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]); + b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]); + c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]); + uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]); + uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]); + uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]); + centroid.copy(a).add(b).add(c).divideScalar(3); + const azi = azimuth(centroid); + correctUV(uvA, j + 0, a, azi); + correctUV(uvB, j + 2, b, azi); + correctUV(uvC, j + 4, c, azi); + } + } + function correctUV(uv, stride, vector, azimuth2) { + if (azimuth2 < 0 && uv.x === 1) { + uvBuffer[stride] = uv.x - 1; + } + if (vector.x === 0 && vector.z === 0) { + uvBuffer[stride] = azimuth2 / 2 / Math.PI + 0.5; + } + } + function azimuth(vector) { + return Math.atan2(vector.z, -vector.x); + } + function inclination(vector) { + return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new PolyhedronGeometry2(data2.vertices, data2.indices, data2.radius, data2.details); + } + } + + class DodecahedronGeometry2 extends PolyhedronGeometry2 { + constructor(radius = 1, detail = 0) { + const t = (1 + Math.sqrt(5)) / 2; + const r = 1 / t; + const vertices = [ + -1, + -1, + -1, + -1, + -1, + 1, + -1, + 1, + -1, + -1, + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + 1, + 1, + -1, + 1, + 1, + 1, + 0, + -r, + -t, + 0, + -r, + t, + 0, + r, + -t, + 0, + r, + t, + -r, + -t, + 0, + -r, + t, + 0, + r, + -t, + 0, + r, + t, + 0, + -t, + 0, + -r, + t, + 0, + -r, + -t, + 0, + r, + t, + 0, + r + ]; + const indices = [ + 3, + 11, + 7, + 3, + 7, + 15, + 3, + 15, + 13, + 7, + 19, + 17, + 7, + 17, + 6, + 7, + 6, + 15, + 17, + 4, + 8, + 17, + 8, + 10, + 17, + 10, + 6, + 8, + 0, + 16, + 8, + 16, + 2, + 8, + 2, + 10, + 0, + 12, + 1, + 0, + 1, + 18, + 0, + 18, + 16, + 6, + 10, + 2, + 6, + 2, + 13, + 6, + 13, + 15, + 2, + 16, + 18, + 2, + 18, + 3, + 2, + 3, + 13, + 18, + 1, + 9, + 18, + 9, + 11, + 18, + 11, + 3, + 4, + 14, + 12, + 4, + 12, + 0, + 4, + 0, + 8, + 11, + 9, + 5, + 11, + 5, + 19, + 11, + 19, + 7, + 19, + 5, + 14, + 19, + 14, + 4, + 19, + 4, + 17, + 1, + 12, + 14, + 1, + 14, + 5, + 1, + 5, + 9 + ]; + super(vertices, indices, radius, detail); + this.type = "DodecahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new DodecahedronGeometry2(data2.radius, data2.detail); + } + } + var _v0$12 = /* @__PURE__ */ new Vector32; + var _v1$12 = /* @__PURE__ */ new Vector32; + var _normal2 = /* @__PURE__ */ new Vector32; + var _triangle2 = /* @__PURE__ */ new Triangle2; + + class EdgesGeometry2 extends BufferGeometry2 { + constructor(geometry = null, thresholdAngle = 1) { + super(); + this.type = "EdgesGeometry"; + this.parameters = { + geometry, + thresholdAngle + }; + if (geometry !== null) { + const precisionPoints = 4; + const precision = Math.pow(10, precisionPoints); + const thresholdDot = Math.cos(DEG2RAD2 * thresholdAngle); + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute("position"); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + const indexArr = [0, 0, 0]; + const vertKeys = ["a", "b", "c"]; + const hashes = new Array(3); + const edgeData = {}; + const vertices = []; + for (let i = 0;i < indexCount; i += 3) { + if (indexAttr) { + indexArr[0] = indexAttr.getX(i); + indexArr[1] = indexAttr.getX(i + 1); + indexArr[2] = indexAttr.getX(i + 2); + } else { + indexArr[0] = i; + indexArr[1] = i + 1; + indexArr[2] = i + 2; + } + const { a, b, c } = _triangle2; + a.fromBufferAttribute(positionAttr, indexArr[0]); + b.fromBufferAttribute(positionAttr, indexArr[1]); + c.fromBufferAttribute(positionAttr, indexArr[2]); + _triangle2.getNormal(_normal2); + hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`; + hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`; + hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; + if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) { + continue; + } + for (let j = 0;j < 3; j++) { + const jNext = (j + 1) % 3; + const vecHash0 = hashes[j]; + const vecHash1 = hashes[jNext]; + const v0 = _triangle2[vertKeys[j]]; + const v1 = _triangle2[vertKeys[jNext]]; + const hash = `${vecHash0}_${vecHash1}`; + const reverseHash = `${vecHash1}_${vecHash0}`; + if (reverseHash in edgeData && edgeData[reverseHash]) { + if (_normal2.dot(edgeData[reverseHash].normal) <= thresholdDot) { + vertices.push(v0.x, v0.y, v0.z); + vertices.push(v1.x, v1.y, v1.z); + } + edgeData[reverseHash] = null; + } else if (!(hash in edgeData)) { + edgeData[hash] = { + index0: indexArr[j], + index1: indexArr[jNext], + normal: _normal2.clone() + }; + } + } + } + for (const key2 in edgeData) { + if (edgeData[key2]) { + const { index0, index1 } = edgeData[key2]; + _v0$12.fromBufferAttribute(positionAttr, index0); + _v1$12.fromBufferAttribute(positionAttr, index1); + vertices.push(_v0$12.x, _v0$12.y, _v0$12.z); + vertices.push(_v1$12.x, _v1$12.y, _v1$12.z); + } + } + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + } + + class Shape2 extends Path2 { + constructor(points) { + super(points); + this.uuid = generateUUID2(); + this.type = "Shape"; + this.holes = []; + } + getPointsHoles(divisions) { + const holesPts = []; + for (let i = 0, l = this.holes.length;i < l; i++) { + holesPts[i] = this.holes[i].getPoints(divisions); + } + return holesPts; + } + extractPoints(divisions) { + return { + shape: this.getPoints(divisions), + holes: this.getPointsHoles(divisions) + }; + } + copy(source) { + super.copy(source); + this.holes = []; + for (let i = 0, l = source.holes.length;i < l; i++) { + const hole = source.holes[i]; + this.holes.push(hole.clone()); + } + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.uuid = this.uuid; + data2.holes = []; + for (let i = 0, l = this.holes.length;i < l; i++) { + const hole = this.holes[i]; + data2.holes.push(hole.toJSON()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.uuid = json.uuid; + this.holes = []; + for (let i = 0, l = json.holes.length;i < l; i++) { + const hole = json.holes[i]; + this.holes.push(new Path2().fromJSON(hole)); + } + return this; + } + } + var Earcut2 = { + triangulate: function(data2, holeIndices, dim = 2) { + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data2.length; + let outerNode = linkedList2(data2, 0, outerLen, dim, true); + const triangles = []; + if (!outerNode || outerNode.next === outerNode.prev) + return triangles; + let minX, minY, maxX, maxY, x, y, invSize; + if (hasHoles) + outerNode = eliminateHoles2(data2, holeIndices, outerNode, dim); + if (data2.length > 80 * dim) { + minX = maxX = data2[0]; + minY = maxY = data2[1]; + for (let i = dim;i < outerLen; i += dim) { + x = data2[i]; + y = data2[i + 1]; + if (x < minX) + minX = x; + if (y < minY) + minY = y; + if (x > maxX) + maxX = x; + if (y > maxY) + maxY = y; + } + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + earcutLinked2(outerNode, triangles, dim, minX, minY, invSize, 0); + return triangles; + } + }; + function linkedList2(data2, start, end, dim, clockwise) { + let i, last2; + if (clockwise === signedArea2(data2, start, end, dim) > 0) { + for (i = start;i < end; i += dim) + last2 = insertNode2(i, data2[i], data2[i + 1], last2); + } else { + for (i = end - dim;i >= start; i -= dim) + last2 = insertNode2(i, data2[i], data2[i + 1], last2); + } + if (last2 && equals2(last2, last2.next)) { + removeNode2(last2); + last2 = last2.next; + } + return last2; + } + function filterPoints2(start, end) { + if (!start) + return start; + if (!end) + end = start; + let p = start, again; + do { + again = false; + if (!p.steiner && (equals2(p, p.next) || area2(p.prev, p, p.next) === 0)) { + removeNode2(p); + p = end = p.prev; + if (p === p.next) + break; + again = true; + } else { + p = p.next; + } + } while (again || p !== end); + return end; + } + function earcutLinked2(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) + return; + if (!pass && invSize) + indexCurve2(ear, minX, minY, invSize); + let stop = ear, prev, next; + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + if (invSize ? isEarHashed2(ear, minX, minY, invSize) : isEar2(ear)) { + triangles.push(prev.i / dim | 0); + triangles.push(ear.i / dim | 0); + triangles.push(next.i / dim | 0); + removeNode2(ear); + ear = next.next; + stop = next.next; + continue; + } + ear = next; + if (ear === stop) { + if (!pass) { + earcutLinked2(filterPoints2(ear), triangles, dim, minX, minY, invSize, 1); + } else if (pass === 1) { + ear = cureLocalIntersections2(filterPoints2(ear), triangles, dim); + earcutLinked2(ear, triangles, dim, minX, minY, invSize, 2); + } else if (pass === 2) { + splitEarcut2(ear, triangles, dim, minX, minY, invSize); + } + break; + } + } + } + function isEar2(ear) { + const a = ear.prev, b = ear, c = ear.next; + if (area2(a, b, c) >= 0) + return false; + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + let p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle2(ax, ay, bx, by, cx, cy, p.x, p.y) && area2(p.prev, p, p.next) >= 0) + return false; + p = p.next; + } + return true; + } + function isEarHashed2(ear, minX, minY, invSize) { + const a = ear.prev, b = ear, c = ear.next; + if (area2(a, b, c) >= 0) + return false; + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + const minZ = zOrder2(x0, y0, minX, minY, invSize), maxZ = zOrder2(x1, y1, minX, minY, invSize); + let { prevZ: p, nextZ: n } = ear; + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle2(ax, ay, bx, by, cx, cy, p.x, p.y) && area2(p.prev, p, p.next) >= 0) + return false; + p = p.prevZ; + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle2(ax, ay, bx, by, cx, cy, n.x, n.y) && area2(n.prev, n, n.next) >= 0) + return false; + n = n.nextZ; + } + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle2(ax, ay, bx, by, cx, cy, p.x, p.y) && area2(p.prev, p, p.next) >= 0) + return false; + p = p.prevZ; + } + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle2(ax, ay, bx, by, cx, cy, n.x, n.y) && area2(n.prev, n, n.next) >= 0) + return false; + n = n.nextZ; + } + return true; + } + function cureLocalIntersections2(start, triangles, dim) { + let p = start; + do { + const a = p.prev, b = p.next.next; + if (!equals2(a, b) && intersects2(a, p, p.next, b) && locallyInside2(a, b) && locallyInside2(b, a)) { + triangles.push(a.i / dim | 0); + triangles.push(p.i / dim | 0); + triangles.push(b.i / dim | 0); + removeNode2(p); + removeNode2(p.next); + p = start = b; + } + p = p.next; + } while (p !== start); + return filterPoints2(p); + } + function splitEarcut2(start, triangles, dim, minX, minY, invSize) { + let a = start; + do { + let b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal2(a, b)) { + let c = splitPolygon2(a, b); + a = filterPoints2(a, a.next); + c = filterPoints2(c, c.next); + earcutLinked2(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked2(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); + } + function eliminateHoles2(data2, holeIndices, outerNode, dim) { + const queue = []; + let i, len, start, end, list; + for (i = 0, len = holeIndices.length;i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data2.length; + list = linkedList2(data2, start, end, dim, false); + if (list === list.next) + list.steiner = true; + queue.push(getLeftmost2(list)); + } + queue.sort(compareX2); + for (i = 0;i < queue.length; i++) { + outerNode = eliminateHole2(queue[i], outerNode); + } + return outerNode; + } + function compareX2(a, b) { + return a.x - b.x; + } + function eliminateHole2(hole, outerNode) { + const bridge = findHoleBridge2(hole, outerNode); + if (!bridge) { + return outerNode; + } + const bridgeReverse = splitPolygon2(bridge, hole); + filterPoints2(bridgeReverse, bridgeReverse.next); + return filterPoints2(bridge, bridge.next); + } + function findHoleBridge2(hole, outerNode) { + let p = outerNode, qx = -Infinity, m; + const { x: hx, y: hy } = hole; + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) + return m; + } + } + p = p.next; + } while (p !== outerNode); + if (!m) + return null; + const stop = m, mx = m.x, my = m.y; + let tanMin = Infinity, tan; + p = m; + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle2(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + tan = Math.abs(hy - p.y) / (hx - p.x); + if (locallyInside2(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector2(m, p)))) { + m = p; + tanMin = tan; + } + } + p = p.next; + } while (p !== stop); + return m; + } + function sectorContainsSector2(m, p) { + return area2(m.prev, m, p.prev) < 0 && area2(p.next, m, m.next) < 0; + } + function indexCurve2(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) + p.z = zOrder2(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + p.prevZ.nextZ = null; + p.prevZ = null; + sortLinked2(p); + } + function sortLinked2(list) { + let i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; + do { + p = list; + list = null; + tail = null; + numMerges = 0; + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0;i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) + break; + } + qSize = inSize; + while (pSize > 0 || qSize > 0 && q) { + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + if (tail) + tail.nextZ = e; + else + list = e; + e.prevZ = tail; + tail = e; + } + p = q; + } + tail.nextZ = null; + inSize *= 2; + } while (numMerges > 1); + return list; + } + function zOrder2(x, y, minX, minY, invSize) { + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + x = (x | x << 8) & 16711935; + x = (x | x << 4) & 252645135; + x = (x | x << 2) & 858993459; + x = (x | x << 1) & 1431655765; + y = (y | y << 8) & 16711935; + y = (y | y << 4) & 252645135; + y = (y | y << 2) & 858993459; + y = (y | y << 1) & 1431655765; + return x | y << 1; + } + function getLeftmost2(start) { + let p = start, leftmost = start; + do { + if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) + leftmost = p; + p = p.next; + } while (p !== start); + return leftmost; + } + function pointInTriangle2(ax, ay, bx, by, cx, cy, px3, py3) { + return (cx - px3) * (ay - py3) >= (ax - px3) * (cy - py3) && (ax - px3) * (by - py3) >= (bx - px3) * (ay - py3) && (bx - px3) * (cy - py3) >= (cx - px3) * (by - py3); + } + function isValidDiagonal2(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon2(a, b) && (locallyInside2(a, b) && locallyInside2(b, a) && middleInside2(a, b) && (area2(a.prev, a, b.prev) || area2(a, b.prev, b)) || equals2(a, b) && area2(a.prev, a, a.next) > 0 && area2(b.prev, b, b.next) > 0); + } + function area2(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + } + function equals2(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; + } + function intersects2(p1, q1, p2, q2) { + const o1 = sign2(area2(p1, q1, p2)); + const o2 = sign2(area2(p1, q1, q2)); + const o3 = sign2(area2(p2, q2, p1)); + const o4 = sign2(area2(p2, q2, q1)); + if (o1 !== o2 && o3 !== o4) + return true; + if (o1 === 0 && onSegment2(p1, p2, q1)) + return true; + if (o2 === 0 && onSegment2(p1, q2, q1)) + return true; + if (o3 === 0 && onSegment2(p2, p1, q2)) + return true; + if (o4 === 0 && onSegment2(p2, q1, q2)) + return true; + return false; + } + function onSegment2(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); + } + function sign2(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; + } + function intersectsPolygon2(a, b) { + let p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects2(p, p.next, a, b)) + return true; + p = p.next; + } while (p !== a); + return false; + } + function locallyInside2(a, b) { + return area2(a.prev, a, a.next) < 0 ? area2(a, b, a.next) >= 0 && area2(a, a.prev, b) >= 0 : area2(a, b, a.prev) < 0 || area2(a, a.next, b) < 0; + } + function middleInside2(a, b) { + let p = a, inside = false; + const px3 = (a.x + b.x) / 2, py3 = (a.y + b.y) / 2; + do { + if (p.y > py3 !== p.next.y > py3 && p.next.y !== p.y && px3 < (p.next.x - p.x) * (py3 - p.y) / (p.next.y - p.y) + p.x) + inside = !inside; + p = p.next; + } while (p !== a); + return inside; + } + function splitPolygon2(a, b) { + const a2 = new Node3(a.i, a.x, a.y), b2 = new Node3(b.i, b.x, b.y), an = a.next, bp = b.prev; + a.next = b; + b.prev = a; + a2.next = an; + an.prev = a2; + b2.next = a2; + a2.prev = b2; + bp.next = b2; + b2.prev = bp; + return b2; + } + function insertNode2(i, x, y, last2) { + const p = new Node3(i, x, y); + if (!last2) { + p.prev = p; + p.next = p; + } else { + p.next = last2.next; + p.prev = last2; + last2.next.prev = p; + last2.next = p; + } + return p; + } + function removeNode2(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + if (p.prevZ) + p.prevZ.nextZ = p.nextZ; + if (p.nextZ) + p.nextZ.prevZ = p.prevZ; + } + function Node3(i, x, y) { + this.i = i; + this.x = x; + this.y = y; + this.prev = null; + this.next = null; + this.z = 0; + this.prevZ = null; + this.nextZ = null; + this.steiner = false; + } + function signedArea2(data2, start, end, dim) { + let sum2 = 0; + for (let i = start, j = end - dim;i < end; i += dim) { + sum2 += (data2[j] - data2[i]) * (data2[i + 1] + data2[j + 1]); + j = i; + } + return sum2; + } + + class ShapeUtils2 { + static area(contour) { + const n = contour.length; + let a = 0; + for (let p = n - 1, q = 0;q < n; p = q++) { + a += contour[p].x * contour[q].y - contour[q].x * contour[p].y; + } + return a * 0.5; + } + static isClockWise(pts) { + return ShapeUtils2.area(pts) < 0; + } + static triangulateShape(contour, holes) { + const vertices = []; + const holeIndices = []; + const faces = []; + removeDupEndPts2(contour); + addContour2(vertices, contour); + let holeIndex = contour.length; + holes.forEach(removeDupEndPts2); + for (let i = 0;i < holes.length; i++) { + holeIndices.push(holeIndex); + holeIndex += holes[i].length; + addContour2(vertices, holes[i]); + } + const triangles = Earcut2.triangulate(vertices, holeIndices); + for (let i = 0;i < triangles.length; i += 3) { + faces.push(triangles.slice(i, i + 3)); + } + return faces; + } + } + function removeDupEndPts2(points) { + const l = points.length; + if (l > 2 && points[l - 1].equals(points[0])) { + points.pop(); + } + } + function addContour2(vertices, contour) { + for (let i = 0;i < contour.length; i++) { + vertices.push(contour[i].x); + vertices.push(contour[i].y); + } + } + + class ExtrudeGeometry2 extends BufferGeometry2 { + constructor(shapes = new Shape2([new Vector22(0.5, 0.5), new Vector22(-0.5, 0.5), new Vector22(-0.5, -0.5), new Vector22(0.5, -0.5)]), options = {}) { + super(); + this.type = "ExtrudeGeometry"; + this.parameters = { + shapes, + options + }; + shapes = Array.isArray(shapes) ? shapes : [shapes]; + const scope = this; + const verticesArray = []; + const uvArray = []; + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + addShape(shape); + } + this.setAttribute("position", new Float32BufferAttribute2(verticesArray, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvArray, 2)); + this.computeVertexNormals(); + function addShape(shape) { + const placeholder = []; + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + const extrudePath = options.extrudePath; + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator2; + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + if (extrudePath) { + extrudePts = extrudePath.getSpacedPoints(steps); + extrudeByPath = true; + bevelEnabled = false; + splineTube = extrudePath.computeFrenetFrames(steps, false); + binormal = new Vector32; + normal = new Vector32; + position2 = new Vector32; + } + if (!bevelEnabled) { + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + } + const shapePoints = shape.extractPoints(curveSegments); + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + const reverse = !ShapeUtils2.isClockWise(vertices); + if (reverse) { + vertices = vertices.reverse(); + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + if (ShapeUtils2.isClockWise(ahole)) { + holes[h] = ahole.reverse(); + } + } + } + const faces = ShapeUtils2.triangulateShape(vertices, holes); + const contour = vertices; + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + vertices = vertices.concat(ahole); + } + function scalePt2(pt, vec, size) { + if (!vec) + console.error("THREE.ExtrudeGeometry: vec does not exist"); + return pt.clone().addScaledVector(vec, size); + } + const vlen = vertices.length, flen = faces.length; + function getBevelVec(inPt, inPrev, inNext) { + let v_trans_x, v_trans_y, shrink_by; + const v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; + const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; + const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x; + if (Math.abs(collinear0) > Number.EPSILON) { + const v_prev_len = Math.sqrt(v_prev_lensq); + const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); + const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len; + const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len; + const ptNextShift_x = inNext.x - v_next_y / v_next_len; + const ptNextShift_y = inNext.y + v_next_x / v_next_len; + const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); + v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x; + v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; + const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y; + if (v_trans_lensq <= 2) { + return new Vector22(v_trans_x, v_trans_y); + } else { + shrink_by = Math.sqrt(v_trans_lensq / 2); + } + } else { + let direction_eq = false; + if (v_prev_x > Number.EPSILON) { + if (v_next_x > Number.EPSILON) { + direction_eq = true; + } + } else { + if (v_prev_x < -Number.EPSILON) { + if (v_next_x < -Number.EPSILON) { + direction_eq = true; + } + } else { + if (Math.sign(v_prev_y) === Math.sign(v_next_y)) { + direction_eq = true; + } + } + } + if (direction_eq) { + v_trans_x = -v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt(v_prev_lensq); + } else { + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt(v_prev_lensq / 2); + } + } + return new Vector22(v_trans_x / shrink_by, v_trans_y / shrink_by); + } + const contourMovements = []; + for (let i = 0, il = contour.length, j = il - 1, k = i + 1;i < il; i++, j++, k++) { + if (j === il) + j = 0; + if (k === il) + k = 0; + contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]); + } + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = []; + for (let i = 0, il = ahole.length, j = il - 1, k = i + 1;i < il; i++, j++, k++) { + if (j === il) + j = 0; + if (k === il) + k = 0; + oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]); + } + holesMovements.push(oneHoleMovements); + verticesMovements = verticesMovements.concat(oneHoleMovements); + } + for (let b = 0;b < bevelSegments; b++) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos(t * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length;i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, -z); + } + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length;i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + v(vert.x, vert.y, -z); + } + } + } + const bs = bevelSize + bevelOffset; + for (let i = 0;i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, 0); + } else { + normal.copy(splineTube.normals[0]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y); + position2.copy(extrudePts[0]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + for (let s = 1;s <= steps; s++) { + for (let i = 0;i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, depth / steps * s); + } else { + normal.copy(splineTube.normals[s]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y); + position2.copy(extrudePts[s]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + } + for (let b = bevelSegments - 1;b >= 0; b--) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos(t * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length;i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, depth + z); + } + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length;i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + if (!extrudeByPath) { + v(vert.x, vert.y, depth + z); + } else { + v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z); + } + } + } + } + buildLidFaces(); + buildSideFaces(); + function buildLidFaces() { + const start = verticesArray.length / 3; + if (bevelEnabled) { + let layer = 0; + let offset = vlen * layer; + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[2] + offset, face[1] + offset, face[0] + offset); + } + layer = steps + bevelSegments * 2; + offset = vlen * layer; + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[0] + offset, face[1] + offset, face[2] + offset); + } + } else { + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[2], face[1], face[0]); + } + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps); + } + } + scope.addGroup(start, verticesArray.length / 3 - start, 0); + } + function buildSideFaces() { + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls(contour, layeroffset); + layeroffset += contour.length; + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + sidewalls(ahole, layeroffset); + layeroffset += ahole.length; + } + scope.addGroup(start, verticesArray.length / 3 - start, 1); + } + function sidewalls(contour2, layeroffset) { + let i = contour2.length; + while (--i >= 0) { + const j = i; + let k = i - 1; + if (k < 0) + k = contour2.length - 1; + for (let s = 0, sl = steps + bevelSegments * 2;s < sl; s++) { + const slen1 = vlen * s; + const slen2 = vlen * (s + 1); + const a = layeroffset + j + slen1, b = layeroffset + k + slen1, c = layeroffset + k + slen2, d = layeroffset + j + slen2; + f4(a, b, c, d); + } + } + } + function v(x, y, z) { + placeholder.push(x); + placeholder.push(y); + placeholder.push(z); + } + function f3(a, b, c) { + addVertex(a); + addVertex(b); + addVertex(c); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[2]); + } + function f4(a, b, c, d) { + addVertex(a); + addVertex(b); + addVertex(d); + addVertex(b); + addVertex(c); + addVertex(d); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[3]); + addUV(uvs[1]); + addUV(uvs[2]); + addUV(uvs[3]); + } + function addVertex(index2) { + verticesArray.push(placeholder[index2 * 3 + 0]); + verticesArray.push(placeholder[index2 * 3 + 1]); + verticesArray.push(placeholder[index2 * 3 + 2]); + } + function addUV(vector2) { + uvArray.push(vector2.x); + uvArray.push(vector2.y); + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + const shapes = this.parameters.shapes; + const options = this.parameters.options; + return toJSON$12(shapes, options, data2); + } + static fromJSON(data2, shapes) { + const geometryShapes = []; + for (let j = 0, jl = data2.shapes.length;j < jl; j++) { + const shape = shapes[data2.shapes[j]]; + geometryShapes.push(shape); + } + const extrudePath = data2.options.extrudePath; + if (extrudePath !== undefined) { + data2.options.extrudePath = new Curves2[extrudePath.type]().fromJSON(extrudePath); + } + return new ExtrudeGeometry2(geometryShapes, data2.options); + } + } + var WorldUVGenerator2 = { + generateTopUV: function(geometry, vertices, indexA, indexB, indexC) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + return [ + new Vector22(a_x, a_y), + new Vector22(b_x, b_y), + new Vector22(c_x, c_y) + ]; + }, + generateSideWallUV: function(geometry, vertices, indexA, indexB, indexC, indexD) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const a_z = vertices[indexA * 3 + 2]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const b_z = vertices[indexB * 3 + 2]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + const c_z = vertices[indexC * 3 + 2]; + const d_x = vertices[indexD * 3]; + const d_y = vertices[indexD * 3 + 1]; + const d_z = vertices[indexD * 3 + 2]; + if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) { + return [ + new Vector22(a_x, 1 - a_z), + new Vector22(b_x, 1 - b_z), + new Vector22(c_x, 1 - c_z), + new Vector22(d_x, 1 - d_z) + ]; + } else { + return [ + new Vector22(a_y, 1 - a_z), + new Vector22(b_y, 1 - b_z), + new Vector22(c_y, 1 - c_z), + new Vector22(d_y, 1 - d_z) + ]; + } + } + }; + function toJSON$12(shapes, options, data2) { + data2.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + data2.shapes.push(shape.uuid); + } + } else { + data2.shapes.push(shapes.uuid); + } + data2.options = Object.assign({}, options); + if (options.extrudePath !== undefined) + data2.options.extrudePath = options.extrudePath.toJSON(); + return data2; + } + + class IcosahedronGeometry2 extends PolyhedronGeometry2 { + constructor(radius = 1, detail = 0) { + const t = (1 + Math.sqrt(5)) / 2; + const vertices = [ + -1, + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + 0, + 0, + -1, + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + t, + 0, + -1, + t, + 0, + 1, + -t, + 0, + -1, + -t, + 0, + 1 + ]; + const indices = [ + 0, + 11, + 5, + 0, + 5, + 1, + 0, + 1, + 7, + 0, + 7, + 10, + 0, + 10, + 11, + 1, + 5, + 9, + 5, + 11, + 4, + 11, + 10, + 2, + 10, + 7, + 6, + 7, + 1, + 8, + 3, + 9, + 4, + 3, + 4, + 2, + 3, + 2, + 6, + 3, + 6, + 8, + 3, + 8, + 9, + 4, + 9, + 5, + 2, + 4, + 11, + 6, + 2, + 10, + 8, + 6, + 7, + 9, + 8, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "IcosahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new IcosahedronGeometry2(data2.radius, data2.detail); + } + } + + class OctahedronGeometry2 extends PolyhedronGeometry2 { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1 + ]; + const indices = [ + 0, + 2, + 4, + 0, + 4, + 3, + 0, + 3, + 5, + 0, + 5, + 2, + 1, + 2, + 5, + 1, + 5, + 3, + 1, + 3, + 4, + 1, + 4, + 2 + ]; + super(vertices, indices, radius, detail); + this.type = "OctahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new OctahedronGeometry2(data2.radius, data2.detail); + } + } + + class PlaneGeometry2 extends BufferGeometry2 { + constructor(width2 = 1, height2 = 1, widthSegments = 1, heightSegments = 1) { + super(); + this.type = "PlaneGeometry"; + this.parameters = { + width: width2, + height: height2, + widthSegments, + heightSegments + }; + const width_half = width2 / 2; + const height_half = height2 / 2; + const gridX = Math.floor(widthSegments); + const gridY = Math.floor(heightSegments); + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + const segment_width = width2 / gridX; + const segment_height = height2 / gridY; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0;iy < gridY1; iy++) { + const y = iy * segment_height - height_half; + for (let ix = 0;ix < gridX1; ix++) { + const x = ix * segment_width - width_half; + vertices.push(x, -y, 0); + normals.push(0, 0, 1); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + } + } + for (let iy = 0;iy < gridY; iy++) { + for (let ix = 0;ix < gridX; ix++) { + const a = ix + gridX1 * iy; + const b = ix + gridX1 * (iy + 1); + const c = ix + 1 + gridX1 * (iy + 1); + const d = ix + 1 + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new PlaneGeometry2(data2.width, data2.height, data2.widthSegments, data2.heightSegments); + } + } + + class RingGeometry2 extends BufferGeometry2 { + constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "RingGeometry"; + this.parameters = { + innerRadius, + outerRadius, + thetaSegments, + phiSegments, + thetaStart, + thetaLength + }; + thetaSegments = Math.max(3, thetaSegments); + phiSegments = Math.max(1, phiSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let radius = innerRadius; + const radiusStep = (outerRadius - innerRadius) / phiSegments; + const vertex3 = new Vector32; + const uv = new Vector22; + for (let j = 0;j <= phiSegments; j++) { + for (let i = 0;i <= thetaSegments; i++) { + const segment = thetaStart + i / thetaSegments * thetaLength; + vertex3.x = radius * Math.cos(segment); + vertex3.y = radius * Math.sin(segment); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normals.push(0, 0, 1); + uv.x = (vertex3.x / outerRadius + 1) / 2; + uv.y = (vertex3.y / outerRadius + 1) / 2; + uvs.push(uv.x, uv.y); + } + radius += radiusStep; + } + for (let j = 0;j < phiSegments; j++) { + const thetaSegmentLevel = j * (thetaSegments + 1); + for (let i = 0;i < thetaSegments; i++) { + const segment = i + thetaSegmentLevel; + const a = segment; + const b = segment + thetaSegments + 1; + const c = segment + thetaSegments + 2; + const d = segment + 1; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new RingGeometry2(data2.innerRadius, data2.outerRadius, data2.thetaSegments, data2.phiSegments, data2.thetaStart, data2.thetaLength); + } + } + + class ShapeGeometry2 extends BufferGeometry2 { + constructor(shapes = new Shape2([new Vector22(0, 0.5), new Vector22(-0.5, -0.5), new Vector22(0.5, -0.5)]), curveSegments = 12) { + super(); + this.type = "ShapeGeometry"; + this.parameters = { + shapes, + curveSegments + }; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let groupStart = 0; + let groupCount = 0; + if (Array.isArray(shapes) === false) { + addShape(shapes); + } else { + for (let i = 0;i < shapes.length; i++) { + addShape(shapes[i]); + this.addGroup(groupStart, groupCount, i); + groupStart += groupCount; + groupCount = 0; + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function addShape(shape) { + const indexOffset = vertices.length / 3; + const points = shape.extractPoints(curveSegments); + let shapeVertices = points.shape; + const shapeHoles = points.holes; + if (ShapeUtils2.isClockWise(shapeVertices) === false) { + shapeVertices = shapeVertices.reverse(); + } + for (let i = 0, l = shapeHoles.length;i < l; i++) { + const shapeHole = shapeHoles[i]; + if (ShapeUtils2.isClockWise(shapeHole) === true) { + shapeHoles[i] = shapeHole.reverse(); + } + } + const faces = ShapeUtils2.triangulateShape(shapeVertices, shapeHoles); + for (let i = 0, l = shapeHoles.length;i < l; i++) { + const shapeHole = shapeHoles[i]; + shapeVertices = shapeVertices.concat(shapeHole); + } + for (let i = 0, l = shapeVertices.length;i < l; i++) { + const vertex3 = shapeVertices[i]; + vertices.push(vertex3.x, vertex3.y, 0); + normals.push(0, 0, 1); + uvs.push(vertex3.x, vertex3.y); + } + for (let i = 0, l = faces.length;i < l; i++) { + const face = faces[i]; + const a = face[0] + indexOffset; + const b = face[1] + indexOffset; + const c = face[2] + indexOffset; + indices.push(a, b, c); + groupCount += 3; + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + const shapes = this.parameters.shapes; + return toJSON2(shapes, data2); + } + static fromJSON(data2, shapes) { + const geometryShapes = []; + for (let j = 0, jl = data2.shapes.length;j < jl; j++) { + const shape = shapes[data2.shapes[j]]; + geometryShapes.push(shape); + } + return new ShapeGeometry2(geometryShapes, data2.curveSegments); + } + } + function toJSON2(shapes, data2) { + data2.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + data2.shapes.push(shape.uuid); + } + } else { + data2.shapes.push(shapes.uuid); + } + return data2; + } + + class SphereGeometry2 extends BufferGeometry2 { + constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) { + super(); + this.type = "SphereGeometry"; + this.parameters = { + radius, + widthSegments, + heightSegments, + phiStart, + phiLength, + thetaStart, + thetaLength + }; + widthSegments = Math.max(3, Math.floor(widthSegments)); + heightSegments = Math.max(2, Math.floor(heightSegments)); + const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI); + let index2 = 0; + const grid = []; + const vertex3 = new Vector32; + const normal = new Vector32; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0;iy <= heightSegments; iy++) { + const verticesRow = []; + const v = iy / heightSegments; + let uOffset = 0; + if (iy === 0 && thetaStart === 0) { + uOffset = 0.5 / widthSegments; + } else if (iy === heightSegments && thetaEnd === Math.PI) { + uOffset = -0.5 / widthSegments; + } + for (let ix = 0;ix <= widthSegments; ix++) { + const u = ix / widthSegments; + vertex3.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertex3.y = radius * Math.cos(thetaStart + v * thetaLength); + vertex3.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normal.copy(vertex3).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u + uOffset, 1 - v); + verticesRow.push(index2++); + } + grid.push(verticesRow); + } + for (let iy = 0;iy < heightSegments; iy++) { + for (let ix = 0;ix < widthSegments; ix++) { + const a = grid[iy][ix + 1]; + const b = grid[iy][ix]; + const c = grid[iy + 1][ix]; + const d = grid[iy + 1][ix + 1]; + if (iy !== 0 || thetaStart > 0) + indices.push(a, b, d); + if (iy !== heightSegments - 1 || thetaEnd < Math.PI) + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new SphereGeometry2(data2.radius, data2.widthSegments, data2.heightSegments, data2.phiStart, data2.phiLength, data2.thetaStart, data2.thetaLength); + } + } + + class TetrahedronGeometry2 extends PolyhedronGeometry2 { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + -1, + 1, + -1, + -1 + ]; + const indices = [ + 2, + 1, + 0, + 0, + 3, + 2, + 1, + 3, + 0, + 2, + 3, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "TetrahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new TetrahedronGeometry2(data2.radius, data2.detail); + } + } + + class TorusGeometry2 extends BufferGeometry2 { + constructor(radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2) { + super(); + this.type = "TorusGeometry"; + this.parameters = { + radius, + tube, + radialSegments, + tubularSegments, + arc + }; + radialSegments = Math.floor(radialSegments); + tubularSegments = Math.floor(tubularSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const center = new Vector32; + const vertex3 = new Vector32; + const normal = new Vector32; + for (let j = 0;j <= radialSegments; j++) { + for (let i = 0;i <= tubularSegments; i++) { + const u = i / tubularSegments * arc; + const v = j / radialSegments * Math.PI * 2; + vertex3.x = (radius + tube * Math.cos(v)) * Math.cos(u); + vertex3.y = (radius + tube * Math.cos(v)) * Math.sin(u); + vertex3.z = tube * Math.sin(v); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + center.x = radius * Math.cos(u); + center.y = radius * Math.sin(u); + normal.subVectors(vertex3, center).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j / radialSegments); + } + } + for (let j = 1;j <= radialSegments; j++) { + for (let i = 1;i <= tubularSegments; i++) { + const a = (tubularSegments + 1) * j + i - 1; + const b = (tubularSegments + 1) * (j - 1) + i - 1; + const c = (tubularSegments + 1) * (j - 1) + i; + const d = (tubularSegments + 1) * j + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new TorusGeometry2(data2.radius, data2.tube, data2.radialSegments, data2.tubularSegments, data2.arc); + } + } + + class TorusKnotGeometry2 extends BufferGeometry2 { + constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) { + super(); + this.type = "TorusKnotGeometry"; + this.parameters = { + radius, + tube, + tubularSegments, + radialSegments, + p, + q + }; + tubularSegments = Math.floor(tubularSegments); + radialSegments = Math.floor(radialSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex3 = new Vector32; + const normal = new Vector32; + const P1 = new Vector32; + const P2 = new Vector32; + const B = new Vector32; + const T = new Vector32; + const N = new Vector32; + for (let i = 0;i <= tubularSegments; ++i) { + const u = i / tubularSegments * p * Math.PI * 2; + calculatePositionOnCurve(u, p, q, radius, P1); + calculatePositionOnCurve(u + 0.01, p, q, radius, P2); + T.subVectors(P2, P1); + N.addVectors(P2, P1); + B.crossVectors(T, N); + N.crossVectors(B, T); + B.normalize(); + N.normalize(); + for (let j = 0;j <= radialSegments; ++j) { + const v = j / radialSegments * Math.PI * 2; + const cx = -tube * Math.cos(v); + const cy = tube * Math.sin(v); + vertex3.x = P1.x + (cx * N.x + cy * B.x); + vertex3.y = P1.y + (cx * N.y + cy * B.y); + vertex3.z = P1.z + (cx * N.z + cy * B.z); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normal.subVectors(vertex3, P1).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j / radialSegments); + } + } + for (let j = 1;j <= tubularSegments; j++) { + for (let i = 1;i <= radialSegments; i++) { + const a = (radialSegments + 1) * (j - 1) + (i - 1); + const b = (radialSegments + 1) * j + (i - 1); + const c = (radialSegments + 1) * j + i; + const d = (radialSegments + 1) * (j - 1) + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function calculatePositionOnCurve(u, p2, q2, radius2, position2) { + const cu = Math.cos(u); + const su = Math.sin(u); + const quOverP = q2 / p2 * u; + const cs = Math.cos(quOverP); + position2.x = radius2 * (2 + cs) * 0.5 * cu; + position2.y = radius2 * (2 + cs) * su * 0.5; + position2.z = radius2 * Math.sin(quOverP) * 0.5; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new TorusKnotGeometry2(data2.radius, data2.tube, data2.tubularSegments, data2.radialSegments, data2.p, data2.q); + } + } + + class TubeGeometry2 extends BufferGeometry2 { + constructor(path = new QuadraticBezierCurve32(new Vector32(-1, -1, 0), new Vector32(-1, 1, 0), new Vector32(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) { + super(); + this.type = "TubeGeometry"; + this.parameters = { + path, + tubularSegments, + radius, + radialSegments, + closed + }; + const frames2 = path.computeFrenetFrames(tubularSegments, closed); + this.tangents = frames2.tangents; + this.normals = frames2.normals; + this.binormals = frames2.binormals; + const vertex3 = new Vector32; + const normal = new Vector32; + const uv = new Vector22; + let P = new Vector32; + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; + generateBufferData(); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function generateBufferData() { + for (let i = 0;i < tubularSegments; i++) { + generateSegment(i); + } + generateSegment(closed === false ? tubularSegments : 0); + generateUVs(); + generateIndices(); + } + function generateSegment(i) { + P = path.getPointAt(i / tubularSegments, P); + const N = frames2.normals[i]; + const B = frames2.binormals[i]; + for (let j = 0;j <= radialSegments; j++) { + const v = j / radialSegments * Math.PI * 2; + const sin = Math.sin(v); + const cos = -Math.cos(v); + normal.x = cos * N.x + sin * B.x; + normal.y = cos * N.y + sin * B.y; + normal.z = cos * N.z + sin * B.z; + normal.normalize(); + normals.push(normal.x, normal.y, normal.z); + vertex3.x = P.x + radius * normal.x; + vertex3.y = P.y + radius * normal.y; + vertex3.z = P.z + radius * normal.z; + vertices.push(vertex3.x, vertex3.y, vertex3.z); + } + } + function generateIndices() { + for (let j = 1;j <= tubularSegments; j++) { + for (let i = 1;i <= radialSegments; i++) { + const a = (radialSegments + 1) * (j - 1) + (i - 1); + const b = (radialSegments + 1) * j + (i - 1); + const c = (radialSegments + 1) * j + i; + const d = (radialSegments + 1) * (j - 1) + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + } + function generateUVs() { + for (let i = 0;i <= tubularSegments; i++) { + for (let j = 0;j <= radialSegments; j++) { + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + uvs.push(uv.x, uv.y); + } + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.path = this.parameters.path.toJSON(); + return data2; + } + static fromJSON(data2) { + return new TubeGeometry2(new Curves2[data2.path.type]().fromJSON(data2.path), data2.tubularSegments, data2.radius, data2.radialSegments, data2.closed); + } + } + + class WireframeGeometry2 extends BufferGeometry2 { + constructor(geometry = null) { + super(); + this.type = "WireframeGeometry"; + this.parameters = { + geometry + }; + if (geometry !== null) { + const vertices = []; + const edges = new Set; + const start = new Vector32; + const end = new Vector32; + if (geometry.index !== null) { + const position2 = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; + if (groups.length === 0) { + groups = [{ start: 0, count: indices.count, materialIndex: 0 }]; + } + for (let o = 0, ol = groups.length;o < ol; ++o) { + const group = groups[o]; + const groupStart = group.start; + const groupCount = group.count; + for (let i = groupStart, l = groupStart + groupCount;i < l; i += 3) { + for (let j = 0;j < 3; j++) { + const index1 = indices.getX(i + j); + const index2 = indices.getX(i + (j + 1) % 3); + start.fromBufferAttribute(position2, index1); + end.fromBufferAttribute(position2, index2); + if (isUniqueEdge2(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + } else { + const position2 = geometry.attributes.position; + for (let i = 0, l = position2.count / 3;i < l; i++) { + for (let j = 0;j < 3; j++) { + const index1 = 3 * i + j; + const index2 = 3 * i + (j + 1) % 3; + start.fromBufferAttribute(position2, index1); + end.fromBufferAttribute(position2, index2); + if (isUniqueEdge2(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + } + function isUniqueEdge2(start, end, edges) { + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; + if (edges.has(hash1) === true || edges.has(hash2) === true) { + return false; + } else { + edges.add(hash1); + edges.add(hash2); + return true; + } + } + var Geometries2 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + BoxGeometry: BoxGeometry2, + CapsuleGeometry: CapsuleGeometry2, + CircleGeometry: CircleGeometry2, + ConeGeometry: ConeGeometry2, + CylinderGeometry: CylinderGeometry2, + DodecahedronGeometry: DodecahedronGeometry2, + EdgesGeometry: EdgesGeometry2, + ExtrudeGeometry: ExtrudeGeometry2, + IcosahedronGeometry: IcosahedronGeometry2, + LatheGeometry: LatheGeometry2, + OctahedronGeometry: OctahedronGeometry2, + PlaneGeometry: PlaneGeometry2, + PolyhedronGeometry: PolyhedronGeometry2, + RingGeometry: RingGeometry2, + ShapeGeometry: ShapeGeometry2, + SphereGeometry: SphereGeometry2, + TetrahedronGeometry: TetrahedronGeometry2, + TorusGeometry: TorusGeometry2, + TorusKnotGeometry: TorusKnotGeometry2, + TubeGeometry: TubeGeometry2, + WireframeGeometry: WireframeGeometry2 + }); + + class ShadowMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isShadowMaterial = true; + this.type = "ShadowMaterial"; + this.color = new Color2(0); + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.fog = source.fog; + return this; + } + } + + class RawShaderMaterial2 extends ShaderMaterial2 { + constructor(parameters) { + super(parameters); + this.isRawShaderMaterial = true; + this.type = "RawShaderMaterial"; + } + } + + class MeshStandardMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshStandardMaterial = true; + this.type = "MeshStandardMaterial"; + this.defines = { STANDARD: "" }; + this.color = new Color2(16777215); + this.roughness = 1; + this.metalness = 0; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color2(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.roughnessMap = null; + this.metalnessMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler2; + this.envMapIntensity = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { STANDARD: "" }; + this.color.copy(source.color); + this.roughness = source.roughness; + this.metalness = source.metalness; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.roughnessMap = source.roughnessMap; + this.metalnessMap = source.metalnessMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.envMapIntensity = source.envMapIntensity; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + + class MeshPhysicalMaterial2 extends MeshStandardMaterial2 { + constructor(parameters) { + super(); + this.isMeshPhysicalMaterial = true; + this.defines = { + STANDARD: "", + PHYSICAL: "" + }; + this.type = "MeshPhysicalMaterial"; + this.anisotropyRotation = 0; + this.anisotropyMap = null; + this.clearcoatMap = null; + this.clearcoatRoughness = 0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector22(1, 1); + this.clearcoatNormalMap = null; + this.ior = 1.5; + Object.defineProperty(this, "reflectivity", { + get: function() { + return clamp3(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1); + }, + set: function(reflectivity) { + this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity); + } + }); + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [100, 400]; + this.iridescenceThicknessMap = null; + this.sheenColor = new Color2(0); + this.sheenColorMap = null; + this.sheenRoughness = 1; + this.sheenRoughnessMap = null; + this.transmissionMap = null; + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = Infinity; + this.attenuationColor = new Color2(1, 1, 1); + this.specularIntensity = 1; + this.specularIntensityMap = null; + this.specularColor = new Color2(1, 1, 1); + this.specularColorMap = null; + this._anisotropy = 0; + this._clearcoat = 0; + this._dispersion = 0; + this._iridescence = 0; + this._sheen = 0; + this._transmission = 0; + this.setValues(parameters); + } + get anisotropy() { + return this._anisotropy; + } + set anisotropy(value2) { + if (this._anisotropy > 0 !== value2 > 0) { + this.version++; + } + this._anisotropy = value2; + } + get clearcoat() { + return this._clearcoat; + } + set clearcoat(value2) { + if (this._clearcoat > 0 !== value2 > 0) { + this.version++; + } + this._clearcoat = value2; + } + get iridescence() { + return this._iridescence; + } + set iridescence(value2) { + if (this._iridescence > 0 !== value2 > 0) { + this.version++; + } + this._iridescence = value2; + } + get dispersion() { + return this._dispersion; + } + set dispersion(value2) { + if (this._dispersion > 0 !== value2 > 0) { + this.version++; + } + this._dispersion = value2; + } + get sheen() { + return this._sheen; + } + set sheen(value2) { + if (this._sheen > 0 !== value2 > 0) { + this.version++; + } + this._sheen = value2; + } + get transmission() { + return this._transmission; + } + set transmission(value2) { + if (this._transmission > 0 !== value2 > 0) { + this.version++; + } + this._transmission = value2; + } + copy(source) { + super.copy(source); + this.defines = { + STANDARD: "", + PHYSICAL: "" + }; + this.anisotropy = source.anisotropy; + this.anisotropyRotation = source.anisotropyRotation; + this.anisotropyMap = source.anisotropyMap; + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy(source.clearcoatNormalScale); + this.dispersion = source.dispersion; + this.ior = source.ior; + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [...source.iridescenceThicknessRange]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + this.sheen = source.sheen; + this.sheenColor.copy(source.sheenColor); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy(source.attenuationColor); + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy(source.specularColor); + this.specularColorMap = source.specularColorMap; + return this; + } + } + + class MeshPhongMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshPhongMaterial = true; + this.type = "MeshPhongMaterial"; + this.color = new Color2(16777215); + this.specular = new Color2(1118481); + this.shininess = 30; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color2(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler2; + this.combine = MultiplyOperation2; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.specular.copy(source.specular); + this.shininess = source.shininess; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + + class MeshToonMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshToonMaterial = true; + this.defines = { TOON: "" }; + this.type = "MeshToonMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.gradientMap = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color2(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.gradientMap = source.gradientMap; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } + } + + class MeshNormalMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshNormalMaterial = true; + this.type = "MeshNormalMaterial"; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.flatShading = false; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.flatShading = source.flatShading; + return this; + } + } + + class MeshLambertMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshLambertMaterial = true; + this.type = "MeshLambertMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color2(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler2; + this.combine = MultiplyOperation2; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + + class MeshDepthMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshDepthMaterial = true; + this.type = "MeshDepthMaterial"; + this.depthPacking = BasicDepthPacking2; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.depthPacking = source.depthPacking; + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + return this; + } + } + + class MeshDistanceMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshDistanceMaterial = true; + this.type = "MeshDistanceMaterial"; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + return this; + } + } + + class MeshMatcapMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshMatcapMaterial = true; + this.defines = { MATCAP: "" }; + this.type = "MeshMatcapMaterial"; + this.color = new Color2(16777215); + this.matcap = null; + this.map = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { MATCAP: "" }; + this.color.copy(source.color); + this.matcap = source.matcap; + this.map = source.map; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + + class LineDashedMaterial2 extends LineBasicMaterial2 { + constructor(parameters) { + super(); + this.isLineDashedMaterial = true; + this.type = "LineDashedMaterial"; + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + return this; + } + } + function convertArray2(array, type, forceClone) { + if (!array || !forceClone && array.constructor === type) + return array; + if (typeof type.BYTES_PER_ELEMENT === "number") { + return new type(array); + } + return Array.prototype.slice.call(array); + } + function isTypedArray2(object) { + return ArrayBuffer.isView(object) && !(object instanceof DataView); + } + function getKeyframeOrder2(times) { + function compareTime(i, j) { + return times[i] - times[j]; + } + const n = times.length; + const result = new Array(n); + for (let i = 0;i !== n; ++i) + result[i] = i; + result.sort(compareTime); + return result; + } + function sortedArray2(values2, stride, order) { + const nValues = values2.length; + const result = new values2.constructor(nValues); + for (let i = 0, dstOffset = 0;dstOffset !== nValues; ++i) { + const srcOffset = order[i] * stride; + for (let j = 0;j !== stride; ++j) { + result[dstOffset++] = values2[srcOffset + j]; + } + } + return result; + } + function flattenJSON2(jsonKeys, times, values2, valuePropertyName) { + let i = 1, key2 = jsonKeys[0]; + while (key2 !== undefined && key2[valuePropertyName] === undefined) { + key2 = jsonKeys[i++]; + } + if (key2 === undefined) + return; + let value2 = key2[valuePropertyName]; + if (value2 === undefined) + return; + if (Array.isArray(value2)) { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + values2.push.apply(values2, value2); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } else if (value2.toArray !== undefined) { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + value2.toArray(values2, values2.length); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } else { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + values2.push(value2); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } + } + function subclip2(sourceClip, name2, startFrame, endFrame, fps = 30) { + const clip = sourceClip.clone(); + clip.name = name2; + const tracks = []; + for (let i = 0;i < clip.tracks.length; ++i) { + const track = clip.tracks[i]; + const valueSize = track.getValueSize(); + const times = []; + const values2 = []; + for (let j = 0;j < track.times.length; ++j) { + const frame = track.times[j] * fps; + if (frame < startFrame || frame >= endFrame) + continue; + times.push(track.times[j]); + for (let k = 0;k < valueSize; ++k) { + values2.push(track.values[j * valueSize + k]); + } + } + if (times.length === 0) + continue; + track.times = convertArray2(times, track.times.constructor); + track.values = convertArray2(values2, track.values.constructor); + tracks.push(track); + } + clip.tracks = tracks; + let minStartTime = Infinity; + for (let i = 0;i < clip.tracks.length; ++i) { + if (minStartTime > clip.tracks[i].times[0]) { + minStartTime = clip.tracks[i].times[0]; + } + } + for (let i = 0;i < clip.tracks.length; ++i) { + clip.tracks[i].shift(-1 * minStartTime); + } + clip.resetDuration(); + return clip; + } + function makeClipAdditive2(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) { + if (fps <= 0) + fps = 30; + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; + for (let i = 0;i < numTracks; ++i) { + const referenceTrack = referenceClip.tracks[i]; + const referenceTrackType = referenceTrack.ValueTypeName; + if (referenceTrackType === "bool" || referenceTrackType === "string") + continue; + const targetTrack = targetClip.tracks.find(function(track) { + return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType; + }); + if (targetTrack === undefined) + continue; + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); + if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + referenceOffset = referenceValueSize / 3; + } + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); + if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + targetOffset = targetValueSize / 3; + } + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; + if (referenceTime <= referenceTrack.times[0]) { + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else if (referenceTime >= referenceTrack.times[lastIndex]) { + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else { + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate(referenceTime); + referenceValue = interpolant.resultBuffer.slice(startIndex, endIndex); + } + if (referenceTrackType === "quaternion") { + const referenceQuat = new Quaternion2().fromArray(referenceValue).normalize().conjugate(); + referenceQuat.toArray(referenceValue); + } + const numTimes = targetTrack.times.length; + for (let j = 0;j < numTimes; ++j) { + const valueStart = j * targetValueSize + targetOffset; + if (referenceTrackType === "quaternion") { + Quaternion2.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart); + } else { + const valueEnd = targetValueSize - targetOffset * 2; + for (let k = 0;k < valueEnd; ++k) { + targetTrack.values[valueStart + k] -= referenceValue[k]; + } + } + } + } + targetClip.blendMode = AdditiveAnimationBlendMode2; + return targetClip; + } + var AnimationUtils2 = { + convertArray: convertArray2, + isTypedArray: isTypedArray2, + getKeyframeOrder: getKeyframeOrder2, + sortedArray: sortedArray2, + flattenJSON: flattenJSON2, + subclip: subclip2, + makeClipAdditive: makeClipAdditive2 + }; + + class Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; + this.settings = null; + this.DefaultSettings_ = {}; + } + evaluate(t) { + const pp = this.parameterPositions; + let i1 = this._cachedIndex, t1 = pp[i1], t0 = pp[i1 - 1]; + validate_interval: { + seek: { + let right; + linear_scan: { + forward_scan: + if (!(t < t1)) { + for (let giveUpAt = i1 + 2;; ) { + if (t1 === undefined) { + if (t < t0) + break forward_scan; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + if (i1 === giveUpAt) + break; + t0 = t1; + t1 = pp[++i1]; + if (t < t1) { + break seek; + } + } + right = pp.length; + break linear_scan; + } + if (!(t >= t0)) { + const t1global = pp[1]; + if (t < t1global) { + i1 = 2; + t0 = t1global; + } + for (let giveUpAt = i1 - 2;; ) { + if (t0 === undefined) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (i1 === giveUpAt) + break; + t1 = t0; + t0 = pp[--i1 - 1]; + if (t >= t0) { + break seek; + } + } + right = i1; + i1 = 0; + break linear_scan; + } + break validate_interval; + } + while (i1 < right) { + const mid = i1 + right >>> 1; + if (t < pp[mid]) { + right = mid; + } else { + i1 = mid + 1; + } + } + t1 = pp[i1]; + t0 = pp[i1 - 1]; + if (t0 === undefined) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (t1 === undefined) { + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + } + this._cachedIndex = i1; + this.intervalChanged_(i1, t0, t1); + } + return this.interpolate_(i1, t0, t, t1); + } + getSettings_() { + return this.settings || this.DefaultSettings_; + } + copySampleValue_(index2) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, offset = index2 * stride; + for (let i = 0;i !== stride; ++i) { + result[i] = values2[offset + i]; + } + return result; + } + interpolate_() { + throw new Error("call to abstract method"); + } + intervalChanged_() { + } + } + + class CubicInterpolant2 extends Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; + this.DefaultSettings_ = { + endingStart: ZeroCurvatureEnding2, + endingEnd: ZeroCurvatureEnding2 + }; + } + intervalChanged_(i1, t0, t1) { + const pp = this.parameterPositions; + let iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[iPrev], tNext = pp[iNext]; + if (tPrev === undefined) { + switch (this.getSettings_().endingStart) { + case ZeroSlopeEnding2: + iPrev = i1; + tPrev = 2 * t0 - t1; + break; + case WrapAroundEnding2: + iPrev = pp.length - 2; + tPrev = t0 + pp[iPrev] - pp[iPrev + 1]; + break; + default: + iPrev = i1; + tPrev = t1; + } + } + if (tNext === undefined) { + switch (this.getSettings_().endingEnd) { + case ZeroSlopeEnding2: + iNext = i1; + tNext = 2 * t1 - t0; + break; + case WrapAroundEnding2: + iNext = 1; + tNext = t1 + pp[1] - pp[0]; + break; + default: + iNext = i1 - 1; + tNext = t0; + } + } + const halfDt = (t1 - t0) * 0.5, stride = this.valueSize; + this._weightPrev = halfDt / (t0 - tPrev); + this._weightNext = halfDt / (tNext - t1); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o0 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p = (t - t0) / (t1 - t0), pp = p * p, ppp = pp * p; + const sP = -wP * ppp + 2 * wP * pp - wP * p; + const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1; + const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; + for (let i = 0;i !== stride; ++i) { + result[i] = sP * values2[oP + i] + s0 * values2[o0 + i] + s1 * values2[o1 + i] + sN * values2[oN + i]; + } + return result; + } + } + + class LinearInterpolant2 extends Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = (t - t0) / (t1 - t0), weight0 = 1 - weight1; + for (let i = 0;i !== stride; ++i) { + result[i] = values2[offset0 + i] * weight0 + values2[offset1 + i] * weight1; + } + return result; + } + } + + class DiscreteInterpolant2 extends Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1) { + return this.copySampleValue_(i1 - 1); + } + } + + class KeyframeTrack2 { + constructor(name2, times, values2, interpolation) { + if (name2 === undefined) + throw new Error("THREE.KeyframeTrack: track name is undefined"); + if (times === undefined || times.length === 0) + throw new Error("THREE.KeyframeTrack: no keyframes in track named " + name2); + this.name = name2; + this.times = convertArray2(times, this.TimeBufferType); + this.values = convertArray2(values2, this.ValueBufferType); + this.setInterpolation(interpolation || this.DefaultInterpolation); + } + static toJSON(track) { + const trackType = track.constructor; + let json; + if (trackType.toJSON !== this.toJSON) { + json = trackType.toJSON(track); + } else { + json = { + name: track.name, + times: convertArray2(track.times, Array), + values: convertArray2(track.values, Array) + }; + const interpolation = track.getInterpolation(); + if (interpolation !== track.DefaultInterpolation) { + json.interpolation = interpolation; + } + } + json.type = track.ValueTypeName; + return json; + } + InterpolantFactoryMethodDiscrete(result) { + return new DiscreteInterpolant2(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodLinear(result) { + return new LinearInterpolant2(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodSmooth(result) { + return new CubicInterpolant2(this.times, this.values, this.getValueSize(), result); + } + setInterpolation(interpolation) { + let factoryMethod; + switch (interpolation) { + case InterpolateDiscrete2: + factoryMethod = this.InterpolantFactoryMethodDiscrete; + break; + case InterpolateLinear2: + factoryMethod = this.InterpolantFactoryMethodLinear; + break; + case InterpolateSmooth2: + factoryMethod = this.InterpolantFactoryMethodSmooth; + break; + } + if (factoryMethod === undefined) { + const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; + if (this.createInterpolant === undefined) { + if (interpolation !== this.DefaultInterpolation) { + this.setInterpolation(this.DefaultInterpolation); + } else { + throw new Error(message); + } + } + console.warn("THREE.KeyframeTrack:", message); + return this; + } + this.createInterpolant = factoryMethod; + return this; + } + getInterpolation() { + switch (this.createInterpolant) { + case this.InterpolantFactoryMethodDiscrete: + return InterpolateDiscrete2; + case this.InterpolantFactoryMethodLinear: + return InterpolateLinear2; + case this.InterpolantFactoryMethodSmooth: + return InterpolateSmooth2; + } + } + getValueSize() { + return this.values.length / this.times.length; + } + shift(timeOffset) { + if (timeOffset !== 0) { + const times = this.times; + for (let i = 0, n = times.length;i !== n; ++i) { + times[i] += timeOffset; + } + } + return this; + } + scale(timeScale) { + if (timeScale !== 1) { + const times = this.times; + for (let i = 0, n = times.length;i !== n; ++i) { + times[i] *= timeScale; + } + } + return this; + } + trim(startTime, endTime) { + const times = this.times, nKeys = times.length; + let from = 0, to = nKeys - 1; + while (from !== nKeys && times[from] < startTime) { + ++from; + } + while (to !== -1 && times[to] > endTime) { + --to; + } + ++to; + if (from !== 0 || to !== nKeys) { + if (from >= to) { + to = Math.max(to, 1); + from = to - 1; + } + const stride = this.getValueSize(); + this.times = times.slice(from, to); + this.values = this.values.slice(from * stride, to * stride); + } + return this; + } + validate() { + let valid = true; + const valueSize = this.getValueSize(); + if (valueSize - Math.floor(valueSize) !== 0) { + console.error("THREE.KeyframeTrack: Invalid value size in track.", this); + valid = false; + } + const times = this.times, values2 = this.values, nKeys = times.length; + if (nKeys === 0) { + console.error("THREE.KeyframeTrack: Track is empty.", this); + valid = false; + } + let prevTime = null; + for (let i = 0;i !== nKeys; i++) { + const currTime = times[i]; + if (typeof currTime === "number" && isNaN(currTime)) { + console.error("THREE.KeyframeTrack: Time is not a valid number.", this, i, currTime); + valid = false; + break; + } + if (prevTime !== null && prevTime > currTime) { + console.error("THREE.KeyframeTrack: Out of order keys.", this, i, currTime, prevTime); + valid = false; + break; + } + prevTime = currTime; + } + if (values2 !== undefined) { + if (isTypedArray2(values2)) { + for (let i = 0, n = values2.length;i !== n; ++i) { + const value2 = values2[i]; + if (isNaN(value2)) { + console.error("THREE.KeyframeTrack: Value is not a valid number.", this, i, value2); + valid = false; + break; + } + } + } + } + return valid; + } + optimize() { + const times = this.times.slice(), values2 = this.values.slice(), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth2, lastIndex = times.length - 1; + let writeIndex = 1; + for (let i = 1;i < lastIndex; ++i) { + let keep = false; + const time2 = times[i]; + const timeNext = times[i + 1]; + if (time2 !== timeNext && (i !== 1 || time2 !== times[0])) { + if (!smoothInterpolation) { + const offset = i * stride, offsetP = offset - stride, offsetN = offset + stride; + for (let j = 0;j !== stride; ++j) { + const value2 = values2[offset + j]; + if (value2 !== values2[offsetP + j] || value2 !== values2[offsetN + j]) { + keep = true; + break; + } + } + } else { + keep = true; + } + } + if (keep) { + if (i !== writeIndex) { + times[writeIndex] = times[i]; + const readOffset = i * stride, writeOffset = writeIndex * stride; + for (let j = 0;j !== stride; ++j) { + values2[writeOffset + j] = values2[readOffset + j]; + } + } + ++writeIndex; + } + } + if (lastIndex > 0) { + times[writeIndex] = times[lastIndex]; + for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0;j !== stride; ++j) { + values2[writeOffset + j] = values2[readOffset + j]; + } + ++writeIndex; + } + if (writeIndex !== times.length) { + this.times = times.slice(0, writeIndex); + this.values = values2.slice(0, writeIndex * stride); + } else { + this.times = times; + this.values = values2; + } + return this; + } + clone() { + const times = this.times.slice(); + const values2 = this.values.slice(); + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack(this.name, times, values2); + track.createInterpolant = this.createInterpolant; + return track; + } + } + KeyframeTrack2.prototype.TimeBufferType = Float32Array; + KeyframeTrack2.prototype.ValueBufferType = Float32Array; + KeyframeTrack2.prototype.DefaultInterpolation = InterpolateLinear2; + + class BooleanKeyframeTrack2 extends KeyframeTrack2 { + constructor(name2, times, values2) { + super(name2, times, values2); + } + } + BooleanKeyframeTrack2.prototype.ValueTypeName = "bool"; + BooleanKeyframeTrack2.prototype.ValueBufferType = Array; + BooleanKeyframeTrack2.prototype.DefaultInterpolation = InterpolateDiscrete2; + BooleanKeyframeTrack2.prototype.InterpolantFactoryMethodLinear = undefined; + BooleanKeyframeTrack2.prototype.InterpolantFactoryMethodSmooth = undefined; + + class ColorKeyframeTrack2 extends KeyframeTrack2 { + } + ColorKeyframeTrack2.prototype.ValueTypeName = "color"; + + class NumberKeyframeTrack2 extends KeyframeTrack2 { + } + NumberKeyframeTrack2.prototype.ValueTypeName = "number"; + + class QuaternionLinearInterpolant2 extends Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, alpha = (t - t0) / (t1 - t0); + let offset = i1 * stride; + for (let end = offset + stride;offset !== end; offset += 4) { + Quaternion2.slerpFlat(result, 0, values2, offset - stride, values2, offset, alpha); + } + return result; + } + } + + class QuaternionKeyframeTrack2 extends KeyframeTrack2 { + InterpolantFactoryMethodLinear(result) { + return new QuaternionLinearInterpolant2(this.times, this.values, this.getValueSize(), result); + } + } + QuaternionKeyframeTrack2.prototype.ValueTypeName = "quaternion"; + QuaternionKeyframeTrack2.prototype.InterpolantFactoryMethodSmooth = undefined; + + class StringKeyframeTrack2 extends KeyframeTrack2 { + constructor(name2, times, values2) { + super(name2, times, values2); + } + } + StringKeyframeTrack2.prototype.ValueTypeName = "string"; + StringKeyframeTrack2.prototype.ValueBufferType = Array; + StringKeyframeTrack2.prototype.DefaultInterpolation = InterpolateDiscrete2; + StringKeyframeTrack2.prototype.InterpolantFactoryMethodLinear = undefined; + StringKeyframeTrack2.prototype.InterpolantFactoryMethodSmooth = undefined; + + class VectorKeyframeTrack2 extends KeyframeTrack2 { + } + VectorKeyframeTrack2.prototype.ValueTypeName = "vector"; + + class AnimationClip2 { + constructor(name2 = "", duration = -1, tracks = [], blendMode = NormalAnimationBlendMode2) { + this.name = name2; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; + this.uuid = generateUUID2(); + if (this.duration < 0) { + this.resetDuration(); + } + } + static parse(json) { + const tracks = [], jsonTracks = json.tracks, frameTime = 1 / (json.fps || 1); + for (let i = 0, n = jsonTracks.length;i !== n; ++i) { + tracks.push(parseKeyframeTrack2(jsonTracks[i]).scale(frameTime)); + } + const clip = new this(json.name, json.duration, tracks, json.blendMode); + clip.uuid = json.uuid; + return clip; + } + static toJSON(clip) { + const tracks = [], clipTracks = clip.tracks; + const json = { + name: clip.name, + duration: clip.duration, + tracks, + uuid: clip.uuid, + blendMode: clip.blendMode + }; + for (let i = 0, n = clipTracks.length;i !== n; ++i) { + tracks.push(KeyframeTrack2.toJSON(clipTracks[i])); + } + return json; + } + static CreateFromMorphTargetSequence(name2, morphTargetSequence, fps, noLoop) { + const numMorphTargets = morphTargetSequence.length; + const tracks = []; + for (let i = 0;i < numMorphTargets; i++) { + let times = []; + let values2 = []; + times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets); + values2.push(0, 1, 0); + const order = getKeyframeOrder2(times); + times = sortedArray2(times, 1, order); + values2 = sortedArray2(values2, 1, order); + if (!noLoop && times[0] === 0) { + times.push(numMorphTargets); + values2.push(values2[0]); + } + tracks.push(new NumberKeyframeTrack2(".morphTargetInfluences[" + morphTargetSequence[i].name + "]", times, values2).scale(1 / fps)); + } + return new this(name2, -1, tracks); + } + static findByName(objectOrClipArray, name2) { + let clipArray = objectOrClipArray; + if (!Array.isArray(objectOrClipArray)) { + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; + } + for (let i = 0;i < clipArray.length; i++) { + if (clipArray[i].name === name2) { + return clipArray[i]; + } + } + return null; + } + static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) { + const animationToMorphTargets = {}; + const pattern = /^([\w-]*?)([\d]+)$/; + for (let i = 0, il = morphTargets.length;i < il; i++) { + const morphTarget = morphTargets[i]; + const parts = morphTarget.name.match(pattern); + if (parts && parts.length > 1) { + const name2 = parts[1]; + let animationMorphTargets = animationToMorphTargets[name2]; + if (!animationMorphTargets) { + animationToMorphTargets[name2] = animationMorphTargets = []; + } + animationMorphTargets.push(morphTarget); + } + } + const clips = []; + for (const name2 in animationToMorphTargets) { + clips.push(this.CreateFromMorphTargetSequence(name2, animationToMorphTargets[name2], fps, noLoop)); + } + return clips; + } + static parseAnimation(animation, bones) { + if (!animation) { + console.error("THREE.AnimationClip: No animation in JSONLoader data."); + return null; + } + const addNonemptyTrack = function(trackType, trackName, animationKeys, propertyName, destTracks) { + if (animationKeys.length !== 0) { + const times = []; + const values2 = []; + flattenJSON2(animationKeys, times, values2, propertyName); + if (times.length !== 0) { + destTracks.push(new trackType(trackName, times, values2)); + } + } + }; + const tracks = []; + const clipName = animation.name || "default"; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; + let duration = animation.length || -1; + const hierarchyTracks = animation.hierarchy || []; + for (let h = 0;h < hierarchyTracks.length; h++) { + const animationKeys = hierarchyTracks[h].keys; + if (!animationKeys || animationKeys.length === 0) + continue; + if (animationKeys[0].morphTargets) { + const morphTargetNames = {}; + let k; + for (k = 0;k < animationKeys.length; k++) { + if (animationKeys[k].morphTargets) { + for (let m = 0;m < animationKeys[k].morphTargets.length; m++) { + morphTargetNames[animationKeys[k].morphTargets[m]] = -1; + } + } + } + for (const morphTargetName in morphTargetNames) { + const times = []; + const values2 = []; + for (let m = 0;m !== animationKeys[k].morphTargets.length; ++m) { + const animationKey = animationKeys[k]; + times.push(animationKey.time); + values2.push(animationKey.morphTarget === morphTargetName ? 1 : 0); + } + tracks.push(new NumberKeyframeTrack2(".morphTargetInfluence[" + morphTargetName + "]", times, values2)); + } + duration = morphTargetNames.length * fps; + } else { + const boneName = ".bones[" + bones[h].name + "]"; + addNonemptyTrack(VectorKeyframeTrack2, boneName + ".position", animationKeys, "pos", tracks); + addNonemptyTrack(QuaternionKeyframeTrack2, boneName + ".quaternion", animationKeys, "rot", tracks); + addNonemptyTrack(VectorKeyframeTrack2, boneName + ".scale", animationKeys, "scl", tracks); + } + } + if (tracks.length === 0) { + return null; + } + const clip = new this(clipName, duration, tracks, blendMode); + return clip; + } + resetDuration() { + const tracks = this.tracks; + let duration = 0; + for (let i = 0, n = tracks.length;i !== n; ++i) { + const track = this.tracks[i]; + duration = Math.max(duration, track.times[track.times.length - 1]); + } + this.duration = duration; + return this; + } + trim() { + for (let i = 0;i < this.tracks.length; i++) { + this.tracks[i].trim(0, this.duration); + } + return this; + } + validate() { + let valid = true; + for (let i = 0;i < this.tracks.length; i++) { + valid = valid && this.tracks[i].validate(); + } + return valid; + } + optimize() { + for (let i = 0;i < this.tracks.length; i++) { + this.tracks[i].optimize(); + } + return this; + } + clone() { + const tracks = []; + for (let i = 0;i < this.tracks.length; i++) { + tracks.push(this.tracks[i].clone()); + } + return new this.constructor(this.name, this.duration, tracks, this.blendMode); + } + toJSON() { + return this.constructor.toJSON(this); + } + } + function getTrackTypeForValueTypeName2(typeName) { + switch (typeName.toLowerCase()) { + case "scalar": + case "double": + case "float": + case "number": + case "integer": + return NumberKeyframeTrack2; + case "vector": + case "vector2": + case "vector3": + case "vector4": + return VectorKeyframeTrack2; + case "color": + return ColorKeyframeTrack2; + case "quaternion": + return QuaternionKeyframeTrack2; + case "bool": + case "boolean": + return BooleanKeyframeTrack2; + case "string": + return StringKeyframeTrack2; + } + throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + typeName); + } + function parseKeyframeTrack2(json) { + if (json.type === undefined) { + throw new Error("THREE.KeyframeTrack: track type undefined, can not parse"); + } + const trackType = getTrackTypeForValueTypeName2(json.type); + if (json.times === undefined) { + const times = [], values2 = []; + flattenJSON2(json.keys, times, values2, "value"); + json.times = times; + json.values = values2; + } + if (trackType.parse !== undefined) { + return trackType.parse(json); + } else { + return new trackType(json.name, json.times, json.values, json.interpolation); + } + } + var Cache2 = { + enabled: false, + files: {}, + add: function(key2, file) { + if (this.enabled === false) + return; + this.files[key2] = file; + }, + get: function(key2) { + if (this.enabled === false) + return; + return this.files[key2]; + }, + remove: function(key2) { + delete this.files[key2]; + }, + clear: function() { + this.files = {}; + } + }; + + class LoadingManager2 { + constructor(onLoad, onProgress, onError) { + const scope = this; + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + this.itemStart = function(url) { + itemsTotal++; + if (isLoading === false) { + if (scope.onStart !== undefined) { + scope.onStart(url, itemsLoaded, itemsTotal); + } + } + isLoading = true; + }; + this.itemEnd = function(url) { + itemsLoaded++; + if (scope.onProgress !== undefined) { + scope.onProgress(url, itemsLoaded, itemsTotal); + } + if (itemsLoaded === itemsTotal) { + isLoading = false; + if (scope.onLoad !== undefined) { + scope.onLoad(); + } + } + }; + this.itemError = function(url) { + if (scope.onError !== undefined) { + scope.onError(url); + } + }; + this.resolveURL = function(url) { + if (urlModifier) { + return urlModifier(url); + } + return url; + }; + this.setURLModifier = function(transform2) { + urlModifier = transform2; + return this; + }; + this.addHandler = function(regex, loader) { + handlers.push(regex, loader); + return this; + }; + this.removeHandler = function(regex) { + const index2 = handlers.indexOf(regex); + if (index2 !== -1) { + handlers.splice(index2, 2); + } + return this; + }; + this.getHandler = function(file) { + for (let i = 0, l = handlers.length;i < l; i += 2) { + const regex = handlers[i]; + const loader = handlers[i + 1]; + if (regex.global) + regex.lastIndex = 0; + if (regex.test(file)) { + return loader; + } + } + return null; + }; + } + } + var DefaultLoadingManager2 = /* @__PURE__ */ new LoadingManager2; + + class Loader2 { + constructor(manager) { + this.manager = manager !== undefined ? manager : DefaultLoadingManager2; + this.crossOrigin = "anonymous"; + this.withCredentials = false; + this.path = ""; + this.resourcePath = ""; + this.requestHeader = {}; + } + load() { + } + loadAsync(url, onProgress) { + const scope = this; + return new Promise(function(resolve, reject2) { + scope.load(url, resolve, onProgress, reject2); + }); + } + parse() { + } + setCrossOrigin(crossOrigin) { + this.crossOrigin = crossOrigin; + return this; + } + setWithCredentials(value2) { + this.withCredentials = value2; + return this; + } + setPath(path) { + this.path = path; + return this; + } + setResourcePath(resourcePath) { + this.resourcePath = resourcePath; + return this; + } + setRequestHeader(requestHeader) { + this.requestHeader = requestHeader; + return this; + } + } + Loader2.DEFAULT_MATERIAL_NAME = "__DEFAULT"; + var loading2 = {}; + + class HttpError2 extends Error { + constructor(message, response) { + super(message); + this.response = response; + } + } + + class FileLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (url === undefined) + url = ""; + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const cached = Cache2.get(url); + if (cached !== undefined) { + this.manager.itemStart(url); + setTimeout(() => { + if (onLoad) + onLoad(cached); + this.manager.itemEnd(url); + }, 0); + return cached; + } + if (loading2[url] !== undefined) { + loading2[url].push({ + onLoad, + onProgress, + onError + }); + return; + } + loading2[url] = []; + loading2[url].push({ + onLoad, + onProgress, + onError + }); + const req = new Request(url, { + headers: new Headers(this.requestHeader), + credentials: this.withCredentials ? "include" : "same-origin" + }); + const mimeType = this.mimeType; + const responseType = this.responseType; + fetch(req).then((response) => { + if (response.status === 200 || response.status === 0) { + if (response.status === 0) { + console.warn("THREE.FileLoader: HTTP Status 0 received."); + } + if (typeof ReadableStream === "undefined" || response.body === undefined || response.body.getReader === undefined) { + return response; + } + const callbacks = loading2[url]; + const reader = response.body.getReader(); + const contentLength = response.headers.get("X-File-Size") || response.headers.get("Content-Length"); + const total = contentLength ? parseInt(contentLength) : 0; + const lengthComputable = total !== 0; + let loaded = 0; + const stream = new ReadableStream({ + start(controller) { + readData(); + function readData() { + reader.read().then(({ done, value: value2 }) => { + if (done) { + controller.close(); + } else { + loaded += value2.byteLength; + const event = new ProgressEvent("progress", { lengthComputable, loaded, total }); + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onProgress) + callback.onProgress(event); + } + controller.enqueue(value2); + readData(); + } + }, (e) => { + controller.error(e); + }); + } + } + }); + return new Response(stream); + } else { + throw new HttpError2(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response); + } + }).then((response) => { + switch (responseType) { + case "arraybuffer": + return response.arrayBuffer(); + case "blob": + return response.blob(); + case "document": + return response.text().then((text2) => { + const parser = new DOMParser; + return parser.parseFromString(text2, mimeType); + }); + case "json": + return response.json(); + default: + if (mimeType === undefined) { + return response.text(); + } else { + const re = /charset="?([^;"\s]*)"?/i; + const exec = re.exec(mimeType); + const label = exec && exec[1] ? exec[1].toLowerCase() : undefined; + const decoder = new TextDecoder(label); + return response.arrayBuffer().then((ab) => decoder.decode(ab)); + } + } + }).then((data2) => { + Cache2.add(url, data2); + const callbacks = loading2[url]; + delete loading2[url]; + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onLoad) + callback.onLoad(data2); + } + }).catch((err) => { + const callbacks = loading2[url]; + if (callbacks === undefined) { + this.manager.itemError(url); + throw err; + } + delete loading2[url]; + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onError) + callback.onError(err); + } + this.manager.itemError(url); + }).finally(() => { + this.manager.itemEnd(url); + }); + this.manager.itemStart(url); + } + setResponseType(value2) { + this.responseType = value2; + return this; + } + setMimeType(value2) { + this.mimeType = value2; + return this; + } + } + + class AnimationLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader2(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const animations = []; + for (let i = 0;i < json.length; i++) { + const clip = AnimationClip2.parse(json[i]); + animations.push(clip); + } + return animations; + } + } + + class CompressedTextureLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const images = []; + const texture = new CompressedTexture2; + const loader = new FileLoader2(this.manager); + loader.setPath(this.path); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(scope.withCredentials); + let loaded = 0; + function loadTexture(i) { + loader.load(url[i], function(buffer) { + const texDatas = scope.parse(buffer, true); + images[i] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + loaded += 1; + if (loaded === 6) { + if (texDatas.mipmapCount === 1) + texture.minFilter = LinearFilter2; + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + } + }, onProgress, onError); + } + if (Array.isArray(url)) { + for (let i = 0, il = url.length;i < il; ++i) { + loadTexture(i); + } + } else { + loader.load(url, function(buffer) { + const texDatas = scope.parse(buffer, true); + if (texDatas.isCubemap) { + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + for (let f = 0;f < faces; f++) { + images[f] = { mipmaps: [] }; + for (let i = 0;i < texDatas.mipmapCount; i++) { + images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]); + images[f].format = texDatas.format; + images[f].width = texDatas.width; + images[f].height = texDatas.height; + } + } + texture.image = images; + } else { + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + } + if (texDatas.mipmapCount === 1) { + texture.minFilter = LinearFilter2; + } + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + }, onProgress, onError); + } + return texture; + } + } + + class ImageLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache2.get(url); + if (cached !== undefined) { + scope.manager.itemStart(url); + setTimeout(function() { + if (onLoad) + onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const image = createElementNS2("img"); + function onImageLoad() { + removeEventListeners(); + Cache2.add(url, this); + if (onLoad) + onLoad(this); + scope.manager.itemEnd(url); + } + function onImageError(event) { + removeEventListeners(); + if (onError) + onError(event); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + } + function removeEventListeners() { + image.removeEventListener("load", onImageLoad, false); + image.removeEventListener("error", onImageError, false); + } + image.addEventListener("load", onImageLoad, false); + image.addEventListener("error", onImageError, false); + if (url.slice(0, 5) !== "data:") { + if (this.crossOrigin !== undefined) + image.crossOrigin = this.crossOrigin; + } + scope.manager.itemStart(url); + image.src = url; + return image; + } + } + + class CubeTextureLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(urls, onLoad, onProgress, onError) { + const texture = new CubeTexture2; + texture.colorSpace = SRGBColorSpace2; + const loader = new ImageLoader2(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + let loaded = 0; + function loadTexture(i) { + loader.load(urls[i], function(image) { + texture.images[i] = image; + loaded++; + if (loaded === 6) { + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + } + }, undefined, onError); + } + for (let i = 0;i < urls.length; ++i) { + loadTexture(i); + } + return texture; + } + } + + class DataTextureLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const texture = new DataTexture2; + const loader = new FileLoader2(this.manager); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setPath(this.path); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(buffer) { + let texData; + try { + texData = scope.parse(buffer); + } catch (error) { + if (onError !== undefined) { + onError(error); + } else { + console.error(error); + return; + } + } + if (texData.image !== undefined) { + texture.image = texData.image; + } else if (texData.data !== undefined) { + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; + } + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping2; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping2; + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter2; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter2; + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + if (texData.colorSpace !== undefined) { + texture.colorSpace = texData.colorSpace; + } + if (texData.flipY !== undefined) { + texture.flipY = texData.flipY; + } + if (texData.format !== undefined) { + texture.format = texData.format; + } + if (texData.type !== undefined) { + texture.type = texData.type; + } + if (texData.mipmaps !== undefined) { + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter2; + } + if (texData.mipmapCount === 1) { + texture.minFilter = LinearFilter2; + } + if (texData.generateMipmaps !== undefined) { + texture.generateMipmaps = texData.generateMipmaps; + } + texture.needsUpdate = true; + if (onLoad) + onLoad(texture, texData); + }, onProgress, onError); + return texture; + } + } + + class TextureLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const texture = new Texture2; + const loader = new ImageLoader2(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + loader.load(url, function(image) { + texture.image = image; + texture.needsUpdate = true; + if (onLoad !== undefined) { + onLoad(texture); + } + }, onProgress, onError); + return texture; + } + } + + class Light2 extends Object3D2 { + constructor(color, intensity = 1) { + super(); + this.isLight = true; + this.type = "Light"; + this.color = new Color2(color); + this.intensity = intensity; + } + dispose() { + } + copy(source, recursive) { + super.copy(source, recursive); + this.color.copy(source.color); + this.intensity = source.intensity; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.color = this.color.getHex(); + data2.object.intensity = this.intensity; + if (this.groundColor !== undefined) + data2.object.groundColor = this.groundColor.getHex(); + if (this.distance !== undefined) + data2.object.distance = this.distance; + if (this.angle !== undefined) + data2.object.angle = this.angle; + if (this.decay !== undefined) + data2.object.decay = this.decay; + if (this.penumbra !== undefined) + data2.object.penumbra = this.penumbra; + if (this.shadow !== undefined) + data2.object.shadow = this.shadow.toJSON(); + if (this.target !== undefined) + data2.object.target = this.target.uuid; + return data2; + } + } + + class HemisphereLight2 extends Light2 { + constructor(skyColor, groundColor, intensity) { + super(skyColor, intensity); + this.isHemisphereLight = true; + this.type = "HemisphereLight"; + this.position.copy(Object3D2.DEFAULT_UP); + this.updateMatrix(); + this.groundColor = new Color2(groundColor); + } + copy(source, recursive) { + super.copy(source, recursive); + this.groundColor.copy(source.groundColor); + return this; + } + } + var _projScreenMatrix$12 = /* @__PURE__ */ new Matrix42; + var _lightPositionWorld$12 = /* @__PURE__ */ new Vector32; + var _lookTarget$12 = /* @__PURE__ */ new Vector32; + + class LightShadow2 { + constructor(camera) { + this.camera = camera; + this.intensity = 1; + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; + this.mapSize = new Vector22(512, 512); + this.map = null; + this.mapPass = null; + this.matrix = new Matrix42; + this.autoUpdate = true; + this.needsUpdate = false; + this._frustum = new Frustum2; + this._frameExtents = new Vector22(1, 1); + this._viewportCount = 1; + this._viewports = [ + new Vector42(0, 0, 1, 1) + ]; + } + getViewportCount() { + return this._viewportCount; + } + getFrustum() { + return this._frustum; + } + updateMatrices(light) { + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; + _lightPositionWorld$12.setFromMatrixPosition(light.matrixWorld); + shadowCamera.position.copy(_lightPositionWorld$12); + _lookTarget$12.setFromMatrixPosition(light.target.matrixWorld); + shadowCamera.lookAt(_lookTarget$12); + shadowCamera.updateMatrixWorld(); + _projScreenMatrix$12.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix$12); + shadowMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + shadowMatrix.multiply(_projScreenMatrix$12); + } + getViewport(viewportIndex) { + return this._viewports[viewportIndex]; + } + getFrameExtents() { + return this._frameExtents; + } + dispose() { + if (this.map) { + this.map.dispose(); + } + if (this.mapPass) { + this.mapPass.dispose(); + } + } + copy(source) { + this.camera = source.camera.clone(); + this.intensity = source.intensity; + this.bias = source.bias; + this.radius = source.radius; + this.mapSize.copy(source.mapSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + toJSON() { + const object = {}; + if (this.intensity !== 1) + object.intensity = this.intensity; + if (this.bias !== 0) + object.bias = this.bias; + if (this.normalBias !== 0) + object.normalBias = this.normalBias; + if (this.radius !== 1) + object.radius = this.radius; + if (this.mapSize.x !== 512 || this.mapSize.y !== 512) + object.mapSize = this.mapSize.toArray(); + object.camera = this.camera.toJSON(false).object; + delete object.camera.matrix; + return object; + } + } + + class SpotLightShadow2 extends LightShadow2 { + constructor() { + super(new PerspectiveCamera2(50, 1, 0.5, 500)); + this.isSpotLightShadow = true; + this.focus = 1; + } + updateMatrices(light) { + const camera = this.camera; + const fov3 = RAD2DEG2 * 2 * light.angle * this.focus; + const aspect3 = this.mapSize.width / this.mapSize.height; + const far = light.distance || camera.far; + if (fov3 !== camera.fov || aspect3 !== camera.aspect || far !== camera.far) { + camera.fov = fov3; + camera.aspect = aspect3; + camera.far = far; + camera.updateProjectionMatrix(); + } + super.updateMatrices(light); + } + copy(source) { + super.copy(source); + this.focus = source.focus; + return this; + } + } + + class SpotLight2 extends Light2 { + constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2) { + super(color, intensity); + this.isSpotLight = true; + this.type = "SpotLight"; + this.position.copy(Object3D2.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D2; + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; + this.map = null; + this.shadow = new SpotLightShadow2; + } + get power() { + return this.intensity * Math.PI; + } + set power(power) { + this.intensity = power / Math.PI; + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } + } + var _projScreenMatrix2 = /* @__PURE__ */ new Matrix42; + var _lightPositionWorld2 = /* @__PURE__ */ new Vector32; + var _lookTarget2 = /* @__PURE__ */ new Vector32; + + class PointLightShadow2 extends LightShadow2 { + constructor() { + super(new PerspectiveCamera2(90, 1, 0.5, 500)); + this.isPointLightShadow = true; + this._frameExtents = new Vector22(4, 2); + this._viewportCount = 6; + this._viewports = [ + new Vector42(2, 1, 1, 1), + new Vector42(0, 1, 1, 1), + new Vector42(3, 1, 1, 1), + new Vector42(1, 1, 1, 1), + new Vector42(3, 0, 1, 1), + new Vector42(1, 0, 1, 1) + ]; + this._cubeDirections = [ + new Vector32(1, 0, 0), + new Vector32(-1, 0, 0), + new Vector32(0, 0, 1), + new Vector32(0, 0, -1), + new Vector32(0, 1, 0), + new Vector32(0, -1, 0) + ]; + this._cubeUps = [ + new Vector32(0, 1, 0), + new Vector32(0, 1, 0), + new Vector32(0, 1, 0), + new Vector32(0, 1, 0), + new Vector32(0, 0, 1), + new Vector32(0, 0, -1) + ]; + } + updateMatrices(light, viewportIndex = 0) { + const camera = this.camera; + const shadowMatrix = this.matrix; + const far = light.distance || camera.far; + if (far !== camera.far) { + camera.far = far; + camera.updateProjectionMatrix(); + } + _lightPositionWorld2.setFromMatrixPosition(light.matrixWorld); + camera.position.copy(_lightPositionWorld2); + _lookTarget2.copy(camera.position); + _lookTarget2.add(this._cubeDirections[viewportIndex]); + camera.up.copy(this._cubeUps[viewportIndex]); + camera.lookAt(_lookTarget2); + camera.updateMatrixWorld(); + shadowMatrix.makeTranslation(-_lightPositionWorld2.x, -_lightPositionWorld2.y, -_lightPositionWorld2.z); + _projScreenMatrix2.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix2); + } + } + + class PointLight2 extends Light2 { + constructor(color, intensity, distance = 0, decay = 2) { + super(color, intensity); + this.isPointLight = true; + this.type = "PointLight"; + this.distance = distance; + this.decay = decay; + this.shadow = new PointLightShadow2; + } + get power() { + return this.intensity * 4 * Math.PI; + } + set power(power) { + this.intensity = power / (4 * Math.PI); + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.decay = source.decay; + this.shadow = source.shadow.clone(); + return this; + } + } + + class OrthographicCamera2 extends Camera2 { + constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) { + super(); + this.isOrthographicCamera = true; + this.type = "OrthographicCamera"; + this.zoom = 1; + this.view = null; + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + this.near = near; + this.far = far; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign({}, source.view); + return this; + } + setViewOffset(fullWidth, fullHeight, x, y, width2, height2) { + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width2; + this.view.height = height2; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const dx = (this.right - this.left) / (2 * this.zoom); + const dy = (this.top - this.bottom) / (2 * this.zoom); + const cx = (this.right + this.left) / 2; + const cy = (this.top + this.bottom) / 2; + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + if (this.view !== null && this.view.enabled) { + const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom; + const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom; + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + } + this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.zoom = this.zoom; + data2.object.left = this.left; + data2.object.right = this.right; + data2.object.top = this.top; + data2.object.bottom = this.bottom; + data2.object.near = this.near; + data2.object.far = this.far; + if (this.view !== null) + data2.object.view = Object.assign({}, this.view); + return data2; + } + } + + class DirectionalLightShadow2 extends LightShadow2 { + constructor() { + super(new OrthographicCamera2(-5, 5, 5, -5, 0.5, 500)); + this.isDirectionalLightShadow = true; + } + } + + class DirectionalLight2 extends Light2 { + constructor(color, intensity) { + super(color, intensity); + this.isDirectionalLight = true; + this.type = "DirectionalLight"; + this.position.copy(Object3D2.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D2; + this.shadow = new DirectionalLightShadow2; + } + dispose() { + this.shadow.dispose(); + } + copy(source) { + super.copy(source); + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } + } + + class AmbientLight2 extends Light2 { + constructor(color, intensity) { + super(color, intensity); + this.isAmbientLight = true; + this.type = "AmbientLight"; + } + } + + class RectAreaLight2 extends Light2 { + constructor(color, intensity, width2 = 10, height2 = 10) { + super(color, intensity); + this.isRectAreaLight = true; + this.type = "RectAreaLight"; + this.width = width2; + this.height = height2; + } + get power() { + return this.intensity * this.width * this.height * Math.PI; + } + set power(power) { + this.intensity = power / (this.width * this.height * Math.PI); + } + copy(source) { + super.copy(source); + this.width = source.width; + this.height = source.height; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.width = this.width; + data2.object.height = this.height; + return data2; + } + } + + class SphericalHarmonics32 { + constructor() { + this.isSphericalHarmonics3 = true; + this.coefficients = []; + for (let i = 0;i < 9; i++) { + this.coefficients.push(new Vector32); + } + } + set(coefficients) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].copy(coefficients[i]); + } + return this; + } + zero() { + for (let i = 0;i < 9; i++) { + this.coefficients[i].set(0, 0, 0); + } + return this; + } + getAt(normal, target) { + const { x, y, z } = normal; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.282095); + target.addScaledVector(coeff[1], 0.488603 * y); + target.addScaledVector(coeff[2], 0.488603 * z); + target.addScaledVector(coeff[3], 0.488603 * x); + target.addScaledVector(coeff[4], 1.092548 * (x * y)); + target.addScaledVector(coeff[5], 1.092548 * (y * z)); + target.addScaledVector(coeff[6], 0.315392 * (3 * z * z - 1)); + target.addScaledVector(coeff[7], 1.092548 * (x * z)); + target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y)); + return target; + } + getIrradianceAt(normal, target) { + const { x, y, z } = normal; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.886227); + target.addScaledVector(coeff[1], 2 * 0.511664 * y); + target.addScaledVector(coeff[2], 2 * 0.511664 * z); + target.addScaledVector(coeff[3], 2 * 0.511664 * x); + target.addScaledVector(coeff[4], 2 * 0.429043 * x * y); + target.addScaledVector(coeff[5], 2 * 0.429043 * y * z); + target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); + target.addScaledVector(coeff[7], 2 * 0.429043 * x * z); + target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); + return target; + } + add(sh) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].add(sh.coefficients[i]); + } + return this; + } + addScaledSH(sh, s) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].addScaledVector(sh.coefficients[i], s); + } + return this; + } + scale(s) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].multiplyScalar(s); + } + return this; + } + lerp(sh, alpha) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].lerp(sh.coefficients[i], alpha); + } + return this; + } + equals(sh) { + for (let i = 0;i < 9; i++) { + if (!this.coefficients[i].equals(sh.coefficients[i])) { + return false; + } + } + return true; + } + copy(sh) { + return this.set(sh.coefficients); + } + clone() { + return new this.constructor().copy(this); + } + fromArray(array, offset = 0) { + const coefficients = this.coefficients; + for (let i = 0;i < 9; i++) { + coefficients[i].fromArray(array, offset + i * 3); + } + return this; + } + toArray(array = [], offset = 0) { + const coefficients = this.coefficients; + for (let i = 0;i < 9; i++) { + coefficients[i].toArray(array, offset + i * 3); + } + return array; + } + static getBasisAt(normal, shBasis) { + const { x, y, z } = normal; + shBasis[0] = 0.282095; + shBasis[1] = 0.488603 * y; + shBasis[2] = 0.488603 * z; + shBasis[3] = 0.488603 * x; + shBasis[4] = 1.092548 * x * y; + shBasis[5] = 1.092548 * y * z; + shBasis[6] = 0.315392 * (3 * z * z - 1); + shBasis[7] = 1.092548 * x * z; + shBasis[8] = 0.546274 * (x * x - y * y); + } + } + + class LightProbe2 extends Light2 { + constructor(sh = new SphericalHarmonics32, intensity = 1) { + super(undefined, intensity); + this.isLightProbe = true; + this.sh = sh; + } + copy(source) { + super.copy(source); + this.sh.copy(source.sh); + return this; + } + fromJSON(json) { + this.intensity = json.intensity; + this.sh.fromArray(json.sh); + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.sh = this.sh.toArray(); + return data2; + } + } + + class MaterialLoader2 extends Loader2 { + constructor(manager) { + super(manager); + this.textures = {}; + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader2(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const textures = this.textures; + function getTexture(name2) { + if (textures[name2] === undefined) { + console.warn("THREE.MaterialLoader: Undefined texture", name2); + } + return textures[name2]; + } + const material = this.createMaterialFromType(json.type); + if (json.uuid !== undefined) + material.uuid = json.uuid; + if (json.name !== undefined) + material.name = json.name; + if (json.color !== undefined && material.color !== undefined) + material.color.setHex(json.color); + if (json.roughness !== undefined) + material.roughness = json.roughness; + if (json.metalness !== undefined) + material.metalness = json.metalness; + if (json.sheen !== undefined) + material.sheen = json.sheen; + if (json.sheenColor !== undefined) + material.sheenColor = new Color2().setHex(json.sheenColor); + if (json.sheenRoughness !== undefined) + material.sheenRoughness = json.sheenRoughness; + if (json.emissive !== undefined && material.emissive !== undefined) + material.emissive.setHex(json.emissive); + if (json.specular !== undefined && material.specular !== undefined) + material.specular.setHex(json.specular); + if (json.specularIntensity !== undefined) + material.specularIntensity = json.specularIntensity; + if (json.specularColor !== undefined && material.specularColor !== undefined) + material.specularColor.setHex(json.specularColor); + if (json.shininess !== undefined) + material.shininess = json.shininess; + if (json.clearcoat !== undefined) + material.clearcoat = json.clearcoat; + if (json.clearcoatRoughness !== undefined) + material.clearcoatRoughness = json.clearcoatRoughness; + if (json.dispersion !== undefined) + material.dispersion = json.dispersion; + if (json.iridescence !== undefined) + material.iridescence = json.iridescence; + if (json.iridescenceIOR !== undefined) + material.iridescenceIOR = json.iridescenceIOR; + if (json.iridescenceThicknessRange !== undefined) + material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if (json.transmission !== undefined) + material.transmission = json.transmission; + if (json.thickness !== undefined) + material.thickness = json.thickness; + if (json.attenuationDistance !== undefined) + material.attenuationDistance = json.attenuationDistance; + if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) + material.attenuationColor.setHex(json.attenuationColor); + if (json.anisotropy !== undefined) + material.anisotropy = json.anisotropy; + if (json.anisotropyRotation !== undefined) + material.anisotropyRotation = json.anisotropyRotation; + if (json.fog !== undefined) + material.fog = json.fog; + if (json.flatShading !== undefined) + material.flatShading = json.flatShading; + if (json.blending !== undefined) + material.blending = json.blending; + if (json.combine !== undefined) + material.combine = json.combine; + if (json.side !== undefined) + material.side = json.side; + if (json.shadowSide !== undefined) + material.shadowSide = json.shadowSide; + if (json.opacity !== undefined) + material.opacity = json.opacity; + if (json.transparent !== undefined) + material.transparent = json.transparent; + if (json.alphaTest !== undefined) + material.alphaTest = json.alphaTest; + if (json.alphaHash !== undefined) + material.alphaHash = json.alphaHash; + if (json.depthFunc !== undefined) + material.depthFunc = json.depthFunc; + if (json.depthTest !== undefined) + material.depthTest = json.depthTest; + if (json.depthWrite !== undefined) + material.depthWrite = json.depthWrite; + if (json.colorWrite !== undefined) + material.colorWrite = json.colorWrite; + if (json.blendSrc !== undefined) + material.blendSrc = json.blendSrc; + if (json.blendDst !== undefined) + material.blendDst = json.blendDst; + if (json.blendEquation !== undefined) + material.blendEquation = json.blendEquation; + if (json.blendSrcAlpha !== undefined) + material.blendSrcAlpha = json.blendSrcAlpha; + if (json.blendDstAlpha !== undefined) + material.blendDstAlpha = json.blendDstAlpha; + if (json.blendEquationAlpha !== undefined) + material.blendEquationAlpha = json.blendEquationAlpha; + if (json.blendColor !== undefined && material.blendColor !== undefined) + material.blendColor.setHex(json.blendColor); + if (json.blendAlpha !== undefined) + material.blendAlpha = json.blendAlpha; + if (json.stencilWriteMask !== undefined) + material.stencilWriteMask = json.stencilWriteMask; + if (json.stencilFunc !== undefined) + material.stencilFunc = json.stencilFunc; + if (json.stencilRef !== undefined) + material.stencilRef = json.stencilRef; + if (json.stencilFuncMask !== undefined) + material.stencilFuncMask = json.stencilFuncMask; + if (json.stencilFail !== undefined) + material.stencilFail = json.stencilFail; + if (json.stencilZFail !== undefined) + material.stencilZFail = json.stencilZFail; + if (json.stencilZPass !== undefined) + material.stencilZPass = json.stencilZPass; + if (json.stencilWrite !== undefined) + material.stencilWrite = json.stencilWrite; + if (json.wireframe !== undefined) + material.wireframe = json.wireframe; + if (json.wireframeLinewidth !== undefined) + material.wireframeLinewidth = json.wireframeLinewidth; + if (json.wireframeLinecap !== undefined) + material.wireframeLinecap = json.wireframeLinecap; + if (json.wireframeLinejoin !== undefined) + material.wireframeLinejoin = json.wireframeLinejoin; + if (json.rotation !== undefined) + material.rotation = json.rotation; + if (json.linewidth !== undefined) + material.linewidth = json.linewidth; + if (json.dashSize !== undefined) + material.dashSize = json.dashSize; + if (json.gapSize !== undefined) + material.gapSize = json.gapSize; + if (json.scale !== undefined) + material.scale = json.scale; + if (json.polygonOffset !== undefined) + material.polygonOffset = json.polygonOffset; + if (json.polygonOffsetFactor !== undefined) + material.polygonOffsetFactor = json.polygonOffsetFactor; + if (json.polygonOffsetUnits !== undefined) + material.polygonOffsetUnits = json.polygonOffsetUnits; + if (json.dithering !== undefined) + material.dithering = json.dithering; + if (json.alphaToCoverage !== undefined) + material.alphaToCoverage = json.alphaToCoverage; + if (json.premultipliedAlpha !== undefined) + material.premultipliedAlpha = json.premultipliedAlpha; + if (json.forceSinglePass !== undefined) + material.forceSinglePass = json.forceSinglePass; + if (json.visible !== undefined) + material.visible = json.visible; + if (json.toneMapped !== undefined) + material.toneMapped = json.toneMapped; + if (json.userData !== undefined) + material.userData = json.userData; + if (json.vertexColors !== undefined) { + if (typeof json.vertexColors === "number") { + material.vertexColors = json.vertexColors > 0 ? true : false; + } else { + material.vertexColors = json.vertexColors; + } + } + if (json.uniforms !== undefined) { + for (const name2 in json.uniforms) { + const uniform = json.uniforms[name2]; + material.uniforms[name2] = {}; + switch (uniform.type) { + case "t": + material.uniforms[name2].value = getTexture(uniform.value); + break; + case "c": + material.uniforms[name2].value = new Color2().setHex(uniform.value); + break; + case "v2": + material.uniforms[name2].value = new Vector22().fromArray(uniform.value); + break; + case "v3": + material.uniforms[name2].value = new Vector32().fromArray(uniform.value); + break; + case "v4": + material.uniforms[name2].value = new Vector42().fromArray(uniform.value); + break; + case "m3": + material.uniforms[name2].value = new Matrix32().fromArray(uniform.value); + break; + case "m4": + material.uniforms[name2].value = new Matrix42().fromArray(uniform.value); + break; + default: + material.uniforms[name2].value = uniform.value; + } + } + } + if (json.defines !== undefined) + material.defines = json.defines; + if (json.vertexShader !== undefined) + material.vertexShader = json.vertexShader; + if (json.fragmentShader !== undefined) + material.fragmentShader = json.fragmentShader; + if (json.glslVersion !== undefined) + material.glslVersion = json.glslVersion; + if (json.extensions !== undefined) { + for (const key2 in json.extensions) { + material.extensions[key2] = json.extensions[key2]; + } + } + if (json.lights !== undefined) + material.lights = json.lights; + if (json.clipping !== undefined) + material.clipping = json.clipping; + if (json.size !== undefined) + material.size = json.size; + if (json.sizeAttenuation !== undefined) + material.sizeAttenuation = json.sizeAttenuation; + if (json.map !== undefined) + material.map = getTexture(json.map); + if (json.matcap !== undefined) + material.matcap = getTexture(json.matcap); + if (json.alphaMap !== undefined) + material.alphaMap = getTexture(json.alphaMap); + if (json.bumpMap !== undefined) + material.bumpMap = getTexture(json.bumpMap); + if (json.bumpScale !== undefined) + material.bumpScale = json.bumpScale; + if (json.normalMap !== undefined) + material.normalMap = getTexture(json.normalMap); + if (json.normalMapType !== undefined) + material.normalMapType = json.normalMapType; + if (json.normalScale !== undefined) { + let normalScale = json.normalScale; + if (Array.isArray(normalScale) === false) { + normalScale = [normalScale, normalScale]; + } + material.normalScale = new Vector22().fromArray(normalScale); + } + if (json.displacementMap !== undefined) + material.displacementMap = getTexture(json.displacementMap); + if (json.displacementScale !== undefined) + material.displacementScale = json.displacementScale; + if (json.displacementBias !== undefined) + material.displacementBias = json.displacementBias; + if (json.roughnessMap !== undefined) + material.roughnessMap = getTexture(json.roughnessMap); + if (json.metalnessMap !== undefined) + material.metalnessMap = getTexture(json.metalnessMap); + if (json.emissiveMap !== undefined) + material.emissiveMap = getTexture(json.emissiveMap); + if (json.emissiveIntensity !== undefined) + material.emissiveIntensity = json.emissiveIntensity; + if (json.specularMap !== undefined) + material.specularMap = getTexture(json.specularMap); + if (json.specularIntensityMap !== undefined) + material.specularIntensityMap = getTexture(json.specularIntensityMap); + if (json.specularColorMap !== undefined) + material.specularColorMap = getTexture(json.specularColorMap); + if (json.envMap !== undefined) + material.envMap = getTexture(json.envMap); + if (json.envMapRotation !== undefined) + material.envMapRotation.fromArray(json.envMapRotation); + if (json.envMapIntensity !== undefined) + material.envMapIntensity = json.envMapIntensity; + if (json.reflectivity !== undefined) + material.reflectivity = json.reflectivity; + if (json.refractionRatio !== undefined) + material.refractionRatio = json.refractionRatio; + if (json.lightMap !== undefined) + material.lightMap = getTexture(json.lightMap); + if (json.lightMapIntensity !== undefined) + material.lightMapIntensity = json.lightMapIntensity; + if (json.aoMap !== undefined) + material.aoMap = getTexture(json.aoMap); + if (json.aoMapIntensity !== undefined) + material.aoMapIntensity = json.aoMapIntensity; + if (json.gradientMap !== undefined) + material.gradientMap = getTexture(json.gradientMap); + if (json.clearcoatMap !== undefined) + material.clearcoatMap = getTexture(json.clearcoatMap); + if (json.clearcoatRoughnessMap !== undefined) + material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap); + if (json.clearcoatNormalMap !== undefined) + material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap); + if (json.clearcoatNormalScale !== undefined) + material.clearcoatNormalScale = new Vector22().fromArray(json.clearcoatNormalScale); + if (json.iridescenceMap !== undefined) + material.iridescenceMap = getTexture(json.iridescenceMap); + if (json.iridescenceThicknessMap !== undefined) + material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap); + if (json.transmissionMap !== undefined) + material.transmissionMap = getTexture(json.transmissionMap); + if (json.thicknessMap !== undefined) + material.thicknessMap = getTexture(json.thicknessMap); + if (json.anisotropyMap !== undefined) + material.anisotropyMap = getTexture(json.anisotropyMap); + if (json.sheenColorMap !== undefined) + material.sheenColorMap = getTexture(json.sheenColorMap); + if (json.sheenRoughnessMap !== undefined) + material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap); + return material; + } + setTextures(value2) { + this.textures = value2; + return this; + } + createMaterialFromType(type) { + return MaterialLoader2.createMaterialFromType(type); + } + static createMaterialFromType(type) { + const materialLib = { + ShadowMaterial: ShadowMaterial2, + SpriteMaterial: SpriteMaterial2, + RawShaderMaterial: RawShaderMaterial2, + ShaderMaterial: ShaderMaterial2, + PointsMaterial: PointsMaterial2, + MeshPhysicalMaterial: MeshPhysicalMaterial2, + MeshStandardMaterial: MeshStandardMaterial2, + MeshPhongMaterial: MeshPhongMaterial2, + MeshToonMaterial: MeshToonMaterial2, + MeshNormalMaterial: MeshNormalMaterial2, + MeshLambertMaterial: MeshLambertMaterial2, + MeshDepthMaterial: MeshDepthMaterial2, + MeshDistanceMaterial: MeshDistanceMaterial2, + MeshBasicMaterial: MeshBasicMaterial2, + MeshMatcapMaterial: MeshMatcapMaterial2, + LineDashedMaterial: LineDashedMaterial2, + LineBasicMaterial: LineBasicMaterial2, + Material: Material2 + }; + return new materialLib[type]; + } + } + + class LoaderUtils2 { + static decodeText(array) { + console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."); + if (typeof TextDecoder !== "undefined") { + return new TextDecoder().decode(array); + } + let s = ""; + for (let i = 0, il = array.length;i < il; i++) { + s += String.fromCharCode(array[i]); + } + try { + return decodeURIComponent(escape(s)); + } catch (e) { + return s; + } + } + static extractUrlBase(url) { + const index2 = url.lastIndexOf("/"); + if (index2 === -1) + return "./"; + return url.slice(0, index2 + 1); + } + static resolveURL(url, path) { + if (typeof url !== "string" || url === "") + return ""; + if (/^https?:\/\//i.test(path) && /^\//.test(url)) { + path = path.replace(/(^https?:\/\/[^\/]+).*/i, "$1"); + } + if (/^(https?:)?\/\//i.test(url)) + return url; + if (/^data:.*,.*$/i.test(url)) + return url; + if (/^blob:.*$/i.test(url)) + return url; + return path + url; + } + } + + class InstancedBufferGeometry2 extends BufferGeometry2 { + constructor() { + super(); + this.isInstancedBufferGeometry = true; + this.type = "InstancedBufferGeometry"; + this.instanceCount = Infinity; + } + copy(source) { + super.copy(source); + this.instanceCount = source.instanceCount; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.instanceCount = this.instanceCount; + data2.isInstancedBufferGeometry = true; + return data2; + } + } + + class BufferGeometryLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader2(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const interleavedBufferMap = {}; + const arrayBufferMap = {}; + function getInterleavedBuffer(json2, uuid) { + if (interleavedBufferMap[uuid] !== undefined) + return interleavedBufferMap[uuid]; + const interleavedBuffers = json2.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[uuid]; + const buffer = getArrayBuffer(json2, interleavedBuffer.buffer); + const array = getTypedArray2(interleavedBuffer.type, buffer); + const ib = new InterleavedBuffer2(array, interleavedBuffer.stride); + ib.uuid = interleavedBuffer.uuid; + interleavedBufferMap[uuid] = ib; + return ib; + } + function getArrayBuffer(json2, uuid) { + if (arrayBufferMap[uuid] !== undefined) + return arrayBufferMap[uuid]; + const arrayBuffers = json2.arrayBuffers; + const arrayBuffer = arrayBuffers[uuid]; + const ab = new Uint32Array(arrayBuffer).buffer; + arrayBufferMap[uuid] = ab; + return ab; + } + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry2 : new BufferGeometry2; + const index2 = json.data.index; + if (index2 !== undefined) { + const typedArray = getTypedArray2(index2.type, index2.array); + geometry.setIndex(new BufferAttribute2(typedArray, 1)); + } + const attributes = json.data.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute2(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray2(attribute.type, attribute.array); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute2 : BufferAttribute2; + bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== undefined) + bufferAttribute.name = attribute.name; + if (attribute.usage !== undefined) + bufferAttribute.setUsage(attribute.usage); + geometry.setAttribute(key2, bufferAttribute); + } + const morphAttributes = json.data.morphAttributes; + if (morphAttributes) { + for (const key2 in morphAttributes) { + const attributeArray = morphAttributes[key2]; + const array = []; + for (let i = 0, il = attributeArray.length;i < il; i++) { + const attribute = attributeArray[i]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute2(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray2(attribute.type, attribute.array); + bufferAttribute = new BufferAttribute2(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== undefined) + bufferAttribute.name = attribute.name; + array.push(bufferAttribute); + } + geometry.morphAttributes[key2] = array; + } + } + const morphTargetsRelative = json.data.morphTargetsRelative; + if (morphTargetsRelative) { + geometry.morphTargetsRelative = true; + } + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + if (groups !== undefined) { + for (let i = 0, n = groups.length;i !== n; ++i) { + const group = groups[i]; + geometry.addGroup(group.start, group.count, group.materialIndex); + } + } + const boundingSphere = json.data.boundingSphere; + if (boundingSphere !== undefined) { + const center = new Vector32; + if (boundingSphere.center !== undefined) { + center.fromArray(boundingSphere.center); + } + geometry.boundingSphere = new Sphere2(center, boundingSphere.radius); + } + if (json.name) + geometry.name = json.name; + if (json.userData) + geometry.userData = json.userData; + return geometry; + } + } + + class ObjectLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const path = this.path === "" ? LoaderUtils2.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader2(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text2) { + let json = null; + try { + json = JSON.parse(text2); + } catch (error) { + if (onError !== undefined) + onError(error); + console.error("THREE:ObjectLoader: Can't parse " + url + ".", error.message); + return; + } + const metadata = json.metadata; + if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === "geometry") { + if (onError !== undefined) + onError(new Error("THREE.ObjectLoader: Can't load " + url)); + console.error("THREE.ObjectLoader: Can't load " + url); + return; + } + scope.parse(json, onLoad); + }, onProgress, onError); + } + async loadAsync(url, onProgress) { + const scope = this; + const path = this.path === "" ? LoaderUtils2.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader2(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + const text2 = await loader.loadAsync(url, onProgress); + const json = JSON.parse(text2); + const metadata = json.metadata; + if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === "geometry") { + throw new Error("THREE.ObjectLoader: Can't load " + url); + } + return await scope.parseAsync(json); + } + parse(json, onLoad) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = this.parseImages(json.images, function() { + if (onLoad !== undefined) + onLoad(object); + }); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + if (onLoad !== undefined) { + let hasImages = false; + for (const uuid in images) { + if (images[uuid].data instanceof HTMLImageElement) { + hasImages = true; + break; + } + } + if (hasImages === false) + onLoad(object); + } + return object; + } + async parseAsync(json) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = await this.parseImagesAsync(json.images); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + return object; + } + parseShapes(json) { + const shapes = {}; + if (json !== undefined) { + for (let i = 0, l = json.length;i < l; i++) { + const shape = new Shape2().fromJSON(json[i]); + shapes[shape.uuid] = shape; + } + } + return shapes; + } + parseSkeletons(json, object) { + const skeletons = {}; + const bones = {}; + object.traverse(function(child) { + if (child.isBone) + bones[child.uuid] = child; + }); + if (json !== undefined) { + for (let i = 0, l = json.length;i < l; i++) { + const skeleton = new Skeleton2().fromJSON(json[i], bones); + skeletons[skeleton.uuid] = skeleton; + } + } + return skeletons; + } + parseGeometries(json, shapes) { + const geometries = {}; + if (json !== undefined) { + const bufferGeometryLoader = new BufferGeometryLoader2; + for (let i = 0, l = json.length;i < l; i++) { + let geometry; + const data2 = json[i]; + switch (data2.type) { + case "BufferGeometry": + case "InstancedBufferGeometry": + geometry = bufferGeometryLoader.parse(data2); + break; + default: + if (data2.type in Geometries2) { + geometry = Geometries2[data2.type].fromJSON(data2, shapes); + } else { + console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data2.type}"`); + } + } + geometry.uuid = data2.uuid; + if (data2.name !== undefined) + geometry.name = data2.name; + if (data2.userData !== undefined) + geometry.userData = data2.userData; + geometries[data2.uuid] = geometry; + } + } + return geometries; + } + parseMaterials(json, textures) { + const cache = {}; + const materials = {}; + if (json !== undefined) { + const loader = new MaterialLoader2; + loader.setTextures(textures); + for (let i = 0, l = json.length;i < l; i++) { + const data2 = json[i]; + if (cache[data2.uuid] === undefined) { + cache[data2.uuid] = loader.parse(data2); + } + materials[data2.uuid] = cache[data2.uuid]; + } + } + return materials; + } + parseAnimations(json) { + const animations = {}; + if (json !== undefined) { + for (let i = 0;i < json.length; i++) { + const data2 = json[i]; + const clip = AnimationClip2.parse(data2); + animations[clip.uuid] = clip; + } + } + return animations; + } + parseImages(json, onLoad) { + const scope = this; + const images = {}; + let loader; + function loadImage(url) { + scope.manager.itemStart(url); + return loader.load(url, function() { + scope.manager.itemEnd(url); + }, undefined, function() { + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + } + function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return loadImage(path); + } else { + if (image.data) { + return { + data: getTypedArray2(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== undefined && json.length > 0) { + const manager = new LoadingManager2(onLoad); + loader = new ImageLoader2(manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length;i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j = 0, jl = url.length;j < jl; j++) { + const currentUrl = url[j]; + const deserializedImage = deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture2(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source2(imageArray); + } else { + const deserializedImage = deserializeImage(image.url); + images[image.uuid] = new Source2(deserializedImage); + } + } + } + return images; + } + async parseImagesAsync(json) { + const scope = this; + const images = {}; + let loader; + async function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return await loader.loadAsync(path); + } else { + if (image.data) { + return { + data: getTypedArray2(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== undefined && json.length > 0) { + loader = new ImageLoader2(this.manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length;i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j = 0, jl = url.length;j < jl; j++) { + const currentUrl = url[j]; + const deserializedImage = await deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture2(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source2(imageArray); + } else { + const deserializedImage = await deserializeImage(image.url); + images[image.uuid] = new Source2(deserializedImage); + } + } + } + return images; + } + parseTextures(json, images) { + function parseConstant(value2, type) { + if (typeof value2 === "number") + return value2; + console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.", value2); + return type[value2]; + } + const textures = {}; + if (json !== undefined) { + for (let i = 0, l = json.length;i < l; i++) { + const data2 = json[i]; + if (data2.image === undefined) { + console.warn('THREE.ObjectLoader: No "image" specified for', data2.uuid); + } + if (images[data2.image] === undefined) { + console.warn("THREE.ObjectLoader: Undefined image", data2.image); + } + const source = images[data2.image]; + const image = source.data; + let texture; + if (Array.isArray(image)) { + texture = new CubeTexture2; + if (image.length === 6) + texture.needsUpdate = true; + } else { + if (image && image.data) { + texture = new DataTexture2; + } else { + texture = new Texture2; + } + if (image) + texture.needsUpdate = true; + } + texture.source = source; + texture.uuid = data2.uuid; + if (data2.name !== undefined) + texture.name = data2.name; + if (data2.mapping !== undefined) + texture.mapping = parseConstant(data2.mapping, TEXTURE_MAPPING2); + if (data2.channel !== undefined) + texture.channel = data2.channel; + if (data2.offset !== undefined) + texture.offset.fromArray(data2.offset); + if (data2.repeat !== undefined) + texture.repeat.fromArray(data2.repeat); + if (data2.center !== undefined) + texture.center.fromArray(data2.center); + if (data2.rotation !== undefined) + texture.rotation = data2.rotation; + if (data2.wrap !== undefined) { + texture.wrapS = parseConstant(data2.wrap[0], TEXTURE_WRAPPING2); + texture.wrapT = parseConstant(data2.wrap[1], TEXTURE_WRAPPING2); + } + if (data2.format !== undefined) + texture.format = data2.format; + if (data2.internalFormat !== undefined) + texture.internalFormat = data2.internalFormat; + if (data2.type !== undefined) + texture.type = data2.type; + if (data2.colorSpace !== undefined) + texture.colorSpace = data2.colorSpace; + if (data2.minFilter !== undefined) + texture.minFilter = parseConstant(data2.minFilter, TEXTURE_FILTER2); + if (data2.magFilter !== undefined) + texture.magFilter = parseConstant(data2.magFilter, TEXTURE_FILTER2); + if (data2.anisotropy !== undefined) + texture.anisotropy = data2.anisotropy; + if (data2.flipY !== undefined) + texture.flipY = data2.flipY; + if (data2.generateMipmaps !== undefined) + texture.generateMipmaps = data2.generateMipmaps; + if (data2.premultiplyAlpha !== undefined) + texture.premultiplyAlpha = data2.premultiplyAlpha; + if (data2.unpackAlignment !== undefined) + texture.unpackAlignment = data2.unpackAlignment; + if (data2.compareFunction !== undefined) + texture.compareFunction = data2.compareFunction; + if (data2.userData !== undefined) + texture.userData = data2.userData; + textures[data2.uuid] = texture; + } + } + return textures; + } + parseObject(data2, geometries, materials, textures, animations) { + let object; + function getGeometry(name2) { + if (geometries[name2] === undefined) { + console.warn("THREE.ObjectLoader: Undefined geometry", name2); + } + return geometries[name2]; + } + function getMaterial(name2) { + if (name2 === undefined) + return; + if (Array.isArray(name2)) { + const array = []; + for (let i = 0, l = name2.length;i < l; i++) { + const uuid = name2[i]; + if (materials[uuid] === undefined) { + console.warn("THREE.ObjectLoader: Undefined material", uuid); + } + array.push(materials[uuid]); + } + return array; + } + if (materials[name2] === undefined) { + console.warn("THREE.ObjectLoader: Undefined material", name2); + } + return materials[name2]; + } + function getTexture(uuid) { + if (textures[uuid] === undefined) { + console.warn("THREE.ObjectLoader: Undefined texture", uuid); + } + return textures[uuid]; + } + let geometry, material; + switch (data2.type) { + case "Scene": + object = new Scene2; + if (data2.background !== undefined) { + if (Number.isInteger(data2.background)) { + object.background = new Color2(data2.background); + } else { + object.background = getTexture(data2.background); + } + } + if (data2.environment !== undefined) { + object.environment = getTexture(data2.environment); + } + if (data2.fog !== undefined) { + if (data2.fog.type === "Fog") { + object.fog = new Fog2(data2.fog.color, data2.fog.near, data2.fog.far); + } else if (data2.fog.type === "FogExp2") { + object.fog = new FogExp22(data2.fog.color, data2.fog.density); + } + if (data2.fog.name !== "") { + object.fog.name = data2.fog.name; + } + } + if (data2.backgroundBlurriness !== undefined) + object.backgroundBlurriness = data2.backgroundBlurriness; + if (data2.backgroundIntensity !== undefined) + object.backgroundIntensity = data2.backgroundIntensity; + if (data2.backgroundRotation !== undefined) + object.backgroundRotation.fromArray(data2.backgroundRotation); + if (data2.environmentIntensity !== undefined) + object.environmentIntensity = data2.environmentIntensity; + if (data2.environmentRotation !== undefined) + object.environmentRotation.fromArray(data2.environmentRotation); + break; + case "PerspectiveCamera": + object = new PerspectiveCamera2(data2.fov, data2.aspect, data2.near, data2.far); + if (data2.focus !== undefined) + object.focus = data2.focus; + if (data2.zoom !== undefined) + object.zoom = data2.zoom; + if (data2.filmGauge !== undefined) + object.filmGauge = data2.filmGauge; + if (data2.filmOffset !== undefined) + object.filmOffset = data2.filmOffset; + if (data2.view !== undefined) + object.view = Object.assign({}, data2.view); + break; + case "OrthographicCamera": + object = new OrthographicCamera2(data2.left, data2.right, data2.top, data2.bottom, data2.near, data2.far); + if (data2.zoom !== undefined) + object.zoom = data2.zoom; + if (data2.view !== undefined) + object.view = Object.assign({}, data2.view); + break; + case "AmbientLight": + object = new AmbientLight2(data2.color, data2.intensity); + break; + case "DirectionalLight": + object = new DirectionalLight2(data2.color, data2.intensity); + object.target = data2.target || ""; + break; + case "PointLight": + object = new PointLight2(data2.color, data2.intensity, data2.distance, data2.decay); + break; + case "RectAreaLight": + object = new RectAreaLight2(data2.color, data2.intensity, data2.width, data2.height); + break; + case "SpotLight": + object = new SpotLight2(data2.color, data2.intensity, data2.distance, data2.angle, data2.penumbra, data2.decay); + object.target = data2.target || ""; + break; + case "HemisphereLight": + object = new HemisphereLight2(data2.color, data2.groundColor, data2.intensity); + break; + case "LightProbe": + object = new LightProbe2().fromJSON(data2); + break; + case "SkinnedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new SkinnedMesh2(geometry, material); + if (data2.bindMode !== undefined) + object.bindMode = data2.bindMode; + if (data2.bindMatrix !== undefined) + object.bindMatrix.fromArray(data2.bindMatrix); + if (data2.skeleton !== undefined) + object.skeleton = data2.skeleton; + break; + case "Mesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new Mesh2(geometry, material); + break; + case "InstancedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + const count = data2.count; + const instanceMatrix = data2.instanceMatrix; + const instanceColor = data2.instanceColor; + object = new InstancedMesh2(geometry, material, count); + object.instanceMatrix = new InstancedBufferAttribute2(new Float32Array(instanceMatrix.array), 16); + if (instanceColor !== undefined) + object.instanceColor = new InstancedBufferAttribute2(new Float32Array(instanceColor.array), instanceColor.itemSize); + break; + case "BatchedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new BatchedMesh2(data2.maxInstanceCount, data2.maxVertexCount, data2.maxIndexCount, material); + object.geometry = geometry; + object.perObjectFrustumCulled = data2.perObjectFrustumCulled; + object.sortObjects = data2.sortObjects; + object._drawRanges = data2.drawRanges; + object._reservedRanges = data2.reservedRanges; + object._visibility = data2.visibility; + object._active = data2.active; + object._bounds = data2.bounds.map((bound) => { + const box = new Box32; + box.min.fromArray(bound.boxMin); + box.max.fromArray(bound.boxMax); + const sphere = new Sphere2; + sphere.radius = bound.sphereRadius; + sphere.center.fromArray(bound.sphereCenter); + return { + boxInitialized: bound.boxInitialized, + box, + sphereInitialized: bound.sphereInitialized, + sphere + }; + }); + object._maxInstanceCount = data2.maxInstanceCount; + object._maxVertexCount = data2.maxVertexCount; + object._maxIndexCount = data2.maxIndexCount; + object._geometryInitialized = data2.geometryInitialized; + object._geometryCount = data2.geometryCount; + object._matricesTexture = getTexture(data2.matricesTexture.uuid); + if (data2.colorsTexture !== undefined) + object._colorsTexture = getTexture(data2.colorsTexture.uuid); + break; + case "LOD": + object = new LOD2; + break; + case "Line": + object = new Line2(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "LineLoop": + object = new LineLoop2(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "LineSegments": + object = new LineSegments2(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "PointCloud": + case "Points": + object = new Points2(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "Sprite": + object = new Sprite2(getMaterial(data2.material)); + break; + case "Group": + object = new Group2; + break; + case "Bone": + object = new Bone2; + break; + default: + object = new Object3D2; + } + object.uuid = data2.uuid; + if (data2.name !== undefined) + object.name = data2.name; + if (data2.matrix !== undefined) { + object.matrix.fromArray(data2.matrix); + if (data2.matrixAutoUpdate !== undefined) + object.matrixAutoUpdate = data2.matrixAutoUpdate; + if (object.matrixAutoUpdate) + object.matrix.decompose(object.position, object.quaternion, object.scale); + } else { + if (data2.position !== undefined) + object.position.fromArray(data2.position); + if (data2.rotation !== undefined) + object.rotation.fromArray(data2.rotation); + if (data2.quaternion !== undefined) + object.quaternion.fromArray(data2.quaternion); + if (data2.scale !== undefined) + object.scale.fromArray(data2.scale); + } + if (data2.up !== undefined) + object.up.fromArray(data2.up); + if (data2.castShadow !== undefined) + object.castShadow = data2.castShadow; + if (data2.receiveShadow !== undefined) + object.receiveShadow = data2.receiveShadow; + if (data2.shadow) { + if (data2.shadow.intensity !== undefined) + object.shadow.intensity = data2.shadow.intensity; + if (data2.shadow.bias !== undefined) + object.shadow.bias = data2.shadow.bias; + if (data2.shadow.normalBias !== undefined) + object.shadow.normalBias = data2.shadow.normalBias; + if (data2.shadow.radius !== undefined) + object.shadow.radius = data2.shadow.radius; + if (data2.shadow.mapSize !== undefined) + object.shadow.mapSize.fromArray(data2.shadow.mapSize); + if (data2.shadow.camera !== undefined) + object.shadow.camera = this.parseObject(data2.shadow.camera); + } + if (data2.visible !== undefined) + object.visible = data2.visible; + if (data2.frustumCulled !== undefined) + object.frustumCulled = data2.frustumCulled; + if (data2.renderOrder !== undefined) + object.renderOrder = data2.renderOrder; + if (data2.userData !== undefined) + object.userData = data2.userData; + if (data2.layers !== undefined) + object.layers.mask = data2.layers; + if (data2.children !== undefined) { + const children = data2.children; + for (let i = 0;i < children.length; i++) { + object.add(this.parseObject(children[i], geometries, materials, textures, animations)); + } + } + if (data2.animations !== undefined) { + const objectAnimations = data2.animations; + for (let i = 0;i < objectAnimations.length; i++) { + const uuid = objectAnimations[i]; + object.animations.push(animations[uuid]); + } + } + if (data2.type === "LOD") { + if (data2.autoUpdate !== undefined) + object.autoUpdate = data2.autoUpdate; + const levels = data2.levels; + for (let l = 0;l < levels.length; l++) { + const level = levels[l]; + const child = object.getObjectByProperty("uuid", level.object); + if (child !== undefined) { + object.addLevel(child, level.distance, level.hysteresis); + } + } + } + return object; + } + bindSkeletons(object, skeletons) { + if (Object.keys(skeletons).length === 0) + return; + object.traverse(function(child) { + if (child.isSkinnedMesh === true && child.skeleton !== undefined) { + const skeleton = skeletons[child.skeleton]; + if (skeleton === undefined) { + console.warn("THREE.ObjectLoader: No skeleton found with UUID:", child.skeleton); + } else { + child.bind(skeleton, child.bindMatrix); + } + } + }); + } + bindLightTargets(object) { + object.traverse(function(child) { + if (child.isDirectionalLight || child.isSpotLight) { + const uuid = child.target; + const target = object.getObjectByProperty("uuid", uuid); + if (target !== undefined) { + child.target = target; + } else { + child.target = new Object3D2; + } + } + }); + } + } + var TEXTURE_MAPPING2 = { + UVMapping: UVMapping2, + CubeReflectionMapping: CubeReflectionMapping2, + CubeRefractionMapping: CubeRefractionMapping2, + EquirectangularReflectionMapping: EquirectangularReflectionMapping2, + EquirectangularRefractionMapping: EquirectangularRefractionMapping2, + CubeUVReflectionMapping: CubeUVReflectionMapping2 + }; + var TEXTURE_WRAPPING2 = { + RepeatWrapping: RepeatWrapping2, + ClampToEdgeWrapping: ClampToEdgeWrapping2, + MirroredRepeatWrapping: MirroredRepeatWrapping2 + }; + var TEXTURE_FILTER2 = { + NearestFilter: NearestFilter2, + NearestMipmapNearestFilter: NearestMipmapNearestFilter2, + NearestMipmapLinearFilter: NearestMipmapLinearFilter2, + LinearFilter: LinearFilter2, + LinearMipmapNearestFilter: LinearMipmapNearestFilter2, + LinearMipmapLinearFilter: LinearMipmapLinearFilter2 + }; + + class ImageBitmapLoader2 extends Loader2 { + constructor(manager) { + super(manager); + this.isImageBitmapLoader = true; + if (typeof createImageBitmap === "undefined") { + console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."); + } + if (typeof fetch === "undefined") { + console.warn("THREE.ImageBitmapLoader: fetch() not supported."); + } + this.options = { premultiplyAlpha: "none" }; + } + setOptions(options) { + this.options = options; + return this; + } + load(url, onLoad, onProgress, onError) { + if (url === undefined) + url = ""; + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache2.get(url); + if (cached !== undefined) { + scope.manager.itemStart(url); + if (cached.then) { + cached.then((imageBitmap) => { + if (onLoad) + onLoad(imageBitmap); + scope.manager.itemEnd(url); + }).catch((e) => { + if (onError) + onError(e); + }); + return; + } + setTimeout(function() { + if (onLoad) + onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const fetchOptions = {}; + fetchOptions.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include"; + fetchOptions.headers = this.requestHeader; + const promise = fetch(url, fetchOptions).then(function(res) { + return res.blob(); + }).then(function(blob) { + return createImageBitmap(blob, Object.assign(scope.options, { colorSpaceConversion: "none" })); + }).then(function(imageBitmap) { + Cache2.add(url, imageBitmap); + if (onLoad) + onLoad(imageBitmap); + scope.manager.itemEnd(url); + return imageBitmap; + }).catch(function(e) { + if (onError) + onError(e); + Cache2.remove(url); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + Cache2.add(url, promise); + scope.manager.itemStart(url); + } + } + var _context2; + + class AudioContext2 { + static getContext() { + if (_context2 === undefined) { + _context2 = new (window.AudioContext || window.webkitAudioContext); + } + return _context2; + } + static setContext(value2) { + _context2 = value2; + } + } + + class AudioLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader2(this.manager); + loader.setResponseType("arraybuffer"); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(buffer) { + try { + const bufferCopy = buffer.slice(0); + const context = AudioContext2.getContext(); + context.decodeAudioData(bufferCopy, function(audioBuffer) { + onLoad(audioBuffer); + }).catch(handleError); + } catch (e) { + handleError(e); + } + }, onProgress, onError); + function handleError(e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + } + } + var _eyeRight2 = /* @__PURE__ */ new Matrix42; + var _eyeLeft2 = /* @__PURE__ */ new Matrix42; + var _projectionMatrix2 = /* @__PURE__ */ new Matrix42; + + class StereoCamera2 { + constructor() { + this.type = "StereoCamera"; + this.aspect = 1; + this.eyeSep = 0.064; + this.cameraL = new PerspectiveCamera2; + this.cameraL.layers.enable(1); + this.cameraL.matrixAutoUpdate = false; + this.cameraR = new PerspectiveCamera2; + this.cameraR.layers.enable(2); + this.cameraR.matrixAutoUpdate = false; + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; + } + update(camera) { + const cache = this._cache; + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + if (needsUpdate) { + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; + _projectionMatrix2.copy(camera.projectionMatrix); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = cache.near * Math.tan(DEG2RAD2 * cache.fov * 0.5) / cache.zoom; + let xmin, xmax; + _eyeLeft2.elements[12] = -eyeSepHalf; + _eyeRight2.elements[12] = eyeSepHalf; + xmin = -ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; + _projectionMatrix2.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix2.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraL.projectionMatrix.copy(_projectionMatrix2); + xmin = -ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + _projectionMatrix2.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix2.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraR.projectionMatrix.copy(_projectionMatrix2); + } + this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft2); + this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight2); + } + } + + class ArrayCamera2 extends PerspectiveCamera2 { + constructor(array = []) { + super(); + this.isArrayCamera = true; + this.cameras = array; + this.index = 0; + } + } + + class Clock2 { + constructor(autoStart = true) { + this.autoStart = autoStart; + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; + this.running = false; + } + start() { + this.startTime = now2(); + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + } + stop() { + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + } + getElapsedTime() { + this.getDelta(); + return this.elapsedTime; + } + getDelta() { + let diff = 0; + if (this.autoStart && !this.running) { + this.start(); + return 0; + } + if (this.running) { + const newTime = now2(); + diff = (newTime - this.oldTime) / 1000; + this.oldTime = newTime; + this.elapsedTime += diff; + } + return diff; + } + } + function now2() { + return performance.now(); + } + var _position$12 = /* @__PURE__ */ new Vector32; + var _quaternion$12 = /* @__PURE__ */ new Quaternion2; + var _scale$12 = /* @__PURE__ */ new Vector32; + var _orientation$12 = /* @__PURE__ */ new Vector32; + + class AudioListener2 extends Object3D2 { + constructor() { + super(); + this.type = "AudioListener"; + this.context = AudioContext2.getContext(); + this.gain = this.context.createGain(); + this.gain.connect(this.context.destination); + this.filter = null; + this.timeDelta = 0; + this._clock = new Clock2; + } + getInput() { + return this.gain; + } + removeFilter() { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + this.gain.connect(this.context.destination); + this.filter = null; + } + return this; + } + getFilter() { + return this.filter; + } + setFilter(value2) { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + } else { + this.gain.disconnect(this.context.destination); + } + this.filter = value2; + this.gain.connect(this.filter); + this.filter.connect(this.context.destination); + return this; + } + getMasterVolume() { + return this.gain.gain.value; + } + setMasterVolume(value2) { + this.gain.gain.setTargetAtTime(value2, this.context.currentTime, 0.01); + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + const listener = this.context.listener; + const up = this.up; + this.timeDelta = this._clock.getDelta(); + this.matrixWorld.decompose(_position$12, _quaternion$12, _scale$12); + _orientation$12.set(0, 0, -1).applyQuaternion(_quaternion$12); + if (listener.positionX) { + const endTime = this.context.currentTime + this.timeDelta; + listener.positionX.linearRampToValueAtTime(_position$12.x, endTime); + listener.positionY.linearRampToValueAtTime(_position$12.y, endTime); + listener.positionZ.linearRampToValueAtTime(_position$12.z, endTime); + listener.forwardX.linearRampToValueAtTime(_orientation$12.x, endTime); + listener.forwardY.linearRampToValueAtTime(_orientation$12.y, endTime); + listener.forwardZ.linearRampToValueAtTime(_orientation$12.z, endTime); + listener.upX.linearRampToValueAtTime(up.x, endTime); + listener.upY.linearRampToValueAtTime(up.y, endTime); + listener.upZ.linearRampToValueAtTime(up.z, endTime); + } else { + listener.setPosition(_position$12.x, _position$12.y, _position$12.z); + listener.setOrientation(_orientation$12.x, _orientation$12.y, _orientation$12.z, up.x, up.y, up.z); + } + } + } + + class Audio2 extends Object3D2 { + constructor(listener) { + super(); + this.type = "Audio"; + this.listener = listener; + this.context = listener.context; + this.gain = this.context.createGain(); + this.gain.connect(listener.getInput()); + this.autoplay = false; + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = undefined; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = "empty"; + this._startedAt = 0; + this._progress = 0; + this._connected = false; + this.filters = []; + } + getOutput() { + return this.gain; + } + setNodeSource(audioNode) { + this.hasPlaybackControl = false; + this.sourceType = "audioNode"; + this.source = audioNode; + this.connect(); + return this; + } + setMediaElementSource(mediaElement) { + this.hasPlaybackControl = false; + this.sourceType = "mediaNode"; + this.source = this.context.createMediaElementSource(mediaElement); + this.connect(); + return this; + } + setMediaStreamSource(mediaStream) { + this.hasPlaybackControl = false; + this.sourceType = "mediaStreamNode"; + this.source = this.context.createMediaStreamSource(mediaStream); + this.connect(); + return this; + } + setBuffer(audioBuffer) { + this.buffer = audioBuffer; + this.sourceType = "buffer"; + if (this.autoplay) + this.play(); + return this; + } + play(delay = 0) { + if (this.isPlaying === true) { + console.warn("THREE.Audio: Audio is already playing."); + return; + } + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._startedAt = this.context.currentTime + delay; + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind(this); + source.start(this._startedAt, this._progress + this.offset, this.duration); + this.isPlaying = true; + this.source = source; + this.setDetune(this.detune); + this.setPlaybackRate(this.playbackRate); + return this.connect(); + } + pause() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + if (this.isPlaying === true) { + this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate; + if (this.loop === true) { + this._progress = this._progress % (this.duration || this.buffer.duration); + } + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; + } + return this; + } + stop(delay = 0) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._progress = 0; + if (this.source !== null) { + this.source.stop(this.context.currentTime + delay); + this.source.onended = null; + } + this.isPlaying = false; + return this; + } + connect() { + if (this.filters.length > 0) { + this.source.connect(this.filters[0]); + for (let i = 1, l = this.filters.length;i < l; i++) { + this.filters[i - 1].connect(this.filters[i]); + } + this.filters[this.filters.length - 1].connect(this.getOutput()); + } else { + this.source.connect(this.getOutput()); + } + this._connected = true; + return this; + } + disconnect() { + if (this._connected === false) { + return; + } + if (this.filters.length > 0) { + this.source.disconnect(this.filters[0]); + for (let i = 1, l = this.filters.length;i < l; i++) { + this.filters[i - 1].disconnect(this.filters[i]); + } + this.filters[this.filters.length - 1].disconnect(this.getOutput()); + } else { + this.source.disconnect(this.getOutput()); + } + this._connected = false; + return this; + } + getFilters() { + return this.filters; + } + setFilters(value2) { + if (!value2) + value2 = []; + if (this._connected === true) { + this.disconnect(); + this.filters = value2.slice(); + this.connect(); + } else { + this.filters = value2.slice(); + } + return this; + } + setDetune(value2) { + this.detune = value2; + if (this.isPlaying === true && this.source.detune !== undefined) { + this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01); + } + return this; + } + getDetune() { + return this.detune; + } + getFilter() { + return this.getFilters()[0]; + } + setFilter(filter2) { + return this.setFilters(filter2 ? [filter2] : []); + } + setPlaybackRate(value2) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.playbackRate = value2; + if (this.isPlaying === true) { + this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01); + } + return this; + } + getPlaybackRate() { + return this.playbackRate; + } + onEnded() { + this.isPlaying = false; + this._progress = 0; + } + getLoop() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return false; + } + return this.loop; + } + setLoop(value2) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.loop = value2; + if (this.isPlaying === true) { + this.source.loop = this.loop; + } + return this; + } + setLoopStart(value2) { + this.loopStart = value2; + return this; + } + setLoopEnd(value2) { + this.loopEnd = value2; + return this; + } + getVolume() { + return this.gain.gain.value; + } + setVolume(value2) { + this.gain.gain.setTargetAtTime(value2, this.context.currentTime, 0.01); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.sourceType !== "buffer") { + console.warn("THREE.Audio: Audio source type cannot be copied."); + return this; + } + this.autoplay = source.autoplay; + this.buffer = source.buffer; + this.detune = source.detune; + this.loop = source.loop; + this.loopStart = source.loopStart; + this.loopEnd = source.loopEnd; + this.offset = source.offset; + this.duration = source.duration; + this.playbackRate = source.playbackRate; + this.hasPlaybackControl = source.hasPlaybackControl; + this.sourceType = source.sourceType; + this.filters = source.filters.slice(); + return this; + } + clone(recursive) { + return new this.constructor(this.listener).copy(this, recursive); + } + } + var _position2 = /* @__PURE__ */ new Vector32; + var _quaternion2 = /* @__PURE__ */ new Quaternion2; + var _scale2 = /* @__PURE__ */ new Vector32; + var _orientation2 = /* @__PURE__ */ new Vector32; + + class PositionalAudio2 extends Audio2 { + constructor(listener) { + super(listener); + this.panner = this.context.createPanner(); + this.panner.panningModel = "HRTF"; + this.panner.connect(this.gain); + } + connect() { + super.connect(); + this.panner.connect(this.gain); + } + disconnect() { + super.disconnect(); + this.panner.disconnect(this.gain); + } + getOutput() { + return this.panner; + } + getRefDistance() { + return this.panner.refDistance; + } + setRefDistance(value2) { + this.panner.refDistance = value2; + return this; + } + getRolloffFactor() { + return this.panner.rolloffFactor; + } + setRolloffFactor(value2) { + this.panner.rolloffFactor = value2; + return this; + } + getDistanceModel() { + return this.panner.distanceModel; + } + setDistanceModel(value2) { + this.panner.distanceModel = value2; + return this; + } + getMaxDistance() { + return this.panner.maxDistance; + } + setMaxDistance(value2) { + this.panner.maxDistance = value2; + return this; + } + setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) { + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.hasPlaybackControl === true && this.isPlaying === false) + return; + this.matrixWorld.decompose(_position2, _quaternion2, _scale2); + _orientation2.set(0, 0, 1).applyQuaternion(_quaternion2); + const panner = this.panner; + if (panner.positionX) { + const endTime = this.context.currentTime + this.listener.timeDelta; + panner.positionX.linearRampToValueAtTime(_position2.x, endTime); + panner.positionY.linearRampToValueAtTime(_position2.y, endTime); + panner.positionZ.linearRampToValueAtTime(_position2.z, endTime); + panner.orientationX.linearRampToValueAtTime(_orientation2.x, endTime); + panner.orientationY.linearRampToValueAtTime(_orientation2.y, endTime); + panner.orientationZ.linearRampToValueAtTime(_orientation2.z, endTime); + } else { + panner.setPosition(_position2.x, _position2.y, _position2.z); + panner.setOrientation(_orientation2.x, _orientation2.y, _orientation2.z); + } + } + } + + class AudioAnalyser2 { + constructor(audio, fftSize = 2048) { + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; + this.data = new Uint8Array(this.analyser.frequencyBinCount); + audio.getOutput().connect(this.analyser); + } + getFrequencyData() { + this.analyser.getByteFrequencyData(this.data); + return this.data; + } + getAverageFrequency() { + let value2 = 0; + const data2 = this.getFrequencyData(); + for (let i = 0;i < data2.length; i++) { + value2 += data2[i]; + } + return value2 / data2.length; + } + } + + class PropertyMixer2 { + constructor(binding, typeName, valueSize) { + this.binding = binding; + this.valueSize = valueSize; + let mixFunction, mixFunctionAdditive, setIdentity; + switch (typeName) { + case "quaternion": + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; + this.buffer = new Float64Array(valueSize * 6); + this._workIndex = 5; + break; + case "string": + case "bool": + mixFunction = this._select; + mixFunctionAdditive = this._select; + setIdentity = this._setAdditiveIdentityOther; + this.buffer = new Array(valueSize * 5); + break; + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; + this.buffer = new Float64Array(valueSize * 5); + } + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + this.useCount = 0; + this.referenceCount = 0; + } + accumulate(accuIndex, weight) { + const buffer = this.buffer, stride = this.valueSize, offset = accuIndex * stride + stride; + let currentWeight = this.cumulativeWeight; + if (currentWeight === 0) { + for (let i = 0;i !== stride; ++i) { + buffer[offset + i] = buffer[i]; + } + currentWeight = weight; + } else { + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion(buffer, offset, 0, mix, stride); + } + this.cumulativeWeight = currentWeight; + } + accumulateAdditive(weight) { + const buffer = this.buffer, stride = this.valueSize, offset = stride * this._addIndex; + if (this.cumulativeWeightAdditive === 0) { + this._setIdentity(); + } + this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride); + this.cumulativeWeightAdditive += weight; + } + apply(accuIndex) { + const stride = this.valueSize, buffer = this.buffer, offset = accuIndex * stride + stride, weight = this.cumulativeWeight, weightAdditive = this.cumulativeWeightAdditive, binding = this.binding; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + if (weight < 1) { + const originalValueOffset = stride * this._origIndex; + this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride); + } + if (weightAdditive > 0) { + this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride); + } + for (let i = stride, e = stride + stride;i !== e; ++i) { + if (buffer[i] !== buffer[i + stride]) { + binding.setValue(buffer, offset); + break; + } + } + } + saveOriginalState() { + const binding = this.binding; + const buffer = this.buffer, stride = this.valueSize, originalValueOffset = stride * this._origIndex; + binding.getValue(buffer, originalValueOffset); + for (let i = stride, e = originalValueOffset;i !== e; ++i) { + buffer[i] = buffer[originalValueOffset + i % stride]; + } + this._setIdentity(); + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + } + restoreOriginalState() { + const originalValueOffset = this.valueSize * 3; + this.binding.setValue(this.buffer, originalValueOffset); + } + _setAdditiveIdentityNumeric() { + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; + for (let i = startIndex;i < endIndex; i++) { + this.buffer[i] = 0; + } + } + _setAdditiveIdentityQuaternion() { + this._setAdditiveIdentityNumeric(); + this.buffer[this._addIndex * this.valueSize + 3] = 1; + } + _setAdditiveIdentityOther() { + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; + for (let i = 0;i < this.valueSize; i++) { + this.buffer[targetIndex + i] = this.buffer[startIndex + i]; + } + } + _select(buffer, dstOffset, srcOffset, t, stride) { + if (t >= 0.5) { + for (let i = 0;i !== stride; ++i) { + buffer[dstOffset + i] = buffer[srcOffset + i]; + } + } + } + _slerp(buffer, dstOffset, srcOffset, t) { + Quaternion2.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t); + } + _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) { + const workOffset = this._workIndex * stride; + Quaternion2.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); + Quaternion2.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t); + } + _lerp(buffer, dstOffset, srcOffset, t, stride) { + const s = 1 - t; + for (let i = 0;i !== stride; ++i) { + const j = dstOffset + i; + buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t; + } + } + _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) { + for (let i = 0;i !== stride; ++i) { + const j = dstOffset + i; + buffer[j] = buffer[j] + buffer[srcOffset + i] * t; + } + } + } + var _RESERVED_CHARS_RE2 = "\\[\\]\\.:\\/"; + var _reservedRe2 = new RegExp("[" + _RESERVED_CHARS_RE2 + "]", "g"); + var _wordChar2 = "[^" + _RESERVED_CHARS_RE2 + "]"; + var _wordCharOrDot2 = "[^" + _RESERVED_CHARS_RE2.replace("\\.", "") + "]"; + var _directoryRe2 = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", _wordChar2); + var _nodeRe2 = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", _wordCharOrDot2); + var _objectRe2 = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", _wordChar2); + var _propertyRe2 = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", _wordChar2); + var _trackRe2 = new RegExp("" + "^" + _directoryRe2 + _nodeRe2 + _objectRe2 + _propertyRe2 + "$"); + var _supportedObjectNames2 = ["material", "materials", "bones", "map"]; + + class Composite2 { + constructor(targetGroup, path, optionalParsedPath) { + const parsedPath = optionalParsedPath || PropertyBinding2.parseTrackName(path); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_(path, parsedPath); + } + getValue(array, offset) { + this.bind(); + const firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[firstValidIndex]; + if (binding !== undefined) + binding.getValue(array, offset); + } + setValue(array, offset) { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) { + bindings[i].setValue(array, offset); + } + } + bind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) { + bindings[i].bind(); + } + } + unbind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) { + bindings[i].unbind(); + } + } + } + + class PropertyBinding2 { + constructor(rootNode, path, parsedPath) { + this.path = path; + this.parsedPath = parsedPath || PropertyBinding2.parseTrackName(path); + this.node = PropertyBinding2.findNode(rootNode, this.parsedPath.nodeName); + this.rootNode = rootNode; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + static create(root, path, parsedPath) { + if (!(root && root.isAnimationObjectGroup)) { + return new PropertyBinding2(root, path, parsedPath); + } else { + return new PropertyBinding2.Composite(root, path, parsedPath); + } + } + static sanitizeNodeName(name2) { + return name2.replace(/\s/g, "_").replace(_reservedRe2, ""); + } + static parseTrackName(trackName) { + const matches = _trackRe2.exec(trackName); + if (matches === null) { + throw new Error("PropertyBinding: Cannot parse trackName: " + trackName); + } + const results = { + nodeName: matches[2], + objectName: matches[3], + objectIndex: matches[4], + propertyName: matches[5], + propertyIndex: matches[6] + }; + const lastDot = results.nodeName && results.nodeName.lastIndexOf("."); + if (lastDot !== undefined && lastDot !== -1) { + const objectName = results.nodeName.substring(lastDot + 1); + if (_supportedObjectNames2.indexOf(objectName) !== -1) { + results.nodeName = results.nodeName.substring(0, lastDot); + results.objectName = objectName; + } + } + if (results.propertyName === null || results.propertyName.length === 0) { + throw new Error("PropertyBinding: can not parse propertyName from trackName: " + trackName); + } + return results; + } + static findNode(root, nodeName) { + if (nodeName === undefined || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) { + return root; + } + if (root.skeleton) { + const bone = root.skeleton.getBoneByName(nodeName); + if (bone !== undefined) { + return bone; + } + } + if (root.children) { + const searchNodeSubtree = function(children) { + for (let i = 0;i < children.length; i++) { + const childNode = children[i]; + if (childNode.name === nodeName || childNode.uuid === nodeName) { + return childNode; + } + const result = searchNodeSubtree(childNode.children); + if (result) + return result; + } + return null; + }; + const subTreeNode = searchNodeSubtree(root.children); + if (subTreeNode) { + return subTreeNode; + } + } + return null; + } + _getValue_unavailable() { + } + _setValue_unavailable() { + } + _getValue_direct(buffer, offset) { + buffer[offset] = this.targetObject[this.propertyName]; + } + _getValue_array(buffer, offset) { + const source = this.resolvedProperty; + for (let i = 0, n = source.length;i !== n; ++i) { + buffer[offset++] = source[i]; + } + } + _getValue_arrayElement(buffer, offset) { + buffer[offset] = this.resolvedProperty[this.propertyIndex]; + } + _getValue_toArray(buffer, offset) { + this.resolvedProperty.toArray(buffer, offset); + } + _setValue_direct(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + } + _setValue_direct_setNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_array(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length;i !== n; ++i) { + dest[i] = buffer[offset++]; + } + } + _setValue_array_setNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length;i !== n; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.needsUpdate = true; + } + _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length;i !== n; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_arrayElement(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + } + _setValue_arrayElement_setNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_fromArray(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + } + _setValue_fromArray_setNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.needsUpdate = true; + } + _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.matrixWorldNeedsUpdate = true; + } + _getValue_unbound(targetArray, offset) { + this.bind(); + this.getValue(targetArray, offset); + } + _setValue_unbound(sourceArray, offset) { + this.bind(); + this.setValue(sourceArray, offset); + } + bind() { + let targetObject = this.node; + const parsedPath = this.parsedPath; + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + if (!targetObject) { + targetObject = PropertyBinding2.findNode(this.rootNode, parsedPath.nodeName); + this.node = targetObject; + } + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; + if (!targetObject) { + console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + "."); + return; + } + if (objectName) { + let objectIndex = parsedPath.objectIndex; + switch (objectName) { + case "materials": + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.materials) { + console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this); + return; + } + targetObject = targetObject.material.materials; + break; + case "bones": + if (!targetObject.skeleton) { + console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this); + return; + } + targetObject = targetObject.skeleton.bones; + for (let i = 0;i < targetObject.length; i++) { + if (targetObject[i].name === objectIndex) { + objectIndex = i; + break; + } + } + break; + case "map": + if ("map" in targetObject) { + targetObject = targetObject.map; + break; + } + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.map) { + console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this); + return; + } + targetObject = targetObject.material.map; + break; + default: + if (targetObject[objectName] === undefined) { + console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this); + return; + } + targetObject = targetObject[objectName]; + } + if (objectIndex !== undefined) { + if (targetObject[objectIndex] === undefined) { + console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, targetObject); + return; + } + targetObject = targetObject[objectIndex]; + } + } + const nodeProperty = targetObject[propertyName]; + if (nodeProperty === undefined) { + const nodeName = parsedPath.nodeName; + console.error("THREE.PropertyBinding: Trying to update property for track: " + nodeName + "." + propertyName + " but it wasn't found.", targetObject); + return; + } + let versioning = this.Versioning.None; + this.targetObject = targetObject; + if (targetObject.isMaterial === true) { + versioning = this.Versioning.NeedsUpdate; + } else if (targetObject.isObject3D === true) { + versioning = this.Versioning.MatrixWorldNeedsUpdate; + } + let bindingType = this.BindingType.Direct; + if (propertyIndex !== undefined) { + if (propertyName === "morphTargetInfluences") { + if (!targetObject.geometry) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this); + return; + } + if (!targetObject.geometry.morphAttributes) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this); + return; + } + if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) { + propertyIndex = targetObject.morphTargetDictionary[propertyIndex]; + } + } + bindingType = this.BindingType.ArrayElement; + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) { + bindingType = this.BindingType.HasFromToArray; + this.resolvedProperty = nodeProperty; + } else if (Array.isArray(nodeProperty)) { + bindingType = this.BindingType.EntireArray; + this.resolvedProperty = nodeProperty; + } else { + this.propertyName = propertyName; + } + this.getValue = this.GetterByBindingType[bindingType]; + this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning]; + } + unbind() { + this.node = null; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + } + PropertyBinding2.Composite = Composite2; + PropertyBinding2.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 + }; + PropertyBinding2.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 + }; + PropertyBinding2.prototype.GetterByBindingType = [ + PropertyBinding2.prototype._getValue_direct, + PropertyBinding2.prototype._getValue_array, + PropertyBinding2.prototype._getValue_arrayElement, + PropertyBinding2.prototype._getValue_toArray + ]; + PropertyBinding2.prototype.SetterByBindingTypeAndVersioning = [ + [ + PropertyBinding2.prototype._setValue_direct, + PropertyBinding2.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding2.prototype._setValue_direct_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding2.prototype._setValue_array, + PropertyBinding2.prototype._setValue_array_setNeedsUpdate, + PropertyBinding2.prototype._setValue_array_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding2.prototype._setValue_arrayElement, + PropertyBinding2.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding2.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding2.prototype._setValue_fromArray, + PropertyBinding2.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding2.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate + ] + ]; + + class AnimationObjectGroup2 { + constructor() { + this.isAnimationObjectGroup = true; + this.uuid = generateUUID2(); + this._objects = Array.prototype.slice.call(arguments); + this.nCachedObjects_ = 0; + const indices = {}; + this._indicesByUUID = indices; + for (let i = 0, n = arguments.length;i !== n; ++i) { + indices[arguments[i].uuid] = i; + } + this._paths = []; + this._parsedPaths = []; + this._bindings = []; + this._bindingsIndicesByPath = {}; + const scope = this; + this.stats = { + objects: { + get total() { + return scope._objects.length; + }, + get inUse() { + return this.total - scope.nCachedObjects_; + } + }, + get bindingsPerObject() { + return scope._bindings.length; + } + }; + } + add() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, nBindings = bindings.length; + let knownObject = undefined, nObjects = objects.length, nCachedObjects = this.nCachedObjects_; + for (let i = 0, n = arguments.length;i !== n; ++i) { + const object = arguments[i], uuid = object.uuid; + let index2 = indicesByUUID[uuid]; + if (index2 === undefined) { + index2 = nObjects++; + indicesByUUID[uuid] = index2; + objects.push(object); + for (let j = 0, m = nBindings;j !== m; ++j) { + bindings[j].push(new PropertyBinding2(object, paths[j], parsedPaths[j])); + } + } else if (index2 < nCachedObjects) { + knownObject = objects[index2]; + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex]; + indicesByUUID[lastCachedObject.uuid] = index2; + objects[index2] = lastCachedObject; + indicesByUUID[uuid] = firstActiveIndex; + objects[firstActiveIndex] = object; + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j], lastCached = bindingsForPath[firstActiveIndex]; + let binding = bindingsForPath[index2]; + bindingsForPath[index2] = lastCached; + if (binding === undefined) { + binding = new PropertyBinding2(object, paths[j], parsedPaths[j]); + } + bindingsForPath[firstActiveIndex] = binding; + } + } else if (objects[index2] !== knownObject) { + console.error("THREE.AnimationObjectGroup: Different objects with the same UUID " + "detected. Clean the caches or recreate your infrastructure when reloading scenes."); + } + } + this.nCachedObjects_ = nCachedObjects; + } + remove() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_; + for (let i = 0, n = arguments.length;i !== n; ++i) { + const object = arguments[i], uuid = object.uuid, index2 = indicesByUUID[uuid]; + if (index2 !== undefined && index2 >= nCachedObjects) { + const lastCachedIndex = nCachedObjects++, firstActiveObject = objects[lastCachedIndex]; + indicesByUUID[firstActiveObject.uuid] = index2; + objects[index2] = firstActiveObject; + indicesByUUID[uuid] = lastCachedIndex; + objects[lastCachedIndex] = object; + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j], firstActive = bindingsForPath[lastCachedIndex], binding = bindingsForPath[index2]; + bindingsForPath[index2] = firstActive; + bindingsForPath[lastCachedIndex] = binding; + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + uncache() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_, nObjects = objects.length; + for (let i = 0, n = arguments.length;i !== n; ++i) { + const object = arguments[i], uuid = object.uuid, index2 = indicesByUUID[uuid]; + if (index2 !== undefined) { + delete indicesByUUID[uuid]; + if (index2 < nCachedObjects) { + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex], lastIndex = --nObjects, lastObject = objects[lastIndex]; + indicesByUUID[lastCachedObject.uuid] = index2; + objects[index2] = lastCachedObject; + indicesByUUID[lastObject.uuid] = firstActiveIndex; + objects[firstActiveIndex] = lastObject; + objects.pop(); + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j], lastCached = bindingsForPath[firstActiveIndex], last2 = bindingsForPath[lastIndex]; + bindingsForPath[index2] = lastCached; + bindingsForPath[firstActiveIndex] = last2; + bindingsForPath.pop(); + } + } else { + const lastIndex = --nObjects, lastObject = objects[lastIndex]; + if (lastIndex > 0) { + indicesByUUID[lastObject.uuid] = index2; + } + objects[index2] = lastObject; + objects.pop(); + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j]; + bindingsForPath[index2] = bindingsForPath[lastIndex]; + bindingsForPath.pop(); + } + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + subscribe_(path, parsedPath) { + const indicesByPath = this._bindingsIndicesByPath; + let index2 = indicesByPath[path]; + const bindings = this._bindings; + if (index2 !== undefined) + return bindings[index2]; + const paths = this._paths, parsedPaths = this._parsedPaths, objects = this._objects, nObjects = objects.length, nCachedObjects = this.nCachedObjects_, bindingsForPath = new Array(nObjects); + index2 = bindings.length; + indicesByPath[path] = index2; + paths.push(path); + parsedPaths.push(parsedPath); + bindings.push(bindingsForPath); + for (let i = nCachedObjects, n = objects.length;i !== n; ++i) { + const object = objects[i]; + bindingsForPath[i] = new PropertyBinding2(object, path, parsedPath); + } + return bindingsForPath; + } + unsubscribe_(path) { + const indicesByPath = this._bindingsIndicesByPath, index2 = indicesByPath[path]; + if (index2 !== undefined) { + const paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, lastBindingsIndex = bindings.length - 1, lastBindings = bindings[lastBindingsIndex], lastBindingsPath = path[lastBindingsIndex]; + indicesByPath[lastBindingsPath] = index2; + bindings[index2] = lastBindings; + bindings.pop(); + parsedPaths[index2] = parsedPaths[lastBindingsIndex]; + parsedPaths.pop(); + paths[index2] = paths[lastBindingsIndex]; + paths.pop(); + } + } + } + + class AnimationAction2 { + constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) { + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; + const tracks = clip.tracks, nTracks = tracks.length, interpolants = new Array(nTracks); + const interpolantSettings = { + endingStart: ZeroCurvatureEnding2, + endingEnd: ZeroCurvatureEnding2 + }; + for (let i = 0;i !== nTracks; ++i) { + const interpolant = tracks[i].createInterpolant(null); + interpolants[i] = interpolant; + interpolant.settings = interpolantSettings; + } + this._interpolantSettings = interpolantSettings; + this._interpolants = interpolants; + this._propertyBindings = new Array(nTracks); + this._cacheIndex = null; + this._byClipCacheIndex = null; + this._timeScaleInterpolant = null; + this._weightInterpolant = null; + this.loop = LoopRepeat2; + this._loopCount = -1; + this._startTime = null; + this.time = 0; + this.timeScale = 1; + this._effectiveTimeScale = 1; + this.weight = 1; + this._effectiveWeight = 1; + this.repetitions = Infinity; + this.paused = false; + this.enabled = true; + this.clampWhenFinished = false; + this.zeroSlopeAtStart = true; + this.zeroSlopeAtEnd = true; + } + play() { + this._mixer._activateAction(this); + return this; + } + stop() { + this._mixer._deactivateAction(this); + return this.reset(); + } + reset() { + this.paused = false; + this.enabled = true; + this.time = 0; + this._loopCount = -1; + this._startTime = null; + return this.stopFading().stopWarping(); + } + isRunning() { + return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this); + } + isScheduled() { + return this._mixer._isActiveAction(this); + } + startAt(time2) { + this._startTime = time2; + return this; + } + setLoop(mode, repetitions) { + this.loop = mode; + this.repetitions = repetitions; + return this; + } + setEffectiveWeight(weight) { + this.weight = weight; + this._effectiveWeight = this.enabled ? weight : 0; + return this.stopFading(); + } + getEffectiveWeight() { + return this._effectiveWeight; + } + fadeIn(duration) { + return this._scheduleFading(duration, 0, 1); + } + fadeOut(duration) { + return this._scheduleFading(duration, 1, 0); + } + crossFadeFrom(fadeOutAction, duration, warp) { + fadeOutAction.fadeOut(duration); + this.fadeIn(duration); + if (warp) { + const fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, startEndRatio = fadeOutDuration / fadeInDuration, endStartRatio = fadeInDuration / fadeOutDuration; + fadeOutAction.warp(1, startEndRatio, duration); + this.warp(endStartRatio, 1, duration); + } + return this; + } + crossFadeTo(fadeInAction, duration, warp) { + return fadeInAction.crossFadeFrom(this, duration, warp); + } + stopFading() { + const weightInterpolant = this._weightInterpolant; + if (weightInterpolant !== null) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant(weightInterpolant); + } + return this; + } + setEffectiveTimeScale(timeScale) { + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; + return this.stopWarping(); + } + getEffectiveTimeScale() { + return this._effectiveTimeScale; + } + setDuration(duration) { + this.timeScale = this._clip.duration / duration; + return this.stopWarping(); + } + syncWith(action) { + this.time = action.time; + this.timeScale = action.timeScale; + return this.stopWarping(); + } + halt(duration) { + return this.warp(this._effectiveTimeScale, 0, duration); + } + warp(startTimeScale, endTimeScale, duration) { + const mixer = this._mixer, now3 = mixer.time, timeScale = this.timeScale; + let interpolant = this._timeScaleInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; + } + const { parameterPositions: times, sampleValues: values2 } = interpolant; + times[0] = now3; + times[1] = now3 + duration; + values2[0] = startTimeScale / timeScale; + values2[1] = endTimeScale / timeScale; + return this; + } + stopWarping() { + const timeScaleInterpolant = this._timeScaleInterpolant; + if (timeScaleInterpolant !== null) { + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant(timeScaleInterpolant); + } + return this; + } + getMixer() { + return this._mixer; + } + getClip() { + return this._clip; + } + getRoot() { + return this._localRoot || this._mixer._root; + } + _update(time2, deltaTime, timeDirection, accuIndex) { + if (!this.enabled) { + this._updateWeight(time2); + return; + } + const startTime = this._startTime; + if (startTime !== null) { + const timeRunning = (time2 - startTime) * timeDirection; + if (timeRunning < 0 || timeDirection === 0) { + deltaTime = 0; + } else { + this._startTime = null; + deltaTime = timeDirection * timeRunning; + } + } + deltaTime *= this._updateTimeScale(time2); + const clipTime = this._updateTime(deltaTime); + const weight = this._updateWeight(time2); + if (weight > 0) { + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; + switch (this.blendMode) { + case AdditiveAnimationBlendMode2: + for (let j = 0, m = interpolants.length;j !== m; ++j) { + interpolants[j].evaluate(clipTime); + propertyMixers[j].accumulateAdditive(weight); + } + break; + case NormalAnimationBlendMode2: + default: + for (let j = 0, m = interpolants.length;j !== m; ++j) { + interpolants[j].evaluate(clipTime); + propertyMixers[j].accumulate(accuIndex, weight); + } + } + } + } + _updateWeight(time2) { + let weight = 0; + if (this.enabled) { + weight = this.weight; + const interpolant = this._weightInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time2)[0]; + weight *= interpolantValue; + if (time2 > interpolant.parameterPositions[1]) { + this.stopFading(); + if (interpolantValue === 0) { + this.enabled = false; + } + } + } + } + this._effectiveWeight = weight; + return weight; + } + _updateTimeScale(time2) { + let timeScale = 0; + if (!this.paused) { + timeScale = this.timeScale; + const interpolant = this._timeScaleInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time2)[0]; + timeScale *= interpolantValue; + if (time2 > interpolant.parameterPositions[1]) { + this.stopWarping(); + if (timeScale === 0) { + this.paused = true; + } else { + this.timeScale = timeScale; + } + } + } + } + this._effectiveTimeScale = timeScale; + return timeScale; + } + _updateTime(deltaTime) { + const duration = this._clip.duration; + const loop = this.loop; + let time2 = this.time + deltaTime; + let loopCount = this._loopCount; + const pingPong = loop === LoopPingPong2; + if (deltaTime === 0) { + if (loopCount === -1) + return time2; + return pingPong && (loopCount & 1) === 1 ? duration - time2 : time2; + } + if (loop === LoopOnce2) { + if (loopCount === -1) { + this._loopCount = 0; + this._setEndings(true, true, false); + } + handle_stop: { + if (time2 >= duration) { + time2 = duration; + } else if (time2 < 0) { + time2 = 0; + } else { + this.time = time2; + break handle_stop; + } + if (this.clampWhenFinished) + this.paused = true; + else + this.enabled = false; + this.time = time2; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime < 0 ? -1 : 1 + }); + } + } else { + if (loopCount === -1) { + if (deltaTime >= 0) { + loopCount = 0; + this._setEndings(true, this.repetitions === 0, pingPong); + } else { + this._setEndings(this.repetitions === 0, true, pingPong); + } + } + if (time2 >= duration || time2 < 0) { + const loopDelta = Math.floor(time2 / duration); + time2 -= duration * loopDelta; + loopCount += Math.abs(loopDelta); + const pending = this.repetitions - loopCount; + if (pending <= 0) { + if (this.clampWhenFinished) + this.paused = true; + else + this.enabled = false; + time2 = deltaTime > 0 ? duration : 0; + this.time = time2; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime > 0 ? 1 : -1 + }); + } else { + if (pending === 1) { + const atStart = deltaTime < 0; + this._setEndings(atStart, !atStart, pingPong); + } else { + this._setEndings(false, false, pingPong); + } + this._loopCount = loopCount; + this.time = time2; + this._mixer.dispatchEvent({ + type: "loop", + action: this, + loopDelta + }); + } + } else { + this.time = time2; + } + if (pingPong && (loopCount & 1) === 1) { + return duration - time2; + } + } + return time2; + } + _setEndings(atStart, atEnd, pingPong) { + const settings = this._interpolantSettings; + if (pingPong) { + settings.endingStart = ZeroSlopeEnding2; + settings.endingEnd = ZeroSlopeEnding2; + } else { + if (atStart) { + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding2 : ZeroCurvatureEnding2; + } else { + settings.endingStart = WrapAroundEnding2; + } + if (atEnd) { + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding2 : ZeroCurvatureEnding2; + } else { + settings.endingEnd = WrapAroundEnding2; + } + } + } + _scheduleFading(duration, weightNow, weightThen) { + const mixer = this._mixer, now3 = mixer.time; + let interpolant = this._weightInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; + } + const { parameterPositions: times, sampleValues: values2 } = interpolant; + times[0] = now3; + values2[0] = weightNow; + times[1] = now3 + duration; + values2[1] = weightThen; + return this; + } + } + var _controlInterpolantsResultBuffer2 = new Float32Array(1); + + class AnimationMixer2 extends EventDispatcher2 { + constructor(root) { + super(); + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1; + } + _bindAction(action, prototypeAction) { + const root = action._localRoot || this._root, tracks = action._clip.tracks, nTracks = tracks.length, bindings = action._propertyBindings, interpolants = action._interpolants, rootUuid = root.uuid, bindingsByRoot = this._bindingsByRootAndName; + let bindingsByName = bindingsByRoot[rootUuid]; + if (bindingsByName === undefined) { + bindingsByName = {}; + bindingsByRoot[rootUuid] = bindingsByName; + } + for (let i = 0;i !== nTracks; ++i) { + const track = tracks[i], trackName = track.name; + let binding = bindingsByName[trackName]; + if (binding !== undefined) { + ++binding.referenceCount; + bindings[i] = binding; + } else { + binding = bindings[i]; + if (binding !== undefined) { + if (binding._cacheIndex === null) { + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + } + continue; + } + const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath; + binding = new PropertyMixer2(PropertyBinding2.create(root, trackName, path), track.ValueTypeName, track.getValueSize()); + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + bindings[i] = binding; + } + interpolants[i].resultBuffer = binding.buffer; + } + } + _activateAction(action) { + if (!this._isActiveAction(action)) { + if (action._cacheIndex === null) { + const rootUuid = (action._localRoot || this._root).uuid, clipUuid = action._clip.uuid, actionsForClip = this._actionsByClip[clipUuid]; + this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]); + this._addInactiveAction(action, clipUuid, rootUuid); + } + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length;i !== n; ++i) { + const binding = bindings[i]; + if (binding.useCount++ === 0) { + this._lendBinding(binding); + binding.saveOriginalState(); + } + } + this._lendAction(action); + } + } + _deactivateAction(action) { + if (this._isActiveAction(action)) { + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length;i !== n; ++i) { + const binding = bindings[i]; + if (--binding.useCount === 0) { + binding.restoreOriginalState(); + this._takeBackBinding(binding); + } + } + this._takeBackAction(action); + } + } + _initMemoryManager() { + this._actions = []; + this._nActiveActions = 0; + this._actionsByClip = {}; + this._bindings = []; + this._nActiveBindings = 0; + this._bindingsByRootAndName = {}; + this._controlInterpolants = []; + this._nActiveControlInterpolants = 0; + const scope = this; + this.stats = { + actions: { + get total() { + return scope._actions.length; + }, + get inUse() { + return scope._nActiveActions; + } + }, + bindings: { + get total() { + return scope._bindings.length; + }, + get inUse() { + return scope._nActiveBindings; + } + }, + controlInterpolants: { + get total() { + return scope._controlInterpolants.length; + }, + get inUse() { + return scope._nActiveControlInterpolants; + } + } + }; + } + _isActiveAction(action) { + const index2 = action._cacheIndex; + return index2 !== null && index2 < this._nActiveActions; + } + _addInactiveAction(action, clipUuid, rootUuid) { + const actions = this._actions, actionsByClip = this._actionsByClip; + let actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip === undefined) { + actionsForClip = { + knownActions: [action], + actionByRoot: {} + }; + action._byClipCacheIndex = 0; + actionsByClip[clipUuid] = actionsForClip; + } else { + const knownActions = actionsForClip.knownActions; + action._byClipCacheIndex = knownActions.length; + knownActions.push(action); + } + action._cacheIndex = actions.length; + actions.push(action); + actionsForClip.actionByRoot[rootUuid] = action; + } + _removeInactiveAction(action) { + const actions = this._actions, lastInactiveAction = actions[actions.length - 1], cacheIndex = action._cacheIndex; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + action._cacheIndex = null; + const clipUuid = action._clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid], knownActionsForClip = actionsForClip.knownActions, lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1], byClipCacheIndex = action._byClipCacheIndex; + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[byClipCacheIndex] = lastKnownAction; + knownActionsForClip.pop(); + action._byClipCacheIndex = null; + const actionByRoot = actionsForClip.actionByRoot, rootUuid = (action._localRoot || this._root).uuid; + delete actionByRoot[rootUuid]; + if (knownActionsForClip.length === 0) { + delete actionsByClip[clipUuid]; + } + this._removeInactiveBindingsForAction(action); + } + _removeInactiveBindingsForAction(action) { + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length;i !== n; ++i) { + const binding = bindings[i]; + if (--binding.referenceCount === 0) { + this._removeInactiveBinding(binding); + } + } + } + _lendAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, lastActiveIndex = this._nActiveActions++, firstInactiveAction = actions[lastActiveIndex]; + action._cacheIndex = lastActiveIndex; + actions[lastActiveIndex] = action; + firstInactiveAction._cacheIndex = prevIndex; + actions[prevIndex] = firstInactiveAction; + } + _takeBackAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, firstInactiveIndex = --this._nActiveActions, lastActiveAction = actions[firstInactiveIndex]; + action._cacheIndex = firstInactiveIndex; + actions[firstInactiveIndex] = action; + lastActiveAction._cacheIndex = prevIndex; + actions[prevIndex] = lastActiveAction; + } + _addInactiveBinding(binding, rootUuid, trackName) { + const bindingsByRoot = this._bindingsByRootAndName, bindings = this._bindings; + let bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName === undefined) { + bindingByName = {}; + bindingsByRoot[rootUuid] = bindingByName; + } + bindingByName[trackName] = binding; + binding._cacheIndex = bindings.length; + bindings.push(binding); + } + _removeInactiveBinding(binding) { + const bindings = this._bindings, propBinding = binding.binding, rootUuid = propBinding.rootNode.uuid, trackName = propBinding.path, bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid], lastInactiveBinding = bindings[bindings.length - 1], cacheIndex = binding._cacheIndex; + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[cacheIndex] = lastInactiveBinding; + bindings.pop(); + delete bindingByName[trackName]; + if (Object.keys(bindingByName).length === 0) { + delete bindingsByRoot[rootUuid]; + } + } + _lendBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, lastActiveIndex = this._nActiveBindings++, firstInactiveBinding = bindings[lastActiveIndex]; + binding._cacheIndex = lastActiveIndex; + bindings[lastActiveIndex] = binding; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = firstInactiveBinding; + } + _takeBackBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, firstInactiveIndex = --this._nActiveBindings, lastActiveBinding = bindings[firstInactiveIndex]; + binding._cacheIndex = firstInactiveIndex; + bindings[firstInactiveIndex] = binding; + lastActiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = lastActiveBinding; + } + _lendControlInterpolant() { + const interpolants = this._controlInterpolants, lastActiveIndex = this._nActiveControlInterpolants++; + let interpolant = interpolants[lastActiveIndex]; + if (interpolant === undefined) { + interpolant = new LinearInterpolant2(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer2); + interpolant.__cacheIndex = lastActiveIndex; + interpolants[lastActiveIndex] = interpolant; + } + return interpolant; + } + _takeBackControlInterpolant(interpolant) { + const interpolants = this._controlInterpolants, prevIndex = interpolant.__cacheIndex, firstInactiveIndex = --this._nActiveControlInterpolants, lastActiveInterpolant = interpolants[firstInactiveIndex]; + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[firstInactiveIndex] = interpolant; + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[prevIndex] = lastActiveInterpolant; + } + clipAction(clip, optionalRoot, blendMode) { + const root = optionalRoot || this._root, rootUuid = root.uuid; + let clipObject = typeof clip === "string" ? AnimationClip2.findByName(root, clip) : clip; + const clipUuid = clipObject !== null ? clipObject.uuid : clip; + const actionsForClip = this._actionsByClip[clipUuid]; + let prototypeAction = null; + if (blendMode === undefined) { + if (clipObject !== null) { + blendMode = clipObject.blendMode; + } else { + blendMode = NormalAnimationBlendMode2; + } + } + if (actionsForClip !== undefined) { + const existingAction = actionsForClip.actionByRoot[rootUuid]; + if (existingAction !== undefined && existingAction.blendMode === blendMode) { + return existingAction; + } + prototypeAction = actionsForClip.knownActions[0]; + if (clipObject === null) + clipObject = prototypeAction._clip; + } + if (clipObject === null) + return null; + const newAction = new AnimationAction2(this, clipObject, optionalRoot, blendMode); + this._bindAction(newAction, prototypeAction); + this._addInactiveAction(newAction, clipUuid, rootUuid); + return newAction; + } + existingAction(clip, optionalRoot) { + const root = optionalRoot || this._root, rootUuid = root.uuid, clipObject = typeof clip === "string" ? AnimationClip2.findByName(root, clip) : clip, clipUuid = clipObject ? clipObject.uuid : clip, actionsForClip = this._actionsByClip[clipUuid]; + if (actionsForClip !== undefined) { + return actionsForClip.actionByRoot[rootUuid] || null; + } + return null; + } + stopAllAction() { + const actions = this._actions, nActions = this._nActiveActions; + for (let i = nActions - 1;i >= 0; --i) { + actions[i].stop(); + } + return this; + } + update(deltaTime) { + deltaTime *= this.timeScale; + const actions = this._actions, nActions = this._nActiveActions, time2 = this.time += deltaTime, timeDirection = Math.sign(deltaTime), accuIndex = this._accuIndex ^= 1; + for (let i = 0;i !== nActions; ++i) { + const action = actions[i]; + action._update(time2, deltaTime, timeDirection, accuIndex); + } + const bindings = this._bindings, nBindings = this._nActiveBindings; + for (let i = 0;i !== nBindings; ++i) { + bindings[i].apply(accuIndex); + } + return this; + } + setTime(timeInSeconds) { + this.time = 0; + for (let i = 0;i < this._actions.length; i++) { + this._actions[i].time = 0; + } + return this.update(timeInSeconds); + } + getRoot() { + return this._root; + } + uncacheClip(clip) { + const actions = this._actions, clipUuid = clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip !== undefined) { + const actionsToRemove = actionsForClip.knownActions; + for (let i = 0, n = actionsToRemove.length;i !== n; ++i) { + const action = actionsToRemove[i]; + this._deactivateAction(action); + const cacheIndex = action._cacheIndex, lastInactiveAction = actions[actions.length - 1]; + action._cacheIndex = null; + action._byClipCacheIndex = null; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + this._removeInactiveBindingsForAction(action); + } + delete actionsByClip[clipUuid]; + } + } + uncacheRoot(root) { + const rootUuid = root.uuid, actionsByClip = this._actionsByClip; + for (const clipUuid in actionsByClip) { + const actionByRoot = actionsByClip[clipUuid].actionByRoot, action = actionByRoot[rootUuid]; + if (action !== undefined) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + const bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName !== undefined) { + for (const trackName in bindingByName) { + const binding = bindingByName[trackName]; + binding.restoreOriginalState(); + this._removeInactiveBinding(binding); + } + } + } + uncacheAction(clip, optionalRoot) { + const action = this.existingAction(clip, optionalRoot); + if (action !== null) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + } + + class RenderTarget3D2 extends RenderTarget2 { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isRenderTarget3D = true; + this.depth = depth; + this.texture = new Data3DTexture2(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } + } + + class RenderTargetArray2 extends RenderTarget2 { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isRenderTargetArray = true; + this.depth = depth; + this.texture = new DataArrayTexture2(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } + } + + class Uniform2 { + constructor(value2) { + this.value = value2; + } + clone() { + return new Uniform2(this.value.clone === undefined ? this.value : this.value.clone()); + } + } + var _id$12 = 0; + + class UniformsGroup2 extends EventDispatcher2 { + constructor() { + super(); + this.isUniformsGroup = true; + Object.defineProperty(this, "id", { value: _id$12++ }); + this.name = ""; + this.usage = StaticDrawUsage2; + this.uniforms = []; + } + add(uniform) { + this.uniforms.push(uniform); + return this; + } + remove(uniform) { + const index2 = this.uniforms.indexOf(uniform); + if (index2 !== -1) + this.uniforms.splice(index2, 1); + return this; + } + setName(name2) { + this.name = name2; + return this; + } + setUsage(value2) { + this.usage = value2; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + return this; + } + copy(source) { + this.name = source.name; + this.usage = source.usage; + const uniformsSource = source.uniforms; + this.uniforms.length = 0; + for (let i = 0, l = uniformsSource.length;i < l; i++) { + const uniforms = Array.isArray(uniformsSource[i]) ? uniformsSource[i] : [uniformsSource[i]]; + for (let j = 0;j < uniforms.length; j++) { + this.uniforms.push(uniforms[j].clone()); + } + } + return this; + } + clone() { + return new this.constructor().copy(this); + } + } + + class InstancedInterleavedBuffer2 extends InterleavedBuffer2 { + constructor(array, stride, meshPerAttribute = 1) { + super(array, stride); + this.isInstancedInterleavedBuffer = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + clone(data2) { + const ib = super.clone(data2); + ib.meshPerAttribute = this.meshPerAttribute; + return ib; + } + toJSON(data2) { + const json = super.toJSON(data2); + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; + return json; + } + } + + class GLBufferAttribute2 { + constructor(buffer, type, itemSize, elementSize, count) { + this.isGLBufferAttribute = true; + this.name = ""; + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; + this.version = 0; + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setBuffer(buffer) { + this.buffer = buffer; + return this; + } + setType(type, elementSize) { + this.type = type; + this.elementSize = elementSize; + return this; + } + setItemSize(itemSize) { + this.itemSize = itemSize; + return this; + } + setCount(count) { + this.count = count; + return this; + } + } + var _matrix2 = /* @__PURE__ */ new Matrix42; + + class Raycaster2 { + constructor(origin, direction, near = 0, far = Infinity) { + this.ray = new Ray2(origin, direction); + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers2; + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + } + set(origin, direction) { + this.ray.set(origin, direction); + } + setFromCamera(coords, camera) { + if (camera.isPerspectiveCamera) { + this.ray.origin.setFromMatrixPosition(camera.matrixWorld); + this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize(); + this.camera = camera; + } else if (camera.isOrthographicCamera) { + this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); + this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld); + this.camera = camera; + } else { + console.error("THREE.Raycaster: Unsupported camera type: " + camera.type); + } + } + setFromXRController(controller) { + _matrix2.identity().extractRotation(controller.matrixWorld); + this.ray.origin.setFromMatrixPosition(controller.matrixWorld); + this.ray.direction.set(0, 0, -1).applyMatrix4(_matrix2); + return this; + } + intersectObject(object, recursive = true, intersects3 = []) { + intersect2(object, this, intersects3, recursive); + intersects3.sort(ascSort2); + return intersects3; + } + intersectObjects(objects, recursive = true, intersects3 = []) { + for (let i = 0, l = objects.length;i < l; i++) { + intersect2(objects[i], this, intersects3, recursive); + } + intersects3.sort(ascSort2); + return intersects3; + } + } + function ascSort2(a, b) { + return a.distance - b.distance; + } + function intersect2(object, raycaster, intersects3, recursive) { + let propagate = true; + if (object.layers.test(raycaster.layers)) { + const result = object.raycast(raycaster, intersects3); + if (result === false) + propagate = false; + } + if (propagate === true && recursive === true) { + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + intersect2(children[i], raycaster, intersects3, true); + } + } + } + + class Spherical2 { + constructor(radius = 1, phi = 0, theta = 0) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + set(radius, phi, theta) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + copy(other) { + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + return this; + } + makeSafe() { + const EPS = 0.000001; + this.phi = clamp3(this.phi, EPS, Math.PI - EPS); + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x, y, z) { + this.radius = Math.sqrt(x * x + y * y + z * z); + if (this.radius === 0) { + this.theta = 0; + this.phi = 0; + } else { + this.theta = Math.atan2(x, z); + this.phi = Math.acos(clamp3(y / this.radius, -1, 1)); + } + return this; + } + clone() { + return new this.constructor().copy(this); + } + } + + class Cylindrical2 { + constructor(radius = 1, theta = 0, y = 0) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + set(radius, theta, y) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + copy(other) { + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x, y, z) { + this.radius = Math.sqrt(x * x + z * z); + this.theta = Math.atan2(x, z); + this.y = y; + return this; + } + clone() { + return new this.constructor().copy(this); + } + } + + class Matrix22 { + constructor(n11, n12, n21, n22) { + Matrix22.prototype.isMatrix2 = true; + this.elements = [ + 1, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n21, n22); + } + } + identity() { + this.set(1, 0, 0, 1); + return this; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 4; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + set(n11, n12, n21, n22) { + const te = this.elements; + te[0] = n11; + te[2] = n12; + te[1] = n21; + te[3] = n22; + return this; + } + } + var _vector$42 = /* @__PURE__ */ new Vector22; + + class Box22 { + constructor(min = new Vector22(Infinity, Infinity), max = new Vector22(-Infinity, -Infinity)) { + this.isBox2 = true; + this.min = min; + this.max = max; + } + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length;i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size) { + const halfSize = _vector$42.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = Infinity; + this.max.x = this.max.y = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y; + } + getParameter(point, target) { + return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y)); + } + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y; + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$42).distanceTo(point); + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) + this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } + } + var _startP2 = /* @__PURE__ */ new Vector32; + var _startEnd2 = /* @__PURE__ */ new Vector32; + + class Line32 { + constructor(start = new Vector32, end = new Vector32) { + this.start = start; + this.end = end; + } + set(start, end) { + this.start.copy(start); + this.end.copy(end); + return this; + } + copy(line) { + this.start.copy(line.start); + this.end.copy(line.end); + return this; + } + getCenter(target) { + return target.addVectors(this.start, this.end).multiplyScalar(0.5); + } + delta(target) { + return target.subVectors(this.end, this.start); + } + distanceSq() { + return this.start.distanceToSquared(this.end); + } + distance() { + return this.start.distanceTo(this.end); + } + at(t, target) { + return this.delta(target).multiplyScalar(t).add(this.start); + } + closestPointToPointParameter(point, clampToLine) { + _startP2.subVectors(point, this.start); + _startEnd2.subVectors(this.end, this.start); + const startEnd2 = _startEnd2.dot(_startEnd2); + const startEnd_startP = _startEnd2.dot(_startP2); + let t = startEnd_startP / startEnd2; + if (clampToLine) { + t = clamp3(t, 0, 1); + } + return t; + } + closestPointToPoint(point, clampToLine, target) { + const t = this.closestPointToPointParameter(point, clampToLine); + return this.delta(target).multiplyScalar(t).add(this.start); + } + applyMatrix4(matrix) { + this.start.applyMatrix4(matrix); + this.end.applyMatrix4(matrix); + return this; + } + equals(line) { + return line.start.equals(this.start) && line.end.equals(this.end); + } + clone() { + return new this.constructor().copy(this); + } + } + var _vector$32 = /* @__PURE__ */ new Vector32; + + class SpotLightHelper2 extends Object3D2 { + constructor(light, color) { + super(); + this.light = light; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "SpotLightHelper"; + const geometry = new BufferGeometry2; + const positions = [ + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + -1, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + -1, + 1 + ]; + for (let i = 0, j = 1, l = 32;i < l; i++, j++) { + const p1 = i / l * Math.PI * 2; + const p2 = j / l * Math.PI * 2; + positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1); + } + geometry.setAttribute("position", new Float32BufferAttribute2(positions, 3)); + const material = new LineBasicMaterial2({ fog: false, toneMapped: false }); + this.cone = new LineSegments2(geometry, material); + this.add(this.cone); + this.update(); + } + dispose() { + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + if (this.parent) { + this.parent.updateWorldMatrix(true); + this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld); + } else { + this.matrix.copy(this.light.matrixWorld); + } + this.matrixWorld.copy(this.light.matrixWorld); + const coneLength = this.light.distance ? this.light.distance : 1000; + const coneWidth = coneLength * Math.tan(this.light.angle); + this.cone.scale.set(coneWidth, coneWidth, coneLength); + _vector$32.setFromMatrixPosition(this.light.target.matrixWorld); + this.cone.lookAt(_vector$32); + if (this.color !== undefined) { + this.cone.material.color.set(this.color); + } else { + this.cone.material.color.copy(this.light.color); + } + } + } + var _vector$22 = /* @__PURE__ */ new Vector32; + var _boneMatrix2 = /* @__PURE__ */ new Matrix42; + var _matrixWorldInv2 = /* @__PURE__ */ new Matrix42; + + class SkeletonHelper2 extends LineSegments2 { + constructor(object) { + const bones = getBoneList2(object); + const geometry = new BufferGeometry2; + const vertices = []; + const colors = []; + const color1 = new Color2(0, 0, 1); + const color2 = new Color2(0, 1, 0); + for (let i = 0;i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + vertices.push(0, 0, 0); + vertices.push(0, 0, 0); + colors.push(color1.r, color1.g, color1.b); + colors.push(color2.r, color2.g, color2.b); + } + } + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + const material = new LineBasicMaterial2({ vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true }); + super(geometry, material); + this.isSkeletonHelper = true; + this.type = "SkeletonHelper"; + this.root = object; + this.bones = bones; + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + } + updateMatrixWorld(force) { + const bones = this.bones; + const geometry = this.geometry; + const position2 = geometry.getAttribute("position"); + _matrixWorldInv2.copy(this.root.matrixWorld).invert(); + for (let i = 0, j = 0;i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + _boneMatrix2.multiplyMatrices(_matrixWorldInv2, bone.matrixWorld); + _vector$22.setFromMatrixPosition(_boneMatrix2); + position2.setXYZ(j, _vector$22.x, _vector$22.y, _vector$22.z); + _boneMatrix2.multiplyMatrices(_matrixWorldInv2, bone.parent.matrixWorld); + _vector$22.setFromMatrixPosition(_boneMatrix2); + position2.setXYZ(j + 1, _vector$22.x, _vector$22.y, _vector$22.z); + j += 2; + } + } + geometry.getAttribute("position").needsUpdate = true; + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + function getBoneList2(object) { + const boneList = []; + if (object.isBone === true) { + boneList.push(object); + } + for (let i = 0;i < object.children.length; i++) { + boneList.push.apply(boneList, getBoneList2(object.children[i])); + } + return boneList; + } + + class PointLightHelper2 extends Mesh2 { + constructor(light, sphereSize, color) { + const geometry = new SphereGeometry2(sphereSize, 4, 2); + const material = new MeshBasicMaterial2({ wireframe: true, fog: false, toneMapped: false }); + super(geometry, material); + this.light = light; + this.color = color; + this.type = "PointLightHelper"; + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; + this.update(); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + if (this.color !== undefined) { + this.material.color.set(this.color); + } else { + this.material.color.copy(this.light.color); + } + } + } + var _vector$12 = /* @__PURE__ */ new Vector32; + var _color12 = /* @__PURE__ */ new Color2; + var _color22 = /* @__PURE__ */ new Color2; + + class HemisphereLightHelper2 extends Object3D2 { + constructor(light, size, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "HemisphereLightHelper"; + const geometry = new OctahedronGeometry2(size); + geometry.rotateY(Math.PI * 0.5); + this.material = new MeshBasicMaterial2({ wireframe: true, fog: false, toneMapped: false }); + if (this.color === undefined) + this.material.vertexColors = true; + const position2 = geometry.getAttribute("position"); + const colors = new Float32Array(position2.count * 3); + geometry.setAttribute("color", new BufferAttribute2(colors, 3)); + this.add(new Mesh2(geometry, this.material)); + this.update(); + } + dispose() { + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + update() { + const mesh = this.children[0]; + if (this.color !== undefined) { + this.material.color.set(this.color); + } else { + const colors = mesh.geometry.getAttribute("color"); + _color12.copy(this.light.color); + _color22.copy(this.light.groundColor); + for (let i = 0, l = colors.count;i < l; i++) { + const color = i < l / 2 ? _color12 : _color22; + colors.setXYZ(i, color.r, color.g, color.b); + } + colors.needsUpdate = true; + } + this.light.updateWorldMatrix(true, false); + mesh.lookAt(_vector$12.setFromMatrixPosition(this.light.matrixWorld).negate()); + } + } + + class GridHelper2 extends LineSegments2 { + constructor(size = 10, divisions = 10, color1 = 4473924, color2 = 8947848) { + color1 = new Color2(color1); + color2 = new Color2(color2); + const center = divisions / 2; + const step = size / divisions; + const halfSize = size / 2; + const vertices = [], colors = []; + for (let i = 0, j = 0, k = -halfSize;i <= divisions; i++, k += step) { + vertices.push(-halfSize, 0, k, halfSize, 0, k); + vertices.push(k, 0, -halfSize, k, 0, halfSize); + const color = i === center ? color1 : color2; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + } + const geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + const material = new LineBasicMaterial2({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "GridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + + class PolarGridHelper2 extends LineSegments2 { + constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 4473924, color2 = 8947848) { + color1 = new Color2(color1); + color2 = new Color2(color2); + const vertices = []; + const colors = []; + if (sectors > 1) { + for (let i = 0;i < sectors; i++) { + const v = i / sectors * (Math.PI * 2); + const x = Math.sin(v) * radius; + const z = Math.cos(v) * radius; + vertices.push(0, 0, 0); + vertices.push(x, 0, z); + const color = i & 1 ? color1 : color2; + colors.push(color.r, color.g, color.b); + colors.push(color.r, color.g, color.b); + } + } + for (let i = 0;i < rings; i++) { + const color = i & 1 ? color1 : color2; + const r = radius - radius / rings * i; + for (let j = 0;j < divisions; j++) { + let v = j / divisions * (Math.PI * 2); + let x = Math.sin(v) * r; + let z = Math.cos(v) * r; + vertices.push(x, 0, z); + colors.push(color.r, color.g, color.b); + v = (j + 1) / divisions * (Math.PI * 2); + x = Math.sin(v) * r; + z = Math.cos(v) * r; + vertices.push(x, 0, z); + colors.push(color.r, color.g, color.b); + } + } + const geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + const material = new LineBasicMaterial2({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "PolarGridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + var _v12 = /* @__PURE__ */ new Vector32; + var _v22 = /* @__PURE__ */ new Vector32; + var _v32 = /* @__PURE__ */ new Vector32; + + class DirectionalLightHelper2 extends Object3D2 { + constructor(light, size, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "DirectionalLightHelper"; + if (size === undefined) + size = 1; + let geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2([ + -size, + size, + 0, + size, + size, + 0, + size, + -size, + 0, + -size, + -size, + 0, + -size, + size, + 0 + ], 3)); + const material = new LineBasicMaterial2({ fog: false, toneMapped: false }); + this.lightPlane = new Line2(geometry, material); + this.add(this.lightPlane); + geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2([0, 0, 0, 0, 0, 1], 3)); + this.targetLine = new Line2(geometry, material); + this.add(this.targetLine); + this.update(); + } + dispose() { + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + _v12.setFromMatrixPosition(this.light.matrixWorld); + _v22.setFromMatrixPosition(this.light.target.matrixWorld); + _v32.subVectors(_v22, _v12); + this.lightPlane.lookAt(_v22); + if (this.color !== undefined) { + this.lightPlane.material.color.set(this.color); + this.targetLine.material.color.set(this.color); + } else { + this.lightPlane.material.color.copy(this.light.color); + this.targetLine.material.color.copy(this.light.color); + } + this.targetLine.lookAt(_v22); + this.targetLine.scale.z = _v32.length(); + } + } + var _vector4 = /* @__PURE__ */ new Vector32; + var _camera2 = /* @__PURE__ */ new Camera2; + + class CameraHelper2 extends LineSegments2 { + constructor(camera) { + const geometry = new BufferGeometry2; + const material = new LineBasicMaterial2({ color: 16777215, vertexColors: true, toneMapped: false }); + const vertices = []; + const colors = []; + const pointMap = {}; + addLine("n1", "n2"); + addLine("n2", "n4"); + addLine("n4", "n3"); + addLine("n3", "n1"); + addLine("f1", "f2"); + addLine("f2", "f4"); + addLine("f4", "f3"); + addLine("f3", "f1"); + addLine("n1", "f1"); + addLine("n2", "f2"); + addLine("n3", "f3"); + addLine("n4", "f4"); + addLine("p", "n1"); + addLine("p", "n2"); + addLine("p", "n3"); + addLine("p", "n4"); + addLine("u1", "u2"); + addLine("u2", "u3"); + addLine("u3", "u1"); + addLine("c", "t"); + addLine("p", "c"); + addLine("cn1", "cn2"); + addLine("cn3", "cn4"); + addLine("cf1", "cf2"); + addLine("cf3", "cf4"); + function addLine(a, b) { + addPoint(a); + addPoint(b); + } + function addPoint(id) { + vertices.push(0, 0, 0); + colors.push(0, 0, 0); + if (pointMap[id] === undefined) { + pointMap[id] = []; + } + pointMap[id].push(vertices.length / 3 - 1); + } + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + super(geometry, material); + this.type = "CameraHelper"; + this.camera = camera; + if (this.camera.updateProjectionMatrix) + this.camera.updateProjectionMatrix(); + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; + this.pointMap = pointMap; + this.update(); + const colorFrustum = new Color2(16755200); + const colorCone = new Color2(16711680); + const colorUp = new Color2(43775); + const colorTarget = new Color2(16777215); + const colorCross = new Color2(3355443); + this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross); + } + setColors(frustum, cone, up, target, cross) { + const geometry = this.geometry; + const colorAttribute = geometry.getAttribute("color"); + colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(24, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(26, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(28, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(30, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(32, up.r, up.g, up.b); + colorAttribute.setXYZ(33, up.r, up.g, up.b); + colorAttribute.setXYZ(34, up.r, up.g, up.b); + colorAttribute.setXYZ(35, up.r, up.g, up.b); + colorAttribute.setXYZ(36, up.r, up.g, up.b); + colorAttribute.setXYZ(37, up.r, up.g, up.b); + colorAttribute.setXYZ(38, target.r, target.g, target.b); + colorAttribute.setXYZ(39, target.r, target.g, target.b); + colorAttribute.setXYZ(40, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(42, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(44, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(46, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(48, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); + colorAttribute.needsUpdate = true; + } + update() { + const geometry = this.geometry; + const pointMap = this.pointMap; + const w = 1, h = 1; + _camera2.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); + const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem2 ? -1 : 0; + setPoint2("c", pointMap, geometry, _camera2, 0, 0, nearZ); + setPoint2("t", pointMap, geometry, _camera2, 0, 0, 1); + setPoint2("n1", pointMap, geometry, _camera2, -w, -h, nearZ); + setPoint2("n2", pointMap, geometry, _camera2, w, -h, nearZ); + setPoint2("n3", pointMap, geometry, _camera2, -w, h, nearZ); + setPoint2("n4", pointMap, geometry, _camera2, w, h, nearZ); + setPoint2("f1", pointMap, geometry, _camera2, -w, -h, 1); + setPoint2("f2", pointMap, geometry, _camera2, w, -h, 1); + setPoint2("f3", pointMap, geometry, _camera2, -w, h, 1); + setPoint2("f4", pointMap, geometry, _camera2, w, h, 1); + setPoint2("u1", pointMap, geometry, _camera2, w * 0.7, h * 1.1, nearZ); + setPoint2("u2", pointMap, geometry, _camera2, -w * 0.7, h * 1.1, nearZ); + setPoint2("u3", pointMap, geometry, _camera2, 0, h * 2, nearZ); + setPoint2("cf1", pointMap, geometry, _camera2, -w, 0, 1); + setPoint2("cf2", pointMap, geometry, _camera2, w, 0, 1); + setPoint2("cf3", pointMap, geometry, _camera2, 0, -h, 1); + setPoint2("cf4", pointMap, geometry, _camera2, 0, h, 1); + setPoint2("cn1", pointMap, geometry, _camera2, -w, 0, nearZ); + setPoint2("cn2", pointMap, geometry, _camera2, w, 0, nearZ); + setPoint2("cn3", pointMap, geometry, _camera2, 0, -h, nearZ); + setPoint2("cn4", pointMap, geometry, _camera2, 0, h, nearZ); + geometry.getAttribute("position").needsUpdate = true; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + function setPoint2(point, pointMap, geometry, camera, x, y, z) { + _vector4.set(x, y, z).unproject(camera); + const points = pointMap[point]; + if (points !== undefined) { + const position2 = geometry.getAttribute("position"); + for (let i = 0, l = points.length;i < l; i++) { + position2.setXYZ(points[i], _vector4.x, _vector4.y, _vector4.z); + } + } + } + var _box2 = /* @__PURE__ */ new Box32; + + class BoxHelper2 extends LineSegments2 { + constructor(object, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = new Float32Array(8 * 3); + const geometry = new BufferGeometry2; + geometry.setIndex(new BufferAttribute2(indices, 1)); + geometry.setAttribute("position", new BufferAttribute2(positions, 3)); + super(geometry, new LineBasicMaterial2({ color, toneMapped: false })); + this.object = object; + this.type = "BoxHelper"; + this.matrixAutoUpdate = false; + this.update(); + } + update(object) { + if (object !== undefined) { + console.warn("THREE.BoxHelper: .update() has no longer arguments."); + } + if (this.object !== undefined) { + _box2.setFromObject(this.object); + } + if (_box2.isEmpty()) + return; + const min = _box2.min; + const max = _box2.max; + const position2 = this.geometry.attributes.position; + const array = position2.array; + array[0] = max.x; + array[1] = max.y; + array[2] = max.z; + array[3] = min.x; + array[4] = max.y; + array[5] = max.z; + array[6] = min.x; + array[7] = min.y; + array[8] = max.z; + array[9] = max.x; + array[10] = min.y; + array[11] = max.z; + array[12] = max.x; + array[13] = max.y; + array[14] = min.z; + array[15] = min.x; + array[16] = max.y; + array[17] = min.z; + array[18] = min.x; + array[19] = min.y; + array[20] = min.z; + array[21] = max.x; + array[22] = min.y; + array[23] = min.z; + position2.needsUpdate = true; + this.geometry.computeBoundingSphere(); + } + setFromObject(object) { + this.object = object; + this.update(); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + this.object = source.object; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + + class Box3Helper2 extends LineSegments2 { + constructor(box, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1]; + const geometry = new BufferGeometry2; + geometry.setIndex(new BufferAttribute2(indices, 1)); + geometry.setAttribute("position", new Float32BufferAttribute2(positions, 3)); + super(geometry, new LineBasicMaterial2({ color, toneMapped: false })); + this.box = box; + this.type = "Box3Helper"; + this.geometry.computeBoundingSphere(); + } + updateMatrixWorld(force) { + const box = this.box; + if (box.isEmpty()) + return; + box.getCenter(this.position); + box.getSize(this.scale); + this.scale.multiplyScalar(0.5); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + + class PlaneHelper2 extends Line2 { + constructor(plane, size = 1, hex = 16776960) { + const color = hex; + const positions = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0]; + const geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2(positions, 3)); + geometry.computeBoundingSphere(); + super(geometry, new LineBasicMaterial2({ color, toneMapped: false })); + this.type = "PlaneHelper"; + this.plane = plane; + this.size = size; + const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0]; + const geometry2 = new BufferGeometry2; + geometry2.setAttribute("position", new Float32BufferAttribute2(positions2, 3)); + geometry2.computeBoundingSphere(); + this.add(new Mesh2(geometry2, new MeshBasicMaterial2({ color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false }))); + } + updateMatrixWorld(force) { + this.position.set(0, 0, 0); + this.scale.set(0.5 * this.size, 0.5 * this.size, 1); + this.lookAt(this.plane.normal); + this.translateZ(-this.plane.constant); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + } + var _axis2 = /* @__PURE__ */ new Vector32; + var _lineGeometry2; + var _coneGeometry2; + + class ArrowHelper2 extends Object3D2 { + constructor(dir = new Vector32(0, 0, 1), origin = new Vector32(0, 0, 0), length2 = 1, color = 16776960, headLength = length2 * 0.2, headWidth = headLength * 0.2) { + super(); + this.type = "ArrowHelper"; + if (_lineGeometry2 === undefined) { + _lineGeometry2 = new BufferGeometry2; + _lineGeometry2.setAttribute("position", new Float32BufferAttribute2([0, 0, 0, 0, 1, 0], 3)); + _coneGeometry2 = new CylinderGeometry2(0, 0.5, 1, 5, 1); + _coneGeometry2.translate(0, -0.5, 0); + } + this.position.copy(origin); + this.line = new Line2(_lineGeometry2, new LineBasicMaterial2({ color, toneMapped: false })); + this.line.matrixAutoUpdate = false; + this.add(this.line); + this.cone = new Mesh2(_coneGeometry2, new MeshBasicMaterial2({ color, toneMapped: false })); + this.cone.matrixAutoUpdate = false; + this.add(this.cone); + this.setDirection(dir); + this.setLength(length2, headLength, headWidth); + } + setDirection(dir) { + if (dir.y > 0.99999) { + this.quaternion.set(0, 0, 0, 1); + } else if (dir.y < -0.99999) { + this.quaternion.set(1, 0, 0, 0); + } else { + _axis2.set(dir.z, 0, -dir.x).normalize(); + const radians = Math.acos(dir.y); + this.quaternion.setFromAxisAngle(_axis2, radians); + } + } + setLength(length2, headLength = length2 * 0.2, headWidth = headLength * 0.2) { + this.line.scale.set(1, Math.max(0.0001, length2 - headLength), 1); + this.line.updateMatrix(); + this.cone.scale.set(headWidth, headLength, headWidth); + this.cone.position.y = length2; + this.cone.updateMatrix(); + } + setColor(color) { + this.line.material.color.set(color); + this.cone.material.color.set(color); + } + copy(source) { + super.copy(source, false); + this.line.copy(source.line); + this.cone.copy(source.cone); + return this; + } + dispose() { + this.line.geometry.dispose(); + this.line.material.dispose(); + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + } + + class AxesHelper2 extends LineSegments2 { + constructor(size = 1) { + const vertices = [ + 0, + 0, + 0, + size, + 0, + 0, + 0, + 0, + 0, + 0, + size, + 0, + 0, + 0, + 0, + 0, + 0, + size + ]; + const colors = [ + 1, + 0, + 0, + 1, + 0.6, + 0, + 0, + 1, + 0, + 0.6, + 1, + 0, + 0, + 0, + 1, + 0, + 0.6, + 1 + ]; + const geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + const material = new LineBasicMaterial2({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "AxesHelper"; + } + setColors(xAxisColor, yAxisColor, zAxisColor) { + const color = new Color2; + const array = this.geometry.attributes.color.array; + color.set(xAxisColor); + color.toArray(array, 0); + color.toArray(array, 3); + color.set(yAxisColor); + color.toArray(array, 6); + color.toArray(array, 9); + color.set(zAxisColor); + color.toArray(array, 12); + color.toArray(array, 15); + this.geometry.attributes.color.needsUpdate = true; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + + class ShapePath3 { + constructor() { + this.type = "ShapePath"; + this.color = new Color2; + this.subPaths = []; + this.currentPath = null; + } + moveTo(x, y) { + this.currentPath = new Path2; + this.subPaths.push(this.currentPath); + this.currentPath.moveTo(x, y); + return this; + } + lineTo(x, y) { + this.currentPath.lineTo(x, y); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY); + return this; + } + splineThru(pts) { + this.currentPath.splineThru(pts); + return this; + } + toShapes(isCCW) { + function toShapesNoHoles(inSubpaths) { + const shapes2 = []; + for (let i = 0, l = inSubpaths.length;i < l; i++) { + const tmpPath2 = inSubpaths[i]; + const tmpShape2 = new Shape2; + tmpShape2.curves = tmpPath2.curves; + shapes2.push(tmpShape2); + } + return shapes2; + } + function isPointInsidePolygon(inPt, inPolygon) { + const polyLen = inPolygon.length; + let inside = false; + for (let p = polyLen - 1, q = 0;q < polyLen; p = q++) { + let edgeLowPt = inPolygon[p]; + let edgeHighPt = inPolygon[q]; + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; + if (Math.abs(edgeDy) > Number.EPSILON) { + if (edgeDy < 0) { + edgeLowPt = inPolygon[q]; + edgeDx = -edgeDx; + edgeHighPt = inPolygon[p]; + edgeDy = -edgeDy; + } + if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) + continue; + if (inPt.y === edgeLowPt.y) { + if (inPt.x === edgeLowPt.x) + return true; + } else { + const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); + if (perpEdge === 0) + return true; + if (perpEdge < 0) + continue; + inside = !inside; + } + } else { + if (inPt.y !== edgeLowPt.y) + continue; + if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) + return true; + } + } + return inside; + } + const isClockWise = ShapeUtils2.isClockWise; + const subPaths = this.subPaths; + if (subPaths.length === 0) + return []; + let solid, tmpPath, tmpShape; + const shapes = []; + if (subPaths.length === 1) { + tmpPath = subPaths[0]; + tmpShape = new Shape2; + tmpShape.curves = tmpPath.curves; + shapes.push(tmpShape); + return shapes; + } + let holesFirst = !isClockWise(subPaths[0].getPoints()); + holesFirst = isCCW ? !holesFirst : holesFirst; + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; + newShapes[mainIdx] = undefined; + newShapeHoles[mainIdx] = []; + for (let i = 0, l = subPaths.length;i < l; i++) { + tmpPath = subPaths[i]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise(tmpPoints); + solid = isCCW ? !solid : solid; + if (solid) { + if (!holesFirst && newShapes[mainIdx]) + mainIdx++; + newShapes[mainIdx] = { s: new Shape2, p: tmpPoints }; + newShapes[mainIdx].s.curves = tmpPath.curves; + if (holesFirst) + mainIdx++; + newShapeHoles[mainIdx] = []; + } else { + newShapeHoles[mainIdx].push({ h: tmpPath, p: tmpPoints[0] }); + } + } + if (!newShapes[0]) + return toShapesNoHoles(subPaths); + if (newShapes.length > 1) { + let ambiguous = false; + let toChange = 0; + for (let sIdx = 0, sLen = newShapes.length;sIdx < sLen; sIdx++) { + betterShapeHoles[sIdx] = []; + } + for (let sIdx = 0, sLen = newShapes.length;sIdx < sLen; sIdx++) { + const sho = newShapeHoles[sIdx]; + for (let hIdx = 0;hIdx < sho.length; hIdx++) { + const ho = sho[hIdx]; + let hole_unassigned = true; + for (let s2Idx = 0;s2Idx < newShapes.length; s2Idx++) { + if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) { + if (sIdx !== s2Idx) + toChange++; + if (hole_unassigned) { + hole_unassigned = false; + betterShapeHoles[s2Idx].push(ho); + } else { + ambiguous = true; + } + } + } + if (hole_unassigned) { + betterShapeHoles[sIdx].push(ho); + } + } + } + if (toChange > 0 && ambiguous === false) { + newShapeHoles = betterShapeHoles; + } + } + let tmpHoles; + for (let i = 0, il = newShapes.length;i < il; i++) { + tmpShape = newShapes[i].s; + shapes.push(tmpShape); + tmpHoles = newShapeHoles[i]; + for (let j = 0, jl = tmpHoles.length;j < jl; j++) { + tmpShape.holes.push(tmpHoles[j].h); + } + } + return shapes; + } + } + + class Controls2 extends EventDispatcher2 { + constructor(object, domElement = null) { + super(); + this.object = object; + this.domElement = domElement; + this.enabled = true; + this.state = -1; + this.keys = {}; + this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null }; + this.touches = { ONE: null, TWO: null }; + } + connect() { + } + disconnect() { + } + dispose() { + } + update() { + } + } + function contain2(texture, aspect3) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect3) { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect3; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } else { + texture.repeat.x = aspect3 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } + return texture; + } + function cover2(texture, aspect3) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect3) { + texture.repeat.x = aspect3 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } else { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect3; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } + return texture; + } + function fill2(texture) { + texture.repeat.x = 1; + texture.repeat.y = 1; + texture.offset.x = 0; + texture.offset.y = 0; + return texture; + } + function getByteLength2(width2, height2, format, type) { + const typeByteLength = getTextureTypeByteLength2(type); + switch (format) { + case AlphaFormat2: + return width2 * height2; + case LuminanceFormat2: + return width2 * height2; + case LuminanceAlphaFormat2: + return width2 * height2 * 2; + case RedFormat2: + return width2 * height2 / typeByteLength.components * typeByteLength.byteLength; + case RedIntegerFormat2: + return width2 * height2 / typeByteLength.components * typeByteLength.byteLength; + case RGFormat2: + return width2 * height2 * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGIntegerFormat2: + return width2 * height2 * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGBFormat2: + return width2 * height2 * 3 / typeByteLength.components * typeByteLength.byteLength; + case RGBAFormat2: + return width2 * height2 * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGBAIntegerFormat2: + return width2 * height2 * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGB_S3TC_DXT1_Format2: + case RGBA_S3TC_DXT1_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 8; + case RGBA_S3TC_DXT3_Format2: + case RGBA_S3TC_DXT5_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGB_PVRTC_2BPPV1_Format2: + case RGBA_PVRTC_2BPPV1_Format2: + return Math.max(width2, 16) * Math.max(height2, 8) / 4; + case RGB_PVRTC_4BPPV1_Format2: + case RGBA_PVRTC_4BPPV1_Format2: + return Math.max(width2, 8) * Math.max(height2, 8) / 2; + case RGB_ETC1_Format2: + case RGB_ETC2_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 8; + case RGBA_ETC2_EAC_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_4x4_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_5x4_Format2: + return Math.floor((width2 + 4) / 5) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_5x5_Format2: + return Math.floor((width2 + 4) / 5) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_6x5_Format2: + return Math.floor((width2 + 5) / 6) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_6x6_Format2: + return Math.floor((width2 + 5) / 6) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_8x5_Format2: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_8x6_Format2: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_8x8_Format2: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 7) / 8) * 16; + case RGBA_ASTC_10x5_Format2: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_10x6_Format2: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_10x8_Format2: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 7) / 8) * 16; + case RGBA_ASTC_10x10_Format2: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 9) / 10) * 16; + case RGBA_ASTC_12x10_Format2: + return Math.floor((width2 + 11) / 12) * Math.floor((height2 + 9) / 10) * 16; + case RGBA_ASTC_12x12_Format2: + return Math.floor((width2 + 11) / 12) * Math.floor((height2 + 11) / 12) * 16; + case RGBA_BPTC_Format2: + case RGB_BPTC_SIGNED_Format2: + case RGB_BPTC_UNSIGNED_Format2: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 16; + case RED_RGTC1_Format2: + case SIGNED_RED_RGTC1_Format2: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 8; + case RED_GREEN_RGTC2_Format2: + case SIGNED_RED_GREEN_RGTC2_Format2: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 16; + } + throw new Error(`Unable to determine texture byte length for ${format} format.`); + } + function getTextureTypeByteLength2(type) { + switch (type) { + case UnsignedByteType2: + case ByteType2: + return { byteLength: 1, components: 1 }; + case UnsignedShortType2: + case ShortType2: + case HalfFloatType2: + return { byteLength: 2, components: 1 }; + case UnsignedShort4444Type2: + case UnsignedShort5551Type2: + return { byteLength: 2, components: 4 }; + case UnsignedIntType2: + case IntType2: + case FloatType2: + return { byteLength: 4, components: 1 }; + case UnsignedInt5999Type2: + return { byteLength: 4, components: 3 }; + } + throw new Error(`Unknown texture type ${type}.`); + } + var TextureUtils2 = { + contain: contain2, + cover: cover2, + fill: fill2, + getByteLength: getByteLength2 + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { + revision: REVISION2 + } })); + } + if (typeof window !== "undefined") { + if (window.__THREE__) { + console.warn("WARNING: Multiple instances of Three.js being imported."); + } else { + window.__THREE__ = REVISION2; + } + } + function WebGLAnimation2() { + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + function onAnimationFrame(time2, frame) { + animationLoop(time2, frame); + requestId = context.requestAnimationFrame(onAnimationFrame); + } + return { + start: function() { + if (isAnimating === true) + return; + if (animationLoop === null) + return; + requestId = context.requestAnimationFrame(onAnimationFrame); + isAnimating = true; + }, + stop: function() { + context.cancelAnimationFrame(requestId); + isAnimating = false; + }, + setAnimationLoop: function(callback) { + animationLoop = callback; + }, + setContext: function(value2) { + context = value2; + } + }; + } + function WebGLAttributes2(gl) { + const buffers = new WeakMap; + function createBuffer(attribute, bufferType) { + const array = attribute.array; + const usage = attribute.usage; + const size = array.byteLength; + const buffer = gl.createBuffer(); + gl.bindBuffer(bufferType, buffer); + gl.bufferData(bufferType, array, usage); + attribute.onUploadCallback(); + let type; + if (array instanceof Float32Array) { + type = gl.FLOAT; + } else if (array instanceof Uint16Array) { + if (attribute.isFloat16BufferAttribute) { + type = gl.HALF_FLOAT; + } else { + type = gl.UNSIGNED_SHORT; + } + } else if (array instanceof Int16Array) { + type = gl.SHORT; + } else if (array instanceof Uint32Array) { + type = gl.UNSIGNED_INT; + } else if (array instanceof Int32Array) { + type = gl.INT; + } else if (array instanceof Int8Array) { + type = gl.BYTE; + } else if (array instanceof Uint8Array) { + type = gl.UNSIGNED_BYTE; + } else if (array instanceof Uint8ClampedArray) { + type = gl.UNSIGNED_BYTE; + } else { + throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + array); + } + return { + buffer, + type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version, + size + }; + } + function updateBuffer(buffer, attribute, bufferType) { + const array = attribute.array; + const updateRanges = attribute.updateRanges; + gl.bindBuffer(bufferType, buffer); + if (updateRanges.length === 0) { + gl.bufferSubData(bufferType, 0, array); + } else { + updateRanges.sort((a, b) => a.start - b.start); + let mergeIndex = 0; + for (let i = 1;i < updateRanges.length; i++) { + const previousRange = updateRanges[mergeIndex]; + const range = updateRanges[i]; + if (range.start <= previousRange.start + previousRange.count + 1) { + previousRange.count = Math.max(previousRange.count, range.start + range.count - previousRange.start); + } else { + ++mergeIndex; + updateRanges[mergeIndex] = range; + } + } + updateRanges.length = mergeIndex + 1; + for (let i = 0, l = updateRanges.length;i < l; i++) { + const range = updateRanges[i]; + gl.bufferSubData(bufferType, range.start * array.BYTES_PER_ELEMENT, array, range.start, range.count); + } + attribute.clearUpdateRanges(); + } + attribute.onUploadCallback(); + } + function get(attribute) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + return buffers.get(attribute); + } + function remove(attribute) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + const data2 = buffers.get(attribute); + if (data2) { + gl.deleteBuffer(data2.buffer); + buffers.delete(attribute); + } + } + function update(attribute, bufferType) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + if (attribute.isGLBufferAttribute) { + const cached = buffers.get(attribute); + if (!cached || cached.version < attribute.version) { + buffers.set(attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + }); + } + return; + } + const data2 = buffers.get(attribute); + if (data2 === undefined) { + buffers.set(attribute, createBuffer(attribute, bufferType)); + } else if (data2.version < attribute.version) { + if (data2.size !== attribute.array.byteLength) { + throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported."); + } + updateBuffer(data2.buffer, attribute, bufferType); + data2.version = attribute.version; + } + } + return { + get, + remove, + update + }; + } + var alphahash_fragment2 = `#ifdef USE_ALPHAHASH + if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard; +#endif`; + var alphahash_pars_fragment2 = `#ifdef USE_ALPHAHASH + const float ALPHA_HASH_SCALE = 0.05; + float hash2D( vec2 value ) { + return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) ); + } + float hash3D( vec3 value ) { + return hash2D( vec2( hash2D( value.xy ), value.z ) ); + } + float getAlphaHashThreshold( vec3 position ) { + float maxDeriv = max( + length( dFdx( position.xyz ) ), + length( dFdy( position.xyz ) ) + ); + float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv ); + vec2 pixScales = vec2( + exp2( floor( log2( pixScale ) ) ), + exp2( ceil( log2( pixScale ) ) ) + ); + vec2 alpha = vec2( + hash3D( floor( pixScales.x * position.xyz ) ), + hash3D( floor( pixScales.y * position.xyz ) ) + ); + float lerpFactor = fract( log2( pixScale ) ); + float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y; + float a = min( lerpFactor, 1.0 - lerpFactor ); + vec3 cases = vec3( + x * x / ( 2.0 * a * ( 1.0 - a ) ), + ( x - 0.5 * a ) / ( 1.0 - a ), + 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) ) + ); + float threshold = ( x < ( 1.0 - a ) ) + ? ( ( x < a ) ? cases.x : cases.y ) + : cases.z; + return clamp( threshold , 1.0e-6, 1.0 ); + } +#endif`; + var alphamap_fragment2 = `#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g; +#endif`; + var alphamap_pars_fragment2 = `#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`; + var alphatest_fragment2 = `#ifdef USE_ALPHATEST + #ifdef ALPHA_TO_COVERAGE + diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a ); + if ( diffuseColor.a == 0.0 ) discard; + #else + if ( diffuseColor.a < alphaTest ) discard; + #endif +#endif`; + var alphatest_pars_fragment2 = `#ifdef USE_ALPHATEST + uniform float alphaTest; +#endif`; + var aomap_fragment2 = `#ifdef USE_AOMAP + float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0; + reflectedLight.indirectDiffuse *= ambientOcclusion; + #if defined( USE_CLEARCOAT ) + clearcoatSpecularIndirect *= ambientOcclusion; + #endif + #if defined( USE_SHEEN ) + sheenSpecularIndirect *= ambientOcclusion; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) + float dotNV = saturate( dot( geometryNormal, geometryViewDir ) ); + reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness ); + #endif +#endif`; + var aomap_pars_fragment2 = `#ifdef USE_AOMAP + uniform sampler2D aoMap; + uniform float aoMapIntensity; +#endif`; + var batching_pars_vertex2 = `#ifdef USE_BATCHING + #if ! defined( GL_ANGLE_multi_draw ) + #define gl_DrawID _gl_DrawID + uniform int _gl_DrawID; + #endif + uniform highp sampler2D batchingTexture; + uniform highp usampler2D batchingIdTexture; + mat4 getBatchingMatrix( const in float i ) { + int size = textureSize( batchingTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } + float getIndirectIndex( const in int i ) { + int size = textureSize( batchingIdTexture, 0 ).x; + int x = i % size; + int y = i / size; + return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r ); + } +#endif +#ifdef USE_BATCHING_COLOR + uniform sampler2D batchingColorTexture; + vec3 getBatchingColor( const in float i ) { + int size = textureSize( batchingColorTexture, 0 ).x; + int j = int( i ); + int x = j % size; + int y = j / size; + return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb; + } +#endif`; + var batching_vertex2 = `#ifdef USE_BATCHING + mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) ); +#endif`; + var begin_vertex2 = `vec3 transformed = vec3( position ); +#ifdef USE_ALPHAHASH + vPosition = vec3( position ); +#endif`; + var beginnormal_vertex2 = `vec3 objectNormal = vec3( normal ); +#ifdef USE_TANGENT + vec3 objectTangent = vec3( tangent.xyz ); +#endif`; + var bsdfs2 = `float G_BlinnPhong_Implicit( ) { + return 0.25; +} +float D_BlinnPhong( const in float shininess, const in float dotNH ) { + return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess ); +} +vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( specularColor, 1.0, dotVH ); + float G = G_BlinnPhong_Implicit( ); + float D = D_BlinnPhong( shininess, dotNH ); + return F * ( G * D ); +} // validated`; + var iridescence_fragment2 = `#ifdef USE_IRIDESCENCE + const mat3 XYZ_TO_REC709 = mat3( + 3.2404542, -0.9692660, 0.0556434, + -1.5371385, 1.8760108, -0.2040259, + -0.4985314, 0.0415560, 1.0572252 + ); + vec3 Fresnel0ToIor( vec3 fresnel0 ) { + vec3 sqrtF0 = sqrt( fresnel0 ); + return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 ); + } + vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) { + return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) ); + } + float IorToFresnel0( float transmittedIor, float incidentIor ) { + return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor )); + } + vec3 evalSensitivity( float OPD, vec3 shift ) { + float phase = 2.0 * PI * OPD * 1.0e-9; + vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 ); + vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 ); + vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 ); + vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var ); + xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) ); + xyz /= 1.0685e-7; + vec3 rgb = XYZ_TO_REC709 * xyz; + return rgb; + } + vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) { + vec3 I; + float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) ); + float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) ); + float cosTheta2Sq = 1.0 - sinTheta2Sq; + if ( cosTheta2Sq < 0.0 ) { + return vec3( 1.0 ); + } + float cosTheta2 = sqrt( cosTheta2Sq ); + float R0 = IorToFresnel0( iridescenceIOR, outsideIOR ); + float R12 = F_Schlick( R0, 1.0, cosTheta1 ); + float T121 = 1.0 - R12; + float phi12 = 0.0; + if ( iridescenceIOR < outsideIOR ) phi12 = PI; + float phi21 = PI - phi12; + vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR ); + vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 ); + vec3 phi23 = vec3( 0.0 ); + if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI; + if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI; + if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI; + float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2; + vec3 phi = vec3( phi21 ) + phi23; + vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 ); + vec3 r123 = sqrt( R123 ); + vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 ); + vec3 C0 = R12 + Rs; + I = C0; + vec3 Cm = Rs - T121; + for ( int m = 1; m <= 2; ++ m ) { + Cm *= r123; + vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi ); + I += Cm * Sm; + } + return max( I, vec3( 0.0 ) ); + } +#endif`; + var bumpmap_pars_fragment2 = `#ifdef USE_BUMPMAP + uniform sampler2D bumpMap; + uniform float bumpScale; + vec2 dHdxy_fwd() { + vec2 dSTdx = dFdx( vBumpMapUv ); + vec2 dSTdy = dFdy( vBumpMapUv ); + float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x; + float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll; + float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll; + return vec2( dBx, dBy ); + } + vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) { + vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) ); + vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) ); + vec3 vN = surf_norm; + vec3 R1 = cross( vSigmaY, vN ); + vec3 R2 = cross( vN, vSigmaX ); + float fDet = dot( vSigmaX, R1 ) * faceDirection; + vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 ); + return normalize( abs( fDet ) * surf_norm - vGrad ); + } +#endif`; + var clipping_planes_fragment2 = `#if NUM_CLIPPING_PLANES > 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`; + var clipping_planes_pars_fragment2 = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`; + var clipping_planes_pars_vertex2 = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`; + var clipping_planes_vertex2 = `#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`; + var color_fragment2 = `#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`; + var color_pars_fragment2 = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`; + var color_pars_vertex2 = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`; + var color_vertex2 = `#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`; + var common2 = `#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`; + var cube_uv_reflection_fragment2 = `#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`; + var defaultnormal_vertex2 = `vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`; + var displacementmap_pars_vertex2 = `#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`; + var displacementmap_vertex2 = `#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`; + var emissivemap_fragment2 = `#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`; + var emissivemap_pars_fragment2 = `#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`; + var colorspace_fragment2 = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; + var colorspace_pars_fragment2 = `vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`; + var envmap_fragment2 = `#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`; + var envmap_common_pars_fragment2 = `#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`; + var envmap_pars_fragment2 = `#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`; + var envmap_pars_vertex2 = `#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`; + var envmap_vertex2 = `#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`; + var fog_vertex2 = `#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`; + var fog_pars_vertex2 = `#ifdef USE_FOG + varying float vFogDepth; +#endif`; + var fog_fragment2 = `#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`; + var fog_pars_fragment2 = `#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`; + var gradientmap_pars_fragment2 = `#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`; + var lightmap_pars_fragment2 = `#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`; + var lights_lambert_fragment2 = `LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`; + var lights_lambert_pars_fragment2 = `varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`; + var lights_pars_begin2 = `uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`; + var envmap_physical_pars_fragment2 = `#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`; + var lights_toon_fragment2 = `ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`; + var lights_toon_pars_fragment2 = `varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`; + var lights_phong_fragment2 = `BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`; + var lights_phong_pars_fragment2 = `varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`; + var lights_physical_fragment2 = `PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`; + var lights_physical_pars_fragment2 = `struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`; + var lights_fragment_begin2 = ` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`; + var lights_fragment_maps2 = `#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`; + var lights_fragment_end2 = `#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`; + var logdepthbuf_fragment2 = `#if defined( USE_LOGDEPTHBUF ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`; + var logdepthbuf_pars_fragment2 = `#if defined( USE_LOGDEPTHBUF ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`; + var logdepthbuf_pars_vertex2 = `#ifdef USE_LOGDEPTHBUF + varying float vFragDepth; + varying float vIsPerspective; +#endif`; + var logdepthbuf_vertex2 = `#ifdef USE_LOGDEPTHBUF + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`; + var map_fragment2 = `#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`; + var map_pars_fragment2 = `#ifdef USE_MAP + uniform sampler2D map; +#endif`; + var map_particle_fragment2 = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`; + var map_particle_pars_fragment2 = `#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`; + var metalnessmap_fragment2 = `float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`; + var metalnessmap_pars_fragment2 = `#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`; + var morphinstance_vertex2 = `#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`; + var morphcolor_vertex2 = `#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`; + var morphnormal_vertex2 = `#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`; + var morphtarget_pars_vertex2 = `#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`; + var morphtarget_vertex2 = `#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`; + var normal_fragment_begin2 = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`; + var normal_fragment_maps2 = `#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`; + var normal_pars_fragment2 = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`; + var normal_pars_vertex2 = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`; + var normal_vertex2 = `#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`; + var normalmap_pars_fragment2 = `#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`; + var clearcoat_normal_fragment_begin2 = `#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`; + var clearcoat_normal_fragment_maps2 = `#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`; + var clearcoat_pars_fragment2 = `#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`; + var iridescence_pars_fragment2 = `#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`; + var opaque_fragment2 = `#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`; + var packing2 = `vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`; + var premultiplied_alpha_fragment2 = `#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`; + var project_vertex2 = `vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`; + var dithering_fragment2 = `#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`; + var dithering_pars_fragment2 = `#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`; + var roughnessmap_fragment2 = `float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`; + var roughnessmap_pars_fragment2 = `#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`; + var shadowmap_pars_fragment2 = `#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`; + var shadowmap_pars_vertex2 = `#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`; + var shadowmap_vertex2 = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`; + var shadowmask_pars_fragment2 = `float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`; + var skinbase_vertex2 = `#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`; + var skinning_pars_vertex2 = `#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`; + var skinning_vertex2 = `#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`; + var skinnormal_vertex2 = `#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`; + var specularmap_fragment2 = `float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`; + var specularmap_pars_fragment2 = `#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`; + var tonemapping_fragment2 = `#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`; + var tonemapping_pars_fragment2 = `#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`; + var transmission_fragment2 = `#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`; + var transmission_pars_fragment2 = `#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`; + var uv_pars_fragment2 = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`; + var uv_pars_vertex2 = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`; + var uv_vertex2 = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`; + var worldpos_vertex2 = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`; + var vertex$h2 = `varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`; + var fragment$h2 = `uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`; + var vertex$g2 = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`; + var fragment$g2 = `#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`; + var vertex$f2 = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`; + var fragment$f2 = `uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`; + var vertex$e2 = `#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`; + var fragment$e2 = `#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`; + var vertex$d2 = `#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`; + var fragment$d2 = `#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`; + var vertex$c2 = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`; + var fragment$c2 = `uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`; + var vertex$b2 = `uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; + var fragment$b2 = `uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`; + var vertex$a2 = `#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; + var fragment$a2 = `uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`; + var vertex$92 = `#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`; + var fragment$92 = `#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`; + var vertex$82 = `#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`; + var fragment$82 = `#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`; + var vertex$72 = `#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`; + var fragment$72 = `#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`; + var vertex$62 = `#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`; + var fragment$62 = `#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`; + var vertex$52 = `#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`; + var fragment$52 = `#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`; + var vertex$42 = `#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`; + var fragment$42 = `#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`; + var vertex$32 = `uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`; + var fragment$32 = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`; + var vertex$22 = `#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; + var fragment$22 = `uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`; + var vertex$12 = `uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`; + var fragment$12 = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`; + var ShaderChunk2 = { + alphahash_fragment: alphahash_fragment2, + alphahash_pars_fragment: alphahash_pars_fragment2, + alphamap_fragment: alphamap_fragment2, + alphamap_pars_fragment: alphamap_pars_fragment2, + alphatest_fragment: alphatest_fragment2, + alphatest_pars_fragment: alphatest_pars_fragment2, + aomap_fragment: aomap_fragment2, + aomap_pars_fragment: aomap_pars_fragment2, + batching_pars_vertex: batching_pars_vertex2, + batching_vertex: batching_vertex2, + begin_vertex: begin_vertex2, + beginnormal_vertex: beginnormal_vertex2, + bsdfs: bsdfs2, + iridescence_fragment: iridescence_fragment2, + bumpmap_pars_fragment: bumpmap_pars_fragment2, + clipping_planes_fragment: clipping_planes_fragment2, + clipping_planes_pars_fragment: clipping_planes_pars_fragment2, + clipping_planes_pars_vertex: clipping_planes_pars_vertex2, + clipping_planes_vertex: clipping_planes_vertex2, + color_fragment: color_fragment2, + color_pars_fragment: color_pars_fragment2, + color_pars_vertex: color_pars_vertex2, + color_vertex: color_vertex2, + common: common2, + cube_uv_reflection_fragment: cube_uv_reflection_fragment2, + defaultnormal_vertex: defaultnormal_vertex2, + displacementmap_pars_vertex: displacementmap_pars_vertex2, + displacementmap_vertex: displacementmap_vertex2, + emissivemap_fragment: emissivemap_fragment2, + emissivemap_pars_fragment: emissivemap_pars_fragment2, + colorspace_fragment: colorspace_fragment2, + colorspace_pars_fragment: colorspace_pars_fragment2, + envmap_fragment: envmap_fragment2, + envmap_common_pars_fragment: envmap_common_pars_fragment2, + envmap_pars_fragment: envmap_pars_fragment2, + envmap_pars_vertex: envmap_pars_vertex2, + envmap_physical_pars_fragment: envmap_physical_pars_fragment2, + envmap_vertex: envmap_vertex2, + fog_vertex: fog_vertex2, + fog_pars_vertex: fog_pars_vertex2, + fog_fragment: fog_fragment2, + fog_pars_fragment: fog_pars_fragment2, + gradientmap_pars_fragment: gradientmap_pars_fragment2, + lightmap_pars_fragment: lightmap_pars_fragment2, + lights_lambert_fragment: lights_lambert_fragment2, + lights_lambert_pars_fragment: lights_lambert_pars_fragment2, + lights_pars_begin: lights_pars_begin2, + lights_toon_fragment: lights_toon_fragment2, + lights_toon_pars_fragment: lights_toon_pars_fragment2, + lights_phong_fragment: lights_phong_fragment2, + lights_phong_pars_fragment: lights_phong_pars_fragment2, + lights_physical_fragment: lights_physical_fragment2, + lights_physical_pars_fragment: lights_physical_pars_fragment2, + lights_fragment_begin: lights_fragment_begin2, + lights_fragment_maps: lights_fragment_maps2, + lights_fragment_end: lights_fragment_end2, + logdepthbuf_fragment: logdepthbuf_fragment2, + logdepthbuf_pars_fragment: logdepthbuf_pars_fragment2, + logdepthbuf_pars_vertex: logdepthbuf_pars_vertex2, + logdepthbuf_vertex: logdepthbuf_vertex2, + map_fragment: map_fragment2, + map_pars_fragment: map_pars_fragment2, + map_particle_fragment: map_particle_fragment2, + map_particle_pars_fragment: map_particle_pars_fragment2, + metalnessmap_fragment: metalnessmap_fragment2, + metalnessmap_pars_fragment: metalnessmap_pars_fragment2, + morphinstance_vertex: morphinstance_vertex2, + morphcolor_vertex: morphcolor_vertex2, + morphnormal_vertex: morphnormal_vertex2, + morphtarget_pars_vertex: morphtarget_pars_vertex2, + morphtarget_vertex: morphtarget_vertex2, + normal_fragment_begin: normal_fragment_begin2, + normal_fragment_maps: normal_fragment_maps2, + normal_pars_fragment: normal_pars_fragment2, + normal_pars_vertex: normal_pars_vertex2, + normal_vertex: normal_vertex2, + normalmap_pars_fragment: normalmap_pars_fragment2, + clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin2, + clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps2, + clearcoat_pars_fragment: clearcoat_pars_fragment2, + iridescence_pars_fragment: iridescence_pars_fragment2, + opaque_fragment: opaque_fragment2, + packing: packing2, + premultiplied_alpha_fragment: premultiplied_alpha_fragment2, + project_vertex: project_vertex2, + dithering_fragment: dithering_fragment2, + dithering_pars_fragment: dithering_pars_fragment2, + roughnessmap_fragment: roughnessmap_fragment2, + roughnessmap_pars_fragment: roughnessmap_pars_fragment2, + shadowmap_pars_fragment: shadowmap_pars_fragment2, + shadowmap_pars_vertex: shadowmap_pars_vertex2, + shadowmap_vertex: shadowmap_vertex2, + shadowmask_pars_fragment: shadowmask_pars_fragment2, + skinbase_vertex: skinbase_vertex2, + skinning_pars_vertex: skinning_pars_vertex2, + skinning_vertex: skinning_vertex2, + skinnormal_vertex: skinnormal_vertex2, + specularmap_fragment: specularmap_fragment2, + specularmap_pars_fragment: specularmap_pars_fragment2, + tonemapping_fragment: tonemapping_fragment2, + tonemapping_pars_fragment: tonemapping_pars_fragment2, + transmission_fragment: transmission_fragment2, + transmission_pars_fragment: transmission_pars_fragment2, + uv_pars_fragment: uv_pars_fragment2, + uv_pars_vertex: uv_pars_vertex2, + uv_vertex: uv_vertex2, + worldpos_vertex: worldpos_vertex2, + background_vert: vertex$h2, + background_frag: fragment$h2, + backgroundCube_vert: vertex$g2, + backgroundCube_frag: fragment$g2, + cube_vert: vertex$f2, + cube_frag: fragment$f2, + depth_vert: vertex$e2, + depth_frag: fragment$e2, + distanceRGBA_vert: vertex$d2, + distanceRGBA_frag: fragment$d2, + equirect_vert: vertex$c2, + equirect_frag: fragment$c2, + linedashed_vert: vertex$b2, + linedashed_frag: fragment$b2, + meshbasic_vert: vertex$a2, + meshbasic_frag: fragment$a2, + meshlambert_vert: vertex$92, + meshlambert_frag: fragment$92, + meshmatcap_vert: vertex$82, + meshmatcap_frag: fragment$82, + meshnormal_vert: vertex$72, + meshnormal_frag: fragment$72, + meshphong_vert: vertex$62, + meshphong_frag: fragment$62, + meshphysical_vert: vertex$52, + meshphysical_frag: fragment$52, + meshtoon_vert: vertex$42, + meshtoon_frag: fragment$42, + points_vert: vertex$32, + points_frag: fragment$32, + shadow_vert: vertex$22, + shadow_frag: fragment$22, + sprite_vert: vertex$12, + sprite_frag: fragment$12 + }; + var UniformsLib2 = { + common: { + diffuse: { value: /* @__PURE__ */ new Color2(16777215) }, + opacity: { value: 1 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaTest: { value: 0 } + }, + specularmap: { + specularMap: { value: null }, + specularMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + envmap: { + envMap: { value: null }, + envMapRotation: { value: /* @__PURE__ */ new Matrix32 }, + flipEnvMap: { value: -1 }, + reflectivity: { value: 1 }, + ior: { value: 1.5 }, + refractionRatio: { value: 0.98 } + }, + aomap: { + aoMap: { value: null }, + aoMapIntensity: { value: 1 }, + aoMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + lightmap: { + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + bumpmap: { + bumpMap: { value: null }, + bumpMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + bumpScale: { value: 1 } + }, + normalmap: { + normalMap: { value: null }, + normalMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + normalScale: { value: /* @__PURE__ */ new Vector22(1, 1) } + }, + displacementmap: { + displacementMap: { value: null }, + displacementMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + }, + emissivemap: { + emissiveMap: { value: null }, + emissiveMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + metalnessmap: { + metalnessMap: { value: null }, + metalnessMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + roughnessmap: { + roughnessMap: { value: null }, + roughnessMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + gradientmap: { + gradientMap: { value: null } + }, + fog: { + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: /* @__PURE__ */ new Color2(16777215) } + }, + lights: { + ambientLightColor: { value: [] }, + lightProbe: { value: [] }, + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + directionalLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + spotLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + pointLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + ltc_1: { value: null }, + ltc_2: { value: null } + }, + points: { + diffuse: { value: /* @__PURE__ */ new Color2(16777215) }, + opacity: { value: 1 }, + size: { value: 1 }, + scale: { value: 1 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaTest: { value: 0 }, + uvTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + sprite: { + diffuse: { value: /* @__PURE__ */ new Color2(16777215) }, + opacity: { value: 1 }, + center: { value: /* @__PURE__ */ new Vector22(0.5, 0.5) }, + rotation: { value: 0 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaTest: { value: 0 } + } + }; + var ShaderLib2 = { + basic: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.specularmap, + UniformsLib2.envmap, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.fog + ]), + vertexShader: ShaderChunk2.meshbasic_vert, + fragmentShader: ShaderChunk2.meshbasic_frag + }, + lambert: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.specularmap, + UniformsLib2.envmap, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.emissivemap, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.fog, + UniformsLib2.lights, + { + emissive: { value: /* @__PURE__ */ new Color2(0) } + } + ]), + vertexShader: ShaderChunk2.meshlambert_vert, + fragmentShader: ShaderChunk2.meshlambert_frag + }, + phong: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.specularmap, + UniformsLib2.envmap, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.emissivemap, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.fog, + UniformsLib2.lights, + { + emissive: { value: /* @__PURE__ */ new Color2(0) }, + specular: { value: /* @__PURE__ */ new Color2(1118481) }, + shininess: { value: 30 } + } + ]), + vertexShader: ShaderChunk2.meshphong_vert, + fragmentShader: ShaderChunk2.meshphong_frag + }, + standard: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.envmap, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.emissivemap, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.roughnessmap, + UniformsLib2.metalnessmap, + UniformsLib2.fog, + UniformsLib2.lights, + { + emissive: { value: /* @__PURE__ */ new Color2(0) }, + roughness: { value: 1 }, + metalness: { value: 0 }, + envMapIntensity: { value: 1 } + } + ]), + vertexShader: ShaderChunk2.meshphysical_vert, + fragmentShader: ShaderChunk2.meshphysical_frag + }, + toon: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.emissivemap, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.gradientmap, + UniformsLib2.fog, + UniformsLib2.lights, + { + emissive: { value: /* @__PURE__ */ new Color2(0) } + } + ]), + vertexShader: ShaderChunk2.meshtoon_vert, + fragmentShader: ShaderChunk2.meshtoon_frag + }, + matcap: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.fog, + { + matcap: { value: null } + } + ]), + vertexShader: ShaderChunk2.meshmatcap_vert, + fragmentShader: ShaderChunk2.meshmatcap_frag + }, + points: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.points, + UniformsLib2.fog + ]), + vertexShader: ShaderChunk2.points_vert, + fragmentShader: ShaderChunk2.points_frag + }, + dashed: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ]), + vertexShader: ShaderChunk2.linedashed_vert, + fragmentShader: ShaderChunk2.linedashed_frag + }, + depth: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.displacementmap + ]), + vertexShader: ShaderChunk2.depth_vert, + fragmentShader: ShaderChunk2.depth_frag + }, + normal: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + { + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk2.meshnormal_vert, + fragmentShader: ShaderChunk2.meshnormal_frag + }, + sprite: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.sprite, + UniformsLib2.fog + ]), + vertexShader: ShaderChunk2.sprite_vert, + fragmentShader: ShaderChunk2.sprite_frag + }, + background: { + uniforms: { + uvTransform: { value: /* @__PURE__ */ new Matrix32 }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + vertexShader: ShaderChunk2.background_vert, + fragmentShader: ShaderChunk2.background_frag + }, + backgroundCube: { + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /* @__PURE__ */ new Matrix32 } + }, + vertexShader: ShaderChunk2.backgroundCube_vert, + fragmentShader: ShaderChunk2.backgroundCube_frag + }, + cube: { + uniforms: { + tCube: { value: null }, + tFlip: { value: -1 }, + opacity: { value: 1 } + }, + vertexShader: ShaderChunk2.cube_vert, + fragmentShader: ShaderChunk2.cube_frag + }, + equirect: { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ShaderChunk2.equirect_vert, + fragmentShader: ShaderChunk2.equirect_frag + }, + distanceRGBA: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.displacementmap, + { + referencePosition: { value: /* @__PURE__ */ new Vector32 }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ]), + vertexShader: ShaderChunk2.distanceRGBA_vert, + fragmentShader: ShaderChunk2.distanceRGBA_frag + }, + shadow: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.lights, + UniformsLib2.fog, + { + color: { value: /* @__PURE__ */ new Color2(0) }, + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk2.shadow_vert, + fragmentShader: ShaderChunk2.shadow_frag + } + }; + ShaderLib2.physical = { + uniforms: /* @__PURE__ */ mergeUniforms2([ + ShaderLib2.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + clearcoatNormalScale: { value: /* @__PURE__ */ new Vector22(1, 1) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + dispersion: { value: 0 }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + sheen: { value: 0 }, + sheenColor: { value: /* @__PURE__ */ new Color2(0) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + transmissionSamplerSize: { value: /* @__PURE__ */ new Vector22 }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /* @__PURE__ */ new Color2(0) }, + specularColor: { value: /* @__PURE__ */ new Color2(1, 1, 1) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + anisotropyVector: { value: /* @__PURE__ */ new Vector22 }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /* @__PURE__ */ new Matrix32 } + } + ]), + vertexShader: ShaderChunk2.meshphysical_vert, + fragmentShader: ShaderChunk2.meshphysical_frag + }; + var _rgb2 = { r: 0, b: 0, g: 0 }; + var _e1$12 = /* @__PURE__ */ new Euler2; + var _m1$13 = /* @__PURE__ */ new Matrix42; + function WebGLBackground2(renderer2, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) { + const clearColor = new Color2(0); + let clearAlpha = alpha === true ? 0 : 1; + let planeMesh; + let boxMesh; + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + function getBackground(scene) { + let background = scene.isScene === true ? scene.background : null; + if (background && background.isTexture) { + const usePMREM = scene.backgroundBlurriness > 0; + background = (usePMREM ? cubeuvmaps : cubemaps).get(background); + } + return background; + } + function render(scene) { + let forceClear = false; + const background = getBackground(scene); + if (background === null) { + setClear(clearColor, clearAlpha); + } else if (background && background.isColor) { + setClear(background, 1); + forceClear = true; + } + const environmentBlendMode = renderer2.xr.getEnvironmentBlendMode(); + if (environmentBlendMode === "additive") { + state.buffers.color.setClear(0, 0, 0, 1, premultipliedAlpha); + } else if (environmentBlendMode === "alpha-blend") { + state.buffers.color.setClear(0, 0, 0, 0, premultipliedAlpha); + } + if (renderer2.autoClear || forceClear) { + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + renderer2.clear(renderer2.autoClearColor, renderer2.autoClearDepth, renderer2.autoClearStencil); + } + } + function addToRenderList(renderList, scene) { + const background = getBackground(scene); + if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping2)) { + if (boxMesh === undefined) { + boxMesh = new Mesh2(new BoxGeometry2(1, 1, 1), new ShaderMaterial2({ + name: "BackgroundCubeMaterial", + uniforms: cloneUniforms2(ShaderLib2.backgroundCube.uniforms), + vertexShader: ShaderLib2.backgroundCube.vertexShader, + fragmentShader: ShaderLib2.backgroundCube.fragmentShader, + side: BackSide2, + depthTest: false, + depthWrite: false, + fog: false + })); + boxMesh.geometry.deleteAttribute("normal"); + boxMesh.geometry.deleteAttribute("uv"); + boxMesh.onBeforeRender = function(renderer3, scene2, camera) { + this.matrixWorld.copyPosition(camera.matrixWorld); + }; + Object.defineProperty(boxMesh.material, "envMap", { + get: function() { + return this.uniforms.envMap.value; + } + }); + objects.update(boxMesh); + } + _e1$12.copy(scene.backgroundRotation); + _e1$12.x *= -1; + _e1$12.y *= -1; + _e1$12.z *= -1; + if (background.isCubeTexture && background.isRenderTargetTexture === false) { + _e1$12.y *= -1; + _e1$12.z *= -1; + } + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4(_m1$13.makeRotationFromEuler(_e1$12)); + boxMesh.material.toneMapped = ColorManagement2.getTransfer(background.colorSpace) !== SRGBTransfer2; + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer2.toneMapping) { + boxMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer2.toneMapping; + } + boxMesh.layers.enableAll(); + renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null); + } else if (background && background.isTexture) { + if (planeMesh === undefined) { + planeMesh = new Mesh2(new PlaneGeometry2(2, 2), new ShaderMaterial2({ + name: "BackgroundMaterial", + uniforms: cloneUniforms2(ShaderLib2.background.uniforms), + vertexShader: ShaderLib2.background.vertexShader, + fragmentShader: ShaderLib2.background.fragmentShader, + side: FrontSide2, + depthTest: false, + depthWrite: false, + fog: false + })); + planeMesh.geometry.deleteAttribute("normal"); + Object.defineProperty(planeMesh.material, "map", { + get: function() { + return this.uniforms.t2D.value; + } + }); + objects.update(planeMesh); + } + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ColorManagement2.getTransfer(background.colorSpace) !== SRGBTransfer2; + if (background.matrixAutoUpdate === true) { + background.updateMatrix(); + } + planeMesh.material.uniforms.uvTransform.value.copy(background.matrix); + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer2.toneMapping) { + planeMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer2.toneMapping; + } + planeMesh.layers.enableAll(); + renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null); + } + } + function setClear(color, alpha2) { + color.getRGB(_rgb2, getUnlitUniformColorSpace2(renderer2)); + state.buffers.color.setClear(_rgb2.r, _rgb2.g, _rgb2.b, alpha2, premultipliedAlpha); + } + function dispose() { + if (boxMesh !== undefined) { + boxMesh.geometry.dispose(); + boxMesh.material.dispose(); + boxMesh = undefined; + } + if (planeMesh !== undefined) { + planeMesh.geometry.dispose(); + planeMesh.material.dispose(); + planeMesh = undefined; + } + } + return { + getClearColor: function() { + return clearColor; + }, + setClearColor: function(color, alpha2 = 1) { + clearColor.set(color); + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + getClearAlpha: function() { + return clearAlpha; + }, + setClearAlpha: function(alpha2) { + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + render, + addToRenderList, + dispose + }; + } + function WebGLBindingStates2(gl, attributes) { + const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const bindingStates = {}; + const defaultState = createBindingState(null); + let currentState = defaultState; + let forceUpdate = false; + function setup(object, material, program, geometry, index2) { + let updateBuffers = false; + const state = getBindingState(geometry, program, material); + if (currentState !== state) { + currentState = state; + bindVertexArrayObject(currentState.object); + } + updateBuffers = needsUpdate(object, geometry, program, index2); + if (updateBuffers) + saveCache(object, geometry, program, index2); + if (index2 !== null) { + attributes.update(index2, gl.ELEMENT_ARRAY_BUFFER); + } + if (updateBuffers || forceUpdate) { + forceUpdate = false; + setupVertexAttributes(object, material, program, geometry); + if (index2 !== null) { + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index2).buffer); + } + } + } + function createVertexArrayObject() { + return gl.createVertexArray(); + } + function bindVertexArrayObject(vao) { + return gl.bindVertexArray(vao); + } + function deleteVertexArrayObject(vao) { + return gl.deleteVertexArray(vao); + } + function getBindingState(geometry, program, material) { + const wireframe = material.wireframe === true; + let programMap = bindingStates[geometry.id]; + if (programMap === undefined) { + programMap = {}; + bindingStates[geometry.id] = programMap; + } + let stateMap = programMap[program.id]; + if (stateMap === undefined) { + stateMap = {}; + programMap[program.id] = stateMap; + } + let state = stateMap[wireframe]; + if (state === undefined) { + state = createBindingState(createVertexArrayObject()); + stateMap[wireframe] = state; + } + return state; + } + function createBindingState(vao) { + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + for (let i = 0;i < maxVertexAttributes; i++) { + newAttributes[i] = 0; + enabledAttributes[i] = 0; + attributeDivisors[i] = 0; + } + return { + geometry: null, + program: null, + wireframe: false, + newAttributes, + enabledAttributes, + attributeDivisors, + object: vao, + attributes: {}, + index: null + }; + } + function needsUpdate(object, geometry, program, index2) { + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + const cachedAttribute = cachedAttributes[name2]; + let geometryAttribute = geometryAttributes[name2]; + if (geometryAttribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + geometryAttribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + geometryAttribute = object.instanceColor; + } + if (cachedAttribute === undefined) + return true; + if (cachedAttribute.attribute !== geometryAttribute) + return true; + if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) + return true; + attributesNum++; + } + } + if (currentState.attributesNum !== attributesNum) + return true; + if (currentState.index !== index2) + return true; + return false; + } + function saveCache(object, geometry, program, index2) { + const cache = {}; + const attributes2 = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + let attribute = attributes2[name2]; + if (attribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + attribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + attribute = object.instanceColor; + } + const data2 = {}; + data2.attribute = attribute; + if (attribute && attribute.data) { + data2.data = attribute.data; + } + cache[name2] = data2; + attributesNum++; + } + } + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + currentState.index = index2; + } + function initAttributes() { + const newAttributes = currentState.newAttributes; + for (let i = 0, il = newAttributes.length;i < il; i++) { + newAttributes[i] = 0; + } + } + function enableAttribute(attribute) { + enableAttributeAndDivisor(attribute, 0); + } + function enableAttributeAndDivisor(attribute, meshPerAttribute) { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + newAttributes[attribute] = 1; + if (enabledAttributes[attribute] === 0) { + gl.enableVertexAttribArray(attribute); + enabledAttributes[attribute] = 1; + } + if (attributeDivisors[attribute] !== meshPerAttribute) { + gl.vertexAttribDivisor(attribute, meshPerAttribute); + attributeDivisors[attribute] = meshPerAttribute; + } + } + function disableUnusedAttributes() { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + for (let i = 0, il = enabledAttributes.length;i < il; i++) { + if (enabledAttributes[i] !== newAttributes[i]) { + gl.disableVertexAttribArray(i); + enabledAttributes[i] = 0; + } + } + } + function vertexAttribPointer(index2, size, type, normalized, stride, offset, integer) { + if (integer === true) { + gl.vertexAttribIPointer(index2, size, type, stride, offset); + } else { + gl.vertexAttribPointer(index2, size, type, normalized, stride, offset); + } + } + function setupVertexAttributes(object, material, program, geometry) { + initAttributes(); + const geometryAttributes = geometry.attributes; + const programAttributes = program.getAttributes(); + const materialDefaultAttributeValues = material.defaultAttributeValues; + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + let geometryAttribute = geometryAttributes[name2]; + if (geometryAttribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + geometryAttribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + geometryAttribute = object.instanceColor; + } + if (geometryAttribute !== undefined) { + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + const attribute = attributes.get(geometryAttribute); + if (attribute === undefined) + continue; + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + const integer = type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType2; + if (geometryAttribute.isInterleavedBufferAttribute) { + const data2 = geometryAttribute.data; + const stride = data2.stride; + const offset = geometryAttribute.offset; + if (data2.isInstancedInterleavedBuffer) { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, data2.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { + geometry._maxInstanceCount = data2.meshPerAttribute * data2.count; + } + } else { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0;i < programAttribute.locationSize; i++) { + vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement, integer); + } + } else { + if (geometryAttribute.isInstancedBufferAttribute) { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } + } else { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0;i < programAttribute.locationSize; i++) { + vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement, integer); + } + } + } else if (materialDefaultAttributeValues !== undefined) { + const value2 = materialDefaultAttributeValues[name2]; + if (value2 !== undefined) { + switch (value2.length) { + case 2: + gl.vertexAttrib2fv(programAttribute.location, value2); + break; + case 3: + gl.vertexAttrib3fv(programAttribute.location, value2); + break; + case 4: + gl.vertexAttrib4fv(programAttribute.location, value2); + break; + default: + gl.vertexAttrib1fv(programAttribute.location, value2); + } + } + } + } + } + disableUnusedAttributes(); + } + function dispose() { + reset(); + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometryId]; + } + } + function releaseStatesOfGeometry(geometry) { + if (bindingStates[geometry.id] === undefined) + return; + const programMap = bindingStates[geometry.id]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometry.id]; + } + function releaseStatesOfProgram(program) { + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + if (programMap[program.id] === undefined) + continue; + const stateMap = programMap[program.id]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[program.id]; + } + } + function reset() { + resetDefaultState(); + forceUpdate = true; + if (currentState === defaultState) + return; + currentState = defaultState; + bindVertexArrayObject(currentState.object); + } + function resetDefaultState() { + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + } + return { + setup, + reset, + resetDefaultState, + dispose, + releaseStatesOfGeometry, + releaseStatesOfProgram, + initAttributes, + enableAttribute, + disableUnusedAttributes + }; + } + function WebGLBufferRenderer2(gl, extensions, info) { + let mode; + function setMode(value2) { + mode = value2; + } + function render(start, count) { + gl.drawArrays(mode, start, count); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) + return; + gl.drawArraysInstanced(mode, start, count, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawArraysWEBGL(mode, starts, 0, counts, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0;i < starts.length; i++) { + renderInstances(starts[i], counts[i], primcount[i]); + } + } else { + extension.multiDrawArraysInstancedWEBGL(mode, starts, 0, counts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i] * primcount[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; + } + function WebGLCapabilities2(gl, extensions, parameters, utils) { + let maxAnisotropy; + function getMaxAnisotropy() { + if (maxAnisotropy !== undefined) + return maxAnisotropy; + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } else { + maxAnisotropy = 0; + } + return maxAnisotropy; + } + function textureFormatReadable(textureFormat) { + if (textureFormat !== RGBAFormat2 && utils.convert(textureFormat) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT)) { + return false; + } + return true; + } + function textureTypeReadable(textureType) { + const halfFloatSupportedByExt = textureType === HalfFloatType2 && (extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float")); + if (textureType !== UnsignedByteType2 && utils.convert(textureType) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE) && textureType !== FloatType2 && !halfFloatSupportedByExt) { + return false; + } + return true; + } + function getMaxPrecision(precision2) { + if (precision2 === "highp") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) { + return "highp"; + } + precision2 = "mediump"; + } + if (precision2 === "mediump") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) { + return "mediump"; + } + } + return "lowp"; + } + let precision = parameters.precision !== undefined ? parameters.precision : "highp"; + const maxPrecision = getMaxPrecision(precision); + if (maxPrecision !== precision) { + console.warn("THREE.WebGLRenderer:", precision, "not supported, using", maxPrecision, "instead."); + precision = maxPrecision; + } + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has("EXT_clip_control"); + const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); + const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); + const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); + const vertexTextures = maxVertexTextures > 0; + const maxSamples = gl.getParameter(gl.MAX_SAMPLES); + return { + isWebGL2: true, + getMaxAnisotropy, + getMaxPrecision, + textureFormatReadable, + textureTypeReadable, + precision, + logarithmicDepthBuffer, + reverseDepthBuffer, + maxTextures, + maxVertexTextures, + maxTextureSize, + maxCubemapSize, + maxAttributes, + maxVertexUniforms, + maxVaryings, + maxFragmentUniforms, + vertexTextures, + maxSamples + }; + } + function WebGLClipping2(properties) { + const scope = this; + let globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false; + const plane = new Plane2, viewNormalMatrix = new Matrix32, uniform = { value: null, needsUpdate: false }; + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + this.init = function(planes, enableLocalClipping) { + const enabled = planes.length !== 0 || enableLocalClipping || numGlobalPlanes !== 0 || localClippingEnabled; + localClippingEnabled = enableLocalClipping; + numGlobalPlanes = planes.length; + return enabled; + }; + this.beginShadows = function() { + renderingShadows = true; + projectPlanes(null); + }; + this.endShadows = function() { + renderingShadows = false; + }; + this.setGlobalState = function(planes, camera) { + globalState = projectPlanes(planes, camera, 0); + }; + this.setState = function(material, camera, useCache) { + const { clippingPlanes: planes, clipIntersection, clipShadows } = material; + const materialProperties = properties.get(material); + if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) { + if (renderingShadows) { + projectPlanes(null); + } else { + resetGlobalState(); + } + } else { + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4; + let dstArray = materialProperties.clippingState || null; + uniform.value = dstArray; + dstArray = projectPlanes(planes, camera, lGlobal, useCache); + for (let i = 0;i !== lGlobal; ++i) { + dstArray[i] = globalState[i]; + } + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + } + }; + function resetGlobalState() { + if (uniform.value !== globalState) { + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + } + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + } + function projectPlanes(planes, camera, dstOffset, skipTransform) { + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + if (nPlanes !== 0) { + dstArray = uniform.value; + if (skipTransform !== true || dstArray === null) { + const flatSize = dstOffset + nPlanes * 4, viewMatrix = camera.matrixWorldInverse; + viewNormalMatrix.getNormalMatrix(viewMatrix); + if (dstArray === null || dstArray.length < flatSize) { + dstArray = new Float32Array(flatSize); + } + for (let i = 0, i4 = dstOffset;i !== nPlanes; ++i, i4 += 4) { + plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix); + plane.normal.toArray(dstArray, i4); + dstArray[i4 + 3] = plane.constant; + } + } + uniform.value = dstArray; + uniform.needsUpdate = true; + } + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + return dstArray; + } + } + function WebGLCubeMaps2(renderer2) { + let cubemaps = new WeakMap; + function mapTextureMapping(texture, mapping) { + if (mapping === EquirectangularReflectionMapping2) { + texture.mapping = CubeReflectionMapping2; + } else if (mapping === EquirectangularRefractionMapping2) { + texture.mapping = CubeRefractionMapping2; + } + return texture; + } + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + if (mapping === EquirectangularReflectionMapping2 || mapping === EquirectangularRefractionMapping2) { + if (cubemaps.has(texture)) { + const cubemap = cubemaps.get(texture).texture; + return mapTextureMapping(cubemap, texture.mapping); + } else { + const image = texture.image; + if (image && image.height > 0) { + const renderTarget = new WebGLCubeRenderTarget2(image.height); + renderTarget.fromEquirectangularTexture(renderer2, texture); + cubemaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return mapTextureMapping(renderTarget.texture, texture.mapping); + } else { + return null; + } + } + } + } + return texture; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemap = cubemaps.get(texture); + if (cubemap !== undefined) { + cubemaps.delete(texture); + cubemap.dispose(); + } + } + function dispose() { + cubemaps = new WeakMap; + } + return { + get, + dispose + }; + } + var LOD_MIN2 = 4; + var EXTRA_LOD_SIGMA2 = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; + var MAX_SAMPLES2 = 20; + var _flatCamera2 = /* @__PURE__ */ new OrthographicCamera2; + var _clearColor2 = /* @__PURE__ */ new Color2; + var _oldTarget2 = null; + var _oldActiveCubeFace2 = 0; + var _oldActiveMipmapLevel2 = 0; + var _oldXrEnabled2 = false; + var PHI2 = (1 + Math.sqrt(5)) / 2; + var INV_PHI2 = 1 / PHI2; + var _axisDirections2 = [ + /* @__PURE__ */ new Vector32(-PHI2, INV_PHI2, 0), + /* @__PURE__ */ new Vector32(PHI2, INV_PHI2, 0), + /* @__PURE__ */ new Vector32(-INV_PHI2, 0, PHI2), + /* @__PURE__ */ new Vector32(INV_PHI2, 0, PHI2), + /* @__PURE__ */ new Vector32(0, PHI2, -INV_PHI2), + /* @__PURE__ */ new Vector32(0, PHI2, INV_PHI2), + /* @__PURE__ */ new Vector32(-1, 1, -1), + /* @__PURE__ */ new Vector32(1, 1, -1), + /* @__PURE__ */ new Vector32(-1, 1, 1), + /* @__PURE__ */ new Vector32(1, 1, 1) + ]; + + class PMREMGenerator2 { + constructor(renderer2) { + this._renderer = renderer2; + this._pingPongRenderTarget = null; + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + this._compileMaterial(this._blurMaterial); + } + fromScene(scene, sigma = 0, near = 0.1, far = 100) { + _oldTarget2 = this._renderer.getRenderTarget(); + _oldActiveCubeFace2 = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel2 = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled2 = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + this._setSize(256); + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget); + if (sigma > 0) { + this._blur(cubeUVRenderTarget, 0, 0, sigma); + } + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + fromEquirectangular(equirectangular, renderTarget = null) { + return this._fromTexture(equirectangular, renderTarget); + } + fromCubemap(cubemap, renderTarget = null) { + return this._fromTexture(cubemap, renderTarget); + } + compileCubemapShader() { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial2(); + this._compileMaterial(this._cubemapMaterial); + } + } + compileEquirectangularShader() { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial2(); + this._compileMaterial(this._equirectMaterial); + } + } + dispose() { + this._dispose(); + if (this._cubemapMaterial !== null) + this._cubemapMaterial.dispose(); + if (this._equirectMaterial !== null) + this._equirectMaterial.dispose(); + } + _setSize(cubeSize) { + this._lodMax = Math.floor(Math.log2(cubeSize)); + this._cubeSize = Math.pow(2, this._lodMax); + } + _dispose() { + if (this._blurMaterial !== null) + this._blurMaterial.dispose(); + if (this._pingPongRenderTarget !== null) + this._pingPongRenderTarget.dispose(); + for (let i = 0;i < this._lodPlanes.length; i++) { + this._lodPlanes[i].dispose(); + } + } + _cleanup(outputTarget) { + this._renderer.setRenderTarget(_oldTarget2, _oldActiveCubeFace2, _oldActiveMipmapLevel2); + this._renderer.xr.enabled = _oldXrEnabled2; + outputTarget.scissorTest = false; + _setViewport2(outputTarget, 0, 0, outputTarget.width, outputTarget.height); + } + _fromTexture(texture, renderTarget) { + if (texture.mapping === CubeReflectionMapping2 || texture.mapping === CubeRefractionMapping2) { + this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width); + } else { + this._setSize(texture.image.width / 4); + } + _oldTarget2 = this._renderer.getRenderTarget(); + _oldActiveCubeFace2 = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel2 = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled2 = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV(texture, cubeUVRenderTarget); + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + _allocateTargets() { + const width2 = 3 * Math.max(this._cubeSize, 16 * 7); + const height2 = 4 * this._cubeSize; + const params = { + magFilter: LinearFilter2, + minFilter: LinearFilter2, + generateMipmaps: false, + type: HalfFloatType2, + format: RGBAFormat2, + colorSpace: LinearSRGBColorSpace2, + depthBuffer: false + }; + const cubeUVRenderTarget = _createRenderTarget2(width2, height2, params); + if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width2 || this._pingPongRenderTarget.height !== height2) { + if (this._pingPongRenderTarget !== null) { + this._dispose(); + } + this._pingPongRenderTarget = _createRenderTarget2(width2, height2, params); + const { _lodMax } = this; + ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes2(_lodMax)); + this._blurMaterial = _getBlurShader2(_lodMax, width2, height2); + } + return cubeUVRenderTarget; + } + _compileMaterial(material) { + const tmpMesh = new Mesh2(this._lodPlanes[0], material); + this._renderer.compile(tmpMesh, _flatCamera2); + } + _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) { + const fov3 = 90; + const aspect3 = 1; + const cubeCamera = new PerspectiveCamera2(fov3, aspect3, near, far); + const upSign = [1, -1, 1, 1, 1, 1]; + const forwardSign = [1, 1, 1, -1, -1, -1]; + const renderer2 = this._renderer; + const originalAutoClear = renderer2.autoClear; + const toneMapping = renderer2.toneMapping; + renderer2.getClearColor(_clearColor2); + renderer2.toneMapping = NoToneMapping2; + renderer2.autoClear = false; + const backgroundMaterial = new MeshBasicMaterial2({ + name: "PMREM.Background", + side: BackSide2, + depthWrite: false, + depthTest: false + }); + const backgroundBox = new Mesh2(new BoxGeometry2, backgroundMaterial); + let useSolidColor = false; + const background = scene.background; + if (background) { + if (background.isColor) { + backgroundMaterial.color.copy(background); + scene.background = null; + useSolidColor = true; + } + } else { + backgroundMaterial.color.copy(_clearColor2); + useSolidColor = true; + } + for (let i = 0;i < 6; i++) { + const col = i % 3; + if (col === 0) { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(forwardSign[i], 0, 0); + } else if (col === 1) { + cubeCamera.up.set(0, 0, upSign[i]); + cubeCamera.lookAt(0, forwardSign[i], 0); + } else { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(0, 0, forwardSign[i]); + } + const size = this._cubeSize; + _setViewport2(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size); + renderer2.setRenderTarget(cubeUVRenderTarget); + if (useSolidColor) { + renderer2.render(backgroundBox, cubeCamera); + } + renderer2.render(scene, cubeCamera); + } + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + renderer2.toneMapping = toneMapping; + renderer2.autoClear = originalAutoClear; + scene.background = background; + } + _textureToCubeUV(texture, cubeUVRenderTarget) { + const renderer2 = this._renderer; + const isCubeTexture = texture.mapping === CubeReflectionMapping2 || texture.mapping === CubeRefractionMapping2; + if (isCubeTexture) { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial2(); + } + this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1; + } else { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial2(); + } + } + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh2(this._lodPlanes[0], material); + const uniforms = material.uniforms; + uniforms["envMap"].value = texture; + const size = this._cubeSize; + _setViewport2(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size); + renderer2.setRenderTarget(cubeUVRenderTarget); + renderer2.render(mesh, _flatCamera2); + } + _applyPMREM(cubeUVRenderTarget) { + const renderer2 = this._renderer; + const autoClear = renderer2.autoClear; + renderer2.autoClear = false; + const n = this._lodPlanes.length; + for (let i = 1;i < n; i++) { + const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]); + const poleAxis = _axisDirections2[(n - i - 1) % _axisDirections2.length]; + this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis); + } + renderer2.autoClear = autoClear; + } + _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) { + const pingPongRenderTarget = this._pingPongRenderTarget; + this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, "latitudinal", poleAxis); + this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, "longitudinal", poleAxis); + } + _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) { + const renderer2 = this._renderer; + const blurMaterial = this._blurMaterial; + if (direction !== "latitudinal" && direction !== "longitudinal") { + console.error("blur direction must be either latitudinal or longitudinal!"); + } + const STANDARD_DEVIATIONS = 3; + const blurMesh = new Mesh2(this._lodPlanes[lodOut], blurMaterial); + const blurUniforms = blurMaterial.uniforms; + const pixels = this._sizeLods[lodIn] - 1; + const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES2 - 1); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES2; + if (samples > MAX_SAMPLES2) { + console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES2}`); + } + const weights = []; + let sum2 = 0; + for (let i = 0;i < MAX_SAMPLES2; ++i) { + const x2 = i / sigmaPixels; + const weight = Math.exp(-x2 * x2 / 2); + weights.push(weight); + if (i === 0) { + sum2 += weight; + } else if (i < samples) { + sum2 += 2 * weight; + } + } + for (let i = 0;i < weights.length; i++) { + weights[i] = weights[i] / sum2; + } + blurUniforms["envMap"].value = targetIn.texture; + blurUniforms["samples"].value = samples; + blurUniforms["weights"].value = weights; + blurUniforms["latitudinal"].value = direction === "latitudinal"; + if (poleAxis) { + blurUniforms["poleAxis"].value = poleAxis; + } + const { _lodMax } = this; + blurUniforms["dTheta"].value = radiansPerPixel; + blurUniforms["mipInt"].value = _lodMax - lodIn; + const outputSize = this._sizeLods[lodOut]; + const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN2 ? lodOut - _lodMax + LOD_MIN2 : 0); + const y = 4 * (this._cubeSize - outputSize); + _setViewport2(targetOut, x, y, 3 * outputSize, 2 * outputSize); + renderer2.setRenderTarget(targetOut); + renderer2.render(blurMesh, _flatCamera2); + } + } + function _createPlanes2(lodMax) { + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + let lod = lodMax; + const totalLods = lodMax - LOD_MIN2 + 1 + EXTRA_LOD_SIGMA2.length; + for (let i = 0;i < totalLods; i++) { + const sizeLod = Math.pow(2, lod); + sizeLods.push(sizeLod); + let sigma = 1 / sizeLod; + if (i > lodMax - LOD_MIN2) { + sigma = EXTRA_LOD_SIGMA2[i - lodMax + LOD_MIN2 - 1]; + } else if (i === 0) { + sigma = 0; + } + sigmas.push(sigma); + const texelSize = 1 / (sizeLod - 2); + const min = -texelSize; + const max = 1 + texelSize; + const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max]; + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + const position2 = new Float32Array(positionSize * vertices * cubeFaces); + const uv = new Float32Array(uvSize * vertices * cubeFaces); + const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces); + for (let face = 0;face < cubeFaces; face++) { + const x = face % 3 * 2 / 3 - 1; + const y = face > 2 ? 0 : -1; + const coordinates = [ + x, + y, + 0, + x + 2 / 3, + y, + 0, + x + 2 / 3, + y + 1, + 0, + x, + y, + 0, + x + 2 / 3, + y + 1, + 0, + x, + y + 1, + 0 + ]; + position2.set(coordinates, positionSize * vertices * face); + uv.set(uv1, uvSize * vertices * face); + const fill3 = [face, face, face, face, face, face]; + faceIndex.set(fill3, faceIndexSize * vertices * face); + } + const planes = new BufferGeometry2; + planes.setAttribute("position", new BufferAttribute2(position2, positionSize)); + planes.setAttribute("uv", new BufferAttribute2(uv, uvSize)); + planes.setAttribute("faceIndex", new BufferAttribute2(faceIndex, faceIndexSize)); + lodPlanes.push(planes); + if (lod > LOD_MIN2) { + lod--; + } + } + return { lodPlanes, sizeLods, sigmas }; + } + function _createRenderTarget2(width2, height2, params) { + const cubeUVRenderTarget = new WebGLRenderTarget2(width2, height2, params); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping2; + cubeUVRenderTarget.texture.name = "PMREM.cubeUv"; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + } + function _setViewport2(target, x, y, width2, height2) { + target.viewport.set(x, y, width2, height2); + target.scissor.set(x, y, width2, height2); + } + function _getBlurShader2(lodMax, width2, height2) { + const weights = new Float32Array(MAX_SAMPLES2); + const poleAxis = new Vector32(0, 1, 0); + const shaderMaterial = new ShaderMaterial2({ + name: "SphericalGaussianBlur", + defines: { + n: MAX_SAMPLES2, + CUBEUV_TEXEL_WIDTH: 1 / width2, + CUBEUV_TEXEL_HEIGHT: 1 / height2, + CUBEUV_MAX_MIP: `${lodMax}.0` + }, + uniforms: { + envMap: { value: null }, + samples: { value: 1 }, + weights: { value: weights }, + latitudinal: { value: false }, + dTheta: { value: 0 }, + mipInt: { value: 0 }, + poleAxis: { value: poleAxis } + }, + vertexShader: _getCommonVertexShader2(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `, + blending: NoBlending2, + depthTest: false, + depthWrite: false + }); + return shaderMaterial; + } + function _getEquirectMaterial2() { + return new ShaderMaterial2({ + name: "EquirectangularToCubeUV", + uniforms: { + envMap: { value: null } + }, + vertexShader: _getCommonVertexShader2(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `, + blending: NoBlending2, + depthTest: false, + depthWrite: false + }); + } + function _getCubemapMaterial2() { + return new ShaderMaterial2({ + name: "CubemapToCubeUV", + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 } + }, + vertexShader: _getCommonVertexShader2(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `, + blending: NoBlending2, + depthTest: false, + depthWrite: false + }); + } + function _getCommonVertexShader2() { + return ` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `; + } + function WebGLCubeUVMaps2(renderer2) { + let cubeUVmaps = new WeakMap; + let pmremGenerator = null; + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + const isEquirectMap = mapping === EquirectangularReflectionMapping2 || mapping === EquirectangularRefractionMapping2; + const isCubeMap = mapping === CubeReflectionMapping2 || mapping === CubeRefractionMapping2; + if (isEquirectMap || isCubeMap) { + let renderTarget = cubeUVmaps.get(texture); + const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0; + if (texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion) { + if (pmremGenerator === null) + pmremGenerator = new PMREMGenerator2(renderer2); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + return renderTarget.texture; + } else { + if (renderTarget !== undefined) { + return renderTarget.texture; + } else { + const image = texture.image; + if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) { + if (pmremGenerator === null) + pmremGenerator = new PMREMGenerator2(renderer2); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return renderTarget.texture; + } else { + return null; + } + } + } + } + } + return texture; + } + function isCubeTextureComplete(image) { + let count = 0; + const length2 = 6; + for (let i = 0;i < length2; i++) { + if (image[i] !== undefined) + count++; + } + return count === length2; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemapUV = cubeUVmaps.get(texture); + if (cubemapUV !== undefined) { + cubeUVmaps.delete(texture); + cubemapUV.dispose(); + } + } + function dispose() { + cubeUVmaps = new WeakMap; + if (pmremGenerator !== null) { + pmremGenerator.dispose(); + pmremGenerator = null; + } + } + return { + get, + dispose + }; + } + function WebGLExtensions2(gl) { + const extensions = {}; + function getExtension(name2) { + if (extensions[name2] !== undefined) { + return extensions[name2]; + } + let extension; + switch (name2) { + case "WEBGL_depth_texture": + extension = gl.getExtension("WEBGL_depth_texture") || gl.getExtension("MOZ_WEBGL_depth_texture") || gl.getExtension("WEBKIT_WEBGL_depth_texture"); + break; + case "EXT_texture_filter_anisotropic": + extension = gl.getExtension("EXT_texture_filter_anisotropic") || gl.getExtension("MOZ_EXT_texture_filter_anisotropic") || gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic"); + break; + case "WEBGL_compressed_texture_s3tc": + extension = gl.getExtension("WEBGL_compressed_texture_s3tc") || gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"); + break; + case "WEBGL_compressed_texture_pvrtc": + extension = gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"); + break; + default: + extension = gl.getExtension(name2); + } + extensions[name2] = extension; + return extension; + } + return { + has: function(name2) { + return getExtension(name2) !== null; + }, + init: function() { + getExtension("EXT_color_buffer_float"); + getExtension("WEBGL_clip_cull_distance"); + getExtension("OES_texture_float_linear"); + getExtension("EXT_color_buffer_half_float"); + getExtension("WEBGL_multisampled_render_to_texture"); + getExtension("WEBGL_render_shared_exponent"); + }, + get: function(name2) { + const extension = getExtension(name2); + if (extension === null) { + warnOnce2("THREE.WebGLRenderer: " + name2 + " extension not supported."); + } + return extension; + } + }; + } + function WebGLGeometries2(gl, attributes, info, bindingStates) { + const geometries = {}; + const wireframeAttributes = new WeakMap; + function onGeometryDispose(event) { + const geometry = event.target; + if (geometry.index !== null) { + attributes.remove(geometry.index); + } + for (const name2 in geometry.attributes) { + attributes.remove(geometry.attributes[name2]); + } + geometry.removeEventListener("dispose", onGeometryDispose); + delete geometries[geometry.id]; + const attribute = wireframeAttributes.get(geometry); + if (attribute) { + attributes.remove(attribute); + wireframeAttributes.delete(geometry); + } + bindingStates.releaseStatesOfGeometry(geometry); + if (geometry.isInstancedBufferGeometry === true) { + delete geometry._maxInstanceCount; + } + info.memory.geometries--; + } + function get(object, geometry) { + if (geometries[geometry.id] === true) + return geometry; + geometry.addEventListener("dispose", onGeometryDispose); + geometries[geometry.id] = true; + info.memory.geometries++; + return geometry; + } + function update(geometry) { + const geometryAttributes = geometry.attributes; + for (const name2 in geometryAttributes) { + attributes.update(geometryAttributes[name2], gl.ARRAY_BUFFER); + } + } + function updateWireframeAttribute(geometry) { + const indices = []; + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + if (geometryIndex !== null) { + const array = geometryIndex.array; + version = geometryIndex.version; + for (let i = 0, l = array.length;i < l; i += 3) { + const a = array[i + 0]; + const b = array[i + 1]; + const c = array[i + 2]; + indices.push(a, b, b, c, c, a); + } + } else if (geometryPosition !== undefined) { + const array = geometryPosition.array; + version = geometryPosition.version; + for (let i = 0, l = array.length / 3 - 1;i < l; i += 3) { + const a = i + 0; + const b = i + 1; + const c = i + 2; + indices.push(a, b, b, c, c, a); + } + } else { + return; + } + const attribute = new ((arrayNeedsUint322(indices)) ? Uint32BufferAttribute2 : Uint16BufferAttribute2)(indices, 1); + attribute.version = version; + const previousAttribute = wireframeAttributes.get(geometry); + if (previousAttribute) + attributes.remove(previousAttribute); + wireframeAttributes.set(geometry, attribute); + } + function getWireframeAttribute(geometry) { + const currentAttribute = wireframeAttributes.get(geometry); + if (currentAttribute) { + const geometryIndex = geometry.index; + if (geometryIndex !== null) { + if (currentAttribute.version < geometryIndex.version) { + updateWireframeAttribute(geometry); + } + } + } else { + updateWireframeAttribute(geometry); + } + return wireframeAttributes.get(geometry); + } + return { + get, + update, + getWireframeAttribute + }; + } + function WebGLIndexedBufferRenderer2(gl, extensions, info) { + let mode; + function setMode(value2) { + mode = value2; + } + let type, bytesPerElement; + function setIndex(value2) { + type = value2.type; + bytesPerElement = value2.bytesPerElement; + } + function render(start, count) { + gl.drawElements(mode, count, type, start * bytesPerElement); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) + return; + gl.drawElementsInstanced(mode, count, type, start * bytesPerElement, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawElementsWEBGL(mode, counts, 0, type, starts, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0;i < starts.length; i++) { + renderInstances(starts[i] / bytesPerElement, counts[i], primcount[i]); + } + } else { + extension.multiDrawElementsInstancedWEBGL(mode, counts, 0, type, starts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i] * primcount[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; + } + function WebGLInfo2(gl) { + const memory = { + geometries: 0, + textures: 0 + }; + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + function update(count, mode, instanceCount) { + render.calls++; + switch (mode) { + case gl.TRIANGLES: + render.triangles += instanceCount * (count / 3); + break; + case gl.LINES: + render.lines += instanceCount * (count / 2); + break; + case gl.LINE_STRIP: + render.lines += instanceCount * (count - 1); + break; + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + case gl.POINTS: + render.points += instanceCount * count; + break; + default: + console.error("THREE.WebGLInfo: Unknown draw mode:", mode); + break; + } + } + function reset() { + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + } + return { + memory, + render, + programs: null, + autoReset: true, + reset, + update + }; + } + function WebGLMorphtargets2(gl, capabilities, textures) { + const morphTextures = new WeakMap; + const morph = new Vector42; + function update(object, geometry, program) { + const objectInfluences = object.morphTargetInfluences; + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + let entry = morphTextures.get(geometry); + if (entry === undefined || entry.count !== morphTargetsCount) { + let disposeTexture = function() { + texture.dispose(); + morphTextures.delete(geometry); + geometry.removeEventListener("dispose", disposeTexture); + }; + if (entry !== undefined) + entry.texture.dispose(); + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + let vertexDataCount = 0; + if (hasMorphPosition === true) + vertexDataCount = 1; + if (hasMorphNormals === true) + vertexDataCount = 2; + if (hasMorphColors === true) + vertexDataCount = 3; + let width2 = geometry.attributes.position.count * vertexDataCount; + let height2 = 1; + if (width2 > capabilities.maxTextureSize) { + height2 = Math.ceil(width2 / capabilities.maxTextureSize); + width2 = capabilities.maxTextureSize; + } + const buffer = new Float32Array(width2 * height2 * 4 * morphTargetsCount); + const texture = new DataArrayTexture2(buffer, width2, height2, morphTargetsCount); + texture.type = FloatType2; + texture.needsUpdate = true; + const vertexDataStride = vertexDataCount * 4; + for (let i = 0;i < morphTargetsCount; i++) { + const morphTarget = morphTargets[i]; + const morphNormal = morphNormals[i]; + const morphColor = morphColors[i]; + const offset = width2 * height2 * 4 * i; + for (let j = 0;j < morphTarget.count; j++) { + const stride = j * vertexDataStride; + if (hasMorphPosition === true) { + morph.fromBufferAttribute(morphTarget, j); + buffer[offset + stride + 0] = morph.x; + buffer[offset + stride + 1] = morph.y; + buffer[offset + stride + 2] = morph.z; + buffer[offset + stride + 3] = 0; + } + if (hasMorphNormals === true) { + morph.fromBufferAttribute(morphNormal, j); + buffer[offset + stride + 4] = morph.x; + buffer[offset + stride + 5] = morph.y; + buffer[offset + stride + 6] = morph.z; + buffer[offset + stride + 7] = 0; + } + if (hasMorphColors === true) { + morph.fromBufferAttribute(morphColor, j); + buffer[offset + stride + 8] = morph.x; + buffer[offset + stride + 9] = morph.y; + buffer[offset + stride + 10] = morph.z; + buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1; + } + } + } + entry = { + count: morphTargetsCount, + texture, + size: new Vector22(width2, height2) + }; + morphTextures.set(geometry, entry); + geometry.addEventListener("dispose", disposeTexture); + } + if (object.isInstancedMesh === true && object.morphTexture !== null) { + program.getUniforms().setValue(gl, "morphTexture", object.morphTexture, textures); + } else { + let morphInfluencesSum = 0; + for (let i = 0;i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence); + program.getUniforms().setValue(gl, "morphTargetInfluences", objectInfluences); + } + program.getUniforms().setValue(gl, "morphTargetsTexture", entry.texture, textures); + program.getUniforms().setValue(gl, "morphTargetsTextureSize", entry.size); + } + return { + update + }; + } + function WebGLObjects2(gl, geometries, attributes, info) { + let updateMap = new WeakMap; + function update(object) { + const frame = info.render.frame; + const geometry = object.geometry; + const buffergeometry = geometries.get(object, geometry); + if (updateMap.get(buffergeometry) !== frame) { + geometries.update(buffergeometry); + updateMap.set(buffergeometry, frame); + } + if (object.isInstancedMesh) { + if (object.hasEventListener("dispose", onInstancedMeshDispose) === false) { + object.addEventListener("dispose", onInstancedMeshDispose); + } + if (updateMap.get(object) !== frame) { + attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER); + if (object.instanceColor !== null) { + attributes.update(object.instanceColor, gl.ARRAY_BUFFER); + } + updateMap.set(object, frame); + } + } + if (object.isSkinnedMesh) { + const skeleton = object.skeleton; + if (updateMap.get(skeleton) !== frame) { + skeleton.update(); + updateMap.set(skeleton, frame); + } + } + return buffergeometry; + } + function dispose() { + updateMap = new WeakMap; + } + function onInstancedMeshDispose(event) { + const instancedMesh = event.target; + instancedMesh.removeEventListener("dispose", onInstancedMeshDispose); + attributes.remove(instancedMesh.instanceMatrix); + if (instancedMesh.instanceColor !== null) + attributes.remove(instancedMesh.instanceColor); + } + return { + update, + dispose + }; + } + var emptyTexture2 = /* @__PURE__ */ new Texture2; + var emptyShadowTexture2 = /* @__PURE__ */ new DepthTexture2(1, 1); + var emptyArrayTexture2 = /* @__PURE__ */ new DataArrayTexture2; + var empty3dTexture2 = /* @__PURE__ */ new Data3DTexture2; + var emptyCubeTexture2 = /* @__PURE__ */ new CubeTexture2; + var arrayCacheF322 = []; + var arrayCacheI322 = []; + var mat4array2 = new Float32Array(16); + var mat3array2 = new Float32Array(9); + var mat2array2 = new Float32Array(4); + function flatten3(array, nBlocks, blockSize) { + const firstElem = array[0]; + if (firstElem <= 0 || firstElem > 0) + return array; + const n = nBlocks * blockSize; + let r = arrayCacheF322[n]; + if (r === undefined) { + r = new Float32Array(n); + arrayCacheF322[n] = r; + } + if (nBlocks !== 0) { + firstElem.toArray(r, 0); + for (let i = 1, offset = 0;i !== nBlocks; ++i) { + offset += blockSize; + array[i].toArray(r, offset); + } + } + return r; + } + function arraysEqual2(a, b) { + if (a.length !== b.length) + return false; + for (let i = 0, l = a.length;i < l; i++) { + if (a[i] !== b[i]) + return false; + } + return true; + } + function copyArray2(a, b) { + for (let i = 0, l = b.length;i < l; i++) { + a[i] = b[i]; + } + } + function allocTexUnits2(textures, n) { + let r = arrayCacheI322[n]; + if (r === undefined) { + r = new Int32Array(n); + arrayCacheI322[n] = r; + } + for (let i = 0;i !== n; ++i) { + r[i] = textures.allocateTextureUnit(); + } + return r; + } + function setValueV1f2(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1f(this.addr, v); + cache[0] = v; + } + function setValueV2f2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2f(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual2(cache, v)) + return; + gl.uniform2fv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV3f2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3f(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else if (v.r !== undefined) { + if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) { + gl.uniform3f(this.addr, v.r, v.g, v.b); + cache[0] = v.r; + cache[1] = v.g; + cache[2] = v.b; + } + } else { + if (arraysEqual2(cache, v)) + return; + gl.uniform3fv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV4f2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4f(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual2(cache, v)) + return; + gl.uniform4fv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueM22(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual2(cache, v)) + return; + gl.uniformMatrix2fv(this.addr, false, v); + copyArray2(cache, v); + } else { + if (arraysEqual2(cache, elements)) + return; + mat2array2.set(elements); + gl.uniformMatrix2fv(this.addr, false, mat2array2); + copyArray2(cache, elements); + } + } + function setValueM32(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual2(cache, v)) + return; + gl.uniformMatrix3fv(this.addr, false, v); + copyArray2(cache, v); + } else { + if (arraysEqual2(cache, elements)) + return; + mat3array2.set(elements); + gl.uniformMatrix3fv(this.addr, false, mat3array2); + copyArray2(cache, elements); + } + } + function setValueM42(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual2(cache, v)) + return; + gl.uniformMatrix4fv(this.addr, false, v); + copyArray2(cache, v); + } else { + if (arraysEqual2(cache, elements)) + return; + mat4array2.set(elements); + gl.uniformMatrix4fv(this.addr, false, mat4array2); + copyArray2(cache, elements); + } + } + function setValueV1i2(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1i(this.addr, v); + cache[0] = v; + } + function setValueV2i2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2i(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual2(cache, v)) + return; + gl.uniform2iv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV3i2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3i(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual2(cache, v)) + return; + gl.uniform3iv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV4i2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4i(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual2(cache, v)) + return; + gl.uniform4iv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV1ui2(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1ui(this.addr, v); + cache[0] = v; + } + function setValueV2ui2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2ui(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual2(cache, v)) + return; + gl.uniform2uiv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV3ui2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3ui(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual2(cache, v)) + return; + gl.uniform3uiv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV4ui2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4ui(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual2(cache, v)) + return; + gl.uniform4uiv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueT12(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + let emptyTexture2D; + if (this.type === gl.SAMPLER_2D_SHADOW) { + emptyShadowTexture2.compareFunction = LessEqualCompare2; + emptyTexture2D = emptyShadowTexture2; + } else { + emptyTexture2D = emptyTexture2; + } + textures.setTexture2D(v || emptyTexture2D, unit); + } + function setValueT3D12(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture3D(v || empty3dTexture2, unit); + } + function setValueT62(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTextureCube(v || emptyCubeTexture2, unit); + } + function setValueT2DArray12(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture2DArray(v || emptyArrayTexture2, unit); + } + function getSingularSetter2(type) { + switch (type) { + case 5126: + return setValueV1f2; + case 35664: + return setValueV2f2; + case 35665: + return setValueV3f2; + case 35666: + return setValueV4f2; + case 35674: + return setValueM22; + case 35675: + return setValueM32; + case 35676: + return setValueM42; + case 5124: + case 35670: + return setValueV1i2; + case 35667: + case 35671: + return setValueV2i2; + case 35668: + case 35672: + return setValueV3i2; + case 35669: + case 35673: + return setValueV4i2; + case 5125: + return setValueV1ui2; + case 36294: + return setValueV2ui2; + case 36295: + return setValueV3ui2; + case 36296: + return setValueV4ui2; + case 35678: + case 36198: + case 36298: + case 36306: + case 35682: + return setValueT12; + case 35679: + case 36299: + case 36307: + return setValueT3D12; + case 35680: + case 36300: + case 36308: + case 36293: + return setValueT62; + case 36289: + case 36303: + case 36311: + case 36292: + return setValueT2DArray12; + } + } + function setValueV1fArray2(gl, v) { + gl.uniform1fv(this.addr, v); + } + function setValueV2fArray2(gl, v) { + const data2 = flatten3(v, this.size, 2); + gl.uniform2fv(this.addr, data2); + } + function setValueV3fArray2(gl, v) { + const data2 = flatten3(v, this.size, 3); + gl.uniform3fv(this.addr, data2); + } + function setValueV4fArray2(gl, v) { + const data2 = flatten3(v, this.size, 4); + gl.uniform4fv(this.addr, data2); + } + function setValueM2Array2(gl, v) { + const data2 = flatten3(v, this.size, 4); + gl.uniformMatrix2fv(this.addr, false, data2); + } + function setValueM3Array2(gl, v) { + const data2 = flatten3(v, this.size, 9); + gl.uniformMatrix3fv(this.addr, false, data2); + } + function setValueM4Array2(gl, v) { + const data2 = flatten3(v, this.size, 16); + gl.uniformMatrix4fv(this.addr, false, data2); + } + function setValueV1iArray2(gl, v) { + gl.uniform1iv(this.addr, v); + } + function setValueV2iArray2(gl, v) { + gl.uniform2iv(this.addr, v); + } + function setValueV3iArray2(gl, v) { + gl.uniform3iv(this.addr, v); + } + function setValueV4iArray2(gl, v) { + gl.uniform4iv(this.addr, v); + } + function setValueV1uiArray2(gl, v) { + gl.uniform1uiv(this.addr, v); + } + function setValueV2uiArray2(gl, v) { + gl.uniform2uiv(this.addr, v); + } + function setValueV3uiArray2(gl, v) { + gl.uniform3uiv(this.addr, v); + } + function setValueV4uiArray2(gl, v) { + gl.uniform4uiv(this.addr, v); + } + function setValueT1Array2(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits2(textures, n); + if (!arraysEqual2(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray2(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTexture2D(v[i] || emptyTexture2, units[i]); + } + } + function setValueT3DArray2(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits2(textures, n); + if (!arraysEqual2(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray2(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTexture3D(v[i] || empty3dTexture2, units[i]); + } + } + function setValueT6Array2(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits2(textures, n); + if (!arraysEqual2(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray2(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTextureCube(v[i] || emptyCubeTexture2, units[i]); + } + } + function setValueT2DArrayArray2(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits2(textures, n); + if (!arraysEqual2(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray2(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTexture2DArray(v[i] || emptyArrayTexture2, units[i]); + } + } + function getPureArraySetter2(type) { + switch (type) { + case 5126: + return setValueV1fArray2; + case 35664: + return setValueV2fArray2; + case 35665: + return setValueV3fArray2; + case 35666: + return setValueV4fArray2; + case 35674: + return setValueM2Array2; + case 35675: + return setValueM3Array2; + case 35676: + return setValueM4Array2; + case 5124: + case 35670: + return setValueV1iArray2; + case 35667: + case 35671: + return setValueV2iArray2; + case 35668: + case 35672: + return setValueV3iArray2; + case 35669: + case 35673: + return setValueV4iArray2; + case 5125: + return setValueV1uiArray2; + case 36294: + return setValueV2uiArray2; + case 36295: + return setValueV3uiArray2; + case 36296: + return setValueV4uiArray2; + case 35678: + case 36198: + case 36298: + case 36306: + case 35682: + return setValueT1Array2; + case 35679: + case 36299: + case 36307: + return setValueT3DArray2; + case 35680: + case 36300: + case 36308: + case 36293: + return setValueT6Array2; + case 36289: + case 36303: + case 36311: + case 36292: + return setValueT2DArrayArray2; + } + } + + class SingleUniform2 { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.setValue = getSingularSetter2(activeInfo.type); + } + } + + class PureArrayUniform2 { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.size = activeInfo.size; + this.setValue = getPureArraySetter2(activeInfo.type); + } + } + + class StructuredUniform2 { + constructor(id) { + this.id = id; + this.seq = []; + this.map = {}; + } + setValue(gl, value2, textures) { + const seq = this.seq; + for (let i = 0, n = seq.length;i !== n; ++i) { + const u = seq[i]; + u.setValue(gl, value2[u.id], textures); + } + } + } + var RePathPart2 = /(\w+)(\])?(\[|\.)?/g; + function addUniform2(container, uniformObject) { + container.seq.push(uniformObject); + container.map[uniformObject.id] = uniformObject; + } + function parseUniform2(activeInfo, addr, container) { + const path = activeInfo.name, pathLength = path.length; + RePathPart2.lastIndex = 0; + while (true) { + const match = RePathPart2.exec(path), matchEnd = RePathPart2.lastIndex; + let id = match[1]; + const idIsIndex = match[2] === "]", subscript = match[3]; + if (idIsIndex) + id = id | 0; + if (subscript === undefined || subscript === "[" && matchEnd + 2 === pathLength) { + addUniform2(container, subscript === undefined ? new SingleUniform2(id, activeInfo, addr) : new PureArrayUniform2(id, activeInfo, addr)); + break; + } else { + const map2 = container.map; + let next = map2[id]; + if (next === undefined) { + next = new StructuredUniform2(id); + addUniform2(container, next); + } + container = next; + } + } + } + + class WebGLUniforms2 { + constructor(gl, program) { + this.seq = []; + this.map = {}; + const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (let i = 0;i < n; ++i) { + const info = gl.getActiveUniform(program, i), addr = gl.getUniformLocation(program, info.name); + parseUniform2(info, addr, this); + } + } + setValue(gl, name2, value2, textures) { + const u = this.map[name2]; + if (u !== undefined) + u.setValue(gl, value2, textures); + } + setOptional(gl, object, name2) { + const v = object[name2]; + if (v !== undefined) + this.setValue(gl, name2, v); + } + static upload(gl, seq, values2, textures) { + for (let i = 0, n = seq.length;i !== n; ++i) { + const u = seq[i], v = values2[u.id]; + if (v.needsUpdate !== false) { + u.setValue(gl, v.value, textures); + } + } + } + static seqWithValue(seq, values2) { + const r = []; + for (let i = 0, n = seq.length;i !== n; ++i) { + const u = seq[i]; + if (u.id in values2) + r.push(u); + } + return r; + } + } + function WebGLShader2(gl, type, string) { + const shader = gl.createShader(type); + gl.shaderSource(shader, string); + gl.compileShader(shader); + return shader; + } + var COMPLETION_STATUS_KHR2 = 37297; + var programIdCount2 = 0; + function handleSource2(string, errorLine) { + const lines = string.split(` +`); + const lines2 = []; + const from = Math.max(errorLine - 6, 0); + const to = Math.min(errorLine + 6, lines.length); + for (let i = from;i < to; i++) { + const line = i + 1; + lines2.push(`${line === errorLine ? ">" : " "} ${line}: ${lines[i]}`); + } + return lines2.join(` +`); + } + var _m02 = /* @__PURE__ */ new Matrix32; + function getEncodingComponents2(colorSpace) { + ColorManagement2._getMatrix(_m02, ColorManagement2.workingColorSpace, colorSpace); + const encodingMatrix = `mat3( ${_m02.elements.map((v) => v.toFixed(4))} )`; + switch (ColorManagement2.getTransfer(colorSpace)) { + case LinearTransfer2: + return [encodingMatrix, "LinearTransferOETF"]; + case SRGBTransfer2: + return [encodingMatrix, "sRGBTransferOETF"]; + default: + console.warn("THREE.WebGLProgram: Unsupported color space: ", colorSpace); + return [encodingMatrix, "LinearTransferOETF"]; + } + } + function getShaderErrors2(gl, shader, type) { + const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS); + const errors = gl.getShaderInfoLog(shader).trim(); + if (status && errors === "") + return ""; + const errorMatches = /ERROR: 0:(\d+)/.exec(errors); + if (errorMatches) { + const errorLine = parseInt(errorMatches[1]); + return type.toUpperCase() + ` + +` + errors + ` + +` + handleSource2(gl.getShaderSource(shader), errorLine); + } else { + return errors; + } + } + function getTexelEncodingFunction2(functionName, colorSpace) { + const components = getEncodingComponents2(colorSpace); + return [ + `vec4 ${functionName}( vec4 value ) {`, + ` return ${components[1]}( vec4( value.rgb * ${components[0]}, value.a ) );`, + "}" + ].join(` +`); + } + function getToneMappingFunction2(functionName, toneMapping) { + let toneMappingName; + switch (toneMapping) { + case LinearToneMapping2: + toneMappingName = "Linear"; + break; + case ReinhardToneMapping2: + toneMappingName = "Reinhard"; + break; + case CineonToneMapping2: + toneMappingName = "Cineon"; + break; + case ACESFilmicToneMapping2: + toneMappingName = "ACESFilmic"; + break; + case AgXToneMapping2: + toneMappingName = "AgX"; + break; + case NeutralToneMapping2: + toneMappingName = "Neutral"; + break; + case CustomToneMapping2: + toneMappingName = "Custom"; + break; + default: + console.warn("THREE.WebGLProgram: Unsupported toneMapping:", toneMapping); + toneMappingName = "Linear"; + } + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; + } + var _v03 = /* @__PURE__ */ new Vector32; + function getLuminanceFunction2() { + ColorManagement2.getLuminanceCoefficients(_v03); + const r = _v03.x.toFixed(4); + const g = _v03.y.toFixed(4); + const b = _v03.z.toFixed(4); + return [ + "float luminance( const in vec3 rgb ) {", + ` const vec3 weights = vec3( ${r}, ${g}, ${b} );`, + "\treturn dot( weights, rgb );", + "}" + ].join(` +`); + } + function generateVertexExtensions2(parameters) { + const chunks = [ + parameters.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "", + parameters.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : "" + ]; + return chunks.filter(filterEmptyLine2).join(` +`); + } + function generateDefines2(defines) { + const chunks = []; + for (const name2 in defines) { + const value2 = defines[name2]; + if (value2 === false) + continue; + chunks.push("#define " + name2 + " " + value2); + } + return chunks.join(` +`); + } + function fetchAttributeLocations2(gl, program) { + const attributes = {}; + const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (let i = 0;i < n; i++) { + const info = gl.getActiveAttrib(program, i); + const name2 = info.name; + let locationSize = 1; + if (info.type === gl.FLOAT_MAT2) + locationSize = 2; + if (info.type === gl.FLOAT_MAT3) + locationSize = 3; + if (info.type === gl.FLOAT_MAT4) + locationSize = 4; + attributes[name2] = { + type: info.type, + location: gl.getAttribLocation(program, name2), + locationSize + }; + } + return attributes; + } + function filterEmptyLine2(string) { + return string !== ""; + } + function replaceLightNums2(string, parameters) { + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows); + } + function replaceClippingPlaneNums2(string, parameters) { + return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection); + } + var includePattern2 = /^[ \t]*#include +<([\w\d./]+)>/gm; + function resolveIncludes2(string) { + return string.replace(includePattern2, includeReplacer2); + } + var shaderChunkMap2 = new Map; + function includeReplacer2(match, include) { + let string = ShaderChunk2[include]; + if (string === undefined) { + const newInclude = shaderChunkMap2.get(include); + if (newInclude !== undefined) { + string = ShaderChunk2[newInclude]; + console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude); + } else { + throw new Error("Can not resolve #include <" + include + ">"); + } + } + return resolveIncludes2(string); + } + var unrollLoopPattern2 = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + function unrollLoops2(string) { + return string.replace(unrollLoopPattern2, loopReplacer2); + } + function loopReplacer2(match, start, end, snippet) { + let string = ""; + for (let i = parseInt(start);i < parseInt(end); i++) { + string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i + " ]").replace(/UNROLLED_LOOP_INDEX/g, i); + } + return string; + } + function generatePrecision2(parameters) { + let precisionstring = `precision ${parameters.precision} float; + precision ${parameters.precision} int; + precision ${parameters.precision} sampler2D; + precision ${parameters.precision} samplerCube; + precision ${parameters.precision} sampler3D; + precision ${parameters.precision} sampler2DArray; + precision ${parameters.precision} sampler2DShadow; + precision ${parameters.precision} samplerCubeShadow; + precision ${parameters.precision} sampler2DArrayShadow; + precision ${parameters.precision} isampler2D; + precision ${parameters.precision} isampler3D; + precision ${parameters.precision} isamplerCube; + precision ${parameters.precision} isampler2DArray; + precision ${parameters.precision} usampler2D; + precision ${parameters.precision} usampler3D; + precision ${parameters.precision} usamplerCube; + precision ${parameters.precision} usampler2DArray; + `; + if (parameters.precision === "highp") { + precisionstring += ` +#define HIGH_PRECISION`; + } else if (parameters.precision === "mediump") { + precisionstring += ` +#define MEDIUM_PRECISION`; + } else if (parameters.precision === "lowp") { + precisionstring += ` +#define LOW_PRECISION`; + } + return precisionstring; + } + function generateShadowMapTypeDefine2(parameters) { + let shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; + if (parameters.shadowMapType === PCFShadowMap2) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; + } else if (parameters.shadowMapType === PCFSoftShadowMap2) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; + } else if (parameters.shadowMapType === VSMShadowMap2) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_VSM"; + } + return shadowMapTypeDefine; + } + function generateEnvMapTypeDefine2(parameters) { + let envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeReflectionMapping2: + case CubeRefractionMapping2: + envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + break; + case CubeUVReflectionMapping2: + envMapTypeDefine = "ENVMAP_TYPE_CUBE_UV"; + break; + } + } + return envMapTypeDefine; + } + function generateEnvMapModeDefine2(parameters) { + let envMapModeDefine = "ENVMAP_MODE_REFLECTION"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeRefractionMapping2: + envMapModeDefine = "ENVMAP_MODE_REFRACTION"; + break; + } + } + return envMapModeDefine; + } + function generateEnvMapBlendingDefine2(parameters) { + let envMapBlendingDefine = "ENVMAP_BLENDING_NONE"; + if (parameters.envMap) { + switch (parameters.combine) { + case MultiplyOperation2: + envMapBlendingDefine = "ENVMAP_BLENDING_MULTIPLY"; + break; + case MixOperation2: + envMapBlendingDefine = "ENVMAP_BLENDING_MIX"; + break; + case AddOperation2: + envMapBlendingDefine = "ENVMAP_BLENDING_ADD"; + break; + } + } + return envMapBlendingDefine; + } + function generateCubeUVSize2(parameters) { + const imageHeight = parameters.envMapCubeUVHeight; + if (imageHeight === null) + return null; + const maxMip = Math.log2(imageHeight) - 2; + const texelHeight = 1 / imageHeight; + const texelWidth = 1 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16)); + return { texelWidth, texelHeight, maxMip }; + } + function WebGLProgram2(renderer2, cacheKey, parameters, bindingStates) { + const gl = renderer2.getContext(); + const defines = parameters.defines; + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + const shadowMapTypeDefine = generateShadowMapTypeDefine2(parameters); + const envMapTypeDefine = generateEnvMapTypeDefine2(parameters); + const envMapModeDefine = generateEnvMapModeDefine2(parameters); + const envMapBlendingDefine = generateEnvMapBlendingDefine2(parameters); + const envMapCubeUVSize = generateCubeUVSize2(parameters); + const customVertexExtensions = generateVertexExtensions2(parameters); + const customDefines = generateDefines2(defines); + const program = gl.createProgram(); + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? "#version " + parameters.glslVersion + ` +` : ""; + if (parameters.isRawShaderMaterial) { + prefixVertex = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine2).join(` +`); + if (prefixVertex.length > 0) { + prefixVertex += ` +`; + } + prefixFragment = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine2).join(` +`); + if (prefixFragment.length > 0) { + prefixFragment += ` +`; + } + } else { + prefixVertex = [ + generatePrecision2(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "", + parameters.batching ? "#define USE_BATCHING" : "", + parameters.batchingColor ? "#define USE_BATCHING_COLOR" : "", + parameters.instancing ? "#define USE_INSTANCING" : "", + parameters.instancingColor ? "#define USE_INSTANCING_COLOR" : "", + parameters.instancingMorph ? "#define USE_INSTANCING_MORPH" : "", + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.displacementMap ? "#define USE_DISPLACEMENTMAP" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.mapUv ? "#define MAP_UV " + parameters.mapUv : "", + parameters.alphaMapUv ? "#define ALPHAMAP_UV " + parameters.alphaMapUv : "", + parameters.lightMapUv ? "#define LIGHTMAP_UV " + parameters.lightMapUv : "", + parameters.aoMapUv ? "#define AOMAP_UV " + parameters.aoMapUv : "", + parameters.emissiveMapUv ? "#define EMISSIVEMAP_UV " + parameters.emissiveMapUv : "", + parameters.bumpMapUv ? "#define BUMPMAP_UV " + parameters.bumpMapUv : "", + parameters.normalMapUv ? "#define NORMALMAP_UV " + parameters.normalMapUv : "", + parameters.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + parameters.displacementMapUv : "", + parameters.metalnessMapUv ? "#define METALNESSMAP_UV " + parameters.metalnessMapUv : "", + parameters.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + parameters.roughnessMapUv : "", + parameters.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + parameters.anisotropyMapUv : "", + parameters.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + parameters.clearcoatMapUv : "", + parameters.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + parameters.clearcoatNormalMapUv : "", + parameters.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + parameters.clearcoatRoughnessMapUv : "", + parameters.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + parameters.iridescenceMapUv : "", + parameters.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + parameters.iridescenceThicknessMapUv : "", + parameters.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + parameters.sheenColorMapUv : "", + parameters.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + parameters.sheenRoughnessMapUv : "", + parameters.specularMapUv ? "#define SPECULARMAP_UV " + parameters.specularMapUv : "", + parameters.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + parameters.specularColorMapUv : "", + parameters.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + parameters.specularIntensityMapUv : "", + parameters.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + parameters.transmissionMapUv : "", + parameters.thicknessMapUv ? "#define THICKNESSMAP_UV " + parameters.thicknessMapUv : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.skinning ? "#define USE_SKINNING" : "", + parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", + parameters.morphNormals && parameters.flatShading === false ? "#define USE_MORPHNORMALS" : "", + parameters.morphColors ? "#define USE_MORPHCOLORS" : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + parameters.morphTextureStride : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + parameters.morphTargetsCount : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "", + "uniform mat4 modelMatrix;", + "uniform mat4 modelViewMatrix;", + "uniform mat4 projectionMatrix;", + "uniform mat4 viewMatrix;", + "uniform mat3 normalMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + "#ifdef USE_INSTANCING", + "\tattribute mat4 instanceMatrix;", + "#endif", + "#ifdef USE_INSTANCING_COLOR", + "\tattribute vec3 instanceColor;", + "#endif", + "#ifdef USE_INSTANCING_MORPH", + "\tuniform sampler2D morphTexture;", + "#endif", + "attribute vec3 position;", + "attribute vec3 normal;", + "attribute vec2 uv;", + "#ifdef USE_UV1", + "\tattribute vec2 uv1;", + "#endif", + "#ifdef USE_UV2", + "\tattribute vec2 uv2;", + "#endif", + "#ifdef USE_UV3", + "\tattribute vec2 uv3;", + "#endif", + "#ifdef USE_TANGENT", + "\tattribute vec4 tangent;", + "#endif", + "#if defined( USE_COLOR_ALPHA )", + "\tattribute vec4 color;", + "#elif defined( USE_COLOR )", + "\tattribute vec3 color;", + "#endif", + "#ifdef USE_SKINNING", + "\tattribute vec4 skinIndex;", + "\tattribute vec4 skinWeight;", + "#endif", + ` +` + ].filter(filterEmptyLine2).join(` +`); + prefixFragment = [ + generatePrecision2(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.matcap ? "#define USE_MATCAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapTypeDefine : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.envMap ? "#define " + envMapBlendingDefine : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_WIDTH " + envMapCubeUVSize.texelWidth : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_HEIGHT " + envMapCubeUVSize.texelHeight : "", + envMapCubeUVSize ? "#define CUBEUV_MAX_MIP " + envMapCubeUVSize.maxMip + ".0" : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoat ? "#define USE_CLEARCOAT" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.dispersion ? "#define USE_DISPERSION" : "", + parameters.iridescence ? "#define USE_IRIDESCENCE" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaTest ? "#define USE_ALPHATEST" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.sheen ? "#define USE_SHEEN" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.gradientMap ? "#define USE_GRADIENTMAP" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", + parameters.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "", + "uniform mat4 viewMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + parameters.toneMapping !== NoToneMapping2 ? "#define TONE_MAPPING" : "", + parameters.toneMapping !== NoToneMapping2 ? ShaderChunk2["tonemapping_pars_fragment"] : "", + parameters.toneMapping !== NoToneMapping2 ? getToneMappingFunction2("toneMapping", parameters.toneMapping) : "", + parameters.dithering ? "#define DITHERING" : "", + parameters.opaque ? "#define OPAQUE" : "", + ShaderChunk2["colorspace_pars_fragment"], + getTexelEncodingFunction2("linearToOutputTexel", parameters.outputColorSpace), + getLuminanceFunction2(), + parameters.useDepthPacking ? "#define DEPTH_PACKING " + parameters.depthPacking : "", + ` +` + ].filter(filterEmptyLine2).join(` +`); + } + vertexShader = resolveIncludes2(vertexShader); + vertexShader = replaceLightNums2(vertexShader, parameters); + vertexShader = replaceClippingPlaneNums2(vertexShader, parameters); + fragmentShader = resolveIncludes2(fragmentShader); + fragmentShader = replaceLightNums2(fragmentShader, parameters); + fragmentShader = replaceClippingPlaneNums2(fragmentShader, parameters); + vertexShader = unrollLoops2(vertexShader); + fragmentShader = unrollLoops2(fragmentShader); + if (parameters.isRawShaderMaterial !== true) { + versionString = `#version 300 es +`; + prefixVertex = [ + customVertexExtensions, + "#define attribute in", + "#define varying out", + "#define texture2D texture" + ].join(` +`) + ` +` + prefixVertex; + prefixFragment = [ + "#define varying in", + parameters.glslVersion === GLSL32 ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", + parameters.glslVersion === GLSL32 ? "" : "#define gl_FragColor pc_fragColor", + "#define gl_FragDepthEXT gl_FragDepth", + "#define texture2D texture", + "#define textureCube texture", + "#define texture2DProj textureProj", + "#define texture2DLodEXT textureLod", + "#define texture2DProjLodEXT textureProjLod", + "#define textureCubeLodEXT textureLod", + "#define texture2DGradEXT textureGrad", + "#define texture2DProjGradEXT textureProjGrad", + "#define textureCubeGradEXT textureGrad" + ].join(` +`) + ` +` + prefixFragment; + } + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + const glVertexShader = WebGLShader2(gl, gl.VERTEX_SHADER, vertexGlsl); + const glFragmentShader = WebGLShader2(gl, gl.FRAGMENT_SHADER, fragmentGlsl); + gl.attachShader(program, glVertexShader); + gl.attachShader(program, glFragmentShader); + if (parameters.index0AttributeName !== undefined) { + gl.bindAttribLocation(program, 0, parameters.index0AttributeName); + } else if (parameters.morphTargets === true) { + gl.bindAttribLocation(program, 0, "position"); + } + gl.linkProgram(program); + function onFirstUse(self2) { + if (renderer2.debug.checkShaderErrors) { + const programLog = gl.getProgramInfoLog(program).trim(); + const vertexLog = gl.getShaderInfoLog(glVertexShader).trim(); + const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim(); + let runnable = true; + let haveDiagnostics = true; + if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) { + runnable = false; + if (typeof renderer2.debug.onShaderError === "function") { + renderer2.debug.onShaderError(gl, program, glVertexShader, glFragmentShader); + } else { + const vertexErrors = getShaderErrors2(gl, glVertexShader, "vertex"); + const fragmentErrors = getShaderErrors2(gl, glFragmentShader, "fragment"); + console.error("THREE.WebGLProgram: Shader Error " + gl.getError() + " - " + "VALIDATE_STATUS " + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + ` + +` + "Material Name: " + self2.name + ` +` + "Material Type: " + self2.type + ` + +` + "Program Info Log: " + programLog + ` +` + vertexErrors + ` +` + fragmentErrors); + } + } else if (programLog !== "") { + console.warn("THREE.WebGLProgram: Program Info Log:", programLog); + } else if (vertexLog === "" || fragmentLog === "") { + haveDiagnostics = false; + } + if (haveDiagnostics) { + self2.diagnostics = { + runnable, + programLog, + vertexShader: { + log: vertexLog, + prefix: prefixVertex + }, + fragmentShader: { + log: fragmentLog, + prefix: prefixFragment + } + }; + } + } + gl.deleteShader(glVertexShader); + gl.deleteShader(glFragmentShader); + cachedUniforms = new WebGLUniforms2(gl, program); + cachedAttributes = fetchAttributeLocations2(gl, program); + } + let cachedUniforms; + this.getUniforms = function() { + if (cachedUniforms === undefined) { + onFirstUse(this); + } + return cachedUniforms; + }; + let cachedAttributes; + this.getAttributes = function() { + if (cachedAttributes === undefined) { + onFirstUse(this); + } + return cachedAttributes; + }; + let programReady = parameters.rendererExtensionParallelShaderCompile === false; + this.isReady = function() { + if (programReady === false) { + programReady = gl.getProgramParameter(program, COMPLETION_STATUS_KHR2); + } + return programReady; + }; + this.destroy = function() { + bindingStates.releaseStatesOfProgram(this); + gl.deleteProgram(program); + this.program = undefined; + }; + this.type = parameters.shaderType; + this.name = parameters.shaderName; + this.id = programIdCount2++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + return this; + } + var _id3 = 0; + + class WebGLShaderCache2 { + constructor() { + this.shaderCache = new Map; + this.materialCache = new Map; + } + update(material) { + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + const vertexShaderStage = this._getShaderStage(vertexShader); + const fragmentShaderStage = this._getShaderStage(fragmentShader); + const materialShaders = this._getShaderCacheForMaterial(material); + if (materialShaders.has(vertexShaderStage) === false) { + materialShaders.add(vertexShaderStage); + vertexShaderStage.usedTimes++; + } + if (materialShaders.has(fragmentShaderStage) === false) { + materialShaders.add(fragmentShaderStage); + fragmentShaderStage.usedTimes++; + } + return this; + } + remove(material) { + const materialShaders = this.materialCache.get(material); + for (const shaderStage of materialShaders) { + shaderStage.usedTimes--; + if (shaderStage.usedTimes === 0) + this.shaderCache.delete(shaderStage.code); + } + this.materialCache.delete(material); + return this; + } + getVertexShaderID(material) { + return this._getShaderStage(material.vertexShader).id; + } + getFragmentShaderID(material) { + return this._getShaderStage(material.fragmentShader).id; + } + dispose() { + this.shaderCache.clear(); + this.materialCache.clear(); + } + _getShaderCacheForMaterial(material) { + const cache = this.materialCache; + let set = cache.get(material); + if (set === undefined) { + set = new Set; + cache.set(material, set); + } + return set; + } + _getShaderStage(code) { + const cache = this.shaderCache; + let stage = cache.get(code); + if (stage === undefined) { + stage = new WebGLShaderStage2(code); + cache.set(code, stage); + } + return stage; + } + } + + class WebGLShaderStage2 { + constructor(code) { + this.id = _id3++; + this.code = code; + this.usedTimes = 0; + } + } + function WebGLPrograms2(renderer2, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) { + const _programLayers = new Layers2; + const _customShaders = new WebGLShaderCache2; + const _activeChannels = new Set; + const programs = []; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures; + let precision = capabilities.precision; + const shaderIDs = { + MeshDepthMaterial: "depth", + MeshDistanceMaterial: "distanceRGBA", + MeshNormalMaterial: "normal", + MeshBasicMaterial: "basic", + MeshLambertMaterial: "lambert", + MeshPhongMaterial: "phong", + MeshToonMaterial: "toon", + MeshStandardMaterial: "physical", + MeshPhysicalMaterial: "physical", + MeshMatcapMaterial: "matcap", + LineBasicMaterial: "basic", + LineDashedMaterial: "dashed", + PointsMaterial: "points", + ShadowMaterial: "shadow", + SpriteMaterial: "sprite" + }; + function getChannel(value2) { + _activeChannels.add(value2); + if (value2 === 0) + return "uv"; + return `uv${value2}`; + } + function getParameters(material, lights, shadows, scene, object) { + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping2 ? envMap.image.height : null; + const shaderID = shaderIDs[material.type]; + if (material.precision !== null) { + precision = capabilities.getMaxPrecision(material.precision); + if (precision !== material.precision) { + console.warn("THREE.WebGLProgram.getParameters:", material.precision, "not supported, using", precision, "instead."); + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + let morphTextureStride = 0; + if (geometry.morphAttributes.position !== undefined) + morphTextureStride = 1; + if (geometry.morphAttributes.normal !== undefined) + morphTextureStride = 2; + if (geometry.morphAttributes.color !== undefined) + morphTextureStride = 3; + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + if (shaderID) { + const shader = ShaderLib2[shaderID]; + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + } else { + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + _customShaders.update(material); + customVertexShaderID = _customShaders.getVertexShaderID(material); + customFragmentShaderID = _customShaders.getFragmentShaderID(material); + } + const currentRenderTarget = renderer2.getRenderTarget(); + const reverseDepthBuffer = renderer2.state.buffers.depth.getReversed(); + const IS_INSTANCEDMESH = object.isInstancedMesh === true; + const IS_BATCHEDMESH = object.isBatchedMesh === true; + const HAS_MAP = !!material.map; + const HAS_MATCAP = !!material.matcap; + const HAS_ENVMAP = !!envMap; + const HAS_AOMAP = !!material.aoMap; + const HAS_LIGHTMAP = !!material.lightMap; + const HAS_BUMPMAP = !!material.bumpMap; + const HAS_NORMALMAP = !!material.normalMap; + const HAS_DISPLACEMENTMAP = !!material.displacementMap; + const HAS_EMISSIVEMAP = !!material.emissiveMap; + const HAS_METALNESSMAP = !!material.metalnessMap; + const HAS_ROUGHNESSMAP = !!material.roughnessMap; + const HAS_ANISOTROPY = material.anisotropy > 0; + const HAS_CLEARCOAT = material.clearcoat > 0; + const HAS_DISPERSION = material.dispersion > 0; + const HAS_IRIDESCENCE = material.iridescence > 0; + const HAS_SHEEN = material.sheen > 0; + const HAS_TRANSMISSION = material.transmission > 0; + const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !!material.anisotropyMap; + const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !!material.clearcoatMap; + const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !!material.clearcoatNormalMap; + const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !!material.clearcoatRoughnessMap; + const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !!material.iridescenceMap; + const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !!material.iridescenceThicknessMap; + const HAS_SHEEN_COLORMAP = HAS_SHEEN && !!material.sheenColorMap; + const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !!material.sheenRoughnessMap; + const HAS_SPECULARMAP = !!material.specularMap; + const HAS_SPECULAR_COLORMAP = !!material.specularColorMap; + const HAS_SPECULAR_INTENSITYMAP = !!material.specularIntensityMap; + const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !!material.transmissionMap; + const HAS_THICKNESSMAP = HAS_TRANSMISSION && !!material.thicknessMap; + const HAS_GRADIENTMAP = !!material.gradientMap; + const HAS_ALPHAMAP = !!material.alphaMap; + const HAS_ALPHATEST = material.alphaTest > 0; + const HAS_ALPHAHASH = !!material.alphaHash; + const HAS_EXTENSIONS = !!material.extensions; + let toneMapping = NoToneMapping2; + if (material.toneMapped) { + if (currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true) { + toneMapping = renderer2.toneMapping; + } + } + const parameters = { + shaderID, + shaderType: material.type, + shaderName: material.name, + vertexShader, + fragmentShader, + defines: material.defines, + customVertexShaderID, + customFragmentShaderID, + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + precision, + batching: IS_BATCHEDMESH, + batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null, + instancing: IS_INSTANCEDMESH, + instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, + supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, + outputColorSpace: currentRenderTarget === null ? renderer2.outputColorSpace : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace2, + alphaToCoverage: !!material.alphaToCoverage, + map: HAS_MAP, + matcap: HAS_MATCAP, + envMap: HAS_ENVMAP, + envMapMode: HAS_ENVMAP && envMap.mapping, + envMapCubeUVHeight, + aoMap: HAS_AOMAP, + lightMap: HAS_LIGHTMAP, + bumpMap: HAS_BUMPMAP, + normalMap: HAS_NORMALMAP, + displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP, + emissiveMap: HAS_EMISSIVEMAP, + normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap2, + normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap2, + metalnessMap: HAS_METALNESSMAP, + roughnessMap: HAS_ROUGHNESSMAP, + anisotropy: HAS_ANISOTROPY, + anisotropyMap: HAS_ANISOTROPYMAP, + clearcoat: HAS_CLEARCOAT, + clearcoatMap: HAS_CLEARCOATMAP, + clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP, + clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP, + dispersion: HAS_DISPERSION, + iridescence: HAS_IRIDESCENCE, + iridescenceMap: HAS_IRIDESCENCEMAP, + iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP, + sheen: HAS_SHEEN, + sheenColorMap: HAS_SHEEN_COLORMAP, + sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP, + specularMap: HAS_SPECULARMAP, + specularColorMap: HAS_SPECULAR_COLORMAP, + specularIntensityMap: HAS_SPECULAR_INTENSITYMAP, + transmission: HAS_TRANSMISSION, + transmissionMap: HAS_TRANSMISSIONMAP, + thicknessMap: HAS_THICKNESSMAP, + gradientMap: HAS_GRADIENTMAP, + opaque: material.transparent === false && material.blending === NormalBlending2 && material.alphaToCoverage === false, + alphaMap: HAS_ALPHAMAP, + alphaTest: HAS_ALPHATEST, + alphaHash: HAS_ALPHAHASH, + combine: material.combine, + mapUv: HAS_MAP && getChannel(material.map.channel), + aoMapUv: HAS_AOMAP && getChannel(material.aoMap.channel), + lightMapUv: HAS_LIGHTMAP && getChannel(material.lightMap.channel), + bumpMapUv: HAS_BUMPMAP && getChannel(material.bumpMap.channel), + normalMapUv: HAS_NORMALMAP && getChannel(material.normalMap.channel), + displacementMapUv: HAS_DISPLACEMENTMAP && getChannel(material.displacementMap.channel), + emissiveMapUv: HAS_EMISSIVEMAP && getChannel(material.emissiveMap.channel), + metalnessMapUv: HAS_METALNESSMAP && getChannel(material.metalnessMap.channel), + roughnessMapUv: HAS_ROUGHNESSMAP && getChannel(material.roughnessMap.channel), + anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel(material.anisotropyMap.channel), + clearcoatMapUv: HAS_CLEARCOATMAP && getChannel(material.clearcoatMap.channel), + clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel(material.clearcoatNormalMap.channel), + clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel(material.clearcoatRoughnessMap.channel), + iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel(material.iridescenceMap.channel), + iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel(material.iridescenceThicknessMap.channel), + sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel(material.sheenColorMap.channel), + sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel(material.sheenRoughnessMap.channel), + specularMapUv: HAS_SPECULARMAP && getChannel(material.specularMap.channel), + specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel(material.specularColorMap.channel), + specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel(material.specularIntensityMap.channel), + transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel(material.transmissionMap.channel), + thicknessMapUv: HAS_THICKNESSMAP && getChannel(material.thicknessMap.channel), + alphaMapUv: HAS_ALPHAMAP && getChannel(material.alphaMap.channel), + vertexTangents: !!geometry.attributes.tangent && (HAS_NORMALMAP || HAS_ANISOTROPY), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4, + pointsUvs: object.isPoints === true && !!geometry.attributes.uv && (HAS_MAP || HAS_ALPHAMAP), + fog: !!fog, + useFog: material.fog === true, + fogExp2: !!fog && fog.isFogExp2, + flatShading: material.flatShading === true, + sizeAttenuation: material.sizeAttenuation === true, + logarithmicDepthBuffer, + reverseDepthBuffer, + skinning: object.isSkinnedMesh === true, + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount, + morphTextureStride, + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + numLightProbes: lights.numLightProbes, + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + dithering: material.dithering, + shadowMapEnabled: renderer2.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer2.shadowMap.type, + toneMapping, + decodeVideoTexture: HAS_MAP && material.map.isVideoTexture === true && ColorManagement2.getTransfer(material.map.colorSpace) === SRGBTransfer2, + decodeVideoTextureEmissive: HAS_EMISSIVEMAP && material.emissiveMap.isVideoTexture === true && ColorManagement2.getTransfer(material.emissiveMap.colorSpace) === SRGBTransfer2, + premultipliedAlpha: material.premultipliedAlpha, + doubleSided: material.side === DoubleSide2, + flipSided: material.side === BackSide2, + useDepthPacking: material.depthPacking >= 0, + depthPacking: material.depthPacking || 0, + index0AttributeName: material.index0AttributeName, + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has("WEBGL_clip_cull_distance"), + extensionMultiDraw: (HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH) && extensions.has("WEBGL_multi_draw"), + rendererExtensionParallelShaderCompile: extensions.has("KHR_parallel_shader_compile"), + customProgramCacheKey: material.customProgramCacheKey() + }; + parameters.vertexUv1s = _activeChannels.has(1); + parameters.vertexUv2s = _activeChannels.has(2); + parameters.vertexUv3s = _activeChannels.has(3); + _activeChannels.clear(); + return parameters; + } + function getProgramCacheKey(parameters) { + const array = []; + if (parameters.shaderID) { + array.push(parameters.shaderID); + } else { + array.push(parameters.customVertexShaderID); + array.push(parameters.customFragmentShaderID); + } + if (parameters.defines !== undefined) { + for (const name2 in parameters.defines) { + array.push(name2); + array.push(parameters.defines[name2]); + } + } + if (parameters.isRawShaderMaterial === false) { + getProgramCacheKeyParameters(array, parameters); + getProgramCacheKeyBooleans(array, parameters); + array.push(renderer2.outputColorSpace); + } + array.push(parameters.customProgramCacheKey); + return array.join(); + } + function getProgramCacheKeyParameters(array, parameters) { + array.push(parameters.precision); + array.push(parameters.outputColorSpace); + array.push(parameters.envMapMode); + array.push(parameters.envMapCubeUVHeight); + array.push(parameters.mapUv); + array.push(parameters.alphaMapUv); + array.push(parameters.lightMapUv); + array.push(parameters.aoMapUv); + array.push(parameters.bumpMapUv); + array.push(parameters.normalMapUv); + array.push(parameters.displacementMapUv); + array.push(parameters.emissiveMapUv); + array.push(parameters.metalnessMapUv); + array.push(parameters.roughnessMapUv); + array.push(parameters.anisotropyMapUv); + array.push(parameters.clearcoatMapUv); + array.push(parameters.clearcoatNormalMapUv); + array.push(parameters.clearcoatRoughnessMapUv); + array.push(parameters.iridescenceMapUv); + array.push(parameters.iridescenceThicknessMapUv); + array.push(parameters.sheenColorMapUv); + array.push(parameters.sheenRoughnessMapUv); + array.push(parameters.specularMapUv); + array.push(parameters.specularColorMapUv); + array.push(parameters.specularIntensityMapUv); + array.push(parameters.transmissionMapUv); + array.push(parameters.thicknessMapUv); + array.push(parameters.combine); + array.push(parameters.fogExp2); + array.push(parameters.sizeAttenuation); + array.push(parameters.morphTargetsCount); + array.push(parameters.morphAttributeCount); + array.push(parameters.numDirLights); + array.push(parameters.numPointLights); + array.push(parameters.numSpotLights); + array.push(parameters.numSpotLightMaps); + array.push(parameters.numHemiLights); + array.push(parameters.numRectAreaLights); + array.push(parameters.numDirLightShadows); + array.push(parameters.numPointLightShadows); + array.push(parameters.numSpotLightShadows); + array.push(parameters.numSpotLightShadowsWithMaps); + array.push(parameters.numLightProbes); + array.push(parameters.shadowMapType); + array.push(parameters.toneMapping); + array.push(parameters.numClippingPlanes); + array.push(parameters.numClipIntersection); + array.push(parameters.depthPacking); + } + function getProgramCacheKeyBooleans(array, parameters) { + _programLayers.disableAll(); + if (parameters.supportsVertexTextures) + _programLayers.enable(0); + if (parameters.instancing) + _programLayers.enable(1); + if (parameters.instancingColor) + _programLayers.enable(2); + if (parameters.instancingMorph) + _programLayers.enable(3); + if (parameters.matcap) + _programLayers.enable(4); + if (parameters.envMap) + _programLayers.enable(5); + if (parameters.normalMapObjectSpace) + _programLayers.enable(6); + if (parameters.normalMapTangentSpace) + _programLayers.enable(7); + if (parameters.clearcoat) + _programLayers.enable(8); + if (parameters.iridescence) + _programLayers.enable(9); + if (parameters.alphaTest) + _programLayers.enable(10); + if (parameters.vertexColors) + _programLayers.enable(11); + if (parameters.vertexAlphas) + _programLayers.enable(12); + if (parameters.vertexUv1s) + _programLayers.enable(13); + if (parameters.vertexUv2s) + _programLayers.enable(14); + if (parameters.vertexUv3s) + _programLayers.enable(15); + if (parameters.vertexTangents) + _programLayers.enable(16); + if (parameters.anisotropy) + _programLayers.enable(17); + if (parameters.alphaHash) + _programLayers.enable(18); + if (parameters.batching) + _programLayers.enable(19); + if (parameters.dispersion) + _programLayers.enable(20); + if (parameters.batchingColor) + _programLayers.enable(21); + array.push(_programLayers.mask); + _programLayers.disableAll(); + if (parameters.fog) + _programLayers.enable(0); + if (parameters.useFog) + _programLayers.enable(1); + if (parameters.flatShading) + _programLayers.enable(2); + if (parameters.logarithmicDepthBuffer) + _programLayers.enable(3); + if (parameters.reverseDepthBuffer) + _programLayers.enable(4); + if (parameters.skinning) + _programLayers.enable(5); + if (parameters.morphTargets) + _programLayers.enable(6); + if (parameters.morphNormals) + _programLayers.enable(7); + if (parameters.morphColors) + _programLayers.enable(8); + if (parameters.premultipliedAlpha) + _programLayers.enable(9); + if (parameters.shadowMapEnabled) + _programLayers.enable(10); + if (parameters.doubleSided) + _programLayers.enable(11); + if (parameters.flipSided) + _programLayers.enable(12); + if (parameters.useDepthPacking) + _programLayers.enable(13); + if (parameters.dithering) + _programLayers.enable(14); + if (parameters.transmission) + _programLayers.enable(15); + if (parameters.sheen) + _programLayers.enable(16); + if (parameters.opaque) + _programLayers.enable(17); + if (parameters.pointsUvs) + _programLayers.enable(18); + if (parameters.decodeVideoTexture) + _programLayers.enable(19); + if (parameters.decodeVideoTextureEmissive) + _programLayers.enable(20); + if (parameters.alphaToCoverage) + _programLayers.enable(21); + array.push(_programLayers.mask); + } + function getUniforms(material) { + const shaderID = shaderIDs[material.type]; + let uniforms; + if (shaderID) { + const shader = ShaderLib2[shaderID]; + uniforms = UniformsUtils2.clone(shader.uniforms); + } else { + uniforms = material.uniforms; + } + return uniforms; + } + function acquireProgram(parameters, cacheKey) { + let program; + for (let p = 0, pl = programs.length;p < pl; p++) { + const preexistingProgram = programs[p]; + if (preexistingProgram.cacheKey === cacheKey) { + program = preexistingProgram; + ++program.usedTimes; + break; + } + } + if (program === undefined) { + program = new WebGLProgram2(renderer2, cacheKey, parameters, bindingStates); + programs.push(program); + } + return program; + } + function releaseProgram(program) { + if (--program.usedTimes === 0) { + const i = programs.indexOf(program); + programs[i] = programs[programs.length - 1]; + programs.pop(); + program.destroy(); + } + } + function releaseShaderCache(material) { + _customShaders.remove(material); + } + function dispose() { + _customShaders.dispose(); + } + return { + getParameters, + getProgramCacheKey, + getUniforms, + acquireProgram, + releaseProgram, + releaseShaderCache, + programs, + dispose + }; + } + function WebGLProperties2() { + let properties = new WeakMap; + function has2(object) { + return properties.has(object); + } + function get(object) { + let map2 = properties.get(object); + if (map2 === undefined) { + map2 = {}; + properties.set(object, map2); + } + return map2; + } + function remove(object) { + properties.delete(object); + } + function update(object, key2, value2) { + properties.get(object)[key2] = value2; + } + function dispose() { + properties = new WeakMap; + } + return { + has: has2, + get, + remove, + update, + dispose + }; + } + function painterSortStable2(a, b) { + if (a.groupOrder !== b.groupOrder) { + return a.groupOrder - b.groupOrder; + } else if (a.renderOrder !== b.renderOrder) { + return a.renderOrder - b.renderOrder; + } else if (a.material.id !== b.material.id) { + return a.material.id - b.material.id; + } else if (a.z !== b.z) { + return a.z - b.z; + } else { + return a.id - b.id; + } + } + function reversePainterSortStable2(a, b) { + if (a.groupOrder !== b.groupOrder) { + return a.groupOrder - b.groupOrder; + } else if (a.renderOrder !== b.renderOrder) { + return a.renderOrder - b.renderOrder; + } else if (a.z !== b.z) { + return b.z - a.z; + } else { + return a.id - b.id; + } + } + function WebGLRenderList2() { + const renderItems = []; + let renderItemsIndex = 0; + const opaque = []; + const transmissive = []; + const transparent = []; + function init() { + renderItemsIndex = 0; + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + } + function getNextRenderItem(object, geometry, material, groupOrder, z, group) { + let renderItem = renderItems[renderItemsIndex]; + if (renderItem === undefined) { + renderItem = { + id: object.id, + object, + geometry, + material, + groupOrder, + renderOrder: object.renderOrder, + z, + group + }; + renderItems[renderItemsIndex] = renderItem; + } else { + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + } + renderItemsIndex++; + return renderItem; + } + function push(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.push(renderItem); + } else if (material.transparent === true) { + transparent.push(renderItem); + } else { + opaque.push(renderItem); + } + } + function unshift(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.unshift(renderItem); + } else if (material.transparent === true) { + transparent.unshift(renderItem); + } else { + opaque.unshift(renderItem); + } + } + function sort(customOpaqueSort, customTransparentSort) { + if (opaque.length > 1) + opaque.sort(customOpaqueSort || painterSortStable2); + if (transmissive.length > 1) + transmissive.sort(customTransparentSort || reversePainterSortStable2); + if (transparent.length > 1) + transparent.sort(customTransparentSort || reversePainterSortStable2); + } + function finish() { + for (let i = renderItemsIndex, il = renderItems.length;i < il; i++) { + const renderItem = renderItems[i]; + if (renderItem.id === null) + break; + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + } + } + return { + opaque, + transmissive, + transparent, + init, + push, + unshift, + finish, + sort + }; + } + function WebGLRenderLists2() { + let lists = new WeakMap; + function get(scene, renderCallDepth) { + const listArray = lists.get(scene); + let list; + if (listArray === undefined) { + list = new WebGLRenderList2; + lists.set(scene, [list]); + } else { + if (renderCallDepth >= listArray.length) { + list = new WebGLRenderList2; + listArray.push(list); + } else { + list = listArray[renderCallDepth]; + } + } + return list; + } + function dispose() { + lists = new WeakMap; + } + return { + get, + dispose + }; + } + function UniformsCache2() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== undefined) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + direction: new Vector32, + color: new Color2 + }; + break; + case "SpotLight": + uniforms = { + position: new Vector32, + direction: new Vector32, + color: new Color2, + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + case "PointLight": + uniforms = { + position: new Vector32, + color: new Color2, + distance: 0, + decay: 0 + }; + break; + case "HemisphereLight": + uniforms = { + direction: new Vector32, + skyColor: new Color2, + groundColor: new Color2 + }; + break; + case "RectAreaLight": + uniforms = { + color: new Color2, + position: new Vector32, + halfWidth: new Vector32, + halfHeight: new Vector32 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; + } + function ShadowUniformsCache2() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== undefined) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector22 + }; + break; + case "SpotLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector22 + }; + break; + case "PointLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector22, + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; + } + var nextVersion2 = 0; + function shadowCastingAndTexturingLightsFirst2(lightA, lightB) { + return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0); + } + function WebGLLights2(extensions) { + const cache = new UniformsCache2; + const shadowCache = ShadowUniformsCache2(); + const state = { + version: 0, + hash: { + directionalLength: -1, + pointLength: -1, + spotLength: -1, + rectAreaLength: -1, + hemiLength: -1, + numDirectionalShadows: -1, + numPointShadows: -1, + numSpotShadows: -1, + numSpotMaps: -1, + numLightProbes: -1 + }, + ambient: [0, 0, 0], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0, + numLightProbes: 0 + }; + for (let i = 0;i < 9; i++) + state.probe.push(new Vector32); + const vector3 = new Vector32; + const matrix4 = new Matrix42; + const matrix42 = new Matrix42; + function setup(lights) { + let r = 0, g = 0, b = 0; + for (let i = 0;i < 9; i++) + state.probe[i].set(0, 0, 0); + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + let numLightProbes = 0; + lights.sort(shadowCastingAndTexturingLightsFirst2); + for (let i = 0, l = lights.length;i < l; i++) { + const light = lights[i]; + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null; + if (light.isAmbientLight) { + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; + } else if (light.isLightProbe) { + for (let j = 0;j < 9; j++) { + state.probe[j].addScaledVector(light.sh.coefficients[j], intensity); + } + numLightProbes++; + } else if (light.isDirectionalLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.directionalShadow[directionalLength] = shadowUniforms; + state.directionalShadowMap[directionalLength] = shadowMap; + state.directionalShadowMatrix[directionalLength] = light.shadow.matrix; + numDirectionalShadows++; + } + state.directional[directionalLength] = uniforms; + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = cache.get(light); + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.distance = distance; + uniforms.coneCos = Math.cos(light.angle); + uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra)); + uniforms.decay = light.decay; + state.spot[spotLength] = uniforms; + const shadow = light.shadow; + if (light.map) { + state.spotLightMap[numSpotMaps] = light.map; + numSpotMaps++; + shadow.updateMatrices(light); + if (light.castShadow) + numSpotShadowsWithMaps++; + } + state.spotLightMatrix[spotLength] = shadow.matrix; + if (light.castShadow) { + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.spotShadow[spotLength] = shadowUniforms; + state.spotShadowMap[spotLength] = shadowMap; + numSpotShadows++; + } + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = cache.get(light); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + state.rectArea[rectAreaLength] = uniforms; + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + state.pointShadow[pointLength] = shadowUniforms; + state.pointShadowMap[pointLength] = shadowMap; + state.pointShadowMatrix[pointLength] = light.shadow.matrix; + numPointShadows++; + } + state.point[pointLength] = uniforms; + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = cache.get(light); + uniforms.skyColor.copy(light.color).multiplyScalar(intensity); + uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity); + state.hemi[hemiLength] = uniforms; + hemiLength++; + } + } + if (rectAreaLength > 0) { + if (extensions.has("OES_texture_float_linear") === true) { + state.rectAreaLTC1 = UniformsLib2.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib2.LTC_FLOAT_2; + } else { + state.rectAreaLTC1 = UniformsLib2.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib2.LTC_HALF_2; + } + } + state.ambient[0] = r; + state.ambient[1] = g; + state.ambient[2] = b; + const hash = state.hash; + if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps || hash.numLightProbes !== numLightProbes) { + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + state.numLightProbes = numLightProbes; + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + hash.numLightProbes = numLightProbes; + state.version = nextVersion2++; + } + } + function setupView(lights, camera) { + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + const viewMatrix = camera.matrixWorldInverse; + for (let i = 0, l = lights.length;i < l; i++) { + const light = lights[i]; + if (light.isDirectionalLight) { + const uniforms = state.directional[directionalLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = state.spot[spotLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = state.rectArea[rectAreaLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + matrix42.identity(); + matrix4.copy(light.matrixWorld); + matrix4.premultiply(viewMatrix); + matrix42.extractRotation(matrix4); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + uniforms.halfWidth.applyMatrix4(matrix42); + uniforms.halfHeight.applyMatrix4(matrix42); + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = state.point[pointLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = state.hemi[hemiLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + uniforms.direction.transformDirection(viewMatrix); + hemiLength++; + } + } + } + return { + setup, + setupView, + state + }; + } + function WebGLRenderState2(extensions) { + const lights = new WebGLLights2(extensions); + const lightsArray = []; + const shadowsArray = []; + function init(camera) { + state.camera = camera; + lightsArray.length = 0; + shadowsArray.length = 0; + } + function pushLight(light) { + lightsArray.push(light); + } + function pushShadow(shadowLight) { + shadowsArray.push(shadowLight); + } + function setupLights() { + lights.setup(lightsArray); + } + function setupLightsView(camera) { + lights.setupView(lightsArray, camera); + } + const state = { + lightsArray, + shadowsArray, + camera: null, + lights, + transmissionRenderTarget: {} + }; + return { + init, + state, + setupLights, + setupLightsView, + pushLight, + pushShadow + }; + } + function WebGLRenderStates2(extensions) { + let renderStates = new WeakMap; + function get(scene, renderCallDepth = 0) { + const renderStateArray = renderStates.get(scene); + let renderState; + if (renderStateArray === undefined) { + renderState = new WebGLRenderState2(extensions); + renderStates.set(scene, [renderState]); + } else { + if (renderCallDepth >= renderStateArray.length) { + renderState = new WebGLRenderState2(extensions); + renderStateArray.push(renderState); + } else { + renderState = renderStateArray[renderCallDepth]; + } + } + return renderState; + } + function dispose() { + renderStates = new WeakMap; + } + return { + get, + dispose + }; + } + var vertex2 = `void main() { + gl_Position = vec4( position, 1.0 ); +}`; + var fragment2 = `uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`; + function WebGLShadowMap2(renderer2, objects, capabilities) { + let _frustum3 = new Frustum2; + const _shadowMapSize = new Vector22, _viewportSize = new Vector22, _viewport = new Vector42, _depthMaterial = new MeshDepthMaterial2({ depthPacking: RGBADepthPacking2 }), _distanceMaterial = new MeshDistanceMaterial2, _materialCache = {}, _maxTextureSize = capabilities.maxTextureSize; + const shadowSide = { [FrontSide2]: BackSide2, [BackSide2]: FrontSide2, [DoubleSide2]: DoubleSide2 }; + const shadowMaterialVertical = new ShaderMaterial2({ + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector22 }, + radius: { value: 4 } + }, + vertexShader: vertex2, + fragmentShader: fragment2 + }); + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + const fullScreenTri = new BufferGeometry2; + fullScreenTri.setAttribute("position", new BufferAttribute2(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3)); + const fullScreenMesh = new Mesh2(fullScreenTri, shadowMaterialVertical); + const scope = this; + this.enabled = false; + this.autoUpdate = true; + this.needsUpdate = false; + this.type = PCFShadowMap2; + let _previousType = this.type; + this.render = function(lights, scene, camera) { + if (scope.enabled === false) + return; + if (scope.autoUpdate === false && scope.needsUpdate === false) + return; + if (lights.length === 0) + return; + const currentRenderTarget = renderer2.getRenderTarget(); + const activeCubeFace = renderer2.getActiveCubeFace(); + const activeMipmapLevel = renderer2.getActiveMipmapLevel(); + const _state = renderer2.state; + _state.setBlending(NoBlending2); + _state.buffers.color.setClear(1, 1, 1, 1); + _state.buffers.depth.setTest(true); + _state.setScissorTest(false); + const toVSM = _previousType !== VSMShadowMap2 && this.type === VSMShadowMap2; + const fromVSM = _previousType === VSMShadowMap2 && this.type !== VSMShadowMap2; + for (let i = 0, il = lights.length;i < il; i++) { + const light = lights[i]; + const shadow = light.shadow; + if (shadow === undefined) { + console.warn("THREE.WebGLShadowMap:", light, "has no shadow."); + continue; + } + if (shadow.autoUpdate === false && shadow.needsUpdate === false) + continue; + _shadowMapSize.copy(shadow.mapSize); + const shadowFrameExtents = shadow.getFrameExtents(); + _shadowMapSize.multiply(shadowFrameExtents); + _viewportSize.copy(shadow.mapSize); + if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) { + if (_shadowMapSize.x > _maxTextureSize) { + _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + } + if (_shadowMapSize.y > _maxTextureSize) { + _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + } + } + if (shadow.map === null || toVSM === true || fromVSM === true) { + const pars = this.type !== VSMShadowMap2 ? { minFilter: NearestFilter2, magFilter: NearestFilter2 } : {}; + if (shadow.map !== null) { + shadow.map.dispose(); + } + shadow.map = new WebGLRenderTarget2(_shadowMapSize.x, _shadowMapSize.y, pars); + shadow.map.texture.name = light.name + ".shadowMap"; + shadow.camera.updateProjectionMatrix(); + } + renderer2.setRenderTarget(shadow.map); + renderer2.clear(); + const viewportCount = shadow.getViewportCount(); + for (let vp = 0;vp < viewportCount; vp++) { + const viewport = shadow.getViewport(vp); + _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w); + _state.viewport(_viewport); + shadow.updateMatrices(light, vp); + _frustum3 = shadow.getFrustum(); + renderObject(scene, camera, shadow.camera, light, this.type); + } + if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap2) { + VSMPass(shadow, camera); + } + shadow.needsUpdate = false; + } + _previousType = this.type; + scope.needsUpdate = false; + renderer2.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel); + }; + function VSMPass(shadow, camera) { + const geometry = objects.update(fullScreenMesh); + if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) { + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + } + if (shadow.mapPass === null) { + shadow.mapPass = new WebGLRenderTarget2(_shadowMapSize.x, _shadowMapSize.y); + } + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + renderer2.setRenderTarget(shadow.mapPass); + renderer2.clear(); + renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + renderer2.setRenderTarget(shadow.map); + renderer2.clear(); + renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null); + } + function getDepthMaterial(object, material, light, type) { + let result = null; + const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial; + if (customMaterial !== undefined) { + result = customMaterial; + } else { + result = light.isPointLight === true ? _distanceMaterial : _depthMaterial; + if (renderer2.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0 || material.map && material.alphaTest > 0) { + const keyA = result.uuid, keyB = material.uuid; + let materialsForVariant = _materialCache[keyA]; + if (materialsForVariant === undefined) { + materialsForVariant = {}; + _materialCache[keyA] = materialsForVariant; + } + let cachedMaterial = materialsForVariant[keyB]; + if (cachedMaterial === undefined) { + cachedMaterial = result.clone(); + materialsForVariant[keyB] = cachedMaterial; + material.addEventListener("dispose", onMaterialDispose); + } + result = cachedMaterial; + } + } + result.visible = material.visible; + result.wireframe = material.wireframe; + if (type === VSMShadowMap2) { + result.side = material.shadowSide !== null ? material.shadowSide : material.side; + } else { + result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side]; + } + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.map = material.map; + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + if (light.isPointLight === true && result.isMeshDistanceMaterial === true) { + const materialProperties = renderer2.properties.get(result); + materialProperties.light = light; + } + return result; + } + function renderObject(object, camera, shadowCamera, light, type) { + if (object.visible === false) + return; + const visible = object.layers.test(camera.layers); + if (visible && (object.isMesh || object.isLine || object.isPoints)) { + if ((object.castShadow || object.receiveShadow && type === VSMShadowMap2) && (!object.frustumCulled || _frustum3.intersectsObject(object))) { + object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld); + const geometry = objects.update(object); + const material = object.material; + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let k = 0, kl = groups.length;k < kl; k++) { + const group = groups[k]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + const depthMaterial = getDepthMaterial(object, groupMaterial, light, type); + object.onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group); + object.onAfterShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + } + } + } else if (material.visible) { + const depthMaterial = getDepthMaterial(object, material, light, type); + object.onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null); + object.onAfterShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + } + } + } + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + renderObject(children[i], camera, shadowCamera, light, type); + } + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + for (const id in _materialCache) { + const cache = _materialCache[id]; + const uuid = event.target.uuid; + if (uuid in cache) { + const shadowMaterial = cache[uuid]; + shadowMaterial.dispose(); + delete cache[uuid]; + } + } + } + } + var reversedFuncs2 = { + [NeverDepth2]: AlwaysDepth2, + [LessDepth2]: GreaterDepth2, + [EqualDepth2]: NotEqualDepth2, + [LessEqualDepth2]: GreaterEqualDepth2, + [AlwaysDepth2]: NeverDepth2, + [GreaterDepth2]: LessDepth2, + [NotEqualDepth2]: EqualDepth2, + [GreaterEqualDepth2]: LessEqualDepth2 + }; + function WebGLState2(gl, extensions) { + function ColorBuffer() { + let locked = false; + const color = new Vector42; + let currentColorMask = null; + const currentColorClear = new Vector42(0, 0, 0, 0); + return { + setMask: function(colorMask) { + if (currentColorMask !== colorMask && !locked) { + gl.colorMask(colorMask, colorMask, colorMask, colorMask); + currentColorMask = colorMask; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(r, g, b, a, premultipliedAlpha) { + if (premultipliedAlpha === true) { + r *= a; + g *= a; + b *= a; + } + color.set(r, g, b, a); + if (currentColorClear.equals(color) === false) { + gl.clearColor(r, g, b, a); + currentColorClear.copy(color); + } + }, + reset: function() { + locked = false; + currentColorMask = null; + currentColorClear.set(-1, 0, 0, 0); + } + }; + } + function DepthBuffer() { + let locked = false; + let reversed = false; + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + return { + setReversed: function(value2) { + if (reversed !== value2) { + const ext = extensions.get("EXT_clip_control"); + if (reversed) { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT); + } else { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT); + } + const oldDepth = currentDepthClear; + currentDepthClear = null; + this.setClear(oldDepth); + } + reversed = value2; + }, + getReversed: function() { + return reversed; + }, + setTest: function(depthTest) { + if (depthTest) { + enable(gl.DEPTH_TEST); + } else { + disable(gl.DEPTH_TEST); + } + }, + setMask: function(depthMask) { + if (currentDepthMask !== depthMask && !locked) { + gl.depthMask(depthMask); + currentDepthMask = depthMask; + } + }, + setFunc: function(depthFunc) { + if (reversed) + depthFunc = reversedFuncs2[depthFunc]; + if (currentDepthFunc !== depthFunc) { + switch (depthFunc) { + case NeverDepth2: + gl.depthFunc(gl.NEVER); + break; + case AlwaysDepth2: + gl.depthFunc(gl.ALWAYS); + break; + case LessDepth2: + gl.depthFunc(gl.LESS); + break; + case LessEqualDepth2: + gl.depthFunc(gl.LEQUAL); + break; + case EqualDepth2: + gl.depthFunc(gl.EQUAL); + break; + case GreaterEqualDepth2: + gl.depthFunc(gl.GEQUAL); + break; + case GreaterDepth2: + gl.depthFunc(gl.GREATER); + break; + case NotEqualDepth2: + gl.depthFunc(gl.NOTEQUAL); + break; + default: + gl.depthFunc(gl.LEQUAL); + } + currentDepthFunc = depthFunc; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(depth) { + if (currentDepthClear !== depth) { + if (reversed) { + depth = 1 - depth; + } + gl.clearDepth(depth); + currentDepthClear = depth; + } + }, + reset: function() { + locked = false; + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + reversed = false; + } + }; + } + function StencilBuffer() { + let locked = false; + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + return { + setTest: function(stencilTest) { + if (!locked) { + if (stencilTest) { + enable(gl.STENCIL_TEST); + } else { + disable(gl.STENCIL_TEST); + } + } + }, + setMask: function(stencilMask) { + if (currentStencilMask !== stencilMask && !locked) { + gl.stencilMask(stencilMask); + currentStencilMask = stencilMask; + } + }, + setFunc: function(stencilFunc, stencilRef, stencilMask) { + if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) { + gl.stencilFunc(stencilFunc, stencilRef, stencilMask); + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + } + }, + setOp: function(stencilFail, stencilZFail, stencilZPass) { + if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) { + gl.stencilOp(stencilFail, stencilZFail, stencilZPass); + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(stencil) { + if (currentStencilClear !== stencil) { + gl.clearStencil(stencil); + currentStencilClear = stencil; + } + }, + reset: function() { + locked = false; + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + } + }; + } + const colorBuffer = new ColorBuffer; + const depthBuffer = new DepthBuffer; + const stencilBuffer = new StencilBuffer; + const uboBindings = new WeakMap; + const uboProgramMap = new WeakMap; + let enabledCapabilities = {}; + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap; + let defaultDrawbuffers = []; + let currentProgram = null; + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentBlendColor = new Color2(0, 0, 0); + let currentBlendAlpha = 0; + let currentPremultipledAlpha = false; + let currentFlipSided = null; + let currentCullFace = null; + let currentLineWidth = null; + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter(gl.VERSION); + if (glVersion.indexOf("WebGL") !== -1) { + version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 1; + } else if (glVersion.indexOf("OpenGL ES") !== -1) { + version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 2; + } + let currentTextureSlot = null; + let currentBoundTextures = {}; + const scissorParam = gl.getParameter(gl.SCISSOR_BOX); + const viewportParam = gl.getParameter(gl.VIEWPORT); + const currentScissor = new Vector42().fromArray(scissorParam); + const currentViewport = new Vector42().fromArray(viewportParam); + function createTexture(type, target, count, dimensions) { + const data2 = new Uint8Array(4); + const texture = gl.createTexture(); + gl.bindTexture(type, texture); + gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + for (let i = 0;i < count; i++) { + if (type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY) { + gl.texImage3D(target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data2); + } else { + gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data2); + } + } + return texture; + } + const emptyTextures = {}; + emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1); + emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); + emptyTextures[gl.TEXTURE_2D_ARRAY] = createTexture(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1); + emptyTextures[gl.TEXTURE_3D] = createTexture(gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1); + colorBuffer.setClear(0, 0, 0, 1); + depthBuffer.setClear(1); + stencilBuffer.setClear(0); + enable(gl.DEPTH_TEST); + depthBuffer.setFunc(LessEqualDepth2); + setFlipSided(false); + setCullFace(CullFaceBack2); + enable(gl.CULL_FACE); + setBlending(NoBlending2); + function enable(id) { + if (enabledCapabilities[id] !== true) { + gl.enable(id); + enabledCapabilities[id] = true; + } + } + function disable(id) { + if (enabledCapabilities[id] !== false) { + gl.disable(id); + enabledCapabilities[id] = false; + } + } + function bindFramebuffer(target, framebuffer) { + if (currentBoundFramebuffers[target] !== framebuffer) { + gl.bindFramebuffer(target, framebuffer); + currentBoundFramebuffers[target] = framebuffer; + if (target === gl.DRAW_FRAMEBUFFER) { + currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer; + } + if (target === gl.FRAMEBUFFER) { + currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer; + } + return true; + } + return false; + } + function drawBuffers(renderTarget, framebuffer) { + let drawBuffers2 = defaultDrawbuffers; + let needsUpdate = false; + if (renderTarget) { + drawBuffers2 = currentDrawbuffers.get(framebuffer); + if (drawBuffers2 === undefined) { + drawBuffers2 = []; + currentDrawbuffers.set(framebuffer, drawBuffers2); + } + const textures = renderTarget.textures; + if (drawBuffers2.length !== textures.length || drawBuffers2[0] !== gl.COLOR_ATTACHMENT0) { + for (let i = 0, il = textures.length;i < il; i++) { + drawBuffers2[i] = gl.COLOR_ATTACHMENT0 + i; + } + drawBuffers2.length = textures.length; + needsUpdate = true; + } + } else { + if (drawBuffers2[0] !== gl.BACK) { + drawBuffers2[0] = gl.BACK; + needsUpdate = true; + } + } + if (needsUpdate) { + gl.drawBuffers(drawBuffers2); + } + } + function useProgram(program) { + if (currentProgram !== program) { + gl.useProgram(program); + currentProgram = program; + return true; + } + return false; + } + const equationToGL = { + [AddEquation2]: gl.FUNC_ADD, + [SubtractEquation2]: gl.FUNC_SUBTRACT, + [ReverseSubtractEquation2]: gl.FUNC_REVERSE_SUBTRACT + }; + equationToGL[MinEquation2] = gl.MIN; + equationToGL[MaxEquation2] = gl.MAX; + const factorToGL = { + [ZeroFactor2]: gl.ZERO, + [OneFactor2]: gl.ONE, + [SrcColorFactor2]: gl.SRC_COLOR, + [SrcAlphaFactor2]: gl.SRC_ALPHA, + [SrcAlphaSaturateFactor2]: gl.SRC_ALPHA_SATURATE, + [DstColorFactor2]: gl.DST_COLOR, + [DstAlphaFactor2]: gl.DST_ALPHA, + [OneMinusSrcColorFactor2]: gl.ONE_MINUS_SRC_COLOR, + [OneMinusSrcAlphaFactor2]: gl.ONE_MINUS_SRC_ALPHA, + [OneMinusDstColorFactor2]: gl.ONE_MINUS_DST_COLOR, + [OneMinusDstAlphaFactor2]: gl.ONE_MINUS_DST_ALPHA, + [ConstantColorFactor2]: gl.CONSTANT_COLOR, + [OneMinusConstantColorFactor2]: gl.ONE_MINUS_CONSTANT_COLOR, + [ConstantAlphaFactor2]: gl.CONSTANT_ALPHA, + [OneMinusConstantAlphaFactor2]: gl.ONE_MINUS_CONSTANT_ALPHA + }; + function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha) { + if (blending === NoBlending2) { + if (currentBlendingEnabled === true) { + disable(gl.BLEND); + currentBlendingEnabled = false; + } + return; + } + if (currentBlendingEnabled === false) { + enable(gl.BLEND); + currentBlendingEnabled = true; + } + if (blending !== CustomBlending2) { + if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) { + if (currentBlendEquation !== AddEquation2 || currentBlendEquationAlpha !== AddEquation2) { + gl.blendEquation(gl.FUNC_ADD); + currentBlendEquation = AddEquation2; + currentBlendEquationAlpha = AddEquation2; + } + if (premultipliedAlpha) { + switch (blending) { + case NormalBlending2: + gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending2: + gl.blendFunc(gl.ONE, gl.ONE); + break; + case SubtractiveBlending2: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending2: + gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } else { + switch (blending) { + case NormalBlending2: + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending2: + gl.blendFunc(gl.SRC_ALPHA, gl.ONE); + break; + case SubtractiveBlending2: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending2: + gl.blendFunc(gl.ZERO, gl.SRC_COLOR); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor.set(0, 0, 0); + currentBlendAlpha = 0; + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + } + return; + } + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) { + gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]); + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + } + if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) { + gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]); + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + } + if (blendColor.equals(currentBlendColor) === false || blendAlpha !== currentBlendAlpha) { + gl.blendColor(blendColor.r, blendColor.g, blendColor.b, blendAlpha); + currentBlendColor.copy(blendColor); + currentBlendAlpha = blendAlpha; + } + currentBlending = blending; + currentPremultipledAlpha = false; + } + function setMaterial(material, frontFaceCW) { + material.side === DoubleSide2 ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE); + let flipSided = material.side === BackSide2; + if (frontFaceCW) + flipSided = !flipSided; + setFlipSided(flipSided); + material.blending === NormalBlending2 && material.transparent === false ? setBlending(NoBlending2) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha); + depthBuffer.setFunc(material.depthFunc); + depthBuffer.setTest(material.depthTest); + depthBuffer.setMask(material.depthWrite); + colorBuffer.setMask(material.colorWrite); + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest(stencilWrite); + if (stencilWrite) { + stencilBuffer.setMask(material.stencilWriteMask); + stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask); + stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass); + } + setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits); + material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + } + function setFlipSided(flipSided) { + if (currentFlipSided !== flipSided) { + if (flipSided) { + gl.frontFace(gl.CW); + } else { + gl.frontFace(gl.CCW); + } + currentFlipSided = flipSided; + } + } + function setCullFace(cullFace) { + if (cullFace !== CullFaceNone2) { + enable(gl.CULL_FACE); + if (cullFace !== currentCullFace) { + if (cullFace === CullFaceBack2) { + gl.cullFace(gl.BACK); + } else if (cullFace === CullFaceFront2) { + gl.cullFace(gl.FRONT); + } else { + gl.cullFace(gl.FRONT_AND_BACK); + } + } + } else { + disable(gl.CULL_FACE); + } + currentCullFace = cullFace; + } + function setLineWidth(width2) { + if (width2 !== currentLineWidth) { + if (lineWidthAvailable) + gl.lineWidth(width2); + currentLineWidth = width2; + } + } + function setPolygonOffset(polygonOffset, factor, units) { + if (polygonOffset) { + enable(gl.POLYGON_OFFSET_FILL); + if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) { + gl.polygonOffset(factor, units); + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + } + } else { + disable(gl.POLYGON_OFFSET_FILL); + } + } + function setScissorTest(scissorTest) { + if (scissorTest) { + enable(gl.SCISSOR_TEST); + } else { + disable(gl.SCISSOR_TEST); + } + } + function activeTexture(webglSlot) { + if (webglSlot === undefined) + webglSlot = gl.TEXTURE0 + maxTextures - 1; + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + } + function bindTexture(webglType, webglTexture, webglSlot) { + if (webglSlot === undefined) { + if (currentTextureSlot === null) { + webglSlot = gl.TEXTURE0 + maxTextures - 1; + } else { + webglSlot = currentTextureSlot; + } + } + let boundTexture = currentBoundTextures[webglSlot]; + if (boundTexture === undefined) { + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[webglSlot] = boundTexture; + } + if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) { + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]); + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + } + } + function unbindTexture() { + const boundTexture = currentBoundTextures[currentTextureSlot]; + if (boundTexture !== undefined && boundTexture.type !== undefined) { + gl.bindTexture(boundTexture.type, null); + boundTexture.type = undefined; + boundTexture.texture = undefined; + } + } + function compressedTexImage2D() { + try { + gl.compressedTexImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexImage3D() { + try { + gl.compressedTexImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage2D() { + try { + gl.texSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage3D() { + try { + gl.texSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage2D() { + try { + gl.compressedTexSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage3D() { + try { + gl.compressedTexSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage2D() { + try { + gl.texStorage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage3D() { + try { + gl.texStorage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage2D() { + try { + gl.texImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage3D() { + try { + gl.texImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function scissor(scissor2) { + if (currentScissor.equals(scissor2) === false) { + gl.scissor(scissor2.x, scissor2.y, scissor2.z, scissor2.w); + currentScissor.copy(scissor2); + } + } + function viewport(viewport2) { + if (currentViewport.equals(viewport2) === false) { + gl.viewport(viewport2.x, viewport2.y, viewport2.z, viewport2.w); + currentViewport.copy(viewport2); + } + } + function updateUBOMapping(uniformsGroup, program) { + let mapping = uboProgramMap.get(program); + if (mapping === undefined) { + mapping = new WeakMap; + uboProgramMap.set(program, mapping); + } + let blockIndex = mapping.get(uniformsGroup); + if (blockIndex === undefined) { + blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name); + mapping.set(uniformsGroup, blockIndex); + } + } + function uniformBlockBinding(uniformsGroup, program) { + const mapping = uboProgramMap.get(program); + const blockIndex = mapping.get(uniformsGroup); + if (uboBindings.get(program) !== blockIndex) { + gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex); + uboBindings.set(program, blockIndex); + } + } + function reset() { + gl.disable(gl.BLEND); + gl.disable(gl.CULL_FACE); + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.POLYGON_OFFSET_FILL); + gl.disable(gl.SCISSOR_TEST); + gl.disable(gl.STENCIL_TEST); + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ZERO); + gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO); + gl.blendColor(0, 0, 0, 0); + gl.colorMask(true, true, true, true); + gl.clearColor(0, 0, 0, 0); + gl.depthMask(true); + gl.depthFunc(gl.LESS); + depthBuffer.setReversed(false); + gl.clearDepth(1); + gl.stencilMask(4294967295); + gl.stencilFunc(gl.ALWAYS, 0, 4294967295); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + gl.clearStencil(0); + gl.cullFace(gl.BACK); + gl.frontFace(gl.CCW); + gl.polygonOffset(0, 0); + gl.activeTexture(gl.TEXTURE0); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); + gl.useProgram(null); + gl.lineWidth(1); + gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); + gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); + enabledCapabilities = {}; + currentTextureSlot = null; + currentBoundTextures = {}; + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap; + defaultDrawbuffers = []; + currentProgram = null; + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor = new Color2(0, 0, 0); + currentBlendAlpha = 0; + currentPremultipledAlpha = false; + currentFlipSided = null; + currentCullFace = null; + currentLineWidth = null; + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height); + currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height); + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + } + return { + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + enable, + disable, + bindFramebuffer, + drawBuffers, + useProgram, + setBlending, + setMaterial, + setFlipSided, + setCullFace, + setLineWidth, + setPolygonOffset, + setScissorTest, + activeTexture, + bindTexture, + unbindTexture, + compressedTexImage2D, + compressedTexImage3D, + texImage2D, + texImage3D, + updateUBOMapping, + uniformBlockBinding, + texStorage2D, + texStorage3D, + texSubImage2D, + texSubImage3D, + compressedTexSubImage2D, + compressedTexSubImage3D, + scissor, + viewport, + reset + }; + } + function WebGLTextures2(_gl, extensions, state, properties, capabilities, utils, info) { + const multisampledRTTExt = extensions.has("WEBGL_multisampled_render_to_texture") ? extensions.get("WEBGL_multisampled_render_to_texture") : null; + const supportsInvalidateFramebuffer = typeof navigator === "undefined" ? false : /OculusBrowser/g.test(navigator.userAgent); + const _imageDimensions = new Vector22; + const _videoTextures = new WeakMap; + let _canvas3; + const _sources = new WeakMap; + let useOffscreenCanvas = false; + try { + useOffscreenCanvas = typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null; + } catch (err) { + } + function createCanvas(width2, height2) { + return useOffscreenCanvas ? new OffscreenCanvas(width2, height2) : createElementNS2("canvas"); + } + function resizeImage(image, needsNewCanvas, maxSize) { + let scale2 = 1; + const dimensions = getDimensions(image); + if (dimensions.width > maxSize || dimensions.height > maxSize) { + scale2 = maxSize / Math.max(dimensions.width, dimensions.height); + } + if (scale2 < 1) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + const width2 = Math.floor(scale2 * dimensions.width); + const height2 = Math.floor(scale2 * dimensions.height); + if (_canvas3 === undefined) + _canvas3 = createCanvas(width2, height2); + const canvas = needsNewCanvas ? createCanvas(width2, height2) : _canvas3; + canvas.width = width2; + canvas.height = height2; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, width2, height2); + console.warn("THREE.WebGLRenderer: Texture has been resized from (" + dimensions.width + "x" + dimensions.height + ") to (" + width2 + "x" + height2 + ")."); + return canvas; + } else { + if ("data" in image) { + console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + dimensions.width + "x" + dimensions.height + ")."); + } + return image; + } + } + return image; + } + function textureNeedsGenerateMipmaps(texture) { + return texture.generateMipmaps; + } + function generateMipmap(target) { + _gl.generateMipmap(target); + } + function getTargetType(texture) { + if (texture.isWebGLCubeRenderTarget) + return _gl.TEXTURE_CUBE_MAP; + if (texture.isWebGL3DRenderTarget) + return _gl.TEXTURE_3D; + if (texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture) + return _gl.TEXTURE_2D_ARRAY; + return _gl.TEXTURE_2D; + } + function getInternalFormat(internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false) { + if (internalFormatName !== null) { + if (_gl[internalFormatName] !== undefined) + return _gl[internalFormatName]; + console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + internalFormatName + "'"); + } + let internalFormat = glFormat; + if (glFormat === _gl.RED) { + if (glType === _gl.FLOAT) + internalFormat = _gl.R32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.R16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.R8; + } + if (glFormat === _gl.RED_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.R8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.R16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.R32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.R8I; + if (glType === _gl.SHORT) + internalFormat = _gl.R16I; + if (glType === _gl.INT) + internalFormat = _gl.R32I; + } + if (glFormat === _gl.RG) { + if (glType === _gl.FLOAT) + internalFormat = _gl.RG32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.RG16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RG8; + } + if (glFormat === _gl.RG_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RG8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RG16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RG32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RG8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RG16I; + if (glType === _gl.INT) + internalFormat = _gl.RG32I; + } + if (glFormat === _gl.RGB_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RGB8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RGB16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RGB32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RGB8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RGB16I; + if (glType === _gl.INT) + internalFormat = _gl.RGB32I; + } + if (glFormat === _gl.RGBA_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RGBA8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RGBA16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RGBA32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RGBA8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RGBA16I; + if (glType === _gl.INT) + internalFormat = _gl.RGBA32I; + } + if (glFormat === _gl.RGB) { + if (glType === _gl.UNSIGNED_INT_5_9_9_9_REV) + internalFormat = _gl.RGB9_E5; + } + if (glFormat === _gl.RGBA) { + const transfer = forceLinearTransfer ? LinearTransfer2 : ColorManagement2.getTransfer(colorSpace); + if (glType === _gl.FLOAT) + internalFormat = _gl.RGBA32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.RGBA16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = transfer === SRGBTransfer2 ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) + internalFormat = _gl.RGBA4; + if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) + internalFormat = _gl.RGB5_A1; + } + if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) { + extensions.get("EXT_color_buffer_float"); + } + return internalFormat; + } + function getInternalDepthFormat(useStencil, depthType) { + let glInternalFormat; + if (useStencil) { + if (depthType === null || depthType === UnsignedIntType2 || depthType === UnsignedInt248Type2) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + } else if (depthType === FloatType2) { + glInternalFormat = _gl.DEPTH32F_STENCIL8; + } else if (depthType === UnsignedShortType2) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment."); + } + } else { + if (depthType === null || depthType === UnsignedIntType2 || depthType === UnsignedInt248Type2) { + glInternalFormat = _gl.DEPTH_COMPONENT24; + } else if (depthType === FloatType2) { + glInternalFormat = _gl.DEPTH_COMPONENT32F; + } else if (depthType === UnsignedShortType2) { + glInternalFormat = _gl.DEPTH_COMPONENT16; + } + } + return glInternalFormat; + } + function getMipLevels(texture, image) { + if (textureNeedsGenerateMipmaps(texture) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter2 && texture.minFilter !== LinearFilter2) { + return Math.log2(Math.max(image.width, image.height)) + 1; + } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) { + return texture.mipmaps.length; + } else if (texture.isCompressedTexture && Array.isArray(texture.image)) { + return image.mipmaps.length; + } else { + return 1; + } + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + deallocateTexture(texture); + if (texture.isVideoTexture) { + _videoTextures.delete(texture); + } + } + function onRenderTargetDispose(event) { + const renderTarget = event.target; + renderTarget.removeEventListener("dispose", onRenderTargetDispose); + deallocateRenderTarget(renderTarget); + } + function deallocateTexture(texture) { + const textureProperties = properties.get(texture); + if (textureProperties.__webglInit === undefined) + return; + const source = texture.source; + const webglTextures = _sources.get(source); + if (webglTextures) { + const webglTexture = webglTextures[textureProperties.__cacheKey]; + webglTexture.usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + if (Object.keys(webglTextures).length === 0) { + _sources.delete(source); + } + } + properties.remove(texture); + } + function deleteTexture(texture) { + const textureProperties = properties.get(texture); + _gl.deleteTexture(textureProperties.__webglTexture); + const source = texture.source; + const webglTextures = _sources.get(source); + delete webglTextures[textureProperties.__cacheKey]; + info.memory.textures--; + } + function deallocateRenderTarget(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTarget.depthTexture) { + renderTarget.depthTexture.dispose(); + properties.remove(renderTarget.depthTexture); + } + if (renderTarget.isWebGLCubeRenderTarget) { + for (let i = 0;i < 6; i++) { + if (Array.isArray(renderTargetProperties.__webglFramebuffer[i])) { + for (let level = 0;level < renderTargetProperties.__webglFramebuffer[i].length; level++) + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i][level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]); + } + if (renderTargetProperties.__webglDepthbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]); + } + } else { + if (Array.isArray(renderTargetProperties.__webglFramebuffer)) { + for (let level = 0;level < renderTargetProperties.__webglFramebuffer.length; level++) + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer); + } + if (renderTargetProperties.__webglDepthbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer); + if (renderTargetProperties.__webglMultisampledFramebuffer) + _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer); + if (renderTargetProperties.__webglColorRenderbuffer) { + for (let i = 0;i < renderTargetProperties.__webglColorRenderbuffer.length; i++) { + if (renderTargetProperties.__webglColorRenderbuffer[i]) + _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]); + } + } + if (renderTargetProperties.__webglDepthRenderbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer); + } + const textures = renderTarget.textures; + for (let i = 0, il = textures.length;i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture) { + _gl.deleteTexture(attachmentProperties.__webglTexture); + info.memory.textures--; + } + properties.remove(textures[i]); + } + properties.remove(renderTarget); + } + let textureUnits = 0; + function resetTextureUnits() { + textureUnits = 0; + } + function allocateTextureUnit() { + const textureUnit = textureUnits; + if (textureUnit >= capabilities.maxTextures) { + console.warn("THREE.WebGLTextures: Trying to use " + textureUnit + " texture units while this GPU supports only " + capabilities.maxTextures); + } + textureUnits += 1; + return textureUnit; + } + function getTextureCacheKey(texture) { + const array = []; + array.push(texture.wrapS); + array.push(texture.wrapT); + array.push(texture.wrapR || 0); + array.push(texture.magFilter); + array.push(texture.minFilter); + array.push(texture.anisotropy); + array.push(texture.internalFormat); + array.push(texture.format); + array.push(texture.type); + array.push(texture.generateMipmaps); + array.push(texture.premultiplyAlpha); + array.push(texture.flipY); + array.push(texture.unpackAlignment); + array.push(texture.colorSpace); + return array.join(); + } + function setTexture2D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isVideoTexture) + updateVideoTexture(texture); + if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { + const image = texture.image; + if (image === null) { + console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found."); + } else if (image.complete === false) { + console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete"); + } else { + uploadTexture(textureProperties, texture, slot); + return; + } + } + state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture2DArray(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture3D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTextureCube(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadCubeTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + const wrappingToGL = { + [RepeatWrapping2]: _gl.REPEAT, + [ClampToEdgeWrapping2]: _gl.CLAMP_TO_EDGE, + [MirroredRepeatWrapping2]: _gl.MIRRORED_REPEAT + }; + const filterToGL = { + [NearestFilter2]: _gl.NEAREST, + [NearestMipmapNearestFilter2]: _gl.NEAREST_MIPMAP_NEAREST, + [NearestMipmapLinearFilter2]: _gl.NEAREST_MIPMAP_LINEAR, + [LinearFilter2]: _gl.LINEAR, + [LinearMipmapNearestFilter2]: _gl.LINEAR_MIPMAP_NEAREST, + [LinearMipmapLinearFilter2]: _gl.LINEAR_MIPMAP_LINEAR + }; + const compareToGL = { + [NeverCompare2]: _gl.NEVER, + [AlwaysCompare2]: _gl.ALWAYS, + [LessCompare2]: _gl.LESS, + [LessEqualCompare2]: _gl.LEQUAL, + [EqualCompare2]: _gl.EQUAL, + [GreaterEqualCompare2]: _gl.GEQUAL, + [GreaterCompare2]: _gl.GREATER, + [NotEqualCompare2]: _gl.NOTEQUAL + }; + function setTextureParameters(textureType, texture) { + if (texture.type === FloatType2 && extensions.has("OES_texture_float_linear") === false && (texture.magFilter === LinearFilter2 || texture.magFilter === LinearMipmapNearestFilter2 || texture.magFilter === NearestMipmapLinearFilter2 || texture.magFilter === LinearMipmapLinearFilter2 || texture.minFilter === LinearFilter2 || texture.minFilter === LinearMipmapNearestFilter2 || texture.minFilter === NearestMipmapLinearFilter2 || texture.minFilter === LinearMipmapLinearFilter2)) { + console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."); + } + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]); + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]); + if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) { + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]); + } + _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]); + _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]); + if (texture.compareFunction) { + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE); + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[texture.compareFunction]); + } + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + if (texture.magFilter === NearestFilter2) + return; + if (texture.minFilter !== NearestMipmapLinearFilter2 && texture.minFilter !== LinearMipmapLinearFilter2) + return; + if (texture.type === FloatType2 && extensions.has("OES_texture_float_linear") === false) + return; + if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy())); + properties.get(texture).__currentAnisotropy = texture.anisotropy; + } + } + } + function initTexture(textureProperties, texture) { + let forceUpload = false; + if (textureProperties.__webglInit === undefined) { + textureProperties.__webglInit = true; + texture.addEventListener("dispose", onTextureDispose); + } + const source = texture.source; + let webglTextures = _sources.get(source); + if (webglTextures === undefined) { + webglTextures = {}; + _sources.set(source, webglTextures); + } + const textureCacheKey = getTextureCacheKey(texture); + if (textureCacheKey !== textureProperties.__cacheKey) { + if (webglTextures[textureCacheKey] === undefined) { + webglTextures[textureCacheKey] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + info.memory.textures++; + forceUpload = true; + } + webglTextures[textureCacheKey].usedTimes++; + const webglTexture = webglTextures[textureProperties.__cacheKey]; + if (webglTexture !== undefined) { + webglTextures[textureProperties.__cacheKey].usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + } + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[textureCacheKey].texture; + } + return forceUpload; + } + function uploadTexture(textureProperties, texture, slot) { + let textureType = _gl.TEXTURE_2D; + if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) + textureType = _gl.TEXTURE_2D_ARRAY; + if (texture.isData3DTexture) + textureType = _gl.TEXTURE_3D; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement2.getPrimaries(ColorManagement2.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace2 ? null : ColorManagement2.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace2 || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + let image = resizeImage(texture.image, false, capabilities.maxTextureSize); + image = verifyColorSpace(texture, image); + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + let glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture); + setTextureParameters(textureType, texture); + let mipmap; + const mipmaps = texture.mipmaps; + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; + const dataReady = source.dataReady; + const levels = getMipLevels(texture, image); + if (texture.isDepthTexture) { + glInternalFormat = getInternalDepthFormat(texture.format === DepthStencilFormat2, texture.type); + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height); + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null); + } + } + } else if (texture.isDataTexture) { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data); + } + } + } else if (texture.isCompressedTexture) { + if (texture.isCompressedArrayTexture) { + if (useTexStorage && allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat2) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength2(mipmap.width, mipmap.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = mipmap.data.subarray(layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT, (layerIndex + 1) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT); + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData); + } + texture.clearLayerUpdates(); + } else { + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data); + } + } + } else { + state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data); + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data); + } + } + } + } else { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat2) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else if (texture.isDataArrayTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength2(image.width, image.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = image.data.subarray(layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT, (layerIndex + 1) * layerByteLength / image.data.BYTES_PER_ELEMENT); + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData); + } + texture.clearLayerUpdates(); + } else { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isData3DTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } else { + state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isFramebufferTexture) { + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } else { + let { width: width2, height: height2 } = image; + for (let i = 0;i < levels; i++) { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width2, height2, 0, glFormat, glType, null); + width2 >>= 1; + height2 >>= 1; + } + } + } + } else { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + const dimensions = getDimensions(mipmaps[0]); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + const dimensions = getDimensions(image); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image); + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(textureType); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) + texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function uploadCubeTexture(textureProperties, texture, slot) { + if (texture.image.length !== 6) + return; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement2.getPrimaries(ColorManagement2.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace2 ? null : ColorManagement2.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace2 || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture; + const isDataTexture = texture.image[0] && texture.image[0].isDataTexture; + const cubeImage = []; + for (let i = 0;i < 6; i++) { + if (!isCompressed && !isDataTexture) { + cubeImage[i] = resizeImage(texture.image[i], true, capabilities.maxCubemapSize); + } else { + cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i]; + } + cubeImage[i] = verifyColorSpace(texture, cubeImage[i]); + } + const image = cubeImage[0], glFormat = utils.convert(texture.format, texture.colorSpace), glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; + const dataReady = source.dataReady; + let levels = getMipLevels(texture, image); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + let mipmaps; + if (isCompressed) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height); + } + for (let i = 0;i < 6; i++) { + mipmaps = cubeImage[i].mipmaps; + for (let j = 0;j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + if (texture.format !== RGBAFormat2) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else { + mipmaps = texture.mipmaps; + if (useTexStorage && allocateMemory) { + if (mipmaps.length > 0) + levels++; + const dimensions = getDimensions(cubeImage[0]); + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0;i < 6; i++) { + if (isDataTexture) { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data); + } + for (let j = 0;j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + const mipmapImage = mipmap.image[i].image; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data); + } + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]); + } + for (let j = 0;j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]); + } + } + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) + texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget, level) { + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + textureProperties.__renderTarget = renderTarget; + if (!renderTargetProperties.__hasExternalTextures) { + const width2 = Math.max(1, renderTarget.width >> level); + const height2 = Math.max(1, renderTarget.height >> level); + if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) { + state.texImage3D(textureTarget, level, glInternalFormat, width2, height2, renderTarget.depth, 0, glFormat, glType, null); + } else { + state.texImage2D(textureTarget, level, glInternalFormat, width2, height2, 0, glFormat, glType, null); + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples(renderTarget)); + } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) { + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null; + const glInternalFormat = getInternalDepthFormat(renderTarget.stencilBuffer, depthType); + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const samples = getRenderTargetSamples(renderTarget); + const isUseMultisampledRTT = useMultisampledRTT(renderTarget); + if (isUseMultisampledRTT) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (isMultisample) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } else { + const textures = renderTarget.textures; + for (let i = 0;i < textures.length; i++) { + const texture = textures[i]; + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const samples = getRenderTargetSamples(renderTarget); + if (isMultisample && useMultisampledRTT(renderTarget) === false) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + } + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + } + function setupDepthTexture(framebuffer, renderTarget) { + const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget; + if (isCube) + throw new Error("Depth Texture with cube render targets is not supported"); + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) { + throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); + } + const textureProperties = properties.get(renderTarget.depthTexture); + textureProperties.__renderTarget = renderTarget; + if (!textureProperties.__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) { + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + } + setTexture2D(renderTarget.depthTexture, 0); + const webglDepthTexture = textureProperties.__webglTexture; + const samples = getRenderTargetSamples(renderTarget); + if (renderTarget.depthTexture.format === DepthFormat2) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else if (renderTarget.depthTexture.format === DepthStencilFormat2) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else { + throw new Error("Unknown depthTexture format"); + } + } + function setupDepthRenderbuffer(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + if (renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__depthDisposeCallback) { + renderTargetProperties.__depthDisposeCallback(); + } + if (depthTexture) { + const disposeEvent = () => { + delete renderTargetProperties.__boundDepthTexture; + delete renderTargetProperties.__depthDisposeCallback; + depthTexture.removeEventListener("dispose", disposeEvent); + }; + depthTexture.addEventListener("dispose", disposeEvent); + renderTargetProperties.__depthDisposeCallback = disposeEvent; + } + renderTargetProperties.__boundDepthTexture = depthTexture; + } + if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) { + if (isCube) + throw new Error("target.depthTexture not supported in Cube render targets"); + setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget); + } else { + if (isCube) { + renderTargetProperties.__webglDepthbuffer = []; + for (let i = 0;i < 6; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]); + if (renderTargetProperties.__webglDepthbuffer[i] === undefined) { + renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer[i]; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } else { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + if (renderTargetProperties.__webglDepthbuffer === undefined) { + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function rebindTextures(renderTarget, colorTexture, depthTexture) { + const renderTargetProperties = properties.get(renderTarget); + if (colorTexture !== undefined) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0); + } + if (depthTexture !== undefined) { + setupDepthRenderbuffer(renderTarget); + } + } + function setupRenderTarget(renderTarget) { + const texture = renderTarget.texture; + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + renderTarget.addEventListener("dispose", onRenderTargetDispose); + const textures = renderTarget.textures; + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + const isMultipleRenderTargets = textures.length > 1; + if (!isMultipleRenderTargets) { + if (textureProperties.__webglTexture === undefined) { + textureProperties.__webglTexture = _gl.createTexture(); + } + textureProperties.__version = texture.version; + info.memory.textures++; + } + if (isCube) { + renderTargetProperties.__webglFramebuffer = []; + for (let i = 0;i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer[i] = []; + for (let level = 0;level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[i][level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer(); + } + } + } else { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer = []; + for (let level = 0;level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + } + if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length;i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture === undefined) { + attachmentProperties.__webglTexture = _gl.createTexture(); + info.memory.textures++; + } + } + } + if (renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + for (let i = 0;i < textures.length; i++) { + const texture2 = textures[i]; + renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer(); + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const glFormat = utils.convert(texture2.format, texture2.colorSpace); + const glType = utils.convert(texture2.type); + const glInternalFormat = getInternalFormat(texture2.internalFormat, glFormat, glType, texture2.colorSpace, renderTarget.isXRRenderTarget === true); + const samples = getRenderTargetSamples(renderTarget); + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + if (renderTarget.depthBuffer) { + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + } + if (isCube) { + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + for (let i = 0;i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0;level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i][level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0); + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + state.unbindTexture(); + } else if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length;i < il; i++) { + const attachment = textures[i]; + const attachmentProperties = properties.get(attachment); + state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_2D, attachment); + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0); + if (textureNeedsGenerateMipmaps(attachment)) { + generateMipmap(_gl.TEXTURE_2D); + } + } + state.unbindTexture(); + } else { + let glTextureType = _gl.TEXTURE_2D; + if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + } + state.bindTexture(glTextureType, textureProperties.__webglTexture); + setTextureParameters(glTextureType, texture); + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0;level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0); + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(glTextureType); + } + state.unbindTexture(); + } + if (renderTarget.depthBuffer) { + setupDepthRenderbuffer(renderTarget); + } + } + function updateRenderTargetMipmap(renderTarget) { + const textures = renderTarget.textures; + for (let i = 0, il = textures.length;i < il; i++) { + const texture = textures[i]; + if (textureNeedsGenerateMipmaps(texture)) { + const targetType = getTargetType(renderTarget); + const webglTexture = properties.get(texture).__webglTexture; + state.bindTexture(targetType, webglTexture); + generateMipmap(targetType); + state.unbindTexture(); + } + } + } + const invalidationArrayRead = []; + const invalidationArrayDraw = []; + function updateMultisampleRenderTarget(renderTarget) { + if (renderTarget.samples > 0) { + if (useMultisampledRTT(renderTarget) === false) { + const textures = renderTarget.textures; + const width2 = renderTarget.width; + const height2 = renderTarget.height; + let mask2 = _gl.COLOR_BUFFER_BIT; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get(renderTarget); + const isMultipleRenderTargets = textures.length > 1; + if (isMultipleRenderTargets) { + for (let i = 0;i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null); + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + for (let i = 0;i < textures.length; i++) { + if (renderTarget.resolveDepthBuffer) { + if (renderTarget.depthBuffer) + mask2 |= _gl.DEPTH_BUFFER_BIT; + if (renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer) + mask2 |= _gl.STENCIL_BUFFER_BIT; + } + if (isMultipleRenderTargets) { + _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0); + } + _gl.blitFramebuffer(0, 0, width2, height2, 0, 0, width2, height2, mask2, _gl.NEAREST); + if (supportsInvalidateFramebuffer === true) { + invalidationArrayRead.length = 0; + invalidationArrayDraw.length = 0; + invalidationArrayRead.push(_gl.COLOR_ATTACHMENT0 + i); + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false) { + invalidationArrayRead.push(depthStyle); + invalidationArrayDraw.push(depthStyle); + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, invalidationArrayDraw); + } + _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArrayRead); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + if (isMultipleRenderTargets) { + for (let i = 0;i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0); + } + } + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + } else { + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer) { + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]); + } + } + } + } + function getRenderTargetSamples(renderTarget) { + return Math.min(capabilities.maxSamples, renderTarget.samples); + } + function useMultisampledRTT(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + return renderTarget.samples > 0 && extensions.has("WEBGL_multisampled_render_to_texture") === true && renderTargetProperties.__useRenderToTexture !== false; + } + function updateVideoTexture(texture) { + const frame = info.render.frame; + if (_videoTextures.get(texture) !== frame) { + _videoTextures.set(texture, frame); + texture.update(); + } + } + function verifyColorSpace(texture, image) { + const colorSpace = texture.colorSpace; + const format = texture.format; + const type = texture.type; + if (texture.isCompressedTexture === true || texture.isVideoTexture === true) + return image; + if (colorSpace !== LinearSRGBColorSpace2 && colorSpace !== NoColorSpace2) { + if (ColorManagement2.getTransfer(colorSpace) === SRGBTransfer2) { + if (format !== RGBAFormat2 || type !== UnsignedByteType2) { + console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."); + } + } else { + console.error("THREE.WebGLTextures: Unsupported texture color space:", colorSpace); + } + } + return image; + } + function getDimensions(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement) { + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + } else if (typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + } else { + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + } + return _imageDimensions; + } + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; + } + function WebGLUtils2(gl, extensions) { + function convert(p, colorSpace = NoColorSpace2) { + let extension; + const transfer = ColorManagement2.getTransfer(colorSpace); + if (p === UnsignedByteType2) + return gl.UNSIGNED_BYTE; + if (p === UnsignedShort4444Type2) + return gl.UNSIGNED_SHORT_4_4_4_4; + if (p === UnsignedShort5551Type2) + return gl.UNSIGNED_SHORT_5_5_5_1; + if (p === UnsignedInt5999Type2) + return gl.UNSIGNED_INT_5_9_9_9_REV; + if (p === ByteType2) + return gl.BYTE; + if (p === ShortType2) + return gl.SHORT; + if (p === UnsignedShortType2) + return gl.UNSIGNED_SHORT; + if (p === IntType2) + return gl.INT; + if (p === UnsignedIntType2) + return gl.UNSIGNED_INT; + if (p === FloatType2) + return gl.FLOAT; + if (p === HalfFloatType2) + return gl.HALF_FLOAT; + if (p === AlphaFormat2) + return gl.ALPHA; + if (p === RGBFormat2) + return gl.RGB; + if (p === RGBAFormat2) + return gl.RGBA; + if (p === LuminanceFormat2) + return gl.LUMINANCE; + if (p === LuminanceAlphaFormat2) + return gl.LUMINANCE_ALPHA; + if (p === DepthFormat2) + return gl.DEPTH_COMPONENT; + if (p === DepthStencilFormat2) + return gl.DEPTH_STENCIL; + if (p === RedFormat2) + return gl.RED; + if (p === RedIntegerFormat2) + return gl.RED_INTEGER; + if (p === RGFormat2) + return gl.RG; + if (p === RGIntegerFormat2) + return gl.RG_INTEGER; + if (p === RGBAIntegerFormat2) + return gl.RGBA_INTEGER; + if (p === RGB_S3TC_DXT1_Format2 || p === RGBA_S3TC_DXT1_Format2 || p === RGBA_S3TC_DXT3_Format2 || p === RGBA_S3TC_DXT5_Format2) { + if (transfer === SRGBTransfer2) { + extension = extensions.get("WEBGL_compressed_texture_s3tc_srgb"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format2) + return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format2) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format2) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format2) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + } else { + return null; + } + } else { + extension = extensions.get("WEBGL_compressed_texture_s3tc"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format2) + return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format2) + return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format2) + return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format2) + return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + } else { + return null; + } + } + } + if (p === RGB_PVRTC_4BPPV1_Format2 || p === RGB_PVRTC_2BPPV1_Format2 || p === RGBA_PVRTC_4BPPV1_Format2 || p === RGBA_PVRTC_2BPPV1_Format2) { + extension = extensions.get("WEBGL_compressed_texture_pvrtc"); + if (extension !== null) { + if (p === RGB_PVRTC_4BPPV1_Format2) + return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if (p === RGB_PVRTC_2BPPV1_Format2) + return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if (p === RGBA_PVRTC_4BPPV1_Format2) + return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if (p === RGBA_PVRTC_2BPPV1_Format2) + return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + } else { + return null; + } + } + if (p === RGB_ETC1_Format2 || p === RGB_ETC2_Format2 || p === RGBA_ETC2_EAC_Format2) { + extension = extensions.get("WEBGL_compressed_texture_etc"); + if (extension !== null) { + if (p === RGB_ETC1_Format2 || p === RGB_ETC2_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if (p === RGBA_ETC2_EAC_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + } else { + return null; + } + } + if (p === RGBA_ASTC_4x4_Format2 || p === RGBA_ASTC_5x4_Format2 || p === RGBA_ASTC_5x5_Format2 || p === RGBA_ASTC_6x5_Format2 || p === RGBA_ASTC_6x6_Format2 || p === RGBA_ASTC_8x5_Format2 || p === RGBA_ASTC_8x6_Format2 || p === RGBA_ASTC_8x8_Format2 || p === RGBA_ASTC_10x5_Format2 || p === RGBA_ASTC_10x6_Format2 || p === RGBA_ASTC_10x8_Format2 || p === RGBA_ASTC_10x10_Format2 || p === RGBA_ASTC_12x10_Format2 || p === RGBA_ASTC_12x12_Format2) { + extension = extensions.get("WEBGL_compressed_texture_astc"); + if (extension !== null) { + if (p === RGBA_ASTC_4x4_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if (p === RGBA_ASTC_5x4_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if (p === RGBA_ASTC_5x5_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if (p === RGBA_ASTC_6x5_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if (p === RGBA_ASTC_6x6_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if (p === RGBA_ASTC_8x5_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if (p === RGBA_ASTC_8x6_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if (p === RGBA_ASTC_8x8_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if (p === RGBA_ASTC_10x5_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if (p === RGBA_ASTC_10x6_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if (p === RGBA_ASTC_10x8_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if (p === RGBA_ASTC_10x10_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if (p === RGBA_ASTC_12x10_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if (p === RGBA_ASTC_12x12_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + } else { + return null; + } + } + if (p === RGBA_BPTC_Format2 || p === RGB_BPTC_SIGNED_Format2 || p === RGB_BPTC_UNSIGNED_Format2) { + extension = extensions.get("EXT_texture_compression_bptc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + if (p === RGB_BPTC_SIGNED_Format2) + return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; + if (p === RGB_BPTC_UNSIGNED_Format2) + return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; + } else { + return null; + } + } + if (p === RED_RGTC1_Format2 || p === SIGNED_RED_RGTC1_Format2 || p === RED_GREEN_RGTC2_Format2 || p === SIGNED_RED_GREEN_RGTC2_Format2) { + extension = extensions.get("EXT_texture_compression_rgtc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format2) + return extension.COMPRESSED_RED_RGTC1_EXT; + if (p === SIGNED_RED_RGTC1_Format2) + return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if (p === RED_GREEN_RGTC2_Format2) + return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if (p === SIGNED_RED_GREEN_RGTC2_Format2) + return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + } else { + return null; + } + } + if (p === UnsignedInt248Type2) + return gl.UNSIGNED_INT_24_8; + return gl[p] !== undefined ? gl[p] : null; + } + return { convert }; + } + var _occlusion_vertex2 = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; + var _occlusion_fragment2 = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; + + class WebXRDepthSensing2 { + constructor() { + this.texture = null; + this.mesh = null; + this.depthNear = 0; + this.depthFar = 0; + } + init(renderer2, depthData, renderState) { + if (this.texture === null) { + const texture = new Texture2; + const texProps = renderer2.properties.get(texture); + texProps.__webglTexture = depthData.texture; + if (depthData.depthNear !== renderState.depthNear || depthData.depthFar !== renderState.depthFar) { + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + } + this.texture = texture; + } + } + getMesh(cameraXR) { + if (this.texture !== null) { + if (this.mesh === null) { + const viewport = cameraXR.cameras[0].viewport; + const material = new ShaderMaterial2({ + vertexShader: _occlusion_vertex2, + fragmentShader: _occlusion_fragment2, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + }); + this.mesh = new Mesh2(new PlaneGeometry2(20, 20), material); + } + } + return this.mesh; + } + reset() { + this.texture = null; + this.mesh = null; + } + getDepthTexture() { + return this.texture; + } + } + + class WebXRManager2 extends EventDispatcher2 { + constructor(renderer2, gl) { + super(); + const scope = this; + let session = null; + let framebufferScaleFactor = 1; + let referenceSpace = null; + let referenceSpaceType = "local-floor"; + let foveation = 1; + let customReferenceSpace = null; + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const depthSensing = new WebXRDepthSensing2; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + const controllers = []; + const controllerInputSources = []; + const currentSize = new Vector22; + let currentPixelRatio = null; + const cameraL = new PerspectiveCamera2; + cameraL.viewport = new Vector42; + const cameraR = new PerspectiveCamera2; + cameraR.viewport = new Vector42; + const cameras = [cameraL, cameraR]; + const cameraXR = new ArrayCamera2; + let _currentDepthNear = null; + let _currentDepthFar = null; + this.cameraAutoUpdate = true; + this.enabled = false; + this.isPresenting = false; + this.getController = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController2; + controllers[index2] = controller; + } + return controller.getTargetRaySpace(); + }; + this.getControllerGrip = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController2; + controllers[index2] = controller; + } + return controller.getGripSpace(); + }; + this.getHand = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController2; + controllers[index2] = controller; + } + return controller.getHandSpace(); + }; + function onSessionEvent(event) { + const controllerIndex = controllerInputSources.indexOf(event.inputSource); + if (controllerIndex === -1) { + return; + } + const controller = controllers[controllerIndex]; + if (controller !== undefined) { + controller.update(event.inputSource, event.frame, customReferenceSpace || referenceSpace); + controller.dispatchEvent({ type: event.type, data: event.inputSource }); + } + } + function onSessionEnd() { + session.removeEventListener("select", onSessionEvent); + session.removeEventListener("selectstart", onSessionEvent); + session.removeEventListener("selectend", onSessionEvent); + session.removeEventListener("squeeze", onSessionEvent); + session.removeEventListener("squeezestart", onSessionEvent); + session.removeEventListener("squeezeend", onSessionEvent); + session.removeEventListener("end", onSessionEnd); + session.removeEventListener("inputsourceschange", onInputSourcesChange); + for (let i = 0;i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + if (inputSource === null) + continue; + controllerInputSources[i] = null; + controllers[i].disconnect(inputSource); + } + _currentDepthNear = null; + _currentDepthFar = null; + depthSensing.reset(); + renderer2.setRenderTarget(initialRenderTarget); + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + animation.stop(); + scope.isPresenting = false; + renderer2.setPixelRatio(currentPixelRatio); + renderer2.setSize(currentSize.width, currentSize.height, false); + scope.dispatchEvent({ type: "sessionend" }); + } + this.setFramebufferScaleFactor = function(value2) { + framebufferScaleFactor = value2; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting."); + } + }; + this.setReferenceSpaceType = function(value2) { + referenceSpaceType = value2; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change reference space type while presenting."); + } + }; + this.getReferenceSpace = function() { + return customReferenceSpace || referenceSpace; + }; + this.setReferenceSpace = function(space) { + customReferenceSpace = space; + }; + this.getBaseLayer = function() { + return glProjLayer !== null ? glProjLayer : glBaseLayer; + }; + this.getBinding = function() { + return glBinding; + }; + this.getFrame = function() { + return xrFrame; + }; + this.getSession = function() { + return session; + }; + this.setSession = async function(value2) { + session = value2; + if (session !== null) { + initialRenderTarget = renderer2.getRenderTarget(); + session.addEventListener("select", onSessionEvent); + session.addEventListener("selectstart", onSessionEvent); + session.addEventListener("selectend", onSessionEvent); + session.addEventListener("squeeze", onSessionEvent); + session.addEventListener("squeezestart", onSessionEvent); + session.addEventListener("squeezeend", onSessionEvent); + session.addEventListener("end", onSessionEnd); + session.addEventListener("inputsourceschange", onInputSourcesChange); + if (attributes.xrCompatible !== true) { + await gl.makeXRCompatible(); + } + currentPixelRatio = renderer2.getPixelRatio(); + renderer2.getSize(currentSize); + const useLayers = typeof XRWebGLBinding !== "undefined" && "createProjectionLayer" in XRWebGLBinding.prototype; + if (!useLayers) { + const layerInit = { + antialias: attributes.antialias, + alpha: true, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor + }; + glBaseLayer = new XRWebGLLayer(session, gl, layerInit); + session.updateRenderState({ baseLayer: glBaseLayer }); + renderer2.setPixelRatio(1); + renderer2.setSize(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false); + newRenderTarget = new WebGLRenderTarget2(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, { + format: RGBAFormat2, + type: UnsignedByteType2, + colorSpace: renderer2.outputColorSpace, + stencilBuffer: attributes.stencil + }); + } else { + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + if (attributes.depth) { + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat2 : DepthFormat2; + depthType = attributes.stencil ? UnsignedInt248Type2 : UnsignedIntType2; + } + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + glBinding = new XRWebGLBinding(session, gl); + glProjLayer = glBinding.createProjectionLayer(projectionlayerInit); + session.updateRenderState({ layers: [glProjLayer] }); + renderer2.setPixelRatio(1); + renderer2.setSize(glProjLayer.textureWidth, glProjLayer.textureHeight, false); + newRenderTarget = new WebGLRenderTarget2(glProjLayer.textureWidth, glProjLayer.textureHeight, { + format: RGBAFormat2, + type: UnsignedByteType2, + depthTexture: new DepthTexture2(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat), + stencilBuffer: attributes.stencil, + colorSpace: renderer2.outputColorSpace, + samples: attributes.antialias ? 4 : 0, + resolveDepthBuffer: glProjLayer.ignoreDepthValues === false + }); + } + newRenderTarget.isXRRenderTarget = true; + this.setFoveation(foveation); + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace(referenceSpaceType); + animation.setContext(session); + animation.start(); + scope.isPresenting = true; + scope.dispatchEvent({ type: "sessionstart" }); + } + }; + this.getEnvironmentBlendMode = function() { + if (session !== null) { + return session.environmentBlendMode; + } + }; + this.getDepthTexture = function() { + return depthSensing.getDepthTexture(); + }; + function onInputSourcesChange(event) { + for (let i = 0;i < event.removed.length; i++) { + const inputSource = event.removed[i]; + const index2 = controllerInputSources.indexOf(inputSource); + if (index2 >= 0) { + controllerInputSources[index2] = null; + controllers[index2].disconnect(inputSource); + } + } + for (let i = 0;i < event.added.length; i++) { + const inputSource = event.added[i]; + let controllerIndex = controllerInputSources.indexOf(inputSource); + if (controllerIndex === -1) { + for (let i2 = 0;i2 < controllers.length; i2++) { + if (i2 >= controllerInputSources.length) { + controllerInputSources.push(inputSource); + controllerIndex = i2; + break; + } else if (controllerInputSources[i2] === null) { + controllerInputSources[i2] = inputSource; + controllerIndex = i2; + break; + } + } + if (controllerIndex === -1) + break; + } + const controller = controllers[controllerIndex]; + if (controller) { + controller.connect(inputSource); + } + } + } + const cameraLPos = new Vector32; + const cameraRPos = new Vector32; + function setProjectionFromUnion(camera, cameraL2, cameraR2) { + cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld); + cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld); + const ipd = cameraLPos.distanceTo(cameraRPos); + const projL = cameraL2.projectionMatrix.elements; + const projR = cameraR2.projectionMatrix.elements; + const near = projL[14] / (projL[10] - 1); + const far = projL[14] / (projL[10] + 1); + const topFov = (projL[9] + 1) / projL[5]; + const bottomFov = (projL[9] - 1) / projL[5]; + const leftFov = (projL[8] - 1) / projL[0]; + const rightFov = (projR[8] + 1) / projR[0]; + const left = near * leftFov; + const right = near * rightFov; + const zOffset = ipd / (-leftFov + rightFov); + const xOffset = zOffset * -leftFov; + cameraL2.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale); + camera.translateX(xOffset); + camera.translateZ(zOffset); + camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale); + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + if (projL[10] === -1) { + camera.projectionMatrix.copy(cameraL2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraL2.projectionMatrixInverse); + } else { + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + (ipd - xOffset); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + } + } + function updateCamera(camera, parent2) { + if (parent2 === null) { + camera.matrixWorld.copy(camera.matrix); + } else { + camera.matrixWorld.multiplyMatrices(parent2.matrixWorld, camera.matrix); + } + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + } + this.updateCamera = function(camera) { + if (session === null) + return; + let depthNear = camera.near; + let depthFar = camera.far; + if (depthSensing.texture !== null) { + if (depthSensing.depthNear > 0) + depthNear = depthSensing.depthNear; + if (depthSensing.depthFar > 0) + depthFar = depthSensing.depthFar; + } + cameraXR.near = cameraR.near = cameraL.near = depthNear; + cameraXR.far = cameraR.far = cameraL.far = depthFar; + if (_currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far) { + session.updateRenderState({ + depthNear: cameraXR.near, + depthFar: cameraXR.far + }); + _currentDepthNear = cameraXR.near; + _currentDepthFar = cameraXR.far; + } + cameraL.layers.mask = camera.layers.mask | 2; + cameraR.layers.mask = camera.layers.mask | 4; + cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask; + const parent2 = camera.parent; + const cameras2 = cameraXR.cameras; + updateCamera(cameraXR, parent2); + for (let i = 0;i < cameras2.length; i++) { + updateCamera(cameras2[i], parent2); + } + if (cameras2.length === 2) { + setProjectionFromUnion(cameraXR, cameraL, cameraR); + } else { + cameraXR.projectionMatrix.copy(cameraL.projectionMatrix); + } + updateUserCamera(camera, cameraXR, parent2); + }; + function updateUserCamera(camera, cameraXR2, parent2) { + if (parent2 === null) { + camera.matrix.copy(cameraXR2.matrixWorld); + } else { + camera.matrix.copy(parent2.matrixWorld); + camera.matrix.invert(); + camera.matrix.multiply(cameraXR2.matrixWorld); + } + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.updateMatrixWorld(true); + camera.projectionMatrix.copy(cameraXR2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraXR2.projectionMatrixInverse); + if (camera.isPerspectiveCamera) { + camera.fov = RAD2DEG2 * 2 * Math.atan(1 / camera.projectionMatrix.elements[5]); + camera.zoom = 1; + } + } + this.getCamera = function() { + return cameraXR; + }; + this.getFoveation = function() { + if (glProjLayer === null && glBaseLayer === null) { + return; + } + return foveation; + }; + this.setFoveation = function(value2) { + foveation = value2; + if (glProjLayer !== null) { + glProjLayer.fixedFoveation = value2; + } + if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) { + glBaseLayer.fixedFoveation = value2; + } + }; + this.hasDepthSensing = function() { + return depthSensing.texture !== null; + }; + this.getDepthSensingMesh = function() { + return depthSensing.getMesh(cameraXR); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time2, frame) { + pose = frame.getViewerPose(customReferenceSpace || referenceSpace); + xrFrame = frame; + if (pose !== null) { + const views = pose.views; + if (glBaseLayer !== null) { + renderer2.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer); + renderer2.setRenderTarget(newRenderTarget); + } + let cameraXRNeedsUpdate = false; + if (views.length !== cameraXR.cameras.length) { + cameraXR.cameras.length = 0; + cameraXRNeedsUpdate = true; + } + for (let i = 0;i < views.length; i++) { + const view = views[i]; + let viewport = null; + if (glBaseLayer !== null) { + viewport = glBaseLayer.getViewport(view); + } else { + const glSubImage = glBinding.getViewSubImage(glProjLayer, view); + viewport = glSubImage.viewport; + if (i === 0) { + renderer2.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture); + renderer2.setRenderTarget(newRenderTarget); + } + } + let camera = cameras[i]; + if (camera === undefined) { + camera = new PerspectiveCamera2; + camera.layers.enable(i); + camera.viewport = new Vector42; + cameras[i] = camera; + } + camera.matrix.fromArray(view.transform.matrix); + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.projectionMatrix.fromArray(view.projectionMatrix); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height); + if (i === 0) { + cameraXR.matrix.copy(camera.matrix); + cameraXR.matrix.decompose(cameraXR.position, cameraXR.quaternion, cameraXR.scale); + } + if (cameraXRNeedsUpdate === true) { + cameraXR.cameras.push(camera); + } + } + const enabledFeatures = session.enabledFeatures; + const gpuDepthSensingEnabled = enabledFeatures && enabledFeatures.includes("depth-sensing") && session.depthUsage == "gpu-optimized"; + if (gpuDepthSensingEnabled && glBinding) { + const depthData = glBinding.getDepthInformation(views[0]); + if (depthData && depthData.isValid && depthData.texture) { + depthSensing.init(renderer2, depthData, session.renderState); + } + } + } + for (let i = 0;i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + const controller = controllers[i]; + if (inputSource !== null && controller !== undefined) { + controller.update(inputSource, frame, customReferenceSpace || referenceSpace); + } + } + if (onAnimationFrameCallback) + onAnimationFrameCallback(time2, frame); + if (frame.detectedPlanes) { + scope.dispatchEvent({ type: "planesdetected", data: frame }); + } + xrFrame = null; + } + const animation = new WebGLAnimation2; + animation.setAnimationLoop(onAnimationFrame); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + }; + this.dispose = function() { + }; + } + } + var _e12 = /* @__PURE__ */ new Euler2; + var _m13 = /* @__PURE__ */ new Matrix42; + function WebGLMaterials2(renderer2, properties) { + function refreshTransformUniform(map2, uniform) { + if (map2.matrixAutoUpdate === true) { + map2.updateMatrix(); + } + uniform.value.copy(map2.matrix); + } + function refreshFogUniforms(uniforms, fog) { + fog.color.getRGB(uniforms.fogColor.value, getUnlitUniformColorSpace2(renderer2)); + if (fog.isFog) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + } else if (fog.isFogExp2) { + uniforms.fogDensity.value = fog.density; + } + } + function refreshMaterialUniforms(uniforms, material, pixelRatio, height2, transmissionRenderTarget) { + if (material.isMeshBasicMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshLambertMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshToonMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsToon(uniforms, material); + } else if (material.isMeshPhongMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsPhong(uniforms, material); + } else if (material.isMeshStandardMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsStandard(uniforms, material); + if (material.isMeshPhysicalMaterial) { + refreshUniformsPhysical(uniforms, material, transmissionRenderTarget); + } + } else if (material.isMeshMatcapMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsMatcap(uniforms, material); + } else if (material.isMeshDepthMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshDistanceMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsDistance(uniforms, material); + } else if (material.isMeshNormalMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isLineBasicMaterial) { + refreshUniformsLine(uniforms, material); + if (material.isLineDashedMaterial) { + refreshUniformsDash(uniforms, material); + } + } else if (material.isPointsMaterial) { + refreshUniformsPoints(uniforms, material, pixelRatio, height2); + } else if (material.isSpriteMaterial) { + refreshUniformsSprites(uniforms, material); + } else if (material.isShadowMaterial) { + uniforms.color.value.copy(material.color); + uniforms.opacity.value = material.opacity; + } else if (material.isShaderMaterial) { + material.uniformsNeedUpdate = false; + } + } + function refreshUniformsCommon(uniforms, material) { + uniforms.opacity.value = material.opacity; + if (material.color) { + uniforms.diffuse.value.copy(material.color); + } + if (material.emissive) { + uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity); + } + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.bumpMap) { + uniforms.bumpMap.value = material.bumpMap; + refreshTransformUniform(material.bumpMap, uniforms.bumpMapTransform); + uniforms.bumpScale.value = material.bumpScale; + if (material.side === BackSide2) { + uniforms.bumpScale.value *= -1; + } + } + if (material.normalMap) { + uniforms.normalMap.value = material.normalMap; + refreshTransformUniform(material.normalMap, uniforms.normalMapTransform); + uniforms.normalScale.value.copy(material.normalScale); + if (material.side === BackSide2) { + uniforms.normalScale.value.negate(); + } + } + if (material.displacementMap) { + uniforms.displacementMap.value = material.displacementMap; + refreshTransformUniform(material.displacementMap, uniforms.displacementMapTransform); + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + } + if (material.emissiveMap) { + uniforms.emissiveMap.value = material.emissiveMap; + refreshTransformUniform(material.emissiveMap, uniforms.emissiveMapTransform); + } + if (material.specularMap) { + uniforms.specularMap.value = material.specularMap; + refreshTransformUniform(material.specularMap, uniforms.specularMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + const materialProperties = properties.get(material); + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; + if (envMap) { + uniforms.envMap.value = envMap; + _e12.copy(envMapRotation); + _e12.x *= -1; + _e12.y *= -1; + _e12.z *= -1; + if (envMap.isCubeTexture && envMap.isRenderTargetTexture === false) { + _e12.y *= -1; + _e12.z *= -1; + } + uniforms.envMapRotation.value.setFromMatrix4(_m13.makeRotationFromEuler(_e12)); + uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + } + if (material.lightMap) { + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; + refreshTransformUniform(material.lightMap, uniforms.lightMapTransform); + } + if (material.aoMap) { + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + refreshTransformUniform(material.aoMap, uniforms.aoMapTransform); + } + } + function refreshUniformsLine(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + } + function refreshUniformsDash(uniforms, material) { + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + } + function refreshUniformsPoints(uniforms, material, pixelRatio, height2) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height2 * 0.5; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.uvTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsSprites(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsPhong(uniforms, material) { + uniforms.specular.value.copy(material.specular); + uniforms.shininess.value = Math.max(material.shininess, 0.0001); + } + function refreshUniformsToon(uniforms, material) { + if (material.gradientMap) { + uniforms.gradientMap.value = material.gradientMap; + } + } + function refreshUniformsStandard(uniforms, material) { + uniforms.metalness.value = material.metalness; + if (material.metalnessMap) { + uniforms.metalnessMap.value = material.metalnessMap; + refreshTransformUniform(material.metalnessMap, uniforms.metalnessMapTransform); + } + uniforms.roughness.value = material.roughness; + if (material.roughnessMap) { + uniforms.roughnessMap.value = material.roughnessMap; + refreshTransformUniform(material.roughnessMap, uniforms.roughnessMapTransform); + } + if (material.envMap) { + uniforms.envMapIntensity.value = material.envMapIntensity; + } + } + function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) { + uniforms.ior.value = material.ior; + if (material.sheen > 0) { + uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen); + uniforms.sheenRoughness.value = material.sheenRoughness; + if (material.sheenColorMap) { + uniforms.sheenColorMap.value = material.sheenColorMap; + refreshTransformUniform(material.sheenColorMap, uniforms.sheenColorMapTransform); + } + if (material.sheenRoughnessMap) { + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + refreshTransformUniform(material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform); + } + } + if (material.clearcoat > 0) { + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + if (material.clearcoatMap) { + uniforms.clearcoatMap.value = material.clearcoatMap; + refreshTransformUniform(material.clearcoatMap, uniforms.clearcoatMapTransform); + } + if (material.clearcoatRoughnessMap) { + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + refreshTransformUniform(material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform); + } + if (material.clearcoatNormalMap) { + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + refreshTransformUniform(material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform); + uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale); + if (material.side === BackSide2) { + uniforms.clearcoatNormalScale.value.negate(); + } + } + } + if (material.dispersion > 0) { + uniforms.dispersion.value = material.dispersion; + } + if (material.iridescence > 0) { + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1]; + if (material.iridescenceMap) { + uniforms.iridescenceMap.value = material.iridescenceMap; + refreshTransformUniform(material.iridescenceMap, uniforms.iridescenceMapTransform); + } + if (material.iridescenceThicknessMap) { + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + refreshTransformUniform(material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform); + } + } + if (material.transmission > 0) { + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height); + if (material.transmissionMap) { + uniforms.transmissionMap.value = material.transmissionMap; + refreshTransformUniform(material.transmissionMap, uniforms.transmissionMapTransform); + } + uniforms.thickness.value = material.thickness; + if (material.thicknessMap) { + uniforms.thicknessMap.value = material.thicknessMap; + refreshTransformUniform(material.thicknessMap, uniforms.thicknessMapTransform); + } + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy(material.attenuationColor); + } + if (material.anisotropy > 0) { + uniforms.anisotropyVector.value.set(material.anisotropy * Math.cos(material.anisotropyRotation), material.anisotropy * Math.sin(material.anisotropyRotation)); + if (material.anisotropyMap) { + uniforms.anisotropyMap.value = material.anisotropyMap; + refreshTransformUniform(material.anisotropyMap, uniforms.anisotropyMapTransform); + } + } + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy(material.specularColor); + if (material.specularColorMap) { + uniforms.specularColorMap.value = material.specularColorMap; + refreshTransformUniform(material.specularColorMap, uniforms.specularColorMapTransform); + } + if (material.specularIntensityMap) { + uniforms.specularIntensityMap.value = material.specularIntensityMap; + refreshTransformUniform(material.specularIntensityMap, uniforms.specularIntensityMapTransform); + } + } + function refreshUniformsMatcap(uniforms, material) { + if (material.matcap) { + uniforms.matcap.value = material.matcap; + } + } + function refreshUniformsDistance(uniforms, material) { + const light = properties.get(material).light; + uniforms.referencePosition.value.setFromMatrixPosition(light.matrixWorld); + uniforms.nearDistance.value = light.shadow.camera.near; + uniforms.farDistance.value = light.shadow.camera.far; + } + return { + refreshFogUniforms, + refreshMaterialUniforms + }; + } + function WebGLUniformsGroups2(gl, info, capabilities, state) { + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + const maxBindingPoints = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS); + function bind(uniformsGroup, program) { + const webglProgram = program.program; + state.uniformBlockBinding(uniformsGroup, webglProgram); + } + function update(uniformsGroup, program) { + let buffer = buffers[uniformsGroup.id]; + if (buffer === undefined) { + prepareUniformsGroup(uniformsGroup); + buffer = createBuffer(uniformsGroup); + buffers[uniformsGroup.id] = buffer; + uniformsGroup.addEventListener("dispose", onUniformsGroupsDispose); + } + const webglProgram = program.program; + state.updateUBOMapping(uniformsGroup, webglProgram); + const frame = info.render.frame; + if (updateList[uniformsGroup.id] !== frame) { + updateBufferData(uniformsGroup); + updateList[uniformsGroup.id] = frame; + } + } + function createBuffer(uniformsGroup) { + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + gl.bufferData(gl.UNIFORM_BUFFER, size, usage); + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer); + return buffer; + } + function allocateBindingPointIndex() { + for (let i = 0;i < maxBindingPoints; i++) { + if (allocatedBindingPoints.indexOf(i) === -1) { + allocatedBindingPoints.push(i); + return i; + } + } + console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."); + return 0; + } + function updateBufferData(uniformsGroup) { + const buffer = buffers[uniformsGroup.id]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + for (let i = 0, il = uniforms.length;i < il; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j = 0, jl = uniformArray.length;j < jl; j++) { + const uniform = uniformArray[j]; + if (hasUniformChanged(uniform, i, j, cache) === true) { + const offset = uniform.__offset; + const values2 = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + let arrayOffset = 0; + for (let k = 0;k < values2.length; k++) { + const value2 = values2[k]; + const info2 = getUniformSize(value2); + if (typeof value2 === "number" || typeof value2 === "boolean") { + uniform.__data[0] = value2; + gl.bufferSubData(gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data); + } else if (value2.isMatrix3) { + uniform.__data[0] = value2.elements[0]; + uniform.__data[1] = value2.elements[1]; + uniform.__data[2] = value2.elements[2]; + uniform.__data[3] = 0; + uniform.__data[4] = value2.elements[3]; + uniform.__data[5] = value2.elements[4]; + uniform.__data[6] = value2.elements[5]; + uniform.__data[7] = 0; + uniform.__data[8] = value2.elements[6]; + uniform.__data[9] = value2.elements[7]; + uniform.__data[10] = value2.elements[8]; + uniform.__data[11] = 0; + } else { + value2.toArray(uniform.__data, arrayOffset); + arrayOffset += info2.storage / Float32Array.BYTES_PER_ELEMENT; + } + } + gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data); + } + } + } + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + } + function hasUniformChanged(uniform, index2, indexArray, cache) { + const value2 = uniform.value; + const indexString = index2 + "_" + indexArray; + if (cache[indexString] === undefined) { + if (typeof value2 === "number" || typeof value2 === "boolean") { + cache[indexString] = value2; + } else { + cache[indexString] = value2.clone(); + } + return true; + } else { + const cachedObject = cache[indexString]; + if (typeof value2 === "number" || typeof value2 === "boolean") { + if (cachedObject !== value2) { + cache[indexString] = value2; + return true; + } + } else { + if (cachedObject.equals(value2) === false) { + cachedObject.copy(value2); + return true; + } + } + } + return false; + } + function prepareUniformsGroup(uniformsGroup) { + const uniforms = uniformsGroup.uniforms; + let offset = 0; + const chunkSize = 16; + for (let i = 0, l = uniforms.length;i < l; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j = 0, jl = uniformArray.length;j < jl; j++) { + const uniform = uniformArray[j]; + const values2 = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + for (let k = 0, kl = values2.length;k < kl; k++) { + const value2 = values2[k]; + const info2 = getUniformSize(value2); + const chunkOffset2 = offset % chunkSize; + const chunkPadding = chunkOffset2 % info2.boundary; + const chunkStart = chunkOffset2 + chunkPadding; + offset += chunkPadding; + if (chunkStart !== 0 && chunkSize - chunkStart < info2.storage) { + offset += chunkSize - chunkStart; + } + uniform.__data = new Float32Array(info2.storage / Float32Array.BYTES_PER_ELEMENT); + uniform.__offset = offset; + offset += info2.storage; + } + } + } + const chunkOffset = offset % chunkSize; + if (chunkOffset > 0) + offset += chunkSize - chunkOffset; + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + return this; + } + function getUniformSize(value2) { + const info2 = { + boundary: 0, + storage: 0 + }; + if (typeof value2 === "number" || typeof value2 === "boolean") { + info2.boundary = 4; + info2.storage = 4; + } else if (value2.isVector2) { + info2.boundary = 8; + info2.storage = 8; + } else if (value2.isVector3 || value2.isColor) { + info2.boundary = 16; + info2.storage = 12; + } else if (value2.isVector4) { + info2.boundary = 16; + info2.storage = 16; + } else if (value2.isMatrix3) { + info2.boundary = 48; + info2.storage = 48; + } else if (value2.isMatrix4) { + info2.boundary = 64; + info2.storage = 64; + } else if (value2.isTexture) { + console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."); + } else { + console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", value2); + } + return info2; + } + function onUniformsGroupsDispose(event) { + const uniformsGroup = event.target; + uniformsGroup.removeEventListener("dispose", onUniformsGroupsDispose); + const index2 = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex); + allocatedBindingPoints.splice(index2, 1); + gl.deleteBuffer(buffers[uniformsGroup.id]); + delete buffers[uniformsGroup.id]; + delete updateList[uniformsGroup.id]; + } + function dispose() { + for (const id in buffers) { + gl.deleteBuffer(buffers[id]); + } + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + } + return { + bind, + update, + dispose + }; + } + + class WebGLRenderer2 { + constructor(parameters = {}) { + const { + canvas = createCanvasElement2(), + context = null, + depth = true, + stencil = false, + alpha = false, + antialias = false, + premultipliedAlpha = true, + preserveDrawingBuffer = false, + powerPreference = "default", + failIfMajorPerformanceCaveat = false, + reverseDepthBuffer = false + } = parameters; + this.isWebGLRenderer = true; + let _alpha; + if (context !== null) { + if (typeof WebGLRenderingContext !== "undefined" && context instanceof WebGLRenderingContext) { + throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163."); + } + _alpha = context.getContextAttributes().alpha; + } else { + _alpha = alpha; + } + const uintClearColor = new Uint32Array(4); + const intClearColor = new Int32Array(4); + let currentRenderList = null; + let currentRenderState = null; + const renderListStack = []; + const renderStateStack = []; + this.domElement = canvas; + this.debug = { + checkShaderErrors: true, + onShaderError: null + }; + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + this.sortObjects = true; + this.clippingPlanes = []; + this.localClippingEnabled = false; + this._outputColorSpace = SRGBColorSpace2; + this.toneMapping = NoToneMapping2; + this.toneMappingExposure = 1; + const _this = this; + let _isContextLost = false; + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = -1; + let _currentCamera = null; + const _currentViewport = new Vector42; + const _currentScissor = new Vector42; + let _currentScissorTest = null; + const _currentClearColor = new Color2(0); + let _currentClearAlpha = 0; + let _width = canvas.width; + let _height = canvas.height; + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + const _viewport = new Vector42(0, 0, _width, _height); + const _scissor = new Vector42(0, 0, _width, _height); + let _scissorTest = false; + const _frustum3 = new Frustum2; + let _clippingEnabled = false; + let _localClippingEnabled = false; + this.transmissionResolutionScale = 1; + const _currentProjectionMatrix = new Matrix42; + const _projScreenMatrix3 = new Matrix42; + const _vector33 = new Vector32; + const _vector42 = new Vector42; + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + let _renderBackground = false; + function getTargetPixelRatio() { + return _currentRenderTarget === null ? _pixelRatio : 1; + } + let _gl = context; + function getContext(contextName, contextAttributes) { + return canvas.getContext(contextName, contextAttributes); + } + try { + const contextAttributes = { + alpha: true, + depth, + stencil, + antialias, + premultipliedAlpha, + preserveDrawingBuffer, + powerPreference, + failIfMajorPerformanceCaveat + }; + if ("setAttribute" in canvas) + canvas.setAttribute("data-engine", `three.js r${REVISION2}`); + canvas.addEventListener("webglcontextlost", onContextLost, false); + canvas.addEventListener("webglcontextrestored", onContextRestore, false); + canvas.addEventListener("webglcontextcreationerror", onContextCreationError, false); + if (_gl === null) { + const contextName = "webgl2"; + _gl = getContext(contextName, contextAttributes); + if (_gl === null) { + if (getContext(contextName)) { + throw new Error("Error creating WebGL context with your selected attributes."); + } else { + throw new Error("Error creating WebGL context."); + } + } + } + } catch (error) { + console.error("THREE.WebGLRenderer: " + error.message); + throw error; + } + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + let utils, bindingStates, uniformsGroups; + function initGLContext() { + extensions = new WebGLExtensions2(_gl); + extensions.init(); + utils = new WebGLUtils2(_gl, extensions); + capabilities = new WebGLCapabilities2(_gl, extensions, parameters, utils); + state = new WebGLState2(_gl, extensions); + if (capabilities.reverseDepthBuffer && reverseDepthBuffer) { + state.buffers.depth.setReversed(true); + } + info = new WebGLInfo2(_gl); + properties = new WebGLProperties2; + textures = new WebGLTextures2(_gl, extensions, state, properties, capabilities, utils, info); + cubemaps = new WebGLCubeMaps2(_this); + cubeuvmaps = new WebGLCubeUVMaps2(_this); + attributes = new WebGLAttributes2(_gl); + bindingStates = new WebGLBindingStates2(_gl, attributes); + geometries = new WebGLGeometries2(_gl, attributes, info, bindingStates); + objects = new WebGLObjects2(_gl, geometries, attributes, info); + morphtargets = new WebGLMorphtargets2(_gl, capabilities, textures); + clipping = new WebGLClipping2(properties); + programCache = new WebGLPrograms2(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping); + materials = new WebGLMaterials2(_this, properties); + renderLists = new WebGLRenderLists2; + renderStates = new WebGLRenderStates2(extensions); + background = new WebGLBackground2(_this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha); + shadowMap = new WebGLShadowMap2(_this, objects, capabilities); + uniformsGroups = new WebGLUniformsGroups2(_gl, info, capabilities, state); + bufferRenderer = new WebGLBufferRenderer2(_gl, extensions, info); + indexedBufferRenderer = new WebGLIndexedBufferRenderer2(_gl, extensions, info); + info.programs = programCache.programs; + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; + } + initGLContext(); + const xr = new WebXRManager2(_this, _gl); + this.xr = xr; + this.getContext = function() { + return _gl; + }; + this.getContextAttributes = function() { + return _gl.getContextAttributes(); + }; + this.forceContextLoss = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) + extension.loseContext(); + }; + this.forceContextRestore = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) + extension.restoreContext(); + }; + this.getPixelRatio = function() { + return _pixelRatio; + }; + this.setPixelRatio = function(value2) { + if (value2 === undefined) + return; + _pixelRatio = value2; + this.setSize(_width, _height, false); + }; + this.getSize = function(target) { + return target.set(_width, _height); + }; + this.setSize = function(width2, height2, updateStyle = true) { + if (xr.isPresenting) { + console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."); + return; + } + _width = width2; + _height = height2; + canvas.width = Math.floor(width2 * _pixelRatio); + canvas.height = Math.floor(height2 * _pixelRatio); + if (updateStyle === true) { + canvas.style.width = width2 + "px"; + canvas.style.height = height2 + "px"; + } + this.setViewport(0, 0, width2, height2); + }; + this.getDrawingBufferSize = function(target) { + return target.set(_width * _pixelRatio, _height * _pixelRatio).floor(); + }; + this.setDrawingBufferSize = function(width2, height2, pixelRatio) { + _width = width2; + _height = height2; + _pixelRatio = pixelRatio; + canvas.width = Math.floor(width2 * pixelRatio); + canvas.height = Math.floor(height2 * pixelRatio); + this.setViewport(0, 0, width2, height2); + }; + this.getCurrentViewport = function(target) { + return target.copy(_currentViewport); + }; + this.getViewport = function(target) { + return target.copy(_viewport); + }; + this.setViewport = function(x, y, width2, height2) { + if (x.isVector4) { + _viewport.set(x.x, x.y, x.z, x.w); + } else { + _viewport.set(x, y, width2, height2); + } + state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).round()); + }; + this.getScissor = function(target) { + return target.copy(_scissor); + }; + this.setScissor = function(x, y, width2, height2) { + if (x.isVector4) { + _scissor.set(x.x, x.y, x.z, x.w); + } else { + _scissor.set(x, y, width2, height2); + } + state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).round()); + }; + this.getScissorTest = function() { + return _scissorTest; + }; + this.setScissorTest = function(boolean) { + state.setScissorTest(_scissorTest = boolean); + }; + this.setOpaqueSort = function(method) { + _opaqueSort = method; + }; + this.setTransparentSort = function(method) { + _transparentSort = method; + }; + this.getClearColor = function(target) { + return target.copy(background.getClearColor()); + }; + this.setClearColor = function() { + background.setClearColor.apply(background, arguments); + }; + this.getClearAlpha = function() { + return background.getClearAlpha(); + }; + this.setClearAlpha = function() { + background.setClearAlpha.apply(background, arguments); + }; + this.clear = function(color = true, depth2 = true, stencil2 = true) { + let bits = 0; + if (color) { + let isIntegerFormat = false; + if (_currentRenderTarget !== null) { + const targetFormat = _currentRenderTarget.texture.format; + isIntegerFormat = targetFormat === RGBAIntegerFormat2 || targetFormat === RGIntegerFormat2 || targetFormat === RedIntegerFormat2; + } + if (isIntegerFormat) { + const targetType = _currentRenderTarget.texture.type; + const isUnsignedType = targetType === UnsignedByteType2 || targetType === UnsignedIntType2 || targetType === UnsignedShortType2 || targetType === UnsignedInt248Type2 || targetType === UnsignedShort4444Type2 || targetType === UnsignedShort5551Type2; + const clearColor = background.getClearColor(); + const a = background.getClearAlpha(); + const r = clearColor.r; + const g = clearColor.g; + const b = clearColor.b; + if (isUnsignedType) { + uintClearColor[0] = r; + uintClearColor[1] = g; + uintClearColor[2] = b; + uintClearColor[3] = a; + _gl.clearBufferuiv(_gl.COLOR, 0, uintClearColor); + } else { + intClearColor[0] = r; + intClearColor[1] = g; + intClearColor[2] = b; + intClearColor[3] = a; + _gl.clearBufferiv(_gl.COLOR, 0, intClearColor); + } + } else { + bits |= _gl.COLOR_BUFFER_BIT; + } + } + if (depth2) { + bits |= _gl.DEPTH_BUFFER_BIT; + } + if (stencil2) { + bits |= _gl.STENCIL_BUFFER_BIT; + this.state.buffers.stencil.setMask(4294967295); + } + _gl.clear(bits); + }; + this.clearColor = function() { + this.clear(true, false, false); + }; + this.clearDepth = function() { + this.clear(false, true, false); + }; + this.clearStencil = function() { + this.clear(false, false, true); + }; + this.dispose = function() { + canvas.removeEventListener("webglcontextlost", onContextLost, false); + canvas.removeEventListener("webglcontextrestored", onContextRestore, false); + canvas.removeEventListener("webglcontextcreationerror", onContextCreationError, false); + background.dispose(); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + xr.dispose(); + xr.removeEventListener("sessionstart", onXRSessionStart); + xr.removeEventListener("sessionend", onXRSessionEnd); + animation.stop(); + }; + function onContextLost(event) { + event.preventDefault(); + console.log("THREE.WebGLRenderer: Context Lost."); + _isContextLost = true; + } + function onContextRestore() { + console.log("THREE.WebGLRenderer: Context Restored."); + _isContextLost = false; + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + initGLContext(); + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + } + function onContextCreationError(event) { + console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", event.statusMessage); + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + deallocateMaterial(material); + } + function deallocateMaterial(material) { + releaseMaterialProgramReferences(material); + properties.remove(material); + } + function releaseMaterialProgramReferences(material) { + const programs = properties.get(material).programs; + if (programs !== undefined) { + programs.forEach(function(program) { + programCache.releaseProgram(program); + }); + if (material.isShaderMaterial) { + programCache.releaseShaderCache(material); + } + } + } + this.renderBufferDirect = function(camera, scene, geometry, material, object, group) { + if (scene === null) + scene = _emptyScene; + const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0; + const program = setProgram(camera, scene, geometry, material, object); + state.setMaterial(material, frontFaceCW); + let index2 = geometry.index; + let rangeFactor = 1; + if (material.wireframe === true) { + index2 = geometries.getWireframeAttribute(geometry); + if (index2 === undefined) + return; + rangeFactor = 2; + } + const drawRange = geometry.drawRange; + const position2 = geometry.attributes.position; + let drawStart = drawRange.start * rangeFactor; + let drawEnd = (drawRange.start + drawRange.count) * rangeFactor; + if (group !== null) { + drawStart = Math.max(drawStart, group.start * rangeFactor); + drawEnd = Math.min(drawEnd, (group.start + group.count) * rangeFactor); + } + if (index2 !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, index2.count); + } else if (position2 !== undefined && position2 !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, position2.count); + } + const drawCount = drawEnd - drawStart; + if (drawCount < 0 || drawCount === Infinity) + return; + bindingStates.setup(object, material, program, geometry, index2); + let attribute; + let renderer2 = bufferRenderer; + if (index2 !== null) { + attribute = attributes.get(index2); + renderer2 = indexedBufferRenderer; + renderer2.setIndex(attribute); + } + if (object.isMesh) { + if (material.wireframe === true) { + state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio()); + renderer2.setMode(_gl.LINES); + } else { + renderer2.setMode(_gl.TRIANGLES); + } + } else if (object.isLine) { + let lineWidth = material.linewidth; + if (lineWidth === undefined) + lineWidth = 1; + state.setLineWidth(lineWidth * getTargetPixelRatio()); + if (object.isLineSegments) { + renderer2.setMode(_gl.LINES); + } else if (object.isLineLoop) { + renderer2.setMode(_gl.LINE_LOOP); + } else { + renderer2.setMode(_gl.LINE_STRIP); + } + } else if (object.isPoints) { + renderer2.setMode(_gl.POINTS); + } else if (object.isSprite) { + renderer2.setMode(_gl.TRIANGLES); + } + if (object.isBatchedMesh) { + if (object._multiDrawInstances !== null) { + renderer2.renderMultiDrawInstances(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances); + } else { + if (!extensions.get("WEBGL_multi_draw")) { + const starts = object._multiDrawStarts; + const counts = object._multiDrawCounts; + const drawCount2 = object._multiDrawCount; + const bytesPerElement = index2 ? attributes.get(index2).bytesPerElement : 1; + const uniforms = properties.get(material).currentProgram.getUniforms(); + for (let i = 0;i < drawCount2; i++) { + uniforms.setValue(_gl, "_gl_DrawID", i); + renderer2.render(starts[i] / bytesPerElement, counts[i]); + } + } else { + renderer2.renderMultiDraw(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount); + } + } + } else if (object.isInstancedMesh) { + renderer2.renderInstances(drawStart, drawCount, object.count); + } else if (geometry.isInstancedBufferGeometry) { + const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min(geometry.instanceCount, maxInstanceCount); + renderer2.renderInstances(drawStart, drawCount, instanceCount); + } else { + renderer2.render(drawStart, drawCount); + } + }; + function prepareMaterial(material, scene, object) { + if (material.transparent === true && material.side === DoubleSide2 && material.forceSinglePass === false) { + material.side = BackSide2; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = FrontSide2; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = DoubleSide2; + } else { + getProgram(material, scene, object); + } + } + this.compile = function(scene, camera, targetScene = null) { + if (targetScene === null) + targetScene = scene; + currentRenderState = renderStates.get(targetScene); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + targetScene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + if (scene !== targetScene) { + scene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + } + currentRenderState.setupLights(); + const materials2 = new Set; + scene.traverse(function(object) { + if (!(object.isMesh || object.isPoints || object.isLine || object.isSprite)) { + return; + } + const material = object.material; + if (material) { + if (Array.isArray(material)) { + for (let i = 0;i < material.length; i++) { + const material2 = material[i]; + prepareMaterial(material2, targetScene, object); + materials2.add(material2); + } + } else { + prepareMaterial(material, targetScene, object); + materials2.add(material); + } + } + }); + renderStateStack.pop(); + currentRenderState = null; + return materials2; + }; + this.compileAsync = function(scene, camera, targetScene = null) { + const materials2 = this.compile(scene, camera, targetScene); + return new Promise((resolve) => { + function checkMaterialsReady() { + materials2.forEach(function(material) { + const materialProperties = properties.get(material); + const program = materialProperties.currentProgram; + if (program.isReady()) { + materials2.delete(material); + } + }); + if (materials2.size === 0) { + resolve(scene); + return; + } + setTimeout(checkMaterialsReady, 10); + } + if (extensions.get("KHR_parallel_shader_compile") !== null) { + checkMaterialsReady(); + } else { + setTimeout(checkMaterialsReady, 10); + } + }); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time2) { + if (onAnimationFrameCallback) + onAnimationFrameCallback(time2); + } + function onXRSessionStart() { + animation.stop(); + } + function onXRSessionEnd() { + animation.start(); + } + const animation = new WebGLAnimation2; + animation.setAnimationLoop(onAnimationFrame); + if (typeof self !== "undefined") + animation.setContext(self); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + xr.setAnimationLoop(callback); + callback === null ? animation.stop() : animation.start(); + }; + xr.addEventListener("sessionstart", onXRSessionStart); + xr.addEventListener("sessionend", onXRSessionEnd); + this.render = function(scene, camera) { + if (camera !== undefined && camera.isCamera !== true) { + console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera."); + return; + } + if (_isContextLost === true) + return; + if (scene.matrixWorldAutoUpdate === true) + scene.updateMatrixWorld(); + if (camera.parent === null && camera.matrixWorldAutoUpdate === true) + camera.updateMatrixWorld(); + if (xr.enabled === true && xr.isPresenting === true) { + if (xr.cameraAutoUpdate === true) + xr.updateCamera(camera); + camera = xr.getCamera(); + } + if (scene.isScene === true) + scene.onBeforeRender(_this, scene, camera, _currentRenderTarget); + currentRenderState = renderStates.get(scene, renderStateStack.length); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + _projScreenMatrix3.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + _frustum3.setFromProjectionMatrix(_projScreenMatrix3); + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled); + currentRenderList = renderLists.get(scene, renderListStack.length); + currentRenderList.init(); + renderListStack.push(currentRenderList); + if (xr.enabled === true && xr.isPresenting === true) { + const depthSensingMesh = _this.xr.getDepthSensingMesh(); + if (depthSensingMesh !== null) { + projectObject(depthSensingMesh, camera, -Infinity, _this.sortObjects); + } + } + projectObject(scene, camera, 0, _this.sortObjects); + currentRenderList.finish(); + if (_this.sortObjects === true) { + currentRenderList.sort(_opaqueSort, _transparentSort); + } + _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false; + if (_renderBackground) { + background.addToRenderList(currentRenderList, scene); + } + this.info.render.frame++; + if (_clippingEnabled === true) + clipping.beginShadows(); + const shadowsArray = currentRenderState.state.shadowsArray; + shadowMap.render(shadowsArray, scene, camera); + if (_clippingEnabled === true) + clipping.endShadows(); + if (this.info.autoReset === true) + this.info.reset(); + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + currentRenderState.setupLights(); + if (camera.isArrayCamera) { + const cameras = camera.cameras; + if (transmissiveObjects.length > 0) { + for (let i = 0, l = cameras.length;i < l; i++) { + const camera2 = cameras[i]; + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera2); + } + } + if (_renderBackground) + background.render(scene); + for (let i = 0, l = cameras.length;i < l; i++) { + const camera2 = cameras[i]; + renderScene(currentRenderList, scene, camera2, camera2.viewport); + } + } else { + if (transmissiveObjects.length > 0) + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera); + if (_renderBackground) + background.render(scene); + renderScene(currentRenderList, scene, camera); + } + if (_currentRenderTarget !== null && _currentActiveMipmapLevel === 0) { + textures.updateMultisampleRenderTarget(_currentRenderTarget); + textures.updateRenderTargetMipmap(_currentRenderTarget); + } + if (scene.isScene === true) + scene.onAfterRender(_this, scene, camera); + bindingStates.resetDefaultState(); + _currentMaterialId = -1; + _currentCamera = null; + renderStateStack.pop(); + if (renderStateStack.length > 0) { + currentRenderState = renderStateStack[renderStateStack.length - 1]; + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, currentRenderState.state.camera); + } else { + currentRenderState = null; + } + renderListStack.pop(); + if (renderListStack.length > 0) { + currentRenderList = renderListStack[renderListStack.length - 1]; + } else { + currentRenderList = null; + } + }; + function projectObject(object, camera, groupOrder, sortObjects) { + if (object.visible === false) + return; + const visible = object.layers.test(camera.layers); + if (visible) { + if (object.isGroup) { + groupOrder = object.renderOrder; + } else if (object.isLOD) { + if (object.autoUpdate === true) + object.update(camera); + } else if (object.isLight) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } else if (object.isSprite) { + if (!object.frustumCulled || _frustum3.intersectsSprite(object)) { + if (sortObjects) { + _vector42.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix3); + } + const geometry = objects.update(object); + const material = object.material; + if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector42.z, null); + } + } + } else if (object.isMesh || object.isLine || object.isPoints) { + if (!object.frustumCulled || _frustum3.intersectsObject(object)) { + const geometry = objects.update(object); + const material = object.material; + if (sortObjects) { + if (object.boundingSphere !== undefined) { + if (object.boundingSphere === null) + object.computeBoundingSphere(); + _vector42.copy(object.boundingSphere.center); + } else { + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _vector42.copy(geometry.boundingSphere.center); + } + _vector42.applyMatrix4(object.matrixWorld).applyMatrix4(_projScreenMatrix3); + } + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector42.z, group); + } + } + } else if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector42.z, null); + } + } + } + } + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + projectObject(children[i], camera, groupOrder, sortObjects); + } + } + function renderScene(currentRenderList2, scene, camera, viewport) { + const opaqueObjects = currentRenderList2.opaque; + const transmissiveObjects = currentRenderList2.transmissive; + const transparentObjects = currentRenderList2.transparent; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, camera); + if (viewport) + state.viewport(_currentViewport.copy(viewport)); + if (opaqueObjects.length > 0) + renderObjects(opaqueObjects, scene, camera); + if (transmissiveObjects.length > 0) + renderObjects(transmissiveObjects, scene, camera); + if (transparentObjects.length > 0) + renderObjects(transparentObjects, scene, camera); + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + state.setPolygonOffset(false); + } + function renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + if (overrideMaterial !== null) { + return; + } + if (currentRenderState.state.transmissionRenderTarget[camera.id] === undefined) { + currentRenderState.state.transmissionRenderTarget[camera.id] = new WebGLRenderTarget2(1, 1, { + generateMipmaps: true, + type: extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float") ? HalfFloatType2 : UnsignedByteType2, + minFilter: LinearMipmapLinearFilter2, + samples: 4, + stencilBuffer: stencil, + resolveDepthBuffer: false, + resolveStencilBuffer: false, + colorSpace: ColorManagement2.workingColorSpace + }); + } + const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[camera.id]; + const activeViewport = camera.viewport || _currentViewport; + transmissionRenderTarget.setSize(activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale); + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget(transmissionRenderTarget); + _this.getClearColor(_currentClearColor); + _currentClearAlpha = _this.getClearAlpha(); + if (_currentClearAlpha < 1) + _this.setClearColor(16777215, 0.5); + _this.clear(); + if (_renderBackground) + background.render(scene); + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping2; + const currentCameraViewport = camera.viewport; + if (camera.viewport !== undefined) + camera.viewport = undefined; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, camera); + renderObjects(opaqueObjects, scene, camera); + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + if (extensions.has("WEBGL_multisampled_render_to_texture") === false) { + let renderTargetNeedsUpdate = false; + for (let i = 0, l = transmissiveObjects.length;i < l; i++) { + const renderItem = transmissiveObjects[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = renderItem.material; + const group = renderItem.group; + if (material.side === DoubleSide2 && object.layers.test(camera.layers)) { + const currentSide = material.side; + material.side = BackSide2; + material.needsUpdate = true; + renderObject(object, scene, camera, geometry, material, group); + material.side = currentSide; + material.needsUpdate = true; + renderTargetNeedsUpdate = true; + } + } + if (renderTargetNeedsUpdate === true) { + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + } + } + _this.setRenderTarget(currentRenderTarget); + _this.setClearColor(_currentClearColor, _currentClearAlpha); + if (currentCameraViewport !== undefined) + camera.viewport = currentCameraViewport; + _this.toneMapping = currentToneMapping; + } + function renderObjects(renderList, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + for (let i = 0, l = renderList.length;i < l; i++) { + const renderItem = renderList[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; + if (object.layers.test(camera.layers)) { + renderObject(object, scene, camera, geometry, material, group); + } + } + } + function renderObject(object, scene, camera, geometry, material, group) { + object.onBeforeRender(_this, scene, camera, geometry, material, group); + object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld); + object.normalMatrix.getNormalMatrix(object.modelViewMatrix); + material.onBeforeRender(_this, scene, camera, geometry, object, group); + if (material.transparent === true && material.side === DoubleSide2 && material.forceSinglePass === false) { + material.side = BackSide2; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = FrontSide2; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = DoubleSide2; + } else { + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + } + object.onAfterRender(_this, scene, camera, geometry, material, group); + } + function getProgram(material, scene, object) { + if (scene.isScene !== true) + scene = _emptyScene; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + const lightsStateVersion = lights.state.version; + const parameters2 = programCache.getParameters(material, lights.state, shadowsArray, scene, object); + const programCacheKey = programCache.getProgramCacheKey(parameters2); + let programs = materialProperties.programs; + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment); + materialProperties.envMapRotation = materialProperties.environment !== null && material.envMap === null ? scene.environmentRotation : material.envMapRotation; + if (programs === undefined) { + material.addEventListener("dispose", onMaterialDispose); + programs = new Map; + materialProperties.programs = programs; + } + let program = programs.get(programCacheKey); + if (program !== undefined) { + if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) { + updateCommonMaterialProperties(material, parameters2); + return program; + } + } else { + parameters2.uniforms = programCache.getUniforms(material); + material.onBeforeCompile(parameters2, _this); + program = programCache.acquireProgram(parameters2, programCacheKey); + programs.set(programCacheKey, program); + materialProperties.uniforms = parameters2.uniforms; + } + const uniforms = materialProperties.uniforms; + if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) { + uniforms.clippingPlanes = clipping.uniform; + } + updateCommonMaterialProperties(material, parameters2); + materialProperties.needsLights = materialNeedsLights(material); + materialProperties.lightsStateVersion = lightsStateVersion; + if (materialProperties.needsLights) { + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + } + materialProperties.currentProgram = program; + materialProperties.uniformsList = null; + return program; + } + function getUniformList(materialProperties) { + if (materialProperties.uniformsList === null) { + const progUniforms = materialProperties.currentProgram.getUniforms(); + materialProperties.uniformsList = WebGLUniforms2.seqWithValue(progUniforms.seq, materialProperties.uniforms); + } + return materialProperties.uniformsList; + } + function updateCommonMaterialProperties(material, parameters2) { + const materialProperties = properties.get(material); + materialProperties.outputColorSpace = parameters2.outputColorSpace; + materialProperties.batching = parameters2.batching; + materialProperties.batchingColor = parameters2.batchingColor; + materialProperties.instancing = parameters2.instancing; + materialProperties.instancingColor = parameters2.instancingColor; + materialProperties.instancingMorph = parameters2.instancingMorph; + materialProperties.skinning = parameters2.skinning; + materialProperties.morphTargets = parameters2.morphTargets; + materialProperties.morphNormals = parameters2.morphNormals; + materialProperties.morphColors = parameters2.morphColors; + materialProperties.morphTargetsCount = parameters2.morphTargetsCount; + materialProperties.numClippingPlanes = parameters2.numClippingPlanes; + materialProperties.numIntersection = parameters2.numClipIntersection; + materialProperties.vertexAlphas = parameters2.vertexAlphas; + materialProperties.vertexTangents = parameters2.vertexTangents; + materialProperties.toneMapping = parameters2.toneMapping; + } + function setProgram(camera, scene, geometry, material, object) { + if (scene.isScene !== true) + scene = _emptyScene; + textures.resetTextureUnits(); + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const colorSpace = _currentRenderTarget === null ? _this.outputColorSpace : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace2; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !!geometry.attributes.tangent && (!!material.normalMap || material.anisotropy > 0); + const morphTargets = !!geometry.morphAttributes.position; + const morphNormals = !!geometry.morphAttributes.normal; + const morphColors = !!geometry.morphAttributes.color; + let toneMapping = NoToneMapping2; + if (material.toneMapped) { + if (_currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true) { + toneMapping = _this.toneMapping; + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + if (_clippingEnabled === true) { + if (_localClippingEnabled === true || camera !== _currentCamera) { + const useCache = camera === _currentCamera && material.id === _currentMaterialId; + clipping.setState(material, camera, useCache); + } + } + let needsProgramChange = false; + if (material.version === materialProperties.__version) { + if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) { + needsProgramChange = true; + } else if (materialProperties.outputColorSpace !== colorSpace) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batching === false) { + needsProgramChange = true; + } else if (!object.isBatchedMesh && materialProperties.batching === true) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancing === false) { + needsProgramChange = true; + } else if (!object.isInstancedMesh && materialProperties.instancing === true) { + needsProgramChange = true; + } else if (object.isSkinnedMesh && materialProperties.skinning === false) { + needsProgramChange = true; + } else if (!object.isSkinnedMesh && materialProperties.skinning === true) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null) { + needsProgramChange = true; + } else if (materialProperties.envMap !== envMap) { + needsProgramChange = true; + } else if (material.fog === true && materialProperties.fog !== fog) { + needsProgramChange = true; + } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) { + needsProgramChange = true; + } else if (materialProperties.vertexAlphas !== vertexAlphas) { + needsProgramChange = true; + } else if (materialProperties.vertexTangents !== vertexTangents) { + needsProgramChange = true; + } else if (materialProperties.morphTargets !== morphTargets) { + needsProgramChange = true; + } else if (materialProperties.morphNormals !== morphNormals) { + needsProgramChange = true; + } else if (materialProperties.morphColors !== morphColors) { + needsProgramChange = true; + } else if (materialProperties.toneMapping !== toneMapping) { + needsProgramChange = true; + } else if (materialProperties.morphTargetsCount !== morphTargetsCount) { + needsProgramChange = true; + } + } else { + needsProgramChange = true; + materialProperties.__version = material.version; + } + let program = materialProperties.currentProgram; + if (needsProgramChange === true) { + program = getProgram(material, scene, object); + } + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + const p_uniforms = program.getUniforms(), m_uniforms = materialProperties.uniforms; + if (state.useProgram(program.program)) { + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + } + if (material.id !== _currentMaterialId) { + _currentMaterialId = material.id; + refreshMaterial = true; + } + if (refreshProgram || _currentCamera !== camera) { + const reverseDepthBuffer2 = state.buffers.depth.getReversed(); + if (reverseDepthBuffer2) { + _currentProjectionMatrix.copy(camera.projectionMatrix); + toNormalizedProjectionMatrix2(_currentProjectionMatrix); + toReversedProjectionMatrix2(_currentProjectionMatrix); + p_uniforms.setValue(_gl, "projectionMatrix", _currentProjectionMatrix); + } else { + p_uniforms.setValue(_gl, "projectionMatrix", camera.projectionMatrix); + } + p_uniforms.setValue(_gl, "viewMatrix", camera.matrixWorldInverse); + const uCamPos = p_uniforms.map.cameraPosition; + if (uCamPos !== undefined) { + uCamPos.setValue(_gl, _vector33.setFromMatrixPosition(camera.matrixWorld)); + } + if (capabilities.logarithmicDepthBuffer) { + p_uniforms.setValue(_gl, "logDepthBufFC", 2 / (Math.log(camera.far + 1) / Math.LN2)); + } + if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) { + p_uniforms.setValue(_gl, "isOrthographic", camera.isOrthographicCamera === true); + } + if (_currentCamera !== camera) { + _currentCamera = camera; + refreshMaterial = true; + refreshLights = true; + } + } + if (object.isSkinnedMesh) { + p_uniforms.setOptional(_gl, object, "bindMatrix"); + p_uniforms.setOptional(_gl, object, "bindMatrixInverse"); + const skeleton = object.skeleton; + if (skeleton) { + if (skeleton.boneTexture === null) + skeleton.computeBoneTexture(); + p_uniforms.setValue(_gl, "boneTexture", skeleton.boneTexture, textures); + } + } + if (object.isBatchedMesh) { + p_uniforms.setOptional(_gl, object, "batchingTexture"); + p_uniforms.setValue(_gl, "batchingTexture", object._matricesTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingIdTexture"); + p_uniforms.setValue(_gl, "batchingIdTexture", object._indirectTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingColorTexture"); + if (object._colorsTexture !== null) { + p_uniforms.setValue(_gl, "batchingColorTexture", object._colorsTexture, textures); + } + } + const morphAttributes = geometry.morphAttributes; + if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined) { + morphtargets.update(object, geometry, program); + } + if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) { + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue(_gl, "receiveShadow", object.receiveShadow); + } + if (material.isMeshGouraudMaterial && material.envMap !== null) { + m_uniforms.envMap.value = envMap; + m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + } + if (material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null) { + m_uniforms.envMapIntensity.value = scene.environmentIntensity; + } + if (refreshMaterial) { + p_uniforms.setValue(_gl, "toneMappingExposure", _this.toneMappingExposure); + if (materialProperties.needsLights) { + markUniformsLightsNeedsUpdate(m_uniforms, refreshLights); + } + if (fog && material.fog === true) { + materials.refreshFogUniforms(m_uniforms, fog); + } + materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[camera.id]); + WebGLUniforms2.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + } + if (material.isShaderMaterial && material.uniformsNeedUpdate === true) { + WebGLUniforms2.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + material.uniformsNeedUpdate = false; + } + if (material.isSpriteMaterial) { + p_uniforms.setValue(_gl, "center", object.center); + } + p_uniforms.setValue(_gl, "modelViewMatrix", object.modelViewMatrix); + p_uniforms.setValue(_gl, "normalMatrix", object.normalMatrix); + p_uniforms.setValue(_gl, "modelMatrix", object.matrixWorld); + if (material.isShaderMaterial || material.isRawShaderMaterial) { + const groups = material.uniformsGroups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + uniformsGroups.update(group, program); + uniformsGroups.bind(group, program); + } + } + return program; + } + function markUniformsLightsNeedsUpdate(uniforms, value2) { + uniforms.ambientLightColor.needsUpdate = value2; + uniforms.lightProbe.needsUpdate = value2; + uniforms.directionalLights.needsUpdate = value2; + uniforms.directionalLightShadows.needsUpdate = value2; + uniforms.pointLights.needsUpdate = value2; + uniforms.pointLightShadows.needsUpdate = value2; + uniforms.spotLights.needsUpdate = value2; + uniforms.spotLightShadows.needsUpdate = value2; + uniforms.rectAreaLights.needsUpdate = value2; + uniforms.hemisphereLights.needsUpdate = value2; + } + function materialNeedsLights(material) { + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true; + } + this.getActiveCubeFace = function() { + return _currentActiveCubeFace; + }; + this.getActiveMipmapLevel = function() { + return _currentActiveMipmapLevel; + }; + this.getRenderTarget = function() { + return _currentRenderTarget; + }; + this.setRenderTargetTextures = function(renderTarget, colorTexture, depthTexture) { + properties.get(renderTarget.texture).__webglTexture = colorTexture; + properties.get(renderTarget.depthTexture).__webglTexture = depthTexture; + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__hasExternalTextures = true; + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; + if (!renderTargetProperties.__autoAllocateDepthBuffer) { + if (extensions.has("WEBGL_multisampled_render_to_texture") === true) { + console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"); + renderTargetProperties.__useRenderToTexture = false; + } + } + }; + this.setRenderTargetFramebuffer = function(renderTarget, defaultFramebuffer) { + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; + }; + const _scratchFrameBuffer = _gl.createFramebuffer(); + this.setRenderTarget = function(renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) { + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + if (renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTargetProperties.__useDefaultFramebuffer !== undefined) { + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + useDefaultFramebuffer = false; + } else if (renderTargetProperties.__webglFramebuffer === undefined) { + textures.setupRenderTarget(renderTarget); + } else if (renderTargetProperties.__hasExternalTextures) { + textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture); + } else if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__boundDepthTexture !== depthTexture) { + if (depthTexture !== null && properties.has(depthTexture) && (renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height)) { + throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size."); + } + textures.setupDepthRenderbuffer(renderTarget); + } + } + const texture = renderTarget.texture; + if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + isRenderTarget3D = true; + } + const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget) { + if (Array.isArray(__webglFramebuffer[activeCubeFace])) { + framebuffer = __webglFramebuffer[activeCubeFace][activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer[activeCubeFace]; + } + isCube = true; + } else if (renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) { + framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer; + } else { + if (Array.isArray(__webglFramebuffer)) { + framebuffer = __webglFramebuffer[activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer; + } + } + _currentViewport.copy(renderTarget.viewport); + _currentScissor.copy(renderTarget.scissor); + _currentScissorTest = renderTarget.scissorTest; + } else { + _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor(); + _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(); + _currentScissorTest = _scissorTest; + } + if (activeMipmapLevel !== 0) { + framebuffer = _scratchFrameBuffer; + } + const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (framebufferBound && useDefaultFramebuffer) { + state.drawBuffers(renderTarget, framebuffer); + } + state.viewport(_currentViewport); + state.scissor(_currentScissor); + state.setScissorTest(_currentScissorTest); + if (isCube) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel); + } else if (isRenderTarget3D) { + const textureProperties = properties.get(renderTarget.texture); + const layer = activeCubeFace; + _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer); + } else if (renderTarget !== null && activeMipmapLevel !== 0) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel); + } + _currentMaterialId = -1; + }; + this.readRenderTargetPixels = function(renderTarget, x, y, width2, height2, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + return; + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + try { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); + return; + } + if (!capabilities.textureTypeReadable(textureType)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); + return; + } + if (x >= 0 && x <= renderTarget.width - width2 && (y >= 0 && y <= renderTarget.height - height2)) { + _gl.readPixels(x, y, width2, height2, utils.convert(textureFormat), utils.convert(textureType), buffer); + } + } finally { + const framebuffer2 = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer2); + } + } + }; + this.readRenderTargetPixelsAsync = async function(renderTarget, x, y, width2, height2, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format."); + } + if (!capabilities.textureTypeReadable(textureType)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type."); + } + if (x >= 0 && x <= renderTarget.width - width2 && (y >= 0 && y <= renderTarget.height - height2)) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + const glBuffer = _gl.createBuffer(); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.bufferData(_gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ); + _gl.readPixels(x, y, width2, height2, utils.convert(textureFormat), utils.convert(textureType), 0); + const currFramebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, currFramebuffer); + const sync = _gl.fenceSync(_gl.SYNC_GPU_COMMANDS_COMPLETE, 0); + _gl.flush(); + await probeAsync2(_gl, sync, 4); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.getBufferSubData(_gl.PIXEL_PACK_BUFFER, 0, buffer); + _gl.deleteBuffer(glBuffer); + _gl.deleteSync(sync); + return buffer; + } else { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range."); + } + } + }; + this.copyFramebufferToTexture = function(texture, position2 = null, level = 0) { + if (texture.isTexture !== true) { + warnOnce2("WebGLRenderer: copyFramebufferToTexture function signature has changed."); + position2 = arguments[0] || null; + texture = arguments[1]; + } + const levelScale = Math.pow(2, -level); + const width2 = Math.floor(texture.image.width * levelScale); + const height2 = Math.floor(texture.image.height * levelScale); + const x = position2 !== null ? position2.x : 0; + const y = position2 !== null ? position2.y : 0; + textures.setTexture2D(texture, 0); + _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, x, y, width2, height2); + state.unbindTexture(); + }; + const _srcFramebuffer = _gl.createFramebuffer(); + const _dstFramebuffer = _gl.createFramebuffer(); + this.copyTextureToTexture = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null) { + if (srcTexture.isTexture !== true) { + warnOnce2("WebGLRenderer: copyTextureToTexture function signature has changed."); + dstPosition = arguments[0] || null; + srcTexture = arguments[1]; + dstTexture = arguments[2]; + dstLevel = arguments[3] || 0; + srcRegion = null; + } + if (dstLevel === null) { + if (srcLevel !== 0) { + warnOnce2("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."); + dstLevel = srcLevel; + srcLevel = 0; + } else { + dstLevel = 0; + } + } + let width2, height2, depth2, minX, minY, minZ; + let dstX, dstY, dstZ; + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[dstLevel] : srcTexture.image; + if (srcRegion !== null) { + width2 = srcRegion.max.x - srcRegion.min.x; + height2 = srcRegion.max.y - srcRegion.min.y; + depth2 = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1; + minX = srcRegion.min.x; + minY = srcRegion.min.y; + minZ = srcRegion.isBox3 ? srcRegion.min.z : 0; + } else { + const levelScale = Math.pow(2, -srcLevel); + width2 = Math.floor(image.width * levelScale); + height2 = Math.floor(image.height * levelScale); + if (srcTexture.isDataArrayTexture) { + depth2 = image.depth; + } else if (srcTexture.isData3DTexture) { + depth2 = Math.floor(image.depth * levelScale); + } else { + depth2 = 1; + } + minX = 0; + minY = 0; + minZ = 0; + } + if (dstPosition !== null) { + dstX = dstPosition.x; + dstY = dstPosition.y; + dstZ = dstPosition.z; + } else { + dstX = 0; + dstY = 0; + dstZ = 0; + } + const glFormat = utils.convert(dstTexture.format); + const glType = utils.convert(dstTexture.type); + let glTarget; + if (dstTexture.isData3DTexture) { + textures.setTexture3D(dstTexture, 0); + glTarget = _gl.TEXTURE_3D; + } else if (dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture) { + textures.setTexture2DArray(dstTexture, 0); + glTarget = _gl.TEXTURE_2D_ARRAY; + } else { + textures.setTexture2D(dstTexture, 0); + glTarget = _gl.TEXTURE_2D; + } + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment); + const currentUnpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH); + const currentUnpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT); + const currentUnpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS); + const currentUnpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS); + const currentUnpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES); + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, minX); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, minY); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, minZ); + const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture; + const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture; + if (srcTexture.isDepthTexture) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + const srcRenderTargetProperties = properties.get(srcTextureProperties.__renderTarget); + const dstRenderTargetProperties = properties.get(dstTextureProperties.__renderTarget); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer); + for (let i = 0;i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(srcTexture).__webglTexture, srcLevel, minZ + i); + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(dstTexture).__webglTexture, dstLevel, dstZ + i); + } + _gl.blitFramebuffer(minX, minY, width2, height2, dstX, dstY, width2, height2, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST); + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else if (srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has(srcTexture)) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, _srcFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, _dstFramebuffer); + for (let i = 0;i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i); + } else { + _gl.framebufferTexture2D(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel); + } + if (isDst3D) { + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i); + } else { + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel); + } + if (srcLevel !== 0) { + _gl.blitFramebuffer(minX, minY, width2, height2, dstX, dstY, width2, height2, _gl.COLOR_BUFFER_BIT, _gl.NEAREST); + } else if (isDst3D) { + _gl.copyTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width2, height2); + } else { + _gl.copyTexSubImage2D(glTarget, dstLevel, dstX, dstY, minX, minY, width2, height2); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else { + if (isDst3D) { + if (srcTexture.isDataTexture || srcTexture.isData3DTexture) { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, glType, image.data); + } else if (dstTexture.isCompressedArrayTexture) { + _gl.compressedTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, image.data); + } else { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, glType, image); + } + } else { + if (srcTexture.isDataTexture) { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width2, height2, glFormat, glType, image.data); + } else if (srcTexture.isCompressedTexture) { + _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data); + } else { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width2, height2, glFormat, glType, image); + } + } + } + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, currentUnpackRowLen); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages); + if (dstLevel === 0 && dstTexture.generateMipmaps) { + _gl.generateMipmap(glTarget); + } + state.unbindTexture(); + }; + this.copyTextureToTexture3D = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0) { + if (srcTexture.isTexture !== true) { + warnOnce2("WebGLRenderer: copyTextureToTexture3D function signature has changed."); + srcRegion = arguments[0] || null; + dstPosition = arguments[1] || null; + srcTexture = arguments[2]; + dstTexture = arguments[3]; + level = arguments[4] || 0; + } + warnOnce2('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'); + return this.copyTextureToTexture(srcTexture, dstTexture, srcRegion, dstPosition, level); + }; + this.initRenderTarget = function(target) { + if (properties.get(target).__webglFramebuffer === undefined) { + textures.setupRenderTarget(target); + } + }; + this.initTexture = function(texture) { + if (texture.isCubeTexture) { + textures.setTextureCube(texture, 0); + } else if (texture.isData3DTexture) { + textures.setTexture3D(texture, 0); + } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + textures.setTexture2DArray(texture, 0); + } else { + textures.setTexture2D(texture, 0); + } + state.unbindTexture(); + }; + this.resetState = function() { + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + state.reset(); + bindingStates.reset(); + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + get coordinateSystem() { + return WebGLCoordinateSystem2; + } + get outputColorSpace() { + return this._outputColorSpace; + } + set outputColorSpace(colorSpace) { + this._outputColorSpace = colorSpace; + const gl = this.getContext(); + gl.drawingBufferColorspace = ColorManagement2._getDrawingBufferColorSpace(colorSpace); + gl.unpackColorSpace = ColorManagement2._getUnpackColorSpace(); + } + } + exports2.ACESFilmicToneMapping = ACESFilmicToneMapping2; + exports2.AddEquation = AddEquation2; + exports2.AddOperation = AddOperation2; + exports2.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode2; + exports2.AdditiveBlending = AdditiveBlending2; + exports2.AgXToneMapping = AgXToneMapping2; + exports2.AlphaFormat = AlphaFormat2; + exports2.AlwaysCompare = AlwaysCompare2; + exports2.AlwaysDepth = AlwaysDepth2; + exports2.AlwaysStencilFunc = AlwaysStencilFunc2; + exports2.AmbientLight = AmbientLight2; + exports2.AnimationAction = AnimationAction2; + exports2.AnimationClip = AnimationClip2; + exports2.AnimationLoader = AnimationLoader2; + exports2.AnimationMixer = AnimationMixer2; + exports2.AnimationObjectGroup = AnimationObjectGroup2; + exports2.AnimationUtils = AnimationUtils2; + exports2.ArcCurve = ArcCurve2; + exports2.ArrayCamera = ArrayCamera2; + exports2.ArrowHelper = ArrowHelper2; + exports2.AttachedBindMode = AttachedBindMode2; + exports2.Audio = Audio2; + exports2.AudioAnalyser = AudioAnalyser2; + exports2.AudioContext = AudioContext2; + exports2.AudioListener = AudioListener2; + exports2.AudioLoader = AudioLoader2; + exports2.AxesHelper = AxesHelper2; + exports2.BackSide = BackSide2; + exports2.BasicDepthPacking = BasicDepthPacking2; + exports2.BasicShadowMap = BasicShadowMap2; + exports2.BatchedMesh = BatchedMesh2; + exports2.Bone = Bone2; + exports2.BooleanKeyframeTrack = BooleanKeyframeTrack2; + exports2.Box2 = Box22; + exports2.Box3 = Box32; + exports2.Box3Helper = Box3Helper2; + exports2.BoxGeometry = BoxGeometry2; + exports2.BoxHelper = BoxHelper2; + exports2.BufferAttribute = BufferAttribute2; + exports2.BufferGeometry = BufferGeometry2; + exports2.BufferGeometryLoader = BufferGeometryLoader2; + exports2.ByteType = ByteType2; + exports2.Cache = Cache2; + exports2.Camera = Camera2; + exports2.CameraHelper = CameraHelper2; + exports2.CanvasTexture = CanvasTexture2; + exports2.CapsuleGeometry = CapsuleGeometry2; + exports2.CatmullRomCurve3 = CatmullRomCurve32; + exports2.CineonToneMapping = CineonToneMapping2; + exports2.CircleGeometry = CircleGeometry2; + exports2.ClampToEdgeWrapping = ClampToEdgeWrapping2; + exports2.Clock = Clock2; + exports2.Color = Color2; + exports2.ColorKeyframeTrack = ColorKeyframeTrack2; + exports2.ColorManagement = ColorManagement2; + exports2.CompressedArrayTexture = CompressedArrayTexture2; + exports2.CompressedCubeTexture = CompressedCubeTexture2; + exports2.CompressedTexture = CompressedTexture2; + exports2.CompressedTextureLoader = CompressedTextureLoader2; + exports2.ConeGeometry = ConeGeometry2; + exports2.ConstantAlphaFactor = ConstantAlphaFactor2; + exports2.ConstantColorFactor = ConstantColorFactor2; + exports2.Controls = Controls2; + exports2.CubeCamera = CubeCamera2; + exports2.CubeReflectionMapping = CubeReflectionMapping2; + exports2.CubeRefractionMapping = CubeRefractionMapping2; + exports2.CubeTexture = CubeTexture2; + exports2.CubeTextureLoader = CubeTextureLoader2; + exports2.CubeUVReflectionMapping = CubeUVReflectionMapping2; + exports2.CubicBezierCurve = CubicBezierCurve2; + exports2.CubicBezierCurve3 = CubicBezierCurve32; + exports2.CubicInterpolant = CubicInterpolant2; + exports2.CullFaceBack = CullFaceBack2; + exports2.CullFaceFront = CullFaceFront2; + exports2.CullFaceFrontBack = CullFaceFrontBack2; + exports2.CullFaceNone = CullFaceNone2; + exports2.Curve = Curve2; + exports2.CurvePath = CurvePath2; + exports2.CustomBlending = CustomBlending2; + exports2.CustomToneMapping = CustomToneMapping2; + exports2.CylinderGeometry = CylinderGeometry2; + exports2.Cylindrical = Cylindrical2; + exports2.Data3DTexture = Data3DTexture2; + exports2.DataArrayTexture = DataArrayTexture2; + exports2.DataTexture = DataTexture2; + exports2.DataTextureLoader = DataTextureLoader2; + exports2.DataUtils = DataUtils2; + exports2.DecrementStencilOp = DecrementStencilOp2; + exports2.DecrementWrapStencilOp = DecrementWrapStencilOp2; + exports2.DefaultLoadingManager = DefaultLoadingManager2; + exports2.DepthFormat = DepthFormat2; + exports2.DepthStencilFormat = DepthStencilFormat2; + exports2.DepthTexture = DepthTexture2; + exports2.DetachedBindMode = DetachedBindMode2; + exports2.DirectionalLight = DirectionalLight2; + exports2.DirectionalLightHelper = DirectionalLightHelper2; + exports2.DiscreteInterpolant = DiscreteInterpolant2; + exports2.DodecahedronGeometry = DodecahedronGeometry2; + exports2.DoubleSide = DoubleSide2; + exports2.DstAlphaFactor = DstAlphaFactor2; + exports2.DstColorFactor = DstColorFactor2; + exports2.DynamicCopyUsage = DynamicCopyUsage2; + exports2.DynamicDrawUsage = DynamicDrawUsage2; + exports2.DynamicReadUsage = DynamicReadUsage2; + exports2.EdgesGeometry = EdgesGeometry2; + exports2.EllipseCurve = EllipseCurve2; + exports2.EqualCompare = EqualCompare2; + exports2.EqualDepth = EqualDepth2; + exports2.EqualStencilFunc = EqualStencilFunc2; + exports2.EquirectangularReflectionMapping = EquirectangularReflectionMapping2; + exports2.EquirectangularRefractionMapping = EquirectangularRefractionMapping2; + exports2.Euler = Euler2; + exports2.EventDispatcher = EventDispatcher2; + exports2.ExtrudeGeometry = ExtrudeGeometry2; + exports2.FileLoader = FileLoader2; + exports2.Float16BufferAttribute = Float16BufferAttribute2; + exports2.Float32BufferAttribute = Float32BufferAttribute2; + exports2.FloatType = FloatType2; + exports2.Fog = Fog2; + exports2.FogExp2 = FogExp22; + exports2.FramebufferTexture = FramebufferTexture2; + exports2.FrontSide = FrontSide2; + exports2.Frustum = Frustum2; + exports2.GLBufferAttribute = GLBufferAttribute2; + exports2.GLSL1 = GLSL12; + exports2.GLSL3 = GLSL32; + exports2.GreaterCompare = GreaterCompare2; + exports2.GreaterDepth = GreaterDepth2; + exports2.GreaterEqualCompare = GreaterEqualCompare2; + exports2.GreaterEqualDepth = GreaterEqualDepth2; + exports2.GreaterEqualStencilFunc = GreaterEqualStencilFunc2; + exports2.GreaterStencilFunc = GreaterStencilFunc2; + exports2.GridHelper = GridHelper2; + exports2.Group = Group2; + exports2.HalfFloatType = HalfFloatType2; + exports2.HemisphereLight = HemisphereLight2; + exports2.HemisphereLightHelper = HemisphereLightHelper2; + exports2.IcosahedronGeometry = IcosahedronGeometry2; + exports2.ImageBitmapLoader = ImageBitmapLoader2; + exports2.ImageLoader = ImageLoader2; + exports2.ImageUtils = ImageUtils2; + exports2.IncrementStencilOp = IncrementStencilOp2; + exports2.IncrementWrapStencilOp = IncrementWrapStencilOp2; + exports2.InstancedBufferAttribute = InstancedBufferAttribute2; + exports2.InstancedBufferGeometry = InstancedBufferGeometry2; + exports2.InstancedInterleavedBuffer = InstancedInterleavedBuffer2; + exports2.InstancedMesh = InstancedMesh2; + exports2.Int16BufferAttribute = Int16BufferAttribute2; + exports2.Int32BufferAttribute = Int32BufferAttribute2; + exports2.Int8BufferAttribute = Int8BufferAttribute2; + exports2.IntType = IntType2; + exports2.InterleavedBuffer = InterleavedBuffer2; + exports2.InterleavedBufferAttribute = InterleavedBufferAttribute2; + exports2.Interpolant = Interpolant2; + exports2.InterpolateDiscrete = InterpolateDiscrete2; + exports2.InterpolateLinear = InterpolateLinear2; + exports2.InterpolateSmooth = InterpolateSmooth2; + exports2.InvertStencilOp = InvertStencilOp2; + exports2.KeepStencilOp = KeepStencilOp2; + exports2.KeyframeTrack = KeyframeTrack2; + exports2.LOD = LOD2; + exports2.LatheGeometry = LatheGeometry2; + exports2.Layers = Layers2; + exports2.LessCompare = LessCompare2; + exports2.LessDepth = LessDepth2; + exports2.LessEqualCompare = LessEqualCompare2; + exports2.LessEqualDepth = LessEqualDepth2; + exports2.LessEqualStencilFunc = LessEqualStencilFunc2; + exports2.LessStencilFunc = LessStencilFunc2; + exports2.Light = Light2; + exports2.LightProbe = LightProbe2; + exports2.Line = Line2; + exports2.Line3 = Line32; + exports2.LineBasicMaterial = LineBasicMaterial2; + exports2.LineCurve = LineCurve2; + exports2.LineCurve3 = LineCurve32; + exports2.LineDashedMaterial = LineDashedMaterial2; + exports2.LineLoop = LineLoop2; + exports2.LineSegments = LineSegments2; + exports2.LinearFilter = LinearFilter2; + exports2.LinearInterpolant = LinearInterpolant2; + exports2.LinearMipMapLinearFilter = LinearMipMapLinearFilter2; + exports2.LinearMipMapNearestFilter = LinearMipMapNearestFilter2; + exports2.LinearMipmapLinearFilter = LinearMipmapLinearFilter2; + exports2.LinearMipmapNearestFilter = LinearMipmapNearestFilter2; + exports2.LinearSRGBColorSpace = LinearSRGBColorSpace2; + exports2.LinearToneMapping = LinearToneMapping2; + exports2.LinearTransfer = LinearTransfer2; + exports2.Loader = Loader2; + exports2.LoaderUtils = LoaderUtils2; + exports2.LoadingManager = LoadingManager2; + exports2.LoopOnce = LoopOnce2; + exports2.LoopPingPong = LoopPingPong2; + exports2.LoopRepeat = LoopRepeat2; + exports2.LuminanceAlphaFormat = LuminanceAlphaFormat2; + exports2.LuminanceFormat = LuminanceFormat2; + exports2.MOUSE = MOUSE2; + exports2.Material = Material2; + exports2.MaterialLoader = MaterialLoader2; + exports2.MathUtils = MathUtils2; + exports2.Matrix2 = Matrix22; + exports2.Matrix3 = Matrix32; + exports2.Matrix4 = Matrix42; + exports2.MaxEquation = MaxEquation2; + exports2.Mesh = Mesh2; + exports2.MeshBasicMaterial = MeshBasicMaterial2; + exports2.MeshDepthMaterial = MeshDepthMaterial2; + exports2.MeshDistanceMaterial = MeshDistanceMaterial2; + exports2.MeshLambertMaterial = MeshLambertMaterial2; + exports2.MeshMatcapMaterial = MeshMatcapMaterial2; + exports2.MeshNormalMaterial = MeshNormalMaterial2; + exports2.MeshPhongMaterial = MeshPhongMaterial2; + exports2.MeshPhysicalMaterial = MeshPhysicalMaterial2; + exports2.MeshStandardMaterial = MeshStandardMaterial2; + exports2.MeshToonMaterial = MeshToonMaterial2; + exports2.MinEquation = MinEquation2; + exports2.MirroredRepeatWrapping = MirroredRepeatWrapping2; + exports2.MixOperation = MixOperation2; + exports2.MultiplyBlending = MultiplyBlending2; + exports2.MultiplyOperation = MultiplyOperation2; + exports2.NearestFilter = NearestFilter2; + exports2.NearestMipMapLinearFilter = NearestMipMapLinearFilter2; + exports2.NearestMipMapNearestFilter = NearestMipMapNearestFilter2; + exports2.NearestMipmapLinearFilter = NearestMipmapLinearFilter2; + exports2.NearestMipmapNearestFilter = NearestMipmapNearestFilter2; + exports2.NeutralToneMapping = NeutralToneMapping2; + exports2.NeverCompare = NeverCompare2; + exports2.NeverDepth = NeverDepth2; + exports2.NeverStencilFunc = NeverStencilFunc2; + exports2.NoBlending = NoBlending2; + exports2.NoColorSpace = NoColorSpace2; + exports2.NoToneMapping = NoToneMapping2; + exports2.NormalAnimationBlendMode = NormalAnimationBlendMode2; + exports2.NormalBlending = NormalBlending2; + exports2.NotEqualCompare = NotEqualCompare2; + exports2.NotEqualDepth = NotEqualDepth2; + exports2.NotEqualStencilFunc = NotEqualStencilFunc2; + exports2.NumberKeyframeTrack = NumberKeyframeTrack2; + exports2.Object3D = Object3D2; + exports2.ObjectLoader = ObjectLoader2; + exports2.ObjectSpaceNormalMap = ObjectSpaceNormalMap2; + exports2.OctahedronGeometry = OctahedronGeometry2; + exports2.OneFactor = OneFactor2; + exports2.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor2; + exports2.OneMinusConstantColorFactor = OneMinusConstantColorFactor2; + exports2.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor2; + exports2.OneMinusDstColorFactor = OneMinusDstColorFactor2; + exports2.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor2; + exports2.OneMinusSrcColorFactor = OneMinusSrcColorFactor2; + exports2.OrthographicCamera = OrthographicCamera2; + exports2.PCFShadowMap = PCFShadowMap2; + exports2.PCFSoftShadowMap = PCFSoftShadowMap2; + exports2.PMREMGenerator = PMREMGenerator2; + exports2.Path = Path2; + exports2.PerspectiveCamera = PerspectiveCamera2; + exports2.Plane = Plane2; + exports2.PlaneGeometry = PlaneGeometry2; + exports2.PlaneHelper = PlaneHelper2; + exports2.PointLight = PointLight2; + exports2.PointLightHelper = PointLightHelper2; + exports2.Points = Points2; + exports2.PointsMaterial = PointsMaterial2; + exports2.PolarGridHelper = PolarGridHelper2; + exports2.PolyhedronGeometry = PolyhedronGeometry2; + exports2.PositionalAudio = PositionalAudio2; + exports2.PropertyBinding = PropertyBinding2; + exports2.PropertyMixer = PropertyMixer2; + exports2.QuadraticBezierCurve = QuadraticBezierCurve2; + exports2.QuadraticBezierCurve3 = QuadraticBezierCurve32; + exports2.Quaternion = Quaternion2; + exports2.QuaternionKeyframeTrack = QuaternionKeyframeTrack2; + exports2.QuaternionLinearInterpolant = QuaternionLinearInterpolant2; + exports2.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format2; + exports2.RED_RGTC1_Format = RED_RGTC1_Format2; + exports2.REVISION = REVISION2; + exports2.RGBADepthPacking = RGBADepthPacking2; + exports2.RGBAFormat = RGBAFormat2; + exports2.RGBAIntegerFormat = RGBAIntegerFormat2; + exports2.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format2; + exports2.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format2; + exports2.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format2; + exports2.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format2; + exports2.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format2; + exports2.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format2; + exports2.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format2; + exports2.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format2; + exports2.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format2; + exports2.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format2; + exports2.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format2; + exports2.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format2; + exports2.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format2; + exports2.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format2; + exports2.RGBA_BPTC_Format = RGBA_BPTC_Format2; + exports2.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format2; + exports2.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format2; + exports2.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format2; + exports2.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format2; + exports2.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format2; + exports2.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format2; + exports2.RGBDepthPacking = RGBDepthPacking2; + exports2.RGBFormat = RGBFormat2; + exports2.RGBIntegerFormat = RGBIntegerFormat2; + exports2.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format2; + exports2.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format2; + exports2.RGB_ETC1_Format = RGB_ETC1_Format2; + exports2.RGB_ETC2_Format = RGB_ETC2_Format2; + exports2.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format2; + exports2.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format2; + exports2.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format2; + exports2.RGDepthPacking = RGDepthPacking2; + exports2.RGFormat = RGFormat2; + exports2.RGIntegerFormat = RGIntegerFormat2; + exports2.RawShaderMaterial = RawShaderMaterial2; + exports2.Ray = Ray2; + exports2.Raycaster = Raycaster2; + exports2.RectAreaLight = RectAreaLight2; + exports2.RedFormat = RedFormat2; + exports2.RedIntegerFormat = RedIntegerFormat2; + exports2.ReinhardToneMapping = ReinhardToneMapping2; + exports2.RenderTarget = RenderTarget2; + exports2.RenderTarget3D = RenderTarget3D2; + exports2.RenderTargetArray = RenderTargetArray2; + exports2.RepeatWrapping = RepeatWrapping2; + exports2.ReplaceStencilOp = ReplaceStencilOp2; + exports2.ReverseSubtractEquation = ReverseSubtractEquation2; + exports2.RingGeometry = RingGeometry2; + exports2.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format2; + exports2.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format2; + exports2.SRGBColorSpace = SRGBColorSpace2; + exports2.SRGBTransfer = SRGBTransfer2; + exports2.Scene = Scene2; + exports2.ShaderChunk = ShaderChunk2; + exports2.ShaderLib = ShaderLib2; + exports2.ShaderMaterial = ShaderMaterial2; + exports2.ShadowMaterial = ShadowMaterial2; + exports2.Shape = Shape2; + exports2.ShapeGeometry = ShapeGeometry2; + exports2.ShapePath = ShapePath3; + exports2.ShapeUtils = ShapeUtils2; + exports2.ShortType = ShortType2; + exports2.Skeleton = Skeleton2; + exports2.SkeletonHelper = SkeletonHelper2; + exports2.SkinnedMesh = SkinnedMesh2; + exports2.Source = Source2; + exports2.Sphere = Sphere2; + exports2.SphereGeometry = SphereGeometry2; + exports2.Spherical = Spherical2; + exports2.SphericalHarmonics3 = SphericalHarmonics32; + exports2.SplineCurve = SplineCurve2; + exports2.SpotLight = SpotLight2; + exports2.SpotLightHelper = SpotLightHelper2; + exports2.Sprite = Sprite2; + exports2.SpriteMaterial = SpriteMaterial2; + exports2.SrcAlphaFactor = SrcAlphaFactor2; + exports2.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor2; + exports2.SrcColorFactor = SrcColorFactor2; + exports2.StaticCopyUsage = StaticCopyUsage2; + exports2.StaticDrawUsage = StaticDrawUsage2; + exports2.StaticReadUsage = StaticReadUsage2; + exports2.StereoCamera = StereoCamera2; + exports2.StreamCopyUsage = StreamCopyUsage2; + exports2.StreamDrawUsage = StreamDrawUsage2; + exports2.StreamReadUsage = StreamReadUsage2; + exports2.StringKeyframeTrack = StringKeyframeTrack2; + exports2.SubtractEquation = SubtractEquation2; + exports2.SubtractiveBlending = SubtractiveBlending2; + exports2.TOUCH = TOUCH2; + exports2.TangentSpaceNormalMap = TangentSpaceNormalMap2; + exports2.TetrahedronGeometry = TetrahedronGeometry2; + exports2.Texture = Texture2; + exports2.TextureLoader = TextureLoader2; + exports2.TextureUtils = TextureUtils2; + exports2.TimestampQuery = TimestampQuery2; + exports2.TorusGeometry = TorusGeometry2; + exports2.TorusKnotGeometry = TorusKnotGeometry2; + exports2.Triangle = Triangle2; + exports2.TriangleFanDrawMode = TriangleFanDrawMode2; + exports2.TriangleStripDrawMode = TriangleStripDrawMode2; + exports2.TrianglesDrawMode = TrianglesDrawMode2; + exports2.TubeGeometry = TubeGeometry2; + exports2.UVMapping = UVMapping2; + exports2.Uint16BufferAttribute = Uint16BufferAttribute2; + exports2.Uint32BufferAttribute = Uint32BufferAttribute2; + exports2.Uint8BufferAttribute = Uint8BufferAttribute2; + exports2.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute2; + exports2.Uniform = Uniform2; + exports2.UniformsGroup = UniformsGroup2; + exports2.UniformsLib = UniformsLib2; + exports2.UniformsUtils = UniformsUtils2; + exports2.UnsignedByteType = UnsignedByteType2; + exports2.UnsignedInt248Type = UnsignedInt248Type2; + exports2.UnsignedInt5999Type = UnsignedInt5999Type2; + exports2.UnsignedIntType = UnsignedIntType2; + exports2.UnsignedShort4444Type = UnsignedShort4444Type2; + exports2.UnsignedShort5551Type = UnsignedShort5551Type2; + exports2.UnsignedShortType = UnsignedShortType2; + exports2.VSMShadowMap = VSMShadowMap2; + exports2.Vector2 = Vector22; + exports2.Vector3 = Vector32; + exports2.Vector4 = Vector42; + exports2.VectorKeyframeTrack = VectorKeyframeTrack2; + exports2.VideoFrameTexture = VideoFrameTexture2; + exports2.VideoTexture = VideoTexture2; + exports2.WebGL3DRenderTarget = WebGL3DRenderTarget2; + exports2.WebGLArrayRenderTarget = WebGLArrayRenderTarget2; + exports2.WebGLCoordinateSystem = WebGLCoordinateSystem2; + exports2.WebGLCubeRenderTarget = WebGLCubeRenderTarget2; + exports2.WebGLRenderTarget = WebGLRenderTarget2; + exports2.WebGLRenderer = WebGLRenderer2; + exports2.WebGLUtils = WebGLUtils2; + exports2.WebGPUCoordinateSystem = WebGPUCoordinateSystem2; + exports2.WebXRController = WebXRController2; + exports2.WireframeGeometry = WireframeGeometry2; + exports2.WrapAroundEnding = WrapAroundEnding2; + exports2.ZeroCurvatureEnding = ZeroCurvatureEnding2; + exports2.ZeroFactor = ZeroFactor2; + exports2.ZeroSlopeEnding = ZeroSlopeEnding2; + exports2.ZeroStencilOp = ZeroStencilOp2; + exports2.createCanvasElement = createCanvasElement2; +}); + +// src/external/ffl.js/FFLShaderMaterial.js +var require_FFLShaderMaterial = __commonJS((exports2, module2) => { + (function(root, factory) { + if (typeof define === "function" && define.amd) { + define(["three"], factory); + } else if (typeof module2 === "object" && module2.exports) { + module2.exports = factory(require_three()); + } else { + root.FFLShaderMaterial = factory(root.THREE); + } + })(typeof self !== "undefined" ? self : exports2, function(THREE2) { + const _FFLShader_vert = ` +// 頂点シェーダーに入力される attribute 変数 +//attribute vec4 position; //!< 入力: 位置情報 +//attribute vec2 uv; //!< 入力: テクスチャー座標 +//attribute vec3 normal; //!< 入力: 法線ベクトル +// All provided by three.js ^^ + +// vertex color is not actually the color of the shape, as such +// it is a custom attribute _COLOR in the glTF + +attribute vec4 _color; //!< 入力: 頂点の色 +attribute vec3 tangent; //!< 入力: 異方位 + +// フラグメントシェーダーへの入力 +varying vec4 v_color; //!< 出力: 頂点の色 +varying vec4 v_position; //!< 出力: 位置情報 +varying vec3 v_normal; //!< 出力: 法線ベクトル +varying vec3 v_tangent; //!< 出力: 異方位 +varying vec2 v_texCoord; //!< 出力: テクスチャー座標 + +// ユニフォーム +//uniform mat3 normalMatrix; //!< ユニフォーム: モデルの法線用行列 +//uniform mat4 modelViewMatrix; //!< ユニフォーム: プロジェクション行列 +//uniform mat4 projectionMatrix; //!< ユニフォーム: モデル行列 +// All provided by three.js ^^ + +// skinning_pars_vertex.glsl.js +#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif + +void main() +{ + + // begin_vertex.glsl.js + vec3 transformed = vec3( position ); +// skinbase_vertex.glsl.js +#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); + // skinning_vertex.glsl.js + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif + +//#ifdef FFL_COORDINATE_MODE_NORMAL + // 頂点座標を変換 + v_position = modelViewMatrix * vec4(transformed, 1.0); + gl_Position = projectionMatrix * v_position; + + vec3 objectNormal = normal; + vec3 objectTangent = tangent.xyz; +// skinnormal_vertex.glsl.js +#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + +#endif + + // 法線も変換 + //v_normal = mat3(inverse(u_mv)) * a_normal; + v_normal = normalize(normalMatrix * objectNormal); +//#elif defined(FFL_COORDINATE_MODE_NONE) +// // 頂点座標を変換 +// gl_Position = vec4(a_position.x, a_position.y * -1.0, a_position.z, a_position.w); +// v_position = a_position; +// +// v_normal = a_normal; +//#endif + + // その他の情報も書き出す + v_texCoord = uv; + // safe normalize + if (tangent != vec3(0.0, 0.0, 0.0)) + { + v_tangent = normalize(normalMatrix * objectTangent); + } + else + { + v_tangent = vec3(0.0, 0.0, 0.0); + } + + v_color = _color; +} +`; + const _FFLShader_frag = ` +// +// sample.flg +// Fragment shader +// Copyright (c) 2014 Nintendo Co., Ltd. All rights reserved. +// +// + +#ifdef GL_ES +precision mediump float; +#else +# define lowp +# define mediump +# define highp +#endif + + +// +// 定数定義ファイル +// + +/// シェーダーモード +#define FFL_SHADER_MODE_UR 0 +#define FFL_SHADER_MODE_UB 1 + +/// 変調処理のマクロ +#define FFL_MODULATE_MODE_CONSTANT 0 +#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 +#define FFL_MODULATE_MODE_RGB_LAYERED 2 +#define FFL_MODULATE_MODE_ALPHA 3 +#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 +#define FFL_MODULATE_MODE_ALPHA_OPA 5 + +/// スペキュラのモード +#define FFL_SPECULAR_MODE_BLINN 0 +#define FFL_SPECULAR_MODE_ANISO 1 + +/// ライトのON/OFF +#define FFL_LIGHT_MODE_DISABLE 0 +#define FFL_LIGHT_MODE_ENABLE 1 + +/// フラグメントのディスカードモード +#define FFL_DISCARD_FRAGMENT_DISABLE 0 +#define FFL_DISCARD_FRAGMENT_ENABLE 1 + +/// 座標変換モード +#define FFL_COORDINATE_MODE_NONE 0 +#define FFL_COORDINATE_MODE_NORMAL 1 + +// +// 関数の定義ファイル +// + +/** + * @brief 異方性反射の反射率を計算します。 + * @param[in] light ライトの向き + * @param[in] tangent 接線 + * @param[in] eye 視線の向き + * @param[in] power 鋭さ + */ +mediump float calculateAnisotropicSpecular(mediump vec3 light, mediump vec3 tangent, mediump vec3 eye, mediump float power ) +{ + mediump float dotLT = dot(light, tangent); + mediump float dotVT = dot(eye, tangent); + mediump float dotLN = sqrt(1.0 - dotLT * dotLT); + mediump float dotVR = dotLN*sqrt(1.0 - dotVT * dotVT) - dotLT * dotVT; + + return pow(max(0.0, dotVR), power); +} + +/** + * @brief 異方性反射の反射率を計算します。 + * @param[in] light ライトの向き + * @param[in] normal 法線 + * @param[in] eye 視線の向き + * @param[in] power 鋭さ + */ +mediump float calculateBlinnSpecular(mediump vec3 light, mediump vec3 normal, mediump vec3 eye, mediump float power) +{ + return pow(max(dot(reflect(-light, normal), eye), 0.0), power); +} + +/** + * @brief 異方性反射、ブリン反射をブレンドします。 + * @param[in] blend ブレンド率 + * @param[in] blinn ブリンの値 + * @param[in] aniso 異方性の値 + */ +mediump float calculateSpecularBlend(mediump float blend, mediump float blinn, mediump float aniso) +{ + return mix(aniso, blinn, blend); +} + +/** + * @brief アンビエントを計算します。 + * @param[in] light ライト + * @param[in] material マテリアル + */ +mediump vec3 calculateAmbientColor(mediump vec3 light, mediump vec3 material) +{ + return light * material; +} + +/** + * @brief 拡散を計算します。 + * @param[in] light ライト + * @param[in] material マテリアル + * @param[in] ln ライトと法線の内積 + */ +mediump vec3 calculateDiffuseColor(mediump vec3 light, mediump vec3 material, mediump float ln) +{ + return light * material * ln; +} + +/** + * @brief 鏡面反射を計算します。 + * @param[in] light ライト + * @param[in] material マテリアル + * @param[in] reflection 反射率 + * @param[in] strength 幅 + */ +mediump vec3 calculateSpecularColor(mediump vec3 light, mediump vec3 material, mediump float reflection, mediump float strength) +{ + return light * material * reflection * strength; +} + +/** + * @brief リムを計算します。 + * @param[in] color リム色 + * @param[in] normalZ 法線のZ方向 + * @param[in] width リム幅 + * @param[in] power リムの鋭さ + */ +mediump vec3 calculateRimColor(mediump vec3 color, mediump float normalZ, mediump float width, mediump float power) +{ + return color * pow(width * (1.0 - abs(normalZ)), power); +} + +/** + * @brief ライト方向と法線の内積を求める + * @note 特殊な実装になっています。 + */ +mediump float calculateDot(mediump vec3 light, mediump vec3 normal) +{ + return max(dot(light, normal), 0.1); +} + +// フラグメントシェーダーに入力される varying 変数 +varying mediump vec4 v_color; //!< 出力: 頂点の色 +varying highp vec4 v_position; //!< 出力: 位置情報 +varying highp vec3 v_normal; //!< 出力: 法線ベクトル +// NOTE: ^^ Those two need to be highp to avoid weird black dot issue on Android +varying mediump vec3 v_tangent; //!< 出力: 異方位 +varying mediump vec2 v_texCoord; //!< 出力: テクスチャー座標 + +/// constカラー +uniform mediump vec4 u_const1; ///< constカラー1 +uniform mediump vec4 u_const2; ///< constカラー2 +uniform mediump vec4 u_const3; ///< constカラー3 + +/// ライト設定 +uniform mediump vec3 u_light_ambient; ///< カメラ空間のライト方向 +uniform mediump vec3 u_light_diffuse; ///< 拡散光用ライト +uniform mediump vec3 u_light_dir; +uniform bool u_light_enable; +uniform mediump vec3 u_light_specular; ///< 鏡面反射用ライト強度 + +/// マテリアル設定 +uniform mediump vec3 u_material_ambient; ///< 環境光用マテリアル設定 +uniform mediump vec3 u_material_diffuse; ///< 拡散光用マテリアル設定 +uniform mediump vec3 u_material_specular; ///< 鏡面反射用マテリアル設定 +uniform int u_material_specular_mode; ///< スペキュラの反射モード(CharModelに依存する設定のためub_modulateにしている) +uniform mediump float u_material_specular_power; ///< スペキュラの鋭さ(0.0を指定すると頂点カラーの設定が利用される) + +/// 変調設定 +uniform int u_mode; ///< 描画モード + +/// リム設定 +uniform mediump vec3 u_rim_color; +uniform mediump float u_rim_power; + +// サンプラー +uniform sampler2D s_texture; + + +// ------------------------------------------------------- +// メイン文 +void main() +{ + mediump vec4 color; + + mediump float specularPower = u_material_specular_power; + mediump float rimWidth = v_color.a; + +//#ifdef FFL_MODULATE_MODE_CONSTANT + if(u_mode == FFL_MODULATE_MODE_CONSTANT) + { + color = u_const1; + } + // modified to handle u_const1 alpha: +//#elif defined(FFL_MODULATE_MODE_TEXTURE_DIRECT) + else if(u_mode == FFL_MODULATE_MODE_TEXTURE_DIRECT) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.rgb, u_const1.a * texel.a); + } +//#elif defined(FFL_MODULATE_MODE_RGB_LAYERED) + else if(u_mode == FFL_MODULATE_MODE_RGB_LAYERED) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.r * u_const1.rgb + texel.g * u_const2.rgb + texel.b * u_const3.rgb, u_const1.a * texel.a); + } +//#elif defined(FFL_MODULATE_MODE_ALPHA) + else if(u_mode == FFL_MODULATE_MODE_ALPHA) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(u_const1.rgb, u_const1.a * texel.r); + } +//#elif defined(FFL_MODULATE_MODE_LUMINANCE_ALPHA) + else if(u_mode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.g * u_const1.rgb, u_const1.a * texel.r); + } +//#elif defined(FFL_MODULATE_MODE_ALPHA_OPA) + else if(u_mode == FFL_MODULATE_MODE_ALPHA_OPA) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.r * u_const1.rgb, u_const1.a); + } +//#endif + + // avoids little outline around mask elements + if(u_mode != FFL_MODULATE_MODE_CONSTANT && color.a == 0.0) + { + discard; + } + +//#ifdef FFL_LIGHT_MODE_ENABLE + if(u_light_enable) + { + /// 環境光の計算 + mediump vec3 ambient = calculateAmbientColor(u_light_ambient.xyz, u_material_ambient.xyz); + + /// 法線ベクトルの正規化 + mediump vec3 norm = normalize(v_normal); + + /// 視線ベクトル + mediump vec3 eye = normalize(-v_position.xyz); + + // ライトの向き + mediump float fDot = calculateDot(u_light_dir, norm); + + /// Diffuse計算 + mediump vec3 diffuse = calculateDiffuseColor(u_light_diffuse.xyz, u_material_diffuse.xyz, fDot); + + /// Specular計算 + mediump float specularBlinn = calculateBlinnSpecular(u_light_dir, norm, eye, u_material_specular_power); + + /// Specularの値を確保する変数を宣言 + mediump float reflection; + mediump float strength = v_color.g; + if(u_material_specular_mode == 0) + { + /// Blinnモデルの場合 + strength = 1.0; + reflection = specularBlinn; + } + else + { + /// Aisoモデルの場合 + mediump float specularAniso = calculateAnisotropicSpecular(u_light_dir, v_tangent, eye, u_material_specular_power); + reflection = calculateSpecularBlend(v_color.r, specularBlinn, specularAniso); + } + /// Specularの色を取得 + mediump vec3 specular = calculateSpecularColor(u_light_specular.xyz, u_material_specular.xyz, reflection, strength); + + // リムの色を計算 + mediump vec3 rimColor = calculateRimColor(u_rim_color.rgb, norm.z, rimWidth, u_rim_power); + + // カラーの計算 + color.rgb = (ambient + diffuse) * color.rgb + specular + rimColor; + } +//#endif + + gl_FragColor = color; +} +`; + + class FFLShaderMaterial extends THREE2.ShaderMaterial { + static defaultLightAmbient = new THREE2.Color(0.73, 0.73, 0.73); + static defaultLightDiffuse = new THREE2.Color(0.6, 0.6, 0.6); + static defaultLightSpecular = new THREE2.Color(0.7, 0.7, 0.7); + static defaultLightDir = new THREE2.Vector3(-0.4531539381, 0.4226179123, 0.7848858833); + static defaultRimColor = new THREE2.Color(0.3, 0.3, 0.3); + static defaultRimPower = 2; + static defaultLightDirection = this.defaultLightDir; + static materialParams = [ + { + ambient: new THREE2.Color(0.85, 0.75, 0.75), + diffuse: new THREE2.Color(0.75, 0.75, 0.75), + specular: new THREE2.Color(0.3, 0.3, 0.3), + specularPower: 1.2, + specularMode: 0 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0, 0, 0), + specularPower: 40, + specularMode: 1 + }, + { + ambient: new THREE2.Color(0.9, 0.85, 0.85), + diffuse: new THREE2.Color(0.75, 0.75, 0.75), + specular: new THREE2.Color(0.22, 0.22, 0.22), + specularPower: 1.5, + specularMode: 0 + }, + { + ambient: new THREE2.Color(0.85, 0.75, 0.75), + diffuse: new THREE2.Color(0.75, 0.75, 0.75), + specular: new THREE2.Color(0.3, 0.3, 0.3), + specularPower: 1.2, + specularMode: 0 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0.35, 0.35, 0.35), + specularPower: 10, + specularMode: 1 + }, + { + ambient: new THREE2.Color(0.75, 0.75, 0.75), + diffuse: new THREE2.Color(0.72, 0.72, 0.72), + specular: new THREE2.Color(0.3, 0.3, 0.3), + specularPower: 1.5, + specularMode: 0 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0, 0, 0), + specularPower: 40, + specularMode: 1 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0, 0, 0), + specularPower: 40, + specularMode: 1 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0, 0, 0), + specularPower: 40, + specularMode: 1 + }, + { + ambient: new THREE2.Color(0.95622, 0.95622, 0.95622), + diffuse: new THREE2.Color(0.49673, 0.49673, 0.49673), + specular: new THREE2.Color(0.24099, 0.24099, 0.24099), + specularPower: 3, + specularMode: 0 + }, + { + ambient: new THREE2.Color(0.95622, 0.95622, 0.95622), + diffuse: new THREE2.Color(1.08497, 1.08497, 1.08497), + specular: new THREE2.Color(0.2409, 0.2409, 0.2409), + specularPower: 3, + specularMode: 0 + } + ]; + constructor(options = {}) { + const uniforms = { + u_light_ambient: { + value: FFLShaderMaterial.defaultLightAmbient + }, + u_light_diffuse: { + value: FFLShaderMaterial.defaultLightDiffuse + }, + u_light_specular: { + value: FFLShaderMaterial.defaultLightSpecular + }, + u_light_dir: { value: FFLShaderMaterial.defaultLightDir.clone() }, + u_light_enable: { value: true }, + u_rim_color: { value: FFLShaderMaterial.defaultRimColor }, + u_rim_power: { value: FFLShaderMaterial.defaultRimPower } + }; + super({ + vertexShader: _FFLShader_vert, + fragmentShader: _FFLShader_frag, + uniforms + }); + this._modulateType = 0; + this.useSpecularModeBlinn = false; + this.setValues(options); + } + get color() { + if (!this.uniforms.u_const1) { + return null; + } else if (this._color3) { + return this._color3; + } + const color4 = this.uniforms.u_const1.value; + const color3 = new THREE2.Color(color4.x, color4.y, color4.z); + this._color3 = color3; + return color3; + } + set color(value2) { + function toColor4(color, opacity2 = 1) { + return new THREE2.Vector4(color.r, color.g, color.b, opacity2); + } + if (Array.isArray(value2)) { + this.uniforms.u_const1 = { value: toColor4(value2[0]) }; + this.uniforms.u_const2 = { value: toColor4(value2[1]) }; + this.uniforms.u_const3 = { value: toColor4(value2[2]) }; + return; + } + const color3 = value2 ? value2 : new THREE2.Color(1, 1, 1); + this._color3 = color3; + const opacity = this.opacity; + if (this._opacity) { + delete this._opacity; + } + this.uniforms.u_const1 = { value: toColor4(color3, opacity) }; + } + get opacity() { + if (!this.uniforms.u_const1) { + return this._opacity ? this._opacity : 1; + } + return this.uniforms.u_const1.value.w; + } + set opacity(value2) { + if (!this.uniforms || !this.uniforms.u_const1) { + this._opacity = 1; + return; + } + this.uniforms.u_const1.value.w = value2; + } + get modulateMode() { + return this.uniforms.u_mode ? this.uniforms.u_mode.value : null; + } + set modulateMode(value2) { + this.uniforms.u_mode = { value: value2 }; + } + get lightEnable() { + return this.uniforms.u_light_enable ? this.uniforms.u_light_enable.value : null; + } + set lightEnable(value2) { + this.uniforms.u_light_enable = { value: value2 }; + } + set useSpecularModeBlinn(value2) { + this._useSpecularModeBlinn = value2; + if (this._modulateType !== undefined) { + this.modulateType = this._modulateType; + } + } + get useSpecularModeBlinn() { + return this._useSpecularModeBlinn; + } + get modulateType() { + return this._modulateType; + } + set modulateType(value2) { + const matParam = FFLShaderMaterial.materialParams[value2]; + if (!matParam) { + return; + } + this._modulateType = value2; + this.uniforms.u_material_ambient = { value: matParam.ambient }; + this.uniforms.u_material_diffuse = { value: matParam.diffuse }; + this.uniforms.u_material_specular = { value: matParam.specular }; + this.uniforms.u_material_specular_mode = { + value: this._useSpecularModeBlinn ? 0 : matParam.specularMode + }; + this.uniforms.u_material_specular_power = { value: matParam.specularPower }; + } + get map() { + return this.uniforms.s_texture ? this.uniforms.s_texture.value : null; + } + set map(value2) { + this.uniforms.s_texture = { value: value2 }; + } + get lightDirection() { + return this.uniforms.u_light_dir.value; + } + set lightDirection(value2) { + this.uniforms.u_light_dir = { value: value2 }; + } + } + return FFLShaderMaterial; + }); +}); + +// src/external/ffl.js/LUTShaderMaterial.js +var require_LUTShaderMaterial = __commonJS((exports2, module2) => { + (function(root, factory) { + if (typeof define === "function" && define.amd) { + define(["three"], factory); + } else if (typeof module2 === "object" && module2.exports) { + module2.exports = factory(require_three()); + } else { + root.LUTShaderMaterial = factory(root.THREE); + } + })(typeof self !== "undefined" ? self : exports2, function(THREE2) { + const _LUTShader_vert = ` +#define AGX_FEATURE_ALBEDO_TEXTURE +/** + * @file LUT.vsh + * @brief LUT + * @since 2014/10/02 + * + * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. + */ + +// シェーダーの種類毎に設定されるマクロリスト +// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 +// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 +// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 +// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 +// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 +// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 +// AGX_FEATURE_SKIN_MASK 肌マスクが有効(uColor0) +// AGX_FEATURE_HAIR_MASK 髪マスクが有効(uColor1) +// AGX_FEATURE_ALPHA_TEST アルファテストが有効 +// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(uColor2) +// AGX_FEATURE_DISABLE_LIGHT ライトが無効 +// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 +// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 +// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 +// AGX_FEATURE_MII Miiを描画する +// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant +// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct +// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered +// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha +// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha +// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa +// +// AGX_BONE_MAX ボーンの最大数 + +#ifdef GL_ES +precision highp float; +#else +# define lowp +# define mediump +# define highp +#endif + +//#ifndef AGX_BONE_MAX +//# define AGX_BONE_MAX 15 +//#endif +#ifndef AGX_DIR_LIGHT_MAX +# define AGX_DIR_LIGHT_MAX 2 +#endif + +// ---------------------------------------- +// 頂点シェーダーに入力される attribute 変数 +//attribute highp vec3 position; //!< 入力:[ 1 : 1 ] 位置情報 +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) +//attribute mediump vec2 uv; //!< 入力:[ 1 : 5 ] テクスチャー座標 +#endif +//attribute mediump vec3 normal; //!< 入力:[ 1 : 2 ] 法線ベクトル +//attribute mediump vec4 aBoneIndex; //!< 入力:[ 1 : 3 ] ボーンのインデックス(最大4つ) +//attribute mediump vec4 aBoneWeight; //!< 入力:[ 1 : 4 ] ボーンの影響度(最大4つ) +#if defined(AGX_FEATURE_VERTEX_COLOR) +//attribute lowp vec4 _color; //!< 入力:[ 1 : 6 ] 頂点カラー +#endif +#if defined(AGX_FEATURE_BUMP_TEXTURE) +//attribute mediump vec3 tangent; //!< 入力:[ 1 : 7 ] 接線ベクトル +#endif + +// ^^ Commented attributes are provided by three.js. + +// ---------------------------------------- +// 頂点シェーダーに入力される uniform 変数 +//uniform highp mat4 modelViewMatrix; //!< 入力:[ 4 / 4 : 4 ] モデルの合成行列 +//uniform mat4 projectionMatrix; +//uniform highp mat4 viewMatrix; //!< 入力:[ 4 / 4 : 8 ] モデルのビュー行列 +//uniform mediump mat3 normalMatrix; //!< 入力:[ 3 / 3 : 11 ] モデルの法線用行列 +//uniform highp mat4 modelMatrix; //!< 入力:[ 4 / 4 : 15 ] モデルのワールド変換行列 +//uniform lowp int uBoneCount; //!< 入力:[ 1 / 1 : 16 ] ボーンの個数 +//uniform highp mat4 uBoneMatrices[AGX_BONE_MAX]; //!< 入力:[ 4 x 15 / 60 : 76 ] ボーンの行列配列 +//uniform mediump mat3 uBoneNormalMatrices[AGX_BONE_MAX]; //!< 入力:[ 3 x 15 / 45 : 121 ] ボーンの法線行列配列 +// ^^ Unused in favor of three.js skinning. +uniform lowp int uDirLightCount; //!< 入力:[ 1 / 1 : 122 ] 方向ライトの数 +uniform mediump vec4 uDirLightDirAndType0;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 +uniform mediump vec4 uDirLightDirAndType1;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 +uniform mediump vec3 uDirLightColor0; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー +uniform mediump vec3 uDirLightColor1; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー +uniform mediump vec3 uHSLightSkyColor; //!< 入力:[ 1 / 1 : 127 ] 半球ライトのスカイカラー +uniform mediump vec3 uHSLightGroundColor; //!< 入力:[ 1 / 1 : 128 ] 半球ライトのグラウンドカラー +//uniform mediump vec3 cameraPosition; //!< 入力:[ 1 / 1 : 129 ] カメラの位置 +// ^^ previously uEyePt +uniform mediump float uAlpha; //!< 入力:[ 1 / 1 : 130 ] アルファ値 + +// ^^ Commented uniforms are provided by three.js. + +// ---------------------------------------- +// フラグメントシェーダーに渡される varying 変数 +varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 +#if !defined(AGX_FEATURE_BUMP_TEXTURE) +varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 +#endif +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) +varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV +#endif +// camera +varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル +#if !defined(AGX_FEATURE_DISABLE_LIGHT) +// punctual light +varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 +varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル +// GI +varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー +// Lighting Result +varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 +#endif +// Reflect +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) +varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル +#endif + +// skinning_pars_vertex.glsl.js +#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif + +// ------------------------------------------------------------ +// 頂点シェーダーのエントリーポイント +// ------------------------------------------------------------ +void main() +{ + // ------------------------------------------------------------ + // 頂点変換用の処理 + // ------------------------------------------------------------ + highp vec4 position_; //!< 最終的な頂点 + mediump vec3 normal_; //!< 最終的な法線 + mediump vec3 tangent_; //!< 最終的な接線 + highp vec4 positionWorld; //!< ワールド空間上での頂点 + + + // begin_vertex.glsl.js + vec3 transformed = vec3( position ); +// skinbase_vertex.glsl.js +#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); + // skinning_vertex.glsl.js + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif + + // ---------------------------------------- + // ボーンが存在しない場合は位置と法線に手を加えない + position_ = vec4(transformed.xyz, 1.0); + + + + normal_ = normal; +#if defined(AGX_FEATURE_BUMP_TEXTURE) + tangent_ = tangent.xyz; +#endif + // skinnormal_vertex.glsl.js +#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + + normal_ = vec4( skinMatrix * vec4( normal_, 0.0 ) ).xyz; +#if defined(AGX_FEATURE_BUMP_TEXTURE) + tangent_ = vec4( skinMatrix * vec4( tangent_, 0.0 ) ).xyz; +#endif // defined(AGX_FEATURE_BUMP_TEXTURE) +#endif // USE_SKINNING + + // ---------------------------------------- + // ワールド上での位置を求める + positionWorld = modelMatrix * position_; + // 最終結果を行う + position_ = projectionMatrix * modelViewMatrix * position_; + normal_ = normalize(normalMatrix * normal_); +#if defined(AGX_FEATURE_BUMP_TEXTURE) + tangent = normalize(normalMatrix * tangent_); +#endif + + // ---------------------------------------- + // 計算結果を保持させる + gl_Position = position_; +#if !defined(AGX_FEATURE_BUMP_TEXTURE) + vNormal = normal_; +#endif +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) + // テクスチャー座標を設定する + vTexcoord0 = uv; +#endif + // モデルの色を指定する +#if defined(AGX_FEATURE_VERTEX_COLOR) + lowp vec4 modelColor = aColor; + +#else + lowp vec4 modelColor = vec4(1.0, 1.0, 1.0, 1.0); +#endif + + // プリマルチプライドアルファ +#if defined(AGX_FEATURE_PREMULTIPLY_ALPHA) + modelColor *= uAlpha; +#else + modelColor.a *= uAlpha; +#endif + + + // ------------------------------------------------------------ + // ライト用の処理 + // ------------------------------------------------------------ + mediump vec3 eyeVecWorld; //!< ワールド状態での視線ベクトル + mediump vec3 eyeVec; //!< 最終的にフラグメントシェーダーに渡す視線ベクトル(バンプの有無によって、ワールド座標系になったり、タンジェント座標系になったりする) + + vec4 eye = modelViewMatrix * position_; + + // 視線ベクトルを取得する + //eyeVecWorld = normalize(cameraPosition - positionWorld.xyz); + eyeVecWorld = normalize(-(eye.xyz) - positionWorld.xyz);//normalize(cameraPosition - positionWorld.xyz); + eyeVec = eyeVecWorld; + + lowp vec3 diffuseColor = vec3(0.0); // バーテックスシェーダーで計算できるディフューズの色をここに格納する + +# if defined(AGX_FEATURE_BUMP_TEXTURE) + // Normal, Binormal, Tangent を取得する + mediump vec3 n = normal; + mediump vec3 t = tangent; + mediump vec3 b = cross(n, t); + // 接空間からローカルへ変換する行列を設定する(mat3(N, T, B)の逆行列) + mediump mat3 tangentMatrix = mat3(t.x, b.x, n.x, t.y, b.y, n.y, t.z, b.z, n.z); + // 視線ベクトルを接空間へ + vEyeVecWorldOrTangent.xyz = tangentMatrix * eyeVec; +#else + vEyeVecWorldOrTangent.xyz = eyeVec; +#endif + +#if !defined(AGX_FEATURE_DISABLE_LIGHT) + // punctual lightの設定 + if (uDirLightCount > 0) + { + mediump vec3 lightDir; + + // 方向ライト + if (uDirLightDirAndType0.w < 0.0) { lightDir = uDirLightDirAndType0.xyz; } + // 点光源ライト + else { lightDir = uDirLightDirAndType0.xyz - positionWorld.xyz; } + lightDir = normalize(lightDir); + +# if defined(AGX_FEATURE_BUMP_TEXTURE) + // ライトを接空間へ + vPunctualLightDirWorldOrTangent.xyz = tangentMatrix * lightDir; +# else + vPunctualLightDirWorldOrTangent.xyz = lightDir; +# endif + + // Halfベクトルを求める + vPunctualLightHalfVecWorldOrTangent.xyz = normalize(vPunctualLightDirWorldOrTangent.xyz + vEyeVecWorldOrTangent.xyz); + + // Diffuse計算 + diffuseColor += (uDirLightColor0.rgb * clamp(dot(lightDir, normal_), 0.0, 1.0)); + } + if (uDirLightCount > 1) + { + mediump vec3 lightDir; + + // 方向ライト + if (uDirLightDirAndType1.w < 0.0) { lightDir = uDirLightDirAndType1.xyz; } + // 点光源ライト + else { lightDir = uDirLightDirAndType1.xyz - positionWorld.xyz; } + lightDir = normalize(lightDir); + + diffuseColor += max(dot(lightDir, normal_), 0.0) * uDirLightColor1; + } + // ライトは1.0を超えないように + diffuseColor = min(diffuseColor, 1.0); +#endif + +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) + { + // キューブ環境マップ用の反射ベクトルを求める +// vReflectDir = reflect(normalize(positionWorld.xyz - cameraPosition), normal_); + + // スフィア環境マップ用の反射ベクトルを求める +// vReflectDir = normalize((uViewMatrix * vec4(normal_, 0.0)).xyz) * 0.5 + 0.5; + + // ビュー座標系での位置と法線を取得 + mediump vec3 viewNormal = normalize(mat3(uViewMatrix) * normal_); + mediump vec4 viewPosition = uViewMatrix * positionWorld; + viewPosition = viewPosition / viewPosition.w; + // ビュー座標系での頂点ベクトルを取得 + viewPosition.z = 1.0 - viewPosition.z; + mediump vec3 viewPositionVec = normalize(viewPosition.xyz); + // ビュー座標系での反射ベクトルを求める + mediump vec3 viewReflect = viewPositionVec - 2.0 * dot(viewPositionVec, viewNormal) * viewNormal; + // 両面スフィア環境マップではないので、反射ベクトルを調整 + viewReflect = normalize(viewReflect - vec3(0.0, 0.0, 1.5)); + // 反射ベクトルをテクスチャー座標系へ + vReflectDir = viewReflect * 0.5 + 0.5; + + // 公式 +// mediump vec3 viewPositionVec = normalize(vec3(uViewMatrix * positionWorld)); +// mediump vec3 viewReflectVec = viewPositionVec - 2.0 * dot(viewPositionVec, normal_) * normal; +// mediump float m = 2.0 * sqrt(viewReflectVec.x * viewReflectVec.x + +// viewReflectVec.y * viewReflectVec.y + +// (viewReflectVec.z + 1.0) * (viewReflectVec.z * 1.0)); +// vReflectDir = viewReflectVec / m + 0.5; + + // 別版 +// mediump vec3 posW = positionWorld.xyz; +// mediump vec3 dir = normalize(mat3(uViewMatrix) * normal); +// +// mediump float radius = 75.0; +// mediump vec3 posWDir = dot(dir, posW) * dir; +// mediump vec3 posWDirV = posW - posWDir; +// mediump float lengthDir = sqrt(radius * radius - dot(posWDirV, posWDirV)) - length(posWDir); +// vReflectDir = normalize(posW + dir * lengthDir) * 0.5 + 0.5; + } +#endif + +#if !defined(AGX_FEATURE_DISABLE_LIGHT) + // GIの計算 + { + mediump vec3 hemiColor; + mediump vec3 sky = uHSLightSkyColor; + mediump vec3 ground = uHSLightGroundColor; + + { + mediump float skyRatio = (normal_.y + 1.0) * 0.5; + hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); + diffuseColor += hemiColor; + } + + { +// mediump vec3 reflectDir = -reflect(normal_, eyeVecWorld); // おそらくコレで良いはず + mediump vec3 reflectDir = 2.0 * dot(eyeVecWorld, normal_) * normal_ - eyeVecWorld; // 多少冗長でも、正しい計算で行なう + + mediump float skyRatio = (reflectDir.y + 1.0) * 0.5; + hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); + vGISpecularLightColor.rgb = hemiColor; + } + } +#endif + + // モデルの色を設定 + vModelColor = modelColor; +#if !defined(AGX_FEATURE_DISABLE_LIGHT) + vDiffuseColor.rgb = diffuseColor; +#endif +} +`; + const _LUTShader_frag = ` +#define AGX_FEATURE_ALBEDO_TEXTURE +#define AGX_FEATURE_MII +/** + * @file LUT.fsh + * @brief LUT + * @since 2014/10/02 + * + * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. + */ + +// シェーダーの種類毎に設定されるマクロリスト +// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 +// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 +// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 +// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 +// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 +// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 +// AGX_FEATURE_SKIN_MASK 肌マスクが有効(uColor0) +// AGX_FEATURE_HAIR_MASK 髪マスクが有効(uColor1) +// AGX_FEATURE_ALPHA_TEST アルファテストが有効 +// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(uColor2) +// AGX_FEATURE_DISABLE_LIGHT ライトが無効 +// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 +// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 +// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 +// AGX_FEATURE_MII Miiを描画する +// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant +// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct +// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered +// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha +// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha +// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa + +#ifdef GL_ES +precision mediump float; +#else +# define lowp +# define mediump +# define highp +#endif + +/// 変調処理のマクロ +#define FFL_MODULATE_MODE_CONSTANT 0 +#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 +#define FFL_MODULATE_MODE_RGB_LAYERED 2 +#define FFL_MODULATE_MODE_ALPHA 3 +#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 +#define FFL_MODULATE_MODE_ALPHA_OPA 5 + +// ---------------------------------------- +// フラグメントシェーダーに入力される uniform 変数 +uniform int uMode; ///< 描画モード +uniform bool uAlphaTest; +uniform bool uLightEnable; +uniform mediump vec4 uColor0; //!< 入力:[ 1 : 1 ] カラー0 (OR 肌カラー) +uniform mediump vec4 uColor1; //!< 入力:[ 1 : 2 ] カラー1 (OR 髪カラー) +uniform mediump vec4 uColor2; //!< 入力:[ 1 : 3 ] カラー2 (OR フェードアウトカラー) +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +uniform mediump vec3 uLightColor; //!< 入力:[ 1 : 4 ] ライトの色 +//#endif + +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) +uniform sampler2D uAlbedoTexture; //!< 入力: テクスチャー +#endif +#if defined(AGX_FEATURE_BUMP_TEXTURE) +uniform sampler2D uNormalTexture; //!< 入力: ノーマルマップ +#endif +#if defined(AGX_FEATURE_MASK_TEXTURE) +uniform sampler2D uMaskTexture; //!< 入力:マスクテクスチャー +#endif +#if defined(AGX_FEATURE_ALPHA_TEXTURE) +uniform sampler2D uAlphaTexture; //!< 入力:アルファテクスチャー +#endif +uniform sampler2D uLUTSpecTexture; //!< 入力: スペキュラーLUT +uniform sampler2D uLUTFresTexture; //!< 入力: フレネルLUT +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) +uniform sampler2D uSphereMapTexture; //!< 入力: スフィア環境マップ +#endif + +// ---------------------------------------- +// フラグメントシェーダーに渡される varying 変数 +varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 +#if !defined(AGX_FEATURE_BUMP_TEXTURE) +varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 +#endif +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) +varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV +#endif +// camera +varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +// punctual light +varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 +varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル +// GI +varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー +// Lighting Result +varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 +//#endif +// Reflect +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) +varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル +#endif + +// ------------------------------------------------------------ +// フラグメントシェーダーのエントリーポイント +// ------------------------------------------------------------ +void main() +{ + + // ディフューズカラーを取得 + lowp vec4 albedoColor = vec4(1.0, 1.0, 1.0, 1.0); + + // ============================================================ + // Mii + // ============================================================ +#if defined(AGX_FEATURE_MII) + + //#if defined(AGX_FEATURE_MII_CONSTANT) + if(uMode == FFL_MODULATE_MODE_CONSTANT) + { + albedoColor = uColor0; + } + //#elif defined(AGX_FEATURE_MII_TEXTURE_DIRECT) + else if(uMode == FFL_MODULATE_MODE_TEXTURE_DIRECT) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + } + //#elif defined(AGX_FEATURE_MII_RGB_LAYERED) + else if(uMode == FFL_MODULATE_MODE_RGB_LAYERED) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(albedoColor.r * uColor0.rgb + albedoColor.g * uColor1.rgb + albedoColor.b * uColor2.rgb, + uColor0.a * albedoColor.a); + } + //#elif defined(AGX_FEATURE_MII_ALPHA) + else if(uMode == FFL_MODULATE_MODE_ALPHA) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(uColor0.rgb, uColor0.a * albedoColor.r); + } + //#elif defined(AGX_FEATURE_MII_LUMINANCE_ALPHA) + else if(uMode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(albedoColor.g * uColor0.rgb, uColor0.a * albedoColor.r); + } + //#elif defined(AGX_FEATURE_MII_ALPHA_OPA) + else if(uMode == FFL_MODULATE_MODE_ALPHA_OPA) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(albedoColor.r * uColor0.rgb, uColor0.a); + } +//#endif + + albedoColor = albedoColor * vModelColor; +#endif + + // ============================================================ + // Albedo Texture + // ============================================================ +#if !defined(AGX_FEATURE_MII) && defined(AGX_FEATURE_ALBEDO_TEXTURE) + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); +#endif +#if defined(AGX_FEATURE_ALPHA_TEXTURE) + albedoColor.a = texture2D(uAlphaTexture, vTexcoord0).r; +#endif + + // ============================================================ + // Color Mask + // ============================================================ + // ---------------------------------------- + // Deprecated +#if defined(AGX_FEATURE_ALPHA_COLOR_FILTER) + // 一部の場所にColor0を反映する + albedoColor.rgb = (albedoColor.rgb * albedoColor.a + uColor0.rgb * (1.0 - albedoColor.a)); + albedoColor.a = 1.0; +#elif defined(AGX_FEATURE_MASK_TEXTURE) + lowp vec3 maskTextureColor = texture2D(uMaskTexture, vTexcoord0).rgb; + +# if defined(AGX_FEATURE_SKIN_MASK) && defined(AGX_FEATURE_HAIR_MASK) + // 肌と髪両方マスクが存在する + lowp float maskColorValue = maskTextureColor.g + maskTextureColor.b; + lowp vec3 maskColor = maskTextureColor.g * uColor0.rgb + maskTextureColor.b * uColor1.rgb; + albedoColor.rgb = (albedoColor.rgb * (1.0 - maskColorValue) + maskColor); + +# elif defined(AGX_FEATURE_SKIN_MASK) + // 肌しかマスクが存在しない + albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.g) + maskTextureColor.g * uColor0.rgb); + +# elif defined(AGX_FEATURE_HAIR_MASK) + // 髪しかマスクが存在しない + albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.b) + maskTextureColor.b * uColor1.rgb); + +# endif +#endif + + // アルベドに頂点カラーを掛ける + albedoColor *= vModelColor; + + // ============================================================ + // Alpha test + // ============================================================ +//#if defined(AGX_FEATURE_ALPHA_TEST) + if (uAlphaTest && albedoColor.a < 0.5) { discard; } +//#endif + + // ============================================================ + // Bumpmap + // ============================================================ + // 頂点からの情報 + lowp vec3 normalWorldOrTangent; +#if defined(AGX_FEATURE_BUMP_TEXTURE) + // バンプマップから法線を取得する + mediump vec3 bumpNormal = texture2D(uNormalTexture, vTexcoord0).rgb; + + // 法線の正規化は処理が重いのでいったん正規化しない様に... +// normalWorldOrTangent = normalize(bumpNormal * 2.0 - 1.0); + normalWorldOrTangent = bumpNormal * 2.0 - 1.0; + +#else + // 法線を正規化して取得する + normalWorldOrTangent = normalize(vNormal); +#endif + + // ============================================================ + // Lighting + // ============================================================ + // 最終的なカラー情報 + lowp vec4 colorOut = vec4(0.0, 0.0, 0.0, albedoColor.a); // 最終的に出力される色 + lowp vec3 fresnel = vec3(0.0, 0.0, 0.0); // フレネル + lowp vec3 specular = vec3(0.0, 0.0, 0.0); // スペキュラー + +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +if (uLightEnable) { + + // BRDFの計算を行う(バンプマッピングの場合は接空間) + lowp vec3 N = normalWorldOrTangent; + lowp vec3 V = vEyeVecWorldOrTangent.xyz;//normalize(vEyeVecWorldOrTangent.xyz); + lowp vec3 I = vPunctualLightDirWorldOrTangent.xyz;//normalize(vPunctualLightDirWorldOrTangent.xyz); + lowp vec3 H = vPunctualLightHalfVecWorldOrTangent.xyz;//normalize(vPunctualLightHalfVecWorldOrTangent.xyz); + + + // ---------------------------------------- + // punctual light + // 平行光源や点光源などの厳密なライティング計算を行なうもの + { + lowp float fSpecular = dot(N, H); + + lowp float specularIntensity = texture2D(uLUTSpecTexture, vec2(fSpecular)).r; + specular = (specularIntensity * uLightColor.rgb); + } + + // ---------------------------------------- + // GI + // 半球ライトやIBL、SHのように法線方向に半球積分された結果でライティング計算を行なうもの + { + lowp float fFresnel = dot(N, V); + lowp float fresnelIntensity = texture2D(uLUTFresTexture, vec2(fFresnel)).r; + + fresnel = (fresnelIntensity * vGISpecularLightColor.rgb); + } +} +//#endif + +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) + // スフィア環境マップ + specular += texture2D(uSphereMapTexture, vReflectDir.xy).rgb; +#endif + + // ============================================================ + // Specular Mask + // ============================================================ +#if !defined(AGX_FEATURE_ALPHA_COLOR_FILTER) && defined(AGX_FEATURE_MASK_TEXTURE) + // スペキュラーマスク + specular = specular * maskTextureColor.r + fresnel; +#else + specular += fresnel; +#endif + + // ============================================================ + // Output + // ============================================================ +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +if (uLightEnable) + colorOut.rgb = vDiffuseColor.rgb * albedoColor.rgb + specular; +//#else +else + colorOut.rgb = albedoColor.rgb; +//#endif + + // フェードアウトを実装する +#if defined(AGX_FEATURE_FADE_OUT_COLOR) + colorOut.rgb = (colorOut.rgb * (1.0 - uColor2.a)) + (uColor2.rgb * uColor2.a); +#endif + + // 色を反映させる + gl_FragColor = colorOut; + + //#include + //#include +} +`; + + class HermitianCurve { + constructor(keys2) { + this.keys = keys2.sort((a, b) => a.x - b.x); + } + interpolate(t, p0, p1, m0, m1) { + const h00 = 2 * t * t * t - 3 * t * t + 1; + const h10 = t * t * t - 2 * t * t + t; + const h01 = -2 * t * t * t + 3 * t * t; + const h11 = t * t * t - t * t; + return h00 * p0 + h10 * m0 + h01 * p1 + h11 * m1; + } + clamp(value2, min, max) { + return Math.min(Math.max(value2, min), max); + } + generateLUT(lutSize = 512) { + const lut = new Uint8Array(lutSize); + let keyIdx = 0; + for (let i = 0;i < lutSize; i++) { + const pos = i / (lutSize - 1); + while (keyIdx < this.keys.length - 2 && pos > this.keys[keyIdx + 1].x) { + keyIdx++; + } + const p0 = this.keys[keyIdx]; + const p1 = this.keys[keyIdx + 1]; + let t = (pos - p0.x) / (p1.x - p0.x); + t = isNaN(t) ? 0 : t; + const y = this.interpolate(t, p0.y, p1.y, p0.dx * (p1.x - p0.x), p1.dx * (p1.x - p0.x)); + lut[i] = Math.round(this.clamp(y, 0, 1) * 255); + } + return lut; + } + } + + class LUTShaderMaterial extends THREE2.ShaderMaterial { + static LUTSpecularTextureType = { + NONE: 0, + DEFAULT_02: 1, + SKIN_01: 2, + MAX: 3 + }; + static LUTFresnelTextureType = { + NONE: 0, + DEFAULT_02: 1, + SKIN_01: 2, + MAX: 3 + }; + static lutDefinitions = { + specular: { + [LUTShaderMaterial.LUTSpecularTextureType.NONE]: new HermitianCurve([ + { x: 0, y: 0, dx: 0, dy: 0 }, + { x: 1, y: 0, dx: 0, dy: 0 } + ]), + [LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02]: new HermitianCurve([ + { x: 0, y: 0, dx: 0, dy: 0 }, + { x: 0.05, y: 0, dx: 0, dy: 0 }, + { + x: 0.8, + y: 0.038, + dx: 0.157894736842105, + dy: 0.157894736842105 + }, + { x: 1, y: 0.11, dx: 0, dy: 0 } + ]), + [LUTShaderMaterial.LUTSpecularTextureType.SKIN_01]: new HermitianCurve([ + { + x: 0, + y: 0.03, + dx: -0.105263157894737, + dy: -0.105263157894737 + }, + { x: 1, y: 0, dx: 0, dy: 0 } + ]) + }, + fresnel: { + [LUTShaderMaterial.LUTFresnelTextureType.NONE]: new HermitianCurve([ + { x: 0, y: 0, dx: 0, dy: 0 }, + { x: 1, y: 0, dx: 0, dy: 0 } + ]), + [LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02]: new HermitianCurve([ + { + x: 0, + y: 0.3, + dx: -0.105263157894734, + dy: -0.105263157894734 + }, + { + x: 0.175, + y: 0.23, + dx: -0.626315789473681, + dy: -0.626315789473681 + }, + { + x: 0.6, + y: 0.05, + dx: -0.210526315789474, + dy: -0.210526315789474 + }, + { + x: 1, + y: 0, + dx: -0.105263157894737, + dy: -0.105263157894737 + } + ]), + [LUTShaderMaterial.LUTFresnelTextureType.SKIN_01]: new HermitianCurve([ + { + x: 0.005, + y: 0.35, + dx: -0.105263157894734, + dy: -0.105263157894734 + }, + { + x: 0.173, + y: 0.319, + dx: -0.205263157894734, + dy: -0.205263157894734 + }, + { + x: 0.552, + y: 0.051, + dx: -0.210526315789474, + dy: -0.210526315789474 + }, + { x: 1, y: 0.001, dx: 0, dy: 0 } + ]) + } + }; + static modulateTypeToLUTSpecular = [ + LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, + LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.NONE, + LUTShaderMaterial.LUTSpecularTextureType.NONE, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02 + ]; + static modulateTypeToLUTFresnel = [ + LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, + LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.NONE, + LUTShaderMaterial.LUTFresnelTextureType.NONE, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02 + ]; + static _lutTextures = null; + static getLUTTextures(lutSize = 512) { + if (LUTShaderMaterial._lutTextures) { + return LUTShaderMaterial._lutTextures; + } + const textures = { specular: {}, fresnel: {} }; + const r8 = Number(THREE2.REVISION) <= 136 ? THREE2.LuminanceFormat : THREE2.RedFormat; + function generateLUTTextures(lutType, target) { + for (const key2 in lutType) { + const lutData = lutType[key2].generateLUT(lutSize); + target[Number(key2)] = Object.assign(new THREE2.DataTexture(lutData, lutSize, 1, r8, THREE2.UnsignedByteType), { + colorSpace: THREE2.LinearSRGBColorSpace, + needsUpdate: true + }); + } + } + generateLUTTextures(LUTShaderMaterial.lutDefinitions.specular, textures.specular); + generateLUTTextures(LUTShaderMaterial.lutDefinitions.fresnel, textures.fresnel); + LUTShaderMaterial._lutTextures = textures; + return textures; + } + static defaultHSLightGroundColor = new THREE2.Color(0.87843, 0.72157, 0.5898); + static defaultHSLightSkyColor = new THREE2.Color(0.87843, 0.83451, 0.80314); + static defaultDirLightColor0 = new THREE2.Color(0.35137, 0.32392, 0.32392); + static defaultDirLightColor1 = new THREE2.Color(0.10039, 0.09255, 0.09255); + static defaultDirLightCount = 2; + static defaultDirLightDirAndType0 = new THREE2.Vector4(-0.2, 0.5, 0.8, -1); + static defaultDirLightDirAndType1 = new THREE2.Vector4(0, -0.19612, 0.98058, -1); + static defaultLightColor = new THREE2.Color(0.35137, 0.32392, 0.32392); + static defaultLightDirection = this.defaultDirLightDirAndType0; + static multiplyColorIfNeeded(color, modulateType, modulateMode) { + if (modulateType === 1 || modulateType === 4 || modulateMode === 0 && modulateType === 9) { + const mul2 = 0.9019608; + color.r *= mul2; + color.g *= mul2; + color.b *= mul2; + } + return color; + } + constructor(options = {}) { + const uniforms = { + uBoneCount: { value: 0 }, + uAlpha: { value: 1 }, + uHSLightGroundColor: { + value: LUTShaderMaterial.defaultHSLightGroundColor + }, + uHSLightSkyColor: { + value: LUTShaderMaterial.defaultHSLightSkyColor + }, + uDirLightColor0: { + value: LUTShaderMaterial.defaultDirLightColor0 + }, + uDirLightColor1: { + value: LUTShaderMaterial.defaultDirLightColor1 + }, + uDirLightCount: { + value: LUTShaderMaterial.defaultDirLightCount + }, + uDirLightDirAndType0: { + value: LUTShaderMaterial.defaultDirLightDirAndType0.clone() + }, + uDirLightDirAndType1: { + value: LUTShaderMaterial.defaultDirLightDirAndType1.clone() + }, + uLightEnable: { value: true }, + uLightColor: { value: LUTShaderMaterial.defaultLightColor } + }; + super({ + vertexShader: _LUTShader_vert, + fragmentShader: _LUTShader_frag, + uniforms + }); + this._modulateType = 0; + this.setValues(options); + } + get color() { + if (!this.uniforms.uColor0) { + return null; + } else if (this._color3) { + return this._color3; + } + const color4 = this.uniforms.uColor0.value; + const color3 = new THREE2.Color(color4.x, color4.y, color4.z); + this._color3 = color3; + return color3; + } + set color(value2) { + function toColor4(color, opacity2 = 1) { + return new THREE2.Vector4(color.r, color.g, color.b, opacity2); + } + if (Array.isArray(value2)) { + this.uniforms.uColor0 = { value: toColor4(value2[0]) }; + this.uniforms.uColor1 = { value: toColor4(value2[1]) }; + this.uniforms.uColor2 = { value: toColor4(value2[2]) }; + return; + } + const color3 = value2 ? value2 : new THREE2.Color(1, 1, 1); + this._color3 = color3.clone(); + if (this.modulateType !== undefined && typeof this.modulateMode === "number") { + LUTShaderMaterial.multiplyColorIfNeeded(color3, this.modulateType, this.modulateMode); + } + const opacity = this.opacity; + if (this._opacity) { + delete this._opacity; + } + this.uniforms.uColor0 = { value: toColor4(color3, opacity) }; + } + get opacity() { + if (!this.uniforms.uColor0) { + return this._opacity ? this._opacity : 1; + } + return this.uniforms.uColor0.value.w; + } + set opacity(value2) { + if (!this.uniforms || !this.uniforms.uColor0) { + this._opacity = 1; + return; + } + this.uniforms.uColor0.value.w = value2; + } + get modulateMode() { + return this.uniforms.uMode ? this.uniforms.uMode.value : null; + } + set modulateMode(value2) { + this.uniforms.uMode = { value: value2 }; + } + get lightEnable() { + return this.uniforms.uLightEnable ? this.uniforms.uLightEnable.value : null; + } + set lightEnable(value2) { + this.uniforms.uLightEnable = { value: value2 }; + } + get modulateType() { + return this._modulateType; + } + set modulateType(value2) { + const lutTextures = LUTShaderMaterial.getLUTTextures(); + const specType = LUTShaderMaterial.modulateTypeToLUTSpecular[value2]; + const fresType = LUTShaderMaterial.modulateTypeToLUTFresnel[value2]; + if (specType === undefined || fresType === undefined) { + return; + } + this._modulateType = value2; + const lutSpecTexture = lutTextures.specular[specType]; + const lutFresTexture = lutTextures.fresnel[fresType]; + this.uniforms.uLUTSpecTexture = { value: lutSpecTexture }; + this.uniforms.uLUTFresTexture = { value: lutFresTexture }; + this.uniforms.uAlphaTest = { + value: value2 >= 6 && value2 <= 8 + }; + this._side = this.side; + this.side = value2 === 6 ? THREE2.DoubleSide : this.side; + } + get map() { + return this.uniforms.uAlbedoTexture ? this.uniforms.uAlbedoTexture.value : null; + } + set map(value2) { + this.uniforms.uAlbedoTexture = { value: value2 }; + } + get lightDirection() { + return this.uniforms.uDirLightDirAndType0.value; + } + set lightDirection(value2) { + this.uniforms.uDirLightDirAndType0 = { value: value2 }; + this.uniforms.uDirLightDirAndType0.value.w = -1; + } + } + return LUTShaderMaterial; + }); +}); + +// node_modules/localforage/dist/localforage.js +var require_localforage = __commonJS((exports2, module2) => { + /*! + localForage -- Offline Storage, Improved + Version 1.10.0 + https://localforage.github.io/localForage + (c) 2013-2017 Mozilla, Apache License 2.0 + */ + (function(f) { + if (typeof exports2 === "object" && typeof module2 !== "undefined") { + module2.exports = f(); + } else if (typeof define === "function" && define.amd) { + define([], f); + } else { + var g; + if (typeof window !== "undefined") { + g = window; + } else if (typeof global !== "undefined") { + g = global; + } else if (typeof self !== "undefined") { + g = self; + } else { + g = this; + } + g.localforage = f(); + } + })(function() { + var define2, module3, exports3; + return function e(t, n, r) { + function s(o2, u) { + if (!n[o2]) { + if (!t[o2]) { + var a = __require; + if (!u && a) + return a(o2, true); + if (i) + return i(o2, true); + var f = new Error("Cannot find module '" + o2 + "'"); + throw f.code = "MODULE_NOT_FOUND", f; + } + var l = n[o2] = { exports: {} }; + t[o2][0].call(l.exports, function(e) { + var n2 = t[o2][1][e]; + return s(n2 ? n2 : e); + }, l, l.exports, e, t, n, r); + } + return n[o2].exports; + } + var i = __require; + for (var o = 0;o < r.length; o++) + s(r[o]); + return s; + }({ 1: [function(_dereq_, module4, exports4) { + (function(global2) { + var Mutation = global2.MutationObserver || global2.WebKitMutationObserver; + var scheduleDrain; + { + if (Mutation) { + var called = 0; + var observer = new Mutation(nextTick); + var element = global2.document.createTextNode(""); + observer.observe(element, { + characterData: true + }); + scheduleDrain = function() { + element.data = called = ++called % 2; + }; + } else if (!global2.setImmediate && typeof global2.MessageChannel !== "undefined") { + var channel = new global2.MessageChannel; + channel.port1.onmessage = nextTick; + scheduleDrain = function() { + channel.port2.postMessage(0); + }; + } else if ("document" in global2 && "onreadystatechange" in global2.document.createElement("script")) { + scheduleDrain = function() { + var scriptEl = global2.document.createElement("script"); + scriptEl.onreadystatechange = function() { + nextTick(); + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + global2.document.documentElement.appendChild(scriptEl); + }; + } else { + scheduleDrain = function() { + setTimeout(nextTick, 0); + }; + } + } + var draining; + var queue = []; + function nextTick() { + draining = true; + var i, oldQueue; + var len = queue.length; + while (len) { + oldQueue = queue; + queue = []; + i = -1; + while (++i < len) { + oldQueue[i](); + } + len = queue.length; + } + draining = false; + } + module4.exports = immediate; + function immediate(task) { + if (queue.push(task) === 1 && !draining) { + scheduleDrain(); + } + } + }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); + }, {}], 2: [function(_dereq_, module4, exports4) { + var immediate = _dereq_(1); + function INTERNAL() { + } + var handlers = {}; + var REJECTED = ["REJECTED"]; + var FULFILLED = ["FULFILLED"]; + var PENDING = ["PENDING"]; + module4.exports = Promise2; + function Promise2(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("resolver must be a function"); + } + this.state = PENDING; + this.queue = []; + this.outcome = undefined; + if (resolver !== INTERNAL) { + safelyResolveThenable(this, resolver); + } + } + Promise2.prototype["catch"] = function(onRejected) { + return this.then(null, onRejected); + }; + Promise2.prototype.then = function(onFulfilled, onRejected) { + if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) { + return this; + } + var promise = new this.constructor(INTERNAL); + if (this.state !== PENDING) { + var resolver = this.state === FULFILLED ? onFulfilled : onRejected; + unwrap(promise, resolver, this.outcome); + } else { + this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); + } + return promise; + }; + function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === "function") { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === "function") { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } + } + QueueItem.prototype.callFulfilled = function(value2) { + handlers.resolve(this.promise, value2); + }; + QueueItem.prototype.otherCallFulfilled = function(value2) { + unwrap(this.promise, this.onFulfilled, value2); + }; + QueueItem.prototype.callRejected = function(value2) { + handlers.reject(this.promise, value2); + }; + QueueItem.prototype.otherCallRejected = function(value2) { + unwrap(this.promise, this.onRejected, value2); + }; + function unwrap(promise, func, value2) { + immediate(function() { + var returnValue; + try { + returnValue = func(value2); + } catch (e) { + return handlers.reject(promise, e); + } + if (returnValue === promise) { + handlers.reject(promise, new TypeError("Cannot resolve promise with itself")); + } else { + handlers.resolve(promise, returnValue); + } + }); + } + handlers.resolve = function(self2, value2) { + var result = tryCatch(getThen, value2); + if (result.status === "error") { + return handlers.reject(self2, result.value); + } + var thenable = result.value; + if (thenable) { + safelyResolveThenable(self2, thenable); + } else { + self2.state = FULFILLED; + self2.outcome = value2; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callFulfilled(value2); + } + } + return self2; + }; + handlers.reject = function(self2, error) { + self2.state = REJECTED; + self2.outcome = error; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callRejected(error); + } + return self2; + }; + function getThen(obj) { + var then = obj && obj.then; + if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") { + return function appyThen() { + then.apply(obj, arguments); + }; + } + } + function safelyResolveThenable(self2, thenable) { + var called = false; + function onError(value2) { + if (called) { + return; + } + called = true; + handlers.reject(self2, value2); + } + function onSuccess(value2) { + if (called) { + return; + } + called = true; + handlers.resolve(self2, value2); + } + function tryToUnwrap() { + thenable(onSuccess, onError); + } + var result = tryCatch(tryToUnwrap); + if (result.status === "error") { + onError(result.value); + } + } + function tryCatch(func, value2) { + var out = {}; + try { + out.value = func(value2); + out.status = "success"; + } catch (e) { + out.status = "error"; + out.value = e; + } + return out; + } + Promise2.resolve = resolve; + function resolve(value2) { + if (value2 instanceof this) { + return value2; + } + return handlers.resolve(new this(INTERNAL), value2); + } + Promise2.reject = reject2; + function reject2(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); + } + Promise2.all = all; + function all(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var values2 = new Array(len); + var resolved = 0; + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + allResolver(iterable[i], i); + } + return promise; + function allResolver(value2, i2) { + self2.resolve(value2).then(resolveFromAll, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values2[i2] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values2); + } + } + } + } + Promise2.race = race; + function race(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + resolver(iterable[i]); + } + return promise; + function resolver(value2) { + self2.resolve(value2).then(function(response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } + } + }, { "1": 1 }], 3: [function(_dereq_, module4, exports4) { + (function(global2) { + if (typeof global2.Promise !== "function") { + global2.Promise = _dereq_(2); + } + }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); + }, { "2": 2 }], 4: [function(_dereq_, module4, exports4) { + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) { + return typeof obj; + } : function(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function getIDB() { + try { + if (typeof indexedDB !== "undefined") { + return indexedDB; + } + if (typeof webkitIndexedDB !== "undefined") { + return webkitIndexedDB; + } + if (typeof mozIndexedDB !== "undefined") { + return mozIndexedDB; + } + if (typeof OIndexedDB !== "undefined") { + return OIndexedDB; + } + if (typeof msIndexedDB !== "undefined") { + return msIndexedDB; + } + } catch (e) { + return; + } + } + var idb = getIDB(); + function isIndexedDBValid() { + try { + if (!idb || !idb.open) { + return false; + } + var isSafari2 = typeof openDatabase !== "undefined" && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform); + var hasFetch = typeof fetch === "function" && fetch.toString().indexOf("[native code") !== -1; + return (!isSafari2 || hasFetch) && typeof indexedDB !== "undefined" && typeof IDBKeyRange !== "undefined"; + } catch (e) { + return false; + } + } + function createBlob(parts, properties) { + parts = parts || []; + properties = properties || {}; + try { + return new Blob(parts, properties); + } catch (e) { + if (e.name !== "TypeError") { + throw e; + } + var Builder = typeof BlobBuilder !== "undefined" ? BlobBuilder : typeof MSBlobBuilder !== "undefined" ? MSBlobBuilder : typeof MozBlobBuilder !== "undefined" ? MozBlobBuilder : WebKitBlobBuilder; + var builder = new Builder; + for (var i = 0;i < parts.length; i += 1) { + builder.append(parts[i]); + } + return builder.getBlob(properties.type); + } + } + if (typeof Promise === "undefined") { + _dereq_(3); + } + var Promise$1 = Promise; + function executeCallback(promise, callback) { + if (callback) { + promise.then(function(result) { + callback(null, result); + }, function(error) { + callback(error); + }); + } + } + function executeTwoCallbacks(promise, callback, errorCallback) { + if (typeof callback === "function") { + promise.then(callback); + } + if (typeof errorCallback === "function") { + promise["catch"](errorCallback); + } + } + function normalizeKey(key3) { + if (typeof key3 !== "string") { + console.warn(key3 + " used as a key, but it is not a string."); + key3 = String(key3); + } + return key3; + } + function getCallback() { + if (arguments.length && typeof arguments[arguments.length - 1] === "function") { + return arguments[arguments.length - 1]; + } + } + var DETECT_BLOB_SUPPORT_STORE = "local-forage-detect-blob-support"; + var supportsBlobs = undefined; + var dbContexts = {}; + var toString2 = Object.prototype.toString; + var READ_ONLY = "readonly"; + var READ_WRITE = "readwrite"; + function _binStringToArrayBuffer(bin) { + var length3 = bin.length; + var buf = new ArrayBuffer(length3); + var arr = new Uint8Array(buf); + for (var i = 0;i < length3; i++) { + arr[i] = bin.charCodeAt(i); + } + return buf; + } + function _checkBlobSupportWithoutCaching(idb2) { + return new Promise$1(function(resolve) { + var txn = idb2.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE); + var blob = createBlob([""]); + txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, "key"); + txn.onabort = function(e) { + e.preventDefault(); + e.stopPropagation(); + resolve(false); + }; + txn.oncomplete = function() { + var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); + var matchedEdge = navigator.userAgent.match(/Edge\//); + resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43); + }; + })["catch"](function() { + return false; + }); + } + function _checkBlobSupport(idb2) { + if (typeof supportsBlobs === "boolean") { + return Promise$1.resolve(supportsBlobs); + } + return _checkBlobSupportWithoutCaching(idb2).then(function(value2) { + supportsBlobs = value2; + return supportsBlobs; + }); + } + function _deferReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + var deferredOperation = {}; + deferredOperation.promise = new Promise$1(function(resolve, reject2) { + deferredOperation.resolve = resolve; + deferredOperation.reject = reject2; + }); + dbContext.deferredOperations.push(deferredOperation); + if (!dbContext.dbReady) { + dbContext.dbReady = deferredOperation.promise; + } else { + dbContext.dbReady = dbContext.dbReady.then(function() { + return deferredOperation.promise; + }); + } + } + function _advanceReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + var deferredOperation = dbContext.deferredOperations.pop(); + if (deferredOperation) { + deferredOperation.resolve(); + return deferredOperation.promise; + } + } + function _rejectReadiness(dbInfo, err) { + var dbContext = dbContexts[dbInfo.name]; + var deferredOperation = dbContext.deferredOperations.pop(); + if (deferredOperation) { + deferredOperation.reject(err); + return deferredOperation.promise; + } + } + function _getConnection(dbInfo, upgradeNeeded) { + return new Promise$1(function(resolve, reject2) { + dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext(); + if (dbInfo.db) { + if (upgradeNeeded) { + _deferReadiness(dbInfo); + dbInfo.db.close(); + } else { + return resolve(dbInfo.db); + } + } + var dbArgs = [dbInfo.name]; + if (upgradeNeeded) { + dbArgs.push(dbInfo.version); + } + var openreq = idb.open.apply(idb, dbArgs); + if (upgradeNeeded) { + openreq.onupgradeneeded = function(e) { + var db = openreq.result; + try { + db.createObjectStore(dbInfo.storeName); + if (e.oldVersion <= 1) { + db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); + } + } catch (ex) { + if (ex.name === "ConstraintError") { + console.warn('The database "' + dbInfo.name + '"' + " has been upgraded from version " + e.oldVersion + " to version " + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); + } else { + throw ex; + } + } + }; + } + openreq.onerror = function(e) { + e.preventDefault(); + reject2(openreq.error); + }; + openreq.onsuccess = function() { + var db = openreq.result; + db.onversionchange = function(e) { + e.target.close(); + }; + resolve(db); + _advanceReadiness(dbInfo); + }; + }); + } + function _getOriginalConnection(dbInfo) { + return _getConnection(dbInfo, false); + } + function _getUpgradedConnection(dbInfo) { + return _getConnection(dbInfo, true); + } + function _isUpgradeNeeded(dbInfo, defaultVersion) { + if (!dbInfo.db) { + return true; + } + var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); + var isDowngrade = dbInfo.version < dbInfo.db.version; + var isUpgrade = dbInfo.version > dbInfo.db.version; + if (isDowngrade) { + if (dbInfo.version !== defaultVersion) { + console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + " to version " + dbInfo.version + "."); + } + dbInfo.version = dbInfo.db.version; + } + if (isUpgrade || isNewStore) { + if (isNewStore) { + var incVersion = dbInfo.db.version + 1; + if (incVersion > dbInfo.version) { + dbInfo.version = incVersion; + } + } + return true; + } + return false; + } + function _encodeBlob(blob) { + return new Promise$1(function(resolve, reject2) { + var reader = new FileReader; + reader.onerror = reject2; + reader.onloadend = function(e) { + var base64 = btoa(e.target.result || ""); + resolve({ + __local_forage_encoded_blob: true, + data: base64, + type: blob.type + }); + }; + reader.readAsBinaryString(blob); + }); + } + function _decodeBlob(encodedBlob) { + var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); + return createBlob([arrayBuff], { type: encodedBlob.type }); + } + function _isEncodedBlob(value2) { + return value2 && value2.__local_forage_encoded_blob; + } + function _fullyReady(callback) { + var self2 = this; + var promise = self2._initReady().then(function() { + var dbContext = dbContexts[self2._dbInfo.name]; + if (dbContext && dbContext.dbReady) { + return dbContext.dbReady; + } + }); + executeTwoCallbacks(promise, callback, callback); + return promise; + } + function _tryReconnect(dbInfo) { + _deferReadiness(dbInfo); + var dbContext = dbContexts[dbInfo.name]; + var forages = dbContext.forages; + for (var i = 0;i < forages.length; i++) { + var forage = forages[i]; + if (forage._dbInfo.db) { + forage._dbInfo.db.close(); + forage._dbInfo.db = null; + } + } + dbInfo.db = null; + return _getOriginalConnection(dbInfo).then(function(db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo)) { + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function(db) { + dbInfo.db = dbContext.db = db; + for (var i2 = 0;i2 < forages.length; i2++) { + forages[i2]._dbInfo.db = db; + } + })["catch"](function(err) { + _rejectReadiness(dbInfo, err); + throw err; + }); + } + function createTransaction(dbInfo, mode, callback, retries) { + if (retries === undefined) { + retries = 1; + } + try { + var tx = dbInfo.db.transaction(dbInfo.storeName, mode); + callback(null, tx); + } catch (err) { + if (retries > 0 && (!dbInfo.db || err.name === "InvalidStateError" || err.name === "NotFoundError")) { + return Promise$1.resolve().then(function() { + if (!dbInfo.db || err.name === "NotFoundError" && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) { + if (dbInfo.db) { + dbInfo.version = dbInfo.db.version + 1; + } + return _getUpgradedConnection(dbInfo); + } + }).then(function() { + return _tryReconnect(dbInfo).then(function() { + createTransaction(dbInfo, mode, callback, retries - 1); + }); + })["catch"](callback); + } + callback(err); + } + } + function createDbContext() { + return { + forages: [], + db: null, + dbReady: null, + deferredOperations: [] + }; + } + function _initStorage(options) { + var self2 = this; + var dbInfo = { + db: null + }; + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + var dbContext = dbContexts[dbInfo.name]; + if (!dbContext) { + dbContext = createDbContext(); + dbContexts[dbInfo.name] = dbContext; + } + dbContext.forages.push(self2); + if (!self2._initReady) { + self2._initReady = self2.ready; + self2.ready = _fullyReady; + } + var initPromises = []; + function ignoreErrors() { + return Promise$1.resolve(); + } + for (var j = 0;j < dbContext.forages.length; j++) { + var forage = dbContext.forages[j]; + if (forage !== self2) { + initPromises.push(forage._initReady()["catch"](ignoreErrors)); + } + } + var forages = dbContext.forages.slice(0); + return Promise$1.all(initPromises).then(function() { + dbInfo.db = dbContext.db; + return _getOriginalConnection(dbInfo); + }).then(function(db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo, self2._defaultConfig.version)) { + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function(db) { + dbInfo.db = dbContext.db = db; + self2._dbInfo = dbInfo; + for (var k = 0;k < forages.length; k++) { + var forage2 = forages[k]; + if (forage2 !== self2) { + forage2._dbInfo.db = dbInfo.db; + forage2._dbInfo.version = dbInfo.version; + } + } + }); + } + function getItem(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.get(key3); + req.onsuccess = function() { + var value2 = req.result; + if (value2 === undefined) { + value2 = null; + } + if (_isEncodedBlob(value2)) { + value2 = _decodeBlob(value2); + } + resolve(value2); + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function iterate(iterator, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.openCursor(); + var iterationNumber = 1; + req.onsuccess = function() { + var cursor = req.result; + if (cursor) { + var value2 = cursor.value; + if (_isEncodedBlob(value2)) { + value2 = _decodeBlob(value2); + } + var result = iterator(value2, cursor.key, iterationNumber++); + if (result !== undefined) { + resolve(result); + } else { + cursor["continue"](); + } + } else { + resolve(); + } + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function setItem(key3, value2, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + var dbInfo; + self2.ready().then(function() { + dbInfo = self2._dbInfo; + if (toString2.call(value2) === "[object Blob]") { + return _checkBlobSupport(dbInfo.db).then(function(blobSupport) { + if (blobSupport) { + return value2; + } + return _encodeBlob(value2); + }); + } + return value2; + }).then(function(value3) { + createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + if (value3 === null) { + value3 = undefined; + } + var req = store.put(value3, key3); + transaction.oncomplete = function() { + if (value3 === undefined) { + value3 = null; + } + resolve(value3); + }; + transaction.onabort = transaction.onerror = function() { + var err2 = req.error ? req.error : req.transaction.error; + reject2(err2); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function removeItem(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store["delete"](key3); + transaction.oncomplete = function() { + resolve(); + }; + transaction.onerror = function() { + reject2(req.error); + }; + transaction.onabort = function() { + var err2 = req.error ? req.error : req.transaction.error; + reject2(err2); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function clear(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.clear(); + transaction.oncomplete = function() { + resolve(); + }; + transaction.onabort = transaction.onerror = function() { + var err2 = req.error ? req.error : req.transaction.error; + reject2(err2); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function length2(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.count(); + req.onsuccess = function() { + resolve(req.result); + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function key2(n, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + if (n < 0) { + resolve(null); + return; + } + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var advanced = false; + var req = store.openKeyCursor(); + req.onsuccess = function() { + var cursor = req.result; + if (!cursor) { + resolve(null); + return; + } + if (n === 0) { + resolve(cursor.key); + } else { + if (!advanced) { + advanced = true; + cursor.advance(n); + } else { + resolve(cursor.key); + } + } + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function keys2(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.openKeyCursor(); + var keys3 = []; + req.onsuccess = function() { + var cursor = req.result; + if (!cursor) { + resolve(keys3); + return; + } + keys3.push(cursor.key); + cursor["continue"](); + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function dropInstance(options, callback) { + callback = getCallback.apply(this, arguments); + var currentConfig = this.config(); + options = typeof options !== "function" && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + var self2 = this; + var promise; + if (!options.name) { + promise = Promise$1.reject("Invalid arguments"); + } else { + var isCurrentDb = options.name === currentConfig.name && self2._dbInfo.db; + var dbPromise = isCurrentDb ? Promise$1.resolve(self2._dbInfo.db) : _getOriginalConnection(options).then(function(db) { + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + dbContext.db = db; + for (var i = 0;i < forages.length; i++) { + forages[i]._dbInfo.db = db; + } + return db; + }); + if (!options.storeName) { + promise = dbPromise.then(function(db) { + _deferReadiness(options); + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + db.close(); + for (var i = 0;i < forages.length; i++) { + var forage = forages[i]; + forage._dbInfo.db = null; + } + var dropDBPromise = new Promise$1(function(resolve, reject2) { + var req = idb.deleteDatabase(options.name); + req.onerror = function() { + var db2 = req.result; + if (db2) { + db2.close(); + } + reject2(req.error); + }; + req.onblocked = function() { + console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed'); + }; + req.onsuccess = function() { + var db2 = req.result; + if (db2) { + db2.close(); + } + resolve(db2); + }; + }); + return dropDBPromise.then(function(db2) { + dbContext.db = db2; + for (var i2 = 0;i2 < forages.length; i2++) { + var _forage = forages[i2]; + _advanceReadiness(_forage._dbInfo); + } + })["catch"](function(err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() { + }); + throw err; + }); + }); + } else { + promise = dbPromise.then(function(db) { + if (!db.objectStoreNames.contains(options.storeName)) { + return; + } + var newVersion = db.version + 1; + _deferReadiness(options); + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + db.close(); + for (var i = 0;i < forages.length; i++) { + var forage = forages[i]; + forage._dbInfo.db = null; + forage._dbInfo.version = newVersion; + } + var dropObjectPromise = new Promise$1(function(resolve, reject2) { + var req = idb.open(options.name, newVersion); + req.onerror = function(err) { + var db2 = req.result; + db2.close(); + reject2(err); + }; + req.onupgradeneeded = function() { + var db2 = req.result; + db2.deleteObjectStore(options.storeName); + }; + req.onsuccess = function() { + var db2 = req.result; + db2.close(); + resolve(db2); + }; + }); + return dropObjectPromise.then(function(db2) { + dbContext.db = db2; + for (var j = 0;j < forages.length; j++) { + var _forage2 = forages[j]; + _forage2._dbInfo.db = db2; + _advanceReadiness(_forage2._dbInfo); + } + })["catch"](function(err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() { + }); + throw err; + }); + }); + } + } + executeCallback(promise, callback); + return promise; + } + var asyncStorage = { + _driver: "asyncStorage", + _initStorage, + _support: isIndexedDBValid(), + iterate, + getItem, + setItem, + removeItem, + clear, + length: length2, + key: key2, + keys: keys2, + dropInstance + }; + function isWebSQLValid() { + return typeof openDatabase === "function"; + } + var BASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var BLOB_TYPE_PREFIX = "~~local_forage_type~"; + var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; + var SERIALIZED_MARKER = "__lfsc__:"; + var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; + var TYPE_ARRAYBUFFER = "arbf"; + var TYPE_BLOB = "blob"; + var TYPE_INT8ARRAY = "si08"; + var TYPE_UINT8ARRAY = "ui08"; + var TYPE_UINT8CLAMPEDARRAY = "uic8"; + var TYPE_INT16ARRAY = "si16"; + var TYPE_INT32ARRAY = "si32"; + var TYPE_UINT16ARRAY = "ur16"; + var TYPE_UINT32ARRAY = "ui32"; + var TYPE_FLOAT32ARRAY = "fl32"; + var TYPE_FLOAT64ARRAY = "fl64"; + var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; + var toString$1 = Object.prototype.toString; + function stringToBuffer(serializedString) { + var bufferLength = serializedString.length * 0.75; + var len = serializedString.length; + var i; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + if (serializedString[serializedString.length - 1] === "=") { + bufferLength--; + if (serializedString[serializedString.length - 2] === "=") { + bufferLength--; + } + } + var buffer = new ArrayBuffer(bufferLength); + var bytes = new Uint8Array(buffer); + for (i = 0;i < len; i += 4) { + encoded1 = BASE_CHARS.indexOf(serializedString[i]); + encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); + encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); + encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + return buffer; + } + function bufferToString(buffer) { + var bytes = new Uint8Array(buffer); + var base64String = ""; + var i; + for (i = 0;i < bytes.length; i += 3) { + base64String += BASE_CHARS[bytes[i] >> 2]; + base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; + base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; + base64String += BASE_CHARS[bytes[i + 2] & 63]; + } + if (bytes.length % 3 === 2) { + base64String = base64String.substring(0, base64String.length - 1) + "="; + } else if (bytes.length % 3 === 1) { + base64String = base64String.substring(0, base64String.length - 2) + "=="; + } + return base64String; + } + function serialize(value2, callback) { + var valueType = ""; + if (value2) { + valueType = toString$1.call(value2); + } + if (value2 && (valueType === "[object ArrayBuffer]" || value2.buffer && toString$1.call(value2.buffer) === "[object ArrayBuffer]")) { + var buffer; + var marker = SERIALIZED_MARKER; + if (value2 instanceof ArrayBuffer) { + buffer = value2; + marker += TYPE_ARRAYBUFFER; + } else { + buffer = value2.buffer; + if (valueType === "[object Int8Array]") { + marker += TYPE_INT8ARRAY; + } else if (valueType === "[object Uint8Array]") { + marker += TYPE_UINT8ARRAY; + } else if (valueType === "[object Uint8ClampedArray]") { + marker += TYPE_UINT8CLAMPEDARRAY; + } else if (valueType === "[object Int16Array]") { + marker += TYPE_INT16ARRAY; + } else if (valueType === "[object Uint16Array]") { + marker += TYPE_UINT16ARRAY; + } else if (valueType === "[object Int32Array]") { + marker += TYPE_INT32ARRAY; + } else if (valueType === "[object Uint32Array]") { + marker += TYPE_UINT32ARRAY; + } else if (valueType === "[object Float32Array]") { + marker += TYPE_FLOAT32ARRAY; + } else if (valueType === "[object Float64Array]") { + marker += TYPE_FLOAT64ARRAY; + } else { + callback(new Error("Failed to get type for BinaryArray")); + } + } + callback(marker + bufferToString(buffer)); + } else if (valueType === "[object Blob]") { + var fileReader = new FileReader; + fileReader.onload = function() { + var str = BLOB_TYPE_PREFIX + value2.type + "~" + bufferToString(this.result); + callback(SERIALIZED_MARKER + TYPE_BLOB + str); + }; + fileReader.readAsArrayBuffer(value2); + } else { + try { + callback(JSON.stringify(value2)); + } catch (e) { + console.error("Couldn't convert value into a JSON string: ", value2); + callback(null, e); + } + } + } + function deserialize(value2) { + if (value2.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { + return JSON.parse(value2); + } + var serializedString = value2.substring(TYPE_SERIALIZED_MARKER_LENGTH); + var type = value2.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); + var blobType; + if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { + var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); + blobType = matcher[1]; + serializedString = serializedString.substring(matcher[0].length); + } + var buffer = stringToBuffer(serializedString); + switch (type) { + case TYPE_ARRAYBUFFER: + return buffer; + case TYPE_BLOB: + return createBlob([buffer], { type: blobType }); + case TYPE_INT8ARRAY: + return new Int8Array(buffer); + case TYPE_UINT8ARRAY: + return new Uint8Array(buffer); + case TYPE_UINT8CLAMPEDARRAY: + return new Uint8ClampedArray(buffer); + case TYPE_INT16ARRAY: + return new Int16Array(buffer); + case TYPE_UINT16ARRAY: + return new Uint16Array(buffer); + case TYPE_INT32ARRAY: + return new Int32Array(buffer); + case TYPE_UINT32ARRAY: + return new Uint32Array(buffer); + case TYPE_FLOAT32ARRAY: + return new Float32Array(buffer); + case TYPE_FLOAT64ARRAY: + return new Float64Array(buffer); + default: + throw new Error("Unkown type: " + type); + } + } + var localforageSerializer = { + serialize, + deserialize, + stringToBuffer, + bufferToString + }; + function createDbTable(t, dbInfo, callback, errorCallback) { + t.executeSql("CREATE TABLE IF NOT EXISTS " + dbInfo.storeName + " " + "(id INTEGER PRIMARY KEY, key unique, value)", [], callback, errorCallback); + } + function _initStorage$1(options) { + var self2 = this; + var dbInfo = { + db: null + }; + if (options) { + for (var i in options) { + dbInfo[i] = typeof options[i] !== "string" ? options[i].toString() : options[i]; + } + } + var dbInfoPromise = new Promise$1(function(resolve, reject2) { + try { + dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); + } catch (e) { + return reject2(e); + } + dbInfo.db.transaction(function(t) { + createDbTable(t, dbInfo, function() { + self2._dbInfo = dbInfo; + resolve(); + }, function(t2, error) { + reject2(error); + }); + }, reject2); + }); + dbInfo.serializer = localforageSerializer; + return dbInfoPromise; + } + function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) { + t.executeSql(sqlStatement, args, callback, function(t2, error) { + if (error.code === error.SYNTAX_ERR) { + t2.executeSql("SELECT name FROM sqlite_master " + "WHERE type='table' AND name = ?", [dbInfo.storeName], function(t3, results) { + if (!results.rows.length) { + createDbTable(t3, dbInfo, function() { + t3.executeSql(sqlStatement, args, callback, errorCallback); + }, errorCallback); + } else { + errorCallback(t3, error); + } + }, errorCallback); + } else { + errorCallback(t2, error); + } + }, errorCallback); + } + function getItem$1(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT * FROM " + dbInfo.storeName + " WHERE key = ? LIMIT 1", [key3], function(t2, results) { + var result = results.rows.length ? results.rows.item(0).value : null; + if (result) { + result = dbInfo.serializer.deserialize(result); + } + resolve(result); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function iterate$1(iterator, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT * FROM " + dbInfo.storeName, [], function(t2, results) { + var rows = results.rows; + var length3 = rows.length; + for (var i = 0;i < length3; i++) { + var item = rows.item(i); + var result = item.value; + if (result) { + result = dbInfo.serializer.deserialize(result); + } + result = iterator(result, item.key, i + 1); + if (result !== undefined) { + resolve(result); + return; + } + } + resolve(); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function _setItem(key3, value2, callback, retriesLeft) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + if (value2 === undefined) { + value2 = null; + } + var originalValue = value2; + var dbInfo = self2._dbInfo; + dbInfo.serializer.serialize(value2, function(value3, error) { + if (error) { + reject2(error); + } else { + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "INSERT OR REPLACE INTO " + dbInfo.storeName + " " + "(key, value) VALUES (?, ?)", [key3, value3], function() { + resolve(originalValue); + }, function(t2, error2) { + reject2(error2); + }); + }, function(sqlError) { + if (sqlError.code === sqlError.QUOTA_ERR) { + if (retriesLeft > 0) { + resolve(_setItem.apply(self2, [key3, originalValue, callback, retriesLeft - 1])); + return; + } + reject2(sqlError); + } + }); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function setItem$1(key3, value2, callback) { + return _setItem.apply(this, [key3, value2, callback, 1]); + } + function removeItem$1(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "DELETE FROM " + dbInfo.storeName + " WHERE key = ?", [key3], function() { + resolve(); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function clear$1(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "DELETE FROM " + dbInfo.storeName, [], function() { + resolve(); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function length$1(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT COUNT(key) as c FROM " + dbInfo.storeName, [], function(t2, results) { + var result = results.rows.item(0).c; + resolve(result); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function key$1(n, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT key FROM " + dbInfo.storeName + " WHERE id = ? LIMIT 1", [n + 1], function(t2, results) { + var result = results.rows.length ? results.rows.item(0).key : null; + resolve(result); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function keys$1(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT key FROM " + dbInfo.storeName, [], function(t2, results) { + var keys3 = []; + for (var i = 0;i < results.rows.length; i++) { + keys3.push(results.rows.item(i).key); + } + resolve(keys3); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function getAllStoreNames(db) { + return new Promise$1(function(resolve, reject2) { + db.transaction(function(t) { + t.executeSql("SELECT name FROM sqlite_master " + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function(t2, results) { + var storeNames = []; + for (var i = 0;i < results.rows.length; i++) { + storeNames.push(results.rows.item(i).name); + } + resolve({ + db, + storeNames + }); + }, function(t2, error) { + reject2(error); + }); + }, function(sqlError) { + reject2(sqlError); + }); + }); + } + function dropInstance$1(options, callback) { + callback = getCallback.apply(this, arguments); + var currentConfig = this.config(); + options = typeof options !== "function" && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + var self2 = this; + var promise; + if (!options.name) { + promise = Promise$1.reject("Invalid arguments"); + } else { + promise = new Promise$1(function(resolve) { + var db; + if (options.name === currentConfig.name) { + db = self2._dbInfo.db; + } else { + db = openDatabase(options.name, "", "", 0); + } + if (!options.storeName) { + resolve(getAllStoreNames(db)); + } else { + resolve({ + db, + storeNames: [options.storeName] + }); + } + }).then(function(operationInfo) { + return new Promise$1(function(resolve, reject2) { + operationInfo.db.transaction(function(t) { + function dropTable(storeName) { + return new Promise$1(function(resolve2, reject3) { + t.executeSql("DROP TABLE IF EXISTS " + storeName, [], function() { + resolve2(); + }, function(t2, error) { + reject3(error); + }); + }); + } + var operations = []; + for (var i = 0, len = operationInfo.storeNames.length;i < len; i++) { + operations.push(dropTable(operationInfo.storeNames[i])); + } + Promise$1.all(operations).then(function() { + resolve(); + })["catch"](function(e) { + reject2(e); + }); + }, function(sqlError) { + reject2(sqlError); + }); + }); + }); + } + executeCallback(promise, callback); + return promise; + } + var webSQLStorage = { + _driver: "webSQLStorage", + _initStorage: _initStorage$1, + _support: isWebSQLValid(), + iterate: iterate$1, + getItem: getItem$1, + setItem: setItem$1, + removeItem: removeItem$1, + clear: clear$1, + length: length$1, + key: key$1, + keys: keys$1, + dropInstance: dropInstance$1 + }; + function isLocalStorageValid() { + try { + return typeof localStorage !== "undefined" && "setItem" in localStorage && !!localStorage.setItem; + } catch (e) { + return false; + } + } + function _getKeyPrefix(options, defaultConfig) { + var keyPrefix = options.name + "/"; + if (options.storeName !== defaultConfig.storeName) { + keyPrefix += options.storeName + "/"; + } + return keyPrefix; + } + function checkIfLocalStorageThrows() { + var localStorageTestKey = "_localforage_support_test"; + try { + localStorage.setItem(localStorageTestKey, true); + localStorage.removeItem(localStorageTestKey); + return false; + } catch (e) { + return true; + } + } + function _isLocalStorageUsable() { + return !checkIfLocalStorageThrows() || localStorage.length > 0; + } + function _initStorage$2(options) { + var self2 = this; + var dbInfo = {}; + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + dbInfo.keyPrefix = _getKeyPrefix(options, self2._defaultConfig); + if (!_isLocalStorageUsable()) { + return Promise$1.reject(); + } + self2._dbInfo = dbInfo; + dbInfo.serializer = localforageSerializer; + return Promise$1.resolve(); + } + function clear$2(callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var keyPrefix = self2._dbInfo.keyPrefix; + for (var i = localStorage.length - 1;i >= 0; i--) { + var key3 = localStorage.key(i); + if (key3.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key3); + } + } + }); + executeCallback(promise, callback); + return promise; + } + function getItem$2(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var result = localStorage.getItem(dbInfo.keyPrefix + key3); + if (result) { + result = dbInfo.serializer.deserialize(result); + } + return result; + }); + executeCallback(promise, callback); + return promise; + } + function iterate$2(iterator, callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var keyPrefix = dbInfo.keyPrefix; + var keyPrefixLength = keyPrefix.length; + var length3 = localStorage.length; + var iterationNumber = 1; + for (var i = 0;i < length3; i++) { + var key3 = localStorage.key(i); + if (key3.indexOf(keyPrefix) !== 0) { + continue; + } + var value2 = localStorage.getItem(key3); + if (value2) { + value2 = dbInfo.serializer.deserialize(value2); + } + value2 = iterator(value2, key3.substring(keyPrefixLength), iterationNumber++); + if (value2 !== undefined) { + return value2; + } + } + }); + executeCallback(promise, callback); + return promise; + } + function key$2(n, callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var result; + try { + result = localStorage.key(n); + } catch (error) { + result = null; + } + if (result) { + result = result.substring(dbInfo.keyPrefix.length); + } + return result; + }); + executeCallback(promise, callback); + return promise; + } + function keys$2(callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var length3 = localStorage.length; + var keys3 = []; + for (var i = 0;i < length3; i++) { + var itemKey = localStorage.key(i); + if (itemKey.indexOf(dbInfo.keyPrefix) === 0) { + keys3.push(itemKey.substring(dbInfo.keyPrefix.length)); + } + } + return keys3; + }); + executeCallback(promise, callback); + return promise; + } + function length$2(callback) { + var self2 = this; + var promise = self2.keys().then(function(keys3) { + return keys3.length; + }); + executeCallback(promise, callback); + return promise; + } + function removeItem$2(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + localStorage.removeItem(dbInfo.keyPrefix + key3); + }); + executeCallback(promise, callback); + return promise; + } + function setItem$2(key3, value2, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = self2.ready().then(function() { + if (value2 === undefined) { + value2 = null; + } + var originalValue = value2; + return new Promise$1(function(resolve, reject2) { + var dbInfo = self2._dbInfo; + dbInfo.serializer.serialize(value2, function(value3, error) { + if (error) { + reject2(error); + } else { + try { + localStorage.setItem(dbInfo.keyPrefix + key3, value3); + resolve(originalValue); + } catch (e) { + if (e.name === "QuotaExceededError" || e.name === "NS_ERROR_DOM_QUOTA_REACHED") { + reject2(e); + } + reject2(e); + } + } + }); + }); + }); + executeCallback(promise, callback); + return promise; + } + function dropInstance$2(options, callback) { + callback = getCallback.apply(this, arguments); + options = typeof options !== "function" && options || {}; + if (!options.name) { + var currentConfig = this.config(); + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + var self2 = this; + var promise; + if (!options.name) { + promise = Promise$1.reject("Invalid arguments"); + } else { + promise = new Promise$1(function(resolve) { + if (!options.storeName) { + resolve(options.name + "/"); + } else { + resolve(_getKeyPrefix(options, self2._defaultConfig)); + } + }).then(function(keyPrefix) { + for (var i = localStorage.length - 1;i >= 0; i--) { + var key3 = localStorage.key(i); + if (key3.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key3); + } + } + }); + } + executeCallback(promise, callback); + return promise; + } + var localStorageWrapper = { + _driver: "localStorageWrapper", + _initStorage: _initStorage$2, + _support: isLocalStorageValid(), + iterate: iterate$2, + getItem: getItem$2, + setItem: setItem$2, + removeItem: removeItem$2, + clear: clear$2, + length: length$2, + key: key$2, + keys: keys$2, + dropInstance: dropInstance$2 + }; + var sameValue = function sameValue(x, y) { + return x === y || typeof x === "number" && typeof y === "number" && isNaN(x) && isNaN(y); + }; + var includes = function includes(array, searchElement) { + var len = array.length; + var i = 0; + while (i < len) { + if (sameValue(array[i], searchElement)) { + return true; + } + i++; + } + return false; + }; + var isArray2 = Array.isArray || function(arg) { + return Object.prototype.toString.call(arg) === "[object Array]"; + }; + var DefinedDrivers = {}; + var DriverSupport = {}; + var DefaultDrivers = { + INDEXEDDB: asyncStorage, + WEBSQL: webSQLStorage, + LOCALSTORAGE: localStorageWrapper + }; + var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver]; + var OptionalDriverMethods = ["dropInstance"]; + var LibraryMethods = ["clear", "getItem", "iterate", "key", "keys", "length", "removeItem", "setItem"].concat(OptionalDriverMethods); + var DefaultConfig = { + description: "", + driver: DefaultDriverOrder.slice(), + name: "localforage", + size: 4980736, + storeName: "keyvaluepairs", + version: 1 + }; + function callWhenReady(localForageInstance, libraryMethod) { + localForageInstance[libraryMethod] = function() { + var _args = arguments; + return localForageInstance.ready().then(function() { + return localForageInstance[libraryMethod].apply(localForageInstance, _args); + }); + }; + } + function extend() { + for (var i = 1;i < arguments.length; i++) { + var arg = arguments[i]; + if (arg) { + for (var _key in arg) { + if (arg.hasOwnProperty(_key)) { + if (isArray2(arg[_key])) { + arguments[0][_key] = arg[_key].slice(); + } else { + arguments[0][_key] = arg[_key]; + } + } + } + } + } + return arguments[0]; + } + var LocalForage = function() { + function LocalForage2(options) { + _classCallCheck(this, LocalForage2); + for (var driverTypeKey in DefaultDrivers) { + if (DefaultDrivers.hasOwnProperty(driverTypeKey)) { + var driver = DefaultDrivers[driverTypeKey]; + var driverName = driver._driver; + this[driverTypeKey] = driverName; + if (!DefinedDrivers[driverName]) { + this.defineDriver(driver); + } + } + } + this._defaultConfig = extend({}, DefaultConfig); + this._config = extend({}, this._defaultConfig, options); + this._driverSet = null; + this._initDriver = null; + this._ready = false; + this._dbInfo = null; + this._wrapLibraryMethodsWithReady(); + this.setDriver(this._config.driver)["catch"](function() { + }); + } + LocalForage2.prototype.config = function config(options) { + if ((typeof options === "undefined" ? "undefined" : _typeof(options)) === "object") { + if (this._ready) { + return new Error("Can't call config() after localforage " + "has been used."); + } + for (var i in options) { + if (i === "storeName") { + options[i] = options[i].replace(/\W/g, "_"); + } + if (i === "version" && typeof options[i] !== "number") { + return new Error("Database version must be a number."); + } + this._config[i] = options[i]; + } + if ("driver" in options && options.driver) { + return this.setDriver(this._config.driver); + } + return true; + } else if (typeof options === "string") { + return this._config[options]; + } else { + return this._config; + } + }; + LocalForage2.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { + var promise = new Promise$1(function(resolve, reject2) { + try { + var driverName = driverObject._driver; + var complianceError = new Error("Custom driver not compliant; see " + "https://mozilla.github.io/localForage/#definedriver"); + if (!driverObject._driver) { + reject2(complianceError); + return; + } + var driverMethods = LibraryMethods.concat("_initStorage"); + for (var i = 0, len = driverMethods.length;i < len; i++) { + var driverMethodName = driverMethods[i]; + var isRequired = !includes(OptionalDriverMethods, driverMethodName); + if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== "function") { + reject2(complianceError); + return; + } + } + var configureMissingMethods = function configureMissingMethods() { + var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) { + return function() { + var error = new Error("Method " + methodName + " is not implemented by the current driver"); + var promise2 = Promise$1.reject(error); + executeCallback(promise2, arguments[arguments.length - 1]); + return promise2; + }; + }; + for (var _i = 0, _len = OptionalDriverMethods.length;_i < _len; _i++) { + var optionalDriverMethod = OptionalDriverMethods[_i]; + if (!driverObject[optionalDriverMethod]) { + driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod); + } + } + }; + configureMissingMethods(); + var setDriverSupport = function setDriverSupport(support) { + if (DefinedDrivers[driverName]) { + console.info("Redefining LocalForage driver: " + driverName); + } + DefinedDrivers[driverName] = driverObject; + DriverSupport[driverName] = support; + resolve(); + }; + if ("_support" in driverObject) { + if (driverObject._support && typeof driverObject._support === "function") { + driverObject._support().then(setDriverSupport, reject2); + } else { + setDriverSupport(!!driverObject._support); + } + } else { + setDriverSupport(true); + } + } catch (e) { + reject2(e); + } + }); + executeTwoCallbacks(promise, callback, errorCallback); + return promise; + }; + LocalForage2.prototype.driver = function driver() { + return this._driver || null; + }; + LocalForage2.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { + var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error("Driver not found.")); + executeTwoCallbacks(getDriverPromise, callback, errorCallback); + return getDriverPromise; + }; + LocalForage2.prototype.getSerializer = function getSerializer(callback) { + var serializerPromise = Promise$1.resolve(localforageSerializer); + executeTwoCallbacks(serializerPromise, callback); + return serializerPromise; + }; + LocalForage2.prototype.ready = function ready(callback) { + var self2 = this; + var promise = self2._driverSet.then(function() { + if (self2._ready === null) { + self2._ready = self2._initDriver(); + } + return self2._ready; + }); + executeTwoCallbacks(promise, callback, callback); + return promise; + }; + LocalForage2.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { + var self2 = this; + if (!isArray2(drivers)) { + drivers = [drivers]; + } + var supportedDrivers = this._getSupportedDrivers(drivers); + function setDriverToConfig() { + self2._config.driver = self2.driver(); + } + function extendSelfWithDriver(driver) { + self2._extend(driver); + setDriverToConfig(); + self2._ready = self2._initStorage(self2._config); + return self2._ready; + } + function initDriver(supportedDrivers2) { + return function() { + var currentDriverIndex = 0; + function driverPromiseLoop() { + while (currentDriverIndex < supportedDrivers2.length) { + var driverName = supportedDrivers2[currentDriverIndex]; + currentDriverIndex++; + self2._dbInfo = null; + self2._ready = null; + return self2.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop); + } + setDriverToConfig(); + var error = new Error("No available storage method found."); + self2._driverSet = Promise$1.reject(error); + return self2._driverSet; + } + return driverPromiseLoop(); + }; + } + var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function() { + return Promise$1.resolve(); + }) : Promise$1.resolve(); + this._driverSet = oldDriverSetDone.then(function() { + var driverName = supportedDrivers[0]; + self2._dbInfo = null; + self2._ready = null; + return self2.getDriver(driverName).then(function(driver) { + self2._driver = driver._driver; + setDriverToConfig(); + self2._wrapLibraryMethodsWithReady(); + self2._initDriver = initDriver(supportedDrivers); + }); + })["catch"](function() { + setDriverToConfig(); + var error = new Error("No available storage method found."); + self2._driverSet = Promise$1.reject(error); + return self2._driverSet; + }); + executeTwoCallbacks(this._driverSet, callback, errorCallback); + return this._driverSet; + }; + LocalForage2.prototype.supports = function supports(driverName) { + return !!DriverSupport[driverName]; + }; + LocalForage2.prototype._extend = function _extend(libraryMethodsAndProperties) { + extend(this, libraryMethodsAndProperties); + }; + LocalForage2.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { + var supportedDrivers = []; + for (var i = 0, len = drivers.length;i < len; i++) { + var driverName = drivers[i]; + if (this.supports(driverName)) { + supportedDrivers.push(driverName); + } + } + return supportedDrivers; + }; + LocalForage2.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { + for (var i = 0, len = LibraryMethods.length;i < len; i++) { + callWhenReady(this, LibraryMethods[i]); + } + }; + LocalForage2.prototype.createInstance = function createInstance(options) { + return new LocalForage2(options); + }; + return LocalForage2; + }(); + var localforage_js = new LocalForage; + module4.exports = localforage_js; + }, { "3": 3 }] }, {}, [4])(4); + }); +}); + +// node:stream +var exports_stream = {}; +__export(exports_stream, { + default: () => Uc +}); +var al, tt, cl, dl, hl, pl, yl = (e, t) => () => (e && (t = e(e = 0)), t), E = (e, t) => () => (t || e((t = { exports: {} }).exports, t), t.exports), Qr = (e, t) => { + for (var r in t) + tt(e, r, { get: t[r], enumerable: true }); +}, et = (e, t, r, n) => { + if (t && typeof t == "object" || typeof t == "function") + for (let i of dl(t)) + !pl.call(e, i) && i !== r && tt(e, i, { get: () => t[i], enumerable: !(n = cl(t, i)) || n.enumerable }); + return e; +}, ue = (e, t, r) => (et(e, t, "default"), r && et(r, t, "default")), rt = (e, t, r) => (r = e != null ? al(hl(e)) : {}, et(t || !e || !e.__esModule ? tt(r, "default", { value: e, enumerable: true }) : r, e)), pe = (e) => et(tt({}, "__esModule", { value: true }), e), tn, rn, te, I, V, ut, C, He, ir, k, Gu, se, ae, ce, di, Se, Et, xt, At, Pi, Tt, Wi, Gi, Er, Ke, Cr, Mo, J, qr, $r, Ut, Jo, Kr, fl, Jr, Ze, Uc; +var init_stream = __esm(() => { + al = Object.create; + tt = Object.defineProperty; + cl = Object.getOwnPropertyDescriptor; + dl = Object.getOwnPropertyNames; + hl = Object.getPrototypeOf; + pl = Object.prototype.hasOwnProperty; + tn = E((nt) => { + nt.byteLength = bl; + nt.toByteArray = _l; + nt.fromByteArray = ml; + var G = [], P = [], wl = typeof Uint8Array < "u" ? Uint8Array : Array, Wt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (ye = 0, Zr = Wt.length;ye < Zr; ++ye) + G[ye] = Wt[ye], P[Wt.charCodeAt(ye)] = ye; + var ye, Zr; + P[45] = 62; + P[95] = 63; + function en(e) { + var t = e.length; + if (t % 4 > 0) + throw new Error("Invalid string. Length must be a multiple of 4"); + var r = e.indexOf("="); + r === -1 && (r = t); + var n = r === t ? 0 : 4 - r % 4; + return [r, n]; + } + function bl(e) { + var t = en(e), r = t[0], n = t[1]; + return (r + n) * 3 / 4 - n; + } + function gl(e, t, r) { + return (t + r) * 3 / 4 - r; + } + function _l(e) { + var t, r = en(e), n = r[0], i = r[1], o = new wl(gl(e, n, i)), l = 0, u = i > 0 ? n - 4 : n, f; + for (f = 0;f < u; f += 4) + t = P[e.charCodeAt(f)] << 18 | P[e.charCodeAt(f + 1)] << 12 | P[e.charCodeAt(f + 2)] << 6 | P[e.charCodeAt(f + 3)], o[l++] = t >> 16 & 255, o[l++] = t >> 8 & 255, o[l++] = t & 255; + return i === 2 && (t = P[e.charCodeAt(f)] << 2 | P[e.charCodeAt(f + 1)] >> 4, o[l++] = t & 255), i === 1 && (t = P[e.charCodeAt(f)] << 10 | P[e.charCodeAt(f + 1)] << 4 | P[e.charCodeAt(f + 2)] >> 2, o[l++] = t >> 8 & 255, o[l++] = t & 255), o; + } + function El(e) { + return G[e >> 18 & 63] + G[e >> 12 & 63] + G[e >> 6 & 63] + G[e & 63]; + } + function Sl(e, t, r) { + for (var n, i = [], o = t;o < r; o += 3) + n = (e[o] << 16 & 16711680) + (e[o + 1] << 8 & 65280) + (e[o + 2] & 255), i.push(El(n)); + return i.join(""); + } + function ml(e) { + for (var t, r = e.length, n = r % 3, i = [], o = 16383, l = 0, u = r - n;l < u; l += o) + i.push(Sl(e, l, l + o > u ? u : l + o)); + return n === 1 ? (t = e[r - 1], i.push(G[t >> 2] + G[t << 4 & 63] + "==")) : n === 2 && (t = (e[r - 2] << 8) + e[r - 1], i.push(G[t >> 10] + G[t >> 4 & 63] + G[t << 2 & 63] + "=")), i.join(""); + } + }); + rn = E(($t) => { + $t.read = function(e, t, r, n, i) { + var o, l, u = i * 8 - n - 1, f = (1 << u) - 1, s = f >> 1, d = -7, c = r ? i - 1 : 0, y = r ? -1 : 1, h = e[t + c]; + for (c += y, o = h & (1 << -d) - 1, h >>= -d, d += u;d > 0; o = o * 256 + e[t + c], c += y, d -= 8) + ; + for (l = o & (1 << -d) - 1, o >>= -d, d += n;d > 0; l = l * 256 + e[t + c], c += y, d -= 8) + ; + if (o === 0) + o = 1 - s; + else { + if (o === f) + return l ? NaN : (h ? -1 : 1) * (1 / 0); + l = l + Math.pow(2, n), o = o - s; + } + return (h ? -1 : 1) * l * Math.pow(2, o - n); + }; + $t.write = function(e, t, r, n, i, o) { + var l, u, f, s = o * 8 - i - 1, d = (1 << s) - 1, c = d >> 1, y = i === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, h = n ? 0 : o - 1, p = n ? 1 : -1, B = t < 0 || t === 0 && 1 / t < 0 ? 1 : 0; + for (t = Math.abs(t), isNaN(t) || t === 1 / 0 ? (u = isNaN(t) ? 1 : 0, l = d) : (l = Math.floor(Math.log(t) / Math.LN2), t * (f = Math.pow(2, -l)) < 1 && (l--, f *= 2), l + c >= 1 ? t += y / f : t += y * Math.pow(2, 1 - c), t * f >= 2 && (l++, f /= 2), l + c >= d ? (u = 0, l = d) : l + c >= 1 ? (u = (t * f - 1) * Math.pow(2, i), l = l + c) : (u = t * Math.pow(2, c - 1) * Math.pow(2, i), l = 0));i >= 8; e[r + h] = u & 255, h += p, u /= 256, i -= 8) + ; + for (l = l << i | u, s += i;s > 0; e[r + h] = l & 255, h += p, l /= 256, s -= 8) + ; + e[r + h - p] |= B * 128; + }; + }); + te = E((Fe) => { + var jt = tn(), Le = rn(), nn = typeof Symbol == "function" && typeof Symbol.for == "function" ? Symbol.for("nodejs.util.inspect.custom") : null; + Fe.Buffer = a; + Fe.SlowBuffer = Bl; + Fe.INSPECT_MAX_BYTES = 50; + var it = 2147483647; + Fe.kMaxLength = it; + a.TYPED_ARRAY_SUPPORT = xl(); + !a.TYPED_ARRAY_SUPPORT && typeof console < "u" && typeof console.error == "function" && console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."); + function xl() { + try { + let e = new Uint8Array(1), t = { foo: function() { + return 42; + } }; + return Object.setPrototypeOf(t, Uint8Array.prototype), Object.setPrototypeOf(e, t), e.foo() === 42; + } catch { + return false; + } + } + Object.defineProperty(a.prototype, "parent", { enumerable: true, get: function() { + if (!!a.isBuffer(this)) + return this.buffer; + } }); + Object.defineProperty(a.prototype, "offset", { enumerable: true, get: function() { + if (!!a.isBuffer(this)) + return this.byteOffset; + } }); + function ee(e) { + if (e > it) + throw new RangeError('The value "' + e + '" is invalid for option "size"'); + let t = new Uint8Array(e); + return Object.setPrototypeOf(t, a.prototype), t; + } + function a(e, t, r) { + if (typeof e == "number") { + if (typeof t == "string") + throw new TypeError('The "string" argument must be of type string. Received type number'); + return Yt(e); + } + return fn(e, t, r); + } + a.poolSize = 8192; + function fn(e, t, r) { + if (typeof e == "string") + return Al(e, t); + if (ArrayBuffer.isView(e)) + return Il(e); + if (e == null) + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e); + if (H(e, ArrayBuffer) || e && H(e.buffer, ArrayBuffer) || typeof SharedArrayBuffer < "u" && (H(e, SharedArrayBuffer) || e && H(e.buffer, SharedArrayBuffer))) + return Ht(e, t, r); + if (typeof e == "number") + throw new TypeError('The "value" argument must not be of type number. Received type number'); + let n = e.valueOf && e.valueOf(); + if (n != null && n !== e) + return a.from(n, t, r); + let i = Tl(e); + if (i) + return i; + if (typeof Symbol < "u" && Symbol.toPrimitive != null && typeof e[Symbol.toPrimitive] == "function") + return a.from(e[Symbol.toPrimitive]("string"), t, r); + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e); + } + a.from = function(e, t, r) { + return fn(e, t, r); + }; + Object.setPrototypeOf(a.prototype, Uint8Array.prototype); + Object.setPrototypeOf(a, Uint8Array); + function sn(e) { + if (typeof e != "number") + throw new TypeError('"size" argument must be of type number'); + if (e < 0) + throw new RangeError('The value "' + e + '" is invalid for option "size"'); + } + function Rl(e, t, r) { + return sn(e), e <= 0 ? ee(e) : t !== undefined ? typeof r == "string" ? ee(e).fill(t, r) : ee(e).fill(t) : ee(e); + } + a.alloc = function(e, t, r) { + return Rl(e, t, r); + }; + function Yt(e) { + return sn(e), ee(e < 0 ? 0 : Kt(e) | 0); + } + a.allocUnsafe = function(e) { + return Yt(e); + }; + a.allocUnsafeSlow = function(e) { + return Yt(e); + }; + function Al(e, t) { + if ((typeof t != "string" || t === "") && (t = "utf8"), !a.isEncoding(t)) + throw new TypeError("Unknown encoding: " + t); + let r = an(e, t) | 0, n = ee(r), i = n.write(e, t); + return i !== r && (n = n.slice(0, i)), n; + } + function Gt(e) { + let t = e.length < 0 ? 0 : Kt(e.length) | 0, r = ee(t); + for (let n = 0;n < t; n += 1) + r[n] = e[n] & 255; + return r; + } + function Il(e) { + if (H(e, Uint8Array)) { + let t = new Uint8Array(e); + return Ht(t.buffer, t.byteOffset, t.byteLength); + } + return Gt(e); + } + function Ht(e, t, r) { + if (t < 0 || e.byteLength < t) + throw new RangeError('"offset" is outside of buffer bounds'); + if (e.byteLength < t + (r || 0)) + throw new RangeError('"length" is outside of buffer bounds'); + let n; + return t === undefined && r === undefined ? n = new Uint8Array(e) : r === undefined ? n = new Uint8Array(e, t) : n = new Uint8Array(e, t, r), Object.setPrototypeOf(n, a.prototype), n; + } + function Tl(e) { + if (a.isBuffer(e)) { + let t = Kt(e.length) | 0, r = ee(t); + return r.length === 0 || e.copy(r, 0, 0, t), r; + } + if (e.length !== undefined) + return typeof e.length != "number" || Xt(e.length) ? ee(0) : Gt(e); + if (e.type === "Buffer" && Array.isArray(e.data)) + return Gt(e.data); + } + function Kt(e) { + if (e >= it) + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + it.toString(16) + " bytes"); + return e | 0; + } + function Bl(e) { + return +e != e && (e = 0), a.alloc(+e); + } + a.isBuffer = function(t) { + return t != null && t._isBuffer === true && t !== a.prototype; + }; + a.compare = function(t, r) { + if (H(t, Uint8Array) && (t = a.from(t, t.offset, t.byteLength)), H(r, Uint8Array) && (r = a.from(r, r.offset, r.byteLength)), !a.isBuffer(t) || !a.isBuffer(r)) + throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'); + if (t === r) + return 0; + let n = t.length, i = r.length; + for (let o = 0, l = Math.min(n, i);o < l; ++o) + if (t[o] !== r[o]) { + n = t[o], i = r[o]; + break; + } + return n < i ? -1 : i < n ? 1 : 0; + }; + a.isEncoding = function(t) { + switch (String(t).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } + }; + a.concat = function(t, r) { + if (!Array.isArray(t)) + throw new TypeError('"list" argument must be an Array of Buffers'); + if (t.length === 0) + return a.alloc(0); + let n; + if (r === undefined) + for (r = 0, n = 0;n < t.length; ++n) + r += t[n].length; + let i = a.allocUnsafe(r), o = 0; + for (n = 0;n < t.length; ++n) { + let l = t[n]; + if (H(l, Uint8Array)) + o + l.length > i.length ? (a.isBuffer(l) || (l = a.from(l)), l.copy(i, o)) : Uint8Array.prototype.set.call(i, l, o); + else if (a.isBuffer(l)) + l.copy(i, o); + else + throw new TypeError('"list" argument must be an Array of Buffers'); + o += l.length; + } + return i; + }; + function an(e, t) { + if (a.isBuffer(e)) + return e.length; + if (ArrayBuffer.isView(e) || H(e, ArrayBuffer)) + return e.byteLength; + if (typeof e != "string") + throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof e); + let r = e.length, n = arguments.length > 2 && arguments[2] === true; + if (!n && r === 0) + return 0; + let i = false; + for (;; ) + switch (t) { + case "ascii": + case "latin1": + case "binary": + return r; + case "utf8": + case "utf-8": + return Vt(e).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return r * 2; + case "hex": + return r >>> 1; + case "base64": + return _n(e).length; + default: + if (i) + return n ? -1 : Vt(e).length; + t = ("" + t).toLowerCase(), i = true; + } + } + a.byteLength = an; + function Ll(e, t, r) { + let n = false; + if ((t === undefined || t < 0) && (t = 0), t > this.length || ((r === undefined || r > this.length) && (r = this.length), r <= 0) || (r >>>= 0, t >>>= 0, r <= t)) + return ""; + for (e || (e = "utf8");; ) + switch (e) { + case "hex": + return vl(this, t, r); + case "utf8": + case "utf-8": + return dn(this, t, r); + case "ascii": + return kl(this, t, r); + case "latin1": + case "binary": + return Ul(this, t, r); + case "base64": + return Dl(this, t, r); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ql(this, t, r); + default: + if (n) + throw new TypeError("Unknown encoding: " + e); + e = (e + "").toLowerCase(), n = true; + } + } + a.prototype._isBuffer = true; + function we(e, t, r) { + let n = e[t]; + e[t] = e[r], e[r] = n; + } + a.prototype.swap16 = function() { + let t = this.length; + if (t % 2 !== 0) + throw new RangeError("Buffer size must be a multiple of 16-bits"); + for (let r = 0;r < t; r += 2) + we(this, r, r + 1); + return this; + }; + a.prototype.swap32 = function() { + let t = this.length; + if (t % 4 !== 0) + throw new RangeError("Buffer size must be a multiple of 32-bits"); + for (let r = 0;r < t; r += 4) + we(this, r, r + 3), we(this, r + 1, r + 2); + return this; + }; + a.prototype.swap64 = function() { + let t = this.length; + if (t % 8 !== 0) + throw new RangeError("Buffer size must be a multiple of 64-bits"); + for (let r = 0;r < t; r += 8) + we(this, r, r + 7), we(this, r + 1, r + 6), we(this, r + 2, r + 5), we(this, r + 3, r + 4); + return this; + }; + a.prototype.toString = function() { + let t = this.length; + return t === 0 ? "" : arguments.length === 0 ? dn(this, 0, t) : Ll.apply(this, arguments); + }; + a.prototype.toLocaleString = a.prototype.toString; + a.prototype.equals = function(t) { + if (!a.isBuffer(t)) + throw new TypeError("Argument must be a Buffer"); + return this === t ? true : a.compare(this, t) === 0; + }; + a.prototype.inspect = function() { + let t = "", r = Fe.INSPECT_MAX_BYTES; + return t = this.toString("hex", 0, r).replace(/(.{2})/g, "$1 ").trim(), this.length > r && (t += " ... "), ""; + }; + nn && (a.prototype[nn] = a.prototype.inspect); + a.prototype.compare = function(t, r, n, i, o) { + if (H(t, Uint8Array) && (t = a.from(t, t.offset, t.byteLength)), !a.isBuffer(t)) + throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof t); + if (r === undefined && (r = 0), n === undefined && (n = t ? t.length : 0), i === undefined && (i = 0), o === undefined && (o = this.length), r < 0 || n > t.length || i < 0 || o > this.length) + throw new RangeError("out of range index"); + if (i >= o && r >= n) + return 0; + if (i >= o) + return -1; + if (r >= n) + return 1; + if (r >>>= 0, n >>>= 0, i >>>= 0, o >>>= 0, this === t) + return 0; + let l = o - i, u = n - r, f = Math.min(l, u), s = this.slice(i, o), d = t.slice(r, n); + for (let c = 0;c < f; ++c) + if (s[c] !== d[c]) { + l = s[c], u = d[c]; + break; + } + return l < u ? -1 : u < l ? 1 : 0; + }; + function cn(e, t, r, n, i) { + if (e.length === 0) + return -1; + if (typeof r == "string" ? (n = r, r = 0) : r > 2147483647 ? r = 2147483647 : r < -2147483648 && (r = -2147483648), r = +r, Xt(r) && (r = i ? 0 : e.length - 1), r < 0 && (r = e.length + r), r >= e.length) { + if (i) + return -1; + r = e.length - 1; + } else if (r < 0) + if (i) + r = 0; + else + return -1; + if (typeof t == "string" && (t = a.from(t, n)), a.isBuffer(t)) + return t.length === 0 ? -1 : on(e, t, r, n, i); + if (typeof t == "number") + return t = t & 255, typeof Uint8Array.prototype.indexOf == "function" ? i ? Uint8Array.prototype.indexOf.call(e, t, r) : Uint8Array.prototype.lastIndexOf.call(e, t, r) : on(e, [t], r, n, i); + throw new TypeError("val must be string, number or Buffer"); + } + function on(e, t, r, n, i) { + let o = 1, l = e.length, u = t.length; + if (n !== undefined && (n = String(n).toLowerCase(), n === "ucs2" || n === "ucs-2" || n === "utf16le" || n === "utf-16le")) { + if (e.length < 2 || t.length < 2) + return -1; + o = 2, l /= 2, u /= 2, r /= 2; + } + function f(d, c) { + return o === 1 ? d[c] : d.readUInt16BE(c * o); + } + let s; + if (i) { + let d = -1; + for (s = r;s < l; s++) + if (f(e, s) === f(t, d === -1 ? 0 : s - d)) { + if (d === -1 && (d = s), s - d + 1 === u) + return d * o; + } else + d !== -1 && (s -= s - d), d = -1; + } else + for (r + u > l && (r = l - u), s = r;s >= 0; s--) { + let d = true; + for (let c = 0;c < u; c++) + if (f(e, s + c) !== f(t, c)) { + d = false; + break; + } + if (d) + return s; + } + return -1; + } + a.prototype.includes = function(t, r, n) { + return this.indexOf(t, r, n) !== -1; + }; + a.prototype.indexOf = function(t, r, n) { + return cn(this, t, r, n, true); + }; + a.prototype.lastIndexOf = function(t, r, n) { + return cn(this, t, r, n, false); + }; + function Nl(e, t, r, n) { + r = Number(r) || 0; + let i = e.length - r; + n ? (n = Number(n), n > i && (n = i)) : n = i; + let o = t.length; + n > o / 2 && (n = o / 2); + let l; + for (l = 0;l < n; ++l) { + let u = parseInt(t.substr(l * 2, 2), 16); + if (Xt(u)) + return l; + e[r + l] = u; + } + return l; + } + function Fl(e, t, r, n) { + return ot(Vt(t, e.length - r), e, r, n); + } + function Ml(e, t, r, n) { + return ot(Gl(t), e, r, n); + } + function Cl(e, t, r, n) { + return ot(_n(t), e, r, n); + } + function Ol(e, t, r, n) { + return ot(Hl(t, e.length - r), e, r, n); + } + a.prototype.write = function(t, r, n, i) { + if (r === undefined) + i = "utf8", n = this.length, r = 0; + else if (n === undefined && typeof r == "string") + i = r, n = this.length, r = 0; + else if (isFinite(r)) + r = r >>> 0, isFinite(n) ? (n = n >>> 0, i === undefined && (i = "utf8")) : (i = n, n = undefined); + else + throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported"); + let o = this.length - r; + if ((n === undefined || n > o) && (n = o), t.length > 0 && (n < 0 || r < 0) || r > this.length) + throw new RangeError("Attempt to write outside buffer bounds"); + i || (i = "utf8"); + let l = false; + for (;; ) + switch (i) { + case "hex": + return Nl(this, t, r, n); + case "utf8": + case "utf-8": + return Fl(this, t, r, n); + case "ascii": + case "latin1": + case "binary": + return Ml(this, t, r, n); + case "base64": + return Cl(this, t, r, n); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return Ol(this, t, r, n); + default: + if (l) + throw new TypeError("Unknown encoding: " + i); + i = ("" + i).toLowerCase(), l = true; + } + }; + a.prototype.toJSON = function() { + return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) }; + }; + function Dl(e, t, r) { + return t === 0 && r === e.length ? jt.fromByteArray(e) : jt.fromByteArray(e.slice(t, r)); + } + function dn(e, t, r) { + r = Math.min(e.length, r); + let n = [], i = t; + for (;i < r; ) { + let o = e[i], l = null, u = o > 239 ? 4 : o > 223 ? 3 : o > 191 ? 2 : 1; + if (i + u <= r) { + let f, s, d, c; + switch (u) { + case 1: + o < 128 && (l = o); + break; + case 2: + f = e[i + 1], (f & 192) === 128 && (c = (o & 31) << 6 | f & 63, c > 127 && (l = c)); + break; + case 3: + f = e[i + 1], s = e[i + 2], (f & 192) === 128 && (s & 192) === 128 && (c = (o & 15) << 12 | (f & 63) << 6 | s & 63, c > 2047 && (c < 55296 || c > 57343) && (l = c)); + break; + case 4: + f = e[i + 1], s = e[i + 2], d = e[i + 3], (f & 192) === 128 && (s & 192) === 128 && (d & 192) === 128 && (c = (o & 15) << 18 | (f & 63) << 12 | (s & 63) << 6 | d & 63, c > 65535 && c < 1114112 && (l = c)); + } + } + l === null ? (l = 65533, u = 1) : l > 65535 && (l -= 65536, n.push(l >>> 10 & 1023 | 55296), l = 56320 | l & 1023), n.push(l), i += u; + } + return Pl(n); + } + var ln = 4096; + function Pl(e) { + let t = e.length; + if (t <= ln) + return String.fromCharCode.apply(String, e); + let r = "", n = 0; + for (;n < t; ) + r += String.fromCharCode.apply(String, e.slice(n, n += ln)); + return r; + } + function kl(e, t, r) { + let n = ""; + r = Math.min(e.length, r); + for (let i = t;i < r; ++i) + n += String.fromCharCode(e[i] & 127); + return n; + } + function Ul(e, t, r) { + let n = ""; + r = Math.min(e.length, r); + for (let i = t;i < r; ++i) + n += String.fromCharCode(e[i]); + return n; + } + function vl(e, t, r) { + let n = e.length; + (!t || t < 0) && (t = 0), (!r || r < 0 || r > n) && (r = n); + let i = ""; + for (let o = t;o < r; ++o) + i += Vl[e[o]]; + return i; + } + function ql(e, t, r) { + let n = e.slice(t, r), i = ""; + for (let o = 0;o < n.length - 1; o += 2) + i += String.fromCharCode(n[o] + n[o + 1] * 256); + return i; + } + a.prototype.slice = function(t, r) { + let n = this.length; + t = ~~t, r = r === undefined ? n : ~~r, t < 0 ? (t += n, t < 0 && (t = 0)) : t > n && (t = n), r < 0 ? (r += n, r < 0 && (r = 0)) : r > n && (r = n), r < t && (r = t); + let i = this.subarray(t, r); + return Object.setPrototypeOf(i, a.prototype), i; + }; + function F(e, t, r) { + if (e % 1 !== 0 || e < 0) + throw new RangeError("offset is not uint"); + if (e + t > r) + throw new RangeError("Trying to access beyond buffer length"); + } + a.prototype.readUintLE = a.prototype.readUIntLE = function(t, r, n) { + t = t >>> 0, r = r >>> 0, n || F(t, r, this.length); + let i = this[t], o = 1, l = 0; + for (;++l < r && (o *= 256); ) + i += this[t + l] * o; + return i; + }; + a.prototype.readUintBE = a.prototype.readUIntBE = function(t, r, n) { + t = t >>> 0, r = r >>> 0, n || F(t, r, this.length); + let i = this[t + --r], o = 1; + for (;r > 0 && (o *= 256); ) + i += this[t + --r] * o; + return i; + }; + a.prototype.readUint8 = a.prototype.readUInt8 = function(t, r) { + return t = t >>> 0, r || F(t, 1, this.length), this[t]; + }; + a.prototype.readUint16LE = a.prototype.readUInt16LE = function(t, r) { + return t = t >>> 0, r || F(t, 2, this.length), this[t] | this[t + 1] << 8; + }; + a.prototype.readUint16BE = a.prototype.readUInt16BE = function(t, r) { + return t = t >>> 0, r || F(t, 2, this.length), this[t] << 8 | this[t + 1]; + }; + a.prototype.readUint32LE = a.prototype.readUInt32LE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), (this[t] | this[t + 1] << 8 | this[t + 2] << 16) + this[t + 3] * 16777216; + }; + a.prototype.readUint32BE = a.prototype.readUInt32BE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), this[t] * 16777216 + (this[t + 1] << 16 | this[t + 2] << 8 | this[t + 3]); + }; + a.prototype.readBigUInt64LE = fe(function(t) { + t = t >>> 0, Ne(t, "offset"); + let r = this[t], n = this[t + 7]; + (r === undefined || n === undefined) && Ge(t, this.length - 8); + let i = r + this[++t] * 2 ** 8 + this[++t] * 2 ** 16 + this[++t] * 2 ** 24, o = this[++t] + this[++t] * 2 ** 8 + this[++t] * 2 ** 16 + n * 2 ** 24; + return BigInt(i) + (BigInt(o) << BigInt(32)); + }); + a.prototype.readBigUInt64BE = fe(function(t) { + t = t >>> 0, Ne(t, "offset"); + let r = this[t], n = this[t + 7]; + (r === undefined || n === undefined) && Ge(t, this.length - 8); + let i = r * 2 ** 24 + this[++t] * 2 ** 16 + this[++t] * 2 ** 8 + this[++t], o = this[++t] * 2 ** 24 + this[++t] * 2 ** 16 + this[++t] * 2 ** 8 + n; + return (BigInt(i) << BigInt(32)) + BigInt(o); + }); + a.prototype.readIntLE = function(t, r, n) { + t = t >>> 0, r = r >>> 0, n || F(t, r, this.length); + let i = this[t], o = 1, l = 0; + for (;++l < r && (o *= 256); ) + i += this[t + l] * o; + return o *= 128, i >= o && (i -= Math.pow(2, 8 * r)), i; + }; + a.prototype.readIntBE = function(t, r, n) { + t = t >>> 0, r = r >>> 0, n || F(t, r, this.length); + let i = r, o = 1, l = this[t + --i]; + for (;i > 0 && (o *= 256); ) + l += this[t + --i] * o; + return o *= 128, l >= o && (l -= Math.pow(2, 8 * r)), l; + }; + a.prototype.readInt8 = function(t, r) { + return t = t >>> 0, r || F(t, 1, this.length), this[t] & 128 ? (255 - this[t] + 1) * -1 : this[t]; + }; + a.prototype.readInt16LE = function(t, r) { + t = t >>> 0, r || F(t, 2, this.length); + let n = this[t] | this[t + 1] << 8; + return n & 32768 ? n | 4294901760 : n; + }; + a.prototype.readInt16BE = function(t, r) { + t = t >>> 0, r || F(t, 2, this.length); + let n = this[t + 1] | this[t] << 8; + return n & 32768 ? n | 4294901760 : n; + }; + a.prototype.readInt32LE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), this[t] | this[t + 1] << 8 | this[t + 2] << 16 | this[t + 3] << 24; + }; + a.prototype.readInt32BE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), this[t] << 24 | this[t + 1] << 16 | this[t + 2] << 8 | this[t + 3]; + }; + a.prototype.readBigInt64LE = fe(function(t) { + t = t >>> 0, Ne(t, "offset"); + let r = this[t], n = this[t + 7]; + (r === undefined || n === undefined) && Ge(t, this.length - 8); + let i = this[t + 4] + this[t + 5] * 2 ** 8 + this[t + 6] * 2 ** 16 + (n << 24); + return (BigInt(i) << BigInt(32)) + BigInt(r + this[++t] * 2 ** 8 + this[++t] * 2 ** 16 + this[++t] * 2 ** 24); + }); + a.prototype.readBigInt64BE = fe(function(t) { + t = t >>> 0, Ne(t, "offset"); + let r = this[t], n = this[t + 7]; + (r === undefined || n === undefined) && Ge(t, this.length - 8); + let i = (r << 24) + this[++t] * 2 ** 16 + this[++t] * 2 ** 8 + this[++t]; + return (BigInt(i) << BigInt(32)) + BigInt(this[++t] * 2 ** 24 + this[++t] * 2 ** 16 + this[++t] * 2 ** 8 + n); + }); + a.prototype.readFloatLE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), Le.read(this, t, true, 23, 4); + }; + a.prototype.readFloatBE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), Le.read(this, t, false, 23, 4); + }; + a.prototype.readDoubleLE = function(t, r) { + return t = t >>> 0, r || F(t, 8, this.length), Le.read(this, t, true, 52, 8); + }; + a.prototype.readDoubleBE = function(t, r) { + return t = t >>> 0, r || F(t, 8, this.length), Le.read(this, t, false, 52, 8); + }; + function O(e, t, r, n, i, o) { + if (!a.isBuffer(e)) + throw new TypeError('"buffer" argument must be a Buffer instance'); + if (t > i || t < o) + throw new RangeError('"value" argument is out of bounds'); + if (r + n > e.length) + throw new RangeError("Index out of range"); + } + a.prototype.writeUintLE = a.prototype.writeUIntLE = function(t, r, n, i) { + if (t = +t, r = r >>> 0, n = n >>> 0, !i) { + let u = Math.pow(2, 8 * n) - 1; + O(this, t, r, n, u, 0); + } + let o = 1, l = 0; + for (this[r] = t & 255;++l < n && (o *= 256); ) + this[r + l] = t / o & 255; + return r + n; + }; + a.prototype.writeUintBE = a.prototype.writeUIntBE = function(t, r, n, i) { + if (t = +t, r = r >>> 0, n = n >>> 0, !i) { + let u = Math.pow(2, 8 * n) - 1; + O(this, t, r, n, u, 0); + } + let o = n - 1, l = 1; + for (this[r + o] = t & 255;--o >= 0 && (l *= 256); ) + this[r + o] = t / l & 255; + return r + n; + }; + a.prototype.writeUint8 = a.prototype.writeUInt8 = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 1, 255, 0), this[r] = t & 255, r + 1; + }; + a.prototype.writeUint16LE = a.prototype.writeUInt16LE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 2, 65535, 0), this[r] = t & 255, this[r + 1] = t >>> 8, r + 2; + }; + a.prototype.writeUint16BE = a.prototype.writeUInt16BE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 2, 65535, 0), this[r] = t >>> 8, this[r + 1] = t & 255, r + 2; + }; + a.prototype.writeUint32LE = a.prototype.writeUInt32LE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 4, 4294967295, 0), this[r + 3] = t >>> 24, this[r + 2] = t >>> 16, this[r + 1] = t >>> 8, this[r] = t & 255, r + 4; + }; + a.prototype.writeUint32BE = a.prototype.writeUInt32BE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 4, 4294967295, 0), this[r] = t >>> 24, this[r + 1] = t >>> 16, this[r + 2] = t >>> 8, this[r + 3] = t & 255, r + 4; + }; + function hn(e, t, r, n, i) { + gn(t, n, i, e, r, 7); + let o = Number(t & BigInt(4294967295)); + e[r++] = o, o = o >> 8, e[r++] = o, o = o >> 8, e[r++] = o, o = o >> 8, e[r++] = o; + let l = Number(t >> BigInt(32) & BigInt(4294967295)); + return e[r++] = l, l = l >> 8, e[r++] = l, l = l >> 8, e[r++] = l, l = l >> 8, e[r++] = l, r; + } + function pn(e, t, r, n, i) { + gn(t, n, i, e, r, 7); + let o = Number(t & BigInt(4294967295)); + e[r + 7] = o, o = o >> 8, e[r + 6] = o, o = o >> 8, e[r + 5] = o, o = o >> 8, e[r + 4] = o; + let l = Number(t >> BigInt(32) & BigInt(4294967295)); + return e[r + 3] = l, l = l >> 8, e[r + 2] = l, l = l >> 8, e[r + 1] = l, l = l >> 8, e[r] = l, r + 8; + } + a.prototype.writeBigUInt64LE = fe(function(t, r = 0) { + return hn(this, t, r, BigInt(0), BigInt("0xffffffffffffffff")); + }); + a.prototype.writeBigUInt64BE = fe(function(t, r = 0) { + return pn(this, t, r, BigInt(0), BigInt("0xffffffffffffffff")); + }); + a.prototype.writeIntLE = function(t, r, n, i) { + if (t = +t, r = r >>> 0, !i) { + let f = Math.pow(2, 8 * n - 1); + O(this, t, r, n, f - 1, -f); + } + let o = 0, l = 1, u = 0; + for (this[r] = t & 255;++o < n && (l *= 256); ) + t < 0 && u === 0 && this[r + o - 1] !== 0 && (u = 1), this[r + o] = (t / l >> 0) - u & 255; + return r + n; + }; + a.prototype.writeIntBE = function(t, r, n, i) { + if (t = +t, r = r >>> 0, !i) { + let f = Math.pow(2, 8 * n - 1); + O(this, t, r, n, f - 1, -f); + } + let o = n - 1, l = 1, u = 0; + for (this[r + o] = t & 255;--o >= 0 && (l *= 256); ) + t < 0 && u === 0 && this[r + o + 1] !== 0 && (u = 1), this[r + o] = (t / l >> 0) - u & 255; + return r + n; + }; + a.prototype.writeInt8 = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 1, 127, -128), t < 0 && (t = 255 + t + 1), this[r] = t & 255, r + 1; + }; + a.prototype.writeInt16LE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 2, 32767, -32768), this[r] = t & 255, this[r + 1] = t >>> 8, r + 2; + }; + a.prototype.writeInt16BE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 2, 32767, -32768), this[r] = t >>> 8, this[r + 1] = t & 255, r + 2; + }; + a.prototype.writeInt32LE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 4, 2147483647, -2147483648), this[r] = t & 255, this[r + 1] = t >>> 8, this[r + 2] = t >>> 16, this[r + 3] = t >>> 24, r + 4; + }; + a.prototype.writeInt32BE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 4, 2147483647, -2147483648), t < 0 && (t = 4294967295 + t + 1), this[r] = t >>> 24, this[r + 1] = t >>> 16, this[r + 2] = t >>> 8, this[r + 3] = t & 255, r + 4; + }; + a.prototype.writeBigInt64LE = fe(function(t, r = 0) { + return hn(this, t, r, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + a.prototype.writeBigInt64BE = fe(function(t, r = 0) { + return pn(this, t, r, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + function yn(e, t, r, n, i, o) { + if (r + n > e.length) + throw new RangeError("Index out of range"); + if (r < 0) + throw new RangeError("Index out of range"); + } + function wn(e, t, r, n, i) { + return t = +t, r = r >>> 0, i || yn(e, t, r, 4, 340282346638528860000000000000000000000, -340282346638528860000000000000000000000), Le.write(e, t, r, n, 23, 4), r + 4; + } + a.prototype.writeFloatLE = function(t, r, n) { + return wn(this, t, r, true, n); + }; + a.prototype.writeFloatBE = function(t, r, n) { + return wn(this, t, r, false, n); + }; + function bn(e, t, r, n, i) { + return t = +t, r = r >>> 0, i || yn(e, t, r, 8, 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, -179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000), Le.write(e, t, r, n, 52, 8), r + 8; + } + a.prototype.writeDoubleLE = function(t, r, n) { + return bn(this, t, r, true, n); + }; + a.prototype.writeDoubleBE = function(t, r, n) { + return bn(this, t, r, false, n); + }; + a.prototype.copy = function(t, r, n, i) { + if (!a.isBuffer(t)) + throw new TypeError("argument should be a Buffer"); + if (n || (n = 0), !i && i !== 0 && (i = this.length), r >= t.length && (r = t.length), r || (r = 0), i > 0 && i < n && (i = n), i === n || t.length === 0 || this.length === 0) + return 0; + if (r < 0) + throw new RangeError("targetStart out of bounds"); + if (n < 0 || n >= this.length) + throw new RangeError("Index out of range"); + if (i < 0) + throw new RangeError("sourceEnd out of bounds"); + i > this.length && (i = this.length), t.length - r < i - n && (i = t.length - r + n); + let o = i - n; + return this === t && typeof Uint8Array.prototype.copyWithin == "function" ? this.copyWithin(r, n, i) : Uint8Array.prototype.set.call(t, this.subarray(n, i), r), o; + }; + a.prototype.fill = function(t, r, n, i) { + if (typeof t == "string") { + if (typeof r == "string" ? (i = r, r = 0, n = this.length) : typeof n == "string" && (i = n, n = this.length), i !== undefined && typeof i != "string") + throw new TypeError("encoding must be a string"); + if (typeof i == "string" && !a.isEncoding(i)) + throw new TypeError("Unknown encoding: " + i); + if (t.length === 1) { + let l = t.charCodeAt(0); + (i === "utf8" && l < 128 || i === "latin1") && (t = l); + } + } else + typeof t == "number" ? t = t & 255 : typeof t == "boolean" && (t = Number(t)); + if (r < 0 || this.length < r || this.length < n) + throw new RangeError("Out of range index"); + if (n <= r) + return this; + r = r >>> 0, n = n === undefined ? this.length : n >>> 0, t || (t = 0); + let o; + if (typeof t == "number") + for (o = r;o < n; ++o) + this[o] = t; + else { + let l = a.isBuffer(t) ? t : a.from(t, i), u = l.length; + if (u === 0) + throw new TypeError('The value "' + t + '" is invalid for argument "value"'); + for (o = 0;o < n - r; ++o) + this[o + r] = l[o % u]; + } + return this; + }; + var Be = {}; + function zt(e, t, r) { + Be[e] = class extends r { + constructor() { + super(), Object.defineProperty(this, "message", { value: t.apply(this, arguments), writable: true, configurable: true }), this.name = `${this.name} [${e}]`, this.stack, delete this.name; + } + get code() { + return e; + } + set code(i) { + Object.defineProperty(this, "code", { configurable: true, enumerable: true, value: i, writable: true }); + } + toString() { + return `${this.name} [${e}]: ${this.message}`; + } + }; + } + zt("ERR_BUFFER_OUT_OF_BOUNDS", function(e) { + return e ? `${e} is outside of buffer bounds` : "Attempt to access memory outside buffer bounds"; + }, RangeError); + zt("ERR_INVALID_ARG_TYPE", function(e, t) { + return `The "${e}" argument must be of type number. Received type ${typeof t}`; + }, TypeError); + zt("ERR_OUT_OF_RANGE", function(e, t, r) { + let n = `The value of "${e}" is out of range.`, i = r; + return Number.isInteger(r) && Math.abs(r) > 2 ** 32 ? i = un(String(r)) : typeof r == "bigint" && (i = String(r), (r > BigInt(2) ** BigInt(32) || r < -(BigInt(2) ** BigInt(32))) && (i = un(i)), i += "n"), n += ` It must be ${t}. Received ${i}`, n; + }, RangeError); + function un(e) { + let t = "", r = e.length, n = e[0] === "-" ? 1 : 0; + for (;r >= n + 4; r -= 3) + t = `_${e.slice(r - 3, r)}${t}`; + return `${e.slice(0, r)}${t}`; + } + function Wl(e, t, r) { + Ne(t, "offset"), (e[t] === undefined || e[t + r] === undefined) && Ge(t, e.length - (r + 1)); + } + function gn(e, t, r, n, i, o) { + if (e > r || e < t) { + let l = typeof t == "bigint" ? "n" : "", u; + throw o > 3 ? t === 0 || t === BigInt(0) ? u = `>= 0${l} and < 2${l} ** ${(o + 1) * 8}${l}` : u = `>= -(2${l} ** ${(o + 1) * 8 - 1}${l}) and < 2 ** ${(o + 1) * 8 - 1}${l}` : u = `>= ${t}${l} and <= ${r}${l}`, new Be.ERR_OUT_OF_RANGE("value", u, e); + } + Wl(n, i, o); + } + function Ne(e, t) { + if (typeof e != "number") + throw new Be.ERR_INVALID_ARG_TYPE(t, "number", e); + } + function Ge(e, t, r) { + throw Math.floor(e) !== e ? (Ne(e, r), new Be.ERR_OUT_OF_RANGE(r || "offset", "an integer", e)) : t < 0 ? new Be.ERR_BUFFER_OUT_OF_BOUNDS : new Be.ERR_OUT_OF_RANGE(r || "offset", `>= ${r ? 1 : 0} and <= ${t}`, e); + } + var $l = /[^+/0-9A-Za-z-_]/g; + function jl(e) { + if (e = e.split("=")[0], e = e.trim().replace($l, ""), e.length < 2) + return ""; + for (;e.length % 4 !== 0; ) + e = e + "="; + return e; + } + function Vt(e, t) { + t = t || 1 / 0; + let r, n = e.length, i = null, o = []; + for (let l = 0;l < n; ++l) { + if (r = e.charCodeAt(l), r > 55295 && r < 57344) { + if (!i) { + if (r > 56319) { + (t -= 3) > -1 && o.push(239, 191, 189); + continue; + } else if (l + 1 === n) { + (t -= 3) > -1 && o.push(239, 191, 189); + continue; + } + i = r; + continue; + } + if (r < 56320) { + (t -= 3) > -1 && o.push(239, 191, 189), i = r; + continue; + } + r = (i - 55296 << 10 | r - 56320) + 65536; + } else + i && (t -= 3) > -1 && o.push(239, 191, 189); + if (i = null, r < 128) { + if ((t -= 1) < 0) + break; + o.push(r); + } else if (r < 2048) { + if ((t -= 2) < 0) + break; + o.push(r >> 6 | 192, r & 63 | 128); + } else if (r < 65536) { + if ((t -= 3) < 0) + break; + o.push(r >> 12 | 224, r >> 6 & 63 | 128, r & 63 | 128); + } else if (r < 1114112) { + if ((t -= 4) < 0) + break; + o.push(r >> 18 | 240, r >> 12 & 63 | 128, r >> 6 & 63 | 128, r & 63 | 128); + } else + throw new Error("Invalid code point"); + } + return o; + } + function Gl(e) { + let t = []; + for (let r = 0;r < e.length; ++r) + t.push(e.charCodeAt(r) & 255); + return t; + } + function Hl(e, t) { + let r, n, i, o = []; + for (let l = 0;l < e.length && !((t -= 2) < 0); ++l) + r = e.charCodeAt(l), n = r >> 8, i = r % 256, o.push(i), o.push(n); + return o; + } + function _n(e) { + return jt.toByteArray(jl(e)); + } + function ot(e, t, r, n) { + let i; + for (i = 0;i < n && !(i + r >= t.length || i >= e.length); ++i) + t[i + r] = e[i]; + return i; + } + function H(e, t) { + return e instanceof t || e != null && e.constructor != null && e.constructor.name != null && e.constructor.name === t.name; + } + function Xt(e) { + return e !== e; + } + var Vl = function() { + let e = "0123456789abcdef", t = new Array(256); + for (let r = 0;r < 16; ++r) { + let n = r * 16; + for (let i = 0;i < 16; ++i) + t[n + i] = e[r] + e[i]; + } + return t; + }(); + function fe(e) { + return typeof BigInt > "u" ? Yl : e; + } + function Yl() { + throw new Error("BigInt not supported"); + } + }); + I = E((Gc, En) => { + En.exports = { ArrayIsArray(e) { + return Array.isArray(e); + }, ArrayPrototypeIncludes(e, t) { + return e.includes(t); + }, ArrayPrototypeIndexOf(e, t) { + return e.indexOf(t); + }, ArrayPrototypeJoin(e, t) { + return e.join(t); + }, ArrayPrototypeMap(e, t) { + return e.map(t); + }, ArrayPrototypePop(e, t) { + return e.pop(t); + }, ArrayPrototypePush(e, t) { + return e.push(t); + }, ArrayPrototypeSlice(e, t, r) { + return e.slice(t, r); + }, Error, FunctionPrototypeCall(e, t, ...r) { + return e.call(t, ...r); + }, FunctionPrototypeSymbolHasInstance(e, t) { + return Function.prototype[Symbol.hasInstance].call(e, t); + }, MathFloor: Math.floor, Number, NumberIsInteger: Number.isInteger, NumberIsNaN: Number.isNaN, NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, NumberParseInt: Number.parseInt, ObjectDefineProperties(e, t) { + return Object.defineProperties(e, t); + }, ObjectDefineProperty(e, t, r) { + return Object.defineProperty(e, t, r); + }, ObjectGetOwnPropertyDescriptor(e, t) { + return Object.getOwnPropertyDescriptor(e, t); + }, ObjectKeys(e) { + return Object.keys(e); + }, ObjectSetPrototypeOf(e, t) { + return Object.setPrototypeOf(e, t); + }, Promise, PromisePrototypeCatch(e, t) { + return e.catch(t); + }, PromisePrototypeThen(e, t, r) { + return e.then(t, r); + }, PromiseReject(e) { + return Promise.reject(e); + }, ReflectApply: Reflect.apply, RegExpPrototypeTest(e, t) { + return e.test(t); + }, SafeSet: Set, String, StringPrototypeSlice(e, t, r) { + return e.slice(t, r); + }, StringPrototypeToLowerCase(e) { + return e.toLowerCase(); + }, StringPrototypeToUpperCase(e) { + return e.toUpperCase(); + }, StringPrototypeTrim(e) { + return e.trim(); + }, Symbol, SymbolAsyncIterator: Symbol.asyncIterator, SymbolHasInstance: Symbol.hasInstance, SymbolIterator: Symbol.iterator, TypedArrayPrototypeSet(e, t, r) { + return e.set(t, r); + }, Uint8Array }; + }); + V = E((Hc, Qt) => { + var Kl = te(), zl = Object.getPrototypeOf(async function() { + }).constructor, Sn = globalThis.Blob || Kl.Blob, Xl = typeof Sn < "u" ? function(t) { + return t instanceof Sn; + } : function(t) { + return false; + }, Jt = class extends Error { + constructor(t) { + if (!Array.isArray(t)) + throw new TypeError(`Expected input to be an Array, got ${typeof t}`); + let r = ""; + for (let n = 0;n < t.length; n++) + r += ` ${t[n].stack} +`; + super(r), this.name = "AggregateError", this.errors = t; + } + }; + Qt.exports = { AggregateError: Jt, kEmptyObject: Object.freeze({}), once(e) { + let t = false; + return function(...r) { + t || (t = true, e.apply(this, r)); + }; + }, createDeferredPromise: function() { + let e, t; + return { promise: new Promise((n, i) => { + e = n, t = i; + }), resolve: e, reject: t }; + }, promisify(e) { + return new Promise((t, r) => { + e((n, ...i) => n ? r(n) : t(...i)); + }); + }, debuglog() { + return function() { + }; + }, format(e, ...t) { + return e.replace(/%([sdifj])/g, function(...[r, n]) { + let i = t.shift(); + return n === "f" ? i.toFixed(6) : n === "j" ? JSON.stringify(i) : n === "s" && typeof i == "object" ? `${i.constructor !== Object ? i.constructor.name : ""} {}`.trim() : i.toString(); + }); + }, inspect(e) { + switch (typeof e) { + case "string": + if (e.includes("'")) + if (e.includes('"')) { + if (!e.includes("`") && !e.includes("${")) + return `\`${e}\``; + } else + return `"${e}"`; + return `'${e}'`; + case "number": + return isNaN(e) ? "NaN" : Object.is(e, -0) ? String(e) : e; + case "bigint": + return `${String(e)}n`; + case "boolean": + case "undefined": + return String(e); + case "object": + return "{}"; + } + }, types: { isAsyncFunction(e) { + return e instanceof zl; + }, isArrayBufferView(e) { + return ArrayBuffer.isView(e); + } }, isBlob: Xl }; + Qt.exports.promisify.custom = Symbol.for("nodejs.util.promisify.custom"); + }); + ut = E((Vc, lt) => { + var { AbortController: mn, AbortSignal: Jl } = typeof self < "u" ? self : typeof window < "u" ? window : undefined; + lt.exports = mn; + lt.exports.AbortSignal = Jl; + lt.exports.default = mn; + }); + C = E((Yc, An) => { + var { format: Ql, inspect: ft, AggregateError: Zl } = V(), eu = globalThis.AggregateError || Zl, tu = Symbol("kIsNodeError"), ru = ["string", "function", "number", "object", "Function", "Object", "boolean", "bigint", "symbol"], nu = /^([A-Z][a-z0-9]*)+$/, iu = "__node_internal_", st = {}; + function be(e, t) { + if (!e) + throw new st.ERR_INTERNAL_ASSERTION(t); + } + function xn(e) { + let t = "", r = e.length, n = e[0] === "-" ? 1 : 0; + for (;r >= n + 4; r -= 3) + t = `_${e.slice(r - 3, r)}${t}`; + return `${e.slice(0, r)}${t}`; + } + function ou(e, t, r) { + if (typeof t == "function") + return be(t.length <= r.length, `Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`), t(...r); + let n = (t.match(/%[dfijoOs]/g) || []).length; + return be(n === r.length, `Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${n}).`), r.length === 0 ? t : Ql(t, ...r); + } + function M(e, t, r) { + r || (r = Error); + + class n extends r { + constructor(...o) { + super(ou(e, t, o)); + } + toString() { + return `${this.name} [${e}]: ${this.message}`; + } + } + Object.defineProperties(n.prototype, { name: { value: r.name, writable: true, enumerable: false, configurable: true }, toString: { value() { + return `${this.name} [${e}]: ${this.message}`; + }, writable: true, enumerable: false, configurable: true } }), n.prototype.code = e, n.prototype[tu] = true, st[e] = n; + } + function Rn(e) { + let t = iu + e.name; + return Object.defineProperty(e, "name", { value: t }), e; + } + function lu(e, t) { + if (e && t && e !== t) { + if (Array.isArray(t.errors)) + return t.errors.push(e), t; + let r = new eu([t, e], t.message); + return r.code = t.code, r; + } + return e || t; + } + var Zt = class extends Error { + constructor(t = "The operation was aborted", r = undefined) { + if (r !== undefined && typeof r != "object") + throw new st.ERR_INVALID_ARG_TYPE("options", "Object", r); + super(t, r), this.code = "ABORT_ERR", this.name = "AbortError"; + } + }; + M("ERR_ASSERTION", "%s", Error); + M("ERR_INVALID_ARG_TYPE", (e, t, r) => { + be(typeof e == "string", "'name' must be a string"), Array.isArray(t) || (t = [t]); + let n = "The "; + e.endsWith(" argument") ? n += `${e} ` : n += `"${e}" ${e.includes(".") ? "property" : "argument"} `, n += "must be "; + let i = [], o = [], l = []; + for (let f of t) + be(typeof f == "string", "All expected entries have to be of type string"), ru.includes(f) ? i.push(f.toLowerCase()) : nu.test(f) ? o.push(f) : (be(f !== "object", 'The value "object" should be written as "Object"'), l.push(f)); + if (o.length > 0) { + let f = i.indexOf("object"); + f !== -1 && (i.splice(i, f, 1), o.push("Object")); + } + if (i.length > 0) { + switch (i.length) { + case 1: + n += `of type ${i[0]}`; + break; + case 2: + n += `one of type ${i[0]} or ${i[1]}`; + break; + default: { + let f = i.pop(); + n += `one of type ${i.join(", ")}, or ${f}`; + } + } + (o.length > 0 || l.length > 0) && (n += " or "); + } + if (o.length > 0) { + switch (o.length) { + case 1: + n += `an instance of ${o[0]}`; + break; + case 2: + n += `an instance of ${o[0]} or ${o[1]}`; + break; + default: { + let f = o.pop(); + n += `an instance of ${o.join(", ")}, or ${f}`; + } + } + l.length > 0 && (n += " or "); + } + switch (l.length) { + case 0: + break; + case 1: + l[0].toLowerCase() !== l[0] && (n += "an "), n += `${l[0]}`; + break; + case 2: + n += `one of ${l[0]} or ${l[1]}`; + break; + default: { + let f = l.pop(); + n += `one of ${l.join(", ")}, or ${f}`; + } + } + if (r == null) + n += `. Received ${r}`; + else if (typeof r == "function" && r.name) + n += `. Received function ${r.name}`; + else if (typeof r == "object") { + var u; + (u = r.constructor) !== null && u !== undefined && u.name ? n += `. Received an instance of ${r.constructor.name}` : n += `. Received ${ft(r, { depth: -1 })}`; + } else { + let f = ft(r, { colors: false }); + f.length > 25 && (f = `${f.slice(0, 25)}...`), n += `. Received type ${typeof r} (${f})`; + } + return n; + }, TypeError); + M("ERR_INVALID_ARG_VALUE", (e, t, r = "is invalid") => { + let n = ft(t); + return n.length > 128 && (n = n.slice(0, 128) + "..."), `The ${e.includes(".") ? "property" : "argument"} '${e}' ${r}. Received ${n}`; + }, TypeError); + M("ERR_INVALID_RETURN_VALUE", (e, t, r) => { + var n; + let i = r != null && (n = r.constructor) !== null && n !== undefined && n.name ? `instance of ${r.constructor.name}` : `type ${typeof r}`; + return `Expected ${e} to be returned from the "${t}" function but got ${i}.`; + }, TypeError); + M("ERR_MISSING_ARGS", (...e) => { + be(e.length > 0, "At least one arg needs to be specified"); + let t, r = e.length; + switch (e = (Array.isArray(e) ? e : [e]).map((n) => `"${n}"`).join(" or "), r) { + case 1: + t += `The ${e[0]} argument`; + break; + case 2: + t += `The ${e[0]} and ${e[1]} arguments`; + break; + default: + { + let n = e.pop(); + t += `The ${e.join(", ")}, and ${n} arguments`; + } + break; + } + return `${t} must be specified`; + }, TypeError); + M("ERR_OUT_OF_RANGE", (e, t, r) => { + be(t, 'Missing "range" argument'); + let n; + return Number.isInteger(r) && Math.abs(r) > 2 ** 32 ? n = xn(String(r)) : typeof r == "bigint" ? (n = String(r), (r > 2n ** 32n || r < -(2n ** 32n)) && (n = xn(n)), n += "n") : n = ft(r), `The value of "${e}" is out of range. It must be ${t}. Received ${n}`; + }, RangeError); + M("ERR_MULTIPLE_CALLBACK", "Callback called multiple times", Error); + M("ERR_METHOD_NOT_IMPLEMENTED", "The %s method is not implemented", Error); + M("ERR_STREAM_ALREADY_FINISHED", "Cannot call %s after a stream was finished", Error); + M("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable", Error); + M("ERR_STREAM_DESTROYED", "Cannot call %s after a stream was destroyed", Error); + M("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + M("ERR_STREAM_PREMATURE_CLOSE", "Premature close", Error); + M("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF", Error); + M("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event", Error); + M("ERR_STREAM_WRITE_AFTER_END", "write after end", Error); + M("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s", TypeError); + An.exports = { AbortError: Zt, aggregateTwoErrors: Rn(lu), hideStackFrames: Rn, codes: st }; + }); + He = E((Kc, Cn) => { + var { ArrayIsArray: Bn, ArrayPrototypeIncludes: Ln, ArrayPrototypeJoin: Nn, ArrayPrototypeMap: uu, NumberIsInteger: tr, NumberIsNaN: fu, NumberMAX_SAFE_INTEGER: su, NumberMIN_SAFE_INTEGER: au, NumberParseInt: cu, ObjectPrototypeHasOwnProperty: du, RegExpPrototypeExec: hu, String: pu, StringPrototypeToUpperCase: yu, StringPrototypeTrim: wu } = I(), { hideStackFrames: W, codes: { ERR_SOCKET_BAD_PORT: bu, ERR_INVALID_ARG_TYPE: D, ERR_INVALID_ARG_VALUE: at, ERR_OUT_OF_RANGE: ge, ERR_UNKNOWN_SIGNAL: In } } = C(), { normalizeEncoding: gu } = V(), { isAsyncFunction: _u, isArrayBufferView: Eu } = V().types, Tn = {}; + function Su(e) { + return e === (e | 0); + } + function mu(e) { + return e === e >>> 0; + } + var xu = /^[0-7]+$/, Ru = "must be a 32-bit unsigned integer or an octal string"; + function Au(e, t, r) { + if (typeof e > "u" && (e = r), typeof e == "string") { + if (hu(xu, e) === null) + throw new at(t, e, Ru); + e = cu(e, 8); + } + return Fn(e, t), e; + } + var Iu = W((e, t, r = au, n = su) => { + if (typeof e != "number") + throw new D(t, "number", e); + if (!tr(e)) + throw new ge(t, "an integer", e); + if (e < r || e > n) + throw new ge(t, `>= ${r} && <= ${n}`, e); + }), Tu = W((e, t, r = -2147483648, n = 2147483647) => { + if (typeof e != "number") + throw new D(t, "number", e); + if (!tr(e)) + throw new ge(t, "an integer", e); + if (e < r || e > n) + throw new ge(t, `>= ${r} && <= ${n}`, e); + }), Fn = W((e, t, r = false) => { + if (typeof e != "number") + throw new D(t, "number", e); + if (!tr(e)) + throw new ge(t, "an integer", e); + let n = r ? 1 : 0, i = 4294967295; + if (e < n || e > i) + throw new ge(t, `>= ${n} && <= ${i}`, e); + }); + function Mn(e, t) { + if (typeof e != "string") + throw new D(t, "string", e); + } + function Bu(e, t, r = undefined, n) { + if (typeof e != "number") + throw new D(t, "number", e); + if (r != null && e < r || n != null && e > n || (r != null || n != null) && fu(e)) + throw new ge(t, `${r != null ? `>= ${r}` : ""}${r != null && n != null ? " && " : ""}${n != null ? `<= ${n}` : ""}`, e); + } + var Lu = W((e, t, r) => { + if (!Ln(r, e)) { + let n = Nn(uu(r, (o) => typeof o == "string" ? `'${o}'` : pu(o)), ", "), i = "must be one of: " + n; + throw new at(t, e, i); + } + }); + function Nu(e, t) { + if (typeof e != "boolean") + throw new D(t, "boolean", e); + } + function er(e, t, r) { + return e == null || !du(e, t) ? r : e[t]; + } + var Fu = W((e, t, r = null) => { + let n = er(r, "allowArray", false), i = er(r, "allowFunction", false); + if (!er(r, "nullable", false) && e === null || !n && Bn(e) || typeof e != "object" && (!i || typeof e != "function")) + throw new D(t, "Object", e); + }), Mu = W((e, t, r = 0) => { + if (!Bn(e)) + throw new D(t, "Array", e); + if (e.length < r) { + let n = `must be longer than ${r}`; + throw new at(t, e, n); + } + }); + function Cu(e, t = "signal") { + if (Mn(e, t), Tn[e] === undefined) + throw Tn[yu(e)] !== undefined ? new In(e + " (signals must use all capital letters)") : new In(e); + } + var Ou = W((e, t = "buffer") => { + if (!Eu(e)) + throw new D(t, ["Buffer", "TypedArray", "DataView"], e); + }); + function Du(e, t) { + let r = gu(t), n = e.length; + if (r === "hex" && n % 2 !== 0) + throw new at("encoding", t, `is invalid for data of length ${n}`); + } + function Pu(e, t = "Port", r = true) { + if (typeof e != "number" && typeof e != "string" || typeof e == "string" && wu(e).length === 0 || +e !== +e >>> 0 || e > 65535 || e === 0 && !r) + throw new bu(t, e, r); + return e | 0; + } + var ku = W((e, t) => { + if (e !== undefined && (e === null || typeof e != "object" || !("aborted" in e))) + throw new D(t, "AbortSignal", e); + }), Uu = W((e, t) => { + if (typeof e != "function") + throw new D(t, "Function", e); + }), vu = W((e, t) => { + if (typeof e != "function" || _u(e)) + throw new D(t, "Function", e); + }), qu = W((e, t) => { + if (e !== undefined) + throw new D(t, "undefined", e); + }); + function Wu(e, t, r) { + if (!Ln(r, e)) + throw new D(t, `('${Nn(r, "|")}')`, e); + } + Cn.exports = { isInt32: Su, isUint32: mu, parseFileMode: Au, validateArray: Mu, validateBoolean: Nu, validateBuffer: Ou, validateEncoding: Du, validateFunction: Uu, validateInt32: Tu, validateInteger: Iu, validateNumber: Bu, validateObject: Fu, validateOneOf: Lu, validatePlainFunction: vu, validatePort: Pu, validateSignalName: Cu, validateString: Mn, validateUint32: Fn, validateUndefined: qu, validateUnion: Wu, validateAbortSignal: ku }; + }); + ir = E((zc, kn) => { + var x = kn.exports = {}, Y, K; + function rr() { + throw new Error("setTimeout has not been defined"); + } + function nr() { + throw new Error("clearTimeout has not been defined"); + } + (function() { + try { + typeof setTimeout == "function" ? Y = setTimeout : Y = rr; + } catch { + Y = rr; + } + try { + typeof clearTimeout == "function" ? K = clearTimeout : K = nr; + } catch { + K = nr; + } + })(); + function On(e) { + if (Y === setTimeout) + return setTimeout(e, 0); + if ((Y === rr || !Y) && setTimeout) + return Y = setTimeout, setTimeout(e, 0); + try { + return Y(e, 0); + } catch { + try { + return Y.call(null, e, 0); + } catch { + return Y.call(this, e, 0); + } + } + } + function $u(e) { + if (K === clearTimeout) + return clearTimeout(e); + if ((K === nr || !K) && clearTimeout) + return K = clearTimeout, clearTimeout(e); + try { + return K(e); + } catch { + try { + return K.call(null, e); + } catch { + return K.call(this, e); + } + } + } + var re = [], Me = false, _e, ct = -1; + function ju() { + !Me || !_e || (Me = false, _e.length ? re = _e.concat(re) : ct = -1, re.length && Dn()); + } + function Dn() { + if (!Me) { + var e = On(ju); + Me = true; + for (var t = re.length;t; ) { + for (_e = re, re = [];++ct < t; ) + _e && _e[ct].run(); + ct = -1, t = re.length; + } + _e = null, Me = false, $u(e); + } + } + x.nextTick = function(e) { + var t = new Array(arguments.length - 1); + if (arguments.length > 1) + for (var r = 1;r < arguments.length; r++) + t[r - 1] = arguments[r]; + re.push(new Pn(e, t)), re.length === 1 && !Me && On(Dn); + }; + function Pn(e, t) { + this.fun = e, this.array = t; + } + Pn.prototype.run = function() { + this.fun.apply(null, this.array); + }; + x.title = "browser"; + x.browser = true; + x.env = {}; + x.argv = []; + x.version = ""; + x.versions = {}; + function ne() { + } + x.on = ne; + x.addListener = ne; + x.once = ne; + x.off = ne; + x.removeListener = ne; + x.removeAllListeners = ne; + x.emit = ne; + x.prependListener = ne; + x.prependOnceListener = ne; + x.listeners = function(e) { + return []; + }; + x.binding = function(e) { + throw new Error("process.binding is not supported"); + }; + x.cwd = function() { + return "/"; + }; + x.chdir = function(e) { + throw new Error("process.chdir is not supported"); + }; + x.umask = function() { + return 0; + }; + }); + k = {}; + Qr(k, { default: () => Gu }); + se = yl(() => { + ue(k, rt(ir())); + Gu = rt(ir()); + }); + ae = E((Jc, zn) => { + var { Symbol: dt, SymbolAsyncIterator: Un, SymbolIterator: vn } = I(), qn = dt("kDestroyed"), Wn = dt("kIsErrored"), or = dt("kIsReadable"), $n = dt("kIsDisturbed"); + function ht(e, t = false) { + var r; + return !!(e && typeof e.pipe == "function" && typeof e.on == "function" && (!t || typeof e.pause == "function" && typeof e.resume == "function") && (!e._writableState || ((r = e._readableState) === null || r === undefined ? undefined : r.readable) !== false) && (!e._writableState || e._readableState)); + } + function pt(e) { + var t; + return !!(e && typeof e.write == "function" && typeof e.on == "function" && (!e._readableState || ((t = e._writableState) === null || t === undefined ? undefined : t.writable) !== false)); + } + function Hu(e) { + return !!(e && typeof e.pipe == "function" && e._readableState && typeof e.on == "function" && typeof e.write == "function"); + } + function Ee(e) { + return e && (e._readableState || e._writableState || typeof e.write == "function" && typeof e.on == "function" || typeof e.pipe == "function" && typeof e.on == "function"); + } + function Vu(e, t) { + return e == null ? false : t === true ? typeof e[Un] == "function" : t === false ? typeof e[vn] == "function" : typeof e[Un] == "function" || typeof e[vn] == "function"; + } + function yt(e) { + if (!Ee(e)) + return null; + let { _writableState: t, _readableState: r } = e, n = t || r; + return !!(e.destroyed || e[qn] || n != null && n.destroyed); + } + function jn(e) { + if (!pt(e)) + return null; + if (e.writableEnded === true) + return true; + let t = e._writableState; + return t != null && t.errored ? false : typeof t?.ended != "boolean" ? null : t.ended; + } + function Yu(e, t) { + if (!pt(e)) + return null; + if (e.writableFinished === true) + return true; + let r = e._writableState; + return r != null && r.errored ? false : typeof r?.finished != "boolean" ? null : !!(r.finished || t === false && r.ended === true && r.length === 0); + } + function Ku(e) { + if (!ht(e)) + return null; + if (e.readableEnded === true) + return true; + let t = e._readableState; + return !t || t.errored ? false : typeof t?.ended != "boolean" ? null : t.ended; + } + function Gn(e, t) { + if (!ht(e)) + return null; + let r = e._readableState; + return r != null && r.errored ? false : typeof r?.endEmitted != "boolean" ? null : !!(r.endEmitted || t === false && r.ended === true && r.length === 0); + } + function Hn(e) { + return e && e[or] != null ? e[or] : typeof e?.readable != "boolean" ? null : yt(e) ? false : ht(e) && e.readable && !Gn(e); + } + function Vn(e) { + return typeof e?.writable != "boolean" ? null : yt(e) ? false : pt(e) && e.writable && !jn(e); + } + function zu(e, t) { + return Ee(e) ? yt(e) ? true : !(t?.readable !== false && Hn(e) || t?.writable !== false && Vn(e)) : null; + } + function Xu(e) { + var t, r; + return Ee(e) ? e.writableErrored ? e.writableErrored : (t = (r = e._writableState) === null || r === undefined ? undefined : r.errored) !== null && t !== undefined ? t : null : null; + } + function Ju(e) { + var t, r; + return Ee(e) ? e.readableErrored ? e.readableErrored : (t = (r = e._readableState) === null || r === undefined ? undefined : r.errored) !== null && t !== undefined ? t : null : null; + } + function Qu(e) { + if (!Ee(e)) + return null; + if (typeof e.closed == "boolean") + return e.closed; + let { _writableState: t, _readableState: r } = e; + return typeof t?.closed == "boolean" || typeof r?.closed == "boolean" ? t?.closed || r?.closed : typeof e._closed == "boolean" && Yn(e) ? e._closed : null; + } + function Yn(e) { + return typeof e._closed == "boolean" && typeof e._defaultKeepAlive == "boolean" && typeof e._removedConnection == "boolean" && typeof e._removedContLen == "boolean"; + } + function Kn(e) { + return typeof e._sent100 == "boolean" && Yn(e); + } + function Zu(e) { + var t; + return typeof e._consuming == "boolean" && typeof e._dumped == "boolean" && ((t = e.req) === null || t === undefined ? undefined : t.upgradeOrConnect) === undefined; + } + function ef(e) { + if (!Ee(e)) + return null; + let { _writableState: t, _readableState: r } = e, n = t || r; + return !n && Kn(e) || !!(n && n.autoDestroy && n.emitClose && n.closed === false); + } + function tf(e) { + var t; + return !!(e && ((t = e[$n]) !== null && t !== undefined ? t : e.readableDidRead || e.readableAborted)); + } + function rf(e) { + var t, r, n, i, o, l, u, f, s, d; + return !!(e && ((t = (r = (n = (i = (o = (l = e[Wn]) !== null && l !== undefined ? l : e.readableErrored) !== null && o !== undefined ? o : e.writableErrored) !== null && i !== undefined ? i : (u = e._readableState) === null || u === undefined ? undefined : u.errorEmitted) !== null && n !== undefined ? n : (f = e._writableState) === null || f === undefined ? undefined : f.errorEmitted) !== null && r !== undefined ? r : (s = e._readableState) === null || s === undefined ? undefined : s.errored) !== null && t !== undefined ? t : (d = e._writableState) === null || d === undefined ? undefined : d.errored)); + } + zn.exports = { kDestroyed: qn, isDisturbed: tf, kIsDisturbed: $n, isErrored: rf, kIsErrored: Wn, isReadable: Hn, kIsReadable: or, isClosed: Qu, isDestroyed: yt, isDuplexNodeStream: Hu, isFinished: zu, isIterable: Vu, isReadableNodeStream: ht, isReadableEnded: Ku, isReadableFinished: Gn, isReadableErrored: Ju, isNodeStream: Ee, isWritable: Vn, isWritableNodeStream: pt, isWritableEnded: jn, isWritableFinished: Yu, isWritableErrored: Xu, isServerRequest: Zu, isServerResponse: Kn, willEmitClose: ef }; + }); + ce = E((Qc, ur) => { + var Ce = (se(), pe(k)), { AbortError: nf, codes: of } = C(), { ERR_INVALID_ARG_TYPE: lf, ERR_STREAM_PREMATURE_CLOSE: Xn } = of, { kEmptyObject: Jn, once: Qn } = V(), { validateAbortSignal: uf, validateFunction: ff, validateObject: sf } = He(), { Promise: af } = I(), { isClosed: cf, isReadable: Zn, isReadableNodeStream: lr, isReadableFinished: ei, isReadableErrored: df, isWritable: ti, isWritableNodeStream: ri, isWritableFinished: ni, isWritableErrored: hf, isNodeStream: pf, willEmitClose: yf } = ae(); + function wf(e) { + return e.setHeader && typeof e.abort == "function"; + } + var bf = () => { + }; + function ii(e, t, r) { + var n, i; + arguments.length === 2 ? (r = t, t = Jn) : t == null ? t = Jn : sf(t, "options"), ff(r, "callback"), uf(t.signal, "options.signal"), r = Qn(r); + let o = (n = t.readable) !== null && n !== undefined ? n : lr(e), l = (i = t.writable) !== null && i !== undefined ? i : ri(e); + if (!pf(e)) + throw new lf("stream", "Stream", e); + let { _writableState: u, _readableState: f } = e, s = () => { + e.writable || y(); + }, d = yf(e) && lr(e) === o && ri(e) === l, c = ni(e, false), y = () => { + c = true, e.destroyed && (d = false), !(d && (!e.readable || o)) && (!o || h) && r.call(e); + }, h = ei(e, false), p = () => { + h = true, e.destroyed && (d = false), !(d && (!e.writable || l)) && (!l || c) && r.call(e); + }, B = (N) => { + r.call(e, N); + }, v = cf(e), w = () => { + v = true; + let N = hf(e) || df(e); + if (N && typeof N != "boolean") + return r.call(e, N); + if (o && !h && lr(e, true) && !ei(e, false)) + return r.call(e, new Xn); + if (l && !c && !ni(e, false)) + return r.call(e, new Xn); + r.call(e); + }, b = () => { + e.req.on("finish", y); + }; + wf(e) ? (e.on("complete", y), d || e.on("abort", w), e.req ? b() : e.on("request", b)) : l && !u && (e.on("end", s), e.on("close", s)), !d && typeof e.aborted == "boolean" && e.on("aborted", w), e.on("end", p), e.on("finish", y), t.error !== false && e.on("error", B), e.on("close", w), v ? Ce.nextTick(w) : u != null && u.errorEmitted || f != null && f.errorEmitted ? d || Ce.nextTick(w) : (!o && (!d || Zn(e)) && (c || ti(e) === false) || !l && (!d || ti(e)) && (h || Zn(e) === false) || f && e.req && e.aborted) && Ce.nextTick(w); + let L = () => { + r = bf, e.removeListener("aborted", w), e.removeListener("complete", y), e.removeListener("abort", w), e.removeListener("request", b), e.req && e.req.removeListener("finish", y), e.removeListener("end", s), e.removeListener("close", s), e.removeListener("finish", y), e.removeListener("end", p), e.removeListener("error", B), e.removeListener("close", w); + }; + if (t.signal && !v) { + let N = () => { + let Q = r; + L(), Q.call(e, new nf(undefined, { cause: t.signal.reason })); + }; + if (t.signal.aborted) + Ce.nextTick(N); + else { + let Q = r; + r = Qn((...Ie) => { + t.signal.removeEventListener("abort", N), Q.apply(e, Ie); + }), t.signal.addEventListener("abort", N); + } + } + return L; + } + function gf(e, t) { + return new af((r, n) => { + ii(e, t, (i) => { + i ? n(i) : r(); + }); + }); + } + ur.exports = ii; + ur.exports.finished = gf; + }); + di = E((Zc, ar) => { + var fi = globalThis.AbortController || ut().AbortController, { codes: { ERR_INVALID_ARG_TYPE: Ve, ERR_MISSING_ARGS: _f, ERR_OUT_OF_RANGE: Ef }, AbortError: z } = C(), { validateAbortSignal: Oe, validateInteger: Sf, validateObject: De } = He(), mf = I().Symbol("kWeak"), { finished: xf } = ce(), { ArrayPrototypePush: Rf, MathFloor: Af, Number: If, NumberIsNaN: Tf, Promise: oi, PromiseReject: li, PromisePrototypeThen: Bf, Symbol: si } = I(), wt = si("kEmpty"), ui = si("kEof"); + function bt(e, t) { + if (typeof e != "function") + throw new Ve("fn", ["Function", "AsyncFunction"], e); + t != null && De(t, "options"), t?.signal != null && Oe(t.signal, "options.signal"); + let r = 1; + return t?.concurrency != null && (r = Af(t.concurrency)), Sf(r, "concurrency", 1), async function* () { + var i, o; + let l = new fi, u = this, f = [], s = l.signal, d = { signal: s }, c = () => l.abort(); + t != null && (i = t.signal) !== null && i !== undefined && i.aborted && c(), t == null || (o = t.signal) === null || o === undefined || o.addEventListener("abort", c); + let y, h, p = false; + function B() { + p = true; + } + async function v() { + try { + for await (let L of u) { + var w; + if (p) + return; + if (s.aborted) + throw new z; + try { + L = e(L, d); + } catch (N) { + L = li(N); + } + L !== wt && (typeof ((w = L) === null || w === undefined ? undefined : w.catch) == "function" && L.catch(B), f.push(L), y && (y(), y = null), !p && f.length && f.length >= r && await new oi((N) => { + h = N; + })); + } + f.push(ui); + } catch (L) { + let N = li(L); + Bf(N, undefined, B), f.push(N); + } finally { + var b; + p = true, y && (y(), y = null), t == null || (b = t.signal) === null || b === undefined || b.removeEventListener("abort", c); + } + } + v(); + try { + for (;; ) { + for (;f.length > 0; ) { + let w = await f[0]; + if (w === ui) + return; + if (s.aborted) + throw new z; + w !== wt && (yield w), f.shift(), h && (h(), h = null); + } + await new oi((w) => { + y = w; + }); + } + } finally { + l.abort(), p = true, h && (h(), h = null); + } + }.call(this); + } + function Lf(e = undefined) { + return e != null && De(e, "options"), e?.signal != null && Oe(e.signal, "options.signal"), async function* () { + let r = 0; + for await (let i of this) { + var n; + if (e != null && (n = e.signal) !== null && n !== undefined && n.aborted) + throw new z({ cause: e.signal.reason }); + yield [r++, i]; + } + }.call(this); + } + async function ai(e, t = undefined) { + for await (let r of sr.call(this, e, t)) + return true; + return false; + } + async function Nf(e, t = undefined) { + if (typeof e != "function") + throw new Ve("fn", ["Function", "AsyncFunction"], e); + return !await ai.call(this, async (...r) => !await e(...r), t); + } + async function Ff(e, t) { + for await (let r of sr.call(this, e, t)) + return r; + } + async function Mf(e, t) { + if (typeof e != "function") + throw new Ve("fn", ["Function", "AsyncFunction"], e); + async function r(n, i) { + return await e(n, i), wt; + } + for await (let n of bt.call(this, r, t)) + ; + } + function sr(e, t) { + if (typeof e != "function") + throw new Ve("fn", ["Function", "AsyncFunction"], e); + async function r(n, i) { + return await e(n, i) ? n : wt; + } + return bt.call(this, r, t); + } + var fr = class extends _f { + constructor() { + super("reduce"), this.message = "Reduce of an empty stream requires an initial value"; + } + }; + async function Cf(e, t, r) { + var n; + if (typeof e != "function") + throw new Ve("reducer", ["Function", "AsyncFunction"], e); + r != null && De(r, "options"), r?.signal != null && Oe(r.signal, "options.signal"); + let i = arguments.length > 1; + if (r != null && (n = r.signal) !== null && n !== undefined && n.aborted) { + let s = new z(undefined, { cause: r.signal.reason }); + throw this.once("error", () => { + }), await xf(this.destroy(s)), s; + } + let o = new fi, l = o.signal; + if (r != null && r.signal) { + let s = { once: true, [mf]: this }; + r.signal.addEventListener("abort", () => o.abort(), s); + } + let u = false; + try { + for await (let s of this) { + var f; + if (u = true, r != null && (f = r.signal) !== null && f !== undefined && f.aborted) + throw new z; + i ? t = await e(t, s, { signal: l }) : (t = s, i = true); + } + if (!u && !i) + throw new fr; + } finally { + o.abort(); + } + return t; + } + async function Of(e) { + e != null && De(e, "options"), e?.signal != null && Oe(e.signal, "options.signal"); + let t = []; + for await (let n of this) { + var r; + if (e != null && (r = e.signal) !== null && r !== undefined && r.aborted) + throw new z(undefined, { cause: e.signal.reason }); + Rf(t, n); + } + return t; + } + function Df(e, t) { + let r = bt.call(this, e, t); + return async function* () { + for await (let i of r) + yield* i; + }.call(this); + } + function ci(e) { + if (e = If(e), Tf(e)) + return 0; + if (e < 0) + throw new Ef("number", ">= 0", e); + return e; + } + function Pf(e, t = undefined) { + return t != null && De(t, "options"), t?.signal != null && Oe(t.signal, "options.signal"), e = ci(e), async function* () { + var n; + if (t != null && (n = t.signal) !== null && n !== undefined && n.aborted) + throw new z; + for await (let o of this) { + var i; + if (t != null && (i = t.signal) !== null && i !== undefined && i.aborted) + throw new z; + e-- <= 0 && (yield o); + } + }.call(this); + } + function kf(e, t = undefined) { + return t != null && De(t, "options"), t?.signal != null && Oe(t.signal, "options.signal"), e = ci(e), async function* () { + var n; + if (t != null && (n = t.signal) !== null && n !== undefined && n.aborted) + throw new z; + for await (let o of this) { + var i; + if (t != null && (i = t.signal) !== null && i !== undefined && i.aborted) + throw new z; + if (e-- > 0) + yield o; + else + return; + } + }.call(this); + } + ar.exports.streamReturningOperators = { asIndexedPairs: Lf, drop: Pf, filter: sr, flatMap: Df, map: bt, take: kf }; + ar.exports.promiseReturningOperators = { every: Nf, forEach: Mf, reduce: Cf, toArray: Of, some: ai, find: Ff }; + }); + Se = E((ed, Ei) => { + var de = (se(), pe(k)), { aggregateTwoErrors: Uf, codes: { ERR_MULTIPLE_CALLBACK: vf }, AbortError: qf } = C(), { Symbol: yi } = I(), { kDestroyed: Wf, isDestroyed: $f, isFinished: jf, isServerRequest: Gf } = ae(), wi = yi("kDestroy"), cr = yi("kConstruct"); + function bi(e, t, r) { + e && (e.stack, t && !t.errored && (t.errored = e), r && !r.errored && (r.errored = e)); + } + function Hf(e, t) { + let r = this._readableState, n = this._writableState, i = n || r; + return n && n.destroyed || r && r.destroyed ? (typeof t == "function" && t(), this) : (bi(e, n, r), n && (n.destroyed = true), r && (r.destroyed = true), i.constructed ? hi(this, e, t) : this.once(wi, function(o) { + hi(this, Uf(o, e), t); + }), this); + } + function hi(e, t, r) { + let n = false; + function i(o) { + if (n) + return; + n = true; + let { _readableState: l, _writableState: u } = e; + bi(o, u, l), u && (u.closed = true), l && (l.closed = true), typeof r == "function" && r(o), o ? de.nextTick(Vf, e, o) : de.nextTick(gi, e); + } + try { + e._destroy(t || null, i); + } catch (o) { + i(o); + } + } + function Vf(e, t) { + dr(e, t), gi(e); + } + function gi(e) { + let { _readableState: t, _writableState: r } = e; + r && (r.closeEmitted = true), t && (t.closeEmitted = true), (r && r.emitClose || t && t.emitClose) && e.emit("close"); + } + function dr(e, t) { + let { _readableState: r, _writableState: n } = e; + n && n.errorEmitted || r && r.errorEmitted || (n && (n.errorEmitted = true), r && (r.errorEmitted = true), e.emit("error", t)); + } + function Yf() { + let e = this._readableState, t = this._writableState; + e && (e.constructed = true, e.closed = false, e.closeEmitted = false, e.destroyed = false, e.errored = null, e.errorEmitted = false, e.reading = false, e.ended = e.readable === false, e.endEmitted = e.readable === false), t && (t.constructed = true, t.destroyed = false, t.closed = false, t.closeEmitted = false, t.errored = null, t.errorEmitted = false, t.finalCalled = false, t.prefinished = false, t.ended = t.writable === false, t.ending = t.writable === false, t.finished = t.writable === false); + } + function hr(e, t, r) { + let { _readableState: n, _writableState: i } = e; + if (i && i.destroyed || n && n.destroyed) + return this; + n && n.autoDestroy || i && i.autoDestroy ? e.destroy(t) : t && (t.stack, i && !i.errored && (i.errored = t), n && !n.errored && (n.errored = t), r ? de.nextTick(dr, e, t) : dr(e, t)); + } + function Kf(e, t) { + if (typeof e._construct != "function") + return; + let { _readableState: r, _writableState: n } = e; + r && (r.constructed = false), n && (n.constructed = false), e.once(cr, t), !(e.listenerCount(cr) > 1) && de.nextTick(zf, e); + } + function zf(e) { + let t = false; + function r(n) { + if (t) { + hr(e, n ?? new vf); + return; + } + t = true; + let { _readableState: i, _writableState: o } = e, l = o || i; + i && (i.constructed = true), o && (o.constructed = true), l.destroyed ? e.emit(wi, n) : n ? hr(e, n, true) : de.nextTick(Xf, e); + } + try { + e._construct(r); + } catch (n) { + r(n); + } + } + function Xf(e) { + e.emit(cr); + } + function pi(e) { + return e && e.setHeader && typeof e.abort == "function"; + } + function _i(e) { + e.emit("close"); + } + function Jf(e, t) { + e.emit("error", t), de.nextTick(_i, e); + } + function Qf(e, t) { + !e || $f(e) || (!t && !jf(e) && (t = new qf), Gf(e) ? (e.socket = null, e.destroy(t)) : pi(e) ? e.abort() : pi(e.req) ? e.req.abort() : typeof e.destroy == "function" ? e.destroy(t) : typeof e.close == "function" ? e.close() : t ? de.nextTick(Jf, e, t) : de.nextTick(_i, e), e.destroyed || (e[Wf] = true)); + } + Ei.exports = { construct: Kf, destroyer: Qf, destroy: Hf, undestroy: Yf, errorOrDestroy: hr }; + }); + Et = E((td, pr) => { + var Pe = typeof Reflect == "object" ? Reflect : null, Si = Pe && typeof Pe.apply == "function" ? Pe.apply : function(t, r, n) { + return Function.prototype.apply.call(t, r, n); + }, gt; + Pe && typeof Pe.ownKeys == "function" ? gt = Pe.ownKeys : Object.getOwnPropertySymbols ? gt = function(t) { + return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t)); + } : gt = function(t) { + return Object.getOwnPropertyNames(t); + }; + function Zf(e) { + console && console.warn && console.warn(e); + } + var xi = Number.isNaN || function(t) { + return t !== t; + }; + function S() { + S.init.call(this); + } + pr.exports = S; + pr.exports.once = ns; + S.EventEmitter = S; + S.prototype._events = undefined; + S.prototype._eventsCount = 0; + S.prototype._maxListeners = undefined; + var mi = 10; + function _t(e) { + if (typeof e != "function") + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof e); + } + Object.defineProperty(S, "defaultMaxListeners", { enumerable: true, get: function() { + return mi; + }, set: function(e) { + if (typeof e != "number" || e < 0 || xi(e)) + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + e + "."); + mi = e; + } }); + S.init = function() { + (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) && (this._events = Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || undefined; + }; + S.prototype.setMaxListeners = function(t) { + if (typeof t != "number" || t < 0 || xi(t)) + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + t + "."); + return this._maxListeners = t, this; + }; + function Ri(e) { + return e._maxListeners === undefined ? S.defaultMaxListeners : e._maxListeners; + } + S.prototype.getMaxListeners = function() { + return Ri(this); + }; + S.prototype.emit = function(t) { + for (var r = [], n = 1;n < arguments.length; n++) + r.push(arguments[n]); + var i = t === "error", o = this._events; + if (o !== undefined) + i = i && o.error === undefined; + else if (!i) + return false; + if (i) { + var l; + if (r.length > 0 && (l = r[0]), l instanceof Error) + throw l; + var u = new Error("Unhandled error." + (l ? " (" + l.message + ")" : "")); + throw u.context = l, u; + } + var f = o[t]; + if (f === undefined) + return false; + if (typeof f == "function") + Si(f, this, r); + else + for (var s = f.length, d = Li(f, s), n = 0;n < s; ++n) + Si(d[n], this, r); + return true; + }; + function Ai(e, t, r, n) { + var i, o, l; + if (_t(r), o = e._events, o === undefined ? (o = e._events = Object.create(null), e._eventsCount = 0) : (o.newListener !== undefined && (e.emit("newListener", t, r.listener ? r.listener : r), o = e._events), l = o[t]), l === undefined) + l = o[t] = r, ++e._eventsCount; + else if (typeof l == "function" ? l = o[t] = n ? [r, l] : [l, r] : n ? l.unshift(r) : l.push(r), i = Ri(e), i > 0 && l.length > i && !l.warned) { + l.warned = true; + var u = new Error("Possible EventEmitter memory leak detected. " + l.length + " " + String(t) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + u.name = "MaxListenersExceededWarning", u.emitter = e, u.type = t, u.count = l.length, Zf(u); + } + return e; + } + S.prototype.addListener = function(t, r) { + return Ai(this, t, r, false); + }; + S.prototype.on = S.prototype.addListener; + S.prototype.prependListener = function(t, r) { + return Ai(this, t, r, true); + }; + function es() { + if (!this.fired) + return this.target.removeListener(this.type, this.wrapFn), this.fired = true, arguments.length === 0 ? this.listener.call(this.target) : this.listener.apply(this.target, arguments); + } + function Ii(e, t, r) { + var n = { fired: false, wrapFn: undefined, target: e, type: t, listener: r }, i = es.bind(n); + return i.listener = r, n.wrapFn = i, i; + } + S.prototype.once = function(t, r) { + return _t(r), this.on(t, Ii(this, t, r)), this; + }; + S.prototype.prependOnceListener = function(t, r) { + return _t(r), this.prependListener(t, Ii(this, t, r)), this; + }; + S.prototype.removeListener = function(t, r) { + var n, i, o, l, u; + if (_t(r), i = this._events, i === undefined) + return this; + if (n = i[t], n === undefined) + return this; + if (n === r || n.listener === r) + --this._eventsCount === 0 ? this._events = Object.create(null) : (delete i[t], i.removeListener && this.emit("removeListener", t, n.listener || r)); + else if (typeof n != "function") { + for (o = -1, l = n.length - 1;l >= 0; l--) + if (n[l] === r || n[l].listener === r) { + u = n[l].listener, o = l; + break; + } + if (o < 0) + return this; + o === 0 ? n.shift() : ts(n, o), n.length === 1 && (i[t] = n[0]), i.removeListener !== undefined && this.emit("removeListener", t, u || r); + } + return this; + }; + S.prototype.off = S.prototype.removeListener; + S.prototype.removeAllListeners = function(t) { + var r, n, i; + if (n = this._events, n === undefined) + return this; + if (n.removeListener === undefined) + return arguments.length === 0 ? (this._events = Object.create(null), this._eventsCount = 0) : n[t] !== undefined && (--this._eventsCount === 0 ? this._events = Object.create(null) : delete n[t]), this; + if (arguments.length === 0) { + var o = Object.keys(n), l; + for (i = 0;i < o.length; ++i) + l = o[i], l !== "removeListener" && this.removeAllListeners(l); + return this.removeAllListeners("removeListener"), this._events = Object.create(null), this._eventsCount = 0, this; + } + if (r = n[t], typeof r == "function") + this.removeListener(t, r); + else if (r !== undefined) + for (i = r.length - 1;i >= 0; i--) + this.removeListener(t, r[i]); + return this; + }; + function Ti(e, t, r) { + var n = e._events; + if (n === undefined) + return []; + var i = n[t]; + return i === undefined ? [] : typeof i == "function" ? r ? [i.listener || i] : [i] : r ? rs(i) : Li(i, i.length); + } + S.prototype.listeners = function(t) { + return Ti(this, t, true); + }; + S.prototype.rawListeners = function(t) { + return Ti(this, t, false); + }; + S.listenerCount = function(e, t) { + return typeof e.listenerCount == "function" ? e.listenerCount(t) : Bi.call(e, t); + }; + S.prototype.listenerCount = Bi; + function Bi(e) { + var t = this._events; + if (t !== undefined) { + var r = t[e]; + if (typeof r == "function") + return 1; + if (r !== undefined) + return r.length; + } + return 0; + } + S.prototype.eventNames = function() { + return this._eventsCount > 0 ? gt(this._events) : []; + }; + function Li(e, t) { + for (var r = new Array(t), n = 0;n < t; ++n) + r[n] = e[n]; + return r; + } + function ts(e, t) { + for (;t + 1 < e.length; t++) + e[t] = e[t + 1]; + e.pop(); + } + function rs(e) { + for (var t = new Array(e.length), r = 0;r < t.length; ++r) + t[r] = e[r].listener || e[r]; + return t; + } + function ns(e, t) { + return new Promise(function(r, n) { + function i(l) { + e.removeListener(t, o), n(l); + } + function o() { + typeof e.removeListener == "function" && e.removeListener("error", i), r([].slice.call(arguments)); + } + Ni(e, t, o, { once: true }), t !== "error" && is(e, i, { once: true }); + }); + } + function is(e, t, r) { + typeof e.on == "function" && Ni(e, "error", t, r); + } + function Ni(e, t, r, n) { + if (typeof e.on == "function") + n.once ? e.once(t, r) : e.on(t, r); + else if (typeof e.addEventListener == "function") + e.addEventListener(t, function i(o) { + n.once && e.removeEventListener(t, i), r(o); + }); + else + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof e); + } + }); + xt = E((rd, Mi) => { + var { ArrayIsArray: os, ObjectSetPrototypeOf: Fi } = I(), { EventEmitter: St } = Et(); + function mt(e) { + St.call(this, e); + } + Fi(mt.prototype, St.prototype); + Fi(mt, St); + mt.prototype.pipe = function(e, t) { + let r = this; + function n(d) { + e.writable && e.write(d) === false && r.pause && r.pause(); + } + r.on("data", n); + function i() { + r.readable && r.resume && r.resume(); + } + e.on("drain", i), !e._isStdio && (!t || t.end !== false) && (r.on("end", l), r.on("close", u)); + let o = false; + function l() { + o || (o = true, e.end()); + } + function u() { + o || (o = true, typeof e.destroy == "function" && e.destroy()); + } + function f(d) { + s(), St.listenerCount(this, "error") === 0 && this.emit("error", d); + } + yr(r, "error", f), yr(e, "error", f); + function s() { + r.removeListener("data", n), e.removeListener("drain", i), r.removeListener("end", l), r.removeListener("close", u), r.removeListener("error", f), e.removeListener("error", f), r.removeListener("end", s), r.removeListener("close", s), e.removeListener("close", s); + } + return r.on("end", s), r.on("close", s), e.on("close", s), e.emit("pipe", r), e; + }; + function yr(e, t, r) { + if (typeof e.prependListener == "function") + return e.prependListener(t, r); + !e._events || !e._events[t] ? e.on(t, r) : os(e._events[t]) ? e._events[t].unshift(r) : e._events[t] = [r, e._events[t]]; + } + Mi.exports = { Stream: mt, prependListener: yr }; + }); + At = E((nd, Rt) => { + var { AbortError: ls, codes: us } = C(), fs = ce(), { ERR_INVALID_ARG_TYPE: Ci } = us, ss = (e, t) => { + if (typeof e != "object" || !("aborted" in e)) + throw new Ci(t, "AbortSignal", e); + }; + function as(e) { + return !!(e && typeof e.pipe == "function"); + } + Rt.exports.addAbortSignal = function(t, r) { + if (ss(t, "signal"), !as(r)) + throw new Ci("stream", "stream.Stream", r); + return Rt.exports.addAbortSignalNoValidate(t, r); + }; + Rt.exports.addAbortSignalNoValidate = function(e, t) { + if (typeof e != "object" || !("aborted" in e)) + return t; + let r = () => { + t.destroy(new ls(undefined, { cause: e.reason })); + }; + return e.aborted ? r() : (e.addEventListener("abort", r), fs(t, () => e.removeEventListener("abort", r))), t; + }; + }); + Pi = E((od, Di) => { + var { StringPrototypeSlice: Oi, SymbolIterator: cs, TypedArrayPrototypeSet: It, Uint8Array: ds } = I(), { Buffer: wr } = te(), { inspect: hs } = V(); + Di.exports = class { + constructor() { + this.head = null, this.tail = null, this.length = 0; + } + push(t) { + let r = { data: t, next: null }; + this.length > 0 ? this.tail.next = r : this.head = r, this.tail = r, ++this.length; + } + unshift(t) { + let r = { data: t, next: this.head }; + this.length === 0 && (this.tail = r), this.head = r, ++this.length; + } + shift() { + if (this.length === 0) + return; + let t = this.head.data; + return this.length === 1 ? this.head = this.tail = null : this.head = this.head.next, --this.length, t; + } + clear() { + this.head = this.tail = null, this.length = 0; + } + join(t) { + if (this.length === 0) + return ""; + let r = this.head, n = "" + r.data; + for (;(r = r.next) !== null; ) + n += t + r.data; + return n; + } + concat(t) { + if (this.length === 0) + return wr.alloc(0); + let r = wr.allocUnsafe(t >>> 0), n = this.head, i = 0; + for (;n; ) + It(r, n.data, i), i += n.data.length, n = n.next; + return r; + } + consume(t, r) { + let n = this.head.data; + if (t < n.length) { + let i = n.slice(0, t); + return this.head.data = n.slice(t), i; + } + return t === n.length ? this.shift() : r ? this._getString(t) : this._getBuffer(t); + } + first() { + return this.head.data; + } + *[cs]() { + for (let t = this.head;t; t = t.next) + yield t.data; + } + _getString(t) { + let r = "", n = this.head, i = 0; + do { + let o = n.data; + if (t > o.length) + r += o, t -= o.length; + else { + t === o.length ? (r += o, ++i, n.next ? this.head = n.next : this.head = this.tail = null) : (r += Oi(o, 0, t), this.head = n, n.data = Oi(o, t)); + break; + } + ++i; + } while ((n = n.next) !== null); + return this.length -= i, r; + } + _getBuffer(t) { + let r = wr.allocUnsafe(t), n = t, i = this.head, o = 0; + do { + let l = i.data; + if (t > l.length) + It(r, l, n - t), t -= l.length; + else { + t === l.length ? (It(r, l, n - t), ++o, i.next ? this.head = i.next : this.head = this.tail = null) : (It(r, new ds(l.buffer, l.byteOffset, t), n - t), this.head = i, i.data = l.slice(t)); + break; + } + ++o; + } while ((i = i.next) !== null); + return this.length -= o, r; + } + [Symbol.for("nodejs.util.inspect.custom")](t, r) { + return hs(this, { ...r, depth: 0, customInspect: false }); + } + }; + }); + Tt = E((ld, Ui) => { + var { MathFloor: ps, NumberIsInteger: ys } = I(), { ERR_INVALID_ARG_VALUE: ws } = C().codes; + function bs(e, t, r) { + return e.highWaterMark != null ? e.highWaterMark : t ? e[r] : null; + } + function ki(e) { + return e ? 16 : 16 * 1024; + } + function gs(e, t, r, n) { + let i = bs(t, n, r); + if (i != null) { + if (!ys(i) || i < 0) { + let o = n ? `options.${r}` : "options.highWaterMark"; + throw new ws(o, i); + } + return ps(i); + } + return ki(e.objectMode); + } + Ui.exports = { getHighWaterMark: gs, getDefaultHighWaterMark: ki }; + }); + Wi = E((br, qi) => { + var Bt = te(), X = Bt.Buffer; + function vi(e, t) { + for (var r in e) + t[r] = e[r]; + } + X.from && X.alloc && X.allocUnsafe && X.allocUnsafeSlow ? qi.exports = Bt : (vi(Bt, br), br.Buffer = me); + function me(e, t, r) { + return X(e, t, r); + } + me.prototype = Object.create(X.prototype); + vi(X, me); + me.from = function(e, t, r) { + if (typeof e == "number") + throw new TypeError("Argument must not be a number"); + return X(e, t, r); + }; + me.alloc = function(e, t, r) { + if (typeof e != "number") + throw new TypeError("Argument must be a number"); + var n = X(e); + return t !== undefined ? typeof r == "string" ? n.fill(t, r) : n.fill(t) : n.fill(0), n; + }; + me.allocUnsafe = function(e) { + if (typeof e != "number") + throw new TypeError("Argument must be a number"); + return X(e); + }; + me.allocUnsafeSlow = function(e) { + if (typeof e != "number") + throw new TypeError("Argument must be a number"); + return Bt.SlowBuffer(e); + }; + }); + Gi = E((ji) => { + var _r = Wi().Buffer, $i = _r.isEncoding || function(e) { + switch (e = "" + e, e && e.toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + case "raw": + return true; + default: + return false; + } + }; + function _s(e) { + if (!e) + return "utf8"; + for (var t;; ) + switch (e) { + case "utf8": + case "utf-8": + return "utf8"; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return "utf16le"; + case "latin1": + case "binary": + return "latin1"; + case "base64": + case "ascii": + case "hex": + return e; + default: + if (t) + return; + e = ("" + e).toLowerCase(), t = true; + } + } + function Es(e) { + var t = _s(e); + if (typeof t != "string" && (_r.isEncoding === $i || !$i(e))) + throw new Error("Unknown encoding: " + e); + return t || e; + } + ji.StringDecoder = Ye; + function Ye(e) { + this.encoding = Es(e); + var t; + switch (this.encoding) { + case "utf16le": + this.text = Is, this.end = Ts, t = 4; + break; + case "utf8": + this.fillLast = xs, t = 4; + break; + case "base64": + this.text = Bs, this.end = Ls, t = 3; + break; + default: + this.write = Ns, this.end = Fs; + return; + } + this.lastNeed = 0, this.lastTotal = 0, this.lastChar = _r.allocUnsafe(t); + } + Ye.prototype.write = function(e) { + if (e.length === 0) + return ""; + var t, r; + if (this.lastNeed) { + if (t = this.fillLast(e), t === undefined) + return ""; + r = this.lastNeed, this.lastNeed = 0; + } else + r = 0; + return r < e.length ? t ? t + this.text(e, r) : this.text(e, r) : t || ""; + }; + Ye.prototype.end = As; + Ye.prototype.text = Rs; + Ye.prototype.fillLast = function(e) { + if (this.lastNeed <= e.length) + return e.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal); + e.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, e.length), this.lastNeed -= e.length; + }; + function gr(e) { + return e <= 127 ? 0 : e >> 5 === 6 ? 2 : e >> 4 === 14 ? 3 : e >> 3 === 30 ? 4 : e >> 6 === 2 ? -1 : -2; + } + function Ss(e, t, r) { + var n = t.length - 1; + if (n < r) + return 0; + var i = gr(t[n]); + return i >= 0 ? (i > 0 && (e.lastNeed = i - 1), i) : --n < r || i === -2 ? 0 : (i = gr(t[n]), i >= 0 ? (i > 0 && (e.lastNeed = i - 2), i) : --n < r || i === -2 ? 0 : (i = gr(t[n]), i >= 0 ? (i > 0 && (i === 2 ? i = 0 : e.lastNeed = i - 3), i) : 0)); + } + function ms(e, t, r) { + if ((t[0] & 192) !== 128) + return e.lastNeed = 0, "�"; + if (e.lastNeed > 1 && t.length > 1) { + if ((t[1] & 192) !== 128) + return e.lastNeed = 1, "�"; + if (e.lastNeed > 2 && t.length > 2 && (t[2] & 192) !== 128) + return e.lastNeed = 2, "�"; + } + } + function xs(e) { + var t = this.lastTotal - this.lastNeed, r = ms(this, e, t); + if (r !== undefined) + return r; + if (this.lastNeed <= e.length) + return e.copy(this.lastChar, t, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal); + e.copy(this.lastChar, t, 0, e.length), this.lastNeed -= e.length; + } + function Rs(e, t) { + var r = Ss(this, e, t); + if (!this.lastNeed) + return e.toString("utf8", t); + this.lastTotal = r; + var n = e.length - (r - this.lastNeed); + return e.copy(this.lastChar, 0, n), e.toString("utf8", t, n); + } + function As(e) { + var t = e && e.length ? this.write(e) : ""; + return this.lastNeed ? t + "�" : t; + } + function Is(e, t) { + if ((e.length - t) % 2 === 0) { + var r = e.toString("utf16le", t); + if (r) { + var n = r.charCodeAt(r.length - 1); + if (n >= 55296 && n <= 56319) + return this.lastNeed = 2, this.lastTotal = 4, this.lastChar[0] = e[e.length - 2], this.lastChar[1] = e[e.length - 1], r.slice(0, -1); + } + return r; + } + return this.lastNeed = 1, this.lastTotal = 2, this.lastChar[0] = e[e.length - 1], e.toString("utf16le", t, e.length - 1); + } + function Ts(e) { + var t = e && e.length ? this.write(e) : ""; + if (this.lastNeed) { + var r = this.lastTotal - this.lastNeed; + return t + this.lastChar.toString("utf16le", 0, r); + } + return t; + } + function Bs(e, t) { + var r = (e.length - t) % 3; + return r === 0 ? e.toString("base64", t) : (this.lastNeed = 3 - r, this.lastTotal = 3, r === 1 ? this.lastChar[0] = e[e.length - 1] : (this.lastChar[0] = e[e.length - 2], this.lastChar[1] = e[e.length - 1]), e.toString("base64", t, e.length - r)); + } + function Ls(e) { + var t = e && e.length ? this.write(e) : ""; + return this.lastNeed ? t + this.lastChar.toString("base64", 0, 3 - this.lastNeed) : t; + } + function Ns(e) { + return e.toString(this.encoding); + } + function Fs(e) { + return e && e.length ? this.write(e) : ""; + } + }); + Er = E((fd, Ki) => { + var Hi = (se(), pe(k)), { PromisePrototypeThen: Ms, SymbolAsyncIterator: Vi, SymbolIterator: Yi } = I(), { Buffer: Cs } = te(), { ERR_INVALID_ARG_TYPE: Os, ERR_STREAM_NULL_VALUES: Ds } = C().codes; + function Ps(e, t, r) { + let n; + if (typeof t == "string" || t instanceof Cs) + return new e({ objectMode: true, ...r, read() { + this.push(t), this.push(null); + } }); + let i; + if (t && t[Vi]) + i = true, n = t[Vi](); + else if (t && t[Yi]) + i = false, n = t[Yi](); + else + throw new Os("iterable", ["Iterable"], t); + let o = new e({ objectMode: true, highWaterMark: 1, ...r }), l = false; + o._read = function() { + l || (l = true, f()); + }, o._destroy = function(s, d) { + Ms(u(s), () => Hi.nextTick(d, s), (c) => Hi.nextTick(d, c || s)); + }; + async function u(s) { + let d = s != null, c = typeof n.throw == "function"; + if (d && c) { + let { value: y, done: h } = await n.throw(s); + if (await y, h) + return; + } + if (typeof n.return == "function") { + let { value: y } = await n.return(); + await y; + } + } + async function f() { + for (;; ) { + try { + let { value: s, done: d } = i ? await n.next() : n.next(); + if (d) + o.push(null); + else { + let c = s && typeof s.then == "function" ? await s : s; + if (c === null) + throw l = false, new Ds; + if (o.push(c)) + continue; + l = false; + } + } catch (s) { + o.destroy(s); + } + break; + } + } + return o; + } + Ki.exports = Ps; + }); + Ke = E((sd, uo) => { + var $ = (se(), pe(k)), { ArrayPrototypeIndexOf: ks, NumberIsInteger: Us, NumberIsNaN: vs, NumberParseInt: qs, ObjectDefineProperties: Ji, ObjectKeys: Ws, ObjectSetPrototypeOf: Qi, Promise: $s, SafeSet: js, SymbolAsyncIterator: Gs, Symbol: Hs } = I(); + uo.exports = g; + g.ReadableState = Ir; + var { EventEmitter: Vs } = Et(), { Stream: he, prependListener: Ys } = xt(), { Buffer: Sr } = te(), { addAbortSignal: Ks } = At(), zs = ce(), _2 = V().debuglog("stream", (e) => { + _2 = e; + }), Xs = Pi(), Ue = Se(), { getHighWaterMark: Js, getDefaultHighWaterMark: Qs } = Tt(), { aggregateTwoErrors: zi, codes: { ERR_INVALID_ARG_TYPE: Zs, ERR_METHOD_NOT_IMPLEMENTED: ea, ERR_OUT_OF_RANGE: ta, ERR_STREAM_PUSH_AFTER_EOF: ra, ERR_STREAM_UNSHIFT_AFTER_END_EVENT: na } } = C(), { validateObject: ia } = He(), xe = Hs("kPaused"), { StringDecoder: Zi } = Gi(), oa = Er(); + Qi(g.prototype, he.prototype); + Qi(g, he); + var mr = () => { + }, { errorOrDestroy: ke } = Ue; + function Ir(e, t, r) { + typeof r != "boolean" && (r = t instanceof J()), this.objectMode = !!(e && e.objectMode), r && (this.objectMode = this.objectMode || !!(e && e.readableObjectMode)), this.highWaterMark = e ? Js(this, e, "readableHighWaterMark", r) : Qs(false), this.buffer = new Xs, this.length = 0, this.pipes = [], this.flowing = null, this.ended = false, this.endEmitted = false, this.reading = false, this.constructed = true, this.sync = true, this.needReadable = false, this.emittedReadable = false, this.readableListening = false, this.resumeScheduled = false, this[xe] = null, this.errorEmitted = false, this.emitClose = !e || e.emitClose !== false, this.autoDestroy = !e || e.autoDestroy !== false, this.destroyed = false, this.errored = null, this.closed = false, this.closeEmitted = false, this.defaultEncoding = e && e.defaultEncoding || "utf8", this.awaitDrainWriters = null, this.multiAwaitDrain = false, this.readingMore = false, this.dataEmitted = false, this.decoder = null, this.encoding = null, e && e.encoding && (this.decoder = new Zi(e.encoding), this.encoding = e.encoding); + } + function g(e) { + if (!(this instanceof g)) + return new g(e); + let t = this instanceof J(); + this._readableState = new Ir(e, this, t), e && (typeof e.read == "function" && (this._read = e.read), typeof e.destroy == "function" && (this._destroy = e.destroy), typeof e.construct == "function" && (this._construct = e.construct), e.signal && !t && Ks(e.signal, this)), he.call(this, e), Ue.construct(this, () => { + this._readableState.needReadable && Lt(this, this._readableState); + }); + } + g.prototype.destroy = Ue.destroy; + g.prototype._undestroy = Ue.undestroy; + g.prototype._destroy = function(e, t) { + t(e); + }; + g.prototype[Vs.captureRejectionSymbol] = function(e) { + this.destroy(e); + }; + g.prototype.push = function(e, t) { + return eo(this, e, t, false); + }; + g.prototype.unshift = function(e, t) { + return eo(this, e, t, true); + }; + function eo(e, t, r, n) { + _2("readableAddChunk", t); + let i = e._readableState, o; + if (i.objectMode || (typeof t == "string" ? (r = r || i.defaultEncoding, i.encoding !== r && (n && i.encoding ? t = Sr.from(t, r).toString(i.encoding) : (t = Sr.from(t, r), r = ""))) : t instanceof Sr ? r = "" : he._isUint8Array(t) ? (t = he._uint8ArrayToBuffer(t), r = "") : t != null && (o = new Zs("chunk", ["string", "Buffer", "Uint8Array"], t))), o) + ke(e, o); + else if (t === null) + i.reading = false, fa(e, i); + else if (i.objectMode || t && t.length > 0) + if (n) + if (i.endEmitted) + ke(e, new na); + else { + if (i.destroyed || i.errored) + return false; + xr(e, i, t, true); + } + else if (i.ended) + ke(e, new ra); + else { + if (i.destroyed || i.errored) + return false; + i.reading = false, i.decoder && !r ? (t = i.decoder.write(t), i.objectMode || t.length !== 0 ? xr(e, i, t, false) : Lt(e, i)) : xr(e, i, t, false); + } + else + n || (i.reading = false, Lt(e, i)); + return !i.ended && (i.length < i.highWaterMark || i.length === 0); + } + function xr(e, t, r, n) { + t.flowing && t.length === 0 && !t.sync && e.listenerCount("data") > 0 ? (t.multiAwaitDrain ? t.awaitDrainWriters.clear() : t.awaitDrainWriters = null, t.dataEmitted = true, e.emit("data", r)) : (t.length += t.objectMode ? 1 : r.length, n ? t.buffer.unshift(r) : t.buffer.push(r), t.needReadable && Nt(e)), Lt(e, t); + } + g.prototype.isPaused = function() { + let e = this._readableState; + return e[xe] === true || e.flowing === false; + }; + g.prototype.setEncoding = function(e) { + let t = new Zi(e); + this._readableState.decoder = t, this._readableState.encoding = this._readableState.decoder.encoding; + let r = this._readableState.buffer, n = ""; + for (let i of r) + n += t.write(i); + return r.clear(), n !== "" && r.push(n), this._readableState.length = n.length, this; + }; + var la = 1073741824; + function ua(e) { + if (e > la) + throw new ta("size", "<= 1GiB", e); + return e--, e |= e >>> 1, e |= e >>> 2, e |= e >>> 4, e |= e >>> 8, e |= e >>> 16, e++, e; + } + function Xi(e, t) { + return e <= 0 || t.length === 0 && t.ended ? 0 : t.objectMode ? 1 : vs(e) ? t.flowing && t.length ? t.buffer.first().length : t.length : e <= t.length ? e : t.ended ? t.length : 0; + } + g.prototype.read = function(e) { + _2("read", e), e === undefined ? e = NaN : Us(e) || (e = qs(e, 10)); + let t = this._readableState, r = e; + if (e > t.highWaterMark && (t.highWaterMark = ua(e)), e !== 0 && (t.emittedReadable = false), e === 0 && t.needReadable && ((t.highWaterMark !== 0 ? t.length >= t.highWaterMark : t.length > 0) || t.ended)) + return _2("read: emitReadable", t.length, t.ended), t.length === 0 && t.ended ? Rr(this) : Nt(this), null; + if (e = Xi(e, t), e === 0 && t.ended) + return t.length === 0 && Rr(this), null; + let n = t.needReadable; + if (_2("need readable", n), (t.length === 0 || t.length - e < t.highWaterMark) && (n = true, _2("length less than watermark", n)), t.ended || t.reading || t.destroyed || t.errored || !t.constructed) + n = false, _2("reading, ended or constructing", n); + else if (n) { + _2("do read"), t.reading = true, t.sync = true, t.length === 0 && (t.needReadable = true); + try { + this._read(t.highWaterMark); + } catch (o) { + ke(this, o); + } + t.sync = false, t.reading || (e = Xi(r, t)); + } + let i; + return e > 0 ? i = oo(e, t) : i = null, i === null ? (t.needReadable = t.length <= t.highWaterMark, e = 0) : (t.length -= e, t.multiAwaitDrain ? t.awaitDrainWriters.clear() : t.awaitDrainWriters = null), t.length === 0 && (t.ended || (t.needReadable = true), r !== e && t.ended && Rr(this)), i !== null && !t.errorEmitted && !t.closeEmitted && (t.dataEmitted = true, this.emit("data", i)), i; + }; + function fa(e, t) { + if (_2("onEofChunk"), !t.ended) { + if (t.decoder) { + let r = t.decoder.end(); + r && r.length && (t.buffer.push(r), t.length += t.objectMode ? 1 : r.length); + } + t.ended = true, t.sync ? Nt(e) : (t.needReadable = false, t.emittedReadable = true, to(e)); + } + } + function Nt(e) { + let t = e._readableState; + _2("emitReadable", t.needReadable, t.emittedReadable), t.needReadable = false, t.emittedReadable || (_2("emitReadable", t.flowing), t.emittedReadable = true, $.nextTick(to, e)); + } + function to(e) { + let t = e._readableState; + _2("emitReadable_", t.destroyed, t.length, t.ended), !t.destroyed && !t.errored && (t.length || t.ended) && (e.emit("readable"), t.emittedReadable = false), t.needReadable = !t.flowing && !t.ended && t.length <= t.highWaterMark, no(e); + } + function Lt(e, t) { + !t.readingMore && t.constructed && (t.readingMore = true, $.nextTick(sa, e, t)); + } + function sa(e, t) { + for (;!t.reading && !t.ended && (t.length < t.highWaterMark || t.flowing && t.length === 0); ) { + let r = t.length; + if (_2("maybeReadMore read 0"), e.read(0), r === t.length) + break; + } + t.readingMore = false; + } + g.prototype._read = function(e) { + throw new ea("_read()"); + }; + g.prototype.pipe = function(e, t) { + let r = this, n = this._readableState; + n.pipes.length === 1 && (n.multiAwaitDrain || (n.multiAwaitDrain = true, n.awaitDrainWriters = new js(n.awaitDrainWriters ? [n.awaitDrainWriters] : []))), n.pipes.push(e), _2("pipe count=%d opts=%j", n.pipes.length, t); + let o = (!t || t.end !== false) && e !== $.stdout && e !== $.stderr ? u : v; + n.endEmitted ? $.nextTick(o) : r.once("end", o), e.on("unpipe", l); + function l(w, b) { + _2("onunpipe"), w === r && b && b.hasUnpiped === false && (b.hasUnpiped = true, d()); + } + function u() { + _2("onend"), e.end(); + } + let f, s = false; + function d() { + _2("cleanup"), e.removeListener("close", p), e.removeListener("finish", B), f && e.removeListener("drain", f), e.removeListener("error", h), e.removeListener("unpipe", l), r.removeListener("end", u), r.removeListener("end", v), r.removeListener("data", y), s = true, f && n.awaitDrainWriters && (!e._writableState || e._writableState.needDrain) && f(); + } + function c() { + s || (n.pipes.length === 1 && n.pipes[0] === e ? (_2("false write response, pause", 0), n.awaitDrainWriters = e, n.multiAwaitDrain = false) : n.pipes.length > 1 && n.pipes.includes(e) && (_2("false write response, pause", n.awaitDrainWriters.size), n.awaitDrainWriters.add(e)), r.pause()), f || (f = aa(r, e), e.on("drain", f)); + } + r.on("data", y); + function y(w) { + _2("ondata"); + let b = e.write(w); + _2("dest.write", b), b === false && c(); + } + function h(w) { + if (_2("onerror", w), v(), e.removeListener("error", h), e.listenerCount("error") === 0) { + let b = e._writableState || e._readableState; + b && !b.errorEmitted ? ke(e, w) : e.emit("error", w); + } + } + Ys(e, "error", h); + function p() { + e.removeListener("finish", B), v(); + } + e.once("close", p); + function B() { + _2("onfinish"), e.removeListener("close", p), v(); + } + e.once("finish", B); + function v() { + _2("unpipe"), r.unpipe(e); + } + return e.emit("pipe", r), e.writableNeedDrain === true ? n.flowing && c() : n.flowing || (_2("pipe resume"), r.resume()), e; + }; + function aa(e, t) { + return function() { + let n = e._readableState; + n.awaitDrainWriters === t ? (_2("pipeOnDrain", 1), n.awaitDrainWriters = null) : n.multiAwaitDrain && (_2("pipeOnDrain", n.awaitDrainWriters.size), n.awaitDrainWriters.delete(t)), (!n.awaitDrainWriters || n.awaitDrainWriters.size === 0) && e.listenerCount("data") && e.resume(); + }; + } + g.prototype.unpipe = function(e) { + let t = this._readableState, r = { hasUnpiped: false }; + if (t.pipes.length === 0) + return this; + if (!e) { + let i = t.pipes; + t.pipes = [], this.pause(); + for (let o = 0;o < i.length; o++) + i[o].emit("unpipe", this, { hasUnpiped: false }); + return this; + } + let n = ks(t.pipes, e); + return n === -1 ? this : (t.pipes.splice(n, 1), t.pipes.length === 0 && this.pause(), e.emit("unpipe", this, r), this); + }; + g.prototype.on = function(e, t) { + let r = he.prototype.on.call(this, e, t), n = this._readableState; + return e === "data" ? (n.readableListening = this.listenerCount("readable") > 0, n.flowing !== false && this.resume()) : e === "readable" && !n.endEmitted && !n.readableListening && (n.readableListening = n.needReadable = true, n.flowing = false, n.emittedReadable = false, _2("on readable", n.length, n.reading), n.length ? Nt(this) : n.reading || $.nextTick(ca, this)), r; + }; + g.prototype.addListener = g.prototype.on; + g.prototype.removeListener = function(e, t) { + let r = he.prototype.removeListener.call(this, e, t); + return e === "readable" && $.nextTick(ro, this), r; + }; + g.prototype.off = g.prototype.removeListener; + g.prototype.removeAllListeners = function(e) { + let t = he.prototype.removeAllListeners.apply(this, arguments); + return (e === "readable" || e === undefined) && $.nextTick(ro, this), t; + }; + function ro(e) { + let t = e._readableState; + t.readableListening = e.listenerCount("readable") > 0, t.resumeScheduled && t[xe] === false ? t.flowing = true : e.listenerCount("data") > 0 ? e.resume() : t.readableListening || (t.flowing = null); + } + function ca(e) { + _2("readable nexttick read 0"), e.read(0); + } + g.prototype.resume = function() { + let e = this._readableState; + return e.flowing || (_2("resume"), e.flowing = !e.readableListening, da(this, e)), e[xe] = false, this; + }; + function da(e, t) { + t.resumeScheduled || (t.resumeScheduled = true, $.nextTick(ha, e, t)); + } + function ha(e, t) { + _2("resume", t.reading), t.reading || e.read(0), t.resumeScheduled = false, e.emit("resume"), no(e), t.flowing && !t.reading && e.read(0); + } + g.prototype.pause = function() { + return _2("call pause flowing=%j", this._readableState.flowing), this._readableState.flowing !== false && (_2("pause"), this._readableState.flowing = false, this.emit("pause")), this._readableState[xe] = true, this; + }; + function no(e) { + let t = e._readableState; + for (_2("flow", t.flowing);t.flowing && e.read() !== null; ) + ; + } + g.prototype.wrap = function(e) { + let t = false; + e.on("data", (n) => { + !this.push(n) && e.pause && (t = true, e.pause()); + }), e.on("end", () => { + this.push(null); + }), e.on("error", (n) => { + ke(this, n); + }), e.on("close", () => { + this.destroy(); + }), e.on("destroy", () => { + this.destroy(); + }), this._read = () => { + t && e.resume && (t = false, e.resume()); + }; + let r = Ws(e); + for (let n = 1;n < r.length; n++) { + let i = r[n]; + this[i] === undefined && typeof e[i] == "function" && (this[i] = e[i].bind(e)); + } + return this; + }; + g.prototype[Gs] = function() { + return io(this); + }; + g.prototype.iterator = function(e) { + return e !== undefined && ia(e, "options"), io(this, e); + }; + function io(e, t) { + typeof e.read != "function" && (e = g.wrap(e, { objectMode: true })); + let r = pa(e, t); + return r.stream = e, r; + } + async function* pa(e, t) { + let r = mr; + function n(l) { + this === e ? (r(), r = mr) : r = l; + } + e.on("readable", n); + let i, o = zs(e, { writable: false }, (l) => { + i = l ? zi(i, l) : null, r(), r = mr; + }); + try { + for (;; ) { + let l = e.destroyed ? null : e.read(); + if (l !== null) + yield l; + else { + if (i) + throw i; + if (i === null) + return; + await new $s(n); + } + } + } catch (l) { + throw i = zi(i, l), i; + } finally { + (i || t?.destroyOnReturn !== false) && (i === undefined || e._readableState.autoDestroy) ? Ue.destroyer(e, null) : (e.off("readable", n), o()); + } + } + Ji(g.prototype, { readable: { __proto__: null, get() { + let e = this._readableState; + return !!e && e.readable !== false && !e.destroyed && !e.errorEmitted && !e.endEmitted; + }, set(e) { + this._readableState && (this._readableState.readable = !!e); + } }, readableDidRead: { __proto__: null, enumerable: false, get: function() { + return this._readableState.dataEmitted; + } }, readableAborted: { __proto__: null, enumerable: false, get: function() { + return !!(this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted); + } }, readableHighWaterMark: { __proto__: null, enumerable: false, get: function() { + return this._readableState.highWaterMark; + } }, readableBuffer: { __proto__: null, enumerable: false, get: function() { + return this._readableState && this._readableState.buffer; + } }, readableFlowing: { __proto__: null, enumerable: false, get: function() { + return this._readableState.flowing; + }, set: function(e) { + this._readableState && (this._readableState.flowing = e); + } }, readableLength: { __proto__: null, enumerable: false, get() { + return this._readableState.length; + } }, readableObjectMode: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.objectMode : false; + } }, readableEncoding: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.encoding : null; + } }, errored: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.errored : null; + } }, closed: { __proto__: null, get() { + return this._readableState ? this._readableState.closed : false; + } }, destroyed: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.destroyed : false; + }, set(e) { + !this._readableState || (this._readableState.destroyed = e); + } }, readableEnded: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.endEmitted : false; + } } }); + Ji(Ir.prototype, { pipesCount: { __proto__: null, get() { + return this.pipes.length; + } }, paused: { __proto__: null, get() { + return this[xe] !== false; + }, set(e) { + this[xe] = !!e; + } } }); + g._fromList = oo; + function oo(e, t) { + if (t.length === 0) + return null; + let r; + return t.objectMode ? r = t.buffer.shift() : !e || e >= t.length ? (t.decoder ? r = t.buffer.join("") : t.buffer.length === 1 ? r = t.buffer.first() : r = t.buffer.concat(t.length), t.buffer.clear()) : r = t.buffer.consume(e, t.decoder), r; + } + function Rr(e) { + let t = e._readableState; + _2("endReadable", t.endEmitted), t.endEmitted || (t.ended = true, $.nextTick(ya, t, e)); + } + function ya(e, t) { + if (_2("endReadableNT", e.endEmitted, e.length), !e.errored && !e.closeEmitted && !e.endEmitted && e.length === 0) { + if (e.endEmitted = true, t.emit("end"), t.writable && t.allowHalfOpen === false) + $.nextTick(wa, t); + else if (e.autoDestroy) { + let r = t._writableState; + (!r || r.autoDestroy && (r.finished || r.writable === false)) && t.destroy(); + } + } + } + function wa(e) { + e.writable && !e.writableEnded && !e.destroyed && e.end(); + } + g.from = function(e, t) { + return oa(g, e, t); + }; + var Ar; + function lo() { + return Ar === undefined && (Ar = {}), Ar; + } + g.fromWeb = function(e, t) { + return lo().newStreamReadableFromReadableStream(e, t); + }; + g.toWeb = function(e, t) { + return lo().newReadableStreamFromStreamReadable(e, t); + }; + g.wrap = function(e, t) { + var r, n; + return new g({ objectMode: (r = (n = e.readableObjectMode) !== null && n !== undefined ? n : e.objectMode) !== null && r !== undefined ? r : true, ...t, destroy(i, o) { + Ue.destroyer(e, i), o(i); + } }).wrap(e); + }; + }); + Cr = E((ad, Eo) => { + var Re = (se(), pe(k)), { ArrayPrototypeSlice: ao, Error: ba, FunctionPrototypeSymbolHasInstance: co, ObjectDefineProperty: ho, ObjectDefineProperties: ga, ObjectSetPrototypeOf: po, StringPrototypeToLowerCase: _a, Symbol: Ea, SymbolHasInstance: Sa } = I(); + Eo.exports = m; + m.WritableState = Je; + var { EventEmitter: ma } = Et(), ze = xt().Stream, { Buffer: Ft } = te(), Ot = Se(), { addAbortSignal: xa } = At(), { getHighWaterMark: Ra, getDefaultHighWaterMark: Aa } = Tt(), { ERR_INVALID_ARG_TYPE: Ia, ERR_METHOD_NOT_IMPLEMENTED: Ta, ERR_MULTIPLE_CALLBACK: yo, ERR_STREAM_CANNOT_PIPE: Ba, ERR_STREAM_DESTROYED: Xe, ERR_STREAM_ALREADY_FINISHED: La, ERR_STREAM_NULL_VALUES: Na, ERR_STREAM_WRITE_AFTER_END: Fa, ERR_UNKNOWN_ENCODING: wo } = C().codes, { errorOrDestroy: ve } = Ot; + po(m.prototype, ze.prototype); + po(m, ze); + function Lr() { + } + var qe = Ea("kOnFinished"); + function Je(e, t, r) { + typeof r != "boolean" && (r = t instanceof J()), this.objectMode = !!(e && e.objectMode), r && (this.objectMode = this.objectMode || !!(e && e.writableObjectMode)), this.highWaterMark = e ? Ra(this, e, "writableHighWaterMark", r) : Aa(false), this.finalCalled = false, this.needDrain = false, this.ending = false, this.ended = false, this.finished = false, this.destroyed = false; + let n = !!(e && e.decodeStrings === false); + this.decodeStrings = !n, this.defaultEncoding = e && e.defaultEncoding || "utf8", this.length = 0, this.writing = false, this.corked = 0, this.sync = true, this.bufferProcessing = false, this.onwrite = Ca.bind(undefined, t), this.writecb = null, this.writelen = 0, this.afterWriteTickInfo = null, Ct(this), this.pendingcb = 0, this.constructed = true, this.prefinished = false, this.errorEmitted = false, this.emitClose = !e || e.emitClose !== false, this.autoDestroy = !e || e.autoDestroy !== false, this.errored = null, this.closed = false, this.closeEmitted = false, this[qe] = []; + } + function Ct(e) { + e.buffered = [], e.bufferedIndex = 0, e.allBuffers = true, e.allNoop = true; + } + Je.prototype.getBuffer = function() { + return ao(this.buffered, this.bufferedIndex); + }; + ho(Je.prototype, "bufferedRequestCount", { __proto__: null, get() { + return this.buffered.length - this.bufferedIndex; + } }); + function m(e) { + let t = this instanceof J(); + if (!t && !co(m, this)) + return new m(e); + this._writableState = new Je(e, this, t), e && (typeof e.write == "function" && (this._write = e.write), typeof e.writev == "function" && (this._writev = e.writev), typeof e.destroy == "function" && (this._destroy = e.destroy), typeof e.final == "function" && (this._final = e.final), typeof e.construct == "function" && (this._construct = e.construct), e.signal && xa(e.signal, this)), ze.call(this, e), Ot.construct(this, () => { + let r = this._writableState; + r.writing || Fr(this, r), Mr(this, r); + }); + } + ho(m, Sa, { __proto__: null, value: function(e) { + return co(this, e) ? true : this !== m ? false : e && e._writableState instanceof Je; + } }); + m.prototype.pipe = function() { + ve(this, new Ba); + }; + function bo(e, t, r, n) { + let i = e._writableState; + if (typeof r == "function") + n = r, r = i.defaultEncoding; + else { + if (!r) + r = i.defaultEncoding; + else if (r !== "buffer" && !Ft.isEncoding(r)) + throw new wo(r); + typeof n != "function" && (n = Lr); + } + if (t === null) + throw new Na; + if (!i.objectMode) + if (typeof t == "string") + i.decodeStrings !== false && (t = Ft.from(t, r), r = "buffer"); + else if (t instanceof Ft) + r = "buffer"; + else if (ze._isUint8Array(t)) + t = ze._uint8ArrayToBuffer(t), r = "buffer"; + else + throw new Ia("chunk", ["string", "Buffer", "Uint8Array"], t); + let o; + return i.ending ? o = new Fa : i.destroyed && (o = new Xe("write")), o ? (Re.nextTick(n, o), ve(e, o, true), o) : (i.pendingcb++, Ma(e, i, t, r, n)); + } + m.prototype.write = function(e, t, r) { + return bo(this, e, t, r) === true; + }; + m.prototype.cork = function() { + this._writableState.corked++; + }; + m.prototype.uncork = function() { + let e = this._writableState; + e.corked && (e.corked--, e.writing || Fr(this, e)); + }; + m.prototype.setDefaultEncoding = function(t) { + if (typeof t == "string" && (t = _a(t)), !Ft.isEncoding(t)) + throw new wo(t); + return this._writableState.defaultEncoding = t, this; + }; + function Ma(e, t, r, n, i) { + let o = t.objectMode ? 1 : r.length; + t.length += o; + let l = t.length < t.highWaterMark; + return l || (t.needDrain = true), t.writing || t.corked || t.errored || !t.constructed ? (t.buffered.push({ chunk: r, encoding: n, callback: i }), t.allBuffers && n !== "buffer" && (t.allBuffers = false), t.allNoop && i !== Lr && (t.allNoop = false)) : (t.writelen = o, t.writecb = i, t.writing = true, t.sync = true, e._write(r, n, t.onwrite), t.sync = false), l && !t.errored && !t.destroyed; + } + function fo(e, t, r, n, i, o, l) { + t.writelen = n, t.writecb = l, t.writing = true, t.sync = true, t.destroyed ? t.onwrite(new Xe("write")) : r ? e._writev(i, t.onwrite) : e._write(i, o, t.onwrite), t.sync = false; + } + function so(e, t, r, n) { + --t.pendingcb, n(r), Nr(t), ve(e, r); + } + function Ca(e, t) { + let r = e._writableState, n = r.sync, i = r.writecb; + if (typeof i != "function") { + ve(e, new yo); + return; + } + r.writing = false, r.writecb = null, r.length -= r.writelen, r.writelen = 0, t ? (t.stack, r.errored || (r.errored = t), e._readableState && !e._readableState.errored && (e._readableState.errored = t), n ? Re.nextTick(so, e, r, t, i) : so(e, r, t, i)) : (r.buffered.length > r.bufferedIndex && Fr(e, r), n ? r.afterWriteTickInfo !== null && r.afterWriteTickInfo.cb === i ? r.afterWriteTickInfo.count++ : (r.afterWriteTickInfo = { count: 1, cb: i, stream: e, state: r }, Re.nextTick(Oa, r.afterWriteTickInfo)) : go(e, r, 1, i)); + } + function Oa({ stream: e, state: t, count: r, cb: n }) { + return t.afterWriteTickInfo = null, go(e, t, r, n); + } + function go(e, t, r, n) { + for (!t.ending && !e.destroyed && t.length === 0 && t.needDrain && (t.needDrain = false, e.emit("drain"));r-- > 0; ) + t.pendingcb--, n(); + t.destroyed && Nr(t), Mr(e, t); + } + function Nr(e) { + if (e.writing) + return; + for (let i = e.bufferedIndex;i < e.buffered.length; ++i) { + var t; + let { chunk: o, callback: l } = e.buffered[i], u = e.objectMode ? 1 : o.length; + e.length -= u, l((t = e.errored) !== null && t !== undefined ? t : new Xe("write")); + } + let r = e[qe].splice(0); + for (let i = 0;i < r.length; i++) { + var n; + r[i]((n = e.errored) !== null && n !== undefined ? n : new Xe("end")); + } + Ct(e); + } + function Fr(e, t) { + if (t.corked || t.bufferProcessing || t.destroyed || !t.constructed) + return; + let { buffered: r, bufferedIndex: n, objectMode: i } = t, o = r.length - n; + if (!o) + return; + let l = n; + if (t.bufferProcessing = true, o > 1 && e._writev) { + t.pendingcb -= o - 1; + let u = t.allNoop ? Lr : (s) => { + for (let d = l;d < r.length; ++d) + r[d].callback(s); + }, f = t.allNoop && l === 0 ? r : ao(r, l); + f.allBuffers = t.allBuffers, fo(e, t, true, t.length, f, "", u), Ct(t); + } else { + do { + let { chunk: u, encoding: f, callback: s } = r[l]; + r[l++] = null; + let d = i ? 1 : u.length; + fo(e, t, false, d, u, f, s); + } while (l < r.length && !t.writing); + l === r.length ? Ct(t) : l > 256 ? (r.splice(0, l), t.bufferedIndex = 0) : t.bufferedIndex = l; + } + t.bufferProcessing = false; + } + m.prototype._write = function(e, t, r) { + if (this._writev) + this._writev([{ chunk: e, encoding: t }], r); + else + throw new Ta("_write()"); + }; + m.prototype._writev = null; + m.prototype.end = function(e, t, r) { + let n = this._writableState; + typeof e == "function" ? (r = e, e = null, t = null) : typeof t == "function" && (r = t, t = null); + let i; + if (e != null) { + let o = bo(this, e, t); + o instanceof ba && (i = o); + } + return n.corked && (n.corked = 1, this.uncork()), i || (!n.errored && !n.ending ? (n.ending = true, Mr(this, n, true), n.ended = true) : n.finished ? i = new La("end") : n.destroyed && (i = new Xe("end"))), typeof r == "function" && (i || n.finished ? Re.nextTick(r, i) : n[qe].push(r)), this; + }; + function Mt(e) { + return e.ending && !e.destroyed && e.constructed && e.length === 0 && !e.errored && e.buffered.length === 0 && !e.finished && !e.writing && !e.errorEmitted && !e.closeEmitted; + } + function Da(e, t) { + let r = false; + function n(i) { + if (r) { + ve(e, i ?? yo()); + return; + } + if (r = true, t.pendingcb--, i) { + let o = t[qe].splice(0); + for (let l = 0;l < o.length; l++) + o[l](i); + ve(e, i, t.sync); + } else + Mt(t) && (t.prefinished = true, e.emit("prefinish"), t.pendingcb++, Re.nextTick(Br, e, t)); + } + t.sync = true, t.pendingcb++; + try { + e._final(n); + } catch (i) { + n(i); + } + t.sync = false; + } + function Pa(e, t) { + !t.prefinished && !t.finalCalled && (typeof e._final == "function" && !t.destroyed ? (t.finalCalled = true, Da(e, t)) : (t.prefinished = true, e.emit("prefinish"))); + } + function Mr(e, t, r) { + Mt(t) && (Pa(e, t), t.pendingcb === 0 && (r ? (t.pendingcb++, Re.nextTick((n, i) => { + Mt(i) ? Br(n, i) : i.pendingcb--; + }, e, t)) : Mt(t) && (t.pendingcb++, Br(e, t)))); + } + function Br(e, t) { + t.pendingcb--, t.finished = true; + let r = t[qe].splice(0); + for (let n = 0;n < r.length; n++) + r[n](); + if (e.emit("finish"), t.autoDestroy) { + let n = e._readableState; + (!n || n.autoDestroy && (n.endEmitted || n.readable === false)) && e.destroy(); + } + } + ga(m.prototype, { closed: { __proto__: null, get() { + return this._writableState ? this._writableState.closed : false; + } }, destroyed: { __proto__: null, get() { + return this._writableState ? this._writableState.destroyed : false; + }, set(e) { + this._writableState && (this._writableState.destroyed = e); + } }, writable: { __proto__: null, get() { + let e = this._writableState; + return !!e && e.writable !== false && !e.destroyed && !e.errored && !e.ending && !e.ended; + }, set(e) { + this._writableState && (this._writableState.writable = !!e); + } }, writableFinished: { __proto__: null, get() { + return this._writableState ? this._writableState.finished : false; + } }, writableObjectMode: { __proto__: null, get() { + return this._writableState ? this._writableState.objectMode : false; + } }, writableBuffer: { __proto__: null, get() { + return this._writableState && this._writableState.getBuffer(); + } }, writableEnded: { __proto__: null, get() { + return this._writableState ? this._writableState.ending : false; + } }, writableNeedDrain: { __proto__: null, get() { + let e = this._writableState; + return e ? !e.destroyed && !e.ending && e.needDrain : false; + } }, writableHighWaterMark: { __proto__: null, get() { + return this._writableState && this._writableState.highWaterMark; + } }, writableCorked: { __proto__: null, get() { + return this._writableState ? this._writableState.corked : 0; + } }, writableLength: { __proto__: null, get() { + return this._writableState && this._writableState.length; + } }, errored: { __proto__: null, enumerable: false, get() { + return this._writableState ? this._writableState.errored : null; + } }, writableAborted: { __proto__: null, enumerable: false, get: function() { + return !!(this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished); + } } }); + var ka = Ot.destroy; + m.prototype.destroy = function(e, t) { + let r = this._writableState; + return !r.destroyed && (r.bufferedIndex < r.buffered.length || r[qe].length) && Re.nextTick(Nr, r), ka.call(this, e, t), this; + }; + m.prototype._undestroy = Ot.undestroy; + m.prototype._destroy = function(e, t) { + t(e); + }; + m.prototype[ma.captureRejectionSymbol] = function(e) { + this.destroy(e); + }; + var Tr; + function _o() { + return Tr === undefined && (Tr = {}), Tr; + } + m.fromWeb = function(e, t) { + return _o().newStreamWritableFromWritableStream(e, t); + }; + m.toWeb = function(e) { + return _o().newWritableStreamFromStreamWritable(e); + }; + }); + Mo = E((cd, Fo) => { + var Or = (se(), pe(k)), Ua = te(), { isReadable: va, isWritable: qa, isIterable: So, isNodeStream: Wa, isReadableNodeStream: mo, isWritableNodeStream: xo, isDuplexNodeStream: $a } = ae(), Ro = ce(), { AbortError: No, codes: { ERR_INVALID_ARG_TYPE: ja, ERR_INVALID_RETURN_VALUE: Ao } } = C(), { destroyer: We } = Se(), Ga = J(), Ha = Ke(), { createDeferredPromise: Io } = V(), To = Er(), Bo = globalThis.Blob || Ua.Blob, Va = typeof Bo < "u" ? function(t) { + return t instanceof Bo; + } : function(t) { + return false; + }, Ya = globalThis.AbortController || ut().AbortController, { FunctionPrototypeCall: Lo } = I(), Ae = class extends Ga { + constructor(t) { + super(t), t?.readable === false && (this._readableState.readable = false, this._readableState.ended = true, this._readableState.endEmitted = true), t?.writable === false && (this._writableState.writable = false, this._writableState.ending = true, this._writableState.ended = true, this._writableState.finished = true); + } + }; + Fo.exports = function e(t, r) { + if ($a(t)) + return t; + if (mo(t)) + return Dt({ readable: t }); + if (xo(t)) + return Dt({ writable: t }); + if (Wa(t)) + return Dt({ writable: false, readable: false }); + if (typeof t == "function") { + let { value: i, write: o, final: l, destroy: u } = Ka(t); + if (So(i)) + return To(Ae, i, { objectMode: true, write: o, final: l, destroy: u }); + let f = i?.then; + if (typeof f == "function") { + let s, d = Lo(f, i, (c) => { + if (c != null) + throw new Ao("nully", "body", c); + }, (c) => { + We(s, c); + }); + return s = new Ae({ objectMode: true, readable: false, write: o, final(c) { + l(async () => { + try { + await d, Or.nextTick(c, null); + } catch (y) { + Or.nextTick(c, y); + } + }); + }, destroy: u }); + } + throw new Ao("Iterable, AsyncIterable or AsyncFunction", r, i); + } + if (Va(t)) + return e(t.arrayBuffer()); + if (So(t)) + return To(Ae, t, { objectMode: true, writable: false }); + if (typeof t?.writable == "object" || typeof t?.readable == "object") { + let i = t != null && t.readable ? mo(t?.readable) ? t?.readable : e(t.readable) : undefined, o = t != null && t.writable ? xo(t?.writable) ? t?.writable : e(t.writable) : undefined; + return Dt({ readable: i, writable: o }); + } + let n = t?.then; + if (typeof n == "function") { + let i; + return Lo(n, t, (o) => { + o != null && i.push(o), i.push(null); + }, (o) => { + We(i, o); + }), i = new Ae({ objectMode: true, writable: false, read() { + } }); + } + throw new ja(r, ["Blob", "ReadableStream", "WritableStream", "Stream", "Iterable", "AsyncIterable", "Function", "{ readable, writable } pair", "Promise"], t); + }; + function Ka(e) { + let { promise: t, resolve: r } = Io(), n = new Ya, i = n.signal; + return { value: e(async function* () { + for (;; ) { + let l = t; + t = null; + let { chunk: u, done: f, cb: s } = await l; + if (Or.nextTick(s), f) + return; + if (i.aborted) + throw new No(undefined, { cause: i.reason }); + ({ promise: t, resolve: r } = Io()), yield u; + } + }(), { signal: i }), write(l, u, f) { + let s = r; + r = null, s({ chunk: l, done: false, cb: f }); + }, final(l) { + let u = r; + r = null, u({ done: true, cb: l }); + }, destroy(l, u) { + n.abort(), u(l); + } }; + } + function Dt(e) { + let t = e.readable && typeof e.readable.read != "function" ? Ha.wrap(e.readable) : e.readable, r = e.writable, n = !!va(t), i = !!qa(r), o, l, u, f, s; + function d(c) { + let y = f; + f = null, y ? y(c) : c ? s.destroy(c) : !n && !i && s.destroy(); + } + return s = new Ae({ readableObjectMode: !!(t != null && t.readableObjectMode), writableObjectMode: !!(r != null && r.writableObjectMode), readable: n, writable: i }), i && (Ro(r, (c) => { + i = false, c && We(t, c), d(c); + }), s._write = function(c, y, h) { + r.write(c, y) ? h() : o = h; + }, s._final = function(c) { + r.end(), l = c; + }, r.on("drain", function() { + if (o) { + let c = o; + o = null, c(); + } + }), r.on("finish", function() { + if (l) { + let c = l; + l = null, c(); + } + })), n && (Ro(t, (c) => { + n = false, c && We(t, c), d(c); + }), t.on("readable", function() { + if (u) { + let c = u; + u = null, c(); + } + }), t.on("end", function() { + s.push(null); + }), s._read = function() { + for (;; ) { + let c = t.read(); + if (c === null) { + u = s._read; + return; + } + if (!s.push(c)) + return; + } + }), s._destroy = function(c, y) { + !c && f !== null && (c = new No), u = null, o = null, l = null, f === null ? y(c) : (f = y, We(r, c), We(t, c)); + }, s; + } + }); + J = E((dd, Do) => { + var { ObjectDefineProperties: za, ObjectGetOwnPropertyDescriptor: ie, ObjectKeys: Xa, ObjectSetPrototypeOf: Co } = I(); + Do.exports = j; + var kr = Ke(), U = Cr(); + Co(j.prototype, kr.prototype); + Co(j, kr); + { + let e = Xa(U.prototype); + for (let t = 0;t < e.length; t++) { + let r = e[t]; + j.prototype[r] || (j.prototype[r] = U.prototype[r]); + } + } + function j(e) { + if (!(this instanceof j)) + return new j(e); + kr.call(this, e), U.call(this, e), e ? (this.allowHalfOpen = e.allowHalfOpen !== false, e.readable === false && (this._readableState.readable = false, this._readableState.ended = true, this._readableState.endEmitted = true), e.writable === false && (this._writableState.writable = false, this._writableState.ending = true, this._writableState.ended = true, this._writableState.finished = true)) : this.allowHalfOpen = true; + } + za(j.prototype, { writable: { __proto__: null, ...ie(U.prototype, "writable") }, writableHighWaterMark: { __proto__: null, ...ie(U.prototype, "writableHighWaterMark") }, writableObjectMode: { __proto__: null, ...ie(U.prototype, "writableObjectMode") }, writableBuffer: { __proto__: null, ...ie(U.prototype, "writableBuffer") }, writableLength: { __proto__: null, ...ie(U.prototype, "writableLength") }, writableFinished: { __proto__: null, ...ie(U.prototype, "writableFinished") }, writableCorked: { __proto__: null, ...ie(U.prototype, "writableCorked") }, writableEnded: { __proto__: null, ...ie(U.prototype, "writableEnded") }, writableNeedDrain: { __proto__: null, ...ie(U.prototype, "writableNeedDrain") }, destroyed: { __proto__: null, get() { + return this._readableState === undefined || this._writableState === undefined ? false : this._readableState.destroyed && this._writableState.destroyed; + }, set(e) { + this._readableState && this._writableState && (this._readableState.destroyed = e, this._writableState.destroyed = e); + } } }); + var Dr; + function Oo() { + return Dr === undefined && (Dr = {}), Dr; + } + j.fromWeb = function(e, t) { + return Oo().newStreamDuplexFromReadableWritablePair(e, t); + }; + j.toWeb = function(e) { + return Oo().newReadableWritablePairFromDuplex(e); + }; + var Pr; + j.from = function(e) { + return Pr || (Pr = Mo()), Pr(e, "body"); + }; + }); + qr = E((hd, ko) => { + var { ObjectSetPrototypeOf: Po, Symbol: Ja } = I(); + ko.exports = oe; + var { ERR_METHOD_NOT_IMPLEMENTED: Qa } = C().codes, vr = J(), { getHighWaterMark: Za } = Tt(); + Po(oe.prototype, vr.prototype); + Po(oe, vr); + var Qe = Ja("kCallback"); + function oe(e) { + if (!(this instanceof oe)) + return new oe(e); + let t = e ? Za(this, e, "readableHighWaterMark", true) : null; + t === 0 && (e = { ...e, highWaterMark: null, readableHighWaterMark: t, writableHighWaterMark: e.writableHighWaterMark || 0 }), vr.call(this, e), this._readableState.sync = false, this[Qe] = null, e && (typeof e.transform == "function" && (this._transform = e.transform), typeof e.flush == "function" && (this._flush = e.flush)), this.on("prefinish", ec); + } + function Ur(e) { + typeof this._flush == "function" && !this.destroyed ? this._flush((t, r) => { + if (t) { + e ? e(t) : this.destroy(t); + return; + } + r != null && this.push(r), this.push(null), e && e(); + }) : (this.push(null), e && e()); + } + function ec() { + this._final !== Ur && Ur.call(this); + } + oe.prototype._final = Ur; + oe.prototype._transform = function(e, t, r) { + throw new Qa("_transform()"); + }; + oe.prototype._write = function(e, t, r) { + let n = this._readableState, i = this._writableState, o = n.length; + this._transform(e, t, (l, u) => { + if (l) { + r(l); + return; + } + u != null && this.push(u), i.ended || o === n.length || n.length < n.highWaterMark ? r() : this[Qe] = r; + }); + }; + oe.prototype._read = function() { + if (this[Qe]) { + let e = this[Qe]; + this[Qe] = null, e(); + } + }; + }); + $r = E((pd, vo) => { + var { ObjectSetPrototypeOf: Uo } = I(); + vo.exports = $e; + var Wr = qr(); + Uo($e.prototype, Wr.prototype); + Uo($e, Wr); + function $e(e) { + if (!(this instanceof $e)) + return new $e(e); + Wr.call(this, e); + } + $e.prototype._transform = function(e, t, r) { + r(null, e); + }; + }); + Ut = E((yd, Vo) => { + var Pt = (se(), pe(k)), { ArrayIsArray: tc, Promise: rc, SymbolAsyncIterator: nc } = I(), kt = ce(), { once: ic } = V(), oc = Se(), qo = J(), { aggregateTwoErrors: lc, codes: { ERR_INVALID_ARG_TYPE: Go, ERR_INVALID_RETURN_VALUE: jr, ERR_MISSING_ARGS: uc, ERR_STREAM_DESTROYED: fc, ERR_STREAM_PREMATURE_CLOSE: sc }, AbortError: ac } = C(), { validateFunction: cc, validateAbortSignal: dc } = He(), { isIterable: je, isReadable: Gr, isReadableNodeStream: Yr, isNodeStream: Wo } = ae(), hc = globalThis.AbortController || ut().AbortController, Hr, Vr; + function $o(e, t, r) { + let n = false; + e.on("close", () => { + n = true; + }); + let i = kt(e, { readable: t, writable: r }, (o) => { + n = !o; + }); + return { destroy: (o) => { + n || (n = true, oc.destroyer(e, o || new fc("pipe"))); + }, cleanup: i }; + } + function pc(e) { + return cc(e[e.length - 1], "streams[stream.length - 1]"), e.pop(); + } + function yc(e) { + if (je(e)) + return e; + if (Yr(e)) + return wc(e); + throw new Go("val", ["Readable", "Iterable", "AsyncIterable"], e); + } + async function* wc(e) { + Vr || (Vr = Ke()), yield* Vr.prototype[nc].call(e); + } + async function jo(e, t, r, { end: n }) { + let i, o = null, l = (s) => { + if (s && (i = s), o) { + let d = o; + o = null, d(); + } + }, u = () => new rc((s, d) => { + i ? d(i) : o = () => { + i ? d(i) : s(); + }; + }); + t.on("drain", l); + let f = kt(t, { readable: false }, l); + try { + t.writableNeedDrain && await u(); + for await (let s of e) + t.write(s) || await u(); + n && t.end(), await u(), r(); + } catch (s) { + r(i !== s ? lc(i, s) : s); + } finally { + f(), t.off("drain", l); + } + } + function bc(...e) { + return Ho(e, ic(pc(e))); + } + function Ho(e, t, r) { + if (e.length === 1 && tc(e[0]) && (e = e[0]), e.length < 2) + throw new uc("streams"); + let n = new hc, i = n.signal, o = r?.signal, l = []; + dc(o, "options.signal"); + function u() { + h(new ac); + } + o?.addEventListener("abort", u); + let f, s, d = [], c = 0; + function y(w) { + h(w, --c === 0); + } + function h(w, b) { + if (w && (!f || f.code === "ERR_STREAM_PREMATURE_CLOSE") && (f = w), !(!f && !b)) { + for (;d.length; ) + d.shift()(f); + o?.removeEventListener("abort", u), n.abort(), b && (f || l.forEach((L) => L()), Pt.nextTick(t, f, s)); + } + } + let p; + for (let w = 0;w < e.length; w++) { + let b = e[w], L = w < e.length - 1, N = w > 0, Q = L || r?.end !== false, Ie = w === e.length - 1; + if (Wo(b)) { + let q = function(Z) { + Z && Z.name !== "AbortError" && Z.code !== "ERR_STREAM_PREMATURE_CLOSE" && y(Z); + }; + var v = q; + if (Q) { + let { destroy: Z, cleanup: qt } = $o(b, L, N); + d.push(Z), Gr(b) && Ie && l.push(qt); + } + b.on("error", q), Gr(b) && Ie && l.push(() => { + b.removeListener("error", q); + }); + } + if (w === 0) + if (typeof b == "function") { + if (p = b({ signal: i }), !je(p)) + throw new jr("Iterable, AsyncIterable or Stream", "source", p); + } else + je(b) || Yr(b) ? p = b : p = qo.from(b); + else if (typeof b == "function") + if (p = yc(p), p = b(p, { signal: i }), L) { + if (!je(p, true)) + throw new jr("AsyncIterable", `transform[${w - 1}]`, p); + } else { + var B; + Hr || (Hr = $r()); + let q = new Hr({ objectMode: true }), Z = (B = p) === null || B === undefined ? undefined : B.then; + if (typeof Z == "function") + c++, Z.call(p, (Te) => { + s = Te, Te != null && q.write(Te), Q && q.end(), Pt.nextTick(y); + }, (Te) => { + q.destroy(Te), Pt.nextTick(y, Te); + }); + else if (je(p, true)) + c++, jo(p, q, y, { end: Q }); + else + throw new jr("AsyncIterable or Promise", "destination", p); + p = q; + let { destroy: qt, cleanup: sl } = $o(p, false, true); + d.push(qt), Ie && l.push(sl); + } + else if (Wo(b)) { + if (Yr(p)) { + c += 2; + let q = gc(p, b, y, { end: Q }); + Gr(b) && Ie && l.push(q); + } else if (je(p)) + c++, jo(p, b, y, { end: Q }); + else + throw new Go("val", ["Readable", "Iterable", "AsyncIterable"], p); + p = b; + } else + p = qo.from(b); + } + return (i != null && i.aborted || o != null && o.aborted) && Pt.nextTick(u), p; + } + function gc(e, t, r, { end: n }) { + let i = false; + return t.on("close", () => { + i || r(new sc); + }), e.pipe(t, { end: n }), n ? e.once("end", () => { + i = true, t.end(); + }) : r(), kt(e, { readable: true, writable: false }, (o) => { + let l = e._readableState; + o && o.code === "ERR_STREAM_PREMATURE_CLOSE" && l && l.ended && !l.errored && !l.errorEmitted ? e.once("end", r).once("error", r) : r(o); + }), kt(t, { readable: false, writable: true }, r); + } + Vo.exports = { pipelineImpl: Ho, pipeline: bc }; + }); + Jo = E((wd, Xo) => { + var { pipeline: _c } = Ut(), vt = J(), { destroyer: Ec } = Se(), { isNodeStream: Sc, isReadable: Yo, isWritable: Ko } = ae(), { AbortError: mc, codes: { ERR_INVALID_ARG_VALUE: zo, ERR_MISSING_ARGS: xc } } = C(); + Xo.exports = function(...t) { + if (t.length === 0) + throw new xc("streams"); + if (t.length === 1) + return vt.from(t[0]); + let r = [...t]; + if (typeof t[0] == "function" && (t[0] = vt.from(t[0])), typeof t[t.length - 1] == "function") { + let h = t.length - 1; + t[h] = vt.from(t[h]); + } + for (let h = 0;h < t.length; ++h) + if (!!Sc(t[h])) { + if (h < t.length - 1 && !Yo(t[h])) + throw new zo(`streams[${h}]`, r[h], "must be readable"); + if (h > 0 && !Ko(t[h])) + throw new zo(`streams[${h}]`, r[h], "must be writable"); + } + let n, i, o, l, u; + function f(h) { + let p = l; + l = null, p ? p(h) : h ? u.destroy(h) : !y && !c && u.destroy(); + } + let s = t[0], d = _c(t, f), c = !!Ko(s), y = !!Yo(d); + return u = new vt({ writableObjectMode: !!(s != null && s.writableObjectMode), readableObjectMode: !!(d != null && d.writableObjectMode), writable: c, readable: y }), c && (u._write = function(h, p, B) { + s.write(h, p) ? B() : n = B; + }, u._final = function(h) { + s.end(), i = h; + }, s.on("drain", function() { + if (n) { + let h = n; + n = null, h(); + } + }), d.on("finish", function() { + if (i) { + let h = i; + i = null, h(); + } + })), y && (d.on("readable", function() { + if (o) { + let h = o; + o = null, h(); + } + }), d.on("end", function() { + u.push(null); + }), u._read = function() { + for (;; ) { + let h = d.read(); + if (h === null) { + o = u._read; + return; + } + if (!u.push(h)) + return; + } + }), u._destroy = function(h, p) { + !h && l !== null && (h = new mc), o = null, n = null, i = null, l === null ? p(h) : (l = p, Ec(d, h)); + }, u; + }; + }); + Kr = E((bd, Qo) => { + var { ArrayPrototypePop: Rc, Promise: Ac } = I(), { isIterable: Ic, isNodeStream: Tc } = ae(), { pipelineImpl: Bc } = Ut(), { finished: Lc } = ce(); + function Nc(...e) { + return new Ac((t, r) => { + let n, i, o = e[e.length - 1]; + if (o && typeof o == "object" && !Tc(o) && !Ic(o)) { + let l = Rc(e); + n = l.signal, i = l.end; + } + Bc(e, (l, u) => { + l ? r(l) : t(u); + }, { signal: n, end: i }); + }); + } + Qo.exports = { finished: Lc, pipeline: Nc }; + }); + fl = E((gd, ul) => { + var { Buffer: Fc } = te(), { ObjectDefineProperty: le, ObjectKeys: tl, ReflectApply: rl } = I(), { promisify: { custom: nl } } = V(), { streamReturningOperators: Zo, promiseReturningOperators: el } = di(), { codes: { ERR_ILLEGAL_CONSTRUCTOR: il } } = C(), Mc = Jo(), { pipeline: ol } = Ut(), { destroyer: Cc } = Se(), ll = ce(), zr = Kr(), Xr = ae(), R = ul.exports = xt().Stream; + R.isDisturbed = Xr.isDisturbed; + R.isErrored = Xr.isErrored; + R.isReadable = Xr.isReadable; + R.Readable = Ke(); + for (let e of tl(Zo)) { + let r = function(...n) { + if (new.target) + throw il(); + return R.Readable.from(rl(t, this, n)); + }; + Dc = r; + let t = Zo[e]; + le(r, "name", { __proto__: null, value: t.name }), le(r, "length", { __proto__: null, value: t.length }), le(R.Readable.prototype, e, { __proto__: null, value: r, enumerable: false, configurable: true, writable: true }); + } + var Dc; + for (let e of tl(el)) { + let r = function(...i) { + if (new.target) + throw il(); + return rl(t, this, i); + }; + Dc = r; + let t = el[e]; + le(r, "name", { __proto__: null, value: t.name }), le(r, "length", { __proto__: null, value: t.length }), le(R.Readable.prototype, e, { __proto__: null, value: r, enumerable: false, configurable: true, writable: true }); + } + var Dc; + R.Writable = Cr(); + R.Duplex = J(); + R.Transform = qr(); + R.PassThrough = $r(); + R.pipeline = ol; + var { addAbortSignal: Oc } = At(); + R.addAbortSignal = Oc; + R.finished = ll; + R.destroy = Cc; + R.compose = Mc; + le(R, "promises", { __proto__: null, configurable: true, enumerable: true, get() { + return zr; + } }); + le(ol, nl, { __proto__: null, enumerable: true, get() { + return zr.pipeline; + } }); + le(ll, nl, { __proto__: null, enumerable: true, get() { + return zr.finished; + } }); + R.Stream = R; + R._isUint8Array = function(t) { + return t instanceof Uint8Array; + }; + R._uint8ArrayToBuffer = function(t) { + return Fc.from(t.buffer, t.byteOffset, t.byteLength); + }; + }); + Jr = E((_d, A) => { + var T = fl(), Pc = Kr(), kc = T.Readable.destroy; + A.exports = T.Readable; + A.exports._uint8ArrayToBuffer = T._uint8ArrayToBuffer; + A.exports._isUint8Array = T._isUint8Array; + A.exports.isDisturbed = T.isDisturbed; + A.exports.isErrored = T.isErrored; + A.exports.isReadable = T.isReadable; + A.exports.Readable = T.Readable; + A.exports.Writable = T.Writable; + A.exports.Duplex = T.Duplex; + A.exports.Transform = T.Transform; + A.exports.PassThrough = T.PassThrough; + A.exports.addAbortSignal = T.addAbortSignal; + A.exports.finished = T.finished; + A.exports.destroy = T.destroy; + A.exports.destroy = kc; + A.exports.pipeline = T.pipeline; + A.exports.compose = T.compose; + Object.defineProperty(T, "promises", { configurable: true, enumerable: true, get() { + return Pc; + } }); + A.exports.Stream = T.Stream; + A.exports.default = A.exports; + }); + Ze = {}; + Qr(Ze, { default: () => Uc }); + ue(Ze, rt(Jr())); + Uc = rt(Jr()); + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + /*! safe-buffer. MIT License. Feross Aboukhadijeh */ +}); + +// node_modules/jszip/lib/support.js +var require_support = __commonJS((exports2) => { + exports2.base64 = true; + exports2.array = true; + exports2.string = true; + exports2.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"; + exports2.nodebuffer = typeof Buffer !== "undefined"; + exports2.uint8array = typeof Uint8Array !== "undefined"; + if (typeof ArrayBuffer === "undefined") { + exports2.blob = false; + } else { + buffer = new ArrayBuffer(0); + try { + exports2.blob = new Blob([buffer], { + type: "application/zip" + }).size === 0; + } catch (e) { + try { + Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; + builder = new Builder; + builder.append(buffer); + exports2.blob = builder.getBlob("application/zip").size === 0; + } catch (e2) { + exports2.blob = false; + } + } + } + var buffer; + var Builder; + var builder; + try { + exports2.nodestream = !!(init_stream(), __toCommonJS(exports_stream)).Readable; + } catch (e) { + exports2.nodestream = false; + } +}); + +// node_modules/jszip/lib/base64.js +var require_base64 = __commonJS((exports2) => { + var utils = require_utils(); + var support = require_support(); + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + exports2.encode = function(input) { + var output = []; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0, len = input.length, remainingBytes = len; + var isArray2 = utils.getTypeOf(input) !== "string"; + while (i < input.length) { + remainingBytes = len - i; + if (!isArray2) { + chr1 = input.charCodeAt(i++); + chr2 = i < len ? input.charCodeAt(i++) : 0; + chr3 = i < len ? input.charCodeAt(i++) : 0; + } else { + chr1 = input[i++]; + chr2 = i < len ? input[i++] : 0; + chr3 = i < len ? input[i++] : 0; + } + enc1 = chr1 >> 2; + enc2 = (chr1 & 3) << 4 | chr2 >> 4; + enc3 = remainingBytes > 1 ? (chr2 & 15) << 2 | chr3 >> 6 : 64; + enc4 = remainingBytes > 2 ? chr3 & 63 : 64; + output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4)); + } + return output.join(""); + }; + exports2.decode = function(input) { + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0, resultIndex = 0; + var dataUrlPrefix = "data:"; + if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) { + throw new Error("Invalid base64 input, it looks like a data url."); + } + input = input.replace(/[^A-Za-z0-9+/=]/g, ""); + var totalLength = input.length * 3 / 4; + if (input.charAt(input.length - 1) === _keyStr.charAt(64)) { + totalLength--; + } + if (input.charAt(input.length - 2) === _keyStr.charAt(64)) { + totalLength--; + } + if (totalLength % 1 !== 0) { + throw new Error("Invalid base64 input, bad content length."); + } + var output; + if (support.uint8array) { + output = new Uint8Array(totalLength | 0); + } else { + output = new Array(totalLength | 0); + } + while (i < input.length) { + enc1 = _keyStr.indexOf(input.charAt(i++)); + enc2 = _keyStr.indexOf(input.charAt(i++)); + enc3 = _keyStr.indexOf(input.charAt(i++)); + enc4 = _keyStr.indexOf(input.charAt(i++)); + chr1 = enc1 << 2 | enc2 >> 4; + chr2 = (enc2 & 15) << 4 | enc3 >> 2; + chr3 = (enc3 & 3) << 6 | enc4; + output[resultIndex++] = chr1; + if (enc3 !== 64) { + output[resultIndex++] = chr2; + } + if (enc4 !== 64) { + output[resultIndex++] = chr3; + } + } + return output; + }; +}); + +// node_modules/jszip/lib/nodejsUtils.js +var require_nodejsUtils = __commonJS((exports2, module2) => { + module2.exports = { + isNode: typeof Buffer !== "undefined", + newBufferFrom: function(data2, encoding) { + if (Buffer.from && Buffer.from !== Uint8Array.from) { + return Buffer.from(data2, encoding); + } else { + if (typeof data2 === "number") { + throw new Error('The "data" argument must not be a number'); + } + return new Buffer(data2, encoding); + } + }, + allocBuffer: function(size) { + if (Buffer.alloc) { + return Buffer.alloc(size); + } else { + var buf = new Buffer(size); + buf.fill(0); + return buf; + } + }, + isBuffer: function(b) { + return Buffer.isBuffer(b); + }, + isStream: function(obj) { + return obj && typeof obj.on === "function" && typeof obj.pause === "function" && typeof obj.resume === "function"; + } + }; +}); + +// node_modules/immediate/lib/browser.js +var require_browser = __commonJS((exports2, module2) => { + var Mutation = global.MutationObserver || global.WebKitMutationObserver; + var scheduleDrain; + { + if (Mutation) { + called = 0; + observer = new Mutation(nextTick); + element = global.document.createTextNode(""); + observer.observe(element, { + characterData: true + }); + scheduleDrain = function() { + element.data = called = ++called % 2; + }; + } else if (!global.setImmediate && typeof global.MessageChannel !== "undefined") { + channel = new global.MessageChannel; + channel.port1.onmessage = nextTick; + scheduleDrain = function() { + channel.port2.postMessage(0); + }; + } else if ("document" in global && "onreadystatechange" in global.document.createElement("script")) { + scheduleDrain = function() { + var scriptEl = global.document.createElement("script"); + scriptEl.onreadystatechange = function() { + nextTick(); + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + global.document.documentElement.appendChild(scriptEl); + }; + } else { + scheduleDrain = function() { + setTimeout(nextTick, 0); + }; + } + } + var called; + var observer; + var element; + var channel; + var draining; + var queue = []; + function nextTick() { + draining = true; + var i, oldQueue; + var len = queue.length; + while (len) { + oldQueue = queue; + queue = []; + i = -1; + while (++i < len) { + oldQueue[i](); + } + len = queue.length; + } + draining = false; + } + module2.exports = immediate; + function immediate(task) { + if (queue.push(task) === 1 && !draining) { + scheduleDrain(); + } + } +}); + +// node_modules/lie/lib/browser.js +var require_browser2 = __commonJS((exports2, module2) => { + var immediate = require_browser(); + function INTERNAL() { + } + var handlers = {}; + var REJECTED = ["REJECTED"]; + var FULFILLED = ["FULFILLED"]; + var PENDING = ["PENDING"]; + module2.exports = Promise2; + function Promise2(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("resolver must be a function"); + } + this.state = PENDING; + this.queue = []; + this.outcome = undefined; + if (resolver !== INTERNAL) { + safelyResolveThenable(this, resolver); + } + } + Promise2.prototype["finally"] = function(callback) { + if (typeof callback !== "function") { + return this; + } + var p = this.constructor; + return this.then(resolve2, reject3); + function resolve2(value2) { + function yes() { + return value2; + } + return p.resolve(callback()).then(yes); + } + function reject3(reason) { + function no() { + throw reason; + } + return p.resolve(callback()).then(no); + } + }; + Promise2.prototype["catch"] = function(onRejected) { + return this.then(null, onRejected); + }; + Promise2.prototype.then = function(onFulfilled, onRejected) { + if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) { + return this; + } + var promise = new this.constructor(INTERNAL); + if (this.state !== PENDING) { + var resolver = this.state === FULFILLED ? onFulfilled : onRejected; + unwrap(promise, resolver, this.outcome); + } else { + this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); + } + return promise; + }; + function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === "function") { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === "function") { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } + } + QueueItem.prototype.callFulfilled = function(value2) { + handlers.resolve(this.promise, value2); + }; + QueueItem.prototype.otherCallFulfilled = function(value2) { + unwrap(this.promise, this.onFulfilled, value2); + }; + QueueItem.prototype.callRejected = function(value2) { + handlers.reject(this.promise, value2); + }; + QueueItem.prototype.otherCallRejected = function(value2) { + unwrap(this.promise, this.onRejected, value2); + }; + function unwrap(promise, func, value2) { + immediate(function() { + var returnValue; + try { + returnValue = func(value2); + } catch (e) { + return handlers.reject(promise, e); + } + if (returnValue === promise) { + handlers.reject(promise, new TypeError("Cannot resolve promise with itself")); + } else { + handlers.resolve(promise, returnValue); + } + }); + } + handlers.resolve = function(self2, value2) { + var result = tryCatch(getThen, value2); + if (result.status === "error") { + return handlers.reject(self2, result.value); + } + var thenable = result.value; + if (thenable) { + safelyResolveThenable(self2, thenable); + } else { + self2.state = FULFILLED; + self2.outcome = value2; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callFulfilled(value2); + } + } + return self2; + }; + handlers.reject = function(self2, error) { + self2.state = REJECTED; + self2.outcome = error; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callRejected(error); + } + return self2; + }; + function getThen(obj) { + var then = obj && obj.then; + if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") { + return function appyThen() { + then.apply(obj, arguments); + }; + } + } + function safelyResolveThenable(self2, thenable) { + var called = false; + function onError(value2) { + if (called) { + return; + } + called = true; + handlers.reject(self2, value2); + } + function onSuccess(value2) { + if (called) { + return; + } + called = true; + handlers.resolve(self2, value2); + } + function tryToUnwrap() { + thenable(onSuccess, onError); + } + var result = tryCatch(tryToUnwrap); + if (result.status === "error") { + onError(result.value); + } + } + function tryCatch(func, value2) { + var out = {}; + try { + out.value = func(value2); + out.status = "success"; + } catch (e) { + out.status = "error"; + out.value = e; + } + return out; + } + Promise2.resolve = resolve; + function resolve(value2) { + if (value2 instanceof this) { + return value2; + } + return handlers.resolve(new this(INTERNAL), value2); + } + Promise2.reject = reject2; + function reject2(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); + } + Promise2.all = all; + function all(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var values2 = new Array(len); + var resolved = 0; + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + allResolver(iterable[i], i); + } + return promise; + function allResolver(value2, i2) { + self2.resolve(value2).then(resolveFromAll, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values2[i2] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values2); + } + } + } + } + Promise2.race = race; + function race(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + resolver(iterable[i]); + } + return promise; + function resolver(value2) { + self2.resolve(value2).then(function(response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } + } +}); + +// node_modules/jszip/lib/external.js +var require_external = __commonJS((exports2, module2) => { + var ES6Promise = null; + if (typeof Promise !== "undefined") { + ES6Promise = Promise; + } else { + ES6Promise = require_browser2(); + } + module2.exports = { + Promise: ES6Promise + }; +}); + +// node_modules/setimmediate/setImmediate.js +var require_setImmediate = __commonJS((exports2) => { + (function(global2, undefined2) { + if (global2.setImmediate) { + return; + } + var nextHandle = 1; + var tasksByHandle = {}; + var currentlyRunningATask = false; + var doc = global2.document; + var registerImmediate; + function setImmediate2(callback) { + if (typeof callback !== "function") { + callback = new Function("" + callback); + } + var args = new Array(arguments.length - 1); + for (var i = 0;i < args.length; i++) { + args[i] = arguments[i + 1]; + } + var task = { callback, args }; + tasksByHandle[nextHandle] = task; + registerImmediate(nextHandle); + return nextHandle++; + } + function clearImmediate(handle) { + delete tasksByHandle[handle]; + } + function run(task) { + var callback = task.callback; + var args = task.args; + switch (args.length) { + case 0: + callback(); + break; + case 1: + callback(args[0]); + break; + case 2: + callback(args[0], args[1]); + break; + case 3: + callback(args[0], args[1], args[2]); + break; + default: + callback.apply(undefined2, args); + break; + } + } + function runIfPresent(handle) { + if (currentlyRunningATask) { + setTimeout(runIfPresent, 0, handle); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunningATask = true; + try { + run(task); + } finally { + clearImmediate(handle); + currentlyRunningATask = false; + } + } + } + } + function installNextTickImplementation() { + registerImmediate = function(handle) { + process.nextTick(function() { + runIfPresent(handle); + }); + }; + } + function canUsePostMessage() { + if (global2.postMessage && !global2.importScripts) { + var postMessageIsAsynchronous = true; + var oldOnMessage = global2.onmessage; + global2.onmessage = function() { + postMessageIsAsynchronous = false; + }; + global2.postMessage("", "*"); + global2.onmessage = oldOnMessage; + return postMessageIsAsynchronous; + } + } + function installPostMessageImplementation() { + var messagePrefix = "setImmediate$" + Math.random() + "$"; + var onGlobalMessage = function(event) { + if (event.source === global2 && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { + runIfPresent(+event.data.slice(messagePrefix.length)); + } + }; + if (global2.addEventListener) { + global2.addEventListener("message", onGlobalMessage, false); + } else { + global2.attachEvent("onmessage", onGlobalMessage); + } + registerImmediate = function(handle) { + global2.postMessage(messagePrefix + handle, "*"); + }; + } + function installMessageChannelImplementation() { + var channel = new MessageChannel; + channel.port1.onmessage = function(event) { + var handle = event.data; + runIfPresent(handle); + }; + registerImmediate = function(handle) { + channel.port2.postMessage(handle); + }; + } + function installReadyStateChangeImplementation() { + var html = doc.documentElement; + registerImmediate = function(handle) { + var script = doc.createElement("script"); + script.onreadystatechange = function() { + runIfPresent(handle); + script.onreadystatechange = null; + html.removeChild(script); + script = null; + }; + html.appendChild(script); + }; + } + function installSetTimeoutImplementation() { + registerImmediate = function(handle) { + setTimeout(runIfPresent, 0, handle); + }; + } + var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global2); + attachTo = attachTo && attachTo.setTimeout ? attachTo : global2; + if ({}.toString.call(global2.process) === "[object process]") { + installNextTickImplementation(); + } else if (canUsePostMessage()) { + installPostMessageImplementation(); + } else if (global2.MessageChannel) { + installMessageChannelImplementation(); + } else if (doc && "onreadystatechange" in doc.createElement("script")) { + installReadyStateChangeImplementation(); + } else { + installSetTimeoutImplementation(); + } + attachTo.setImmediate = setImmediate2; + attachTo.clearImmediate = clearImmediate; + })(typeof self === "undefined" ? typeof global === "undefined" ? exports2 : global : self); +}); + +// node_modules/jszip/lib/utils.js +var require_utils = __commonJS((exports2) => { + var support = require_support(); + var base64 = require_base64(); + var nodejsUtils = require_nodejsUtils(); + var external = require_external(); + require_setImmediate(); + function string2binary(str) { + var result = null; + if (support.uint8array) { + result = new Uint8Array(str.length); + } else { + result = new Array(str.length); + } + return stringToArrayLike(str, result); + } + exports2.newBlob = function(part, type) { + exports2.checkSupport("blob"); + try { + return new Blob([part], { + type + }); + } catch (e) { + try { + var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; + var builder = new Builder; + builder.append(part); + return builder.getBlob(type); + } catch (e2) { + throw new Error("Bug : can't construct the Blob."); + } + } + }; + function identity(input) { + return input; + } + function stringToArrayLike(str, array) { + for (var i = 0;i < str.length; ++i) { + array[i] = str.charCodeAt(i) & 255; + } + return array; + } + var arrayToStringHelper = { + stringifyByChunk: function(array, type, chunk) { + var result = [], k2 = 0, len = array.length; + if (len <= chunk) { + return String.fromCharCode.apply(null, array); + } + while (k2 < len) { + if (type === "array" || type === "nodebuffer") { + result.push(String.fromCharCode.apply(null, array.slice(k2, Math.min(k2 + chunk, len)))); + } else { + result.push(String.fromCharCode.apply(null, array.subarray(k2, Math.min(k2 + chunk, len)))); + } + k2 += chunk; + } + return result.join(""); + }, + stringifyByChar: function(array) { + var resultStr = ""; + for (var i = 0;i < array.length; i++) { + resultStr += String.fromCharCode(array[i]); + } + return resultStr; + }, + applyCanBeUsed: { + uint8array: function() { + try { + return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1; + } catch (e) { + return false; + } + }(), + nodebuffer: function() { + try { + return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1; + } catch (e) { + return false; + } + }() + } + }; + function arrayLikeToString(array) { + var chunk = 65536, type = exports2.getTypeOf(array), canUseApply = true; + if (type === "uint8array") { + canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array; + } else if (type === "nodebuffer") { + canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer; + } + if (canUseApply) { + while (chunk > 1) { + try { + return arrayToStringHelper.stringifyByChunk(array, type, chunk); + } catch (e) { + chunk = Math.floor(chunk / 2); + } + } + } + return arrayToStringHelper.stringifyByChar(array); + } + exports2.applyFromCharCode = arrayLikeToString; + function arrayLikeToArrayLike(arrayFrom, arrayTo) { + for (var i = 0;i < arrayFrom.length; i++) { + arrayTo[i] = arrayFrom[i]; + } + return arrayTo; + } + var transform2 = {}; + transform2["string"] = { + string: identity, + array: function(input) { + return stringToArrayLike(input, new Array(input.length)); + }, + arraybuffer: function(input) { + return transform2["string"]["uint8array"](input).buffer; + }, + uint8array: function(input) { + return stringToArrayLike(input, new Uint8Array(input.length)); + }, + nodebuffer: function(input) { + return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length)); + } + }; + transform2["array"] = { + string: arrayLikeToString, + array: identity, + arraybuffer: function(input) { + return new Uint8Array(input).buffer; + }, + uint8array: function(input) { + return new Uint8Array(input); + }, + nodebuffer: function(input) { + return nodejsUtils.newBufferFrom(input); + } + }; + transform2["arraybuffer"] = { + string: function(input) { + return arrayLikeToString(new Uint8Array(input)); + }, + array: function(input) { + return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); + }, + arraybuffer: identity, + uint8array: function(input) { + return new Uint8Array(input); + }, + nodebuffer: function(input) { + return nodejsUtils.newBufferFrom(new Uint8Array(input)); + } + }; + transform2["uint8array"] = { + string: arrayLikeToString, + array: function(input) { + return arrayLikeToArrayLike(input, new Array(input.length)); + }, + arraybuffer: function(input) { + return input.buffer; + }, + uint8array: identity, + nodebuffer: function(input) { + return nodejsUtils.newBufferFrom(input); + } + }; + transform2["nodebuffer"] = { + string: arrayLikeToString, + array: function(input) { + return arrayLikeToArrayLike(input, new Array(input.length)); + }, + arraybuffer: function(input) { + return transform2["nodebuffer"]["uint8array"](input).buffer; + }, + uint8array: function(input) { + return arrayLikeToArrayLike(input, new Uint8Array(input.length)); + }, + nodebuffer: identity + }; + exports2.transformTo = function(outputType, input) { + if (!input) { + input = ""; + } + if (!outputType) { + return input; + } + exports2.checkSupport(outputType); + var inputType = exports2.getTypeOf(input); + var result = transform2[inputType][outputType](input); + return result; + }; + exports2.resolve = function(path) { + var parts = path.split("/"); + var result = []; + for (var index2 = 0;index2 < parts.length; index2++) { + var part = parts[index2]; + if (part === "." || part === "" && index2 !== 0 && index2 !== parts.length - 1) { + continue; + } else if (part === "..") { + result.pop(); + } else { + result.push(part); + } + } + return result.join("/"); + }; + exports2.getTypeOf = function(input) { + if (typeof input === "string") { + return "string"; + } + if (Object.prototype.toString.call(input) === "[object Array]") { + return "array"; + } + if (support.nodebuffer && nodejsUtils.isBuffer(input)) { + return "nodebuffer"; + } + if (support.uint8array && input instanceof Uint8Array) { + return "uint8array"; + } + if (support.arraybuffer && input instanceof ArrayBuffer) { + return "arraybuffer"; + } + }; + exports2.checkSupport = function(type) { + var supported = support[type.toLowerCase()]; + if (!supported) { + throw new Error(type + " is not supported by this platform"); + } + }; + exports2.MAX_VALUE_16BITS = 65535; + exports2.MAX_VALUE_32BITS = -1; + exports2.pretty = function(str) { + var res = "", code, i; + for (i = 0;i < (str || "").length; i++) { + code = str.charCodeAt(i); + res += "\\x" + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); + } + return res; + }; + exports2.delay = function(callback, args, self2) { + setImmediate(function() { + callback.apply(self2 || null, args || []); + }); + }; + exports2.inherits = function(ctor, superCtor) { + var Obj = function() { + }; + Obj.prototype = superCtor.prototype; + ctor.prototype = new Obj; + }; + exports2.extend = function() { + var result = {}, i, attr; + for (i = 0;i < arguments.length; i++) { + for (attr in arguments[i]) { + if (Object.prototype.hasOwnProperty.call(arguments[i], attr) && typeof result[attr] === "undefined") { + result[attr] = arguments[i][attr]; + } + } + } + return result; + }; + exports2.prepareContent = function(name2, inputData, isBinary, isOptimizedBinaryString, isBase64) { + var promise = external.Promise.resolve(inputData).then(function(data2) { + var isBlob = support.blob && (data2 instanceof Blob || ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(data2)) !== -1); + if (isBlob && typeof FileReader !== "undefined") { + return new external.Promise(function(resolve, reject2) { + var reader = new FileReader; + reader.onload = function(e) { + resolve(e.target.result); + }; + reader.onerror = function(e) { + reject2(e.target.error); + }; + reader.readAsArrayBuffer(data2); + }); + } else { + return data2; + } + }); + return promise.then(function(data2) { + var dataType = exports2.getTypeOf(data2); + if (!dataType) { + return external.Promise.reject(new Error("Can't read the data of '" + name2 + "'. Is it " + "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")); + } + if (dataType === "arraybuffer") { + data2 = exports2.transformTo("uint8array", data2); + } else if (dataType === "string") { + if (isBase64) { + data2 = base64.decode(data2); + } else if (isBinary) { + if (isOptimizedBinaryString !== true) { + data2 = string2binary(data2); + } + } + } + return data2; + }); + }; +}); + +// node_modules/jszip/lib/stream/GenericWorker.js +var require_GenericWorker = __commonJS((exports2, module2) => { + function GenericWorker(name2) { + this.name = name2 || "default"; + this.streamInfo = {}; + this.generatedError = null; + this.extraStreamInfo = {}; + this.isPaused = true; + this.isFinished = false; + this.isLocked = false; + this._listeners = { + data: [], + end: [], + error: [] + }; + this.previous = null; + } + GenericWorker.prototype = { + push: function(chunk) { + this.emit("data", chunk); + }, + end: function() { + if (this.isFinished) { + return false; + } + this.flush(); + try { + this.emit("end"); + this.cleanUp(); + this.isFinished = true; + } catch (e) { + this.emit("error", e); + } + return true; + }, + error: function(e) { + if (this.isFinished) { + return false; + } + if (this.isPaused) { + this.generatedError = e; + } else { + this.isFinished = true; + this.emit("error", e); + if (this.previous) { + this.previous.error(e); + } + this.cleanUp(); + } + return true; + }, + on: function(name2, listener) { + this._listeners[name2].push(listener); + return this; + }, + cleanUp: function() { + this.streamInfo = this.generatedError = this.extraStreamInfo = null; + this._listeners = []; + }, + emit: function(name2, arg) { + if (this._listeners[name2]) { + for (var i = 0;i < this._listeners[name2].length; i++) { + this._listeners[name2][i].call(this, arg); + } + } + }, + pipe: function(next) { + return next.registerPrevious(this); + }, + registerPrevious: function(previous) { + if (this.isLocked) { + throw new Error("The stream '" + this + "' has already been used."); + } + this.streamInfo = previous.streamInfo; + this.mergeStreamInfo(); + this.previous = previous; + var self2 = this; + previous.on("data", function(chunk) { + self2.processChunk(chunk); + }); + previous.on("end", function() { + self2.end(); + }); + previous.on("error", function(e) { + self2.error(e); + }); + return this; + }, + pause: function() { + if (this.isPaused || this.isFinished) { + return false; + } + this.isPaused = true; + if (this.previous) { + this.previous.pause(); + } + return true; + }, + resume: function() { + if (!this.isPaused || this.isFinished) { + return false; + } + this.isPaused = false; + var withError = false; + if (this.generatedError) { + this.error(this.generatedError); + withError = true; + } + if (this.previous) { + this.previous.resume(); + } + return !withError; + }, + flush: function() { + }, + processChunk: function(chunk) { + this.push(chunk); + }, + withStreamInfo: function(key2, value2) { + this.extraStreamInfo[key2] = value2; + this.mergeStreamInfo(); + return this; + }, + mergeStreamInfo: function() { + for (var key2 in this.extraStreamInfo) { + if (!Object.prototype.hasOwnProperty.call(this.extraStreamInfo, key2)) { + continue; + } + this.streamInfo[key2] = this.extraStreamInfo[key2]; + } + }, + lock: function() { + if (this.isLocked) { + throw new Error("The stream '" + this + "' has already been used."); + } + this.isLocked = true; + if (this.previous) { + this.previous.lock(); + } + }, + toString: function() { + var me = "Worker " + this.name; + if (this.previous) { + return this.previous + " -> " + me; + } else { + return me; + } + } + }; + module2.exports = GenericWorker; +}); + +// node_modules/jszip/lib/utf8.js +var require_utf8 = __commonJS((exports2) => { + var utils = require_utils(); + var support = require_support(); + var nodejsUtils = require_nodejsUtils(); + var GenericWorker = require_GenericWorker(); + var _utf8len = new Array(256); + for (i = 0;i < 256; i++) { + _utf8len[i] = i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1; + } + var i; + _utf8len[254] = _utf8len[254] = 1; + var string2buf = function(str) { + var buf, c, c2, m_pos, i2, str_len = str.length, buf_len = 0; + for (m_pos = 0;m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4; + } + if (support.uint8array) { + buf = new Uint8Array(buf_len); + } else { + buf = new Array(buf_len); + } + for (i2 = 0, m_pos = 0;i2 < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + if (c < 128) { + buf[i2++] = c; + } else if (c < 2048) { + buf[i2++] = 192 | c >>> 6; + buf[i2++] = 128 | c & 63; + } else if (c < 65536) { + buf[i2++] = 224 | c >>> 12; + buf[i2++] = 128 | c >>> 6 & 63; + buf[i2++] = 128 | c & 63; + } else { + buf[i2++] = 240 | c >>> 18; + buf[i2++] = 128 | c >>> 12 & 63; + buf[i2++] = 128 | c >>> 6 & 63; + buf[i2++] = 128 | c & 63; + } + } + return buf; + }; + var utf8border = function(buf, max) { + var pos; + max = max || buf.length; + if (max > buf.length) { + max = buf.length; + } + pos = max - 1; + while (pos >= 0 && (buf[pos] & 192) === 128) { + pos--; + } + if (pos < 0) { + return max; + } + if (pos === 0) { + return max; + } + return pos + _utf8len[buf[pos]] > max ? pos : max; + }; + var buf2string = function(buf) { + var i2, out, c, c_len; + var len = buf.length; + var utf16buf = new Array(len * 2); + for (out = 0, i2 = 0;i2 < len; ) { + c = buf[i2++]; + if (c < 128) { + utf16buf[out++] = c; + continue; + } + c_len = _utf8len[c]; + if (c_len > 4) { + utf16buf[out++] = 65533; + i2 += c_len - 1; + continue; + } + c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7; + while (c_len > 1 && i2 < len) { + c = c << 6 | buf[i2++] & 63; + c_len--; + } + if (c_len > 1) { + utf16buf[out++] = 65533; + continue; + } + if (c < 65536) { + utf16buf[out++] = c; + } else { + c -= 65536; + utf16buf[out++] = 55296 | c >> 10 & 1023; + utf16buf[out++] = 56320 | c & 1023; + } + } + if (utf16buf.length !== out) { + if (utf16buf.subarray) { + utf16buf = utf16buf.subarray(0, out); + } else { + utf16buf.length = out; + } + } + return utils.applyFromCharCode(utf16buf); + }; + exports2.utf8encode = function utf8encode(str) { + if (support.nodebuffer) { + return nodejsUtils.newBufferFrom(str, "utf-8"); + } + return string2buf(str); + }; + exports2.utf8decode = function utf8decode(buf) { + if (support.nodebuffer) { + return utils.transformTo("nodebuffer", buf).toString("utf-8"); + } + buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf); + return buf2string(buf); + }; + function Utf8DecodeWorker() { + GenericWorker.call(this, "utf-8 decode"); + this.leftOver = null; + } + utils.inherits(Utf8DecodeWorker, GenericWorker); + Utf8DecodeWorker.prototype.processChunk = function(chunk) { + var data2 = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data); + if (this.leftOver && this.leftOver.length) { + if (support.uint8array) { + var previousData = data2; + data2 = new Uint8Array(previousData.length + this.leftOver.length); + data2.set(this.leftOver, 0); + data2.set(previousData, this.leftOver.length); + } else { + data2 = this.leftOver.concat(data2); + } + this.leftOver = null; + } + var nextBoundary = utf8border(data2); + var usableData = data2; + if (nextBoundary !== data2.length) { + if (support.uint8array) { + usableData = data2.subarray(0, nextBoundary); + this.leftOver = data2.subarray(nextBoundary, data2.length); + } else { + usableData = data2.slice(0, nextBoundary); + this.leftOver = data2.slice(nextBoundary, data2.length); + } + } + this.push({ + data: exports2.utf8decode(usableData), + meta: chunk.meta + }); + }; + Utf8DecodeWorker.prototype.flush = function() { + if (this.leftOver && this.leftOver.length) { + this.push({ + data: exports2.utf8decode(this.leftOver), + meta: {} + }); + this.leftOver = null; + } + }; + exports2.Utf8DecodeWorker = Utf8DecodeWorker; + function Utf8EncodeWorker() { + GenericWorker.call(this, "utf-8 encode"); + } + utils.inherits(Utf8EncodeWorker, GenericWorker); + Utf8EncodeWorker.prototype.processChunk = function(chunk) { + this.push({ + data: exports2.utf8encode(chunk.data), + meta: chunk.meta + }); + }; + exports2.Utf8EncodeWorker = Utf8EncodeWorker; +}); + +// node_modules/jszip/lib/stream/ConvertWorker.js +var require_ConvertWorker = __commonJS((exports2, module2) => { + var GenericWorker = require_GenericWorker(); + var utils = require_utils(); + function ConvertWorker(destType) { + GenericWorker.call(this, "ConvertWorker to " + destType); + this.destType = destType; + } + utils.inherits(ConvertWorker, GenericWorker); + ConvertWorker.prototype.processChunk = function(chunk) { + this.push({ + data: utils.transformTo(this.destType, chunk.data), + meta: chunk.meta + }); + }; + module2.exports = ConvertWorker; +}); + +// node_modules/jszip/lib/nodejs/NodejsStreamOutputAdapter.js +var require_NodejsStreamOutputAdapter = __commonJS((exports2, module2) => { + var Readable = (init_stream(), __toCommonJS(exports_stream)).Readable; + var utils = require_utils(); + utils.inherits(NodejsStreamOutputAdapter, Readable); + function NodejsStreamOutputAdapter(helper, options, updateCb) { + Readable.call(this, options); + this._helper = helper; + var self2 = this; + helper.on("data", function(data2, meta) { + if (!self2.push(data2)) { + self2._helper.pause(); + } + if (updateCb) { + updateCb(meta); + } + }).on("error", function(e) { + self2.emit("error", e); + }).on("end", function() { + self2.push(null); + }); + } + NodejsStreamOutputAdapter.prototype._read = function() { + this._helper.resume(); + }; + module2.exports = NodejsStreamOutputAdapter; +}); + +// node_modules/jszip/lib/stream/StreamHelper.js +var require_StreamHelper = __commonJS((exports2, module2) => { + var utils = require_utils(); + var ConvertWorker = require_ConvertWorker(); + var GenericWorker = require_GenericWorker(); + var base64 = require_base64(); + var support = require_support(); + var external = require_external(); + var NodejsStreamOutputAdapter = null; + if (support.nodestream) { + try { + NodejsStreamOutputAdapter = require_NodejsStreamOutputAdapter(); + } catch (e) { + } + } + function transformZipOutput(type, content2, mimeType) { + switch (type) { + case "blob": + return utils.newBlob(utils.transformTo("arraybuffer", content2), mimeType); + case "base64": + return base64.encode(content2); + default: + return utils.transformTo(type, content2); + } + } + function concat(type, dataArray) { + var i, index2 = 0, res = null, totalLength = 0; + for (i = 0;i < dataArray.length; i++) { + totalLength += dataArray[i].length; + } + switch (type) { + case "string": + return dataArray.join(""); + case "array": + return Array.prototype.concat.apply([], dataArray); + case "uint8array": + res = new Uint8Array(totalLength); + for (i = 0;i < dataArray.length; i++) { + res.set(dataArray[i], index2); + index2 += dataArray[i].length; + } + return res; + case "nodebuffer": + return Buffer.concat(dataArray); + default: + throw new Error("concat : unsupported type '" + type + "'"); + } + } + function accumulate(helper, updateCallback) { + return new external.Promise(function(resolve, reject2) { + var dataArray = []; + var { _internalType: chunkType, _outputType: resultType, _mimeType: mimeType } = helper; + helper.on("data", function(data2, meta) { + dataArray.push(data2); + if (updateCallback) { + updateCallback(meta); + } + }).on("error", function(err) { + dataArray = []; + reject2(err); + }).on("end", function() { + try { + var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType); + resolve(result); + } catch (e) { + reject2(e); + } + dataArray = []; + }).resume(); + }); + } + function StreamHelper(worker, outputType, mimeType) { + var internalType = outputType; + switch (outputType) { + case "blob": + case "arraybuffer": + internalType = "uint8array"; + break; + case "base64": + internalType = "string"; + break; + } + try { + this._internalType = internalType; + this._outputType = outputType; + this._mimeType = mimeType; + utils.checkSupport(internalType); + this._worker = worker.pipe(new ConvertWorker(internalType)); + worker.lock(); + } catch (e) { + this._worker = new GenericWorker("error"); + this._worker.error(e); + } + } + StreamHelper.prototype = { + accumulate: function(updateCb) { + return accumulate(this, updateCb); + }, + on: function(evt, fn) { + var self2 = this; + if (evt === "data") { + this._worker.on(evt, function(chunk) { + fn.call(self2, chunk.data, chunk.meta); + }); + } else { + this._worker.on(evt, function() { + utils.delay(fn, arguments, self2); + }); + } + return this; + }, + resume: function() { + utils.delay(this._worker.resume, [], this._worker); + return this; + }, + pause: function() { + this._worker.pause(); + return this; + }, + toNodejsStream: function(updateCb) { + utils.checkSupport("nodestream"); + if (this._outputType !== "nodebuffer") { + throw new Error(this._outputType + " is not supported by this method"); + } + return new NodejsStreamOutputAdapter(this, { + objectMode: this._outputType !== "nodebuffer" + }, updateCb); + } + }; + module2.exports = StreamHelper; +}); + +// node_modules/jszip/lib/defaults.js +var require_defaults = __commonJS((exports2) => { + exports2.base64 = false; + exports2.binary = false; + exports2.dir = false; + exports2.createFolders = true; + exports2.date = null; + exports2.compression = null; + exports2.compressionOptions = null; + exports2.comment = null; + exports2.unixPermissions = null; + exports2.dosPermissions = null; +}); + +// node_modules/jszip/lib/stream/DataWorker.js +var require_DataWorker = __commonJS((exports2, module2) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var DEFAULT_BLOCK_SIZE = 16 * 1024; + function DataWorker(dataP) { + GenericWorker.call(this, "DataWorker"); + var self2 = this; + this.dataIsReady = false; + this.index = 0; + this.max = 0; + this.data = null; + this.type = ""; + this._tickScheduled = false; + dataP.then(function(data2) { + self2.dataIsReady = true; + self2.data = data2; + self2.max = data2 && data2.length || 0; + self2.type = utils.getTypeOf(data2); + if (!self2.isPaused) { + self2._tickAndRepeat(); + } + }, function(e) { + self2.error(e); + }); + } + utils.inherits(DataWorker, GenericWorker); + DataWorker.prototype.cleanUp = function() { + GenericWorker.prototype.cleanUp.call(this); + this.data = null; + }; + DataWorker.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) { + return false; + } + if (!this._tickScheduled && this.dataIsReady) { + this._tickScheduled = true; + utils.delay(this._tickAndRepeat, [], this); + } + return true; + }; + DataWorker.prototype._tickAndRepeat = function() { + this._tickScheduled = false; + if (this.isPaused || this.isFinished) { + return; + } + this._tick(); + if (!this.isFinished) { + utils.delay(this._tickAndRepeat, [], this); + this._tickScheduled = true; + } + }; + DataWorker.prototype._tick = function() { + if (this.isPaused || this.isFinished) { + return false; + } + var size = DEFAULT_BLOCK_SIZE; + var data2 = null, nextIndex = Math.min(this.max, this.index + size); + if (this.index >= this.max) { + return this.end(); + } else { + switch (this.type) { + case "string": + data2 = this.data.substring(this.index, nextIndex); + break; + case "uint8array": + data2 = this.data.subarray(this.index, nextIndex); + break; + case "array": + case "nodebuffer": + data2 = this.data.slice(this.index, nextIndex); + break; + } + this.index = nextIndex; + return this.push({ + data: data2, + meta: { + percent: this.max ? this.index / this.max * 100 : 0 + } + }); + } + }; + module2.exports = DataWorker; +}); + +// node_modules/jszip/lib/crc32.js +var require_crc32 = __commonJS((exports2, module2) => { + var utils = require_utils(); + function makeTable() { + var c, table = []; + for (var n = 0;n < 256; n++) { + c = n; + for (var k2 = 0;k2 < 8; k2++) { + c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; + } + table[n] = c; + } + return table; + } + var crcTable = makeTable(); + function crc32(crc, buf, len, pos) { + var t = crcTable, end = pos + len; + crc = crc ^ -1; + for (var i = pos;i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255]; + } + return crc ^ -1; + } + function crc32str(crc, str, len, pos) { + var t = crcTable, end = pos + len; + crc = crc ^ -1; + for (var i = pos;i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ str.charCodeAt(i)) & 255]; + } + return crc ^ -1; + } + module2.exports = function crc32wrapper(input, crc) { + if (typeof input === "undefined" || !input.length) { + return 0; + } + var isArray2 = utils.getTypeOf(input) !== "string"; + if (isArray2) { + return crc32(crc | 0, input, input.length, 0); + } else { + return crc32str(crc | 0, input, input.length, 0); + } + }; +}); + +// node_modules/jszip/lib/stream/Crc32Probe.js +var require_Crc32Probe = __commonJS((exports2, module2) => { + var GenericWorker = require_GenericWorker(); + var crc32 = require_crc32(); + var utils = require_utils(); + function Crc32Probe() { + GenericWorker.call(this, "Crc32Probe"); + this.withStreamInfo("crc32", 0); + } + utils.inherits(Crc32Probe, GenericWorker); + Crc32Probe.prototype.processChunk = function(chunk) { + this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0); + this.push(chunk); + }; + module2.exports = Crc32Probe; +}); + +// node_modules/jszip/lib/stream/DataLengthProbe.js +var require_DataLengthProbe = __commonJS((exports2, module2) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + function DataLengthProbe(propName) { + GenericWorker.call(this, "DataLengthProbe for " + propName); + this.propName = propName; + this.withStreamInfo(propName, 0); + } + utils.inherits(DataLengthProbe, GenericWorker); + DataLengthProbe.prototype.processChunk = function(chunk) { + if (chunk) { + var length2 = this.streamInfo[this.propName] || 0; + this.streamInfo[this.propName] = length2 + chunk.data.length; + } + GenericWorker.prototype.processChunk.call(this, chunk); + }; + module2.exports = DataLengthProbe; +}); + +// node_modules/jszip/lib/compressedObject.js +var require_compressedObject = __commonJS((exports2, module2) => { + var external = require_external(); + var DataWorker = require_DataWorker(); + var Crc32Probe = require_Crc32Probe(); + var DataLengthProbe = require_DataLengthProbe(); + function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data2) { + this.compressedSize = compressedSize; + this.uncompressedSize = uncompressedSize; + this.crc32 = crc32; + this.compression = compression; + this.compressedContent = data2; + } + CompressedObject.prototype = { + getContentWorker: function() { + var worker = new DataWorker(external.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new DataLengthProbe("data_length")); + var that = this; + worker.on("end", function() { + if (this.streamInfo["data_length"] !== that.uncompressedSize) { + throw new Error("Bug : uncompressed data size mismatch"); + } + }); + return worker; + }, + getCompressedWorker: function() { + return new DataWorker(external.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression); + } + }; + CompressedObject.createWorkerFrom = function(uncompressedWorker, compression, compressionOptions) { + return uncompressedWorker.pipe(new Crc32Probe).pipe(new DataLengthProbe("uncompressedSize")).pipe(compression.compressWorker(compressionOptions)).pipe(new DataLengthProbe("compressedSize")).withStreamInfo("compression", compression); + }; + module2.exports = CompressedObject; +}); + +// node_modules/jszip/lib/zipObject.js +var require_zipObject = __commonJS((exports2, module2) => { + var StreamHelper = require_StreamHelper(); + var DataWorker = require_DataWorker(); + var utf8 = require_utf8(); + var CompressedObject = require_compressedObject(); + var GenericWorker = require_GenericWorker(); + var ZipObject = function(name2, data2, options) { + this.name = name2; + this.dir = options.dir; + this.date = options.date; + this.comment = options.comment; + this.unixPermissions = options.unixPermissions; + this.dosPermissions = options.dosPermissions; + this._data = data2; + this._dataBinary = options.binary; + this.options = { + compression: options.compression, + compressionOptions: options.compressionOptions + }; + }; + ZipObject.prototype = { + internalStream: function(type) { + var result = null, outputType = "string"; + try { + if (!type) { + throw new Error("No output type specified."); + } + outputType = type.toLowerCase(); + var askUnicodeString = outputType === "string" || outputType === "text"; + if (outputType === "binarystring" || outputType === "text") { + outputType = "string"; + } + result = this._decompressWorker(); + var isUnicodeString = !this._dataBinary; + if (isUnicodeString && !askUnicodeString) { + result = result.pipe(new utf8.Utf8EncodeWorker); + } + if (!isUnicodeString && askUnicodeString) { + result = result.pipe(new utf8.Utf8DecodeWorker); + } + } catch (e) { + result = new GenericWorker("error"); + result.error(e); + } + return new StreamHelper(result, outputType, ""); + }, + async: function(type, onUpdate) { + return this.internalStream(type).accumulate(onUpdate); + }, + nodeStream: function(type, onUpdate) { + return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate); + }, + _compressWorker: function(compression, compressionOptions) { + if (this._data instanceof CompressedObject && this._data.compression.magic === compression.magic) { + return this._data.getCompressedWorker(); + } else { + var result = this._decompressWorker(); + if (!this._dataBinary) { + result = result.pipe(new utf8.Utf8EncodeWorker); + } + return CompressedObject.createWorkerFrom(result, compression, compressionOptions); + } + }, + _decompressWorker: function() { + if (this._data instanceof CompressedObject) { + return this._data.getContentWorker(); + } else if (this._data instanceof GenericWorker) { + return this._data; + } else { + return new DataWorker(this._data); + } + } + }; + var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"]; + var removedFn = function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }; + for (i = 0;i < removedMethods.length; i++) { + ZipObject.prototype[removedMethods[i]] = removedFn; + } + var i; + module2.exports = ZipObject; +}); + +// node_modules/pako/lib/utils/common.js +var require_common = __commonJS((exports2) => { + var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined"; + function _has(obj, key2) { + return Object.prototype.hasOwnProperty.call(obj, key2); + } + exports2.assign = function(obj) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { + continue; + } + if (typeof source !== "object") { + throw new TypeError(source + "must be non-object"); + } + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + return obj; + }; + exports2.shrinkBuf = function(buf, size) { + if (buf.length === size) { + return buf; + } + if (buf.subarray) { + return buf.subarray(0, size); + } + buf.length = size; + return buf; + }; + var fnTyped = { + arraySet: function(dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + for (var i = 0;i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + flattenChunks: function(chunks) { + var i, l, len, pos, chunk, result; + len = 0; + for (i = 0, l = chunks.length;i < l; i++) { + len += chunks[i].length; + } + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length;i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + return result; + } + }; + var fnUntyped = { + arraySet: function(dest, src, src_offs, len, dest_offs) { + for (var i = 0;i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + flattenChunks: function(chunks) { + return [].concat.apply([], chunks); + } + }; + exports2.setTyped = function(on) { + if (on) { + exports2.Buf8 = Uint8Array; + exports2.Buf16 = Uint16Array; + exports2.Buf32 = Int32Array; + exports2.assign(exports2, fnTyped); + } else { + exports2.Buf8 = Array; + exports2.Buf16 = Array; + exports2.Buf32 = Array; + exports2.assign(exports2, fnUntyped); + } + }; + exports2.setTyped(TYPED_OK); +}); + +// node_modules/pako/lib/zlib/trees.js +var require_trees = __commonJS((exports2) => { + var utils = require_common(); + var Z_FIXED = 4; + var Z_BINARY = 0; + var Z_TEXT = 1; + var Z_UNKNOWN = 2; + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + var STORED_BLOCK = 0; + var STATIC_TREES = 1; + var DYN_TREES = 2; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var Buf_size = 16; + var MAX_BL_BITS = 7; + var END_BLOCK = 256; + var REP_3_6 = 16; + var REPZ_3_10 = 17; + var REPZ_11_138 = 18; + var 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]; + var 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]; + var extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]; + var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + var DIST_CODE_LEN = 512; + var static_ltree = new Array((L_CODES + 2) * 2); + zero(static_ltree); + var static_dtree = new Array(D_CODES * 2); + zero(static_dtree); + var _dist_code = new Array(DIST_CODE_LEN); + zero(_dist_code); + var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); + zero(_length_code); + var base_length = new Array(LENGTH_CODES); + zero(base_length); + var base_dist = new Array(D_CODES); + zero(base_dist); + function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + this.static_tree = static_tree; + this.extra_bits = extra_bits; + this.extra_base = extra_base; + this.elems = elems; + this.max_length = max_length; + this.has_stree = static_tree && static_tree.length; + } + var static_l_desc; + var static_d_desc; + var static_bl_desc; + function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; + this.max_code = 0; + this.stat_desc = stat_desc; + } + function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; + } + function put_short(s, w) { + s.pending_buf[s.pending++] = w & 255; + s.pending_buf[s.pending++] = w >>> 8 & 255; + } + function send_bits(s, value2, length2) { + if (s.bi_valid > Buf_size - length2) { + s.bi_buf |= value2 << s.bi_valid & 65535; + put_short(s, s.bi_buf); + s.bi_buf = value2 >> Buf_size - s.bi_valid; + s.bi_valid += length2 - Buf_size; + } else { + s.bi_buf |= value2 << s.bi_valid & 65535; + s.bi_valid += length2; + } + } + function send_code(s, c, tree) { + send_bits(s, tree[c * 2], tree[c * 2 + 1]); + } + function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; + } + function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 255; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } + } + function gen_bitlen(s, desc) { + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; + var n, m; + var bits; + var xbits; + var f; + var overflow = 0; + for (bits = 0;bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + tree[s.heap[s.heap_max] * 2 + 1] = 0; + for (h = s.heap_max + 1;h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1] = bits; + if (n > max_code) { + continue; + } + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1] + xbits); + } + } + if (overflow === 0) { + return; + } + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { + bits--; + } + s.bl_count[bits]--; + s.bl_count[bits + 1] += 2; + s.bl_count[max_length]--; + overflow -= 2; + } while (overflow > 0); + for (bits = max_length;bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { + continue; + } + if (tree[m * 2 + 1] !== bits) { + s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2]; + tree[m * 2 + 1] = bits; + } + n--; + } + } + } + function gen_codes(tree, max_code, bl_count) { + var next_code = new Array(MAX_BITS + 1); + var code = 0; + var bits; + var n; + for (bits = 1;bits <= MAX_BITS; bits++) { + next_code[bits] = code = code + bl_count[bits - 1] << 1; + } + for (n = 0;n <= max_code; n++) { + var len = tree[n * 2 + 1]; + if (len === 0) { + continue; + } + tree[n * 2] = bi_reverse(next_code[len]++, len); + } + } + function tr_static_init() { + var n; + var bits; + var length2; + var code; + var dist; + var bl_count = new Array(MAX_BITS + 1); + length2 = 0; + for (code = 0;code < LENGTH_CODES - 1; code++) { + base_length[code] = length2; + for (n = 0;n < 1 << extra_lbits[code]; n++) { + _length_code[length2++] = code; + } + } + _length_code[length2 - 1] = code; + dist = 0; + for (code = 0;code < 16; code++) { + base_dist[code] = dist; + for (n = 0;n < 1 << extra_dbits[code]; n++) { + _dist_code[dist++] = code; + } + } + dist >>= 7; + for (;code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0;n < 1 << extra_dbits[code] - 7; n++) { + _dist_code[256 + dist++] = code; + } + } + for (bits = 0;bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1] = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1] = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + gen_codes(static_ltree, L_CODES + 1, bl_count); + for (n = 0;n < D_CODES; n++) { + static_dtree[n * 2 + 1] = 5; + static_dtree[n * 2] = bi_reverse(n, 5); + } + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + } + function init_block(s) { + var n; + for (n = 0;n < L_CODES; n++) { + s.dyn_ltree[n * 2] = 0; + } + for (n = 0;n < D_CODES; n++) { + s.dyn_dtree[n * 2] = 0; + } + for (n = 0;n < BL_CODES; n++) { + s.bl_tree[n * 2] = 0; + } + s.dyn_ltree[END_BLOCK * 2] = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; + } + function bi_windup(s) { + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; + } + function copy_block(s, buf, len, header) { + bi_windup(s); + if (header) { + put_short(s, len); + put_short(s, ~len); + } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; + } + function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return tree[_n2] < tree[_m2] || tree[_n2] === tree[_m2] && depth[n] <= depth[m]; + } + function pqdownheap(s, tree, k2) { + var v = s.heap[k2]; + var j = k2 << 1; + while (j <= s.heap_len) { + if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + if (smaller(tree, v, s.heap[j], s.depth)) { + break; + } + s.heap[k2] = s.heap[j]; + k2 = j; + j <<= 1; + } + s.heap[k2] = v; + } + function compress_block(s, ltree, dtree) { + var dist; + var lc; + var lx = 0; + var code; + var extra; + if (s.last_lit !== 0) { + do { + dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1]; + lc = s.pending_buf[s.l_buf + lx]; + lx++; + if (dist === 0) { + send_code(s, lc, ltree); + } else { + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); + } + dist--; + code = d_code(dist); + send_code(s, code, dtree); + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); + } + } + } while (lx < s.last_lit); + } + send_code(s, END_BLOCK, ltree); + } + function build_tree(s, desc) { + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; + var max_code = -1; + var node; + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + for (n = 0;n < elems; n++) { + if (tree[n * 2] !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + } else { + tree[n * 2 + 1] = 0; + } + } + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; + tree[node * 2] = 1; + s.depth[node] = 0; + s.opt_len--; + if (has_stree) { + s.static_len -= stree[node * 2 + 1]; + } + } + desc.max_code = max_code; + for (n = s.heap_len >> 1;n >= 1; n--) { + pqdownheap(s, tree, n); + } + node = elems; + do { + n = s.heap[1]; + s.heap[1] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1); + m = s.heap[1]; + s.heap[--s.heap_max] = n; + s.heap[--s.heap_max] = m; + tree[node * 2] = tree[n * 2] + tree[m * 2]; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1] = tree[m * 2 + 1] = node; + s.heap[1] = node++; + pqdownheap(s, tree, 1); + } while (s.heap_len >= 2); + s.heap[--s.heap_max] = s.heap[1]; + gen_bitlen(s, desc); + gen_codes(tree, max_code, s.bl_count); + } + function scan_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[0 * 2 + 1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1] = 65535; + for (n = 0;n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) { + continue; + } else if (count < min_count) { + s.bl_tree[curlen * 2] += count; + } else if (curlen !== 0) { + if (curlen !== prevlen) { + s.bl_tree[curlen * 2]++; + } + s.bl_tree[REP_3_6 * 2]++; + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]++; + } else { + s.bl_tree[REPZ_11_138 * 2]++; + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function send_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[0 * 2 + 1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + for (n = 0;n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) { + continue; + } else if (count < min_count) { + do { + send_code(s, curlen, s.bl_tree); + } while (--count !== 0); + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function build_bl_tree(s) { + var max_blindex; + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + build_tree(s, s.bl_desc); + for (max_blindex = BL_CODES - 1;max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1] !== 0) { + break; + } + } + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + return max_blindex; + } + function send_all_trees(s, lcodes, dcodes, blcodes) { + var rank; + send_bits(s, lcodes - 257, 5); + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); + for (rank = 0;rank < blcodes; rank++) { + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1], 3); + } + send_tree(s, s.dyn_ltree, lcodes - 1); + send_tree(s, s.dyn_dtree, dcodes - 1); + } + function detect_data_type(s) { + var black_mask = 4093624447; + var n; + for (n = 0;n <= 31; n++, black_mask >>>= 1) { + if (black_mask & 1 && s.dyn_ltree[n * 2] !== 0) { + return Z_BINARY; + } + } + if (s.dyn_ltree[9 * 2] !== 0 || s.dyn_ltree[10 * 2] !== 0 || s.dyn_ltree[13 * 2] !== 0) { + return Z_TEXT; + } + for (n = 32;n < LITERALS; n++) { + if (s.dyn_ltree[n * 2] !== 0) { + return Z_TEXT; + } + } + return Z_BINARY; + } + var static_init_done = false; + function _tr_init(s) { + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + s.bi_buf = 0; + s.bi_valid = 0; + init_block(s); + } + function _tr_stored_block(s, buf, stored_len, last2) { + send_bits(s, (STORED_BLOCK << 1) + (last2 ? 1 : 0), 3); + copy_block(s, buf, stored_len, true); + } + function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); + } + function _tr_flush_block(s, buf, stored_len, last2) { + var opt_lenb, static_lenb; + var max_blindex = 0; + if (s.level > 0) { + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + build_tree(s, s.l_desc); + build_tree(s, s.d_desc); + max_blindex = build_bl_tree(s); + opt_lenb = s.opt_len + 3 + 7 >>> 3; + static_lenb = s.static_len + 3 + 7 >>> 3; + if (static_lenb <= opt_lenb) { + opt_lenb = static_lenb; + } + } else { + opt_lenb = static_lenb = stored_len + 5; + } + if (stored_len + 4 <= opt_lenb && buf !== -1) { + _tr_stored_block(s, buf, stored_len, last2); + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + send_bits(s, (STATIC_TREES << 1) + (last2 ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + } else { + send_bits(s, (DYN_TREES << 1) + (last2 ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + init_block(s); + if (last2) { + bi_windup(s); + } + } + function _tr_tally(s, dist, lc) { + s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 255; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 255; + s.pending_buf[s.l_buf + s.last_lit] = lc & 255; + s.last_lit++; + if (dist === 0) { + s.dyn_ltree[lc * 2]++; + } else { + s.matches++; + dist--; + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]++; + s.dyn_dtree[d_code(dist) * 2]++; + } + return s.last_lit === s.lit_bufsize - 1; + } + exports2._tr_init = _tr_init; + exports2._tr_stored_block = _tr_stored_block; + exports2._tr_flush_block = _tr_flush_block; + exports2._tr_tally = _tr_tally; + exports2._tr_align = _tr_align; +}); + +// node_modules/pako/lib/zlib/adler32.js +var require_adler32 = __commonJS((exports2, module2) => { + function adler32(adler, buf, len, pos) { + var s1 = adler & 65535 | 0, s2 = adler >>> 16 & 65535 | 0, n = 0; + while (len !== 0) { + n = len > 2000 ? 2000 : len; + len -= n; + do { + s1 = s1 + buf[pos++] | 0; + s2 = s2 + s1 | 0; + } while (--n); + s1 %= 65521; + s2 %= 65521; + } + return s1 | s2 << 16 | 0; + } + module2.exports = adler32; +}); + +// node_modules/pako/lib/zlib/crc32.js +var require_crc322 = __commonJS((exports2, module2) => { + function makeTable() { + var c, table = []; + for (var n = 0;n < 256; n++) { + c = n; + for (var k2 = 0;k2 < 8; k2++) { + c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; + } + table[n] = c; + } + return table; + } + var crcTable = makeTable(); + function crc32(crc, buf, len, pos) { + var t = crcTable, end = pos + len; + crc ^= -1; + for (var i = pos;i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255]; + } + return crc ^ -1; + } + module2.exports = crc32; +}); + +// node_modules/pako/lib/zlib/messages.js +var require_messages = __commonJS((exports2, module2) => { + module2.exports = { + 2: "need dictionary", + 1: "stream end", + 0: "", + "-1": "file error", + "-2": "stream error", + "-3": "data error", + "-4": "insufficient memory", + "-5": "buffer error", + "-6": "incompatible version" + }; +}); + +// node_modules/pako/lib/zlib/deflate.js +var require_deflate = __commonJS((exports2) => { + var utils = require_common(); + var trees = require_trees(); + var adler32 = require_adler32(); + var crc32 = require_crc322(); + var msg = require_messages(); + var Z_NO_FLUSH = 0; + var Z_PARTIAL_FLUSH = 1; + var Z_FULL_FLUSH = 3; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_BUF_ERROR = -5; + var Z_DEFAULT_COMPRESSION = -1; + var Z_FILTERED = 1; + var Z_HUFFMAN_ONLY = 2; + var Z_RLE = 3; + var Z_FIXED = 4; + var Z_DEFAULT_STRATEGY = 0; + var Z_UNKNOWN = 2; + var Z_DEFLATED = 8; + var MAX_MEM_LEVEL = 9; + var MAX_WBITS = 15; + var DEF_MEM_LEVEL = 8; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1; + var PRESET_DICT = 32; + var INIT_STATE = 42; + var EXTRA_STATE = 69; + var NAME_STATE = 73; + var COMMENT_STATE = 91; + var HCRC_STATE = 103; + var BUSY_STATE = 113; + var FINISH_STATE = 666; + var BS_NEED_MORE = 1; + var BS_BLOCK_DONE = 2; + var BS_FINISH_STARTED = 3; + var BS_FINISH_DONE = 4; + var OS_CODE = 3; + function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; + } + function rank(f) { + return (f << 1) - (f > 4 ? 9 : 0); + } + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + function flush_pending(strm) { + var s = strm.state; + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { + return; + } + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } + } + function flush_block_only(s, last2) { + trees._tr_flush_block(s, s.block_start >= 0 ? s.block_start : -1, s.strstart - s.block_start, last2); + s.block_start = s.strstart; + flush_pending(s.strm); + } + function put_byte(s, b) { + s.pending_buf[s.pending++] = b; + } + function putShortMSB(s, b) { + s.pending_buf[s.pending++] = b >>> 8 & 255; + s.pending_buf[s.pending++] = b & 255; + } + function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + if (len > size) { + len = size; + } + if (len === 0) { + return 0; + } + strm.avail_in -= len; + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + strm.next_in += len; + strm.total_in += len; + return len; + } + function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; + var scan = s.strstart; + var match; + var len; + var best_len = s.prev_length; + var nice_match = s.nice_match; + var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0; + var _win = s.window; + var wmask = s.w_mask; + var prev = s.prev; + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + if (nice_match > s.lookahead) { + nice_match = s.lookahead; + } + do { + match = cur_match; + if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { + continue; + } + scan += 2; + match++; + do { + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; + } + function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + do { + more = s.window_size - s.lookahead - s.strstart; + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + s.block_start -= _w_size; + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + 1]) & s.hash_mask; + while (s.insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + } + function deflate_stored(s, flush) { + var max_block_size = 65535; + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + for (;; ) { + if (s.lookahead <= 1) { + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + s.strstart += s.lookahead; + s.lookahead = 0; + var max_start = s.block_start + max_block_size; + if (s.strstart === 0 || s.strstart >= max_start) { + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + if (s.strstart - s.block_start >= s.w_size - MIN_LOOKAHEAD) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.strstart > s.block_start) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_NEED_MORE; + } + function deflate_fast(s, flush) { + var hash_head; + var bflush; + for (;; ) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + if (hash_head !== 0 && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + } + if (s.match_length >= MIN_MATCH) { + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + if (s.match_length <= s.max_lazy_match && s.lookahead >= MIN_MATCH) { + s.match_length--; + do { + s.strstart++; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } while (--s.match_length !== 0); + s.strstart++; + } else { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + 1]) & s.hash_mask; + } + } else { + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_slow(s, flush) { + var hash_head; + var bflush; + var max_insert; + for (;; ) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + if (hash_head !== 0 && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + if (s.match_length <= 5 && (s.strategy === Z_FILTERED || s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096)) { + s.match_length = MIN_MATCH - 1; + } + } + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } else if (s.match_available) { + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + if (bflush) { + flush_block_only(s, false); + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + if (s.match_available) { + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_rle(s, flush) { + var bflush; + var prev; + var scan, strend; + var _win = s.window; + for (;; ) { + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + } + if (s.match_length >= MIN_MATCH) { + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_huff(s, flush) { + var bflush; + for (;; ) { + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; + } + } + s.match_length = 0; + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; + } + var configuration_table; + configuration_table = [ + new Config(0, 0, 0, 0, deflate_stored), + new Config(4, 4, 8, 4, deflate_fast), + new Config(4, 5, 16, 8, deflate_fast), + new Config(4, 6, 32, 32, deflate_fast), + new Config(4, 4, 16, 16, deflate_slow), + new Config(8, 16, 32, 32, deflate_slow), + new Config(8, 16, 128, 128, deflate_slow), + new Config(8, 32, 128, 256, deflate_slow), + new Config(32, 128, 258, 1024, deflate_slow), + new Config(32, 258, 258, 4096, deflate_slow) + ]; + function lm_init(s) { + s.window_size = 2 * s.w_size; + zero(s.head); + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; + } + function DeflateState() { + this.strm = null; + this.status = 0; + this.pending_buf = null; + this.pending_buf_size = 0; + this.pending_out = 0; + this.pending = 0; + this.wrap = 0; + this.gzhead = null; + this.gzindex = 0; + this.method = Z_DEFLATED; + this.last_flush = -1; + this.w_size = 0; + this.w_bits = 0; + this.w_mask = 0; + this.window = null; + this.window_size = 0; + this.prev = null; + this.head = null; + this.ins_h = 0; + this.hash_size = 0; + this.hash_bits = 0; + this.hash_mask = 0; + this.hash_shift = 0; + this.block_start = 0; + this.match_length = 0; + this.prev_match = 0; + this.match_available = 0; + this.strstart = 0; + this.match_start = 0; + this.lookahead = 0; + this.prev_length = 0; + this.max_chain_length = 0; + this.max_lazy_match = 0; + this.level = 0; + this.strategy = 0; + this.good_match = 0; + this.nice_match = 0; + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + this.l_desc = null; + this.d_desc = null; + this.bl_desc = null; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + this.heap = new utils.Buf16(2 * L_CODES + 1); + zero(this.heap); + this.heap_len = 0; + this.heap_max = 0; + this.depth = new utils.Buf16(2 * L_CODES + 1); + zero(this.depth); + this.l_buf = 0; + this.lit_bufsize = 0; + this.last_lit = 0; + this.d_buf = 0; + this.opt_len = 0; + this.static_len = 0; + this.matches = 0; + this.insert = 0; + this.bi_buf = 0; + this.bi_valid = 0; + } + function deflateResetKeep(strm) { + var s; + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + s = strm.state; + s.pending = 0; + s.pending_out = 0; + if (s.wrap < 0) { + s.wrap = -s.wrap; + } + s.status = s.wrap ? INIT_STATE : BUSY_STATE; + strm.adler = s.wrap === 2 ? 0 : 1; + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; + } + function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; + } + function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + if (strm.state.wrap !== 2) { + return Z_STREAM_ERROR; + } + strm.state.gzhead = head; + return Z_OK; + } + function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { + return Z_STREAM_ERROR; + } + var wrap = 1; + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else if (windowBits > 15) { + wrap = 2; + windowBits -= 16; + } + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + if (windowBits === 8) { + windowBits = 9; + } + var s = new DeflateState; + strm.state = s; + s.strm = strm; + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + s.lit_bufsize = 1 << memLevel + 6; + s.pending_buf_size = s.lit_bufsize * 4; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + s.d_buf = 1 * s.lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + s.level = level; + s.strategy = strategy; + s.method = method; + return deflateReset(strm); + } + function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); + } + function deflate(strm, flush) { + var old_flush, s; + var beg, val2; + if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + s = strm.state; + if (!strm.output || !strm.input && strm.avail_in !== 0 || s.status === FINISH_STATE && flush !== Z_FINISH) { + return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + s.strm = strm; + old_flush = s.last_flush; + s.last_flush = flush; + if (s.status === INIT_STATE) { + if (s.wrap === 2) { + strm.adler = 0; + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } else { + put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16)); + put_byte(s, s.gzhead.time & 255); + put_byte(s, s.gzhead.time >> 8 & 255); + put_byte(s, s.gzhead.time >> 16 & 255); + put_byte(s, s.gzhead.time >> 24 & 255); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, s.gzhead.os & 255); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 255); + put_byte(s, s.gzhead.extra.length >> 8 & 255); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } else { + var header = Z_DEFLATED + (s.w_bits - 8 << 4) << 8; + var level_flags = -1; + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= level_flags << 6; + if (s.strstart !== 0) { + header |= PRESET_DICT; + } + header += 31 - header % 31; + s.status = BUSY_STATE; + putShortMSB(s, header); + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + strm.adler = 1; + } + } + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra) { + beg = s.pending; + while (s.gzindex < (s.gzhead.extra.length & 65535)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 255); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val2 = 1; + break; + } + } + if (s.gzindex < s.gzhead.name.length) { + val2 = s.gzhead.name.charCodeAt(s.gzindex++) & 255; + } else { + val2 = 0; + } + put_byte(s, val2); + } while (val2 !== 0); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val2 === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val2 = 1; + break; + } + } + if (s.gzindex < s.gzhead.comment.length) { + val2 = s.gzhead.comment.charCodeAt(s.gzindex++) & 255; + } else { + val2 = 0; + } + put_byte(s, val2); + } while (val2 !== 0); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val2 === 0) { + s.status = HCRC_STATE; + } + } else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + strm.adler = 0; + s.status = BUSY_STATE; + } + } else { + s.status = BUSY_STATE; + } + } + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + if (strm.avail_in !== 0 || s.lookahead !== 0 || flush !== Z_NO_FLUSH && s.status !== FINISH_STATE) { + var bstate = s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush); + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + } + return Z_OK; + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } else if (flush !== Z_BLOCK) { + trees._tr_stored_block(s, 0, 0, false); + if (flush === Z_FULL_FLUSH) { + zero(s.head); + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } + } + if (flush !== Z_FINISH) { + return Z_OK; + } + if (s.wrap <= 0) { + return Z_STREAM_END; + } + if (s.wrap === 2) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + put_byte(s, strm.adler >> 16 & 255); + put_byte(s, strm.adler >> 24 & 255); + put_byte(s, strm.total_in & 255); + put_byte(s, strm.total_in >> 8 & 255); + put_byte(s, strm.total_in >> 16 & 255); + put_byte(s, strm.total_in >> 24 & 255); + } else { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + flush_pending(strm); + if (s.wrap > 0) { + s.wrap = -s.wrap; + } + return s.pending !== 0 ? Z_OK : Z_STREAM_END; + } + function deflateEnd(strm) { + var status; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + status = strm.state.status; + if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE) { + return err(strm, Z_STREAM_ERROR); + } + strm.state = null; + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; + } + function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + s = strm.state; + wrap = s.wrap; + if (wrap === 2 || wrap === 1 && s.status !== INIT_STATE || s.lookahead) { + return Z_STREAM_ERROR; + } + if (wrap === 1) { + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + s.wrap = 0; + if (dictLength >= s.w_size) { + if (wrap === 0) { + zero(s.head); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; + } + exports2.deflateInit = deflateInit; + exports2.deflateInit2 = deflateInit2; + exports2.deflateReset = deflateReset; + exports2.deflateResetKeep = deflateResetKeep; + exports2.deflateSetHeader = deflateSetHeader; + exports2.deflate = deflate; + exports2.deflateEnd = deflateEnd; + exports2.deflateSetDictionary = deflateSetDictionary; + exports2.deflateInfo = "pako deflate (from Nodeca project)"; +}); + +// node_modules/pako/lib/utils/strings.js +var require_strings = __commonJS((exports2) => { + var utils = require_common(); + var STR_APPLY_OK = true; + var STR_APPLY_UIA_OK = true; + try { + String.fromCharCode.apply(null, [0]); + } catch (__) { + STR_APPLY_OK = false; + } + try { + String.fromCharCode.apply(null, new Uint8Array(1)); + } catch (__) { + STR_APPLY_UIA_OK = false; + } + var _utf8len = new utils.Buf8(256); + for (q = 0;q < 256; q++) { + _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1; + } + var q; + _utf8len[254] = _utf8len[254] = 1; + exports2.string2buf = function(str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + for (m_pos = 0;m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4; + } + buf = new utils.Buf8(buf_len); + for (i = 0, m_pos = 0;i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + if (c < 128) { + buf[i++] = c; + } else if (c < 2048) { + buf[i++] = 192 | c >>> 6; + buf[i++] = 128 | c & 63; + } else if (c < 65536) { + buf[i++] = 224 | c >>> 12; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } else { + buf[i++] = 240 | c >>> 18; + buf[i++] = 128 | c >>> 12 & 63; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } + } + return buf; + }; + function buf2binstring(buf, len) { + if (len < 65534) { + if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + var result = ""; + for (var i = 0;i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; + } + exports2.buf2binstring = function(buf) { + return buf2binstring(buf, buf.length); + }; + exports2.binstring2buf = function(str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length;i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; + }; + exports2.buf2string = function(buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + var utf16buf = new Array(len * 2); + for (out = 0, i = 0;i < len; ) { + c = buf[i++]; + if (c < 128) { + utf16buf[out++] = c; + continue; + } + c_len = _utf8len[c]; + if (c_len > 4) { + utf16buf[out++] = 65533; + i += c_len - 1; + continue; + } + c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7; + while (c_len > 1 && i < len) { + c = c << 6 | buf[i++] & 63; + c_len--; + } + if (c_len > 1) { + utf16buf[out++] = 65533; + continue; + } + if (c < 65536) { + utf16buf[out++] = c; + } else { + c -= 65536; + utf16buf[out++] = 55296 | c >> 10 & 1023; + utf16buf[out++] = 56320 | c & 1023; + } + } + return buf2binstring(utf16buf, out); + }; + exports2.utf8border = function(buf, max) { + var pos; + max = max || buf.length; + if (max > buf.length) { + max = buf.length; + } + pos = max - 1; + while (pos >= 0 && (buf[pos] & 192) === 128) { + pos--; + } + if (pos < 0) { + return max; + } + if (pos === 0) { + return max; + } + return pos + _utf8len[buf[pos]] > max ? pos : max; + }; +}); + +// node_modules/pako/lib/zlib/zstream.js +var require_zstream = __commonJS((exports2, module2) => { + function ZStream() { + this.input = null; + this.next_in = 0; + this.avail_in = 0; + this.total_in = 0; + this.output = null; + this.next_out = 0; + this.avail_out = 0; + this.total_out = 0; + this.msg = ""; + this.state = null; + this.data_type = 2; + this.adler = 0; + } + module2.exports = ZStream; +}); + +// node_modules/pako/lib/deflate.js +var require_deflate2 = __commonJS((exports2) => { + var zlib_deflate = require_deflate(); + var utils = require_common(); + var strings = require_strings(); + var msg = require_messages(); + var ZStream = require_zstream(); + var toString2 = Object.prototype.toString; + var Z_NO_FLUSH = 0; + var Z_FINISH = 4; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_SYNC_FLUSH = 2; + var Z_DEFAULT_COMPRESSION = -1; + var Z_DEFAULT_STRATEGY = 0; + var Z_DEFLATED = 8; + function Deflate(options) { + if (!(this instanceof Deflate)) + return new Deflate(options); + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: "" + }, options || {}); + var opt = this.options; + if (opt.raw && opt.windowBits > 0) { + opt.windowBits = -opt.windowBits; + } else if (opt.gzip && opt.windowBits > 0 && opt.windowBits < 16) { + opt.windowBits += 16; + } + this.err = 0; + this.msg = ""; + this.ended = false; + this.chunks = []; + this.strm = new ZStream; + this.strm.avail_out = 0; + var status = zlib_deflate.deflateInit2(this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy); + if (status !== Z_OK) { + throw new Error(msg[status]); + } + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } + if (opt.dictionary) { + var dict; + if (typeof opt.dictionary === "string") { + dict = strings.string2buf(opt.dictionary); + } else if (toString2.call(opt.dictionary) === "[object ArrayBuffer]") { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + if (status !== Z_OK) { + throw new Error(msg[status]); + } + this._dict_set = true; + } + } + Deflate.prototype.push = function(data2, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + if (this.ended) { + return false; + } + _mode = mode === ~~mode ? mode : mode === true ? Z_FINISH : Z_NO_FLUSH; + if (typeof data2 === "string") { + strm.input = strings.string2buf(data2); + } else if (toString2.call(data2) === "[object ArrayBuffer]") { + strm.input = new Uint8Array(data2); + } else { + strm.input = data2; + } + strm.next_in = 0; + strm.avail_in = strm.input.length; + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH)) { + if (this.options.to === "string") { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + return true; + }; + Deflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); + }; + Deflate.prototype.onEnd = function(status) { + if (status === Z_OK) { + if (this.options.to === "string") { + this.result = this.chunks.join(""); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; + function deflate(input, options) { + var deflator = new Deflate(options); + deflator.push(input, true); + if (deflator.err) { + throw deflator.msg || msg[deflator.err]; + } + return deflator.result; + } + function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); + } + function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); + } + exports2.Deflate = Deflate; + exports2.deflate = deflate; + exports2.deflateRaw = deflateRaw; + exports2.gzip = gzip; +}); + +// node_modules/pako/lib/zlib/inffast.js +var require_inffast = __commonJS((exports2, module2) => { + var BAD = 30; + var TYPE = 12; + module2.exports = function inflate_fast(strm, start) { + var state; + var _in; + var last2; + var _out; + var beg; + var end; + var dmax; + var wsize; + var whave; + var wnext; + var s_window; + var hold; + var bits; + var lcode; + var dcode; + var lmask; + var dmask; + var here; + var op; + var len; + var dist; + var from; + var from_source; + var input, output; + state = strm.state; + _in = strm.next_in; + input = strm.input; + last2 = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); + dmax = state.dmax; + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + for (;; ) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op === 0) { + output[_out++] = here & 65535; + } else if (op & 16) { + len = here & 65535; + op &= 15; + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & (1 << op) - 1; + hold >>>= op; + bits -= op; + } + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + for (;; ) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op & 16) { + dist = here & 65535; + op &= 15; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & (1 << op) - 1; + if (dist > dmax) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break top; + } + hold >>>= op; + bits -= op; + op = _out - beg; + if (dist > op) { + op = dist - op; + if (op > whave) { + if (state.sane) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break top; + } + } + from = 0; + from_source = s_window; + if (wnext === 0) { + from += wsize - op; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } else if (wnext < op) { + from += wsize + wnext - op; + op -= wnext; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } + } else { + from += wnext - op; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } else { + from = _out - dist; + do { + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } else if ((op & 64) === 0) { + here = dcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dodist; + } else { + strm.msg = "invalid distance code"; + state.mode = BAD; + break top; + } + break; + } + } else if ((op & 64) === 0) { + here = lcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dolen; + } else if (op & 32) { + state.mode = TYPE; + break top; + } else { + strm.msg = "invalid literal/length code"; + state.mode = BAD; + break top; + } + break; + } + } while (_in < last2 && _out < end); + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = _in < last2 ? 5 + (last2 - _in) : 5 - (_in - last2); + strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); + state.hold = hold; + state.bits = bits; + return; + }; +}); + +// node_modules/pako/lib/zlib/inftrees.js +var require_inftrees = __commonJS((exports2, module2) => { + var utils = require_common(); + var MAXBITS = 15; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var lbase = [ + 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 + ]; + var lext = [ + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 17, + 17, + 17, + 17, + 18, + 18, + 18, + 18, + 19, + 19, + 19, + 19, + 20, + 20, + 20, + 20, + 21, + 21, + 21, + 21, + 16, + 72, + 78 + ]; + var dbase = [ + 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, + 0, + 0 + ]; + var dext = [ + 16, + 16, + 16, + 16, + 17, + 17, + 18, + 18, + 19, + 19, + 20, + 20, + 21, + 21, + 22, + 22, + 23, + 23, + 24, + 24, + 25, + 25, + 26, + 26, + 27, + 27, + 28, + 28, + 29, + 29, + 64, + 64 + ]; + module2.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { + var bits = opts.bits; + var len = 0; + var sym = 0; + var min = 0, max = 0; + var root = 0; + var curr = 0; + var drop2 = 0; + var left = 0; + var used = 0; + var huff = 0; + var incr; + var fill2; + var low; + var mask2; + var next; + var base = null; + var base_index = 0; + var end; + var count = new utils.Buf16(MAXBITS + 1); + var offs = new utils.Buf16(MAXBITS + 1); + var extra = null; + var extra_index = 0; + var here_bits, here_op, here_val; + for (len = 0;len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0;sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + root = bits; + for (max = MAXBITS;max >= 1; max--) { + if (count[max] !== 0) { + break; + } + } + if (root > max) { + root = max; + } + if (max === 0) { + table[table_index++] = 1 << 24 | 64 << 16 | 0; + table[table_index++] = 1 << 24 | 64 << 16 | 0; + opts.bits = 1; + return 0; + } + for (min = 1;min < max; min++) { + if (count[min] !== 0) { + break; + } + } + if (root < min) { + root = min; + } + left = 1; + for (len = 1;len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; + } + offs[1] = 0; + for (len = 1;len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + for (sym = 0;sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + if (type === CODES) { + base = extra = work; + end = 19; + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + } else { + base = dbase; + extra = dext; + end = -1; + } + huff = 0; + sym = 0; + len = min; + next = table_index; + curr = root; + drop2 = 0; + low = -1; + used = 1 << root; + mask2 = used - 1; + if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) { + return 1; + } + for (;; ) { + here_bits = len - drop2; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } else { + here_op = 32 + 64; + here_val = 0; + } + incr = 1 << len - drop2; + fill2 = 1 << curr; + min = fill2; + do { + fill2 -= incr; + table[next + (huff >> drop2) + fill2] = here_bits << 24 | here_op << 16 | here_val | 0; + } while (fill2 !== 0); + incr = 1 << len - 1; + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + sym++; + if (--count[len] === 0) { + if (len === max) { + break; + } + len = lens[lens_index + work[sym]]; + } + if (len > root && (huff & mask2) !== low) { + if (drop2 === 0) { + drop2 = root; + } + next += min; + curr = len - drop2; + left = 1 << curr; + while (curr + drop2 < max) { + left -= count[curr + drop2]; + if (left <= 0) { + break; + } + curr++; + left <<= 1; + } + used += 1 << curr; + if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) { + return 1; + } + low = huff & mask2; + table[low] = root << 24 | curr << 16 | next - table_index | 0; + } + } + if (huff !== 0) { + table[next + huff] = len - drop2 << 24 | 64 << 16 | 0; + } + opts.bits = root; + return 0; + }; +}); + +// node_modules/pako/lib/zlib/inflate.js +var require_inflate = __commonJS((exports2) => { + var utils = require_common(); + var adler32 = require_adler32(); + var crc32 = require_crc322(); + var inflate_fast = require_inffast(); + var inflate_table = require_inftrees(); + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_TREES = 6; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_NEED_DICT = 2; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_MEM_ERROR = -4; + var Z_BUF_ERROR = -5; + var Z_DEFLATED = 8; + var HEAD = 1; + var FLAGS = 2; + var TIME = 3; + var OS = 4; + var EXLEN = 5; + var EXTRA = 6; + var NAME = 7; + var COMMENT = 8; + var HCRC = 9; + var DICTID = 10; + var DICT = 11; + var TYPE = 12; + var TYPEDO = 13; + var STORED = 14; + var COPY_ = 15; + var COPY = 16; + var TABLE = 17; + var LENLENS = 18; + var CODELENS = 19; + var LEN_ = 20; + var LEN = 21; + var LENEXT = 22; + var DIST = 23; + var DISTEXT = 24; + var MATCH = 25; + var LIT = 26; + var CHECK = 27; + var LENGTH = 28; + var DONE = 29; + var BAD = 30; + var MEM = 31; + var SYNC = 32; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var MAX_WBITS = 15; + var DEF_WBITS = MAX_WBITS; + function zswap32(q) { + return (q >>> 24 & 255) + (q >>> 8 & 65280) + ((q & 65280) << 8) + ((q & 255) << 24); + } + function InflateState() { + this.mode = 0; + this.last = false; + this.wrap = 0; + this.havedict = false; + this.flags = 0; + this.dmax = 0; + this.check = 0; + this.total = 0; + this.head = null; + this.wbits = 0; + this.wsize = 0; + this.whave = 0; + this.wnext = 0; + this.window = null; + this.hold = 0; + this.bits = 0; + this.length = 0; + this.offset = 0; + this.extra = 0; + this.lencode = null; + this.distcode = null; + this.lenbits = 0; + this.distbits = 0; + this.ncode = 0; + this.nlen = 0; + this.ndist = 0; + this.have = 0; + this.next = null; + this.lens = new utils.Buf16(320); + this.work = new utils.Buf16(288); + this.lendyn = null; + this.distdyn = null; + this.sane = 0; + this.back = 0; + this.was = 0; + } + function inflateResetKeep(strm) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ""; + if (state.wrap) { + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null; + state.hold = 0; + state.bits = 0; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + state.sane = 1; + state.back = -1; + return Z_OK; + } + function inflateReset(strm) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + } + function inflateReset2(strm, windowBits) { + var wrap; + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); + } + function inflateInit2(strm, windowBits) { + var ret; + var state; + if (!strm) { + return Z_STREAM_ERROR; + } + state = new InflateState; + strm.state = state; + state.window = null; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null; + } + return ret; + } + function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); + } + var virgin = true; + var lenfix; + var distfix; + function fixedtables(state) { + if (virgin) { + var sym; + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + sym = 0; + while (sym < 144) { + state.lens[sym++] = 8; + } + while (sym < 256) { + state.lens[sym++] = 9; + } + while (sym < 280) { + state.lens[sym++] = 7; + } + while (sym < 288) { + state.lens[sym++] = 8; + } + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + sym = 0; + while (sym < 32) { + state.lens[sym++] = 5; + } + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + virgin = false; + } + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; + } + function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + state.window = new utils.Buf8(state.wsize); + } + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } else { + state.wnext += dist; + if (state.wnext === state.wsize) { + state.wnext = 0; + } + if (state.whave < state.wsize) { + state.whave += dist; + } + } + } + return 0; + } + function inflate(strm, flush) { + var state; + var input, output; + var next; + var put; + var have, left; + var hold; + var bits; + var _in, _out; + var copy; + var from; + var from_source; + var here = 0; + var here_bits, here_op, here_val; + var last_bits, last_op, last_val; + var len; + var ret; + var hbuf = new utils.Buf8(4); + var opts; + var n; + var order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (state.mode === TYPE) { + state.mode = TYPEDO; + } + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + _in = have; + _out = left; + ret = Z_OK; + inf_leave: + for (;; ) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.wrap & 2 && hold === 35615) { + state.check = 0; + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + hold = 0; + bits = 0; + state.mode = FLAGS; + break; + } + state.flags = 0; + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || (((hold & 255) << 8) + (hold >> 8)) % 31) { + strm.msg = "incorrect header check"; + state.mode = BAD; + break; + } + if ((hold & 15) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state.mode = BAD; + break; + } + hold >>>= 4; + bits -= 4; + len = (hold & 15) + 8; + if (state.wbits === 0) { + state.wbits = len; + } else if (len > state.wbits) { + strm.msg = "invalid window size"; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + strm.adler = state.check = 1; + state.mode = hold & 512 ? DICTID : TYPE; + hold = 0; + bits = 0; + break; + case FLAGS: + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.flags = hold; + if ((state.flags & 255) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state.mode = BAD; + break; + } + if (state.flags & 57344) { + strm.msg = "unknown header flags set"; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = hold >> 8 & 1; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state.mode = TIME; + case TIME: + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.head) { + state.head.time = hold; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + hbuf[2] = hold >>> 16 & 255; + hbuf[3] = hold >>> 24 & 255; + state.check = crc32(state.check, hbuf, 4, 0); + } + hold = 0; + bits = 0; + state.mode = OS; + case OS: + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.head) { + state.head.xflags = hold & 255; + state.head.os = hold >> 8; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state.mode = EXLEN; + case EXLEN: + if (state.flags & 1024) { + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + } else if (state.head) { + state.head.extra = null; + } + state.mode = EXTRA; + case EXTRA: + if (state.flags & 1024) { + copy = state.length; + if (copy > have) { + copy = have; + } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet(state.head.extra, input, next, copy, len); + } + if (state.flags & 512) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { + break inf_leave; + } + } + state.length = 0; + state.mode = NAME; + case NAME: + if (state.flags & 2048) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + len = input[next + copy++]; + if (state.head && len && state.length < 65536) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 512) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + case COMMENT: + if (state.flags & 4096) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + len = input[next + copy++]; + if (state.head && len && state.length < 65536) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 512) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + case HCRC: + if (state.flags & 512) { + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state.check & 65535)) { + strm.msg = "header crc mismatch"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + if (state.head) { + state.head.hcrc = state.flags >> 9 & 1; + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + strm.adler = state.check = zswap32(hold); + hold = 0; + bits = 0; + state.mode = DICT; + case DICT: + if (state.havedict === 0) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + return Z_NEED_DICT; + } + strm.adler = state.check = 1; + state.mode = TYPE; + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { + break inf_leave; + } + case TYPEDO: + if (state.last) { + hold >>>= bits & 7; + bits -= bits & 7; + state.mode = CHECK; + break; + } + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.last = hold & 1; + hold >>>= 1; + bits -= 1; + switch (hold & 3) { + case 0: + state.mode = STORED; + break; + case 1: + fixedtables(state); + state.mode = LEN_; + if (flush === Z_TREES) { + hold >>>= 2; + bits -= 2; + break inf_leave; + } + break; + case 2: + state.mode = TABLE; + break; + case 3: + strm.msg = "invalid block type"; + state.mode = BAD; + } + hold >>>= 2; + bits -= 2; + break; + case STORED: + hold >>>= bits & 7; + bits -= bits & 7; + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((hold & 65535) !== (hold >>> 16 ^ 65535)) { + strm.msg = "invalid stored block lengths"; + state.mode = BAD; + break; + } + state.length = hold & 65535; + hold = 0; + bits = 0; + state.mode = COPY_; + if (flush === Z_TREES) { + break inf_leave; + } + case COPY_: + state.mode = COPY; + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { + copy = have; + } + if (copy > left) { + copy = left; + } + if (copy === 0) { + break inf_leave; + } + utils.arraySet(output, input, next, copy, put); + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + state.mode = TYPE; + break; + case TABLE: + while (bits < 14) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.nlen = (hold & 31) + 257; + hold >>>= 5; + bits -= 5; + state.ndist = (hold & 31) + 1; + hold >>>= 5; + bits -= 5; + state.ncode = (hold & 15) + 4; + hold >>>= 4; + bits -= 4; + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = "too many length or distance symbols"; + state.mode = BAD; + break; + } + state.have = 0; + state.mode = LENLENS; + case LENLENS: + while (state.have < state.ncode) { + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.lens[order[state.have++]] = hold & 7; + hold >>>= 3; + bits -= 3; + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + state.lencode = state.lendyn; + state.lenbits = 7; + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid code lengths set"; + state.mode = BAD; + break; + } + state.have = 0; + state.mode = CODELENS; + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;; ) { + here = state.lencode[hold & (1 << state.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_val < 16) { + hold >>>= here_bits; + bits -= here_bits; + state.lens[state.have++] = here_val; + } else { + if (here_val === 16) { + n = here_bits + 2; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + if (state.have === 0) { + strm.msg = "invalid bit length repeat"; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 3); + hold >>>= 2; + bits -= 2; + } else if (here_val === 17) { + n = here_bits + 3; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy = 3 + (hold & 7); + hold >>>= 3; + bits -= 3; + } else { + n = here_bits + 7; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy = 11 + (hold & 127); + hold >>>= 7; + bits -= 7; + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = "invalid bit length repeat"; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + if (state.mode === BAD) { + break; + } + if (state.lens[256] === 0) { + strm.msg = "invalid code -- missing end-of-block"; + state.mode = BAD; + break; + } + state.lenbits = 9; + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid literal/lengths set"; + state.mode = BAD; + break; + } + state.distbits = 6; + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + state.distbits = opts.bits; + if (ret) { + strm.msg = "invalid distances set"; + state.mode = BAD; + break; + } + state.mode = LEN_; + if (flush === Z_TREES) { + break inf_leave; + } + case LEN_: + state.mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + inflate_fast(strm, _out); + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;; ) { + here = state.lencode[hold & (1 << state.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_op && (here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;; ) { + here = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + state.mode = LIT; + break; + } + if (here_op & 32) { + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = "invalid literal/length code"; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + case LENEXT: + if (state.extra) { + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.length += hold & (1 << state.extra) - 1; + hold >>>= state.extra; + bits -= state.extra; + state.back += state.extra; + } + state.was = state.length; + state.mode = DIST; + case DIST: + for (;; ) { + here = state.distcode[hold & (1 << state.distbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;; ) { + here = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state.back += here_bits; + if (here_op & 64) { + strm.msg = "invalid distance code"; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = here_op & 15; + state.mode = DISTEXT; + case DISTEXT: + if (state.extra) { + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.offset += hold & (1 << state.extra) - 1; + hold >>>= state.extra; + bits -= state.extra; + state.back += state.extra; + } + if (state.offset > state.dmax) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break; + } + state.mode = MATCH; + case MATCH: + if (left === 0) { + break inf_leave; + } + copy = _out - left; + if (state.offset > copy) { + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break; + } + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } else { + from = state.wnext - copy; + } + if (copy > state.length) { + copy = state.length; + } + from_source = state.window; + } else { + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { + copy = left; + } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { + state.mode = LEN; + } + break; + case LIT: + if (left === 0) { + break inf_leave; + } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold |= input[next++] << bits; + bits += 8; + } + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out); + } + _out = left; + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = "incorrect data check"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state.mode = LENGTH; + case LENGTH: + if (state.wrap && state.flags) { + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state.total & 4294967295)) { + strm.msg = "incorrect length check"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state.mode = DONE; + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + } + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + if (state.wsize || _out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH)) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if ((_in === 0 && _out === 0 || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; + } + function inflateEnd(strm) { + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; + } + function inflateGetHeader(strm, head) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if ((state.wrap & 2) === 0) { + return Z_STREAM_ERROR; + } + state.head = head; + head.done = false; + return Z_OK; + } + function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var state; + var dictid; + var ret; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + if (state.mode === DICT) { + dictid = 1; + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + return Z_OK; + } + exports2.inflateReset = inflateReset; + exports2.inflateReset2 = inflateReset2; + exports2.inflateResetKeep = inflateResetKeep; + exports2.inflateInit = inflateInit; + exports2.inflateInit2 = inflateInit2; + exports2.inflate = inflate; + exports2.inflateEnd = inflateEnd; + exports2.inflateGetHeader = inflateGetHeader; + exports2.inflateSetDictionary = inflateSetDictionary; + exports2.inflateInfo = "pako inflate (from Nodeca project)"; +}); + +// node_modules/pako/lib/zlib/constants.js +var require_constants = __commonJS((exports2, module2) => { + module2.exports = { + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + Z_BUF_ERROR: -5, + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + Z_BINARY: 0, + Z_TEXT: 1, + Z_UNKNOWN: 2, + Z_DEFLATED: 8 + }; +}); + +// node_modules/pako/lib/zlib/gzheader.js +var require_gzheader = __commonJS((exports2, module2) => { + function GZheader() { + this.text = 0; + this.time = 0; + this.xflags = 0; + this.os = 0; + this.extra = null; + this.extra_len = 0; + this.name = ""; + this.comment = ""; + this.hcrc = 0; + this.done = false; + } + module2.exports = GZheader; +}); + +// node_modules/pako/lib/inflate.js +var require_inflate2 = __commonJS((exports2) => { + var zlib_inflate = require_inflate(); + var utils = require_common(); + var strings = require_strings(); + var c = require_constants(); + var msg = require_messages(); + var ZStream = require_zstream(); + var GZheader = require_gzheader(); + var toString2 = Object.prototype.toString; + function Inflate(options) { + if (!(this instanceof Inflate)) + return new Inflate(options); + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: "" + }, options || {}); + var opt = this.options; + if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { + opt.windowBits = -15; + } + } + if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) { + opt.windowBits += 32; + } + if (opt.windowBits > 15 && opt.windowBits < 48) { + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + this.err = 0; + this.msg = ""; + this.ended = false; + this.chunks = []; + this.strm = new ZStream; + this.strm.avail_out = 0; + var status = zlib_inflate.inflateInit2(this.strm, opt.windowBits); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + this.header = new GZheader; + zlib_inflate.inflateGetHeader(this.strm, this.header); + if (opt.dictionary) { + if (typeof opt.dictionary === "string") { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString2.call(opt.dictionary) === "[object ArrayBuffer]") { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { + status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + } + } + } + Inflate.prototype.push = function(data2, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + var allowBufError = false; + if (this.ended) { + return false; + } + _mode = mode === ~~mode ? mode : mode === true ? c.Z_FINISH : c.Z_NO_FLUSH; + if (typeof data2 === "string") { + strm.input = strings.binstring2buf(data2); + } else if (toString2.call(data2) === "[object ArrayBuffer]") { + strm.input = new Uint8Array(data2); + } else { + strm.input = data2; + } + strm.next_in = 0; + strm.avail_in = strm.input.length; + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); + if (status === c.Z_NEED_DICT && dictionary) { + status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); + } + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH)) { + if (this.options.to === "string") { + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { + utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); + } + this.onData(utf8str); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + return true; + }; + Inflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); + }; + Inflate.prototype.onEnd = function(status) { + if (status === c.Z_OK) { + if (this.options.to === "string") { + this.result = this.chunks.join(""); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; + function inflate(input, options) { + var inflator = new Inflate(options); + inflator.push(input, true); + if (inflator.err) { + throw inflator.msg || msg[inflator.err]; + } + return inflator.result; + } + function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); + } + exports2.Inflate = Inflate; + exports2.inflate = inflate; + exports2.inflateRaw = inflateRaw; + exports2.ungzip = inflate; +}); + +// node_modules/pako/index.js +var require_pako = __commonJS((exports2, module2) => { + var assign2 = require_common().assign; + var deflate = require_deflate2(); + var inflate = require_inflate2(); + var constants = require_constants(); + var pako = {}; + assign2(pako, deflate, inflate, constants); + module2.exports = pako; +}); + +// node_modules/jszip/lib/flate.js +var require_flate = __commonJS((exports2) => { + var USE_TYPEDARRAY = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Uint32Array !== "undefined"; + var pako = require_pako(); + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array"; + exports2.magic = "\b\x00"; + function FlateWorker(action, options) { + GenericWorker.call(this, "FlateWorker/" + action); + this._pako = null; + this._pakoAction = action; + this._pakoOptions = options; + this.meta = {}; + } + utils.inherits(FlateWorker, GenericWorker); + FlateWorker.prototype.processChunk = function(chunk) { + this.meta = chunk.meta; + if (this._pako === null) { + this._createPako(); + } + this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false); + }; + FlateWorker.prototype.flush = function() { + GenericWorker.prototype.flush.call(this); + if (this._pako === null) { + this._createPako(); + } + this._pako.push([], true); + }; + FlateWorker.prototype.cleanUp = function() { + GenericWorker.prototype.cleanUp.call(this); + this._pako = null; + }; + FlateWorker.prototype._createPako = function() { + this._pako = new pako[this._pakoAction]({ + raw: true, + level: this._pakoOptions.level || -1 + }); + var self2 = this; + this._pako.onData = function(data2) { + self2.push({ + data: data2, + meta: self2.meta + }); + }; + }; + exports2.compressWorker = function(compressionOptions) { + return new FlateWorker("Deflate", compressionOptions); + }; + exports2.uncompressWorker = function() { + return new FlateWorker("Inflate", {}); + }; +}); + +// node_modules/jszip/lib/compressions.js +var require_compressions = __commonJS((exports2) => { + var GenericWorker = require_GenericWorker(); + exports2.STORE = { + magic: "\x00\x00", + compressWorker: function() { + return new GenericWorker("STORE compression"); + }, + uncompressWorker: function() { + return new GenericWorker("STORE decompression"); + } + }; + exports2.DEFLATE = require_flate(); +}); + +// node_modules/jszip/lib/signature.js +var require_signature = __commonJS((exports2) => { + exports2.LOCAL_FILE_HEADER = "PK\x03\x04"; + exports2.CENTRAL_FILE_HEADER = "PK\x01\x02"; + exports2.CENTRAL_DIRECTORY_END = "PK\x05\x06"; + exports2.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07"; + exports2.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06"; + exports2.DATA_DESCRIPTOR = "PK\x07\b"; +}); + +// node_modules/jszip/lib/generate/ZipFileWorker.js +var require_ZipFileWorker = __commonJS((exports2, module2) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var utf8 = require_utf8(); + var crc32 = require_crc32(); + var signature = require_signature(); + var decToHex = function(dec, bytes) { + var hex = "", i; + for (i = 0;i < bytes; i++) { + hex += String.fromCharCode(dec & 255); + dec = dec >>> 8; + } + return hex; + }; + var generateUnixExternalFileAttr = function(unixPermissions, isDir) { + var result = unixPermissions; + if (!unixPermissions) { + result = isDir ? 16893 : 33204; + } + return (result & 65535) << 16; + }; + var generateDosExternalFileAttr = function(dosPermissions) { + return (dosPermissions || 0) & 63; + }; + var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) { + var file = streamInfo["file"], compression = streamInfo["compression"], useCustomEncoding = encodeFileName !== utf8.utf8encode, encodedFileName = utils.transformTo("string", encodeFileName(file.name)), utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), comment = file.comment, encodedComment = utils.transformTo("string", encodeFileName(comment)), utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, useUTF8ForComment = utfEncodedComment.length !== comment.length, dosTime, dosDate, extraFields = "", unicodePathExtraField = "", unicodeCommentExtraField = "", dir = file.dir, date = file.date; + var dataInfo = { + crc32: 0, + compressedSize: 0, + uncompressedSize: 0 + }; + if (!streamedContent || streamingEnded) { + dataInfo.crc32 = streamInfo["crc32"]; + dataInfo.compressedSize = streamInfo["compressedSize"]; + dataInfo.uncompressedSize = streamInfo["uncompressedSize"]; + } + var bitflag = 0; + if (streamedContent) { + bitflag |= 8; + } + if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) { + bitflag |= 2048; + } + var extFileAttr = 0; + var versionMadeBy = 0; + if (dir) { + extFileAttr |= 16; + } + if (platform === "UNIX") { + versionMadeBy = 798; + extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir); + } else { + versionMadeBy = 20; + extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir); + } + dosTime = date.getUTCHours(); + dosTime = dosTime << 6; + dosTime = dosTime | date.getUTCMinutes(); + dosTime = dosTime << 5; + dosTime = dosTime | date.getUTCSeconds() / 2; + dosDate = date.getUTCFullYear() - 1980; + dosDate = dosDate << 4; + dosDate = dosDate | date.getUTCMonth() + 1; + dosDate = dosDate << 5; + dosDate = dosDate | date.getUTCDate(); + if (useUTF8ForFileName) { + unicodePathExtraField = decToHex(1, 1) + decToHex(crc32(encodedFileName), 4) + utfEncodedFileName; + extraFields += "up" + decToHex(unicodePathExtraField.length, 2) + unicodePathExtraField; + } + if (useUTF8ForComment) { + unicodeCommentExtraField = decToHex(1, 1) + decToHex(crc32(encodedComment), 4) + utfEncodedComment; + extraFields += "uc" + decToHex(unicodeCommentExtraField.length, 2) + unicodeCommentExtraField; + } + var header = ""; + header += ` +\x00`; + header += decToHex(bitflag, 2); + header += compression.magic; + header += decToHex(dosTime, 2); + header += decToHex(dosDate, 2); + header += decToHex(dataInfo.crc32, 4); + header += decToHex(dataInfo.compressedSize, 4); + header += decToHex(dataInfo.uncompressedSize, 4); + header += decToHex(encodedFileName.length, 2); + header += decToHex(extraFields.length, 2); + var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields; + var dirRecord = signature.CENTRAL_FILE_HEADER + decToHex(versionMadeBy, 2) + header + decToHex(encodedComment.length, 2) + "\x00\x00" + "\x00\x00" + decToHex(extFileAttr, 4) + decToHex(offset, 4) + encodedFileName + extraFields + encodedComment; + return { + fileRecord, + dirRecord + }; + }; + var generateCentralDirectoryEnd = function(entriesCount, centralDirLength, localDirLength, comment, encodeFileName) { + var dirEnd = ""; + var encodedComment = utils.transformTo("string", encodeFileName(comment)); + dirEnd = signature.CENTRAL_DIRECTORY_END + "\x00\x00" + "\x00\x00" + decToHex(entriesCount, 2) + decToHex(entriesCount, 2) + decToHex(centralDirLength, 4) + decToHex(localDirLength, 4) + decToHex(encodedComment.length, 2) + encodedComment; + return dirEnd; + }; + var generateDataDescriptors = function(streamInfo) { + var descriptor = ""; + descriptor = signature.DATA_DESCRIPTOR + decToHex(streamInfo["crc32"], 4) + decToHex(streamInfo["compressedSize"], 4) + decToHex(streamInfo["uncompressedSize"], 4); + return descriptor; + }; + function ZipFileWorker(streamFiles, comment, platform, encodeFileName) { + GenericWorker.call(this, "ZipFileWorker"); + this.bytesWritten = 0; + this.zipComment = comment; + this.zipPlatform = platform; + this.encodeFileName = encodeFileName; + this.streamFiles = streamFiles; + this.accumulate = false; + this.contentBuffer = []; + this.dirRecords = []; + this.currentSourceOffset = 0; + this.entriesCount = 0; + this.currentFile = null; + this._sources = []; + } + utils.inherits(ZipFileWorker, GenericWorker); + ZipFileWorker.prototype.push = function(chunk) { + var currentFilePercent = chunk.meta.percent || 0; + var entriesCount = this.entriesCount; + var remainingFiles = this._sources.length; + if (this.accumulate) { + this.contentBuffer.push(chunk); + } else { + this.bytesWritten += chunk.data.length; + GenericWorker.prototype.push.call(this, { + data: chunk.data, + meta: { + currentFile: this.currentFile, + percent: entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100 + } + }); + } + }; + ZipFileWorker.prototype.openedSource = function(streamInfo) { + this.currentSourceOffset = this.bytesWritten; + this.currentFile = streamInfo["file"].name; + var streamedContent = this.streamFiles && !streamInfo["file"].dir; + if (streamedContent) { + var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.push({ + data: record.fileRecord, + meta: { percent: 0 } + }); + } else { + this.accumulate = true; + } + }; + ZipFileWorker.prototype.closedSource = function(streamInfo) { + this.accumulate = false; + var streamedContent = this.streamFiles && !streamInfo["file"].dir; + var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.dirRecords.push(record.dirRecord); + if (streamedContent) { + this.push({ + data: generateDataDescriptors(streamInfo), + meta: { percent: 100 } + }); + } else { + this.push({ + data: record.fileRecord, + meta: { percent: 0 } + }); + while (this.contentBuffer.length) { + this.push(this.contentBuffer.shift()); + } + } + this.currentFile = null; + }; + ZipFileWorker.prototype.flush = function() { + var localDirLength = this.bytesWritten; + for (var i = 0;i < this.dirRecords.length; i++) { + this.push({ + data: this.dirRecords[i], + meta: { percent: 100 } + }); + } + var centralDirLength = this.bytesWritten - localDirLength; + var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName); + this.push({ + data: dirEnd, + meta: { percent: 100 } + }); + }; + ZipFileWorker.prototype.prepareNextSource = function() { + this.previous = this._sources.shift(); + this.openedSource(this.previous.streamInfo); + if (this.isPaused) { + this.previous.pause(); + } else { + this.previous.resume(); + } + }; + ZipFileWorker.prototype.registerPrevious = function(previous) { + this._sources.push(previous); + var self2 = this; + previous.on("data", function(chunk) { + self2.processChunk(chunk); + }); + previous.on("end", function() { + self2.closedSource(self2.previous.streamInfo); + if (self2._sources.length) { + self2.prepareNextSource(); + } else { + self2.end(); + } + }); + previous.on("error", function(e) { + self2.error(e); + }); + return this; + }; + ZipFileWorker.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) { + return false; + } + if (!this.previous && this._sources.length) { + this.prepareNextSource(); + return true; + } + if (!this.previous && !this._sources.length && !this.generatedError) { + this.end(); + return true; + } + }; + ZipFileWorker.prototype.error = function(e) { + var sources = this._sources; + if (!GenericWorker.prototype.error.call(this, e)) { + return false; + } + for (var i = 0;i < sources.length; i++) { + try { + sources[i].error(e); + } catch (e2) { + } + } + return true; + }; + ZipFileWorker.prototype.lock = function() { + GenericWorker.prototype.lock.call(this); + var sources = this._sources; + for (var i = 0;i < sources.length; i++) { + sources[i].lock(); + } + }; + module2.exports = ZipFileWorker; +}); + +// node_modules/jszip/lib/generate/index.js +var require_generate = __commonJS((exports2) => { + var compressions = require_compressions(); + var ZipFileWorker = require_ZipFileWorker(); + var getCompression = function(fileCompression, zipCompression) { + var compressionName = fileCompression || zipCompression; + var compression = compressions[compressionName]; + if (!compression) { + throw new Error(compressionName + " is not a valid compression method !"); + } + return compression; + }; + exports2.generateWorker = function(zip, options, comment) { + var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName); + var entriesCount = 0; + try { + zip.forEach(function(relativePath, file) { + entriesCount++; + var compression = getCompression(file.options.compression, options.compression); + var compressionOptions = file.options.compressionOptions || options.compressionOptions || {}; + var { dir, date } = file; + file._compressWorker(compression, compressionOptions).withStreamInfo("file", { + name: relativePath, + dir, + date, + comment: file.comment || "", + unixPermissions: file.unixPermissions, + dosPermissions: file.dosPermissions + }).pipe(zipFileWorker); + }); + zipFileWorker.entriesCount = entriesCount; + } catch (e) { + zipFileWorker.error(e); + } + return zipFileWorker; + }; +}); + +// node_modules/jszip/lib/nodejs/NodejsStreamInputAdapter.js +var require_NodejsStreamInputAdapter = __commonJS((exports2, module2) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + function NodejsStreamInputAdapter(filename, stream) { + GenericWorker.call(this, "Nodejs stream input adapter for " + filename); + this._upstreamEnded = false; + this._bindStream(stream); + } + utils.inherits(NodejsStreamInputAdapter, GenericWorker); + NodejsStreamInputAdapter.prototype._bindStream = function(stream) { + var self2 = this; + this._stream = stream; + stream.pause(); + stream.on("data", function(chunk) { + self2.push({ + data: chunk, + meta: { + percent: 0 + } + }); + }).on("error", function(e) { + if (self2.isPaused) { + this.generatedError = e; + } else { + self2.error(e); + } + }).on("end", function() { + if (self2.isPaused) { + self2._upstreamEnded = true; + } else { + self2.end(); + } + }); + }; + NodejsStreamInputAdapter.prototype.pause = function() { + if (!GenericWorker.prototype.pause.call(this)) { + return false; + } + this._stream.pause(); + return true; + }; + NodejsStreamInputAdapter.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) { + return false; + } + if (this._upstreamEnded) { + this.end(); + } else { + this._stream.resume(); + } + return true; + }; + module2.exports = NodejsStreamInputAdapter; +}); + +// node_modules/jszip/lib/object.js +var require_object = __commonJS((exports2, module2) => { + var utf8 = require_utf8(); + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var StreamHelper = require_StreamHelper(); + var defaults2 = require_defaults(); + var CompressedObject = require_compressedObject(); + var ZipObject = require_zipObject(); + var generate = require_generate(); + var nodejsUtils = require_nodejsUtils(); + var NodejsStreamInputAdapter = require_NodejsStreamInputAdapter(); + var fileAdd = function(name2, data2, originalOptions) { + var dataType = utils.getTypeOf(data2), parent2; + var o = utils.extend(originalOptions || {}, defaults2); + o.date = o.date || new Date; + if (o.compression !== null) { + o.compression = o.compression.toUpperCase(); + } + if (typeof o.unixPermissions === "string") { + o.unixPermissions = parseInt(o.unixPermissions, 8); + } + if (o.unixPermissions && o.unixPermissions & 16384) { + o.dir = true; + } + if (o.dosPermissions && o.dosPermissions & 16) { + o.dir = true; + } + if (o.dir) { + name2 = forceTrailingSlash(name2); + } + if (o.createFolders && (parent2 = parentFolder(name2))) { + folderAdd.call(this, parent2, true); + } + var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false; + if (!originalOptions || typeof originalOptions.binary === "undefined") { + o.binary = !isUnicodeString; + } + var isCompressedEmpty = data2 instanceof CompressedObject && data2.uncompressedSize === 0; + if (isCompressedEmpty || o.dir || !data2 || data2.length === 0) { + o.base64 = false; + o.binary = true; + data2 = ""; + o.compression = "STORE"; + dataType = "string"; + } + var zipObjectContent = null; + if (data2 instanceof CompressedObject || data2 instanceof GenericWorker) { + zipObjectContent = data2; + } else if (nodejsUtils.isNode && nodejsUtils.isStream(data2)) { + zipObjectContent = new NodejsStreamInputAdapter(name2, data2); + } else { + zipObjectContent = utils.prepareContent(name2, data2, o.binary, o.optimizedBinaryString, o.base64); + } + var object = new ZipObject(name2, zipObjectContent, o); + this.files[name2] = object; + }; + var parentFolder = function(path) { + if (path.slice(-1) === "/") { + path = path.substring(0, path.length - 1); + } + var lastSlash = path.lastIndexOf("/"); + return lastSlash > 0 ? path.substring(0, lastSlash) : ""; + }; + var forceTrailingSlash = function(path) { + if (path.slice(-1) !== "/") { + path += "/"; + } + return path; + }; + var folderAdd = function(name2, createFolders) { + createFolders = typeof createFolders !== "undefined" ? createFolders : defaults2.createFolders; + name2 = forceTrailingSlash(name2); + if (!this.files[name2]) { + fileAdd.call(this, name2, null, { + dir: true, + createFolders + }); + } + return this.files[name2]; + }; + function isRegExp2(object) { + return Object.prototype.toString.call(object) === "[object RegExp]"; + } + var out = { + load: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, + forEach: function(cb) { + var filename, relativePath, file; + for (filename in this.files) { + file = this.files[filename]; + relativePath = filename.slice(this.root.length, filename.length); + if (relativePath && filename.slice(0, this.root.length) === this.root) { + cb(relativePath, file); + } + } + }, + filter: function(search) { + var result = []; + this.forEach(function(relativePath, entry) { + if (search(relativePath, entry)) { + result.push(entry); + } + }); + return result; + }, + file: function(name2, data2, o) { + if (arguments.length === 1) { + if (isRegExp2(name2)) { + var regexp = name2; + return this.filter(function(relativePath, file) { + return !file.dir && regexp.test(relativePath); + }); + } else { + var obj = this.files[this.root + name2]; + if (obj && !obj.dir) { + return obj; + } else { + return null; + } + } + } else { + name2 = this.root + name2; + fileAdd.call(this, name2, data2, o); + } + return this; + }, + folder: function(arg) { + if (!arg) { + return this; + } + if (isRegExp2(arg)) { + return this.filter(function(relativePath, file) { + return file.dir && arg.test(relativePath); + }); + } + var name2 = this.root + arg; + var newFolder = folderAdd.call(this, name2); + var ret = this.clone(); + ret.root = newFolder.name; + return ret; + }, + remove: function(name2) { + name2 = this.root + name2; + var file = this.files[name2]; + if (!file) { + if (name2.slice(-1) !== "/") { + name2 += "/"; + } + file = this.files[name2]; + } + if (file && !file.dir) { + delete this.files[name2]; + } else { + var kids = this.filter(function(relativePath, file2) { + return file2.name.slice(0, name2.length) === name2; + }); + for (var i = 0;i < kids.length; i++) { + delete this.files[kids[i].name]; + } + } + return this; + }, + generate: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, + generateInternalStream: function(options) { + var worker, opts = {}; + try { + opts = utils.extend(options || {}, { + streamFiles: false, + compression: "STORE", + compressionOptions: null, + type: "", + platform: "DOS", + comment: null, + mimeType: "application/zip", + encodeFileName: utf8.utf8encode + }); + opts.type = opts.type.toLowerCase(); + opts.compression = opts.compression.toUpperCase(); + if (opts.type === "binarystring") { + opts.type = "string"; + } + if (!opts.type) { + throw new Error("No output type specified."); + } + utils.checkSupport(opts.type); + if (opts.platform === "darwin" || opts.platform === "freebsd" || opts.platform === "linux" || opts.platform === "sunos") { + opts.platform = "UNIX"; + } + if (opts.platform === "win32") { + opts.platform = "DOS"; + } + var comment = opts.comment || this.comment || ""; + worker = generate.generateWorker(this, opts, comment); + } catch (e) { + worker = new GenericWorker("error"); + worker.error(e); + } + return new StreamHelper(worker, opts.type || "string", opts.mimeType); + }, + generateAsync: function(options, onUpdate) { + return this.generateInternalStream(options).accumulate(onUpdate); + }, + generateNodeStream: function(options, onUpdate) { + options = options || {}; + if (!options.type) { + options.type = "nodebuffer"; + } + return this.generateInternalStream(options).toNodejsStream(onUpdate); + } + }; + module2.exports = out; +}); + +// node_modules/jszip/lib/reader/DataReader.js +var require_DataReader = __commonJS((exports2, module2) => { + var utils = require_utils(); + function DataReader(data2) { + this.data = data2; + this.length = data2.length; + this.index = 0; + this.zero = 0; + } + DataReader.prototype = { + checkOffset: function(offset) { + this.checkIndex(this.index + offset); + }, + checkIndex: function(newIndex) { + if (this.length < this.zero + newIndex || newIndex < 0) { + throw new Error("End of data reached (data length = " + this.length + ", asked index = " + newIndex + "). Corrupted zip ?"); + } + }, + setIndex: function(newIndex) { + this.checkIndex(newIndex); + this.index = newIndex; + }, + skip: function(n) { + this.setIndex(this.index + n); + }, + byteAt: function() { + }, + readInt: function(size) { + var result = 0, i; + this.checkOffset(size); + for (i = this.index + size - 1;i >= this.index; i--) { + result = (result << 8) + this.byteAt(i); + } + this.index += size; + return result; + }, + readString: function(size) { + return utils.transformTo("string", this.readData(size)); + }, + readData: function() { + }, + lastIndexOfSignature: function() { + }, + readAndCheckSignature: function() { + }, + readDate: function() { + var dostime = this.readInt(4); + return new Date(Date.UTC((dostime >> 25 & 127) + 1980, (dostime >> 21 & 15) - 1, dostime >> 16 & 31, dostime >> 11 & 31, dostime >> 5 & 63, (dostime & 31) << 1)); + } + }; + module2.exports = DataReader; +}); + +// node_modules/jszip/lib/reader/ArrayReader.js +var require_ArrayReader = __commonJS((exports2, module2) => { + var DataReader = require_DataReader(); + var utils = require_utils(); + function ArrayReader(data2) { + DataReader.call(this, data2); + for (var i = 0;i < this.data.length; i++) { + data2[i] = data2[i] & 255; + } + } + utils.inherits(ArrayReader, DataReader); + ArrayReader.prototype.byteAt = function(i) { + return this.data[this.zero + i]; + }; + ArrayReader.prototype.lastIndexOfSignature = function(sig) { + var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3); + for (var i = this.length - 4;i >= 0; --i) { + if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) { + return i - this.zero; + } + } + return -1; + }; + ArrayReader.prototype.readAndCheckSignature = function(sig) { + var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3), data2 = this.readData(4); + return sig0 === data2[0] && sig1 === data2[1] && sig2 === data2[2] && sig3 === data2[3]; + }; + ArrayReader.prototype.readData = function(size) { + this.checkOffset(size); + if (size === 0) { + return []; + } + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module2.exports = ArrayReader; +}); + +// node_modules/jszip/lib/reader/StringReader.js +var require_StringReader = __commonJS((exports2, module2) => { + var DataReader = require_DataReader(); + var utils = require_utils(); + function StringReader(data2) { + DataReader.call(this, data2); + } + utils.inherits(StringReader, DataReader); + StringReader.prototype.byteAt = function(i) { + return this.data.charCodeAt(this.zero + i); + }; + StringReader.prototype.lastIndexOfSignature = function(sig) { + return this.data.lastIndexOf(sig) - this.zero; + }; + StringReader.prototype.readAndCheckSignature = function(sig) { + var data2 = this.readData(4); + return sig === data2; + }; + StringReader.prototype.readData = function(size) { + this.checkOffset(size); + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module2.exports = StringReader; +}); + +// node_modules/jszip/lib/reader/Uint8ArrayReader.js +var require_Uint8ArrayReader = __commonJS((exports2, module2) => { + var ArrayReader = require_ArrayReader(); + var utils = require_utils(); + function Uint8ArrayReader(data2) { + ArrayReader.call(this, data2); + } + utils.inherits(Uint8ArrayReader, ArrayReader); + Uint8ArrayReader.prototype.readData = function(size) { + this.checkOffset(size); + if (size === 0) { + return new Uint8Array(0); + } + var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module2.exports = Uint8ArrayReader; +}); + +// node_modules/jszip/lib/reader/NodeBufferReader.js +var require_NodeBufferReader = __commonJS((exports2, module2) => { + var Uint8ArrayReader = require_Uint8ArrayReader(); + var utils = require_utils(); + function NodeBufferReader(data2) { + Uint8ArrayReader.call(this, data2); + } + utils.inherits(NodeBufferReader, Uint8ArrayReader); + NodeBufferReader.prototype.readData = function(size) { + this.checkOffset(size); + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module2.exports = NodeBufferReader; +}); + +// node_modules/jszip/lib/reader/readerFor.js +var require_readerFor = __commonJS((exports2, module2) => { + var utils = require_utils(); + var support = require_support(); + var ArrayReader = require_ArrayReader(); + var StringReader = require_StringReader(); + var NodeBufferReader = require_NodeBufferReader(); + var Uint8ArrayReader = require_Uint8ArrayReader(); + module2.exports = function(data2) { + var type = utils.getTypeOf(data2); + utils.checkSupport(type); + if (type === "string" && !support.uint8array) { + return new StringReader(data2); + } + if (type === "nodebuffer") { + return new NodeBufferReader(data2); + } + if (support.uint8array) { + return new Uint8ArrayReader(utils.transformTo("uint8array", data2)); + } + return new ArrayReader(utils.transformTo("array", data2)); + }; +}); + +// node_modules/jszip/lib/zipEntry.js +var require_zipEntry = __commonJS((exports2, module2) => { + var readerFor = require_readerFor(); + var utils = require_utils(); + var CompressedObject = require_compressedObject(); + var crc32fn = require_crc32(); + var utf8 = require_utf8(); + var compressions = require_compressions(); + var support = require_support(); + var MADE_BY_DOS = 0; + var MADE_BY_UNIX = 3; + var findCompression = function(compressionMethod) { + for (var method in compressions) { + if (!Object.prototype.hasOwnProperty.call(compressions, method)) { + continue; + } + if (compressions[method].magic === compressionMethod) { + return compressions[method]; + } + } + return null; + }; + function ZipEntry(options, loadOptions) { + this.options = options; + this.loadOptions = loadOptions; + } + ZipEntry.prototype = { + isEncrypted: function() { + return (this.bitFlag & 1) === 1; + }, + useUTF8: function() { + return (this.bitFlag & 2048) === 2048; + }, + readLocalPart: function(reader) { + var compression, localExtraFieldsLength; + reader.skip(22); + this.fileNameLength = reader.readInt(2); + localExtraFieldsLength = reader.readInt(2); + this.fileName = reader.readData(this.fileNameLength); + reader.skip(localExtraFieldsLength); + if (this.compressedSize === -1 || this.uncompressedSize === -1) { + throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)"); + } + compression = findCompression(this.compressionMethod); + if (compression === null) { + throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")"); + } + this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize)); + }, + readCentralPart: function(reader) { + this.versionMadeBy = reader.readInt(2); + reader.skip(2); + this.bitFlag = reader.readInt(2); + this.compressionMethod = reader.readString(2); + this.date = reader.readDate(); + this.crc32 = reader.readInt(4); + this.compressedSize = reader.readInt(4); + this.uncompressedSize = reader.readInt(4); + var fileNameLength = reader.readInt(2); + this.extraFieldsLength = reader.readInt(2); + this.fileCommentLength = reader.readInt(2); + this.diskNumberStart = reader.readInt(2); + this.internalFileAttributes = reader.readInt(2); + this.externalFileAttributes = reader.readInt(4); + this.localHeaderOffset = reader.readInt(4); + if (this.isEncrypted()) { + throw new Error("Encrypted zip are not supported"); + } + reader.skip(fileNameLength); + this.readExtraFields(reader); + this.parseZIP64ExtraField(reader); + this.fileComment = reader.readData(this.fileCommentLength); + }, + processAttributes: function() { + this.unixPermissions = null; + this.dosPermissions = null; + var madeBy = this.versionMadeBy >> 8; + this.dir = this.externalFileAttributes & 16 ? true : false; + if (madeBy === MADE_BY_DOS) { + this.dosPermissions = this.externalFileAttributes & 63; + } + if (madeBy === MADE_BY_UNIX) { + this.unixPermissions = this.externalFileAttributes >> 16 & 65535; + } + if (!this.dir && this.fileNameStr.slice(-1) === "/") { + this.dir = true; + } + }, + parseZIP64ExtraField: function() { + if (!this.extraFields[1]) { + return; + } + var extraReader = readerFor(this.extraFields[1].value); + if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { + this.uncompressedSize = extraReader.readInt(8); + } + if (this.compressedSize === utils.MAX_VALUE_32BITS) { + this.compressedSize = extraReader.readInt(8); + } + if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { + this.localHeaderOffset = extraReader.readInt(8); + } + if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { + this.diskNumberStart = extraReader.readInt(4); + } + }, + readExtraFields: function(reader) { + var end = reader.index + this.extraFieldsLength, extraFieldId, extraFieldLength, extraFieldValue; + if (!this.extraFields) { + this.extraFields = {}; + } + while (reader.index + 4 < end) { + extraFieldId = reader.readInt(2); + extraFieldLength = reader.readInt(2); + extraFieldValue = reader.readData(extraFieldLength); + this.extraFields[extraFieldId] = { + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue + }; + } + reader.setIndex(end); + }, + handleUTF8: function() { + var decodeParamType = support.uint8array ? "uint8array" : "array"; + if (this.useUTF8()) { + this.fileNameStr = utf8.utf8decode(this.fileName); + this.fileCommentStr = utf8.utf8decode(this.fileComment); + } else { + var upath = this.findExtraFieldUnicodePath(); + if (upath !== null) { + this.fileNameStr = upath; + } else { + var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName); + this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray); + } + var ucomment = this.findExtraFieldUnicodeComment(); + if (ucomment !== null) { + this.fileCommentStr = ucomment; + } else { + var commentByteArray = utils.transformTo(decodeParamType, this.fileComment); + this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray); + } + } + }, + findExtraFieldUnicodePath: function() { + var upathField = this.extraFields[28789]; + if (upathField) { + var extraReader = readerFor(upathField.value); + if (extraReader.readInt(1) !== 1) { + return null; + } + if (crc32fn(this.fileName) !== extraReader.readInt(4)) { + return null; + } + return utf8.utf8decode(extraReader.readData(upathField.length - 5)); + } + return null; + }, + findExtraFieldUnicodeComment: function() { + var ucommentField = this.extraFields[25461]; + if (ucommentField) { + var extraReader = readerFor(ucommentField.value); + if (extraReader.readInt(1) !== 1) { + return null; + } + if (crc32fn(this.fileComment) !== extraReader.readInt(4)) { + return null; + } + return utf8.utf8decode(extraReader.readData(ucommentField.length - 5)); + } + return null; + } + }; + module2.exports = ZipEntry; +}); + +// node_modules/jszip/lib/zipEntries.js +var require_zipEntries = __commonJS((exports2, module2) => { + var readerFor = require_readerFor(); + var utils = require_utils(); + var sig = require_signature(); + var ZipEntry = require_zipEntry(); + var support = require_support(); + function ZipEntries(loadOptions) { + this.files = []; + this.loadOptions = loadOptions; + } + ZipEntries.prototype = { + checkSignature: function(expectedSignature) { + if (!this.reader.readAndCheckSignature(expectedSignature)) { + this.reader.index -= 4; + var signature = this.reader.readString(4); + throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); + } + }, + isSignature: function(askedIndex, expectedSignature) { + var currentIndex = this.reader.index; + this.reader.setIndex(askedIndex); + var signature = this.reader.readString(4); + var result = signature === expectedSignature; + this.reader.setIndex(currentIndex); + return result; + }, + readBlockEndOfCentral: function() { + this.diskNumber = this.reader.readInt(2); + this.diskWithCentralDirStart = this.reader.readInt(2); + this.centralDirRecordsOnThisDisk = this.reader.readInt(2); + this.centralDirRecords = this.reader.readInt(2); + this.centralDirSize = this.reader.readInt(4); + this.centralDirOffset = this.reader.readInt(4); + this.zipCommentLength = this.reader.readInt(2); + var zipComment = this.reader.readData(this.zipCommentLength); + var decodeParamType = support.uint8array ? "uint8array" : "array"; + var decodeContent = utils.transformTo(decodeParamType, zipComment); + this.zipComment = this.loadOptions.decodeFileName(decodeContent); + }, + readBlockZip64EndOfCentral: function() { + this.zip64EndOfCentralSize = this.reader.readInt(8); + this.reader.skip(4); + this.diskNumber = this.reader.readInt(4); + this.diskWithCentralDirStart = this.reader.readInt(4); + this.centralDirRecordsOnThisDisk = this.reader.readInt(8); + this.centralDirRecords = this.reader.readInt(8); + this.centralDirSize = this.reader.readInt(8); + this.centralDirOffset = this.reader.readInt(8); + this.zip64ExtensibleData = {}; + var extraDataSize = this.zip64EndOfCentralSize - 44, index2 = 0, extraFieldId, extraFieldLength, extraFieldValue; + while (index2 < extraDataSize) { + extraFieldId = this.reader.readInt(2); + extraFieldLength = this.reader.readInt(4); + extraFieldValue = this.reader.readData(extraFieldLength); + this.zip64ExtensibleData[extraFieldId] = { + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue + }; + } + }, + readBlockZip64EndOfCentralLocator: function() { + this.diskWithZip64CentralDirStart = this.reader.readInt(4); + this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); + this.disksCount = this.reader.readInt(4); + if (this.disksCount > 1) { + throw new Error("Multi-volumes zip are not supported"); + } + }, + readLocalFiles: function() { + var i, file; + for (i = 0;i < this.files.length; i++) { + file = this.files[i]; + this.reader.setIndex(file.localHeaderOffset); + this.checkSignature(sig.LOCAL_FILE_HEADER); + file.readLocalPart(this.reader); + file.handleUTF8(); + file.processAttributes(); + } + }, + readCentralDir: function() { + var file; + this.reader.setIndex(this.centralDirOffset); + while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) { + file = new ZipEntry({ + zip64: this.zip64 + }, this.loadOptions); + file.readCentralPart(this.reader); + this.files.push(file); + } + if (this.centralDirRecords !== this.files.length) { + if (this.centralDirRecords !== 0 && this.files.length === 0) { + throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); + } else { + } + } + }, + readEndOfCentral: function() { + var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); + if (offset < 0) { + var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER); + if (isGarbage) { + throw new Error("Can't find end of central directory : is this a zip file ? " + "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"); + } else { + throw new Error("Corrupted zip: can't find end of central directory"); + } + } + this.reader.setIndex(offset); + var endOfCentralDirOffset = offset; + this.checkSignature(sig.CENTRAL_DIRECTORY_END); + this.readBlockEndOfCentral(); + if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { + this.zip64 = true; + offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); + if (offset < 0) { + throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); + } + this.reader.setIndex(offset); + this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); + this.readBlockZip64EndOfCentralLocator(); + if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) { + this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + if (this.relativeOffsetEndOfZip64CentralDir < 0) { + throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); + } + } + this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); + this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + this.readBlockZip64EndOfCentral(); + } + var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize; + if (this.zip64) { + expectedEndOfCentralDirOffset += 20; + expectedEndOfCentralDirOffset += 12 + this.zip64EndOfCentralSize; + } + var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset; + if (extraBytes > 0) { + if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) { + } else { + this.reader.zero = extraBytes; + } + } else if (extraBytes < 0) { + throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes."); + } + }, + prepareReader: function(data2) { + this.reader = readerFor(data2); + }, + load: function(data2) { + this.prepareReader(data2); + this.readEndOfCentral(); + this.readCentralDir(); + this.readLocalFiles(); + } + }; + module2.exports = ZipEntries; +}); + +// node_modules/jszip/lib/load.js +var require_load = __commonJS((exports2, module2) => { + var utils = require_utils(); + var external = require_external(); + var utf8 = require_utf8(); + var ZipEntries = require_zipEntries(); + var Crc32Probe = require_Crc32Probe(); + var nodejsUtils = require_nodejsUtils(); + function checkEntryCRC32(zipEntry) { + return new external.Promise(function(resolve, reject2) { + var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe); + worker.on("error", function(e) { + reject2(e); + }).on("end", function() { + if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) { + reject2(new Error("Corrupted zip : CRC32 mismatch")); + } else { + resolve(); + } + }).resume(); + }); + } + module2.exports = function(data2, options) { + var zip = this; + options = utils.extend(options || {}, { + base64: false, + checkCRC32: false, + optimizedBinaryString: false, + createFolders: false, + decodeFileName: utf8.utf8decode + }); + if (nodejsUtils.isNode && nodejsUtils.isStream(data2)) { + return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")); + } + return utils.prepareContent("the loaded zip file", data2, true, options.optimizedBinaryString, options.base64).then(function(data3) { + var zipEntries = new ZipEntries(options); + zipEntries.load(data3); + return zipEntries; + }).then(function checkCRC32(zipEntries) { + var promises = [external.Promise.resolve(zipEntries)]; + var files = zipEntries.files; + if (options.checkCRC32) { + for (var i = 0;i < files.length; i++) { + promises.push(checkEntryCRC32(files[i])); + } + } + return external.Promise.all(promises); + }).then(function addFiles(results) { + var zipEntries = results.shift(); + var files = zipEntries.files; + for (var i = 0;i < files.length; i++) { + var input = files[i]; + var unsafeName = input.fileNameStr; + var safeName = utils.resolve(input.fileNameStr); + zip.file(safeName, input.decompressed, { + binary: true, + optimizedBinaryString: true, + date: input.date, + dir: input.dir, + comment: input.fileCommentStr.length ? input.fileCommentStr : null, + unixPermissions: input.unixPermissions, + dosPermissions: input.dosPermissions, + createFolders: options.createFolders + }); + if (!input.dir) { + zip.file(safeName).unsafeOriginalName = unsafeName; + } + } + if (zipEntries.zipComment.length) { + zip.comment = zipEntries.zipComment; + } + return zip; + }); + }; +}); + +// node_modules/jszip/lib/index.js +var require_lib = __commonJS((exports2, module2) => { + function JSZip() { + if (!(this instanceof JSZip)) { + return new JSZip; + } + if (arguments.length) { + throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide."); + } + this.files = Object.create(null); + this.comment = null; + this.root = ""; + this.clone = function() { + var newObj = new JSZip; + for (var i in this) { + if (typeof this[i] !== "function") { + newObj[i] = this[i]; + } + } + return newObj; + }; + } + JSZip.prototype = require_object(); + JSZip.prototype.loadAsync = require_load(); + JSZip.support = require_support(); + JSZip.defaults = require_defaults(); + JSZip.version = "3.10.1"; + JSZip.loadAsync = function(content2, options) { + return new JSZip().loadAsync(content2, options); + }; + JSZip.external = require_external(); + module2.exports = JSZip; +}); + +// src/external/ffl.js/ffl-emscripten.js +var require_ffl_emscripten = __commonJS((exports2, module2) => { + var ModuleFFL = (() => { + var _scriptName = typeof document != "undefined" ? document.currentScript?.src : undefined; + return async function(moduleArg = {}) { + var moduleRtn; + var Module = moduleArg; + var readyPromiseResolve, readyPromiseReject; + var readyPromise = new Promise((resolve, reject2) => { + readyPromiseResolve = resolve; + readyPromiseReject = reject2; + }); + var ENVIRONMENT_IS_WEB = true; + var ENVIRONMENT_IS_WORKER = false; + var moduleOverrides = { ...Module }; + var scriptDirectory = ""; + function locateFile(path) { + if (Module["locateFile"]) { + return Module["locateFile"](path, scriptDirectory); + } + return scriptDirectory + path; + } + var readAsync, readBinary; + if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { + if (ENVIRONMENT_IS_WORKER) { + scriptDirectory = self.location.href; + } else if (typeof document != "undefined" && document.currentScript) { + scriptDirectory = document.currentScript.src; + } + if (_scriptName) { + scriptDirectory = _scriptName; + } + if (scriptDirectory.startsWith("blob:")) { + scriptDirectory = ""; + } else { + scriptDirectory = scriptDirectory.slice(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1); + } + { + readAsync = async (url) => { + var response = await fetch(url, { credentials: "same-origin" }); + if (response.ok) { + return response.arrayBuffer(); + } + throw new Error(response.status + " : " + response.url); + }; + } + } else { + } + var out = console.log.bind(console); + var err = console.error.bind(console); + Object.assign(Module, moduleOverrides); + moduleOverrides = null; + var wasmBinary; + var wasmMemory; + var ABORT = false; + var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAP64, HEAPU64, HEAPF64; + var runtimeInitialized = false; + function updateMemoryViews() { + var b2 = wasmMemory.buffer; + Module["HEAP8"] = HEAP8 = new Int8Array(b2); + HEAP16 = new Int16Array(b2); + Module["HEAPU8"] = HEAPU8 = new Uint8Array(b2); + Module["HEAPU16"] = HEAPU16 = new Uint16Array(b2); + Module["HEAP32"] = HEAP32 = new Int32Array(b2); + Module["HEAPU32"] = HEAPU32 = new Uint32Array(b2); + Module["HEAPF32"] = HEAPF32 = new Float32Array(b2); + HEAPF64 = new Float64Array(b2); + HEAP64 = new BigInt64Array(b2); + HEAPU64 = new BigUint64Array(b2); + } + function preRun() { + } + function initRuntime() { + runtimeInitialized = true; + wasmExports["e"](); + } + function postRun() { + } + var runDependencies = 0; + var dependenciesFulfilled = null; + function addRunDependency(id) { + runDependencies++; + } + function removeRunDependency(id) { + runDependencies--; + if (runDependencies == 0) { + if (dependenciesFulfilled) { + var callback = dependenciesFulfilled; + dependenciesFulfilled = null; + callback(); + } + } + } + function abort(what) { + what = "Aborted(" + what + ")"; + err(what); + ABORT = true; + what += ". Build with -sASSERTIONS for more info."; + var e = new WebAssembly.RuntimeError(what); + readyPromiseReject(e); + throw e; + } + var wasmBinaryFile; + function findWasmBinary() { + return locateFile("ffl-emscripten.wasm"); + } + function getBinarySync(file) { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary); + } + if (readBinary) { + return readBinary(file); + } + throw "both async and sync fetching of the wasm failed"; + } + async function getWasmBinary(binaryFile) { + if (!wasmBinary) { + try { + var response = await readAsync(binaryFile); + return new Uint8Array(response); + } catch { + } + } + return getBinarySync(binaryFile); + } + async function instantiateArrayBuffer(binaryFile, imports) { + try { + var binary = await getWasmBinary(binaryFile); + var instance = await WebAssembly.instantiate(binary, imports); + return instance; + } catch (reason) { + err(`failed to asynchronously prepare wasm: ${reason}`); + abort(reason); + } + } + async function instantiateAsync(binary, binaryFile, imports) { + if (!binary && typeof WebAssembly.instantiateStreaming == "function") { + try { + var response = fetch(binaryFile, { credentials: "same-origin" }); + var instantiationResult = await WebAssembly.instantiateStreaming(response, imports); + return instantiationResult; + } catch (reason) { + err(`wasm streaming compile failed: ${reason}`); + err("falling back to ArrayBuffer instantiation"); + } + } + return instantiateArrayBuffer(binaryFile, imports); + } + function getWasmImports() { + return { a: wasmImports }; + } + async function createWasm() { + function receiveInstance(instance, module3) { + wasmExports = instance.exports; + wasmMemory = wasmExports["d"]; + updateMemoryViews(); + wasmTable = wasmExports["O"]; + removeRunDependency("wasm-instantiate"); + return wasmExports; + } + addRunDependency("wasm-instantiate"); + function receiveInstantiationResult(result2) { + return receiveInstance(result2["instance"]); + } + var info = getWasmImports(); + wasmBinaryFile ??= findWasmBinary(); + try { + var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info); + var exports3 = receiveInstantiationResult(result); + return exports3; + } catch (e) { + readyPromiseReject(e); + return Promise.reject(e); + } + } + + class ExitStatus { + name = "ExitStatus"; + constructor(status) { + this.message = `Program terminated with exit(${status})`; + this.status = status; + } + } + function stackTrace() { + abort("missing function: $stackTrace"); + } + stackTrace.stub = true; + var __abort_js = () => abort(""); + var _emscripten_random = () => Math.random(); + var getHeapMax = () => 2147483648; + var alignMemory = (size2, alignment) => Math.ceil(size2 / alignment) * alignment; + var growMemory = (size2) => { + var b2 = wasmMemory.buffer; + var pages = (size2 - b2.byteLength + 65535) / 65536 | 0; + try { + wasmMemory.grow(pages); + updateMemoryViews(); + return 1; + } catch (e) { + } + }; + var _emscripten_resize_heap = (requestedSize) => { + var oldSize = HEAPU8.length; + requestedSize >>>= 0; + var maxHeapSize = getHeapMax(); + if (requestedSize > maxHeapSize) { + return false; + } + for (var cutDown = 1;cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); + overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); + var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536)); + var replacement = growMemory(newSize); + if (replacement) { + return true; + } + } + return false; + }; + var uleb128Encode = (n2, target) => { + if (n2 < 128) { + target.push(n2); + } else { + target.push(n2 % 128 | 128, n2 >> 7); + } + }; + var sigToWasmTypes = (sig) => { + var typeNames = { i: "i32", j: "i64", f: "f32", d: "f64", e: "externref", p: "i32" }; + var type = { parameters: [], results: sig[0] == "v" ? [] : [typeNames[sig[0]]] }; + for (var i = 1;i < sig.length; ++i) { + type.parameters.push(typeNames[sig[i]]); + } + return type; + }; + var generateFuncType = (sig, target) => { + var sigRet = sig.slice(0, 1); + var sigParam = sig.slice(1); + var typeCodes = { i: 127, p: 127, j: 126, f: 125, d: 124, e: 111 }; + target.push(96); + uleb128Encode(sigParam.length, target); + for (var paramType of sigParam) { + target.push(typeCodes[paramType]); + } + if (sigRet == "v") { + target.push(0); + } else { + target.push(1, typeCodes[sigRet]); + } + }; + var convertJsFunctionToWasm = (func, sig) => { + if (typeof WebAssembly.Function == "function") { + return new WebAssembly.Function(sigToWasmTypes(sig), func); + } + var typeSectionBody = [1]; + generateFuncType(sig, typeSectionBody); + var bytes = [0, 97, 115, 109, 1, 0, 0, 0, 1]; + uleb128Encode(typeSectionBody.length, bytes); + bytes.push(...typeSectionBody); + bytes.push(2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0); + var module3 = new WebAssembly.Module(new Uint8Array(bytes)); + var instance = new WebAssembly.Instance(module3, { e: { f: func } }); + var wrappedFunc = instance.exports["f"]; + return wrappedFunc; + }; + var wasmTableMirror = []; + var wasmTable; + var getWasmTableEntry = (funcPtr) => { + var func = wasmTableMirror[funcPtr]; + if (!func) { + wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr); + } + return func; + }; + var updateTableMap = (offset, count) => { + if (functionsInTableMap) { + for (var i = offset;i < offset + count; i++) { + var item = getWasmTableEntry(i); + if (item) { + functionsInTableMap.set(item, i); + } + } + } + }; + var functionsInTableMap; + var getFunctionAddress = (func) => { + if (!functionsInTableMap) { + functionsInTableMap = new WeakMap; + updateTableMap(0, wasmTable.length); + } + return functionsInTableMap.get(func) || 0; + }; + var freeTableIndexes = []; + var getEmptyTableSlot = () => { + if (freeTableIndexes.length) { + return freeTableIndexes.pop(); + } + try { + wasmTable.grow(1); + } catch (err2) { + if (!(err2 instanceof RangeError)) { + throw err2; + } + throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."; + } + return wasmTable.length - 1; + }; + var setWasmTableEntry = (idx, func) => { + wasmTable.set(idx, func); + wasmTableMirror[idx] = wasmTable.get(idx); + }; + var addFunction = (func, sig) => { + var rtn = getFunctionAddress(func); + if (rtn) { + return rtn; + } + var ret = getEmptyTableSlot(); + try { + setWasmTableEntry(ret, func); + } catch (err2) { + if (!(err2 instanceof TypeError)) { + throw err2; + } + var wrapped = convertJsFunctionToWasm(func, sig); + setWasmTableEntry(ret, wrapped); + } + functionsInTableMap.set(func, ret); + return ret; + }; + var removeFunction = (index2) => { + functionsInTableMap.delete(getWasmTableEntry(index2)); + setWasmTableEntry(index2, null); + freeTableIndexes.push(index2); + }; + var wasmImports = { a: __abort_js, c: _emscripten_random, b: _emscripten_resize_heap }; + var wasmExports = await createWasm(); + var ___wasm_call_ctors = wasmExports["e"]; + var _FFLInitCharModelCPUStepWithCallback = Module["_FFLInitCharModelCPUStepWithCallback"] = wasmExports["f"]; + var _FFLInitCharModelCPUStep = Module["_FFLInitCharModelCPUStep"] = wasmExports["g"]; + var _FFLDeleteCharModel = Module["_FFLDeleteCharModel"] = wasmExports["h"]; + var _FFLGetDrawParamOpaFaceline = Module["_FFLGetDrawParamOpaFaceline"] = wasmExports["i"]; + var _FFLGetDrawParamOpaBeard = Module["_FFLGetDrawParamOpaBeard"] = wasmExports["j"]; + var _FFLGetDrawParamOpaNose = Module["_FFLGetDrawParamOpaNose"] = wasmExports["k"]; + var _FFLGetDrawParamOpaForehead = Module["_FFLGetDrawParamOpaForehead"] = wasmExports["l"]; + var _FFLGetDrawParamOpaHair = Module["_FFLGetDrawParamOpaHair"] = wasmExports["m"]; + var _FFLGetDrawParamOpaCap = Module["_FFLGetDrawParamOpaCap"] = wasmExports["n"]; + var _FFLGetDrawParamXluMask = Module["_FFLGetDrawParamXluMask"] = wasmExports["o"]; + var _FFLGetDrawParamXluNoseLine = Module["_FFLGetDrawParamXluNoseLine"] = wasmExports["p"]; + var _FFLGetDrawParamXluGlass = Module["_FFLGetDrawParamXluGlass"] = wasmExports["q"]; + var _FFLSetExpression = Module["_FFLSetExpression"] = wasmExports["r"]; + var _FFLGetExpression = Module["_FFLGetExpression"] = wasmExports["s"]; + var _FFLSetViewModelType = Module["_FFLSetViewModelType"] = wasmExports["t"]; + var _FFLGetBoundingBox = Module["_FFLGetBoundingBox"] = wasmExports["u"]; + var _FFLIsAvailableExpression = Module["_FFLIsAvailableExpression"] = wasmExports["v"]; + var _FFLSetCoordinate = Module["_FFLSetCoordinate"] = wasmExports["w"]; + var _FFLSetScale = Module["_FFLSetScale"] = wasmExports["x"]; + var _FFLiGetRandomCharInfo = Module["_FFLiGetRandomCharInfo"] = wasmExports["y"]; + var _FFLpGetStoreDataFromCharInfo = Module["_FFLpGetStoreDataFromCharInfo"] = wasmExports["z"]; + var _FFLpGetCharInfoFromStoreData = Module["_FFLpGetCharInfoFromStoreData"] = wasmExports["A"]; + var _FFLpGetCharInfoFromMiiDataOfficialRFL = Module["_FFLpGetCharInfoFromMiiDataOfficialRFL"] = wasmExports["B"]; + var _FFLGetAdditionalInfo = Module["_FFLGetAdditionalInfo"] = wasmExports["C"]; + var _FFLInitRes = Module["_FFLInitRes"] = wasmExports["D"]; + var _FFLInitResGPUStep = Module["_FFLInitResGPUStep"] = wasmExports["E"]; + var _FFLExit = Module["_FFLExit"] = wasmExports["F"]; + var _FFLIsAvailable = Module["_FFLIsAvailable"] = wasmExports["G"]; + var _FFLGetFavoriteColor = Module["_FFLGetFavoriteColor"] = wasmExports["H"]; + var _FFLSetLinearGammaMode = Module["_FFLSetLinearGammaMode"] = wasmExports["I"]; + var _FFLGetFacelineColor = Module["_FFLGetFacelineColor"] = wasmExports["J"]; + var _FFLSetTextureFlipY = Module["_FFLSetTextureFlipY"] = wasmExports["K"]; + var _FFLSetNormalIsSnorm8_8_8_8 = Module["_FFLSetNormalIsSnorm8_8_8_8"] = wasmExports["L"]; + var _FFLSetFrontCullForFlipX = Module["_FFLSetFrontCullForFlipX"] = wasmExports["M"]; + var _FFLSetTextureCallback = Module["_FFLSetTextureCallback"] = wasmExports["N"]; + var _FFLiDeleteTempObjectMaskTextures = Module["_FFLiDeleteTempObjectMaskTextures"] = wasmExports["P"]; + var _FFLiDeleteTempObjectFacelineTexture = Module["_FFLiDeleteTempObjectFacelineTexture"] = wasmExports["Q"]; + var _FFLiDeleteTextureTempObject = Module["_FFLiDeleteTextureTempObject"] = wasmExports["R"]; + var _FFLiiGetEyeRotateOffset = Module["_FFLiiGetEyeRotateOffset"] = wasmExports["S"]; + var _FFLiiGetEyebrowRotateOffset = Module["_FFLiiGetEyebrowRotateOffset"] = wasmExports["T"]; + var _FFLiInvalidateTempObjectFacelineTexture = Module["_FFLiInvalidateTempObjectFacelineTexture"] = wasmExports["U"]; + var _FFLiInvalidatePartsTextures = Module["_FFLiInvalidatePartsTextures"] = wasmExports["V"]; + var _FFLiInvalidateRawMask = Module["_FFLiInvalidateRawMask"] = wasmExports["W"]; + var _GX2CalcSurfaceSizeAndAlignment = Module["_GX2CalcSurfaceSizeAndAlignment"] = wasmExports["X"]; + var _GX2CopySurface = Module["_GX2CopySurface"] = wasmExports["Y"]; + var _FFLiVerifyCharInfoWithReason = Module["_FFLiVerifyCharInfoWithReason"] = wasmExports["Z"]; + var _malloc = Module["_malloc"] = wasmExports["_"]; + var _free = Module["_free"] = wasmExports["$"]; + Module["addFunction"] = addFunction; + Module["removeFunction"] = removeFunction; + function run() { + if (runDependencies > 0) { + dependenciesFulfilled = run; + return; + } + preRun(); + if (runDependencies > 0) { + dependenciesFulfilled = run; + return; + } + function doRun() { + Module["calledRun"] = true; + if (ABORT) + return; + initRuntime(); + readyPromiseResolve(Module); + Module["onRuntimeInitialized"]?.(); + postRun(); + } + { + doRun(); + } + } + run(); + moduleRtn = readyPromise; + return moduleRtn; + }; + })(); + if (typeof exports2 === "object" && typeof module2 === "object") { + module2.exports = ModuleFFL; + module2.exports.default = ModuleFFL; + } else if (typeof define === "function" && define["amd"]) + define([], () => ModuleFFL); +}); + +// node_modules/three/build/three.module.js +var exports_three_module = {}; +__export(exports_three_module, { + createCanvasElement: () => createCanvasElement, + ZeroStencilOp: () => ZeroStencilOp, + ZeroSlopeEnding: () => ZeroSlopeEnding, + ZeroFactor: () => ZeroFactor, + ZeroCurvatureEnding: () => ZeroCurvatureEnding, + WrapAroundEnding: () => WrapAroundEnding, + WireframeGeometry: () => WireframeGeometry, + WebXRController: () => WebXRController, + WebGPUCoordinateSystem: () => WebGPUCoordinateSystem, + WebGLUtils: () => WebGLUtils, + WebGLRenderer: () => WebGLRenderer, + WebGLRenderTarget: () => WebGLRenderTarget, + WebGLCubeRenderTarget: () => WebGLCubeRenderTarget, + WebGLCoordinateSystem: () => WebGLCoordinateSystem, + WebGLArrayRenderTarget: () => WebGLArrayRenderTarget, + WebGL3DRenderTarget: () => WebGL3DRenderTarget, + VideoTexture: () => VideoTexture, + VideoFrameTexture: () => VideoFrameTexture, + VectorKeyframeTrack: () => VectorKeyframeTrack, + Vector4: () => Vector4, + Vector3: () => Vector3, + Vector2: () => Vector2, + VSMShadowMap: () => VSMShadowMap, + UnsignedShortType: () => UnsignedShortType, + UnsignedShort5551Type: () => UnsignedShort5551Type, + UnsignedShort4444Type: () => UnsignedShort4444Type, + UnsignedIntType: () => UnsignedIntType, + UnsignedInt5999Type: () => UnsignedInt5999Type, + UnsignedInt248Type: () => UnsignedInt248Type, + UnsignedByteType: () => UnsignedByteType, + UniformsUtils: () => UniformsUtils, + UniformsLib: () => UniformsLib, + UniformsGroup: () => UniformsGroup, + Uniform: () => Uniform, + Uint8ClampedBufferAttribute: () => Uint8ClampedBufferAttribute, + Uint8BufferAttribute: () => Uint8BufferAttribute, + Uint32BufferAttribute: () => Uint32BufferAttribute, + Uint16BufferAttribute: () => Uint16BufferAttribute, + UVMapping: () => UVMapping, + TubeGeometry: () => TubeGeometry, + TrianglesDrawMode: () => TrianglesDrawMode, + TriangleStripDrawMode: () => TriangleStripDrawMode, + TriangleFanDrawMode: () => TriangleFanDrawMode, + Triangle: () => Triangle, + TorusKnotGeometry: () => TorusKnotGeometry, + TorusGeometry: () => TorusGeometry, + TimestampQuery: () => TimestampQuery, + TextureUtils: () => TextureUtils, + TextureLoader: () => TextureLoader, + Texture: () => Texture, + TetrahedronGeometry: () => TetrahedronGeometry, + TangentSpaceNormalMap: () => TangentSpaceNormalMap, + TOUCH: () => TOUCH, + SubtractiveBlending: () => SubtractiveBlending, + SubtractEquation: () => SubtractEquation, + StringKeyframeTrack: () => StringKeyframeTrack, + StreamReadUsage: () => StreamReadUsage, + StreamDrawUsage: () => StreamDrawUsage, + StreamCopyUsage: () => StreamCopyUsage, + StereoCamera: () => StereoCamera, + StaticReadUsage: () => StaticReadUsage, + StaticDrawUsage: () => StaticDrawUsage, + StaticCopyUsage: () => StaticCopyUsage, + SrcColorFactor: () => SrcColorFactor, + SrcAlphaSaturateFactor: () => SrcAlphaSaturateFactor, + SrcAlphaFactor: () => SrcAlphaFactor, + SpriteMaterial: () => SpriteMaterial, + Sprite: () => Sprite, + SpotLightHelper: () => SpotLightHelper, + SpotLight: () => SpotLight, + SplineCurve: () => SplineCurve, + SphericalHarmonics3: () => SphericalHarmonics3, + Spherical: () => Spherical, + SphereGeometry: () => SphereGeometry, + Sphere: () => Sphere, + Source: () => Source, + SkinnedMesh: () => SkinnedMesh, + SkeletonHelper: () => SkeletonHelper, + Skeleton: () => Skeleton, + ShortType: () => ShortType, + ShapeUtils: () => ShapeUtils, + ShapePath: () => ShapePath2, + ShapeGeometry: () => ShapeGeometry, + Shape: () => Shape, + ShadowMaterial: () => ShadowMaterial, + ShaderMaterial: () => ShaderMaterial, + ShaderLib: () => ShaderLib, + ShaderChunk: () => ShaderChunk, + Scene: () => Scene, + SRGBTransfer: () => SRGBTransfer, + SRGBColorSpace: () => SRGBColorSpace, + SIGNED_RED_RGTC1_Format: () => SIGNED_RED_RGTC1_Format, + SIGNED_RED_GREEN_RGTC2_Format: () => SIGNED_RED_GREEN_RGTC2_Format, + RingGeometry: () => RingGeometry, + ReverseSubtractEquation: () => ReverseSubtractEquation, + ReplaceStencilOp: () => ReplaceStencilOp, + RepeatWrapping: () => RepeatWrapping, + RenderTargetArray: () => RenderTargetArray, + RenderTarget3D: () => RenderTarget3D, + RenderTarget: () => RenderTarget, + ReinhardToneMapping: () => ReinhardToneMapping, + RedIntegerFormat: () => RedIntegerFormat, + RedFormat: () => RedFormat, + RectAreaLight: () => RectAreaLight, + Raycaster: () => Raycaster, + Ray: () => Ray, + RawShaderMaterial: () => RawShaderMaterial, + RGIntegerFormat: () => RGIntegerFormat, + RGFormat: () => RGFormat, + RGDepthPacking: () => RGDepthPacking, + RGB_S3TC_DXT1_Format: () => RGB_S3TC_DXT1_Format, + RGB_PVRTC_4BPPV1_Format: () => RGB_PVRTC_4BPPV1_Format, + RGB_PVRTC_2BPPV1_Format: () => RGB_PVRTC_2BPPV1_Format, + RGB_ETC2_Format: () => RGB_ETC2_Format, + RGB_ETC1_Format: () => RGB_ETC1_Format, + RGB_BPTC_UNSIGNED_Format: () => RGB_BPTC_UNSIGNED_Format, + RGB_BPTC_SIGNED_Format: () => RGB_BPTC_SIGNED_Format, + RGBIntegerFormat: () => RGBIntegerFormat, + RGBFormat: () => RGBFormat, + RGBDepthPacking: () => RGBDepthPacking, + RGBA_S3TC_DXT5_Format: () => RGBA_S3TC_DXT5_Format, + RGBA_S3TC_DXT3_Format: () => RGBA_S3TC_DXT3_Format, + RGBA_S3TC_DXT1_Format: () => RGBA_S3TC_DXT1_Format, + RGBA_PVRTC_4BPPV1_Format: () => RGBA_PVRTC_4BPPV1_Format, + RGBA_PVRTC_2BPPV1_Format: () => RGBA_PVRTC_2BPPV1_Format, + RGBA_ETC2_EAC_Format: () => RGBA_ETC2_EAC_Format, + RGBA_BPTC_Format: () => RGBA_BPTC_Format, + RGBA_ASTC_8x8_Format: () => RGBA_ASTC_8x8_Format, + RGBA_ASTC_8x6_Format: () => RGBA_ASTC_8x6_Format, + RGBA_ASTC_8x5_Format: () => RGBA_ASTC_8x5_Format, + RGBA_ASTC_6x6_Format: () => RGBA_ASTC_6x6_Format, + RGBA_ASTC_6x5_Format: () => RGBA_ASTC_6x5_Format, + RGBA_ASTC_5x5_Format: () => RGBA_ASTC_5x5_Format, + RGBA_ASTC_5x4_Format: () => RGBA_ASTC_5x4_Format, + RGBA_ASTC_4x4_Format: () => RGBA_ASTC_4x4_Format, + RGBA_ASTC_12x12_Format: () => RGBA_ASTC_12x12_Format, + RGBA_ASTC_12x10_Format: () => RGBA_ASTC_12x10_Format, + RGBA_ASTC_10x8_Format: () => RGBA_ASTC_10x8_Format, + RGBA_ASTC_10x6_Format: () => RGBA_ASTC_10x6_Format, + RGBA_ASTC_10x5_Format: () => RGBA_ASTC_10x5_Format, + RGBA_ASTC_10x10_Format: () => RGBA_ASTC_10x10_Format, + RGBAIntegerFormat: () => RGBAIntegerFormat, + RGBAFormat: () => RGBAFormat, + RGBADepthPacking: () => RGBADepthPacking, + REVISION: () => REVISION, + RED_RGTC1_Format: () => RED_RGTC1_Format, + RED_GREEN_RGTC2_Format: () => RED_GREEN_RGTC2_Format, + QuaternionLinearInterpolant: () => QuaternionLinearInterpolant, + QuaternionKeyframeTrack: () => QuaternionKeyframeTrack, + Quaternion: () => Quaternion, + QuadraticBezierCurve3: () => QuadraticBezierCurve3, + QuadraticBezierCurve: () => QuadraticBezierCurve, + PropertyMixer: () => PropertyMixer, + PropertyBinding: () => PropertyBinding, + PositionalAudio: () => PositionalAudio, + PolyhedronGeometry: () => PolyhedronGeometry, + PolarGridHelper: () => PolarGridHelper, + PointsMaterial: () => PointsMaterial, + Points: () => Points, + PointLightHelper: () => PointLightHelper, + PointLight: () => PointLight, + PlaneHelper: () => PlaneHelper, + PlaneGeometry: () => PlaneGeometry, + Plane: () => Plane, + PerspectiveCamera: () => PerspectiveCamera, + Path: () => Path, + PMREMGenerator: () => PMREMGenerator, + PCFSoftShadowMap: () => PCFSoftShadowMap, + PCFShadowMap: () => PCFShadowMap, + OrthographicCamera: () => OrthographicCamera, + OneMinusSrcColorFactor: () => OneMinusSrcColorFactor, + OneMinusSrcAlphaFactor: () => OneMinusSrcAlphaFactor, + OneMinusDstColorFactor: () => OneMinusDstColorFactor, + OneMinusDstAlphaFactor: () => OneMinusDstAlphaFactor, + OneMinusConstantColorFactor: () => OneMinusConstantColorFactor, + OneMinusConstantAlphaFactor: () => OneMinusConstantAlphaFactor, + OneFactor: () => OneFactor, + OctahedronGeometry: () => OctahedronGeometry, + ObjectSpaceNormalMap: () => ObjectSpaceNormalMap, + ObjectLoader: () => ObjectLoader, + Object3D: () => Object3D, + NumberKeyframeTrack: () => NumberKeyframeTrack, + NotEqualStencilFunc: () => NotEqualStencilFunc, + NotEqualDepth: () => NotEqualDepth, + NotEqualCompare: () => NotEqualCompare, + NormalBlending: () => NormalBlending, + NormalAnimationBlendMode: () => NormalAnimationBlendMode, + NoToneMapping: () => NoToneMapping, + NoColorSpace: () => NoColorSpace, + NoBlending: () => NoBlending, + NeverStencilFunc: () => NeverStencilFunc, + NeverDepth: () => NeverDepth, + NeverCompare: () => NeverCompare, + NeutralToneMapping: () => NeutralToneMapping, + NearestMipmapNearestFilter: () => NearestMipmapNearestFilter, + NearestMipmapLinearFilter: () => NearestMipmapLinearFilter, + NearestMipMapNearestFilter: () => NearestMipMapNearestFilter, + NearestMipMapLinearFilter: () => NearestMipMapLinearFilter, + NearestFilter: () => NearestFilter, + MultiplyOperation: () => MultiplyOperation, + MultiplyBlending: () => MultiplyBlending, + MixOperation: () => MixOperation, + MirroredRepeatWrapping: () => MirroredRepeatWrapping, + MinEquation: () => MinEquation, + MeshToonMaterial: () => MeshToonMaterial, + MeshStandardMaterial: () => MeshStandardMaterial, + MeshPhysicalMaterial: () => MeshPhysicalMaterial, + MeshPhongMaterial: () => MeshPhongMaterial, + MeshNormalMaterial: () => MeshNormalMaterial, + MeshMatcapMaterial: () => MeshMatcapMaterial, + MeshLambertMaterial: () => MeshLambertMaterial, + MeshDistanceMaterial: () => MeshDistanceMaterial, + MeshDepthMaterial: () => MeshDepthMaterial, + MeshBasicMaterial: () => MeshBasicMaterial, + Mesh: () => Mesh, + MaxEquation: () => MaxEquation, + Matrix4: () => Matrix4, + Matrix3: () => Matrix3, + Matrix2: () => Matrix2, + MathUtils: () => MathUtils, + MaterialLoader: () => MaterialLoader, + Material: () => Material, + MOUSE: () => MOUSE, + LuminanceFormat: () => LuminanceFormat, + LuminanceAlphaFormat: () => LuminanceAlphaFormat, + LoopRepeat: () => LoopRepeat, + LoopPingPong: () => LoopPingPong, + LoopOnce: () => LoopOnce, + LoadingManager: () => LoadingManager, + LoaderUtils: () => LoaderUtils, + Loader: () => Loader, + LinearTransfer: () => LinearTransfer, + LinearToneMapping: () => LinearToneMapping, + LinearSRGBColorSpace: () => LinearSRGBColorSpace, + LinearMipmapNearestFilter: () => LinearMipmapNearestFilter, + LinearMipmapLinearFilter: () => LinearMipmapLinearFilter, + LinearMipMapNearestFilter: () => LinearMipMapNearestFilter, + LinearMipMapLinearFilter: () => LinearMipMapLinearFilter, + LinearInterpolant: () => LinearInterpolant, + LinearFilter: () => LinearFilter, + LineSegments: () => LineSegments, + LineLoop: () => LineLoop, + LineDashedMaterial: () => LineDashedMaterial, + LineCurve3: () => LineCurve3, + LineCurve: () => LineCurve, + LineBasicMaterial: () => LineBasicMaterial, + Line3: () => Line3, + Line: () => Line, + LightProbe: () => LightProbe, + Light: () => Light, + LessStencilFunc: () => LessStencilFunc, + LessEqualStencilFunc: () => LessEqualStencilFunc, + LessEqualDepth: () => LessEqualDepth, + LessEqualCompare: () => LessEqualCompare, + LessDepth: () => LessDepth, + LessCompare: () => LessCompare, + Layers: () => Layers, + LatheGeometry: () => LatheGeometry, + LOD: () => LOD, + KeyframeTrack: () => KeyframeTrack, + KeepStencilOp: () => KeepStencilOp, + InvertStencilOp: () => InvertStencilOp, + InterpolateSmooth: () => InterpolateSmooth, + InterpolateLinear: () => InterpolateLinear, + InterpolateDiscrete: () => InterpolateDiscrete, + Interpolant: () => Interpolant, + InterleavedBufferAttribute: () => InterleavedBufferAttribute, + InterleavedBuffer: () => InterleavedBuffer, + IntType: () => IntType, + Int8BufferAttribute: () => Int8BufferAttribute, + Int32BufferAttribute: () => Int32BufferAttribute, + Int16BufferAttribute: () => Int16BufferAttribute, + InstancedMesh: () => InstancedMesh, + InstancedInterleavedBuffer: () => InstancedInterleavedBuffer, + InstancedBufferGeometry: () => InstancedBufferGeometry, + InstancedBufferAttribute: () => InstancedBufferAttribute, + IncrementWrapStencilOp: () => IncrementWrapStencilOp, + IncrementStencilOp: () => IncrementStencilOp, + ImageUtils: () => ImageUtils, + ImageLoader: () => ImageLoader, + ImageBitmapLoader: () => ImageBitmapLoader, + IcosahedronGeometry: () => IcosahedronGeometry, + HemisphereLightHelper: () => HemisphereLightHelper, + HemisphereLight: () => HemisphereLight, + HalfFloatType: () => HalfFloatType, + Group: () => Group, + GridHelper: () => GridHelper, + GreaterStencilFunc: () => GreaterStencilFunc, + GreaterEqualStencilFunc: () => GreaterEqualStencilFunc, + GreaterEqualDepth: () => GreaterEqualDepth, + GreaterEqualCompare: () => GreaterEqualCompare, + GreaterDepth: () => GreaterDepth, + GreaterCompare: () => GreaterCompare, + GLSL3: () => GLSL3, + GLSL1: () => GLSL1, + GLBufferAttribute: () => GLBufferAttribute, + Frustum: () => Frustum, + FrontSide: () => FrontSide, + FramebufferTexture: () => FramebufferTexture, + FogExp2: () => FogExp2, + Fog: () => Fog, + FloatType: () => FloatType, + Float32BufferAttribute: () => Float32BufferAttribute, + Float16BufferAttribute: () => Float16BufferAttribute, + FileLoader: () => FileLoader, + ExtrudeGeometry: () => ExtrudeGeometry, + EventDispatcher: () => EventDispatcher, + Euler: () => Euler, + EquirectangularRefractionMapping: () => EquirectangularRefractionMapping, + EquirectangularReflectionMapping: () => EquirectangularReflectionMapping, + EqualStencilFunc: () => EqualStencilFunc, + EqualDepth: () => EqualDepth, + EqualCompare: () => EqualCompare, + EllipseCurve: () => EllipseCurve, + EdgesGeometry: () => EdgesGeometry, + DynamicReadUsage: () => DynamicReadUsage, + DynamicDrawUsage: () => DynamicDrawUsage, + DynamicCopyUsage: () => DynamicCopyUsage, + DstColorFactor: () => DstColorFactor, + DstAlphaFactor: () => DstAlphaFactor, + DoubleSide: () => DoubleSide, + DodecahedronGeometry: () => DodecahedronGeometry, + DiscreteInterpolant: () => DiscreteInterpolant, + DirectionalLightHelper: () => DirectionalLightHelper, + DirectionalLight: () => DirectionalLight, + DetachedBindMode: () => DetachedBindMode, + DepthTexture: () => DepthTexture, + DepthStencilFormat: () => DepthStencilFormat, + DepthFormat: () => DepthFormat, + DefaultLoadingManager: () => DefaultLoadingManager, + DecrementWrapStencilOp: () => DecrementWrapStencilOp, + DecrementStencilOp: () => DecrementStencilOp, + DataUtils: () => DataUtils, + DataTextureLoader: () => DataTextureLoader, + DataTexture: () => DataTexture, + DataArrayTexture: () => DataArrayTexture, + Data3DTexture: () => Data3DTexture, + Cylindrical: () => Cylindrical, + CylinderGeometry: () => CylinderGeometry, + CustomToneMapping: () => CustomToneMapping, + CustomBlending: () => CustomBlending, + CurvePath: () => CurvePath, + Curve: () => Curve, + CullFaceNone: () => CullFaceNone, + CullFaceFrontBack: () => CullFaceFrontBack, + CullFaceFront: () => CullFaceFront, + CullFaceBack: () => CullFaceBack, + CubicInterpolant: () => CubicInterpolant, + CubicBezierCurve3: () => CubicBezierCurve3, + CubicBezierCurve: () => CubicBezierCurve, + CubeUVReflectionMapping: () => CubeUVReflectionMapping, + CubeTextureLoader: () => CubeTextureLoader, + CubeTexture: () => CubeTexture, + CubeRefractionMapping: () => CubeRefractionMapping, + CubeReflectionMapping: () => CubeReflectionMapping, + CubeCamera: () => CubeCamera, + Controls: () => Controls, + ConstantColorFactor: () => ConstantColorFactor, + ConstantAlphaFactor: () => ConstantAlphaFactor, + ConeGeometry: () => ConeGeometry, + CompressedTextureLoader: () => CompressedTextureLoader, + CompressedTexture: () => CompressedTexture, + CompressedCubeTexture: () => CompressedCubeTexture, + CompressedArrayTexture: () => CompressedArrayTexture, + ColorManagement: () => ColorManagement, + ColorKeyframeTrack: () => ColorKeyframeTrack, + Color: () => Color, + Clock: () => Clock, + ClampToEdgeWrapping: () => ClampToEdgeWrapping, + CircleGeometry: () => CircleGeometry, + CineonToneMapping: () => CineonToneMapping, + CatmullRomCurve3: () => CatmullRomCurve3, + CapsuleGeometry: () => CapsuleGeometry, + CanvasTexture: () => CanvasTexture, + CameraHelper: () => CameraHelper, + Camera: () => Camera, + Cache: () => Cache, + ByteType: () => ByteType, + BufferGeometryLoader: () => BufferGeometryLoader, + BufferGeometry: () => BufferGeometry, + BufferAttribute: () => BufferAttribute, + BoxHelper: () => BoxHelper, + BoxGeometry: () => BoxGeometry, + Box3Helper: () => Box3Helper, + Box3: () => Box3, + Box2: () => Box2, + BooleanKeyframeTrack: () => BooleanKeyframeTrack, + Bone: () => Bone, + BatchedMesh: () => BatchedMesh, + BasicShadowMap: () => BasicShadowMap, + BasicDepthPacking: () => BasicDepthPacking, + BackSide: () => BackSide, + AxesHelper: () => AxesHelper, + AudioLoader: () => AudioLoader, + AudioListener: () => AudioListener, + AudioContext: () => AudioContext, + AudioAnalyser: () => AudioAnalyser, + Audio: () => Audio, + AttachedBindMode: () => AttachedBindMode, + ArrowHelper: () => ArrowHelper, + ArrayCamera: () => ArrayCamera, + ArcCurve: () => ArcCurve, + AnimationUtils: () => AnimationUtils, + AnimationObjectGroup: () => AnimationObjectGroup, + AnimationMixer: () => AnimationMixer, + AnimationLoader: () => AnimationLoader, + AnimationClip: () => AnimationClip, + AnimationAction: () => AnimationAction, + AmbientLight: () => AmbientLight, + AlwaysStencilFunc: () => AlwaysStencilFunc, + AlwaysDepth: () => AlwaysDepth, + AlwaysCompare: () => AlwaysCompare, + AlphaFormat: () => AlphaFormat, + AgXToneMapping: () => AgXToneMapping, + AdditiveBlending: () => AdditiveBlending, + AdditiveAnimationBlendMode: () => AdditiveAnimationBlendMode, + AddOperation: () => AddOperation, + AddEquation: () => AddEquation, + ACESFilmicToneMapping: () => ACESFilmicToneMapping +}); + +// node_modules/three/build/three.core.js +var REVISION = "173"; +var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; +var TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; +var CullFaceNone = 0; +var CullFaceBack = 1; +var CullFaceFront = 2; +var CullFaceFrontBack = 3; +var BasicShadowMap = 0; +var PCFShadowMap = 1; +var PCFSoftShadowMap = 2; +var VSMShadowMap = 3; +var FrontSide = 0; +var BackSide = 1; +var DoubleSide = 2; +var NoBlending = 0; +var NormalBlending = 1; +var AdditiveBlending = 2; +var SubtractiveBlending = 3; +var MultiplyBlending = 4; +var CustomBlending = 5; +var AddEquation = 100; +var SubtractEquation = 101; +var ReverseSubtractEquation = 102; +var MinEquation = 103; +var MaxEquation = 104; +var ZeroFactor = 200; +var OneFactor = 201; +var SrcColorFactor = 202; +var OneMinusSrcColorFactor = 203; +var SrcAlphaFactor = 204; +var OneMinusSrcAlphaFactor = 205; +var DstAlphaFactor = 206; +var OneMinusDstAlphaFactor = 207; +var DstColorFactor = 208; +var OneMinusDstColorFactor = 209; +var SrcAlphaSaturateFactor = 210; +var ConstantColorFactor = 211; +var OneMinusConstantColorFactor = 212; +var ConstantAlphaFactor = 213; +var OneMinusConstantAlphaFactor = 214; +var NeverDepth = 0; +var AlwaysDepth = 1; +var LessDepth = 2; +var LessEqualDepth = 3; +var EqualDepth = 4; +var GreaterEqualDepth = 5; +var GreaterDepth = 6; +var NotEqualDepth = 7; +var MultiplyOperation = 0; +var MixOperation = 1; +var AddOperation = 2; +var NoToneMapping = 0; +var LinearToneMapping = 1; +var ReinhardToneMapping = 2; +var CineonToneMapping = 3; +var ACESFilmicToneMapping = 4; +var CustomToneMapping = 5; +var AgXToneMapping = 6; +var NeutralToneMapping = 7; +var AttachedBindMode = "attached"; +var DetachedBindMode = "detached"; +var UVMapping = 300; +var CubeReflectionMapping = 301; +var CubeRefractionMapping = 302; +var EquirectangularReflectionMapping = 303; +var EquirectangularRefractionMapping = 304; +var CubeUVReflectionMapping = 306; +var RepeatWrapping = 1000; +var ClampToEdgeWrapping = 1001; +var MirroredRepeatWrapping = 1002; +var NearestFilter = 1003; +var NearestMipmapNearestFilter = 1004; +var NearestMipMapNearestFilter = 1004; +var NearestMipmapLinearFilter = 1005; +var NearestMipMapLinearFilter = 1005; +var LinearFilter = 1006; +var LinearMipmapNearestFilter = 1007; +var LinearMipMapNearestFilter = 1007; +var LinearMipmapLinearFilter = 1008; +var LinearMipMapLinearFilter = 1008; +var UnsignedByteType = 1009; +var ByteType = 1010; +var ShortType = 1011; +var UnsignedShortType = 1012; +var IntType = 1013; +var UnsignedIntType = 1014; +var FloatType = 1015; +var HalfFloatType = 1016; +var UnsignedShort4444Type = 1017; +var UnsignedShort5551Type = 1018; +var UnsignedInt248Type = 1020; +var UnsignedInt5999Type = 35902; +var AlphaFormat = 1021; +var RGBFormat = 1022; +var RGBAFormat = 1023; +var LuminanceFormat = 1024; +var LuminanceAlphaFormat = 1025; +var DepthFormat = 1026; +var DepthStencilFormat = 1027; +var RedFormat = 1028; +var RedIntegerFormat = 1029; +var RGFormat = 1030; +var RGIntegerFormat = 1031; +var RGBIntegerFormat = 1032; +var RGBAIntegerFormat = 1033; +var RGB_S3TC_DXT1_Format = 33776; +var RGBA_S3TC_DXT1_Format = 33777; +var RGBA_S3TC_DXT3_Format = 33778; +var RGBA_S3TC_DXT5_Format = 33779; +var RGB_PVRTC_4BPPV1_Format = 35840; +var RGB_PVRTC_2BPPV1_Format = 35841; +var RGBA_PVRTC_4BPPV1_Format = 35842; +var RGBA_PVRTC_2BPPV1_Format = 35843; +var RGB_ETC1_Format = 36196; +var RGB_ETC2_Format = 37492; +var RGBA_ETC2_EAC_Format = 37496; +var RGBA_ASTC_4x4_Format = 37808; +var RGBA_ASTC_5x4_Format = 37809; +var RGBA_ASTC_5x5_Format = 37810; +var RGBA_ASTC_6x5_Format = 37811; +var RGBA_ASTC_6x6_Format = 37812; +var RGBA_ASTC_8x5_Format = 37813; +var RGBA_ASTC_8x6_Format = 37814; +var RGBA_ASTC_8x8_Format = 37815; +var RGBA_ASTC_10x5_Format = 37816; +var RGBA_ASTC_10x6_Format = 37817; +var RGBA_ASTC_10x8_Format = 37818; +var RGBA_ASTC_10x10_Format = 37819; +var RGBA_ASTC_12x10_Format = 37820; +var RGBA_ASTC_12x12_Format = 37821; +var RGBA_BPTC_Format = 36492; +var RGB_BPTC_SIGNED_Format = 36494; +var RGB_BPTC_UNSIGNED_Format = 36495; +var RED_RGTC1_Format = 36283; +var SIGNED_RED_RGTC1_Format = 36284; +var RED_GREEN_RGTC2_Format = 36285; +var SIGNED_RED_GREEN_RGTC2_Format = 36286; +var LoopOnce = 2200; +var LoopRepeat = 2201; +var LoopPingPong = 2202; +var InterpolateDiscrete = 2300; +var InterpolateLinear = 2301; +var InterpolateSmooth = 2302; +var ZeroCurvatureEnding = 2400; +var ZeroSlopeEnding = 2401; +var WrapAroundEnding = 2402; +var NormalAnimationBlendMode = 2500; +var AdditiveAnimationBlendMode = 2501; +var TrianglesDrawMode = 0; +var TriangleStripDrawMode = 1; +var TriangleFanDrawMode = 2; +var BasicDepthPacking = 3200; +var RGBADepthPacking = 3201; +var RGBDepthPacking = 3202; +var RGDepthPacking = 3203; +var TangentSpaceNormalMap = 0; +var ObjectSpaceNormalMap = 1; +var NoColorSpace = ""; +var SRGBColorSpace = "srgb"; +var LinearSRGBColorSpace = "srgb-linear"; +var LinearTransfer = "linear"; +var SRGBTransfer = "srgb"; +var ZeroStencilOp = 0; +var KeepStencilOp = 7680; +var ReplaceStencilOp = 7681; +var IncrementStencilOp = 7682; +var DecrementStencilOp = 7683; +var IncrementWrapStencilOp = 34055; +var DecrementWrapStencilOp = 34056; +var InvertStencilOp = 5386; +var NeverStencilFunc = 512; +var LessStencilFunc = 513; +var EqualStencilFunc = 514; +var LessEqualStencilFunc = 515; +var GreaterStencilFunc = 516; +var NotEqualStencilFunc = 517; +var GreaterEqualStencilFunc = 518; +var AlwaysStencilFunc = 519; +var NeverCompare = 512; +var LessCompare = 513; +var EqualCompare = 514; +var LessEqualCompare = 515; +var GreaterCompare = 516; +var NotEqualCompare = 517; +var GreaterEqualCompare = 518; +var AlwaysCompare = 519; +var StaticDrawUsage = 35044; +var DynamicDrawUsage = 35048; +var StreamDrawUsage = 35040; +var StaticReadUsage = 35045; +var DynamicReadUsage = 35049; +var StreamReadUsage = 35041; +var StaticCopyUsage = 35046; +var DynamicCopyUsage = 35050; +var StreamCopyUsage = 35042; +var GLSL1 = "100"; +var GLSL3 = "300 es"; +var WebGLCoordinateSystem = 2000; +var WebGPUCoordinateSystem = 2001; +var TimestampQuery = { + COMPUTE: "compute", + RENDER: "render" +}; + +class EventDispatcher { + addEventListener(type, listener) { + if (this._listeners === undefined) + this._listeners = {}; + const listeners = this._listeners; + if (listeners[type] === undefined) { + listeners[type] = []; + } + if (listeners[type].indexOf(listener) === -1) { + listeners[type].push(listener); + } + } + hasEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === undefined) + return false; + return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1; + } + removeEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === undefined) + return; + const listenerArray = listeners[type]; + if (listenerArray !== undefined) { + const index2 = listenerArray.indexOf(listener); + if (index2 !== -1) { + listenerArray.splice(index2, 1); + } + } + } + dispatchEvent(event) { + const listeners = this._listeners; + if (listeners === undefined) + return; + const listenerArray = listeners[event.type]; + if (listenerArray !== undefined) { + event.target = this; + const array = listenerArray.slice(0); + for (let i = 0, l = array.length;i < l; i++) { + array[i].call(this, event); + } + event.target = null; + } + } +} +var _lut = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"]; +var _seed = 1234567; +var DEG2RAD = Math.PI / 180; +var RAD2DEG = 180 / Math.PI; +function generateUUID() { + const d0 = Math.random() * 4294967295 | 0; + const d1 = Math.random() * 4294967295 | 0; + const d2 = Math.random() * 4294967295 | 0; + const d3 = Math.random() * 4294967295 | 0; + const uuid = _lut[d0 & 255] + _lut[d0 >> 8 & 255] + _lut[d0 >> 16 & 255] + _lut[d0 >> 24 & 255] + "-" + _lut[d1 & 255] + _lut[d1 >> 8 & 255] + "-" + _lut[d1 >> 16 & 15 | 64] + _lut[d1 >> 24 & 255] + "-" + _lut[d2 & 63 | 128] + _lut[d2 >> 8 & 255] + "-" + _lut[d2 >> 16 & 255] + _lut[d2 >> 24 & 255] + _lut[d3 & 255] + _lut[d3 >> 8 & 255] + _lut[d3 >> 16 & 255] + _lut[d3 >> 24 & 255]; + return uuid.toLowerCase(); +} +function clamp2(value2, min, max) { + return Math.max(min, Math.min(max, value2)); +} +function euclideanModulo(n, m) { + return (n % m + m) % m; +} +function mapLinear(x, a1, a2, b1, b2) { + return b1 + (x - a1) * (b2 - b1) / (a2 - a1); +} +function inverseLerp(x, y, value2) { + if (x !== y) { + return (value2 - x) / (y - x); + } else { + return 0; + } +} +function lerp(x, y, t) { + return (1 - t) * x + t * y; +} +function damp(x, y, lambda, dt) { + return lerp(x, y, 1 - Math.exp(-lambda * dt)); +} +function pingpong(x, length2 = 1) { + return length2 - Math.abs(euclideanModulo(x, length2 * 2) - length2); +} +function smoothstep(x, min, max) { + if (x <= min) + return 0; + if (x >= max) + return 1; + x = (x - min) / (max - min); + return x * x * (3 - 2 * x); +} +function smootherstep(x, min, max) { + if (x <= min) + return 0; + if (x >= max) + return 1; + x = (x - min) / (max - min); + return x * x * x * (x * (x * 6 - 15) + 10); +} +function randInt(low, high) { + return low + Math.floor(Math.random() * (high - low + 1)); +} +function randFloat(low, high) { + return low + Math.random() * (high - low); +} +function randFloatSpread(range) { + return range * (0.5 - Math.random()); +} +function seededRandom(s) { + if (s !== undefined) + _seed = s; + let t = _seed += 1831565813; + t = Math.imul(t ^ t >>> 15, t | 1); + t ^= t + Math.imul(t ^ t >>> 7, t | 61); + return ((t ^ t >>> 14) >>> 0) / 4294967296; +} +function degToRad(degrees) { + return degrees * DEG2RAD; +} +function radToDeg(radians) { + return radians * RAD2DEG; +} +function isPowerOfTwo(value2) { + return (value2 & value2 - 1) === 0 && value2 !== 0; +} +function ceilPowerOfTwo(value2) { + return Math.pow(2, Math.ceil(Math.log(value2) / Math.LN2)); +} +function floorPowerOfTwo(value2) { + return Math.pow(2, Math.floor(Math.log(value2) / Math.LN2)); +} +function setQuaternionFromProperEuler(q, a, b, c, order) { + const cos = Math.cos; + const sin = Math.sin; + const c2 = cos(b / 2); + const s2 = sin(b / 2); + const c13 = cos((a + c) / 2); + const s13 = sin((a + c) / 2); + const c1_3 = cos((a - c) / 2); + const s1_3 = sin((a - c) / 2); + const c3_1 = cos((c - a) / 2); + const s3_1 = sin((c - a) / 2); + switch (order) { + case "XYX": + q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13); + break; + case "YZY": + q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13); + break; + case "ZXZ": + q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13); + break; + case "XZX": + q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13); + break; + case "YXY": + q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13); + break; + case "ZYZ": + q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13); + break; + default: + console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + order); + } +} +function denormalize(value2, array) { + switch (array.constructor) { + case Float32Array: + return value2; + case Uint32Array: + return value2 / 4294967295; + case Uint16Array: + return value2 / 65535; + case Uint8Array: + return value2 / 255; + case Int32Array: + return Math.max(value2 / 2147483647, -1); + case Int16Array: + return Math.max(value2 / 32767, -1); + case Int8Array: + return Math.max(value2 / 127, -1); + default: + throw new Error("Invalid component type."); + } +} +function normalize2(value2, array) { + switch (array.constructor) { + case Float32Array: + return value2; + case Uint32Array: + return Math.round(value2 * 4294967295); + case Uint16Array: + return Math.round(value2 * 65535); + case Uint8Array: + return Math.round(value2 * 255); + case Int32Array: + return Math.round(value2 * 2147483647); + case Int16Array: + return Math.round(value2 * 32767); + case Int8Array: + return Math.round(value2 * 127); + default: + throw new Error("Invalid component type."); + } +} +var MathUtils = { + DEG2RAD, + RAD2DEG, + generateUUID, + clamp: clamp2, + euclideanModulo, + mapLinear, + inverseLerp, + lerp, + damp, + pingpong, + smoothstep, + smootherstep, + randInt, + randFloat, + randFloatSpread, + seededRandom, + degToRad, + radToDeg, + isPowerOfTwo, + ceilPowerOfTwo, + floorPowerOfTwo, + setQuaternionFromProperEuler, + normalize: normalize2, + denormalize +}; + +class Vector2 { + constructor(x = 0, y = 0) { + Vector2.prototype.isVector2 = true; + this.x = x; + this.y = y; + } + get width() { + return this.x; + } + set width(value2) { + this.x = value2; + } + get height() { + return this.y; + } + set height(value2) { + this.y = value2; + } + set(x, y) { + this.x = x; + this.y = y; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y); + } + copy(v) { + this.x = v.x; + this.y = v.y; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + applyMatrix3(m) { + const x = this.x, y = this.y; + const e = m.elements; + this.x = e[0] * x + e[3] * y + e[6]; + this.y = e[1] * x + e[4] * y + e[7]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + return this; + } + clamp(min, max) { + this.x = clamp2(this.x, min.x, max.x); + this.y = clamp2(this.y, min.y, max.y); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp2(this.x, minVal, maxVal); + this.y = clamp2(this.y, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp2(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y; + } + cross(v) { + return this.x * v.y - this.y * v.x; + } + lengthSq() { + return this.x * this.x + this.y * this.y; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + angle() { + const angle = Math.atan2(-this.y, -this.x) + Math.PI; + return angle; + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) + return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp2(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + return this; + } + rotateAround(center, angle) { + const c = Math.cos(angle), s = Math.sin(angle); + const x = this.x - center.x; + const y = this.y - center.y; + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + } +} + +class Matrix3 { + constructor(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + Matrix3.prototype.isMatrix3 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n13, n21, n22, n23, n31, n32, n33); + } + } + set(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + const te = this.elements; + te[0] = n11; + te[1] = n21; + te[2] = n31; + te[3] = n12; + te[4] = n22; + te[5] = n32; + te[6] = n13; + te[7] = n23; + te[8] = n33; + return this; + } + identity() { + this.set(1, 0, 0, 0, 1, 0, 0, 0, 1); + return this; + } + copy(m) { + const te = this.elements; + const me = m.elements; + te[0] = me[0]; + te[1] = me[1]; + te[2] = me[2]; + te[3] = me[3]; + te[4] = me[4]; + te[5] = me[5]; + te[6] = me[6]; + te[7] = me[7]; + te[8] = me[8]; + return this; + } + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrix3Column(this, 0); + yAxis.setFromMatrix3Column(this, 1); + zAxis.setFromMatrix3Column(this, 2); + return this; + } + setFromMatrix4(m) { + const me = m.elements; + this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]); + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a, b) { + const ae = a.elements; + const be = b.elements; + const te = this.elements; + const a11 = ae[0], a12 = ae[3], a13 = ae[6]; + const a21 = ae[1], a22 = ae[4], a23 = ae[7]; + const a31 = ae[2], a32 = ae[5], a33 = ae[8]; + const b11 = be[0], b12 = be[3], b13 = be[6]; + const b21 = be[1], b22 = be[4], b23 = be[7]; + const b31 = be[2], b32 = be[5], b33 = be[8]; + te[0] = a11 * b11 + a12 * b21 + a13 * b31; + te[3] = a11 * b12 + a12 * b22 + a13 * b32; + te[6] = a11 * b13 + a12 * b23 + a13 * b33; + te[1] = a21 * b11 + a22 * b21 + a23 * b31; + te[4] = a21 * b12 + a22 * b22 + a23 * b32; + te[7] = a21 * b13 + a22 * b23 + a23 * b33; + te[2] = a31 * b11 + a32 * b21 + a33 * b31; + te[5] = a31 * b12 + a32 * b22 + a33 * b32; + te[8] = a31 * b13 + a32 * b23 + a33 * b33; + return this; + } + multiplyScalar(s) { + const te = this.elements; + te[0] *= s; + te[3] *= s; + te[6] *= s; + te[1] *= s; + te[4] *= s; + te[7] *= s; + te[2] *= s; + te[5] *= s; + te[8] *= s; + return this; + } + determinant() { + const te = this.elements; + const a = te[0], b = te[1], c = te[2], d = te[3], e = te[4], f = te[5], g = te[6], h = te[7], i = te[8]; + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + } + invert() { + const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n12 = te[3], n22 = te[4], n32 = te[5], n13 = te[6], n23 = te[7], n33 = te[8], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13; + if (det === 0) + return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te[0] = t11 * detInv; + te[1] = (n31 * n23 - n33 * n21) * detInv; + te[2] = (n32 * n21 - n31 * n22) * detInv; + te[3] = t12 * detInv; + te[4] = (n33 * n11 - n31 * n13) * detInv; + te[5] = (n31 * n12 - n32 * n11) * detInv; + te[6] = t13 * detInv; + te[7] = (n21 * n13 - n23 * n11) * detInv; + te[8] = (n22 * n11 - n21 * n12) * detInv; + return this; + } + transpose() { + let tmp; + const m = this.elements; + tmp = m[1]; + m[1] = m[3]; + m[3] = tmp; + tmp = m[2]; + m[2] = m[6]; + m[6] = tmp; + tmp = m[5]; + m[5] = m[7]; + m[7] = tmp; + return this; + } + getNormalMatrix(matrix4) { + return this.setFromMatrix4(matrix4).invert().transpose(); + } + transposeIntoArray(r) { + const m = this.elements; + r[0] = m[0]; + r[1] = m[3]; + r[2] = m[6]; + r[3] = m[1]; + r[4] = m[4]; + r[5] = m[7]; + r[6] = m[2]; + r[7] = m[5]; + r[8] = m[8]; + return this; + } + setUvTransform(tx, ty, sx, sy, rotation2, cx, cy) { + const c = Math.cos(rotation2); + const s = Math.sin(rotation2); + this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1); + return this; + } + scale(sx, sy) { + this.premultiply(_m3.makeScale(sx, sy)); + return this; + } + rotate(theta) { + this.premultiply(_m3.makeRotation(-theta)); + return this; + } + translate(tx, ty) { + this.premultiply(_m3.makeTranslation(tx, ty)); + return this; + } + makeTranslation(x, y) { + if (x.isVector2) { + this.set(1, 0, x.x, 0, 1, x.y, 0, 0, 1); + } else { + this.set(1, 0, x, 0, 1, y, 0, 0, 1); + } + return this; + } + makeRotation(theta) { + const c = Math.cos(theta); + const s = Math.sin(theta); + this.set(c, -s, 0, s, c, 0, 0, 0, 1); + return this; + } + makeScale(x, y) { + this.set(x, 0, 0, 0, y, 0, 0, 0, 1); + return this; + } + equals(matrix) { + const te = this.elements; + const me = matrix.elements; + for (let i = 0;i < 9; i++) { + if (te[i] !== me[i]) + return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 9; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te = this.elements; + array[offset] = te[0]; + array[offset + 1] = te[1]; + array[offset + 2] = te[2]; + array[offset + 3] = te[3]; + array[offset + 4] = te[4]; + array[offset + 5] = te[5]; + array[offset + 6] = te[6]; + array[offset + 7] = te[7]; + array[offset + 8] = te[8]; + return array; + } + clone() { + return new this.constructor().fromArray(this.elements); + } +} +var _m3 = /* @__PURE__ */ new Matrix3; +function arrayNeedsUint32(array) { + for (let i = array.length - 1;i >= 0; --i) { + if (array[i] >= 65535) + return true; + } + return false; +} +var TYPED_ARRAYS = { + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array +}; +function getTypedArray(type, buffer) { + return new TYPED_ARRAYS[type](buffer); +} +function createElementNS(name2) { + return document.createElementNS("http://www.w3.org/1999/xhtml", name2); +} +function createCanvasElement() { + const canvas = createElementNS("canvas"); + canvas.style.display = "block"; + return canvas; +} +var _cache = {}; +function warnOnce(message) { + if (message in _cache) + return; + _cache[message] = true; + console.warn(message); +} +function probeAsync(gl, sync, interval) { + return new Promise(function(resolve, reject2) { + function probe() { + switch (gl.clientWaitSync(sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0)) { + case gl.WAIT_FAILED: + reject2(); + break; + case gl.TIMEOUT_EXPIRED: + setTimeout(probe, interval); + break; + default: + resolve(); + } + } + setTimeout(probe, interval); + }); +} +function toNormalizedProjectionMatrix(projectionMatrix) { + const m = projectionMatrix.elements; + m[2] = 0.5 * m[2] + 0.5 * m[3]; + m[6] = 0.5 * m[6] + 0.5 * m[7]; + m[10] = 0.5 * m[10] + 0.5 * m[11]; + m[14] = 0.5 * m[14] + 0.5 * m[15]; +} +function toReversedProjectionMatrix(projectionMatrix) { + const m = projectionMatrix.elements; + const isPerspectiveMatrix = m[11] === -1; + if (isPerspectiveMatrix) { + m[10] = -m[10] - 1; + m[14] = -m[14]; + } else { + m[10] = -m[10]; + m[14] = -m[14] + 1; + } +} +var LINEAR_REC709_TO_XYZ = /* @__PURE__ */ new Matrix3().set(0.4123908, 0.3575843, 0.1804808, 0.212639, 0.7151687, 0.0721923, 0.0193308, 0.1191948, 0.9505322); +var XYZ_TO_LINEAR_REC709 = /* @__PURE__ */ new Matrix3().set(3.2409699, -1.5373832, -0.4986108, -0.9692436, 1.8759675, 0.0415551, 0.0556301, -0.203977, 1.0569715); +function createColorManagement() { + const ColorManagement = { + enabled: true, + workingColorSpace: LinearSRGBColorSpace, + spaces: {}, + convert: function(color, sourceColorSpace, targetColorSpace) { + if (this.enabled === false || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) { + return color; + } + if (this.spaces[sourceColorSpace].transfer === SRGBTransfer) { + color.r = SRGBToLinear(color.r); + color.g = SRGBToLinear(color.g); + color.b = SRGBToLinear(color.b); + } + if (this.spaces[sourceColorSpace].primaries !== this.spaces[targetColorSpace].primaries) { + color.applyMatrix3(this.spaces[sourceColorSpace].toXYZ); + color.applyMatrix3(this.spaces[targetColorSpace].fromXYZ); + } + if (this.spaces[targetColorSpace].transfer === SRGBTransfer) { + color.r = LinearToSRGB(color.r); + color.g = LinearToSRGB(color.g); + color.b = LinearToSRGB(color.b); + } + return color; + }, + fromWorkingColorSpace: function(color, targetColorSpace) { + return this.convert(color, this.workingColorSpace, targetColorSpace); + }, + toWorkingColorSpace: function(color, sourceColorSpace) { + return this.convert(color, sourceColorSpace, this.workingColorSpace); + }, + getPrimaries: function(colorSpace) { + return this.spaces[colorSpace].primaries; + }, + getTransfer: function(colorSpace) { + if (colorSpace === NoColorSpace) + return LinearTransfer; + return this.spaces[colorSpace].transfer; + }, + getLuminanceCoefficients: function(target, colorSpace = this.workingColorSpace) { + return target.fromArray(this.spaces[colorSpace].luminanceCoefficients); + }, + define: function(colorSpaces) { + Object.assign(this.spaces, colorSpaces); + }, + _getMatrix: function(targetMatrix, sourceColorSpace, targetColorSpace) { + return targetMatrix.copy(this.spaces[sourceColorSpace].toXYZ).multiply(this.spaces[targetColorSpace].fromXYZ); + }, + _getDrawingBufferColorSpace: function(colorSpace) { + return this.spaces[colorSpace].outputColorSpaceConfig.drawingBufferColorSpace; + }, + _getUnpackColorSpace: function(colorSpace = this.workingColorSpace) { + return this.spaces[colorSpace].workingColorSpaceConfig.unpackColorSpace; + } + }; + const REC709_PRIMARIES = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06]; + const REC709_LUMINANCE_COEFFICIENTS = [0.2126, 0.7152, 0.0722]; + const D65 = [0.3127, 0.329]; + ColorManagement.define({ + [LinearSRGBColorSpace]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: LinearTransfer, + toXYZ: LINEAR_REC709_TO_XYZ, + fromXYZ: XYZ_TO_LINEAR_REC709, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace }, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace } + }, + [SRGBColorSpace]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: SRGBTransfer, + toXYZ: LINEAR_REC709_TO_XYZ, + fromXYZ: XYZ_TO_LINEAR_REC709, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace } + } + }); + return ColorManagement; +} +var ColorManagement = /* @__PURE__ */ createColorManagement(); +function SRGBToLinear(c) { + return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); +} +function LinearToSRGB(c) { + return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055; +} +var _canvas; + +class ImageUtils { + static getDataURL(image) { + if (/^data:/i.test(image.src)) { + return image.src; + } + if (typeof HTMLCanvasElement === "undefined") { + return image.src; + } + let canvas; + if (image instanceof HTMLCanvasElement) { + canvas = image; + } else { + if (_canvas === undefined) + _canvas = createElementNS("canvas"); + _canvas.width = image.width; + _canvas.height = image.height; + const context = _canvas.getContext("2d"); + if (image instanceof ImageData) { + context.putImageData(image, 0, 0); + } else { + context.drawImage(image, 0, 0, image.width, image.height); + } + canvas = _canvas; + } + return canvas.toDataURL("image/png"); + } + static sRGBToLinear(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + const canvas = createElementNS("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, image.width, image.height); + const imageData = context.getImageData(0, 0, image.width, image.height); + const data2 = imageData.data; + for (let i = 0;i < data2.length; i++) { + data2[i] = SRGBToLinear(data2[i] / 255) * 255; + } + context.putImageData(imageData, 0, 0); + return canvas; + } else if (image.data) { + const data2 = image.data.slice(0); + for (let i = 0;i < data2.length; i++) { + if (data2 instanceof Uint8Array || data2 instanceof Uint8ClampedArray) { + data2[i] = Math.floor(SRGBToLinear(data2[i] / 255) * 255); + } else { + data2[i] = SRGBToLinear(data2[i]); + } + } + return { + data: data2, + width: image.width, + height: image.height + }; + } else { + console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."); + return image; + } + } +} +var _sourceId = 0; + +class Source { + constructor(data2 = null) { + this.isSource = true; + Object.defineProperty(this, "id", { value: _sourceId++ }); + this.uuid = generateUUID(); + this.data = data2; + this.dataReady = true; + this.version = 0; + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + if (!isRootObject && meta.images[this.uuid] !== undefined) { + return meta.images[this.uuid]; + } + const output = { + uuid: this.uuid, + url: "" + }; + const data2 = this.data; + if (data2 !== null) { + let url; + if (Array.isArray(data2)) { + url = []; + for (let i = 0, l = data2.length;i < l; i++) { + if (data2[i].isDataTexture) { + url.push(serializeImage(data2[i].image)); + } else { + url.push(serializeImage(data2[i])); + } + } + } else { + url = serializeImage(data2); + } + output.url = url; + } + if (!isRootObject) { + meta.images[this.uuid] = output; + } + return output; + } +} +function serializeImage(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + return ImageUtils.getDataURL(image); + } else { + if (image.data) { + return { + data: Array.from(image.data), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; + } else { + console.warn("THREE.Texture: Unable to serialize Texture."); + return {}; + } + } +} +var _textureId = 0; + +class Texture extends EventDispatcher { + constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace) { + super(); + this.isTexture = true; + Object.defineProperty(this, "id", { value: _textureId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.source = new Source(image); + this.mipmaps = []; + this.mapping = mapping; + this.channel = 0; + this.wrapS = wrapS; + this.wrapT = wrapT; + this.magFilter = magFilter; + this.minFilter = minFilter; + this.anisotropy = anisotropy; + this.format = format; + this.internalFormat = null; + this.type = type; + this.offset = new Vector2(0, 0); + this.repeat = new Vector2(1, 1); + this.center = new Vector2(0, 0); + this.rotation = 0; + this.matrixAutoUpdate = true; + this.matrix = new Matrix3; + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; + this.colorSpace = colorSpace; + this.userData = {}; + this.version = 0; + this.onUpdate = null; + this.renderTarget = null; + this.isRenderTargetTexture = false; + this.pmremVersion = 0; + } + get image() { + return this.source.data; + } + set image(value2 = null) { + this.source.data = value2; + } + updateMatrix() { + this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.source = source.source; + this.mipmaps = source.mipmaps.slice(0); + this.mapping = source.mapping; + this.channel = source.channel; + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + this.anisotropy = source.anisotropy; + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + this.offset.copy(source.offset); + this.repeat.copy(source.repeat); + this.center.copy(source.center); + this.rotation = source.rotation; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy(source.matrix); + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.colorSpace = source.colorSpace; + this.renderTarget = source.renderTarget; + this.isRenderTargetTexture = source.isRenderTargetTexture; + this.userData = JSON.parse(JSON.stringify(source.userData)); + this.needsUpdate = true; + return this; + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + if (!isRootObject && meta.textures[this.uuid] !== undefined) { + return meta.textures[this.uuid]; + } + const output = { + metadata: { + version: 4.6, + type: "Texture", + generator: "Texture.toJSON" + }, + uuid: this.uuid, + name: this.name, + image: this.source.toJSON(meta).uuid, + mapping: this.mapping, + channel: this.channel, + repeat: [this.repeat.x, this.repeat.y], + offset: [this.offset.x, this.offset.y], + center: [this.center.x, this.center.y], + rotation: this.rotation, + wrap: [this.wrapS, this.wrapT], + format: this.format, + internalFormat: this.internalFormat, + type: this.type, + colorSpace: this.colorSpace, + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + flipY: this.flipY, + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + }; + if (Object.keys(this.userData).length > 0) + output.userData = this.userData; + if (!isRootObject) { + meta.textures[this.uuid] = output; + } + return output; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + transformUv(uv) { + if (this.mapping !== UVMapping) + return uv; + uv.applyMatrix3(this.matrix); + if (uv.x < 0 || uv.x > 1) { + switch (this.wrapS) { + case RepeatWrapping: + uv.x = uv.x - Math.floor(uv.x); + break; + case ClampToEdgeWrapping: + uv.x = uv.x < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping: + if (Math.abs(Math.floor(uv.x) % 2) === 1) { + uv.x = Math.ceil(uv.x) - uv.x; + } else { + uv.x = uv.x - Math.floor(uv.x); + } + break; + } + } + if (uv.y < 0 || uv.y > 1) { + switch (this.wrapT) { + case RepeatWrapping: + uv.y = uv.y - Math.floor(uv.y); + break; + case ClampToEdgeWrapping: + uv.y = uv.y < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping: + if (Math.abs(Math.floor(uv.y) % 2) === 1) { + uv.y = Math.ceil(uv.y) - uv.y; + } else { + uv.y = uv.y - Math.floor(uv.y); + } + break; + } + } + if (this.flipY) { + uv.y = 1 - uv.y; + } + return uv; + } + set needsUpdate(value2) { + if (value2 === true) { + this.version++; + this.source.needsUpdate = true; + } + } + set needsPMREMUpdate(value2) { + if (value2 === true) { + this.pmremVersion++; + } + } +} +Texture.DEFAULT_IMAGE = null; +Texture.DEFAULT_MAPPING = UVMapping; +Texture.DEFAULT_ANISOTROPY = 1; + +class Vector4 { + constructor(x = 0, y = 0, z = 0, w = 1) { + Vector4.prototype.isVector4 = true; + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + get width() { + return this.z; + } + set width(value2) { + this.z = value2; + } + get height() { + return this.w; + } + set height(value2) { + this.w = value2; + } + set(x, y, z, w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setZ(z) { + this.z = z; + return this; + } + setW(w) { + this.w = w; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + case 2: + this.z = value2; + break; + case 3: + this.w = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + case 3: + return this.w; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z, this.w); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = v.w !== undefined ? v.w : 1; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + this.w += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + return this; + } + applyMatrix4(m) { + const x = this.x, y = this.y, z = this.z, w = this.w; + const e = m.elements; + this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w; + this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w; + this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w; + this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + this.w /= v.w; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + setAxisAngleFromQuaternion(q) { + this.w = 2 * Math.acos(q.w); + const s = Math.sqrt(1 - q.w * q.w); + if (s < 0.0001) { + this.x = 1; + this.y = 0; + this.z = 0; + } else { + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; + } + return this; + } + setAxisAngleFromRotationMatrix(m) { + let angle, x, y, z; + const epsilon = 0.01, epsilon2 = 0.1, te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10]; + if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) { + if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) { + this.set(1, 0, 0, 0); + return this; + } + angle = Math.PI; + const xx = (m11 + 1) / 2; + const yy = (m22 + 1) / 2; + const zz = (m33 + 1) / 2; + const xy = (m12 + m21) / 4; + const xz = (m13 + m31) / 4; + const yz = (m23 + m32) / 4; + if (xx > yy && xx > zz) { + if (xx < epsilon) { + x = 0; + y = 0.707106781; + z = 0.707106781; + } else { + x = Math.sqrt(xx); + y = xy / x; + z = xz / x; + } + } else if (yy > zz) { + if (yy < epsilon) { + x = 0.707106781; + y = 0; + z = 0.707106781; + } else { + y = Math.sqrt(yy); + x = xy / y; + z = yz / y; + } + } else { + if (zz < epsilon) { + x = 0.707106781; + y = 0.707106781; + z = 0; + } else { + z = Math.sqrt(zz); + x = xz / z; + y = yz / z; + } + } + this.set(x, y, z, angle); + return this; + } + let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); + if (Math.abs(s) < 0.001) + s = 1; + this.x = (m32 - m23) / s; + this.y = (m13 - m31) / s; + this.z = (m21 - m12) / s; + this.w = Math.acos((m11 + m22 + m33 - 1) / 2); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + this.w = e[15]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + this.w = Math.min(this.w, v.w); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + this.w = Math.max(this.w, v.w); + return this; + } + clamp(min, max) { + this.x = clamp2(this.x, min.x, max.x); + this.y = clamp2(this.y, min.y, max.y); + this.z = clamp2(this.z, min.z, max.z); + this.w = clamp2(this.w, min.w, max.w); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp2(this.x, minVal, maxVal); + this.y = clamp2(this.y, minVal, maxVal); + this.z = clamp2(this.z, minVal, maxVal); + this.w = clamp2(this.w, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp2(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + this.w = Math.floor(this.w); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + this.w = Math.ceil(this.w); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + this.w = Math.round(this.w); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + this.w = Math.trunc(this.w); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + this.w += (v.w - this.w) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + this.w = v1.w + (v2.w - v1.w) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + this.w = array[offset + 3]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + array[offset + 3] = this.w; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + this.z = attribute.getZ(index2); + this.w = attribute.getW(index2); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + yield this.w; + } +} + +class RenderTarget extends EventDispatcher { + constructor(width2 = 1, height2 = 1, options = {}) { + super(); + this.isRenderTarget = true; + this.width = width2; + this.height = height2; + this.depth = 1; + this.scissor = new Vector4(0, 0, width2, height2); + this.scissorTest = false; + this.viewport = new Vector4(0, 0, width2, height2); + const image = { width: width2, height: height2, depth: 1 }; + options = Object.assign({ + generateMipmaps: false, + internalFormat: null, + minFilter: LinearFilter, + depthBuffer: true, + stencilBuffer: false, + resolveDepthBuffer: true, + resolveStencilBuffer: true, + depthTexture: null, + samples: 0, + count: 1 + }, options); + const texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + texture.flipY = false; + texture.generateMipmaps = options.generateMipmaps; + texture.internalFormat = options.internalFormat; + this.textures = []; + const count = options.count; + for (let i = 0;i < count; i++) { + this.textures[i] = texture.clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + } + this.depthBuffer = options.depthBuffer; + this.stencilBuffer = options.stencilBuffer; + this.resolveDepthBuffer = options.resolveDepthBuffer; + this.resolveStencilBuffer = options.resolveStencilBuffer; + this._depthTexture = null; + this.depthTexture = options.depthTexture; + this.samples = options.samples; + } + get texture() { + return this.textures[0]; + } + set texture(value2) { + this.textures[0] = value2; + } + set depthTexture(current) { + if (this._depthTexture !== null) + this._depthTexture.renderTarget = null; + if (current !== null) + current.renderTarget = this; + this._depthTexture = current; + } + get depthTexture() { + return this._depthTexture; + } + setSize(width2, height2, depth = 1) { + if (this.width !== width2 || this.height !== height2 || this.depth !== depth) { + this.width = width2; + this.height = height2; + this.depth = depth; + for (let i = 0, il = this.textures.length;i < il; i++) { + this.textures[i].image.width = width2; + this.textures[i].image.height = height2; + this.textures[i].image.depth = depth; + } + this.dispose(); + } + this.viewport.set(0, 0, width2, height2); + this.scissor.set(0, 0, width2, height2); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + this.scissor.copy(source.scissor); + this.scissorTest = source.scissorTest; + this.viewport.copy(source.viewport); + this.textures.length = 0; + for (let i = 0, il = source.textures.length;i < il; i++) { + this.textures[i] = source.textures[i].clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + } + const image = Object.assign({}, source.texture.image); + this.texture.source = new Source(image); + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.resolveDepthBuffer = source.resolveDepthBuffer; + this.resolveStencilBuffer = source.resolveStencilBuffer; + if (source.depthTexture !== null) + this.depthTexture = source.depthTexture.clone(); + this.samples = source.samples; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } +} + +class WebGLRenderTarget extends RenderTarget { + constructor(width2 = 1, height2 = 1, options = {}) { + super(width2, height2, options); + this.isWebGLRenderTarget = true; + } +} + +class DataArrayTexture extends Texture { + constructor(data2 = null, width2 = 1, height2 = 1, depth = 1) { + super(null); + this.isDataArrayTexture = true; + this.image = { data: data2, width: width2, height: height2, depth }; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.wrapR = ClampToEdgeWrapping; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + this.layerUpdates = new Set; + } + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + clearLayerUpdates() { + this.layerUpdates.clear(); + } +} + +class WebGLArrayRenderTarget extends WebGLRenderTarget { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isWebGLArrayRenderTarget = true; + this.depth = depth; + this.texture = new DataArrayTexture(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } +} + +class Data3DTexture extends Texture { + constructor(data2 = null, width2 = 1, height2 = 1, depth = 1) { + super(null); + this.isData3DTexture = true; + this.image = { data: data2, width: width2, height: height2, depth }; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.wrapR = ClampToEdgeWrapping; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } +} + +class WebGL3DRenderTarget extends WebGLRenderTarget { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isWebGL3DRenderTarget = true; + this.depth = depth; + this.texture = new Data3DTexture(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } +} + +class Quaternion { + constructor(x = 0, y = 0, z = 0, w = 1) { + this.isQuaternion = true; + this._x = x; + this._y = y; + this._z = z; + this._w = w; + } + static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) { + let x0 = src0[srcOffset0 + 0], y0 = src0[srcOffset0 + 1], z0 = src0[srcOffset0 + 2], w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1 + 0], y1 = src1[srcOffset1 + 1], z1 = src1[srcOffset1 + 2], w1 = src1[srcOffset1 + 3]; + if (t === 0) { + dst[dstOffset + 0] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + return; + } + if (t === 1) { + dst[dstOffset + 0] = x1; + dst[dstOffset + 1] = y1; + dst[dstOffset + 2] = z1; + dst[dstOffset + 3] = w1; + return; + } + if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) { + let s = 1 - t; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, dir = cos >= 0 ? 1 : -1, sqrSin = 1 - cos * cos; + if (sqrSin > Number.EPSILON) { + const sin = Math.sqrt(sqrSin), len = Math.atan2(sin, cos * dir); + s = Math.sin(s * len) / sin; + t = Math.sin(t * len) / sin; + } + const tDir = t * dir; + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; + if (s === 1 - t) { + const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0); + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; + } + } + dst[dstOffset] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + } + static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) { + const x0 = src0[srcOffset0]; + const y0 = src0[srcOffset0 + 1]; + const z0 = src0[srcOffset0 + 2]; + const w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1]; + const y1 = src1[srcOffset1 + 1]; + const z1 = src1[srcOffset1 + 2]; + const w1 = src1[srcOffset1 + 3]; + dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + return dst; + } + get x() { + return this._x; + } + set x(value2) { + this._x = value2; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value2) { + this._y = value2; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value2) { + this._z = value2; + this._onChangeCallback(); + } + get w() { + return this._w; + } + set w(value2) { + this._w = value2; + this._onChangeCallback(); + } + set(x, y, z, w) { + this._x = x; + this._y = y; + this._z = z; + this._w = w; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._w); + } + copy(quaternion) { + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + this._onChangeCallback(); + return this; + } + setFromEuler(euler, update = true) { + const { _x: x, _y: y, _z: z, _order: order } = euler; + const cos = Math.cos; + const sin = Math.sin; + const c1 = cos(x / 2); + const c2 = cos(y / 2); + const c3 = cos(z / 2); + const s1 = sin(x / 2); + const s2 = sin(y / 2); + const s3 = sin(z / 2); + switch (order) { + case "XYZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "YXZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "ZXY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "ZYX": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "YZX": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "XZY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + default: + console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + order); + } + if (update === true) + this._onChangeCallback(); + return this; + } + setFromAxisAngle(axis, angle) { + const halfAngle = angle / 2, s = Math.sin(halfAngle); + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos(halfAngle); + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m) { + const te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10], trace = m11 + m22 + m33; + if (trace > 0) { + const s = 0.5 / Math.sqrt(trace + 1); + this._w = 0.25 / s; + this._x = (m32 - m23) * s; + this._y = (m13 - m31) * s; + this._z = (m21 - m12) * s; + } else if (m11 > m22 && m11 > m33) { + const s = 2 * Math.sqrt(1 + m11 - m22 - m33); + this._w = (m32 - m23) / s; + this._x = 0.25 * s; + this._y = (m12 + m21) / s; + this._z = (m13 + m31) / s; + } else if (m22 > m33) { + const s = 2 * Math.sqrt(1 + m22 - m11 - m33); + this._w = (m13 - m31) / s; + this._x = (m12 + m21) / s; + this._y = 0.25 * s; + this._z = (m23 + m32) / s; + } else { + const s = 2 * Math.sqrt(1 + m33 - m11 - m22); + this._w = (m21 - m12) / s; + this._x = (m13 + m31) / s; + this._y = (m23 + m32) / s; + this._z = 0.25 * s; + } + this._onChangeCallback(); + return this; + } + setFromUnitVectors(vFrom, vTo) { + let r = vFrom.dot(vTo) + 1; + if (r < Number.EPSILON) { + r = 0; + if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) { + this._x = -vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + } else { + this._x = 0; + this._y = -vFrom.z; + this._z = vFrom.y; + this._w = r; + } + } else { + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + } + return this.normalize(); + } + angleTo(q) { + return 2 * Math.acos(Math.abs(clamp2(this.dot(q), -1, 1))); + } + rotateTowards(q, step) { + const angle = this.angleTo(q); + if (angle === 0) + return this; + const t = Math.min(1, step / angle); + this.slerp(q, t); + return this; + } + identity() { + return this.set(0, 0, 0, 1); + } + invert() { + return this.conjugate(); + } + conjugate() { + this._x *= -1; + this._y *= -1; + this._z *= -1; + this._onChangeCallback(); + return this; + } + dot(v) { + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + } + lengthSq() { + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + } + length() { + return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); + } + normalize() { + let l = this.length(); + if (l === 0) { + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + } else { + l = 1 / l; + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; + } + this._onChangeCallback(); + return this; + } + multiply(q) { + return this.multiplyQuaternions(this, q); + } + premultiply(q) { + return this.multiplyQuaternions(q, this); + } + multiplyQuaternions(a, b) { + const { _x: qax, _y: qay, _z: qaz, _w: qaw } = a; + const { _x: qbx, _y: qby, _z: qbz, _w: qbw } = b; + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + this._onChangeCallback(); + return this; + } + slerp(qb, t) { + if (t === 0) + return this; + if (t === 1) + return this.copy(qb); + const x = this._x, y = this._y, z = this._z, w = this._w; + let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + if (cosHalfTheta < 0) { + this._w = -qb._w; + this._x = -qb._x; + this._y = -qb._y; + this._z = -qb._z; + cosHalfTheta = -cosHalfTheta; + } else { + this.copy(qb); + } + if (cosHalfTheta >= 1) { + this._w = w; + this._x = x; + this._y = y; + this._z = z; + return this; + } + const sqrSinHalfTheta = 1 - cosHalfTheta * cosHalfTheta; + if (sqrSinHalfTheta <= Number.EPSILON) { + const s = 1 - t; + this._w = s * w + t * this._w; + this._x = s * x + t * this._x; + this._y = s * y + t * this._y; + this._z = s * z + t * this._z; + this.normalize(); + return this; + } + const sinHalfTheta = Math.sqrt(sqrSinHalfTheta); + const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta); + const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta, ratioB = Math.sin(t * halfTheta) / sinHalfTheta; + this._w = w * ratioA + this._w * ratioB; + this._x = x * ratioA + this._x * ratioB; + this._y = y * ratioA + this._y * ratioB; + this._z = z * ratioA + this._z * ratioB; + this._onChangeCallback(); + return this; + } + slerpQuaternions(qa, qb, t) { + return this.copy(qa).slerp(qb, t); + } + random() { + const theta1 = 2 * Math.PI * Math.random(); + const theta2 = 2 * Math.PI * Math.random(); + const x0 = Math.random(); + const r1 = Math.sqrt(1 - x0); + const r2 = Math.sqrt(x0); + return this.set(r1 * Math.sin(theta1), r1 * Math.cos(theta1), r2 * Math.sin(theta2), r2 * Math.cos(theta2)); + } + equals(quaternion) { + return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w; + } + fromArray(array, offset = 0) { + this._x = array[offset]; + this._y = array[offset + 1]; + this._z = array[offset + 2]; + this._w = array[offset + 3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._w; + return array; + } + fromBufferAttribute(attribute, index2) { + this._x = attribute.getX(index2); + this._y = attribute.getY(index2); + this._z = attribute.getZ(index2); + this._w = attribute.getW(index2); + this._onChangeCallback(); + return this; + } + toJSON() { + return this.toArray(); + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._w; + } +} + +class Vector3 { + constructor(x = 0, y = 0, z = 0) { + Vector3.prototype.isVector3 = true; + this.x = x; + this.y = y; + this.z = z; + } + set(x, y, z) { + if (z === undefined) + z = this.z; + this.x = x; + this.y = y; + this.z = z; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setZ(z) { + this.z = z; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + case 2: + this.z = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + return this; + } + multiplyVectors(a, b) { + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; + return this; + } + applyEuler(euler) { + return this.applyQuaternion(_quaternion$4.setFromEuler(euler)); + } + applyAxisAngle(axis, angle) { + return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle)); + } + applyMatrix3(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + this.x = e[0] * x + e[3] * y + e[6] * z; + this.y = e[1] * x + e[4] * y + e[7] * z; + this.z = e[2] * x + e[5] * y + e[8] * z; + return this; + } + applyNormalMatrix(m) { + return this.applyMatrix3(m).normalize(); + } + applyMatrix4(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]); + this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w; + this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w; + this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w; + return this; + } + applyQuaternion(q) { + const vx = this.x, vy = this.y, vz = this.z; + const { x: qx, y: qy, z: qz, w: qw } = q; + const tx = 2 * (qy * vz - qz * vy); + const ty = 2 * (qz * vx - qx * vz); + const tz = 2 * (qx * vy - qy * vx); + this.x = vx + qw * tx + qy * tz - qz * ty; + this.y = vy + qw * ty + qz * tx - qx * tz; + this.z = vz + qw * tz + qx * ty - qy * tx; + return this; + } + project(camera) { + return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix); + } + unproject(camera) { + return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld); + } + transformDirection(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + this.x = e[0] * x + e[4] * y + e[8] * z; + this.y = e[1] * x + e[5] * y + e[9] * z; + this.z = e[2] * x + e[6] * y + e[10] * z; + return this.normalize(); + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + return this; + } + clamp(min, max) { + this.x = clamp2(this.x, min.x, max.x); + this.y = clamp2(this.y, min.y, max.y); + this.z = clamp2(this.z, min.z, max.z); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp2(this.x, minVal, maxVal); + this.y = clamp2(this.y, minVal, maxVal); + this.z = clamp2(this.z, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp2(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + return this; + } + cross(v) { + return this.crossVectors(this, v); + } + crossVectors(a, b) { + const { x: ax, y: ay, z: az } = a; + const { x: bx, y: by, z: bz } = b; + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + return this; + } + projectOnVector(v) { + const denominator = v.lengthSq(); + if (denominator === 0) + return this.set(0, 0, 0); + const scalar = v.dot(this) / denominator; + return this.copy(v).multiplyScalar(scalar); + } + projectOnPlane(planeNormal) { + _vector$c.copy(this).projectOnVector(planeNormal); + return this.sub(_vector$c); + } + reflect(normal) { + return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal))); + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) + return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp2(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + return dx * dx + dy * dy + dz * dz; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z); + } + setFromSpherical(s) { + return this.setFromSphericalCoords(s.radius, s.phi, s.theta); + } + setFromSphericalCoords(radius, phi, theta) { + const sinPhiRadius = Math.sin(phi) * radius; + this.x = sinPhiRadius * Math.sin(theta); + this.y = Math.cos(phi) * radius; + this.z = sinPhiRadius * Math.cos(theta); + return this; + } + setFromCylindrical(c) { + return this.setFromCylindricalCoords(c.radius, c.theta, c.y); + } + setFromCylindricalCoords(radius, theta, y) { + this.x = radius * Math.sin(theta); + this.y = y; + this.z = radius * Math.cos(theta); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + return this; + } + setFromMatrixScale(m) { + const sx = this.setFromMatrixColumn(m, 0).length(); + const sy = this.setFromMatrixColumn(m, 1).length(); + const sz = this.setFromMatrixColumn(m, 2).length(); + this.x = sx; + this.y = sy; + this.z = sz; + return this; + } + setFromMatrixColumn(m, index2) { + return this.fromArray(m.elements, index2 * 4); + } + setFromMatrix3Column(m, index2) { + return this.fromArray(m.elements, index2 * 3); + } + setFromEuler(e) { + this.x = e._x; + this.y = e._y; + this.z = e._z; + return this; + } + setFromColor(c) { + this.x = c.r; + this.y = c.g; + this.z = c.b; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + this.z = attribute.getZ(index2); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + return this; + } + randomDirection() { + const theta = Math.random() * Math.PI * 2; + const u = Math.random() * 2 - 1; + const c = Math.sqrt(1 - u * u); + this.x = c * Math.cos(theta); + this.y = u; + this.z = c * Math.sin(theta); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + } +} +var _vector$c = /* @__PURE__ */ new Vector3; +var _quaternion$4 = /* @__PURE__ */ new Quaternion; + +class Box3 { + constructor(min = new Vector3(Infinity, Infinity, Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) { + this.isBox3 = true; + this.min = min; + this.max = max; + } + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + setFromArray(array) { + this.makeEmpty(); + for (let i = 0, il = array.length;i < il; i += 3) { + this.expandByPoint(_vector$b.fromArray(array, i)); + } + return this; + } + setFromBufferAttribute(attribute) { + this.makeEmpty(); + for (let i = 0, il = attribute.count;i < il; i++) { + this.expandByPoint(_vector$b.fromBufferAttribute(attribute, i)); + } + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length;i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size) { + const halfSize = _vector$b.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + setFromObject(object, precise = false) { + this.makeEmpty(); + return this.expandByObject(object, precise); + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = this.min.z = Infinity; + this.max.x = this.max.y = this.max.z = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + expandByObject(object, precise = false) { + object.updateWorldMatrix(false, false); + const geometry = object.geometry; + if (geometry !== undefined) { + const positionAttribute = geometry.getAttribute("position"); + if (precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true) { + for (let i = 0, l = positionAttribute.count;i < l; i++) { + if (object.isMesh === true) { + object.getVertexPosition(i, _vector$b); + } else { + _vector$b.fromBufferAttribute(positionAttribute, i); + } + _vector$b.applyMatrix4(object.matrixWorld); + this.expandByPoint(_vector$b); + } + } else { + if (object.boundingBox !== undefined) { + if (object.boundingBox === null) { + object.computeBoundingBox(); + } + _box$4.copy(object.boundingBox); + } else { + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + _box$4.copy(geometry.boundingBox); + } + _box$4.applyMatrix4(object.matrixWorld); + this.union(_box$4); + } + } + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + this.expandByObject(children[i], precise); + } + return this; + } + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y && point.z >= this.min.z && point.z <= this.max.z; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z; + } + getParameter(point, target) { + return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z)); + } + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y && box.max.z >= this.min.z && box.min.z <= this.max.z; + } + intersectsSphere(sphere) { + this.clampPoint(sphere.center, _vector$b); + return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; + } + intersectsPlane(plane) { + let min, max; + if (plane.normal.x > 0) { + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + } else { + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + } + if (plane.normal.y > 0) { + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + } else { + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + } + if (plane.normal.z > 0) { + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + } else { + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + } + return min <= -plane.constant && max >= -plane.constant; + } + intersectsTriangle(triangle) { + if (this.isEmpty()) { + return false; + } + this.getCenter(_center); + _extents.subVectors(this.max, _center); + _v0$2.subVectors(triangle.a, _center); + _v1$7.subVectors(triangle.b, _center); + _v2$4.subVectors(triangle.c, _center); + _f0.subVectors(_v1$7, _v0$2); + _f1.subVectors(_v2$4, _v1$7); + _f2.subVectors(_v0$2, _v2$4); + let axes = [ + 0, + -_f0.z, + _f0.y, + 0, + -_f1.z, + _f1.y, + 0, + -_f2.z, + _f2.y, + _f0.z, + 0, + -_f0.x, + _f1.z, + 0, + -_f1.x, + _f2.z, + 0, + -_f2.x, + -_f0.y, + _f0.x, + 0, + -_f1.y, + _f1.x, + 0, + -_f2.y, + _f2.x, + 0 + ]; + if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) { + return false; + } + axes = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) { + return false; + } + _triangleNormal.crossVectors(_f0, _f1); + axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z]; + return satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents); + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$b).distanceTo(point); + } + getBoundingSphere(target) { + if (this.isEmpty()) { + target.makeEmpty(); + } else { + this.getCenter(target.center); + target.radius = this.getSize(_vector$b).length() * 0.5; + } + return target; + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) + this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + applyMatrix4(matrix) { + if (this.isEmpty()) + return this; + _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); + _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); + this.setFromPoints(_points); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } +} +var _points = [ + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3 +]; +var _vector$b = /* @__PURE__ */ new Vector3; +var _box$4 = /* @__PURE__ */ new Box3; +var _v0$2 = /* @__PURE__ */ new Vector3; +var _v1$7 = /* @__PURE__ */ new Vector3; +var _v2$4 = /* @__PURE__ */ new Vector3; +var _f0 = /* @__PURE__ */ new Vector3; +var _f1 = /* @__PURE__ */ new Vector3; +var _f2 = /* @__PURE__ */ new Vector3; +var _center = /* @__PURE__ */ new Vector3; +var _extents = /* @__PURE__ */ new Vector3; +var _triangleNormal = /* @__PURE__ */ new Vector3; +var _testAxis = /* @__PURE__ */ new Vector3; +function satForAxes(axes, v0, v1, v2, extents) { + for (let i = 0, j = axes.length - 3;i <= j; i += 3) { + _testAxis.fromArray(axes, i); + const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); + const p0 = v0.dot(_testAxis); + const p1 = v1.dot(_testAxis); + const p2 = v2.dot(_testAxis); + if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) { + return false; + } + } + return true; +} +var _box$3 = /* @__PURE__ */ new Box3; +var _v1$6 = /* @__PURE__ */ new Vector3; +var _v2$3 = /* @__PURE__ */ new Vector3; + +class Sphere { + constructor(center = new Vector3, radius = -1) { + this.isSphere = true; + this.center = center; + this.radius = radius; + } + set(center, radius) { + this.center.copy(center); + this.radius = radius; + return this; + } + setFromPoints(points, optionalCenter) { + const center = this.center; + if (optionalCenter !== undefined) { + center.copy(optionalCenter); + } else { + _box$3.setFromPoints(points).getCenter(center); + } + let maxRadiusSq = 0; + for (let i = 0, il = points.length;i < il; i++) { + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i])); + } + this.radius = Math.sqrt(maxRadiusSq); + return this; + } + copy(sphere) { + this.center.copy(sphere.center); + this.radius = sphere.radius; + return this; + } + isEmpty() { + return this.radius < 0; + } + makeEmpty() { + this.center.set(0, 0, 0); + this.radius = -1; + return this; + } + containsPoint(point) { + return point.distanceToSquared(this.center) <= this.radius * this.radius; + } + distanceToPoint(point) { + return point.distanceTo(this.center) - this.radius; + } + intersectsSphere(sphere) { + const radiusSum = this.radius + sphere.radius; + return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum; + } + intersectsBox(box) { + return box.intersectsSphere(this); + } + intersectsPlane(plane) { + return Math.abs(plane.distanceToPoint(this.center)) <= this.radius; + } + clampPoint(point, target) { + const deltaLengthSq = this.center.distanceToSquared(point); + target.copy(point); + if (deltaLengthSq > this.radius * this.radius) { + target.sub(this.center).normalize(); + target.multiplyScalar(this.radius).add(this.center); + } + return target; + } + getBoundingBox(target) { + if (this.isEmpty()) { + target.makeEmpty(); + return target; + } + target.set(this.center, this.center); + target.expandByScalar(this.radius); + return target; + } + applyMatrix4(matrix) { + this.center.applyMatrix4(matrix); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); + return this; + } + translate(offset) { + this.center.add(offset); + return this; + } + expandByPoint(point) { + if (this.isEmpty()) { + this.center.copy(point); + this.radius = 0; + return this; + } + _v1$6.subVectors(point, this.center); + const lengthSq = _v1$6.lengthSq(); + if (lengthSq > this.radius * this.radius) { + const length2 = Math.sqrt(lengthSq); + const delta = (length2 - this.radius) * 0.5; + this.center.addScaledVector(_v1$6, delta / length2); + this.radius += delta; + } + return this; + } + union(sphere) { + if (sphere.isEmpty()) { + return this; + } + if (this.isEmpty()) { + this.copy(sphere); + return this; + } + if (this.center.equals(sphere.center) === true) { + this.radius = Math.max(this.radius, sphere.radius); + } else { + _v2$3.subVectors(sphere.center, this.center).setLength(sphere.radius); + this.expandByPoint(_v1$6.copy(sphere.center).add(_v2$3)); + this.expandByPoint(_v1$6.copy(sphere.center).sub(_v2$3)); + } + return this; + } + equals(sphere) { + return sphere.center.equals(this.center) && sphere.radius === this.radius; + } + clone() { + return new this.constructor().copy(this); + } +} +var _vector$a = /* @__PURE__ */ new Vector3; +var _segCenter = /* @__PURE__ */ new Vector3; +var _segDir = /* @__PURE__ */ new Vector3; +var _diff = /* @__PURE__ */ new Vector3; +var _edge1 = /* @__PURE__ */ new Vector3; +var _edge2 = /* @__PURE__ */ new Vector3; +var _normal$1 = /* @__PURE__ */ new Vector3; + +class Ray { + constructor(origin = new Vector3, direction = new Vector3(0, 0, -1)) { + this.origin = origin; + this.direction = direction; + } + set(origin, direction) { + this.origin.copy(origin); + this.direction.copy(direction); + return this; + } + copy(ray) { + this.origin.copy(ray.origin); + this.direction.copy(ray.direction); + return this; + } + at(t, target) { + return target.copy(this.origin).addScaledVector(this.direction, t); + } + lookAt(v) { + this.direction.copy(v).sub(this.origin).normalize(); + return this; + } + recast(t) { + this.origin.copy(this.at(t, _vector$a)); + return this; + } + closestPointToPoint(point, target) { + target.subVectors(point, this.origin); + const directionDistance = target.dot(this.direction); + if (directionDistance < 0) { + return target.copy(this.origin); + } + return target.copy(this.origin).addScaledVector(this.direction, directionDistance); + } + distanceToPoint(point) { + return Math.sqrt(this.distanceSqToPoint(point)); + } + distanceSqToPoint(point) { + const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); + if (directionDistance < 0) { + return this.origin.distanceToSquared(point); + } + _vector$a.copy(this.origin).addScaledVector(this.direction, directionDistance); + return _vector$a.distanceToSquared(point); + } + distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) { + _segCenter.copy(v0).add(v1).multiplyScalar(0.5); + _segDir.copy(v1).sub(v0).normalize(); + _diff.copy(this.origin).sub(_segCenter); + const segExtent = v0.distanceTo(v1) * 0.5; + const a01 = -this.direction.dot(_segDir); + const b0 = _diff.dot(this.direction); + const b1 = -_diff.dot(_segDir); + const c = _diff.lengthSq(); + const det = Math.abs(1 - a01 * a01); + let s0, s1, sqrDist, extDet; + if (det > 0) { + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + if (s0 >= 0) { + if (s1 >= -extDet) { + if (s1 <= extDet) { + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c; + } else { + s1 = segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } else { + s1 = -segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } else { + if (s1 <= -extDet) { + s0 = Math.max(0, -(-a01 * segExtent + b0)); + s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } else if (s1 <= extDet) { + s0 = 0; + s1 = Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = s1 * (s1 + 2 * b1) + c; + } else { + s0 = Math.max(0, -(a01 * segExtent + b0)); + s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } + } else { + s1 = a01 > 0 ? -segExtent : segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + if (optionalPointOnRay) { + optionalPointOnRay.copy(this.origin).addScaledVector(this.direction, s0); + } + if (optionalPointOnSegment) { + optionalPointOnSegment.copy(_segCenter).addScaledVector(_segDir, s1); + } + return sqrDist; + } + intersectSphere(sphere, target) { + _vector$a.subVectors(sphere.center, this.origin); + const tca = _vector$a.dot(this.direction); + const d2 = _vector$a.dot(_vector$a) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + if (d2 > radius2) + return null; + const thc = Math.sqrt(radius2 - d2); + const t0 = tca - thc; + const t1 = tca + thc; + if (t1 < 0) + return null; + if (t0 < 0) + return this.at(t1, target); + return this.at(t0, target); + } + intersectsSphere(sphere) { + return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius; + } + distanceToPlane(plane) { + const denominator = plane.normal.dot(this.direction); + if (denominator === 0) { + if (plane.distanceToPoint(this.origin) === 0) { + return 0; + } + return null; + } + const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; + return t >= 0 ? t : null; + } + intersectPlane(plane, target) { + const t = this.distanceToPlane(plane); + if (t === null) { + return null; + } + return this.at(t, target); + } + intersectsPlane(plane) { + const distToPoint = plane.distanceToPoint(this.origin); + if (distToPoint === 0) { + return true; + } + const denominator = plane.normal.dot(this.direction); + if (denominator * distToPoint < 0) { + return true; + } + return false; + } + intersectBox(box, target) { + let tmin, tmax, tymin, tymax, tzmin, tzmax; + const invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z; + const origin = this.origin; + if (invdirx >= 0) { + tmin = (box.min.x - origin.x) * invdirx; + tmax = (box.max.x - origin.x) * invdirx; + } else { + tmin = (box.max.x - origin.x) * invdirx; + tmax = (box.min.x - origin.x) * invdirx; + } + if (invdiry >= 0) { + tymin = (box.min.y - origin.y) * invdiry; + tymax = (box.max.y - origin.y) * invdiry; + } else { + tymin = (box.max.y - origin.y) * invdiry; + tymax = (box.min.y - origin.y) * invdiry; + } + if (tmin > tymax || tymin > tmax) + return null; + if (tymin > tmin || isNaN(tmin)) + tmin = tymin; + if (tymax < tmax || isNaN(tmax)) + tmax = tymax; + if (invdirz >= 0) { + tzmin = (box.min.z - origin.z) * invdirz; + tzmax = (box.max.z - origin.z) * invdirz; + } else { + tzmin = (box.max.z - origin.z) * invdirz; + tzmax = (box.min.z - origin.z) * invdirz; + } + if (tmin > tzmax || tzmin > tmax) + return null; + if (tzmin > tmin || tmin !== tmin) + tmin = tzmin; + if (tzmax < tmax || tmax !== tmax) + tmax = tzmax; + if (tmax < 0) + return null; + return this.at(tmin >= 0 ? tmin : tmax, target); + } + intersectsBox(box) { + return this.intersectBox(box, _vector$a) !== null; + } + intersectTriangle(a, b, c, backfaceCulling, target) { + _edge1.subVectors(b, a); + _edge2.subVectors(c, a); + _normal$1.crossVectors(_edge1, _edge2); + let DdN = this.direction.dot(_normal$1); + let sign; + if (DdN > 0) { + if (backfaceCulling) + return null; + sign = 1; + } else if (DdN < 0) { + sign = -1; + DdN = -DdN; + } else { + return null; + } + _diff.subVectors(this.origin, a); + const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); + if (DdQxE2 < 0) { + return null; + } + const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); + if (DdE1xQ < 0) { + return null; + } + if (DdQxE2 + DdE1xQ > DdN) { + return null; + } + const QdN = -sign * _diff.dot(_normal$1); + if (QdN < 0) { + return null; + } + return this.at(QdN / DdN, target); + } + applyMatrix4(matrix4) { + this.origin.applyMatrix4(matrix4); + this.direction.transformDirection(matrix4); + return this; + } + equals(ray) { + return ray.origin.equals(this.origin) && ray.direction.equals(this.direction); + } + clone() { + return new this.constructor().copy(this); + } +} + +class Matrix4 { + constructor(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + Matrix4.prototype.isMatrix4 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44); + } + } + set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + const te = this.elements; + te[0] = n11; + te[4] = n12; + te[8] = n13; + te[12] = n14; + te[1] = n21; + te[5] = n22; + te[9] = n23; + te[13] = n24; + te[2] = n31; + te[6] = n32; + te[10] = n33; + te[14] = n34; + te[3] = n41; + te[7] = n42; + te[11] = n43; + te[15] = n44; + return this; + } + identity() { + this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return this; + } + clone() { + return new Matrix4().fromArray(this.elements); + } + copy(m) { + const te = this.elements; + const me = m.elements; + te[0] = me[0]; + te[1] = me[1]; + te[2] = me[2]; + te[3] = me[3]; + te[4] = me[4]; + te[5] = me[5]; + te[6] = me[6]; + te[7] = me[7]; + te[8] = me[8]; + te[9] = me[9]; + te[10] = me[10]; + te[11] = me[11]; + te[12] = me[12]; + te[13] = me[13]; + te[14] = me[14]; + te[15] = me[15]; + return this; + } + copyPosition(m) { + const te = this.elements, me = m.elements; + te[12] = me[12]; + te[13] = me[13]; + te[14] = me[14]; + return this; + } + setFromMatrix3(m) { + const me = m.elements; + this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1); + return this; + } + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrixColumn(this, 0); + yAxis.setFromMatrixColumn(this, 1); + zAxis.setFromMatrixColumn(this, 2); + return this; + } + makeBasis(xAxis, yAxis, zAxis) { + this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1); + return this; + } + extractRotation(m) { + const te = this.elements; + const me = m.elements; + const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length(); + const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length(); + const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length(); + te[0] = me[0] * scaleX; + te[1] = me[1] * scaleX; + te[2] = me[2] * scaleX; + te[3] = 0; + te[4] = me[4] * scaleY; + te[5] = me[5] * scaleY; + te[6] = me[6] * scaleY; + te[7] = 0; + te[8] = me[8] * scaleZ; + te[9] = me[9] * scaleZ; + te[10] = me[10] * scaleZ; + te[11] = 0; + te[12] = 0; + te[13] = 0; + te[14] = 0; + te[15] = 1; + return this; + } + makeRotationFromEuler(euler) { + const te = this.elements; + const { x, y, z } = euler; + const a = Math.cos(x), b = Math.sin(x); + const c = Math.cos(y), d = Math.sin(y); + const e = Math.cos(z), f = Math.sin(z); + if (euler.order === "XYZ") { + const ae = a * e, af = a * f, be = b * e, bf = b * f; + te[0] = c * e; + te[4] = -c * f; + te[8] = d; + te[1] = af + be * d; + te[5] = ae - bf * d; + te[9] = -b * c; + te[2] = bf - ae * d; + te[6] = be + af * d; + te[10] = a * c; + } else if (euler.order === "YXZ") { + const ce = c * e, cf = c * f, de = d * e, df = d * f; + te[0] = ce + df * b; + te[4] = de * b - cf; + te[8] = a * d; + te[1] = a * f; + te[5] = a * e; + te[9] = -b; + te[2] = cf * b - de; + te[6] = df + ce * b; + te[10] = a * c; + } else if (euler.order === "ZXY") { + const ce = c * e, cf = c * f, de = d * e, df = d * f; + te[0] = ce - df * b; + te[4] = -a * f; + te[8] = de + cf * b; + te[1] = cf + de * b; + te[5] = a * e; + te[9] = df - ce * b; + te[2] = -a * d; + te[6] = b; + te[10] = a * c; + } else if (euler.order === "ZYX") { + const ae = a * e, af = a * f, be = b * e, bf = b * f; + te[0] = c * e; + te[4] = be * d - af; + te[8] = ae * d + bf; + te[1] = c * f; + te[5] = bf * d + ae; + te[9] = af * d - be; + te[2] = -d; + te[6] = b * c; + te[10] = a * c; + } else if (euler.order === "YZX") { + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + te[0] = c * e; + te[4] = bd - ac * f; + te[8] = bc * f + ad; + te[1] = f; + te[5] = a * e; + te[9] = -b * e; + te[2] = -d * e; + te[6] = ad * f + bc; + te[10] = ac - bd * f; + } else if (euler.order === "XZY") { + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + te[0] = c * e; + te[4] = -f; + te[8] = d * e; + te[1] = ac * f + bd; + te[5] = a * e; + te[9] = ad * f - bc; + te[2] = bc * f - ad; + te[6] = b * e; + te[10] = bd * f + ac; + } + te[3] = 0; + te[7] = 0; + te[11] = 0; + te[12] = 0; + te[13] = 0; + te[14] = 0; + te[15] = 1; + return this; + } + makeRotationFromQuaternion(q) { + return this.compose(_zero, q, _one); + } + lookAt(eye, target, up) { + const te = this.elements; + _z.subVectors(eye, target); + if (_z.lengthSq() === 0) { + _z.z = 1; + } + _z.normalize(); + _x.crossVectors(up, _z); + if (_x.lengthSq() === 0) { + if (Math.abs(up.z) === 1) { + _z.x += 0.0001; + } else { + _z.z += 0.0001; + } + _z.normalize(); + _x.crossVectors(up, _z); + } + _x.normalize(); + _y.crossVectors(_z, _x); + te[0] = _x.x; + te[4] = _y.x; + te[8] = _z.x; + te[1] = _x.y; + te[5] = _y.y; + te[9] = _z.y; + te[2] = _x.z; + te[6] = _y.z; + te[10] = _z.z; + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a, b) { + const ae = a.elements; + const be = b.elements; + const te = this.elements; + const a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12]; + const a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13]; + const a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14]; + const a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15]; + const b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; + const b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; + const b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; + const b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; + te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + return this; + } + multiplyScalar(s) { + const te = this.elements; + te[0] *= s; + te[4] *= s; + te[8] *= s; + te[12] *= s; + te[1] *= s; + te[5] *= s; + te[9] *= s; + te[13] *= s; + te[2] *= s; + te[6] *= s; + te[10] *= s; + te[14] *= s; + te[3] *= s; + te[7] *= s; + te[11] *= s; + te[15] *= s; + return this; + } + determinant() { + const te = this.elements; + const n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12]; + const n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13]; + const n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14]; + const n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15]; + return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31); + } + transpose() { + const te = this.elements; + let tmp; + tmp = te[1]; + te[1] = te[4]; + te[4] = tmp; + tmp = te[2]; + te[2] = te[8]; + te[8] = tmp; + tmp = te[6]; + te[6] = te[9]; + te[9] = tmp; + tmp = te[3]; + te[3] = te[12]; + te[12] = tmp; + tmp = te[7]; + te[7] = te[13]; + te[13] = tmp; + tmp = te[11]; + te[11] = te[14]; + te[14] = tmp; + return this; + } + setPosition(x, y, z) { + const te = this.elements; + if (x.isVector3) { + te[12] = x.x; + te[13] = x.y; + te[14] = x.z; + } else { + te[12] = x; + te[13] = y; + te[14] = z; + } + return this; + } + invert() { + const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n41 = te[3], n12 = te[4], n22 = te[5], n32 = te[6], n42 = te[7], n13 = te[8], n23 = te[9], n33 = te[10], n43 = te[11], n14 = te[12], n24 = te[13], n34 = te[14], n44 = te[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + if (det === 0) + return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te[0] = t11 * detInv; + te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; + te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; + te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; + te[4] = t12 * detInv; + te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; + te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; + te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; + te[8] = t13 * detInv; + te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; + te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; + te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; + te[12] = t14 * detInv; + te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; + te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; + te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; + return this; + } + scale(v) { + const te = this.elements; + const { x, y, z } = v; + te[0] *= x; + te[4] *= y; + te[8] *= z; + te[1] *= x; + te[5] *= y; + te[9] *= z; + te[2] *= x; + te[6] *= y; + te[10] *= z; + te[3] *= x; + te[7] *= y; + te[11] *= z; + return this; + } + getMaxScaleOnAxis() { + const te = this.elements; + const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2]; + const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6]; + const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10]; + return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); + } + makeTranslation(x, y, z) { + if (x.isVector3) { + this.set(1, 0, 0, x.x, 0, 1, 0, x.y, 0, 0, 1, x.z, 0, 0, 0, 1); + } else { + this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1); + } + return this; + } + makeRotationX(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1); + return this; + } + makeRotationY(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1); + return this; + } + makeRotationZ(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return this; + } + makeRotationAxis(axis, angle) { + const c = Math.cos(angle); + const s = Math.sin(angle); + const t = 1 - c; + const { x, y, z } = axis; + const tx = t * x, ty = t * y; + this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1); + return this; + } + makeScale(x, y, z) { + this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); + return this; + } + makeShear(xy, xz, yx, yz, zx, zy) { + this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1); + return this; + } + compose(position2, quaternion, scale2) { + const te = this.elements; + const { _x: x, _y: y, _z: z, _w: w } = quaternion; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; + const { x: sx, y: sy, z: sz } = scale2; + te[0] = (1 - (yy + zz)) * sx; + te[1] = (xy + wz) * sx; + te[2] = (xz - wy) * sx; + te[3] = 0; + te[4] = (xy - wz) * sy; + te[5] = (1 - (xx + zz)) * sy; + te[6] = (yz + wx) * sy; + te[7] = 0; + te[8] = (xz + wy) * sz; + te[9] = (yz - wx) * sz; + te[10] = (1 - (xx + yy)) * sz; + te[11] = 0; + te[12] = position2.x; + te[13] = position2.y; + te[14] = position2.z; + te[15] = 1; + return this; + } + decompose(position2, quaternion, scale2) { + const te = this.elements; + let sx = _v1$5.set(te[0], te[1], te[2]).length(); + const sy = _v1$5.set(te[4], te[5], te[6]).length(); + const sz = _v1$5.set(te[8], te[9], te[10]).length(); + const det = this.determinant(); + if (det < 0) + sx = -sx; + position2.x = te[12]; + position2.y = te[13]; + position2.z = te[14]; + _m1$2.copy(this); + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + _m1$2.elements[0] *= invSX; + _m1$2.elements[1] *= invSX; + _m1$2.elements[2] *= invSX; + _m1$2.elements[4] *= invSY; + _m1$2.elements[5] *= invSY; + _m1$2.elements[6] *= invSY; + _m1$2.elements[8] *= invSZ; + _m1$2.elements[9] *= invSZ; + _m1$2.elements[10] *= invSZ; + quaternion.setFromRotationMatrix(_m1$2); + scale2.x = sx; + scale2.y = sy; + scale2.z = sz; + return this; + } + makePerspective(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem) { + const te = this.elements; + const x = 2 * near / (right - left); + const y = 2 * near / (top - bottom); + const a = (right + left) / (right - left); + const b = (top + bottom) / (top - bottom); + let c, d; + if (coordinateSystem === WebGLCoordinateSystem) { + c = -(far + near) / (far - near); + d = -2 * far * near / (far - near); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + c = -far / (far - near); + d = -far * near / (far - near); + } else { + throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + coordinateSystem); + } + te[0] = x; + te[4] = 0; + te[8] = a; + te[12] = 0; + te[1] = 0; + te[5] = y; + te[9] = b; + te[13] = 0; + te[2] = 0; + te[6] = 0; + te[10] = c; + te[14] = d; + te[3] = 0; + te[7] = 0; + te[11] = -1; + te[15] = 0; + return this; + } + makeOrthographic(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem) { + const te = this.elements; + const w = 1 / (right - left); + const h = 1 / (top - bottom); + const p = 1 / (far - near); + const x = (right + left) * w; + const y = (top + bottom) * h; + let z, zInv; + if (coordinateSystem === WebGLCoordinateSystem) { + z = (far + near) * p; + zInv = -2 * p; + } else if (coordinateSystem === WebGPUCoordinateSystem) { + z = near * p; + zInv = -1 * p; + } else { + throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + coordinateSystem); + } + te[0] = 2 * w; + te[4] = 0; + te[8] = 0; + te[12] = -x; + te[1] = 0; + te[5] = 2 * h; + te[9] = 0; + te[13] = -y; + te[2] = 0; + te[6] = 0; + te[10] = zInv; + te[14] = -z; + te[3] = 0; + te[7] = 0; + te[11] = 0; + te[15] = 1; + return this; + } + equals(matrix) { + const te = this.elements; + const me = matrix.elements; + for (let i = 0;i < 16; i++) { + if (te[i] !== me[i]) + return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 16; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te = this.elements; + array[offset] = te[0]; + array[offset + 1] = te[1]; + array[offset + 2] = te[2]; + array[offset + 3] = te[3]; + array[offset + 4] = te[4]; + array[offset + 5] = te[5]; + array[offset + 6] = te[6]; + array[offset + 7] = te[7]; + array[offset + 8] = te[8]; + array[offset + 9] = te[9]; + array[offset + 10] = te[10]; + array[offset + 11] = te[11]; + array[offset + 12] = te[12]; + array[offset + 13] = te[13]; + array[offset + 14] = te[14]; + array[offset + 15] = te[15]; + return array; + } +} +var _v1$5 = /* @__PURE__ */ new Vector3; +var _m1$2 = /* @__PURE__ */ new Matrix4; +var _zero = /* @__PURE__ */ new Vector3(0, 0, 0); +var _one = /* @__PURE__ */ new Vector3(1, 1, 1); +var _x = /* @__PURE__ */ new Vector3; +var _y = /* @__PURE__ */ new Vector3; +var _z = /* @__PURE__ */ new Vector3; +var _matrix$2 = /* @__PURE__ */ new Matrix4; +var _quaternion$3 = /* @__PURE__ */ new Quaternion; + +class Euler { + constructor(x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER) { + this.isEuler = true; + this._x = x; + this._y = y; + this._z = z; + this._order = order; + } + get x() { + return this._x; + } + set x(value2) { + this._x = value2; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value2) { + this._y = value2; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value2) { + this._z = value2; + this._onChangeCallback(); + } + get order() { + return this._order; + } + set order(value2) { + this._order = value2; + this._onChangeCallback(); + } + set(x, y, z, order = this._order) { + this._x = x; + this._y = y; + this._z = z; + this._order = order; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._order); + } + copy(euler) { + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m, order = this._order, update = true) { + const te = m.elements; + const m11 = te[0], m12 = te[4], m13 = te[8]; + const m21 = te[1], m22 = te[5], m23 = te[9]; + const m31 = te[2], m32 = te[6], m33 = te[10]; + switch (order) { + case "XYZ": + this._y = Math.asin(clamp2(m13, -1, 1)); + if (Math.abs(m13) < 0.9999999) { + this._x = Math.atan2(-m23, m33); + this._z = Math.atan2(-m12, m11); + } else { + this._x = Math.atan2(m32, m22); + this._z = 0; + } + break; + case "YXZ": + this._x = Math.asin(-clamp2(m23, -1, 1)); + if (Math.abs(m23) < 0.9999999) { + this._y = Math.atan2(m13, m33); + this._z = Math.atan2(m21, m22); + } else { + this._y = Math.atan2(-m31, m11); + this._z = 0; + } + break; + case "ZXY": + this._x = Math.asin(clamp2(m32, -1, 1)); + if (Math.abs(m32) < 0.9999999) { + this._y = Math.atan2(-m31, m33); + this._z = Math.atan2(-m12, m22); + } else { + this._y = 0; + this._z = Math.atan2(m21, m11); + } + break; + case "ZYX": + this._y = Math.asin(-clamp2(m31, -1, 1)); + if (Math.abs(m31) < 0.9999999) { + this._x = Math.atan2(m32, m33); + this._z = Math.atan2(m21, m11); + } else { + this._x = 0; + this._z = Math.atan2(-m12, m22); + } + break; + case "YZX": + this._z = Math.asin(clamp2(m21, -1, 1)); + if (Math.abs(m21) < 0.9999999) { + this._x = Math.atan2(-m23, m22); + this._y = Math.atan2(-m31, m11); + } else { + this._x = 0; + this._y = Math.atan2(m13, m33); + } + break; + case "XZY": + this._z = Math.asin(-clamp2(m12, -1, 1)); + if (Math.abs(m12) < 0.9999999) { + this._x = Math.atan2(m32, m22); + this._y = Math.atan2(m13, m11); + } else { + this._x = Math.atan2(-m23, m33); + this._y = 0; + } + break; + default: + console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + order); + } + this._order = order; + if (update === true) + this._onChangeCallback(); + return this; + } + setFromQuaternion(q, order, update) { + _matrix$2.makeRotationFromQuaternion(q); + return this.setFromRotationMatrix(_matrix$2, order, update); + } + setFromVector3(v, order = this._order) { + return this.set(v.x, v.y, v.z, order); + } + reorder(newOrder) { + _quaternion$3.setFromEuler(this); + return this.setFromQuaternion(_quaternion$3, newOrder); + } + equals(euler) { + return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order; + } + fromArray(array) { + this._x = array[0]; + this._y = array[1]; + this._z = array[2]; + if (array[3] !== undefined) + this._order = array[3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._order; + return array; + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._order; + } +} +Euler.DEFAULT_ORDER = "XYZ"; + +class Layers { + constructor() { + this.mask = 1 | 0; + } + set(channel) { + this.mask = (1 << channel | 0) >>> 0; + } + enable(channel) { + this.mask |= 1 << channel | 0; + } + enableAll() { + this.mask = 4294967295 | 0; + } + toggle(channel) { + this.mask ^= 1 << channel | 0; + } + disable(channel) { + this.mask &= ~(1 << channel | 0); + } + disableAll() { + this.mask = 0; + } + test(layers) { + return (this.mask & layers.mask) !== 0; + } + isEnabled(channel) { + return (this.mask & (1 << channel | 0)) !== 0; + } +} +var _object3DId = 0; +var _v1$4 = /* @__PURE__ */ new Vector3; +var _q1 = /* @__PURE__ */ new Quaternion; +var _m1$1 = /* @__PURE__ */ new Matrix4; +var _target = /* @__PURE__ */ new Vector3; +var _position$3 = /* @__PURE__ */ new Vector3; +var _scale$2 = /* @__PURE__ */ new Vector3; +var _quaternion$2 = /* @__PURE__ */ new Quaternion; +var _xAxis = /* @__PURE__ */ new Vector3(1, 0, 0); +var _yAxis = /* @__PURE__ */ new Vector3(0, 1, 0); +var _zAxis = /* @__PURE__ */ new Vector3(0, 0, 1); +var _addedEvent = { type: "added" }; +var _removedEvent = { type: "removed" }; +var _childaddedEvent = { type: "childadded", child: null }; +var _childremovedEvent = { type: "childremoved", child: null }; + +class Object3D extends EventDispatcher { + constructor() { + super(); + this.isObject3D = true; + Object.defineProperty(this, "id", { value: _object3DId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "Object3D"; + this.parent = null; + this.children = []; + this.up = Object3D.DEFAULT_UP.clone(); + const position2 = new Vector3; + const rotation2 = new Euler; + const quaternion = new Quaternion; + const scale2 = new Vector3(1, 1, 1); + function onRotationChange() { + quaternion.setFromEuler(rotation2, false); + } + function onQuaternionChange() { + rotation2.setFromQuaternion(quaternion, undefined, false); + } + rotation2._onChange(onRotationChange); + quaternion._onChange(onQuaternionChange); + Object.defineProperties(this, { + position: { + configurable: true, + enumerable: true, + value: position2 + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation2 + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale2 + }, + modelViewMatrix: { + value: new Matrix4 + }, + normalMatrix: { + value: new Matrix3 + } + }); + this.matrix = new Matrix4; + this.matrixWorld = new Matrix4; + this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + this.layers = new Layers; + this.visible = true; + this.castShadow = false; + this.receiveShadow = false; + this.frustumCulled = true; + this.renderOrder = 0; + this.animations = []; + this.userData = {}; + } + onBeforeShadow() { + } + onAfterShadow() { + } + onBeforeRender() { + } + onAfterRender() { + } + applyMatrix4(matrix) { + if (this.matrixAutoUpdate) + this.updateMatrix(); + this.matrix.premultiply(matrix); + this.matrix.decompose(this.position, this.quaternion, this.scale); + } + applyQuaternion(q) { + this.quaternion.premultiply(q); + return this; + } + setRotationFromAxisAngle(axis, angle) { + this.quaternion.setFromAxisAngle(axis, angle); + } + setRotationFromEuler(euler) { + this.quaternion.setFromEuler(euler, true); + } + setRotationFromMatrix(m) { + this.quaternion.setFromRotationMatrix(m); + } + setRotationFromQuaternion(q) { + this.quaternion.copy(q); + } + rotateOnAxis(axis, angle) { + _q1.setFromAxisAngle(axis, angle); + this.quaternion.multiply(_q1); + return this; + } + rotateOnWorldAxis(axis, angle) { + _q1.setFromAxisAngle(axis, angle); + this.quaternion.premultiply(_q1); + return this; + } + rotateX(angle) { + return this.rotateOnAxis(_xAxis, angle); + } + rotateY(angle) { + return this.rotateOnAxis(_yAxis, angle); + } + rotateZ(angle) { + return this.rotateOnAxis(_zAxis, angle); + } + translateOnAxis(axis, distance) { + _v1$4.copy(axis).applyQuaternion(this.quaternion); + this.position.add(_v1$4.multiplyScalar(distance)); + return this; + } + translateX(distance) { + return this.translateOnAxis(_xAxis, distance); + } + translateY(distance) { + return this.translateOnAxis(_yAxis, distance); + } + translateZ(distance) { + return this.translateOnAxis(_zAxis, distance); + } + localToWorld(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(this.matrixWorld); + } + worldToLocal(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert()); + } + lookAt(x, y, z) { + if (x.isVector3) { + _target.copy(x); + } else { + _target.set(x, y, z); + } + const parent2 = this.parent; + this.updateWorldMatrix(true, false); + _position$3.setFromMatrixPosition(this.matrixWorld); + if (this.isCamera || this.isLight) { + _m1$1.lookAt(_position$3, _target, this.up); + } else { + _m1$1.lookAt(_target, _position$3, this.up); + } + this.quaternion.setFromRotationMatrix(_m1$1); + if (parent2) { + _m1$1.extractRotation(parent2.matrixWorld); + _q1.setFromRotationMatrix(_m1$1); + this.quaternion.premultiply(_q1.invert()); + } + } + add(object) { + if (arguments.length > 1) { + for (let i = 0;i < arguments.length; i++) { + this.add(arguments[i]); + } + return this; + } + if (object === this) { + console.error("THREE.Object3D.add: object can't be added as a child of itself.", object); + return this; + } + if (object && object.isObject3D) { + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.dispatchEvent(_addedEvent); + _childaddedEvent.child = object; + this.dispatchEvent(_childaddedEvent); + _childaddedEvent.child = null; + } else { + console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object); + } + return this; + } + remove(object) { + if (arguments.length > 1) { + for (let i = 0;i < arguments.length; i++) { + this.remove(arguments[i]); + } + return this; + } + const index2 = this.children.indexOf(object); + if (index2 !== -1) { + object.parent = null; + this.children.splice(index2, 1); + object.dispatchEvent(_removedEvent); + _childremovedEvent.child = object; + this.dispatchEvent(_childremovedEvent); + _childremovedEvent.child = null; + } + return this; + } + removeFromParent() { + const parent2 = this.parent; + if (parent2 !== null) { + parent2.remove(this); + } + return this; + } + clear() { + return this.remove(...this.children); + } + attach(object) { + this.updateWorldMatrix(true, false); + _m1$1.copy(this.matrixWorld).invert(); + if (object.parent !== null) { + object.parent.updateWorldMatrix(true, false); + _m1$1.multiply(object.parent.matrixWorld); + } + object.applyMatrix4(_m1$1); + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.updateWorldMatrix(false, true); + object.dispatchEvent(_addedEvent); + _childaddedEvent.child = object; + this.dispatchEvent(_childaddedEvent); + _childaddedEvent.child = null; + return this; + } + getObjectById(id) { + return this.getObjectByProperty("id", id); + } + getObjectByName(name2) { + return this.getObjectByProperty("name", name2); + } + getObjectByProperty(name2, value2) { + if (this[name2] === value2) + return this; + for (let i = 0, l = this.children.length;i < l; i++) { + const child = this.children[i]; + const object = child.getObjectByProperty(name2, value2); + if (object !== undefined) { + return object; + } + } + return; + } + getObjectsByProperty(name2, value2, result = []) { + if (this[name2] === value2) + result.push(this); + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + children[i].getObjectsByProperty(name2, value2, result); + } + return result; + } + getWorldPosition(target) { + this.updateWorldMatrix(true, false); + return target.setFromMatrixPosition(this.matrixWorld); + } + getWorldQuaternion(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$3, target, _scale$2); + return target; + } + getWorldScale(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$3, _quaternion$2, target); + return target; + } + getWorldDirection(target) { + this.updateWorldMatrix(true, false); + const e = this.matrixWorld.elements; + return target.set(e[8], e[9], e[10]).normalize(); + } + raycast() { + } + traverse(callback) { + callback(this); + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + children[i].traverse(callback); + } + } + traverseVisible(callback) { + if (this.visible === false) + return; + callback(this); + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + children[i].traverseVisible(callback); + } + } + traverseAncestors(callback) { + const parent2 = this.parent; + if (parent2 !== null) { + callback(parent2); + parent2.traverseAncestors(callback); + } + } + updateMatrix() { + this.matrix.compose(this.position, this.quaternion, this.scale); + this.matrixWorldNeedsUpdate = true; + } + updateMatrixWorld(force) { + if (this.matrixAutoUpdate) + this.updateMatrix(); + if (this.matrixWorldNeedsUpdate || force) { + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + this.matrixWorldNeedsUpdate = false; + force = true; + } + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + const child = children[i]; + child.updateMatrixWorld(force); + } + } + updateWorldMatrix(updateParents, updateChildren) { + const parent2 = this.parent; + if (updateParents === true && parent2 !== null) { + parent2.updateWorldMatrix(true, false); + } + if (this.matrixAutoUpdate) + this.updateMatrix(); + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + if (updateChildren === true) { + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + const child = children[i]; + child.updateWorldMatrix(false, true); + } + } + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + const output = {}; + if (isRootObject) { + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + output.metadata = { + version: 4.6, + type: "Object", + generator: "Object3D.toJSON" + }; + } + const object = {}; + object.uuid = this.uuid; + object.type = this.type; + if (this.name !== "") + object.name = this.name; + if (this.castShadow === true) + object.castShadow = true; + if (this.receiveShadow === true) + object.receiveShadow = true; + if (this.visible === false) + object.visible = false; + if (this.frustumCulled === false) + object.frustumCulled = false; + if (this.renderOrder !== 0) + object.renderOrder = this.renderOrder; + if (Object.keys(this.userData).length > 0) + object.userData = this.userData; + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + object.up = this.up.toArray(); + if (this.matrixAutoUpdate === false) + object.matrixAutoUpdate = false; + if (this.isInstancedMesh) { + object.type = "InstancedMesh"; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if (this.instanceColor !== null) + object.instanceColor = this.instanceColor.toJSON(); + } + if (this.isBatchedMesh) { + object.type = "BatchedMesh"; + object.perObjectFrustumCulled = this.perObjectFrustumCulled; + object.sortObjects = this.sortObjects; + object.drawRanges = this._drawRanges; + object.reservedRanges = this._reservedRanges; + object.visibility = this._visibility; + object.active = this._active; + object.bounds = this._bounds.map((bound) => ({ + boxInitialized: bound.boxInitialized, + boxMin: bound.box.min.toArray(), + boxMax: bound.box.max.toArray(), + sphereInitialized: bound.sphereInitialized, + sphereRadius: bound.sphere.radius, + sphereCenter: bound.sphere.center.toArray() + })); + object.maxInstanceCount = this._maxInstanceCount; + object.maxVertexCount = this._maxVertexCount; + object.maxIndexCount = this._maxIndexCount; + object.geometryInitialized = this._geometryInitialized; + object.geometryCount = this._geometryCount; + object.matricesTexture = this._matricesTexture.toJSON(meta); + if (this._colorsTexture !== null) + object.colorsTexture = this._colorsTexture.toJSON(meta); + if (this.boundingSphere !== null) { + object.boundingSphere = { + center: object.boundingSphere.center.toArray(), + radius: object.boundingSphere.radius + }; + } + if (this.boundingBox !== null) { + object.boundingBox = { + min: object.boundingBox.min.toArray(), + max: object.boundingBox.max.toArray() + }; + } + } + function serialize(library, element) { + if (library[element.uuid] === undefined) { + library[element.uuid] = element.toJSON(meta); + } + return element.uuid; + } + if (this.isScene) { + if (this.background) { + if (this.background.isColor) { + object.background = this.background.toJSON(); + } else if (this.background.isTexture) { + object.background = this.background.toJSON(meta).uuid; + } + } + if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) { + object.environment = this.environment.toJSON(meta).uuid; + } + } else if (this.isMesh || this.isLine || this.isPoints) { + object.geometry = serialize(meta.geometries, this.geometry); + const parameters = this.geometry.parameters; + if (parameters !== undefined && parameters.shapes !== undefined) { + const shapes = parameters.shapes; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + serialize(meta.shapes, shape); + } + } else { + serialize(meta.shapes, shapes); + } + } + } + if (this.isSkinnedMesh) { + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + if (this.skeleton !== undefined) { + serialize(meta.skeletons, this.skeleton); + object.skeleton = this.skeleton.uuid; + } + } + if (this.material !== undefined) { + if (Array.isArray(this.material)) { + const uuids = []; + for (let i = 0, l = this.material.length;i < l; i++) { + uuids.push(serialize(meta.materials, this.material[i])); + } + object.material = uuids; + } else { + object.material = serialize(meta.materials, this.material); + } + } + if (this.children.length > 0) { + object.children = []; + for (let i = 0;i < this.children.length; i++) { + object.children.push(this.children[i].toJSON(meta).object); + } + } + if (this.animations.length > 0) { + object.animations = []; + for (let i = 0;i < this.animations.length; i++) { + const animation = this.animations[i]; + object.animations.push(serialize(meta.animations, animation)); + } + } + if (isRootObject) { + const geometries = extractFromCache(meta.geometries); + const materials = extractFromCache(meta.materials); + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + const shapes = extractFromCache(meta.shapes); + const skeletons = extractFromCache(meta.skeletons); + const animations = extractFromCache(meta.animations); + const nodes = extractFromCache(meta.nodes); + if (geometries.length > 0) + output.geometries = geometries; + if (materials.length > 0) + output.materials = materials; + if (textures.length > 0) + output.textures = textures; + if (images.length > 0) + output.images = images; + if (shapes.length > 0) + output.shapes = shapes; + if (skeletons.length > 0) + output.skeletons = skeletons; + if (animations.length > 0) + output.animations = animations; + if (nodes.length > 0) + output.nodes = nodes; + } + output.object = object; + return output; + function extractFromCache(cache) { + const values2 = []; + for (const key2 in cache) { + const data2 = cache[key2]; + delete data2.metadata; + values2.push(data2); + } + return values2; + } + } + clone(recursive) { + return new this.constructor().copy(this, recursive); + } + copy(source, recursive = true) { + this.name = source.name; + this.up.copy(source.up); + this.position.copy(source.position); + this.rotation.order = source.rotation.order; + this.quaternion.copy(source.quaternion); + this.scale.copy(source.scale); + this.matrix.copy(source.matrix); + this.matrixWorld.copy(source.matrixWorld); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + this.layers.mask = source.layers.mask; + this.visible = source.visible; + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + this.animations = source.animations.slice(); + this.userData = JSON.parse(JSON.stringify(source.userData)); + if (recursive === true) { + for (let i = 0;i < source.children.length; i++) { + const child = source.children[i]; + this.add(child.clone()); + } + } + return this; + } +} +Object3D.DEFAULT_UP = /* @__PURE__ */ new Vector3(0, 1, 0); +Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true; +Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; +var _v0$1 = /* @__PURE__ */ new Vector3; +var _v1$3 = /* @__PURE__ */ new Vector3; +var _v2$2 = /* @__PURE__ */ new Vector3; +var _v3$2 = /* @__PURE__ */ new Vector3; +var _vab = /* @__PURE__ */ new Vector3; +var _vac = /* @__PURE__ */ new Vector3; +var _vbc = /* @__PURE__ */ new Vector3; +var _vap = /* @__PURE__ */ new Vector3; +var _vbp = /* @__PURE__ */ new Vector3; +var _vcp = /* @__PURE__ */ new Vector3; +var _v40 = /* @__PURE__ */ new Vector4; +var _v41 = /* @__PURE__ */ new Vector4; +var _v42 = /* @__PURE__ */ new Vector4; + +class Triangle { + constructor(a = new Vector3, b = new Vector3, c = new Vector3) { + this.a = a; + this.b = b; + this.c = c; + } + static getNormal(a, b, c, target) { + target.subVectors(c, b); + _v0$1.subVectors(a, b); + target.cross(_v0$1); + const targetLengthSq = target.lengthSq(); + if (targetLengthSq > 0) { + return target.multiplyScalar(1 / Math.sqrt(targetLengthSq)); + } + return target.set(0, 0, 0); + } + static getBarycoord(point, a, b, c, target) { + _v0$1.subVectors(c, a); + _v1$3.subVectors(b, a); + _v2$2.subVectors(point, a); + const dot00 = _v0$1.dot(_v0$1); + const dot01 = _v0$1.dot(_v1$3); + const dot02 = _v0$1.dot(_v2$2); + const dot11 = _v1$3.dot(_v1$3); + const dot12 = _v1$3.dot(_v2$2); + const denom = dot00 * dot11 - dot01 * dot01; + if (denom === 0) { + target.set(0, 0, 0); + return null; + } + const invDenom = 1 / denom; + const u = (dot11 * dot02 - dot01 * dot12) * invDenom; + const v = (dot00 * dot12 - dot01 * dot02) * invDenom; + return target.set(1 - u - v, v, u); + } + static containsPoint(point, a, b, c) { + if (this.getBarycoord(point, a, b, c, _v3$2) === null) { + return false; + } + return _v3$2.x >= 0 && _v3$2.y >= 0 && _v3$2.x + _v3$2.y <= 1; + } + static getInterpolation(point, p1, p2, p3, v1, v2, v3, target) { + if (this.getBarycoord(point, p1, p2, p3, _v3$2) === null) { + target.x = 0; + target.y = 0; + if ("z" in target) + target.z = 0; + if ("w" in target) + target.w = 0; + return null; + } + target.setScalar(0); + target.addScaledVector(v1, _v3$2.x); + target.addScaledVector(v2, _v3$2.y); + target.addScaledVector(v3, _v3$2.z); + return target; + } + static getInterpolatedAttribute(attr, i1, i2, i3, barycoord, target) { + _v40.setScalar(0); + _v41.setScalar(0); + _v42.setScalar(0); + _v40.fromBufferAttribute(attr, i1); + _v41.fromBufferAttribute(attr, i2); + _v42.fromBufferAttribute(attr, i3); + target.setScalar(0); + target.addScaledVector(_v40, barycoord.x); + target.addScaledVector(_v41, barycoord.y); + target.addScaledVector(_v42, barycoord.z); + return target; + } + static isFrontFacing(a, b, c, direction) { + _v0$1.subVectors(c, b); + _v1$3.subVectors(a, b); + return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false; + } + set(a, b, c) { + this.a.copy(a); + this.b.copy(b); + this.c.copy(c); + return this; + } + setFromPointsAndIndices(points, i0, i1, i2) { + this.a.copy(points[i0]); + this.b.copy(points[i1]); + this.c.copy(points[i2]); + return this; + } + setFromAttributeAndIndices(attribute, i0, i1, i2) { + this.a.fromBufferAttribute(attribute, i0); + this.b.fromBufferAttribute(attribute, i1); + this.c.fromBufferAttribute(attribute, i2); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(triangle) { + this.a.copy(triangle.a); + this.b.copy(triangle.b); + this.c.copy(triangle.c); + return this; + } + getArea() { + _v0$1.subVectors(this.c, this.b); + _v1$3.subVectors(this.a, this.b); + return _v0$1.cross(_v1$3).length() * 0.5; + } + getMidpoint(target) { + return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); + } + getNormal(target) { + return Triangle.getNormal(this.a, this.b, this.c, target); + } + getPlane(target) { + return target.setFromCoplanarPoints(this.a, this.b, this.c); + } + getBarycoord(point, target) { + return Triangle.getBarycoord(point, this.a, this.b, this.c, target); + } + getInterpolation(point, v1, v2, v3, target) { + return Triangle.getInterpolation(point, this.a, this.b, this.c, v1, v2, v3, target); + } + containsPoint(point) { + return Triangle.containsPoint(point, this.a, this.b, this.c); + } + isFrontFacing(direction) { + return Triangle.isFrontFacing(this.a, this.b, this.c, direction); + } + intersectsBox(box) { + return box.intersectsTriangle(this); + } + closestPointToPoint(p, target) { + const a = this.a, b = this.b, c = this.c; + let v, w; + _vab.subVectors(b, a); + _vac.subVectors(c, a); + _vap.subVectors(p, a); + const d1 = _vab.dot(_vap); + const d2 = _vac.dot(_vap); + if (d1 <= 0 && d2 <= 0) { + return target.copy(a); + } + _vbp.subVectors(p, b); + const d3 = _vab.dot(_vbp); + const d4 = _vac.dot(_vbp); + if (d3 >= 0 && d4 <= d3) { + return target.copy(b); + } + const vc = d1 * d4 - d3 * d2; + if (vc <= 0 && d1 >= 0 && d3 <= 0) { + v = d1 / (d1 - d3); + return target.copy(a).addScaledVector(_vab, v); + } + _vcp.subVectors(p, c); + const d5 = _vab.dot(_vcp); + const d6 = _vac.dot(_vcp); + if (d6 >= 0 && d5 <= d6) { + return target.copy(c); + } + const vb = d5 * d2 - d1 * d6; + if (vb <= 0 && d2 >= 0 && d6 <= 0) { + w = d2 / (d2 - d6); + return target.copy(a).addScaledVector(_vac, w); + } + const va = d3 * d6 - d5 * d4; + if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { + _vbc.subVectors(c, b); + w = (d4 - d3) / (d4 - d3 + (d5 - d6)); + return target.copy(b).addScaledVector(_vbc, w); + } + const denom = 1 / (va + vb + vc); + v = vb * denom; + w = vc * denom; + return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w); + } + equals(triangle) { + return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c); + } +} +var _colorKeywords = { + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + rebeccapurple: 6697881, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 +}; +var _hslA = { h: 0, s: 0, l: 0 }; +var _hslB = { h: 0, s: 0, l: 0 }; +function hue2rgb2(p, q, t) { + if (t < 0) + t += 1; + if (t > 1) + t -= 1; + if (t < 1 / 6) + return p + (q - p) * 6 * t; + if (t < 1 / 2) + return q; + if (t < 2 / 3) + return p + (q - p) * 6 * (2 / 3 - t); + return p; +} + +class Color { + constructor(r, g, b) { + this.isColor = true; + this.r = 1; + this.g = 1; + this.b = 1; + return this.set(r, g, b); + } + set(r, g, b) { + if (g === undefined && b === undefined) { + const value2 = r; + if (value2 && value2.isColor) { + this.copy(value2); + } else if (typeof value2 === "number") { + this.setHex(value2); + } else if (typeof value2 === "string") { + this.setStyle(value2); + } + } else { + this.setRGB(r, g, b); + } + return this; + } + setScalar(scalar) { + this.r = scalar; + this.g = scalar; + this.b = scalar; + return this; + } + setHex(hex, colorSpace = SRGBColorSpace) { + hex = Math.floor(hex); + this.r = (hex >> 16 & 255) / 255; + this.g = (hex >> 8 & 255) / 255; + this.b = (hex & 255) / 255; + ColorManagement.toWorkingColorSpace(this, colorSpace); + return this; + } + setRGB(r, g, b, colorSpace = ColorManagement.workingColorSpace) { + this.r = r; + this.g = g; + this.b = b; + ColorManagement.toWorkingColorSpace(this, colorSpace); + return this; + } + setHSL(h, s, l, colorSpace = ColorManagement.workingColorSpace) { + h = euclideanModulo(h, 1); + s = clamp2(s, 0, 1); + l = clamp2(l, 0, 1); + if (s === 0) { + this.r = this.g = this.b = l; + } else { + const p = l <= 0.5 ? l * (1 + s) : l + s - l * s; + const q = 2 * l - p; + this.r = hue2rgb2(q, p, h + 1 / 3); + this.g = hue2rgb2(q, p, h); + this.b = hue2rgb2(q, p, h - 1 / 3); + } + ColorManagement.toWorkingColorSpace(this, colorSpace); + return this; + } + setStyle(style, colorSpace = SRGBColorSpace) { + function handleAlpha(string) { + if (string === undefined) + return; + if (parseFloat(string) < 1) { + console.warn("THREE.Color: Alpha component of " + style + " will be ignored."); + } + } + let m; + if (m = /^(\w+)\(([^\)]*)\)/.exec(style)) { + let color; + const name2 = m[1]; + const components = m[2]; + switch (name2) { + case "rgb": + case "rgba": + if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB(Math.min(255, parseInt(color[1], 10)) / 255, Math.min(255, parseInt(color[2], 10)) / 255, Math.min(255, parseInt(color[3], 10)) / 255, colorSpace); + } + if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB(Math.min(100, parseInt(color[1], 10)) / 100, Math.min(100, parseInt(color[2], 10)) / 100, Math.min(100, parseInt(color[3], 10)) / 100, colorSpace); + } + break; + case "hsl": + case "hsla": + if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setHSL(parseFloat(color[1]) / 360, parseFloat(color[2]) / 100, parseFloat(color[3]) / 100, colorSpace); + } + break; + default: + console.warn("THREE.Color: Unknown color model " + style); + } + } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) { + const hex = m[1]; + const size = hex.length; + if (size === 3) { + return this.setRGB(parseInt(hex.charAt(0), 16) / 15, parseInt(hex.charAt(1), 16) / 15, parseInt(hex.charAt(2), 16) / 15, colorSpace); + } else if (size === 6) { + return this.setHex(parseInt(hex, 16), colorSpace); + } else { + console.warn("THREE.Color: Invalid hex color " + style); + } + } else if (style && style.length > 0) { + return this.setColorName(style, colorSpace); + } + return this; + } + setColorName(style, colorSpace = SRGBColorSpace) { + const hex = _colorKeywords[style.toLowerCase()]; + if (hex !== undefined) { + this.setHex(hex, colorSpace); + } else { + console.warn("THREE.Color: Unknown color " + style); + } + return this; + } + clone() { + return new this.constructor(this.r, this.g, this.b); + } + copy(color) { + this.r = color.r; + this.g = color.g; + this.b = color.b; + return this; + } + copySRGBToLinear(color) { + this.r = SRGBToLinear(color.r); + this.g = SRGBToLinear(color.g); + this.b = SRGBToLinear(color.b); + return this; + } + copyLinearToSRGB(color) { + this.r = LinearToSRGB(color.r); + this.g = LinearToSRGB(color.g); + this.b = LinearToSRGB(color.b); + return this; + } + convertSRGBToLinear() { + this.copySRGBToLinear(this); + return this; + } + convertLinearToSRGB() { + this.copyLinearToSRGB(this); + return this; + } + getHex(colorSpace = SRGBColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + return Math.round(clamp2(_color.r * 255, 0, 255)) * 65536 + Math.round(clamp2(_color.g * 255, 0, 255)) * 256 + Math.round(clamp2(_color.b * 255, 0, 255)); + } + getHexString(colorSpace = SRGBColorSpace) { + return ("000000" + this.getHex(colorSpace).toString(16)).slice(-6); + } + getHSL(target, colorSpace = ColorManagement.workingColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + const { r, g, b } = _color; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + let hue, saturation; + const lightness = (min + max) / 2; + if (min === max) { + hue = 0; + saturation = 0; + } else { + const delta = max - min; + saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min); + switch (max) { + case r: + hue = (g - b) / delta + (g < b ? 6 : 0); + break; + case g: + hue = (b - r) / delta + 2; + break; + case b: + hue = (r - g) / delta + 4; + break; + } + hue /= 6; + } + target.h = hue; + target.s = saturation; + target.l = lightness; + return target; + } + getRGB(target, colorSpace = ColorManagement.workingColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + target.r = _color.r; + target.g = _color.g; + target.b = _color.b; + return target; + } + getStyle(colorSpace = SRGBColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + const { r, g, b } = _color; + if (colorSpace !== SRGBColorSpace) { + return `color(${colorSpace} ${r.toFixed(3)} ${g.toFixed(3)} ${b.toFixed(3)})`; + } + return `rgb(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)})`; + } + offsetHSL(h, s, l) { + this.getHSL(_hslA); + return this.setHSL(_hslA.h + h, _hslA.s + s, _hslA.l + l); + } + add(color) { + this.r += color.r; + this.g += color.g; + this.b += color.b; + return this; + } + addColors(color1, color2) { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + return this; + } + addScalar(s) { + this.r += s; + this.g += s; + this.b += s; + return this; + } + sub(color) { + this.r = Math.max(0, this.r - color.r); + this.g = Math.max(0, this.g - color.g); + this.b = Math.max(0, this.b - color.b); + return this; + } + multiply(color) { + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + return this; + } + multiplyScalar(s) { + this.r *= s; + this.g *= s; + this.b *= s; + return this; + } + lerp(color, alpha) { + this.r += (color.r - this.r) * alpha; + this.g += (color.g - this.g) * alpha; + this.b += (color.b - this.b) * alpha; + return this; + } + lerpColors(color1, color2, alpha) { + this.r = color1.r + (color2.r - color1.r) * alpha; + this.g = color1.g + (color2.g - color1.g) * alpha; + this.b = color1.b + (color2.b - color1.b) * alpha; + return this; + } + lerpHSL(color, alpha) { + this.getHSL(_hslA); + color.getHSL(_hslB); + const h = lerp(_hslA.h, _hslB.h, alpha); + const s = lerp(_hslA.s, _hslB.s, alpha); + const l = lerp(_hslA.l, _hslB.l, alpha); + this.setHSL(h, s, l); + return this; + } + setFromVector3(v) { + this.r = v.x; + this.g = v.y; + this.b = v.z; + return this; + } + applyMatrix3(m) { + const r = this.r, g = this.g, b = this.b; + const e = m.elements; + this.r = e[0] * r + e[3] * g + e[6] * b; + this.g = e[1] * r + e[4] * g + e[7] * b; + this.b = e[2] * r + e[5] * g + e[8] * b; + return this; + } + equals(c) { + return c.r === this.r && c.g === this.g && c.b === this.b; + } + fromArray(array, offset = 0) { + this.r = array[offset]; + this.g = array[offset + 1]; + this.b = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.r; + array[offset + 1] = this.g; + array[offset + 2] = this.b; + return array; + } + fromBufferAttribute(attribute, index2) { + this.r = attribute.getX(index2); + this.g = attribute.getY(index2); + this.b = attribute.getZ(index2); + return this; + } + toJSON() { + return this.getHex(); + } + *[Symbol.iterator]() { + yield this.r; + yield this.g; + yield this.b; + } +} +var _color = /* @__PURE__ */ new Color; +Color.NAMES = _colorKeywords; +var _materialId = 0; + +class Material extends EventDispatcher { + constructor() { + super(); + this.isMaterial = true; + Object.defineProperty(this, "id", { value: _materialId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "Material"; + this.blending = NormalBlending; + this.side = FrontSide; + this.vertexColors = false; + this.opacity = 1; + this.transparent = false; + this.alphaHash = false; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; + this.blendColor = new Color(0, 0, 0); + this.blendAlpha = 0; + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; + this.stencilWriteMask = 255; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 255; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + this.shadowSide = null; + this.colorWrite = true; + this.precision = null; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + this.dithering = false; + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + this.forceSinglePass = false; + this.visible = true; + this.toneMapped = true; + this.userData = {}; + this.version = 0; + this._alphaTest = 0; + } + get alphaTest() { + return this._alphaTest; + } + set alphaTest(value2) { + if (this._alphaTest > 0 !== value2 > 0) { + this.version++; + } + this._alphaTest = value2; + } + onBeforeRender() { + } + onBeforeCompile() { + } + customProgramCacheKey() { + return this.onBeforeCompile.toString(); + } + setValues(values2) { + if (values2 === undefined) + return; + for (const key2 in values2) { + const newValue = values2[key2]; + if (newValue === undefined) { + console.warn(`THREE.Material: parameter '${key2}' has value of undefined.`); + continue; + } + const currentValue = this[key2]; + if (currentValue === undefined) { + console.warn(`THREE.Material: '${key2}' is not a property of THREE.${this.type}.`); + continue; + } + if (currentValue && currentValue.isColor) { + currentValue.set(newValue); + } else if (currentValue && currentValue.isVector3 && (newValue && newValue.isVector3)) { + currentValue.copy(newValue); + } else { + this[key2] = newValue; + } + } + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + if (isRootObject) { + meta = { + textures: {}, + images: {} + }; + } + const data2 = { + metadata: { + version: 4.6, + type: "Material", + generator: "Material.toJSON" + } + }; + data2.uuid = this.uuid; + data2.type = this.type; + if (this.name !== "") + data2.name = this.name; + if (this.color && this.color.isColor) + data2.color = this.color.getHex(); + if (this.roughness !== undefined) + data2.roughness = this.roughness; + if (this.metalness !== undefined) + data2.metalness = this.metalness; + if (this.sheen !== undefined) + data2.sheen = this.sheen; + if (this.sheenColor && this.sheenColor.isColor) + data2.sheenColor = this.sheenColor.getHex(); + if (this.sheenRoughness !== undefined) + data2.sheenRoughness = this.sheenRoughness; + if (this.emissive && this.emissive.isColor) + data2.emissive = this.emissive.getHex(); + if (this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1) + data2.emissiveIntensity = this.emissiveIntensity; + if (this.specular && this.specular.isColor) + data2.specular = this.specular.getHex(); + if (this.specularIntensity !== undefined) + data2.specularIntensity = this.specularIntensity; + if (this.specularColor && this.specularColor.isColor) + data2.specularColor = this.specularColor.getHex(); + if (this.shininess !== undefined) + data2.shininess = this.shininess; + if (this.clearcoat !== undefined) + data2.clearcoat = this.clearcoat; + if (this.clearcoatRoughness !== undefined) + data2.clearcoatRoughness = this.clearcoatRoughness; + if (this.clearcoatMap && this.clearcoatMap.isTexture) { + data2.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid; + } + if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) { + data2.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid; + } + if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) { + data2.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid; + data2.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + } + if (this.dispersion !== undefined) + data2.dispersion = this.dispersion; + if (this.iridescence !== undefined) + data2.iridescence = this.iridescence; + if (this.iridescenceIOR !== undefined) + data2.iridescenceIOR = this.iridescenceIOR; + if (this.iridescenceThicknessRange !== undefined) + data2.iridescenceThicknessRange = this.iridescenceThicknessRange; + if (this.iridescenceMap && this.iridescenceMap.isTexture) { + data2.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid; + } + if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) { + data2.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid; + } + if (this.anisotropy !== undefined) + data2.anisotropy = this.anisotropy; + if (this.anisotropyRotation !== undefined) + data2.anisotropyRotation = this.anisotropyRotation; + if (this.anisotropyMap && this.anisotropyMap.isTexture) { + data2.anisotropyMap = this.anisotropyMap.toJSON(meta).uuid; + } + if (this.map && this.map.isTexture) + data2.map = this.map.toJSON(meta).uuid; + if (this.matcap && this.matcap.isTexture) + data2.matcap = this.matcap.toJSON(meta).uuid; + if (this.alphaMap && this.alphaMap.isTexture) + data2.alphaMap = this.alphaMap.toJSON(meta).uuid; + if (this.lightMap && this.lightMap.isTexture) { + data2.lightMap = this.lightMap.toJSON(meta).uuid; + data2.lightMapIntensity = this.lightMapIntensity; + } + if (this.aoMap && this.aoMap.isTexture) { + data2.aoMap = this.aoMap.toJSON(meta).uuid; + data2.aoMapIntensity = this.aoMapIntensity; + } + if (this.bumpMap && this.bumpMap.isTexture) { + data2.bumpMap = this.bumpMap.toJSON(meta).uuid; + data2.bumpScale = this.bumpScale; + } + if (this.normalMap && this.normalMap.isTexture) { + data2.normalMap = this.normalMap.toJSON(meta).uuid; + data2.normalMapType = this.normalMapType; + data2.normalScale = this.normalScale.toArray(); + } + if (this.displacementMap && this.displacementMap.isTexture) { + data2.displacementMap = this.displacementMap.toJSON(meta).uuid; + data2.displacementScale = this.displacementScale; + data2.displacementBias = this.displacementBias; + } + if (this.roughnessMap && this.roughnessMap.isTexture) + data2.roughnessMap = this.roughnessMap.toJSON(meta).uuid; + if (this.metalnessMap && this.metalnessMap.isTexture) + data2.metalnessMap = this.metalnessMap.toJSON(meta).uuid; + if (this.emissiveMap && this.emissiveMap.isTexture) + data2.emissiveMap = this.emissiveMap.toJSON(meta).uuid; + if (this.specularMap && this.specularMap.isTexture) + data2.specularMap = this.specularMap.toJSON(meta).uuid; + if (this.specularIntensityMap && this.specularIntensityMap.isTexture) + data2.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid; + if (this.specularColorMap && this.specularColorMap.isTexture) + data2.specularColorMap = this.specularColorMap.toJSON(meta).uuid; + if (this.envMap && this.envMap.isTexture) { + data2.envMap = this.envMap.toJSON(meta).uuid; + if (this.combine !== undefined) + data2.combine = this.combine; + } + if (this.envMapRotation !== undefined) + data2.envMapRotation = this.envMapRotation.toArray(); + if (this.envMapIntensity !== undefined) + data2.envMapIntensity = this.envMapIntensity; + if (this.reflectivity !== undefined) + data2.reflectivity = this.reflectivity; + if (this.refractionRatio !== undefined) + data2.refractionRatio = this.refractionRatio; + if (this.gradientMap && this.gradientMap.isTexture) { + data2.gradientMap = this.gradientMap.toJSON(meta).uuid; + } + if (this.transmission !== undefined) + data2.transmission = this.transmission; + if (this.transmissionMap && this.transmissionMap.isTexture) + data2.transmissionMap = this.transmissionMap.toJSON(meta).uuid; + if (this.thickness !== undefined) + data2.thickness = this.thickness; + if (this.thicknessMap && this.thicknessMap.isTexture) + data2.thicknessMap = this.thicknessMap.toJSON(meta).uuid; + if (this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity) + data2.attenuationDistance = this.attenuationDistance; + if (this.attenuationColor !== undefined) + data2.attenuationColor = this.attenuationColor.getHex(); + if (this.size !== undefined) + data2.size = this.size; + if (this.shadowSide !== null) + data2.shadowSide = this.shadowSide; + if (this.sizeAttenuation !== undefined) + data2.sizeAttenuation = this.sizeAttenuation; + if (this.blending !== NormalBlending) + data2.blending = this.blending; + if (this.side !== FrontSide) + data2.side = this.side; + if (this.vertexColors === true) + data2.vertexColors = true; + if (this.opacity < 1) + data2.opacity = this.opacity; + if (this.transparent === true) + data2.transparent = true; + if (this.blendSrc !== SrcAlphaFactor) + data2.blendSrc = this.blendSrc; + if (this.blendDst !== OneMinusSrcAlphaFactor) + data2.blendDst = this.blendDst; + if (this.blendEquation !== AddEquation) + data2.blendEquation = this.blendEquation; + if (this.blendSrcAlpha !== null) + data2.blendSrcAlpha = this.blendSrcAlpha; + if (this.blendDstAlpha !== null) + data2.blendDstAlpha = this.blendDstAlpha; + if (this.blendEquationAlpha !== null) + data2.blendEquationAlpha = this.blendEquationAlpha; + if (this.blendColor && this.blendColor.isColor) + data2.blendColor = this.blendColor.getHex(); + if (this.blendAlpha !== 0) + data2.blendAlpha = this.blendAlpha; + if (this.depthFunc !== LessEqualDepth) + data2.depthFunc = this.depthFunc; + if (this.depthTest === false) + data2.depthTest = this.depthTest; + if (this.depthWrite === false) + data2.depthWrite = this.depthWrite; + if (this.colorWrite === false) + data2.colorWrite = this.colorWrite; + if (this.stencilWriteMask !== 255) + data2.stencilWriteMask = this.stencilWriteMask; + if (this.stencilFunc !== AlwaysStencilFunc) + data2.stencilFunc = this.stencilFunc; + if (this.stencilRef !== 0) + data2.stencilRef = this.stencilRef; + if (this.stencilFuncMask !== 255) + data2.stencilFuncMask = this.stencilFuncMask; + if (this.stencilFail !== KeepStencilOp) + data2.stencilFail = this.stencilFail; + if (this.stencilZFail !== KeepStencilOp) + data2.stencilZFail = this.stencilZFail; + if (this.stencilZPass !== KeepStencilOp) + data2.stencilZPass = this.stencilZPass; + if (this.stencilWrite === true) + data2.stencilWrite = this.stencilWrite; + if (this.rotation !== undefined && this.rotation !== 0) + data2.rotation = this.rotation; + if (this.polygonOffset === true) + data2.polygonOffset = true; + if (this.polygonOffsetFactor !== 0) + data2.polygonOffsetFactor = this.polygonOffsetFactor; + if (this.polygonOffsetUnits !== 0) + data2.polygonOffsetUnits = this.polygonOffsetUnits; + if (this.linewidth !== undefined && this.linewidth !== 1) + data2.linewidth = this.linewidth; + if (this.dashSize !== undefined) + data2.dashSize = this.dashSize; + if (this.gapSize !== undefined) + data2.gapSize = this.gapSize; + if (this.scale !== undefined) + data2.scale = this.scale; + if (this.dithering === true) + data2.dithering = true; + if (this.alphaTest > 0) + data2.alphaTest = this.alphaTest; + if (this.alphaHash === true) + data2.alphaHash = true; + if (this.alphaToCoverage === true) + data2.alphaToCoverage = true; + if (this.premultipliedAlpha === true) + data2.premultipliedAlpha = true; + if (this.forceSinglePass === true) + data2.forceSinglePass = true; + if (this.wireframe === true) + data2.wireframe = true; + if (this.wireframeLinewidth > 1) + data2.wireframeLinewidth = this.wireframeLinewidth; + if (this.wireframeLinecap !== "round") + data2.wireframeLinecap = this.wireframeLinecap; + if (this.wireframeLinejoin !== "round") + data2.wireframeLinejoin = this.wireframeLinejoin; + if (this.flatShading === true) + data2.flatShading = true; + if (this.visible === false) + data2.visible = false; + if (this.toneMapped === false) + data2.toneMapped = false; + if (this.fog === false) + data2.fog = false; + if (Object.keys(this.userData).length > 0) + data2.userData = this.userData; + function extractFromCache(cache) { + const values2 = []; + for (const key2 in cache) { + const data3 = cache[key2]; + delete data3.metadata; + values2.push(data3); + } + return values2; + } + if (isRootObject) { + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + if (textures.length > 0) + data2.textures = textures; + if (images.length > 0) + data2.images = images; + } + return data2; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + this.opacity = source.opacity; + this.transparent = source.transparent; + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + this.blendColor.copy(source.blendColor); + this.blendAlpha = source.blendAlpha; + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + if (srcPlanes !== null) { + const n = srcPlanes.length; + dstPlanes = new Array(n); + for (let i = 0;i !== n; ++i) { + dstPlanes[i] = srcPlanes[i].clone(); + } + } + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + this.shadowSide = source.shadowSide; + this.colorWrite = source.colorWrite; + this.precision = source.precision; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + this.dithering = source.dithering; + this.alphaTest = source.alphaTest; + this.alphaHash = source.alphaHash; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + this.forceSinglePass = source.forceSinglePass; + this.visible = source.visible; + this.toneMapped = source.toneMapped; + this.userData = JSON.parse(JSON.stringify(source.userData)); + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + onBuild() { + console.warn("Material: onBuild() has been removed."); + } +} + +class MeshBasicMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshBasicMaterial = true; + this.type = "MeshBasicMaterial"; + this.color = new Color(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } +} +var _tables = /* @__PURE__ */ _generateTables(); +function _generateTables() { + const buffer = new ArrayBuffer(4); + const floatView = new Float32Array(buffer); + const uint32View = new Uint32Array(buffer); + const baseTable = new Uint32Array(512); + const shiftTable = new Uint32Array(512); + for (let i = 0;i < 256; ++i) { + const e = i - 127; + if (e < -27) { + baseTable[i] = 0; + baseTable[i | 256] = 32768; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else if (e < -14) { + baseTable[i] = 1024 >> -e - 14; + baseTable[i | 256] = 1024 >> -e - 14 | 32768; + shiftTable[i] = -e - 1; + shiftTable[i | 256] = -e - 1; + } else if (e <= 15) { + baseTable[i] = e + 15 << 10; + baseTable[i | 256] = e + 15 << 10 | 32768; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } else if (e < 128) { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } + } + const mantissaTable = new Uint32Array(2048); + const exponentTable = new Uint32Array(64); + const offsetTable = new Uint32Array(64); + for (let i = 1;i < 1024; ++i) { + let m = i << 13; + let e = 0; + while ((m & 8388608) === 0) { + m <<= 1; + e -= 8388608; + } + m &= ~8388608; + e += 947912704; + mantissaTable[i] = m | e; + } + for (let i = 1024;i < 2048; ++i) { + mantissaTable[i] = 939524096 + (i - 1024 << 13); + } + for (let i = 1;i < 31; ++i) { + exponentTable[i] = i << 23; + } + exponentTable[31] = 1199570944; + exponentTable[32] = 2147483648; + for (let i = 33;i < 63; ++i) { + exponentTable[i] = 2147483648 + (i - 32 << 23); + } + exponentTable[63] = 3347054592; + for (let i = 1;i < 64; ++i) { + if (i !== 32) { + offsetTable[i] = 1024; + } + } + return { + floatView, + uint32View, + baseTable, + shiftTable, + mantissaTable, + exponentTable, + offsetTable + }; +} +function toHalfFloat(val2) { + if (Math.abs(val2) > 65504) + console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."); + val2 = clamp2(val2, -65504, 65504); + _tables.floatView[0] = val2; + const f = _tables.uint32View[0]; + const e = f >> 23 & 511; + return _tables.baseTable[e] + ((f & 8388607) >> _tables.shiftTable[e]); +} +function fromHalfFloat(val2) { + const m = val2 >> 10; + _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val2 & 1023)] + _tables.exponentTable[m]; + return _tables.floatView[0]; +} +var DataUtils = { + toHalfFloat, + fromHalfFloat +}; +var _vector$9 = /* @__PURE__ */ new Vector3; +var _vector2$1 = /* @__PURE__ */ new Vector2; +var _id$2 = 0; + +class BufferAttribute { + constructor(array, itemSize, normalized = false) { + if (Array.isArray(array)) { + throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); + } + this.isBufferAttribute = true; + Object.defineProperty(this, "id", { value: _id$2++ }); + this.name = ""; + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized; + this.usage = StaticDrawUsage; + this.updateRanges = []; + this.gpuType = FloatType; + this.version = 0; + } + onUploadCallback() { + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setUsage(value2) { + this.usage = value2; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.name = source.name; + this.array = new source.array.constructor(source.array); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + this.usage = source.usage; + this.gpuType = source.gpuType; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.itemSize; + index2 *= attribute.itemSize; + for (let i = 0, l = this.itemSize;i < l; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + copyArray(array) { + this.array.set(array); + return this; + } + applyMatrix3(m) { + if (this.itemSize === 2) { + for (let i = 0, l = this.count;i < l; i++) { + _vector2$1.fromBufferAttribute(this, i); + _vector2$1.applyMatrix3(m); + this.setXY(i, _vector2$1.x, _vector2$1.y); + } + } else if (this.itemSize === 3) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.applyMatrix3(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + } + return this; + } + applyMatrix4(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.applyMatrix4(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.applyNormalMatrix(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.transformDirection(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + set(value2, offset = 0) { + this.array.set(value2, offset); + return this; + } + getComponent(index2, component) { + let value2 = this.array[index2 * this.itemSize + component]; + if (this.normalized) + value2 = denormalize(value2, this.array); + return value2; + } + setComponent(index2, component, value2) { + if (this.normalized) + value2 = normalize2(value2, this.array); + this.array[index2 * this.itemSize + component] = value2; + return this; + } + getX(index2) { + let x = this.array[index2 * this.itemSize]; + if (this.normalized) + x = denormalize(x, this.array); + return x; + } + setX(index2, x) { + if (this.normalized) + x = normalize2(x, this.array); + this.array[index2 * this.itemSize] = x; + return this; + } + getY(index2) { + let y = this.array[index2 * this.itemSize + 1]; + if (this.normalized) + y = denormalize(y, this.array); + return y; + } + setY(index2, y) { + if (this.normalized) + y = normalize2(y, this.array); + this.array[index2 * this.itemSize + 1] = y; + return this; + } + getZ(index2) { + let z = this.array[index2 * this.itemSize + 2]; + if (this.normalized) + z = denormalize(z, this.array); + return z; + } + setZ(index2, z) { + if (this.normalized) + z = normalize2(z, this.array); + this.array[index2 * this.itemSize + 2] = z; + return this; + } + getW(index2) { + let w = this.array[index2 * this.itemSize + 3]; + if (this.normalized) + w = denormalize(w, this.array); + return w; + } + setW(index2, w) { + if (this.normalized) + w = normalize2(w, this.array); + this.array[index2 * this.itemSize + 3] = w; + return this; + } + setXY(index2, x, y) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + } + this.array[index2 + 0] = x; + this.array[index2 + 1] = y; + return this; + } + setXYZ(index2, x, y, z) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + } + this.array[index2 + 0] = x; + this.array[index2 + 1] = y; + this.array[index2 + 2] = z; + return this; + } + setXYZW(index2, x, y, z, w) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + w = normalize2(w, this.array); + } + this.array[index2 + 0] = x; + this.array[index2 + 1] = y; + this.array[index2 + 2] = z; + this.array[index2 + 3] = w; + return this; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + clone() { + return new this.constructor(this.array, this.itemSize).copy(this); + } + toJSON() { + const data2 = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from(this.array), + normalized: this.normalized + }; + if (this.name !== "") + data2.name = this.name; + if (this.usage !== StaticDrawUsage) + data2.usage = this.usage; + return data2; + } +} + +class Int8BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Int8Array(array), itemSize, normalized); + } +} + +class Uint8BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint8Array(array), itemSize, normalized); + } +} + +class Uint8ClampedBufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint8ClampedArray(array), itemSize, normalized); + } +} + +class Int16BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Int16Array(array), itemSize, normalized); + } +} + +class Uint16BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + } +} + +class Int32BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Int32Array(array), itemSize, normalized); + } +} + +class Uint32BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint32Array(array), itemSize, normalized); + } +} + +class Float16BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + this.isFloat16BufferAttribute = true; + } + getX(index2) { + let x = fromHalfFloat(this.array[index2 * this.itemSize]); + if (this.normalized) + x = denormalize(x, this.array); + return x; + } + setX(index2, x) { + if (this.normalized) + x = normalize2(x, this.array); + this.array[index2 * this.itemSize] = toHalfFloat(x); + return this; + } + getY(index2) { + let y = fromHalfFloat(this.array[index2 * this.itemSize + 1]); + if (this.normalized) + y = denormalize(y, this.array); + return y; + } + setY(index2, y) { + if (this.normalized) + y = normalize2(y, this.array); + this.array[index2 * this.itemSize + 1] = toHalfFloat(y); + return this; + } + getZ(index2) { + let z = fromHalfFloat(this.array[index2 * this.itemSize + 2]); + if (this.normalized) + z = denormalize(z, this.array); + return z; + } + setZ(index2, z) { + if (this.normalized) + z = normalize2(z, this.array); + this.array[index2 * this.itemSize + 2] = toHalfFloat(z); + return this; + } + getW(index2) { + let w = fromHalfFloat(this.array[index2 * this.itemSize + 3]); + if (this.normalized) + w = denormalize(w, this.array); + return w; + } + setW(index2, w) { + if (this.normalized) + w = normalize2(w, this.array); + this.array[index2 * this.itemSize + 3] = toHalfFloat(w); + return this; + } + setXY(index2, x, y) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + } + this.array[index2 + 0] = toHalfFloat(x); + this.array[index2 + 1] = toHalfFloat(y); + return this; + } + setXYZ(index2, x, y, z) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + } + this.array[index2 + 0] = toHalfFloat(x); + this.array[index2 + 1] = toHalfFloat(y); + this.array[index2 + 2] = toHalfFloat(z); + return this; + } + setXYZW(index2, x, y, z, w) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + w = normalize2(w, this.array); + } + this.array[index2 + 0] = toHalfFloat(x); + this.array[index2 + 1] = toHalfFloat(y); + this.array[index2 + 2] = toHalfFloat(z); + this.array[index2 + 3] = toHalfFloat(w); + return this; + } +} + +class Float32BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Float32Array(array), itemSize, normalized); + } +} +var _id$1 = 0; +var _m1 = /* @__PURE__ */ new Matrix4; +var _obj = /* @__PURE__ */ new Object3D; +var _offset = /* @__PURE__ */ new Vector3; +var _box$2 = /* @__PURE__ */ new Box3; +var _boxMorphTargets = /* @__PURE__ */ new Box3; +var _vector$8 = /* @__PURE__ */ new Vector3; + +class BufferGeometry extends EventDispatcher { + constructor() { + super(); + this.isBufferGeometry = true; + Object.defineProperty(this, "id", { value: _id$1++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "BufferGeometry"; + this.index = null; + this.indirect = null; + this.attributes = {}; + this.morphAttributes = {}; + this.morphTargetsRelative = false; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + this.drawRange = { start: 0, count: Infinity }; + this.userData = {}; + } + getIndex() { + return this.index; + } + setIndex(index2) { + if (Array.isArray(index2)) { + this.index = new ((arrayNeedsUint32(index2)) ? Uint32BufferAttribute : Uint16BufferAttribute)(index2, 1); + } else { + this.index = index2; + } + return this; + } + setIndirect(indirect) { + this.indirect = indirect; + return this; + } + getIndirect() { + return this.indirect; + } + getAttribute(name2) { + return this.attributes[name2]; + } + setAttribute(name2, attribute) { + this.attributes[name2] = attribute; + return this; + } + deleteAttribute(name2) { + delete this.attributes[name2]; + return this; + } + hasAttribute(name2) { + return this.attributes[name2] !== undefined; + } + addGroup(start, count, materialIndex = 0) { + this.groups.push({ + start, + count, + materialIndex + }); + } + clearGroups() { + this.groups = []; + } + setDrawRange(start, count) { + this.drawRange.start = start; + this.drawRange.count = count; + } + applyMatrix4(matrix) { + const position2 = this.attributes.position; + if (position2 !== undefined) { + position2.applyMatrix4(matrix); + position2.needsUpdate = true; + } + const normal = this.attributes.normal; + if (normal !== undefined) { + const normalMatrix = new Matrix3().getNormalMatrix(matrix); + normal.applyNormalMatrix(normalMatrix); + normal.needsUpdate = true; + } + const tangent = this.attributes.tangent; + if (tangent !== undefined) { + tangent.transformDirection(matrix); + tangent.needsUpdate = true; + } + if (this.boundingBox !== null) { + this.computeBoundingBox(); + } + if (this.boundingSphere !== null) { + this.computeBoundingSphere(); + } + return this; + } + applyQuaternion(q) { + _m1.makeRotationFromQuaternion(q); + this.applyMatrix4(_m1); + return this; + } + rotateX(angle) { + _m1.makeRotationX(angle); + this.applyMatrix4(_m1); + return this; + } + rotateY(angle) { + _m1.makeRotationY(angle); + this.applyMatrix4(_m1); + return this; + } + rotateZ(angle) { + _m1.makeRotationZ(angle); + this.applyMatrix4(_m1); + return this; + } + translate(x, y, z) { + _m1.makeTranslation(x, y, z); + this.applyMatrix4(_m1); + return this; + } + scale(x, y, z) { + _m1.makeScale(x, y, z); + this.applyMatrix4(_m1); + return this; + } + lookAt(vector) { + _obj.lookAt(vector); + _obj.updateMatrix(); + this.applyMatrix4(_obj.matrix); + return this; + } + center() { + this.computeBoundingBox(); + this.boundingBox.getCenter(_offset).negate(); + this.translate(_offset.x, _offset.y, _offset.z); + return this; + } + setFromPoints(points) { + const positionAttribute = this.getAttribute("position"); + if (positionAttribute === undefined) { + const position2 = []; + for (let i = 0, l = points.length;i < l; i++) { + const point = points[i]; + position2.push(point.x, point.y, point.z || 0); + } + this.setAttribute("position", new Float32BufferAttribute(position2, 3)); + } else { + const l = Math.min(points.length, positionAttribute.count); + for (let i = 0;i < l; i++) { + const point = points[i]; + positionAttribute.setXYZ(i, point.x, point.y, point.z || 0); + } + if (points.length > positionAttribute.count) { + console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."); + } + positionAttribute.needsUpdate = true; + } + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box3; + } + const position2 = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position2 && position2.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this); + this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(Infinity, Infinity, Infinity)); + return; + } + if (position2 !== undefined) { + this.boundingBox.setFromBufferAttribute(position2); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _box$2.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$8.addVectors(this.boundingBox.min, _box$2.min); + this.boundingBox.expandByPoint(_vector$8); + _vector$8.addVectors(this.boundingBox.max, _box$2.max); + this.boundingBox.expandByPoint(_vector$8); + } else { + this.boundingBox.expandByPoint(_box$2.min); + this.boundingBox.expandByPoint(_box$2.max); + } + } + } + } else { + this.boundingBox.makeEmpty(); + } + if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) { + console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere; + } + const position2 = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position2 && position2.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this); + this.boundingSphere.set(new Vector3, Infinity); + return; + } + if (position2) { + const center = this.boundingSphere.center; + _box$2.setFromBufferAttribute(position2); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _boxMorphTargets.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$8.addVectors(_box$2.min, _boxMorphTargets.min); + _box$2.expandByPoint(_vector$8); + _vector$8.addVectors(_box$2.max, _boxMorphTargets.max); + _box$2.expandByPoint(_vector$8); + } else { + _box$2.expandByPoint(_boxMorphTargets.min); + _box$2.expandByPoint(_boxMorphTargets.max); + } + } + } + _box$2.getCenter(center); + let maxRadiusSq = 0; + for (let i = 0, il = position2.count;i < il; i++) { + _vector$8.fromBufferAttribute(position2, i); + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); + } + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + const morphTargetsRelative = this.morphTargetsRelative; + for (let j = 0, jl = morphAttribute.count;j < jl; j++) { + _vector$8.fromBufferAttribute(morphAttribute, j); + if (morphTargetsRelative) { + _offset.fromBufferAttribute(position2, j); + _vector$8.add(_offset); + } + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); + } + } + } + this.boundingSphere.radius = Math.sqrt(maxRadiusSq); + if (isNaN(this.boundingSphere.radius)) { + console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); + } + } + } + computeTangents() { + const index2 = this.index; + const attributes = this.attributes; + if (index2 === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) { + console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); + return; + } + const positionAttribute = attributes.position; + const normalAttribute = attributes.normal; + const uvAttribute = attributes.uv; + if (this.hasAttribute("tangent") === false) { + this.setAttribute("tangent", new BufferAttribute(new Float32Array(4 * positionAttribute.count), 4)); + } + const tangentAttribute = this.getAttribute("tangent"); + const tan1 = [], tan2 = []; + for (let i = 0;i < positionAttribute.count; i++) { + tan1[i] = new Vector3; + tan2[i] = new Vector3; + } + const vA = new Vector3, vB = new Vector3, vC = new Vector3, uvA = new Vector2, uvB = new Vector2, uvC = new Vector2, sdir = new Vector3, tdir = new Vector3; + function handleTriangle(a, b, c) { + vA.fromBufferAttribute(positionAttribute, a); + vB.fromBufferAttribute(positionAttribute, b); + vC.fromBufferAttribute(positionAttribute, c); + uvA.fromBufferAttribute(uvAttribute, a); + uvB.fromBufferAttribute(uvAttribute, b); + uvC.fromBufferAttribute(uvAttribute, c); + vB.sub(vA); + vC.sub(vA); + uvB.sub(uvA); + uvC.sub(uvA); + const r = 1 / (uvB.x * uvC.y - uvC.x * uvB.y); + if (!isFinite(r)) + return; + sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r); + tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r); + tan1[a].add(sdir); + tan1[b].add(sdir); + tan1[c].add(sdir); + tan2[a].add(tdir); + tan2[b].add(tdir); + tan2[c].add(tdir); + } + let groups = this.groups; + if (groups.length === 0) { + groups = [{ + start: 0, + count: index2.count + }]; + } + for (let i = 0, il = groups.length;i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j = start, jl = start + count;j < jl; j += 3) { + handleTriangle(index2.getX(j + 0), index2.getX(j + 1), index2.getX(j + 2)); + } + } + const tmp = new Vector3, tmp2 = new Vector3; + const n = new Vector3, n2 = new Vector3; + function handleVertex(v) { + n.fromBufferAttribute(normalAttribute, v); + n2.copy(n); + const t = tan1[v]; + tmp.copy(t); + tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); + tmp2.crossVectors(n2, t); + const test = tmp2.dot(tan2[v]); + const w = test < 0 ? -1 : 1; + tangentAttribute.setXYZW(v, tmp.x, tmp.y, tmp.z, w); + } + for (let i = 0, il = groups.length;i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j = start, jl = start + count;j < jl; j += 3) { + handleVertex(index2.getX(j + 0)); + handleVertex(index2.getX(j + 1)); + handleVertex(index2.getX(j + 2)); + } + } + } + computeVertexNormals() { + const index2 = this.index; + const positionAttribute = this.getAttribute("position"); + if (positionAttribute !== undefined) { + let normalAttribute = this.getAttribute("normal"); + if (normalAttribute === undefined) { + normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3); + this.setAttribute("normal", normalAttribute); + } else { + for (let i = 0, il = normalAttribute.count;i < il; i++) { + normalAttribute.setXYZ(i, 0, 0, 0); + } + } + const pA = new Vector3, pB = new Vector3, pC = new Vector3; + const nA = new Vector3, nB = new Vector3, nC = new Vector3; + const cb = new Vector3, ab = new Vector3; + if (index2) { + for (let i = 0, il = index2.count;i < il; i += 3) { + const vA = index2.getX(i + 0); + const vB = index2.getX(i + 1); + const vC = index2.getX(i + 2); + pA.fromBufferAttribute(positionAttribute, vA); + pB.fromBufferAttribute(positionAttribute, vB); + pC.fromBufferAttribute(positionAttribute, vC); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + nA.fromBufferAttribute(normalAttribute, vA); + nB.fromBufferAttribute(normalAttribute, vB); + nC.fromBufferAttribute(normalAttribute, vC); + nA.add(cb); + nB.add(cb); + nC.add(cb); + normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z); + normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z); + normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z); + } + } else { + for (let i = 0, il = positionAttribute.count;i < il; i += 3) { + pA.fromBufferAttribute(positionAttribute, i + 0); + pB.fromBufferAttribute(positionAttribute, i + 1); + pC.fromBufferAttribute(positionAttribute, i + 2); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z); + } + } + this.normalizeNormals(); + normalAttribute.needsUpdate = true; + } + } + normalizeNormals() { + const normals = this.attributes.normal; + for (let i = 0, il = normals.count;i < il; i++) { + _vector$8.fromBufferAttribute(normals, i); + _vector$8.normalize(); + normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z); + } + } + toNonIndexed() { + function convertBufferAttribute(attribute, indices2) { + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + const array2 = new array.constructor(indices2.length * itemSize); + let index2 = 0, index22 = 0; + for (let i = 0, l = indices2.length;i < l; i++) { + if (attribute.isInterleavedBufferAttribute) { + index2 = indices2[i] * attribute.data.stride + attribute.offset; + } else { + index2 = indices2[i] * itemSize; + } + for (let j = 0;j < itemSize; j++) { + array2[index22++] = array[index2++]; + } + } + return new BufferAttribute(array2, itemSize, normalized); + } + if (this.index === null) { + console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."); + return this; + } + const geometry2 = new BufferGeometry; + const indices = this.index.array; + const attributes = this.attributes; + for (const name2 in attributes) { + const attribute = attributes[name2]; + const newAttribute = convertBufferAttribute(attribute, indices); + geometry2.setAttribute(name2, newAttribute); + } + const morphAttributes = this.morphAttributes; + for (const name2 in morphAttributes) { + const morphArray = []; + const morphAttribute = morphAttributes[name2]; + for (let i = 0, il = morphAttribute.length;i < il; i++) { + const attribute = morphAttribute[i]; + const newAttribute = convertBufferAttribute(attribute, indices); + morphArray.push(newAttribute); + } + geometry2.morphAttributes[name2] = morphArray; + } + geometry2.morphTargetsRelative = this.morphTargetsRelative; + const groups = this.groups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + geometry2.addGroup(group.start, group.count, group.materialIndex); + } + return geometry2; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "BufferGeometry", + generator: "BufferGeometry.toJSON" + } + }; + data2.uuid = this.uuid; + data2.type = this.type; + if (this.name !== "") + data2.name = this.name; + if (Object.keys(this.userData).length > 0) + data2.userData = this.userData; + if (this.parameters !== undefined) { + const parameters = this.parameters; + for (const key2 in parameters) { + if (parameters[key2] !== undefined) + data2[key2] = parameters[key2]; + } + return data2; + } + data2.data = { attributes: {} }; + const index2 = this.index; + if (index2 !== null) { + data2.data.index = { + type: index2.array.constructor.name, + array: Array.prototype.slice.call(index2.array) + }; + } + const attributes = this.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + data2.data.attributes[key2] = attribute.toJSON(data2.data); + } + const morphAttributes = {}; + let hasMorphAttributes = false; + for (const key2 in this.morphAttributes) { + const attributeArray = this.morphAttributes[key2]; + const array = []; + for (let i = 0, il = attributeArray.length;i < il; i++) { + const attribute = attributeArray[i]; + array.push(attribute.toJSON(data2.data)); + } + if (array.length > 0) { + morphAttributes[key2] = array; + hasMorphAttributes = true; + } + } + if (hasMorphAttributes) { + data2.data.morphAttributes = morphAttributes; + data2.data.morphTargetsRelative = this.morphTargetsRelative; + } + const groups = this.groups; + if (groups.length > 0) { + data2.data.groups = JSON.parse(JSON.stringify(groups)); + } + const boundingSphere = this.boundingSphere; + if (boundingSphere !== null) { + data2.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; + } + return data2; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + const data2 = {}; + this.name = source.name; + const index2 = source.index; + if (index2 !== null) { + this.setIndex(index2.clone(data2)); + } + const attributes = source.attributes; + for (const name2 in attributes) { + const attribute = attributes[name2]; + this.setAttribute(name2, attribute.clone(data2)); + } + const morphAttributes = source.morphAttributes; + for (const name2 in morphAttributes) { + const array = []; + const morphAttribute = morphAttributes[name2]; + for (let i = 0, l = morphAttribute.length;i < l; i++) { + array.push(morphAttribute[i].clone(data2)); + } + this.morphAttributes[name2] = array; + } + this.morphTargetsRelative = source.morphTargetsRelative; + const groups = source.groups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + this.addGroup(group.start, group.count, group.materialIndex); + } + const boundingBox = source.boundingBox; + if (boundingBox !== null) { + this.boundingBox = boundingBox.clone(); + } + const boundingSphere = source.boundingSphere; + if (boundingSphere !== null) { + this.boundingSphere = boundingSphere.clone(); + } + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + this.userData = source.userData; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } +} +var _inverseMatrix$3 = /* @__PURE__ */ new Matrix4; +var _ray$3 = /* @__PURE__ */ new Ray; +var _sphere$6 = /* @__PURE__ */ new Sphere; +var _sphereHitAt = /* @__PURE__ */ new Vector3; +var _vA$1 = /* @__PURE__ */ new Vector3; +var _vB$1 = /* @__PURE__ */ new Vector3; +var _vC$1 = /* @__PURE__ */ new Vector3; +var _tempA = /* @__PURE__ */ new Vector3; +var _morphA = /* @__PURE__ */ new Vector3; +var _intersectionPoint = /* @__PURE__ */ new Vector3; +var _intersectionPointWorld = /* @__PURE__ */ new Vector3; + +class Mesh extends Object3D { + constructor(geometry = new BufferGeometry, material = new MeshBasicMaterial) { + super(); + this.isMesh = true; + this.type = "Mesh"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.morphTargetInfluences !== undefined) { + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + } + if (source.morphTargetDictionary !== undefined) { + this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary); + } + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } + getVertexPosition(index2, target) { + const geometry = this.geometry; + const position2 = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + target.fromBufferAttribute(position2, index2); + const morphInfluences = this.morphTargetInfluences; + if (morphPosition && morphInfluences) { + _morphA.set(0, 0, 0); + for (let i = 0, il = morphPosition.length;i < il; i++) { + const influence = morphInfluences[i]; + const morphAttribute = morphPosition[i]; + if (influence === 0) + continue; + _tempA.fromBufferAttribute(morphAttribute, index2); + if (morphTargetsRelative) { + _morphA.addScaledVector(_tempA, influence); + } else { + _morphA.addScaledVector(_tempA.sub(target), influence); + } + } + target.add(_morphA); + } + return target; + } + raycast(raycaster, intersects) { + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === undefined) + return; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$6.copy(geometry.boundingSphere); + _sphere$6.applyMatrix4(matrixWorld); + _ray$3.copy(raycaster.ray).recast(raycaster.near); + if (_sphere$6.containsPoint(_ray$3.origin) === false) { + if (_ray$3.intersectSphere(_sphere$6, _sphereHitAt) === null) + return; + if (_ray$3.origin.distanceToSquared(_sphereHitAt) > (raycaster.far - raycaster.near) ** 2) + return; + } + _inverseMatrix$3.copy(matrixWorld).invert(); + _ray$3.copy(raycaster.ray).applyMatrix4(_inverseMatrix$3); + if (geometry.boundingBox !== null) { + if (_ray$3.intersectsBox(geometry.boundingBox) === false) + return; + } + this._computeIntersections(raycaster, intersects, _ray$3); + } + _computeIntersections(raycaster, intersects, rayLocalSpace) { + let intersection; + const geometry = this.geometry; + const material = this.material; + const index2 = geometry.index; + const position2 = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv1 = geometry.attributes.uv1; + const normal = geometry.attributes.normal; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + if (index2 !== null) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length;i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(index2.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j = start, jl = end;j < jl; j += 3) { + const a = index2.getX(j); + const b = index2.getX(j + 1); + const c = index2.getX(j + 2); + intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(j / 3); + intersection.face.materialIndex = group.materialIndex; + intersects.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i += 3) { + const a = index2.getX(i); + const b = index2.getX(i + 1); + const c = index2.getX(i + 2); + intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects.push(intersection); + } + } + } + } else if (position2 !== undefined) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length;i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(position2.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j = start, jl = end;j < jl; j += 3) { + const a = j; + const b = j + 1; + const c = j + 2; + intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(j / 3); + intersection.face.materialIndex = group.materialIndex; + intersects.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(position2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i += 3) { + const a = i; + const b = i + 1; + const c = i + 2; + intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects.push(intersection); + } + } + } + } + } +} +function checkIntersection$1(object, material, raycaster, ray, pA, pB, pC, point) { + let intersect; + if (material.side === BackSide) { + intersect = ray.intersectTriangle(pC, pB, pA, true, point); + } else { + intersect = ray.intersectTriangle(pA, pB, pC, material.side === FrontSide, point); + } + if (intersect === null) + return null; + _intersectionPointWorld.copy(point); + _intersectionPointWorld.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld); + if (distance < raycaster.near || distance > raycaster.far) + return null; + return { + distance, + point: _intersectionPointWorld.clone(), + object + }; +} +function checkGeometryIntersection(object, material, raycaster, ray, uv, uv1, normal, a, b, c) { + object.getVertexPosition(a, _vA$1); + object.getVertexPosition(b, _vB$1); + object.getVertexPosition(c, _vC$1); + const intersection = checkIntersection$1(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint); + if (intersection) { + const barycoord = new Vector3; + Triangle.getBarycoord(_intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord); + if (uv) { + intersection.uv = Triangle.getInterpolatedAttribute(uv, a, b, c, barycoord, new Vector2); + } + if (uv1) { + intersection.uv1 = Triangle.getInterpolatedAttribute(uv1, a, b, c, barycoord, new Vector2); + } + if (normal) { + intersection.normal = Triangle.getInterpolatedAttribute(normal, a, b, c, barycoord, new Vector3); + if (intersection.normal.dot(ray.direction) > 0) { + intersection.normal.multiplyScalar(-1); + } + } + const face = { + a, + b, + c, + normal: new Vector3, + materialIndex: 0 + }; + Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal); + intersection.face = face; + intersection.barycoord = barycoord; + } + return intersection; +} + +class BoxGeometry extends BufferGeometry { + constructor(width2 = 1, height2 = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) { + super(); + this.type = "BoxGeometry"; + this.parameters = { + width: width2, + height: height2, + depth, + widthSegments, + heightSegments, + depthSegments + }; + const scope = this; + widthSegments = Math.floor(widthSegments); + heightSegments = Math.floor(heightSegments); + depthSegments = Math.floor(depthSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let numberOfVertices = 0; + let groupStart = 0; + buildPlane("z", "y", "x", -1, -1, depth, height2, width2, depthSegments, heightSegments, 0); + buildPlane("z", "y", "x", 1, -1, depth, height2, -width2, depthSegments, heightSegments, 1); + buildPlane("x", "z", "y", 1, 1, width2, depth, height2, widthSegments, depthSegments, 2); + buildPlane("x", "z", "y", 1, -1, width2, depth, -height2, widthSegments, depthSegments, 3); + buildPlane("x", "y", "z", 1, -1, width2, height2, depth, widthSegments, heightSegments, 4); + buildPlane("x", "y", "z", -1, -1, width2, height2, -depth, widthSegments, heightSegments, 5); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function buildPlane(u, v, w, udir, vdir, width3, height3, depth2, gridX, gridY, materialIndex) { + const segmentWidth = width3 / gridX; + const segmentHeight = height3 / gridY; + const widthHalf = width3 / 2; + const heightHalf = height3 / 2; + const depthHalf = depth2 / 2; + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + let vertexCounter = 0; + let groupCount = 0; + const vector = new Vector3; + for (let iy = 0;iy < gridY1; iy++) { + const y = iy * segmentHeight - heightHalf; + for (let ix = 0;ix < gridX1; ix++) { + const x = ix * segmentWidth - widthHalf; + vector[u] = x * udir; + vector[v] = y * vdir; + vector[w] = depthHalf; + vertices.push(vector.x, vector.y, vector.z); + vector[u] = 0; + vector[v] = 0; + vector[w] = depth2 > 0 ? 1 : -1; + normals.push(vector.x, vector.y, vector.z); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + vertexCounter += 1; + } + } + for (let iy = 0;iy < gridY; iy++) { + for (let ix = 0;ix < gridX; ix++) { + const a = numberOfVertices + ix + gridX1 * iy; + const b = numberOfVertices + ix + gridX1 * (iy + 1); + const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1); + const d = numberOfVertices + (ix + 1) + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + groupCount += 6; + } + } + scope.addGroup(groupStart, groupCount, materialIndex); + groupStart += groupCount; + numberOfVertices += vertexCounter; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new BoxGeometry(data2.width, data2.height, data2.depth, data2.widthSegments, data2.heightSegments, data2.depthSegments); + } +} +function cloneUniforms(src) { + const dst = {}; + for (const u in src) { + dst[u] = {}; + for (const p in src[u]) { + const property2 = src[u][p]; + if (property2 && (property2.isColor || property2.isMatrix3 || property2.isMatrix4 || property2.isVector2 || property2.isVector3 || property2.isVector4 || property2.isTexture || property2.isQuaternion)) { + if (property2.isRenderTargetTexture) { + console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."); + dst[u][p] = null; + } else { + dst[u][p] = property2.clone(); + } + } else if (Array.isArray(property2)) { + dst[u][p] = property2.slice(); + } else { + dst[u][p] = property2; + } + } + } + return dst; +} +function mergeUniforms(uniforms) { + const merged = {}; + for (let u = 0;u < uniforms.length; u++) { + const tmp = cloneUniforms(uniforms[u]); + for (const p in tmp) { + merged[p] = tmp[p]; + } + } + return merged; +} +function cloneUniformsGroups(src) { + const dst = []; + for (let u = 0;u < src.length; u++) { + dst.push(src[u].clone()); + } + return dst; +} +function getUnlitUniformColorSpace(renderer2) { + const currentRenderTarget = renderer2.getRenderTarget(); + if (currentRenderTarget === null) { + return renderer2.outputColorSpace; + } + if (currentRenderTarget.isXRRenderTarget === true) { + return currentRenderTarget.texture.colorSpace; + } + return ColorManagement.workingColorSpace; +} +var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; +var default_vertex = `void main() { + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); +}`; +var default_fragment = `void main() { + gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); +}`; + +class ShaderMaterial extends Material { + constructor(parameters) { + super(); + this.isShaderMaterial = true; + this.type = "ShaderMaterial"; + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; + this.linewidth = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.fog = false; + this.lights = false; + this.clipping = false; + this.forceSinglePass = true; + this.extensions = { + clipCullDistance: false, + multiDraw: false + }; + this.defaultAttributeValues = { + color: [1, 1, 1], + uv: [0, 0], + uv1: [0, 0] + }; + this.index0AttributeName = undefined; + this.uniformsNeedUpdate = false; + this.glslVersion = null; + if (parameters !== undefined) { + this.setValues(parameters); + } + } + copy(source) { + super.copy(source); + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + this.uniforms = cloneUniforms(source.uniforms); + this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups); + this.defines = Object.assign({}, source.defines); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + this.extensions = Object.assign({}, source.extensions); + this.glslVersion = source.glslVersion; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.glslVersion = this.glslVersion; + data2.uniforms = {}; + for (const name2 in this.uniforms) { + const uniform = this.uniforms[name2]; + const value2 = uniform.value; + if (value2 && value2.isTexture) { + data2.uniforms[name2] = { + type: "t", + value: value2.toJSON(meta).uuid + }; + } else if (value2 && value2.isColor) { + data2.uniforms[name2] = { + type: "c", + value: value2.getHex() + }; + } else if (value2 && value2.isVector2) { + data2.uniforms[name2] = { + type: "v2", + value: value2.toArray() + }; + } else if (value2 && value2.isVector3) { + data2.uniforms[name2] = { + type: "v3", + value: value2.toArray() + }; + } else if (value2 && value2.isVector4) { + data2.uniforms[name2] = { + type: "v4", + value: value2.toArray() + }; + } else if (value2 && value2.isMatrix3) { + data2.uniforms[name2] = { + type: "m3", + value: value2.toArray() + }; + } else if (value2 && value2.isMatrix4) { + data2.uniforms[name2] = { + type: "m4", + value: value2.toArray() + }; + } else { + data2.uniforms[name2] = { + value: value2 + }; + } + } + if (Object.keys(this.defines).length > 0) + data2.defines = this.defines; + data2.vertexShader = this.vertexShader; + data2.fragmentShader = this.fragmentShader; + data2.lights = this.lights; + data2.clipping = this.clipping; + const extensions = {}; + for (const key2 in this.extensions) { + if (this.extensions[key2] === true) + extensions[key2] = true; + } + if (Object.keys(extensions).length > 0) + data2.extensions = extensions; + return data2; + } +} + +class Camera extends Object3D { + constructor() { + super(); + this.isCamera = true; + this.type = "Camera"; + this.matrixWorldInverse = new Matrix4; + this.projectionMatrix = new Matrix4; + this.projectionMatrixInverse = new Matrix4; + this.coordinateSystem = WebGLCoordinateSystem; + } + copy(source, recursive) { + super.copy(source, recursive); + this.matrixWorldInverse.copy(source.matrixWorldInverse); + this.projectionMatrix.copy(source.projectionMatrix); + this.projectionMatrixInverse.copy(source.projectionMatrixInverse); + this.coordinateSystem = source.coordinateSystem; + return this; + } + getWorldDirection(target) { + return super.getWorldDirection(target).negate(); + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + updateWorldMatrix(updateParents, updateChildren) { + super.updateWorldMatrix(updateParents, updateChildren); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + clone() { + return new this.constructor().copy(this); + } +} +var _v3$1 = /* @__PURE__ */ new Vector3; +var _minTarget = /* @__PURE__ */ new Vector2; +var _maxTarget = /* @__PURE__ */ new Vector2; + +class PerspectiveCamera extends Camera { + constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) { + super(); + this.isPerspectiveCamera = true; + this.type = "PerspectiveCamera"; + this.fov = fov; + this.zoom = 1; + this.near = near; + this.far = far; + this.focus = 10; + this.aspect = aspect; + this.view = null; + this.filmGauge = 35; + this.filmOffset = 0; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.fov = source.fov; + this.zoom = source.zoom; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign({}, source.view); + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + return this; + } + setFocalLength(focalLength) { + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope); + this.updateProjectionMatrix(); + } + getFocalLength() { + const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov); + return 0.5 * this.getFilmHeight() / vExtentSlope; + } + getEffectiveFOV() { + return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom); + } + getFilmWidth() { + return this.filmGauge * Math.min(this.aspect, 1); + } + getFilmHeight() { + return this.filmGauge / Math.max(this.aspect, 1); + } + getViewBounds(distance, minTarget, maxTarget) { + _v3$1.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse); + minTarget.set(_v3$1.x, _v3$1.y).multiplyScalar(-distance / _v3$1.z); + _v3$1.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse); + maxTarget.set(_v3$1.x, _v3$1.y).multiplyScalar(-distance / _v3$1.z); + } + getViewSize(distance, target) { + this.getViewBounds(distance, _minTarget, _maxTarget); + return target.subVectors(_maxTarget, _minTarget); + } + setViewOffset(fullWidth, fullHeight, x, y, width2, height2) { + this.aspect = fullWidth / fullHeight; + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width2; + this.view.height = height2; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const near = this.near; + let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom; + let height2 = 2 * top; + let width2 = this.aspect * height2; + let left = -0.5 * width2; + const view = this.view; + if (this.view !== null && this.view.enabled) { + const { fullWidth, fullHeight } = view; + left += view.offsetX * width2 / fullWidth; + top -= view.offsetY * height2 / fullHeight; + width2 *= view.width / fullWidth; + height2 *= view.height / fullHeight; + } + const skew = this.filmOffset; + if (skew !== 0) + left += near * skew / this.getFilmWidth(); + this.projectionMatrix.makePerspective(left, left + width2, top, top - height2, near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.fov = this.fov; + data2.object.zoom = this.zoom; + data2.object.near = this.near; + data2.object.far = this.far; + data2.object.focus = this.focus; + data2.object.aspect = this.aspect; + if (this.view !== null) + data2.object.view = Object.assign({}, this.view); + data2.object.filmGauge = this.filmGauge; + data2.object.filmOffset = this.filmOffset; + return data2; + } +} +var fov = -90; +var aspect = 1; + +class CubeCamera extends Object3D { + constructor(near, far, renderTarget) { + super(); + this.type = "CubeCamera"; + this.renderTarget = renderTarget; + this.coordinateSystem = null; + this.activeMipmapLevel = 0; + const cameraPX = new PerspectiveCamera(fov, aspect, near, far); + cameraPX.layers = this.layers; + this.add(cameraPX); + const cameraNX = new PerspectiveCamera(fov, aspect, near, far); + cameraNX.layers = this.layers; + this.add(cameraNX); + const cameraPY = new PerspectiveCamera(fov, aspect, near, far); + cameraPY.layers = this.layers; + this.add(cameraPY); + const cameraNY = new PerspectiveCamera(fov, aspect, near, far); + cameraNY.layers = this.layers; + this.add(cameraNY); + const cameraPZ = new PerspectiveCamera(fov, aspect, near, far); + cameraPZ.layers = this.layers; + this.add(cameraPZ); + const cameraNZ = new PerspectiveCamera(fov, aspect, near, far); + cameraNZ.layers = this.layers; + this.add(cameraNZ); + } + updateCoordinateSystem() { + const coordinateSystem = this.coordinateSystem; + const cameras = this.children.concat(); + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = cameras; + for (const camera of cameras) + this.remove(camera); + if (coordinateSystem === WebGLCoordinateSystem) { + cameraPX.up.set(0, 1, 0); + cameraPX.lookAt(1, 0, 0); + cameraNX.up.set(0, 1, 0); + cameraNX.lookAt(-1, 0, 0); + cameraPY.up.set(0, 0, -1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, 1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, 1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, 1, 0); + cameraNZ.lookAt(0, 0, -1); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + cameraPX.up.set(0, -1, 0); + cameraPX.lookAt(-1, 0, 0); + cameraNX.up.set(0, -1, 0); + cameraNX.lookAt(1, 0, 0); + cameraPY.up.set(0, 0, 1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, -1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, -1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, -1, 0); + cameraNZ.lookAt(0, 0, -1); + } else { + throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + coordinateSystem); + } + for (const camera of cameras) { + this.add(camera); + camera.updateMatrixWorld(); + } + } + update(renderer2, scene) { + if (this.parent === null) + this.updateMatrixWorld(); + const { renderTarget, activeMipmapLevel } = this; + if (this.coordinateSystem !== renderer2.coordinateSystem) { + this.coordinateSystem = renderer2.coordinateSystem; + this.updateCoordinateSystem(); + } + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children; + const currentRenderTarget = renderer2.getRenderTarget(); + const currentActiveCubeFace = renderer2.getActiveCubeFace(); + const currentActiveMipmapLevel = renderer2.getActiveMipmapLevel(); + const currentXrEnabled = renderer2.xr.enabled; + renderer2.xr.enabled = false; + const generateMipmaps = renderTarget.texture.generateMipmaps; + renderTarget.texture.generateMipmaps = false; + renderer2.setRenderTarget(renderTarget, 0, activeMipmapLevel); + renderer2.render(scene, cameraPX); + renderer2.setRenderTarget(renderTarget, 1, activeMipmapLevel); + renderer2.render(scene, cameraNX); + renderer2.setRenderTarget(renderTarget, 2, activeMipmapLevel); + renderer2.render(scene, cameraPY); + renderer2.setRenderTarget(renderTarget, 3, activeMipmapLevel); + renderer2.render(scene, cameraNY); + renderer2.setRenderTarget(renderTarget, 4, activeMipmapLevel); + renderer2.render(scene, cameraPZ); + renderTarget.texture.generateMipmaps = generateMipmaps; + renderer2.setRenderTarget(renderTarget, 5, activeMipmapLevel); + renderer2.render(scene, cameraNZ); + renderer2.setRenderTarget(currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel); + renderer2.xr.enabled = currentXrEnabled; + renderTarget.texture.needsPMREMUpdate = true; + } +} + +class CubeTexture extends Texture { + constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace) { + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; + super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCubeTexture = true; + this.flipY = false; + } + get images() { + return this.image; + } + set images(value2) { + this.image = value2; + } +} + +class WebGLCubeRenderTarget extends WebGLRenderTarget { + constructor(size = 1, options = {}) { + super(size, size, options); + this.isWebGLCubeRenderTarget = true; + const image = { width: size, height: size, depth: 1 }; + const images = [image, image, image, image, image, image]; + this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + this.texture.isRenderTargetTexture = true; + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + } + fromEquirectangularTexture(renderer2, texture) { + this.texture.type = texture.type; + this.texture.colorSpace = texture.colorSpace; + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + const shader = { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `, + fragmentShader: ` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + }; + const geometry = new BoxGeometry(5, 5, 5); + const material = new ShaderMaterial({ + name: "CubemapFromEquirect", + uniforms: cloneUniforms(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + blending: NoBlending + }); + material.uniforms.tEquirect.value = texture; + const mesh = new Mesh(geometry, material); + const currentMinFilter = texture.minFilter; + if (texture.minFilter === LinearMipmapLinearFilter) + texture.minFilter = LinearFilter; + const camera = new CubeCamera(1, 10, this); + camera.update(renderer2, mesh); + texture.minFilter = currentMinFilter; + mesh.geometry.dispose(); + mesh.material.dispose(); + return this; + } + clear(renderer2, color, depth, stencil) { + const currentRenderTarget = renderer2.getRenderTarget(); + for (let i = 0;i < 6; i++) { + renderer2.setRenderTarget(this, i); + renderer2.clear(color, depth, stencil); + } + renderer2.setRenderTarget(currentRenderTarget); + } +} + +class Group extends Object3D { + constructor() { + super(); + this.isGroup = true; + this.type = "Group"; + } +} +var _moveEvent = { type: "move" }; + +class WebXRController { + constructor() { + this._targetRay = null; + this._grip = null; + this._hand = null; + } + getHandSpace() { + if (this._hand === null) { + this._hand = new Group; + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + } + return this._hand; + } + getTargetRaySpace() { + if (this._targetRay === null) { + this._targetRay = new Group; + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3; + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3; + } + return this._targetRay; + } + getGripSpace() { + if (this._grip === null) { + this._grip = new Group; + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3; + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3; + } + return this._grip; + } + dispatchEvent(event) { + if (this._targetRay !== null) { + this._targetRay.dispatchEvent(event); + } + if (this._grip !== null) { + this._grip.dispatchEvent(event); + } + if (this._hand !== null) { + this._hand.dispatchEvent(event); + } + return this; + } + connect(inputSource) { + if (inputSource && inputSource.hand) { + const hand = this._hand; + if (hand) { + for (const inputjoint of inputSource.hand.values()) { + this._getHandJoint(hand, inputjoint); + } + } + } + this.dispatchEvent({ type: "connected", data: inputSource }); + return this; + } + disconnect(inputSource) { + this.dispatchEvent({ type: "disconnected", data: inputSource }); + if (this._targetRay !== null) { + this._targetRay.visible = false; + } + if (this._grip !== null) { + this._grip.visible = false; + } + if (this._hand !== null) { + this._hand.visible = false; + } + return this; + } + update(inputSource, frame, referenceSpace) { + let inputPose = null; + let gripPose = null; + let handPose = null; + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + if (inputSource && frame.session.visibilityState !== "visible-blurred") { + if (hand && inputSource.hand) { + handPose = true; + for (const inputjoint of inputSource.hand.values()) { + const jointPose = frame.getJointPose(inputjoint, referenceSpace); + const joint = this._getHandJoint(hand, inputjoint); + if (jointPose !== null) { + joint.matrix.fromArray(jointPose.transform.matrix); + joint.matrix.decompose(joint.position, joint.rotation, joint.scale); + joint.matrixWorldNeedsUpdate = true; + joint.jointRadius = jointPose.radius; + } + joint.visible = jointPose !== null; + } + const indexTip = hand.joints["index-finger-tip"]; + const thumbTip = hand.joints["thumb-tip"]; + const distance = indexTip.position.distanceTo(thumbTip.position); + const distanceToPinch = 0.02; + const threshold = 0.005; + if (hand.inputState.pinching && distance > distanceToPinch + threshold) { + hand.inputState.pinching = false; + this.dispatchEvent({ + type: "pinchend", + handedness: inputSource.handedness, + target: this + }); + } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) { + hand.inputState.pinching = true; + this.dispatchEvent({ + type: "pinchstart", + handedness: inputSource.handedness, + target: this + }); + } + } else { + if (grip !== null && inputSource.gripSpace) { + gripPose = frame.getPose(inputSource.gripSpace, referenceSpace); + if (gripPose !== null) { + grip.matrix.fromArray(gripPose.transform.matrix); + grip.matrix.decompose(grip.position, grip.rotation, grip.scale); + grip.matrixWorldNeedsUpdate = true; + if (gripPose.linearVelocity) { + grip.hasLinearVelocity = true; + grip.linearVelocity.copy(gripPose.linearVelocity); + } else { + grip.hasLinearVelocity = false; + } + if (gripPose.angularVelocity) { + grip.hasAngularVelocity = true; + grip.angularVelocity.copy(gripPose.angularVelocity); + } else { + grip.hasAngularVelocity = false; + } + } + } + } + if (targetRay !== null) { + inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); + if (inputPose === null && gripPose !== null) { + inputPose = gripPose; + } + if (inputPose !== null) { + targetRay.matrix.fromArray(inputPose.transform.matrix); + targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale); + targetRay.matrixWorldNeedsUpdate = true; + if (inputPose.linearVelocity) { + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy(inputPose.linearVelocity); + } else { + targetRay.hasLinearVelocity = false; + } + if (inputPose.angularVelocity) { + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy(inputPose.angularVelocity); + } else { + targetRay.hasAngularVelocity = false; + } + this.dispatchEvent(_moveEvent); + } + } + } + if (targetRay !== null) { + targetRay.visible = inputPose !== null; + } + if (grip !== null) { + grip.visible = gripPose !== null; + } + if (hand !== null) { + hand.visible = handPose !== null; + } + return this; + } + _getHandJoint(hand, inputjoint) { + if (hand.joints[inputjoint.jointName] === undefined) { + const joint = new Group; + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[inputjoint.jointName] = joint; + hand.add(joint); + } + return hand.joints[inputjoint.jointName]; + } +} + +class FogExp2 { + constructor(color, density = 0.00025) { + this.isFogExp2 = true; + this.name = ""; + this.color = new Color(color); + this.density = density; + } + clone() { + return new FogExp2(this.color, this.density); + } + toJSON() { + return { + type: "FogExp2", + name: this.name, + color: this.color.getHex(), + density: this.density + }; + } +} + +class Fog { + constructor(color, near = 1, far = 1000) { + this.isFog = true; + this.name = ""; + this.color = new Color(color); + this.near = near; + this.far = far; + } + clone() { + return new Fog(this.color, this.near, this.far); + } + toJSON() { + return { + type: "Fog", + name: this.name, + color: this.color.getHex(), + near: this.near, + far: this.far + }; + } +} + +class Scene extends Object3D { + constructor() { + super(); + this.isScene = true; + this.type = "Scene"; + this.background = null; + this.environment = null; + this.fog = null; + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + this.backgroundRotation = new Euler; + this.environmentIntensity = 1; + this.environmentRotation = new Euler; + this.overrideMaterial = null; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.background !== null) + this.background = source.background.clone(); + if (source.environment !== null) + this.environment = source.environment.clone(); + if (source.fog !== null) + this.fog = source.fog.clone(); + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + this.backgroundRotation.copy(source.backgroundRotation); + this.environmentIntensity = source.environmentIntensity; + this.environmentRotation.copy(source.environmentRotation); + if (source.overrideMaterial !== null) + this.overrideMaterial = source.overrideMaterial.clone(); + this.matrixAutoUpdate = source.matrixAutoUpdate; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + if (this.fog !== null) + data2.object.fog = this.fog.toJSON(); + if (this.backgroundBlurriness > 0) + data2.object.backgroundBlurriness = this.backgroundBlurriness; + if (this.backgroundIntensity !== 1) + data2.object.backgroundIntensity = this.backgroundIntensity; + data2.object.backgroundRotation = this.backgroundRotation.toArray(); + if (this.environmentIntensity !== 1) + data2.object.environmentIntensity = this.environmentIntensity; + data2.object.environmentRotation = this.environmentRotation.toArray(); + return data2; + } +} + +class InterleavedBuffer { + constructor(array, stride) { + this.isInterleavedBuffer = true; + this.array = array; + this.stride = stride; + this.count = array !== undefined ? array.length / stride : 0; + this.usage = StaticDrawUsage; + this.updateRanges = []; + this.version = 0; + this.uuid = generateUUID(); + } + onUploadCallback() { + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setUsage(value2) { + this.usage = value2; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.array = new source.array.constructor(source.array); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.stride; + index2 *= attribute.stride; + for (let i = 0, l = this.stride;i < l; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + set(value2, offset = 0) { + this.array.set(value2, offset); + return this; + } + clone(data2) { + if (data2.arrayBuffers === undefined) { + data2.arrayBuffers = {}; + } + if (this.array.buffer._uuid === undefined) { + this.array.buffer._uuid = generateUUID(); + } + if (data2.arrayBuffers[this.array.buffer._uuid] === undefined) { + data2.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer; + } + const array = new this.array.constructor(data2.arrayBuffers[this.array.buffer._uuid]); + const ib = new this.constructor(array, this.stride); + ib.setUsage(this.usage); + return ib; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + toJSON(data2) { + if (data2.arrayBuffers === undefined) { + data2.arrayBuffers = {}; + } + if (this.array.buffer._uuid === undefined) { + this.array.buffer._uuid = generateUUID(); + } + if (data2.arrayBuffers[this.array.buffer._uuid] === undefined) { + data2.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer)); + } + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; + } +} +var _vector$7 = /* @__PURE__ */ new Vector3; + +class InterleavedBufferAttribute { + constructor(interleavedBuffer, itemSize, offset, normalized = false) { + this.isInterleavedBufferAttribute = true; + this.name = ""; + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; + this.normalized = normalized; + } + get count() { + return this.data.count; + } + get array() { + return this.data.array; + } + set needsUpdate(value2) { + this.data.needsUpdate = value2; + } + applyMatrix4(m) { + for (let i = 0, l = this.data.count;i < l; i++) { + _vector$7.fromBufferAttribute(this, i); + _vector$7.applyMatrix4(m); + this.setXYZ(i, _vector$7.x, _vector$7.y, _vector$7.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$7.fromBufferAttribute(this, i); + _vector$7.applyNormalMatrix(m); + this.setXYZ(i, _vector$7.x, _vector$7.y, _vector$7.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$7.fromBufferAttribute(this, i); + _vector$7.transformDirection(m); + this.setXYZ(i, _vector$7.x, _vector$7.y, _vector$7.z); + } + return this; + } + getComponent(index2, component) { + let value2 = this.array[index2 * this.data.stride + this.offset + component]; + if (this.normalized) + value2 = denormalize(value2, this.array); + return value2; + } + setComponent(index2, component, value2) { + if (this.normalized) + value2 = normalize2(value2, this.array); + this.data.array[index2 * this.data.stride + this.offset + component] = value2; + return this; + } + setX(index2, x) { + if (this.normalized) + x = normalize2(x, this.array); + this.data.array[index2 * this.data.stride + this.offset] = x; + return this; + } + setY(index2, y) { + if (this.normalized) + y = normalize2(y, this.array); + this.data.array[index2 * this.data.stride + this.offset + 1] = y; + return this; + } + setZ(index2, z) { + if (this.normalized) + z = normalize2(z, this.array); + this.data.array[index2 * this.data.stride + this.offset + 2] = z; + return this; + } + setW(index2, w) { + if (this.normalized) + w = normalize2(w, this.array); + this.data.array[index2 * this.data.stride + this.offset + 3] = w; + return this; + } + getX(index2) { + let x = this.data.array[index2 * this.data.stride + this.offset]; + if (this.normalized) + x = denormalize(x, this.array); + return x; + } + getY(index2) { + let y = this.data.array[index2 * this.data.stride + this.offset + 1]; + if (this.normalized) + y = denormalize(y, this.array); + return y; + } + getZ(index2) { + let z = this.data.array[index2 * this.data.stride + this.offset + 2]; + if (this.normalized) + z = denormalize(z, this.array); + return z; + } + getW(index2) { + let w = this.data.array[index2 * this.data.stride + this.offset + 3]; + if (this.normalized) + w = denormalize(w, this.array); + return w; + } + setXY(index2, x, y) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + } + this.data.array[index2 + 0] = x; + this.data.array[index2 + 1] = y; + return this; + } + setXYZ(index2, x, y, z) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + } + this.data.array[index2 + 0] = x; + this.data.array[index2 + 1] = y; + this.data.array[index2 + 2] = z; + return this; + } + setXYZW(index2, x, y, z, w) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + w = normalize2(w, this.array); + } + this.data.array[index2 + 0] = x; + this.data.array[index2 + 1] = y; + this.data.array[index2 + 2] = z; + this.data.array[index2 + 3] = w; + return this; + } + clone(data2) { + if (data2 === undefined) { + console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0;i < this.count; i++) { + const index2 = i * this.data.stride + this.offset; + for (let j = 0;j < this.itemSize; j++) { + array.push(this.data.array[index2 + j]); + } + } + return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized); + } else { + if (data2.interleavedBuffers === undefined) { + data2.interleavedBuffers = {}; + } + if (data2.interleavedBuffers[this.data.uuid] === undefined) { + data2.interleavedBuffers[this.data.uuid] = this.data.clone(data2); + } + return new InterleavedBufferAttribute(data2.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized); + } + } + toJSON(data2) { + if (data2 === undefined) { + console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0;i < this.count; i++) { + const index2 = i * this.data.stride + this.offset; + for (let j = 0;j < this.itemSize; j++) { + array.push(this.data.array[index2 + j]); + } + } + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array, + normalized: this.normalized + }; + } else { + if (data2.interleavedBuffers === undefined) { + data2.interleavedBuffers = {}; + } + if (data2.interleavedBuffers[this.data.uuid] === undefined) { + data2.interleavedBuffers[this.data.uuid] = this.data.toJSON(data2); + } + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + } + } +} + +class SpriteMaterial extends Material { + constructor(parameters) { + super(); + this.isSpriteMaterial = true; + this.type = "SpriteMaterial"; + this.color = new Color(16777215); + this.map = null; + this.alphaMap = null; + this.rotation = 0; + this.sizeAttenuation = true; + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.rotation = source.rotation; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } +} +var _geometry; +var _intersectPoint = /* @__PURE__ */ new Vector3; +var _worldScale = /* @__PURE__ */ new Vector3; +var _mvPosition = /* @__PURE__ */ new Vector3; +var _alignedPosition = /* @__PURE__ */ new Vector2; +var _rotatedPosition = /* @__PURE__ */ new Vector2; +var _viewWorldMatrix = /* @__PURE__ */ new Matrix4; +var _vA = /* @__PURE__ */ new Vector3; +var _vB = /* @__PURE__ */ new Vector3; +var _vC = /* @__PURE__ */ new Vector3; +var _uvA = /* @__PURE__ */ new Vector2; +var _uvB = /* @__PURE__ */ new Vector2; +var _uvC = /* @__PURE__ */ new Vector2; + +class Sprite extends Object3D { + constructor(material = new SpriteMaterial) { + super(); + this.isSprite = true; + this.type = "Sprite"; + if (_geometry === undefined) { + _geometry = new BufferGeometry; + const float32Array = new Float32Array([ + -0.5, + -0.5, + 0, + 0, + 0, + 0.5, + -0.5, + 0, + 1, + 0, + 0.5, + 0.5, + 0, + 1, + 1, + -0.5, + 0.5, + 0, + 0, + 1 + ]); + const interleavedBuffer = new InterleavedBuffer(float32Array, 5); + _geometry.setIndex([0, 1, 2, 0, 2, 3]); + _geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false)); + _geometry.setAttribute("uv", new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false)); + } + this.geometry = _geometry; + this.material = material; + this.center = new Vector2(0.5, 0.5); + } + raycast(raycaster, intersects) { + if (raycaster.camera === null) { + console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'); + } + _worldScale.setFromMatrixScale(this.matrixWorld); + _viewWorldMatrix.copy(raycaster.camera.matrixWorld); + this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld); + _mvPosition.setFromMatrixPosition(this.modelViewMatrix); + if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) { + _worldScale.multiplyScalar(-_mvPosition.z); + } + const rotation2 = this.material.rotation; + let sin, cos; + if (rotation2 !== 0) { + cos = Math.cos(rotation2); + sin = Math.sin(rotation2); + } + const center = this.center; + transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos); + transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos); + transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos); + _uvA.set(0, 0); + _uvB.set(1, 0); + _uvC.set(1, 1); + let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint); + if (intersect === null) { + transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos); + _uvB.set(0, 1); + intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint); + if (intersect === null) { + return; + } + } + const distance = raycaster.ray.origin.distanceTo(_intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) + return; + intersects.push({ + distance, + point: _intersectPoint.clone(), + uv: Triangle.getInterpolation(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2), + face: null, + object: this + }); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.center !== undefined) + this.center.copy(source.center); + this.material = source.material; + return this; + } +} +function transformVertex(vertexPosition, mvPosition, center, scale2, sin, cos) { + _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale2); + if (sin !== undefined) { + _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y; + _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y; + } else { + _rotatedPosition.copy(_alignedPosition); + } + vertexPosition.copy(mvPosition); + vertexPosition.x += _rotatedPosition.x; + vertexPosition.y += _rotatedPosition.y; + vertexPosition.applyMatrix4(_viewWorldMatrix); +} +var _v1$2 = /* @__PURE__ */ new Vector3; +var _v2$1 = /* @__PURE__ */ new Vector3; + +class LOD extends Object3D { + constructor() { + super(); + this._currentLevel = 0; + this.type = "LOD"; + Object.defineProperties(this, { + levels: { + enumerable: true, + value: [] + }, + isLOD: { + value: true + } + }); + this.autoUpdate = true; + } + copy(source) { + super.copy(source, false); + const levels = source.levels; + for (let i = 0, l = levels.length;i < l; i++) { + const level = levels[i]; + this.addLevel(level.object.clone(), level.distance, level.hysteresis); + } + this.autoUpdate = source.autoUpdate; + return this; + } + addLevel(object, distance = 0, hysteresis = 0) { + distance = Math.abs(distance); + const levels = this.levels; + let l; + for (l = 0;l < levels.length; l++) { + if (distance < levels[l].distance) { + break; + } + } + levels.splice(l, 0, { distance, hysteresis, object }); + this.add(object); + return this; + } + removeLevel(distance) { + const levels = this.levels; + for (let i = 0;i < levels.length; i++) { + if (levels[i].distance === distance) { + const removedElements = levels.splice(i, 1); + this.remove(removedElements[0].object); + return true; + } + } + return false; + } + getCurrentLevel() { + return this._currentLevel; + } + getObjectForDistance(distance) { + const levels = this.levels; + if (levels.length > 0) { + let i, l; + for (i = 1, l = levels.length;i < l; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance < levelDistance) { + break; + } + } + return levels[i - 1].object; + } + return null; + } + raycast(raycaster, intersects) { + const levels = this.levels; + if (levels.length > 0) { + _v1$2.setFromMatrixPosition(this.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_v1$2); + this.getObjectForDistance(distance).raycast(raycaster, intersects); + } + } + update(camera) { + const levels = this.levels; + if (levels.length > 1) { + _v1$2.setFromMatrixPosition(camera.matrixWorld); + _v2$1.setFromMatrixPosition(this.matrixWorld); + const distance = _v1$2.distanceTo(_v2$1) / camera.zoom; + levels[0].object.visible = true; + let i, l; + for (i = 1, l = levels.length;i < l; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance >= levelDistance) { + levels[i - 1].object.visible = false; + levels[i].object.visible = true; + } else { + break; + } + } + this._currentLevel = i - 1; + for (;i < l; i++) { + levels[i].object.visible = false; + } + } + } + toJSON(meta) { + const data2 = super.toJSON(meta); + if (this.autoUpdate === false) + data2.object.autoUpdate = false; + data2.object.levels = []; + const levels = this.levels; + for (let i = 0, l = levels.length;i < l; i++) { + const level = levels[i]; + data2.object.levels.push({ + object: level.object.uuid, + distance: level.distance, + hysteresis: level.hysteresis + }); + } + return data2; + } +} +var _basePosition = /* @__PURE__ */ new Vector3; +var _skinIndex = /* @__PURE__ */ new Vector4; +var _skinWeight = /* @__PURE__ */ new Vector4; +var _vector3 = /* @__PURE__ */ new Vector3; +var _matrix4 = /* @__PURE__ */ new Matrix4; +var _vertex = /* @__PURE__ */ new Vector3; +var _sphere$5 = /* @__PURE__ */ new Sphere; +var _inverseMatrix$2 = /* @__PURE__ */ new Matrix4; +var _ray$2 = /* @__PURE__ */ new Ray; + +class SkinnedMesh extends Mesh { + constructor(geometry, material) { + super(geometry, material); + this.isSkinnedMesh = true; + this.type = "SkinnedMesh"; + this.bindMode = AttachedBindMode; + this.bindMatrix = new Matrix4; + this.bindMatrixInverse = new Matrix4; + this.boundingBox = null; + this.boundingSphere = null; + } + computeBoundingBox() { + const geometry = this.geometry; + if (this.boundingBox === null) { + this.boundingBox = new Box3; + } + this.boundingBox.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0;i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex); + this.boundingBox.expandByPoint(_vertex); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere; + } + this.boundingSphere.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0;i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex); + this.boundingSphere.expandByPoint(_vertex); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.bindMode = source.bindMode; + this.bindMatrix.copy(source.bindMatrix); + this.bindMatrixInverse.copy(source.bindMatrixInverse); + this.skeleton = source.skeleton; + if (source.boundingBox !== null) + this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) + this.boundingSphere = source.boundingSphere.clone(); + return this; + } + raycast(raycaster, intersects) { + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === undefined) + return; + if (this.boundingSphere === null) + this.computeBoundingSphere(); + _sphere$5.copy(this.boundingSphere); + _sphere$5.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$5) === false) + return; + _inverseMatrix$2.copy(matrixWorld).invert(); + _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); + if (this.boundingBox !== null) { + if (_ray$2.intersectsBox(this.boundingBox) === false) + return; + } + this._computeIntersections(raycaster, intersects, _ray$2); + } + getVertexPosition(index2, target) { + super.getVertexPosition(index2, target); + this.applyBoneTransform(index2, target); + return target; + } + bind(skeleton, bindMatrix) { + this.skeleton = skeleton; + if (bindMatrix === undefined) { + this.updateMatrixWorld(true); + this.skeleton.calculateInverses(); + bindMatrix = this.matrixWorld; + } + this.bindMatrix.copy(bindMatrix); + this.bindMatrixInverse.copy(bindMatrix).invert(); + } + pose() { + this.skeleton.pose(); + } + normalizeSkinWeights() { + const vector = new Vector4; + const skinWeight = this.geometry.attributes.skinWeight; + for (let i = 0, l = skinWeight.count;i < l; i++) { + vector.fromBufferAttribute(skinWeight, i); + const scale2 = 1 / vector.manhattanLength(); + if (scale2 !== Infinity) { + vector.multiplyScalar(scale2); + } else { + vector.set(1, 0, 0, 0); + } + skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w); + } + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.bindMode === AttachedBindMode) { + this.bindMatrixInverse.copy(this.matrixWorld).invert(); + } else if (this.bindMode === DetachedBindMode) { + this.bindMatrixInverse.copy(this.bindMatrix).invert(); + } else { + console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode); + } + } + applyBoneTransform(index2, vector) { + const skeleton = this.skeleton; + const geometry = this.geometry; + _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index2); + _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index2); + _basePosition.copy(vector).applyMatrix4(this.bindMatrix); + vector.set(0, 0, 0); + for (let i = 0;i < 4; i++) { + const weight = _skinWeight.getComponent(i); + if (weight !== 0) { + const boneIndex = _skinIndex.getComponent(i); + _matrix4.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]); + vector.addScaledVector(_vector3.copy(_basePosition).applyMatrix4(_matrix4), weight); + } + } + return vector.applyMatrix4(this.bindMatrixInverse); + } +} + +class Bone extends Object3D { + constructor() { + super(); + this.isBone = true; + this.type = "Bone"; + } +} + +class DataTexture extends Texture { + constructor(data2 = null, width2 = 1, height2 = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isDataTexture = true; + this.image = { data: data2, width: width2, height: height2 }; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } +} +var _offsetMatrix = /* @__PURE__ */ new Matrix4; +var _identityMatrix = /* @__PURE__ */ new Matrix4; + +class Skeleton { + constructor(bones = [], boneInverses = []) { + this.uuid = generateUUID(); + this.bones = bones.slice(0); + this.boneInverses = boneInverses; + this.boneMatrices = null; + this.boneTexture = null; + this.init(); + } + init() { + const bones = this.bones; + const boneInverses = this.boneInverses; + this.boneMatrices = new Float32Array(bones.length * 16); + if (boneInverses.length === 0) { + this.calculateInverses(); + } else { + if (bones.length !== boneInverses.length) { + console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."); + this.boneInverses = []; + for (let i = 0, il = this.bones.length;i < il; i++) { + this.boneInverses.push(new Matrix4); + } + } + } + } + calculateInverses() { + this.boneInverses.length = 0; + for (let i = 0, il = this.bones.length;i < il; i++) { + const inverse = new Matrix4; + if (this.bones[i]) { + inverse.copy(this.bones[i].matrixWorld).invert(); + } + this.boneInverses.push(inverse); + } + } + pose() { + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone) { + bone.matrixWorld.copy(this.boneInverses[i]).invert(); + } + } + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone) { + if (bone.parent && bone.parent.isBone) { + bone.matrix.copy(bone.parent.matrixWorld).invert(); + bone.matrix.multiply(bone.matrixWorld); + } else { + bone.matrix.copy(bone.matrixWorld); + } + bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); + } + } + } + update() { + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; + for (let i = 0, il = bones.length;i < il; i++) { + const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix; + _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]); + _offsetMatrix.toArray(boneMatrices, i * 16); + } + if (boneTexture !== null) { + boneTexture.needsUpdate = true; + } + } + clone() { + return new Skeleton(this.bones, this.boneInverses); + } + computeBoneTexture() { + let size = Math.sqrt(this.bones.length * 4); + size = Math.ceil(size / 4) * 4; + size = Math.max(size, 4); + const boneMatrices = new Float32Array(size * size * 4); + boneMatrices.set(this.boneMatrices); + const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType); + boneTexture.needsUpdate = true; + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + return this; + } + getBoneByName(name2) { + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone.name === name2) { + return bone; + } + } + return; + } + dispose() { + if (this.boneTexture !== null) { + this.boneTexture.dispose(); + this.boneTexture = null; + } + } + fromJSON(json, bones) { + this.uuid = json.uuid; + for (let i = 0, l = json.bones.length;i < l; i++) { + const uuid = json.bones[i]; + let bone = bones[uuid]; + if (bone === undefined) { + console.warn("THREE.Skeleton: No bone found with UUID:", uuid); + bone = new Bone; + } + this.bones.push(bone); + this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i])); + } + this.init(); + return this; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "Skeleton", + generator: "Skeleton.toJSON" + }, + bones: [], + boneInverses: [] + }; + data2.uuid = this.uuid; + const bones = this.bones; + const boneInverses = this.boneInverses; + for (let i = 0, l = bones.length;i < l; i++) { + const bone = bones[i]; + data2.bones.push(bone.uuid); + const boneInverse = boneInverses[i]; + data2.boneInverses.push(boneInverse.toArray()); + } + return data2; + } +} + +class InstancedBufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized, meshPerAttribute = 1) { + super(array, itemSize, normalized); + this.isInstancedBufferAttribute = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.meshPerAttribute = this.meshPerAttribute; + data2.isInstancedBufferAttribute = true; + return data2; + } +} +var _instanceLocalMatrix = /* @__PURE__ */ new Matrix4; +var _instanceWorldMatrix = /* @__PURE__ */ new Matrix4; +var _instanceIntersects = []; +var _box3 = /* @__PURE__ */ new Box3; +var _identity = /* @__PURE__ */ new Matrix4; +var _mesh$1 = /* @__PURE__ */ new Mesh; +var _sphere$4 = /* @__PURE__ */ new Sphere; + +class InstancedMesh extends Mesh { + constructor(geometry, material, count) { + super(geometry, material); + this.isInstancedMesh = true; + this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16); + this.instanceColor = null; + this.morphTexture = null; + this.count = count; + this.boundingBox = null; + this.boundingSphere = null; + for (let i = 0;i < count; i++) { + this.setMatrixAt(i, _identity); + } + } + computeBoundingBox() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingBox === null) { + this.boundingBox = new Box3; + } + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + this.boundingBox.makeEmpty(); + for (let i = 0;i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix); + _box3.copy(geometry.boundingBox).applyMatrix4(_instanceLocalMatrix); + this.boundingBox.union(_box3); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere; + } + if (geometry.boundingSphere === null) { + geometry.computeBoundingSphere(); + } + this.boundingSphere.makeEmpty(); + for (let i = 0;i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix); + _sphere$4.copy(geometry.boundingSphere).applyMatrix4(_instanceLocalMatrix); + this.boundingSphere.union(_sphere$4); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.instanceMatrix.copy(source.instanceMatrix); + if (source.morphTexture !== null) + this.morphTexture = source.morphTexture.clone(); + if (source.instanceColor !== null) + this.instanceColor = source.instanceColor.clone(); + this.count = source.count; + if (source.boundingBox !== null) + this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) + this.boundingSphere = source.boundingSphere.clone(); + return this; + } + getColorAt(index2, color) { + color.fromArray(this.instanceColor.array, index2 * 3); + } + getMatrixAt(index2, matrix) { + matrix.fromArray(this.instanceMatrix.array, index2 * 16); + } + getMorphAt(index2, object) { + const objectInfluences = object.morphTargetInfluences; + const array = this.morphTexture.source.data.data; + const len = objectInfluences.length + 1; + const dataIndex = index2 * len + 1; + for (let i = 0;i < objectInfluences.length; i++) { + objectInfluences[i] = array[dataIndex + i]; + } + } + raycast(raycaster, intersects) { + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + _mesh$1.geometry = this.geometry; + _mesh$1.material = this.material; + if (_mesh$1.material === undefined) + return; + if (this.boundingSphere === null) + this.computeBoundingSphere(); + _sphere$4.copy(this.boundingSphere); + _sphere$4.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$4) === false) + return; + for (let instanceId = 0;instanceId < raycastTimes; instanceId++) { + this.getMatrixAt(instanceId, _instanceLocalMatrix); + _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); + _mesh$1.matrixWorld = _instanceWorldMatrix; + _mesh$1.raycast(raycaster, _instanceIntersects); + for (let i = 0, l = _instanceIntersects.length;i < l; i++) { + const intersect = _instanceIntersects[i]; + intersect.instanceId = instanceId; + intersect.object = this; + intersects.push(intersect); + } + _instanceIntersects.length = 0; + } + } + setColorAt(index2, color) { + if (this.instanceColor === null) { + this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3); + } + color.toArray(this.instanceColor.array, index2 * 3); + } + setMatrixAt(index2, matrix) { + matrix.toArray(this.instanceMatrix.array, index2 * 16); + } + setMorphAt(index2, object) { + const objectInfluences = object.morphTargetInfluences; + const len = objectInfluences.length + 1; + if (this.morphTexture === null) { + this.morphTexture = new DataTexture(new Float32Array(len * this.count), len, this.count, RedFormat, FloatType); + } + const array = this.morphTexture.source.data.data; + let morphInfluencesSum = 0; + for (let i = 0;i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + const dataIndex = len * index2; + array[dataIndex] = morphBaseInfluence; + array.set(objectInfluences, dataIndex + 1); + } + updateMorphTargets() { + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + if (this.morphTexture !== null) { + this.morphTexture.dispose(); + this.morphTexture = null; + } + return this; + } +} +var _vector1 = /* @__PURE__ */ new Vector3; +var _vector2 = /* @__PURE__ */ new Vector3; +var _normalMatrix = /* @__PURE__ */ new Matrix3; + +class Plane { + constructor(normal = new Vector3(1, 0, 0), constant = 0) { + this.isPlane = true; + this.normal = normal; + this.constant = constant; + } + set(normal, constant) { + this.normal.copy(normal); + this.constant = constant; + return this; + } + setComponents(x, y, z, w) { + this.normal.set(x, y, z); + this.constant = w; + return this; + } + setFromNormalAndCoplanarPoint(normal, point) { + this.normal.copy(normal); + this.constant = -point.dot(this.normal); + return this; + } + setFromCoplanarPoints(a, b, c) { + const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); + this.setFromNormalAndCoplanarPoint(normal, a); + return this; + } + copy(plane) { + this.normal.copy(plane.normal); + this.constant = plane.constant; + return this; + } + normalize() { + const inverseNormalLength = 1 / this.normal.length(); + this.normal.multiplyScalar(inverseNormalLength); + this.constant *= inverseNormalLength; + return this; + } + negate() { + this.constant *= -1; + this.normal.negate(); + return this; + } + distanceToPoint(point) { + return this.normal.dot(point) + this.constant; + } + distanceToSphere(sphere) { + return this.distanceToPoint(sphere.center) - sphere.radius; + } + projectPoint(point, target) { + return target.copy(point).addScaledVector(this.normal, -this.distanceToPoint(point)); + } + intersectLine(line, target) { + const direction = line.delta(_vector1); + const denominator = this.normal.dot(direction); + if (denominator === 0) { + if (this.distanceToPoint(line.start) === 0) { + return target.copy(line.start); + } + return null; + } + const t = -(line.start.dot(this.normal) + this.constant) / denominator; + if (t < 0 || t > 1) { + return null; + } + return target.copy(line.start).addScaledVector(direction, t); + } + intersectsLine(line) { + const startSign = this.distanceToPoint(line.start); + const endSign = this.distanceToPoint(line.end); + return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0; + } + intersectsBox(box) { + return box.intersectsPlane(this); + } + intersectsSphere(sphere) { + return sphere.intersectsPlane(this); + } + coplanarPoint(target) { + return target.copy(this.normal).multiplyScalar(-this.constant); + } + applyMatrix4(matrix, optionalNormalMatrix) { + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix); + const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix); + const normal = this.normal.applyMatrix3(normalMatrix).normalize(); + this.constant = -referencePoint.dot(normal); + return this; + } + translate(offset) { + this.constant -= offset.dot(this.normal); + return this; + } + equals(plane) { + return plane.normal.equals(this.normal) && plane.constant === this.constant; + } + clone() { + return new this.constructor().copy(this); + } +} +var _sphere$3 = /* @__PURE__ */ new Sphere; +var _vector$6 = /* @__PURE__ */ new Vector3; + +class Frustum { + constructor(p0 = new Plane, p1 = new Plane, p2 = new Plane, p3 = new Plane, p4 = new Plane, p5 = new Plane) { + this.planes = [p0, p1, p2, p3, p4, p5]; + } + set(p0, p1, p2, p3, p4, p5) { + const planes = this.planes; + planes[0].copy(p0); + planes[1].copy(p1); + planes[2].copy(p2); + planes[3].copy(p3); + planes[4].copy(p4); + planes[5].copy(p5); + return this; + } + copy(frustum) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + planes[i].copy(frustum.planes[i]); + } + return this; + } + setFromProjectionMatrix(m, coordinateSystem = WebGLCoordinateSystem) { + const planes = this.planes; + const me = m.elements; + const me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3]; + const me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7]; + const me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11]; + const me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15]; + planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize(); + planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize(); + planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize(); + planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize(); + planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); + if (coordinateSystem === WebGLCoordinateSystem) { + planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize(); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + planes[5].setComponents(me2, me6, me10, me14).normalize(); + } else { + throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + coordinateSystem); + } + return this; + } + intersectsObject(object) { + if (object.boundingSphere !== undefined) { + if (object.boundingSphere === null) + object.computeBoundingSphere(); + _sphere$3.copy(object.boundingSphere).applyMatrix4(object.matrixWorld); + } else { + const geometry = object.geometry; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$3.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld); + } + return this.intersectsSphere(_sphere$3); + } + intersectsSprite(sprite) { + _sphere$3.center.set(0, 0, 0); + _sphere$3.radius = 0.7071067811865476; + _sphere$3.applyMatrix4(sprite.matrixWorld); + return this.intersectsSphere(_sphere$3); + } + intersectsSphere(sphere) { + const planes = this.planes; + const center = sphere.center; + const negRadius = -sphere.radius; + for (let i = 0;i < 6; i++) { + const distance = planes[i].distanceToPoint(center); + if (distance < negRadius) { + return false; + } + } + return true; + } + intersectsBox(box) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + const plane = planes[i]; + _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z; + if (plane.distanceToPoint(_vector$6) < 0) { + return false; + } + } + return true; + } + containsPoint(point) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + if (planes[i].distanceToPoint(point) < 0) { + return false; + } + } + return true; + } + clone() { + return new this.constructor().copy(this); + } +} +function ascIdSort(a, b) { + return a - b; +} +function sortOpaque(a, b) { + return a.z - b.z; +} +function sortTransparent(a, b) { + return b.z - a.z; +} + +class MultiDrawRenderList { + constructor() { + this.index = 0; + this.pool = []; + this.list = []; + } + push(start, count, z, index2) { + const pool = this.pool; + const list = this.list; + if (this.index >= pool.length) { + pool.push({ + start: -1, + count: -1, + z: -1, + index: -1 + }); + } + const item = pool[this.index]; + list.push(item); + this.index++; + item.start = start; + item.count = count; + item.z = z; + item.index = index2; + } + reset() { + this.list.length = 0; + this.index = 0; + } +} +var _matrix$1 = /* @__PURE__ */ new Matrix4; +var _whiteColor = /* @__PURE__ */ new Color(1, 1, 1); +var _frustum = /* @__PURE__ */ new Frustum; +var _box$1 = /* @__PURE__ */ new Box3; +var _sphere$2 = /* @__PURE__ */ new Sphere; +var _vector$5 = /* @__PURE__ */ new Vector3; +var _forward = /* @__PURE__ */ new Vector3; +var _temp = /* @__PURE__ */ new Vector3; +var _renderList = /* @__PURE__ */ new MultiDrawRenderList; +var _mesh = /* @__PURE__ */ new Mesh; +var _batchIntersects = []; +function copyAttributeData(src, target, targetOffset = 0) { + const itemSize = target.itemSize; + if (src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor) { + const vertexCount = src.count; + for (let i = 0;i < vertexCount; i++) { + for (let c = 0;c < itemSize; c++) { + target.setComponent(i + targetOffset, c, src.getComponent(i, c)); + } + } + } else { + target.array.set(src.array, targetOffset * itemSize); + } + target.needsUpdate = true; +} +function copyArrayContents(src, target) { + if (src.constructor !== target.constructor) { + const len = Math.min(src.length, target.length); + for (let i = 0;i < len; i++) { + target[i] = src[i]; + } + } else { + const len = Math.min(src.length, target.length); + target.set(new src.constructor(src.buffer, 0, len)); + } +} + +class BatchedMesh extends Mesh { + get maxInstanceCount() { + return this._maxInstanceCount; + } + get instanceCount() { + return this._instanceInfo.length - this._availableInstanceIds.length; + } + get unusedVertexCount() { + return this._maxVertexCount - this._nextVertexStart; + } + get unusedIndexCount() { + return this._maxIndexCount - this._nextIndexStart; + } + constructor(maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material) { + super(new BufferGeometry, material); + this.isBatchedMesh = true; + this.perObjectFrustumCulled = true; + this.sortObjects = true; + this.boundingBox = null; + this.boundingSphere = null; + this.customSort = null; + this._instanceInfo = []; + this._geometryInfo = []; + this._availableInstanceIds = []; + this._availableGeometryIds = []; + this._nextIndexStart = 0; + this._nextVertexStart = 0; + this._geometryCount = 0; + this._visibilityChanged = true; + this._geometryInitialized = false; + this._maxInstanceCount = maxInstanceCount; + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + this._multiDrawCounts = new Int32Array(maxInstanceCount); + this._multiDrawStarts = new Int32Array(maxInstanceCount); + this._multiDrawCount = 0; + this._multiDrawInstances = null; + this._matricesTexture = null; + this._indirectTexture = null; + this._colorsTexture = null; + this._initMatricesTexture(); + this._initIndirectTexture(); + } + _initMatricesTexture() { + let size = Math.sqrt(this._maxInstanceCount * 4); + size = Math.ceil(size / 4) * 4; + size = Math.max(size, 4); + const matricesArray = new Float32Array(size * size * 4); + const matricesTexture = new DataTexture(matricesArray, size, size, RGBAFormat, FloatType); + this._matricesTexture = matricesTexture; + } + _initIndirectTexture() { + let size = Math.sqrt(this._maxInstanceCount); + size = Math.ceil(size); + const indirectArray = new Uint32Array(size * size); + const indirectTexture = new DataTexture(indirectArray, size, size, RedIntegerFormat, UnsignedIntType); + this._indirectTexture = indirectTexture; + } + _initColorsTexture() { + let size = Math.sqrt(this._maxInstanceCount); + size = Math.ceil(size); + const colorsArray = new Float32Array(size * size * 4).fill(1); + const colorsTexture = new DataTexture(colorsArray, size, size, RGBAFormat, FloatType); + colorsTexture.colorSpace = ColorManagement.workingColorSpace; + this._colorsTexture = colorsTexture; + } + _initializeGeometry(reference) { + const geometry = this.geometry; + const maxVertexCount = this._maxVertexCount; + const maxIndexCount = this._maxIndexCount; + if (this._geometryInitialized === false) { + for (const attributeName in reference.attributes) { + const srcAttribute = reference.getAttribute(attributeName); + const { array, itemSize, normalized } = srcAttribute; + const dstArray = new array.constructor(maxVertexCount * itemSize); + const dstAttribute = new BufferAttribute(dstArray, itemSize, normalized); + geometry.setAttribute(attributeName, dstAttribute); + } + if (reference.getIndex() !== null) { + const indexArray = maxVertexCount > 65535 ? new Uint32Array(maxIndexCount) : new Uint16Array(maxIndexCount); + geometry.setIndex(new BufferAttribute(indexArray, 1)); + } + this._geometryInitialized = true; + } + } + _validateGeometry(geometry) { + const batchGeometry = this.geometry; + if (Boolean(geometry.getIndex()) !== Boolean(batchGeometry.getIndex())) { + throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".'); + } + for (const attributeName in batchGeometry.attributes) { + if (!geometry.hasAttribute(attributeName)) { + throw new Error(`THREE.BatchedMesh: Added geometry missing "${attributeName}". All geometries must have consistent attributes.`); + } + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + if (srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized) { + throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value."); + } + } + } + validateInstanceId(instanceId) { + const instanceInfo = this._instanceInfo; + if (instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[instanceId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.`); + } + } + validateGeometryId(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.`); + } + } + setCustomSort(func) { + this.customSort = func; + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box3; + } + const boundingBox = this.boundingBox; + const instanceInfo = this._instanceInfo; + boundingBox.makeEmpty(); + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].active === false) + continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$1); + this.getBoundingBoxAt(geometryId, _box$1).applyMatrix4(_matrix$1); + boundingBox.union(_box$1); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere; + } + const boundingSphere = this.boundingSphere; + const instanceInfo = this._instanceInfo; + boundingSphere.makeEmpty(); + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].active === false) + continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$1); + this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1); + boundingSphere.union(_sphere$2); + } + } + addInstance(geometryId) { + const atCapacity = this._instanceInfo.length >= this.maxInstanceCount; + if (atCapacity && this._availableInstanceIds.length === 0) { + throw new Error("THREE.BatchedMesh: Maximum item count reached."); + } + const instanceInfo = { + visible: true, + active: true, + geometryIndex: geometryId + }; + let drawId = null; + if (this._availableInstanceIds.length > 0) { + this._availableInstanceIds.sort(ascIdSort); + drawId = this._availableInstanceIds.shift(); + this._instanceInfo[drawId] = instanceInfo; + } else { + drawId = this._instanceInfo.length; + this._instanceInfo.push(instanceInfo); + } + const matricesTexture = this._matricesTexture; + _matrix$1.identity().toArray(matricesTexture.image.data, drawId * 16); + matricesTexture.needsUpdate = true; + const colorsTexture = this._colorsTexture; + if (colorsTexture) { + _whiteColor.toArray(colorsTexture.image.data, drawId * 4); + colorsTexture.needsUpdate = true; + } + this._visibilityChanged = true; + return drawId; + } + addGeometry(geometry, reservedVertexCount = -1, reservedIndexCount = -1) { + this._initializeGeometry(geometry); + this._validateGeometry(geometry); + const geometryInfo = { + vertexStart: -1, + vertexCount: -1, + reservedVertexCount: -1, + indexStart: -1, + indexCount: -1, + reservedIndexCount: -1, + start: -1, + count: -1, + boundingBox: null, + boundingSphere: null, + active: true + }; + const geometryInfoList = this._geometryInfo; + geometryInfo.vertexStart = this._nextVertexStart; + geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute("position").count : reservedVertexCount; + const index2 = geometry.getIndex(); + const hasIndex = index2 !== null; + if (hasIndex) { + geometryInfo.indexStart = this._nextIndexStart; + geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index2.count : reservedIndexCount; + } + if (geometryInfo.indexStart !== -1 && geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount || geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size."); + } + let geometryId; + if (this._availableGeometryIds.length > 0) { + this._availableGeometryIds.sort(ascIdSort); + geometryId = this._availableGeometryIds.shift(); + geometryInfoList[geometryId] = geometryInfo; + } else { + geometryId = this._geometryCount; + this._geometryCount++; + geometryInfoList.push(geometryInfo); + } + this.setGeometryAt(geometryId, geometry); + this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + return geometryId; + } + setGeometryAt(geometryId, geometry) { + if (geometryId >= this._geometryCount) { + throw new Error("THREE.BatchedMesh: Maximum geometry count reached."); + } + this._validateGeometry(geometry); + const batchGeometry = this.geometry; + const hasIndex = batchGeometry.getIndex() !== null; + const dstIndex = batchGeometry.getIndex(); + const srcIndex = geometry.getIndex(); + const geometryInfo = this._geometryInfo[geometryId]; + if (hasIndex && srcIndex.count > geometryInfo.reservedIndexCount || geometry.attributes.position.count > geometryInfo.reservedVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry."); + } + const vertexStart = geometryInfo.vertexStart; + const reservedVertexCount = geometryInfo.reservedVertexCount; + geometryInfo.vertexCount = geometry.getAttribute("position").count; + for (const attributeName in batchGeometry.attributes) { + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + copyAttributeData(srcAttribute, dstAttribute, vertexStart); + const itemSize = srcAttribute.itemSize; + for (let i = srcAttribute.count, l = reservedVertexCount;i < l; i++) { + const index2 = vertexStart + i; + for (let c = 0;c < itemSize; c++) { + dstAttribute.setComponent(index2, c, 0); + } + } + dstAttribute.needsUpdate = true; + dstAttribute.addUpdateRange(vertexStart * itemSize, reservedVertexCount * itemSize); + } + if (hasIndex) { + const indexStart = geometryInfo.indexStart; + const reservedIndexCount = geometryInfo.reservedIndexCount; + geometryInfo.indexCount = geometry.getIndex().count; + for (let i = 0;i < srcIndex.count; i++) { + dstIndex.setX(indexStart + i, vertexStart + srcIndex.getX(i)); + } + for (let i = srcIndex.count, l = reservedIndexCount;i < l; i++) { + dstIndex.setX(indexStart + i, vertexStart); + } + dstIndex.needsUpdate = true; + dstIndex.addUpdateRange(indexStart, geometryInfo.reservedIndexCount); + } + geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart; + geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount; + geometryInfo.boundingBox = null; + if (geometry.boundingBox !== null) { + geometryInfo.boundingBox = geometry.boundingBox.clone(); + } + geometryInfo.boundingSphere = null; + if (geometry.boundingSphere !== null) { + geometryInfo.boundingSphere = geometry.boundingSphere.clone(); + } + this._visibilityChanged = true; + return geometryId; + } + deleteGeometry(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + return this; + } + const instanceInfo = this._instanceInfo; + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].active && instanceInfo[i].geometryIndex === geometryId) { + this.deleteInstance(i); + } + } + geometryInfoList[geometryId].active = false; + this._availableGeometryIds.push(geometryId); + this._visibilityChanged = true; + return this; + } + deleteInstance(instanceId) { + this.validateInstanceId(instanceId); + this._instanceInfo[instanceId].active = false; + this._availableInstanceIds.push(instanceId); + this._visibilityChanged = true; + return this; + } + optimize() { + let nextVertexStart = 0; + let nextIndexStart = 0; + const geometryInfoList = this._geometryInfo; + const indices = geometryInfoList.map((e, i) => i).sort((a, b) => { + return geometryInfoList[a].vertexStart - geometryInfoList[b].vertexStart; + }); + const geometry = this.geometry; + for (let i = 0, l = geometryInfoList.length;i < l; i++) { + const index2 = indices[i]; + const geometryInfo = geometryInfoList[index2]; + if (geometryInfo.active === false) { + continue; + } + if (geometry.index !== null) { + if (geometryInfo.indexStart !== nextIndexStart) { + const { indexStart, vertexStart, reservedIndexCount } = geometryInfo; + const index3 = geometry.index; + const array = index3.array; + const elementDelta = nextVertexStart - vertexStart; + for (let j = indexStart;j < indexStart + reservedIndexCount; j++) { + array[j] = array[j] + elementDelta; + } + index3.array.copyWithin(nextIndexStart, indexStart, indexStart + reservedIndexCount); + index3.addUpdateRange(nextIndexStart, reservedIndexCount); + geometryInfo.indexStart = nextIndexStart; + } + nextIndexStart += geometryInfo.reservedIndexCount; + } + if (geometryInfo.vertexStart !== nextVertexStart) { + const { vertexStart, reservedVertexCount } = geometryInfo; + const attributes = geometry.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + const { array, itemSize } = attribute; + array.copyWithin(nextVertexStart * itemSize, vertexStart * itemSize, (vertexStart + reservedVertexCount) * itemSize); + attribute.addUpdateRange(nextVertexStart * itemSize, reservedVertexCount * itemSize); + } + geometryInfo.vertexStart = nextVertexStart; + } + nextVertexStart += geometryInfo.reservedVertexCount; + geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart; + this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + } + return this; + } + getBoundingBoxAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingBox === null) { + const box = new Box3; + const index2 = geometry.index; + const position2 = geometry.attributes.position; + for (let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count;i < l; i++) { + let iv = i; + if (index2) { + iv = index2.getX(iv); + } + box.expandByPoint(_vector$5.fromBufferAttribute(position2, iv)); + } + geometryInfo.boundingBox = box; + } + target.copy(geometryInfo.boundingBox); + return target; + } + getBoundingSphereAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingSphere === null) { + const sphere = new Sphere; + this.getBoundingBoxAt(geometryId, _box$1); + _box$1.getCenter(sphere.center); + const index2 = geometry.index; + const position2 = geometry.attributes.position; + let maxRadiusSq = 0; + for (let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count;i < l; i++) { + let iv = i; + if (index2) { + iv = index2.getX(iv); + } + _vector$5.fromBufferAttribute(position2, iv); + maxRadiusSq = Math.max(maxRadiusSq, sphere.center.distanceToSquared(_vector$5)); + } + sphere.radius = Math.sqrt(maxRadiusSq); + geometryInfo.boundingSphere = sphere; + } + target.copy(geometryInfo.boundingSphere); + return target; + } + setMatrixAt(instanceId, matrix) { + this.validateInstanceId(instanceId); + const matricesTexture = this._matricesTexture; + const matricesArray = this._matricesTexture.image.data; + matrix.toArray(matricesArray, instanceId * 16); + matricesTexture.needsUpdate = true; + return this; + } + getMatrixAt(instanceId, matrix) { + this.validateInstanceId(instanceId); + return matrix.fromArray(this._matricesTexture.image.data, instanceId * 16); + } + setColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + if (this._colorsTexture === null) { + this._initColorsTexture(); + } + color.toArray(this._colorsTexture.image.data, instanceId * 4); + this._colorsTexture.needsUpdate = true; + return this; + } + getColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + return color.fromArray(this._colorsTexture.image.data, instanceId * 4); + } + setVisibleAt(instanceId, value2) { + this.validateInstanceId(instanceId); + if (this._instanceInfo[instanceId].visible === value2) { + return this; + } + this._instanceInfo[instanceId].visible = value2; + this._visibilityChanged = true; + return this; + } + getVisibleAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].visible; + } + setGeometryIdAt(instanceId, geometryId) { + this.validateInstanceId(instanceId); + this.validateGeometryId(geometryId); + this._instanceInfo[instanceId].geometryIndex = geometryId; + return this; + } + getGeometryIdAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].geometryIndex; + } + getGeometryRangeAt(geometryId, target = {}) { + this.validateGeometryId(geometryId); + const geometryInfo = this._geometryInfo[geometryId]; + target.vertexStart = geometryInfo.vertexStart; + target.vertexCount = geometryInfo.vertexCount; + target.reservedVertexCount = geometryInfo.reservedVertexCount; + target.indexStart = geometryInfo.indexStart; + target.indexCount = geometryInfo.indexCount; + target.reservedIndexCount = geometryInfo.reservedIndexCount; + target.start = geometryInfo.start; + target.count = geometryInfo.count; + return target; + } + setInstanceCount(maxInstanceCount) { + const availableInstanceIds = this._availableInstanceIds; + const instanceInfo = this._instanceInfo; + availableInstanceIds.sort(ascIdSort); + while (availableInstanceIds[availableInstanceIds.length - 1] === instanceInfo.length) { + instanceInfo.pop(); + availableInstanceIds.pop(); + } + if (maxInstanceCount < instanceInfo.length) { + throw new Error(`BatchedMesh: Instance ids outside the range ${maxInstanceCount} are being used. Cannot shrink instance count.`); + } + const multiDrawCounts = new Int32Array(maxInstanceCount); + const multiDrawStarts = new Int32Array(maxInstanceCount); + copyArrayContents(this._multiDrawCounts, multiDrawCounts); + copyArrayContents(this._multiDrawStarts, multiDrawStarts); + this._multiDrawCounts = multiDrawCounts; + this._multiDrawStarts = multiDrawStarts; + this._maxInstanceCount = maxInstanceCount; + const indirectTexture = this._indirectTexture; + const matricesTexture = this._matricesTexture; + const colorsTexture = this._colorsTexture; + indirectTexture.dispose(); + this._initIndirectTexture(); + copyArrayContents(indirectTexture.image.data, this._indirectTexture.image.data); + matricesTexture.dispose(); + this._initMatricesTexture(); + copyArrayContents(matricesTexture.image.data, this._matricesTexture.image.data); + if (colorsTexture) { + colorsTexture.dispose(); + this._initColorsTexture(); + copyArrayContents(colorsTexture.image.data, this._colorsTexture.image.data); + } + } + setGeometrySize(maxVertexCount, maxIndexCount) { + const validRanges = [...this._geometryInfo].filter((info) => info.active); + const requiredVertexLength = Math.max(...validRanges.map((range) => range.vertexStart + range.reservedVertexCount)); + if (requiredVertexLength > maxVertexCount) { + throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + if (this.geometry.index) { + const requiredIndexLength = Math.max(...validRanges.map((range) => range.indexStart + range.reservedIndexCount)); + if (requiredIndexLength > maxIndexCount) { + throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + } + const oldGeometry = this.geometry; + oldGeometry.dispose(); + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + if (this._geometryInitialized) { + this._geometryInitialized = false; + this.geometry = new BufferGeometry; + this._initializeGeometry(oldGeometry); + } + const geometry = this.geometry; + if (oldGeometry.index) { + copyArrayContents(oldGeometry.index.array, geometry.index.array); + } + for (const key2 in oldGeometry.attributes) { + copyArrayContents(oldGeometry.attributes[key2].array, geometry.attributes[key2].array); + } + } + raycast(raycaster, intersects) { + const instanceInfo = this._instanceInfo; + const geometryInfoList = this._geometryInfo; + const matrixWorld = this.matrixWorld; + const batchGeometry = this.geometry; + _mesh.material = this.material; + _mesh.geometry.index = batchGeometry.index; + _mesh.geometry.attributes = batchGeometry.attributes; + if (_mesh.geometry.boundingBox === null) { + _mesh.geometry.boundingBox = new Box3; + } + if (_mesh.geometry.boundingSphere === null) { + _mesh.geometry.boundingSphere = new Sphere; + } + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (!instanceInfo[i].visible || !instanceInfo[i].active) { + continue; + } + const geometryId = instanceInfo[i].geometryIndex; + const geometryInfo = geometryInfoList[geometryId]; + _mesh.geometry.setDrawRange(geometryInfo.start, geometryInfo.count); + this.getMatrixAt(i, _mesh.matrixWorld).premultiply(matrixWorld); + this.getBoundingBoxAt(geometryId, _mesh.geometry.boundingBox); + this.getBoundingSphereAt(geometryId, _mesh.geometry.boundingSphere); + _mesh.raycast(raycaster, _batchIntersects); + for (let j = 0, l2 = _batchIntersects.length;j < l2; j++) { + const intersect = _batchIntersects[j]; + intersect.object = this; + intersect.batchId = i; + intersects.push(intersect); + } + _batchIntersects.length = 0; + } + _mesh.material = null; + _mesh.geometry.index = null; + _mesh.geometry.attributes = {}; + _mesh.geometry.setDrawRange(0, Infinity); + } + copy(source) { + super.copy(source); + this.geometry = source.geometry.clone(); + this.perObjectFrustumCulled = source.perObjectFrustumCulled; + this.sortObjects = source.sortObjects; + this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null; + this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null; + this._geometryInfo = source._geometryInfo.map((info) => ({ + ...info, + boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null, + boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null + })); + this._instanceInfo = source._instanceInfo.map((info) => ({ ...info })); + this._maxInstanceCount = source._maxInstanceCount; + this._maxVertexCount = source._maxVertexCount; + this._maxIndexCount = source._maxIndexCount; + this._geometryInitialized = source._geometryInitialized; + this._geometryCount = source._geometryCount; + this._multiDrawCounts = source._multiDrawCounts.slice(); + this._multiDrawStarts = source._multiDrawStarts.slice(); + this._matricesTexture = source._matricesTexture.clone(); + this._matricesTexture.image.data = this._matricesTexture.image.data.slice(); + if (this._colorsTexture !== null) { + this._colorsTexture = source._colorsTexture.clone(); + this._colorsTexture.image.data = this._colorsTexture.image.data.slice(); + } + return this; + } + dispose() { + this.geometry.dispose(); + this._matricesTexture.dispose(); + this._matricesTexture = null; + this._indirectTexture.dispose(); + this._indirectTexture = null; + if (this._colorsTexture !== null) { + this._colorsTexture.dispose(); + this._colorsTexture = null; + } + return this; + } + onBeforeRender(renderer2, scene, camera, geometry, material) { + if (!this._visibilityChanged && !this.perObjectFrustumCulled && !this.sortObjects) { + return; + } + const index2 = geometry.getIndex(); + const bytesPerElement = index2 === null ? 1 : index2.array.BYTES_PER_ELEMENT; + const instanceInfo = this._instanceInfo; + const multiDrawStarts = this._multiDrawStarts; + const multiDrawCounts = this._multiDrawCounts; + const geometryInfoList = this._geometryInfo; + const perObjectFrustumCulled = this.perObjectFrustumCulled; + const indirectTexture = this._indirectTexture; + const indirectArray = indirectTexture.image.data; + if (perObjectFrustumCulled) { + _matrix$1.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).multiply(this.matrixWorld); + _frustum.setFromProjectionMatrix(_matrix$1, renderer2.coordinateSystem); + } + let multiDrawCount = 0; + if (this.sortObjects) { + _matrix$1.copy(this.matrixWorld).invert(); + _vector$5.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(_matrix$1); + _forward.set(0, 0, -1).transformDirection(camera.matrixWorld).transformDirection(_matrix$1); + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$1); + this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1); + let culled = false; + if (perObjectFrustumCulled) { + culled = !_frustum.intersectsSphere(_sphere$2); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + const z = _temp.subVectors(_sphere$2.center, _vector$5).dot(_forward); + _renderList.push(geometryInfo.start, geometryInfo.count, z, i); + } + } + } + const list = _renderList.list; + const customSort = this.customSort; + if (customSort === null) { + list.sort(material.transparent ? sortTransparent : sortOpaque); + } else { + customSort.call(this, list, camera); + } + for (let i = 0, l = list.length;i < l; i++) { + const item = list[i]; + multiDrawStarts[multiDrawCount] = item.start * bytesPerElement; + multiDrawCounts[multiDrawCount] = item.count; + indirectArray[multiDrawCount] = item.index; + multiDrawCount++; + } + _renderList.reset(); + } else { + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + let culled = false; + if (perObjectFrustumCulled) { + this.getMatrixAt(i, _matrix$1); + this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1); + culled = !_frustum.intersectsSphere(_sphere$2); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + multiDrawStarts[multiDrawCount] = geometryInfo.start * bytesPerElement; + multiDrawCounts[multiDrawCount] = geometryInfo.count; + indirectArray[multiDrawCount] = i; + multiDrawCount++; + } + } + } + } + indirectTexture.needsUpdate = true; + this._multiDrawCount = multiDrawCount; + this._visibilityChanged = false; + } + onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial) { + this.onBeforeRender(renderer2, null, shadowCamera, geometry, depthMaterial); + } +} + +class LineBasicMaterial extends Material { + constructor(parameters) { + super(); + this.isLineBasicMaterial = true; + this.type = "LineBasicMaterial"; + this.color = new Color(16777215); + this.map = null; + this.linewidth = 1; + this.linecap = "round"; + this.linejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + this.fog = source.fog; + return this; + } +} +var _vStart = /* @__PURE__ */ new Vector3; +var _vEnd = /* @__PURE__ */ new Vector3; +var _inverseMatrix$1 = /* @__PURE__ */ new Matrix4; +var _ray$1 = /* @__PURE__ */ new Ray; +var _sphere$1 = /* @__PURE__ */ new Sphere; +var _intersectPointOnRay = /* @__PURE__ */ new Vector3; +var _intersectPointOnSegment = /* @__PURE__ */ new Vector3; + +class Line extends Object3D { + constructor(geometry = new BufferGeometry, material = new LineBasicMaterial) { + super(); + this.isLine = true; + this.type = "Line"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = [0]; + for (let i = 1, l = positionAttribute.count;i < l; i++) { + _vStart.fromBufferAttribute(positionAttribute, i - 1); + _vEnd.fromBufferAttribute(positionAttribute, i); + lineDistances[i] = lineDistances[i - 1]; + lineDistances[i] += _vStart.distanceTo(_vEnd); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1)); + } else { + console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + raycast(raycaster, intersects) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$1.copy(geometry.boundingSphere); + _sphere$1.applyMatrix4(matrixWorld); + _sphere$1.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere$1) === false) + return; + _inverseMatrix$1.copy(matrixWorld).invert(); + _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const step = this.isLineSegments ? 2 : 1; + const index2 = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index2 !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, l = end - 1;i < l; i += step) { + const a = index2.getX(i); + const b = index2.getX(i + 1); + const intersect = checkIntersection(this, raycaster, _ray$1, localThresholdSq, a, b, i); + if (intersect) { + intersects.push(intersect); + } + } + if (this.isLineLoop) { + const a = index2.getX(end - 1); + const b = index2.getX(start); + const intersect = checkIntersection(this, raycaster, _ray$1, localThresholdSq, a, b, end - 1); + if (intersect) { + intersects.push(intersect); + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l = end - 1;i < l; i += step) { + const intersect = checkIntersection(this, raycaster, _ray$1, localThresholdSq, i, i + 1, i); + if (intersect) { + intersects.push(intersect); + } + } + if (this.isLineLoop) { + const intersect = checkIntersection(this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1); + if (intersect) { + intersects.push(intersect); + } + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } +} +function checkIntersection(object, raycaster, ray, thresholdSq, a, b, i) { + const positionAttribute = object.geometry.attributes.position; + _vStart.fromBufferAttribute(positionAttribute, a); + _vEnd.fromBufferAttribute(positionAttribute, b); + const distSq = ray.distanceSqToSegment(_vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment); + if (distSq > thresholdSq) + return; + _intersectPointOnRay.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectPointOnRay); + if (distance < raycaster.near || distance > raycaster.far) + return; + return { + distance, + point: _intersectPointOnSegment.clone().applyMatrix4(object.matrixWorld), + index: i, + face: null, + faceIndex: null, + barycoord: null, + object + }; +} +var _start = /* @__PURE__ */ new Vector3; +var _end = /* @__PURE__ */ new Vector3; + +class LineSegments extends Line { + constructor(geometry, material) { + super(geometry, material); + this.isLineSegments = true; + this.type = "LineSegments"; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + for (let i = 0, l = positionAttribute.count;i < l; i += 2) { + _start.fromBufferAttribute(positionAttribute, i); + _end.fromBufferAttribute(positionAttribute, i + 1); + lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1]; + lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1)); + } else { + console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } +} + +class LineLoop extends Line { + constructor(geometry, material) { + super(geometry, material); + this.isLineLoop = true; + this.type = "LineLoop"; + } +} + +class PointsMaterial extends Material { + constructor(parameters) { + super(); + this.isPointsMaterial = true; + this.type = "PointsMaterial"; + this.color = new Color(16777215); + this.map = null; + this.alphaMap = null; + this.size = 1; + this.sizeAttenuation = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } +} +var _inverseMatrix = /* @__PURE__ */ new Matrix4; +var _ray = /* @__PURE__ */ new Ray; +var _sphere = /* @__PURE__ */ new Sphere; +var _position$2 = /* @__PURE__ */ new Vector3; + +class Points extends Object3D { + constructor(geometry = new BufferGeometry, material = new PointsMaterial) { + super(); + this.isPoints = true; + this.type = "Points"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + raycast(raycaster, intersects) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere.copy(geometry.boundingSphere); + _sphere.applyMatrix4(matrixWorld); + _sphere.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere) === false) + return; + _inverseMatrix.copy(matrixWorld).invert(); + _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const index2 = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index2 !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i++) { + const a = index2.getX(i); + _position$2.fromBufferAttribute(positionAttribute, a); + testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this); + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l = end;i < l; i++) { + _position$2.fromBufferAttribute(positionAttribute, i); + testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this); + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } +} +function testPoint(point, index2, localThresholdSq, matrixWorld, raycaster, intersects, object) { + const rayPointDistanceSq = _ray.distanceSqToPoint(point); + if (rayPointDistanceSq < localThresholdSq) { + const intersectPoint = new Vector3; + _ray.closestPointToPoint(point, intersectPoint); + intersectPoint.applyMatrix4(matrixWorld); + const distance = raycaster.ray.origin.distanceTo(intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) + return; + intersects.push({ + distance, + distanceToRay: Math.sqrt(rayPointDistanceSq), + point: intersectPoint, + index: index2, + face: null, + faceIndex: null, + barycoord: null, + object + }); + } +} + +class VideoTexture extends Texture { + constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoTexture = true; + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.generateMipmaps = false; + const scope = this; + function updateVideo() { + scope.needsUpdate = true; + video.requestVideoFrameCallback(updateVideo); + } + if ("requestVideoFrameCallback" in video) { + video.requestVideoFrameCallback(updateVideo); + } + } + clone() { + return new this.constructor(this.image).copy(this); + } + update() { + const video = this.image; + const hasVideoFrameCallback = "requestVideoFrameCallback" in video; + if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) { + this.needsUpdate = true; + } + } +} + +class VideoFrameTexture extends VideoTexture { + constructor(mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super({}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoFrameTexture = true; + } + update() { + } + clone() { + return new this.constructor().copy(this); + } + setFrame(frame) { + this.image = frame; + this.needsUpdate = true; + } +} + +class FramebufferTexture extends Texture { + constructor(width2, height2) { + super({ width: width2, height: height2 }); + this.isFramebufferTexture = true; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.generateMipmaps = false; + this.needsUpdate = true; + } +} + +class CompressedTexture extends Texture { + constructor(mipmaps, width2, height2, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCompressedTexture = true; + this.image = { width: width2, height: height2 }; + this.mipmaps = mipmaps; + this.flipY = false; + this.generateMipmaps = false; + } +} + +class CompressedArrayTexture extends CompressedTexture { + constructor(mipmaps, width2, height2, depth, format, type) { + super(mipmaps, width2, height2, format, type); + this.isCompressedArrayTexture = true; + this.image.depth = depth; + this.wrapR = ClampToEdgeWrapping; + this.layerUpdates = new Set; + } + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + clearLayerUpdates() { + this.layerUpdates.clear(); + } +} + +class CompressedCubeTexture extends CompressedTexture { + constructor(images, format, type) { + super(undefined, images[0].width, images[0].height, format, type, CubeReflectionMapping); + this.isCompressedCubeTexture = true; + this.isCubeTexture = true; + this.image = images; + } +} + +class CanvasTexture extends Texture { + constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isCanvasTexture = true; + this.needsUpdate = true; + } +} + +class DepthTexture extends Texture { + constructor(width2, height2, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat) { + if (format !== DepthFormat && format !== DepthStencilFormat) { + throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); + } + if (type === undefined && format === DepthFormat) + type = UnsignedIntType; + if (type === undefined && format === DepthStencilFormat) + type = UnsignedInt248Type; + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isDepthTexture = true; + this.image = { width: width2, height: height2 }; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + this.flipY = false; + this.generateMipmaps = false; + this.compareFunction = null; + } + copy(source) { + super.copy(source); + this.compareFunction = source.compareFunction; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + if (this.compareFunction !== null) + data2.compareFunction = this.compareFunction; + return data2; + } +} + +class Curve { + constructor() { + this.type = "Curve"; + this.arcLengthDivisions = 200; + } + getPoint() { + console.warn("THREE.Curve: .getPoint() not implemented."); + return null; + } + getPointAt(u, optionalTarget) { + const t = this.getUtoTmapping(u); + return this.getPoint(t, optionalTarget); + } + getPoints(divisions = 5) { + const points = []; + for (let d = 0;d <= divisions; d++) { + points.push(this.getPoint(d / divisions)); + } + return points; + } + getSpacedPoints(divisions = 5) { + const points = []; + for (let d = 0;d <= divisions; d++) { + points.push(this.getPointAt(d / divisions)); + } + return points; + } + getLength() { + const lengths = this.getLengths(); + return lengths[lengths.length - 1]; + } + getLengths(divisions = this.arcLengthDivisions) { + if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) { + return this.cacheArcLengths; + } + this.needsUpdate = false; + const cache = []; + let current, last2 = this.getPoint(0); + let sum2 = 0; + cache.push(0); + for (let p = 1;p <= divisions; p++) { + current = this.getPoint(p / divisions); + sum2 += current.distanceTo(last2); + cache.push(sum2); + last2 = current; + } + this.cacheArcLengths = cache; + return cache; + } + updateArcLengths() { + this.needsUpdate = true; + this.getLengths(); + } + getUtoTmapping(u, distance) { + const arcLengths = this.getLengths(); + let i = 0; + const il = arcLengths.length; + let targetArcLength; + if (distance) { + targetArcLength = distance; + } else { + targetArcLength = u * arcLengths[il - 1]; + } + let low = 0, high = il - 1, comparison; + while (low <= high) { + i = Math.floor(low + (high - low) / 2); + comparison = arcLengths[i] - targetArcLength; + if (comparison < 0) { + low = i + 1; + } else if (comparison > 0) { + high = i - 1; + } else { + high = i; + break; + } + } + i = high; + if (arcLengths[i] === targetArcLength) { + return i / (il - 1); + } + const lengthBefore = arcLengths[i]; + const lengthAfter = arcLengths[i + 1]; + const segmentLength = lengthAfter - lengthBefore; + const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; + const t = (i + segmentFraction) / (il - 1); + return t; + } + getTangent(t, optionalTarget) { + const delta = 0.0001; + let t1 = t - delta; + let t2 = t + delta; + if (t1 < 0) + t1 = 0; + if (t2 > 1) + t2 = 1; + const pt1 = this.getPoint(t1); + const pt2 = this.getPoint(t2); + const tangent = optionalTarget || (pt1.isVector2 ? new Vector2 : new Vector3); + tangent.copy(pt2).sub(pt1).normalize(); + return tangent; + } + getTangentAt(u, optionalTarget) { + const t = this.getUtoTmapping(u); + return this.getTangent(t, optionalTarget); + } + computeFrenetFrames(segments, closed) { + const normal = new Vector3; + const tangents = []; + const normals = []; + const binormals = []; + const vec = new Vector3; + const mat = new Matrix4; + for (let i = 0;i <= segments; i++) { + const u = i / segments; + tangents[i] = this.getTangentAt(u, new Vector3); + } + normals[0] = new Vector3; + binormals[0] = new Vector3; + let min = Number.MAX_VALUE; + const tx = Math.abs(tangents[0].x); + const ty = Math.abs(tangents[0].y); + const tz = Math.abs(tangents[0].z); + if (tx <= min) { + min = tx; + normal.set(1, 0, 0); + } + if (ty <= min) { + min = ty; + normal.set(0, 1, 0); + } + if (tz <= min) { + normal.set(0, 0, 1); + } + vec.crossVectors(tangents[0], normal).normalize(); + normals[0].crossVectors(tangents[0], vec); + binormals[0].crossVectors(tangents[0], normals[0]); + for (let i = 1;i <= segments; i++) { + normals[i] = normals[i - 1].clone(); + binormals[i] = binormals[i - 1].clone(); + vec.crossVectors(tangents[i - 1], tangents[i]); + if (vec.length() > Number.EPSILON) { + vec.normalize(); + const theta = Math.acos(clamp2(tangents[i - 1].dot(tangents[i]), -1, 1)); + normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta)); + } + binormals[i].crossVectors(tangents[i], normals[i]); + } + if (closed === true) { + let theta = Math.acos(clamp2(normals[0].dot(normals[segments]), -1, 1)); + theta /= segments; + if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) { + theta = -theta; + } + for (let i = 1;i <= segments; i++) { + normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i)); + binormals[i].crossVectors(tangents[i], normals[i]); + } + } + return { + tangents, + normals, + binormals + }; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.arcLengthDivisions = source.arcLengthDivisions; + return this; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "Curve", + generator: "Curve.toJSON" + } + }; + data2.arcLengthDivisions = this.arcLengthDivisions; + data2.type = this.type; + return data2; + } + fromJSON(json) { + this.arcLengthDivisions = json.arcLengthDivisions; + return this; + } +} + +class EllipseCurve extends Curve { + constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) { + super(); + this.isEllipseCurve = true; + this.type = "EllipseCurve"; + this.aX = aX; + this.aY = aY; + this.xRadius = xRadius; + this.yRadius = yRadius; + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; + this.aClockwise = aClockwise; + this.aRotation = aRotation; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs(deltaAngle) < Number.EPSILON; + while (deltaAngle < 0) + deltaAngle += twoPi; + while (deltaAngle > twoPi) + deltaAngle -= twoPi; + if (deltaAngle < Number.EPSILON) { + if (samePoints) { + deltaAngle = 0; + } else { + deltaAngle = twoPi; + } + } + if (this.aClockwise === true && !samePoints) { + if (deltaAngle === twoPi) { + deltaAngle = -twoPi; + } else { + deltaAngle = deltaAngle - twoPi; + } + } + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos(angle); + let y = this.aY + this.yRadius * Math.sin(angle); + if (this.aRotation !== 0) { + const cos = Math.cos(this.aRotation); + const sin = Math.sin(this.aRotation); + const tx = x - this.aX; + const ty = y - this.aY; + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; + } + return point.set(x, y); + } + copy(source) { + super.copy(source); + this.aX = source.aX; + this.aY = source.aY; + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + this.aClockwise = source.aClockwise; + this.aRotation = source.aRotation; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.aX = this.aX; + data2.aY = this.aY; + data2.xRadius = this.xRadius; + data2.yRadius = this.yRadius; + data2.aStartAngle = this.aStartAngle; + data2.aEndAngle = this.aEndAngle; + data2.aClockwise = this.aClockwise; + data2.aRotation = this.aRotation; + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.aX = json.aX; + this.aY = json.aY; + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + this.aClockwise = json.aClockwise; + this.aRotation = json.aRotation; + return this; + } +} + +class ArcCurve extends EllipseCurve { + constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + this.isArcCurve = true; + this.type = "ArcCurve"; + } +} +function CubicPoly() { + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + function init(x0, x1, t0, t1) { + c0 = x0; + c1 = t0; + c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + } + return { + initCatmullRom: function(x0, x1, x2, x3, tension) { + init(x1, x2, tension * (x2 - x0), tension * (x3 - x1)); + }, + initNonuniformCatmullRom: function(x0, x1, x2, x3, dt0, dt1, dt2) { + let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1; + let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; + t1 *= dt1; + t2 *= dt1; + init(x1, x2, t1, t2); + }, + calc: function(t) { + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; + } + }; +} +var tmp = /* @__PURE__ */ new Vector3; +var px = /* @__PURE__ */ new CubicPoly; +var py = /* @__PURE__ */ new CubicPoly; +var pz = /* @__PURE__ */ new CubicPoly; + +class CatmullRomCurve3 extends Curve { + constructor(points = [], closed = false, curveType = "centripetal", tension = 0.5) { + super(); + this.isCatmullRomCurve3 = true; + this.type = "CatmullRomCurve3"; + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + } + getPoint(t, optionalTarget = new Vector3) { + const point = optionalTarget; + const points = this.points; + const l = points.length; + const p = (l - (this.closed ? 0 : 1)) * t; + let intPoint = Math.floor(p); + let weight = p - intPoint; + if (this.closed) { + intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l; + } else if (weight === 0 && intPoint === l - 1) { + intPoint = l - 2; + weight = 1; + } + let p0, p3; + if (this.closed || intPoint > 0) { + p0 = points[(intPoint - 1) % l]; + } else { + tmp.subVectors(points[0], points[1]).add(points[0]); + p0 = tmp; + } + const p1 = points[intPoint % l]; + const p2 = points[(intPoint + 1) % l]; + if (this.closed || intPoint + 2 < l) { + p3 = points[(intPoint + 2) % l]; + } else { + tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]); + p3 = tmp; + } + if (this.curveType === "centripetal" || this.curveType === "chordal") { + const pow = this.curveType === "chordal" ? 0.5 : 0.25; + let dt0 = Math.pow(p0.distanceToSquared(p1), pow); + let dt1 = Math.pow(p1.distanceToSquared(p2), pow); + let dt2 = Math.pow(p2.distanceToSquared(p3), pow); + if (dt1 < 0.0001) + dt1 = 1; + if (dt0 < 0.0001) + dt0 = dt1; + if (dt2 < 0.0001) + dt2 = dt1; + px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2); + py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2); + pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2); + } else if (this.curveType === "catmullrom") { + px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension); + py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension); + pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension); + } + point.set(px.calc(weight), py.calc(weight), pz.calc(weight)); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l = source.points.length;i < l; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.points = []; + for (let i = 0, l = this.points.length;i < l; i++) { + const point = this.points[i]; + data2.points.push(point.toArray()); + } + data2.closed = this.closed; + data2.curveType = this.curveType; + data2.tension = this.tension; + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l = json.points.length;i < l; i++) { + const point = json.points[i]; + this.points.push(new Vector3().fromArray(point)); + } + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + return this; + } +} +function CatmullRom(t, p0, p1, p2, p3) { + const v0 = (p2 - p0) * 0.5; + const v1 = (p3 - p1) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; +} +function QuadraticBezierP0(t, p) { + const k = 1 - t; + return k * k * p; +} +function QuadraticBezierP1(t, p) { + return 2 * (1 - t) * t * p; +} +function QuadraticBezierP2(t, p) { + return t * t * p; +} +function QuadraticBezier(t, p0, p1, p2) { + return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2); +} +function CubicBezierP0(t, p) { + const k = 1 - t; + return k * k * k * p; +} +function CubicBezierP1(t, p) { + const k = 1 - t; + return 3 * k * k * t * p; +} +function CubicBezierP2(t, p) { + return 3 * (1 - t) * t * t * p; +} +function CubicBezierP3(t, p) { + return t * t * t * p; +} +function CubicBezier(t, p0, p1, p2, p3) { + return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3); +} + +class CubicBezierCurve extends Curve { + constructor(v0 = new Vector2, v1 = new Vector2, v2 = new Vector2, v3 = new Vector2) { + super(); + this.isCubicBezierCurve = true; + this.type = "CubicBezierCurve"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + data2.v3 = this.v3.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } +} + +class CubicBezierCurve3 extends Curve { + constructor(v0 = new Vector3, v1 = new Vector3, v2 = new Vector3, v3 = new Vector3) { + super(); + this.isCubicBezierCurve3 = true; + this.type = "CubicBezierCurve3"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + } + getPoint(t, optionalTarget = new Vector3) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + data2.v3 = this.v3.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } +} + +class LineCurve extends Curve { + constructor(v1 = new Vector2, v2 = new Vector2) { + super(); + this.isLineCurve = true; + this.type = "LineCurve"; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + if (t === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t).add(this.v1); + } + return point; + } + getPointAt(u, optionalTarget) { + return this.getPoint(u, optionalTarget); + } + getTangent(t, optionalTarget = new Vector2) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u, optionalTarget) { + return this.getTangent(u, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } +} + +class LineCurve3 extends Curve { + constructor(v1 = new Vector3, v2 = new Vector3) { + super(); + this.isLineCurve3 = true; + this.type = "LineCurve3"; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector3) { + const point = optionalTarget; + if (t === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t).add(this.v1); + } + return point; + } + getPointAt(u, optionalTarget) { + return this.getPoint(u, optionalTarget); + } + getTangent(t, optionalTarget = new Vector3) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u, optionalTarget) { + return this.getTangent(u, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } +} + +class QuadraticBezierCurve extends Curve { + constructor(v0 = new Vector2, v1 = new Vector2, v2 = new Vector2) { + super(); + this.isQuadraticBezierCurve = true; + this.type = "QuadraticBezierCurve"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } +} + +class QuadraticBezierCurve3 extends Curve { + constructor(v0 = new Vector3, v1 = new Vector3, v2 = new Vector3) { + super(); + this.isQuadraticBezierCurve3 = true; + this.type = "QuadraticBezierCurve3"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector3) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } +} + +class SplineCurve extends Curve { + constructor(points = []) { + super(); + this.isSplineCurve = true; + this.type = "SplineCurve"; + this.points = points; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + const points = this.points; + const p = (points.length - 1) * t; + const intPoint = Math.floor(p); + const weight = p - intPoint; + const p0 = points[intPoint === 0 ? intPoint : intPoint - 1]; + const p1 = points[intPoint]; + const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1]; + const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2]; + point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y)); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l = source.points.length;i < l; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.points = []; + for (let i = 0, l = this.points.length;i < l; i++) { + const point = this.points[i]; + data2.points.push(point.toArray()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l = json.points.length;i < l; i++) { + const point = json.points[i]; + this.points.push(new Vector2().fromArray(point)); + } + return this; + } +} +var Curves = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ArcCurve, + CatmullRomCurve3, + CubicBezierCurve, + CubicBezierCurve3, + EllipseCurve, + LineCurve, + LineCurve3, + QuadraticBezierCurve, + QuadraticBezierCurve3, + SplineCurve +}); + +class CurvePath extends Curve { + constructor() { + super(); + this.type = "CurvePath"; + this.curves = []; + this.autoClose = false; + } + add(curve) { + this.curves.push(curve); + } + closePath() { + const startPoint = this.curves[0].getPoint(0); + const endPoint = this.curves[this.curves.length - 1].getPoint(1); + if (!startPoint.equals(endPoint)) { + const lineType = startPoint.isVector2 === true ? "LineCurve" : "LineCurve3"; + this.curves.push(new Curves[lineType](endPoint, startPoint)); + } + return this; + } + getPoint(t, optionalTarget) { + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + while (i < curveLengths.length) { + if (curveLengths[i] >= d) { + const diff = curveLengths[i] - d; + const curve = this.curves[i]; + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + return curve.getPointAt(u, optionalTarget); + } + i++; + } + return null; + } + getLength() { + const lens = this.getCurveLengths(); + return lens[lens.length - 1]; + } + updateArcLengths() { + this.needsUpdate = true; + this.cacheLengths = null; + this.getCurveLengths(); + } + getCurveLengths() { + if (this.cacheLengths && this.cacheLengths.length === this.curves.length) { + return this.cacheLengths; + } + const lengths = []; + let sums = 0; + for (let i = 0, l = this.curves.length;i < l; i++) { + sums += this.curves[i].getLength(); + lengths.push(sums); + } + this.cacheLengths = lengths; + return lengths; + } + getSpacedPoints(divisions = 40) { + const points = []; + for (let i = 0;i <= divisions; i++) { + points.push(this.getPoint(i / divisions)); + } + if (this.autoClose) { + points.push(points[0]); + } + return points; + } + getPoints(divisions = 12) { + const points = []; + let last2; + for (let i = 0, curves = this.curves;i < curves.length; i++) { + const curve = curves[i]; + const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions; + const pts = curve.getPoints(resolution); + for (let j = 0;j < pts.length; j++) { + const point = pts[j]; + if (last2 && last2.equals(point)) + continue; + points.push(point); + last2 = point; + } + } + if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) { + points.push(points[0]); + } + return points; + } + copy(source) { + super.copy(source); + this.curves = []; + for (let i = 0, l = source.curves.length;i < l; i++) { + const curve = source.curves[i]; + this.curves.push(curve.clone()); + } + this.autoClose = source.autoClose; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.autoClose = this.autoClose; + data2.curves = []; + for (let i = 0, l = this.curves.length;i < l; i++) { + const curve = this.curves[i]; + data2.curves.push(curve.toJSON()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.autoClose = json.autoClose; + this.curves = []; + for (let i = 0, l = json.curves.length;i < l; i++) { + const curve = json.curves[i]; + this.curves.push(new Curves[curve.type]().fromJSON(curve)); + } + return this; + } +} + +class Path extends CurvePath { + constructor(points) { + super(); + this.type = "Path"; + this.currentPoint = new Vector2; + if (points) { + this.setFromPoints(points); + } + } + setFromPoints(points) { + this.moveTo(points[0].x, points[0].y); + for (let i = 1, l = points.length;i < l; i++) { + this.lineTo(points[i].x, points[i].y); + } + return this; + } + moveTo(x, y) { + this.currentPoint.set(x, y); + return this; + } + lineTo(x, y) { + const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y)); + this.curves.push(curve); + this.currentPoint.set(x, y); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY)); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY)); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + splineThru(pts) { + const npts = [this.currentPoint.clone()].concat(pts); + const curve = new SplineCurve(npts); + this.curves.push(curve); + this.currentPoint.copy(pts[pts.length - 1]); + return this; + } + arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + return this; + } + absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + if (this.curves.length > 0) { + const firstPoint = curve.getPoint(0); + if (!firstPoint.equals(this.currentPoint)) { + this.lineTo(firstPoint.x, firstPoint.y); + } + } + this.curves.push(curve); + const lastPoint = curve.getPoint(1); + this.currentPoint.copy(lastPoint); + return this; + } + copy(source) { + super.copy(source); + this.currentPoint.copy(source.currentPoint); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.currentPoint = this.currentPoint.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.currentPoint.fromArray(json.currentPoint); + return this; + } +} + +class LatheGeometry extends BufferGeometry { + constructor(points = [new Vector2(0, -0.5), new Vector2(0.5, 0), new Vector2(0, 0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) { + super(); + this.type = "LatheGeometry"; + this.parameters = { + points, + segments, + phiStart, + phiLength + }; + segments = Math.floor(segments); + phiLength = clamp2(phiLength, 0, Math.PI * 2); + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; + const inverseSegments = 1 / segments; + const vertex = new Vector3; + const uv = new Vector2; + const normal = new Vector3; + const curNormal = new Vector3; + const prevNormal = new Vector3; + let dx = 0; + let dy = 0; + for (let j = 0;j <= points.length - 1; j++) { + switch (j) { + case 0: + dx = points[j + 1].x - points[j].x; + dy = points[j + 1].y - points[j].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + prevNormal.copy(normal); + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + break; + case points.length - 1: + initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z); + break; + default: + dx = points[j + 1].x - points[j].x; + dy = points[j + 1].y - points[j].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + curNormal.copy(normal); + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + prevNormal.copy(curNormal); + } + } + for (let i = 0;i <= segments; i++) { + const phi = phiStart + i * inverseSegments * phiLength; + const sin = Math.sin(phi); + const cos = Math.cos(phi); + for (let j = 0;j <= points.length - 1; j++) { + vertex.x = points[j].x * sin; + vertex.y = points[j].y; + vertex.z = points[j].x * cos; + vertices.push(vertex.x, vertex.y, vertex.z); + uv.x = i / segments; + uv.y = j / (points.length - 1); + uvs.push(uv.x, uv.y); + const x = initNormals[3 * j + 0] * sin; + const y = initNormals[3 * j + 1]; + const z = initNormals[3 * j + 0] * cos; + normals.push(x, y, z); + } + } + for (let i = 0;i < segments; i++) { + for (let j = 0;j < points.length - 1; j++) { + const base = j + i * points.length; + const a = base; + const b = base + points.length; + const c = base + points.length + 1; + const d = base + 1; + indices.push(a, b, d); + indices.push(c, d, b); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new LatheGeometry(data2.points, data2.segments, data2.phiStart, data2.phiLength); + } +} + +class CapsuleGeometry extends LatheGeometry { + constructor(radius = 1, length2 = 1, capSegments = 4, radialSegments = 8) { + const path = new Path; + path.absarc(0, -length2 / 2, radius, Math.PI * 1.5, 0); + path.absarc(0, length2 / 2, radius, 0, Math.PI * 0.5); + super(path.getPoints(capSegments), radialSegments); + this.type = "CapsuleGeometry"; + this.parameters = { + radius, + length: length2, + capSegments, + radialSegments + }; + } + static fromJSON(data2) { + return new CapsuleGeometry(data2.radius, data2.length, data2.capSegments, data2.radialSegments); + } +} + +class CircleGeometry extends BufferGeometry { + constructor(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CircleGeometry"; + this.parameters = { + radius, + segments, + thetaStart, + thetaLength + }; + segments = Math.max(3, segments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex = new Vector3; + const uv = new Vector2; + vertices.push(0, 0, 0); + normals.push(0, 0, 1); + uvs.push(0.5, 0.5); + for (let s = 0, i = 3;s <= segments; s++, i += 3) { + const segment = thetaStart + s / segments * thetaLength; + vertex.x = radius * Math.cos(segment); + vertex.y = radius * Math.sin(segment); + vertices.push(vertex.x, vertex.y, vertex.z); + normals.push(0, 0, 1); + uv.x = (vertices[i] / radius + 1) / 2; + uv.y = (vertices[i + 1] / radius + 1) / 2; + uvs.push(uv.x, uv.y); + } + for (let i = 1;i <= segments; i++) { + indices.push(i, i + 1, 0); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new CircleGeometry(data2.radius, data2.segments, data2.thetaStart, data2.thetaLength); + } +} + +class CylinderGeometry extends BufferGeometry { + constructor(radiusTop = 1, radiusBottom = 1, height2 = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CylinderGeometry"; + this.parameters = { + radiusTop, + radiusBottom, + height: height2, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + const scope = this; + radialSegments = Math.floor(radialSegments); + heightSegments = Math.floor(heightSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let index2 = 0; + const indexArray = []; + const halfHeight = height2 / 2; + let groupStart = 0; + generateTorso(); + if (openEnded === false) { + if (radiusTop > 0) + generateCap(true); + if (radiusBottom > 0) + generateCap(false); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function generateTorso() { + const normal = new Vector3; + const vertex = new Vector3; + let groupCount = 0; + const slope = (radiusBottom - radiusTop) / height2; + for (let y = 0;y <= heightSegments; y++) { + const indexRow = []; + const v = y / heightSegments; + const radius = v * (radiusBottom - radiusTop) + radiusTop; + for (let x = 0;x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const sinTheta = Math.sin(theta); + const cosTheta = Math.cos(theta); + vertex.x = radius * sinTheta; + vertex.y = -v * height2 + halfHeight; + vertex.z = radius * cosTheta; + vertices.push(vertex.x, vertex.y, vertex.z); + normal.set(sinTheta, slope, cosTheta).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u, 1 - v); + indexRow.push(index2++); + } + indexArray.push(indexRow); + } + for (let x = 0;x < radialSegments; x++) { + for (let y = 0;y < heightSegments; y++) { + const a = indexArray[y][x]; + const b = indexArray[y + 1][x]; + const c = indexArray[y + 1][x + 1]; + const d = indexArray[y][x + 1]; + if (radiusTop > 0 || y !== 0) { + indices.push(a, b, d); + groupCount += 3; + } + if (radiusBottom > 0 || y !== heightSegments - 1) { + indices.push(b, c, d); + groupCount += 3; + } + } + } + scope.addGroup(groupStart, groupCount, 0); + groupStart += groupCount; + } + function generateCap(top) { + const centerIndexStart = index2; + const uv = new Vector2; + const vertex = new Vector3; + let groupCount = 0; + const radius = top === true ? radiusTop : radiusBottom; + const sign = top === true ? 1 : -1; + for (let x = 1;x <= radialSegments; x++) { + vertices.push(0, halfHeight * sign, 0); + normals.push(0, sign, 0); + uvs.push(0.5, 0.5); + index2++; + } + const centerIndexEnd = index2; + for (let x = 0;x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const cosTheta = Math.cos(theta); + const sinTheta = Math.sin(theta); + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.push(vertex.x, vertex.y, vertex.z); + normals.push(0, sign, 0); + uv.x = cosTheta * 0.5 + 0.5; + uv.y = sinTheta * 0.5 * sign + 0.5; + uvs.push(uv.x, uv.y); + index2++; + } + for (let x = 0;x < radialSegments; x++) { + const c = centerIndexStart + x; + const i = centerIndexEnd + x; + if (top === true) { + indices.push(i, i + 1, c); + } else { + indices.push(i + 1, i, c); + } + groupCount += 3; + } + scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); + groupStart += groupCount; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new CylinderGeometry(data2.radiusTop, data2.radiusBottom, data2.height, data2.radialSegments, data2.heightSegments, data2.openEnded, data2.thetaStart, data2.thetaLength); + } +} + +class ConeGeometry extends CylinderGeometry { + constructor(radius = 1, height2 = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(0, radius, height2, radialSegments, heightSegments, openEnded, thetaStart, thetaLength); + this.type = "ConeGeometry"; + this.parameters = { + radius, + height: height2, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + } + static fromJSON(data2) { + return new ConeGeometry(data2.radius, data2.height, data2.radialSegments, data2.heightSegments, data2.openEnded, data2.thetaStart, data2.thetaLength); + } +} + +class PolyhedronGeometry extends BufferGeometry { + constructor(vertices = [], indices = [], radius = 1, detail = 0) { + super(); + this.type = "PolyhedronGeometry"; + this.parameters = { + vertices, + indices, + radius, + detail + }; + const vertexBuffer = []; + const uvBuffer = []; + subdivide(detail); + applyRadius(radius); + generateUVs(); + this.setAttribute("position", new Float32BufferAttribute(vertexBuffer, 3)); + this.setAttribute("normal", new Float32BufferAttribute(vertexBuffer.slice(), 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvBuffer, 2)); + if (detail === 0) { + this.computeVertexNormals(); + } else { + this.normalizeNormals(); + } + function subdivide(detail2) { + const a = new Vector3; + const b = new Vector3; + const c = new Vector3; + for (let i = 0;i < indices.length; i += 3) { + getVertexByIndex(indices[i + 0], a); + getVertexByIndex(indices[i + 1], b); + getVertexByIndex(indices[i + 2], c); + subdivideFace(a, b, c, detail2); + } + } + function subdivideFace(a, b, c, detail2) { + const cols = detail2 + 1; + const v = []; + for (let i = 0;i <= cols; i++) { + v[i] = []; + const aj = a.clone().lerp(c, i / cols); + const bj = b.clone().lerp(c, i / cols); + const rows = cols - i; + for (let j = 0;j <= rows; j++) { + if (j === 0 && i === cols) { + v[i][j] = aj; + } else { + v[i][j] = aj.clone().lerp(bj, j / rows); + } + } + } + for (let i = 0;i < cols; i++) { + for (let j = 0;j < 2 * (cols - i) - 1; j++) { + const k = Math.floor(j / 2); + if (j % 2 === 0) { + pushVertex(v[i][k + 1]); + pushVertex(v[i + 1][k]); + pushVertex(v[i][k]); + } else { + pushVertex(v[i][k + 1]); + pushVertex(v[i + 1][k + 1]); + pushVertex(v[i + 1][k]); + } + } + } + } + function applyRadius(radius2) { + const vertex = new Vector3; + for (let i = 0;i < vertexBuffer.length; i += 3) { + vertex.x = vertexBuffer[i + 0]; + vertex.y = vertexBuffer[i + 1]; + vertex.z = vertexBuffer[i + 2]; + vertex.normalize().multiplyScalar(radius2); + vertexBuffer[i + 0] = vertex.x; + vertexBuffer[i + 1] = vertex.y; + vertexBuffer[i + 2] = vertex.z; + } + } + function generateUVs() { + const vertex = new Vector3; + for (let i = 0;i < vertexBuffer.length; i += 3) { + vertex.x = vertexBuffer[i + 0]; + vertex.y = vertexBuffer[i + 1]; + vertex.z = vertexBuffer[i + 2]; + const u = azimuth(vertex) / 2 / Math.PI + 0.5; + const v = inclination(vertex) / Math.PI + 0.5; + uvBuffer.push(u, 1 - v); + } + correctUVs(); + correctSeam(); + } + function correctSeam() { + for (let i = 0;i < uvBuffer.length; i += 6) { + const x0 = uvBuffer[i + 0]; + const x1 = uvBuffer[i + 2]; + const x2 = uvBuffer[i + 4]; + const max = Math.max(x0, x1, x2); + const min = Math.min(x0, x1, x2); + if (max > 0.9 && min < 0.1) { + if (x0 < 0.2) + uvBuffer[i + 0] += 1; + if (x1 < 0.2) + uvBuffer[i + 2] += 1; + if (x2 < 0.2) + uvBuffer[i + 4] += 1; + } + } + } + function pushVertex(vertex) { + vertexBuffer.push(vertex.x, vertex.y, vertex.z); + } + function getVertexByIndex(index2, vertex) { + const stride = index2 * 3; + vertex.x = vertices[stride + 0]; + vertex.y = vertices[stride + 1]; + vertex.z = vertices[stride + 2]; + } + function correctUVs() { + const a = new Vector3; + const b = new Vector3; + const c = new Vector3; + const centroid = new Vector3; + const uvA = new Vector2; + const uvB = new Vector2; + const uvC = new Vector2; + for (let i = 0, j = 0;i < vertexBuffer.length; i += 9, j += 6) { + a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]); + b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]); + c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]); + uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]); + uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]); + uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]); + centroid.copy(a).add(b).add(c).divideScalar(3); + const azi = azimuth(centroid); + correctUV(uvA, j + 0, a, azi); + correctUV(uvB, j + 2, b, azi); + correctUV(uvC, j + 4, c, azi); + } + } + function correctUV(uv, stride, vector, azimuth2) { + if (azimuth2 < 0 && uv.x === 1) { + uvBuffer[stride] = uv.x - 1; + } + if (vector.x === 0 && vector.z === 0) { + uvBuffer[stride] = azimuth2 / 2 / Math.PI + 0.5; + } + } + function azimuth(vector) { + return Math.atan2(vector.z, -vector.x); + } + function inclination(vector) { + return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new PolyhedronGeometry(data2.vertices, data2.indices, data2.radius, data2.details); + } +} + +class DodecahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const t = (1 + Math.sqrt(5)) / 2; + const r = 1 / t; + const vertices = [ + -1, + -1, + -1, + -1, + -1, + 1, + -1, + 1, + -1, + -1, + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + 1, + 1, + -1, + 1, + 1, + 1, + 0, + -r, + -t, + 0, + -r, + t, + 0, + r, + -t, + 0, + r, + t, + -r, + -t, + 0, + -r, + t, + 0, + r, + -t, + 0, + r, + t, + 0, + -t, + 0, + -r, + t, + 0, + -r, + -t, + 0, + r, + t, + 0, + r + ]; + const indices = [ + 3, + 11, + 7, + 3, + 7, + 15, + 3, + 15, + 13, + 7, + 19, + 17, + 7, + 17, + 6, + 7, + 6, + 15, + 17, + 4, + 8, + 17, + 8, + 10, + 17, + 10, + 6, + 8, + 0, + 16, + 8, + 16, + 2, + 8, + 2, + 10, + 0, + 12, + 1, + 0, + 1, + 18, + 0, + 18, + 16, + 6, + 10, + 2, + 6, + 2, + 13, + 6, + 13, + 15, + 2, + 16, + 18, + 2, + 18, + 3, + 2, + 3, + 13, + 18, + 1, + 9, + 18, + 9, + 11, + 18, + 11, + 3, + 4, + 14, + 12, + 4, + 12, + 0, + 4, + 0, + 8, + 11, + 9, + 5, + 11, + 5, + 19, + 11, + 19, + 7, + 19, + 5, + 14, + 19, + 14, + 4, + 19, + 4, + 17, + 1, + 12, + 14, + 1, + 14, + 5, + 1, + 5, + 9 + ]; + super(vertices, indices, radius, detail); + this.type = "DodecahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new DodecahedronGeometry(data2.radius, data2.detail); + } +} +var _v0 = /* @__PURE__ */ new Vector3; +var _v1$1 = /* @__PURE__ */ new Vector3; +var _normal = /* @__PURE__ */ new Vector3; +var _triangle = /* @__PURE__ */ new Triangle; + +class EdgesGeometry extends BufferGeometry { + constructor(geometry = null, thresholdAngle = 1) { + super(); + this.type = "EdgesGeometry"; + this.parameters = { + geometry, + thresholdAngle + }; + if (geometry !== null) { + const precisionPoints = 4; + const precision = Math.pow(10, precisionPoints); + const thresholdDot = Math.cos(DEG2RAD * thresholdAngle); + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute("position"); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + const indexArr = [0, 0, 0]; + const vertKeys = ["a", "b", "c"]; + const hashes = new Array(3); + const edgeData = {}; + const vertices = []; + for (let i = 0;i < indexCount; i += 3) { + if (indexAttr) { + indexArr[0] = indexAttr.getX(i); + indexArr[1] = indexAttr.getX(i + 1); + indexArr[2] = indexAttr.getX(i + 2); + } else { + indexArr[0] = i; + indexArr[1] = i + 1; + indexArr[2] = i + 2; + } + const { a, b, c } = _triangle; + a.fromBufferAttribute(positionAttr, indexArr[0]); + b.fromBufferAttribute(positionAttr, indexArr[1]); + c.fromBufferAttribute(positionAttr, indexArr[2]); + _triangle.getNormal(_normal); + hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`; + hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`; + hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; + if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) { + continue; + } + for (let j = 0;j < 3; j++) { + const jNext = (j + 1) % 3; + const vecHash0 = hashes[j]; + const vecHash1 = hashes[jNext]; + const v0 = _triangle[vertKeys[j]]; + const v1 = _triangle[vertKeys[jNext]]; + const hash = `${vecHash0}_${vecHash1}`; + const reverseHash = `${vecHash1}_${vecHash0}`; + if (reverseHash in edgeData && edgeData[reverseHash]) { + if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) { + vertices.push(v0.x, v0.y, v0.z); + vertices.push(v1.x, v1.y, v1.z); + } + edgeData[reverseHash] = null; + } else if (!(hash in edgeData)) { + edgeData[hash] = { + index0: indexArr[j], + index1: indexArr[jNext], + normal: _normal.clone() + }; + } + } + } + for (const key2 in edgeData) { + if (edgeData[key2]) { + const { index0, index1 } = edgeData[key2]; + _v0.fromBufferAttribute(positionAttr, index0); + _v1$1.fromBufferAttribute(positionAttr, index1); + vertices.push(_v0.x, _v0.y, _v0.z); + vertices.push(_v1$1.x, _v1$1.y, _v1$1.z); + } + } + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } +} + +class Shape extends Path { + constructor(points) { + super(points); + this.uuid = generateUUID(); + this.type = "Shape"; + this.holes = []; + } + getPointsHoles(divisions) { + const holesPts = []; + for (let i = 0, l = this.holes.length;i < l; i++) { + holesPts[i] = this.holes[i].getPoints(divisions); + } + return holesPts; + } + extractPoints(divisions) { + return { + shape: this.getPoints(divisions), + holes: this.getPointsHoles(divisions) + }; + } + copy(source) { + super.copy(source); + this.holes = []; + for (let i = 0, l = source.holes.length;i < l; i++) { + const hole = source.holes[i]; + this.holes.push(hole.clone()); + } + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.uuid = this.uuid; + data2.holes = []; + for (let i = 0, l = this.holes.length;i < l; i++) { + const hole = this.holes[i]; + data2.holes.push(hole.toJSON()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.uuid = json.uuid; + this.holes = []; + for (let i = 0, l = json.holes.length;i < l; i++) { + const hole = json.holes[i]; + this.holes.push(new Path().fromJSON(hole)); + } + return this; + } +} +var Earcut = { + triangulate: function(data2, holeIndices, dim = 2) { + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data2.length; + let outerNode = linkedList(data2, 0, outerLen, dim, true); + const triangles = []; + if (!outerNode || outerNode.next === outerNode.prev) + return triangles; + let minX, minY, maxX, maxY, x, y, invSize; + if (hasHoles) + outerNode = eliminateHoles(data2, holeIndices, outerNode, dim); + if (data2.length > 80 * dim) { + minX = maxX = data2[0]; + minY = maxY = data2[1]; + for (let i = dim;i < outerLen; i += dim) { + x = data2[i]; + y = data2[i + 1]; + if (x < minX) + minX = x; + if (y < minY) + minY = y; + if (x > maxX) + maxX = x; + if (y > maxY) + maxY = y; + } + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + return triangles; + } +}; +function linkedList(data2, start, end, dim, clockwise) { + let i, last2; + if (clockwise === signedArea(data2, start, end, dim) > 0) { + for (i = start;i < end; i += dim) + last2 = insertNode(i, data2[i], data2[i + 1], last2); + } else { + for (i = end - dim;i >= start; i -= dim) + last2 = insertNode(i, data2[i], data2[i + 1], last2); + } + if (last2 && equals(last2, last2.next)) { + removeNode(last2); + last2 = last2.next; + } + return last2; +} +function filterPoints(start, end) { + if (!start) + return start; + if (!end) + end = start; + let p = start, again; + do { + again = false; + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) + break; + again = true; + } else { + p = p.next; + } + } while (again || p !== end); + return end; +} +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) + return; + if (!pass && invSize) + indexCurve(ear, minX, minY, invSize); + let stop = ear, prev, next; + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + triangles.push(prev.i / dim | 0); + triangles.push(ear.i / dim | 0); + triangles.push(next.i / dim | 0); + removeNode(ear); + ear = next.next; + stop = next.next; + continue; + } + ear = next; + if (ear === stop) { + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + break; + } + } +} +function isEar(ear) { + const a = ear.prev, b = ear, c = ear.next; + if (area(a, b, c) >= 0) + return false; + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + let p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) + return false; + p = p.next; + } + return true; +} +function isEarHashed(ear, minX, minY, invSize) { + const a = ear.prev, b = ear, c = ear.next; + if (area(a, b, c) >= 0) + return false; + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + const minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize); + let { prevZ: p, nextZ: n } = ear; + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) + return false; + p = p.prevZ; + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) + return false; + n = n.nextZ; + } + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) + return false; + p = p.prevZ; + } + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) + return false; + n = n.nextZ; + } + return true; +} +function cureLocalIntersections(start, triangles, dim) { + let p = start; + do { + const a = p.prev, b = p.next.next; + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + triangles.push(a.i / dim | 0); + triangles.push(p.i / dim | 0); + triangles.push(b.i / dim | 0); + removeNode(p); + removeNode(p.next); + p = start = b; + } + p = p.next; + } while (p !== start); + return filterPoints(p); +} +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + let a = start; + do { + let b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + let c = splitPolygon(a, b); + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} +function eliminateHoles(data2, holeIndices, outerNode, dim) { + const queue = []; + let i, len, start, end, list; + for (i = 0, len = holeIndices.length;i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data2.length; + list = linkedList(data2, start, end, dim, false); + if (list === list.next) + list.steiner = true; + queue.push(getLeftmost(list)); + } + queue.sort(compareX); + for (i = 0;i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + return outerNode; +} +function compareX(a, b) { + return a.x - b.x; +} +function eliminateHole(hole, outerNode) { + const bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + const bridgeReverse = splitPolygon(bridge, hole); + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); +} +function findHoleBridge(hole, outerNode) { + let p = outerNode, qx = -Infinity, m; + const { x: hx, y: hy } = hole; + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) + return m; + } + } + p = p.next; + } while (p !== outerNode); + if (!m) + return null; + const stop = m, mx = m.x, my = m.y; + let tanMin = Infinity, tan; + p = m; + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + tan = Math.abs(hy - p.y) / (hx - p.x); + if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) { + m = p; + tanMin = tan; + } + } + p = p.next; + } while (p !== stop); + return m; +} +function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; +} +function indexCurve(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) + p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + p.prevZ.nextZ = null; + p.prevZ = null; + sortLinked(p); +} +function sortLinked(list) { + let i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; + do { + p = list; + list = null; + tail = null; + numMerges = 0; + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0;i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) + break; + } + qSize = inSize; + while (pSize > 0 || qSize > 0 && q) { + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + if (tail) + tail.nextZ = e; + else + list = e; + e.prevZ = tail; + tail = e; + } + p = q; + } + tail.nextZ = null; + inSize *= 2; + } while (numMerges > 1); + return list; +} +function zOrder(x, y, minX, minY, invSize) { + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + x = (x | x << 8) & 16711935; + x = (x | x << 4) & 252645135; + x = (x | x << 2) & 858993459; + x = (x | x << 1) & 1431655765; + y = (y | y << 8) & 16711935; + y = (y | y << 4) & 252645135; + y = (y | y << 2) & 858993459; + y = (y | y << 1) & 1431655765; + return x | y << 1; +} +function getLeftmost(start) { + let p = start, leftmost = start; + do { + if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) + leftmost = p; + p = p.next; + } while (p !== start); + return leftmost; +} +function pointInTriangle(ax, ay, bx, by, cx, cy, px2, py2) { + return (cx - px2) * (ay - py2) >= (ax - px2) * (cy - py2) && (ax - px2) * (by - py2) >= (bx - px2) * (ay - py2) && (bx - px2) * (cy - py2) >= (cx - px2) * (by - py2); +} +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && (area(a.prev, a, b.prev) || area(a, b.prev, b)) || equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); +} +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} +function intersects(p1, q1, p2, q2) { + const o1 = sign(area(p1, q1, p2)); + const o2 = sign(area(p1, q1, q2)); + const o3 = sign(area(p2, q2, p1)); + const o4 = sign(area(p2, q2, q1)); + if (o1 !== o2 && o3 !== o4) + return true; + if (o1 === 0 && onSegment(p1, p2, q1)) + return true; + if (o2 === 0 && onSegment(p1, q2, q1)) + return true; + if (o3 === 0 && onSegment(p2, p1, q2)) + return true; + if (o4 === 0 && onSegment(p2, q1, q2)) + return true; + return false; +} +function onSegment(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); +} +function sign(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; +} +function intersectsPolygon(a, b) { + let p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) + return true; + p = p.next; + } while (p !== a); + return false; +} +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} +function middleInside(a, b) { + let p = a, inside = false; + const px2 = (a.x + b.x) / 2, py2 = (a.y + b.y) / 2; + do { + if (p.y > py2 !== p.next.y > py2 && p.next.y !== p.y && px2 < (p.next.x - p.x) * (py2 - p.y) / (p.next.y - p.y) + p.x) + inside = !inside; + p = p.next; + } while (p !== a); + return inside; +} +function splitPolygon(a, b) { + const a2 = new Node2(a.i, a.x, a.y), b2 = new Node2(b.i, b.x, b.y), an = a.next, bp = b.prev; + a.next = b; + b.prev = a; + a2.next = an; + an.prev = a2; + b2.next = a2; + a2.prev = b2; + bp.next = b2; + b2.prev = bp; + return b2; +} +function insertNode(i, x, y, last2) { + const p = new Node2(i, x, y); + if (!last2) { + p.prev = p; + p.next = p; + } else { + p.next = last2.next; + p.prev = last2; + last2.next.prev = p; + last2.next = p; + } + return p; +} +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + if (p.prevZ) + p.prevZ.nextZ = p.nextZ; + if (p.nextZ) + p.nextZ.prevZ = p.prevZ; +} +function Node2(i, x, y) { + this.i = i; + this.x = x; + this.y = y; + this.prev = null; + this.next = null; + this.z = 0; + this.prevZ = null; + this.nextZ = null; + this.steiner = false; +} +function signedArea(data2, start, end, dim) { + let sum2 = 0; + for (let i = start, j = end - dim;i < end; i += dim) { + sum2 += (data2[j] - data2[i]) * (data2[i + 1] + data2[j + 1]); + j = i; + } + return sum2; +} + +class ShapeUtils { + static area(contour) { + const n = contour.length; + let a = 0; + for (let p = n - 1, q = 0;q < n; p = q++) { + a += contour[p].x * contour[q].y - contour[q].x * contour[p].y; + } + return a * 0.5; + } + static isClockWise(pts) { + return ShapeUtils.area(pts) < 0; + } + static triangulateShape(contour, holes) { + const vertices = []; + const holeIndices = []; + const faces = []; + removeDupEndPts(contour); + addContour(vertices, contour); + let holeIndex = contour.length; + holes.forEach(removeDupEndPts); + for (let i = 0;i < holes.length; i++) { + holeIndices.push(holeIndex); + holeIndex += holes[i].length; + addContour(vertices, holes[i]); + } + const triangles = Earcut.triangulate(vertices, holeIndices); + for (let i = 0;i < triangles.length; i += 3) { + faces.push(triangles.slice(i, i + 3)); + } + return faces; + } +} +function removeDupEndPts(points) { + const l = points.length; + if (l > 2 && points[l - 1].equals(points[0])) { + points.pop(); + } +} +function addContour(vertices, contour) { + for (let i = 0;i < contour.length; i++) { + vertices.push(contour[i].x); + vertices.push(contour[i].y); + } +} + +class ExtrudeGeometry extends BufferGeometry { + constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) { + super(); + this.type = "ExtrudeGeometry"; + this.parameters = { + shapes, + options + }; + shapes = Array.isArray(shapes) ? shapes : [shapes]; + const scope = this; + const verticesArray = []; + const uvArray = []; + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + addShape(shape); + } + this.setAttribute("position", new Float32BufferAttribute(verticesArray, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvArray, 2)); + this.computeVertexNormals(); + function addShape(shape) { + const placeholder = []; + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + const extrudePath = options.extrudePath; + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + if (extrudePath) { + extrudePts = extrudePath.getSpacedPoints(steps); + extrudeByPath = true; + bevelEnabled = false; + splineTube = extrudePath.computeFrenetFrames(steps, false); + binormal = new Vector3; + normal = new Vector3; + position2 = new Vector3; + } + if (!bevelEnabled) { + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + } + const shapePoints = shape.extractPoints(curveSegments); + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + const reverse = !ShapeUtils.isClockWise(vertices); + if (reverse) { + vertices = vertices.reverse(); + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + if (ShapeUtils.isClockWise(ahole)) { + holes[h] = ahole.reverse(); + } + } + } + const faces = ShapeUtils.triangulateShape(vertices, holes); + const contour = vertices; + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + vertices = vertices.concat(ahole); + } + function scalePt2(pt, vec, size) { + if (!vec) + console.error("THREE.ExtrudeGeometry: vec does not exist"); + return pt.clone().addScaledVector(vec, size); + } + const vlen = vertices.length, flen = faces.length; + function getBevelVec(inPt, inPrev, inNext) { + let v_trans_x, v_trans_y, shrink_by; + const v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; + const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; + const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x; + if (Math.abs(collinear0) > Number.EPSILON) { + const v_prev_len = Math.sqrt(v_prev_lensq); + const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); + const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len; + const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len; + const ptNextShift_x = inNext.x - v_next_y / v_next_len; + const ptNextShift_y = inNext.y + v_next_x / v_next_len; + const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); + v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x; + v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; + const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y; + if (v_trans_lensq <= 2) { + return new Vector2(v_trans_x, v_trans_y); + } else { + shrink_by = Math.sqrt(v_trans_lensq / 2); + } + } else { + let direction_eq = false; + if (v_prev_x > Number.EPSILON) { + if (v_next_x > Number.EPSILON) { + direction_eq = true; + } + } else { + if (v_prev_x < -Number.EPSILON) { + if (v_next_x < -Number.EPSILON) { + direction_eq = true; + } + } else { + if (Math.sign(v_prev_y) === Math.sign(v_next_y)) { + direction_eq = true; + } + } + } + if (direction_eq) { + v_trans_x = -v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt(v_prev_lensq); + } else { + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt(v_prev_lensq / 2); + } + } + return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by); + } + const contourMovements = []; + for (let i = 0, il = contour.length, j = il - 1, k = i + 1;i < il; i++, j++, k++) { + if (j === il) + j = 0; + if (k === il) + k = 0; + contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]); + } + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = []; + for (let i = 0, il = ahole.length, j = il - 1, k = i + 1;i < il; i++, j++, k++) { + if (j === il) + j = 0; + if (k === il) + k = 0; + oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]); + } + holesMovements.push(oneHoleMovements); + verticesMovements = verticesMovements.concat(oneHoleMovements); + } + for (let b = 0;b < bevelSegments; b++) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos(t * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length;i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, -z); + } + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length;i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + v(vert.x, vert.y, -z); + } + } + } + const bs = bevelSize + bevelOffset; + for (let i = 0;i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, 0); + } else { + normal.copy(splineTube.normals[0]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y); + position2.copy(extrudePts[0]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + for (let s = 1;s <= steps; s++) { + for (let i = 0;i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, depth / steps * s); + } else { + normal.copy(splineTube.normals[s]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y); + position2.copy(extrudePts[s]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + } + for (let b = bevelSegments - 1;b >= 0; b--) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos(t * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length;i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, depth + z); + } + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length;i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + if (!extrudeByPath) { + v(vert.x, vert.y, depth + z); + } else { + v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z); + } + } + } + } + buildLidFaces(); + buildSideFaces(); + function buildLidFaces() { + const start = verticesArray.length / 3; + if (bevelEnabled) { + let layer = 0; + let offset = vlen * layer; + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[2] + offset, face[1] + offset, face[0] + offset); + } + layer = steps + bevelSegments * 2; + offset = vlen * layer; + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[0] + offset, face[1] + offset, face[2] + offset); + } + } else { + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[2], face[1], face[0]); + } + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps); + } + } + scope.addGroup(start, verticesArray.length / 3 - start, 0); + } + function buildSideFaces() { + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls(contour, layeroffset); + layeroffset += contour.length; + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + sidewalls(ahole, layeroffset); + layeroffset += ahole.length; + } + scope.addGroup(start, verticesArray.length / 3 - start, 1); + } + function sidewalls(contour2, layeroffset) { + let i = contour2.length; + while (--i >= 0) { + const j = i; + let k = i - 1; + if (k < 0) + k = contour2.length - 1; + for (let s = 0, sl = steps + bevelSegments * 2;s < sl; s++) { + const slen1 = vlen * s; + const slen2 = vlen * (s + 1); + const a = layeroffset + j + slen1, b = layeroffset + k + slen1, c = layeroffset + k + slen2, d = layeroffset + j + slen2; + f4(a, b, c, d); + } + } + } + function v(x, y, z) { + placeholder.push(x); + placeholder.push(y); + placeholder.push(z); + } + function f3(a, b, c) { + addVertex(a); + addVertex(b); + addVertex(c); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[2]); + } + function f4(a, b, c, d) { + addVertex(a); + addVertex(b); + addVertex(d); + addVertex(b); + addVertex(c); + addVertex(d); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[3]); + addUV(uvs[1]); + addUV(uvs[2]); + addUV(uvs[3]); + } + function addVertex(index2) { + verticesArray.push(placeholder[index2 * 3 + 0]); + verticesArray.push(placeholder[index2 * 3 + 1]); + verticesArray.push(placeholder[index2 * 3 + 2]); + } + function addUV(vector2) { + uvArray.push(vector2.x); + uvArray.push(vector2.y); + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + const shapes = this.parameters.shapes; + const options = this.parameters.options; + return toJSON$1(shapes, options, data2); + } + static fromJSON(data2, shapes) { + const geometryShapes = []; + for (let j = 0, jl = data2.shapes.length;j < jl; j++) { + const shape = shapes[data2.shapes[j]]; + geometryShapes.push(shape); + } + const extrudePath = data2.options.extrudePath; + if (extrudePath !== undefined) { + data2.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath); + } + return new ExtrudeGeometry(geometryShapes, data2.options); + } +} +var WorldUVGenerator = { + generateTopUV: function(geometry, vertices, indexA, indexB, indexC) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + return [ + new Vector2(a_x, a_y), + new Vector2(b_x, b_y), + new Vector2(c_x, c_y) + ]; + }, + generateSideWallUV: function(geometry, vertices, indexA, indexB, indexC, indexD) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const a_z = vertices[indexA * 3 + 2]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const b_z = vertices[indexB * 3 + 2]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + const c_z = vertices[indexC * 3 + 2]; + const d_x = vertices[indexD * 3]; + const d_y = vertices[indexD * 3 + 1]; + const d_z = vertices[indexD * 3 + 2]; + if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) { + return [ + new Vector2(a_x, 1 - a_z), + new Vector2(b_x, 1 - b_z), + new Vector2(c_x, 1 - c_z), + new Vector2(d_x, 1 - d_z) + ]; + } else { + return [ + new Vector2(a_y, 1 - a_z), + new Vector2(b_y, 1 - b_z), + new Vector2(c_y, 1 - c_z), + new Vector2(d_y, 1 - d_z) + ]; + } + } +}; +function toJSON$1(shapes, options, data2) { + data2.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + data2.shapes.push(shape.uuid); + } + } else { + data2.shapes.push(shapes.uuid); + } + data2.options = Object.assign({}, options); + if (options.extrudePath !== undefined) + data2.options.extrudePath = options.extrudePath.toJSON(); + return data2; +} + +class IcosahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const t = (1 + Math.sqrt(5)) / 2; + const vertices = [ + -1, + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + 0, + 0, + -1, + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + t, + 0, + -1, + t, + 0, + 1, + -t, + 0, + -1, + -t, + 0, + 1 + ]; + const indices = [ + 0, + 11, + 5, + 0, + 5, + 1, + 0, + 1, + 7, + 0, + 7, + 10, + 0, + 10, + 11, + 1, + 5, + 9, + 5, + 11, + 4, + 11, + 10, + 2, + 10, + 7, + 6, + 7, + 1, + 8, + 3, + 9, + 4, + 3, + 4, + 2, + 3, + 2, + 6, + 3, + 6, + 8, + 3, + 8, + 9, + 4, + 9, + 5, + 2, + 4, + 11, + 6, + 2, + 10, + 8, + 6, + 7, + 9, + 8, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "IcosahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new IcosahedronGeometry(data2.radius, data2.detail); + } +} + +class OctahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1 + ]; + const indices = [ + 0, + 2, + 4, + 0, + 4, + 3, + 0, + 3, + 5, + 0, + 5, + 2, + 1, + 2, + 5, + 1, + 5, + 3, + 1, + 3, + 4, + 1, + 4, + 2 + ]; + super(vertices, indices, radius, detail); + this.type = "OctahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new OctahedronGeometry(data2.radius, data2.detail); + } +} + +class PlaneGeometry extends BufferGeometry { + constructor(width2 = 1, height2 = 1, widthSegments = 1, heightSegments = 1) { + super(); + this.type = "PlaneGeometry"; + this.parameters = { + width: width2, + height: height2, + widthSegments, + heightSegments + }; + const width_half = width2 / 2; + const height_half = height2 / 2; + const gridX = Math.floor(widthSegments); + const gridY = Math.floor(heightSegments); + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + const segment_width = width2 / gridX; + const segment_height = height2 / gridY; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0;iy < gridY1; iy++) { + const y = iy * segment_height - height_half; + for (let ix = 0;ix < gridX1; ix++) { + const x = ix * segment_width - width_half; + vertices.push(x, -y, 0); + normals.push(0, 0, 1); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + } + } + for (let iy = 0;iy < gridY; iy++) { + for (let ix = 0;ix < gridX; ix++) { + const a = ix + gridX1 * iy; + const b = ix + gridX1 * (iy + 1); + const c = ix + 1 + gridX1 * (iy + 1); + const d = ix + 1 + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new PlaneGeometry(data2.width, data2.height, data2.widthSegments, data2.heightSegments); + } +} + +class RingGeometry extends BufferGeometry { + constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "RingGeometry"; + this.parameters = { + innerRadius, + outerRadius, + thetaSegments, + phiSegments, + thetaStart, + thetaLength + }; + thetaSegments = Math.max(3, thetaSegments); + phiSegments = Math.max(1, phiSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let radius = innerRadius; + const radiusStep = (outerRadius - innerRadius) / phiSegments; + const vertex = new Vector3; + const uv = new Vector2; + for (let j = 0;j <= phiSegments; j++) { + for (let i = 0;i <= thetaSegments; i++) { + const segment = thetaStart + i / thetaSegments * thetaLength; + vertex.x = radius * Math.cos(segment); + vertex.y = radius * Math.sin(segment); + vertices.push(vertex.x, vertex.y, vertex.z); + normals.push(0, 0, 1); + uv.x = (vertex.x / outerRadius + 1) / 2; + uv.y = (vertex.y / outerRadius + 1) / 2; + uvs.push(uv.x, uv.y); + } + radius += radiusStep; + } + for (let j = 0;j < phiSegments; j++) { + const thetaSegmentLevel = j * (thetaSegments + 1); + for (let i = 0;i < thetaSegments; i++) { + const segment = i + thetaSegmentLevel; + const a = segment; + const b = segment + thetaSegments + 1; + const c = segment + thetaSegments + 2; + const d = segment + 1; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new RingGeometry(data2.innerRadius, data2.outerRadius, data2.thetaSegments, data2.phiSegments, data2.thetaStart, data2.thetaLength); + } +} + +class ShapeGeometry extends BufferGeometry { + constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) { + super(); + this.type = "ShapeGeometry"; + this.parameters = { + shapes, + curveSegments + }; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let groupStart = 0; + let groupCount = 0; + if (Array.isArray(shapes) === false) { + addShape(shapes); + } else { + for (let i = 0;i < shapes.length; i++) { + addShape(shapes[i]); + this.addGroup(groupStart, groupCount, i); + groupStart += groupCount; + groupCount = 0; + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function addShape(shape) { + const indexOffset = vertices.length / 3; + const points = shape.extractPoints(curveSegments); + let shapeVertices = points.shape; + const shapeHoles = points.holes; + if (ShapeUtils.isClockWise(shapeVertices) === false) { + shapeVertices = shapeVertices.reverse(); + } + for (let i = 0, l = shapeHoles.length;i < l; i++) { + const shapeHole = shapeHoles[i]; + if (ShapeUtils.isClockWise(shapeHole) === true) { + shapeHoles[i] = shapeHole.reverse(); + } + } + const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); + for (let i = 0, l = shapeHoles.length;i < l; i++) { + const shapeHole = shapeHoles[i]; + shapeVertices = shapeVertices.concat(shapeHole); + } + for (let i = 0, l = shapeVertices.length;i < l; i++) { + const vertex = shapeVertices[i]; + vertices.push(vertex.x, vertex.y, 0); + normals.push(0, 0, 1); + uvs.push(vertex.x, vertex.y); + } + for (let i = 0, l = faces.length;i < l; i++) { + const face = faces[i]; + const a = face[0] + indexOffset; + const b = face[1] + indexOffset; + const c = face[2] + indexOffset; + indices.push(a, b, c); + groupCount += 3; + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + const shapes = this.parameters.shapes; + return toJSON(shapes, data2); + } + static fromJSON(data2, shapes) { + const geometryShapes = []; + for (let j = 0, jl = data2.shapes.length;j < jl; j++) { + const shape = shapes[data2.shapes[j]]; + geometryShapes.push(shape); + } + return new ShapeGeometry(geometryShapes, data2.curveSegments); + } +} +function toJSON(shapes, data2) { + data2.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + data2.shapes.push(shape.uuid); + } + } else { + data2.shapes.push(shapes.uuid); + } + return data2; +} + +class SphereGeometry extends BufferGeometry { + constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) { + super(); + this.type = "SphereGeometry"; + this.parameters = { + radius, + widthSegments, + heightSegments, + phiStart, + phiLength, + thetaStart, + thetaLength + }; + widthSegments = Math.max(3, Math.floor(widthSegments)); + heightSegments = Math.max(2, Math.floor(heightSegments)); + const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI); + let index2 = 0; + const grid = []; + const vertex = new Vector3; + const normal = new Vector3; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0;iy <= heightSegments; iy++) { + const verticesRow = []; + const v = iy / heightSegments; + let uOffset = 0; + if (iy === 0 && thetaStart === 0) { + uOffset = 0.5 / widthSegments; + } else if (iy === heightSegments && thetaEnd === Math.PI) { + uOffset = -0.5 / widthSegments; + } + for (let ix = 0;ix <= widthSegments; ix++) { + const u = ix / widthSegments; + vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertex.y = radius * Math.cos(thetaStart + v * thetaLength); + vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertices.push(vertex.x, vertex.y, vertex.z); + normal.copy(vertex).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u + uOffset, 1 - v); + verticesRow.push(index2++); + } + grid.push(verticesRow); + } + for (let iy = 0;iy < heightSegments; iy++) { + for (let ix = 0;ix < widthSegments; ix++) { + const a = grid[iy][ix + 1]; + const b = grid[iy][ix]; + const c = grid[iy + 1][ix]; + const d = grid[iy + 1][ix + 1]; + if (iy !== 0 || thetaStart > 0) + indices.push(a, b, d); + if (iy !== heightSegments - 1 || thetaEnd < Math.PI) + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new SphereGeometry(data2.radius, data2.widthSegments, data2.heightSegments, data2.phiStart, data2.phiLength, data2.thetaStart, data2.thetaLength); + } +} + +class TetrahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + -1, + 1, + -1, + -1 + ]; + const indices = [ + 2, + 1, + 0, + 0, + 3, + 2, + 1, + 3, + 0, + 2, + 3, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "TetrahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new TetrahedronGeometry(data2.radius, data2.detail); + } +} + +class TorusGeometry extends BufferGeometry { + constructor(radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2) { + super(); + this.type = "TorusGeometry"; + this.parameters = { + radius, + tube, + radialSegments, + tubularSegments, + arc + }; + radialSegments = Math.floor(radialSegments); + tubularSegments = Math.floor(tubularSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const center = new Vector3; + const vertex = new Vector3; + const normal = new Vector3; + for (let j = 0;j <= radialSegments; j++) { + for (let i = 0;i <= tubularSegments; i++) { + const u = i / tubularSegments * arc; + const v = j / radialSegments * Math.PI * 2; + vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u); + vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u); + vertex.z = tube * Math.sin(v); + vertices.push(vertex.x, vertex.y, vertex.z); + center.x = radius * Math.cos(u); + center.y = radius * Math.sin(u); + normal.subVectors(vertex, center).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j / radialSegments); + } + } + for (let j = 1;j <= radialSegments; j++) { + for (let i = 1;i <= tubularSegments; i++) { + const a = (tubularSegments + 1) * j + i - 1; + const b = (tubularSegments + 1) * (j - 1) + i - 1; + const c = (tubularSegments + 1) * (j - 1) + i; + const d = (tubularSegments + 1) * j + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new TorusGeometry(data2.radius, data2.tube, data2.radialSegments, data2.tubularSegments, data2.arc); + } +} + +class TorusKnotGeometry extends BufferGeometry { + constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) { + super(); + this.type = "TorusKnotGeometry"; + this.parameters = { + radius, + tube, + tubularSegments, + radialSegments, + p, + q + }; + tubularSegments = Math.floor(tubularSegments); + radialSegments = Math.floor(radialSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex = new Vector3; + const normal = new Vector3; + const P1 = new Vector3; + const P2 = new Vector3; + const B = new Vector3; + const T = new Vector3; + const N = new Vector3; + for (let i = 0;i <= tubularSegments; ++i) { + const u = i / tubularSegments * p * Math.PI * 2; + calculatePositionOnCurve(u, p, q, radius, P1); + calculatePositionOnCurve(u + 0.01, p, q, radius, P2); + T.subVectors(P2, P1); + N.addVectors(P2, P1); + B.crossVectors(T, N); + N.crossVectors(B, T); + B.normalize(); + N.normalize(); + for (let j = 0;j <= radialSegments; ++j) { + const v = j / radialSegments * Math.PI * 2; + const cx = -tube * Math.cos(v); + const cy = tube * Math.sin(v); + vertex.x = P1.x + (cx * N.x + cy * B.x); + vertex.y = P1.y + (cx * N.y + cy * B.y); + vertex.z = P1.z + (cx * N.z + cy * B.z); + vertices.push(vertex.x, vertex.y, vertex.z); + normal.subVectors(vertex, P1).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j / radialSegments); + } + } + for (let j = 1;j <= tubularSegments; j++) { + for (let i = 1;i <= radialSegments; i++) { + const a = (radialSegments + 1) * (j - 1) + (i - 1); + const b = (radialSegments + 1) * j + (i - 1); + const c = (radialSegments + 1) * j + i; + const d = (radialSegments + 1) * (j - 1) + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function calculatePositionOnCurve(u, p2, q2, radius2, position2) { + const cu = Math.cos(u); + const su = Math.sin(u); + const quOverP = q2 / p2 * u; + const cs = Math.cos(quOverP); + position2.x = radius2 * (2 + cs) * 0.5 * cu; + position2.y = radius2 * (2 + cs) * su * 0.5; + position2.z = radius2 * Math.sin(quOverP) * 0.5; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new TorusKnotGeometry(data2.radius, data2.tube, data2.tubularSegments, data2.radialSegments, data2.p, data2.q); + } +} + +class TubeGeometry extends BufferGeometry { + constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) { + super(); + this.type = "TubeGeometry"; + this.parameters = { + path, + tubularSegments, + radius, + radialSegments, + closed + }; + const frames2 = path.computeFrenetFrames(tubularSegments, closed); + this.tangents = frames2.tangents; + this.normals = frames2.normals; + this.binormals = frames2.binormals; + const vertex = new Vector3; + const normal = new Vector3; + const uv = new Vector2; + let P = new Vector3; + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; + generateBufferData(); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function generateBufferData() { + for (let i = 0;i < tubularSegments; i++) { + generateSegment(i); + } + generateSegment(closed === false ? tubularSegments : 0); + generateUVs(); + generateIndices(); + } + function generateSegment(i) { + P = path.getPointAt(i / tubularSegments, P); + const N = frames2.normals[i]; + const B = frames2.binormals[i]; + for (let j = 0;j <= radialSegments; j++) { + const v = j / radialSegments * Math.PI * 2; + const sin = Math.sin(v); + const cos = -Math.cos(v); + normal.x = cos * N.x + sin * B.x; + normal.y = cos * N.y + sin * B.y; + normal.z = cos * N.z + sin * B.z; + normal.normalize(); + normals.push(normal.x, normal.y, normal.z); + vertex.x = P.x + radius * normal.x; + vertex.y = P.y + radius * normal.y; + vertex.z = P.z + radius * normal.z; + vertices.push(vertex.x, vertex.y, vertex.z); + } + } + function generateIndices() { + for (let j = 1;j <= tubularSegments; j++) { + for (let i = 1;i <= radialSegments; i++) { + const a = (radialSegments + 1) * (j - 1) + (i - 1); + const b = (radialSegments + 1) * j + (i - 1); + const c = (radialSegments + 1) * j + i; + const d = (radialSegments + 1) * (j - 1) + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + } + function generateUVs() { + for (let i = 0;i <= tubularSegments; i++) { + for (let j = 0;j <= radialSegments; j++) { + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + uvs.push(uv.x, uv.y); + } + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.path = this.parameters.path.toJSON(); + return data2; + } + static fromJSON(data2) { + return new TubeGeometry(new Curves[data2.path.type]().fromJSON(data2.path), data2.tubularSegments, data2.radius, data2.radialSegments, data2.closed); + } +} + +class WireframeGeometry extends BufferGeometry { + constructor(geometry = null) { + super(); + this.type = "WireframeGeometry"; + this.parameters = { + geometry + }; + if (geometry !== null) { + const vertices = []; + const edges = new Set; + const start = new Vector3; + const end = new Vector3; + if (geometry.index !== null) { + const position2 = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; + if (groups.length === 0) { + groups = [{ start: 0, count: indices.count, materialIndex: 0 }]; + } + for (let o = 0, ol = groups.length;o < ol; ++o) { + const group = groups[o]; + const groupStart = group.start; + const groupCount = group.count; + for (let i = groupStart, l = groupStart + groupCount;i < l; i += 3) { + for (let j = 0;j < 3; j++) { + const index1 = indices.getX(i + j); + const index2 = indices.getX(i + (j + 1) % 3); + start.fromBufferAttribute(position2, index1); + end.fromBufferAttribute(position2, index2); + if (isUniqueEdge(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + } else { + const position2 = geometry.attributes.position; + for (let i = 0, l = position2.count / 3;i < l; i++) { + for (let j = 0;j < 3; j++) { + const index1 = 3 * i + j; + const index2 = 3 * i + (j + 1) % 3; + start.fromBufferAttribute(position2, index1); + end.fromBufferAttribute(position2, index2); + if (isUniqueEdge(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } +} +function isUniqueEdge(start, end, edges) { + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; + if (edges.has(hash1) === true || edges.has(hash2) === true) { + return false; + } else { + edges.add(hash1); + edges.add(hash2); + return true; + } +} +var Geometries = /* @__PURE__ */ Object.freeze({ + __proto__: null, + BoxGeometry, + CapsuleGeometry, + CircleGeometry, + ConeGeometry, + CylinderGeometry, + DodecahedronGeometry, + EdgesGeometry, + ExtrudeGeometry, + IcosahedronGeometry, + LatheGeometry, + OctahedronGeometry, + PlaneGeometry, + PolyhedronGeometry, + RingGeometry, + ShapeGeometry, + SphereGeometry, + TetrahedronGeometry, + TorusGeometry, + TorusKnotGeometry, + TubeGeometry, + WireframeGeometry +}); + +class ShadowMaterial extends Material { + constructor(parameters) { + super(); + this.isShadowMaterial = true; + this.type = "ShadowMaterial"; + this.color = new Color(0); + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.fog = source.fog; + return this; + } +} + +class RawShaderMaterial extends ShaderMaterial { + constructor(parameters) { + super(parameters); + this.isRawShaderMaterial = true; + this.type = "RawShaderMaterial"; + } +} + +class MeshStandardMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshStandardMaterial = true; + this.type = "MeshStandardMaterial"; + this.defines = { STANDARD: "" }; + this.color = new Color(16777215); + this.roughness = 1; + this.metalness = 0; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.roughnessMap = null; + this.metalnessMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler; + this.envMapIntensity = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { STANDARD: "" }; + this.color.copy(source.color); + this.roughness = source.roughness; + this.metalness = source.metalness; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.roughnessMap = source.roughnessMap; + this.metalnessMap = source.metalnessMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.envMapIntensity = source.envMapIntensity; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } +} + +class MeshPhysicalMaterial extends MeshStandardMaterial { + constructor(parameters) { + super(); + this.isMeshPhysicalMaterial = true; + this.defines = { + STANDARD: "", + PHYSICAL: "" + }; + this.type = "MeshPhysicalMaterial"; + this.anisotropyRotation = 0; + this.anisotropyMap = null; + this.clearcoatMap = null; + this.clearcoatRoughness = 0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector2(1, 1); + this.clearcoatNormalMap = null; + this.ior = 1.5; + Object.defineProperty(this, "reflectivity", { + get: function() { + return clamp2(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1); + }, + set: function(reflectivity) { + this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity); + } + }); + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [100, 400]; + this.iridescenceThicknessMap = null; + this.sheenColor = new Color(0); + this.sheenColorMap = null; + this.sheenRoughness = 1; + this.sheenRoughnessMap = null; + this.transmissionMap = null; + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = Infinity; + this.attenuationColor = new Color(1, 1, 1); + this.specularIntensity = 1; + this.specularIntensityMap = null; + this.specularColor = new Color(1, 1, 1); + this.specularColorMap = null; + this._anisotropy = 0; + this._clearcoat = 0; + this._dispersion = 0; + this._iridescence = 0; + this._sheen = 0; + this._transmission = 0; + this.setValues(parameters); + } + get anisotropy() { + return this._anisotropy; + } + set anisotropy(value2) { + if (this._anisotropy > 0 !== value2 > 0) { + this.version++; + } + this._anisotropy = value2; + } + get clearcoat() { + return this._clearcoat; + } + set clearcoat(value2) { + if (this._clearcoat > 0 !== value2 > 0) { + this.version++; + } + this._clearcoat = value2; + } + get iridescence() { + return this._iridescence; + } + set iridescence(value2) { + if (this._iridescence > 0 !== value2 > 0) { + this.version++; + } + this._iridescence = value2; + } + get dispersion() { + return this._dispersion; + } + set dispersion(value2) { + if (this._dispersion > 0 !== value2 > 0) { + this.version++; + } + this._dispersion = value2; + } + get sheen() { + return this._sheen; + } + set sheen(value2) { + if (this._sheen > 0 !== value2 > 0) { + this.version++; + } + this._sheen = value2; + } + get transmission() { + return this._transmission; + } + set transmission(value2) { + if (this._transmission > 0 !== value2 > 0) { + this.version++; + } + this._transmission = value2; + } + copy(source) { + super.copy(source); + this.defines = { + STANDARD: "", + PHYSICAL: "" + }; + this.anisotropy = source.anisotropy; + this.anisotropyRotation = source.anisotropyRotation; + this.anisotropyMap = source.anisotropyMap; + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy(source.clearcoatNormalScale); + this.dispersion = source.dispersion; + this.ior = source.ior; + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [...source.iridescenceThicknessRange]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + this.sheen = source.sheen; + this.sheenColor.copy(source.sheenColor); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy(source.attenuationColor); + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy(source.specularColor); + this.specularColorMap = source.specularColorMap; + return this; + } +} + +class MeshPhongMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshPhongMaterial = true; + this.type = "MeshPhongMaterial"; + this.color = new Color(16777215); + this.specular = new Color(1118481); + this.shininess = 30; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.specular.copy(source.specular); + this.shininess = source.shininess; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } +} + +class MeshToonMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshToonMaterial = true; + this.defines = { TOON: "" }; + this.type = "MeshToonMaterial"; + this.color = new Color(16777215); + this.map = null; + this.gradientMap = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.gradientMap = source.gradientMap; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } +} + +class MeshNormalMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshNormalMaterial = true; + this.type = "MeshNormalMaterial"; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.flatShading = false; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.flatShading = source.flatShading; + return this; + } +} + +class MeshLambertMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshLambertMaterial = true; + this.type = "MeshLambertMaterial"; + this.color = new Color(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } +} + +class MeshDepthMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshDepthMaterial = true; + this.type = "MeshDepthMaterial"; + this.depthPacking = BasicDepthPacking; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.depthPacking = source.depthPacking; + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + return this; + } +} + +class MeshDistanceMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshDistanceMaterial = true; + this.type = "MeshDistanceMaterial"; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + return this; + } +} + +class MeshMatcapMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshMatcapMaterial = true; + this.defines = { MATCAP: "" }; + this.type = "MeshMatcapMaterial"; + this.color = new Color(16777215); + this.matcap = null; + this.map = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { MATCAP: "" }; + this.color.copy(source.color); + this.matcap = source.matcap; + this.map = source.map; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } +} + +class LineDashedMaterial extends LineBasicMaterial { + constructor(parameters) { + super(); + this.isLineDashedMaterial = true; + this.type = "LineDashedMaterial"; + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + return this; + } +} +function convertArray(array, type, forceClone) { + if (!array || !forceClone && array.constructor === type) + return array; + if (typeof type.BYTES_PER_ELEMENT === "number") { + return new type(array); + } + return Array.prototype.slice.call(array); +} +function isTypedArray(object) { + return ArrayBuffer.isView(object) && !(object instanceof DataView); +} +function getKeyframeOrder(times) { + function compareTime(i, j) { + return times[i] - times[j]; + } + const n = times.length; + const result = new Array(n); + for (let i = 0;i !== n; ++i) + result[i] = i; + result.sort(compareTime); + return result; +} +function sortedArray(values2, stride, order) { + const nValues = values2.length; + const result = new values2.constructor(nValues); + for (let i = 0, dstOffset = 0;dstOffset !== nValues; ++i) { + const srcOffset = order[i] * stride; + for (let j = 0;j !== stride; ++j) { + result[dstOffset++] = values2[srcOffset + j]; + } + } + return result; +} +function flattenJSON(jsonKeys, times, values2, valuePropertyName) { + let i = 1, key2 = jsonKeys[0]; + while (key2 !== undefined && key2[valuePropertyName] === undefined) { + key2 = jsonKeys[i++]; + } + if (key2 === undefined) + return; + let value2 = key2[valuePropertyName]; + if (value2 === undefined) + return; + if (Array.isArray(value2)) { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + values2.push.apply(values2, value2); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } else if (value2.toArray !== undefined) { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + value2.toArray(values2, values2.length); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } else { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + values2.push(value2); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } +} +function subclip(sourceClip, name2, startFrame, endFrame, fps = 30) { + const clip = sourceClip.clone(); + clip.name = name2; + const tracks = []; + for (let i = 0;i < clip.tracks.length; ++i) { + const track = clip.tracks[i]; + const valueSize = track.getValueSize(); + const times = []; + const values2 = []; + for (let j = 0;j < track.times.length; ++j) { + const frame = track.times[j] * fps; + if (frame < startFrame || frame >= endFrame) + continue; + times.push(track.times[j]); + for (let k = 0;k < valueSize; ++k) { + values2.push(track.values[j * valueSize + k]); + } + } + if (times.length === 0) + continue; + track.times = convertArray(times, track.times.constructor); + track.values = convertArray(values2, track.values.constructor); + tracks.push(track); + } + clip.tracks = tracks; + let minStartTime = Infinity; + for (let i = 0;i < clip.tracks.length; ++i) { + if (minStartTime > clip.tracks[i].times[0]) { + minStartTime = clip.tracks[i].times[0]; + } + } + for (let i = 0;i < clip.tracks.length; ++i) { + clip.tracks[i].shift(-1 * minStartTime); + } + clip.resetDuration(); + return clip; +} +function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) { + if (fps <= 0) + fps = 30; + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; + for (let i = 0;i < numTracks; ++i) { + const referenceTrack = referenceClip.tracks[i]; + const referenceTrackType = referenceTrack.ValueTypeName; + if (referenceTrackType === "bool" || referenceTrackType === "string") + continue; + const targetTrack = targetClip.tracks.find(function(track) { + return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType; + }); + if (targetTrack === undefined) + continue; + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); + if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + referenceOffset = referenceValueSize / 3; + } + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); + if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + targetOffset = targetValueSize / 3; + } + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; + if (referenceTime <= referenceTrack.times[0]) { + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else if (referenceTime >= referenceTrack.times[lastIndex]) { + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else { + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate(referenceTime); + referenceValue = interpolant.resultBuffer.slice(startIndex, endIndex); + } + if (referenceTrackType === "quaternion") { + const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate(); + referenceQuat.toArray(referenceValue); + } + const numTimes = targetTrack.times.length; + for (let j = 0;j < numTimes; ++j) { + const valueStart = j * targetValueSize + targetOffset; + if (referenceTrackType === "quaternion") { + Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart); + } else { + const valueEnd = targetValueSize - targetOffset * 2; + for (let k = 0;k < valueEnd; ++k) { + targetTrack.values[valueStart + k] -= referenceValue[k]; + } + } + } + } + targetClip.blendMode = AdditiveAnimationBlendMode; + return targetClip; +} +var AnimationUtils = { + convertArray, + isTypedArray, + getKeyframeOrder, + sortedArray, + flattenJSON, + subclip, + makeClipAdditive +}; + +class Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; + this.settings = null; + this.DefaultSettings_ = {}; + } + evaluate(t) { + const pp = this.parameterPositions; + let i1 = this._cachedIndex, t1 = pp[i1], t0 = pp[i1 - 1]; + validate_interval: { + seek: { + let right; + linear_scan: { + forward_scan: + if (!(t < t1)) { + for (let giveUpAt = i1 + 2;; ) { + if (t1 === undefined) { + if (t < t0) + break forward_scan; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + if (i1 === giveUpAt) + break; + t0 = t1; + t1 = pp[++i1]; + if (t < t1) { + break seek; + } + } + right = pp.length; + break linear_scan; + } + if (!(t >= t0)) { + const t1global = pp[1]; + if (t < t1global) { + i1 = 2; + t0 = t1global; + } + for (let giveUpAt = i1 - 2;; ) { + if (t0 === undefined) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (i1 === giveUpAt) + break; + t1 = t0; + t0 = pp[--i1 - 1]; + if (t >= t0) { + break seek; + } + } + right = i1; + i1 = 0; + break linear_scan; + } + break validate_interval; + } + while (i1 < right) { + const mid = i1 + right >>> 1; + if (t < pp[mid]) { + right = mid; + } else { + i1 = mid + 1; + } + } + t1 = pp[i1]; + t0 = pp[i1 - 1]; + if (t0 === undefined) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (t1 === undefined) { + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + } + this._cachedIndex = i1; + this.intervalChanged_(i1, t0, t1); + } + return this.interpolate_(i1, t0, t, t1); + } + getSettings_() { + return this.settings || this.DefaultSettings_; + } + copySampleValue_(index2) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, offset = index2 * stride; + for (let i = 0;i !== stride; ++i) { + result[i] = values2[offset + i]; + } + return result; + } + interpolate_() { + throw new Error("call to abstract method"); + } + intervalChanged_() { + } +} + +class CubicInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; + this.DefaultSettings_ = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + } + intervalChanged_(i1, t0, t1) { + const pp = this.parameterPositions; + let iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[iPrev], tNext = pp[iNext]; + if (tPrev === undefined) { + switch (this.getSettings_().endingStart) { + case ZeroSlopeEnding: + iPrev = i1; + tPrev = 2 * t0 - t1; + break; + case WrapAroundEnding: + iPrev = pp.length - 2; + tPrev = t0 + pp[iPrev] - pp[iPrev + 1]; + break; + default: + iPrev = i1; + tPrev = t1; + } + } + if (tNext === undefined) { + switch (this.getSettings_().endingEnd) { + case ZeroSlopeEnding: + iNext = i1; + tNext = 2 * t1 - t0; + break; + case WrapAroundEnding: + iNext = 1; + tNext = t1 + pp[1] - pp[0]; + break; + default: + iNext = i1 - 1; + tNext = t0; + } + } + const halfDt = (t1 - t0) * 0.5, stride = this.valueSize; + this._weightPrev = halfDt / (t0 - tPrev); + this._weightNext = halfDt / (tNext - t1); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o0 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p = (t - t0) / (t1 - t0), pp = p * p, ppp = pp * p; + const sP = -wP * ppp + 2 * wP * pp - wP * p; + const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1; + const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; + for (let i = 0;i !== stride; ++i) { + result[i] = sP * values2[oP + i] + s0 * values2[o0 + i] + s1 * values2[o1 + i] + sN * values2[oN + i]; + } + return result; + } +} + +class LinearInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = (t - t0) / (t1 - t0), weight0 = 1 - weight1; + for (let i = 0;i !== stride; ++i) { + result[i] = values2[offset0 + i] * weight0 + values2[offset1 + i] * weight1; + } + return result; + } +} + +class DiscreteInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1) { + return this.copySampleValue_(i1 - 1); + } +} + +class KeyframeTrack { + constructor(name2, times, values2, interpolation) { + if (name2 === undefined) + throw new Error("THREE.KeyframeTrack: track name is undefined"); + if (times === undefined || times.length === 0) + throw new Error("THREE.KeyframeTrack: no keyframes in track named " + name2); + this.name = name2; + this.times = convertArray(times, this.TimeBufferType); + this.values = convertArray(values2, this.ValueBufferType); + this.setInterpolation(interpolation || this.DefaultInterpolation); + } + static toJSON(track) { + const trackType = track.constructor; + let json; + if (trackType.toJSON !== this.toJSON) { + json = trackType.toJSON(track); + } else { + json = { + name: track.name, + times: convertArray(track.times, Array), + values: convertArray(track.values, Array) + }; + const interpolation = track.getInterpolation(); + if (interpolation !== track.DefaultInterpolation) { + json.interpolation = interpolation; + } + } + json.type = track.ValueTypeName; + return json; + } + InterpolantFactoryMethodDiscrete(result) { + return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodLinear(result) { + return new LinearInterpolant(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodSmooth(result) { + return new CubicInterpolant(this.times, this.values, this.getValueSize(), result); + } + setInterpolation(interpolation) { + let factoryMethod; + switch (interpolation) { + case InterpolateDiscrete: + factoryMethod = this.InterpolantFactoryMethodDiscrete; + break; + case InterpolateLinear: + factoryMethod = this.InterpolantFactoryMethodLinear; + break; + case InterpolateSmooth: + factoryMethod = this.InterpolantFactoryMethodSmooth; + break; + } + if (factoryMethod === undefined) { + const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; + if (this.createInterpolant === undefined) { + if (interpolation !== this.DefaultInterpolation) { + this.setInterpolation(this.DefaultInterpolation); + } else { + throw new Error(message); + } + } + console.warn("THREE.KeyframeTrack:", message); + return this; + } + this.createInterpolant = factoryMethod; + return this; + } + getInterpolation() { + switch (this.createInterpolant) { + case this.InterpolantFactoryMethodDiscrete: + return InterpolateDiscrete; + case this.InterpolantFactoryMethodLinear: + return InterpolateLinear; + case this.InterpolantFactoryMethodSmooth: + return InterpolateSmooth; + } + } + getValueSize() { + return this.values.length / this.times.length; + } + shift(timeOffset) { + if (timeOffset !== 0) { + const times = this.times; + for (let i = 0, n = times.length;i !== n; ++i) { + times[i] += timeOffset; + } + } + return this; + } + scale(timeScale) { + if (timeScale !== 1) { + const times = this.times; + for (let i = 0, n = times.length;i !== n; ++i) { + times[i] *= timeScale; + } + } + return this; + } + trim(startTime, endTime) { + const times = this.times, nKeys = times.length; + let from = 0, to = nKeys - 1; + while (from !== nKeys && times[from] < startTime) { + ++from; + } + while (to !== -1 && times[to] > endTime) { + --to; + } + ++to; + if (from !== 0 || to !== nKeys) { + if (from >= to) { + to = Math.max(to, 1); + from = to - 1; + } + const stride = this.getValueSize(); + this.times = times.slice(from, to); + this.values = this.values.slice(from * stride, to * stride); + } + return this; + } + validate() { + let valid = true; + const valueSize = this.getValueSize(); + if (valueSize - Math.floor(valueSize) !== 0) { + console.error("THREE.KeyframeTrack: Invalid value size in track.", this); + valid = false; + } + const times = this.times, values2 = this.values, nKeys = times.length; + if (nKeys === 0) { + console.error("THREE.KeyframeTrack: Track is empty.", this); + valid = false; + } + let prevTime = null; + for (let i = 0;i !== nKeys; i++) { + const currTime = times[i]; + if (typeof currTime === "number" && isNaN(currTime)) { + console.error("THREE.KeyframeTrack: Time is not a valid number.", this, i, currTime); + valid = false; + break; + } + if (prevTime !== null && prevTime > currTime) { + console.error("THREE.KeyframeTrack: Out of order keys.", this, i, currTime, prevTime); + valid = false; + break; + } + prevTime = currTime; + } + if (values2 !== undefined) { + if (isTypedArray(values2)) { + for (let i = 0, n = values2.length;i !== n; ++i) { + const value2 = values2[i]; + if (isNaN(value2)) { + console.error("THREE.KeyframeTrack: Value is not a valid number.", this, i, value2); + valid = false; + break; + } + } + } + } + return valid; + } + optimize() { + const times = this.times.slice(), values2 = this.values.slice(), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth, lastIndex = times.length - 1; + let writeIndex = 1; + for (let i = 1;i < lastIndex; ++i) { + let keep = false; + const time2 = times[i]; + const timeNext = times[i + 1]; + if (time2 !== timeNext && (i !== 1 || time2 !== times[0])) { + if (!smoothInterpolation) { + const offset = i * stride, offsetP = offset - stride, offsetN = offset + stride; + for (let j = 0;j !== stride; ++j) { + const value2 = values2[offset + j]; + if (value2 !== values2[offsetP + j] || value2 !== values2[offsetN + j]) { + keep = true; + break; + } + } + } else { + keep = true; + } + } + if (keep) { + if (i !== writeIndex) { + times[writeIndex] = times[i]; + const readOffset = i * stride, writeOffset = writeIndex * stride; + for (let j = 0;j !== stride; ++j) { + values2[writeOffset + j] = values2[readOffset + j]; + } + } + ++writeIndex; + } + } + if (lastIndex > 0) { + times[writeIndex] = times[lastIndex]; + for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0;j !== stride; ++j) { + values2[writeOffset + j] = values2[readOffset + j]; + } + ++writeIndex; + } + if (writeIndex !== times.length) { + this.times = times.slice(0, writeIndex); + this.values = values2.slice(0, writeIndex * stride); + } else { + this.times = times; + this.values = values2; + } + return this; + } + clone() { + const times = this.times.slice(); + const values2 = this.values.slice(); + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack(this.name, times, values2); + track.createInterpolant = this.createInterpolant; + return track; + } +} +KeyframeTrack.prototype.TimeBufferType = Float32Array; +KeyframeTrack.prototype.ValueBufferType = Float32Array; +KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + +class BooleanKeyframeTrack extends KeyframeTrack { + constructor(name2, times, values2) { + super(name2, times, values2); + } +} +BooleanKeyframeTrack.prototype.ValueTypeName = "bool"; +BooleanKeyframeTrack.prototype.ValueBufferType = Array; +BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +class ColorKeyframeTrack extends KeyframeTrack { +} +ColorKeyframeTrack.prototype.ValueTypeName = "color"; + +class NumberKeyframeTrack extends KeyframeTrack { +} +NumberKeyframeTrack.prototype.ValueTypeName = "number"; + +class QuaternionLinearInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, alpha = (t - t0) / (t1 - t0); + let offset = i1 * stride; + for (let end = offset + stride;offset !== end; offset += 4) { + Quaternion.slerpFlat(result, 0, values2, offset - stride, values2, offset, alpha); + } + return result; + } +} + +class QuaternionKeyframeTrack extends KeyframeTrack { + InterpolantFactoryMethodLinear(result) { + return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result); + } +} +QuaternionKeyframeTrack.prototype.ValueTypeName = "quaternion"; +QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +class StringKeyframeTrack extends KeyframeTrack { + constructor(name2, times, values2) { + super(name2, times, values2); + } +} +StringKeyframeTrack.prototype.ValueTypeName = "string"; +StringKeyframeTrack.prototype.ValueBufferType = Array; +StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +class VectorKeyframeTrack extends KeyframeTrack { +} +VectorKeyframeTrack.prototype.ValueTypeName = "vector"; + +class AnimationClip { + constructor(name2 = "", duration = -1, tracks = [], blendMode = NormalAnimationBlendMode) { + this.name = name2; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; + this.uuid = generateUUID(); + if (this.duration < 0) { + this.resetDuration(); + } + } + static parse(json) { + const tracks = [], jsonTracks = json.tracks, frameTime = 1 / (json.fps || 1); + for (let i = 0, n = jsonTracks.length;i !== n; ++i) { + tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime)); + } + const clip = new this(json.name, json.duration, tracks, json.blendMode); + clip.uuid = json.uuid; + return clip; + } + static toJSON(clip) { + const tracks = [], clipTracks = clip.tracks; + const json = { + name: clip.name, + duration: clip.duration, + tracks, + uuid: clip.uuid, + blendMode: clip.blendMode + }; + for (let i = 0, n = clipTracks.length;i !== n; ++i) { + tracks.push(KeyframeTrack.toJSON(clipTracks[i])); + } + return json; + } + static CreateFromMorphTargetSequence(name2, morphTargetSequence, fps, noLoop) { + const numMorphTargets = morphTargetSequence.length; + const tracks = []; + for (let i = 0;i < numMorphTargets; i++) { + let times = []; + let values2 = []; + times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets); + values2.push(0, 1, 0); + const order = getKeyframeOrder(times); + times = sortedArray(times, 1, order); + values2 = sortedArray(values2, 1, order); + if (!noLoop && times[0] === 0) { + times.push(numMorphTargets); + values2.push(values2[0]); + } + tracks.push(new NumberKeyframeTrack(".morphTargetInfluences[" + morphTargetSequence[i].name + "]", times, values2).scale(1 / fps)); + } + return new this(name2, -1, tracks); + } + static findByName(objectOrClipArray, name2) { + let clipArray = objectOrClipArray; + if (!Array.isArray(objectOrClipArray)) { + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; + } + for (let i = 0;i < clipArray.length; i++) { + if (clipArray[i].name === name2) { + return clipArray[i]; + } + } + return null; + } + static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) { + const animationToMorphTargets = {}; + const pattern = /^([\w-]*?)([\d]+)$/; + for (let i = 0, il = morphTargets.length;i < il; i++) { + const morphTarget = morphTargets[i]; + const parts = morphTarget.name.match(pattern); + if (parts && parts.length > 1) { + const name2 = parts[1]; + let animationMorphTargets = animationToMorphTargets[name2]; + if (!animationMorphTargets) { + animationToMorphTargets[name2] = animationMorphTargets = []; + } + animationMorphTargets.push(morphTarget); + } + } + const clips = []; + for (const name2 in animationToMorphTargets) { + clips.push(this.CreateFromMorphTargetSequence(name2, animationToMorphTargets[name2], fps, noLoop)); + } + return clips; + } + static parseAnimation(animation, bones) { + if (!animation) { + console.error("THREE.AnimationClip: No animation in JSONLoader data."); + return null; + } + const addNonemptyTrack = function(trackType, trackName, animationKeys, propertyName, destTracks) { + if (animationKeys.length !== 0) { + const times = []; + const values2 = []; + flattenJSON(animationKeys, times, values2, propertyName); + if (times.length !== 0) { + destTracks.push(new trackType(trackName, times, values2)); + } + } + }; + const tracks = []; + const clipName = animation.name || "default"; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; + let duration = animation.length || -1; + const hierarchyTracks = animation.hierarchy || []; + for (let h = 0;h < hierarchyTracks.length; h++) { + const animationKeys = hierarchyTracks[h].keys; + if (!animationKeys || animationKeys.length === 0) + continue; + if (animationKeys[0].morphTargets) { + const morphTargetNames = {}; + let k; + for (k = 0;k < animationKeys.length; k++) { + if (animationKeys[k].morphTargets) { + for (let m = 0;m < animationKeys[k].morphTargets.length; m++) { + morphTargetNames[animationKeys[k].morphTargets[m]] = -1; + } + } + } + for (const morphTargetName in morphTargetNames) { + const times = []; + const values2 = []; + for (let m = 0;m !== animationKeys[k].morphTargets.length; ++m) { + const animationKey = animationKeys[k]; + times.push(animationKey.time); + values2.push(animationKey.morphTarget === morphTargetName ? 1 : 0); + } + tracks.push(new NumberKeyframeTrack(".morphTargetInfluence[" + morphTargetName + "]", times, values2)); + } + duration = morphTargetNames.length * fps; + } else { + const boneName = ".bones[" + bones[h].name + "]"; + addNonemptyTrack(VectorKeyframeTrack, boneName + ".position", animationKeys, "pos", tracks); + addNonemptyTrack(QuaternionKeyframeTrack, boneName + ".quaternion", animationKeys, "rot", tracks); + addNonemptyTrack(VectorKeyframeTrack, boneName + ".scale", animationKeys, "scl", tracks); + } + } + if (tracks.length === 0) { + return null; + } + const clip = new this(clipName, duration, tracks, blendMode); + return clip; + } + resetDuration() { + const tracks = this.tracks; + let duration = 0; + for (let i = 0, n = tracks.length;i !== n; ++i) { + const track = this.tracks[i]; + duration = Math.max(duration, track.times[track.times.length - 1]); + } + this.duration = duration; + return this; + } + trim() { + for (let i = 0;i < this.tracks.length; i++) { + this.tracks[i].trim(0, this.duration); + } + return this; + } + validate() { + let valid = true; + for (let i = 0;i < this.tracks.length; i++) { + valid = valid && this.tracks[i].validate(); + } + return valid; + } + optimize() { + for (let i = 0;i < this.tracks.length; i++) { + this.tracks[i].optimize(); + } + return this; + } + clone() { + const tracks = []; + for (let i = 0;i < this.tracks.length; i++) { + tracks.push(this.tracks[i].clone()); + } + return new this.constructor(this.name, this.duration, tracks, this.blendMode); + } + toJSON() { + return this.constructor.toJSON(this); + } +} +function getTrackTypeForValueTypeName(typeName) { + switch (typeName.toLowerCase()) { + case "scalar": + case "double": + case "float": + case "number": + case "integer": + return NumberKeyframeTrack; + case "vector": + case "vector2": + case "vector3": + case "vector4": + return VectorKeyframeTrack; + case "color": + return ColorKeyframeTrack; + case "quaternion": + return QuaternionKeyframeTrack; + case "bool": + case "boolean": + return BooleanKeyframeTrack; + case "string": + return StringKeyframeTrack; + } + throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + typeName); +} +function parseKeyframeTrack(json) { + if (json.type === undefined) { + throw new Error("THREE.KeyframeTrack: track type undefined, can not parse"); + } + const trackType = getTrackTypeForValueTypeName(json.type); + if (json.times === undefined) { + const times = [], values2 = []; + flattenJSON(json.keys, times, values2, "value"); + json.times = times; + json.values = values2; + } + if (trackType.parse !== undefined) { + return trackType.parse(json); + } else { + return new trackType(json.name, json.times, json.values, json.interpolation); + } +} +var Cache = { + enabled: false, + files: {}, + add: function(key2, file) { + if (this.enabled === false) + return; + this.files[key2] = file; + }, + get: function(key2) { + if (this.enabled === false) + return; + return this.files[key2]; + }, + remove: function(key2) { + delete this.files[key2]; + }, + clear: function() { + this.files = {}; + } +}; + +class LoadingManager { + constructor(onLoad, onProgress, onError) { + const scope = this; + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + this.itemStart = function(url) { + itemsTotal++; + if (isLoading === false) { + if (scope.onStart !== undefined) { + scope.onStart(url, itemsLoaded, itemsTotal); + } + } + isLoading = true; + }; + this.itemEnd = function(url) { + itemsLoaded++; + if (scope.onProgress !== undefined) { + scope.onProgress(url, itemsLoaded, itemsTotal); + } + if (itemsLoaded === itemsTotal) { + isLoading = false; + if (scope.onLoad !== undefined) { + scope.onLoad(); + } + } + }; + this.itemError = function(url) { + if (scope.onError !== undefined) { + scope.onError(url); + } + }; + this.resolveURL = function(url) { + if (urlModifier) { + return urlModifier(url); + } + return url; + }; + this.setURLModifier = function(transform2) { + urlModifier = transform2; + return this; + }; + this.addHandler = function(regex, loader) { + handlers.push(regex, loader); + return this; + }; + this.removeHandler = function(regex) { + const index2 = handlers.indexOf(regex); + if (index2 !== -1) { + handlers.splice(index2, 2); + } + return this; + }; + this.getHandler = function(file) { + for (let i = 0, l = handlers.length;i < l; i += 2) { + const regex = handlers[i]; + const loader = handlers[i + 1]; + if (regex.global) + regex.lastIndex = 0; + if (regex.test(file)) { + return loader; + } + } + return null; + }; + } +} +var DefaultLoadingManager = /* @__PURE__ */ new LoadingManager; + +class Loader { + constructor(manager) { + this.manager = manager !== undefined ? manager : DefaultLoadingManager; + this.crossOrigin = "anonymous"; + this.withCredentials = false; + this.path = ""; + this.resourcePath = ""; + this.requestHeader = {}; + } + load() { + } + loadAsync(url, onProgress) { + const scope = this; + return new Promise(function(resolve, reject2) { + scope.load(url, resolve, onProgress, reject2); + }); + } + parse() { + } + setCrossOrigin(crossOrigin) { + this.crossOrigin = crossOrigin; + return this; + } + setWithCredentials(value2) { + this.withCredentials = value2; + return this; + } + setPath(path) { + this.path = path; + return this; + } + setResourcePath(resourcePath) { + this.resourcePath = resourcePath; + return this; + } + setRequestHeader(requestHeader) { + this.requestHeader = requestHeader; + return this; + } +} +Loader.DEFAULT_MATERIAL_NAME = "__DEFAULT"; +var loading = {}; + +class HttpError extends Error { + constructor(message, response) { + super(message); + this.response = response; + } +} + +class FileLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (url === undefined) + url = ""; + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const cached = Cache.get(url); + if (cached !== undefined) { + this.manager.itemStart(url); + setTimeout(() => { + if (onLoad) + onLoad(cached); + this.manager.itemEnd(url); + }, 0); + return cached; + } + if (loading[url] !== undefined) { + loading[url].push({ + onLoad, + onProgress, + onError + }); + return; + } + loading[url] = []; + loading[url].push({ + onLoad, + onProgress, + onError + }); + const req = new Request(url, { + headers: new Headers(this.requestHeader), + credentials: this.withCredentials ? "include" : "same-origin" + }); + const mimeType = this.mimeType; + const responseType = this.responseType; + fetch(req).then((response) => { + if (response.status === 200 || response.status === 0) { + if (response.status === 0) { + console.warn("THREE.FileLoader: HTTP Status 0 received."); + } + if (typeof ReadableStream === "undefined" || response.body === undefined || response.body.getReader === undefined) { + return response; + } + const callbacks = loading[url]; + const reader = response.body.getReader(); + const contentLength = response.headers.get("X-File-Size") || response.headers.get("Content-Length"); + const total = contentLength ? parseInt(contentLength) : 0; + const lengthComputable = total !== 0; + let loaded = 0; + const stream = new ReadableStream({ + start(controller) { + readData(); + function readData() { + reader.read().then(({ done, value: value2 }) => { + if (done) { + controller.close(); + } else { + loaded += value2.byteLength; + const event = new ProgressEvent("progress", { lengthComputable, loaded, total }); + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onProgress) + callback.onProgress(event); + } + controller.enqueue(value2); + readData(); + } + }, (e) => { + controller.error(e); + }); + } + } + }); + return new Response(stream); + } else { + throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response); + } + }).then((response) => { + switch (responseType) { + case "arraybuffer": + return response.arrayBuffer(); + case "blob": + return response.blob(); + case "document": + return response.text().then((text2) => { + const parser = new DOMParser; + return parser.parseFromString(text2, mimeType); + }); + case "json": + return response.json(); + default: + if (mimeType === undefined) { + return response.text(); + } else { + const re = /charset="?([^;"\s]*)"?/i; + const exec = re.exec(mimeType); + const label = exec && exec[1] ? exec[1].toLowerCase() : undefined; + const decoder = new TextDecoder(label); + return response.arrayBuffer().then((ab) => decoder.decode(ab)); + } + } + }).then((data2) => { + Cache.add(url, data2); + const callbacks = loading[url]; + delete loading[url]; + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onLoad) + callback.onLoad(data2); + } + }).catch((err) => { + const callbacks = loading[url]; + if (callbacks === undefined) { + this.manager.itemError(url); + throw err; + } + delete loading[url]; + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onError) + callback.onError(err); + } + this.manager.itemError(url); + }).finally(() => { + this.manager.itemEnd(url); + }); + this.manager.itemStart(url); + } + setResponseType(value2) { + this.responseType = value2; + return this; + } + setMimeType(value2) { + this.mimeType = value2; + return this; + } +} + +class AnimationLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const animations = []; + for (let i = 0;i < json.length; i++) { + const clip = AnimationClip.parse(json[i]); + animations.push(clip); + } + return animations; + } +} + +class CompressedTextureLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const images = []; + const texture = new CompressedTexture; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(scope.withCredentials); + let loaded = 0; + function loadTexture(i) { + loader.load(url[i], function(buffer) { + const texDatas = scope.parse(buffer, true); + images[i] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + loaded += 1; + if (loaded === 6) { + if (texDatas.mipmapCount === 1) + texture.minFilter = LinearFilter; + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + } + }, onProgress, onError); + } + if (Array.isArray(url)) { + for (let i = 0, il = url.length;i < il; ++i) { + loadTexture(i); + } + } else { + loader.load(url, function(buffer) { + const texDatas = scope.parse(buffer, true); + if (texDatas.isCubemap) { + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + for (let f = 0;f < faces; f++) { + images[f] = { mipmaps: [] }; + for (let i = 0;i < texDatas.mipmapCount; i++) { + images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]); + images[f].format = texDatas.format; + images[f].width = texDatas.width; + images[f].height = texDatas.height; + } + } + texture.image = images; + } else { + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + } + if (texDatas.mipmapCount === 1) { + texture.minFilter = LinearFilter; + } + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + }, onProgress, onError); + } + return texture; + } +} + +class ImageLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache.get(url); + if (cached !== undefined) { + scope.manager.itemStart(url); + setTimeout(function() { + if (onLoad) + onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const image = createElementNS("img"); + function onImageLoad() { + removeEventListeners(); + Cache.add(url, this); + if (onLoad) + onLoad(this); + scope.manager.itemEnd(url); + } + function onImageError(event) { + removeEventListeners(); + if (onError) + onError(event); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + } + function removeEventListeners() { + image.removeEventListener("load", onImageLoad, false); + image.removeEventListener("error", onImageError, false); + } + image.addEventListener("load", onImageLoad, false); + image.addEventListener("error", onImageError, false); + if (url.slice(0, 5) !== "data:") { + if (this.crossOrigin !== undefined) + image.crossOrigin = this.crossOrigin; + } + scope.manager.itemStart(url); + image.src = url; + return image; + } +} + +class CubeTextureLoader extends Loader { + constructor(manager) { + super(manager); + } + load(urls, onLoad, onProgress, onError) { + const texture = new CubeTexture; + texture.colorSpace = SRGBColorSpace; + const loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + let loaded = 0; + function loadTexture(i) { + loader.load(urls[i], function(image) { + texture.images[i] = image; + loaded++; + if (loaded === 6) { + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + } + }, undefined, onError); + } + for (let i = 0;i < urls.length; ++i) { + loadTexture(i); + } + return texture; + } +} + +class DataTextureLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const texture = new DataTexture; + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setPath(this.path); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(buffer) { + let texData; + try { + texData = scope.parse(buffer); + } catch (error) { + if (onError !== undefined) { + onError(error); + } else { + console.error(error); + return; + } + } + if (texData.image !== undefined) { + texture.image = texData.image; + } else if (texData.data !== undefined) { + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; + } + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + if (texData.colorSpace !== undefined) { + texture.colorSpace = texData.colorSpace; + } + if (texData.flipY !== undefined) { + texture.flipY = texData.flipY; + } + if (texData.format !== undefined) { + texture.format = texData.format; + } + if (texData.type !== undefined) { + texture.type = texData.type; + } + if (texData.mipmaps !== undefined) { + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter; + } + if (texData.mipmapCount === 1) { + texture.minFilter = LinearFilter; + } + if (texData.generateMipmaps !== undefined) { + texture.generateMipmaps = texData.generateMipmaps; + } + texture.needsUpdate = true; + if (onLoad) + onLoad(texture, texData); + }, onProgress, onError); + return texture; + } +} + +class TextureLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const texture = new Texture; + const loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + loader.load(url, function(image) { + texture.image = image; + texture.needsUpdate = true; + if (onLoad !== undefined) { + onLoad(texture); + } + }, onProgress, onError); + return texture; + } +} + +class Light extends Object3D { + constructor(color, intensity = 1) { + super(); + this.isLight = true; + this.type = "Light"; + this.color = new Color(color); + this.intensity = intensity; + } + dispose() { + } + copy(source, recursive) { + super.copy(source, recursive); + this.color.copy(source.color); + this.intensity = source.intensity; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.color = this.color.getHex(); + data2.object.intensity = this.intensity; + if (this.groundColor !== undefined) + data2.object.groundColor = this.groundColor.getHex(); + if (this.distance !== undefined) + data2.object.distance = this.distance; + if (this.angle !== undefined) + data2.object.angle = this.angle; + if (this.decay !== undefined) + data2.object.decay = this.decay; + if (this.penumbra !== undefined) + data2.object.penumbra = this.penumbra; + if (this.shadow !== undefined) + data2.object.shadow = this.shadow.toJSON(); + if (this.target !== undefined) + data2.object.target = this.target.uuid; + return data2; + } +} + +class HemisphereLight extends Light { + constructor(skyColor, groundColor, intensity) { + super(skyColor, intensity); + this.isHemisphereLight = true; + this.type = "HemisphereLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.groundColor = new Color(groundColor); + } + copy(source, recursive) { + super.copy(source, recursive); + this.groundColor.copy(source.groundColor); + return this; + } +} +var _projScreenMatrix$1 = /* @__PURE__ */ new Matrix4; +var _lightPositionWorld$1 = /* @__PURE__ */ new Vector3; +var _lookTarget$1 = /* @__PURE__ */ new Vector3; + +class LightShadow { + constructor(camera) { + this.camera = camera; + this.intensity = 1; + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; + this.mapSize = new Vector2(512, 512); + this.map = null; + this.mapPass = null; + this.matrix = new Matrix4; + this.autoUpdate = true; + this.needsUpdate = false; + this._frustum = new Frustum; + this._frameExtents = new Vector2(1, 1); + this._viewportCount = 1; + this._viewports = [ + new Vector4(0, 0, 1, 1) + ]; + } + getViewportCount() { + return this._viewportCount; + } + getFrustum() { + return this._frustum; + } + updateMatrices(light) { + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; + _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld); + shadowCamera.position.copy(_lightPositionWorld$1); + _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld); + shadowCamera.lookAt(_lookTarget$1); + shadowCamera.updateMatrixWorld(); + _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix$1); + shadowMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + shadowMatrix.multiply(_projScreenMatrix$1); + } + getViewport(viewportIndex) { + return this._viewports[viewportIndex]; + } + getFrameExtents() { + return this._frameExtents; + } + dispose() { + if (this.map) { + this.map.dispose(); + } + if (this.mapPass) { + this.mapPass.dispose(); + } + } + copy(source) { + this.camera = source.camera.clone(); + this.intensity = source.intensity; + this.bias = source.bias; + this.radius = source.radius; + this.mapSize.copy(source.mapSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + toJSON() { + const object = {}; + if (this.intensity !== 1) + object.intensity = this.intensity; + if (this.bias !== 0) + object.bias = this.bias; + if (this.normalBias !== 0) + object.normalBias = this.normalBias; + if (this.radius !== 1) + object.radius = this.radius; + if (this.mapSize.x !== 512 || this.mapSize.y !== 512) + object.mapSize = this.mapSize.toArray(); + object.camera = this.camera.toJSON(false).object; + delete object.camera.matrix; + return object; + } +} + +class SpotLightShadow extends LightShadow { + constructor() { + super(new PerspectiveCamera(50, 1, 0.5, 500)); + this.isSpotLightShadow = true; + this.focus = 1; + } + updateMatrices(light) { + const camera = this.camera; + const fov2 = RAD2DEG * 2 * light.angle * this.focus; + const aspect2 = this.mapSize.width / this.mapSize.height; + const far = light.distance || camera.far; + if (fov2 !== camera.fov || aspect2 !== camera.aspect || far !== camera.far) { + camera.fov = fov2; + camera.aspect = aspect2; + camera.far = far; + camera.updateProjectionMatrix(); + } + super.updateMatrices(light); + } + copy(source) { + super.copy(source); + this.focus = source.focus; + return this; + } +} + +class SpotLight extends Light { + constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2) { + super(color, intensity); + this.isSpotLight = true; + this.type = "SpotLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D; + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; + this.map = null; + this.shadow = new SpotLightShadow; + } + get power() { + return this.intensity * Math.PI; + } + set power(power) { + this.intensity = power / Math.PI; + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } +} +var _projScreenMatrix = /* @__PURE__ */ new Matrix4; +var _lightPositionWorld = /* @__PURE__ */ new Vector3; +var _lookTarget = /* @__PURE__ */ new Vector3; + +class PointLightShadow extends LightShadow { + constructor() { + super(new PerspectiveCamera(90, 1, 0.5, 500)); + this.isPointLightShadow = true; + this._frameExtents = new Vector2(4, 2); + this._viewportCount = 6; + this._viewports = [ + new Vector4(2, 1, 1, 1), + new Vector4(0, 1, 1, 1), + new Vector4(3, 1, 1, 1), + new Vector4(1, 1, 1, 1), + new Vector4(3, 0, 1, 1), + new Vector4(1, 0, 1, 1) + ]; + this._cubeDirections = [ + new Vector3(1, 0, 0), + new Vector3(-1, 0, 0), + new Vector3(0, 0, 1), + new Vector3(0, 0, -1), + new Vector3(0, 1, 0), + new Vector3(0, -1, 0) + ]; + this._cubeUps = [ + new Vector3(0, 1, 0), + new Vector3(0, 1, 0), + new Vector3(0, 1, 0), + new Vector3(0, 1, 0), + new Vector3(0, 0, 1), + new Vector3(0, 0, -1) + ]; + } + updateMatrices(light, viewportIndex = 0) { + const camera = this.camera; + const shadowMatrix = this.matrix; + const far = light.distance || camera.far; + if (far !== camera.far) { + camera.far = far; + camera.updateProjectionMatrix(); + } + _lightPositionWorld.setFromMatrixPosition(light.matrixWorld); + camera.position.copy(_lightPositionWorld); + _lookTarget.copy(camera.position); + _lookTarget.add(this._cubeDirections[viewportIndex]); + camera.up.copy(this._cubeUps[viewportIndex]); + camera.lookAt(_lookTarget); + camera.updateMatrixWorld(); + shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z); + _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix); + } +} + +class PointLight extends Light { + constructor(color, intensity, distance = 0, decay = 2) { + super(color, intensity); + this.isPointLight = true; + this.type = "PointLight"; + this.distance = distance; + this.decay = decay; + this.shadow = new PointLightShadow; + } + get power() { + return this.intensity * 4 * Math.PI; + } + set power(power) { + this.intensity = power / (4 * Math.PI); + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.decay = source.decay; + this.shadow = source.shadow.clone(); + return this; + } +} + +class OrthographicCamera extends Camera { + constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) { + super(); + this.isOrthographicCamera = true; + this.type = "OrthographicCamera"; + this.zoom = 1; + this.view = null; + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + this.near = near; + this.far = far; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign({}, source.view); + return this; + } + setViewOffset(fullWidth, fullHeight, x, y, width2, height2) { + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width2; + this.view.height = height2; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const dx = (this.right - this.left) / (2 * this.zoom); + const dy = (this.top - this.bottom) / (2 * this.zoom); + const cx = (this.right + this.left) / 2; + const cy = (this.top + this.bottom) / 2; + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + if (this.view !== null && this.view.enabled) { + const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom; + const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom; + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + } + this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.zoom = this.zoom; + data2.object.left = this.left; + data2.object.right = this.right; + data2.object.top = this.top; + data2.object.bottom = this.bottom; + data2.object.near = this.near; + data2.object.far = this.far; + if (this.view !== null) + data2.object.view = Object.assign({}, this.view); + return data2; + } +} + +class DirectionalLightShadow extends LightShadow { + constructor() { + super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500)); + this.isDirectionalLightShadow = true; + } +} + +class DirectionalLight extends Light { + constructor(color, intensity) { + super(color, intensity); + this.isDirectionalLight = true; + this.type = "DirectionalLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D; + this.shadow = new DirectionalLightShadow; + } + dispose() { + this.shadow.dispose(); + } + copy(source) { + super.copy(source); + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } +} + +class AmbientLight extends Light { + constructor(color, intensity) { + super(color, intensity); + this.isAmbientLight = true; + this.type = "AmbientLight"; + } +} + +class RectAreaLight extends Light { + constructor(color, intensity, width2 = 10, height2 = 10) { + super(color, intensity); + this.isRectAreaLight = true; + this.type = "RectAreaLight"; + this.width = width2; + this.height = height2; + } + get power() { + return this.intensity * this.width * this.height * Math.PI; + } + set power(power) { + this.intensity = power / (this.width * this.height * Math.PI); + } + copy(source) { + super.copy(source); + this.width = source.width; + this.height = source.height; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.width = this.width; + data2.object.height = this.height; + return data2; + } +} + +class SphericalHarmonics3 { + constructor() { + this.isSphericalHarmonics3 = true; + this.coefficients = []; + for (let i = 0;i < 9; i++) { + this.coefficients.push(new Vector3); + } + } + set(coefficients) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].copy(coefficients[i]); + } + return this; + } + zero() { + for (let i = 0;i < 9; i++) { + this.coefficients[i].set(0, 0, 0); + } + return this; + } + getAt(normal, target) { + const { x, y, z } = normal; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.282095); + target.addScaledVector(coeff[1], 0.488603 * y); + target.addScaledVector(coeff[2], 0.488603 * z); + target.addScaledVector(coeff[3], 0.488603 * x); + target.addScaledVector(coeff[4], 1.092548 * (x * y)); + target.addScaledVector(coeff[5], 1.092548 * (y * z)); + target.addScaledVector(coeff[6], 0.315392 * (3 * z * z - 1)); + target.addScaledVector(coeff[7], 1.092548 * (x * z)); + target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y)); + return target; + } + getIrradianceAt(normal, target) { + const { x, y, z } = normal; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.886227); + target.addScaledVector(coeff[1], 2 * 0.511664 * y); + target.addScaledVector(coeff[2], 2 * 0.511664 * z); + target.addScaledVector(coeff[3], 2 * 0.511664 * x); + target.addScaledVector(coeff[4], 2 * 0.429043 * x * y); + target.addScaledVector(coeff[5], 2 * 0.429043 * y * z); + target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); + target.addScaledVector(coeff[7], 2 * 0.429043 * x * z); + target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); + return target; + } + add(sh) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].add(sh.coefficients[i]); + } + return this; + } + addScaledSH(sh, s) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].addScaledVector(sh.coefficients[i], s); + } + return this; + } + scale(s) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].multiplyScalar(s); + } + return this; + } + lerp(sh, alpha) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].lerp(sh.coefficients[i], alpha); + } + return this; + } + equals(sh) { + for (let i = 0;i < 9; i++) { + if (!this.coefficients[i].equals(sh.coefficients[i])) { + return false; + } + } + return true; + } + copy(sh) { + return this.set(sh.coefficients); + } + clone() { + return new this.constructor().copy(this); + } + fromArray(array, offset = 0) { + const coefficients = this.coefficients; + for (let i = 0;i < 9; i++) { + coefficients[i].fromArray(array, offset + i * 3); + } + return this; + } + toArray(array = [], offset = 0) { + const coefficients = this.coefficients; + for (let i = 0;i < 9; i++) { + coefficients[i].toArray(array, offset + i * 3); + } + return array; + } + static getBasisAt(normal, shBasis) { + const { x, y, z } = normal; + shBasis[0] = 0.282095; + shBasis[1] = 0.488603 * y; + shBasis[2] = 0.488603 * z; + shBasis[3] = 0.488603 * x; + shBasis[4] = 1.092548 * x * y; + shBasis[5] = 1.092548 * y * z; + shBasis[6] = 0.315392 * (3 * z * z - 1); + shBasis[7] = 1.092548 * x * z; + shBasis[8] = 0.546274 * (x * x - y * y); + } +} + +class LightProbe extends Light { + constructor(sh = new SphericalHarmonics3, intensity = 1) { + super(undefined, intensity); + this.isLightProbe = true; + this.sh = sh; + } + copy(source) { + super.copy(source); + this.sh.copy(source.sh); + return this; + } + fromJSON(json) { + this.intensity = json.intensity; + this.sh.fromArray(json.sh); + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.sh = this.sh.toArray(); + return data2; + } +} + +class MaterialLoader extends Loader { + constructor(manager) { + super(manager); + this.textures = {}; + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const textures = this.textures; + function getTexture(name2) { + if (textures[name2] === undefined) { + console.warn("THREE.MaterialLoader: Undefined texture", name2); + } + return textures[name2]; + } + const material = this.createMaterialFromType(json.type); + if (json.uuid !== undefined) + material.uuid = json.uuid; + if (json.name !== undefined) + material.name = json.name; + if (json.color !== undefined && material.color !== undefined) + material.color.setHex(json.color); + if (json.roughness !== undefined) + material.roughness = json.roughness; + if (json.metalness !== undefined) + material.metalness = json.metalness; + if (json.sheen !== undefined) + material.sheen = json.sheen; + if (json.sheenColor !== undefined) + material.sheenColor = new Color().setHex(json.sheenColor); + if (json.sheenRoughness !== undefined) + material.sheenRoughness = json.sheenRoughness; + if (json.emissive !== undefined && material.emissive !== undefined) + material.emissive.setHex(json.emissive); + if (json.specular !== undefined && material.specular !== undefined) + material.specular.setHex(json.specular); + if (json.specularIntensity !== undefined) + material.specularIntensity = json.specularIntensity; + if (json.specularColor !== undefined && material.specularColor !== undefined) + material.specularColor.setHex(json.specularColor); + if (json.shininess !== undefined) + material.shininess = json.shininess; + if (json.clearcoat !== undefined) + material.clearcoat = json.clearcoat; + if (json.clearcoatRoughness !== undefined) + material.clearcoatRoughness = json.clearcoatRoughness; + if (json.dispersion !== undefined) + material.dispersion = json.dispersion; + if (json.iridescence !== undefined) + material.iridescence = json.iridescence; + if (json.iridescenceIOR !== undefined) + material.iridescenceIOR = json.iridescenceIOR; + if (json.iridescenceThicknessRange !== undefined) + material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if (json.transmission !== undefined) + material.transmission = json.transmission; + if (json.thickness !== undefined) + material.thickness = json.thickness; + if (json.attenuationDistance !== undefined) + material.attenuationDistance = json.attenuationDistance; + if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) + material.attenuationColor.setHex(json.attenuationColor); + if (json.anisotropy !== undefined) + material.anisotropy = json.anisotropy; + if (json.anisotropyRotation !== undefined) + material.anisotropyRotation = json.anisotropyRotation; + if (json.fog !== undefined) + material.fog = json.fog; + if (json.flatShading !== undefined) + material.flatShading = json.flatShading; + if (json.blending !== undefined) + material.blending = json.blending; + if (json.combine !== undefined) + material.combine = json.combine; + if (json.side !== undefined) + material.side = json.side; + if (json.shadowSide !== undefined) + material.shadowSide = json.shadowSide; + if (json.opacity !== undefined) + material.opacity = json.opacity; + if (json.transparent !== undefined) + material.transparent = json.transparent; + if (json.alphaTest !== undefined) + material.alphaTest = json.alphaTest; + if (json.alphaHash !== undefined) + material.alphaHash = json.alphaHash; + if (json.depthFunc !== undefined) + material.depthFunc = json.depthFunc; + if (json.depthTest !== undefined) + material.depthTest = json.depthTest; + if (json.depthWrite !== undefined) + material.depthWrite = json.depthWrite; + if (json.colorWrite !== undefined) + material.colorWrite = json.colorWrite; + if (json.blendSrc !== undefined) + material.blendSrc = json.blendSrc; + if (json.blendDst !== undefined) + material.blendDst = json.blendDst; + if (json.blendEquation !== undefined) + material.blendEquation = json.blendEquation; + if (json.blendSrcAlpha !== undefined) + material.blendSrcAlpha = json.blendSrcAlpha; + if (json.blendDstAlpha !== undefined) + material.blendDstAlpha = json.blendDstAlpha; + if (json.blendEquationAlpha !== undefined) + material.blendEquationAlpha = json.blendEquationAlpha; + if (json.blendColor !== undefined && material.blendColor !== undefined) + material.blendColor.setHex(json.blendColor); + if (json.blendAlpha !== undefined) + material.blendAlpha = json.blendAlpha; + if (json.stencilWriteMask !== undefined) + material.stencilWriteMask = json.stencilWriteMask; + if (json.stencilFunc !== undefined) + material.stencilFunc = json.stencilFunc; + if (json.stencilRef !== undefined) + material.stencilRef = json.stencilRef; + if (json.stencilFuncMask !== undefined) + material.stencilFuncMask = json.stencilFuncMask; + if (json.stencilFail !== undefined) + material.stencilFail = json.stencilFail; + if (json.stencilZFail !== undefined) + material.stencilZFail = json.stencilZFail; + if (json.stencilZPass !== undefined) + material.stencilZPass = json.stencilZPass; + if (json.stencilWrite !== undefined) + material.stencilWrite = json.stencilWrite; + if (json.wireframe !== undefined) + material.wireframe = json.wireframe; + if (json.wireframeLinewidth !== undefined) + material.wireframeLinewidth = json.wireframeLinewidth; + if (json.wireframeLinecap !== undefined) + material.wireframeLinecap = json.wireframeLinecap; + if (json.wireframeLinejoin !== undefined) + material.wireframeLinejoin = json.wireframeLinejoin; + if (json.rotation !== undefined) + material.rotation = json.rotation; + if (json.linewidth !== undefined) + material.linewidth = json.linewidth; + if (json.dashSize !== undefined) + material.dashSize = json.dashSize; + if (json.gapSize !== undefined) + material.gapSize = json.gapSize; + if (json.scale !== undefined) + material.scale = json.scale; + if (json.polygonOffset !== undefined) + material.polygonOffset = json.polygonOffset; + if (json.polygonOffsetFactor !== undefined) + material.polygonOffsetFactor = json.polygonOffsetFactor; + if (json.polygonOffsetUnits !== undefined) + material.polygonOffsetUnits = json.polygonOffsetUnits; + if (json.dithering !== undefined) + material.dithering = json.dithering; + if (json.alphaToCoverage !== undefined) + material.alphaToCoverage = json.alphaToCoverage; + if (json.premultipliedAlpha !== undefined) + material.premultipliedAlpha = json.premultipliedAlpha; + if (json.forceSinglePass !== undefined) + material.forceSinglePass = json.forceSinglePass; + if (json.visible !== undefined) + material.visible = json.visible; + if (json.toneMapped !== undefined) + material.toneMapped = json.toneMapped; + if (json.userData !== undefined) + material.userData = json.userData; + if (json.vertexColors !== undefined) { + if (typeof json.vertexColors === "number") { + material.vertexColors = json.vertexColors > 0 ? true : false; + } else { + material.vertexColors = json.vertexColors; + } + } + if (json.uniforms !== undefined) { + for (const name2 in json.uniforms) { + const uniform = json.uniforms[name2]; + material.uniforms[name2] = {}; + switch (uniform.type) { + case "t": + material.uniforms[name2].value = getTexture(uniform.value); + break; + case "c": + material.uniforms[name2].value = new Color().setHex(uniform.value); + break; + case "v2": + material.uniforms[name2].value = new Vector2().fromArray(uniform.value); + break; + case "v3": + material.uniforms[name2].value = new Vector3().fromArray(uniform.value); + break; + case "v4": + material.uniforms[name2].value = new Vector4().fromArray(uniform.value); + break; + case "m3": + material.uniforms[name2].value = new Matrix3().fromArray(uniform.value); + break; + case "m4": + material.uniforms[name2].value = new Matrix4().fromArray(uniform.value); + break; + default: + material.uniforms[name2].value = uniform.value; + } + } + } + if (json.defines !== undefined) + material.defines = json.defines; + if (json.vertexShader !== undefined) + material.vertexShader = json.vertexShader; + if (json.fragmentShader !== undefined) + material.fragmentShader = json.fragmentShader; + if (json.glslVersion !== undefined) + material.glslVersion = json.glslVersion; + if (json.extensions !== undefined) { + for (const key2 in json.extensions) { + material.extensions[key2] = json.extensions[key2]; + } + } + if (json.lights !== undefined) + material.lights = json.lights; + if (json.clipping !== undefined) + material.clipping = json.clipping; + if (json.size !== undefined) + material.size = json.size; + if (json.sizeAttenuation !== undefined) + material.sizeAttenuation = json.sizeAttenuation; + if (json.map !== undefined) + material.map = getTexture(json.map); + if (json.matcap !== undefined) + material.matcap = getTexture(json.matcap); + if (json.alphaMap !== undefined) + material.alphaMap = getTexture(json.alphaMap); + if (json.bumpMap !== undefined) + material.bumpMap = getTexture(json.bumpMap); + if (json.bumpScale !== undefined) + material.bumpScale = json.bumpScale; + if (json.normalMap !== undefined) + material.normalMap = getTexture(json.normalMap); + if (json.normalMapType !== undefined) + material.normalMapType = json.normalMapType; + if (json.normalScale !== undefined) { + let normalScale = json.normalScale; + if (Array.isArray(normalScale) === false) { + normalScale = [normalScale, normalScale]; + } + material.normalScale = new Vector2().fromArray(normalScale); + } + if (json.displacementMap !== undefined) + material.displacementMap = getTexture(json.displacementMap); + if (json.displacementScale !== undefined) + material.displacementScale = json.displacementScale; + if (json.displacementBias !== undefined) + material.displacementBias = json.displacementBias; + if (json.roughnessMap !== undefined) + material.roughnessMap = getTexture(json.roughnessMap); + if (json.metalnessMap !== undefined) + material.metalnessMap = getTexture(json.metalnessMap); + if (json.emissiveMap !== undefined) + material.emissiveMap = getTexture(json.emissiveMap); + if (json.emissiveIntensity !== undefined) + material.emissiveIntensity = json.emissiveIntensity; + if (json.specularMap !== undefined) + material.specularMap = getTexture(json.specularMap); + if (json.specularIntensityMap !== undefined) + material.specularIntensityMap = getTexture(json.specularIntensityMap); + if (json.specularColorMap !== undefined) + material.specularColorMap = getTexture(json.specularColorMap); + if (json.envMap !== undefined) + material.envMap = getTexture(json.envMap); + if (json.envMapRotation !== undefined) + material.envMapRotation.fromArray(json.envMapRotation); + if (json.envMapIntensity !== undefined) + material.envMapIntensity = json.envMapIntensity; + if (json.reflectivity !== undefined) + material.reflectivity = json.reflectivity; + if (json.refractionRatio !== undefined) + material.refractionRatio = json.refractionRatio; + if (json.lightMap !== undefined) + material.lightMap = getTexture(json.lightMap); + if (json.lightMapIntensity !== undefined) + material.lightMapIntensity = json.lightMapIntensity; + if (json.aoMap !== undefined) + material.aoMap = getTexture(json.aoMap); + if (json.aoMapIntensity !== undefined) + material.aoMapIntensity = json.aoMapIntensity; + if (json.gradientMap !== undefined) + material.gradientMap = getTexture(json.gradientMap); + if (json.clearcoatMap !== undefined) + material.clearcoatMap = getTexture(json.clearcoatMap); + if (json.clearcoatRoughnessMap !== undefined) + material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap); + if (json.clearcoatNormalMap !== undefined) + material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap); + if (json.clearcoatNormalScale !== undefined) + material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale); + if (json.iridescenceMap !== undefined) + material.iridescenceMap = getTexture(json.iridescenceMap); + if (json.iridescenceThicknessMap !== undefined) + material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap); + if (json.transmissionMap !== undefined) + material.transmissionMap = getTexture(json.transmissionMap); + if (json.thicknessMap !== undefined) + material.thicknessMap = getTexture(json.thicknessMap); + if (json.anisotropyMap !== undefined) + material.anisotropyMap = getTexture(json.anisotropyMap); + if (json.sheenColorMap !== undefined) + material.sheenColorMap = getTexture(json.sheenColorMap); + if (json.sheenRoughnessMap !== undefined) + material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap); + return material; + } + setTextures(value2) { + this.textures = value2; + return this; + } + createMaterialFromType(type) { + return MaterialLoader.createMaterialFromType(type); + } + static createMaterialFromType(type) { + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material + }; + return new materialLib[type]; + } +} + +class LoaderUtils { + static decodeText(array) { + console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."); + if (typeof TextDecoder !== "undefined") { + return new TextDecoder().decode(array); + } + let s = ""; + for (let i = 0, il = array.length;i < il; i++) { + s += String.fromCharCode(array[i]); + } + try { + return decodeURIComponent(escape(s)); + } catch (e) { + return s; + } + } + static extractUrlBase(url) { + const index2 = url.lastIndexOf("/"); + if (index2 === -1) + return "./"; + return url.slice(0, index2 + 1); + } + static resolveURL(url, path) { + if (typeof url !== "string" || url === "") + return ""; + if (/^https?:\/\//i.test(path) && /^\//.test(url)) { + path = path.replace(/(^https?:\/\/[^\/]+).*/i, "$1"); + } + if (/^(https?:)?\/\//i.test(url)) + return url; + if (/^data:.*,.*$/i.test(url)) + return url; + if (/^blob:.*$/i.test(url)) + return url; + return path + url; + } +} + +class InstancedBufferGeometry extends BufferGeometry { + constructor() { + super(); + this.isInstancedBufferGeometry = true; + this.type = "InstancedBufferGeometry"; + this.instanceCount = Infinity; + } + copy(source) { + super.copy(source); + this.instanceCount = source.instanceCount; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.instanceCount = this.instanceCount; + data2.isInstancedBufferGeometry = true; + return data2; + } +} + +class BufferGeometryLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const interleavedBufferMap = {}; + const arrayBufferMap = {}; + function getInterleavedBuffer(json2, uuid) { + if (interleavedBufferMap[uuid] !== undefined) + return interleavedBufferMap[uuid]; + const interleavedBuffers = json2.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[uuid]; + const buffer = getArrayBuffer(json2, interleavedBuffer.buffer); + const array = getTypedArray(interleavedBuffer.type, buffer); + const ib = new InterleavedBuffer(array, interleavedBuffer.stride); + ib.uuid = interleavedBuffer.uuid; + interleavedBufferMap[uuid] = ib; + return ib; + } + function getArrayBuffer(json2, uuid) { + if (arrayBufferMap[uuid] !== undefined) + return arrayBufferMap[uuid]; + const arrayBuffers = json2.arrayBuffers; + const arrayBuffer = arrayBuffers[uuid]; + const ab = new Uint32Array(arrayBuffer).buffer; + arrayBufferMap[uuid] = ab; + return ab; + } + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry : new BufferGeometry; + const index2 = json.data.index; + if (index2 !== undefined) { + const typedArray = getTypedArray(index2.type, index2.array); + geometry.setIndex(new BufferAttribute(typedArray, 1)); + } + const attributes = json.data.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray(attribute.type, attribute.array); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; + bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== undefined) + bufferAttribute.name = attribute.name; + if (attribute.usage !== undefined) + bufferAttribute.setUsage(attribute.usage); + geometry.setAttribute(key2, bufferAttribute); + } + const morphAttributes = json.data.morphAttributes; + if (morphAttributes) { + for (const key2 in morphAttributes) { + const attributeArray = morphAttributes[key2]; + const array = []; + for (let i = 0, il = attributeArray.length;i < il; i++) { + const attribute = attributeArray[i]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray(attribute.type, attribute.array); + bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== undefined) + bufferAttribute.name = attribute.name; + array.push(bufferAttribute); + } + geometry.morphAttributes[key2] = array; + } + } + const morphTargetsRelative = json.data.morphTargetsRelative; + if (morphTargetsRelative) { + geometry.morphTargetsRelative = true; + } + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + if (groups !== undefined) { + for (let i = 0, n = groups.length;i !== n; ++i) { + const group = groups[i]; + geometry.addGroup(group.start, group.count, group.materialIndex); + } + } + const boundingSphere = json.data.boundingSphere; + if (boundingSphere !== undefined) { + const center = new Vector3; + if (boundingSphere.center !== undefined) { + center.fromArray(boundingSphere.center); + } + geometry.boundingSphere = new Sphere(center, boundingSphere.radius); + } + if (json.name) + geometry.name = json.name; + if (json.userData) + geometry.userData = json.userData; + return geometry; + } +} + +class ObjectLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text2) { + let json = null; + try { + json = JSON.parse(text2); + } catch (error) { + if (onError !== undefined) + onError(error); + console.error("THREE:ObjectLoader: Can't parse " + url + ".", error.message); + return; + } + const metadata = json.metadata; + if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === "geometry") { + if (onError !== undefined) + onError(new Error("THREE.ObjectLoader: Can't load " + url)); + console.error("THREE.ObjectLoader: Can't load " + url); + return; + } + scope.parse(json, onLoad); + }, onProgress, onError); + } + async loadAsync(url, onProgress) { + const scope = this; + const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + const text2 = await loader.loadAsync(url, onProgress); + const json = JSON.parse(text2); + const metadata = json.metadata; + if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === "geometry") { + throw new Error("THREE.ObjectLoader: Can't load " + url); + } + return await scope.parseAsync(json); + } + parse(json, onLoad) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = this.parseImages(json.images, function() { + if (onLoad !== undefined) + onLoad(object); + }); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + if (onLoad !== undefined) { + let hasImages = false; + for (const uuid in images) { + if (images[uuid].data instanceof HTMLImageElement) { + hasImages = true; + break; + } + } + if (hasImages === false) + onLoad(object); + } + return object; + } + async parseAsync(json) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = await this.parseImagesAsync(json.images); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + return object; + } + parseShapes(json) { + const shapes = {}; + if (json !== undefined) { + for (let i = 0, l = json.length;i < l; i++) { + const shape = new Shape().fromJSON(json[i]); + shapes[shape.uuid] = shape; + } + } + return shapes; + } + parseSkeletons(json, object) { + const skeletons = {}; + const bones = {}; + object.traverse(function(child) { + if (child.isBone) + bones[child.uuid] = child; + }); + if (json !== undefined) { + for (let i = 0, l = json.length;i < l; i++) { + const skeleton = new Skeleton().fromJSON(json[i], bones); + skeletons[skeleton.uuid] = skeleton; + } + } + return skeletons; + } + parseGeometries(json, shapes) { + const geometries = {}; + if (json !== undefined) { + const bufferGeometryLoader = new BufferGeometryLoader; + for (let i = 0, l = json.length;i < l; i++) { + let geometry; + const data2 = json[i]; + switch (data2.type) { + case "BufferGeometry": + case "InstancedBufferGeometry": + geometry = bufferGeometryLoader.parse(data2); + break; + default: + if (data2.type in Geometries) { + geometry = Geometries[data2.type].fromJSON(data2, shapes); + } else { + console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data2.type}"`); + } + } + geometry.uuid = data2.uuid; + if (data2.name !== undefined) + geometry.name = data2.name; + if (data2.userData !== undefined) + geometry.userData = data2.userData; + geometries[data2.uuid] = geometry; + } + } + return geometries; + } + parseMaterials(json, textures) { + const cache = {}; + const materials = {}; + if (json !== undefined) { + const loader = new MaterialLoader; + loader.setTextures(textures); + for (let i = 0, l = json.length;i < l; i++) { + const data2 = json[i]; + if (cache[data2.uuid] === undefined) { + cache[data2.uuid] = loader.parse(data2); + } + materials[data2.uuid] = cache[data2.uuid]; + } + } + return materials; + } + parseAnimations(json) { + const animations = {}; + if (json !== undefined) { + for (let i = 0;i < json.length; i++) { + const data2 = json[i]; + const clip = AnimationClip.parse(data2); + animations[clip.uuid] = clip; + } + } + return animations; + } + parseImages(json, onLoad) { + const scope = this; + const images = {}; + let loader; + function loadImage(url) { + scope.manager.itemStart(url); + return loader.load(url, function() { + scope.manager.itemEnd(url); + }, undefined, function() { + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + } + function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return loadImage(path); + } else { + if (image.data) { + return { + data: getTypedArray(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== undefined && json.length > 0) { + const manager = new LoadingManager(onLoad); + loader = new ImageLoader(manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length;i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j = 0, jl = url.length;j < jl; j++) { + const currentUrl = url[j]; + const deserializedImage = deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source(imageArray); + } else { + const deserializedImage = deserializeImage(image.url); + images[image.uuid] = new Source(deserializedImage); + } + } + } + return images; + } + async parseImagesAsync(json) { + const scope = this; + const images = {}; + let loader; + async function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return await loader.loadAsync(path); + } else { + if (image.data) { + return { + data: getTypedArray(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== undefined && json.length > 0) { + loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length;i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j = 0, jl = url.length;j < jl; j++) { + const currentUrl = url[j]; + const deserializedImage = await deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source(imageArray); + } else { + const deserializedImage = await deserializeImage(image.url); + images[image.uuid] = new Source(deserializedImage); + } + } + } + return images; + } + parseTextures(json, images) { + function parseConstant(value2, type) { + if (typeof value2 === "number") + return value2; + console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.", value2); + return type[value2]; + } + const textures = {}; + if (json !== undefined) { + for (let i = 0, l = json.length;i < l; i++) { + const data2 = json[i]; + if (data2.image === undefined) { + console.warn('THREE.ObjectLoader: No "image" specified for', data2.uuid); + } + if (images[data2.image] === undefined) { + console.warn("THREE.ObjectLoader: Undefined image", data2.image); + } + const source = images[data2.image]; + const image = source.data; + let texture; + if (Array.isArray(image)) { + texture = new CubeTexture; + if (image.length === 6) + texture.needsUpdate = true; + } else { + if (image && image.data) { + texture = new DataTexture; + } else { + texture = new Texture; + } + if (image) + texture.needsUpdate = true; + } + texture.source = source; + texture.uuid = data2.uuid; + if (data2.name !== undefined) + texture.name = data2.name; + if (data2.mapping !== undefined) + texture.mapping = parseConstant(data2.mapping, TEXTURE_MAPPING); + if (data2.channel !== undefined) + texture.channel = data2.channel; + if (data2.offset !== undefined) + texture.offset.fromArray(data2.offset); + if (data2.repeat !== undefined) + texture.repeat.fromArray(data2.repeat); + if (data2.center !== undefined) + texture.center.fromArray(data2.center); + if (data2.rotation !== undefined) + texture.rotation = data2.rotation; + if (data2.wrap !== undefined) { + texture.wrapS = parseConstant(data2.wrap[0], TEXTURE_WRAPPING); + texture.wrapT = parseConstant(data2.wrap[1], TEXTURE_WRAPPING); + } + if (data2.format !== undefined) + texture.format = data2.format; + if (data2.internalFormat !== undefined) + texture.internalFormat = data2.internalFormat; + if (data2.type !== undefined) + texture.type = data2.type; + if (data2.colorSpace !== undefined) + texture.colorSpace = data2.colorSpace; + if (data2.minFilter !== undefined) + texture.minFilter = parseConstant(data2.minFilter, TEXTURE_FILTER); + if (data2.magFilter !== undefined) + texture.magFilter = parseConstant(data2.magFilter, TEXTURE_FILTER); + if (data2.anisotropy !== undefined) + texture.anisotropy = data2.anisotropy; + if (data2.flipY !== undefined) + texture.flipY = data2.flipY; + if (data2.generateMipmaps !== undefined) + texture.generateMipmaps = data2.generateMipmaps; + if (data2.premultiplyAlpha !== undefined) + texture.premultiplyAlpha = data2.premultiplyAlpha; + if (data2.unpackAlignment !== undefined) + texture.unpackAlignment = data2.unpackAlignment; + if (data2.compareFunction !== undefined) + texture.compareFunction = data2.compareFunction; + if (data2.userData !== undefined) + texture.userData = data2.userData; + textures[data2.uuid] = texture; + } + } + return textures; + } + parseObject(data2, geometries, materials, textures, animations) { + let object; + function getGeometry(name2) { + if (geometries[name2] === undefined) { + console.warn("THREE.ObjectLoader: Undefined geometry", name2); + } + return geometries[name2]; + } + function getMaterial(name2) { + if (name2 === undefined) + return; + if (Array.isArray(name2)) { + const array = []; + for (let i = 0, l = name2.length;i < l; i++) { + const uuid = name2[i]; + if (materials[uuid] === undefined) { + console.warn("THREE.ObjectLoader: Undefined material", uuid); + } + array.push(materials[uuid]); + } + return array; + } + if (materials[name2] === undefined) { + console.warn("THREE.ObjectLoader: Undefined material", name2); + } + return materials[name2]; + } + function getTexture(uuid) { + if (textures[uuid] === undefined) { + console.warn("THREE.ObjectLoader: Undefined texture", uuid); + } + return textures[uuid]; + } + let geometry, material; + switch (data2.type) { + case "Scene": + object = new Scene; + if (data2.background !== undefined) { + if (Number.isInteger(data2.background)) { + object.background = new Color(data2.background); + } else { + object.background = getTexture(data2.background); + } + } + if (data2.environment !== undefined) { + object.environment = getTexture(data2.environment); + } + if (data2.fog !== undefined) { + if (data2.fog.type === "Fog") { + object.fog = new Fog(data2.fog.color, data2.fog.near, data2.fog.far); + } else if (data2.fog.type === "FogExp2") { + object.fog = new FogExp2(data2.fog.color, data2.fog.density); + } + if (data2.fog.name !== "") { + object.fog.name = data2.fog.name; + } + } + if (data2.backgroundBlurriness !== undefined) + object.backgroundBlurriness = data2.backgroundBlurriness; + if (data2.backgroundIntensity !== undefined) + object.backgroundIntensity = data2.backgroundIntensity; + if (data2.backgroundRotation !== undefined) + object.backgroundRotation.fromArray(data2.backgroundRotation); + if (data2.environmentIntensity !== undefined) + object.environmentIntensity = data2.environmentIntensity; + if (data2.environmentRotation !== undefined) + object.environmentRotation.fromArray(data2.environmentRotation); + break; + case "PerspectiveCamera": + object = new PerspectiveCamera(data2.fov, data2.aspect, data2.near, data2.far); + if (data2.focus !== undefined) + object.focus = data2.focus; + if (data2.zoom !== undefined) + object.zoom = data2.zoom; + if (data2.filmGauge !== undefined) + object.filmGauge = data2.filmGauge; + if (data2.filmOffset !== undefined) + object.filmOffset = data2.filmOffset; + if (data2.view !== undefined) + object.view = Object.assign({}, data2.view); + break; + case "OrthographicCamera": + object = new OrthographicCamera(data2.left, data2.right, data2.top, data2.bottom, data2.near, data2.far); + if (data2.zoom !== undefined) + object.zoom = data2.zoom; + if (data2.view !== undefined) + object.view = Object.assign({}, data2.view); + break; + case "AmbientLight": + object = new AmbientLight(data2.color, data2.intensity); + break; + case "DirectionalLight": + object = new DirectionalLight(data2.color, data2.intensity); + object.target = data2.target || ""; + break; + case "PointLight": + object = new PointLight(data2.color, data2.intensity, data2.distance, data2.decay); + break; + case "RectAreaLight": + object = new RectAreaLight(data2.color, data2.intensity, data2.width, data2.height); + break; + case "SpotLight": + object = new SpotLight(data2.color, data2.intensity, data2.distance, data2.angle, data2.penumbra, data2.decay); + object.target = data2.target || ""; + break; + case "HemisphereLight": + object = new HemisphereLight(data2.color, data2.groundColor, data2.intensity); + break; + case "LightProbe": + object = new LightProbe().fromJSON(data2); + break; + case "SkinnedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new SkinnedMesh(geometry, material); + if (data2.bindMode !== undefined) + object.bindMode = data2.bindMode; + if (data2.bindMatrix !== undefined) + object.bindMatrix.fromArray(data2.bindMatrix); + if (data2.skeleton !== undefined) + object.skeleton = data2.skeleton; + break; + case "Mesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new Mesh(geometry, material); + break; + case "InstancedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + const count = data2.count; + const instanceMatrix = data2.instanceMatrix; + const instanceColor = data2.instanceColor; + object = new InstancedMesh(geometry, material, count); + object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16); + if (instanceColor !== undefined) + object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize); + break; + case "BatchedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new BatchedMesh(data2.maxInstanceCount, data2.maxVertexCount, data2.maxIndexCount, material); + object.geometry = geometry; + object.perObjectFrustumCulled = data2.perObjectFrustumCulled; + object.sortObjects = data2.sortObjects; + object._drawRanges = data2.drawRanges; + object._reservedRanges = data2.reservedRanges; + object._visibility = data2.visibility; + object._active = data2.active; + object._bounds = data2.bounds.map((bound) => { + const box = new Box3; + box.min.fromArray(bound.boxMin); + box.max.fromArray(bound.boxMax); + const sphere = new Sphere; + sphere.radius = bound.sphereRadius; + sphere.center.fromArray(bound.sphereCenter); + return { + boxInitialized: bound.boxInitialized, + box, + sphereInitialized: bound.sphereInitialized, + sphere + }; + }); + object._maxInstanceCount = data2.maxInstanceCount; + object._maxVertexCount = data2.maxVertexCount; + object._maxIndexCount = data2.maxIndexCount; + object._geometryInitialized = data2.geometryInitialized; + object._geometryCount = data2.geometryCount; + object._matricesTexture = getTexture(data2.matricesTexture.uuid); + if (data2.colorsTexture !== undefined) + object._colorsTexture = getTexture(data2.colorsTexture.uuid); + break; + case "LOD": + object = new LOD; + break; + case "Line": + object = new Line(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "LineLoop": + object = new LineLoop(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "LineSegments": + object = new LineSegments(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "PointCloud": + case "Points": + object = new Points(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "Sprite": + object = new Sprite(getMaterial(data2.material)); + break; + case "Group": + object = new Group; + break; + case "Bone": + object = new Bone; + break; + default: + object = new Object3D; + } + object.uuid = data2.uuid; + if (data2.name !== undefined) + object.name = data2.name; + if (data2.matrix !== undefined) { + object.matrix.fromArray(data2.matrix); + if (data2.matrixAutoUpdate !== undefined) + object.matrixAutoUpdate = data2.matrixAutoUpdate; + if (object.matrixAutoUpdate) + object.matrix.decompose(object.position, object.quaternion, object.scale); + } else { + if (data2.position !== undefined) + object.position.fromArray(data2.position); + if (data2.rotation !== undefined) + object.rotation.fromArray(data2.rotation); + if (data2.quaternion !== undefined) + object.quaternion.fromArray(data2.quaternion); + if (data2.scale !== undefined) + object.scale.fromArray(data2.scale); + } + if (data2.up !== undefined) + object.up.fromArray(data2.up); + if (data2.castShadow !== undefined) + object.castShadow = data2.castShadow; + if (data2.receiveShadow !== undefined) + object.receiveShadow = data2.receiveShadow; + if (data2.shadow) { + if (data2.shadow.intensity !== undefined) + object.shadow.intensity = data2.shadow.intensity; + if (data2.shadow.bias !== undefined) + object.shadow.bias = data2.shadow.bias; + if (data2.shadow.normalBias !== undefined) + object.shadow.normalBias = data2.shadow.normalBias; + if (data2.shadow.radius !== undefined) + object.shadow.radius = data2.shadow.radius; + if (data2.shadow.mapSize !== undefined) + object.shadow.mapSize.fromArray(data2.shadow.mapSize); + if (data2.shadow.camera !== undefined) + object.shadow.camera = this.parseObject(data2.shadow.camera); + } + if (data2.visible !== undefined) + object.visible = data2.visible; + if (data2.frustumCulled !== undefined) + object.frustumCulled = data2.frustumCulled; + if (data2.renderOrder !== undefined) + object.renderOrder = data2.renderOrder; + if (data2.userData !== undefined) + object.userData = data2.userData; + if (data2.layers !== undefined) + object.layers.mask = data2.layers; + if (data2.children !== undefined) { + const children = data2.children; + for (let i = 0;i < children.length; i++) { + object.add(this.parseObject(children[i], geometries, materials, textures, animations)); + } + } + if (data2.animations !== undefined) { + const objectAnimations = data2.animations; + for (let i = 0;i < objectAnimations.length; i++) { + const uuid = objectAnimations[i]; + object.animations.push(animations[uuid]); + } + } + if (data2.type === "LOD") { + if (data2.autoUpdate !== undefined) + object.autoUpdate = data2.autoUpdate; + const levels = data2.levels; + for (let l = 0;l < levels.length; l++) { + const level = levels[l]; + const child = object.getObjectByProperty("uuid", level.object); + if (child !== undefined) { + object.addLevel(child, level.distance, level.hysteresis); + } + } + } + return object; + } + bindSkeletons(object, skeletons) { + if (Object.keys(skeletons).length === 0) + return; + object.traverse(function(child) { + if (child.isSkinnedMesh === true && child.skeleton !== undefined) { + const skeleton = skeletons[child.skeleton]; + if (skeleton === undefined) { + console.warn("THREE.ObjectLoader: No skeleton found with UUID:", child.skeleton); + } else { + child.bind(skeleton, child.bindMatrix); + } + } + }); + } + bindLightTargets(object) { + object.traverse(function(child) { + if (child.isDirectionalLight || child.isSpotLight) { + const uuid = child.target; + const target = object.getObjectByProperty("uuid", uuid); + if (target !== undefined) { + child.target = target; + } else { + child.target = new Object3D; + } + } + }); + } +} +var TEXTURE_MAPPING = { + UVMapping, + CubeReflectionMapping, + CubeRefractionMapping, + EquirectangularReflectionMapping, + EquirectangularRefractionMapping, + CubeUVReflectionMapping +}; +var TEXTURE_WRAPPING = { + RepeatWrapping, + ClampToEdgeWrapping, + MirroredRepeatWrapping +}; +var TEXTURE_FILTER = { + NearestFilter, + NearestMipmapNearestFilter, + NearestMipmapLinearFilter, + LinearFilter, + LinearMipmapNearestFilter, + LinearMipmapLinearFilter +}; + +class ImageBitmapLoader extends Loader { + constructor(manager) { + super(manager); + this.isImageBitmapLoader = true; + if (typeof createImageBitmap === "undefined") { + console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."); + } + if (typeof fetch === "undefined") { + console.warn("THREE.ImageBitmapLoader: fetch() not supported."); + } + this.options = { premultiplyAlpha: "none" }; + } + setOptions(options) { + this.options = options; + return this; + } + load(url, onLoad, onProgress, onError) { + if (url === undefined) + url = ""; + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache.get(url); + if (cached !== undefined) { + scope.manager.itemStart(url); + if (cached.then) { + cached.then((imageBitmap) => { + if (onLoad) + onLoad(imageBitmap); + scope.manager.itemEnd(url); + }).catch((e) => { + if (onError) + onError(e); + }); + return; + } + setTimeout(function() { + if (onLoad) + onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const fetchOptions = {}; + fetchOptions.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include"; + fetchOptions.headers = this.requestHeader; + const promise = fetch(url, fetchOptions).then(function(res) { + return res.blob(); + }).then(function(blob) { + return createImageBitmap(blob, Object.assign(scope.options, { colorSpaceConversion: "none" })); + }).then(function(imageBitmap) { + Cache.add(url, imageBitmap); + if (onLoad) + onLoad(imageBitmap); + scope.manager.itemEnd(url); + return imageBitmap; + }).catch(function(e) { + if (onError) + onError(e); + Cache.remove(url); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + Cache.add(url, promise); + scope.manager.itemStart(url); + } +} +var _context; + +class AudioContext { + static getContext() { + if (_context === undefined) { + _context = new (window.AudioContext || window.webkitAudioContext); + } + return _context; + } + static setContext(value2) { + _context = value2; + } +} + +class AudioLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(buffer) { + try { + const bufferCopy = buffer.slice(0); + const context = AudioContext.getContext(); + context.decodeAudioData(bufferCopy, function(audioBuffer) { + onLoad(audioBuffer); + }).catch(handleError); + } catch (e) { + handleError(e); + } + }, onProgress, onError); + function handleError(e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + } +} +var _eyeRight = /* @__PURE__ */ new Matrix4; +var _eyeLeft = /* @__PURE__ */ new Matrix4; +var _projectionMatrix = /* @__PURE__ */ new Matrix4; + +class StereoCamera { + constructor() { + this.type = "StereoCamera"; + this.aspect = 1; + this.eyeSep = 0.064; + this.cameraL = new PerspectiveCamera; + this.cameraL.layers.enable(1); + this.cameraL.matrixAutoUpdate = false; + this.cameraR = new PerspectiveCamera; + this.cameraR.layers.enable(2); + this.cameraR.matrixAutoUpdate = false; + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; + } + update(camera) { + const cache = this._cache; + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + if (needsUpdate) { + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; + _projectionMatrix.copy(camera.projectionMatrix); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom; + let xmin, xmax; + _eyeLeft.elements[12] = -eyeSepHalf; + _eyeRight.elements[12] = eyeSepHalf; + xmin = -ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; + _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraL.projectionMatrix.copy(_projectionMatrix); + xmin = -ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraR.projectionMatrix.copy(_projectionMatrix); + } + this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft); + this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight); + } +} + +class ArrayCamera extends PerspectiveCamera { + constructor(array = []) { + super(); + this.isArrayCamera = true; + this.cameras = array; + this.index = 0; + } +} + +class Clock { + constructor(autoStart = true) { + this.autoStart = autoStart; + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; + this.running = false; + } + start() { + this.startTime = now(); + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + } + stop() { + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + } + getElapsedTime() { + this.getDelta(); + return this.elapsedTime; + } + getDelta() { + let diff = 0; + if (this.autoStart && !this.running) { + this.start(); + return 0; + } + if (this.running) { + const newTime = now(); + diff = (newTime - this.oldTime) / 1000; + this.oldTime = newTime; + this.elapsedTime += diff; + } + return diff; + } +} +function now() { + return performance.now(); +} +var _position$1 = /* @__PURE__ */ new Vector3; +var _quaternion$1 = /* @__PURE__ */ new Quaternion; +var _scale$1 = /* @__PURE__ */ new Vector3; +var _orientation$1 = /* @__PURE__ */ new Vector3; + +class AudioListener extends Object3D { + constructor() { + super(); + this.type = "AudioListener"; + this.context = AudioContext.getContext(); + this.gain = this.context.createGain(); + this.gain.connect(this.context.destination); + this.filter = null; + this.timeDelta = 0; + this._clock = new Clock; + } + getInput() { + return this.gain; + } + removeFilter() { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + this.gain.connect(this.context.destination); + this.filter = null; + } + return this; + } + getFilter() { + return this.filter; + } + setFilter(value2) { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + } else { + this.gain.disconnect(this.context.destination); + } + this.filter = value2; + this.gain.connect(this.filter); + this.filter.connect(this.context.destination); + return this; + } + getMasterVolume() { + return this.gain.gain.value; + } + setMasterVolume(value2) { + this.gain.gain.setTargetAtTime(value2, this.context.currentTime, 0.01); + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + const listener = this.context.listener; + const up = this.up; + this.timeDelta = this._clock.getDelta(); + this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1); + _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1); + if (listener.positionX) { + const endTime = this.context.currentTime + this.timeDelta; + listener.positionX.linearRampToValueAtTime(_position$1.x, endTime); + listener.positionY.linearRampToValueAtTime(_position$1.y, endTime); + listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime); + listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime); + listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime); + listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime); + listener.upX.linearRampToValueAtTime(up.x, endTime); + listener.upY.linearRampToValueAtTime(up.y, endTime); + listener.upZ.linearRampToValueAtTime(up.z, endTime); + } else { + listener.setPosition(_position$1.x, _position$1.y, _position$1.z); + listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z); + } + } +} + +class Audio extends Object3D { + constructor(listener) { + super(); + this.type = "Audio"; + this.listener = listener; + this.context = listener.context; + this.gain = this.context.createGain(); + this.gain.connect(listener.getInput()); + this.autoplay = false; + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = undefined; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = "empty"; + this._startedAt = 0; + this._progress = 0; + this._connected = false; + this.filters = []; + } + getOutput() { + return this.gain; + } + setNodeSource(audioNode) { + this.hasPlaybackControl = false; + this.sourceType = "audioNode"; + this.source = audioNode; + this.connect(); + return this; + } + setMediaElementSource(mediaElement) { + this.hasPlaybackControl = false; + this.sourceType = "mediaNode"; + this.source = this.context.createMediaElementSource(mediaElement); + this.connect(); + return this; + } + setMediaStreamSource(mediaStream) { + this.hasPlaybackControl = false; + this.sourceType = "mediaStreamNode"; + this.source = this.context.createMediaStreamSource(mediaStream); + this.connect(); + return this; + } + setBuffer(audioBuffer) { + this.buffer = audioBuffer; + this.sourceType = "buffer"; + if (this.autoplay) + this.play(); + return this; + } + play(delay = 0) { + if (this.isPlaying === true) { + console.warn("THREE.Audio: Audio is already playing."); + return; + } + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._startedAt = this.context.currentTime + delay; + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind(this); + source.start(this._startedAt, this._progress + this.offset, this.duration); + this.isPlaying = true; + this.source = source; + this.setDetune(this.detune); + this.setPlaybackRate(this.playbackRate); + return this.connect(); + } + pause() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + if (this.isPlaying === true) { + this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate; + if (this.loop === true) { + this._progress = this._progress % (this.duration || this.buffer.duration); + } + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; + } + return this; + } + stop(delay = 0) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._progress = 0; + if (this.source !== null) { + this.source.stop(this.context.currentTime + delay); + this.source.onended = null; + } + this.isPlaying = false; + return this; + } + connect() { + if (this.filters.length > 0) { + this.source.connect(this.filters[0]); + for (let i = 1, l = this.filters.length;i < l; i++) { + this.filters[i - 1].connect(this.filters[i]); + } + this.filters[this.filters.length - 1].connect(this.getOutput()); + } else { + this.source.connect(this.getOutput()); + } + this._connected = true; + return this; + } + disconnect() { + if (this._connected === false) { + return; + } + if (this.filters.length > 0) { + this.source.disconnect(this.filters[0]); + for (let i = 1, l = this.filters.length;i < l; i++) { + this.filters[i - 1].disconnect(this.filters[i]); + } + this.filters[this.filters.length - 1].disconnect(this.getOutput()); + } else { + this.source.disconnect(this.getOutput()); + } + this._connected = false; + return this; + } + getFilters() { + return this.filters; + } + setFilters(value2) { + if (!value2) + value2 = []; + if (this._connected === true) { + this.disconnect(); + this.filters = value2.slice(); + this.connect(); + } else { + this.filters = value2.slice(); + } + return this; + } + setDetune(value2) { + this.detune = value2; + if (this.isPlaying === true && this.source.detune !== undefined) { + this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01); + } + return this; + } + getDetune() { + return this.detune; + } + getFilter() { + return this.getFilters()[0]; + } + setFilter(filter2) { + return this.setFilters(filter2 ? [filter2] : []); + } + setPlaybackRate(value2) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.playbackRate = value2; + if (this.isPlaying === true) { + this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01); + } + return this; + } + getPlaybackRate() { + return this.playbackRate; + } + onEnded() { + this.isPlaying = false; + this._progress = 0; + } + getLoop() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return false; + } + return this.loop; + } + setLoop(value2) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.loop = value2; + if (this.isPlaying === true) { + this.source.loop = this.loop; + } + return this; + } + setLoopStart(value2) { + this.loopStart = value2; + return this; + } + setLoopEnd(value2) { + this.loopEnd = value2; + return this; + } + getVolume() { + return this.gain.gain.value; + } + setVolume(value2) { + this.gain.gain.setTargetAtTime(value2, this.context.currentTime, 0.01); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.sourceType !== "buffer") { + console.warn("THREE.Audio: Audio source type cannot be copied."); + return this; + } + this.autoplay = source.autoplay; + this.buffer = source.buffer; + this.detune = source.detune; + this.loop = source.loop; + this.loopStart = source.loopStart; + this.loopEnd = source.loopEnd; + this.offset = source.offset; + this.duration = source.duration; + this.playbackRate = source.playbackRate; + this.hasPlaybackControl = source.hasPlaybackControl; + this.sourceType = source.sourceType; + this.filters = source.filters.slice(); + return this; + } + clone(recursive) { + return new this.constructor(this.listener).copy(this, recursive); + } +} +var _position = /* @__PURE__ */ new Vector3; +var _quaternion = /* @__PURE__ */ new Quaternion; +var _scale = /* @__PURE__ */ new Vector3; +var _orientation = /* @__PURE__ */ new Vector3; + +class PositionalAudio extends Audio { + constructor(listener) { + super(listener); + this.panner = this.context.createPanner(); + this.panner.panningModel = "HRTF"; + this.panner.connect(this.gain); + } + connect() { + super.connect(); + this.panner.connect(this.gain); + } + disconnect() { + super.disconnect(); + this.panner.disconnect(this.gain); + } + getOutput() { + return this.panner; + } + getRefDistance() { + return this.panner.refDistance; + } + setRefDistance(value2) { + this.panner.refDistance = value2; + return this; + } + getRolloffFactor() { + return this.panner.rolloffFactor; + } + setRolloffFactor(value2) { + this.panner.rolloffFactor = value2; + return this; + } + getDistanceModel() { + return this.panner.distanceModel; + } + setDistanceModel(value2) { + this.panner.distanceModel = value2; + return this; + } + getMaxDistance() { + return this.panner.maxDistance; + } + setMaxDistance(value2) { + this.panner.maxDistance = value2; + return this; + } + setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) { + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.hasPlaybackControl === true && this.isPlaying === false) + return; + this.matrixWorld.decompose(_position, _quaternion, _scale); + _orientation.set(0, 0, 1).applyQuaternion(_quaternion); + const panner = this.panner; + if (panner.positionX) { + const endTime = this.context.currentTime + this.listener.timeDelta; + panner.positionX.linearRampToValueAtTime(_position.x, endTime); + panner.positionY.linearRampToValueAtTime(_position.y, endTime); + panner.positionZ.linearRampToValueAtTime(_position.z, endTime); + panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime); + panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime); + panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime); + } else { + panner.setPosition(_position.x, _position.y, _position.z); + panner.setOrientation(_orientation.x, _orientation.y, _orientation.z); + } + } +} + +class AudioAnalyser { + constructor(audio, fftSize = 2048) { + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; + this.data = new Uint8Array(this.analyser.frequencyBinCount); + audio.getOutput().connect(this.analyser); + } + getFrequencyData() { + this.analyser.getByteFrequencyData(this.data); + return this.data; + } + getAverageFrequency() { + let value2 = 0; + const data2 = this.getFrequencyData(); + for (let i = 0;i < data2.length; i++) { + value2 += data2[i]; + } + return value2 / data2.length; + } +} + +class PropertyMixer { + constructor(binding, typeName, valueSize) { + this.binding = binding; + this.valueSize = valueSize; + let mixFunction, mixFunctionAdditive, setIdentity; + switch (typeName) { + case "quaternion": + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; + this.buffer = new Float64Array(valueSize * 6); + this._workIndex = 5; + break; + case "string": + case "bool": + mixFunction = this._select; + mixFunctionAdditive = this._select; + setIdentity = this._setAdditiveIdentityOther; + this.buffer = new Array(valueSize * 5); + break; + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; + this.buffer = new Float64Array(valueSize * 5); + } + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + this.useCount = 0; + this.referenceCount = 0; + } + accumulate(accuIndex, weight) { + const buffer = this.buffer, stride = this.valueSize, offset = accuIndex * stride + stride; + let currentWeight = this.cumulativeWeight; + if (currentWeight === 0) { + for (let i = 0;i !== stride; ++i) { + buffer[offset + i] = buffer[i]; + } + currentWeight = weight; + } else { + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion(buffer, offset, 0, mix, stride); + } + this.cumulativeWeight = currentWeight; + } + accumulateAdditive(weight) { + const buffer = this.buffer, stride = this.valueSize, offset = stride * this._addIndex; + if (this.cumulativeWeightAdditive === 0) { + this._setIdentity(); + } + this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride); + this.cumulativeWeightAdditive += weight; + } + apply(accuIndex) { + const stride = this.valueSize, buffer = this.buffer, offset = accuIndex * stride + stride, weight = this.cumulativeWeight, weightAdditive = this.cumulativeWeightAdditive, binding = this.binding; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + if (weight < 1) { + const originalValueOffset = stride * this._origIndex; + this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride); + } + if (weightAdditive > 0) { + this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride); + } + for (let i = stride, e = stride + stride;i !== e; ++i) { + if (buffer[i] !== buffer[i + stride]) { + binding.setValue(buffer, offset); + break; + } + } + } + saveOriginalState() { + const binding = this.binding; + const buffer = this.buffer, stride = this.valueSize, originalValueOffset = stride * this._origIndex; + binding.getValue(buffer, originalValueOffset); + for (let i = stride, e = originalValueOffset;i !== e; ++i) { + buffer[i] = buffer[originalValueOffset + i % stride]; + } + this._setIdentity(); + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + } + restoreOriginalState() { + const originalValueOffset = this.valueSize * 3; + this.binding.setValue(this.buffer, originalValueOffset); + } + _setAdditiveIdentityNumeric() { + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; + for (let i = startIndex;i < endIndex; i++) { + this.buffer[i] = 0; + } + } + _setAdditiveIdentityQuaternion() { + this._setAdditiveIdentityNumeric(); + this.buffer[this._addIndex * this.valueSize + 3] = 1; + } + _setAdditiveIdentityOther() { + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; + for (let i = 0;i < this.valueSize; i++) { + this.buffer[targetIndex + i] = this.buffer[startIndex + i]; + } + } + _select(buffer, dstOffset, srcOffset, t, stride) { + if (t >= 0.5) { + for (let i = 0;i !== stride; ++i) { + buffer[dstOffset + i] = buffer[srcOffset + i]; + } + } + } + _slerp(buffer, dstOffset, srcOffset, t) { + Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t); + } + _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) { + const workOffset = this._workIndex * stride; + Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); + Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t); + } + _lerp(buffer, dstOffset, srcOffset, t, stride) { + const s = 1 - t; + for (let i = 0;i !== stride; ++i) { + const j = dstOffset + i; + buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t; + } + } + _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) { + for (let i = 0;i !== stride; ++i) { + const j = dstOffset + i; + buffer[j] = buffer[j] + buffer[srcOffset + i] * t; + } + } +} +var _RESERVED_CHARS_RE = "\\[\\]\\.:\\/"; +var _reservedRe = new RegExp("[" + _RESERVED_CHARS_RE + "]", "g"); +var _wordChar = "[^" + _RESERVED_CHARS_RE + "]"; +var _wordCharOrDot = "[^" + _RESERVED_CHARS_RE.replace("\\.", "") + "]"; +var _directoryRe = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", _wordChar); +var _nodeRe = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", _wordCharOrDot); +var _objectRe = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", _wordChar); +var _propertyRe = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", _wordChar); +var _trackRe = new RegExp("" + "^" + _directoryRe + _nodeRe + _objectRe + _propertyRe + "$"); +var _supportedObjectNames = ["material", "materials", "bones", "map"]; + +class Composite { + constructor(targetGroup, path, optionalParsedPath) { + const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_(path, parsedPath); + } + getValue(array, offset) { + this.bind(); + const firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[firstValidIndex]; + if (binding !== undefined) + binding.getValue(array, offset); + } + setValue(array, offset) { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) { + bindings[i].setValue(array, offset); + } + } + bind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) { + bindings[i].bind(); + } + } + unbind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) { + bindings[i].unbind(); + } + } +} + +class PropertyBinding { + constructor(rootNode, path, parsedPath) { + this.path = path; + this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path); + this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName); + this.rootNode = rootNode; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + static create(root, path, parsedPath) { + if (!(root && root.isAnimationObjectGroup)) { + return new PropertyBinding(root, path, parsedPath); + } else { + return new PropertyBinding.Composite(root, path, parsedPath); + } + } + static sanitizeNodeName(name2) { + return name2.replace(/\s/g, "_").replace(_reservedRe, ""); + } + static parseTrackName(trackName) { + const matches = _trackRe.exec(trackName); + if (matches === null) { + throw new Error("PropertyBinding: Cannot parse trackName: " + trackName); + } + const results = { + nodeName: matches[2], + objectName: matches[3], + objectIndex: matches[4], + propertyName: matches[5], + propertyIndex: matches[6] + }; + const lastDot = results.nodeName && results.nodeName.lastIndexOf("."); + if (lastDot !== undefined && lastDot !== -1) { + const objectName = results.nodeName.substring(lastDot + 1); + if (_supportedObjectNames.indexOf(objectName) !== -1) { + results.nodeName = results.nodeName.substring(0, lastDot); + results.objectName = objectName; + } + } + if (results.propertyName === null || results.propertyName.length === 0) { + throw new Error("PropertyBinding: can not parse propertyName from trackName: " + trackName); + } + return results; + } + static findNode(root, nodeName) { + if (nodeName === undefined || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) { + return root; + } + if (root.skeleton) { + const bone = root.skeleton.getBoneByName(nodeName); + if (bone !== undefined) { + return bone; + } + } + if (root.children) { + const searchNodeSubtree = function(children) { + for (let i = 0;i < children.length; i++) { + const childNode = children[i]; + if (childNode.name === nodeName || childNode.uuid === nodeName) { + return childNode; + } + const result = searchNodeSubtree(childNode.children); + if (result) + return result; + } + return null; + }; + const subTreeNode = searchNodeSubtree(root.children); + if (subTreeNode) { + return subTreeNode; + } + } + return null; + } + _getValue_unavailable() { + } + _setValue_unavailable() { + } + _getValue_direct(buffer, offset) { + buffer[offset] = this.targetObject[this.propertyName]; + } + _getValue_array(buffer, offset) { + const source = this.resolvedProperty; + for (let i = 0, n = source.length;i !== n; ++i) { + buffer[offset++] = source[i]; + } + } + _getValue_arrayElement(buffer, offset) { + buffer[offset] = this.resolvedProperty[this.propertyIndex]; + } + _getValue_toArray(buffer, offset) { + this.resolvedProperty.toArray(buffer, offset); + } + _setValue_direct(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + } + _setValue_direct_setNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_array(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length;i !== n; ++i) { + dest[i] = buffer[offset++]; + } + } + _setValue_array_setNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length;i !== n; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.needsUpdate = true; + } + _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length;i !== n; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_arrayElement(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + } + _setValue_arrayElement_setNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_fromArray(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + } + _setValue_fromArray_setNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.needsUpdate = true; + } + _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.matrixWorldNeedsUpdate = true; + } + _getValue_unbound(targetArray, offset) { + this.bind(); + this.getValue(targetArray, offset); + } + _setValue_unbound(sourceArray, offset) { + this.bind(); + this.setValue(sourceArray, offset); + } + bind() { + let targetObject = this.node; + const parsedPath = this.parsedPath; + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + if (!targetObject) { + targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName); + this.node = targetObject; + } + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; + if (!targetObject) { + console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + "."); + return; + } + if (objectName) { + let objectIndex = parsedPath.objectIndex; + switch (objectName) { + case "materials": + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.materials) { + console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this); + return; + } + targetObject = targetObject.material.materials; + break; + case "bones": + if (!targetObject.skeleton) { + console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this); + return; + } + targetObject = targetObject.skeleton.bones; + for (let i = 0;i < targetObject.length; i++) { + if (targetObject[i].name === objectIndex) { + objectIndex = i; + break; + } + } + break; + case "map": + if ("map" in targetObject) { + targetObject = targetObject.map; + break; + } + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.map) { + console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this); + return; + } + targetObject = targetObject.material.map; + break; + default: + if (targetObject[objectName] === undefined) { + console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this); + return; + } + targetObject = targetObject[objectName]; + } + if (objectIndex !== undefined) { + if (targetObject[objectIndex] === undefined) { + console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, targetObject); + return; + } + targetObject = targetObject[objectIndex]; + } + } + const nodeProperty = targetObject[propertyName]; + if (nodeProperty === undefined) { + const nodeName = parsedPath.nodeName; + console.error("THREE.PropertyBinding: Trying to update property for track: " + nodeName + "." + propertyName + " but it wasn't found.", targetObject); + return; + } + let versioning = this.Versioning.None; + this.targetObject = targetObject; + if (targetObject.isMaterial === true) { + versioning = this.Versioning.NeedsUpdate; + } else if (targetObject.isObject3D === true) { + versioning = this.Versioning.MatrixWorldNeedsUpdate; + } + let bindingType = this.BindingType.Direct; + if (propertyIndex !== undefined) { + if (propertyName === "morphTargetInfluences") { + if (!targetObject.geometry) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this); + return; + } + if (!targetObject.geometry.morphAttributes) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this); + return; + } + if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) { + propertyIndex = targetObject.morphTargetDictionary[propertyIndex]; + } + } + bindingType = this.BindingType.ArrayElement; + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) { + bindingType = this.BindingType.HasFromToArray; + this.resolvedProperty = nodeProperty; + } else if (Array.isArray(nodeProperty)) { + bindingType = this.BindingType.EntireArray; + this.resolvedProperty = nodeProperty; + } else { + this.propertyName = propertyName; + } + this.getValue = this.GetterByBindingType[bindingType]; + this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning]; + } + unbind() { + this.node = null; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } +} +PropertyBinding.Composite = Composite; +PropertyBinding.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 +}; +PropertyBinding.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 +}; +PropertyBinding.prototype.GetterByBindingType = [ + PropertyBinding.prototype._getValue_direct, + PropertyBinding.prototype._getValue_array, + PropertyBinding.prototype._getValue_arrayElement, + PropertyBinding.prototype._getValue_toArray +]; +PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ + [ + PropertyBinding.prototype._setValue_direct, + PropertyBinding.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding.prototype._setValue_array, + PropertyBinding.prototype._setValue_array_setNeedsUpdate, + PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding.prototype._setValue_arrayElement, + PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding.prototype._setValue_fromArray, + PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate + ] +]; + +class AnimationObjectGroup { + constructor() { + this.isAnimationObjectGroup = true; + this.uuid = generateUUID(); + this._objects = Array.prototype.slice.call(arguments); + this.nCachedObjects_ = 0; + const indices = {}; + this._indicesByUUID = indices; + for (let i = 0, n = arguments.length;i !== n; ++i) { + indices[arguments[i].uuid] = i; + } + this._paths = []; + this._parsedPaths = []; + this._bindings = []; + this._bindingsIndicesByPath = {}; + const scope = this; + this.stats = { + objects: { + get total() { + return scope._objects.length; + }, + get inUse() { + return this.total - scope.nCachedObjects_; + } + }, + get bindingsPerObject() { + return scope._bindings.length; + } + }; + } + add() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, nBindings = bindings.length; + let knownObject = undefined, nObjects = objects.length, nCachedObjects = this.nCachedObjects_; + for (let i = 0, n = arguments.length;i !== n; ++i) { + const object = arguments[i], uuid = object.uuid; + let index2 = indicesByUUID[uuid]; + if (index2 === undefined) { + index2 = nObjects++; + indicesByUUID[uuid] = index2; + objects.push(object); + for (let j = 0, m = nBindings;j !== m; ++j) { + bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j])); + } + } else if (index2 < nCachedObjects) { + knownObject = objects[index2]; + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex]; + indicesByUUID[lastCachedObject.uuid] = index2; + objects[index2] = lastCachedObject; + indicesByUUID[uuid] = firstActiveIndex; + objects[firstActiveIndex] = object; + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j], lastCached = bindingsForPath[firstActiveIndex]; + let binding = bindingsForPath[index2]; + bindingsForPath[index2] = lastCached; + if (binding === undefined) { + binding = new PropertyBinding(object, paths[j], parsedPaths[j]); + } + bindingsForPath[firstActiveIndex] = binding; + } + } else if (objects[index2] !== knownObject) { + console.error("THREE.AnimationObjectGroup: Different objects with the same UUID " + "detected. Clean the caches or recreate your infrastructure when reloading scenes."); + } + } + this.nCachedObjects_ = nCachedObjects; + } + remove() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_; + for (let i = 0, n = arguments.length;i !== n; ++i) { + const object = arguments[i], uuid = object.uuid, index2 = indicesByUUID[uuid]; + if (index2 !== undefined && index2 >= nCachedObjects) { + const lastCachedIndex = nCachedObjects++, firstActiveObject = objects[lastCachedIndex]; + indicesByUUID[firstActiveObject.uuid] = index2; + objects[index2] = firstActiveObject; + indicesByUUID[uuid] = lastCachedIndex; + objects[lastCachedIndex] = object; + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j], firstActive = bindingsForPath[lastCachedIndex], binding = bindingsForPath[index2]; + bindingsForPath[index2] = firstActive; + bindingsForPath[lastCachedIndex] = binding; + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + uncache() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_, nObjects = objects.length; + for (let i = 0, n = arguments.length;i !== n; ++i) { + const object = arguments[i], uuid = object.uuid, index2 = indicesByUUID[uuid]; + if (index2 !== undefined) { + delete indicesByUUID[uuid]; + if (index2 < nCachedObjects) { + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex], lastIndex = --nObjects, lastObject = objects[lastIndex]; + indicesByUUID[lastCachedObject.uuid] = index2; + objects[index2] = lastCachedObject; + indicesByUUID[lastObject.uuid] = firstActiveIndex; + objects[firstActiveIndex] = lastObject; + objects.pop(); + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j], lastCached = bindingsForPath[firstActiveIndex], last2 = bindingsForPath[lastIndex]; + bindingsForPath[index2] = lastCached; + bindingsForPath[firstActiveIndex] = last2; + bindingsForPath.pop(); + } + } else { + const lastIndex = --nObjects, lastObject = objects[lastIndex]; + if (lastIndex > 0) { + indicesByUUID[lastObject.uuid] = index2; + } + objects[index2] = lastObject; + objects.pop(); + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j]; + bindingsForPath[index2] = bindingsForPath[lastIndex]; + bindingsForPath.pop(); + } + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + subscribe_(path, parsedPath) { + const indicesByPath = this._bindingsIndicesByPath; + let index2 = indicesByPath[path]; + const bindings = this._bindings; + if (index2 !== undefined) + return bindings[index2]; + const paths = this._paths, parsedPaths = this._parsedPaths, objects = this._objects, nObjects = objects.length, nCachedObjects = this.nCachedObjects_, bindingsForPath = new Array(nObjects); + index2 = bindings.length; + indicesByPath[path] = index2; + paths.push(path); + parsedPaths.push(parsedPath); + bindings.push(bindingsForPath); + for (let i = nCachedObjects, n = objects.length;i !== n; ++i) { + const object = objects[i]; + bindingsForPath[i] = new PropertyBinding(object, path, parsedPath); + } + return bindingsForPath; + } + unsubscribe_(path) { + const indicesByPath = this._bindingsIndicesByPath, index2 = indicesByPath[path]; + if (index2 !== undefined) { + const paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, lastBindingsIndex = bindings.length - 1, lastBindings = bindings[lastBindingsIndex], lastBindingsPath = path[lastBindingsIndex]; + indicesByPath[lastBindingsPath] = index2; + bindings[index2] = lastBindings; + bindings.pop(); + parsedPaths[index2] = parsedPaths[lastBindingsIndex]; + parsedPaths.pop(); + paths[index2] = paths[lastBindingsIndex]; + paths.pop(); + } + } +} + +class AnimationAction { + constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) { + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; + const tracks = clip.tracks, nTracks = tracks.length, interpolants = new Array(nTracks); + const interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + for (let i = 0;i !== nTracks; ++i) { + const interpolant = tracks[i].createInterpolant(null); + interpolants[i] = interpolant; + interpolant.settings = interpolantSettings; + } + this._interpolantSettings = interpolantSettings; + this._interpolants = interpolants; + this._propertyBindings = new Array(nTracks); + this._cacheIndex = null; + this._byClipCacheIndex = null; + this._timeScaleInterpolant = null; + this._weightInterpolant = null; + this.loop = LoopRepeat; + this._loopCount = -1; + this._startTime = null; + this.time = 0; + this.timeScale = 1; + this._effectiveTimeScale = 1; + this.weight = 1; + this._effectiveWeight = 1; + this.repetitions = Infinity; + this.paused = false; + this.enabled = true; + this.clampWhenFinished = false; + this.zeroSlopeAtStart = true; + this.zeroSlopeAtEnd = true; + } + play() { + this._mixer._activateAction(this); + return this; + } + stop() { + this._mixer._deactivateAction(this); + return this.reset(); + } + reset() { + this.paused = false; + this.enabled = true; + this.time = 0; + this._loopCount = -1; + this._startTime = null; + return this.stopFading().stopWarping(); + } + isRunning() { + return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this); + } + isScheduled() { + return this._mixer._isActiveAction(this); + } + startAt(time2) { + this._startTime = time2; + return this; + } + setLoop(mode, repetitions) { + this.loop = mode; + this.repetitions = repetitions; + return this; + } + setEffectiveWeight(weight) { + this.weight = weight; + this._effectiveWeight = this.enabled ? weight : 0; + return this.stopFading(); + } + getEffectiveWeight() { + return this._effectiveWeight; + } + fadeIn(duration) { + return this._scheduleFading(duration, 0, 1); + } + fadeOut(duration) { + return this._scheduleFading(duration, 1, 0); + } + crossFadeFrom(fadeOutAction, duration, warp) { + fadeOutAction.fadeOut(duration); + this.fadeIn(duration); + if (warp) { + const fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, startEndRatio = fadeOutDuration / fadeInDuration, endStartRatio = fadeInDuration / fadeOutDuration; + fadeOutAction.warp(1, startEndRatio, duration); + this.warp(endStartRatio, 1, duration); + } + return this; + } + crossFadeTo(fadeInAction, duration, warp) { + return fadeInAction.crossFadeFrom(this, duration, warp); + } + stopFading() { + const weightInterpolant = this._weightInterpolant; + if (weightInterpolant !== null) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant(weightInterpolant); + } + return this; + } + setEffectiveTimeScale(timeScale) { + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; + return this.stopWarping(); + } + getEffectiveTimeScale() { + return this._effectiveTimeScale; + } + setDuration(duration) { + this.timeScale = this._clip.duration / duration; + return this.stopWarping(); + } + syncWith(action) { + this.time = action.time; + this.timeScale = action.timeScale; + return this.stopWarping(); + } + halt(duration) { + return this.warp(this._effectiveTimeScale, 0, duration); + } + warp(startTimeScale, endTimeScale, duration) { + const mixer = this._mixer, now2 = mixer.time, timeScale = this.timeScale; + let interpolant = this._timeScaleInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; + } + const { parameterPositions: times, sampleValues: values2 } = interpolant; + times[0] = now2; + times[1] = now2 + duration; + values2[0] = startTimeScale / timeScale; + values2[1] = endTimeScale / timeScale; + return this; + } + stopWarping() { + const timeScaleInterpolant = this._timeScaleInterpolant; + if (timeScaleInterpolant !== null) { + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant(timeScaleInterpolant); + } + return this; + } + getMixer() { + return this._mixer; + } + getClip() { + return this._clip; + } + getRoot() { + return this._localRoot || this._mixer._root; + } + _update(time2, deltaTime, timeDirection, accuIndex) { + if (!this.enabled) { + this._updateWeight(time2); + return; + } + const startTime = this._startTime; + if (startTime !== null) { + const timeRunning = (time2 - startTime) * timeDirection; + if (timeRunning < 0 || timeDirection === 0) { + deltaTime = 0; + } else { + this._startTime = null; + deltaTime = timeDirection * timeRunning; + } + } + deltaTime *= this._updateTimeScale(time2); + const clipTime = this._updateTime(deltaTime); + const weight = this._updateWeight(time2); + if (weight > 0) { + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; + switch (this.blendMode) { + case AdditiveAnimationBlendMode: + for (let j = 0, m = interpolants.length;j !== m; ++j) { + interpolants[j].evaluate(clipTime); + propertyMixers[j].accumulateAdditive(weight); + } + break; + case NormalAnimationBlendMode: + default: + for (let j = 0, m = interpolants.length;j !== m; ++j) { + interpolants[j].evaluate(clipTime); + propertyMixers[j].accumulate(accuIndex, weight); + } + } + } + } + _updateWeight(time2) { + let weight = 0; + if (this.enabled) { + weight = this.weight; + const interpolant = this._weightInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time2)[0]; + weight *= interpolantValue; + if (time2 > interpolant.parameterPositions[1]) { + this.stopFading(); + if (interpolantValue === 0) { + this.enabled = false; + } + } + } + } + this._effectiveWeight = weight; + return weight; + } + _updateTimeScale(time2) { + let timeScale = 0; + if (!this.paused) { + timeScale = this.timeScale; + const interpolant = this._timeScaleInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time2)[0]; + timeScale *= interpolantValue; + if (time2 > interpolant.parameterPositions[1]) { + this.stopWarping(); + if (timeScale === 0) { + this.paused = true; + } else { + this.timeScale = timeScale; + } + } + } + } + this._effectiveTimeScale = timeScale; + return timeScale; + } + _updateTime(deltaTime) { + const duration = this._clip.duration; + const loop = this.loop; + let time2 = this.time + deltaTime; + let loopCount = this._loopCount; + const pingPong = loop === LoopPingPong; + if (deltaTime === 0) { + if (loopCount === -1) + return time2; + return pingPong && (loopCount & 1) === 1 ? duration - time2 : time2; + } + if (loop === LoopOnce) { + if (loopCount === -1) { + this._loopCount = 0; + this._setEndings(true, true, false); + } + handle_stop: { + if (time2 >= duration) { + time2 = duration; + } else if (time2 < 0) { + time2 = 0; + } else { + this.time = time2; + break handle_stop; + } + if (this.clampWhenFinished) + this.paused = true; + else + this.enabled = false; + this.time = time2; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime < 0 ? -1 : 1 + }); + } + } else { + if (loopCount === -1) { + if (deltaTime >= 0) { + loopCount = 0; + this._setEndings(true, this.repetitions === 0, pingPong); + } else { + this._setEndings(this.repetitions === 0, true, pingPong); + } + } + if (time2 >= duration || time2 < 0) { + const loopDelta = Math.floor(time2 / duration); + time2 -= duration * loopDelta; + loopCount += Math.abs(loopDelta); + const pending = this.repetitions - loopCount; + if (pending <= 0) { + if (this.clampWhenFinished) + this.paused = true; + else + this.enabled = false; + time2 = deltaTime > 0 ? duration : 0; + this.time = time2; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime > 0 ? 1 : -1 + }); + } else { + if (pending === 1) { + const atStart = deltaTime < 0; + this._setEndings(atStart, !atStart, pingPong); + } else { + this._setEndings(false, false, pingPong); + } + this._loopCount = loopCount; + this.time = time2; + this._mixer.dispatchEvent({ + type: "loop", + action: this, + loopDelta + }); + } + } else { + this.time = time2; + } + if (pingPong && (loopCount & 1) === 1) { + return duration - time2; + } + } + return time2; + } + _setEndings(atStart, atEnd, pingPong) { + const settings = this._interpolantSettings; + if (pingPong) { + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; + } else { + if (atStart) { + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; + } else { + settings.endingStart = WrapAroundEnding; + } + if (atEnd) { + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; + } else { + settings.endingEnd = WrapAroundEnding; + } + } + } + _scheduleFading(duration, weightNow, weightThen) { + const mixer = this._mixer, now2 = mixer.time; + let interpolant = this._weightInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; + } + const { parameterPositions: times, sampleValues: values2 } = interpolant; + times[0] = now2; + values2[0] = weightNow; + times[1] = now2 + duration; + values2[1] = weightThen; + return this; + } +} +var _controlInterpolantsResultBuffer = new Float32Array(1); + +class AnimationMixer extends EventDispatcher { + constructor(root) { + super(); + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1; + } + _bindAction(action, prototypeAction) { + const root = action._localRoot || this._root, tracks = action._clip.tracks, nTracks = tracks.length, bindings = action._propertyBindings, interpolants = action._interpolants, rootUuid = root.uuid, bindingsByRoot = this._bindingsByRootAndName; + let bindingsByName = bindingsByRoot[rootUuid]; + if (bindingsByName === undefined) { + bindingsByName = {}; + bindingsByRoot[rootUuid] = bindingsByName; + } + for (let i = 0;i !== nTracks; ++i) { + const track = tracks[i], trackName = track.name; + let binding = bindingsByName[trackName]; + if (binding !== undefined) { + ++binding.referenceCount; + bindings[i] = binding; + } else { + binding = bindings[i]; + if (binding !== undefined) { + if (binding._cacheIndex === null) { + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + } + continue; + } + const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath; + binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize()); + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + bindings[i] = binding; + } + interpolants[i].resultBuffer = binding.buffer; + } + } + _activateAction(action) { + if (!this._isActiveAction(action)) { + if (action._cacheIndex === null) { + const rootUuid = (action._localRoot || this._root).uuid, clipUuid = action._clip.uuid, actionsForClip = this._actionsByClip[clipUuid]; + this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]); + this._addInactiveAction(action, clipUuid, rootUuid); + } + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length;i !== n; ++i) { + const binding = bindings[i]; + if (binding.useCount++ === 0) { + this._lendBinding(binding); + binding.saveOriginalState(); + } + } + this._lendAction(action); + } + } + _deactivateAction(action) { + if (this._isActiveAction(action)) { + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length;i !== n; ++i) { + const binding = bindings[i]; + if (--binding.useCount === 0) { + binding.restoreOriginalState(); + this._takeBackBinding(binding); + } + } + this._takeBackAction(action); + } + } + _initMemoryManager() { + this._actions = []; + this._nActiveActions = 0; + this._actionsByClip = {}; + this._bindings = []; + this._nActiveBindings = 0; + this._bindingsByRootAndName = {}; + this._controlInterpolants = []; + this._nActiveControlInterpolants = 0; + const scope = this; + this.stats = { + actions: { + get total() { + return scope._actions.length; + }, + get inUse() { + return scope._nActiveActions; + } + }, + bindings: { + get total() { + return scope._bindings.length; + }, + get inUse() { + return scope._nActiveBindings; + } + }, + controlInterpolants: { + get total() { + return scope._controlInterpolants.length; + }, + get inUse() { + return scope._nActiveControlInterpolants; + } + } + }; + } + _isActiveAction(action) { + const index2 = action._cacheIndex; + return index2 !== null && index2 < this._nActiveActions; + } + _addInactiveAction(action, clipUuid, rootUuid) { + const actions = this._actions, actionsByClip = this._actionsByClip; + let actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip === undefined) { + actionsForClip = { + knownActions: [action], + actionByRoot: {} + }; + action._byClipCacheIndex = 0; + actionsByClip[clipUuid] = actionsForClip; + } else { + const knownActions = actionsForClip.knownActions; + action._byClipCacheIndex = knownActions.length; + knownActions.push(action); + } + action._cacheIndex = actions.length; + actions.push(action); + actionsForClip.actionByRoot[rootUuid] = action; + } + _removeInactiveAction(action) { + const actions = this._actions, lastInactiveAction = actions[actions.length - 1], cacheIndex = action._cacheIndex; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + action._cacheIndex = null; + const clipUuid = action._clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid], knownActionsForClip = actionsForClip.knownActions, lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1], byClipCacheIndex = action._byClipCacheIndex; + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[byClipCacheIndex] = lastKnownAction; + knownActionsForClip.pop(); + action._byClipCacheIndex = null; + const actionByRoot = actionsForClip.actionByRoot, rootUuid = (action._localRoot || this._root).uuid; + delete actionByRoot[rootUuid]; + if (knownActionsForClip.length === 0) { + delete actionsByClip[clipUuid]; + } + this._removeInactiveBindingsForAction(action); + } + _removeInactiveBindingsForAction(action) { + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length;i !== n; ++i) { + const binding = bindings[i]; + if (--binding.referenceCount === 0) { + this._removeInactiveBinding(binding); + } + } + } + _lendAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, lastActiveIndex = this._nActiveActions++, firstInactiveAction = actions[lastActiveIndex]; + action._cacheIndex = lastActiveIndex; + actions[lastActiveIndex] = action; + firstInactiveAction._cacheIndex = prevIndex; + actions[prevIndex] = firstInactiveAction; + } + _takeBackAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, firstInactiveIndex = --this._nActiveActions, lastActiveAction = actions[firstInactiveIndex]; + action._cacheIndex = firstInactiveIndex; + actions[firstInactiveIndex] = action; + lastActiveAction._cacheIndex = prevIndex; + actions[prevIndex] = lastActiveAction; + } + _addInactiveBinding(binding, rootUuid, trackName) { + const bindingsByRoot = this._bindingsByRootAndName, bindings = this._bindings; + let bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName === undefined) { + bindingByName = {}; + bindingsByRoot[rootUuid] = bindingByName; + } + bindingByName[trackName] = binding; + binding._cacheIndex = bindings.length; + bindings.push(binding); + } + _removeInactiveBinding(binding) { + const bindings = this._bindings, propBinding = binding.binding, rootUuid = propBinding.rootNode.uuid, trackName = propBinding.path, bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid], lastInactiveBinding = bindings[bindings.length - 1], cacheIndex = binding._cacheIndex; + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[cacheIndex] = lastInactiveBinding; + bindings.pop(); + delete bindingByName[trackName]; + if (Object.keys(bindingByName).length === 0) { + delete bindingsByRoot[rootUuid]; + } + } + _lendBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, lastActiveIndex = this._nActiveBindings++, firstInactiveBinding = bindings[lastActiveIndex]; + binding._cacheIndex = lastActiveIndex; + bindings[lastActiveIndex] = binding; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = firstInactiveBinding; + } + _takeBackBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, firstInactiveIndex = --this._nActiveBindings, lastActiveBinding = bindings[firstInactiveIndex]; + binding._cacheIndex = firstInactiveIndex; + bindings[firstInactiveIndex] = binding; + lastActiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = lastActiveBinding; + } + _lendControlInterpolant() { + const interpolants = this._controlInterpolants, lastActiveIndex = this._nActiveControlInterpolants++; + let interpolant = interpolants[lastActiveIndex]; + if (interpolant === undefined) { + interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer); + interpolant.__cacheIndex = lastActiveIndex; + interpolants[lastActiveIndex] = interpolant; + } + return interpolant; + } + _takeBackControlInterpolant(interpolant) { + const interpolants = this._controlInterpolants, prevIndex = interpolant.__cacheIndex, firstInactiveIndex = --this._nActiveControlInterpolants, lastActiveInterpolant = interpolants[firstInactiveIndex]; + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[firstInactiveIndex] = interpolant; + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[prevIndex] = lastActiveInterpolant; + } + clipAction(clip, optionalRoot, blendMode) { + const root = optionalRoot || this._root, rootUuid = root.uuid; + let clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip; + const clipUuid = clipObject !== null ? clipObject.uuid : clip; + const actionsForClip = this._actionsByClip[clipUuid]; + let prototypeAction = null; + if (blendMode === undefined) { + if (clipObject !== null) { + blendMode = clipObject.blendMode; + } else { + blendMode = NormalAnimationBlendMode; + } + } + if (actionsForClip !== undefined) { + const existingAction = actionsForClip.actionByRoot[rootUuid]; + if (existingAction !== undefined && existingAction.blendMode === blendMode) { + return existingAction; + } + prototypeAction = actionsForClip.knownActions[0]; + if (clipObject === null) + clipObject = prototypeAction._clip; + } + if (clipObject === null) + return null; + const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode); + this._bindAction(newAction, prototypeAction); + this._addInactiveAction(newAction, clipUuid, rootUuid); + return newAction; + } + existingAction(clip, optionalRoot) { + const root = optionalRoot || this._root, rootUuid = root.uuid, clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip, clipUuid = clipObject ? clipObject.uuid : clip, actionsForClip = this._actionsByClip[clipUuid]; + if (actionsForClip !== undefined) { + return actionsForClip.actionByRoot[rootUuid] || null; + } + return null; + } + stopAllAction() { + const actions = this._actions, nActions = this._nActiveActions; + for (let i = nActions - 1;i >= 0; --i) { + actions[i].stop(); + } + return this; + } + update(deltaTime) { + deltaTime *= this.timeScale; + const actions = this._actions, nActions = this._nActiveActions, time2 = this.time += deltaTime, timeDirection = Math.sign(deltaTime), accuIndex = this._accuIndex ^= 1; + for (let i = 0;i !== nActions; ++i) { + const action = actions[i]; + action._update(time2, deltaTime, timeDirection, accuIndex); + } + const bindings = this._bindings, nBindings = this._nActiveBindings; + for (let i = 0;i !== nBindings; ++i) { + bindings[i].apply(accuIndex); + } + return this; + } + setTime(timeInSeconds) { + this.time = 0; + for (let i = 0;i < this._actions.length; i++) { + this._actions[i].time = 0; + } + return this.update(timeInSeconds); + } + getRoot() { + return this._root; + } + uncacheClip(clip) { + const actions = this._actions, clipUuid = clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip !== undefined) { + const actionsToRemove = actionsForClip.knownActions; + for (let i = 0, n = actionsToRemove.length;i !== n; ++i) { + const action = actionsToRemove[i]; + this._deactivateAction(action); + const cacheIndex = action._cacheIndex, lastInactiveAction = actions[actions.length - 1]; + action._cacheIndex = null; + action._byClipCacheIndex = null; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + this._removeInactiveBindingsForAction(action); + } + delete actionsByClip[clipUuid]; + } + } + uncacheRoot(root) { + const rootUuid = root.uuid, actionsByClip = this._actionsByClip; + for (const clipUuid in actionsByClip) { + const actionByRoot = actionsByClip[clipUuid].actionByRoot, action = actionByRoot[rootUuid]; + if (action !== undefined) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + const bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName !== undefined) { + for (const trackName in bindingByName) { + const binding = bindingByName[trackName]; + binding.restoreOriginalState(); + this._removeInactiveBinding(binding); + } + } + } + uncacheAction(clip, optionalRoot) { + const action = this.existingAction(clip, optionalRoot); + if (action !== null) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } +} + +class RenderTarget3D extends RenderTarget { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isRenderTarget3D = true; + this.depth = depth; + this.texture = new Data3DTexture(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } +} + +class RenderTargetArray extends RenderTarget { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isRenderTargetArray = true; + this.depth = depth; + this.texture = new DataArrayTexture(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } +} + +class Uniform { + constructor(value2) { + this.value = value2; + } + clone() { + return new Uniform(this.value.clone === undefined ? this.value : this.value.clone()); + } +} +var _id = 0; + +class UniformsGroup extends EventDispatcher { + constructor() { + super(); + this.isUniformsGroup = true; + Object.defineProperty(this, "id", { value: _id++ }); + this.name = ""; + this.usage = StaticDrawUsage; + this.uniforms = []; + } + add(uniform) { + this.uniforms.push(uniform); + return this; + } + remove(uniform) { + const index2 = this.uniforms.indexOf(uniform); + if (index2 !== -1) + this.uniforms.splice(index2, 1); + return this; + } + setName(name2) { + this.name = name2; + return this; + } + setUsage(value2) { + this.usage = value2; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + return this; + } + copy(source) { + this.name = source.name; + this.usage = source.usage; + const uniformsSource = source.uniforms; + this.uniforms.length = 0; + for (let i = 0, l = uniformsSource.length;i < l; i++) { + const uniforms = Array.isArray(uniformsSource[i]) ? uniformsSource[i] : [uniformsSource[i]]; + for (let j = 0;j < uniforms.length; j++) { + this.uniforms.push(uniforms[j].clone()); + } + } + return this; + } + clone() { + return new this.constructor().copy(this); + } +} + +class InstancedInterleavedBuffer extends InterleavedBuffer { + constructor(array, stride, meshPerAttribute = 1) { + super(array, stride); + this.isInstancedInterleavedBuffer = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + clone(data2) { + const ib = super.clone(data2); + ib.meshPerAttribute = this.meshPerAttribute; + return ib; + } + toJSON(data2) { + const json = super.toJSON(data2); + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; + return json; + } +} + +class GLBufferAttribute { + constructor(buffer, type, itemSize, elementSize, count) { + this.isGLBufferAttribute = true; + this.name = ""; + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; + this.version = 0; + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setBuffer(buffer) { + this.buffer = buffer; + return this; + } + setType(type, elementSize) { + this.type = type; + this.elementSize = elementSize; + return this; + } + setItemSize(itemSize) { + this.itemSize = itemSize; + return this; + } + setCount(count) { + this.count = count; + return this; + } +} +var _matrix = /* @__PURE__ */ new Matrix4; + +class Raycaster { + constructor(origin, direction, near = 0, far = Infinity) { + this.ray = new Ray(origin, direction); + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers; + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + } + set(origin, direction) { + this.ray.set(origin, direction); + } + setFromCamera(coords, camera) { + if (camera.isPerspectiveCamera) { + this.ray.origin.setFromMatrixPosition(camera.matrixWorld); + this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize(); + this.camera = camera; + } else if (camera.isOrthographicCamera) { + this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); + this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld); + this.camera = camera; + } else { + console.error("THREE.Raycaster: Unsupported camera type: " + camera.type); + } + } + setFromXRController(controller) { + _matrix.identity().extractRotation(controller.matrixWorld); + this.ray.origin.setFromMatrixPosition(controller.matrixWorld); + this.ray.direction.set(0, 0, -1).applyMatrix4(_matrix); + return this; + } + intersectObject(object, recursive = true, intersects2 = []) { + intersect(object, this, intersects2, recursive); + intersects2.sort(ascSort); + return intersects2; + } + intersectObjects(objects, recursive = true, intersects2 = []) { + for (let i = 0, l = objects.length;i < l; i++) { + intersect(objects[i], this, intersects2, recursive); + } + intersects2.sort(ascSort); + return intersects2; + } +} +function ascSort(a, b) { + return a.distance - b.distance; +} +function intersect(object, raycaster, intersects2, recursive) { + let propagate = true; + if (object.layers.test(raycaster.layers)) { + const result = object.raycast(raycaster, intersects2); + if (result === false) + propagate = false; + } + if (propagate === true && recursive === true) { + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + intersect(children[i], raycaster, intersects2, true); + } + } +} + +class Spherical { + constructor(radius = 1, phi = 0, theta = 0) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + set(radius, phi, theta) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + copy(other) { + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + return this; + } + makeSafe() { + const EPS = 0.000001; + this.phi = clamp2(this.phi, EPS, Math.PI - EPS); + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x, y, z) { + this.radius = Math.sqrt(x * x + y * y + z * z); + if (this.radius === 0) { + this.theta = 0; + this.phi = 0; + } else { + this.theta = Math.atan2(x, z); + this.phi = Math.acos(clamp2(y / this.radius, -1, 1)); + } + return this; + } + clone() { + return new this.constructor().copy(this); + } +} + +class Cylindrical { + constructor(radius = 1, theta = 0, y = 0) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + set(radius, theta, y) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + copy(other) { + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x, y, z) { + this.radius = Math.sqrt(x * x + z * z); + this.theta = Math.atan2(x, z); + this.y = y; + return this; + } + clone() { + return new this.constructor().copy(this); + } +} + +class Matrix2 { + constructor(n11, n12, n21, n22) { + Matrix2.prototype.isMatrix2 = true; + this.elements = [ + 1, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n21, n22); + } + } + identity() { + this.set(1, 0, 0, 1); + return this; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 4; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + set(n11, n12, n21, n22) { + const te = this.elements; + te[0] = n11; + te[2] = n12; + te[1] = n21; + te[3] = n22; + return this; + } +} +var _vector$4 = /* @__PURE__ */ new Vector2; + +class Box2 { + constructor(min = new Vector2(Infinity, Infinity), max = new Vector2(-Infinity, -Infinity)) { + this.isBox2 = true; + this.min = min; + this.max = max; + } + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length;i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size) { + const halfSize = _vector$4.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = Infinity; + this.max.x = this.max.y = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y; + } + getParameter(point, target) { + return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y)); + } + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y; + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$4).distanceTo(point); + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) + this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } +} +var _startP = /* @__PURE__ */ new Vector3; +var _startEnd = /* @__PURE__ */ new Vector3; + +class Line3 { + constructor(start = new Vector3, end = new Vector3) { + this.start = start; + this.end = end; + } + set(start, end) { + this.start.copy(start); + this.end.copy(end); + return this; + } + copy(line) { + this.start.copy(line.start); + this.end.copy(line.end); + return this; + } + getCenter(target) { + return target.addVectors(this.start, this.end).multiplyScalar(0.5); + } + delta(target) { + return target.subVectors(this.end, this.start); + } + distanceSq() { + return this.start.distanceToSquared(this.end); + } + distance() { + return this.start.distanceTo(this.end); + } + at(t, target) { + return this.delta(target).multiplyScalar(t).add(this.start); + } + closestPointToPointParameter(point, clampToLine) { + _startP.subVectors(point, this.start); + _startEnd.subVectors(this.end, this.start); + const startEnd2 = _startEnd.dot(_startEnd); + const startEnd_startP = _startEnd.dot(_startP); + let t = startEnd_startP / startEnd2; + if (clampToLine) { + t = clamp2(t, 0, 1); + } + return t; + } + closestPointToPoint(point, clampToLine, target) { + const t = this.closestPointToPointParameter(point, clampToLine); + return this.delta(target).multiplyScalar(t).add(this.start); + } + applyMatrix4(matrix) { + this.start.applyMatrix4(matrix); + this.end.applyMatrix4(matrix); + return this; + } + equals(line) { + return line.start.equals(this.start) && line.end.equals(this.end); + } + clone() { + return new this.constructor().copy(this); + } +} +var _vector$3 = /* @__PURE__ */ new Vector3; + +class SpotLightHelper extends Object3D { + constructor(light, color) { + super(); + this.light = light; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "SpotLightHelper"; + const geometry = new BufferGeometry; + const positions = [ + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + -1, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + -1, + 1 + ]; + for (let i = 0, j = 1, l = 32;i < l; i++, j++) { + const p1 = i / l * Math.PI * 2; + const p2 = j / l * Math.PI * 2; + positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1); + } + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + const material = new LineBasicMaterial({ fog: false, toneMapped: false }); + this.cone = new LineSegments(geometry, material); + this.add(this.cone); + this.update(); + } + dispose() { + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + if (this.parent) { + this.parent.updateWorldMatrix(true); + this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld); + } else { + this.matrix.copy(this.light.matrixWorld); + } + this.matrixWorld.copy(this.light.matrixWorld); + const coneLength = this.light.distance ? this.light.distance : 1000; + const coneWidth = coneLength * Math.tan(this.light.angle); + this.cone.scale.set(coneWidth, coneWidth, coneLength); + _vector$3.setFromMatrixPosition(this.light.target.matrixWorld); + this.cone.lookAt(_vector$3); + if (this.color !== undefined) { + this.cone.material.color.set(this.color); + } else { + this.cone.material.color.copy(this.light.color); + } + } +} +var _vector$2 = /* @__PURE__ */ new Vector3; +var _boneMatrix = /* @__PURE__ */ new Matrix4; +var _matrixWorldInv = /* @__PURE__ */ new Matrix4; + +class SkeletonHelper extends LineSegments { + constructor(object) { + const bones = getBoneList(object); + const geometry = new BufferGeometry; + const vertices = []; + const colors = []; + const color1 = new Color(0, 0, 1); + const color2 = new Color(0, 1, 0); + for (let i = 0;i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + vertices.push(0, 0, 0); + vertices.push(0, 0, 0); + colors.push(color1.r, color1.g, color1.b); + colors.push(color2.r, color2.g, color2.b); + } + } + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true }); + super(geometry, material); + this.isSkeletonHelper = true; + this.type = "SkeletonHelper"; + this.root = object; + this.bones = bones; + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + } + updateMatrixWorld(force) { + const bones = this.bones; + const geometry = this.geometry; + const position2 = geometry.getAttribute("position"); + _matrixWorldInv.copy(this.root.matrixWorld).invert(); + for (let i = 0, j = 0;i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld); + _vector$2.setFromMatrixPosition(_boneMatrix); + position2.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z); + _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld); + _vector$2.setFromMatrixPosition(_boneMatrix); + position2.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z); + j += 2; + } + } + geometry.getAttribute("position").needsUpdate = true; + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} +function getBoneList(object) { + const boneList = []; + if (object.isBone === true) { + boneList.push(object); + } + for (let i = 0;i < object.children.length; i++) { + boneList.push.apply(boneList, getBoneList(object.children[i])); + } + return boneList; +} + +class PointLightHelper extends Mesh { + constructor(light, sphereSize, color) { + const geometry = new SphereGeometry(sphereSize, 4, 2); + const material = new MeshBasicMaterial({ wireframe: true, fog: false, toneMapped: false }); + super(geometry, material); + this.light = light; + this.color = color; + this.type = "PointLightHelper"; + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; + this.update(); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + if (this.color !== undefined) { + this.material.color.set(this.color); + } else { + this.material.color.copy(this.light.color); + } + } +} +var _vector$1 = /* @__PURE__ */ new Vector3; +var _color1 = /* @__PURE__ */ new Color; +var _color2 = /* @__PURE__ */ new Color; + +class HemisphereLightHelper extends Object3D { + constructor(light, size, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "HemisphereLightHelper"; + const geometry = new OctahedronGeometry(size); + geometry.rotateY(Math.PI * 0.5); + this.material = new MeshBasicMaterial({ wireframe: true, fog: false, toneMapped: false }); + if (this.color === undefined) + this.material.vertexColors = true; + const position2 = geometry.getAttribute("position"); + const colors = new Float32Array(position2.count * 3); + geometry.setAttribute("color", new BufferAttribute(colors, 3)); + this.add(new Mesh(geometry, this.material)); + this.update(); + } + dispose() { + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + update() { + const mesh = this.children[0]; + if (this.color !== undefined) { + this.material.color.set(this.color); + } else { + const colors = mesh.geometry.getAttribute("color"); + _color1.copy(this.light.color); + _color2.copy(this.light.groundColor); + for (let i = 0, l = colors.count;i < l; i++) { + const color = i < l / 2 ? _color1 : _color2; + colors.setXYZ(i, color.r, color.g, color.b); + } + colors.needsUpdate = true; + } + this.light.updateWorldMatrix(true, false); + mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate()); + } +} + +class GridHelper extends LineSegments { + constructor(size = 10, divisions = 10, color1 = 4473924, color2 = 8947848) { + color1 = new Color(color1); + color2 = new Color(color2); + const center = divisions / 2; + const step = size / divisions; + const halfSize = size / 2; + const vertices = [], colors = []; + for (let i = 0, j = 0, k = -halfSize;i <= divisions; i++, k += step) { + vertices.push(-halfSize, 0, k, halfSize, 0, k); + vertices.push(k, 0, -halfSize, k, 0, halfSize); + const color = i === center ? color1 : color2; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + } + const geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "GridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} + +class PolarGridHelper extends LineSegments { + constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 4473924, color2 = 8947848) { + color1 = new Color(color1); + color2 = new Color(color2); + const vertices = []; + const colors = []; + if (sectors > 1) { + for (let i = 0;i < sectors; i++) { + const v = i / sectors * (Math.PI * 2); + const x = Math.sin(v) * radius; + const z = Math.cos(v) * radius; + vertices.push(0, 0, 0); + vertices.push(x, 0, z); + const color = i & 1 ? color1 : color2; + colors.push(color.r, color.g, color.b); + colors.push(color.r, color.g, color.b); + } + } + for (let i = 0;i < rings; i++) { + const color = i & 1 ? color1 : color2; + const r = radius - radius / rings * i; + for (let j = 0;j < divisions; j++) { + let v = j / divisions * (Math.PI * 2); + let x = Math.sin(v) * r; + let z = Math.cos(v) * r; + vertices.push(x, 0, z); + colors.push(color.r, color.g, color.b); + v = (j + 1) / divisions * (Math.PI * 2); + x = Math.sin(v) * r; + z = Math.cos(v) * r; + vertices.push(x, 0, z); + colors.push(color.r, color.g, color.b); + } + } + const geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "PolarGridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} +var _v1 = /* @__PURE__ */ new Vector3; +var _v2 = /* @__PURE__ */ new Vector3; +var _v3 = /* @__PURE__ */ new Vector3; + +class DirectionalLightHelper extends Object3D { + constructor(light, size, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "DirectionalLightHelper"; + if (size === undefined) + size = 1; + let geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute([ + -size, + size, + 0, + size, + size, + 0, + size, + -size, + 0, + -size, + -size, + 0, + -size, + size, + 0 + ], 3)); + const material = new LineBasicMaterial({ fog: false, toneMapped: false }); + this.lightPlane = new Line(geometry, material); + this.add(this.lightPlane); + geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3)); + this.targetLine = new Line(geometry, material); + this.add(this.targetLine); + this.update(); + } + dispose() { + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + _v1.setFromMatrixPosition(this.light.matrixWorld); + _v2.setFromMatrixPosition(this.light.target.matrixWorld); + _v3.subVectors(_v2, _v1); + this.lightPlane.lookAt(_v2); + if (this.color !== undefined) { + this.lightPlane.material.color.set(this.color); + this.targetLine.material.color.set(this.color); + } else { + this.lightPlane.material.color.copy(this.light.color); + this.targetLine.material.color.copy(this.light.color); + } + this.targetLine.lookAt(_v2); + this.targetLine.scale.z = _v3.length(); + } +} +var _vector = /* @__PURE__ */ new Vector3; +var _camera = /* @__PURE__ */ new Camera; + +class CameraHelper extends LineSegments { + constructor(camera) { + const geometry = new BufferGeometry; + const material = new LineBasicMaterial({ color: 16777215, vertexColors: true, toneMapped: false }); + const vertices = []; + const colors = []; + const pointMap = {}; + addLine("n1", "n2"); + addLine("n2", "n4"); + addLine("n4", "n3"); + addLine("n3", "n1"); + addLine("f1", "f2"); + addLine("f2", "f4"); + addLine("f4", "f3"); + addLine("f3", "f1"); + addLine("n1", "f1"); + addLine("n2", "f2"); + addLine("n3", "f3"); + addLine("n4", "f4"); + addLine("p", "n1"); + addLine("p", "n2"); + addLine("p", "n3"); + addLine("p", "n4"); + addLine("u1", "u2"); + addLine("u2", "u3"); + addLine("u3", "u1"); + addLine("c", "t"); + addLine("p", "c"); + addLine("cn1", "cn2"); + addLine("cn3", "cn4"); + addLine("cf1", "cf2"); + addLine("cf3", "cf4"); + function addLine(a, b) { + addPoint(a); + addPoint(b); + } + function addPoint(id) { + vertices.push(0, 0, 0); + colors.push(0, 0, 0); + if (pointMap[id] === undefined) { + pointMap[id] = []; + } + pointMap[id].push(vertices.length / 3 - 1); + } + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + super(geometry, material); + this.type = "CameraHelper"; + this.camera = camera; + if (this.camera.updateProjectionMatrix) + this.camera.updateProjectionMatrix(); + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; + this.pointMap = pointMap; + this.update(); + const colorFrustum = new Color(16755200); + const colorCone = new Color(16711680); + const colorUp = new Color(43775); + const colorTarget = new Color(16777215); + const colorCross = new Color(3355443); + this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross); + } + setColors(frustum, cone, up, target, cross) { + const geometry = this.geometry; + const colorAttribute = geometry.getAttribute("color"); + colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(24, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(26, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(28, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(30, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(32, up.r, up.g, up.b); + colorAttribute.setXYZ(33, up.r, up.g, up.b); + colorAttribute.setXYZ(34, up.r, up.g, up.b); + colorAttribute.setXYZ(35, up.r, up.g, up.b); + colorAttribute.setXYZ(36, up.r, up.g, up.b); + colorAttribute.setXYZ(37, up.r, up.g, up.b); + colorAttribute.setXYZ(38, target.r, target.g, target.b); + colorAttribute.setXYZ(39, target.r, target.g, target.b); + colorAttribute.setXYZ(40, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(42, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(44, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(46, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(48, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); + colorAttribute.needsUpdate = true; + } + update() { + const geometry = this.geometry; + const pointMap = this.pointMap; + const w = 1, h = 1; + _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); + const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? -1 : 0; + setPoint("c", pointMap, geometry, _camera, 0, 0, nearZ); + setPoint("t", pointMap, geometry, _camera, 0, 0, 1); + setPoint("n1", pointMap, geometry, _camera, -w, -h, nearZ); + setPoint("n2", pointMap, geometry, _camera, w, -h, nearZ); + setPoint("n3", pointMap, geometry, _camera, -w, h, nearZ); + setPoint("n4", pointMap, geometry, _camera, w, h, nearZ); + setPoint("f1", pointMap, geometry, _camera, -w, -h, 1); + setPoint("f2", pointMap, geometry, _camera, w, -h, 1); + setPoint("f3", pointMap, geometry, _camera, -w, h, 1); + setPoint("f4", pointMap, geometry, _camera, w, h, 1); + setPoint("u1", pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ); + setPoint("u2", pointMap, geometry, _camera, -w * 0.7, h * 1.1, nearZ); + setPoint("u3", pointMap, geometry, _camera, 0, h * 2, nearZ); + setPoint("cf1", pointMap, geometry, _camera, -w, 0, 1); + setPoint("cf2", pointMap, geometry, _camera, w, 0, 1); + setPoint("cf3", pointMap, geometry, _camera, 0, -h, 1); + setPoint("cf4", pointMap, geometry, _camera, 0, h, 1); + setPoint("cn1", pointMap, geometry, _camera, -w, 0, nearZ); + setPoint("cn2", pointMap, geometry, _camera, w, 0, nearZ); + setPoint("cn3", pointMap, geometry, _camera, 0, -h, nearZ); + setPoint("cn4", pointMap, geometry, _camera, 0, h, nearZ); + geometry.getAttribute("position").needsUpdate = true; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} +function setPoint(point, pointMap, geometry, camera, x, y, z) { + _vector.set(x, y, z).unproject(camera); + const points = pointMap[point]; + if (points !== undefined) { + const position2 = geometry.getAttribute("position"); + for (let i = 0, l = points.length;i < l; i++) { + position2.setXYZ(points[i], _vector.x, _vector.y, _vector.z); + } + } +} +var _box = /* @__PURE__ */ new Box3; + +class BoxHelper extends LineSegments { + constructor(object, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = new Float32Array(8 * 3); + const geometry = new BufferGeometry; + geometry.setIndex(new BufferAttribute(indices, 1)); + geometry.setAttribute("position", new BufferAttribute(positions, 3)); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.object = object; + this.type = "BoxHelper"; + this.matrixAutoUpdate = false; + this.update(); + } + update(object) { + if (object !== undefined) { + console.warn("THREE.BoxHelper: .update() has no longer arguments."); + } + if (this.object !== undefined) { + _box.setFromObject(this.object); + } + if (_box.isEmpty()) + return; + const min = _box.min; + const max = _box.max; + const position2 = this.geometry.attributes.position; + const array = position2.array; + array[0] = max.x; + array[1] = max.y; + array[2] = max.z; + array[3] = min.x; + array[4] = max.y; + array[5] = max.z; + array[6] = min.x; + array[7] = min.y; + array[8] = max.z; + array[9] = max.x; + array[10] = min.y; + array[11] = max.z; + array[12] = max.x; + array[13] = max.y; + array[14] = min.z; + array[15] = min.x; + array[16] = max.y; + array[17] = min.z; + array[18] = min.x; + array[19] = min.y; + array[20] = min.z; + array[21] = max.x; + array[22] = min.y; + array[23] = min.z; + position2.needsUpdate = true; + this.geometry.computeBoundingSphere(); + } + setFromObject(object) { + this.object = object; + this.update(); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + this.object = source.object; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} + +class Box3Helper extends LineSegments { + constructor(box, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1]; + const geometry = new BufferGeometry; + geometry.setIndex(new BufferAttribute(indices, 1)); + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.box = box; + this.type = "Box3Helper"; + this.geometry.computeBoundingSphere(); + } + updateMatrixWorld(force) { + const box = this.box; + if (box.isEmpty()) + return; + box.getCenter(this.position); + box.getSize(this.scale); + this.scale.multiplyScalar(0.5); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} + +class PlaneHelper extends Line { + constructor(plane, size = 1, hex = 16776960) { + const color = hex; + const positions = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0]; + const geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + geometry.computeBoundingSphere(); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.type = "PlaneHelper"; + this.plane = plane; + this.size = size; + const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0]; + const geometry2 = new BufferGeometry; + geometry2.setAttribute("position", new Float32BufferAttribute(positions2, 3)); + geometry2.computeBoundingSphere(); + this.add(new Mesh(geometry2, new MeshBasicMaterial({ color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false }))); + } + updateMatrixWorld(force) { + this.position.set(0, 0, 0); + this.scale.set(0.5 * this.size, 0.5 * this.size, 1); + this.lookAt(this.plane.normal); + this.translateZ(-this.plane.constant); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } +} +var _axis = /* @__PURE__ */ new Vector3; +var _lineGeometry; +var _coneGeometry; + +class ArrowHelper extends Object3D { + constructor(dir = new Vector3(0, 0, 1), origin = new Vector3(0, 0, 0), length2 = 1, color = 16776960, headLength = length2 * 0.2, headWidth = headLength * 0.2) { + super(); + this.type = "ArrowHelper"; + if (_lineGeometry === undefined) { + _lineGeometry = new BufferGeometry; + _lineGeometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3)); + _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1); + _coneGeometry.translate(0, -0.5, 0); + } + this.position.copy(origin); + this.line = new Line(_lineGeometry, new LineBasicMaterial({ color, toneMapped: false })); + this.line.matrixAutoUpdate = false; + this.add(this.line); + this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({ color, toneMapped: false })); + this.cone.matrixAutoUpdate = false; + this.add(this.cone); + this.setDirection(dir); + this.setLength(length2, headLength, headWidth); + } + setDirection(dir) { + if (dir.y > 0.99999) { + this.quaternion.set(0, 0, 0, 1); + } else if (dir.y < -0.99999) { + this.quaternion.set(1, 0, 0, 0); + } else { + _axis.set(dir.z, 0, -dir.x).normalize(); + const radians = Math.acos(dir.y); + this.quaternion.setFromAxisAngle(_axis, radians); + } + } + setLength(length2, headLength = length2 * 0.2, headWidth = headLength * 0.2) { + this.line.scale.set(1, Math.max(0.0001, length2 - headLength), 1); + this.line.updateMatrix(); + this.cone.scale.set(headWidth, headLength, headWidth); + this.cone.position.y = length2; + this.cone.updateMatrix(); + } + setColor(color) { + this.line.material.color.set(color); + this.cone.material.color.set(color); + } + copy(source) { + super.copy(source, false); + this.line.copy(source.line); + this.cone.copy(source.cone); + return this; + } + dispose() { + this.line.geometry.dispose(); + this.line.material.dispose(); + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } +} + +class AxesHelper extends LineSegments { + constructor(size = 1) { + const vertices = [ + 0, + 0, + 0, + size, + 0, + 0, + 0, + 0, + 0, + 0, + size, + 0, + 0, + 0, + 0, + 0, + 0, + size + ]; + const colors = [ + 1, + 0, + 0, + 1, + 0.6, + 0, + 0, + 1, + 0, + 0.6, + 1, + 0, + 0, + 0, + 1, + 0, + 0.6, + 1 + ]; + const geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "AxesHelper"; + } + setColors(xAxisColor, yAxisColor, zAxisColor) { + const color = new Color; + const array = this.geometry.attributes.color.array; + color.set(xAxisColor); + color.toArray(array, 0); + color.toArray(array, 3); + color.set(yAxisColor); + color.toArray(array, 6); + color.toArray(array, 9); + color.set(zAxisColor); + color.toArray(array, 12); + color.toArray(array, 15); + this.geometry.attributes.color.needsUpdate = true; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} + +class ShapePath2 { + constructor() { + this.type = "ShapePath"; + this.color = new Color; + this.subPaths = []; + this.currentPath = null; + } + moveTo(x, y) { + this.currentPath = new Path; + this.subPaths.push(this.currentPath); + this.currentPath.moveTo(x, y); + return this; + } + lineTo(x, y) { + this.currentPath.lineTo(x, y); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY); + return this; + } + splineThru(pts) { + this.currentPath.splineThru(pts); + return this; + } + toShapes(isCCW) { + function toShapesNoHoles(inSubpaths) { + const shapes2 = []; + for (let i = 0, l = inSubpaths.length;i < l; i++) { + const tmpPath2 = inSubpaths[i]; + const tmpShape2 = new Shape; + tmpShape2.curves = tmpPath2.curves; + shapes2.push(tmpShape2); + } + return shapes2; + } + function isPointInsidePolygon(inPt, inPolygon) { + const polyLen = inPolygon.length; + let inside = false; + for (let p = polyLen - 1, q = 0;q < polyLen; p = q++) { + let edgeLowPt = inPolygon[p]; + let edgeHighPt = inPolygon[q]; + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; + if (Math.abs(edgeDy) > Number.EPSILON) { + if (edgeDy < 0) { + edgeLowPt = inPolygon[q]; + edgeDx = -edgeDx; + edgeHighPt = inPolygon[p]; + edgeDy = -edgeDy; + } + if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) + continue; + if (inPt.y === edgeLowPt.y) { + if (inPt.x === edgeLowPt.x) + return true; + } else { + const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); + if (perpEdge === 0) + return true; + if (perpEdge < 0) + continue; + inside = !inside; + } + } else { + if (inPt.y !== edgeLowPt.y) + continue; + if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) + return true; + } + } + return inside; + } + const isClockWise = ShapeUtils.isClockWise; + const subPaths = this.subPaths; + if (subPaths.length === 0) + return []; + let solid, tmpPath, tmpShape; + const shapes = []; + if (subPaths.length === 1) { + tmpPath = subPaths[0]; + tmpShape = new Shape; + tmpShape.curves = tmpPath.curves; + shapes.push(tmpShape); + return shapes; + } + let holesFirst = !isClockWise(subPaths[0].getPoints()); + holesFirst = isCCW ? !holesFirst : holesFirst; + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; + newShapes[mainIdx] = undefined; + newShapeHoles[mainIdx] = []; + for (let i = 0, l = subPaths.length;i < l; i++) { + tmpPath = subPaths[i]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise(tmpPoints); + solid = isCCW ? !solid : solid; + if (solid) { + if (!holesFirst && newShapes[mainIdx]) + mainIdx++; + newShapes[mainIdx] = { s: new Shape, p: tmpPoints }; + newShapes[mainIdx].s.curves = tmpPath.curves; + if (holesFirst) + mainIdx++; + newShapeHoles[mainIdx] = []; + } else { + newShapeHoles[mainIdx].push({ h: tmpPath, p: tmpPoints[0] }); + } + } + if (!newShapes[0]) + return toShapesNoHoles(subPaths); + if (newShapes.length > 1) { + let ambiguous = false; + let toChange = 0; + for (let sIdx = 0, sLen = newShapes.length;sIdx < sLen; sIdx++) { + betterShapeHoles[sIdx] = []; + } + for (let sIdx = 0, sLen = newShapes.length;sIdx < sLen; sIdx++) { + const sho = newShapeHoles[sIdx]; + for (let hIdx = 0;hIdx < sho.length; hIdx++) { + const ho = sho[hIdx]; + let hole_unassigned = true; + for (let s2Idx = 0;s2Idx < newShapes.length; s2Idx++) { + if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) { + if (sIdx !== s2Idx) + toChange++; + if (hole_unassigned) { + hole_unassigned = false; + betterShapeHoles[s2Idx].push(ho); + } else { + ambiguous = true; + } + } + } + if (hole_unassigned) { + betterShapeHoles[sIdx].push(ho); + } + } + } + if (toChange > 0 && ambiguous === false) { + newShapeHoles = betterShapeHoles; + } + } + let tmpHoles; + for (let i = 0, il = newShapes.length;i < il; i++) { + tmpShape = newShapes[i].s; + shapes.push(tmpShape); + tmpHoles = newShapeHoles[i]; + for (let j = 0, jl = tmpHoles.length;j < jl; j++) { + tmpShape.holes.push(tmpHoles[j].h); + } + } + return shapes; + } +} + +class Controls extends EventDispatcher { + constructor(object, domElement = null) { + super(); + this.object = object; + this.domElement = domElement; + this.enabled = true; + this.state = -1; + this.keys = {}; + this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null }; + this.touches = { ONE: null, TWO: null }; + } + connect() { + } + disconnect() { + } + dispose() { + } + update() { + } +} +function contain(texture, aspect2) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect2) { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect2; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } else { + texture.repeat.x = aspect2 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } + return texture; +} +function cover(texture, aspect2) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect2) { + texture.repeat.x = aspect2 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } else { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect2; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } + return texture; +} +function fill(texture) { + texture.repeat.x = 1; + texture.repeat.y = 1; + texture.offset.x = 0; + texture.offset.y = 0; + return texture; +} +function getByteLength(width2, height2, format, type) { + const typeByteLength = getTextureTypeByteLength(type); + switch (format) { + case AlphaFormat: + return width2 * height2; + case LuminanceFormat: + return width2 * height2; + case LuminanceAlphaFormat: + return width2 * height2 * 2; + case RedFormat: + return width2 * height2 / typeByteLength.components * typeByteLength.byteLength; + case RedIntegerFormat: + return width2 * height2 / typeByteLength.components * typeByteLength.byteLength; + case RGFormat: + return width2 * height2 * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGIntegerFormat: + return width2 * height2 * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGBFormat: + return width2 * height2 * 3 / typeByteLength.components * typeByteLength.byteLength; + case RGBAFormat: + return width2 * height2 * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGBAIntegerFormat: + return width2 * height2 * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGB_S3TC_DXT1_Format: + case RGBA_S3TC_DXT1_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 8; + case RGBA_S3TC_DXT3_Format: + case RGBA_S3TC_DXT5_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGB_PVRTC_2BPPV1_Format: + case RGBA_PVRTC_2BPPV1_Format: + return Math.max(width2, 16) * Math.max(height2, 8) / 4; + case RGB_PVRTC_4BPPV1_Format: + case RGBA_PVRTC_4BPPV1_Format: + return Math.max(width2, 8) * Math.max(height2, 8) / 2; + case RGB_ETC1_Format: + case RGB_ETC2_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 8; + case RGBA_ETC2_EAC_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_4x4_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_5x4_Format: + return Math.floor((width2 + 4) / 5) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_5x5_Format: + return Math.floor((width2 + 4) / 5) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_6x5_Format: + return Math.floor((width2 + 5) / 6) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_6x6_Format: + return Math.floor((width2 + 5) / 6) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_8x5_Format: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_8x6_Format: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_8x8_Format: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 7) / 8) * 16; + case RGBA_ASTC_10x5_Format: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_10x6_Format: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_10x8_Format: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 7) / 8) * 16; + case RGBA_ASTC_10x10_Format: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 9) / 10) * 16; + case RGBA_ASTC_12x10_Format: + return Math.floor((width2 + 11) / 12) * Math.floor((height2 + 9) / 10) * 16; + case RGBA_ASTC_12x12_Format: + return Math.floor((width2 + 11) / 12) * Math.floor((height2 + 11) / 12) * 16; + case RGBA_BPTC_Format: + case RGB_BPTC_SIGNED_Format: + case RGB_BPTC_UNSIGNED_Format: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 16; + case RED_RGTC1_Format: + case SIGNED_RED_RGTC1_Format: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 8; + case RED_GREEN_RGTC2_Format: + case SIGNED_RED_GREEN_RGTC2_Format: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 16; + } + throw new Error(`Unable to determine texture byte length for ${format} format.`); +} +function getTextureTypeByteLength(type) { + switch (type) { + case UnsignedByteType: + case ByteType: + return { byteLength: 1, components: 1 }; + case UnsignedShortType: + case ShortType: + case HalfFloatType: + return { byteLength: 2, components: 1 }; + case UnsignedShort4444Type: + case UnsignedShort5551Type: + return { byteLength: 2, components: 4 }; + case UnsignedIntType: + case IntType: + case FloatType: + return { byteLength: 4, components: 1 }; + case UnsignedInt5999Type: + return { byteLength: 4, components: 3 }; + } + throw new Error(`Unknown texture type ${type}.`); +} +var TextureUtils = { + contain, + cover, + fill, + getByteLength +}; +if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { + revision: REVISION + } })); +} +if (typeof window !== "undefined") { + if (window.__THREE__) { + console.warn("WARNING: Multiple instances of Three.js being imported."); + } else { + window.__THREE__ = REVISION; + } +} + +// node_modules/three/build/three.module.js +function WebGLAnimation() { + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + function onAnimationFrame(time2, frame) { + animationLoop(time2, frame); + requestId = context.requestAnimationFrame(onAnimationFrame); + } + return { + start: function() { + if (isAnimating === true) + return; + if (animationLoop === null) + return; + requestId = context.requestAnimationFrame(onAnimationFrame); + isAnimating = true; + }, + stop: function() { + context.cancelAnimationFrame(requestId); + isAnimating = false; + }, + setAnimationLoop: function(callback) { + animationLoop = callback; + }, + setContext: function(value2) { + context = value2; + } + }; +} +function WebGLAttributes(gl) { + const buffers = new WeakMap; + function createBuffer(attribute, bufferType) { + const array = attribute.array; + const usage = attribute.usage; + const size = array.byteLength; + const buffer = gl.createBuffer(); + gl.bindBuffer(bufferType, buffer); + gl.bufferData(bufferType, array, usage); + attribute.onUploadCallback(); + let type; + if (array instanceof Float32Array) { + type = gl.FLOAT; + } else if (array instanceof Uint16Array) { + if (attribute.isFloat16BufferAttribute) { + type = gl.HALF_FLOAT; + } else { + type = gl.UNSIGNED_SHORT; + } + } else if (array instanceof Int16Array) { + type = gl.SHORT; + } else if (array instanceof Uint32Array) { + type = gl.UNSIGNED_INT; + } else if (array instanceof Int32Array) { + type = gl.INT; + } else if (array instanceof Int8Array) { + type = gl.BYTE; + } else if (array instanceof Uint8Array) { + type = gl.UNSIGNED_BYTE; + } else if (array instanceof Uint8ClampedArray) { + type = gl.UNSIGNED_BYTE; + } else { + throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + array); + } + return { + buffer, + type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version, + size + }; + } + function updateBuffer(buffer, attribute, bufferType) { + const array = attribute.array; + const updateRanges = attribute.updateRanges; + gl.bindBuffer(bufferType, buffer); + if (updateRanges.length === 0) { + gl.bufferSubData(bufferType, 0, array); + } else { + updateRanges.sort((a, b) => a.start - b.start); + let mergeIndex = 0; + for (let i = 1;i < updateRanges.length; i++) { + const previousRange = updateRanges[mergeIndex]; + const range = updateRanges[i]; + if (range.start <= previousRange.start + previousRange.count + 1) { + previousRange.count = Math.max(previousRange.count, range.start + range.count - previousRange.start); + } else { + ++mergeIndex; + updateRanges[mergeIndex] = range; + } + } + updateRanges.length = mergeIndex + 1; + for (let i = 0, l = updateRanges.length;i < l; i++) { + const range = updateRanges[i]; + gl.bufferSubData(bufferType, range.start * array.BYTES_PER_ELEMENT, array, range.start, range.count); + } + attribute.clearUpdateRanges(); + } + attribute.onUploadCallback(); + } + function get(attribute) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + return buffers.get(attribute); + } + function remove(attribute) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + const data2 = buffers.get(attribute); + if (data2) { + gl.deleteBuffer(data2.buffer); + buffers.delete(attribute); + } + } + function update(attribute, bufferType) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + if (attribute.isGLBufferAttribute) { + const cached = buffers.get(attribute); + if (!cached || cached.version < attribute.version) { + buffers.set(attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + }); + } + return; + } + const data2 = buffers.get(attribute); + if (data2 === undefined) { + buffers.set(attribute, createBuffer(attribute, bufferType)); + } else if (data2.version < attribute.version) { + if (data2.size !== attribute.array.byteLength) { + throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported."); + } + updateBuffer(data2.buffer, attribute, bufferType); + data2.version = attribute.version; + } + } + return { + get, + remove, + update + }; +} +var alphahash_fragment = `#ifdef USE_ALPHAHASH + if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard; +#endif`; +var alphahash_pars_fragment = `#ifdef USE_ALPHAHASH + const float ALPHA_HASH_SCALE = 0.05; + float hash2D( vec2 value ) { + return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) ); + } + float hash3D( vec3 value ) { + return hash2D( vec2( hash2D( value.xy ), value.z ) ); + } + float getAlphaHashThreshold( vec3 position ) { + float maxDeriv = max( + length( dFdx( position.xyz ) ), + length( dFdy( position.xyz ) ) + ); + float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv ); + vec2 pixScales = vec2( + exp2( floor( log2( pixScale ) ) ), + exp2( ceil( log2( pixScale ) ) ) + ); + vec2 alpha = vec2( + hash3D( floor( pixScales.x * position.xyz ) ), + hash3D( floor( pixScales.y * position.xyz ) ) + ); + float lerpFactor = fract( log2( pixScale ) ); + float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y; + float a = min( lerpFactor, 1.0 - lerpFactor ); + vec3 cases = vec3( + x * x / ( 2.0 * a * ( 1.0 - a ) ), + ( x - 0.5 * a ) / ( 1.0 - a ), + 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) ) + ); + float threshold = ( x < ( 1.0 - a ) ) + ? ( ( x < a ) ? cases.x : cases.y ) + : cases.z; + return clamp( threshold , 1.0e-6, 1.0 ); + } +#endif`; +var alphamap_fragment = `#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g; +#endif`; +var alphamap_pars_fragment = `#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`; +var alphatest_fragment = `#ifdef USE_ALPHATEST + #ifdef ALPHA_TO_COVERAGE + diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a ); + if ( diffuseColor.a == 0.0 ) discard; + #else + if ( diffuseColor.a < alphaTest ) discard; + #endif +#endif`; +var alphatest_pars_fragment = `#ifdef USE_ALPHATEST + uniform float alphaTest; +#endif`; +var aomap_fragment = `#ifdef USE_AOMAP + float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0; + reflectedLight.indirectDiffuse *= ambientOcclusion; + #if defined( USE_CLEARCOAT ) + clearcoatSpecularIndirect *= ambientOcclusion; + #endif + #if defined( USE_SHEEN ) + sheenSpecularIndirect *= ambientOcclusion; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) + float dotNV = saturate( dot( geometryNormal, geometryViewDir ) ); + reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness ); + #endif +#endif`; +var aomap_pars_fragment = `#ifdef USE_AOMAP + uniform sampler2D aoMap; + uniform float aoMapIntensity; +#endif`; +var batching_pars_vertex = `#ifdef USE_BATCHING + #if ! defined( GL_ANGLE_multi_draw ) + #define gl_DrawID _gl_DrawID + uniform int _gl_DrawID; + #endif + uniform highp sampler2D batchingTexture; + uniform highp usampler2D batchingIdTexture; + mat4 getBatchingMatrix( const in float i ) { + int size = textureSize( batchingTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } + float getIndirectIndex( const in int i ) { + int size = textureSize( batchingIdTexture, 0 ).x; + int x = i % size; + int y = i / size; + return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r ); + } +#endif +#ifdef USE_BATCHING_COLOR + uniform sampler2D batchingColorTexture; + vec3 getBatchingColor( const in float i ) { + int size = textureSize( batchingColorTexture, 0 ).x; + int j = int( i ); + int x = j % size; + int y = j / size; + return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb; + } +#endif`; +var batching_vertex = `#ifdef USE_BATCHING + mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) ); +#endif`; +var begin_vertex = `vec3 transformed = vec3( position ); +#ifdef USE_ALPHAHASH + vPosition = vec3( position ); +#endif`; +var beginnormal_vertex = `vec3 objectNormal = vec3( normal ); +#ifdef USE_TANGENT + vec3 objectTangent = vec3( tangent.xyz ); +#endif`; +var bsdfs = `float G_BlinnPhong_Implicit( ) { + return 0.25; +} +float D_BlinnPhong( const in float shininess, const in float dotNH ) { + return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess ); +} +vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( specularColor, 1.0, dotVH ); + float G = G_BlinnPhong_Implicit( ); + float D = D_BlinnPhong( shininess, dotNH ); + return F * ( G * D ); +} // validated`; +var iridescence_fragment = `#ifdef USE_IRIDESCENCE + const mat3 XYZ_TO_REC709 = mat3( + 3.2404542, -0.9692660, 0.0556434, + -1.5371385, 1.8760108, -0.2040259, + -0.4985314, 0.0415560, 1.0572252 + ); + vec3 Fresnel0ToIor( vec3 fresnel0 ) { + vec3 sqrtF0 = sqrt( fresnel0 ); + return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 ); + } + vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) { + return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) ); + } + float IorToFresnel0( float transmittedIor, float incidentIor ) { + return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor )); + } + vec3 evalSensitivity( float OPD, vec3 shift ) { + float phase = 2.0 * PI * OPD * 1.0e-9; + vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 ); + vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 ); + vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 ); + vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var ); + xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) ); + xyz /= 1.0685e-7; + vec3 rgb = XYZ_TO_REC709 * xyz; + return rgb; + } + vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) { + vec3 I; + float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) ); + float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) ); + float cosTheta2Sq = 1.0 - sinTheta2Sq; + if ( cosTheta2Sq < 0.0 ) { + return vec3( 1.0 ); + } + float cosTheta2 = sqrt( cosTheta2Sq ); + float R0 = IorToFresnel0( iridescenceIOR, outsideIOR ); + float R12 = F_Schlick( R0, 1.0, cosTheta1 ); + float T121 = 1.0 - R12; + float phi12 = 0.0; + if ( iridescenceIOR < outsideIOR ) phi12 = PI; + float phi21 = PI - phi12; + vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR ); + vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 ); + vec3 phi23 = vec3( 0.0 ); + if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI; + if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI; + if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI; + float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2; + vec3 phi = vec3( phi21 ) + phi23; + vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 ); + vec3 r123 = sqrt( R123 ); + vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 ); + vec3 C0 = R12 + Rs; + I = C0; + vec3 Cm = Rs - T121; + for ( int m = 1; m <= 2; ++ m ) { + Cm *= r123; + vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi ); + I += Cm * Sm; + } + return max( I, vec3( 0.0 ) ); + } +#endif`; +var bumpmap_pars_fragment = `#ifdef USE_BUMPMAP + uniform sampler2D bumpMap; + uniform float bumpScale; + vec2 dHdxy_fwd() { + vec2 dSTdx = dFdx( vBumpMapUv ); + vec2 dSTdy = dFdy( vBumpMapUv ); + float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x; + float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll; + float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll; + return vec2( dBx, dBy ); + } + vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) { + vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) ); + vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) ); + vec3 vN = surf_norm; + vec3 R1 = cross( vSigmaY, vN ); + vec3 R2 = cross( vN, vSigmaX ); + float fDet = dot( vSigmaX, R1 ) * faceDirection; + vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 ); + return normalize( abs( fDet ) * surf_norm - vGrad ); + } +#endif`; +var clipping_planes_fragment = `#if NUM_CLIPPING_PLANES > 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`; +var clipping_planes_pars_fragment = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`; +var clipping_planes_pars_vertex = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`; +var clipping_planes_vertex = `#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`; +var color_fragment = `#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`; +var color_pars_fragment = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`; +var color_pars_vertex = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`; +var color_vertex = `#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`; +var common = `#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`; +var cube_uv_reflection_fragment = `#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`; +var defaultnormal_vertex = `vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`; +var displacementmap_pars_vertex = `#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`; +var displacementmap_vertex = `#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`; +var emissivemap_fragment = `#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`; +var emissivemap_pars_fragment = `#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`; +var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; +var colorspace_pars_fragment = `vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`; +var envmap_fragment = `#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`; +var envmap_common_pars_fragment = `#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`; +var envmap_pars_fragment = `#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`; +var envmap_pars_vertex = `#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`; +var envmap_vertex = `#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`; +var fog_vertex = `#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`; +var fog_pars_vertex = `#ifdef USE_FOG + varying float vFogDepth; +#endif`; +var fog_fragment = `#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`; +var fog_pars_fragment = `#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`; +var gradientmap_pars_fragment = `#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`; +var lightmap_pars_fragment = `#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`; +var lights_lambert_fragment = `LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`; +var lights_lambert_pars_fragment = `varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`; +var lights_pars_begin = `uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`; +var envmap_physical_pars_fragment = `#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`; +var lights_toon_fragment = `ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`; +var lights_toon_pars_fragment = `varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`; +var lights_phong_fragment = `BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`; +var lights_phong_pars_fragment = `varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`; +var lights_physical_fragment = `PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`; +var lights_physical_pars_fragment = `struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`; +var lights_fragment_begin = ` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`; +var lights_fragment_maps = `#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`; +var lights_fragment_end = `#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`; +var logdepthbuf_fragment = `#if defined( USE_LOGDEPTHBUF ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`; +var logdepthbuf_pars_fragment = `#if defined( USE_LOGDEPTHBUF ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`; +var logdepthbuf_pars_vertex = `#ifdef USE_LOGDEPTHBUF + varying float vFragDepth; + varying float vIsPerspective; +#endif`; +var logdepthbuf_vertex = `#ifdef USE_LOGDEPTHBUF + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`; +var map_fragment = `#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`; +var map_pars_fragment = `#ifdef USE_MAP + uniform sampler2D map; +#endif`; +var map_particle_fragment = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`; +var map_particle_pars_fragment = `#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`; +var metalnessmap_fragment = `float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`; +var metalnessmap_pars_fragment = `#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`; +var morphinstance_vertex = `#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`; +var morphcolor_vertex = `#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`; +var morphnormal_vertex = `#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`; +var morphtarget_pars_vertex = `#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`; +var morphtarget_vertex = `#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`; +var normal_fragment_begin = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`; +var normal_fragment_maps = `#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`; +var normal_pars_fragment = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`; +var normal_pars_vertex = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`; +var normal_vertex = `#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`; +var normalmap_pars_fragment = `#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`; +var clearcoat_normal_fragment_begin = `#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`; +var clearcoat_normal_fragment_maps = `#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`; +var clearcoat_pars_fragment = `#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`; +var iridescence_pars_fragment = `#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`; +var opaque_fragment = `#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`; +var packing = `vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`; +var premultiplied_alpha_fragment = `#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`; +var project_vertex = `vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`; +var dithering_fragment = `#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`; +var dithering_pars_fragment = `#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`; +var roughnessmap_fragment = `float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`; +var roughnessmap_pars_fragment = `#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`; +var shadowmap_pars_fragment = `#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`; +var shadowmap_pars_vertex = `#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`; +var shadowmap_vertex = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`; +var shadowmask_pars_fragment = `float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`; +var skinbase_vertex = `#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`; +var skinning_pars_vertex = `#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`; +var skinning_vertex = `#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`; +var skinnormal_vertex = `#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`; +var specularmap_fragment = `float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`; +var specularmap_pars_fragment = `#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`; +var tonemapping_fragment = `#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`; +var tonemapping_pars_fragment = `#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`; +var transmission_fragment = `#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`; +var transmission_pars_fragment = `#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`; +var uv_pars_fragment = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`; +var uv_pars_vertex = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`; +var uv_vertex = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`; +var worldpos_vertex = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`; +var vertex$h = `varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`; +var fragment$h = `uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`; +var vertex$g = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`; +var fragment$g = `#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`; +var vertex$f = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`; +var fragment$f = `uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`; +var vertex$e = `#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`; +var fragment$e = `#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`; +var vertex$d = `#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`; +var fragment$d = `#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`; +var vertex$c = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`; +var fragment$c = `uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`; +var vertex$b = `uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; +var fragment$b = `uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`; +var vertex$a = `#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; +var fragment$a = `uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`; +var vertex$9 = `#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`; +var fragment$9 = `#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`; +var vertex$8 = `#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`; +var fragment$8 = `#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`; +var vertex$7 = `#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`; +var fragment$7 = `#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`; +var vertex$6 = `#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`; +var fragment$6 = `#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`; +var vertex$5 = `#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`; +var fragment$5 = `#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`; +var vertex$4 = `#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`; +var fragment$4 = `#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`; +var vertex$3 = `uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`; +var fragment$3 = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`; +var vertex$2 = `#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; +var fragment$2 = `uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`; +var vertex$1 = `uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`; +var fragment$1 = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`; +var ShaderChunk = { + alphahash_fragment, + alphahash_pars_fragment, + alphamap_fragment, + alphamap_pars_fragment, + alphatest_fragment, + alphatest_pars_fragment, + aomap_fragment, + aomap_pars_fragment, + batching_pars_vertex, + batching_vertex, + begin_vertex, + beginnormal_vertex, + bsdfs, + iridescence_fragment, + bumpmap_pars_fragment, + clipping_planes_fragment, + clipping_planes_pars_fragment, + clipping_planes_pars_vertex, + clipping_planes_vertex, + color_fragment, + color_pars_fragment, + color_pars_vertex, + color_vertex, + common, + cube_uv_reflection_fragment, + defaultnormal_vertex, + displacementmap_pars_vertex, + displacementmap_vertex, + emissivemap_fragment, + emissivemap_pars_fragment, + colorspace_fragment, + colorspace_pars_fragment, + envmap_fragment, + envmap_common_pars_fragment, + envmap_pars_fragment, + envmap_pars_vertex, + envmap_physical_pars_fragment, + envmap_vertex, + fog_vertex, + fog_pars_vertex, + fog_fragment, + fog_pars_fragment, + gradientmap_pars_fragment, + lightmap_pars_fragment, + lights_lambert_fragment, + lights_lambert_pars_fragment, + lights_pars_begin, + lights_toon_fragment, + lights_toon_pars_fragment, + lights_phong_fragment, + lights_phong_pars_fragment, + lights_physical_fragment, + lights_physical_pars_fragment, + lights_fragment_begin, + lights_fragment_maps, + lights_fragment_end, + logdepthbuf_fragment, + logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex, + logdepthbuf_vertex, + map_fragment, + map_pars_fragment, + map_particle_fragment, + map_particle_pars_fragment, + metalnessmap_fragment, + metalnessmap_pars_fragment, + morphinstance_vertex, + morphcolor_vertex, + morphnormal_vertex, + morphtarget_pars_vertex, + morphtarget_vertex, + normal_fragment_begin, + normal_fragment_maps, + normal_pars_fragment, + normal_pars_vertex, + normal_vertex, + normalmap_pars_fragment, + clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps, + clearcoat_pars_fragment, + iridescence_pars_fragment, + opaque_fragment, + packing, + premultiplied_alpha_fragment, + project_vertex, + dithering_fragment, + dithering_pars_fragment, + roughnessmap_fragment, + roughnessmap_pars_fragment, + shadowmap_pars_fragment, + shadowmap_pars_vertex, + shadowmap_vertex, + shadowmask_pars_fragment, + skinbase_vertex, + skinning_pars_vertex, + skinning_vertex, + skinnormal_vertex, + specularmap_fragment, + specularmap_pars_fragment, + tonemapping_fragment, + tonemapping_pars_fragment, + transmission_fragment, + transmission_pars_fragment, + uv_pars_fragment, + uv_pars_vertex, + uv_vertex, + worldpos_vertex, + background_vert: vertex$h, + background_frag: fragment$h, + backgroundCube_vert: vertex$g, + backgroundCube_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distanceRGBA_vert: vertex$d, + distanceRGBA_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 +}; +var UniformsLib = { + common: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaTest: { value: 0 } + }, + specularmap: { + specularMap: { value: null }, + specularMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + envmap: { + envMap: { value: null }, + envMapRotation: { value: /* @__PURE__ */ new Matrix3 }, + flipEnvMap: { value: -1 }, + reflectivity: { value: 1 }, + ior: { value: 1.5 }, + refractionRatio: { value: 0.98 } + }, + aomap: { + aoMap: { value: null }, + aoMapIntensity: { value: 1 }, + aoMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + lightmap: { + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + bumpmap: { + bumpMap: { value: null }, + bumpMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + bumpScale: { value: 1 } + }, + normalmap: { + normalMap: { value: null }, + normalMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + normalScale: { value: /* @__PURE__ */ new Vector2(1, 1) } + }, + displacementmap: { + displacementMap: { value: null }, + displacementMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + }, + emissivemap: { + emissiveMap: { value: null }, + emissiveMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + metalnessmap: { + metalnessMap: { value: null }, + metalnessMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + roughnessmap: { + roughnessMap: { value: null }, + roughnessMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + gradientmap: { + gradientMap: { value: null } + }, + fog: { + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: /* @__PURE__ */ new Color(16777215) } + }, + lights: { + ambientLightColor: { value: [] }, + lightProbe: { value: [] }, + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + directionalLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + spotLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + pointLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + ltc_1: { value: null }, + ltc_2: { value: null } + }, + points: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + size: { value: 1 }, + scale: { value: 1 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaTest: { value: 0 }, + uvTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + sprite: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + center: { value: /* @__PURE__ */ new Vector2(0.5, 0.5) }, + rotation: { value: 0 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaTest: { value: 0 } + } +}; +var ShaderLib = { + basic: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag + }, + lambert: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) } + } + ]), + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + }, + phong: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + specular: { value: /* @__PURE__ */ new Color(1118481) }, + shininess: { value: 30 } + } + ]), + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag + }, + standard: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + roughness: { value: 1 }, + metalness: { value: 0 }, + envMapIntensity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + }, + toon: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) } + } + ]), + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag + }, + matcap: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ]), + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag + }, + points: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.points, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag + }, + dashed: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ]), + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag + }, + depth: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.displacementmap + ]), + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag + }, + normal: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag + }, + sprite: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.sprite, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag + }, + background: { + uniforms: { + uvTransform: { value: /* @__PURE__ */ new Matrix3 }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag + }, + backgroundCube: { + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /* @__PURE__ */ new Matrix3 } + }, + vertexShader: ShaderChunk.backgroundCube_vert, + fragmentShader: ShaderChunk.backgroundCube_frag + }, + cube: { + uniforms: { + tCube: { value: null }, + tFlip: { value: -1 }, + opacity: { value: 1 } + }, + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag + }, + equirect: { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag + }, + distanceRGBA: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: /* @__PURE__ */ new Vector3 }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ]), + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag + }, + shadow: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: /* @__PURE__ */ new Color(0) }, + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag + } +}; +ShaderLib.physical = { + uniforms: /* @__PURE__ */ mergeUniforms([ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + clearcoatNormalScale: { value: /* @__PURE__ */ new Vector2(1, 1) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + dispersion: { value: 0 }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + sheen: { value: 0 }, + sheenColor: { value: /* @__PURE__ */ new Color(0) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + transmissionSamplerSize: { value: /* @__PURE__ */ new Vector2 }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /* @__PURE__ */ new Color(0) }, + specularColor: { value: /* @__PURE__ */ new Color(1, 1, 1) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + anisotropyVector: { value: /* @__PURE__ */ new Vector2 }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /* @__PURE__ */ new Matrix3 } + } + ]), + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag +}; +var _rgb = { r: 0, b: 0, g: 0 }; +var _e1$1 = /* @__PURE__ */ new Euler; +var _m1$12 = /* @__PURE__ */ new Matrix4; +function WebGLBackground(renderer2, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) { + const clearColor = new Color(0); + let clearAlpha = alpha === true ? 0 : 1; + let planeMesh; + let boxMesh; + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + function getBackground(scene) { + let background = scene.isScene === true ? scene.background : null; + if (background && background.isTexture) { + const usePMREM = scene.backgroundBlurriness > 0; + background = (usePMREM ? cubeuvmaps : cubemaps).get(background); + } + return background; + } + function render(scene) { + let forceClear = false; + const background = getBackground(scene); + if (background === null) { + setClear(clearColor, clearAlpha); + } else if (background && background.isColor) { + setClear(background, 1); + forceClear = true; + } + const environmentBlendMode = renderer2.xr.getEnvironmentBlendMode(); + if (environmentBlendMode === "additive") { + state.buffers.color.setClear(0, 0, 0, 1, premultipliedAlpha); + } else if (environmentBlendMode === "alpha-blend") { + state.buffers.color.setClear(0, 0, 0, 0, premultipliedAlpha); + } + if (renderer2.autoClear || forceClear) { + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + renderer2.clear(renderer2.autoClearColor, renderer2.autoClearDepth, renderer2.autoClearStencil); + } + } + function addToRenderList(renderList, scene) { + const background = getBackground(scene); + if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) { + if (boxMesh === undefined) { + boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({ + name: "BackgroundCubeMaterial", + uniforms: cloneUniforms(ShaderLib.backgroundCube.uniforms), + vertexShader: ShaderLib.backgroundCube.vertexShader, + fragmentShader: ShaderLib.backgroundCube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false + })); + boxMesh.geometry.deleteAttribute("normal"); + boxMesh.geometry.deleteAttribute("uv"); + boxMesh.onBeforeRender = function(renderer3, scene2, camera) { + this.matrixWorld.copyPosition(camera.matrixWorld); + }; + Object.defineProperty(boxMesh.material, "envMap", { + get: function() { + return this.uniforms.envMap.value; + } + }); + objects.update(boxMesh); + } + _e1$1.copy(scene.backgroundRotation); + _e1$1.x *= -1; + _e1$1.y *= -1; + _e1$1.z *= -1; + if (background.isCubeTexture && background.isRenderTargetTexture === false) { + _e1$1.y *= -1; + _e1$1.z *= -1; + } + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4(_m1$12.makeRotationFromEuler(_e1$1)); + boxMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer; + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer2.toneMapping) { + boxMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer2.toneMapping; + } + boxMesh.layers.enableAll(); + renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null); + } else if (background && background.isTexture) { + if (planeMesh === undefined) { + planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({ + name: "BackgroundMaterial", + uniforms: cloneUniforms(ShaderLib.background.uniforms), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false + })); + planeMesh.geometry.deleteAttribute("normal"); + Object.defineProperty(planeMesh.material, "map", { + get: function() { + return this.uniforms.t2D.value; + } + }); + objects.update(planeMesh); + } + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer; + if (background.matrixAutoUpdate === true) { + background.updateMatrix(); + } + planeMesh.material.uniforms.uvTransform.value.copy(background.matrix); + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer2.toneMapping) { + planeMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer2.toneMapping; + } + planeMesh.layers.enableAll(); + renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null); + } + } + function setClear(color, alpha2) { + color.getRGB(_rgb, getUnlitUniformColorSpace(renderer2)); + state.buffers.color.setClear(_rgb.r, _rgb.g, _rgb.b, alpha2, premultipliedAlpha); + } + function dispose() { + if (boxMesh !== undefined) { + boxMesh.geometry.dispose(); + boxMesh.material.dispose(); + boxMesh = undefined; + } + if (planeMesh !== undefined) { + planeMesh.geometry.dispose(); + planeMesh.material.dispose(); + planeMesh = undefined; + } + } + return { + getClearColor: function() { + return clearColor; + }, + setClearColor: function(color, alpha2 = 1) { + clearColor.set(color); + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + getClearAlpha: function() { + return clearAlpha; + }, + setClearAlpha: function(alpha2) { + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + render, + addToRenderList, + dispose + }; +} +function WebGLBindingStates(gl, attributes) { + const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const bindingStates = {}; + const defaultState = createBindingState(null); + let currentState = defaultState; + let forceUpdate = false; + function setup(object, material, program, geometry, index2) { + let updateBuffers = false; + const state = getBindingState(geometry, program, material); + if (currentState !== state) { + currentState = state; + bindVertexArrayObject(currentState.object); + } + updateBuffers = needsUpdate(object, geometry, program, index2); + if (updateBuffers) + saveCache(object, geometry, program, index2); + if (index2 !== null) { + attributes.update(index2, gl.ELEMENT_ARRAY_BUFFER); + } + if (updateBuffers || forceUpdate) { + forceUpdate = false; + setupVertexAttributes(object, material, program, geometry); + if (index2 !== null) { + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index2).buffer); + } + } + } + function createVertexArrayObject() { + return gl.createVertexArray(); + } + function bindVertexArrayObject(vao) { + return gl.bindVertexArray(vao); + } + function deleteVertexArrayObject(vao) { + return gl.deleteVertexArray(vao); + } + function getBindingState(geometry, program, material) { + const wireframe = material.wireframe === true; + let programMap = bindingStates[geometry.id]; + if (programMap === undefined) { + programMap = {}; + bindingStates[geometry.id] = programMap; + } + let stateMap = programMap[program.id]; + if (stateMap === undefined) { + stateMap = {}; + programMap[program.id] = stateMap; + } + let state = stateMap[wireframe]; + if (state === undefined) { + state = createBindingState(createVertexArrayObject()); + stateMap[wireframe] = state; + } + return state; + } + function createBindingState(vao) { + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + for (let i = 0;i < maxVertexAttributes; i++) { + newAttributes[i] = 0; + enabledAttributes[i] = 0; + attributeDivisors[i] = 0; + } + return { + geometry: null, + program: null, + wireframe: false, + newAttributes, + enabledAttributes, + attributeDivisors, + object: vao, + attributes: {}, + index: null + }; + } + function needsUpdate(object, geometry, program, index2) { + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + const cachedAttribute = cachedAttributes[name2]; + let geometryAttribute = geometryAttributes[name2]; + if (geometryAttribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + geometryAttribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + geometryAttribute = object.instanceColor; + } + if (cachedAttribute === undefined) + return true; + if (cachedAttribute.attribute !== geometryAttribute) + return true; + if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) + return true; + attributesNum++; + } + } + if (currentState.attributesNum !== attributesNum) + return true; + if (currentState.index !== index2) + return true; + return false; + } + function saveCache(object, geometry, program, index2) { + const cache = {}; + const attributes2 = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + let attribute = attributes2[name2]; + if (attribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + attribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + attribute = object.instanceColor; + } + const data2 = {}; + data2.attribute = attribute; + if (attribute && attribute.data) { + data2.data = attribute.data; + } + cache[name2] = data2; + attributesNum++; + } + } + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + currentState.index = index2; + } + function initAttributes() { + const newAttributes = currentState.newAttributes; + for (let i = 0, il = newAttributes.length;i < il; i++) { + newAttributes[i] = 0; + } + } + function enableAttribute(attribute) { + enableAttributeAndDivisor(attribute, 0); + } + function enableAttributeAndDivisor(attribute, meshPerAttribute) { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + newAttributes[attribute] = 1; + if (enabledAttributes[attribute] === 0) { + gl.enableVertexAttribArray(attribute); + enabledAttributes[attribute] = 1; + } + if (attributeDivisors[attribute] !== meshPerAttribute) { + gl.vertexAttribDivisor(attribute, meshPerAttribute); + attributeDivisors[attribute] = meshPerAttribute; + } + } + function disableUnusedAttributes() { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + for (let i = 0, il = enabledAttributes.length;i < il; i++) { + if (enabledAttributes[i] !== newAttributes[i]) { + gl.disableVertexAttribArray(i); + enabledAttributes[i] = 0; + } + } + } + function vertexAttribPointer(index2, size, type, normalized, stride, offset, integer) { + if (integer === true) { + gl.vertexAttribIPointer(index2, size, type, stride, offset); + } else { + gl.vertexAttribPointer(index2, size, type, normalized, stride, offset); + } + } + function setupVertexAttributes(object, material, program, geometry) { + initAttributes(); + const geometryAttributes = geometry.attributes; + const programAttributes = program.getAttributes(); + const materialDefaultAttributeValues = material.defaultAttributeValues; + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + let geometryAttribute = geometryAttributes[name2]; + if (geometryAttribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + geometryAttribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + geometryAttribute = object.instanceColor; + } + if (geometryAttribute !== undefined) { + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + const attribute = attributes.get(geometryAttribute); + if (attribute === undefined) + continue; + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + const integer = type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType; + if (geometryAttribute.isInterleavedBufferAttribute) { + const data2 = geometryAttribute.data; + const stride = data2.stride; + const offset = geometryAttribute.offset; + if (data2.isInstancedInterleavedBuffer) { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, data2.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { + geometry._maxInstanceCount = data2.meshPerAttribute * data2.count; + } + } else { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0;i < programAttribute.locationSize; i++) { + vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement, integer); + } + } else { + if (geometryAttribute.isInstancedBufferAttribute) { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } + } else { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0;i < programAttribute.locationSize; i++) { + vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement, integer); + } + } + } else if (materialDefaultAttributeValues !== undefined) { + const value2 = materialDefaultAttributeValues[name2]; + if (value2 !== undefined) { + switch (value2.length) { + case 2: + gl.vertexAttrib2fv(programAttribute.location, value2); + break; + case 3: + gl.vertexAttrib3fv(programAttribute.location, value2); + break; + case 4: + gl.vertexAttrib4fv(programAttribute.location, value2); + break; + default: + gl.vertexAttrib1fv(programAttribute.location, value2); + } + } + } + } + } + disableUnusedAttributes(); + } + function dispose() { + reset(); + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometryId]; + } + } + function releaseStatesOfGeometry(geometry) { + if (bindingStates[geometry.id] === undefined) + return; + const programMap = bindingStates[geometry.id]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometry.id]; + } + function releaseStatesOfProgram(program) { + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + if (programMap[program.id] === undefined) + continue; + const stateMap = programMap[program.id]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[program.id]; + } + } + function reset() { + resetDefaultState(); + forceUpdate = true; + if (currentState === defaultState) + return; + currentState = defaultState; + bindVertexArrayObject(currentState.object); + } + function resetDefaultState() { + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + } + return { + setup, + reset, + resetDefaultState, + dispose, + releaseStatesOfGeometry, + releaseStatesOfProgram, + initAttributes, + enableAttribute, + disableUnusedAttributes + }; +} +function WebGLBufferRenderer(gl, extensions, info) { + let mode; + function setMode(value2) { + mode = value2; + } + function render(start, count) { + gl.drawArrays(mode, start, count); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) + return; + gl.drawArraysInstanced(mode, start, count, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawArraysWEBGL(mode, starts, 0, counts, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0;i < starts.length; i++) { + renderInstances(starts[i], counts[i], primcount[i]); + } + } else { + extension.multiDrawArraysInstancedWEBGL(mode, starts, 0, counts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i] * primcount[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; +} +function WebGLCapabilities(gl, extensions, parameters, utils) { + let maxAnisotropy; + function getMaxAnisotropy() { + if (maxAnisotropy !== undefined) + return maxAnisotropy; + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } else { + maxAnisotropy = 0; + } + return maxAnisotropy; + } + function textureFormatReadable(textureFormat) { + if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT)) { + return false; + } + return true; + } + function textureTypeReadable(textureType) { + const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float")); + if (textureType !== UnsignedByteType && utils.convert(textureType) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE) && textureType !== FloatType && !halfFloatSupportedByExt) { + return false; + } + return true; + } + function getMaxPrecision(precision2) { + if (precision2 === "highp") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) { + return "highp"; + } + precision2 = "mediump"; + } + if (precision2 === "mediump") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) { + return "mediump"; + } + } + return "lowp"; + } + let precision = parameters.precision !== undefined ? parameters.precision : "highp"; + const maxPrecision = getMaxPrecision(precision); + if (maxPrecision !== precision) { + console.warn("THREE.WebGLRenderer:", precision, "not supported, using", maxPrecision, "instead."); + precision = maxPrecision; + } + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has("EXT_clip_control"); + const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); + const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); + const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); + const vertexTextures = maxVertexTextures > 0; + const maxSamples = gl.getParameter(gl.MAX_SAMPLES); + return { + isWebGL2: true, + getMaxAnisotropy, + getMaxPrecision, + textureFormatReadable, + textureTypeReadable, + precision, + logarithmicDepthBuffer, + reverseDepthBuffer, + maxTextures, + maxVertexTextures, + maxTextureSize, + maxCubemapSize, + maxAttributes, + maxVertexUniforms, + maxVaryings, + maxFragmentUniforms, + vertexTextures, + maxSamples + }; +} +function WebGLClipping(properties) { + const scope = this; + let globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false; + const plane = new Plane, viewNormalMatrix = new Matrix3, uniform = { value: null, needsUpdate: false }; + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + this.init = function(planes, enableLocalClipping) { + const enabled = planes.length !== 0 || enableLocalClipping || numGlobalPlanes !== 0 || localClippingEnabled; + localClippingEnabled = enableLocalClipping; + numGlobalPlanes = planes.length; + return enabled; + }; + this.beginShadows = function() { + renderingShadows = true; + projectPlanes(null); + }; + this.endShadows = function() { + renderingShadows = false; + }; + this.setGlobalState = function(planes, camera) { + globalState = projectPlanes(planes, camera, 0); + }; + this.setState = function(material, camera, useCache) { + const { clippingPlanes: planes, clipIntersection, clipShadows } = material; + const materialProperties = properties.get(material); + if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) { + if (renderingShadows) { + projectPlanes(null); + } else { + resetGlobalState(); + } + } else { + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4; + let dstArray = materialProperties.clippingState || null; + uniform.value = dstArray; + dstArray = projectPlanes(planes, camera, lGlobal, useCache); + for (let i = 0;i !== lGlobal; ++i) { + dstArray[i] = globalState[i]; + } + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + } + }; + function resetGlobalState() { + if (uniform.value !== globalState) { + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + } + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + } + function projectPlanes(planes, camera, dstOffset, skipTransform) { + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + if (nPlanes !== 0) { + dstArray = uniform.value; + if (skipTransform !== true || dstArray === null) { + const flatSize = dstOffset + nPlanes * 4, viewMatrix = camera.matrixWorldInverse; + viewNormalMatrix.getNormalMatrix(viewMatrix); + if (dstArray === null || dstArray.length < flatSize) { + dstArray = new Float32Array(flatSize); + } + for (let i = 0, i4 = dstOffset;i !== nPlanes; ++i, i4 += 4) { + plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix); + plane.normal.toArray(dstArray, i4); + dstArray[i4 + 3] = plane.constant; + } + } + uniform.value = dstArray; + uniform.needsUpdate = true; + } + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + return dstArray; + } +} +function WebGLCubeMaps(renderer2) { + let cubemaps = new WeakMap; + function mapTextureMapping(texture, mapping) { + if (mapping === EquirectangularReflectionMapping) { + texture.mapping = CubeReflectionMapping; + } else if (mapping === EquirectangularRefractionMapping) { + texture.mapping = CubeRefractionMapping; + } + return texture; + } + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) { + if (cubemaps.has(texture)) { + const cubemap = cubemaps.get(texture).texture; + return mapTextureMapping(cubemap, texture.mapping); + } else { + const image = texture.image; + if (image && image.height > 0) { + const renderTarget = new WebGLCubeRenderTarget(image.height); + renderTarget.fromEquirectangularTexture(renderer2, texture); + cubemaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return mapTextureMapping(renderTarget.texture, texture.mapping); + } else { + return null; + } + } + } + } + return texture; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemap = cubemaps.get(texture); + if (cubemap !== undefined) { + cubemaps.delete(texture); + cubemap.dispose(); + } + } + function dispose() { + cubemaps = new WeakMap; + } + return { + get, + dispose + }; +} +var LOD_MIN = 4; +var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; +var MAX_SAMPLES = 20; +var _flatCamera = /* @__PURE__ */ new OrthographicCamera; +var _clearColor = /* @__PURE__ */ new Color; +var _oldTarget = null; +var _oldActiveCubeFace = 0; +var _oldActiveMipmapLevel = 0; +var _oldXrEnabled = false; +var PHI = (1 + Math.sqrt(5)) / 2; +var INV_PHI = 1 / PHI; +var _axisDirections = [ + /* @__PURE__ */ new Vector3(-PHI, INV_PHI, 0), + /* @__PURE__ */ new Vector3(PHI, INV_PHI, 0), + /* @__PURE__ */ new Vector3(-INV_PHI, 0, PHI), + /* @__PURE__ */ new Vector3(INV_PHI, 0, PHI), + /* @__PURE__ */ new Vector3(0, PHI, -INV_PHI), + /* @__PURE__ */ new Vector3(0, PHI, INV_PHI), + /* @__PURE__ */ new Vector3(-1, 1, -1), + /* @__PURE__ */ new Vector3(1, 1, -1), + /* @__PURE__ */ new Vector3(-1, 1, 1), + /* @__PURE__ */ new Vector3(1, 1, 1) +]; + +class PMREMGenerator { + constructor(renderer2) { + this._renderer = renderer2; + this._pingPongRenderTarget = null; + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + this._compileMaterial(this._blurMaterial); + } + fromScene(scene, sigma = 0, near = 0.1, far = 100) { + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + this._setSize(256); + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget); + if (sigma > 0) { + this._blur(cubeUVRenderTarget, 0, 0, sigma); + } + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + fromEquirectangular(equirectangular, renderTarget = null) { + return this._fromTexture(equirectangular, renderTarget); + } + fromCubemap(cubemap, renderTarget = null) { + return this._fromTexture(cubemap, renderTarget); + } + compileCubemapShader() { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial(this._cubemapMaterial); + } + } + compileEquirectangularShader() { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial(this._equirectMaterial); + } + } + dispose() { + this._dispose(); + if (this._cubemapMaterial !== null) + this._cubemapMaterial.dispose(); + if (this._equirectMaterial !== null) + this._equirectMaterial.dispose(); + } + _setSize(cubeSize) { + this._lodMax = Math.floor(Math.log2(cubeSize)); + this._cubeSize = Math.pow(2, this._lodMax); + } + _dispose() { + if (this._blurMaterial !== null) + this._blurMaterial.dispose(); + if (this._pingPongRenderTarget !== null) + this._pingPongRenderTarget.dispose(); + for (let i = 0;i < this._lodPlanes.length; i++) { + this._lodPlanes[i].dispose(); + } + } + _cleanup(outputTarget) { + this._renderer.setRenderTarget(_oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel); + this._renderer.xr.enabled = _oldXrEnabled; + outputTarget.scissorTest = false; + _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height); + } + _fromTexture(texture, renderTarget) { + if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) { + this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width); + } else { + this._setSize(texture.image.width / 4); + } + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV(texture, cubeUVRenderTarget); + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + _allocateTargets() { + const width2 = 3 * Math.max(this._cubeSize, 16 * 7); + const height2 = 4 * this._cubeSize; + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + colorSpace: LinearSRGBColorSpace, + depthBuffer: false + }; + const cubeUVRenderTarget = _createRenderTarget(width2, height2, params); + if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width2 || this._pingPongRenderTarget.height !== height2) { + if (this._pingPongRenderTarget !== null) { + this._dispose(); + } + this._pingPongRenderTarget = _createRenderTarget(width2, height2, params); + const { _lodMax } = this; + ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes(_lodMax)); + this._blurMaterial = _getBlurShader(_lodMax, width2, height2); + } + return cubeUVRenderTarget; + } + _compileMaterial(material) { + const tmpMesh = new Mesh(this._lodPlanes[0], material); + this._renderer.compile(tmpMesh, _flatCamera); + } + _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) { + const fov2 = 90; + const aspect2 = 1; + const cubeCamera = new PerspectiveCamera(fov2, aspect2, near, far); + const upSign = [1, -1, 1, 1, 1, 1]; + const forwardSign = [1, 1, 1, -1, -1, -1]; + const renderer2 = this._renderer; + const originalAutoClear = renderer2.autoClear; + const toneMapping = renderer2.toneMapping; + renderer2.getClearColor(_clearColor); + renderer2.toneMapping = NoToneMapping; + renderer2.autoClear = false; + const backgroundMaterial = new MeshBasicMaterial({ + name: "PMREM.Background", + side: BackSide, + depthWrite: false, + depthTest: false + }); + const backgroundBox = new Mesh(new BoxGeometry, backgroundMaterial); + let useSolidColor = false; + const background = scene.background; + if (background) { + if (background.isColor) { + backgroundMaterial.color.copy(background); + scene.background = null; + useSolidColor = true; + } + } else { + backgroundMaterial.color.copy(_clearColor); + useSolidColor = true; + } + for (let i = 0;i < 6; i++) { + const col = i % 3; + if (col === 0) { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(forwardSign[i], 0, 0); + } else if (col === 1) { + cubeCamera.up.set(0, 0, upSign[i]); + cubeCamera.lookAt(0, forwardSign[i], 0); + } else { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(0, 0, forwardSign[i]); + } + const size = this._cubeSize; + _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size); + renderer2.setRenderTarget(cubeUVRenderTarget); + if (useSolidColor) { + renderer2.render(backgroundBox, cubeCamera); + } + renderer2.render(scene, cubeCamera); + } + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + renderer2.toneMapping = toneMapping; + renderer2.autoClear = originalAutoClear; + scene.background = background; + } + _textureToCubeUV(texture, cubeUVRenderTarget) { + const renderer2 = this._renderer; + const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping; + if (isCubeTexture) { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial(); + } + this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1; + } else { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial(); + } + } + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh(this._lodPlanes[0], material); + const uniforms = material.uniforms; + uniforms["envMap"].value = texture; + const size = this._cubeSize; + _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size); + renderer2.setRenderTarget(cubeUVRenderTarget); + renderer2.render(mesh, _flatCamera); + } + _applyPMREM(cubeUVRenderTarget) { + const renderer2 = this._renderer; + const autoClear = renderer2.autoClear; + renderer2.autoClear = false; + const n = this._lodPlanes.length; + for (let i = 1;i < n; i++) { + const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]); + const poleAxis = _axisDirections[(n - i - 1) % _axisDirections.length]; + this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis); + } + renderer2.autoClear = autoClear; + } + _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) { + const pingPongRenderTarget = this._pingPongRenderTarget; + this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, "latitudinal", poleAxis); + this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, "longitudinal", poleAxis); + } + _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) { + const renderer2 = this._renderer; + const blurMaterial = this._blurMaterial; + if (direction !== "latitudinal" && direction !== "longitudinal") { + console.error("blur direction must be either latitudinal or longitudinal!"); + } + const STANDARD_DEVIATIONS = 3; + const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial); + const blurUniforms = blurMaterial.uniforms; + const pixels = this._sizeLods[lodIn] - 1; + const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES; + if (samples > MAX_SAMPLES) { + console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`); + } + const weights = []; + let sum2 = 0; + for (let i = 0;i < MAX_SAMPLES; ++i) { + const x2 = i / sigmaPixels; + const weight = Math.exp(-x2 * x2 / 2); + weights.push(weight); + if (i === 0) { + sum2 += weight; + } else if (i < samples) { + sum2 += 2 * weight; + } + } + for (let i = 0;i < weights.length; i++) { + weights[i] = weights[i] / sum2; + } + blurUniforms["envMap"].value = targetIn.texture; + blurUniforms["samples"].value = samples; + blurUniforms["weights"].value = weights; + blurUniforms["latitudinal"].value = direction === "latitudinal"; + if (poleAxis) { + blurUniforms["poleAxis"].value = poleAxis; + } + const { _lodMax } = this; + blurUniforms["dTheta"].value = radiansPerPixel; + blurUniforms["mipInt"].value = _lodMax - lodIn; + const outputSize = this._sizeLods[lodOut]; + const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0); + const y = 4 * (this._cubeSize - outputSize); + _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize); + renderer2.setRenderTarget(targetOut); + renderer2.render(blurMesh, _flatCamera); + } +} +function _createPlanes(lodMax) { + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + let lod = lodMax; + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + for (let i = 0;i < totalLods; i++) { + const sizeLod = Math.pow(2, lod); + sizeLods.push(sizeLod); + let sigma = 1 / sizeLod; + if (i > lodMax - LOD_MIN) { + sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1]; + } else if (i === 0) { + sigma = 0; + } + sigmas.push(sigma); + const texelSize = 1 / (sizeLod - 2); + const min = -texelSize; + const max = 1 + texelSize; + const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max]; + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + const position2 = new Float32Array(positionSize * vertices * cubeFaces); + const uv = new Float32Array(uvSize * vertices * cubeFaces); + const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces); + for (let face = 0;face < cubeFaces; face++) { + const x = face % 3 * 2 / 3 - 1; + const y = face > 2 ? 0 : -1; + const coordinates = [ + x, + y, + 0, + x + 2 / 3, + y, + 0, + x + 2 / 3, + y + 1, + 0, + x, + y, + 0, + x + 2 / 3, + y + 1, + 0, + x, + y + 1, + 0 + ]; + position2.set(coordinates, positionSize * vertices * face); + uv.set(uv1, uvSize * vertices * face); + const fill2 = [face, face, face, face, face, face]; + faceIndex.set(fill2, faceIndexSize * vertices * face); + } + const planes = new BufferGeometry; + planes.setAttribute("position", new BufferAttribute(position2, positionSize)); + planes.setAttribute("uv", new BufferAttribute(uv, uvSize)); + planes.setAttribute("faceIndex", new BufferAttribute(faceIndex, faceIndexSize)); + lodPlanes.push(planes); + if (lod > LOD_MIN) { + lod--; + } + } + return { lodPlanes, sizeLods, sigmas }; +} +function _createRenderTarget(width2, height2, params) { + const cubeUVRenderTarget = new WebGLRenderTarget(width2, height2, params); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = "PMREM.cubeUv"; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; +} +function _setViewport(target, x, y, width2, height2) { + target.viewport.set(x, y, width2, height2); + target.scissor.set(x, y, width2, height2); +} +function _getBlurShader(lodMax, width2, height2) { + const weights = new Float32Array(MAX_SAMPLES); + const poleAxis = new Vector3(0, 1, 0); + const shaderMaterial = new ShaderMaterial({ + name: "SphericalGaussianBlur", + defines: { + n: MAX_SAMPLES, + CUBEUV_TEXEL_WIDTH: 1 / width2, + CUBEUV_TEXEL_HEIGHT: 1 / height2, + CUBEUV_MAX_MIP: `${lodMax}.0` + }, + uniforms: { + envMap: { value: null }, + samples: { value: 1 }, + weights: { value: weights }, + latitudinal: { value: false }, + dTheta: { value: 0 }, + mipInt: { value: 0 }, + poleAxis: { value: poleAxis } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + return shaderMaterial; +} +function _getEquirectMaterial() { + return new ShaderMaterial({ + name: "EquirectangularToCubeUV", + uniforms: { + envMap: { value: null } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); +} +function _getCubemapMaterial() { + return new ShaderMaterial({ + name: "CubemapToCubeUV", + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); +} +function _getCommonVertexShader() { + return ` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `; +} +function WebGLCubeUVMaps(renderer2) { + let cubeUVmaps = new WeakMap; + let pmremGenerator = null; + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping; + const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; + if (isEquirectMap || isCubeMap) { + let renderTarget = cubeUVmaps.get(texture); + const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0; + if (texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion) { + if (pmremGenerator === null) + pmremGenerator = new PMREMGenerator(renderer2); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + return renderTarget.texture; + } else { + if (renderTarget !== undefined) { + return renderTarget.texture; + } else { + const image = texture.image; + if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) { + if (pmremGenerator === null) + pmremGenerator = new PMREMGenerator(renderer2); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return renderTarget.texture; + } else { + return null; + } + } + } + } + } + return texture; + } + function isCubeTextureComplete(image) { + let count = 0; + const length2 = 6; + for (let i = 0;i < length2; i++) { + if (image[i] !== undefined) + count++; + } + return count === length2; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemapUV = cubeUVmaps.get(texture); + if (cubemapUV !== undefined) { + cubeUVmaps.delete(texture); + cubemapUV.dispose(); + } + } + function dispose() { + cubeUVmaps = new WeakMap; + if (pmremGenerator !== null) { + pmremGenerator.dispose(); + pmremGenerator = null; + } + } + return { + get, + dispose + }; +} +function WebGLExtensions(gl) { + const extensions = {}; + function getExtension(name2) { + if (extensions[name2] !== undefined) { + return extensions[name2]; + } + let extension; + switch (name2) { + case "WEBGL_depth_texture": + extension = gl.getExtension("WEBGL_depth_texture") || gl.getExtension("MOZ_WEBGL_depth_texture") || gl.getExtension("WEBKIT_WEBGL_depth_texture"); + break; + case "EXT_texture_filter_anisotropic": + extension = gl.getExtension("EXT_texture_filter_anisotropic") || gl.getExtension("MOZ_EXT_texture_filter_anisotropic") || gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic"); + break; + case "WEBGL_compressed_texture_s3tc": + extension = gl.getExtension("WEBGL_compressed_texture_s3tc") || gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"); + break; + case "WEBGL_compressed_texture_pvrtc": + extension = gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"); + break; + default: + extension = gl.getExtension(name2); + } + extensions[name2] = extension; + return extension; + } + return { + has: function(name2) { + return getExtension(name2) !== null; + }, + init: function() { + getExtension("EXT_color_buffer_float"); + getExtension("WEBGL_clip_cull_distance"); + getExtension("OES_texture_float_linear"); + getExtension("EXT_color_buffer_half_float"); + getExtension("WEBGL_multisampled_render_to_texture"); + getExtension("WEBGL_render_shared_exponent"); + }, + get: function(name2) { + const extension = getExtension(name2); + if (extension === null) { + warnOnce("THREE.WebGLRenderer: " + name2 + " extension not supported."); + } + return extension; + } + }; +} +function WebGLGeometries(gl, attributes, info, bindingStates) { + const geometries = {}; + const wireframeAttributes = new WeakMap; + function onGeometryDispose(event) { + const geometry = event.target; + if (geometry.index !== null) { + attributes.remove(geometry.index); + } + for (const name2 in geometry.attributes) { + attributes.remove(geometry.attributes[name2]); + } + geometry.removeEventListener("dispose", onGeometryDispose); + delete geometries[geometry.id]; + const attribute = wireframeAttributes.get(geometry); + if (attribute) { + attributes.remove(attribute); + wireframeAttributes.delete(geometry); + } + bindingStates.releaseStatesOfGeometry(geometry); + if (geometry.isInstancedBufferGeometry === true) { + delete geometry._maxInstanceCount; + } + info.memory.geometries--; + } + function get(object, geometry) { + if (geometries[geometry.id] === true) + return geometry; + geometry.addEventListener("dispose", onGeometryDispose); + geometries[geometry.id] = true; + info.memory.geometries++; + return geometry; + } + function update(geometry) { + const geometryAttributes = geometry.attributes; + for (const name2 in geometryAttributes) { + attributes.update(geometryAttributes[name2], gl.ARRAY_BUFFER); + } + } + function updateWireframeAttribute(geometry) { + const indices = []; + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + if (geometryIndex !== null) { + const array = geometryIndex.array; + version = geometryIndex.version; + for (let i = 0, l = array.length;i < l; i += 3) { + const a = array[i + 0]; + const b = array[i + 1]; + const c = array[i + 2]; + indices.push(a, b, b, c, c, a); + } + } else if (geometryPosition !== undefined) { + const array = geometryPosition.array; + version = geometryPosition.version; + for (let i = 0, l = array.length / 3 - 1;i < l; i += 3) { + const a = i + 0; + const b = i + 1; + const c = i + 2; + indices.push(a, b, b, c, c, a); + } + } else { + return; + } + const attribute = new ((arrayNeedsUint32(indices)) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1); + attribute.version = version; + const previousAttribute = wireframeAttributes.get(geometry); + if (previousAttribute) + attributes.remove(previousAttribute); + wireframeAttributes.set(geometry, attribute); + } + function getWireframeAttribute(geometry) { + const currentAttribute = wireframeAttributes.get(geometry); + if (currentAttribute) { + const geometryIndex = geometry.index; + if (geometryIndex !== null) { + if (currentAttribute.version < geometryIndex.version) { + updateWireframeAttribute(geometry); + } + } + } else { + updateWireframeAttribute(geometry); + } + return wireframeAttributes.get(geometry); + } + return { + get, + update, + getWireframeAttribute + }; +} +function WebGLIndexedBufferRenderer(gl, extensions, info) { + let mode; + function setMode(value2) { + mode = value2; + } + let type, bytesPerElement; + function setIndex(value2) { + type = value2.type; + bytesPerElement = value2.bytesPerElement; + } + function render(start, count) { + gl.drawElements(mode, count, type, start * bytesPerElement); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) + return; + gl.drawElementsInstanced(mode, count, type, start * bytesPerElement, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawElementsWEBGL(mode, counts, 0, type, starts, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0;i < starts.length; i++) { + renderInstances(starts[i] / bytesPerElement, counts[i], primcount[i]); + } + } else { + extension.multiDrawElementsInstancedWEBGL(mode, counts, 0, type, starts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i] * primcount[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; +} +function WebGLInfo(gl) { + const memory = { + geometries: 0, + textures: 0 + }; + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + function update(count, mode, instanceCount) { + render.calls++; + switch (mode) { + case gl.TRIANGLES: + render.triangles += instanceCount * (count / 3); + break; + case gl.LINES: + render.lines += instanceCount * (count / 2); + break; + case gl.LINE_STRIP: + render.lines += instanceCount * (count - 1); + break; + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + case gl.POINTS: + render.points += instanceCount * count; + break; + default: + console.error("THREE.WebGLInfo: Unknown draw mode:", mode); + break; + } + } + function reset() { + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + } + return { + memory, + render, + programs: null, + autoReset: true, + reset, + update + }; +} +function WebGLMorphtargets(gl, capabilities, textures) { + const morphTextures = new WeakMap; + const morph = new Vector4; + function update(object, geometry, program) { + const objectInfluences = object.morphTargetInfluences; + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + let entry = morphTextures.get(geometry); + if (entry === undefined || entry.count !== morphTargetsCount) { + let disposeTexture = function() { + texture.dispose(); + morphTextures.delete(geometry); + geometry.removeEventListener("dispose", disposeTexture); + }; + if (entry !== undefined) + entry.texture.dispose(); + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + let vertexDataCount = 0; + if (hasMorphPosition === true) + vertexDataCount = 1; + if (hasMorphNormals === true) + vertexDataCount = 2; + if (hasMorphColors === true) + vertexDataCount = 3; + let width2 = geometry.attributes.position.count * vertexDataCount; + let height2 = 1; + if (width2 > capabilities.maxTextureSize) { + height2 = Math.ceil(width2 / capabilities.maxTextureSize); + width2 = capabilities.maxTextureSize; + } + const buffer = new Float32Array(width2 * height2 * 4 * morphTargetsCount); + const texture = new DataArrayTexture(buffer, width2, height2, morphTargetsCount); + texture.type = FloatType; + texture.needsUpdate = true; + const vertexDataStride = vertexDataCount * 4; + for (let i = 0;i < morphTargetsCount; i++) { + const morphTarget = morphTargets[i]; + const morphNormal = morphNormals[i]; + const morphColor = morphColors[i]; + const offset = width2 * height2 * 4 * i; + for (let j = 0;j < morphTarget.count; j++) { + const stride = j * vertexDataStride; + if (hasMorphPosition === true) { + morph.fromBufferAttribute(morphTarget, j); + buffer[offset + stride + 0] = morph.x; + buffer[offset + stride + 1] = morph.y; + buffer[offset + stride + 2] = morph.z; + buffer[offset + stride + 3] = 0; + } + if (hasMorphNormals === true) { + morph.fromBufferAttribute(morphNormal, j); + buffer[offset + stride + 4] = morph.x; + buffer[offset + stride + 5] = morph.y; + buffer[offset + stride + 6] = morph.z; + buffer[offset + stride + 7] = 0; + } + if (hasMorphColors === true) { + morph.fromBufferAttribute(morphColor, j); + buffer[offset + stride + 8] = morph.x; + buffer[offset + stride + 9] = morph.y; + buffer[offset + stride + 10] = morph.z; + buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1; + } + } + } + entry = { + count: morphTargetsCount, + texture, + size: new Vector2(width2, height2) + }; + morphTextures.set(geometry, entry); + geometry.addEventListener("dispose", disposeTexture); + } + if (object.isInstancedMesh === true && object.morphTexture !== null) { + program.getUniforms().setValue(gl, "morphTexture", object.morphTexture, textures); + } else { + let morphInfluencesSum = 0; + for (let i = 0;i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence); + program.getUniforms().setValue(gl, "morphTargetInfluences", objectInfluences); + } + program.getUniforms().setValue(gl, "morphTargetsTexture", entry.texture, textures); + program.getUniforms().setValue(gl, "morphTargetsTextureSize", entry.size); + } + return { + update + }; +} +function WebGLObjects(gl, geometries, attributes, info) { + let updateMap = new WeakMap; + function update(object) { + const frame = info.render.frame; + const geometry = object.geometry; + const buffergeometry = geometries.get(object, geometry); + if (updateMap.get(buffergeometry) !== frame) { + geometries.update(buffergeometry); + updateMap.set(buffergeometry, frame); + } + if (object.isInstancedMesh) { + if (object.hasEventListener("dispose", onInstancedMeshDispose) === false) { + object.addEventListener("dispose", onInstancedMeshDispose); + } + if (updateMap.get(object) !== frame) { + attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER); + if (object.instanceColor !== null) { + attributes.update(object.instanceColor, gl.ARRAY_BUFFER); + } + updateMap.set(object, frame); + } + } + if (object.isSkinnedMesh) { + const skeleton = object.skeleton; + if (updateMap.get(skeleton) !== frame) { + skeleton.update(); + updateMap.set(skeleton, frame); + } + } + return buffergeometry; + } + function dispose() { + updateMap = new WeakMap; + } + function onInstancedMeshDispose(event) { + const instancedMesh = event.target; + instancedMesh.removeEventListener("dispose", onInstancedMeshDispose); + attributes.remove(instancedMesh.instanceMatrix); + if (instancedMesh.instanceColor !== null) + attributes.remove(instancedMesh.instanceColor); + } + return { + update, + dispose + }; +} +var emptyTexture = /* @__PURE__ */ new Texture; +var emptyShadowTexture = /* @__PURE__ */ new DepthTexture(1, 1); +var emptyArrayTexture = /* @__PURE__ */ new DataArrayTexture; +var empty3dTexture = /* @__PURE__ */ new Data3DTexture; +var emptyCubeTexture = /* @__PURE__ */ new CubeTexture; +var arrayCacheF32 = []; +var arrayCacheI32 = []; +var mat4array = new Float32Array(16); +var mat3array = new Float32Array(9); +var mat2array = new Float32Array(4); +function flatten2(array, nBlocks, blockSize) { + const firstElem = array[0]; + if (firstElem <= 0 || firstElem > 0) + return array; + const n = nBlocks * blockSize; + let r = arrayCacheF32[n]; + if (r === undefined) { + r = new Float32Array(n); + arrayCacheF32[n] = r; + } + if (nBlocks !== 0) { + firstElem.toArray(r, 0); + for (let i = 1, offset = 0;i !== nBlocks; ++i) { + offset += blockSize; + array[i].toArray(r, offset); + } + } + return r; +} +function arraysEqual(a, b) { + if (a.length !== b.length) + return false; + for (let i = 0, l = a.length;i < l; i++) { + if (a[i] !== b[i]) + return false; + } + return true; +} +function copyArray(a, b) { + for (let i = 0, l = b.length;i < l; i++) { + a[i] = b[i]; + } +} +function allocTexUnits(textures, n) { + let r = arrayCacheI32[n]; + if (r === undefined) { + r = new Int32Array(n); + arrayCacheI32[n] = r; + } + for (let i = 0;i !== n; ++i) { + r[i] = textures.allocateTextureUnit(); + } + return r; +} +function setValueV1f(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1f(this.addr, v); + cache[0] = v; +} +function setValueV2f(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2f(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform2fv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV3f(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3f(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else if (v.r !== undefined) { + if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) { + gl.uniform3f(this.addr, v.r, v.g, v.b); + cache[0] = v.r; + cache[1] = v.g; + cache[2] = v.b; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform3fv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV4f(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4f(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform4fv(this.addr, v); + copyArray(cache, v); + } +} +function setValueM2(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual(cache, v)) + return; + gl.uniformMatrix2fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) + return; + mat2array.set(elements); + gl.uniformMatrix2fv(this.addr, false, mat2array); + copyArray(cache, elements); + } +} +function setValueM3(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual(cache, v)) + return; + gl.uniformMatrix3fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) + return; + mat3array.set(elements); + gl.uniformMatrix3fv(this.addr, false, mat3array); + copyArray(cache, elements); + } +} +function setValueM4(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual(cache, v)) + return; + gl.uniformMatrix4fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) + return; + mat4array.set(elements); + gl.uniformMatrix4fv(this.addr, false, mat4array); + copyArray(cache, elements); + } +} +function setValueV1i(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1i(this.addr, v); + cache[0] = v; +} +function setValueV2i(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2i(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform2iv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV3i(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3i(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform3iv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV4i(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4i(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform4iv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV1ui(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1ui(this.addr, v); + cache[0] = v; +} +function setValueV2ui(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2ui(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform2uiv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV3ui(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3ui(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform3uiv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV4ui(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4ui(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform4uiv(this.addr, v); + copyArray(cache, v); + } +} +function setValueT1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + let emptyTexture2D; + if (this.type === gl.SAMPLER_2D_SHADOW) { + emptyShadowTexture.compareFunction = LessEqualCompare; + emptyTexture2D = emptyShadowTexture; + } else { + emptyTexture2D = emptyTexture; + } + textures.setTexture2D(v || emptyTexture2D, unit); +} +function setValueT3D1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture3D(v || empty3dTexture, unit); +} +function setValueT6(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTextureCube(v || emptyCubeTexture, unit); +} +function setValueT2DArray1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture2DArray(v || emptyArrayTexture, unit); +} +function getSingularSetter(type) { + switch (type) { + case 5126: + return setValueV1f; + case 35664: + return setValueV2f; + case 35665: + return setValueV3f; + case 35666: + return setValueV4f; + case 35674: + return setValueM2; + case 35675: + return setValueM3; + case 35676: + return setValueM4; + case 5124: + case 35670: + return setValueV1i; + case 35667: + case 35671: + return setValueV2i; + case 35668: + case 35672: + return setValueV3i; + case 35669: + case 35673: + return setValueV4i; + case 5125: + return setValueV1ui; + case 36294: + return setValueV2ui; + case 36295: + return setValueV3ui; + case 36296: + return setValueV4ui; + case 35678: + case 36198: + case 36298: + case 36306: + case 35682: + return setValueT1; + case 35679: + case 36299: + case 36307: + return setValueT3D1; + case 35680: + case 36300: + case 36308: + case 36293: + return setValueT6; + case 36289: + case 36303: + case 36311: + case 36292: + return setValueT2DArray1; + } +} +function setValueV1fArray(gl, v) { + gl.uniform1fv(this.addr, v); +} +function setValueV2fArray(gl, v) { + const data2 = flatten2(v, this.size, 2); + gl.uniform2fv(this.addr, data2); +} +function setValueV3fArray(gl, v) { + const data2 = flatten2(v, this.size, 3); + gl.uniform3fv(this.addr, data2); +} +function setValueV4fArray(gl, v) { + const data2 = flatten2(v, this.size, 4); + gl.uniform4fv(this.addr, data2); +} +function setValueM2Array(gl, v) { + const data2 = flatten2(v, this.size, 4); + gl.uniformMatrix2fv(this.addr, false, data2); +} +function setValueM3Array(gl, v) { + const data2 = flatten2(v, this.size, 9); + gl.uniformMatrix3fv(this.addr, false, data2); +} +function setValueM4Array(gl, v) { + const data2 = flatten2(v, this.size, 16); + gl.uniformMatrix4fv(this.addr, false, data2); +} +function setValueV1iArray(gl, v) { + gl.uniform1iv(this.addr, v); +} +function setValueV2iArray(gl, v) { + gl.uniform2iv(this.addr, v); +} +function setValueV3iArray(gl, v) { + gl.uniform3iv(this.addr, v); +} +function setValueV4iArray(gl, v) { + gl.uniform4iv(this.addr, v); +} +function setValueV1uiArray(gl, v) { + gl.uniform1uiv(this.addr, v); +} +function setValueV2uiArray(gl, v) { + gl.uniform2uiv(this.addr, v); +} +function setValueV3uiArray(gl, v) { + gl.uniform3uiv(this.addr, v); +} +function setValueV4uiArray(gl, v) { + gl.uniform4uiv(this.addr, v); +} +function setValueT1Array(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTexture2D(v[i] || emptyTexture, units[i]); + } +} +function setValueT3DArray(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTexture3D(v[i] || empty3dTexture, units[i]); + } +} +function setValueT6Array(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTextureCube(v[i] || emptyCubeTexture, units[i]); + } +} +function setValueT2DArrayArray(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]); + } +} +function getPureArraySetter(type) { + switch (type) { + case 5126: + return setValueV1fArray; + case 35664: + return setValueV2fArray; + case 35665: + return setValueV3fArray; + case 35666: + return setValueV4fArray; + case 35674: + return setValueM2Array; + case 35675: + return setValueM3Array; + case 35676: + return setValueM4Array; + case 5124: + case 35670: + return setValueV1iArray; + case 35667: + case 35671: + return setValueV2iArray; + case 35668: + case 35672: + return setValueV3iArray; + case 35669: + case 35673: + return setValueV4iArray; + case 5125: + return setValueV1uiArray; + case 36294: + return setValueV2uiArray; + case 36295: + return setValueV3uiArray; + case 36296: + return setValueV4uiArray; + case 35678: + case 36198: + case 36298: + case 36306: + case 35682: + return setValueT1Array; + case 35679: + case 36299: + case 36307: + return setValueT3DArray; + case 35680: + case 36300: + case 36308: + case 36293: + return setValueT6Array; + case 36289: + case 36303: + case 36311: + case 36292: + return setValueT2DArrayArray; + } +} + +class SingleUniform { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.setValue = getSingularSetter(activeInfo.type); + } +} + +class PureArrayUniform { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.size = activeInfo.size; + this.setValue = getPureArraySetter(activeInfo.type); + } +} + +class StructuredUniform { + constructor(id) { + this.id = id; + this.seq = []; + this.map = {}; + } + setValue(gl, value2, textures) { + const seq = this.seq; + for (let i = 0, n = seq.length;i !== n; ++i) { + const u = seq[i]; + u.setValue(gl, value2[u.id], textures); + } + } +} +var RePathPart = /(\w+)(\])?(\[|\.)?/g; +function addUniform(container, uniformObject) { + container.seq.push(uniformObject); + container.map[uniformObject.id] = uniformObject; +} +function parseUniform(activeInfo, addr, container) { + const path = activeInfo.name, pathLength = path.length; + RePathPart.lastIndex = 0; + while (true) { + const match = RePathPart.exec(path), matchEnd = RePathPart.lastIndex; + let id = match[1]; + const idIsIndex = match[2] === "]", subscript = match[3]; + if (idIsIndex) + id = id | 0; + if (subscript === undefined || subscript === "[" && matchEnd + 2 === pathLength) { + addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr)); + break; + } else { + const map2 = container.map; + let next = map2[id]; + if (next === undefined) { + next = new StructuredUniform(id); + addUniform(container, next); + } + container = next; + } + } +} + +class WebGLUniforms { + constructor(gl, program) { + this.seq = []; + this.map = {}; + const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (let i = 0;i < n; ++i) { + const info = gl.getActiveUniform(program, i), addr = gl.getUniformLocation(program, info.name); + parseUniform(info, addr, this); + } + } + setValue(gl, name2, value2, textures) { + const u = this.map[name2]; + if (u !== undefined) + u.setValue(gl, value2, textures); + } + setOptional(gl, object, name2) { + const v = object[name2]; + if (v !== undefined) + this.setValue(gl, name2, v); + } + static upload(gl, seq, values2, textures) { + for (let i = 0, n = seq.length;i !== n; ++i) { + const u = seq[i], v = values2[u.id]; + if (v.needsUpdate !== false) { + u.setValue(gl, v.value, textures); + } + } + } + static seqWithValue(seq, values2) { + const r = []; + for (let i = 0, n = seq.length;i !== n; ++i) { + const u = seq[i]; + if (u.id in values2) + r.push(u); + } + return r; + } +} +function WebGLShader(gl, type, string) { + const shader = gl.createShader(type); + gl.shaderSource(shader, string); + gl.compileShader(shader); + return shader; +} +var COMPLETION_STATUS_KHR = 37297; +var programIdCount = 0; +function handleSource(string, errorLine) { + const lines = string.split(` +`); + const lines2 = []; + const from = Math.max(errorLine - 6, 0); + const to = Math.min(errorLine + 6, lines.length); + for (let i = from;i < to; i++) { + const line = i + 1; + lines2.push(`${line === errorLine ? ">" : " "} ${line}: ${lines[i]}`); + } + return lines2.join(` +`); +} +var _m0 = /* @__PURE__ */ new Matrix3; +function getEncodingComponents(colorSpace) { + ColorManagement._getMatrix(_m0, ColorManagement.workingColorSpace, colorSpace); + const encodingMatrix = `mat3( ${_m0.elements.map((v) => v.toFixed(4))} )`; + switch (ColorManagement.getTransfer(colorSpace)) { + case LinearTransfer: + return [encodingMatrix, "LinearTransferOETF"]; + case SRGBTransfer: + return [encodingMatrix, "sRGBTransferOETF"]; + default: + console.warn("THREE.WebGLProgram: Unsupported color space: ", colorSpace); + return [encodingMatrix, "LinearTransferOETF"]; + } +} +function getShaderErrors(gl, shader, type) { + const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS); + const errors = gl.getShaderInfoLog(shader).trim(); + if (status && errors === "") + return ""; + const errorMatches = /ERROR: 0:(\d+)/.exec(errors); + if (errorMatches) { + const errorLine = parseInt(errorMatches[1]); + return type.toUpperCase() + ` + +` + errors + ` + +` + handleSource(gl.getShaderSource(shader), errorLine); + } else { + return errors; + } +} +function getTexelEncodingFunction(functionName, colorSpace) { + const components = getEncodingComponents(colorSpace); + return [ + `vec4 ${functionName}( vec4 value ) {`, + ` return ${components[1]}( vec4( value.rgb * ${components[0]}, value.a ) );`, + "}" + ].join(` +`); +} +function getToneMappingFunction(functionName, toneMapping) { + let toneMappingName; + switch (toneMapping) { + case LinearToneMapping: + toneMappingName = "Linear"; + break; + case ReinhardToneMapping: + toneMappingName = "Reinhard"; + break; + case CineonToneMapping: + toneMappingName = "Cineon"; + break; + case ACESFilmicToneMapping: + toneMappingName = "ACESFilmic"; + break; + case AgXToneMapping: + toneMappingName = "AgX"; + break; + case NeutralToneMapping: + toneMappingName = "Neutral"; + break; + case CustomToneMapping: + toneMappingName = "Custom"; + break; + default: + console.warn("THREE.WebGLProgram: Unsupported toneMapping:", toneMapping); + toneMappingName = "Linear"; + } + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; +} +var _v02 = /* @__PURE__ */ new Vector3; +function getLuminanceFunction() { + ColorManagement.getLuminanceCoefficients(_v02); + const r = _v02.x.toFixed(4); + const g = _v02.y.toFixed(4); + const b = _v02.z.toFixed(4); + return [ + "float luminance( const in vec3 rgb ) {", + ` const vec3 weights = vec3( ${r}, ${g}, ${b} );`, + "\treturn dot( weights, rgb );", + "}" + ].join(` +`); +} +function generateVertexExtensions(parameters) { + const chunks = [ + parameters.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "", + parameters.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : "" + ]; + return chunks.filter(filterEmptyLine).join(` +`); +} +function generateDefines(defines) { + const chunks = []; + for (const name2 in defines) { + const value2 = defines[name2]; + if (value2 === false) + continue; + chunks.push("#define " + name2 + " " + value2); + } + return chunks.join(` +`); +} +function fetchAttributeLocations(gl, program) { + const attributes = {}; + const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (let i = 0;i < n; i++) { + const info = gl.getActiveAttrib(program, i); + const name2 = info.name; + let locationSize = 1; + if (info.type === gl.FLOAT_MAT2) + locationSize = 2; + if (info.type === gl.FLOAT_MAT3) + locationSize = 3; + if (info.type === gl.FLOAT_MAT4) + locationSize = 4; + attributes[name2] = { + type: info.type, + location: gl.getAttribLocation(program, name2), + locationSize + }; + } + return attributes; +} +function filterEmptyLine(string) { + return string !== ""; +} +function replaceLightNums(string, parameters) { + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows); +} +function replaceClippingPlaneNums(string, parameters) { + return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection); +} +var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; +function resolveIncludes(string) { + return string.replace(includePattern, includeReplacer); +} +var shaderChunkMap = new Map; +function includeReplacer(match, include) { + let string = ShaderChunk[include]; + if (string === undefined) { + const newInclude = shaderChunkMap.get(include); + if (newInclude !== undefined) { + string = ShaderChunk[newInclude]; + console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude); + } else { + throw new Error("Can not resolve #include <" + include + ">"); + } + } + return resolveIncludes(string); +} +var unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; +function unrollLoops(string) { + return string.replace(unrollLoopPattern, loopReplacer); +} +function loopReplacer(match, start, end, snippet) { + let string = ""; + for (let i = parseInt(start);i < parseInt(end); i++) { + string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i + " ]").replace(/UNROLLED_LOOP_INDEX/g, i); + } + return string; +} +function generatePrecision(parameters) { + let precisionstring = `precision ${parameters.precision} float; + precision ${parameters.precision} int; + precision ${parameters.precision} sampler2D; + precision ${parameters.precision} samplerCube; + precision ${parameters.precision} sampler3D; + precision ${parameters.precision} sampler2DArray; + precision ${parameters.precision} sampler2DShadow; + precision ${parameters.precision} samplerCubeShadow; + precision ${parameters.precision} sampler2DArrayShadow; + precision ${parameters.precision} isampler2D; + precision ${parameters.precision} isampler3D; + precision ${parameters.precision} isamplerCube; + precision ${parameters.precision} isampler2DArray; + precision ${parameters.precision} usampler2D; + precision ${parameters.precision} usampler3D; + precision ${parameters.precision} usamplerCube; + precision ${parameters.precision} usampler2DArray; + `; + if (parameters.precision === "highp") { + precisionstring += ` +#define HIGH_PRECISION`; + } else if (parameters.precision === "mediump") { + precisionstring += ` +#define MEDIUM_PRECISION`; + } else if (parameters.precision === "lowp") { + precisionstring += ` +#define LOW_PRECISION`; + } + return precisionstring; +} +function generateShadowMapTypeDefine(parameters) { + let shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; + if (parameters.shadowMapType === PCFShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; + } else if (parameters.shadowMapType === PCFSoftShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; + } else if (parameters.shadowMapType === VSMShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_VSM"; + } + return shadowMapTypeDefine; +} +function generateEnvMapTypeDefine(parameters) { + let envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + break; + case CubeUVReflectionMapping: + envMapTypeDefine = "ENVMAP_TYPE_CUBE_UV"; + break; + } + } + return envMapTypeDefine; +} +function generateEnvMapModeDefine(parameters) { + let envMapModeDefine = "ENVMAP_MODE_REFLECTION"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeRefractionMapping: + envMapModeDefine = "ENVMAP_MODE_REFRACTION"; + break; + } + } + return envMapModeDefine; +} +function generateEnvMapBlendingDefine(parameters) { + let envMapBlendingDefine = "ENVMAP_BLENDING_NONE"; + if (parameters.envMap) { + switch (parameters.combine) { + case MultiplyOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_MULTIPLY"; + break; + case MixOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_MIX"; + break; + case AddOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_ADD"; + break; + } + } + return envMapBlendingDefine; +} +function generateCubeUVSize(parameters) { + const imageHeight = parameters.envMapCubeUVHeight; + if (imageHeight === null) + return null; + const maxMip = Math.log2(imageHeight) - 2; + const texelHeight = 1 / imageHeight; + const texelWidth = 1 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16)); + return { texelWidth, texelHeight, maxMip }; +} +function WebGLProgram(renderer2, cacheKey, parameters, bindingStates) { + const gl = renderer2.getContext(); + const defines = parameters.defines; + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters); + const envMapTypeDefine = generateEnvMapTypeDefine(parameters); + const envMapModeDefine = generateEnvMapModeDefine(parameters); + const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters); + const envMapCubeUVSize = generateCubeUVSize(parameters); + const customVertexExtensions = generateVertexExtensions(parameters); + const customDefines = generateDefines(defines); + const program = gl.createProgram(); + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? "#version " + parameters.glslVersion + ` +` : ""; + if (parameters.isRawShaderMaterial) { + prefixVertex = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine).join(` +`); + if (prefixVertex.length > 0) { + prefixVertex += ` +`; + } + prefixFragment = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine).join(` +`); + if (prefixFragment.length > 0) { + prefixFragment += ` +`; + } + } else { + prefixVertex = [ + generatePrecision(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "", + parameters.batching ? "#define USE_BATCHING" : "", + parameters.batchingColor ? "#define USE_BATCHING_COLOR" : "", + parameters.instancing ? "#define USE_INSTANCING" : "", + parameters.instancingColor ? "#define USE_INSTANCING_COLOR" : "", + parameters.instancingMorph ? "#define USE_INSTANCING_MORPH" : "", + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.displacementMap ? "#define USE_DISPLACEMENTMAP" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.mapUv ? "#define MAP_UV " + parameters.mapUv : "", + parameters.alphaMapUv ? "#define ALPHAMAP_UV " + parameters.alphaMapUv : "", + parameters.lightMapUv ? "#define LIGHTMAP_UV " + parameters.lightMapUv : "", + parameters.aoMapUv ? "#define AOMAP_UV " + parameters.aoMapUv : "", + parameters.emissiveMapUv ? "#define EMISSIVEMAP_UV " + parameters.emissiveMapUv : "", + parameters.bumpMapUv ? "#define BUMPMAP_UV " + parameters.bumpMapUv : "", + parameters.normalMapUv ? "#define NORMALMAP_UV " + parameters.normalMapUv : "", + parameters.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + parameters.displacementMapUv : "", + parameters.metalnessMapUv ? "#define METALNESSMAP_UV " + parameters.metalnessMapUv : "", + parameters.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + parameters.roughnessMapUv : "", + parameters.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + parameters.anisotropyMapUv : "", + parameters.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + parameters.clearcoatMapUv : "", + parameters.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + parameters.clearcoatNormalMapUv : "", + parameters.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + parameters.clearcoatRoughnessMapUv : "", + parameters.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + parameters.iridescenceMapUv : "", + parameters.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + parameters.iridescenceThicknessMapUv : "", + parameters.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + parameters.sheenColorMapUv : "", + parameters.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + parameters.sheenRoughnessMapUv : "", + parameters.specularMapUv ? "#define SPECULARMAP_UV " + parameters.specularMapUv : "", + parameters.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + parameters.specularColorMapUv : "", + parameters.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + parameters.specularIntensityMapUv : "", + parameters.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + parameters.transmissionMapUv : "", + parameters.thicknessMapUv ? "#define THICKNESSMAP_UV " + parameters.thicknessMapUv : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.skinning ? "#define USE_SKINNING" : "", + parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", + parameters.morphNormals && parameters.flatShading === false ? "#define USE_MORPHNORMALS" : "", + parameters.morphColors ? "#define USE_MORPHCOLORS" : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + parameters.morphTextureStride : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + parameters.morphTargetsCount : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "", + "uniform mat4 modelMatrix;", + "uniform mat4 modelViewMatrix;", + "uniform mat4 projectionMatrix;", + "uniform mat4 viewMatrix;", + "uniform mat3 normalMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + "#ifdef USE_INSTANCING", + "\tattribute mat4 instanceMatrix;", + "#endif", + "#ifdef USE_INSTANCING_COLOR", + "\tattribute vec3 instanceColor;", + "#endif", + "#ifdef USE_INSTANCING_MORPH", + "\tuniform sampler2D morphTexture;", + "#endif", + "attribute vec3 position;", + "attribute vec3 normal;", + "attribute vec2 uv;", + "#ifdef USE_UV1", + "\tattribute vec2 uv1;", + "#endif", + "#ifdef USE_UV2", + "\tattribute vec2 uv2;", + "#endif", + "#ifdef USE_UV3", + "\tattribute vec2 uv3;", + "#endif", + "#ifdef USE_TANGENT", + "\tattribute vec4 tangent;", + "#endif", + "#if defined( USE_COLOR_ALPHA )", + "\tattribute vec4 color;", + "#elif defined( USE_COLOR )", + "\tattribute vec3 color;", + "#endif", + "#ifdef USE_SKINNING", + "\tattribute vec4 skinIndex;", + "\tattribute vec4 skinWeight;", + "#endif", + ` +` + ].filter(filterEmptyLine).join(` +`); + prefixFragment = [ + generatePrecision(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.matcap ? "#define USE_MATCAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapTypeDefine : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.envMap ? "#define " + envMapBlendingDefine : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_WIDTH " + envMapCubeUVSize.texelWidth : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_HEIGHT " + envMapCubeUVSize.texelHeight : "", + envMapCubeUVSize ? "#define CUBEUV_MAX_MIP " + envMapCubeUVSize.maxMip + ".0" : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoat ? "#define USE_CLEARCOAT" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.dispersion ? "#define USE_DISPERSION" : "", + parameters.iridescence ? "#define USE_IRIDESCENCE" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaTest ? "#define USE_ALPHATEST" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.sheen ? "#define USE_SHEEN" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.gradientMap ? "#define USE_GRADIENTMAP" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", + parameters.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "", + "uniform mat4 viewMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + parameters.toneMapping !== NoToneMapping ? "#define TONE_MAPPING" : "", + parameters.toneMapping !== NoToneMapping ? ShaderChunk["tonemapping_pars_fragment"] : "", + parameters.toneMapping !== NoToneMapping ? getToneMappingFunction("toneMapping", parameters.toneMapping) : "", + parameters.dithering ? "#define DITHERING" : "", + parameters.opaque ? "#define OPAQUE" : "", + ShaderChunk["colorspace_pars_fragment"], + getTexelEncodingFunction("linearToOutputTexel", parameters.outputColorSpace), + getLuminanceFunction(), + parameters.useDepthPacking ? "#define DEPTH_PACKING " + parameters.depthPacking : "", + ` +` + ].filter(filterEmptyLine).join(` +`); + } + vertexShader = resolveIncludes(vertexShader); + vertexShader = replaceLightNums(vertexShader, parameters); + vertexShader = replaceClippingPlaneNums(vertexShader, parameters); + fragmentShader = resolveIncludes(fragmentShader); + fragmentShader = replaceLightNums(fragmentShader, parameters); + fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters); + vertexShader = unrollLoops(vertexShader); + fragmentShader = unrollLoops(fragmentShader); + if (parameters.isRawShaderMaterial !== true) { + versionString = `#version 300 es +`; + prefixVertex = [ + customVertexExtensions, + "#define attribute in", + "#define varying out", + "#define texture2D texture" + ].join(` +`) + ` +` + prefixVertex; + prefixFragment = [ + "#define varying in", + parameters.glslVersion === GLSL3 ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", + parameters.glslVersion === GLSL3 ? "" : "#define gl_FragColor pc_fragColor", + "#define gl_FragDepthEXT gl_FragDepth", + "#define texture2D texture", + "#define textureCube texture", + "#define texture2DProj textureProj", + "#define texture2DLodEXT textureLod", + "#define texture2DProjLodEXT textureProjLod", + "#define textureCubeLodEXT textureLod", + "#define texture2DGradEXT textureGrad", + "#define texture2DProjGradEXT textureProjGrad", + "#define textureCubeGradEXT textureGrad" + ].join(` +`) + ` +` + prefixFragment; + } + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl); + const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl); + gl.attachShader(program, glVertexShader); + gl.attachShader(program, glFragmentShader); + if (parameters.index0AttributeName !== undefined) { + gl.bindAttribLocation(program, 0, parameters.index0AttributeName); + } else if (parameters.morphTargets === true) { + gl.bindAttribLocation(program, 0, "position"); + } + gl.linkProgram(program); + function onFirstUse(self2) { + if (renderer2.debug.checkShaderErrors) { + const programLog = gl.getProgramInfoLog(program).trim(); + const vertexLog = gl.getShaderInfoLog(glVertexShader).trim(); + const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim(); + let runnable = true; + let haveDiagnostics = true; + if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) { + runnable = false; + if (typeof renderer2.debug.onShaderError === "function") { + renderer2.debug.onShaderError(gl, program, glVertexShader, glFragmentShader); + } else { + const vertexErrors = getShaderErrors(gl, glVertexShader, "vertex"); + const fragmentErrors = getShaderErrors(gl, glFragmentShader, "fragment"); + console.error("THREE.WebGLProgram: Shader Error " + gl.getError() + " - " + "VALIDATE_STATUS " + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + ` + +` + "Material Name: " + self2.name + ` +` + "Material Type: " + self2.type + ` + +` + "Program Info Log: " + programLog + ` +` + vertexErrors + ` +` + fragmentErrors); + } + } else if (programLog !== "") { + console.warn("THREE.WebGLProgram: Program Info Log:", programLog); + } else if (vertexLog === "" || fragmentLog === "") { + haveDiagnostics = false; + } + if (haveDiagnostics) { + self2.diagnostics = { + runnable, + programLog, + vertexShader: { + log: vertexLog, + prefix: prefixVertex + }, + fragmentShader: { + log: fragmentLog, + prefix: prefixFragment + } + }; + } + } + gl.deleteShader(glVertexShader); + gl.deleteShader(glFragmentShader); + cachedUniforms = new WebGLUniforms(gl, program); + cachedAttributes = fetchAttributeLocations(gl, program); + } + let cachedUniforms; + this.getUniforms = function() { + if (cachedUniforms === undefined) { + onFirstUse(this); + } + return cachedUniforms; + }; + let cachedAttributes; + this.getAttributes = function() { + if (cachedAttributes === undefined) { + onFirstUse(this); + } + return cachedAttributes; + }; + let programReady = parameters.rendererExtensionParallelShaderCompile === false; + this.isReady = function() { + if (programReady === false) { + programReady = gl.getProgramParameter(program, COMPLETION_STATUS_KHR); + } + return programReady; + }; + this.destroy = function() { + bindingStates.releaseStatesOfProgram(this); + gl.deleteProgram(program); + this.program = undefined; + }; + this.type = parameters.shaderType; + this.name = parameters.shaderName; + this.id = programIdCount++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + return this; +} +var _id2 = 0; + +class WebGLShaderCache { + constructor() { + this.shaderCache = new Map; + this.materialCache = new Map; + } + update(material) { + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + const vertexShaderStage = this._getShaderStage(vertexShader); + const fragmentShaderStage = this._getShaderStage(fragmentShader); + const materialShaders = this._getShaderCacheForMaterial(material); + if (materialShaders.has(vertexShaderStage) === false) { + materialShaders.add(vertexShaderStage); + vertexShaderStage.usedTimes++; + } + if (materialShaders.has(fragmentShaderStage) === false) { + materialShaders.add(fragmentShaderStage); + fragmentShaderStage.usedTimes++; + } + return this; + } + remove(material) { + const materialShaders = this.materialCache.get(material); + for (const shaderStage of materialShaders) { + shaderStage.usedTimes--; + if (shaderStage.usedTimes === 0) + this.shaderCache.delete(shaderStage.code); + } + this.materialCache.delete(material); + return this; + } + getVertexShaderID(material) { + return this._getShaderStage(material.vertexShader).id; + } + getFragmentShaderID(material) { + return this._getShaderStage(material.fragmentShader).id; + } + dispose() { + this.shaderCache.clear(); + this.materialCache.clear(); + } + _getShaderCacheForMaterial(material) { + const cache = this.materialCache; + let set = cache.get(material); + if (set === undefined) { + set = new Set; + cache.set(material, set); + } + return set; + } + _getShaderStage(code) { + const cache = this.shaderCache; + let stage = cache.get(code); + if (stage === undefined) { + stage = new WebGLShaderStage(code); + cache.set(code, stage); + } + return stage; + } +} + +class WebGLShaderStage { + constructor(code) { + this.id = _id2++; + this.code = code; + this.usedTimes = 0; + } +} +function WebGLPrograms(renderer2, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) { + const _programLayers = new Layers; + const _customShaders = new WebGLShaderCache; + const _activeChannels = new Set; + const programs = []; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures; + let precision = capabilities.precision; + const shaderIDs = { + MeshDepthMaterial: "depth", + MeshDistanceMaterial: "distanceRGBA", + MeshNormalMaterial: "normal", + MeshBasicMaterial: "basic", + MeshLambertMaterial: "lambert", + MeshPhongMaterial: "phong", + MeshToonMaterial: "toon", + MeshStandardMaterial: "physical", + MeshPhysicalMaterial: "physical", + MeshMatcapMaterial: "matcap", + LineBasicMaterial: "basic", + LineDashedMaterial: "dashed", + PointsMaterial: "points", + ShadowMaterial: "shadow", + SpriteMaterial: "sprite" + }; + function getChannel(value2) { + _activeChannels.add(value2); + if (value2 === 0) + return "uv"; + return `uv${value2}`; + } + function getParameters(material, lights, shadows, scene, object) { + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null; + const shaderID = shaderIDs[material.type]; + if (material.precision !== null) { + precision = capabilities.getMaxPrecision(material.precision); + if (precision !== material.precision) { + console.warn("THREE.WebGLProgram.getParameters:", material.precision, "not supported, using", precision, "instead."); + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + let morphTextureStride = 0; + if (geometry.morphAttributes.position !== undefined) + morphTextureStride = 1; + if (geometry.morphAttributes.normal !== undefined) + morphTextureStride = 2; + if (geometry.morphAttributes.color !== undefined) + morphTextureStride = 3; + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + if (shaderID) { + const shader = ShaderLib[shaderID]; + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + } else { + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + _customShaders.update(material); + customVertexShaderID = _customShaders.getVertexShaderID(material); + customFragmentShaderID = _customShaders.getFragmentShaderID(material); + } + const currentRenderTarget = renderer2.getRenderTarget(); + const reverseDepthBuffer = renderer2.state.buffers.depth.getReversed(); + const IS_INSTANCEDMESH = object.isInstancedMesh === true; + const IS_BATCHEDMESH = object.isBatchedMesh === true; + const HAS_MAP = !!material.map; + const HAS_MATCAP = !!material.matcap; + const HAS_ENVMAP = !!envMap; + const HAS_AOMAP = !!material.aoMap; + const HAS_LIGHTMAP = !!material.lightMap; + const HAS_BUMPMAP = !!material.bumpMap; + const HAS_NORMALMAP = !!material.normalMap; + const HAS_DISPLACEMENTMAP = !!material.displacementMap; + const HAS_EMISSIVEMAP = !!material.emissiveMap; + const HAS_METALNESSMAP = !!material.metalnessMap; + const HAS_ROUGHNESSMAP = !!material.roughnessMap; + const HAS_ANISOTROPY = material.anisotropy > 0; + const HAS_CLEARCOAT = material.clearcoat > 0; + const HAS_DISPERSION = material.dispersion > 0; + const HAS_IRIDESCENCE = material.iridescence > 0; + const HAS_SHEEN = material.sheen > 0; + const HAS_TRANSMISSION = material.transmission > 0; + const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !!material.anisotropyMap; + const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !!material.clearcoatMap; + const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !!material.clearcoatNormalMap; + const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !!material.clearcoatRoughnessMap; + const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !!material.iridescenceMap; + const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !!material.iridescenceThicknessMap; + const HAS_SHEEN_COLORMAP = HAS_SHEEN && !!material.sheenColorMap; + const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !!material.sheenRoughnessMap; + const HAS_SPECULARMAP = !!material.specularMap; + const HAS_SPECULAR_COLORMAP = !!material.specularColorMap; + const HAS_SPECULAR_INTENSITYMAP = !!material.specularIntensityMap; + const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !!material.transmissionMap; + const HAS_THICKNESSMAP = HAS_TRANSMISSION && !!material.thicknessMap; + const HAS_GRADIENTMAP = !!material.gradientMap; + const HAS_ALPHAMAP = !!material.alphaMap; + const HAS_ALPHATEST = material.alphaTest > 0; + const HAS_ALPHAHASH = !!material.alphaHash; + const HAS_EXTENSIONS = !!material.extensions; + let toneMapping = NoToneMapping; + if (material.toneMapped) { + if (currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true) { + toneMapping = renderer2.toneMapping; + } + } + const parameters = { + shaderID, + shaderType: material.type, + shaderName: material.name, + vertexShader, + fragmentShader, + defines: material.defines, + customVertexShaderID, + customFragmentShaderID, + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + precision, + batching: IS_BATCHEDMESH, + batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null, + instancing: IS_INSTANCEDMESH, + instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, + supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, + outputColorSpace: currentRenderTarget === null ? renderer2.outputColorSpace : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace, + alphaToCoverage: !!material.alphaToCoverage, + map: HAS_MAP, + matcap: HAS_MATCAP, + envMap: HAS_ENVMAP, + envMapMode: HAS_ENVMAP && envMap.mapping, + envMapCubeUVHeight, + aoMap: HAS_AOMAP, + lightMap: HAS_LIGHTMAP, + bumpMap: HAS_BUMPMAP, + normalMap: HAS_NORMALMAP, + displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP, + emissiveMap: HAS_EMISSIVEMAP, + normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap, + normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap, + metalnessMap: HAS_METALNESSMAP, + roughnessMap: HAS_ROUGHNESSMAP, + anisotropy: HAS_ANISOTROPY, + anisotropyMap: HAS_ANISOTROPYMAP, + clearcoat: HAS_CLEARCOAT, + clearcoatMap: HAS_CLEARCOATMAP, + clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP, + clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP, + dispersion: HAS_DISPERSION, + iridescence: HAS_IRIDESCENCE, + iridescenceMap: HAS_IRIDESCENCEMAP, + iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP, + sheen: HAS_SHEEN, + sheenColorMap: HAS_SHEEN_COLORMAP, + sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP, + specularMap: HAS_SPECULARMAP, + specularColorMap: HAS_SPECULAR_COLORMAP, + specularIntensityMap: HAS_SPECULAR_INTENSITYMAP, + transmission: HAS_TRANSMISSION, + transmissionMap: HAS_TRANSMISSIONMAP, + thicknessMap: HAS_THICKNESSMAP, + gradientMap: HAS_GRADIENTMAP, + opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false, + alphaMap: HAS_ALPHAMAP, + alphaTest: HAS_ALPHATEST, + alphaHash: HAS_ALPHAHASH, + combine: material.combine, + mapUv: HAS_MAP && getChannel(material.map.channel), + aoMapUv: HAS_AOMAP && getChannel(material.aoMap.channel), + lightMapUv: HAS_LIGHTMAP && getChannel(material.lightMap.channel), + bumpMapUv: HAS_BUMPMAP && getChannel(material.bumpMap.channel), + normalMapUv: HAS_NORMALMAP && getChannel(material.normalMap.channel), + displacementMapUv: HAS_DISPLACEMENTMAP && getChannel(material.displacementMap.channel), + emissiveMapUv: HAS_EMISSIVEMAP && getChannel(material.emissiveMap.channel), + metalnessMapUv: HAS_METALNESSMAP && getChannel(material.metalnessMap.channel), + roughnessMapUv: HAS_ROUGHNESSMAP && getChannel(material.roughnessMap.channel), + anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel(material.anisotropyMap.channel), + clearcoatMapUv: HAS_CLEARCOATMAP && getChannel(material.clearcoatMap.channel), + clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel(material.clearcoatNormalMap.channel), + clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel(material.clearcoatRoughnessMap.channel), + iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel(material.iridescenceMap.channel), + iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel(material.iridescenceThicknessMap.channel), + sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel(material.sheenColorMap.channel), + sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel(material.sheenRoughnessMap.channel), + specularMapUv: HAS_SPECULARMAP && getChannel(material.specularMap.channel), + specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel(material.specularColorMap.channel), + specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel(material.specularIntensityMap.channel), + transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel(material.transmissionMap.channel), + thicknessMapUv: HAS_THICKNESSMAP && getChannel(material.thicknessMap.channel), + alphaMapUv: HAS_ALPHAMAP && getChannel(material.alphaMap.channel), + vertexTangents: !!geometry.attributes.tangent && (HAS_NORMALMAP || HAS_ANISOTROPY), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4, + pointsUvs: object.isPoints === true && !!geometry.attributes.uv && (HAS_MAP || HAS_ALPHAMAP), + fog: !!fog, + useFog: material.fog === true, + fogExp2: !!fog && fog.isFogExp2, + flatShading: material.flatShading === true, + sizeAttenuation: material.sizeAttenuation === true, + logarithmicDepthBuffer, + reverseDepthBuffer, + skinning: object.isSkinnedMesh === true, + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount, + morphTextureStride, + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + numLightProbes: lights.numLightProbes, + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + dithering: material.dithering, + shadowMapEnabled: renderer2.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer2.shadowMap.type, + toneMapping, + decodeVideoTexture: HAS_MAP && material.map.isVideoTexture === true && ColorManagement.getTransfer(material.map.colorSpace) === SRGBTransfer, + decodeVideoTextureEmissive: HAS_EMISSIVEMAP && material.emissiveMap.isVideoTexture === true && ColorManagement.getTransfer(material.emissiveMap.colorSpace) === SRGBTransfer, + premultipliedAlpha: material.premultipliedAlpha, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + useDepthPacking: material.depthPacking >= 0, + depthPacking: material.depthPacking || 0, + index0AttributeName: material.index0AttributeName, + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has("WEBGL_clip_cull_distance"), + extensionMultiDraw: (HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH) && extensions.has("WEBGL_multi_draw"), + rendererExtensionParallelShaderCompile: extensions.has("KHR_parallel_shader_compile"), + customProgramCacheKey: material.customProgramCacheKey() + }; + parameters.vertexUv1s = _activeChannels.has(1); + parameters.vertexUv2s = _activeChannels.has(2); + parameters.vertexUv3s = _activeChannels.has(3); + _activeChannels.clear(); + return parameters; + } + function getProgramCacheKey(parameters) { + const array = []; + if (parameters.shaderID) { + array.push(parameters.shaderID); + } else { + array.push(parameters.customVertexShaderID); + array.push(parameters.customFragmentShaderID); + } + if (parameters.defines !== undefined) { + for (const name2 in parameters.defines) { + array.push(name2); + array.push(parameters.defines[name2]); + } + } + if (parameters.isRawShaderMaterial === false) { + getProgramCacheKeyParameters(array, parameters); + getProgramCacheKeyBooleans(array, parameters); + array.push(renderer2.outputColorSpace); + } + array.push(parameters.customProgramCacheKey); + return array.join(); + } + function getProgramCacheKeyParameters(array, parameters) { + array.push(parameters.precision); + array.push(parameters.outputColorSpace); + array.push(parameters.envMapMode); + array.push(parameters.envMapCubeUVHeight); + array.push(parameters.mapUv); + array.push(parameters.alphaMapUv); + array.push(parameters.lightMapUv); + array.push(parameters.aoMapUv); + array.push(parameters.bumpMapUv); + array.push(parameters.normalMapUv); + array.push(parameters.displacementMapUv); + array.push(parameters.emissiveMapUv); + array.push(parameters.metalnessMapUv); + array.push(parameters.roughnessMapUv); + array.push(parameters.anisotropyMapUv); + array.push(parameters.clearcoatMapUv); + array.push(parameters.clearcoatNormalMapUv); + array.push(parameters.clearcoatRoughnessMapUv); + array.push(parameters.iridescenceMapUv); + array.push(parameters.iridescenceThicknessMapUv); + array.push(parameters.sheenColorMapUv); + array.push(parameters.sheenRoughnessMapUv); + array.push(parameters.specularMapUv); + array.push(parameters.specularColorMapUv); + array.push(parameters.specularIntensityMapUv); + array.push(parameters.transmissionMapUv); + array.push(parameters.thicknessMapUv); + array.push(parameters.combine); + array.push(parameters.fogExp2); + array.push(parameters.sizeAttenuation); + array.push(parameters.morphTargetsCount); + array.push(parameters.morphAttributeCount); + array.push(parameters.numDirLights); + array.push(parameters.numPointLights); + array.push(parameters.numSpotLights); + array.push(parameters.numSpotLightMaps); + array.push(parameters.numHemiLights); + array.push(parameters.numRectAreaLights); + array.push(parameters.numDirLightShadows); + array.push(parameters.numPointLightShadows); + array.push(parameters.numSpotLightShadows); + array.push(parameters.numSpotLightShadowsWithMaps); + array.push(parameters.numLightProbes); + array.push(parameters.shadowMapType); + array.push(parameters.toneMapping); + array.push(parameters.numClippingPlanes); + array.push(parameters.numClipIntersection); + array.push(parameters.depthPacking); + } + function getProgramCacheKeyBooleans(array, parameters) { + _programLayers.disableAll(); + if (parameters.supportsVertexTextures) + _programLayers.enable(0); + if (parameters.instancing) + _programLayers.enable(1); + if (parameters.instancingColor) + _programLayers.enable(2); + if (parameters.instancingMorph) + _programLayers.enable(3); + if (parameters.matcap) + _programLayers.enable(4); + if (parameters.envMap) + _programLayers.enable(5); + if (parameters.normalMapObjectSpace) + _programLayers.enable(6); + if (parameters.normalMapTangentSpace) + _programLayers.enable(7); + if (parameters.clearcoat) + _programLayers.enable(8); + if (parameters.iridescence) + _programLayers.enable(9); + if (parameters.alphaTest) + _programLayers.enable(10); + if (parameters.vertexColors) + _programLayers.enable(11); + if (parameters.vertexAlphas) + _programLayers.enable(12); + if (parameters.vertexUv1s) + _programLayers.enable(13); + if (parameters.vertexUv2s) + _programLayers.enable(14); + if (parameters.vertexUv3s) + _programLayers.enable(15); + if (parameters.vertexTangents) + _programLayers.enable(16); + if (parameters.anisotropy) + _programLayers.enable(17); + if (parameters.alphaHash) + _programLayers.enable(18); + if (parameters.batching) + _programLayers.enable(19); + if (parameters.dispersion) + _programLayers.enable(20); + if (parameters.batchingColor) + _programLayers.enable(21); + array.push(_programLayers.mask); + _programLayers.disableAll(); + if (parameters.fog) + _programLayers.enable(0); + if (parameters.useFog) + _programLayers.enable(1); + if (parameters.flatShading) + _programLayers.enable(2); + if (parameters.logarithmicDepthBuffer) + _programLayers.enable(3); + if (parameters.reverseDepthBuffer) + _programLayers.enable(4); + if (parameters.skinning) + _programLayers.enable(5); + if (parameters.morphTargets) + _programLayers.enable(6); + if (parameters.morphNormals) + _programLayers.enable(7); + if (parameters.morphColors) + _programLayers.enable(8); + if (parameters.premultipliedAlpha) + _programLayers.enable(9); + if (parameters.shadowMapEnabled) + _programLayers.enable(10); + if (parameters.doubleSided) + _programLayers.enable(11); + if (parameters.flipSided) + _programLayers.enable(12); + if (parameters.useDepthPacking) + _programLayers.enable(13); + if (parameters.dithering) + _programLayers.enable(14); + if (parameters.transmission) + _programLayers.enable(15); + if (parameters.sheen) + _programLayers.enable(16); + if (parameters.opaque) + _programLayers.enable(17); + if (parameters.pointsUvs) + _programLayers.enable(18); + if (parameters.decodeVideoTexture) + _programLayers.enable(19); + if (parameters.decodeVideoTextureEmissive) + _programLayers.enable(20); + if (parameters.alphaToCoverage) + _programLayers.enable(21); + array.push(_programLayers.mask); + } + function getUniforms(material) { + const shaderID = shaderIDs[material.type]; + let uniforms; + if (shaderID) { + const shader = ShaderLib[shaderID]; + uniforms = UniformsUtils.clone(shader.uniforms); + } else { + uniforms = material.uniforms; + } + return uniforms; + } + function acquireProgram(parameters, cacheKey) { + let program; + for (let p = 0, pl = programs.length;p < pl; p++) { + const preexistingProgram = programs[p]; + if (preexistingProgram.cacheKey === cacheKey) { + program = preexistingProgram; + ++program.usedTimes; + break; + } + } + if (program === undefined) { + program = new WebGLProgram(renderer2, cacheKey, parameters, bindingStates); + programs.push(program); + } + return program; + } + function releaseProgram(program) { + if (--program.usedTimes === 0) { + const i = programs.indexOf(program); + programs[i] = programs[programs.length - 1]; + programs.pop(); + program.destroy(); + } + } + function releaseShaderCache(material) { + _customShaders.remove(material); + } + function dispose() { + _customShaders.dispose(); + } + return { + getParameters, + getProgramCacheKey, + getUniforms, + acquireProgram, + releaseProgram, + releaseShaderCache, + programs, + dispose + }; +} +function WebGLProperties() { + let properties = new WeakMap; + function has2(object) { + return properties.has(object); + } + function get(object) { + let map2 = properties.get(object); + if (map2 === undefined) { + map2 = {}; + properties.set(object, map2); + } + return map2; + } + function remove(object) { + properties.delete(object); + } + function update(object, key2, value2) { + properties.get(object)[key2] = value2; + } + function dispose() { + properties = new WeakMap; + } + return { + has: has2, + get, + remove, + update, + dispose + }; +} +function painterSortStable(a, b) { + if (a.groupOrder !== b.groupOrder) { + return a.groupOrder - b.groupOrder; + } else if (a.renderOrder !== b.renderOrder) { + return a.renderOrder - b.renderOrder; + } else if (a.material.id !== b.material.id) { + return a.material.id - b.material.id; + } else if (a.z !== b.z) { + return a.z - b.z; + } else { + return a.id - b.id; + } +} +function reversePainterSortStable(a, b) { + if (a.groupOrder !== b.groupOrder) { + return a.groupOrder - b.groupOrder; + } else if (a.renderOrder !== b.renderOrder) { + return a.renderOrder - b.renderOrder; + } else if (a.z !== b.z) { + return b.z - a.z; + } else { + return a.id - b.id; + } +} +function WebGLRenderList() { + const renderItems = []; + let renderItemsIndex = 0; + const opaque = []; + const transmissive = []; + const transparent = []; + function init() { + renderItemsIndex = 0; + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + } + function getNextRenderItem(object, geometry, material, groupOrder, z, group) { + let renderItem = renderItems[renderItemsIndex]; + if (renderItem === undefined) { + renderItem = { + id: object.id, + object, + geometry, + material, + groupOrder, + renderOrder: object.renderOrder, + z, + group + }; + renderItems[renderItemsIndex] = renderItem; + } else { + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + } + renderItemsIndex++; + return renderItem; + } + function push(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.push(renderItem); + } else if (material.transparent === true) { + transparent.push(renderItem); + } else { + opaque.push(renderItem); + } + } + function unshift(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.unshift(renderItem); + } else if (material.transparent === true) { + transparent.unshift(renderItem); + } else { + opaque.unshift(renderItem); + } + } + function sort(customOpaqueSort, customTransparentSort) { + if (opaque.length > 1) + opaque.sort(customOpaqueSort || painterSortStable); + if (transmissive.length > 1) + transmissive.sort(customTransparentSort || reversePainterSortStable); + if (transparent.length > 1) + transparent.sort(customTransparentSort || reversePainterSortStable); + } + function finish() { + for (let i = renderItemsIndex, il = renderItems.length;i < il; i++) { + const renderItem = renderItems[i]; + if (renderItem.id === null) + break; + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + } + } + return { + opaque, + transmissive, + transparent, + init, + push, + unshift, + finish, + sort + }; +} +function WebGLRenderLists() { + let lists = new WeakMap; + function get(scene, renderCallDepth) { + const listArray = lists.get(scene); + let list; + if (listArray === undefined) { + list = new WebGLRenderList; + lists.set(scene, [list]); + } else { + if (renderCallDepth >= listArray.length) { + list = new WebGLRenderList; + listArray.push(list); + } else { + list = listArray[renderCallDepth]; + } + } + return list; + } + function dispose() { + lists = new WeakMap; + } + return { + get, + dispose + }; +} +function UniformsCache() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== undefined) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + direction: new Vector3, + color: new Color + }; + break; + case "SpotLight": + uniforms = { + position: new Vector3, + direction: new Vector3, + color: new Color, + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + case "PointLight": + uniforms = { + position: new Vector3, + color: new Color, + distance: 0, + decay: 0 + }; + break; + case "HemisphereLight": + uniforms = { + direction: new Vector3, + skyColor: new Color, + groundColor: new Color + }; + break; + case "RectAreaLight": + uniforms = { + color: new Color, + position: new Vector3, + halfWidth: new Vector3, + halfHeight: new Vector3 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; +} +function ShadowUniformsCache() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== undefined) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2 + }; + break; + case "SpotLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2 + }; + break; + case "PointLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2, + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; +} +var nextVersion = 0; +function shadowCastingAndTexturingLightsFirst(lightA, lightB) { + return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0); +} +function WebGLLights(extensions) { + const cache = new UniformsCache; + const shadowCache = ShadowUniformsCache(); + const state = { + version: 0, + hash: { + directionalLength: -1, + pointLength: -1, + spotLength: -1, + rectAreaLength: -1, + hemiLength: -1, + numDirectionalShadows: -1, + numPointShadows: -1, + numSpotShadows: -1, + numSpotMaps: -1, + numLightProbes: -1 + }, + ambient: [0, 0, 0], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0, + numLightProbes: 0 + }; + for (let i = 0;i < 9; i++) + state.probe.push(new Vector3); + const vector3 = new Vector3; + const matrix4 = new Matrix4; + const matrix42 = new Matrix4; + function setup(lights) { + let r = 0, g = 0, b = 0; + for (let i = 0;i < 9; i++) + state.probe[i].set(0, 0, 0); + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + let numLightProbes = 0; + lights.sort(shadowCastingAndTexturingLightsFirst); + for (let i = 0, l = lights.length;i < l; i++) { + const light = lights[i]; + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null; + if (light.isAmbientLight) { + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; + } else if (light.isLightProbe) { + for (let j = 0;j < 9; j++) { + state.probe[j].addScaledVector(light.sh.coefficients[j], intensity); + } + numLightProbes++; + } else if (light.isDirectionalLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.directionalShadow[directionalLength] = shadowUniforms; + state.directionalShadowMap[directionalLength] = shadowMap; + state.directionalShadowMatrix[directionalLength] = light.shadow.matrix; + numDirectionalShadows++; + } + state.directional[directionalLength] = uniforms; + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = cache.get(light); + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.distance = distance; + uniforms.coneCos = Math.cos(light.angle); + uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra)); + uniforms.decay = light.decay; + state.spot[spotLength] = uniforms; + const shadow = light.shadow; + if (light.map) { + state.spotLightMap[numSpotMaps] = light.map; + numSpotMaps++; + shadow.updateMatrices(light); + if (light.castShadow) + numSpotShadowsWithMaps++; + } + state.spotLightMatrix[spotLength] = shadow.matrix; + if (light.castShadow) { + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.spotShadow[spotLength] = shadowUniforms; + state.spotShadowMap[spotLength] = shadowMap; + numSpotShadows++; + } + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = cache.get(light); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + state.rectArea[rectAreaLength] = uniforms; + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + state.pointShadow[pointLength] = shadowUniforms; + state.pointShadowMap[pointLength] = shadowMap; + state.pointShadowMatrix[pointLength] = light.shadow.matrix; + numPointShadows++; + } + state.point[pointLength] = uniforms; + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = cache.get(light); + uniforms.skyColor.copy(light.color).multiplyScalar(intensity); + uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity); + state.hemi[hemiLength] = uniforms; + hemiLength++; + } + } + if (rectAreaLength > 0) { + if (extensions.has("OES_texture_float_linear") === true) { + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + } else { + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + } + } + state.ambient[0] = r; + state.ambient[1] = g; + state.ambient[2] = b; + const hash = state.hash; + if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps || hash.numLightProbes !== numLightProbes) { + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + state.numLightProbes = numLightProbes; + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + hash.numLightProbes = numLightProbes; + state.version = nextVersion++; + } + } + function setupView(lights, camera) { + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + const viewMatrix = camera.matrixWorldInverse; + for (let i = 0, l = lights.length;i < l; i++) { + const light = lights[i]; + if (light.isDirectionalLight) { + const uniforms = state.directional[directionalLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = state.spot[spotLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = state.rectArea[rectAreaLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + matrix42.identity(); + matrix4.copy(light.matrixWorld); + matrix4.premultiply(viewMatrix); + matrix42.extractRotation(matrix4); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + uniforms.halfWidth.applyMatrix4(matrix42); + uniforms.halfHeight.applyMatrix4(matrix42); + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = state.point[pointLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = state.hemi[hemiLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + uniforms.direction.transformDirection(viewMatrix); + hemiLength++; + } + } + } + return { + setup, + setupView, + state + }; +} +function WebGLRenderState(extensions) { + const lights = new WebGLLights(extensions); + const lightsArray = []; + const shadowsArray = []; + function init(camera) { + state.camera = camera; + lightsArray.length = 0; + shadowsArray.length = 0; + } + function pushLight(light) { + lightsArray.push(light); + } + function pushShadow(shadowLight) { + shadowsArray.push(shadowLight); + } + function setupLights() { + lights.setup(lightsArray); + } + function setupLightsView(camera) { + lights.setupView(lightsArray, camera); + } + const state = { + lightsArray, + shadowsArray, + camera: null, + lights, + transmissionRenderTarget: {} + }; + return { + init, + state, + setupLights, + setupLightsView, + pushLight, + pushShadow + }; +} +function WebGLRenderStates(extensions) { + let renderStates = new WeakMap; + function get(scene, renderCallDepth = 0) { + const renderStateArray = renderStates.get(scene); + let renderState; + if (renderStateArray === undefined) { + renderState = new WebGLRenderState(extensions); + renderStates.set(scene, [renderState]); + } else { + if (renderCallDepth >= renderStateArray.length) { + renderState = new WebGLRenderState(extensions); + renderStateArray.push(renderState); + } else { + renderState = renderStateArray[renderCallDepth]; + } + } + return renderState; + } + function dispose() { + renderStates = new WeakMap; + } + return { + get, + dispose + }; +} +var vertex = `void main() { + gl_Position = vec4( position, 1.0 ); +}`; +var fragment = `uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`; +function WebGLShadowMap(renderer2, objects, capabilities) { + let _frustum2 = new Frustum; + const _shadowMapSize = new Vector2, _viewportSize = new Vector2, _viewport = new Vector4, _depthMaterial = new MeshDepthMaterial({ depthPacking: RGBADepthPacking }), _distanceMaterial = new MeshDistanceMaterial, _materialCache = {}, _maxTextureSize = capabilities.maxTextureSize; + const shadowSide = { [FrontSide]: BackSide, [BackSide]: FrontSide, [DoubleSide]: DoubleSide }; + const shadowMaterialVertical = new ShaderMaterial({ + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2 }, + radius: { value: 4 } + }, + vertexShader: vertex, + fragmentShader: fragment + }); + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + const fullScreenTri = new BufferGeometry; + fullScreenTri.setAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3)); + const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); + const scope = this; + this.enabled = false; + this.autoUpdate = true; + this.needsUpdate = false; + this.type = PCFShadowMap; + let _previousType = this.type; + this.render = function(lights, scene, camera) { + if (scope.enabled === false) + return; + if (scope.autoUpdate === false && scope.needsUpdate === false) + return; + if (lights.length === 0) + return; + const currentRenderTarget = renderer2.getRenderTarget(); + const activeCubeFace = renderer2.getActiveCubeFace(); + const activeMipmapLevel = renderer2.getActiveMipmapLevel(); + const _state = renderer2.state; + _state.setBlending(NoBlending); + _state.buffers.color.setClear(1, 1, 1, 1); + _state.buffers.depth.setTest(true); + _state.setScissorTest(false); + const toVSM = _previousType !== VSMShadowMap && this.type === VSMShadowMap; + const fromVSM = _previousType === VSMShadowMap && this.type !== VSMShadowMap; + for (let i = 0, il = lights.length;i < il; i++) { + const light = lights[i]; + const shadow = light.shadow; + if (shadow === undefined) { + console.warn("THREE.WebGLShadowMap:", light, "has no shadow."); + continue; + } + if (shadow.autoUpdate === false && shadow.needsUpdate === false) + continue; + _shadowMapSize.copy(shadow.mapSize); + const shadowFrameExtents = shadow.getFrameExtents(); + _shadowMapSize.multiply(shadowFrameExtents); + _viewportSize.copy(shadow.mapSize); + if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) { + if (_shadowMapSize.x > _maxTextureSize) { + _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + } + if (_shadowMapSize.y > _maxTextureSize) { + _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + } + } + if (shadow.map === null || toVSM === true || fromVSM === true) { + const pars = this.type !== VSMShadowMap ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; + if (shadow.map !== null) { + shadow.map.dispose(); + } + shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars); + shadow.map.texture.name = light.name + ".shadowMap"; + shadow.camera.updateProjectionMatrix(); + } + renderer2.setRenderTarget(shadow.map); + renderer2.clear(); + const viewportCount = shadow.getViewportCount(); + for (let vp = 0;vp < viewportCount; vp++) { + const viewport = shadow.getViewport(vp); + _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w); + _state.viewport(_viewport); + shadow.updateMatrices(light, vp); + _frustum2 = shadow.getFrustum(); + renderObject(scene, camera, shadow.camera, light, this.type); + } + if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) { + VSMPass(shadow, camera); + } + shadow.needsUpdate = false; + } + _previousType = this.type; + scope.needsUpdate = false; + renderer2.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel); + }; + function VSMPass(shadow, camera) { + const geometry = objects.update(fullScreenMesh); + if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) { + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + } + if (shadow.mapPass === null) { + shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y); + } + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + renderer2.setRenderTarget(shadow.mapPass); + renderer2.clear(); + renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + renderer2.setRenderTarget(shadow.map); + renderer2.clear(); + renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null); + } + function getDepthMaterial(object, material, light, type) { + let result = null; + const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial; + if (customMaterial !== undefined) { + result = customMaterial; + } else { + result = light.isPointLight === true ? _distanceMaterial : _depthMaterial; + if (renderer2.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0 || material.map && material.alphaTest > 0) { + const keyA = result.uuid, keyB = material.uuid; + let materialsForVariant = _materialCache[keyA]; + if (materialsForVariant === undefined) { + materialsForVariant = {}; + _materialCache[keyA] = materialsForVariant; + } + let cachedMaterial = materialsForVariant[keyB]; + if (cachedMaterial === undefined) { + cachedMaterial = result.clone(); + materialsForVariant[keyB] = cachedMaterial; + material.addEventListener("dispose", onMaterialDispose); + } + result = cachedMaterial; + } + } + result.visible = material.visible; + result.wireframe = material.wireframe; + if (type === VSMShadowMap) { + result.side = material.shadowSide !== null ? material.shadowSide : material.side; + } else { + result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side]; + } + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.map = material.map; + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + if (light.isPointLight === true && result.isMeshDistanceMaterial === true) { + const materialProperties = renderer2.properties.get(result); + materialProperties.light = light; + } + return result; + } + function renderObject(object, camera, shadowCamera, light, type) { + if (object.visible === false) + return; + const visible = object.layers.test(camera.layers); + if (visible && (object.isMesh || object.isLine || object.isPoints)) { + if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum2.intersectsObject(object))) { + object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld); + const geometry = objects.update(object); + const material = object.material; + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let k = 0, kl = groups.length;k < kl; k++) { + const group = groups[k]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + const depthMaterial = getDepthMaterial(object, groupMaterial, light, type); + object.onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group); + object.onAfterShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + } + } + } else if (material.visible) { + const depthMaterial = getDepthMaterial(object, material, light, type); + object.onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null); + object.onAfterShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + } + } + } + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + renderObject(children[i], camera, shadowCamera, light, type); + } + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + for (const id in _materialCache) { + const cache = _materialCache[id]; + const uuid = event.target.uuid; + if (uuid in cache) { + const shadowMaterial = cache[uuid]; + shadowMaterial.dispose(); + delete cache[uuid]; + } + } + } +} +var reversedFuncs = { + [NeverDepth]: AlwaysDepth, + [LessDepth]: GreaterDepth, + [EqualDepth]: NotEqualDepth, + [LessEqualDepth]: GreaterEqualDepth, + [AlwaysDepth]: NeverDepth, + [GreaterDepth]: LessDepth, + [NotEqualDepth]: EqualDepth, + [GreaterEqualDepth]: LessEqualDepth +}; +function WebGLState(gl, extensions) { + function ColorBuffer() { + let locked = false; + const color = new Vector4; + let currentColorMask = null; + const currentColorClear = new Vector4(0, 0, 0, 0); + return { + setMask: function(colorMask) { + if (currentColorMask !== colorMask && !locked) { + gl.colorMask(colorMask, colorMask, colorMask, colorMask); + currentColorMask = colorMask; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(r, g, b, a, premultipliedAlpha) { + if (premultipliedAlpha === true) { + r *= a; + g *= a; + b *= a; + } + color.set(r, g, b, a); + if (currentColorClear.equals(color) === false) { + gl.clearColor(r, g, b, a); + currentColorClear.copy(color); + } + }, + reset: function() { + locked = false; + currentColorMask = null; + currentColorClear.set(-1, 0, 0, 0); + } + }; + } + function DepthBuffer() { + let locked = false; + let reversed = false; + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + return { + setReversed: function(value2) { + if (reversed !== value2) { + const ext = extensions.get("EXT_clip_control"); + if (reversed) { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT); + } else { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT); + } + const oldDepth = currentDepthClear; + currentDepthClear = null; + this.setClear(oldDepth); + } + reversed = value2; + }, + getReversed: function() { + return reversed; + }, + setTest: function(depthTest) { + if (depthTest) { + enable(gl.DEPTH_TEST); + } else { + disable(gl.DEPTH_TEST); + } + }, + setMask: function(depthMask) { + if (currentDepthMask !== depthMask && !locked) { + gl.depthMask(depthMask); + currentDepthMask = depthMask; + } + }, + setFunc: function(depthFunc) { + if (reversed) + depthFunc = reversedFuncs[depthFunc]; + if (currentDepthFunc !== depthFunc) { + switch (depthFunc) { + case NeverDepth: + gl.depthFunc(gl.NEVER); + break; + case AlwaysDepth: + gl.depthFunc(gl.ALWAYS); + break; + case LessDepth: + gl.depthFunc(gl.LESS); + break; + case LessEqualDepth: + gl.depthFunc(gl.LEQUAL); + break; + case EqualDepth: + gl.depthFunc(gl.EQUAL); + break; + case GreaterEqualDepth: + gl.depthFunc(gl.GEQUAL); + break; + case GreaterDepth: + gl.depthFunc(gl.GREATER); + break; + case NotEqualDepth: + gl.depthFunc(gl.NOTEQUAL); + break; + default: + gl.depthFunc(gl.LEQUAL); + } + currentDepthFunc = depthFunc; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(depth) { + if (currentDepthClear !== depth) { + if (reversed) { + depth = 1 - depth; + } + gl.clearDepth(depth); + currentDepthClear = depth; + } + }, + reset: function() { + locked = false; + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + reversed = false; + } + }; + } + function StencilBuffer() { + let locked = false; + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + return { + setTest: function(stencilTest) { + if (!locked) { + if (stencilTest) { + enable(gl.STENCIL_TEST); + } else { + disable(gl.STENCIL_TEST); + } + } + }, + setMask: function(stencilMask) { + if (currentStencilMask !== stencilMask && !locked) { + gl.stencilMask(stencilMask); + currentStencilMask = stencilMask; + } + }, + setFunc: function(stencilFunc, stencilRef, stencilMask) { + if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) { + gl.stencilFunc(stencilFunc, stencilRef, stencilMask); + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + } + }, + setOp: function(stencilFail, stencilZFail, stencilZPass) { + if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) { + gl.stencilOp(stencilFail, stencilZFail, stencilZPass); + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(stencil) { + if (currentStencilClear !== stencil) { + gl.clearStencil(stencil); + currentStencilClear = stencil; + } + }, + reset: function() { + locked = false; + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + } + }; + } + const colorBuffer = new ColorBuffer; + const depthBuffer = new DepthBuffer; + const stencilBuffer = new StencilBuffer; + const uboBindings = new WeakMap; + const uboProgramMap = new WeakMap; + let enabledCapabilities = {}; + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap; + let defaultDrawbuffers = []; + let currentProgram = null; + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentBlendColor = new Color(0, 0, 0); + let currentBlendAlpha = 0; + let currentPremultipledAlpha = false; + let currentFlipSided = null; + let currentCullFace = null; + let currentLineWidth = null; + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter(gl.VERSION); + if (glVersion.indexOf("WebGL") !== -1) { + version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 1; + } else if (glVersion.indexOf("OpenGL ES") !== -1) { + version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 2; + } + let currentTextureSlot = null; + let currentBoundTextures = {}; + const scissorParam = gl.getParameter(gl.SCISSOR_BOX); + const viewportParam = gl.getParameter(gl.VIEWPORT); + const currentScissor = new Vector4().fromArray(scissorParam); + const currentViewport = new Vector4().fromArray(viewportParam); + function createTexture(type, target, count, dimensions) { + const data2 = new Uint8Array(4); + const texture = gl.createTexture(); + gl.bindTexture(type, texture); + gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + for (let i = 0;i < count; i++) { + if (type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY) { + gl.texImage3D(target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data2); + } else { + gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data2); + } + } + return texture; + } + const emptyTextures = {}; + emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1); + emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); + emptyTextures[gl.TEXTURE_2D_ARRAY] = createTexture(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1); + emptyTextures[gl.TEXTURE_3D] = createTexture(gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1); + colorBuffer.setClear(0, 0, 0, 1); + depthBuffer.setClear(1); + stencilBuffer.setClear(0); + enable(gl.DEPTH_TEST); + depthBuffer.setFunc(LessEqualDepth); + setFlipSided(false); + setCullFace(CullFaceBack); + enable(gl.CULL_FACE); + setBlending(NoBlending); + function enable(id) { + if (enabledCapabilities[id] !== true) { + gl.enable(id); + enabledCapabilities[id] = true; + } + } + function disable(id) { + if (enabledCapabilities[id] !== false) { + gl.disable(id); + enabledCapabilities[id] = false; + } + } + function bindFramebuffer(target, framebuffer) { + if (currentBoundFramebuffers[target] !== framebuffer) { + gl.bindFramebuffer(target, framebuffer); + currentBoundFramebuffers[target] = framebuffer; + if (target === gl.DRAW_FRAMEBUFFER) { + currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer; + } + if (target === gl.FRAMEBUFFER) { + currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer; + } + return true; + } + return false; + } + function drawBuffers(renderTarget, framebuffer) { + let drawBuffers2 = defaultDrawbuffers; + let needsUpdate = false; + if (renderTarget) { + drawBuffers2 = currentDrawbuffers.get(framebuffer); + if (drawBuffers2 === undefined) { + drawBuffers2 = []; + currentDrawbuffers.set(framebuffer, drawBuffers2); + } + const textures = renderTarget.textures; + if (drawBuffers2.length !== textures.length || drawBuffers2[0] !== gl.COLOR_ATTACHMENT0) { + for (let i = 0, il = textures.length;i < il; i++) { + drawBuffers2[i] = gl.COLOR_ATTACHMENT0 + i; + } + drawBuffers2.length = textures.length; + needsUpdate = true; + } + } else { + if (drawBuffers2[0] !== gl.BACK) { + drawBuffers2[0] = gl.BACK; + needsUpdate = true; + } + } + if (needsUpdate) { + gl.drawBuffers(drawBuffers2); + } + } + function useProgram(program) { + if (currentProgram !== program) { + gl.useProgram(program); + currentProgram = program; + return true; + } + return false; + } + const equationToGL = { + [AddEquation]: gl.FUNC_ADD, + [SubtractEquation]: gl.FUNC_SUBTRACT, + [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT + }; + equationToGL[MinEquation] = gl.MIN; + equationToGL[MaxEquation] = gl.MAX; + const factorToGL = { + [ZeroFactor]: gl.ZERO, + [OneFactor]: gl.ONE, + [SrcColorFactor]: gl.SRC_COLOR, + [SrcAlphaFactor]: gl.SRC_ALPHA, + [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE, + [DstColorFactor]: gl.DST_COLOR, + [DstAlphaFactor]: gl.DST_ALPHA, + [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR, + [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA, + [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR, + [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA, + [ConstantColorFactor]: gl.CONSTANT_COLOR, + [OneMinusConstantColorFactor]: gl.ONE_MINUS_CONSTANT_COLOR, + [ConstantAlphaFactor]: gl.CONSTANT_ALPHA, + [OneMinusConstantAlphaFactor]: gl.ONE_MINUS_CONSTANT_ALPHA + }; + function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha) { + if (blending === NoBlending) { + if (currentBlendingEnabled === true) { + disable(gl.BLEND); + currentBlendingEnabled = false; + } + return; + } + if (currentBlendingEnabled === false) { + enable(gl.BLEND); + currentBlendingEnabled = true; + } + if (blending !== CustomBlending) { + if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) { + if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) { + gl.blendEquation(gl.FUNC_ADD); + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; + } + if (premultipliedAlpha) { + switch (blending) { + case NormalBlending: + gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending: + gl.blendFunc(gl.ONE, gl.ONE); + break; + case SubtractiveBlending: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending: + gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } else { + switch (blending) { + case NormalBlending: + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending: + gl.blendFunc(gl.SRC_ALPHA, gl.ONE); + break; + case SubtractiveBlending: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending: + gl.blendFunc(gl.ZERO, gl.SRC_COLOR); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor.set(0, 0, 0); + currentBlendAlpha = 0; + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + } + return; + } + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) { + gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]); + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + } + if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) { + gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]); + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + } + if (blendColor.equals(currentBlendColor) === false || blendAlpha !== currentBlendAlpha) { + gl.blendColor(blendColor.r, blendColor.g, blendColor.b, blendAlpha); + currentBlendColor.copy(blendColor); + currentBlendAlpha = blendAlpha; + } + currentBlending = blending; + currentPremultipledAlpha = false; + } + function setMaterial(material, frontFaceCW) { + material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE); + let flipSided = material.side === BackSide; + if (frontFaceCW) + flipSided = !flipSided; + setFlipSided(flipSided); + material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha); + depthBuffer.setFunc(material.depthFunc); + depthBuffer.setTest(material.depthTest); + depthBuffer.setMask(material.depthWrite); + colorBuffer.setMask(material.colorWrite); + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest(stencilWrite); + if (stencilWrite) { + stencilBuffer.setMask(material.stencilWriteMask); + stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask); + stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass); + } + setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits); + material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + } + function setFlipSided(flipSided) { + if (currentFlipSided !== flipSided) { + if (flipSided) { + gl.frontFace(gl.CW); + } else { + gl.frontFace(gl.CCW); + } + currentFlipSided = flipSided; + } + } + function setCullFace(cullFace) { + if (cullFace !== CullFaceNone) { + enable(gl.CULL_FACE); + if (cullFace !== currentCullFace) { + if (cullFace === CullFaceBack) { + gl.cullFace(gl.BACK); + } else if (cullFace === CullFaceFront) { + gl.cullFace(gl.FRONT); + } else { + gl.cullFace(gl.FRONT_AND_BACK); + } + } + } else { + disable(gl.CULL_FACE); + } + currentCullFace = cullFace; + } + function setLineWidth(width2) { + if (width2 !== currentLineWidth) { + if (lineWidthAvailable) + gl.lineWidth(width2); + currentLineWidth = width2; + } + } + function setPolygonOffset(polygonOffset, factor, units) { + if (polygonOffset) { + enable(gl.POLYGON_OFFSET_FILL); + if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) { + gl.polygonOffset(factor, units); + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + } + } else { + disable(gl.POLYGON_OFFSET_FILL); + } + } + function setScissorTest(scissorTest) { + if (scissorTest) { + enable(gl.SCISSOR_TEST); + } else { + disable(gl.SCISSOR_TEST); + } + } + function activeTexture(webglSlot) { + if (webglSlot === undefined) + webglSlot = gl.TEXTURE0 + maxTextures - 1; + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + } + function bindTexture(webglType, webglTexture, webglSlot) { + if (webglSlot === undefined) { + if (currentTextureSlot === null) { + webglSlot = gl.TEXTURE0 + maxTextures - 1; + } else { + webglSlot = currentTextureSlot; + } + } + let boundTexture = currentBoundTextures[webglSlot]; + if (boundTexture === undefined) { + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[webglSlot] = boundTexture; + } + if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) { + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]); + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + } + } + function unbindTexture() { + const boundTexture = currentBoundTextures[currentTextureSlot]; + if (boundTexture !== undefined && boundTexture.type !== undefined) { + gl.bindTexture(boundTexture.type, null); + boundTexture.type = undefined; + boundTexture.texture = undefined; + } + } + function compressedTexImage2D() { + try { + gl.compressedTexImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexImage3D() { + try { + gl.compressedTexImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage2D() { + try { + gl.texSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage3D() { + try { + gl.texSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage2D() { + try { + gl.compressedTexSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage3D() { + try { + gl.compressedTexSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage2D() { + try { + gl.texStorage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage3D() { + try { + gl.texStorage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage2D() { + try { + gl.texImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage3D() { + try { + gl.texImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function scissor(scissor2) { + if (currentScissor.equals(scissor2) === false) { + gl.scissor(scissor2.x, scissor2.y, scissor2.z, scissor2.w); + currentScissor.copy(scissor2); + } + } + function viewport(viewport2) { + if (currentViewport.equals(viewport2) === false) { + gl.viewport(viewport2.x, viewport2.y, viewport2.z, viewport2.w); + currentViewport.copy(viewport2); + } + } + function updateUBOMapping(uniformsGroup, program) { + let mapping = uboProgramMap.get(program); + if (mapping === undefined) { + mapping = new WeakMap; + uboProgramMap.set(program, mapping); + } + let blockIndex = mapping.get(uniformsGroup); + if (blockIndex === undefined) { + blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name); + mapping.set(uniformsGroup, blockIndex); + } + } + function uniformBlockBinding(uniformsGroup, program) { + const mapping = uboProgramMap.get(program); + const blockIndex = mapping.get(uniformsGroup); + if (uboBindings.get(program) !== blockIndex) { + gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex); + uboBindings.set(program, blockIndex); + } + } + function reset() { + gl.disable(gl.BLEND); + gl.disable(gl.CULL_FACE); + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.POLYGON_OFFSET_FILL); + gl.disable(gl.SCISSOR_TEST); + gl.disable(gl.STENCIL_TEST); + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ZERO); + gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO); + gl.blendColor(0, 0, 0, 0); + gl.colorMask(true, true, true, true); + gl.clearColor(0, 0, 0, 0); + gl.depthMask(true); + gl.depthFunc(gl.LESS); + depthBuffer.setReversed(false); + gl.clearDepth(1); + gl.stencilMask(4294967295); + gl.stencilFunc(gl.ALWAYS, 0, 4294967295); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + gl.clearStencil(0); + gl.cullFace(gl.BACK); + gl.frontFace(gl.CCW); + gl.polygonOffset(0, 0); + gl.activeTexture(gl.TEXTURE0); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); + gl.useProgram(null); + gl.lineWidth(1); + gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); + gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); + enabledCapabilities = {}; + currentTextureSlot = null; + currentBoundTextures = {}; + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap; + defaultDrawbuffers = []; + currentProgram = null; + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor = new Color(0, 0, 0); + currentBlendAlpha = 0; + currentPremultipledAlpha = false; + currentFlipSided = null; + currentCullFace = null; + currentLineWidth = null; + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height); + currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height); + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + } + return { + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + enable, + disable, + bindFramebuffer, + drawBuffers, + useProgram, + setBlending, + setMaterial, + setFlipSided, + setCullFace, + setLineWidth, + setPolygonOffset, + setScissorTest, + activeTexture, + bindTexture, + unbindTexture, + compressedTexImage2D, + compressedTexImage3D, + texImage2D, + texImage3D, + updateUBOMapping, + uniformBlockBinding, + texStorage2D, + texStorage3D, + texSubImage2D, + texSubImage3D, + compressedTexSubImage2D, + compressedTexSubImage3D, + scissor, + viewport, + reset + }; +} +function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) { + const multisampledRTTExt = extensions.has("WEBGL_multisampled_render_to_texture") ? extensions.get("WEBGL_multisampled_render_to_texture") : null; + const supportsInvalidateFramebuffer = typeof navigator === "undefined" ? false : /OculusBrowser/g.test(navigator.userAgent); + const _imageDimensions = new Vector2; + const _videoTextures = new WeakMap; + let _canvas2; + const _sources = new WeakMap; + let useOffscreenCanvas = false; + try { + useOffscreenCanvas = typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null; + } catch (err) { + } + function createCanvas(width2, height2) { + return useOffscreenCanvas ? new OffscreenCanvas(width2, height2) : createElementNS("canvas"); + } + function resizeImage(image, needsNewCanvas, maxSize) { + let scale2 = 1; + const dimensions = getDimensions(image); + if (dimensions.width > maxSize || dimensions.height > maxSize) { + scale2 = maxSize / Math.max(dimensions.width, dimensions.height); + } + if (scale2 < 1) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + const width2 = Math.floor(scale2 * dimensions.width); + const height2 = Math.floor(scale2 * dimensions.height); + if (_canvas2 === undefined) + _canvas2 = createCanvas(width2, height2); + const canvas = needsNewCanvas ? createCanvas(width2, height2) : _canvas2; + canvas.width = width2; + canvas.height = height2; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, width2, height2); + console.warn("THREE.WebGLRenderer: Texture has been resized from (" + dimensions.width + "x" + dimensions.height + ") to (" + width2 + "x" + height2 + ")."); + return canvas; + } else { + if ("data" in image) { + console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + dimensions.width + "x" + dimensions.height + ")."); + } + return image; + } + } + return image; + } + function textureNeedsGenerateMipmaps(texture) { + return texture.generateMipmaps; + } + function generateMipmap(target) { + _gl.generateMipmap(target); + } + function getTargetType(texture) { + if (texture.isWebGLCubeRenderTarget) + return _gl.TEXTURE_CUBE_MAP; + if (texture.isWebGL3DRenderTarget) + return _gl.TEXTURE_3D; + if (texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture) + return _gl.TEXTURE_2D_ARRAY; + return _gl.TEXTURE_2D; + } + function getInternalFormat(internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false) { + if (internalFormatName !== null) { + if (_gl[internalFormatName] !== undefined) + return _gl[internalFormatName]; + console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + internalFormatName + "'"); + } + let internalFormat = glFormat; + if (glFormat === _gl.RED) { + if (glType === _gl.FLOAT) + internalFormat = _gl.R32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.R16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.R8; + } + if (glFormat === _gl.RED_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.R8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.R16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.R32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.R8I; + if (glType === _gl.SHORT) + internalFormat = _gl.R16I; + if (glType === _gl.INT) + internalFormat = _gl.R32I; + } + if (glFormat === _gl.RG) { + if (glType === _gl.FLOAT) + internalFormat = _gl.RG32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.RG16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RG8; + } + if (glFormat === _gl.RG_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RG8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RG16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RG32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RG8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RG16I; + if (glType === _gl.INT) + internalFormat = _gl.RG32I; + } + if (glFormat === _gl.RGB_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RGB8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RGB16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RGB32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RGB8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RGB16I; + if (glType === _gl.INT) + internalFormat = _gl.RGB32I; + } + if (glFormat === _gl.RGBA_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RGBA8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RGBA16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RGBA32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RGBA8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RGBA16I; + if (glType === _gl.INT) + internalFormat = _gl.RGBA32I; + } + if (glFormat === _gl.RGB) { + if (glType === _gl.UNSIGNED_INT_5_9_9_9_REV) + internalFormat = _gl.RGB9_E5; + } + if (glFormat === _gl.RGBA) { + const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer(colorSpace); + if (glType === _gl.FLOAT) + internalFormat = _gl.RGBA32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.RGBA16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = transfer === SRGBTransfer ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) + internalFormat = _gl.RGBA4; + if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) + internalFormat = _gl.RGB5_A1; + } + if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) { + extensions.get("EXT_color_buffer_float"); + } + return internalFormat; + } + function getInternalDepthFormat(useStencil, depthType) { + let glInternalFormat; + if (useStencil) { + if (depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + } else if (depthType === FloatType) { + glInternalFormat = _gl.DEPTH32F_STENCIL8; + } else if (depthType === UnsignedShortType) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment."); + } + } else { + if (depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type) { + glInternalFormat = _gl.DEPTH_COMPONENT24; + } else if (depthType === FloatType) { + glInternalFormat = _gl.DEPTH_COMPONENT32F; + } else if (depthType === UnsignedShortType) { + glInternalFormat = _gl.DEPTH_COMPONENT16; + } + } + return glInternalFormat; + } + function getMipLevels(texture, image) { + if (textureNeedsGenerateMipmaps(texture) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) { + return Math.log2(Math.max(image.width, image.height)) + 1; + } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) { + return texture.mipmaps.length; + } else if (texture.isCompressedTexture && Array.isArray(texture.image)) { + return image.mipmaps.length; + } else { + return 1; + } + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + deallocateTexture(texture); + if (texture.isVideoTexture) { + _videoTextures.delete(texture); + } + } + function onRenderTargetDispose(event) { + const renderTarget = event.target; + renderTarget.removeEventListener("dispose", onRenderTargetDispose); + deallocateRenderTarget(renderTarget); + } + function deallocateTexture(texture) { + const textureProperties = properties.get(texture); + if (textureProperties.__webglInit === undefined) + return; + const source = texture.source; + const webglTextures = _sources.get(source); + if (webglTextures) { + const webglTexture = webglTextures[textureProperties.__cacheKey]; + webglTexture.usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + if (Object.keys(webglTextures).length === 0) { + _sources.delete(source); + } + } + properties.remove(texture); + } + function deleteTexture(texture) { + const textureProperties = properties.get(texture); + _gl.deleteTexture(textureProperties.__webglTexture); + const source = texture.source; + const webglTextures = _sources.get(source); + delete webglTextures[textureProperties.__cacheKey]; + info.memory.textures--; + } + function deallocateRenderTarget(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTarget.depthTexture) { + renderTarget.depthTexture.dispose(); + properties.remove(renderTarget.depthTexture); + } + if (renderTarget.isWebGLCubeRenderTarget) { + for (let i = 0;i < 6; i++) { + if (Array.isArray(renderTargetProperties.__webglFramebuffer[i])) { + for (let level = 0;level < renderTargetProperties.__webglFramebuffer[i].length; level++) + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i][level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]); + } + if (renderTargetProperties.__webglDepthbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]); + } + } else { + if (Array.isArray(renderTargetProperties.__webglFramebuffer)) { + for (let level = 0;level < renderTargetProperties.__webglFramebuffer.length; level++) + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer); + } + if (renderTargetProperties.__webglDepthbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer); + if (renderTargetProperties.__webglMultisampledFramebuffer) + _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer); + if (renderTargetProperties.__webglColorRenderbuffer) { + for (let i = 0;i < renderTargetProperties.__webglColorRenderbuffer.length; i++) { + if (renderTargetProperties.__webglColorRenderbuffer[i]) + _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]); + } + } + if (renderTargetProperties.__webglDepthRenderbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer); + } + const textures = renderTarget.textures; + for (let i = 0, il = textures.length;i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture) { + _gl.deleteTexture(attachmentProperties.__webglTexture); + info.memory.textures--; + } + properties.remove(textures[i]); + } + properties.remove(renderTarget); + } + let textureUnits = 0; + function resetTextureUnits() { + textureUnits = 0; + } + function allocateTextureUnit() { + const textureUnit = textureUnits; + if (textureUnit >= capabilities.maxTextures) { + console.warn("THREE.WebGLTextures: Trying to use " + textureUnit + " texture units while this GPU supports only " + capabilities.maxTextures); + } + textureUnits += 1; + return textureUnit; + } + function getTextureCacheKey(texture) { + const array = []; + array.push(texture.wrapS); + array.push(texture.wrapT); + array.push(texture.wrapR || 0); + array.push(texture.magFilter); + array.push(texture.minFilter); + array.push(texture.anisotropy); + array.push(texture.internalFormat); + array.push(texture.format); + array.push(texture.type); + array.push(texture.generateMipmaps); + array.push(texture.premultiplyAlpha); + array.push(texture.flipY); + array.push(texture.unpackAlignment); + array.push(texture.colorSpace); + return array.join(); + } + function setTexture2D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isVideoTexture) + updateVideoTexture(texture); + if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { + const image = texture.image; + if (image === null) { + console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found."); + } else if (image.complete === false) { + console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete"); + } else { + uploadTexture(textureProperties, texture, slot); + return; + } + } + state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture2DArray(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture3D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTextureCube(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadCubeTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + const wrappingToGL = { + [RepeatWrapping]: _gl.REPEAT, + [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE, + [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT + }; + const filterToGL = { + [NearestFilter]: _gl.NEAREST, + [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST, + [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR, + [LinearFilter]: _gl.LINEAR, + [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST, + [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR + }; + const compareToGL = { + [NeverCompare]: _gl.NEVER, + [AlwaysCompare]: _gl.ALWAYS, + [LessCompare]: _gl.LESS, + [LessEqualCompare]: _gl.LEQUAL, + [EqualCompare]: _gl.EQUAL, + [GreaterEqualCompare]: _gl.GEQUAL, + [GreaterCompare]: _gl.GREATER, + [NotEqualCompare]: _gl.NOTEQUAL + }; + function setTextureParameters(textureType, texture) { + if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false && (texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter || texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter)) { + console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."); + } + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]); + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]); + if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) { + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]); + } + _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]); + _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]); + if (texture.compareFunction) { + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE); + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[texture.compareFunction]); + } + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + if (texture.magFilter === NearestFilter) + return; + if (texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter) + return; + if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false) + return; + if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy())); + properties.get(texture).__currentAnisotropy = texture.anisotropy; + } + } + } + function initTexture(textureProperties, texture) { + let forceUpload = false; + if (textureProperties.__webglInit === undefined) { + textureProperties.__webglInit = true; + texture.addEventListener("dispose", onTextureDispose); + } + const source = texture.source; + let webglTextures = _sources.get(source); + if (webglTextures === undefined) { + webglTextures = {}; + _sources.set(source, webglTextures); + } + const textureCacheKey = getTextureCacheKey(texture); + if (textureCacheKey !== textureProperties.__cacheKey) { + if (webglTextures[textureCacheKey] === undefined) { + webglTextures[textureCacheKey] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + info.memory.textures++; + forceUpload = true; + } + webglTextures[textureCacheKey].usedTimes++; + const webglTexture = webglTextures[textureProperties.__cacheKey]; + if (webglTexture !== undefined) { + webglTextures[textureProperties.__cacheKey].usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + } + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[textureCacheKey].texture; + } + return forceUpload; + } + function uploadTexture(textureProperties, texture, slot) { + let textureType = _gl.TEXTURE_2D; + if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) + textureType = _gl.TEXTURE_2D_ARRAY; + if (texture.isData3DTexture) + textureType = _gl.TEXTURE_3D; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + let image = resizeImage(texture.image, false, capabilities.maxTextureSize); + image = verifyColorSpace(texture, image); + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + let glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture); + setTextureParameters(textureType, texture); + let mipmap; + const mipmaps = texture.mipmaps; + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; + const dataReady = source.dataReady; + const levels = getMipLevels(texture, image); + if (texture.isDepthTexture) { + glInternalFormat = getInternalDepthFormat(texture.format === DepthStencilFormat, texture.type); + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height); + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null); + } + } + } else if (texture.isDataTexture) { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data); + } + } + } else if (texture.isCompressedTexture) { + if (texture.isCompressedArrayTexture) { + if (useTexStorage && allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength(mipmap.width, mipmap.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = mipmap.data.subarray(layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT, (layerIndex + 1) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT); + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData); + } + texture.clearLayerUpdates(); + } else { + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data); + } + } + } else { + state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data); + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data); + } + } + } + } else { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else if (texture.isDataArrayTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength(image.width, image.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = image.data.subarray(layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT, (layerIndex + 1) * layerByteLength / image.data.BYTES_PER_ELEMENT); + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData); + } + texture.clearLayerUpdates(); + } else { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isData3DTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } else { + state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isFramebufferTexture) { + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } else { + let { width: width2, height: height2 } = image; + for (let i = 0;i < levels; i++) { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width2, height2, 0, glFormat, glType, null); + width2 >>= 1; + height2 >>= 1; + } + } + } + } else { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + const dimensions = getDimensions(mipmaps[0]); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + const dimensions = getDimensions(image); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image); + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(textureType); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) + texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function uploadCubeTexture(textureProperties, texture, slot) { + if (texture.image.length !== 6) + return; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture; + const isDataTexture = texture.image[0] && texture.image[0].isDataTexture; + const cubeImage = []; + for (let i = 0;i < 6; i++) { + if (!isCompressed && !isDataTexture) { + cubeImage[i] = resizeImage(texture.image[i], true, capabilities.maxCubemapSize); + } else { + cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i]; + } + cubeImage[i] = verifyColorSpace(texture, cubeImage[i]); + } + const image = cubeImage[0], glFormat = utils.convert(texture.format, texture.colorSpace), glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; + const dataReady = source.dataReady; + let levels = getMipLevels(texture, image); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + let mipmaps; + if (isCompressed) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height); + } + for (let i = 0;i < 6; i++) { + mipmaps = cubeImage[i].mipmaps; + for (let j = 0;j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else { + mipmaps = texture.mipmaps; + if (useTexStorage && allocateMemory) { + if (mipmaps.length > 0) + levels++; + const dimensions = getDimensions(cubeImage[0]); + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0;i < 6; i++) { + if (isDataTexture) { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data); + } + for (let j = 0;j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + const mipmapImage = mipmap.image[i].image; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data); + } + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]); + } + for (let j = 0;j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]); + } + } + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) + texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget, level) { + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + textureProperties.__renderTarget = renderTarget; + if (!renderTargetProperties.__hasExternalTextures) { + const width2 = Math.max(1, renderTarget.width >> level); + const height2 = Math.max(1, renderTarget.height >> level); + if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) { + state.texImage3D(textureTarget, level, glInternalFormat, width2, height2, renderTarget.depth, 0, glFormat, glType, null); + } else { + state.texImage2D(textureTarget, level, glInternalFormat, width2, height2, 0, glFormat, glType, null); + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples(renderTarget)); + } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) { + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null; + const glInternalFormat = getInternalDepthFormat(renderTarget.stencilBuffer, depthType); + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const samples = getRenderTargetSamples(renderTarget); + const isUseMultisampledRTT = useMultisampledRTT(renderTarget); + if (isUseMultisampledRTT) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (isMultisample) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } else { + const textures = renderTarget.textures; + for (let i = 0;i < textures.length; i++) { + const texture = textures[i]; + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const samples = getRenderTargetSamples(renderTarget); + if (isMultisample && useMultisampledRTT(renderTarget) === false) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + } + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + } + function setupDepthTexture(framebuffer, renderTarget) { + const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget; + if (isCube) + throw new Error("Depth Texture with cube render targets is not supported"); + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) { + throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); + } + const textureProperties = properties.get(renderTarget.depthTexture); + textureProperties.__renderTarget = renderTarget; + if (!textureProperties.__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) { + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + } + setTexture2D(renderTarget.depthTexture, 0); + const webglDepthTexture = textureProperties.__webglTexture; + const samples = getRenderTargetSamples(renderTarget); + if (renderTarget.depthTexture.format === DepthFormat) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else if (renderTarget.depthTexture.format === DepthStencilFormat) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else { + throw new Error("Unknown depthTexture format"); + } + } + function setupDepthRenderbuffer(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + if (renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__depthDisposeCallback) { + renderTargetProperties.__depthDisposeCallback(); + } + if (depthTexture) { + const disposeEvent = () => { + delete renderTargetProperties.__boundDepthTexture; + delete renderTargetProperties.__depthDisposeCallback; + depthTexture.removeEventListener("dispose", disposeEvent); + }; + depthTexture.addEventListener("dispose", disposeEvent); + renderTargetProperties.__depthDisposeCallback = disposeEvent; + } + renderTargetProperties.__boundDepthTexture = depthTexture; + } + if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) { + if (isCube) + throw new Error("target.depthTexture not supported in Cube render targets"); + setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget); + } else { + if (isCube) { + renderTargetProperties.__webglDepthbuffer = []; + for (let i = 0;i < 6; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]); + if (renderTargetProperties.__webglDepthbuffer[i] === undefined) { + renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer[i]; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } else { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + if (renderTargetProperties.__webglDepthbuffer === undefined) { + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function rebindTextures(renderTarget, colorTexture, depthTexture) { + const renderTargetProperties = properties.get(renderTarget); + if (colorTexture !== undefined) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0); + } + if (depthTexture !== undefined) { + setupDepthRenderbuffer(renderTarget); + } + } + function setupRenderTarget(renderTarget) { + const texture = renderTarget.texture; + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + renderTarget.addEventListener("dispose", onRenderTargetDispose); + const textures = renderTarget.textures; + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + const isMultipleRenderTargets = textures.length > 1; + if (!isMultipleRenderTargets) { + if (textureProperties.__webglTexture === undefined) { + textureProperties.__webglTexture = _gl.createTexture(); + } + textureProperties.__version = texture.version; + info.memory.textures++; + } + if (isCube) { + renderTargetProperties.__webglFramebuffer = []; + for (let i = 0;i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer[i] = []; + for (let level = 0;level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[i][level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer(); + } + } + } else { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer = []; + for (let level = 0;level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + } + if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length;i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture === undefined) { + attachmentProperties.__webglTexture = _gl.createTexture(); + info.memory.textures++; + } + } + } + if (renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + for (let i = 0;i < textures.length; i++) { + const texture2 = textures[i]; + renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer(); + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const glFormat = utils.convert(texture2.format, texture2.colorSpace); + const glType = utils.convert(texture2.type); + const glInternalFormat = getInternalFormat(texture2.internalFormat, glFormat, glType, texture2.colorSpace, renderTarget.isXRRenderTarget === true); + const samples = getRenderTargetSamples(renderTarget); + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + if (renderTarget.depthBuffer) { + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + } + if (isCube) { + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + for (let i = 0;i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0;level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i][level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0); + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + state.unbindTexture(); + } else if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length;i < il; i++) { + const attachment = textures[i]; + const attachmentProperties = properties.get(attachment); + state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_2D, attachment); + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0); + if (textureNeedsGenerateMipmaps(attachment)) { + generateMipmap(_gl.TEXTURE_2D); + } + } + state.unbindTexture(); + } else { + let glTextureType = _gl.TEXTURE_2D; + if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + } + state.bindTexture(glTextureType, textureProperties.__webglTexture); + setTextureParameters(glTextureType, texture); + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0;level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0); + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(glTextureType); + } + state.unbindTexture(); + } + if (renderTarget.depthBuffer) { + setupDepthRenderbuffer(renderTarget); + } + } + function updateRenderTargetMipmap(renderTarget) { + const textures = renderTarget.textures; + for (let i = 0, il = textures.length;i < il; i++) { + const texture = textures[i]; + if (textureNeedsGenerateMipmaps(texture)) { + const targetType = getTargetType(renderTarget); + const webglTexture = properties.get(texture).__webglTexture; + state.bindTexture(targetType, webglTexture); + generateMipmap(targetType); + state.unbindTexture(); + } + } + } + const invalidationArrayRead = []; + const invalidationArrayDraw = []; + function updateMultisampleRenderTarget(renderTarget) { + if (renderTarget.samples > 0) { + if (useMultisampledRTT(renderTarget) === false) { + const textures = renderTarget.textures; + const width2 = renderTarget.width; + const height2 = renderTarget.height; + let mask2 = _gl.COLOR_BUFFER_BIT; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get(renderTarget); + const isMultipleRenderTargets = textures.length > 1; + if (isMultipleRenderTargets) { + for (let i = 0;i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null); + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + for (let i = 0;i < textures.length; i++) { + if (renderTarget.resolveDepthBuffer) { + if (renderTarget.depthBuffer) + mask2 |= _gl.DEPTH_BUFFER_BIT; + if (renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer) + mask2 |= _gl.STENCIL_BUFFER_BIT; + } + if (isMultipleRenderTargets) { + _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0); + } + _gl.blitFramebuffer(0, 0, width2, height2, 0, 0, width2, height2, mask2, _gl.NEAREST); + if (supportsInvalidateFramebuffer === true) { + invalidationArrayRead.length = 0; + invalidationArrayDraw.length = 0; + invalidationArrayRead.push(_gl.COLOR_ATTACHMENT0 + i); + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false) { + invalidationArrayRead.push(depthStyle); + invalidationArrayDraw.push(depthStyle); + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, invalidationArrayDraw); + } + _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArrayRead); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + if (isMultipleRenderTargets) { + for (let i = 0;i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0); + } + } + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + } else { + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer) { + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]); + } + } + } + } + function getRenderTargetSamples(renderTarget) { + return Math.min(capabilities.maxSamples, renderTarget.samples); + } + function useMultisampledRTT(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + return renderTarget.samples > 0 && extensions.has("WEBGL_multisampled_render_to_texture") === true && renderTargetProperties.__useRenderToTexture !== false; + } + function updateVideoTexture(texture) { + const frame = info.render.frame; + if (_videoTextures.get(texture) !== frame) { + _videoTextures.set(texture, frame); + texture.update(); + } + } + function verifyColorSpace(texture, image) { + const colorSpace = texture.colorSpace; + const format = texture.format; + const type = texture.type; + if (texture.isCompressedTexture === true || texture.isVideoTexture === true) + return image; + if (colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace) { + if (ColorManagement.getTransfer(colorSpace) === SRGBTransfer) { + if (format !== RGBAFormat || type !== UnsignedByteType) { + console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."); + } + } else { + console.error("THREE.WebGLTextures: Unsupported texture color space:", colorSpace); + } + } + return image; + } + function getDimensions(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement) { + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + } else if (typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + } else { + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + } + return _imageDimensions; + } + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; +} +function WebGLUtils(gl, extensions) { + function convert(p, colorSpace = NoColorSpace) { + let extension; + const transfer = ColorManagement.getTransfer(colorSpace); + if (p === UnsignedByteType) + return gl.UNSIGNED_BYTE; + if (p === UnsignedShort4444Type) + return gl.UNSIGNED_SHORT_4_4_4_4; + if (p === UnsignedShort5551Type) + return gl.UNSIGNED_SHORT_5_5_5_1; + if (p === UnsignedInt5999Type) + return gl.UNSIGNED_INT_5_9_9_9_REV; + if (p === ByteType) + return gl.BYTE; + if (p === ShortType) + return gl.SHORT; + if (p === UnsignedShortType) + return gl.UNSIGNED_SHORT; + if (p === IntType) + return gl.INT; + if (p === UnsignedIntType) + return gl.UNSIGNED_INT; + if (p === FloatType) + return gl.FLOAT; + if (p === HalfFloatType) + return gl.HALF_FLOAT; + if (p === AlphaFormat) + return gl.ALPHA; + if (p === RGBFormat) + return gl.RGB; + if (p === RGBAFormat) + return gl.RGBA; + if (p === LuminanceFormat) + return gl.LUMINANCE; + if (p === LuminanceAlphaFormat) + return gl.LUMINANCE_ALPHA; + if (p === DepthFormat) + return gl.DEPTH_COMPONENT; + if (p === DepthStencilFormat) + return gl.DEPTH_STENCIL; + if (p === RedFormat) + return gl.RED; + if (p === RedIntegerFormat) + return gl.RED_INTEGER; + if (p === RGFormat) + return gl.RG; + if (p === RGIntegerFormat) + return gl.RG_INTEGER; + if (p === RGBAIntegerFormat) + return gl.RGBA_INTEGER; + if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) { + if (transfer === SRGBTransfer) { + extension = extensions.get("WEBGL_compressed_texture_s3tc_srgb"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format) + return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + } else { + return null; + } + } else { + extension = extensions.get("WEBGL_compressed_texture_s3tc"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format) + return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format) + return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format) + return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format) + return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + } else { + return null; + } + } + } + if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) { + extension = extensions.get("WEBGL_compressed_texture_pvrtc"); + if (extension !== null) { + if (p === RGB_PVRTC_4BPPV1_Format) + return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if (p === RGB_PVRTC_2BPPV1_Format) + return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if (p === RGBA_PVRTC_4BPPV1_Format) + return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if (p === RGBA_PVRTC_2BPPV1_Format) + return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + } else { + return null; + } + } + if (p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) { + extension = extensions.get("WEBGL_compressed_texture_etc"); + if (extension !== null) { + if (p === RGB_ETC1_Format || p === RGB_ETC2_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if (p === RGBA_ETC2_EAC_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + } else { + return null; + } + } + if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format) { + extension = extensions.get("WEBGL_compressed_texture_astc"); + if (extension !== null) { + if (p === RGBA_ASTC_4x4_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if (p === RGBA_ASTC_5x4_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if (p === RGBA_ASTC_5x5_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if (p === RGBA_ASTC_6x5_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if (p === RGBA_ASTC_6x6_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if (p === RGBA_ASTC_8x5_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if (p === RGBA_ASTC_8x6_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if (p === RGBA_ASTC_8x8_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if (p === RGBA_ASTC_10x5_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if (p === RGBA_ASTC_10x6_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if (p === RGBA_ASTC_10x8_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if (p === RGBA_ASTC_10x10_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if (p === RGBA_ASTC_12x10_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if (p === RGBA_ASTC_12x12_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + } else { + return null; + } + } + if (p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format) { + extension = extensions.get("EXT_texture_compression_bptc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + if (p === RGB_BPTC_SIGNED_Format) + return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; + if (p === RGB_BPTC_UNSIGNED_Format) + return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; + } else { + return null; + } + } + if (p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format) { + extension = extensions.get("EXT_texture_compression_rgtc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format) + return extension.COMPRESSED_RED_RGTC1_EXT; + if (p === SIGNED_RED_RGTC1_Format) + return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if (p === RED_GREEN_RGTC2_Format) + return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if (p === SIGNED_RED_GREEN_RGTC2_Format) + return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + } else { + return null; + } + } + if (p === UnsignedInt248Type) + return gl.UNSIGNED_INT_24_8; + return gl[p] !== undefined ? gl[p] : null; + } + return { convert }; +} +var _occlusion_vertex = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; +var _occlusion_fragment = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; + +class WebXRDepthSensing { + constructor() { + this.texture = null; + this.mesh = null; + this.depthNear = 0; + this.depthFar = 0; + } + init(renderer2, depthData, renderState) { + if (this.texture === null) { + const texture = new Texture; + const texProps = renderer2.properties.get(texture); + texProps.__webglTexture = depthData.texture; + if (depthData.depthNear !== renderState.depthNear || depthData.depthFar !== renderState.depthFar) { + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + } + this.texture = texture; + } + } + getMesh(cameraXR) { + if (this.texture !== null) { + if (this.mesh === null) { + const viewport = cameraXR.cameras[0].viewport; + const material = new ShaderMaterial({ + vertexShader: _occlusion_vertex, + fragmentShader: _occlusion_fragment, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + }); + this.mesh = new Mesh(new PlaneGeometry(20, 20), material); + } + } + return this.mesh; + } + reset() { + this.texture = null; + this.mesh = null; + } + getDepthTexture() { + return this.texture; + } +} + +class WebXRManager extends EventDispatcher { + constructor(renderer2, gl) { + super(); + const scope = this; + let session = null; + let framebufferScaleFactor = 1; + let referenceSpace = null; + let referenceSpaceType = "local-floor"; + let foveation = 1; + let customReferenceSpace = null; + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const depthSensing = new WebXRDepthSensing; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + const controllers = []; + const controllerInputSources = []; + const currentSize = new Vector2; + let currentPixelRatio = null; + const cameraL = new PerspectiveCamera; + cameraL.viewport = new Vector4; + const cameraR = new PerspectiveCamera; + cameraR.viewport = new Vector4; + const cameras = [cameraL, cameraR]; + const cameraXR = new ArrayCamera; + let _currentDepthNear = null; + let _currentDepthFar = null; + this.cameraAutoUpdate = true; + this.enabled = false; + this.isPresenting = false; + this.getController = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController; + controllers[index2] = controller; + } + return controller.getTargetRaySpace(); + }; + this.getControllerGrip = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController; + controllers[index2] = controller; + } + return controller.getGripSpace(); + }; + this.getHand = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController; + controllers[index2] = controller; + } + return controller.getHandSpace(); + }; + function onSessionEvent(event) { + const controllerIndex = controllerInputSources.indexOf(event.inputSource); + if (controllerIndex === -1) { + return; + } + const controller = controllers[controllerIndex]; + if (controller !== undefined) { + controller.update(event.inputSource, event.frame, customReferenceSpace || referenceSpace); + controller.dispatchEvent({ type: event.type, data: event.inputSource }); + } + } + function onSessionEnd() { + session.removeEventListener("select", onSessionEvent); + session.removeEventListener("selectstart", onSessionEvent); + session.removeEventListener("selectend", onSessionEvent); + session.removeEventListener("squeeze", onSessionEvent); + session.removeEventListener("squeezestart", onSessionEvent); + session.removeEventListener("squeezeend", onSessionEvent); + session.removeEventListener("end", onSessionEnd); + session.removeEventListener("inputsourceschange", onInputSourcesChange); + for (let i = 0;i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + if (inputSource === null) + continue; + controllerInputSources[i] = null; + controllers[i].disconnect(inputSource); + } + _currentDepthNear = null; + _currentDepthFar = null; + depthSensing.reset(); + renderer2.setRenderTarget(initialRenderTarget); + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + animation.stop(); + scope.isPresenting = false; + renderer2.setPixelRatio(currentPixelRatio); + renderer2.setSize(currentSize.width, currentSize.height, false); + scope.dispatchEvent({ type: "sessionend" }); + } + this.setFramebufferScaleFactor = function(value2) { + framebufferScaleFactor = value2; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting."); + } + }; + this.setReferenceSpaceType = function(value2) { + referenceSpaceType = value2; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change reference space type while presenting."); + } + }; + this.getReferenceSpace = function() { + return customReferenceSpace || referenceSpace; + }; + this.setReferenceSpace = function(space) { + customReferenceSpace = space; + }; + this.getBaseLayer = function() { + return glProjLayer !== null ? glProjLayer : glBaseLayer; + }; + this.getBinding = function() { + return glBinding; + }; + this.getFrame = function() { + return xrFrame; + }; + this.getSession = function() { + return session; + }; + this.setSession = async function(value2) { + session = value2; + if (session !== null) { + initialRenderTarget = renderer2.getRenderTarget(); + session.addEventListener("select", onSessionEvent); + session.addEventListener("selectstart", onSessionEvent); + session.addEventListener("selectend", onSessionEvent); + session.addEventListener("squeeze", onSessionEvent); + session.addEventListener("squeezestart", onSessionEvent); + session.addEventListener("squeezeend", onSessionEvent); + session.addEventListener("end", onSessionEnd); + session.addEventListener("inputsourceschange", onInputSourcesChange); + if (attributes.xrCompatible !== true) { + await gl.makeXRCompatible(); + } + currentPixelRatio = renderer2.getPixelRatio(); + renderer2.getSize(currentSize); + const useLayers = typeof XRWebGLBinding !== "undefined" && "createProjectionLayer" in XRWebGLBinding.prototype; + if (!useLayers) { + const layerInit = { + antialias: attributes.antialias, + alpha: true, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor + }; + glBaseLayer = new XRWebGLLayer(session, gl, layerInit); + session.updateRenderState({ baseLayer: glBaseLayer }); + renderer2.setPixelRatio(1); + renderer2.setSize(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false); + newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, { + format: RGBAFormat, + type: UnsignedByteType, + colorSpace: renderer2.outputColorSpace, + stencilBuffer: attributes.stencil + }); + } else { + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + if (attributes.depth) { + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; + } + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + glBinding = new XRWebGLBinding(session, gl); + glProjLayer = glBinding.createProjectionLayer(projectionlayerInit); + session.updateRenderState({ layers: [glProjLayer] }); + renderer2.setPixelRatio(1); + renderer2.setSize(glProjLayer.textureWidth, glProjLayer.textureHeight, false); + newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat), + stencilBuffer: attributes.stencil, + colorSpace: renderer2.outputColorSpace, + samples: attributes.antialias ? 4 : 0, + resolveDepthBuffer: glProjLayer.ignoreDepthValues === false + }); + } + newRenderTarget.isXRRenderTarget = true; + this.setFoveation(foveation); + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace(referenceSpaceType); + animation.setContext(session); + animation.start(); + scope.isPresenting = true; + scope.dispatchEvent({ type: "sessionstart" }); + } + }; + this.getEnvironmentBlendMode = function() { + if (session !== null) { + return session.environmentBlendMode; + } + }; + this.getDepthTexture = function() { + return depthSensing.getDepthTexture(); + }; + function onInputSourcesChange(event) { + for (let i = 0;i < event.removed.length; i++) { + const inputSource = event.removed[i]; + const index2 = controllerInputSources.indexOf(inputSource); + if (index2 >= 0) { + controllerInputSources[index2] = null; + controllers[index2].disconnect(inputSource); + } + } + for (let i = 0;i < event.added.length; i++) { + const inputSource = event.added[i]; + let controllerIndex = controllerInputSources.indexOf(inputSource); + if (controllerIndex === -1) { + for (let i2 = 0;i2 < controllers.length; i2++) { + if (i2 >= controllerInputSources.length) { + controllerInputSources.push(inputSource); + controllerIndex = i2; + break; + } else if (controllerInputSources[i2] === null) { + controllerInputSources[i2] = inputSource; + controllerIndex = i2; + break; + } + } + if (controllerIndex === -1) + break; + } + const controller = controllers[controllerIndex]; + if (controller) { + controller.connect(inputSource); + } + } + } + const cameraLPos = new Vector3; + const cameraRPos = new Vector3; + function setProjectionFromUnion(camera, cameraL2, cameraR2) { + cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld); + cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld); + const ipd = cameraLPos.distanceTo(cameraRPos); + const projL = cameraL2.projectionMatrix.elements; + const projR = cameraR2.projectionMatrix.elements; + const near = projL[14] / (projL[10] - 1); + const far = projL[14] / (projL[10] + 1); + const topFov = (projL[9] + 1) / projL[5]; + const bottomFov = (projL[9] - 1) / projL[5]; + const leftFov = (projL[8] - 1) / projL[0]; + const rightFov = (projR[8] + 1) / projR[0]; + const left = near * leftFov; + const right = near * rightFov; + const zOffset = ipd / (-leftFov + rightFov); + const xOffset = zOffset * -leftFov; + cameraL2.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale); + camera.translateX(xOffset); + camera.translateZ(zOffset); + camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale); + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + if (projL[10] === -1) { + camera.projectionMatrix.copy(cameraL2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraL2.projectionMatrixInverse); + } else { + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + (ipd - xOffset); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + } + } + function updateCamera(camera, parent2) { + if (parent2 === null) { + camera.matrixWorld.copy(camera.matrix); + } else { + camera.matrixWorld.multiplyMatrices(parent2.matrixWorld, camera.matrix); + } + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + } + this.updateCamera = function(camera) { + if (session === null) + return; + let depthNear = camera.near; + let depthFar = camera.far; + if (depthSensing.texture !== null) { + if (depthSensing.depthNear > 0) + depthNear = depthSensing.depthNear; + if (depthSensing.depthFar > 0) + depthFar = depthSensing.depthFar; + } + cameraXR.near = cameraR.near = cameraL.near = depthNear; + cameraXR.far = cameraR.far = cameraL.far = depthFar; + if (_currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far) { + session.updateRenderState({ + depthNear: cameraXR.near, + depthFar: cameraXR.far + }); + _currentDepthNear = cameraXR.near; + _currentDepthFar = cameraXR.far; + } + cameraL.layers.mask = camera.layers.mask | 2; + cameraR.layers.mask = camera.layers.mask | 4; + cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask; + const parent2 = camera.parent; + const cameras2 = cameraXR.cameras; + updateCamera(cameraXR, parent2); + for (let i = 0;i < cameras2.length; i++) { + updateCamera(cameras2[i], parent2); + } + if (cameras2.length === 2) { + setProjectionFromUnion(cameraXR, cameraL, cameraR); + } else { + cameraXR.projectionMatrix.copy(cameraL.projectionMatrix); + } + updateUserCamera(camera, cameraXR, parent2); + }; + function updateUserCamera(camera, cameraXR2, parent2) { + if (parent2 === null) { + camera.matrix.copy(cameraXR2.matrixWorld); + } else { + camera.matrix.copy(parent2.matrixWorld); + camera.matrix.invert(); + camera.matrix.multiply(cameraXR2.matrixWorld); + } + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.updateMatrixWorld(true); + camera.projectionMatrix.copy(cameraXR2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraXR2.projectionMatrixInverse); + if (camera.isPerspectiveCamera) { + camera.fov = RAD2DEG * 2 * Math.atan(1 / camera.projectionMatrix.elements[5]); + camera.zoom = 1; + } + } + this.getCamera = function() { + return cameraXR; + }; + this.getFoveation = function() { + if (glProjLayer === null && glBaseLayer === null) { + return; + } + return foveation; + }; + this.setFoveation = function(value2) { + foveation = value2; + if (glProjLayer !== null) { + glProjLayer.fixedFoveation = value2; + } + if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) { + glBaseLayer.fixedFoveation = value2; + } + }; + this.hasDepthSensing = function() { + return depthSensing.texture !== null; + }; + this.getDepthSensingMesh = function() { + return depthSensing.getMesh(cameraXR); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time2, frame) { + pose = frame.getViewerPose(customReferenceSpace || referenceSpace); + xrFrame = frame; + if (pose !== null) { + const views = pose.views; + if (glBaseLayer !== null) { + renderer2.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer); + renderer2.setRenderTarget(newRenderTarget); + } + let cameraXRNeedsUpdate = false; + if (views.length !== cameraXR.cameras.length) { + cameraXR.cameras.length = 0; + cameraXRNeedsUpdate = true; + } + for (let i = 0;i < views.length; i++) { + const view = views[i]; + let viewport = null; + if (glBaseLayer !== null) { + viewport = glBaseLayer.getViewport(view); + } else { + const glSubImage = glBinding.getViewSubImage(glProjLayer, view); + viewport = glSubImage.viewport; + if (i === 0) { + renderer2.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture); + renderer2.setRenderTarget(newRenderTarget); + } + } + let camera = cameras[i]; + if (camera === undefined) { + camera = new PerspectiveCamera; + camera.layers.enable(i); + camera.viewport = new Vector4; + cameras[i] = camera; + } + camera.matrix.fromArray(view.transform.matrix); + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.projectionMatrix.fromArray(view.projectionMatrix); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height); + if (i === 0) { + cameraXR.matrix.copy(camera.matrix); + cameraXR.matrix.decompose(cameraXR.position, cameraXR.quaternion, cameraXR.scale); + } + if (cameraXRNeedsUpdate === true) { + cameraXR.cameras.push(camera); + } + } + const enabledFeatures = session.enabledFeatures; + const gpuDepthSensingEnabled = enabledFeatures && enabledFeatures.includes("depth-sensing") && session.depthUsage == "gpu-optimized"; + if (gpuDepthSensingEnabled && glBinding) { + const depthData = glBinding.getDepthInformation(views[0]); + if (depthData && depthData.isValid && depthData.texture) { + depthSensing.init(renderer2, depthData, session.renderState); + } + } + } + for (let i = 0;i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + const controller = controllers[i]; + if (inputSource !== null && controller !== undefined) { + controller.update(inputSource, frame, customReferenceSpace || referenceSpace); + } + } + if (onAnimationFrameCallback) + onAnimationFrameCallback(time2, frame); + if (frame.detectedPlanes) { + scope.dispatchEvent({ type: "planesdetected", data: frame }); + } + xrFrame = null; + } + const animation = new WebGLAnimation; + animation.setAnimationLoop(onAnimationFrame); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + }; + this.dispose = function() { + }; + } +} +var _e1 = /* @__PURE__ */ new Euler; +var _m12 = /* @__PURE__ */ new Matrix4; +function WebGLMaterials(renderer2, properties) { + function refreshTransformUniform(map2, uniform) { + if (map2.matrixAutoUpdate === true) { + map2.updateMatrix(); + } + uniform.value.copy(map2.matrix); + } + function refreshFogUniforms(uniforms, fog) { + fog.color.getRGB(uniforms.fogColor.value, getUnlitUniformColorSpace(renderer2)); + if (fog.isFog) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + } else if (fog.isFogExp2) { + uniforms.fogDensity.value = fog.density; + } + } + function refreshMaterialUniforms(uniforms, material, pixelRatio, height2, transmissionRenderTarget) { + if (material.isMeshBasicMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshLambertMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshToonMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsToon(uniforms, material); + } else if (material.isMeshPhongMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsPhong(uniforms, material); + } else if (material.isMeshStandardMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsStandard(uniforms, material); + if (material.isMeshPhysicalMaterial) { + refreshUniformsPhysical(uniforms, material, transmissionRenderTarget); + } + } else if (material.isMeshMatcapMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsMatcap(uniforms, material); + } else if (material.isMeshDepthMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshDistanceMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsDistance(uniforms, material); + } else if (material.isMeshNormalMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isLineBasicMaterial) { + refreshUniformsLine(uniforms, material); + if (material.isLineDashedMaterial) { + refreshUniformsDash(uniforms, material); + } + } else if (material.isPointsMaterial) { + refreshUniformsPoints(uniforms, material, pixelRatio, height2); + } else if (material.isSpriteMaterial) { + refreshUniformsSprites(uniforms, material); + } else if (material.isShadowMaterial) { + uniforms.color.value.copy(material.color); + uniforms.opacity.value = material.opacity; + } else if (material.isShaderMaterial) { + material.uniformsNeedUpdate = false; + } + } + function refreshUniformsCommon(uniforms, material) { + uniforms.opacity.value = material.opacity; + if (material.color) { + uniforms.diffuse.value.copy(material.color); + } + if (material.emissive) { + uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity); + } + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.bumpMap) { + uniforms.bumpMap.value = material.bumpMap; + refreshTransformUniform(material.bumpMap, uniforms.bumpMapTransform); + uniforms.bumpScale.value = material.bumpScale; + if (material.side === BackSide) { + uniforms.bumpScale.value *= -1; + } + } + if (material.normalMap) { + uniforms.normalMap.value = material.normalMap; + refreshTransformUniform(material.normalMap, uniforms.normalMapTransform); + uniforms.normalScale.value.copy(material.normalScale); + if (material.side === BackSide) { + uniforms.normalScale.value.negate(); + } + } + if (material.displacementMap) { + uniforms.displacementMap.value = material.displacementMap; + refreshTransformUniform(material.displacementMap, uniforms.displacementMapTransform); + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + } + if (material.emissiveMap) { + uniforms.emissiveMap.value = material.emissiveMap; + refreshTransformUniform(material.emissiveMap, uniforms.emissiveMapTransform); + } + if (material.specularMap) { + uniforms.specularMap.value = material.specularMap; + refreshTransformUniform(material.specularMap, uniforms.specularMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + const materialProperties = properties.get(material); + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; + if (envMap) { + uniforms.envMap.value = envMap; + _e1.copy(envMapRotation); + _e1.x *= -1; + _e1.y *= -1; + _e1.z *= -1; + if (envMap.isCubeTexture && envMap.isRenderTargetTexture === false) { + _e1.y *= -1; + _e1.z *= -1; + } + uniforms.envMapRotation.value.setFromMatrix4(_m12.makeRotationFromEuler(_e1)); + uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + } + if (material.lightMap) { + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; + refreshTransformUniform(material.lightMap, uniforms.lightMapTransform); + } + if (material.aoMap) { + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + refreshTransformUniform(material.aoMap, uniforms.aoMapTransform); + } + } + function refreshUniformsLine(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + } + function refreshUniformsDash(uniforms, material) { + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + } + function refreshUniformsPoints(uniforms, material, pixelRatio, height2) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height2 * 0.5; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.uvTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsSprites(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsPhong(uniforms, material) { + uniforms.specular.value.copy(material.specular); + uniforms.shininess.value = Math.max(material.shininess, 0.0001); + } + function refreshUniformsToon(uniforms, material) { + if (material.gradientMap) { + uniforms.gradientMap.value = material.gradientMap; + } + } + function refreshUniformsStandard(uniforms, material) { + uniforms.metalness.value = material.metalness; + if (material.metalnessMap) { + uniforms.metalnessMap.value = material.metalnessMap; + refreshTransformUniform(material.metalnessMap, uniforms.metalnessMapTransform); + } + uniforms.roughness.value = material.roughness; + if (material.roughnessMap) { + uniforms.roughnessMap.value = material.roughnessMap; + refreshTransformUniform(material.roughnessMap, uniforms.roughnessMapTransform); + } + if (material.envMap) { + uniforms.envMapIntensity.value = material.envMapIntensity; + } + } + function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) { + uniforms.ior.value = material.ior; + if (material.sheen > 0) { + uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen); + uniforms.sheenRoughness.value = material.sheenRoughness; + if (material.sheenColorMap) { + uniforms.sheenColorMap.value = material.sheenColorMap; + refreshTransformUniform(material.sheenColorMap, uniforms.sheenColorMapTransform); + } + if (material.sheenRoughnessMap) { + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + refreshTransformUniform(material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform); + } + } + if (material.clearcoat > 0) { + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + if (material.clearcoatMap) { + uniforms.clearcoatMap.value = material.clearcoatMap; + refreshTransformUniform(material.clearcoatMap, uniforms.clearcoatMapTransform); + } + if (material.clearcoatRoughnessMap) { + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + refreshTransformUniform(material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform); + } + if (material.clearcoatNormalMap) { + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + refreshTransformUniform(material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform); + uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale); + if (material.side === BackSide) { + uniforms.clearcoatNormalScale.value.negate(); + } + } + } + if (material.dispersion > 0) { + uniforms.dispersion.value = material.dispersion; + } + if (material.iridescence > 0) { + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1]; + if (material.iridescenceMap) { + uniforms.iridescenceMap.value = material.iridescenceMap; + refreshTransformUniform(material.iridescenceMap, uniforms.iridescenceMapTransform); + } + if (material.iridescenceThicknessMap) { + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + refreshTransformUniform(material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform); + } + } + if (material.transmission > 0) { + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height); + if (material.transmissionMap) { + uniforms.transmissionMap.value = material.transmissionMap; + refreshTransformUniform(material.transmissionMap, uniforms.transmissionMapTransform); + } + uniforms.thickness.value = material.thickness; + if (material.thicknessMap) { + uniforms.thicknessMap.value = material.thicknessMap; + refreshTransformUniform(material.thicknessMap, uniforms.thicknessMapTransform); + } + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy(material.attenuationColor); + } + if (material.anisotropy > 0) { + uniforms.anisotropyVector.value.set(material.anisotropy * Math.cos(material.anisotropyRotation), material.anisotropy * Math.sin(material.anisotropyRotation)); + if (material.anisotropyMap) { + uniforms.anisotropyMap.value = material.anisotropyMap; + refreshTransformUniform(material.anisotropyMap, uniforms.anisotropyMapTransform); + } + } + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy(material.specularColor); + if (material.specularColorMap) { + uniforms.specularColorMap.value = material.specularColorMap; + refreshTransformUniform(material.specularColorMap, uniforms.specularColorMapTransform); + } + if (material.specularIntensityMap) { + uniforms.specularIntensityMap.value = material.specularIntensityMap; + refreshTransformUniform(material.specularIntensityMap, uniforms.specularIntensityMapTransform); + } + } + function refreshUniformsMatcap(uniforms, material) { + if (material.matcap) { + uniforms.matcap.value = material.matcap; + } + } + function refreshUniformsDistance(uniforms, material) { + const light = properties.get(material).light; + uniforms.referencePosition.value.setFromMatrixPosition(light.matrixWorld); + uniforms.nearDistance.value = light.shadow.camera.near; + uniforms.farDistance.value = light.shadow.camera.far; + } + return { + refreshFogUniforms, + refreshMaterialUniforms + }; +} +function WebGLUniformsGroups(gl, info, capabilities, state) { + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + const maxBindingPoints = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS); + function bind(uniformsGroup, program) { + const webglProgram = program.program; + state.uniformBlockBinding(uniformsGroup, webglProgram); + } + function update(uniformsGroup, program) { + let buffer = buffers[uniformsGroup.id]; + if (buffer === undefined) { + prepareUniformsGroup(uniformsGroup); + buffer = createBuffer(uniformsGroup); + buffers[uniformsGroup.id] = buffer; + uniformsGroup.addEventListener("dispose", onUniformsGroupsDispose); + } + const webglProgram = program.program; + state.updateUBOMapping(uniformsGroup, webglProgram); + const frame = info.render.frame; + if (updateList[uniformsGroup.id] !== frame) { + updateBufferData(uniformsGroup); + updateList[uniformsGroup.id] = frame; + } + } + function createBuffer(uniformsGroup) { + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + gl.bufferData(gl.UNIFORM_BUFFER, size, usage); + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer); + return buffer; + } + function allocateBindingPointIndex() { + for (let i = 0;i < maxBindingPoints; i++) { + if (allocatedBindingPoints.indexOf(i) === -1) { + allocatedBindingPoints.push(i); + return i; + } + } + console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."); + return 0; + } + function updateBufferData(uniformsGroup) { + const buffer = buffers[uniformsGroup.id]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + for (let i = 0, il = uniforms.length;i < il; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j = 0, jl = uniformArray.length;j < jl; j++) { + const uniform = uniformArray[j]; + if (hasUniformChanged(uniform, i, j, cache) === true) { + const offset = uniform.__offset; + const values2 = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + let arrayOffset = 0; + for (let k = 0;k < values2.length; k++) { + const value2 = values2[k]; + const info2 = getUniformSize(value2); + if (typeof value2 === "number" || typeof value2 === "boolean") { + uniform.__data[0] = value2; + gl.bufferSubData(gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data); + } else if (value2.isMatrix3) { + uniform.__data[0] = value2.elements[0]; + uniform.__data[1] = value2.elements[1]; + uniform.__data[2] = value2.elements[2]; + uniform.__data[3] = 0; + uniform.__data[4] = value2.elements[3]; + uniform.__data[5] = value2.elements[4]; + uniform.__data[6] = value2.elements[5]; + uniform.__data[7] = 0; + uniform.__data[8] = value2.elements[6]; + uniform.__data[9] = value2.elements[7]; + uniform.__data[10] = value2.elements[8]; + uniform.__data[11] = 0; + } else { + value2.toArray(uniform.__data, arrayOffset); + arrayOffset += info2.storage / Float32Array.BYTES_PER_ELEMENT; + } + } + gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data); + } + } + } + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + } + function hasUniformChanged(uniform, index2, indexArray, cache) { + const value2 = uniform.value; + const indexString = index2 + "_" + indexArray; + if (cache[indexString] === undefined) { + if (typeof value2 === "number" || typeof value2 === "boolean") { + cache[indexString] = value2; + } else { + cache[indexString] = value2.clone(); + } + return true; + } else { + const cachedObject = cache[indexString]; + if (typeof value2 === "number" || typeof value2 === "boolean") { + if (cachedObject !== value2) { + cache[indexString] = value2; + return true; + } + } else { + if (cachedObject.equals(value2) === false) { + cachedObject.copy(value2); + return true; + } + } + } + return false; + } + function prepareUniformsGroup(uniformsGroup) { + const uniforms = uniformsGroup.uniforms; + let offset = 0; + const chunkSize = 16; + for (let i = 0, l = uniforms.length;i < l; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j = 0, jl = uniformArray.length;j < jl; j++) { + const uniform = uniformArray[j]; + const values2 = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + for (let k = 0, kl = values2.length;k < kl; k++) { + const value2 = values2[k]; + const info2 = getUniformSize(value2); + const chunkOffset2 = offset % chunkSize; + const chunkPadding = chunkOffset2 % info2.boundary; + const chunkStart = chunkOffset2 + chunkPadding; + offset += chunkPadding; + if (chunkStart !== 0 && chunkSize - chunkStart < info2.storage) { + offset += chunkSize - chunkStart; + } + uniform.__data = new Float32Array(info2.storage / Float32Array.BYTES_PER_ELEMENT); + uniform.__offset = offset; + offset += info2.storage; + } + } + } + const chunkOffset = offset % chunkSize; + if (chunkOffset > 0) + offset += chunkSize - chunkOffset; + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + return this; + } + function getUniformSize(value2) { + const info2 = { + boundary: 0, + storage: 0 + }; + if (typeof value2 === "number" || typeof value2 === "boolean") { + info2.boundary = 4; + info2.storage = 4; + } else if (value2.isVector2) { + info2.boundary = 8; + info2.storage = 8; + } else if (value2.isVector3 || value2.isColor) { + info2.boundary = 16; + info2.storage = 12; + } else if (value2.isVector4) { + info2.boundary = 16; + info2.storage = 16; + } else if (value2.isMatrix3) { + info2.boundary = 48; + info2.storage = 48; + } else if (value2.isMatrix4) { + info2.boundary = 64; + info2.storage = 64; + } else if (value2.isTexture) { + console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."); + } else { + console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", value2); + } + return info2; + } + function onUniformsGroupsDispose(event) { + const uniformsGroup = event.target; + uniformsGroup.removeEventListener("dispose", onUniformsGroupsDispose); + const index2 = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex); + allocatedBindingPoints.splice(index2, 1); + gl.deleteBuffer(buffers[uniformsGroup.id]); + delete buffers[uniformsGroup.id]; + delete updateList[uniformsGroup.id]; + } + function dispose() { + for (const id in buffers) { + gl.deleteBuffer(buffers[id]); + } + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + } + return { + bind, + update, + dispose + }; +} + +class WebGLRenderer { + constructor(parameters = {}) { + const { + canvas = createCanvasElement(), + context = null, + depth = true, + stencil = false, + alpha = false, + antialias = false, + premultipliedAlpha = true, + preserveDrawingBuffer = false, + powerPreference = "default", + failIfMajorPerformanceCaveat = false, + reverseDepthBuffer = false + } = parameters; + this.isWebGLRenderer = true; + let _alpha; + if (context !== null) { + if (typeof WebGLRenderingContext !== "undefined" && context instanceof WebGLRenderingContext) { + throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163."); + } + _alpha = context.getContextAttributes().alpha; + } else { + _alpha = alpha; + } + const uintClearColor = new Uint32Array(4); + const intClearColor = new Int32Array(4); + let currentRenderList = null; + let currentRenderState = null; + const renderListStack = []; + const renderStateStack = []; + this.domElement = canvas; + this.debug = { + checkShaderErrors: true, + onShaderError: null + }; + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + this.sortObjects = true; + this.clippingPlanes = []; + this.localClippingEnabled = false; + this._outputColorSpace = SRGBColorSpace; + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1; + const _this = this; + let _isContextLost = false; + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = -1; + let _currentCamera = null; + const _currentViewport = new Vector4; + const _currentScissor = new Vector4; + let _currentScissorTest = null; + const _currentClearColor = new Color(0); + let _currentClearAlpha = 0; + let _width = canvas.width; + let _height = canvas.height; + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + const _viewport = new Vector4(0, 0, _width, _height); + const _scissor = new Vector4(0, 0, _width, _height); + let _scissorTest = false; + const _frustum2 = new Frustum; + let _clippingEnabled = false; + let _localClippingEnabled = false; + this.transmissionResolutionScale = 1; + const _currentProjectionMatrix = new Matrix4; + const _projScreenMatrix2 = new Matrix4; + const _vector32 = new Vector3; + const _vector4 = new Vector4; + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + let _renderBackground = false; + function getTargetPixelRatio() { + return _currentRenderTarget === null ? _pixelRatio : 1; + } + let _gl = context; + function getContext(contextName, contextAttributes) { + return canvas.getContext(contextName, contextAttributes); + } + try { + const contextAttributes = { + alpha: true, + depth, + stencil, + antialias, + premultipliedAlpha, + preserveDrawingBuffer, + powerPreference, + failIfMajorPerformanceCaveat + }; + if ("setAttribute" in canvas) + canvas.setAttribute("data-engine", `three.js r${REVISION}`); + canvas.addEventListener("webglcontextlost", onContextLost, false); + canvas.addEventListener("webglcontextrestored", onContextRestore, false); + canvas.addEventListener("webglcontextcreationerror", onContextCreationError, false); + if (_gl === null) { + const contextName = "webgl2"; + _gl = getContext(contextName, contextAttributes); + if (_gl === null) { + if (getContext(contextName)) { + throw new Error("Error creating WebGL context with your selected attributes."); + } else { + throw new Error("Error creating WebGL context."); + } + } + } + } catch (error) { + console.error("THREE.WebGLRenderer: " + error.message); + throw error; + } + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + let utils, bindingStates, uniformsGroups; + function initGLContext() { + extensions = new WebGLExtensions(_gl); + extensions.init(); + utils = new WebGLUtils(_gl, extensions); + capabilities = new WebGLCapabilities(_gl, extensions, parameters, utils); + state = new WebGLState(_gl, extensions); + if (capabilities.reverseDepthBuffer && reverseDepthBuffer) { + state.buffers.depth.setReversed(true); + } + info = new WebGLInfo(_gl); + properties = new WebGLProperties; + textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info); + cubemaps = new WebGLCubeMaps(_this); + cubeuvmaps = new WebGLCubeUVMaps(_this); + attributes = new WebGLAttributes(_gl); + bindingStates = new WebGLBindingStates(_gl, attributes); + geometries = new WebGLGeometries(_gl, attributes, info, bindingStates); + objects = new WebGLObjects(_gl, geometries, attributes, info); + morphtargets = new WebGLMorphtargets(_gl, capabilities, textures); + clipping = new WebGLClipping(properties); + programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping); + materials = new WebGLMaterials(_this, properties); + renderLists = new WebGLRenderLists; + renderStates = new WebGLRenderStates(extensions); + background = new WebGLBackground(_this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha); + shadowMap = new WebGLShadowMap(_this, objects, capabilities); + uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state); + bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info); + indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info); + info.programs = programCache.programs; + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; + } + initGLContext(); + const xr = new WebXRManager(_this, _gl); + this.xr = xr; + this.getContext = function() { + return _gl; + }; + this.getContextAttributes = function() { + return _gl.getContextAttributes(); + }; + this.forceContextLoss = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) + extension.loseContext(); + }; + this.forceContextRestore = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) + extension.restoreContext(); + }; + this.getPixelRatio = function() { + return _pixelRatio; + }; + this.setPixelRatio = function(value2) { + if (value2 === undefined) + return; + _pixelRatio = value2; + this.setSize(_width, _height, false); + }; + this.getSize = function(target) { + return target.set(_width, _height); + }; + this.setSize = function(width2, height2, updateStyle = true) { + if (xr.isPresenting) { + console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."); + return; + } + _width = width2; + _height = height2; + canvas.width = Math.floor(width2 * _pixelRatio); + canvas.height = Math.floor(height2 * _pixelRatio); + if (updateStyle === true) { + canvas.style.width = width2 + "px"; + canvas.style.height = height2 + "px"; + } + this.setViewport(0, 0, width2, height2); + }; + this.getDrawingBufferSize = function(target) { + return target.set(_width * _pixelRatio, _height * _pixelRatio).floor(); + }; + this.setDrawingBufferSize = function(width2, height2, pixelRatio) { + _width = width2; + _height = height2; + _pixelRatio = pixelRatio; + canvas.width = Math.floor(width2 * pixelRatio); + canvas.height = Math.floor(height2 * pixelRatio); + this.setViewport(0, 0, width2, height2); + }; + this.getCurrentViewport = function(target) { + return target.copy(_currentViewport); + }; + this.getViewport = function(target) { + return target.copy(_viewport); + }; + this.setViewport = function(x, y, width2, height2) { + if (x.isVector4) { + _viewport.set(x.x, x.y, x.z, x.w); + } else { + _viewport.set(x, y, width2, height2); + } + state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).round()); + }; + this.getScissor = function(target) { + return target.copy(_scissor); + }; + this.setScissor = function(x, y, width2, height2) { + if (x.isVector4) { + _scissor.set(x.x, x.y, x.z, x.w); + } else { + _scissor.set(x, y, width2, height2); + } + state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).round()); + }; + this.getScissorTest = function() { + return _scissorTest; + }; + this.setScissorTest = function(boolean) { + state.setScissorTest(_scissorTest = boolean); + }; + this.setOpaqueSort = function(method) { + _opaqueSort = method; + }; + this.setTransparentSort = function(method) { + _transparentSort = method; + }; + this.getClearColor = function(target) { + return target.copy(background.getClearColor()); + }; + this.setClearColor = function() { + background.setClearColor.apply(background, arguments); + }; + this.getClearAlpha = function() { + return background.getClearAlpha(); + }; + this.setClearAlpha = function() { + background.setClearAlpha.apply(background, arguments); + }; + this.clear = function(color = true, depth2 = true, stencil2 = true) { + let bits = 0; + if (color) { + let isIntegerFormat = false; + if (_currentRenderTarget !== null) { + const targetFormat = _currentRenderTarget.texture.format; + isIntegerFormat = targetFormat === RGBAIntegerFormat || targetFormat === RGIntegerFormat || targetFormat === RedIntegerFormat; + } + if (isIntegerFormat) { + const targetType = _currentRenderTarget.texture.type; + const isUnsignedType = targetType === UnsignedByteType || targetType === UnsignedIntType || targetType === UnsignedShortType || targetType === UnsignedInt248Type || targetType === UnsignedShort4444Type || targetType === UnsignedShort5551Type; + const clearColor = background.getClearColor(); + const a = background.getClearAlpha(); + const r = clearColor.r; + const g = clearColor.g; + const b = clearColor.b; + if (isUnsignedType) { + uintClearColor[0] = r; + uintClearColor[1] = g; + uintClearColor[2] = b; + uintClearColor[3] = a; + _gl.clearBufferuiv(_gl.COLOR, 0, uintClearColor); + } else { + intClearColor[0] = r; + intClearColor[1] = g; + intClearColor[2] = b; + intClearColor[3] = a; + _gl.clearBufferiv(_gl.COLOR, 0, intClearColor); + } + } else { + bits |= _gl.COLOR_BUFFER_BIT; + } + } + if (depth2) { + bits |= _gl.DEPTH_BUFFER_BIT; + } + if (stencil2) { + bits |= _gl.STENCIL_BUFFER_BIT; + this.state.buffers.stencil.setMask(4294967295); + } + _gl.clear(bits); + }; + this.clearColor = function() { + this.clear(true, false, false); + }; + this.clearDepth = function() { + this.clear(false, true, false); + }; + this.clearStencil = function() { + this.clear(false, false, true); + }; + this.dispose = function() { + canvas.removeEventListener("webglcontextlost", onContextLost, false); + canvas.removeEventListener("webglcontextrestored", onContextRestore, false); + canvas.removeEventListener("webglcontextcreationerror", onContextCreationError, false); + background.dispose(); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + xr.dispose(); + xr.removeEventListener("sessionstart", onXRSessionStart); + xr.removeEventListener("sessionend", onXRSessionEnd); + animation.stop(); + }; + function onContextLost(event) { + event.preventDefault(); + console.log("THREE.WebGLRenderer: Context Lost."); + _isContextLost = true; + } + function onContextRestore() { + console.log("THREE.WebGLRenderer: Context Restored."); + _isContextLost = false; + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + initGLContext(); + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + } + function onContextCreationError(event) { + console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", event.statusMessage); + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + deallocateMaterial(material); + } + function deallocateMaterial(material) { + releaseMaterialProgramReferences(material); + properties.remove(material); + } + function releaseMaterialProgramReferences(material) { + const programs = properties.get(material).programs; + if (programs !== undefined) { + programs.forEach(function(program) { + programCache.releaseProgram(program); + }); + if (material.isShaderMaterial) { + programCache.releaseShaderCache(material); + } + } + } + this.renderBufferDirect = function(camera, scene, geometry, material, object, group) { + if (scene === null) + scene = _emptyScene; + const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0; + const program = setProgram(camera, scene, geometry, material, object); + state.setMaterial(material, frontFaceCW); + let index2 = geometry.index; + let rangeFactor = 1; + if (material.wireframe === true) { + index2 = geometries.getWireframeAttribute(geometry); + if (index2 === undefined) + return; + rangeFactor = 2; + } + const drawRange = geometry.drawRange; + const position2 = geometry.attributes.position; + let drawStart = drawRange.start * rangeFactor; + let drawEnd = (drawRange.start + drawRange.count) * rangeFactor; + if (group !== null) { + drawStart = Math.max(drawStart, group.start * rangeFactor); + drawEnd = Math.min(drawEnd, (group.start + group.count) * rangeFactor); + } + if (index2 !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, index2.count); + } else if (position2 !== undefined && position2 !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, position2.count); + } + const drawCount = drawEnd - drawStart; + if (drawCount < 0 || drawCount === Infinity) + return; + bindingStates.setup(object, material, program, geometry, index2); + let attribute; + let renderer2 = bufferRenderer; + if (index2 !== null) { + attribute = attributes.get(index2); + renderer2 = indexedBufferRenderer; + renderer2.setIndex(attribute); + } + if (object.isMesh) { + if (material.wireframe === true) { + state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio()); + renderer2.setMode(_gl.LINES); + } else { + renderer2.setMode(_gl.TRIANGLES); + } + } else if (object.isLine) { + let lineWidth = material.linewidth; + if (lineWidth === undefined) + lineWidth = 1; + state.setLineWidth(lineWidth * getTargetPixelRatio()); + if (object.isLineSegments) { + renderer2.setMode(_gl.LINES); + } else if (object.isLineLoop) { + renderer2.setMode(_gl.LINE_LOOP); + } else { + renderer2.setMode(_gl.LINE_STRIP); + } + } else if (object.isPoints) { + renderer2.setMode(_gl.POINTS); + } else if (object.isSprite) { + renderer2.setMode(_gl.TRIANGLES); + } + if (object.isBatchedMesh) { + if (object._multiDrawInstances !== null) { + renderer2.renderMultiDrawInstances(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances); + } else { + if (!extensions.get("WEBGL_multi_draw")) { + const starts = object._multiDrawStarts; + const counts = object._multiDrawCounts; + const drawCount2 = object._multiDrawCount; + const bytesPerElement = index2 ? attributes.get(index2).bytesPerElement : 1; + const uniforms = properties.get(material).currentProgram.getUniforms(); + for (let i = 0;i < drawCount2; i++) { + uniforms.setValue(_gl, "_gl_DrawID", i); + renderer2.render(starts[i] / bytesPerElement, counts[i]); + } + } else { + renderer2.renderMultiDraw(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount); + } + } + } else if (object.isInstancedMesh) { + renderer2.renderInstances(drawStart, drawCount, object.count); + } else if (geometry.isInstancedBufferGeometry) { + const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min(geometry.instanceCount, maxInstanceCount); + renderer2.renderInstances(drawStart, drawCount, instanceCount); + } else { + renderer2.render(drawStart, drawCount); + } + }; + function prepareMaterial(material, scene, object) { + if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) { + material.side = BackSide; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = FrontSide; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = DoubleSide; + } else { + getProgram(material, scene, object); + } + } + this.compile = function(scene, camera, targetScene = null) { + if (targetScene === null) + targetScene = scene; + currentRenderState = renderStates.get(targetScene); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + targetScene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + if (scene !== targetScene) { + scene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + } + currentRenderState.setupLights(); + const materials2 = new Set; + scene.traverse(function(object) { + if (!(object.isMesh || object.isPoints || object.isLine || object.isSprite)) { + return; + } + const material = object.material; + if (material) { + if (Array.isArray(material)) { + for (let i = 0;i < material.length; i++) { + const material2 = material[i]; + prepareMaterial(material2, targetScene, object); + materials2.add(material2); + } + } else { + prepareMaterial(material, targetScene, object); + materials2.add(material); + } + } + }); + renderStateStack.pop(); + currentRenderState = null; + return materials2; + }; + this.compileAsync = function(scene, camera, targetScene = null) { + const materials2 = this.compile(scene, camera, targetScene); + return new Promise((resolve) => { + function checkMaterialsReady() { + materials2.forEach(function(material) { + const materialProperties = properties.get(material); + const program = materialProperties.currentProgram; + if (program.isReady()) { + materials2.delete(material); + } + }); + if (materials2.size === 0) { + resolve(scene); + return; + } + setTimeout(checkMaterialsReady, 10); + } + if (extensions.get("KHR_parallel_shader_compile") !== null) { + checkMaterialsReady(); + } else { + setTimeout(checkMaterialsReady, 10); + } + }); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time2) { + if (onAnimationFrameCallback) + onAnimationFrameCallback(time2); + } + function onXRSessionStart() { + animation.stop(); + } + function onXRSessionEnd() { + animation.start(); + } + const animation = new WebGLAnimation; + animation.setAnimationLoop(onAnimationFrame); + if (typeof self !== "undefined") + animation.setContext(self); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + xr.setAnimationLoop(callback); + callback === null ? animation.stop() : animation.start(); + }; + xr.addEventListener("sessionstart", onXRSessionStart); + xr.addEventListener("sessionend", onXRSessionEnd); + this.render = function(scene, camera) { + if (camera !== undefined && camera.isCamera !== true) { + console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera."); + return; + } + if (_isContextLost === true) + return; + if (scene.matrixWorldAutoUpdate === true) + scene.updateMatrixWorld(); + if (camera.parent === null && camera.matrixWorldAutoUpdate === true) + camera.updateMatrixWorld(); + if (xr.enabled === true && xr.isPresenting === true) { + if (xr.cameraAutoUpdate === true) + xr.updateCamera(camera); + camera = xr.getCamera(); + } + if (scene.isScene === true) + scene.onBeforeRender(_this, scene, camera, _currentRenderTarget); + currentRenderState = renderStates.get(scene, renderStateStack.length); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + _projScreenMatrix2.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + _frustum2.setFromProjectionMatrix(_projScreenMatrix2); + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled); + currentRenderList = renderLists.get(scene, renderListStack.length); + currentRenderList.init(); + renderListStack.push(currentRenderList); + if (xr.enabled === true && xr.isPresenting === true) { + const depthSensingMesh = _this.xr.getDepthSensingMesh(); + if (depthSensingMesh !== null) { + projectObject(depthSensingMesh, camera, -Infinity, _this.sortObjects); + } + } + projectObject(scene, camera, 0, _this.sortObjects); + currentRenderList.finish(); + if (_this.sortObjects === true) { + currentRenderList.sort(_opaqueSort, _transparentSort); + } + _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false; + if (_renderBackground) { + background.addToRenderList(currentRenderList, scene); + } + this.info.render.frame++; + if (_clippingEnabled === true) + clipping.beginShadows(); + const shadowsArray = currentRenderState.state.shadowsArray; + shadowMap.render(shadowsArray, scene, camera); + if (_clippingEnabled === true) + clipping.endShadows(); + if (this.info.autoReset === true) + this.info.reset(); + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + currentRenderState.setupLights(); + if (camera.isArrayCamera) { + const cameras = camera.cameras; + if (transmissiveObjects.length > 0) { + for (let i = 0, l = cameras.length;i < l; i++) { + const camera2 = cameras[i]; + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera2); + } + } + if (_renderBackground) + background.render(scene); + for (let i = 0, l = cameras.length;i < l; i++) { + const camera2 = cameras[i]; + renderScene(currentRenderList, scene, camera2, camera2.viewport); + } + } else { + if (transmissiveObjects.length > 0) + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera); + if (_renderBackground) + background.render(scene); + renderScene(currentRenderList, scene, camera); + } + if (_currentRenderTarget !== null && _currentActiveMipmapLevel === 0) { + textures.updateMultisampleRenderTarget(_currentRenderTarget); + textures.updateRenderTargetMipmap(_currentRenderTarget); + } + if (scene.isScene === true) + scene.onAfterRender(_this, scene, camera); + bindingStates.resetDefaultState(); + _currentMaterialId = -1; + _currentCamera = null; + renderStateStack.pop(); + if (renderStateStack.length > 0) { + currentRenderState = renderStateStack[renderStateStack.length - 1]; + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, currentRenderState.state.camera); + } else { + currentRenderState = null; + } + renderListStack.pop(); + if (renderListStack.length > 0) { + currentRenderList = renderListStack[renderListStack.length - 1]; + } else { + currentRenderList = null; + } + }; + function projectObject(object, camera, groupOrder, sortObjects) { + if (object.visible === false) + return; + const visible = object.layers.test(camera.layers); + if (visible) { + if (object.isGroup) { + groupOrder = object.renderOrder; + } else if (object.isLOD) { + if (object.autoUpdate === true) + object.update(camera); + } else if (object.isLight) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } else if (object.isSprite) { + if (!object.frustumCulled || _frustum2.intersectsSprite(object)) { + if (sortObjects) { + _vector4.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix2); + } + const geometry = objects.update(object); + const material = object.material; + if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector4.z, null); + } + } + } else if (object.isMesh || object.isLine || object.isPoints) { + if (!object.frustumCulled || _frustum2.intersectsObject(object)) { + const geometry = objects.update(object); + const material = object.material; + if (sortObjects) { + if (object.boundingSphere !== undefined) { + if (object.boundingSphere === null) + object.computeBoundingSphere(); + _vector4.copy(object.boundingSphere.center); + } else { + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _vector4.copy(geometry.boundingSphere.center); + } + _vector4.applyMatrix4(object.matrixWorld).applyMatrix4(_projScreenMatrix2); + } + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector4.z, group); + } + } + } else if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector4.z, null); + } + } + } + } + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + projectObject(children[i], camera, groupOrder, sortObjects); + } + } + function renderScene(currentRenderList2, scene, camera, viewport) { + const opaqueObjects = currentRenderList2.opaque; + const transmissiveObjects = currentRenderList2.transmissive; + const transparentObjects = currentRenderList2.transparent; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, camera); + if (viewport) + state.viewport(_currentViewport.copy(viewport)); + if (opaqueObjects.length > 0) + renderObjects(opaqueObjects, scene, camera); + if (transmissiveObjects.length > 0) + renderObjects(transmissiveObjects, scene, camera); + if (transparentObjects.length > 0) + renderObjects(transparentObjects, scene, camera); + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + state.setPolygonOffset(false); + } + function renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + if (overrideMaterial !== null) { + return; + } + if (currentRenderState.state.transmissionRenderTarget[camera.id] === undefined) { + currentRenderState.state.transmissionRenderTarget[camera.id] = new WebGLRenderTarget(1, 1, { + generateMipmaps: true, + type: extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float") ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: 4, + stencilBuffer: stencil, + resolveDepthBuffer: false, + resolveStencilBuffer: false, + colorSpace: ColorManagement.workingColorSpace + }); + } + const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[camera.id]; + const activeViewport = camera.viewport || _currentViewport; + transmissionRenderTarget.setSize(activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale); + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget(transmissionRenderTarget); + _this.getClearColor(_currentClearColor); + _currentClearAlpha = _this.getClearAlpha(); + if (_currentClearAlpha < 1) + _this.setClearColor(16777215, 0.5); + _this.clear(); + if (_renderBackground) + background.render(scene); + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; + const currentCameraViewport = camera.viewport; + if (camera.viewport !== undefined) + camera.viewport = undefined; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, camera); + renderObjects(opaqueObjects, scene, camera); + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + if (extensions.has("WEBGL_multisampled_render_to_texture") === false) { + let renderTargetNeedsUpdate = false; + for (let i = 0, l = transmissiveObjects.length;i < l; i++) { + const renderItem = transmissiveObjects[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = renderItem.material; + const group = renderItem.group; + if (material.side === DoubleSide && object.layers.test(camera.layers)) { + const currentSide = material.side; + material.side = BackSide; + material.needsUpdate = true; + renderObject(object, scene, camera, geometry, material, group); + material.side = currentSide; + material.needsUpdate = true; + renderTargetNeedsUpdate = true; + } + } + if (renderTargetNeedsUpdate === true) { + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + } + } + _this.setRenderTarget(currentRenderTarget); + _this.setClearColor(_currentClearColor, _currentClearAlpha); + if (currentCameraViewport !== undefined) + camera.viewport = currentCameraViewport; + _this.toneMapping = currentToneMapping; + } + function renderObjects(renderList, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + for (let i = 0, l = renderList.length;i < l; i++) { + const renderItem = renderList[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; + if (object.layers.test(camera.layers)) { + renderObject(object, scene, camera, geometry, material, group); + } + } + } + function renderObject(object, scene, camera, geometry, material, group) { + object.onBeforeRender(_this, scene, camera, geometry, material, group); + object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld); + object.normalMatrix.getNormalMatrix(object.modelViewMatrix); + material.onBeforeRender(_this, scene, camera, geometry, object, group); + if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) { + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = DoubleSide; + } else { + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + } + object.onAfterRender(_this, scene, camera, geometry, material, group); + } + function getProgram(material, scene, object) { + if (scene.isScene !== true) + scene = _emptyScene; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + const lightsStateVersion = lights.state.version; + const parameters2 = programCache.getParameters(material, lights.state, shadowsArray, scene, object); + const programCacheKey = programCache.getProgramCacheKey(parameters2); + let programs = materialProperties.programs; + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment); + materialProperties.envMapRotation = materialProperties.environment !== null && material.envMap === null ? scene.environmentRotation : material.envMapRotation; + if (programs === undefined) { + material.addEventListener("dispose", onMaterialDispose); + programs = new Map; + materialProperties.programs = programs; + } + let program = programs.get(programCacheKey); + if (program !== undefined) { + if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) { + updateCommonMaterialProperties(material, parameters2); + return program; + } + } else { + parameters2.uniforms = programCache.getUniforms(material); + material.onBeforeCompile(parameters2, _this); + program = programCache.acquireProgram(parameters2, programCacheKey); + programs.set(programCacheKey, program); + materialProperties.uniforms = parameters2.uniforms; + } + const uniforms = materialProperties.uniforms; + if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) { + uniforms.clippingPlanes = clipping.uniform; + } + updateCommonMaterialProperties(material, parameters2); + materialProperties.needsLights = materialNeedsLights(material); + materialProperties.lightsStateVersion = lightsStateVersion; + if (materialProperties.needsLights) { + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + } + materialProperties.currentProgram = program; + materialProperties.uniformsList = null; + return program; + } + function getUniformList(materialProperties) { + if (materialProperties.uniformsList === null) { + const progUniforms = materialProperties.currentProgram.getUniforms(); + materialProperties.uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, materialProperties.uniforms); + } + return materialProperties.uniformsList; + } + function updateCommonMaterialProperties(material, parameters2) { + const materialProperties = properties.get(material); + materialProperties.outputColorSpace = parameters2.outputColorSpace; + materialProperties.batching = parameters2.batching; + materialProperties.batchingColor = parameters2.batchingColor; + materialProperties.instancing = parameters2.instancing; + materialProperties.instancingColor = parameters2.instancingColor; + materialProperties.instancingMorph = parameters2.instancingMorph; + materialProperties.skinning = parameters2.skinning; + materialProperties.morphTargets = parameters2.morphTargets; + materialProperties.morphNormals = parameters2.morphNormals; + materialProperties.morphColors = parameters2.morphColors; + materialProperties.morphTargetsCount = parameters2.morphTargetsCount; + materialProperties.numClippingPlanes = parameters2.numClippingPlanes; + materialProperties.numIntersection = parameters2.numClipIntersection; + materialProperties.vertexAlphas = parameters2.vertexAlphas; + materialProperties.vertexTangents = parameters2.vertexTangents; + materialProperties.toneMapping = parameters2.toneMapping; + } + function setProgram(camera, scene, geometry, material, object) { + if (scene.isScene !== true) + scene = _emptyScene; + textures.resetTextureUnits(); + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const colorSpace = _currentRenderTarget === null ? _this.outputColorSpace : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !!geometry.attributes.tangent && (!!material.normalMap || material.anisotropy > 0); + const morphTargets = !!geometry.morphAttributes.position; + const morphNormals = !!geometry.morphAttributes.normal; + const morphColors = !!geometry.morphAttributes.color; + let toneMapping = NoToneMapping; + if (material.toneMapped) { + if (_currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true) { + toneMapping = _this.toneMapping; + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + if (_clippingEnabled === true) { + if (_localClippingEnabled === true || camera !== _currentCamera) { + const useCache = camera === _currentCamera && material.id === _currentMaterialId; + clipping.setState(material, camera, useCache); + } + } + let needsProgramChange = false; + if (material.version === materialProperties.__version) { + if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) { + needsProgramChange = true; + } else if (materialProperties.outputColorSpace !== colorSpace) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batching === false) { + needsProgramChange = true; + } else if (!object.isBatchedMesh && materialProperties.batching === true) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancing === false) { + needsProgramChange = true; + } else if (!object.isInstancedMesh && materialProperties.instancing === true) { + needsProgramChange = true; + } else if (object.isSkinnedMesh && materialProperties.skinning === false) { + needsProgramChange = true; + } else if (!object.isSkinnedMesh && materialProperties.skinning === true) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null) { + needsProgramChange = true; + } else if (materialProperties.envMap !== envMap) { + needsProgramChange = true; + } else if (material.fog === true && materialProperties.fog !== fog) { + needsProgramChange = true; + } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) { + needsProgramChange = true; + } else if (materialProperties.vertexAlphas !== vertexAlphas) { + needsProgramChange = true; + } else if (materialProperties.vertexTangents !== vertexTangents) { + needsProgramChange = true; + } else if (materialProperties.morphTargets !== morphTargets) { + needsProgramChange = true; + } else if (materialProperties.morphNormals !== morphNormals) { + needsProgramChange = true; + } else if (materialProperties.morphColors !== morphColors) { + needsProgramChange = true; + } else if (materialProperties.toneMapping !== toneMapping) { + needsProgramChange = true; + } else if (materialProperties.morphTargetsCount !== morphTargetsCount) { + needsProgramChange = true; + } + } else { + needsProgramChange = true; + materialProperties.__version = material.version; + } + let program = materialProperties.currentProgram; + if (needsProgramChange === true) { + program = getProgram(material, scene, object); + } + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + const p_uniforms = program.getUniforms(), m_uniforms = materialProperties.uniforms; + if (state.useProgram(program.program)) { + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + } + if (material.id !== _currentMaterialId) { + _currentMaterialId = material.id; + refreshMaterial = true; + } + if (refreshProgram || _currentCamera !== camera) { + const reverseDepthBuffer2 = state.buffers.depth.getReversed(); + if (reverseDepthBuffer2) { + _currentProjectionMatrix.copy(camera.projectionMatrix); + toNormalizedProjectionMatrix(_currentProjectionMatrix); + toReversedProjectionMatrix(_currentProjectionMatrix); + p_uniforms.setValue(_gl, "projectionMatrix", _currentProjectionMatrix); + } else { + p_uniforms.setValue(_gl, "projectionMatrix", camera.projectionMatrix); + } + p_uniforms.setValue(_gl, "viewMatrix", camera.matrixWorldInverse); + const uCamPos = p_uniforms.map.cameraPosition; + if (uCamPos !== undefined) { + uCamPos.setValue(_gl, _vector32.setFromMatrixPosition(camera.matrixWorld)); + } + if (capabilities.logarithmicDepthBuffer) { + p_uniforms.setValue(_gl, "logDepthBufFC", 2 / (Math.log(camera.far + 1) / Math.LN2)); + } + if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) { + p_uniforms.setValue(_gl, "isOrthographic", camera.isOrthographicCamera === true); + } + if (_currentCamera !== camera) { + _currentCamera = camera; + refreshMaterial = true; + refreshLights = true; + } + } + if (object.isSkinnedMesh) { + p_uniforms.setOptional(_gl, object, "bindMatrix"); + p_uniforms.setOptional(_gl, object, "bindMatrixInverse"); + const skeleton = object.skeleton; + if (skeleton) { + if (skeleton.boneTexture === null) + skeleton.computeBoneTexture(); + p_uniforms.setValue(_gl, "boneTexture", skeleton.boneTexture, textures); + } + } + if (object.isBatchedMesh) { + p_uniforms.setOptional(_gl, object, "batchingTexture"); + p_uniforms.setValue(_gl, "batchingTexture", object._matricesTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingIdTexture"); + p_uniforms.setValue(_gl, "batchingIdTexture", object._indirectTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingColorTexture"); + if (object._colorsTexture !== null) { + p_uniforms.setValue(_gl, "batchingColorTexture", object._colorsTexture, textures); + } + } + const morphAttributes = geometry.morphAttributes; + if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined) { + morphtargets.update(object, geometry, program); + } + if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) { + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue(_gl, "receiveShadow", object.receiveShadow); + } + if (material.isMeshGouraudMaterial && material.envMap !== null) { + m_uniforms.envMap.value = envMap; + m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + } + if (material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null) { + m_uniforms.envMapIntensity.value = scene.environmentIntensity; + } + if (refreshMaterial) { + p_uniforms.setValue(_gl, "toneMappingExposure", _this.toneMappingExposure); + if (materialProperties.needsLights) { + markUniformsLightsNeedsUpdate(m_uniforms, refreshLights); + } + if (fog && material.fog === true) { + materials.refreshFogUniforms(m_uniforms, fog); + } + materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[camera.id]); + WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + } + if (material.isShaderMaterial && material.uniformsNeedUpdate === true) { + WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + material.uniformsNeedUpdate = false; + } + if (material.isSpriteMaterial) { + p_uniforms.setValue(_gl, "center", object.center); + } + p_uniforms.setValue(_gl, "modelViewMatrix", object.modelViewMatrix); + p_uniforms.setValue(_gl, "normalMatrix", object.normalMatrix); + p_uniforms.setValue(_gl, "modelMatrix", object.matrixWorld); + if (material.isShaderMaterial || material.isRawShaderMaterial) { + const groups = material.uniformsGroups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + uniformsGroups.update(group, program); + uniformsGroups.bind(group, program); + } + } + return program; + } + function markUniformsLightsNeedsUpdate(uniforms, value2) { + uniforms.ambientLightColor.needsUpdate = value2; + uniforms.lightProbe.needsUpdate = value2; + uniforms.directionalLights.needsUpdate = value2; + uniforms.directionalLightShadows.needsUpdate = value2; + uniforms.pointLights.needsUpdate = value2; + uniforms.pointLightShadows.needsUpdate = value2; + uniforms.spotLights.needsUpdate = value2; + uniforms.spotLightShadows.needsUpdate = value2; + uniforms.rectAreaLights.needsUpdate = value2; + uniforms.hemisphereLights.needsUpdate = value2; + } + function materialNeedsLights(material) { + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true; + } + this.getActiveCubeFace = function() { + return _currentActiveCubeFace; + }; + this.getActiveMipmapLevel = function() { + return _currentActiveMipmapLevel; + }; + this.getRenderTarget = function() { + return _currentRenderTarget; + }; + this.setRenderTargetTextures = function(renderTarget, colorTexture, depthTexture) { + properties.get(renderTarget.texture).__webglTexture = colorTexture; + properties.get(renderTarget.depthTexture).__webglTexture = depthTexture; + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__hasExternalTextures = true; + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; + if (!renderTargetProperties.__autoAllocateDepthBuffer) { + if (extensions.has("WEBGL_multisampled_render_to_texture") === true) { + console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"); + renderTargetProperties.__useRenderToTexture = false; + } + } + }; + this.setRenderTargetFramebuffer = function(renderTarget, defaultFramebuffer) { + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; + }; + const _scratchFrameBuffer = _gl.createFramebuffer(); + this.setRenderTarget = function(renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) { + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + if (renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTargetProperties.__useDefaultFramebuffer !== undefined) { + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + useDefaultFramebuffer = false; + } else if (renderTargetProperties.__webglFramebuffer === undefined) { + textures.setupRenderTarget(renderTarget); + } else if (renderTargetProperties.__hasExternalTextures) { + textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture); + } else if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__boundDepthTexture !== depthTexture) { + if (depthTexture !== null && properties.has(depthTexture) && (renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height)) { + throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size."); + } + textures.setupDepthRenderbuffer(renderTarget); + } + } + const texture = renderTarget.texture; + if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + isRenderTarget3D = true; + } + const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget) { + if (Array.isArray(__webglFramebuffer[activeCubeFace])) { + framebuffer = __webglFramebuffer[activeCubeFace][activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer[activeCubeFace]; + } + isCube = true; + } else if (renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) { + framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer; + } else { + if (Array.isArray(__webglFramebuffer)) { + framebuffer = __webglFramebuffer[activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer; + } + } + _currentViewport.copy(renderTarget.viewport); + _currentScissor.copy(renderTarget.scissor); + _currentScissorTest = renderTarget.scissorTest; + } else { + _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor(); + _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(); + _currentScissorTest = _scissorTest; + } + if (activeMipmapLevel !== 0) { + framebuffer = _scratchFrameBuffer; + } + const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (framebufferBound && useDefaultFramebuffer) { + state.drawBuffers(renderTarget, framebuffer); + } + state.viewport(_currentViewport); + state.scissor(_currentScissor); + state.setScissorTest(_currentScissorTest); + if (isCube) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel); + } else if (isRenderTarget3D) { + const textureProperties = properties.get(renderTarget.texture); + const layer = activeCubeFace; + _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer); + } else if (renderTarget !== null && activeMipmapLevel !== 0) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel); + } + _currentMaterialId = -1; + }; + this.readRenderTargetPixels = function(renderTarget, x, y, width2, height2, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + return; + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + try { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); + return; + } + if (!capabilities.textureTypeReadable(textureType)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); + return; + } + if (x >= 0 && x <= renderTarget.width - width2 && (y >= 0 && y <= renderTarget.height - height2)) { + _gl.readPixels(x, y, width2, height2, utils.convert(textureFormat), utils.convert(textureType), buffer); + } + } finally { + const framebuffer2 = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer2); + } + } + }; + this.readRenderTargetPixelsAsync = async function(renderTarget, x, y, width2, height2, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format."); + } + if (!capabilities.textureTypeReadable(textureType)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type."); + } + if (x >= 0 && x <= renderTarget.width - width2 && (y >= 0 && y <= renderTarget.height - height2)) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + const glBuffer = _gl.createBuffer(); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.bufferData(_gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ); + _gl.readPixels(x, y, width2, height2, utils.convert(textureFormat), utils.convert(textureType), 0); + const currFramebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, currFramebuffer); + const sync = _gl.fenceSync(_gl.SYNC_GPU_COMMANDS_COMPLETE, 0); + _gl.flush(); + await probeAsync(_gl, sync, 4); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.getBufferSubData(_gl.PIXEL_PACK_BUFFER, 0, buffer); + _gl.deleteBuffer(glBuffer); + _gl.deleteSync(sync); + return buffer; + } else { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range."); + } + } + }; + this.copyFramebufferToTexture = function(texture, position2 = null, level = 0) { + if (texture.isTexture !== true) { + warnOnce("WebGLRenderer: copyFramebufferToTexture function signature has changed."); + position2 = arguments[0] || null; + texture = arguments[1]; + } + const levelScale = Math.pow(2, -level); + const width2 = Math.floor(texture.image.width * levelScale); + const height2 = Math.floor(texture.image.height * levelScale); + const x = position2 !== null ? position2.x : 0; + const y = position2 !== null ? position2.y : 0; + textures.setTexture2D(texture, 0); + _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, x, y, width2, height2); + state.unbindTexture(); + }; + const _srcFramebuffer = _gl.createFramebuffer(); + const _dstFramebuffer = _gl.createFramebuffer(); + this.copyTextureToTexture = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null) { + if (srcTexture.isTexture !== true) { + warnOnce("WebGLRenderer: copyTextureToTexture function signature has changed."); + dstPosition = arguments[0] || null; + srcTexture = arguments[1]; + dstTexture = arguments[2]; + dstLevel = arguments[3] || 0; + srcRegion = null; + } + if (dstLevel === null) { + if (srcLevel !== 0) { + warnOnce("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."); + dstLevel = srcLevel; + srcLevel = 0; + } else { + dstLevel = 0; + } + } + let width2, height2, depth2, minX, minY, minZ; + let dstX, dstY, dstZ; + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[dstLevel] : srcTexture.image; + if (srcRegion !== null) { + width2 = srcRegion.max.x - srcRegion.min.x; + height2 = srcRegion.max.y - srcRegion.min.y; + depth2 = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1; + minX = srcRegion.min.x; + minY = srcRegion.min.y; + minZ = srcRegion.isBox3 ? srcRegion.min.z : 0; + } else { + const levelScale = Math.pow(2, -srcLevel); + width2 = Math.floor(image.width * levelScale); + height2 = Math.floor(image.height * levelScale); + if (srcTexture.isDataArrayTexture) { + depth2 = image.depth; + } else if (srcTexture.isData3DTexture) { + depth2 = Math.floor(image.depth * levelScale); + } else { + depth2 = 1; + } + minX = 0; + minY = 0; + minZ = 0; + } + if (dstPosition !== null) { + dstX = dstPosition.x; + dstY = dstPosition.y; + dstZ = dstPosition.z; + } else { + dstX = 0; + dstY = 0; + dstZ = 0; + } + const glFormat = utils.convert(dstTexture.format); + const glType = utils.convert(dstTexture.type); + let glTarget; + if (dstTexture.isData3DTexture) { + textures.setTexture3D(dstTexture, 0); + glTarget = _gl.TEXTURE_3D; + } else if (dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture) { + textures.setTexture2DArray(dstTexture, 0); + glTarget = _gl.TEXTURE_2D_ARRAY; + } else { + textures.setTexture2D(dstTexture, 0); + glTarget = _gl.TEXTURE_2D; + } + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment); + const currentUnpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH); + const currentUnpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT); + const currentUnpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS); + const currentUnpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS); + const currentUnpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES); + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, minX); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, minY); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, minZ); + const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture; + const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture; + if (srcTexture.isDepthTexture) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + const srcRenderTargetProperties = properties.get(srcTextureProperties.__renderTarget); + const dstRenderTargetProperties = properties.get(dstTextureProperties.__renderTarget); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer); + for (let i = 0;i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(srcTexture).__webglTexture, srcLevel, minZ + i); + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(dstTexture).__webglTexture, dstLevel, dstZ + i); + } + _gl.blitFramebuffer(minX, minY, width2, height2, dstX, dstY, width2, height2, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST); + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else if (srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has(srcTexture)) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, _srcFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, _dstFramebuffer); + for (let i = 0;i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i); + } else { + _gl.framebufferTexture2D(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel); + } + if (isDst3D) { + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i); + } else { + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel); + } + if (srcLevel !== 0) { + _gl.blitFramebuffer(minX, minY, width2, height2, dstX, dstY, width2, height2, _gl.COLOR_BUFFER_BIT, _gl.NEAREST); + } else if (isDst3D) { + _gl.copyTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width2, height2); + } else { + _gl.copyTexSubImage2D(glTarget, dstLevel, dstX, dstY, minX, minY, width2, height2); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else { + if (isDst3D) { + if (srcTexture.isDataTexture || srcTexture.isData3DTexture) { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, glType, image.data); + } else if (dstTexture.isCompressedArrayTexture) { + _gl.compressedTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, image.data); + } else { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, glType, image); + } + } else { + if (srcTexture.isDataTexture) { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width2, height2, glFormat, glType, image.data); + } else if (srcTexture.isCompressedTexture) { + _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data); + } else { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width2, height2, glFormat, glType, image); + } + } + } + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, currentUnpackRowLen); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages); + if (dstLevel === 0 && dstTexture.generateMipmaps) { + _gl.generateMipmap(glTarget); + } + state.unbindTexture(); + }; + this.copyTextureToTexture3D = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0) { + if (srcTexture.isTexture !== true) { + warnOnce("WebGLRenderer: copyTextureToTexture3D function signature has changed."); + srcRegion = arguments[0] || null; + dstPosition = arguments[1] || null; + srcTexture = arguments[2]; + dstTexture = arguments[3]; + level = arguments[4] || 0; + } + warnOnce('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'); + return this.copyTextureToTexture(srcTexture, dstTexture, srcRegion, dstPosition, level); + }; + this.initRenderTarget = function(target) { + if (properties.get(target).__webglFramebuffer === undefined) { + textures.setupRenderTarget(target); + } + }; + this.initTexture = function(texture) { + if (texture.isCubeTexture) { + textures.setTextureCube(texture, 0); + } else if (texture.isData3DTexture) { + textures.setTexture3D(texture, 0); + } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + textures.setTexture2DArray(texture, 0); + } else { + textures.setTexture2D(texture, 0); + } + state.unbindTexture(); + }; + this.resetState = function() { + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + state.reset(); + bindingStates.reset(); + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + get coordinateSystem() { + return WebGLCoordinateSystem; + } + get outputColorSpace() { + return this._outputColorSpace; + } + set outputColorSpace(colorSpace) { + this._outputColorSpace = colorSpace; + const gl = this.getContext(); + gl.drawingBufferColorspace = ColorManagement._getDrawingBufferColorSpace(colorSpace); + gl.unpackColorSpace = ColorManagement._getUnpackColorSpace(); + } +} + +// src/external/ffl.js/ffl.js +var _Import = __toESM(require_struct_fu(), 1); +/*! + * Bindings for FFL, a Mii renderer, in JavaScript. + * https://github.com/ariankordi/FFL.js + * @author Arian Kordi + */ +globalThis._ = globalThis._; +globalThis.THREE = globalThis.THREE; +var _ = globalThis._; +_ = !_ ? _Import : _; +var FFLResult = { + OK: 0, + ERROR: 1, + HDB_EMPTY: 2, + FILE_INVALID: 3, + MANAGER_NOT_CONSTRUCT: 4, + FILE_LOAD_ERROR: 5, + FILE_SAVE_ERROR: 7, + RES_FS_ERROR: 9, + ODB_EMPTY: 10, + OUT_OF_MEMORY: 12, + UNKNOWN_17: 17, + FS_ERROR: 18, + FS_NOT_FOUND: 19, + MAX: 20 +}; +var FFLiShapeType = { + OPA_BEARD: 0, + OPA_FACELINE: 1, + OPA_HAIR_NORMAL: 2, + OPA_FOREHEAD_NORMAL: 3, + XLU_MASK: 4, + XLU_NOSELINE: 5, + OPA_NOSE: 6, + OPA_HAT_NORMAL: 7, + XLU_GLASS: 8, + OPA_HAIR_CAP: 9, + OPA_FOREHEAD_CAP: 10, + OPA_HAT_CAP: 11, + MAX: 12 +}; +var FFLAttributeBufferType = { + POSITION: 0, + TEXCOORD: 1, + NORMAL: 2, + TANGENT: 3, + COLOR: 4, + MAX: 5 +}; +var FFLCullMode = { + NONE: 0, + BACK: 1, + FRONT: 2, + MAX: 3 +}; +var FFLModulateMode = { + CONSTANT: 0, + TEXTURE_DIRECT: 1, + RGB_LAYERED: 2, + ALPHA: 3, + LUMINANCE_ALPHA: 4, + ALPHA_OPA: 5 +}; +var FFLModulateType = { + SHAPE_FACELINE: 0, + SHAPE_BEARD: 1, + SHAPE_NOSE: 2, + SHAPE_FOREHEAD: 3, + SHAPE_HAIR: 4, + SHAPE_CAP: 5, + SHAPE_MASK: 6, + SHAPE_NOSELINE: 7, + SHAPE_GLASS: 8, + MUSTACHE: 9, + MOUTH: 10, + EYEBROW: 11, + EYE: 12, + MOLE: 13, + FACE_MAKE: 14, + FACE_LINE: 15, + FACE_BEARD: 16, + FILL: 17, + SHAPE_MAX: 9 +}; +var FFLResourceType = { + MIDDLE: 0, + HIGH: 1, + MAX: 2 +}; +var FFLExpression = { + NORMAL: 0, + SMILE: 1, + ANGER: 2, + SORROW: 3, + PUZZLED: 3, + SURPRISE: 4, + SURPRISED: 4, + BLINK: 5, + OPEN_MOUTH: 6, + SMILE_OPEN_MOUTH: 7, + HAPPY: 7, + ANGER_OPEN_MOUTH: 8, + SORROW_OPEN_MOUTH: 9, + SURPRISE_OPEN_MOUTH: 10, + BLINK_OPEN_MOUTH: 11, + WINK_LEFT: 12, + WINK_RIGHT: 13, + WINK_LEFT_OPEN_MOUTH: 14, + WINK_RIGHT_OPEN_MOUTH: 15, + LIKE_WINK_LEFT: 16, + LIKE: 16, + LIKE_WINK_RIGHT: 17, + FRUSTRATED: 18, + BORED: 19, + BORED_OPEN_MOUTH: 20, + SIGH_MOUTH_STRAIGHT: 21, + SIGH: 22, + DISGUSTED_MOUTH_STRAIGHT: 23, + DISGUSTED: 24, + LOVE: 25, + LOVE_OPEN_MOUTH: 26, + DETERMINED_MOUTH_STRAIGHT: 27, + DETERMINED: 28, + CRY_MOUTH_STRAIGHT: 29, + CRY: 30, + BIG_SMILE_MOUTH_STRAIGHT: 31, + BIG_SMILE: 32, + CHEEKY: 33, + CHEEKY_DUPLICATE: 34, + JOJO_EYES_FUNNY_MOUTH: 35, + JOJO_EYES_FUNNY_MOUTH_OPEN: 36, + SMUG: 37, + SMUG_OPEN_MOUTH: 38, + RESOLVE: 39, + RESOLVE_OPEN_MOUTH: 40, + UNBELIEVABLE: 41, + UNBELIEVABLE_DUPLICATE: 42, + CUNNING: 43, + CUNNING_DUPLICATE: 44, + RASPBERRY: 45, + RASPBERRY_DUPLICATE: 46, + INNOCENT: 47, + INNOCENT_DUPLICATE: 48, + CAT: 49, + CAT_DUPLICATE: 50, + DOG: 51, + DOG_DUPLICATE: 52, + TASTY: 53, + TASTY_DUPLICATE: 54, + MONEY_MOUTH_STRAIGHT: 55, + MONEY: 56, + SPIRAL_MOUTH_STRAIGHT: 57, + CONFUSED: 58, + CHEERFUL_MOUTH_STRAIGHT: 59, + CHEERFUL: 60, + BLANK_61: 61, + BLANK_62: 62, + GRUMBLE_MOUTH_STRAIGHT: 63, + GRUMBLE: 64, + MOVED_MOUTH_STRAIGHT: 65, + MOVED: 66, + SINGING_MOUTH_SMALL: 67, + SINGING: 68, + STUNNED: 69, + MAX: 70 +}; +var FFLModelFlag = { + NORMAL: 1 << 0, + HAT: 1 << 1, + FACE_ONLY: 1 << 2, + FLATTEN_NOSE: 1 << 3, + NEW_EXPRESSIONS: 1 << 4, + NEW_MASK_ONLY: 1 << 5 +}; +var _uintptr = _.uint32le; +var FFLAttributeBuffer = _.struct([ + _.uint32le("size"), + _.uint32le("stride"), + _uintptr("ptr") +]); +var FFLAttributeBufferParam = _.struct([ + _.struct("attributeBuffers", [FFLAttributeBuffer], 5) +]); +var FFLPrimitiveParam = _.struct([ + _.uint32le("primitiveType"), + _.uint32le("indexCount"), + _uintptr("pAdjustMatrix"), + _uintptr("pIndexBuffer") +]); +var FFLColor = _.struct([ + _.float32le("r"), + _.float32le("g"), + _.float32le("b"), + _.float32le("a") +]); +var FFLVec3 = _.struct([ + _.float32le("x"), + _.float32le("y"), + _.float32le("z") +]); +var FFLModulateParam = _.struct([ + _.uint32le("mode"), + _.uint32le("type"), + _uintptr("pColorR"), + _uintptr("pColorG"), + _uintptr("pColorB"), + _uintptr("pTexture2D") +]); +var FFLDrawParam = _.struct([ + _.struct("attributeBufferParam", [FFLAttributeBufferParam]), + _.struct("modulateParam", [FFLModulateParam]), + _.uint32le("cullMode"), + _.struct("primitiveParam", [FFLPrimitiveParam]) +]); +var FFLCreateID = _.struct([ + _.uint8("data", 10) +]); +var FFLiCharInfo = _.struct([ + _.int32le("miiVersion"), + _.struct("faceline", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("texture"), + _.int32le("make") + ]), + _.struct("hair", [_.int32le("type"), _.int32le("color"), _.int32le("flip")]), + _.struct("eye", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("aspect"), + _.int32le("rotate"), + _.int32le("x"), + _.int32le("y") + ]), + _.struct("eyebrow", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("aspect"), + _.int32le("rotate"), + _.int32le("x"), + _.int32le("y") + ]), + _.struct("nose", [ + _.int32le("type"), + _.int32le("scale"), + _.int32le("y") + ]), + _.struct("mouth", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("aspect"), + _.int32le("y") + ]), + _.struct("beard", [ + _.int32le("mustache"), + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("y") + ]), + _.struct("glass", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("y") + ]), + _.struct("mole", [ + _.int32le("type"), + _.int32le("scale"), + _.int32le("x"), + _.int32le("y") + ]), + _.struct("body", [_.int32le("height"), _.int32le("build")]), + _.struct("personal", [ + _.char16le("name", 22), + _.char16le("creator", 22), + _.int32le("gender"), + _.int32le("birthMonth"), + _.int32le("birthDay"), + _.int32le("favoriteColor"), + _.uint8("favorite"), + _.uint8("copyable"), + _.uint8("ngWord"), + _.uint8("localonly"), + _.int32le("regionMove"), + _.int32le("fontRegion"), + _.int32le("roomIndex"), + _.int32le("positionInRoom"), + _.int32le("birthPlatform") + ]), + _.struct("createID", [FFLCreateID]), + _.uint16le("padding_0"), + _.int32le("authorType"), + _.uint8("authorID", 8) +]); +var FFLStoreData_size = 96; +var commonColorEnableMask = 1 << 31; +var commonColorMask = (color) => color | commonColorEnableMask; +var FFLAdditionalInfo = _.struct([ + _.char16le("name", 22), + _.char16le("creator", 22), + _.struct("createID", [FFLCreateID]), + _.byte("_padding0", 2), + _.struct("skinColor", [FFLColor]), + _.uint32le("flags"), + _.uint8("facelineType"), + _.uint8("hairType"), + _.byte("_padding1", 2) +]); +var FFLiRenderTexture = _.struct([ + _uintptr("pTexture2DRenderBufferColorTargetDepthTarget", 4) +]); +var FFLiFacelineTextureTempObject = _.struct([ + _uintptr("pTextureFaceLine"), + _.struct("drawParamFaceLine", [FFLDrawParam]), + _uintptr("pTextureFaceMake"), + _.struct("drawParamFaceMake", [FFLDrawParam]), + _uintptr("pTextureFaceBeard"), + _.struct("drawParamFaceBeard", [FFLDrawParam]), + _uintptr("pRenderTextureCompressorParam", 2) +]); +var FFLiRawMaskDrawParam = _.struct([ + _.struct("drawParamRawMaskPartsEye", [FFLDrawParam], 2), + _.struct("drawParamRawMaskPartsEyebrow", [FFLDrawParam], 2), + _.struct("drawParamRawMaskPartsMouth", [FFLDrawParam]), + _.struct("drawParamRawMaskPartsMustache", [FFLDrawParam], 2), + _.struct("drawParamRawMaskPartsMole", [FFLDrawParam]), + _.struct("drawParamRawMaskPartsFill", [FFLDrawParam]) +]); +var FFLiMaskTexturesTempObject = _.struct([ + _.uint8("partsTextures", 340), + _uintptr("pRawMaskDrawParam", FFLExpression.MAX), + _.byte("_remaining", 904 - 620) +]); +var FFLiTextureTempObject = _.struct([ + _.struct("maskTextures", [FFLiMaskTexturesTempObject]), + _.struct("facelineTexture", [FFLiFacelineTextureTempObject]) +]); +var FFLiMaskTextures = _.struct([ + _uintptr("pRenderTextures", FFLExpression.MAX) +]); +var FFL_RESOLUTION_MASK = 1073741823; +var FFLCharModelDesc = _.struct([ + _.uint32le("resolution"), + _.uint32le("allExpressionFlag", 3), + _.uint32le("modelFlag"), + _.uint32le("resourceType") +]); +var FFLCharModelDescDefault = { + resolution: 512, + allExpressionFlag: new Uint32Array([1, 0, 0]), + modelFlag: FFLModelFlag.NORMAL, + resourceType: FFLResourceType.HIGH +}; +var FFLBoundingBox = _.struct([ + _.struct("min", [FFLVec3]), + _.struct("max", [FFLVec3]) +]); +var FFLPartsTransform = _.struct([ + _.struct("hatTranslate", [FFLVec3]), + _.struct("headFrontRotate", [FFLVec3]), + _.struct("headFrontTranslate", [FFLVec3]), + _.struct("headSideRotate", [FFLVec3]), + _.struct("headSideTranslate", [FFLVec3]), + _.struct("headTopRotate", [FFLVec3]), + _.struct("headTopTranslate", [FFLVec3]) +]); +var FFLiCharModel = _.struct([ + _.struct("charInfo", [FFLiCharInfo]), + _.struct("charModelDesc", [FFLCharModelDesc]), + _.uint32le("expression"), + _uintptr("pTextureTempObject"), + _.struct("drawParam", [FFLDrawParam], FFLiShapeType.MAX), + _uintptr("pShapeData", FFLiShapeType.MAX), + _.struct("facelineRenderTexture", [FFLiRenderTexture]), + _uintptr("pCapGlassNoselineTextures", 3), + _.struct("maskTextures", [FFLiMaskTextures]), + _.struct("beardHairFaceCenterPos", [FFLVec3], 3), + _.struct("partsTransform", [FFLPartsTransform]), + _.uint32le("modelType"), + _.struct("boundingBox", [FFLBoundingBox], 3) +]); +var FFLDataSource = { + OFFICIAL: 0, + DEFAULT: 1, + MIDDLE_DB: 2, + STORE_DATA_OFFICIAL: 3, + STORE_DATA: 4, + BUFFER: 5, + DIRECT_POINTER: 6 +}; +var FFLCharModelSource = _.struct([ + _.uint32le("dataSource"), + _uintptr("pBuffer"), + _.uint16le("index") +]); +var FFLResourceDesc = _.struct([ + _uintptr("pData", FFLResourceType.MAX), + _.uint32le("size", FFLResourceType.MAX) +]); +var FFLTextureFormat = { + R8_UNORM: 0, + R8_G8_UNORM: 1, + R8_G8_B8_A8_UNORM: 2, + MAX: 3 +}; +var FFLTextureInfo = _.struct([ + _.uint16le("width"), + _.uint16le("height"), + _.uint8("mipCount"), + _.uint8("format"), + _.uint8("isGX2Tiled"), + _.byte("_padding", 1), + _.uint32le("imageSize"), + _uintptr("imagePtr"), + _.uint32le("mipSize"), + _uintptr("mipPtr"), + _.uint32le("mipLevelOffset", 13) +]); +var FFLTextureCallback = _.struct([ + _uintptr("pObj"), + _.uint8("useOriginalTileMode"), + _.byte("_padding", 3), + _uintptr("pCreateFunc"), + _uintptr("pDeleteFunc") +]); + +class TextureManager { + constructor(module2, setToFFLGlobal = false) { + this._module = module2; + this._textures = new Map; + this._textureCallbackPtr = 0; + this.logging = false; + this._setTextureCallback(); + if (setToFFLGlobal) { + module2._FFLSetTextureCallback(this._textureCallbackPtr); + } + } + static _allocateTextureCallback(module2, createCallback, deleteCallback) { + const ptr = module2._malloc(FFLTextureCallback.size); + const textureCallback = { + pObj: 0, + useOriginalTileMode: false, + _padding: [0, 0, 0], + pCreateFunc: createCallback, + pDeleteFunc: deleteCallback + }; + const packed = FFLTextureCallback.pack(textureCallback); + module2.HEAPU8.set(packed, ptr); + return ptr; + } + _setTextureCallback(addDeleteCallback = false) { + const mod2 = this._module; + this._createCallback = mod2.addFunction(this._textureCreateFunc.bind(this), "vppp"); + if (addDeleteCallback) { + this._deleteCallback = mod2.addFunction(this._textureDeleteFunc.bind(this), "vpp"); + } + this._textureCallbackPtr = TextureManager._allocateTextureCallback(mod2, this._createCallback, this._deleteCallback ? this._deleteCallback : 0); + } + _getTextureFormat(format) { + const useGLES2Formats = Number(REVISION) <= 136; + const r8 = useGLES2Formats ? LuminanceFormat : RedFormat; + const r8g8 = useGLES2Formats ? LuminanceAlphaFormat : RGFormat; + const textureFormatToThreeFormat = { + [FFLTextureFormat.R8_UNORM]: r8, + [FFLTextureFormat.R8_G8_UNORM]: r8g8, + [FFLTextureFormat.R8_G8_B8_A8_UNORM]: RGBAFormat + }; + const dataFormat = textureFormatToThreeFormat[format]; + if (dataFormat === undefined) { + throw new Error(`_textureCreateFunc: Unexpected FFLTextureFormat value: ${format}`); + } + return dataFormat; + } + _textureCreateFunc(_2, textureInfoPtr, texturePtrPtr) { + const u8 = this._module.HEAPU8.subarray(textureInfoPtr, textureInfoPtr + FFLTextureInfo.size); + const textureInfo = FFLTextureInfo.unpack(u8); + if (this.logging) { + console.debug(`_textureCreateFunc: width=${textureInfo.width}, height=${textureInfo.height}, format=${textureInfo.format}, imageSize=${textureInfo.imageSize}, mipCount=${textureInfo.mipCount}`); + } + const format = this._getTextureFormat(textureInfo.format); + const imageData = this._module.HEAPU8.slice(textureInfo.imagePtr, textureInfo.imagePtr + textureInfo.imageSize); + const canUseMipmaps = Number(REVISION) >= 138; + const useMipmaps = textureInfo.mipCount > 1 && canUseMipmaps; + const texture = new DataTexture(useMipmaps ? null : imageData, textureInfo.width, textureInfo.height, format, UnsignedByteType); + texture.magFilter = LinearFilter; + texture.minFilter = LinearFilter; + if (useMipmaps) { + texture.mipmaps = [{ + data: imageData, + width: textureInfo.width, + height: textureInfo.height + }]; + texture.minFilter = LinearMipmapLinearFilter; + texture.generateMipmaps = false; + this._addMipmaps(texture, textureInfo); + } + texture.needsUpdate = true; + this.set(texture.id, texture); + this._module.HEAPU32[texturePtrPtr / 4] = texture.id; + } + _addMipmaps(texture, textureInfo) { + if (textureInfo.mipPtr === 0) { + throw new Error("_addMipmaps: mipPtr is null, so the caller incorrectly assumed this texture has mipmaps"); + } + for (let mipLevel = 1;mipLevel < textureInfo.mipCount; mipLevel++) { + const mipOffset = textureInfo.mipLevelOffset[mipLevel - 1]; + const mipWidth = Math.max(1, textureInfo.width >> mipLevel); + const mipHeight = Math.max(1, textureInfo.height >> mipLevel); + const nextMipOffset = textureInfo.mipLevelOffset[mipLevel] || textureInfo.mipSize; + const end = textureInfo.mipPtr + nextMipOffset; + const start = textureInfo.mipPtr + mipOffset; + const mipData = this._module.HEAPU8.slice(start, end); + if (this.logging) { + console.debug(` - Mip ${mipLevel}: ${mipWidth}x${mipHeight}, offset=${mipOffset}, range=${start}-${end}`); + } + texture.mipmaps.push({ + data: mipData, + width: mipWidth, + height: mipHeight + }); + } + } + _textureDeleteFunc(_2, texturePtrPtr) { + const texId = this._module.HEAPU32[texturePtrPtr / 4]; + const tex = this._textures.get(texId); + if (tex && this.logging) { + console.debug("Delete texture ", tex.id); + } + } + get(id) { + const texture = this._textures.get(id); + if (!texture && this.logging) { + console.error("Unknown texture", id); + } + return texture; + } + set(id, texture) { + const disposeReal = texture.dispose.bind(texture); + texture.dispose = () => { + disposeReal(); + this.delete(id); + }; + this._textures.set(id, texture); + if (this.logging) { + console.debug("Adding texture ", texture.id); + } + } + delete(id) { + const texture = this._textures.get(id); + if (texture) { + texture.source = null; + texture.mipmaps = null; + if (this.logging) { + console.debug("Deleted texture ", id); + } + this._textures.delete(id); + } + } + disposeCallback() { + if (this._textureCallbackPtr) { + this._module._free(this._textureCallbackPtr); + this._textureCallbackPtr = 0; + } + if (this._deleteCallback) { + this._module.removeFunction(this._deleteCallback); + this._deleteCallback = 0; + } + if (this._createCallback) { + this._module.removeFunction(this._createCallback); + this._createCallback = 0; + } + } + dispose() { + this._textures.forEach((tex) => { + tex.dispose(); + }); + this._textures.clear(); + this.disposeCallback(); + } +} + +class FFLResultException extends Error { + constructor(result, funcName, message) { + if (!message) { + if (funcName) { + message = `${funcName} failed with FFLResult: ${result}`; + } else { + message = `From FFLResult: ${result}`; + } + } + super(message); + this.result = result; + } + static handleResult(result, funcName) { + switch (result) { + case FFLResult.ERROR: + throw new FFLResultWrongParam(funcName); + case FFLResult.FILE_INVALID: + throw new FFLResultBroken(funcName); + case FFLResult.MANAGER_NOT_CONSTRUCT: + throw new FFLResultNotAvailable(funcName); + case FFLResult.FILE_LOAD_ERROR: + throw new FFLResultFatal(funcName); + case FFLResult.OK: + return; + default: + throw new FFLResultException(result, funcName); + } + } +} + +class FFLResultWrongParam extends FFLResultException { + constructor(funcName) { + super(1, funcName, `${funcName} returned FFL_RESULT_WRONG_PARAM. This usually means parameters going into that function were invalid.`); + } +} + +class FFLResultBroken extends FFLResultException { + constructor(funcName, message) { + super(3, funcName, message ? message : `${funcName} returned FFL_RESULT_BROKEN. This usually indicates invalid underlying data.`); + } +} + +class BrokenInitRes extends FFLResultBroken { + constructor() { + super("FFLInitRes", 'The header for the FFL resource is probably invalid. Check the version and magic, should be "FFRA" or "ARFF".'); + } +} + +class BrokenInitModel extends FFLResultBroken { + constructor() { + super("FFLInitCharModelCPUStep", "FFLInitCharModelCPUStep failed probably because your data failed CRC or CharInfo verification (FFLiVerifyCharInfoWithReason)."); + } +} + +class FFLResultNotAvailable extends FFLResultException { + constructor(funcName) { + super(4, funcName, `Tried to call FFL function ${funcName} when FFLManager is not constructed (FFL is not initialized properly).`); + } +} + +class FFLResultFatal extends FFLResultException { + constructor(funcName) { + super(5, funcName, `Failed to uncompress or load a specific asset from the FFL resource file during call to ${funcName}`); + } +} + +class FFLiVerifyReasonException extends Error { + constructor(result) { + super(`FFLiVerifyCharInfoWithReason (CharInfo verification) failed with result: ${result}`); + this.result = result; + } +} + +class ExpressionNotSet extends Error { + constructor(expression) { + super(`Attempted to set expression ${expression}, but the mask for that expression does not exist. You must reinitialize the CharModel with this expression in the expression flags before using it.`); + this.expression = expression; + } +} +async function _loadDataIntoHeap(resource, module2) { + let heapSize; + let heapPtr; + try { + if (resource instanceof ArrayBuffer) { + resource = new Uint8Array(resource); + } + if (resource instanceof Uint8Array) { + heapSize = resource.length; + heapPtr = module2._malloc(heapSize); + console.debug(`_loadDataIntoHeap: Loading from buffer. Size: ${heapSize}, pointer: ${heapPtr}`); + module2.HEAPU8.set(resource, heapPtr); + } else if (resource instanceof Response) { + if (!resource.ok) { + throw new Error(`HTTP error while fetching resource at URL = ${resource.url}, response code = ${resource.status}`); + } + if (!resource.body) { + throw new Error(`Response body is null (resource.body = ${resource.body})`); + } + const contentLength = resource.headers.get("Content-Length"); + if (!contentLength) { + console.debug("_loadDataIntoHeap: Fetch response is missing Content-Length, falling back to reading as ArrayBuffer."); + return _loadDataIntoHeap(await resource.arrayBuffer(), module2); + } + heapSize = parseInt(contentLength, 10); + heapPtr = module2._malloc(heapSize); + console.debug(`loadDataIntoHeap: Streaming from fetch response. Size: ${heapSize}, pointer: ${heapPtr}, URL: ${resource.url}`); + const reader = resource.body.getReader(); + let offset = heapPtr; + while (true) { + const { done, value: value2 } = await reader.read(); + if (done) { + break; + } + module2.HEAPU8.set(value2, offset); + offset += value2.length; + } + } else { + throw new Error("loadDataIntoHeap: type is not Uint8Array or Response"); + } + return { pointer: heapPtr, size: heapSize }; + } catch (error) { + if (heapPtr) { + module2._free(heapPtr); + } + throw error; + } +} +async function initializeFFL(resource, moduleOrPromise) { + console.debug("initializeFFL: Entrypoint, waiting for module to be ready."); + let resourceDescPtr; + function freeResDesc() { + if (resourceDescPtr) { + module2._free(resourceDescPtr); + } + } + const resourceType = FFLResourceType.HIGH; + let module2; + if (typeof moduleOrPromise === "function") { + moduleOrPromise = moduleOrPromise(); + } + if (moduleOrPromise instanceof Promise) { + module2 = await moduleOrPromise; + } else { + module2 = moduleOrPromise; + } + if (!module2.calledRun && !module2.onRuntimeInitialized) { + await new Promise((resolve) => { + module2.onRuntimeInitialized = () => { + console.debug("initializeFFL: Emscripten runtime initialized, resolving."); + resolve(null); + }; + console.debug(`initializeFFL: module.calledRun: ${module2.calledRun}, module.onRuntimeInitialized: +${module2.onRuntimeInitialized} + // ^^ assigned and waiting.`); + }); + } else { + console.debug("initializeFFL: Assuming module is ready."); + } + let resourceDesc = null; + try { + if (resource instanceof Promise) { + resource = await resource; + } + const { pointer: heapPtr, size: heapSize } = await _loadDataIntoHeap(resource, module2); + console.debug(`initializeFFL: Resource loaded into heap. Pointer: ${heapPtr}, Size: ${heapSize}`); + resourceDesc = { pData: [0, 0], size: [0, 0] }; + resourceDesc.pData[resourceType] = heapPtr; + resourceDesc.size[resourceType] = heapSize; + const resourceDescData = FFLResourceDesc.pack(resourceDesc); + resourceDescPtr = module2._malloc(FFLResourceDesc.size); + module2.HEAPU8.set(resourceDescData, resourceDescPtr); + const result = module2._FFLInitRes(0, resourceDescPtr); + if (result === FFLResult.FILE_INVALID) { + throw new BrokenInitRes; + } + FFLResultException.handleResult(result, "FFLInitRes"); + module2._FFLInitResGPUStep(); + module2._FFLSetNormalIsSnorm8_8_8_8(true); + module2._FFLSetTextureFlipY(true); + } catch (error) { + _freeResourceDesc(resourceDesc, module2); + freeResDesc(); + console.error("initializeFFL failed:", error); + throw error; + } finally { + freeResDesc(); + } + return { + module: module2, + resourceDesc + }; +} +async function initializeFFLWithResource(module2, resourcePath) { + const querySelectorResourcePath = "meta[itemprop=ffl-js-resource-fetch-path]"; + if (!resourcePath && typeof document !== "undefined") { + const resourceFetchElement = document.querySelector(querySelectorResourcePath); + if (!resourceFetchElement || !resourceFetchElement.getAttribute("content")) { + throw new Error(`initializeFFLWithResource: Element not found or does not have "content" attribute with path to FFL resource: ${querySelectorResourcePath}`); + } + resourcePath = resourceFetchElement.getAttribute("content"); + } + if (!resourcePath) { + throw new Error("initializeFFLWithResource: resourcePath must be a string"); + } + try { + const response = await fetch(resourcePath); + const ret = await initializeFFL(response, module2); + console.debug("initializeFFLWithResource: FFLiManager and TextureManager initialized, exiting"); + return ret; + } catch (error) { + if (typeof alert !== "undefined") { + alert(`Error initializing FFL with resource: ${error}`); + } + throw error; + } +} +function _freeResourceDesc(desc, module2) { + if (!desc || !desc.pData) { + return; + } + desc.pData.forEach((ptr, i) => { + if (ptr) { + module2._free(ptr); + desc.pData[i] = 0; + } + }); +} +class CharModel { + constructor(ptr, module2, materialClass, texManager) { + this._module = module2; + this._data = null; + this._materialClass = materialClass; + this._materialTextureClass = materialClass; + this._textureManager = texManager; + this._ptr = ptr; + this.__ptr = ptr; + const charModelData = this._module.HEAPU8.subarray(ptr, ptr + FFLiCharModel.size); + this._model = FFLiCharModel.unpack(charModelData); + this._facelineTarget = null; + this._maskTargets = new Array(FFLExpression.MAX).fill(null); + this.meshes = new Group; + this._addCharModelMeshes(module2); + } + _addCharModelMeshes(module2) { + if (!this.meshes) { + throw new Error("_addCharModelMeshes: this.meshes is null or undefined, was this CharModel disposed?"); + } + for (let shapeType = 0;shapeType < FFLiShapeType.MAX; shapeType++) { + const drawParam = this._model.drawParam[shapeType]; + const mesh = drawParamToMesh(drawParam, this._materialClass, module2, this._textureManager); + if (!mesh) { + continue; + } + mesh.renderOrder = drawParam.modulateParam.type; + switch (shapeType) { + case FFLiShapeType.OPA_FACELINE: + this._facelineMesh = mesh; + break; + case FFLiShapeType.XLU_MASK: + this._maskMesh = mesh; + break; + } + this.meshes.add(mesh); + } + } + _getTextureTempObjectPtr() { + return this._model.pTextureTempObject; + } + _getTextureTempObject() { + const ptr = this._getTextureTempObjectPtr(); + return FFLiTextureTempObject.unpack(this._module.HEAPU8.subarray(ptr, ptr + FFLiTextureTempObject.size)); + } + _getPartsTransform() { + const obj = this._model.partsTransform; + const newPartsTransform = {}; + for (const key2 in obj) { + const vec = obj[key2]; + if (vec.x === undefined) { + throw new Error; + } + newPartsTransform[key2] = new Vector3(vec.x, vec.y, vec.z); + } + return newPartsTransform; + } + _getFacelineColor() { + const mod2 = this._module; + const facelineColor = this._model.charInfo.faceline.color; + const colorPtr = mod2._malloc(FFLColor.size); + mod2._FFLGetFacelineColor(colorPtr, facelineColor); + const color = _getFFLColor3(_getFFLColor(colorPtr, mod2.HEAPF32)); + mod2._free(colorPtr); + return color; + } + _getFavoriteColor() { + const mod2 = this._module; + const favoriteColor = this._model.charInfo.personal.favoriteColor; + const colorPtr = mod2._malloc(FFLColor.size); + mod2._FFLGetFavoriteColor(colorPtr, favoriteColor); + const color = _getFFLColor3(_getFFLColor(colorPtr, mod2.HEAPF32)); + mod2._free(colorPtr); + return color; + } + _getCharInfoUint8Array() { + return FFLiCharInfo.pack(this._model.charInfo); + } + _getPartsTexturesPtr() { + return this._model.pTextureTempObject + FFLiTextureTempObject.fields.maskTextures.offset + FFLiMaskTexturesTempObject.fields.partsTextures.offset; + } + _getFacelineTempObjectPtr() { + return this._model.pTextureTempObject + FFLiTextureTempObject.fields.facelineTexture.offset; + } + _getMaskTempObjectPtr() { + return this._model.pTextureTempObject + FFLiTextureTempObject.fields.maskTextures.offset; + } + _getExpressionFlagPtr() { + return this._ptr + FFLiCharModel.fields.charModelDesc.offset + FFLCharModelDesc.fields.allExpressionFlag.offset; + } + _getBoundingBox() { + const bbox = this._model.boundingBox[this._model.modelType]; + if (!(bbox.max.x === 0 && bbox.max.y === 0 && bbox.max.z === 0)) { + const min = new Vector3(bbox.min.x, bbox.min.y, bbox.min.z); + const max = new Vector3(bbox.max.x, bbox.max.y, bbox.max.z); + return new Box3(min, max); + } + const excludeFromBox = [FFLModulateType.SHAPE_MASK, FFLModulateType.SHAPE_GLASS]; + const box = new Box3; + if (!this.meshes) { + throw new Error("_getBoundingBox: this.meshes is null."); + } + this.meshes.traverse((child) => { + if (!(child instanceof Mesh) || excludeFromBox.indexOf(child.geometry.userData.modulateType) !== -1) { + return; + } + box.expandByObject(child); + }); + return box; + } + _getResolution() { + return this._model.charModelDesc.resolution & FFL_RESOLUTION_MASK; + } + _finalizeCharModel() { + if (!this._ptr) { + return; + } + this._module._FFLDeleteCharModel(this._ptr); + this._module._free(this._ptr); + this._ptr = 0; + } + disposeTargets() { + if (this._facelineTarget) { + console.debug(`Disposing target ${this._facelineTarget.texture.id} for faceline`); + this._facelineTarget.dispose(); + this._facelineTarget = null; + } + this._maskTargets.forEach((target, i) => { + if (!target) { + return; + } + console.debug(`Disposing target ${target.texture.id} for mask ${i}`); + target.dispose(); + this._maskTargets[i] = null; + }); + } + dispose(disposeTargets = true) { + console.debug("CharModel.dispose: ptr =", this.__ptr); + this._finalizeCharModel(); + if (this.meshes) { + this._facelineMesh = null; + this._maskMesh = null; + disposeMeshes(this.meshes); + this.meshes = null; + } + if (disposeTargets) { + this.disposeTargets(); + } + if (this._textureManager) { + this._textureManager.dispose(); + this._textureManager = null; + } + } + getStoreData() { + const charInfoData = this._getCharInfoUint8Array(); + const mod2 = this._module; + const charInfoPtr = mod2._malloc(FFLiCharInfo.size); + const storeDataPtr = mod2._malloc(FFLStoreData_size); + mod2.HEAPU8.set(charInfoData, charInfoPtr); + const result = mod2._FFLpGetStoreDataFromCharInfo(storeDataPtr, charInfoPtr); + const storeData = mod2.HEAPU8.slice(storeDataPtr, storeDataPtr + FFLStoreData_size); + mod2._free(charInfoPtr); + mod2._free(storeDataPtr); + if (!result) { + throw new Error("getStoreData: call to FFLpGetStoreDataFromCharInfo returned false, CharInfo verification probably failed"); + } + return storeData; + } + setExpression(expression) { + this._model.expression = expression; + const targ = this._maskTargets[expression]; + if (!targ || !targ.texture) { + throw new ExpressionNotSet(expression); + } + const mesh = this._maskMesh; + if (!mesh || !(mesh instanceof Mesh)) { + if (expression === FFLExpression.BLANK_61 || expression === FFLExpression.BLANK_62) { + return; + } + throw new Error("setExpression: mask mesh does not exist, cannot set expression on it"); + } + targ.texture._target = targ; + mesh.material.map = targ.texture; + mesh.material.needsUpdate = true; + } + getFaceline() { + if (this._facelineTarget) { + return this._facelineTarget; + } + return null; + } + getMask(expression = this.expression) { + if (this._maskTargets && this._maskTargets[expression]) { + return this._maskTargets[expression]; + } + return null; + } + get expression() { + return this._model.expression; + } + get charInfo() { + return this._model.charInfo; + } + get facelineColor() { + if (!this._facelineColor) { + this._facelineColor = this._getFacelineColor(); + } + return this._facelineColor; + } + get favoriteColor() { + if (!this._favoriteColor) { + this._favoriteColor = this._getFavoriteColor(); + } + return this._favoriteColor; + } + get gender() { + return this._model.charInfo.personal.gender; + } + get partsTransform() { + if (!this._partsTransform) { + this._partsTransform = this._getPartsTransform(); + } + return this._partsTransform; + } + get boundingBox() { + if (!this._boundingBox) { + this._boundingBox = this._getBoundingBox(); + } + return this._boundingBox; + } + static BodyScaleMode = { + Apply: 0, + Limit: 1 + }; + getBodyScale(scaleMode = CharModel.BodyScaleMode.Apply) { + const build = this._model.charInfo.body.build; + const height2 = this._model.charInfo.body.height; + const bodyScale = new Vector3; + switch (scaleMode) { + case CharModel.BodyScaleMode.Apply: { + bodyScale.x = build * (height2 * 0.003671875 + 0.4) / 128 + height2 * 0.001796875 + 0.4; + bodyScale.y = height2 * 0.006015625 + 0.5; + break; + } + case CharModel.BodyScaleMode.Limit: { + const heightFactor = height2 / 128; + bodyScale.y = heightFactor * 0.55 + 0.6; + bodyScale.x = heightFactor * 0.3 + 0.6; + bodyScale.x = (heightFactor * 0.6 + 0.8 - bodyScale.x) * (build / 128) + bodyScale.x; + break; + } + default: + throw new Error(`getBodyScale: Unexpected value for scaleMode: ${scaleMode}`); + } + bodyScale.z = bodyScale.x; + return bodyScale; + } +} +var PantsColor = { + GrayNormal: 0, + BluePresent: 1, + RedRegular: 2, + GoldSpecial: 3 +}; +var pantsColors = { + [PantsColor.GrayNormal]: new Color(4212558), + [PantsColor.BluePresent]: new Color(2637946), + [PantsColor.RedRegular]: new Color(7348245), + [PantsColor.GoldSpecial]: new Color(12623920) +}; +function _allocateModelSource(data2, module2) { + const bufferPtr = module2._malloc(FFLiCharInfo.size); + const modelSource = { + dataSource: FFLDataSource.DIRECT_POINTER, + pBuffer: bufferPtr, + index: 0 + }; + if (!(data2 instanceof Uint8Array)) { + try { + if (typeof data2 !== "object") { + throw new Error("_allocateModelSource: data passed in is not FFLiCharInfo object or Uint8Array"); + } + data2 = FFLiCharInfo.pack(data2); + } catch (e) { + module2._free(bufferPtr); + throw e; + } + } + function setStudioData(src) { + const studio = StudioCharInfo.unpack(src); + const charInfo = convertStudioCharInfoToFFLiCharInfo(studio); + data2 = FFLiCharInfo.pack(charInfo); + module2.HEAPU8.set(data2, bufferPtr); + } + function callGetCharInfoFunc(data3, size, funcName) { + const dataPtr = module2._malloc(size); + module2.HEAPU8.set(data3, dataPtr); + const result = module2[funcName](bufferPtr, dataPtr); + module2._free(dataPtr); + if (!result) { + module2._free(bufferPtr); + throw new Error(`_allocateModelSource: call to ${funcName} returned false, CharInfo verification probably failed`); + } + } + switch (data2.length) { + case FFLStoreData_size: { + callGetCharInfoFunc(data2, FFLStoreData_size, "_FFLpGetCharInfoFromStoreData"); + break; + } + case 74: + case 76: { + callGetCharInfoFunc(data2, 74, "_FFLpGetCharInfoFromMiiDataOfficialRFL"); + break; + } + case FFLiCharInfo.size: + module2.HEAPU8.set(data2, bufferPtr); + break; + case StudioCharInfo.size + 1: { + data2 = studioURLObfuscationDecode(data2); + setStudioData(data2); + break; + } + case StudioCharInfo.size: { + setStudioData(data2); + break; + } + default: { + module2._free(bufferPtr); + throw new Error(`_allocateModelSource: Unknown data length: ${data2.length}`); + } + } + return modelSource; +} +function verifyCharInfo(data2, module2, verifyName = false) { + let charInfoPtr = 0; + let charInfoAllocated = false; + if (typeof data2 === "number") { + charInfoPtr = data2; + charInfoAllocated = false; + } else { + charInfoAllocated = true; + charInfoPtr = module2._malloc(FFLiCharInfo.size); + module2.HEAPU8.set(data2, charInfoPtr); + } + const result = module2._FFLiVerifyCharInfoWithReason(charInfoPtr, verifyName); + if (charInfoAllocated) { + module2._free(charInfoPtr); + } + if (result !== 0) { + throw new FFLiVerifyReasonException(result); + } +} +function makeExpressionFlag(expressions) { + function checkRange(i) { + if (i >= FFLExpression.MAX) { + throw new Error(`makeExpressionFlag: input out of range: got ${i}, max: ${FFLExpression.MAX}`); + } + } + function warnIfChangesShapes(i) { + const expressionsDisablingNose = [49, 50, 51, 52, 61, 62]; + const expressionsDisablingMask = [61, 62]; + const prefix = `makeExpressionFlag > warnIfChangesShapes: An expression was enabled (${i}) that is meant to disable nose or mask shape for the entire CharModel, so it is only recommended to set this as a single expression rather than as one of multiple.`; + if (expressionsDisablingNose.indexOf(i) !== -1) { + console.warn(`${prefix} (nose shape)`); + } + if (expressionsDisablingMask.indexOf(i) !== -1) { + console.warn(`${prefix} (in this case, MASK SHAPE so there is supposed to be NO FACE)`); + } + } + const flags = new Uint32Array([0, 0, 0]); + if (typeof expressions === "number") { + expressions = [expressions]; + } else if (!Array.isArray(expressions)) { + throw new Error("makeExpressionFlag: expected array or single number"); + } + for (const index2 of expressions) { + checkRange(index2); + warnIfChangesShapes(index2); + const part = Math.floor(index2 / 32); + const bitIndex = index2 % 32; + flags[part] |= 1 << bitIndex; + } + return flags; +} +function createCharModel(data2, modelDesc, materialClass, module2, verify = true) { + modelDesc = modelDesc || FFLCharModelDescDefault; + if (!module2 || !module2._malloc) { + throw new Error("createCharModel: module is null or does not have ._malloc."); + } + if (!data2) { + throw new Error("createCharModel: data is null or undefined."); + } + if (typeof modelDesc !== "object" || modelDesc.allExpressionFlag === undefined) { + throw new Error("createCharModel: modelDesc argument is invalid, make sure it is FFLCharModelDesc."); + } + const modelSourcePtr = module2._malloc(FFLCharModelSource.size); + const modelDescPtr = module2._malloc(FFLCharModelDesc.size); + const charModelPtr = module2._malloc(FFLiCharModel.size); + const modelSource = _allocateModelSource(data2, module2); + const charInfoPtr = modelSource.pBuffer; + const modelSourceBuffer = FFLCharModelSource.pack(modelSource); + module2.HEAPU8.set(modelSourceBuffer, modelSourcePtr); + modelDesc.modelFlag |= FFLModelFlag.NEW_EXPRESSIONS; + const modelDescBuffer = FFLCharModelDesc.pack(modelDesc); + module2.HEAPU8.set(modelDescBuffer, modelDescPtr); + let textureManager = null; + try { + if (verify) { + verifyCharInfo(charInfoPtr, module2, false); + } + textureManager = new TextureManager(module2, false); + const result = module2._FFLInitCharModelCPUStepWithCallback(charModelPtr, modelSourcePtr, modelDescPtr, textureManager._textureCallbackPtr); + if (result === FFLResult.FILE_INVALID) { + throw new BrokenInitModel; + } + FFLResultException.handleResult(result, "FFLInitCharModelCPUStep"); + } catch (error) { + if (textureManager) { + textureManager.dispose(); + } + module2._free(charModelPtr); + throw error; + } finally { + module2._free(modelSourcePtr); + module2._free(modelDescPtr); + module2._free(charInfoPtr); + if (textureManager) { + textureManager.disposeCallback(); + } + } + const charModel = new CharModel(charModelPtr, module2, materialClass, textureManager); + charModel._data = data2; + console.debug(`createCharModel: Initialized for "${charModel._model.charInfo.personal.name}", ptr =`, charModelPtr); + return charModel; +} +function matSupportsFFL(material) { + return "modulateMode" in material.prototype; +} +function drawParamToMesh(drawParam, materialClass, module2, texManager) { + if (!drawParam) { + throw new Error("drawParamToMesh: drawParam may be null."); + } + if (!texManager) { + throw new Error("drawParamToMesh: Passed in TextureManager is null or undefined, is it constructed?"); + } + if (typeof materialClass !== "function") { + throw new Error("drawParamToMesh: materialClass is unexpectedly not a function."); + } + if (drawParam.primitiveParam.indexCount === 0) { + return null; + } + const geometry = _bindDrawParamGeometry(drawParam, module2); + const cullModeToThreeSide = { + [FFLCullMode.NONE]: DoubleSide, + [FFLCullMode.BACK]: FrontSide, + [FFLCullMode.FRONT]: BackSide, + [FFLCullMode.MAX]: DoubleSide + }; + const side = cullModeToThreeSide[drawParam.cullMode]; + if (side === undefined) { + throw new Error(`drawParamToMesh: Unexpected value for FFLCullMode: ${drawParam.cullMode}`); + } + const texture = _getTextureFromModulateParam(drawParam.modulateParam, texManager); + const isFFLMaterial = matSupportsFFL(materialClass); + const params = _applyModulateParam(drawParam.modulateParam, module2, isFFLMaterial); + const materialParam = { + side, + map: texture, + ...params + }; + if (geometry.attributes.tangent === undefined && "useSpecularModeBlinn" in materialClass.prototype) { + materialParam.useSpecularModeBlinn = true; + } + const material = new materialClass(materialParam); + const mesh = new Mesh(geometry, material); + if (drawParam.primitiveParam.pAdjustMatrix !== 0) { + _applyAdjustMatrixToMesh(drawParam.primitiveParam.pAdjustMatrix, mesh, module2.HEAPF32); + } + if (mesh.geometry.userData) { + mesh.geometry.userData.modulateMode = drawParam.modulateParam.mode; + mesh.geometry.userData.modulateType = drawParam.modulateParam.type; + mesh.geometry.userData.color = params.color instanceof Color ? [params.color.r, params.color.g, params.color.b, 1] : [1, 1, 1, 1]; + mesh.geometry.userData.cullMode = drawParam.cullMode; + } + return mesh; +} +function _bindDrawParamGeometry(drawParam, module2) { + function unexpectedStride(typeStr, stride) { + throw new Error(`_bindDrawParamGeometry: Unexpected stride for attribute ${typeStr}: ${stride}`); + } + const attributes = drawParam.attributeBufferParam.attributeBuffers; + const positionBuffer = attributes[FFLAttributeBufferType.POSITION]; + if (positionBuffer.size === 0) { + throw new Error("_bindDrawParamGeometry: Position buffer must not have size of 0"); + } + const vertexCount = positionBuffer.size / positionBuffer.stride; + const geometry = new BufferGeometry; + const indexPtr = drawParam.primitiveParam.pIndexBuffer / 2; + const indexCount = drawParam.primitiveParam.indexCount; + const indices = module2.HEAPU16.subarray(indexPtr, indexPtr + indexCount); + geometry.setIndex(new Uint16BufferAttribute(indices, 1)); + for (const typeStr in attributes) { + const buffer = attributes[typeStr]; + const type = parseInt(typeStr); + if (buffer.size === 0) { + continue; + } + switch (type) { + case FFLAttributeBufferType.POSITION: { + if (buffer.stride === 16) { + const ptr = buffer.ptr / 4; + const data2 = module2.HEAPF32.subarray(ptr, ptr + vertexCount * 4); + const interleavedBuffer = new InterleavedBuffer(data2, 4); + geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0)); + } else if (buffer.stride === 6) { + const ptr = buffer.ptr / 2; + const data2 = module2.HEAPU16.subarray(ptr, ptr + vertexCount * 3); + geometry.setAttribute("position", new Float16BufferAttribute(data2, 3)); + } else { + unexpectedStride(typeStr, buffer.stride); + } + break; + } + case FFLAttributeBufferType.NORMAL: { + const data2 = module2.HEAP8.subarray(buffer.ptr, buffer.ptr + buffer.size); + geometry.setAttribute("normal", new Int8BufferAttribute(data2, buffer.stride, true)); + break; + } + case FFLAttributeBufferType.TANGENT: { + const data2 = module2.HEAP8.subarray(buffer.ptr, buffer.ptr + buffer.size); + geometry.setAttribute("tangent", new Int8BufferAttribute(data2, buffer.stride, true)); + break; + } + case FFLAttributeBufferType.TEXCOORD: { + if (buffer.stride === 8) { + const ptr = buffer.ptr / 4; + const data2 = module2.HEAPF32.subarray(ptr, ptr + vertexCount * 2); + geometry.setAttribute("uv", new Float32BufferAttribute(data2, 2)); + } else if (buffer.stride === 4) { + const ptr = buffer.ptr / 2; + const data2 = module2.HEAPU16.subarray(ptr, ptr + vertexCount * 2); + geometry.setAttribute("uv", new Float16BufferAttribute(data2, 2)); + } else { + unexpectedStride(typeStr, buffer.stride); + } + break; + } + case FFLAttributeBufferType.COLOR: { + if (buffer.stride === 0) { + break; + } + const data2 = module2.HEAPU8.subarray(buffer.ptr, buffer.ptr + buffer.size); + geometry.setAttribute("_color", new Uint8BufferAttribute(data2, buffer.stride, true)); + break; + } + } + } + return geometry; +} +function _getTextureFromModulateParam(modulateParam, textureManager) { + if (!modulateParam.pTexture2D || modulateParam.pTexture2D === 1) { + return null; + } + const texturePtr = modulateParam.pTexture2D; + const texture = textureManager.get(texturePtr); + if (!texture) { + throw new Error(`_getTextureFromModulateParam: Texture not found for ${texturePtr}.`); + } + const applyMirrorTypes = [ + FFLModulateType.SHAPE_FACELINE, + FFLModulateType.SHAPE_CAP, + FFLModulateType.SHAPE_GLASS + ]; + if (applyMirrorTypes.indexOf(modulateParam.type) !== -1) { + texture.wrapS = MirroredRepeatWrapping; + texture.wrapT = MirroredRepeatWrapping; + texture.needsUpdate = true; + } + return texture; +} +function _getBlendOptionsFromModulateType(modulateType, modulateMode) { + if (modulateMode !== 0 && modulateType >= FFLModulateType.SHAPE_MAX && modulateType <= FFLModulateType.MOLE) { + return { + blending: CustomBlending, + blendSrc: OneMinusDstAlphaFactor, + blendSrcAlpha: SrcAlphaFactor, + blendDst: DstAlphaFactor + }; + } else if (modulateMode !== 0 && modulateType >= FFLModulateType.FACE_MAKE && modulateType <= FFLModulateType.FILL) { + return { + blending: CustomBlending, + blendSrc: SrcAlphaFactor, + blendDst: OneMinusSrcAlphaFactor, + blendSrcAlpha: OneFactor, + blendDstAlpha: OneFactor + }; + } + return {}; +} +function _applyModulateParam(modulateParam, module2, forFFLMaterial = true) { + let color = null; + let color4 = null; + const f32 = module2.HEAPF32; + if (modulateParam.pColorG !== 0 && modulateParam.pColorB !== 0) { + color = [ + _getFFLColor3(_getFFLColor(modulateParam.pColorR, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorG, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorB, f32)) + ]; + if (self.eyeScleraHack && modulateParam.type === 12) { + color = [ + _getFFLColor3(_getFFLColor(modulateParam.pColorR, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorB, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorB, f32)) + ]; + } + } else if (modulateParam.pColorR !== 0) { + color4 = _getFFLColor(modulateParam.pColorR, f32); + color = _getFFLColor3(color4); + } + const opacity = color4 ? color4.a : 1; + const transparent = modulateParam.type >= FFLModulateType.SHAPE_MASK; + const lightEnable = !(modulateParam.type >= FFLModulateType.SHAPE_MAX && modulateParam.mode !== FFLModulateMode.CONSTANT); + const modulateModeType = forFFLMaterial ? { + modulateMode: modulateParam.mode, + modulateType: modulateParam.type + } : {}; + const param = Object.assign(modulateModeType, { + color, + opacity, + transparent, + depthWrite: !transparent, + ..._getBlendOptionsFromModulateType(modulateParam.type, modulateParam.mode) + }); + if (!lightEnable) { + param.lightEnable = lightEnable; + } + return param; +} +function _getFFLColor(colorPtr, heapf32) { + if (!colorPtr) { + throw new Error("_getFFLColor: Received null pointer"); + } + const colorData = heapf32.subarray(colorPtr / 4, colorPtr / 4 + 4); + return { r: colorData[0], g: colorData[1], b: colorData[2], a: colorData[3] }; +} +function _getFFLColor3(color) { + return new Color(color.r, color.g, color.b); +} +function _applyAdjustMatrixToMesh(pMtx, mesh, heapf32) { + const ptr = pMtx / 4; + const m = heapf32.slice(ptr, ptr + 48 / 4); + function matrixFromRowMajor3x4(m2) { + const matrix2 = new Matrix4; + matrix2.set(m2[0], m2[4], m2[8], m2[3], m2[1], m2[5], m2[9], m2[7], m2[2], m2[6], m2[10], m2[11], 0, 0, 0, 1); + return matrix2; + } + const matrix = matrixFromRowMajor3x4(m); + mesh.scale.setFromMatrixScale(matrix); + mesh.position.setFromMatrixPosition(matrix); + if (matrix.elements[0] === -1) { + mesh.scale.x = -1; + } +} +function initCharModelTextures(charModel, renderer2, materialClass = charModel._materialClass) { + if (!(renderer2 instanceof WebGLRenderer) && renderer2["isWebGPURenderer"] === undefined) { + throw new Error("initCharModelTextures: renderer is an invalid or unexpected type."); + } + const module2 = charModel._module; + charModel._materialTextureClass = materialClass; + const textureTempObject = charModel._getTextureTempObject(); + _drawFacelineTexture(charModel, textureTempObject, renderer2, module2, materialClass); + const clearAlpha = renderer2.getClearAlpha(); + clearAlpha !== 0 && renderer2.setClearAlpha(0); + _drawMaskTextures(charModel, textureTempObject, renderer2, module2, materialClass); + charModel._finalizeCharModel(); + charModel.setExpression(charModel.expression); + clearAlpha !== 0 && renderer2.setClearAlpha(clearAlpha); + if (!matSupportsFFL(charModel._materialClass)) { + if (!matSupportsFFL(charModel._materialTextureClass)) { + console.warn("initCharModelTextures: charModel._materialClass does not support modulateMode (no getter), but the _materialTextureClass is either the same or also does not support modulateMode so textures will look wrong"); + } else { + convertModelTexturesToRGBA(charModel, renderer2, charModel._materialTextureClass); + } + } +} +function _drawFacelineTexture(charModel, textureTempObject, renderer2, module2, materialClass) { + const facelineTempObjectPtr = charModel._getFacelineTempObjectPtr(); + module2._FFLiInvalidateTempObjectFacelineTexture(facelineTempObjectPtr); + const drawParams = [ + textureTempObject.facelineTexture.drawParamFaceMake, + textureTempObject.facelineTexture.drawParamFaceLine, + textureTempObject.facelineTexture.drawParamFaceBeard + ].filter((dp) => dp && dp.modulateParam.pTexture2D !== 0); + if (drawParams.length === 0) { + console.debug("_drawFacelineTexture: Skipping faceline texture."); + return; + } + const bgColor = charModel.facelineColor; + const { scene: offscreenScene } = createSceneFromDrawParams(drawParams, bgColor, materialClass, charModel._module, charModel._textureManager); + const width2 = charModel._getResolution() / 2; + const height2 = charModel._getResolution(); + const options = { + depthBuffer: false, + stencilBuffer: false, + wrapS: MirroredRepeatWrapping, + wrapT: MirroredRepeatWrapping + }; + const target = createAndRenderToTarget(offscreenScene, getIdentCamera(), renderer2, width2, height2, options); + console.debug(`Creating target ${target.texture.id} for faceline`); + _setFaceline(charModel, target); + module2._FFLiDeleteTempObjectFacelineTexture(facelineTempObjectPtr, charModel._ptr, charModel._model.charModelDesc.resourceType); + disposeMeshes(offscreenScene); +} +function _drawMaskTextures(charModel, textureTempObject, renderer2, module2, materialClass) { + const maskTempObjectPtr = charModel._getMaskTempObjectPtr(); + const expressionFlagPtr = charModel._getExpressionFlagPtr(); + const scenes = []; + for (let i = 0;i < charModel._model.maskTextures.pRenderTextures.length; i++) { + if (charModel._model.maskTextures.pRenderTextures[i] === 0) { + continue; + } + const rawMaskDrawParamPtr = textureTempObject.maskTextures.pRawMaskDrawParam[i]; + const rawMaskDrawParam = FFLiRawMaskDrawParam.unpack(module2.HEAPU8.subarray(rawMaskDrawParamPtr, rawMaskDrawParamPtr + FFLiRawMaskDrawParam.size)); + module2._FFLiInvalidateRawMask(rawMaskDrawParamPtr); + const { target, scene } = _drawMaskTexture(charModel, rawMaskDrawParam, renderer2, module2, materialClass); + console.debug(`Creating target ${target.texture.id} for mask ${i}`); + charModel._maskTargets[i] = target; + scenes.push(scene); + } + scenes.forEach((scene) => { + disposeMeshes(scene); + }); + module2._FFLiDeleteTempObjectMaskTextures(maskTempObjectPtr, expressionFlagPtr, charModel._model.charModelDesc.resourceType); + module2._FFLiDeleteTextureTempObject(charModel._ptr); +} +function _drawMaskTexture(charModel, rawMaskParam, renderer2, module2, materialClass) { + const drawParams = [ + rawMaskParam.drawParamRawMaskPartsMustache[0], + rawMaskParam.drawParamRawMaskPartsMustache[1], + rawMaskParam.drawParamRawMaskPartsMouth, + rawMaskParam.drawParamRawMaskPartsEyebrow[0], + rawMaskParam.drawParamRawMaskPartsEyebrow[1], + rawMaskParam.drawParamRawMaskPartsEye[0], + rawMaskParam.drawParamRawMaskPartsEye[1], + rawMaskParam.drawParamRawMaskPartsMole + ].filter((dp) => dp && dp.primitiveParam.indexCount !== 0); + if (drawParams.length === 0) { + throw new Error("_drawMaskTexture: All DrawParams are empty."); + } + const options = { + depthBuffer: false, + stencilBuffer: false + }; + const { scene: offscreenScene } = createSceneFromDrawParams(drawParams, null, materialClass, module2, charModel._textureManager); + const width2 = charModel._getResolution(); + const target = createAndRenderToTarget(offscreenScene, getIdentCamera(), renderer2, width2, width2, options); + return { target, scene: offscreenScene }; +} +function _setFaceline(charModel, target) { + if (!target || !target.texture) { + throw new Error("setFaceline: passed in RenderTarget is invalid"); + } + charModel._facelineTarget = target; + const mesh = charModel._facelineMesh; + if (!mesh || !(mesh instanceof Mesh)) { + throw new Error("setFaceline: faceline shape does not exist"); + } + target.texture._target = target; + mesh.material.map = target.texture; + mesh.material.needsUpdate = true; +} +function _texDrawRGBATarget(renderer2, material, userData, materialTextureClass) { + const plane = new PlaneGeometry(2, 2); + const scene = new Scene; + const bgClearRGBMesh = new Mesh(plane, new MeshBasicMaterial({ + color: material.color, + transparent: true, + opacity: 0, + blending: NoBlending + })); + scene.add(bgClearRGBMesh); + if (!material.map) { + throw new Error("_texDrawRGBATarget: material.map is null or undefined"); + } + const tex = material.map; + const texMat = new materialTextureClass({ + map: tex, + modulateMode: userData.modulateMode, + color: material.color, + lightEnable: false + }); + texMat.blending = NoBlending; + texMat.transparent = true; + const textureMesh = new Mesh(plane, texMat); + scene.add(textureMesh); + const target = createAndRenderToTarget(scene, getIdentCamera(false), renderer2, tex.image.width, tex.image.height, { + wrapS: tex.wrapS, + wrapT: tex.wrapT, + depthBuffer: false, + stencilBuffer: false + }); + target.texture._target = target; + material.map.dispose(); + material.map = target.texture; + material.color = new Color(1, 1, 1); + userData.modulateMode = 1; + return target; +} +function convertModelTexturesToRGBA(charModel, renderer2, materialTextureClass) { + const convertTextureForTypes = [ + FFLModulateType.SHAPE_CAP, + FFLModulateType.SHAPE_NOSELINE, + FFLModulateType.SHAPE_GLASS + ]; + if (!charModel.meshes) { + throw new Error("convertModelTexturesToRGBA: charModel.meshes is null."); + } + charModel.meshes.traverse((mesh) => { + if (!(mesh instanceof Mesh) || !mesh.geometry.userData.modulateType || !mesh.material.map || convertTextureForTypes.indexOf(mesh.geometry.userData.modulateType) === -1) { + return; + } + const target = _texDrawRGBATarget(renderer2, mesh.material, mesh.geometry.userData, materialTextureClass); + charModel._maskTargets.push(target); + }); +} +function createSceneFromDrawParams(drawParams, bgColor, ...drawParamArgs) { + const scene = new Scene; + scene.background = bgColor || null; + const meshes = []; + drawParams.forEach((param) => { + const mesh = drawParamToMesh(param, ...drawParamArgs); + if (mesh) { + scene.add(mesh); + meshes.push(mesh); + } + }); + return { scene, meshes }; +} +function getIdentCamera(flipY = false) { + const camera = new OrthographicCamera(-1, 1, flipY ? -1 : 1, flipY ? 1 : -1, 0.1, 10); + camera.position.z = 1; + return camera; +} +function createAndRenderToTarget(scene, camera, renderer2, width2, height2, targetOptions = {}) { + const options = { + minFilter: LinearFilter, + magFilter: LinearFilter, + ...targetOptions + }; + const renderTarget = renderer2["isWebGPURenderer"] === undefined ? new WebGLRenderTarget(width2, height2, options) : new RenderTarget(width2, height2, options); + const prevTarget = renderer2.getRenderTarget(); + renderer2.setRenderTarget(renderTarget); + renderer2.render(scene, camera); + renderer2.setRenderTarget(prevTarget); + return renderTarget; +} +function disposeMeshes(group, scene) { + function disposeMaterial(material) { + if (material.map) { + material.map.dispose(); + } + material.dispose(); + } + group.traverse((child) => { + if (!(child instanceof Mesh)) { + return; + } + if (child.geometry) { + child.geometry.dispose(); + } + if (child.material) { + Array.isArray(child.material) ? child.material.forEach((material) => { + disposeMaterial(material); + }) : disposeMaterial(child.material); + } + }); + if (scene && scene instanceof Scene) { + scene.remove(group); + } + group.children = []; +} +var ViewType = { + Face: 0, + MakeIcon: 1, + IconFovy45: 2 +}; +var StudioCharInfo = _.struct([ + _.uint8("beardColor"), + _.uint8("beardType"), + _.uint8("build"), + _.uint8("eyeAspect"), + _.uint8("eyeColor"), + _.uint8("eyeRotate"), + _.uint8("eyeScale"), + _.uint8("eyeType"), + _.uint8("eyeX"), + _.uint8("eyeY"), + _.uint8("eyebrowAspect"), + _.uint8("eyebrowColor"), + _.uint8("eyebrowRotate"), + _.uint8("eyebrowScale"), + _.uint8("eyebrowType"), + _.uint8("eyebrowX"), + _.uint8("eyebrowY"), + _.uint8("facelineColor"), + _.uint8("facelineMake"), + _.uint8("facelineType"), + _.uint8("facelineWrinkle"), + _.uint8("favoriteColor"), + _.uint8("gender"), + _.uint8("glassColor"), + _.uint8("glassScale"), + _.uint8("glassType"), + _.uint8("glassY"), + _.uint8("hairColor"), + _.uint8("hairFlip"), + _.uint8("hairType"), + _.uint8("height"), + _.uint8("moleScale"), + _.uint8("moleType"), + _.uint8("moleX"), + _.uint8("moleY"), + _.uint8("mouthAspect"), + _.uint8("mouthColor"), + _.uint8("mouthScale"), + _.uint8("mouthType"), + _.uint8("mouthY"), + _.uint8("mustacheScale"), + _.uint8("mustacheType"), + _.uint8("mustacheY"), + _.uint8("noseScale"), + _.uint8("noseType"), + _.uint8("noseY") +]); +function convertStudioCharInfoToFFLiCharInfo(src) { + return { + miiVersion: 0, + faceline: { + type: src.facelineType, + color: src.facelineColor, + texture: src.facelineWrinkle, + make: src.facelineMake + }, + hair: { + type: src.hairType, + color: commonColorMask(src.hairColor), + flip: src.hairFlip + }, + eye: { + type: src.eyeType, + color: commonColorMask(src.eyeColor), + scale: src.eyeScale, + aspect: src.eyeAspect, + rotate: src.eyeRotate, + x: src.eyeX, + y: src.eyeY + }, + eyebrow: { + type: src.eyebrowType, + color: commonColorMask(src.eyebrowColor), + scale: src.eyebrowScale, + aspect: src.eyebrowAspect, + rotate: src.eyebrowRotate, + x: src.eyebrowX, + y: src.eyebrowY + }, + nose: { + type: src.noseType, + scale: src.noseScale, + y: src.noseY + }, + mouth: { + type: src.mouthType, + color: commonColorMask(src.mouthColor), + scale: src.mouthScale, + aspect: src.mouthAspect, + y: src.mouthY + }, + beard: { + mustache: src.mustacheType, + type: src.beardType, + color: commonColorMask(src.beardColor), + scale: src.mustacheScale, + y: src.mustacheY + }, + glass: { + type: src.glassType, + color: commonColorMask(src.glassColor), + scale: src.glassScale, + y: src.glassY + }, + mole: { + type: src.moleType, + scale: src.moleScale, + x: src.moleX, + y: src.moleY + }, + body: { + height: src.height, + build: src.build + }, + personal: { + name: "", + creator: "", + gender: src.gender, + birthMonth: 0, + birthDay: 0, + favoriteColor: src.favoriteColor, + favorite: 0, + copyable: 0, + ngWord: 0, + localonly: 0, + regionMove: 0, + fontRegion: 0, + roomIndex: 0, + positionInRoom: 0, + birthPlatform: 3 + }, + createID: { + data: new Array(10).fill(0) + }, + padding_0: 0, + authorType: 0, + authorID: new Array(8).fill(0) + }; +} +function studioURLObfuscationDecode(data2) { + const decodedData = new Uint8Array(data2); + const random2 = decodedData[0]; + let previous = random2; + for (let i = 1;i < 48; i++) { + const encodedByte = decodedData[i]; + const original = (encodedByte - 7 + 256) % 256; + decodedData[i - 1] = original ^ previous; + previous = encodedByte; + } + return decodedData.slice(0, StudioCharInfo.size); +} +function stripSpaces(str) { + return str.replace(/\s+/g, ""); +} +function hexToUint8Array(hex) { + const match = hex.match(/.{1,2}/g); + const arr = (match ? match : []).map(function(byte) { + return parseInt(byte, 16); + }); + return new Uint8Array(arr); +} +function base64ToUint8Array(base64) { + const normalizedBase64 = base64.replace(/-/g, "+").replace(/_/g, "/"); + function padBase64(str) { + while (str.length % 4 !== 0) { + str += "="; + } + return str; + } + const paddedBase64 = padBase64(normalizedBase64); + const binaryString = atob(paddedBase64); + const len = binaryString.length; + const bytes = new Uint8Array(len); + for (let i = 0;i < len; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function parseHexOrB64ToUint8Array(text2) { + let inputData; + const textData = stripSpaces(text2); + if (/^[0-9a-fA-F]+$/.test(textData)) { + inputData = hexToUint8Array(textData); + } else { + inputData = base64ToUint8Array(textData); + } + return inputData; +} + +// src/constants/BodyShaderTypes.ts +var BodyType; +((BodyType2) => { + BodyType2["WiiU"] = "wiiu"; + BodyType2["Switch"] = "switch"; + BodyType2["Miitomo"] = "miitomo"; + BodyType2["StreetPass"] = "streetpass"; +})(BodyType ||= {}); +var ShaderType; +((ShaderType2) => { + ShaderType2["WiiU"] = "wiiu"; + ShaderType2["Switch"] = "switch"; + ShaderType2["LightDisabled"] = "lightDisabled"; + ShaderType2["Miitomo"] = "miitomo"; + ShaderType2["MiitomoBasic"] = "miitomo_basic"; + ShaderType2["WiiUBlinn"] = "wiiu_blinn"; + ShaderType2["WiiUFFLIconWithBody"] = "wiiu_ffliconwithbody"; + ShaderType2["WiiUToon"] = "wiiu_toon"; + ShaderType2["ThreeToon"] = "three_toon"; + ShaderType2["ThreePhong"] = "three_phong"; +})(ShaderType ||= {}); +function adjustShaderQuery(params, shader) { + switch (shader) { + case "wiiu" /* WiiU */: + case "switch" /* Switch */: + case "miitomo" /* Miitomo */: + params.set("shaderType", shader); + break; + case "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */: + params.set("shaderType", "ffliconwithbody"); + break; + case "wiiu_toon" /* WiiUToon */: + params.set("shaderType", "wiiu"); + break; + case "wiiu_blinn" /* WiiUBlinn */: + params.set("shaderType", "wiiu_blinn"); + break; + case "lightDisabled" /* LightDisabled */: + params.set("shaderType", "wiiu"); + params.set("lightEnable", "0"); + break; + default: + console.warn(`unknown shader type: ${shader}`); + } +} + +// src/class/3d/shader/ShaderUtils.ts +var import_FFLShaderMaterial2 = __toESM(require_FFLShaderMaterial(), 1); +var import_LUTShaderMaterial2 = __toESM(require_LUTShaderMaterial(), 1); +var import_localforage = __toESM(require_localforage(), 1); + +// src/class/3d/shader/FFLShaderAlternateMaterial.ts +var import_FFLShaderMaterial = __toESM(require_FFLShaderMaterial(), 1); +var import_LUTShaderMaterial = __toESM(require_LUTShaderMaterial(), 1); + +// src/class/3d/shader/fflShaderConst.ts +var FFLToonMaterial = { + ambient: new Color(0.8, 0.8, 0.8), + diffuse: new Color(0.8, 0.8, 0.8), + specular: new Color(0.1, 0.1, 0.1), + specularPower: 0.01, + specularMode: 0 +}; +var cLightAmbientFFLIconWithBody = new Color(0.5, 0.5, 0.5); +var cLightDiffuseFFLIconWithBody = new Color(0.9, 0.9, 0.9); +var cLightSpecularFFLIconWithBody = new Color(1, 1, 1); +var cLightDirGlossy = new Vector3(-0.35, 1, 0.8); +var cLightDirFFLIconWithBody = new Vector3(-0.5, 0.366, 0.785); +var cRimColor = new Vector4(0.3, 0.3, 0.3, 1); +var cPantsColorGray = [0.25098, 0.27451, 0.30588]; +var cPantsColorRed = [0.43922, 0.12549, 0.06275]; +var cPantsColorBlue = [0.15686, 0.25098, 0.47059]; +var cPantsColorGold = [0.75294, 0.62745, 0.18824]; +var cPantsColorRedHex = "#902010"; +var cPantsColorGoldHex = "#c0a030"; +var MiiFavoriteFFLColorLookupTable = { + 0: [0.824, 0.118, 0.078], + 1: [1, 0.431, 0.098], + 2: [1, 0.847, 0.125], + 3: [0.471, 0.824, 0.125], + 4: [0, 0.471, 0.188], + 5: [0.039, 0.282, 0.706], + 6: [0.235, 0.667, 0.871], + 7: [0.961, 0.353, 0.49], + 8: [0.451, 0.157, 0.678], + 9: [0.282, 0.22, 0.094], + 10: [0.878, 0.878, 0.878], + 11: [0.094, 0.094, 0.078] +}; + +// src/class/3d/shader/FFLShaderAlternateMaterial.ts +class FFLShaderBlinnMaterial extends import_FFLShaderMaterial.default { + constructor(options = {}) { + options = Object.assign({ + useSpecularModeBlinn: true + }, options); + super(options); + if (this.uniforms.u_material_specular_power) + this.uniforms.u_material_specular_power.value = 2; + } +} +class FFLShaderToonMaterial extends import_FFLShaderMaterial.default { + constructor(options = {}) { + options = Object.assign({}, options); + super(options); + this.uniforms.u_light_dir.value = cLightDirGlossy; + if (this.uniforms.u_material_ambient) { + this.uniforms.u_material_ambient.value = FFLToonMaterial.ambient; + this.uniforms.u_material_diffuse.value = FFLToonMaterial.diffuse; + this.uniforms.u_material_specular.value = FFLToonMaterial.specular; + this.uniforms.u_material_specular_power.value = FFLToonMaterial.specularPower; + this.uniforms.u_material_specular_mode.value = FFLToonMaterial.specularMode; + } + } +} + +class FFLShaderBrightMaterial extends import_FFLShaderMaterial.default { + constructor(options = {}) { + options = Object.assign({}, options); + super(options); + this.uniforms.u_light_dir.value = cLightDirFFLIconWithBody; + this.uniforms.u_light_ambient.value = cLightAmbientFFLIconWithBody; + this.uniforms.u_light_diffuse.value = cLightDiffuseFFLIconWithBody; + this.uniforms.u_light_specular.value = cLightSpecularFFLIconWithBody; + } +} + +class LUTShaderPretendoMaterial extends import_LUTShaderMaterial.default { + constructor(options = {}) { + options = Object.assign({}, options); + super(options); + this.uniforms.uDirLightDirAndType0.value = new Vector4(-0.2, 0.5, 0.8, -1); + this.uniforms.uDirLightDirAndType1.value = new Vector4(0, -0.19612, 0.98058, -1); + this.uniforms.uHSLightGroundColor.value = new Color(14793111).convertLinearToSRGB(); + this.uniforms.uHSLightSkyColor.value = new Color(14800590).convertLinearToSRGB(); + this.uniforms.uDirLightColor0.value = new Color(5919571).convertLinearToSRGB(); + this.uniforms.uDirLightColor1.value = new Color(1710104).convertLinearToSRGB(); + } +} + +// src/class/3d/shader/ShaderUtils.ts +var getSettingSafe = async (key2) => { + const value2 = await import_localforage.default.getItem("settings_" + key2); + if (value2 == null && key2 === "shaderType") { + return "wiiu"; + } + return value2; +}; +function traverseAddShader(model, shaderType) { + model.traverse((n) => { + const node = n; + if (node.isMesh) { + traverseMesh(node, shaderType); + } + }); +} +async function traverseMesh(node, shaderType) { + const shaderSetting = shaderType || await getSettingSafe("shaderType"); + const originalMaterial = node.material; + const userData = node.geometry.userData; + if (userData.ignore !== undefined) { + if (userData.ignore === 1) + return; + } + let modulateType = userData.modulateType; + if (userData.modulateType === undefined) + console.warn(`Mesh "${node.name}" is missing "modulateType" in userData.`); + const lightEnable = modulateType > 5 ? false : true; + let materialParam = modulateType !== undefined ? modulateType && modulateType < 9 ? import_FFLShaderMaterial2.default.materialParams[modulateType] : import_FFLShaderMaterial2.default.materialParams[0] : import_FFLShaderMaterial2.default.materialParams[0]; + let modulateMode = userData.modulateMode === undefined ? 0 : userData.modulateMode; + let modulateColor; + if (!userData.modulateColor) { + console.warn(`Mesh "${node.name}" is missing "modulateColor" in userData.`); + modulateColor = new Vector4(1, 0, 0, 1); + } else { + modulateColor = new Vector4(...userData.modulateColor, 1); + } + ColorManagement.enabled = false; + const defines = {}; + if (originalMaterial.map) { + defines.USE_MAP = ""; + originalMaterial.map.colorSpace = LinearSRGBColorSpace; + originalMaterial.needsUpdate = true; + } + let side = originalMaterial.side; + if (userData.cullMode !== undefined) { + switch (userData.cullMode) { + case 0: + side = DoubleSide; + break; + case 1: + side = FrontSide; + break; + case 2: + side = BackSide; + break; + } + } + let finalMat; + const isUsingShader = await isShaderMaterial(); + let modulate = isUsingShader ? { + modulateMode, + modulateType, + lightEnable: shaderSetting === "lightDisabled" /* LightDisabled */ ? false : true + } : {}; + const params = { + color: new Color(...modulateColor), + ...modulate, + map: originalMaterial.map || undefined, + side + }; + let shaderMaterial = await getShaderMaterialFromShaderType(shaderSetting); + finalMat = new shaderMaterial(params); + node.material = finalMat; +} +async function isShaderMaterial(shader = undefined) { + let shaderType = shader || await getSettingSafe("shaderType"); + switch (shaderType) { + case "wiiu" /* WiiU */: + case "wiiu_blinn" /* WiiUBlinn */: + case "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */: + case "wiiu_toon" /* WiiUToon */: + case "switch" /* Switch */: + case "miitomo" /* Miitomo */: + case "miitomo_basic" /* MiitomoBasic */: + return true; + case "lightDisabled" /* LightDisabled */: + case "three_toon" /* ThreeToon */: + case "three_phong" /* ThreePhong */: + return false; + } +} +async function getShaderMaterialFromShaderType(type) { + const shaderType = type || await getSettingSafe("shaderType"); + switch (shaderType) { + case "wiiu" /* WiiU */: + return import_FFLShaderMaterial2.default; + case "lightDisabled" /* LightDisabled */: + return MeshBasicMaterial; + case "wiiu_blinn" /* WiiUBlinn */: + return FFLShaderBlinnMaterial; + case "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */: + return FFLShaderBrightMaterial; + case "wiiu_toon" /* WiiUToon */: + return FFLShaderToonMaterial; + case "switch" /* Switch */: + return import_FFLShaderMaterial2.default; + case "miitomo" /* Miitomo */: + return import_LUTShaderMaterial2.default; + case "miitomo_basic" /* MiitomoBasic */: + return LUTShaderPretendoMaterial; + case "three_toon" /* ThreeToon */: + return MeshToonMaterial; + case "three_phong" /* ThreePhong */: + return MeshPhongMaterial; + } +} +var ThreeMaterialStandardLights = (scene) => { + const intensity = Number(REVISION) >= 155 ? Math.PI : 1; + const ambientLight = new AmbientLight(new Color(0.73, 0.73, 0.73), intensity); + const directionalLight = new DirectionalLight(new Color(0.6, 0.6, 0.6), intensity); + directionalLight.position.set(-0.455, 0.348, 0.5); + ambientLight.name = "ambientLight"; + directionalLight.name = "directionalLight"; + scene.add(ambientLight, directionalLight); +}; +var ThreeMaterialToonLights = (scene) => { + const intensity = 2.5; + const ambientLight = new AmbientLight(new Color(0.73, 0.73, 0.73), intensity); + const directionalLight = new DirectionalLight(new Color(0.6, 0.6, 0.6), intensity); + directionalLight.position.set(-0.255, 0.348, 0.5); + ambientLight.name = "ambientLight"; + directionalLight.name = "directionalLight"; + scene.add(ambientLight, directionalLight); +}; +async function getSimpleMaterialAddLights(type) { + const shaderType = type || await getSettingSafe("shaderType"); + switch (shaderType) { + case "wiiu" /* WiiU */: + case "wiiu_blinn" /* WiiUBlinn */: + case "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */: + case "wiiu_toon" /* WiiUToon */: + case "switch" /* Switch */: + case "miitomo" /* Miitomo */: + case "miitomo_basic" /* MiitomoBasic */: + return; + case "lightDisabled" /* LightDisabled */: + case "three_phong" /* ThreePhong */: + return ThreeMaterialStandardLights; + case "three_toon" /* ThreeToon */: + return ThreeMaterialToonLights; + } +} +function cleanupLights(scene) { + let amb = scene.getObjectByName("ambientLight"); + let dir = scene.getObjectByName("directionalLight"); + if (amb) + scene.remove(amb); + if (dir) + scene.remove(dir); +} + +// src/util/ModelLoader.ts +var import_jszip = __toESM(require_lib(), 1); +var import_localforage2 = __toESM(require_localforage(), 1); +// node_modules/three/examples/jsm/animation/CCDIKSolver.js +var _q = new Quaternion; +var _targetPos = new Vector3; +var _targetVec = new Vector3; +var _effectorPos = new Vector3; +var _effectorVec = new Vector3; +var _linkPos = new Vector3; +var _invLinkQ = new Quaternion; +var _linkScale = new Vector3; +var _axis2 = new Vector3; +var _vector4 = new Vector3; +var _matrix2 = new Matrix4; +// node_modules/three/examples/jsm/controls/ArcballControls.js +var STATE = { + IDLE: Symbol(), + ROTATE: Symbol(), + PAN: Symbol(), + SCALE: Symbol(), + FOV: Symbol(), + FOCUS: Symbol(), + ZROTATE: Symbol(), + TOUCH_MULTI: Symbol(), + ANIMATION_FOCUS: Symbol(), + ANIMATION_ROTATE: Symbol() +}; +var INPUT = { + NONE: Symbol(), + ONE_FINGER: Symbol(), + ONE_FINGER_SWITCHED: Symbol(), + TWO_FINGER: Symbol(), + MULT_FINGER: Symbol(), + CURSOR: Symbol() +}; +var _transformation = { + camera: new Matrix4, + gizmos: new Matrix4 +}; +var _raycaster = new Raycaster; +var _offset2 = new Vector3; +var _gizmoMatrixStateTemp = new Matrix4; +var _cameraMatrixStateTemp = new Matrix4; +var _scalePointTemp = new Vector3; +// node_modules/three/examples/jsm/controls/DragControls.js +var _plane = new Plane; +var _pointer = new Vector2; +var _offset3 = new Vector3; +var _diff2 = new Vector2; +var _previousPointer = new Vector2; +var _intersection = new Vector3; +var _worldPosition = new Vector3; +var _inverseMatrix2 = new Matrix4; +var _up = new Vector3; +var _right = new Vector3; +// node_modules/three/examples/jsm/controls/FirstPersonControls.js +var _lookDirection = new Vector3; +var _spherical = new Spherical; +var _target2 = new Vector3; +var _targetPosition = new Vector3; +// node_modules/three/examples/jsm/controls/FlyControls.js +var _tmpQuaternion = new Quaternion; +// node_modules/three/examples/jsm/controls/OrbitControls.js +var _ray2 = new Ray; +var _plane2 = new Plane; +var _TILT_LIMIT = Math.cos(70 * MathUtils.DEG2RAD); +var _v = new Vector3; +var _twoPI = 2 * Math.PI; +// node_modules/three/examples/jsm/controls/PointerLockControls.js +var _euler = new Euler(0, 0, 0, "YXZ"); +var _vector6 = new Vector3; +var _PI_2 = Math.PI / 2; +// node_modules/three/examples/jsm/controls/TrackballControls.js +var _v22 = new Vector2; +var _mouseChange = new Vector2; +var _objectUp = new Vector3; +var _pan = new Vector3; +var _axis3 = new Vector3; +var _quaternion2 = new Quaternion; +var _eyeDirection = new Vector3; +var _objectUpDirection = new Vector3; +var _objectSidewaysDirection = new Vector3; +var _moveDirection = new Vector3; +// node_modules/three/examples/jsm/controls/TransformControls.js +var _raycaster2 = new Raycaster; +var _tempVector = new Vector3; +var _tempVector2 = new Vector3; +var _tempQuaternion = new Quaternion; +var _unit = { + X: new Vector3(1, 0, 0), + Y: new Vector3(0, 1, 0), + Z: new Vector3(0, 0, 1) +}; +var _tempEuler = new Euler; +var _alignVector = new Vector3(0, 1, 0); +var _zeroVector = new Vector3(0, 0, 0); +var _lookAtMatrix = new Matrix4; +var _tempQuaternion2 = new Quaternion; +var _identityQuaternion = new Quaternion; +var _dirVector = new Vector3; +var _tempMatrix = new Matrix4; +var _unitX = new Vector3(1, 0, 0); +var _unitY = new Vector3(0, 1, 0); +var _unitZ = new Vector3(0, 0, 1); +var _v12 = new Vector3; +var _v23 = new Vector3; +var _v32 = new Vector3; +// node_modules/three/examples/jsm/csm/CSMFrustum.js +var inverseProjectionMatrix = new Matrix4; + +class CSMFrustum { + constructor(data2) { + data2 = data2 || {}; + this.zNear = data2.webGL === true ? -1 : 0; + this.vertices = { + near: [ + new Vector3, + new Vector3, + new Vector3, + new Vector3 + ], + far: [ + new Vector3, + new Vector3, + new Vector3, + new Vector3 + ] + }; + if (data2.projectionMatrix !== undefined) { + this.setFromProjectionMatrix(data2.projectionMatrix, data2.maxFar || 1e4); + } + } + setFromProjectionMatrix(projectionMatrix, maxFar) { + const zNear = this.zNear; + const isOrthographic = projectionMatrix.elements[2 * 4 + 3] === 0; + inverseProjectionMatrix.copy(projectionMatrix).invert(); + this.vertices.near[0].set(1, 1, zNear); + this.vertices.near[1].set(1, -1, zNear); + this.vertices.near[2].set(-1, -1, zNear); + this.vertices.near[3].set(-1, 1, zNear); + this.vertices.near.forEach(function(v) { + v.applyMatrix4(inverseProjectionMatrix); + }); + this.vertices.far[0].set(1, 1, 1); + this.vertices.far[1].set(1, -1, 1); + this.vertices.far[2].set(-1, -1, 1); + this.vertices.far[3].set(-1, 1, 1); + this.vertices.far.forEach(function(v) { + v.applyMatrix4(inverseProjectionMatrix); + const absZ = Math.abs(v.z); + if (isOrthographic) { + v.z *= Math.min(maxFar / absZ, 1); + } else { + v.multiplyScalar(Math.min(maxFar / absZ, 1)); + } + }); + return this.vertices; + } + split(breaks, target) { + while (breaks.length > target.length) { + target.push(new CSMFrustum); + } + target.length = breaks.length; + for (let i = 0;i < breaks.length; i++) { + const cascade = target[i]; + if (i === 0) { + for (let j = 0;j < 4; j++) { + cascade.vertices.near[j].copy(this.vertices.near[j]); + } + } else { + for (let j = 0;j < 4; j++) { + cascade.vertices.near[j].lerpVectors(this.vertices.near[j], this.vertices.far[j], breaks[i - 1]); + } + } + if (i === breaks.length - 1) { + for (let j = 0;j < 4; j++) { + cascade.vertices.far[j].copy(this.vertices.far[j]); + } + } else { + for (let j = 0;j < 4; j++) { + cascade.vertices.far[j].lerpVectors(this.vertices.near[j], this.vertices.far[j], breaks[i]); + } + } + } + } + toSpace(cameraMatrix, target) { + for (let i = 0;i < 4; i++) { + target.vertices.near[i].copy(this.vertices.near[i]).applyMatrix4(cameraMatrix); + target.vertices.far[i].copy(this.vertices.far[i]).applyMatrix4(cameraMatrix); + } + } +} + +// node_modules/three/examples/jsm/csm/CSMShader.js +var CSMShader = { + lights_fragment_begin: ` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); + +vec3 geometryClearcoatNormal = vec3( 0.0 ); + +#ifdef USE_CLEARCOAT + + geometryClearcoatNormal = clearcoatNormal; + +#endif + +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + // Iridescence F0 approximation + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif + +IncidentLight directLight; + +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + + pointLight = pointLights[ i ]; + + getPointLightInfo( pointLight, geometryPosition, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + + spotLight = spotLights[ i ]; + + getSpotLightInfo( spotLight, geometryPosition, directLight ); + + // spot lights are ordered [shadows with maps, shadows without maps, maps without shadows, none] + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + + #endif + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES ) + + DirectionalLight directionalLight; + float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear); + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + + #if defined( USE_SHADOWMAP ) && defined( CSM_FADE ) + vec2 cascade; + float cascadeCenter; + float closestEdge; + float margin; + float csmx; + float csmy; + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + + #if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + // NOTE: Depth gets larger away from the camera. + // cascade.x is closer, cascade.y is further + cascade = CSM_cascades[ i ]; + cascadeCenter = ( cascade.x + cascade.y ) / 2.0; + closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y; + margin = 0.25 * pow( closestEdge, 2.0 ); + csmx = cascade.x - margin / 2.0; + csmy = cascade.y + margin / 2.0; + if( linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) { + + float dist = min( linearDepth - csmx, csmy - linearDepth ); + float ratio = clamp( dist / margin, 0.0, 1.0 ); + + vec3 prevColor = directLight.color; + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + + bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter; + directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 ); + + ReflectedLight prevLight = reflectedLight; + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter; + float blendRatio = shouldBlend ? ratio : 1.0; + + reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio ); + reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio ); + reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio ); + reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio ); + + } + #endif + + } + #pragma unroll_loop_end + #elif defined (USE_SHADOWMAP) + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + + #if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + + directionalLightShadow = directionalLightShadows[ i ]; + if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + + if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + #endif + + } + #pragma unroll_loop_end + + #elif ( NUM_DIR_LIGHT_SHADOWS > 0 ) + // note: no loop here - all CSM lights are in fact one light only + getDirectionalLightInfo( directionalLights[0], directLight ); + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + #endif + + #if ( NUM_DIR_LIGHTS > NUM_DIR_LIGHT_SHADOWS) + // compute the lights not casting shadows (if any) + + #pragma unroll_loop_start + for ( int i = NUM_DIR_LIGHT_SHADOWS; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + + getDirectionalLightInfo( directionalLight, directLight ); + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + + #endif + +#endif + + +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !defined( USE_CSM ) && !defined( CSM_CASCADES ) + + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + + getDirectionalLightInfo( directionalLight, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + + RectAreaLight rectAreaLight; + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if defined( RE_IndirectDiffuse ) + + vec3 iblIrradiance = vec3( 0.0 ); + + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + + #if defined( USE_LIGHT_PROBES ) + + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + + #endif + + #if ( NUM_HEMI_LIGHTS > 0 ) + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + + } + #pragma unroll_loop_end + + #endif + +#endif + +#if defined( RE_IndirectSpecular ) + + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); + +#endif +`, + lights_pars_begin: ` +#if defined( USE_CSM ) && defined( CSM_CASCADES ) +uniform vec2 CSM_cascades[CSM_CASCADES]; +uniform float cameraNear; +uniform float shadowFar; +#endif + ` + ShaderChunk.lights_pars_begin +}; + +// node_modules/three/examples/jsm/csm/CSM.js +var _cameraToLightMatrix = new Matrix4; +var _lightSpaceFrustum = new CSMFrustum({ webGL: true }); +var _center2 = new Vector3; +var _bbox = new Box3; +var _lightOrientationMatrix = new Matrix4; +var _lightOrientationMatrixInverse = new Matrix4; +var _up2 = new Vector3(0, 1, 0); +// node_modules/three/examples/jsm/postprocessing/Pass.js +class Pass { + constructor() { + this.isPass = true; + this.enabled = true; + this.needsSwap = true; + this.clear = false; + this.renderToScreen = false; + } + setSize() { + } + render() { + console.error("THREE.Pass: .render() must be implemented in derived pass."); + } + dispose() { + } +} +var _camera2 = new OrthographicCamera(-1, 1, 1, -1, 0, 1); + +class FullscreenTriangleGeometry extends BufferGeometry { + constructor() { + super(); + this.setAttribute("position", new Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3)); + this.setAttribute("uv", new Float32BufferAttribute([0, 2, 0, 0, 2, 0], 2)); + } +} +var _geometry2 = new FullscreenTriangleGeometry; + +class FullScreenQuad { + constructor(material) { + this._mesh = new Mesh(_geometry2, material); + } + dispose() { + this._mesh.geometry.dispose(); + } + render(renderer2) { + renderer2.render(this._mesh, _camera2); + } + get material() { + return this._mesh.material; + } + set material(value2) { + this._mesh.material = value2; + } +} +// node_modules/three/examples/jsm/exporters/DRACOExporter.js +class DRACOExporter { + parse(object, options = {}) { + options = Object.assign({ + decodeSpeed: 5, + encodeSpeed: 5, + encoderMethod: DRACOExporter.MESH_EDGEBREAKER_ENCODING, + quantization: [16, 8, 8, 8, 8], + exportUvs: true, + exportNormals: true, + exportColor: false + }, options); + if (DracoEncoderModule === undefined) { + throw new Error("THREE.DRACOExporter: required the draco_encoder to work."); + } + const geometry = object.geometry; + const dracoEncoder = DracoEncoderModule(); + const encoder = new dracoEncoder.Encoder; + let builder; + let dracoObject; + if (object.isMesh === true) { + builder = new dracoEncoder.MeshBuilder; + dracoObject = new dracoEncoder.Mesh; + const vertices = geometry.getAttribute("position"); + builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); + const faces = geometry.getIndex(); + if (faces !== null) { + builder.AddFacesToMesh(dracoObject, faces.count / 3, faces.array); + } else { + const faces2 = new (vertices.count > 65535 ? Uint32Array : Uint16Array)(vertices.count); + for (let i = 0;i < faces2.length; i++) { + faces2[i] = i; + } + builder.AddFacesToMesh(dracoObject, vertices.count, faces2); + } + if (options.exportNormals === true) { + const normals = geometry.getAttribute("normal"); + if (normals !== undefined) { + builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.NORMAL, normals.count, normals.itemSize, normals.array); + } + } + if (options.exportUvs === true) { + const uvs = geometry.getAttribute("uv"); + if (uvs !== undefined) { + builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.TEX_COORD, uvs.count, uvs.itemSize, uvs.array); + } + } + if (options.exportColor === true) { + const colors = geometry.getAttribute("color"); + if (colors !== undefined) { + const array = createVertexColorSRGBArray(colors); + builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, array); + } + } + } else if (object.isPoints === true) { + builder = new dracoEncoder.PointCloudBuilder; + dracoObject = new dracoEncoder.PointCloud; + const vertices = geometry.getAttribute("position"); + builder.AddFloatAttribute(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); + if (options.exportColor === true) { + const colors = geometry.getAttribute("color"); + if (colors !== undefined) { + const array = createVertexColorSRGBArray(colors); + builder.AddFloatAttribute(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, array); + } + } + } else { + throw new Error("DRACOExporter: Unsupported object type."); + } + const encodedData = new dracoEncoder.DracoInt8Array; + const encodeSpeed = options.encodeSpeed !== undefined ? options.encodeSpeed : 5; + const decodeSpeed = options.decodeSpeed !== undefined ? options.decodeSpeed : 5; + encoder.SetSpeedOptions(encodeSpeed, decodeSpeed); + if (options.encoderMethod !== undefined) { + encoder.SetEncodingMethod(options.encoderMethod); + } + if (options.quantization !== undefined) { + for (let i = 0;i < 5; i++) { + if (options.quantization[i] !== undefined) { + encoder.SetAttributeQuantization(i, options.quantization[i]); + } + } + } + let length2; + if (object.isMesh === true) { + length2 = encoder.EncodeMeshToDracoBuffer(dracoObject, encodedData); + } else { + length2 = encoder.EncodePointCloudToDracoBuffer(dracoObject, true, encodedData); + } + dracoEncoder.destroy(dracoObject); + if (length2 === 0) { + throw new Error("THREE.DRACOExporter: Draco encoding failed."); + } + const outputData = new Int8Array(new ArrayBuffer(length2)); + for (let i = 0;i < length2; i++) { + outputData[i] = encodedData.GetValue(i); + } + dracoEncoder.destroy(encodedData); + dracoEncoder.destroy(encoder); + dracoEncoder.destroy(builder); + return outputData; + } +} +function createVertexColorSRGBArray(attribute) { + const _color3 = new Color; + const count = attribute.count; + const itemSize = attribute.itemSize; + const array = new Float32Array(count * itemSize); + for (let i = 0, il = count;i < il; i++) { + _color3.fromBufferAttribute(attribute, i); + ColorManagement.fromWorkingColorSpace(_color3, SRGBColorSpace); + array[i * itemSize] = _color3.r; + array[i * itemSize + 1] = _color3.g; + array[i * itemSize + 2] = _color3.b; + if (itemSize === 4) { + array[i * itemSize + 3] = attribute.getW(i); + } + } + return array; +} +DRACOExporter.MESH_EDGEBREAKER_ENCODING = 1; +DRACOExporter.MESH_SEQUENTIAL_ENCODING = 0; +DRACOExporter.POINT_CLOUD = 0; +DRACOExporter.TRIANGULAR_MESH = 1; +DRACOExporter.INVALID = -1; +DRACOExporter.POSITION = 0; +DRACOExporter.NORMAL = 1; +DRACOExporter.COLOR = 2; +DRACOExporter.TEX_COORD = 3; +DRACOExporter.GENERIC = 4; +// node_modules/three/examples/jsm/libs/fflate.module.js +/*! +fflate - fast JavaScript compression/decompression + +Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE +version 0.8.2 +*/ +var u8 = Uint8Array; +var u16 = Uint16Array; +var i32 = Int32Array; +var fleb = new u8([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, 0, 0, 0]); +var fdeb = new u8([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, 0, 0]); +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +var freb = function(eb, start) { + var b = new u16(31); + for (var i = 0;i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + var r = new i32(b[30]); + for (var i = 1;i < 30; ++i) { + for (var j = b[i];j < b[i + 1]; ++j) { + r[j] = j - b[i] << 5 | i; + } + } + return { b, r }; +}; +var _a = freb(fleb, 2); +var fl2 = _a.b; +var revfl = _a.r; +fl2[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0); +var fd = _b.b; +var revfd = _b.r; +var rev = new u16(32768); +for (i = 0;i < 32768; ++i) { + x = (i & 43690) >> 1 | (i & 21845) << 1; + x = (x & 52428) >> 2 | (x & 13107) << 2; + x = (x & 61680) >> 4 | (x & 3855) << 4; + rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1; +} +var x; +var i; +var flt = new u8(288); +for (i = 0;i < 144; ++i) + flt[i] = 8; +var i; +for (i = 144;i < 256; ++i) + flt[i] = 9; +var i; +for (i = 256;i < 280; ++i) + flt[i] = 7; +var i; +for (i = 280;i < 288; ++i) + flt[i] = 8; +var i; +var fdt = new u8(32); +for (i = 0;i < 32; ++i) + fdt[i] = 5; +var i; +var et2 = /* @__PURE__ */ new u8(0); +var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder; +var tds = 0; +try { + td.decode(et2, { stream: true }); + tds = 1; +} catch (e) { +} + +// node_modules/three/examples/jsm/exporters/EXRExporter.js +var textEncoder = new TextEncoder; +// node_modules/three/examples/jsm/exporters/GLTFExporter.js +var KHR_mesh_quantization_ExtraAttrTypes = { + POSITION: [ + "byte", + "byte normalized", + "unsigned byte", + "unsigned byte normalized", + "short", + "short normalized", + "unsigned short", + "unsigned short normalized" + ], + NORMAL: [ + "byte normalized", + "short normalized" + ], + TANGENT: [ + "byte normalized", + "short normalized" + ], + TEXCOORD: [ + "byte", + "byte normalized", + "unsigned byte", + "short", + "short normalized", + "unsigned short" + ] +}; + +class GLTFExporter { + constructor() { + this.textureUtils = null; + this.pluginCallbacks = []; + this.register(function(writer) { + return new GLTFLightExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsUnlitExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsTransmissionExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsVolumeExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsIorExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsSpecularExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsClearcoatExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsDispersionExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsIridescenceExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsSheenExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsAnisotropyExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsEmissiveStrengthExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsBumpExtension(writer); + }); + this.register(function(writer) { + return new GLTFMeshGpuInstancing(writer); + }); + } + register(callback) { + if (this.pluginCallbacks.indexOf(callback) === -1) { + this.pluginCallbacks.push(callback); + } + return this; + } + unregister(callback) { + if (this.pluginCallbacks.indexOf(callback) !== -1) { + this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); + } + return this; + } + setTextureUtils(utils) { + this.textureUtils = utils; + return this; + } + parse(input, onDone, onError, options) { + const writer = new GLTFWriter; + const plugins = []; + for (let i = 0, il = this.pluginCallbacks.length;i < il; i++) { + plugins.push(this.pluginCallbacks[i](writer)); + } + writer.setPlugins(plugins); + writer.setTextureUtils(this.textureUtils); + writer.writeAsync(input, onDone, options).catch(onError); + } + parseAsync(input, options) { + const scope = this; + return new Promise(function(resolve, reject2) { + scope.parse(input, resolve, reject2, options); + }); + } +} +var WEBGL_CONSTANTS = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6, + BYTE: 5120, + UNSIGNED_BYTE: 5121, + SHORT: 5122, + UNSIGNED_SHORT: 5123, + INT: 5124, + UNSIGNED_INT: 5125, + FLOAT: 5126, + ARRAY_BUFFER: 34962, + ELEMENT_ARRAY_BUFFER: 34963, + NEAREST: 9728, + LINEAR: 9729, + NEAREST_MIPMAP_NEAREST: 9984, + LINEAR_MIPMAP_NEAREST: 9985, + NEAREST_MIPMAP_LINEAR: 9986, + LINEAR_MIPMAP_LINEAR: 9987, + CLAMP_TO_EDGE: 33071, + MIRRORED_REPEAT: 33648, + REPEAT: 10497 +}; +var KHR_MESH_QUANTIZATION = "KHR_mesh_quantization"; +var THREE_TO_WEBGL = {}; +THREE_TO_WEBGL[NearestFilter] = WEBGL_CONSTANTS.NEAREST; +THREE_TO_WEBGL[NearestMipmapNearestFilter] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST; +THREE_TO_WEBGL[NearestMipmapLinearFilter] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR; +THREE_TO_WEBGL[LinearFilter] = WEBGL_CONSTANTS.LINEAR; +THREE_TO_WEBGL[LinearMipmapNearestFilter] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST; +THREE_TO_WEBGL[LinearMipmapLinearFilter] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR; +THREE_TO_WEBGL[ClampToEdgeWrapping] = WEBGL_CONSTANTS.CLAMP_TO_EDGE; +THREE_TO_WEBGL[RepeatWrapping] = WEBGL_CONSTANTS.REPEAT; +THREE_TO_WEBGL[MirroredRepeatWrapping] = WEBGL_CONSTANTS.MIRRORED_REPEAT; +var PATH_PROPERTIES = { + scale: "scale", + position: "translation", + quaternion: "rotation", + morphTargetInfluences: "weights" +}; +var DEFAULT_SPECULAR_COLOR = new Color; +var GLB_HEADER_BYTES = 12; +var GLB_HEADER_MAGIC = 1179937895; +var GLB_VERSION = 2; +var GLB_CHUNK_PREFIX_BYTES = 8; +var GLB_CHUNK_TYPE_JSON = 1313821514; +var GLB_CHUNK_TYPE_BIN = 5130562; +function equalArray(array1, array2) { + return array1.length === array2.length && array1.every(function(element, index2) { + return element === array2[index2]; + }); +} +function stringToArrayBuffer(text2) { + return new TextEncoder().encode(text2).buffer; +} +function isIdentityMatrix(matrix) { + return equalArray(matrix.elements, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); +} +function getMinMax(attribute, start, count) { + const output = { + min: new Array(attribute.itemSize).fill(Number.POSITIVE_INFINITY), + max: new Array(attribute.itemSize).fill(Number.NEGATIVE_INFINITY) + }; + for (let i = start;i < start + count; i++) { + for (let a = 0;a < attribute.itemSize; a++) { + let value2; + if (attribute.itemSize > 4) { + value2 = attribute.array[i * attribute.itemSize + a]; + } else { + if (a === 0) + value2 = attribute.getX(i); + else if (a === 1) + value2 = attribute.getY(i); + else if (a === 2) + value2 = attribute.getZ(i); + else if (a === 3) + value2 = attribute.getW(i); + if (attribute.normalized === true) { + value2 = MathUtils.normalize(value2, attribute.array); + } + } + output.min[a] = Math.min(output.min[a], value2); + output.max[a] = Math.max(output.max[a], value2); + } + } + return output; +} +function getPaddedBufferSize(bufferSize) { + return Math.ceil(bufferSize / 4) * 4; +} +function getPaddedArrayBuffer(arrayBuffer, paddingByte = 0) { + const paddedLength = getPaddedBufferSize(arrayBuffer.byteLength); + if (paddedLength !== arrayBuffer.byteLength) { + const array = new Uint8Array(paddedLength); + array.set(new Uint8Array(arrayBuffer)); + if (paddingByte !== 0) { + for (let i = arrayBuffer.byteLength;i < paddedLength; i++) { + array[i] = paddingByte; + } + } + return array.buffer; + } + return arrayBuffer; +} +function getCanvas() { + if (typeof document === "undefined" && typeof OffscreenCanvas !== "undefined") { + return new OffscreenCanvas(1, 1); + } + return document.createElement("canvas"); +} +function getToBlobPromise(canvas, mimeType) { + if (canvas.toBlob !== undefined) { + return new Promise((resolve) => canvas.toBlob(resolve, mimeType)); + } + let quality; + if (mimeType === "image/jpeg") { + quality = 0.92; + } else if (mimeType === "image/webp") { + quality = 0.8; + } + return canvas.convertToBlob({ + type: mimeType, + quality + }); +} + +class GLTFWriter { + constructor() { + this.plugins = []; + this.options = {}; + this.pending = []; + this.buffers = []; + this.byteOffset = 0; + this.buffers = []; + this.nodeMap = new Map; + this.skins = []; + this.extensionsUsed = {}; + this.extensionsRequired = {}; + this.uids = new Map; + this.uid = 0; + this.json = { + asset: { + version: "2.0", + generator: "THREE.GLTFExporter r" + REVISION + } + }; + this.cache = { + meshes: new Map, + attributes: new Map, + attributesNormalized: new Map, + materials: new Map, + textures: new Map, + images: new Map + }; + this.textureUtils = null; + } + setPlugins(plugins) { + this.plugins = plugins; + } + setTextureUtils(utils) { + this.textureUtils = utils; + } + async writeAsync(input, onDone, options = {}) { + this.options = Object.assign({ + binary: false, + trs: false, + onlyVisible: true, + maxTextureSize: Infinity, + animations: [], + includeCustomExtensions: false + }, options); + if (this.options.animations.length > 0) { + this.options.trs = true; + } + await this.processInputAsync(input); + await Promise.all(this.pending); + const writer = this; + const buffers = writer.buffers; + const json = writer.json; + options = writer.options; + const extensionsUsed = writer.extensionsUsed; + const extensionsRequired = writer.extensionsRequired; + const blob = new Blob(buffers, { type: "application/octet-stream" }); + const extensionsUsedList = Object.keys(extensionsUsed); + const extensionsRequiredList = Object.keys(extensionsRequired); + if (extensionsUsedList.length > 0) + json.extensionsUsed = extensionsUsedList; + if (extensionsRequiredList.length > 0) + json.extensionsRequired = extensionsRequiredList; + if (json.buffers && json.buffers.length > 0) + json.buffers[0].byteLength = blob.size; + if (options.binary === true) { + const reader = new FileReader; + reader.readAsArrayBuffer(blob); + reader.onloadend = function() { + const binaryChunk = getPaddedArrayBuffer(reader.result); + const binaryChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); + binaryChunkPrefix.setUint32(0, binaryChunk.byteLength, true); + binaryChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_BIN, true); + const jsonChunk = getPaddedArrayBuffer(stringToArrayBuffer(JSON.stringify(json)), 32); + const jsonChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); + jsonChunkPrefix.setUint32(0, jsonChunk.byteLength, true); + jsonChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_JSON, true); + const header = new ArrayBuffer(GLB_HEADER_BYTES); + const headerView = new DataView(header); + headerView.setUint32(0, GLB_HEADER_MAGIC, true); + headerView.setUint32(4, GLB_VERSION, true); + const totalByteLength = GLB_HEADER_BYTES + jsonChunkPrefix.byteLength + jsonChunk.byteLength + binaryChunkPrefix.byteLength + binaryChunk.byteLength; + headerView.setUint32(8, totalByteLength, true); + const glbBlob = new Blob([ + header, + jsonChunkPrefix, + jsonChunk, + binaryChunkPrefix, + binaryChunk + ], { type: "application/octet-stream" }); + const glbReader = new FileReader; + glbReader.readAsArrayBuffer(glbBlob); + glbReader.onloadend = function() { + onDone(glbReader.result); + }; + }; + } else { + if (json.buffers && json.buffers.length > 0) { + const reader = new FileReader; + reader.readAsDataURL(blob); + reader.onloadend = function() { + const base64data = reader.result; + json.buffers[0].uri = base64data; + onDone(json); + }; + } else { + onDone(json); + } + } + } + serializeUserData(object, objectDef) { + if (Object.keys(object.userData).length === 0) + return; + const options = this.options; + const extensionsUsed = this.extensionsUsed; + try { + const json = JSON.parse(JSON.stringify(object.userData)); + if (options.includeCustomExtensions && json.gltfExtensions) { + if (objectDef.extensions === undefined) + objectDef.extensions = {}; + for (const extensionName in json.gltfExtensions) { + objectDef.extensions[extensionName] = json.gltfExtensions[extensionName]; + extensionsUsed[extensionName] = true; + } + delete json.gltfExtensions; + } + if (Object.keys(json).length > 0) + objectDef.extras = json; + } catch (error) { + console.warn("THREE.GLTFExporter: userData of '" + object.name + "' " + "won't be serialized because of JSON.stringify error - " + error.message); + } + } + getUID(attribute, isRelativeCopy = false) { + if (this.uids.has(attribute) === false) { + const uids2 = new Map; + uids2.set(true, this.uid++); + uids2.set(false, this.uid++); + this.uids.set(attribute, uids2); + } + const uids = this.uids.get(attribute); + return uids.get(isRelativeCopy); + } + isNormalizedNormalAttribute(normal) { + const cache = this.cache; + if (cache.attributesNormalized.has(normal)) + return false; + const v = new Vector3; + for (let i = 0, il = normal.count;i < il; i++) { + if (Math.abs(v.fromBufferAttribute(normal, i).length() - 1) > 0.0005) + return false; + } + return true; + } + createNormalizedNormalAttribute(normal) { + const cache = this.cache; + if (cache.attributesNormalized.has(normal)) + return cache.attributesNormalized.get(normal); + const attribute = normal.clone(); + const v = new Vector3; + for (let i = 0, il = attribute.count;i < il; i++) { + v.fromBufferAttribute(attribute, i); + if (v.x === 0 && v.y === 0 && v.z === 0) { + v.setX(1); + } else { + v.normalize(); + } + attribute.setXYZ(i, v.x, v.y, v.z); + } + cache.attributesNormalized.set(normal, attribute); + return attribute; + } + applyTextureTransform(mapDef, texture) { + let didTransform = false; + const transformDef = {}; + if (texture.offset.x !== 0 || texture.offset.y !== 0) { + transformDef.offset = texture.offset.toArray(); + didTransform = true; + } + if (texture.rotation !== 0) { + transformDef.rotation = texture.rotation; + didTransform = true; + } + if (texture.repeat.x !== 1 || texture.repeat.y !== 1) { + transformDef.scale = texture.repeat.toArray(); + didTransform = true; + } + if (didTransform) { + mapDef.extensions = mapDef.extensions || {}; + mapDef.extensions["KHR_texture_transform"] = transformDef; + this.extensionsUsed["KHR_texture_transform"] = true; + } + } + async buildMetalRoughTextureAsync(metalnessMap, roughnessMap) { + if (metalnessMap === roughnessMap) + return metalnessMap; + function getEncodingConversion(map2) { + if (map2.colorSpace === SRGBColorSpace) { + return function SRGBToLinear(c) { + return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); + }; + } + return function LinearToLinear(c) { + return c; + }; + } + if (metalnessMap instanceof CompressedTexture) { + metalnessMap = await this.decompressTextureAsync(metalnessMap); + } + if (roughnessMap instanceof CompressedTexture) { + roughnessMap = await this.decompressTextureAsync(roughnessMap); + } + const metalness = metalnessMap ? metalnessMap.image : null; + const roughness = roughnessMap ? roughnessMap.image : null; + const width2 = Math.max(metalness ? metalness.width : 0, roughness ? roughness.width : 0); + const height2 = Math.max(metalness ? metalness.height : 0, roughness ? roughness.height : 0); + const canvas = getCanvas(); + canvas.width = width2; + canvas.height = height2; + const context = canvas.getContext("2d", { + willReadFrequently: true + }); + context.fillStyle = "#00ffff"; + context.fillRect(0, 0, width2, height2); + const composite = context.getImageData(0, 0, width2, height2); + if (metalness) { + context.drawImage(metalness, 0, 0, width2, height2); + const convert = getEncodingConversion(metalnessMap); + const data2 = context.getImageData(0, 0, width2, height2).data; + for (let i = 2;i < data2.length; i += 4) { + composite.data[i] = convert(data2[i] / 256) * 256; + } + } + if (roughness) { + context.drawImage(roughness, 0, 0, width2, height2); + const convert = getEncodingConversion(roughnessMap); + const data2 = context.getImageData(0, 0, width2, height2).data; + for (let i = 1;i < data2.length; i += 4) { + composite.data[i] = convert(data2[i] / 256) * 256; + } + } + context.putImageData(composite, 0, 0); + const reference = metalnessMap || roughnessMap; + const texture = reference.clone(); + texture.source = new Source(canvas); + texture.colorSpace = NoColorSpace; + texture.channel = (metalnessMap || roughnessMap).channel; + if (metalnessMap && roughnessMap && metalnessMap.channel !== roughnessMap.channel) { + console.warn("THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match."); + } + console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."); + return texture; + } + async decompressTextureAsync(texture, maxTextureSize = Infinity) { + if (this.textureUtils === null) { + throw new Error("THREE.GLTFExporter: setTextureUtils() must be called to process compressed textures."); + } + return await this.textureUtils.decompress(texture, maxTextureSize); + } + processBuffer(buffer) { + const json = this.json; + const buffers = this.buffers; + if (!json.buffers) + json.buffers = [{ byteLength: 0 }]; + buffers.push(buffer); + return 0; + } + processBufferView(attribute, componentType, start, count, target) { + const json = this.json; + if (!json.bufferViews) + json.bufferViews = []; + let componentSize; + switch (componentType) { + case WEBGL_CONSTANTS.BYTE: + case WEBGL_CONSTANTS.UNSIGNED_BYTE: + componentSize = 1; + break; + case WEBGL_CONSTANTS.SHORT: + case WEBGL_CONSTANTS.UNSIGNED_SHORT: + componentSize = 2; + break; + default: + componentSize = 4; + } + let byteStride = attribute.itemSize * componentSize; + if (target === WEBGL_CONSTANTS.ARRAY_BUFFER) { + byteStride = Math.ceil(byteStride / 4) * 4; + } + const byteLength = getPaddedBufferSize(count * byteStride); + const dataView = new DataView(new ArrayBuffer(byteLength)); + let offset = 0; + for (let i = start;i < start + count; i++) { + for (let a = 0;a < attribute.itemSize; a++) { + let value2; + if (attribute.itemSize > 4) { + value2 = attribute.array[i * attribute.itemSize + a]; + } else { + if (a === 0) + value2 = attribute.getX(i); + else if (a === 1) + value2 = attribute.getY(i); + else if (a === 2) + value2 = attribute.getZ(i); + else if (a === 3) + value2 = attribute.getW(i); + if (attribute.normalized === true) { + value2 = MathUtils.normalize(value2, attribute.array); + } + } + if (componentType === WEBGL_CONSTANTS.FLOAT) { + dataView.setFloat32(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.INT) { + dataView.setInt32(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_INT) { + dataView.setUint32(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.SHORT) { + dataView.setInt16(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT) { + dataView.setUint16(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.BYTE) { + dataView.setInt8(offset, value2); + } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE) { + dataView.setUint8(offset, value2); + } + offset += componentSize; + } + if (offset % byteStride !== 0) { + offset += byteStride - offset % byteStride; + } + } + const bufferViewDef = { + buffer: this.processBuffer(dataView.buffer), + byteOffset: this.byteOffset, + byteLength + }; + if (target !== undefined) + bufferViewDef.target = target; + if (target === WEBGL_CONSTANTS.ARRAY_BUFFER) { + bufferViewDef.byteStride = byteStride; + } + this.byteOffset += byteLength; + json.bufferViews.push(bufferViewDef); + const output = { + id: json.bufferViews.length - 1, + byteLength: 0 + }; + return output; + } + processBufferViewImage(blob) { + const writer = this; + const json = writer.json; + if (!json.bufferViews) + json.bufferViews = []; + return new Promise(function(resolve) { + const reader = new FileReader; + reader.readAsArrayBuffer(blob); + reader.onloadend = function() { + const buffer = getPaddedArrayBuffer(reader.result); + const bufferViewDef = { + buffer: writer.processBuffer(buffer), + byteOffset: writer.byteOffset, + byteLength: buffer.byteLength + }; + writer.byteOffset += buffer.byteLength; + resolve(json.bufferViews.push(bufferViewDef) - 1); + }; + }); + } + processAccessor(attribute, geometry, start, count) { + const json = this.json; + const types = { + 1: "SCALAR", + 2: "VEC2", + 3: "VEC3", + 4: "VEC4", + 9: "MAT3", + 16: "MAT4" + }; + let componentType; + if (attribute.array.constructor === Float32Array) { + componentType = WEBGL_CONSTANTS.FLOAT; + } else if (attribute.array.constructor === Int32Array) { + componentType = WEBGL_CONSTANTS.INT; + } else if (attribute.array.constructor === Uint32Array) { + componentType = WEBGL_CONSTANTS.UNSIGNED_INT; + } else if (attribute.array.constructor === Int16Array) { + componentType = WEBGL_CONSTANTS.SHORT; + } else if (attribute.array.constructor === Uint16Array) { + componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT; + } else if (attribute.array.constructor === Int8Array) { + componentType = WEBGL_CONSTANTS.BYTE; + } else if (attribute.array.constructor === Uint8Array) { + componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE; + } else { + throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: " + attribute.array.constructor.name); + } + if (start === undefined) + start = 0; + if (count === undefined || count === Infinity) + count = attribute.count; + if (count === 0) + return null; + const minMax = getMinMax(attribute, start, count); + let bufferViewTarget; + if (geometry !== undefined) { + bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER; + } + const bufferView = this.processBufferView(attribute, componentType, start, count, bufferViewTarget); + const accessorDef = { + bufferView: bufferView.id, + byteOffset: bufferView.byteOffset, + componentType, + count, + max: minMax.max, + min: minMax.min, + type: types[attribute.itemSize] + }; + if (attribute.normalized === true) + accessorDef.normalized = true; + if (!json.accessors) + json.accessors = []; + return json.accessors.push(accessorDef) - 1; + } + processImage(image, format, flipY, mimeType = "image/png") { + if (image !== null) { + const writer = this; + const cache = writer.cache; + const json = writer.json; + const options = writer.options; + const pending = writer.pending; + if (!cache.images.has(image)) + cache.images.set(image, {}); + const cachedImages = cache.images.get(image); + const key2 = mimeType + ":flipY/" + flipY.toString(); + if (cachedImages[key2] !== undefined) + return cachedImages[key2]; + if (!json.images) + json.images = []; + const imageDef = { mimeType }; + const canvas = getCanvas(); + canvas.width = Math.min(image.width, options.maxTextureSize); + canvas.height = Math.min(image.height, options.maxTextureSize); + const ctx = canvas.getContext("2d", { + willReadFrequently: true + }); + if (flipY === true) { + ctx.translate(0, canvas.height); + ctx.scale(1, -1); + } + if (image.data !== undefined) { + if (format !== RGBAFormat) { + console.error("GLTFExporter: Only RGBAFormat is supported.", format); + } + if (image.width > options.maxTextureSize || image.height > options.maxTextureSize) { + console.warn("GLTFExporter: Image size is bigger than maxTextureSize", image); + } + const data2 = new Uint8ClampedArray(image.height * image.width * 4); + for (let i = 0;i < data2.length; i += 4) { + data2[i + 0] = image.data[i + 0]; + data2[i + 1] = image.data[i + 1]; + data2[i + 2] = image.data[i + 2]; + data2[i + 3] = image.data[i + 3]; + } + ctx.putImageData(new ImageData(data2, image.width, image.height), 0, 0); + } else { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof OffscreenCanvas !== "undefined" && image instanceof OffscreenCanvas) { + ctx.drawImage(image, 0, 0, canvas.width, canvas.height); + } else { + throw new Error("THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas."); + } + } + if (options.binary === true) { + pending.push(getToBlobPromise(canvas, mimeType).then((blob) => writer.processBufferViewImage(blob)).then((bufferViewIndex) => { + imageDef.bufferView = bufferViewIndex; + })); + } else { + if (canvas.toDataURL !== undefined) { + imageDef.uri = canvas.toDataURL(mimeType); + } else { + pending.push(getToBlobPromise(canvas, mimeType).then((blob) => new FileReader().readAsDataURL(blob)).then((dataURL) => { + imageDef.uri = dataURL; + })); + } + } + const index2 = json.images.push(imageDef) - 1; + cachedImages[key2] = index2; + return index2; + } else { + throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture."); + } + } + processSampler(map2) { + const json = this.json; + if (!json.samplers) + json.samplers = []; + const samplerDef = { + magFilter: THREE_TO_WEBGL[map2.magFilter], + minFilter: THREE_TO_WEBGL[map2.minFilter], + wrapS: THREE_TO_WEBGL[map2.wrapS], + wrapT: THREE_TO_WEBGL[map2.wrapT] + }; + return json.samplers.push(samplerDef) - 1; + } + async processTextureAsync(map2) { + const writer = this; + const options = writer.options; + const cache = this.cache; + const json = this.json; + if (cache.textures.has(map2)) + return cache.textures.get(map2); + if (!json.textures) + json.textures = []; + if (map2 instanceof CompressedTexture) { + map2 = await this.decompressTextureAsync(map2, options.maxTextureSize); + } + let mimeType = map2.userData.mimeType; + if (mimeType === "image/webp") + mimeType = "image/png"; + const textureDef = { + sampler: this.processSampler(map2), + source: this.processImage(map2.image, map2.format, map2.flipY, mimeType) + }; + if (map2.name) + textureDef.name = map2.name; + await this._invokeAllAsync(async function(ext) { + ext.writeTexture && await ext.writeTexture(map2, textureDef); + }); + const index2 = json.textures.push(textureDef) - 1; + cache.textures.set(map2, index2); + return index2; + } + async processMaterialAsync(material) { + const cache = this.cache; + const json = this.json; + if (cache.materials.has(material)) + return cache.materials.get(material); + if (material.isShaderMaterial) { + console.warn("GLTFExporter: THREE.ShaderMaterial not supported."); + return null; + } + if (!json.materials) + json.materials = []; + const materialDef = { pbrMetallicRoughness: {} }; + if (material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true) { + console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results."); + } + const color = material.color.toArray().concat([material.opacity]); + if (!equalArray(color, [1, 1, 1, 1])) { + materialDef.pbrMetallicRoughness.baseColorFactor = color; + } + if (material.isMeshStandardMaterial) { + materialDef.pbrMetallicRoughness.metallicFactor = material.metalness; + materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness; + } else { + materialDef.pbrMetallicRoughness.metallicFactor = 0; + materialDef.pbrMetallicRoughness.roughnessFactor = 1; + } + if (material.metalnessMap || material.roughnessMap) { + const metalRoughTexture = await this.buildMetalRoughTextureAsync(material.metalnessMap, material.roughnessMap); + const metalRoughMapDef = { + index: await this.processTextureAsync(metalRoughTexture), + texCoord: metalRoughTexture.channel + }; + this.applyTextureTransform(metalRoughMapDef, metalRoughTexture); + materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef; + } + if (material.map) { + const baseColorMapDef = { + index: await this.processTextureAsync(material.map), + texCoord: material.map.channel + }; + this.applyTextureTransform(baseColorMapDef, material.map); + materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef; + } + if (material.emissive) { + const emissive = material.emissive; + const maxEmissiveComponent = Math.max(emissive.r, emissive.g, emissive.b); + if (maxEmissiveComponent > 0) { + materialDef.emissiveFactor = material.emissive.toArray(); + } + if (material.emissiveMap) { + const emissiveMapDef = { + index: await this.processTextureAsync(material.emissiveMap), + texCoord: material.emissiveMap.channel + }; + this.applyTextureTransform(emissiveMapDef, material.emissiveMap); + materialDef.emissiveTexture = emissiveMapDef; + } + } + if (material.normalMap) { + const normalMapDef = { + index: await this.processTextureAsync(material.normalMap), + texCoord: material.normalMap.channel + }; + if (material.normalScale && material.normalScale.x !== 1) { + normalMapDef.scale = material.normalScale.x; + } + this.applyTextureTransform(normalMapDef, material.normalMap); + materialDef.normalTexture = normalMapDef; + } + if (material.aoMap) { + const occlusionMapDef = { + index: await this.processTextureAsync(material.aoMap), + texCoord: material.aoMap.channel + }; + if (material.aoMapIntensity !== 1) { + occlusionMapDef.strength = material.aoMapIntensity; + } + this.applyTextureTransform(occlusionMapDef, material.aoMap); + materialDef.occlusionTexture = occlusionMapDef; + } + if (material.transparent) { + materialDef.alphaMode = "BLEND"; + } else { + if (material.alphaTest > 0) { + materialDef.alphaMode = "MASK"; + materialDef.alphaCutoff = material.alphaTest; + } + } + if (material.side === DoubleSide) + materialDef.doubleSided = true; + if (material.name !== "") + materialDef.name = material.name; + this.serializeUserData(material, materialDef); + await this._invokeAllAsync(async function(ext) { + ext.writeMaterialAsync && await ext.writeMaterialAsync(material, materialDef); + }); + const index2 = json.materials.push(materialDef) - 1; + cache.materials.set(material, index2); + return index2; + } + async processMeshAsync(mesh) { + const cache = this.cache; + const json = this.json; + const meshCacheKeyParts = [mesh.geometry.uuid]; + if (Array.isArray(mesh.material)) { + for (let i = 0, l = mesh.material.length;i < l; i++) { + meshCacheKeyParts.push(mesh.material[i].uuid); + } + } else { + meshCacheKeyParts.push(mesh.material.uuid); + } + const meshCacheKey = meshCacheKeyParts.join(":"); + if (cache.meshes.has(meshCacheKey)) + return cache.meshes.get(meshCacheKey); + const geometry = mesh.geometry; + let mode; + if (mesh.isLineSegments) { + mode = WEBGL_CONSTANTS.LINES; + } else if (mesh.isLineLoop) { + mode = WEBGL_CONSTANTS.LINE_LOOP; + } else if (mesh.isLine) { + mode = WEBGL_CONSTANTS.LINE_STRIP; + } else if (mesh.isPoints) { + mode = WEBGL_CONSTANTS.POINTS; + } else { + mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES; + } + const meshDef = {}; + const attributes = {}; + const primitives = []; + const targets = []; + const nameConversion = { + uv: "TEXCOORD_0", + uv1: "TEXCOORD_1", + uv2: "TEXCOORD_2", + uv3: "TEXCOORD_3", + color: "COLOR_0", + skinWeight: "WEIGHTS_0", + skinIndex: "JOINTS_0" + }; + const originalNormal = geometry.getAttribute("normal"); + if (originalNormal !== undefined && !this.isNormalizedNormalAttribute(originalNormal)) { + console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."); + geometry.setAttribute("normal", this.createNormalizedNormalAttribute(originalNormal)); + } + let modifiedAttribute = null; + for (let attributeName in geometry.attributes) { + if (attributeName.slice(0, 5) === "morph") + continue; + const attribute = geometry.attributes[attributeName]; + attributeName = nameConversion[attributeName] || attributeName.toUpperCase(); + const validVertexAttributes = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/; + if (!validVertexAttributes.test(attributeName)) + attributeName = "_" + attributeName; + if (cache.attributes.has(this.getUID(attribute))) { + attributes[attributeName] = cache.attributes.get(this.getUID(attribute)); + continue; + } + modifiedAttribute = null; + const array = attribute.array; + if (attributeName === "JOINTS_0" && !(array instanceof Uint16Array) && !(array instanceof Uint8Array)) { + console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'); + modifiedAttribute = new BufferAttribute(new Uint16Array(array), attribute.itemSize, attribute.normalized); + } else if ((array instanceof Uint32Array || array instanceof Int32Array) && !attributeName.startsWith("_")) { + console.warn(`GLTFExporter: Attribute "${attributeName}" converted to type FLOAT.`); + modifiedAttribute = GLTFExporter.Utils.toFloat32BufferAttribute(attribute); + } + const accessor = this.processAccessor(modifiedAttribute || attribute, geometry); + if (accessor !== null) { + if (!attributeName.startsWith("_")) { + this.detectMeshQuantization(attributeName, attribute); + } + attributes[attributeName] = accessor; + cache.attributes.set(this.getUID(attribute), accessor); + } + } + if (originalNormal !== undefined) + geometry.setAttribute("normal", originalNormal); + if (Object.keys(attributes).length === 0) + return null; + if (mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0) { + const weights = []; + const targetNames = []; + const reverseDictionary = {}; + if (mesh.morphTargetDictionary !== undefined) { + for (const key2 in mesh.morphTargetDictionary) { + reverseDictionary[mesh.morphTargetDictionary[key2]] = key2; + } + } + for (let i = 0;i < mesh.morphTargetInfluences.length; ++i) { + const target = {}; + let warned = false; + for (const attributeName in geometry.morphAttributes) { + if (attributeName !== "position" && attributeName !== "normal") { + if (!warned) { + console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."); + warned = true; + } + continue; + } + const attribute = geometry.morphAttributes[attributeName][i]; + const gltfAttributeName = attributeName.toUpperCase(); + const baseAttribute = geometry.attributes[attributeName]; + if (cache.attributes.has(this.getUID(attribute, true))) { + target[gltfAttributeName] = cache.attributes.get(this.getUID(attribute, true)); + continue; + } + const relativeAttribute = attribute.clone(); + if (!geometry.morphTargetsRelative) { + for (let j = 0, jl = attribute.count;j < jl; j++) { + for (let a = 0;a < attribute.itemSize; a++) { + if (a === 0) + relativeAttribute.setX(j, attribute.getX(j) - baseAttribute.getX(j)); + if (a === 1) + relativeAttribute.setY(j, attribute.getY(j) - baseAttribute.getY(j)); + if (a === 2) + relativeAttribute.setZ(j, attribute.getZ(j) - baseAttribute.getZ(j)); + if (a === 3) + relativeAttribute.setW(j, attribute.getW(j) - baseAttribute.getW(j)); + } + } + } + target[gltfAttributeName] = this.processAccessor(relativeAttribute, geometry); + cache.attributes.set(this.getUID(baseAttribute, true), target[gltfAttributeName]); + } + targets.push(target); + weights.push(mesh.morphTargetInfluences[i]); + if (mesh.morphTargetDictionary !== undefined) + targetNames.push(reverseDictionary[i]); + } + meshDef.weights = weights; + if (targetNames.length > 0) { + meshDef.extras = {}; + meshDef.extras.targetNames = targetNames; + } + } + const isMultiMaterial = Array.isArray(mesh.material); + if (isMultiMaterial && geometry.groups.length === 0) + return null; + let didForceIndices = false; + if (isMultiMaterial && geometry.index === null) { + const indices = []; + for (let i = 0, il = geometry.attributes.position.count;i < il; i++) { + indices[i] = i; + } + geometry.setIndex(indices); + didForceIndices = true; + } + const materials = isMultiMaterial ? mesh.material : [mesh.material]; + const groups = isMultiMaterial ? geometry.groups : [{ materialIndex: 0, start: undefined, count: undefined }]; + for (let i = 0, il = groups.length;i < il; i++) { + const primitive = { + mode, + attributes + }; + this.serializeUserData(geometry, primitive); + if (targets.length > 0) + primitive.targets = targets; + if (geometry.index !== null) { + let cacheKey = this.getUID(geometry.index); + if (groups[i].start !== undefined || groups[i].count !== undefined) { + cacheKey += ":" + groups[i].start + ":" + groups[i].count; + } + if (cache.attributes.has(cacheKey)) { + primitive.indices = cache.attributes.get(cacheKey); + } else { + primitive.indices = this.processAccessor(geometry.index, geometry, groups[i].start, groups[i].count); + cache.attributes.set(cacheKey, primitive.indices); + } + if (primitive.indices === null) + delete primitive.indices; + } + const material = await this.processMaterialAsync(materials[groups[i].materialIndex]); + if (material !== null) + primitive.material = material; + primitives.push(primitive); + } + if (didForceIndices === true) { + geometry.setIndex(null); + } + meshDef.primitives = primitives; + if (!json.meshes) + json.meshes = []; + await this._invokeAllAsync(function(ext) { + ext.writeMesh && ext.writeMesh(mesh, meshDef); + }); + const index2 = json.meshes.push(meshDef) - 1; + cache.meshes.set(meshCacheKey, index2); + return index2; + } + detectMeshQuantization(attributeName, attribute) { + if (this.extensionsUsed[KHR_MESH_QUANTIZATION]) + return; + let attrType = undefined; + switch (attribute.array.constructor) { + case Int8Array: + attrType = "byte"; + break; + case Uint8Array: + attrType = "unsigned byte"; + break; + case Int16Array: + attrType = "short"; + break; + case Uint16Array: + attrType = "unsigned short"; + break; + default: + return; + } + if (attribute.normalized) + attrType += " normalized"; + const attrNamePrefix = attributeName.split("_", 1)[0]; + if (KHR_mesh_quantization_ExtraAttrTypes[attrNamePrefix] && KHR_mesh_quantization_ExtraAttrTypes[attrNamePrefix].includes(attrType)) { + this.extensionsUsed[KHR_MESH_QUANTIZATION] = true; + this.extensionsRequired[KHR_MESH_QUANTIZATION] = true; + } + } + processCamera(camera) { + const json = this.json; + if (!json.cameras) + json.cameras = []; + const isOrtho = camera.isOrthographicCamera; + const cameraDef = { + type: isOrtho ? "orthographic" : "perspective" + }; + if (isOrtho) { + cameraDef.orthographic = { + xmag: camera.right * 2, + ymag: camera.top * 2, + zfar: camera.far <= 0 ? 0.001 : camera.far, + znear: camera.near < 0 ? 0 : camera.near + }; + } else { + cameraDef.perspective = { + aspectRatio: camera.aspect, + yfov: MathUtils.degToRad(camera.fov), + zfar: camera.far <= 0 ? 0.001 : camera.far, + znear: camera.near < 0 ? 0 : camera.near + }; + } + if (camera.name !== "") + cameraDef.name = camera.type; + return json.cameras.push(cameraDef) - 1; + } + processAnimation(clip, root) { + const json = this.json; + const nodeMap = this.nodeMap; + if (!json.animations) + json.animations = []; + clip = GLTFExporter.Utils.mergeMorphTargetTracks(clip.clone(), root); + const tracks = clip.tracks; + const channels = []; + const samplers = []; + for (let i = 0;i < tracks.length; ++i) { + const track = tracks[i]; + const trackBinding = PropertyBinding.parseTrackName(track.name); + let trackNode = PropertyBinding.findNode(root, trackBinding.nodeName); + const trackProperty = PATH_PROPERTIES[trackBinding.propertyName]; + if (trackBinding.objectName === "bones") { + if (trackNode.isSkinnedMesh === true) { + trackNode = trackNode.skeleton.getBoneByName(trackBinding.objectIndex); + } else { + trackNode = undefined; + } + } + if (!trackNode || !trackProperty) { + console.warn('THREE.GLTFExporter: Could not export animation track "%s".', track.name); + continue; + } + const inputItemSize = 1; + let outputItemSize = track.values.length / track.times.length; + if (trackProperty === PATH_PROPERTIES.morphTargetInfluences) { + outputItemSize /= trackNode.morphTargetInfluences.length; + } + let interpolation; + if (track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true) { + interpolation = "CUBICSPLINE"; + outputItemSize /= 3; + } else if (track.getInterpolation() === InterpolateDiscrete) { + interpolation = "STEP"; + } else { + interpolation = "LINEAR"; + } + samplers.push({ + input: this.processAccessor(new BufferAttribute(track.times, inputItemSize)), + output: this.processAccessor(new BufferAttribute(track.values, outputItemSize)), + interpolation + }); + channels.push({ + sampler: samplers.length - 1, + target: { + node: nodeMap.get(trackNode), + path: trackProperty + } + }); + } + json.animations.push({ + name: clip.name || "clip_" + json.animations.length, + samplers, + channels + }); + return json.animations.length - 1; + } + processSkin(object) { + const json = this.json; + const nodeMap = this.nodeMap; + const node = json.nodes[nodeMap.get(object)]; + const skeleton = object.skeleton; + if (skeleton === undefined) + return null; + const rootJoint = object.skeleton.bones[0]; + if (rootJoint === undefined) + return null; + const joints = []; + const inverseBindMatrices = new Float32Array(skeleton.bones.length * 16); + const temporaryBoneInverse = new Matrix4; + for (let i = 0;i < skeleton.bones.length; ++i) { + joints.push(nodeMap.get(skeleton.bones[i])); + temporaryBoneInverse.copy(skeleton.boneInverses[i]); + temporaryBoneInverse.multiply(object.bindMatrix).toArray(inverseBindMatrices, i * 16); + } + if (json.skins === undefined) + json.skins = []; + json.skins.push({ + inverseBindMatrices: this.processAccessor(new BufferAttribute(inverseBindMatrices, 16)), + joints, + skeleton: nodeMap.get(rootJoint) + }); + const skinIndex = node.skin = json.skins.length - 1; + return skinIndex; + } + async processNodeAsync(object) { + const json = this.json; + const options = this.options; + const nodeMap = this.nodeMap; + if (!json.nodes) + json.nodes = []; + const nodeDef = {}; + if (options.trs) { + const rotation2 = object.quaternion.toArray(); + const position2 = object.position.toArray(); + const scale2 = object.scale.toArray(); + if (!equalArray(rotation2, [0, 0, 0, 1])) { + nodeDef.rotation = rotation2; + } + if (!equalArray(position2, [0, 0, 0])) { + nodeDef.translation = position2; + } + if (!equalArray(scale2, [1, 1, 1])) { + nodeDef.scale = scale2; + } + } else { + if (object.matrixAutoUpdate) { + object.updateMatrix(); + } + if (isIdentityMatrix(object.matrix) === false) { + nodeDef.matrix = object.matrix.elements; + } + } + if (object.name !== "") + nodeDef.name = String(object.name); + this.serializeUserData(object, nodeDef); + if (object.isMesh || object.isLine || object.isPoints) { + const meshIndex = await this.processMeshAsync(object); + if (meshIndex !== null) + nodeDef.mesh = meshIndex; + } else if (object.isCamera) { + nodeDef.camera = this.processCamera(object); + } + if (object.isSkinnedMesh) + this.skins.push(object); + if (object.children.length > 0) { + const children = []; + for (let i = 0, l = object.children.length;i < l; i++) { + const child = object.children[i]; + if (child.visible || options.onlyVisible === false) { + const nodeIndex2 = await this.processNodeAsync(child); + if (nodeIndex2 !== null) + children.push(nodeIndex2); + } + } + if (children.length > 0) + nodeDef.children = children; + } + await this._invokeAllAsync(function(ext) { + ext.writeNode && ext.writeNode(object, nodeDef); + }); + const nodeIndex = json.nodes.push(nodeDef) - 1; + nodeMap.set(object, nodeIndex); + return nodeIndex; + } + async processSceneAsync(scene) { + const json = this.json; + const options = this.options; + if (!json.scenes) { + json.scenes = []; + json.scene = 0; + } + const sceneDef = {}; + if (scene.name !== "") + sceneDef.name = scene.name; + json.scenes.push(sceneDef); + const nodes = []; + for (let i = 0, l = scene.children.length;i < l; i++) { + const child = scene.children[i]; + if (child.visible || options.onlyVisible === false) { + const nodeIndex = await this.processNodeAsync(child); + if (nodeIndex !== null) + nodes.push(nodeIndex); + } + } + if (nodes.length > 0) + sceneDef.nodes = nodes; + this.serializeUserData(scene, sceneDef); + } + async processObjectsAsync(objects) { + const scene = new Scene; + scene.name = "AuxScene"; + for (let i = 0;i < objects.length; i++) { + scene.children.push(objects[i]); + } + await this.processSceneAsync(scene); + } + async processInputAsync(input) { + const options = this.options; + input = input instanceof Array ? input : [input]; + await this._invokeAllAsync(function(ext) { + ext.beforeParse && ext.beforeParse(input); + }); + const objectsWithoutScene = []; + for (let i = 0;i < input.length; i++) { + if (input[i] instanceof Scene) { + await this.processSceneAsync(input[i]); + } else { + objectsWithoutScene.push(input[i]); + } + } + if (objectsWithoutScene.length > 0) { + await this.processObjectsAsync(objectsWithoutScene); + } + for (let i = 0;i < this.skins.length; ++i) { + this.processSkin(this.skins[i]); + } + for (let i = 0;i < options.animations.length; ++i) { + this.processAnimation(options.animations[i], input[0]); + } + await this._invokeAllAsync(function(ext) { + ext.afterParse && ext.afterParse(input); + }); + } + async _invokeAllAsync(func) { + for (let i = 0, il = this.plugins.length;i < il; i++) { + await func(this.plugins[i]); + } + } +} + +class GLTFLightExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_lights_punctual"; + } + writeNode(light, nodeDef) { + if (!light.isLight) + return; + if (!light.isDirectionalLight && !light.isPointLight && !light.isSpotLight) { + console.warn("THREE.GLTFExporter: Only directional, point, and spot lights are supported.", light); + return; + } + const writer = this.writer; + const json = writer.json; + const extensionsUsed = writer.extensionsUsed; + const lightDef = {}; + if (light.name) + lightDef.name = light.name; + lightDef.color = light.color.toArray(); + lightDef.intensity = light.intensity; + if (light.isDirectionalLight) { + lightDef.type = "directional"; + } else if (light.isPointLight) { + lightDef.type = "point"; + if (light.distance > 0) + lightDef.range = light.distance; + } else if (light.isSpotLight) { + lightDef.type = "spot"; + if (light.distance > 0) + lightDef.range = light.distance; + lightDef.spot = {}; + lightDef.spot.innerConeAngle = (1 - light.penumbra) * light.angle; + lightDef.spot.outerConeAngle = light.angle; + } + if (light.decay !== undefined && light.decay !== 2) { + console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, " + "and expects light.decay=2."); + } + if (light.target && (light.target.parent !== light || light.target.position.x !== 0 || light.target.position.y !== 0 || light.target.position.z !== -1)) { + console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, " + "make light.target a child of the light with position 0,0,-1."); + } + if (!extensionsUsed[this.name]) { + json.extensions = json.extensions || {}; + json.extensions[this.name] = { lights: [] }; + extensionsUsed[this.name] = true; + } + const lights = json.extensions[this.name].lights; + lights.push(lightDef); + nodeDef.extensions = nodeDef.extensions || {}; + nodeDef.extensions[this.name] = { light: lights.length - 1 }; + } +} + +class GLTFMaterialsUnlitExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_unlit"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshBasicMaterial) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = {}; + extensionsUsed[this.name] = true; + materialDef.pbrMetallicRoughness.metallicFactor = 0; + materialDef.pbrMetallicRoughness.roughnessFactor = 0.9; + } +} + +class GLTFMaterialsClearcoatExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_clearcoat"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.clearcoat === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.clearcoatFactor = material.clearcoat; + if (material.clearcoatMap) { + const clearcoatMapDef = { + index: await writer.processTextureAsync(material.clearcoatMap), + texCoord: material.clearcoatMap.channel + }; + writer.applyTextureTransform(clearcoatMapDef, material.clearcoatMap); + extensionDef.clearcoatTexture = clearcoatMapDef; + } + extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness; + if (material.clearcoatRoughnessMap) { + const clearcoatRoughnessMapDef = { + index: await writer.processTextureAsync(material.clearcoatRoughnessMap), + texCoord: material.clearcoatRoughnessMap.channel + }; + writer.applyTextureTransform(clearcoatRoughnessMapDef, material.clearcoatRoughnessMap); + extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef; + } + if (material.clearcoatNormalMap) { + const clearcoatNormalMapDef = { + index: await writer.processTextureAsync(material.clearcoatNormalMap), + texCoord: material.clearcoatNormalMap.channel + }; + if (material.clearcoatNormalScale.x !== 1) + clearcoatNormalMapDef.scale = material.clearcoatNormalScale.x; + writer.applyTextureTransform(clearcoatNormalMapDef, material.clearcoatNormalMap); + extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef; + } + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsDispersionExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_dispersion"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.dispersion === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.dispersion = material.dispersion; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsIridescenceExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_iridescence"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.iridescence === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.iridescenceFactor = material.iridescence; + if (material.iridescenceMap) { + const iridescenceMapDef = { + index: await writer.processTextureAsync(material.iridescenceMap), + texCoord: material.iridescenceMap.channel + }; + writer.applyTextureTransform(iridescenceMapDef, material.iridescenceMap); + extensionDef.iridescenceTexture = iridescenceMapDef; + } + extensionDef.iridescenceIor = material.iridescenceIOR; + extensionDef.iridescenceThicknessMinimum = material.iridescenceThicknessRange[0]; + extensionDef.iridescenceThicknessMaximum = material.iridescenceThicknessRange[1]; + if (material.iridescenceThicknessMap) { + const iridescenceThicknessMapDef = { + index: await writer.processTextureAsync(material.iridescenceThicknessMap), + texCoord: material.iridescenceThicknessMap.channel + }; + writer.applyTextureTransform(iridescenceThicknessMapDef, material.iridescenceThicknessMap); + extensionDef.iridescenceThicknessTexture = iridescenceThicknessMapDef; + } + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsTransmissionExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_transmission"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.transmission === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.transmissionFactor = material.transmission; + if (material.transmissionMap) { + const transmissionMapDef = { + index: await writer.processTextureAsync(material.transmissionMap), + texCoord: material.transmissionMap.channel + }; + writer.applyTextureTransform(transmissionMapDef, material.transmissionMap); + extensionDef.transmissionTexture = transmissionMapDef; + } + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsVolumeExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_volume"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.transmission === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.thicknessFactor = material.thickness; + if (material.thicknessMap) { + const thicknessMapDef = { + index: await writer.processTextureAsync(material.thicknessMap), + texCoord: material.thicknessMap.channel + }; + writer.applyTextureTransform(thicknessMapDef, material.thicknessMap); + extensionDef.thicknessTexture = thicknessMapDef; + } + if (material.attenuationDistance !== Infinity) { + extensionDef.attenuationDistance = material.attenuationDistance; + } + extensionDef.attenuationColor = material.attenuationColor.toArray(); + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsIorExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_ior"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.ior === 1.5) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.ior = material.ior; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsSpecularExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_specular"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.specularIntensity === 1 && material.specularColor.equals(DEFAULT_SPECULAR_COLOR) && !material.specularIntensityMap && !material.specularColorMap) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.specularIntensityMap) { + const specularIntensityMapDef = { + index: await writer.processTextureAsync(material.specularIntensityMap), + texCoord: material.specularIntensityMap.channel + }; + writer.applyTextureTransform(specularIntensityMapDef, material.specularIntensityMap); + extensionDef.specularTexture = specularIntensityMapDef; + } + if (material.specularColorMap) { + const specularColorMapDef = { + index: await writer.processTextureAsync(material.specularColorMap), + texCoord: material.specularColorMap.channel + }; + writer.applyTextureTransform(specularColorMapDef, material.specularColorMap); + extensionDef.specularColorTexture = specularColorMapDef; + } + extensionDef.specularFactor = material.specularIntensity; + extensionDef.specularColorFactor = material.specularColor.toArray(); + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsSheenExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_sheen"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.sheen == 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.sheenRoughnessMap) { + const sheenRoughnessMapDef = { + index: await writer.processTextureAsync(material.sheenRoughnessMap), + texCoord: material.sheenRoughnessMap.channel + }; + writer.applyTextureTransform(sheenRoughnessMapDef, material.sheenRoughnessMap); + extensionDef.sheenRoughnessTexture = sheenRoughnessMapDef; + } + if (material.sheenColorMap) { + const sheenColorMapDef = { + index: await writer.processTextureAsync(material.sheenColorMap), + texCoord: material.sheenColorMap.channel + }; + writer.applyTextureTransform(sheenColorMapDef, material.sheenColorMap); + extensionDef.sheenColorTexture = sheenColorMapDef; + } + extensionDef.sheenRoughnessFactor = material.sheenRoughness; + extensionDef.sheenColorFactor = material.sheenColor.toArray(); + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsAnisotropyExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_anisotropy"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.anisotropy == 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.anisotropyMap) { + const anisotropyMapDef = { index: await writer.processTextureAsync(material.anisotropyMap) }; + writer.applyTextureTransform(anisotropyMapDef, material.anisotropyMap); + extensionDef.anisotropyTexture = anisotropyMapDef; + } + extensionDef.anisotropyStrength = material.anisotropy; + extensionDef.anisotropyRotation = material.anisotropyRotation; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsEmissiveStrengthExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_emissive_strength"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshStandardMaterial || material.emissiveIntensity === 1) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.emissiveStrength = material.emissiveIntensity; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsBumpExtension { + constructor(writer) { + this.writer = writer; + this.name = "EXT_materials_bump"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshStandardMaterial || material.bumpScale === 1 && !material.bumpMap) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.bumpMap) { + const bumpMapDef = { + index: await writer.processTextureAsync(material.bumpMap), + texCoord: material.bumpMap.channel + }; + writer.applyTextureTransform(bumpMapDef, material.bumpMap); + extensionDef.bumpTexture = bumpMapDef; + } + extensionDef.bumpFactor = material.bumpScale; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMeshGpuInstancing { + constructor(writer) { + this.writer = writer; + this.name = "EXT_mesh_gpu_instancing"; + } + writeNode(object, nodeDef) { + if (!object.isInstancedMesh) + return; + const writer = this.writer; + const mesh = object; + const translationAttr = new Float32Array(mesh.count * 3); + const rotationAttr = new Float32Array(mesh.count * 4); + const scaleAttr = new Float32Array(mesh.count * 3); + const matrix = new Matrix4; + const position2 = new Vector3; + const quaternion = new Quaternion; + const scale2 = new Vector3; + for (let i = 0;i < mesh.count; i++) { + mesh.getMatrixAt(i, matrix); + matrix.decompose(position2, quaternion, scale2); + position2.toArray(translationAttr, i * 3); + quaternion.toArray(rotationAttr, i * 4); + scale2.toArray(scaleAttr, i * 3); + } + const attributes = { + TRANSLATION: writer.processAccessor(new BufferAttribute(translationAttr, 3)), + ROTATION: writer.processAccessor(new BufferAttribute(rotationAttr, 4)), + SCALE: writer.processAccessor(new BufferAttribute(scaleAttr, 3)) + }; + if (mesh.instanceColor) + attributes._COLOR_0 = writer.processAccessor(mesh.instanceColor); + nodeDef.extensions = nodeDef.extensions || {}; + nodeDef.extensions[this.name] = { attributes }; + writer.extensionsUsed[this.name] = true; + writer.extensionsRequired[this.name] = true; + } +} +GLTFExporter.Utils = { + insertKeyframe: function(track, time2) { + const tolerance = 0.001; + const valueSize = track.getValueSize(); + const times = new track.TimeBufferType(track.times.length + 1); + const values2 = new track.ValueBufferType(track.values.length + valueSize); + const interpolant = track.createInterpolant(new track.ValueBufferType(valueSize)); + let index2; + if (track.times.length === 0) { + times[0] = time2; + for (let i = 0;i < valueSize; i++) { + values2[i] = 0; + } + index2 = 0; + } else if (time2 < track.times[0]) { + if (Math.abs(track.times[0] - time2) < tolerance) + return 0; + times[0] = time2; + times.set(track.times, 1); + values2.set(interpolant.evaluate(time2), 0); + values2.set(track.values, valueSize); + index2 = 0; + } else if (time2 > track.times[track.times.length - 1]) { + if (Math.abs(track.times[track.times.length - 1] - time2) < tolerance) { + return track.times.length - 1; + } + times[times.length - 1] = time2; + times.set(track.times, 0); + values2.set(track.values, 0); + values2.set(interpolant.evaluate(time2), track.values.length); + index2 = times.length - 1; + } else { + for (let i = 0;i < track.times.length; i++) { + if (Math.abs(track.times[i] - time2) < tolerance) + return i; + if (track.times[i] < time2 && track.times[i + 1] > time2) { + times.set(track.times.slice(0, i + 1), 0); + times[i + 1] = time2; + times.set(track.times.slice(i + 1), i + 2); + values2.set(track.values.slice(0, (i + 1) * valueSize), 0); + values2.set(interpolant.evaluate(time2), (i + 1) * valueSize); + values2.set(track.values.slice((i + 1) * valueSize), (i + 2) * valueSize); + index2 = i + 1; + break; + } + } + } + track.times = times; + track.values = values2; + return index2; + }, + mergeMorphTargetTracks: function(clip, root) { + const tracks = []; + const mergedTracks = {}; + const sourceTracks = clip.tracks; + for (let i = 0;i < sourceTracks.length; ++i) { + let sourceTrack = sourceTracks[i]; + const sourceTrackBinding = PropertyBinding.parseTrackName(sourceTrack.name); + const sourceTrackNode = PropertyBinding.findNode(root, sourceTrackBinding.nodeName); + if (sourceTrackBinding.propertyName !== "morphTargetInfluences" || sourceTrackBinding.propertyIndex === undefined) { + tracks.push(sourceTrack); + continue; + } + if (sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear) { + if (sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation."); + } + console.warn("THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead."); + sourceTrack = sourceTrack.clone(); + sourceTrack.setInterpolation(InterpolateLinear); + } + const targetCount = sourceTrackNode.morphTargetInfluences.length; + const targetIndex = sourceTrackNode.morphTargetDictionary[sourceTrackBinding.propertyIndex]; + if (targetIndex === undefined) { + throw new Error("THREE.GLTFExporter: Morph target name not found: " + sourceTrackBinding.propertyIndex); + } + let mergedTrack; + if (mergedTracks[sourceTrackNode.uuid] === undefined) { + mergedTrack = sourceTrack.clone(); + const values2 = new mergedTrack.ValueBufferType(targetCount * mergedTrack.times.length); + for (let j = 0;j < mergedTrack.times.length; j++) { + values2[j * targetCount + targetIndex] = mergedTrack.values[j]; + } + mergedTrack.name = (sourceTrackBinding.nodeName || "") + ".morphTargetInfluences"; + mergedTrack.values = values2; + mergedTracks[sourceTrackNode.uuid] = mergedTrack; + tracks.push(mergedTrack); + continue; + } + const sourceInterpolant = sourceTrack.createInterpolant(new sourceTrack.ValueBufferType(1)); + mergedTrack = mergedTracks[sourceTrackNode.uuid]; + for (let j = 0;j < mergedTrack.times.length; j++) { + mergedTrack.values[j * targetCount + targetIndex] = sourceInterpolant.evaluate(mergedTrack.times[j]); + } + for (let j = 0;j < sourceTrack.times.length; j++) { + const keyframeIndex = this.insertKeyframe(mergedTrack, sourceTrack.times[j]); + mergedTrack.values[keyframeIndex * targetCount + targetIndex] = sourceTrack.values[j]; + } + } + clip.tracks = tracks; + return clip; + }, + toFloat32BufferAttribute: function(srcAttribute) { + const dstAttribute = new BufferAttribute(new Float32Array(srcAttribute.count * srcAttribute.itemSize), srcAttribute.itemSize, false); + if (!srcAttribute.normalized && !srcAttribute.isInterleavedBufferAttribute) { + dstAttribute.array.set(srcAttribute.array); + return dstAttribute; + } + for (let i = 0, il = srcAttribute.count;i < il; i++) { + for (let j = 0;j < srcAttribute.itemSize; j++) { + dstAttribute.setComponent(i, j, srcAttribute.getComponent(i, j)); + } + } + return dstAttribute; + } +}; +// node_modules/three/examples/jsm/libs/ktx-parse.module.js +var t = 0; +var n = 2; +var g = 1; +var u = 2; +var T = 0; +var C2 = 1; +var R = 10; +var it = 0; +var ct = 9; +var yt = 15; +var xt2 = 16; +var wt = 22; +var Ft = 37; +var Ct = 43; +var te2 = 76; +var ae2 = 83; +var ge = 97; +var ue2 = 100; +var we = 103; +var Ae = 109; +var In = 165; +var Sn = 166; +var pi = 1000066000; +class Ii { + constructor() { + this.vkFormat = 0, this.typeSize = 1, this.pixelWidth = 0, this.pixelHeight = 0, this.pixelDepth = 0, this.layerCount = 0, this.faceCount = 1, this.supercompressionScheme = 0, this.levels = [], this.dataFormatDescriptor = [{ vendorId: 0, descriptorType: 0, descriptorBlockSize: 0, versionNumber: 2, colorModel: 0, colorPrimaries: 1, transferFunction: 2, flags: 0, texelBlockDimension: [0, 0, 0, 0], bytesPlane: [0, 0, 0, 0, 0, 0, 0, 0], samples: [] }], this.keyValue = {}, this.globalData = null; + } +} + +class Si { + constructor(t2, e, n2, i) { + this._dataView = undefined, this._littleEndian = undefined, this._offset = undefined, this._dataView = new DataView(t2.buffer, t2.byteOffset + e, n2), this._littleEndian = i, this._offset = 0; + } + _nextUint8() { + const t2 = this._dataView.getUint8(this._offset); + return this._offset += 1, t2; + } + _nextUint16() { + const t2 = this._dataView.getUint16(this._offset, this._littleEndian); + return this._offset += 2, t2; + } + _nextUint32() { + const t2 = this._dataView.getUint32(this._offset, this._littleEndian); + return this._offset += 4, t2; + } + _nextUint64() { + const t2 = this._dataView.getUint32(this._offset, this._littleEndian) + 2 ** 32 * this._dataView.getUint32(this._offset + 4, this._littleEndian); + return this._offset += 8, t2; + } + _nextInt32() { + const t2 = this._dataView.getInt32(this._offset, this._littleEndian); + return this._offset += 4, t2; + } + _nextUint8Array(t2) { + const e = new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + this._offset, t2); + return this._offset += t2, e; + } + _skip(t2) { + return this._offset += t2, this; + } + _scan(t2, e) { + e === undefined && (e = 0); + const n2 = this._offset; + let i = 0; + for (;this._dataView.getUint8(this._offset) !== e && i < t2; ) + i++, this._offset++; + return i < t2 && this._offset++, new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + n2, i); + } +} +var Fi = new Uint8Array([0]); +var Oi = [171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10]; +function Ti(t2) { + return new TextDecoder().decode(t2); +} +function Pi2(t2) { + const e = new Uint8Array(t2.buffer, t2.byteOffset, Oi.length); + if (e[0] !== Oi[0] || e[1] !== Oi[1] || e[2] !== Oi[2] || e[3] !== Oi[3] || e[4] !== Oi[4] || e[5] !== Oi[5] || e[6] !== Oi[6] || e[7] !== Oi[7] || e[8] !== Oi[8] || e[9] !== Oi[9] || e[10] !== Oi[10] || e[11] !== Oi[11]) + throw new Error("Missing KTX 2.0 identifier."); + const n2 = new Ii, i = 17 * Uint32Array.BYTES_PER_ELEMENT, s = new Si(t2, Oi.length, i, true); + n2.vkFormat = s._nextUint32(), n2.typeSize = s._nextUint32(), n2.pixelWidth = s._nextUint32(), n2.pixelHeight = s._nextUint32(), n2.pixelDepth = s._nextUint32(), n2.layerCount = s._nextUint32(), n2.faceCount = s._nextUint32(); + const a = s._nextUint32(); + n2.supercompressionScheme = s._nextUint32(); + const r = s._nextUint32(), o = s._nextUint32(), l = s._nextUint32(), f = s._nextUint32(), h = s._nextUint64(), U = s._nextUint64(), c = new Si(t2, Oi.length + i, 3 * a * 8, true); + for (let e2 = 0;e2 < a; e2++) + n2.levels.push({ levelData: new Uint8Array(t2.buffer, t2.byteOffset + c._nextUint64(), c._nextUint64()), uncompressedByteLength: c._nextUint64() }); + const _2 = new Si(t2, r, o, true), p = { vendorId: _2._skip(4)._nextUint16(), descriptorType: _2._nextUint16(), versionNumber: _2._nextUint16(), descriptorBlockSize: _2._nextUint16(), colorModel: _2._nextUint8(), colorPrimaries: _2._nextUint8(), transferFunction: _2._nextUint8(), flags: _2._nextUint8(), texelBlockDimension: [_2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8()], bytesPlane: [_2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8()], samples: [] }, g2 = (p.descriptorBlockSize / 4 - 6) / 4; + for (let t3 = 0;t3 < g2; t3++) { + const e2 = { bitOffset: _2._nextUint16(), bitLength: _2._nextUint8(), channelType: _2._nextUint8(), samplePosition: [_2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8()], sampleLower: -Infinity, sampleUpper: Infinity }; + 64 & e2.channelType ? (e2.sampleLower = _2._nextInt32(), e2.sampleUpper = _2._nextInt32()) : (e2.sampleLower = _2._nextUint32(), e2.sampleUpper = _2._nextUint32()), p.samples[t3] = e2; + } + n2.dataFormatDescriptor.length = 0, n2.dataFormatDescriptor.push(p); + const y = new Si(t2, l, f, true); + for (;y._offset < f; ) { + const t3 = y._nextUint32(), e2 = y._scan(t3), i2 = Ti(e2); + if (n2.keyValue[i2] = y._nextUint8Array(t3 - e2.byteLength - 1), i2.match(/^ktx/i)) { + const t4 = Ti(n2.keyValue[i2]); + n2.keyValue[i2] = t4.substring(0, t4.lastIndexOf("\x00")); + } + y._skip(t3 % 4 ? 4 - t3 % 4 : 0); + } + if (U <= 0) + return n2; + const x = new Si(t2, h, U, true), u2 = x._nextUint16(), b = x._nextUint16(), d = x._nextUint32(), w = x._nextUint32(), m = x._nextUint32(), D = x._nextUint32(), B = []; + for (let t3 = 0;t3 < a; t3++) + B.push({ imageFlags: x._nextUint32(), rgbSliceByteOffset: x._nextUint32(), rgbSliceByteLength: x._nextUint32(), alphaSliceByteOffset: x._nextUint32(), alphaSliceByteLength: x._nextUint32() }); + const L = h + x._offset, v = L + d, A = v + w, k2 = A + m, V2 = new Uint8Array(t2.buffer, t2.byteOffset + L, d), I2 = new Uint8Array(t2.buffer, t2.byteOffset + v, w), S = new Uint8Array(t2.buffer, t2.byteOffset + A, m), F = new Uint8Array(t2.buffer, t2.byteOffset + k2, D); + return n2.globalData = { endpointCount: u2, selectorCount: b, imageDescs: B, endpointsData: V2, selectorsData: I2, tablesData: S, extendedData: F }, n2; +} + +// node_modules/three/examples/jsm/exporters/KTX2Exporter.js +var VK_FORMAT_MAP = { + [RGBAFormat]: { + [FloatType]: { + [NoColorSpace]: Ae, + [LinearSRGBColorSpace]: Ae + }, + [HalfFloatType]: { + [NoColorSpace]: ge, + [LinearSRGBColorSpace]: ge + }, + [UnsignedByteType]: { + [NoColorSpace]: Ft, + [LinearSRGBColorSpace]: Ft, + [SRGBColorSpace]: Ct + } + }, + [RGFormat]: { + [FloatType]: { + [NoColorSpace]: we, + [LinearSRGBColorSpace]: we + }, + [HalfFloatType]: { + [NoColorSpace]: ae2, + [LinearSRGBColorSpace]: ae2 + }, + [UnsignedByteType]: { + [NoColorSpace]: xt2, + [LinearSRGBColorSpace]: xt2, + [SRGBColorSpace]: wt + } + }, + [RedFormat]: { + [FloatType]: { + [NoColorSpace]: ue2, + [LinearSRGBColorSpace]: ue2 + }, + [HalfFloatType]: { + [NoColorSpace]: te2, + [LinearSRGBColorSpace]: te2 + }, + [UnsignedByteType]: { + [NoColorSpace]: ct, + [LinearSRGBColorSpace]: ct, + [SRGBColorSpace]: yt + } + } +}; +var KHR_DF_CHANNEL_SAMPLE_LOWER_UPPER = { + [FloatType]: [3212836864, 1065353216], + [HalfFloatType]: [3212836864, 1065353216], + [UnsignedByteType]: [0, 255] +}; +// node_modules/three/examples/jsm/math/ConvexHull.js +var _v13 = new Vector3; +var _line3 = new Line3; +var _plane3 = new Plane; +var _closestPoint = new Vector3; +var _triangle2 = new Triangle; +// node_modules/three/examples/jsm/geometries/ParametricGeometry.js +class ParametricGeometry extends BufferGeometry { + constructor(func = (u2, v, target) => target.set(u2, v, Math.cos(u2) * Math.sin(v)), slices = 8, stacks = 8) { + super(); + this.type = "ParametricGeometry"; + this.parameters = { + func, + slices, + stacks + }; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const EPS = 0.00001; + const normal = new Vector3; + const p0 = new Vector3, p1 = new Vector3; + const pu = new Vector3, pv = new Vector3; + const sliceCount = slices + 1; + for (let i = 0;i <= stacks; i++) { + const v = i / stacks; + for (let j2 = 0;j2 <= slices; j2++) { + const u2 = j2 / slices; + func(u2, v, p0); + vertices.push(p0.x, p0.y, p0.z); + if (u2 - EPS >= 0) { + func(u2 - EPS, v, p1); + pu.subVectors(p0, p1); + } else { + func(u2 + EPS, v, p1); + pu.subVectors(p1, p0); + } + if (v - EPS >= 0) { + func(u2, v - EPS, p1); + pv.subVectors(p0, p1); + } else { + func(u2, v + EPS, p1); + pv.subVectors(p1, p0); + } + normal.crossVectors(pu, pv).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u2, v); + } + } + for (let i = 0;i < stacks; i++) { + for (let j2 = 0;j2 < slices; j2++) { + const a = i * sliceCount + j2; + const b = i * sliceCount + j2 + 1; + const c = (i + 1) * sliceCount + j2 + 1; + const d = (i + 1) * sliceCount + j2; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } +} + +// node_modules/three/examples/jsm/geometries/ParametricGeometries.js +var ParametricGeometries = { + klein: function(v, u2, target) { + u2 *= Math.PI; + v *= 2 * Math.PI; + u2 = u2 * 2; + let x2, z; + if (u2 < Math.PI) { + x2 = 3 * Math.cos(u2) * (1 + Math.sin(u2)) + 2 * (1 - Math.cos(u2) / 2) * Math.cos(u2) * Math.cos(v); + z = -8 * Math.sin(u2) - 2 * (1 - Math.cos(u2) / 2) * Math.sin(u2) * Math.cos(v); + } else { + x2 = 3 * Math.cos(u2) * (1 + Math.sin(u2)) + 2 * (1 - Math.cos(u2) / 2) * Math.cos(v + Math.PI); + z = -8 * Math.sin(u2); + } + const y = -2 * (1 - Math.cos(u2) / 2) * Math.sin(v); + target.set(x2, y, z); + }, + plane: function(width2, height2) { + return function(u2, v, target) { + const x2 = u2 * width2; + const y = 0; + const z = v * height2; + target.set(x2, y, z); + }; + }, + mobius: function(u2, t2, target) { + u2 = u2 - 0.5; + const v = 2 * Math.PI * t2; + const a = 2; + const x2 = Math.cos(v) * (a + u2 * Math.cos(v / 2)); + const y = Math.sin(v) * (a + u2 * Math.cos(v / 2)); + const z = u2 * Math.sin(v / 2); + target.set(x2, y, z); + }, + mobius3d: function(u2, t2, target) { + u2 *= Math.PI; + t2 *= 2 * Math.PI; + u2 = u2 * 2; + const phi = u2 / 2; + const major = 2.25, a = 0.125, b = 0.65; + let x2 = a * Math.cos(t2) * Math.cos(phi) - b * Math.sin(t2) * Math.sin(phi); + const z = a * Math.cos(t2) * Math.sin(phi) + b * Math.sin(t2) * Math.cos(phi); + const y = (major + x2) * Math.sin(u2); + x2 = (major + x2) * Math.cos(u2); + target.set(x2, y, z); + } +}; +ParametricGeometries.TubeGeometry = class TubeGeometry2 extends ParametricGeometry { + constructor(path, segments = 64, radius = 1, segmentsRadius = 8, closed = false) { + const numpoints = segments + 1; + const frames2 = path.computeFrenetFrames(segments, closed), tangents = frames2.tangents, normals = frames2.normals, binormals = frames2.binormals; + const position2 = new Vector3; + function ParametricTube(u2, v, target) { + v *= 2 * Math.PI; + const i = Math.floor(u2 * (numpoints - 1)); + path.getPointAt(u2, position2); + const normal = normals[i]; + const binormal = binormals[i]; + const cx = -radius * Math.cos(v); + const cy = radius * Math.sin(v); + position2.x += cx * normal.x + cy * binormal.x; + position2.y += cx * normal.y + cy * binormal.y; + position2.z += cx * normal.z + cy * binormal.z; + target.copy(position2); + } + super(ParametricTube, segments, segmentsRadius); + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; + this.path = path; + this.segments = segments; + this.radius = radius; + this.segmentsRadius = segmentsRadius; + this.closed = closed; + } +}; +ParametricGeometries.TorusKnotGeometry = class TorusKnotGeometry2 extends ParametricGeometries.TubeGeometry { + constructor(radius = 200, tube = 40, segmentsT = 64, segmentsR = 8, p = 2, q2 = 3) { + + class TorusKnotCurve extends Curve { + getPoint(t2, optionalTarget = new Vector3) { + const point = optionalTarget; + t2 *= Math.PI * 2; + const r = 0.5; + const x2 = (1 + r * Math.cos(q2 * t2)) * Math.cos(p * t2); + const y = (1 + r * Math.cos(q2 * t2)) * Math.sin(p * t2); + const z = r * Math.sin(q2 * t2); + return point.set(x2, y, z).multiplyScalar(radius); + } + } + const segments = segmentsT; + const radiusSegments = segmentsR; + const extrudePath = new TorusKnotCurve; + super(extrudePath, segments, tube, radiusSegments, true, false); + this.radius = radius; + this.tube = tube; + this.segmentsT = segmentsT; + this.segmentsR = segmentsR; + this.p = p; + this.q = q2; + } +}; +ParametricGeometries.SphereGeometry = class SphereGeometry2 extends ParametricGeometry { + constructor(size, u2, v) { + function sphere(u3, v2, target) { + u3 *= Math.PI; + v2 *= 2 * Math.PI; + const x2 = size * Math.sin(u3) * Math.cos(v2); + const y = size * Math.sin(u3) * Math.sin(v2); + const z = size * Math.cos(u3); + target.set(x2, y, z); + } + super(sphere, u2, v); + } +}; +ParametricGeometries.PlaneGeometry = class PlaneGeometry2 extends ParametricGeometry { + constructor(width2, depth, segmentsWidth, segmentsDepth) { + function plane(u2, v, target) { + const x2 = u2 * width2; + const y = 0; + const z = v * depth; + target.set(x2, y, z); + } + super(plane, segmentsWidth, segmentsDepth); + } +}; +// node_modules/three/examples/jsm/geometries/RoundedBoxGeometry.js +var _tempNormal = new Vector3; +// node_modules/three/examples/jsm/utils/BufferGeometryUtils.js +function toTrianglesDrawMode(geometry, drawMode) { + if (drawMode === TrianglesDrawMode) { + console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."); + return geometry; + } + if (drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode) { + let index2 = geometry.getIndex(); + if (index2 === null) { + const indices = []; + const position2 = geometry.getAttribute("position"); + if (position2 !== undefined) { + for (let i = 0;i < position2.count; i++) { + indices.push(i); + } + geometry.setIndex(indices); + index2 = geometry.getIndex(); + } else { + console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."); + return geometry; + } + } + const numberOfTriangles = index2.count - 2; + const newIndices = []; + if (drawMode === TriangleFanDrawMode) { + for (let i = 1;i <= numberOfTriangles; i++) { + newIndices.push(index2.getX(0)); + newIndices.push(index2.getX(i)); + newIndices.push(index2.getX(i + 1)); + } + } else { + for (let i = 0;i < numberOfTriangles; i++) { + if (i % 2 === 0) { + newIndices.push(index2.getX(i)); + newIndices.push(index2.getX(i + 1)); + newIndices.push(index2.getX(i + 2)); + } else { + newIndices.push(index2.getX(i + 2)); + newIndices.push(index2.getX(i + 1)); + newIndices.push(index2.getX(i)); + } + } + } + if (newIndices.length / 3 !== numberOfTriangles) { + console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles."); + } + const newGeometry = geometry.clone(); + newGeometry.setIndex(newIndices); + newGeometry.clearGroups(); + return newGeometry; + } else { + console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:", drawMode); + return geometry; + } +} +// node_modules/three/examples/jsm/helpers/VertexNormalsHelper.js +var _v14 = new Vector3; +var _v24 = new Vector3; +var _normalMatrix2 = new Matrix3; +// node_modules/three/examples/jsm/helpers/VertexTangentsHelper.js +var _v15 = new Vector3; +var _v25 = new Vector3; +// node_modules/three/examples/jsm/interactive/HTMLMesh.js +var canvases = new WeakMap; +// node_modules/three/examples/jsm/interactive/InteractiveGroup.js +var _pointer2 = new Vector2; +var _raycaster3 = new Raycaster; +// node_modules/three/examples/jsm/interactive/SelectionBox.js +var _frustum2 = new Frustum; +var _center3 = new Vector3; +var _tmpPoint = new Vector3; +var _vecNear = new Vector3; +var _vecTopLeft = new Vector3; +var _vecTopRight = new Vector3; +var _vecDownRight = new Vector3; +var _vecDownLeft = new Vector3; +var _vecFarTopLeft = new Vector3; +var _vecFarTopRight = new Vector3; +var _vecFarDownRight = new Vector3; +var _vecFarDownLeft = new Vector3; +var _vectemp1 = new Vector3; +var _vectemp2 = new Vector3; +var _vectemp3 = new Vector3; +var _matrix3 = new Matrix4; +var _quaternion3 = new Quaternion; +var _scale2 = new Vector3; +// node_modules/three/examples/jsm/lights/RectAreaLightTexturesLib.js +class RectAreaLightTexturesLib { + static init() { + const LTC_MAT_1 = [1, 0, 0, 0.00002, 1, 0, 0, 0.000503905, 1, 0, 0, 0.00201562, 1, 0, 0, 0.00453516, 1, 0, 0, 0.00806253, 1, 0, 0, 0.0125978, 1, 0, 0, 0.018141, 1, 0, 0, 0.0246924, 1, 0, 0, 0.0322525, 1, 0, 0, 0.0408213, 1, 0, 0, 0.0503999, 1, 0, 0, 0.0609894, 1, 0, 0, 0.0725906, 1, 0, 0, 0.0852058, 1, 0, 0, 0.0988363, 1, 0, 0, 0.113484, 1, 0, 0, 0.129153, 1, 0, 0, 0.145839, 1, 0, 0, 0.163548, 1, 0, 0, 0.182266, 1, 0, 0, 0.201942, 1, 0, 0, 0.222314, 1, 0, 0, 0.241906, 1, 0, 0, 0.262314, 1, 0, 0, 0.285754, 1, 0, 0, 0.310159, 1, 0, 0, 0.335426, 1, 0, 0, 0.361341, 1, 0, 0, 0.387445, 1, 0, 0, 0.412784, 1, 0, 0, 0.438197, 1, 0, 0, 0.466966, 1, 0, 0, 0.49559, 1, 0, 0, 0.523448, 1, 0, 0, 0.549938, 1, 0, 0, 0.57979, 1, 0, 0, 0.608746, 1, 0, 0, 0.636185, 1, 0, 0, 0.664748, 1, 0, 0, 0.69313, 1, 0, 0, 0.71966, 1, 0, 0, 0.747662, 1, 0, 0, 0.774023, 1, 0, 0, 0.799775, 1, 0, 0, 0.825274, 1, 0, 0, 0.849156, 1, 0, 0, 0.873248, 1, 0, 0, 0.89532, 1, 0, 0, 0.917565, 1, 0, 0, 0.937863, 1, 0, 0, 0.958139, 1, 0, 0, 0.976563, 1, 0, 0, 0.994658, 1, 0, 0, 1.0112, 1, 0, 0, 1.02712, 1, 0, 0, 1.04189, 1, 0, 0, 1.05568, 1, 0, 0, 1.06877, 1, 0, 0, 1.08058, 1, 0, 0, 1.09194, 1, 0, 0, 1.10191, 1, 0, 0, 1.11161, 1, 0, 0, 1.1199, 1, 0, 0, 1.12813, 0.999547, -0.000000448815, 0.0224417, 0.0000199902, 0.999495, -0.0000113079, 0.0224406, 0.000503651, 0.999496, -0.0000452317, 0.0224406, 0.00201461, 0.999496, -0.000101772, 0.0224406, 0.00453287, 0.999495, -0.000180928, 0.0224406, 0.00805845, 0.999497, -0.000282702, 0.0224406, 0.0125914, 0.999496, -0.000407096, 0.0224406, 0.0181319, 0.999498, -0.000554114, 0.0224406, 0.02468, 0.999499, -0.000723768, 0.0224406, 0.0322363, 0.999495, -0.000916058, 0.0224405, 0.0408009, 0.999499, -0.00113101, 0.0224408, 0.050375, 0.999494, -0.00136863, 0.0224405, 0.0609586, 0.999489, -0.00162896, 0.0224401, 0.0725537, 0.999489, -0.00191201, 0.0224414, 0.0851619, 0.999498, -0.00221787, 0.0224413, 0.0987867, 0.999492, -0.00254642, 0.0224409, 0.113426, 0.999507, -0.00289779, 0.0224417, 0.129088, 0.999494, -0.0032716, 0.0224386, 0.145767, 0.999546, -0.0036673, 0.0224424, 0.163472, 0.999543, -0.00408166, 0.0224387, 0.182182, 0.999499, -0.00450056, 0.0224338, 0.201843, 0.999503, -0.00483661, 0.0224203, 0.222198, 0.999546, -0.00452928, 0.022315, 0.241714, 0.999508, -0.00587403, 0.0224329, 0.262184, 0.999509, -0.00638806, 0.0224271, 0.285609, 0.999501, -0.00691028, 0.0224166, 0.309998, 0.999539, -0.00741979, 0.0223989, 0.335262, 0.999454, -0.00786282, 0.0223675, 0.361154, 0.999529, -0.00811928, 0.0222828, 0.387224, 0.999503, -0.00799941, 0.0221063, 0.41252, 0.999561, -0.00952753, 0.0223057, 0.438006, 0.999557, -0.0099134, 0.0222065, 0.466735, 0.999541, -0.0100935, 0.0220402, 0.495332, 0.999562, -0.00996821, 0.0218067, 0.523197, 0.999556, -0.0105031, 0.0217096, 0.550223, 0.999561, -0.0114191, 0.0217215, 0.579498, 0.999588, -0.0111818, 0.0213357, 0.608416, 0.999633, -0.0107725, 0.0208689, 0.635965, 0.999527, -0.0121671, 0.0210149, 0.664476, 0.999508, -0.0116005, 0.020431, 0.692786, 0.999568, -0.0115604, 0.0199791, 0.719709, 0.999671, -0.0121117, 0.0197415, 0.74737, 0.999688, -0.0110769, 0.0188846, 0.773692, 0.99962, -0.0122368, 0.0188452, 0.799534, 0.999823, -0.0110325, 0.0178001, 0.825046, 0.999599, -0.0114923, 0.0174221, 0.849075, 0.999619, -0.0105923, 0.0164345, 0.872999, 0.999613, -0.0105988, 0.0158227, 0.895371, 0.99964, -0.00979861, 0.0148131, 0.917364, 0.99977, -0.00967238, 0.0140721, 0.938002, 0.999726, -0.00869175, 0.0129543, 0.957917, 0.99973, -0.00866872, 0.0122329, 0.976557, 0.999773, -0.00731956, 0.0108958, 0.994459, 0.999811, -0.00756027, 0.0102715, 1.01118, 0.999862, -0.00583732, 0.00878781, 1.02701, 0.999835, -0.00631438, 0.00827529, 1.04186, 0.999871, -0.00450785, 0.00674583, 1.05569, 0.999867, -0.00486079, 0.00621041, 1.06861, 0.999939, -0.00322072, 0.00478301, 1.08064, 0.999918, -0.00318199, 0.00406395, 1.09181, 1.00003, -0.00193348, 0.00280682, 1.10207, 0.999928, -0.00153729, 0.00198741, 1.11152, 0.999933, -0.000623666, 0.000917714, 1.12009, 1, -0.00000102387, 0.000000907581, 1.12813, 0.997866, -0.000000896716, 0.0448334, 0.0000199584, 0.997987, -0.0000225945, 0.0448389, 0.000502891, 0.997987, -0.0000903781, 0.0448388, 0.00201156, 0.997985, -0.000203351, 0.0448388, 0.00452602, 0.997986, -0.000361514, 0.0448388, 0.00804629, 0.997987, -0.00056487, 0.0448389, 0.0125724, 0.997988, -0.000813423, 0.0448389, 0.0181045, 0.997984, -0.00110718, 0.0448387, 0.0246427, 0.997985, -0.00144616, 0.0448388, 0.0321875, 0.997987, -0.00183038, 0.044839, 0.0407392, 0.997983, -0.00225987, 0.0448387, 0.0502986, 0.997991, -0.00273467, 0.0448389, 0.0608667, 0.997984, -0.00325481, 0.0448384, 0.0724444, 0.998002, -0.00382043, 0.044839, 0.0850348, 0.997997, -0.00443145, 0.0448396, 0.0986372, 0.998007, -0.00508796, 0.0448397, 0.113255, 0.998008, -0.00578985, 0.04484, 0.128891, 0.998003, -0.00653683, 0.0448384, 0.145548, 0.997983, -0.00732713, 0.0448358, 0.163221, 0.997985, -0.00815454, 0.0448358, 0.181899, 0.998005, -0.00898985, 0.0448286, 0.201533, 0.998026, -0.00964404, 0.0447934, 0.221821, 0.998055, -0.00922677, 0.044611, 0.241282, 0.99804, -0.0117361, 0.0448245, 0.261791, 0.998048, -0.0127628, 0.0448159, 0.285181, 0.998088, -0.0138055, 0.0447996, 0.30954, 0.998058, -0.0148206, 0.0447669, 0.334751, 0.998099, -0.0156998, 0.044697, 0.36061, 0.998116, -0.0161976, 0.0445122, 0.386603, 0.998195, -0.015945, 0.0441711, 0.411844, 0.998168, -0.0183947, 0.0444255, 0.43773, 0.998184, -0.0197913, 0.0443809, 0.466009, 0.998251, -0.0201426, 0.0440689, 0.494574, 0.998305, -0.0198847, 0.0435632, 0.522405, 0.998273, -0.0210577, 0.043414, 0.549967, 0.998254, -0.0227901, 0.0433943, 0.578655, 0.998349, -0.0223108, 0.0426529, 0.60758, 0.99843, -0.0223088, 0.042, 0.635524, 0.998373, -0.0241141, 0.0418987, 0.663621, 0.998425, -0.0231446, 0.0408118, 0.691906, 0.998504, -0.0233684, 0.0400565, 0.719339, 0.998443, -0.0241652, 0.0394634, 0.74643, 0.99848, -0.0228715, 0.0380002, 0.773086, 0.998569, -0.023519, 0.0372322, 0.798988, 0.998619, -0.0223108, 0.0356468, 0.824249, 0.998594, -0.0223105, 0.034523, 0.848808, 0.998622, -0.0213426, 0.0328887, 0.87227, 0.998669, -0.0207912, 0.0314374, 0.895157, 0.998705, -0.0198416, 0.0296925, 0.916769, 0.998786, -0.0189168, 0.0279634, 0.937773, 0.998888, -0.0178811, 0.0261597, 0.957431, 0.99906, -0.0166845, 0.0242159, 0.976495, 0.999038, -0.0155464, 0.0222638, 0.994169, 0.999237, -0.0141349, 0.0201967, 1.01112, 0.999378, -0.0129324, 0.0181744, 1.02692, 0.999433, -0.0113192, 0.0159898, 1.04174, 0.999439, -0.0101244, 0.0140385, 1.05559, 0.999614, -0.00837456, 0.0117826, 1.06852, 0.999722, -0.00721769, 0.00983745, 1.08069, 0.999817, -0.00554067, 0.00769002, 1.09176, 0.99983, -0.00426961, 0.005782, 1.10211, 0.999964, -0.00273904, 0.00374503, 1.11152, 1.00001, -0.00136739, 0.00187176, 1.12031, 0.999946, 0.0000393227, -0.000028919, 1.12804, 0.995847, -0.0000013435, 0.0671785, 0.000019916, 0.995464, -0.0000338387, 0.0671527, 0.000501622, 0.99547, -0.000135355, 0.0671531, 0.00200649, 0.995471, -0.00030455, 0.0671532, 0.00451461, 0.99547, -0.000541423, 0.0671531, 0.008026, 0.995471, -0.00084598, 0.0671531, 0.0125407, 0.99547, -0.00121823, 0.0671531, 0.0180589, 0.99547, -0.00165817, 0.0671531, 0.0245806, 0.995463, -0.00216583, 0.0671526, 0.0321062, 0.995468, -0.00274127, 0.0671527, 0.0406366, 0.995474, -0.00338447, 0.0671534, 0.0501717, 0.995473, -0.00409554, 0.0671533, 0.0607131, 0.995478, -0.00487451, 0.0671531, 0.0722618, 0.995476, -0.00572148, 0.0671532, 0.0848191, 0.995477, -0.00663658, 0.0671539, 0.0983882, 0.995498, -0.00761986, 0.0671541, 0.112972, 0.995509, -0.00867094, 0.0671542, 0.128568, 0.995509, -0.00978951, 0.0671531, 0.145183, 0.995503, -0.0109725, 0.0671491, 0.162808, 0.995501, -0.012211, 0.0671465, 0.181441, 0.99553, -0.0134565, 0.0671371, 0.201015, 0.99555, -0.014391, 0.0670831, 0.221206, 0.99558, -0.014351, 0.0668883, 0.240813, 0.995577, -0.0173997, 0.0671055, 0.261257, 0.995602, -0.0191111, 0.0671178, 0.284467, 0.995623, -0.0206705, 0.0670946, 0.308765, 0.995658, -0.022184, 0.0670472, 0.333905, 0.995705, -0.0234832, 0.0669417, 0.359677, 0.995719, -0.0241933, 0.0666714, 0.385554, 0.995786, -0.0243539, 0.066266, 0.410951, 0.995887, -0.0271866, 0.0664367, 0.437163, 0.995944, -0.0296012, 0.0664931, 0.464842, 0.996004, -0.0301045, 0.0660105, 0.49332, 0.996128, -0.0298311, 0.0652694, 0.521131, 0.996253, -0.0316426, 0.0650739, 0.549167, 0.996244, -0.0339043, 0.0649433, 0.57737, 0.996309, -0.033329, 0.0638926, 0.606073, 0.996417, -0.0338935, 0.0630849, 0.634527, 0.996372, -0.0353104, 0.0625083, 0.66256, 0.996542, -0.0348942, 0.0611986, 0.690516, 0.996568, -0.0351614, 0.060069, 0.718317, 0.996711, -0.0354317, 0.0588522, 0.74528, 0.996671, -0.0349513, 0.0571902, 0.772061, 0.996865, -0.0345622, 0.0555321, 0.798089, 0.996802, -0.0342566, 0.0537816, 0.823178, 0.996992, -0.0330862, 0.0516095, 0.847949, 0.996944, -0.0324666, 0.0495537, 0.871431, 0.997146, -0.0309544, 0.0470302, 0.894357, 0.997189, -0.0299372, 0.0446043, 0.916142, 0.997471, -0.0281389, 0.0418812, 0.937193, 0.997515, -0.0268702, 0.0391823, 0.957, 0.997812, -0.0247166, 0.0361338, 0.975936, 0.998027, -0.0233525, 0.0333945, 0.99391, 0.998233, -0.0209839, 0.0301917, 1.01075, 0.998481, -0.0194309, 0.027271, 1.02669, 0.998859, -0.0169728, 0.0240162, 1.04173, 0.99894, -0.0152322, 0.0210517, 1.05551, 0.999132, -0.0127497, 0.0178632, 1.06856, 0.999369, -0.0108282, 0.014787, 1.08054, 0.999549, -0.00845886, 0.0116185, 1.09185, 0.999805, -0.0063937, 0.00867209, 1.10207, 0.99985, -0.00414582, 0.00566823, 1.1117, 0.999912, -0.00207443, 0.00277562, 1.12022, 1.00001, 0.0000870226, -0.000053766, 1.12832, 0.991943, -0.00000178672, 0.0893382, 0.0000198384, 0.991952, -0.0000450183, 0.089339, 0.000499849, 0.991956, -0.000180074, 0.0893394, 0.0019994, 0.991955, -0.000405167, 0.0893393, 0.00449867, 0.991953, -0.000720298, 0.0893391, 0.00799764, 0.991955, -0.00112548, 0.0893393, 0.0124964, 0.991957, -0.0016207, 0.0893395, 0.0179951, 0.991958, -0.00220601, 0.0893396, 0.0244939, 0.991947, -0.00288137, 0.0893385, 0.0319929, 0.991962, -0.00364693, 0.0893399, 0.0404933, 0.991965, -0.00450264, 0.0893399, 0.049995, 0.99198, -0.00544862, 0.0893411, 0.0604995, 0.99197, -0.00648491, 0.0893397, 0.0720074, 0.991976, -0.00761164, 0.089341, 0.0845207, 0.99198, -0.00882891, 0.0893405, 0.0980413, 0.991982, -0.0101367, 0.0893396, 0.112571, 0.992008, -0.011535, 0.0893415, 0.128115, 0.992026, -0.0130228, 0.0893414, 0.144672, 0.992064, -0.0145966, 0.0893418, 0.162241, 0.992041, -0.0162421, 0.0893359, 0.180801, 0.992086, -0.0178888, 0.0893214, 0.200302, 0.992157, -0.0190368, 0.0892401, 0.220332, 0.992181, -0.0195584, 0.0890525, 0.240144, 0.992175, -0.0227257, 0.0892153, 0.260728, 0.99221, -0.0254195, 0.089304, 0.283473, 0.99222, -0.0274883, 0.0892703, 0.307673, 0.992317, -0.0294905, 0.0892027, 0.332729, 0.992374, -0.0311861, 0.0890577, 0.358387, 0.992505, -0.0320656, 0.0886994, 0.384102, 0.992568, -0.0329715, 0.0883198, 0.409767, 0.992675, -0.036006, 0.0883602, 0.436145, 0.992746, -0.0392897, 0.0884591, 0.463217, 0.992873, -0.0399337, 0.0878287, 0.491557, 0.992934, -0.040231, 0.0870108, 0.519516, 0.993091, -0.0422013, 0.0865857, 0.547741, 0.993259, -0.0443503, 0.0861937, 0.575792, 0.993455, -0.0446368, 0.0851187, 0.604233, 0.993497, -0.0454299, 0.0840576, 0.632925, 0.993694, -0.0463296, 0.0829671, 0.660985, 0.993718, -0.0470619, 0.0817185, 0.688714, 0.993973, -0.0468838, 0.0800294, 0.716743, 0.994207, -0.046705, 0.0781286, 0.74377, 0.994168, -0.0469698, 0.0763337, 0.77042, 0.9945, -0.0456816, 0.0738184, 0.796659, 0.994356, -0.0455518, 0.0715545, 0.821868, 0.994747, -0.0439488, 0.0686085, 0.846572, 0.994937, -0.0430056, 0.065869, 0.870435, 0.995142, -0.0413414, 0.0626446, 0.893272, 0.995451, -0.0396521, 0.05929, 0.915376, 0.995445, -0.0378453, 0.0558503, 0.936196, 0.995967, -0.0355219, 0.0520949, 0.956376, 0.996094, -0.0335146, 0.048377, 0.975327, 0.996622, -0.030682, 0.0442575, 0.993471, 0.996938, -0.0285504, 0.0404693, 1.01052, 0.997383, -0.0253399, 0.0360903, 1.02637, 0.997714, -0.0231651, 0.0322176, 1.04139, 0.998249, -0.0198138, 0.0278433, 1.05542, 0.998596, -0.0174337, 0.0238759, 1.06846, 0.998946, -0.0141349, 0.0195944, 1.08056, 0.99928, -0.0115603, 0.0156279, 1.09181, 0.999507, -0.00839065, 0.0114607, 1.10213, 0.999697, -0.005666, 0.00763325, 1.11169, 0.999869, -0.00269902, 0.00364946, 1.12042, 1.00001, 0.0000623836, -0.0000319288, 1.12832, 0.987221, -0.00000222675, 0.111332, 0.0000197456, 0.98739, -0.0000561116, 0.111351, 0.000497563, 0.987448, -0.000224453, 0.111357, 0.00199031, 0.987441, -0.000505019, 0.111357, 0.0044782, 0.987442, -0.000897816, 0.111357, 0.00796129, 0.987442, -0.00140284, 0.111357, 0.0124396, 0.987444, -0.00202012, 0.111357, 0.0179132, 0.987442, -0.00274964, 0.111357, 0.0243824, 0.987446, -0.00359147, 0.111357, 0.0318474, 0.987435, -0.00454562, 0.111356, 0.0403086, 0.987461, -0.00561225, 0.111358, 0.0497678, 0.987458, -0.00679125, 0.111358, 0.0602239, 0.987443, -0.0080828, 0.111356, 0.0716792, 0.987476, -0.0094872, 0.111358, 0.0841364, 0.98749, -0.0110044, 0.111361, 0.097597, 0.987508, -0.0126344, 0.111362, 0.112062, 0.987494, -0.0143767, 0.111357, 0.127533, 0.987526, -0.0162307, 0.111359, 0.144015, 0.987558, -0.0181912, 0.111361, 0.161502, 0.987602, -0.0202393, 0.111355, 0.179979, 0.987692, -0.022273, 0.111346, 0.199386, 0.987702, -0.0235306, 0.111215, 0.219183, 0.987789, -0.0247628, 0.111061, 0.239202, 0.987776, -0.0280668, 0.111171, 0.259957, 0.987856, -0.0316751, 0.111327, 0.282198, 0.987912, -0.0342468, 0.111282, 0.306294, 0.988, -0.0367205, 0.111198, 0.331219, 0.988055, -0.0387766, 0.110994, 0.356708, 0.988241, -0.0397722, 0.110547, 0.382234, 0.988399, -0.0416076, 0.110198, 0.408227, 0.988539, -0.0448192, 0.110137, 0.434662, 0.988661, -0.0483793, 0.110143, 0.461442, 0.988967, -0.0495895, 0.109453, 0.489318, 0.989073, -0.0506797, 0.108628, 0.517516, 0.989274, -0.0526953, 0.108003, 0.545844, 0.989528, -0.054578, 0.107255, 0.573823, 0.989709, -0.0561503, 0.106294, 0.601944, 0.989991, -0.056866, 0.104896, 0.630855, 0.990392, -0.0572914, 0.103336, 0.658925, 0.990374, -0.0586224, 0.10189, 0.686661, 0.990747, -0.0584764, 0.099783, 0.714548, 0.991041, -0.0582662, 0.0974309, 0.74186, 0.991236, -0.0584118, 0.0951678, 0.768422, 0.991585, -0.0573055, 0.0921581, 0.794817, 0.991984, -0.0564241, 0.0891167, 0.820336, 0.9921, -0.0553608, 0.085805, 0.84493, 0.992749, -0.0533816, 0.0820354, 0.868961, 0.99288, -0.0518661, 0.0782181, 0.891931, 0.993511, -0.0492492, 0.0738935, 0.914186, 0.993617, -0.0471956, 0.0696402, 0.93532, 0.99411, -0.044216, 0.0649659, 0.95543, 0.994595, -0.0416654, 0.0603177, 0.974685, 0.994976, -0.0384314, 0.0553493, 0.992807, 0.995579, -0.0353491, 0.0503942, 1.00996, 0.996069, -0.0319787, 0.0452123, 1.02606, 0.996718, -0.028472, 0.0400112, 1.04114, 0.997173, -0.0250789, 0.0349456, 1.05517, 0.997818, -0.0213326, 0.029653, 1.0683, 0.998318, -0.0178509, 0.024549, 1.0805, 0.998853, -0.0141118, 0.0194197, 1.09177, 0.999218, -0.0105914, 0.0143869, 1.1022, 0.999594, -0.00693474, 0.00943517, 1.11175, 0.99975, -0.00340478, 0.00464051, 1.12056, 1.00001, 0.000109172, -0.000112821, 1.12853, 0.983383, -0.00000266524, 0.133358, 0.0000196534, 0.981942, -0.0000671009, 0.133162, 0.000494804, 0.981946, -0.000268405, 0.133163, 0.00197923, 0.981944, -0.000603912, 0.133163, 0.00445326, 0.981941, -0.00107362, 0.133162, 0.00791693, 0.981946, -0.00167755, 0.133163, 0.0123703, 0.981944, -0.00241569, 0.133162, 0.0178135, 0.981945, -0.00328807, 0.133163, 0.0242466, 0.981945, -0.00429472, 0.133162, 0.03167, 0.981955, -0.00543573, 0.133164, 0.0400846, 0.981951, -0.00671105, 0.133163, 0.0494901, 0.981968, -0.00812092, 0.133165, 0.0598886, 0.981979, -0.00966541, 0.133166, 0.0712811, 0.981996, -0.0113446, 0.133168, 0.083669, 0.982014, -0.0131585, 0.133169, 0.0970533, 0.982011, -0.0151073, 0.133167, 0.111438, 0.982062, -0.0171906, 0.133172, 0.126826, 0.9821, -0.0194067, 0.133175, 0.143215, 0.982149, -0.0217502, 0.133176, 0.160609, 0.982163, -0.0241945, 0.133173, 0.178981, 0.982247, -0.0265907, 0.133148, 0.198249, 0.982291, -0.027916, 0.132974, 0.217795, 0.982396, -0.0299663, 0.132868, 0.238042, 0.982456, -0.0334544, 0.132934, 0.258901, 0.982499, -0.0378636, 0.133137, 0.280639, 0.982617, -0.0409274, 0.133085, 0.304604, 0.98274, -0.0438523, 0.132985, 0.329376, 0.982944, -0.0462288, 0.132728, 0.354697, 0.98308, -0.0475995, 0.132228, 0.380102, 0.983391, -0.0501901, 0.131924, 0.406256, 0.983514, -0.0535899, 0.131737, 0.432735, 0.98373, -0.0571858, 0.131567, 0.459359, 0.984056, -0.0592353, 0.130932, 0.486637, 0.984234, -0.0610488, 0.130092, 0.51509, 0.984748, -0.0630758, 0.12923, 0.543461, 0.985073, -0.0647398, 0.128174, 0.571376, 0.985195, -0.0671941, 0.127133, 0.599414, 0.985734, -0.0681345, 0.125576, 0.628134, 0.986241, -0.0686089, 0.123639, 0.656399, 0.986356, -0.0698511, 0.121834, 0.684258, 0.986894, -0.0700931, 0.119454, 0.711818, 0.987382, -0.0698321, 0.116718, 0.739511, 0.988109, -0.0693975, 0.113699, 0.766267, 0.988363, -0.0689584, 0.110454, 0.792456, 0.989112, -0.0672353, 0.106602, 0.81813, 0.989241, -0.0662034, 0.10267, 0.842889, 0.990333, -0.0638938, 0.0981381, 0.867204, 0.990591, -0.0618534, 0.0935388, 0.89038, 0.991106, -0.0593117, 0.088553, 0.912576, 0.991919, -0.0562676, 0.0832187, 0.934118, 0.992111, -0.0534085, 0.0778302, 0.954254, 0.992997, -0.0495459, 0.0720453, 0.973722, 0.993317, -0.0463707, 0.0663458, 0.991949, 0.994133, -0.0421245, 0.0601883, 1.00936, 0.994705, -0.0384977, 0.0542501, 1.02559, 0.995495, -0.0340956, 0.0479862, 1.04083, 0.996206, -0.030105, 0.041887, 1.05497, 0.996971, -0.0256095, 0.0355355, 1.06824, 0.997796, -0.0213932, 0.0293655, 1.08056, 0.998272, -0.0169612, 0.0232926, 1.09182, 0.998857, -0.0126756, 0.0172786, 1.10219, 0.99939, -0.00832486, 0.0113156, 1.11192, 0.999752, -0.00410826, 0.00557892, 1.12075, 1, 0.000150957, -0.000119101, 1.12885, 0.975169, -0.00000309397, 0.154669, 0.0000195073, 0.975439, -0.0000779608, 0.154712, 0.000491534, 0.975464, -0.000311847, 0.154716, 0.00196617, 0.975464, -0.000701656, 0.154716, 0.00442387, 0.975462, -0.0012474, 0.154715, 0.0078647, 0.975461, -0.00194906, 0.154715, 0.0122886, 0.975464, -0.00280667, 0.154715, 0.0176959, 0.975468, -0.00382025, 0.154716, 0.0240867, 0.975471, -0.00498985, 0.154716, 0.0314612, 0.975472, -0.00631541, 0.154717, 0.0398199, 0.975486, -0.00779719, 0.154718, 0.0491639, 0.975489, -0.00943505, 0.154718, 0.0594932, 0.975509, -0.0112295, 0.154721, 0.0708113, 0.97554, -0.0131802, 0.154724, 0.0831176, 0.975557, -0.0152876, 0.154726, 0.096415, 0.975585, -0.0175512, 0.154728, 0.110705, 0.975605, -0.0199713, 0.154729, 0.125992, 0.975645, -0.0225447, 0.154729, 0.142272, 0.975711, -0.0252649, 0.154735, 0.159549, 0.975788, -0.0280986, 0.154736, 0.177805, 0.975872, -0.0308232, 0.154704, 0.196911, 0.975968, -0.0324841, 0.154525, 0.216324, 0.976063, -0.0351281, 0.154432, 0.236628, 0.976157, -0.0388618, 0.15446, 0.257539, 0.976204, -0.0437704, 0.154665, 0.278975, 0.976358, -0.047514, 0.154652, 0.302606, 0.976571, -0.0508638, 0.154535, 0.327204, 0.976725, -0.0534995, 0.154221, 0.352276, 0.977013, -0.0555547, 0.153737, 0.377696, 0.977294, -0.0586728, 0.153403, 0.403855, 0.977602, -0.0622715, 0.15312, 0.430333, 0.977932, -0.0658166, 0.152755, 0.456855, 0.978241, -0.0689877, 0.152233, 0.483668, 0.978602, -0.0712805, 0.15132, 0.512097, 0.979234, -0.0732775, 0.150235, 0.540455, 0.97977, -0.075163, 0.148978, 0.568486, 0.979995, -0.0778026, 0.147755, 0.596524, 0.98078, -0.0791854, 0.146019, 0.624825, 0.981628, -0.0799666, 0.143906, 0.653403, 0.982067, -0.0808532, 0.141561, 0.681445, 0.98271, -0.0816024, 0.139025, 0.708918, 0.983734, -0.0812511, 0.135764, 0.736594, 0.98431, -0.0806201, 0.132152, 0.763576, 0.985071, -0.0801605, 0.12846, 0.789797, 0.98618, -0.0784208, 0.124084, 0.815804, 0.986886, -0.0766643, 0.1193, 0.840869, 0.987485, -0.0747744, 0.114236, 0.864952, 0.988431, -0.0716701, 0.108654, 0.888431, 0.988886, -0.0691609, 0.102994, 0.910963, 0.990024, -0.0654048, 0.0967278, 0.932629, 0.990401, -0.0619765, 0.090384, 0.95313, 0.991093, -0.0579296, 0.0837885, 0.972587, 0.992018, -0.0536576, 0.0770171, 0.991184, 0.992536, -0.0493719, 0.0701486, 1.00863, 0.993421, -0.0444813, 0.062953, 1.02494, 0.993928, -0.040008, 0.0560455, 1.04017, 0.994994, -0.0347982, 0.04856, 1.05463, 0.995866, -0.0301017, 0.0416152, 1.06807, 0.996916, -0.0248225, 0.0342597, 1.08039, 0.997766, -0.0199229, 0.0271668, 1.09177, 0.998479, -0.0147422, 0.0201387, 1.10235, 0.99921, -0.00980173, 0.0131944, 1.11206, 0.999652, -0.0047426, 0.00640712, 1.12104, 0.999998, 0.0000891673, -0.00010379, 1.12906, 0.967868, -0.00000351885, 0.175947, 0.0000193569, 0.968001, -0.0000886733, 0.175972, 0.000487782, 0.96801, -0.000354697, 0.175973, 0.00195115, 0.968012, -0.000798063, 0.175974, 0.00439006, 0.968011, -0.00141879, 0.175973, 0.00780461, 0.968011, -0.00221686, 0.175973, 0.0121948, 0.968016, -0.00319231, 0.175974, 0.0175607, 0.968019, -0.00434515, 0.175974, 0.0239027, 0.968018, -0.00567538, 0.175974, 0.0312208, 0.968033, -0.00718308, 0.175977, 0.0395158, 0.968049, -0.00886836, 0.175979, 0.0487885, 0.968047, -0.0107312, 0.175978, 0.0590394, 0.968072, -0.0127719, 0.175981, 0.0702705, 0.968108, -0.0149905, 0.175986, 0.0824836, 0.968112, -0.0173866, 0.175985, 0.0956783, 0.968173, -0.0199611, 0.175993, 0.109862, 0.96827, -0.0227128, 0.176008, 0.125033, 0.968292, -0.025639, 0.17601, 0.141193, 0.968339, -0.0287299, 0.176007, 0.158336, 0.968389, -0.0319399, 0.176001, 0.176441, 0.968501, -0.034941, 0.175962, 0.195359, 0.968646, -0.0370812, 0.175793, 0.214686, 0.968789, -0.0402329, 0.175708, 0.234973, 0.96886, -0.0442601, 0.1757, 0.255871, 0.969013, -0.049398, 0.175876, 0.277238, 0.969242, -0.0539932, 0.17594, 0.300326, 0.969419, -0.0577299, 0.175781, 0.324702, 0.969763, -0.0605643, 0.175432, 0.349527, 0.970093, -0.0634488, 0.174992, 0.374976, 0.970361, -0.0670589, 0.174611, 0.401097, 0.970825, -0.0708246, 0.174226, 0.427496, 0.971214, -0.0742871, 0.173684, 0.453858, 0.971622, -0.0782608, 0.173186, 0.480637, 0.972175, -0.0813151, 0.172288, 0.508655, 0.972944, -0.0832678, 0.170979, 0.536973, 0.973595, -0.0855964, 0.169573, 0.565138, 0.974345, -0.0882163, 0.168152, 0.593222, 0.975233, -0.0901671, 0.166314, 0.621201, 0.976239, -0.0912111, 0.163931, 0.649919, 0.977289, -0.0916959, 0.161106, 0.678011, 0.978076, -0.0927061, 0.158272, 0.705717, 0.979533, -0.0925562, 0.15475, 0.733228, 0.980335, -0.0918159, 0.150638, 0.760454, 0.981808, -0.0908508, 0.146201, 0.786918, 0.983061, -0.0896172, 0.141386, 0.812953, 0.984148, -0.0871588, 0.135837, 0.838281, 0.985047, -0.0850624, 0.130135, 0.862594, 0.986219, -0.0818541, 0.123882, 0.88633, 0.987043, -0.0784523, 0.117126, 0.908952, 0.988107, -0.0749601, 0.110341, 0.930744, 0.988955, -0.0703548, 0.102885, 0.951728, 0.989426, -0.0662798, 0.0954167, 0.971166, 0.990421, -0.0610834, 0.0876331, 0.989984, 0.991032, -0.0562936, 0.0797785, 1.00765, 0.992041, -0.0508154, 0.0718166, 1.02434, 0.992794, -0.0454045, 0.0637125, 1.03976, 0.993691, -0.0398194, 0.0555338, 1.05418, 0.994778, -0.0341482, 0.0473388, 1.06772, 0.995915, -0.028428, 0.0391016, 1.08028, 0.997109, -0.022642, 0.0309953, 1.09185, 0.998095, -0.0168738, 0.0230288, 1.10247, 0.998985, -0.0111274, 0.0150722, 1.11229, 0.999581, -0.00543881, 0.00740605, 1.12131, 1.00003, 0.000162239, -0.000105549, 1.12946, 0.959505, -0.00000393734, 0.196876, 0.0000191893, 0.959599, -0.0000992157, 0.196895, 0.000483544, 0.959641, -0.000396868, 0.196903, 0.0019342, 0.959599, -0.000892948, 0.196895, 0.00435193, 0.959603, -0.00158747, 0.196896, 0.0077368, 0.959604, -0.00248042, 0.196896, 0.0120888, 0.959605, -0.00357184, 0.196896, 0.0174082, 0.959605, -0.00486169, 0.196896, 0.0236949, 0.959613, -0.00635008, 0.196897, 0.0309497, 0.959619, -0.00803696, 0.196898, 0.0391725, 0.959636, -0.00992255, 0.196901, 0.0483649, 0.959634, -0.0120067, 0.1969, 0.0585266, 0.959675, -0.0142898, 0.196906, 0.0696609, 0.959712, -0.0167717, 0.196911, 0.0817678, 0.959752, -0.0194524, 0.196918, 0.0948494, 0.959807, -0.0223321, 0.196925, 0.10891, 0.959828, -0.0254091, 0.196924, 0.123947, 0.959906, -0.0286815, 0.196934, 0.139968, 0.960005, -0.0321371, 0.196944, 0.156968, 0.960071, -0.0357114, 0.196936, 0.17491, 0.960237, -0.0389064, 0.196882, 0.193597, 0.960367, -0.041623, 0.196731, 0.21285, 0.960562, -0.0452655, 0.196654, 0.233075, 0.960735, -0.0496207, 0.196643, 0.253941, 0.960913, -0.0549379, 0.196774, 0.275278, 0.961121, -0.0603414, 0.196893, 0.297733, 0.96139, -0.0644244, 0.196717, 0.321877, 0.961818, -0.067556, 0.196314, 0.346476, 0.962175, -0.0712709, 0.195917, 0.371907, 0.96255, -0.0752848, 0.1955, 0.397916, 0.963164, -0.0792073, 0.195026, 0.424229, 0.963782, -0.0828225, 0.194424, 0.450637, 0.964306, -0.0873119, 0.193831, 0.477288, 0.964923, -0.0911051, 0.192973, 0.504716, 0.966048, -0.093251, 0.19151, 0.533053, 0.967024, -0.0958983, 0.190013, 0.561366, 0.968038, -0.09835, 0.188253, 0.589464, 0.969152, -0.100754, 0.186257, 0.617433, 0.970557, -0.102239, 0.183775, 0.645801, 0.972104, -0.102767, 0.180645, 0.674278, 0.973203, -0.103492, 0.177242, 0.702004, 0.975123, -0.103793, 0.17345, 0.729529, 0.97641, -0.102839, 0.168886, 0.756712, 0.978313, -0.101687, 0.163892, 0.783801, 0.980036, -0.100314, 0.158439, 0.809671, 0.981339, -0.097836, 0.152211, 0.835402, 0.982794, -0.0950006, 0.145679, 0.860081, 0.984123, -0.0920994, 0.138949, 0.883757, 0.984918, -0.0878641, 0.131283, 0.90685, 0.985999, -0.083939, 0.123464, 0.928786, 0.987151, -0.0791234, 0.115324, 0.94983, 0.987827, -0.0739332, 0.106854, 0.96962, 0.988806, -0.0688088, 0.0982691, 0.98861, 0.989588, -0.0628962, 0.0893456, 1.00667, 0.990438, -0.0573146, 0.0805392, 1.02344, 0.991506, -0.0509433, 0.0713725, 1.03933, 0.992492, -0.0448724, 0.0623732, 1.05378, 0.993663, -0.0383497, 0.0530838, 1.06747, 0.994956, -0.0319593, 0.0439512, 1.08007, 0.99634, -0.025401, 0.0347803, 1.09182, 0.99761, -0.0189687, 0.0257954, 1.1025, 0.99863, -0.0124441, 0.0169893, 1.11247, 0.99947, -0.00614003, 0.00829498, 1.12151, 1.00008, 0.000216624, -0.000146107, 1.12993, 0.950129, -0.00000434955, 0.217413, 0.0000190081, 0.950264, -0.00010957, 0.217444, 0.00047884, 0.9503, -0.000438299, 0.217451, 0.00191543, 0.950246, -0.000986124, 0.21744, 0.00430951, 0.950246, -0.00175311, 0.21744, 0.00766137, 0.950245, -0.00273923, 0.21744, 0.011971, 0.950253, -0.00394453, 0.217441, 0.0172385, 0.950258, -0.00536897, 0.217442, 0.0234641, 0.950267, -0.00701262, 0.217444, 0.030648, 0.950277, -0.00887551, 0.217446, 0.038791, 0.950284, -0.0109576, 0.217446, 0.0478931, 0.950312, -0.0132591, 0.217451, 0.0579568, 0.950334, -0.01578, 0.217454, 0.0689821, 0.950378, -0.0185204, 0.217462, 0.0809714, 0.950417, -0.0214803, 0.217467, 0.0939265, 0.950488, -0.0246594, 0.217479, 0.10785, 0.950534, -0.0280565, 0.217483, 0.122743, 0.950633, -0.0316685, 0.217498, 0.138611, 0.950698, -0.0354787, 0.217499, 0.155442, 0.950844, -0.0394003, 0.217507, 0.173208, 0.950999, -0.0426812, 0.217419, 0.191605, 0.951221, -0.0461302, 0.217317, 0.21084, 0.951412, -0.0502131, 0.217238, 0.230945, 0.951623, -0.0549183, 0.21722, 0.251745, 0.951867, -0.0604493, 0.217306, 0.273001, 0.952069, -0.0665189, 0.217466, 0.294874, 0.952459, -0.0709179, 0.217266, 0.318732, 0.952996, -0.0746112, 0.216891, 0.34318, 0.953425, -0.0789252, 0.216503, 0.36849, 0.953885, -0.0833293, 0.216042, 0.394373, 0.954617, -0.087371, 0.215469, 0.420505, 0.955429, -0.0914054, 0.214802, 0.446907, 0.956068, -0.0961671, 0.214146, 0.473522, 0.957094, -0.10048, 0.213286, 0.50052, 0.958372, -0.103248, 0.211796, 0.528715, 0.959654, -0.106033, 0.21016, 0.557065, 0.961305, -0.108384, 0.208149, 0.585286, 0.962785, -0.111122, 0.206024, 0.613334, 0.964848, -0.112981, 0.203442, 0.641334, 0.966498, -0.113717, 0.19996, 0.669955, 0.968678, -0.114121, 0.196105, 0.698094, 0.970489, -0.114524, 0.191906, 0.725643, 0.972903, -0.113792, 0.186963, 0.752856, 0.974701, -0.112406, 0.181343, 0.780013, 0.976718, -0.110685, 0.175185, 0.806268, 0.978905, -0.108468, 0.168535, 0.832073, 0.980267, -0.105061, 0.161106, 0.857149, 0.981967, -0.101675, 0.153387, 0.881145, 0.983063, -0.0974492, 0.145199, 0.904255, 0.984432, -0.0925815, 0.136527, 0.926686, 0.985734, -0.0877983, 0.127584, 0.947901, 0.986228, -0.081884, 0.118125, 0.968111, 0.98719, -0.0761208, 0.108594, 0.98719, 0.988228, -0.0698196, 0.0989996, 1.00559, 0.989046, -0.0632739, 0.0890074, 1.02246, 0.990242, -0.056522, 0.0790832, 1.03841, 0.991252, -0.0495272, 0.0689182, 1.05347, 0.992542, -0.0425373, 0.0588592, 1.06724, 0.994096, -0.0353198, 0.0486833, 1.08009, 0.995593, -0.028235, 0.0385977, 1.09177, 0.99711, -0.0209511, 0.0286457, 1.10274, 0.998263, -0.0139289, 0.0188497, 1.11262, 0.999254, -0.0067359, 0.009208, 1.12191, 0.999967, 0.000141846, -0.0000657764, 1.13024, 0.935608, -0.00000474692, 0.236466, 0.0000187817, 0.93996, -0.00011971, 0.237568, 0.000473646, 0.939959, -0.000478845, 0.237567, 0.0018946, 0.939954, -0.0010774, 0.237566, 0.00426284, 0.939956, -0.00191538, 0.237566, 0.00757842, 0.939954, -0.00299277, 0.237566, 0.0118413, 0.93996, -0.00430961, 0.237567, 0.0170518, 0.939969, -0.00586589, 0.237569, 0.02321, 0.939982, -0.00766166, 0.237572, 0.0303164, 0.939987, -0.00969686, 0.237572, 0.0383711, 0.939997, -0.0119715, 0.237574, 0.0473751, 0.940031, -0.0144858, 0.237581, 0.0573298, 0.940073, -0.0172399, 0.237589, 0.0682366, 0.94012, -0.0202335, 0.237598, 0.080097, 0.940162, -0.0234663, 0.237604, 0.0929116, 0.940237, -0.0269387, 0.237615, 0.106686, 0.940328, -0.0306489, 0.237632, 0.121421, 0.940419, -0.0345917, 0.237645, 0.137115, 0.940522, -0.0387481, 0.237654, 0.153766, 0.940702, -0.0429906, 0.237661, 0.17133, 0.940871, -0.0465089, 0.237561, 0.189502, 0.941103, -0.050531, 0.23748, 0.208616, 0.941369, -0.0550657, 0.237423, 0.228595, 0.941641, -0.0601337, 0.237399, 0.249287, 0.941903, -0.0658804, 0.237443, 0.270467, 0.942224, -0.0722674, 0.237597, 0.292024, 0.942633, -0.0771788, 0.237419, 0.315272, 0.943172, -0.0815623, 0.237068, 0.339579, 0.943691, -0.0863973, 0.236682, 0.364717, 0.944382, -0.0911536, 0.236213, 0.390435, 0.945392, -0.0952967, 0.235562, 0.416425, 0.946185, -0.0998948, 0.234832, 0.442772, 0.947212, -0.104796, 0.234114, 0.469347, 0.948778, -0.10928, 0.233222, 0.496162, 0.950149, -0.113081, 0.231845, 0.523978, 0.951989, -0.115893, 0.230005, 0.552295, 0.953921, -0.11846, 0.227862, 0.580569, 0.955624, -0.12115, 0.225439, 0.608698, 0.958234, -0.123373, 0.222635, 0.636696, 0.960593, -0.124519, 0.219093, 0.665208, 0.963201, -0.124736, 0.214749, 0.693557, 0.965642, -0.125012, 0.210059, 0.721334, 0.968765, -0.124661, 0.204935, 0.748613, 0.971753, -0.122996, 0.198661, 0.776224, 0.973751, -0.120998, 0.191823, 0.802461, 0.976709, -0.118583, 0.184359, 0.828399, 0.977956, -0.115102, 0.176437, 0.853693, 0.979672, -0.111077, 0.167681, 0.877962, 0.981816, -0.10688, 0.158872, 0.901564, 0.98238, -0.101469, 0.149398, 0.924057, 0.983964, -0.0960013, 0.139436, 0.945751, 0.984933, -0.0899626, 0.12943, 0.966272, 0.985694, -0.0832973, 0.11894, 0.985741, 0.986822, -0.0767082, 0.108349, 1.00407, 0.987725, -0.0693614, 0.0976026, 1.02154, 0.98877, -0.06211, 0.086652, 1.03757, 0.990129, -0.0544143, 0.0756182, 1.05296, 0.991337, -0.046744, 0.0645753, 1.06683, 0.992978, -0.0387931, 0.0534683, 1.0798, 0.994676, -0.030973, 0.0424137, 1.09181, 0.99645, -0.0230311, 0.0314035, 1.10286, 0.997967, -0.0152065, 0.0206869, 1.11291, 0.99922, -0.00744837, 0.010155, 1.12237, 1.00002, 0.000240209, -0.0000752767, 1.13089, 0.922948, -0.00000515351, 0.255626, 0.0000186069, 0.928785, -0.000129623, 0.257244, 0.000468009, 0.928761, -0.00051849, 0.257237, 0.00187202, 0.928751, -0.0011666, 0.257235, 0.00421204, 0.928751, -0.00207395, 0.257234, 0.0074881, 0.928754, -0.00324055, 0.257235, 0.0117002, 0.92876, -0.00466639, 0.257236, 0.0168486, 0.928763, -0.00635149, 0.257237, 0.0229334, 0.928774, -0.00829584, 0.257239, 0.029955, 0.928791, -0.0104995, 0.257243, 0.0379139, 0.928804, -0.0129623, 0.257245, 0.0468108, 0.928847, -0.0156846, 0.257255, 0.0566473, 0.92889, -0.0186661, 0.257263, 0.0674246, 0.928924, -0.0219067, 0.257268, 0.0791433, 0.928989, -0.0254066, 0.257282, 0.0918076, 0.92909, -0.0291651, 0.257301, 0.105419, 0.92918, -0.0331801, 0.257316, 0.119978, 0.92929, -0.0374469, 0.257332, 0.135491, 0.929453, -0.041939, 0.257357, 0.151948, 0.929586, -0.0464612, 0.257347, 0.169275, 0.929858, -0.0503426, 0.257269, 0.187257, 0.930125, -0.0548409, 0.257199, 0.206204, 0.930403, -0.0598063, 0.257149, 0.22601, 0.930726, -0.0652437, 0.257122, 0.246561, 0.931098, -0.0712376, 0.257153, 0.267618, 0.931396, -0.0777506, 0.257237, 0.288993, 0.931947, -0.0832374, 0.257124, 0.311527, 0.932579, -0.0883955, 0.25683, 0.335697, 0.933194, -0.0937037, 0.256444, 0.360634, 0.934013, -0.0987292, 0.255939, 0.386126, 0.935307, -0.103215, 0.255282, 0.412018, 0.936374, -0.108234, 0.254538, 0.438292, 0.93776, -0.113234, 0.253728, 0.464805, 0.939599, -0.118013, 0.25275, 0.491464, 0.941036, -0.122661, 0.251404, 0.518751, 0.94337, -0.125477, 0.249435, 0.547133, 0.945318, -0.128374, 0.247113, 0.575456, 0.947995, -0.130996, 0.244441, 0.60372, 0.950818, -0.133438, 0.241352, 0.63174, 0.954378, -0.135004, 0.237849, 0.659971, 0.957151, -0.135313, 0.233188, 0.688478, 0.960743, -0.13521, 0.228001, 0.716767, 0.964352, -0.135007, 0.222249, 0.744349, 0.967273, -0.133523, 0.21542, 0.771786, 0.969767, -0.131155, 0.208039, 0.798639, 0.973195, -0.128492, 0.200076, 0.824774, 0.975557, -0.125094, 0.191451, 0.850222, 0.977692, -0.120578, 0.18184, 0.874761, 0.98026, -0.115882, 0.172102, 0.898497, 0.981394, -0.110372, 0.161859, 0.921636, 0.982386, -0.10415, 0.15108, 0.943467, 0.983783, -0.0978128, 0.140407, 0.964045, 0.98422, -0.0906171, 0.129058, 0.98398, 0.985447, -0.0832921, 0.117614, 1.00276, 0.986682, -0.0754412, 0.10585, 1.02047, 0.987326, -0.0673885, 0.0940943, 1.03678, 0.988707, -0.0592565, 0.0822093, 1.05218, 0.990185, -0.050717, 0.070192, 1.06652, 0.991866, -0.0423486, 0.0582081, 1.07965, 0.993897, -0.0336118, 0.0460985, 1.09188, 0.995841, -0.0252178, 0.0342737, 1.10307, 0.997605, -0.0164893, 0.0224829, 1.11324, 0.999037, -0.00817112, 0.0110647, 1.12262, 1.00003, 0.000291686, -0.000168673, 1.13139, 0.915304, -0.00000552675, 0.275999, 0.0000183285, 0.91668, -0.000139285, 0.276414, 0.000461914, 0.916664, -0.00055713, 0.276409, 0.00184763, 0.916653, -0.00125354, 0.276406, 0.00415715, 0.916651, -0.00222851, 0.276405, 0.00739053, 0.916655, -0.00348205, 0.276406, 0.0115478, 0.916653, -0.00501414, 0.276405, 0.0166291, 0.916667, -0.00682478, 0.276409, 0.0226346, 0.91668, -0.00891398, 0.276412, 0.0295648, 0.91669, -0.0112817, 0.276413, 0.0374199, 0.916727, -0.013928, 0.276422, 0.0462016, 0.916759, -0.0168528, 0.276429, 0.0559101, 0.916793, -0.0200558, 0.276436, 0.0665466, 0.916849, -0.0235373, 0.276448, 0.0781139, 0.916964, -0.0272973, 0.276474, 0.0906156, 0.917047, -0.0313344, 0.276491, 0.104051, 0.917152, -0.0356465, 0.276511, 0.118424, 0.917286, -0.0402271, 0.276533, 0.133736, 0.917469, -0.0450408, 0.276564, 0.149978, 0.917686, -0.0497872, 0.276563, 0.167057, 0.917953, -0.0540937, 0.276493, 0.184846, 0.918228, -0.0590709, 0.276437, 0.203614, 0.918572, -0.0644277, 0.276398, 0.223212, 0.918918, -0.0702326, 0.276362, 0.243584, 0.919356, -0.076484, 0.276383, 0.264465, 0.919842, -0.0830808, 0.276434, 0.285701, 0.920451, -0.0892972, 0.276407, 0.307559, 0.921113, -0.095016, 0.276128, 0.331501, 0.921881, -0.100771, 0.275754, 0.356207, 0.923027, -0.106029, 0.275254, 0.381477, 0.924364, -0.111029, 0.274595, 0.40722, 0.925818, -0.116345, 0.273841, 0.433385, 0.92746, -0.121424, 0.272913, 0.459848, 0.929167, -0.12657, 0.271837, 0.486493, 0.931426, -0.131581, 0.270575, 0.513432, 0.934001, -0.135038, 0.268512, 0.541502, 0.936296, -0.138039, 0.266135, 0.569658, 0.939985, -0.140687, 0.263271, 0.598375, 0.943516, -0.143247, 0.260058, 0.626563, 0.94782, -0.145135, 0.256138, 0.654711, 0.951023, -0.145733, 0.251154, 0.683285, 0.955338, -0.145554, 0.245562, 0.711831, 0.959629, -0.145008, 0.239265, 0.739573, 0.963123, -0.144003, 0.232064, 0.767027, 0.966742, -0.141289, 0.224036, 0.794359, 0.969991, -0.138247, 0.215305, 0.820361, 0.973403, -0.134786, 0.206051, 0.846548, 0.975317, -0.129966, 0.195914, 0.871541, 0.977647, -0.12471, 0.185184, 0.895313, 0.980137, -0.119086, 0.174161, 0.918398, 0.981031, -0.112297, 0.162792, 0.940679, 0.982037, -0.105372, 0.150952, 0.961991, 0.983164, -0.097821, 0.138921, 0.981913, 0.983757, -0.0897245, 0.126611, 1.00109, 0.985036, -0.0815974, 0.114228, 1.01902, 0.986289, -0.0727725, 0.101389, 1.03604, 0.987329, -0.0639323, 0.0886476, 1.05149, 0.989193, -0.0548109, 0.0756837, 1.06619, 0.990716, -0.045687, 0.0627581, 1.07948, 0.992769, -0.0364315, 0.0498337, 1.09172, 0.99524, -0.0271761, 0.0370305, 1.1033, 0.997154, -0.0179609, 0.0243959, 1.11353, 0.998845, -0.00878063, 0.0119567, 1.12319, 1.00002, 0.000259038, -0.000108146, 1.13177, 0.903945, -0.00000591681, 0.295126, 0.0000181226, 0.903668, -0.000148672, 0.295037, 0.000455367, 0.903677, -0.000594683, 0.29504, 0.00182145, 0.903673, -0.00133805, 0.295039, 0.00409831, 0.903666, -0.00237872, 0.295036, 0.00728584, 0.903668, -0.00371676, 0.295037, 0.0113842, 0.903679, -0.00535212, 0.29504, 0.0163936, 0.903684, -0.00728479, 0.295041, 0.0223141, 0.903698, -0.00951473, 0.295044, 0.0291462, 0.903718, -0.0120419, 0.295049, 0.0368904, 0.903754, -0.0148664, 0.295058, 0.0455477, 0.903801, -0.017988, 0.29507, 0.0551194, 0.903851, -0.0214064, 0.295082, 0.0656058, 0.903921, -0.0251219, 0.295097, 0.0770109, 0.904002, -0.0291337, 0.295116, 0.0893354, 0.904111, -0.033441, 0.29514, 0.102583, 0.904246, -0.0380415, 0.295169, 0.116755, 0.904408, -0.0429258, 0.295202, 0.131853, 0.904637, -0.0480468, 0.295245, 0.147869, 0.904821, -0.0529208, 0.295214, 0.164658, 0.905163, -0.0577748, 0.295185, 0.182274, 0.905469, -0.0631763, 0.295143, 0.200828, 0.905851, -0.068917, 0.295112, 0.2202, 0.906322, -0.0750861, 0.295104, 0.240372, 0.906761, -0.0815855, 0.295086, 0.261082, 0.90735, -0.0882138, 0.295095, 0.282123, 0.908087, -0.095082, 0.295139, 0.303563, 0.908826, -0.101488, 0.29492, 0.327028, 0.909832, -0.107577, 0.294577, 0.351464, 0.911393, -0.113033, 0.294115, 0.376497, 0.912804, -0.118629, 0.293446, 0.402115, 0.914081, -0.124232, 0.292581, 0.428111, 0.91637, -0.129399, 0.29166, 0.454442, 0.91814, -0.134892, 0.290422, 0.481024, 0.921179, -0.140069, 0.289194, 0.507924, 0.924544, -0.144431, 0.287421, 0.535557, 0.927995, -0.147498, 0.284867, 0.563984, 0.931556, -0.150197, 0.281722, 0.5923, 0.935777, -0.152711, 0.278207, 0.620832, 0.940869, -0.154836, 0.274148, 0.649069, 0.945994, -0.155912, 0.269057, 0.677746, 0.949634, -0.155641, 0.262799, 0.706293, 0.955032, -0.154809, 0.256097, 0.734278, 0.95917, -0.153678, 0.248618, 0.761751, 0.962931, -0.151253, 0.239794, 0.789032, 0.966045, -0.147625, 0.230281, 0.815422, 0.96971, -0.143964, 0.220382, 0.841787, 0.972747, -0.139464, 0.209846, 0.867446, 0.975545, -0.133459, 0.198189, 0.892004, 0.978381, -0.127424, 0.186362, 0.915458, 0.979935, -0.120506, 0.173964, 0.937948, 0.980948, -0.11282, 0.161429, 0.959732, 0.982234, -0.104941, 0.148557, 0.980118, 0.982767, -0.0962905, 0.135508, 0.999463, 0.983544, -0.0873625, 0.122338, 1.01756, 0.984965, -0.0783447, 0.108669, 1.03492, 0.986233, -0.0684798, 0.0949911, 1.05087, 0.987796, -0.0590867, 0.0811386, 1.0656, 0.989885, -0.0489145, 0.0673099, 1.0794, 0.991821, -0.0391, 0.0535665, 1.09174, 0.99448, -0.029087, 0.0397529, 1.10341, 0.996769, -0.019114, 0.0261463, 1.11383, 0.998641, -0.00947007, 0.0128731, 1.1237, 0.999978, 0.000446316, -0.000169093, 1.13253, 0.888362, -0.00000627064, 0.312578, 0.0000178215, 0.889988, -0.000157791, 0.313148, 0.000448451, 0.889825, -0.000631076, 0.313092, 0.00179356, 0.88984, -0.00141994, 0.313097, 0.00403554, 0.889828, -0.0025243, 0.313092, 0.00717429, 0.889831, -0.00394421, 0.313093, 0.0112099, 0.889831, -0.00567962, 0.313093, 0.0161425, 0.889844, -0.00773051, 0.313096, 0.0219724, 0.889858, -0.0100968, 0.3131, 0.0286999, 0.889882, -0.0127786, 0.313106, 0.0363256, 0.889918, -0.0157757, 0.313116, 0.0448509, 0.889967, -0.0190878, 0.313129, 0.0542758, 0.89003, -0.022715, 0.313145, 0.0646032, 0.890108, -0.0266566, 0.313165, 0.0758339, 0.890218, -0.0309131, 0.313193, 0.0879729, 0.890351, -0.0354819, 0.313226, 0.101019, 0.89051, -0.0403613, 0.313263, 0.114979, 0.890672, -0.0455385, 0.313294, 0.129848, 0.890882, -0.0509444, 0.313333, 0.145616, 0.891189, -0.0559657, 0.313324, 0.162122, 0.891457, -0.0613123, 0.313281, 0.179524, 0.891856, -0.0671488, 0.313281, 0.197855, 0.892312, -0.0732732, 0.313268, 0.216991, 0.892819, -0.0797865, 0.313263, 0.236924, 0.893369, -0.0865269, 0.313247, 0.257433, 0.894045, -0.0931592, 0.313205, 0.278215, 0.894884, -0.100532, 0.313276, 0.299467, 0.895832, -0.107716, 0.313205, 0.322276, 0.897043, -0.114099, 0.312873, 0.34642, 0.898515, -0.119941, 0.312331, 0.371187, 0.900191, -0.126044, 0.311731, 0.396656, 0.90188, -0.131808, 0.310859, 0.422488, 0.904359, -0.137289, 0.309857, 0.448744, 0.906923, -0.142991, 0.308714, 0.475239, 0.910634, -0.148253, 0.307465, 0.501983, 0.914502, -0.153332, 0.305774, 0.529254, 0.919046, -0.156646, 0.303156, 0.557709, 0.923194, -0.159612, 0.299928, 0.586267, 0.928858, -0.162027, 0.296245, 0.614925, 0.934464, -0.164203, 0.291832, 0.643187, 0.939824, -0.165602, 0.286565, 0.671601, 0.944582, -0.165383, 0.280073, 0.700213, 0.949257, -0.164439, 0.272891, 0.728432, 0.954389, -0.162953, 0.264771, 0.756082, 0.958595, -0.161007, 0.255927, 0.78369, 0.962138, -0.157243, 0.245769, 0.810769, 0.966979, -0.152872, 0.235127, 0.836999, 0.969566, -0.148209, 0.22347, 0.862684, 0.972372, -0.142211, 0.211147, 0.887847, 0.975916, -0.135458, 0.198606, 0.911843, 0.978026, -0.128398, 0.185498, 0.934795, 0.979686, -0.120313, 0.17171, 0.956787, 0.980748, -0.11166, 0.158159, 0.978046, 0.981622, -0.103035, 0.144399, 0.997693, 0.982356, -0.0930328, 0.13001, 1.01642, 0.983308, -0.0834627, 0.115778, 1.03366, 0.985037, -0.0732249, 0.101327, 1.05014, 0.986493, -0.0628145, 0.086554, 1.06507, 0.988484, -0.0526556, 0.0720413, 1.07907, 0.991051, -0.0415744, 0.0571151, 1.09189, 0.993523, -0.0314275, 0.0426643, 1.10369, 0.99628, -0.0203603, 0.0279325, 1.11423, 0.998344, -0.0102446, 0.0138182, 1.12421, 0.999997, 0.00042612, -0.000193628, 1.1333, 0.871555, -0.00000660007, 0.329176, 0.0000174749, 0.875255, -0.000166579, 0.330571, 0.000441051, 0.875644, -0.000666394, 0.330718, 0.00176441, 0.875159, -0.00149903, 0.330536, 0.00396899, 0.87516, -0.00266493, 0.330536, 0.007056, 0.875158, -0.00416393, 0.330535, 0.0110251, 0.87516, -0.00599598, 0.330535, 0.0158764, 0.875163, -0.00816108, 0.330536, 0.0216101, 0.875174, -0.0106591, 0.330538, 0.0282266, 0.875199, -0.0134899, 0.330545, 0.0357266, 0.875257, -0.0166538, 0.330563, 0.0441117, 0.875304, -0.0201501, 0.330575, 0.0533821, 0.875373, -0.0239785, 0.330595, 0.0635395, 0.875464, -0.0281389, 0.330619, 0.0745872, 0.875565, -0.0326301, 0.330645, 0.0865255, 0.875691, -0.0374516, 0.330676, 0.0993599, 0.875897, -0.0425993, 0.330733, 0.113093, 0.876091, -0.0480576, 0.330776, 0.127722, 0.876353, -0.0537216, 0.330826, 0.143227, 0.876649, -0.0589807, 0.330809, 0.159462, 0.877034, -0.0647865, 0.330819, 0.176642, 0.877443, -0.0709789, 0.330817, 0.194702, 0.877956, -0.0774782, 0.330832, 0.213577, 0.878499, -0.0843175, 0.330822, 0.233246, 0.879144, -0.0912714, 0.330804, 0.253512, 0.879982, -0.0980824, 0.330766, 0.274137, 0.88097, -0.105823, 0.330864, 0.295209, 0.882051, -0.113671, 0.330896, 0.317226, 0.883397, -0.120303, 0.330545, 0.341068, 0.884987, -0.12667, 0.330068, 0.365613, 0.886789, -0.133118, 0.329418, 0.390807, 0.889311, -0.139024, 0.328683, 0.416494, 0.891995, -0.144971, 0.327729, 0.442618, 0.895106, -0.150747, 0.326521, 0.469131, 0.899527, -0.156283, 0.325229, 0.495921, 0.90504, -0.161707, 0.32378, 0.523162, 0.909875, -0.165661, 0.32122, 0.55092, 0.91561, -0.168755, 0.317942, 0.579928, 0.921225, -0.171193, 0.313983, 0.608539, 0.927308, -0.17319, 0.309636, 0.636854, 0.933077, -0.174819, 0.304262, 0.66523, 0.938766, -0.175002, 0.297563, 0.693609, 0.943667, -0.173946, 0.289613, 0.722157, 0.949033, -0.172221, 0.281227, 0.750021, 0.953765, -0.169869, 0.271545, 0.777466, 0.95804, -0.166578, 0.261034, 0.804853, 0.962302, -0.161761, 0.249434, 0.831569, 0.966544, -0.156636, 0.237484, 0.857779, 0.969372, -0.150784, 0.224395, 0.883051, 0.972486, -0.143672, 0.210786, 0.907864, 0.975853, -0.135772, 0.196556, 0.931223, 0.977975, -0.127942, 0.182307, 0.954061, 0.979122, -0.118347, 0.167607, 0.97531, 0.980719, -0.109112, 0.152739, 0.995666, 0.981223, -0.0991789, 0.137932, 1.01475, 0.98216, -0.0883553, 0.122692, 1.03253, 0.983379, -0.0780825, 0.107493, 1.04917, 0.985434, -0.0665646, 0.0917791, 1.06464, 0.987332, -0.0557714, 0.0764949, 1.07896, 0.990004, -0.0442805, 0.060721, 1.09199, 0.992975, -0.0331676, 0.0452284, 1.10393, 0.995811, -0.0219547, 0.0297934, 1.11476, 0.9982, -0.0107613, 0.0146415, 1.12484, 1.00002, 0.000248678, -0.00014555, 1.13413, 0.859519, -0.00000693595, 0.347264, 0.0000171673, 0.859843, -0.00017503, 0.347394, 0.000433219, 0.859656, -0.000700076, 0.347319, 0.00173277, 0.859671, -0.00157517, 0.347325, 0.00389875, 0.859669, -0.00280028, 0.347324, 0.00693112, 0.85967, -0.0043754, 0.347324, 0.01083, 0.859665, -0.00630049, 0.347321, 0.0155954, 0.859685, -0.0085755, 0.347328, 0.0212278, 0.859694, -0.0112003, 0.347329, 0.0277273, 0.859718, -0.0141747, 0.347336, 0.0350946, 0.85976, -0.0174988, 0.347348, 0.0433314, 0.85982, -0.0211722, 0.347366, 0.0524384, 0.859892, -0.0251941, 0.347387, 0.0624168, 0.860006, -0.0295649, 0.347422, 0.0732708, 0.860122, -0.0342825, 0.347453, 0.0849999, 0.860282, -0.0393462, 0.347499, 0.0976102, 0.860482, -0.0447513, 0.347554, 0.111104, 0.860719, -0.0504775, 0.347614, 0.125479, 0.860998, -0.0563577, 0.347666, 0.140703, 0.861322, -0.0619473, 0.347662, 0.156681, 0.861724, -0.0681277, 0.347684, 0.173597, 0.862198, -0.0746567, 0.347709, 0.191371, 0.862733, -0.0815234, 0.347727, 0.209976, 0.863371, -0.0886643, 0.347744, 0.229351, 0.86414, -0.0957908, 0.347734, 0.24934, 0.865138, -0.102912, 0.34772, 0.269797, 0.866182, -0.110924, 0.3478, 0.290654, 0.867436, -0.119223, 0.347911, 0.312074, 0.869087, -0.126197, 0.347649, 0.335438, 0.870859, -0.133145, 0.347222, 0.359732, 0.872997, -0.139869, 0.346645, 0.38467, 0.875939, -0.146089, 0.345935, 0.41019, 0.879012, -0.152334, 0.345012, 0.436218, 0.883353, -0.15821, 0.343924, 0.462641, 0.888362, -0.164097, 0.342636, 0.489449, 0.895026, -0.169528, 0.341351, 0.516629, 0.900753, -0.174408, 0.339115, 0.544109, 0.906814, -0.17751, 0.335809, 0.572857, 0.912855, -0.180101, 0.331597, 0.601554, 0.919438, -0.182116, 0.32698, 0.630198, 0.925962, -0.183494, 0.321449, 0.658404, 0.931734, -0.184159, 0.314595, 0.686625, 0.93762, -0.18304, 0.306462, 0.71531, 0.943858, -0.181323, 0.297514, 0.744272, 0.948662, -0.178683, 0.287447, 0.771462, 0.953299, -0.175379, 0.276166, 0.798593, 0.957346, -0.170395, 0.263758, 0.8256, 0.962565, -0.165042, 0.251019, 0.852575, 0.966075, -0.158655, 0.237011, 0.878316, 0.969048, -0.151707, 0.222518, 0.90329, 0.972423, -0.143271, 0.207848, 0.927745, 0.975833, -0.134824, 0.192463, 0.950859, 0.977629, -0.125444, 0.1768, 0.972947, 0.978995, -0.114949, 0.161033, 0.993263, 0.980533, -0.104936, 0.145523, 1.01337, 0.980745, -0.0935577, 0.129799, 1.03128, 0.981814, -0.0822956, 0.113486, 1.04825, 0.983943, -0.0710082, 0.0972925, 1.06405, 0.986141, -0.0587931, 0.0808138, 1.0785, 0.988878, -0.0472755, 0.0644915, 1.09204, 0.992132, -0.0349128, 0.0478128, 1.10413, 0.9953, -0.0232407, 0.031621, 1.11527, 0.998117, -0.0112713, 0.0154935, 1.12551, 1.00003, 0.000339743, -0.000195763, 1.13504, 0.845441, -0.00000729126, 0.364305, 0.0000169208, 0.843588, -0.000183164, 0.363506, 0.000425067, 0.843412, -0.00073253, 0.36343, 0.00169999, 0.843401, -0.00164818, 0.363426, 0.00382495, 0.843399, -0.00293008, 0.363425, 0.00679993, 0.843401, -0.00457822, 0.363425, 0.010625, 0.843394, -0.00659249, 0.363421, 0.0153002, 0.843398, -0.00897282, 0.363421, 0.0208258, 0.843415, -0.0117191, 0.363426, 0.0272024, 0.843438, -0.0148312, 0.363432, 0.0344305, 0.843483, -0.018309, 0.363447, 0.0425116, 0.84356, -0.0221521, 0.363472, 0.0514471, 0.843646, -0.0263597, 0.363499, 0.061238, 0.843743, -0.0309315, 0.363527, 0.0718873, 0.84388, -0.0358658, 0.363569, 0.0833969, 0.844079, -0.0411624, 0.363631, 0.0957742, 0.844279, -0.0468128, 0.363688, 0.109015, 0.844549, -0.0527923, 0.363761, 0.123124, 0.844858, -0.0588204, 0.363817, 0.138044, 0.84522, -0.0647573, 0.36383, 0.153755, 0.845669, -0.0713181, 0.363879, 0.170394, 0.846155, -0.0781697, 0.363908, 0.187861, 0.846789, -0.0853913, 0.363969, 0.206176, 0.847502, -0.0928086, 0.363999, 0.225244, 0.8484, -0.10005, 0.363997, 0.244926, 0.849461, -0.107615, 0.364008, 0.265188, 0.850562, -0.115814, 0.364055, 0.28587, 0.851962, -0.124334, 0.364179, 0.306926, 0.854326, -0.131995, 0.364233, 0.329605, 0.856295, -0.139338, 0.363856, 0.35359, 0.858857, -0.146346, 0.363347, 0.37831, 0.862428, -0.152994, 0.362807, 0.403722, 0.866203, -0.159463, 0.361963, 0.429537, 0.871629, -0.165623, 0.36112, 0.456, 0.877365, -0.171649, 0.359917, 0.482773, 0.883744, -0.177151, 0.35848, 0.509705, 0.890693, -0.182381, 0.356523, 0.537215, 0.897278, -0.186076, 0.3533, 0.565493, 0.903958, -0.188602, 0.349095, 0.594293, 0.910908, -0.190755, 0.344215, 0.623165, 0.918117, -0.192063, 0.338606, 0.651573, 0.924644, -0.192758, 0.331544, 0.679869, 0.931054, -0.192238, 0.323163, 0.708668, 0.937303, -0.190035, 0.313529, 0.737201, 0.943387, -0.187162, 0.303152, 0.764977, 0.948494, -0.183876, 0.29146, 0.792683, 0.952546, -0.178901, 0.277917, 0.819228, 0.958077, -0.173173, 0.264753, 0.846559, 0.962462, -0.16645, 0.25002, 0.872962, 0.966569, -0.159452, 0.234873, 0.898729, 0.969108, -0.15074, 0.218752, 0.923126, 0.973072, -0.141523, 0.202673, 0.947278, 0.975452, -0.132075, 0.186326, 0.969938, 0.977784, -0.121257, 0.169396, 0.991325, 0.97899, -0.110182, 0.153044, 1.01123, 0.979777, -0.0989634, 0.136485, 1.0299, 0.980865, -0.0865894, 0.119343, 1.04727, 0.982432, -0.0746115, 0.102452, 1.06341, 0.984935, -0.0621822, 0.0852423, 1.07834, 0.987776, -0.0495694, 0.0678546, 1.092, 0.99103, -0.0372386, 0.0506917, 1.1043, 0.99474, -0.0244353, 0.0333316, 1.11576, 0.997768, -0.0121448, 0.0164348, 1.12617, 1.00003, 0.00031774, -0.000169504, 1.13598, 0.825551, -0.00000756799, 0.378425, 0.0000165099, 0.82664, -0.000190922, 0.378923, 0.000416504, 0.826323, -0.000763495, 0.378779, 0.0016656, 0.826359, -0.00171789, 0.378795, 0.00374768, 0.82636, -0.00305402, 0.378795, 0.00666259, 0.826368, -0.00477185, 0.378798, 0.0104104, 0.826364, -0.00687131, 0.378795, 0.0149912, 0.826368, -0.00935232, 0.378795, 0.0204054, 0.826376, -0.0122146, 0.378797, 0.0266532, 0.826399, -0.0154581, 0.378803, 0.0337355, 0.82646, -0.0190825, 0.378824, 0.0416537, 0.826525, -0.0230873, 0.378846, 0.0504091, 0.826614, -0.0274719, 0.378876, 0.0600032, 0.82674, -0.0322355, 0.378917, 0.0704393, 0.826888, -0.0373766, 0.378964, 0.0817195, 0.827078, -0.0428936, 0.379024, 0.0938492, 0.827318, -0.0487778, 0.379099, 0.106828, 0.82764, -0.0549935, 0.379199, 0.120659, 0.827926, -0.0611058, 0.379227, 0.13526, 0.828325, -0.0675054, 0.379275, 0.150713, 0.828801, -0.0743455, 0.379332, 0.167034, 0.8294, -0.0815523, 0.379415, 0.184209, 0.830094, -0.0890779, 0.379495, 0.202203, 0.8309, -0.096736, 0.379555, 0.220945, 0.831943, -0.104135, 0.379577, 0.240306, 0.833037, -0.112106, 0.379604, 0.260317, 0.834278, -0.120554, 0.379668, 0.2808, 0.836192, -0.129128, 0.3799, 0.301654, 0.838671, -0.137541, 0.380109, 0.323502, 0.840939, -0.14523, 0.379809, 0.347176, 0.844575, -0.15248, 0.379593, 0.371706, 0.848379, -0.159607, 0.37909, 0.39688, 0.853616, -0.166267, 0.378617, 0.422702, 0.858921, -0.172698, 0.377746, 0.448919, 0.865324, -0.178823, 0.376749, 0.475661, 0.872207, -0.184542, 0.375363, 0.502599, 0.880018, -0.189836, 0.373657, 0.529914, 0.88694, -0.194294, 0.370673, 0.557683, 0.894779, -0.197022, 0.36662, 0.586848, 0.902242, -0.199108, 0.36138, 0.615831, 0.909914, -0.200398, 0.355434, 0.644478, 0.917088, -0.20094, 0.348173, 0.672905, 0.923888, -0.200671, 0.339482, 0.701327, 0.930495, -0.198773, 0.32956, 0.730101, 0.937247, -0.195394, 0.318363, 0.758383, 0.943108, -0.191956, 0.306323, 0.786539, 0.948296, -0.187227, 0.292576, 0.813637, 0.953472, -0.181165, 0.278234, 0.840793, 0.958485, -0.174119, 0.263054, 0.867712, 0.962714, -0.166564, 0.246756, 0.893635, 0.966185, -0.158181, 0.229945, 0.919028, 0.970146, -0.148275, 0.212633, 0.943413, 0.973491, -0.138157, 0.195229, 0.966627, 0.975741, -0.127574, 0.178048, 0.988817, 0.977238, -0.11554, 0.160312, 1.00924, 0.978411, -0.10364, 0.142857, 1.02845, 0.979811, -0.0913122, 0.125317, 1.04648, 0.98116, -0.0782558, 0.107627, 1.06284, 0.983543, -0.0655957, 0.0895862, 1.07798, 0.986789, -0.0520411, 0.0713756, 1.092, 0.990292, -0.0389727, 0.053228, 1.10484, 0.994187, -0.025808, 0.0351945, 1.11642, 0.997499, -0.0126071, 0.0173198, 1.12703, 0.999999, 0.000275604, -0.000148602, 1.13674, 0.81075, -0.0000078735, 0.394456, 0.0000161829, 0.808692, -0.000198293, 0.393453, 0.000407564, 0.80846, -0.000792877, 0.39334, 0.00162965, 0.808595, -0.00178416, 0.393407, 0.00366711, 0.808597, -0.00317182, 0.393408, 0.00651934, 0.808598, -0.00495589, 0.393408, 0.0101866, 0.808591, -0.00713627, 0.393403, 0.0146689, 0.808592, -0.00971285, 0.393402, 0.0199667, 0.80861, -0.0126855, 0.393407, 0.0260803, 0.808633, -0.0160538, 0.393413, 0.0330107, 0.80868, -0.0198175, 0.393429, 0.0407589, 0.808748, -0.0239758, 0.393453, 0.0493264, 0.808854, -0.0285286, 0.39349, 0.0587161, 0.808992, -0.0334748, 0.39354, 0.0689304, 0.809141, -0.0388116, 0.393588, 0.0799707, 0.809352, -0.0445375, 0.39366, 0.0918432, 0.809608, -0.0506427, 0.393742, 0.104549, 0.809915, -0.0570708, 0.393834, 0.118085, 0.810253, -0.0633526, 0.393885, 0.132377, 0.810687, -0.0700966, 0.393953, 0.147537, 0.811233, -0.0772274, 0.394047, 0.163543, 0.811865, -0.0847629, 0.394148, 0.180394, 0.812648, -0.0925663, 0.394265, 0.198051, 0.813583, -0.100416, 0.394363, 0.216443, 0.814683, -0.108119, 0.394402, 0.235502, 0.815948, -0.11644, 0.394489, 0.255242, 0.817278, -0.125036, 0.394542, 0.275441, 0.819605, -0.133655, 0.39486, 0.296094, 0.822256, -0.142682, 0.395248, 0.317309, 0.825349, -0.150756, 0.395241, 0.340516, 0.829605, -0.158392, 0.395285, 0.364819, 0.83391, -0.165801, 0.394922, 0.389736, 0.839808, -0.172677, 0.394691, 0.415409, 0.845708, -0.179448, 0.394006, 0.441546, 0.853025, -0.185746, 0.393279, 0.46832, 0.859666, -0.191684, 0.391655, 0.495302, 0.86789, -0.197146, 0.390068, 0.52262, 0.875845, -0.201904, 0.38727, 0.550336, 0.882634, -0.205023, 0.382688, 0.578825, 0.891076, -0.207098, 0.377543, 0.608103, 0.900589, -0.208474, 0.371752, 0.63723, 0.90791, -0.209068, 0.364016, 0.665769, 0.915971, -0.208655, 0.355593, 0.694428, 0.923455, -0.20729, 0.345439, 0.723224, 0.931514, -0.203821, 0.334099, 0.751925, 0.937885, -0.19986, 0.321069, 0.780249, 0.943136, -0.194993, 0.306571, 0.8077, 0.948818, -0.189132, 0.291556, 0.83497, 0.954433, -0.181617, 0.275745, 0.86188, 0.959078, -0.173595, 0.258695, 0.888562, 0.962705, -0.164855, 0.240825, 0.914008, 0.966753, -0.155129, 0.22268, 0.939145, 0.970704, -0.144241, 0.204542, 0.963393, 0.973367, -0.133188, 0.185927, 0.985983, 0.975984, -0.121146, 0.167743, 1.00704, 0.976994, -0.108366, 0.149218, 1.02715, 0.978485, -0.0956746, 0.13131, 1.0455, 0.980074, -0.0820733, 0.112513, 1.06221, 0.98225, -0.0684061, 0.0938323, 1.07782, 0.98553, -0.0549503, 0.0749508, 1.09199, 0.989529, -0.0407857, 0.055848, 1.10508, 0.993536, -0.0271978, 0.0368581, 1.11684, 0.997247, -0.0132716, 0.0181845, 1.12789, 1, 0.000431817, -0.000198809, 1.13792, 0.785886, -0.00000812608, 0.405036, 0.0000157669, 0.790388, -0.000205278, 0.407355, 0.000398297, 0.790145, -0.000820824, 0.407231, 0.00159263, 0.790135, -0.00184681, 0.407226, 0.00358336, 0.790119, -0.00328316, 0.407218, 0.00637039, 0.790126, -0.00512988, 0.40722, 0.0099539, 0.79013, -0.00738684, 0.407221, 0.0143339, 0.790135, -0.0100538, 0.407221, 0.0195107, 0.790134, -0.0131306, 0.407217, 0.0254848, 0.79016, -0.0166169, 0.407224, 0.0322572, 0.790197, -0.020512, 0.407236, 0.0398284, 0.790273, -0.0248157, 0.407263, 0.0482014, 0.790381, -0.029527, 0.407304, 0.0573777, 0.790521, -0.0346446, 0.407355, 0.0673602, 0.790704, -0.0401665, 0.40742, 0.0781522, 0.790925, -0.0460896, 0.407499, 0.0897582, 0.791195, -0.0524017, 0.407589, 0.10218, 0.791522, -0.0590121, 0.407691, 0.11541, 0.791878, -0.0654876, 0.407748, 0.12939, 0.792361, -0.0725207, 0.407849, 0.144237, 0.792942, -0.0799844, 0.407963, 0.159924, 0.79362, -0.0877896, 0.408087, 0.176425, 0.794529, -0.0958451, 0.408259, 0.193733, 0.795521, -0.103827, 0.408362, 0.211756, 0.796778, -0.111937, 0.408482, 0.230524, 0.798027, -0.120521, 0.408547, 0.249967, 0.799813, -0.129242, 0.408721, 0.269926, 0.802387, -0.138048, 0.409148, 0.290338, 0.805279, -0.147301, 0.409641, 0.311193, 0.809251, -0.155895, 0.410154, 0.333611, 0.813733, -0.163942, 0.410297, 0.357615, 0.819081, -0.171666, 0.410373, 0.382339, 0.825427, -0.178905, 0.410348, 0.407828, 0.83172, -0.185812, 0.409486, 0.434034, 0.83877, -0.192318, 0.408776, 0.460493, 0.845817, -0.198249, 0.407176, 0.487346, 0.854664, -0.204034, 0.405719, 0.514832, 0.863495, -0.208908, 0.403282, 0.542401, 0.871883, -0.212765, 0.399293, 0.570683, 0.88065, -0.214911, 0.393803, 0.599947, 0.89004, -0.216214, 0.387536, 0.62932, 0.898476, -0.216745, 0.379846, 0.658319, 0.906738, -0.216387, 0.370625, 0.687138, 0.914844, -0.215053, 0.360139, 0.71601, 0.923877, -0.212007, 0.348849, 0.745124, 0.931925, -0.207481, 0.335639, 0.773366, 0.938054, -0.202418, 0.320798, 0.801636, 0.943895, -0.196507, 0.304772, 0.829055, 0.949468, -0.189009, 0.288033, 0.856097, 0.955152, -0.180539, 0.270532, 0.88301, 0.959403, -0.171437, 0.251639, 0.909296, 0.963309, -0.161661, 0.232563, 0.934868, 0.967399, -0.150425, 0.213231, 0.959662, 0.972009, -0.138659, 0.194247, 0.98302, 0.97433, -0.126595, 0.174718, 1.00517, 0.975823, -0.113205, 0.155518, 1.02566, 0.976371, -0.0996096, 0.136709, 1.04418, 0.978705, -0.0860754, 0.117571, 1.06146, 0.981477, -0.0714438, 0.0980046, 1.07777, 0.984263, -0.0572304, 0.0782181, 1.09214, 0.988423, -0.0428875, 0.0584052, 1.10553, 0.993, -0.0282442, 0.038522, 1.11758, 0.99704, -0.0140183, 0.0190148, 1.12864, 0.999913, 0.000369494, -0.000145203, 1.13901, 0.777662, -0.0000084153, 0.423844, 0.0000154403, 0.770458, -0.000211714, 0.419915, 0.00038845, 0.770716, -0.000846888, 0.420055, 0.00155386, 0.770982, -0.00190567, 0.420202, 0.00349653, 0.770981, -0.00338782, 0.420201, 0.00621606, 0.77098, -0.00529338, 0.4202, 0.00971274, 0.770983, -0.00762223, 0.4202, 0.0139867, 0.770985, -0.0103741, 0.420198, 0.0190381, 0.770996, -0.0135489, 0.4202, 0.0248677, 0.771029, -0.0171461, 0.420212, 0.0314764, 0.771052, -0.0211647, 0.420215, 0.0388648, 0.771131, -0.0256048, 0.420245, 0.047036, 0.771235, -0.0304647, 0.420284, 0.0559911, 0.771383, -0.0357436, 0.420341, 0.0657346, 0.771591, -0.0414392, 0.420423, 0.0762694, 0.771819, -0.0475462, 0.420506, 0.0875984, 0.772123, -0.0540506, 0.420617, 0.099727, 0.772464, -0.060797, 0.42072, 0.112637, 0.772855, -0.0675393, 0.420799, 0.126313, 0.773317, -0.0748323, 0.420893, 0.140824, 0.773981, -0.0825681, 0.421058, 0.15617, 0.774746, -0.0906307, 0.421226, 0.172322, 0.77566, -0.0988982, 0.421397, 0.189253, 0.776837, -0.106994, 0.421569, 0.206912, 0.778097, -0.115528, 0.421704, 0.225359, 0.779588, -0.124317, 0.421849, 0.24447, 0.781574, -0.133139, 0.422097, 0.264156, 0.784451, -0.142179, 0.422615, 0.284318, 0.787682, -0.15165, 0.423269, 0.304902, 0.792433, -0.160771, 0.424396, 0.3265, 0.797359, -0.169166, 0.424772, 0.35014, 0.803986, -0.177149, 0.425475, 0.374768, 0.809504, -0.184745, 0.424996, 0.399928, 0.815885, -0.19173, 0.424247, 0.425796, 0.823513, -0.198525, 0.423515, 0.452287, 0.832549, -0.204709, 0.422787, 0.479321, 0.841653, -0.210447, 0.421187, 0.506718, 0.850401, -0.215501, 0.418519, 0.53432, 0.859854, -0.219752, 0.414715, 0.56242, 0.869364, -0.222305, 0.409462, 0.591558, 0.878837, -0.223744, 0.402926, 0.621074, 0.888636, -0.224065, 0.395043, 0.650538, 0.898132, -0.223742, 0.38564, 0.679538, 0.907181, -0.222308, 0.375378, 0.708674, 0.915621, -0.219837, 0.363212, 0.737714, 0.9239, -0.215233, 0.349313, 0.767014, 0.931644, -0.209592, 0.334162, 0.795133, 0.938887, -0.203644, 0.317943, 0.823228, 0.945282, -0.196349, 0.300581, 0.850822, 0.950758, -0.18742, 0.282195, 0.877594, 0.956146, -0.177879, 0.262481, 0.904564, 0.960355, -0.167643, 0.242487, 0.930741, 0.965256, -0.156671, 0.222668, 0.955868, 0.968029, -0.144123, 0.201907, 0.979869, 0.97251, -0.131305, 0.18202, 1.00291, 0.974925, -0.118335, 0.161909, 1.02392, 0.975402, -0.103714, 0.142129, 1.0433, 0.976987, -0.089415, 0.122447, 1.06089, 0.979677, -0.0748858, 0.102248, 1.07713, 0.983184, -0.0596086, 0.0814851, 1.09218, 0.987466, -0.0447671, 0.0609484, 1.10585, 0.992348, -0.0295217, 0.0401835, 1.11829, 0.996674, -0.0143917, 0.0198163, 1.12966, 1.00003, 0.000321364, -0.000149983, 1.1402, 0.757901, -0.00000869074, 0.436176, 0.0000151011, 0.751195, -0.000217848, 0.432317, 0.000378533, 0.751178, -0.000871373, 0.432307, 0.0015141, 0.751195, -0.00196061, 0.432317, 0.0034068, 0.751198, -0.00348552, 0.432318, 0.00605659, 0.751195, -0.00544599, 0.432315, 0.00946353, 0.751207, -0.00784203, 0.43232, 0.013628, 0.751213, -0.0106732, 0.43232, 0.0185499, 0.751221, -0.0139393, 0.432319, 0.0242302, 0.751244, -0.0176398, 0.432325, 0.0306694, 0.7513, -0.0217743, 0.432348, 0.0378698, 0.751358, -0.0263412, 0.432367, 0.0458321, 0.751458, -0.0313396, 0.432404, 0.0545587, 0.751608, -0.0367682, 0.432464, 0.0640543, 0.7518, -0.0426246, 0.43254, 0.0743222, 0.752065, -0.0489031, 0.432645, 0.0853668, 0.752376, -0.0555828, 0.432762, 0.0971911, 0.752715, -0.0623861, 0.432859, 0.109768, 0.753137, -0.069415, 0.432958, 0.123126, 0.753676, -0.0770039, 0.433099, 0.137308, 0.754345, -0.084971, 0.433272, 0.15229, 0.755235, -0.0932681, 0.433504, 0.168075, 0.756186, -0.10171, 0.433693, 0.184625, 0.757363, -0.110019, 0.433857, 0.201897, 0.75884, -0.11887, 0.434102, 0.220014, 0.760467, -0.127881, 0.434306, 0.238778, 0.762969, -0.136766, 0.434751, 0.258172, 0.765823, -0.14612, 0.43529, 0.278062, 0.769676, -0.15566, 0.436236, 0.298437, 0.774909, -0.165177, 0.437754, 0.319532, 0.77994, -0.17402, 0.438343, 0.342505, 0.785757, -0.182201, 0.438609, 0.366693, 0.792487, -0.190104, 0.438762, 0.391668, 0.80038, -0.197438, 0.438795, 0.417494, 0.808494, -0.204365, 0.438226, 0.443933, 0.817695, -0.210714, 0.437283, 0.470929, 0.828111, -0.216651, 0.436087, 0.498569, 0.837901, -0.221804, 0.433717, 0.526165, 0.847813, -0.226318, 0.430133, 0.554155, 0.858314, -0.229297, 0.425213, 0.582822, 0.868891, -0.230999, 0.418576, 0.612847, 0.878941, -0.231155, 0.410405, 0.642445, 0.888809, -0.230935, 0.400544, 0.672024, 0.898089, -0.229343, 0.389613, 0.701366, 0.908081, -0.226886, 0.377197, 0.730763, 0.916819, -0.222676, 0.363397, 0.759642, 0.924968, -0.216835, 0.347437, 0.788775, 0.932906, -0.210245, 0.32995, 0.817135, 0.940025, -0.202992, 0.312262, 0.844912, 0.946101, -0.19436, 0.293313, 0.872164, 0.952835, -0.184125, 0.273638, 0.899443, 0.957347, -0.173657, 0.252385, 0.926389, 0.961434, -0.162204, 0.231038, 0.951947, 0.965522, -0.14979, 0.209834, 0.976751, 0.969412, -0.136307, 0.188821, 1.00022, 0.973902, -0.122527, 0.168013, 1.02229, 0.974045, -0.108213, 0.147634, 1.04199, 0.975775, -0.0927397, 0.12705, 1.06019, 0.978383, -0.0778212, 0.106309, 1.07711, 0.98211, -0.0621216, 0.0849279, 1.09245, 0.986517, -0.0463847, 0.0633519, 1.10651, 0.991696, -0.0309353, 0.0419698, 1.11903, 0.996349, -0.0150914, 0.0206272, 1.13073, 1.00003, 0.000442449, -0.000231396, 1.14146, 0.727498, -0.00000885074, 0.441528, 0.0000145832, 0.730897, -0.000223525, 0.443589, 0.000368298, 0.730796, -0.000893996, 0.443528, 0.00147303, 0.730805, -0.00201149, 0.443533, 0.00331433, 0.730814, -0.00357596, 0.443538, 0.00589222, 0.730815, -0.00558734, 0.443538, 0.00920678, 0.730822, -0.00804544, 0.44354, 0.0132582, 0.730836, -0.0109501, 0.443545, 0.0180468, 0.730848, -0.0143008, 0.443546, 0.0235732, 0.730871, -0.0180969, 0.443552, 0.0298382, 0.730915, -0.022338, 0.443567, 0.0368438, 0.730982, -0.0270225, 0.443591, 0.044591, 0.731076, -0.0321491, 0.443627, 0.0530831, 0.731245, -0.0377166, 0.443699, 0.0623243, 0.73144, -0.0437216, 0.443777, 0.0723181, 0.7317, -0.0501576, 0.443881, 0.0830691, 0.732034, -0.0569942, 0.444014, 0.0945809, 0.732388, -0.0638756, 0.444113, 0.106825, 0.732853, -0.071203, 0.444247, 0.119859, 0.733473, -0.0790076, 0.444442, 0.13369, 0.734195, -0.0871937, 0.444645, 0.148304, 0.735069, -0.095696, 0.444877, 0.163702, 0.736169, -0.10426, 0.445133, 0.179861, 0.73747, -0.112853, 0.44537, 0.196778, 0.738991, -0.12199, 0.445651, 0.214496, 0.740865, -0.131153, 0.445958, 0.232913, 0.743637, -0.140245, 0.446548, 0.251977, 0.746797, -0.149722, 0.447246, 0.271551, 0.751517, -0.159341, 0.448656, 0.291774, 0.756156, -0.169106, 0.449866, 0.312455, 0.761519, -0.178436, 0.450919, 0.334552, 0.768295, -0.186904, 0.451776, 0.358491, 0.776613, -0.195117, 0.452832, 0.383446, 0.783966, -0.202695, 0.45249, 0.408945, 0.793542, -0.20985, 0.452587, 0.435364, 0.803192, -0.216403, 0.451852, 0.462336, 0.813892, -0.22251, 0.450708, 0.48987, 0.824968, -0.227676, 0.4486, 0.517697, 0.835859, -0.232443, 0.445156, 0.545975, 0.846825, -0.235775, 0.440351, 0.574483, 0.858085, -0.237897, 0.433641, 0.604246, 0.868825, -0.238074, 0.425354, 0.634101, 0.879638, -0.237661, 0.415383, 0.664201, 0.889966, -0.236186, 0.404136, 0.693918, 0.899479, -0.233599, 0.390917, 0.723481, 0.908769, -0.229737, 0.376352, 0.75258, 0.917966, -0.223836, 0.360372, 0.781764, 0.926304, -0.217067, 0.342551, 0.811139, 0.934626, -0.209309, 0.324238, 0.839585, 0.941841, -0.20071, 0.304484, 0.867044, 0.94789, -0.190602, 0.283607, 0.894579, 0.954196, -0.179253, 0.262205, 0.921743, 0.958383, -0.167646, 0.239847, 0.948026, 0.963119, -0.155073, 0.218078, 0.973296, 0.966941, -0.141426, 0.195899, 0.998135, 0.970836, -0.126849, 0.174121, 1.02021, 0.973301, -0.112296, 0.153052, 1.04085, 0.97448, -0.0964965, 0.131733, 1.05946, 0.977045, -0.080489, 0.10997, 1.07693, 0.980751, -0.064844, 0.0881657, 1.09254, 0.985475, -0.0481938, 0.0657987, 1.10697, 0.991089, -0.0319185, 0.0435215, 1.12004, 0.996122, -0.0158088, 0.0214779, 1.13173, 1.00001, 0.000372455, -0.000200295, 1.14291, 0.708622, -0.00000907597, 0.45304, 0.0000141962, 0.711162, -0.000228911, 0.454662, 0.000358052, 0.709812, -0.000914446, 0.453797, 0.00143034, 0.709865, -0.00205819, 0.453834, 0.00321935, 0.709864, -0.00365894, 0.453833, 0.00572331, 0.709855, -0.00571692, 0.453826, 0.00894278, 0.709862, -0.00823201, 0.453828, 0.012878, 0.709875, -0.011204, 0.453832, 0.0175295, 0.709896, -0.0146323, 0.453839, 0.0228978, 0.709925, -0.0185163, 0.453847, 0.0289839, 0.709974, -0.0228551, 0.453866, 0.0357894, 0.710045, -0.0276473, 0.453892, 0.0433161, 0.710133, -0.032891, 0.453924, 0.0515665, 0.710292, -0.0385851, 0.453992, 0.0605458, 0.710485, -0.0447254, 0.45407, 0.0702574, 0.710769, -0.0513051, 0.454192, 0.0807077, 0.711106, -0.0582733, 0.454329, 0.091896, 0.711516, -0.0652866, 0.45446, 0.103814, 0.712071, -0.0728426, 0.454653, 0.116508, 0.712676, -0.0808307, 0.45484, 0.129968, 0.713476, -0.0892216, 0.455096, 0.144206, 0.714377, -0.0979047, 0.455346, 0.159212, 0.715579, -0.106531, 0.455647, 0.174973, 0.716977, -0.115492, 0.455961, 0.191504, 0.71862, -0.124821, 0.456315, 0.208835, 0.72084, -0.134079, 0.4568, 0.226869, 0.723786, -0.143427, 0.457521, 0.245582, 0.727464, -0.153061, 0.458475, 0.264957, 0.732771, -0.162768, 0.460239, 0.284948, 0.736515, -0.172627, 0.460899, 0.30522, 0.743519, -0.182487, 0.463225, 0.326717, 0.750041, -0.191295, 0.464027, 0.350113, 0.758589, -0.199746, 0.465227, 0.374782, 0.767703, -0.207584, 0.465877, 0.400226, 0.777484, -0.214973, 0.465996, 0.426442, 0.788792, -0.221796, 0.466019, 0.453688, 0.800194, -0.228038, 0.465083, 0.481246, 0.811234, -0.233346, 0.462506, 0.509086, 0.822859, -0.238073, 0.459257, 0.537338, 0.835082, -0.241764, 0.454863, 0.566108, 0.846332, -0.244241, 0.448163, 0.595126, 0.858355, -0.244736, 0.439709, 0.625574, 0.87034, -0.244278, 0.429837, 0.65617, 0.881027, -0.24255, 0.418002, 0.686029, 0.891007, -0.239912, 0.404325, 0.716039, 0.900874, -0.236133, 0.389222, 0.745518, 0.911072, -0.230672, 0.373269, 0.775026, 0.920359, -0.22356, 0.355083, 0.804521, 0.928604, -0.215591, 0.335533, 0.834045, 0.937175, -0.206503, 0.315278, 0.861612, 0.942825, -0.196684, 0.293653, 0.889131, 0.949805, -0.185116, 0.271503, 0.916853, 0.955535, -0.172703, 0.248821, 0.943541, 0.959843, -0.159978, 0.225591, 0.970132, 0.964393, -0.146375, 0.202719, 0.994709, 0.968008, -0.131269, 0.179928, 1.0186, 0.971013, -0.11569, 0.158007, 1.03928, 0.973334, -0.1003, 0.13624, 1.05887, 0.975775, -0.0833352, 0.1138, 1.07652, 0.979579, -0.0668981, 0.0913141, 1.09297, 0.984323, -0.0500902, 0.0683051, 1.10734, 0.990351, -0.0332377, 0.0451771, 1.12084, 0.995823, -0.0161491, 0.0221705, 1.13296, 1.0001, 0.000234083, -0.000108712, 1.14441, 0.683895, -0.00000924677, 0.46015, 0.0000137429, 0.68833, -0.000233383, 0.463134, 0.000346865, 0.688368, -0.000933547, 0.463159, 0.00138748, 0.688367, -0.00210049, 0.463159, 0.00312187, 0.688369, -0.00373415, 0.463159, 0.00555004, 0.688377, -0.00583449, 0.463163, 0.00867216, 0.688386, -0.00840128, 0.463166, 0.0124884, 0.688398, -0.0114343, 0.463169, 0.0169993, 0.688418, -0.0149329, 0.463175, 0.0222054, 0.688453, -0.0188964, 0.463188, 0.028108, 0.688515, -0.0233239, 0.463214, 0.0347085, 0.68857, -0.0282136, 0.463231, 0.0420091, 0.688679, -0.033564, 0.463276, 0.0500132, 0.688854, -0.0393733, 0.463356, 0.0587255, 0.689038, -0.0456354, 0.46343, 0.0681476, 0.689321, -0.0523433, 0.463553, 0.0782897, 0.689662, -0.059412, 0.463693, 0.0891501, 0.690188, -0.0665736, 0.4639, 0.100735, 0.690755, -0.0743106, 0.464107, 0.113074, 0.691405, -0.0824722, 0.464329, 0.126161, 0.692198, -0.0910484, 0.464585, 0.140007, 0.693196, -0.0998778, 0.464893, 0.154612, 0.69454, -0.108651, 0.465285, 0.169984, 0.695921, -0.117855, 0.465596, 0.186106, 0.697749, -0.12734, 0.466056, 0.203034, 0.700375, -0.136714, 0.466771, 0.220703, 0.703395, -0.146386, 0.467579, 0.239062, 0.707904, -0.156096, 0.469067, 0.258188, 0.711673, -0.165904, 0.469851, 0.277759, 0.717489, -0.175812, 0.471815, 0.297935, 0.724051, -0.185931, 0.47389, 0.318916, 0.731965, -0.195238, 0.47587, 0.341591, 0.741151, -0.204021, 0.477523, 0.366062, 0.751416, -0.212113, 0.478881, 0.391396, 0.761848, -0.21979, 0.479226, 0.417599, 0.771886, -0.2267, 0.478495, 0.444401, 0.783998, -0.232991, 0.477622, 0.472084, 0.796523, -0.238645, 0.475833, 0.500193, 0.808851, -0.243396, 0.472568, 0.52865, 0.821191, -0.247226, 0.467857, 0.557362, 0.834261, -0.250102, 0.461871, 0.586768, 0.846762, -0.251056, 0.453543, 0.617085, 0.859867, -0.250604, 0.443494, 0.647659, 0.871948, -0.248783, 0.431711, 0.678119, 0.882967, -0.245855, 0.417911, 0.708399, 0.892826, -0.242168, 0.401993, 0.738256, 0.90332, -0.237062, 0.385371, 0.767999, 0.913633, -0.22997, 0.366837, 0.798191, 0.922774, -0.221687, 0.346372, 0.827756, 0.931371, -0.212345, 0.325682, 0.856425, 0.938929, -0.20206, 0.303665, 0.884299, 0.944821, -0.190981, 0.280786, 0.912023, 0.951792, -0.178065, 0.2573, 0.939669, 0.957712, -0.164634, 0.233448, 0.96655, 0.961912, -0.150863, 0.209504, 0.992366, 0.966382, -0.13577, 0.18597, 1.01633, 0.969588, -0.119593, 0.162905, 1.03843, 0.971777, -0.103203, 0.14053, 1.05841, 0.97433, -0.0865888, 0.117909, 1.07632, 0.978686, -0.0690829, 0.0944101, 1.09326, 0.983281, -0.0516568, 0.0705671, 1.10796, 0.989562, -0.034558, 0.0468592, 1.12182, 0.995465, -0.0167808, 0.0229846, 1.1342, 0.999991, 0.000373016, -0.000235606, 1.1459, 0.662251, -0.00000939016, 0.468575, 0.0000132714, 0.666634, -0.000237624, 0.471675, 0.000335842, 0.666411, -0.000950385, 0.471516, 0.00134321, 0.666399, -0.00213833, 0.471509, 0.00302221, 0.666386, -0.0038014, 0.471499, 0.00537283, 0.666405, -0.00593958, 0.471511, 0.00839533, 0.666406, -0.00855253, 0.471508, 0.0120898, 0.666428, -0.0116401, 0.471519, 0.0164569, 0.666444, -0.0152015, 0.471522, 0.0214971, 0.66649, -0.0192362, 0.471543, 0.027212, 0.666537, -0.0237428, 0.471558, 0.033603, 0.666617, -0.0287198, 0.471591, 0.0406728, 0.666718, -0.0341647, 0.471631, 0.0484238, 0.666889, -0.0400759, 0.47171, 0.0568621, 0.667104, -0.0464479, 0.471805, 0.0659915, 0.667374, -0.0532677, 0.471923, 0.0758178, 0.667772, -0.0603805, 0.472098, 0.0863425, 0.668371, -0.0677392, 0.472363, 0.0975917, 0.668971, -0.0756028, 0.472596, 0.109567, 0.669696, -0.0839293, 0.472869, 0.122272, 0.670481, -0.0926683, 0.473126, 0.135718, 0.6715, -0.1016, 0.473442, 0.149914, 0.672911, -0.110566, 0.47389, 0.164882, 0.674512, -0.119984, 0.474354, 0.180602, 0.67651, -0.129574, 0.474922, 0.19711, 0.679292, -0.139106, 0.475764, 0.214371, 0.682798, -0.148993, 0.476886, 0.232405, 0.686955, -0.158737, 0.478179, 0.251153, 0.691406, -0.168754, 0.479432, 0.270436, 0.697438, -0.178703, 0.481481, 0.290374, 0.704761, -0.188955, 0.484143, 0.311044, 0.713599, -0.198814, 0.487007, 0.333003, 0.723194, -0.207869, 0.488962, 0.357144, 0.732601, -0.216189, 0.489815, 0.382169, 0.744193, -0.22398, 0.490888, 0.408227, 0.754907, -0.231156, 0.490355, 0.434928, 0.767403, -0.23747, 0.489548, 0.462599, 0.78107, -0.243503, 0.488274, 0.490908, 0.793893, -0.248114, 0.484843, 0.519421, 0.807296, -0.25222, 0.4803, 0.548561, 0.820529, -0.255265, 0.474097, 0.577772, 0.833716, -0.256741, 0.466041, 0.607782, 0.848403, -0.25637, 0.456547, 0.638807, 0.860755, -0.254804, 0.443946, 0.670058, 0.874012, -0.251834, 0.430852, 0.700749, 0.885619, -0.247867, 0.414903, 0.731446, 0.896069, -0.242634, 0.397276, 0.761191, 0.906266, -0.236093, 0.378535, 0.791053, 0.916759, -0.227543, 0.358038, 0.821298, 0.92523, -0.21783, 0.335705, 0.850747, 0.93436, -0.207534, 0.313797, 0.879258, 0.941631, -0.195983, 0.289671, 0.907734, 0.947564, -0.183567, 0.265319, 0.935206, 0.953681, -0.169345, 0.240815, 0.962739, 0.960008, -0.154909, 0.216119, 0.989227, 0.964145, -0.140161, 0.192096, 1.01465, 0.968171, -0.123411, 0.167855, 1.03737, 0.969859, -0.106525, 0.144817, 1.05767, 0.972666, -0.0891023, 0.12149, 1.0761, 0.977055, -0.0718094, 0.0975306, 1.09336, 0.982527, -0.0534213, 0.0730217, 1.10878, 0.989001, -0.0355579, 0.0483366, 1.12285, 0.99512, -0.0176383, 0.023938, 1.13548, 1.00007, 0.000368831, -0.000211581, 1.14744, 0.651047, -0.00000960845, 0.484101, 0.000012922, 0.644145, -0.000241347, 0.478968, 0.000324578, 0.64396, -0.000965142, 0.478831, 0.00129798, 0.64396, -0.00217154, 0.47883, 0.00292046, 0.643968, -0.00386049, 0.478835, 0.00519202, 0.643974, -0.00603186, 0.478838, 0.0081128, 0.643977, -0.0086854, 0.478836, 0.011683, 0.643982, -0.0118207, 0.478834, 0.0159031, 0.644024, -0.0154374, 0.478856, 0.0207743, 0.644059, -0.0195343, 0.478868, 0.0262975, 0.644122, -0.0241103, 0.478896, 0.0324747, 0.644207, -0.0291638, 0.478933, 0.039309, 0.64432, -0.0346919, 0.478981, 0.0468029, 0.644481, -0.0406919, 0.479053, 0.0549614, 0.644722, -0.047159, 0.479169, 0.0637909, 0.645013, -0.0540748, 0.479302, 0.0732974, 0.645503, -0.0612001, 0.479541, 0.0834898, 0.646117, -0.0687303, 0.479829, 0.0943873, 0.646707, -0.0767846, 0.480061, 0.105991, 0.647431, -0.0852465, 0.480343, 0.11831, 0.64831, -0.0940719, 0.48066, 0.131348, 0.649486, -0.103056, 0.481083, 0.14514, 0.650864, -0.112261, 0.481528, 0.159676, 0.652604, -0.121852, 0.482102, 0.174979, 0.654825, -0.131505, 0.482813, 0.191079, 0.657876, -0.141189, 0.483876, 0.207927, 0.661339, -0.151239, 0.48499, 0.225586, 0.665463, -0.161091, 0.486279, 0.243947, 0.670542, -0.171235, 0.487968, 0.262957, 0.677361, -0.181347, 0.49053, 0.282781, 0.685672, -0.191679, 0.493862, 0.303311, 0.694551, -0.201781, 0.49699, 0.324607, 0.703753, -0.211164, 0.498884, 0.347916, 0.713703, -0.219675, 0.500086, 0.372628, 0.725911, -0.227836, 0.501554, 0.398694, 0.73862, -0.23533, 0.502193, 0.425529, 0.752118, -0.241786, 0.501811, 0.453209, 0.76579, -0.247865, 0.500185, 0.481381, 0.779568, -0.252696, 0.497159, 0.51011, 0.793991, -0.256802, 0.492765, 0.539322, 0.808182, -0.259942, 0.486827, 0.569078, 0.821698, -0.261703, 0.478386, 0.598818, 0.836009, -0.262006, 0.468772, 0.629762, 0.849824, -0.260333, 0.456352, 0.661366, 0.863888, -0.257398, 0.442533, 0.69295, 0.876585, -0.253264, 0.426573, 0.723608, 0.888665, -0.248026, 0.408964, 0.754378, 0.899537, -0.241487, 0.389677, 0.784761, 0.9094, -0.233463, 0.368516, 0.814688, 0.920166, -0.223397, 0.346624, 0.845009, 0.928899, -0.21255, 0.322717, 0.874431, 0.937156, -0.200869, 0.298698, 0.902922, 0.943861, -0.188387, 0.273491, 0.931356, 0.949557, -0.174341, 0.247866, 0.958854, 0.955862, -0.158994, 0.222496, 0.986098, 0.961721, -0.143664, 0.197522, 1.01229, 0.965976, -0.127412, 0.17302, 1.03571, 0.968652, -0.109798, 0.148954, 1.05699, 0.971084, -0.0916787, 0.125044, 1.07587, 0.975584, -0.0739634, 0.100577, 1.09372, 0.98122, -0.055322, 0.0753666, 1.10948, 0.988253, -0.0366825, 0.0498899, 1.12394, 0.99482, -0.0180389, 0.024611, 1.13694, 1.00001, 0.000229839, -0.000188283, 1.14919, 0.613867, -0.00000964198, 0.479449, 0.0000123452, 0.621485, -0.000244534, 0.485399, 0.000313091, 0.621429, -0.000978202, 0.485353, 0.00125245, 0.62112, -0.00220004, 0.485114, 0.00281687, 0.621119, -0.0039111, 0.485112, 0.00500783, 0.621122, -0.00611091, 0.485112, 0.00782498, 0.621133, -0.00879922, 0.485117, 0.0112687, 0.621152, -0.0119756, 0.485125, 0.0153394, 0.621183, -0.0156396, 0.485139, 0.0200382, 0.621227, -0.0197898, 0.485158, 0.0253663, 0.621298, -0.0244253, 0.485192, 0.0313261, 0.621388, -0.0295441, 0.485233, 0.0379204, 0.621507, -0.0351432, 0.485286, 0.0451523, 0.621693, -0.0412198, 0.485378, 0.0530277, 0.621933, -0.0477673, 0.485495, 0.0615522, 0.622232, -0.0547574, 0.485635, 0.0707316, 0.622809, -0.0619417, 0.485943, 0.0805883, 0.623407, -0.069625, 0.486232, 0.0911267, 0.62406, -0.077796, 0.486516, 0.102354, 0.624835, -0.0863731, 0.486838, 0.114279, 0.625758, -0.095251, 0.487188, 0.126902, 0.627043, -0.104299, 0.487695, 0.140285, 0.628438, -0.113724, 0.488163, 0.154397, 0.630325, -0.123417, 0.488858, 0.169267, 0.632801, -0.133137, 0.489754, 0.184941, 0.635784, -0.143052, 0.490815, 0.20136, 0.639406, -0.153132, 0.492048, 0.218643, 0.643872, -0.163143, 0.49363, 0.236615, 0.6499, -0.17333, 0.496009, 0.255449, 0.657201, -0.183622, 0.498994, 0.275006, 0.666221, -0.194019, 0.502888, 0.295354, 0.674419, -0.204192, 0.505459, 0.316244, 0.683729, -0.21406, 0.507771, 0.33849, 0.695584, -0.222854, 0.510245, 0.363166, 0.708583, -0.231315, 0.512293, 0.389071, 0.721233, -0.238911, 0.512747, 0.415737, 0.735134, -0.245657, 0.512482, 0.443331, 0.750179, -0.251879, 0.511526, 0.471891, 0.765073, -0.256911, 0.508935, 0.500892, 0.779794, -0.261144, 0.504341, 0.530294, 0.794801, -0.264316, 0.498515, 0.560144, 0.810339, -0.266276, 0.491015, 0.590213, 0.824818, -0.266981, 0.481126, 0.620865, 0.839375, -0.265778, 0.468685, 0.652687, 0.853043, -0.262748, 0.453925, 0.684759, 0.867335, -0.258474, 0.437912, 0.716209, 0.88037, -0.253187, 0.419648, 0.747508, 0.891711, -0.246476, 0.39982, 0.77797, 0.902896, -0.238735, 0.37879, 0.808586, 0.913601, -0.22885, 0.355891, 0.838843, 0.923019, -0.217656, 0.331773, 0.869014, 0.933432, -0.205539, 0.307356, 0.898512, 0.939691, -0.192595, 0.281321, 0.9269, 0.946938, -0.178945, 0.255441, 0.955297, 0.952372, -0.163587, 0.229013, 0.983231, 0.95909, -0.147214, 0.203179, 1.00971, 0.963675, -0.13064, 0.17792, 1.03438, 0.968247, -0.113121, 0.152898, 1.05625, 0.97001, -0.0945824, 0.128712, 1.07598, 0.974458, -0.0755648, 0.103349, 1.094, 0.980168, -0.0571998, 0.0776731, 1.1104, 0.987295, -0.0377994, 0.0514445, 1.12491, 0.994432, -0.0186417, 0.025429, 1.13851, 0.999975, 0.000542714, -0.000282356, 1.15108, 0.592656, -0.00000980249, 0.486018, 0.0000119532, 0.598467, -0.000247275, 0.490781, 0.000301531, 0.597934, -0.000988317, 0.490343, 0.00120517, 0.597903, -0.00222366, 0.490319, 0.0027116, 0.597913, -0.00395315, 0.490327, 0.00482077, 0.597919, -0.00617653, 0.490329, 0.00753264, 0.597936, -0.00889375, 0.490339, 0.0108478, 0.597956, -0.0121043, 0.490347, 0.0147668, 0.597992, -0.0158073, 0.490365, 0.0192905, 0.598032, -0.0200017, 0.490382, 0.0244204, 0.598109, -0.0246865, 0.49042, 0.0301593, 0.598215, -0.0298594, 0.490474, 0.03651, 0.59833, -0.0355167, 0.490524, 0.0434757, 0.598525, -0.0416559, 0.490624, 0.0510629, 0.598778, -0.0482692, 0.490753, 0.0592781, 0.599135, -0.0553114, 0.49094, 0.0681304, 0.599802, -0.062542, 0.491328, 0.0776467, 0.600361, -0.0703638, 0.491598, 0.0878184, 0.60101, -0.0786256, 0.491882, 0.0986573, 0.601811, -0.0872962, 0.492232, 0.11018, 0.602861, -0.0962284, 0.492684, 0.1224, 0.604167, -0.10538, 0.493213, 0.135354, 0.605693, -0.114896, 0.493799, 0.149034, 0.607682, -0.124654, 0.494576, 0.163469, 0.610672, -0.13456, 0.4959, 0.178747, 0.613313, -0.144581, 0.496713, 0.194723, 0.617603, -0.154703, 0.498499, 0.211617, 0.622174, -0.16489, 0.500188, 0.229183, 0.628855, -0.175164, 0.503072, 0.247786, 0.636963, -0.185565, 0.506798, 0.267116, 0.644866, -0.195911, 0.509719, 0.28702, 0.653741, -0.206104, 0.512776, 0.307763, 0.664942, -0.216447, 0.516812, 0.329631, 0.67633, -0.22552, 0.519181, 0.353515, 0.690012, -0.234316, 0.521681, 0.379226, 0.704243, -0.242032, 0.523129, 0.405901, 0.719396, -0.249172, 0.523768, 0.433585, 0.734471, -0.255543, 0.522541, 0.462085, 0.750539, -0.260697, 0.520217, 0.491233, 0.766365, -0.26501, 0.516293, 0.521094, 0.781677, -0.268409, 0.509708, 0.551014, 0.797132, -0.270399, 0.501944, 0.581463, 0.812655, -0.271247, 0.492025, 0.612402, 0.828592, -0.270708, 0.480424, 0.643798, 0.844044, -0.268085, 0.465955, 0.67682, 0.857305, -0.263459, 0.448425, 0.708496, 0.87114, -0.258151, 0.430243, 0.74046, 0.884936, -0.251171, 0.410578, 0.771583, 0.895772, -0.243305, 0.38862, 0.802234, 0.906961, -0.234037, 0.365214, 0.833179, 0.917775, -0.222714, 0.34116, 0.86353, 0.927883, -0.210175, 0.31572, 0.893557, 0.936617, -0.196925, 0.289159, 0.922976, 0.943384, -0.182788, 0.261996, 0.951606, 0.949713, -0.167965, 0.235324, 0.979958, 0.955818, -0.151109, 0.208408, 1.00765, 0.961344, -0.133834, 0.182591, 1.03329, 0.965469, -0.115987, 0.156958, 1.0557, 0.968693, -0.09746, 0.132239, 1.07583, 0.973165, -0.0778514, 0.106195, 1.09451, 0.979387, -0.0585067, 0.0797669, 1.11137, 0.98671, -0.0390409, 0.0530263, 1.12643, 0.994093, -0.019408, 0.0263163, 1.14016, 1.00002, 0.000540029, -0.000194487, 1.15299, 0.574483, -0.00000989066, 0.494533, 0.0000114896, 0.574478, -0.000249127, 0.494528, 0.000289403, 0.574607, -0.000996811, 0.494637, 0.00115797, 0.574396, -0.00224241, 0.494458, 0.00260498, 0.574377, -0.00398632, 0.49444, 0.00463102, 0.574386, -0.00622836, 0.494445, 0.00723623, 0.574401, -0.0089683, 0.494453, 0.010421, 0.574419, -0.0122056, 0.49446, 0.0141859, 0.574459, -0.0159396, 0.494481, 0.0185322, 0.574525, -0.0201692, 0.49452, 0.0234617, 0.574587, -0.0248924, 0.494547, 0.0289762, 0.574697, -0.0301074, 0.494604, 0.0350797, 0.574853, -0.0358114, 0.494688, 0.0417767, 0.575027, -0.041999, 0.494772, 0.0490718, 0.575294, -0.0486618, 0.494915, 0.0569728, 0.575733, -0.0557148, 0.495173, 0.0654955, 0.576356, -0.0630489, 0.495537, 0.0746612, 0.576944, -0.0709285, 0.495836, 0.0844615, 0.57765, -0.0792723, 0.496177, 0.0949142, 0.578491, -0.0880167, 0.496563, 0.10603, 0.579639, -0.0969462, 0.497096, 0.117841, 0.580989, -0.10622, 0.497684, 0.130367, 0.582587, -0.115861, 0.498337, 0.143609, 0.584951, -0.125605, 0.499414, 0.157625, 0.587602, -0.135608, 0.500518, 0.172413, 0.59076, -0.145742, 0.501767, 0.187999, 0.594992, -0.155934, 0.503542, 0.20445, 0.600656, -0.166303, 0.506135, 0.221764, 0.607816, -0.176681, 0.509542, 0.24002, 0.61522, -0.187071, 0.51263, 0.258992, 0.623702, -0.197465, 0.516021, 0.278773, 0.634192, -0.207816, 0.520422, 0.299377, 0.644936, -0.218183, 0.524073, 0.320802, 0.657888, -0.2278, 0.528049, 0.34384, 0.670666, -0.236747, 0.52986, 0.36916, 0.685626, -0.24484, 0.531892, 0.395867, 0.701304, -0.252071, 0.532727, 0.423488, 0.717727, -0.258714, 0.532146, 0.452201, 0.733914, -0.264211, 0.529883, 0.481579, 0.750529, -0.26859, 0.5259, 0.511558, 0.76747, -0.272046, 0.51999, 0.542042, 0.785189, -0.274225, 0.513083, 0.572799, 0.800954, -0.275189, 0.502936, 0.603816, 0.816962, -0.274946, 0.490921, 0.635461, 0.83336, -0.272695, 0.47684, 0.6676, 0.848143, -0.268223, 0.459405, 0.70051, 0.861818, -0.262768, 0.440319, 0.732902, 0.876828, -0.255872, 0.420123, 0.765084, 0.889312, -0.247703, 0.398379, 0.796391, 0.900412, -0.238381, 0.374496, 0.827333, 0.912251, -0.227783, 0.349874, 0.858385, 0.921792, -0.214832, 0.323181, 0.888652, 0.931273, -0.200949, 0.296624, 0.917763, 0.940295, -0.186537, 0.269211, 0.947878, 0.946812, -0.171538, 0.241447, 0.977016, 0.953588, -0.155254, 0.213829, 1.00501, 0.958841, -0.137156, 0.186807, 1.03179, 0.963746, -0.118699, 0.160706, 1.05502, 0.966468, -0.0998358, 0.135504, 1.07568, 0.971178, -0.0805186, 0.109131, 1.09479, 0.97831, -0.0599348, 0.0818293, 1.1123, 0.985886, -0.0399661, 0.0545872, 1.12771, 0.994021, -0.0198682, 0.0269405, 1.14186, 1.00009, 0.000271022, -0.00012989, 1.15514, 0.538716, -0.00000990918, 0.486732, 0.0000109675, 0.550656, -0.000250642, 0.497518, 0.000277412, 0.55057, -0.00100265, 0.497441, 0.00110974, 0.550903, -0.00225672, 0.497733, 0.00249779, 0.550568, -0.00401046, 0.497438, 0.00443906, 0.550574, -0.00626613, 0.49744, 0.00693637, 0.550591, -0.0090226, 0.497449, 0.00998921, 0.550623, -0.0122795, 0.497469, 0.0135984, 0.550667, -0.0160361, 0.497495, 0.0177654, 0.550724, -0.0202908, 0.497526, 0.0224915, 0.550792, -0.0250421, 0.497557, 0.0277795, 0.550918, -0.0302878, 0.49763, 0.0336334, 0.551058, -0.0360241, 0.497701, 0.0400573, 0.551276, -0.0422473, 0.497824, 0.0470585, 0.551551, -0.0489441, 0.497977, 0.0546433, 0.552074, -0.0559596, 0.498312, 0.0628367, 0.552681, -0.0633978, 0.498679, 0.071646, 0.553324, -0.0713176, 0.499031, 0.0810746, 0.554011, -0.0797268, 0.499365, 0.091129, 0.55488, -0.0885238, 0.499779, 0.101837, 0.556171, -0.0974417, 0.500444, 0.113239, 0.557498, -0.106841, 0.501025, 0.125316, 0.559299, -0.116533, 0.501864, 0.138128, 0.561647, -0.126298, 0.502967, 0.151695, 0.564347, -0.136388, 0.504129, 0.16604, 0.567863, -0.146576, 0.505713, 0.181207, 0.572569, -0.156832, 0.507953, 0.197259, 0.578919, -0.167323, 0.511186, 0.214258, 0.585387, -0.177712, 0.514042, 0.232038, 0.593134, -0.188184, 0.517484, 0.250733, 0.603295, -0.198717, 0.522345, 0.270454, 0.613854, -0.209177, 0.526751, 0.290807, 0.626092, -0.219644, 0.531595, 0.312202, 0.637868, -0.229494, 0.534721, 0.334435, 0.652458, -0.238718, 0.538304, 0.359184, 0.666985, -0.247061, 0.539875, 0.385637, 0.683301, -0.254652, 0.541042, 0.41328, 0.69998, -0.261376, 0.540735, 0.441903, 0.717824, -0.267085, 0.539139, 0.471609, 0.734617, -0.271465, 0.534958, 0.501446, 0.753663, -0.27528, 0.53032, 0.532571, 0.770512, -0.277617, 0.522134, 0.563641, 0.787356, -0.278525, 0.51206, 0.595067, 0.806252, -0.278512, 0.50119, 0.627226, 0.822061, -0.277023, 0.486791, 0.659402, 0.838959, -0.273175, 0.470467, 0.692874, 0.85379, -0.267238, 0.450688, 0.725702, 0.868268, -0.260327, 0.429741, 0.75832, 0.881994, -0.251946, 0.407223, 0.790189, 0.893885, -0.242432, 0.383214, 0.821625, 0.905118, -0.231904, 0.357297, 0.853011, 0.916045, -0.219545, 0.330733, 0.883773, 0.927614, -0.205378, 0.303916, 0.914435, 0.936005, -0.190388, 0.275941, 0.944502, 0.944533, -0.1749, 0.247493, 0.974439, 0.950758, -0.158588, 0.218996, 1.00286, 0.957078, -0.141027, 0.191559, 1.0304, 0.962448, -0.121507, 0.164457, 1.05466, 0.964993, -0.102068, 0.138636, 1.0761, 0.970017, -0.0822598, 0.111861, 1.09541, 0.97661, -0.062033, 0.0843438, 1.11317, 0.985073, -0.0409832, 0.0558496, 1.12911, 0.993515, -0.020146, 0.0275331, 1.1438, 1.00006, 0.00027329, -0.000107883, 1.15736, 0.525324, -0.00000999341, 0.498153, 0.0000105385, 0.526513, -0.000251605, 0.499277, 0.000265329, 0.526517, -0.00100641, 0.499282, 0.0010613, 0.526588, -0.00226466, 0.499337, 0.00238823, 0.526539, -0.0040255, 0.499302, 0.00424535, 0.526547, -0.00628954, 0.499306, 0.00663364, 0.526561, -0.00905628, 0.499313, 0.00955337, 0.526593, -0.0123253, 0.499334, 0.0130054, 0.526642, -0.0160957, 0.499365, 0.0169911, 0.5267, -0.0203661, 0.499396, 0.0215122, 0.526792, -0.0251347, 0.499451, 0.0265718, 0.526904, -0.0303985, 0.499511, 0.0321732, 0.527079, -0.0361554, 0.499617, 0.0383231, 0.527285, -0.0423982, 0.499731, 0.045026, 0.527602, -0.0491121, 0.499924, 0.0522936, 0.528166, -0.0561127, 0.500306, 0.0601528, 0.52879, -0.0635988, 0.5007, 0.0686059, 0.529421, -0.071581, 0.501048, 0.0776518, 0.530144, -0.0799854, 0.501421, 0.0873148, 0.531062, -0.0888032, 0.501884, 0.0976084, 0.532374, -0.0977643, 0.50259, 0.108588, 0.533828, -0.107197, 0.50329, 0.120234, 0.53581, -0.116887, 0.504312, 0.132602, 0.538063, -0.126755, 0.505365, 0.145721, 0.5409, -0.136819, 0.506668, 0.159617, 0.544882, -0.147117, 0.508731, 0.174369, 0.550238, -0.157446, 0.511601, 0.190028, 0.556038, -0.167988, 0.514431, 0.206587, 0.563031, -0.178364, 0.517808, 0.224046, 0.571543, -0.189007, 0.521937, 0.242503, 0.582255, -0.199546, 0.527415, 0.261977, 0.59272, -0.210084, 0.531682, 0.282162, 0.605648, -0.220448, 0.537123, 0.303426, 0.61785, -0.230593, 0.540664, 0.325323, 0.632223, -0.240238, 0.544467, 0.348993, 0.648819, -0.24887, 0.547594, 0.375462, 0.665825, -0.256657, 0.54912, 0.403024, 0.683389, -0.263711, 0.549294, 0.431773, 0.701495, -0.269666, 0.547649, 0.461494, 0.719197, -0.274169, 0.543786, 0.491623, 0.737906, -0.278124, 0.538644, 0.522994, 0.756652, -0.280632, 0.531057, 0.554775, 0.775279, -0.281741, 0.521972, 0.586441, 0.792688, -0.281652, 0.509613, 0.618596, 0.811894, -0.280345, 0.496497, 0.651462, 0.827938, -0.277128, 0.47968, 0.684023, 0.844837, -0.271646, 0.460688, 0.718024, 0.859239, -0.264397, 0.438872, 0.751207, 0.874088, -0.256144, 0.41577, 0.784232, 0.887693, -0.246311, 0.391369, 0.816191, 0.899402, -0.235497, 0.365872, 0.847828, 0.910973, -0.223631, 0.338618, 0.87934, 0.92204, -0.209874, 0.310803, 0.910325, 0.930987, -0.194265, 0.281802, 0.940695, 0.94, -0.178125, 0.252836, 0.970958, 0.948018, -0.161479, 0.224239, 1.00078, 0.955141, -0.144038, 0.195857, 1.0288, 0.960513, -0.124915, 0.168487, 1.05371, 0.963964, -0.104284, 0.141495, 1.07596, 0.968713, -0.0838732, 0.114437, 1.09628, 0.975524, -0.0635579, 0.0863105, 1.11448, 0.98431, -0.042291, 0.0574774, 1.13069, 0.992916, -0.0209131, 0.0284343, 1.14568, 0.999926, 0.000743097, -0.000379265, 1.15955, 0.501042, -0.00000998428, 0.498726, 0.0000100306, 0.502992, -0.000252112, 0.500665, 0.000253283, 0.502417, -0.00100791, 0.500092, 0.00101259, 0.502965, -0.00226919, 0.500621, 0.00227978, 0.502318, -0.00403109, 0.499994, 0.00405011, 0.502333, -0.00629832, 0.500005, 0.00632868, 0.502362, -0.00906907, 0.500027, 0.00911446, 0.502369, -0.0123423, 0.500023, 0.0124078, 0.50243, -0.0161178, 0.500066, 0.016211, 0.502493, -0.0203937, 0.500103, 0.0205256, 0.502592, -0.0251684, 0.500166, 0.0253548, 0.502707, -0.0304389, 0.50023, 0.0307029, 0.502881, -0.0362015, 0.500335, 0.0365753, 0.503124, -0.0424507, 0.500488, 0.0429798, 0.503443, -0.0491582, 0.500686, 0.0499268, 0.504083, -0.0561476, 0.501155, 0.0574541, 0.504668, -0.0636846, 0.501524, 0.0655408, 0.505319, -0.0716834, 0.501904, 0.0742072, 0.50609, -0.0800925, 0.502321, 0.0834699, 0.507122, -0.0888425, 0.502896, 0.0933603, 0.508414, -0.097855, 0.503603, 0.10391, 0.509955, -0.107304, 0.504416, 0.115113, 0.512061, -0.116921, 0.505565, 0.127054, 0.514419, -0.12689, 0.506732, 0.139709, 0.517529, -0.136934, 0.508338, 0.153173, 0.522085, -0.147327, 0.510987, 0.167528, 0.526986, -0.157612, 0.513527, 0.182708, 0.533122, -0.168213, 0.516717, 0.198881, 0.540807, -0.178688, 0.520832, 0.215986, 0.550687, -0.189511, 0.52632, 0.234335, 0.560567, -0.199998, 0.531009, 0.253375, 0.571698, -0.210652, 0.535839, 0.273499, 0.584364, -0.220917, 0.541091, 0.294355, 0.599066, -0.23137, 0.546875, 0.316525, 0.614148, -0.241206, 0.551306, 0.339671, 0.631157, -0.250379, 0.555187, 0.36531, 0.647919, -0.258397, 0.556595, 0.392767, 0.666112, -0.265528, 0.556949, 0.421397, 0.686158, -0.271827, 0.556617, 0.451433, 0.704838, -0.27674, 0.552975, 0.482131, 0.723957, -0.280733, 0.547814, 0.513458, 0.74262, -0.283359, 0.53997, 0.545446, 0.762009, -0.284541, 0.530422, 0.57775, 0.781314, -0.284507, 0.518546, 0.610434, 0.799116, -0.283309, 0.504178, 0.643178, 0.817604, -0.280378, 0.48843, 0.676248, 0.83459, -0.275619, 0.469457, 0.709698, 0.850974, -0.26856, 0.447698, 0.744245, 0.866747, -0.260094, 0.424791, 0.777695, 0.881412, -0.249929, 0.399913, 0.810392, 0.8936, -0.239137, 0.37308, 0.842872, 0.905943, -0.226818, 0.345705, 0.874677, 0.916408, -0.213699, 0.31706, 0.906257, 0.927215, -0.198428, 0.288444, 0.936881, 0.935625, -0.181643, 0.258329, 0.96795, 0.944076, -0.164386, 0.228488, 0.998216, 0.951229, -0.146339, 0.199763, 1.02689, 0.958793, -0.127709, 0.172153, 1.0535, 0.963219, -0.107244, 0.144989, 1.07646, 0.967562, -0.0857764, 0.11685, 1.09675, 0.974866, -0.0645377, 0.0880571, 1.11576, 0.983353, -0.0431732, 0.0587352, 1.13227, 0.992503, -0.0218356, 0.0294181, 1.1478, 1.00003, 0.000605203, -0.000231013, 1.16207, 0.482935, -0.0000101177, 0.504695, 0.00000968142, 0.477554, -0.000251521, 0.499071, 0.000240676, 0.477904, -0.00100683, 0.499436, 0.00096342, 0.478368, -0.00226636, 0.499899, 0.0021687, 0.477977, -0.00402719, 0.499513, 0.00385384, 0.477993, -0.00629226, 0.499525, 0.0060221, 0.478011, -0.00906011, 0.499536, 0.00867289, 0.478051, -0.0123305, 0.499566, 0.0118074, 0.478089, -0.016102, 0.499587, 0.0154269, 0.478171, -0.0203736, 0.499645, 0.0195341, 0.478254, -0.025143, 0.499692, 0.0241318, 0.47839, -0.0304071, 0.499779, 0.0292247, 0.478588, -0.0361631, 0.499911, 0.0348196, 0.478812, -0.0424023, 0.500046, 0.0409231, 0.479208, -0.0490724, 0.500326, 0.047552, 0.479841, -0.0560722, 0.500805, 0.0547377, 0.480392, -0.0636125, 0.501152, 0.0624607, 0.481068, -0.0716134, 0.501561, 0.0707473, 0.481898, -0.0800062, 0.502054, 0.0796118, 0.483022, -0.0886568, 0.502728, 0.0890974, 0.484332, -0.0977553, 0.503479, 0.0992099, 0.486126, -0.107173, 0.504546, 0.10999, 0.488066, -0.11677, 0.50557, 0.121476, 0.490521, -0.126725, 0.506849, 0.133672, 0.494232, -0.136793, 0.50911, 0.146731, 0.498302, -0.147116, 0.511345, 0.160577, 0.503565, -0.157446, 0.514344, 0.175335, 0.510902, -0.168121, 0.518824, 0.191207, 0.519263, -0.178799, 0.523666, 0.208058, 0.528204, -0.189407, 0.528296, 0.225875, 0.538854, -0.200145, 0.533724, 0.244782, 0.551278, -0.210701, 0.539833, 0.264753, 0.565222, -0.221303, 0.546131, 0.285745, 0.579403, -0.231688, 0.551496, 0.307592, 0.595469, -0.241718, 0.556809, 0.330582, 0.610929, -0.250992, 0.559641, 0.354995, 0.629433, -0.259602, 0.562379, 0.382471, 0.648504, -0.267038, 0.563676, 0.411126, 0.66756, -0.273388, 0.562092, 0.440924, 0.689143, -0.278788, 0.560807, 0.472118, 0.709056, -0.282783, 0.555701, 0.503774, 0.729855, -0.285836, 0.548698, 0.536364, 0.748954, -0.287078, 0.538544, 0.56895, 0.768373, -0.287133, 0.526711, 0.601991, 0.78827, -0.285839, 0.512511, 0.635403, 0.807465, -0.283238, 0.496323, 0.668797, 0.825194, -0.27906, 0.477638, 0.702584, 0.842203, -0.272286, 0.456253, 0.736393, 0.857749, -0.263854, 0.432412, 0.77096, 0.874799, -0.253943, 0.407806, 0.80489, 0.887497, -0.24237, 0.38033, 0.83771, 0.89966, -0.230278, 0.352446, 0.870376, 0.911753, -0.21646, 0.323268, 0.902256, 0.923011, -0.202071, 0.294314, 0.933306, 0.932375, -0.185519, 0.264104, 0.965177, 0.940537, -0.167604, 0.234035, 0.996303, 0.948904, -0.149068, 0.20412, 1.0261, 0.955263, -0.129539, 0.175431, 1.05304, 0.960303, -0.109932, 0.148116, 1.07617, 0.965512, -0.0880572, 0.119693, 1.09742, 0.973466, -0.0660548, 0.0901619, 1.11721, 0.98284, -0.0439228, 0.0599875, 1.13436, 0.992216, -0.0219588, 0.0298975, 1.15006, 0.999946, 0.000119402, -0.0000208547, 1.16471, 0.447827, -0.0000100414, 0.491543, 0.00000914833, 0.454778, -0.000251257, 0.499172, 0.00022891, 0.453519, -0.00100342, 0.497787, 0.000914184, 0.45357, -0.00225776, 0.497847, 0.00205701, 0.453578, -0.00401371, 0.497855, 0.00365705, 0.45357, -0.00627107, 0.497841, 0.00571453, 0.453598, -0.00902968, 0.497864, 0.00823019, 0.453627, -0.0122888, 0.497882, 0.0112049, 0.453684, -0.0160475, 0.497923, 0.0146405, 0.453764, -0.0203044, 0.49798, 0.0185394, 0.453866, -0.0250576, 0.498049, 0.0229054, 0.453996, -0.0303028, 0.49813, 0.0277424, 0.454196, -0.0360379, 0.498267, 0.0330587, 0.454457, -0.0422521, 0.498445, 0.0388613, 0.454926, -0.0488393, 0.498812, 0.0451767, 0.455525, -0.0558653, 0.499272, 0.0520153, 0.456074, -0.0633772, 0.499625, 0.0593754, 0.456752, -0.0713606, 0.500049, 0.0672751, 0.457648, -0.07971, 0.500615, 0.0757447, 0.458849, -0.0883032, 0.501399, 0.0848231, 0.46029, -0.0974095, 0.502293, 0.0945135, 0.462, -0.106729, 0.503301, 0.104848, 0.464121, -0.116354, 0.504533, 0.115884, 0.466889, -0.126214, 0.506172, 0.127652, 0.470744, -0.136324, 0.508667, 0.14024, 0.47488, -0.146595, 0.510995, 0.153673, 0.480845, -0.157027, 0.514832, 0.168053, 0.488262, -0.167658, 0.519506, 0.183508, 0.496547, -0.178343, 0.524347, 0.199948, 0.506254, -0.188916, 0.52983, 0.217503, 0.517961, -0.199975, 0.536357, 0.236272, 0.531484, -0.210624, 0.543641, 0.256096, 0.545496, -0.221227, 0.550048, 0.277085, 0.559497, -0.231568, 0.555076, 0.298615, 0.575752, -0.241698, 0.560541, 0.321547, 0.591999, -0.251172, 0.564156, 0.345602, 0.610654, -0.260178, 0.567607, 0.371851, 0.630484, -0.268094, 0.56923, 0.40076, 0.651807, -0.274661, 0.569779, 0.430801, 0.67239, -0.280331, 0.566791, 0.461939, 0.693024, -0.284501, 0.562007, 0.493854, 0.715473, -0.287852, 0.555791, 0.526992, 0.736323, -0.28929, 0.546345, 0.560102, 0.755771, -0.289405, 0.534, 0.593543, 0.775424, -0.2881, 0.519114, 0.627256, 0.795447, -0.285562, 0.502543, 0.661464, 0.815319, -0.281416, 0.484773, 0.695206, 0.831769, -0.275523, 0.463445, 0.729044, 0.849464, -0.267516, 0.440269, 0.764069, 0.866775, -0.257584, 0.415049, 0.799089, 0.881252, -0.245817, 0.388049, 0.831948, 0.894209, -0.233127, 0.35889, 0.865526, 0.906922, -0.219579, 0.329915, 0.89818, 0.919686, -0.204491, 0.300441, 0.930013, 0.929044, -0.188962, 0.269445, 0.962061, 0.938393, -0.171079, 0.238402, 0.994214, 0.94661, -0.15199, 0.208204, 1.02533, 0.953095, -0.131953, 0.178653, 1.0529, 0.958644, -0.111233, 0.150684, 1.0771, 0.963925, -0.0903098, 0.122359, 1.09855, 0.971995, -0.0680505, 0.0923342, 1.11874, 0.981658, -0.0448512, 0.0614195, 1.13635, 0.991649, -0.0221931, 0.0303582, 1.15238, 0.999985, 0.000393403, -0.000111086, 1.16772, 0.396806, -0.00000971563, 0.457671, 0.00000842355, 0.429186, -0.000249421, 0.495017, 0.00021625, 0.429324, -0.000998052, 0.495173, 0.000865322, 0.429175, -0.00224487, 0.494999, 0.00194637, 0.429129, -0.00399041, 0.494952, 0.00346004, 0.429153, -0.00623476, 0.494974, 0.00540684, 0.429168, -0.0089773, 0.494983, 0.00778714, 0.429207, -0.0122175, 0.495012, 0.0106022, 0.429257, -0.0159542, 0.495047, 0.0138535, 0.429338, -0.0201864, 0.495106, 0.0175443, 0.429431, -0.0249104, 0.495165, 0.0216774, 0.429587, -0.0301252, 0.495279, 0.0262594, 0.429796, -0.0358249, 0.495432, 0.0312968, 0.430065, -0.0419972, 0.495621, 0.0367985, 0.430588, -0.0485144, 0.496061, 0.042798, 0.43113, -0.0555028, 0.496472, 0.0492914, 0.431743, -0.0629852, 0.496904, 0.0562907, 0.432448, -0.0709256, 0.497369, 0.0638056, 0.433414, -0.0791942, 0.498032, 0.071885, 0.434638, -0.0877346, 0.498854, 0.0805517, 0.43611, -0.0968056, 0.499812, 0.0898047, 0.437859, -0.106002, 0.500891, 0.0997142, 0.440017, -0.115648, 0.502198, 0.110289, 0.443236, -0.125427, 0.504389, 0.121644, 0.44697, -0.135492, 0.506809, 0.133769, 0.451689, -0.145746, 0.509858, 0.146787, 0.45811, -0.156219, 0.514247, 0.160793, 0.465305, -0.166834, 0.518816, 0.175791, 0.474085, -0.177546, 0.524331, 0.191906, 0.484808, -0.188262, 0.53104, 0.209199, 0.49732, -0.199346, 0.538511, 0.227825, 0.509693, -0.209951, 0.544554, 0.247269, 0.524367, -0.220533, 0.551616, 0.267978, 0.539228, -0.231082, 0.557368, 0.289672, 0.55644, -0.241342, 0.563782, 0.31268, 0.574204, -0.250964, 0.568851, 0.33651, 0.593388, -0.260306, 0.57312, 0.362219, 0.613358, -0.268667, 0.574916, 0.390322, 0.634512, -0.275591, 0.575053, 0.420478, 0.65563, -0.281328, 0.572404, 0.451614, 0.678265, -0.285948, 0.568893, 0.484112, 0.70011, -0.289408, 0.561878, 0.517348, 0.723005, -0.291328, 0.55359, 0.551355, 0.743744, -0.291418, 0.541099, 0.585109, 0.763949, -0.290252, 0.526489, 0.619487, 0.784186, -0.287648, 0.509496, 0.65404, 0.804304, -0.283782, 0.491484, 0.688649, 0.823629, -0.278067, 0.470517, 0.723133, 0.84094, -0.270588, 0.44705, 0.757163, 0.857852, -0.261188, 0.421252, 0.792816, 0.874934, -0.249313, 0.394191, 0.827248, 0.888709, -0.236492, 0.365359, 0.861074, 0.902589, -0.222185, 0.336016, 0.894417, 0.914201, -0.207314, 0.30527, 0.926825, 0.925978, -0.191146, 0.274532, 0.9595, 0.93512, -0.174135, 0.243393, 0.991583, 0.943656, -0.155231, 0.212414, 1.02356, 0.951719, -0.134403, 0.182005, 1.05239, 0.957164, -0.113023, 0.153043, 1.07754, 0.962656, -0.0914493, 0.124186, 1.09984, 0.970695, -0.0694179, 0.0941654, 1.12, 0.980749, -0.0466199, 0.0629671, 1.13849, 0.991205, -0.0227032, 0.0311146, 1.15494, 0.999884, 0.000632388, -0.000254483, 1.1706, 0.379821, -0.00000957289, 0.460637, 0.00000789337, 0.405188, -0.000247483, 0.491396, 0.000204064, 0.404796, -0.000989434, 0.490914, 0.000815853, 0.40483, -0.00222607, 0.490949, 0.00183559, 0.40473, -0.00395723, 0.49084, 0.00326332, 0.404731, -0.00618287, 0.490836, 0.00509945, 0.404768, -0.00890258, 0.490871, 0.00734463, 0.404791, -0.0121156, 0.490883, 0.00999992, 0.404857, -0.0158214, 0.490938, 0.0130676, 0.404943, -0.0200178, 0.491004, 0.0165503, 0.405059, -0.0247027, 0.491093, 0.0204521, 0.405213, -0.0298729, 0.491205, 0.0247788, 0.405399, -0.0355226, 0.491333, 0.0295373, 0.405731, -0.0416352, 0.491604, 0.034741, 0.406303, -0.0480807, 0.492116, 0.0404255, 0.406814, -0.0550458, 0.492506, 0.0465732, 0.407404, -0.0624652, 0.492926, 0.0532058, 0.408149, -0.0702958, 0.493442, 0.0603442, 0.409128, -0.0784623, 0.494136, 0.0680297, 0.410408, -0.087007, 0.495054, 0.0762786, 0.411813, -0.0959639, 0.495962, 0.0851046, 0.413735, -0.105075, 0.497257, 0.0945878, 0.416137, -0.114646, 0.498882, 0.104725, 0.41934, -0.124394, 0.501132, 0.11563, 0.423326, -0.134328, 0.503883, 0.127325, 0.428419, -0.14458, 0.50747, 0.139911, 0.43484, -0.154979, 0.511964, 0.153481, 0.442641, -0.165628, 0.517328, 0.168114, 0.452511, -0.176365, 0.524258, 0.183995, 0.463473, -0.187298, 0.531248, 0.200953, 0.475564, -0.198244, 0.538367, 0.219176, 0.488664, -0.208938, 0.545175, 0.238514, 0.504073, -0.219599, 0.553227, 0.259129, 0.520832, -0.230378, 0.560653, 0.280997, 0.538455, -0.240703, 0.567523, 0.303821, 0.55709, -0.250548, 0.573287, 0.327948, 0.576646, -0.259964, 0.577795, 0.353362, 0.596705, -0.268721, 0.580077, 0.380336, 0.618053, -0.276054, 0.58018, 0.4101, 0.640303, -0.282176, 0.578747, 0.44161, 0.662365, -0.286931, 0.574294, 0.474106, 0.684542, -0.290521, 0.567035, 0.507549, 0.707984, -0.292672, 0.558687, 0.541853, 0.730913, -0.293189, 0.547606, 0.576581, 0.752948, -0.292199, 0.533471, 0.61172, 0.773452, -0.289508, 0.516395, 0.646339, 0.794715, -0.285716, 0.497873, 0.682131, 0.814251, -0.280051, 0.476845, 0.716396, 0.833057, -0.272873, 0.453449, 0.751503, 0.84959, -0.263982, 0.427857, 0.786085, 0.867022, -0.252745, 0.400335, 0.821355, 0.882277, -0.239655, 0.371304, 0.85646, 0.895375, -0.225386, 0.340397, 0.890828, 0.909347, -0.209587, 0.310005, 0.923532, 0.921885, -0.193433, 0.2796, 0.956419, 0.932127, -0.176135, 0.247276, 0.989445, 0.941869, -0.157872, 0.216186, 1.02221, 0.949735, -0.137577, 0.185602, 1.05195, 0.956617, -0.115285, 0.155767, 1.07822, 0.961974, -0.0928418, 0.126103, 1.10149, 0.96972, -0.0700592, 0.0956758, 1.12207, 0.98012, -0.0474671, 0.0643269, 1.1408, 0.990825, -0.0238113, 0.0320863, 1.1577, 0.999876, 0.000381574, -0.0000812203, 1.17403, 0.367636, -0.00000961342, 0.469176, 0.00000753287, 0.380377, -0.000244772, 0.485434, 0.000191797, 0.380416, -0.000978857, 0.485475, 0.000767015, 0.380376, -0.00220165, 0.485435, 0.00172522, 0.380419, -0.00391408, 0.485487, 0.00306734, 0.380438, -0.00611549, 0.485505, 0.00479332, 0.380462, -0.00880558, 0.485525, 0.00690391, 0.380496, -0.0119837, 0.485551, 0.00940039, 0.38056, -0.0156487, 0.485605, 0.0122848, 0.38064, -0.0197988, 0.485666, 0.0155601, 0.380767, -0.0244324, 0.48577, 0.0192313, 0.380909, -0.0295444, 0.485871, 0.0233032, 0.381142, -0.0351321, 0.48606, 0.0277861, 0.381472, -0.0411535, 0.486336, 0.0326939, 0.382015, -0.0475408, 0.486833, 0.0380565, 0.382523, -0.0544395, 0.487231, 0.0438615, 0.383129, -0.061784, 0.487683, 0.0501332, 0.383952, -0.0695085, 0.488313, 0.0568996, 0.38498, -0.0775819, 0.489077, 0.0641952, 0.386331, -0.0860443, 0.490113, 0.0720324, 0.387788, -0.0948406, 0.491099, 0.0804379, 0.389808, -0.103899, 0.492566, 0.0894899, 0.39252, -0.113313, 0.494601, 0.0992098, 0.395493, -0.123007, 0.496619, 0.109641, 0.399826, -0.132859, 0.499912, 0.120919, 0.405341, -0.143077, 0.504061, 0.133107, 0.411932, -0.153465, 0.508905, 0.146263, 0.420591, -0.164108, 0.515482, 0.160544, 0.43101, -0.174893, 0.523191, 0.176123, 0.441881, -0.185839, 0.53026, 0.192757, 0.453919, -0.196633, 0.537295, 0.210535, 0.468715, -0.207611, 0.546156, 0.229886, 0.485182, -0.218517, 0.555173, 0.250543, 0.501926, -0.229249, 0.562728, 0.27221, 0.51785, -0.239481, 0.567494, 0.294892, 0.536947, -0.249395, 0.573889, 0.318987, 0.557115, -0.259, 0.578831, 0.344348, 0.577966, -0.268075, 0.582055, 0.371223, 0.599489, -0.276115, 0.583307, 0.399834, 0.62479, -0.282523, 0.583902, 0.431415, 0.647504, -0.287663, 0.57953, 0.464301, 0.670601, -0.291538, 0.573103, 0.498123, 0.693539, -0.293842, 0.563731, 0.532662, 0.717385, -0.294681, 0.553169, 0.567925, 0.741533, -0.293717, 0.539908, 0.603502, 0.762142, -0.291156, 0.521902, 0.639074, 0.783014, -0.28719, 0.502815, 0.674439, 0.805158, -0.281773, 0.482598, 0.710497, 0.823646, -0.274682, 0.458949, 0.7456, 0.841879, -0.266184, 0.433129, 0.781085, 0.859515, -0.255682, 0.406064, 0.816, 0.875335, -0.242849, 0.376509, 0.851074, 0.890147, -0.228329, 0.345502, 0.886473, 0.903144, -0.212491, 0.31428, 0.920751, 0.916618, -0.195695, 0.282994, 0.954606, 0.927953, -0.178267, 0.251091, 0.988402, 0.937414, -0.159549, 0.219107, 1.02141, 0.946823, -0.140022, 0.18896, 1.05167, 0.954651, -0.118154, 0.158667, 1.07819, 0.959955, -0.0946636, 0.128808, 1.1025, 0.96858, -0.0711792, 0.0973787, 1.12391, 0.97938, -0.0475046, 0.0650965, 1.14322, 0.990498, -0.024059, 0.0326267, 1.16077, 0.999844, -0.0000512408, 0.000112444, 1.17727, 0.316912, -0.00000934977, 0.425996, 0.00000695559, 0.356423, -0.000241372, 0.479108, 0.000179562, 0.356272, -0.000965292, 0.478897, 0.00071811, 0.356262, -0.00217182, 0.478894, 0.00161574, 0.356265, -0.00386092, 0.478895, 0.00287261, 0.356278, -0.0060324, 0.478905, 0.00448907, 0.356293, -0.00868565, 0.478914, 0.00646572, 0.356346, -0.0118207, 0.478965, 0.00880438, 0.356395, -0.0154355, 0.479001, 0.0115066, 0.356484, -0.019529, 0.479075, 0.0145762, 0.356609, -0.0240991, 0.47918, 0.018018, 0.356766, -0.0291413, 0.479305, 0.0218379, 0.357009, -0.0346498, 0.479512, 0.0260454, 0.357424, -0.0405462, 0.479909, 0.0306657, 0.357899, -0.0468825, 0.480337, 0.0357054, 0.358424, -0.0536887, 0.480771, 0.0411728, 0.359041, -0.0609416, 0.481242, 0.0470841, 0.359903, -0.0685239, 0.481943, 0.0534831, 0.360932, -0.0764883, 0.482741, 0.0603795, 0.362196, -0.0848364, 0.483688, 0.0678028, 0.363847, -0.0935002, 0.484947, 0.0758086, 0.365972, -0.102471, 0.486588, 0.0844173, 0.368741, -0.111751, 0.488787, 0.0937199, 0.372146, -0.121334, 0.491405, 0.103732, 0.377114, -0.131147, 0.495604, 0.114608, 0.38226, -0.141213, 0.499436, 0.126345, 0.389609, -0.151632, 0.505334, 0.139116, 0.397925, -0.162073, 0.51168, 0.152995, 0.407824, -0.172819, 0.518876, 0.168071, 0.420014, -0.183929, 0.527639, 0.184495, 0.434266, -0.195032, 0.537588, 0.20232, 0.447352, -0.205792, 0.544379, 0.221189, 0.463726, -0.216704, 0.553422, 0.241616, 0.481406, -0.227531, 0.562074, 0.263298, 0.498707, -0.238017, 0.568227, 0.286116, 0.518039, -0.247936, 0.574473, 0.3101, 0.538277, -0.257437, 0.579191, 0.335401, 0.561166, -0.266829, 0.584807, 0.362246, 0.583189, -0.275329, 0.586476, 0.390609, 0.606024, -0.28234, 0.585578, 0.420998, 0.632419, -0.287924, 0.584496, 0.454357, 0.656128, -0.291972, 0.577766, 0.488233, 0.679953, -0.29456, 0.56875, 0.523248, 0.704654, -0.295816, 0.558388, 0.559168, 0.729016, -0.295157, 0.544826, 0.595326, 0.752062, -0.292779, 0.528273, 0.631864, 0.773138, -0.288681, 0.508482, 0.667793, 0.794869, -0.283358, 0.487341, 0.704035, 0.815101, -0.27608, 0.46354, 0.739925, 0.834212, -0.26767, 0.438672, 0.775539, 0.852368, -0.257397, 0.411239, 0.810895, 0.870207, -0.245689, 0.3829, 0.846472, 0.884063, -0.231452, 0.351496, 0.881788, 0.898284, -0.215561, 0.31895, 0.917438, 0.912964, -0.198208, 0.287367, 0.952422, 0.924666, -0.180426, 0.254487, 0.987551, 0.934429, -0.161525, 0.222226, 1.02142, 0.943485, -0.141197, 0.191143, 1.05218, 0.9521, -0.120085, 0.161112, 1.07937, 0.957876, -0.0975881, 0.130982, 1.10403, 0.966943, -0.0726842, 0.0990553, 1.12616, 0.978313, -0.0483705, 0.0662818, 1.14619, 0.990048, -0.0239072, 0.0329243, 1.16413, 0.999984, 0.000461885, -0.0000772859, 1.18099, 0.321287, -0.00000935049, 0.455413, 0.00000659662, 0.332595, -0.000237513, 0.471437, 0.000167562, 0.332729, -0.000949964, 0.471618, 0.000670192, 0.332305, -0.00213618, 0.471028, 0.00150712, 0.332326, -0.00379765, 0.471055, 0.00267959, 0.332344, -0.00593353, 0.471072, 0.00418751, 0.332356, -0.00854349, 0.471077, 0.00603172, 0.332403, -0.0116268, 0.471121, 0.00821362, 0.332461, -0.0151824, 0.47117, 0.0107357, 0.332552, -0.0192088, 0.471251, 0.0136014, 0.332657, -0.0237024, 0.47133, 0.0168152, 0.332835, -0.0286615, 0.471487, 0.0203853, 0.333083, -0.0340765, 0.471708, 0.0243212, 0.333547, -0.0398563, 0.47219, 0.0286518, 0.333989, -0.0460916, 0.472587, 0.0333763, 0.334532, -0.0527897, 0.473054, 0.0385084, 0.335167, -0.0599284, 0.473568, 0.0440638, 0.33608, -0.0673514, 0.474362, 0.0500962, 0.337146, -0.0752237, 0.475231, 0.0566022, 0.338462, -0.083418, 0.476282, 0.0636272, 0.34014, -0.0919382, 0.477615, 0.0712153, 0.342341, -0.100741, 0.479404, 0.079417, 0.345088, -0.109905, 0.481618, 0.0882631, 0.349049, -0.119369, 0.485081, 0.0978851, 0.353939, -0.129033, 0.489317, 0.108336, 0.359893, -0.139038, 0.494309, 0.119698, 0.366945, -0.149411, 0.499983, 0.132024, 0.375814, -0.159843, 0.507185, 0.145558, 0.387112, -0.170664, 0.516392, 0.160433, 0.40023, -0.181897, 0.526519, 0.176648, 0.412555, -0.192785, 0.53423, 0.193922, 0.427023, -0.203663, 0.542741, 0.212662, 0.443685, -0.214695, 0.552066, 0.232944, 0.461499, -0.225561, 0.560762, 0.254495, 0.480975, -0.236257, 0.569421, 0.277531, 0.501, -0.24639, 0.576101, 0.301724, 0.521691, -0.256101, 0.581493, 0.327112, 0.543478, -0.265289, 0.585221, 0.353917, 0.566094, -0.273938, 0.587614, 0.381941, 0.589578, -0.281679, 0.587991, 0.41172, 0.614583, -0.287655, 0.585928, 0.444148, 0.641813, -0.292228, 0.582092, 0.478617, 0.666189, -0.295172, 0.57398, 0.51397, 0.690475, -0.29648, 0.561676, 0.550118, 0.715543, -0.296203, 0.548758, 0.586933, 0.740405, -0.293999, 0.532792, 0.62384, 0.762183, -0.28998, 0.512735, 0.660723, 0.786069, -0.28478, 0.492402, 0.69807, 0.806812, -0.277568, 0.469058, 0.734422, 0.826987, -0.268951, 0.443017, 0.770946, 0.844588, -0.259049, 0.415501, 0.80699, 0.863725, -0.2471, 0.387328, 0.842107, 0.879137, -0.234157, 0.356108, 0.878078, 0.894634, -0.218719, 0.324315, 0.914058, 0.909162, -0.201293, 0.291813, 0.949922, 0.92072, -0.18267, 0.258474, 0.985337, 0.93158, -0.163212, 0.225593, 1.0205, 0.941238, -0.142771, 0.193986, 1.05273, 0.949293, -0.120956, 0.163392, 1.08075, 0.956226, -0.0985743, 0.132934, 1.10559, 0.96546, -0.075118, 0.101255, 1.12823, 0.977403, -0.0497921, 0.0675441, 1.149, 0.989648, -0.0241574, 0.0334681, 1.16765, 1.00001, 0.0005762, -0.000184807, 1.18519, 0.303474, -0.00000916603, 0.4542, 0.0000061243, 0.308894, -0.000232869, 0.462306, 0.000155592, 0.309426, -0.000931661, 0.463093, 0.000622499, 0.308643, -0.0020949, 0.461933, 0.00139979, 0.308651, -0.0037242, 0.461941, 0.00248874, 0.308662, -0.00581873, 0.46195, 0.00388933, 0.308687, -0.00837818, 0.461974, 0.00560247, 0.308728, -0.0114016, 0.462011, 0.00762948, 0.308789, -0.0148884, 0.462067, 0.00997326, 0.308882, -0.0188369, 0.462151, 0.0126375, 0.309007, -0.0232436, 0.462263, 0.0156271, 0.30918, -0.0281054, 0.462417, 0.0189498, 0.309442, -0.0334065, 0.462667, 0.0226167, 0.309901, -0.0390589, 0.463162, 0.0266614, 0.310331, -0.0452042, 0.463555, 0.0310715, 0.310858, -0.0517735, 0.464019, 0.0358698, 0.311576, -0.0587359, 0.464669, 0.0410848, 0.312436, -0.0660383, 0.465406, 0.0467453, 0.313526, -0.0737266, 0.466339, 0.0528718, 0.314903, -0.0817574, 0.467504, 0.0595039, 0.316814, -0.090167, 0.469226, 0.0666888, 0.318965, -0.0987555, 0.470981, 0.0744658, 0.322077, -0.107792, 0.473814, 0.082912, 0.325947, -0.117098, 0.477241, 0.0920846, 0.331008, -0.126602, 0.48184, 0.102137, 0.337893, -0.136619, 0.488334, 0.113135, 0.345106, -0.146838, 0.494415, 0.12511, 0.355111, -0.157357, 0.503275, 0.138356, 0.365095, -0.167955, 0.510966, 0.152686, 0.378344, -0.179157, 0.521508, 0.16856, 0.391599, -0.190143, 0.530455, 0.18561, 0.407786, -0.20123, 0.541275, 0.204308, 0.425294, -0.212456, 0.551784, 0.224623, 0.444021, -0.223568, 0.561493, 0.246172, 0.463418, -0.234154, 0.569886, 0.268979, 0.484077, -0.244546, 0.577116, 0.293411, 0.505513, -0.254301, 0.582914, 0.318936, 0.527672, -0.263564, 0.587208, 0.345856, 0.550565, -0.272332, 0.589277, 0.374054, 0.573656, -0.280011, 0.588426, 0.403276, 0.59827, -0.286924, 0.587504, 0.43474, 0.624731, -0.291994, 0.583401, 0.468767, 0.652396, -0.295159, 0.576997, 0.504411, 0.67732, -0.296954, 0.565863, 0.54114, 0.703147, -0.296877, 0.552316, 0.57816, 0.728715, -0.295147, 0.536773, 0.616124, 0.752448, -0.291275, 0.51771, 0.653885, 0.775169, -0.285905, 0.496087, 0.691537, 0.799307, -0.279064, 0.474232, 0.729251, 0.819482, -0.270294, 0.447676, 0.766267, 0.837659, -0.260032, 0.419656, 0.802616, 0.856903, -0.248497, 0.391328, 0.838583, 0.873325, -0.235252, 0.360285, 0.874711, 0.889788, -0.221126, 0.329215, 0.91077, 0.904486, -0.204304, 0.296392, 0.94653, 0.917711, -0.185562, 0.262159, 0.983828, 0.928969, -0.165635, 0.229142, 1.01955, 0.939707, -0.14442, 0.19673, 1.05317, 0.948167, -0.122147, 0.165095, 1.0823, 0.955222, -0.099098, 0.13451, 1.10791, 0.964401, -0.0755332, 0.102476, 1.1312, 0.976605, -0.0513817, 0.0689667, 1.15218, 0.989085, -0.0258499, 0.034506, 1.17129, 0.999908, 0.000617773, -0.000271268, 1.18961, 0.285803, -0.00000905752, 0.452348, 0.00000572272, 0.284689, -0.00022732, 0.450581, 0.000143626, 0.285263, -0.000910214, 0.451482, 0.000575099, 0.285302, -0.00204784, 0.451553, 0.00129395, 0.285318, -0.00364057, 0.451574, 0.0023006, 0.28533, -0.00568813, 0.451585, 0.00359547, 0.285361, -0.00819001, 0.451618, 0.00517934, 0.285397, -0.0111458, 0.45165, 0.007054, 0.285447, -0.0145536, 0.451688, 0.00922167, 0.285527, -0.0184127, 0.451758, 0.0116869, 0.285688, -0.0227207, 0.451929, 0.0144555, 0.28584, -0.0274712, 0.452055, 0.0175341, 0.286136, -0.0326278, 0.452369, 0.0209406, 0.286574, -0.0381792, 0.452853, 0.0246965, 0.287012, -0.0441879, 0.453272, 0.0287996, 0.287542, -0.0506096, 0.453752, 0.033268, 0.288299, -0.0573634, 0.454488, 0.0381504, 0.289186, -0.0645458, 0.455294, 0.0434447, 0.290302, -0.0720405, 0.456301, 0.0491973, 0.291776, -0.0799046, 0.457648, 0.0554453, 0.29372, -0.088117, 0.459483, 0.0622311, 0.296052, -0.0965328, 0.461571, 0.0695992, 0.299563, -0.105409, 0.465085, 0.077658, 0.30335, -0.114553, 0.468506, 0.0864176, 0.309167, -0.123917, 0.474423, 0.0961078, 0.31529, -0.13381, 0.47995, 0.106643, 0.324163, -0.144021, 0.488592, 0.118322, 0.333272, -0.154382, 0.496461, 0.131133, 0.344224, -0.165015, 0.50562, 0.145208, 0.357733, -0.176168, 0.516719, 0.16073, 0.373046, -0.187468, 0.528513, 0.177807, 0.38788, -0.198488, 0.537713, 0.196072, 0.405133, -0.209545, 0.547999, 0.21605, 0.423845, -0.220724, 0.55759, 0.237484, 0.443777, -0.231518, 0.566246, 0.26039, 0.464824, -0.242035, 0.574326, 0.284835, 0.486635, -0.251898, 0.58037, 0.310518, 0.51012, -0.261304, 0.58568, 0.337678, 0.535301, -0.270384, 0.590197, 0.366242, 0.559193, -0.27841, 0.590569, 0.395873, 0.583544, -0.285325, 0.588161, 0.426857, 0.608834, -0.291113, 0.584249, 0.459477, 0.635753, -0.294882, 0.57763, 0.494734, 0.664367, -0.297088, 0.569479, 0.532023, 0.689688, -0.297364, 0.555064, 0.569629, 0.715732, -0.295949, 0.539522, 0.608124, 0.741307, -0.292259, 0.521613, 0.646231, 0.764949, -0.287063, 0.49969, 0.684938, 0.788599, -0.28012, 0.476747, 0.723548, 0.81048, -0.27153, 0.45116, 0.761135, 0.831372, -0.261289, 0.424101, 0.798916, 0.850092, -0.249559, 0.39443, 0.835952, 0.867777, -0.236348, 0.363849, 0.871606, 0.884632, -0.221569, 0.332477, 0.907843, 0.90047, -0.20618, 0.300667, 0.944187, 0.914524, -0.188771, 0.266552, 0.981371, 0.926892, -0.168362, 0.232349, 1.01841, 0.937951, -0.146761, 0.199359, 1.05308, 0.947236, -0.123813, 0.1675, 1.0839, 0.954367, -0.099984, 0.136166, 1.11047, 0.963907, -0.0759278, 0.103808, 1.13414, 0.976218, -0.0511367, 0.0697061, 1.15575, 0.988772, -0.0267415, 0.0352529, 1.17531, 0.999888, -0.000520778, 0.000289926, 1.19389, 0.263546, -0.00000883274, 0.441896, 0.00000526783, 0.262352, -0.000221849, 0.439889, 0.000132311, 0.262325, -0.000886683, 0.439848, 0.000528824, 0.26228, -0.00199476, 0.439765, 0.00118975, 0.262372, -0.00354671, 0.439922, 0.00211568, 0.26239, -0.00554141, 0.439941, 0.00330652, 0.262412, -0.00797888, 0.439961, 0.00476346, 0.262453, -0.0108584, 0.440002, 0.00648818, 0.262528, -0.0141788, 0.440085, 0.0084835, 0.262615, -0.017938, 0.440166, 0.0107533, 0.262744, -0.0221346, 0.440291, 0.0133044, 0.262939, -0.026762, 0.440493, 0.0161445, 0.263277, -0.0317573, 0.440889, 0.0192974, 0.26368, -0.0371832, 0.441338, 0.0227699, 0.264106, -0.0430371, 0.441753, 0.0265698, 0.264624, -0.0493035, 0.442227, 0.0307178, 0.265378, -0.0558669, 0.442985, 0.0352616, 0.266253, -0.0628718, 0.443795, 0.0401968, 0.267478, -0.0701569, 0.445008, 0.04559, 0.269062, -0.077845, 0.446599, 0.0514539, 0.270926, -0.0857941, 0.448349, 0.0578382, 0.273693, -0.0940773, 0.451221, 0.0648363, 0.276746, -0.102704, 0.454097, 0.0724389, 0.281693, -0.111735, 0.459517, 0.0808744, 0.287335, -0.121004, 0.46531, 0.0901551, 0.29448, -0.130734, 0.472605, 0.100371, 0.30257, -0.140777, 0.480251, 0.111644, 0.312465, -0.15111, 0.489444, 0.124111, 0.324856, -0.16189, 0.500919, 0.137979, 0.33774, -0.172946, 0.511317, 0.153163, 0.35255, -0.184152, 0.522684, 0.169817, 0.367786, -0.19522, 0.53248, 0.187886, 0.385474, -0.20632, 0.543326, 0.207634, 0.404976, -0.217744, 0.554109, 0.229165, 0.425203, -0.228691, 0.563395, 0.252068, 0.446704, -0.239299, 0.571565, 0.276471, 0.468951, -0.249348, 0.577935, 0.302323, 0.493487, -0.258933, 0.584309, 0.329882, 0.517861, -0.268009, 0.58773, 0.358525, 0.543309, -0.276238, 0.589612, 0.388585, 0.569704, -0.28356, 0.589294, 0.419787, 0.594871, -0.289497, 0.585137, 0.452114, 0.622555, -0.294452, 0.580356, 0.486466, 0.651167, -0.296918, 0.57185, 0.523079, 0.677332, -0.297647, 0.558428, 0.5611, 0.703718, -0.296321, 0.542232, 0.599592, 0.730262, -0.293339, 0.524541, 0.639138, 0.754304, -0.288036, 0.502691, 0.677978, 0.778051, -0.281018, 0.479212, 0.716537, 0.801557, -0.272414, 0.454071, 0.75586, 0.822559, -0.262419, 0.425952, 0.794477, 0.843051, -0.250702, 0.397313, 0.832664, 0.86232, -0.237264, 0.366534, 0.869876, 0.879044, -0.222716, 0.334816, 0.906973, 0.896362, -0.206827, 0.303143, 0.943558, 0.910342, -0.189659, 0.269699, 0.979759, 0.924119, -0.171108, 0.236411, 1.01718, 0.935374, -0.149579, 0.202224, 1.05289, 0.944295, -0.126295, 0.16989, 1.08496, 0.952227, -0.101511, 0.138089, 1.11256, 0.962041, -0.0766392, 0.105053, 1.1375, 0.97528, -0.0511967, 0.070329, 1.15983, 0.988476, -0.025463, 0.0351268, 1.17987, 0.999962, 0.0000286808, 0.0000145564, 1.19901, 0.227089, -0.00000841413, 0.404216, 0.00000472707, 0.239725, -0.000215083, 0.426708, 0.000120833, 0.239904, -0.000860718, 0.427028, 0.000483555, 0.239911, -0.00193661, 0.427039, 0.00108806, 0.239914, -0.00344276, 0.42704, 0.00193457, 0.239933, -0.00537907, 0.427064, 0.00302363, 0.239944, -0.00774482, 0.427065, 0.00435604, 0.239993, -0.01054, 0.427122, 0.00593398, 0.240052, -0.0137626, 0.427179, 0.00775987, 0.240148, -0.0174115, 0.427279, 0.00983854, 0.240278, -0.021484, 0.42741, 0.0121763, 0.240472, -0.0259729, 0.427618, 0.0147827, 0.240839, -0.0308131, 0.428086, 0.0176837, 0.241201, -0.0360893, 0.428482, 0.0208775, 0.241626, -0.0417723, 0.428907, 0.0243821, 0.242207, -0.0478337, 0.42952, 0.0282228, 0.24298, -0.0542199, 0.430332, 0.0324333, 0.243881, -0.0610015, 0.431222, 0.0370252, 0.245123, -0.0680874, 0.432512, 0.0420535, 0.24667, -0.0755482, 0.434088, 0.0475414, 0.248779, -0.0832873, 0.436323, 0.0535542, 0.251665, -0.0913546, 0.439509, 0.0601716, 0.255305, -0.0998489, 0.443478, 0.0674282, 0.260049, -0.108576, 0.448713, 0.0754673, 0.266192, -0.117754, 0.455524, 0.084339, 0.273158, -0.127294, 0.4627, 0.0941683, 0.282131, -0.137311, 0.472068, 0.10515, 0.293332, -0.147736, 0.483565, 0.117402, 0.304667, -0.158357, 0.493702, 0.130824, 0.317785, -0.169274, 0.504708, 0.145724, 0.333245, -0.180595, 0.517107, 0.16215, 0.349843, -0.191892, 0.528849, 0.180149, 0.367944, -0.203168, 0.540301, 0.199746, 0.387579, -0.214443, 0.551514, 0.221047, 0.408247, -0.225624, 0.560906, 0.243981, 0.43014, -0.236422, 0.56959, 0.268513, 0.452669, -0.24654, 0.576098, 0.294409, 0.476196, -0.256157, 0.580925, 0.322002, 0.501157, -0.265289, 0.584839, 0.351052, 0.527632, -0.273671, 0.587614, 0.3812, 0.555754, -0.281254, 0.589119, 0.412994, 0.581682, -0.287448, 0.585204, 0.445498, 0.608196, -0.292614, 0.579006, 0.479505, 0.635661, -0.296068, 0.571297, 0.514643, 0.664999, -0.297395, 0.560855, 0.552213, 0.691039, -0.296645, 0.544525, 0.591365, 0.7179, -0.293785, 0.526535, 0.630883, 0.744059, -0.289089, 0.50545, 0.670932, 0.76863, -0.282239, 0.482514, 0.710904, 0.793273, -0.273688, 0.457246, 0.750259, 0.814731, -0.26328, 0.428872, 0.78948, 0.835603, -0.251526, 0.399384, 0.828597, 0.85489, -0.238339, 0.368811, 0.866892, 0.872828, -0.223607, 0.336617, 0.90563, 0.889462, -0.207538, 0.303997, 0.943538, 0.904929, -0.190297, 0.270812, 0.980591, 0.919101, -0.172034, 0.237453, 1.01935, 0.930536, -0.152058, 0.204431, 1.05498, 0.941223, -0.129515, 0.172495, 1.08717, 0.94982, -0.104263, 0.140175, 1.11551, 0.960592, -0.0781944, 0.106465, 1.14098, 0.974629, -0.051688, 0.0711592, 1.16418, 0.98811, -0.0253929, 0.0354432, 1.18465, 1.00004, 0.000804378, -0.000330876, 1.20462, 0.214668, -0.00000821282, 0.406619, 0.00000433582, 0.218053, -0.000208144, 0.413025, 0.000109887, 0.217987, -0.000832212, 0.412901, 0.000439362, 0.217971, -0.00187246, 0.412876, 0.000988623, 0.217968, -0.00332855, 0.41286, 0.00175772, 0.217985, -0.00520055, 0.412882, 0.00274729, 0.218014, -0.00748814, 0.412916, 0.00395842, 0.218054, -0.0101901, 0.412957, 0.00539274, 0.218106, -0.0133057, 0.413005, 0.00705348, 0.218217, -0.0168342, 0.413139, 0.00894581, 0.218338, -0.0207707, 0.413258, 0.0110754, 0.21855, -0.0251001, 0.413509, 0.0134551, 0.218913, -0.0297861, 0.413992, 0.0161081, 0.219265, -0.0348956, 0.414383, 0.0190307, 0.219696, -0.0403909, 0.414839, 0.0222458, 0.220329, -0.0462003, 0.415567, 0.025792, 0.220989, -0.0524208, 0.41621, 0.0296637, 0.222027, -0.058948, 0.417385, 0.0339323, 0.223301, -0.0658208, 0.418779, 0.0386055, 0.224988, -0.0730347, 0.420665, 0.0437355, 0.227211, -0.0805274, 0.423198, 0.0493844, 0.230131, -0.088395, 0.426566, 0.0556135, 0.233908, -0.0966208, 0.43091, 0.0624829, 0.239092, -0.105223, 0.437148, 0.0701636, 0.245315, -0.11424, 0.444302, 0.0786949, 0.253166, -0.12368, 0.453262, 0.0882382, 0.262374, -0.133569, 0.463211, 0.0988682, 0.273145, -0.143836, 0.474271, 0.110727, 0.285512, -0.154577, 0.4863, 0.123945, 0.299512, -0.165501, 0.498817, 0.138581, 0.314287, -0.176698, 0.510341, 0.154676, 0.331083, -0.188066, 0.522583, 0.172459, 0.349615, -0.199597, 0.534879, 0.191979, 0.369318, -0.210843, 0.546083, 0.21309, 0.390377, -0.222068, 0.5562, 0.235998, 0.412411, -0.233059, 0.564704, 0.260518, 0.435715, -0.24357, 0.572314, 0.286795, 0.461196, -0.253356, 0.579395, 0.314559, 0.485587, -0.262362, 0.581985, 0.343581, 0.511908, -0.270895, 0.584347, 0.374367, 0.539798, -0.278452, 0.58505, 0.406015, 0.567974, -0.284877, 0.583344, 0.439168, 0.594303, -0.290124, 0.577348, 0.473005, 0.622951, -0.294183, 0.570751, 0.508534, 0.652404, -0.296389, 0.561541, 0.544764, 0.679291, -0.296605, 0.546426, 0.582927, 0.706437, -0.294095, 0.528599, 0.622681, 0.734485, -0.28978, 0.508676, 0.663567, 0.758841, -0.283363, 0.484768, 0.704092, 0.78537, -0.275015, 0.460434, 0.745101, 0.807315, -0.264689, 0.432166, 0.784712, 0.8271, -0.252597, 0.401807, 0.824241, 0.849191, -0.239154, 0.371458, 0.863803, 0.867046, -0.224451, 0.338873, 0.903063, 0.8852, -0.208342, 0.306175, 0.942763, 0.901771, -0.190684, 0.272759, 0.981559, 0.915958, -0.172105, 0.239306, 1.02048, 0.928046, -0.152214, 0.206071, 1.05765, 0.939961, -0.130247, 0.17367, 1.08999, 0.948711, -0.10672, 0.142201, 1.11829, 0.959305, -0.0808688, 0.108454, 1.14467, 0.973009, -0.0539145, 0.0728109, 1.16839, 0.987631, -0.0262947, 0.0360625, 1.19004, 0.999978, 0.00132758, -0.000559424, 1.21058, 0.193925, -0.00000793421, 0.391974, 0.00000392537, 0.196746, -0.000200315, 0.397675, 0.0000991033, 0.19667, -0.000801099, 0.397521, 0.000396342, 0.196633, -0.00180246, 0.397445, 0.000891829, 0.196654, -0.00320443, 0.397482, 0.00158582, 0.196659, -0.00500647, 0.39748, 0.00247867, 0.196683, -0.0072086, 0.397506, 0.00357167, 0.196728, -0.00981001, 0.397562, 0.00486675, 0.196792, -0.0128096, 0.397633, 0.00636707, 0.19689, -0.0162055, 0.397746, 0.00807752, 0.197017, -0.0199943, 0.397884, 0.0100052, 0.19729, -0.024139, 0.39827, 0.0121691, 0.197583, -0.0286671, 0.398639, 0.0145755, 0.197927, -0.0335858, 0.399034, 0.0172355, 0.198383, -0.0388806, 0.399554, 0.0201718, 0.199002, -0.0444736, 0.400289, 0.0234194, 0.199739, -0.0504583, 0.401111, 0.026984, 0.200784, -0.056729, 0.402349, 0.0309217, 0.202075, -0.0633643, 0.403841, 0.0352496, 0.203898, -0.0703247, 0.406076, 0.0400313, 0.206199, -0.0775565, 0.408841, 0.0453282, 0.209252, -0.085184, 0.41259, 0.0511794, 0.213638, -0.0931994, 0.418288, 0.0577459, 0.21881, -0.101617, 0.424681, 0.0650508, 0.225642, -0.11052, 0.433429, 0.0732759, 0.233717, -0.119772, 0.442897, 0.0824683, 0.242823, -0.129505, 0.452888, 0.0927484, 0.254772, -0.139906, 0.466407, 0.104417, 0.266603, -0.150402, 0.477413, 0.117211, 0.28073, -0.161395, 0.490519, 0.131598, 0.295399, -0.172465, 0.50201, 0.147407, 0.312705, -0.183982, 0.515311, 0.165031, 0.331335, -0.195532, 0.52786, 0.184336, 0.351037, -0.206971, 0.5392, 0.205361, 0.372175, -0.218117, 0.54941, 0.228043, 0.394548, -0.229327, 0.558642, 0.25267, 0.419598, -0.240052, 0.567861, 0.279071, 0.443922, -0.249937, 0.573332, 0.306882, 0.471495, -0.259407, 0.58013, 0.33661, 0.496769, -0.267749, 0.580564, 0.367328, 0.524951, -0.275524, 0.581696, 0.399753, 0.55318, -0.282148, 0.579885, 0.433134, 0.581577, -0.287533, 0.575471, 0.467534, 0.609231, -0.291612, 0.567445, 0.502943, 0.637478, -0.293911, 0.557657, 0.53871, 0.667795, -0.295096, 0.546535, 0.576568, 0.694272, -0.294073, 0.529561, 0.614929, 0.722937, -0.290386, 0.510561, 0.655909, 0.749682, -0.284481, 0.487846, 0.697663, 0.774754, -0.276188, 0.462487, 0.738515, 0.799301, -0.266215, 0.43481, 0.779802, 0.820762, -0.254116, 0.404879, 0.820045, 0.843231, -0.240393, 0.374559, 0.860294, 0.861857, -0.225503, 0.341582, 0.900965, 0.880815, -0.209382, 0.308778, 0.941727, 0.89766, -0.19155, 0.275232, 0.980916, 0.912926, -0.172346, 0.240938, 1.02162, 0.926391, -0.151799, 0.207223, 1.0597, 0.938429, -0.129968, 0.17484, 1.09291, 0.947834, -0.10651, 0.142984, 1.12248, 0.958432, -0.0824098, 0.109902, 1.149, 0.972402, -0.0565242, 0.0744454, 1.1733, 0.987191, -0.028427, 0.0373794, 1.19538, 0.999975, 0.0000385685, -0.00004203, 1.21676, 0.178114, -0.00000766075, 0.385418, 0.00000354027, 0.176074, -0.000191966, 0.381002, 0.0000887135, 0.17601, -0.000767549, 0.380861, 0.000354715, 0.17598, -0.00172696, 0.380798, 0.000798168, 0.175994, -0.00307012, 0.380824, 0.00141928, 0.176017, -0.00479684, 0.380858, 0.00221859, 0.176019, -0.00690648, 0.380839, 0.00319714, 0.176072, -0.00939888, 0.380913, 0.0043572, 0.176131, -0.0122726, 0.380979, 0.005702, 0.176239, -0.0155264, 0.38112, 0.00723689, 0.176371, -0.0191551, 0.381272, 0.00896907, 0.176638, -0.023117, 0.381669, 0.0109194, 0.176912, -0.0274633, 0.382015, 0.0130903, 0.177279, -0.032173, 0.382476, 0.0154949, 0.17774, -0.0372219, 0.383041, 0.0181669, 0.178344, -0.0426132, 0.38378, 0.0211209, 0.179153, -0.0483309, 0.384773, 0.0243899, 0.180197, -0.0543447, 0.386076, 0.0280062, 0.181581, -0.0607122, 0.387809, 0.032004, 0.18344, -0.0673855, 0.390205, 0.036453, 0.186139, -0.0743989, 0.393944, 0.0414162, 0.189432, -0.0817731, 0.39832, 0.0469394, 0.193795, -0.0895464, 0.404188, 0.0531442, 0.199641, -0.0978264, 0.4121, 0.0601374, 0.206679, -0.106499, 0.421425, 0.0680078, 0.214865, -0.115654, 0.431504, 0.076919, 0.224406, -0.125268, 0.442526, 0.0868835, 0.235876, -0.135475, 0.455465, 0.0981875, 0.248335, -0.146023, 0.4681, 0.110759, 0.262868, -0.157016, 0.482069, 0.124885, 0.278962, -0.168245, 0.496182, 0.140645, 0.295082, -0.17958, 0.507401, 0.157838, 0.313738, -0.191227, 0.520252, 0.17695, 0.333573, -0.202718, 0.531708, 0.197817, 0.356433, -0.214424, 0.544509, 0.220785, 0.378853, -0.225492, 0.55373, 0.245306, 0.402717, -0.236236, 0.561348, 0.271593, 0.428375, -0.246568, 0.568538, 0.299776, 0.454724, -0.255941, 0.573462, 0.329433, 0.482291, -0.264511, 0.576356, 0.360598, 0.509706, -0.272129, 0.576446, 0.393204, 0.538805, -0.278979, 0.575298, 0.427227, 0.568919, -0.284528, 0.572154, 0.462157, 0.596804, -0.288801, 0.564691, 0.497997, 0.625987, -0.291334, 0.555134, 0.534467, 0.656414, -0.292722, 0.545051, 0.571736, 0.683916, -0.292185, 0.528813, 0.610158, 0.711809, -0.290043, 0.51106, 0.649061, 0.739547, -0.285246, 0.490103, 0.690081, 0.766914, -0.277647, 0.465523, 0.732554, 0.791375, -0.267603, 0.437718, 0.773982, 0.814772, -0.256109, 0.40882, 0.81609, 0.836691, -0.242281, 0.377823, 0.856849, 0.856984, -0.227155, 0.34496, 0.898363, 0.876332, -0.210395, 0.311335, 0.939471, 0.894988, -0.192612, 0.277703, 0.980799, 0.911113, -0.173236, 0.243019, 1.02215, 0.924092, -0.152258, 0.209037, 1.06139, 0.936828, -0.129575, 0.175909, 1.09635, 0.946869, -0.10594, 0.143852, 1.12707, 0.958284, -0.081318, 0.110289, 1.15419, 0.972325, -0.0556133, 0.0747232, 1.17909, 0.986878, -0.0297899, 0.0383149, 1.20163, 0.999936, -0.00197169, 0.000912402, 1.22338, 0.151174, -0.00000720365, 0.351531, 0.00000309789, 0.155594, -0.00018279, 0.361806, 0.000078608, 0.156099, -0.000731569, 0.362982, 0.000314615, 0.156053, -0.00164578, 0.362869, 0.000707845, 0.156093, -0.0029261, 0.362961, 0.00125884, 0.156099, -0.00457155, 0.362959, 0.00196783, 0.15612, -0.00658224, 0.362982, 0.00283622, 0.156168, -0.00895774, 0.363048, 0.00386625, 0.156221, -0.0116962, 0.363101, 0.00506109, 0.156324, -0.0147973, 0.363241, 0.00642675, 0.156476, -0.0182503, 0.363448, 0.00797175, 0.156731, -0.0220266, 0.36384, 0.00971484, 0.156994, -0.026176, 0.364179, 0.0116575, 0.157341, -0.0306701, 0.36462, 0.0138207, 0.157867, -0.0354591, 0.365364, 0.0162356, 0.15846, -0.0406141, 0.366111, 0.0189092, 0.159308, -0.0460519, 0.367248, 0.021885, 0.160426, -0.0518096, 0.368767, 0.0252004, 0.161877, -0.0578906, 0.370745, 0.0288825, 0.163995, -0.0642812, 0.373831, 0.0330139, 0.16655, -0.0710067, 0.377366, 0.0376283, 0.170237, -0.0781522, 0.382799, 0.0428493, 0.175096, -0.0857172, 0.389915, 0.0487324, 0.181069, -0.0938025, 0.398487, 0.0554214, 0.188487, -0.102363, 0.408799, 0.0630189, 0.197029, -0.111343, 0.419991, 0.071634, 0.206684, -0.120812, 0.431455, 0.0812797, 0.218698, -0.131033, 0.445746, 0.0923651, 0.230726, -0.141373, 0.457471, 0.104545, 0.245516, -0.152387, 0.472388, 0.118449, 0.261551, -0.163628, 0.486671, 0.133923, 0.277437, -0.174814, 0.49762, 0.150849, 0.296662, -0.186713, 0.51162, 0.169924, 0.31795, -0.198513, 0.525435, 0.190848, 0.339422, -0.210119, 0.536267, 0.213504, 0.362143, -0.221354, 0.545982, 0.237947, 0.387198, -0.23224, 0.555364, 0.264427, 0.412349, -0.24257, 0.561489, 0.292519, 0.439274, -0.252284, 0.566903, 0.322561, 0.466779, -0.261023, 0.569614, 0.353952, 0.496011, -0.26899, 0.571589, 0.387278, 0.524964, -0.275498, 0.570325, 0.421356, 0.556518, -0.281449, 0.568792, 0.457314, 0.584363, -0.285526, 0.560268, 0.493199, 0.614214, -0.28844, 0.55205, 0.530276, 0.645684, -0.289777, 0.541906, 0.56855, 0.673446, -0.289722, 0.526464, 0.606927, 0.701924, -0.287792, 0.509872, 0.645945, 0.73037, -0.284315, 0.490649, 0.685564, 0.757405, -0.278804, 0.467964, 0.726511, 0.784025, -0.269543, 0.441468, 0.768601, 0.808255, -0.258117, 0.41216, 0.811321, 0.830739, -0.244728, 0.380606, 0.853496, 0.851914, -0.229428, 0.348111, 0.895374, 0.872586, -0.212508, 0.314732, 0.937674, 0.891581, -0.194025, 0.280338, 0.979869, 0.907641, -0.174711, 0.245203, 1.02253, 0.922233, -0.153509, 0.21077, 1.06371, 0.935878, -0.130418, 0.177399, 1.09972, 0.946338, -0.105558, 0.144507, 1.13124, 0.957265, -0.080059, 0.110508, 1.15973, 0.971668, -0.0539766, 0.0742311, 1.18515, 0.9866, -0.0277101, 0.0375224, 1.20858, 1.00021, -0.000515531, 0.000135226, 1.23135, 0.137468, -0.00000686011, 0.345041, 0.00000273315, 0.13703, -0.000173378, 0.343936, 0.0000690761, 0.136986, -0.000693048, 0.34383, 0.000276126, 0.136964, -0.00155931, 0.343761, 0.000621337, 0.137003, -0.00277211, 0.343863, 0.00110494, 0.137012, -0.00433103, 0.343868, 0.00172744, 0.137043, -0.00623606, 0.343916, 0.00249022, 0.13709, -0.0084868, 0.343986, 0.00339559, 0.137145, -0.0110814, 0.344045, 0.00444687, 0.137242, -0.0140187, 0.344177, 0.00565007, 0.137431, -0.0172713, 0.344491, 0.00701868, 0.137644, -0.0208605, 0.344805, 0.00856042, 0.13791, -0.024792, 0.345172, 0.0102863, 0.138295, -0.0290461, 0.345734, 0.0122185, 0.138764, -0.0335957, 0.346371, 0.0143771, 0.139415, -0.038467, 0.347298, 0.0167894, 0.140272, -0.0436176, 0.348527, 0.0194895, 0.141457, -0.0491016, 0.350276, 0.0225043, 0.14303, -0.0548764, 0.352646, 0.0258962, 0.145289, -0.0610096, 0.356206, 0.0297168, 0.148502, -0.0674777, 0.361488, 0.0340562, 0.152188, -0.074345, 0.367103, 0.0389534, 0.157359, -0.0817442, 0.375247, 0.0445541, 0.16379, -0.0896334, 0.385064, 0.0509535, 0.171376, -0.098005, 0.396082, 0.0582611, 0.179901, -0.106817, 0.407418, 0.06654, 0.189892, -0.116239, 0.420031, 0.075994, 0.201838, -0.12627, 0.434321, 0.0867239, 0.214311, -0.136701, 0.447631, 0.0987517, 0.228902, -0.147616, 0.462046, 0.112353, 0.245107, -0.158871, 0.476942, 0.127605, 0.262292, -0.170261, 0.490285, 0.144469, 0.281215, -0.182017, 0.503783, 0.163282, 0.301058, -0.193729, 0.515505, 0.183873, 0.322752, -0.205512, 0.52682, 0.206466, 0.347547, -0.217214, 0.539473, 0.231194, 0.370969, -0.227966, 0.546625, 0.257288, 0.397533, -0.238555, 0.55472, 0.285789, 0.42398, -0.248278, 0.559468, 0.315746, 0.452928, -0.257422, 0.564095, 0.347724, 0.482121, -0.265306, 0.565426, 0.380922, 0.510438, -0.272043, 0.563205, 0.415639, 0.541188, -0.277614, 0.561087, 0.451702, 0.571667, -0.281927, 0.554922, 0.48845, 0.602432, -0.285015, 0.546838, 0.526442, 0.634126, -0.286512, 0.537415, 0.564896, 0.662816, -0.286388, 0.522906, 0.604037, 0.692411, -0.284734, 0.507003, 0.643795, 0.720946, -0.281297, 0.488398, 0.68298, 0.748293, -0.276262, 0.466353, 0.723466, 0.776931, -0.269978, 0.443573, 0.764565, 0.801065, -0.260305, 0.415279, 0.805838, 0.825843, -0.247426, 0.384773, 0.849985, 0.84807, -0.232437, 0.352555, 0.893174, 0.869122, -0.215806, 0.318642, 0.936564, 0.888963, -0.197307, 0.28381, 0.980253, 0.905547, -0.177203, 0.247888, 1.02463, 0.918554, -0.155542, 0.212904, 1.06714, 0.931395, -0.131948, 0.1787, 1.10451, 0.941749, -0.106723, 0.145902, 1.13694, 0.954551, -0.0804939, 0.111193, 1.1666, 0.970279, -0.0534239, 0.0744697, 1.19249, 0.986117, -0.0257452, 0.0368788, 1.21665, 0.999938, 0.00190634, -0.0010291, 1.23981, 0.118493, -0.00000647439, 0.32272, 0.0000023772, 0.118765, -0.000163023, 0.323456, 0.0000598573, 0.118772, -0.00065212, 0.323477, 0.000239447, 0.118843, -0.00146741, 0.323657, 0.000538881, 0.118804, -0.00260846, 0.323553, 0.00095826, 0.118826, -0.00407576, 0.323595, 0.00149845, 0.118846, -0.00586826, 0.323617, 0.00216047, 0.118886, -0.00798578, 0.32367, 0.00294679, 0.118947, -0.0104273, 0.323753, 0.00386124, 0.119055, -0.0131909, 0.323922, 0.00490999, 0.119241, -0.0162444, 0.324251, 0.00610804, 0.11944, -0.0196339, 0.324544, 0.00745805, 0.119739, -0.0233378, 0.325026, 0.00897805, 0.12011, -0.0273179, 0.325586, 0.0106895, 0.120571, -0.0316143, 0.326231, 0.0126073, 0.12124, -0.0361939, 0.327264, 0.0147654, 0.122162, -0.0410511, 0.328733, 0.0172001, 0.123378, -0.0462233, 0.330659, 0.0199375, 0.125183, -0.0517109, 0.333754, 0.0230498, 0.127832, -0.0575652, 0.338507, 0.026597, 0.130909, -0.0637441, 0.343666, 0.0306345, 0.135221, -0.0704302, 0.351063, 0.035273, 0.14082, -0.0776364, 0.360604, 0.0406137, 0.146781, -0.0852293, 0.369638, 0.0466788, 0.155121, -0.0935351, 0.3827, 0.0537628, 0.16398, -0.102234, 0.39522, 0.0617985, 0.173926, -0.111465, 0.40793, 0.07097, 0.185137, -0.121296, 0.42105, 0.0813426, 0.19826, -0.13169, 0.435735, 0.0931596, 0.212938, -0.142614, 0.450932, 0.106547, 0.229046, -0.153884, 0.465726, 0.121575, 0.246246, -0.165382, 0.479461, 0.138286, 0.264637, -0.176806, 0.492106, 0.15666, 0.284959, -0.188793, 0.504774, 0.17728, 0.308157, -0.200763, 0.518805, 0.19988, 0.330951, -0.21239, 0.528231, 0.224293, 0.3549, -0.223521, 0.536376, 0.250541, 0.381502, -0.234169, 0.544846, 0.278902, 0.409529, -0.244077, 0.551717, 0.309227, 0.437523, -0.253363, 0.55517, 0.341426, 0.467624, -0.261659, 0.557772, 0.37518, 0.497268, -0.268498, 0.556442, 0.41007, 0.528294, -0.274018, 0.553915, 0.446445, 0.559053, -0.278169, 0.549153, 0.483779, 0.589329, -0.281229, 0.539878, 0.522249, 0.622503, -0.282902, 0.53162, 0.561754, 0.652382, -0.282815, 0.518119, 0.601544, 0.681847, -0.281247, 0.502187, 0.641574, 0.712285, -0.277986, 0.484824, 0.682633, 0.740094, -0.273017, 0.463483, 0.723426, 0.768478, -0.266692, 0.441299, 0.763747, 0.794556, -0.258358, 0.415238, 0.805565, 0.819408, -0.248807, 0.386912, 0.847254, 0.843411, -0.236214, 0.356165, 0.891091, 0.862397, -0.219794, 0.320562, 0.936174, 0.883113, -0.201768, 0.285322, 0.982562, 0.90023, -0.181672, 0.249713, 1.02862, 0.915192, -0.159279, 0.214546, 1.07163, 0.928458, -0.134725, 0.180285, 1.10995, 0.94069, -0.10913, 0.147119, 1.14354, 0.953409, -0.0821315, 0.112492, 1.17372, 0.969537, -0.0542677, 0.0752014, 1.20043, 0.985612, -0.0259096, 0.0370361, 1.22528, 0.999835, 0.00298198, -0.00151801, 1.24959, 0.10097, -0.00000602574, 0.300277, 0.00000202619, 0.101577, -0.000152164, 0.302077, 0.0000511662, 0.101572, -0.000608889, 0.302066, 0.000204751, 0.101566, -0.00136997, 0.302047, 0.000460753, 0.101592, -0.00243557, 0.302114, 0.000819497, 0.101608, -0.0038053, 0.30214, 0.00128154, 0.101627, -0.00547906, 0.30216, 0.0018483, 0.101669, -0.00745647, 0.302224, 0.00252223, 0.101732, -0.00973615, 0.302318, 0.00330716, 0.101844, -0.0123097, 0.302513, 0.00421061, 0.102025, -0.0151681, 0.30285, 0.00524481, 0.102224, -0.0183334, 0.303166, 0.0064154, 0.102515, -0.0217819, 0.303654, 0.00774063, 0.102886, -0.0255067, 0.304243, 0.0092398, 0.103395, -0.029514, 0.305089, 0.0109339, 0.104109, -0.0337912, 0.306301, 0.0128561, 0.105074, -0.0383565, 0.30798, 0.0150338, 0.10654, -0.0432132, 0.310726, 0.0175228, 0.108478, -0.0484244, 0.314351, 0.0203648, 0.111015, -0.0539339, 0.319032, 0.0236325, 0.114682, -0.0598885, 0.32605, 0.0274188, 0.11911, -0.0663375, 0.334109, 0.0317905, 0.124736, -0.0733011, 0.344013, 0.0368502, 0.131479, -0.0807744, 0.355358, 0.0427104, 0.139283, -0.0888204, 0.367614, 0.0494788, 0.148054, -0.0973394, 0.380072, 0.0572367, 0.159037, -0.10665, 0.395678, 0.0662704, 0.169794, -0.116221, 0.40795, 0.0763192, 0.18314, -0.126632, 0.423546, 0.087956, 0.197515, -0.137383, 0.438213, 0.101042, 0.213514, -0.148641, 0.453248, 0.115827, 0.23065, -0.160117, 0.46688, 0.132283, 0.249148, -0.171807, 0.479962, 0.150644, 0.270219, -0.183695, 0.494618, 0.171073, 0.292338, -0.195574, 0.506937, 0.193378, 0.314999, -0.207205, 0.516463, 0.217585, 0.340991, -0.218955, 0.528123, 0.24428, 0.367982, -0.229917, 0.537025, 0.272784, 0.39432, -0.239737, 0.541627, 0.302742, 0.423364, -0.249048, 0.546466, 0.335112, 0.453751, -0.257329, 0.549466, 0.369032, 0.48416, -0.264623, 0.549503, 0.404577, 0.515262, -0.270411, 0.547008, 0.441337, 0.547036, -0.274581, 0.542249, 0.479162, 0.576614, -0.277266, 0.533015, 0.517904, 0.611143, -0.279144, 0.525512, 0.558508, 0.640989, -0.279001, 0.51154, 0.598995, 0.671182, -0.277324, 0.495641, 0.639935, 0.700848, -0.273908, 0.477526, 0.681017, 0.729862, -0.269063, 0.457955, 0.722764, 0.758273, -0.262282, 0.434846, 0.764349, 0.784121, -0.254281, 0.409203, 0.806206, 0.809798, -0.24505, 0.382694, 0.848617, 0.834953, -0.233861, 0.354034, 0.892445, 0.856817, -0.221308, 0.321764, 0.936263, 0.877609, -0.205996, 0.288118, 0.982401, 0.897489, -0.186702, 0.253277, 1.02975, 0.913792, -0.164618, 0.217963, 1.07488, 0.92785, -0.140023, 0.183221, 1.11487, 0.940378, -0.11328, 0.149385, 1.14947, 0.95273, -0.0853958, 0.114152, 1.1807, 0.969059, -0.0568698, 0.0769845, 1.20912, 0.985574, -0.0276502, 0.0381186, 1.23498, 0.999943, 0.00239052, -0.00126861, 1.25987, 0.0852715, -0.00000560067, 0.279021, 0.00000171162, 0.0854143, -0.000140871, 0.279483, 0.0000430516, 0.0854191, -0.000563385, 0.2795, 0.000172184, 0.0854188, -0.00126753, 0.279493, 0.000387464, 0.0854229, -0.00225337, 0.279501, 0.00068918, 0.0854443, -0.00352086, 0.279549, 0.00107803, 0.0854697, -0.00506962, 0.279591, 0.00155536, 0.0855093, -0.00689873, 0.279652, 0.00212354, 0.0855724, -0.00900821, 0.279752, 0.00278703, 0.0856991, -0.0113799, 0.280011, 0.0035551, 0.085855, -0.0140314, 0.280297, 0.00443449, 0.0860682, -0.016963, 0.280682, 0.00543636, 0.086344, -0.0201438, 0.281159, 0.0065788, 0.0867426, -0.0235999, 0.281886, 0.00787977, 0.087239, -0.0273069, 0.282745, 0.0093606, 0.0879815, -0.031269, 0.284139, 0.011056, 0.0891258, -0.035531, 0.28647, 0.0130065, 0.0906909, -0.0400947, 0.289708, 0.0152495, 0.0927624, -0.0449638, 0.293904, 0.0178454, 0.0958376, -0.0502427, 0.300471, 0.0208915, 0.0995827, -0.0559514, 0.30806, 0.0244247, 0.104526, -0.0622152, 0.317874, 0.0285721, 0.110532, -0.0690046, 0.329332, 0.0334227, 0.117385, -0.0763068, 0.341217, 0.0390466, 0.12522, -0.084184, 0.353968, 0.0455786, 0.134037, -0.0925248, 0.366797, 0.0530773, 0.144014, -0.101487, 0.380209, 0.0617424, 0.156013, -0.111273, 0.395956, 0.071777, 0.168872, -0.121431, 0.41053, 0.0830905, 0.183089, -0.132105, 0.425073, 0.0959341, 0.198763, -0.143286, 0.439833, 0.110448, 0.216159, -0.154841, 0.454507, 0.126769, 0.234859, -0.166588, 0.468368, 0.14495, 0.255879, -0.178626, 0.482846, 0.165233, 0.27677, -0.190218, 0.493489, 0.187217, 0.301184, -0.202227, 0.506549, 0.211659, 0.325852, -0.213764, 0.5158, 0.237922, 0.352824, -0.22487, 0.525442, 0.26632, 0.380882, -0.235246, 0.532487, 0.296691, 0.410137, -0.244847, 0.537703, 0.329179, 0.439787, -0.253122, 0.540361, 0.363135, 0.472291, -0.260517, 0.542734, 0.399222, 0.501856, -0.266519, 0.538826, 0.436352, 0.534816, -0.270905, 0.535152, 0.474505, 0.565069, -0.273826, 0.525979, 0.513988, 0.597154, -0.275333, 0.516394, 0.554852, 0.630473, -0.275314, 0.506206, 0.596592, 0.660574, -0.273323, 0.489769, 0.638117, 0.692015, -0.270008, 0.472578, 0.680457, 0.720647, -0.265001, 0.452134, 0.723008, 0.750528, -0.258311, 0.430344, 0.765954, 0.777568, -0.250046, 0.405624, 0.809012, 0.80387, -0.240114, 0.378339, 0.852425, 0.828439, -0.228737, 0.349877, 0.895346, 0.851472, -0.216632, 0.318968, 0.940695, 0.873906, -0.202782, 0.287489, 0.987235, 0.89467, -0.187059, 0.254394, 1.03348, 0.912281, -0.168818, 0.221294, 1.07812, 0.927358, -0.146494, 0.18675, 1.11928, 0.940385, -0.120009, 0.152322, 1.15609, 0.952672, -0.0917183, 0.117514, 1.18875, 0.968496, -0.0620321, 0.0797405, 1.21821, 0.985236, -0.0314945, 0.0402383, 1.24523, 0.99998, -0.000575153, 0.000110644, 1.27133, 0.0702429, -0.00000512222, 0.255273, 0.00000140947, 0.0702981, -0.000128826, 0.255469, 0.0000354488, 0.0703691, -0.000515562, 0.255727, 0.000141874, 0.0703805, -0.00116, 0.255754, 0.00031929, 0.0703961, -0.00206224, 0.255813, 0.000567999, 0.0704102, -0.00322223, 0.255839, 0.00088871, 0.0704298, -0.00463928, 0.255863, 0.00128272, 0.0704759, -0.00631375, 0.255953, 0.00175283, 0.0705434, -0.00824317, 0.256079, 0.00230342, 0.0706693, -0.010412, 0.25636, 0.0029443, 0.0708189, -0.0128439, 0.256647, 0.00368031, 0.0710364, -0.0155177, 0.257084, 0.00452614, 0.0713223, -0.0184374, 0.257637, 0.00549706, 0.0717182, -0.0216002, 0.258416, 0.00661246, 0.072321, -0.0249966, 0.259699, 0.00790147, 0.0731446, -0.0286566, 0.261475, 0.0093884, 0.0743352, -0.0325888, 0.264132, 0.0111186, 0.0760676, -0.036843, 0.26815, 0.013145, 0.078454, -0.0414292, 0.273636, 0.0155251, 0.0818618, -0.0464634, 0.281653, 0.0183525, 0.0857382, -0.0519478, 0.289992, 0.0216642, 0.0908131, -0.0579836, 0.30066, 0.0255956, 0.0967512, -0.0645124, 0.312204, 0.0301954, 0.103717, -0.0716505, 0.325001, 0.0356017, 0.111596, -0.0793232, 0.338129, 0.041896, 0.120933, -0.087645, 0.352853, 0.0492447, 0.130787, -0.096492, 0.366192, 0.0576749, 0.142311, -0.105973, 0.380864, 0.0673969, 0.155344, -0.116182, 0.396575, 0.0785899, 0.169535, -0.126815, 0.411443, 0.0912377, 0.185173, -0.138015, 0.426256, 0.105607, 0.201755, -0.149325, 0.439607, 0.121551, 0.221334, -0.161207, 0.455467, 0.139608, 0.241461, -0.173162, 0.469096, 0.159591, 0.26294, -0.18504, 0.481014, 0.18156, 0.286776, -0.196881, 0.493291, 0.205781, 0.311596, -0.208311, 0.503556, 0.231819, 0.338667, -0.219671, 0.513268, 0.260274, 0.366021, -0.230451, 0.519414, 0.290862, 0.395875, -0.240131, 0.526766, 0.323196, 0.425564, -0.248566, 0.52905, 0.357071, 0.457094, -0.256195, 0.530796, 0.393262, 0.488286, -0.262331, 0.528703, 0.430797, 0.522291, -0.267141, 0.52727, 0.470231, 0.554172, -0.270411, 0.519848, 0.510477, 0.586427, -0.271986, 0.510307, 0.551594, 0.619638, -0.27192, 0.499158, 0.593849, 0.650656, -0.269817, 0.483852, 0.636314, 0.68284, -0.266267, 0.467515, 0.679679, 0.714356, -0.26113, 0.44931, 0.723884, 0.742717, -0.254067, 0.425789, 0.767245, 0.770894, -0.245652, 0.401144, 0.811819, 0.797358, -0.235554, 0.374224, 0.856315, 0.823377, -0.223896, 0.346167, 0.901077, 0.847456, -0.210865, 0.316056, 0.946502, 0.870697, -0.196574, 0.284503, 0.993711, 0.891068, -0.180814, 0.251628, 1.04134, 0.909267, -0.163314, 0.219065, 1.08609, 0.925653, -0.143304, 0.186446, 1.12702, 0.940017, -0.121322, 0.153416, 1.16371, 0.952398, -0.0973872, 0.120334, 1.19712, 0.967568, -0.0698785, 0.08352, 1.22791, 0.984772, -0.0390031, 0.0439209, 1.25672, 1.00026, -0.0070087, 0.00315668, 1.28428, 0.0556653, -0.00000459654, 0.227325, 0.00000112556, 0.0565238, -0.000116382, 0.230826, 0.0000284985, 0.0565717, -0.000465666, 0.231026, 0.000114036, 0.0565859, -0.00104773, 0.231079, 0.000256656, 0.0565761, -0.00186255, 0.231025, 0.00045663, 0.0565913, -0.00291002, 0.231058, 0.000714664, 0.0566108, -0.00418998, 0.231085, 0.00103224, 0.0566532, -0.00570206, 0.231169, 0.00141202, 0.0567473, -0.00743666, 0.231417, 0.00186018, 0.0568567, -0.00940298, 0.231661, 0.00238264, 0.0569859, -0.0115991, 0.231895, 0.00298699, 0.0572221, -0.0140096, 0.232456, 0.00368957, 0.057519, -0.0166508, 0.233096, 0.00450303, 0.0579534, -0.01951, 0.234094, 0.00544945, 0.0585922, -0.0225991, 0.235629, 0.00655564, 0.0595647, -0.0259416, 0.238106, 0.00785724, 0.0609109, -0.0295661, 0.241557, 0.00939127, 0.0628751, -0.0335126, 0.246652, 0.0112198, 0.0656908, -0.0378604, 0.254091, 0.0134168, 0.0691347, -0.0426543, 0.262666, 0.0160374, 0.0732165, -0.0478967, 0.272029, 0.0191514, 0.0782863, -0.0536716, 0.283007, 0.0228597, 0.0843973, -0.0600683, 0.295732, 0.0272829, 0.0913598, -0.0670095, 0.308779, 0.032484, 0.0994407, -0.0745516, 0.322886, 0.0385886, 0.108189, -0.082712, 0.336408, 0.0457133, 0.118574, -0.0914927, 0.351692, 0.0539832, 0.129989, -0.100854, 0.366502, 0.0635162, 0.142722, -0.110837, 0.381675, 0.0744386, 0.156654, -0.121353, 0.3963, 0.0868483, 0.172151, -0.132414, 0.411477, 0.100963, 0.188712, -0.143809, 0.42508, 0.116795, 0.208093, -0.155765, 0.441328, 0.134715, 0.227936, -0.167608, 0.454328, 0.154396, 0.249495, -0.179579, 0.467235, 0.176179, 0.27362, -0.191488, 0.480248, 0.200193, 0.296371, -0.202618, 0.487886, 0.225775, 0.324234, -0.214133, 0.499632, 0.25441, 0.353049, -0.225212, 0.509532, 0.285077, 0.381785, -0.234875, 0.514265, 0.317047, 0.414038, -0.244205, 0.521282, 0.351874, 0.445251, -0.252145, 0.522931, 0.388279, 0.476819, -0.258433, 0.520947, 0.425825, 0.509209, -0.263411, 0.517669, 0.465104, 0.542759, -0.266732, 0.512841, 0.505741, 0.574822, -0.268263, 0.503317, 0.547611, 0.609324, -0.268489, 0.493035, 0.590953, 0.641772, -0.266941, 0.478816, 0.63488, 0.674049, -0.263297, 0.462863, 0.679072, 0.705071, -0.257618, 0.442931, 0.723487, 0.734709, -0.250625, 0.421299, 0.768708, 0.763704, -0.24179, 0.397085, 0.814375, 0.791818, -0.231115, 0.370577, 0.859907, 0.817439, -0.21922, 0.34232, 0.906715, 0.843202, -0.205658, 0.312627, 0.953943, 0.866639, -0.190563, 0.280933, 1.00185, 0.888129, -0.173978, 0.248393, 1.05105, 0.907239, -0.155485, 0.216007, 1.09704, 0.923893, -0.134782, 0.183233, 1.13857, 0.938882, -0.11249, 0.150376, 1.17539, 0.952464, -0.0890706, 0.117177, 1.20924, 0.968529, -0.0646523, 0.0813095, 1.24055, 0.984763, -0.038606, 0.0439378, 1.27018, 1.00053, -0.01238, 0.00598668, 1.29873, 0.0437928, -0.00000409594, 0.204012, 0.000000879224, 0.0440166, -0.000103395, 0.205049, 0.0000221946, 0.0440529, -0.000413633, 0.205225, 0.0000887981, 0.0440493, -0.000930594, 0.2052, 0.000199858, 0.0439884, -0.00165352, 0.204901, 0.000355495, 0.0440716, -0.0025849, 0.205255, 0.000556983, 0.0440968, -0.00372222, 0.205311, 0.000805326, 0.0441359, -0.00506478, 0.205391, 0.00110333, 0.0442231, -0.00660384, 0.205638, 0.00145768, 0.0443254, -0.00835246, 0.205877, 0.00187275, 0.0444832, -0.0102992, 0.20627, 0.00235938, 0.0447001, -0.0124449, 0.206796, 0.0029299, 0.0450168, -0.0147935, 0.207593, 0.0036005, 0.0454816, -0.017336, 0.208819, 0.00439246, 0.0462446, -0.0201156, 0.211036, 0.00533864, 0.0473694, -0.0231568, 0.214388, 0.00646984, 0.0490191, -0.0264941, 0.219357, 0.00783856, 0.0512776, -0.030184, 0.226061, 0.00950182, 0.0541279, -0.0342661, 0.234094, 0.0115156, 0.0578989, -0.0388539, 0.244297, 0.0139687, 0.0620835, -0.0438735, 0.254457, 0.0169015, 0.0673497, -0.04951, 0.266706, 0.0204554, 0.0731759, -0.0556263, 0.278753, 0.0246606, 0.0803937, -0.0624585, 0.29309, 0.0297126, 0.0879287, -0.0697556, 0.305856, 0.0355868, 0.0970669, -0.0778795, 0.321059, 0.0425768, 0.106508, -0.0863541, 0.333873, 0.05056, 0.11776, -0.0955935, 0.349008, 0.0598972, 0.130081, -0.105438, 0.363776, 0.0706314, 0.144454, -0.115899, 0.380112, 0.0828822, 0.1596, -0.126827, 0.394843, 0.0967611, 0.176097, -0.138161, 0.409033, 0.112381, 0.194726, -0.149904, 0.424257, 0.129952, 0.213944, -0.161675, 0.436945, 0.149333, 0.235516, -0.173659, 0.450176, 0.170892, 0.260564, -0.185963, 0.466305, 0.194984, 0.285183, -0.197582, 0.477328, 0.220805, 0.311095, -0.208697, 0.486566, 0.248694, 0.338924, -0.219519, 0.494811, 0.279015, 0.369757, -0.229766, 0.504065, 0.311725, 0.3996, -0.238879, 0.507909, 0.345844, 0.430484, -0.246802, 0.509805, 0.381749, 0.46413, -0.253924, 0.511436, 0.420251, 0.497077, -0.259319, 0.508787, 0.459957, 0.530434, -0.263297, 0.50394, 0.501356, 0.565725, -0.265619, 0.49804, 0.544252, 0.599254, -0.265842, 0.487346, 0.587856, 0.631251, -0.263978, 0.472975, 0.631969, 0.663972, -0.26043, 0.457135, 0.677471, 0.697724, -0.255358, 0.439844, 0.723744, 0.727725, -0.248308, 0.417872, 0.770653, 0.756417, -0.239181, 0.39273, 0.817357, 0.785419, -0.22814, 0.367839, 0.864221, 0.81266, -0.215681, 0.339449, 0.912701, 0.839391, -0.201623, 0.309279, 0.962419, 0.86366, -0.185624, 0.278029, 1.0122, 0.885028, -0.16797, 0.245294, 1.06186, 0.904639, -0.148336, 0.212689, 1.10934, 0.922048, -0.12637, 0.179616, 1.15063, 0.936952, -0.102928, 0.146749, 1.18885, 0.951895, -0.0785268, 0.112733, 1.22352, 0.967198, -0.0530153, 0.0760056, 1.25681, 0.984405, -0.02649, 0.0383183, 1.28762, 1.00021, 0.00070019, -0.00020039, 1.31656, 0.0325964, -0.00000355447, 0.176706, 0.000000655682, 0.0329333, -0.0000899174, 0.178527, 0.0000165869, 0.0329181, -0.000359637, 0.178453, 0.0000663498, 0.0329085, -0.000808991, 0.178383, 0.000149332, 0.0329181, -0.00143826, 0.178394, 0.000265873, 0.0329425, -0.00224678, 0.178517, 0.000416597, 0.0329511, -0.00323575, 0.17849, 0.000603299, 0.033011, -0.00439875, 0.178695, 0.000829422, 0.0330733, -0.00574059, 0.178843, 0.00109908, 0.0331857, -0.00725896, 0.179176, 0.00141933, 0.0333445, -0.00895289, 0.179618, 0.0017999, 0.0335674, -0.0108219, 0.180238, 0.00225316, 0.033939, -0.0128687, 0.181417, 0.00279765, 0.0345239, -0.015114, 0.183395, 0.0034564, 0.0354458, -0.017596, 0.186616, 0.00425864, 0.0368313, -0.0203524, 0.191547, 0.00524936, 0.0386115, -0.0234105, 0.197508, 0.00647033, 0.0410303, -0.0268509, 0.205395, 0.00798121, 0.0442245, -0.0307481, 0.215365, 0.0098557, 0.0478659, -0.0350863, 0.225595, 0.0121417, 0.0522416, -0.0399506, 0.236946, 0.0149385, 0.0574513, -0.045357, 0.249442, 0.0183189, 0.0631208, -0.0512863, 0.261222, 0.0223644, 0.0701124, -0.0579273, 0.275418, 0.0272418, 0.0777331, -0.0650652, 0.288989, 0.0329458, 0.0862709, -0.0728813, 0.302546, 0.0396819, 0.096103, -0.081363, 0.317164, 0.04757, 0.106976, -0.0904463, 0.331733, 0.0567012, 0.119175, -0.100105, 0.34661, 0.067202, 0.132919, -0.110375, 0.362249, 0.0792588, 0.147727, -0.121115, 0.376978, 0.0928672, 0.163618, -0.132299, 0.390681, 0.108228, 0.182234, -0.143887, 0.406571, 0.125502, 0.201809, -0.155827, 0.42042, 0.144836, 0.225041, -0.168357, 0.438411, 0.166706, 0.247621, -0.18004, 0.450368, 0.189909, 0.27097, -0.191536, 0.460083, 0.215251, 0.296658, -0.203024, 0.469765, 0.243164, 0.325892, -0.214056, 0.481837, 0.273388, 0.35406, -0.224104, 0.487474, 0.305344, 0.384372, -0.233489, 0.492773, 0.339741, 0.41749, -0.241874, 0.498451, 0.376287, 0.45013, -0.248834, 0.499632, 0.414195, 0.481285, -0.254658, 0.495233, 0.454077, 0.519183, -0.259367, 0.496401, 0.496352, 0.551544, -0.261818, 0.487686, 0.538798, 0.587349, -0.262964, 0.479453, 0.583626, 0.621679, -0.262128, 0.467709, 0.629451, 0.654991, -0.258998, 0.452123, 0.67566, 0.686873, -0.254119, 0.433495, 0.723248, 0.719801, -0.246946, 0.413657, 0.771156, 0.750355, -0.237709, 0.390366, 0.81989, 0.780033, -0.226549, 0.364947, 0.868601, 0.809254, -0.214186, 0.337256, 0.920034, 0.836576, -0.199639, 0.307395, 0.971706, 0.861774, -0.183169, 0.275431, 1.02479, 0.885707, -0.165111, 0.243431, 1.07837, 0.904742, -0.144363, 0.210921, 1.12783, 0.915604, -0.121305, 0.17647, 1.17254, 0.930959, -0.0962119, 0.143106, 1.21012, 0.948404, -0.069969, 0.108112, 1.24474, 0.967012, -0.0427586, 0.0708478, 1.27718, 0.984183, -0.0147043, 0.032335, 1.3083, 0.999577, 0.0142165, -0.00726867, 1.3382, 0.0229227, -0.00000299799, 0.148623, 0.000000462391, 0.0232194, -0.0000758796, 0.15054, 0.0000117033, 0.0232315, -0.000303636, 0.15063, 0.0000468397, 0.0232354, -0.000683189, 0.150624, 0.000105472, 0.0232092, -0.0012136, 0.150445, 0.000187744, 0.0232523, -0.00189765, 0.150679, 0.000294847, 0.0232828, -0.00273247, 0.150789, 0.000428013, 0.0233371, -0.00371287, 0.150995, 0.000591134, 0.0234015, -0.00484794, 0.15118, 0.000787642, 0.023514, -0.00612877, 0.151562, 0.00102547, 0.023679, -0.00756125, 0.152116, 0.00131351, 0.0239559, -0.00914651, 0.153162, 0.00166594, 0.0244334, -0.010904, 0.155133, 0.00210182, 0.025139, -0.0128615, 0.158035, 0.00264406, 0.0262598, -0.0150628, 0.162751, 0.00332923, 0.0277875, -0.0175532, 0.168944, 0.00419773, 0.0298472, -0.0203981, 0.176835, 0.00530034, 0.0325444, -0.023655, 0.186686, 0.00669777, 0.0355581, -0.0272982, 0.196248, 0.00842661, 0.0392841, -0.0314457, 0.207352, 0.0105854, 0.0436815, -0.0361157, 0.219279, 0.0132458, 0.0485272, -0.0412932, 0.230728, 0.0164736, 0.0541574, -0.0470337, 0.242994, 0.0203715, 0.0609479, -0.0535002, 0.257042, 0.0250953, 0.0685228, -0.0605409, 0.27102, 0.0306856, 0.0768042, -0.0680553, 0.28406, 0.037193, 0.0864844, -0.0765011, 0.299186, 0.0449795, 0.0969415, -0.0852674, 0.3132, 0.0538316, 0.108478, -0.0947333, 0.327138, 0.0641149, 0.121705, -0.10481, 0.342345, 0.0759185, 0.136743, -0.115474, 0.358472, 0.0894116, 0.152986, -0.126536, 0.374067, 0.104562, 0.170397, -0.138061, 0.388267, 0.121632, 0.191392, -0.150203, 0.406467, 0.140996, 0.211566, -0.161751, 0.418641, 0.161696, 0.233567, -0.173407, 0.430418, 0.184557, 0.257769, -0.185397, 0.44277, 0.210092, 0.28531, -0.197048, 0.457191, 0.237827, 0.311726, -0.20784, 0.464712, 0.267253, 0.340537, -0.218345, 0.472539, 0.299332, 0.372921, -0.228306, 0.482331, 0.333988, 0.402924, -0.236665, 0.484378, 0.369722, 0.434475, -0.244097, 0.484717, 0.407836, 0.469736, -0.250547, 0.487093, 0.448465, 0.505045, -0.25511, 0.485575, 0.490263, 0.540262, -0.258444, 0.481225, 0.534495, 0.576347, -0.259903, 0.473481, 0.579451, 0.608656, -0.259572, 0.4603, 0.625604, 0.646679, -0.257908, 0.450341, 0.674511, 0.679902, -0.253663, 0.431561, 0.723269, 0.714159, -0.247419, 0.412684, 0.773263, 0.745345, -0.239122, 0.389388, 0.824182, 0.778248, -0.228837, 0.365361, 0.876634, 0.807208, -0.216197, 0.337667, 0.92945, 0.835019, -0.201772, 0.307197, 0.985261, 0.860261, -0.185291, 0.274205, 1.04299, 0.877601, -0.165809, 0.240178, 1.09816, 0.898211, -0.143897, 0.207571, 1.14694, 0.915789, -0.119513, 0.174904, 1.19008, 0.931831, -0.0932919, 0.141423, 1.2297, 0.949244, -0.0656528, 0.105603, 1.26553, 0.967527, -0.0370262, 0.0679551, 1.29986, 0.984139, -0.00730117, 0.0283133, 1.33252, 0.999713, 0.0234648, -0.0121785, 1.36397, 0.0152135, -0.00000245447, 0.122795, 0.000000304092, 0.0151652, -0.0000615778, 0.122399, 0.0000076292, 0.0151181, -0.000245948, 0.122023, 0.0000304802, 0.0151203, -0.000553394, 0.12203, 0.0000686634, 0.015125, -0.000983841, 0.122037, 0.000122463, 0.0151427, -0.00153774, 0.12214, 0.000192706, 0.0151708, -0.0022103, 0.122237, 0.000281219, 0.0152115, -0.00300741, 0.12238, 0.000390804, 0.0152877, -0.00392494, 0.1227, 0.000526317, 0.015412, -0.00496597, 0.123244, 0.00069443, 0.0156201, -0.00613314, 0.124228, 0.00090547, 0.0159658, -0.00744113, 0.125945, 0.0011732, 0.0165674, -0.00892546, 0.129098, 0.00151888, 0.017487, -0.010627, 0.133865, 0.00197007, 0.018839, -0.0126043, 0.140682, 0.0025637, 0.020554, -0.0148814, 0.148534, 0.00333637, 0.0226727, -0.0175123, 0.157381, 0.00433738, 0.0251879, -0.0205266, 0.166685, 0.00561664, 0.0283635, -0.0240319, 0.177796, 0.00725563, 0.0318694, -0.0279432, 0.188251, 0.00928811, 0.0361044, -0.0324313, 0.200038, 0.011835, 0.0406656, -0.0373527, 0.210685, 0.0149146, 0.0463846, -0.0430132, 0.224182, 0.0187254, 0.0525696, -0.0491013, 0.23634, 0.0232283, 0.0598083, -0.0559175, 0.250013, 0.0286521, 0.0679437, -0.0633657, 0.263981, 0.0350634, 0.0771181, -0.0714602, 0.278072, 0.0425882, 0.0881273, -0.0803502, 0.29511, 0.0514487, 0.0996628, -0.0896903, 0.309976, 0.0615766, 0.112702, -0.099644, 0.325611, 0.0732139, 0.126488, -0.109829, 0.339321, 0.0862324, 0.142625, -0.120859, 0.35574, 0.101275, 0.15953, -0.131956, 0.369845, 0.117892, 0.176991, -0.143145, 0.38146, 0.136205, 0.199715, -0.155292, 0.40052, 0.157252, 0.220787, -0.167066, 0.412055, 0.179966, 0.243697, -0.178396, 0.423133, 0.204418, 0.272106, -0.190433, 0.439524, 0.232141, 0.297637, -0.201265, 0.447041, 0.261109, 0.325273, -0.211834, 0.454488, 0.292627, 0.357219, -0.221889, 0.465004, 0.326669, 0.387362, -0.230729, 0.468527, 0.362426, 0.423131, -0.23924, 0.475836, 0.401533, 0.45543, -0.246067, 0.475017, 0.441902, 0.493393, -0.251557, 0.478017, 0.484239, 0.526253, -0.255571, 0.4709, 0.528586, 0.560554, -0.257752, 0.463167, 0.574346, 0.599306, -0.258076, 0.456452, 0.621655, 0.634541, -0.256471, 0.443725, 0.670492, 0.668907, -0.253283, 0.428719, 0.721943, 0.705619, -0.247562, 0.411348, 0.772477, 0.739034, -0.240626, 0.388939, 0.8264, 0.771408, -0.231493, 0.36425, 0.881702, 0.803312, -0.220125, 0.337321, 0.9385, 0.828457, -0.206645, 0.305364, 0.997437, 0.854819, -0.190664, 0.273715, 1.05693, 0.878666, -0.171429, 0.242218, 1.11251, 0.898404, -0.149235, 0.209556, 1.16398, 0.917416, -0.12435, 0.176863, 1.21014, 0.933133, -0.0972703, 0.142775, 1.25178, 0.95066, -0.0683607, 0.106735, 1.29028, 0.968589, -0.0378724, 0.0681609, 1.32703, 0.984776, -0.00605712, 0.0273966, 1.36158, 0.99994, 0.0263276, -0.0138124, 1.3943, 0.00867437, -0.00000186005, 0.0928979, 0.000000173682, 0.00864003, -0.0000466389, 0.0925237, 0.00000435505, 0.00864593, -0.000186594, 0.0925806, 0.0000174322, 0.00864095, -0.000419639, 0.0924903, 0.0000392862, 0.00863851, -0.000746272, 0.0924589, 0.0000702598, 0.00868531, -0.00116456, 0.0929, 0.000111188, 0.00869667, -0.00167711, 0.0928529, 0.000163867, 0.00874332, -0.00228051, 0.0930914, 0.00023104, 0.00882709, -0.00297864, 0.0935679, 0.00031741, 0.00898874, -0.00377557, 0.0946165, 0.000430186, 0.00929346, -0.00469247, 0.0967406, 0.000580383, 0.00978271, -0.00575491, 0.100084, 0.000783529, 0.0105746, -0.00701514, 0.105447, 0.00106304, 0.0116949, -0.00851797, 0.112494, 0.00144685, 0.0130419, -0.0102757, 0.119876, 0.00196439, 0.0148375, -0.012381, 0.129034, 0.00266433, 0.0168725, -0.01482, 0.137812, 0.00358364, 0.0193689, -0.0176563, 0.147696, 0.00478132, 0.0222691, -0.0209211, 0.157795, 0.00631721, 0.0256891, -0.0246655, 0.168431, 0.00826346, 0.0294686, -0.0288597, 0.178587, 0.0106714, 0.0340412, -0.0336441, 0.190251, 0.0136629, 0.0393918, -0.039033, 0.202999, 0.0173272, 0.0453947, -0.0450087, 0.215655, 0.0217448, 0.0521936, -0.0515461, 0.228686, 0.0269941, 0.0600279, -0.058817, 0.242838, 0.033272, 0.0692398, -0.0667228, 0.258145, 0.0406457, 0.0793832, -0.0752401, 0.273565, 0.0492239, 0.0902297, -0.0841851, 0.287735, 0.0590105, 0.102014, -0.0936479, 0.301161, 0.0702021, 0.116054, -0.103967, 0.317438, 0.0832001, 0.13191, -0.114622, 0.334166, 0.0977951, 0.148239, -0.125452, 0.348192, 0.113985, 0.165809, -0.136453, 0.361094, 0.131928, 0.184616, -0.147648, 0.373534, 0.151811, 0.207491, -0.159607, 0.39101, 0.174476, 0.230106, -0.171119, 0.402504, 0.198798, 0.257036, -0.182906, 0.418032, 0.225796, 0.281172, -0.193605, 0.425468, 0.254027, 0.312034, -0.204771, 0.440379, 0.285713, 0.340402, -0.214988, 0.445406, 0.319196, 0.370231, -0.224711, 0.44968, 0.35537, 0.407105, -0.233516, 0.460747, 0.393838, 0.439037, -0.240801, 0.460624, 0.433747, 0.47781, -0.24762, 0.465957, 0.477234, 0.510655, -0.251823, 0.460054, 0.52044, 0.550584, -0.255552, 0.459172, 0.567853, 0.585872, -0.257036, 0.450311, 0.615943, 0.620466, -0.257535, 0.437763, 0.667693, 0.660496, -0.255248, 0.426639, 0.718988, 0.695578, -0.251141, 0.409185, 0.772503, 0.732176, -0.244718, 0.39015, 0.827023, 0.760782, -0.236782, 0.362594, 0.885651, 0.79422, -0.225923, 0.33711, 0.943756, 0.824521, -0.213855, 0.308272, 1.00874, 0.854964, -0.197723, 0.278529, 1.06764, 0.878065, -0.179209, 0.246208, 1.12836, 0.899834, -0.157569, 0.21329, 1.18318, 0.918815, -0.133206, 0.181038, 1.23161, 0.934934, -0.106545, 0.146993, 1.27644, 0.952115, -0.0780574, 0.111175, 1.31842, 0.96906, -0.0478279, 0.0728553, 1.35839, 0.985178, -0.0160014, 0.032579, 1.39697, 1.00039, 0.0173126, -0.0095256, 1.43312, 0.00384146, -0.00000124311, 0.0613583, 0.0000000778271, 0.00390023, -0.0000314043, 0.0622919, 0.00000196626, 0.00389971, -0.000125622, 0.0622632, 0.00000787379, 0.00389491, -0.000282352, 0.0620659, 0.00001778, 0.00391618, -0.000502512, 0.0624687, 0.0000320918, 0.00392662, -0.000784458, 0.0625113, 0.0000515573, 0.00396053, -0.00112907, 0.0628175, 0.0000778668, 0.00401911, -0.00153821, 0.0633286, 0.000113811, 0.00414994, -0.0020208, 0.0646443, 0.00016445, 0.00441223, -0.00260007, 0.0673886, 0.000237734, 0.00484427, -0.0033097, 0.0716528, 0.000345929, 0.00549109, -0.00418966, 0.0774998, 0.000505987, 0.00636293, -0.00527331, 0.0844758, 0.000739208, 0.00746566, -0.00660428, 0.0921325, 0.00107347, 0.00876625, -0.00818826, 0.0997067, 0.00153691, 0.0103125, -0.0100811, 0.107433, 0.00217153, 0.0123309, -0.0123643, 0.117088, 0.00303427, 0.0146274, -0.0150007, 0.126438, 0.00416018, 0.0172295, -0.0180531, 0.135672, 0.00561513, 0.0204248, -0.0215962, 0.146244, 0.007478, 0.0241597, -0.0256234, 0.157481, 0.00981046, 0.0284693, -0.0302209, 0.169125, 0.0127148, 0.033445, -0.0353333, 0.181659, 0.0162453, 0.0391251, -0.0410845, 0.1944, 0.0205417, 0.0454721, -0.0473451, 0.207082, 0.0256333, 0.0530983, -0.0542858, 0.221656, 0.0317036, 0.0615356, -0.0618384, 0.236036, 0.0388319, 0.0703363, -0.0697631, 0.248398, 0.046974, 0.0810391, -0.0784757, 0.263611, 0.0565246, 0.0920144, -0.0873488, 0.275857, 0.0671724, 0.105584, -0.0973652, 0.292555, 0.0798105, 0.119506, -0.107271, 0.306333, 0.0935945, 0.134434, -0.117608, 0.318888, 0.109106, 0.153399, -0.128938, 0.337552, 0.127074, 0.171258, -0.139944, 0.349955, 0.14643, 0.191059, -0.151288, 0.361545, 0.168, 0.215069, -0.163018, 0.378421, 0.192082, 0.237838, -0.174226, 0.38879, 0.217838, 0.266965, -0.186063, 0.405857, 0.246931, 0.292827, -0.196909, 0.414146, 0.277505, 0.324352, -0.207473, 0.426955, 0.310711, 0.354427, -0.217713, 0.433429, 0.346794, 0.389854, -0.227183, 0.443966, 0.385237, 0.420749, -0.235131, 0.44471, 0.424955, 0.459597, -0.242786, 0.451729, 0.468446, 0.495316, -0.248767, 0.45072, 0.513422, 0.534903, -0.253351, 0.450924, 0.560618, 0.572369, -0.256277, 0.445266, 0.609677, 0.612383, -0.2576, 0.438798, 0.660995, 0.644037, -0.256931, 0.421693, 0.713807, 0.686749, -0.254036, 0.4109, 0.767616, 0.719814, -0.249785, 0.390151, 0.82533, 0.754719, -0.244283, 0.367847, 0.888311, 0.792022, -0.235076, 0.345013, 0.948177, 0.822404, -0.225061, 0.316193, 1.01661, 0.853084, -0.211113, 0.287013, 1.08075, 0.879871, -0.19449, 0.255424, 1.14501, 0.901655, -0.174023, 0.222879, 1.20203, 0.919957, -0.1509, 0.18989, 1.25698, 0.938412, -0.124923, 0.15606, 1.30588, 0.953471, -0.0968139, 0.120512, 1.3529, 0.970451, -0.066734, 0.0828515, 1.3986, 0.985522, -0.034734, 0.0424458, 1.44148, 1.00099, -0.00102222, 0.000678929, 1.48398, 0.000965494, -0.000000627338, 0.0306409, 0.0000000197672, 0.00099168, -0.0000158573, 0.0314638, 0.000000499803, 0.000991068, -0.0000634012, 0.031363, 0.00000200682, 0.000974567, -0.00014144, 0.03036, 0.00000457312, 0.000998079, -0.000252812, 0.031496, 0.00000860131, 0.00102243, -0.000396506, 0.0319955, 0.0000148288, 0.00107877, -0.000577593, 0.0331376, 0.0000249141, 0.00121622, -0.000816816, 0.0359396, 0.0000423011, 0.0014455, -0.00113761, 0.0399652, 0.0000724613, 0.00178791, -0.00156959, 0.0450556, 0.000123929, 0.00225668, -0.00214064, 0.0508025, 0.000208531, 0.00285627, -0.00287655, 0.0568443, 0.000341969, 0.0035991, -0.00380271, 0.0630892, 0.000544158, 0.00455524, -0.00496264, 0.0702204, 0.000842423, 0.00569143, -0.0063793, 0.0773426, 0.00126704, 0.00716928, -0.00813531, 0.0860839, 0.00186642, 0.00885307, -0.0101946, 0.0944079, 0.00267014, 0.0109316, -0.0126386, 0.103951, 0.00374033, 0.0133704, -0.0154876, 0.113786, 0.0051304, 0.0161525, -0.0187317, 0.123477, 0.00688858, 0.0194267, -0.0224652, 0.133986, 0.00910557, 0.0230967, -0.0265976, 0.143979, 0.0118074, 0.0273627, -0.0312848, 0.154645, 0.0151266, 0.0323898, -0.0365949, 0.166765, 0.0191791, 0.0379225, -0.0422914, 0.177932, 0.0239236, 0.0447501, -0.0487469, 0.19167, 0.0296568, 0.0519391, -0.0556398, 0.203224, 0.0362924, 0.0599464, -0.0631646, 0.215652, 0.0440585, 0.0702427, -0.0714308, 0.232089, 0.0531619, 0.0806902, -0.0800605, 0.245258, 0.0634564, 0.0923194, -0.0892815, 0.258609, 0.0752481, 0.106938, -0.09931, 0.276654, 0.0888914, 0.121238, -0.109575, 0.289847, 0.104055, 0.138817, -0.120461, 0.307566, 0.121266, 0.15595, -0.131209, 0.320117, 0.139944, 0.178418, -0.143049, 0.339677, 0.161591, 0.197875, -0.154074, 0.349886, 0.184303, 0.224368, -0.166307, 0.369352, 0.210669, 0.252213, -0.178051, 0.386242, 0.238895, 0.277321, -0.189335, 0.395294, 0.269182, 0.310332, -0.200683, 0.412148, 0.302508, 0.338809, -0.210856, 0.418266, 0.337264, 0.372678, -0.220655, 0.428723, 0.374881, 0.405632, -0.230053, 0.433887, 0.415656, 0.442293, -0.237993, 0.439911, 0.457982, 0.477256, -0.244897, 0.440175, 0.502831, 0.515592, -0.250657, 0.441079, 0.550277, 0.550969, -0.255459, 0.435219, 0.601102, 0.592883, -0.257696, 0.432882, 0.651785, 0.629092, -0.259894, 0.421054, 0.708961, 0.672033, -0.258592, 0.41177, 0.763806, 0.709147, -0.256525, 0.395267, 0.824249, 0.745367, -0.254677, 0.375013, 0.8951, 0.784715, -0.247892, 0.353906, 0.959317, 0.818107, -0.240162, 0.327801, 1.03153, 0.847895, -0.229741, 0.298821, 1.10601, 0.879603, -0.213084, 0.269115, 1.164, 0.902605, -0.195242, 0.236606, 1.22854, 0.922788, -0.174505, 0.203442, 1.29017, 0.944831, -0.150169, 0.169594, 1.34157, 0.959656, -0.124099, 0.135909, 1.3956, 0.972399, -0.0960626, 0.0990563, 1.45128, 0.986549, -0.0657097, 0.0602348, 1.50312, 1.00013, -0.0333558, 0.0186694, 1.55364, 0.00000619747, -0.0000001, 0.00778326, 0.0000000000796756, 0.0000000237499, -0.0000000999999, 0.0000282592, 0.000000000114596, 0.00000100292, -0.00000166369, 0.000250354, 0.00000000677492, 0.00000350752, -0.00000637769, 0.000357289, 0.0000000631655, 0.00000826445, -0.0000174689, 0.000516179, 0.00000031851, 0.0000242481, -0.0000450868, 0.0010223, 0.00000130577, 0.0000455631, -0.000089044, 0.00144302, 0.00000374587, 0.0000971222, -0.000178311, 0.00241912, 0.0000102584, 0.000171403, -0.000313976, 0.00354938, 0.0000236481, 0.000292747, -0.000520026, 0.00513765, 0.0000496014, 0.000789827, -0.00118187, 0.0238621, 0.000139056, 0.00114093, -0.00171827, 0.0286691, 0.000244093, 0.00176119, -0.00249667, 0.0368565, 0.000420623, 0.0022233, -0.00333742, 0.0400469, 0.00065673, 0.00343382, -0.00481976, 0.0535751, 0.00109323, 0.00427602, -0.00600755, 0.057099, 0.00155268, 0.00461435, -0.00737637, 0.0551084, 0.00215031, 0.00695698, -0.00971401, 0.0715767, 0.00316529, 0.00867619, -0.0120943, 0.0793314, 0.00436995, 0.0106694, -0.0148202, 0.0869391, 0.0058959, 0.0140351, -0.0183501, 0.101572, 0.00798757, 0.0168939, -0.022006, 0.11018, 0.0104233, 0.020197, -0.0261568, 0.119041, 0.0134167, 0.0254702, -0.0312778, 0.135404, 0.0173009, 0.0298384, -0.0362469, 0.1437, 0.0215428, 0.035159, -0.042237, 0.15512, 0.0268882, 0.0427685, -0.0488711, 0.17128, 0.033235, 0.0494848, -0.0557997, 0.181813, 0.0404443, 0.0592394, -0.0635578, 0.198745, 0.0490043, 0.0681463, -0.071838, 0.210497, 0.0588239, 0.0804753, -0.0809297, 0.228864, 0.0702835, 0.0942205, -0.0906488, 0.247008, 0.0834012, 0.106777, -0.100216, 0.258812, 0.0975952, 0.124471, -0.110827, 0.278617, 0.114162, 0.138389, -0.121193, 0.287049, 0.131983, 0.159543, -0.13253, 0.307151, 0.152541, 0.176432, -0.143611, 0.31564, 0.174673, 0.201723, -0.15548, 0.33538, 0.199842, 0.229721, -0.167166, 0.355256, 0.227097, 0.250206, -0.178238, 0.360047, 0.256014, 0.282118, -0.189905, 0.378761, 0.28855, 0.312821, -0.201033, 0.39181, 0.323348, 0.341482, -0.211584, 0.397716, 0.360564, 0.377368, -0.221314, 0.410141, 0.400004, 0.418229, -0.230474, 0.423485, 0.442371, 0.444881, -0.239443, 0.418874, 0.488796, 0.488899, -0.245987, 0.427545, 0.535012, 0.520317, -0.253948, 0.422147, 0.589678, 0.568566, -0.256616, 0.42719, 0.637683, 0.599607, -0.26376, 0.415114, 0.703363, 0.64222, -0.268687, 0.408715, 0.771363, 0.685698, -0.2694, 0.399722, 0.83574, 0.732327, -0.266642, 0.388651, 0.897764, 0.769873, -0.267712, 0.369198, 0.983312, 0.806733, -0.263479, 0.346802, 1.06222, 0.843466, -0.254575, 0.321368, 1.13477, 0.873008, -0.242749, 0.29211, 1.20712, 0.908438, -0.22725, 0.262143, 1.27465, 0.936321, -0.207621, 0.228876, 1.33203, 0.950353, -0.187932, 0.19484, 1.40439, 0.96442, -0.165154, 0.163178, 1.4732, 0.979856, -0.139302, 0.127531, 1.53574, 0.982561, -0.11134, 0.0903457, 1.59982, 0.996389, -0.0808124, 0.0489007, 1.6577]; + const LTC_MAT_2 = [1, 0, 0, 0, 1, 0.000000000000000000000000000000791421, 0, 0, 1, 0.00000000000000000000000104392, 0, 0, 1, 0.00000000000000000000349405, 0, 0, 1, 0.00000000000000000109923, 0, 0, 1, 0.0000000000000000947414, 0, 0, 1, 0.00000000000000359627, 0, 0, 1, 0.0000000000000772053, 0, 0, 1, 0.00000000000108799, 0, 0, 1, 0.0000000000110655, 0, 0, 1, 0.0000000000865818, 0, 0, 0.999998, 0.000000000545037, 0, 0, 0.999994, 0.00000000285095, 0, 0, 0.999989, 0.0000000126931, 0, 0, 0.999973, 0.0000000489938, 0, 0, 0.999947, 0.000000166347, 0, 0, 0.999894, 0.000000502694, 0, 0, 0.999798, 0.00000136532, 0, 0, 0.999617, 0.00000335898, 0, 0, 0.999234, 0.00000752126, 0, 0, 0.998258, 0.0000152586, 0, 0, 0.99504, 0.0000266207, 0, 0, 0.980816, 0.0000236802, 0, 0, 0.967553, 0.00000207684, 0, 0, 0.966877, 0.00000403733, 0, 0, 0.965752, 0.00000741174, 0, 0, 0.96382, 0.0000127746, 0, 0, 0.960306, 0.0000202792, 0, 0, 0.953619, 0.0000280232, 0, 0, 0.941103, 0.0000278816, 0, 0, 0.926619, 0.0000160221, 0, 0, 0.920983, 0.0000235164, 0, 0, 0.912293, 0.0000311924, 0, 0.0158731, 0.899277, 0.0000348118, 0, 0.0476191, 0.880884, 0.000026041, 0, 0.0793651, 0.870399, 0.0000338726, 0, 0.111111, 0.856138, 0.0000392906, 0, 0.142857, 0.837436, 0.0000372874, 0, 0.174603, 0.820973, 0.0000392558, 0, 0.206349, 0.803583, 0.0000434658, 0, 0.238095, 0.782168, 0.000040256, 0, 0.269841, 0.764107, 0.0000448159, 0, 0.301587, 0.743092, 0.0000457627, 0, 0.333333, 0.721626, 0.0000455314, 0, 0.365079, 0.700375, 0.0000477335, 0, 0.396825, 0.677334, 0.0000461072, 0, 0.428571, 0.655702, 0.0000484393, 0, 0.460317, 0.632059, 0.0000464583, 0, 0.492064, 0.610125, 0.0000483923, 0, 0.52381, 0.58653, 0.0000464342, 0, 0.555556, 0.564508, 0.0000477033, 0, 0.587302, 0.541405, 0.0000459263, 0, 0.619048, 0.519556, 0.000046412, 0, 0.650794, 0.497292, 0.0000448913, 0, 0.68254, 0.475898, 0.0000445789, 0, 0.714286, 0.454722, 0.0000433496, 0, 0.746032, 0.434042, 0.0000423054, 0, 0.777778, 0.414126, 0.0000413737, 0, 0.809524, 0.394387, 0.0000397265, 0, 0.84127, 0.375841, 0.0000390709, 0, 0.873016, 0.357219, 0.0000369938, 0, 0.904762, 0.340084, 0.0000365618, 0, 0.936508, 0.322714, 0.0000342533, 0, 0.968254, 0.306974, 0.0000339596, 0, 1, 1, 0.00000000000000000101524, 0, 0, 1, 0.0000000000000000010292, 0, 0, 1, 0.00000000000000000130908, 0, 0, 1, 0.00000000000000000473331, 0, 0, 1, 0.0000000000000000625319, 0, 0, 1, 0.00000000000000107932, 0, 0, 1, 0.0000000000000163779, 0, 0, 1, 0.000000000000203198, 0, 0, 1, 0.00000000000204717, 0, 0, 0.999999, 0.0000000000168995, 0, 0, 0.999998, 0.000000000115855, 0, 0, 0.999996, 0.00000000066947, 0, 0, 0.999991, 0.00000000330863, 0, 0, 0.999983, 0.0000000141737, 0, 0, 0.999968, 0.0000000532626, 0, 0, 0.99994, 0.000000177431, 0, 0, 0.999891, 0.000000528835, 0, 0, 0.999797, 0.00000142169, 0, 0, 0.999617, 0.00000347057, 0, 0, 0.999227, 0.0000077231, 0, 0, 0.998239, 0.0000155753, 0, 0, 0.994937, 0.0000268495, 0, 0, 0.980225, 0.0000213742, 0, 0, 0.967549, 0.0000021631, 0, 0, 0.966865, 0.00000417989, 0, 0, 0.965739, 0.00000763341, 0, 0, 0.963794, 0.0000130892, 0, 0, 0.960244, 0.0000206456, 0, 0, 0.953495, 0.0000282016, 0, 0.000148105, 0.940876, 0.0000271581, 0, 0.002454, 0.926569, 0.0000164159, 0, 0.00867491, 0.920905, 0.0000239521, 0, 0.01956, 0.912169, 0.0000315127, 0, 0.035433, 0.899095, 0.0000346626, 0, 0.056294, 0.882209, 0.0000290223, 0, 0.0818191, 0.870272, 0.0000342992, 0, 0.111259, 0.855977, 0.0000394164, 0, 0.142857, 0.837431, 0.0000372343, 0, 0.174603, 0.820826, 0.0000396691, 0, 0.206349, 0.803408, 0.0000435395, 0, 0.238095, 0.782838, 0.0000419579, 0, 0.269841, 0.763941, 0.0000450953, 0, 0.301587, 0.742904, 0.0000455847, 0, 0.333333, 0.721463, 0.0000458833, 0, 0.365079, 0.700197, 0.0000477159, 0, 0.396825, 0.677501, 0.0000470641, 0, 0.428571, 0.655527, 0.0000484732, 0, 0.460317, 0.6324, 0.0000476834, 0, 0.492064, 0.609964, 0.0000484213, 0, 0.52381, 0.586839, 0.0000475541, 0, 0.555556, 0.564353, 0.0000476951, 0, 0.587302, 0.541589, 0.0000467611, 0, 0.619048, 0.519413, 0.0000463493, 0, 0.650794, 0.497337, 0.0000453994, 0, 0.68254, 0.475797, 0.0000445308, 0, 0.714286, 0.454659, 0.0000435787, 0, 0.746032, 0.434065, 0.0000424839, 0, 0.777778, 0.414018, 0.000041436, 0, 0.809524, 0.39455, 0.0000401902, 0, 0.84127, 0.375742, 0.0000390813, 0, 0.873016, 0.357501, 0.0000377116, 0, 0.904762, 0.339996, 0.000036535, 0, 0.936508, 0.323069, 0.0000351265, 0, 0.968254, 0.306897, 0.0000339112, 0, 1, 1, 0.0000000000000010396, 0, 0, 1, 0.00000000000000104326, 0, 0, 1, 0.00000000000000110153, 0, 0, 1, 0.00000000000000144668, 0, 0, 1, 0.0000000000000034528, 0, 0, 1, 0.0000000000000175958, 0, 0, 1, 0.00000000000012627, 0, 0, 1, 0.000000000000936074, 0, 0, 1, 0.00000000000645742, 0, 0, 0.999998, 0.0000000000401228, 0, 0, 0.999997, 0.000000000222338, 0, 0, 0.999995, 0.0000000010967, 0, 0, 0.999991, 0.00000000482132, 0, 0, 0.999981, 0.0000000189434, 0, 0, 0.999967, 0.0000000667716, 0, 0, 0.999938, 0.000000212066, 0, 0, 0.999886, 0.00000060977, 0, 0, 0.999792, 0.00000159504, 0, 0, 0.999608, 0.00000381191, 0, 0, 0.999209, 0.00000833727, 0, 0, 0.998179, 0.0000165288, 0, 0, 0.994605, 0.0000274387, 0, 0, 0.979468, 0.0000167316, 0, 0, 0.967529, 0.00000242877, 0, 0, 0.966836, 0.00000461696, 0, 0, 0.96569, 0.00000830977, 0, 0, 0.963706, 0.0000140427, 0, 0.00000244659, 0.960063, 0.0000217353, 0, 0.000760774, 0.953113, 0.0000286606, 0, 0.00367261, 0.940192, 0.0000247691, 0, 0.00940263, 0.927731, 0.0000195814, 0, 0.018333, 0.920669, 0.0000252531, 0, 0.0306825, 0.911799, 0.0000324277, 0, 0.0465556, 0.89857, 0.0000340982, 0, 0.0659521, 0.883283, 0.0000319622, 0, 0.0887677, 0.86989, 0.000035548, 0, 0.114784, 0.855483, 0.0000397143, 0, 0.143618, 0.837987, 0.0000391665, 0, 0.174606, 0.820546, 0.0000411306, 0, 0.206349, 0.802878, 0.0000436753, 0, 0.238095, 0.783402, 0.0000444, 0, 0.269841, 0.763439, 0.0000458726, 0, 0.301587, 0.742925, 0.0000467097, 0, 0.333333, 0.721633, 0.0000478887, 0, 0.365079, 0.69985, 0.0000481251, 0, 0.396825, 0.67783, 0.0000491811, 0, 0.428571, 0.655126, 0.0000488199, 0, 0.460318, 0.632697, 0.0000496025, 0, 0.492064, 0.609613, 0.000048829, 0, 0.52381, 0.587098, 0.0000492754, 0, 0.555556, 0.564119, 0.0000482625, 0, 0.587302, 0.541813, 0.0000482807, 0, 0.619048, 0.519342, 0.0000471552, 0, 0.650794, 0.497514, 0.0000466765, 0, 0.68254, 0.475879, 0.0000455582, 0, 0.714286, 0.454789, 0.0000446007, 0, 0.746032, 0.434217, 0.0000435382, 0, 0.777778, 0.414086, 0.0000421753, 0, 0.809524, 0.394744, 0.0000412093, 0, 0.84127, 0.375782, 0.0000396634, 0, 0.873016, 0.357707, 0.0000386419, 0, 0.904762, 0.340038, 0.0000370345, 0, 0.936508, 0.323284, 0.0000359725, 0, 0.968254, 0.306954, 0.00003436, 0, 1, 1, 0.0000000000000599567, 0, 0, 1, 0.0000000000000600497, 0, 0, 1, 0.0000000000000614839, 0, 0, 1, 0.0000000000000686641, 0, 0, 1, 0.0000000000000972658, 0, 0, 1, 0.000000000000221271, 0, 0, 1, 0.000000000000833195, 0, 0, 1, 0.00000000000403601, 0, 0, 0.999999, 0.0000000000206001, 0, 0, 0.999998, 0.000000000101739, 0, 0, 0.999997, 0.000000000470132, 0, 0, 0.999993, 0.00000000200436, 0, 0, 0.999988, 0.00000000783682, 0, 0, 0.999979, 0.0000000280338, 0, 0, 0.999962, 0.0000000917033, 0, 0, 0.999933, 0.000000274514, 0, 0, 0.999881, 0.000000753201, 0, 0, 0.999783, 0.00000189826, 0, 0, 0.999594, 0.00000440279, 0, 0, 0.999178, 0.0000093898, 0, 0, 0.998073, 0.0000181265, 0, 0, 0.993993, 0.0000280487, 0, 0, 0.979982, 0.0000149422, 0, 0, 0.968145, 0.00000378481, 0, 0, 0.966786, 0.0000053771, 0, 0, 0.965611, 0.00000947508, 0, 0.0000388934, 0.963557, 0.0000156616, 0, 0.0009693, 0.959752, 0.0000235144, 0, 0.00370329, 0.952461, 0.0000291568, 0, 0.00868428, 0.940193, 0.0000240102, 0, 0.0161889, 0.929042, 0.0000231235, 0, 0.0263948, 0.920266, 0.0000273968, 0, 0.0394088, 0.911178, 0.0000337915, 0, 0.0552818, 0.897873, 0.0000333629, 0, 0.0740138, 0.884053, 0.0000351405, 0, 0.0955539, 0.869455, 0.0000378034, 0, 0.119795, 0.854655, 0.0000399378, 0, 0.14656, 0.838347, 0.0000419108, 0, 0.175573, 0.820693, 0.0000440831, 0, 0.206388, 0.802277, 0.0000445599, 0, 0.238095, 0.783634, 0.0000472691, 0, 0.269841, 0.763159, 0.0000476984, 0, 0.301587, 0.742914, 0.0000491487, 0, 0.333333, 0.721662, 0.0000502312, 0, 0.365079, 0.699668, 0.0000502817, 0, 0.396825, 0.677839, 0.000051406, 0, 0.428571, 0.655091, 0.0000511095, 0, 0.460317, 0.632665, 0.0000516067, 0, 0.492064, 0.609734, 0.0000512255, 0, 0.52381, 0.587043, 0.0000510263, 0, 0.555556, 0.564298, 0.000050565, 0, 0.587302, 0.541769, 0.0000497951, 0, 0.619048, 0.519529, 0.0000492698, 0, 0.650794, 0.497574, 0.0000482066, 0, 0.68254, 0.476028, 0.0000473689, 0, 0.714286, 0.454961, 0.0000461941, 0, 0.746032, 0.434341, 0.0000450618, 0, 0.777778, 0.414364, 0.0000438355, 0, 0.809524, 0.394832, 0.0000424196, 0, 0.84127, 0.376109, 0.0000412563, 0, 0.873016, 0.35779, 0.0000396226, 0, 0.904762, 0.340379, 0.0000384886, 0, 0.936508, 0.323385, 0.0000368214, 0, 0.968254, 0.307295, 0.0000356636, 0, 1, 1, 0.00000000000106465, 0, 0, 1, 0.00000000000106555, 0, 0, 1, 0.00000000000107966, 0, 0, 1, 0.00000000000114601, 0, 0, 1, 0.00000000000137123, 0, 0, 1, 0.0000000000021243, 0, 0, 0.999999, 0.00000000000489653, 0, 0, 0.999999, 0.0000000000160283, 0, 0, 0.999998, 0.000000000062269, 0, 0, 0.999997, 0.000000000251859, 0, 0, 0.999996, 0.000000000996192, 0, 0, 0.999992, 0.00000000374531, 0, 0, 0.999986, 0.0000000132022, 0, 0, 0.999975, 0.0000000433315, 0, 0, 0.999959, 0.000000131956, 0, 0, 0.999927, 0.000000372249, 0, 0, 0.999871, 0.000000972461, 0, 0, 0.999771, 0.00000235343, 0, 0, 0.999572, 0.0000052768, 0, 0, 0.999133, 0.0000109237, 0, 0, 0.997912, 0.0000203675, 0, 0, 0.993008, 0.0000279396, 0, 0, 0.980645, 0.0000139604, 0, 0, 0.970057, 0.00000646596, 0, 0, 0.966717, 0.0000065089, 0, 0.0000474145, 0.965497, 0.0000111863, 0, 0.00089544, 0.96334, 0.0000179857, 0, 0.0032647, 0.959294, 0.0000259045, 0, 0.0075144, 0.951519, 0.0000292327, 0, 0.0138734, 0.940517, 0.0000249769, 0, 0.0224952, 0.93014, 0.000026803, 0, 0.0334828, 0.91972, 0.0000303656, 0, 0.0468973, 0.910294, 0.0000353323, 0, 0.0627703, 0.897701, 0.0000351002, 0, 0.0811019, 0.884522, 0.0000388104, 0, 0.10186, 0.869489, 0.0000412932, 0, 0.124985, 0.853983, 0.0000415781, 0, 0.150372, 0.838425, 0.0000454066, 0, 0.177868, 0.820656, 0.0000471624, 0, 0.207245, 0.801875, 0.0000475243, 0, 0.238143, 0.783521, 0.0000505621, 0, 0.269841, 0.763131, 0.000050721, 0, 0.301587, 0.74261, 0.0000523293, 0, 0.333333, 0.72148, 0.0000528699, 0, 0.365079, 0.699696, 0.0000538677, 0, 0.396825, 0.677592, 0.0000539255, 0, 0.428571, 0.65525, 0.0000546367, 0, 0.460317, 0.632452, 0.0000541348, 0, 0.492064, 0.609903, 0.0000544976, 0, 0.52381, 0.586928, 0.0000536201, 0, 0.555556, 0.564464, 0.0000535185, 0, 0.587302, 0.541801, 0.0000524949, 0, 0.619048, 0.519681, 0.000051812, 0, 0.650794, 0.497685, 0.0000507687, 0, 0.68254, 0.47622, 0.0000496243, 0, 0.714286, 0.455135, 0.0000485714, 0, 0.746032, 0.4346, 0.0000471847, 0, 0.777778, 0.414564, 0.0000459294, 0, 0.809524, 0.395165, 0.0000444705, 0, 0.84127, 0.376333, 0.0000430772, 0, 0.873016, 0.358197, 0.0000416229, 0, 0.904762, 0.34064, 0.0000401019, 0, 0.936508, 0.323816, 0.0000386623, 0, 0.968254, 0.307581, 0.0000370933, 0, 1, 1, 0.00000000000991541, 0, 0, 1, 0.00000000000992077, 0, 0, 1, 0.0000000000100041, 0, 0, 1, 0.000000000010385, 0, 0, 1, 0.0000000000115777, 0, 0, 1, 0.0000000000150215, 0, 0, 0.999999, 0.0000000000254738, 0, 0, 0.999999, 0.0000000000598822, 0, 0, 0.999998, 0.000000000179597, 0, 0, 0.999997, 0.000000000602367, 0, 0, 0.999994, 0.00000000206835, 0, 0, 0.99999, 0.00000000694952, 0, 0, 0.999984, 0.0000000223363, 0, 0, 0.999972, 0.0000000678578, 0, 0, 0.999952, 0.000000193571, 0, 0, 0.999919, 0.000000516594, 0, 0, 0.99986, 0.00000128739, 0, 0, 0.999753, 0.00000299298, 0, 0, 0.999546, 0.00000648258, 0, 0, 0.999074, 0.0000129985, 0, 0, 0.997671, 0.0000232176, 0, 0, 0.991504, 0.0000256701, 0, 0, 0.981148, 0.0000131141, 0, 0, 0.971965, 0.00000869048, 0, 0.0000280182, 0.966624, 0.00000808301, 0, 0.000695475, 0.965344, 0.0000135235, 0, 0.00265522, 0.963048, 0.0000210592, 0, 0.00622975, 0.958673, 0.0000287473, 0, 0.0116234, 0.950262, 0.0000281379, 0, 0.018976, 0.940836, 0.0000271089, 0, 0.0283844, 0.930996, 0.000030926, 0, 0.0399151, 0.919848, 0.0000348359, 0, 0.0536063, 0.909136, 0.0000366092, 0, 0.0694793, 0.897554, 0.0000384162, 0, 0.0875342, 0.884691, 0.0000430971, 0, 0.107749, 0.869414, 0.0000447803, 0, 0.130087, 0.853462, 0.0000452858, 0, 0.154481, 0.838187, 0.0000495769, 0, 0.180833, 0.820381, 0.0000502709, 0, 0.209005, 0.801844, 0.0000522713, 0, 0.238791, 0.783061, 0.0000541505, 0, 0.269869, 0.763205, 0.0000553712, 0, 0.301587, 0.742362, 0.0000564909, 0, 0.333333, 0.721393, 0.0000572646, 0, 0.365079, 0.699676, 0.0000581012, 0, 0.396825, 0.677395, 0.000058096, 0, 0.428571, 0.655208, 0.0000585766, 0, 0.460317, 0.632451, 0.0000583602, 0, 0.492064, 0.609839, 0.0000580234, 0, 0.52381, 0.587093, 0.0000577161, 0, 0.555556, 0.564467, 0.0000568447, 0, 0.587302, 0.542043, 0.0000563166, 0, 0.619048, 0.519826, 0.000055156, 0, 0.650794, 0.497952, 0.0000541682, 0, 0.68254, 0.476477, 0.0000528971, 0, 0.714286, 0.455412, 0.0000514952, 0, 0.746032, 0.434926, 0.0000502222, 0, 0.777778, 0.4149, 0.0000485779, 0, 0.809524, 0.395552, 0.0000472242, 0, 0.84127, 0.376712, 0.0000454891, 0, 0.873016, 0.358622, 0.0000440924, 0, 0.904762, 0.341048, 0.0000422984, 0, 0.936508, 0.324262, 0.0000408582, 0, 0.968254, 0.308013, 0.0000390839, 0, 1, 1, 0.0000000000613913, 0, 0, 1, 0.0000000000614145, 0, 0, 1, 0.0000000000617708, 0, 0, 1, 0.0000000000633717, 0, 0, 1, 0.0000000000681648, 0, 0, 1, 0.0000000000808291, 0, 0, 1, 0.000000000114608, 0, 0, 0.999998, 0.000000000210507, 0, 0, 0.999997, 0.000000000499595, 0, 0, 0.999995, 0.00000000139897, 0, 0, 0.999994, 0.00000000419818, 0, 0, 0.999988, 0.0000000127042, 0, 0, 0.999979, 0.0000000375153, 0, 0, 0.999965, 0.000000106206, 0, 0, 0.999945, 0.000000285381, 0, 0, 0.999908, 0.000000723611, 0, 0, 0.999846, 0.0000017255, 0, 0, 0.999733, 0.00000386104, 0, 0, 0.999511, 0.00000808493, 0, 0, 0.998993, 0.0000156884, 0, 0, 0.997326, 0.0000265538, 0, 0, 0.989706, 0.0000206466, 0, 0, 0.981713, 0.0000130756, 0, 0.0000070005, 0.973636, 0.0000106473, 0, 0.000464797, 0.966509, 0.000010194, 0, 0.00201743, 0.965149, 0.0000165881, 0, 0.00497549, 0.962669, 0.0000249147, 0, 0.00953262, 0.95786, 0.0000317449, 0, 0.0158211, 0.949334, 0.0000281045, 0, 0.0239343, 0.941041, 0.0000303263, 0, 0.0339372, 0.931575, 0.0000356754, 0, 0.0458738, 0.920102, 0.0000397075, 0, 0.059772, 0.908002, 0.0000384886, 0, 0.075645, 0.897269, 0.000043027, 0, 0.0934929, 0.884559, 0.0000479925, 0, 0.113302, 0.869161, 0.000048246, 0, 0.135045, 0.853342, 0.0000509505, 0, 0.158678, 0.837633, 0.0000542846, 0, 0.184136, 0.820252, 0.0000554139, 0, 0.211325, 0.801872, 0.0000581412, 0, 0.240113, 0.782418, 0.0000585535, 0, 0.270306, 0.7631, 0.0000610923, 0, 0.301594, 0.742183, 0.0000613678, 0, 0.333333, 0.721098, 0.0000627275, 0, 0.365079, 0.699512, 0.0000629413, 0, 0.396825, 0.677372, 0.0000636351, 0, 0.428571, 0.655059, 0.0000633555, 0, 0.460317, 0.632567, 0.0000636513, 0, 0.492064, 0.609784, 0.0000628965, 0, 0.52381, 0.587237, 0.0000625546, 0, 0.555556, 0.564525, 0.0000615825, 0, 0.587302, 0.542181, 0.0000605048, 0, 0.619048, 0.520017, 0.0000596329, 0, 0.650794, 0.498204, 0.0000581516, 0, 0.68254, 0.476742, 0.0000569186, 0, 0.714286, 0.455803, 0.0000553833, 0, 0.746032, 0.435251, 0.0000537807, 0, 0.777778, 0.415374, 0.0000522025, 0, 0.809524, 0.395921, 0.0000503421, 0, 0.84127, 0.377253, 0.0000488211, 0, 0.873016, 0.359021, 0.0000468234, 0, 0.904762, 0.341637, 0.0000453269, 0, 0.936508, 0.3247, 0.0000433014, 0, 0.968254, 0.308625, 0.0000418007, 0, 1, 1, 0.000000000286798, 0, 0, 1, 0.000000000286877, 0, 0, 1, 0.000000000288094, 0, 0, 1, 0.000000000293506, 0, 0, 1, 0.000000000309262, 0, 0, 0.999999, 0.000000000348593, 0, 0, 0.999999, 0.000000000444582, 0, 0, 0.999998, 0.000000000688591, 0, 0, 0.999996, 0.00000000134391, 0, 0, 0.999993, 0.00000000317438, 0, 0, 0.999989, 0.00000000835609, 0, 0, 0.999983, 0.0000000228677, 0, 0, 0.999974, 0.0000000623361, 0, 0, 0.999959, 0.000000165225, 0, 0, 0.999936, 0.000000419983, 0, 0, 0.999896, 0.00000101546, 0, 0, 0.99983, 0.00000232376, 0, 0, 0.999709, 0.0000050156, 0, 0, 0.999469, 0.000010167, 0, 0, 0.998886, 0.0000190775, 0, 0, 0.996819, 0.0000300511, 0, 0, 0.988837, 0.0000185092, 0, 0.000000168222, 0.982178, 0.0000134622, 0, 0.000259622, 0.975017, 0.0000125961, 0, 0.00142595, 0.967101, 0.000013507, 0, 0.00382273, 0.964905, 0.0000205003, 0, 0.00764164, 0.96218, 0.000029546, 0, 0.0130121, 0.956821, 0.0000343738, 0, 0.0200253, 0.948829, 0.0000305063, 0, 0.0287452, 0.941092, 0.0000346487, 0, 0.039218, 0.931883, 0.0000412061, 0, 0.0514748, 0.920211, 0.0000444651, 0, 0.0655351, 0.907307, 0.0000431252, 0, 0.0814082, 0.89684, 0.0000490382, 0, 0.0990939, 0.884119, 0.000053334, 0, 0.118583, 0.869148, 0.000054114, 0, 0.139856, 0.853377, 0.0000578536, 0, 0.162882, 0.836753, 0.0000592285, 0, 0.187615, 0.820063, 0.0000622787, 0, 0.213991, 0.801694, 0.0000645492, 0, 0.241918, 0.782116, 0.000065353, 0, 0.271267, 0.762673, 0.0000674344, 0, 0.301847, 0.742133, 0.0000682788, 0, 0.333333, 0.720779, 0.0000691959, 0, 0.365079, 0.699386, 0.0000696817, 0, 0.396826, 0.67732, 0.0000699583, 0, 0.428572, 0.654888, 0.0000698447, 0, 0.460318, 0.632499, 0.0000694063, 0, 0.492064, 0.609825, 0.0000691612, 0, 0.52381, 0.587287, 0.0000681576, 0, 0.555556, 0.564743, 0.0000674138, 0, 0.587302, 0.542409, 0.0000661617, 0, 0.619048, 0.520282, 0.0000647785, 0, 0.650794, 0.498506, 0.0000633836, 0, 0.68254, 0.477102, 0.0000615905, 0, 0.714286, 0.456167, 0.0000601013, 0, 0.746032, 0.435728, 0.0000581457, 0, 0.777778, 0.415809, 0.0000564215, 0, 0.809524, 0.396517, 0.0000544997, 0, 0.84127, 0.377737, 0.0000525061, 0, 0.873016, 0.359698, 0.0000506831, 0, 0.904762, 0.342164, 0.000048568, 0, 0.936508, 0.325417, 0.0000467826, 0, 0.968254, 0.309186, 0.0000446736, 0, 1, 1, 0.00000000109018, 0, 0, 1, 0.0000000010904, 0, 0, 1, 0.00000000109393, 0, 0, 1, 0.0000000011095, 0, 0, 1, 0.000000001154, 0, 0, 1, 0.00000000126089, 0, 0, 0.999999, 0.0000000015059, 0, 0, 0.999997, 0.00000000207899, 0, 0, 0.999994, 0.00000000348164, 0, 0, 0.999993, 0.00000000705728, 0, 0, 0.999987, 0.0000000163692, 0, 0, 0.999981, 0.0000000406033, 0, 0, 0.999969, 0.00000010245, 0, 0, 0.999953, 0.000000255023, 0, 0, 0.999925, 0.00000061511, 0, 0, 0.999881, 0.00000142218, 0, 0, 0.99981, 0.00000313086, 0, 0, 0.99968, 0.00000653119, 0, 0, 0.999418, 0.000012832, 0, 0, 0.998748, 0.0000232497, 0, 0, 0.996066, 0.0000329522, 0, 0, 0.988379, 0.0000179613, 0, 0.000108799, 0.982567, 0.0000143715, 0, 0.000921302, 0.976097, 0.0000148096, 0, 0.00280738, 0.968475, 0.0000178905, 0, 0.00596622, 0.964606, 0.0000253921, 0, 0.0105284, 0.961564, 0.0000348623, 0, 0.0165848, 0.955517, 0.0000357612, 0, 0.0242, 0.948381, 0.0000343493, 0, 0.03342, 0.941095, 0.0000405849, 0, 0.0442777, 0.931923, 0.0000475394, 0, 0.0567958, 0.91996, 0.0000484328, 0, 0.0709879, 0.907419, 0.0000502146, 0, 0.086861, 0.89618, 0.0000561654, 0, 0.104415, 0.88337, 0.0000587612, 0, 0.123643, 0.869046, 0.0000618057, 0, 0.144531, 0.853278, 0.0000657392, 0, 0.167057, 0.836091, 0.000066303, 0, 0.191188, 0.819644, 0.0000704445, 0, 0.216878, 0.801246, 0.0000714071, 0, 0.244062, 0.782031, 0.0000740093, 0, 0.272649, 0.762066, 0.000074685, 0, 0.302509, 0.741964, 0.0000766647, 0, 0.333442, 0.720554, 0.0000766328, 0, 0.365079, 0.699098, 0.0000777857, 0, 0.396826, 0.677189, 0.0000774633, 0, 0.428572, 0.65484, 0.0000776235, 0, 0.460318, 0.632496, 0.0000770316, 0, 0.492064, 0.609908, 0.0000762669, 0, 0.52381, 0.587312, 0.0000753972, 0, 0.555556, 0.564938, 0.0000739994, 0, 0.587302, 0.542577, 0.0000728382, 0, 0.619048, 0.52062, 0.000071112, 0, 0.650794, 0.498819, 0.0000694004, 0, 0.68254, 0.477555, 0.0000675575, 0, 0.714286, 0.456568, 0.0000653449, 0, 0.746032, 0.436278, 0.0000636068, 0, 0.777778, 0.41637, 0.0000613466, 0, 0.809524, 0.397144, 0.0000594177, 0, 0.84127, 0.378412, 0.0000570987, 0, 0.873016, 0.360376, 0.0000550419, 0, 0.904762, 0.342906, 0.0000527422, 0, 0.936508, 0.326136, 0.0000506544, 0, 0.968254, 0.30997, 0.0000484307, 0, 1, 1, 0.00000000354014, 0, 0, 1, 0.00000000354073, 0, 0, 1, 0.00000000354972, 0, 0, 1, 0.00000000358929, 0, 0, 1, 0.00000000370093, 0, 0, 0.999999, 0.00000000396194, 0, 0, 0.999998, 0.00000000453352, 0, 0, 0.999997, 0.00000000578828, 0, 0, 0.999994, 0.00000000863812, 0, 0, 0.999991, 0.0000000153622, 0, 0, 0.999985, 0.0000000316356, 0, 0, 0.999977, 0.0000000712781, 0, 0, 0.999964, 0.000000166725, 0, 0, 0.999945, 0.000000390501, 0, 0, 0.999912, 0.000000895622, 0, 0, 0.999866, 0.00000198428, 0, 0, 0.999786, 0.00000421038, 0, 0, 0.999647, 0.00000850239, 0, 0, 0.999356, 0.0000162059, 0, 0, 0.998563, 0.0000282652, 0, 0, 0.994928, 0.0000336309, 0, 0.0000244244, 0.987999, 0.0000178458, 0, 0.000523891, 0.982893, 0.0000159162, 0, 0.00194729, 0.977044, 0.0000178056, 0, 0.00451099, 0.969972, 0.0000230624, 0, 0.00835132, 0.964237, 0.0000313922, 0, 0.013561, 0.960791, 0.0000406145, 0, 0.0202056, 0.954292, 0.0000372796, 0, 0.0283321, 0.948052, 0.0000403199, 0, 0.0379739, 0.940938, 0.0000479537, 0, 0.0491551, 0.931689, 0.0000545292, 0, 0.0618918, 0.91987, 0.000054038, 0, 0.0761941, 0.907665, 0.0000589909, 0, 0.0920672, 0.895281, 0.0000642651, 0, 0.109511, 0.882621, 0.0000659707, 0, 0.12852, 0.86873, 0.0000709973, 0, 0.149085, 0.853008, 0.0000742221, 0, 0.171189, 0.835944, 0.0000761754, 0, 0.194809, 0.818949, 0.0000797052, 0, 0.21991, 0.800951, 0.0000812434, 0, 0.246447, 0.781847, 0.0000838075, 0, 0.274352, 0.761649, 0.000084501, 0, 0.303535, 0.74152, 0.0000860258, 0, 0.333857, 0.720495, 0.0000866233, 0, 0.365104, 0.698742, 0.0000868326, 0, 0.396826, 0.677096, 0.000087133, 0, 0.428572, 0.654782, 0.0000863497, 0, 0.460318, 0.632335, 0.0000860206, 0, 0.492064, 0.610031, 0.0000849337, 0, 0.52381, 0.587457, 0.0000838279, 0, 0.555556, 0.56513, 0.000082309, 0, 0.587302, 0.542877, 0.0000803542, 0, 0.619048, 0.5209, 0.0000786928, 0, 0.650794, 0.499291, 0.0000765171, 0, 0.68254, 0.477971, 0.0000744753, 0, 0.714286, 0.457221, 0.000072209, 0, 0.746032, 0.436803, 0.0000697448, 0, 0.777778, 0.417083, 0.0000675333, 0, 0.809524, 0.397749, 0.0000648058, 0, 0.84127, 0.379177, 0.0000625759, 0, 0.873016, 0.361061, 0.0000598584, 0, 0.904762, 0.343713, 0.0000575797, 0, 0.936508, 0.326894, 0.0000549999, 0, 0.968254, 0.310816, 0.0000527482, 0, 1, 1, 0.000000010153, 0, 0, 1, 0.0000000101544, 0, 0, 1, 0.0000000101751, 0, 0, 1, 0.0000000102662, 0, 0, 1, 0.000000010521, 0, 0, 0.999999, 0.0000000111049, 0, 0, 0.999999, 0.0000000123408, 0, 0, 0.999996, 0.000000014924, 0, 0, 0.999992, 0.0000000204471, 0, 0, 0.999989, 0.0000000326539, 0, 0, 0.99998, 0.0000000603559, 0, 0, 0.999971, 0.000000123936, 0, 0, 0.999955, 0.000000269058, 0, 0, 0.999933, 0.000000593604, 0, 0, 0.999901, 0.00000129633, 0, 0, 0.999847, 0.00000275621, 0, 0, 0.999761, 0.00000564494, 0, 0, 0.999607, 0.0000110485, 0, 0, 0.999282, 0.0000204388, 0, 0, 0.99831, 0.0000341084, 0, 0.00000022038, 0.993288, 0.0000294949, 0, 0.000242388, 0.987855, 0.0000192736, 0, 0.0012503, 0.983167, 0.0000182383, 0, 0.0032745, 0.977908, 0.0000218633, 0, 0.00646321, 0.971194, 0.0000290662, 0, 0.0109133, 0.963867, 0.0000386401, 0, 0.0166927, 0.95982, 0.0000462827, 0, 0.0238494, 0.953497, 0.0000420705, 0, 0.0324178, 0.947621, 0.0000477743, 0, 0.0424225, 0.940611, 0.0000568258, 0, 0.0538808, 0.931174, 0.0000618061, 0, 0.0668047, 0.919919, 0.0000627098, 0, 0.0812014, 0.907856, 0.0000694714, 0, 0.0970745, 0.894509, 0.0000735008, 0, 0.114424, 0.881954, 0.0000763369, 0, 0.133246, 0.868309, 0.0000821896, 0, 0.153534, 0.852511, 0.000083769, 0, 0.175275, 0.835821, 0.0000881615, 0, 0.198453, 0.817981, 0.0000896368, 0, 0.223042, 0.800504, 0.0000930906, 0, 0.249009, 0.78141, 0.0000945056, 0, 0.276304, 0.761427, 0.0000963605, 0, 0.304862, 0.74094, 0.0000968088, 0, 0.334584, 0.720233, 0.0000981481, 0, 0.365322, 0.698592, 0.0000979122, 0, 0.396826, 0.676763, 0.0000981057, 0, 0.428571, 0.654808, 0.0000973956, 0, 0.460318, 0.632326, 0.0000962619, 0, 0.492064, 0.610049, 0.0000952996, 0, 0.52381, 0.58763, 0.0000933334, 0, 0.555556, 0.565261, 0.0000917573, 0, 0.587302, 0.543244, 0.0000896636, 0, 0.619048, 0.521273, 0.0000873304, 0, 0.650794, 0.499818, 0.0000852648, 0, 0.68254, 0.478536, 0.0000823961, 0, 0.714286, 0.457826, 0.000079939, 0, 0.746032, 0.437549, 0.000077126, 0, 0.777778, 0.41776, 0.0000743043, 0, 0.809524, 0.39863, 0.0000716426, 0, 0.84127, 0.379954, 0.0000686456, 0, 0.873016, 0.362025, 0.0000660514, 0, 0.904762, 0.344581, 0.0000630755, 0, 0.936508, 0.327909, 0.0000605439, 0, 0.968254, 0.311736, 0.0000576345, 0, 1, 1, 0.0000000263344, 0, 0, 1, 0.0000000263373, 0, 0, 1, 0.0000000263815, 0, 0, 1, 0.0000000265753, 0, 0, 1, 0.0000000271132, 0, 0, 0.999999, 0.0000000283279, 0, 0, 0.999997, 0.000000030833, 0, 0, 0.999995, 0.0000000358711, 0, 0, 0.999992, 0.0000000461266, 0, 0, 0.999985, 0.000000067574, 0, 0, 0.999977, 0.00000011358, 0, 0, 0.999966, 0.000000213657, 0, 0, 0.999948, 0.000000431151, 0, 0, 0.999923, 0.000000896656, 0, 0, 0.999884, 0.00000186603, 0, 0, 0.999826, 0.00000381115, 0, 0, 0.999732, 0.00000754184, 0, 0, 0.999561, 0.0000143192, 0, 0, 0.999191, 0.0000257061, 0, 0, 0.997955, 0.0000405724, 0, 0.0000744132, 0.992228, 0.0000276537, 0, 0.000716477, 0.987638, 0.0000208885, 0, 0.0022524, 0.983395, 0.0000215226, 0, 0.00484816, 0.978614, 0.0000270795, 0, 0.00860962, 0.972389, 0.0000365282, 0, 0.0136083, 0.964392, 0.0000474747, 0, 0.0198941, 0.95861, 0.0000509141, 0, 0.0275023, 0.952806, 0.000048963, 0, 0.0364584, 0.94712, 0.0000571119, 0, 0.04678, 0.940104, 0.0000671704, 0, 0.0584799, 0.930398, 0.0000687586, 0, 0.0715665, 0.919866, 0.0000738161, 0, 0.086045, 0.907853, 0.0000813235, 0, 0.101918, 0.894078, 0.0000834582, 0, 0.119186, 0.881177, 0.0000892093, 0, 0.137845, 0.867575, 0.0000944548, 0, 0.157891, 0.852107, 0.0000969607, 0, 0.179316, 0.835502, 0.000101456, 0, 0.202106, 0.81756, 0.000103256, 0, 0.226243, 0.79984, 0.000106954, 0, 0.251704, 0.780998, 0.000108066, 0, 0.278451, 0.761132, 0.000110111, 0, 0.306436, 0.740429, 0.000110459, 0, 0.335586, 0.719836, 0.000111219, 0, 0.365796, 0.698467, 0.00011145, 0, 0.3969, 0.676446, 0.000110393, 0, 0.428571, 0.654635, 0.000110035, 0, 0.460318, 0.632411, 0.000108548, 0, 0.492064, 0.609986, 0.000106963, 0, 0.52381, 0.587872, 0.000105238, 0, 0.555556, 0.565528, 0.000102665, 0, 0.587302, 0.543563, 0.000100543, 0, 0.619048, 0.52176, 0.0000976182, 0, 0.650794, 0.500188, 0.0000947099, 0, 0.68254, 0.479204, 0.0000919929, 0, 0.714286, 0.458413, 0.0000886139, 0, 0.746032, 0.438314, 0.0000857839, 0, 0.777778, 0.418573, 0.000082411, 0, 0.809524, 0.39947, 0.0000792211, 0, 0.84127, 0.380892, 0.0000759546, 0, 0.873016, 0.362953, 0.0000727571, 0, 0.904762, 0.345601, 0.0000695738, 0, 0.936508, 0.328895, 0.0000664907, 0, 0.968254, 0.312808, 0.0000634277, 0, 1, 1, 0.0000000628647, 0, 0, 1, 0.0000000628705, 0, 0, 1, 0.0000000629587, 0, 0, 1, 0.0000000633441, 0, 0, 0.999999, 0.0000000644087, 0, 0, 0.999998, 0.0000000667856, 0, 0, 0.999997, 0.0000000715889, 0, 0, 0.999995, 0.0000000809577, 0, 0, 0.999989, 0.0000000992764, 0, 0, 0.999983, 0.000000135834, 0, 0, 0.999974, 0.000000210482, 0, 0, 0.999959, 0.000000365215, 0, 0, 0.999939, 0.000000686693, 0, 0, 0.999911, 0.0000013472, 0, 0, 0.999868, 0.0000026731, 0, 0, 0.999804, 0.00000524756, 0, 0, 0.9997, 0.0000100403, 0, 0, 0.99951, 0.0000185019, 0, 0, 0.999078, 0.0000322036, 0, 0.00000620676, 0.997428, 0.0000470002, 0, 0.000341552, 0.99162, 0.0000287123, 0, 0.00143727, 0.987479, 0.0000234706, 0, 0.00349201, 0.983582, 0.0000260083, 0, 0.0066242, 0.979186, 0.0000337927, 0, 0.0109113, 0.97325, 0.0000454689, 0, 0.0164064, 0.965221, 0.0000573759, 0, 0.0231463, 0.957262, 0.0000544114, 0, 0.0311571, 0.952211, 0.0000587006, 0, 0.0404572, 0.946631, 0.0000692256, 0, 0.0510592, 0.939391, 0.0000787819, 0, 0.0629723, 0.929795, 0.0000792368, 0, 0.0762025, 0.91965, 0.0000875075, 0, 0.090753, 0.907737, 0.0000950903, 0, 0.106626, 0.893899, 0.0000972963, 0, 0.123822, 0.880239, 0.00010459, 0, 0.142337, 0.866562, 0.000107689, 0, 0.16217, 0.85164, 0.000113081, 0, 0.183314, 0.835021, 0.000116636, 0, 0.20576, 0.817311, 0.000120074, 0, 0.229496, 0.798845, 0.000121921, 0, 0.254502, 0.780479, 0.00012475, 0, 0.280753, 0.760694, 0.000125255, 0, 0.308212, 0.740142, 0.000126719, 0, 0.336825, 0.719248, 0.00012636, 0, 0.366517, 0.698209, 0.000126712, 0, 0.397167, 0.676398, 0.000125769, 0, 0.428578, 0.654378, 0.000124432, 0, 0.460318, 0.632484, 0.000123272, 0, 0.492064, 0.610113, 0.00012085, 0, 0.52381, 0.587931, 0.000118411, 0, 0.555556, 0.565872, 0.00011569, 0, 0.587302, 0.543814, 0.000112521, 0, 0.619048, 0.522265, 0.000109737, 0, 0.650794, 0.500835, 0.000106228, 0, 0.68254, 0.479818, 0.000102591, 0, 0.714286, 0.459258, 0.0000991288, 0, 0.746032, 0.439061, 0.0000952325, 0, 0.777778, 0.419552, 0.000091895, 0, 0.809524, 0.400399, 0.0000879051, 0, 0.84127, 0.381976, 0.0000844775, 0, 0.873016, 0.364009, 0.0000806316, 0, 0.904762, 0.346761, 0.0000771848, 0, 0.936508, 0.330049, 0.0000735429, 0, 0.968254, 0.314018, 0.0000702103, 0, 1, 1, 0.000000139968, 0, 0, 1, 0.000000139979, 0, 0, 1, 0.000000140145, 0, 0, 1, 0.00000014087, 0, 0, 0.999999, 0.000000142865, 0, 0, 0.999998, 0.000000147279, 0, 0, 0.999997, 0.000000156057, 0, 0, 0.999992, 0.00000017276, 0, 0, 0.999989, 0.000000204352, 0, 0, 0.99998, 0.00000026494, 0, 0, 0.999969, 0.000000383435, 0, 0, 0.999953, 0.000000618641, 0, 0, 0.999929, 0.00000108755, 0, 0, 0.999898, 0.00000201497, 0, 0, 0.999849, 0.00000381346, 0, 0, 0.999778, 0.00000719815, 0, 0, 0.999661, 0.0000133215, 0, 0, 0.999451, 0.0000238313, 0, 0, 0.998936, 0.0000401343, 0, 0.000113724, 0.99662, 0.0000517346, 0, 0.000820171, 0.991094, 0.0000304323, 0, 0.00238143, 0.987487, 0.0000281757, 0, 0.00493527, 0.983731, 0.0000320048, 0, 0.00856859, 0.979647, 0.0000423905, 0, 0.0133393, 0.973837, 0.0000562935, 0, 0.0192863, 0.96584, 0.0000677442, 0, 0.0264369, 0.956309, 0.0000623073, 0, 0.03481, 0.951523, 0.0000704131, 0, 0.0444184, 0.946003, 0.0000836594, 0, 0.0552713, 0.938454, 0.0000911736, 0, 0.0673749, 0.929279, 0.0000938264, 0, 0.0807329, 0.919239, 0.000103754, 0, 0.0953479, 0.907293, 0.000109928, 0, 0.111221, 0.893936, 0.000115257, 0, 0.128352, 0.879674, 0.000122265, 0, 0.14674, 0.865668, 0.000125733, 0, 0.166382, 0.850998, 0.000132305, 0, 0.187276, 0.834498, 0.000134844, 0, 0.209413, 0.816903, 0.000139276, 0, 0.232786, 0.798235, 0.000140984, 0, 0.257382, 0.779724, 0.00014378, 0, 0.283181, 0.760251, 0.000144623, 0, 0.310156, 0.739808, 0.000145228, 0, 0.338269, 0.718762, 0.00014539, 0, 0.367461, 0.697815, 0.000144432, 0, 0.397646, 0.67631, 0.000143893, 0, 0.428685, 0.654278, 0.000141846, 0, 0.460318, 0.632347, 0.00013935, 0, 0.492064, 0.610296, 0.000137138, 0, 0.52381, 0.588039, 0.000133806, 0, 0.555556, 0.566218, 0.000130755, 0, 0.587302, 0.544346, 0.000127128, 0, 0.619048, 0.522701, 0.000123002, 0, 0.650794, 0.501542, 0.000119443, 0, 0.68254, 0.480508, 0.000115055, 0, 0.714286, 0.460092, 0.000111032, 0, 0.746032, 0.440021, 0.000106635, 0, 0.777778, 0.420446, 0.000102162, 0, 0.809524, 0.401512, 0.000098184, 0, 0.84127, 0.38299, 0.0000936497, 0, 0.873016, 0.365232, 0.000089813, 0, 0.904762, 0.347865, 0.0000853073, 0, 0.936508, 0.331342, 0.0000817068, 0, 0.968254, 0.315202, 0.0000773818, 0, 1, 1, 0.00000029368, 0, 0, 1, 0.0000002937, 0, 0, 1, 0.000000293998, 0, 0, 1, 0.000000295298, 0, 0, 0.999999, 0.000000298865, 0, 0, 0.999998, 0.0000003067, 0, 0, 0.999995, 0.000000322082, 0, 0, 0.999992, 0.000000350767, 0, 0, 0.999986, 0.000000403538, 0, 0, 0.999976, 0.000000501372, 0, 0, 0.999964, 0.00000068562, 0, 0, 0.999945, 0.0000010374, 0, 0, 0.999919, 0.00000171269, 0, 0, 0.999882, 0.00000300175, 0, 0, 0.999829, 0.00000542144, 0, 0, 0.999749, 0.00000984182, 0, 0, 0.99962, 0.0000176213, 0, 0, 0.999382, 0.0000305995, 0, 0.0000138418, 0.998751, 0.0000496686, 0, 0.000389844, 0.995344, 0.0000510733, 0, 0.00150343, 0.990768, 0.0000345829, 0, 0.00352451, 0.987464, 0.0000342841, 0, 0.00655379, 0.983846, 0.0000399072, 0, 0.0106554, 0.980007, 0.0000533219, 0, 0.0158723, 0.974494, 0.0000696992, 0, 0.0222333, 0.96622, 0.0000776754, 0, 0.029758, 0.956273, 0.0000747718, 0, 0.0384596, 0.950952, 0.0000864611, 0, 0.0483473, 0.945215, 0.000100464, 0, 0.0594266, 0.937287, 0.000103729, 0, 0.0717019, 0.928649, 0.000111665, 0, 0.0851752, 0.918791, 0.00012353, 0, 0.0998479, 0.906685, 0.000127115, 0, 0.115721, 0.893706, 0.00013628, 0, 0.132794, 0.879248, 0.000142427, 0, 0.151067, 0.864685, 0.000148091, 0, 0.170538, 0.850032, 0.000153517, 0, 0.191204, 0.833853, 0.000157322, 0, 0.213063, 0.816353, 0.000161086, 0, 0.236107, 0.797834, 0.000164111, 0, 0.260329, 0.778831, 0.000165446, 0, 0.285714, 0.759756, 0.000167492, 0, 0.312243, 0.739419, 0.000166928, 0, 0.339887, 0.718491, 0.000167, 0, 0.368604, 0.697392, 0.000165674, 0, 0.398329, 0.676102, 0.000163815, 0, 0.428961, 0.654243, 0.000162003, 0, 0.460331, 0.632176, 0.000158831, 0, 0.492064, 0.610407, 0.000155463, 0, 0.52381, 0.588394, 0.000152062, 0, 0.555556, 0.56645, 0.000147665, 0, 0.587302, 0.5449, 0.00014375, 0, 0.619048, 0.523276, 0.000138905, 0, 0.650794, 0.502179, 0.000134189, 0, 0.68254, 0.481359, 0.000129392, 0, 0.714286, 0.46092, 0.000124556, 0, 0.746032, 0.441084, 0.00011957, 0, 0.777778, 0.421517, 0.000114652, 0, 0.809524, 0.402721, 0.000109688, 0, 0.84127, 0.384222, 0.000104667, 0, 0.873016, 0.366534, 0.0000999633, 0, 0.904762, 0.349205, 0.0000950177, 0, 0.936508, 0.332702, 0.0000907301, 0, 0.968254, 0.316599, 0.0000859769, 0, 1, 1, 0.000000585473, 0, 0, 1, 0.000000585507, 0, 0, 1, 0.00000058602, 0, 0, 0.999999, 0.000000588259, 0, 0, 0.999999, 0.000000594381, 0, 0, 0.999998, 0.000000607754, 0, 0, 0.999995, 0.000000633729, 0, 0, 0.99999, 0.00000068137, 0, 0, 0.999984, 0.000000767003, 0, 0, 0.999973, 0.000000921212, 0, 0, 0.999959, 0.00000120218, 0, 0, 0.999936, 0.00000172024, 0, 0, 0.999907, 0.00000268088, 0, 0, 0.999866, 0.00000445512, 0, 0, 0.999806, 0.00000768481, 0, 0, 0.999716, 0.00001342, 0, 0, 0.999576, 0.0000232473, 0, 0, 0.9993, 0.0000391694, 0, 0.000129917, 0.998498, 0.0000608429, 0, 0.000845035, 0.994132, 0.0000489743, 0, 0.00237616, 0.99031, 0.0000384644, 0, 0.00484456, 0.987409, 0.0000421768, 0, 0.00832472, 0.983981, 0.0000504854, 0, 0.0128643, 0.980268, 0.0000671028, 0, 0.0184947, 0.974875, 0.0000852749, 0, 0.025237, 0.966063, 0.000085531, 0, 0.0331046, 0.956779, 0.0000900588, 0, 0.0421067, 0.950259, 0.00010577, 0, 0.0522487, 0.944239, 0.000119458, 0, 0.0635343, 0.936341, 0.000122164, 0, 0.0759654, 0.928047, 0.000134929, 0, 0.0895434, 0.918065, 0.000145544, 0, 0.104269, 0.906267, 0.000150531, 0, 0.120142, 0.893419, 0.000161652, 0, 0.137163, 0.878758, 0.00016593, 0, 0.15533, 0.863699, 0.000174014, 0, 0.174645, 0.848876, 0.000177877, 0, 0.195106, 0.833032, 0.000184049, 0, 0.21671, 0.815557, 0.000186088, 0, 0.239454, 0.797323, 0.00019054, 0, 0.263332, 0.778124, 0.000191765, 0, 0.288336, 0.758929, 0.000192535, 0, 0.314451, 0.738979, 0.000192688, 0, 0.341658, 0.718213, 0.000191522, 0, 0.369924, 0.696947, 0.000190491, 0, 0.399202, 0.675807, 0.000187913, 0, 0.429416, 0.654147, 0.000184451, 0, 0.460447, 0.63229, 0.000181442, 0, 0.492064, 0.610499, 0.000177139, 0, 0.523809, 0.588747, 0.000172596, 0, 0.555555, 0.566783, 0.000167457, 0, 0.587301, 0.545359, 0.000162518, 0, 0.619048, 0.523984, 0.000156818, 0, 0.650794, 0.502917, 0.000151884, 0, 0.68254, 0.482294, 0.000145514, 0, 0.714286, 0.461945, 0.000140199, 0, 0.746032, 0.442133, 0.000134101, 0, 0.777778, 0.422705, 0.000128374, 0, 0.809524, 0.403916, 0.000122996, 0, 0.84127, 0.38554, 0.000116808, 0, 0.873016, 0.367909, 0.000111973, 0, 0.904762, 0.350651, 0.000105938, 0, 0.936508, 0.334208, 0.000101355, 0, 0.968254, 0.318123, 0.0000957629, 0, 1, 1, 0.00000111633, 0, 0, 1, 0.00000111639, 0, 0, 1, 0.00000111725, 0, 0, 1, 0.00000112096, 0, 0, 0.999999, 0.0000011311, 0, 0, 0.999997, 0.00000115315, 0, 0, 0.999995, 0.0000011956, 0, 0, 0.999989, 0.00000127239, 0, 0, 0.999981, 0.00000140772, 0, 0, 0.999969, 0.00000164541, 0, 0, 0.999952, 0.00000206607, 0, 0, 0.999928, 0.00000281783, 0, 0, 0.999895, 0.00000416835, 0, 0, 0.999848, 0.00000658728, 0, 0, 0.999781, 0.0000108648, 0, 0, 0.999682, 0.0000182579, 0, 0, 0.999523, 0.0000306003, 0, 0.0000159122, 0.999205, 0.0000499862, 0, 0.000391184, 0.998131, 0.000073306, 0, 0.00147534, 0.993334, 0.0000513229, 0, 0.0034227, 0.99016, 0.0000467783, 0, 0.00632232, 0.987321, 0.0000523413, 0, 0.0102295, 0.984099, 0.000064267, 0, 0.0151794, 0.980432, 0.0000843042, 0, 0.0211947, 0.974976, 0.000102819, 0, 0.0282899, 0.966429, 0.0000996234, 0, 0.0364739, 0.957633, 0.000111074, 0, 0.0457522, 0.949422, 0.000128644, 0, 0.0561278, 0.943045, 0.000140076, 0, 0.0676023, 0.935448, 0.000146349, 0, 0.0801762, 0.927225, 0.000161854, 0, 0.0938499, 0.917033, 0.000169135, 0, 0.108623, 0.905762, 0.000179987, 0, 0.124496, 0.892879, 0.000189832, 0, 0.141469, 0.878435, 0.000195881, 0, 0.159541, 0.863114, 0.00020466, 0, 0.178713, 0.84776, 0.000209473, 0, 0.198985, 0.832084, 0.000214861, 0, 0.220355, 0.814915, 0.000217695, 0, 0.242823, 0.796711, 0.000220313, 0, 0.266385, 0.777603, 0.00022313, 0, 0.291036, 0.757991, 0.000222471, 0, 0.316767, 0.738371, 0.000222869, 0, 0.343563, 0.717872, 0.000221243, 0, 0.371402, 0.696619, 0.000218089, 0, 0.400248, 0.675379, 0.00021562, 0, 0.430047, 0.65411, 0.00021169, 0, 0.460709, 0.63241, 0.000206947, 0, 0.492079, 0.61046, 0.000201709, 0, 0.52381, 0.58903, 0.000196753, 0, 0.555556, 0.567267, 0.000189637, 0, 0.587302, 0.545886, 0.000184735, 0, 0.619048, 0.524714, 0.000177257, 0, 0.650794, 0.503789, 0.000171424, 0, 0.68254, 0.483204, 0.000164688, 0, 0.714286, 0.462976, 0.000157172, 0, 0.746032, 0.443294, 0.000151341, 0, 0.777778, 0.423988, 0.000143737, 0, 0.809524, 0.405325, 0.000138098, 0, 0.84127, 0.386981, 0.000130698, 0, 0.873016, 0.369436, 0.000125276, 0, 0.904762, 0.35219, 0.000118349, 0, 0.936508, 0.335804, 0.00011312, 0, 0.968254, 0.319749, 0.000106687, 0, 1, 1, 0.00000204685, 0, 0, 1, 0.00000204694, 0, 0, 1, 0.00000204831, 0, 0, 0.999999, 0.00000205428, 0, 0, 0.999999, 0.00000207056, 0, 0, 0.999997, 0.00000210581, 0, 0, 0.999993, 0.0000021732, 0, 0, 0.999987, 0.00000229365, 0, 0, 0.999979, 0.00000250243, 0, 0, 0.999965, 0.00000286127, 0, 0, 0.999947, 0.00000348028, 0, 0, 0.999918, 0.00000455588, 0, 0, 0.999881, 0.00000643303, 0, 0, 0.999828, 0.00000970064, 0, 0, 0.999753, 0.0000153233, 0, 0, 0.999642, 0.000024793, 0, 0, 0.999464, 0.0000402032, 0, 0.000122947, 0.999089, 0.0000635852, 0, 0.000807414, 0.997567, 0.0000857026, 0, 0.00227206, 0.992903, 0.0000594912, 0, 0.00462812, 0.990011, 0.0000578515, 0, 0.00794162, 0.987192, 0.000065399, 0, 0.0122534, 0.98418, 0.0000819675, 0, 0.0175888, 0.980491, 0.000105514, 0, 0.0239635, 0.974779, 0.000121532, 0, 0.031387, 0.96675, 0.000119144, 0, 0.0398644, 0.958248, 0.000136125, 0, 0.0493982, 0.948884, 0.000155408, 0, 0.0599896, 0.941673, 0.000162281, 0, 0.0716382, 0.934521, 0.000176754, 0, 0.0843437, 0.926205, 0.000192873, 0, 0.0981056, 0.916089, 0.000200038, 0, 0.112923, 0.904963, 0.000213624, 0, 0.128796, 0.892089, 0.000221834, 0, 0.145725, 0.878028, 0.000232619, 0, 0.163709, 0.86249, 0.000238632, 0, 0.182749, 0.846587, 0.000247002, 0, 0.202847, 0.830988, 0.000250702, 0, 0.224001, 0.814165, 0.000255562, 0, 0.246214, 0.796135, 0.000257505, 0, 0.269482, 0.777052, 0.000258625, 0, 0.293805, 0.757201, 0.000258398, 0, 0.319176, 0.737655, 0.000256714, 0, 0.345587, 0.717477, 0.000255187, 0, 0.373021, 0.696433, 0.000251792, 0, 0.401454, 0.675084, 0.000247223, 0, 0.430844, 0.653907, 0.000242213, 0, 0.461125, 0.632561, 0.000237397, 0, 0.492187, 0.610658, 0.000229313, 0, 0.52381, 0.589322, 0.000224402, 0, 0.555556, 0.567857, 0.000216116, 0, 0.587302, 0.54652, 0.000209124, 0, 0.619048, 0.525433, 0.000201601, 0, 0.650794, 0.504679, 0.000192957, 0, 0.68254, 0.484203, 0.000186052, 0, 0.714286, 0.464203, 0.000177672, 0, 0.746032, 0.444549, 0.000170005, 0, 0.777778, 0.425346, 0.000162401, 0, 0.809524, 0.406706, 0.0001544, 0, 0.84127, 0.388576, 0.000147437, 0, 0.873016, 0.37094, 0.000139493, 0, 0.904762, 0.353996, 0.000133219, 0, 0.936508, 0.337391, 0.000125573, 0, 0.968254, 0.321648, 0.000119867, 0, 1, 1, 0.00000362511, 0, 0, 1, 0.00000362525, 0, 0, 1, 0.00000362739, 0, 0, 0.999999, 0.00000363673, 0, 0, 0.999998, 0.00000366214, 0, 0, 0.999996, 0.00000371698, 0, 0, 0.999992, 0.00000382116, 0, 0, 0.999986, 0.00000400554, 0, 0, 0.999976, 0.00000432058, 0, 0, 0.999961, 0.00000485194, 0, 0, 0.999938, 0.00000574808, 0, 0, 0.999908, 0.00000726643, 0, 0, 0.999865, 0.00000984707, 0, 0, 0.999807, 0.0000142217, 0, 0, 0.999723, 0.0000215581, 0, 0, 0.999602, 0.0000336114, 0, 0.0000119113, 0.999398, 0.0000527353, 0, 0.000355813, 0.998946, 0.0000805809, 0, 0.00137768, 0.996647, 0.0000942908, 0, 0.00322469, 0.992298, 0.0000668733, 0, 0.00597897, 0.989802, 0.0000716564, 0, 0.00968903, 0.987019, 0.0000821355, 0, 0.0143845, 0.984219, 0.000104555, 0, 0.0200831, 0.980425, 0.000131245, 0, 0.0267948, 0.974241, 0.000139613, 0, 0.034525, 0.967006, 0.000145931, 0, 0.0432757, 0.95893, 0.000167153, 0, 0.0530471, 0.949157, 0.000188146, 0, 0.0638386, 0.94062, 0.000194625, 0, 0.0756487, 0.933509, 0.000213721, 0, 0.0884762, 0.925088, 0.000229616, 0, 0.10232, 0.915178, 0.000239638, 0, 0.117178, 0.904093, 0.000254814, 0, 0.133051, 0.891337, 0.000263685, 0, 0.149939, 0.877326, 0.000274789, 0, 0.167841, 0.861794, 0.000280534, 0, 0.18676, 0.845758, 0.000289534, 0, 0.206696, 0.829792, 0.000294446, 0, 0.22765, 0.813037, 0.000296877, 0, 0.249625, 0.795285, 0.000300217, 0, 0.27262, 0.776323, 0.000299826, 0, 0.296636, 0.756673, 0.000299787, 0, 0.321671, 0.736856, 0.000297867, 0, 0.347718, 0.716883, 0.000294052, 0, 0.374768, 0.696089, 0.000289462, 0, 0.402804, 0.67505, 0.000285212, 0, 0.431796, 0.653509, 0.00027653, 0, 0.461695, 0.63258, 0.000271759, 0, 0.49242, 0.61104, 0.000262811, 0, 0.523822, 0.589567, 0.000255151, 0, 0.555556, 0.568322, 0.000246434, 0, 0.587302, 0.547235, 0.000237061, 0, 0.619048, 0.52616, 0.000228343, 0, 0.650794, 0.505716, 0.000219236, 0, 0.68254, 0.485274, 0.000209595, 0, 0.714286, 0.465411, 0.000201011, 0, 0.746032, 0.445854, 0.00019109, 0, 0.777778, 0.426911, 0.000182897, 0, 0.809524, 0.408222, 0.000173569, 0, 0.84127, 0.390307, 0.000165496, 0, 0.873016, 0.372624, 0.000156799, 0, 0.904762, 0.355804, 0.00014917, 0, 0.936508, 0.33924, 0.000140907, 0, 0.968254, 0.323534, 0.000134062, 0, 1, 1, 0.00000622487, 0, 0, 1, 0.0000062251, 0, 0, 1, 0.00000622837, 0, 0, 0.999999, 0.00000624259, 0, 0, 0.999998, 0.00000628127, 0, 0, 0.999996, 0.00000636451, 0, 0, 0.999991, 0.0000065218, 0, 0, 0.999984, 0.00000679782, 0, 0, 0.999973, 0.00000726361, 0, 0, 0.999955, 0.00000803644, 0, 0, 0.999931, 0.00000931397, 0, 0, 0.999896, 0.0000114299, 0, 0, 0.999847, 0.0000149402, 0, 0, 0.999784, 0.0000207461, 0, 0, 0.999692, 0.0000302493, 0, 0, 0.999554, 0.0000454957, 0, 0.0000997275, 0.999326, 0.0000690762, 0, 0.000724813, 0.998757, 0.000101605, 0, 0.0020972, 0.995367, 0.0000958745, 0, 0.00432324, 0.99209, 0.0000832808, 0, 0.00746347, 0.989517, 0.0000887601, 0, 0.0115534, 0.987008, 0.00010564, 0, 0.0166134, 0.98421, 0.000133179, 0, 0.0226552, 0.98021, 0.000161746, 0, 0.0296838, 0.973676, 0.000161821, 0, 0.0377016, 0.967052, 0.000178635, 0, 0.0467079, 0.959385, 0.000206765, 0, 0.0567013, 0.949461, 0.00022476, 0, 0.0676796, 0.939578, 0.00023574, 0, 0.0796403, 0.932416, 0.00025893, 0, 0.0925812, 0.923759, 0.000271228, 0, 0.106501, 0.914223, 0.000289165, 0, 0.121397, 0.902942, 0.000301156, 0, 0.13727, 0.890419, 0.000313852, 0, 0.15412, 0.876639, 0.000324408, 0, 0.171946, 0.861316, 0.00033249, 0, 0.190751, 0.84496, 0.000338497, 0, 0.210537, 0.828427, 0.000345861, 0, 0.231305, 0.811871, 0.000347863, 0, 0.253057, 0.794397, 0.000350225, 0, 0.275797, 0.775726, 0.000349915, 0, 0.299525, 0.75617, 0.000347297, 0, 0.324242, 0.736091, 0.000344232, 0, 0.349947, 0.716213, 0.000340835, 0, 0.376633, 0.695736, 0.000332369, 0, 0.404289, 0.674961, 0.000327943, 0, 0.432895, 0.653518, 0.000318533, 0, 0.462415, 0.632574, 0.000310391, 0, 0.492788, 0.61134, 0.000300755, 0, 0.523909, 0.590017, 0.000290506, 0, 0.555556, 0.568752, 0.000280446, 0, 0.587302, 0.548061, 0.000269902, 0, 0.619048, 0.52711, 0.000258815, 0, 0.650794, 0.506682, 0.000248481, 0, 0.68254, 0.486524, 0.000237141, 0, 0.714286, 0.466812, 0.000226872, 0, 0.746032, 0.44732, 0.000216037, 0, 0.777778, 0.428473, 0.000205629, 0, 0.809524, 0.409921, 0.000195691, 0, 0.84127, 0.392028, 0.000185457, 0, 0.873016, 0.374606, 0.000176436, 0, 0.904762, 0.357601, 0.000166508, 0, 0.936508, 0.341348, 0.000158385, 0, 0.968254, 0.32542, 0.000149203, 0, 1, 1, 0.0000103967, 0, 0, 1, 0.000010397, 0, 0, 1, 0.0000104019, 0, 0, 0.999999, 0.0000104231, 0, 0, 0.999998, 0.0000104806, 0, 0, 0.999995, 0.0000106042, 0, 0, 0.999991, 0.0000108366, 0, 0, 0.999982, 0.0000112415, 0, 0, 0.999968, 0.0000119174, 0, 0, 0.99995, 0.0000130227, 0, 0, 0.999922, 0.0000148176, 0, 0, 0.999884, 0.0000177303, 0, 0, 0.99983, 0.0000224564, 0, 0, 0.999758, 0.0000300966, 0, 0, 0.999654, 0.0000423193, 0, 0.00000549083, 0.999503, 0.0000614848, 0, 0.000296087, 0.999237, 0.0000903576, 0, 0.00123144, 0.998491, 0.0001271, 0, 0.00295954, 0.994594, 0.000107754, 0, 0.00555829, 0.99178, 0.000103025, 0, 0.00907209, 0.989265, 0.00011154, 0, 0.0135257, 0.986998, 0.000136296, 0, 0.0189327, 0.984137, 0.000169154, 0, 0.0252993, 0.979798, 0.000196671, 0, 0.0326272, 0.97337, 0.000196678, 0, 0.0409157, 0.967239, 0.000223121, 0, 0.0501623, 0.959543, 0.000253809, 0, 0.0603638, 0.949466, 0.000265972, 0, 0.0715171, 0.939074, 0.000288372, 0, 0.0836187, 0.931118, 0.000310983, 0, 0.0966657, 0.922525, 0.000325561, 0, 0.110656, 0.912983, 0.000345725, 0, 0.125588, 0.901617, 0.0003556, 0, 0.141461, 0.889487, 0.000374012, 0, 0.158275, 0.875787, 0.000383445, 0, 0.176031, 0.860654, 0.000393972, 0, 0.19473, 0.844417, 0.000400311, 0, 0.214374, 0.82741, 0.000405004, 0, 0.234967, 0.810545, 0.000407378, 0, 0.256512, 0.793312, 0.000407351, 0, 0.279011, 0.774847, 0.000406563, 0, 0.302468, 0.755621, 0.000404903, 0, 0.326887, 0.735511, 0.000397486, 0, 0.352266, 0.715435, 0.00039357, 0, 0.378605, 0.695403, 0.000384739, 0, 0.405897, 0.674681, 0.000376108, 0, 0.43413, 0.65359, 0.000365997, 0, 0.463277, 0.632471, 0.000354957, 0, 0.493295, 0.61151, 0.000343593, 0, 0.524106, 0.59064, 0.000331841, 0, 0.555561, 0.569386, 0.000318891, 0, 0.587302, 0.548785, 0.0003072, 0, 0.619048, 0.528146, 0.00029361, 0, 0.650794, 0.507872, 0.000281709, 0, 0.68254, 0.487805, 0.000268627, 0, 0.714286, 0.468196, 0.000255887, 0, 0.746032, 0.448922, 0.000243997, 0, 0.777778, 0.430093, 0.000231662, 0, 0.809524, 0.411845, 0.000220339, 0, 0.84127, 0.393808, 0.000208694, 0, 0.873016, 0.376615, 0.000198045, 0, 0.904762, 0.359655, 0.000187375, 0, 0.936508, 0.343452, 0.000177371, 0, 0.968254, 0.32765, 0.000167525, 0, 1, 1, 0.0000169351, 0, 0, 1, 0.0000169356, 0, 0, 1, 0.0000169427, 0, 0, 0.999999, 0.0000169736, 0, 0, 0.999998, 0.0000170575, 0, 0, 0.999995, 0.0000172372, 0, 0, 0.99999, 0.0000175739, 0, 0, 0.999979, 0.0000181568, 0, 0, 0.999966, 0.0000191206, 0, 0, 0.999944, 0.000020677, 0, 0, 0.999912, 0.0000231644, 0, 0, 0.999869, 0.0000271268, 0, 0, 0.999811, 0.0000334272, 0, 0, 0.99973, 0.0000433979, 0, 0, 0.999617, 0.0000590083, 0, 0.0000680315, 0.999445, 0.0000829497, 0, 0.000612796, 0.999138, 0.000118019, 0, 0.00187408, 0.998095, 0.000156712, 0, 0.00395791, 0.993919, 0.000125054, 0, 0.00692144, 0.991333, 0.000126091, 0, 0.0107962, 0.989226, 0.000144912, 0, 0.0155986, 0.986954, 0.000175737, 0, 0.0213364, 0.983982, 0.000213883, 0, 0.0280114, 0.979128, 0.000234526, 0, 0.0356226, 0.973327, 0.000243725, 0, 0.0441668, 0.967416, 0.0002773, 0, 0.0536399, 0.959729, 0.000308799, 0, 0.0640376, 0.949758, 0.000322447, 0, 0.0753554, 0.939173, 0.000350021, 0, 0.0875893, 0.9296, 0.000370089, 0, 0.100736, 0.921181, 0.000391365, 0, 0.114793, 0.91164, 0.000413636, 0, 0.129759, 0.900435, 0.000427068, 0, 0.145632, 0.888183, 0.000441046, 0, 0.162412, 0.874772, 0.000454968, 0, 0.180101, 0.859566, 0.000461882, 0, 0.1987, 0.843579, 0.000471556, 0, 0.218213, 0.826453, 0.000474335, 0, 0.238641, 0.809164, 0.000477078, 0, 0.259989, 0.792179, 0.00047755, 0, 0.282262, 0.773866, 0.000472573, 0, 0.305464, 0.754944, 0.000469765, 0, 0.329599, 0.735133, 0.000462371, 0, 0.35467, 0.714858, 0.000453674, 0, 0.380678, 0.694829, 0.000443888, 0, 0.407622, 0.674453, 0.000432052, 0, 0.435493, 0.653685, 0.000420315, 0, 0.464275, 0.632666, 0.000406829, 0, 0.493938, 0.611676, 0.000392234, 0, 0.524422, 0.591193, 0.000379208, 0, 0.555624, 0.570145, 0.00036319, 0, 0.587302, 0.549566, 0.000349111, 0, 0.619048, 0.529278, 0.000334166, 0, 0.650794, 0.509026, 0.000318456, 0, 0.68254, 0.489186, 0.00030449, 0, 0.714286, 0.469662, 0.000289051, 0, 0.746032, 0.450691, 0.000275494, 0, 0.777778, 0.431841, 0.000261437, 0, 0.809524, 0.413752, 0.000247846, 0, 0.84127, 0.395951, 0.000235085, 0, 0.873016, 0.378633, 0.000222245, 0, 0.904762, 0.36194, 0.000210533, 0, 0.936508, 0.345599, 0.000198494, 0, 0.968254, 0.329999, 0.000188133, 0, 1, 1, 0.0000269663, 0, 0, 1, 0.000026967, 0, 0, 1, 0.0000269772, 0, 0, 0.999999, 0.0000270214, 0, 0, 0.999998, 0.0000271415, 0, 0, 0.999994, 0.000027398, 0, 0, 0.999988, 0.0000278771, 0, 0, 0.999977, 0.0000287019, 0, 0, 0.999961, 0.0000300544, 0, 0, 0.999937, 0.0000322138, 0, 0, 0.999904, 0.0000356163, 0, 0, 0.999854, 0.0000409465, 0, 0, 0.99979, 0.0000492651, 0, 0, 0.999699, 0.0000621722, 0, 0.00000088288, 0.999572, 0.0000819715, 0, 0.000223369, 0.999381, 0.000111689, 0, 0.00105414, 0.999016, 0.000153862, 0, 0.0026493, 0.997437, 0.000187667, 0, 0.00508608, 0.993545, 0.000155672, 0, 0.00840554, 0.991135, 0.000161455, 0, 0.012629, 0.989157, 0.000188241, 0, 0.0177661, 0.986874, 0.000226229, 0, 0.0238198, 0.983714, 0.000268668, 0, 0.0307887, 0.978301, 0.000277109, 0, 0.0386688, 0.973227, 0.000303446, 0, 0.0474554, 0.967317, 0.000341851, 0, 0.0571428, 0.959477, 0.000370885, 0, 0.0677256, 0.950012, 0.000392753, 0, 0.0791988, 0.939484, 0.00042781, 0, 0.0915576, 0.928135, 0.000443866, 0, 0.104798, 0.919819, 0.000472959, 0, 0.118918, 0.910049, 0.000491551, 0, 0.133915, 0.899181, 0.000512616, 0, 0.149788, 0.886881, 0.000523563, 0, 0.166537, 0.87359, 0.000540183, 0, 0.184164, 0.858613, 0.000547386, 0, 0.202669, 0.842809, 0.000554809, 0, 0.222056, 0.825727, 0.000558316, 0, 0.242329, 0.808086, 0.000557824, 0, 0.263492, 0.790728, 0.000556346, 0, 0.285551, 0.772987, 0.000552672, 0, 0.30851, 0.7541, 0.000543738, 0, 0.332376, 0.734669, 0.000536107, 0, 0.357153, 0.714411, 0.000523342, 0, 0.382845, 0.694196, 0.000512238, 0, 0.409454, 0.674252, 0.000497465, 0, 0.436977, 0.65357, 0.000481096, 0, 0.465404, 0.632999, 0.000467054, 0, 0.494713, 0.611994, 0.000448771, 0, 0.524864, 0.591604, 0.000431889, 0, 0.555779, 0.571134, 0.000415238, 0, 0.587302, 0.550528, 0.000396369, 0, 0.619048, 0.530292, 0.000379477, 0, 0.650794, 0.510364, 0.000361488, 0, 0.68254, 0.490749, 0.000343787, 0, 0.714286, 0.471266, 0.000327822, 0, 0.746032, 0.452462, 0.000310626, 0, 0.777778, 0.433907, 0.000295352, 0, 0.809524, 0.415659, 0.000279179, 0, 0.84127, 0.398138, 0.000264685, 0, 0.873016, 0.380833, 0.000249905, 0, 0.904762, 0.364247, 0.000236282, 0, 0.936508, 0.348041, 0.000222905, 0, 0.968254, 0.332389, 0.000210522, 0, 1, 1, 0.0000420604, 0, 0, 1, 0.0000420614, 0, 0, 1, 0.0000420757, 0, 0, 0.999999, 0.000042138, 0, 0, 0.999997, 0.0000423067, 0, 0, 0.999993, 0.0000426668, 0, 0, 0.999986, 0.0000433372, 0, 0, 0.999974, 0.0000444857, 0, 0, 0.999956, 0.0000463554, 0, 0, 0.99993, 0.0000493105, 0, 0, 0.999892, 0.0000539077, 0, 0, 0.999838, 0.0000610005, 0, 0, 0.999767, 0.0000718822, 0, 0, 0.999666, 0.0000884581, 0, 0.0000365471, 0.999525, 0.000113398, 0, 0.000485623, 0.999311, 0.000150043, 0, 0.00162096, 0.998865, 0.000200063, 0, 0.00355319, 0.996278, 0.000211014, 0, 0.00633818, 0.992956, 0.000189672, 0, 0.0100043, 0.991017, 0.000210262, 0, 0.0145648, 0.989055, 0.000244292, 0, 0.0200237, 0.986741, 0.000290481, 0, 0.0263798, 0.983288, 0.000334303, 0, 0.033629, 0.977784, 0.000340307, 0, 0.0417652, 0.973037, 0.000377864, 0, 0.0507821, 0.967181, 0.0004239, 0, 0.060673, 0.958971, 0.000443854, 0, 0.0714314, 0.950093, 0.000483039, 0, 0.0830518, 0.939552, 0.000517934, 0, 0.0955288, 0.927678, 0.000539449, 0, 0.108859, 0.918278, 0.000568604, 0, 0.123038, 0.908449, 0.000588505, 0, 0.138065, 0.897713, 0.000612473, 0, 0.153938, 0.885533, 0.000625575, 0, 0.170657, 0.872131, 0.00063854, 0, 0.188224, 0.857517, 0.000647034, 0, 0.20664, 0.841796, 0.00065209, 0, 0.225909, 0.824726, 0.0006544, 0, 0.246035, 0.807297, 0.000655744, 0, 0.267022, 0.789058, 0.000646716, 0, 0.288878, 0.77189, 0.000643898, 0, 0.311607, 0.753082, 0.000629973, 0, 0.335216, 0.7341, 0.000621564, 0, 0.359713, 0.714094, 0.000605171, 0, 0.385103, 0.693839, 0.000588752, 0, 0.41139, 0.673891, 0.000573294, 0, 0.438576, 0.653565, 0.000552682, 0, 0.466656, 0.633326, 0.000533446, 0, 0.495617, 0.612582, 0.000514635, 0, 0.525431, 0.59205, 0.00049303, 0, 0.556041, 0.571918, 0.000471842, 0, 0.587338, 0.551572, 0.000451713, 0, 0.619048, 0.531553, 0.000430049, 0, 0.650794, 0.51175, 0.000410445, 0, 0.68254, 0.49238, 0.000390098, 0, 0.714286, 0.473143, 0.000370033, 0, 0.746032, 0.45423, 0.000351205, 0, 0.777778, 0.435963, 0.000332049, 0, 0.809524, 0.41787, 0.000315021, 0, 0.84127, 0.400387, 0.000297315, 0, 0.873016, 0.383332, 0.000281385, 0, 0.904762, 0.366665, 0.000265397, 0, 0.936508, 0.350633, 0.000250601, 0, 0.968254, 0.334964, 0.00023589, 0, 1, 1, 0.0000643736, 0, 0, 1, 0.000064375, 0, 0, 1, 0.0000643947, 0, 0, 0.999999, 0.000064481, 0, 0, 0.999997, 0.0000647143, 0, 0, 0.999994, 0.0000652119, 0, 0, 0.999985, 0.0000661359, 0, 0, 0.999972, 0.0000677116, 0, 0, 0.999952, 0.0000702599, 0, 0, 0.999922, 0.0000742517, 0, 0, 0.99988, 0.0000803906, 0, 0, 0.99982, 0.0000897315, 0, 0, 0.999741, 0.000103838, 0, 0, 0.999629, 0.00012496, 0, 0.000149024, 0.999474, 0.000156161, 0, 0.000861027, 0.999229, 0.000201034, 0, 0.00231198, 0.998662, 0.000259069, 0, 0.00458147, 0.995299, 0.000245439, 0, 0.00770895, 0.992732, 0.00024498, 0, 0.0117126, 0.990847, 0.000273211, 0, 0.0165989, 0.988911, 0.000316492, 0, 0.0223674, 0.98654, 0.00037161, 0, 0.0290135, 0.982636, 0.000410352, 0, 0.0365309, 0.977346, 0.000421756, 0, 0.0449117, 0.972909, 0.000475578, 0, 0.0541481, 0.966821, 0.000522482, 0, 0.0642326, 0.958686, 0.000545008, 0, 0.075158, 0.949754, 0.000589286, 0, 0.0869181, 0.939184, 0.000619995, 0, 0.0995074, 0.927505, 0.000654266, 0, 0.112922, 0.916606, 0.000682362, 0, 0.127157, 0.906707, 0.000704286, 0, 0.142212, 0.895937, 0.000725909, 0, 0.158085, 0.883913, 0.000743939, 0, 0.174776, 0.870642, 0.000755157, 0, 0.192287, 0.856241, 0.000764387, 0, 0.210619, 0.84069, 0.000771032, 0, 0.229775, 0.823728, 0.000765906, 0, 0.249761, 0.806481, 0.000767604, 0, 0.270582, 0.787924, 0.000754385, 0, 0.292243, 0.770588, 0.000749668, 0, 0.314753, 0.751991, 0.000731613, 0, 0.338118, 0.733407, 0.000717655, 0, 0.362347, 0.713688, 0.000700604, 0, 0.387447, 0.693595, 0.000678765, 0, 0.413424, 0.673426, 0.000657042, 0, 0.440284, 0.65359, 0.000635892, 0, 0.468027, 0.633576, 0.000611569, 0, 0.496645, 0.613144, 0.000586011, 0, 0.526122, 0.592711, 0.000563111, 0, 0.556417, 0.572722, 0.000537699, 0, 0.587451, 0.552762, 0.000512556, 0, 0.619048, 0.532985, 0.000489757, 0, 0.650794, 0.513219, 0.000464139, 0, 0.68254, 0.493992, 0.000442193, 0, 0.714286, 0.47509, 0.000418629, 0, 0.746032, 0.456287, 0.000397045, 0, 0.777778, 0.438152, 0.000375504, 0, 0.809524, 0.420294, 0.00035492, 0, 0.84127, 0.402749, 0.000335327, 0, 0.873016, 0.385879, 0.000316422, 0, 0.904762, 0.369352, 0.000298333, 0, 0.936508, 0.353301, 0.000281417, 0, 0.968254, 0.337781, 0.000265203, 0, 1, 1, 0.0000968267, 0, 0, 1, 0.0000968284, 0, 0, 1, 0.0000968556, 0, 0, 0.999999, 0.0000969733, 0, 0, 0.999997, 0.0000972913, 0, 0, 0.999993, 0.0000979688, 0, 0, 0.999984, 0.0000992239, 0, 0, 0.999969, 0.000101356, 0, 0, 0.999946, 0.000104784, 0, 0, 0.999913, 0.000110111, 0, 0, 0.999868, 0.000118217, 0, 0, 0.999801, 0.000130396, 0, 0, 0.999712, 0.000148523, 0, 0.0000124907, 0.999589, 0.000175233, 0, 0.000355405, 0.999416, 0.000213999, 0, 0.0013528, 0.999136, 0.000268529, 0, 0.00312557, 0.998367, 0.000333088, 0, 0.00573045, 0.994701, 0.000304757, 0, 0.00919397, 0.992497, 0.000318031, 0, 0.0135261, 0.990608, 0.000353863, 0, 0.0187278, 0.988715, 0.000409044, 0, 0.0247947, 0.986241, 0.000472967, 0, 0.0317196, 0.981696, 0.000495104, 0, 0.039494, 0.977097, 0.000532873, 0, 0.0481087, 0.972583, 0.000594447, 0, 0.0575549, 0.966142, 0.000636867, 0, 0.0678242, 0.95823, 0.000669899, 0, 0.0789089, 0.949677, 0.000719499, 0, 0.0908023, 0.939226, 0.000750584, 0, 0.103499, 0.927501, 0.000793183, 0, 0.116993, 0.915199, 0.00081995, 0, 0.131282, 0.90498, 0.000847654, 0, 0.146364, 0.894243, 0.000868929, 0, 0.162237, 0.882154, 0.000884278, 0, 0.178902, 0.869161, 0.000898108, 0, 0.196358, 0.854751, 0.000901254, 0, 0.21461, 0.839368, 0.00090679, 0, 0.23366, 0.822874, 0.000901541, 0, 0.253512, 0.805514, 0.000897297, 0, 0.274174, 0.78716, 0.000881856, 0, 0.29565, 0.769061, 0.000870032, 0, 0.31795, 0.751, 0.000851719, 0, 0.341081, 0.732614, 0.000830671, 0, 0.365053, 0.713171, 0.000806569, 0, 0.389874, 0.693472, 0.00078338, 0, 0.415553, 0.673528, 0.000756404, 0, 0.442098, 0.653397, 0.000726872, 0, 0.469512, 0.633781, 0.000700494, 0, 0.497794, 0.613877, 0.00067105, 0, 0.526935, 0.593506, 0.000640361, 0, 0.556908, 0.573667, 0.000613502, 0, 0.587657, 0.553932, 0.000583177, 0, 0.61906, 0.534345, 0.000554375, 0, 0.650794, 0.515042, 0.000527811, 0, 0.68254, 0.495674, 0.000499367, 0, 0.714286, 0.477132, 0.00047429, 0, 0.746032, 0.458609, 0.000447726, 0, 0.777778, 0.440354, 0.000424205, 0, 0.809524, 0.422765, 0.000399549, 0, 0.84127, 0.405472, 0.000378315, 0, 0.873016, 0.388482, 0.000355327, 0, 0.904762, 0.372191, 0.000336122, 0, 0.936508, 0.356099, 0.000315247, 0, 0.968254, 0.340737, 0.00029794, 0, 1, 1, 0.000143327, 0, 0, 1, 0.00014333, 0, 0, 1, 0.000143366, 0, 0, 0.999999, 0.000143524, 0, 0, 0.999996, 0.000143952, 0, 0, 0.999991, 0.000144862, 0, 0, 0.999981, 0.000146544, 0, 0, 0.999966, 0.000149391, 0, 0, 0.999941, 0.000153946, 0, 0, 0.999905, 0.000160971, 0, 0, 0.999852, 0.000171562, 0, 0, 0.99978, 0.00018729, 0, 0, 0.999681, 0.000210386, 0, 0.0000826239, 0.999546, 0.000243906, 0, 0.000664807, 0.999352, 0.000291739, 0, 0.00196192, 0.999027, 0.000357419, 0, 0.00405941, 0.997886, 0.000422349, 0, 0.00699664, 0.99419, 0.000385008, 0, 0.0107896, 0.99214, 0.000409775, 0, 0.0154415, 0.990274, 0.000456418, 0, 0.0209488, 0.988455, 0.000527008, 0, 0.0273037, 0.985804, 0.000597685, 0, 0.0344969, 0.98103, 0.000613124, 0, 0.0425183, 0.976674, 0.000668321, 0, 0.0513575, 0.972021, 0.000736985, 0, 0.0610046, 0.965274, 0.000773789, 0, 0.0714508, 0.958046, 0.000830852, 0, 0.0826877, 0.949333, 0.000875766, 0, 0.0947085, 0.939135, 0.000917088, 0, 0.107507, 0.927119, 0.000952244, 0, 0.121078, 0.91469, 0.000990626, 0, 0.135419, 0.903006, 0.00101304, 0, 0.150526, 0.892368, 0.00103834, 0, 0.166399, 0.880231, 0.00105002, 0, 0.183038, 0.867432, 0.00106331, 0, 0.200443, 0.853208, 0.00106783, 0, 0.218618, 0.837956, 0.00106458, 0, 0.237566, 0.821772, 0.00105945, 0, 0.257291, 0.804328, 0.00104685, 0, 0.2778, 0.786465, 0.00103178, 0, 0.2991, 0.768004, 0.00101077, 0, 0.321199, 0.74972, 0.000985504, 0, 0.344106, 0.731682, 0.000962893, 0, 0.36783, 0.712813, 0.000932146, 0, 0.392383, 0.693139, 0.00089871, 0, 0.417774, 0.673566, 0.000869678, 0, 0.444013, 0.653483, 0.000835525, 0, 0.471107, 0.633891, 0.000799853, 0, 0.49906, 0.614433, 0.000766838, 0, 0.527869, 0.594586, 0.000732227, 0, 0.557517, 0.574769, 0.000696442, 0, 0.587966, 0.555149, 0.000663935, 0, 0.61913, 0.535898, 0.000629826, 0, 0.650794, 0.516753, 0.000596486, 0, 0.68254, 0.497816, 0.000567078, 0, 0.714286, 0.479034, 0.000534399, 0, 0.746032, 0.460975, 0.000507013, 0, 0.777778, 0.442935, 0.000477421, 0, 0.809524, 0.425263, 0.000451101, 0, 0.84127, 0.408248, 0.000424964, 0, 0.873016, 0.391339, 0.00039993, 0, 0.904762, 0.37513, 0.000377619, 0, 0.936508, 0.359172, 0.000354418, 0, 0.968254, 0.343876, 0.000334823, 0, 1, 1, 0.000209042, 0, 0, 1, 0.000209045, 0, 0, 1, 0.000209093, 0, 0, 0.999999, 0.000209304, 0, 0, 0.999996, 0.000209871, 0, 0, 0.999991, 0.000211078, 0, 0, 0.999979, 0.000213304, 0, 0, 0.999963, 0.000217061, 0, 0, 0.999933, 0.000223042, 0, 0, 0.999894, 0.000232206, 0, 0, 0.999837, 0.000245901, 0, 0, 0.999756, 0.000266023, 0, 0.00000102927, 0.999648, 0.000295204, 0, 0.000233468, 0.999499, 0.000336958, 0, 0.00108237, 0.999283, 0.000395563, 0, 0.00268832, 0.998896, 0.000473785, 0, 0.00511138, 0.997006, 0.000520008, 0, 0.00837705, 0.993819, 0.000497261, 0, 0.0124928, 0.991632, 0.000523722, 0, 0.0174561, 0.989875, 0.000587258, 0, 0.0232596, 0.988109, 0.000676329, 0, 0.0298932, 0.985155, 0.000747701, 0, 0.0373453, 0.980479, 0.000768803, 0, 0.0456045, 0.976271, 0.000841054, 0, 0.0546593, 0.971347, 0.000911469, 0, 0.0644994, 0.964528, 0.000953057, 0, 0.0751152, 0.957632, 0.00102221, 0, 0.0864981, 0.948681, 0.00106122, 0, 0.0986407, 0.938716, 0.00111857, 0, 0.111537, 0.926629, 0.00114762, 0, 0.125182, 0.914025, 0.00118995, 0, 0.139571, 0.901026, 0.00121228, 0, 0.154703, 0.890358, 0.00123946, 0, 0.170576, 0.878283, 0.0012527, 0, 0.18719, 0.865459, 0.00125536, 0, 0.204547, 0.851407, 0.00126134, 0, 0.222648, 0.836276, 0.00124759, 0, 0.241498, 0.820436, 0.00124443, 0, 0.261101, 0.803253, 0.00122071, 0, 0.281465, 0.785562, 0.00120107, 0, 0.302595, 0.76718, 0.00117762, 0, 0.324501, 0.748551, 0.00114289, 0, 0.347192, 0.730564, 0.00110872, 0, 0.370679, 0.712253, 0.00107636, 0, 0.394973, 0.692867, 0.00103646, 0, 0.420085, 0.673695, 0.000996793, 0, 0.446027, 0.653912, 0.00095675, 0, 0.47281, 0.634129, 0.000916739, 0, 0.500441, 0.615004, 0.000874401, 0, 0.528921, 0.595587, 0.000833411, 0, 0.558244, 0.575965, 0.000794556, 0, 0.588384, 0.5566, 0.00075196, 0, 0.619281, 0.537428, 0.000716381, 0, 0.650795, 0.518623, 0.000676558, 0, 0.68254, 0.499964, 0.00064074, 0, 0.714286, 0.481356, 0.000605984, 0, 0.746032, 0.463279, 0.000570256, 0, 0.777778, 0.445673, 0.000540138, 0, 0.809524, 0.428032, 0.000507299, 0, 0.84127, 0.411112, 0.000479553, 0, 0.873016, 0.394444, 0.000450737, 0, 0.904762, 0.378247, 0.000424269, 0, 0.936508, 0.362415, 0.000399111, 0, 0.968254, 0.347103, 0.000375274, 0, 1, 1, 0.000300729, 0, 0, 1, 0.000300733, 0, 0, 1, 0.000300797, 0, 0, 0.999998, 0.000301072, 0, 0, 0.999996, 0.000301817, 0, 0, 0.999989, 0.000303398, 0, 0, 0.999977, 0.000306309, 0, 0, 0.999958, 0.000311209, 0, 0, 0.999927, 0.000318975, 0, 0, 0.999884, 0.000330804, 0, 0, 0.99982, 0.00034834, 0, 0, 0.999733, 0.000373854, 0, 0.0000326995, 0.999613, 0.000410424, 0, 0.000477174, 0.999447, 0.000462047, 0, 0.00161099, 0.999204, 0.000533322, 0, 0.00353153, 0.998725, 0.000624964, 0, 0.00627965, 0.995871, 0.000631786, 0, 0.0098693, 0.993194, 0.000632017, 0, 0.0143011, 0.991541, 0.00068923, 0, 0.019568, 0.989773, 0.000766892, 0, 0.0256593, 0.987647, 0.000863668, 0, 0.0325625, 0.984193, 0.000922089, 0, 0.0402647, 0.980016, 0.000970749, 0, 0.0487532, 0.975859, 0.00106027, 0, 0.058016, 0.970514, 0.00112239, 0, 0.0680419, 0.963625, 0.00117212, 0, 0.0788208, 0.956959, 0.00125211, 0, 0.0903439, 0.947956, 0.00129411, 0, 0.102604, 0.93809, 0.00135879, 0, 0.115594, 0.92659, 0.00139309, 0, 0.129309, 0.913829, 0.00143253, 0, 0.143745, 0.90005, 0.00145809, 0, 0.158901, 0.888129, 0.0014748, 0, 0.174774, 0.87607, 0.00148756, 0, 0.191365, 0.863461, 0.00148714, 0, 0.208674, 0.849594, 0.00148892, 0, 0.226705, 0.834531, 0.00146496, 0, 0.245461, 0.81903, 0.0014579, 0, 0.264947, 0.802122, 0.00143039, 0, 0.28517, 0.78445, 0.00139717, 0, 0.306137, 0.766434, 0.00136312, 0, 0.327857, 0.747816, 0.00132597, 0, 0.350341, 0.729519, 0.00128323, 0, 0.373598, 0.711454, 0.00123803, 0, 0.397642, 0.692699, 0.00119097, 0, 0.422485, 0.673723, 0.00114565, 0, 0.448139, 0.654386, 0.00109552, 0, 0.474619, 0.634673, 0.00104553, 0, 0.501933, 0.615554, 0.00099985, 0, 0.530089, 0.596462, 0.000948207, 0, 0.559087, 0.577385, 0.000902299, 0, 0.588913, 0.558257, 0.000856448, 0, 0.619525, 0.5392, 0.000810395, 0, 0.650826, 0.520543, 0.000768558, 0, 0.68254, 0.502206, 0.0007239, 0, 0.714286, 0.48402, 0.000685794, 0, 0.746032, 0.465779, 0.00064471, 0, 0.777778, 0.448455, 0.000609583, 0, 0.809524, 0.431091, 0.00057227, 0, 0.84127, 0.414147, 0.00054042, 0, 0.873016, 0.39765, 0.000506545, 0, 0.904762, 0.381576, 0.000477635, 0, 0.936508, 0.365881, 0.000448446, 0, 0.968254, 0.350582, 0.000421424, 0, 1, 1, 0.000427144, 0, 0, 1, 0.000427151, 0, 0, 1, 0.000427232, 0, 0, 0.999998, 0.00042759, 0, 0, 0.999995, 0.000428555, 0, 0, 0.999988, 0.000430603, 0, 0, 0.999976, 0.000434368, 0, 0, 0.999952, 0.000440688, 0, 0, 0.999919, 0.000450667, 0, 0, 0.999871, 0.00046578, 0, 0, 0.999801, 0.000488024, 0, 0, 0.999704, 0.000520092, 0, 0.000129791, 0.999572, 0.000565553, 0, 0.000821056, 0.999389, 0.000628906, 0, 0.00225241, 0.999114, 0.000714911, 0, 0.00449109, 0.998488, 0.000819218, 0, 0.00756249, 0.995234, 0.00080415, 0, 0.0114716, 0.993021, 0.000830181, 0, 0.0162131, 0.991407, 0.000902645, 0, 0.021776, 0.989625, 0.000996934, 0, 0.0281471, 0.987064, 0.00109707, 0, 0.0353118, 0.983265, 0.00114353, 0, 0.0432562, 0.979535, 0.0012272, 0, 0.0519665, 0.975224, 0.00132642, 0, 0.0614298, 0.969574, 0.00138092, 0, 0.0716348, 0.963021, 0.00145896, 0, 0.0825709, 0.956046, 0.00152834, 0, 0.094229, 0.947136, 0.00158217, 0, 0.106602, 0.937313, 0.0016347, 0, 0.119682, 0.926073, 0.00168383, 0, 0.133465, 0.913121, 0.00171627, 0, 0.147947, 0.899165, 0.00174229, 0, 0.163125, 0.885891, 0.00176137, 0, 0.178998, 0.873783, 0.00176406, 0, 0.195566, 0.861331, 0.00176156, 0, 0.21283, 0.847569, 0.00175346, 0, 0.230793, 0.832785, 0.00172753, 0, 0.249459, 0.817442, 0.00170204, 0, 0.268832, 0.800613, 0.00166576, 0, 0.28892, 0.783597, 0.00162909, 0, 0.30973, 0.76571, 0.0015826, 0, 0.331271, 0.747021, 0.00153106, 0, 0.353554, 0.728593, 0.00148036, 0, 0.37659, 0.710661, 0.00142808, 0, 0.400391, 0.692426, 0.00136906, 0, 0.424973, 0.673623, 0.00131066, 0, 0.450347, 0.65494, 0.00125569, 0, 0.476531, 0.635448, 0.00119517, 0, 0.503535, 0.616221, 0.00113828, 0, 0.531372, 0.597531, 0.0010816, 0, 0.560047, 0.578795, 0.00102673, 0, 0.589554, 0.559892, 0.000970985, 0, 0.619869, 0.541307, 0.000919773, 0, 0.650923, 0.522608, 0.000868479, 0, 0.68254, 0.504484, 0.00082137, 0, 0.714286, 0.486603, 0.000772916, 0, 0.746032, 0.468802, 0.000730353, 0, 0.777778, 0.451172, 0.000684955, 0, 0.809524, 0.434348, 0.000647565, 0, 0.84127, 0.417445, 0.000605863, 0, 0.873016, 0.401077, 0.000571885, 0, 0.904762, 0.385039, 0.000536034, 0, 0.936508, 0.369483, 0.000504227, 0, 0.968254, 0.354272, 0.000473165, 0, 1, 1, 0.000599525, 0, 0, 1, 0.000599533, 0, 0, 1, 0.000599639, 0, 0, 0.999998, 0.000600097, 0, 0, 0.999994, 0.000601336, 0, 0, 0.999987, 0.000603958, 0, 0, 0.999972, 0.000608775, 0, 0, 0.999949, 0.000616842, 0, 0, 0.999912, 0.000629534, 0, 0, 0.999857, 0.000648658, 0, 0, 0.999781, 0.000676615, 0, 0.00000538873, 0.999674, 0.000716574, 0, 0.000308602, 0.999528, 0.000772641, 0, 0.00127003, 0.999326, 0.000849806, 0, 0.00300783, 0.999009, 0.000952682, 0, 0.00556637, 0.998112, 0.00106394, 0, 0.00895889, 0.994496, 0.00102228, 0, 0.0131827, 0.992806, 0.00108586, 0, 0.0182277, 0.991211, 0.0011759, 0, 0.0240795, 0.989415, 0.00128955, 0, 0.030723, 0.986499, 0.00139038, 0, 0.0381418, 0.982679, 0.00144539, 0, 0.046321, 0.978839, 0.00153954, 0, 0.0552459, 0.974295, 0.00164417, 0, 0.0649034, 0.968784, 0.00171517, 0, 0.0752814, 0.962324, 0.00180282, 0, 0.0863693, 0.954956, 0.00186387, 0, 0.0981578, 0.94624, 0.00193817, 0, 0.110639, 0.936517, 0.00198156, 0, 0.123806, 0.925186, 0.00203042, 0, 0.137655, 0.91252, 0.0020664, 0, 0.15218, 0.898441, 0.00207822, 0, 0.16738, 0.884394, 0.0020992, 0, 0.183253, 0.871273, 0.00208748, 0, 0.199799, 0.859057, 0.00208686, 0, 0.21702, 0.845243, 0.00205519, 0, 0.234918, 0.830723, 0.00202868, 0, 0.253496, 0.815801, 0.00199501, 0, 0.272761, 0.79914, 0.00194193, 0, 0.292719, 0.782372, 0.00188824, 0, 0.313377, 0.76482, 0.00183695, 0, 0.334745, 0.746586, 0.00177418, 0, 0.356833, 0.7281, 0.00170628, 0, 0.379654, 0.709842, 0.00164063, 0, 0.403221, 0.692019, 0.00157355, 0, 0.427548, 0.67364, 0.00150262, 0, 0.452651, 0.655277, 0.00143473, 0, 0.478545, 0.636438, 0.00136371, 0, 0.505246, 0.617364, 0.00129911, 0, 0.532768, 0.598603, 0.00123014, 0, 0.561122, 0.580195, 0.00116587, 0, 0.590309, 0.561786, 0.00110398, 0, 0.620318, 0.543377, 0.00104148, 0, 0.651102, 0.525093, 0.000983984, 0, 0.682545, 0.506791, 0.00092667, 0, 0.714286, 0.489291, 0.000874326, 0, 0.746032, 0.471811, 0.000821734, 0, 0.777778, 0.454435, 0.000774698, 0, 0.809524, 0.437493, 0.000727302, 0, 0.84127, 0.420977, 0.000684039, 0, 0.873016, 0.404729, 0.00064373, 0, 0.904762, 0.388756, 0.00060285, 0, 0.936508, 0.373344, 0.00056765, 0, 0.968254, 0.358191, 0.000531929, 0, 1, 1, 0.000832169, 0, 0, 1, 0.000832178, 0, 0, 1, 0.00083231, 0, 0, 0.999998, 0.000832893, 0, 0, 0.999995, 0.000834465, 0, 0, 0.999985, 0.000837791, 0, 0, 0.999969, 0.000843893, 0, 0, 0.999944, 0.000854086, 0, 0, 0.999903, 0.000870071, 0, 0, 0.999843, 0.000894042, 0, 0, 0.999759, 0.000928865, 0, 0.0000531805, 0.999643, 0.000978242, 0, 0.000579365, 0.99948, 0.00104684, 0, 0.00182774, 0.999255, 0.00114012, 0, 0.00387804, 0.998885, 0.00126188, 0, 0.00675709, 0.997405, 0.00135888, 0, 0.010468, 0.99424, 0.00133626, 0, 0.0150018, 0.992458, 0.00140905, 0, 0.0203443, 0.990929, 0.00152305, 0, 0.0264786, 0.989116, 0.00165882, 0, 0.0333875, 0.985624, 0.00174128, 0, 0.0410536, 0.982003, 0.00182108, 0, 0.0494609, 0.978336, 0.00194498, 0, 0.0585941, 0.973184, 0.00202708, 0, 0.0684396, 0.9678, 0.00212166, 0, 0.0789851, 0.961348, 0.00221366, 0, 0.0902199, 0.953841, 0.00228219, 0, 0.102134, 0.94534, 0.00235662, 0, 0.114721, 0.935552, 0.00240572, 0, 0.127972, 0.924064, 0.00244405, 0, 0.141884, 0.911827, 0.00247557, 0, 0.156451, 0.897731, 0.00248374, 0, 0.171672, 0.883409, 0.00249863, 0, 0.187545, 0.868625, 0.00246688, 0, 0.20407, 0.856529, 0.00246523, 0, 0.221249, 0.842999, 0.00242368, 0, 0.239083, 0.828505, 0.00237354, 0, 0.257578, 0.813825, 0.00232588, 0, 0.276738, 0.797813, 0.00226731, 0, 0.296569, 0.781097, 0.00219704, 0, 0.31708, 0.764038, 0.00212394, 0, 0.338281, 0.746067, 0.00204786, 0, 0.360181, 0.727687, 0.00196728, 0, 0.382794, 0.709571, 0.00188779, 0, 0.406133, 0.691503, 0.00180532, 0, 0.430213, 0.673673, 0.00171849, 0, 0.45505, 0.655732, 0.00164147, 0, 0.480662, 0.637399, 0.00155858, 0, 0.507065, 0.618616, 0.00147641, 0, 0.534278, 0.60005, 0.00140125, 0, 0.562313, 0.581713, 0.00132441, 0, 0.59118, 0.563546, 0.00125014, 0, 0.620875, 0.545605, 0.00118249, 0, 0.651373, 0.527559, 0.0011116, 0, 0.682593, 0.509764, 0.00104979, 0, 0.714286, 0.49193, 0.000985977, 0, 0.746032, 0.475011, 0.000928592, 0, 0.777778, 0.457878, 0.000873466, 0, 0.809524, 0.440979, 0.000819585, 0, 0.84127, 0.424613, 0.000772365, 0, 0.873016, 0.408549, 0.000722195, 0, 0.904762, 0.392771, 0.000680014, 0, 0.936508, 0.377317, 0.000636797, 0, 0.968254, 0.362352, 0.000598318, 0, 1, 1, 0.00114313, 0, 0, 1, 0.00114314, 0, 0, 0.999999, 0.00114331, 0, 0, 0.999998, 0.00114404, 0, 0, 0.999994, 0.00114601, 0, 0, 0.999984, 0.00115019, 0, 0, 0.999967, 0.00115784, 0, 0, 0.999937, 0.0011706, 0, 0, 0.999894, 0.00119054, 0, 0, 0.999828, 0.00122031, 0, 0, 0.999735, 0.00126331, 0, 0.000169263, 0.999606, 0.00132382, 0, 0.000949167, 0.999426, 0.0014071, 0, 0.00249668, 0.999173, 0.00151895, 0, 0.00486392, 0.99873, 0.00166102, 0, 0.00806323, 0.996243, 0.0017023, 0, 0.0120895, 0.993779, 0.00172782, 0, 0.0169288, 0.9919, 0.0018108, 0, 0.0225633, 0.990524, 0.00196028, 0, 0.028974, 0.98868, 0.00212014, 0, 0.036142, 0.984663, 0.00217598, 0, 0.044049, 0.981457, 0.00230563, 0, 0.0526781, 0.977608, 0.00243966, 0, 0.0620137, 0.972215, 0.00251336, 0, 0.0720418, 0.966798, 0.0026285, 0, 0.0827499, 0.960241, 0.00271409, 0, 0.0941271, 0.952489, 0.00278381, 0, 0.106164, 0.944127, 0.00285399, 0, 0.118852, 0.934282, 0.00290994, 0, 0.132185, 0.923271, 0.00294558, 0, 0.146157, 0.910803, 0.00296269, 0, 0.160766, 0.896705, 0.00296803, 0, 0.176007, 0.88238, 0.00296637, 0, 0.19188, 0.867116, 0.00293163, 0, 0.208385, 0.853636, 0.00289418, 0, 0.225523, 0.840469, 0.00284663, 0, 0.243296, 0.82639, 0.00278594, 0, 0.261709, 0.811759, 0.00271618, 0, 0.280767, 0.796113, 0.00263187, 0, 0.300476, 0.779518, 0.00254589, 0, 0.320845, 0.763142, 0.00246003, 0, 0.341883, 0.745464, 0.00236529, 0, 0.363601, 0.727491, 0.00226536, 0, 0.386011, 0.709414, 0.00216375, 0, 0.409128, 0.691396, 0.00207127, 0, 0.432967, 0.67368, 0.00197106, 0, 0.457545, 0.656049, 0.00187022, 0, 0.482881, 0.638188, 0.00177605, 0, 0.508992, 0.620177, 0.00168482, 0, 0.535899, 0.601506, 0.00158909, 0, 0.563619, 0.58362, 0.00150583, 0, 0.592165, 0.565496, 0.00141791, 0, 0.621544, 0.54789, 0.00133693, 0, 0.651743, 0.530323, 0.00126038, 0, 0.682709, 0.512795, 0.00118556, 0, 0.714286, 0.495199, 0.00111527, 0, 0.746032, 0.478101, 0.0010489, 0, 0.777778, 0.461511, 0.000984264, 0, 0.809524, 0.444879, 0.00092591, 0, 0.84127, 0.428424, 0.000866582, 0, 0.873016, 0.412495, 0.000814463, 0, 0.904762, 0.396975, 0.000764498, 0, 0.936508, 0.381614, 0.000715967, 0, 0.968254, 0.366732, 0.000672483, 0, 1, 1, 0.00155501, 0, 0, 1, 0.00155503, 0, 0, 1, 0.00155524, 0, 0, 0.999998, 0.00155615, 0, 0, 0.999994, 0.0015586, 0, 0, 0.999983, 0.00156379, 0, 0, 0.999963, 0.0015733, 0, 0, 0.999932, 0.00158911, 0, 0, 0.999882, 0.00161376, 0, 0, 0.99981, 0.00165041, 0, 0.0000100875, 0.999708, 0.00170304, 0, 0.000367658, 0.999565, 0.00177658, 0, 0.0014234, 0.999368, 0.00187688, 0, 0.00327939, 0.999081, 0.00200989, 0, 0.00596629, 0.99852, 0.00217177, 0, 0.0094852, 0.99549, 0.0021745, 0, 0.013824, 0.993252, 0.00222357, 0, 0.0189642, 0.991727, 0.00235022, 0, 0.0248856, 0.989951, 0.00250561, 0, 0.0315669, 0.988029, 0.00268829, 0, 0.0389882, 0.984029, 0.0027496, 0, 0.0471302, 0.980683, 0.00289793, 0, 0.0559754, 0.976554, 0.00303315, 0, 0.0655081, 0.97139, 0.00313257, 0, 0.0757138, 0.965544, 0.00323656, 0, 0.08658, 0.95912, 0.00333432, 0, 0.0980954, 0.951183, 0.0034039, 0, 0.110251, 0.942974, 0.00347515, 0, 0.123038, 0.932642, 0.00350381, 0, 0.13645, 0.922158, 0.00354519, 0, 0.150482, 0.909404, 0.00353851, 0, 0.165129, 0.896071, 0.0035435, 0, 0.18039, 0.881206, 0.00349936, 0, 0.196263, 0.866077, 0.00347256, 0, 0.212748, 0.85093, 0.003415, 0, 0.229847, 0.837703, 0.00333367, 0, 0.247561, 0.823878, 0.003249, 0, 0.265895, 0.809449, 0.00316347, 0, 0.284854, 0.794379, 0.00306351, 0, 0.304445, 0.778138, 0.0029499, 0, 0.324675, 0.761997, 0.00284099, 0, 0.345555, 0.744938, 0.00272104, 0, 0.367095, 0.727212, 0.00260715, 0, 0.389309, 0.709549, 0.00248855, 0, 0.41221, 0.691704, 0.00236783, 0, 0.435814, 0.673689, 0.00225178, 0, 0.460138, 0.656453, 0.00213765, 0, 0.485203, 0.639128, 0.00202178, 0, 0.511028, 0.621512, 0.00191443, 0, 0.537634, 0.603598, 0.00180977, 0, 0.565041, 0.58559, 0.00170456, 0, 0.593268, 0.567852, 0.00160927, 0, 0.622327, 0.5503, 0.00151395, 0, 0.652217, 0.533033, 0.00142499, 0, 0.682907, 0.515942, 0.00133955, 0, 0.714296, 0.498814, 0.0012602, 0, 0.746032, 0.481595, 0.00118188, 0, 0.777778, 0.465117, 0.00111171, 0, 0.809524, 0.448865, 0.00104091, 0, 0.84127, 0.432711, 0.000976618, 0, 0.873016, 0.416822, 0.00091859, 0, 0.904762, 0.401272, 0.000857704, 0, 0.936508, 0.386226, 0.000807172, 0, 0.968254, 0.371321, 0.00075464, 0, 1, 1, 0.00209596, 0, 0, 1, 0.00209598, 0, 0, 1, 0.00209624, 0, 0, 0.999997, 0.00209736, 0, 0, 0.999991, 0.00210039, 0, 0, 0.999979, 0.00210678, 0, 0, 0.999959, 0.00211847, 0, 0, 0.999925, 0.0021379, 0, 0, 0.99987, 0.00216809, 0, 0, 0.999791, 0.00221281, 0, 0.0000681487, 0.999677, 0.00227669, 0, 0.000658161, 0.999521, 0.00236533, 0, 0.00200635, 0.999301, 0.00248514, 0, 0.0041779, 0.998977, 0.00264185, 0, 0.00718648, 0.998191, 0.00281695, 0, 0.0110239, 0.994801, 0.00278518, 0, 0.015672, 0.993091, 0.00288774, 0, 0.0211091, 0.991571, 0.00303931, 0, 0.0273123, 0.9897, 0.00321643, 0, 0.034259, 0.987023, 0.00337332, 0, 0.0419282, 0.983289, 0.00346146, 0, 0.0502998, 0.979892, 0.00363704, 0, 0.0593562, 0.975111, 0.00373601, 0, 0.069081, 0.970351, 0.0038842, 0, 0.0794598, 0.964131, 0.00397053, 0, 0.0904798, 0.957747, 0.00408078, 0, 0.10213, 0.949536, 0.00413533, 0, 0.1144, 0.941372, 0.00420305, 0, 0.127284, 0.931049, 0.00422815, 0, 0.140772, 0.920647, 0.00425048, 0, 0.154862, 0.908033, 0.0042281, 0, 0.169548, 0.895028, 0.00422026, 0, 0.184828, 0.879968, 0.00415042, 0, 0.200701, 0.864875, 0.00408821, 0, 0.217167, 0.84918, 0.00400909, 0, 0.234227, 0.834934, 0.00391178, 0, 0.251884, 0.821397, 0.00380066, 0, 0.270141, 0.807135, 0.00367974, 0, 0.289004, 0.792363, 0.00355172, 0, 0.308479, 0.776661, 0.003411, 0, 0.328575, 0.760705, 0.00328123, 0, 0.349301, 0.744408, 0.00314003, 0, 0.370668, 0.726994, 0.0029906, 0, 0.392689, 0.709598, 0.00285034, 0, 0.415379, 0.692112, 0.00271179, 0, 0.438754, 0.674435, 0.00257185, 0, 0.46283, 0.65676, 0.00243425, 0, 0.48763, 0.639982, 0.00230351, 0, 0.513173, 0.622983, 0.0021777, 0, 0.539482, 0.605471, 0.00204991, 0, 0.566579, 0.58796, 0.00193759, 0, 0.594488, 0.570463, 0.00181976, 0, 0.623226, 0.553058, 0.00171497, 0, 0.6528, 0.535894, 0.00161109, 0, 0.683198, 0.519089, 0.00151394, 0, 0.714354, 0.502454, 0.00142122, 0, 0.746032, 0.485681, 0.00133488, 0, 0.777778, 0.468935, 0.00124975, 0, 0.809524, 0.452951, 0.00117309, 0, 0.84127, 0.437139, 0.00110155, 0, 0.873016, 0.421446, 0.00103124, 0, 0.904762, 0.405951, 0.000966387, 0, 0.936508, 0.391003, 0.000908119, 0, 0.968254, 0.376198, 0.000848057, 0, 1, 1, 0.00280076, 0, 0, 1, 0.00280078, 0, 0, 0.999999, 0.00280109, 0, 0, 0.999997, 0.00280246, 0, 0, 0.999992, 0.00280616, 0, 0, 0.999979, 0.00281396, 0, 0, 0.999956, 0.00282822, 0, 0, 0.999916, 0.00285186, 0, 0, 0.999857, 0.0028885, 0, 0, 0.999768, 0.00294259, 0, 0.000196026, 0.999645, 0.00301946, 0, 0.00104842, 0.99947, 0.00312541, 0, 0.00270199, 0.999229, 0.00326733, 0, 0.00519449, 0.998852, 0.00344992, 0, 0.00852602, 0.997558, 0.00361052, 0, 0.0126804, 0.994417, 0.0035898, 0, 0.017635, 0.992824, 0.00372393, 0, 0.023365, 0.991344, 0.00390695, 0, 0.0298456, 0.989337, 0.00410392, 0, 0.0370529, 0.985811, 0.00420987, 0, 0.0449651, 0.982772, 0.00437488, 0, 0.0535615, 0.979001, 0.00455069, 0, 0.0628243, 0.974102, 0.00464462, 0, 0.0727368, 0.969197, 0.00480577, 0, 0.0832844, 0.962759, 0.00487818, 0, 0.0944545, 0.956207, 0.00498176, 0, 0.106236, 0.947909, 0.00503392, 0, 0.118619, 0.939596, 0.00507474, 0, 0.131595, 0.929642, 0.00509798, 0, 0.145159, 0.918807, 0.00508476, 0, 0.159305, 0.906921, 0.00505634, 0, 0.174028, 0.893312, 0.00498845, 0, 0.189327, 0.878933, 0.0049133, 0, 0.2052, 0.863986, 0.0048259, 0, 0.221647, 0.847936, 0.00470848, 0, 0.23867, 0.832253, 0.00456889, 0, 0.25627, 0.818619, 0.00442726, 0, 0.274453, 0.804788, 0.00427677, 0, 0.293222, 0.790241, 0.00411906, 0, 0.312585, 0.775162, 0.00394833, 0, 0.33255, 0.759463, 0.00377366, 0, 0.353126, 0.743598, 0.00361026, 0, 0.374324, 0.72697, 0.00343627, 0, 0.396158, 0.709646, 0.00326422, 0, 0.418641, 0.69277, 0.00309717, 0, 0.44179, 0.675371, 0.0029356, 0, 0.465624, 0.657863, 0.00277712, 0, 0.490163, 0.640772, 0.00261738, 0, 0.515429, 0.624441, 0.0024737, 0, 0.541445, 0.607497, 0.00233125, 0, 0.568236, 0.590438, 0.00218994, 0, 0.595828, 0.573224, 0.0020664, 0, 0.624242, 0.556168, 0.00193526, 0, 0.653496, 0.539232, 0.00182463, 0, 0.683588, 0.522352, 0.00170735, 0, 0.714482, 0.506172, 0.00160555, 0, 0.746032, 0.489842, 0.00150451, 0, 0.777778, 0.473463, 0.00140938, 0, 0.809524, 0.457266, 0.00132568, 0, 0.84127, 0.441609, 0.0012376, 0, 0.873016, 0.426348, 0.00116265, 0, 0.904762, 0.411002, 0.00108935, 0, 0.936508, 0.396045, 0.00101946, 0, 0.968254, 0.381448, 0.000955665, 0, 1, 1, 0.0037121, 0, 0, 1, 0.00371213, 0, 0, 1, 0.00371251, 0, 0, 0.999997, 0.00371417, 0, 0, 0.99999, 0.00371863, 0, 0, 0.999977, 0.00372807, 0, 0, 0.99995, 0.00374529, 0, 0, 0.999908, 0.0037738, 0, 0, 0.999843, 0.00381789, 0, 0.0000123596, 0.999745, 0.00388273, 0, 0.000407442, 0.999608, 0.00397443, 0, 0.0015447, 0.999415, 0.00409998, 0, 0.00351385, 0.999143, 0.00426662, 0, 0.0063316, 0.9987, 0.00447625, 0, 0.00998679, 0.996363, 0.00455323, 0, 0.0144569, 0.994021, 0.00461052, 0, 0.0197151, 0.992372, 0.00476359, 0, 0.0257344, 0.991007, 0.00499101, 0, 0.0324882, 0.988767, 0.0051972, 0, 0.0399517, 0.984872, 0.00528407, 0, 0.0481022, 0.982004, 0.00548926, 0, 0.0569191, 0.977714, 0.00564385, 0, 0.0663839, 0.973076, 0.0057693, 0, 0.0764801, 0.967565, 0.0058924, 0, 0.0871928, 0.961384, 0.00599629, 0, 0.0985095, 0.954435, 0.00605998, 0, 0.110419, 0.946303, 0.0061133, 0, 0.122912, 0.937662, 0.00612028, 0, 0.13598, 0.927867, 0.00612209, 0, 0.149617, 0.916475, 0.00604813, 0, 0.163817, 0.90541, 0.00603088, 0, 0.178577, 0.891591, 0.00592218, 0, 0.193894, 0.877573, 0.00578854, 0, 0.209767, 0.862511, 0.00566648, 0, 0.226196, 0.846861, 0.00551481, 0, 0.243182, 0.83068, 0.00533754, 0, 0.260728, 0.815725, 0.00515487, 0, 0.278837, 0.802321, 0.0049655, 0, 0.297515, 0.787826, 0.00475421, 0, 0.316768, 0.773454, 0.00456002, 0, 0.336605, 0.758224, 0.00434727, 0, 0.357034, 0.74265, 0.00414444, 0, 0.378067, 0.726729, 0.00393738, 0, 0.399717, 0.710155, 0.00373575, 0, 0.421998, 0.693312, 0.00353736, 0, 0.444928, 0.67653, 0.00334368, 0, 0.468523, 0.659444, 0.00315981, 0, 0.492806, 0.642051, 0.00297809, 0, 0.517798, 0.625758, 0.00280592, 0, 0.543525, 0.609615, 0.00264254, 0, 0.570012, 0.592919, 0.00248459, 0, 0.597288, 0.576298, 0.00233327, 0, 0.625379, 0.559489, 0.00219519, 0, 0.654307, 0.542891, 0.00205441, 0, 0.684084, 0.526255, 0.00193385, 0, 0.714693, 0.509853, 0.00180745, 0, 0.746044, 0.494131, 0.00169817, 0, 0.777778, 0.478114, 0.0015913, 0, 0.809524, 0.462274, 0.00148981, 0, 0.84127, 0.446412, 0.00139537, 0, 0.873016, 0.431274, 0.00130984, 0, 0.904762, 0.41635, 0.00122403, 0, 0.936508, 0.401476, 0.00114809, 0, 0.968254, 0.386993, 0.00107563, 0, 1, 1, 0.00488216, 0, 0, 1, 0.0048822, 0, 0, 1, 0.00488265, 0, 0, 0.999997, 0.00488463, 0, 0, 0.999988, 0.00488999, 0, 0, 0.999974, 0.00490129, 0, 0, 0.999946, 0.00492191, 0, 0, 0.999897, 0.00495598, 0, 0, 0.999825, 0.00500855, 0, 0.0000744791, 0.999718, 0.00508559, 0, 0.000712744, 0.999565, 0.005194, 0, 0.00215249, 0.999352, 0.00534147, 0, 0.00444576, 0.999046, 0.00553523, 0, 0.00759218, 0.998492, 0.00577016, 0, 0.0115714, 0.995564, 0.00578487, 0, 0.0163557, 0.993339, 0.00586414, 0, 0.021915, 0.991834, 0.00606002, 0, 0.0282201, 0.990496, 0.00633312, 0, 0.0352433, 0.987826, 0.00651941, 0, 0.042959, 0.98383, 0.00660842, 0, 0.0513439, 0.98109, 0.00685523, 0, 0.0603772, 0.976131, 0.00695778, 0, 0.0700402, 0.971922, 0.00714236, 0, 0.0803163, 0.965901, 0.00721437, 0, 0.0911908, 0.959606, 0.00732017, 0, 0.102651, 0.952504, 0.00735788, 0, 0.114686, 0.944365, 0.00738493, 0, 0.127286, 0.935652, 0.00737969, 0, 0.140443, 0.925813, 0.00733612, 0, 0.154151, 0.914397, 0.00723094, 0, 0.168405, 0.903257, 0.00714002, 0, 0.183201, 0.890015, 0.00700149, 0, 0.198536, 0.876014, 0.00682813, 0, 0.214409, 0.861436, 0.00665567, 0, 0.23082, 0.845752, 0.00644526, 0, 0.24777, 0.829169, 0.00621635, 0, 0.265263, 0.813435, 0.00597789, 0, 0.283301, 0.799701, 0.00575694, 0, 0.301889, 0.785726, 0.00549866, 0, 0.321035, 0.77152, 0.0052503, 0, 0.340746, 0.75683, 0.00499619, 0, 0.361032, 0.741951, 0.0047543, 0, 0.381904, 0.726367, 0.0045084, 0, 0.403374, 0.710537, 0.00426784, 0, 0.425457, 0.693965, 0.00403487, 0, 0.448169, 0.677724, 0.0038075, 0, 0.47153, 0.66117, 0.00359431, 0, 0.495561, 0.644274, 0.00338354, 0, 0.520284, 0.627449, 0.00318163, 0, 0.545725, 0.611645, 0.00299672, 0, 0.571911, 0.595614, 0.00281016, 0, 0.598873, 0.579426, 0.00264252, 0, 0.62664, 0.563016, 0.00247509, 0, 0.655239, 0.546728, 0.00232647, 0, 0.684692, 0.530539, 0.00217803, 0, 0.714999, 0.514164, 0.00204216, 0, 0.746106, 0.498344, 0.00191403, 0, 0.777778, 0.482957, 0.00179203, 0, 0.809524, 0.467336, 0.00167695, 0, 0.84127, 0.451994, 0.00157567, 0, 0.873016, 0.436514, 0.00147113, 0, 0.904762, 0.42178, 0.00138034, 0, 0.936508, 0.407271, 0.00129219, 0, 0.968254, 0.392822, 0.0012098, 0, 1, 1, 0.00637427, 0, 0, 1, 0.00637431, 0, 0, 0.999999, 0.00637485, 0, 0, 0.999996, 0.00637721, 0, 0, 0.999987, 0.00638357, 0, 0, 0.999971, 0.006397, 0, 0, 0.999939, 0.00642142, 0, 0, 0.999888, 0.00646177, 0, 0, 0.999807, 0.00652387, 0, 0.000207916, 0.999689, 0.00661454, 0, 0.00112051, 0.99952, 0.00674155, 0, 0.00287719, 0.999283, 0.00691313, 0, 0.00550145, 0.998936, 0.00713598, 0, 0.00897928, 0.998165, 0.00738501, 0, 0.0132829, 0.994847, 0.00734388, 0, 0.01838, 0.993182, 0.00749991, 0, 0.0242381, 0.991665, 0.0077246, 0, 0.030826, 0.989708, 0.00797579, 0, 0.0381152, 0.986663, 0.00813011, 0, 0.0460794, 0.983288, 0.00830365, 0, 0.0546951, 0.980104, 0.00853496, 0, 0.0639411, 0.974855, 0.00861045, 0, 0.0737988, 0.97045, 0.00879133, 0, 0.0842516, 0.964509, 0.00886377, 0, 0.0952848, 0.957594, 0.00890346, 0, 0.106886, 0.950546, 0.00893289, 0, 0.119044, 0.942225, 0.00890074, 0, 0.131749, 0.933365, 0.00886826, 0, 0.144994, 0.923202, 0.0087316, 0, 0.158772, 0.912605, 0.00863082, 0, 0.173078, 0.901099, 0.00847403, 0, 0.187908, 0.888177, 0.00825838, 0, 0.203261, 0.873955, 0.00801834, 0, 0.219134, 0.860091, 0.00779026, 0, 0.235527, 0.84434, 0.00752478, 0, 0.252443, 0.828517, 0.00724074, 0, 0.269883, 0.81239, 0.00693769, 0, 0.287851, 0.79721, 0.00664817, 0, 0.306352, 0.783489, 0.00634763, 0, 0.325393, 0.769514, 0.00604221, 0, 0.344981, 0.755419, 0.00573568, 0, 0.365126, 0.741083, 0.00544359, 0, 0.385839, 0.726059, 0.00515515, 0, 0.407132, 0.710809, 0.00487139, 0, 0.42902, 0.695052, 0.00459846, 0, 0.45152, 0.678886, 0.00433412, 0, 0.474651, 0.663042, 0.00407981, 0, 0.498433, 0.646634, 0.00384264, 0, 0.52289, 0.630117, 0.00360897, 0, 0.548048, 0.613804, 0.00338863, 0, 0.573936, 0.598338, 0.00318486, 0, 0.600584, 0.582687, 0.00298377, 0, 0.628027, 0.566809, 0.00280082, 0, 0.656295, 0.550817, 0.00262255, 0, 0.685417, 0.534937, 0.00245835, 0, 0.715406, 0.519151, 0.00230574, 0, 0.74624, 0.503118, 0.0021549, 0, 0.777778, 0.487723, 0.00202008, 0, 0.809524, 0.472725, 0.00189355, 0, 0.84127, 0.457599, 0.00177108, 0, 0.873016, 0.442558, 0.00165843, 0, 0.904762, 0.427624, 0.00155494, 0, 0.936508, 0.413171, 0.00145273, 0, 0.968254, 0.399122, 0.00136454, 0, 1, 1, 0.00826496, 0, 0, 1, 0.00826499, 0, 0, 1, 0.00826564, 0, 0, 0.999996, 0.00826842, 0, 0, 0.999987, 0.00827589, 0, 0, 0.999967, 0.00829167, 0, 0, 0.999933, 0.00832037, 0, 0, 0.999876, 0.00836768, 0, 0.0000109338, 0.999786, 0.00844031, 0, 0.000427145, 0.999655, 0.00854603, 0, 0.0016384, 0.999468, 0.00869337, 0, 0.00372392, 0.999203, 0.008891, 0, 0.00668513, 0.998803, 0.00914387, 0, 0.0104968, 0.99748, 0.00935838, 0, 0.015125, 0.994446, 0.00933309, 0, 0.0205338, 0.99292, 0.00953084, 0, 0.0266884, 0.991414, 0.0097893, 0, 0.0335565, 0.989049, 0.0100228, 0, 0.0411086, 0.98582, 0.0101664, 0, 0.0493181, 0.982441, 0.0103582, 0, 0.0581613, 0.978595, 0.0105292, 0, 0.0676169, 0.973495, 0.0106274, 0, 0.0776661, 0.968405, 0.0107261, 0, 0.0882926, 0.962717, 0.0108234, 0, 0.0994817, 0.955478, 0.0108102, 0, 0.111221, 0.948275, 0.0107914, 0, 0.123499, 0.940006, 0.0107161, 0, 0.136308, 0.930831, 0.0106309, 0, 0.149639, 0.920648, 0.0104083, 0, 0.163485, 0.910205, 0.0102312, 0, 0.177843, 0.898445, 0.0100051, 0, 0.192707, 0.885986, 0.00971928, 0, 0.208077, 0.872204, 0.00940747, 0, 0.22395, 0.858436, 0.0091085, 0, 0.240326, 0.843454, 0.00876595, 0, 0.257208, 0.827437, 0.00839794, 0, 0.274596, 0.811488, 0.00803692, 0, 0.292496, 0.796039, 0.00767352, 0, 0.310911, 0.781083, 0.0073097, 0, 0.329849, 0.767642, 0.00694032, 0, 0.349316, 0.753901, 0.00657476, 0, 0.369323, 0.740131, 0.00622699, 0, 0.38988, 0.725845, 0.0058838, 0, 0.410999, 0.710991, 0.00555586, 0, 0.432696, 0.696002, 0.00523089, 0, 0.454987, 0.680461, 0.00492494, 0, 0.47789, 0.664875, 0.00463464, 0, 0.501426, 0.649273, 0.00435422, 0, 0.52562, 0.63302, 0.0040875, 0, 0.550498, 0.61705, 0.00384075, 0, 0.576089, 0.601154, 0.00359557, 0, 0.602427, 0.586008, 0.00337636, 0, 0.629544, 0.570699, 0.00316019, 0, 0.657479, 0.555166, 0.00296033, 0, 0.686264, 0.539645, 0.00277552, 0, 0.715924, 0.524159, 0.00259499, 0, 0.746459, 0.508682, 0.00243257, 0, 0.777789, 0.493163, 0.00227851, 0, 0.809524, 0.478004, 0.00213083, 0, 0.84127, 0.46347, 0.00199502, 0, 0.873016, 0.448778, 0.00186967, 0, 0.904762, 0.434105, 0.00174732, 0, 0.936508, 0.419576, 0.00163861, 0, 0.968254, 0.405541, 0.00153341, 0, 1, 1, 0.0106462, 0, 0, 1, 0.0106462, 0, 0, 0.999999, 0.010647, 0, 0, 0.999995, 0.0106502, 0, 0, 0.999985, 0.0106589, 0, 0, 0.999964, 0.0106773, 0, 0, 0.999925, 0.0107106, 0, 0, 0.999861, 0.0107655, 0, 0.0000712986, 0.999763, 0.0108497, 0, 0.000743959, 0.999616, 0.0109716, 0, 0.00227361, 0.999408, 0.0111408, 0, 0.0046983, 0.999112, 0.0113659, 0, 0.00800158, 0.998637, 0.0116475, 0, 0.0121493, 0.996223, 0.0117231, 0, 0.0171023, 0.994006, 0.0118064, 0, 0.0228218, 0.992444, 0.0120254, 0, 0.0292711, 0.991028, 0.0123314, 0, 0.036417, 0.98803, 0.0124954, 0, 0.0442295, 0.984816, 0.0126538, 0, 0.0526815, 0.981399, 0.0128537, 0, 0.0617492, 0.977085, 0.0129694, 0, 0.0714114, 0.972154, 0.013091, 0, 0.0816495, 0.966617, 0.0131166, 0, 0.0924472, 0.960628, 0.0131583, 0, 0.10379, 0.953295, 0.0131094, 0, 0.115665, 0.94575, 0.0129966, 0, 0.128062, 0.937654, 0.0128796, 0, 0.140972, 0.927716, 0.0126477, 0, 0.154387, 0.917932, 0.0123889, 0, 0.168301, 0.907719, 0.012131, 0, 0.182709, 0.89584, 0.0118013, 0, 0.197608, 0.883526, 0.0114145, 0, 0.212994, 0.870301, 0.0110075, 0, 0.228867, 0.856272, 0.0106019, 0, 0.245227, 0.842251, 0.0101938, 0, 0.262074, 0.826466, 0.00973254, 0, 0.279412, 0.810859, 0.0092846, 0, 0.297244, 0.795051, 0.00883304, 0, 0.315575, 0.780053, 0.00840272, 0, 0.334412, 0.76575, 0.00796438, 0, 0.35376, 0.752298, 0.00752526, 0, 0.373631, 0.739153, 0.00711486, 0, 0.394034, 0.725514, 0.00670361, 0, 0.414983, 0.711473, 0.00632656, 0, 0.436491, 0.696936, 0.00595206, 0, 0.458575, 0.682126, 0.00559191, 0, 0.481253, 0.667027, 0.00525362, 0, 0.504547, 0.651875, 0.00493805, 0, 0.528481, 0.636463, 0.00462848, 0, 0.553081, 0.620641, 0.00433936, 0, 0.578377, 0.604931, 0.00407, 0, 0.604404, 0.589549, 0.00380864, 0, 0.631197, 0.574712, 0.00357049, 0, 0.658795, 0.559775, 0.00334466, 0, 0.687238, 0.544514, 0.00312505, 0, 0.716559, 0.529555, 0.00293199, 0, 0.746776, 0.514402, 0.00274204, 0, 0.777849, 0.499302, 0.00256647, 0, 0.809524, 0.484114, 0.00239901, 0, 0.84127, 0.469308, 0.00225148, 0, 0.873016, 0.455133, 0.00210178, 0, 0.904762, 0.440939, 0.0019727, 0, 0.936508, 0.426627, 0.00184382, 0, 0.968254, 0.412509, 0.00172548, 0, 1, 1, 0.013628, 0, 0, 1, 0.0136281, 0, 0, 0.999999, 0.0136289, 0, 0, 0.999995, 0.0136327, 0, 0, 0.999983, 0.0136427, 0, 0, 0.99996, 0.0136638, 0, 0, 0.999917, 0.0137022, 0, 0, 0.999846, 0.0137652, 0, 0.000204597, 0.999736, 0.0138615, 0, 0.00116837, 0.999573, 0.0140007, 0, 0.00303325, 0.99934, 0.0141927, 0, 0.00580613, 0.999004, 0.0144457, 0, 0.00945626, 0.998407, 0.0147489, 0, 0.0139421, 0.995464, 0.014731, 0, 0.0192202, 0.993328, 0.0148283, 0, 0.0252495, 0.991799, 0.0150797, 0, 0.0319921, 0.990397, 0.0154316, 0, 0.0394138, 0.986835, 0.0155005, 0, 0.0474843, 0.983938, 0.0157308, 0, 0.0561763, 0.980154, 0.0158753, 0, 0.0654661, 0.975659, 0.0159581, 0, 0.0753326, 0.970171, 0.0159832, 0, 0.0857571, 0.964803, 0.0160084, 0, 0.0967236, 0.958366, 0.0159484, 0, 0.108218, 0.950613, 0.0158001, 0, 0.120227, 0.942874, 0.0155845, 0, 0.132741, 0.935005, 0.0154292, 0, 0.145751, 0.924991, 0.0150742, 0, 0.159249, 0.914814, 0.0146757, 0, 0.17323, 0.904743, 0.0143097, 0, 0.187687, 0.893216, 0.0138695, 0, 0.202619, 0.880769, 0.0133706, 0, 0.218021, 0.868136, 0.0128606, 0, 0.233894, 0.85469, 0.0123403, 0, 0.250238, 0.840593, 0.0118091, 0, 0.267052, 0.825808, 0.011253, 0, 0.284341, 0.81009, 0.0107099, 0, 0.302106, 0.79504, 0.0101636, 0, 0.320354, 0.779757, 0.00964041, 0, 0.33909, 0.764697, 0.00911896, 0, 0.358322, 0.750913, 0.00859533, 0, 0.378059, 0.738175, 0.00811592, 0, 0.398311, 0.725242, 0.00764504, 0, 0.41909, 0.711864, 0.00718885, 0, 0.440412, 0.698009, 0.00675843, 0, 0.462292, 0.683841, 0.00634984, 0, 0.484748, 0.669391, 0.00595502, 0, 0.507802, 0.654731, 0.00558671, 0, 0.531477, 0.639805, 0.00523578, 0, 0.555802, 0.624789, 0.00490834, 0, 0.580805, 0.609325, 0.00459448, 0, 0.606522, 0.593975, 0.00430342, 0, 0.63299, 0.578983, 0.00403019, 0, 0.66025, 0.564442, 0.0037707, 0, 0.688346, 0.549835, 0.0035316, 0, 0.717319, 0.535039, 0.00330255, 0, 0.7472, 0.520403, 0.00308932, 0, 0.777982, 0.505687, 0.00289335, 0, 0.809524, 0.490939, 0.00270818, 0, 0.84127, 0.476233, 0.0025343, 0, 0.873016, 0.461624, 0.00237097, 0, 0.904762, 0.447833, 0.00222065, 0, 0.936508, 0.433992, 0.00207561, 0, 0.968254, 0.420147, 0.00194955, 0, 1, 1, 0.0173415, 0, 0, 1, 0.0173416, 0, 0, 0.999999, 0.0173426, 0, 0, 0.999995, 0.0173468, 0, 0, 0.999983, 0.0173582, 0, 0, 0.999954, 0.0173822, 0, 0, 0.999908, 0.0174258, 0, 0.00000669501, 0.999828, 0.0174973, 0, 0.000427399, 0.999705, 0.0176063, 0, 0.00171019, 0.999524, 0.0177631, 0, 0.0039248, 0.999263, 0.0179781, 0, 0.00705382, 0.998878, 0.018258, 0, 0.0110552, 0.998012, 0.0185551, 0, 0.0158812, 0.994614, 0.0184264, 0, 0.0214852, 0.993132, 0.0186385, 0, 0.0278239, 0.991563, 0.0189067, 0, 0.0348585, 0.989298, 0.0191577, 0, 0.0425544, 0.986036, 0.0192522, 0, 0.050881, 0.982558, 0.0194063, 0, 0.059811, 0.978531, 0.019486, 0, 0.0693209, 0.974198, 0.0195847, 0, 0.0793895, 0.968148, 0.0194749, 0, 0.0899984, 0.962565, 0.0194277, 0, 0.101132, 0.956041, 0.0192991, 0, 0.112775, 0.947749, 0.0189893, 0, 0.124917, 0.94018, 0.018704, 0, 0.137547, 0.93165, 0.0183458, 0, 0.150655, 0.921798, 0.0178775, 0, 0.164236, 0.911573, 0.0173618, 0, 0.178281, 0.901569, 0.0168482, 0, 0.192788, 0.890341, 0.016265, 0, 0.207752, 0.877835, 0.0156199, 0, 0.223171, 0.865472, 0.0149516, 0, 0.239044, 0.852905, 0.0143274, 0, 0.255371, 0.838906, 0.0136643, 0, 0.272153, 0.824888, 0.0129903, 0, 0.289393, 0.809977, 0.0123218, 0, 0.307093, 0.794697, 0.0116572, 0, 0.325259, 0.780028, 0.0110307, 0, 0.343896, 0.765124, 0.0104236, 0, 0.363012, 0.750411, 0.0098219, 0, 0.382617, 0.737264, 0.00924397, 0, 0.402719, 0.724799, 0.00868719, 0, 0.423332, 0.712253, 0.00816476, 0, 0.444469, 0.699267, 0.00767262, 0, 0.466146, 0.685618, 0.00719746, 0, 0.488383, 0.671736, 0.00673916, 0, 0.511199, 0.657777, 0.00631937, 0, 0.534618, 0.643497, 0.00592411, 0, 0.558668, 0.62889, 0.00553928, 0, 0.58338, 0.614299, 0.0051934, 0, 0.608787, 0.599197, 0.00485985, 0, 0.634929, 0.584175, 0.00454357, 0, 0.661849, 0.569541, 0.00425787, 0, 0.689594, 0.555193, 0.00397905, 0, 0.718211, 0.540947, 0.00372364, 0, 0.747742, 0.526593, 0.00348599, 0, 0.778205, 0.512335, 0.00326103, 0, 0.80953, 0.498017, 0.00305137, 0, 0.84127, 0.483609, 0.00285485, 0, 0.873016, 0.469368, 0.00267472, 0, 0.904762, 0.455037, 0.00249945, 0, 0.936508, 0.441493, 0.00234792, 0, 0.968254, 0.428147, 0.00219936, 0, 1, 1, 0.0219422, 0, 0, 1, 0.0219423, 0, 0, 0.999998, 0.0219434, 0, 0, 0.999993, 0.0219481, 0, 0, 0.999981, 0.021961, 0, 0, 0.999949, 0.0219879, 0, 0, 0.999896, 0.0220367, 0, 0.0000593194, 0.999808, 0.0221167, 0, 0.00075364, 0.99967, 0.0222383, 0, 0.00237884, 0.999466, 0.0224125, 0, 0.00495612, 0.999174, 0.0226495, 0, 0.00844887, 0.998725, 0.0229525, 0, 0.0128058, 0.996979, 0.0231123, 0, 0.0179742, 0.994317, 0.0230742, 0, 0.0239047, 0.992781, 0.0232895, 0, 0.0305526, 0.991191, 0.0235734, 0, 0.0378786, 0.987787, 0.0236152, 0, 0.0458475, 0.985092, 0.0237994, 0, 0.0544287, 0.981121, 0.0238553, 0, 0.0635952, 0.976924, 0.0238706, 0, 0.0733233, 0.97218, 0.0238704, 0, 0.0835922, 0.965956, 0.0236598, 0, 0.0943839, 0.959998, 0.0234735, 0, 0.105682, 0.953245, 0.0232277, 0, 0.117474, 0.944445, 0.0226973, 0, 0.129747, 0.937087, 0.0223527, 0, 0.142491, 0.928341, 0.0218144, 0, 0.155697, 0.9184, 0.0211516, 0, 0.169358, 0.907959, 0.0204553, 0, 0.183469, 0.89808, 0.0197673, 0, 0.198024, 0.887047, 0.0189915, 0, 0.21302, 0.875221, 0.0182082, 0, 0.228455, 0.86269, 0.0173584, 0, 0.244329, 0.850735, 0.0165718, 0, 0.260639, 0.837545, 0.0157524, 0, 0.277389, 0.823639, 0.0149482, 0, 0.29458, 0.809699, 0.0141431, 0, 0.312216, 0.794797, 0.0133527, 0, 0.3303, 0.780578, 0.0126193, 0, 0.34884, 0.766019, 0.0118914, 0, 0.367842, 0.751447, 0.0111839, 0, 0.387315, 0.737275, 0.010514, 0, 0.40727, 0.724545, 0.00987277, 0, 0.427717, 0.712644, 0.00926569, 0, 0.448671, 0.700432, 0.00869029, 0, 0.470149, 0.687664, 0.00814691, 0, 0.492167, 0.674288, 0.00763012, 0, 0.514746, 0.660966, 0.00714437, 0, 0.537911, 0.647264, 0.00668457, 0, 0.561688, 0.633431, 0.00626581, 0, 0.586108, 0.619133, 0.00585593, 0, 0.611206, 0.604935, 0.00548188, 0, 0.637022, 0.590236, 0.00513288, 0, 0.663599, 0.575473, 0.0047906, 0, 0.690989, 0.561228, 0.00448895, 0, 0.719242, 0.547054, 0.00420233, 0, 0.748411, 0.533175, 0.00392869, 0, 0.778531, 0.519163, 0.00367445, 0, 0.809583, 0.505328, 0.00344097, 0, 0.84127, 0.491446, 0.00322003, 0, 0.873016, 0.477356, 0.00301283, 0, 0.904762, 0.46356, 0.00282592, 0, 0.936508, 0.449623, 0.00264956, 0, 0.968254, 0.436068, 0.00246956, 0, 1, 1, 0.0276135, 0, 0, 1, 0.0276136, 0, 0, 0.999998, 0.0276148, 0, 0, 0.999993, 0.0276201, 0, 0, 0.999976, 0.0276342, 0, 0, 0.999945, 0.027664, 0, 0, 0.999884, 0.0277179, 0, 0.00018679, 0.999784, 0.027806, 0, 0.00119607, 0.99963, 0.0279394, 0, 0.00318407, 0.999401, 0.0281295, 0, 0.00613601, 0.999066, 0.0283858, 0, 0.00999963, 0.998524, 0.0287027, 0, 0.0147164, 0.995702, 0.0286256, 0, 0.0202295, 0.993593, 0.0286733, 0, 0.0264876, 0.992067, 0.0288989, 0, 0.0334452, 0.990548, 0.0292135, 0, 0.0410621, 0.986775, 0.0291296, 0, 0.0493032, 0.984054, 0.0293099, 0, 0.0581381, 0.979481, 0.0291881, 0, 0.0675397, 0.975297, 0.0291598, 0, 0.0774848, 0.96981, 0.028954, 0, 0.0879528, 0.963524, 0.028628, 0, 0.0989258, 0.957398, 0.0283135, 0, 0.110388, 0.950088, 0.0278469, 0, 0.122327, 0.941538, 0.0271798, 0, 0.134729, 0.933332, 0.0265388, 0, 0.147587, 0.924392, 0.0257776, 0, 0.160889, 0.914581, 0.024916, 0, 0.174631, 0.904347, 0.0240242, 0, 0.188806, 0.894324, 0.0231229, 0, 0.203409, 0.883724, 0.022153, 0, 0.218437, 0.872207, 0.0211355, 0, 0.233888, 0.859927, 0.0201048, 0, 0.249761, 0.848373, 0.0191263, 0, 0.266056, 0.836023, 0.0181306, 0, 0.282774, 0.82289, 0.0171718, 0, 0.299917, 0.809324, 0.0162196, 0, 0.317488, 0.795361, 0.0152622, 0, 0.335493, 0.781253, 0.01439, 0, 0.353936, 0.767338, 0.013533, 0, 0.372825, 0.753156, 0.0127244, 0, 0.392168, 0.739122, 0.0119454, 0, 0.411976, 0.725358, 0.0112054, 0, 0.432259, 0.712949, 0.010487, 0, 0.453032, 0.701621, 0.00984032, 0, 0.47431, 0.689703, 0.00921495, 0, 0.496111, 0.677216, 0.00862492, 0, 0.518456, 0.664217, 0.00806882, 0, 0.541367, 0.65137, 0.00755922, 0, 0.564872, 0.638, 0.00705705, 0, 0.589001, 0.62453, 0.00661266, 0, 0.613789, 0.610601, 0.00618432, 0, 0.639277, 0.59676, 0.00578033, 0, 0.66551, 0.582433, 0.00540927, 0, 0.692539, 0.568026, 0.00506104, 0, 0.720422, 0.55414, 0.0047353, 0, 0.749216, 0.540178, 0.00442889, 0, 0.778974, 0.526513, 0.00414363, 0, 0.809711, 0.512954, 0.00388237, 0, 0.84127, 0.499403, 0.00362875, 0, 0.873016, 0.486026, 0.00340827, 0, 0.904762, 0.472345, 0.00318598, 0, 0.936508, 0.458828, 0.00297635, 0, 0.968254, 0.445379, 0.00279447, 0, 1, 1, 0.0345716, 0, 0, 1, 0.0345717, 0, 0, 0.999999, 0.034573, 0, 0, 0.999991, 0.0345787, 0, 0, 0.999974, 0.0345941, 0, 0, 0.999937, 0.0346263, 0, 0.00000188589, 0.999869, 0.0346847, 0, 0.000409238, 0.999757, 0.0347798, 0, 0.0017674, 0.999582, 0.0349233, 0, 0.00413658, 0.999322, 0.0351265, 0, 0.00747408, 0.998939, 0.0353967, 0, 0.0117157, 0.998219, 0.0357018, 0, 0.0167966, 0.994974, 0.0354726, 0, 0.0226572, 0.993201, 0.0355621, 0, 0.0292445, 0.991573, 0.0357641, 0, 0.0365123, 0.989301, 0.0359252, 0, 0.0444203, 0.985712, 0.0358017, 0, 0.0529334, 0.982411, 0.0358353, 0, 0.0620214, 0.977827, 0.035617, 0, 0.0716574, 0.973278, 0.0354398, 0, 0.0818186, 0.967397, 0.0350483, 0, 0.0924846, 0.960696, 0.0344795, 0, 0.103638, 0.954349, 0.0339861, 0, 0.115263, 0.946066, 0.0331323, 0, 0.127348, 0.938012, 0.032359, 0, 0.13988, 0.929413, 0.0314413, 0, 0.152849, 0.920355, 0.0304103, 0, 0.166248, 0.910586, 0.0292785, 0, 0.18007, 0.900609, 0.0281391, 0, 0.194308, 0.890093, 0.0269103, 0, 0.208958, 0.880013, 0.0257269, 0, 0.224018, 0.869001, 0.0244671, 0, 0.239485, 0.85751, 0.0232252, 0, 0.255359, 0.84582, 0.0220117, 0, 0.271638, 0.834383, 0.0208274, 0, 0.288324, 0.822158, 0.0196628, 0, 0.305419, 0.809056, 0.0185306, 0, 0.322927, 0.795832, 0.0174174, 0, 0.340851, 0.782547, 0.0163758, 0, 0.359199, 0.7689, 0.015391, 0, 0.377975, 0.755526, 0.0144488, 0, 0.397189, 0.741681, 0.0135372, 0, 0.416851, 0.728178, 0.0126957, 0, 0.436971, 0.714642, 0.0118812, 0, 0.457564, 0.702756, 0.0111165, 0, 0.478644, 0.69175, 0.0104145, 0, 0.500229, 0.680159, 0.00974439, 0, 0.522339, 0.668073, 0.00911926, 0, 0.544997, 0.655405, 0.00851393, 0, 0.56823, 0.642921, 0.00797637, 0, 0.592068, 0.629993, 0.00745119, 0, 0.616546, 0.616828, 0.00696972, 0, 0.641705, 0.603305, 0.00652425, 0, 0.66759, 0.589833, 0.00610188, 0, 0.694255, 0.575945, 0.00570834, 0, 0.72176, 0.561745, 0.00533384, 0, 0.750168, 0.548277, 0.00500001, 0, 0.779545, 0.534467, 0.00467582, 0, 0.809933, 0.521032, 0.00438092, 0, 0.841272, 0.507877, 0.00410348, 0, 0.873016, 0.494654, 0.00383618, 0, 0.904762, 0.481592, 0.00358699, 0, 0.936508, 0.468509, 0.00337281, 0, 0.968254, 0.455293, 0.00316196, 0, 1, 1, 0.0430698, 0, 0, 1, 0.0430699, 0, 0, 0.999998, 0.0430713, 0, 0, 0.999991, 0.0430773, 0, 0, 0.99997, 0.0430936, 0, 0, 0.999928, 0.0431277, 0, 0.0000406396, 0.999852, 0.0431893, 0, 0.000744376, 0.999724, 0.0432895, 0, 0.0024806, 0.999527, 0.0434397, 0, 0.00524779, 0.99923, 0.0436507, 0, 0.00898164, 0.998783, 0.0439255, 0, 0.0136083, 0.997507, 0.0441104, 0, 0.0190582, 0.994418, 0.0438225, 0, 0.0252694, 0.992864, 0.0439396, 0, 0.0321879, 0.991127, 0.0440962, 0, 0.039767, 0.987331, 0.0438408, 0, 0.0479667, 0.984819, 0.0438991, 0, 0.056752, 0.980384, 0.0435906, 0, 0.0660929, 0.975846, 0.0432543, 0, 0.075963, 0.970748, 0.0428293, 0, 0.0863398, 0.964303, 0.042153, 0, 0.0972035, 0.95772, 0.0414111, 0, 0.108537, 0.950747, 0.0405893, 0, 0.120325, 0.942533, 0.0394887, 0, 0.132554, 0.934045, 0.0383544, 0, 0.145215, 0.924942, 0.037057, 0, 0.158296, 0.915811, 0.0356993, 0, 0.17179, 0.90612, 0.0342401, 0, 0.185691, 0.896434, 0.0328078, 0, 0.199993, 0.886021, 0.031288, 0, 0.214691, 0.876081, 0.0297776, 0, 0.229782, 0.865608, 0.0282334, 0, 0.245265, 0.854924, 0.026749, 0, 0.261138, 0.843607, 0.02526, 0, 0.277401, 0.832456, 0.0238214, 0, 0.294056, 0.821342, 0.0224682, 0, 0.311104, 0.809303, 0.0211297, 0, 0.328548, 0.796468, 0.0198387, 0, 0.346394, 0.784046, 0.0186227, 0, 0.364645, 0.771262, 0.0174561, 0, 0.38331, 0.758118, 0.0163806, 0, 0.402396, 0.745075, 0.0153287, 0, 0.421912, 0.731926, 0.0143647, 0, 0.44187, 0.71863, 0.0134363, 0, 0.462283, 0.705414, 0.0125603, 0, 0.483165, 0.693792, 0.0117508, 0, 0.504535, 0.683108, 0.0110016, 0, 0.52641, 0.67183, 0.0102757, 0, 0.548816, 0.66015, 0.00962044, 0, 0.571776, 0.647907, 0.00898031, 0, 0.595323, 0.635734, 0.00840811, 0, 0.619489, 0.623208, 0.00786211, 0, 0.644317, 0.610438, 0.00734953, 0, 0.669852, 0.597345, 0.00687688, 0, 0.696148, 0.584138, 0.00643469, 0, 0.723267, 0.5707, 0.00602236, 0, 0.75128, 0.556966, 0.0056324, 0, 0.780258, 0.543607, 0.00528277, 0, 0.810268, 0.530213, 0.00493999, 0, 0.841311, 0.516912, 0.00462265, 0, 0.873016, 0.503916, 0.0043307, 0, 0.904762, 0.491146, 0.00406858, 0, 0.936508, 0.478439, 0.00381436, 0, 0.968254, 0.465834, 0.00358003, 0, 1, 1, 0.0534039, 0, 0, 1, 0.053404, 0, 0, 0.999998, 0.0534055, 0, 0, 0.999989, 0.0534116, 0, 0, 0.999968, 0.0534283, 0, 0, 0.999918, 0.0534633, 0, 0.000155895, 0.99983, 0.0535262, 0, 0.00120914, 0.999685, 0.0536281, 0, 0.00334944, 0.999461, 0.0537799, 0, 0.00653077, 0.999119, 0.0539902, 0, 0.0106718, 0.998582, 0.0542524, 0, 0.0156907, 0.995919, 0.0540318, 0, 0.0215147, 0.993735, 0.0538914, 0, 0.0280801, 0.992126, 0.0539557, 0, 0.0353323, 0.990266, 0.0540401, 0, 0.0432247, 0.986317, 0.0536064, 0, 0.0517172, 0.983213, 0.0534425, 0, 0.0607754, 0.978303, 0.0528622, 0, 0.0703698, 0.973665, 0.0523363, 0, 0.0804742, 0.968091, 0.0516165, 0, 0.0910667, 0.961026, 0.0505434, 0, 0.102128, 0.954333, 0.049523, 0, 0.113641, 0.946372, 0.0481698, 0, 0.125591, 0.938254, 0.0467674, 0, 0.137965, 0.929516, 0.0452341, 0, 0.150754, 0.920106, 0.0435083, 0, 0.163947, 0.910899, 0.0417399, 0, 0.177537, 0.901532, 0.0399389, 0, 0.191516, 0.891919, 0.0380901, 0, 0.205881, 0.882006, 0.0362341, 0, 0.220626, 0.871965, 0.0343444, 0, 0.235749, 0.862145, 0.0324832, 0, 0.251248, 0.852058, 0.0306681, 0, 0.267121, 0.84161, 0.0289097, 0, 0.283368, 0.830806, 0.0272079, 0, 0.299992, 0.820476, 0.0256089, 0, 0.316992, 0.809514, 0.0240394, 0, 0.334374, 0.797865, 0.0225379, 0, 0.35214, 0.785621, 0.0211235, 0, 0.370296, 0.773765, 0.0197908, 0, 0.388849, 0.761629, 0.0185235, 0, 0.407807, 0.748891, 0.0173358, 0, 0.427178, 0.736437, 0.0162305, 0, 0.446974, 0.723707, 0.0151778, 0, 0.467207, 0.710606, 0.0141791, 0, 0.487892, 0.698019, 0.0132592, 0, 0.509046, 0.686203, 0.0123887, 0, 0.530687, 0.675692, 0.0115976, 0, 0.552839, 0.664826, 0.0108325, 0, 0.575527, 0.65349, 0.0101348, 0, 0.59878, 0.641774, 0.00947756, 0, 0.622634, 0.629794, 0.00886058, 0, 0.647128, 0.617647, 0.00828526, 0, 0.672308, 0.60534, 0.00775312, 0, 0.698231, 0.592718, 0.00726033, 0, 0.724958, 0.579746, 0.00679731, 0, 0.752563, 0.566763, 0.00636111, 0, 0.781127, 0.553515, 0.00595228, 0, 0.810733, 0.540118, 0.00556876, 0, 0.841426, 0.527325, 0.00523051, 0, 0.873016, 0.514265, 0.00490712, 0, 0.904762, 0.501406, 0.00460297, 0, 0.936508, 0.488922, 0.00431247, 0, 0.968254, 0.476541, 0.0040472, 0, 1, 1, 0.0659184, 0, 0, 1, 0.0659185, 0, 0, 0.999998, 0.06592, 0, 0, 0.999988, 0.0659259, 0, 0, 0.999963, 0.0659423, 0, 0, 0.999907, 0.0659764, 0, 0.000374198, 0.999806, 0.0660376, 0, 0.00182071, 0.999639, 0.0661361, 0, 0.0043894, 0.999378, 0.0662814, 0, 0.00800055, 0.998985, 0.0664779, 0, 0.0125594, 0.998285, 0.0666914, 0, 0.0179786, 0.995071, 0.0661989, 0, 0.0241822, 0.993172, 0.0660454, 0, 0.031106, 0.991438, 0.0660105, 0, 0.0386952, 0.988428, 0.0656875, 0, 0.0469032, 0.985218, 0.0652913, 0, 0.0556905, 0.981128, 0.0647107, 0, 0.065023, 0.976015, 0.0638491, 0, 0.0748717, 0.97097, 0.062993, 0, 0.0852112, 0.964582, 0.0617927, 0, 0.0960199, 0.957383, 0.0603626, 0, 0.107279, 0.949969, 0.0588128, 0, 0.118971, 0.941843, 0.0570274, 0, 0.131084, 0.933624, 0.0551885, 0, 0.143604, 0.924543, 0.053122, 0, 0.156521, 0.914919, 0.0508897, 0, 0.169825, 0.905773, 0.0486418, 0, 0.18351, 0.896434, 0.0463364, 0, 0.197569, 0.887195, 0.0440623, 0, 0.211997, 0.877706, 0.0417799, 0, 0.226789, 0.867719, 0.03945, 0, 0.241944, 0.858587, 0.037243, 0, 0.257458, 0.849317, 0.0350956, 0, 0.273331, 0.839585, 0.0329852, 0, 0.289563, 0.829856, 0.0310028, 0, 0.306154, 0.819589, 0.0290953, 0, 0.323108, 0.809714, 0.0272738, 0, 0.340426, 0.79934, 0.0255631, 0, 0.358113, 0.788224, 0.0239175, 0, 0.376175, 0.776619, 0.0223831, 0, 0.394616, 0.76521, 0.0209298, 0, 0.413445, 0.753716, 0.0195786, 0, 0.432671, 0.741564, 0.0183001, 0, 0.452305, 0.729413, 0.0171259, 0, 0.472358, 0.717146, 0.0159933, 0, 0.492845, 0.70436, 0.0149495, 0, 0.513783, 0.69219, 0.0139681, 0, 0.535189, 0.680289, 0.0130577, 0, 0.557087, 0.669611, 0.0122198, 0, 0.5795, 0.659113, 0.0114174, 0, 0.602459, 0.648148, 0.0106729, 0, 0.625997, 0.636905, 0.00998997, 0, 0.650154, 0.625154, 0.00934313, 0, 0.674976, 0.613481, 0.00874839, 0, 0.700518, 0.60154, 0.00818265, 0, 0.726845, 0.58943, 0.00766889, 0, 0.754032, 0.576828, 0.00717153, 0, 0.782167, 0.564194, 0.00672696, 0, 0.811344, 0.551501, 0.00630863, 0, 0.841644, 0.538635, 0.00592177, 0, 0.873016, 0.525724, 0.00554888, 0, 0.904762, 0.513209, 0.00520225, 0, 0.936508, 0.500457, 0.00488231, 0, 0.968254, 0.48799, 0.00457153, 0, 1, 1, 0.0810131, 0, 0, 1, 0.0810133, 0, 0, 0.999997, 0.0810145, 0, 0, 0.999985, 0.08102, 0, 0, 0.999956, 0.0810347, 0, 0.0000195026, 0.999893, 0.0810656, 0, 0.000719316, 0.999777, 0.0811205, 0, 0.00259774, 0.999583, 0.081208, 0, 0.00561807, 0.999281, 0.0813343, 0, 0.00967472, 0.998813, 0.0814969, 0, 0.0146627, 0.997597, 0.0815217, 0, 0.0204902, 0.994379, 0.0808502, 0, 0.0270802, 0.992744, 0.0806792, 0, 0.0343674, 0.990745, 0.0804589, 0, 0.0422974, 0.986646, 0.0796107, 0, 0.0508242, 0.983611, 0.0790913, 0, 0.0599087, 0.978869, 0.0780746, 0, 0.0695175, 0.973475, 0.0768218, 0, 0.0796223, 0.967845, 0.0754926, 0, 0.0901983, 0.960778, 0.0737063, 0, 0.101224, 0.953333, 0.0718052, 0, 0.112682, 0.945274, 0.0695946, 0, 0.124555, 0.936955, 0.0672492, 0, 0.136831, 0.928319, 0.0647732, 0, 0.149496, 0.919075, 0.0620947, 0, 0.162542, 0.909114, 0.0591816, 0, 0.175958, 0.900137, 0.0563917, 0, 0.189739, 0.891069, 0.0535392, 0, 0.203877, 0.882262, 0.0507642, 0, 0.218368, 0.873232, 0.0479793, 0, 0.233208, 0.864042, 0.045226, 0, 0.248393, 0.855002, 0.0425413, 0, 0.263923, 0.846569, 0.0400126, 0, 0.279796, 0.837714, 0.0375269, 0, 0.296012, 0.828918, 0.0352027, 0, 0.312573, 0.819783, 0.0330011, 0, 0.329479, 0.810129, 0.0308908, 0, 0.346734, 0.800866, 0.0289112, 0, 0.364342, 0.79093, 0.0270255, 0, 0.382307, 0.780593, 0.0252758, 0, 0.400637, 0.769511, 0.0236178, 0, 0.419337, 0.758558, 0.0220652, 0, 0.438418, 0.747632, 0.0206289, 0, 0.457889, 0.736146, 0.0192873, 0, 0.477761, 0.724093, 0.0180333, 0, 0.49805, 0.71234, 0.0168264, 0, 0.51877, 0.700201, 0.015746, 0, 0.53994, 0.687949, 0.0147027, 0, 0.561581, 0.676163, 0.0137512, 0, 0.583718, 0.665001, 0.0128655, 0, 0.60638, 0.65472, 0.0120366, 0, 0.629599, 0.644213, 0.0112604, 0, 0.653415, 0.633382, 0.0105413, 0, 0.677874, 0.62212, 0.00986498, 0, 0.70303, 0.610631, 0.00923308, 0, 0.728948, 0.599078, 0.00864206, 0, 0.755706, 0.587519, 0.00811784, 0, 0.783396, 0.575505, 0.00761237, 0, 0.812121, 0.563148, 0.00713949, 0, 0.841989, 0.550828, 0.00668379, 0, 0.873035, 0.538458, 0.00627715, 0, 0.904762, 0.525905, 0.00588336, 0, 0.936508, 0.513517, 0.00552687, 0, 0.968254, 0.501395, 0.00519681, 0, 1, 1, 0.0991506, 0, 0, 1, 0.0991504, 0, 0, 0.999996, 0.0991515, 0, 0, 0.999984, 0.0991558, 0, 0, 0.999947, 0.0991672, 0, 0.000114389, 0.999874, 0.0991912, 0, 0.00121503, 0.999739, 0.0992331, 0, 0.00356108, 0.999514, 0.0992983, 0, 0.00705578, 0.999159, 0.0993877, 0, 0.011574, 0.998586, 0.0994837, 0, 0.017003, 0.995731, 0.0988425, 0, 0.0232484, 0.993384, 0.098276, 0, 0.0302318, 0.991615, 0.0979269, 0, 0.0378884, 0.989029, 0.0973432, 0, 0.0461641, 0.985373, 0.0963539, 0, 0.0550136, 0.981278, 0.0952306, 0, 0.0643988, 0.975777, 0.0936233, 0, 0.0742868, 0.970526, 0.0920219, 0, 0.0846501, 0.963755, 0.0898912, 0, 0.0954644, 0.956676, 0.0876064, 0, 0.106709, 0.948099, 0.0847751, 0, 0.118367, 0.939718, 0.0818638, 0, 0.130423, 0.931305, 0.078857, 0, 0.142862, 0.922342, 0.0756127, 0, 0.155674, 0.912842, 0.0721473, 0, 0.168849, 0.903304, 0.0686195, 0, 0.182378, 0.89411, 0.0650589, 0, 0.196255, 0.885512, 0.0616022, 0, 0.210473, 0.877193, 0.0582434, 0, 0.225027, 0.86877, 0.0548979, 0, 0.239915, 0.860267, 0.0516095, 0, 0.255132, 0.851915, 0.048468, 0, 0.270678, 0.843912, 0.0454447, 0, 0.286551, 0.83604, 0.0425612, 0, 0.302751, 0.828245, 0.0398752, 0, 0.31928, 0.820159, 0.0373198, 0, 0.336138, 0.81167, 0.034916, 0, 0.35333, 0.802659, 0.0326402, 0, 0.370858, 0.793921, 0.0304901, 0, 0.388728, 0.784713, 0.0284857, 0, 0.406944, 0.774946, 0.0266186, 0, 0.425515, 0.76448, 0.0248593, 0, 0.444449, 0.753793, 0.0232114, 0, 0.463756, 0.743506, 0.0217039, 0, 0.483447, 0.732555, 0.0202841, 0, 0.503535, 0.720965, 0.0189648, 0, 0.524036, 0.709422, 0.0177189, 0, 0.544968, 0.697756, 0.0165626, 0, 0.56635, 0.685565, 0.015483, 0, 0.588208, 0.673987, 0.0144892, 0, 0.610569, 0.66244, 0.0135607, 0, 0.633466, 0.651675, 0.0126956, 0, 0.656936, 0.641598, 0.0118788, 0, 0.681025, 0.63121, 0.0111261, 0, 0.705788, 0.620514, 0.010437, 0, 0.731289, 0.609366, 0.00978747, 0, 0.757606, 0.598137, 0.00917257, 0, 0.784834, 0.586966, 0.00859778, 0, 0.813085, 0.575549, 0.00806803, 0, 0.842485, 0.563797, 0.00757294, 0, 0.87313, 0.551758, 0.00710592, 0, 0.904762, 0.539894, 0.0066841, 0, 0.936508, 0.527901, 0.00627901, 0, 0.968254, 0.515819, 0.00590506, 0, 1, 1, 0.120864, 0, 0, 1, 0.120864, 0, 0, 0.999996, 0.120864, 0, 0, 0.99998, 0.120867, 0, 0, 0.99994, 0.120872, 0, 0.000323781, 0.999852, 0.120884, 0, 0.00188693, 0.999693, 0.120903, 0, 0.00473489, 0.999426, 0.120929, 0, 0.00872704, 0.999002, 0.120955, 0, 0.0137237, 0.998235, 0.120918, 0, 0.0196068, 0.994608, 0.119764, 0, 0.0262803, 0.992997, 0.119265, 0, 0.0336657, 0.990968, 0.11863, 0, 0.0416987, 0.987002, 0.117261, 0, 0.0503261, 0.983524, 0.116009, 0, 0.0595035, 0.97875, 0.114252, 0, 0.0691935, 0.972652, 0.11193, 0, 0.0793645, 0.966613, 0.109555, 0, 0.0899894, 0.959275, 0.106612, 0, 0.101045, 0.951272, 0.103375, 0, 0.112512, 0.942323, 0.0996594, 0, 0.124372, 0.933679, 0.0958841, 0, 0.136611, 0.924822, 0.0919265, 0, 0.149216, 0.915742, 0.0878061, 0, 0.162176, 0.906348, 0.0834894, 0, 0.175482, 0.896883, 0.079085, 0, 0.189125, 0.88774, 0.0746745, 0, 0.203098, 0.87986, 0.0705773, 0, 0.217396, 0.871998, 0.0665005, 0, 0.232015, 0.864325, 0.0625413, 0, 0.24695, 0.856685, 0.0586781, 0, 0.2622, 0.84925, 0.0550063, 0, 0.277761, 0.841719, 0.0514727, 0, 0.293634, 0.834755, 0.0481398, 0, 0.309819, 0.827853, 0.0450172, 0, 0.326315, 0.820888, 0.0420969, 0, 0.343126, 0.813616, 0.0393702, 0, 0.360254, 0.805767, 0.0367771, 0, 0.377701, 0.797338, 0.0343274, 0, 0.395474, 0.789122, 0.0320529, 0, 0.413577, 0.780601, 0.0299485, 0, 0.432018, 0.771424, 0.0279812, 0, 0.450804, 0.761502, 0.0261054, 0, 0.469944, 0.751166, 0.0243942, 0, 0.489451, 0.741276, 0.0228087, 0, 0.509337, 0.730898, 0.0213265, 0, 0.529617, 0.719878, 0.0199307, 0, 0.550307, 0.708379, 0.0186574, 0, 0.571428, 0.697165, 0.0174446, 0, 0.593003, 0.685554, 0.0163144, 0, 0.615059, 0.673631, 0.015276, 0, 0.637628, 0.662385, 0.0143003, 0, 0.660746, 0.651059, 0.0134112, 0, 0.68446, 0.640451, 0.0125794, 0, 0.70882, 0.630536, 0.011793, 0, 0.733893, 0.620316, 0.0110547, 0, 0.759756, 0.609722, 0.0103668, 0, 0.786505, 0.598804, 0.00973009, 0, 0.814259, 0.587871, 0.00912812, 0, 0.843157, 0.577121, 0.00858916, 0, 0.87334, 0.566019, 0.00807333, 0, 0.904762, 0.554664, 0.00759687, 0, 0.936508, 0.543101, 0.00714759, 0, 0.968254, 0.531558, 0.00673418, 0, 1, 1, 0.146767, 0, 0, 1, 0.146767, 0, 0, 0.999997, 0.146767, 0, 0, 0.999977, 0.146765, 0, 0.00000320658, 0.999929, 0.146762, 0, 0.000682576, 0.999823, 0.146753, 0, 0.00276402, 0.999633, 0.146735, 0, 0.00614771, 0.999314, 0.146699, 0, 0.0106613, 0.998796, 0.14662, 0, 0.0161546, 0.997124, 0.146107, 0, 0.0225063, 0.994062, 0.144857, 0, 0.0296198, 0.992154, 0.144011, 0, 0.037417, 0.989186, 0.142712, 0, 0.0458348, 0.985279, 0.140926, 0, 0.0548211, 0.980826, 0.13885, 0, 0.0643326, 0.975056, 0.136168, 0, 0.074333, 0.969005, 0.133217, 0, 0.0847917, 0.961554, 0.12959, 0, 0.0956828, 0.954206, 0.125886, 0, 0.106984, 0.945046, 0.121335, 0, 0.118675, 0.935678, 0.116492, 0, 0.130741, 0.926748, 0.111635, 0, 0.143166, 0.917764, 0.106625, 0, 0.155939, 0.908358, 0.101325, 0, 0.169049, 0.899219, 0.0960249, 0, 0.182487, 0.890089, 0.0906527, 0, 0.196245, 0.881488, 0.0853905, 0, 0.210317, 0.874031, 0.0804177, 0, 0.224697, 0.866932, 0.0756005, 0, 0.23938, 0.859976, 0.0709019, 0, 0.254364, 0.853375, 0.0664391, 0, 0.269646, 0.846971, 0.0622012, 0, 0.285223, 0.840483, 0.058129, 0, 0.301096, 0.833969, 0.0542762, 0, 0.317265, 0.82806, 0.0507042, 0, 0.333729, 0.822128, 0.047368, 0, 0.350491, 0.815989, 0.044272, 0, 0.367554, 0.809336, 0.0413444, 0, 0.38492, 0.802177, 0.038601, 0, 0.402594, 0.79441, 0.0360227, 0, 0.420582, 0.786573, 0.0336383, 0, 0.438891, 0.778619, 0.0314321, 0, 0.457527, 0.77, 0.029362, 0, 0.476499, 0.760698, 0.0274102, 0, 0.49582, 0.750932, 0.0256146, 0, 0.5155, 0.740993, 0.023974, 0, 0.535555, 0.731159, 0.0224182, 0, 0.556, 0.720836, 0.0209889, 0, 0.576855, 0.709913, 0.0196411, 0, 0.598143, 0.698415, 0.0183824, 0, 0.619888, 0.68745, 0.0172222, 0, 0.642123, 0.676154, 0.0161509, 0, 0.664883, 0.664383, 0.0151397, 0, 0.688211, 0.6533, 0.0141873, 0, 0.71216, 0.642072, 0.0133105, 0, 0.736792, 0.631412, 0.0124932, 0, 0.762186, 0.621622, 0.0117408, 0, 0.788439, 0.611681, 0.0110358, 0, 0.815672, 0.60142, 0.0103775, 0, 0.844034, 0.59083, 0.00975623, 0, 0.873699, 0.580254, 0.00918084, 0, 0.904765, 0.569841, 0.00864721, 0, 0.936508, 0.559224, 0.00815731, 0, 0.968254, 0.548315, 0.00767924, 0, 1, 1, 0.177563, 0, 0, 1, 0.177563, 0, 0, 0.999994, 0.177562, 0, 0, 0.999972, 0.177555, 0, 0.0000664171, 0.999914, 0.177536, 0, 0.0012276, 0.999787, 0.177496, 0, 0.00388025, 0.999556, 0.17742, 0, 0.00783463, 0.999165, 0.177285, 0, 0.0128953, 0.9985, 0.177037, 0, 0.0189053, 0.995388, 0.175634, 0, 0.025742, 0.993102, 0.174375, 0, 0.033309, 0.990992, 0.173121, 0, 0.0415298, 0.986932, 0.170896, 0, 0.0503425, 0.982786, 0.16847, 0, 0.0596964, 0.977592, 0.165455, 0, 0.0695498, 0.971075, 0.161676, 0, 0.0798676, 0.963967, 0.157458, 0, 0.0906201, 0.956397, 0.152836, 0, 0.101783, 0.947489, 0.147467, 0, 0.113333, 0.937564, 0.14145, 0, 0.125254, 0.928182, 0.135383, 0, 0.137529, 0.919027, 0.129212, 0, 0.150144, 0.909618, 0.12276, 0, 0.163088, 0.900492, 0.116273, 0, 0.176351, 0.891671, 0.1098, 0, 0.189924, 0.883146, 0.103362, 0, 0.203799, 0.875151, 0.0970799, 0, 0.21797, 0.868338, 0.0911732, 0, 0.232433, 0.862033, 0.0854966, 0, 0.247182, 0.856107, 0.0800691, 0, 0.262216, 0.850644, 0.0749618, 0, 0.27753, 0.845261, 0.070079, 0, 0.293124, 0.839885, 0.0654321, 0, 0.308997, 0.834609, 0.0610975, 0, 0.325149, 0.829083, 0.0569741, 0, 0.341581, 0.82404, 0.0531736, 0, 0.358294, 0.818968, 0.049665, 0, 0.37529, 0.813496, 0.0463856, 0, 0.392573, 0.807533, 0.0433217, 0, 0.410148, 0.80099, 0.0404402, 0, 0.428019, 0.793891, 0.0377578, 0, 0.446192, 0.786281, 0.0352616, 0, 0.464676, 0.778773, 0.0329577, 0, 0.483478, 0.770737, 0.030808, 0, 0.502608, 0.762094, 0.0287964, 0, 0.522079, 0.752898, 0.0269254, 0, 0.541905, 0.743306, 0.0251926, 0, 0.5621, 0.733416, 0.023595, 0, 0.582684, 0.723742, 0.0221155, 0, 0.603677, 0.713542, 0.0207435, 0, 0.625106, 0.702755, 0.019434, 0, 0.646998, 0.691484, 0.0182046, 0, 0.66939, 0.680531, 0.0170771, 0, 0.692324, 0.66953, 0.0160339, 0, 0.715849, 0.658126, 0.0150677, 0, 0.740028, 0.646933, 0.0141551, 0, 0.764937, 0.636107, 0.0133179, 0, 0.790673, 0.625271, 0.0125284, 0, 0.817358, 0.615225, 0.0117937, 0, 0.84515, 0.605678, 0.0111181, 0, 0.874244, 0.59583, 0.0104759, 0, 0.904828, 0.585704, 0.00986672, 0, 0.936508, 0.575413, 0.00929712, 0, 0.968254, 0.565373, 0.00876713, 0, 1, 1, 0.214058, 0, 0, 0.999999, 0.214058, 0, 0, 0.999994, 0.214055, 0, 0, 0.999966, 0.214039, 0, 0.000259642, 0.999893, 0.213998, 0, 0.00200075, 0.999737, 0.21391, 0, 0.00527775, 0.999449, 0.213745, 0, 0.00983959, 0.99896, 0.213458, 0, 0.0154755, 0.9979, 0.212855, 0, 0.0220249, 0.994278, 0.210779, 0, 0.0293654, 0.992254, 0.20926, 0, 0.0374021, 0.98881, 0.206908, 0, 0.0460604, 0.984715, 0.204009, 0, 0.0552802, 0.979738, 0.200471, 0, 0.0650127, 0.972884, 0.195813, 0, 0.0752175, 0.965996, 0.190856, 0, 0.0858612, 0.957974, 0.185077, 0, 0.0969155, 0.949155, 0.17868, 0, 0.108356, 0.939288, 0.171513, 0, 0.120163, 0.928996, 0.163838, 0, 0.132319, 0.919563, 0.156246, 0, 0.144808, 0.910004, 0.148359, 0, 0.157618, 0.900791, 0.140417, 0, 0.170737, 0.892135, 0.132569, 0, 0.184155, 0.883803, 0.124741, 0, 0.197866, 0.876034, 0.117091, 0, 0.211861, 0.869219, 0.109835, 0, 0.226134, 0.863062, 0.102859, 0, 0.240682, 0.857795, 0.0962928, 0, 0.255499, 0.853009, 0.0900725, 0, 0.270583, 0.848603, 0.0842101, 0, 0.285931, 0.844335, 0.0786527, 0, 0.301542, 0.840208, 0.0734397, 0, 0.317415, 0.836035, 0.0685334, 0, 0.33355, 0.83172, 0.0639275, 0, 0.349948, 0.827135, 0.0595909, 0, 0.36661, 0.822797, 0.0556204, 0, 0.383539, 0.818387, 0.0519394, 0, 0.400738, 0.813565, 0.0485317, 0, 0.41821, 0.808142, 0.0453138, 0, 0.435961, 0.802212, 0.0423354, 0, 0.453997, 0.79573, 0.0395553, 0, 0.472324, 0.788741, 0.036988, 0, 0.490951, 0.781093, 0.0345688, 0, 0.509887, 0.773597, 0.0323297, 0, 0.529144, 0.765622, 0.0302719, 0, 0.548735, 0.757083, 0.0283477, 0, 0.568674, 0.747992, 0.0265562, 0, 0.588979, 0.738591, 0.0248844, 0, 0.609671, 0.728719, 0.0233342, 0, 0.630773, 0.719146, 0.0219081, 0, 0.652314, 0.709165, 0.0205711, 0, 0.674328, 0.69875, 0.0193248, 0, 0.696854, 0.687884, 0.0181582, 0, 0.719942, 0.676818, 0.0170746, 0, 0.743651, 0.666247, 0.0160718, 0, 0.768057, 0.655284, 0.0151262, 0, 0.793253, 0.64401, 0.0142561, 0, 0.819363, 0.633353, 0.0134327, 0, 0.846547, 0.622674, 0.012653, 0, 0.875017, 0.612265, 0.0119354, 0, 0.905021, 0.602455, 0.0112533, 0, 0.936508, 0.593147, 0.0106234, 0, 0.968254, 0.583592, 0.0100213, 0, 1, 1, 0.25717, 0, 0, 1, 0.25717, 0, 0, 0.999992, 0.257164, 0, 0, 0.999958, 0.257135, 0, 0.000641715, 0.999864, 0.25706, 0, 0.00305314, 0.999666, 0.256897, 0, 0.00700975, 0.999302, 0.256596, 0, 0.0122194, 0.998663, 0.25607, 0, 0.0184622, 0.995607, 0.254123, 0, 0.0255773, 0.993094, 0.252081, 0, 0.0334439, 0.9907, 0.249867, 0, 0.0419696, 0.98594, 0.246118, 0, 0.0510823, 0.981214, 0.242049, 0, 0.0607242, 0.974966, 0.236869, 0, 0.0708486, 0.967589, 0.230724, 0, 0.081417, 0.95915, 0.223635, 0, 0.0923974, 0.950257, 0.21596, 0, 0.103763, 0.940165, 0.207296, 0, 0.115491, 0.929396, 0.197901, 0, 0.127562, 0.919288, 0.188437, 0, 0.13996, 0.909428, 0.178762, 0, 0.15267, 0.900105, 0.169072, 0, 0.165679, 0.891418, 0.159478, 0, 0.178979, 0.883347, 0.15002, 0, 0.192558, 0.875992, 0.140813, 0, 0.20641, 0.869466, 0.13196, 0, 0.220529, 0.863699, 0.123501, 0, 0.234907, 0.858553, 0.115436, 0, 0.249542, 0.854379, 0.107901, 0, 0.264428, 0.850894, 0.10088, 0, 0.279564, 0.847632, 0.0942296, 0, 0.294947, 0.844571, 0.0879861, 0, 0.310575, 0.84163, 0.0821534, 0, 0.326448, 0.838542, 0.0766409, 0, 0.342566, 0.835412, 0.0715322, 0, 0.358929, 0.831899, 0.0666883, 0, 0.37554, 0.828177, 0.0622175, 0, 0.392399, 0.82416, 0.0580452, 0, 0.409511, 0.820393, 0.054267, 0, 0.426878, 0.816068, 0.0507172, 0, 0.444506, 0.811201, 0.0474041, 0, 0.4624, 0.805785, 0.0443174, 0, 0.480566, 0.799878, 0.0414562, 0, 0.499013, 0.793469, 0.0388147, 0, 0.517749, 0.786473, 0.0363453, 0, 0.536785, 0.778874, 0.0340225, 0, 0.556134, 0.771277, 0.0318599, 0, 0.575809, 0.763426, 0.0298859, 0, 0.595827, 0.755044, 0.0280357, 0, 0.616207, 0.746161, 0.0262979, 0, 0.636973, 0.737124, 0.0247295, 0, 0.65815, 0.72761, 0.0232514, 0, 0.679772, 0.717822, 0.0218755, 0, 0.701876, 0.708279, 0.0205942, 0, 0.724509, 0.698333, 0.0193947, 0, 0.74773, 0.68802, 0.0182717, 0, 0.771609, 0.677321, 0.0172044, 0, 0.79624, 0.666504, 0.0162122, 0, 0.821743, 0.656184, 0.0152924, 0, 0.84828, 0.64556, 0.0144326, 0, 0.876069, 0.634636, 0.0136157, 0, 0.905404, 0.624124, 0.0128612, 0, 0.936508, 0.613914, 0.0121435, 0, 0.968254, 0.603589, 0.0114887, 0, 1, 1, 0.307946, 0, 0, 0.999999, 0.307945, 0, 0, 0.999988, 0.307934, 0, 0.0000204479, 0.999944, 0.307886, 0, 0.00127833, 0.999824, 0.307756, 0, 0.00445047, 0.999565, 0.30748, 0, 0.00914673, 0.999085, 0.306966, 0, 0.0150498, 0.998103, 0.306004, 0, 0.0219367, 0.994249, 0.303028, 0, 0.0296485, 0.991807, 0.300435, 0, 0.038068, 0.987773, 0.296554, 0, 0.0471062, 0.982673, 0.2916, 0, 0.0566942, 0.976623, 0.285641, 0, 0.0667768, 0.968757, 0.27815, 0, 0.0773099, 0.959849, 0.269529, 0, 0.088257, 0.950663, 0.260248, 0, 0.0995879, 0.940129, 0.249704, 0, 0.111277, 0.92895, 0.238291, 0, 0.123304, 0.917996, 0.226501, 0, 0.13565, 0.907813, 0.214669, 0, 0.148299, 0.898305, 0.202835, 0, 0.161237, 0.889626, 0.191158, 0, 0.174455, 0.88175, 0.179695, 0, 0.187941, 0.874715, 0.168548, 0, 0.201687, 0.868746, 0.15792, 0, 0.215687, 0.863703, 0.147807, 0, 0.229933, 0.859315, 0.138149, 0, 0.24442, 0.855538, 0.128993, 0, 0.259145, 0.852428, 0.120414, 0, 0.274103, 0.850168, 0.112498, 0, 0.289293, 0.848132, 0.105054, 0, 0.304711, 0.846291, 0.0981087, 0, 0.320357, 0.844431, 0.0915942, 0, 0.33623, 0.842493, 0.0855056, 0, 0.35233, 0.840368, 0.0798204, 0, 0.368658, 0.83798, 0.0745097, 0, 0.385214, 0.83523, 0.0695424, 0, 0.402002, 0.832091, 0.0649092, 0, 0.419023, 0.828667, 0.0606291, 0, 0.436282, 0.824805, 0.0566523, 0, 0.453782, 0.820988, 0.0530229, 0, 0.471529, 0.816635, 0.0496364, 0, 0.489528, 0.811725, 0.0464658, 0, 0.507788, 0.806316, 0.0435082, 0, 0.526317, 0.800469, 0.0407873, 0, 0.545124, 0.794107, 0.038255, 0, 0.564221, 0.787218, 0.0358825, 0, 0.583621, 0.779872, 0.0336785, 0, 0.603341, 0.772097, 0.0316379, 0, 0.623397, 0.764484, 0.0297379, 0, 0.643812, 0.756428, 0.0279581, 0, 0.664611, 0.748022, 0.0263153, 0, 0.685824, 0.739268, 0.0247799, 0, 0.707488, 0.73024, 0.0233385, 0, 0.729646, 0.720893, 0.0220035, 0, 0.752354, 0.71119, 0.0207555, 0, 0.77568, 0.701791, 0.0195843, 0, 0.799715, 0.692184, 0.0184891, 0, 0.824574, 0.682258, 0.0174541, 0, 0.850417, 0.67206, 0.0164873, 0, 0.877466, 0.661717, 0.0155959, 0, 0.90604, 0.651462, 0.0147519, 0, 0.936528, 0.641467, 0.0139727, 0, 0.968254, 0.631229, 0.0132363, 0, 1, 1, 0.367573, 0, 0, 0.999999, 0.367571, 0, 0, 0.999984, 0.367553, 0, 0.000183382, 0.999925, 0.367473, 0, 0.00225254, 0.999759, 0.367259, 0, 0.00628165, 0.99941, 0.366801, 0, 0.0117858, 0.998739, 0.365946, 0, 0.0184359, 0.995529, 0.363191, 0, 0.0260114, 0.992875, 0.360171, 0, 0.0343581, 0.989135, 0.355981, 0, 0.0433637, 0.984166, 0.350401, 0, 0.0529438, 0.977871, 0.343348, 0, 0.0630334, 0.96951, 0.334341, 0, 0.0735805, 0.959964, 0.323862, 0, 0.0845437, 0.950162, 0.312521, 0, 0.095889, 0.938882, 0.299577, 0, 0.107588, 0.926992, 0.285573, 0, 0.119617, 0.915589, 0.271212, 0, 0.131957, 0.904791, 0.256611, 0, 0.144591, 0.895177, 0.242224, 0, 0.157503, 0.886403, 0.227952, 0, 0.170682, 0.878957, 0.214192, 0, 0.184117, 0.872418, 0.200795, 0, 0.197799, 0.867029, 0.188015, 0, 0.21172, 0.862835, 0.175975, 0, 0.225873, 0.859411, 0.164526, 0, 0.240253, 0.856655, 0.153693, 0, 0.254854, 0.854519, 0.14352, 0, 0.269673, 0.852828, 0.13397, 0, 0.284707, 0.851412, 0.124984, 0, 0.299953, 0.850609, 0.116748, 0, 0.315408, 0.849855, 0.10905, 0, 0.331073, 0.849017, 0.101839, 0, 0.346946, 0.848079, 0.0951359, 0, 0.363028, 0.846911, 0.0888774, 0, 0.379318, 0.845445, 0.0830375, 0, 0.395818, 0.84362, 0.0775844, 0, 0.41253, 0.841411, 0.0725054, 0, 0.429457, 0.838768, 0.0677691, 0, 0.446602, 0.835801, 0.0634016, 0, 0.463968, 0.832341, 0.0593095, 0, 0.481561, 0.828424, 0.0555121, 0, 0.499386, 0.824312, 0.052024, 0, 0.51745, 0.819918, 0.0487865, 0, 0.535761, 0.815072, 0.0457801, 0, 0.554328, 0.809863, 0.0430184, 0, 0.573162, 0.804164, 0.0404245, 0, 0.592275, 0.798034, 0.0380146, 0, 0.611681, 0.791436, 0.0357436, 0, 0.631398, 0.784498, 0.0336475, 0, 0.651445, 0.777125, 0.0316666, 0, 0.671845, 0.769365, 0.0298122, 0, 0.692628, 0.761579, 0.0281001, 0, 0.713827, 0.753746, 0.0265049, 0, 0.735484, 0.745573, 0.0250067, 0, 0.75765, 0.737083, 0.0236026, 0, 0.78039, 0.728545, 0.0223302, 0, 0.803789, 0.719691, 0.0211243, 0, 0.82796, 0.710569, 0.0199983, 0, 0.853056, 0.701216, 0.0189569, 0, 0.879298, 0.692094, 0.0179702, 0, 0.907014, 0.682909, 0.0170418, 0, 0.936691, 0.673509, 0.0161732, 0, 0.968254, 0.663863, 0.0153406, 0, 1, 1, 0.437395, 0, 0, 0.999998, 0.437394, 0, 0, 0.99998, 0.437363, 0, 0.000616704, 0.999891, 0.437232, 0, 0.00367925, 0.999656, 0.436877, 0, 0.00867446, 0.999148, 0.436121, 0, 0.0150679, 0.997959, 0.434564, 0, 0.022531, 0.993464, 0.430134, 0, 0.0308507, 0.990606, 0.426077, 0, 0.0398805, 0.985027, 0.419397, 0, 0.0495148, 0.978491, 0.41118, 0, 0.0596749, 0.969643, 0.40048, 0, 0.0703001, 0.959189, 0.38769, 0, 0.0813427, 0.948223, 0.373575, 0, 0.0927641, 0.935955, 0.357622, 0, 0.104533, 0.923237, 0.34043, 0, 0.116624, 0.911074, 0.322735, 0, 0.129015, 0.899724, 0.30479, 0, 0.141687, 0.890189, 0.287392, 0, 0.154626, 0.881796, 0.270248, 0, 0.167818, 0.874781, 0.253659, 0, 0.181252, 0.869166, 0.237786, 0, 0.194918, 0.864725, 0.222618, 0, 0.208807, 0.861565, 0.208356, 0, 0.222913, 0.859284, 0.194867, 0, 0.237229, 0.857677, 0.18212, 0, 0.25175, 0.856714, 0.17018, 0, 0.266473, 0.856155, 0.158969, 0, 0.281392, 0.8558, 0.148413, 0, 0.296505, 0.855672, 0.138578, 0, 0.311811, 0.855538, 0.129345, 0, 0.327306, 0.855689, 0.120861, 0, 0.342991, 0.855767, 0.112969, 0, 0.358864, 0.855618, 0.105593, 0, 0.374925, 0.85525, 0.0987451, 0, 0.391176, 0.854583, 0.0923727, 0, 0.407616, 0.853534, 0.0864143, 0, 0.424249, 0.852061, 0.0808338, 0, 0.441076, 0.850253, 0.0756771, 0, 0.4581, 0.848004, 0.0708612, 0, 0.475324, 0.845333, 0.0663784, 0, 0.492754, 0.842376, 0.0622631, 0, 0.510394, 0.838956, 0.0584112, 0, 0.528251, 0.835121, 0.0548328, 0, 0.546331, 0.830842, 0.0514838, 0, 0.564644, 0.826212, 0.048355, 0, 0.583198, 0.821522, 0.0454714, 0, 0.602005, 0.816551, 0.0428263, 0, 0.621078, 0.811211, 0.0403612, 0, 0.640434, 0.805479, 0.038039, 0, 0.660089, 0.799409, 0.0358739, 0, 0.680066, 0.79306, 0.0338727, 0, 0.70039, 0.786395, 0.0319985, 0, 0.721094, 0.779416, 0.030241, 0, 0.742215, 0.77214, 0.0285951, 0, 0.7638, 0.764636, 0.0270747, 0, 0.785912, 0.756836, 0.0256354, 0, 0.808628, 0.749315, 0.0243027, 0, 0.832055, 0.741561, 0.0230497, 0, 0.856338, 0.733589, 0.0218801, 0, 0.88169, 0.725479, 0.020784, 0, 0.908441, 0.717255, 0.0197702, 0, 0.937125, 0.708829, 0.0188168, 0, 0.968254, 0.700191, 0.0179113, 0, 1, 1, 0.518937, 0, 0, 0.999998, 0.518933, 0, 0, 0.999967, 0.518883, 0, 0.00147741, 0.999832, 0.51866, 0, 0.00573221, 0.999466, 0.518057, 0, 0.011826, 0.998644, 0.516752, 0, 0.0192116, 0.994458, 0.512347, 0, 0.027573, 0.991223, 0.507675, 0, 0.0367099, 0.985515, 0.500188, 0, 0.046487, 0.978308, 0.490408, 0, 0.0568071, 0.968359, 0.477357, 0, 0.0675984, 0.95682, 0.461752, 0, 0.0788059, 0.943929, 0.443796, 0, 0.090386, 0.930224, 0.423893, 0, 0.102304, 0.916514, 0.402682, 0, 0.114532, 0.903653, 0.380914, 0, 0.127047, 0.892315, 0.359212, 0, 0.139828, 0.882942, 0.338102, 0, 0.152861, 0.875438, 0.31773, 0, 0.16613, 0.869642, 0.298186, 0, 0.179624, 0.865304, 0.279491, 0, 0.193332, 0.862382, 0.261804, 0, 0.207247, 0.860666, 0.245146, 0, 0.22136, 0.859788, 0.229406, 0, 0.235666, 0.859608, 0.214605, 0, 0.250158, 0.859912, 0.200691, 0, 0.264832, 0.86053, 0.187623, 0, 0.279684, 0.861368, 0.17539, 0, 0.294711, 0.862237, 0.163901, 0, 0.309911, 0.863127, 0.153175, 0, 0.32528, 0.863923, 0.143147, 0, 0.340819, 0.864567, 0.133781, 0, 0.356524, 0.865013, 0.125042, 0, 0.372397, 0.86539, 0.116952, 0, 0.388438, 0.865591, 0.109476, 0, 0.404645, 0.865517, 0.102542, 0, 0.421022, 0.865084, 0.0960688, 0, 0.437569, 0.864309, 0.0900499, 0, 0.454287, 0.863151, 0.0844328, 0, 0.471181, 0.861649, 0.0792218, 0, 0.488253, 0.859742, 0.0743482, 0, 0.505507, 0.857446, 0.0697963, 0, 0.522947, 0.854757, 0.0655364, 0, 0.54058, 0.851783, 0.061608, 0, 0.558412, 0.848516, 0.0579701, 0, 0.576449, 0.844897, 0.0545742, 0, 0.594701, 0.840956, 0.0514167, 0, 0.613178, 0.836676, 0.0484598, 0, 0.631892, 0.832075, 0.0456934, 0, 0.650856, 0.827191, 0.0431178, 0, 0.670088, 0.822295, 0.0407718, 0, 0.689606, 0.817294, 0.0386032, 0, 0.709434, 0.812013, 0.0365675, 0, 0.7296, 0.806465, 0.0346547, 0, 0.750138, 0.800691, 0.0328717, 0, 0.771093, 0.794709, 0.031211, 0, 0.792519, 0.788493, 0.0296504, 0, 0.814488, 0.782049, 0.0281782, 0, 0.837097, 0.775403, 0.0267965, 0, 0.860481, 0.76857, 0.0255002, 0, 0.884842, 0.761536, 0.0242759, 0, 0.910494, 0.754303, 0.0231142, 0, 0.937985, 0.74692, 0.0220305, 0, 0.968254, 0.739745, 0.0210192, 0, 1, 1, 0.613914, 0, 0, 0.999996, 0.613907, 0, 0.0000963597, 0.999942, 0.613814, 0, 0.00301247, 0.999704, 0.613407, 0, 0.00870385, 0.999046, 0.612302, 0, 0.0160714, 0.995516, 0.608266, 0, 0.0245899, 0.991726, 0.602863, 0, 0.0339681, 0.985157, 0.593956, 0, 0.0440254, 0.97642, 0.581748, 0, 0.0546409, 0.964404, 0.565183, 0, 0.0657284, 0.950601, 0.545273, 0, 0.0772246, 0.935158, 0.522129, 0, 0.0890812, 0.919364, 0.496782, 0, 0.10126, 0.904754, 0.470571, 0, 0.113731, 0.89176, 0.444037, 0, 0.126469, 0.881492, 0.418322, 0, 0.139454, 0.873656, 0.393522, 0, 0.15267, 0.868053, 0.369795, 0, 0.166101, 0.864336, 0.347171, 0, 0.179736, 0.862259, 0.325737, 0, 0.193565, 0.861556, 0.305532, 0, 0.207578, 0.861776, 0.286416, 0, 0.221769, 0.862661, 0.268355, 0, 0.23613, 0.864015, 0.251334, 0, 0.250656, 0.865711, 0.235352, 0, 0.265343, 0.867519, 0.220302, 0, 0.280187, 0.869351, 0.206161, 0, 0.295183, 0.871144, 0.192908, 0, 0.31033, 0.872839, 0.180505, 0, 0.325624, 0.874307, 0.168848, 0, 0.341065, 0.875667, 0.158021, 0, 0.35665, 0.876758, 0.147877, 0, 0.37238, 0.87764, 0.138441, 0, 0.388253, 0.878237, 0.129627, 0, 0.404269, 0.878563, 0.121415, 0, 0.42043, 0.878572, 0.113741, 0, 0.436735, 0.87842, 0.106652, 0, 0.453187, 0.878057, 0.100097, 0, 0.469786, 0.877413, 0.0940128, 0, 0.486536, 0.87646, 0.0883462, 0, 0.503439, 0.875233, 0.0830924, 0, 0.520498, 0.8737, 0.0781975, 0, 0.537717, 0.871873, 0.07364, 0, 0.555102, 0.86978, 0.0694103, 0, 0.572657, 0.867405, 0.0654696, 0, 0.59039, 0.864751, 0.0617914, 0, 0.608307, 0.861818, 0.0583491, 0, 0.626419, 0.858645, 0.0551443, 0, 0.644733, 0.855307, 0.0521894, 0, 0.663264, 0.851736, 0.0494334, 0, 0.682025, 0.847927, 0.0468504, 0, 0.701032, 0.843888, 0.0444261, 0, 0.720308, 0.839629, 0.0421497, 0, 0.739875, 0.835158, 0.0400082, 0, 0.759764, 0.830509, 0.0380076, 0, 0.780014, 0.825714, 0.0361488, 0, 0.800673, 0.820729, 0.0343956, 0, 0.821803, 0.815751, 0.0327781, 0, 0.843492, 0.810752, 0.031275, 0, 0.86586, 0.805587, 0.0298542, 0, 0.889087, 0.800317, 0.0285397, 0, 0.913466, 0.79489, 0.0272948, 0, 0.93952, 0.789314, 0.0261139, 0, 0.96835, 0.783593, 0.0249938, 0, 1, 1, 0.724258, 0, 0, 0.999992, 0.724243, 0, 0.000726889, 0.99987, 0.724044, 0, 0.00569574, 0.999336, 0.72317, 0, 0.0131702, 0.996271, 0.719432, 0, 0.0220738, 0.991159, 0.712576, 0, 0.0319405, 0.982465, 0.700927, 0, 0.0425202, 0.97049, 0.684297, 0, 0.0536599, 0.953973, 0.661244, 0, 0.065258, 0.935546, 0.633804, 0, 0.0772427, 0.916596, 0.603071, 0, 0.0895616, 0.899353, 0.57105, 0, 0.102175, 0.885216, 0.539206, 0, 0.11505, 0.875076, 0.508714, 0, 0.128164, 0.868334, 0.479571, 0, 0.141495, 0.864414, 0.451796, 0, 0.155026, 0.862678, 0.425328, 0, 0.168745, 0.862835, 0.400352, 0, 0.182639, 0.864067, 0.376532, 0, 0.196699, 0.866086, 0.35391, 0, 0.210915, 0.868557, 0.332424, 0, 0.225282, 0.871271, 0.312053, 0, 0.239792, 0.874058, 0.292764, 0, 0.25444, 0.8768, 0.27453, 0, 0.269223, 0.87939, 0.257297, 0, 0.284135, 0.8819, 0.24114, 0, 0.299174, 0.884187, 0.225934, 0, 0.314337, 0.886262, 0.211669, 0, 0.329622, 0.888119, 0.198311, 0, 0.345026, 0.889709, 0.185783, 0, 0.360549, 0.891054, 0.174063, 0, 0.376189, 0.892196, 0.163143, 0, 0.391946, 0.893101, 0.152952, 0, 0.407819, 0.893803, 0.143475, 0, 0.423808, 0.894277, 0.134647, 0, 0.439914, 0.894532, 0.126434, 0, 0.456137, 0.894576, 0.1188, 0, 0.472479, 0.894393, 0.111694, 0, 0.48894, 0.893976, 0.105069, 0, 0.505523, 0.893346, 0.0989077, 0, 0.52223, 0.892502, 0.0931724, 0, 0.539064, 0.891441, 0.0878276, 0, 0.556028, 0.890276, 0.082903, 0, 0.573125, 0.888972, 0.0783505, 0, 0.590361, 0.887469, 0.0741083, 0, 0.607741, 0.885785, 0.0701633, 0, 0.62527, 0.883914, 0.0664835, 0, 0.642957, 0.881872, 0.0630567, 0, 0.660809, 0.879651, 0.0598527, 0, 0.678836, 0.877267, 0.0568615, 0, 0.69705, 0.874717, 0.05406, 0, 0.715465, 0.872012, 0.0514378, 0, 0.734098, 0.869157, 0.0489805, 0, 0.752968, 0.866155, 0.0466727, 0, 0.772101, 0.863014, 0.0445056, 0, 0.791529, 0.859748, 0.0424733, 0, 0.81129, 0.856416, 0.0405957, 0, 0.831438, 0.852958, 0.0388273, 0, 0.852044, 0.849382, 0.0371619, 0, 0.87321, 0.845694, 0.0355959, 0, 0.89509, 0.841893, 0.0341155, 0, 0.917932, 0.837981, 0.0327141, 0, 0.942204, 0.833963, 0.0313856, 0, 0.968981, 0.829847, 0.0301275, 0, 1, 1, 0.85214, 0, 0, 0.999969, 0.852095, 0, 0.00279627, 0.999483, 0.851408, 0, 0.0107635, 0.994545, 0.84579, 0, 0.0206454, 0.986188, 0.835231, 0, 0.0315756, 0.969847, 0.814687, 0, 0.0432021, 0.945951, 0.783735, 0, 0.0553396, 0.91917, 0.746074, 0, 0.0678766, 0.895488, 0.706938, 0, 0.0807395, 0.878232, 0.669534, 0, 0.0938767, 0.868252, 0.635168, 0, 0.10725, 0.863873, 0.603069, 0, 0.120832, 0.863369, 0.572514, 0, 0.134598, 0.86545, 0.543169, 0, 0.148533, 0.868803, 0.514578, 0, 0.16262, 0.872794, 0.486762, 0, 0.176849, 0.87702, 0.459811, 0, 0.19121, 0.881054, 0.433654, 0, 0.205694, 0.884974, 0.408574, 0, 0.220294, 0.888587, 0.384525, 0, 0.235005, 0.891877, 0.36156, 0, 0.24982, 0.894793, 0.339661, 0, 0.264737, 0.89743, 0.318913, 0, 0.279751, 0.899796, 0.299302, 0, 0.294859, 0.901943, 0.280843, 0, 0.310058, 0.903858, 0.263481, 0, 0.325346, 0.905574, 0.247197, 0, 0.340721, 0.907069, 0.231915, 0, 0.356181, 0.908379, 0.217614, 0, 0.371725, 0.90952, 0.20425, 0, 0.387353, 0.910483, 0.191758, 0, 0.403063, 0.91128, 0.180092, 0, 0.418854, 0.911936, 0.169222, 0, 0.434727, 0.912454, 0.159098, 0, 0.450682, 0.912835, 0.149668, 0, 0.466718, 0.913078, 0.140884, 0, 0.482837, 0.913192, 0.132709, 0, 0.499038, 0.913175, 0.125095, 0, 0.515324, 0.91304, 0.118012, 0, 0.531695, 0.912781, 0.111417, 0, 0.548153, 0.91241, 0.105281, 0, 0.5647, 0.911924, 0.0995691, 0, 0.581338, 0.911331, 0.0942531, 0, 0.59807, 0.910637, 0.0893076, 0, 0.6149, 0.90984, 0.0846998, 0, 0.63183, 0.908941, 0.0804044, 0, 0.648865, 0.907944, 0.0763984, 0, 0.666011, 0.906857, 0.0726638, 0, 0.683273, 0.90568, 0.0691783, 0, 0.700659, 0.904416, 0.0659222, 0, 0.718176, 0.903067, 0.0628782, 0, 0.735834, 0.901637, 0.0600307, 0, 0.753646, 0.900128, 0.0573647, 0, 0.771625, 0.898544, 0.0548668, 0, 0.78979, 0.89689, 0.052527, 0, 0.808162, 0.895165, 0.0503306, 0, 0.826771, 0.893371, 0.0482668, 0, 0.845654, 0.891572, 0.0463605, 0, 0.864863, 0.889763, 0.0445998, 0, 0.884472, 0.887894, 0.0429451, 0, 0.904592, 0.885967, 0.0413884, 0, 0.925407, 0.883984, 0.0399225, 0, 0.947271, 0.881945, 0.0385405, 0, 0.97105, 0.879854, 0.0372362, 0, 1, 0.999804, 0.995833, 0, 0, 0.938155, 0.933611, 0, 0.0158731, 0.864755, 0.854311, 0, 0.0317461, 0.888594, 0.865264, 0, 0.0476191, 0.905575, 0.863922, 0, 0.0634921, 0.915125, 0.850558, 0, 0.0793651, 0.920665, 0.829254, 0, 0.0952381, 0.924073, 0.802578, 0, 0.111111, 0.926304, 0.772211, 0, 0.126984, 0.927829, 0.739366, 0, 0.142857, 0.928924, 0.705033, 0, 0.15873, 0.92973, 0.670019, 0, 0.174603, 0.930339, 0.634993, 0, 0.190476, 0.930811, 0.600485, 0, 0.206349, 0.931191, 0.566897, 0, 0.222222, 0.93149, 0.534485, 0, 0.238095, 0.931737, 0.503429, 0, 0.253968, 0.931939, 0.473811, 0, 0.269841, 0.932108, 0.445668, 0, 0.285714, 0.93225, 0.418993, 0, 0.301587, 0.932371, 0.393762, 0, 0.31746, 0.932474, 0.369939, 0, 0.333333, 0.932562, 0.347479, 0, 0.349206, 0.932638, 0.326336, 0, 0.365079, 0.932703, 0.306462, 0, 0.380952, 0.93276, 0.287805, 0, 0.396825, 0.932809, 0.270313, 0, 0.412698, 0.932851, 0.253933, 0, 0.428571, 0.932887, 0.23861, 0, 0.444444, 0.932917, 0.224289, 0, 0.460317, 0.932943, 0.210917, 0, 0.47619, 0.932965, 0.19844, 0, 0.492063, 0.932982, 0.186807, 0, 0.507937, 0.932995, 0.175966, 0, 0.52381, 0.933005, 0.165869, 0, 0.539683, 0.933011, 0.156468, 0, 0.555556, 0.933013, 0.147719, 0, 0.571429, 0.933013, 0.139579, 0, 0.587302, 0.93301, 0.132007, 0, 0.603175, 0.933004, 0.124965, 0, 0.619048, 0.932994, 0.118416, 0, 0.634921, 0.932982, 0.112326, 0, 0.650794, 0.932968, 0.106663, 0, 0.666667, 0.93295, 0.101397, 0, 0.68254, 0.932931, 0.0964993, 0, 0.698413, 0.932908, 0.0919438, 0, 0.714286, 0.932883, 0.0877057, 0, 0.730159, 0.932856, 0.0837623, 0, 0.746032, 0.932827, 0.0800921, 0, 0.761905, 0.932796, 0.0766754, 0, 0.777778, 0.932762, 0.0734936, 0, 0.793651, 0.932727, 0.0705296, 0, 0.809524, 0.932689, 0.0677676, 0, 0.825397, 0.93265, 0.0651929, 0, 0.84127, 0.932609, 0.0627917, 0, 0.857143, 0.932565, 0.0605515, 0, 0.873016, 0.932521, 0.0584606, 0, 0.888889, 0.932474, 0.0565082, 0, 0.904762, 0.932427, 0.0546841, 0, 0.920635, 0.932377, 0.0529793, 0, 0.936508, 0.932326, 0.0513851, 0, 0.952381, 0.932274, 0.0498936, 0, 0.968254, 0.93222, 0.0484975, 0, 0.984127, 0.932164, 0.0471899, 0, 1]; + const ltc_float_1 = new Float32Array(LTC_MAT_1); + const ltc_float_2 = new Float32Array(LTC_MAT_2); + const LTC_FLOAT_1 = new DataTexture(ltc_float_1, 64, 64, RGBAFormat, FloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); + const LTC_FLOAT_2 = new DataTexture(ltc_float_2, 64, 64, RGBAFormat, FloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); + LTC_FLOAT_1.needsUpdate = true; + LTC_FLOAT_2.needsUpdate = true; + const ltc_half_1 = new Uint16Array(LTC_MAT_1.length); + LTC_MAT_1.forEach(function(x2, index2) { + ltc_half_1[index2] = DataUtils.toHalfFloat(x2); + }); + const ltc_half_2 = new Uint16Array(LTC_MAT_2.length); + LTC_MAT_2.forEach(function(x2, index2) { + ltc_half_2[index2] = DataUtils.toHalfFloat(x2); + }); + const LTC_HALF_1 = new DataTexture(ltc_half_1, 64, 64, RGBAFormat, HalfFloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); + const LTC_HALF_2 = new DataTexture(ltc_half_2, 64, 64, RGBAFormat, HalfFloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); + LTC_HALF_1.needsUpdate = true; + LTC_HALF_2.needsUpdate = true; + this.LTC_HALF_1 = LTC_HALF_1; + this.LTC_HALF_2 = LTC_HALF_2; + this.LTC_FLOAT_1 = LTC_FLOAT_1; + this.LTC_FLOAT_2 = LTC_FLOAT_2; + return this; + } +} +RectAreaLightTexturesLib.LTC_HALF_1 = null; +RectAreaLightTexturesLib.LTC_HALF_1 = null; +RectAreaLightTexturesLib.LTC_FLOAT_1 = null; +RectAreaLightTexturesLib.LTC_FLOAT_2 = null; +// node_modules/three/examples/jsm/lines/LineSegmentsGeometry.js +var _box2 = new Box3; +var _vector7 = new Vector3; + +// node_modules/three/examples/jsm/lines/LineMaterial.js +UniformsLib.line = { + worldUnits: { value: 1 }, + linewidth: { value: 1 }, + resolution: { value: new Vector2(1, 1) }, + dashOffset: { value: 0 }, + dashScale: { value: 1 }, + dashSize: { value: 1 }, + gapSize: { value: 1 } +}; +ShaderLib["line"] = { + uniforms: UniformsUtils.merge([ + UniformsLib.common, + UniformsLib.fog, + UniformsLib.line + ]), + vertexShader: ` + #include + #include + #include + #include + #include + + uniform float linewidth; + uniform vec2 resolution; + + attribute vec3 instanceStart; + attribute vec3 instanceEnd; + + attribute vec3 instanceColorStart; + attribute vec3 instanceColorEnd; + + #ifdef WORLD_UNITS + + varying vec4 worldPos; + varying vec3 worldStart; + varying vec3 worldEnd; + + #ifdef USE_DASH + + varying vec2 vUv; + + #endif + + #else + + varying vec2 vUv; + + #endif + + #ifdef USE_DASH + + uniform float dashScale; + attribute float instanceDistanceStart; + attribute float instanceDistanceEnd; + varying float vLineDistance; + + #endif + + void trimSegment( const in vec4 start, inout vec4 end ) { + + // trim end segment so it terminates between the camera plane and the near plane + + // conservative estimate of the near plane + float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column + float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column + float nearEstimate = - 0.5 * b / a; + + float alpha = ( nearEstimate - start.z ) / ( end.z - start.z ); + + end.xyz = mix( start.xyz, end.xyz, alpha ); + + } + + void main() { + + #ifdef USE_COLOR + + vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd; + + #endif + + #ifdef USE_DASH + + vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd; + vUv = uv; + + #endif + + float aspect = resolution.x / resolution.y; + + // camera space + vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 ); + vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 ); + + #ifdef WORLD_UNITS + + worldStart = start.xyz; + worldEnd = end.xyz; + + #else + + vUv = uv; + + #endif + + // special case for perspective projection, and segments that terminate either in, or behind, the camera plane + // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space + // but we need to perform ndc-space calculations in the shader, so we must address this issue directly + // perhaps there is a more elegant solution -- WestLangley + + bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column + + if ( perspective ) { + + if ( start.z < 0.0 && end.z >= 0.0 ) { + + trimSegment( start, end ); + + } else if ( end.z < 0.0 && start.z >= 0.0 ) { + + trimSegment( end, start ); + + } + + } + + // clip space + vec4 clipStart = projectionMatrix * start; + vec4 clipEnd = projectionMatrix * end; + + // ndc space + vec3 ndcStart = clipStart.xyz / clipStart.w; + vec3 ndcEnd = clipEnd.xyz / clipEnd.w; + + // direction + vec2 dir = ndcEnd.xy - ndcStart.xy; + + // account for clip-space aspect ratio + dir.x *= aspect; + dir = normalize( dir ); + + #ifdef WORLD_UNITS + + vec3 worldDir = normalize( end.xyz - start.xyz ); + vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) ); + vec3 worldUp = normalize( cross( worldDir, tmpFwd ) ); + vec3 worldFwd = cross( worldDir, worldUp ); + worldPos = position.y < 0.5 ? start: end; + + // height offset + float hw = linewidth * 0.5; + worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp; + + // don't extend the line if we're rendering dashes because we + // won't be rendering the endcaps + #ifndef USE_DASH + + // cap extension + worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir; + + // add width to the box + worldPos.xyz += worldFwd * hw; + + // endcaps + if ( position.y > 1.0 || position.y < 0.0 ) { + + worldPos.xyz -= worldFwd * 2.0 * hw; + + } + + #endif + + // project the worldpos + vec4 clip = projectionMatrix * worldPos; + + // shift the depth of the projected points so the line + // segments overlap neatly + vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd; + clip.z = clipPose.z * clip.w; + + #else + + vec2 offset = vec2( dir.y, - dir.x ); + // undo aspect ratio adjustment + dir.x /= aspect; + offset.x /= aspect; + + // sign flip + if ( position.x < 0.0 ) offset *= - 1.0; + + // endcaps + if ( position.y < 0.0 ) { + + offset += - dir; + + } else if ( position.y > 1.0 ) { + + offset += dir; + + } + + // adjust for linewidth + offset *= linewidth; + + // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ... + offset /= resolution.y; + + // select end + vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd; + + // back to clip space + offset *= clip.w; + + clip.xy += offset; + + #endif + + gl_Position = clip; + + vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation + + #include + #include + #include + + } + `, + fragmentShader: ` + uniform vec3 diffuse; + uniform float opacity; + uniform float linewidth; + + #ifdef USE_DASH + + uniform float dashOffset; + uniform float dashSize; + uniform float gapSize; + + #endif + + varying float vLineDistance; + + #ifdef WORLD_UNITS + + varying vec4 worldPos; + varying vec3 worldStart; + varying vec3 worldEnd; + + #ifdef USE_DASH + + varying vec2 vUv; + + #endif + + #else + + varying vec2 vUv; + + #endif + + #include + #include + #include + #include + #include + + vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) { + + float mua; + float mub; + + vec3 p13 = p1 - p3; + vec3 p43 = p4 - p3; + + vec3 p21 = p2 - p1; + + float d1343 = dot( p13, p43 ); + float d4321 = dot( p43, p21 ); + float d1321 = dot( p13, p21 ); + float d4343 = dot( p43, p43 ); + float d2121 = dot( p21, p21 ); + + float denom = d2121 * d4343 - d4321 * d4321; + + float numer = d1343 * d4321 - d1321 * d4343; + + mua = numer / denom; + mua = clamp( mua, 0.0, 1.0 ); + mub = ( d1343 + d4321 * ( mua ) ) / d4343; + mub = clamp( mub, 0.0, 1.0 ); + + return vec2( mua, mub ); + + } + + void main() { + + #include + + #ifdef USE_DASH + + if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps + + if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX + + #endif + + float alpha = opacity; + + #ifdef WORLD_UNITS + + // Find the closest points on the view ray and the line segment + vec3 rayEnd = normalize( worldPos.xyz ) * 1e5; + vec3 lineDir = worldEnd - worldStart; + vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd ); + + vec3 p1 = worldStart + lineDir * params.x; + vec3 p2 = rayEnd * params.y; + vec3 delta = p1 - p2; + float len = length( delta ); + float norm = len / linewidth; + + #ifndef USE_DASH + + #ifdef USE_ALPHA_TO_COVERAGE + + float dnorm = fwidth( norm ); + alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm ); + + #else + + if ( norm > 0.5 ) { + + discard; + + } + + #endif + + #endif + + #else + + #ifdef USE_ALPHA_TO_COVERAGE + + // artifacts appear on some hardware if a derivative is taken within a conditional + float a = vUv.x; + float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; + float len2 = a * a + b * b; + float dlen = fwidth( len2 ); + + if ( abs( vUv.y ) > 1.0 ) { + + alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 ); + + } + + #else + + if ( abs( vUv.y ) > 1.0 ) { + + float a = vUv.x; + float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; + float len2 = a * a + b * b; + + if ( len2 > 1.0 ) discard; + + } + + #endif + + #endif + + vec4 diffuseColor = vec4( diffuse, alpha ); + + #include + #include + + gl_FragColor = vec4( diffuseColor.rgb, alpha ); + + #include + #include + #include + #include + + } + ` +}; + +// node_modules/three/examples/jsm/lines/LineSegments2.js +var _viewport = new Vector4; +var _start2 = new Vector3; +var _end2 = new Vector3; +var _start4 = new Vector4; +var _end4 = new Vector4; +var _ssOrigin = new Vector4; +var _ssOrigin3 = new Vector3; +var _mvMatrix = new Matrix4; +var _line = new Line3; +var _closestPoint2 = new Vector3; +var _box4 = new Box3; +var _sphere2 = new Sphere; +var _clipToWorldVector = new Vector4; +// node_modules/three/examples/jsm/lines/Wireframe.js +var _start3 = new Vector3; +var _end3 = new Vector3; +var _viewport2 = new Vector4; +// node_modules/three/examples/jsm/loaders/3DMLoader.js +var _taskCache = new WeakMap; +// node_modules/three/examples/jsm/loaders/DRACOLoader.js +var _taskCache2 = new WeakMap; +// node_modules/three/examples/jsm/loaders/FBXLoader.js +var tempEuler = new Euler; +var tempVec = new Vector3; +// node_modules/three/examples/jsm/loaders/GLTFLoader.js +class GLTFLoader extends Loader { + constructor(manager) { + super(manager); + this.dracoLoader = null; + this.ktx2Loader = null; + this.meshoptDecoder = null; + this.pluginCallbacks = []; + this.register(function(parser) { + return new GLTFMaterialsClearcoatExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsDispersionExtension2(parser); + }); + this.register(function(parser) { + return new GLTFTextureBasisUExtension(parser); + }); + this.register(function(parser) { + return new GLTFTextureWebPExtension(parser); + }); + this.register(function(parser) { + return new GLTFTextureAVIFExtension(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsSheenExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsTransmissionExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsVolumeExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsIorExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsEmissiveStrengthExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsSpecularExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsIridescenceExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsAnisotropyExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsBumpExtension2(parser); + }); + this.register(function(parser) { + return new GLTFLightsExtension(parser); + }); + this.register(function(parser) { + return new GLTFMeshoptCompression(parser); + }); + this.register(function(parser) { + return new GLTFMeshGpuInstancing2(parser); + }); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + let resourcePath; + if (this.resourcePath !== "") { + resourcePath = this.resourcePath; + } else if (this.path !== "") { + const relativeUrl = LoaderUtils.extractUrlBase(url); + resourcePath = LoaderUtils.resolveURL(relativeUrl, this.path); + } else { + resourcePath = LoaderUtils.extractUrlBase(url); + } + this.manager.itemStart(url); + const _onError = function(e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(data2) { + try { + scope.parse(data2, resourcePath, function(gltf) { + onLoad(gltf); + scope.manager.itemEnd(url); + }, _onError); + } catch (e) { + _onError(e); + } + }, onProgress, _onError); + } + setDRACOLoader(dracoLoader) { + this.dracoLoader = dracoLoader; + return this; + } + setKTX2Loader(ktx2Loader) { + this.ktx2Loader = ktx2Loader; + return this; + } + setMeshoptDecoder(meshoptDecoder) { + this.meshoptDecoder = meshoptDecoder; + return this; + } + register(callback) { + if (this.pluginCallbacks.indexOf(callback) === -1) { + this.pluginCallbacks.push(callback); + } + return this; + } + unregister(callback) { + if (this.pluginCallbacks.indexOf(callback) !== -1) { + this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); + } + return this; + } + parse(data2, path, onLoad, onError) { + let json; + const extensions = {}; + const plugins = {}; + const textDecoder = new TextDecoder; + if (typeof data2 === "string") { + json = JSON.parse(data2); + } else if (data2 instanceof ArrayBuffer) { + const magic = textDecoder.decode(new Uint8Array(data2, 0, 4)); + if (magic === BINARY_EXTENSION_HEADER_MAGIC) { + try { + extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data2); + } catch (error) { + if (onError) + onError(error); + return; + } + json = JSON.parse(extensions[EXTENSIONS.KHR_BINARY_GLTF].content); + } else { + json = JSON.parse(textDecoder.decode(data2)); + } + } else { + json = data2; + } + if (json.asset === undefined || json.asset.version[0] < 2) { + if (onError) + onError(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")); + return; + } + const parser = new GLTFParser(json, { + path: path || this.resourcePath || "", + crossOrigin: this.crossOrigin, + requestHeader: this.requestHeader, + manager: this.manager, + ktx2Loader: this.ktx2Loader, + meshoptDecoder: this.meshoptDecoder + }); + parser.fileLoader.setRequestHeader(this.requestHeader); + for (let i = 0;i < this.pluginCallbacks.length; i++) { + const plugin = this.pluginCallbacks[i](parser); + if (!plugin.name) + console.error("THREE.GLTFLoader: Invalid plugin found: missing name"); + plugins[plugin.name] = plugin; + extensions[plugin.name] = true; + } + if (json.extensionsUsed) { + for (let i = 0;i < json.extensionsUsed.length; ++i) { + const extensionName = json.extensionsUsed[i]; + const extensionsRequired = json.extensionsRequired || []; + switch (extensionName) { + case EXTENSIONS.KHR_MATERIALS_UNLIT: + extensions[extensionName] = new GLTFMaterialsUnlitExtension2; + break; + case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: + extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader); + break; + case EXTENSIONS.KHR_TEXTURE_TRANSFORM: + extensions[extensionName] = new GLTFTextureTransformExtension; + break; + case EXTENSIONS.KHR_MESH_QUANTIZATION: + extensions[extensionName] = new GLTFMeshQuantizationExtension; + break; + default: + if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === undefined) { + console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".'); + } + } + } + } + parser.setExtensions(extensions); + parser.setPlugins(plugins); + parser.parse(onLoad, onError); + } + parseAsync(data2, path) { + const scope = this; + return new Promise(function(resolve, reject2) { + scope.parse(data2, path, resolve, reject2); + }); + } +} +function GLTFRegistry() { + let objects = {}; + return { + get: function(key2) { + return objects[key2]; + }, + add: function(key2, object) { + objects[key2] = object; + }, + remove: function(key2) { + delete objects[key2]; + }, + removeAll: function() { + objects = {}; + } + }; +} +var EXTENSIONS = { + KHR_BINARY_GLTF: "KHR_binary_glTF", + KHR_DRACO_MESH_COMPRESSION: "KHR_draco_mesh_compression", + KHR_LIGHTS_PUNCTUAL: "KHR_lights_punctual", + KHR_MATERIALS_CLEARCOAT: "KHR_materials_clearcoat", + KHR_MATERIALS_DISPERSION: "KHR_materials_dispersion", + KHR_MATERIALS_IOR: "KHR_materials_ior", + KHR_MATERIALS_SHEEN: "KHR_materials_sheen", + KHR_MATERIALS_SPECULAR: "KHR_materials_specular", + KHR_MATERIALS_TRANSMISSION: "KHR_materials_transmission", + KHR_MATERIALS_IRIDESCENCE: "KHR_materials_iridescence", + KHR_MATERIALS_ANISOTROPY: "KHR_materials_anisotropy", + KHR_MATERIALS_UNLIT: "KHR_materials_unlit", + KHR_MATERIALS_VOLUME: "KHR_materials_volume", + KHR_TEXTURE_BASISU: "KHR_texture_basisu", + KHR_TEXTURE_TRANSFORM: "KHR_texture_transform", + KHR_MESH_QUANTIZATION: "KHR_mesh_quantization", + KHR_MATERIALS_EMISSIVE_STRENGTH: "KHR_materials_emissive_strength", + EXT_MATERIALS_BUMP: "EXT_materials_bump", + EXT_TEXTURE_WEBP: "EXT_texture_webp", + EXT_TEXTURE_AVIF: "EXT_texture_avif", + EXT_MESHOPT_COMPRESSION: "EXT_meshopt_compression", + EXT_MESH_GPU_INSTANCING: "EXT_mesh_gpu_instancing" +}; + +class GLTFLightsExtension { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; + this.cache = { refs: {}, uses: {} }; + } + _markDefs() { + const parser = this.parser; + const nodeDefs = this.parser.json.nodes || []; + for (let nodeIndex = 0, nodeLength = nodeDefs.length;nodeIndex < nodeLength; nodeIndex++) { + const nodeDef = nodeDefs[nodeIndex]; + if (nodeDef.extensions && nodeDef.extensions[this.name] && nodeDef.extensions[this.name].light !== undefined) { + parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light); + } + } + } + _loadLight(lightIndex) { + const parser = this.parser; + const cacheKey = "light:" + lightIndex; + let dependency = parser.cache.get(cacheKey); + if (dependency) + return dependency; + const json = parser.json; + const extensions = json.extensions && json.extensions[this.name] || {}; + const lightDefs = extensions.lights || []; + const lightDef = lightDefs[lightIndex]; + let lightNode; + const color = new Color(16777215); + if (lightDef.color !== undefined) + color.setRGB(lightDef.color[0], lightDef.color[1], lightDef.color[2], LinearSRGBColorSpace); + const range = lightDef.range !== undefined ? lightDef.range : 0; + switch (lightDef.type) { + case "directional": + lightNode = new DirectionalLight(color); + lightNode.target.position.set(0, 0, -1); + lightNode.add(lightNode.target); + break; + case "point": + lightNode = new PointLight(color); + lightNode.distance = range; + break; + case "spot": + lightNode = new SpotLight(color); + lightNode.distance = range; + lightDef.spot = lightDef.spot || {}; + lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0; + lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4; + lightNode.angle = lightDef.spot.outerConeAngle; + lightNode.penumbra = 1 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle; + lightNode.target.position.set(0, 0, -1); + lightNode.add(lightNode.target); + break; + default: + throw new Error("THREE.GLTFLoader: Unexpected light type: " + lightDef.type); + } + lightNode.position.set(0, 0, 0); + assignExtrasToUserData(lightNode, lightDef); + if (lightDef.intensity !== undefined) + lightNode.intensity = lightDef.intensity; + lightNode.name = parser.createUniqueName(lightDef.name || "light_" + lightIndex); + dependency = Promise.resolve(lightNode); + parser.cache.add(cacheKey, dependency); + return dependency; + } + getDependency(type, index2) { + if (type !== "light") + return; + return this._loadLight(index2); + } + createNodeAttachment(nodeIndex) { + const self2 = this; + const parser = this.parser; + const json = parser.json; + const nodeDef = json.nodes[nodeIndex]; + const lightDef = nodeDef.extensions && nodeDef.extensions[this.name] || {}; + const lightIndex = lightDef.light; + if (lightIndex === undefined) + return null; + return this._loadLight(lightIndex).then(function(light) { + return parser._getNodeRef(self2.cache, lightIndex, light); + }); + } +} + +class GLTFMaterialsUnlitExtension2 { + constructor() { + this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; + } + getMaterialType() { + return MeshBasicMaterial; + } + extendParams(materialParams, materialDef, parser) { + const pending = []; + materialParams.color = new Color(1, 1, 1); + materialParams.opacity = 1; + const metallicRoughness = materialDef.pbrMetallicRoughness; + if (metallicRoughness) { + if (Array.isArray(metallicRoughness.baseColorFactor)) { + const array = metallicRoughness.baseColorFactor; + materialParams.color.setRGB(array[0], array[1], array[2], LinearSRGBColorSpace); + materialParams.opacity = array[3]; + } + if (metallicRoughness.baseColorTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, SRGBColorSpace)); + } + } + return Promise.all(pending); + } +} + +class GLTFMaterialsEmissiveStrengthExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const emissiveStrength = materialDef.extensions[this.name].emissiveStrength; + if (emissiveStrength !== undefined) { + materialParams.emissiveIntensity = emissiveStrength; + } + return Promise.resolve(); + } +} + +class GLTFMaterialsClearcoatExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + if (extension.clearcoatFactor !== undefined) { + materialParams.clearcoat = extension.clearcoatFactor; + } + if (extension.clearcoatTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "clearcoatMap", extension.clearcoatTexture)); + } + if (extension.clearcoatRoughnessFactor !== undefined) { + materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor; + } + if (extension.clearcoatRoughnessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "clearcoatRoughnessMap", extension.clearcoatRoughnessTexture)); + } + if (extension.clearcoatNormalTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "clearcoatNormalMap", extension.clearcoatNormalTexture)); + if (extension.clearcoatNormalTexture.scale !== undefined) { + const scale2 = extension.clearcoatNormalTexture.scale; + materialParams.clearcoatNormalScale = new Vector2(scale2, scale2); + } + } + return Promise.all(pending); + } +} + +class GLTFMaterialsDispersionExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_DISPERSION; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const extension = materialDef.extensions[this.name]; + materialParams.dispersion = extension.dispersion !== undefined ? extension.dispersion : 0; + return Promise.resolve(); + } +} + +class GLTFMaterialsIridescenceExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + if (extension.iridescenceFactor !== undefined) { + materialParams.iridescence = extension.iridescenceFactor; + } + if (extension.iridescenceTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "iridescenceMap", extension.iridescenceTexture)); + } + if (extension.iridescenceIor !== undefined) { + materialParams.iridescenceIOR = extension.iridescenceIor; + } + if (materialParams.iridescenceThicknessRange === undefined) { + materialParams.iridescenceThicknessRange = [100, 400]; + } + if (extension.iridescenceThicknessMinimum !== undefined) { + materialParams.iridescenceThicknessRange[0] = extension.iridescenceThicknessMinimum; + } + if (extension.iridescenceThicknessMaximum !== undefined) { + materialParams.iridescenceThicknessRange[1] = extension.iridescenceThicknessMaximum; + } + if (extension.iridescenceThicknessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "iridescenceThicknessMap", extension.iridescenceThicknessTexture)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsSheenExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_SHEEN; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + materialParams.sheenColor = new Color(0, 0, 0); + materialParams.sheenRoughness = 0; + materialParams.sheen = 1; + const extension = materialDef.extensions[this.name]; + if (extension.sheenColorFactor !== undefined) { + const colorFactor = extension.sheenColorFactor; + materialParams.sheenColor.setRGB(colorFactor[0], colorFactor[1], colorFactor[2], LinearSRGBColorSpace); + } + if (extension.sheenRoughnessFactor !== undefined) { + materialParams.sheenRoughness = extension.sheenRoughnessFactor; + } + if (extension.sheenColorTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "sheenColorMap", extension.sheenColorTexture, SRGBColorSpace)); + } + if (extension.sheenRoughnessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "sheenRoughnessMap", extension.sheenRoughnessTexture)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsTransmissionExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + if (extension.transmissionFactor !== undefined) { + materialParams.transmission = extension.transmissionFactor; + } + if (extension.transmissionTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "transmissionMap", extension.transmissionTexture)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsVolumeExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_VOLUME; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0; + if (extension.thicknessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "thicknessMap", extension.thicknessTexture)); + } + materialParams.attenuationDistance = extension.attenuationDistance || Infinity; + const colorArray = extension.attenuationColor || [1, 1, 1]; + materialParams.attenuationColor = new Color().setRGB(colorArray[0], colorArray[1], colorArray[2], LinearSRGBColorSpace); + return Promise.all(pending); + } +} + +class GLTFMaterialsIorExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_IOR; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const extension = materialDef.extensions[this.name]; + materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5; + return Promise.resolve(); + } +} + +class GLTFMaterialsSpecularExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1; + if (extension.specularTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "specularIntensityMap", extension.specularTexture)); + } + const colorArray = extension.specularColorFactor || [1, 1, 1]; + materialParams.specularColor = new Color().setRGB(colorArray[0], colorArray[1], colorArray[2], LinearSRGBColorSpace); + if (extension.specularColorTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "specularColorMap", extension.specularColorTexture, SRGBColorSpace)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsBumpExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.EXT_MATERIALS_BUMP; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + materialParams.bumpScale = extension.bumpFactor !== undefined ? extension.bumpFactor : 1; + if (extension.bumpTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "bumpMap", extension.bumpTexture)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsAnisotropyExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + if (extension.anisotropyStrength !== undefined) { + materialParams.anisotropy = extension.anisotropyStrength; + } + if (extension.anisotropyRotation !== undefined) { + materialParams.anisotropyRotation = extension.anisotropyRotation; + } + if (extension.anisotropyTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "anisotropyMap", extension.anisotropyTexture)); + } + return Promise.all(pending); + } +} + +class GLTFTextureBasisUExtension { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_TEXTURE_BASISU; + } + loadTexture(textureIndex) { + const parser = this.parser; + const json = parser.json; + const textureDef = json.textures[textureIndex]; + if (!textureDef.extensions || !textureDef.extensions[this.name]) { + return null; + } + const extension = textureDef.extensions[this.name]; + const loader = parser.options.ktx2Loader; + if (!loader) { + if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) { + throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures"); + } else { + return null; + } + } + return parser.loadTextureImage(textureIndex, extension.source, loader); + } +} + +class GLTFTextureWebPExtension { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.EXT_TEXTURE_WEBP; + this.isSupported = null; + } + loadTexture(textureIndex) { + const name2 = this.name; + const parser = this.parser; + const json = parser.json; + const textureDef = json.textures[textureIndex]; + if (!textureDef.extensions || !textureDef.extensions[name2]) { + return null; + } + const extension = textureDef.extensions[name2]; + const source = json.images[extension.source]; + let loader = parser.textureLoader; + if (source.uri) { + const handler = parser.options.manager.getHandler(source.uri); + if (handler !== null) + loader = handler; + } + return this.detectSupport().then(function(isSupported) { + if (isSupported) + return parser.loadTextureImage(textureIndex, extension.source, loader); + if (json.extensionsRequired && json.extensionsRequired.indexOf(name2) >= 0) { + throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported."); + } + return parser.loadTexture(textureIndex); + }); + } + detectSupport() { + if (!this.isSupported) { + this.isSupported = new Promise(function(resolve) { + const image = new Image; + image.src = "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA"; + image.onload = image.onerror = function() { + resolve(image.height === 1); + }; + }); + } + return this.isSupported; + } +} + +class GLTFTextureAVIFExtension { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.EXT_TEXTURE_AVIF; + this.isSupported = null; + } + loadTexture(textureIndex) { + const name2 = this.name; + const parser = this.parser; + const json = parser.json; + const textureDef = json.textures[textureIndex]; + if (!textureDef.extensions || !textureDef.extensions[name2]) { + return null; + } + const extension = textureDef.extensions[name2]; + const source = json.images[extension.source]; + let loader = parser.textureLoader; + if (source.uri) { + const handler = parser.options.manager.getHandler(source.uri); + if (handler !== null) + loader = handler; + } + return this.detectSupport().then(function(isSupported) { + if (isSupported) + return parser.loadTextureImage(textureIndex, extension.source, loader); + if (json.extensionsRequired && json.extensionsRequired.indexOf(name2) >= 0) { + throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported."); + } + return parser.loadTexture(textureIndex); + }); + } + detectSupport() { + if (!this.isSupported) { + this.isSupported = new Promise(function(resolve) { + const image = new Image; + image.src = "data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI="; + image.onload = image.onerror = function() { + resolve(image.height === 1); + }; + }); + } + return this.isSupported; + } +} + +class GLTFMeshoptCompression { + constructor(parser) { + this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION; + this.parser = parser; + } + loadBufferView(index2) { + const json = this.parser.json; + const bufferView = json.bufferViews[index2]; + if (bufferView.extensions && bufferView.extensions[this.name]) { + const extensionDef = bufferView.extensions[this.name]; + const buffer = this.parser.getDependency("buffer", extensionDef.buffer); + const decoder = this.parser.options.meshoptDecoder; + if (!decoder || !decoder.supported) { + if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) { + throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files"); + } else { + return null; + } + } + return buffer.then(function(res) { + const byteOffset = extensionDef.byteOffset || 0; + const byteLength = extensionDef.byteLength || 0; + const count = extensionDef.count; + const stride = extensionDef.byteStride; + const source = new Uint8Array(res, byteOffset, byteLength); + if (decoder.decodeGltfBufferAsync) { + return decoder.decodeGltfBufferAsync(count, stride, source, extensionDef.mode, extensionDef.filter).then(function(res2) { + return res2.buffer; + }); + } else { + return decoder.ready.then(function() { + const result = new ArrayBuffer(count * stride); + decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter); + return result; + }); + } + }); + } else { + return null; + } + } +} + +class GLTFMeshGpuInstancing2 { + constructor(parser) { + this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING; + this.parser = parser; + } + createNodeMesh(nodeIndex) { + const json = this.parser.json; + const nodeDef = json.nodes[nodeIndex]; + if (!nodeDef.extensions || !nodeDef.extensions[this.name] || nodeDef.mesh === undefined) { + return null; + } + const meshDef = json.meshes[nodeDef.mesh]; + for (const primitive of meshDef.primitives) { + if (primitive.mode !== WEBGL_CONSTANTS2.TRIANGLES && primitive.mode !== WEBGL_CONSTANTS2.TRIANGLE_STRIP && primitive.mode !== WEBGL_CONSTANTS2.TRIANGLE_FAN && primitive.mode !== undefined) { + return null; + } + } + const extensionDef = nodeDef.extensions[this.name]; + const attributesDef = extensionDef.attributes; + const pending = []; + const attributes = {}; + for (const key2 in attributesDef) { + pending.push(this.parser.getDependency("accessor", attributesDef[key2]).then((accessor) => { + attributes[key2] = accessor; + return attributes[key2]; + })); + } + if (pending.length < 1) { + return null; + } + pending.push(this.parser.createNodeMesh(nodeIndex)); + return Promise.all(pending).then((results) => { + const nodeObject = results.pop(); + const meshes = nodeObject.isGroup ? nodeObject.children : [nodeObject]; + const count = results[0].count; + const instancedMeshes = []; + for (const mesh of meshes) { + const m = new Matrix4; + const p = new Vector3; + const q2 = new Quaternion; + const s = new Vector3(1, 1, 1); + const instancedMesh = new InstancedMesh(mesh.geometry, mesh.material, count); + for (let i = 0;i < count; i++) { + if (attributes.TRANSLATION) { + p.fromBufferAttribute(attributes.TRANSLATION, i); + } + if (attributes.ROTATION) { + q2.fromBufferAttribute(attributes.ROTATION, i); + } + if (attributes.SCALE) { + s.fromBufferAttribute(attributes.SCALE, i); + } + instancedMesh.setMatrixAt(i, m.compose(p, q2, s)); + } + for (const attributeName in attributes) { + if (attributeName === "_COLOR_0") { + const attr = attributes[attributeName]; + instancedMesh.instanceColor = new InstancedBufferAttribute(attr.array, attr.itemSize, attr.normalized); + } else if (attributeName !== "TRANSLATION" && attributeName !== "ROTATION" && attributeName !== "SCALE") { + mesh.geometry.setAttribute(attributeName, attributes[attributeName]); + } + } + Object3D.prototype.copy.call(instancedMesh, mesh); + this.parser.assignFinalMaterial(instancedMesh); + instancedMeshes.push(instancedMesh); + } + if (nodeObject.isGroup) { + nodeObject.clear(); + nodeObject.add(...instancedMeshes); + return nodeObject; + } + return instancedMeshes[0]; + }); + } +} +var BINARY_EXTENSION_HEADER_MAGIC = "glTF"; +var BINARY_EXTENSION_HEADER_LENGTH = 12; +var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 1313821514, BIN: 5130562 }; + +class GLTFBinaryExtension { + constructor(data2) { + this.name = EXTENSIONS.KHR_BINARY_GLTF; + this.content = null; + this.body = null; + const headerView = new DataView(data2, 0, BINARY_EXTENSION_HEADER_LENGTH); + const textDecoder = new TextDecoder; + this.header = { + magic: textDecoder.decode(new Uint8Array(data2.slice(0, 4))), + version: headerView.getUint32(4, true), + length: headerView.getUint32(8, true) + }; + if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) { + throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header."); + } else if (this.header.version < 2) { + throw new Error("THREE.GLTFLoader: Legacy binary file detected."); + } + const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH; + const chunkView = new DataView(data2, BINARY_EXTENSION_HEADER_LENGTH); + let chunkIndex = 0; + while (chunkIndex < chunkContentsLength) { + const chunkLength = chunkView.getUint32(chunkIndex, true); + chunkIndex += 4; + const chunkType = chunkView.getUint32(chunkIndex, true); + chunkIndex += 4; + if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) { + const contentArray = new Uint8Array(data2, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength); + this.content = textDecoder.decode(contentArray); + } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) { + const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; + this.body = data2.slice(byteOffset, byteOffset + chunkLength); + } + chunkIndex += chunkLength; + } + if (this.content === null) { + throw new Error("THREE.GLTFLoader: JSON content not found."); + } + } +} + +class GLTFDracoMeshCompressionExtension { + constructor(json, dracoLoader) { + if (!dracoLoader) { + throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided."); + } + this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; + this.json = json; + this.dracoLoader = dracoLoader; + this.dracoLoader.preload(); + } + decodePrimitive(primitive, parser) { + const json = this.json; + const dracoLoader = this.dracoLoader; + const bufferViewIndex = primitive.extensions[this.name].bufferView; + const gltfAttributeMap = primitive.extensions[this.name].attributes; + const threeAttributeMap = {}; + const attributeNormalizedMap = {}; + const attributeTypeMap = {}; + for (const attributeName in gltfAttributeMap) { + const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); + threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName]; + } + for (const attributeName in primitive.attributes) { + const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); + if (gltfAttributeMap[attributeName] !== undefined) { + const accessorDef = json.accessors[primitive.attributes[attributeName]]; + const componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; + attributeTypeMap[threeAttributeName] = componentType.name; + attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true; + } + } + return parser.getDependency("bufferView", bufferViewIndex).then(function(bufferView) { + return new Promise(function(resolve, reject2) { + dracoLoader.decodeDracoFile(bufferView, function(geometry) { + for (const attributeName in geometry.attributes) { + const attribute = geometry.attributes[attributeName]; + const normalized = attributeNormalizedMap[attributeName]; + if (normalized !== undefined) + attribute.normalized = normalized; + } + resolve(geometry); + }, threeAttributeMap, attributeTypeMap, LinearSRGBColorSpace, reject2); + }); + }); + } +} + +class GLTFTextureTransformExtension { + constructor() { + this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; + } + extendTexture(texture, transform2) { + if ((transform2.texCoord === undefined || transform2.texCoord === texture.channel) && transform2.offset === undefined && transform2.rotation === undefined && transform2.scale === undefined) { + return texture; + } + texture = texture.clone(); + if (transform2.texCoord !== undefined) { + texture.channel = transform2.texCoord; + } + if (transform2.offset !== undefined) { + texture.offset.fromArray(transform2.offset); + } + if (transform2.rotation !== undefined) { + texture.rotation = transform2.rotation; + } + if (transform2.scale !== undefined) { + texture.repeat.fromArray(transform2.scale); + } + texture.needsUpdate = true; + return texture; + } +} + +class GLTFMeshQuantizationExtension { + constructor() { + this.name = EXTENSIONS.KHR_MESH_QUANTIZATION; + } +} + +class GLTFCubicSplineInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + copySampleValue_(index2) { + const result = this.resultBuffer, values2 = this.sampleValues, valueSize = this.valueSize, offset = index2 * valueSize * 3 + valueSize; + for (let i = 0;i !== valueSize; i++) { + result[i] = values2[offset + i]; + } + return result; + } + interpolate_(i1, t0, t2, t1) { + const result = this.resultBuffer; + const values2 = this.sampleValues; + const stride = this.valueSize; + const stride2 = stride * 2; + const stride3 = stride * 3; + const td2 = t1 - t0; + const p = (t2 - t0) / td2; + const pp = p * p; + const ppp = pp * p; + const offset1 = i1 * stride3; + const offset0 = offset1 - stride3; + const s2 = -2 * ppp + 3 * pp; + const s3 = ppp - pp; + const s0 = 1 - s2; + const s1 = s3 - pp + p; + for (let i = 0;i !== stride; i++) { + const p0 = values2[offset0 + i + stride]; + const m0 = values2[offset0 + i + stride2] * td2; + const p1 = values2[offset1 + i + stride]; + const m1 = values2[offset1 + i] * td2; + result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; + } + return result; + } +} +var _q2 = new Quaternion; + +class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant { + interpolate_(i1, t0, t2, t1) { + const result = super.interpolate_(i1, t0, t2, t1); + _q2.fromArray(result).normalize().toArray(result); + return result; + } +} +var WEBGL_CONSTANTS2 = { + FLOAT: 5126, + FLOAT_MAT3: 35675, + FLOAT_MAT4: 35676, + FLOAT_VEC2: 35664, + FLOAT_VEC3: 35665, + FLOAT_VEC4: 35666, + LINEAR: 9729, + REPEAT: 10497, + SAMPLER_2D: 35678, + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6, + UNSIGNED_BYTE: 5121, + UNSIGNED_SHORT: 5123 +}; +var WEBGL_COMPONENT_TYPES = { + 5120: Int8Array, + 5121: Uint8Array, + 5122: Int16Array, + 5123: Uint16Array, + 5125: Uint32Array, + 5126: Float32Array +}; +var WEBGL_FILTERS = { + 9728: NearestFilter, + 9729: LinearFilter, + 9984: NearestMipmapNearestFilter, + 9985: LinearMipmapNearestFilter, + 9986: NearestMipmapLinearFilter, + 9987: LinearMipmapLinearFilter +}; +var WEBGL_WRAPPINGS = { + 33071: ClampToEdgeWrapping, + 33648: MirroredRepeatWrapping, + 10497: RepeatWrapping +}; +var WEBGL_TYPE_SIZES = { + SCALAR: 1, + VEC2: 2, + VEC3: 3, + VEC4: 4, + MAT2: 4, + MAT3: 9, + MAT4: 16 +}; +var ATTRIBUTES = { + POSITION: "position", + NORMAL: "normal", + TANGENT: "tangent", + TEXCOORD_0: "uv", + TEXCOORD_1: "uv1", + TEXCOORD_2: "uv2", + TEXCOORD_3: "uv3", + COLOR_0: "color", + WEIGHTS_0: "skinWeight", + JOINTS_0: "skinIndex" +}; +var PATH_PROPERTIES2 = { + scale: "scale", + translation: "position", + rotation: "quaternion", + weights: "morphTargetInfluences" +}; +var INTERPOLATION = { + CUBICSPLINE: undefined, + LINEAR: InterpolateLinear, + STEP: InterpolateDiscrete +}; +var ALPHA_MODES = { + OPAQUE: "OPAQUE", + MASK: "MASK", + BLEND: "BLEND" +}; +function createDefaultMaterial(cache) { + if (cache["DefaultMaterial"] === undefined) { + cache["DefaultMaterial"] = new MeshStandardMaterial({ + color: 16777215, + emissive: 0, + metalness: 1, + roughness: 1, + transparent: false, + depthTest: true, + side: FrontSide + }); + } + return cache["DefaultMaterial"]; +} +function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) { + for (const name2 in objectDef.extensions) { + if (knownExtensions[name2] === undefined) { + object.userData.gltfExtensions = object.userData.gltfExtensions || {}; + object.userData.gltfExtensions[name2] = objectDef.extensions[name2]; + } + } +} +function assignExtrasToUserData(object, gltfDef) { + if (gltfDef.extras !== undefined) { + if (typeof gltfDef.extras === "object") { + Object.assign(object.userData, gltfDef.extras); + } else { + console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, " + gltfDef.extras); + } + } +} +function addMorphTargets(geometry, targets, parser) { + let hasMorphPosition = false; + let hasMorphNormal = false; + let hasMorphColor = false; + for (let i = 0, il = targets.length;i < il; i++) { + const target = targets[i]; + if (target.POSITION !== undefined) + hasMorphPosition = true; + if (target.NORMAL !== undefined) + hasMorphNormal = true; + if (target.COLOR_0 !== undefined) + hasMorphColor = true; + if (hasMorphPosition && hasMorphNormal && hasMorphColor) + break; + } + if (!hasMorphPosition && !hasMorphNormal && !hasMorphColor) + return Promise.resolve(geometry); + const pendingPositionAccessors = []; + const pendingNormalAccessors = []; + const pendingColorAccessors = []; + for (let i = 0, il = targets.length;i < il; i++) { + const target = targets[i]; + if (hasMorphPosition) { + const pendingAccessor = target.POSITION !== undefined ? parser.getDependency("accessor", target.POSITION) : geometry.attributes.position; + pendingPositionAccessors.push(pendingAccessor); + } + if (hasMorphNormal) { + const pendingAccessor = target.NORMAL !== undefined ? parser.getDependency("accessor", target.NORMAL) : geometry.attributes.normal; + pendingNormalAccessors.push(pendingAccessor); + } + if (hasMorphColor) { + const pendingAccessor = target.COLOR_0 !== undefined ? parser.getDependency("accessor", target.COLOR_0) : geometry.attributes.color; + pendingColorAccessors.push(pendingAccessor); + } + } + return Promise.all([ + Promise.all(pendingPositionAccessors), + Promise.all(pendingNormalAccessors), + Promise.all(pendingColorAccessors) + ]).then(function(accessors) { + const morphPositions = accessors[0]; + const morphNormals = accessors[1]; + const morphColors = accessors[2]; + if (hasMorphPosition) + geometry.morphAttributes.position = morphPositions; + if (hasMorphNormal) + geometry.morphAttributes.normal = morphNormals; + if (hasMorphColor) + geometry.morphAttributes.color = morphColors; + geometry.morphTargetsRelative = true; + return geometry; + }); +} +function updateMorphTargets(mesh, meshDef) { + mesh.updateMorphTargets(); + if (meshDef.weights !== undefined) { + for (let i = 0, il = meshDef.weights.length;i < il; i++) { + mesh.morphTargetInfluences[i] = meshDef.weights[i]; + } + } + if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) { + const targetNames = meshDef.extras.targetNames; + if (mesh.morphTargetInfluences.length === targetNames.length) { + mesh.morphTargetDictionary = {}; + for (let i = 0, il = targetNames.length;i < il; i++) { + mesh.morphTargetDictionary[targetNames[i]] = i; + } + } else { + console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names."); + } + } +} +function createPrimitiveKey(primitiveDef) { + let geometryKey; + const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]; + if (dracoExtension) { + geometryKey = "draco:" + dracoExtension.bufferView + ":" + dracoExtension.indices + ":" + createAttributesKey(dracoExtension.attributes); + } else { + geometryKey = primitiveDef.indices + ":" + createAttributesKey(primitiveDef.attributes) + ":" + primitiveDef.mode; + } + if (primitiveDef.targets !== undefined) { + for (let i = 0, il = primitiveDef.targets.length;i < il; i++) { + geometryKey += ":" + createAttributesKey(primitiveDef.targets[i]); + } + } + return geometryKey; +} +function createAttributesKey(attributes) { + let attributesKey = ""; + const keys2 = Object.keys(attributes).sort(); + for (let i = 0, il = keys2.length;i < il; i++) { + attributesKey += keys2[i] + ":" + attributes[keys2[i]] + ";"; + } + return attributesKey; +} +function getNormalizedComponentScale(constructor) { + switch (constructor) { + case Int8Array: + return 1 / 127; + case Uint8Array: + return 1 / 255; + case Int16Array: + return 1 / 32767; + case Uint16Array: + return 1 / 65535; + default: + throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type."); + } +} +function getImageURIMimeType(uri) { + if (uri.search(/\.jpe?g($|\?)/i) > 0 || uri.search(/^data\:image\/jpeg/) === 0) + return "image/jpeg"; + if (uri.search(/\.webp($|\?)/i) > 0 || uri.search(/^data\:image\/webp/) === 0) + return "image/webp"; + if (uri.search(/\.ktx2($|\?)/i) > 0 || uri.search(/^data\:image\/ktx2/) === 0) + return "image/ktx2"; + return "image/png"; +} +var _identityMatrix2 = new Matrix4; + +class GLTFParser { + constructor(json = {}, options = {}) { + this.json = json; + this.extensions = {}; + this.plugins = {}; + this.options = options; + this.cache = new GLTFRegistry; + this.associations = new Map; + this.primitiveCache = {}; + this.nodeCache = {}; + this.meshCache = { refs: {}, uses: {} }; + this.cameraCache = { refs: {}, uses: {} }; + this.lightCache = { refs: {}, uses: {} }; + this.sourceCache = {}; + this.textureCache = {}; + this.nodeNamesUsed = {}; + let isSafari2 = false; + let safariVersion = -1; + let isFirefox = false; + let firefoxVersion = -1; + if (typeof navigator !== "undefined") { + const userAgent = navigator.userAgent; + isSafari2 = /^((?!chrome|android).)*safari/i.test(userAgent) === true; + const safariMatch = userAgent.match(/Version\/(\d+)/); + safariVersion = isSafari2 && safariMatch ? parseInt(safariMatch[1], 10) : -1; + isFirefox = userAgent.indexOf("Firefox") > -1; + firefoxVersion = isFirefox ? userAgent.match(/Firefox\/([0-9]+)\./)[1] : -1; + } + if (typeof createImageBitmap === "undefined" || isSafari2 && safariVersion < 17 || isFirefox && firefoxVersion < 98) { + this.textureLoader = new TextureLoader(this.options.manager); + } else { + this.textureLoader = new ImageBitmapLoader(this.options.manager); + } + this.textureLoader.setCrossOrigin(this.options.crossOrigin); + this.textureLoader.setRequestHeader(this.options.requestHeader); + this.fileLoader = new FileLoader(this.options.manager); + this.fileLoader.setResponseType("arraybuffer"); + if (this.options.crossOrigin === "use-credentials") { + this.fileLoader.setWithCredentials(true); + } + } + setExtensions(extensions) { + this.extensions = extensions; + } + setPlugins(plugins) { + this.plugins = plugins; + } + parse(onLoad, onError) { + const parser = this; + const json = this.json; + const extensions = this.extensions; + this.cache.removeAll(); + this.nodeCache = {}; + this._invokeAll(function(ext) { + return ext._markDefs && ext._markDefs(); + }); + Promise.all(this._invokeAll(function(ext) { + return ext.beforeRoot && ext.beforeRoot(); + })).then(function() { + return Promise.all([ + parser.getDependencies("scene"), + parser.getDependencies("animation"), + parser.getDependencies("camera") + ]); + }).then(function(dependencies) { + const result = { + scene: dependencies[0][json.scene || 0], + scenes: dependencies[0], + animations: dependencies[1], + cameras: dependencies[2], + asset: json.asset, + parser, + userData: {} + }; + addUnknownExtensionsToUserData(extensions, result, json); + assignExtrasToUserData(result, json); + return Promise.all(parser._invokeAll(function(ext) { + return ext.afterRoot && ext.afterRoot(result); + })).then(function() { + for (const scene of result.scenes) { + scene.updateMatrixWorld(); + } + onLoad(result); + }); + }).catch(onError); + } + _markDefs() { + const nodeDefs = this.json.nodes || []; + const skinDefs = this.json.skins || []; + const meshDefs = this.json.meshes || []; + for (let skinIndex = 0, skinLength = skinDefs.length;skinIndex < skinLength; skinIndex++) { + const joints = skinDefs[skinIndex].joints; + for (let i = 0, il = joints.length;i < il; i++) { + nodeDefs[joints[i]].isBone = true; + } + } + for (let nodeIndex = 0, nodeLength = nodeDefs.length;nodeIndex < nodeLength; nodeIndex++) { + const nodeDef = nodeDefs[nodeIndex]; + if (nodeDef.mesh !== undefined) { + this._addNodeRef(this.meshCache, nodeDef.mesh); + if (nodeDef.skin !== undefined) { + meshDefs[nodeDef.mesh].isSkinnedMesh = true; + } + } + if (nodeDef.camera !== undefined) { + this._addNodeRef(this.cameraCache, nodeDef.camera); + } + } + } + _addNodeRef(cache, index2) { + if (index2 === undefined) + return; + if (cache.refs[index2] === undefined) { + cache.refs[index2] = cache.uses[index2] = 0; + } + cache.refs[index2]++; + } + _getNodeRef(cache, index2, object) { + if (cache.refs[index2] <= 1) + return object; + const ref = object.clone(); + const updateMappings = (original, clone) => { + const mappings = this.associations.get(original); + if (mappings != null) { + this.associations.set(clone, mappings); + } + for (const [i, child] of original.children.entries()) { + updateMappings(child, clone.children[i]); + } + }; + updateMappings(object, ref); + ref.name += "_instance_" + cache.uses[index2]++; + return ref; + } + _invokeOne(func) { + const extensions = Object.values(this.plugins); + extensions.push(this); + for (let i = 0;i < extensions.length; i++) { + const result = func(extensions[i]); + if (result) + return result; + } + return null; + } + _invokeAll(func) { + const extensions = Object.values(this.plugins); + extensions.unshift(this); + const pending = []; + for (let i = 0;i < extensions.length; i++) { + const result = func(extensions[i]); + if (result) + pending.push(result); + } + return pending; + } + getDependency(type, index2) { + const cacheKey = type + ":" + index2; + let dependency = this.cache.get(cacheKey); + if (!dependency) { + switch (type) { + case "scene": + dependency = this.loadScene(index2); + break; + case "node": + dependency = this._invokeOne(function(ext) { + return ext.loadNode && ext.loadNode(index2); + }); + break; + case "mesh": + dependency = this._invokeOne(function(ext) { + return ext.loadMesh && ext.loadMesh(index2); + }); + break; + case "accessor": + dependency = this.loadAccessor(index2); + break; + case "bufferView": + dependency = this._invokeOne(function(ext) { + return ext.loadBufferView && ext.loadBufferView(index2); + }); + break; + case "buffer": + dependency = this.loadBuffer(index2); + break; + case "material": + dependency = this._invokeOne(function(ext) { + return ext.loadMaterial && ext.loadMaterial(index2); + }); + break; + case "texture": + dependency = this._invokeOne(function(ext) { + return ext.loadTexture && ext.loadTexture(index2); + }); + break; + case "skin": + dependency = this.loadSkin(index2); + break; + case "animation": + dependency = this._invokeOne(function(ext) { + return ext.loadAnimation && ext.loadAnimation(index2); + }); + break; + case "camera": + dependency = this.loadCamera(index2); + break; + default: + dependency = this._invokeOne(function(ext) { + return ext != this && ext.getDependency && ext.getDependency(type, index2); + }); + if (!dependency) { + throw new Error("Unknown type: " + type); + } + break; + } + this.cache.add(cacheKey, dependency); + } + return dependency; + } + getDependencies(type) { + let dependencies = this.cache.get(type); + if (!dependencies) { + const parser = this; + const defs = this.json[type + (type === "mesh" ? "es" : "s")] || []; + dependencies = Promise.all(defs.map(function(def, index2) { + return parser.getDependency(type, index2); + })); + this.cache.add(type, dependencies); + } + return dependencies; + } + loadBuffer(bufferIndex) { + const bufferDef = this.json.buffers[bufferIndex]; + const loader = this.fileLoader; + if (bufferDef.type && bufferDef.type !== "arraybuffer") { + throw new Error("THREE.GLTFLoader: " + bufferDef.type + " buffer type is not supported."); + } + if (bufferDef.uri === undefined && bufferIndex === 0) { + return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body); + } + const options = this.options; + return new Promise(function(resolve, reject2) { + loader.load(LoaderUtils.resolveURL(bufferDef.uri, options.path), resolve, undefined, function() { + reject2(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".')); + }); + }); + } + loadBufferView(bufferViewIndex) { + const bufferViewDef = this.json.bufferViews[bufferViewIndex]; + return this.getDependency("buffer", bufferViewDef.buffer).then(function(buffer) { + const byteLength = bufferViewDef.byteLength || 0; + const byteOffset = bufferViewDef.byteOffset || 0; + return buffer.slice(byteOffset, byteOffset + byteLength); + }); + } + loadAccessor(accessorIndex) { + const parser = this; + const json = this.json; + const accessorDef = this.json.accessors[accessorIndex]; + if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) { + const itemSize = WEBGL_TYPE_SIZES[accessorDef.type]; + const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; + const normalized = accessorDef.normalized === true; + const array = new TypedArray(accessorDef.count * itemSize); + return Promise.resolve(new BufferAttribute(array, itemSize, normalized)); + } + const pendingBufferViews = []; + if (accessorDef.bufferView !== undefined) { + pendingBufferViews.push(this.getDependency("bufferView", accessorDef.bufferView)); + } else { + pendingBufferViews.push(null); + } + if (accessorDef.sparse !== undefined) { + pendingBufferViews.push(this.getDependency("bufferView", accessorDef.sparse.indices.bufferView)); + pendingBufferViews.push(this.getDependency("bufferView", accessorDef.sparse.values.bufferView)); + } + return Promise.all(pendingBufferViews).then(function(bufferViews) { + const bufferView = bufferViews[0]; + const itemSize = WEBGL_TYPE_SIZES[accessorDef.type]; + const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; + const elementBytes = TypedArray.BYTES_PER_ELEMENT; + const itemBytes = elementBytes * itemSize; + const byteOffset = accessorDef.byteOffset || 0; + const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined; + const normalized = accessorDef.normalized === true; + let array, bufferAttribute; + if (byteStride && byteStride !== itemBytes) { + const ibSlice = Math.floor(byteOffset / byteStride); + const ibCacheKey = "InterleavedBuffer:" + accessorDef.bufferView + ":" + accessorDef.componentType + ":" + ibSlice + ":" + accessorDef.count; + let ib = parser.cache.get(ibCacheKey); + if (!ib) { + array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); + ib = new InterleavedBuffer(array, byteStride / elementBytes); + parser.cache.add(ibCacheKey, ib); + } + bufferAttribute = new InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized); + } else { + if (bufferView === null) { + array = new TypedArray(accessorDef.count * itemSize); + } else { + array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize); + } + bufferAttribute = new BufferAttribute(array, itemSize, normalized); + } + if (accessorDef.sparse !== undefined) { + const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; + const TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType]; + const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; + const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; + const sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices); + const sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize); + if (bufferView !== null) { + bufferAttribute = new BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized); + } + bufferAttribute.normalized = false; + for (let i = 0, il = sparseIndices.length;i < il; i++) { + const index2 = sparseIndices[i]; + bufferAttribute.setX(index2, sparseValues[i * itemSize]); + if (itemSize >= 2) + bufferAttribute.setY(index2, sparseValues[i * itemSize + 1]); + if (itemSize >= 3) + bufferAttribute.setZ(index2, sparseValues[i * itemSize + 2]); + if (itemSize >= 4) + bufferAttribute.setW(index2, sparseValues[i * itemSize + 3]); + if (itemSize >= 5) + throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute."); + } + bufferAttribute.normalized = normalized; + } + return bufferAttribute; + }); + } + loadTexture(textureIndex) { + const json = this.json; + const options = this.options; + const textureDef = json.textures[textureIndex]; + const sourceIndex = textureDef.source; + const sourceDef = json.images[sourceIndex]; + let loader = this.textureLoader; + if (sourceDef.uri) { + const handler = options.manager.getHandler(sourceDef.uri); + if (handler !== null) + loader = handler; + } + return this.loadTextureImage(textureIndex, sourceIndex, loader); + } + loadTextureImage(textureIndex, sourceIndex, loader) { + const parser = this; + const json = this.json; + const textureDef = json.textures[textureIndex]; + const sourceDef = json.images[sourceIndex]; + const cacheKey = (sourceDef.uri || sourceDef.bufferView) + ":" + textureDef.sampler; + if (this.textureCache[cacheKey]) { + return this.textureCache[cacheKey]; + } + const promise = this.loadImageSource(sourceIndex, loader).then(function(texture) { + texture.flipY = false; + texture.name = textureDef.name || sourceDef.name || ""; + if (texture.name === "" && typeof sourceDef.uri === "string" && sourceDef.uri.startsWith("data:image/") === false) { + texture.name = sourceDef.uri; + } + const samplers = json.samplers || {}; + const sampler = samplers[textureDef.sampler] || {}; + texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || LinearFilter; + texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || LinearMipmapLinearFilter; + texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || RepeatWrapping; + texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || RepeatWrapping; + texture.generateMipmaps = !texture.isCompressedTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; + parser.associations.set(texture, { textures: textureIndex }); + return texture; + }).catch(function() { + return null; + }); + this.textureCache[cacheKey] = promise; + return promise; + } + loadImageSource(sourceIndex, loader) { + const parser = this; + const json = this.json; + const options = this.options; + if (this.sourceCache[sourceIndex] !== undefined) { + return this.sourceCache[sourceIndex].then((texture) => texture.clone()); + } + const sourceDef = json.images[sourceIndex]; + const URL2 = self.URL || self.webkitURL; + let sourceURI = sourceDef.uri || ""; + let isObjectURL = false; + if (sourceDef.bufferView !== undefined) { + sourceURI = parser.getDependency("bufferView", sourceDef.bufferView).then(function(bufferView) { + isObjectURL = true; + const blob = new Blob([bufferView], { type: sourceDef.mimeType }); + sourceURI = URL2.createObjectURL(blob); + return sourceURI; + }); + } else if (sourceDef.uri === undefined) { + throw new Error("THREE.GLTFLoader: Image " + sourceIndex + " is missing URI and bufferView"); + } + const promise = Promise.resolve(sourceURI).then(function(sourceURI2) { + return new Promise(function(resolve, reject2) { + let onLoad = resolve; + if (loader.isImageBitmapLoader === true) { + onLoad = function(imageBitmap) { + const texture = new Texture(imageBitmap); + texture.needsUpdate = true; + resolve(texture); + }; + } + loader.load(LoaderUtils.resolveURL(sourceURI2, options.path), onLoad, undefined, reject2); + }); + }).then(function(texture) { + if (isObjectURL === true) { + URL2.revokeObjectURL(sourceURI); + } + assignExtrasToUserData(texture, sourceDef); + texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType(sourceDef.uri); + return texture; + }).catch(function(error) { + console.error("THREE.GLTFLoader: Couldn't load texture", sourceURI); + throw error; + }); + this.sourceCache[sourceIndex] = promise; + return promise; + } + assignTexture(materialParams, mapName, mapDef, colorSpace) { + const parser = this; + return this.getDependency("texture", mapDef.index).then(function(texture) { + if (!texture) + return null; + if (mapDef.texCoord !== undefined && mapDef.texCoord > 0) { + texture = texture.clone(); + texture.channel = mapDef.texCoord; + } + if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) { + const transform2 = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined; + if (transform2) { + const gltfReference = parser.associations.get(texture); + texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform2); + parser.associations.set(texture, gltfReference); + } + } + if (colorSpace !== undefined) { + texture.colorSpace = colorSpace; + } + materialParams[mapName] = texture; + return texture; + }); + } + assignFinalMaterial(mesh) { + const geometry = mesh.geometry; + let material = mesh.material; + const useDerivativeTangents = geometry.attributes.tangent === undefined; + const useVertexColors = geometry.attributes.color !== undefined; + const useFlatShading = geometry.attributes.normal === undefined; + if (mesh.isPoints) { + const cacheKey = "PointsMaterial:" + material.uuid; + let pointsMaterial = this.cache.get(cacheKey); + if (!pointsMaterial) { + pointsMaterial = new PointsMaterial; + Material.prototype.copy.call(pointsMaterial, material); + pointsMaterial.color.copy(material.color); + pointsMaterial.map = material.map; + pointsMaterial.sizeAttenuation = false; + this.cache.add(cacheKey, pointsMaterial); + } + material = pointsMaterial; + } else if (mesh.isLine) { + const cacheKey = "LineBasicMaterial:" + material.uuid; + let lineMaterial = this.cache.get(cacheKey); + if (!lineMaterial) { + lineMaterial = new LineBasicMaterial; + Material.prototype.copy.call(lineMaterial, material); + lineMaterial.color.copy(material.color); + lineMaterial.map = material.map; + this.cache.add(cacheKey, lineMaterial); + } + material = lineMaterial; + } + if (useDerivativeTangents || useVertexColors || useFlatShading) { + let cacheKey = "ClonedMaterial:" + material.uuid + ":"; + if (useDerivativeTangents) + cacheKey += "derivative-tangents:"; + if (useVertexColors) + cacheKey += "vertex-colors:"; + if (useFlatShading) + cacheKey += "flat-shading:"; + let cachedMaterial = this.cache.get(cacheKey); + if (!cachedMaterial) { + cachedMaterial = material.clone(); + if (useVertexColors) + cachedMaterial.vertexColors = true; + if (useFlatShading) + cachedMaterial.flatShading = true; + if (useDerivativeTangents) { + if (cachedMaterial.normalScale) + cachedMaterial.normalScale.y *= -1; + if (cachedMaterial.clearcoatNormalScale) + cachedMaterial.clearcoatNormalScale.y *= -1; + } + this.cache.add(cacheKey, cachedMaterial); + this.associations.set(cachedMaterial, this.associations.get(material)); + } + material = cachedMaterial; + } + mesh.material = material; + } + getMaterialType() { + return MeshStandardMaterial; + } + loadMaterial(materialIndex) { + const parser = this; + const json = this.json; + const extensions = this.extensions; + const materialDef = json.materials[materialIndex]; + let materialType; + const materialParams = {}; + const materialExtensions = materialDef.extensions || {}; + const pending = []; + if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) { + const kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT]; + materialType = kmuExtension.getMaterialType(); + pending.push(kmuExtension.extendParams(materialParams, materialDef, parser)); + } else { + const metallicRoughness = materialDef.pbrMetallicRoughness || {}; + materialParams.color = new Color(1, 1, 1); + materialParams.opacity = 1; + if (Array.isArray(metallicRoughness.baseColorFactor)) { + const array = metallicRoughness.baseColorFactor; + materialParams.color.setRGB(array[0], array[1], array[2], LinearSRGBColorSpace); + materialParams.opacity = array[3]; + } + if (metallicRoughness.baseColorTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, SRGBColorSpace)); + } + materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1; + materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1; + if (metallicRoughness.metallicRoughnessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "metalnessMap", metallicRoughness.metallicRoughnessTexture)); + pending.push(parser.assignTexture(materialParams, "roughnessMap", metallicRoughness.metallicRoughnessTexture)); + } + materialType = this._invokeOne(function(ext) { + return ext.getMaterialType && ext.getMaterialType(materialIndex); + }); + pending.push(Promise.all(this._invokeAll(function(ext) { + return ext.extendMaterialParams && ext.extendMaterialParams(materialIndex, materialParams); + }))); + } + if (materialDef.doubleSided === true) { + materialParams.side = DoubleSide; + } + const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; + if (alphaMode === ALPHA_MODES.BLEND) { + materialParams.transparent = true; + materialParams.depthWrite = false; + } else { + materialParams.transparent = false; + if (alphaMode === ALPHA_MODES.MASK) { + materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5; + } + } + if (materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial) { + pending.push(parser.assignTexture(materialParams, "normalMap", materialDef.normalTexture)); + materialParams.normalScale = new Vector2(1, 1); + if (materialDef.normalTexture.scale !== undefined) { + const scale2 = materialDef.normalTexture.scale; + materialParams.normalScale.set(scale2, scale2); + } + } + if (materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial) { + pending.push(parser.assignTexture(materialParams, "aoMap", materialDef.occlusionTexture)); + if (materialDef.occlusionTexture.strength !== undefined) { + materialParams.aoMapIntensity = materialDef.occlusionTexture.strength; + } + } + if (materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial) { + const emissiveFactor = materialDef.emissiveFactor; + materialParams.emissive = new Color().setRGB(emissiveFactor[0], emissiveFactor[1], emissiveFactor[2], LinearSRGBColorSpace); + } + if (materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial) { + pending.push(parser.assignTexture(materialParams, "emissiveMap", materialDef.emissiveTexture, SRGBColorSpace)); + } + return Promise.all(pending).then(function() { + const material = new materialType(materialParams); + if (materialDef.name) + material.name = materialDef.name; + assignExtrasToUserData(material, materialDef); + parser.associations.set(material, { materials: materialIndex }); + if (materialDef.extensions) + addUnknownExtensionsToUserData(extensions, material, materialDef); + return material; + }); + } + createUniqueName(originalName) { + const sanitizedName = PropertyBinding.sanitizeNodeName(originalName || ""); + if (sanitizedName in this.nodeNamesUsed) { + return sanitizedName + "_" + ++this.nodeNamesUsed[sanitizedName]; + } else { + this.nodeNamesUsed[sanitizedName] = 0; + return sanitizedName; + } + } + loadGeometries(primitives) { + const parser = this; + const extensions = this.extensions; + const cache = this.primitiveCache; + function createDracoPrimitive(primitive) { + return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function(geometry) { + return addPrimitiveAttributes(geometry, primitive, parser); + }); + } + const pending = []; + for (let i = 0, il = primitives.length;i < il; i++) { + const primitive = primitives[i]; + const cacheKey = createPrimitiveKey(primitive); + const cached = cache[cacheKey]; + if (cached) { + pending.push(cached.promise); + } else { + let geometryPromise; + if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) { + geometryPromise = createDracoPrimitive(primitive); + } else { + geometryPromise = addPrimitiveAttributes(new BufferGeometry, primitive, parser); + } + cache[cacheKey] = { primitive, promise: geometryPromise }; + pending.push(geometryPromise); + } + } + return Promise.all(pending); + } + loadMesh(meshIndex) { + const parser = this; + const json = this.json; + const extensions = this.extensions; + const meshDef = json.meshes[meshIndex]; + const primitives = meshDef.primitives; + const pending = []; + for (let i = 0, il = primitives.length;i < il; i++) { + const material = primitives[i].material === undefined ? createDefaultMaterial(this.cache) : this.getDependency("material", primitives[i].material); + pending.push(material); + } + pending.push(parser.loadGeometries(primitives)); + return Promise.all(pending).then(function(results) { + const materials = results.slice(0, results.length - 1); + const geometries = results[results.length - 1]; + const meshes = []; + for (let i = 0, il = geometries.length;i < il; i++) { + const geometry = geometries[i]; + const primitive = primitives[i]; + let mesh; + const material = materials[i]; + if (primitive.mode === WEBGL_CONSTANTS2.TRIANGLES || primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_FAN || primitive.mode === undefined) { + mesh = meshDef.isSkinnedMesh === true ? new SkinnedMesh(geometry, material) : new Mesh(geometry, material); + if (mesh.isSkinnedMesh === true) { + mesh.normalizeSkinWeights(); + } + if (primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_STRIP) { + mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleStripDrawMode); + } else if (primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_FAN) { + mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleFanDrawMode); + } + } else if (primitive.mode === WEBGL_CONSTANTS2.LINES) { + mesh = new LineSegments(geometry, material); + } else if (primitive.mode === WEBGL_CONSTANTS2.LINE_STRIP) { + mesh = new Line(geometry, material); + } else if (primitive.mode === WEBGL_CONSTANTS2.LINE_LOOP) { + mesh = new LineLoop(geometry, material); + } else if (primitive.mode === WEBGL_CONSTANTS2.POINTS) { + mesh = new Points(geometry, material); + } else { + throw new Error("THREE.GLTFLoader: Primitive mode unsupported: " + primitive.mode); + } + if (Object.keys(mesh.geometry.morphAttributes).length > 0) { + updateMorphTargets(mesh, meshDef); + } + mesh.name = parser.createUniqueName(meshDef.name || "mesh_" + meshIndex); + assignExtrasToUserData(mesh, meshDef); + if (primitive.extensions) + addUnknownExtensionsToUserData(extensions, mesh, primitive); + parser.assignFinalMaterial(mesh); + meshes.push(mesh); + } + for (let i = 0, il = meshes.length;i < il; i++) { + parser.associations.set(meshes[i], { + meshes: meshIndex, + primitives: i + }); + } + if (meshes.length === 1) { + if (meshDef.extensions) + addUnknownExtensionsToUserData(extensions, meshes[0], meshDef); + return meshes[0]; + } + const group = new Group; + if (meshDef.extensions) + addUnknownExtensionsToUserData(extensions, group, meshDef); + parser.associations.set(group, { meshes: meshIndex }); + for (let i = 0, il = meshes.length;i < il; i++) { + group.add(meshes[i]); + } + return group; + }); + } + loadCamera(cameraIndex) { + let camera; + const cameraDef = this.json.cameras[cameraIndex]; + const params = cameraDef[cameraDef.type]; + if (!params) { + console.warn("THREE.GLTFLoader: Missing camera parameters."); + return; + } + if (cameraDef.type === "perspective") { + camera = new PerspectiveCamera(MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2000000); + } else if (cameraDef.type === "orthographic") { + camera = new OrthographicCamera(-params.xmag, params.xmag, params.ymag, -params.ymag, params.znear, params.zfar); + } + if (cameraDef.name) + camera.name = this.createUniqueName(cameraDef.name); + assignExtrasToUserData(camera, cameraDef); + return Promise.resolve(camera); + } + loadSkin(skinIndex) { + const skinDef = this.json.skins[skinIndex]; + const pending = []; + for (let i = 0, il = skinDef.joints.length;i < il; i++) { + pending.push(this._loadNodeShallow(skinDef.joints[i])); + } + if (skinDef.inverseBindMatrices !== undefined) { + pending.push(this.getDependency("accessor", skinDef.inverseBindMatrices)); + } else { + pending.push(null); + } + return Promise.all(pending).then(function(results) { + const inverseBindMatrices = results.pop(); + const jointNodes = results; + const bones = []; + const boneInverses = []; + for (let i = 0, il = jointNodes.length;i < il; i++) { + const jointNode = jointNodes[i]; + if (jointNode) { + bones.push(jointNode); + const mat = new Matrix4; + if (inverseBindMatrices !== null) { + mat.fromArray(inverseBindMatrices.array, i * 16); + } + boneInverses.push(mat); + } else { + console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[i]); + } + } + return new Skeleton(bones, boneInverses); + }); + } + loadAnimation(animationIndex) { + const json = this.json; + const parser = this; + const animationDef = json.animations[animationIndex]; + const animationName = animationDef.name ? animationDef.name : "animation_" + animationIndex; + const pendingNodes = []; + const pendingInputAccessors = []; + const pendingOutputAccessors = []; + const pendingSamplers = []; + const pendingTargets = []; + for (let i = 0, il = animationDef.channels.length;i < il; i++) { + const channel = animationDef.channels[i]; + const sampler = animationDef.samplers[channel.sampler]; + const target = channel.target; + const name2 = target.node; + const input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input; + const output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output; + if (target.node === undefined) + continue; + pendingNodes.push(this.getDependency("node", name2)); + pendingInputAccessors.push(this.getDependency("accessor", input)); + pendingOutputAccessors.push(this.getDependency("accessor", output)); + pendingSamplers.push(sampler); + pendingTargets.push(target); + } + return Promise.all([ + Promise.all(pendingNodes), + Promise.all(pendingInputAccessors), + Promise.all(pendingOutputAccessors), + Promise.all(pendingSamplers), + Promise.all(pendingTargets) + ]).then(function(dependencies) { + const nodes = dependencies[0]; + const inputAccessors = dependencies[1]; + const outputAccessors = dependencies[2]; + const samplers = dependencies[3]; + const targets = dependencies[4]; + const tracks = []; + for (let i = 0, il = nodes.length;i < il; i++) { + const node = nodes[i]; + const inputAccessor = inputAccessors[i]; + const outputAccessor = outputAccessors[i]; + const sampler = samplers[i]; + const target = targets[i]; + if (node === undefined) + continue; + if (node.updateMatrix) { + node.updateMatrix(); + } + const createdTracks = parser._createAnimationTracks(node, inputAccessor, outputAccessor, sampler, target); + if (createdTracks) { + for (let k2 = 0;k2 < createdTracks.length; k2++) { + tracks.push(createdTracks[k2]); + } + } + } + return new AnimationClip(animationName, undefined, tracks); + }); + } + createNodeMesh(nodeIndex) { + const json = this.json; + const parser = this; + const nodeDef = json.nodes[nodeIndex]; + if (nodeDef.mesh === undefined) + return null; + return parser.getDependency("mesh", nodeDef.mesh).then(function(mesh) { + const node = parser._getNodeRef(parser.meshCache, nodeDef.mesh, mesh); + if (nodeDef.weights !== undefined) { + node.traverse(function(o) { + if (!o.isMesh) + return; + for (let i = 0, il = nodeDef.weights.length;i < il; i++) { + o.morphTargetInfluences[i] = nodeDef.weights[i]; + } + }); + } + return node; + }); + } + loadNode(nodeIndex) { + const json = this.json; + const parser = this; + const nodeDef = json.nodes[nodeIndex]; + const nodePending = parser._loadNodeShallow(nodeIndex); + const childPending = []; + const childrenDef = nodeDef.children || []; + for (let i = 0, il = childrenDef.length;i < il; i++) { + childPending.push(parser.getDependency("node", childrenDef[i])); + } + const skeletonPending = nodeDef.skin === undefined ? Promise.resolve(null) : parser.getDependency("skin", nodeDef.skin); + return Promise.all([ + nodePending, + Promise.all(childPending), + skeletonPending + ]).then(function(results) { + const node = results[0]; + const children = results[1]; + const skeleton = results[2]; + if (skeleton !== null) { + node.traverse(function(mesh) { + if (!mesh.isSkinnedMesh) + return; + mesh.bind(skeleton, _identityMatrix2); + }); + } + for (let i = 0, il = children.length;i < il; i++) { + node.add(children[i]); + } + return node; + }); + } + _loadNodeShallow(nodeIndex) { + const json = this.json; + const extensions = this.extensions; + const parser = this; + if (this.nodeCache[nodeIndex] !== undefined) { + return this.nodeCache[nodeIndex]; + } + const nodeDef = json.nodes[nodeIndex]; + const nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : ""; + const pending = []; + const meshPromise = parser._invokeOne(function(ext) { + return ext.createNodeMesh && ext.createNodeMesh(nodeIndex); + }); + if (meshPromise) { + pending.push(meshPromise); + } + if (nodeDef.camera !== undefined) { + pending.push(parser.getDependency("camera", nodeDef.camera).then(function(camera) { + return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera); + })); + } + parser._invokeAll(function(ext) { + return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex); + }).forEach(function(promise) { + pending.push(promise); + }); + this.nodeCache[nodeIndex] = Promise.all(pending).then(function(objects) { + let node; + if (nodeDef.isBone === true) { + node = new Bone; + } else if (objects.length > 1) { + node = new Group; + } else if (objects.length === 1) { + node = objects[0]; + } else { + node = new Object3D; + } + if (node !== objects[0]) { + for (let i = 0, il = objects.length;i < il; i++) { + node.add(objects[i]); + } + } + if (nodeDef.name) { + node.userData.name = nodeDef.name; + node.name = nodeName; + } + assignExtrasToUserData(node, nodeDef); + if (nodeDef.extensions) + addUnknownExtensionsToUserData(extensions, node, nodeDef); + if (nodeDef.matrix !== undefined) { + const matrix = new Matrix4; + matrix.fromArray(nodeDef.matrix); + node.applyMatrix4(matrix); + } else { + if (nodeDef.translation !== undefined) { + node.position.fromArray(nodeDef.translation); + } + if (nodeDef.rotation !== undefined) { + node.quaternion.fromArray(nodeDef.rotation); + } + if (nodeDef.scale !== undefined) { + node.scale.fromArray(nodeDef.scale); + } + } + if (!parser.associations.has(node)) { + parser.associations.set(node, {}); + } + parser.associations.get(node).nodes = nodeIndex; + return node; + }); + return this.nodeCache[nodeIndex]; + } + loadScene(sceneIndex) { + const extensions = this.extensions; + const sceneDef = this.json.scenes[sceneIndex]; + const parser = this; + const scene = new Group; + if (sceneDef.name) + scene.name = parser.createUniqueName(sceneDef.name); + assignExtrasToUserData(scene, sceneDef); + if (sceneDef.extensions) + addUnknownExtensionsToUserData(extensions, scene, sceneDef); + const nodeIds = sceneDef.nodes || []; + const pending = []; + for (let i = 0, il = nodeIds.length;i < il; i++) { + pending.push(parser.getDependency("node", nodeIds[i])); + } + return Promise.all(pending).then(function(nodes) { + for (let i = 0, il = nodes.length;i < il; i++) { + scene.add(nodes[i]); + } + const reduceAssociations = (node) => { + const reducedAssociations = new Map; + for (const [key2, value2] of parser.associations) { + if (key2 instanceof Material || key2 instanceof Texture) { + reducedAssociations.set(key2, value2); + } + } + node.traverse((node2) => { + const mappings = parser.associations.get(node2); + if (mappings != null) { + reducedAssociations.set(node2, mappings); + } + }); + return reducedAssociations; + }; + parser.associations = reduceAssociations(scene); + return scene; + }); + } + _createAnimationTracks(node, inputAccessor, outputAccessor, sampler, target) { + const tracks = []; + const targetName = node.name ? node.name : node.uuid; + const targetNames = []; + if (PATH_PROPERTIES2[target.path] === PATH_PROPERTIES2.weights) { + node.traverse(function(object) { + if (object.morphTargetInfluences) { + targetNames.push(object.name ? object.name : object.uuid); + } + }); + } else { + targetNames.push(targetName); + } + let TypedKeyframeTrack; + switch (PATH_PROPERTIES2[target.path]) { + case PATH_PROPERTIES2.weights: + TypedKeyframeTrack = NumberKeyframeTrack; + break; + case PATH_PROPERTIES2.rotation: + TypedKeyframeTrack = QuaternionKeyframeTrack; + break; + case PATH_PROPERTIES2.position: + case PATH_PROPERTIES2.scale: + TypedKeyframeTrack = VectorKeyframeTrack; + break; + default: + switch (outputAccessor.itemSize) { + case 1: + TypedKeyframeTrack = NumberKeyframeTrack; + break; + case 2: + case 3: + default: + TypedKeyframeTrack = VectorKeyframeTrack; + break; + } + break; + } + const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : InterpolateLinear; + const outputArray = this._getArrayFromAccessor(outputAccessor); + for (let j2 = 0, jl = targetNames.length;j2 < jl; j2++) { + const track = new TypedKeyframeTrack(targetNames[j2] + "." + PATH_PROPERTIES2[target.path], inputAccessor.array, outputArray, interpolation); + if (sampler.interpolation === "CUBICSPLINE") { + this._createCubicSplineTrackInterpolant(track); + } + tracks.push(track); + } + return tracks; + } + _getArrayFromAccessor(accessor) { + let outputArray = accessor.array; + if (accessor.normalized) { + const scale2 = getNormalizedComponentScale(outputArray.constructor); + const scaled = new Float32Array(outputArray.length); + for (let j2 = 0, jl = outputArray.length;j2 < jl; j2++) { + scaled[j2] = outputArray[j2] * scale2; + } + outputArray = scaled; + } + return outputArray; + } + _createCubicSplineTrackInterpolant(track) { + track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) { + const interpolantType = this instanceof QuaternionKeyframeTrack ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant; + return new interpolantType(this.times, this.values, this.getValueSize() / 3, result); + }; + track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true; + } +} +function computeBounds(geometry, primitiveDef, parser) { + const attributes = primitiveDef.attributes; + const box = new Box3; + if (attributes.POSITION !== undefined) { + const accessor = parser.json.accessors[attributes.POSITION]; + const min = accessor.min; + const max = accessor.max; + if (min !== undefined && max !== undefined) { + box.set(new Vector3(min[0], min[1], min[2]), new Vector3(max[0], max[1], max[2])); + if (accessor.normalized) { + const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]); + box.min.multiplyScalar(boxScale); + box.max.multiplyScalar(boxScale); + } + } else { + console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION."); + return; + } + } else { + return; + } + const targets = primitiveDef.targets; + if (targets !== undefined) { + const maxDisplacement = new Vector3; + const vector = new Vector3; + for (let i = 0, il = targets.length;i < il; i++) { + const target = targets[i]; + if (target.POSITION !== undefined) { + const accessor = parser.json.accessors[target.POSITION]; + const min = accessor.min; + const max = accessor.max; + if (min !== undefined && max !== undefined) { + vector.setX(Math.max(Math.abs(min[0]), Math.abs(max[0]))); + vector.setY(Math.max(Math.abs(min[1]), Math.abs(max[1]))); + vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max[2]))); + if (accessor.normalized) { + const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]); + vector.multiplyScalar(boxScale); + } + maxDisplacement.max(vector); + } else { + console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION."); + } + } + } + box.expandByVector(maxDisplacement); + } + geometry.boundingBox = box; + const sphere = new Sphere; + box.getCenter(sphere.center); + sphere.radius = box.min.distanceTo(box.max) / 2; + geometry.boundingSphere = sphere; +} +function addPrimitiveAttributes(geometry, primitiveDef, parser) { + const attributes = primitiveDef.attributes; + const pending = []; + function assignAttributeAccessor(accessorIndex, attributeName) { + return parser.getDependency("accessor", accessorIndex).then(function(accessor) { + geometry.setAttribute(attributeName, accessor); + }); + } + for (const gltfAttributeName in attributes) { + const threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); + if (threeAttributeName in geometry.attributes) + continue; + pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName)); + } + if (primitiveDef.indices !== undefined && !geometry.index) { + const accessor = parser.getDependency("accessor", primitiveDef.indices).then(function(accessor2) { + geometry.setIndex(accessor2); + }); + pending.push(accessor); + } + if (ColorManagement.workingColorSpace !== LinearSRGBColorSpace && "COLOR_0" in attributes) { + console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ColorManagement.workingColorSpace}" not supported.`); + } + assignExtrasToUserData(geometry, primitiveDef); + computeBounds(geometry, primitiveDef, parser); + return Promise.all(pending).then(function() { + return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry; + }); +} +// node_modules/three/examples/jsm/utils/WorkerPool.js +class WorkerPool { + constructor(pool = 4) { + this.pool = pool; + this.queue = []; + this.workers = []; + this.workersResolve = []; + this.workerStatus = 0; + } + _initWorker(workerId) { + if (!this.workers[workerId]) { + const worker = this.workerCreator(); + worker.addEventListener("message", this._onMessage.bind(this, workerId)); + this.workers[workerId] = worker; + } + } + _getIdleWorker() { + for (let i = 0;i < this.pool; i++) + if (!(this.workerStatus & 1 << i)) + return i; + return -1; + } + _onMessage(workerId, msg) { + const resolve = this.workersResolve[workerId]; + resolve && resolve(msg); + if (this.queue.length) { + const { resolve: resolve2, msg: msg2, transfer } = this.queue.shift(); + this.workersResolve[workerId] = resolve2; + this.workers[workerId].postMessage(msg2, transfer); + } else { + this.workerStatus ^= 1 << workerId; + } + } + setWorkerCreator(workerCreator) { + this.workerCreator = workerCreator; + } + setWorkerLimit(pool) { + this.pool = pool; + } + postMessage(msg, transfer) { + return new Promise((resolve) => { + const workerId = this._getIdleWorker(); + if (workerId !== -1) { + this._initWorker(workerId); + this.workerStatus |= 1 << workerId; + this.workersResolve[workerId] = resolve; + this.workers[workerId].postMessage(msg, transfer); + } else { + this.queue.push({ resolve, msg, transfer }); + } + }); + } + dispose() { + this.workers.forEach((worker) => worker.terminate()); + this.workersResolve.length = 0; + this.workers.length = 0; + this.queue.length = 0; + this.workerStatus = 0; + } +} + +// node_modules/three/examples/jsm/libs/zstddec.module.js +var A; +var I2; +var B; +var g2 = { env: { emscripten_notify_memory_growth: function(A2) { + B = new Uint8Array(I2.exports.memory.buffer); +} } }; + +class Q { + init() { + return A || (A = typeof fetch != "undefined" ? fetch("data:application/wasm;base64," + C3).then((A2) => A2.arrayBuffer()).then((A2) => WebAssembly.instantiate(A2, g2)).then(this._init) : WebAssembly.instantiate(Buffer.from(C3, "base64"), g2).then(this._init), A); + } + _init(A2) { + I2 = A2.instance, g2.env.emscripten_notify_memory_growth(0); + } + decode(A2, g3 = 0) { + if (!I2) + throw new Error("ZSTDDecoder: Await .init() before decoding."); + const Q2 = A2.byteLength, C3 = I2.exports.malloc(Q2); + B.set(A2, C3), g3 = g3 || Number(I2.exports.ZSTD_findDecompressedSize(C3, Q2)); + const E2 = I2.exports.malloc(g3), i = I2.exports.ZSTD_decompress(E2, g3, C3, Q2), D = B.slice(E2, E2 + i); + return I2.exports.free(C3), I2.exports.free(E2), D; + } +} +var C3 = "AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDBgEACQkHBgICAAYGAgQUBwYGAwIGAAMCAQgBBwUGCgoEEQAEBAEIAwgDBQgDEA8IAAcABAUBcAECAgUEAQCAAgYJAX8BQaCgwAILB2AHBm1lbW9yeQIABm1hbGxvYwAoBGZyZWUAJgxaU1REX2lzRXJyb3IAaBlaU1REX2ZpbmREZWNvbXByZXNzZWRTaXplAFQPWlNURF9kZWNvbXByZXNzAEoGX3N0YXJ0ACQJBwEAQQELASQKussBaA8AIAAgACgCBCABajYCBAsZACAAKAIAIAAoAgRBH3F0QQAgAWtBH3F2CwgAIABBiH9LC34BBH9BAyEBIAAoAgQiA0EgTQRAIAAoAggiASAAKAIQTwRAIAAQDQ8LIAAoAgwiAiABRgRAQQFBAiADQSBJGw8LIAAgASABIAJrIANBA3YiBCABIARrIAJJIgEbIgJrIgQ2AgggACADIAJBA3RrNgIEIAAgBCgAADYCAAsgAQsUAQF/IAAgARACIQIgACABEAEgAgv3AQECfyACRQRAIABCADcCACAAQQA2AhAgAEIANwIIQbh/DwsgACABNgIMIAAgAUEEajYCECACQQRPBEAgACABIAJqIgFBfGoiAzYCCCAAIAMoAAA2AgAgAUF/ai0AACIBBEAgAEEIIAEQFGs2AgQgAg8LIABBADYCBEF/DwsgACABNgIIIAAgAS0AACIDNgIAIAJBfmoiBEEBTQRAIARBAWtFBEAgACABLQACQRB0IANyIgM2AgALIAAgAS0AAUEIdCADajYCAAsgASACakF/ai0AACIBRQRAIABBADYCBEFsDwsgAEEoIAEQFCACQQN0ams2AgQgAgsWACAAIAEpAAA3AAAgACABKQAINwAICy8BAX8gAUECdEGgHWooAgAgACgCAEEgIAEgACgCBGprQR9xdnEhAiAAIAEQASACCyEAIAFCz9bTvtLHq9lCfiAAfEIfiUKHla+vmLbem55/fgsdAQF/IAAoAgggACgCDEYEfyAAKAIEQSBGBUEACwuCBAEDfyACQYDAAE8EQCAAIAEgAhBnIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAsMACAAIAEpAAA3AAALQQECfyAAKAIIIgEgACgCEEkEQEEDDwsgACAAKAIEIgJBB3E2AgQgACABIAJBA3ZrIgE2AgggACABKAAANgIAQQALDAAgACABKAIANgAAC/cCAQJ/AkAgACABRg0AAkAgASACaiAASwRAIAAgAmoiBCABSw0BCyAAIAEgAhALDwsgACABc0EDcSEDAkACQCAAIAFJBEAgAwRAIAAhAwwDCyAAQQNxRQRAIAAhAwwCCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigCACACaiAAQQZ2IgFBAnRBsB5qKAIAaiAAQSBxIgBFaiABRSAAQQV2cWoFQbh/CwsdACAAKAKQ4gEQWiAAQQA2AqDiASAAQgA3A5DiAQu1AwEFfyMAQZACayIKJABBuH8hBgJAIAVFDQAgBCwAACIIQf8BcSEHAkAgCEF/TARAIAdBgn9qQQF2IgggBU8NAkFsIQYgB0GBf2oiBUGAAk8NAiAEQQFqIQdBACEGA0AgBiAFTwRAIAUhBiAIIQcMAwUgACAGaiAHIAZBAXZqIgQtAABBBHY6AAAgACAGQQFyaiAELQAAQQ9xOgAAIAZBAmohBgwBCwAACwALIAcgBU8NASAAIARBAWogByAKEFMiBhADDQELIAYhBEEAIQYgAUEAQTQQECEJQQAhBQNAIAQgBkcEQCAAIAZqIggtAAAiAUELSwRAQWwhBgwDBSAJIAFBAnRqIgEgASgCAEEBajYCACAGQQFqIQZBASAILQAAdEEBdSAFaiEFDAILAAsLQWwhBiAFRQ0AIAUQFEEBaiIBQQxLDQAgAyABNgIAQQFBASABdCAFayIDEBQiAXQgA0cNACAAIARqIAFBAWoiADoAACAJIABBAnRqIgAgACgCAEEBajYCACAJKAIEIgBBAkkgAEEBcXINACACIARBAWo2AgAgB0EBaiEGCyAKQZACaiQAIAYLxhEBDH8jAEHwAGsiBSQAQWwhCwJAIANBCkkNACACLwAAIQogAi8AAiEJIAIvAAQhByAFQQhqIAQQDgJAIAMgByAJIApqakEGaiIMSQ0AIAUtAAohCCAFQdgAaiACQQZqIgIgChAGIgsQAw0BIAVBQGsgAiAKaiICIAkQBiILEAMNASAFQShqIAIgCWoiAiAHEAYiCxADDQEgBUEQaiACIAdqIAMgDGsQBiILEAMNASAAIAFqIg9BfWohECAEQQRqIQZBASELIAAgAUEDakECdiIDaiIMIANqIgIgA2oiDiEDIAIhBCAMIQcDQCALIAMgEElxBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgCS0AAyELIAcgBiAFQUBrIAgQAkECdGoiCS8BADsAACAFQUBrIAktAAIQASAJLQADIQogBCAGIAVBKGogCBACQQJ0aiIJLwEAOwAAIAVBKGogCS0AAhABIAktAAMhCSADIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgDS0AAyENIAAgC2oiCyAGIAVB2ABqIAgQAkECdGoiAC8BADsAACAFQdgAaiAALQACEAEgAC0AAyEAIAcgCmoiCiAGIAVBQGsgCBACQQJ0aiIHLwEAOwAAIAVBQGsgBy0AAhABIActAAMhByAEIAlqIgkgBiAFQShqIAgQAkECdGoiBC8BADsAACAFQShqIAQtAAIQASAELQADIQQgAyANaiIDIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgACALaiEAIAcgCmohByAEIAlqIQQgAyANLQADaiEDIAVB2ABqEA0gBUFAaxANciAFQShqEA1yIAVBEGoQDXJFIQsMAQsLIAQgDksgByACS3INAEFsIQsgACAMSw0BIAxBfWohCQNAQQAgACAJSSAFQdgAahAEGwRAIAAgBiAFQdgAaiAIEAJBAnRqIgovAQA7AAAgBUHYAGogCi0AAhABIAAgCi0AA2oiACAGIAVB2ABqIAgQAkECdGoiCi8BADsAACAFQdgAaiAKLQACEAEgACAKLQADaiEADAEFIAxBfmohCgNAIAVB2ABqEAQgACAKS3JFBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgACAJLQADaiEADAELCwNAIAAgCk0EQCAAIAYgBUHYAGogCBACQQJ0aiIJLwEAOwAAIAVB2ABqIAktAAIQASAAIAktAANqIQAMAQsLAkAgACAMTw0AIAAgBiAFQdgAaiAIEAIiAEECdGoiDC0AADoAACAMLQADQQFGBEAgBUHYAGogDC0AAhABDAELIAUoAlxBH0sNACAFQdgAaiAGIABBAnRqLQACEAEgBSgCXEEhSQ0AIAVBIDYCXAsgAkF9aiEMA0BBACAHIAxJIAVBQGsQBBsEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiIAIAYgBUFAayAIEAJBAnRqIgcvAQA7AAAgBUFAayAHLQACEAEgACAHLQADaiEHDAEFIAJBfmohDANAIAVBQGsQBCAHIAxLckUEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwNAIAcgDE0EQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwJAIAcgAk8NACAHIAYgBUFAayAIEAIiAEECdGoiAi0AADoAACACLQADQQFGBEAgBUFAayACLQACEAEMAQsgBSgCREEfSw0AIAVBQGsgBiAAQQJ0ai0AAhABIAUoAkRBIUkNACAFQSA2AkQLIA5BfWohAgNAQQAgBCACSSAFQShqEAQbBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2oiACAGIAVBKGogCBACQQJ0aiIELwEAOwAAIAVBKGogBC0AAhABIAAgBC0AA2ohBAwBBSAOQX5qIQIDQCAFQShqEAQgBCACS3JFBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsDQCAEIAJNBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsCQCAEIA5PDQAgBCAGIAVBKGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBKGogAi0AAhABDAELIAUoAixBH0sNACAFQShqIAYgAEECdGotAAIQASAFKAIsQSFJDQAgBUEgNgIsCwNAQQAgAyAQSSAFQRBqEAQbBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2oiACAGIAVBEGogCBACQQJ0aiICLwEAOwAAIAVBEGogAi0AAhABIAAgAi0AA2ohAwwBBSAPQX5qIQIDQCAFQRBqEAQgAyACS3JFBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsDQCADIAJNBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsCQCADIA9PDQAgAyAGIAVBEGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBEGogAi0AAhABDAELIAUoAhRBH0sNACAFQRBqIAYgAEECdGotAAIQASAFKAIUQSFJDQAgBUEgNgIUCyABQWwgBUHYAGoQCiAFQUBrEApxIAVBKGoQCnEgBUEQahAKcRshCwwJCwAACwALAAALAAsAAAsACwAACwALQWwhCwsgBUHwAGokACALC7UEAQ5/IwBBEGsiBiQAIAZBBGogABAOQVQhBQJAIARB3AtJDQAgBi0ABCEHIANB8ARqQQBB7AAQECEIIAdBDEsNACADQdwJaiIJIAggBkEIaiAGQQxqIAEgAhAxIhAQA0UEQCAGKAIMIgQgB0sNASADQdwFaiEPIANBpAVqIREgAEEEaiESIANBqAVqIQEgBCEFA0AgBSICQX9qIQUgCCACQQJ0aigCAEUNAAsgAkEBaiEOQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgASALaiAKNgIAIAVBAWohBSAKIAxqIQoMAQsLIAEgCjYCAEEAIQUgBigCCCELA0AgBSALRkUEQCABIAUgCWotAAAiDEECdGoiDSANKAIAIg1BAWo2AgAgDyANQQF0aiINIAw6AAEgDSAFOgAAIAVBAWohBQwBCwtBACEBIANBADYCqAUgBEF/cyAHaiEJQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgAyALaiABNgIAIAwgBSAJanQgAWohASAFQQFqIQUMAQsLIAcgBEEBaiIBIAJrIgRrQQFqIQgDQEEBIQUgBCAIT0UEQANAIAUgDk9FBEAgBUECdCIJIAMgBEE0bGpqIAMgCWooAgAgBHY2AgAgBUEBaiEFDAELCyAEQQFqIQQMAQsLIBIgByAPIAogESADIAIgARBkIAZBAToABSAGIAc6AAYgACAGKAIENgIACyAQIQULIAZBEGokACAFC8ENAQt/IwBB8ABrIgUkAEFsIQkCQCADQQpJDQAgAi8AACEKIAIvAAIhDCACLwAEIQYgBUEIaiAEEA4CQCADIAYgCiAMampBBmoiDUkNACAFLQAKIQcgBUHYAGogAkEGaiICIAoQBiIJEAMNASAFQUBrIAIgCmoiAiAMEAYiCRADDQEgBUEoaiACIAxqIgIgBhAGIgkQAw0BIAVBEGogAiAGaiADIA1rEAYiCRADDQEgACABaiIOQX1qIQ8gBEEEaiEGQQEhCSAAIAFBA2pBAnYiAmoiCiACaiIMIAJqIg0hAyAMIQQgCiECA0AgCSADIA9JcQRAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAACAGIAVBQGsgBxACQQF0aiIILQAAIQsgBUFAayAILQABEAEgAiALOgAAIAYgBUEoaiAHEAJBAXRqIggtAAAhCyAFQShqIAgtAAEQASAEIAs6AAAgBiAFQRBqIAcQAkEBdGoiCC0AACELIAVBEGogCC0AARABIAMgCzoAACAGIAVB2ABqIAcQAkEBdGoiCC0AACELIAVB2ABqIAgtAAEQASAAIAs6AAEgBiAFQUBrIAcQAkEBdGoiCC0AACELIAVBQGsgCC0AARABIAIgCzoAASAGIAVBKGogBxACQQF0aiIILQAAIQsgBUEoaiAILQABEAEgBCALOgABIAYgBUEQaiAHEAJBAXRqIggtAAAhCyAFQRBqIAgtAAEQASADIAs6AAEgA0ECaiEDIARBAmohBCACQQJqIQIgAEECaiEAIAkgBUHYAGoQDUVxIAVBQGsQDUVxIAVBKGoQDUVxIAVBEGoQDUVxIQkMAQsLIAQgDUsgAiAMS3INAEFsIQkgACAKSw0BIApBfWohCQNAIAVB2ABqEAQgACAJT3JFBEAgBiAFQdgAaiAHEAJBAXRqIggtAAAhCyAFQdgAaiAILQABEAEgACALOgAAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAASAAQQJqIQAMAQsLA0AgBUHYAGoQBCAAIApPckUEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCwNAIAAgCkkEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCyAMQX1qIQADQCAFQUBrEAQgAiAAT3JFBEAgBiAFQUBrIAcQAkEBdGoiCi0AACEJIAVBQGsgCi0AARABIAIgCToAACAGIAVBQGsgBxACQQF0aiIKLQAAIQkgBUFAayAKLQABEAEgAiAJOgABIAJBAmohAgwBCwsDQCAFQUBrEAQgAiAMT3JFBEAgBiAFQUBrIAcQAkEBdGoiAC0AACEKIAVBQGsgAC0AARABIAIgCjoAACACQQFqIQIMAQsLA0AgAiAMSQRAIAYgBUFAayAHEAJBAXRqIgAtAAAhCiAFQUBrIAAtAAEQASACIAo6AAAgAkEBaiECDAELCyANQX1qIQADQCAFQShqEAQgBCAAT3JFBEAgBiAFQShqIAcQAkEBdGoiAi0AACEKIAVBKGogAi0AARABIAQgCjoAACAGIAVBKGogBxACQQF0aiICLQAAIQogBUEoaiACLQABEAEgBCAKOgABIARBAmohBAwBCwsDQCAFQShqEAQgBCANT3JFBEAgBiAFQShqIAcQAkEBdGoiAC0AACECIAVBKGogAC0AARABIAQgAjoAACAEQQFqIQQMAQsLA0AgBCANSQRAIAYgBUEoaiAHEAJBAXRqIgAtAAAhAiAFQShqIAAtAAEQASAEIAI6AAAgBEEBaiEEDAELCwNAIAVBEGoQBCADIA9PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIAYgBUEQaiAHEAJBAXRqIgAtAAAhAiAFQRBqIAAtAAEQASADIAI6AAEgA0ECaiEDDAELCwNAIAVBEGoQBCADIA5PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIANBAWohAwwBCwsDQCADIA5JBEAgBiAFQRBqIAcQAkEBdGoiAC0AACECIAVBEGogAC0AARABIAMgAjoAACADQQFqIQMMAQsLIAFBbCAFQdgAahAKIAVBQGsQCnEgBUEoahAKcSAFQRBqEApxGyEJDAELQWwhCQsgBUHwAGokACAJC8oCAQR/IwBBIGsiBSQAIAUgBBAOIAUtAAIhByAFQQhqIAIgAxAGIgIQA0UEQCAEQQRqIQIgACABaiIDQX1qIQQDQCAFQQhqEAQgACAET3JFBEAgAiAFQQhqIAcQAkEBdGoiBi0AACEIIAVBCGogBi0AARABIAAgCDoAACACIAVBCGogBxACQQF0aiIGLQAAIQggBUEIaiAGLQABEAEgACAIOgABIABBAmohAAwBCwsDQCAFQQhqEAQgACADT3JFBEAgAiAFQQhqIAcQAkEBdGoiBC0AACEGIAVBCGogBC0AARABIAAgBjoAACAAQQFqIQAMAQsLA0AgACADT0UEQCACIAVBCGogBxACQQF0aiIELQAAIQYgBUEIaiAELQABEAEgACAGOgAAIABBAWohAAwBCwsgAUFsIAVBCGoQChshAgsgBUEgaiQAIAILtgMBCX8jAEEQayIGJAAgBkEANgIMIAZBADYCCEFUIQQCQAJAIANBQGsiDCADIAZBCGogBkEMaiABIAIQMSICEAMNACAGQQRqIAAQDiAGKAIMIgcgBi0ABEEBaksNASAAQQRqIQogBkEAOgAFIAYgBzoABiAAIAYoAgQ2AgAgB0EBaiEJQQEhBANAIAQgCUkEQCADIARBAnRqIgEoAgAhACABIAU2AgAgACAEQX9qdCAFaiEFIARBAWohBAwBCwsgB0EBaiEHQQAhBSAGKAIIIQkDQCAFIAlGDQEgAyAFIAxqLQAAIgRBAnRqIgBBASAEdEEBdSILIAAoAgAiAWoiADYCACAHIARrIQhBACEEAkAgC0EDTQRAA0AgBCALRg0CIAogASAEakEBdGoiACAIOgABIAAgBToAACAEQQFqIQQMAAALAAsDQCABIABPDQEgCiABQQF0aiIEIAg6AAEgBCAFOgAAIAQgCDoAAyAEIAU6AAIgBCAIOgAFIAQgBToABCAEIAg6AAcgBCAFOgAGIAFBBGohAQwAAAsACyAFQQFqIQUMAAALAAsgAiEECyAGQRBqJAAgBAutAQECfwJAQYQgKAIAIABHIAAoAgBBAXYiAyABa0F4aiICQXhxQQhHcgR/IAIFIAMQJ0UNASACQQhqC0EQSQ0AIAAgACgCACICQQFxIAAgAWpBD2pBeHEiASAAa0EBdHI2AgAgASAANgIEIAEgASgCAEEBcSAAIAJBAXZqIAFrIgJBAXRyNgIAQYQgIAEgAkH/////B3FqQQRqQYQgKAIAIABGGyABNgIAIAEQJQsLygIBBX8CQAJAAkAgAEEIIABBCEsbZ0EfcyAAaUEBR2oiAUEESSAAIAF2cg0AIAFBAnRB/B5qKAIAIgJFDQADQCACQXhqIgMoAgBBAXZBeGoiBSAATwRAIAIgBUEIIAVBCEsbZ0Efc0ECdEGAH2oiASgCAEYEQCABIAIoAgQ2AgALDAMLIARBHksNASAEQQFqIQQgAigCBCICDQALC0EAIQMgAUEgTw0BA0AgAUECdEGAH2ooAgAiAkUEQCABQR5LIQIgAUEBaiEBIAJFDQEMAwsLIAIgAkF4aiIDKAIAQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgBGBEAgASACKAIENgIACwsgAigCACIBBEAgASACKAIENgIECyACKAIEIgEEQCABIAIoAgA2AgALIAMgAygCAEEBcjYCACADIAAQNwsgAwvhCwINfwV+IwBB8ABrIgckACAHIAAoAvDhASIINgJcIAEgAmohDSAIIAAoAoDiAWohDwJAAkAgBUUEQCABIQQMAQsgACgCxOABIRAgACgCwOABIREgACgCvOABIQ4gAEEBNgKM4QFBACEIA0AgCEEDRwRAIAcgCEECdCICaiAAIAJqQazQAWooAgA2AkQgCEEBaiEIDAELC0FsIQwgB0EYaiADIAQQBhADDQEgB0EsaiAHQRhqIAAoAgAQEyAHQTRqIAdBGGogACgCCBATIAdBPGogB0EYaiAAKAIEEBMgDUFgaiESIAEhBEEAIQwDQCAHKAIwIAcoAixBA3RqKQIAIhRCEIinQf8BcSEIIAcoAkAgBygCPEEDdGopAgAiFUIQiKdB/wFxIQsgBygCOCAHKAI0QQN0aikCACIWQiCIpyEJIBVCIIghFyAUQiCIpyECAkAgFkIQiKdB/wFxIgNBAk8EQAJAIAZFIANBGUlyRQRAIAkgB0EYaiADQSAgBygCHGsiCiAKIANLGyIKEAUgAyAKayIDdGohCSAHQRhqEAQaIANFDQEgB0EYaiADEAUgCWohCQwBCyAHQRhqIAMQBSAJaiEJIAdBGGoQBBoLIAcpAkQhGCAHIAk2AkQgByAYNwNIDAELAkAgA0UEQCACBEAgBygCRCEJDAMLIAcoAkghCQwBCwJAAkAgB0EYakEBEAUgCSACRWpqIgNBA0YEQCAHKAJEQX9qIgMgA0VqIQkMAQsgA0ECdCAHaigCRCIJIAlFaiEJIANBAUYNAQsgByAHKAJINgJMCwsgByAHKAJENgJIIAcgCTYCRAsgF6chAyALBEAgB0EYaiALEAUgA2ohAwsgCCALakEUTwRAIAdBGGoQBBoLIAgEQCAHQRhqIAgQBSACaiECCyAHQRhqEAQaIAcgB0EYaiAUQhiIp0H/AXEQCCAUp0H//wNxajYCLCAHIAdBGGogFUIYiKdB/wFxEAggFadB//8DcWo2AjwgB0EYahAEGiAHIAdBGGogFkIYiKdB/wFxEAggFqdB//8DcWo2AjQgByACNgJgIAcoAlwhCiAHIAk2AmggByADNgJkAkACQAJAIAQgAiADaiILaiASSw0AIAIgCmoiEyAPSw0AIA0gBGsgC0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ"; + +// node_modules/three/examples/jsm/math/ColorSpaces.js +var DisplayP3ColorSpace = "display-p3"; +var LinearDisplayP3ColorSpace = "display-p3-linear"; + +// node_modules/three/examples/jsm/loaders/KTX2Loader.js +var _taskCache3 = new WeakMap; +var _activeLoaders = 0; +var _zstd; + +class KTX2Loader extends Loader { + constructor(manager) { + super(manager); + this.transcoderPath = ""; + this.transcoderBinary = null; + this.transcoderPending = null; + this.workerPool = new WorkerPool; + this.workerSourceURL = ""; + this.workerConfig = null; + if (typeof MSC_TRANSCODER !== "undefined") { + console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder".' + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'); + } + } + setTranscoderPath(path) { + this.transcoderPath = path; + return this; + } + setWorkerLimit(num) { + this.workerPool.setWorkerLimit(num); + return this; + } + async detectSupportAsync(renderer2) { + this.workerConfig = { + astcSupported: await renderer2.hasFeatureAsync("texture-compression-astc"), + astcHDRSupported: false, + etc1Supported: await renderer2.hasFeatureAsync("texture-compression-etc1"), + etc2Supported: await renderer2.hasFeatureAsync("texture-compression-etc2"), + dxtSupported: await renderer2.hasFeatureAsync("texture-compression-bc"), + bptcSupported: await renderer2.hasFeatureAsync("texture-compression-bptc"), + pvrtcSupported: await renderer2.hasFeatureAsync("texture-compression-pvrtc") + }; + return this; + } + detectSupport(renderer2) { + if (renderer2.isWebGPURenderer === true) { + this.workerConfig = { + astcSupported: renderer2.hasFeature("texture-compression-astc"), + astcHDRSupported: false, + etc1Supported: renderer2.hasFeature("texture-compression-etc1"), + etc2Supported: renderer2.hasFeature("texture-compression-etc2"), + dxtSupported: renderer2.hasFeature("texture-compression-bc"), + bptcSupported: renderer2.hasFeature("texture-compression-bptc"), + pvrtcSupported: renderer2.hasFeature("texture-compression-pvrtc") + }; + } else { + this.workerConfig = { + astcSupported: renderer2.extensions.has("WEBGL_compressed_texture_astc"), + astcHDRSupported: renderer2.extensions.has("WEBGL_compressed_texture_astc") && renderer2.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"), + etc1Supported: renderer2.extensions.has("WEBGL_compressed_texture_etc1"), + etc2Supported: renderer2.extensions.has("WEBGL_compressed_texture_etc"), + dxtSupported: renderer2.extensions.has("WEBGL_compressed_texture_s3tc"), + bptcSupported: renderer2.extensions.has("EXT_texture_compression_bptc"), + pvrtcSupported: renderer2.extensions.has("WEBGL_compressed_texture_pvrtc") || renderer2.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc") + }; + } + return this; + } + init() { + if (!this.transcoderPending) { + const jsLoader = new FileLoader(this.manager); + jsLoader.setPath(this.transcoderPath); + jsLoader.setWithCredentials(this.withCredentials); + const jsContent = jsLoader.loadAsync("basis_transcoder.js"); + const binaryLoader = new FileLoader(this.manager); + binaryLoader.setPath(this.transcoderPath); + binaryLoader.setResponseType("arraybuffer"); + binaryLoader.setWithCredentials(this.withCredentials); + const binaryContent = binaryLoader.loadAsync("basis_transcoder.wasm"); + this.transcoderPending = Promise.all([jsContent, binaryContent]).then(([jsContent2, binaryContent2]) => { + const fn = KTX2Loader.BasisWorker.toString(); + const body = [ + "/* constants */", + "let _EngineFormat = " + JSON.stringify(KTX2Loader.EngineFormat), + "let _EngineType = " + JSON.stringify(KTX2Loader.EngineType), + "let _TranscoderFormat = " + JSON.stringify(KTX2Loader.TranscoderFormat), + "let _BasisFormat = " + JSON.stringify(KTX2Loader.BasisFormat), + "/* basis_transcoder.js */", + jsContent2, + "/* worker */", + fn.substring(fn.indexOf("{") + 1, fn.lastIndexOf("}")) + ].join(` +`); + this.workerSourceURL = URL.createObjectURL(new Blob([body])); + this.transcoderBinary = binaryContent2; + this.workerPool.setWorkerCreator(() => { + const worker = new Worker(this.workerSourceURL); + const transcoderBinary = this.transcoderBinary.slice(0); + worker.postMessage({ type: "init", config: this.workerConfig, transcoderBinary }, [transcoderBinary]); + return worker; + }); + }); + if (_activeLoaders > 0) { + console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues." + " Use a single KTX2Loader instance, or call .dispose() on old instances."); + } + _activeLoaders++; + } + return this.transcoderPending; + } + load(url, onLoad, onProgress, onError) { + if (this.workerConfig === null) { + throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`."); + } + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setWithCredentials(this.withCredentials); + loader.load(url, (buffer) => { + this.parse(buffer, onLoad, onError); + }, onProgress, onError); + } + parse(buffer, onLoad, onError) { + if (this.workerConfig === null) { + throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`."); + } + if (_taskCache3.has(buffer)) { + const cachedTask = _taskCache3.get(buffer); + return cachedTask.promise.then(onLoad).catch(onError); + } + this._createTexture(buffer).then((texture) => onLoad ? onLoad(texture) : null).catch(onError); + } + _createTextureFrom(transcodeResult, container) { + const { type: messageType, error, data: { faces, width: width2, height: height2, format, type, dfdFlags } } = transcodeResult; + if (messageType === "error") + return Promise.reject(error); + let texture; + if (container.faceCount === 6) { + texture = new CompressedCubeTexture(faces, format, type); + } else { + const mipmaps = faces[0].mipmaps; + texture = container.layerCount > 1 ? new CompressedArrayTexture(mipmaps, width2, height2, container.layerCount, format, type) : new CompressedTexture(mipmaps, width2, height2, format, type); + } + texture.minFilter = faces[0].mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; + texture.magFilter = LinearFilter; + texture.generateMipmaps = false; + texture.needsUpdate = true; + texture.colorSpace = parseColorSpace(container); + texture.premultiplyAlpha = !!(dfdFlags & g); + return texture; + } + async _createTexture(buffer, config = {}) { + const container = Pi2(new Uint8Array(buffer)); + const isBasisHDR = container.vkFormat === pi && container.dataFormatDescriptor[0].colorModel === 167; + const needsTranscoder = container.vkFormat === it || isBasisHDR && !this.workerConfig.astcHDRSupported; + if (!needsTranscoder) { + return createRawTexture(container); + } + const taskConfig = config; + const texturePending = this.init().then(() => { + return this.workerPool.postMessage({ type: "transcode", buffer, taskConfig }, [buffer]); + }).then((e) => this._createTextureFrom(e.data, container)); + _taskCache3.set(buffer, { promise: texturePending }); + return texturePending; + } + dispose() { + this.workerPool.dispose(); + if (this.workerSourceURL) + URL.revokeObjectURL(this.workerSourceURL); + _activeLoaders--; + return this; + } +} +KTX2Loader.BasisFormat = { + ETC1S: 0, + UASTC: 1, + UASTC_HDR: 2 +}; +KTX2Loader.TranscoderFormat = { + ETC1: 0, + ETC2: 1, + BC1: 2, + BC3: 3, + BC4: 4, + BC5: 5, + BC7_M6_OPAQUE_ONLY: 6, + BC7_M5: 7, + PVRTC1_4_RGB: 8, + PVRTC1_4_RGBA: 9, + ASTC_4x4: 10, + ATC_RGB: 11, + ATC_RGBA_INTERPOLATED_ALPHA: 12, + RGBA32: 13, + RGB565: 14, + BGR565: 15, + RGBA4444: 16, + BC6H: 22, + RGB_HALF: 24, + RGBA_HALF: 25 +}; +KTX2Loader.EngineFormat = { + RGBAFormat, + RGBA_ASTC_4x4_Format, + RGB_BPTC_UNSIGNED_Format, + RGBA_BPTC_Format, + RGBA_ETC2_EAC_Format, + RGBA_PVRTC_4BPPV1_Format, + RGBA_S3TC_DXT5_Format, + RGB_ETC1_Format, + RGB_ETC2_Format, + RGB_PVRTC_4BPPV1_Format, + RGBA_S3TC_DXT1_Format +}; +KTX2Loader.EngineType = { + UnsignedByteType, + HalfFloatType, + FloatType +}; +KTX2Loader.BasisWorker = function() { + let config; + let transcoderPending; + let BasisModule; + const EngineFormat = _EngineFormat; + const EngineType = _EngineType; + const TranscoderFormat = _TranscoderFormat; + const BasisFormat = _BasisFormat; + self.addEventListener("message", function(e) { + const message = e.data; + switch (message.type) { + case "init": + config = message.config; + init(message.transcoderBinary); + break; + case "transcode": + transcoderPending.then(() => { + try { + const { faces, buffers, width: width2, height: height2, hasAlpha, format, type, dfdFlags } = transcode(message.buffer); + self.postMessage({ type: "transcode", id: message.id, data: { faces, width: width2, height: height2, hasAlpha, format, type, dfdFlags } }, buffers); + } catch (error) { + console.error(error); + self.postMessage({ type: "error", id: message.id, error: error.message }); + } + }); + break; + } + }); + function init(wasmBinary) { + transcoderPending = new Promise((resolve) => { + BasisModule = { wasmBinary, onRuntimeInitialized: resolve }; + BASIS(BasisModule); + }).then(() => { + BasisModule.initializeBasis(); + if (BasisModule.KTX2File === undefined) { + console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder."); + } + }); + } + function transcode(buffer) { + const ktx2File = new BasisModule.KTX2File(new Uint8Array(buffer)); + function cleanup() { + ktx2File.close(); + ktx2File.delete(); + } + if (!ktx2File.isValid()) { + cleanup(); + throw new Error("THREE.KTX2Loader:\tInvalid or unsupported .ktx2 file"); + } + let basisFormat; + if (ktx2File.isUASTC()) { + basisFormat = BasisFormat.UASTC; + } else if (ktx2File.isETC1S()) { + basisFormat = BasisFormat.ETC1S; + } else if (ktx2File.isHDR()) { + basisFormat = BasisFormat.UASTC_HDR; + } else { + throw new Error("THREE.KTX2Loader: Unknown Basis encoding"); + } + const width2 = ktx2File.getWidth(); + const height2 = ktx2File.getHeight(); + const layerCount = ktx2File.getLayers() || 1; + const levelCount = ktx2File.getLevels(); + const faceCount = ktx2File.getFaces(); + const hasAlpha = ktx2File.getHasAlpha(); + const dfdFlags = ktx2File.getDFDFlags(); + const { transcoderFormat, engineFormat, engineType } = getTranscoderFormat(basisFormat, width2, height2, hasAlpha); + if (!width2 || !height2 || !levelCount) { + cleanup(); + throw new Error("THREE.KTX2Loader:\tInvalid texture"); + } + if (!ktx2File.startTranscoding()) { + cleanup(); + throw new Error("THREE.KTX2Loader: .startTranscoding failed"); + } + const faces = []; + const buffers = []; + for (let face = 0;face < faceCount; face++) { + const mipmaps = []; + for (let mip = 0;mip < levelCount; mip++) { + const layerMips = []; + let mipWidth, mipHeight; + for (let layer = 0;layer < layerCount; layer++) { + const levelInfo = ktx2File.getImageLevelInfo(mip, layer, face); + if (face === 0 && mip === 0 && layer === 0 && (levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0)) { + console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions."); + } + if (levelCount > 1) { + mipWidth = levelInfo.origWidth; + mipHeight = levelInfo.origHeight; + } else { + mipWidth = levelInfo.width; + mipHeight = levelInfo.height; + } + let dst = new Uint8Array(ktx2File.getImageTranscodedSizeInBytes(mip, layer, 0, transcoderFormat)); + const status = ktx2File.transcodeImage(dst, mip, layer, face, transcoderFormat, 0, -1, -1); + if (engineType === EngineType.HalfFloatType) { + dst = new Uint16Array(dst.buffer, dst.byteOffset, dst.byteLength / Uint16Array.BYTES_PER_ELEMENT); + } + if (!status) { + cleanup(); + throw new Error("THREE.KTX2Loader: .transcodeImage failed."); + } + layerMips.push(dst); + } + const mipData = concat(layerMips); + mipmaps.push({ data: mipData, width: mipWidth, height: mipHeight }); + buffers.push(mipData.buffer); + } + faces.push({ mipmaps, width: width2, height: height2, format: engineFormat, type: engineType }); + } + cleanup(); + return { faces, buffers, width: width2, height: height2, hasAlpha, dfdFlags, format: engineFormat, type: engineType }; + } + const FORMAT_OPTIONS = [ + { + if: "astcSupported", + basisFormat: [BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4], + engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: Infinity, + priorityUASTC: 1, + needsPowerOfTwo: false + }, + { + if: "bptcSupported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5], + engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 3, + priorityUASTC: 2, + needsPowerOfTwo: false + }, + { + if: "dxtSupported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3], + engineFormat: [EngineFormat.RGBA_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 4, + priorityUASTC: 5, + needsPowerOfTwo: false + }, + { + if: "etc2Supported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2], + engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 1, + priorityUASTC: 3, + needsPowerOfTwo: false + }, + { + if: "etc1Supported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.ETC1], + engineFormat: [EngineFormat.RGB_ETC1_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 2, + priorityUASTC: 4, + needsPowerOfTwo: false + }, + { + if: "pvrtcSupported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA], + engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 5, + priorityUASTC: 6, + needsPowerOfTwo: true + }, + { + if: "bptcSupported", + basisFormat: [BasisFormat.UASTC_HDR], + transcoderFormat: [TranscoderFormat.BC6H], + engineFormat: [EngineFormat.RGB_BPTC_UNSIGNED_Format], + engineType: [EngineType.HalfFloatType], + priorityHDR: 1, + needsPowerOfTwo: false + }, + { + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.RGBA32, TranscoderFormat.RGBA32], + engineFormat: [EngineFormat.RGBAFormat, EngineFormat.RGBAFormat], + engineType: [EngineType.UnsignedByteType, EngineType.UnsignedByteType], + priorityETC1S: 100, + priorityUASTC: 100, + needsPowerOfTwo: false + }, + { + basisFormat: [BasisFormat.UASTC_HDR], + transcoderFormat: [TranscoderFormat.RGBA_HALF], + engineFormat: [EngineFormat.RGBAFormat], + engineType: [EngineType.HalfFloatType], + priorityHDR: 100, + needsPowerOfTwo: false + } + ]; + const OPTIONS = { + [BasisFormat.ETC1S]: FORMAT_OPTIONS.filter((opt) => opt.basisFormat.includes(BasisFormat.ETC1S)).sort((a, b) => a.priorityUASTC - b.priorityUASTC), + [BasisFormat.UASTC]: FORMAT_OPTIONS.filter((opt) => opt.basisFormat.includes(BasisFormat.UASTC)).sort((a, b) => a.priorityUASTC - b.priorityUASTC), + [BasisFormat.UASTC_HDR]: FORMAT_OPTIONS.filter((opt) => opt.basisFormat.includes(BasisFormat.UASTC_HDR)).sort((a, b) => a.priorityHDR - b.priorityHDR) + }; + function getTranscoderFormat(basisFormat, width2, height2, hasAlpha) { + const options = OPTIONS[basisFormat]; + for (let i = 0;i < options.length; i++) { + const opt = options[i]; + if (opt.if && !config[opt.if]) + continue; + if (!opt.basisFormat.includes(basisFormat)) + continue; + if (hasAlpha && opt.transcoderFormat.length < 2) + continue; + if (opt.needsPowerOfTwo && !(isPowerOfTwo2(width2) && isPowerOfTwo2(height2))) + continue; + const transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0]; + const engineFormat = opt.engineFormat[hasAlpha ? 1 : 0]; + const engineType = opt.engineType[0]; + return { transcoderFormat, engineFormat, engineType }; + } + throw new Error("THREE.KTX2Loader: Failed to identify transcoding target."); + } + function isPowerOfTwo2(value2) { + if (value2 <= 2) + return true; + return (value2 & value2 - 1) === 0 && value2 !== 0; + } + function concat(arrays) { + if (arrays.length === 1) + return arrays[0]; + let totalByteLength = 0; + for (let i = 0;i < arrays.length; i++) { + const array = arrays[i]; + totalByteLength += array.byteLength; + } + const result = new Uint8Array(totalByteLength); + let byteOffset = 0; + for (let i = 0;i < arrays.length; i++) { + const array = arrays[i]; + result.set(array, byteOffset); + byteOffset += array.byteLength; + } + return result; + } +}; +var UNCOMPRESSED_FORMATS = new Set([RGBAFormat, RGFormat, RedFormat]); +var FORMAT_MAP = { + [Ae]: RGBAFormat, + [ge]: RGBAFormat, + [Ft]: RGBAFormat, + [Ct]: RGBAFormat, + [we]: RGFormat, + [ae2]: RGFormat, + [xt2]: RGFormat, + [wt]: RGFormat, + [ue2]: RedFormat, + [te2]: RedFormat, + [yt]: RedFormat, + [ct]: RedFormat, + [pi]: RGBA_ASTC_4x4_Format, + [Sn]: RGBA_ASTC_6x6_Format, + [In]: RGBA_ASTC_6x6_Format +}; +var TYPE_MAP = { + [Ae]: FloatType, + [ge]: HalfFloatType, + [Ft]: UnsignedByteType, + [Ct]: UnsignedByteType, + [we]: FloatType, + [ae2]: HalfFloatType, + [xt2]: UnsignedByteType, + [wt]: UnsignedByteType, + [ue2]: FloatType, + [te2]: HalfFloatType, + [yt]: UnsignedByteType, + [ct]: UnsignedByteType, + [pi]: HalfFloatType, + [Sn]: UnsignedByteType, + [In]: UnsignedByteType +}; +async function createRawTexture(container) { + const { vkFormat } = container; + if (FORMAT_MAP[vkFormat] === undefined) { + throw new Error("THREE.KTX2Loader: Unsupported vkFormat."); + } + let zstd; + if (container.supercompressionScheme === n) { + if (!_zstd) { + _zstd = new Promise(async (resolve) => { + const zstd2 = new Q; + await zstd2.init(); + resolve(zstd2); + }); + } + zstd = await _zstd; + } + const mipmaps = []; + for (let levelIndex = 0;levelIndex < container.levels.length; levelIndex++) { + const levelWidth = Math.max(1, container.pixelWidth >> levelIndex); + const levelHeight = Math.max(1, container.pixelHeight >> levelIndex); + const levelDepth = container.pixelDepth ? Math.max(1, container.pixelDepth >> levelIndex) : 0; + const level = container.levels[levelIndex]; + let levelData; + if (container.supercompressionScheme === t) { + levelData = level.levelData; + } else if (container.supercompressionScheme === n) { + levelData = zstd.decode(level.levelData, level.uncompressedByteLength); + } else { + throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme."); + } + let data2; + if (TYPE_MAP[vkFormat] === FloatType) { + data2 = new Float32Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Float32Array.BYTES_PER_ELEMENT); + } else if (TYPE_MAP[vkFormat] === HalfFloatType) { + data2 = new Uint16Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT); + } else { + data2 = levelData; + } + mipmaps.push({ + data: data2, + width: levelWidth, + height: levelHeight, + depth: levelDepth + }); + } + let texture; + if (UNCOMPRESSED_FORMATS.has(FORMAT_MAP[vkFormat])) { + texture = container.pixelDepth === 0 ? new DataTexture(mipmaps[0].data, container.pixelWidth, container.pixelHeight) : new Data3DTexture(mipmaps[0].data, container.pixelWidth, container.pixelHeight, container.pixelDepth); + } else { + if (container.pixelDepth > 0) + throw new Error("THREE.KTX2Loader: Unsupported pixelDepth."); + texture = new CompressedTexture(mipmaps, container.pixelWidth, container.pixelHeight); + texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; + texture.magFilter = LinearFilter; + } + texture.mipmaps = mipmaps; + texture.type = TYPE_MAP[vkFormat]; + texture.format = FORMAT_MAP[vkFormat]; + texture.colorSpace = parseColorSpace(container); + texture.needsUpdate = true; + return Promise.resolve(texture); +} +function parseColorSpace(container) { + const dfd = container.dataFormatDescriptor[0]; + if (dfd.colorPrimaries === C2) { + return dfd.transferFunction === u ? SRGBColorSpace : LinearSRGBColorSpace; + } else if (dfd.colorPrimaries === R) { + return dfd.transferFunction === u ? DisplayP3ColorSpace : LinearDisplayP3ColorSpace; + } else if (dfd.colorPrimaries === T) { + return NoColorSpace; + } else { + console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${dfd.colorPrimaries}"`); + return NoColorSpace; + } +} +// node_modules/three/examples/jsm/loaders/KTXLoader.js +var HEADER_LEN = 12 + 13 * 4; +// node_modules/three/examples/jsm/loaders/LDrawLoader.js +var _tempVec0 = new Vector3; +var _tempVec1 = new Vector3; +var _ray3 = new Ray; +// node_modules/three/examples/jsm/libs/lottie_canvas.module.js +var exports_lottie_canvas_module = {}; +__export(exports_lottie_canvas_module, { + default: () => lottie +}); +var lottie = {}; +if (typeof document !== "undefined") { + function createTag(type) { + return document.createElement(type); + } + function extendPrototype(sources, destination) { + var i; + var len = sources.length; + var sourcePrototype; + for (i = 0;i < len; i += 1) { + sourcePrototype = sources[i].prototype; + for (var attr in sourcePrototype) { + if (Object.prototype.hasOwnProperty.call(sourcePrototype, attr)) + destination.prototype[attr] = sourcePrototype[attr]; + } + } + } + function getDescriptor(object, prop) { + return Object.getOwnPropertyDescriptor(object, prop); + } + function createProxyFunction(prototype) { + function ProxyFunction() { + } + ProxyFunction.prototype = prototype; + return ProxyFunction; + } + function createSizedArray(len) { + return Array.apply(null, { length: len }); + } + function ProjectInterface$1() { + return {}; + } + function roundValues(flag) { + _shouldRoundValues = !!flag; + } + function bmRnd(value2) { + if (_shouldRoundValues) { + return Math.round(value2); + } + return value2; + } + function styleDiv(element) { + element.style.position = "absolute"; + element.style.top = 0; + element.style.left = 0; + element.style.display = "block"; + element.style.transformOrigin = "0 0"; + element.style.webkitTransformOrigin = "0 0"; + element.style.backfaceVisibility = "visible"; + element.style.webkitBackfaceVisibility = "visible"; + element.style.transformStyle = "preserve-3d"; + element.style.webkitTransformStyle = "preserve-3d"; + element.style.mozTransformStyle = "preserve-3d"; + } + function BMEnterFrameEvent(type, currentTime, totalTime, frameMultiplier) { + this.type = type; + this.currentTime = currentTime; + this.totalTime = totalTime; + this.direction = frameMultiplier < 0 ? -1 : 1; + } + function BMCompleteEvent(type, frameMultiplier) { + this.type = type; + this.direction = frameMultiplier < 0 ? -1 : 1; + } + function BMCompleteLoopEvent(type, totalLoops, currentLoop, frameMultiplier) { + this.type = type; + this.currentLoop = currentLoop; + this.totalLoops = totalLoops; + this.direction = frameMultiplier < 0 ? -1 : 1; + } + function BMSegmentStartEvent(type, firstFrame, totalFrames) { + this.type = type; + this.firstFrame = firstFrame; + this.totalFrames = totalFrames; + } + function BMDestroyEvent(type, target) { + this.type = type; + this.target = target; + } + function BMRenderFrameErrorEvent(nativeError, currentTime) { + this.type = "renderFrameError"; + this.nativeError = nativeError; + this.currentTime = currentTime; + } + function BMConfigErrorEvent(nativeError) { + this.type = "configError"; + this.nativeError = nativeError; + } + function BMAnimationConfigErrorEvent(type, nativeError) { + this.type = type; + this.nativeError = nativeError; + } + function HSVtoRGB(h, s, v) { + var r; + var g3; + var b; + var i; + var f; + var p; + var q2; + var t2; + i = Math.floor(h * 6); + f = h * 6 - i; + p = v * (1 - s); + q2 = v * (1 - f * s); + t2 = v * (1 - (1 - f) * s); + switch (i % 6) { + case 0: + r = v; + g3 = t2; + b = p; + break; + case 1: + r = q2; + g3 = v; + b = p; + break; + case 2: + r = p; + g3 = v; + b = t2; + break; + case 3: + r = p; + g3 = q2; + b = v; + break; + case 4: + r = t2; + g3 = p; + b = v; + break; + case 5: + r = v; + g3 = p; + b = q2; + break; + default: + break; + } + return [ + r, + g3, + b + ]; + } + function RGBtoHSV(r, g3, b) { + var max = Math.max(r, g3, b); + var min = Math.min(r, g3, b); + var d = max - min; + var h; + var s = max === 0 ? 0 : d / max; + var v = max / 255; + switch (max) { + case min: + h = 0; + break; + case r: + h = g3 - b + d * (g3 < b ? 6 : 0); + h /= 6 * d; + break; + case g3: + h = b - r + d * 2; + h /= 6 * d; + break; + case b: + h = r - g3 + d * 4; + h /= 6 * d; + break; + default: + break; + } + return [ + h, + s, + v + ]; + } + function addSaturationToRGB(color, offset) { + var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255); + hsv[1] += offset; + if (hsv[1] > 1) { + hsv[1] = 1; + } else if (hsv[1] <= 0) { + hsv[1] = 0; + } + return HSVtoRGB(hsv[0], hsv[1], hsv[2]); + } + function addBrightnessToRGB(color, offset) { + var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255); + hsv[2] += offset; + if (hsv[2] > 1) { + hsv[2] = 1; + } else if (hsv[2] < 0) { + hsv[2] = 0; + } + return HSVtoRGB(hsv[0], hsv[1], hsv[2]); + } + function addHueToRGB(color, offset) { + var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255); + hsv[0] += offset / 360; + if (hsv[0] > 1) { + hsv[0] -= 1; + } else if (hsv[0] < 0) { + hsv[0] += 1; + } + return HSVtoRGB(hsv[0], hsv[1], hsv[2]); + } + function createNS(type) { + return document.createElementNS(svgNS, type); + } + function BaseEvent() { + } + function getRenderer(key2) { + return renderers[key2]; + } + function bezFunction() { + var math = Math; + function pointOnLine2D(x1, y1, x2, y2, x3, y3) { + var det1 = x1 * y2 + y1 * x3 + x2 * y3 - x3 * y2 - y3 * x1 - x2 * y1; + return det1 > -0.001 && det1 < 0.001; + } + function pointOnLine3D(x1, y1, z1, x2, y2, z2, x3, y3, z3) { + if (z1 === 0 && z2 === 0 && z3 === 0) { + return pointOnLine2D(x1, y1, x2, y2, x3, y3); + } + var dist1 = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2) + math.pow(z2 - z1, 2)); + var dist2 = math.sqrt(math.pow(x3 - x1, 2) + math.pow(y3 - y1, 2) + math.pow(z3 - z1, 2)); + var dist3 = math.sqrt(math.pow(x3 - x2, 2) + math.pow(y3 - y2, 2) + math.pow(z3 - z2, 2)); + var diffDist; + if (dist1 > dist2) { + if (dist1 > dist3) { + diffDist = dist1 - dist2 - dist3; + } else { + diffDist = dist3 - dist2 - dist1; + } + } else if (dist3 > dist2) { + diffDist = dist3 - dist2 - dist1; + } else { + diffDist = dist2 - dist1 - dist3; + } + return diffDist > -0.0001 && diffDist < 0.0001; + } + var getBezierLength = function() { + return function(pt1, pt2, pt3, pt4) { + var curveSegments = getDefaultCurveSegments(); + var k2; + var i; + var len; + var ptCoord; + var perc; + var addedLength = 0; + var ptDistance; + var point = []; + var lastPoint = []; + var lengthData = bezierLengthPool.newElement(); + len = pt3.length; + for (k2 = 0;k2 < curveSegments; k2 += 1) { + perc = k2 / (curveSegments - 1); + ptDistance = 0; + for (i = 0;i < len; i += 1) { + ptCoord = bmPow(1 - perc, 3) * pt1[i] + 3 * bmPow(1 - perc, 2) * perc * pt3[i] + 3 * (1 - perc) * bmPow(perc, 2) * pt4[i] + bmPow(perc, 3) * pt2[i]; + point[i] = ptCoord; + if (lastPoint[i] !== null) { + ptDistance += bmPow(point[i] - lastPoint[i], 2); + } + lastPoint[i] = point[i]; + } + if (ptDistance) { + ptDistance = bmSqrt(ptDistance); + addedLength += ptDistance; + } + lengthData.percents[k2] = perc; + lengthData.lengths[k2] = addedLength; + } + lengthData.addedLength = addedLength; + return lengthData; + }; + }(); + function getSegmentsLength(shapeData) { + var segmentsLength = segmentsLengthPool.newElement(); + var closed = shapeData.c; + var pathV = shapeData.v; + var pathO = shapeData.o; + var pathI = shapeData.i; + var i; + var len = shapeData._length; + var lengths = segmentsLength.lengths; + var totalLength = 0; + for (i = 0;i < len - 1; i += 1) { + lengths[i] = getBezierLength(pathV[i], pathV[i + 1], pathO[i], pathI[i + 1]); + totalLength += lengths[i].addedLength; + } + if (closed && len) { + lengths[i] = getBezierLength(pathV[i], pathV[0], pathO[i], pathI[0]); + totalLength += lengths[i].addedLength; + } + segmentsLength.totalLength = totalLength; + return segmentsLength; + } + function BezierData(length2) { + this.segmentLength = 0; + this.points = new Array(length2); + } + function PointData(partial2, point) { + this.partialLength = partial2; + this.point = point; + } + var buildBezierData = function() { + var storedData = {}; + return function(pt1, pt2, pt3, pt4) { + var bezierName = (pt1[0] + "_" + pt1[1] + "_" + pt2[0] + "_" + pt2[1] + "_" + pt3[0] + "_" + pt3[1] + "_" + pt4[0] + "_" + pt4[1]).replace(/\./g, "p"); + if (!storedData[bezierName]) { + var curveSegments = getDefaultCurveSegments(); + var k2; + var i; + var len; + var ptCoord; + var perc; + var addedLength = 0; + var ptDistance; + var point; + var lastPoint = null; + if (pt1.length === 2 && (pt1[0] !== pt2[0] || pt1[1] !== pt2[1]) && pointOnLine2D(pt1[0], pt1[1], pt2[0], pt2[1], pt1[0] + pt3[0], pt1[1] + pt3[1]) && pointOnLine2D(pt1[0], pt1[1], pt2[0], pt2[1], pt2[0] + pt4[0], pt2[1] + pt4[1])) { + curveSegments = 2; + } + var bezierData = new BezierData(curveSegments); + len = pt3.length; + for (k2 = 0;k2 < curveSegments; k2 += 1) { + point = createSizedArray(len); + perc = k2 / (curveSegments - 1); + ptDistance = 0; + for (i = 0;i < len; i += 1) { + ptCoord = bmPow(1 - perc, 3) * pt1[i] + 3 * bmPow(1 - perc, 2) * perc * (pt1[i] + pt3[i]) + 3 * (1 - perc) * bmPow(perc, 2) * (pt2[i] + pt4[i]) + bmPow(perc, 3) * pt2[i]; + point[i] = ptCoord; + if (lastPoint !== null) { + ptDistance += bmPow(point[i] - lastPoint[i], 2); + } + } + ptDistance = bmSqrt(ptDistance); + addedLength += ptDistance; + bezierData.points[k2] = new PointData(ptDistance, point); + lastPoint = point; + } + bezierData.segmentLength = addedLength; + storedData[bezierName] = bezierData; + } + return storedData[bezierName]; + }; + }(); + function getDistancePerc(perc, bezierData) { + var percents = bezierData.percents; + var lengths = bezierData.lengths; + var len = percents.length; + var initPos = bmFloor((len - 1) * perc); + var lengthPos = perc * bezierData.addedLength; + var lPerc = 0; + if (initPos === len - 1 || initPos === 0 || lengthPos === lengths[initPos]) { + return percents[initPos]; + } + var dir = lengths[initPos] > lengthPos ? -1 : 1; + var flag = true; + while (flag) { + if (lengths[initPos] <= lengthPos && lengths[initPos + 1] > lengthPos) { + lPerc = (lengthPos - lengths[initPos]) / (lengths[initPos + 1] - lengths[initPos]); + flag = false; + } else { + initPos += dir; + } + if (initPos < 0 || initPos >= len - 1) { + if (initPos === len - 1) { + return percents[initPos]; + } + flag = false; + } + } + return percents[initPos] + (percents[initPos + 1] - percents[initPos]) * lPerc; + } + function getPointInSegment(pt1, pt2, pt3, pt4, percent, bezierData) { + var t1 = getDistancePerc(percent, bezierData); + var u1 = 1 - t1; + var ptX = math.round((u1 * u1 * u1 * pt1[0] + (t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1) * pt3[0] + (t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1) * pt4[0] + t1 * t1 * t1 * pt2[0]) * 1000) / 1000; + var ptY = math.round((u1 * u1 * u1 * pt1[1] + (t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1) * pt3[1] + (t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1) * pt4[1] + t1 * t1 * t1 * pt2[1]) * 1000) / 1000; + return [ptX, ptY]; + } + var bezierSegmentPoints = createTypedArray("float32", 8); + function getNewSegment(pt1, pt2, pt3, pt4, startPerc, endPerc, bezierData) { + if (startPerc < 0) { + startPerc = 0; + } else if (startPerc > 1) { + startPerc = 1; + } + var t0 = getDistancePerc(startPerc, bezierData); + endPerc = endPerc > 1 ? 1 : endPerc; + var t1 = getDistancePerc(endPerc, bezierData); + var i; + var len = pt1.length; + var u0 = 1 - t0; + var u1 = 1 - t1; + var u0u0u0 = u0 * u0 * u0; + var t0u0u0_3 = t0 * u0 * u0 * 3; + var t0t0u0_3 = t0 * t0 * u0 * 3; + var t0t0t0 = t0 * t0 * t0; + var u0u0u1 = u0 * u0 * u1; + var t0u0u1_3 = t0 * u0 * u1 + u0 * t0 * u1 + u0 * u0 * t1; + var t0t0u1_3 = t0 * t0 * u1 + u0 * t0 * t1 + t0 * u0 * t1; + var t0t0t1 = t0 * t0 * t1; + var u0u1u1 = u0 * u1 * u1; + var t0u1u1_3 = t0 * u1 * u1 + u0 * t1 * u1 + u0 * u1 * t1; + var t0t1u1_3 = t0 * t1 * u1 + u0 * t1 * t1 + t0 * u1 * t1; + var t0t1t1 = t0 * t1 * t1; + var u1u1u1 = u1 * u1 * u1; + var t1u1u1_3 = t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1; + var t1t1u1_3 = t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1; + var t1t1t1 = t1 * t1 * t1; + for (i = 0;i < len; i += 1) { + bezierSegmentPoints[i * 4] = math.round((u0u0u0 * pt1[i] + t0u0u0_3 * pt3[i] + t0t0u0_3 * pt4[i] + t0t0t0 * pt2[i]) * 1000) / 1000; + bezierSegmentPoints[i * 4 + 1] = math.round((u0u0u1 * pt1[i] + t0u0u1_3 * pt3[i] + t0t0u1_3 * pt4[i] + t0t0t1 * pt2[i]) * 1000) / 1000; + bezierSegmentPoints[i * 4 + 2] = math.round((u0u1u1 * pt1[i] + t0u1u1_3 * pt3[i] + t0t1u1_3 * pt4[i] + t0t1t1 * pt2[i]) * 1000) / 1000; + bezierSegmentPoints[i * 4 + 3] = math.round((u1u1u1 * pt1[i] + t1u1u1_3 * pt3[i] + t1t1u1_3 * pt4[i] + t1t1t1 * pt2[i]) * 1000) / 1000; + } + return bezierSegmentPoints; + } + return { + getSegmentsLength, + getNewSegment, + getPointInSegment, + buildBezierData, + pointOnLine2D, + pointOnLine3D + }; + } + function DynamicPropertyContainer() { + } + function ShapePath() { + this.c = false; + this._length = 0; + this._maxLength = 8; + this.v = createSizedArray(this._maxLength); + this.o = createSizedArray(this._maxLength); + this.i = createSizedArray(this._maxLength); + } + function ShapeCollection() { + this._length = 0; + this._maxLength = 4; + this.shapes = createSizedArray(this._maxLength); + } + function setLocation(href) { + setLocationHref(href); + } + function searchAnimations() { + if (standalone === true) { + animationManager.searchAnimations(animationData, standalone, renderer); + } else { + animationManager.searchAnimations(); + } + } + function setSubframeRendering(flag) { + setSubframeEnabled(flag); + } + function setPrefix(prefix) { + setIdPrefix(prefix); + } + function loadAnimation(params) { + if (standalone === true) { + params.animationData = JSON.parse(animationData); + } + return animationManager.loadAnimation(params); + } + function setQuality(value2) { + if (typeof value2 === "string") { + switch (value2) { + case "high": + setDefaultCurveSegments(200); + break; + default: + case "medium": + setDefaultCurveSegments(50); + break; + case "low": + setDefaultCurveSegments(10); + break; + } + } else if (!isNaN(value2) && value2 > 1) { + setDefaultCurveSegments(value2); + } + if (getDefaultCurveSegments() >= 50) { + roundValues(false); + } else { + roundValues(true); + } + } + function inBrowser() { + return typeof navigator !== "undefined"; + } + function installPlugin(type, plugin) { + if (type === "expressions") { + setExpressionsPlugin(plugin); + } + } + function getFactory(name2) { + switch (name2) { + case "propertyFactory": + return PropertyFactory; + case "shapePropertyFactory": + return ShapePropertyFactory; + case "matrix": + return Matrix; + default: + return null; + } + } + function checkReady() { + if (document.readyState === "complete") { + clearInterval(readyStateCheckInterval); + searchAnimations(); + } + } + function getQueryVariable(variable) { + var vars = queryString.split("&"); + for (var i = 0;i < vars.length; i += 1) { + var pair = vars[i].split("="); + if (decodeURIComponent(pair[0]) == variable) { + return decodeURIComponent(pair[1]); + } + } + return null; + } + function ShapeModifier() { + } + function TrimModifier() { + } + function PuckerAndBloatModifier() { + } + function RepeaterModifier() { + } + function RoundCornersModifier() { + } + function getFontProperties(fontData) { + var styles = fontData.fStyle ? fontData.fStyle.split(" ") : []; + var fWeight = "normal"; + var fStyle = "normal"; + var len = styles.length; + var styleName; + for (var i = 0;i < len; i += 1) { + styleName = styles[i].toLowerCase(); + switch (styleName) { + case "italic": + fStyle = "italic"; + break; + case "bold": + fWeight = "700"; + break; + case "black": + fWeight = "900"; + break; + case "medium": + fWeight = "500"; + break; + case "regular": + case "normal": + fWeight = "400"; + break; + case "light": + case "thin": + fWeight = "200"; + break; + default: + break; + } + } + return { + style: fStyle, + weight: fontData.fWeight || fWeight + }; + } + function RenderableElement() { + } + function SliderEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function AngleEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function ColorEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 1, 0, container); + } + function PointEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 1, 0, container); + } + function LayerIndexEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function MaskIndexEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function CheckboxEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function NoValueEffect() { + this.p = {}; + } + function EffectsManager(data2, element) { + var effects = data2.ef || []; + this.effectElements = []; + var i; + var len = effects.length; + var effectItem; + for (i = 0;i < len; i += 1) { + effectItem = new GroupEffect(effects[i], element); + this.effectElements.push(effectItem); + } + } + function GroupEffect(data2, element) { + this.init(data2, element); + } + function BaseElement() { + } + function FrameElement() { + } + function FootageElement(data2, globalData2, comp2) { + this.initFrame(); + this.initRenderable(); + this.assetData = globalData2.getAssetData(data2.refId); + this.footageData = globalData2.imageLoader.getAsset(this.assetData); + this.initBaseData(data2, globalData2, comp2); + } + function AudioElement(data2, globalData2, comp2) { + this.initFrame(); + this.initRenderable(); + this.assetData = globalData2.getAssetData(data2.refId); + this.initBaseData(data2, globalData2, comp2); + this._isPlaying = false; + this._canPlay = false; + var assetPath = this.globalData.getAssetsPath(this.assetData); + this.audio = this.globalData.audioController.createAudio(assetPath); + this._currentTime = 0; + this.globalData.audioController.addAudio(this); + this._volumeMultiplier = 1; + this._volume = 1; + this._previousVolume = null; + this.tm = data2.tm ? PropertyFactory.getProp(this, data2.tm, 0, globalData2.frameRate, this) : { _placeholder: true }; + this.lv = PropertyFactory.getProp(this, data2.au && data2.au.lv ? data2.au.lv : { k: [100] }, 1, 0.01, this); + } + function BaseRenderer() { + } + function TransformElement() { + } + function MaskElement(data2, element, globalData2) { + this.data = data2; + this.element = element; + this.globalData = globalData2; + this.storedData = []; + this.masksProperties = this.data.masksProperties || []; + this.maskElement = null; + var defs = this.globalData.defs; + var i; + var len = this.masksProperties ? this.masksProperties.length : 0; + this.viewData = createSizedArray(len); + this.solidPath = ""; + var path; + var properties = this.masksProperties; + var count = 0; + var currentMasks = []; + var j2; + var jLen; + var layerId = createElementID(); + var rect; + var expansor; + var feMorph; + var x2; + var maskType = "clipPath"; + var maskRef = "clip-path"; + for (i = 0;i < len; i += 1) { + if (properties[i].mode !== "a" && properties[i].mode !== "n" || properties[i].inv || properties[i].o.k !== 100 || properties[i].o.x) { + maskType = "mask"; + maskRef = "mask"; + } + if ((properties[i].mode === "s" || properties[i].mode === "i") && count === 0) { + rect = createNS("rect"); + rect.setAttribute("fill", "#ffffff"); + rect.setAttribute("width", this.element.comp.data.w || 0); + rect.setAttribute("height", this.element.comp.data.h || 0); + currentMasks.push(rect); + } else { + rect = null; + } + path = createNS("path"); + if (properties[i].mode === "n") { + this.viewData[i] = { + op: PropertyFactory.getProp(this.element, properties[i].o, 0, 0.01, this.element), + prop: ShapePropertyFactory.getShapeProp(this.element, properties[i], 3), + elem: path, + lastPath: "" + }; + defs.appendChild(path); + } else { + count += 1; + path.setAttribute("fill", properties[i].mode === "s" ? "#000000" : "#ffffff"); + path.setAttribute("clip-rule", "nonzero"); + var filterID; + if (properties[i].x.k !== 0) { + maskType = "mask"; + maskRef = "mask"; + x2 = PropertyFactory.getProp(this.element, properties[i].x, 0, null, this.element); + filterID = createElementID(); + expansor = createNS("filter"); + expansor.setAttribute("id", filterID); + feMorph = createNS("feMorphology"); + feMorph.setAttribute("operator", "erode"); + feMorph.setAttribute("in", "SourceGraphic"); + feMorph.setAttribute("radius", "0"); + expansor.appendChild(feMorph); + defs.appendChild(expansor); + path.setAttribute("stroke", properties[i].mode === "s" ? "#000000" : "#ffffff"); + } else { + feMorph = null; + x2 = null; + } + this.storedData[i] = { + elem: path, + x: x2, + expan: feMorph, + lastPath: "", + lastOperator: "", + filterId: filterID, + lastRadius: 0 + }; + if (properties[i].mode === "i") { + jLen = currentMasks.length; + var g3 = createNS("g"); + for (j2 = 0;j2 < jLen; j2 += 1) { + g3.appendChild(currentMasks[j2]); + } + var mask2 = createNS("mask"); + mask2.setAttribute("mask-type", "alpha"); + mask2.setAttribute("id", layerId + "_" + count); + mask2.appendChild(path); + defs.appendChild(mask2); + g3.setAttribute("mask", "url(" + getLocationHref() + "#" + layerId + "_" + count + ")"); + currentMasks.length = 0; + currentMasks.push(g3); + } else { + currentMasks.push(path); + } + if (properties[i].inv && !this.solidPath) { + this.solidPath = this.createLayerSolidPath(); + } + this.viewData[i] = { + elem: path, + lastPath: "", + op: PropertyFactory.getProp(this.element, properties[i].o, 0, 0.01, this.element), + prop: ShapePropertyFactory.getShapeProp(this.element, properties[i], 3), + invRect: rect + }; + if (!this.viewData[i].prop.k) { + this.drawPath(properties[i], this.viewData[i].prop.v, this.viewData[i]); + } + } + } + this.maskElement = createNS(maskType); + len = currentMasks.length; + for (i = 0;i < len; i += 1) { + this.maskElement.appendChild(currentMasks[i]); + } + if (count > 0) { + this.maskElement.setAttribute("id", layerId); + this.element.maskedElement.setAttribute(maskRef, "url(" + getLocationHref() + "#" + layerId + ")"); + defs.appendChild(this.maskElement); + } + if (this.viewData.length) { + this.element.addRenderableComponent(this); + } + } + function SVGEffects(elem2) { + var i; + var source = "SourceGraphic"; + var len = elem2.data.ef ? elem2.data.ef.length : 0; + var filId = createElementID(); + var fil = filtersFactory.createFilter(filId, true); + var count = 0; + this.filters = []; + var filterManager; + for (i = 0;i < len; i += 1) { + filterManager = null; + var type = elem2.data.ef[i].ty; + if (registeredEffects[type]) { + var Effect = registeredEffects[type].effect; + filterManager = new Effect(fil, elem2.effectsManager.effectElements[i], elem2, idPrefix + count, source); + source = idPrefix + count; + if (registeredEffects[type].countsAsEffect) { + count += 1; + } + } + if (filterManager) { + this.filters.push(filterManager); + } + } + if (count) { + elem2.globalData.defs.appendChild(fil); + elem2.layerElement.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")"); + } + if (this.filters.length) { + elem2.addRenderableComponent(this); + } + } + function registerEffect(id, effect2, countsAsEffect) { + registeredEffects[id] = { + effect: effect2, + countsAsEffect + }; + } + function SVGBaseElement() { + } + function HierarchyElement() { + } + function RenderableDOMElement() { + } + function IImageElement(data2, globalData2, comp2) { + this.assetData = globalData2.getAssetData(data2.refId); + this.initElement(data2, globalData2, comp2); + this.sourceRect = { + top: 0, + left: 0, + width: this.assetData.w, + height: this.assetData.h + }; + } + function ProcessedElement(element, position2) { + this.elem = element; + this.pos = position2; + } + function IShapeElement() { + } + function SVGShapeData(transformers, level, shape) { + this.caches = []; + this.styles = []; + this.transformers = transformers; + this.lStr = ""; + this.sh = shape; + this.lvl = level; + this._isAnimated = !!shape.k; + var i = 0; + var len = transformers.length; + while (i < len) { + if (transformers[i].mProps.dynamicProperties.length) { + this._isAnimated = true; + break; + } + i += 1; + } + } + function SVGStyleData(data2, level) { + this.data = data2; + this.type = data2.ty; + this.d = ""; + this.lvl = level; + this._mdf = false; + this.closed = data2.hd === true; + this.pElem = createNS("path"); + this.msElem = null; + } + function DashProperty(elem2, data2, renderer2, container) { + this.elem = elem2; + this.frameId = -1; + this.dataProps = createSizedArray(data2.length); + this.renderer = renderer2; + this.k = false; + this.dashStr = ""; + this.dashArray = createTypedArray("float32", data2.length ? data2.length - 1 : 0); + this.dashoffset = createTypedArray("float32", 1); + this.initDynamicPropertyContainer(container); + var i; + var len = data2.length || 0; + var prop; + for (i = 0;i < len; i += 1) { + prop = PropertyFactory.getProp(elem2, data2[i].v, 0, 0, this); + this.k = prop.k || this.k; + this.dataProps[i] = { n: data2[i].n, p: prop }; + } + if (!this.k) { + this.getValue(true); + } + this._isAnimated = this.k; + } + function SVGStrokeStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, this); + this.w = PropertyFactory.getProp(elem2, data2.w, 0, null, this); + this.d = new DashProperty(elem2, data2.d || {}, "svg", this); + this.c = PropertyFactory.getProp(elem2, data2.c, 1, 255, this); + this.style = styleOb; + this._isAnimated = !!this._isAnimated; + } + function SVGFillStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, this); + this.c = PropertyFactory.getProp(elem2, data2.c, 1, 255, this); + this.style = styleOb; + } + function SVGNoStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.style = styleOb; + } + function GradientProperty(elem2, data2, container) { + this.data = data2; + this.c = createTypedArray("uint8c", data2.p * 4); + var cLength = data2.k.k[0].s ? data2.k.k[0].s.length - data2.p * 4 : data2.k.k.length - data2.p * 4; + this.o = createTypedArray("float32", cLength); + this._cmdf = false; + this._omdf = false; + this._collapsable = this.checkCollapsable(); + this._hasOpacity = cLength; + this.initDynamicPropertyContainer(container); + this.prop = PropertyFactory.getProp(elem2, data2.k, 1, null, this); + this.k = this.prop.k; + this.getValue(true); + } + function SVGGradientFillStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.initGradientData(elem2, data2, styleOb); + } + function SVGGradientStrokeStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.w = PropertyFactory.getProp(elem2, data2.w, 0, null, this); + this.d = new DashProperty(elem2, data2.d || {}, "svg", this); + this.initGradientData(elem2, data2, styleOb); + this._isAnimated = !!this._isAnimated; + } + function ShapeGroupData() { + this.it = []; + this.prevViewData = []; + this.gr = createNS("g"); + } + function SVGTransformData(mProps, op, container) { + this.transform = { + mProps, + op, + container + }; + this.elements = []; + this._isAnimated = this.transform.mProps.dynamicProperties.length || this.transform.op.effectsSequence.length; + } + function SVGShapeElement(data2, globalData2, comp2) { + this.shapes = []; + this.shapesData = data2.shapes; + this.stylesList = []; + this.shapeModifiers = []; + this.itemsData = []; + this.processedElements = []; + this.animatedContents = []; + this.initElement(data2, globalData2, comp2); + this.prevViewData = []; + } + function LetterProps(o, sw, sc, fc, m, p) { + this.o = o; + this.sw = sw; + this.sc = sc; + this.fc = fc; + this.m = m; + this.p = p; + this._mdf = { + o: true, + sw: !!sw, + sc: !!sc, + fc: !!fc, + m: true, + p: true + }; + } + function TextProperty(elem2, data2) { + this._frameId = initialDefaultFrame; + this.pv = ""; + this.v = ""; + this.kf = false; + this._isFirstFrame = true; + this._mdf = false; + this.data = data2; + this.elem = elem2; + this.comp = this.elem.comp; + this.keysIndex = 0; + this.canResize = false; + this.minimumFontSize = 1; + this.effectsSequence = []; + this.currentData = { + ascent: 0, + boxWidth: this.defaultBoxWidth, + f: "", + fStyle: "", + fWeight: "", + fc: "", + j: "", + justifyOffset: "", + l: [], + lh: 0, + lineWidths: [], + ls: "", + of: "", + s: "", + sc: "", + sw: 0, + t: 0, + tr: 0, + sz: 0, + ps: null, + fillColorAnim: false, + strokeColorAnim: false, + strokeWidthAnim: false, + yOffset: 0, + finalSize: 0, + finalText: [], + finalLineHeight: 0, + __complete: false + }; + this.copyData(this.currentData, this.data.d.k[0].s); + if (!this.searchProperty()) { + this.completeTextData(this.currentData); + } + } + function TextAnimatorDataProperty(elem2, animatorProps, container) { + var defaultData = { propType: false }; + var getProp = PropertyFactory.getProp; + var textAnimatorAnimatables = animatorProps.a; + this.a = { + r: textAnimatorAnimatables.r ? getProp(elem2, textAnimatorAnimatables.r, 0, degToRads, container) : defaultData, + rx: textAnimatorAnimatables.rx ? getProp(elem2, textAnimatorAnimatables.rx, 0, degToRads, container) : defaultData, + ry: textAnimatorAnimatables.ry ? getProp(elem2, textAnimatorAnimatables.ry, 0, degToRads, container) : defaultData, + sk: textAnimatorAnimatables.sk ? getProp(elem2, textAnimatorAnimatables.sk, 0, degToRads, container) : defaultData, + sa: textAnimatorAnimatables.sa ? getProp(elem2, textAnimatorAnimatables.sa, 0, degToRads, container) : defaultData, + s: textAnimatorAnimatables.s ? getProp(elem2, textAnimatorAnimatables.s, 1, 0.01, container) : defaultData, + a: textAnimatorAnimatables.a ? getProp(elem2, textAnimatorAnimatables.a, 1, 0, container) : defaultData, + o: textAnimatorAnimatables.o ? getProp(elem2, textAnimatorAnimatables.o, 0, 0.01, container) : defaultData, + p: textAnimatorAnimatables.p ? getProp(elem2, textAnimatorAnimatables.p, 1, 0, container) : defaultData, + sw: textAnimatorAnimatables.sw ? getProp(elem2, textAnimatorAnimatables.sw, 0, 0, container) : defaultData, + sc: textAnimatorAnimatables.sc ? getProp(elem2, textAnimatorAnimatables.sc, 1, 0, container) : defaultData, + fc: textAnimatorAnimatables.fc ? getProp(elem2, textAnimatorAnimatables.fc, 1, 0, container) : defaultData, + fh: textAnimatorAnimatables.fh ? getProp(elem2, textAnimatorAnimatables.fh, 0, 0, container) : defaultData, + fs: textAnimatorAnimatables.fs ? getProp(elem2, textAnimatorAnimatables.fs, 0, 0.01, container) : defaultData, + fb: textAnimatorAnimatables.fb ? getProp(elem2, textAnimatorAnimatables.fb, 0, 0.01, container) : defaultData, + t: textAnimatorAnimatables.t ? getProp(elem2, textAnimatorAnimatables.t, 0, 0, container) : defaultData + }; + this.s = TextSelectorProp.getTextSelectorProp(elem2, animatorProps.s, container); + this.s.t = animatorProps.s.t; + } + function TextAnimatorProperty(textData, renderType, elem2) { + this._isFirstFrame = true; + this._hasMaskedPath = false; + this._frameId = -1; + this._textData = textData; + this._renderType = renderType; + this._elem = elem2; + this._animatorsData = createSizedArray(this._textData.a.length); + this._pathData = {}; + this._moreOptions = { + alignment: {} + }; + this.renderedLetters = []; + this.lettersChangedFlag = false; + this.initDynamicPropertyContainer(elem2); + } + function ITextElement() { + } + function SVGTextLottieElement(data2, globalData2, comp2) { + this.textSpans = []; + this.renderType = "svg"; + this.initElement(data2, globalData2, comp2); + } + function ISolidElement(data2, globalData2, comp2) { + this.initElement(data2, globalData2, comp2); + } + function NullElement(data2, globalData2, comp2) { + this.initFrame(); + this.initBaseData(data2, globalData2, comp2); + this.initFrame(); + this.initTransform(data2, globalData2, comp2); + this.initHierarchy(); + } + function SVGRendererBase() { + } + function ICompElement() { + } + function SVGCompElement(data2, globalData2, comp2) { + this.layers = data2.layers; + this.supports3d = true; + this.completeLayers = false; + this.pendingElements = []; + this.elements = this.layers ? createSizedArray(this.layers.length) : []; + this.initElement(data2, globalData2, comp2); + this.tm = data2.tm ? PropertyFactory.getProp(this, data2.tm, 0, globalData2.frameRate, this) : { _placeholder: true }; + } + function SVGRenderer(animationItem, config) { + this.animationItem = animationItem; + this.layers = null; + this.renderedFrame = -1; + this.svgElement = createNS("svg"); + var ariaLabel = ""; + if (config && config.title) { + var titleElement = createNS("title"); + var titleId = createElementID(); + titleElement.setAttribute("id", titleId); + titleElement.textContent = config.title; + this.svgElement.appendChild(titleElement); + ariaLabel += titleId; + } + if (config && config.description) { + var descElement = createNS("desc"); + var descId = createElementID(); + descElement.setAttribute("id", descId); + descElement.textContent = config.description; + this.svgElement.appendChild(descElement); + ariaLabel += " " + descId; + } + if (ariaLabel) { + this.svgElement.setAttribute("aria-labelledby", ariaLabel); + } + var defs = createNS("defs"); + this.svgElement.appendChild(defs); + var maskElement = createNS("g"); + this.svgElement.appendChild(maskElement); + this.layerElement = maskElement; + this.renderConfig = { + preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet", + imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice", + contentVisibility: config && config.contentVisibility || "visible", + progressiveLoad: config && config.progressiveLoad || false, + hideOnTransparent: !(config && config.hideOnTransparent === false), + viewBoxOnly: config && config.viewBoxOnly || false, + viewBoxSize: config && config.viewBoxSize || false, + className: config && config.className || "", + id: config && config.id || "", + focusable: config && config.focusable, + filterSize: { + width: config && config.filterSize && config.filterSize.width || "100%", + height: config && config.filterSize && config.filterSize.height || "100%", + x: config && config.filterSize && config.filterSize.x || "0%", + y: config && config.filterSize && config.filterSize.y || "0%" + }, + width: config && config.width, + height: config && config.height + }; + this.globalData = { + _mdf: false, + frameNum: -1, + defs, + renderConfig: this.renderConfig + }; + this.elements = []; + this.pendingElements = []; + this.destroyed = false; + this.rendererType = "svg"; + } + function CVContextData() { + this.saved = []; + this.cArrPos = 0; + this.cTr = new Matrix; + this.cO = 1; + var i; + var len = 15; + this.savedOp = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + this.saved[i] = createTypedArray("float32", 16); + } + this._length = len; + } + function ShapeTransformManager() { + this.sequences = {}; + this.sequenceList = []; + this.transform_key_count = 0; + } + function CVEffects() { + } + function CVMaskElement(data2, element) { + this.data = data2; + this.element = element; + this.masksProperties = this.data.masksProperties || []; + this.viewData = createSizedArray(this.masksProperties.length); + var i; + var len = this.masksProperties.length; + var hasMasks = false; + for (i = 0;i < len; i += 1) { + if (this.masksProperties[i].mode !== "n") { + hasMasks = true; + } + this.viewData[i] = ShapePropertyFactory.getShapeProp(this.element, this.masksProperties[i], 3); + } + this.hasMasks = hasMasks; + if (hasMasks) { + this.element.addRenderableComponent(this); + } + } + function CVBaseElement() { + } + function CVShapeData(element, data2, styles, transformsManager) { + this.styledShapes = []; + this.tr = [0, 0, 0, 0, 0, 0]; + var ty = 4; + if (data2.ty === "rc") { + ty = 5; + } else if (data2.ty === "el") { + ty = 6; + } else if (data2.ty === "sr") { + ty = 7; + } + this.sh = ShapePropertyFactory.getShapeProp(element, data2, ty, element); + var i; + var len = styles.length; + var styledShape; + for (i = 0;i < len; i += 1) { + if (!styles[i].closed) { + styledShape = { + transforms: transformsManager.addTransformSequence(styles[i].transforms), + trNodes: [] + }; + this.styledShapes.push(styledShape); + styles[i].elements.push(styledShape); + } + } + } + function CVShapeElement(data2, globalData2, comp2) { + this.shapes = []; + this.shapesData = data2.shapes; + this.stylesList = []; + this.itemsData = []; + this.prevViewData = []; + this.shapeModifiers = []; + this.processedElements = []; + this.transformsManager = new ShapeTransformManager; + this.initElement(data2, globalData2, comp2); + } + function CVTextElement(data2, globalData2, comp2) { + this.textSpans = []; + this.yOffset = 0; + this.fillColorAnim = false; + this.strokeColorAnim = false; + this.strokeWidthAnim = false; + this.stroke = false; + this.fill = false; + this.justifyOffset = 0; + this.currentRender = null; + this.renderType = "canvas"; + this.values = { + fill: "rgba(0,0,0,0)", + stroke: "rgba(0,0,0,0)", + sWidth: 0, + fValue: "" + }; + this.initElement(data2, globalData2, comp2); + } + function CVImageElement(data2, globalData2, comp2) { + this.assetData = globalData2.getAssetData(data2.refId); + this.img = globalData2.imageLoader.getAsset(this.assetData); + this.initElement(data2, globalData2, comp2); + } + function CVSolidElement(data2, globalData2, comp2) { + this.initElement(data2, globalData2, comp2); + } + function CanvasRendererBase(animationItem, config) { + this.animationItem = animationItem; + this.renderConfig = { + clearCanvas: config && config.clearCanvas !== undefined ? config.clearCanvas : true, + context: config && config.context || null, + progressiveLoad: config && config.progressiveLoad || false, + preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet", + imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice", + contentVisibility: config && config.contentVisibility || "visible", + className: config && config.className || "", + id: config && config.id || "" + }; + this.renderConfig.dpr = config && config.dpr || 1; + if (this.animationItem.wrapper) { + this.renderConfig.dpr = config && config.dpr || window.devicePixelRatio || 1; + } + this.renderedFrame = -1; + this.globalData = { + frameNum: -1, + _mdf: false, + renderConfig: this.renderConfig, + currentGlobalAlpha: -1 + }; + this.contextData = new CVContextData; + this.elements = []; + this.pendingElements = []; + this.transformMat = new Matrix; + this.completeLayers = false; + this.rendererType = "canvas"; + } + function CVCompElement(data2, globalData2, comp2) { + this.completeLayers = false; + this.layers = data2.layers; + this.pendingElements = []; + this.elements = createSizedArray(this.layers.length); + this.initElement(data2, globalData2, comp2); + this.tm = data2.tm ? PropertyFactory.getProp(this, data2.tm, 0, globalData2.frameRate, this) : { _placeholder: true }; + } + function CanvasRenderer(animationItem, config) { + this.animationItem = animationItem; + this.renderConfig = { + clearCanvas: config && config.clearCanvas !== undefined ? config.clearCanvas : true, + context: config && config.context || null, + progressiveLoad: config && config.progressiveLoad || false, + preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet", + imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice", + contentVisibility: config && config.contentVisibility || "visible", + className: config && config.className || "", + id: config && config.id || "" + }; + this.renderConfig.dpr = config && config.dpr || 1; + if (this.animationItem.wrapper) { + this.renderConfig.dpr = config && config.dpr || window.devicePixelRatio || 1; + } + this.renderedFrame = -1; + this.globalData = { + frameNum: -1, + _mdf: false, + renderConfig: this.renderConfig, + currentGlobalAlpha: -1 + }; + this.contextData = new CVContextData; + this.elements = []; + this.pendingElements = []; + this.transformMat = new Matrix; + this.completeLayers = false; + this.rendererType = "canvas"; + } + function seedRandom(pool, math) { + var global2 = this, width2 = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width2, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask2 = width2 - 1, nodecrypto; + function seedrandom(seed, options, callback) { + var key2 = []; + options = options === true ? { entropy: true } : options || {}; + var shortseed = mixkey(flatten3(options.entropy ? [seed, tostring(pool)] : seed === null ? autoseed() : seed, 3), key2); + var arc4 = new ARC4(key2); + var prng = function() { + var n2 = arc4.g(chunks), d = startdenom, x2 = 0; + while (n2 < significance) { + n2 = (n2 + x2) * width2; + d *= width2; + x2 = arc4.g(1); + } + while (n2 >= overflow) { + n2 /= 2; + d /= 2; + x2 >>>= 1; + } + return (n2 + x2) / d; + }; + prng.int32 = function() { + return arc4.g(4) | 0; + }; + prng.quick = function() { + return arc4.g(4) / 4294967296; + }; + prng.double = prng; + mixkey(tostring(arc4.S), pool); + return (options.pass || callback || function(prng2, seed2, is_math_call, state) { + if (state) { + if (state.S) { + copy(state, arc4); + } + prng2.state = function() { + return copy(arc4, {}); + }; + } + if (is_math_call) { + math[rngname] = prng2; + return seed2; + } else + return prng2; + })(prng, shortseed, "global" in options ? options.global : this == math, options.state); + } + math["seed" + rngname] = seedrandom; + function ARC4(key2) { + var t2, keylen = key2.length, me = this, i = 0, j2 = me.i = me.j = 0, s = me.S = []; + if (!keylen) { + key2 = [keylen++]; + } + while (i < width2) { + s[i] = i++; + } + for (i = 0;i < width2; i++) { + s[i] = s[j2 = mask2 & j2 + key2[i % keylen] + (t2 = s[i])]; + s[j2] = t2; + } + me.g = function(count) { + var t3, r = 0, i2 = me.i, j3 = me.j, s2 = me.S; + while (count--) { + t3 = s2[i2 = mask2 & i2 + 1]; + r = r * width2 + s2[mask2 & (s2[i2] = s2[j3 = mask2 & j3 + t3]) + (s2[j3] = t3)]; + } + me.i = i2; + me.j = j3; + return r; + }; + } + function copy(f, t2) { + t2.i = f.i; + t2.j = f.j; + t2.S = f.S.slice(); + return t2; + } + function flatten3(obj, depth) { + var result = [], typ = typeof obj, prop; + if (depth && typ == "object") { + for (prop in obj) { + try { + result.push(flatten3(obj[prop], depth - 1)); + } catch (e) { + } + } + } + return result.length ? result : typ == "string" ? obj : obj + "\x00"; + } + function mixkey(seed, key2) { + var stringseed = seed + "", smear, j2 = 0; + while (j2 < stringseed.length) { + key2[mask2 & j2] = mask2 & (smear ^= key2[mask2 & j2] * 19) + stringseed.charCodeAt(j2++); + } + return tostring(key2); + } + function autoseed() { + try { + if (nodecrypto) { + return tostring(nodecrypto.randomBytes(width2)); + } + var out = new Uint8Array(width2); + (global2.crypto || global2.msCrypto).getRandomValues(out); + return tostring(out); + } catch (e) { + var browser = global2.navigator, plugins = browser && browser.plugins; + return [+new Date, global2, plugins, global2.screen, tostring(pool)]; + } + } + function tostring(a) { + return String.fromCharCode.apply(0, a); + } + mixkey(math.random(), pool); + } + function initialize$2(BMMath2) { + seedRandom([], BMMath2); + } + function addPropertyDecorator() { + function loopOut2(type, duration, durationFlag) { + if (!this.k || !this.keyframes) { + return this.pv; + } + type = type ? type.toLowerCase() : ""; + var currentFrame = this.comp.renderedFrame; + var keyframes = this.keyframes; + var lastKeyFrame = keyframes[keyframes.length - 1].t; + if (currentFrame <= lastKeyFrame) { + return this.pv; + } + var cycleDuration; + var firstKeyFrame; + if (!durationFlag) { + if (!duration || duration > keyframes.length - 1) { + duration = keyframes.length - 1; + } + firstKeyFrame = keyframes[keyframes.length - 1 - duration].t; + cycleDuration = lastKeyFrame - firstKeyFrame; + } else { + if (!duration) { + cycleDuration = Math.max(0, lastKeyFrame - this.elem.data.ip); + } else { + cycleDuration = Math.abs(lastKeyFrame - this.elem.comp.globalData.frameRate * duration); + } + firstKeyFrame = lastKeyFrame - cycleDuration; + } + var i; + var len; + var ret; + if (type === "pingpong") { + var iterations = Math.floor((currentFrame - firstKeyFrame) / cycleDuration); + if (iterations % 2 !== 0) { + return this.getValueAtTime((cycleDuration - (currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + } + } else if (type === "offset") { + var initV = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0); + var endV = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0); + var current = this.getValueAtTime(((currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + var repeats = Math.floor((currentFrame - firstKeyFrame) / cycleDuration); + if (this.pv.length) { + ret = new Array(initV.length); + len = ret.length; + for (i = 0;i < len; i += 1) { + ret[i] = (endV[i] - initV[i]) * repeats + current[i]; + } + return ret; + } + return (endV - initV) * repeats + current; + } else if (type === "continue") { + var lastValue = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0); + var nextLastValue = this.getValueAtTime((lastKeyFrame - 0.001) / this.comp.globalData.frameRate, 0); + if (this.pv.length) { + ret = new Array(lastValue.length); + len = ret.length; + for (i = 0;i < len; i += 1) { + ret[i] = lastValue[i] + (lastValue[i] - nextLastValue[i]) * ((currentFrame - lastKeyFrame) / this.comp.globalData.frameRate) / 0.0005; + } + return ret; + } + return lastValue + (lastValue - nextLastValue) * ((currentFrame - lastKeyFrame) / 0.001); + } + return this.getValueAtTime(((currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + } + function loopIn2(type, duration, durationFlag) { + if (!this.k) { + return this.pv; + } + type = type ? type.toLowerCase() : ""; + var currentFrame = this.comp.renderedFrame; + var keyframes = this.keyframes; + var firstKeyFrame = keyframes[0].t; + if (currentFrame >= firstKeyFrame) { + return this.pv; + } + var cycleDuration; + var lastKeyFrame; + if (!durationFlag) { + if (!duration || duration > keyframes.length - 1) { + duration = keyframes.length - 1; + } + lastKeyFrame = keyframes[duration].t; + cycleDuration = lastKeyFrame - firstKeyFrame; + } else { + if (!duration) { + cycleDuration = Math.max(0, this.elem.data.op - firstKeyFrame); + } else { + cycleDuration = Math.abs(this.elem.comp.globalData.frameRate * duration); + } + lastKeyFrame = firstKeyFrame + cycleDuration; + } + var i; + var len; + var ret; + if (type === "pingpong") { + var iterations = Math.floor((firstKeyFrame - currentFrame) / cycleDuration); + if (iterations % 2 === 0) { + return this.getValueAtTime(((firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + } + } else if (type === "offset") { + var initV = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0); + var endV = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0); + var current = this.getValueAtTime((cycleDuration - (firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + var repeats = Math.floor((firstKeyFrame - currentFrame) / cycleDuration) + 1; + if (this.pv.length) { + ret = new Array(initV.length); + len = ret.length; + for (i = 0;i < len; i += 1) { + ret[i] = current[i] - (endV[i] - initV[i]) * repeats; + } + return ret; + } + return current - (endV - initV) * repeats; + } else if (type === "continue") { + var firstValue = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0); + var nextFirstValue = this.getValueAtTime((firstKeyFrame + 0.001) / this.comp.globalData.frameRate, 0); + if (this.pv.length) { + ret = new Array(firstValue.length); + len = ret.length; + for (i = 0;i < len; i += 1) { + ret[i] = firstValue[i] + (firstValue[i] - nextFirstValue[i]) * (firstKeyFrame - currentFrame) / 0.001; + } + return ret; + } + return firstValue + (firstValue - nextFirstValue) * (firstKeyFrame - currentFrame) / 0.001; + } + return this.getValueAtTime((cycleDuration - ((firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame)) / this.comp.globalData.frameRate, 0); + } + function smooth2(width2, samples) { + if (!this.k) { + return this.pv; + } + width2 = (width2 || 0.4) * 0.5; + samples = Math.floor(samples || 5); + if (samples <= 1) { + return this.pv; + } + var currentTime = this.comp.renderedFrame / this.comp.globalData.frameRate; + var initFrame = currentTime - width2; + var endFrame = currentTime + width2; + var sampleFrequency = samples > 1 ? (endFrame - initFrame) / (samples - 1) : 1; + var i = 0; + var j2 = 0; + var value2; + if (this.pv.length) { + value2 = createTypedArray("float32", this.pv.length); + } else { + value2 = 0; + } + var sampleValue; + while (i < samples) { + sampleValue = this.getValueAtTime(initFrame + i * sampleFrequency); + if (this.pv.length) { + for (j2 = 0;j2 < this.pv.length; j2 += 1) { + value2[j2] += sampleValue[j2]; + } + } else { + value2 += sampleValue; + } + i += 1; + } + if (this.pv.length) { + for (j2 = 0;j2 < this.pv.length; j2 += 1) { + value2[j2] /= samples; + } + } else { + value2 /= samples; + } + return value2; + } + function getTransformValueAtTime(time2) { + if (!this._transformCachingAtTime) { + this._transformCachingAtTime = { + v: new Matrix + }; + } + var matrix = this._transformCachingAtTime.v; + matrix.cloneFromProps(this.pre.props); + if (this.appliedTransformations < 1) { + var anchor = this.a.getValueAtTime(time2); + matrix.translate(-anchor[0] * this.a.mult, -anchor[1] * this.a.mult, anchor[2] * this.a.mult); + } + if (this.appliedTransformations < 2) { + var scale2 = this.s.getValueAtTime(time2); + matrix.scale(scale2[0] * this.s.mult, scale2[1] * this.s.mult, scale2[2] * this.s.mult); + } + if (this.sk && this.appliedTransformations < 3) { + var skew = this.sk.getValueAtTime(time2); + var skewAxis = this.sa.getValueAtTime(time2); + matrix.skewFromAxis(-skew * this.sk.mult, skewAxis * this.sa.mult); + } + if (this.r && this.appliedTransformations < 4) { + var rotation2 = this.r.getValueAtTime(time2); + matrix.rotate(-rotation2 * this.r.mult); + } else if (!this.r && this.appliedTransformations < 4) { + var rotationZ = this.rz.getValueAtTime(time2); + var rotationY = this.ry.getValueAtTime(time2); + var rotationX = this.rx.getValueAtTime(time2); + var orientation = this.or.getValueAtTime(time2); + matrix.rotateZ(-rotationZ * this.rz.mult).rotateY(rotationY * this.ry.mult).rotateX(rotationX * this.rx.mult).rotateZ(-orientation[2] * this.or.mult).rotateY(orientation[1] * this.or.mult).rotateX(orientation[0] * this.or.mult); + } + if (this.data.p && this.data.p.s) { + var positionX = this.px.getValueAtTime(time2); + var positionY = this.py.getValueAtTime(time2); + if (this.data.p.z) { + var positionZ = this.pz.getValueAtTime(time2); + matrix.translate(positionX * this.px.mult, positionY * this.py.mult, -positionZ * this.pz.mult); + } else { + matrix.translate(positionX * this.px.mult, positionY * this.py.mult, 0); + } + } else { + var position2 = this.p.getValueAtTime(time2); + matrix.translate(position2[0] * this.p.mult, position2[1] * this.p.mult, -position2[2] * this.p.mult); + } + return matrix; + } + function getTransformStaticValueAtTime() { + return this.v.clone(new Matrix); + } + var getTransformProperty = TransformPropertyFactory.getTransformProperty; + TransformPropertyFactory.getTransformProperty = function(elem2, data2, container) { + var prop = getTransformProperty(elem2, data2, container); + if (prop.dynamicProperties.length) { + prop.getValueAtTime = getTransformValueAtTime.bind(prop); + } else { + prop.getValueAtTime = getTransformStaticValueAtTime.bind(prop); + } + prop.setGroupProperty = expressionHelpers.setGroupProperty; + return prop; + }; + var propertyGetProp = PropertyFactory.getProp; + PropertyFactory.getProp = function(elem2, data2, type, mult, container) { + var prop = propertyGetProp(elem2, data2, type, mult, container); + if (prop.kf) { + prop.getValueAtTime = expressionHelpers.getValueAtTime.bind(prop); + } else { + prop.getValueAtTime = expressionHelpers.getStaticValueAtTime.bind(prop); + } + prop.setGroupProperty = expressionHelpers.setGroupProperty; + prop.loopOut = loopOut2; + prop.loopIn = loopIn2; + prop.smooth = smooth2; + prop.getVelocityAtTime = expressionHelpers.getVelocityAtTime.bind(prop); + prop.getSpeedAtTime = expressionHelpers.getSpeedAtTime.bind(prop); + prop.numKeys = data2.a === 1 ? data2.k.length : 0; + prop.propertyIndex = data2.ix; + var value2 = 0; + if (type !== 0) { + value2 = createTypedArray("float32", data2.a === 1 ? data2.k[0].s.length : data2.k.length); + } + prop._cachingAtTime = { + lastFrame: initialDefaultFrame, + lastIndex: 0, + value: value2 + }; + expressionHelpers.searchExpressions(elem2, data2, prop); + if (prop.k) { + container.addDynamicProperty(prop); + } + return prop; + }; + function getShapeValueAtTime(frameNum) { + if (!this._cachingAtTime) { + this._cachingAtTime = { + shapeValue: shapePool.clone(this.pv), + lastIndex: 0, + lastTime: initialDefaultFrame + }; + } + frameNum *= this.elem.globalData.frameRate; + frameNum -= this.offsetTime; + if (frameNum !== this._cachingAtTime.lastTime) { + this._cachingAtTime.lastIndex = this._cachingAtTime.lastTime < frameNum ? this._caching.lastIndex : 0; + this._cachingAtTime.lastTime = frameNum; + this.interpolateShape(frameNum, this._cachingAtTime.shapeValue, this._cachingAtTime); + } + return this._cachingAtTime.shapeValue; + } + var ShapePropertyConstructorFunction = ShapePropertyFactory.getConstructorFunction(); + var KeyframedShapePropertyConstructorFunction = ShapePropertyFactory.getKeyframedConstructorFunction(); + function ShapeExpressions() { + } + ShapeExpressions.prototype = { + vertices: function(prop, time2) { + if (this.k) { + this.getValue(); + } + var shapePath = this.v; + if (time2 !== undefined) { + shapePath = this.getValueAtTime(time2, 0); + } + var i; + var len = shapePath._length; + var vertices = shapePath[prop]; + var points = shapePath.v; + var arr = createSizedArray(len); + for (i = 0;i < len; i += 1) { + if (prop === "i" || prop === "o") { + arr[i] = [vertices[i][0] - points[i][0], vertices[i][1] - points[i][1]]; + } else { + arr[i] = [vertices[i][0], vertices[i][1]]; + } + } + return arr; + }, + points: function(time2) { + return this.vertices("v", time2); + }, + inTangents: function(time2) { + return this.vertices("i", time2); + }, + outTangents: function(time2) { + return this.vertices("o", time2); + }, + isClosed: function() { + return this.v.c; + }, + pointOnPath: function(perc, time2) { + var shapePath = this.v; + if (time2 !== undefined) { + shapePath = this.getValueAtTime(time2, 0); + } + if (!this._segmentsLength) { + this._segmentsLength = bez.getSegmentsLength(shapePath); + } + var segmentsLength = this._segmentsLength; + var lengths = segmentsLength.lengths; + var lengthPos = segmentsLength.totalLength * perc; + var i = 0; + var len = lengths.length; + var accumulatedLength = 0; + var pt; + while (i < len) { + if (accumulatedLength + lengths[i].addedLength > lengthPos) { + var initIndex = i; + var endIndex = shapePath.c && i === len - 1 ? 0 : i + 1; + var segmentPerc = (lengthPos - accumulatedLength) / lengths[i].addedLength; + pt = bez.getPointInSegment(shapePath.v[initIndex], shapePath.v[endIndex], shapePath.o[initIndex], shapePath.i[endIndex], segmentPerc, lengths[i]); + break; + } else { + accumulatedLength += lengths[i].addedLength; + } + i += 1; + } + if (!pt) { + pt = shapePath.c ? [shapePath.v[0][0], shapePath.v[0][1]] : [shapePath.v[shapePath._length - 1][0], shapePath.v[shapePath._length - 1][1]]; + } + return pt; + }, + vectorOnPath: function(perc, time2, vectorType) { + if (perc == 1) { + perc = this.v.c; + } else if (perc == 0) { + perc = 0.999; + } + var pt1 = this.pointOnPath(perc, time2); + var pt2 = this.pointOnPath(perc + 0.001, time2); + var xLength = pt2[0] - pt1[0]; + var yLength = pt2[1] - pt1[1]; + var magnitude = Math.sqrt(Math.pow(xLength, 2) + Math.pow(yLength, 2)); + if (magnitude === 0) { + return [0, 0]; + } + var unitVector = vectorType === "tangent" ? [xLength / magnitude, yLength / magnitude] : [-yLength / magnitude, xLength / magnitude]; + return unitVector; + }, + tangentOnPath: function(perc, time2) { + return this.vectorOnPath(perc, time2, "tangent"); + }, + normalOnPath: function(perc, time2) { + return this.vectorOnPath(perc, time2, "normal"); + }, + setGroupProperty: expressionHelpers.setGroupProperty, + getValueAtTime: expressionHelpers.getStaticValueAtTime + }; + extendPrototype([ShapeExpressions], ShapePropertyConstructorFunction); + extendPrototype([ShapeExpressions], KeyframedShapePropertyConstructorFunction); + KeyframedShapePropertyConstructorFunction.prototype.getValueAtTime = getShapeValueAtTime; + KeyframedShapePropertyConstructorFunction.prototype.initiateExpression = ExpressionManager.initiateExpression; + var propertyGetShapeProp = ShapePropertyFactory.getShapeProp; + ShapePropertyFactory.getShapeProp = function(elem2, data2, type, arr, trims) { + var prop = propertyGetShapeProp(elem2, data2, type, arr, trims); + prop.propertyIndex = data2.ix; + prop.lock = false; + if (type === 3) { + expressionHelpers.searchExpressions(elem2, data2.pt, prop); + } else if (type === 4) { + expressionHelpers.searchExpressions(elem2, data2.ks, prop); + } + if (prop.k) { + elem2.addDynamicProperty(prop); + } + return prop; + }; + } + function initialize$1() { + addPropertyDecorator(); + } + function addDecorator() { + function searchExpressions() { + if (this.data.d.x) { + this.calculateExpression = ExpressionManager.initiateExpression.bind(this)(this.elem, this.data.d, this); + this.addEffect(this.getExpressionValue.bind(this)); + return true; + } + return null; + } + TextProperty.prototype.getExpressionValue = function(currentValue, text2) { + var newValue = this.calculateExpression(text2); + if (currentValue.t !== newValue) { + var newData = {}; + this.copyData(newData, currentValue); + newData.t = newValue.toString(); + newData.__complete = false; + return newData; + } + return currentValue; + }; + TextProperty.prototype.searchProperty = function() { + var isKeyframed = this.searchKeyframes(); + var hasExpressions = this.searchExpressions(); + this.kf = isKeyframed || hasExpressions; + return this.kf; + }; + TextProperty.prototype.searchExpressions = searchExpressions; + } + function initialize() { + addDecorator(); + } + const svgNS = "http://www.w3.org/2000/svg"; + let locationHref = ""; + let _useWebWorker = false; + const initialDefaultFrame = -999999; + const setWebWorker = (flag) => { + _useWebWorker = !!flag; + }; + const getWebWorker = () => _useWebWorker; + const setLocationHref = (value2) => { + locationHref = value2; + }; + const getLocationHref = () => locationHref; + const audioControllerFactory = function() { + function AudioController(audioFactory) { + this.audios = []; + this.audioFactory = audioFactory; + this._volume = 1; + this._isMuted = false; + } + AudioController.prototype = { + addAudio: function(audio) { + this.audios.push(audio); + }, + pause: function() { + var i; + var len = this.audios.length; + for (i = 0;i < len; i += 1) { + this.audios[i].pause(); + } + }, + resume: function() { + var i; + var len = this.audios.length; + for (i = 0;i < len; i += 1) { + this.audios[i].resume(); + } + }, + setRate: function(rateValue) { + var i; + var len = this.audios.length; + for (i = 0;i < len; i += 1) { + this.audios[i].setRate(rateValue); + } + }, + createAudio: function(assetPath) { + if (this.audioFactory) { + return this.audioFactory(assetPath); + } + if (window.Howl) { + return new window.Howl({ + src: [assetPath] + }); + } + return { + isPlaying: false, + play: function() { + this.isPlaying = true; + }, + seek: function() { + this.isPlaying = false; + }, + playing: function() { + }, + rate: function() { + }, + setVolume: function() { + } + }; + }, + setAudioFactory: function(audioFactory) { + this.audioFactory = audioFactory; + }, + setVolume: function(value2) { + this._volume = value2; + this._updateVolume(); + }, + mute: function() { + this._isMuted = true; + this._updateVolume(); + }, + unmute: function() { + this._isMuted = false; + this._updateVolume(); + }, + getVolume: function() { + return this._volume; + }, + _updateVolume: function() { + var i; + var len = this.audios.length; + for (i = 0;i < len; i += 1) { + this.audios[i].volume(this._volume * (this._isMuted ? 0 : 1)); + } + } + }; + return function() { + return new AudioController; + }; + }(); + const createTypedArray = function() { + function createRegularArray(type, len) { + var i = 0; + var arr = []; + var value2; + switch (type) { + case "int16": + case "uint8c": + value2 = 1; + break; + default: + value2 = 1.1; + break; + } + for (i = 0;i < len; i += 1) { + arr.push(value2); + } + return arr; + } + function createTypedArrayFactory(type, len) { + if (type === "float32") { + return new Float32Array(len); + } + if (type === "int16") { + return new Int16Array(len); + } + if (type === "uint8c") { + return new Uint8ClampedArray(len); + } + return createRegularArray(type, len); + } + if (typeof Uint8ClampedArray === "function" && typeof Float32Array === "function") { + return createTypedArrayFactory; + } + return createRegularArray; + }(); + let subframeEnabled = true; + let expressionsPlugin = null; + let idPrefix$1 = ""; + const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); + let _shouldRoundValues = false; + const bmPow = Math.pow; + const bmSqrt = Math.sqrt; + const bmFloor = Math.floor; + const bmMax = Math.max; + const bmMin = Math.min; + const BMMath = {}; + (function() { + var propertyNames = ["abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "atan2", "ceil", "cbrt", "expm1", "clz32", "cos", "cosh", "exp", "floor", "fround", "hypot", "imul", "log", "log1p", "log2", "log10", "max", "min", "pow", "random", "round", "sign", "sin", "sinh", "sqrt", "tan", "tanh", "trunc", "E", "LN10", "LN2", "LOG10E", "LOG2E", "PI", "SQRT1_2", "SQRT2"]; + var i; + var len = propertyNames.length; + for (i = 0;i < len; i += 1) { + BMMath[propertyNames[i]] = Math[propertyNames[i]]; + } + })(); + BMMath.random = Math.random; + BMMath.abs = function(val2) { + var tOfVal = typeof val2; + if (tOfVal === "object" && val2.length) { + var absArr = createSizedArray(val2.length); + var i; + var len = val2.length; + for (i = 0;i < len; i += 1) { + absArr[i] = Math.abs(val2[i]); + } + return absArr; + } + return Math.abs(val2); + }; + let defaultCurveSegments = 150; + const degToRads = Math.PI / 180; + const roundCorner = 0.5519; + const createElementID = function() { + var _count = 0; + return function createID() { + _count += 1; + return idPrefix$1 + "__lottie_element_" + _count; + }; + }(); + const rgbToHex = function() { + var colorMap = []; + var i; + var hex; + for (i = 0;i < 256; i += 1) { + hex = i.toString(16); + colorMap[i] = hex.length === 1 ? "0" + hex : hex; + } + return function(r, g3, b) { + if (r < 0) { + r = 0; + } + if (g3 < 0) { + g3 = 0; + } + if (b < 0) { + b = 0; + } + return "#" + colorMap[r] + colorMap[g3] + colorMap[b]; + }; + }(); + const setSubframeEnabled = (flag) => { + subframeEnabled = !!flag; + }; + const getSubframeEnabled = () => subframeEnabled; + const setExpressionsPlugin = (value2) => { + expressionsPlugin = value2; + }; + const getExpressionsPlugin = () => expressionsPlugin; + const setDefaultCurveSegments = (value2) => { + defaultCurveSegments = value2; + }; + const getDefaultCurveSegments = () => defaultCurveSegments; + const setIdPrefix = (value2) => { + idPrefix$1 = value2; + }; + const getIdPrefix = () => idPrefix$1; + const dataManager = function() { + var _counterId = 1; + var processes = []; + var workerFn; + var workerInstance; + var workerProxy = { + onmessage: function() { + }, + postMessage: function(path) { + workerFn({ + data: path + }); + } + }; + var _workerSelf = { + postMessage: function(data2) { + workerProxy.onmessage({ + data: data2 + }); + } + }; + function createWorker(fn) { + if (window.Worker && window.Blob && getWebWorker()) { + var blob = new Blob(["var _workerSelf = self; self.onmessage = ", fn.toString()], { type: "text/javascript" }); + var url = URL.createObjectURL(blob); + return new Worker(url); + } + workerFn = fn; + return workerProxy; + } + function setupWorker() { + if (!workerInstance) { + workerInstance = createWorker(function workerStart(e) { + function dataFunctionManager() { + function completeLayers(layers, comps) { + var layerData; + var i; + var len = layers.length; + var j2; + var jLen; + var k2; + var kLen; + for (i = 0;i < len; i += 1) { + layerData = layers[i]; + if ("ks" in layerData && !layerData.completed) { + layerData.completed = true; + if (layerData.tt) { + layers[i - 1].td = layerData.tt; + } + if (layerData.hasMask) { + var maskProps = layerData.masksProperties; + jLen = maskProps.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (maskProps[j2].pt.k.i) { + convertPathsToAbsoluteValues(maskProps[j2].pt.k); + } else { + kLen = maskProps[j2].pt.k.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + if (maskProps[j2].pt.k[k2].s) { + convertPathsToAbsoluteValues(maskProps[j2].pt.k[k2].s[0]); + } + if (maskProps[j2].pt.k[k2].e) { + convertPathsToAbsoluteValues(maskProps[j2].pt.k[k2].e[0]); + } + } + } + } + } + if (layerData.ty === 0) { + layerData.layers = findCompLayers(layerData.refId, comps); + completeLayers(layerData.layers, comps); + } else if (layerData.ty === 4) { + completeShapes(layerData.shapes); + } else if (layerData.ty === 5) { + completeText(layerData); + } + } + } + } + function completeChars(chars, assets) { + if (chars) { + var i = 0; + var len = chars.length; + for (i = 0;i < len; i += 1) { + if (chars[i].t === 1) { + chars[i].data.layers = findCompLayers(chars[i].data.refId, assets); + completeLayers(chars[i].data.layers, assets); + } + } + } + } + function findComp(id, comps) { + var i = 0; + var len = comps.length; + while (i < len) { + if (comps[i].id === id) { + return comps[i]; + } + i += 1; + } + return null; + } + function findCompLayers(id, comps) { + var comp2 = findComp(id, comps); + if (comp2) { + if (!comp2.layers.__used) { + comp2.layers.__used = true; + return comp2.layers; + } + return JSON.parse(JSON.stringify(comp2.layers)); + } + return null; + } + function completeShapes(arr) { + var i; + var len = arr.length; + var j2; + var jLen; + for (i = len - 1;i >= 0; i -= 1) { + if (arr[i].ty === "sh") { + if (arr[i].ks.k.i) { + convertPathsToAbsoluteValues(arr[i].ks.k); + } else { + jLen = arr[i].ks.k.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (arr[i].ks.k[j2].s) { + convertPathsToAbsoluteValues(arr[i].ks.k[j2].s[0]); + } + if (arr[i].ks.k[j2].e) { + convertPathsToAbsoluteValues(arr[i].ks.k[j2].e[0]); + } + } + } + } else if (arr[i].ty === "gr") { + completeShapes(arr[i].it); + } + } + } + function convertPathsToAbsoluteValues(path) { + var i; + var len = path.i.length; + for (i = 0;i < len; i += 1) { + path.i[i][0] += path.v[i][0]; + path.i[i][1] += path.v[i][1]; + path.o[i][0] += path.v[i][0]; + path.o[i][1] += path.v[i][1]; + } + } + function checkVersion(minimum, animVersionString) { + var animVersion = animVersionString ? animVersionString.split(".") : [100, 100, 100]; + if (minimum[0] > animVersion[0]) { + return true; + } + if (animVersion[0] > minimum[0]) { + return false; + } + if (minimum[1] > animVersion[1]) { + return true; + } + if (animVersion[1] > minimum[1]) { + return false; + } + if (minimum[2] > animVersion[2]) { + return true; + } + if (animVersion[2] > minimum[2]) { + return false; + } + return null; + } + var checkText = function() { + var minimumVersion = [4, 4, 14]; + function updateTextLayer(textLayer) { + var documentData = textLayer.t.d; + textLayer.t.d = { + k: [ + { + s: documentData, + t: 0 + } + ] + }; + } + function iterateLayers(layers) { + var i; + var len = layers.length; + for (i = 0;i < len; i += 1) { + if (layers[i].ty === 5) { + updateTextLayer(layers[i]); + } + } + } + return function(animationData2) { + if (checkVersion(minimumVersion, animationData2.v)) { + iterateLayers(animationData2.layers); + if (animationData2.assets) { + var i; + var len = animationData2.assets.length; + for (i = 0;i < len; i += 1) { + if (animationData2.assets[i].layers) { + iterateLayers(animationData2.assets[i].layers); + } + } + } + } + }; + }(); + var checkChars = function() { + var minimumVersion = [4, 7, 99]; + return function(animationData2) { + if (animationData2.chars && !checkVersion(minimumVersion, animationData2.v)) { + var i; + var len = animationData2.chars.length; + for (i = 0;i < len; i += 1) { + var charData = animationData2.chars[i]; + if (charData.data && charData.data.shapes) { + completeShapes(charData.data.shapes); + charData.data.ip = 0; + charData.data.op = 99999; + charData.data.st = 0; + charData.data.sr = 1; + charData.data.ks = { + p: { k: [0, 0], a: 0 }, + s: { k: [100, 100], a: 0 }, + a: { k: [0, 0], a: 0 }, + r: { k: 0, a: 0 }, + o: { k: 100, a: 0 } + }; + if (!animationData2.chars[i].t) { + charData.data.shapes.push({ + ty: "no" + }); + charData.data.shapes[0].it.push({ + p: { k: [0, 0], a: 0 }, + s: { k: [100, 100], a: 0 }, + a: { k: [0, 0], a: 0 }, + r: { k: 0, a: 0 }, + o: { k: 100, a: 0 }, + sk: { k: 0, a: 0 }, + sa: { k: 0, a: 0 }, + ty: "tr" + }); + } + } + } + } + }; + }(); + var checkPathProperties = function() { + var minimumVersion = [5, 7, 15]; + function updateTextLayer(textLayer) { + var pathData = textLayer.t.p; + if (typeof pathData.a === "number") { + pathData.a = { + a: 0, + k: pathData.a + }; + } + if (typeof pathData.p === "number") { + pathData.p = { + a: 0, + k: pathData.p + }; + } + if (typeof pathData.r === "number") { + pathData.r = { + a: 0, + k: pathData.r + }; + } + } + function iterateLayers(layers) { + var i; + var len = layers.length; + for (i = 0;i < len; i += 1) { + if (layers[i].ty === 5) { + updateTextLayer(layers[i]); + } + } + } + return function(animationData2) { + if (checkVersion(minimumVersion, animationData2.v)) { + iterateLayers(animationData2.layers); + if (animationData2.assets) { + var i; + var len = animationData2.assets.length; + for (i = 0;i < len; i += 1) { + if (animationData2.assets[i].layers) { + iterateLayers(animationData2.assets[i].layers); + } + } + } + } + }; + }(); + var checkColors = function() { + var minimumVersion = [4, 1, 9]; + function iterateShapes(shapes) { + var i; + var len = shapes.length; + var j2; + var jLen; + for (i = 0;i < len; i += 1) { + if (shapes[i].ty === "gr") { + iterateShapes(shapes[i].it); + } else if (shapes[i].ty === "fl" || shapes[i].ty === "st") { + if (shapes[i].c.k && shapes[i].c.k[0].i) { + jLen = shapes[i].c.k.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (shapes[i].c.k[j2].s) { + shapes[i].c.k[j2].s[0] /= 255; + shapes[i].c.k[j2].s[1] /= 255; + shapes[i].c.k[j2].s[2] /= 255; + shapes[i].c.k[j2].s[3] /= 255; + } + if (shapes[i].c.k[j2].e) { + shapes[i].c.k[j2].e[0] /= 255; + shapes[i].c.k[j2].e[1] /= 255; + shapes[i].c.k[j2].e[2] /= 255; + shapes[i].c.k[j2].e[3] /= 255; + } + } + } else { + shapes[i].c.k[0] /= 255; + shapes[i].c.k[1] /= 255; + shapes[i].c.k[2] /= 255; + shapes[i].c.k[3] /= 255; + } + } + } + } + function iterateLayers(layers) { + var i; + var len = layers.length; + for (i = 0;i < len; i += 1) { + if (layers[i].ty === 4) { + iterateShapes(layers[i].shapes); + } + } + } + return function(animationData2) { + if (checkVersion(minimumVersion, animationData2.v)) { + iterateLayers(animationData2.layers); + if (animationData2.assets) { + var i; + var len = animationData2.assets.length; + for (i = 0;i < len; i += 1) { + if (animationData2.assets[i].layers) { + iterateLayers(animationData2.assets[i].layers); + } + } + } + } + }; + }(); + var checkShapes = function() { + var minimumVersion = [4, 4, 18]; + function completeClosingShapes(arr) { + var i; + var len = arr.length; + var j2; + var jLen; + for (i = len - 1;i >= 0; i -= 1) { + if (arr[i].ty === "sh") { + if (arr[i].ks.k.i) { + arr[i].ks.k.c = arr[i].closed; + } else { + jLen = arr[i].ks.k.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (arr[i].ks.k[j2].s) { + arr[i].ks.k[j2].s[0].c = arr[i].closed; + } + if (arr[i].ks.k[j2].e) { + arr[i].ks.k[j2].e[0].c = arr[i].closed; + } + } + } + } else if (arr[i].ty === "gr") { + completeClosingShapes(arr[i].it); + } + } + } + function iterateLayers(layers) { + var layerData; + var i; + var len = layers.length; + var j2; + var jLen; + var k2; + var kLen; + for (i = 0;i < len; i += 1) { + layerData = layers[i]; + if (layerData.hasMask) { + var maskProps = layerData.masksProperties; + jLen = maskProps.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (maskProps[j2].pt.k.i) { + maskProps[j2].pt.k.c = maskProps[j2].cl; + } else { + kLen = maskProps[j2].pt.k.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + if (maskProps[j2].pt.k[k2].s) { + maskProps[j2].pt.k[k2].s[0].c = maskProps[j2].cl; + } + if (maskProps[j2].pt.k[k2].e) { + maskProps[j2].pt.k[k2].e[0].c = maskProps[j2].cl; + } + } + } + } + } + if (layerData.ty === 4) { + completeClosingShapes(layerData.shapes); + } + } + } + return function(animationData2) { + if (checkVersion(minimumVersion, animationData2.v)) { + iterateLayers(animationData2.layers); + if (animationData2.assets) { + var i; + var len = animationData2.assets.length; + for (i = 0;i < len; i += 1) { + if (animationData2.assets[i].layers) { + iterateLayers(animationData2.assets[i].layers); + } + } + } + } + }; + }(); + function completeData(animationData2) { + if (animationData2.__complete) { + return; + } + checkColors(animationData2); + checkText(animationData2); + checkChars(animationData2); + checkPathProperties(animationData2); + checkShapes(animationData2); + completeLayers(animationData2.layers, animationData2.assets); + completeChars(animationData2.chars, animationData2.assets); + animationData2.__complete = true; + } + function completeText(data2) { + if (data2.t.a.length === 0 && !("m" in data2.t.p)) { + } + } + var moduleOb = {}; + moduleOb.completeData = completeData; + moduleOb.checkColors = checkColors; + moduleOb.checkChars = checkChars; + moduleOb.checkPathProperties = checkPathProperties; + moduleOb.checkShapes = checkShapes; + moduleOb.completeLayers = completeLayers; + return moduleOb; + } + if (!_workerSelf.dataManager) { + _workerSelf.dataManager = dataFunctionManager(); + } + if (!_workerSelf.assetLoader) { + _workerSelf.assetLoader = function() { + function formatResponse(xhr) { + var contentTypeHeader = xhr.getResponseHeader("content-type"); + if (contentTypeHeader && xhr.responseType === "json" && contentTypeHeader.indexOf("json") !== -1) { + return xhr.response; + } + if (xhr.response && typeof xhr.response === "object") { + return xhr.response; + } + if (xhr.response && typeof xhr.response === "string") { + return JSON.parse(xhr.response); + } + if (xhr.responseText) { + return JSON.parse(xhr.responseText); + } + return null; + } + function loadAsset(path, fullPath, callback, errorCallback) { + var response; + var xhr = new XMLHttpRequest; + try { + xhr.responseType = "json"; + } catch (err) { + } + xhr.onreadystatechange = function() { + if (xhr.readyState === 4) { + if (xhr.status === 200) { + response = formatResponse(xhr); + callback(response); + } else { + try { + response = formatResponse(xhr); + callback(response); + } catch (err) { + if (errorCallback) { + errorCallback(err); + } + } + } + } + }; + try { + xhr.open("GET", path, true); + } catch (error) { + xhr.open("GET", fullPath + "/" + path, true); + } + xhr.send(); + } + return { + load: loadAsset + }; + }(); + } + if (e.data.type === "loadAnimation") { + _workerSelf.assetLoader.load(e.data.path, e.data.fullPath, function(data2) { + _workerSelf.dataManager.completeData(data2); + _workerSelf.postMessage({ + id: e.data.id, + payload: data2, + status: "success" + }); + }, function() { + _workerSelf.postMessage({ + id: e.data.id, + status: "error" + }); + }); + } else if (e.data.type === "complete") { + var animation = e.data.animation; + _workerSelf.dataManager.completeData(animation); + _workerSelf.postMessage({ + id: e.data.id, + payload: animation, + status: "success" + }); + } else if (e.data.type === "loadData") { + _workerSelf.assetLoader.load(e.data.path, e.data.fullPath, function(data2) { + _workerSelf.postMessage({ + id: e.data.id, + payload: data2, + status: "success" + }); + }, function() { + _workerSelf.postMessage({ + id: e.data.id, + status: "error" + }); + }); + } + }); + workerInstance.onmessage = function(event) { + var data2 = event.data; + var id = data2.id; + var process2 = processes[id]; + processes[id] = null; + if (data2.status === "success") { + process2.onComplete(data2.payload); + } else if (process2.onError) { + process2.onError(); + } + }; + } + } + function createProcess(onComplete, onError) { + _counterId += 1; + var id = "processId_" + _counterId; + processes[id] = { + onComplete, + onError + }; + return id; + } + function loadAnimation2(path, onComplete, onError) { + setupWorker(); + var processId = createProcess(onComplete, onError); + workerInstance.postMessage({ + type: "loadAnimation", + path, + fullPath: window.location.origin + window.location.pathname, + id: processId + }); + } + function loadData(path, onComplete, onError) { + setupWorker(); + var processId = createProcess(onComplete, onError); + workerInstance.postMessage({ + type: "loadData", + path, + fullPath: window.location.origin + window.location.pathname, + id: processId + }); + } + function completeAnimation(anim, onComplete, onError) { + setupWorker(); + var processId = createProcess(onComplete, onError); + workerInstance.postMessage({ + type: "complete", + animation: anim, + id: processId + }); + } + return { + loadAnimation: loadAnimation2, + loadData, + completeAnimation + }; + }(); + const ImagePreloader = function() { + var proxyImage = function() { + var canvas = createTag("canvas"); + canvas.width = 1; + canvas.height = 1; + var ctx = canvas.getContext("2d"); + ctx.fillStyle = "rgba(0,0,0,0)"; + ctx.fillRect(0, 0, 1, 1); + return canvas; + }(); + function imageLoaded() { + this.loadedAssets += 1; + if (this.loadedAssets === this.totalImages && this.loadedFootagesCount === this.totalFootages) { + if (this.imagesLoadedCb) { + this.imagesLoadedCb(null); + } + } + } + function footageLoaded() { + this.loadedFootagesCount += 1; + if (this.loadedAssets === this.totalImages && this.loadedFootagesCount === this.totalFootages) { + if (this.imagesLoadedCb) { + this.imagesLoadedCb(null); + } + } + } + function getAssetsPath(assetData, assetsPath, originalPath) { + var path = ""; + if (assetData.e) { + path = assetData.p; + } else if (assetsPath) { + var imagePath = assetData.p; + if (imagePath.indexOf("images/") !== -1) { + imagePath = imagePath.split("/")[1]; + } + path = assetsPath + imagePath; + } else { + path = originalPath; + path += assetData.u ? assetData.u : ""; + path += assetData.p; + } + return path; + } + function testImageLoaded(img) { + var _count = 0; + var intervalId = setInterval(function() { + var box = img.getBBox(); + if (box.width || _count > 500) { + this._imageLoaded(); + clearInterval(intervalId); + } + _count += 1; + }.bind(this), 50); + } + function createImageData(assetData) { + var path = getAssetsPath(assetData, this.assetsPath, this.path); + var img = createNS("image"); + if (isSafari) { + this.testImageLoaded(img); + } else { + img.addEventListener("load", this._imageLoaded, false); + } + img.addEventListener("error", function() { + ob2.img = proxyImage; + this._imageLoaded(); + }.bind(this), false); + img.setAttributeNS("http://www.w3.org/1999/xlink", "href", path); + if (this._elementHelper.append) { + this._elementHelper.append(img); + } else { + this._elementHelper.appendChild(img); + } + var ob2 = { + img, + assetData + }; + return ob2; + } + function createImgData(assetData) { + var path = getAssetsPath(assetData, this.assetsPath, this.path); + var img = createTag("img"); + img.crossOrigin = "anonymous"; + img.addEventListener("load", this._imageLoaded, false); + img.addEventListener("error", function() { + ob2.img = proxyImage; + this._imageLoaded(); + }.bind(this), false); + img.src = path; + var ob2 = { + img, + assetData + }; + return ob2; + } + function createFootageData(data2) { + var ob2 = { + assetData: data2 + }; + var path = getAssetsPath(data2, this.assetsPath, this.path); + dataManager.loadData(path, function(footageData) { + ob2.img = footageData; + this._footageLoaded(); + }.bind(this), function() { + ob2.img = {}; + this._footageLoaded(); + }.bind(this)); + return ob2; + } + function loadAssets(assets, cb) { + this.imagesLoadedCb = cb; + var i; + var len = assets.length; + for (i = 0;i < len; i += 1) { + if (!assets[i].layers) { + if (!assets[i].t || assets[i].t === "seq") { + this.totalImages += 1; + this.images.push(this._createImageData(assets[i])); + } else if (assets[i].t === 3) { + this.totalFootages += 1; + this.images.push(this.createFootageData(assets[i])); + } + } + } + } + function setPath(path) { + this.path = path || ""; + } + function setAssetsPath(path) { + this.assetsPath = path || ""; + } + function getAsset(assetData) { + var i = 0; + var len = this.images.length; + while (i < len) { + if (this.images[i].assetData === assetData) { + return this.images[i].img; + } + i += 1; + } + return null; + } + function destroy() { + this.imagesLoadedCb = null; + this.images.length = 0; + } + function loadedImages() { + return this.totalImages === this.loadedAssets; + } + function loadedFootages() { + return this.totalFootages === this.loadedFootagesCount; + } + function setCacheType(type, elementHelper) { + if (type === "svg") { + this._elementHelper = elementHelper; + this._createImageData = this.createImageData.bind(this); + } else { + this._createImageData = this.createImgData.bind(this); + } + } + function ImagePreloaderFactory() { + this._imageLoaded = imageLoaded.bind(this); + this._footageLoaded = footageLoaded.bind(this); + this.testImageLoaded = testImageLoaded.bind(this); + this.createFootageData = createFootageData.bind(this); + this.assetsPath = ""; + this.path = ""; + this.totalImages = 0; + this.totalFootages = 0; + this.loadedAssets = 0; + this.loadedFootagesCount = 0; + this.imagesLoadedCb = null; + this.images = []; + } + ImagePreloaderFactory.prototype = { + loadAssets, + setAssetsPath, + setPath, + loadedImages, + loadedFootages, + destroy, + getAsset, + createImgData, + createImageData, + imageLoaded, + footageLoaded, + setCacheType + }; + return ImagePreloaderFactory; + }(); + BaseEvent.prototype = { + triggerEvent: function(eventName, args) { + if (this._cbs[eventName]) { + var callbacks = this._cbs[eventName]; + for (var i = 0;i < callbacks.length; i += 1) { + callbacks[i](args); + } + } + }, + addEventListener: function(eventName, callback) { + if (!this._cbs[eventName]) { + this._cbs[eventName] = []; + } + this._cbs[eventName].push(callback); + return function() { + this.removeEventListener(eventName, callback); + }.bind(this); + }, + removeEventListener: function(eventName, callback) { + if (!callback) { + this._cbs[eventName] = null; + } else if (this._cbs[eventName]) { + var i = 0; + var len = this._cbs[eventName].length; + while (i < len) { + if (this._cbs[eventName][i] === callback) { + this._cbs[eventName].splice(i, 1); + i -= 1; + len -= 1; + } + i += 1; + } + if (!this._cbs[eventName].length) { + this._cbs[eventName] = null; + } + } + } + }; + const markerParser = function() { + function parsePayloadLines(payload) { + var lines = payload.split(`\r +`); + var keys2 = {}; + var line; + var keysCount = 0; + for (var i = 0;i < lines.length; i += 1) { + line = lines[i].split(":"); + if (line.length === 2) { + keys2[line[0]] = line[1].trim(); + keysCount += 1; + } + } + if (keysCount === 0) { + throw new Error; + } + return keys2; + } + return function(_markers) { + var markers = []; + for (var i = 0;i < _markers.length; i += 1) { + var _marker = _markers[i]; + var markerData = { + time: _marker.tm, + duration: _marker.dr + }; + try { + markerData.payload = JSON.parse(_markers[i].cm); + } catch (_2) { + try { + markerData.payload = parsePayloadLines(_markers[i].cm); + } catch (__) { + markerData.payload = { + name: _markers[i].cm + }; + } + } + markers.push(markerData); + } + return markers; + }; + }(); + const ProjectInterface = function() { + function registerComposition(comp2) { + this.compositions.push(comp2); + } + return function() { + function _thisProjectFunction(name2) { + var i = 0; + var len = this.compositions.length; + while (i < len) { + if (this.compositions[i].data && this.compositions[i].data.nm === name2) { + if (this.compositions[i].prepareFrame && this.compositions[i].data.xt) { + this.compositions[i].prepareFrame(this.currentFrame); + } + return this.compositions[i].compInterface; + } + i += 1; + } + return null; + } + _thisProjectFunction.compositions = []; + _thisProjectFunction.currentFrame = 0; + _thisProjectFunction.registerComposition = registerComposition; + return _thisProjectFunction; + }; + }(); + const renderers = {}; + const registerRenderer = (key2, value2) => { + renderers[key2] = value2; + }; + const AnimationItem = function() { + this._cbs = []; + this.name = ""; + this.path = ""; + this.isLoaded = false; + this.currentFrame = 0; + this.currentRawFrame = 0; + this.firstFrame = 0; + this.totalFrames = 0; + this.frameRate = 0; + this.frameMult = 0; + this.playSpeed = 1; + this.playDirection = 1; + this.playCount = 0; + this.animationData = {}; + this.assets = []; + this.isPaused = true; + this.autoplay = false; + this.loop = true; + this.renderer = null; + this.animationID = createElementID(); + this.assetsPath = ""; + this.timeCompleted = 0; + this.segmentPos = 0; + this.isSubframeEnabled = getSubframeEnabled(); + this.segments = []; + this._idle = true; + this._completedLoop = false; + this.projectInterface = ProjectInterface(); + this.imagePreloader = new ImagePreloader; + this.audioController = audioControllerFactory(); + this.markers = []; + this.configAnimation = this.configAnimation.bind(this); + this.onSetupError = this.onSetupError.bind(this); + this.onSegmentComplete = this.onSegmentComplete.bind(this); + this.drawnFrameEvent = new BMEnterFrameEvent("drawnFrame", 0, 0, 0); + }; + extendPrototype([BaseEvent], AnimationItem); + AnimationItem.prototype.setParams = function(params) { + if (params.wrapper || params.container) { + this.wrapper = params.wrapper || params.container; + } + var animType = "svg"; + if (params.animType) { + animType = params.animType; + } else if (params.renderer) { + animType = params.renderer; + } + const RendererClass = getRenderer(animType); + this.renderer = new RendererClass(this, params.rendererSettings); + this.imagePreloader.setCacheType(animType, this.renderer.globalData.defs); + this.renderer.setProjectInterface(this.projectInterface); + this.animType = animType; + if (params.loop === "" || params.loop === null || params.loop === undefined || params.loop === true) { + this.loop = true; + } else if (params.loop === false) { + this.loop = false; + } else { + this.loop = parseInt(params.loop, 10); + } + this.autoplay = "autoplay" in params ? params.autoplay : true; + this.name = params.name ? params.name : ""; + this.autoloadSegments = Object.prototype.hasOwnProperty.call(params, "autoloadSegments") ? params.autoloadSegments : true; + this.assetsPath = params.assetsPath; + this.initialSegment = params.initialSegment; + if (params.audioFactory) { + this.audioController.setAudioFactory(params.audioFactory); + } + if (params.animationData) { + this.setupAnimation(params.animationData); + } else if (params.path) { + if (params.path.lastIndexOf("\\") !== -1) { + this.path = params.path.substr(0, params.path.lastIndexOf("\\") + 1); + } else { + this.path = params.path.substr(0, params.path.lastIndexOf("/") + 1); + } + this.fileName = params.path.substr(params.path.lastIndexOf("/") + 1); + this.fileName = this.fileName.substr(0, this.fileName.lastIndexOf(".json")); + dataManager.loadAnimation(params.path, this.configAnimation, this.onSetupError); + } + }; + AnimationItem.prototype.onSetupError = function() { + this.trigger("data_failed"); + }; + AnimationItem.prototype.setupAnimation = function(data2) { + dataManager.completeAnimation(data2, this.configAnimation); + }; + AnimationItem.prototype.setData = function(wrapper, animationData2) { + if (animationData2) { + if (typeof animationData2 !== "object") { + animationData2 = JSON.parse(animationData2); + } + } + var params = { + wrapper, + animationData: animationData2 + }; + var wrapperAttributes = wrapper.attributes; + params.path = wrapperAttributes.getNamedItem("data-animation-path") ? wrapperAttributes.getNamedItem("data-animation-path").value : wrapperAttributes.getNamedItem("data-bm-path") ? wrapperAttributes.getNamedItem("data-bm-path").value : wrapperAttributes.getNamedItem("bm-path") ? wrapperAttributes.getNamedItem("bm-path").value : ""; + params.animType = wrapperAttributes.getNamedItem("data-anim-type") ? wrapperAttributes.getNamedItem("data-anim-type").value : wrapperAttributes.getNamedItem("data-bm-type") ? wrapperAttributes.getNamedItem("data-bm-type").value : wrapperAttributes.getNamedItem("bm-type") ? wrapperAttributes.getNamedItem("bm-type").value : wrapperAttributes.getNamedItem("data-bm-renderer") ? wrapperAttributes.getNamedItem("data-bm-renderer").value : wrapperAttributes.getNamedItem("bm-renderer") ? wrapperAttributes.getNamedItem("bm-renderer").value : "canvas"; + var loop = wrapperAttributes.getNamedItem("data-anim-loop") ? wrapperAttributes.getNamedItem("data-anim-loop").value : wrapperAttributes.getNamedItem("data-bm-loop") ? wrapperAttributes.getNamedItem("data-bm-loop").value : wrapperAttributes.getNamedItem("bm-loop") ? wrapperAttributes.getNamedItem("bm-loop").value : ""; + if (loop === "false") { + params.loop = false; + } else if (loop === "true") { + params.loop = true; + } else if (loop !== "") { + params.loop = parseInt(loop, 10); + } + var autoplay = wrapperAttributes.getNamedItem("data-anim-autoplay") ? wrapperAttributes.getNamedItem("data-anim-autoplay").value : wrapperAttributes.getNamedItem("data-bm-autoplay") ? wrapperAttributes.getNamedItem("data-bm-autoplay").value : wrapperAttributes.getNamedItem("bm-autoplay") ? wrapperAttributes.getNamedItem("bm-autoplay").value : true; + params.autoplay = autoplay !== "false"; + params.name = wrapperAttributes.getNamedItem("data-name") ? wrapperAttributes.getNamedItem("data-name").value : wrapperAttributes.getNamedItem("data-bm-name") ? wrapperAttributes.getNamedItem("data-bm-name").value : wrapperAttributes.getNamedItem("bm-name") ? wrapperAttributes.getNamedItem("bm-name").value : ""; + var prerender = wrapperAttributes.getNamedItem("data-anim-prerender") ? wrapperAttributes.getNamedItem("data-anim-prerender").value : wrapperAttributes.getNamedItem("data-bm-prerender") ? wrapperAttributes.getNamedItem("data-bm-prerender").value : wrapperAttributes.getNamedItem("bm-prerender") ? wrapperAttributes.getNamedItem("bm-prerender").value : ""; + if (prerender === "false") { + params.prerender = false; + } + this.setParams(params); + }; + AnimationItem.prototype.includeLayers = function(data2) { + if (data2.op > this.animationData.op) { + this.animationData.op = data2.op; + this.totalFrames = Math.floor(data2.op - this.animationData.ip); + } + var layers = this.animationData.layers; + var i; + var len = layers.length; + var newLayers = data2.layers; + var j2; + var jLen = newLayers.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + i = 0; + while (i < len) { + if (layers[i].id === newLayers[j2].id) { + layers[i] = newLayers[j2]; + break; + } + i += 1; + } + } + if (data2.chars || data2.fonts) { + this.renderer.globalData.fontManager.addChars(data2.chars); + this.renderer.globalData.fontManager.addFonts(data2.fonts, this.renderer.globalData.defs); + } + if (data2.assets) { + len = data2.assets.length; + for (i = 0;i < len; i += 1) { + this.animationData.assets.push(data2.assets[i]); + } + } + this.animationData.__complete = false; + dataManager.completeAnimation(this.animationData, this.onSegmentComplete); + }; + AnimationItem.prototype.onSegmentComplete = function(data2) { + this.animationData = data2; + var expressionsPlugin2 = getExpressionsPlugin(); + if (expressionsPlugin2) { + expressionsPlugin2.initExpressions(this); + } + this.loadNextSegment(); + }; + AnimationItem.prototype.loadNextSegment = function() { + var segments = this.animationData.segments; + if (!segments || segments.length === 0 || !this.autoloadSegments) { + this.trigger("data_ready"); + this.timeCompleted = this.totalFrames; + return; + } + var segment = segments.shift(); + this.timeCompleted = segment.time * this.frameRate; + var segmentPath = this.path + this.fileName + "_" + this.segmentPos + ".json"; + this.segmentPos += 1; + dataManager.loadData(segmentPath, this.includeLayers.bind(this), function() { + this.trigger("data_failed"); + }.bind(this)); + }; + AnimationItem.prototype.loadSegments = function() { + var segments = this.animationData.segments; + if (!segments) { + this.timeCompleted = this.totalFrames; + } + this.loadNextSegment(); + }; + AnimationItem.prototype.imagesLoaded = function() { + this.trigger("loaded_images"); + this.checkLoaded(); + }; + AnimationItem.prototype.preloadImages = function() { + this.imagePreloader.setAssetsPath(this.assetsPath); + this.imagePreloader.setPath(this.path); + this.imagePreloader.loadAssets(this.animationData.assets, this.imagesLoaded.bind(this)); + }; + AnimationItem.prototype.configAnimation = function(animData) { + if (!this.renderer) { + return; + } + try { + this.animationData = animData; + if (this.initialSegment) { + this.totalFrames = Math.floor(this.initialSegment[1] - this.initialSegment[0]); + this.firstFrame = Math.round(this.initialSegment[0]); + } else { + this.totalFrames = Math.floor(this.animationData.op - this.animationData.ip); + this.firstFrame = Math.round(this.animationData.ip); + } + this.renderer.configAnimation(animData); + if (!animData.assets) { + animData.assets = []; + } + this.assets = this.animationData.assets; + this.frameRate = this.animationData.fr; + this.frameMult = this.animationData.fr / 1000; + this.renderer.searchExtraCompositions(animData.assets); + this.markers = markerParser(animData.markers || []); + this.trigger("config_ready"); + this.preloadImages(); + this.loadSegments(); + this.updaFrameModifier(); + this.waitForFontsLoaded(); + if (this.isPaused) { + this.audioController.pause(); + } + } catch (error) { + this.triggerConfigError(error); + } + }; + AnimationItem.prototype.waitForFontsLoaded = function() { + if (!this.renderer) { + return; + } + if (this.renderer.globalData.fontManager.isLoaded) { + this.checkLoaded(); + } else { + setTimeout(this.waitForFontsLoaded.bind(this), 20); + } + }; + AnimationItem.prototype.checkLoaded = function() { + if (!this.isLoaded && this.renderer.globalData.fontManager.isLoaded && (this.imagePreloader.loadedImages() || this.renderer.rendererType !== "canvas") && this.imagePreloader.loadedFootages()) { + this.isLoaded = true; + var expressionsPlugin2 = getExpressionsPlugin(); + if (expressionsPlugin2) { + expressionsPlugin2.initExpressions(this); + } + this.renderer.initItems(); + setTimeout(function() { + this.trigger("DOMLoaded"); + }.bind(this), 0); + this.gotoFrame(); + if (this.autoplay) { + this.play(); + } + } + }; + AnimationItem.prototype.resize = function() { + this.renderer.updateContainerSize(); + }; + AnimationItem.prototype.setSubframe = function(flag) { + this.isSubframeEnabled = !!flag; + }; + AnimationItem.prototype.gotoFrame = function() { + this.currentFrame = this.isSubframeEnabled ? this.currentRawFrame : ~~this.currentRawFrame; + if (this.timeCompleted !== this.totalFrames && this.currentFrame > this.timeCompleted) { + this.currentFrame = this.timeCompleted; + } + this.trigger("enterFrame"); + this.renderFrame(); + this.trigger("drawnFrame"); + }; + AnimationItem.prototype.renderFrame = function() { + if (this.isLoaded === false || !this.renderer) { + return; + } + try { + this.renderer.renderFrame(this.currentFrame + this.firstFrame); + } catch (error) { + this.triggerRenderFrameError(error); + } + }; + AnimationItem.prototype.play = function(name2) { + if (name2 && this.name !== name2) { + return; + } + if (this.isPaused === true) { + this.isPaused = false; + this.trigger("_pause"); + this.audioController.resume(); + if (this._idle) { + this._idle = false; + this.trigger("_active"); + } + } + }; + AnimationItem.prototype.pause = function(name2) { + if (name2 && this.name !== name2) { + return; + } + if (this.isPaused === false) { + this.isPaused = true; + this.trigger("_play"); + this._idle = true; + this.trigger("_idle"); + this.audioController.pause(); + } + }; + AnimationItem.prototype.togglePause = function(name2) { + if (name2 && this.name !== name2) { + return; + } + if (this.isPaused === true) { + this.play(); + } else { + this.pause(); + } + }; + AnimationItem.prototype.stop = function(name2) { + if (name2 && this.name !== name2) { + return; + } + this.pause(); + this.playCount = 0; + this._completedLoop = false; + this.setCurrentRawFrameValue(0); + }; + AnimationItem.prototype.getMarkerData = function(markerName) { + var marker; + for (var i = 0;i < this.markers.length; i += 1) { + marker = this.markers[i]; + if (marker.payload && marker.payload.name === markerName) { + return marker; + } + } + return null; + }; + AnimationItem.prototype.goToAndStop = function(value2, isFrame, name2) { + if (name2 && this.name !== name2) { + return; + } + var numValue = Number(value2); + if (isNaN(numValue)) { + var marker = this.getMarkerData(value2); + if (marker) { + this.goToAndStop(marker.time, true); + } + } else if (isFrame) { + this.setCurrentRawFrameValue(value2); + } else { + this.setCurrentRawFrameValue(value2 * this.frameModifier); + } + this.pause(); + }; + AnimationItem.prototype.goToAndPlay = function(value2, isFrame, name2) { + if (name2 && this.name !== name2) { + return; + } + var numValue = Number(value2); + if (isNaN(numValue)) { + var marker = this.getMarkerData(value2); + if (marker) { + if (!marker.duration) { + this.goToAndStop(marker.time, true); + } else { + this.playSegments([marker.time, marker.time + marker.duration], true); + } + } + } else { + this.goToAndStop(numValue, isFrame, name2); + } + this.play(); + }; + AnimationItem.prototype.advanceTime = function(value2) { + if (this.isPaused === true || this.isLoaded === false) { + return; + } + var nextValue = this.currentRawFrame + value2 * this.frameModifier; + var _isComplete = false; + if (nextValue >= this.totalFrames - 1 && this.frameModifier > 0) { + if (!this.loop || this.playCount === this.loop) { + if (!this.checkSegments(nextValue > this.totalFrames ? nextValue % this.totalFrames : 0)) { + _isComplete = true; + nextValue = this.totalFrames - 1; + } + } else if (nextValue >= this.totalFrames) { + this.playCount += 1; + if (!this.checkSegments(nextValue % this.totalFrames)) { + this.setCurrentRawFrameValue(nextValue % this.totalFrames); + this._completedLoop = true; + this.trigger("loopComplete"); + } + } else { + this.setCurrentRawFrameValue(nextValue); + } + } else if (nextValue < 0) { + if (!this.checkSegments(nextValue % this.totalFrames)) { + if (this.loop && !(this.playCount-- <= 0 && this.loop !== true)) { + this.setCurrentRawFrameValue(this.totalFrames + nextValue % this.totalFrames); + if (!this._completedLoop) { + this._completedLoop = true; + } else { + this.trigger("loopComplete"); + } + } else { + _isComplete = true; + nextValue = 0; + } + } + } else { + this.setCurrentRawFrameValue(nextValue); + } + if (_isComplete) { + this.setCurrentRawFrameValue(nextValue); + this.pause(); + this.trigger("complete"); + } + }; + AnimationItem.prototype.adjustSegment = function(arr, offset) { + this.playCount = 0; + if (arr[1] < arr[0]) { + if (this.frameModifier > 0) { + if (this.playSpeed < 0) { + this.setSpeed(-this.playSpeed); + } else { + this.setDirection(-1); + } + } + this.totalFrames = arr[0] - arr[1]; + this.timeCompleted = this.totalFrames; + this.firstFrame = arr[1]; + this.setCurrentRawFrameValue(this.totalFrames - 0.001 - offset); + } else if (arr[1] > arr[0]) { + if (this.frameModifier < 0) { + if (this.playSpeed < 0) { + this.setSpeed(-this.playSpeed); + } else { + this.setDirection(1); + } + } + this.totalFrames = arr[1] - arr[0]; + this.timeCompleted = this.totalFrames; + this.firstFrame = arr[0]; + this.setCurrentRawFrameValue(0.001 + offset); + } + this.trigger("segmentStart"); + }; + AnimationItem.prototype.setSegment = function(init, end) { + var pendingFrame = -1; + if (this.isPaused) { + if (this.currentRawFrame + this.firstFrame < init) { + pendingFrame = init; + } else if (this.currentRawFrame + this.firstFrame > end) { + pendingFrame = end - init; + } + } + this.firstFrame = init; + this.totalFrames = end - init; + this.timeCompleted = this.totalFrames; + if (pendingFrame !== -1) { + this.goToAndStop(pendingFrame, true); + } + }; + AnimationItem.prototype.playSegments = function(arr, forceFlag) { + if (forceFlag) { + this.segments.length = 0; + } + if (typeof arr[0] === "object") { + var i; + var len = arr.length; + for (i = 0;i < len; i += 1) { + this.segments.push(arr[i]); + } + } else { + this.segments.push(arr); + } + if (this.segments.length && forceFlag) { + this.adjustSegment(this.segments.shift(), 0); + } + if (this.isPaused) { + this.play(); + } + }; + AnimationItem.prototype.resetSegments = function(forceFlag) { + this.segments.length = 0; + this.segments.push([this.animationData.ip, this.animationData.op]); + if (forceFlag) { + this.checkSegments(0); + } + }; + AnimationItem.prototype.checkSegments = function(offset) { + if (this.segments.length) { + this.adjustSegment(this.segments.shift(), offset); + return true; + } + return false; + }; + AnimationItem.prototype.destroy = function(name2) { + if (name2 && this.name !== name2 || !this.renderer) { + return; + } + this.renderer.destroy(); + this.imagePreloader.destroy(); + this.trigger("destroy"); + this._cbs = null; + this.onEnterFrame = null; + this.onLoopComplete = null; + this.onComplete = null; + this.onSegmentStart = null; + this.onDestroy = null; + this.renderer = null; + this.renderer = null; + this.imagePreloader = null; + this.projectInterface = null; + }; + AnimationItem.prototype.setCurrentRawFrameValue = function(value2) { + this.currentRawFrame = value2; + this.gotoFrame(); + }; + AnimationItem.prototype.setSpeed = function(val2) { + this.playSpeed = val2; + this.updaFrameModifier(); + }; + AnimationItem.prototype.setDirection = function(val2) { + this.playDirection = val2 < 0 ? -1 : 1; + this.updaFrameModifier(); + }; + AnimationItem.prototype.setVolume = function(val2, name2) { + if (name2 && this.name !== name2) { + return; + } + this.audioController.setVolume(val2); + }; + AnimationItem.prototype.getVolume = function() { + return this.audioController.getVolume(); + }; + AnimationItem.prototype.mute = function(name2) { + if (name2 && this.name !== name2) { + return; + } + this.audioController.mute(); + }; + AnimationItem.prototype.unmute = function(name2) { + if (name2 && this.name !== name2) { + return; + } + this.audioController.unmute(); + }; + AnimationItem.prototype.updaFrameModifier = function() { + this.frameModifier = this.frameMult * this.playSpeed * this.playDirection; + this.audioController.setRate(this.playSpeed * this.playDirection); + }; + AnimationItem.prototype.getPath = function() { + return this.path; + }; + AnimationItem.prototype.getAssetsPath = function(assetData) { + var path = ""; + if (assetData.e) { + path = assetData.p; + } else if (this.assetsPath) { + var imagePath = assetData.p; + if (imagePath.indexOf("images/") !== -1) { + imagePath = imagePath.split("/")[1]; + } + path = this.assetsPath + imagePath; + } else { + path = this.path; + path += assetData.u ? assetData.u : ""; + path += assetData.p; + } + return path; + }; + AnimationItem.prototype.getAssetData = function(id) { + var i = 0; + var len = this.assets.length; + while (i < len) { + if (id === this.assets[i].id) { + return this.assets[i]; + } + i += 1; + } + return null; + }; + AnimationItem.prototype.hide = function() { + this.renderer.hide(); + }; + AnimationItem.prototype.show = function() { + this.renderer.show(); + }; + AnimationItem.prototype.getDuration = function(isFrame) { + return isFrame ? this.totalFrames : this.totalFrames / this.frameRate; + }; + AnimationItem.prototype.updateDocumentData = function(path, documentData, index2) { + try { + var element = this.renderer.getElementByPath(path); + element.updateDocumentData(documentData, index2); + } catch (error) { + } + }; + AnimationItem.prototype.trigger = function(name2) { + if (this._cbs && this._cbs[name2]) { + switch (name2) { + case "enterFrame": + this.triggerEvent(name2, new BMEnterFrameEvent(name2, this.currentFrame, this.totalFrames, this.frameModifier)); + break; + case "drawnFrame": + this.drawnFrameEvent.currentTime = this.currentFrame; + this.drawnFrameEvent.totalTime = this.totalFrames; + this.drawnFrameEvent.direction = this.frameModifier; + this.triggerEvent(name2, this.drawnFrameEvent); + break; + case "loopComplete": + this.triggerEvent(name2, new BMCompleteLoopEvent(name2, this.loop, this.playCount, this.frameMult)); + break; + case "complete": + this.triggerEvent(name2, new BMCompleteEvent(name2, this.frameMult)); + break; + case "segmentStart": + this.triggerEvent(name2, new BMSegmentStartEvent(name2, this.firstFrame, this.totalFrames)); + break; + case "destroy": + this.triggerEvent(name2, new BMDestroyEvent(name2, this)); + break; + default: + this.triggerEvent(name2); + } + } + if (name2 === "enterFrame" && this.onEnterFrame) { + this.onEnterFrame.call(this, new BMEnterFrameEvent(name2, this.currentFrame, this.totalFrames, this.frameMult)); + } + if (name2 === "loopComplete" && this.onLoopComplete) { + this.onLoopComplete.call(this, new BMCompleteLoopEvent(name2, this.loop, this.playCount, this.frameMult)); + } + if (name2 === "complete" && this.onComplete) { + this.onComplete.call(this, new BMCompleteEvent(name2, this.frameMult)); + } + if (name2 === "segmentStart" && this.onSegmentStart) { + this.onSegmentStart.call(this, new BMSegmentStartEvent(name2, this.firstFrame, this.totalFrames)); + } + if (name2 === "destroy" && this.onDestroy) { + this.onDestroy.call(this, new BMDestroyEvent(name2, this)); + } + }; + AnimationItem.prototype.triggerRenderFrameError = function(nativeError) { + var error = new BMRenderFrameErrorEvent(nativeError, this.currentFrame); + this.triggerEvent("error", error); + if (this.onError) { + this.onError.call(this, error); + } + }; + AnimationItem.prototype.triggerConfigError = function(nativeError) { + var error = new BMConfigErrorEvent(nativeError, this.currentFrame); + this.triggerEvent("error", error); + if (this.onError) { + this.onError.call(this, error); + } + }; + const animationManager = function() { + var moduleOb = {}; + var registeredAnimations = []; + var initTime = 0; + var len = 0; + var playingAnimationsNum = 0; + var _stopped = true; + var _isFrozen = false; + function removeElement(ev) { + var i = 0; + var animItem = ev.target; + while (i < len) { + if (registeredAnimations[i].animation === animItem) { + registeredAnimations.splice(i, 1); + i -= 1; + len -= 1; + if (!animItem.isPaused) { + subtractPlayingCount(); + } + } + i += 1; + } + } + function registerAnimation(element, animationData2) { + if (!element) { + return null; + } + var i = 0; + while (i < len) { + if (registeredAnimations[i].elem === element && registeredAnimations[i].elem !== null) { + return registeredAnimations[i].animation; + } + i += 1; + } + var animItem = new AnimationItem; + setupAnimation(animItem, element); + animItem.setData(element, animationData2); + return animItem; + } + function getRegisteredAnimations() { + var i; + var lenAnims = registeredAnimations.length; + var animations = []; + for (i = 0;i < lenAnims; i += 1) { + animations.push(registeredAnimations[i].animation); + } + return animations; + } + function addPlayingCount() { + playingAnimationsNum += 1; + activate(); + } + function subtractPlayingCount() { + playingAnimationsNum -= 1; + } + function setupAnimation(animItem, element) { + animItem.addEventListener("destroy", removeElement); + animItem.addEventListener("_active", addPlayingCount); + animItem.addEventListener("_idle", subtractPlayingCount); + registeredAnimations.push({ elem: element, animation: animItem }); + len += 1; + } + function loadAnimation2(params) { + var animItem = new AnimationItem; + setupAnimation(animItem, null); + animItem.setParams(params); + return animItem; + } + function setSpeed(val2, animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.setSpeed(val2, animation); + } + } + function setDirection(val2, animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.setDirection(val2, animation); + } + } + function play(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.play(animation); + } + } + function resume(nowTime) { + var elapsedTime = nowTime - initTime; + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.advanceTime(elapsedTime); + } + initTime = nowTime; + if (playingAnimationsNum && !_isFrozen) { + window.requestAnimationFrame(resume); + } else { + _stopped = true; + } + } + function first2(nowTime) { + initTime = nowTime; + window.requestAnimationFrame(resume); + } + function pause(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.pause(animation); + } + } + function goToAndStop(value2, isFrame, animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.goToAndStop(value2, isFrame, animation); + } + } + function stop(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.stop(animation); + } + } + function togglePause(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.togglePause(animation); + } + } + function destroy(animation) { + var i; + for (i = len - 1;i >= 0; i -= 1) { + registeredAnimations[i].animation.destroy(animation); + } + } + function searchAnimations2(animationData2, standalone2, renderer2) { + var animElements = [].concat([].slice.call(document.getElementsByClassName("lottie")), [].slice.call(document.getElementsByClassName("bodymovin"))); + var i; + var lenAnims = animElements.length; + for (i = 0;i < lenAnims; i += 1) { + if (renderer2) { + animElements[i].setAttribute("data-bm-type", renderer2); + } + registerAnimation(animElements[i], animationData2); + } + if (standalone2 && lenAnims === 0) { + if (!renderer2) { + renderer2 = "svg"; + } + var body = document.getElementsByTagName("body")[0]; + body.innerText = ""; + var div2 = createTag("div"); + div2.style.width = "100%"; + div2.style.height = "100%"; + div2.setAttribute("data-bm-type", renderer2); + body.appendChild(div2); + registerAnimation(div2, animationData2); + } + } + function resize() { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.resize(); + } + } + function activate() { + if (!_isFrozen && playingAnimationsNum) { + if (_stopped) { + window.requestAnimationFrame(first2); + _stopped = false; + } + } + } + function freeze() { + _isFrozen = true; + } + function unfreeze() { + _isFrozen = false; + activate(); + } + function setVolume(val2, animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.setVolume(val2, animation); + } + } + function mute(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.mute(animation); + } + } + function unmute(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.unmute(animation); + } + } + moduleOb.registerAnimation = registerAnimation; + moduleOb.loadAnimation = loadAnimation2; + moduleOb.setSpeed = setSpeed; + moduleOb.setDirection = setDirection; + moduleOb.play = play; + moduleOb.pause = pause; + moduleOb.stop = stop; + moduleOb.togglePause = togglePause; + moduleOb.searchAnimations = searchAnimations2; + moduleOb.resize = resize; + moduleOb.goToAndStop = goToAndStop; + moduleOb.destroy = destroy; + moduleOb.freeze = freeze; + moduleOb.unfreeze = unfreeze; + moduleOb.setVolume = setVolume; + moduleOb.mute = mute; + moduleOb.unmute = unmute; + moduleOb.getRegisteredAnimations = getRegisteredAnimations; + return moduleOb; + }(); + const BezierFactory = function() { + var ob2 = {}; + ob2.getBezierEasing = getBezierEasing; + var beziers = {}; + function getBezierEasing(a, b, c, d, nm) { + var str = nm || ("bez_" + a + "_" + b + "_" + c + "_" + d).replace(/\./g, "p"); + if (beziers[str]) { + return beziers[str]; + } + var bezEasing = new BezierEasing([a, b, c, d]); + beziers[str] = bezEasing; + return bezEasing; + } + var NEWTON_ITERATIONS = 4; + var NEWTON_MIN_SLOPE = 0.001; + var SUBDIVISION_PRECISION = 0.0000001; + var SUBDIVISION_MAX_ITERATIONS = 10; + var kSplineTableSize = 11; + var kSampleStepSize = 1 / (kSplineTableSize - 1); + var float32ArraySupported = typeof Float32Array === "function"; + function A2(aA1, aA2) { + return 1 - 3 * aA2 + 3 * aA1; + } + function B2(aA1, aA2) { + return 3 * aA2 - 6 * aA1; + } + function C4(aA1) { + return 3 * aA1; + } + function calcBezier(aT, aA1, aA2) { + return ((A2(aA1, aA2) * aT + B2(aA1, aA2)) * aT + C4(aA1)) * aT; + } + function getSlope(aT, aA1, aA2) { + return 3 * A2(aA1, aA2) * aT * aT + 2 * B2(aA1, aA2) * aT + C4(aA1); + } + function binarySubdivide(aX, aA, aB, mX1, mX2) { + var currentX, currentT, i = 0; + do { + currentT = aA + (aB - aA) / 2; + currentX = calcBezier(currentT, mX1, mX2) - aX; + if (currentX > 0) { + aB = currentT; + } else { + aA = currentT; + } + } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS); + return currentT; + } + function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { + for (var i = 0;i < NEWTON_ITERATIONS; ++i) { + var currentSlope = getSlope(aGuessT, mX1, mX2); + if (currentSlope === 0) + return aGuessT; + var currentX = calcBezier(aGuessT, mX1, mX2) - aX; + aGuessT -= currentX / currentSlope; + } + return aGuessT; + } + function BezierEasing(points) { + this._p = points; + this._mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize); + this._precomputed = false; + this.get = this.get.bind(this); + } + BezierEasing.prototype = { + get: function(x2) { + var mX1 = this._p[0], mY1 = this._p[1], mX2 = this._p[2], mY2 = this._p[3]; + if (!this._precomputed) + this._precompute(); + if (mX1 === mY1 && mX2 === mY2) + return x2; + if (x2 === 0) + return 0; + if (x2 === 1) + return 1; + return calcBezier(this._getTForX(x2), mY1, mY2); + }, + _precompute: function() { + var mX1 = this._p[0], mY1 = this._p[1], mX2 = this._p[2], mY2 = this._p[3]; + this._precomputed = true; + if (mX1 !== mY1 || mX2 !== mY2) { + this._calcSampleValues(); + } + }, + _calcSampleValues: function() { + var mX1 = this._p[0], mX2 = this._p[2]; + for (var i = 0;i < kSplineTableSize; ++i) { + this._mSampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); + } + }, + _getTForX: function(aX) { + var mX1 = this._p[0], mX2 = this._p[2], mSampleValues = this._mSampleValues; + var intervalStart = 0; + var currentSample = 1; + var lastSample = kSplineTableSize - 1; + for (;currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) { + intervalStart += kSampleStepSize; + } + --currentSample; + var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]); + var guessForT = intervalStart + dist * kSampleStepSize; + var initialSlope = getSlope(guessForT, mX1, mX2); + if (initialSlope >= NEWTON_MIN_SLOPE) { + return newtonRaphsonIterate(aX, guessForT, mX1, mX2); + } + if (initialSlope === 0) { + return guessForT; + } + return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2); + } + }; + return ob2; + }(); + const pooling = function() { + function double(arr) { + return arr.concat(createSizedArray(arr.length)); + } + return { + double + }; + }(); + const poolFactory = function() { + return function(initialLength, _create, _release) { + var _length = 0; + var _maxLength = initialLength; + var pool = createSizedArray(_maxLength); + var ob2 = { + newElement, + release + }; + function newElement() { + var element; + if (_length) { + _length -= 1; + element = pool[_length]; + } else { + element = _create(); + } + return element; + } + function release(element) { + if (_length === _maxLength) { + pool = pooling.double(pool); + _maxLength *= 2; + } + if (_release) { + _release(element); + } + pool[_length] = element; + _length += 1; + } + return ob2; + }; + }(); + const bezierLengthPool = function() { + function create() { + return { + addedLength: 0, + percents: createTypedArray("float32", getDefaultCurveSegments()), + lengths: createTypedArray("float32", getDefaultCurveSegments()) + }; + } + return poolFactory(8, create); + }(); + const segmentsLengthPool = function() { + function create() { + return { + lengths: [], + totalLength: 0 + }; + } + function release(element) { + var i; + var len = element.lengths.length; + for (i = 0;i < len; i += 1) { + bezierLengthPool.release(element.lengths[i]); + } + element.lengths.length = 0; + } + return poolFactory(8, create, release); + }(); + const bez = bezFunction(); + const PropertyFactory = function() { + var initFrame = initialDefaultFrame; + var mathAbs = Math.abs; + function interpolateValue(frameNum, caching) { + var offsetTime = this.offsetTime; + var newValue; + if (this.propType === "multidimensional") { + newValue = createTypedArray("float32", this.pv.length); + } + var iterationIndex = caching.lastIndex; + var i = iterationIndex; + var len = this.keyframes.length - 1; + var flag = true; + var keyData; + var nextKeyData; + var keyframeMetadata; + while (flag) { + keyData = this.keyframes[i]; + nextKeyData = this.keyframes[i + 1]; + if (i === len - 1 && frameNum >= nextKeyData.t - offsetTime) { + if (keyData.h) { + keyData = nextKeyData; + } + iterationIndex = 0; + break; + } + if (nextKeyData.t - offsetTime > frameNum) { + iterationIndex = i; + break; + } + if (i < len - 1) { + i += 1; + } else { + iterationIndex = 0; + flag = false; + } + } + keyframeMetadata = this.keyframesMetadata[i] || {}; + var k2; + var kLen; + var perc; + var jLen; + var j2; + var fnc; + var nextKeyTime = nextKeyData.t - offsetTime; + var keyTime = keyData.t - offsetTime; + var endValue; + if (keyData.to) { + if (!keyframeMetadata.bezierData) { + keyframeMetadata.bezierData = bez.buildBezierData(keyData.s, nextKeyData.s || keyData.e, keyData.to, keyData.ti); + } + var bezierData = keyframeMetadata.bezierData; + if (frameNum >= nextKeyTime || frameNum < keyTime) { + var ind = frameNum >= nextKeyTime ? bezierData.points.length - 1 : 0; + kLen = bezierData.points[ind].point.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + newValue[k2] = bezierData.points[ind].point[k2]; + } + } else { + if (keyframeMetadata.__fnct) { + fnc = keyframeMetadata.__fnct; + } else { + fnc = BezierFactory.getBezierEasing(keyData.o.x, keyData.o.y, keyData.i.x, keyData.i.y, keyData.n).get; + keyframeMetadata.__fnct = fnc; + } + perc = fnc((frameNum - keyTime) / (nextKeyTime - keyTime)); + var distanceInLine = bezierData.segmentLength * perc; + var segmentPerc; + var addedLength = caching.lastFrame < frameNum && caching._lastKeyframeIndex === i ? caching._lastAddedLength : 0; + j2 = caching.lastFrame < frameNum && caching._lastKeyframeIndex === i ? caching._lastPoint : 0; + flag = true; + jLen = bezierData.points.length; + while (flag) { + addedLength += bezierData.points[j2].partialLength; + if (distanceInLine === 0 || perc === 0 || j2 === bezierData.points.length - 1) { + kLen = bezierData.points[j2].point.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + newValue[k2] = bezierData.points[j2].point[k2]; + } + break; + } else if (distanceInLine >= addedLength && distanceInLine < addedLength + bezierData.points[j2 + 1].partialLength) { + segmentPerc = (distanceInLine - addedLength) / bezierData.points[j2 + 1].partialLength; + kLen = bezierData.points[j2].point.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + newValue[k2] = bezierData.points[j2].point[k2] + (bezierData.points[j2 + 1].point[k2] - bezierData.points[j2].point[k2]) * segmentPerc; + } + break; + } + if (j2 < jLen - 1) { + j2 += 1; + } else { + flag = false; + } + } + caching._lastPoint = j2; + caching._lastAddedLength = addedLength - bezierData.points[j2].partialLength; + caching._lastKeyframeIndex = i; + } + } else { + var outX; + var outY; + var inX; + var inY; + var keyValue; + len = keyData.s.length; + endValue = nextKeyData.s || keyData.e; + if (this.sh && keyData.h !== 1) { + if (frameNum >= nextKeyTime) { + newValue[0] = endValue[0]; + newValue[1] = endValue[1]; + newValue[2] = endValue[2]; + } else if (frameNum <= keyTime) { + newValue[0] = keyData.s[0]; + newValue[1] = keyData.s[1]; + newValue[2] = keyData.s[2]; + } else { + var quatStart = createQuaternion(keyData.s); + var quatEnd = createQuaternion(endValue); + var time2 = (frameNum - keyTime) / (nextKeyTime - keyTime); + quaternionToEuler(newValue, slerp(quatStart, quatEnd, time2)); + } + } else { + for (i = 0;i < len; i += 1) { + if (keyData.h !== 1) { + if (frameNum >= nextKeyTime) { + perc = 1; + } else if (frameNum < keyTime) { + perc = 0; + } else { + if (keyData.o.x.constructor === Array) { + if (!keyframeMetadata.__fnct) { + keyframeMetadata.__fnct = []; + } + if (!keyframeMetadata.__fnct[i]) { + outX = keyData.o.x[i] === undefined ? keyData.o.x[0] : keyData.o.x[i]; + outY = keyData.o.y[i] === undefined ? keyData.o.y[0] : keyData.o.y[i]; + inX = keyData.i.x[i] === undefined ? keyData.i.x[0] : keyData.i.x[i]; + inY = keyData.i.y[i] === undefined ? keyData.i.y[0] : keyData.i.y[i]; + fnc = BezierFactory.getBezierEasing(outX, outY, inX, inY).get; + keyframeMetadata.__fnct[i] = fnc; + } else { + fnc = keyframeMetadata.__fnct[i]; + } + } else if (!keyframeMetadata.__fnct) { + outX = keyData.o.x; + outY = keyData.o.y; + inX = keyData.i.x; + inY = keyData.i.y; + fnc = BezierFactory.getBezierEasing(outX, outY, inX, inY).get; + keyData.keyframeMetadata = fnc; + } else { + fnc = keyframeMetadata.__fnct; + } + perc = fnc((frameNum - keyTime) / (nextKeyTime - keyTime)); + } + } + endValue = nextKeyData.s || keyData.e; + keyValue = keyData.h === 1 ? keyData.s[i] : keyData.s[i] + (endValue[i] - keyData.s[i]) * perc; + if (this.propType === "multidimensional") { + newValue[i] = keyValue; + } else { + newValue = keyValue; + } + } + } + } + caching.lastIndex = iterationIndex; + return newValue; + } + function slerp(a, b, t2) { + var out = []; + var ax = a[0]; + var ay = a[1]; + var az = a[2]; + var aw = a[3]; + var bx = b[0]; + var by = b[1]; + var bz = b[2]; + var bw = b[3]; + var omega; + var cosom; + var sinom; + var scale0; + var scale1; + cosom = ax * bx + ay * by + az * bz + aw * bw; + if (cosom < 0) { + cosom = -cosom; + bx = -bx; + by = -by; + bz = -bz; + bw = -bw; + } + if (1 - cosom > 0.000001) { + omega = Math.acos(cosom); + sinom = Math.sin(omega); + scale0 = Math.sin((1 - t2) * omega) / sinom; + scale1 = Math.sin(t2 * omega) / sinom; + } else { + scale0 = 1 - t2; + scale1 = t2; + } + out[0] = scale0 * ax + scale1 * bx; + out[1] = scale0 * ay + scale1 * by; + out[2] = scale0 * az + scale1 * bz; + out[3] = scale0 * aw + scale1 * bw; + return out; + } + function quaternionToEuler(out, quat) { + var qx = quat[0]; + var qy = quat[1]; + var qz = quat[2]; + var qw = quat[3]; + var heading = Math.atan2(2 * qy * qw - 2 * qx * qz, 1 - 2 * qy * qy - 2 * qz * qz); + var attitude = Math.asin(2 * qx * qy + 2 * qz * qw); + var bank = Math.atan2(2 * qx * qw - 2 * qy * qz, 1 - 2 * qx * qx - 2 * qz * qz); + out[0] = heading / degToRads; + out[1] = attitude / degToRads; + out[2] = bank / degToRads; + } + function createQuaternion(values2) { + var heading = values2[0] * degToRads; + var attitude = values2[1] * degToRads; + var bank = values2[2] * degToRads; + var c1 = Math.cos(heading / 2); + var c2 = Math.cos(attitude / 2); + var c3 = Math.cos(bank / 2); + var s1 = Math.sin(heading / 2); + var s2 = Math.sin(attitude / 2); + var s3 = Math.sin(bank / 2); + var w = c1 * c2 * c3 - s1 * s2 * s3; + var x2 = s1 * s2 * c3 + c1 * c2 * s3; + var y = s1 * c2 * c3 + c1 * s2 * s3; + var z = c1 * s2 * c3 - s1 * c2 * s3; + return [x2, y, z, w]; + } + function getValueAtCurrentTime() { + var frameNum = this.comp.renderedFrame - this.offsetTime; + var initTime = this.keyframes[0].t - this.offsetTime; + var endTime = this.keyframes[this.keyframes.length - 1].t - this.offsetTime; + if (!(frameNum === this._caching.lastFrame || this._caching.lastFrame !== initFrame && (this._caching.lastFrame >= endTime && frameNum >= endTime || this._caching.lastFrame < initTime && frameNum < initTime))) { + if (this._caching.lastFrame >= frameNum) { + this._caching._lastKeyframeIndex = -1; + this._caching.lastIndex = 0; + } + var renderResult = this.interpolateValue(frameNum, this._caching); + this.pv = renderResult; + } + this._caching.lastFrame = frameNum; + return this.pv; + } + function setVValue(val2) { + var multipliedValue; + if (this.propType === "unidimensional") { + multipliedValue = val2 * this.mult; + if (mathAbs(this.v - multipliedValue) > 0.00001) { + this.v = multipliedValue; + this._mdf = true; + } + } else { + var i = 0; + var len = this.v.length; + while (i < len) { + multipliedValue = val2[i] * this.mult; + if (mathAbs(this.v[i] - multipliedValue) > 0.00001) { + this.v[i] = multipliedValue; + this._mdf = true; + } + i += 1; + } + } + } + function processEffectsSequence() { + if (this.elem.globalData.frameId === this.frameId || !this.effectsSequence.length) { + return; + } + if (this.lock) { + this.setVValue(this.pv); + return; + } + this.lock = true; + this._mdf = this._isFirstFrame; + var i; + var len = this.effectsSequence.length; + var finalValue = this.kf ? this.pv : this.data.k; + for (i = 0;i < len; i += 1) { + finalValue = this.effectsSequence[i](finalValue); + } + this.setVValue(finalValue); + this._isFirstFrame = false; + this.lock = false; + this.frameId = this.elem.globalData.frameId; + } + function addEffect(effectFunction) { + this.effectsSequence.push(effectFunction); + this.container.addDynamicProperty(this); + } + function ValueProperty(elem2, data2, mult, container) { + this.propType = "unidimensional"; + this.mult = mult || 1; + this.data = data2; + this.v = mult ? data2.k * mult : data2.k; + this.pv = data2.k; + this._mdf = false; + this.elem = elem2; + this.container = container; + this.comp = elem2.comp; + this.k = false; + this.kf = false; + this.vel = 0; + this.effectsSequence = []; + this._isFirstFrame = true; + this.getValue = processEffectsSequence; + this.setVValue = setVValue; + this.addEffect = addEffect; + } + function MultiDimensionalProperty(elem2, data2, mult, container) { + this.propType = "multidimensional"; + this.mult = mult || 1; + this.data = data2; + this._mdf = false; + this.elem = elem2; + this.container = container; + this.comp = elem2.comp; + this.k = false; + this.kf = false; + this.frameId = -1; + var i; + var len = data2.k.length; + this.v = createTypedArray("float32", len); + this.pv = createTypedArray("float32", len); + this.vel = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + this.v[i] = data2.k[i] * this.mult; + this.pv[i] = data2.k[i]; + } + this._isFirstFrame = true; + this.effectsSequence = []; + this.getValue = processEffectsSequence; + this.setVValue = setVValue; + this.addEffect = addEffect; + } + function KeyframedValueProperty(elem2, data2, mult, container) { + this.propType = "unidimensional"; + this.keyframes = data2.k; + this.keyframesMetadata = []; + this.offsetTime = elem2.data.st; + this.frameId = -1; + this._caching = { + lastFrame: initFrame, + lastIndex: 0, + value: 0, + _lastKeyframeIndex: -1 + }; + this.k = true; + this.kf = true; + this.data = data2; + this.mult = mult || 1; + this.elem = elem2; + this.container = container; + this.comp = elem2.comp; + this.v = initFrame; + this.pv = initFrame; + this._isFirstFrame = true; + this.getValue = processEffectsSequence; + this.setVValue = setVValue; + this.interpolateValue = interpolateValue; + this.effectsSequence = [getValueAtCurrentTime.bind(this)]; + this.addEffect = addEffect; + } + function KeyframedMultidimensionalProperty(elem2, data2, mult, container) { + this.propType = "multidimensional"; + var i; + var len = data2.k.length; + var s; + var e; + var to; + var ti; + for (i = 0;i < len - 1; i += 1) { + if (data2.k[i].to && data2.k[i].s && data2.k[i + 1] && data2.k[i + 1].s) { + s = data2.k[i].s; + e = data2.k[i + 1].s; + to = data2.k[i].to; + ti = data2.k[i].ti; + if (s.length === 2 && !(s[0] === e[0] && s[1] === e[1]) && bez.pointOnLine2D(s[0], s[1], e[0], e[1], s[0] + to[0], s[1] + to[1]) && bez.pointOnLine2D(s[0], s[1], e[0], e[1], e[0] + ti[0], e[1] + ti[1]) || s.length === 3 && !(s[0] === e[0] && s[1] === e[1] && s[2] === e[2]) && bez.pointOnLine3D(s[0], s[1], s[2], e[0], e[1], e[2], s[0] + to[0], s[1] + to[1], s[2] + to[2]) && bez.pointOnLine3D(s[0], s[1], s[2], e[0], e[1], e[2], e[0] + ti[0], e[1] + ti[1], e[2] + ti[2])) { + data2.k[i].to = null; + data2.k[i].ti = null; + } + if (s[0] === e[0] && s[1] === e[1] && to[0] === 0 && to[1] === 0 && ti[0] === 0 && ti[1] === 0) { + if (s.length === 2 || s[2] === e[2] && to[2] === 0 && ti[2] === 0) { + data2.k[i].to = null; + data2.k[i].ti = null; + } + } + } + } + this.effectsSequence = [getValueAtCurrentTime.bind(this)]; + this.data = data2; + this.keyframes = data2.k; + this.keyframesMetadata = []; + this.offsetTime = elem2.data.st; + this.k = true; + this.kf = true; + this._isFirstFrame = true; + this.mult = mult || 1; + this.elem = elem2; + this.container = container; + this.comp = elem2.comp; + this.getValue = processEffectsSequence; + this.setVValue = setVValue; + this.interpolateValue = interpolateValue; + this.frameId = -1; + var arrLen = data2.k[0].s.length; + this.v = createTypedArray("float32", arrLen); + this.pv = createTypedArray("float32", arrLen); + for (i = 0;i < arrLen; i += 1) { + this.v[i] = initFrame; + this.pv[i] = initFrame; + } + this._caching = { lastFrame: initFrame, lastIndex: 0, value: createTypedArray("float32", arrLen) }; + this.addEffect = addEffect; + } + function getProp(elem2, data2, type, mult, container) { + var p; + if (!data2.k.length) { + p = new ValueProperty(elem2, data2, mult, container); + } else if (typeof data2.k[0] === "number") { + p = new MultiDimensionalProperty(elem2, data2, mult, container); + } else { + switch (type) { + case 0: + p = new KeyframedValueProperty(elem2, data2, mult, container); + break; + case 1: + p = new KeyframedMultidimensionalProperty(elem2, data2, mult, container); + break; + default: + break; + } + } + if (p.effectsSequence.length) { + container.addDynamicProperty(p); + } + return p; + } + var ob2 = { + getProp + }; + return ob2; + }(); + DynamicPropertyContainer.prototype = { + addDynamicProperty: function(prop) { + if (this.dynamicProperties.indexOf(prop) === -1) { + this.dynamicProperties.push(prop); + this.container.addDynamicProperty(this); + this._isAnimated = true; + } + }, + iterateDynamicProperties: function() { + this._mdf = false; + var i; + var len = this.dynamicProperties.length; + for (i = 0;i < len; i += 1) { + this.dynamicProperties[i].getValue(); + if (this.dynamicProperties[i]._mdf) { + this._mdf = true; + } + } + }, + initDynamicPropertyContainer: function(container) { + this.container = container; + this.dynamicProperties = []; + this._mdf = false; + this._isAnimated = false; + } + }; + const pointPool = function() { + function create() { + return createTypedArray("float32", 2); + } + return poolFactory(8, create); + }(); + ShapePath.prototype.setPathData = function(closed, len) { + this.c = closed; + this.setLength(len); + var i = 0; + while (i < len) { + this.v[i] = pointPool.newElement(); + this.o[i] = pointPool.newElement(); + this.i[i] = pointPool.newElement(); + i += 1; + } + }; + ShapePath.prototype.setLength = function(len) { + while (this._maxLength < len) { + this.doubleArrayLength(); + } + this._length = len; + }; + ShapePath.prototype.doubleArrayLength = function() { + this.v = this.v.concat(createSizedArray(this._maxLength)); + this.i = this.i.concat(createSizedArray(this._maxLength)); + this.o = this.o.concat(createSizedArray(this._maxLength)); + this._maxLength *= 2; + }; + ShapePath.prototype.setXYAt = function(x2, y, type, pos, replace) { + var arr; + this._length = Math.max(this._length, pos + 1); + if (this._length >= this._maxLength) { + this.doubleArrayLength(); + } + switch (type) { + case "v": + arr = this.v; + break; + case "i": + arr = this.i; + break; + case "o": + arr = this.o; + break; + default: + arr = []; + break; + } + if (!arr[pos] || arr[pos] && !replace) { + arr[pos] = pointPool.newElement(); + } + arr[pos][0] = x2; + arr[pos][1] = y; + }; + ShapePath.prototype.setTripleAt = function(vX, vY, oX, oY, iX, iY, pos, replace) { + this.setXYAt(vX, vY, "v", pos, replace); + this.setXYAt(oX, oY, "o", pos, replace); + this.setXYAt(iX, iY, "i", pos, replace); + }; + ShapePath.prototype.reverse = function() { + var newPath = new ShapePath; + newPath.setPathData(this.c, this._length); + var vertices = this.v; + var outPoints = this.o; + var inPoints = this.i; + var init = 0; + if (this.c) { + newPath.setTripleAt(vertices[0][0], vertices[0][1], inPoints[0][0], inPoints[0][1], outPoints[0][0], outPoints[0][1], 0, false); + init = 1; + } + var cnt = this._length - 1; + var len = this._length; + var i; + for (i = init;i < len; i += 1) { + newPath.setTripleAt(vertices[cnt][0], vertices[cnt][1], inPoints[cnt][0], inPoints[cnt][1], outPoints[cnt][0], outPoints[cnt][1], i, false); + cnt -= 1; + } + return newPath; + }; + const shapePool = function() { + function create() { + return new ShapePath; + } + function release(shapePath) { + var len = shapePath._length; + var i; + for (i = 0;i < len; i += 1) { + pointPool.release(shapePath.v[i]); + pointPool.release(shapePath.i[i]); + pointPool.release(shapePath.o[i]); + shapePath.v[i] = null; + shapePath.i[i] = null; + shapePath.o[i] = null; + } + shapePath._length = 0; + shapePath.c = false; + } + function clone(shape) { + var cloned = factory.newElement(); + var i; + var len = shape._length === undefined ? shape.v.length : shape._length; + cloned.setLength(len); + cloned.c = shape.c; + for (i = 0;i < len; i += 1) { + cloned.setTripleAt(shape.v[i][0], shape.v[i][1], shape.o[i][0], shape.o[i][1], shape.i[i][0], shape.i[i][1], i); + } + return cloned; + } + var factory = poolFactory(4, create, release); + factory.clone = clone; + return factory; + }(); + ShapeCollection.prototype.addShape = function(shapeData) { + if (this._length === this._maxLength) { + this.shapes = this.shapes.concat(createSizedArray(this._maxLength)); + this._maxLength *= 2; + } + this.shapes[this._length] = shapeData; + this._length += 1; + }; + ShapeCollection.prototype.releaseShapes = function() { + var i; + for (i = 0;i < this._length; i += 1) { + shapePool.release(this.shapes[i]); + } + this._length = 0; + }; + const shapeCollectionPool = function() { + var ob2 = { + newShapeCollection, + release + }; + var _length = 0; + var _maxLength = 4; + var pool = createSizedArray(_maxLength); + function newShapeCollection() { + var shapeCollection; + if (_length) { + _length -= 1; + shapeCollection = pool[_length]; + } else { + shapeCollection = new ShapeCollection; + } + return shapeCollection; + } + function release(shapeCollection) { + var i; + var len = shapeCollection._length; + for (i = 0;i < len; i += 1) { + shapePool.release(shapeCollection.shapes[i]); + } + shapeCollection._length = 0; + if (_length === _maxLength) { + pool = pooling.double(pool); + _maxLength *= 2; + } + pool[_length] = shapeCollection; + _length += 1; + } + return ob2; + }(); + const ShapePropertyFactory = function() { + var initFrame = -999999; + function interpolateShape(frameNum, previousValue, caching) { + var iterationIndex = caching.lastIndex; + var keyPropS; + var keyPropE; + var isHold; + var j2; + var k2; + var jLen; + var kLen; + var perc; + var vertexValue; + var kf = this.keyframes; + if (frameNum < kf[0].t - this.offsetTime) { + keyPropS = kf[0].s[0]; + isHold = true; + iterationIndex = 0; + } else if (frameNum >= kf[kf.length - 1].t - this.offsetTime) { + keyPropS = kf[kf.length - 1].s ? kf[kf.length - 1].s[0] : kf[kf.length - 2].e[0]; + isHold = true; + } else { + var i = iterationIndex; + var len = kf.length - 1; + var flag = true; + var keyData; + var nextKeyData; + var keyframeMetadata; + while (flag) { + keyData = kf[i]; + nextKeyData = kf[i + 1]; + if (nextKeyData.t - this.offsetTime > frameNum) { + break; + } + if (i < len - 1) { + i += 1; + } else { + flag = false; + } + } + keyframeMetadata = this.keyframesMetadata[i] || {}; + isHold = keyData.h === 1; + iterationIndex = i; + if (!isHold) { + if (frameNum >= nextKeyData.t - this.offsetTime) { + perc = 1; + } else if (frameNum < keyData.t - this.offsetTime) { + perc = 0; + } else { + var fnc; + if (keyframeMetadata.__fnct) { + fnc = keyframeMetadata.__fnct; + } else { + fnc = BezierFactory.getBezierEasing(keyData.o.x, keyData.o.y, keyData.i.x, keyData.i.y).get; + keyframeMetadata.__fnct = fnc; + } + perc = fnc((frameNum - (keyData.t - this.offsetTime)) / (nextKeyData.t - this.offsetTime - (keyData.t - this.offsetTime))); + } + keyPropE = nextKeyData.s ? nextKeyData.s[0] : keyData.e[0]; + } + keyPropS = keyData.s[0]; + } + jLen = previousValue._length; + kLen = keyPropS.i[0].length; + caching.lastIndex = iterationIndex; + for (j2 = 0;j2 < jLen; j2 += 1) { + for (k2 = 0;k2 < kLen; k2 += 1) { + vertexValue = isHold ? keyPropS.i[j2][k2] : keyPropS.i[j2][k2] + (keyPropE.i[j2][k2] - keyPropS.i[j2][k2]) * perc; + previousValue.i[j2][k2] = vertexValue; + vertexValue = isHold ? keyPropS.o[j2][k2] : keyPropS.o[j2][k2] + (keyPropE.o[j2][k2] - keyPropS.o[j2][k2]) * perc; + previousValue.o[j2][k2] = vertexValue; + vertexValue = isHold ? keyPropS.v[j2][k2] : keyPropS.v[j2][k2] + (keyPropE.v[j2][k2] - keyPropS.v[j2][k2]) * perc; + previousValue.v[j2][k2] = vertexValue; + } + } + } + function interpolateShapeCurrentTime() { + var frameNum = this.comp.renderedFrame - this.offsetTime; + var initTime = this.keyframes[0].t - this.offsetTime; + var endTime = this.keyframes[this.keyframes.length - 1].t - this.offsetTime; + var lastFrame = this._caching.lastFrame; + if (!(lastFrame !== initFrame && (lastFrame < initTime && frameNum < initTime || lastFrame > endTime && frameNum > endTime))) { + this._caching.lastIndex = lastFrame < frameNum ? this._caching.lastIndex : 0; + this.interpolateShape(frameNum, this.pv, this._caching); + } + this._caching.lastFrame = frameNum; + return this.pv; + } + function resetShape() { + this.paths = this.localShapeCollection; + } + function shapesEqual(shape1, shape2) { + if (shape1._length !== shape2._length || shape1.c !== shape2.c) { + return false; + } + var i; + var len = shape1._length; + for (i = 0;i < len; i += 1) { + if (shape1.v[i][0] !== shape2.v[i][0] || shape1.v[i][1] !== shape2.v[i][1] || shape1.o[i][0] !== shape2.o[i][0] || shape1.o[i][1] !== shape2.o[i][1] || shape1.i[i][0] !== shape2.i[i][0] || shape1.i[i][1] !== shape2.i[i][1]) { + return false; + } + } + return true; + } + function setVValue(newPath) { + if (!shapesEqual(this.v, newPath)) { + this.v = shapePool.clone(newPath); + this.localShapeCollection.releaseShapes(); + this.localShapeCollection.addShape(this.v); + this._mdf = true; + this.paths = this.localShapeCollection; + } + } + function processEffectsSequence() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + if (!this.effectsSequence.length) { + this._mdf = false; + return; + } + if (this.lock) { + this.setVValue(this.pv); + return; + } + this.lock = true; + this._mdf = false; + var finalValue; + if (this.kf) { + finalValue = this.pv; + } else if (this.data.ks) { + finalValue = this.data.ks.k; + } else { + finalValue = this.data.pt.k; + } + var i; + var len = this.effectsSequence.length; + for (i = 0;i < len; i += 1) { + finalValue = this.effectsSequence[i](finalValue); + } + this.setVValue(finalValue); + this.lock = false; + this.frameId = this.elem.globalData.frameId; + } + function ShapeProperty(elem2, data2, type) { + this.propType = "shape"; + this.comp = elem2.comp; + this.container = elem2; + this.elem = elem2; + this.data = data2; + this.k = false; + this.kf = false; + this._mdf = false; + var pathData = type === 3 ? data2.pt.k : data2.ks.k; + this.v = shapePool.clone(pathData); + this.pv = shapePool.clone(this.v); + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.paths = this.localShapeCollection; + this.paths.addShape(this.v); + this.reset = resetShape; + this.effectsSequence = []; + } + function addEffect(effectFunction) { + this.effectsSequence.push(effectFunction); + this.container.addDynamicProperty(this); + } + ShapeProperty.prototype.interpolateShape = interpolateShape; + ShapeProperty.prototype.getValue = processEffectsSequence; + ShapeProperty.prototype.setVValue = setVValue; + ShapeProperty.prototype.addEffect = addEffect; + function KeyframedShapeProperty(elem2, data2, type) { + this.propType = "shape"; + this.comp = elem2.comp; + this.elem = elem2; + this.container = elem2; + this.offsetTime = elem2.data.st; + this.keyframes = type === 3 ? data2.pt.k : data2.ks.k; + this.keyframesMetadata = []; + this.k = true; + this.kf = true; + var len = this.keyframes[0].s[0].i.length; + this.v = shapePool.newElement(); + this.v.setPathData(this.keyframes[0].s[0].c, len); + this.pv = shapePool.clone(this.v); + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.paths = this.localShapeCollection; + this.paths.addShape(this.v); + this.lastFrame = initFrame; + this.reset = resetShape; + this._caching = { lastFrame: initFrame, lastIndex: 0 }; + this.effectsSequence = [interpolateShapeCurrentTime.bind(this)]; + } + KeyframedShapeProperty.prototype.getValue = processEffectsSequence; + KeyframedShapeProperty.prototype.interpolateShape = interpolateShape; + KeyframedShapeProperty.prototype.setVValue = setVValue; + KeyframedShapeProperty.prototype.addEffect = addEffect; + var EllShapeProperty = function() { + var cPoint = roundCorner; + function EllShapePropertyFactory(elem2, data2) { + this.v = shapePool.newElement(); + this.v.setPathData(true, 4); + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.paths = this.localShapeCollection; + this.localShapeCollection.addShape(this.v); + this.d = data2.d; + this.elem = elem2; + this.comp = elem2.comp; + this.frameId = -1; + this.initDynamicPropertyContainer(elem2); + this.p = PropertyFactory.getProp(elem2, data2.p, 1, 0, this); + this.s = PropertyFactory.getProp(elem2, data2.s, 1, 0, this); + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.k = false; + this.convertEllToPath(); + } + } + EllShapePropertyFactory.prototype = { + reset: resetShape, + getValue: function() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + if (this._mdf) { + this.convertEllToPath(); + } + }, + convertEllToPath: function() { + var p0 = this.p.v[0]; + var p1 = this.p.v[1]; + var s0 = this.s.v[0] / 2; + var s1 = this.s.v[1] / 2; + var _cw = this.d !== 3; + var _v4 = this.v; + _v4.v[0][0] = p0; + _v4.v[0][1] = p1 - s1; + _v4.v[1][0] = _cw ? p0 + s0 : p0 - s0; + _v4.v[1][1] = p1; + _v4.v[2][0] = p0; + _v4.v[2][1] = p1 + s1; + _v4.v[3][0] = _cw ? p0 - s0 : p0 + s0; + _v4.v[3][1] = p1; + _v4.i[0][0] = _cw ? p0 - s0 * cPoint : p0 + s0 * cPoint; + _v4.i[0][1] = p1 - s1; + _v4.i[1][0] = _cw ? p0 + s0 : p0 - s0; + _v4.i[1][1] = p1 - s1 * cPoint; + _v4.i[2][0] = _cw ? p0 + s0 * cPoint : p0 - s0 * cPoint; + _v4.i[2][1] = p1 + s1; + _v4.i[3][0] = _cw ? p0 - s0 : p0 + s0; + _v4.i[3][1] = p1 + s1 * cPoint; + _v4.o[0][0] = _cw ? p0 + s0 * cPoint : p0 - s0 * cPoint; + _v4.o[0][1] = p1 - s1; + _v4.o[1][0] = _cw ? p0 + s0 : p0 - s0; + _v4.o[1][1] = p1 + s1 * cPoint; + _v4.o[2][0] = _cw ? p0 - s0 * cPoint : p0 + s0 * cPoint; + _v4.o[2][1] = p1 + s1; + _v4.o[3][0] = _cw ? p0 - s0 : p0 + s0; + _v4.o[3][1] = p1 - s1 * cPoint; + } + }; + extendPrototype([DynamicPropertyContainer], EllShapePropertyFactory); + return EllShapePropertyFactory; + }(); + var StarShapeProperty = function() { + function StarShapePropertyFactory(elem2, data2) { + this.v = shapePool.newElement(); + this.v.setPathData(true, 0); + this.elem = elem2; + this.comp = elem2.comp; + this.data = data2; + this.frameId = -1; + this.d = data2.d; + this.initDynamicPropertyContainer(elem2); + if (data2.sy === 1) { + this.ir = PropertyFactory.getProp(elem2, data2.ir, 0, 0, this); + this.is = PropertyFactory.getProp(elem2, data2.is, 0, 0.01, this); + this.convertToPath = this.convertStarToPath; + } else { + this.convertToPath = this.convertPolygonToPath; + } + this.pt = PropertyFactory.getProp(elem2, data2.pt, 0, 0, this); + this.p = PropertyFactory.getProp(elem2, data2.p, 1, 0, this); + this.r = PropertyFactory.getProp(elem2, data2.r, 0, degToRads, this); + this.or = PropertyFactory.getProp(elem2, data2.or, 0, 0, this); + this.os = PropertyFactory.getProp(elem2, data2.os, 0, 0.01, this); + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.localShapeCollection.addShape(this.v); + this.paths = this.localShapeCollection; + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.k = false; + this.convertToPath(); + } + } + StarShapePropertyFactory.prototype = { + reset: resetShape, + getValue: function() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + if (this._mdf) { + this.convertToPath(); + } + }, + convertStarToPath: function() { + var numPts = Math.floor(this.pt.v) * 2; + var angle = Math.PI * 2 / numPts; + var longFlag = true; + var longRad = this.or.v; + var shortRad = this.ir.v; + var longRound = this.os.v; + var shortRound = this.is.v; + var longPerimSegment = 2 * Math.PI * longRad / (numPts * 2); + var shortPerimSegment = 2 * Math.PI * shortRad / (numPts * 2); + var i; + var rad; + var roundness; + var perimSegment; + var currentAng = -Math.PI / 2; + currentAng += this.r.v; + var dir = this.data.d === 3 ? -1 : 1; + this.v._length = 0; + for (i = 0;i < numPts; i += 1) { + rad = longFlag ? longRad : shortRad; + roundness = longFlag ? longRound : shortRound; + perimSegment = longFlag ? longPerimSegment : shortPerimSegment; + var x2 = rad * Math.cos(currentAng); + var y = rad * Math.sin(currentAng); + var ox = x2 === 0 && y === 0 ? 0 : y / Math.sqrt(x2 * x2 + y * y); + var oy = x2 === 0 && y === 0 ? 0 : -x2 / Math.sqrt(x2 * x2 + y * y); + x2 += +this.p.v[0]; + y += +this.p.v[1]; + this.v.setTripleAt(x2, y, x2 - ox * perimSegment * roundness * dir, y - oy * perimSegment * roundness * dir, x2 + ox * perimSegment * roundness * dir, y + oy * perimSegment * roundness * dir, i, true); + longFlag = !longFlag; + currentAng += angle * dir; + } + }, + convertPolygonToPath: function() { + var numPts = Math.floor(this.pt.v); + var angle = Math.PI * 2 / numPts; + var rad = this.or.v; + var roundness = this.os.v; + var perimSegment = 2 * Math.PI * rad / (numPts * 4); + var i; + var currentAng = -Math.PI * 0.5; + var dir = this.data.d === 3 ? -1 : 1; + currentAng += this.r.v; + this.v._length = 0; + for (i = 0;i < numPts; i += 1) { + var x2 = rad * Math.cos(currentAng); + var y = rad * Math.sin(currentAng); + var ox = x2 === 0 && y === 0 ? 0 : y / Math.sqrt(x2 * x2 + y * y); + var oy = x2 === 0 && y === 0 ? 0 : -x2 / Math.sqrt(x2 * x2 + y * y); + x2 += +this.p.v[0]; + y += +this.p.v[1]; + this.v.setTripleAt(x2, y, x2 - ox * perimSegment * roundness * dir, y - oy * perimSegment * roundness * dir, x2 + ox * perimSegment * roundness * dir, y + oy * perimSegment * roundness * dir, i, true); + currentAng += angle * dir; + } + this.paths.length = 0; + this.paths[0] = this.v; + } + }; + extendPrototype([DynamicPropertyContainer], StarShapePropertyFactory); + return StarShapePropertyFactory; + }(); + var RectShapeProperty = function() { + function RectShapePropertyFactory(elem2, data2) { + this.v = shapePool.newElement(); + this.v.c = true; + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.localShapeCollection.addShape(this.v); + this.paths = this.localShapeCollection; + this.elem = elem2; + this.comp = elem2.comp; + this.frameId = -1; + this.d = data2.d; + this.initDynamicPropertyContainer(elem2); + this.p = PropertyFactory.getProp(elem2, data2.p, 1, 0, this); + this.s = PropertyFactory.getProp(elem2, data2.s, 1, 0, this); + this.r = PropertyFactory.getProp(elem2, data2.r, 0, 0, this); + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.k = false; + this.convertRectToPath(); + } + } + RectShapePropertyFactory.prototype = { + convertRectToPath: function() { + var p0 = this.p.v[0]; + var p1 = this.p.v[1]; + var v0 = this.s.v[0] / 2; + var v1 = this.s.v[1] / 2; + var round = bmMin(v0, v1, this.r.v); + var cPoint = round * (1 - roundCorner); + this.v._length = 0; + if (this.d === 2 || this.d === 1) { + this.v.setTripleAt(p0 + v0, p1 - v1 + round, p0 + v0, p1 - v1 + round, p0 + v0, p1 - v1 + cPoint, 0, true); + this.v.setTripleAt(p0 + v0, p1 + v1 - round, p0 + v0, p1 + v1 - cPoint, p0 + v0, p1 + v1 - round, 1, true); + if (round !== 0) { + this.v.setTripleAt(p0 + v0 - round, p1 + v1, p0 + v0 - round, p1 + v1, p0 + v0 - cPoint, p1 + v1, 2, true); + this.v.setTripleAt(p0 - v0 + round, p1 + v1, p0 - v0 + cPoint, p1 + v1, p0 - v0 + round, p1 + v1, 3, true); + this.v.setTripleAt(p0 - v0, p1 + v1 - round, p0 - v0, p1 + v1 - round, p0 - v0, p1 + v1 - cPoint, 4, true); + this.v.setTripleAt(p0 - v0, p1 - v1 + round, p0 - v0, p1 - v1 + cPoint, p0 - v0, p1 - v1 + round, 5, true); + this.v.setTripleAt(p0 - v0 + round, p1 - v1, p0 - v0 + round, p1 - v1, p0 - v0 + cPoint, p1 - v1, 6, true); + this.v.setTripleAt(p0 + v0 - round, p1 - v1, p0 + v0 - cPoint, p1 - v1, p0 + v0 - round, p1 - v1, 7, true); + } else { + this.v.setTripleAt(p0 - v0, p1 + v1, p0 - v0 + cPoint, p1 + v1, p0 - v0, p1 + v1, 2); + this.v.setTripleAt(p0 - v0, p1 - v1, p0 - v0, p1 - v1 + cPoint, p0 - v0, p1 - v1, 3); + } + } else { + this.v.setTripleAt(p0 + v0, p1 - v1 + round, p0 + v0, p1 - v1 + cPoint, p0 + v0, p1 - v1 + round, 0, true); + if (round !== 0) { + this.v.setTripleAt(p0 + v0 - round, p1 - v1, p0 + v0 - round, p1 - v1, p0 + v0 - cPoint, p1 - v1, 1, true); + this.v.setTripleAt(p0 - v0 + round, p1 - v1, p0 - v0 + cPoint, p1 - v1, p0 - v0 + round, p1 - v1, 2, true); + this.v.setTripleAt(p0 - v0, p1 - v1 + round, p0 - v0, p1 - v1 + round, p0 - v0, p1 - v1 + cPoint, 3, true); + this.v.setTripleAt(p0 - v0, p1 + v1 - round, p0 - v0, p1 + v1 - cPoint, p0 - v0, p1 + v1 - round, 4, true); + this.v.setTripleAt(p0 - v0 + round, p1 + v1, p0 - v0 + round, p1 + v1, p0 - v0 + cPoint, p1 + v1, 5, true); + this.v.setTripleAt(p0 + v0 - round, p1 + v1, p0 + v0 - cPoint, p1 + v1, p0 + v0 - round, p1 + v1, 6, true); + this.v.setTripleAt(p0 + v0, p1 + v1 - round, p0 + v0, p1 + v1 - round, p0 + v0, p1 + v1 - cPoint, 7, true); + } else { + this.v.setTripleAt(p0 - v0, p1 - v1, p0 - v0 + cPoint, p1 - v1, p0 - v0, p1 - v1, 1, true); + this.v.setTripleAt(p0 - v0, p1 + v1, p0 - v0, p1 + v1 - cPoint, p0 - v0, p1 + v1, 2, true); + this.v.setTripleAt(p0 + v0, p1 + v1, p0 + v0 - cPoint, p1 + v1, p0 + v0, p1 + v1, 3, true); + } + } + }, + getValue: function() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + if (this._mdf) { + this.convertRectToPath(); + } + }, + reset: resetShape + }; + extendPrototype([DynamicPropertyContainer], RectShapePropertyFactory); + return RectShapePropertyFactory; + }(); + function getShapeProp(elem2, data2, type) { + var prop; + if (type === 3 || type === 4) { + var dataProp = type === 3 ? data2.pt : data2.ks; + var keys2 = dataProp.k; + if (keys2.length) { + prop = new KeyframedShapeProperty(elem2, data2, type); + } else { + prop = new ShapeProperty(elem2, data2, type); + } + } else if (type === 5) { + prop = new RectShapeProperty(elem2, data2); + } else if (type === 6) { + prop = new EllShapeProperty(elem2, data2); + } else if (type === 7) { + prop = new StarShapeProperty(elem2, data2); + } + if (prop.k) { + elem2.addDynamicProperty(prop); + } + return prop; + } + function getConstructorFunction() { + return ShapeProperty; + } + function getKeyframedConstructorFunction() { + return KeyframedShapeProperty; + } + var ob2 = {}; + ob2.getShapeProp = getShapeProp; + ob2.getConstructorFunction = getConstructorFunction; + ob2.getKeyframedConstructorFunction = getKeyframedConstructorFunction; + return ob2; + }(); + /*! + Transformation Matrix v2.0 + (c) Epistemex 2014-2015 + www.epistemex.com + By Ken Fyrstenberg + Contributions by leeoniya. + License: MIT, header required. + */ + const Matrix = function() { + var _cos = Math.cos; + var _sin = Math.sin; + var _tan = Math.tan; + var _rnd = Math.round; + function reset() { + this.props[0] = 1; + this.props[1] = 0; + this.props[2] = 0; + this.props[3] = 0; + this.props[4] = 0; + this.props[5] = 1; + this.props[6] = 0; + this.props[7] = 0; + this.props[8] = 0; + this.props[9] = 0; + this.props[10] = 1; + this.props[11] = 0; + this.props[12] = 0; + this.props[13] = 0; + this.props[14] = 0; + this.props[15] = 1; + return this; + } + function rotate(angle) { + if (angle === 0) { + return this; + } + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + } + function rotateX(angle) { + if (angle === 0) { + return this; + } + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(1, 0, 0, 0, 0, mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1); + } + function rotateY(angle) { + if (angle === 0) { + return this; + } + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(mCos, 0, mSin, 0, 0, 1, 0, 0, -mSin, 0, mCos, 0, 0, 0, 0, 1); + } + function rotateZ(angle) { + if (angle === 0) { + return this; + } + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + } + function shear(sx, sy) { + return this._t(1, sy, sx, 1, 0, 0); + } + function skew(ax, ay) { + return this.shear(_tan(ax), _tan(ay)); + } + function skewFromAxis(ax, angle) { + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(mCos, mSin, 0, 0, -mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)._t(1, 0, 0, 0, _tan(ax), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + } + function scale2(sx, sy, sz) { + if (!sz && sz !== 0) { + sz = 1; + } + if (sx === 1 && sy === 1 && sz === 1) { + return this; + } + return this._t(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, 0, 0, 0, 1); + } + function setTransform(a, b, c, d, e, f, g3, h, i, j2, k2, l2, m, n2, o, p) { + this.props[0] = a; + this.props[1] = b; + this.props[2] = c; + this.props[3] = d; + this.props[4] = e; + this.props[5] = f; + this.props[6] = g3; + this.props[7] = h; + this.props[8] = i; + this.props[9] = j2; + this.props[10] = k2; + this.props[11] = l2; + this.props[12] = m; + this.props[13] = n2; + this.props[14] = o; + this.props[15] = p; + return this; + } + function translate(tx, ty, tz) { + tz = tz || 0; + if (tx !== 0 || ty !== 0 || tz !== 0) { + return this._t(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, tx, ty, tz, 1); + } + return this; + } + function transform2(a2, b2, c2, d2, e2, f2, g22, h2, i2, j2, k2, l2, m2, n2, o2, p2) { + var _p = this.props; + if (a2 === 1 && b2 === 0 && c2 === 0 && d2 === 0 && e2 === 0 && f2 === 1 && g22 === 0 && h2 === 0 && i2 === 0 && j2 === 0 && k2 === 1 && l2 === 0) { + _p[12] = _p[12] * a2 + _p[15] * m2; + _p[13] = _p[13] * f2 + _p[15] * n2; + _p[14] = _p[14] * k2 + _p[15] * o2; + _p[15] *= p2; + this._identityCalculated = false; + return this; + } + var a1 = _p[0]; + var b1 = _p[1]; + var c1 = _p[2]; + var d1 = _p[3]; + var e1 = _p[4]; + var f1 = _p[5]; + var g1 = _p[6]; + var h1 = _p[7]; + var i1 = _p[8]; + var j1 = _p[9]; + var k1 = _p[10]; + var l1 = _p[11]; + var m1 = _p[12]; + var n1 = _p[13]; + var o1 = _p[14]; + var p1 = _p[15]; + _p[0] = a1 * a2 + b1 * e2 + c1 * i2 + d1 * m2; + _p[1] = a1 * b2 + b1 * f2 + c1 * j2 + d1 * n2; + _p[2] = a1 * c2 + b1 * g22 + c1 * k2 + d1 * o2; + _p[3] = a1 * d2 + b1 * h2 + c1 * l2 + d1 * p2; + _p[4] = e1 * a2 + f1 * e2 + g1 * i2 + h1 * m2; + _p[5] = e1 * b2 + f1 * f2 + g1 * j2 + h1 * n2; + _p[6] = e1 * c2 + f1 * g22 + g1 * k2 + h1 * o2; + _p[7] = e1 * d2 + f1 * h2 + g1 * l2 + h1 * p2; + _p[8] = i1 * a2 + j1 * e2 + k1 * i2 + l1 * m2; + _p[9] = i1 * b2 + j1 * f2 + k1 * j2 + l1 * n2; + _p[10] = i1 * c2 + j1 * g22 + k1 * k2 + l1 * o2; + _p[11] = i1 * d2 + j1 * h2 + k1 * l2 + l1 * p2; + _p[12] = m1 * a2 + n1 * e2 + o1 * i2 + p1 * m2; + _p[13] = m1 * b2 + n1 * f2 + o1 * j2 + p1 * n2; + _p[14] = m1 * c2 + n1 * g22 + o1 * k2 + p1 * o2; + _p[15] = m1 * d2 + n1 * h2 + o1 * l2 + p1 * p2; + this._identityCalculated = false; + return this; + } + function isIdentity() { + if (!this._identityCalculated) { + this._identity = !(this.props[0] !== 1 || this.props[1] !== 0 || this.props[2] !== 0 || this.props[3] !== 0 || this.props[4] !== 0 || this.props[5] !== 1 || this.props[6] !== 0 || this.props[7] !== 0 || this.props[8] !== 0 || this.props[9] !== 0 || this.props[10] !== 1 || this.props[11] !== 0 || this.props[12] !== 0 || this.props[13] !== 0 || this.props[14] !== 0 || this.props[15] !== 1); + this._identityCalculated = true; + } + return this._identity; + } + function equals2(matr) { + var i = 0; + while (i < 16) { + if (matr.props[i] !== this.props[i]) { + return false; + } + i += 1; + } + return true; + } + function clone(matr) { + var i; + for (i = 0;i < 16; i += 1) { + matr.props[i] = this.props[i]; + } + return matr; + } + function cloneFromProps(props) { + var i; + for (i = 0;i < 16; i += 1) { + this.props[i] = props[i]; + } + } + function applyToPoint(x2, y, z) { + return { + x: x2 * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12], + y: x2 * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13], + z: x2 * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14] + }; + } + function applyToX(x2, y, z) { + return x2 * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12]; + } + function applyToY(x2, y, z) { + return x2 * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13]; + } + function applyToZ(x2, y, z) { + return x2 * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14]; + } + function getInverseMatrix() { + var determinant = this.props[0] * this.props[5] - this.props[1] * this.props[4]; + var a = this.props[5] / determinant; + var b = -this.props[1] / determinant; + var c = -this.props[4] / determinant; + var d = this.props[0] / determinant; + var e = (this.props[4] * this.props[13] - this.props[5] * this.props[12]) / determinant; + var f = -(this.props[0] * this.props[13] - this.props[1] * this.props[12]) / determinant; + var inverseMatrix = new Matrix; + inverseMatrix.props[0] = a; + inverseMatrix.props[1] = b; + inverseMatrix.props[4] = c; + inverseMatrix.props[5] = d; + inverseMatrix.props[12] = e; + inverseMatrix.props[13] = f; + return inverseMatrix; + } + function inversePoint(pt) { + var inverseMatrix = this.getInverseMatrix(); + return inverseMatrix.applyToPointArray(pt[0], pt[1], pt[2] || 0); + } + function inversePoints(pts) { + var i; + var len = pts.length; + var retPts = []; + for (i = 0;i < len; i += 1) { + retPts[i] = inversePoint(pts[i]); + } + return retPts; + } + function applyToTriplePoints(pt1, pt2, pt3) { + var arr = createTypedArray("float32", 6); + if (this.isIdentity()) { + arr[0] = pt1[0]; + arr[1] = pt1[1]; + arr[2] = pt2[0]; + arr[3] = pt2[1]; + arr[4] = pt3[0]; + arr[5] = pt3[1]; + } else { + var p0 = this.props[0]; + var p1 = this.props[1]; + var p4 = this.props[4]; + var p5 = this.props[5]; + var p12 = this.props[12]; + var p13 = this.props[13]; + arr[0] = pt1[0] * p0 + pt1[1] * p4 + p12; + arr[1] = pt1[0] * p1 + pt1[1] * p5 + p13; + arr[2] = pt2[0] * p0 + pt2[1] * p4 + p12; + arr[3] = pt2[0] * p1 + pt2[1] * p5 + p13; + arr[4] = pt3[0] * p0 + pt3[1] * p4 + p12; + arr[5] = pt3[0] * p1 + pt3[1] * p5 + p13; + } + return arr; + } + function applyToPointArray(x2, y, z) { + var arr; + if (this.isIdentity()) { + arr = [x2, y, z]; + } else { + arr = [ + x2 * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12], + x2 * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13], + x2 * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14] + ]; + } + return arr; + } + function applyToPointStringified(x2, y) { + if (this.isIdentity()) { + return x2 + "," + y; + } + var _p = this.props; + return Math.round((x2 * _p[0] + y * _p[4] + _p[12]) * 100) / 100 + "," + Math.round((x2 * _p[1] + y * _p[5] + _p[13]) * 100) / 100; + } + function toCSS() { + var i = 0; + var props = this.props; + var cssValue = "matrix3d("; + var v = 1e4; + while (i < 16) { + cssValue += _rnd(props[i] * v) / v; + cssValue += i === 15 ? ")" : ","; + i += 1; + } + return cssValue; + } + function roundMatrixProperty(val2) { + var v = 1e4; + if (val2 < 0.000001 && val2 > 0 || val2 > -0.000001 && val2 < 0) { + return _rnd(val2 * v) / v; + } + return val2; + } + function to2dCSS() { + var props = this.props; + var _a2 = roundMatrixProperty(props[0]); + var _b2 = roundMatrixProperty(props[1]); + var _c = roundMatrixProperty(props[4]); + var _d = roundMatrixProperty(props[5]); + var _e = roundMatrixProperty(props[12]); + var _f = roundMatrixProperty(props[13]); + return "matrix(" + _a2 + "," + _b2 + "," + _c + "," + _d + "," + _e + "," + _f + ")"; + } + return function() { + this.reset = reset; + this.rotate = rotate; + this.rotateX = rotateX; + this.rotateY = rotateY; + this.rotateZ = rotateZ; + this.skew = skew; + this.skewFromAxis = skewFromAxis; + this.shear = shear; + this.scale = scale2; + this.setTransform = setTransform; + this.translate = translate; + this.transform = transform2; + this.applyToPoint = applyToPoint; + this.applyToX = applyToX; + this.applyToY = applyToY; + this.applyToZ = applyToZ; + this.applyToPointArray = applyToPointArray; + this.applyToTriplePoints = applyToTriplePoints; + this.applyToPointStringified = applyToPointStringified; + this.toCSS = toCSS; + this.to2dCSS = to2dCSS; + this.clone = clone; + this.cloneFromProps = cloneFromProps; + this.equals = equals2; + this.inversePoints = inversePoints; + this.inversePoint = inversePoint; + this.getInverseMatrix = getInverseMatrix; + this._t = this.transform; + this.isIdentity = isIdentity; + this._identity = true; + this._identityCalculated = false; + this.props = createTypedArray("float32", 16); + this.reset(); + }; + }(); + standalone = "__[STANDALONE]__"; + animationData = "__[ANIMATIONDATA]__"; + renderer = ""; + lottie.play = animationManager.play; + lottie.pause = animationManager.pause; + lottie.setLocationHref = setLocation; + lottie.togglePause = animationManager.togglePause; + lottie.setSpeed = animationManager.setSpeed; + lottie.setDirection = animationManager.setDirection; + lottie.stop = animationManager.stop; + lottie.searchAnimations = searchAnimations; + lottie.registerAnimation = animationManager.registerAnimation; + lottie.loadAnimation = loadAnimation; + lottie.setSubframeRendering = setSubframeRendering; + lottie.resize = animationManager.resize; + lottie.goToAndStop = animationManager.goToAndStop; + lottie.destroy = animationManager.destroy; + lottie.setQuality = setQuality; + lottie.inBrowser = inBrowser; + lottie.installPlugin = installPlugin; + lottie.freeze = animationManager.freeze; + lottie.unfreeze = animationManager.unfreeze; + lottie.setVolume = animationManager.setVolume; + lottie.mute = animationManager.mute; + lottie.unmute = animationManager.unmute; + lottie.getRegisteredAnimations = animationManager.getRegisteredAnimations; + lottie.useWebWorker = setWebWorker; + lottie.setIDPrefix = setPrefix; + lottie.__getFactory = getFactory; + lottie.version = "[[BM_VERSION]]"; + queryString = ""; + if (standalone) { + scripts = document.getElementsByTagName("script"); + index2 = scripts.length - 1; + myScript = scripts[index2] || { + src: "" + }; + queryString = myScript.src ? myScript.src.replace(/^[^\?]+\??/, "") : ""; + renderer = getQueryVariable("renderer"); + } + readyStateCheckInterval = setInterval(checkReady, 100); + try { + if (!(typeof exports_lottie_canvas_module === "object" && typeof module_lottie_canvas_module !== "undefined") && !(typeof define === "function" && define.amd)) { + window.bodymovin = lottie; + } + } catch (err) { + } + const ShapeModifiers = function() { + var ob2 = {}; + var modifiers = {}; + ob2.registerModifier = registerModifier; + ob2.getModifier = getModifier; + function registerModifier(nm, factory) { + if (!modifiers[nm]) { + modifiers[nm] = factory; + } + } + function getModifier(nm, elem2, data2) { + return new modifiers[nm](elem2, data2); + } + return ob2; + }(); + ShapeModifier.prototype.initModifierProperties = function() { + }; + ShapeModifier.prototype.addShapeToModifier = function() { + }; + ShapeModifier.prototype.addShape = function(data2) { + if (!this.closed) { + data2.sh.container.addDynamicProperty(data2.sh); + var shapeData = { shape: data2.sh, data: data2, localShapeCollection: shapeCollectionPool.newShapeCollection() }; + this.shapes.push(shapeData); + this.addShapeToModifier(shapeData); + if (this._isAnimated) { + data2.setAsAnimated(); + } + } + }; + ShapeModifier.prototype.init = function(elem2, data2) { + this.shapes = []; + this.elem = elem2; + this.initDynamicPropertyContainer(elem2); + this.initModifierProperties(elem2, data2); + this.frameId = initialDefaultFrame; + this.closed = false; + this.k = false; + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.getValue(true); + } + }; + ShapeModifier.prototype.processKeys = function() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + }; + extendPrototype([DynamicPropertyContainer], ShapeModifier); + extendPrototype([ShapeModifier], TrimModifier); + TrimModifier.prototype.initModifierProperties = function(elem2, data2) { + this.s = PropertyFactory.getProp(elem2, data2.s, 0, 0.01, this); + this.e = PropertyFactory.getProp(elem2, data2.e, 0, 0.01, this); + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0, this); + this.sValue = 0; + this.eValue = 0; + this.getValue = this.processKeys; + this.m = data2.m; + this._isAnimated = !!this.s.effectsSequence.length || !!this.e.effectsSequence.length || !!this.o.effectsSequence.length; + }; + TrimModifier.prototype.addShapeToModifier = function(shapeData) { + shapeData.pathsData = []; + }; + TrimModifier.prototype.calculateShapeEdges = function(s, e, shapeLength, addedLength, totalModifierLength) { + var segments = []; + if (e <= 1) { + segments.push({ + s, + e + }); + } else if (s >= 1) { + segments.push({ + s: s - 1, + e: e - 1 + }); + } else { + segments.push({ + s, + e: 1 + }); + segments.push({ + s: 0, + e: e - 1 + }); + } + var shapeSegments = []; + var i; + var len = segments.length; + var segmentOb; + for (i = 0;i < len; i += 1) { + segmentOb = segments[i]; + if (!(segmentOb.e * totalModifierLength < addedLength || segmentOb.s * totalModifierLength > addedLength + shapeLength)) { + var shapeS; + var shapeE; + if (segmentOb.s * totalModifierLength <= addedLength) { + shapeS = 0; + } else { + shapeS = (segmentOb.s * totalModifierLength - addedLength) / shapeLength; + } + if (segmentOb.e * totalModifierLength >= addedLength + shapeLength) { + shapeE = 1; + } else { + shapeE = (segmentOb.e * totalModifierLength - addedLength) / shapeLength; + } + shapeSegments.push([shapeS, shapeE]); + } + } + if (!shapeSegments.length) { + shapeSegments.push([0, 0]); + } + return shapeSegments; + }; + TrimModifier.prototype.releasePathsData = function(pathsData) { + var i; + var len = pathsData.length; + for (i = 0;i < len; i += 1) { + segmentsLengthPool.release(pathsData[i]); + } + pathsData.length = 0; + return pathsData; + }; + TrimModifier.prototype.processShapes = function(_isFirstFrame) { + var s; + var e; + if (this._mdf || _isFirstFrame) { + var o = this.o.v % 360 / 360; + if (o < 0) { + o += 1; + } + if (this.s.v > 1) { + s = 1 + o; + } else if (this.s.v < 0) { + s = 0 + o; + } else { + s = this.s.v + o; + } + if (this.e.v > 1) { + e = 1 + o; + } else if (this.e.v < 0) { + e = 0 + o; + } else { + e = this.e.v + o; + } + if (s > e) { + var _s = s; + s = e; + e = _s; + } + s = Math.round(s * 1e4) * 0.0001; + e = Math.round(e * 1e4) * 0.0001; + this.sValue = s; + this.eValue = e; + } else { + s = this.sValue; + e = this.eValue; + } + var shapePaths; + var i; + var len = this.shapes.length; + var j2; + var jLen; + var pathsData; + var pathData; + var totalShapeLength; + var totalModifierLength = 0; + if (e === s) { + for (i = 0;i < len; i += 1) { + this.shapes[i].localShapeCollection.releaseShapes(); + this.shapes[i].shape._mdf = true; + this.shapes[i].shape.paths = this.shapes[i].localShapeCollection; + if (this._mdf) { + this.shapes[i].pathsData.length = 0; + } + } + } else if (!(e === 1 && s === 0 || e === 0 && s === 1)) { + var segments = []; + var shapeData; + var localShapeCollection; + for (i = 0;i < len; i += 1) { + shapeData = this.shapes[i]; + if (!shapeData.shape._mdf && !this._mdf && !_isFirstFrame && this.m !== 2) { + shapeData.shape.paths = shapeData.localShapeCollection; + } else { + shapePaths = shapeData.shape.paths; + jLen = shapePaths._length; + totalShapeLength = 0; + if (!shapeData.shape._mdf && shapeData.pathsData.length) { + totalShapeLength = shapeData.totalShapeLength; + } else { + pathsData = this.releasePathsData(shapeData.pathsData); + for (j2 = 0;j2 < jLen; j2 += 1) { + pathData = bez.getSegmentsLength(shapePaths.shapes[j2]); + pathsData.push(pathData); + totalShapeLength += pathData.totalLength; + } + shapeData.totalShapeLength = totalShapeLength; + shapeData.pathsData = pathsData; + } + totalModifierLength += totalShapeLength; + shapeData.shape._mdf = true; + } + } + var shapeS = s; + var shapeE = e; + var addedLength = 0; + var edges; + for (i = len - 1;i >= 0; i -= 1) { + shapeData = this.shapes[i]; + if (shapeData.shape._mdf) { + localShapeCollection = shapeData.localShapeCollection; + localShapeCollection.releaseShapes(); + if (this.m === 2 && len > 1) { + edges = this.calculateShapeEdges(s, e, shapeData.totalShapeLength, addedLength, totalModifierLength); + addedLength += shapeData.totalShapeLength; + } else { + edges = [[shapeS, shapeE]]; + } + jLen = edges.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + shapeS = edges[j2][0]; + shapeE = edges[j2][1]; + segments.length = 0; + if (shapeE <= 1) { + segments.push({ + s: shapeData.totalShapeLength * shapeS, + e: shapeData.totalShapeLength * shapeE + }); + } else if (shapeS >= 1) { + segments.push({ + s: shapeData.totalShapeLength * (shapeS - 1), + e: shapeData.totalShapeLength * (shapeE - 1) + }); + } else { + segments.push({ + s: shapeData.totalShapeLength * shapeS, + e: shapeData.totalShapeLength + }); + segments.push({ + s: 0, + e: shapeData.totalShapeLength * (shapeE - 1) + }); + } + var newShapesData = this.addShapes(shapeData, segments[0]); + if (segments[0].s !== segments[0].e) { + if (segments.length > 1) { + var lastShapeInCollection = shapeData.shape.paths.shapes[shapeData.shape.paths._length - 1]; + if (lastShapeInCollection.c) { + var lastShape = newShapesData.pop(); + this.addPaths(newShapesData, localShapeCollection); + newShapesData = this.addShapes(shapeData, segments[1], lastShape); + } else { + this.addPaths(newShapesData, localShapeCollection); + newShapesData = this.addShapes(shapeData, segments[1]); + } + } + this.addPaths(newShapesData, localShapeCollection); + } + } + shapeData.shape.paths = localShapeCollection; + } + } + } else if (this._mdf) { + for (i = 0;i < len; i += 1) { + this.shapes[i].pathsData.length = 0; + this.shapes[i].shape._mdf = true; + } + } + }; + TrimModifier.prototype.addPaths = function(newPaths, localShapeCollection) { + var i; + var len = newPaths.length; + for (i = 0;i < len; i += 1) { + localShapeCollection.addShape(newPaths[i]); + } + }; + TrimModifier.prototype.addSegment = function(pt1, pt2, pt3, pt4, shapePath, pos, newShape) { + shapePath.setXYAt(pt2[0], pt2[1], "o", pos); + shapePath.setXYAt(pt3[0], pt3[1], "i", pos + 1); + if (newShape) { + shapePath.setXYAt(pt1[0], pt1[1], "v", pos); + } + shapePath.setXYAt(pt4[0], pt4[1], "v", pos + 1); + }; + TrimModifier.prototype.addSegmentFromArray = function(points, shapePath, pos, newShape) { + shapePath.setXYAt(points[1], points[5], "o", pos); + shapePath.setXYAt(points[2], points[6], "i", pos + 1); + if (newShape) { + shapePath.setXYAt(points[0], points[4], "v", pos); + } + shapePath.setXYAt(points[3], points[7], "v", pos + 1); + }; + TrimModifier.prototype.addShapes = function(shapeData, shapeSegment, shapePath) { + var pathsData = shapeData.pathsData; + var shapePaths = shapeData.shape.paths.shapes; + var i; + var len = shapeData.shape.paths._length; + var j2; + var jLen; + var addedLength = 0; + var currentLengthData; + var segmentCount; + var lengths; + var segment; + var shapes = []; + var initPos; + var newShape = true; + if (!shapePath) { + shapePath = shapePool.newElement(); + segmentCount = 0; + initPos = 0; + } else { + segmentCount = shapePath._length; + initPos = shapePath._length; + } + shapes.push(shapePath); + for (i = 0;i < len; i += 1) { + lengths = pathsData[i].lengths; + shapePath.c = shapePaths[i].c; + jLen = shapePaths[i].c ? lengths.length : lengths.length + 1; + for (j2 = 1;j2 < jLen; j2 += 1) { + currentLengthData = lengths[j2 - 1]; + if (addedLength + currentLengthData.addedLength < shapeSegment.s) { + addedLength += currentLengthData.addedLength; + shapePath.c = false; + } else if (addedLength > shapeSegment.e) { + shapePath.c = false; + break; + } else { + if (shapeSegment.s <= addedLength && shapeSegment.e >= addedLength + currentLengthData.addedLength) { + this.addSegment(shapePaths[i].v[j2 - 1], shapePaths[i].o[j2 - 1], shapePaths[i].i[j2], shapePaths[i].v[j2], shapePath, segmentCount, newShape); + newShape = false; + } else { + segment = bez.getNewSegment(shapePaths[i].v[j2 - 1], shapePaths[i].v[j2], shapePaths[i].o[j2 - 1], shapePaths[i].i[j2], (shapeSegment.s - addedLength) / currentLengthData.addedLength, (shapeSegment.e - addedLength) / currentLengthData.addedLength, lengths[j2 - 1]); + this.addSegmentFromArray(segment, shapePath, segmentCount, newShape); + newShape = false; + shapePath.c = false; + } + addedLength += currentLengthData.addedLength; + segmentCount += 1; + } + } + if (shapePaths[i].c && lengths.length) { + currentLengthData = lengths[j2 - 1]; + if (addedLength <= shapeSegment.e) { + var segmentLength = lengths[j2 - 1].addedLength; + if (shapeSegment.s <= addedLength && shapeSegment.e >= addedLength + segmentLength) { + this.addSegment(shapePaths[i].v[j2 - 1], shapePaths[i].o[j2 - 1], shapePaths[i].i[0], shapePaths[i].v[0], shapePath, segmentCount, newShape); + newShape = false; + } else { + segment = bez.getNewSegment(shapePaths[i].v[j2 - 1], shapePaths[i].v[0], shapePaths[i].o[j2 - 1], shapePaths[i].i[0], (shapeSegment.s - addedLength) / segmentLength, (shapeSegment.e - addedLength) / segmentLength, lengths[j2 - 1]); + this.addSegmentFromArray(segment, shapePath, segmentCount, newShape); + newShape = false; + shapePath.c = false; + } + } else { + shapePath.c = false; + } + addedLength += currentLengthData.addedLength; + segmentCount += 1; + } + if (shapePath._length) { + shapePath.setXYAt(shapePath.v[initPos][0], shapePath.v[initPos][1], "i", initPos); + shapePath.setXYAt(shapePath.v[shapePath._length - 1][0], shapePath.v[shapePath._length - 1][1], "o", shapePath._length - 1); + } + if (addedLength > shapeSegment.e) { + break; + } + if (i < len - 1) { + shapePath = shapePool.newElement(); + newShape = true; + shapes.push(shapePath); + segmentCount = 0; + } + } + return shapes; + }; + extendPrototype([ShapeModifier], PuckerAndBloatModifier); + PuckerAndBloatModifier.prototype.initModifierProperties = function(elem2, data2) { + this.getValue = this.processKeys; + this.amount = PropertyFactory.getProp(elem2, data2.a, 0, null, this); + this._isAnimated = !!this.amount.effectsSequence.length; + }; + PuckerAndBloatModifier.prototype.processPath = function(path, amount) { + var percent = amount / 100; + var centerPoint = [0, 0]; + var pathLength = path._length; + var i = 0; + for (i = 0;i < pathLength; i += 1) { + centerPoint[0] += path.v[i][0]; + centerPoint[1] += path.v[i][1]; + } + centerPoint[0] /= pathLength; + centerPoint[1] /= pathLength; + var clonedPath = shapePool.newElement(); + clonedPath.c = path.c; + var vX; + var vY; + var oX; + var oY; + var iX; + var iY; + for (i = 0;i < pathLength; i += 1) { + vX = path.v[i][0] + (centerPoint[0] - path.v[i][0]) * percent; + vY = path.v[i][1] + (centerPoint[1] - path.v[i][1]) * percent; + oX = path.o[i][0] + (centerPoint[0] - path.o[i][0]) * -percent; + oY = path.o[i][1] + (centerPoint[1] - path.o[i][1]) * -percent; + iX = path.i[i][0] + (centerPoint[0] - path.i[i][0]) * -percent; + iY = path.i[i][1] + (centerPoint[1] - path.i[i][1]) * -percent; + clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, i); + } + return clonedPath; + }; + PuckerAndBloatModifier.prototype.processShapes = function(_isFirstFrame) { + var shapePaths; + var i; + var len = this.shapes.length; + var j2; + var jLen; + var amount = this.amount.v; + if (amount !== 0) { + var shapeData; + var localShapeCollection; + for (i = 0;i < len; i += 1) { + shapeData = this.shapes[i]; + localShapeCollection = shapeData.localShapeCollection; + if (!(!shapeData.shape._mdf && !this._mdf && !_isFirstFrame)) { + localShapeCollection.releaseShapes(); + shapeData.shape._mdf = true; + shapePaths = shapeData.shape.paths.shapes; + jLen = shapeData.shape.paths._length; + for (j2 = 0;j2 < jLen; j2 += 1) { + localShapeCollection.addShape(this.processPath(shapePaths[j2], amount)); + } + } + shapeData.shape.paths = shapeData.localShapeCollection; + } + } + if (!this.dynamicProperties.length) { + this._mdf = false; + } + }; + const TransformPropertyFactory = function() { + var defaultVector = [0, 0]; + function applyToMatrix(mat) { + var _mdf = this._mdf; + this.iterateDynamicProperties(); + this._mdf = this._mdf || _mdf; + if (this.a) { + mat.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]); + } + if (this.s) { + mat.scale(this.s.v[0], this.s.v[1], this.s.v[2]); + } + if (this.sk) { + mat.skewFromAxis(-this.sk.v, this.sa.v); + } + if (this.r) { + mat.rotate(-this.r.v); + } else { + mat.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]); + } + if (this.data.p.s) { + if (this.data.p.z) { + mat.translate(this.px.v, this.py.v, -this.pz.v); + } else { + mat.translate(this.px.v, this.py.v, 0); + } + } else { + mat.translate(this.p.v[0], this.p.v[1], -this.p.v[2]); + } + } + function processKeys(forceRender) { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + if (this._isDirty) { + this.precalculateMatrix(); + this._isDirty = false; + } + this.iterateDynamicProperties(); + if (this._mdf || forceRender) { + var frameRate; + this.v.cloneFromProps(this.pre.props); + if (this.appliedTransformations < 1) { + this.v.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]); + } + if (this.appliedTransformations < 2) { + this.v.scale(this.s.v[0], this.s.v[1], this.s.v[2]); + } + if (this.sk && this.appliedTransformations < 3) { + this.v.skewFromAxis(-this.sk.v, this.sa.v); + } + if (this.r && this.appliedTransformations < 4) { + this.v.rotate(-this.r.v); + } else if (!this.r && this.appliedTransformations < 4) { + this.v.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]); + } + if (this.autoOriented) { + var v1; + var v2; + frameRate = this.elem.globalData.frameRate; + if (this.p && this.p.keyframes && this.p.getValueAtTime) { + if (this.p._caching.lastFrame + this.p.offsetTime <= this.p.keyframes[0].t) { + v1 = this.p.getValueAtTime((this.p.keyframes[0].t + 0.01) / frameRate, 0); + v2 = this.p.getValueAtTime(this.p.keyframes[0].t / frameRate, 0); + } else if (this.p._caching.lastFrame + this.p.offsetTime >= this.p.keyframes[this.p.keyframes.length - 1].t) { + v1 = this.p.getValueAtTime(this.p.keyframes[this.p.keyframes.length - 1].t / frameRate, 0); + v2 = this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length - 1].t - 0.05) / frameRate, 0); + } else { + v1 = this.p.pv; + v2 = this.p.getValueAtTime((this.p._caching.lastFrame + this.p.offsetTime - 0.01) / frameRate, this.p.offsetTime); + } + } else if (this.px && this.px.keyframes && this.py.keyframes && this.px.getValueAtTime && this.py.getValueAtTime) { + v1 = []; + v2 = []; + var px2 = this.px; + var py2 = this.py; + if (px2._caching.lastFrame + px2.offsetTime <= px2.keyframes[0].t) { + v1[0] = px2.getValueAtTime((px2.keyframes[0].t + 0.01) / frameRate, 0); + v1[1] = py2.getValueAtTime((py2.keyframes[0].t + 0.01) / frameRate, 0); + v2[0] = px2.getValueAtTime(px2.keyframes[0].t / frameRate, 0); + v2[1] = py2.getValueAtTime(py2.keyframes[0].t / frameRate, 0); + } else if (px2._caching.lastFrame + px2.offsetTime >= px2.keyframes[px2.keyframes.length - 1].t) { + v1[0] = px2.getValueAtTime(px2.keyframes[px2.keyframes.length - 1].t / frameRate, 0); + v1[1] = py2.getValueAtTime(py2.keyframes[py2.keyframes.length - 1].t / frameRate, 0); + v2[0] = px2.getValueAtTime((px2.keyframes[px2.keyframes.length - 1].t - 0.01) / frameRate, 0); + v2[1] = py2.getValueAtTime((py2.keyframes[py2.keyframes.length - 1].t - 0.01) / frameRate, 0); + } else { + v1 = [px2.pv, py2.pv]; + v2[0] = px2.getValueAtTime((px2._caching.lastFrame + px2.offsetTime - 0.01) / frameRate, px2.offsetTime); + v2[1] = py2.getValueAtTime((py2._caching.lastFrame + py2.offsetTime - 0.01) / frameRate, py2.offsetTime); + } + } else { + v2 = defaultVector; + v1 = v2; + } + this.v.rotate(-Math.atan2(v1[1] - v2[1], v1[0] - v2[0])); + } + if (this.data.p && this.data.p.s) { + if (this.data.p.z) { + this.v.translate(this.px.v, this.py.v, -this.pz.v); + } else { + this.v.translate(this.px.v, this.py.v, 0); + } + } else { + this.v.translate(this.p.v[0], this.p.v[1], -this.p.v[2]); + } + } + this.frameId = this.elem.globalData.frameId; + } + function precalculateMatrix() { + if (!this.a.k) { + this.pre.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]); + this.appliedTransformations = 1; + } else { + return; + } + if (!this.s.effectsSequence.length) { + this.pre.scale(this.s.v[0], this.s.v[1], this.s.v[2]); + this.appliedTransformations = 2; + } else { + return; + } + if (this.sk) { + if (!this.sk.effectsSequence.length && !this.sa.effectsSequence.length) { + this.pre.skewFromAxis(-this.sk.v, this.sa.v); + this.appliedTransformations = 3; + } else { + return; + } + } + if (this.r) { + if (!this.r.effectsSequence.length) { + this.pre.rotate(-this.r.v); + this.appliedTransformations = 4; + } + } else if (!this.rz.effectsSequence.length && !this.ry.effectsSequence.length && !this.rx.effectsSequence.length && !this.or.effectsSequence.length) { + this.pre.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]); + this.appliedTransformations = 4; + } + } + function autoOrient() { + } + function addDynamicProperty(prop) { + this._addDynamicProperty(prop); + this.elem.addDynamicProperty(prop); + this._isDirty = true; + } + function TransformProperty(elem2, data2, container) { + this.elem = elem2; + this.frameId = -1; + this.propType = "transform"; + this.data = data2; + this.v = new Matrix; + this.pre = new Matrix; + this.appliedTransformations = 0; + this.initDynamicPropertyContainer(container || elem2); + if (data2.p && data2.p.s) { + this.px = PropertyFactory.getProp(elem2, data2.p.x, 0, 0, this); + this.py = PropertyFactory.getProp(elem2, data2.p.y, 0, 0, this); + if (data2.p.z) { + this.pz = PropertyFactory.getProp(elem2, data2.p.z, 0, 0, this); + } + } else { + this.p = PropertyFactory.getProp(elem2, data2.p || { k: [0, 0, 0] }, 1, 0, this); + } + if (data2.rx) { + this.rx = PropertyFactory.getProp(elem2, data2.rx, 0, degToRads, this); + this.ry = PropertyFactory.getProp(elem2, data2.ry, 0, degToRads, this); + this.rz = PropertyFactory.getProp(elem2, data2.rz, 0, degToRads, this); + if (data2.or.k[0].ti) { + var i; + var len = data2.or.k.length; + for (i = 0;i < len; i += 1) { + data2.or.k[i].to = null; + data2.or.k[i].ti = null; + } + } + this.or = PropertyFactory.getProp(elem2, data2.or, 1, degToRads, this); + this.or.sh = true; + } else { + this.r = PropertyFactory.getProp(elem2, data2.r || { k: 0 }, 0, degToRads, this); + } + if (data2.sk) { + this.sk = PropertyFactory.getProp(elem2, data2.sk, 0, degToRads, this); + this.sa = PropertyFactory.getProp(elem2, data2.sa, 0, degToRads, this); + } + this.a = PropertyFactory.getProp(elem2, data2.a || { k: [0, 0, 0] }, 1, 0, this); + this.s = PropertyFactory.getProp(elem2, data2.s || { k: [100, 100, 100] }, 1, 0.01, this); + if (data2.o) { + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, elem2); + } else { + this.o = { _mdf: false, v: 1 }; + } + this._isDirty = true; + if (!this.dynamicProperties.length) { + this.getValue(true); + } + } + TransformProperty.prototype = { + applyToMatrix, + getValue: processKeys, + precalculateMatrix, + autoOrient + }; + extendPrototype([DynamicPropertyContainer], TransformProperty); + TransformProperty.prototype.addDynamicProperty = addDynamicProperty; + TransformProperty.prototype._addDynamicProperty = DynamicPropertyContainer.prototype.addDynamicProperty; + function getTransformProperty(elem2, data2, container) { + return new TransformProperty(elem2, data2, container); + } + return { + getTransformProperty + }; + }(); + extendPrototype([ShapeModifier], RepeaterModifier); + RepeaterModifier.prototype.initModifierProperties = function(elem2, data2) { + this.getValue = this.processKeys; + this.c = PropertyFactory.getProp(elem2, data2.c, 0, null, this); + this.o = PropertyFactory.getProp(elem2, data2.o, 0, null, this); + this.tr = TransformPropertyFactory.getTransformProperty(elem2, data2.tr, this); + this.so = PropertyFactory.getProp(elem2, data2.tr.so, 0, 0.01, this); + this.eo = PropertyFactory.getProp(elem2, data2.tr.eo, 0, 0.01, this); + this.data = data2; + if (!this.dynamicProperties.length) { + this.getValue(true); + } + this._isAnimated = !!this.dynamicProperties.length; + this.pMatrix = new Matrix; + this.rMatrix = new Matrix; + this.sMatrix = new Matrix; + this.tMatrix = new Matrix; + this.matrix = new Matrix; + }; + RepeaterModifier.prototype.applyTransforms = function(pMatrix, rMatrix, sMatrix, transform2, perc, inv) { + var dir = inv ? -1 : 1; + var scaleX = transform2.s.v[0] + (1 - transform2.s.v[0]) * (1 - perc); + var scaleY = transform2.s.v[1] + (1 - transform2.s.v[1]) * (1 - perc); + pMatrix.translate(transform2.p.v[0] * dir * perc, transform2.p.v[1] * dir * perc, transform2.p.v[2]); + rMatrix.translate(-transform2.a.v[0], -transform2.a.v[1], transform2.a.v[2]); + rMatrix.rotate(-transform2.r.v * dir * perc); + rMatrix.translate(transform2.a.v[0], transform2.a.v[1], transform2.a.v[2]); + sMatrix.translate(-transform2.a.v[0], -transform2.a.v[1], transform2.a.v[2]); + sMatrix.scale(inv ? 1 / scaleX : scaleX, inv ? 1 / scaleY : scaleY); + sMatrix.translate(transform2.a.v[0], transform2.a.v[1], transform2.a.v[2]); + }; + RepeaterModifier.prototype.init = function(elem2, arr, pos, elemsData) { + this.elem = elem2; + this.arr = arr; + this.pos = pos; + this.elemsData = elemsData; + this._currentCopies = 0; + this._elements = []; + this._groups = []; + this.frameId = -1; + this.initDynamicPropertyContainer(elem2); + this.initModifierProperties(elem2, arr[pos]); + while (pos > 0) { + pos -= 1; + this._elements.unshift(arr[pos]); + } + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.getValue(true); + } + }; + RepeaterModifier.prototype.resetElements = function(elements) { + var i; + var len = elements.length; + for (i = 0;i < len; i += 1) { + elements[i]._processed = false; + if (elements[i].ty === "gr") { + this.resetElements(elements[i].it); + } + } + }; + RepeaterModifier.prototype.cloneElements = function(elements) { + var newElements = JSON.parse(JSON.stringify(elements)); + this.resetElements(newElements); + return newElements; + }; + RepeaterModifier.prototype.changeGroupRender = function(elements, renderFlag) { + var i; + var len = elements.length; + for (i = 0;i < len; i += 1) { + elements[i]._render = renderFlag; + if (elements[i].ty === "gr") { + this.changeGroupRender(elements[i].it, renderFlag); + } + } + }; + RepeaterModifier.prototype.processShapes = function(_isFirstFrame) { + var items; + var itemsTransform; + var i; + var dir; + var cont; + var hasReloaded = false; + if (this._mdf || _isFirstFrame) { + var copies = Math.ceil(this.c.v); + if (this._groups.length < copies) { + while (this._groups.length < copies) { + var group = { + it: this.cloneElements(this._elements), + ty: "gr" + }; + group.it.push({ + a: { a: 0, ix: 1, k: [0, 0] }, + nm: "Transform", + o: { a: 0, ix: 7, k: 100 }, + p: { a: 0, ix: 2, k: [0, 0] }, + r: { a: 1, ix: 6, k: [{ s: 0, e: 0, t: 0 }, { s: 0, e: 0, t: 1 }] }, + s: { a: 0, ix: 3, k: [100, 100] }, + sa: { a: 0, ix: 5, k: 0 }, + sk: { a: 0, ix: 4, k: 0 }, + ty: "tr" + }); + this.arr.splice(0, 0, group); + this._groups.splice(0, 0, group); + this._currentCopies += 1; + } + this.elem.reloadShapes(); + hasReloaded = true; + } + cont = 0; + var renderFlag; + for (i = 0;i <= this._groups.length - 1; i += 1) { + renderFlag = cont < copies; + this._groups[i]._render = renderFlag; + this.changeGroupRender(this._groups[i].it, renderFlag); + if (!renderFlag) { + var elems = this.elemsData[i].it; + var transformData = elems[elems.length - 1]; + if (transformData.transform.op.v !== 0) { + transformData.transform.op._mdf = true; + transformData.transform.op.v = 0; + } else { + transformData.transform.op._mdf = false; + } + } + cont += 1; + } + this._currentCopies = copies; + var offset = this.o.v; + var offsetModulo = offset % 1; + var roundOffset = offset > 0 ? Math.floor(offset) : Math.ceil(offset); + var pProps = this.pMatrix.props; + var rProps = this.rMatrix.props; + var sProps = this.sMatrix.props; + this.pMatrix.reset(); + this.rMatrix.reset(); + this.sMatrix.reset(); + this.tMatrix.reset(); + this.matrix.reset(); + var iteration = 0; + if (offset > 0) { + while (iteration < roundOffset) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, false); + iteration += 1; + } + if (offsetModulo) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, offsetModulo, false); + iteration += offsetModulo; + } + } else if (offset < 0) { + while (iteration > roundOffset) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, true); + iteration -= 1; + } + if (offsetModulo) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, -offsetModulo, true); + iteration -= offsetModulo; + } + } + i = this.data.m === 1 ? 0 : this._currentCopies - 1; + dir = this.data.m === 1 ? 1 : -1; + cont = this._currentCopies; + var j2; + var jLen; + while (cont) { + items = this.elemsData[i].it; + itemsTransform = items[items.length - 1].transform.mProps.v.props; + jLen = itemsTransform.length; + items[items.length - 1].transform.mProps._mdf = true; + items[items.length - 1].transform.op._mdf = true; + items[items.length - 1].transform.op.v = this._currentCopies === 1 ? this.so.v : this.so.v + (this.eo.v - this.so.v) * (i / (this._currentCopies - 1)); + if (iteration !== 0) { + if (i !== 0 && dir === 1 || i !== this._currentCopies - 1 && dir === -1) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, false); + } + this.matrix.transform(rProps[0], rProps[1], rProps[2], rProps[3], rProps[4], rProps[5], rProps[6], rProps[7], rProps[8], rProps[9], rProps[10], rProps[11], rProps[12], rProps[13], rProps[14], rProps[15]); + this.matrix.transform(sProps[0], sProps[1], sProps[2], sProps[3], sProps[4], sProps[5], sProps[6], sProps[7], sProps[8], sProps[9], sProps[10], sProps[11], sProps[12], sProps[13], sProps[14], sProps[15]); + this.matrix.transform(pProps[0], pProps[1], pProps[2], pProps[3], pProps[4], pProps[5], pProps[6], pProps[7], pProps[8], pProps[9], pProps[10], pProps[11], pProps[12], pProps[13], pProps[14], pProps[15]); + for (j2 = 0;j2 < jLen; j2 += 1) { + itemsTransform[j2] = this.matrix.props[j2]; + } + this.matrix.reset(); + } else { + this.matrix.reset(); + for (j2 = 0;j2 < jLen; j2 += 1) { + itemsTransform[j2] = this.matrix.props[j2]; + } + } + iteration += 1; + cont -= 1; + i += dir; + } + } else { + cont = this._currentCopies; + i = 0; + dir = 1; + while (cont) { + items = this.elemsData[i].it; + itemsTransform = items[items.length - 1].transform.mProps.v.props; + items[items.length - 1].transform.mProps._mdf = false; + items[items.length - 1].transform.op._mdf = false; + cont -= 1; + i += dir; + } + } + return hasReloaded; + }; + RepeaterModifier.prototype.addShape = function() { + }; + extendPrototype([ShapeModifier], RoundCornersModifier); + RoundCornersModifier.prototype.initModifierProperties = function(elem2, data2) { + this.getValue = this.processKeys; + this.rd = PropertyFactory.getProp(elem2, data2.r, 0, null, this); + this._isAnimated = !!this.rd.effectsSequence.length; + }; + RoundCornersModifier.prototype.processPath = function(path, round) { + var clonedPath = shapePool.newElement(); + clonedPath.c = path.c; + var i; + var len = path._length; + var currentV; + var currentI; + var currentO; + var closerV; + var distance; + var newPosPerc; + var index2 = 0; + var vX; + var vY; + var oX; + var oY; + var iX; + var iY; + for (i = 0;i < len; i += 1) { + currentV = path.v[i]; + currentO = path.o[i]; + currentI = path.i[i]; + if (currentV[0] === currentO[0] && currentV[1] === currentO[1] && currentV[0] === currentI[0] && currentV[1] === currentI[1]) { + if ((i === 0 || i === len - 1) && !path.c) { + clonedPath.setTripleAt(currentV[0], currentV[1], currentO[0], currentO[1], currentI[0], currentI[1], index2); + index2 += 1; + } else { + if (i === 0) { + closerV = path.v[len - 1]; + } else { + closerV = path.v[i - 1]; + } + distance = Math.sqrt(Math.pow(currentV[0] - closerV[0], 2) + Math.pow(currentV[1] - closerV[1], 2)); + newPosPerc = distance ? Math.min(distance / 2, round) / distance : 0; + iX = currentV[0] + (closerV[0] - currentV[0]) * newPosPerc; + vX = iX; + iY = currentV[1] - (currentV[1] - closerV[1]) * newPosPerc; + vY = iY; + oX = vX - (vX - currentV[0]) * roundCorner; + oY = vY - (vY - currentV[1]) * roundCorner; + clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, index2); + index2 += 1; + if (i === len - 1) { + closerV = path.v[0]; + } else { + closerV = path.v[i + 1]; + } + distance = Math.sqrt(Math.pow(currentV[0] - closerV[0], 2) + Math.pow(currentV[1] - closerV[1], 2)); + newPosPerc = distance ? Math.min(distance / 2, round) / distance : 0; + oX = currentV[0] + (closerV[0] - currentV[0]) * newPosPerc; + vX = oX; + oY = currentV[1] + (closerV[1] - currentV[1]) * newPosPerc; + vY = oY; + iX = vX - (vX - currentV[0]) * roundCorner; + iY = vY - (vY - currentV[1]) * roundCorner; + clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, index2); + index2 += 1; + } + } else { + clonedPath.setTripleAt(path.v[i][0], path.v[i][1], path.o[i][0], path.o[i][1], path.i[i][0], path.i[i][1], index2); + index2 += 1; + } + } + return clonedPath; + }; + RoundCornersModifier.prototype.processShapes = function(_isFirstFrame) { + var shapePaths; + var i; + var len = this.shapes.length; + var j2; + var jLen; + var rd = this.rd.v; + if (rd !== 0) { + var shapeData; + var localShapeCollection; + for (i = 0;i < len; i += 1) { + shapeData = this.shapes[i]; + localShapeCollection = shapeData.localShapeCollection; + if (!(!shapeData.shape._mdf && !this._mdf && !_isFirstFrame)) { + localShapeCollection.releaseShapes(); + shapeData.shape._mdf = true; + shapePaths = shapeData.shape.paths.shapes; + jLen = shapeData.shape.paths._length; + for (j2 = 0;j2 < jLen; j2 += 1) { + localShapeCollection.addShape(this.processPath(shapePaths[j2], rd)); + } + } + shapeData.shape.paths = shapeData.localShapeCollection; + } + } + if (!this.dynamicProperties.length) { + this._mdf = false; + } + }; + const FontManager = function() { + var maxWaitingTime = 5000; + var emptyChar = { + w: 0, + size: 0, + shapes: [], + data: { + shapes: [] + } + }; + var combinedCharacters = []; + combinedCharacters = combinedCharacters.concat([ + 2304, + 2305, + 2306, + 2307, + 2362, + 2363, + 2364, + 2364, + 2366, + 2367, + 2368, + 2369, + 2370, + 2371, + 2372, + 2373, + 2374, + 2375, + 2376, + 2377, + 2378, + 2379, + 2380, + 2381, + 2382, + 2383, + 2387, + 2388, + 2389, + 2390, + 2391, + 2402, + 2403 + ]); + var surrogateModifiers = [ + "d83cdffb", + "d83cdffc", + "d83cdffd", + "d83cdffe", + "d83cdfff" + ]; + var zeroWidthJoiner = [65039, 8205]; + function trimFontOptions(font) { + var familyArray = font.split(","); + var i; + var len = familyArray.length; + var enabledFamilies = []; + for (i = 0;i < len; i += 1) { + if (familyArray[i] !== "sans-serif" && familyArray[i] !== "monospace") { + enabledFamilies.push(familyArray[i]); + } + } + return enabledFamilies.join(","); + } + function setUpNode(font, family) { + var parentNode = createTag("span"); + parentNode.setAttribute("aria-hidden", true); + parentNode.style.fontFamily = family; + var node = createTag("span"); + node.innerText = "giItT1WQy@!-/#"; + parentNode.style.position = "absolute"; + parentNode.style.left = "-10000px"; + parentNode.style.top = "-10000px"; + parentNode.style.fontSize = "300px"; + parentNode.style.fontVariant = "normal"; + parentNode.style.fontStyle = "normal"; + parentNode.style.fontWeight = "normal"; + parentNode.style.letterSpacing = "0"; + parentNode.appendChild(node); + document.body.appendChild(parentNode); + var width2 = node.offsetWidth; + node.style.fontFamily = trimFontOptions(font) + ", " + family; + return { node, w: width2, parent: parentNode }; + } + function checkLoadedFonts() { + var i; + var len = this.fonts.length; + var node; + var w; + var loadedCount = len; + for (i = 0;i < len; i += 1) { + if (this.fonts[i].loaded) { + loadedCount -= 1; + } else if (this.fonts[i].fOrigin === "n" || this.fonts[i].origin === 0) { + this.fonts[i].loaded = true; + } else { + node = this.fonts[i].monoCase.node; + w = this.fonts[i].monoCase.w; + if (node.offsetWidth !== w) { + loadedCount -= 1; + this.fonts[i].loaded = true; + } else { + node = this.fonts[i].sansCase.node; + w = this.fonts[i].sansCase.w; + if (node.offsetWidth !== w) { + loadedCount -= 1; + this.fonts[i].loaded = true; + } + } + if (this.fonts[i].loaded) { + this.fonts[i].sansCase.parent.parentNode.removeChild(this.fonts[i].sansCase.parent); + this.fonts[i].monoCase.parent.parentNode.removeChild(this.fonts[i].monoCase.parent); + } + } + } + if (loadedCount !== 0 && Date.now() - this.initTime < maxWaitingTime) { + setTimeout(this.checkLoadedFontsBinded, 20); + } else { + setTimeout(this.setIsLoadedBinded, 10); + } + } + function createHelper(fontData, def) { + var engine = document.body && def ? "svg" : "canvas"; + var helper; + var fontProps = getFontProperties(fontData); + if (engine === "svg") { + var tHelper = createNS("text"); + tHelper.style.fontSize = "100px"; + tHelper.setAttribute("font-family", fontData.fFamily); + tHelper.setAttribute("font-style", fontProps.style); + tHelper.setAttribute("font-weight", fontProps.weight); + tHelper.textContent = "1"; + if (fontData.fClass) { + tHelper.style.fontFamily = "inherit"; + tHelper.setAttribute("class", fontData.fClass); + } else { + tHelper.style.fontFamily = fontData.fFamily; + } + def.appendChild(tHelper); + helper = tHelper; + } else { + var tCanvasHelper = new OffscreenCanvas(500, 500).getContext("2d"); + tCanvasHelper.font = fontProps.style + " " + fontProps.weight + " 100px " + fontData.fFamily; + helper = tCanvasHelper; + } + function measure(text2) { + if (engine === "svg") { + helper.textContent = text2; + return helper.getComputedTextLength(); + } + return helper.measureText(text2).width; + } + return { + measureText: measure + }; + } + function addFonts(fontData, defs) { + if (!fontData) { + this.isLoaded = true; + return; + } + if (this.chars) { + this.isLoaded = true; + this.fonts = fontData.list; + return; + } + if (!document.body) { + this.isLoaded = true; + fontData.list.forEach((data2) => { + data2.helper = createHelper(data2); + data2.cache = {}; + }); + this.fonts = fontData.list; + return; + } + var fontArr = fontData.list; + var i; + var len = fontArr.length; + var _pendingFonts = len; + for (i = 0;i < len; i += 1) { + var shouldLoadFont = true; + var loadedSelector; + var j2; + fontArr[i].loaded = false; + fontArr[i].monoCase = setUpNode(fontArr[i].fFamily, "monospace"); + fontArr[i].sansCase = setUpNode(fontArr[i].fFamily, "sans-serif"); + if (!fontArr[i].fPath) { + fontArr[i].loaded = true; + _pendingFonts -= 1; + } else if (fontArr[i].fOrigin === "p" || fontArr[i].origin === 3) { + loadedSelector = document.querySelectorAll('style[f-forigin="p"][f-family="' + fontArr[i].fFamily + '"], style[f-origin="3"][f-family="' + fontArr[i].fFamily + '"]'); + if (loadedSelector.length > 0) { + shouldLoadFont = false; + } + if (shouldLoadFont) { + var s = createTag("style"); + s.setAttribute("f-forigin", fontArr[i].fOrigin); + s.setAttribute("f-origin", fontArr[i].origin); + s.setAttribute("f-family", fontArr[i].fFamily); + s.type = "text/css"; + s.innerText = "@font-face {font-family: " + fontArr[i].fFamily + "; font-style: normal; src: url('" + fontArr[i].fPath + "');}"; + defs.appendChild(s); + } + } else if (fontArr[i].fOrigin === "g" || fontArr[i].origin === 1) { + loadedSelector = document.querySelectorAll('link[f-forigin="g"], link[f-origin="1"]'); + for (j2 = 0;j2 < loadedSelector.length; j2 += 1) { + if (loadedSelector[j2].href.indexOf(fontArr[i].fPath) !== -1) { + shouldLoadFont = false; + } + } + if (shouldLoadFont) { + var l2 = createTag("link"); + l2.setAttribute("f-forigin", fontArr[i].fOrigin); + l2.setAttribute("f-origin", fontArr[i].origin); + l2.type = "text/css"; + l2.rel = "stylesheet"; + l2.href = fontArr[i].fPath; + document.body.appendChild(l2); + } + } else if (fontArr[i].fOrigin === "t" || fontArr[i].origin === 2) { + loadedSelector = document.querySelectorAll('script[f-forigin="t"], script[f-origin="2"]'); + for (j2 = 0;j2 < loadedSelector.length; j2 += 1) { + if (fontArr[i].fPath === loadedSelector[j2].src) { + shouldLoadFont = false; + } + } + if (shouldLoadFont) { + var sc = createTag("link"); + sc.setAttribute("f-forigin", fontArr[i].fOrigin); + sc.setAttribute("f-origin", fontArr[i].origin); + sc.setAttribute("rel", "stylesheet"); + sc.setAttribute("href", fontArr[i].fPath); + defs.appendChild(sc); + } + } + fontArr[i].helper = createHelper(fontArr[i], defs); + fontArr[i].cache = {}; + this.fonts.push(fontArr[i]); + } + if (_pendingFonts === 0) { + this.isLoaded = true; + } else { + setTimeout(this.checkLoadedFonts.bind(this), 100); + } + } + function addChars(chars) { + if (!chars) { + return; + } + if (!this.chars) { + this.chars = []; + } + var i; + var len = chars.length; + var j2; + var jLen = this.chars.length; + var found; + for (i = 0;i < len; i += 1) { + j2 = 0; + found = false; + while (j2 < jLen) { + if (this.chars[j2].style === chars[i].style && this.chars[j2].fFamily === chars[i].fFamily && this.chars[j2].ch === chars[i].ch) { + found = true; + } + j2 += 1; + } + if (!found) { + this.chars.push(chars[i]); + jLen += 1; + } + } + } + function getCharData(char, style, font) { + var i = 0; + var len = this.chars.length; + while (i < len) { + if (this.chars[i].ch === char && this.chars[i].style === style && this.chars[i].fFamily === font) { + return this.chars[i]; + } + i += 1; + } + if ((typeof char === "string" && char.charCodeAt(0) !== 13 || !char) && console && console.warn && !this._warned) { + this._warned = true; + console.warn("Missing character from exported characters list: ", char, style, font); + } + return emptyChar; + } + function measureText(char, fontName, size) { + var fontData = this.getFontByName(fontName); + var index2 = char.charCodeAt(0); + if (!fontData.cache[index2 + 1]) { + var tHelper = fontData.helper; + if (char === " ") { + var doubleSize = tHelper.measureText("|" + char + "|"); + var singleSize = tHelper.measureText("||"); + fontData.cache[index2 + 1] = (doubleSize - singleSize) / 100; + } else { + fontData.cache[index2 + 1] = tHelper.measureText(char) / 100; + } + } + return fontData.cache[index2 + 1] * size; + } + function getFontByName(name2) { + var i = 0; + var len = this.fonts.length; + while (i < len) { + if (this.fonts[i].fName === name2) { + return this.fonts[i]; + } + i += 1; + } + return this.fonts[0]; + } + function isModifier(firstCharCode, secondCharCode) { + var sum2 = firstCharCode.toString(16) + secondCharCode.toString(16); + return surrogateModifiers.indexOf(sum2) !== -1; + } + function isZeroWidthJoiner(firstCharCode, secondCharCode) { + if (!secondCharCode) { + return firstCharCode === zeroWidthJoiner[1]; + } + return firstCharCode === zeroWidthJoiner[0] && secondCharCode === zeroWidthJoiner[1]; + } + function isCombinedCharacter(char) { + return combinedCharacters.indexOf(char) !== -1; + } + function setIsLoaded() { + this.isLoaded = true; + } + var Font = function() { + this.fonts = []; + this.chars = null; + this.typekitLoaded = 0; + this.isLoaded = false; + this._warned = false; + this.initTime = Date.now(); + this.setIsLoadedBinded = this.setIsLoaded.bind(this); + this.checkLoadedFontsBinded = this.checkLoadedFonts.bind(this); + }; + Font.isModifier = isModifier; + Font.isZeroWidthJoiner = isZeroWidthJoiner; + Font.isCombinedCharacter = isCombinedCharacter; + var fontPrototype = { + addChars, + addFonts, + getCharData, + getFontByName, + measureText, + checkLoadedFonts, + setIsLoaded + }; + Font.prototype = fontPrototype; + return Font; + }(); + RenderableElement.prototype = { + initRenderable: function() { + this.isInRange = false; + this.hidden = false; + this.isTransparent = false; + this.renderableComponents = []; + }, + addRenderableComponent: function(component) { + if (this.renderableComponents.indexOf(component) === -1) { + this.renderableComponents.push(component); + } + }, + removeRenderableComponent: function(component) { + if (this.renderableComponents.indexOf(component) !== -1) { + this.renderableComponents.splice(this.renderableComponents.indexOf(component), 1); + } + }, + prepareRenderableFrame: function(num) { + this.checkLayerLimits(num); + }, + checkTransparency: function() { + if (this.finalTransform.mProp.o.v <= 0) { + if (!this.isTransparent && this.globalData.renderConfig.hideOnTransparent) { + this.isTransparent = true; + this.hide(); + } + } else if (this.isTransparent) { + this.isTransparent = false; + this.show(); + } + }, + checkLayerLimits: function(num) { + if (this.data.ip - this.data.st <= num && this.data.op - this.data.st > num) { + if (this.isInRange !== true) { + this.globalData._mdf = true; + this._mdf = true; + this.isInRange = true; + this.show(); + } + } else if (this.isInRange !== false) { + this.globalData._mdf = true; + this.isInRange = false; + this.hide(); + } + }, + renderRenderable: function() { + var i; + var len = this.renderableComponents.length; + for (i = 0;i < len; i += 1) { + this.renderableComponents[i].renderFrame(this._isFirstFrame); + } + }, + sourceRectAtTime: function() { + return { + top: 0, + left: 0, + width: 100, + height: 100 + }; + }, + getLayerSize: function() { + if (this.data.ty === 5) { + return { w: this.data.textData.width, h: this.data.textData.height }; + } + return { w: this.data.width, h: this.data.height }; + } + }; + const MaskManagerInterface = function() { + function MaskInterface(mask2, data2) { + this._mask = mask2; + this._data = data2; + } + Object.defineProperty(MaskInterface.prototype, "maskPath", { + get: function() { + if (this._mask.prop.k) { + this._mask.prop.getValue(); + } + return this._mask.prop; + } + }); + Object.defineProperty(MaskInterface.prototype, "maskOpacity", { + get: function() { + if (this._mask.op.k) { + this._mask.op.getValue(); + } + return this._mask.op.v * 100; + } + }); + var MaskManager = function(maskManager) { + var _masksInterfaces = createSizedArray(maskManager.viewData.length); + var i; + var len = maskManager.viewData.length; + for (i = 0;i < len; i += 1) { + _masksInterfaces[i] = new MaskInterface(maskManager.viewData[i], maskManager.masksProperties[i]); + } + var maskFunction = function(name2) { + i = 0; + while (i < len) { + if (maskManager.masksProperties[i].nm === name2) { + return _masksInterfaces[i]; + } + i += 1; + } + return null; + }; + return maskFunction; + }; + return MaskManager; + }(); + const ExpressionPropertyInterface = function() { + var defaultUnidimensionalValue = { pv: 0, v: 0, mult: 1 }; + var defaultMultidimensionalValue = { pv: [0, 0, 0], v: [0, 0, 0], mult: 1 }; + function completeProperty(expressionValue, property2, type) { + Object.defineProperty(expressionValue, "velocity", { + get: function() { + return property2.getVelocityAtTime(property2.comp.currentFrame); + } + }); + expressionValue.numKeys = property2.keyframes ? property2.keyframes.length : 0; + expressionValue.key = function(pos) { + if (!expressionValue.numKeys) { + return 0; + } + var value2 = ""; + if ("s" in property2.keyframes[pos - 1]) { + value2 = property2.keyframes[pos - 1].s; + } else if ("e" in property2.keyframes[pos - 2]) { + value2 = property2.keyframes[pos - 2].e; + } else { + value2 = property2.keyframes[pos - 2].s; + } + var valueProp = type === "unidimensional" ? new Number(value2) : Object.assign({}, value2); + valueProp.time = property2.keyframes[pos - 1].t / property2.elem.comp.globalData.frameRate; + valueProp.value = type === "unidimensional" ? value2[0] : value2; + return valueProp; + }; + expressionValue.valueAtTime = property2.getValueAtTime; + expressionValue.speedAtTime = property2.getSpeedAtTime; + expressionValue.velocityAtTime = property2.getVelocityAtTime; + expressionValue.propertyGroup = property2.propertyGroup; + } + function UnidimensionalPropertyInterface(property2) { + if (!property2 || !("pv" in property2)) { + property2 = defaultUnidimensionalValue; + } + var mult = 1 / property2.mult; + var val2 = property2.pv * mult; + var expressionValue = new Number(val2); + expressionValue.value = val2; + completeProperty(expressionValue, property2, "unidimensional"); + return function() { + if (property2.k) { + property2.getValue(); + } + val2 = property2.v * mult; + if (expressionValue.value !== val2) { + expressionValue = new Number(val2); + expressionValue.value = val2; + completeProperty(expressionValue, property2, "unidimensional"); + } + return expressionValue; + }; + } + function MultidimensionalPropertyInterface(property2) { + if (!property2 || !("pv" in property2)) { + property2 = defaultMultidimensionalValue; + } + var mult = 1 / property2.mult; + var len = property2.data && property2.data.l || property2.pv.length; + var expressionValue = createTypedArray("float32", len); + var arrValue = createTypedArray("float32", len); + expressionValue.value = arrValue; + completeProperty(expressionValue, property2, "multidimensional"); + return function() { + if (property2.k) { + property2.getValue(); + } + for (var i = 0;i < len; i += 1) { + arrValue[i] = property2.v[i] * mult; + expressionValue[i] = arrValue[i]; + } + return expressionValue; + }; + } + function defaultGetter() { + return defaultUnidimensionalValue; + } + return function(property2) { + if (!property2) { + return defaultGetter; + } + if (property2.propType === "unidimensional") { + return UnidimensionalPropertyInterface(property2); + } + return MultidimensionalPropertyInterface(property2); + }; + }(); + const TransformExpressionInterface = function() { + return function(transform2) { + function _thisFunction(name2) { + switch (name2) { + case "scale": + case "Scale": + case "ADBE Scale": + case 6: + return _thisFunction.scale; + case "rotation": + case "Rotation": + case "ADBE Rotation": + case "ADBE Rotate Z": + case 10: + return _thisFunction.rotation; + case "ADBE Rotate X": + return _thisFunction.xRotation; + case "ADBE Rotate Y": + return _thisFunction.yRotation; + case "position": + case "Position": + case "ADBE Position": + case 2: + return _thisFunction.position; + case "ADBE Position_0": + return _thisFunction.xPosition; + case "ADBE Position_1": + return _thisFunction.yPosition; + case "ADBE Position_2": + return _thisFunction.zPosition; + case "anchorPoint": + case "AnchorPoint": + case "Anchor Point": + case "ADBE AnchorPoint": + case 1: + return _thisFunction.anchorPoint; + case "opacity": + case "Opacity": + case 11: + return _thisFunction.opacity; + default: + return null; + } + } + Object.defineProperty(_thisFunction, "rotation", { + get: ExpressionPropertyInterface(transform2.r || transform2.rz) + }); + Object.defineProperty(_thisFunction, "zRotation", { + get: ExpressionPropertyInterface(transform2.rz || transform2.r) + }); + Object.defineProperty(_thisFunction, "xRotation", { + get: ExpressionPropertyInterface(transform2.rx) + }); + Object.defineProperty(_thisFunction, "yRotation", { + get: ExpressionPropertyInterface(transform2.ry) + }); + Object.defineProperty(_thisFunction, "scale", { + get: ExpressionPropertyInterface(transform2.s) + }); + var _px; + var _py; + var _pz; + var _transformFactory; + if (transform2.p) { + _transformFactory = ExpressionPropertyInterface(transform2.p); + } else { + _px = ExpressionPropertyInterface(transform2.px); + _py = ExpressionPropertyInterface(transform2.py); + if (transform2.pz) { + _pz = ExpressionPropertyInterface(transform2.pz); + } + } + Object.defineProperty(_thisFunction, "position", { + get: function() { + if (transform2.p) { + return _transformFactory(); + } + return [ + _px(), + _py(), + _pz ? _pz() : 0 + ]; + } + }); + Object.defineProperty(_thisFunction, "xPosition", { + get: ExpressionPropertyInterface(transform2.px) + }); + Object.defineProperty(_thisFunction, "yPosition", { + get: ExpressionPropertyInterface(transform2.py) + }); + Object.defineProperty(_thisFunction, "zPosition", { + get: ExpressionPropertyInterface(transform2.pz) + }); + Object.defineProperty(_thisFunction, "anchorPoint", { + get: ExpressionPropertyInterface(transform2.a) + }); + Object.defineProperty(_thisFunction, "opacity", { + get: ExpressionPropertyInterface(transform2.o) + }); + Object.defineProperty(_thisFunction, "skew", { + get: ExpressionPropertyInterface(transform2.sk) + }); + Object.defineProperty(_thisFunction, "skewAxis", { + get: ExpressionPropertyInterface(transform2.sa) + }); + Object.defineProperty(_thisFunction, "orientation", { + get: ExpressionPropertyInterface(transform2.or) + }); + return _thisFunction; + }; + }(); + const LayerExpressionInterface = function() { + function getMatrix(time2) { + var toWorldMat = new Matrix; + if (time2 !== undefined) { + var propMatrix = this._elem.finalTransform.mProp.getValueAtTime(time2); + propMatrix.clone(toWorldMat); + } else { + var transformMat = this._elem.finalTransform.mProp; + transformMat.applyToMatrix(toWorldMat); + } + return toWorldMat; + } + function toWorldVec(arr, time2) { + var toWorldMat = this.getMatrix(time2); + toWorldMat.props[12] = 0; + toWorldMat.props[13] = 0; + toWorldMat.props[14] = 0; + return this.applyPoint(toWorldMat, arr); + } + function toWorld2(arr, time2) { + var toWorldMat = this.getMatrix(time2); + return this.applyPoint(toWorldMat, arr); + } + function fromWorldVec(arr, time2) { + var toWorldMat = this.getMatrix(time2); + toWorldMat.props[12] = 0; + toWorldMat.props[13] = 0; + toWorldMat.props[14] = 0; + return this.invertPoint(toWorldMat, arr); + } + function fromWorld2(arr, time2) { + var toWorldMat = this.getMatrix(time2); + return this.invertPoint(toWorldMat, arr); + } + function applyPoint(matrix, arr) { + if (this._elem.hierarchy && this._elem.hierarchy.length) { + var i; + var len = this._elem.hierarchy.length; + for (i = 0;i < len; i += 1) { + this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(matrix); + } + } + return matrix.applyToPointArray(arr[0], arr[1], arr[2] || 0); + } + function invertPoint(matrix, arr) { + if (this._elem.hierarchy && this._elem.hierarchy.length) { + var i; + var len = this._elem.hierarchy.length; + for (i = 0;i < len; i += 1) { + this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(matrix); + } + } + return matrix.inversePoint(arr); + } + function fromComp2(arr) { + var toWorldMat = new Matrix; + toWorldMat.reset(); + this._elem.finalTransform.mProp.applyToMatrix(toWorldMat); + if (this._elem.hierarchy && this._elem.hierarchy.length) { + var i; + var len = this._elem.hierarchy.length; + for (i = 0;i < len; i += 1) { + this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(toWorldMat); + } + return toWorldMat.inversePoint(arr); + } + return toWorldMat.inversePoint(arr); + } + function sampleImage() { + return [1, 1, 1, 1]; + } + return function(elem2) { + var transformInterface; + function _registerMaskInterface(maskManager) { + _thisLayerFunction.mask = new MaskManagerInterface(maskManager, elem2); + } + function _registerEffectsInterface(effects) { + _thisLayerFunction.effect = effects; + } + function _thisLayerFunction(name2) { + switch (name2) { + case "ADBE Root Vectors Group": + case "Contents": + case 2: + return _thisLayerFunction.shapeInterface; + case 1: + case 6: + case "Transform": + case "transform": + case "ADBE Transform Group": + return transformInterface; + case 4: + case "ADBE Effect Parade": + case "effects": + case "Effects": + return _thisLayerFunction.effect; + case "ADBE Text Properties": + return _thisLayerFunction.textInterface; + default: + return null; + } + } + _thisLayerFunction.getMatrix = getMatrix; + _thisLayerFunction.invertPoint = invertPoint; + _thisLayerFunction.applyPoint = applyPoint; + _thisLayerFunction.toWorld = toWorld2; + _thisLayerFunction.toWorldVec = toWorldVec; + _thisLayerFunction.fromWorld = fromWorld2; + _thisLayerFunction.fromWorldVec = fromWorldVec; + _thisLayerFunction.toComp = toWorld2; + _thisLayerFunction.fromComp = fromComp2; + _thisLayerFunction.sampleImage = sampleImage; + _thisLayerFunction.sourceRectAtTime = elem2.sourceRectAtTime.bind(elem2); + _thisLayerFunction._elem = elem2; + transformInterface = TransformExpressionInterface(elem2.finalTransform.mProp); + var anchorPointDescriptor = getDescriptor(transformInterface, "anchorPoint"); + Object.defineProperties(_thisLayerFunction, { + hasParent: { + get: function() { + return elem2.hierarchy.length; + } + }, + parent: { + get: function() { + return elem2.hierarchy[0].layerInterface; + } + }, + rotation: getDescriptor(transformInterface, "rotation"), + scale: getDescriptor(transformInterface, "scale"), + position: getDescriptor(transformInterface, "position"), + opacity: getDescriptor(transformInterface, "opacity"), + anchorPoint: anchorPointDescriptor, + anchor_point: anchorPointDescriptor, + transform: { + get: function() { + return transformInterface; + } + }, + active: { + get: function() { + return elem2.isInRange; + } + } + }); + _thisLayerFunction.startTime = elem2.data.st; + _thisLayerFunction.index = elem2.data.ind; + _thisLayerFunction.source = elem2.data.refId; + _thisLayerFunction.height = elem2.data.ty === 0 ? elem2.data.h : 100; + _thisLayerFunction.width = elem2.data.ty === 0 ? elem2.data.w : 100; + _thisLayerFunction.inPoint = elem2.data.ip / elem2.comp.globalData.frameRate; + _thisLayerFunction.outPoint = elem2.data.op / elem2.comp.globalData.frameRate; + _thisLayerFunction._name = elem2.data.nm; + _thisLayerFunction.registerMaskInterface = _registerMaskInterface; + _thisLayerFunction.registerEffectsInterface = _registerEffectsInterface; + return _thisLayerFunction; + }; + }(); + const propertyGroupFactory = function() { + return function(interfaceFunction, parentPropertyGroup) { + return function(val2) { + val2 = val2 === undefined ? 1 : val2; + if (val2 <= 0) { + return interfaceFunction; + } + return parentPropertyGroup(val2 - 1); + }; + }; + }(); + const PropertyInterface = function() { + return function(propertyName, propertyGroup) { + var interfaceFunction = { + _name: propertyName + }; + function _propertyGroup(val2) { + val2 = val2 === undefined ? 1 : val2; + if (val2 <= 0) { + return interfaceFunction; + } + return propertyGroup(val2 - 1); + } + return _propertyGroup; + }; + }(); + const EffectsExpressionInterface = function() { + var ob2 = { + createEffectsInterface + }; + function createEffectsInterface(elem2, propertyGroup) { + if (elem2.effectsManager) { + var effectElements = []; + var effectsData = elem2.data.ef; + var i; + var len = elem2.effectsManager.effectElements.length; + for (i = 0;i < len; i += 1) { + effectElements.push(createGroupInterface(effectsData[i], elem2.effectsManager.effectElements[i], propertyGroup, elem2)); + } + var effects = elem2.data.ef || []; + var groupInterface = function(name2) { + i = 0; + len = effects.length; + while (i < len) { + if (name2 === effects[i].nm || name2 === effects[i].mn || name2 === effects[i].ix) { + return effectElements[i]; + } + i += 1; + } + return null; + }; + Object.defineProperty(groupInterface, "numProperties", { + get: function() { + return effects.length; + } + }); + return groupInterface; + } + return null; + } + function createGroupInterface(data2, elements, propertyGroup, elem2) { + function groupInterface(name2) { + var effects = data2.ef; + var i2 = 0; + var len2 = effects.length; + while (i2 < len2) { + if (name2 === effects[i2].nm || name2 === effects[i2].mn || name2 === effects[i2].ix) { + if (effects[i2].ty === 5) { + return effectElements[i2]; + } + return effectElements[i2](); + } + i2 += 1; + } + throw new Error; + } + var _propertyGroup = propertyGroupFactory(groupInterface, propertyGroup); + var effectElements = []; + var i; + var len = data2.ef.length; + for (i = 0;i < len; i += 1) { + if (data2.ef[i].ty === 5) { + effectElements.push(createGroupInterface(data2.ef[i], elements.effectElements[i], elements.effectElements[i].propertyGroup, elem2)); + } else { + effectElements.push(createValueInterface(elements.effectElements[i], data2.ef[i].ty, elem2, _propertyGroup)); + } + } + if (data2.mn === "ADBE Color Control") { + Object.defineProperty(groupInterface, "color", { + get: function() { + return effectElements[0](); + } + }); + } + Object.defineProperties(groupInterface, { + numProperties: { + get: function() { + return data2.np; + } + }, + _name: { value: data2.nm }, + propertyGroup: { value: _propertyGroup } + }); + groupInterface.enabled = data2.en !== 0; + groupInterface.active = groupInterface.enabled; + return groupInterface; + } + function createValueInterface(element, type, elem2, propertyGroup) { + var expressionProperty = ExpressionPropertyInterface(element.p); + function interfaceFunction() { + if (type === 10) { + return elem2.comp.compInterface(element.p.v); + } + return expressionProperty(); + } + if (element.p.setGroupProperty) { + element.p.setGroupProperty(PropertyInterface("", propertyGroup)); + } + return interfaceFunction; + } + return ob2; + }(); + const CompExpressionInterface = function() { + return function(comp2) { + function _thisLayerFunction(name2) { + var i = 0; + var len = comp2.layers.length; + while (i < len) { + if (comp2.layers[i].nm === name2 || comp2.layers[i].ind === name2) { + return comp2.elements[i].layerInterface; + } + i += 1; + } + return null; + } + Object.defineProperty(_thisLayerFunction, "_name", { value: comp2.data.nm }); + _thisLayerFunction.layer = _thisLayerFunction; + _thisLayerFunction.pixelAspect = 1; + _thisLayerFunction.height = comp2.data.h || comp2.globalData.compSize.h; + _thisLayerFunction.width = comp2.data.w || comp2.globalData.compSize.w; + _thisLayerFunction.pixelAspect = 1; + _thisLayerFunction.frameDuration = 1 / comp2.globalData.frameRate; + _thisLayerFunction.displayStartTime = 0; + _thisLayerFunction.numLayers = comp2.layers.length; + return _thisLayerFunction; + }; + }(); + const ShapePathInterface = function() { + return function pathInterfaceFactory(shape, view, propertyGroup) { + var prop = view.sh; + function interfaceFunction(val2) { + if (val2 === "Shape" || val2 === "shape" || val2 === "Path" || val2 === "path" || val2 === "ADBE Vector Shape" || val2 === 2) { + return interfaceFunction.path; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + prop.setGroupProperty(PropertyInterface("Path", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + path: { + get: function() { + if (prop.k) { + prop.getValue(); + } + return prop; + } + }, + shape: { + get: function() { + if (prop.k) { + prop.getValue(); + } + return prop; + } + }, + _name: { value: shape.nm }, + ix: { value: shape.ix }, + propertyIndex: { value: shape.ix }, + mn: { value: shape.mn }, + propertyGroup: { value: propertyGroup } + }); + return interfaceFunction; + }; + }(); + const ShapeExpressionInterface = function() { + function iterateElements(shapes, view, propertyGroup) { + var arr = []; + var i; + var len = shapes ? shapes.length : 0; + for (i = 0;i < len; i += 1) { + if (shapes[i].ty === "gr") { + arr.push(groupInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "fl") { + arr.push(fillInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "st") { + arr.push(strokeInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "tm") { + arr.push(trimInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "tr") { + } else if (shapes[i].ty === "el") { + arr.push(ellipseInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "sr") { + arr.push(starInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "sh") { + arr.push(ShapePathInterface(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "rc") { + arr.push(rectInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "rd") { + arr.push(roundedInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "rp") { + arr.push(repeaterInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "gf") { + arr.push(gradientFillInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else { + arr.push(defaultInterfaceFactory(shapes[i], view[i], propertyGroup)); + } + } + return arr; + } + function contentsInterfaceFactory(shape, view, propertyGroup) { + var interfaces; + var interfaceFunction = function _interfaceFunction(value2) { + var i = 0; + var len = interfaces.length; + while (i < len) { + if (interfaces[i]._name === value2 || interfaces[i].mn === value2 || interfaces[i].propertyIndex === value2 || interfaces[i].ix === value2 || interfaces[i].ind === value2) { + return interfaces[i]; + } + i += 1; + } + if (typeof value2 === "number") { + return interfaces[value2 - 1]; + } + return null; + }; + interfaceFunction.propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + interfaces = iterateElements(shape.it, view.it, interfaceFunction.propertyGroup); + interfaceFunction.numProperties = interfaces.length; + var transformInterface = transformInterfaceFactory(shape.it[shape.it.length - 1], view.it[view.it.length - 1], interfaceFunction.propertyGroup); + interfaceFunction.transform = transformInterface; + interfaceFunction.propertyIndex = shape.cix; + interfaceFunction._name = shape.nm; + return interfaceFunction; + } + function groupInterfaceFactory(shape, view, propertyGroup) { + var interfaceFunction = function _interfaceFunction(value2) { + switch (value2) { + case "ADBE Vectors Group": + case "Contents": + case 2: + return interfaceFunction.content; + default: + return interfaceFunction.transform; + } + }; + interfaceFunction.propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var content2 = contentsInterfaceFactory(shape, view, interfaceFunction.propertyGroup); + var transformInterface = transformInterfaceFactory(shape.it[shape.it.length - 1], view.it[view.it.length - 1], interfaceFunction.propertyGroup); + interfaceFunction.content = content2; + interfaceFunction.transform = transformInterface; + Object.defineProperty(interfaceFunction, "_name", { + get: function() { + return shape.nm; + } + }); + interfaceFunction.numProperties = shape.np; + interfaceFunction.propertyIndex = shape.ix; + interfaceFunction.nm = shape.nm; + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function fillInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(val2) { + if (val2 === "Color" || val2 === "color") { + return interfaceFunction.color; + } + if (val2 === "Opacity" || val2 === "opacity") { + return interfaceFunction.opacity; + } + return null; + } + Object.defineProperties(interfaceFunction, { + color: { + get: ExpressionPropertyInterface(view.c) + }, + opacity: { + get: ExpressionPropertyInterface(view.o) + }, + _name: { value: shape.nm }, + mn: { value: shape.mn } + }); + view.c.setGroupProperty(PropertyInterface("Color", propertyGroup)); + view.o.setGroupProperty(PropertyInterface("Opacity", propertyGroup)); + return interfaceFunction; + } + function gradientFillInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(val2) { + if (val2 === "Start Point" || val2 === "start point") { + return interfaceFunction.startPoint; + } + if (val2 === "End Point" || val2 === "end point") { + return interfaceFunction.endPoint; + } + if (val2 === "Opacity" || val2 === "opacity") { + return interfaceFunction.opacity; + } + return null; + } + Object.defineProperties(interfaceFunction, { + startPoint: { + get: ExpressionPropertyInterface(view.s) + }, + endPoint: { + get: ExpressionPropertyInterface(view.e) + }, + opacity: { + get: ExpressionPropertyInterface(view.o) + }, + type: { + get: function() { + return "a"; + } + }, + _name: { value: shape.nm }, + mn: { value: shape.mn } + }); + view.s.setGroupProperty(PropertyInterface("Start Point", propertyGroup)); + view.e.setGroupProperty(PropertyInterface("End Point", propertyGroup)); + view.o.setGroupProperty(PropertyInterface("Opacity", propertyGroup)); + return interfaceFunction; + } + function defaultInterfaceFactory() { + function interfaceFunction() { + return null; + } + return interfaceFunction; + } + function strokeInterfaceFactory(shape, view, propertyGroup) { + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var _dashPropertyGroup = propertyGroupFactory(dashOb, _propertyGroup); + function addPropertyToDashOb(i2) { + Object.defineProperty(dashOb, shape.d[i2].nm, { + get: ExpressionPropertyInterface(view.d.dataProps[i2].p) + }); + } + var i; + var len = shape.d ? shape.d.length : 0; + var dashOb = {}; + for (i = 0;i < len; i += 1) { + addPropertyToDashOb(i); + view.d.dataProps[i].p.setGroupProperty(_dashPropertyGroup); + } + function interfaceFunction(val2) { + if (val2 === "Color" || val2 === "color") { + return interfaceFunction.color; + } + if (val2 === "Opacity" || val2 === "opacity") { + return interfaceFunction.opacity; + } + if (val2 === "Stroke Width" || val2 === "stroke width") { + return interfaceFunction.strokeWidth; + } + return null; + } + Object.defineProperties(interfaceFunction, { + color: { + get: ExpressionPropertyInterface(view.c) + }, + opacity: { + get: ExpressionPropertyInterface(view.o) + }, + strokeWidth: { + get: ExpressionPropertyInterface(view.w) + }, + dash: { + get: function() { + return dashOb; + } + }, + _name: { value: shape.nm }, + mn: { value: shape.mn } + }); + view.c.setGroupProperty(PropertyInterface("Color", _propertyGroup)); + view.o.setGroupProperty(PropertyInterface("Opacity", _propertyGroup)); + view.w.setGroupProperty(PropertyInterface("Stroke Width", _propertyGroup)); + return interfaceFunction; + } + function trimInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(val2) { + if (val2 === shape.e.ix || val2 === "End" || val2 === "end") { + return interfaceFunction.end; + } + if (val2 === shape.s.ix) { + return interfaceFunction.start; + } + if (val2 === shape.o.ix) { + return interfaceFunction.offset; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + interfaceFunction.propertyIndex = shape.ix; + view.s.setGroupProperty(PropertyInterface("Start", _propertyGroup)); + view.e.setGroupProperty(PropertyInterface("End", _propertyGroup)); + view.o.setGroupProperty(PropertyInterface("Offset", _propertyGroup)); + interfaceFunction.propertyIndex = shape.ix; + interfaceFunction.propertyGroup = propertyGroup; + Object.defineProperties(interfaceFunction, { + start: { + get: ExpressionPropertyInterface(view.s) + }, + end: { + get: ExpressionPropertyInterface(view.e) + }, + offset: { + get: ExpressionPropertyInterface(view.o) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function transformInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.a.ix === value2 || value2 === "Anchor Point") { + return interfaceFunction.anchorPoint; + } + if (shape.o.ix === value2 || value2 === "Opacity") { + return interfaceFunction.opacity; + } + if (shape.p.ix === value2 || value2 === "Position") { + return interfaceFunction.position; + } + if (shape.r.ix === value2 || value2 === "Rotation" || value2 === "ADBE Vector Rotation") { + return interfaceFunction.rotation; + } + if (shape.s.ix === value2 || value2 === "Scale") { + return interfaceFunction.scale; + } + if (shape.sk && shape.sk.ix === value2 || value2 === "Skew") { + return interfaceFunction.skew; + } + if (shape.sa && shape.sa.ix === value2 || value2 === "Skew Axis") { + return interfaceFunction.skewAxis; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + view.transform.mProps.o.setGroupProperty(PropertyInterface("Opacity", _propertyGroup)); + view.transform.mProps.p.setGroupProperty(PropertyInterface("Position", _propertyGroup)); + view.transform.mProps.a.setGroupProperty(PropertyInterface("Anchor Point", _propertyGroup)); + view.transform.mProps.s.setGroupProperty(PropertyInterface("Scale", _propertyGroup)); + view.transform.mProps.r.setGroupProperty(PropertyInterface("Rotation", _propertyGroup)); + if (view.transform.mProps.sk) { + view.transform.mProps.sk.setGroupProperty(PropertyInterface("Skew", _propertyGroup)); + view.transform.mProps.sa.setGroupProperty(PropertyInterface("Skew Angle", _propertyGroup)); + } + view.transform.op.setGroupProperty(PropertyInterface("Opacity", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + opacity: { + get: ExpressionPropertyInterface(view.transform.mProps.o) + }, + position: { + get: ExpressionPropertyInterface(view.transform.mProps.p) + }, + anchorPoint: { + get: ExpressionPropertyInterface(view.transform.mProps.a) + }, + scale: { + get: ExpressionPropertyInterface(view.transform.mProps.s) + }, + rotation: { + get: ExpressionPropertyInterface(view.transform.mProps.r) + }, + skew: { + get: ExpressionPropertyInterface(view.transform.mProps.sk) + }, + skewAxis: { + get: ExpressionPropertyInterface(view.transform.mProps.sa) + }, + _name: { value: shape.nm } + }); + interfaceFunction.ty = "tr"; + interfaceFunction.mn = shape.mn; + interfaceFunction.propertyGroup = propertyGroup; + return interfaceFunction; + } + function ellipseInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.p.ix === value2) { + return interfaceFunction.position; + } + if (shape.s.ix === value2) { + return interfaceFunction.size; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + interfaceFunction.propertyIndex = shape.ix; + var prop = view.sh.ty === "tm" ? view.sh.prop : view.sh; + prop.s.setGroupProperty(PropertyInterface("Size", _propertyGroup)); + prop.p.setGroupProperty(PropertyInterface("Position", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + size: { + get: ExpressionPropertyInterface(prop.s) + }, + position: { + get: ExpressionPropertyInterface(prop.p) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function starInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.p.ix === value2) { + return interfaceFunction.position; + } + if (shape.r.ix === value2) { + return interfaceFunction.rotation; + } + if (shape.pt.ix === value2) { + return interfaceFunction.points; + } + if (shape.or.ix === value2 || value2 === "ADBE Vector Star Outer Radius") { + return interfaceFunction.outerRadius; + } + if (shape.os.ix === value2) { + return interfaceFunction.outerRoundness; + } + if (shape.ir && (shape.ir.ix === value2 || value2 === "ADBE Vector Star Inner Radius")) { + return interfaceFunction.innerRadius; + } + if (shape.is && shape.is.ix === value2) { + return interfaceFunction.innerRoundness; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var prop = view.sh.ty === "tm" ? view.sh.prop : view.sh; + interfaceFunction.propertyIndex = shape.ix; + prop.or.setGroupProperty(PropertyInterface("Outer Radius", _propertyGroup)); + prop.os.setGroupProperty(PropertyInterface("Outer Roundness", _propertyGroup)); + prop.pt.setGroupProperty(PropertyInterface("Points", _propertyGroup)); + prop.p.setGroupProperty(PropertyInterface("Position", _propertyGroup)); + prop.r.setGroupProperty(PropertyInterface("Rotation", _propertyGroup)); + if (shape.ir) { + prop.ir.setGroupProperty(PropertyInterface("Inner Radius", _propertyGroup)); + prop.is.setGroupProperty(PropertyInterface("Inner Roundness", _propertyGroup)); + } + Object.defineProperties(interfaceFunction, { + position: { + get: ExpressionPropertyInterface(prop.p) + }, + rotation: { + get: ExpressionPropertyInterface(prop.r) + }, + points: { + get: ExpressionPropertyInterface(prop.pt) + }, + outerRadius: { + get: ExpressionPropertyInterface(prop.or) + }, + outerRoundness: { + get: ExpressionPropertyInterface(prop.os) + }, + innerRadius: { + get: ExpressionPropertyInterface(prop.ir) + }, + innerRoundness: { + get: ExpressionPropertyInterface(prop.is) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function rectInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.p.ix === value2) { + return interfaceFunction.position; + } + if (shape.r.ix === value2) { + return interfaceFunction.roundness; + } + if (shape.s.ix === value2 || value2 === "Size" || value2 === "ADBE Vector Rect Size") { + return interfaceFunction.size; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var prop = view.sh.ty === "tm" ? view.sh.prop : view.sh; + interfaceFunction.propertyIndex = shape.ix; + prop.p.setGroupProperty(PropertyInterface("Position", _propertyGroup)); + prop.s.setGroupProperty(PropertyInterface("Size", _propertyGroup)); + prop.r.setGroupProperty(PropertyInterface("Rotation", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + position: { + get: ExpressionPropertyInterface(prop.p) + }, + roundness: { + get: ExpressionPropertyInterface(prop.r) + }, + size: { + get: ExpressionPropertyInterface(prop.s) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function roundedInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.r.ix === value2 || value2 === "Round Corners 1") { + return interfaceFunction.radius; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var prop = view; + interfaceFunction.propertyIndex = shape.ix; + prop.rd.setGroupProperty(PropertyInterface("Radius", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + radius: { + get: ExpressionPropertyInterface(prop.rd) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function repeaterInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.c.ix === value2 || value2 === "Copies") { + return interfaceFunction.copies; + } + if (shape.o.ix === value2 || value2 === "Offset") { + return interfaceFunction.offset; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var prop = view; + interfaceFunction.propertyIndex = shape.ix; + prop.c.setGroupProperty(PropertyInterface("Copies", _propertyGroup)); + prop.o.setGroupProperty(PropertyInterface("Offset", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + copies: { + get: ExpressionPropertyInterface(prop.c) + }, + offset: { + get: ExpressionPropertyInterface(prop.o) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + return function(shapes, view, propertyGroup) { + var interfaces; + function _interfaceFunction(value2) { + if (typeof value2 === "number") { + value2 = value2 === undefined ? 1 : value2; + if (value2 === 0) { + return propertyGroup; + } + return interfaces[value2 - 1]; + } + var i = 0; + var len = interfaces.length; + while (i < len) { + if (interfaces[i]._name === value2) { + return interfaces[i]; + } + i += 1; + } + return null; + } + function parentGroupWrapper() { + return propertyGroup; + } + _interfaceFunction.propertyGroup = propertyGroupFactory(_interfaceFunction, parentGroupWrapper); + interfaces = iterateElements(shapes, view, _interfaceFunction.propertyGroup); + _interfaceFunction.numProperties = interfaces.length; + _interfaceFunction._name = "Contents"; + return _interfaceFunction; + }; + }(); + const TextExpressionInterface = function() { + return function(elem2) { + var _prevValue; + var _sourceText; + function _thisLayerFunction(name2) { + switch (name2) { + case "ADBE Text Document": + return _thisLayerFunction.sourceText; + default: + return null; + } + } + Object.defineProperty(_thisLayerFunction, "sourceText", { + get: function() { + elem2.textProperty.getValue(); + var stringValue = elem2.textProperty.currentData.t; + if (stringValue !== _prevValue) { + elem2.textProperty.currentData.t = _prevValue; + _sourceText = new String(stringValue); + _sourceText.value = stringValue || new String(stringValue); + } + return _sourceText; + } + }); + return _thisLayerFunction; + }; + }(); + const getBlendMode = function() { + var blendModeEnums = { + 0: "source-over", + 1: "multiply", + 2: "screen", + 3: "overlay", + 4: "darken", + 5: "lighten", + 6: "color-dodge", + 7: "color-burn", + 8: "hard-light", + 9: "soft-light", + 10: "difference", + 11: "exclusion", + 12: "hue", + 13: "saturation", + 14: "color", + 15: "luminosity" + }; + return function(mode) { + return blendModeEnums[mode] || ""; + }; + }(); + extendPrototype([DynamicPropertyContainer], GroupEffect); + GroupEffect.prototype.getValue = GroupEffect.prototype.iterateDynamicProperties; + GroupEffect.prototype.init = function(data2, element) { + this.data = data2; + this.effectElements = []; + this.initDynamicPropertyContainer(element); + var i; + var len = this.data.ef.length; + var eff; + var effects = this.data.ef; + for (i = 0;i < len; i += 1) { + eff = null; + switch (effects[i].ty) { + case 0: + eff = new SliderEffect(effects[i], element, this); + break; + case 1: + eff = new AngleEffect(effects[i], element, this); + break; + case 2: + eff = new ColorEffect(effects[i], element, this); + break; + case 3: + eff = new PointEffect(effects[i], element, this); + break; + case 4: + case 7: + eff = new CheckboxEffect(effects[i], element, this); + break; + case 10: + eff = new LayerIndexEffect(effects[i], element, this); + break; + case 11: + eff = new MaskIndexEffect(effects[i], element, this); + break; + case 5: + eff = new EffectsManager(effects[i], element, this); + break; + default: + eff = new NoValueEffect(effects[i], element, this); + break; + } + if (eff) { + this.effectElements.push(eff); + } + } + }; + BaseElement.prototype = { + checkMasks: function() { + if (!this.data.hasMask) { + return false; + } + var i = 0; + var len = this.data.masksProperties.length; + while (i < len) { + if (this.data.masksProperties[i].mode !== "n" && this.data.masksProperties[i].cl !== false) { + return true; + } + i += 1; + } + return false; + }, + initExpressions: function() { + this.layerInterface = LayerExpressionInterface(this); + if (this.data.hasMask && this.maskManager) { + this.layerInterface.registerMaskInterface(this.maskManager); + } + var effectsInterface = EffectsExpressionInterface.createEffectsInterface(this, this.layerInterface); + this.layerInterface.registerEffectsInterface(effectsInterface); + if (this.data.ty === 0 || this.data.xt) { + this.compInterface = CompExpressionInterface(this); + } else if (this.data.ty === 4) { + this.layerInterface.shapeInterface = ShapeExpressionInterface(this.shapesData, this.itemsData, this.layerInterface); + this.layerInterface.content = this.layerInterface.shapeInterface; + } else if (this.data.ty === 5) { + this.layerInterface.textInterface = TextExpressionInterface(this); + this.layerInterface.text = this.layerInterface.textInterface; + } + }, + setBlendMode: function() { + var blendModeValue = getBlendMode(this.data.bm); + var elem2 = this.baseElement || this.layerElement; + elem2.style["mix-blend-mode"] = blendModeValue; + }, + initBaseData: function(data2, globalData2, comp2) { + this.globalData = globalData2; + this.comp = comp2; + this.data = data2; + this.layerId = createElementID(); + if (!this.data.sr) { + this.data.sr = 1; + } + this.effectsManager = new EffectsManager(this.data, this, this.dynamicProperties); + }, + getType: function() { + return this.type; + }, + sourceRectAtTime: function() { + } + }; + FrameElement.prototype = { + initFrame: function() { + this._isFirstFrame = false; + this.dynamicProperties = []; + this._mdf = false; + }, + prepareProperties: function(num, isVisible) { + var i; + var len = this.dynamicProperties.length; + for (i = 0;i < len; i += 1) { + if (isVisible || this._isParent && this.dynamicProperties[i].propType === "transform") { + this.dynamicProperties[i].getValue(); + if (this.dynamicProperties[i]._mdf) { + this.globalData._mdf = true; + this._mdf = true; + } + } + } + }, + addDynamicProperty: function(prop) { + if (this.dynamicProperties.indexOf(prop) === -1) { + this.dynamicProperties.push(prop); + } + } + }; + const FootageInterface = function() { + var outlineInterfaceFactory = function(elem2) { + var currentPropertyName = ""; + var currentProperty = elem2.getFootageData(); + function init() { + currentPropertyName = ""; + currentProperty = elem2.getFootageData(); + return searchProperty; + } + function searchProperty(value2) { + if (currentProperty[value2]) { + currentPropertyName = value2; + currentProperty = currentProperty[value2]; + if (typeof currentProperty === "object") { + return searchProperty; + } + return currentProperty; + } + var propertyNameIndex = value2.indexOf(currentPropertyName); + if (propertyNameIndex !== -1) { + var index2 = parseInt(value2.substr(propertyNameIndex + currentPropertyName.length), 10); + currentProperty = currentProperty[index2]; + if (typeof currentProperty === "object") { + return searchProperty; + } + return currentProperty; + } + return ""; + } + return init; + }; + var dataInterfaceFactory = function(elem2) { + function interfaceFunction(value2) { + if (value2 === "Outline") { + return interfaceFunction.outlineInterface(); + } + return null; + } + interfaceFunction._name = "Outline"; + interfaceFunction.outlineInterface = outlineInterfaceFactory(elem2); + return interfaceFunction; + }; + return function(elem2) { + function _interfaceFunction(value2) { + if (value2 === "Data") { + return _interfaceFunction.dataInterface; + } + return null; + } + _interfaceFunction._name = "Data"; + _interfaceFunction.dataInterface = dataInterfaceFactory(elem2); + return _interfaceFunction; + }; + }(); + FootageElement.prototype.prepareFrame = function() { + }; + extendPrototype([RenderableElement, BaseElement, FrameElement], FootageElement); + FootageElement.prototype.getBaseElement = function() { + return null; + }; + FootageElement.prototype.renderFrame = function() { + }; + FootageElement.prototype.destroy = function() { + }; + FootageElement.prototype.initExpressions = function() { + this.layerInterface = FootageInterface(this); + }; + FootageElement.prototype.getFootageData = function() { + return this.footageData; + }; + AudioElement.prototype.prepareFrame = function(num) { + this.prepareRenderableFrame(num, true); + this.prepareProperties(num, true); + if (!this.tm._placeholder) { + var timeRemapped = this.tm.v; + this._currentTime = timeRemapped; + } else { + this._currentTime = num / this.data.sr; + } + this._volume = this.lv.v[0]; + var totalVolume = this._volume * this._volumeMultiplier; + if (this._previousVolume !== totalVolume) { + this._previousVolume = totalVolume; + this.audio.volume(totalVolume); + } + }; + extendPrototype([RenderableElement, BaseElement, FrameElement], AudioElement); + AudioElement.prototype.renderFrame = function() { + if (this.isInRange && this._canPlay) { + if (!this._isPlaying) { + this.audio.play(); + this.audio.seek(this._currentTime / this.globalData.frameRate); + this._isPlaying = true; + } else if (!this.audio.playing() || Math.abs(this._currentTime / this.globalData.frameRate - this.audio.seek()) > 0.1) { + this.audio.seek(this._currentTime / this.globalData.frameRate); + } + } + }; + AudioElement.prototype.show = function() { + }; + AudioElement.prototype.hide = function() { + this.audio.pause(); + this._isPlaying = false; + }; + AudioElement.prototype.pause = function() { + this.audio.pause(); + this._isPlaying = false; + this._canPlay = false; + }; + AudioElement.prototype.resume = function() { + this._canPlay = true; + }; + AudioElement.prototype.setRate = function(rateValue) { + this.audio.rate(rateValue); + }; + AudioElement.prototype.volume = function(volumeValue) { + this._volumeMultiplier = volumeValue; + this._previousVolume = volumeValue * this._volume; + this.audio.volume(this._previousVolume); + }; + AudioElement.prototype.getBaseElement = function() { + return null; + }; + AudioElement.prototype.destroy = function() { + }; + AudioElement.prototype.sourceRectAtTime = function() { + }; + AudioElement.prototype.initExpressions = function() { + }; + BaseRenderer.prototype.checkLayers = function(num) { + var i; + var len = this.layers.length; + var data2; + this.completeLayers = true; + for (i = len - 1;i >= 0; i -= 1) { + if (!this.elements[i]) { + data2 = this.layers[i]; + if (data2.ip - data2.st <= num - this.layers[i].st && data2.op - data2.st > num - this.layers[i].st) { + this.buildItem(i); + } + } + this.completeLayers = this.elements[i] ? this.completeLayers : false; + } + this.checkPendingElements(); + }; + BaseRenderer.prototype.createItem = function(layer) { + switch (layer.ty) { + case 2: + return this.createImage(layer); + case 0: + return this.createComp(layer); + case 1: + return this.createSolid(layer); + case 3: + return this.createNull(layer); + case 4: + return this.createShape(layer); + case 5: + return this.createText(layer); + case 6: + return this.createAudio(layer); + case 13: + return this.createCamera(layer); + case 15: + return this.createFootage(layer); + default: + return this.createNull(layer); + } + }; + BaseRenderer.prototype.createCamera = function() { + throw new Error("You're using a 3d camera. Try the html renderer."); + }; + BaseRenderer.prototype.createAudio = function(data2) { + return new AudioElement(data2, this.globalData, this); + }; + BaseRenderer.prototype.createFootage = function(data2) { + return new FootageElement(data2, this.globalData, this); + }; + BaseRenderer.prototype.buildAllItems = function() { + var i; + var len = this.layers.length; + for (i = 0;i < len; i += 1) { + this.buildItem(i); + } + this.checkPendingElements(); + }; + BaseRenderer.prototype.includeLayers = function(newLayers) { + this.completeLayers = false; + var i; + var len = newLayers.length; + var j2; + var jLen = this.layers.length; + for (i = 0;i < len; i += 1) { + j2 = 0; + while (j2 < jLen) { + if (this.layers[j2].id === newLayers[i].id) { + this.layers[j2] = newLayers[i]; + break; + } + j2 += 1; + } + } + }; + BaseRenderer.prototype.setProjectInterface = function(pInterface) { + this.globalData.projectInterface = pInterface; + }; + BaseRenderer.prototype.initItems = function() { + if (!this.globalData.progressiveLoad) { + this.buildAllItems(); + } + }; + BaseRenderer.prototype.buildElementParenting = function(element, parentName, hierarchy) { + var elements = this.elements; + var layers = this.layers; + var i = 0; + var len = layers.length; + while (i < len) { + if (layers[i].ind == parentName) { + if (!elements[i] || elements[i] === true) { + this.buildItem(i); + this.addPendingElement(element); + } else { + hierarchy.push(elements[i]); + elements[i].setAsParent(); + if (layers[i].parent !== undefined) { + this.buildElementParenting(element, layers[i].parent, hierarchy); + } else { + element.setHierarchy(hierarchy); + } + } + } + i += 1; + } + }; + BaseRenderer.prototype.addPendingElement = function(element) { + this.pendingElements.push(element); + }; + BaseRenderer.prototype.searchExtraCompositions = function(assets) { + var i; + var len = assets.length; + for (i = 0;i < len; i += 1) { + if (assets[i].xt) { + var comp2 = this.createComp(assets[i]); + comp2.initExpressions(); + this.globalData.projectInterface.registerComposition(comp2); + } + } + }; + BaseRenderer.prototype.getElementByPath = function(path) { + var pathValue = path.shift(); + var element; + if (typeof pathValue === "number") { + element = this.elements[pathValue]; + } else { + var i; + var len = this.elements.length; + for (i = 0;i < len; i += 1) { + if (this.elements[i].data.nm === pathValue) { + element = this.elements[i]; + break; + } + } + } + if (path.length === 0) { + return element; + } + return element.getElementByPath(path); + }; + BaseRenderer.prototype.setupGlobalData = function(animData, fontsContainer) { + this.globalData.fontManager = new FontManager; + this.globalData.fontManager.addChars(animData.chars); + this.globalData.fontManager.addFonts(animData.fonts, fontsContainer); + this.globalData.getAssetData = this.animationItem.getAssetData.bind(this.animationItem); + this.globalData.getAssetsPath = this.animationItem.getAssetsPath.bind(this.animationItem); + this.globalData.imageLoader = this.animationItem.imagePreloader; + this.globalData.audioController = this.animationItem.audioController; + this.globalData.frameId = 0; + this.globalData.frameRate = animData.fr; + this.globalData.nm = animData.nm; + this.globalData.compSize = { + w: animData.w, + h: animData.h + }; + }; + TransformElement.prototype = { + initTransform: function() { + this.finalTransform = { + mProp: this.data.ks ? TransformPropertyFactory.getTransformProperty(this, this.data.ks, this) : { o: 0 }, + _matMdf: false, + _opMdf: false, + mat: new Matrix + }; + if (this.data.ao) { + this.finalTransform.mProp.autoOriented = true; + } + if (this.data.ty !== 11) { + } + }, + renderTransform: function() { + this.finalTransform._opMdf = this.finalTransform.mProp.o._mdf || this._isFirstFrame; + this.finalTransform._matMdf = this.finalTransform.mProp._mdf || this._isFirstFrame; + if (this.hierarchy) { + var mat; + var finalMat = this.finalTransform.mat; + var i = 0; + var len = this.hierarchy.length; + if (!this.finalTransform._matMdf) { + while (i < len) { + if (this.hierarchy[i].finalTransform.mProp._mdf) { + this.finalTransform._matMdf = true; + break; + } + i += 1; + } + } + if (this.finalTransform._matMdf) { + mat = this.finalTransform.mProp.v.props; + finalMat.cloneFromProps(mat); + for (i = 0;i < len; i += 1) { + mat = this.hierarchy[i].finalTransform.mProp.v.props; + finalMat.transform(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5], mat[6], mat[7], mat[8], mat[9], mat[10], mat[11], mat[12], mat[13], mat[14], mat[15]); + } + } + } + }, + globalToLocal: function(pt) { + var transforms = []; + transforms.push(this.finalTransform); + var flag = true; + var comp2 = this.comp; + while (flag) { + if (comp2.finalTransform) { + if (comp2.data.hasMask) { + transforms.splice(0, 0, comp2.finalTransform); + } + comp2 = comp2.comp; + } else { + flag = false; + } + } + var i; + var len = transforms.length; + var ptNew; + for (i = 0;i < len; i += 1) { + ptNew = transforms[i].mat.applyToPointArray(0, 0, 0); + pt = [pt[0] - ptNew[0], pt[1] - ptNew[1], 0]; + } + return pt; + }, + mHelper: new Matrix + }; + MaskElement.prototype.getMaskProperty = function(pos) { + return this.viewData[pos].prop; + }; + MaskElement.prototype.renderFrame = function(isFirstFrame) { + var finalMat = this.element.finalTransform.mat; + var i; + var len = this.masksProperties.length; + for (i = 0;i < len; i += 1) { + if (this.viewData[i].prop._mdf || isFirstFrame) { + this.drawPath(this.masksProperties[i], this.viewData[i].prop.v, this.viewData[i]); + } + if (this.viewData[i].op._mdf || isFirstFrame) { + this.viewData[i].elem.setAttribute("fill-opacity", this.viewData[i].op.v); + } + if (this.masksProperties[i].mode !== "n") { + if (this.viewData[i].invRect && (this.element.finalTransform.mProp._mdf || isFirstFrame)) { + this.viewData[i].invRect.setAttribute("transform", finalMat.getInverseMatrix().to2dCSS()); + } + if (this.storedData[i].x && (this.storedData[i].x._mdf || isFirstFrame)) { + var feMorph = this.storedData[i].expan; + if (this.storedData[i].x.v < 0) { + if (this.storedData[i].lastOperator !== "erode") { + this.storedData[i].lastOperator = "erode"; + this.storedData[i].elem.setAttribute("filter", "url(" + getLocationHref() + "#" + this.storedData[i].filterId + ")"); + } + feMorph.setAttribute("radius", -this.storedData[i].x.v); + } else { + if (this.storedData[i].lastOperator !== "dilate") { + this.storedData[i].lastOperator = "dilate"; + this.storedData[i].elem.setAttribute("filter", null); + } + this.storedData[i].elem.setAttribute("stroke-width", this.storedData[i].x.v * 2); + } + } + } + } + }; + MaskElement.prototype.getMaskelement = function() { + return this.maskElement; + }; + MaskElement.prototype.createLayerSolidPath = function() { + var path = "M0,0 "; + path += " h" + this.globalData.compSize.w; + path += " v" + this.globalData.compSize.h; + path += " h-" + this.globalData.compSize.w; + path += " v-" + this.globalData.compSize.h + " "; + return path; + }; + MaskElement.prototype.drawPath = function(pathData, pathNodes, viewData) { + var pathString = " M" + pathNodes.v[0][0] + "," + pathNodes.v[0][1]; + var i; + var len; + len = pathNodes._length; + for (i = 1;i < len; i += 1) { + pathString += " C" + pathNodes.o[i - 1][0] + "," + pathNodes.o[i - 1][1] + " " + pathNodes.i[i][0] + "," + pathNodes.i[i][1] + " " + pathNodes.v[i][0] + "," + pathNodes.v[i][1]; + } + if (pathNodes.c && len > 1) { + pathString += " C" + pathNodes.o[i - 1][0] + "," + pathNodes.o[i - 1][1] + " " + pathNodes.i[0][0] + "," + pathNodes.i[0][1] + " " + pathNodes.v[0][0] + "," + pathNodes.v[0][1]; + } + if (viewData.lastPath !== pathString) { + var pathShapeValue = ""; + if (viewData.elem) { + if (pathNodes.c) { + pathShapeValue = pathData.inv ? this.solidPath + pathString : pathString; + } + viewData.elem.setAttribute("d", pathShapeValue); + } + viewData.lastPath = pathString; + } + }; + MaskElement.prototype.destroy = function() { + this.element = null; + this.globalData = null; + this.maskElement = null; + this.data = null; + this.masksProperties = null; + }; + const filtersFactory = function() { + var ob2 = {}; + ob2.createFilter = createFilter; + ob2.createAlphaToLuminanceFilter = createAlphaToLuminanceFilter; + function createFilter(filId, skipCoordinates) { + var fil = createNS("filter"); + fil.setAttribute("id", filId); + if (skipCoordinates !== true) { + fil.setAttribute("filterUnits", "objectBoundingBox"); + fil.setAttribute("x", "0%"); + fil.setAttribute("y", "0%"); + fil.setAttribute("width", "100%"); + fil.setAttribute("height", "100%"); + } + return fil; + } + function createAlphaToLuminanceFilter() { + var feColorMatrix = createNS("feColorMatrix"); + feColorMatrix.setAttribute("type", "matrix"); + feColorMatrix.setAttribute("color-interpolation-filters", "sRGB"); + feColorMatrix.setAttribute("values", "0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1"); + return feColorMatrix; + } + return ob2; + }(); + const featureSupport = function() { + var ob2 = { + maskType: true + }; + if (/MSIE 10/i.test(navigator.userAgent) || /MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent) || /Edge\/\d./i.test(navigator.userAgent)) { + ob2.maskType = false; + } + return ob2; + }(); + registeredEffects = {}; + idPrefix = "filter_result_"; + SVGEffects.prototype.renderFrame = function(_isFirstFrame) { + var i; + var len = this.filters.length; + for (i = 0;i < len; i += 1) { + this.filters[i].renderFrame(_isFirstFrame); + } + }; + SVGBaseElement.prototype = { + initRendererElement: function() { + this.layerElement = createNS("g"); + }, + createContainerElements: function() { + this.matteElement = createNS("g"); + this.transformedElement = this.layerElement; + this.maskedElement = this.layerElement; + this._sizeChanged = false; + var layerElementParent = null; + var filId; + var fil; + var gg; + if (this.data.td) { + if (this.data.td == 3 || this.data.td == 1) { + var masker = createNS("mask"); + masker.setAttribute("id", this.layerId); + masker.setAttribute("mask-type", this.data.td == 3 ? "luminance" : "alpha"); + masker.appendChild(this.layerElement); + layerElementParent = masker; + this.globalData.defs.appendChild(masker); + if (!featureSupport.maskType && this.data.td == 1) { + masker.setAttribute("mask-type", "luminance"); + filId = createElementID(); + fil = filtersFactory.createFilter(filId); + this.globalData.defs.appendChild(fil); + fil.appendChild(filtersFactory.createAlphaToLuminanceFilter()); + gg = createNS("g"); + gg.appendChild(this.layerElement); + layerElementParent = gg; + masker.appendChild(gg); + gg.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")"); + } + } else if (this.data.td == 2) { + var maskGroup = createNS("mask"); + maskGroup.setAttribute("id", this.layerId); + maskGroup.setAttribute("mask-type", "alpha"); + var maskGrouper = createNS("g"); + maskGroup.appendChild(maskGrouper); + filId = createElementID(); + fil = filtersFactory.createFilter(filId); + var feCTr = createNS("feComponentTransfer"); + feCTr.setAttribute("in", "SourceGraphic"); + fil.appendChild(feCTr); + var feFunc = createNS("feFuncA"); + feFunc.setAttribute("type", "table"); + feFunc.setAttribute("tableValues", "1.0 0.0"); + feCTr.appendChild(feFunc); + this.globalData.defs.appendChild(fil); + var alphaRect = createNS("rect"); + alphaRect.setAttribute("width", this.comp.data.w); + alphaRect.setAttribute("height", this.comp.data.h); + alphaRect.setAttribute("x", "0"); + alphaRect.setAttribute("y", "0"); + alphaRect.setAttribute("fill", "#ffffff"); + alphaRect.setAttribute("opacity", "0"); + maskGrouper.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")"); + maskGrouper.appendChild(alphaRect); + maskGrouper.appendChild(this.layerElement); + layerElementParent = maskGrouper; + if (!featureSupport.maskType) { + maskGroup.setAttribute("mask-type", "luminance"); + fil.appendChild(filtersFactory.createAlphaToLuminanceFilter()); + gg = createNS("g"); + maskGrouper.appendChild(alphaRect); + gg.appendChild(this.layerElement); + layerElementParent = gg; + maskGrouper.appendChild(gg); + } + this.globalData.defs.appendChild(maskGroup); + } + } else if (this.data.tt) { + this.matteElement.appendChild(this.layerElement); + layerElementParent = this.matteElement; + this.baseElement = this.matteElement; + } else { + this.baseElement = this.layerElement; + } + if (this.data.ln) { + this.layerElement.setAttribute("id", this.data.ln); + } + if (this.data.cl) { + this.layerElement.setAttribute("class", this.data.cl); + } + if (this.data.ty === 0 && !this.data.hd) { + var cp = createNS("clipPath"); + var pt = createNS("path"); + pt.setAttribute("d", "M0,0 L" + this.data.w + ",0 L" + this.data.w + "," + this.data.h + " L0," + this.data.h + "z"); + var clipId = createElementID(); + cp.setAttribute("id", clipId); + cp.appendChild(pt); + this.globalData.defs.appendChild(cp); + if (this.checkMasks()) { + var cpGroup = createNS("g"); + cpGroup.setAttribute("clip-path", "url(" + getLocationHref() + "#" + clipId + ")"); + cpGroup.appendChild(this.layerElement); + this.transformedElement = cpGroup; + if (layerElementParent) { + layerElementParent.appendChild(this.transformedElement); + } else { + this.baseElement = this.transformedElement; + } + } else { + this.layerElement.setAttribute("clip-path", "url(" + getLocationHref() + "#" + clipId + ")"); + } + } + if (this.data.bm !== 0) { + this.setBlendMode(); + } + }, + renderElement: function() { + if (this.finalTransform._matMdf) { + this.transformedElement.setAttribute("transform", this.finalTransform.mat.to2dCSS()); + } + if (this.finalTransform._opMdf) { + this.transformedElement.setAttribute("opacity", this.finalTransform.mProp.o.v); + } + }, + destroyBaseElement: function() { + this.layerElement = null; + this.matteElement = null; + this.maskManager.destroy(); + }, + getBaseElement: function() { + if (this.data.hd) { + return null; + } + return this.baseElement; + }, + createRenderableComponents: function() { + this.maskManager = new MaskElement(this.data, this, this.globalData); + this.renderableEffectsManager = new SVGEffects(this); + }, + setMatte: function(id) { + if (!this.matteElement) { + return; + } + this.matteElement.setAttribute("mask", "url(" + getLocationHref() + "#" + id + ")"); + } + }; + HierarchyElement.prototype = { + initHierarchy: function() { + this.hierarchy = []; + this._isParent = false; + this.checkParenting(); + }, + setHierarchy: function(hierarchy) { + this.hierarchy = hierarchy; + }, + setAsParent: function() { + this._isParent = true; + }, + checkParenting: function() { + if (this.data.parent !== undefined) { + this.comp.buildElementParenting(this, this.data.parent, []); + } + } + }; + (function() { + var _prototype = { + initElement: function(data2, globalData2, comp2) { + this.initFrame(); + this.initBaseData(data2, globalData2, comp2); + this.initTransform(data2, globalData2, comp2); + this.initHierarchy(); + this.initRenderable(); + this.initRendererElement(); + this.createContainerElements(); + this.createRenderableComponents(); + this.createContent(); + this.hide(); + }, + hide: function() { + if (!this.hidden && (!this.isInRange || this.isTransparent)) { + var elem2 = this.baseElement || this.layerElement; + elem2.style.display = "none"; + this.hidden = true; + } + }, + show: function() { + if (this.isInRange && !this.isTransparent) { + if (!this.data.hd) { + var elem2 = this.baseElement || this.layerElement; + elem2.style.display = "block"; + } + this.hidden = false; + this._isFirstFrame = true; + } + }, + renderFrame: function() { + if (this.data.hd || this.hidden) { + return; + } + this.renderTransform(); + this.renderRenderable(); + this.renderElement(); + this.renderInnerContent(); + if (this._isFirstFrame) { + this._isFirstFrame = false; + } + }, + renderInnerContent: function() { + }, + prepareFrame: function(num) { + this._mdf = false; + this.prepareRenderableFrame(num); + this.prepareProperties(num, this.isInRange); + this.checkTransparency(); + }, + destroy: function() { + this.innerElem = null; + this.destroyBaseElement(); + } + }; + extendPrototype([RenderableElement, createProxyFunction(_prototype)], RenderableDOMElement); + })(); + extendPrototype([BaseElement, TransformElement, SVGBaseElement, HierarchyElement, FrameElement, RenderableDOMElement], IImageElement); + IImageElement.prototype.createContent = function() { + var assetPath = this.globalData.getAssetsPath(this.assetData); + this.innerElem = createNS("image"); + this.innerElem.setAttribute("width", this.assetData.w + "px"); + this.innerElem.setAttribute("height", this.assetData.h + "px"); + this.innerElem.setAttribute("preserveAspectRatio", this.assetData.pr || this.globalData.renderConfig.imagePreserveAspectRatio); + this.innerElem.setAttributeNS("http://www.w3.org/1999/xlink", "href", assetPath); + this.layerElement.appendChild(this.innerElem); + }; + IImageElement.prototype.sourceRectAtTime = function() { + return this.sourceRect; + }; + IShapeElement.prototype = { + addShapeToModifiers: function(data2) { + var i; + var len = this.shapeModifiers.length; + for (i = 0;i < len; i += 1) { + this.shapeModifiers[i].addShape(data2); + } + }, + isShapeInAnimatedModifiers: function(data2) { + var i = 0; + var len = this.shapeModifiers.length; + while (i < len) { + if (this.shapeModifiers[i].isAnimatedWithShape(data2)) { + return true; + } + } + return false; + }, + renderModifiers: function() { + if (!this.shapeModifiers.length) { + return; + } + var i; + var len = this.shapes.length; + for (i = 0;i < len; i += 1) { + this.shapes[i].sh.reset(); + } + len = this.shapeModifiers.length; + var shouldBreakProcess; + for (i = len - 1;i >= 0; i -= 1) { + shouldBreakProcess = this.shapeModifiers[i].processShapes(this._isFirstFrame); + if (shouldBreakProcess) { + break; + } + } + }, + searchProcessedElement: function(elem2) { + var elements = this.processedElements; + var i = 0; + var len = elements.length; + while (i < len) { + if (elements[i].elem === elem2) { + return elements[i].pos; + } + i += 1; + } + return 0; + }, + addProcessedElement: function(elem2, pos) { + var elements = this.processedElements; + var i = elements.length; + while (i) { + i -= 1; + if (elements[i].elem === elem2) { + elements[i].pos = pos; + return; + } + } + elements.push(new ProcessedElement(elem2, pos)); + }, + prepareFrame: function(num) { + this.prepareRenderableFrame(num); + this.prepareProperties(num, this.isInRange); + } + }; + const lineCapEnum = { + 1: "butt", + 2: "round", + 3: "square" + }; + const lineJoinEnum = { + 1: "miter", + 2: "round", + 3: "bevel" + }; + SVGShapeData.prototype.setAsAnimated = function() { + this._isAnimated = true; + }; + SVGStyleData.prototype.reset = function() { + this.d = ""; + this._mdf = false; + }; + DashProperty.prototype.getValue = function(forceRender) { + if (this.elem.globalData.frameId === this.frameId && !forceRender) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + this._mdf = this._mdf || forceRender; + if (this._mdf) { + var i = 0; + var len = this.dataProps.length; + if (this.renderer === "svg") { + this.dashStr = ""; + } + for (i = 0;i < len; i += 1) { + if (this.dataProps[i].n !== "o") { + if (this.renderer === "svg") { + this.dashStr += " " + this.dataProps[i].p.v; + } else { + this.dashArray[i] = this.dataProps[i].p.v; + } + } else { + this.dashoffset[0] = this.dataProps[i].p.v; + } + } + } + }; + extendPrototype([DynamicPropertyContainer], DashProperty); + extendPrototype([DynamicPropertyContainer], SVGStrokeStyleData); + extendPrototype([DynamicPropertyContainer], SVGFillStyleData); + extendPrototype([DynamicPropertyContainer], SVGNoStyleData); + GradientProperty.prototype.comparePoints = function(values2, points) { + var i = 0; + var len = this.o.length / 2; + var diff; + while (i < len) { + diff = Math.abs(values2[i * 4] - values2[points * 4 + i * 2]); + if (diff > 0.01) { + return false; + } + i += 1; + } + return true; + }; + GradientProperty.prototype.checkCollapsable = function() { + if (this.o.length / 2 !== this.c.length / 4) { + return false; + } + if (this.data.k.k[0].s) { + var i = 0; + var len = this.data.k.k.length; + while (i < len) { + if (!this.comparePoints(this.data.k.k[i].s, this.data.p)) { + return false; + } + i += 1; + } + } else if (!this.comparePoints(this.data.k.k, this.data.p)) { + return false; + } + return true; + }; + GradientProperty.prototype.getValue = function(forceRender) { + this.prop.getValue(); + this._mdf = false; + this._cmdf = false; + this._omdf = false; + if (this.prop._mdf || forceRender) { + var i; + var len = this.data.p * 4; + var mult; + var val2; + for (i = 0;i < len; i += 1) { + mult = i % 4 === 0 ? 100 : 255; + val2 = Math.round(this.prop.v[i] * mult); + if (this.c[i] !== val2) { + this.c[i] = val2; + this._cmdf = !forceRender; + } + } + if (this.o.length) { + len = this.prop.v.length; + for (i = this.data.p * 4;i < len; i += 1) { + mult = i % 2 === 0 ? 100 : 1; + val2 = i % 2 === 0 ? Math.round(this.prop.v[i] * 100) : this.prop.v[i]; + if (this.o[i - this.data.p * 4] !== val2) { + this.o[i - this.data.p * 4] = val2; + this._omdf = !forceRender; + } + } + } + this._mdf = !forceRender; + } + }; + extendPrototype([DynamicPropertyContainer], GradientProperty); + SVGGradientFillStyleData.prototype.initGradientData = function(elem2, data2, styleOb) { + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, this); + this.s = PropertyFactory.getProp(elem2, data2.s, 1, null, this); + this.e = PropertyFactory.getProp(elem2, data2.e, 1, null, this); + this.h = PropertyFactory.getProp(elem2, data2.h || { k: 0 }, 0, 0.01, this); + this.a = PropertyFactory.getProp(elem2, data2.a || { k: 0 }, 0, degToRads, this); + this.g = new GradientProperty(elem2, data2.g, this); + this.style = styleOb; + this.stops = []; + this.setGradientData(styleOb.pElem, data2); + this.setGradientOpacity(data2, styleOb); + this._isAnimated = !!this._isAnimated; + }; + SVGGradientFillStyleData.prototype.setGradientData = function(pathElement, data2) { + var gradientId = createElementID(); + var gfill = createNS(data2.t === 1 ? "linearGradient" : "radialGradient"); + gfill.setAttribute("id", gradientId); + gfill.setAttribute("spreadMethod", "pad"); + gfill.setAttribute("gradientUnits", "userSpaceOnUse"); + var stops = []; + var stop; + var j2; + var jLen; + jLen = data2.g.p * 4; + for (j2 = 0;j2 < jLen; j2 += 4) { + stop = createNS("stop"); + gfill.appendChild(stop); + stops.push(stop); + } + pathElement.setAttribute(data2.ty === "gf" ? "fill" : "stroke", "url(" + getLocationHref() + "#" + gradientId + ")"); + this.gf = gfill; + this.cst = stops; + }; + SVGGradientFillStyleData.prototype.setGradientOpacity = function(data2, styleOb) { + if (this.g._hasOpacity && !this.g._collapsable) { + var stop; + var j2; + var jLen; + var mask2 = createNS("mask"); + var maskElement = createNS("path"); + mask2.appendChild(maskElement); + var opacityId = createElementID(); + var maskId = createElementID(); + mask2.setAttribute("id", maskId); + var opFill = createNS(data2.t === 1 ? "linearGradient" : "radialGradient"); + opFill.setAttribute("id", opacityId); + opFill.setAttribute("spreadMethod", "pad"); + opFill.setAttribute("gradientUnits", "userSpaceOnUse"); + jLen = data2.g.k.k[0].s ? data2.g.k.k[0].s.length : data2.g.k.k.length; + var stops = this.stops; + for (j2 = data2.g.p * 4;j2 < jLen; j2 += 2) { + stop = createNS("stop"); + stop.setAttribute("stop-color", "rgb(255,255,255)"); + opFill.appendChild(stop); + stops.push(stop); + } + maskElement.setAttribute(data2.ty === "gf" ? "fill" : "stroke", "url(" + getLocationHref() + "#" + opacityId + ")"); + if (data2.ty === "gs") { + maskElement.setAttribute("stroke-linecap", lineCapEnum[data2.lc || 2]); + maskElement.setAttribute("stroke-linejoin", lineJoinEnum[data2.lj || 2]); + if (data2.lj === 1) { + maskElement.setAttribute("stroke-miterlimit", data2.ml); + } + } + this.of = opFill; + this.ms = mask2; + this.ost = stops; + this.maskId = maskId; + styleOb.msElem = maskElement; + } + }; + extendPrototype([DynamicPropertyContainer], SVGGradientFillStyleData); + extendPrototype([SVGGradientFillStyleData, DynamicPropertyContainer], SVGGradientStrokeStyleData); + const buildShapeString = function(pathNodes, length2, closed, mat) { + if (length2 === 0) { + return ""; + } + var _o = pathNodes.o; + var _i = pathNodes.i; + var _v4 = pathNodes.v; + var i; + var shapeString = " M" + mat.applyToPointStringified(_v4[0][0], _v4[0][1]); + for (i = 1;i < length2; i += 1) { + shapeString += " C" + mat.applyToPointStringified(_o[i - 1][0], _o[i - 1][1]) + " " + mat.applyToPointStringified(_i[i][0], _i[i][1]) + " " + mat.applyToPointStringified(_v4[i][0], _v4[i][1]); + } + if (closed && length2) { + shapeString += " C" + mat.applyToPointStringified(_o[i - 1][0], _o[i - 1][1]) + " " + mat.applyToPointStringified(_i[0][0], _i[0][1]) + " " + mat.applyToPointStringified(_v4[0][0], _v4[0][1]); + shapeString += "z"; + } + return shapeString; + }; + const SVGElementsRenderer = function() { + var _identityMatrix3 = new Matrix; + var _matrixHelper = new Matrix; + var ob2 = { + createRenderFunction + }; + function createRenderFunction(data2) { + switch (data2.ty) { + case "fl": + return renderFill; + case "gf": + return renderGradient; + case "gs": + return renderGradientStroke; + case "st": + return renderStroke; + case "sh": + case "el": + case "rc": + case "sr": + return renderPath; + case "tr": + return renderContentTransform; + case "no": + return renderNoop; + default: + return null; + } + } + function renderContentTransform(styleData, itemData, isFirstFrame) { + if (isFirstFrame || itemData.transform.op._mdf) { + itemData.transform.container.setAttribute("opacity", itemData.transform.op.v); + } + if (isFirstFrame || itemData.transform.mProps._mdf) { + itemData.transform.container.setAttribute("transform", itemData.transform.mProps.v.to2dCSS()); + } + } + function renderNoop() { + } + function renderPath(styleData, itemData, isFirstFrame) { + var j2; + var jLen; + var pathStringTransformed; + var redraw; + var pathNodes; + var l2; + var lLen = itemData.styles.length; + var lvl = itemData.lvl; + var paths; + var mat; + var props; + var iterations; + var k2; + for (l2 = 0;l2 < lLen; l2 += 1) { + redraw = itemData.sh._mdf || isFirstFrame; + if (itemData.styles[l2].lvl < lvl) { + mat = _matrixHelper.reset(); + iterations = lvl - itemData.styles[l2].lvl; + k2 = itemData.transformers.length - 1; + while (!redraw && iterations > 0) { + redraw = itemData.transformers[k2].mProps._mdf || redraw; + iterations -= 1; + k2 -= 1; + } + if (redraw) { + iterations = lvl - itemData.styles[l2].lvl; + k2 = itemData.transformers.length - 1; + while (iterations > 0) { + props = itemData.transformers[k2].mProps.v.props; + mat.transform(props[0], props[1], props[2], props[3], props[4], props[5], props[6], props[7], props[8], props[9], props[10], props[11], props[12], props[13], props[14], props[15]); + iterations -= 1; + k2 -= 1; + } + } + } else { + mat = _identityMatrix3; + } + paths = itemData.sh.paths; + jLen = paths._length; + if (redraw) { + pathStringTransformed = ""; + for (j2 = 0;j2 < jLen; j2 += 1) { + pathNodes = paths.shapes[j2]; + if (pathNodes && pathNodes._length) { + pathStringTransformed += buildShapeString(pathNodes, pathNodes._length, pathNodes.c, mat); + } + } + itemData.caches[l2] = pathStringTransformed; + } else { + pathStringTransformed = itemData.caches[l2]; + } + itemData.styles[l2].d += styleData.hd === true ? "" : pathStringTransformed; + itemData.styles[l2]._mdf = redraw || itemData.styles[l2]._mdf; + } + } + function renderFill(styleData, itemData, isFirstFrame) { + var styleElem = itemData.style; + if (itemData.c._mdf || isFirstFrame) { + styleElem.pElem.setAttribute("fill", "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"); + } + if (itemData.o._mdf || isFirstFrame) { + styleElem.pElem.setAttribute("fill-opacity", itemData.o.v); + } + } + function renderGradientStroke(styleData, itemData, isFirstFrame) { + renderGradient(styleData, itemData, isFirstFrame); + renderStroke(styleData, itemData, isFirstFrame); + } + function renderGradient(styleData, itemData, isFirstFrame) { + var gfill = itemData.gf; + var hasOpacity = itemData.g._hasOpacity; + var pt1 = itemData.s.v; + var pt2 = itemData.e.v; + if (itemData.o._mdf || isFirstFrame) { + var attr = styleData.ty === "gf" ? "fill-opacity" : "stroke-opacity"; + itemData.style.pElem.setAttribute(attr, itemData.o.v); + } + if (itemData.s._mdf || isFirstFrame) { + var attr1 = styleData.t === 1 ? "x1" : "cx"; + var attr2 = attr1 === "x1" ? "y1" : "cy"; + gfill.setAttribute(attr1, pt1[0]); + gfill.setAttribute(attr2, pt1[1]); + if (hasOpacity && !itemData.g._collapsable) { + itemData.of.setAttribute(attr1, pt1[0]); + itemData.of.setAttribute(attr2, pt1[1]); + } + } + var stops; + var i; + var len; + var stop; + if (itemData.g._cmdf || isFirstFrame) { + stops = itemData.cst; + var cValues = itemData.g.c; + len = stops.length; + for (i = 0;i < len; i += 1) { + stop = stops[i]; + stop.setAttribute("offset", cValues[i * 4] + "%"); + stop.setAttribute("stop-color", "rgb(" + cValues[i * 4 + 1] + "," + cValues[i * 4 + 2] + "," + cValues[i * 4 + 3] + ")"); + } + } + if (hasOpacity && (itemData.g._omdf || isFirstFrame)) { + var oValues = itemData.g.o; + if (itemData.g._collapsable) { + stops = itemData.cst; + } else { + stops = itemData.ost; + } + len = stops.length; + for (i = 0;i < len; i += 1) { + stop = stops[i]; + if (!itemData.g._collapsable) { + stop.setAttribute("offset", oValues[i * 2] + "%"); + } + stop.setAttribute("stop-opacity", oValues[i * 2 + 1]); + } + } + if (styleData.t === 1) { + if (itemData.e._mdf || isFirstFrame) { + gfill.setAttribute("x2", pt2[0]); + gfill.setAttribute("y2", pt2[1]); + if (hasOpacity && !itemData.g._collapsable) { + itemData.of.setAttribute("x2", pt2[0]); + itemData.of.setAttribute("y2", pt2[1]); + } + } + } else { + var rad; + if (itemData.s._mdf || itemData.e._mdf || isFirstFrame) { + rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); + gfill.setAttribute("r", rad); + if (hasOpacity && !itemData.g._collapsable) { + itemData.of.setAttribute("r", rad); + } + } + if (itemData.e._mdf || itemData.h._mdf || itemData.a._mdf || isFirstFrame) { + if (!rad) { + rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); + } + var ang = Math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]); + var percent = itemData.h.v; + if (percent >= 1) { + percent = 0.99; + } else if (percent <= -1) { + percent = -0.99; + } + var dist = rad * percent; + var x2 = Math.cos(ang + itemData.a.v) * dist + pt1[0]; + var y = Math.sin(ang + itemData.a.v) * dist + pt1[1]; + gfill.setAttribute("fx", x2); + gfill.setAttribute("fy", y); + if (hasOpacity && !itemData.g._collapsable) { + itemData.of.setAttribute("fx", x2); + itemData.of.setAttribute("fy", y); + } + } + } + } + function renderStroke(styleData, itemData, isFirstFrame) { + var styleElem = itemData.style; + var d = itemData.d; + if (d && (d._mdf || isFirstFrame) && d.dashStr) { + styleElem.pElem.setAttribute("stroke-dasharray", d.dashStr); + styleElem.pElem.setAttribute("stroke-dashoffset", d.dashoffset[0]); + } + if (itemData.c && (itemData.c._mdf || isFirstFrame)) { + styleElem.pElem.setAttribute("stroke", "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"); + } + if (itemData.o._mdf || isFirstFrame) { + styleElem.pElem.setAttribute("stroke-opacity", itemData.o.v); + } + if (itemData.w._mdf || isFirstFrame) { + styleElem.pElem.setAttribute("stroke-width", itemData.w.v); + if (styleElem.msElem) { + styleElem.msElem.setAttribute("stroke-width", itemData.w.v); + } + } + } + return ob2; + }(); + extendPrototype([BaseElement, TransformElement, SVGBaseElement, IShapeElement, HierarchyElement, FrameElement, RenderableDOMElement], SVGShapeElement); + SVGShapeElement.prototype.initSecondaryElement = function() { + }; + SVGShapeElement.prototype.identityMatrix = new Matrix; + SVGShapeElement.prototype.buildExpressionInterface = function() { + }; + SVGShapeElement.prototype.createContent = function() { + this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, this.layerElement, 0, [], true); + this.filterUniqueShapes(); + }; + SVGShapeElement.prototype.filterUniqueShapes = function() { + var i; + var len = this.shapes.length; + var shape; + var j2; + var jLen = this.stylesList.length; + var style; + var tempShapes = []; + var areAnimated = false; + for (j2 = 0;j2 < jLen; j2 += 1) { + style = this.stylesList[j2]; + areAnimated = false; + tempShapes.length = 0; + for (i = 0;i < len; i += 1) { + shape = this.shapes[i]; + if (shape.styles.indexOf(style) !== -1) { + tempShapes.push(shape); + areAnimated = shape._isAnimated || areAnimated; + } + } + if (tempShapes.length > 1 && areAnimated) { + this.setShapesAsAnimated(tempShapes); + } + } + }; + SVGShapeElement.prototype.setShapesAsAnimated = function(shapes) { + var i; + var len = shapes.length; + for (i = 0;i < len; i += 1) { + shapes[i].setAsAnimated(); + } + }; + SVGShapeElement.prototype.createStyleElement = function(data2, level) { + var elementData; + var styleOb = new SVGStyleData(data2, level); + var pathElement = styleOb.pElem; + if (data2.ty === "st") { + elementData = new SVGStrokeStyleData(this, data2, styleOb); + } else if (data2.ty === "fl") { + elementData = new SVGFillStyleData(this, data2, styleOb); + } else if (data2.ty === "gf" || data2.ty === "gs") { + var GradientConstructor = data2.ty === "gf" ? SVGGradientFillStyleData : SVGGradientStrokeStyleData; + elementData = new GradientConstructor(this, data2, styleOb); + this.globalData.defs.appendChild(elementData.gf); + if (elementData.maskId) { + this.globalData.defs.appendChild(elementData.ms); + this.globalData.defs.appendChild(elementData.of); + pathElement.setAttribute("mask", "url(" + getLocationHref() + "#" + elementData.maskId + ")"); + } + } else if (data2.ty === "no") { + elementData = new SVGNoStyleData(this, data2, styleOb); + } + if (data2.ty === "st" || data2.ty === "gs") { + pathElement.setAttribute("stroke-linecap", lineCapEnum[data2.lc || 2]); + pathElement.setAttribute("stroke-linejoin", lineJoinEnum[data2.lj || 2]); + pathElement.setAttribute("fill-opacity", "0"); + if (data2.lj === 1) { + pathElement.setAttribute("stroke-miterlimit", data2.ml); + } + } + if (data2.r === 2) { + pathElement.setAttribute("fill-rule", "evenodd"); + } + if (data2.ln) { + pathElement.setAttribute("id", data2.ln); + } + if (data2.cl) { + pathElement.setAttribute("class", data2.cl); + } + if (data2.bm) { + pathElement.style["mix-blend-mode"] = getBlendMode(data2.bm); + } + this.stylesList.push(styleOb); + this.addToAnimatedContents(data2, elementData); + return elementData; + }; + SVGShapeElement.prototype.createGroupElement = function(data2) { + var elementData = new ShapeGroupData; + if (data2.ln) { + elementData.gr.setAttribute("id", data2.ln); + } + if (data2.cl) { + elementData.gr.setAttribute("class", data2.cl); + } + if (data2.bm) { + elementData.gr.style["mix-blend-mode"] = getBlendMode(data2.bm); + } + return elementData; + }; + SVGShapeElement.prototype.createTransformElement = function(data2, container) { + var transformProperty = TransformPropertyFactory.getTransformProperty(this, data2, this); + var elementData = new SVGTransformData(transformProperty, transformProperty.o, container); + this.addToAnimatedContents(data2, elementData); + return elementData; + }; + SVGShapeElement.prototype.createShapeElement = function(data2, ownTransformers, level) { + var ty = 4; + if (data2.ty === "rc") { + ty = 5; + } else if (data2.ty === "el") { + ty = 6; + } else if (data2.ty === "sr") { + ty = 7; + } + var shapeProperty = ShapePropertyFactory.getShapeProp(this, data2, ty, this); + var elementData = new SVGShapeData(ownTransformers, level, shapeProperty); + this.shapes.push(elementData); + this.addShapeToModifiers(elementData); + this.addToAnimatedContents(data2, elementData); + return elementData; + }; + SVGShapeElement.prototype.addToAnimatedContents = function(data2, element) { + var i = 0; + var len = this.animatedContents.length; + while (i < len) { + if (this.animatedContents[i].element === element) { + return; + } + i += 1; + } + this.animatedContents.push({ + fn: SVGElementsRenderer.createRenderFunction(data2), + element, + data: data2 + }); + }; + SVGShapeElement.prototype.setElementStyles = function(elementData) { + var arr = elementData.styles; + var j2; + var jLen = this.stylesList.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (!this.stylesList[j2].closed) { + arr.push(this.stylesList[j2]); + } + } + }; + SVGShapeElement.prototype.reloadShapes = function() { + this._isFirstFrame = true; + var i; + var len = this.itemsData.length; + for (i = 0;i < len; i += 1) { + this.prevViewData[i] = this.itemsData[i]; + } + this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, this.layerElement, 0, [], true); + this.filterUniqueShapes(); + len = this.dynamicProperties.length; + for (i = 0;i < len; i += 1) { + this.dynamicProperties[i].getValue(); + } + this.renderModifiers(); + }; + SVGShapeElement.prototype.searchShapes = function(arr, itemsData, prevViewData, container, level, transformers, render) { + var ownTransformers = [].concat(transformers); + var i; + var len = arr.length - 1; + var j2; + var jLen; + var ownStyles = []; + var ownModifiers = []; + var currentTransform; + var modifier; + var processedPos; + for (i = len;i >= 0; i -= 1) { + processedPos = this.searchProcessedElement(arr[i]); + if (!processedPos) { + arr[i]._render = render; + } else { + itemsData[i] = prevViewData[processedPos - 1]; + } + if (arr[i].ty === "fl" || arr[i].ty === "st" || arr[i].ty === "gf" || arr[i].ty === "gs" || arr[i].ty === "no") { + if (!processedPos) { + itemsData[i] = this.createStyleElement(arr[i], level); + } else { + itemsData[i].style.closed = false; + } + if (arr[i]._render) { + if (itemsData[i].style.pElem.parentNode !== container) { + container.appendChild(itemsData[i].style.pElem); + } + } + ownStyles.push(itemsData[i].style); + } else if (arr[i].ty === "gr") { + if (!processedPos) { + itemsData[i] = this.createGroupElement(arr[i]); + } else { + jLen = itemsData[i].it.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + itemsData[i].prevViewData[j2] = itemsData[i].it[j2]; + } + } + this.searchShapes(arr[i].it, itemsData[i].it, itemsData[i].prevViewData, itemsData[i].gr, level + 1, ownTransformers, render); + if (arr[i]._render) { + if (itemsData[i].gr.parentNode !== container) { + container.appendChild(itemsData[i].gr); + } + } + } else if (arr[i].ty === "tr") { + if (!processedPos) { + itemsData[i] = this.createTransformElement(arr[i], container); + } + currentTransform = itemsData[i].transform; + ownTransformers.push(currentTransform); + } else if (arr[i].ty === "sh" || arr[i].ty === "rc" || arr[i].ty === "el" || arr[i].ty === "sr") { + if (!processedPos) { + itemsData[i] = this.createShapeElement(arr[i], ownTransformers, level); + } + this.setElementStyles(itemsData[i]); + } else if (arr[i].ty === "tm" || arr[i].ty === "rd" || arr[i].ty === "ms" || arr[i].ty === "pb") { + if (!processedPos) { + modifier = ShapeModifiers.getModifier(arr[i].ty); + modifier.init(this, arr[i]); + itemsData[i] = modifier; + this.shapeModifiers.push(modifier); + } else { + modifier = itemsData[i]; + modifier.closed = false; + } + ownModifiers.push(modifier); + } else if (arr[i].ty === "rp") { + if (!processedPos) { + modifier = ShapeModifiers.getModifier(arr[i].ty); + itemsData[i] = modifier; + modifier.init(this, arr, i, itemsData); + this.shapeModifiers.push(modifier); + render = false; + } else { + modifier = itemsData[i]; + modifier.closed = true; + } + ownModifiers.push(modifier); + } + this.addProcessedElement(arr[i], i + 1); + } + len = ownStyles.length; + for (i = 0;i < len; i += 1) { + ownStyles[i].closed = true; + } + len = ownModifiers.length; + for (i = 0;i < len; i += 1) { + ownModifiers[i].closed = true; + } + }; + SVGShapeElement.prototype.renderInnerContent = function() { + this.renderModifiers(); + var i; + var len = this.stylesList.length; + for (i = 0;i < len; i += 1) { + this.stylesList[i].reset(); + } + this.renderShape(); + for (i = 0;i < len; i += 1) { + if (this.stylesList[i]._mdf || this._isFirstFrame) { + if (this.stylesList[i].msElem) { + this.stylesList[i].msElem.setAttribute("d", this.stylesList[i].d); + this.stylesList[i].d = "M0 0" + this.stylesList[i].d; + } + this.stylesList[i].pElem.setAttribute("d", this.stylesList[i].d || "M0 0"); + } + } + }; + SVGShapeElement.prototype.renderShape = function() { + var i; + var len = this.animatedContents.length; + var animatedContent; + for (i = 0;i < len; i += 1) { + animatedContent = this.animatedContents[i]; + if ((this._isFirstFrame || animatedContent.element._isAnimated) && animatedContent.data !== true) { + animatedContent.fn(animatedContent.data, animatedContent.element, this._isFirstFrame); + } + } + }; + SVGShapeElement.prototype.destroy = function() { + this.destroyBaseElement(); + this.shapesData = null; + this.itemsData = null; + }; + LetterProps.prototype.update = function(o, sw, sc, fc, m, p) { + this._mdf.o = false; + this._mdf.sw = false; + this._mdf.sc = false; + this._mdf.fc = false; + this._mdf.m = false; + this._mdf.p = false; + var updated = false; + if (this.o !== o) { + this.o = o; + this._mdf.o = true; + updated = true; + } + if (this.sw !== sw) { + this.sw = sw; + this._mdf.sw = true; + updated = true; + } + if (this.sc !== sc) { + this.sc = sc; + this._mdf.sc = true; + updated = true; + } + if (this.fc !== fc) { + this.fc = fc; + this._mdf.fc = true; + updated = true; + } + if (this.m !== m) { + this.m = m; + this._mdf.m = true; + updated = true; + } + if (p.length && (this.p[0] !== p[0] || this.p[1] !== p[1] || this.p[4] !== p[4] || this.p[5] !== p[5] || this.p[12] !== p[12] || this.p[13] !== p[13])) { + this.p = p; + this._mdf.p = true; + updated = true; + } + return updated; + }; + TextProperty.prototype.defaultBoxWidth = [0, 0]; + TextProperty.prototype.copyData = function(obj, data2) { + for (var s in data2) { + if (Object.prototype.hasOwnProperty.call(data2, s)) { + obj[s] = data2[s]; + } + } + return obj; + }; + TextProperty.prototype.setCurrentData = function(data2) { + if (!data2.__complete) { + this.completeTextData(data2); + } + this.currentData = data2; + this.currentData.boxWidth = this.currentData.boxWidth || this.defaultBoxWidth; + this._mdf = true; + }; + TextProperty.prototype.searchProperty = function() { + return this.searchKeyframes(); + }; + TextProperty.prototype.searchKeyframes = function() { + this.kf = this.data.d.k.length > 1; + if (this.kf) { + this.addEffect(this.getKeyframeValue.bind(this)); + } + return this.kf; + }; + TextProperty.prototype.addEffect = function(effectFunction) { + this.effectsSequence.push(effectFunction); + this.elem.addDynamicProperty(this); + }; + TextProperty.prototype.getValue = function(_finalValue) { + if ((this.elem.globalData.frameId === this.frameId || !this.effectsSequence.length) && !_finalValue) { + return; + } + this.currentData.t = this.data.d.k[this.keysIndex].s.t; + var currentValue = this.currentData; + var currentIndex = this.keysIndex; + if (this.lock) { + this.setCurrentData(this.currentData); + return; + } + this.lock = true; + this._mdf = false; + var i; + var len = this.effectsSequence.length; + var finalValue = _finalValue || this.data.d.k[this.keysIndex].s; + for (i = 0;i < len; i += 1) { + if (currentIndex !== this.keysIndex) { + finalValue = this.effectsSequence[i](finalValue, finalValue.t); + } else { + finalValue = this.effectsSequence[i](this.currentData, finalValue.t); + } + } + if (currentValue !== finalValue) { + this.setCurrentData(finalValue); + } + this.v = this.currentData; + this.pv = this.v; + this.lock = false; + this.frameId = this.elem.globalData.frameId; + }; + TextProperty.prototype.getKeyframeValue = function() { + var textKeys = this.data.d.k; + var frameNum = this.elem.comp.renderedFrame; + var i = 0; + var len = textKeys.length; + while (i <= len - 1) { + if (i === len - 1 || textKeys[i + 1].t > frameNum) { + break; + } + i += 1; + } + if (this.keysIndex !== i) { + this.keysIndex = i; + } + return this.data.d.k[this.keysIndex].s; + }; + TextProperty.prototype.buildFinalText = function(text2) { + var charactersArray = []; + var i = 0; + var len = text2.length; + var charCode; + var secondCharCode; + var shouldCombine = false; + while (i < len) { + charCode = text2.charCodeAt(i); + if (FontManager.isCombinedCharacter(charCode)) { + charactersArray[charactersArray.length - 1] += text2.charAt(i); + } else if (charCode >= 55296 && charCode <= 56319) { + secondCharCode = text2.charCodeAt(i + 1); + if (secondCharCode >= 56320 && secondCharCode <= 57343) { + if (shouldCombine || FontManager.isModifier(charCode, secondCharCode)) { + charactersArray[charactersArray.length - 1] += text2.substr(i, 2); + shouldCombine = false; + } else { + charactersArray.push(text2.substr(i, 2)); + } + i += 1; + } else { + charactersArray.push(text2.charAt(i)); + } + } else if (charCode > 56319) { + secondCharCode = text2.charCodeAt(i + 1); + if (FontManager.isZeroWidthJoiner(charCode, secondCharCode)) { + shouldCombine = true; + charactersArray[charactersArray.length - 1] += text2.substr(i, 2); + i += 1; + } else { + charactersArray.push(text2.charAt(i)); + } + } else if (FontManager.isZeroWidthJoiner(charCode)) { + charactersArray[charactersArray.length - 1] += text2.charAt(i); + shouldCombine = true; + } else { + charactersArray.push(text2.charAt(i)); + } + i += 1; + } + return charactersArray; + }; + TextProperty.prototype.completeTextData = function(documentData) { + documentData.__complete = true; + var fontManager = this.elem.globalData.fontManager; + var data2 = this.data; + var letters = []; + var i; + var len; + var newLineFlag; + var index2 = 0; + var val2; + var anchorGrouping = data2.m.g; + var currentSize = 0; + var currentPos = 0; + var currentLine = 0; + var lineWidths = []; + var lineWidth = 0; + var maxLineWidth = 0; + var j2; + var jLen; + var fontData = fontManager.getFontByName(documentData.f); + var charData; + var cLength = 0; + var fontProps = getFontProperties(fontData); + documentData.fWeight = fontProps.weight; + documentData.fStyle = fontProps.style; + documentData.finalSize = documentData.s; + documentData.finalText = this.buildFinalText(documentData.t); + len = documentData.finalText.length; + documentData.finalLineHeight = documentData.lh; + var trackingOffset = documentData.tr / 1000 * documentData.finalSize; + var charCode; + if (documentData.sz) { + var flag = true; + var boxWidth = documentData.sz[0]; + var boxHeight = documentData.sz[1]; + var currentHeight; + var finalText; + while (flag) { + finalText = this.buildFinalText(documentData.t); + currentHeight = 0; + lineWidth = 0; + len = finalText.length; + trackingOffset = documentData.tr / 1000 * documentData.finalSize; + var lastSpaceIndex = -1; + for (i = 0;i < len; i += 1) { + charCode = finalText[i].charCodeAt(0); + newLineFlag = false; + if (finalText[i] === " ") { + lastSpaceIndex = i; + } else if (charCode === 13 || charCode === 3) { + lineWidth = 0; + newLineFlag = true; + currentHeight += documentData.finalLineHeight || documentData.finalSize * 1.2; + } + if (fontManager.chars) { + charData = fontManager.getCharData(finalText[i], fontData.fStyle, fontData.fFamily); + cLength = newLineFlag ? 0 : charData.w * documentData.finalSize / 100; + } else { + cLength = fontManager.measureText(finalText[i], documentData.f, documentData.finalSize); + } + if (lineWidth + cLength > boxWidth && finalText[i] !== " ") { + if (lastSpaceIndex === -1) { + len += 1; + } else { + i = lastSpaceIndex; + } + currentHeight += documentData.finalLineHeight || documentData.finalSize * 1.2; + finalText.splice(i, lastSpaceIndex === i ? 1 : 0, "\r"); + lastSpaceIndex = -1; + lineWidth = 0; + } else { + lineWidth += cLength; + lineWidth += trackingOffset; + } + } + currentHeight += fontData.ascent * documentData.finalSize / 100; + if (this.canResize && documentData.finalSize > this.minimumFontSize && boxHeight < currentHeight) { + documentData.finalSize -= 1; + documentData.finalLineHeight = documentData.finalSize * documentData.lh / documentData.s; + } else { + documentData.finalText = finalText; + len = documentData.finalText.length; + flag = false; + } + } + } + lineWidth = -trackingOffset; + cLength = 0; + var uncollapsedSpaces = 0; + var currentChar; + for (i = 0;i < len; i += 1) { + newLineFlag = false; + currentChar = documentData.finalText[i]; + charCode = currentChar.charCodeAt(0); + if (charCode === 13 || charCode === 3) { + uncollapsedSpaces = 0; + lineWidths.push(lineWidth); + maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth; + lineWidth = -2 * trackingOffset; + val2 = ""; + newLineFlag = true; + currentLine += 1; + } else { + val2 = currentChar; + } + if (fontManager.chars) { + charData = fontManager.getCharData(currentChar, fontData.fStyle, fontManager.getFontByName(documentData.f).fFamily); + cLength = newLineFlag ? 0 : charData.w * documentData.finalSize / 100; + } else { + cLength = fontManager.measureText(val2, documentData.f, documentData.finalSize); + } + if (currentChar === " ") { + uncollapsedSpaces += cLength + trackingOffset; + } else { + lineWidth += cLength + trackingOffset + uncollapsedSpaces; + uncollapsedSpaces = 0; + } + letters.push({ + l: cLength, + an: cLength, + add: currentSize, + n: newLineFlag, + anIndexes: [], + val: val2, + line: currentLine, + animatorJustifyOffset: 0 + }); + if (anchorGrouping == 2) { + currentSize += cLength; + if (val2 === "" || val2 === " " || i === len - 1) { + if (val2 === "" || val2 === " ") { + currentSize -= cLength; + } + while (currentPos <= i) { + letters[currentPos].an = currentSize; + letters[currentPos].ind = index2; + letters[currentPos].extra = cLength; + currentPos += 1; + } + index2 += 1; + currentSize = 0; + } + } else if (anchorGrouping == 3) { + currentSize += cLength; + if (val2 === "" || i === len - 1) { + if (val2 === "") { + currentSize -= cLength; + } + while (currentPos <= i) { + letters[currentPos].an = currentSize; + letters[currentPos].ind = index2; + letters[currentPos].extra = cLength; + currentPos += 1; + } + currentSize = 0; + index2 += 1; + } + } else { + letters[index2].ind = index2; + letters[index2].extra = 0; + index2 += 1; + } + } + documentData.l = letters; + maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth; + lineWidths.push(lineWidth); + if (documentData.sz) { + documentData.boxWidth = documentData.sz[0]; + documentData.justifyOffset = 0; + } else { + documentData.boxWidth = maxLineWidth; + switch (documentData.j) { + case 1: + documentData.justifyOffset = -documentData.boxWidth; + break; + case 2: + documentData.justifyOffset = -documentData.boxWidth / 2; + break; + default: + documentData.justifyOffset = 0; + } + } + documentData.lineWidths = lineWidths; + var animators = data2.a; + var animatorData; + var letterData; + jLen = animators.length; + var based; + var ind; + var indexes = []; + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorData = animators[j2]; + if (animatorData.a.sc) { + documentData.strokeColorAnim = true; + } + if (animatorData.a.sw) { + documentData.strokeWidthAnim = true; + } + if (animatorData.a.fc || animatorData.a.fh || animatorData.a.fs || animatorData.a.fb) { + documentData.fillColorAnim = true; + } + ind = 0; + based = animatorData.s.b; + for (i = 0;i < len; i += 1) { + letterData = letters[i]; + letterData.anIndexes[j2] = ind; + if (based == 1 && letterData.val !== "" || based == 2 && letterData.val !== "" && letterData.val !== " " || based == 3 && (letterData.n || letterData.val == " " || i == len - 1) || based == 4 && (letterData.n || i == len - 1)) { + if (animatorData.s.rn === 1) { + indexes.push(ind); + } + ind += 1; + } + } + data2.a[j2].s.totalChars = ind; + var currentInd = -1; + var newInd; + if (animatorData.s.rn === 1) { + for (i = 0;i < len; i += 1) { + letterData = letters[i]; + if (currentInd != letterData.anIndexes[j2]) { + currentInd = letterData.anIndexes[j2]; + newInd = indexes.splice(Math.floor(Math.random() * indexes.length), 1)[0]; + } + letterData.anIndexes[j2] = newInd; + } + } + } + documentData.yOffset = documentData.finalLineHeight || documentData.finalSize * 1.2; + documentData.ls = documentData.ls || 0; + documentData.ascent = fontData.ascent * documentData.finalSize / 100; + }; + TextProperty.prototype.updateDocumentData = function(newData, index2) { + index2 = index2 === undefined ? this.keysIndex : index2; + var dData = this.copyData({}, this.data.d.k[index2].s); + dData = this.copyData(dData, newData); + this.data.d.k[index2].s = dData; + this.recalculate(index2); + this.elem.addDynamicProperty(this); + }; + TextProperty.prototype.recalculate = function(index2) { + var dData = this.data.d.k[index2].s; + dData.__complete = false; + this.keysIndex = 0; + this._isFirstFrame = true; + this.getValue(dData); + }; + TextProperty.prototype.canResizeFont = function(_canResize) { + this.canResize = _canResize; + this.recalculate(this.keysIndex); + this.elem.addDynamicProperty(this); + }; + TextProperty.prototype.setMinimumFontSize = function(_fontValue) { + this.minimumFontSize = Math.floor(_fontValue) || 1; + this.recalculate(this.keysIndex); + this.elem.addDynamicProperty(this); + }; + const TextSelectorProp = function() { + var max = Math.max; + var min = Math.min; + var floor = Math.floor; + function TextSelectorPropFactory(elem2, data2) { + this._currentTextLength = -1; + this.k = false; + this.data = data2; + this.elem = elem2; + this.comp = elem2.comp; + this.finalS = 0; + this.finalE = 0; + this.initDynamicPropertyContainer(elem2); + this.s = PropertyFactory.getProp(elem2, data2.s || { k: 0 }, 0, 0, this); + if ("e" in data2) { + this.e = PropertyFactory.getProp(elem2, data2.e, 0, 0, this); + } else { + this.e = { v: 100 }; + } + this.o = PropertyFactory.getProp(elem2, data2.o || { k: 0 }, 0, 0, this); + this.xe = PropertyFactory.getProp(elem2, data2.xe || { k: 0 }, 0, 0, this); + this.ne = PropertyFactory.getProp(elem2, data2.ne || { k: 0 }, 0, 0, this); + this.sm = PropertyFactory.getProp(elem2, data2.sm || { k: 100 }, 0, 0, this); + this.a = PropertyFactory.getProp(elem2, data2.a, 0, 0.01, this); + if (!this.dynamicProperties.length) { + this.getValue(); + } + } + TextSelectorPropFactory.prototype = { + getMult: function(ind) { + if (this._currentTextLength !== this.elem.textProperty.currentData.l.length) { + this.getValue(); + } + var x1 = 0; + var y1 = 0; + var x2 = 1; + var y2 = 1; + if (this.ne.v > 0) { + x1 = this.ne.v / 100; + } else { + y1 = -this.ne.v / 100; + } + if (this.xe.v > 0) { + x2 = 1 - this.xe.v / 100; + } else { + y2 = 1 + this.xe.v / 100; + } + var easer = BezierFactory.getBezierEasing(x1, y1, x2, y2).get; + var mult = 0; + var s = this.finalS; + var e = this.finalE; + var type = this.data.sh; + if (type === 2) { + if (e === s) { + mult = ind >= e ? 1 : 0; + } else { + mult = max(0, min(0.5 / (e - s) + (ind - s) / (e - s), 1)); + } + mult = easer(mult); + } else if (type === 3) { + if (e === s) { + mult = ind >= e ? 0 : 1; + } else { + mult = 1 - max(0, min(0.5 / (e - s) + (ind - s) / (e - s), 1)); + } + mult = easer(mult); + } else if (type === 4) { + if (e === s) { + mult = 0; + } else { + mult = max(0, min(0.5 / (e - s) + (ind - s) / (e - s), 1)); + if (mult < 0.5) { + mult *= 2; + } else { + mult = 1 - 2 * (mult - 0.5); + } + } + mult = easer(mult); + } else if (type === 5) { + if (e === s) { + mult = 0; + } else { + var tot = e - s; + ind = min(max(0, ind + 0.5 - s), e - s); + var x3 = -tot / 2 + ind; + var a = tot / 2; + mult = Math.sqrt(1 - x3 * x3 / (a * a)); + } + mult = easer(mult); + } else if (type === 6) { + if (e === s) { + mult = 0; + } else { + ind = min(max(0, ind + 0.5 - s), e - s); + mult = (1 + Math.cos(Math.PI + Math.PI * 2 * ind / (e - s))) / 2; + } + mult = easer(mult); + } else { + if (ind >= floor(s)) { + if (ind - s < 0) { + mult = max(0, min(min(e, 1) - (s - ind), 1)); + } else { + mult = max(0, min(e - ind, 1)); + } + } + mult = easer(mult); + } + if (this.sm.v !== 100) { + var smoothness = this.sm.v * 0.01; + if (smoothness === 0) { + smoothness = 0.00000001; + } + var threshold = 0.5 - smoothness * 0.5; + if (mult < threshold) { + mult = 0; + } else { + mult = (mult - threshold) / smoothness; + if (mult > 1) { + mult = 1; + } + } + } + return mult * this.a.v; + }, + getValue: function(newCharsFlag) { + this.iterateDynamicProperties(); + this._mdf = newCharsFlag || this._mdf; + this._currentTextLength = this.elem.textProperty.currentData.l.length || 0; + if (newCharsFlag && this.data.r === 2) { + this.e.v = this._currentTextLength; + } + var divisor = this.data.r === 2 ? 1 : 100 / this.data.totalChars; + var o = this.o.v / divisor; + var s = this.s.v / divisor + o; + var e = this.e.v / divisor + o; + if (s > e) { + var _s = s; + s = e; + e = _s; + } + this.finalS = s; + this.finalE = e; + } + }; + extendPrototype([DynamicPropertyContainer], TextSelectorPropFactory); + function getTextSelectorProp(elem2, data2, arr) { + return new TextSelectorPropFactory(elem2, data2, arr); + } + return { + getTextSelectorProp + }; + }(); + TextAnimatorProperty.prototype.searchProperties = function() { + var i; + var len = this._textData.a.length; + var animatorProps; + var getProp = PropertyFactory.getProp; + for (i = 0;i < len; i += 1) { + animatorProps = this._textData.a[i]; + this._animatorsData[i] = new TextAnimatorDataProperty(this._elem, animatorProps, this); + } + if (this._textData.p && "m" in this._textData.p) { + this._pathData = { + a: getProp(this._elem, this._textData.p.a, 0, 0, this), + f: getProp(this._elem, this._textData.p.f, 0, 0, this), + l: getProp(this._elem, this._textData.p.l, 0, 0, this), + r: getProp(this._elem, this._textData.p.r, 0, 0, this), + p: getProp(this._elem, this._textData.p.p, 0, 0, this), + m: this._elem.maskManager.getMaskProperty(this._textData.p.m) + }; + this._hasMaskedPath = true; + } else { + this._hasMaskedPath = false; + } + this._moreOptions.alignment = getProp(this._elem, this._textData.m.a, 1, 0, this); + }; + TextAnimatorProperty.prototype.getMeasures = function(documentData, lettersChangedFlag) { + this.lettersChangedFlag = lettersChangedFlag; + if (!this._mdf && !this._isFirstFrame && !lettersChangedFlag && (!this._hasMaskedPath || !this._pathData.m._mdf)) { + return; + } + this._isFirstFrame = false; + var alignment = this._moreOptions.alignment.v; + var animators = this._animatorsData; + var textData = this._textData; + var matrixHelper = this.mHelper; + var renderType = this._renderType; + var renderedLettersCount = this.renderedLetters.length; + var xPos; + var yPos; + var i; + var len; + var letters = documentData.l; + var pathInfo; + var currentLength; + var currentPoint; + var segmentLength; + var flag; + var pointInd; + var segmentInd; + var prevPoint; + var points; + var segments; + var partialLength; + var totalLength; + var perc; + var tanAngle; + var mask2; + if (this._hasMaskedPath) { + mask2 = this._pathData.m; + if (!this._pathData.n || this._pathData._mdf) { + var paths = mask2.v; + if (this._pathData.r.v) { + paths = paths.reverse(); + } + pathInfo = { + tLength: 0, + segments: [] + }; + len = paths._length - 1; + var bezierData; + totalLength = 0; + for (i = 0;i < len; i += 1) { + bezierData = bez.buildBezierData(paths.v[i], paths.v[i + 1], [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]], [paths.i[i + 1][0] - paths.v[i + 1][0], paths.i[i + 1][1] - paths.v[i + 1][1]]); + pathInfo.tLength += bezierData.segmentLength; + pathInfo.segments.push(bezierData); + totalLength += bezierData.segmentLength; + } + i = len; + if (mask2.v.c) { + bezierData = bez.buildBezierData(paths.v[i], paths.v[0], [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]], [paths.i[0][0] - paths.v[0][0], paths.i[0][1] - paths.v[0][1]]); + pathInfo.tLength += bezierData.segmentLength; + pathInfo.segments.push(bezierData); + totalLength += bezierData.segmentLength; + } + this._pathData.pi = pathInfo; + } + pathInfo = this._pathData.pi; + currentLength = this._pathData.f.v; + segmentInd = 0; + pointInd = 1; + segmentLength = 0; + flag = true; + segments = pathInfo.segments; + if (currentLength < 0 && mask2.v.c) { + if (pathInfo.tLength < Math.abs(currentLength)) { + currentLength = -Math.abs(currentLength) % pathInfo.tLength; + } + segmentInd = segments.length - 1; + points = segments[segmentInd].points; + pointInd = points.length - 1; + while (currentLength < 0) { + currentLength += points[pointInd].partialLength; + pointInd -= 1; + if (pointInd < 0) { + segmentInd -= 1; + points = segments[segmentInd].points; + pointInd = points.length - 1; + } + } + } + points = segments[segmentInd].points; + prevPoint = points[pointInd - 1]; + currentPoint = points[pointInd]; + partialLength = currentPoint.partialLength; + } + len = letters.length; + xPos = 0; + yPos = 0; + var yOff = documentData.finalSize * 1.2 * 0.714; + var firstLine = true; + var animatorProps; + var animatorSelector; + var j2; + var jLen; + var letterValue; + jLen = animators.length; + var mult; + var ind = -1; + var offf; + var xPathPos; + var yPathPos; + var initPathPos = currentLength; + var initSegmentInd = segmentInd; + var initPointInd = pointInd; + var currentLine = -1; + var elemOpacity; + var sc; + var sw; + var fc; + var k2; + var letterSw; + var letterSc; + var letterFc; + var letterM = ""; + var letterP = this.defaultPropsArray; + var letterO; + if (documentData.j === 2 || documentData.j === 1) { + var animatorJustifyOffset = 0; + var animatorFirstCharOffset = 0; + var justifyOffsetMult = documentData.j === 2 ? -0.5 : -1; + var lastIndex = 0; + var isNewLine = true; + for (i = 0;i < len; i += 1) { + if (letters[i].n) { + if (animatorJustifyOffset) { + animatorJustifyOffset += animatorFirstCharOffset; + } + while (lastIndex < i) { + letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset; + lastIndex += 1; + } + animatorJustifyOffset = 0; + isNewLine = true; + } else { + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.t.propType) { + if (isNewLine && documentData.j === 2) { + animatorFirstCharOffset += animatorProps.t.v * justifyOffsetMult; + } + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + animatorJustifyOffset += animatorProps.t.v * mult[0] * justifyOffsetMult; + } else { + animatorJustifyOffset += animatorProps.t.v * mult * justifyOffsetMult; + } + } + } + isNewLine = false; + } + } + if (animatorJustifyOffset) { + animatorJustifyOffset += animatorFirstCharOffset; + } + while (lastIndex < i) { + letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset; + lastIndex += 1; + } + } + for (i = 0;i < len; i += 1) { + matrixHelper.reset(); + elemOpacity = 1; + if (letters[i].n) { + xPos = 0; + yPos += documentData.yOffset; + yPos += firstLine ? 1 : 0; + currentLength = initPathPos; + firstLine = false; + if (this._hasMaskedPath) { + segmentInd = initSegmentInd; + pointInd = initPointInd; + points = segments[segmentInd].points; + prevPoint = points[pointInd - 1]; + currentPoint = points[pointInd]; + partialLength = currentPoint.partialLength; + segmentLength = 0; + } + letterM = ""; + letterFc = ""; + letterSw = ""; + letterO = ""; + letterP = this.defaultPropsArray; + } else { + if (this._hasMaskedPath) { + if (currentLine !== letters[i].line) { + switch (documentData.j) { + case 1: + currentLength += totalLength - documentData.lineWidths[letters[i].line]; + break; + case 2: + currentLength += (totalLength - documentData.lineWidths[letters[i].line]) / 2; + break; + default: + break; + } + currentLine = letters[i].line; + } + if (ind !== letters[i].ind) { + if (letters[ind]) { + currentLength += letters[ind].extra; + } + currentLength += letters[i].an / 2; + ind = letters[i].ind; + } + currentLength += alignment[0] * letters[i].an * 0.005; + var animatorOffset = 0; + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.p.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + animatorOffset += animatorProps.p.v[0] * mult[0]; + } else { + animatorOffset += animatorProps.p.v[0] * mult; + } + } + if (animatorProps.a.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + animatorOffset += animatorProps.a.v[0] * mult[0]; + } else { + animatorOffset += animatorProps.a.v[0] * mult; + } + } + } + flag = true; + if (this._pathData.a.v) { + currentLength = letters[0].an * 0.5 + (totalLength - this._pathData.f.v - letters[0].an * 0.5 - letters[letters.length - 1].an * 0.5) * ind / (len - 1); + currentLength += this._pathData.f.v; + } + while (flag) { + if (segmentLength + partialLength >= currentLength + animatorOffset || !points) { + perc = (currentLength + animatorOffset - segmentLength) / currentPoint.partialLength; + xPathPos = prevPoint.point[0] + (currentPoint.point[0] - prevPoint.point[0]) * perc; + yPathPos = prevPoint.point[1] + (currentPoint.point[1] - prevPoint.point[1]) * perc; + matrixHelper.translate(-alignment[0] * letters[i].an * 0.005, -(alignment[1] * yOff) * 0.01); + flag = false; + } else if (points) { + segmentLength += currentPoint.partialLength; + pointInd += 1; + if (pointInd >= points.length) { + pointInd = 0; + segmentInd += 1; + if (!segments[segmentInd]) { + if (mask2.v.c) { + pointInd = 0; + segmentInd = 0; + points = segments[segmentInd].points; + } else { + segmentLength -= currentPoint.partialLength; + points = null; + } + } else { + points = segments[segmentInd].points; + } + } + if (points) { + prevPoint = currentPoint; + currentPoint = points[pointInd]; + partialLength = currentPoint.partialLength; + } + } + } + offf = letters[i].an / 2 - letters[i].add; + matrixHelper.translate(-offf, 0, 0); + } else { + offf = letters[i].an / 2 - letters[i].add; + matrixHelper.translate(-offf, 0, 0); + matrixHelper.translate(-alignment[0] * letters[i].an * 0.005, -alignment[1] * yOff * 0.01, 0); + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.t.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (xPos !== 0 || documentData.j !== 0) { + if (this._hasMaskedPath) { + if (mult.length) { + currentLength += animatorProps.t.v * mult[0]; + } else { + currentLength += animatorProps.t.v * mult; + } + } else if (mult.length) { + xPos += animatorProps.t.v * mult[0]; + } else { + xPos += animatorProps.t.v * mult; + } + } + } + } + if (documentData.strokeWidthAnim) { + sw = documentData.sw || 0; + } + if (documentData.strokeColorAnim) { + if (documentData.sc) { + sc = [documentData.sc[0], documentData.sc[1], documentData.sc[2]]; + } else { + sc = [0, 0, 0]; + } + } + if (documentData.fillColorAnim && documentData.fc) { + fc = [documentData.fc[0], documentData.fc[1], documentData.fc[2]]; + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.a.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + matrixHelper.translate(-animatorProps.a.v[0] * mult[0], -animatorProps.a.v[1] * mult[1], animatorProps.a.v[2] * mult[2]); + } else { + matrixHelper.translate(-animatorProps.a.v[0] * mult, -animatorProps.a.v[1] * mult, animatorProps.a.v[2] * mult); + } + } + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.s.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + matrixHelper.scale(1 + (animatorProps.s.v[0] - 1) * mult[0], 1 + (animatorProps.s.v[1] - 1) * mult[1], 1); + } else { + matrixHelper.scale(1 + (animatorProps.s.v[0] - 1) * mult, 1 + (animatorProps.s.v[1] - 1) * mult, 1); + } + } + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (animatorProps.sk.propType) { + if (mult.length) { + matrixHelper.skewFromAxis(-animatorProps.sk.v * mult[0], animatorProps.sa.v * mult[1]); + } else { + matrixHelper.skewFromAxis(-animatorProps.sk.v * mult, animatorProps.sa.v * mult); + } + } + if (animatorProps.r.propType) { + if (mult.length) { + matrixHelper.rotateZ(-animatorProps.r.v * mult[2]); + } else { + matrixHelper.rotateZ(-animatorProps.r.v * mult); + } + } + if (animatorProps.ry.propType) { + if (mult.length) { + matrixHelper.rotateY(animatorProps.ry.v * mult[1]); + } else { + matrixHelper.rotateY(animatorProps.ry.v * mult); + } + } + if (animatorProps.rx.propType) { + if (mult.length) { + matrixHelper.rotateX(animatorProps.rx.v * mult[0]); + } else { + matrixHelper.rotateX(animatorProps.rx.v * mult); + } + } + if (animatorProps.o.propType) { + if (mult.length) { + elemOpacity += (animatorProps.o.v * mult[0] - elemOpacity) * mult[0]; + } else { + elemOpacity += (animatorProps.o.v * mult - elemOpacity) * mult; + } + } + if (documentData.strokeWidthAnim && animatorProps.sw.propType) { + if (mult.length) { + sw += animatorProps.sw.v * mult[0]; + } else { + sw += animatorProps.sw.v * mult; + } + } + if (documentData.strokeColorAnim && animatorProps.sc.propType) { + for (k2 = 0;k2 < 3; k2 += 1) { + if (mult.length) { + sc[k2] += (animatorProps.sc.v[k2] - sc[k2]) * mult[0]; + } else { + sc[k2] += (animatorProps.sc.v[k2] - sc[k2]) * mult; + } + } + } + if (documentData.fillColorAnim && documentData.fc) { + if (animatorProps.fc.propType) { + for (k2 = 0;k2 < 3; k2 += 1) { + if (mult.length) { + fc[k2] += (animatorProps.fc.v[k2] - fc[k2]) * mult[0]; + } else { + fc[k2] += (animatorProps.fc.v[k2] - fc[k2]) * mult; + } + } + } + if (animatorProps.fh.propType) { + if (mult.length) { + fc = addHueToRGB(fc, animatorProps.fh.v * mult[0]); + } else { + fc = addHueToRGB(fc, animatorProps.fh.v * mult); + } + } + if (animatorProps.fs.propType) { + if (mult.length) { + fc = addSaturationToRGB(fc, animatorProps.fs.v * mult[0]); + } else { + fc = addSaturationToRGB(fc, animatorProps.fs.v * mult); + } + } + if (animatorProps.fb.propType) { + if (mult.length) { + fc = addBrightnessToRGB(fc, animatorProps.fb.v * mult[0]); + } else { + fc = addBrightnessToRGB(fc, animatorProps.fb.v * mult); + } + } + } + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.p.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (this._hasMaskedPath) { + if (mult.length) { + matrixHelper.translate(0, animatorProps.p.v[1] * mult[0], -animatorProps.p.v[2] * mult[1]); + } else { + matrixHelper.translate(0, animatorProps.p.v[1] * mult, -animatorProps.p.v[2] * mult); + } + } else if (mult.length) { + matrixHelper.translate(animatorProps.p.v[0] * mult[0], animatorProps.p.v[1] * mult[1], -animatorProps.p.v[2] * mult[2]); + } else { + matrixHelper.translate(animatorProps.p.v[0] * mult, animatorProps.p.v[1] * mult, -animatorProps.p.v[2] * mult); + } + } + } + if (documentData.strokeWidthAnim) { + letterSw = sw < 0 ? 0 : sw; + } + if (documentData.strokeColorAnim) { + letterSc = "rgb(" + Math.round(sc[0] * 255) + "," + Math.round(sc[1] * 255) + "," + Math.round(sc[2] * 255) + ")"; + } + if (documentData.fillColorAnim && documentData.fc) { + letterFc = "rgb(" + Math.round(fc[0] * 255) + "," + Math.round(fc[1] * 255) + "," + Math.round(fc[2] * 255) + ")"; + } + if (this._hasMaskedPath) { + matrixHelper.translate(0, -documentData.ls); + matrixHelper.translate(0, alignment[1] * yOff * 0.01 + yPos, 0); + if (this._pathData.p.v) { + tanAngle = (currentPoint.point[1] - prevPoint.point[1]) / (currentPoint.point[0] - prevPoint.point[0]); + var rot = Math.atan(tanAngle) * 180 / Math.PI; + if (currentPoint.point[0] < prevPoint.point[0]) { + rot += 180; + } + matrixHelper.rotate(-rot * Math.PI / 180); + } + matrixHelper.translate(xPathPos, yPathPos, 0); + currentLength -= alignment[0] * letters[i].an * 0.005; + if (letters[i + 1] && ind !== letters[i + 1].ind) { + currentLength += letters[i].an / 2; + currentLength += documentData.tr * 0.001 * documentData.finalSize; + } + } else { + matrixHelper.translate(xPos, yPos, 0); + if (documentData.ps) { + matrixHelper.translate(documentData.ps[0], documentData.ps[1] + documentData.ascent, 0); + } + switch (documentData.j) { + case 1: + matrixHelper.translate(letters[i].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i].line]), 0, 0); + break; + case 2: + matrixHelper.translate(letters[i].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i].line]) / 2, 0, 0); + break; + default: + break; + } + matrixHelper.translate(0, -documentData.ls); + matrixHelper.translate(offf, 0, 0); + matrixHelper.translate(alignment[0] * letters[i].an * 0.005, alignment[1] * yOff * 0.01, 0); + xPos += letters[i].l + documentData.tr * 0.001 * documentData.finalSize; + } + if (renderType === "html") { + letterM = matrixHelper.toCSS(); + } else if (renderType === "svg") { + letterM = matrixHelper.to2dCSS(); + } else { + letterP = [matrixHelper.props[0], matrixHelper.props[1], matrixHelper.props[2], matrixHelper.props[3], matrixHelper.props[4], matrixHelper.props[5], matrixHelper.props[6], matrixHelper.props[7], matrixHelper.props[8], matrixHelper.props[9], matrixHelper.props[10], matrixHelper.props[11], matrixHelper.props[12], matrixHelper.props[13], matrixHelper.props[14], matrixHelper.props[15]]; + } + letterO = elemOpacity; + } + if (renderedLettersCount <= i) { + letterValue = new LetterProps(letterO, letterSw, letterSc, letterFc, letterM, letterP); + this.renderedLetters.push(letterValue); + renderedLettersCount += 1; + this.lettersChangedFlag = true; + } else { + letterValue = this.renderedLetters[i]; + this.lettersChangedFlag = letterValue.update(letterO, letterSw, letterSc, letterFc, letterM, letterP) || this.lettersChangedFlag; + } + } + }; + TextAnimatorProperty.prototype.getValue = function() { + if (this._elem.globalData.frameId === this._frameId) { + return; + } + this._frameId = this._elem.globalData.frameId; + this.iterateDynamicProperties(); + }; + TextAnimatorProperty.prototype.mHelper = new Matrix; + TextAnimatorProperty.prototype.defaultPropsArray = []; + extendPrototype([DynamicPropertyContainer], TextAnimatorProperty); + ITextElement.prototype.initElement = function(data2, globalData2, comp2) { + this.lettersChangedFlag = true; + this.initFrame(); + this.initBaseData(data2, globalData2, comp2); + this.textProperty = new TextProperty(this, data2.t, this.dynamicProperties); + this.textAnimator = new TextAnimatorProperty(data2.t, this.renderType, this); + this.initTransform(data2, globalData2, comp2); + this.initHierarchy(); + this.initRenderable(); + this.initRendererElement(); + this.createContainerElements(); + this.createRenderableComponents(); + this.createContent(); + this.hide(); + this.textAnimator.searchProperties(this.dynamicProperties); + }; + ITextElement.prototype.prepareFrame = function(num) { + this._mdf = false; + this.prepareRenderableFrame(num); + this.prepareProperties(num, this.isInRange); + if (this.textProperty._mdf || this.textProperty._isFirstFrame) { + this.buildNewText(); + this.textProperty._isFirstFrame = false; + this.textProperty._mdf = false; + } + }; + ITextElement.prototype.createPathShape = function(matrixHelper, shapes) { + var j2; + var jLen = shapes.length; + var pathNodes; + var shapeStr = ""; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (shapes[j2].ty === "sh") { + pathNodes = shapes[j2].ks.k; + shapeStr += buildShapeString(pathNodes, pathNodes.i.length, true, matrixHelper); + } + } + return shapeStr; + }; + ITextElement.prototype.updateDocumentData = function(newData, index2) { + this.textProperty.updateDocumentData(newData, index2); + }; + ITextElement.prototype.canResizeFont = function(_canResize) { + this.textProperty.canResizeFont(_canResize); + }; + ITextElement.prototype.setMinimumFontSize = function(_fontSize) { + this.textProperty.setMinimumFontSize(_fontSize); + }; + ITextElement.prototype.applyTextPropertiesToMatrix = function(documentData, matrixHelper, lineNumber, xPos, yPos) { + if (documentData.ps) { + matrixHelper.translate(documentData.ps[0], documentData.ps[1] + documentData.ascent, 0); + } + matrixHelper.translate(0, -documentData.ls, 0); + switch (documentData.j) { + case 1: + matrixHelper.translate(documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[lineNumber]), 0, 0); + break; + case 2: + matrixHelper.translate(documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[lineNumber]) / 2, 0, 0); + break; + default: + break; + } + matrixHelper.translate(xPos, yPos, 0); + }; + ITextElement.prototype.buildColor = function(colorData) { + return "rgb(" + Math.round(colorData[0] * 255) + "," + Math.round(colorData[1] * 255) + "," + Math.round(colorData[2] * 255) + ")"; + }; + ITextElement.prototype.emptyProp = new LetterProps; + ITextElement.prototype.destroy = function() { + }; + emptyShapeData = { + shapes: [] + }; + extendPrototype([BaseElement, TransformElement, SVGBaseElement, HierarchyElement, FrameElement, RenderableDOMElement, ITextElement], SVGTextLottieElement); + SVGTextLottieElement.prototype.createContent = function() { + if (this.data.singleShape && !this.globalData.fontManager.chars) { + this.textContainer = createNS("text"); + } + }; + SVGTextLottieElement.prototype.buildTextContents = function(textArray) { + var i = 0; + var len = textArray.length; + var textContents = []; + var currentTextContent = ""; + while (i < len) { + if (textArray[i] === String.fromCharCode(13) || textArray[i] === String.fromCharCode(3)) { + textContents.push(currentTextContent); + currentTextContent = ""; + } else { + currentTextContent += textArray[i]; + } + i += 1; + } + textContents.push(currentTextContent); + return textContents; + }; + SVGTextLottieElement.prototype.buildShapeData = function(data2, scale2) { + if (data2.shapes && data2.shapes.length) { + var shape = data2.shapes[0]; + if (shape.it) { + var shapeItem = shape.it[shape.it.length - 1]; + if (shapeItem.s) { + shapeItem.s.k[0] = scale2; + shapeItem.s.k[1] = scale2; + } + } + } + return data2; + }; + SVGTextLottieElement.prototype.buildNewText = function() { + this.addDynamicProperty(this); + var i; + var len; + var documentData = this.textProperty.currentData; + this.renderedLetters = createSizedArray(documentData ? documentData.l.length : 0); + if (documentData.fc) { + this.layerElement.setAttribute("fill", this.buildColor(documentData.fc)); + } else { + this.layerElement.setAttribute("fill", "rgba(0,0,0,0)"); + } + if (documentData.sc) { + this.layerElement.setAttribute("stroke", this.buildColor(documentData.sc)); + this.layerElement.setAttribute("stroke-width", documentData.sw); + } + this.layerElement.setAttribute("font-size", documentData.finalSize); + var fontData = this.globalData.fontManager.getFontByName(documentData.f); + if (fontData.fClass) { + this.layerElement.setAttribute("class", fontData.fClass); + } else { + this.layerElement.setAttribute("font-family", fontData.fFamily); + var fWeight = documentData.fWeight; + var fStyle = documentData.fStyle; + this.layerElement.setAttribute("font-style", fStyle); + this.layerElement.setAttribute("font-weight", fWeight); + } + this.layerElement.setAttribute("aria-label", documentData.t); + var letters = documentData.l || []; + var usesGlyphs = !!this.globalData.fontManager.chars; + len = letters.length; + var tSpan; + var matrixHelper = this.mHelper; + var shapeStr = ""; + var singleShape = this.data.singleShape; + var xPos = 0; + var yPos = 0; + var firstLine = true; + var trackingOffset = documentData.tr * 0.001 * documentData.finalSize; + if (singleShape && !usesGlyphs && !documentData.sz) { + var tElement = this.textContainer; + var justify = "start"; + switch (documentData.j) { + case 1: + justify = "end"; + break; + case 2: + justify = "middle"; + break; + default: + justify = "start"; + break; + } + tElement.setAttribute("text-anchor", justify); + tElement.setAttribute("letter-spacing", trackingOffset); + var textContent = this.buildTextContents(documentData.finalText); + len = textContent.length; + yPos = documentData.ps ? documentData.ps[1] + documentData.ascent : 0; + for (i = 0;i < len; i += 1) { + tSpan = this.textSpans[i].span || createNS("tspan"); + tSpan.textContent = textContent[i]; + tSpan.setAttribute("x", 0); + tSpan.setAttribute("y", yPos); + tSpan.style.display = "inherit"; + tElement.appendChild(tSpan); + if (!this.textSpans[i]) { + this.textSpans[i] = { + span: null, + glyph: null + }; + } + this.textSpans[i].span = tSpan; + yPos += documentData.finalLineHeight; + } + this.layerElement.appendChild(tElement); + } else { + var cachedSpansLength = this.textSpans.length; + var charData; + for (i = 0;i < len; i += 1) { + if (!this.textSpans[i]) { + this.textSpans[i] = { + span: null, + childSpan: null, + glyph: null + }; + } + if (!usesGlyphs || !singleShape || i === 0) { + tSpan = cachedSpansLength > i ? this.textSpans[i].span : createNS(usesGlyphs ? "g" : "text"); + if (cachedSpansLength <= i) { + tSpan.setAttribute("stroke-linecap", "butt"); + tSpan.setAttribute("stroke-linejoin", "round"); + tSpan.setAttribute("stroke-miterlimit", "4"); + this.textSpans[i].span = tSpan; + if (usesGlyphs) { + var childSpan = createNS("g"); + tSpan.appendChild(childSpan); + this.textSpans[i].childSpan = childSpan; + } + this.textSpans[i].span = tSpan; + this.layerElement.appendChild(tSpan); + } + tSpan.style.display = "inherit"; + } + matrixHelper.reset(); + if (singleShape) { + if (letters[i].n) { + xPos = -trackingOffset; + yPos += documentData.yOffset; + yPos += firstLine ? 1 : 0; + firstLine = false; + } + this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i].line, xPos, yPos); + xPos += letters[i].l || 0; + xPos += trackingOffset; + } + if (usesGlyphs) { + charData = this.globalData.fontManager.getCharData(documentData.finalText[i], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily); + var glyphElement; + if (charData.t === 1) { + glyphElement = new SVGCompElement(charData.data, this.globalData, this); + } else { + var data2 = emptyShapeData; + if (charData.data && charData.data.shapes) { + data2 = this.buildShapeData(charData.data, documentData.finalSize); + } + glyphElement = new SVGShapeElement(data2, this.globalData, this); + } + if (this.textSpans[i].glyph) { + var glyph = this.textSpans[i].glyph; + this.textSpans[i].childSpan.removeChild(glyph.layerElement); + glyph.destroy(); + } + this.textSpans[i].glyph = glyphElement; + glyphElement._debug = true; + glyphElement.prepareFrame(0); + glyphElement.renderFrame(); + this.textSpans[i].childSpan.appendChild(glyphElement.layerElement); + if (charData.t === 1) { + this.textSpans[i].childSpan.setAttribute("transform", "scale(" + documentData.finalSize / 100 + "," + documentData.finalSize / 100 + ")"); + } + } else { + if (singleShape) { + tSpan.setAttribute("transform", "translate(" + matrixHelper.props[12] + "," + matrixHelper.props[13] + ")"); + } + tSpan.textContent = letters[i].val; + tSpan.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space", "preserve"); + } + } + if (singleShape && tSpan) { + tSpan.setAttribute("d", shapeStr); + } + } + while (i < this.textSpans.length) { + this.textSpans[i].span.style.display = "none"; + i += 1; + } + this._sizeChanged = true; + }; + SVGTextLottieElement.prototype.sourceRectAtTime = function() { + this.prepareFrame(this.comp.renderedFrame - this.data.st); + this.renderInnerContent(); + if (this._sizeChanged) { + this._sizeChanged = false; + var textBox = this.layerElement.getBBox(); + this.bbox = { + top: textBox.y, + left: textBox.x, + width: textBox.width, + height: textBox.height + }; + } + return this.bbox; + }; + SVGTextLottieElement.prototype.getValue = function() { + var i; + var len = this.textSpans.length; + var glyphElement; + this.renderedFrame = this.comp.renderedFrame; + for (i = 0;i < len; i += 1) { + glyphElement = this.textSpans[i].glyph; + if (glyphElement) { + glyphElement.prepareFrame(this.comp.renderedFrame - this.data.st); + if (glyphElement._mdf) { + this._mdf = true; + } + } + } + }; + SVGTextLottieElement.prototype.renderInnerContent = function() { + if (!this.data.singleShape || this._mdf) { + this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag); + if (this.lettersChangedFlag || this.textAnimator.lettersChangedFlag) { + this._sizeChanged = true; + var i; + var len; + var renderedLetters = this.textAnimator.renderedLetters; + var letters = this.textProperty.currentData.l; + len = letters.length; + var renderedLetter; + var textSpan; + var glyphElement; + for (i = 0;i < len; i += 1) { + if (!letters[i].n) { + renderedLetter = renderedLetters[i]; + textSpan = this.textSpans[i].span; + glyphElement = this.textSpans[i].glyph; + if (glyphElement) { + glyphElement.renderFrame(); + } + if (renderedLetter._mdf.m) { + textSpan.setAttribute("transform", renderedLetter.m); + } + if (renderedLetter._mdf.o) { + textSpan.setAttribute("opacity", renderedLetter.o); + } + if (renderedLetter._mdf.sw) { + textSpan.setAttribute("stroke-width", renderedLetter.sw); + } + if (renderedLetter._mdf.sc) { + textSpan.setAttribute("stroke", renderedLetter.sc); + } + if (renderedLetter._mdf.fc) { + textSpan.setAttribute("fill", renderedLetter.fc); + } + } + } + } + } + }; + extendPrototype([IImageElement], ISolidElement); + ISolidElement.prototype.createContent = function() { + var rect = createNS("rect"); + rect.setAttribute("width", this.data.sw); + rect.setAttribute("height", this.data.sh); + rect.setAttribute("fill", this.data.sc); + this.layerElement.appendChild(rect); + }; + NullElement.prototype.prepareFrame = function(num) { + this.prepareProperties(num, true); + }; + NullElement.prototype.renderFrame = function() { + }; + NullElement.prototype.getBaseElement = function() { + return null; + }; + NullElement.prototype.destroy = function() { + }; + NullElement.prototype.sourceRectAtTime = function() { + }; + NullElement.prototype.hide = function() { + }; + extendPrototype([BaseElement, TransformElement, HierarchyElement, FrameElement], NullElement); + extendPrototype([BaseRenderer], SVGRendererBase); + SVGRendererBase.prototype.createNull = function(data2) { + return new NullElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.createShape = function(data2) { + return new SVGShapeElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.createText = function(data2) { + return new SVGTextLottieElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.createImage = function(data2) { + return new IImageElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.createSolid = function(data2) { + return new ISolidElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.configAnimation = function(animData) { + this.svgElement.setAttribute("xmlns", "http://www.w3.org/2000/svg"); + if (this.renderConfig.viewBoxSize) { + this.svgElement.setAttribute("viewBox", this.renderConfig.viewBoxSize); + } else { + this.svgElement.setAttribute("viewBox", "0 0 " + animData.w + " " + animData.h); + } + if (!this.renderConfig.viewBoxOnly) { + this.svgElement.setAttribute("width", animData.w); + this.svgElement.setAttribute("height", animData.h); + this.svgElement.style.width = "100%"; + this.svgElement.style.height = "100%"; + this.svgElement.style.transform = "translate3d(0,0,0)"; + this.svgElement.style.contentVisibility = this.renderConfig.contentVisibility; + } + if (this.renderConfig.width) { + this.svgElement.setAttribute("width", this.renderConfig.width); + } + if (this.renderConfig.height) { + this.svgElement.setAttribute("height", this.renderConfig.height); + } + if (this.renderConfig.className) { + this.svgElement.setAttribute("class", this.renderConfig.className); + } + if (this.renderConfig.id) { + this.svgElement.setAttribute("id", this.renderConfig.id); + } + if (this.renderConfig.focusable !== undefined) { + this.svgElement.setAttribute("focusable", this.renderConfig.focusable); + } + this.svgElement.setAttribute("preserveAspectRatio", this.renderConfig.preserveAspectRatio); + this.animationItem.wrapper.appendChild(this.svgElement); + var defs = this.globalData.defs; + this.setupGlobalData(animData, defs); + this.globalData.progressiveLoad = this.renderConfig.progressiveLoad; + this.data = animData; + var maskElement = createNS("clipPath"); + var rect = createNS("rect"); + rect.setAttribute("width", animData.w); + rect.setAttribute("height", animData.h); + rect.setAttribute("x", 0); + rect.setAttribute("y", 0); + var maskId = createElementID(); + maskElement.setAttribute("id", maskId); + maskElement.appendChild(rect); + this.layerElement.setAttribute("clip-path", "url(" + getLocationHref() + "#" + maskId + ")"); + defs.appendChild(maskElement); + this.layers = animData.layers; + this.elements = createSizedArray(animData.layers.length); + }; + SVGRendererBase.prototype.destroy = function() { + if (this.animationItem.wrapper) { + this.animationItem.wrapper.innerText = ""; + } + this.layerElement = null; + this.globalData.defs = null; + var i; + var len = this.layers ? this.layers.length : 0; + for (i = 0;i < len; i += 1) { + if (this.elements[i]) { + this.elements[i].destroy(); + } + } + this.elements.length = 0; + this.destroyed = true; + this.animationItem = null; + }; + SVGRendererBase.prototype.updateContainerSize = function() { + }; + SVGRendererBase.prototype.buildItem = function(pos) { + var elements = this.elements; + if (elements[pos] || this.layers[pos].ty === 99) { + return; + } + elements[pos] = true; + var element = this.createItem(this.layers[pos]); + elements[pos] = element; + if (getExpressionsPlugin()) { + if (this.layers[pos].ty === 0) { + this.globalData.projectInterface.registerComposition(element); + } + element.initExpressions(); + } + this.appendElementInPos(element, pos); + if (this.layers[pos].tt) { + if (!this.elements[pos - 1] || this.elements[pos - 1] === true) { + this.buildItem(pos - 1); + this.addPendingElement(element); + } else { + element.setMatte(elements[pos - 1].layerId); + } + } + }; + SVGRendererBase.prototype.checkPendingElements = function() { + while (this.pendingElements.length) { + var element = this.pendingElements.pop(); + element.checkParenting(); + if (element.data.tt) { + var i = 0; + var len = this.elements.length; + while (i < len) { + if (this.elements[i] === element) { + element.setMatte(this.elements[i - 1].layerId); + break; + } + i += 1; + } + } + } + }; + SVGRendererBase.prototype.renderFrame = function(num) { + if (this.renderedFrame === num || this.destroyed) { + return; + } + if (num === null) { + num = this.renderedFrame; + } else { + this.renderedFrame = num; + } + this.globalData.frameNum = num; + this.globalData.frameId += 1; + this.globalData.projectInterface.currentFrame = num; + this.globalData._mdf = false; + var i; + var len = this.layers.length; + if (!this.completeLayers) { + this.checkLayers(num); + } + for (i = len - 1;i >= 0; i -= 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].prepareFrame(num - this.layers[i].st); + } + } + if (this.globalData._mdf) { + for (i = 0;i < len; i += 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].renderFrame(); + } + } + } + }; + SVGRendererBase.prototype.appendElementInPos = function(element, pos) { + var newElement = element.getBaseElement(); + if (!newElement) { + return; + } + var i = 0; + var nextElement; + while (i < pos) { + if (this.elements[i] && this.elements[i] !== true && this.elements[i].getBaseElement()) { + nextElement = this.elements[i].getBaseElement(); + } + i += 1; + } + if (nextElement) { + this.layerElement.insertBefore(newElement, nextElement); + } else { + this.layerElement.appendChild(newElement); + } + }; + SVGRendererBase.prototype.hide = function() { + this.layerElement.style.display = "none"; + }; + SVGRendererBase.prototype.show = function() { + this.layerElement.style.display = "block"; + }; + extendPrototype([BaseElement, TransformElement, HierarchyElement, FrameElement, RenderableDOMElement], ICompElement); + ICompElement.prototype.initElement = function(data2, globalData2, comp2) { + this.initFrame(); + this.initBaseData(data2, globalData2, comp2); + this.initTransform(data2, globalData2, comp2); + this.initRenderable(); + this.initHierarchy(); + this.initRendererElement(); + this.createContainerElements(); + this.createRenderableComponents(); + if (this.data.xt || !globalData2.progressiveLoad) { + this.buildAllItems(); + } + this.hide(); + }; + ICompElement.prototype.prepareFrame = function(num) { + this._mdf = false; + this.prepareRenderableFrame(num); + this.prepareProperties(num, this.isInRange); + if (!this.isInRange && !this.data.xt) { + return; + } + if (!this.tm._placeholder) { + var timeRemapped = this.tm.v; + if (timeRemapped === this.data.op) { + timeRemapped = this.data.op - 1; + } + this.renderedFrame = timeRemapped; + } else { + this.renderedFrame = num / this.data.sr; + } + var i; + var len = this.elements.length; + if (!this.completeLayers) { + this.checkLayers(this.renderedFrame); + } + for (i = len - 1;i >= 0; i -= 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].prepareFrame(this.renderedFrame - this.layers[i].st); + if (this.elements[i]._mdf) { + this._mdf = true; + } + } + } + }; + ICompElement.prototype.renderInnerContent = function() { + var i; + var len = this.layers.length; + for (i = 0;i < len; i += 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].renderFrame(); + } + } + }; + ICompElement.prototype.setElements = function(elems) { + this.elements = elems; + }; + ICompElement.prototype.getElements = function() { + return this.elements; + }; + ICompElement.prototype.destroyElements = function() { + var i; + var len = this.layers.length; + for (i = 0;i < len; i += 1) { + if (this.elements[i]) { + this.elements[i].destroy(); + } + } + }; + ICompElement.prototype.destroy = function() { + this.destroyElements(); + this.destroyBaseElement(); + }; + extendPrototype([SVGRendererBase, ICompElement, SVGBaseElement], SVGCompElement); + SVGCompElement.prototype.createComp = function(data2) { + return new SVGCompElement(data2, this.globalData, this); + }; + extendPrototype([SVGRendererBase], SVGRenderer); + SVGRenderer.prototype.createComp = function(data2) { + return new SVGCompElement(data2, this.globalData, this); + }; + CVContextData.prototype.duplicate = function() { + var newLength = this._length * 2; + var currentSavedOp = this.savedOp; + this.savedOp = createTypedArray("float32", newLength); + this.savedOp.set(currentSavedOp); + var i = 0; + for (i = this._length;i < newLength; i += 1) { + this.saved[i] = createTypedArray("float32", 16); + } + this._length = newLength; + }; + CVContextData.prototype.reset = function() { + this.cArrPos = 0; + this.cTr.reset(); + this.cO = 1; + }; + ShapeTransformManager.prototype = { + addTransformSequence: function(transforms) { + var i; + var len = transforms.length; + var key2 = "_"; + for (i = 0;i < len; i += 1) { + key2 += transforms[i].transform.key + "_"; + } + var sequence = this.sequences[key2]; + if (!sequence) { + sequence = { + transforms: [].concat(transforms), + finalTransform: new Matrix, + _mdf: false + }; + this.sequences[key2] = sequence; + this.sequenceList.push(sequence); + } + return sequence; + }, + processSequence: function(sequence, isFirstFrame) { + var i = 0; + var len = sequence.transforms.length; + var _mdf = isFirstFrame; + while (i < len && !isFirstFrame) { + if (sequence.transforms[i].transform.mProps._mdf) { + _mdf = true; + break; + } + i += 1; + } + if (_mdf) { + var props; + sequence.finalTransform.reset(); + for (i = len - 1;i >= 0; i -= 1) { + props = sequence.transforms[i].transform.mProps.v.props; + sequence.finalTransform.transform(props[0], props[1], props[2], props[3], props[4], props[5], props[6], props[7], props[8], props[9], props[10], props[11], props[12], props[13], props[14], props[15]); + } + } + sequence._mdf = _mdf; + }, + processSequences: function(isFirstFrame) { + var i; + var len = this.sequenceList.length; + for (i = 0;i < len; i += 1) { + this.processSequence(this.sequenceList[i], isFirstFrame); + } + }, + getNewKey: function() { + this.transform_key_count += 1; + return "_" + this.transform_key_count; + } + }; + CVEffects.prototype.renderFrame = function() { + }; + CVMaskElement.prototype.renderFrame = function() { + if (!this.hasMasks) { + return; + } + var transform2 = this.element.finalTransform.mat; + var ctx = this.element.canvasContext; + var i; + var len = this.masksProperties.length; + var pt; + var pts; + var data2; + ctx.beginPath(); + for (i = 0;i < len; i += 1) { + if (this.masksProperties[i].mode !== "n") { + if (this.masksProperties[i].inv) { + ctx.moveTo(0, 0); + ctx.lineTo(this.element.globalData.compSize.w, 0); + ctx.lineTo(this.element.globalData.compSize.w, this.element.globalData.compSize.h); + ctx.lineTo(0, this.element.globalData.compSize.h); + ctx.lineTo(0, 0); + } + data2 = this.viewData[i].v; + pt = transform2.applyToPointArray(data2.v[0][0], data2.v[0][1], 0); + ctx.moveTo(pt[0], pt[1]); + var j2; + var jLen = data2._length; + for (j2 = 1;j2 < jLen; j2 += 1) { + pts = transform2.applyToTriplePoints(data2.o[j2 - 1], data2.i[j2], data2.v[j2]); + ctx.bezierCurveTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]); + } + pts = transform2.applyToTriplePoints(data2.o[j2 - 1], data2.i[0], data2.v[0]); + ctx.bezierCurveTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]); + } + } + this.element.globalData.renderer.save(true); + ctx.clip(); + }; + CVMaskElement.prototype.getMaskProperty = MaskElement.prototype.getMaskProperty; + CVMaskElement.prototype.destroy = function() { + this.element = null; + }; + CVBaseElement.prototype = { + createElements: function() { + }, + initRendererElement: function() { + }, + createContainerElements: function() { + this.canvasContext = this.globalData.canvasContext; + this.renderableEffectsManager = new CVEffects(this); + }, + createContent: function() { + }, + setBlendMode: function() { + var globalData2 = this.globalData; + if (globalData2.blendMode !== this.data.bm) { + globalData2.blendMode = this.data.bm; + var blendModeValue = getBlendMode(this.data.bm); + globalData2.canvasContext.globalCompositeOperation = blendModeValue; + } + }, + createRenderableComponents: function() { + this.maskManager = new CVMaskElement(this.data, this); + }, + hideElement: function() { + if (!this.hidden && (!this.isInRange || this.isTransparent)) { + this.hidden = true; + } + }, + showElement: function() { + if (this.isInRange && !this.isTransparent) { + this.hidden = false; + this._isFirstFrame = true; + this.maskManager._isFirstFrame = true; + } + }, + renderFrame: function() { + if (this.hidden || this.data.hd) { + return; + } + this.renderTransform(); + this.renderRenderable(); + this.setBlendMode(); + var forceRealStack = this.data.ty === 0; + this.globalData.renderer.save(forceRealStack); + this.globalData.renderer.ctxTransform(this.finalTransform.mat.props); + this.globalData.renderer.ctxOpacity(this.finalTransform.mProp.o.v); + this.renderInnerContent(); + this.globalData.renderer.restore(forceRealStack); + if (this.maskManager.hasMasks) { + this.globalData.renderer.restore(true); + } + if (this._isFirstFrame) { + this._isFirstFrame = false; + } + }, + destroy: function() { + this.canvasContext = null; + this.data = null; + this.globalData = null; + this.maskManager.destroy(); + }, + mHelper: new Matrix + }; + CVBaseElement.prototype.hide = CVBaseElement.prototype.hideElement; + CVBaseElement.prototype.show = CVBaseElement.prototype.showElement; + CVShapeData.prototype.setAsAnimated = SVGShapeData.prototype.setAsAnimated; + extendPrototype([BaseElement, TransformElement, CVBaseElement, IShapeElement, HierarchyElement, FrameElement, RenderableElement], CVShapeElement); + CVShapeElement.prototype.initElement = RenderableDOMElement.prototype.initElement; + CVShapeElement.prototype.transformHelper = { opacity: 1, _opMdf: false }; + CVShapeElement.prototype.dashResetter = []; + CVShapeElement.prototype.createContent = function() { + this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, true, []); + }; + CVShapeElement.prototype.createStyleElement = function(data2, transforms) { + var styleElem = { + data: data2, + type: data2.ty, + preTransforms: this.transformsManager.addTransformSequence(transforms), + transforms: [], + elements: [], + closed: data2.hd === true + }; + var elementData = {}; + if (data2.ty === "fl" || data2.ty === "st") { + elementData.c = PropertyFactory.getProp(this, data2.c, 1, 255, this); + if (!elementData.c.k) { + styleElem.co = "rgb(" + bmFloor(elementData.c.v[0]) + "," + bmFloor(elementData.c.v[1]) + "," + bmFloor(elementData.c.v[2]) + ")"; + } + } else if (data2.ty === "gf" || data2.ty === "gs") { + elementData.s = PropertyFactory.getProp(this, data2.s, 1, null, this); + elementData.e = PropertyFactory.getProp(this, data2.e, 1, null, this); + elementData.h = PropertyFactory.getProp(this, data2.h || { k: 0 }, 0, 0.01, this); + elementData.a = PropertyFactory.getProp(this, data2.a || { k: 0 }, 0, degToRads, this); + elementData.g = new GradientProperty(this, data2.g, this); + } + elementData.o = PropertyFactory.getProp(this, data2.o, 0, 0.01, this); + if (data2.ty === "st" || data2.ty === "gs") { + styleElem.lc = lineCapEnum[data2.lc || 2]; + styleElem.lj = lineJoinEnum[data2.lj || 2]; + if (data2.lj == 1) { + styleElem.ml = data2.ml; + } + elementData.w = PropertyFactory.getProp(this, data2.w, 0, null, this); + if (!elementData.w.k) { + styleElem.wi = elementData.w.v; + } + if (data2.d) { + var d = new DashProperty(this, data2.d, "canvas", this); + elementData.d = d; + if (!elementData.d.k) { + styleElem.da = elementData.d.dashArray; + styleElem.do = elementData.d.dashoffset[0]; + } + } + } else { + styleElem.r = data2.r === 2 ? "evenodd" : "nonzero"; + } + this.stylesList.push(styleElem); + elementData.style = styleElem; + return elementData; + }; + CVShapeElement.prototype.createGroupElement = function() { + var elementData = { + it: [], + prevViewData: [] + }; + return elementData; + }; + CVShapeElement.prototype.createTransformElement = function(data2) { + var elementData = { + transform: { + opacity: 1, + _opMdf: false, + key: this.transformsManager.getNewKey(), + op: PropertyFactory.getProp(this, data2.o, 0, 0.01, this), + mProps: TransformPropertyFactory.getTransformProperty(this, data2, this) + } + }; + return elementData; + }; + CVShapeElement.prototype.createShapeElement = function(data2) { + var elementData = new CVShapeData(this, data2, this.stylesList, this.transformsManager); + this.shapes.push(elementData); + this.addShapeToModifiers(elementData); + return elementData; + }; + CVShapeElement.prototype.reloadShapes = function() { + this._isFirstFrame = true; + var i; + var len = this.itemsData.length; + for (i = 0;i < len; i += 1) { + this.prevViewData[i] = this.itemsData[i]; + } + this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, true, []); + len = this.dynamicProperties.length; + for (i = 0;i < len; i += 1) { + this.dynamicProperties[i].getValue(); + } + this.renderModifiers(); + this.transformsManager.processSequences(this._isFirstFrame); + }; + CVShapeElement.prototype.addTransformToStyleList = function(transform2) { + var i; + var len = this.stylesList.length; + for (i = 0;i < len; i += 1) { + if (!this.stylesList[i].closed) { + this.stylesList[i].transforms.push(transform2); + } + } + }; + CVShapeElement.prototype.removeTransformFromStyleList = function() { + var i; + var len = this.stylesList.length; + for (i = 0;i < len; i += 1) { + if (!this.stylesList[i].closed) { + this.stylesList[i].transforms.pop(); + } + } + }; + CVShapeElement.prototype.closeStyles = function(styles) { + var i; + var len = styles.length; + for (i = 0;i < len; i += 1) { + styles[i].closed = true; + } + }; + CVShapeElement.prototype.searchShapes = function(arr, itemsData, prevViewData, shouldRender, transforms) { + var i; + var len = arr.length - 1; + var j2; + var jLen; + var ownStyles = []; + var ownModifiers = []; + var processedPos; + var modifier; + var currentTransform; + var ownTransforms = [].concat(transforms); + for (i = len;i >= 0; i -= 1) { + processedPos = this.searchProcessedElement(arr[i]); + if (!processedPos) { + arr[i]._shouldRender = shouldRender; + } else { + itemsData[i] = prevViewData[processedPos - 1]; + } + if (arr[i].ty === "fl" || arr[i].ty === "st" || arr[i].ty === "gf" || arr[i].ty === "gs") { + if (!processedPos) { + itemsData[i] = this.createStyleElement(arr[i], ownTransforms); + } else { + itemsData[i].style.closed = false; + } + ownStyles.push(itemsData[i].style); + } else if (arr[i].ty === "gr") { + if (!processedPos) { + itemsData[i] = this.createGroupElement(arr[i]); + } else { + jLen = itemsData[i].it.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + itemsData[i].prevViewData[j2] = itemsData[i].it[j2]; + } + } + this.searchShapes(arr[i].it, itemsData[i].it, itemsData[i].prevViewData, shouldRender, ownTransforms); + } else if (arr[i].ty === "tr") { + if (!processedPos) { + currentTransform = this.createTransformElement(arr[i]); + itemsData[i] = currentTransform; + } + ownTransforms.push(itemsData[i]); + this.addTransformToStyleList(itemsData[i]); + } else if (arr[i].ty === "sh" || arr[i].ty === "rc" || arr[i].ty === "el" || arr[i].ty === "sr") { + if (!processedPos) { + itemsData[i] = this.createShapeElement(arr[i]); + } + } else if (arr[i].ty === "tm" || arr[i].ty === "rd" || arr[i].ty === "pb") { + if (!processedPos) { + modifier = ShapeModifiers.getModifier(arr[i].ty); + modifier.init(this, arr[i]); + itemsData[i] = modifier; + this.shapeModifiers.push(modifier); + } else { + modifier = itemsData[i]; + modifier.closed = false; + } + ownModifiers.push(modifier); + } else if (arr[i].ty === "rp") { + if (!processedPos) { + modifier = ShapeModifiers.getModifier(arr[i].ty); + itemsData[i] = modifier; + modifier.init(this, arr, i, itemsData); + this.shapeModifiers.push(modifier); + shouldRender = false; + } else { + modifier = itemsData[i]; + modifier.closed = true; + } + ownModifiers.push(modifier); + } + this.addProcessedElement(arr[i], i + 1); + } + this.removeTransformFromStyleList(); + this.closeStyles(ownStyles); + len = ownModifiers.length; + for (i = 0;i < len; i += 1) { + ownModifiers[i].closed = true; + } + }; + CVShapeElement.prototype.renderInnerContent = function() { + this.transformHelper.opacity = 1; + this.transformHelper._opMdf = false; + this.renderModifiers(); + this.transformsManager.processSequences(this._isFirstFrame); + this.renderShape(this.transformHelper, this.shapesData, this.itemsData, true); + }; + CVShapeElement.prototype.renderShapeTransform = function(parentTransform, groupTransform) { + if (parentTransform._opMdf || groupTransform.op._mdf || this._isFirstFrame) { + groupTransform.opacity = parentTransform.opacity; + groupTransform.opacity *= groupTransform.op.v; + groupTransform._opMdf = true; + } + }; + CVShapeElement.prototype.drawLayer = function() { + var i; + var len = this.stylesList.length; + var j2; + var jLen; + var k2; + var kLen; + var elems; + var nodes; + var renderer2 = this.globalData.renderer; + var ctx = this.globalData.canvasContext; + var type; + var currentStyle; + for (i = 0;i < len; i += 1) { + currentStyle = this.stylesList[i]; + type = currentStyle.type; + if (!((type === "st" || type === "gs") && currentStyle.wi === 0 || !currentStyle.data._shouldRender || currentStyle.coOp === 0 || this.globalData.currentGlobalAlpha === 0)) { + renderer2.save(); + elems = currentStyle.elements; + if (type === "st" || type === "gs") { + ctx.strokeStyle = type === "st" ? currentStyle.co : currentStyle.grd; + ctx.lineWidth = currentStyle.wi; + ctx.lineCap = currentStyle.lc; + ctx.lineJoin = currentStyle.lj; + ctx.miterLimit = currentStyle.ml || 0; + } else { + ctx.fillStyle = type === "fl" ? currentStyle.co : currentStyle.grd; + } + renderer2.ctxOpacity(currentStyle.coOp); + if (type !== "st" && type !== "gs") { + ctx.beginPath(); + } + renderer2.ctxTransform(currentStyle.preTransforms.finalTransform.props); + jLen = elems.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (type === "st" || type === "gs") { + ctx.beginPath(); + if (currentStyle.da) { + ctx.setLineDash(currentStyle.da); + ctx.lineDashOffset = currentStyle.do; + } + } + nodes = elems[j2].trNodes; + kLen = nodes.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + if (nodes[k2].t === "m") { + ctx.moveTo(nodes[k2].p[0], nodes[k2].p[1]); + } else if (nodes[k2].t === "c") { + ctx.bezierCurveTo(nodes[k2].pts[0], nodes[k2].pts[1], nodes[k2].pts[2], nodes[k2].pts[3], nodes[k2].pts[4], nodes[k2].pts[5]); + } else { + ctx.closePath(); + } + } + if (type === "st" || type === "gs") { + ctx.stroke(); + if (currentStyle.da) { + ctx.setLineDash(this.dashResetter); + } + } + } + if (type !== "st" && type !== "gs") { + ctx.fill(currentStyle.r); + } + renderer2.restore(); + } + } + }; + CVShapeElement.prototype.renderShape = function(parentTransform, items, data2, isMain) { + var i; + var len = items.length - 1; + var groupTransform; + groupTransform = parentTransform; + for (i = len;i >= 0; i -= 1) { + if (items[i].ty === "tr") { + groupTransform = data2[i].transform; + this.renderShapeTransform(parentTransform, groupTransform); + } else if (items[i].ty === "sh" || items[i].ty === "el" || items[i].ty === "rc" || items[i].ty === "sr") { + this.renderPath(items[i], data2[i]); + } else if (items[i].ty === "fl") { + this.renderFill(items[i], data2[i], groupTransform); + } else if (items[i].ty === "st") { + this.renderStroke(items[i], data2[i], groupTransform); + } else if (items[i].ty === "gf" || items[i].ty === "gs") { + this.renderGradientFill(items[i], data2[i], groupTransform); + } else if (items[i].ty === "gr") { + this.renderShape(groupTransform, items[i].it, data2[i].it); + } else if (items[i].ty === "tm") { + } + } + if (isMain) { + this.drawLayer(); + } + }; + CVShapeElement.prototype.renderStyledShape = function(styledShape, shape) { + if (this._isFirstFrame || shape._mdf || styledShape.transforms._mdf) { + var shapeNodes = styledShape.trNodes; + var paths = shape.paths; + var i; + var len; + var j2; + var jLen = paths._length; + shapeNodes.length = 0; + var groupTransformMat = styledShape.transforms.finalTransform; + for (j2 = 0;j2 < jLen; j2 += 1) { + var pathNodes = paths.shapes[j2]; + if (pathNodes && pathNodes.v) { + len = pathNodes._length; + for (i = 1;i < len; i += 1) { + if (i === 1) { + shapeNodes.push({ + t: "m", + p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0) + }); + } + shapeNodes.push({ + t: "c", + pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[i], pathNodes.v[i]) + }); + } + if (len === 1) { + shapeNodes.push({ + t: "m", + p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0) + }); + } + if (pathNodes.c && len) { + shapeNodes.push({ + t: "c", + pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[0], pathNodes.v[0]) + }); + shapeNodes.push({ + t: "z" + }); + } + } + } + styledShape.trNodes = shapeNodes; + } + }; + CVShapeElement.prototype.renderPath = function(pathData, itemData) { + if (pathData.hd !== true && pathData._shouldRender) { + var i; + var len = itemData.styledShapes.length; + for (i = 0;i < len; i += 1) { + this.renderStyledShape(itemData.styledShapes[i], itemData.sh); + } + } + }; + CVShapeElement.prototype.renderFill = function(styleData, itemData, groupTransform) { + var styleElem = itemData.style; + if (itemData.c._mdf || this._isFirstFrame) { + styleElem.co = "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"; + } + if (itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame) { + styleElem.coOp = itemData.o.v * groupTransform.opacity; + } + }; + CVShapeElement.prototype.renderGradientFill = function(styleData, itemData, groupTransform) { + var styleElem = itemData.style; + var grd; + if (!styleElem.grd || itemData.g._mdf || itemData.s._mdf || itemData.e._mdf || styleData.t !== 1 && (itemData.h._mdf || itemData.a._mdf)) { + var ctx = this.globalData.canvasContext; + var pt1 = itemData.s.v; + var pt2 = itemData.e.v; + if (styleData.t === 1) { + grd = ctx.createLinearGradient(pt1[0], pt1[1], pt2[0], pt2[1]); + } else { + var rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); + var ang = Math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]); + var percent = itemData.h.v; + if (percent >= 1) { + percent = 0.99; + } else if (percent <= -1) { + percent = -0.99; + } + var dist = rad * percent; + var x2 = Math.cos(ang + itemData.a.v) * dist + pt1[0]; + var y = Math.sin(ang + itemData.a.v) * dist + pt1[1]; + grd = ctx.createRadialGradient(x2, y, 0, pt1[0], pt1[1], rad); + } + var i; + var len = styleData.g.p; + var cValues = itemData.g.c; + var opacity = 1; + for (i = 0;i < len; i += 1) { + if (itemData.g._hasOpacity && itemData.g._collapsable) { + opacity = itemData.g.o[i * 2 + 1]; + } + grd.addColorStop(cValues[i * 4] / 100, "rgba(" + cValues[i * 4 + 1] + "," + cValues[i * 4 + 2] + "," + cValues[i * 4 + 3] + "," + opacity + ")"); + } + styleElem.grd = grd; + } + styleElem.coOp = itemData.o.v * groupTransform.opacity; + }; + CVShapeElement.prototype.renderStroke = function(styleData, itemData, groupTransform) { + var styleElem = itemData.style; + var d = itemData.d; + if (d && (d._mdf || this._isFirstFrame)) { + styleElem.da = d.dashArray; + styleElem.do = d.dashoffset[0]; + } + if (itemData.c._mdf || this._isFirstFrame) { + styleElem.co = "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"; + } + if (itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame) { + styleElem.coOp = itemData.o.v * groupTransform.opacity; + } + if (itemData.w._mdf || this._isFirstFrame) { + styleElem.wi = itemData.w.v; + } + }; + CVShapeElement.prototype.destroy = function() { + this.shapesData = null; + this.globalData = null; + this.canvasContext = null; + this.stylesList.length = 0; + this.itemsData.length = 0; + }; + extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement, ITextElement], CVTextElement); + CVTextElement.prototype.tHelper = createTag("canvas").getContext("2d"); + CVTextElement.prototype.buildNewText = function() { + var documentData = this.textProperty.currentData; + this.renderedLetters = createSizedArray(documentData.l ? documentData.l.length : 0); + var hasFill = false; + if (documentData.fc) { + hasFill = true; + this.values.fill = this.buildColor(documentData.fc); + } else { + this.values.fill = "rgba(0,0,0,0)"; + } + this.fill = hasFill; + var hasStroke = false; + if (documentData.sc) { + hasStroke = true; + this.values.stroke = this.buildColor(documentData.sc); + this.values.sWidth = documentData.sw; + } + var fontData = this.globalData.fontManager.getFontByName(documentData.f); + var i; + var len; + var letters = documentData.l; + var matrixHelper = this.mHelper; + this.stroke = hasStroke; + this.values.fValue = documentData.finalSize + "px " + this.globalData.fontManager.getFontByName(documentData.f).fFamily; + len = documentData.finalText.length; + var charData; + var shapeData; + var k2; + var kLen; + var shapes; + var j2; + var jLen; + var pathNodes; + var commands; + var pathArr; + var singleShape = this.data.singleShape; + var trackingOffset = documentData.tr * 0.001 * documentData.finalSize; + var xPos = 0; + var yPos = 0; + var firstLine = true; + var cnt = 0; + for (i = 0;i < len; i += 1) { + charData = this.globalData.fontManager.getCharData(documentData.finalText[i], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily); + shapeData = charData && charData.data || {}; + matrixHelper.reset(); + if (singleShape && letters[i].n) { + xPos = -trackingOffset; + yPos += documentData.yOffset; + yPos += firstLine ? 1 : 0; + firstLine = false; + } + shapes = shapeData.shapes ? shapeData.shapes[0].it : []; + jLen = shapes.length; + matrixHelper.scale(documentData.finalSize / 100, documentData.finalSize / 100); + if (singleShape) { + this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i].line, xPos, yPos); + } + commands = createSizedArray(jLen - 1); + var commandsCounter = 0; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (shapes[j2].ty === "sh") { + kLen = shapes[j2].ks.k.i.length; + pathNodes = shapes[j2].ks.k; + pathArr = []; + for (k2 = 1;k2 < kLen; k2 += 1) { + if (k2 === 1) { + pathArr.push(matrixHelper.applyToX(pathNodes.v[0][0], pathNodes.v[0][1], 0), matrixHelper.applyToY(pathNodes.v[0][0], pathNodes.v[0][1], 0)); + } + pathArr.push(matrixHelper.applyToX(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToY(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToX(pathNodes.i[k2][0], pathNodes.i[k2][1], 0), matrixHelper.applyToY(pathNodes.i[k2][0], pathNodes.i[k2][1], 0), matrixHelper.applyToX(pathNodes.v[k2][0], pathNodes.v[k2][1], 0), matrixHelper.applyToY(pathNodes.v[k2][0], pathNodes.v[k2][1], 0)); + } + pathArr.push(matrixHelper.applyToX(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToY(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToX(pathNodes.i[0][0], pathNodes.i[0][1], 0), matrixHelper.applyToY(pathNodes.i[0][0], pathNodes.i[0][1], 0), matrixHelper.applyToX(pathNodes.v[0][0], pathNodes.v[0][1], 0), matrixHelper.applyToY(pathNodes.v[0][0], pathNodes.v[0][1], 0)); + commands[commandsCounter] = pathArr; + commandsCounter += 1; + } + } + if (singleShape) { + xPos += letters[i].l; + xPos += trackingOffset; + } + if (this.textSpans[cnt]) { + this.textSpans[cnt].elem = commands; + } else { + this.textSpans[cnt] = { elem: commands }; + } + cnt += 1; + } + }; + CVTextElement.prototype.renderInnerContent = function() { + var ctx = this.canvasContext; + ctx.font = this.values.fValue; + ctx.lineCap = "butt"; + ctx.lineJoin = "miter"; + ctx.miterLimit = 4; + if (!this.data.singleShape) { + this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag); + } + var i; + var len; + var j2; + var jLen; + var k2; + var kLen; + var renderedLetters = this.textAnimator.renderedLetters; + var letters = this.textProperty.currentData.l; + len = letters.length; + var renderedLetter; + var lastFill = null; + var lastStroke = null; + var lastStrokeW = null; + var commands; + var pathArr; + for (i = 0;i < len; i += 1) { + if (!letters[i].n) { + renderedLetter = renderedLetters[i]; + if (renderedLetter) { + this.globalData.renderer.save(); + this.globalData.renderer.ctxTransform(renderedLetter.p); + this.globalData.renderer.ctxOpacity(renderedLetter.o); + } + if (this.fill) { + if (renderedLetter && renderedLetter.fc) { + if (lastFill !== renderedLetter.fc) { + lastFill = renderedLetter.fc; + ctx.fillStyle = renderedLetter.fc; + } + } else if (lastFill !== this.values.fill) { + lastFill = this.values.fill; + ctx.fillStyle = this.values.fill; + } + commands = this.textSpans[i].elem; + jLen = commands.length; + this.globalData.canvasContext.beginPath(); + for (j2 = 0;j2 < jLen; j2 += 1) { + pathArr = commands[j2]; + kLen = pathArr.length; + this.globalData.canvasContext.moveTo(pathArr[0], pathArr[1]); + for (k2 = 2;k2 < kLen; k2 += 6) { + this.globalData.canvasContext.bezierCurveTo(pathArr[k2], pathArr[k2 + 1], pathArr[k2 + 2], pathArr[k2 + 3], pathArr[k2 + 4], pathArr[k2 + 5]); + } + } + this.globalData.canvasContext.closePath(); + this.globalData.canvasContext.fill(); + } + if (this.stroke) { + if (renderedLetter && renderedLetter.sw) { + if (lastStrokeW !== renderedLetter.sw) { + lastStrokeW = renderedLetter.sw; + ctx.lineWidth = renderedLetter.sw; + } + } else if (lastStrokeW !== this.values.sWidth) { + lastStrokeW = this.values.sWidth; + ctx.lineWidth = this.values.sWidth; + } + if (renderedLetter && renderedLetter.sc) { + if (lastStroke !== renderedLetter.sc) { + lastStroke = renderedLetter.sc; + ctx.strokeStyle = renderedLetter.sc; + } + } else if (lastStroke !== this.values.stroke) { + lastStroke = this.values.stroke; + ctx.strokeStyle = this.values.stroke; + } + commands = this.textSpans[i].elem; + jLen = commands.length; + this.globalData.canvasContext.beginPath(); + for (j2 = 0;j2 < jLen; j2 += 1) { + pathArr = commands[j2]; + kLen = pathArr.length; + this.globalData.canvasContext.moveTo(pathArr[0], pathArr[1]); + for (k2 = 2;k2 < kLen; k2 += 6) { + this.globalData.canvasContext.bezierCurveTo(pathArr[k2], pathArr[k2 + 1], pathArr[k2 + 2], pathArr[k2 + 3], pathArr[k2 + 4], pathArr[k2 + 5]); + } + } + this.globalData.canvasContext.closePath(); + this.globalData.canvasContext.stroke(); + } + if (renderedLetter) { + this.globalData.renderer.restore(); + } + } + } + }; + extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement], CVImageElement); + CVImageElement.prototype.initElement = SVGShapeElement.prototype.initElement; + CVImageElement.prototype.prepareFrame = IImageElement.prototype.prepareFrame; + CVImageElement.prototype.createContent = function() { + if (this.img.width && (this.assetData.w !== this.img.width || this.assetData.h !== this.img.height)) { + var canvas = createTag("canvas"); + canvas.width = this.assetData.w; + canvas.height = this.assetData.h; + var ctx = canvas.getContext("2d"); + var imgW = this.img.width; + var imgH = this.img.height; + var imgRel = imgW / imgH; + var canvasRel = this.assetData.w / this.assetData.h; + var widthCrop; + var heightCrop; + var par = this.assetData.pr || this.globalData.renderConfig.imagePreserveAspectRatio; + if (imgRel > canvasRel && par === "xMidYMid slice" || imgRel < canvasRel && par !== "xMidYMid slice") { + heightCrop = imgH; + widthCrop = heightCrop * canvasRel; + } else { + widthCrop = imgW; + heightCrop = widthCrop / canvasRel; + } + ctx.drawImage(this.img, (imgW - widthCrop) / 2, (imgH - heightCrop) / 2, widthCrop, heightCrop, 0, 0, this.assetData.w, this.assetData.h); + this.img = canvas; + } + }; + CVImageElement.prototype.renderInnerContent = function() { + this.canvasContext.drawImage(this.img, 0, 0); + }; + CVImageElement.prototype.destroy = function() { + this.img = null; + }; + extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement], CVSolidElement); + CVSolidElement.prototype.initElement = SVGShapeElement.prototype.initElement; + CVSolidElement.prototype.prepareFrame = IImageElement.prototype.prepareFrame; + CVSolidElement.prototype.renderInnerContent = function() { + var ctx = this.canvasContext; + ctx.fillStyle = this.data.sc; + ctx.fillRect(0, 0, this.data.sw, this.data.sh); + }; + extendPrototype([BaseRenderer], CanvasRendererBase); + CanvasRendererBase.prototype.createShape = function(data2) { + return new CVShapeElement(data2, this.globalData, this); + }; + CanvasRendererBase.prototype.createText = function(data2) { + return new CVTextElement(data2, this.globalData, this); + }; + CanvasRendererBase.prototype.createImage = function(data2) { + return new CVImageElement(data2, this.globalData, this); + }; + CanvasRendererBase.prototype.createSolid = function(data2) { + return new CVSolidElement(data2, this.globalData, this); + }; + CanvasRendererBase.prototype.createNull = SVGRenderer.prototype.createNull; + CanvasRendererBase.prototype.ctxTransform = function(props) { + if (props[0] === 1 && props[1] === 0 && props[4] === 0 && props[5] === 1 && props[12] === 0 && props[13] === 0) { + return; + } + if (!this.renderConfig.clearCanvas) { + this.canvasContext.transform(props[0], props[1], props[4], props[5], props[12], props[13]); + return; + } + this.transformMat.cloneFromProps(props); + var cProps = this.contextData.cTr.props; + this.transformMat.transform(cProps[0], cProps[1], cProps[2], cProps[3], cProps[4], cProps[5], cProps[6], cProps[7], cProps[8], cProps[9], cProps[10], cProps[11], cProps[12], cProps[13], cProps[14], cProps[15]); + this.contextData.cTr.cloneFromProps(this.transformMat.props); + var trProps = this.contextData.cTr.props; + this.canvasContext.setTransform(trProps[0], trProps[1], trProps[4], trProps[5], trProps[12], trProps[13]); + }; + CanvasRendererBase.prototype.ctxOpacity = function(op) { + if (!this.renderConfig.clearCanvas) { + this.canvasContext.globalAlpha *= op < 0 ? 0 : op; + this.globalData.currentGlobalAlpha = this.contextData.cO; + return; + } + this.contextData.cO *= op < 0 ? 0 : op; + if (this.globalData.currentGlobalAlpha !== this.contextData.cO) { + this.canvasContext.globalAlpha = this.contextData.cO; + this.globalData.currentGlobalAlpha = this.contextData.cO; + } + }; + CanvasRendererBase.prototype.reset = function() { + if (!this.renderConfig.clearCanvas) { + this.canvasContext.restore(); + return; + } + this.contextData.reset(); + }; + CanvasRendererBase.prototype.save = function(actionFlag) { + if (!this.renderConfig.clearCanvas) { + this.canvasContext.save(); + return; + } + if (actionFlag) { + this.canvasContext.save(); + } + var props = this.contextData.cTr.props; + if (this.contextData._length <= this.contextData.cArrPos) { + this.contextData.duplicate(); + } + var i; + var arr = this.contextData.saved[this.contextData.cArrPos]; + for (i = 0;i < 16; i += 1) { + arr[i] = props[i]; + } + this.contextData.savedOp[this.contextData.cArrPos] = this.contextData.cO; + this.contextData.cArrPos += 1; + }; + CanvasRendererBase.prototype.restore = function(actionFlag) { + if (!this.renderConfig.clearCanvas) { + this.canvasContext.restore(); + return; + } + if (actionFlag) { + this.canvasContext.restore(); + this.globalData.blendMode = "source-over"; + } + this.contextData.cArrPos -= 1; + var popped = this.contextData.saved[this.contextData.cArrPos]; + var i; + var arr = this.contextData.cTr.props; + for (i = 0;i < 16; i += 1) { + arr[i] = popped[i]; + } + this.canvasContext.setTransform(popped[0], popped[1], popped[4], popped[5], popped[12], popped[13]); + popped = this.contextData.savedOp[this.contextData.cArrPos]; + this.contextData.cO = popped; + if (this.globalData.currentGlobalAlpha !== popped) { + this.canvasContext.globalAlpha = popped; + this.globalData.currentGlobalAlpha = popped; + } + }; + CanvasRendererBase.prototype.configAnimation = function(animData) { + if (this.animationItem.wrapper) { + this.animationItem.container = createTag("canvas"); + var containerStyle = this.animationItem.container.style; + containerStyle.width = "100%"; + containerStyle.height = "100%"; + var origin = "0px 0px 0px"; + containerStyle.transformOrigin = origin; + containerStyle.mozTransformOrigin = origin; + containerStyle.webkitTransformOrigin = origin; + containerStyle["-webkit-transform"] = origin; + containerStyle.contentVisibility = this.renderConfig.contentVisibility; + this.animationItem.wrapper.appendChild(this.animationItem.container); + this.canvasContext = this.animationItem.container.getContext("2d"); + if (this.renderConfig.className) { + this.animationItem.container.setAttribute("class", this.renderConfig.className); + } + if (this.renderConfig.id) { + this.animationItem.container.setAttribute("id", this.renderConfig.id); + } + } else { + this.canvasContext = this.renderConfig.context; + } + this.data = animData; + this.layers = animData.layers; + this.transformCanvas = { + w: animData.w, + h: animData.h, + sx: 0, + sy: 0, + tx: 0, + ty: 0 + }; + this.setupGlobalData(animData, document.body); + this.globalData.canvasContext = this.canvasContext; + this.globalData.renderer = this; + this.globalData.isDashed = false; + this.globalData.progressiveLoad = this.renderConfig.progressiveLoad; + this.globalData.transformCanvas = this.transformCanvas; + this.elements = createSizedArray(animData.layers.length); + this.updateContainerSize(); + }; + CanvasRendererBase.prototype.updateContainerSize = function() { + this.reset(); + var elementWidth; + var elementHeight; + if (this.animationItem.wrapper && this.animationItem.container) { + elementWidth = this.animationItem.wrapper.offsetWidth; + elementHeight = this.animationItem.wrapper.offsetHeight; + this.animationItem.container.setAttribute("width", elementWidth * this.renderConfig.dpr); + this.animationItem.container.setAttribute("height", elementHeight * this.renderConfig.dpr); + } else { + elementWidth = this.canvasContext.canvas.width * this.renderConfig.dpr; + elementHeight = this.canvasContext.canvas.height * this.renderConfig.dpr; + } + var elementRel; + var animationRel; + if (this.renderConfig.preserveAspectRatio.indexOf("meet") !== -1 || this.renderConfig.preserveAspectRatio.indexOf("slice") !== -1) { + var par = this.renderConfig.preserveAspectRatio.split(" "); + var fillType = par[1] || "meet"; + var pos = par[0] || "xMidYMid"; + var xPos = pos.substr(0, 4); + var yPos = pos.substr(4); + elementRel = elementWidth / elementHeight; + animationRel = this.transformCanvas.w / this.transformCanvas.h; + if (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice") { + this.transformCanvas.sx = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr); + this.transformCanvas.sy = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr); + } else { + this.transformCanvas.sx = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr); + this.transformCanvas.sy = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr); + } + if (xPos === "xMid" && (animationRel < elementRel && fillType === "meet" || animationRel > elementRel && fillType === "slice")) { + this.transformCanvas.tx = (elementWidth - this.transformCanvas.w * (elementHeight / this.transformCanvas.h)) / 2 * this.renderConfig.dpr; + } else if (xPos === "xMax" && (animationRel < elementRel && fillType === "meet" || animationRel > elementRel && fillType === "slice")) { + this.transformCanvas.tx = (elementWidth - this.transformCanvas.w * (elementHeight / this.transformCanvas.h)) * this.renderConfig.dpr; + } else { + this.transformCanvas.tx = 0; + } + if (yPos === "YMid" && (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice")) { + this.transformCanvas.ty = (elementHeight - this.transformCanvas.h * (elementWidth / this.transformCanvas.w)) / 2 * this.renderConfig.dpr; + } else if (yPos === "YMax" && (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice")) { + this.transformCanvas.ty = (elementHeight - this.transformCanvas.h * (elementWidth / this.transformCanvas.w)) * this.renderConfig.dpr; + } else { + this.transformCanvas.ty = 0; + } + } else if (this.renderConfig.preserveAspectRatio === "none") { + this.transformCanvas.sx = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr); + this.transformCanvas.sy = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr); + this.transformCanvas.tx = 0; + this.transformCanvas.ty = 0; + } else { + this.transformCanvas.sx = this.renderConfig.dpr; + this.transformCanvas.sy = this.renderConfig.dpr; + this.transformCanvas.tx = 0; + this.transformCanvas.ty = 0; + } + this.transformCanvas.props = [this.transformCanvas.sx, 0, 0, 0, 0, this.transformCanvas.sy, 0, 0, 0, 0, 1, 0, this.transformCanvas.tx, this.transformCanvas.ty, 0, 1]; + this.ctxTransform(this.transformCanvas.props); + this.canvasContext.beginPath(); + this.canvasContext.rect(0, 0, this.transformCanvas.w, this.transformCanvas.h); + this.canvasContext.closePath(); + this.canvasContext.clip(); + this.renderFrame(this.renderedFrame, true); + }; + CanvasRendererBase.prototype.destroy = function() { + if (this.renderConfig.clearCanvas && this.animationItem.wrapper) { + this.animationItem.wrapper.innerText = ""; + } + var i; + var len = this.layers ? this.layers.length : 0; + for (i = len - 1;i >= 0; i -= 1) { + if (this.elements[i]) { + this.elements[i].destroy(); + } + } + this.elements.length = 0; + this.globalData.canvasContext = null; + this.animationItem.container = null; + this.destroyed = true; + }; + CanvasRendererBase.prototype.renderFrame = function(num, forceRender) { + if (this.renderedFrame === num && this.renderConfig.clearCanvas === true && !forceRender || this.destroyed || num === -1) { + return; + } + this.renderedFrame = num; + this.globalData.frameNum = num - this.animationItem._isFirstFrame; + this.globalData.frameId += 1; + this.globalData._mdf = !this.renderConfig.clearCanvas || forceRender; + this.globalData.projectInterface.currentFrame = num; + var i; + var len = this.layers.length; + if (!this.completeLayers) { + this.checkLayers(num); + } + for (i = 0;i < len; i += 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].prepareFrame(num - this.layers[i].st); + } + } + if (this.globalData._mdf) { + if (this.renderConfig.clearCanvas === true) { + this.canvasContext.clearRect(0, 0, this.transformCanvas.w, this.transformCanvas.h); + } else { + this.save(); + } + for (i = len - 1;i >= 0; i -= 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].renderFrame(); + } + } + if (this.renderConfig.clearCanvas !== true) { + this.restore(); + } + } + }; + CanvasRendererBase.prototype.buildItem = function(pos) { + var elements = this.elements; + if (elements[pos] || this.layers[pos].ty === 99) { + return; + } + var element = this.createItem(this.layers[pos], this, this.globalData); + elements[pos] = element; + element.initExpressions(); + }; + CanvasRendererBase.prototype.checkPendingElements = function() { + while (this.pendingElements.length) { + var element = this.pendingElements.pop(); + element.checkParenting(); + } + }; + CanvasRendererBase.prototype.hide = function() { + this.animationItem.container.style.display = "none"; + }; + CanvasRendererBase.prototype.show = function() { + this.animationItem.container.style.display = "block"; + }; + extendPrototype([CanvasRendererBase, ICompElement, CVBaseElement], CVCompElement); + CVCompElement.prototype.renderInnerContent = function() { + var ctx = this.canvasContext; + ctx.beginPath(); + ctx.moveTo(0, 0); + ctx.lineTo(this.data.w, 0); + ctx.lineTo(this.data.w, this.data.h); + ctx.lineTo(0, this.data.h); + ctx.lineTo(0, 0); + ctx.clip(); + var i; + var len = this.layers.length; + for (i = len - 1;i >= 0; i -= 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].renderFrame(); + } + } + }; + CVCompElement.prototype.destroy = function() { + var i; + var len = this.layers.length; + for (i = len - 1;i >= 0; i -= 1) { + if (this.elements[i]) { + this.elements[i].destroy(); + } + } + this.layers = null; + this.elements = null; + }; + CVCompElement.prototype.createComp = function(data2) { + return new CVCompElement(data2, this.globalData, this); + }; + extendPrototype([CanvasRendererBase], CanvasRenderer); + CanvasRenderer.prototype.createComp = function(data2) { + return new CVCompElement(data2, this.globalData, this); + }; + registerRenderer("canvas", CanvasRenderer); + ShapeModifiers.registerModifier("tm", TrimModifier); + ShapeModifiers.registerModifier("pb", PuckerAndBloatModifier); + ShapeModifiers.registerModifier("rp", RepeaterModifier); + ShapeModifiers.registerModifier("rd", RoundCornersModifier); + const Expressions = function() { + var ob2 = {}; + ob2.initExpressions = initExpressions; + function initExpressions(animation) { + var stackCount = 0; + var registers = []; + function pushExpression() { + stackCount += 1; + } + function popExpression() { + stackCount -= 1; + if (stackCount === 0) { + releaseInstances(); + } + } + function registerExpressionProperty(expression) { + if (registers.indexOf(expression) === -1) { + registers.push(expression); + } + } + function releaseInstances() { + var i; + var len = registers.length; + for (i = 0;i < len; i += 1) { + registers[i].release(); + } + registers.length = 0; + } + animation.renderer.compInterface = CompExpressionInterface(animation.renderer); + animation.renderer.globalData.projectInterface.registerComposition(animation.renderer); + animation.renderer.globalData.pushExpression = pushExpression; + animation.renderer.globalData.popExpression = popExpression; + animation.renderer.globalData.registerExpressionProperty = registerExpressionProperty; + } + return ob2; + }(); + propTypes = { + SHAPE: "shape" + }; + const ExpressionManager = function() { + var ob = {}; + var Math = BMMath; + var window = null; + var document = null; + var XMLHttpRequest = null; + var fetch = null; + var frames = null; + initialize$2(BMMath); + function $bm_isInstanceOfArray(arr) { + return arr.constructor === Array || arr.constructor === Float32Array; + } + function isNumerable(tOfV, v) { + return tOfV === "number" || tOfV === "boolean" || tOfV === "string" || v instanceof Number; + } + function $bm_neg(a) { + var tOfA = typeof a; + if (tOfA === "number" || tOfA === "boolean" || a instanceof Number) { + return -a; + } + if ($bm_isInstanceOfArray(a)) { + var i; + var lenA = a.length; + var retArr = []; + for (i = 0;i < lenA; i += 1) { + retArr[i] = -a[i]; + } + return retArr; + } + if (a.propType) { + return a.v; + } + return -a; + } + var easeInBez = BezierFactory.getBezierEasing(0.333, 0, 0.833, 0.833, "easeIn").get; + var easeOutBez = BezierFactory.getBezierEasing(0.167, 0.167, 0.667, 1, "easeOut").get; + var easeInOutBez = BezierFactory.getBezierEasing(0.33, 0, 0.667, 1, "easeInOut").get; + function sum(a, b) { + var tOfA = typeof a; + var tOfB = typeof b; + if (tOfA === "string" || tOfB === "string") { + return a + b; + } + if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { + return a + b; + } + if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { + a = a.slice(0); + a[0] += b; + return a; + } + if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { + b = b.slice(0); + b[0] = a + b[0]; + return b; + } + if ($bm_isInstanceOfArray(a) && $bm_isInstanceOfArray(b)) { + var i = 0; + var lenA = a.length; + var lenB = b.length; + var retArr = []; + while (i < lenA || i < lenB) { + if ((typeof a[i] === "number" || a[i] instanceof Number) && (typeof b[i] === "number" || b[i] instanceof Number)) { + retArr[i] = a[i] + b[i]; + } else { + retArr[i] = b[i] === undefined ? a[i] : a[i] || b[i]; + } + i += 1; + } + return retArr; + } + return 0; + } + var add = sum; + function sub(a, b) { + var tOfA = typeof a; + var tOfB = typeof b; + if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { + if (tOfA === "string") { + a = parseInt(a, 10); + } + if (tOfB === "string") { + b = parseInt(b, 10); + } + return a - b; + } + if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { + a = a.slice(0); + a[0] -= b; + return a; + } + if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { + b = b.slice(0); + b[0] = a - b[0]; + return b; + } + if ($bm_isInstanceOfArray(a) && $bm_isInstanceOfArray(b)) { + var i = 0; + var lenA = a.length; + var lenB = b.length; + var retArr = []; + while (i < lenA || i < lenB) { + if ((typeof a[i] === "number" || a[i] instanceof Number) && (typeof b[i] === "number" || b[i] instanceof Number)) { + retArr[i] = a[i] - b[i]; + } else { + retArr[i] = b[i] === undefined ? a[i] : a[i] || b[i]; + } + i += 1; + } + return retArr; + } + return 0; + } + function mul(a, b) { + var tOfA = typeof a; + var tOfB = typeof b; + var arr; + if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { + return a * b; + } + var i; + var len; + if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { + len = a.length; + arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = a[i] * b; + } + return arr; + } + if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { + len = b.length; + arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = a * b[i]; + } + return arr; + } + return 0; + } + function div(a, b) { + var tOfA = typeof a; + var tOfB = typeof b; + var arr; + if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { + return a / b; + } + var i; + var len; + if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { + len = a.length; + arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = a[i] / b; + } + return arr; + } + if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { + len = b.length; + arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = a / b[i]; + } + return arr; + } + return 0; + } + function mod(a, b) { + if (typeof a === "string") { + a = parseInt(a, 10); + } + if (typeof b === "string") { + b = parseInt(b, 10); + } + return a % b; + } + var $bm_sum = sum; + var $bm_sub = sub; + var $bm_mul = mul; + var $bm_div = div; + var $bm_mod = mod; + function clamp(num, min, max) { + if (min > max) { + var mm = max; + max = min; + min = mm; + } + return Math.min(Math.max(num, min), max); + } + function radiansToDegrees(val2) { + return val2 / degToRads; + } + var radians_to_degrees = radiansToDegrees; + function degreesToRadians(val2) { + return val2 * degToRads; + } + var degrees_to_radians = radiansToDegrees; + var helperLengthArray = [0, 0, 0, 0, 0, 0]; + function length(arr1, arr2) { + if (typeof arr1 === "number" || arr1 instanceof Number) { + arr2 = arr2 || 0; + return Math.abs(arr1 - arr2); + } + if (!arr2) { + arr2 = helperLengthArray; + } + var i; + var len = Math.min(arr1.length, arr2.length); + var addedLength = 0; + for (i = 0;i < len; i += 1) { + addedLength += Math.pow(arr2[i] - arr1[i], 2); + } + return Math.sqrt(addedLength); + } + function normalize(vec) { + return div(vec, length(vec)); + } + function rgbToHsl(val2) { + var r = val2[0]; + var g3 = val2[1]; + var b = val2[2]; + var max = Math.max(r, g3, b); + var min = Math.min(r, g3, b); + var h; + var s; + var l2 = (max + min) / 2; + if (max === min) { + h = 0; + s = 0; + } else { + var d = max - min; + s = l2 > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g3 - b) / d + (g3 < b ? 6 : 0); + break; + case g3: + h = (b - r) / d + 2; + break; + case b: + h = (r - g3) / d + 4; + break; + default: + break; + } + h /= 6; + } + return [h, s, l2, val2[3]]; + } + function hue2rgb(p, q2, t2) { + if (t2 < 0) + t2 += 1; + if (t2 > 1) + t2 -= 1; + if (t2 < 1 / 6) + return p + (q2 - p) * 6 * t2; + if (t2 < 1 / 2) + return q2; + if (t2 < 2 / 3) + return p + (q2 - p) * (2 / 3 - t2) * 6; + return p; + } + function hslToRgb(val2) { + var h = val2[0]; + var s = val2[1]; + var l2 = val2[2]; + var r; + var g3; + var b; + if (s === 0) { + r = l2; + b = l2; + g3 = l2; + } else { + var q2 = l2 < 0.5 ? l2 * (1 + s) : l2 + s - l2 * s; + var p = 2 * l2 - q2; + r = hue2rgb(p, q2, h + 1 / 3); + g3 = hue2rgb(p, q2, h); + b = hue2rgb(p, q2, h - 1 / 3); + } + return [r, g3, b, val2[3]]; + } + function linear(t2, tMin, tMax, value1, value2) { + if (value1 === undefined || value2 === undefined) { + value1 = tMin; + value2 = tMax; + tMin = 0; + tMax = 1; + } + if (tMax < tMin) { + var _tMin = tMax; + tMax = tMin; + tMin = _tMin; + } + if (t2 <= tMin) { + return value1; + } + if (t2 >= tMax) { + return value2; + } + var perc = tMax === tMin ? 0 : (t2 - tMin) / (tMax - tMin); + if (!value1.length) { + return value1 + (value2 - value1) * perc; + } + var i; + var len = value1.length; + var arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = value1[i] + (value2[i] - value1[i]) * perc; + } + return arr; + } + function random(min, max) { + if (max === undefined) { + if (min === undefined) { + min = 0; + max = 1; + } else { + max = min; + min = undefined; + } + } + if (max.length) { + var i; + var len = max.length; + if (!min) { + min = createTypedArray("float32", len); + } + var arr = createTypedArray("float32", len); + var rnd = BMMath.random(); + for (i = 0;i < len; i += 1) { + arr[i] = min[i] + rnd * (max[i] - min[i]); + } + return arr; + } + if (min === undefined) { + min = 0; + } + var rndm = BMMath.random(); + return min + rndm * (max - min); + } + function createPath(points, inTangents, outTangents, closed) { + var i; + var len = points.length; + var path = shapePool.newElement(); + path.setPathData(!!closed, len); + var arrPlaceholder = [0, 0]; + var inVertexPoint; + var outVertexPoint; + for (i = 0;i < len; i += 1) { + inVertexPoint = inTangents && inTangents[i] ? inTangents[i] : arrPlaceholder; + outVertexPoint = outTangents && outTangents[i] ? outTangents[i] : arrPlaceholder; + path.setTripleAt(points[i][0], points[i][1], outVertexPoint[0] + points[i][0], outVertexPoint[1] + points[i][1], inVertexPoint[0] + points[i][0], inVertexPoint[1] + points[i][1], i, true); + } + return path; + } + function initiateExpression(elem, data, property) { + var val = data.x; + var needsVelocity = /velocity(?![\w\d])/.test(val); + var _needsRandom = val.indexOf("random") !== -1; + var elemType = elem.data.ty; + var transform; + var $bm_transform; + var content; + var effect; + var thisProperty = property; + thisProperty.valueAtTime = thisProperty.getValueAtTime; + Object.defineProperty(thisProperty, "value", { + get: function() { + return thisProperty.v; + } + }); + elem.comp.frameDuration = 1 / elem.comp.globalData.frameRate; + elem.comp.displayStartTime = 0; + var inPoint = elem.data.ip / elem.comp.globalData.frameRate; + var outPoint = elem.data.op / elem.comp.globalData.frameRate; + var width = elem.data.sw ? elem.data.sw : 0; + var height = elem.data.sh ? elem.data.sh : 0; + var name = elem.data.nm; + var loopIn; + var loop_in; + var loopOut; + var loop_out; + var smooth; + var toWorld; + var fromWorld; + var fromComp; + var toComp; + var fromCompToSurface; + var position; + var rotation; + var anchorPoint; + var scale; + var thisLayer; + var thisComp; + var mask; + var valueAtTime; + var velocityAtTime; + var scoped_bm_rt; + var expression_function = eval("[function _expression_function(){" + val + ";scoped_bm_rt=$bm_rt}]")[0]; + var numKeys = property.kf ? data.k.length : 0; + var active = !this.data || this.data.hd !== true; + var wiggle = function wiggle(freq, amp) { + var iWiggle; + var j2; + var lenWiggle = this.pv.length ? this.pv.length : 1; + var addedAmps = createTypedArray("float32", lenWiggle); + freq = 5; + var iterations = Math.floor(time * freq); + iWiggle = 0; + j2 = 0; + while (iWiggle < iterations) { + for (j2 = 0;j2 < lenWiggle; j2 += 1) { + addedAmps[j2] += -amp + amp * 2 * BMMath.random(); + } + iWiggle += 1; + } + var periods = time * freq; + var perc = periods - Math.floor(periods); + var arr = createTypedArray("float32", lenWiggle); + if (lenWiggle > 1) { + for (j2 = 0;j2 < lenWiggle; j2 += 1) { + arr[j2] = this.pv[j2] + addedAmps[j2] + (-amp + amp * 2 * BMMath.random()) * perc; + } + return arr; + } + return this.pv + addedAmps[0] + (-amp + amp * 2 * BMMath.random()) * perc; + }.bind(this); + if (thisProperty.loopIn) { + loopIn = thisProperty.loopIn.bind(thisProperty); + loop_in = loopIn; + } + if (thisProperty.loopOut) { + loopOut = thisProperty.loopOut.bind(thisProperty); + loop_out = loopOut; + } + if (thisProperty.smooth) { + smooth = thisProperty.smooth.bind(thisProperty); + } + function loopInDuration(type, duration) { + return loopIn(type, duration, true); + } + function loopOutDuration(type, duration) { + return loopOut(type, duration, true); + } + if (this.getValueAtTime) { + valueAtTime = this.getValueAtTime.bind(this); + } + if (this.getVelocityAtTime) { + velocityAtTime = this.getVelocityAtTime.bind(this); + } + var comp = elem.comp.globalData.projectInterface.bind(elem.comp.globalData.projectInterface); + function lookAt(elem1, elem2) { + var fVec = [elem2[0] - elem1[0], elem2[1] - elem1[1], elem2[2] - elem1[2]]; + var pitch = Math.atan2(fVec[0], Math.sqrt(fVec[1] * fVec[1] + fVec[2] * fVec[2])) / degToRads; + var yaw = -Math.atan2(fVec[1], fVec[2]) / degToRads; + return [yaw, pitch, 0]; + } + function easeOut(t2, tMin, tMax, val1, val2) { + return applyEase(easeOutBez, t2, tMin, tMax, val1, val2); + } + function easeIn(t2, tMin, tMax, val1, val2) { + return applyEase(easeInBez, t2, tMin, tMax, val1, val2); + } + function ease(t2, tMin, tMax, val1, val2) { + return applyEase(easeInOutBez, t2, tMin, tMax, val1, val2); + } + function applyEase(fn, t2, tMin, tMax, val1, val2) { + if (val1 === undefined) { + val1 = tMin; + val2 = tMax; + } else { + t2 = (t2 - tMin) / (tMax - tMin); + } + if (t2 > 1) { + t2 = 1; + } else if (t2 < 0) { + t2 = 0; + } + var mult = fn(t2); + if ($bm_isInstanceOfArray(val1)) { + var iKey; + var lenKey = val1.length; + var arr = createTypedArray("float32", lenKey); + for (iKey = 0;iKey < lenKey; iKey += 1) { + arr[iKey] = (val2[iKey] - val1[iKey]) * mult + val1[iKey]; + } + return arr; + } + return (val2 - val1) * mult + val1; + } + function nearestKey(time2) { + var iKey; + var lenKey = data.k.length; + var index2; + var keyTime; + if (!data.k.length || typeof data.k[0] === "number") { + index2 = 0; + keyTime = 0; + } else { + index2 = -1; + time2 *= elem.comp.globalData.frameRate; + if (time2 < data.k[0].t) { + index2 = 1; + keyTime = data.k[0].t; + } else { + for (iKey = 0;iKey < lenKey - 1; iKey += 1) { + if (time2 === data.k[iKey].t) { + index2 = iKey + 1; + keyTime = data.k[iKey].t; + break; + } else if (time2 > data.k[iKey].t && time2 < data.k[iKey + 1].t) { + if (time2 - data.k[iKey].t > data.k[iKey + 1].t - time2) { + index2 = iKey + 2; + keyTime = data.k[iKey + 1].t; + } else { + index2 = iKey + 1; + keyTime = data.k[iKey].t; + } + break; + } + } + if (index2 === -1) { + index2 = iKey + 1; + keyTime = data.k[iKey].t; + } + } + } + var obKey = {}; + obKey.index = index2; + obKey.time = keyTime / elem.comp.globalData.frameRate; + return obKey; + } + function key(ind) { + var obKey; + var iKey; + var lenKey; + if (!data.k.length || typeof data.k[0] === "number") { + throw new Error("The property has no keyframe at index " + ind); + } + ind -= 1; + obKey = { + time: data.k[ind].t / elem.comp.globalData.frameRate, + value: [] + }; + var arr = Object.prototype.hasOwnProperty.call(data.k[ind], "s") ? data.k[ind].s : data.k[ind - 1].e; + lenKey = arr.length; + for (iKey = 0;iKey < lenKey; iKey += 1) { + obKey[iKey] = arr[iKey]; + obKey.value[iKey] = arr[iKey]; + } + return obKey; + } + function framesToTime(fr, fps) { + if (!fps) { + fps = elem.comp.globalData.frameRate; + } + return fr / fps; + } + function timeToFrames(t2, fps) { + if (!t2 && t2 !== 0) { + t2 = time; + } + if (!fps) { + fps = elem.comp.globalData.frameRate; + } + return t2 * fps; + } + function seedRandom(seed) { + BMMath.seedrandom(randSeed + seed); + } + function sourceRectAtTime() { + return elem.sourceRectAtTime(); + } + function substring(init, end) { + if (typeof value === "string") { + if (end === undefined) { + return value.substring(init); + } + return value.substring(init, end); + } + return ""; + } + function substr(init, end) { + if (typeof value === "string") { + if (end === undefined) { + return value.substr(init); + } + return value.substr(init, end); + } + return ""; + } + function posterizeTime(framesPerSecond) { + time = framesPerSecond === 0 ? 0 : Math.floor(time * framesPerSecond) / framesPerSecond; + value = valueAtTime(time); + } + var time; + var velocity; + var value; + var text; + var textIndex; + var textTotal; + var selectorValue; + var index = elem.data.ind; + var hasParent = !!(elem.hierarchy && elem.hierarchy.length); + var parent; + var randSeed = Math.floor(Math.random() * 1e6); + var globalData = elem.globalData; + function executeExpression(_value) { + value = _value; + if (this.frameExpressionId === elem.globalData.frameId && this.propType !== "textSelector") { + return value; + } + if (this.propType === "textSelector") { + textIndex = this.textIndex; + textTotal = this.textTotal; + selectorValue = this.selectorValue; + } + if (!thisLayer) { + text = elem.layerInterface.text; + thisLayer = elem.layerInterface; + thisComp = elem.comp.compInterface; + toWorld = thisLayer.toWorld.bind(thisLayer); + fromWorld = thisLayer.fromWorld.bind(thisLayer); + fromComp = thisLayer.fromComp.bind(thisLayer); + toComp = thisLayer.toComp.bind(thisLayer); + mask = thisLayer.mask ? thisLayer.mask.bind(thisLayer) : null; + fromCompToSurface = fromComp; + } + if (!transform) { + transform = elem.layerInterface("ADBE Transform Group"); + $bm_transform = transform; + if (transform) { + anchorPoint = transform.anchorPoint; + } + } + if (elemType === 4 && !content) { + content = thisLayer("ADBE Root Vectors Group"); + } + if (!effect) { + effect = thisLayer(4); + } + hasParent = !!(elem.hierarchy && elem.hierarchy.length); + if (hasParent && !parent) { + parent = elem.hierarchy[0].layerInterface; + } + time = this.comp.renderedFrame / this.comp.globalData.frameRate; + if (_needsRandom) { + seedRandom(randSeed + time); + } + if (needsVelocity) { + velocity = velocityAtTime(time); + } + expression_function(); + this.frameExpressionId = elem.globalData.frameId; + scoped_bm_rt = scoped_bm_rt.propType === propTypes.SHAPE ? scoped_bm_rt.v : scoped_bm_rt; + return scoped_bm_rt; + } + executeExpression.__preventDeadCodeRemoval = [$bm_transform, anchorPoint, time, velocity, inPoint, outPoint, width, height, name, loop_in, loop_out, smooth, toComp, fromCompToSurface, toWorld, fromWorld, mask, position, rotation, scale, thisComp, numKeys, active, wiggle, loopInDuration, loopOutDuration, comp, lookAt, easeOut, easeIn, ease, nearestKey, key, text, textIndex, textTotal, selectorValue, framesToTime, timeToFrames, sourceRectAtTime, substring, substr, posterizeTime, index, globalData]; + return executeExpression; + } + ob.initiateExpression = initiateExpression; + ob.__preventDeadCodeRemoval = [window, document, XMLHttpRequest, fetch, frames, $bm_neg, add, $bm_sum, $bm_sub, $bm_mul, $bm_div, $bm_mod, clamp, radians_to_degrees, degreesToRadians, degrees_to_radians, normalize, rgbToHsl, hslToRgb, linear, random, createPath]; + return ob; + }(); + const expressionHelpers = function() { + function searchExpressions(elem2, data2, prop) { + if (data2.x) { + prop.k = true; + prop.x = true; + prop.initiateExpression = ExpressionManager.initiateExpression; + prop.effectsSequence.push(prop.initiateExpression(elem2, data2, prop).bind(prop)); + } + } + function getValueAtTime(frameNum) { + frameNum *= this.elem.globalData.frameRate; + frameNum -= this.offsetTime; + if (frameNum !== this._cachingAtTime.lastFrame) { + this._cachingAtTime.lastIndex = this._cachingAtTime.lastFrame < frameNum ? this._cachingAtTime.lastIndex : 0; + this._cachingAtTime.value = this.interpolateValue(frameNum, this._cachingAtTime); + this._cachingAtTime.lastFrame = frameNum; + } + return this._cachingAtTime.value; + } + function getSpeedAtTime(frameNum) { + var delta = -0.01; + var v1 = this.getValueAtTime(frameNum); + var v2 = this.getValueAtTime(frameNum + delta); + var speed = 0; + if (v1.length) { + var i; + for (i = 0;i < v1.length; i += 1) { + speed += Math.pow(v2[i] - v1[i], 2); + } + speed = Math.sqrt(speed) * 100; + } else { + speed = 0; + } + return speed; + } + function getVelocityAtTime(frameNum) { + if (this.vel !== undefined) { + return this.vel; + } + var delta = -0.001; + var v1 = this.getValueAtTime(frameNum); + var v2 = this.getValueAtTime(frameNum + delta); + var velocity2; + if (v1.length) { + velocity2 = createTypedArray("float32", v1.length); + var i; + for (i = 0;i < v1.length; i += 1) { + velocity2[i] = (v2[i] - v1[i]) / delta; + } + } else { + velocity2 = (v2 - v1) / delta; + } + return velocity2; + } + function getStaticValueAtTime() { + return this.pv; + } + function setGroupProperty(propertyGroup) { + this.propertyGroup = propertyGroup; + } + return { + searchExpressions, + getSpeedAtTime, + getVelocityAtTime, + getValueAtTime, + getStaticValueAtTime, + setGroupProperty + }; + }(); + setExpressionsPlugin(Expressions); + initialize$1(); + initialize(); +} +var standalone; +var animationData; +var renderer; +var queryString; +var scripts; +var index2; +var myScript; +var readyStateCheckInterval; +var registeredEffects; +var idPrefix; +var emptyShapeData; +var propTypes; +// node_modules/three/examples/jsm/loaders/OBJLoader.js +var _vA2 = new Vector3; +var _vB2 = new Vector3; +var _vC2 = new Vector3; +var _ab = new Vector3; +var _cb = new Vector3; +var _color3 = new Color; +// node_modules/three/examples/jsm/loaders/PLYLoader.js +var _color5 = new Color; +// node_modules/three/examples/jsm/loaders/UltraHDRLoader.js +var SRGB_TO_LINEAR = Array(1024).fill(0).map((_2, value2) => Math.pow(value2 / 255 * 0.9478672986 + 0.0521327014, 2.4)); +// node_modules/three/examples/jsm/loaders/RGBMLoader.js +var UPNG = {}; +UPNG.toRGBA8 = function(out) { + var { width: w, height: h } = out; + if (out.tabs.acTL == null) + return [UPNG.toRGBA8.decodeImage(out.data, w, h, out).buffer]; + var frms = []; + if (out.frames[0].data == null) + out.frames[0].data = out.data; + var len = w * h * 4, img = new Uint8Array(len), empty = new Uint8Array(len), prev = new Uint8Array(len); + for (var i = 0;i < out.frames.length; i++) { + var frm = out.frames[i]; + var fx = frm.rect.x, fy = frm.rect.y, fw = frm.rect.width, fh = frm.rect.height; + var fdata = UPNG.toRGBA8.decodeImage(frm.data, fw, fh, out); + if (i != 0) + for (var j2 = 0;j2 < len; j2++) + prev[j2] = img[j2]; + if (frm.blend == 0) + UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 0); + else if (frm.blend == 1) + UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 1); + frms.push(img.buffer.slice(0)); + if (frm.dispose == 1) + UPNG._copyTile(empty, fw, fh, img, w, h, fx, fy, 0); + else if (frm.dispose == 2) + for (var j2 = 0;j2 < len; j2++) + img[j2] = prev[j2]; + } + return frms; +}; +UPNG.toRGBA8.decodeImage = function(data2, w, h, out) { + var area2 = w * h, bpp = UPNG.decode._getBPP(out); + var bpl = Math.ceil(w * bpp / 8); + var bf = new Uint8Array(area2 * 4), bf32 = new Uint32Array(bf.buffer); + var { ctype, depth } = out; + var rs = UPNG._bin.readUshort; + if (ctype == 6) { + var qarea = area2 << 2; + if (depth == 8) + for (var i = 0;i < qarea; i += 4) { + bf[i] = data2[i]; + bf[i + 1] = data2[i + 1]; + bf[i + 2] = data2[i + 2]; + bf[i + 3] = data2[i + 3]; + } + if (depth == 16) + for (var i = 0;i < qarea; i++) { + bf[i] = data2[i << 1]; + } + } else if (ctype == 2) { + var ts = out.tabs["tRNS"]; + if (ts == null) { + if (depth == 8) + for (var i = 0;i < area2; i++) { + var ti = i * 3; + bf32[i] = 255 << 24 | data2[ti + 2] << 16 | data2[ti + 1] << 8 | data2[ti]; + } + if (depth == 16) + for (var i = 0;i < area2; i++) { + var ti = i * 6; + bf32[i] = 255 << 24 | data2[ti + 4] << 16 | data2[ti + 2] << 8 | data2[ti]; + } + } else { + var tr = ts[0], tg = ts[1], tb = ts[2]; + if (depth == 8) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 3; + bf32[i] = 255 << 24 | data2[ti + 2] << 16 | data2[ti + 1] << 8 | data2[ti]; + if (data2[ti] == tr && data2[ti + 1] == tg && data2[ti + 2] == tb) + bf[qi + 3] = 0; + } + if (depth == 16) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 6; + bf32[i] = 255 << 24 | data2[ti + 4] << 16 | data2[ti + 2] << 8 | data2[ti]; + if (rs(data2, ti) == tr && rs(data2, ti + 2) == tg && rs(data2, ti + 4) == tb) + bf[qi + 3] = 0; + } + } + } else if (ctype == 3) { + var p = out.tabs["PLTE"], ap = out.tabs["tRNS"], tl = ap ? ap.length : 0; + if (depth == 1) + for (var y = 0;y < h; y++) { + var s0 = y * bpl, t0 = y * w; + for (var i = 0;i < w; i++) { + var qi = t0 + i << 2, j2 = data2[s0 + (i >> 3)] >> 7 - ((i & 7) << 0) & 1, cj = 3 * j2; + bf[qi] = p[cj]; + bf[qi + 1] = p[cj + 1]; + bf[qi + 2] = p[cj + 2]; + bf[qi + 3] = j2 < tl ? ap[j2] : 255; + } + } + if (depth == 2) + for (var y = 0;y < h; y++) { + var s0 = y * bpl, t0 = y * w; + for (var i = 0;i < w; i++) { + var qi = t0 + i << 2, j2 = data2[s0 + (i >> 2)] >> 6 - ((i & 3) << 1) & 3, cj = 3 * j2; + bf[qi] = p[cj]; + bf[qi + 1] = p[cj + 1]; + bf[qi + 2] = p[cj + 2]; + bf[qi + 3] = j2 < tl ? ap[j2] : 255; + } + } + if (depth == 4) + for (var y = 0;y < h; y++) { + var s0 = y * bpl, t0 = y * w; + for (var i = 0;i < w; i++) { + var qi = t0 + i << 2, j2 = data2[s0 + (i >> 1)] >> 4 - ((i & 1) << 2) & 15, cj = 3 * j2; + bf[qi] = p[cj]; + bf[qi + 1] = p[cj + 1]; + bf[qi + 2] = p[cj + 2]; + bf[qi + 3] = j2 < tl ? ap[j2] : 255; + } + } + if (depth == 8) + for (var i = 0;i < area2; i++) { + var qi = i << 2, j2 = data2[i], cj = 3 * j2; + bf[qi] = p[cj]; + bf[qi + 1] = p[cj + 1]; + bf[qi + 2] = p[cj + 2]; + bf[qi + 3] = j2 < tl ? ap[j2] : 255; + } + } else if (ctype == 4) { + if (depth == 8) + for (var i = 0;i < area2; i++) { + var qi = i << 2, di2 = i << 1, gr = data2[di2]; + bf[qi] = gr; + bf[qi + 1] = gr; + bf[qi + 2] = gr; + bf[qi + 3] = data2[di2 + 1]; + } + if (depth == 16) + for (var i = 0;i < area2; i++) { + var qi = i << 2, di2 = i << 2, gr = data2[di2]; + bf[qi] = gr; + bf[qi + 1] = gr; + bf[qi + 2] = gr; + bf[qi + 3] = data2[di2 + 2]; + } + } else if (ctype == 0) { + var tr = out.tabs["tRNS"] ? out.tabs["tRNS"] : -1; + for (var y = 0;y < h; y++) { + var off = y * bpl, to = y * w; + if (depth == 1) + for (var x2 = 0;x2 < w; x2++) { + var gr = 255 * (data2[off + (x2 >>> 3)] >>> 7 - (x2 & 7) & 1), al2 = gr == tr * 255 ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + else if (depth == 2) + for (var x2 = 0;x2 < w; x2++) { + var gr = 85 * (data2[off + (x2 >>> 2)] >>> 6 - ((x2 & 3) << 1) & 3), al2 = gr == tr * 85 ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + else if (depth == 4) + for (var x2 = 0;x2 < w; x2++) { + var gr = 17 * (data2[off + (x2 >>> 1)] >>> 4 - ((x2 & 1) << 2) & 15), al2 = gr == tr * 17 ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + else if (depth == 8) + for (var x2 = 0;x2 < w; x2++) { + var gr = data2[off + x2], al2 = gr == tr ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + else if (depth == 16) + for (var x2 = 0;x2 < w; x2++) { + var gr = data2[off + (x2 << 1)], al2 = rs(data2, off + (x2 << 1)) == tr ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + } + } + return bf; +}; +UPNG.decode = function(buff) { + var data2 = new Uint8Array(buff), offset = 8, bin = UPNG._bin, rUs = bin.readUshort, rUi = bin.readUint; + var out = { tabs: {}, frames: [] }; + var dd = new Uint8Array(data2.length), doff = 0; + var fd2, foff = 0; + var text2, keyw, bfr; + var mgck = [137, 80, 78, 71, 13, 10, 26, 10]; + for (var i = 0;i < 8; i++) + if (data2[i] != mgck[i]) + throw new Error("The input is not a PNG file!"); + while (offset < data2.length) { + var len = bin.readUint(data2, offset); + offset += 4; + var type = bin.readASCII(data2, offset, 4); + offset += 4; + if (type == "IHDR") { + UPNG.decode._IHDR(data2, offset, out); + } else if (type == "CgBI") { + out.tabs[type] = data2.slice(offset, offset + 4); + } else if (type == "IDAT") { + for (var i = 0;i < len; i++) + dd[doff + i] = data2[offset + i]; + doff += len; + } else if (type == "acTL") { + out.tabs[type] = { num_frames: rUi(data2, offset), num_plays: rUi(data2, offset + 4) }; + fd2 = new Uint8Array(data2.length); + } else if (type == "fcTL") { + if (foff != 0) { + var fr = out.frames[out.frames.length - 1]; + fr.data = UPNG.decode._decompress(out, fd2.slice(0, foff), fr.rect.width, fr.rect.height); + foff = 0; + } + var rct = { x: rUi(data2, offset + 12), y: rUi(data2, offset + 16), width: rUi(data2, offset + 4), height: rUi(data2, offset + 8) }; + var del = rUs(data2, offset + 22); + del = rUs(data2, offset + 20) / (del == 0 ? 100 : del); + var frm = { rect: rct, delay: Math.round(del * 1000), dispose: data2[offset + 24], blend: data2[offset + 25] }; + out.frames.push(frm); + } else if (type == "fdAT") { + for (var i = 0;i < len - 4; i++) + fd2[foff + i] = data2[offset + i + 4]; + foff += len - 4; + } else if (type == "pHYs") { + out.tabs[type] = [bin.readUint(data2, offset), bin.readUint(data2, offset + 4), data2[offset + 8]]; + } else if (type == "cHRM") { + out.tabs[type] = []; + for (var i = 0;i < 8; i++) + out.tabs[type].push(bin.readUint(data2, offset + i * 4)); + } else if (type == "tEXt" || type == "zTXt") { + if (out.tabs[type] == null) + out.tabs[type] = {}; + var nz = bin.nextZero(data2, offset); + keyw = bin.readASCII(data2, offset, nz - offset); + var tl = offset + len - nz - 1; + if (type == "tEXt") + text2 = bin.readASCII(data2, nz + 1, tl); + else { + bfr = UPNG.decode._inflate(data2.slice(nz + 2, nz + 2 + tl)); + text2 = bin.readUTF8(bfr, 0, bfr.length); + } + out.tabs[type][keyw] = text2; + } else if (type == "iTXt") { + if (out.tabs[type] == null) + out.tabs[type] = {}; + var nz = 0, off = offset; + nz = bin.nextZero(data2, off); + keyw = bin.readASCII(data2, off, nz - off); + off = nz + 1; + var cflag = data2[off]; + off += 2; + nz = bin.nextZero(data2, off); + bin.readASCII(data2, off, nz - off); + off = nz + 1; + nz = bin.nextZero(data2, off); + bin.readUTF8(data2, off, nz - off); + off = nz + 1; + var tl = len - (off - offset); + if (cflag == 0) + text2 = bin.readUTF8(data2, off, tl); + else { + bfr = UPNG.decode._inflate(data2.slice(off, off + tl)); + text2 = bin.readUTF8(bfr, 0, bfr.length); + } + out.tabs[type][keyw] = text2; + } else if (type == "PLTE") { + out.tabs[type] = bin.readBytes(data2, offset, len); + } else if (type == "hIST") { + var pl2 = out.tabs["PLTE"].length / 3; + out.tabs[type] = []; + for (var i = 0;i < pl2; i++) + out.tabs[type].push(rUs(data2, offset + i * 2)); + } else if (type == "tRNS") { + if (out.ctype == 3) + out.tabs[type] = bin.readBytes(data2, offset, len); + else if (out.ctype == 0) + out.tabs[type] = rUs(data2, offset); + else if (out.ctype == 2) + out.tabs[type] = [rUs(data2, offset), rUs(data2, offset + 2), rUs(data2, offset + 4)]; + } else if (type == "gAMA") + out.tabs[type] = bin.readUint(data2, offset) / 1e5; + else if (type == "sRGB") + out.tabs[type] = data2[offset]; + else if (type == "bKGD") { + if (out.ctype == 0 || out.ctype == 4) + out.tabs[type] = [rUs(data2, offset)]; + else if (out.ctype == 2 || out.ctype == 6) + out.tabs[type] = [rUs(data2, offset), rUs(data2, offset + 2), rUs(data2, offset + 4)]; + else if (out.ctype == 3) + out.tabs[type] = data2[offset]; + } else if (type == "IEND") { + break; + } + offset += len; + bin.readUint(data2, offset); + offset += 4; + } + if (foff != 0) { + var fr = out.frames[out.frames.length - 1]; + fr.data = UPNG.decode._decompress(out, fd2.slice(0, foff), fr.rect.width, fr.rect.height); + } + out.data = UPNG.decode._decompress(out, dd, out.width, out.height); + delete out.compress; + delete out.interlace; + delete out.filter; + return out; +}; +UPNG.decode._decompress = function(out, dd, w, h) { + var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w * bpp / 8), buff = new Uint8Array((bpl + 1 + out.interlace) * h); + if (out.tabs["CgBI"]) + dd = UPNG.inflateRaw(dd, buff); + else + dd = UPNG.decode._inflate(dd, buff); + if (out.interlace == 0) + dd = UPNG.decode._filterZero(dd, out, 0, w, h); + else if (out.interlace == 1) + dd = UPNG.decode._readInterlace(dd, out); + return dd; +}; +UPNG.decode._inflate = function(data2, buff) { + var out = UPNG["inflateRaw"](new Uint8Array(data2.buffer, 2, data2.length - 6), buff); + return out; +}; +UPNG.inflateRaw = function() { + var H = {}; + H.H = {}; + H.H.N = function(N, W) { + var R2 = Uint8Array, i = 0, m = 0, J2 = 0, h = 0, Q2 = 0, X = 0, u2 = 0, w = 0, d = 0, v, C4; + if (N[0] == 3 && N[1] == 0) + return W ? W : new R2(0); + var V2 = H.H, n2 = V2.b, A2 = V2.e, l2 = V2.R, M = V2.n, I3 = V2.A, e = V2.Z, b = V2.m, Z2 = W == null; + if (Z2) + W = new R2(N.length >>> 2 << 5); + while (i == 0) { + i = n2(N, d, 1); + m = n2(N, d + 1, 2); + d += 3; + if (m == 0) { + if ((d & 7) != 0) + d += 8 - (d & 7); + var D = (d >>> 3) + 4, q2 = N[D - 4] | N[D - 3] << 8; + if (Z2) + W = H.H.W(W, w + q2); + W.set(new R2(N.buffer, N.byteOffset + D, q2), w); + d = D + q2 << 3; + w += q2; + continue; + } + if (Z2) + W = H.H.W(W, w + (1 << 17)); + if (m == 1) { + v = b.J; + C4 = b.h; + X = (1 << 9) - 1; + u2 = (1 << 5) - 1; + } + if (m == 2) { + J2 = A2(N, d, 5) + 257; + h = A2(N, d + 5, 5) + 1; + Q2 = A2(N, d + 10, 4) + 4; + d += 14; + var j2 = 1; + for (var c = 0;c < 38; c += 2) { + b.Q[c] = 0; + b.Q[c + 1] = 0; + } + for (var c = 0;c < Q2; c++) { + var K = A2(N, d + c * 3, 3); + b.Q[(b.X[c] << 1) + 1] = K; + if (K > j2) + j2 = K; + } + d += 3 * Q2; + M(b.Q, j2); + I3(b.Q, j2, b.u); + v = b.w; + C4 = b.d; + d = l2(b.u, (1 << j2) - 1, J2 + h, N, d, b.v); + var r = V2.V(b.v, 0, J2, b.C); + X = (1 << r) - 1; + var S = V2.V(b.v, J2, h, b.D); + u2 = (1 << S) - 1; + M(b.C, r); + I3(b.C, r, v); + M(b.D, S); + I3(b.D, S, C4); + } + while (true) { + var T2 = v[e(N, d) & X]; + d += T2 & 15; + var p = T2 >>> 4; + if (p >>> 8 == 0) { + W[w++] = p; + } else if (p == 256) { + break; + } else { + var z = w + p - 254; + if (p > 264) { + var _2 = b.q[p - 257]; + z = w + (_2 >>> 3) + A2(N, d, _2 & 7); + d += _2 & 7; + } + var $2 = C4[e(N, d) & u2]; + d += $2 & 15; + var s = $2 >>> 4, Y = b.c[s], a = (Y >>> 4) + n2(N, d, Y & 15); + d += Y & 15; + while (w < z) { + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + } + w = z; + } + } + } + return W.length == w ? W : W.slice(0, w); + }; + H.H.W = function(N, W) { + var R2 = N.length; + if (W <= R2) + return N; + var V2 = new Uint8Array(R2 << 1); + V2.set(N, 0); + return V2; + }; + H.H.R = function(N, W, R2, V2, n2, A2) { + var l2 = H.H.e, M = H.H.Z, I3 = 0; + while (I3 < R2) { + var e = N[M(V2, n2) & W]; + n2 += e & 15; + var b = e >>> 4; + if (b <= 15) { + A2[I3] = b; + I3++; + } else { + var Z2 = 0, m = 0; + if (b == 16) { + m = 3 + l2(V2, n2, 2); + n2 += 2; + Z2 = A2[I3 - 1]; + } else if (b == 17) { + m = 3 + l2(V2, n2, 3); + n2 += 3; + } else if (b == 18) { + m = 11 + l2(V2, n2, 7); + n2 += 7; + } + var J2 = I3 + m; + while (I3 < J2) { + A2[I3] = Z2; + I3++; + } + } + } + return n2; + }; + H.H.V = function(N, W, R2, V2) { + var n2 = 0, A2 = 0, l2 = V2.length >>> 1; + while (A2 < R2) { + var M = N[A2 + W]; + V2[A2 << 1] = 0; + V2[(A2 << 1) + 1] = M; + if (M > n2) + n2 = M; + A2++; + } + while (A2 < l2) { + V2[A2 << 1] = 0; + V2[(A2 << 1) + 1] = 0; + A2++; + } + return n2; + }; + H.H.n = function(N, W) { + var R2 = H.H.m, V2 = N.length, n2, A2, l2, M, I3, e = R2.j; + for (var M = 0;M <= W; M++) + e[M] = 0; + for (M = 1;M < V2; M += 2) + e[N[M]]++; + var b = R2.K; + n2 = 0; + e[0] = 0; + for (A2 = 1;A2 <= W; A2++) { + n2 = n2 + e[A2 - 1] << 1; + b[A2] = n2; + } + for (l2 = 0;l2 < V2; l2 += 2) { + I3 = N[l2 + 1]; + if (I3 != 0) { + N[l2] = b[I3]; + b[I3]++; + } + } + }; + H.H.A = function(N, W, R2) { + var V2 = N.length, n2 = H.H.m, A2 = n2.r; + for (var l2 = 0;l2 < V2; l2 += 2) + if (N[l2 + 1] != 0) { + var M = l2 >> 1, I3 = N[l2 + 1], e = M << 4 | I3, b = W - I3, Z2 = N[l2] << b, m = Z2 + (1 << b); + while (Z2 != m) { + var J2 = A2[Z2] >>> 15 - W; + R2[J2] = e; + Z2++; + } + } + }; + H.H.l = function(N, W) { + var R2 = H.H.m.r, V2 = 15 - W; + for (var n2 = 0;n2 < N.length; n2 += 2) { + var A2 = N[n2] << W - N[n2 + 1]; + N[n2] = R2[A2] >>> V2; + } + }; + H.H.M = function(N, W, R2) { + R2 = R2 << (W & 7); + var V2 = W >>> 3; + N[V2] |= R2; + N[V2 + 1] |= R2 >>> 8; + }; + H.H.I = function(N, W, R2) { + R2 = R2 << (W & 7); + var V2 = W >>> 3; + N[V2] |= R2; + N[V2 + 1] |= R2 >>> 8; + N[V2 + 2] |= R2 >>> 16; + }; + H.H.e = function(N, W, R2) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8) >>> (W & 7) & (1 << R2) - 1; + }; + H.H.b = function(N, W, R2) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7) & (1 << R2) - 1; + }; + H.H.Z = function(N, W) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7); + }; + H.H.i = function(N, W) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16 | N[(W >>> 3) + 3] << 24) >>> (W & 7); + }; + H.H.m = function() { + var N = Uint16Array, W = Uint32Array; + return { K: new N(16), j: new N(16), X: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], S: [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, 999, 999, 999], T: [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, 0, 0, 0], q: new N(32), 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, 65535, 65535], z: [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, 0, 0], c: new W(32), J: new N(512), _: [], h: new N(32), $: [], w: new N(32768), C: [], v: [], d: new N(32768), D: [], u: new N(512), Q: [], r: new N(1 << 15), s: new W(286), Y: new W(30), a: new W(19), t: new W(15000), k: new N(1 << 16), g: new N(1 << 15) }; + }(); + (function() { + var N = H.H.m, W = 1 << 15; + for (var R2 = 0;R2 < W; R2++) { + var V2 = R2; + V2 = (V2 & 2863311530) >>> 1 | (V2 & 1431655765) << 1; + V2 = (V2 & 3435973836) >>> 2 | (V2 & 858993459) << 2; + V2 = (V2 & 4042322160) >>> 4 | (V2 & 252645135) << 4; + V2 = (V2 & 4278255360) >>> 8 | (V2 & 16711935) << 8; + N.r[R2] = (V2 >>> 16 | V2 << 16) >>> 17; + } + function n2(A2, l2, M) { + while (l2-- != 0) + A2.push(0, M); + } + for (var R2 = 0;R2 < 32; R2++) { + N.q[R2] = N.S[R2] << 3 | N.T[R2]; + N.c[R2] = N.p[R2] << 4 | N.z[R2]; + } + n2(N._, 144, 8); + n2(N._, 255 - 143, 9); + n2(N._, 279 - 255, 7); + n2(N._, 287 - 279, 8); + H.H.n(N._, 9); + H.H.A(N._, 9, N.J); + H.H.l(N._, 9); + n2(N.$, 32, 5); + H.H.n(N.$, 5); + H.H.A(N.$, 5, N.h); + H.H.l(N.$, 5); + n2(N.Q, 19, 0); + n2(N.C, 286, 0); + n2(N.D, 30, 0); + n2(N.v, 320, 0); + })(); + return H.H.N; +}(); +UPNG.decode._readInterlace = function(data2, out) { + var { width: w, height: h } = out; + var bpp = UPNG.decode._getBPP(out), cbpp = bpp >> 3, bpl = Math.ceil(w * bpp / 8); + var img = new Uint8Array(h * bpl); + var di2 = 0; + var starting_row = [0, 0, 4, 0, 2, 0, 1]; + var starting_col = [0, 4, 0, 2, 0, 1, 0]; + var row_increment = [8, 8, 8, 4, 4, 2, 2]; + var col_increment = [8, 8, 4, 4, 2, 2, 1]; + var pass = 0; + while (pass < 7) { + var ri = row_increment[pass], ci = col_increment[pass]; + var sw = 0, sh = 0; + var cr = starting_row[pass]; + while (cr < h) { + cr += ri; + sh++; + } + var cc = starting_col[pass]; + while (cc < w) { + cc += ci; + sw++; + } + var bpll = Math.ceil(sw * bpp / 8); + UPNG.decode._filterZero(data2, out, di2, sw, sh); + var y = 0, row = starting_row[pass]; + var val2; + while (row < h) { + var col = starting_col[pass]; + var cdi = di2 + y * bpll << 3; + while (col < w) { + if (bpp == 1) { + val2 = data2[cdi >> 3]; + val2 = val2 >> 7 - (cdi & 7) & 1; + img[row * bpl + (col >> 3)] |= val2 << 7 - ((col & 7) << 0); + } + if (bpp == 2) { + val2 = data2[cdi >> 3]; + val2 = val2 >> 6 - (cdi & 7) & 3; + img[row * bpl + (col >> 2)] |= val2 << 6 - ((col & 3) << 1); + } + if (bpp == 4) { + val2 = data2[cdi >> 3]; + val2 = val2 >> 4 - (cdi & 7) & 15; + img[row * bpl + (col >> 1)] |= val2 << 4 - ((col & 1) << 2); + } + if (bpp >= 8) { + var ii = row * bpl + col * cbpp; + for (var j2 = 0;j2 < cbpp; j2++) + img[ii + j2] = data2[(cdi >> 3) + j2]; + } + cdi += bpp; + col += ci; + } + y++; + row += ri; + } + if (sw * sh != 0) + di2 += sh * (1 + bpll); + pass = pass + 1; + } + return img; +}; +UPNG.decode._getBPP = function(out) { + var noc = [1, null, 3, 1, 2, null, 4][out.ctype]; + return noc * out.depth; +}; +UPNG.decode._filterZero = function(data2, out, off, w, h) { + var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w * bpp / 8), paeth = UPNG.decode._paeth; + bpp = Math.ceil(bpp / 8); + var i, di2, type = data2[off], x2 = 0; + if (type > 1) + data2[off] = [0, 0, 1][type - 2]; + if (type == 3) + for (x2 = bpp;x2 < bpl; x2++) + data2[x2 + 1] = data2[x2 + 1] + (data2[x2 + 1 - bpp] >>> 1) & 255; + for (var y = 0;y < h; y++) { + i = off + y * bpl; + di2 = i + y + 1; + type = data2[di2 - 1]; + x2 = 0; + if (type == 0) + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2]; + else if (type == 1) { + for (;x2 < bpp; x2++) + data2[i + x2] = data2[di2 + x2]; + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2] + data2[i + x2 - bpp]; + } else if (type == 2) { + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2] + data2[i + x2 - bpl]; + } else if (type == 3) { + for (;x2 < bpp; x2++) + data2[i + x2] = data2[di2 + x2] + (data2[i + x2 - bpl] >>> 1); + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2] + (data2[i + x2 - bpl] + data2[i + x2 - bpp] >>> 1); + } else { + for (;x2 < bpp; x2++) + data2[i + x2] = data2[di2 + x2] + paeth(0, data2[i + x2 - bpl], 0); + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2] + paeth(data2[i + x2 - bpp], data2[i + x2 - bpl], data2[i + x2 - bpp - bpl]); + } + } + return data2; +}; +UPNG.decode._paeth = function(a, b, c) { + var p = a + b - c, pa = p - a, pb = p - b, pc = p - c; + if (pa * pa <= pb * pb && pa * pa <= pc * pc) + return a; + else if (pb * pb <= pc * pc) + return b; + return c; +}; +UPNG.decode._IHDR = function(data2, offset, out) { + var bin = UPNG._bin; + out.width = bin.readUint(data2, offset); + offset += 4; + out.height = bin.readUint(data2, offset); + offset += 4; + out.depth = data2[offset]; + offset++; + out.ctype = data2[offset]; + offset++; + out.compress = data2[offset]; + offset++; + out.filter = data2[offset]; + offset++; + out.interlace = data2[offset]; + offset++; +}; +UPNG._bin = { + nextZero: function(data2, p) { + while (data2[p] != 0) + p++; + return p; + }, + readUshort: function(buff, p) { + return buff[p] << 8 | buff[p + 1]; + }, + writeUshort: function(buff, p, n2) { + buff[p] = n2 >> 8 & 255; + buff[p + 1] = n2 & 255; + }, + readUint: function(buff, p) { + return buff[p] * (256 * 256 * 256) + (buff[p + 1] << 16 | buff[p + 2] << 8 | buff[p + 3]); + }, + writeUint: function(buff, p, n2) { + buff[p] = n2 >> 24 & 255; + buff[p + 1] = n2 >> 16 & 255; + buff[p + 2] = n2 >> 8 & 255; + buff[p + 3] = n2 & 255; + }, + readASCII: function(buff, p, l2) { + var s = ""; + for (var i = 0;i < l2; i++) + s += String.fromCharCode(buff[p + i]); + return s; + }, + writeASCII: function(data2, p, s) { + for (var i = 0;i < s.length; i++) + data2[p + i] = s.charCodeAt(i); + }, + readBytes: function(buff, p, l2) { + var arr = []; + for (var i = 0;i < l2; i++) + arr.push(buff[p + i]); + return arr; + }, + pad: function(n2) { + return n2.length < 2 ? "0" + n2 : n2; + }, + readUTF8: function(buff, p, l2) { + var s = "", ns; + for (var i = 0;i < l2; i++) + s += "%" + UPNG._bin.pad(buff[p + i].toString(16)); + try { + ns = decodeURIComponent(s); + } catch (e) { + return UPNG._bin.readASCII(buff, p, l2); + } + return ns; + } +}; +UPNG._copyTile = function(sb, sw, sh, tb, tw, th, xoff, yoff, mode) { + var w = Math.min(sw, tw), h = Math.min(sh, th); + var si = 0, ti = 0; + for (var y = 0;y < h; y++) + for (var x2 = 0;x2 < w; x2++) { + if (xoff >= 0 && yoff >= 0) { + si = y * sw + x2 << 2; + ti = (yoff + y) * tw + xoff + x2 << 2; + } else { + si = (-yoff + y) * sw - xoff + x2 << 2; + ti = y * tw + x2 << 2; + } + if (mode == 0) { + tb[ti] = sb[si]; + tb[ti + 1] = sb[si + 1]; + tb[ti + 2] = sb[si + 2]; + tb[ti + 3] = sb[si + 3]; + } else if (mode == 1) { + var fa = sb[si + 3] * (1 / 255), fr = sb[si] * fa, fg = sb[si + 1] * fa, fb = sb[si + 2] * fa; + var ba = tb[ti + 3] * (1 / 255), br = tb[ti] * ba, bg = tb[ti + 1] * ba, bb = tb[ti + 2] * ba; + var ifa = 1 - fa, oa = fa + ba * ifa, ioa = oa == 0 ? 0 : 1 / oa; + tb[ti + 3] = 255 * oa; + tb[ti + 0] = (fr + br * ifa) * ioa; + tb[ti + 1] = (fg + bg * ifa) * ioa; + tb[ti + 2] = (fb + bb * ifa) * ioa; + } else if (mode == 2) { + var fa = sb[si + 3], fr = sb[si], fg = sb[si + 1], fb = sb[si + 2]; + var ba = tb[ti + 3], br = tb[ti], bg = tb[ti + 1], bb = tb[ti + 2]; + if (fa == ba && fr == br && fg == bg && fb == bb) { + tb[ti] = 0; + tb[ti + 1] = 0; + tb[ti + 2] = 0; + tb[ti + 3] = 0; + } else { + tb[ti] = fr; + tb[ti + 1] = fg; + tb[ti + 2] = fb; + tb[ti + 3] = fa; + } + } else if (mode == 3) { + var fa = sb[si + 3], fr = sb[si], fg = sb[si + 1], fb = sb[si + 2]; + var ba = tb[ti + 3], br = tb[ti], bg = tb[ti + 1], bb = tb[ti + 2]; + if (fa == ba && fr == br && fg == bg && fb == bb) + continue; + if (fa < 220 && ba > 20) + return false; + } + } + return true; +}; +// node_modules/three/examples/jsm/libs/utif.module.js +var UTIF = {}; +(function() { + var W = function a1() { + function W2(p) { + this.message = "JPEG error: " + p; + } + W2.prototype = new Error; + W2.prototype.name = "JpegError"; + W2.constructor = W2; + return W2; + }(), ak = function ag() { + var p = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]), t2 = 4017, ac = 799, ah = 3406, ao = 2276, ar = 1567, ai = 3784, s = 5793, ad = 2896; + function ak2(Q2) { + if (Q2 == null) + Q2 = {}; + if (Q2.w == null) + Q2.w = -1; + this.V = Q2.n; + this.N = Q2.w; + } + function a5(Q2, h) { + var f = 0, G2 = [], n2, E2, a = 16, F; + while (a > 0 && !Q2[a - 1]) { + a--; + } + G2.push({ children: [], index: 0 }); + var C4 = G2[0]; + for (n2 = 0;n2 < a; n2++) { + for (E2 = 0;E2 < Q2[n2]; E2++) { + C4 = G2.pop(); + C4.children[C4.index] = h[f]; + while (C4.index > 0) { + C4 = G2.pop(); + } + C4.index++; + G2.push(C4); + while (G2.length <= n2) { + G2.push(F = { children: [], index: 0 }); + C4.children[C4.index] = F.children; + C4 = F; + } + f++; + } + if (n2 + 1 < a) { + G2.push(F = { children: [], index: 0 }); + C4.children[C4.index] = F.children; + C4 = F; + } + } + return G2[0].children; + } + function a2(Q2, h, f) { + return 64 * ((Q2.P + 1) * h + f); + } + function a7(Q2, h, f, G2, n2, E2, a, C4, F, d) { + if (d == null) + d = false; + var { m: T2, Z: U } = f, z = h, J2 = 0, V2 = 0, r = 0, D = 0, a8, q2 = 0, X, O, _2, N, e, K, x2 = 0, k2, g3, R2, c; + function Y() { + if (V2 > 0) { + V2--; + return J2 >> V2 & 1; + } + J2 = Q2[h++]; + if (J2 === 255) { + var I3 = Q2[h++]; + if (I3) { + if (I3 === 220 && d) { + h += 2; + var l2 = Z2(Q2, h); + h += 2; + if (l2 > 0 && l2 !== f.s) { + throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data", l2); + } + } else if (I3 === 217) { + if (d) { + var M = q2 * 8; + if (M > 0 && M < f.s / 10) { + throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, " + "possibly caused by incorrect `scanLines` parameter", M); + } + } + throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data"); + } + throw new W("unexpected marker"); + } + } + V2 = 7; + return J2 >>> 7; + } + function u2(I3) { + var l2 = I3; + while (true) { + l2 = l2[Y()]; + switch (typeof l2) { + case "number": + return l2; + case "object": + continue; + } + throw new W("invalid huffman sequence"); + } + } + function m(I3) { + var e2 = 0; + while (I3 > 0) { + e2 = e2 << 1 | Y(); + I3--; + } + return e2; + } + function j2(I3) { + if (I3 === 1) { + return Y() === 1 ? 1 : -1; + } + var e2 = m(I3); + if (e2 >= 1 << I3 - 1) { + return e2; + } + return e2 + (-1 << I3) + 1; + } + function v(X2, I3) { + var l2 = u2(X2.J), M = l2 === 0 ? 0 : j2(l2), N2 = 1; + X2.D[I3] = X2.Q += M; + while (N2 < 64) { + var S = u2(X2.i), i = S & 15, A2 = S >> 4; + if (i === 0) { + if (A2 < 15) { + break; + } + N2 += 16; + continue; + } + N2 += A2; + var o = p[N2]; + X2.D[I3 + o] = j2(i); + N2++; + } + } + function $2(X2, I3) { + var l2 = u2(X2.J), M = l2 === 0 ? 0 : j2(l2) << F; + X2.D[I3] = X2.Q += M; + } + function b(X2, I3) { + X2.D[I3] |= Y() << F; + } + function P(X2, I3) { + if (r > 0) { + r--; + return; + } + var N2 = E2, l2 = a; + while (N2 <= l2) { + var M = u2(X2.i), S = M & 15, i = M >> 4; + if (S === 0) { + if (i < 15) { + r = m(i) + (1 << i) - 1; + break; + } + N2 += 16; + continue; + } + N2 += i; + var A2 = p[N2]; + X2.D[I3 + A2] = j2(S) * (1 << F); + N2++; + } + } + function a4(X2, I3) { + var N2 = E2, l2 = a, M = 0, S, i; + while (N2 <= l2) { + var A2 = I3 + p[N2], o = X2.D[A2] < 0 ? -1 : 1; + switch (D) { + case 0: + i = u2(X2.i); + S = i & 15; + M = i >> 4; + if (S === 0) { + if (M < 15) { + r = m(M) + (1 << M); + D = 4; + } else { + M = 16; + D = 1; + } + } else { + if (S !== 1) { + throw new W("invalid ACn encoding"); + } + a8 = j2(S); + D = M ? 2 : 3; + } + continue; + case 1: + case 2: + if (X2.D[A2]) { + X2.D[A2] += o * (Y() << F); + } else { + M--; + if (M === 0) { + D = D === 2 ? 3 : 0; + } + } + break; + case 3: + if (X2.D[A2]) { + X2.D[A2] += o * (Y() << F); + } else { + X2.D[A2] = a8 << F; + D = 0; + } + break; + case 4: + if (X2.D[A2]) { + X2.D[A2] += o * (Y() << F); + } + break; + } + N2++; + } + if (D === 4) { + r--; + if (r === 0) { + D = 0; + } + } + } + function H(X2, I3, x3, l2, M) { + var S = x3 / T2 | 0, i = x3 % T2; + q2 = S * X2.A + l2; + var A2 = i * X2.h + M, o = a2(X2, q2, A2); + I3(X2, o); + } + function w(X2, I3, x3) { + q2 = x3 / X2.P | 0; + var l2 = x3 % X2.P, M = a2(X2, q2, l2); + I3(X2, M); + } + var y = G2.length; + if (U) { + if (E2 === 0) { + K = C4 === 0 ? $2 : b; + } else { + K = C4 === 0 ? P : a4; + } + } else { + K = v; + } + if (y === 1) { + g3 = G2[0].P * G2[0].c; + } else { + g3 = T2 * f.R; + } + while (x2 <= g3) { + var L = n2 ? Math.min(g3 - x2, n2) : g3; + if (L > 0) { + for (O = 0;O < y; O++) { + G2[O].Q = 0; + } + r = 0; + if (y === 1) { + X = G2[0]; + for (e = 0;e < L; e++) { + w(X, K, x2); + x2++; + } + } else { + for (e = 0;e < L; e++) { + for (O = 0;O < y; O++) { + X = G2[O]; + R2 = X.h; + c = X.A; + for (_2 = 0;_2 < c; _2++) { + for (N = 0;N < R2; N++) { + H(X, K, x2, _2, N); + } + } + } + x2++; + } + } + } + V2 = 0; + k2 = an(Q2, h); + if (!k2) { + break; + } + if (k2.u) { + var a6 = L > 0 ? "unexpected" : "excessive"; + h = k2.offset; + } + if (k2.M >= 65488 && k2.M <= 65495) { + h += 2; + } else { + break; + } + } + return h - z; + } + function al2(Q2, h, f) { + var { $: G2, D: n2 } = Q2, E2, a, C4, F, d, T2, U, z, J2, V2, Y, u2, m, j2, v, $2, b; + if (!G2) { + throw new W("missing required Quantization Table."); + } + for (var r = 0;r < 64; r += 8) { + J2 = n2[h + r]; + V2 = n2[h + r + 1]; + Y = n2[h + r + 2]; + u2 = n2[h + r + 3]; + m = n2[h + r + 4]; + j2 = n2[h + r + 5]; + v = n2[h + r + 6]; + $2 = n2[h + r + 7]; + J2 *= G2[r]; + if ((V2 | Y | u2 | m | j2 | v | $2) === 0) { + b = s * J2 + 512 >> 10; + f[r] = b; + f[r + 1] = b; + f[r + 2] = b; + f[r + 3] = b; + f[r + 4] = b; + f[r + 5] = b; + f[r + 6] = b; + f[r + 7] = b; + continue; + } + V2 *= G2[r + 1]; + Y *= G2[r + 2]; + u2 *= G2[r + 3]; + m *= G2[r + 4]; + j2 *= G2[r + 5]; + v *= G2[r + 6]; + $2 *= G2[r + 7]; + E2 = s * J2 + 128 >> 8; + a = s * m + 128 >> 8; + C4 = Y; + F = v; + d = ad * (V2 - $2) + 128 >> 8; + z = ad * (V2 + $2) + 128 >> 8; + T2 = u2 << 4; + U = j2 << 4; + E2 = E2 + a + 1 >> 1; + a = E2 - a; + b = C4 * ai + F * ar + 128 >> 8; + C4 = C4 * ar - F * ai + 128 >> 8; + F = b; + d = d + U + 1 >> 1; + U = d - U; + z = z + T2 + 1 >> 1; + T2 = z - T2; + E2 = E2 + F + 1 >> 1; + F = E2 - F; + a = a + C4 + 1 >> 1; + C4 = a - C4; + b = d * ao + z * ah + 2048 >> 12; + d = d * ah - z * ao + 2048 >> 12; + z = b; + b = T2 * ac + U * t2 + 2048 >> 12; + T2 = T2 * t2 - U * ac + 2048 >> 12; + U = b; + f[r] = E2 + z; + f[r + 7] = E2 - z; + f[r + 1] = a + U; + f[r + 6] = a - U; + f[r + 2] = C4 + T2; + f[r + 5] = C4 - T2; + f[r + 3] = F + d; + f[r + 4] = F - d; + } + for (var P = 0;P < 8; ++P) { + J2 = f[P]; + V2 = f[P + 8]; + Y = f[P + 16]; + u2 = f[P + 24]; + m = f[P + 32]; + j2 = f[P + 40]; + v = f[P + 48]; + $2 = f[P + 56]; + if ((V2 | Y | u2 | m | j2 | v | $2) === 0) { + b = s * J2 + 8192 >> 14; + if (b < -2040) { + b = 0; + } else if (b >= 2024) { + b = 255; + } else { + b = b + 2056 >> 4; + } + n2[h + P] = b; + n2[h + P + 8] = b; + n2[h + P + 16] = b; + n2[h + P + 24] = b; + n2[h + P + 32] = b; + n2[h + P + 40] = b; + n2[h + P + 48] = b; + n2[h + P + 56] = b; + continue; + } + E2 = s * J2 + 2048 >> 12; + a = s * m + 2048 >> 12; + C4 = Y; + F = v; + d = ad * (V2 - $2) + 2048 >> 12; + z = ad * (V2 + $2) + 2048 >> 12; + T2 = u2; + U = j2; + E2 = (E2 + a + 1 >> 1) + 4112; + a = E2 - a; + b = C4 * ai + F * ar + 2048 >> 12; + C4 = C4 * ar - F * ai + 2048 >> 12; + F = b; + d = d + U + 1 >> 1; + U = d - U; + z = z + T2 + 1 >> 1; + T2 = z - T2; + E2 = E2 + F + 1 >> 1; + F = E2 - F; + a = a + C4 + 1 >> 1; + C4 = a - C4; + b = d * ao + z * ah + 2048 >> 12; + d = d * ah - z * ao + 2048 >> 12; + z = b; + b = T2 * ac + U * t2 + 2048 >> 12; + T2 = T2 * t2 - U * ac + 2048 >> 12; + U = b; + J2 = E2 + z; + $2 = E2 - z; + V2 = a + U; + v = a - U; + Y = C4 + T2; + j2 = C4 - T2; + u2 = F + d; + m = F - d; + if (J2 < 16) { + J2 = 0; + } else if (J2 >= 4080) { + J2 = 255; + } else { + J2 >>= 4; + } + if (V2 < 16) { + V2 = 0; + } else if (V2 >= 4080) { + V2 = 255; + } else { + V2 >>= 4; + } + if (Y < 16) { + Y = 0; + } else if (Y >= 4080) { + Y = 255; + } else { + Y >>= 4; + } + if (u2 < 16) { + u2 = 0; + } else if (u2 >= 4080) { + u2 = 255; + } else { + u2 >>= 4; + } + if (m < 16) { + m = 0; + } else if (m >= 4080) { + m = 255; + } else { + m >>= 4; + } + if (j2 < 16) { + j2 = 0; + } else if (j2 >= 4080) { + j2 = 255; + } else { + j2 >>= 4; + } + if (v < 16) { + v = 0; + } else if (v >= 4080) { + v = 255; + } else { + v >>= 4; + } + if ($2 < 16) { + $2 = 0; + } else if ($2 >= 4080) { + $2 = 255; + } else { + $2 >>= 4; + } + n2[h + P] = J2; + n2[h + P + 8] = V2; + n2[h + P + 16] = Y; + n2[h + P + 24] = u2; + n2[h + P + 32] = m; + n2[h + P + 40] = j2; + n2[h + P + 48] = v; + n2[h + P + 56] = $2; + } + } + function a0(Q2, h) { + var { P: f, c: G2 } = h, n2 = new Int16Array(64); + for (var E2 = 0;E2 < G2; E2++) { + for (var a = 0;a < f; a++) { + var C4 = a2(h, E2, a); + al2(h, C4, n2); + } + } + return h.D; + } + function an(Q2, h, f) { + if (f == null) + f = h; + var G2 = Q2.length - 1, n2 = f < h ? f : h; + if (h >= G2) { + return null; + } + var E2 = Z2(Q2, h); + if (E2 >= 65472 && E2 <= 65534) { + return { u: null, M: E2, offset: h }; + } + var a = Z2(Q2, n2); + while (!(a >= 65472 && a <= 65534)) { + if (++n2 >= G2) { + return null; + } + a = Z2(Q2, n2); + } + return { u: E2.toString(16), M: a, offset: n2 }; + } + ak2.prototype = { parse(Q2, h) { + if (h == null) + h = {}; + var f = h.F, E2 = 0, a = null, C4 = null, F, d, T2 = 0; + function G2() { + var o = Z2(Q2, E2); + E2 += 2; + var B2 = E2 + o - 2, V3 = an(Q2, B2, E2); + if (V3 && V3.u) { + B2 = V3.offset; + } + var ab = Q2.subarray(E2, B2); + E2 += ab.length; + return ab; + } + function n2(F2) { + var o = Math.ceil(F2.o / 8 / F2.X), B2 = Math.ceil(F2.s / 8 / F2.B); + for (var Y2 = 0;Y2 < F2.W.length; Y2++) { + R2 = F2.W[Y2]; + var ab = Math.ceil(Math.ceil(F2.o / 8) * R2.h / F2.X), af = Math.ceil(Math.ceil(F2.s / 8) * R2.A / F2.B), ap = o * R2.h, aq = B2 * R2.A, ae3 = 64 * aq * (ap + 1); + R2.D = new Int16Array(ae3); + R2.P = ab; + R2.c = af; + } + F2.m = o; + F2.R = B2; + } + var U = [], z = [], J2 = [], V2 = Z2(Q2, E2); + E2 += 2; + if (V2 !== 65496) { + throw new W("SOI not found"); + } + V2 = Z2(Q2, E2); + E2 += 2; + markerLoop: + while (V2 !== 65497) { + var Y, u2, m; + switch (V2) { + case 65504: + case 65505: + case 65506: + case 65507: + case 65508: + case 65509: + case 65510: + case 65511: + case 65512: + case 65513: + case 65514: + case 65515: + case 65516: + case 65517: + case 65518: + case 65519: + case 65534: + var j2 = G2(); + if (V2 === 65504) { + if (j2[0] === 74 && j2[1] === 70 && j2[2] === 73 && j2[3] === 70 && j2[4] === 0) { + a = { version: { d: j2[5], T: j2[6] }, K: j2[7], j: j2[8] << 8 | j2[9], H: j2[10] << 8 | j2[11], S: j2[12], I: j2[13], C: j2.subarray(14, 14 + 3 * j2[12] * j2[13]) }; + } + } + if (V2 === 65518) { + if (j2[0] === 65 && j2[1] === 100 && j2[2] === 111 && j2[3] === 98 && j2[4] === 101) { + C4 = { version: j2[5] << 8 | j2[6], k: j2[7] << 8 | j2[8], q: j2[9] << 8 | j2[10], a: j2[11] }; + } + } + break; + case 65499: + var v = Z2(Q2, E2), b; + E2 += 2; + var $2 = v + E2 - 2; + while (E2 < $2) { + var r = Q2[E2++], P = new Uint16Array(64); + if (r >> 4 === 0) { + for (u2 = 0;u2 < 64; u2++) { + b = p[u2]; + P[b] = Q2[E2++]; + } + } else if (r >> 4 === 1) { + for (u2 = 0;u2 < 64; u2++) { + b = p[u2]; + P[b] = Z2(Q2, E2); + E2 += 2; + } + } else { + throw new W("DQT - invalid table spec"); + } + U[r & 15] = P; + } + break; + case 65472: + case 65473: + case 65474: + if (F) { + throw new W("Only single frame JPEGs supported"); + } + E2 += 2; + F = {}; + F.G = V2 === 65473; + F.Z = V2 === 65474; + F.precision = Q2[E2++]; + var D = Z2(Q2, E2), a4, q2 = 0, H = 0; + E2 += 2; + F.s = f || D; + F.o = Z2(Q2, E2); + E2 += 2; + F.W = []; + F._ = {}; + var a8 = Q2[E2++]; + for (Y = 0;Y < a8; Y++) { + a4 = Q2[E2]; + var w = Q2[E2 + 1] >> 4, y = Q2[E2 + 1] & 15; + if (q2 < w) { + q2 = w; + } + if (H < y) { + H = y; + } + var X = Q2[E2 + 2]; + m = F.W.push({ h: w, A: y, L: X, $: null }); + F._[a4] = m - 1; + E2 += 3; + } + F.X = q2; + F.B = H; + n2(F); + break; + case 65476: + var O = Z2(Q2, E2); + E2 += 2; + for (Y = 2;Y < O; ) { + var _2 = Q2[E2++], N = new Uint8Array(16), e = 0; + for (u2 = 0;u2 < 16; u2++, E2++) { + e += N[u2] = Q2[E2]; + } + var K = new Uint8Array(e); + for (u2 = 0;u2 < e; u2++, E2++) { + K[u2] = Q2[E2]; + } + Y += 17 + e; + (_2 >> 4 === 0 ? J2 : z)[_2 & 15] = a5(N, K); + } + break; + case 65501: + E2 += 2; + d = Z2(Q2, E2); + E2 += 2; + break; + case 65498: + var x2 = ++T2 === 1 && !f, R2; + E2 += 2; + var k2 = Q2[E2++], g3 = []; + for (Y = 0;Y < k2; Y++) { + var c = Q2[E2++], L = F._[c]; + R2 = F.W[L]; + R2.index = c; + var a6 = Q2[E2++]; + R2.J = J2[a6 >> 4]; + R2.i = z[a6 & 15]; + g3.push(R2); + } + var I3 = Q2[E2++], l2 = Q2[E2++], M = Q2[E2++]; + try { + var S = a7(Q2, E2, F, g3, d, I3, l2, M >> 4, M & 15, x2); + E2 += S; + } catch (ex) { + if (ex instanceof DNLMarkerError) { + return this.parse(Q2, { F: ex.s }); + } else if (ex instanceof EOIMarkerError) { + break markerLoop; + } + throw ex; + } + break; + case 65500: + E2 += 4; + break; + case 65535: + if (Q2[E2] !== 255) { + E2--; + } + break; + default: + var i = an(Q2, E2 - 2, E2 - 3); + if (i && i.u) { + E2 = i.offset; + break; + } + if (E2 >= Q2.length - 1) { + break markerLoop; + } + throw new W("JpegImage.parse - unknown marker: " + V2.toString(16)); + } + V2 = Z2(Q2, E2); + E2 += 2; + } + this.width = F.o; + this.height = F.s; + this.g = a; + this.b = C4; + this.W = []; + for (Y = 0;Y < F.W.length; Y++) { + R2 = F.W[Y]; + var A2 = U[R2.L]; + if (A2) { + R2.$ = A2; + } + this.W.push({ index: R2.index, e: a0(F, R2), l: R2.h / F.X, t: R2.A / F.B, P: R2.P, c: R2.c }); + } + this.p = this.W.length; + return; + }, Y(Q2, h, f) { + if (f == null) + f = false; + var G2 = this.width / Q2, n2 = this.height / h, E2, a, C4, F, d, T2, U, z, J2, V2, Y = 0, u2, m = this.W.length, j2 = Q2 * h * m, v = new Uint8ClampedArray(j2), $2 = new Uint32Array(Q2), b = 4294967288, r; + for (U = 0;U < m; U++) { + E2 = this.W[U]; + a = E2.l * G2; + C4 = E2.t * n2; + Y = U; + u2 = E2.e; + F = E2.P + 1 << 3; + if (a !== r) { + for (d = 0;d < Q2; d++) { + z = 0 | d * a; + $2[d] = (z & b) << 3 | z & 7; + } + r = a; + } + for (T2 = 0;T2 < h; T2++) { + z = 0 | T2 * C4; + V2 = F * (z & b) | (z & 7) << 3; + for (d = 0;d < Q2; d++) { + v[Y] = u2[V2 + $2[d]]; + Y += m; + } + } + } + var P = this.V; + if (!f && m === 4 && !P) { + P = new Int32Array([-256, 255, -256, 255, -256, 255, -256, 255]); + } + if (P) { + for (U = 0;U < j2; ) { + for (z = 0, J2 = 0;z < m; z++, U++, J2 += 2) { + v[U] = (v[U] * P[J2] >> 8) + P[J2 + 1]; + } + } + } + return v; + }, get f() { + if (this.b) { + return !!this.b.a; + } + if (this.p === 3) { + if (this.N === 0) { + return false; + } else if (this.W[0].index === 82 && this.W[1].index === 71 && this.W[2].index === 66) { + return false; + } + return true; + } + if (this.N === 1) { + return true; + } + return false; + }, z: function aj(Q2) { + var h, f, G2; + for (var n2 = 0, E2 = Q2.length;n2 < E2; n2 += 3) { + h = Q2[n2]; + f = Q2[n2 + 1]; + G2 = Q2[n2 + 2]; + Q2[n2] = h - 179.456 + 1.402 * G2; + Q2[n2 + 1] = h + 135.459 - 0.344 * f - 0.714 * G2; + Q2[n2 + 2] = h - 226.816 + 1.772 * f; + } + return Q2; + }, O: function aa(Q2) { + var h, f, G2, n2, E2 = 0; + for (var a = 0, C4 = Q2.length;a < C4; a += 4) { + h = Q2[a]; + f = Q2[a + 1]; + G2 = Q2[a + 2]; + n2 = Q2[a + 3]; + Q2[E2++] = -122.67195406894 + f * (-0.0000660635669420364 * f + 0.000437130475926232 * G2 - 0.000054080610064599 * h + 0.00048449797120281 * n2 - 0.154362151871126) + G2 * (-0.000957964378445773 * G2 + 0.000817076911346625 * h - 0.00477271405408747 * n2 + 1.53380253221734) + h * (0.000961250184130688 * h - 0.00266257332283933 * n2 + 0.48357088451265) + n2 * (-0.000336197177618394 * n2 + 0.484791561490776); + Q2[E2++] = 107.268039397724 + f * (0.0000219927104525741 * f - 0.000640992018297945 * G2 + 0.000659397001245577 * h + 0.000426105652938837 * n2 - 0.176491792462875) + G2 * (-0.000778269941513683 * G2 + 0.00130872261408275 * h + 0.000770482631801132 * n2 - 0.151051492775562) + h * (0.00126935368114843 * h - 0.00265090189010898 * n2 + 0.25802910206845) + n2 * (-0.000318913117588328 * n2 - 0.213742400323665); + Q2[E2++] = -20.810012546947 + f * (-0.000570115196973677 * f - 0.0000263409051004589 * G2 + 0.0020741088115012 * h - 0.00288260236853442 * n2 + 0.814272968359295) + G2 * (-0.0000153496057440975 * G2 - 0.000132689043961446 * h + 0.000560833691242812 * n2 - 0.195152027534049) + h * (0.00174418132927582 * h - 0.00255243321439347 * n2 + 0.116935020465145) + n2 * (-0.000343531996510555 * n2 + 0.24165260232407); + } + return Q2.subarray(0, E2); + }, r: function a3(Q2) { + var h, f, G2; + for (var n2 = 0, E2 = Q2.length;n2 < E2; n2 += 4) { + h = Q2[n2]; + f = Q2[n2 + 1]; + G2 = Q2[n2 + 2]; + Q2[n2] = 434.456 - h - 1.402 * G2; + Q2[n2 + 1] = 119.541 - h + 0.344 * f + 0.714 * G2; + Q2[n2 + 2] = 481.816 - h - 1.772 * f; + } + return Q2; + }, U: function as(Q2) { + var h, f, G2, n2, E2 = 0; + for (var a = 0, C4 = Q2.length;a < C4; a += 4) { + h = Q2[a]; + f = Q2[a + 1]; + G2 = Q2[a + 2]; + n2 = Q2[a + 3]; + Q2[E2++] = 255 + h * (-0.00006747147073602441 * h + 0.0008379262121013727 * f + 0.0002894718188643294 * G2 + 0.003264231057537806 * n2 - 1.1185611867203937) + f * (0.000026374107616089405 * f - 0.00008626949158638572 * G2 - 0.0002748769067499491 * n2 - 0.02155688794978967) + G2 * (-0.00003878099212869363 * G2 - 0.0003267808279485286 * n2 + 0.0686742238595345) - n2 * (0.0003361971776183937 * n2 + 0.7430659151342254); + Q2[E2++] = 255 + h * (0.00013596372813588848 * h + 0.000924537132573585 * f + 0.00010567359618683593 * G2 + 0.0004791864687436512 * n2 - 0.3109689587515875) + f * (-0.00023545346108370344 * f + 0.0002702845253534714 * G2 + 0.0020200308977307156 * n2 - 0.7488052167015494) + G2 * (0.00006834815998235662 * G2 + 0.00015168452363460973 * n2 - 0.09751927774728933) - n2 * (0.0003189131175883281 * n2 + 0.7364883807733168); + Q2[E2++] = 255 + h * (0.000013598650411385307 * h + 0.00012423956175490851 * f + 0.0004751985097583589 * G2 - 0.0000036729317476630422 * n2 - 0.05562186980264034) + f * (0.00016141380598724676 * f + 0.0009692239130725186 * G2 + 0.0007782692450036253 * n2 - 0.44015232367526463) + G2 * (0.0000005068882914068769 * G2 + 0.0017778369011375071 * n2 - 0.7591454649749609) - n2 * (0.0003435319965105553 * n2 + 0.7063770186160144); + } + return Q2.subarray(0, E2); + }, getData: function(Q2) { + var { width: h, height: f, forceRGB: G2, isSourcePDF: n2 } = Q2; + if (this.p > 4) { + throw new W("Unsupported color mode"); + } + var E2 = this.Y(h, f, n2); + if (this.p === 1 && G2) { + var a = E2.length, C4 = new Uint8ClampedArray(a * 3), F = 0; + for (var d = 0;d < a; d++) { + var T2 = E2[d]; + C4[F++] = T2; + C4[F++] = T2; + C4[F++] = T2; + } + return C4; + } else if (this.p === 3 && this.f) { + return this.z(E2); + } else if (this.p === 4) { + if (this.f) { + if (G2) { + return this.O(E2); + } + return this.r(E2); + } else if (G2) { + return this.U(E2); + } + } + return E2; + } }; + return ak2; + }(); + function a9(p, t2) { + return p[t2] << 24 >> 24; + } + function Z2(p, t2) { + return p[t2] << 8 | p[t2 + 1]; + } + function am(p, t2) { + return (p[t2] << 24 | p[t2 + 1] << 16 | p[t2 + 2] << 8 | p[t2 + 3]) >>> 0; + } + UTIF.JpegDecoder = ak; +})(); +UTIF.encodeImage = function(rgba, w, h, metadata) { + var idf = { + t256: [w], + t257: [h], + t258: [8, 8, 8, 8], + t259: [1], + t262: [2], + t273: [1000], + t277: [4], + t278: [h], + t279: [w * h * 4], + t282: [[72, 1]], + t283: [[72, 1]], + t284: [1], + t286: [[0, 1]], + t287: [[0, 1]], + t296: [1], + t305: ["Photopea (UTIF.js)"], + t338: [1] + }; + if (metadata) + for (var i in metadata) + idf[i] = metadata[i]; + var prfx = new Uint8Array(UTIF.encode([idf])); + var img = new Uint8Array(rgba); + var data2 = new Uint8Array(1000 + w * h * 4); + for (var i = 0;i < prfx.length; i++) + data2[i] = prfx[i]; + for (var i = 0;i < img.length; i++) + data2[1000 + i] = img[i]; + return data2.buffer; +}; +UTIF.encode = function(ifds) { + var LE = false; + var data2 = new Uint8Array(20000), offset = 4, bin = LE ? UTIF._binLE : UTIF._binBE; + data2[0] = data2[1] = LE ? 73 : 77; + bin.writeUshort(data2, 2, 42); + var ifdo = 8; + bin.writeUint(data2, offset, ifdo); + offset += 4; + for (var i = 0;i < ifds.length; i++) { + var noffs = UTIF._writeIFD(bin, UTIF._types.basic, data2, ifdo, ifds[i]); + ifdo = noffs[1]; + if (i < ifds.length - 1) { + if ((ifdo & 3) != 0) + ifdo += 4 - (ifdo & 3); + bin.writeUint(data2, noffs[0], ifdo); + } + } + return data2.slice(0, ifdo).buffer; +}; +UTIF.decode = function(buff, prm) { + if (prm == null) + prm = { parseMN: true, debug: false }; + var data2 = new Uint8Array(buff), offset = 0; + var id = UTIF._binBE.readASCII(data2, offset, 2); + offset += 2; + var bin = id == "II" ? UTIF._binLE : UTIF._binBE; + var num = bin.readUshort(data2, offset); + offset += 2; + var ifdo = bin.readUint(data2, offset); + offset += 4; + var ifds = []; + while (true) { + var cnt = bin.readUshort(data2, ifdo), typ = bin.readUshort(data2, ifdo + 4); + if (cnt != 0) { + if (typ < 1 || 13 < typ) { + log("error in TIFF"); + break; + } + } + UTIF._readIFD(bin, data2, ifdo, ifds, 0, prm); + ifdo = bin.readUint(data2, ifdo + 2 + cnt * 12); + if (ifdo == 0) + break; + } + return ifds; +}; +UTIF.decodeImage = function(buff, img, ifds) { + if (img.data) + return; + var data2 = new Uint8Array(buff); + var id = UTIF._binBE.readASCII(data2, 0, 2); + if (img["t256"] == null) + return; + img.isLE = id == "II"; + img.width = img["t256"][0]; + img.height = img["t257"][0]; + var cmpr = img["t259"] ? img["t259"][0] : 1; + var fo = img["t266"] ? img["t266"][0] : 1; + if (img["t284"] && img["t284"][0] == 2) + log("PlanarConfiguration 2 should not be used!"); + if (cmpr == 7 && img["t258"] && img["t258"].length > 3) + img["t258"] = img["t258"].slice(0, 3); + var spp = img["t277"] ? img["t277"][0] : 1; + var bps = img["t258"] ? img["t258"][0] : 1; + var bipp = bps * spp; + if (cmpr == 1 && img["t279"] != null && img["t278"] && img["t262"][0] == 32803) { + bipp = Math.round(img["t279"][0] * 8 / (img.width * img["t278"][0])); + } + if (img["t50885"] && img["t50885"][0] == 4) + bipp = img["t258"][0] * 3; + var bipl = Math.ceil(img.width * bipp / 8) * 8; + var soff = img["t273"]; + if (soff == null || img["t322"]) + soff = img["t324"]; + var bcnt = img["t279"]; + if (cmpr == 1 && soff.length == 1) + bcnt = [img.height * (bipl >>> 3)]; + if (bcnt == null || img["t322"]) + bcnt = img["t325"]; + var bytes = new Uint8Array(img.height * (bipl >>> 3)), bilen = 0; + if (img["t322"] != null) { + var tw = img["t322"][0], th = img["t323"][0]; + var tx = Math.floor((img.width + tw - 1) / tw); + var ty = Math.floor((img.height + th - 1) / th); + var tbuff = new Uint8Array(Math.ceil(tw * th * bipp / 8) | 0); + console.log("====", tx, ty); + for (var y = 0;y < ty; y++) + for (var x2 = 0;x2 < tx; x2++) { + var i = y * tx + x2; + tbuff.fill(0); + UTIF.decode._decompress(img, ifds, data2, soff[i], bcnt[i], cmpr, tbuff, 0, fo, tw, th); + if (cmpr == 6) + bytes = tbuff; + else + UTIF._copyTile(tbuff, Math.ceil(tw * bipp / 8) | 0, th, bytes, Math.ceil(img.width * bipp / 8) | 0, img.height, Math.ceil(x2 * tw * bipp / 8) | 0, y * th); + } + bilen = bytes.length * 8; + } else { + if (soff == null) + return; + var rps = img["t278"] ? img["t278"][0] : img.height; + rps = Math.min(rps, img.height); + for (var i = 0;i < soff.length; i++) { + UTIF.decode._decompress(img, ifds, data2, soff[i], bcnt[i], cmpr, bytes, Math.ceil(bilen / 8) | 0, fo, img.width, rps); + bilen += bipl * rps; + } + bilen = Math.min(bilen, bytes.length * 8); + } + img.data = new Uint8Array(bytes.buffer, 0, Math.ceil(bilen / 8) | 0); +}; +UTIF.decode._decompress = function(img, ifds, data2, off, len, cmpr, tgt, toff, fo, w, h) { + if (img["t271"] && img["t271"][0] == "Panasonic" && img["t45"] && img["t45"][0] == 6) + cmpr = 34316; + if (false) { + } else if (cmpr == 1) + for (var j2 = 0;j2 < len; j2++) + tgt[toff + j2] = data2[off + j2]; + else if (cmpr == 2) + UTIF.decode._decodeG2(data2, off, len, tgt, toff, w, fo); + else if (cmpr == 3) + UTIF.decode._decodeG3(data2, off, len, tgt, toff, w, fo, img["t292"] ? (img["t292"][0] & 1) == 1 : false); + else if (cmpr == 4) + UTIF.decode._decodeG4(data2, off, len, tgt, toff, w, fo); + else if (cmpr == 5) + UTIF.decode._decodeLZW(data2, off, len, tgt, toff, 8); + else if (cmpr == 6) + UTIF.decode._decodeOldJPEG(img, data2, off, len, tgt, toff); + else if (cmpr == 7 || cmpr == 34892) + UTIF.decode._decodeNewJPEG(img, data2, off, len, tgt, toff); + else if (cmpr == 8 || cmpr == 32946) { + var src = new Uint8Array(data2.buffer, off + 2, len - 6); + var bin = UTIF._inflateRaw(src); + if (toff + bin.length <= tgt.length) + tgt.set(bin, toff); + } else if (cmpr == 9) + UTIF.decode._decodeVC5(data2, off, len, tgt, toff, img["t33422"]); + else if (cmpr == 32767) + UTIF.decode._decodeARW(img, data2, off, len, tgt, toff); + else if (cmpr == 32773) + UTIF.decode._decodePackBits(data2, off, len, tgt, toff); + else if (cmpr == 32809) + UTIF.decode._decodeThunder(data2, off, len, tgt, toff); + else if (cmpr == 34316) + UTIF.decode._decodePanasonic(img, data2, off, len, tgt, toff); + else if (cmpr == 34713) + UTIF.decode._decodeNikon(img, ifds, data2, off, len, tgt, toff); + else if (cmpr == 34676) + UTIF.decode._decodeLogLuv32(img, data2, off, len, tgt, toff); + else + log("Unknown compression", cmpr); + var bps = img["t258"] ? Math.min(32, img["t258"][0]) : 1; + var noc = img["t277"] ? img["t277"][0] : 1, bpp = bps * noc >>> 3, bpl = Math.ceil(bps * noc * w / 8); + if (bps == 16 && !img.isLE && img["t33422"] == null) + for (var y = 0;y < h; y++) { + var roff = toff + y * bpl; + for (var x2 = 1;x2 < bpl; x2 += 2) { + var t2 = tgt[roff + x2]; + tgt[roff + x2] = tgt[roff + x2 - 1]; + tgt[roff + x2 - 1] = t2; + } + } + if (img["t317"] && img["t317"][0] == 2) { + for (var y = 0;y < h; y++) { + var ntoff = toff + y * bpl; + if (bps == 16) + for (var j2 = bpp;j2 < bpl; j2 += 2) { + var nv = (tgt[ntoff + j2 + 1] << 8 | tgt[ntoff + j2]) + (tgt[ntoff + j2 - bpp + 1] << 8 | tgt[ntoff + j2 - bpp]); + tgt[ntoff + j2] = nv & 255; + tgt[ntoff + j2 + 1] = nv >>> 8 & 255; + } + else if (noc == 3) + for (var j2 = 3;j2 < bpl; j2 += 3) { + tgt[ntoff + j2] = tgt[ntoff + j2] + tgt[ntoff + j2 - 3] & 255; + tgt[ntoff + j2 + 1] = tgt[ntoff + j2 + 1] + tgt[ntoff + j2 - 2] & 255; + tgt[ntoff + j2 + 2] = tgt[ntoff + j2 + 2] + tgt[ntoff + j2 - 1] & 255; + } + else + for (var j2 = bpp;j2 < bpl; j2++) + tgt[ntoff + j2] = tgt[ntoff + j2] + tgt[ntoff + j2 - bpp] & 255; + } + } +}; +UTIF.decode._decodePanasonic = function(img, data2, off, len, tgt, toff) { + var img_buffer = data2.buffer; + var rawWidth = img["t2"][0]; + var rawHeight = img["t3"][0]; + var bitsPerSample = img["t10"][0]; + var RW2_Format = img["t45"][0]; + var bidx = 0; + var imageIndex = 0; + var vpos = 0; + var byte = 0; + var arr_a, arr_b; + var bytes = RW2_Format == 6 ? new Uint32Array(18) : new Uint8Array(16); + var i, j2, sh, pred = [0, 0], nonz = [0, 0], isOdd, idx = 0, pixel_base; + var row, col, crow; + var buffer = new Uint8Array(16384); + var result = new Uint16Array(tgt.buffer); + function getDataRaw(bits) { + if (vpos == 0) { + var arr_a2 = new Uint8Array(img_buffer, off + imageIndex + 8184, 16384 - 8184); + var arr_b2 = new Uint8Array(img_buffer, off + imageIndex, 8184); + buffer.set(arr_a2); + buffer.set(arr_b2, arr_a2.length); + imageIndex += 16384; + } + if (RW2_Format == 5) { + for (i = 0;i < 16; i++) { + bytes[i] = buffer[vpos++]; + vpos &= 16383; + } + } else { + vpos = vpos - bits & 131071; + byte = vpos >> 3 ^ 16368; + return (buffer[byte] | buffer[byte + 1] << 8) >> (vpos & 7) & ~(-1 << bits); + } + } + function getBufferDataRW6(i2) { + return buffer[vpos + 15 - i2]; + } + function readPageRW6() { + bytes[0] = getBufferDataRW6(0) << 6 | getBufferDataRW6(1) >> 2; + bytes[1] = ((getBufferDataRW6(1) & 3) << 12 | getBufferDataRW6(2) << 4 | getBufferDataRW6(3) >> 4) & 16383; + bytes[2] = getBufferDataRW6(3) >> 2 & 3; + bytes[3] = (getBufferDataRW6(3) & 3) << 8 | getBufferDataRW6(4); + bytes[4] = getBufferDataRW6(5) << 2 | getBufferDataRW6(6) >> 6; + bytes[5] = (getBufferDataRW6(6) & 63) << 4 | getBufferDataRW6(7) >> 4; + bytes[6] = getBufferDataRW6(7) >> 2 & 3; + bytes[7] = (getBufferDataRW6(7) & 3) << 8 | getBufferDataRW6(8); + bytes[8] = getBufferDataRW6(9) << 2 & 1020 | getBufferDataRW6(10) >> 6; + bytes[9] = (getBufferDataRW6(10) << 4 | getBufferDataRW6(11) >> 4) & 1023; + bytes[10] = getBufferDataRW6(11) >> 2 & 3; + bytes[11] = (getBufferDataRW6(11) & 3) << 8 | getBufferDataRW6(12); + bytes[12] = (getBufferDataRW6(13) << 2 & 1020 | getBufferDataRW6(14) >> 6) & 1023; + bytes[13] = (getBufferDataRW6(14) << 4 | getBufferDataRW6(15) >> 4) & 1023; + vpos += 16; + byte = 0; + } + function readPageRw6_bps12() { + bytes[0] = getBufferDataRW6(0) << 4 | getBufferDataRW6(1) >> 4; + bytes[1] = ((getBufferDataRW6(1) & 15) << 8 | getBufferDataRW6(2)) & 4095; + bytes[2] = getBufferDataRW6(3) >> 6 & 3; + bytes[3] = (getBufferDataRW6(3) & 63) << 2 | getBufferDataRW6(4) >> 6; + bytes[4] = (getBufferDataRW6(4) & 63) << 2 | getBufferDataRW6(5) >> 6; + bytes[5] = (getBufferDataRW6(5) & 63) << 2 | getBufferDataRW6(6) >> 6; + bytes[6] = getBufferDataRW6(6) >> 4 & 3; + bytes[7] = (getBufferDataRW6(6) & 15) << 4 | getBufferDataRW6(7) >> 4; + bytes[8] = (getBufferDataRW6(7) & 15) << 4 | getBufferDataRW6(8) >> 4; + bytes[9] = (getBufferDataRW6(8) & 15) << 4 | getBufferDataRW6(9) >> 4; + bytes[10] = getBufferDataRW6(9) >> 2 & 3; + bytes[11] = (getBufferDataRW6(9) & 3) << 6 | getBufferDataRW6(10) >> 2; + bytes[12] = (getBufferDataRW6(10) & 3) << 6 | getBufferDataRW6(11) >> 2; + bytes[13] = (getBufferDataRW6(11) & 3) << 6 | getBufferDataRW6(12) >> 2; + bytes[14] = getBufferDataRW6(12) & 3; + bytes[15] = getBufferDataRW6(13); + bytes[16] = getBufferDataRW6(14); + bytes[17] = getBufferDataRW6(15); + vpos += 16; + byte = 0; + } + function resetPredNonzeros() { + pred[0] = 0; + pred[1] = 0; + nonz[0] = 0; + nonz[1] = 0; + } + if (RW2_Format == 7) { + throw RW2_Format; + } else if (RW2_Format == 6) { + var is12bit = bitsPerSample == 12, readPageRw6Fn = is12bit ? readPageRw6_bps12 : readPageRW6, pixelsPerBlock = is12bit ? 14 : 11, pixelbase0 = is12bit ? 128 : 512, pixelbase_compare = is12bit ? 2048 : 8192, spix_compare = is12bit ? 16383 : 65535, pixel_mask = is12bit ? 4095 : 16383, blocksperrow = rawWidth / pixelsPerBlock, rowbytes = blocksperrow * 16, bufferSize = is12bit ? 18 : 14; + for (row = 0;row < rawHeight - 15; row += 16) { + var rowstoread = Math.min(16, rawHeight - row); + var readlen = rowbytes * rowstoread; + buffer = new Uint8Array(img_buffer, off + bidx, readlen); + vpos = 0; + bidx += readlen; + for (crow = 0, col = 0;crow < rowstoread; crow++, col = 0) { + idx = (row + crow) * rawWidth; + for (var rblock = 0;rblock < blocksperrow; rblock++) { + readPageRw6Fn(); + resetPredNonzeros(); + sh = 0; + pixel_base = 0; + for (i = 0;i < pixelsPerBlock; i++) { + isOdd = i & 1; + if (i % 3 == 2) { + var base = byte < bufferSize ? bytes[byte++] : 0; + if (base == 3) + base = 4; + pixel_base = pixelbase0 << base; + sh = 1 << base; + } + var epixel = byte < bufferSize ? bytes[byte++] : 0; + if (pred[isOdd]) { + epixel *= sh; + if (pixel_base < pixelbase_compare && nonz[isOdd] > pixel_base) + epixel += nonz[isOdd] - pixel_base; + nonz[isOdd] = epixel; + } else { + pred[isOdd] = epixel; + if (epixel) + nonz[isOdd] = epixel; + else + epixel = nonz[isOdd]; + } + result[idx + col++] = epixel - 15 <= spix_compare ? epixel - 15 & spix_compare : epixel + 2147483633 >> 31 & pixel_mask; + } + } + } + } + } else if (RW2_Format == 5) { + var blockSize = bitsPerSample == 12 ? 10 : 9; + for (row = 0;row < rawHeight; row++) { + for (col = 0;col < rawWidth; col += blockSize) { + getDataRaw(0); + if (bitsPerSample == 12) { + result[idx++] = ((bytes[1] & 15) << 8) + bytes[0]; + result[idx++] = 16 * bytes[2] + (bytes[1] >> 4); + result[idx++] = ((bytes[4] & 15) << 8) + bytes[3]; + result[idx++] = 16 * bytes[5] + (bytes[4] >> 4); + result[idx++] = ((bytes[7] & 15) << 8) + bytes[6]; + result[idx++] = 16 * bytes[8] + (bytes[7] >> 4); + result[idx++] = ((bytes[10] & 15) << 8) + bytes[9]; + result[idx++] = 16 * bytes[11] + (bytes[10] >> 4); + result[idx++] = ((bytes[13] & 15) << 8) + bytes[12]; + result[idx++] = 16 * bytes[14] + (bytes[13] >> 4); + } else if (bitsPerSample == 14) { + result[idx++] = bytes[0] + ((bytes[1] & 63) << 8); + result[idx++] = (bytes[1] >> 6) + 4 * bytes[2] + ((bytes[3] & 15) << 10); + result[idx++] = (bytes[3] >> 4) + 16 * bytes[4] + ((bytes[5] & 3) << 12); + result[idx++] = ((bytes[5] & 252) >> 2) + (bytes[6] << 6); + result[idx++] = bytes[7] + ((bytes[8] & 63) << 8); + result[idx++] = (bytes[8] >> 6) + 4 * bytes[9] + ((bytes[10] & 15) << 10); + result[idx++] = (bytes[10] >> 4) + 16 * bytes[11] + ((bytes[12] & 3) << 12); + result[idx++] = ((bytes[12] & 252) >> 2) + (bytes[13] << 6); + result[idx++] = bytes[14] + ((bytes[15] & 63) << 8); + } + } + } + } else if (RW2_Format == 4) { + for (row = 0;row < rawHeight; row++) { + for (col = 0;col < rawWidth; col++) { + i = col % 14; + isOdd = i & 1; + if (i == 0) + resetPredNonzeros(); + if (i % 3 == 2) + sh = 4 >> 3 - getDataRaw(2); + if (nonz[isOdd]) { + j2 = getDataRaw(8); + if (j2 != 0) { + pred[isOdd] -= 128 << sh; + if (pred[isOdd] < 0 || sh == 4) + pred[isOdd] &= ~(-1 << sh); + pred[isOdd] += j2 << sh; + } + } else { + nonz[isOdd] = getDataRaw(8); + if (nonz[isOdd] || i > 11) + pred[isOdd] = nonz[isOdd] << 4 | getDataRaw(4); + } + result[idx++] = pred[col & 1]; + } + } + } else + throw RW2_Format; +}; +UTIF.decode._decodeVC5 = function() { + var x2 = [1, 0, 1, 0, 2, 2, 1, 1, 3, 7, 1, 2, 5, 25, 1, 3, 6, 48, 1, 4, 6, 54, 1, 5, 7, 111, 1, 8, 7, 99, 1, 6, 7, 105, 12, 0, 7, 107, 1, 7, 8, 209, 20, 0, 8, 212, 1, 9, 8, 220, 1, 10, 9, 393, 1, 11, 9, 394, 32, 0, 9, 416, 1, 12, 9, 427, 1, 13, 10, 887, 1, 18, 10, 784, 1, 14, 10, 790, 1, 15, 10, 835, 60, 0, 10, 852, 1, 16, 10, 885, 1, 17, 11, 1571, 1, 19, 11, 1668, 1, 20, 11, 1669, 100, 0, 11, 1707, 1, 21, 11, 1772, 1, 22, 12, 3547, 1, 29, 12, 3164, 1, 24, 12, 3166, 1, 25, 12, 3140, 1, 23, 12, 3413, 1, 26, 12, 3537, 1, 27, 12, 3539, 1, 28, 13, 7093, 1, 35, 13, 6283, 1, 30, 13, 6331, 1, 31, 13, 6335, 180, 0, 13, 6824, 1, 32, 13, 7072, 1, 33, 13, 7077, 320, 0, 13, 7076, 1, 34, 14, 12565, 1, 36, 14, 12661, 1, 37, 14, 12669, 1, 38, 14, 13651, 1, 39, 14, 14184, 1, 40, 15, 28295, 1, 46, 15, 28371, 1, 47, 15, 25320, 1, 42, 15, 25336, 1, 43, 15, 25128, 1, 41, 15, 27300, 1, 44, 15, 28293, 1, 45, 16, 50259, 1, 48, 16, 50643, 1, 49, 16, 50675, 1, 50, 16, 56740, 1, 53, 16, 56584, 1, 51, 16, 56588, 1, 52, 17, 113483, 1, 61, 17, 113482, 1, 60, 17, 101285, 1, 55, 17, 101349, 1, 56, 17, 109205, 1, 57, 17, 109207, 1, 58, 17, 100516, 1, 54, 17, 113171, 1, 59, 18, 202568, 1, 62, 18, 202696, 1, 63, 18, 218408, 1, 64, 18, 218412, 1, 65, 18, 226340, 1, 66, 18, 226356, 1, 67, 18, 226358, 1, 68, 19, 402068, 1, 69, 19, 405138, 1, 70, 19, 405394, 1, 71, 19, 436818, 1, 72, 19, 436826, 1, 73, 19, 452714, 1, 75, 19, 452718, 1, 76, 19, 452682, 1, 74, 20, 804138, 1, 77, 20, 810279, 1, 78, 20, 810790, 1, 79, 20, 873638, 1, 80, 20, 873654, 1, 81, 20, 905366, 1, 82, 20, 905430, 1, 83, 20, 905438, 1, 84, 21, 1608278, 1, 85, 21, 1620557, 1, 86, 21, 1621582, 1, 87, 21, 1621583, 1, 88, 21, 1747310, 1, 89, 21, 1810734, 1, 90, 21, 1810735, 1, 91, 21, 1810863, 1, 92, 21, 1810879, 1, 93, 22, 3621725, 1, 99, 22, 3621757, 1, 100, 22, 3241112, 1, 94, 22, 3494556, 1, 95, 22, 3494557, 1, 96, 22, 3494622, 1, 97, 22, 3494623, 1, 98, 23, 6482227, 1, 102, 23, 6433117, 1, 101, 23, 6989117, 1, 103, 23, 6989119, 1, 105, 23, 6989118, 1, 104, 23, 7243449, 1, 106, 23, 7243512, 1, 107, 24, 13978233, 1, 111, 24, 12964453, 1, 109, 24, 12866232, 1, 108, 24, 14486897, 1, 113, 24, 13978232, 1, 110, 24, 14486896, 1, 112, 24, 14487026, 1, 114, 24, 14487027, 1, 115, 25, 25732598, 1, 225, 25, 25732597, 1, 189, 25, 25732596, 1, 188, 25, 25732595, 1, 203, 25, 25732594, 1, 202, 25, 25732593, 1, 197, 25, 25732592, 1, 207, 25, 25732591, 1, 169, 25, 25732590, 1, 223, 25, 25732589, 1, 159, 25, 25732522, 1, 235, 25, 25732579, 1, 152, 25, 25732575, 1, 192, 25, 25732489, 1, 179, 25, 25732573, 1, 201, 25, 25732472, 1, 172, 25, 25732576, 1, 149, 25, 25732488, 1, 178, 25, 25732566, 1, 120, 25, 25732571, 1, 219, 25, 25732577, 1, 150, 25, 25732487, 1, 127, 25, 25732506, 1, 211, 25, 25732548, 1, 125, 25, 25732588, 1, 158, 25, 25732486, 1, 247, 25, 25732467, 1, 238, 25, 25732508, 1, 163, 25, 25732552, 1, 228, 25, 25732603, 1, 183, 25, 25732513, 1, 217, 25, 25732587, 1, 168, 25, 25732520, 1, 122, 25, 25732484, 1, 128, 25, 25732562, 1, 249, 25, 25732505, 1, 187, 25, 25732504, 1, 186, 25, 25732483, 1, 136, 25, 25928905, 1, 181, 25, 25732560, 1, 255, 25, 25732500, 1, 230, 25, 25732482, 1, 135, 25, 25732555, 1, 233, 25, 25732568, 1, 222, 25, 25732583, 1, 145, 25, 25732481, 1, 134, 25, 25732586, 1, 167, 25, 25732521, 1, 248, 25, 25732518, 1, 209, 25, 25732480, 1, 243, 25, 25732512, 1, 216, 25, 25732509, 1, 164, 25, 25732547, 1, 140, 25, 25732479, 1, 157, 25, 25732544, 1, 239, 25, 25732574, 1, 191, 25, 25732564, 1, 251, 25, 25732478, 1, 156, 25, 25732546, 1, 139, 25, 25732498, 1, 242, 25, 25732557, 1, 133, 25, 25732477, 1, 162, 25, 25732515, 1, 213, 25, 25732584, 1, 165, 25, 25732514, 1, 212, 25, 25732476, 1, 227, 25, 25732494, 1, 198, 25, 25732531, 1, 236, 25, 25732530, 1, 234, 25, 25732529, 1, 117, 25, 25732528, 1, 215, 25, 25732527, 1, 124, 25, 25732526, 1, 123, 25, 25732525, 1, 254, 25, 25732524, 1, 253, 25, 25732523, 1, 148, 25, 25732570, 1, 218, 25, 25732580, 1, 146, 25, 25732581, 1, 147, 25, 25732569, 1, 224, 25, 25732533, 1, 143, 25, 25732540, 1, 184, 25, 25732541, 1, 185, 25, 25732585, 1, 166, 25, 25732556, 1, 132, 25, 25732485, 1, 129, 25, 25732563, 1, 250, 25, 25732578, 1, 151, 25, 25732501, 1, 119, 25, 25732502, 1, 193, 25, 25732536, 1, 176, 25, 25732496, 1, 245, 25, 25732553, 1, 229, 25, 25732516, 1, 206, 25, 25732582, 1, 144, 25, 25732517, 1, 208, 25, 25732558, 1, 137, 25, 25732543, 1, 241, 25, 25732466, 1, 237, 25, 25732507, 1, 190, 25, 25732542, 1, 240, 25, 25732551, 1, 131, 25, 25732554, 1, 232, 25, 25732565, 1, 252, 25, 25732475, 1, 171, 25, 25732493, 1, 205, 25, 25732492, 1, 204, 25, 25732491, 1, 118, 25, 25732490, 1, 214, 25, 25928904, 1, 180, 25, 25732549, 1, 126, 25, 25732602, 1, 182, 25, 25732539, 1, 175, 25, 25732545, 1, 141, 25, 25732559, 1, 138, 25, 25732537, 1, 177, 25, 25732534, 1, 153, 25, 25732503, 1, 194, 25, 25732606, 1, 160, 25, 25732567, 1, 121, 25, 25732538, 1, 174, 25, 25732497, 1, 246, 25, 25732550, 1, 130, 25, 25732572, 1, 200, 25, 25732474, 1, 170, 25, 25732511, 1, 221, 25, 25732601, 1, 196, 25, 25732532, 1, 142, 25, 25732519, 1, 210, 25, 25732495, 1, 199, 25, 25732605, 1, 155, 25, 25732535, 1, 154, 25, 25732499, 1, 244, 25, 25732510, 1, 220, 25, 25732600, 1, 195, 25, 25732607, 1, 161, 25, 25732604, 1, 231, 25, 25732473, 1, 173, 25, 25732599, 1, 226, 26, 51465122, 1, 116, 26, 51465123, 0, 1], o, C4, k2, P = [3, 3, 3, 3, 2, 2, 2, 1, 1, 1], V2 = 24576, ar = 16384, H = 8192, az = ar | H; + function d(t2) { + var E2 = t2[1], h = t2[0][E2 >>> 3] >>> 7 - (E2 & 7) & 1; + t2[1]++; + return h; + } + function ag(t2, E2) { + if (o == null) { + o = {}; + for (var h = 0;h < x2.length; h += 4) + o[x2[h + 1]] = x2.slice(h, h + 4); + } + var L = d(t2), g3 = o[L]; + while (g3 == null) { + L = L << 1 | d(t2); + g3 = o[L]; + } + var n2 = g3[3]; + if (n2 != 0) + n2 = d(t2) == 0 ? n2 : -n2; + E2[0] = g3[2]; + E2[1] = n2; + } + function m(t2, E2) { + for (var h = 0;h < E2; h++) { + if ((t2 & 1) == 1) + t2++; + t2 = t2 >>> 1; + } + return t2; + } + function A2(t2, E2) { + return t2 >> E2; + } + function O(t2, E2, h, L, g3, n2) { + E2[h] = A2(A2(11 * t2[g3] - 4 * t2[g3 + n2] + t2[g3 + n2 + n2] + 4, 3) + t2[L], 1); + E2[h + n2] = A2(A2(5 * t2[g3] + 4 * t2[g3 + n2] - t2[g3 + n2 + n2] + 4, 3) - t2[L], 1); + } + function J2(t2, E2, h, L, g3, n2) { + var W = t2[g3 - n2] - t2[g3 + n2], j2 = t2[g3], $2 = t2[L]; + E2[h] = A2(A2(W + 4, 3) + j2 + $2, 1); + E2[h + n2] = A2(A2(-W + 4, 3) + j2 - $2, 1); + } + function y(t2, E2, h, L, g3, n2) { + E2[h] = A2(A2(5 * t2[g3] + 4 * t2[g3 - n2] - t2[g3 - n2 - n2] + 4, 3) + t2[L], 1); + E2[h + n2] = A2(A2(11 * t2[g3] - 4 * t2[g3 - n2] + t2[g3 - n2 - n2] + 4, 3) - t2[L], 1); + } + function q2(t2) { + t2 = t2 < 0 ? 0 : t2 > 4095 ? 4095 : t2; + t2 = k2[t2] >>> 2; + return t2; + } + function av(t2, E2, h, L, g3, n2) { + L = new Uint16Array(L.buffer); + var W = Date.now(), j2 = UTIF._binBE, $2 = E2 + h, r, u2, X, I3, ax, a3, R2, ai, aa, ap, ah, ae3, aD, al2, i, aE, T2, B2; + E2 += 4; + var a5 = n2[0] == 1; + while (E2 < $2) { + var S = j2.readShort(t2, E2), s = j2.readUshort(t2, E2 + 2); + E2 += 4; + if (S == 12) + r = s; + else if (S == 20) + u2 = s; + else if (S == 21) + X = s; + else if (S == 48) + I3 = s; + else if (S == 53) + ax = s; + else if (S == 35) + a3 = s; + else if (S == 62) + R2 = s; + else if (S == 101) + ai = s; + else if (S == 109) + aa = s; + else if (S == 84) + ap = s; + else if (S == 106) + ah = s; + else if (S == 107) + ae3 = s; + else if (S == 108) + aD = s; + else if (S == 102) + al2 = s; + else if (S == 104) + i = s; + else if (S == 105) + aE = s; + else { + var F = S < 0 ? -S : S, D = F & 65280, _2 = 0; + if (F & az) { + if (F & H) { + _2 = s & 65535; + _2 += (F & 255) << 16; + } else { + _2 = s & 65535; + } + } + if ((F & V2) == V2) { + if (T2 == null) { + T2 = []; + for (var M = 0;M < 4; M++) + T2[M] = new Int16Array((u2 >>> 1) * (X >>> 1)); + B2 = new Int16Array((u2 >>> 1) * (X >>> 1)); + C4 = new Int16Array(1024); + for (var M = 0;M < 1024; M++) { + var aG = M - 512, p = Math.abs(aG), r = Math.floor(768 * p * p * p / (255 * 255 * 255)) + p; + C4[M] = Math.sign(aG) * r; + } + k2 = new Uint16Array(4096); + var aA = (1 << 16) - 1; + for (var M = 0;M < 4096; M++) { + var at = M, a1 = aA * (Math.pow(113, at / 4095) - 1) / 112; + k2[M] = Math.min(a1, aA); + } + } + var w = T2[R2], v = m(u2, 1 + P[I3]), N = m(X, 1 + P[I3]); + if (I3 == 0) { + for (var b = 0;b < N; b++) + for (var G2 = 0;G2 < v; G2++) { + var c = E2 + (b * v + G2) * 2; + w[b * (u2 >>> 1) + G2] = t2[c] << 8 | t2[c + 1]; + } + } else { + var a7 = [t2, E2 * 8], a4 = [], ay = 0, aw = v * N, f = [0, 0], Q2 = 0, s = 0; + while (ay < aw) { + ag(a7, f); + Q2 = f[0]; + s = f[1]; + while (Q2 > 0) { + a4[ay++] = s; + Q2--; + } + } + var l2 = (I3 - 1) % 3, aF = l2 != 1 ? v : 0, a2 = l2 != 0 ? N : 0; + for (var b = 0;b < N; b++) { + var af = (b + a2) * (u2 >>> 1) + aF, au = b * v; + for (var G2 = 0;G2 < v; G2++) + w[af + G2] = C4[a4[au + G2] + 512] * ax; + } + if (l2 == 2) { + var i = u2 >>> 1, an = v * 2, a9 = N * 2; + for (var b = 0;b < N; b++) { + for (var G2 = 0;G2 < an; G2++) { + var M = b * 2 * i + G2, a = b * i + G2, e = N * i + a; + if (b == 0) + O(w, B2, M, e, a, i); + else if (b == N - 1) + y(w, B2, M, e, a, i); + else + J2(w, B2, M, e, a, i); + } + } + var Z2 = w; + w = B2; + B2 = Z2; + for (var b = 0;b < a9; b++) { + for (var G2 = 0;G2 < v; G2++) { + var M = b * i + 2 * G2, a = b * i + G2, e = v + a; + if (G2 == 0) + O(w, B2, M, e, a, 1); + else if (G2 == v - 1) + y(w, B2, M, e, a, 1); + else + J2(w, B2, M, e, a, 1); + } + } + var Z2 = w; + w = B2; + B2 = Z2; + var aC = [], aB = 2 - ~~((I3 - 1) / 3); + for (var K = 0;K < 3; K++) + aC[K] = aa >> 14 - K * 2 & 3; + var a6 = aC[aB]; + if (a6 != 0) + for (var b = 0;b < a9; b++) + for (var G2 = 0;G2 < an; G2++) { + var M = b * i + G2; + w[M] = w[M] << a6; + } + } + } + if (I3 == 9 && R2 == 3) { + var a8 = T2[0], ab = T2[1], aq = T2[2], as = T2[3]; + for (var b = 0;b < X; b += 2) + for (var G2 = 0;G2 < u2; G2 += 2) { + var U = b * u2 + G2, c = (b >>> 1) * (u2 >>> 1) + (G2 >>> 1), z = a8[c], ao = ab[c] - 2048, ak = aq[c] - 2048, ad = as[c] - 2048, aj = (ao << 1) + z, a0 = (ak << 1) + z, aH = z + ad, am = z - ad; + if (a5) { + L[U] = q2(aH); + L[U + 1] = q2(a0); + L[U + u2] = q2(aj); + L[U + u2 + 1] = q2(am); + } else { + L[U] = q2(aj); + L[U + 1] = q2(aH); + L[U + u2] = q2(am); + L[U + u2 + 1] = q2(a0); + } + } + } + E2 += _2 * 4; + } else if (F == 16388) { + E2 += _2 * 4; + } else if (D == 8192 || D == 8448 || D == 9216) { + } else + throw F.toString(16); + } + } + console.log(Date.now() - W); + } + return av; +}(); +UTIF.decode._decodeLogLuv32 = function(img, data2, off, len, tgt, toff) { + var w = img.width, qw = w * 4; + var io = 0, out = new Uint8Array(qw); + while (io < len) { + var oo = 0; + while (oo < qw) { + var c = data2[off + io]; + io++; + if (c < 128) { + for (var j2 = 0;j2 < c; j2++) + out[oo + j2] = data2[off + io + j2]; + oo += c; + io += c; + } else { + c = c - 126; + for (var j2 = 0;j2 < c; j2++) + out[oo + j2] = data2[off + io]; + oo += c; + io++; + } + } + for (var x2 = 0;x2 < w; x2++) { + tgt[toff + 0] = out[x2]; + tgt[toff + 1] = out[x2 + w]; + tgt[toff + 2] = out[x2 + w * 2]; + tgt[toff + 4] = out[x2 + w * 3]; + toff += 6; + } + } +}; +UTIF.decode._ljpeg_diff = function(data2, prm, huff) { + var getbithuff = UTIF.decode._getbithuff; + var len, diff; + len = getbithuff(data2, prm, huff[0], huff); + diff = getbithuff(data2, prm, len, 0); + if ((diff & 1 << len - 1) == 0) + diff -= (1 << len) - 1; + return diff; +}; +UTIF.decode._decodeARW = function(img, inp, off, src_length, tgt, toff) { + var raw_width = img["t256"][0], height2 = img["t257"][0], tiff_bps = img["t258"][0]; + var bin = img.isLE ? UTIF._binLE : UTIF._binBE; + var arw2 = raw_width * height2 == src_length || raw_width * height2 * 1.5 == src_length; + if (!arw2) { + height2 += 8; + var prm = [off, 0, 0, 0]; + var huff = new Uint16Array(32770); + var tab = [ + 3857, + 3856, + 3599, + 3342, + 3085, + 2828, + 2571, + 2314, + 2057, + 1800, + 1543, + 1286, + 1029, + 772, + 771, + 768, + 514, + 513 + ]; + var i, c, n2, col, row, sum2 = 0; + var ljpeg_diff = UTIF.decode._ljpeg_diff; + huff[0] = 15; + for (n2 = i = 0;i < 18; i++) { + var lim = 32768 >>> (tab[i] >>> 8); + for (var c = 0;c < lim; c++) + huff[++n2] = tab[i]; + } + for (col = raw_width;col--; ) + for (row = 0;row < height2 + 1; row += 2) { + if (row == height2) + row = 1; + sum2 += ljpeg_diff(inp, prm, huff); + if (row < height2) { + var clr = sum2 & 4095; + UTIF.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps); + } + } + return; + } + if (raw_width * height2 * 1.5 == src_length) { + for (var i = 0;i < src_length; i += 3) { + var b0 = inp[off + i + 0], b1 = inp[off + i + 1], b2 = inp[off + i + 2]; + tgt[toff + i] = b1 << 4 | b0 >>> 4; + tgt[toff + i + 1] = b0 << 4 | b2 >>> 4; + tgt[toff + i + 2] = b2 << 4 | b1 >>> 4; + } + return; + } + var pix = new Uint16Array(16); + var row, col, val2, max, min, imax, imin, sh, bit, i, dp; + var data2 = new Uint8Array(raw_width + 1); + for (row = 0;row < height2; row++) { + for (var j2 = 0;j2 < raw_width; j2++) + data2[j2] = inp[off++]; + for (dp = 0, col = 0;col < raw_width - 30; dp += 16) { + max = 2047 & (val2 = bin.readUint(data2, dp)); + min = 2047 & val2 >>> 11; + imax = 15 & val2 >>> 22; + imin = 15 & val2 >>> 26; + for (sh = 0;sh < 4 && 128 << sh <= max - min; sh++) + ; + for (bit = 30, i = 0;i < 16; i++) + if (i == imax) + pix[i] = max; + else if (i == imin) + pix[i] = min; + else { + pix[i] = ((bin.readUshort(data2, dp + (bit >> 3)) >>> (bit & 7) & 127) << sh) + min; + if (pix[i] > 2047) + pix[i] = 2047; + bit += 7; + } + for (i = 0;i < 16; i++, col += 2) { + var clr = pix[i] << 1; + UTIF.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps); + } + col -= col & 1 ? 1 : 31; + } + } +}; +UTIF.decode._decodeNikon = function(img, imgs, data2, off, src_length, tgt, toff) { + var nikon_tree = [ + [ + 0, + 0, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 5, + 4, + 3, + 6, + 2, + 7, + 1, + 0, + 8, + 9, + 11, + 10, + 12 + ], + [ + 0, + 0, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 57, + 90, + 56, + 39, + 22, + 5, + 4, + 3, + 2, + 1, + 0, + 11, + 12, + 12 + ], + [ + 0, + 0, + 1, + 4, + 2, + 3, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 5, + 4, + 6, + 3, + 7, + 2, + 8, + 1, + 9, + 0, + 10, + 11, + 12 + ], + [ + 0, + 0, + 1, + 4, + 3, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 5, + 6, + 4, + 7, + 8, + 3, + 9, + 2, + 1, + 0, + 10, + 11, + 12, + 13, + 14 + ], + [ + 0, + 0, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 8, + 92, + 75, + 58, + 41, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + 0, + 13, + 14 + ], + [ + 0, + 0, + 1, + 4, + 2, + 2, + 3, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 6, + 8, + 5, + 9, + 4, + 10, + 3, + 11, + 12, + 2, + 0, + 1, + 13, + 14 + ] + ]; + var raw_width = img["t256"][0], height2 = img["t257"][0], tiff_bps = img["t258"][0]; + var tree = 0, split = 0; + var make_decoder = UTIF.decode._make_decoder; + var getbithuff = UTIF.decode._getbithuff; + var mn = imgs[0].exifIFD.makerNote, md = mn["t150"] ? mn["t150"] : mn["t140"], mdo = 0; + var ver0 = md[mdo++], ver1 = md[mdo++]; + if (ver0 == 73 || ver1 == 88) + mdo += 2110; + if (ver0 == 70) + tree = 2; + if (tiff_bps == 14) + tree += 3; + var vpred = [[0, 0], [0, 0]], bin = img.isLE ? UTIF._binLE : UTIF._binBE; + for (var i = 0;i < 2; i++) + for (var j2 = 0;j2 < 2; j2++) { + vpred[i][j2] = bin.readShort(md, mdo); + mdo += 2; + } + var max = 1 << tiff_bps & 32767, step = 0; + var csize = bin.readShort(md, mdo); + mdo += 2; + if (csize > 1) + step = Math.floor(max / (csize - 1)); + if (ver0 == 68 && ver1 == 32 && step > 0) + split = bin.readShort(md, 562); + var i; + var row, col; + var len, shl, diff; + var min_v = 0; + var hpred = [0, 0]; + var huff = make_decoder(nikon_tree[tree]); + var prm = [off, 0, 0, 0]; + for (min_v = row = 0;row < height2; row++) { + if (split && row == split) { + huff = make_decoder(nikon_tree[tree + 1]); + } + for (col = 0;col < raw_width; col++) { + i = getbithuff(data2, prm, huff[0], huff); + len = i & 15; + shl = i >>> 4; + diff = (getbithuff(data2, prm, len - shl, 0) << 1) + 1 << shl >>> 1; + if ((diff & 1 << len - 1) == 0) + diff -= (1 << len) - (shl == 0 ? 1 : 0); + if (col < 2) + hpred[col] = vpred[row & 1][col] += diff; + else + hpred[col & 1] += diff; + var clr = Math.min(Math.max(hpred[col & 1], 0), (1 << tiff_bps) - 1); + var bti = (row * raw_width + col) * tiff_bps; + UTIF.decode._putsF(tgt, bti, clr << 16 - tiff_bps); + } + } +}; +UTIF.decode._putsF = function(dt, pos, val2) { + val2 = val2 << 8 - (pos & 7); + var o = pos >>> 3; + dt[o] |= val2 >>> 16; + dt[o + 1] |= val2 >>> 8; + dt[o + 2] |= val2; +}; +UTIF.decode._getbithuff = function(data2, prm, nbits, huff) { + var zero_after_ff = 0; + var get_byte = UTIF.decode._get_byte; + var c; + var off = prm[0], bitbuf = prm[1], vbits = prm[2], reset = prm[3]; + if (nbits == 0 || vbits < 0) + return 0; + while (!reset && vbits < nbits && (c = data2[off++]) != -1 && !(reset = zero_after_ff && c == 255 && data2[off++])) { + bitbuf = (bitbuf << 8) + c; + vbits += 8; + } + c = bitbuf << 32 - vbits >>> 32 - nbits; + if (huff) { + vbits -= huff[c + 1] >>> 8; + c = huff[c + 1] & 255; + } else + vbits -= nbits; + if (vbits < 0) + throw "e"; + prm[0] = off; + prm[1] = bitbuf; + prm[2] = vbits; + prm[3] = reset; + return c; +}; +UTIF.decode._make_decoder = function(source) { + var max, len, h, i, j2; + var huff = []; + for (max = 16;max != 0 && !source[max]; max--) + ; + var si = 17; + huff[0] = max; + for (h = len = 1;len <= max; len++) + for (i = 0;i < source[len]; i++, ++si) + for (j2 = 0;j2 < 1 << max - len; j2++) + if (h <= 1 << max) + huff[h++] = len << 8 | source[si]; + return huff; +}; +UTIF.decode._decodeNewJPEG = function(img, data2, off, len, tgt, toff) { + len = Math.min(len, data2.length - off); + var tables = img["t347"], tlen = tables ? tables.length : 0, buff = new Uint8Array(tlen + len); + if (tables) { + var SOI = 216, EOI2 = 217, boff = 0; + for (var i = 0;i < tlen - 1; i++) { + if (tables[i] == 255 && tables[i + 1] == EOI2) + break; + buff[boff++] = tables[i]; + } + var byte1 = data2[off], byte2 = data2[off + 1]; + if (byte1 != 255 || byte2 != SOI) { + buff[boff++] = byte1; + buff[boff++] = byte2; + } + for (var i = 2;i < len; i++) + buff[boff++] = data2[off + i]; + } else + for (var i = 0;i < len; i++) + buff[i] = data2[off + i]; + if (img["t262"][0] == 32803 || img["t259"][0] == 7 && img["t262"][0] == 34892) { + var bps = img["t258"][0]; + var out = UTIF.LosslessJpegDecode(buff), olen = out.length; + if (false) { + } else if (bps == 16) { + if (img.isLE) + for (var i = 0;i < olen; i++) { + tgt[toff + (i << 1)] = out[i] & 255; + tgt[toff + (i << 1) + 1] = out[i] >>> 8; + } + else + for (var i = 0;i < olen; i++) { + tgt[toff + (i << 1)] = out[i] >>> 8; + tgt[toff + (i << 1) + 1] = out[i] & 255; + } + } else if (bps == 14 || bps == 12 || bps == 10) { + var rst = 16 - bps; + for (var i = 0;i < olen; i++) + UTIF.decode._putsF(tgt, i * bps, out[i] << rst); + } else if (bps == 8) { + for (var i = 0;i < olen; i++) + tgt[toff + i] = out[i]; + } else + throw new Error("unsupported bit depth " + bps); + } else { + var parser = new UTIF.JpegDecoder; + parser.parse(buff); + var decoded = parser.getData({ width: parser.width, height: parser.height, forceRGB: true, isSourcePDF: false }); + for (var i = 0;i < decoded.length; i++) + tgt[toff + i] = decoded[i]; + } + if (img["t262"][0] == 6) + img["t262"][0] = 2; +}; +UTIF.decode._decodeOldJPEGInit = function(img, data2, off, len) { + var SOI = 216, EOI2 = 217, DQT = 219, DHT = 196, DRI = 221, SOF0 = 192, SOS2 = 218; + var joff = 0, soff = 0, tables, sosMarker2, isTiled = false, i, j2, k2; + var jpgIchgFmt = img["t513"], jifoff = jpgIchgFmt ? jpgIchgFmt[0] : 0; + var jpgIchgFmtLen = img["t514"], jiflen = jpgIchgFmtLen ? jpgIchgFmtLen[0] : 0; + var soffTag = img["t324"] || img["t273"] || jpgIchgFmt; + var ycbcrss = img["t530"], ssx = 0, ssy = 0; + var spp = img["t277"] ? img["t277"][0] : 1; + var jpgresint = img["t515"]; + if (soffTag) { + soff = soffTag[0]; + isTiled = soffTag.length > 1; + } + if (!isTiled) { + if (data2[off] == 255 && data2[off + 1] == SOI) + return { jpegOffset: off }; + if (jpgIchgFmt != null) { + if (data2[off + jifoff] == 255 && data2[off + jifoff + 1] == SOI) + joff = off + jifoff; + else + log("JPEGInterchangeFormat does not point to SOI"); + if (jpgIchgFmtLen == null) + log("JPEGInterchangeFormatLength field is missing"); + else if (jifoff >= soff || jifoff + jiflen <= soff) + log("JPEGInterchangeFormatLength field value is invalid"); + if (joff != null) + return { jpegOffset: joff }; + } + } + if (ycbcrss != null) { + ssx = ycbcrss[0]; + ssy = ycbcrss[1]; + } + if (jpgIchgFmt != null) { + if (jpgIchgFmtLen != null) + if (jiflen >= 2 && jifoff + jiflen <= soff) { + if (data2[off + jifoff + jiflen - 2] == 255 && data2[off + jifoff + jiflen - 1] == SOI) + tables = new Uint8Array(jiflen - 2); + else + tables = new Uint8Array(jiflen); + for (i = 0;i < tables.length; i++) + tables[i] = data2[off + jifoff + i]; + log("Incorrect JPEG interchange format: using JPEGInterchangeFormat offset to derive tables"); + } else + log("JPEGInterchangeFormat+JPEGInterchangeFormatLength > offset to first strip or tile"); + } + if (tables == null) { + var ooff = 0, out = []; + out[ooff++] = 255; + out[ooff++] = SOI; + var qtables = img["t519"]; + if (qtables == null) + throw new Error("JPEGQTables tag is missing"); + for (i = 0;i < qtables.length; i++) { + out[ooff++] = 255; + out[ooff++] = DQT; + out[ooff++] = 0; + out[ooff++] = 67; + out[ooff++] = i; + for (j2 = 0;j2 < 64; j2++) + out[ooff++] = data2[off + qtables[i] + j2]; + } + for (k2 = 0;k2 < 2; k2++) { + var htables = img[k2 == 0 ? "t520" : "t521"]; + if (htables == null) + throw new Error((k2 == 0 ? "JPEGDCTables" : "JPEGACTables") + " tag is missing"); + for (i = 0;i < htables.length; i++) { + out[ooff++] = 255; + out[ooff++] = DHT; + var nc = 19; + for (j2 = 0;j2 < 16; j2++) + nc += data2[off + htables[i] + j2]; + out[ooff++] = nc >>> 8; + out[ooff++] = nc & 255; + out[ooff++] = i | k2 << 4; + for (j2 = 0;j2 < 16; j2++) + out[ooff++] = data2[off + htables[i] + j2]; + for (j2 = 0;j2 < nc; j2++) + out[ooff++] = data2[off + htables[i] + 16 + j2]; + } + } + out[ooff++] = 255; + out[ooff++] = SOF0; + out[ooff++] = 0; + out[ooff++] = 8 + 3 * spp; + out[ooff++] = 8; + out[ooff++] = img.height >>> 8 & 255; + out[ooff++] = img.height & 255; + out[ooff++] = img.width >>> 8 & 255; + out[ooff++] = img.width & 255; + out[ooff++] = spp; + if (spp == 1) { + out[ooff++] = 1; + out[ooff++] = 17; + out[ooff++] = 0; + } else + for (i = 0;i < 3; i++) { + out[ooff++] = i + 1; + out[ooff++] = i != 0 ? 17 : (ssx & 15) << 4 | ssy & 15; + out[ooff++] = i; + } + if (jpgresint != null && jpgresint[0] != 0) { + out[ooff++] = 255; + out[ooff++] = DRI; + out[ooff++] = 0; + out[ooff++] = 4; + out[ooff++] = jpgresint[0] >>> 8 & 255; + out[ooff++] = jpgresint[0] & 255; + } + tables = new Uint8Array(out); + } + var sofpos = -1; + i = 0; + while (i < tables.length - 1) { + if (tables[i] == 255 && tables[i + 1] == SOF0) { + sofpos = i; + break; + } + i++; + } + if (sofpos == -1) { + var tmptab = new Uint8Array(tables.length + 10 + 3 * spp); + tmptab.set(tables); + var tmpoff = tables.length; + sofpos = tables.length; + tables = tmptab; + tables[tmpoff++] = 255; + tables[tmpoff++] = SOF0; + tables[tmpoff++] = 0; + tables[tmpoff++] = 8 + 3 * spp; + tables[tmpoff++] = 8; + tables[tmpoff++] = img.height >>> 8 & 255; + tables[tmpoff++] = img.height & 255; + tables[tmpoff++] = img.width >>> 8 & 255; + tables[tmpoff++] = img.width & 255; + tables[tmpoff++] = spp; + if (spp == 1) { + tables[tmpoff++] = 1; + tables[tmpoff++] = 17; + tables[tmpoff++] = 0; + } else + for (i = 0;i < 3; i++) { + tables[tmpoff++] = i + 1; + tables[tmpoff++] = i != 0 ? 17 : (ssx & 15) << 4 | ssy & 15; + tables[tmpoff++] = i; + } + } + if (data2[soff] == 255 && data2[soff + 1] == SOS2) { + var soslen = data2[soff + 2] << 8 | data2[soff + 3]; + sosMarker2 = new Uint8Array(soslen + 2); + sosMarker2[0] = data2[soff]; + sosMarker2[1] = data2[soff + 1]; + sosMarker2[2] = data2[soff + 2]; + sosMarker2[3] = data2[soff + 3]; + for (i = 0;i < soslen - 2; i++) + sosMarker2[i + 4] = data2[soff + i + 4]; + } else { + sosMarker2 = new Uint8Array(2 + 6 + 2 * spp); + var sosoff = 0; + sosMarker2[sosoff++] = 255; + sosMarker2[sosoff++] = SOS2; + sosMarker2[sosoff++] = 0; + sosMarker2[sosoff++] = 6 + 2 * spp; + sosMarker2[sosoff++] = spp; + if (spp == 1) { + sosMarker2[sosoff++] = 1; + sosMarker2[sosoff++] = 0; + } else + for (i = 0;i < 3; i++) { + sosMarker2[sosoff++] = i + 1; + sosMarker2[sosoff++] = i << 4 | i; + } + sosMarker2[sosoff++] = 0; + sosMarker2[sosoff++] = 63; + sosMarker2[sosoff++] = 0; + } + return { jpegOffset: off, tables, sosMarker: sosMarker2, sofPosition: sofpos }; +}; +UTIF.decode._decodeOldJPEG = function(img, data2, off, len, tgt, toff) { + var i, dlen, tlen, buff, buffoff; + var jpegData = UTIF.decode._decodeOldJPEGInit(img, data2, off, len); + if (jpegData.jpegOffset != null) { + dlen = off + len - jpegData.jpegOffset; + buff = new Uint8Array(dlen); + for (i = 0;i < dlen; i++) + buff[i] = data2[jpegData.jpegOffset + i]; + } else { + tlen = jpegData.tables.length; + buff = new Uint8Array(tlen + jpegData.sosMarker.length + len + 2); + buff.set(jpegData.tables); + buffoff = tlen; + buff[jpegData.sofPosition + 5] = img.height >>> 8 & 255; + buff[jpegData.sofPosition + 6] = img.height & 255; + buff[jpegData.sofPosition + 7] = img.width >>> 8 & 255; + buff[jpegData.sofPosition + 8] = img.width & 255; + if (data2[off] != 255 || data2[off + 1] != SOS) { + buff.set(jpegData.sosMarker, buffoff); + buffoff += sosMarker.length; + } + for (i = 0;i < len; i++) + buff[buffoff++] = data2[off + i]; + buff[buffoff++] = 255; + buff[buffoff++] = EOI; + } + var parser = new UTIF.JpegDecoder; + parser.parse(buff); + var decoded = parser.getData({ width: parser.width, height: parser.height, forceRGB: true, isSourcePDF: false }); + for (var i = 0;i < decoded.length; i++) + tgt[toff + i] = decoded[i]; + if (img["t262"] && img["t262"][0] == 6) + img["t262"][0] = 2; +}; +UTIF.decode._decodePackBits = function(data2, off, len, tgt, toff) { + var sa = new Int8Array(data2.buffer), ta = new Int8Array(tgt.buffer), lim = off + len; + while (off < lim) { + var n2 = sa[off]; + off++; + if (n2 >= 0 && n2 < 128) + for (var i = 0;i < n2 + 1; i++) { + ta[toff] = sa[off]; + toff++; + off++; + } + if (n2 >= -127 && n2 < 0) { + for (var i = 0;i < -n2 + 1; i++) { + ta[toff] = sa[off]; + toff++; + } + off++; + } + } + return toff; +}; +UTIF.decode._decodeThunder = function(data2, off, len, tgt, toff) { + var d2 = [0, 1, 0, -1], d3 = [0, 1, 2, 3, 0, -3, -2, -1]; + var lim = off + len, qoff = toff * 2, px2 = 0; + while (off < lim) { + var b = data2[off], msk = b >>> 6, n2 = b & 63; + off++; + if (msk == 3) { + px2 = n2 & 15; + tgt[qoff >>> 1] |= px2 << 4 * (1 - qoff & 1); + qoff++; + } + if (msk == 0) + for (var i = 0;i < n2; i++) { + tgt[qoff >>> 1] |= px2 << 4 * (1 - qoff & 1); + qoff++; + } + if (msk == 2) + for (var i = 0;i < 2; i++) { + var d = n2 >>> 3 * (1 - i) & 7; + if (d != 4) { + px2 += d3[d]; + tgt[qoff >>> 1] |= px2 << 4 * (1 - qoff & 1); + qoff++; + } + } + if (msk == 1) + for (var i = 0;i < 3; i++) { + var d = n2 >>> 2 * (2 - i) & 3; + if (d != 2) { + px2 += d2[d]; + tgt[qoff >>> 1] |= px2 << 4 * (1 - qoff & 1); + qoff++; + } + } + } +}; +UTIF.decode._dmap = { "1": 0, "011": 1, "000011": 2, "0000011": 3, "010": -1, "000010": -2, "0000010": -3 }; +UTIF.decode._lens = function() { + var addKeys = function(lens, arr, i0, inc) { + for (var i = 0;i < arr.length; i++) + lens[arr[i]] = i0 + i * inc; + }; + var termW = "00110101,000111,0111,1000,1011,1100,1110,1111,10011,10100,00111,01000,001000,000011,110100,110101," + "101010,101011,0100111,0001100,0001000,0010111,0000011,0000100,0101000,0101011,0010011,0100100,0011000,00000010,00000011,00011010," + "00011011,00010010,00010011,00010100,00010101,00010110,00010111,00101000,00101001,00101010,00101011,00101100,00101101,00000100,00000101,00001010," + "00001011,01010010,01010011,01010100,01010101,00100100,00100101,01011000,01011001,01011010,01011011,01001010,01001011,00110010,00110011,00110100"; + var termB = "0000110111,010,11,10,011,0011,0010,00011,000101,000100,0000100,0000101,0000111,00000100,00000111,000011000," + "0000010111,0000011000,0000001000,00001100111,00001101000,00001101100,00000110111,00000101000,00000010111,00000011000,000011001010,000011001011,000011001100,000011001101,000001101000,000001101001," + "000001101010,000001101011,000011010010,000011010011,000011010100,000011010101,000011010110,000011010111,000001101100,000001101101,000011011010,000011011011,000001010100,000001010101,000001010110,000001010111," + "000001100100,000001100101,000001010010,000001010011,000000100100,000000110111,000000111000,000000100111,000000101000,000001011000,000001011001,000000101011,000000101100,000001011010,000001100110,000001100111"; + var makeW = "11011,10010,010111,0110111,00110110,00110111,01100100,01100101,01101000,01100111,011001100,011001101,011010010,011010011,011010100,011010101,011010110," + "011010111,011011000,011011001,011011010,011011011,010011000,010011001,010011010,011000,010011011"; + var makeB = "0000001111,000011001000,000011001001,000001011011,000000110011,000000110100,000000110101,0000001101100,0000001101101,0000001001010,0000001001011,0000001001100," + "0000001001101,0000001110010,0000001110011,0000001110100,0000001110101,0000001110110,0000001110111,0000001010010,0000001010011,0000001010100,0000001010101,0000001011010," + "0000001011011,0000001100100,0000001100101"; + var makeA = "00000001000,00000001100,00000001101,000000010010,000000010011,000000010100,000000010101,000000010110,000000010111,000000011100,000000011101,000000011110,000000011111"; + termW = termW.split(","); + termB = termB.split(","); + makeW = makeW.split(","); + makeB = makeB.split(","); + makeA = makeA.split(","); + var lensW = {}, lensB = {}; + addKeys(lensW, termW, 0, 1); + addKeys(lensW, makeW, 64, 64); + addKeys(lensW, makeA, 1792, 64); + addKeys(lensB, termB, 0, 1); + addKeys(lensB, makeB, 64, 64); + addKeys(lensB, makeA, 1792, 64); + return [lensW, lensB]; +}(); +UTIF.decode._decodeG4 = function(data2, off, slen, tgt, toff, w, fo) { + var U = UTIF.decode, boff = off << 3, len = 0, wrd = ""; + var line = [], pline = []; + for (var i = 0;i < w; i++) + pline.push(0); + pline = U._makeDiff(pline); + var a0 = 0, a1 = 0, a2 = 0, b1 = 0, b2 = 0, clr = 0; + var y = 0, mode = "", toRead = 0; + var bipl = Math.ceil(w / 8) * 8; + while (boff >>> 3 < off + slen) { + b1 = U._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b2 = U._findDiff(pline, b1, clr); + var bit = 0; + if (fo == 1) + bit = data2[boff >>> 3] >>> 7 - (boff & 7) & 1; + if (fo == 2) + bit = data2[boff >>> 3] >>> (boff & 7) & 1; + boff++; + wrd += bit; + if (mode == "H") { + if (U._lens[clr][wrd] != null) { + var dl2 = U._lens[clr][wrd]; + wrd = ""; + len += dl2; + if (dl2 < 64) { + U._addNtimes(line, len, clr); + a0 += len; + clr = 1 - clr; + len = 0; + toRead--; + if (toRead == 0) + mode = ""; + } + } + } else { + if (wrd == "0001") { + wrd = ""; + U._addNtimes(line, b2 - a0, clr); + a0 = b2; + } + if (wrd == "001") { + wrd = ""; + mode = "H"; + toRead = 2; + } + if (U._dmap[wrd] != null) { + a1 = b1 + U._dmap[wrd]; + U._addNtimes(line, a1 - a0, clr); + a0 = a1; + wrd = ""; + clr = 1 - clr; + } + } + if (line.length == w && mode == "") { + U._writeBits(line, tgt, toff * 8 + y * bipl); + clr = 0; + y++; + a0 = 0; + pline = U._makeDiff(line); + line = []; + } + } +}; +UTIF.decode._findDiff = function(line, x2, clr) { + for (var i = 0;i < line.length; i += 2) + if (line[i] >= x2 && line[i + 1] == clr) + return line[i]; +}; +UTIF.decode._makeDiff = function(line) { + var out = []; + if (line[0] == 1) + out.push(0, 1); + for (var i = 1;i < line.length; i++) + if (line[i - 1] != line[i]) + out.push(i, line[i]); + out.push(line.length, 0, line.length, 1); + return out; +}; +UTIF.decode._decodeG2 = function(data2, off, slen, tgt, toff, w, fo) { + var U = UTIF.decode, boff = off << 3, len = 0, wrd = ""; + var line = []; + var clr = 0; + var y = 0; + var bipl = Math.ceil(w / 8) * 8; + while (boff >>> 3 < off + slen) { + var bit = 0; + if (fo == 1) + bit = data2[boff >>> 3] >>> 7 - (boff & 7) & 1; + if (fo == 2) + bit = data2[boff >>> 3] >>> (boff & 7) & 1; + boff++; + wrd += bit; + len = U._lens[clr][wrd]; + if (len != null) { + U._addNtimes(line, len, clr); + wrd = ""; + if (len < 64) + clr = 1 - clr; + if (line.length == w) { + U._writeBits(line, tgt, toff * 8 + y * bipl); + line = []; + y++; + clr = 0; + if ((boff & 7) != 0) + boff += 8 - (boff & 7); + if (len >= 64) + boff += 8; + } + } + } +}; +UTIF.decode._decodeG3 = function(data2, off, slen, tgt, toff, w, fo, twoDim) { + var U = UTIF.decode, boff = off << 3, len = 0, wrd = ""; + var line = [], pline = []; + for (var i = 0;i < w; i++) + line.push(0); + var a0 = 0, a1 = 0, a2 = 0, b1 = 0, b2 = 0, clr = 0; + var y = -1, mode = "", toRead = 0, is1D = true; + var bipl = Math.ceil(w / 8) * 8; + while (boff >>> 3 < off + slen) { + b1 = U._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b2 = U._findDiff(pline, b1, clr); + var bit = 0; + if (fo == 1) + bit = data2[boff >>> 3] >>> 7 - (boff & 7) & 1; + if (fo == 2) + bit = data2[boff >>> 3] >>> (boff & 7) & 1; + boff++; + wrd += bit; + if (is1D) { + if (U._lens[clr][wrd] != null) { + var dl2 = U._lens[clr][wrd]; + wrd = ""; + len += dl2; + if (dl2 < 64) { + U._addNtimes(line, len, clr); + clr = 1 - clr; + len = 0; + } + } + } else { + if (mode == "H") { + if (U._lens[clr][wrd] != null) { + var dl2 = U._lens[clr][wrd]; + wrd = ""; + len += dl2; + if (dl2 < 64) { + U._addNtimes(line, len, clr); + a0 += len; + clr = 1 - clr; + len = 0; + toRead--; + if (toRead == 0) + mode = ""; + } + } + } else { + if (wrd == "0001") { + wrd = ""; + U._addNtimes(line, b2 - a0, clr); + a0 = b2; + } + if (wrd == "001") { + wrd = ""; + mode = "H"; + toRead = 2; + } + if (U._dmap[wrd] != null) { + a1 = b1 + U._dmap[wrd]; + U._addNtimes(line, a1 - a0, clr); + a0 = a1; + wrd = ""; + clr = 1 - clr; + } + } + } + if (wrd.endsWith("000000000001")) { + if (y >= 0) + U._writeBits(line, tgt, toff * 8 + y * bipl); + if (twoDim) { + if (fo == 1) + is1D = (data2[boff >>> 3] >>> 7 - (boff & 7) & 1) == 1; + if (fo == 2) + is1D = (data2[boff >>> 3] >>> (boff & 7) & 1) == 1; + boff++; + } + wrd = ""; + clr = 0; + y++; + a0 = 0; + pline = U._makeDiff(line); + line = []; + } + } + if (line.length == w) + U._writeBits(line, tgt, toff * 8 + y * bipl); +}; +UTIF.decode._addNtimes = function(arr, n2, val2) { + for (var i = 0;i < n2; i++) + arr.push(val2); +}; +UTIF.decode._writeBits = function(bits, tgt, boff) { + for (var i = 0;i < bits.length; i++) + tgt[boff + i >>> 3] |= bits[i] << 7 - (boff + i & 7); +}; +UTIF.decode._decodeLZW = UTIF.decode._decodeLZW = function() { + var e, U, Z2, u2, K = 0, V2 = 0, g3 = 0, N = 0, O = function() { + var S = e >>> 3, A2 = U[S] << 16 | U[S + 1] << 8 | U[S + 2], j2 = A2 >>> 24 - (e & 7) - V2 & (1 << V2) - 1; + e += V2; + return j2; + }, h = new Uint32Array(4096 * 4), w = 0, m = function(S) { + if (S == w) + return; + w = S; + g3 = 1 << S; + N = g3 + 1; + for (var A2 = 0;A2 < N + 1; A2++) { + h[4 * A2] = h[4 * A2 + 3] = A2; + h[4 * A2 + 1] = 65535; + h[4 * A2 + 2] = 1; + } + }, i = function(S) { + V2 = S + 1; + K = N + 1; + }, D = function(S) { + var A2 = S << 2, j2 = h[A2 + 2], a = u2 + j2 - 1; + while (A2 != 65535) { + Z2[a--] = h[A2]; + A2 = h[A2 + 1]; + } + u2 += j2; + }, L = function(S, A2) { + var j2 = K << 2, a = S << 2; + h[j2] = h[(A2 << 2) + 3]; + h[j2 + 1] = a; + h[j2 + 2] = h[a + 2] + 1; + h[j2 + 3] = h[a + 3]; + K++; + if (K + 1 == 1 << V2 && V2 != 12) + V2++; + }, T2 = function(S, A2, j2, a, n2, q2) { + e = A2 << 3; + U = S; + Z2 = a; + u2 = n2; + var B2 = A2 + j2 << 3, _2 = 0, t2 = 0; + m(q2); + i(q2); + while (e < B2 && (_2 = O()) != N) { + if (_2 == g3) { + i(q2); + _2 = O(); + if (_2 == N) + break; + D(_2); + } else { + if (_2 < K) { + D(_2); + L(t2, _2); + } else { + L(t2, t2); + D(K - 1); + } + } + t2 = _2; + } + return u2; + }; + return T2; +}(); +UTIF.tags = {}; +UTIF._types = function() { + var main = new Array(250); + main.fill(0); + main = main.concat([0, 0, 0, 0, 4, 3, 3, 3, 3, 3, 0, 0, 3, 0, 0, 0, 3, 0, 0, 2, 2, 2, 2, 4, 3, 0, 0, 3, 4, 4, 3, 3, 5, 5, 3, 2, 5, 5, 0, 0, 0, 0, 4, 4, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 5, 5, 3, 0, 3, 3, 4, 4, 4, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + var rest = { 33432: 2, 33434: 5, 33437: 5, 34665: 4, 34850: 3, 34853: 4, 34855: 3, 34864: 3, 34866: 4, 36864: 7, 36867: 2, 36868: 2, 37121: 7, 37377: 10, 37378: 5, 37380: 10, 37381: 5, 37383: 3, 37384: 3, 37385: 3, 37386: 5, 37510: 7, 37520: 2, 37521: 2, 37522: 2, 40960: 7, 40961: 3, 40962: 4, 40963: 4, 40965: 4, 41486: 5, 41487: 5, 41488: 3, 41985: 3, 41986: 3, 41987: 3, 41988: 5, 41989: 3, 41990: 3, 41993: 3, 41994: 3, 41995: 7, 41996: 3, 42032: 2, 42033: 2, 42034: 5, 42036: 2, 42037: 2, 59932: 7 }; + return { + basic: { + main, + rest + }, + gps: { + main: [1, 2, 5, 2, 5, 1, 5, 5, 0, 9], + rest: { 18: 2, 29: 2 } + } + }; +}(); +UTIF._readIFD = function(bin, data2, offset, ifds, depth, prm) { + var cnt = bin.readUshort(data2, offset); + offset += 2; + var ifd = {}; + if (prm.debug) + log(" ".repeat(depth), ifds.length - 1, ">>>----------------"); + for (var i = 0;i < cnt; i++) { + var tag = bin.readUshort(data2, offset); + offset += 2; + var type = bin.readUshort(data2, offset); + offset += 2; + var num = bin.readUint(data2, offset); + offset += 4; + var voff = bin.readUint(data2, offset); + offset += 4; + var arr = []; + if (type == 1 || type == 7) { + var no = num < 5 ? offset - 4 : voff; + if (no + num > data2.buffer.byteLength) + num = data2.buffer.byteLength - no; + arr = new Uint8Array(data2.buffer, no, num); + } + if (type == 2) { + var o0 = num < 5 ? offset - 4 : voff, c = data2[o0], len = Math.max(0, Math.min(num - 1, data2.length - o0)); + if (c < 128 || len == 0) + arr.push(bin.readASCII(data2, o0, len)); + else + arr = new Uint8Array(data2.buffer, o0, len); + } + if (type == 3) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readUshort(data2, (num < 3 ? offset - 4 : voff) + 2 * j2)); + } + if (type == 4 || type == 13) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readUint(data2, (num < 2 ? offset - 4 : voff) + 4 * j2)); + } + if (type == 5 || type == 10) { + var ri = type == 5 ? bin.readUint : bin.readInt; + for (var j2 = 0;j2 < num; j2++) + arr.push([ri(data2, voff + j2 * 8), ri(data2, voff + j2 * 8 + 4)]); + } + if (type == 8) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readShort(data2, (num < 3 ? offset - 4 : voff) + 2 * j2)); + } + if (type == 9) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readInt(data2, (num < 2 ? offset - 4 : voff) + 4 * j2)); + } + if (type == 11) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readFloat(data2, voff + j2 * 4)); + } + if (type == 12) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readDouble(data2, voff + j2 * 8)); + } + if (num != 0 && arr.length == 0) { + log(tag, "unknown TIFF tag type: ", type, "num:", num); + if (i == 0) + return; + continue; + } + if (prm.debug) + log(" ".repeat(depth), tag, type, UTIF.tags[tag], arr); + ifd["t" + tag] = arr; + if (tag == 330 && ifd["t272"] && ifd["t272"][0] == "DSLR-A100") { + } else if (tag == 330 || tag == 34665 || tag == 34853 || tag == 50740 && bin.readUshort(data2, bin.readUint(arr, 0)) < 300 || tag == 61440) { + var oarr = tag == 50740 ? [bin.readUint(arr, 0)] : arr; + var subfd = []; + for (var j2 = 0;j2 < oarr.length; j2++) + UTIF._readIFD(bin, data2, oarr[j2], subfd, depth + 1, prm); + if (tag == 330) + ifd.subIFD = subfd; + if (tag == 34665) + ifd.exifIFD = subfd[0]; + if (tag == 34853) + ifd.gpsiIFD = subfd[0]; + if (tag == 50740) + ifd.dngPrvt = subfd[0]; + if (tag == 61440) + ifd.fujiIFD = subfd[0]; + } + if (tag == 37500 && prm.parseMN) { + var mn = arr; + if (bin.readASCII(mn, 0, 5) == "Nikon") + ifd.makerNote = UTIF["decode"](mn.slice(10).buffer)[0]; + else if (bin.readASCII(mn, 0, 5) == "OLYMP" || bin.readASCII(mn, 0, 9) == "OM SYSTEM") { + var inds = [8208, 8224, 8240, 8256, 8272]; + var subsub = []; + UTIF._readIFD(bin, mn, mn[1] == 77 ? 16 : mn[5] == 85 ? 12 : 8, subsub, depth + 1, prm); + var obj = ifd.makerNote = subsub.pop(); + for (var j2 = 0;j2 < inds.length; j2++) { + var k2 = "t" + inds[j2]; + if (obj[k2] == null) + continue; + UTIF._readIFD(bin, mn, obj[k2][0], subsub, depth + 1, prm); + obj[k2] = subsub.pop(); + } + if (obj["t12288"]) { + UTIF._readIFD(bin, obj["t12288"], 0, subsub, depth + 1, prm); + obj["t12288"] = subsub.pop(); + } + } else if (bin.readUshort(data2, voff) < 300 && bin.readUshort(data2, voff + 4) <= 12) { + var subsub = []; + UTIF._readIFD(bin, data2, voff, subsub, depth + 1, prm); + ifd.makerNote = subsub[0]; + } + } + } + ifds.push(ifd); + if (prm.debug) + log(" ".repeat(depth), "<<<---------------"); + return offset; +}; +UTIF._writeIFD = function(bin, types, data2, offset, ifd) { + var keys2 = Object.keys(ifd), knum = keys2.length; + if (ifd["exifIFD"]) + knum--; + if (ifd["gpsiIFD"]) + knum--; + bin.writeUshort(data2, offset, knum); + offset += 2; + var eoff = offset + knum * 12 + 4; + for (var ki = 0;ki < keys2.length; ki++) { + var key2 = keys2[ki]; + if (key2 == "t34665" || key2 == "t34853") + continue; + if (key2 == "exifIFD") + key2 = "t34665"; + if (key2 == "gpsiIFD") + key2 = "t34853"; + var tag = parseInt(key2.slice(1)), type = types.main[tag]; + if (type == null) + type = types.rest[tag]; + if (type == null || type == 0) + throw new Error("unknown type of tag: " + tag); + var val2 = ifd[key2]; + if (tag == 34665) { + var outp = UTIF._writeIFD(bin, types, data2, eoff, ifd["exifIFD"]); + val2 = [eoff]; + eoff = outp[1]; + } + if (tag == 34853) { + var outp = UTIF._writeIFD(bin, UTIF._types.gps, data2, eoff, ifd["gpsiIFD"]); + val2 = [eoff]; + eoff = outp[1]; + } + if (type == 2) + val2 = val2[0] + "\x00"; + var num = val2.length; + bin.writeUshort(data2, offset, tag); + offset += 2; + bin.writeUshort(data2, offset, type); + offset += 2; + bin.writeUint(data2, offset, num); + offset += 4; + var dlen = [-1, 1, 1, 2, 4, 8, 0, 1, 0, 4, 8, 0, 8][type] * num; + var toff = offset; + if (dlen > 4) { + bin.writeUint(data2, offset, eoff); + toff = eoff; + } + if (type == 1 || type == 7) { + for (var i = 0;i < num; i++) + data2[toff + i] = val2[i]; + } else if (type == 2) { + bin.writeASCII(data2, toff, val2); + } else if (type == 3) { + for (var i = 0;i < num; i++) + bin.writeUshort(data2, toff + 2 * i, val2[i]); + } else if (type == 4) { + for (var i = 0;i < num; i++) + bin.writeUint(data2, toff + 4 * i, val2[i]); + } else if (type == 5 || type == 10) { + var wr = type == 5 ? bin.writeUint : bin.writeInt; + for (var i = 0;i < num; i++) { + var v = val2[i], nu = v[0], de = v[1]; + if (nu == null) + throw "e"; + wr(data2, toff + 8 * i, nu); + wr(data2, toff + 8 * i + 4, de); + } + } else if (type == 9) { + for (var i = 0;i < num; i++) + bin.writeInt(data2, toff + 4 * i, val2[i]); + } else if (type == 12) { + for (var i = 0;i < num; i++) + bin.writeDouble(data2, toff + 8 * i, val2[i]); + } else + throw type; + if (dlen > 4) { + dlen += dlen & 1; + eoff += dlen; + } + offset += 4; + } + return [offset, eoff]; +}; +UTIF.toRGBA8 = function(out, scl) { + function gamma(x3) { + return x3 < 0.0031308 ? 12.92 * x3 : 1.055 * Math.pow(x3, 1 / 2.4) - 0.055; + } + var { width: w, height: h } = out, area2 = w * h, qarea = area2 * 4, data2 = out.data; + var img = new Uint8Array(area2 * 4); + var intp = out["t262"] ? out["t262"][0] : 2, bps = out["t258"] ? Math.min(32, out["t258"][0]) : 1; + if (out["t262"] == null && bps == 1) + intp = 0; + var smpls = out["t277"] ? out["t277"][0] : out["t258"] ? out["t258"].length : [1, 1, 3, 1, 1, 4, 3][intp]; + var sfmt = out["t339"] ? out["t339"][0] : null; + if (intp == 1 && bps == 32 && sfmt != 3) + throw "e"; + var bpl = Math.ceil(smpls * bps * w / 8); + if (false) { + } else if (intp == 0) { + scl = 1 / 256; + for (var y = 0;y < h; y++) { + var off = y * bpl, io = y * w; + if (bps == 1) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + (i >> 3)] >> 7 - (i & 7) & 1; + img[qi] = img[qi + 1] = img[qi + 2] = (1 - px2) * 255; + img[qi + 3] = 255; + } + if (bps == 4) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + (i >> 1)] >> 4 - 4 * (i & 1) & 15; + img[qi] = img[qi + 1] = img[qi + 2] = (15 - px2) * 17; + img[qi + 3] = 255; + } + if (bps == 8) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + i]; + img[qi] = img[qi + 1] = img[qi + 2] = 255 - px2; + img[qi + 3] = 255; + } + if (bps == 16) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, o = off + 2 * i, px2 = data2[o + 1] << 8 | data2[o]; + img[qi] = img[qi + 1] = img[qi + 2] = Math.min(255, 255 - ~~(px2 * scl)); + img[qi + 3] = 255; + } + } + } else if (intp == 1) { + if (scl == null) + scl = 1 / 256; + var f32 = (data2.length & 3) == 0 ? new Float32Array(data2.buffer) : null; + for (var y = 0;y < h; y++) { + var off = y * bpl, io = y * w; + if (bps == 1) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + (i >> 3)] >> 7 - (i & 7) & 1; + img[qi] = img[qi + 1] = img[qi + 2] = px2 * 255; + img[qi + 3] = 255; + } + if (bps == 2) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + (i >> 2)] >> 6 - 2 * (i & 3) & 3; + img[qi] = img[qi + 1] = img[qi + 2] = px2 * 85; + img[qi + 3] = 255; + } + if (bps == 8) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + i * smpls]; + img[qi] = img[qi + 1] = img[qi + 2] = px2; + img[qi + 3] = 255; + } + if (bps == 16) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, o = off + 2 * i, px2 = data2[o + 1] << 8 | data2[o]; + img[qi] = img[qi + 1] = img[qi + 2] = Math.min(255, ~~(px2 * scl)); + img[qi + 3] = 255; + } + if (bps == 32) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, o = (off >>> 2) + i, px2 = f32[o]; + img[qi] = img[qi + 1] = img[qi + 2] = ~~(0.5 + 255 * px2); + img[qi + 3] = 255; + } + } + } else if (intp == 2) { + if (bps == 8) { + if (smpls == 1) + for (var i = 0;i < area2; i++) { + img[4 * i] = img[4 * i + 1] = img[4 * i + 2] = data2[i]; + img[4 * i + 3] = 255; + } + if (smpls == 3) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 3; + img[qi] = data2[ti]; + img[qi + 1] = data2[ti + 1]; + img[qi + 2] = data2[ti + 2]; + img[qi + 3] = 255; + } + if (smpls >= 4) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * smpls; + img[qi] = data2[ti]; + img[qi + 1] = data2[ti + 1]; + img[qi + 2] = data2[ti + 2]; + img[qi + 3] = data2[ti + 3]; + } + } else if (bps == 16) { + if (smpls == 4) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 8 + 1; + img[qi] = data2[ti]; + img[qi + 1] = data2[ti + 2]; + img[qi + 2] = data2[ti + 4]; + img[qi + 3] = data2[ti + 6]; + } + if (smpls == 3) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 6 + 1; + img[qi] = data2[ti]; + img[qi + 1] = data2[ti + 2]; + img[qi + 2] = data2[ti + 4]; + img[qi + 3] = 255; + } + } else if (bps == 32) { + var ndt = new Float32Array(data2.buffer); + var min = 0; + for (var i = 0;i < ndt.length; i++) + min = Math.min(min, ndt[i]); + if (min < 0) + for (var i = 0;i < data2.length; i += 4) { + var t2 = data2[i]; + data2[i] = data2[i + 3]; + data2[i + 3] = t2; + t2 = data2[i + 1]; + data2[i + 1] = data2[i + 2]; + data2[i + 2] = t2; + } + var pmap = []; + for (var i = 0;i < 65536; i++) + pmap.push(gamma(i / 65535)); + for (var i = 0;i < ndt.length; i++) { + var cv = Math.max(0, Math.min(1, ndt[i])); + ndt[i] = pmap[~~(0.5 + cv * 65535)]; + } + if (smpls == 3) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 3; + img[qi] = ~~(0.5 + ndt[ti] * 255); + img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255); + img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255); + img[qi + 3] = 255; + } + else if (smpls == 4) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 4; + img[qi] = ~~(0.5 + ndt[ti] * 255); + img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255); + img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255); + img[qi + 3] = ~~(0.5 + ndt[ti + 3] * 255); + } + else + throw smpls; + } else + throw bps; + } else if (intp == 3) { + var map2 = out["t320"]; + var cn = 1 << bps; + var nexta = bps == 8 && smpls > 1 && out["t338"] && out["t338"][0] != 0; + for (var y = 0;y < h; y++) + for (var x2 = 0;x2 < w; x2++) { + var i = y * w + x2; + var qi = i << 2, mi = 0; + var dof = y * bpl; + if (false) { + } else if (bps == 1) + mi = data2[dof + (x2 >>> 3)] >>> 7 - (x2 & 7) & 1; + else if (bps == 2) + mi = data2[dof + (x2 >>> 2)] >>> 6 - 2 * (x2 & 3) & 3; + else if (bps == 4) + mi = data2[dof + (x2 >>> 1)] >>> 4 - 4 * (x2 & 1) & 15; + else if (bps == 8) + mi = data2[dof + x2 * smpls]; + else + throw bps; + img[qi] = map2[mi] >> 8; + img[qi + 1] = map2[cn + mi] >> 8; + img[qi + 2] = map2[cn + cn + mi] >> 8; + img[qi + 3] = nexta ? data2[dof + x2 * smpls + 1] : 255; + } + } else if (intp == 5) { + var gotAlpha = smpls > 4 ? 1 : 0; + for (var i = 0;i < area2; i++) { + var qi = i << 2, si = i * smpls; + if (window.UDOC) { + var C4 = data2[si], M = data2[si + 1], Y = data2[si + 2], K = data2[si + 3]; + var c = UDOC.C.cmykToRgb([C4 * (1 / 255), M * (1 / 255), Y * (1 / 255), K * (1 / 255)]); + img[qi] = ~~(0.5 + 255 * c[0]); + img[qi + 1] = ~~(0.5 + 255 * c[1]); + img[qi + 2] = ~~(0.5 + 255 * c[2]); + } else { + var C4 = 255 - data2[si], M = 255 - data2[si + 1], Y = 255 - data2[si + 2], K = (255 - data2[si + 3]) * (1 / 255); + img[qi] = ~~(C4 * K + 0.5); + img[qi + 1] = ~~(M * K + 0.5); + img[qi + 2] = ~~(Y * K + 0.5); + } + img[qi + 3] = 255 * (1 - gotAlpha) + data2[si + 4] * gotAlpha; + } + } else if (intp == 6 && out["t278"]) { + var rps = out["t278"][0]; + for (var y = 0;y < h; y += rps) { + var i = y * w, len = rps * w; + for (var j2 = 0;j2 < len; j2++) { + var qi = 4 * (i + j2), si = 3 * i + 4 * (j2 >>> 1); + var Y = data2[si + (j2 & 1)], Cb = data2[si + 2] - 128, Cr2 = data2[si + 3] - 128; + var r = Y + ((Cr2 >> 2) + (Cr2 >> 3) + (Cr2 >> 5)); + var g3 = Y - ((Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ((Cr2 >> 1) + (Cr2 >> 3) + (Cr2 >> 4) + (Cr2 >> 5)); + var b = Y + (Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)); + img[qi] = Math.max(0, Math.min(255, r)); + img[qi + 1] = Math.max(0, Math.min(255, g3)); + img[qi + 2] = Math.max(0, Math.min(255, b)); + img[qi + 3] = 255; + } + } + } else if (intp == 32845) { + for (var y = 0;y < h; y++) + for (var x2 = 0;x2 < w; x2++) { + var si = (y * w + x2) * 6, qi = (y * w + x2) * 4; + var L = data2[si + 1] << 8 | data2[si]; + var L = Math.pow(2, (L + 0.5) / 256 - 64); + var u2 = (data2[si + 3] + 0.5) / 410; + var v = (data2[si + 5] + 0.5) / 410; + var sX = 9 * u2 / (6 * u2 - 16 * v + 12); + var sY = 4 * v / (6 * u2 - 16 * v + 12); + var bY = L; + var X = sX * bY / sY, Y = bY, Z2 = (1 - sX - sY) * bY / sY; + var r = 2.69 * X - 1.276 * Y - 0.414 * Z2; + var g3 = -1.022 * X + 1.978 * Y + 0.044 * Z2; + var b = 0.061 * X - 0.224 * Y + 1.163 * Z2; + img[qi] = gamma(Math.min(r, 1)) * 255; + img[qi + 1] = gamma(Math.min(g3, 1)) * 255; + img[qi + 2] = gamma(Math.min(b, 1)) * 255; + img[qi + 3] = 255; + } + } else + log("Unknown Photometric interpretation: " + intp); + return img; +}; +UTIF.replaceIMG = function(imgs) { + if (imgs == null) + imgs = document.getElementsByTagName("img"); + var sufs = ["tif", "tiff", "dng", "cr2", "nef"]; + for (var i = 0;i < imgs.length; i++) { + var img = imgs[i], src = img.getAttribute("src"); + if (src == null) + continue; + var suff = src.split(".").pop().toLowerCase(); + if (sufs.indexOf(suff) == -1) + continue; + var xhr = new XMLHttpRequest; + UTIF._xhrs.push(xhr); + UTIF._imgs.push(img); + xhr.open("GET", src); + xhr.responseType = "arraybuffer"; + xhr.onload = UTIF._imgLoaded; + xhr.send(); + } +}; +UTIF._xhrs = []; +UTIF._imgs = []; +UTIF._imgLoaded = function(e) { + var ind = UTIF._xhrs.indexOf(e.target), img = UTIF._imgs[ind]; + UTIF._xhrs.splice(ind, 1); + UTIF._imgs.splice(ind, 1); + img.setAttribute("src", UTIF.bufferToURI(e.target.response)); +}; +UTIF.bufferToURI = function(buff) { + var ifds = UTIF.decode(buff); + var vsns = ifds, ma = 0, page = vsns[0]; + if (ifds[0].subIFD) + vsns = vsns.concat(ifds[0].subIFD); + for (var i = 0;i < vsns.length; i++) { + var img = vsns[i]; + if (img["t258"] == null || img["t258"].length < 3) + continue; + var ar = img["t256"] * img["t257"]; + if (ar > ma) { + ma = ar; + page = img; + } + } + UTIF.decodeImage(buff, page, ifds); + var rgba = UTIF.toRGBA8(page), w = page.width, h = page.height; + var cnv = document.createElement("canvas"); + cnv.width = w; + cnv.height = h; + var ctx = cnv.getContext("2d"); + var imgd = new ImageData(new Uint8ClampedArray(rgba.buffer), w, h); + ctx.putImageData(imgd, 0, 0); + return cnv.toDataURL(); +}; +UTIF._binBE = { + nextZero: function(data2, o) { + while (data2[o] != 0) + o++; + return o; + }, + readUshort: function(buff, p) { + return buff[p] << 8 | buff[p + 1]; + }, + readShort: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 1]; + a[1] = buff[p + 0]; + return UTIF._binBE.i16[0]; + }, + readInt: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 3]; + a[1] = buff[p + 2]; + a[2] = buff[p + 1]; + a[3] = buff[p + 0]; + return UTIF._binBE.i32[0]; + }, + readUint: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 3]; + a[1] = buff[p + 2]; + a[2] = buff[p + 1]; + a[3] = buff[p + 0]; + return UTIF._binBE.ui32[0]; + }, + readASCII: function(buff, p, l2) { + var s = ""; + for (var i = 0;i < l2; i++) + s += String.fromCharCode(buff[p + i]); + return s; + }, + readFloat: function(buff, p) { + var a = UTIF._binBE.ui8; + for (var i = 0;i < 4; i++) + a[i] = buff[p + 3 - i]; + return UTIF._binBE.fl32[0]; + }, + readDouble: function(buff, p) { + var a = UTIF._binBE.ui8; + for (var i = 0;i < 8; i++) + a[i] = buff[p + 7 - i]; + return UTIF._binBE.fl64[0]; + }, + writeUshort: function(buff, p, n2) { + buff[p] = n2 >> 8 & 255; + buff[p + 1] = n2 & 255; + }, + writeInt: function(buff, p, n2) { + var a = UTIF._binBE.ui8; + UTIF._binBE.i32[0] = n2; + buff[p + 3] = a[0]; + buff[p + 2] = a[1]; + buff[p + 1] = a[2]; + buff[p + 0] = a[3]; + }, + writeUint: function(buff, p, n2) { + buff[p] = n2 >> 24 & 255; + buff[p + 1] = n2 >> 16 & 255; + buff[p + 2] = n2 >> 8 & 255; + buff[p + 3] = n2 >> 0 & 255; + }, + writeASCII: function(buff, p, s) { + for (var i = 0;i < s.length; i++) + buff[p + i] = s.charCodeAt(i); + }, + writeDouble: function(buff, p, n2) { + UTIF._binBE.fl64[0] = n2; + for (var i = 0;i < 8; i++) + buff[p + i] = UTIF._binBE.ui8[7 - i]; + } +}; +UTIF._binBE.ui8 = new Uint8Array(8); +UTIF._binBE.i16 = new Int16Array(UTIF._binBE.ui8.buffer); +UTIF._binBE.i32 = new Int32Array(UTIF._binBE.ui8.buffer); +UTIF._binBE.ui32 = new Uint32Array(UTIF._binBE.ui8.buffer); +UTIF._binBE.fl32 = new Float32Array(UTIF._binBE.ui8.buffer); +UTIF._binBE.fl64 = new Float64Array(UTIF._binBE.ui8.buffer); +UTIF._binLE = { + nextZero: UTIF._binBE.nextZero, + readUshort: function(buff, p) { + return buff[p + 1] << 8 | buff[p]; + }, + readShort: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 0]; + a[1] = buff[p + 1]; + return UTIF._binBE.i16[0]; + }, + readInt: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 0]; + a[1] = buff[p + 1]; + a[2] = buff[p + 2]; + a[3] = buff[p + 3]; + return UTIF._binBE.i32[0]; + }, + readUint: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 0]; + a[1] = buff[p + 1]; + a[2] = buff[p + 2]; + a[3] = buff[p + 3]; + return UTIF._binBE.ui32[0]; + }, + readASCII: UTIF._binBE.readASCII, + readFloat: function(buff, p) { + var a = UTIF._binBE.ui8; + for (var i = 0;i < 4; i++) + a[i] = buff[p + i]; + return UTIF._binBE.fl32[0]; + }, + readDouble: function(buff, p) { + var a = UTIF._binBE.ui8; + for (var i = 0;i < 8; i++) + a[i] = buff[p + i]; + return UTIF._binBE.fl64[0]; + }, + writeUshort: function(buff, p, n2) { + buff[p] = n2 & 255; + buff[p + 1] = n2 >> 8 & 255; + }, + writeInt: function(buff, p, n2) { + var a = UTIF._binBE.ui8; + UTIF._binBE.i32[0] = n2; + buff[p + 0] = a[0]; + buff[p + 1] = a[1]; + buff[p + 2] = a[2]; + buff[p + 3] = a[3]; + }, + writeUint: function(buff, p, n2) { + buff[p] = n2 >>> 0 & 255; + buff[p + 1] = n2 >>> 8 & 255; + buff[p + 2] = n2 >>> 16 & 255; + buff[p + 3] = n2 >>> 24 & 255; + }, + writeASCII: UTIF._binBE.writeASCII +}; +UTIF._copyTile = function(tb, tw, th, b, w, h, xoff, yoff) { + var xlim = Math.min(tw, w - xoff); + var ylim = Math.min(th, h - yoff); + for (var y = 0;y < ylim; y++) { + var tof = (yoff + y) * w + xoff; + var sof = y * tw; + for (var x2 = 0;x2 < xlim; x2++) + b[tof + x2] = tb[sof + x2]; + } +}; +UTIF._inflateRaw = function() { + var H = {}; + H.H = {}; + H.H.N = function(N, W) { + var R2 = Uint8Array, i = 0, m = 0, J2 = 0, h = 0, Q2 = 0, X = 0, u2 = 0, w = 0, d = 0, v, C4; + if (N[0] == 3 && N[1] == 0) + return W ? W : new R2(0); + var V2 = H.H, n2 = V2.b, A2 = V2.e, l2 = V2.R, M = V2.n, I3 = V2.A, e = V2.Z, b = V2.m, Z2 = W == null; + if (Z2) + W = new R2(N.length >>> 2 << 5); + while (i == 0) { + i = n2(N, d, 1); + m = n2(N, d + 1, 2); + d += 3; + if (m == 0) { + if ((d & 7) != 0) + d += 8 - (d & 7); + var D = (d >>> 3) + 4, q2 = N[D - 4] | N[D - 3] << 8; + if (Z2) + W = H.H.W(W, w + q2); + W.set(new R2(N.buffer, N.byteOffset + D, q2), w); + d = D + q2 << 3; + w += q2; + continue; + } + if (Z2) + W = H.H.W(W, w + (1 << 17)); + if (m == 1) { + v = b.J; + C4 = b.h; + X = (1 << 9) - 1; + u2 = (1 << 5) - 1; + } + if (m == 2) { + J2 = A2(N, d, 5) + 257; + h = A2(N, d + 5, 5) + 1; + Q2 = A2(N, d + 10, 4) + 4; + d += 14; + var E2 = d, j2 = 1; + for (var c = 0;c < 38; c += 2) { + b.Q[c] = 0; + b.Q[c + 1] = 0; + } + for (var c = 0;c < Q2; c++) { + var K = A2(N, d + c * 3, 3); + b.Q[(b.X[c] << 1) + 1] = K; + if (K > j2) + j2 = K; + } + d += 3 * Q2; + M(b.Q, j2); + I3(b.Q, j2, b.u); + v = b.w; + C4 = b.d; + d = l2(b.u, (1 << j2) - 1, J2 + h, N, d, b.v); + var r = V2.V(b.v, 0, J2, b.C); + X = (1 << r) - 1; + var S = V2.V(b.v, J2, h, b.D); + u2 = (1 << S) - 1; + M(b.C, r); + I3(b.C, r, v); + M(b.D, S); + I3(b.D, S, C4); + } + while (true) { + var T2 = v[e(N, d) & X]; + d += T2 & 15; + var p = T2 >>> 4; + if (p >>> 8 == 0) { + W[w++] = p; + } else if (p == 256) { + break; + } else { + var z = w + p - 254; + if (p > 264) { + var _2 = b.q[p - 257]; + z = w + (_2 >>> 3) + A2(N, d, _2 & 7); + d += _2 & 7; + } + var $2 = C4[e(N, d) & u2]; + d += $2 & 15; + var s = $2 >>> 4, Y = b.c[s], a = (Y >>> 4) + n2(N, d, Y & 15); + d += Y & 15; + while (w < z) { + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + } + w = z; + } + } + } + return W.length == w ? W : W.slice(0, w); + }; + H.H.W = function(N, W) { + var R2 = N.length; + if (W <= R2) + return N; + var V2 = new Uint8Array(R2 << 1); + V2.set(N, 0); + return V2; + }; + H.H.R = function(N, W, R2, V2, n2, A2) { + var l2 = H.H.e, M = H.H.Z, I3 = 0; + while (I3 < R2) { + var e = N[M(V2, n2) & W]; + n2 += e & 15; + var b = e >>> 4; + if (b <= 15) { + A2[I3] = b; + I3++; + } else { + var Z2 = 0, m = 0; + if (b == 16) { + m = 3 + l2(V2, n2, 2); + n2 += 2; + Z2 = A2[I3 - 1]; + } else if (b == 17) { + m = 3 + l2(V2, n2, 3); + n2 += 3; + } else if (b == 18) { + m = 11 + l2(V2, n2, 7); + n2 += 7; + } + var J2 = I3 + m; + while (I3 < J2) { + A2[I3] = Z2; + I3++; + } + } + } + return n2; + }; + H.H.V = function(N, W, R2, V2) { + var n2 = 0, A2 = 0, l2 = V2.length >>> 1; + while (A2 < R2) { + var M = N[A2 + W]; + V2[A2 << 1] = 0; + V2[(A2 << 1) + 1] = M; + if (M > n2) + n2 = M; + A2++; + } + while (A2 < l2) { + V2[A2 << 1] = 0; + V2[(A2 << 1) + 1] = 0; + A2++; + } + return n2; + }; + H.H.n = function(N, W) { + var R2 = H.H.m, V2 = N.length, n2, A2, l2, M, I3, e = R2.j; + for (var M = 0;M <= W; M++) + e[M] = 0; + for (M = 1;M < V2; M += 2) + e[N[M]]++; + var b = R2.K; + n2 = 0; + e[0] = 0; + for (A2 = 1;A2 <= W; A2++) { + n2 = n2 + e[A2 - 1] << 1; + b[A2] = n2; + } + for (l2 = 0;l2 < V2; l2 += 2) { + I3 = N[l2 + 1]; + if (I3 != 0) { + N[l2] = b[I3]; + b[I3]++; + } + } + }; + H.H.A = function(N, W, R2) { + var V2 = N.length, n2 = H.H.m, A2 = n2.r; + for (var l2 = 0;l2 < V2; l2 += 2) + if (N[l2 + 1] != 0) { + var M = l2 >> 1, I3 = N[l2 + 1], e = M << 4 | I3, b = W - I3, Z2 = N[l2] << b, m = Z2 + (1 << b); + while (Z2 != m) { + var J2 = A2[Z2] >>> 15 - W; + R2[J2] = e; + Z2++; + } + } + }; + H.H.l = function(N, W) { + var R2 = H.H.m.r, V2 = 15 - W; + for (var n2 = 0;n2 < N.length; n2 += 2) { + var A2 = N[n2] << W - N[n2 + 1]; + N[n2] = R2[A2] >>> V2; + } + }; + H.H.M = function(N, W, R2) { + R2 = R2 << (W & 7); + var V2 = W >>> 3; + N[V2] |= R2; + N[V2 + 1] |= R2 >>> 8; + }; + H.H.I = function(N, W, R2) { + R2 = R2 << (W & 7); + var V2 = W >>> 3; + N[V2] |= R2; + N[V2 + 1] |= R2 >>> 8; + N[V2 + 2] |= R2 >>> 16; + }; + H.H.e = function(N, W, R2) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8) >>> (W & 7) & (1 << R2) - 1; + }; + H.H.b = function(N, W, R2) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7) & (1 << R2) - 1; + }; + H.H.Z = function(N, W) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7); + }; + H.H.i = function(N, W) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16 | N[(W >>> 3) + 3] << 24) >>> (W & 7); + }; + H.H.m = function() { + var N = Uint16Array, W = Uint32Array; + return { K: new N(16), j: new N(16), X: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], S: [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, 999, 999, 999], T: [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, 0, 0, 0], q: new N(32), 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, 65535, 65535], z: [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, 0, 0], c: new W(32), J: new N(512), _: [], h: new N(32), $: [], w: new N(32768), C: [], v: [], d: new N(32768), D: [], u: new N(512), Q: [], r: new N(1 << 15), s: new W(286), Y: new W(30), a: new W(19), t: new W(15000), k: new N(1 << 16), g: new N(1 << 15) }; + }(); + (function() { + var N = H.H.m, W = 1 << 15; + for (var R2 = 0;R2 < W; R2++) { + var V2 = R2; + V2 = (V2 & 2863311530) >>> 1 | (V2 & 1431655765) << 1; + V2 = (V2 & 3435973836) >>> 2 | (V2 & 858993459) << 2; + V2 = (V2 & 4042322160) >>> 4 | (V2 & 252645135) << 4; + V2 = (V2 & 4278255360) >>> 8 | (V2 & 16711935) << 8; + N.r[R2] = (V2 >>> 16 | V2 << 16) >>> 17; + } + function n2(A2, l2, M) { + while (l2-- != 0) + A2.push(0, M); + } + for (var R2 = 0;R2 < 32; R2++) { + N.q[R2] = N.S[R2] << 3 | N.T[R2]; + N.c[R2] = N.p[R2] << 4 | N.z[R2]; + } + n2(N._, 144, 8); + n2(N._, 255 - 143, 9); + n2(N._, 279 - 255, 7); + n2(N._, 287 - 279, 8); + H.H.n(N._, 9); + H.H.A(N._, 9, N.J); + H.H.l(N._, 9); + n2(N.$, 32, 5); + H.H.n(N.$, 5); + H.H.A(N.$, 5, N.h); + H.H.l(N.$, 5); + n2(N.Q, 19, 0); + n2(N.C, 286, 0); + n2(N.D, 30, 0); + n2(N.v, 320, 0); + })(); + return H.H.N; +}(); +UTIF.LosslessJpegDecode = function() { + var b, O; + function l2() { + return b[O++]; + } + function m() { + return b[O++] << 8 | b[O++]; + } + function a0(h) { + var V2 = l2(), I3 = [0, 0, 0, 255], f = [], G2 = 8; + for (var w = 0;w < 16; w++) + f[w] = l2(); + for (var w = 0;w < 16; w++) { + for (var x2 = 0;x2 < f[w]; x2++) { + var T2 = z(I3, 0, w + 1, 1); + I3[T2 + 3] = l2(); + } + } + var E2 = new Uint8Array(1 << G2); + h[V2] = [new Uint8Array(I3), E2]; + for (var w = 0;w < 1 << G2; w++) { + var s = G2, _2 = w, Y = 0, F = 0; + while (I3[Y + 3] == 255 && s != 0) { + F = _2 >> --s & 1; + Y = I3[Y + F]; + } + E2[w] = Y; + } + } + function z(h, V2, I3, f) { + if (h[V2 + 3] != 255) + return 0; + if (I3 == 0) + return V2; + for (var w = 0;w < 2; w++) { + if (h[V2 + w] == 0) { + h[V2 + w] = h.length; + h.push(0, 0, f, 255); + } + var x2 = z(h, h[V2 + w], I3 - 1, f + 1); + if (x2 != 0) + return x2; + } + return 0; + } + function i(h) { + var { b: V2, f: I3 } = h; + while (V2 < 25 && h.a < h.d) { + var f = h.data[h.a++]; + if (f == 255 && !h.c) + h.a++; + I3 = I3 << 8 | f; + V2 += 8; + } + if (V2 < 0) + throw "e"; + h.b = V2; + h.f = I3; + } + function H(h, V2) { + if (V2.b < h) + i(V2); + return V2.f >> (V2.b -= h) & 65535 >> 16 - h; + } + function g3(h, V2) { + var I3 = h[0], f = 0, w = 255, x2 = 0; + if (V2.b < 16) + i(V2); + var T2 = V2.f >> V2.b - 8 & 255; + f = h[1][T2]; + w = I3[f + 3]; + V2.b -= I3[f + 2]; + while (w == 255) { + x2 = V2.f >> --V2.b & 1; + f = I3[f + x2]; + w = I3[f + 3]; + } + return w; + } + function P(h, V2) { + if (h < 32768 >> 16 - V2) + h += -(1 << V2) + 1; + return h; + } + function a2(h, V2) { + var I3 = g3(h, V2); + if (I3 == 0) + return 0; + if (I3 == 16) + return -32768; + var f = H(I3, V2); + return P(f, I3); + } + function X(h, V2, I3, f, w, x2) { + var T2 = 0; + for (var G2 = 0;G2 < x2; G2++) { + var s = G2 * V2; + for (var _2 = 0;_2 < V2; _2 += w) { + T2++; + for (var Y = 0;Y < w; Y++) + h[s + _2 + Y] = a2(f[Y], I3); + } + if (I3.e != 0 && T2 % I3.e == 0 && G2 != 0) { + var { a: F, data: t2 } = I3; + while (t2[F] != 255 || !(208 <= t2[F + 1] && t2[F + 1] <= 215)) + F--; + I3.a = F + 2; + I3.f = 0; + I3.b = 0; + } + } + } + function o(h, V2) { + return P(H(h, V2), h); + } + function a1(h, V2, I3, f, w) { + var x2 = b.length - O; + for (var T2 = 0;T2 < x2; T2 += 4) { + var G2 = b[O + T2]; + b[O + T2] = b[O + T2 + 3]; + b[O + T2 + 3] = G2; + var G2 = b[O + T2 + 1]; + b[O + T2 + 1] = b[O + T2 + 2]; + b[O + T2 + 2] = G2; + } + for (var E2 = 0;E2 < w; E2++) { + var s = 32768, _2 = 32768; + for (var Y = 0;Y < V2; Y += 2) { + var F = g3(f, I3), t2 = g3(f, I3); + if (F != 0) + s += o(F, I3); + if (t2 != 0) + _2 += o(t2, I3); + h[E2 * V2 + Y] = s & 65535; + h[E2 * V2 + Y + 1] = _2 & 65535; + } + } + } + function C4(h) { + b = h; + O = 0; + if (m() != 65496) + throw "e"; + var V2 = [], I3 = 0, f = 0, w = 0, x2 = [], T2 = [], G2 = [], E2 = 0, s = 0, _2 = 0; + while (true) { + var Y = m(); + if (Y == 65535) { + O--; + continue; + } + var F = m(); + if (Y == 65475) { + f = l2(); + s = m(); + _2 = m(); + E2 = l2(); + for (var t2 = 0;t2 < E2; t2++) { + var a = l2(), J2 = l2(), r = l2(); + if (r != 0) + throw "e"; + V2[a] = [t2, J2 >> 4, J2 & 15]; + } + } else if (Y == 65476) { + var a3 = O + F - 2; + while (O < a3) + a0(T2); + } else if (Y == 65498) { + O++; + for (var t2 = 0;t2 < E2; t2++) { + var a5 = l2(), v = V2[a5]; + G2[v[0]] = T2[l2() >>> 4]; + x2[v[0]] = v.slice(1); + } + I3 = l2(); + O += 2; + break; + } else if (Y == 65501) { + w = m(); + } else { + O += F - 2; + } + } + var a4 = f > 8 ? Uint16Array : Uint8Array, $2 = new a4(s * _2 * E2), M = { b: 0, f: 0, c: I3 == 8, a: O, data: b, d: b.length, e: w }; + if (M.c) + a1($2, _2 * E2, M, G2[0], s); + else { + var c = [], p = 0, D = 0; + for (var t2 = 0;t2 < E2; t2++) { + var N = x2[t2], S = N[0], K = N[1]; + if (S > p) + p = S; + if (K > D) + D = K; + c.push(S * K); + } + if (p != 1 || D != 1) { + if (E2 != 3 || c[1] != 1 || c[2] != 1) + throw "e"; + if (p != 2 || D != 1 && D != 2) + throw "e"; + var u2 = [], Z2 = 0; + for (var t2 = 0;t2 < E2; t2++) { + for (var R2 = 0;R2 < c[t2]; R2++) + u2.push(G2[t2]); + Z2 += c[t2]; + } + var B2 = _2 / p, e = s / D, d = B2 * e; + X($2, B2 * Z2, M, u2, Z2, e); + j2($2, I3, B2, e, Z2 - 2, Z2, Z2, f); + var A2 = new Uint16Array(d * c[0]); + if (p == 2 && D == 2) { + for (var t2 = 0;t2 < d; t2++) { + A2[4 * t2] = $2[6 * t2]; + A2[4 * t2 + 1] = $2[6 * t2 + 1]; + A2[4 * t2 + 2] = $2[6 * t2 + 2]; + A2[4 * t2 + 3] = $2[6 * t2 + 3]; + } + j2(A2, I3, B2 * 4, e, 0, 1, 1, f); + for (var t2 = 0;t2 < d; t2++) { + $2[6 * t2] = A2[4 * t2]; + $2[6 * t2 + 1] = A2[4 * t2 + 1]; + $2[6 * t2 + 2] = A2[4 * t2 + 2]; + $2[6 * t2 + 3] = A2[4 * t2 + 3]; + } + } + if (p == 2 && D == 1) { + for (var t2 = 0;t2 < d; t2++) { + A2[2 * t2] = $2[4 * t2]; + A2[2 * t2 + 1] = $2[4 * t2 + 1]; + } + j2(A2, I3, B2 * 2, e, 0, 1, 1, f); + for (var t2 = 0;t2 < d; t2++) { + $2[4 * t2] = A2[2 * t2]; + $2[4 * t2 + 1] = A2[2 * t2 + 1]; + } + } + var n2 = $2.slice(0); + for (var K = 0;K < s; K++) { + if (D == 2) + for (var S = 0;S < _2; S++) { + var q2 = (K * _2 + S) * E2, k2 = ((K >>> 1) * B2 + (S >>> 1)) * Z2, y = (K & 1) * 2 + (S & 1); + $2[q2] = n2[k2 + y]; + $2[q2 + 1] = n2[k2 + 4]; + $2[q2 + 2] = n2[k2 + 5]; + } + else + for (var S = 0;S < _2; S++) { + var q2 = (K * _2 + S) * E2, k2 = (K * B2 + (S >>> 1)) * Z2, y = S & 1; + $2[q2] = n2[k2 + y]; + $2[q2 + 1] = n2[k2 + 2]; + $2[q2 + 2] = n2[k2 + 3]; + } + } + } else { + X($2, _2 * E2, M, G2, E2, s); + if (w == 0) + j2($2, I3, _2, s, 0, E2, E2, f); + else { + var U = Math.floor(w / _2); + for (var K = 0;K < s; K += U) { + var L = $2.slice(K * _2 * E2, (K + U) * _2 * E2); + j2(L, I3, _2, U, 0, E2, E2, f); + $2.set(L, K * _2 * E2); + } + } + } + } + return $2; + } + function j2(h, V2, I3, f, w, x2, G2, E2) { + var s = I3 * G2; + for (var _2 = w;_2 < x2; _2++) + h[_2] += 1 << E2 - 1; + for (var Y = G2;Y < s; Y += G2) + for (var _2 = w;_2 < x2; _2++) + h[Y + _2] += h[Y + _2 - G2]; + for (var F = 1;F < f; F++) { + var t2 = F * s; + for (var _2 = w;_2 < x2; _2++) + h[t2 + _2] += h[t2 + _2 - s]; + for (var Y = G2;Y < s; Y += G2) { + for (var _2 = w;_2 < x2; _2++) { + var a = t2 + Y + _2, J2 = a - s, r = h[a - G2], Q2 = 0; + if (V2 == 0) + Q2 = 0; + else if (V2 == 1) + Q2 = r; + else if (V2 == 2) + Q2 = h[J2]; + else if (V2 == 3) + Q2 = h[J2 - G2]; + else if (V2 == 4) + Q2 = r + (h[J2] - h[J2 - G2]); + else if (V2 == 5) + Q2 = r + (h[J2] - h[J2 - G2] >>> 1); + else if (V2 == 6) + Q2 = h[J2] + (r - h[J2 - G2] >>> 1); + else if (V2 == 7) + Q2 = r + h[J2] >>> 1; + else + throw V2; + h[a] += Q2; + } + } + } + } + return C4; +}(); +(function() { + var G2 = 0, F = 1, i = 2, b = 3, J2 = 4, N = 5, E2 = 6, s = 7, c = 8, T2 = 9, a3 = 10, f = 11, q2 = 12, M = 13, m = 14, x2 = 15, L = 16, $2 = 17, p = 18; + function a5(t2) { + var Z2 = UTIF._binBE.readUshort, u2 = { b: Z2(t2, 0), i: t2[2], C: t2[3], u: t2[4], q: Z2(t2, 5), k: Z2(t2, 7), e: Z2(t2, 9), l: Z2(t2, 11), s: t2[13], d: Z2(t2, 14) }; + if (u2.b != 18771 || u2.i > 1 || u2.q < 6 || u2.q % 6 || u2.e < 768 || u2.e % 24 || u2.l != 768 || u2.k < u2.l || u2.k % u2.l || u2.k - u2.e >= u2.l || u2.s > 16 || u2.s != u2.k / u2.l || u2.s != Math.ceil(u2.e / u2.l) || u2.d != u2.q / 6 || u2.u != 12 && u2.u != 14 && u2.u != 16 || u2.C != 16 && u2.C != 0) { + throw "Invalid data"; + } + if (u2.i == 0) { + throw "Not implemented. We need this file!"; + } + u2.h = u2.C == 16; + u2.m = (u2.h ? u2.l * 2 / 3 : u2.l >>> 1) | 0; + u2.A = u2.m + 2; + u2.f = 64; + u2.g = (1 << u2.u) - 1; + u2.n = 4 * u2.u; + return u2; + } + function a7(t2, Z2) { + var u2 = new Array(Z2.s), e = 4 * Z2.s, Q2 = 16 + e; + if (e & 12) + Q2 += 16 - (e & 12); + for (var V2 = 0, O = 16;V2 < Z2.s; O += 4) { + var o = UTIF._binBE.readUint(t2, O); + u2[V2] = t2.slice(Q2, Q2 + o); + u2[V2].j = 0; + u2[V2].a = 0; + Q2 += o; + V2++; + } + if (Q2 != t2.length) + throw "Invalid data"; + return u2; + } + function a6(t2, Z2) { + for (var u2 = -Z2[4], e = 0;u2 <= Z2[4]; e++, u2++) { + t2[e] = u2 <= -Z2[3] ? -4 : u2 <= -Z2[2] ? -3 : u2 <= -Z2[1] ? -2 : u2 < -Z2[0] ? -1 : u2 <= Z2[0] ? 0 : u2 < Z2[1] ? 1 : u2 < Z2[2] ? 2 : u2 < Z2[3] ? 3 : 4; + } + } + function a1(t2, Z2, u2) { + var e = [Z2, 3 * Z2 + 18, 5 * Z2 + 67, 7 * Z2 + 276, u2]; + t2.o = Z2; + t2.w = (e[4] + 2 * Z2) / (2 * Z2 + 1) + 1 | 0; + t2.v = Math.ceil(Math.log2(t2.w)); + t2.t = 9; + a6(t2.c, e); + } + function a2(t2) { + var Z2 = { c: new Int8Array(2 << t2.u) }; + a1(Z2, 0, t2.g); + return Z2; + } + function D(t2) { + var Z2 = [[], [], []], u2 = Math.max(2, t2.w + 32 >>> 6); + for (var e = 0;e < 3; e++) { + for (var Q2 = 0;Q2 < 41; Q2++) { + Z2[e][Q2] = [u2, 1]; + } + } + return Z2; + } + function a4(t2) { + for (var Z2 = -1, u2 = 0;!u2; Z2++) { + u2 = t2[t2.j] >>> 7 - t2.a & 1; + t2.a++; + t2.a &= 7; + if (!t2.a) + t2.j++; + } + return Z2; + } + function K(t2, Z2) { + var u2 = 0, e = 8 - t2.a, Q2 = t2.j, V2 = t2.a; + if (Z2) { + if (Z2 >= e) { + do { + u2 <<= e; + Z2 -= e; + u2 |= t2[t2.j] & (1 << e) - 1; + t2.j++; + e = 8; + } while (Z2 >= 8); + } + if (Z2) { + u2 <<= Z2; + e -= Z2; + u2 |= t2[t2.j] >>> e & (1 << Z2) - 1; + } + t2.a = 8 - e; + } + return u2; + } + function a0(t2, Z2) { + var u2 = 0; + if (Z2 < t2) { + while (u2 <= 14 && Z2 << ++u2 < t2) + ; + } + return u2; + } + function r(t2, Z2, u2, e, Q2, V2, O, o) { + if (o == null) + o = 0; + var X = V2 + 1, k2 = X % 2, j2 = 0, I3 = 0, a = 0, l2, R2, w = e[Q2], S = e[Q2 - 1], H = e[Q2 - 2][X], g3 = S[X - 1], Y = S[X], P = S[X + 1], A2 = w[X - 1], v = w[X + 1], y = Math.abs, d, C4, n2, h; + if (k2) { + d = y(P - Y); + C4 = y(H - Y); + n2 = y(g3 - Y); + } + if (k2) { + h = d > n2 && C4 < d ? H + g3 : d < n2 && C4 < n2 ? H + P : P + g3; + h = h + 2 * Y >>> 2; + if (o) { + w[X] = h; + return; + } + l2 = Z2.t * Z2.c[t2.g + Y - H] + Z2.c[t2.g + g3 - Y]; + } else { + h = Y > g3 && Y > P || Y < g3 && Y < P ? v + A2 + 2 * Y >>> 2 : A2 + v >>> 1; + l2 = Z2.t * Z2.c[t2.g + Y - g3] + Z2.c[t2.g + g3 - A2]; + } + R2 = y(l2); + var W = a4(u2); + if (W < t2.n - Z2.v - 1) { + var z = a0(O[R2][0], O[R2][1]); + a = K(u2, z) + (W << z); + } else { + a = K(u2, Z2.v) + 1; + } + a = a & 1 ? -1 - (a >>> 1) : a >>> 1; + O[R2][0] += y(a); + if (O[R2][1] == t2.f) { + O[R2][0] >>>= 1; + O[R2][1] >>>= 1; + } + O[R2][1]++; + h = l2 < 0 ? h - a : h + a; + if (t2.i) { + if (h < 0) + h += Z2.w; + else if (h > t2.g) + h -= Z2.w; + } + w[X] = h >= 0 ? Math.min(h, t2.g) : 0; + } + function U(t2, Z2, u2) { + var e = t2[0].length; + for (var Q2 = Z2;Q2 <= u2; Q2++) { + t2[Q2][0] = t2[Q2 - 1][1]; + t2[Q2][e - 1] = t2[Q2 - 1][e - 2]; + } + } + function B2(t2) { + U(t2, s, q2); + U(t2, i, J2); + U(t2, x2, $2); + } + function _2(t2, Z2, u2, e, Q2, V2, O, o, X, k2, j2, I3, a) { + var l2 = 0, R2 = 1, w = Q2 < M && Q2 > J2; + while (R2 < t2.m) { + if (l2 < t2.m) { + r(t2, Z2, u2, e, Q2, l2, O[X], t2.h && (w && k2 || !w && (j2 || (l2 & I3) == a))); + r(t2, Z2, u2, e, V2, l2, O[X], t2.h && (!w && k2 || w && (j2 || (l2 & I3) == a))); + l2 += 2; + } + if (l2 > 8) { + r(t2, Z2, u2, e, Q2, R2, o[X]); + r(t2, Z2, u2, e, V2, R2, o[X]); + R2 += 2; + } + } + B2(e); + } + function a8(t2, Z2, u2, e, Q2, V2) { + _2(t2, Z2, u2, e, i, s, Q2, V2, 0, 0, 1, 0, 8); + _2(t2, Z2, u2, e, c, x2, Q2, V2, 1, 0, 1, 0, 8); + _2(t2, Z2, u2, e, b, T2, Q2, V2, 2, 1, 0, 3, 0); + _2(t2, Z2, u2, e, a3, L, Q2, V2, 0, 0, 0, 3, 2); + _2(t2, Z2, u2, e, J2, f, Q2, V2, 1, 0, 0, 3, 2); + _2(t2, Z2, u2, e, q2, $2, Q2, V2, 2, 1, 0, 3, 0); + } + function a9(t2, Z2, u2, e, Q2, V2) { + var O = V2.length, o = t2.l; + if (Q2 + 1 == t2.s) + o = t2.e - Q2 * t2.l; + var X = 6 * t2.e * e + Q2 * t2.l; + for (var k2 = 0;k2 < 6; k2++) { + for (var j2 = 0;j2 < o; j2++) { + var I3 = V2[k2 % O][j2 % O], a; + if (I3 == 0) { + a = i + (k2 >>> 1); + } else if (I3 == 2) { + a = x2 + (k2 >>> 1); + } else { + a = s + k2; + } + var l2 = t2.h ? (j2 * 2 / 3 & 2147483646 | j2 % 3 & 1) + (j2 % 3 >>> 1) : j2 >>> 1; + Z2[X + j2] = u2[a][l2 + 1]; + } + X += t2.e; + } + } + UTIF._decompressRAF = function(t2, Z2) { + var u2 = a5(t2), e = a7(t2, u2), Q2 = a2(u2), V2 = new Int16Array(u2.e * u2.q); + if (Z2 == null) { + Z2 = u2.h ? [[1, 1, 0, 1, 1, 2], [1, 1, 2, 1, 1, 0], [2, 0, 1, 0, 2, 1], [1, 1, 2, 1, 1, 0], [1, 1, 0, 1, 1, 2], [0, 2, 1, 2, 0, 1]] : [[0, 1], [3, 2]]; + } + var O = [[G2, b], [F, J2], [N, f], [E2, q2], [M, L], [m, $2]], o = []; + for (var X = 0;X < p; X++) { + o[X] = new Uint16Array(u2.A); + } + for (var k2 = 0;k2 < u2.s; k2++) { + var j2 = D(Q2), I3 = D(Q2); + for (var X = 0;X < p; X++) { + for (var a = 0;a < u2.A; a++) { + o[X][a] = 0; + } + } + for (var l2 = 0;l2 < u2.d; l2++) { + a8(u2, Q2, e[k2], o, j2, I3); + for (var X = 0;X < 6; X++) { + for (var a = 0;a < u2.A; a++) { + o[O[X][0]][a] = o[O[X][1]][a]; + } + } + a9(u2, V2, o, l2, k2, Z2); + for (var X = i;X < p; X++) { + if ([N, E2, M, m].indexOf(X) == -1) { + for (var a = 0;a < u2.A; a++) { + o[X][a] = 0; + } + } + } + B2(o); + } + } + return V2; + }; +})(); +// node_modules/three/examples/jsm/libs/opentype.module.js +/*! https://mths.be/codepointat v0.2.0 by @mathias */ +if (!String.prototype.codePointAt) { + (function() { + var defineProperty = function() { + try { + var object = {}; + var $defineProperty = Object.defineProperty; + var result = $defineProperty(object, object, object) && $defineProperty; + } catch (error) { + } + return result; + }(); + var codePointAt = function(position2) { + if (this == null) { + throw TypeError(); + } + var string = String(this); + var size = string.length; + var index2 = position2 ? Number(position2) : 0; + if (index2 != index2) { + index2 = 0; + } + if (index2 < 0 || index2 >= size) { + return; + } + var first2 = string.charCodeAt(index2); + var second; + if (first2 >= 55296 && first2 <= 56319 && size > index2 + 1) { + second = string.charCodeAt(index2 + 1); + if (second >= 56320 && second <= 57343) { + return (first2 - 55296) * 1024 + second - 56320 + 65536; + } + } + return first2; + }; + if (defineProperty) { + defineProperty(String.prototype, "codePointAt", { + value: codePointAt, + configurable: true, + writable: true + }); + } else { + String.prototype.codePointAt = codePointAt; + } + })(); +} +function Tree() { + this.table = new Uint16Array(16); + this.trans = new Uint16Array(288); +} +var sltree = new Tree; +var sdtree = new Tree; +var length_bits = new Uint8Array(30); +var length_base = new Uint16Array(30); +var dist_bits = new Uint8Array(30); +var dist_base = new Uint16Array(30); +var clcidx = new Uint8Array([ + 16, + 17, + 18, + 0, + 8, + 7, + 9, + 6, + 10, + 5, + 11, + 4, + 12, + 3, + 13, + 2, + 14, + 1, + 15 +]); +var code_tree = new Tree; +var lengths = new Uint8Array(288 + 32); +function tinf_build_bits_base(bits, base, delta, first2) { + var i, sum2; + for (i = 0;i < delta; ++i) { + bits[i] = 0; + } + for (i = 0;i < 30 - delta; ++i) { + bits[i + delta] = i / delta | 0; + } + for (sum2 = first2, i = 0;i < 30; ++i) { + base[i] = sum2; + sum2 += 1 << bits[i]; + } +} +function tinf_build_fixed_trees(lt, dt) { + var i; + for (i = 0;i < 7; ++i) { + lt.table[i] = 0; + } + lt.table[7] = 24; + lt.table[8] = 152; + lt.table[9] = 112; + for (i = 0;i < 24; ++i) { + lt.trans[i] = 256 + i; + } + for (i = 0;i < 144; ++i) { + lt.trans[24 + i] = i; + } + for (i = 0;i < 8; ++i) { + lt.trans[24 + 144 + i] = 280 + i; + } + for (i = 0;i < 112; ++i) { + lt.trans[24 + 144 + 8 + i] = 144 + i; + } + for (i = 0;i < 5; ++i) { + dt.table[i] = 0; + } + dt.table[5] = 32; + for (i = 0;i < 32; ++i) { + dt.trans[i] = i; + } +} +var offs = new Uint16Array(16); +tinf_build_fixed_trees(sltree, sdtree); +tinf_build_bits_base(length_bits, length_base, 4, 3); +tinf_build_bits_base(dist_bits, dist_base, 2, 1); +length_bits[28] = 0; +length_base[28] = 258; +function derive(v0, v1, v2, v3, t2) { + return Math.pow(1 - t2, 3) * v0 + 3 * Math.pow(1 - t2, 2) * t2 * v1 + 3 * (1 - t2) * Math.pow(t2, 2) * v2 + Math.pow(t2, 3) * v3; +} +function BoundingBox() { + this.x1 = Number.NaN; + this.y1 = Number.NaN; + this.x2 = Number.NaN; + this.y2 = Number.NaN; +} +BoundingBox.prototype.isEmpty = function() { + return isNaN(this.x1) || isNaN(this.y1) || isNaN(this.x2) || isNaN(this.y2); +}; +BoundingBox.prototype.addPoint = function(x2, y) { + if (typeof x2 === "number") { + if (isNaN(this.x1) || isNaN(this.x2)) { + this.x1 = x2; + this.x2 = x2; + } + if (x2 < this.x1) { + this.x1 = x2; + } + if (x2 > this.x2) { + this.x2 = x2; + } + } + if (typeof y === "number") { + if (isNaN(this.y1) || isNaN(this.y2)) { + this.y1 = y; + this.y2 = y; + } + if (y < this.y1) { + this.y1 = y; + } + if (y > this.y2) { + this.y2 = y; + } + } +}; +BoundingBox.prototype.addX = function(x2) { + this.addPoint(x2, null); +}; +BoundingBox.prototype.addY = function(y) { + this.addPoint(null, y); +}; +BoundingBox.prototype.addBezier = function(x0, y0, x1, y1, x2, y2, x3, y) { + var p0 = [x0, y0]; + var p1 = [x1, y1]; + var p2 = [x2, y2]; + var p3 = [x3, y]; + this.addPoint(x0, y0); + this.addPoint(x3, y); + for (var i = 0;i <= 1; i++) { + var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; + var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; + var c = 3 * p1[i] - 3 * p0[i]; + if (a === 0) { + if (b === 0) { + continue; + } + var t2 = -c / b; + if (0 < t2 && t2 < 1) { + if (i === 0) { + this.addX(derive(p0[i], p1[i], p2[i], p3[i], t2)); + } + if (i === 1) { + this.addY(derive(p0[i], p1[i], p2[i], p3[i], t2)); + } + } + continue; + } + var b2ac = Math.pow(b, 2) - 4 * c * a; + if (b2ac < 0) { + continue; + } + var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); + if (0 < t1 && t1 < 1) { + if (i === 0) { + this.addX(derive(p0[i], p1[i], p2[i], p3[i], t1)); + } + if (i === 1) { + this.addY(derive(p0[i], p1[i], p2[i], p3[i], t1)); + } + } + var t22 = (-b - Math.sqrt(b2ac)) / (2 * a); + if (0 < t22 && t22 < 1) { + if (i === 0) { + this.addX(derive(p0[i], p1[i], p2[i], p3[i], t22)); + } + if (i === 1) { + this.addY(derive(p0[i], p1[i], p2[i], p3[i], t22)); + } + } + } +}; +BoundingBox.prototype.addQuad = function(x0, y0, x1, y1, x2, y) { + var cp1x = x0 + 2 / 3 * (x1 - x0); + var cp1y = y0 + 2 / 3 * (y1 - y0); + var cp2x = cp1x + 1 / 3 * (x2 - x0); + var cp2y = cp1y + 1 / 3 * (y - y0); + this.addBezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x2, y); +}; +function Path2() { + this.commands = []; + this.fill = "black"; + this.stroke = null; + this.strokeWidth = 1; +} +Path2.prototype.moveTo = function(x2, y) { + this.commands.push({ + type: "M", + x: x2, + y + }); +}; +Path2.prototype.lineTo = function(x2, y) { + this.commands.push({ + type: "L", + x: x2, + y + }); +}; +Path2.prototype.curveTo = Path2.prototype.bezierCurveTo = function(x1, y1, x2, y2, x3, y) { + this.commands.push({ + type: "C", + x1, + y1, + x2, + y2, + x: x3, + y + }); +}; +Path2.prototype.quadTo = Path2.prototype.quadraticCurveTo = function(x1, y1, x2, y) { + this.commands.push({ + type: "Q", + x1, + y1, + x: x2, + y + }); +}; +Path2.prototype.close = Path2.prototype.closePath = function() { + this.commands.push({ + type: "Z" + }); +}; +Path2.prototype.extend = function(pathOrCommands) { + if (pathOrCommands.commands) { + pathOrCommands = pathOrCommands.commands; + } else if (pathOrCommands instanceof BoundingBox) { + var box = pathOrCommands; + this.moveTo(box.x1, box.y1); + this.lineTo(box.x2, box.y1); + this.lineTo(box.x2, box.y2); + this.lineTo(box.x1, box.y2); + this.close(); + return; + } + Array.prototype.push.apply(this.commands, pathOrCommands); +}; +Path2.prototype.getBoundingBox = function() { + var box = new BoundingBox; + var startX = 0; + var startY = 0; + var prevX = 0; + var prevY = 0; + for (var i = 0;i < this.commands.length; i++) { + var cmd = this.commands[i]; + switch (cmd.type) { + case "M": + box.addPoint(cmd.x, cmd.y); + startX = prevX = cmd.x; + startY = prevY = cmd.y; + break; + case "L": + box.addPoint(cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case "Q": + box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case "C": + box.addBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case "Z": + prevX = startX; + prevY = startY; + break; + default: + throw new Error("Unexpected path command " + cmd.type); + } + } + if (box.isEmpty()) { + box.addPoint(0, 0); + } + return box; +}; +Path2.prototype.draw = function(ctx) { + ctx.beginPath(); + for (var i = 0;i < this.commands.length; i += 1) { + var cmd = this.commands[i]; + if (cmd.type === "M") { + ctx.moveTo(cmd.x, cmd.y); + } else if (cmd.type === "L") { + ctx.lineTo(cmd.x, cmd.y); + } else if (cmd.type === "C") { + ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === "Q") { + ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); + } else if (cmd.type === "Z") { + ctx.closePath(); + } + } + if (this.fill) { + ctx.fillStyle = this.fill; + ctx.fill(); + } + if (this.stroke) { + ctx.strokeStyle = this.stroke; + ctx.lineWidth = this.strokeWidth; + ctx.stroke(); + } +}; +Path2.prototype.toPathData = function(decimalPlaces) { + decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2; + function floatToString(v) { + if (Math.round(v) === v) { + return "" + Math.round(v); + } else { + return v.toFixed(decimalPlaces); + } + } + function packValues() { + var arguments$1 = arguments; + var s = ""; + for (var i2 = 0;i2 < arguments.length; i2 += 1) { + var v = arguments$1[i2]; + if (v >= 0 && i2 > 0) { + s += " "; + } + s += floatToString(v); + } + return s; + } + var d = ""; + for (var i = 0;i < this.commands.length; i += 1) { + var cmd = this.commands[i]; + if (cmd.type === "M") { + d += "M" + packValues(cmd.x, cmd.y); + } else if (cmd.type === "L") { + d += "L" + packValues(cmd.x, cmd.y); + } else if (cmd.type === "C") { + d += "C" + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === "Q") { + d += "Q" + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y); + } else if (cmd.type === "Z") { + d += "Z"; + } + } + return d; +}; +Path2.prototype.toSVG = function(decimalPlaces) { + var svg = '= 0 && v <= 255, "Byte value should be between 0 and 255."); + return [v]; +}; +sizeOf.BYTE = constant(1); +encode.CHAR = function(v) { + return [v.charCodeAt(0)]; +}; +sizeOf.CHAR = constant(1); +encode.CHARARRAY = function(v) { + if (typeof v === "undefined") { + v = ""; + console.warn("Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name."); + } + var b = []; + for (var i = 0;i < v.length; i += 1) { + b[i] = v.charCodeAt(i); + } + return b; +}; +sizeOf.CHARARRAY = function(v) { + if (typeof v === "undefined") { + return 0; + } + return v.length; +}; +encode.USHORT = function(v) { + return [v >> 8 & 255, v & 255]; +}; +sizeOf.USHORT = constant(2); +encode.SHORT = function(v) { + if (v >= LIMIT16) { + v = -(2 * LIMIT16 - v); + } + return [v >> 8 & 255, v & 255]; +}; +sizeOf.SHORT = constant(2); +encode.UINT24 = function(v) { + return [v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.UINT24 = constant(3); +encode.ULONG = function(v) { + return [v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.ULONG = constant(4); +encode.LONG = function(v) { + if (v >= LIMIT32) { + v = -(2 * LIMIT32 - v); + } + return [v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.LONG = constant(4); +encode.FIXED = encode.ULONG; +sizeOf.FIXED = sizeOf.ULONG; +encode.FWORD = encode.SHORT; +sizeOf.FWORD = sizeOf.SHORT; +encode.UFWORD = encode.USHORT; +sizeOf.UFWORD = sizeOf.USHORT; +encode.LONGDATETIME = function(v) { + return [0, 0, 0, 0, v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.LONGDATETIME = constant(8); +encode.TAG = function(v) { + check.argument(v.length === 4, "Tag should be exactly 4 ASCII characters."); + return [ + v.charCodeAt(0), + v.charCodeAt(1), + v.charCodeAt(2), + v.charCodeAt(3) + ]; +}; +sizeOf.TAG = constant(4); +encode.Card8 = encode.BYTE; +sizeOf.Card8 = sizeOf.BYTE; +encode.Card16 = encode.USHORT; +sizeOf.Card16 = sizeOf.USHORT; +encode.OffSize = encode.BYTE; +sizeOf.OffSize = sizeOf.BYTE; +encode.SID = encode.USHORT; +sizeOf.SID = sizeOf.USHORT; +encode.NUMBER = function(v) { + if (v >= -107 && v <= 107) { + return [v + 139]; + } else if (v >= 108 && v <= 1131) { + v = v - 108; + return [(v >> 8) + 247, v & 255]; + } else if (v >= -1131 && v <= -108) { + v = -v - 108; + return [(v >> 8) + 251, v & 255]; + } else if (v >= -32768 && v <= 32767) { + return encode.NUMBER16(v); + } else { + return encode.NUMBER32(v); + } +}; +sizeOf.NUMBER = function(v) { + return encode.NUMBER(v).length; +}; +encode.NUMBER16 = function(v) { + return [28, v >> 8 & 255, v & 255]; +}; +sizeOf.NUMBER16 = constant(3); +encode.NUMBER32 = function(v) { + return [29, v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.NUMBER32 = constant(5); +encode.REAL = function(v) { + var value2 = v.toString(); + var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value2); + if (m) { + var epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length)); + value2 = (Math.round(v * epsilon) / epsilon).toString(); + } + var nibbles = ""; + for (var i = 0, ii = value2.length;i < ii; i += 1) { + var c = value2[i]; + if (c === "e") { + nibbles += value2[++i] === "-" ? "c" : "b"; + } else if (c === ".") { + nibbles += "a"; + } else if (c === "-") { + nibbles += "e"; + } else { + nibbles += c; + } + } + nibbles += nibbles.length & 1 ? "f" : "ff"; + var out = [30]; + for (var i$1 = 0, ii$1 = nibbles.length;i$1 < ii$1; i$1 += 2) { + out.push(parseInt(nibbles.substr(i$1, 2), 16)); + } + return out; +}; +sizeOf.REAL = function(v) { + return encode.REAL(v).length; +}; +encode.NAME = encode.CHARARRAY; +sizeOf.NAME = sizeOf.CHARARRAY; +encode.STRING = encode.CHARARRAY; +sizeOf.STRING = sizeOf.CHARARRAY; +decode.UTF8 = function(data2, offset, numBytes) { + var codePoints = []; + var numChars = numBytes; + for (var j2 = 0;j2 < numChars; j2++, offset += 1) { + codePoints[j2] = data2.getUint8(offset); + } + return String.fromCharCode.apply(null, codePoints); +}; +decode.UTF16 = function(data2, offset, numBytes) { + var codePoints = []; + var numChars = numBytes / 2; + for (var j2 = 0;j2 < numChars; j2++, offset += 2) { + codePoints[j2] = data2.getUint16(offset); + } + return String.fromCharCode.apply(null, codePoints); +}; +encode.UTF16 = function(v) { + var b = []; + for (var i = 0;i < v.length; i += 1) { + var codepoint = v.charCodeAt(i); + b[b.length] = codepoint >> 8 & 255; + b[b.length] = codepoint & 255; + } + return b; +}; +sizeOf.UTF16 = function(v) { + return v.length * 2; +}; +var eightBitMacEncodings = { + "x-mac-croatian": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø" + "¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ", + "x-mac-cyrillic": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ" + "јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю", + "x-mac-gaelic": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø" + "ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ", + "x-mac-greek": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ" + "άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­", + "x-mac-icelandic": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø" + "¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", + "x-mac-inuit": "ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ" + "ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł", + "x-mac-ce": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ" + "ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ", + macintosh: "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø" + "¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", + "x-mac-romanian": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș" + "¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", + "x-mac-turkish": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø" + "¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ" +}; +decode.MACSTRING = function(dataView, offset, dataLength, encoding) { + var table = eightBitMacEncodings[encoding]; + if (table === undefined) { + return; + } + var result = ""; + for (var i = 0;i < dataLength; i++) { + var c = dataView.getUint8(offset + i); + if (c <= 127) { + result += String.fromCharCode(c); + } else { + result += table[c & 127]; + } + } + return result; +}; +var macEncodingTableCache = typeof WeakMap === "function" && new WeakMap; +var macEncodingCacheKeys; +var getMacEncodingTable = function(encoding) { + if (!macEncodingCacheKeys) { + macEncodingCacheKeys = {}; + for (var e in eightBitMacEncodings) { + macEncodingCacheKeys[e] = new String(e); + } + } + var cacheKey = macEncodingCacheKeys[encoding]; + if (cacheKey === undefined) { + return; + } + if (macEncodingTableCache) { + var cachedTable = macEncodingTableCache.get(cacheKey); + if (cachedTable !== undefined) { + return cachedTable; + } + } + var decodingTable = eightBitMacEncodings[encoding]; + if (decodingTable === undefined) { + return; + } + var encodingTable = {}; + for (var i = 0;i < decodingTable.length; i++) { + encodingTable[decodingTable.charCodeAt(i)] = i + 128; + } + if (macEncodingTableCache) { + macEncodingTableCache.set(cacheKey, encodingTable); + } + return encodingTable; +}; +encode.MACSTRING = function(str, encoding) { + var table = getMacEncodingTable(encoding); + if (table === undefined) { + return; + } + var result = []; + for (var i = 0;i < str.length; i++) { + var c = str.charCodeAt(i); + if (c >= 128) { + c = table[c]; + if (c === undefined) { + return; + } + } + result[i] = c; + } + return result; +}; +sizeOf.MACSTRING = function(str, encoding) { + var b = encode.MACSTRING(str, encoding); + if (b !== undefined) { + return b.length; + } else { + return 0; + } +}; +function isByteEncodable(value2) { + return value2 >= -128 && value2 <= 127; +} +function encodeVarDeltaRunAsZeroes(deltas, pos, result) { + var runLength = 0; + var numDeltas = deltas.length; + while (pos < numDeltas && runLength < 64 && deltas[pos] === 0) { + ++pos; + ++runLength; + } + result.push(128 | runLength - 1); + return pos; +} +function encodeVarDeltaRunAsBytes(deltas, offset, result) { + var runLength = 0; + var numDeltas = deltas.length; + var pos = offset; + while (pos < numDeltas && runLength < 64) { + var value2 = deltas[pos]; + if (!isByteEncodable(value2)) { + break; + } + if (value2 === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) { + break; + } + ++pos; + ++runLength; + } + result.push(runLength - 1); + for (var i = offset;i < pos; ++i) { + result.push(deltas[i] + 256 & 255); + } + return pos; +} +function encodeVarDeltaRunAsWords(deltas, offset, result) { + var runLength = 0; + var numDeltas = deltas.length; + var pos = offset; + while (pos < numDeltas && runLength < 64) { + var value2 = deltas[pos]; + if (value2 === 0) { + break; + } + if (isByteEncodable(value2) && pos + 1 < numDeltas && isByteEncodable(deltas[pos + 1])) { + break; + } + ++pos; + ++runLength; + } + result.push(64 | runLength - 1); + for (var i = offset;i < pos; ++i) { + var val2 = deltas[i]; + result.push(val2 + 65536 >> 8 & 255, val2 + 256 & 255); + } + return pos; +} +encode.VARDELTAS = function(deltas) { + var pos = 0; + var result = []; + while (pos < deltas.length) { + var value2 = deltas[pos]; + if (value2 === 0) { + pos = encodeVarDeltaRunAsZeroes(deltas, pos, result); + } else if (value2 >= -128 && value2 <= 127) { + pos = encodeVarDeltaRunAsBytes(deltas, pos, result); + } else { + pos = encodeVarDeltaRunAsWords(deltas, pos, result); + } + } + return result; +}; +encode.INDEX = function(l2) { + var offset = 1; + var offsets = [offset]; + var data2 = []; + for (var i = 0;i < l2.length; i += 1) { + var v = encode.OBJECT(l2[i]); + Array.prototype.push.apply(data2, v); + offset += v.length; + offsets.push(offset); + } + if (data2.length === 0) { + return [0, 0]; + } + var encodedOffsets = []; + var offSize = 1 + Math.floor(Math.log(offset) / Math.log(2)) / 8 | 0; + var offsetEncoder = [undefined, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize]; + for (var i$1 = 0;i$1 < offsets.length; i$1 += 1) { + var encodedOffset = offsetEncoder(offsets[i$1]); + Array.prototype.push.apply(encodedOffsets, encodedOffset); + } + return Array.prototype.concat(encode.Card16(l2.length), encode.OffSize(offSize), encodedOffsets, data2); +}; +sizeOf.INDEX = function(v) { + return encode.INDEX(v).length; +}; +encode.DICT = function(m) { + var d = []; + var keys2 = Object.keys(m); + var length2 = keys2.length; + for (var i = 0;i < length2; i += 1) { + var k2 = parseInt(keys2[i], 0); + var v = m[k2]; + d = d.concat(encode.OPERAND(v.value, v.type)); + d = d.concat(encode.OPERATOR(k2)); + } + return d; +}; +sizeOf.DICT = function(m) { + return encode.DICT(m).length; +}; +encode.OPERATOR = function(v) { + if (v < 1200) { + return [v]; + } else { + return [12, v - 1200]; + } +}; +encode.OPERAND = function(v, type) { + var d = []; + if (Array.isArray(type)) { + for (var i = 0;i < type.length; i += 1) { + check.argument(v.length === type.length, "Not enough arguments given for type" + type); + d = d.concat(encode.OPERAND(v[i], type[i])); + } + } else { + if (type === "SID") { + d = d.concat(encode.NUMBER(v)); + } else if (type === "offset") { + d = d.concat(encode.NUMBER32(v)); + } else if (type === "number") { + d = d.concat(encode.NUMBER(v)); + } else if (type === "real") { + d = d.concat(encode.REAL(v)); + } else { + throw new Error("Unknown operand type " + type); + } + } + return d; +}; +encode.OP = encode.BYTE; +sizeOf.OP = sizeOf.BYTE; +var wmm = typeof WeakMap === "function" && new WeakMap; +encode.CHARSTRING = function(ops) { + if (wmm) { + var cachedValue = wmm.get(ops); + if (cachedValue !== undefined) { + return cachedValue; + } + } + var d = []; + var length2 = ops.length; + for (var i = 0;i < length2; i += 1) { + var op = ops[i]; + d = d.concat(encode[op.type](op.value)); + } + if (wmm) { + wmm.set(ops, d); + } + return d; +}; +sizeOf.CHARSTRING = function(ops) { + return encode.CHARSTRING(ops).length; +}; +encode.OBJECT = function(v) { + var encodingFunction = encode[v.type]; + check.argument(encodingFunction !== undefined, "No encoding function for type " + v.type); + return encodingFunction(v.value); +}; +sizeOf.OBJECT = function(v) { + var sizeOfFunction = sizeOf[v.type]; + check.argument(sizeOfFunction !== undefined, "No sizeOf function for type " + v.type); + return sizeOfFunction(v.value); +}; +encode.TABLE = function(table) { + var d = []; + var length2 = table.fields.length; + var subtables = []; + var subtableOffsets = []; + for (var i = 0;i < length2; i += 1) { + var field = table.fields[i]; + var encodingFunction = encode[field.type]; + check.argument(encodingFunction !== undefined, "No encoding function for field type " + field.type + " (" + field.name + ")"); + var value2 = table[field.name]; + if (value2 === undefined) { + value2 = field.value; + } + var bytes = encodingFunction(value2); + if (field.type === "TABLE") { + subtableOffsets.push(d.length); + d = d.concat([0, 0]); + subtables.push(bytes); + } else { + d = d.concat(bytes); + } + } + for (var i$1 = 0;i$1 < subtables.length; i$1 += 1) { + var o = subtableOffsets[i$1]; + var offset = d.length; + check.argument(offset < 65536, "Table " + table.tableName + " too big."); + d[o] = offset >> 8; + d[o + 1] = offset & 255; + d = d.concat(subtables[i$1]); + } + return d; +}; +sizeOf.TABLE = function(table) { + var numBytes = 0; + var length2 = table.fields.length; + for (var i = 0;i < length2; i += 1) { + var field = table.fields[i]; + var sizeOfFunction = sizeOf[field.type]; + check.argument(sizeOfFunction !== undefined, "No sizeOf function for field type " + field.type + " (" + field.name + ")"); + var value2 = table[field.name]; + if (value2 === undefined) { + value2 = field.value; + } + numBytes += sizeOfFunction(value2); + if (field.type === "TABLE") { + numBytes += 2; + } + } + return numBytes; +}; +encode.RECORD = encode.TABLE; +sizeOf.RECORD = sizeOf.TABLE; +encode.LITERAL = function(v) { + return v; +}; +sizeOf.LITERAL = function(v) { + return v.length; +}; +function Table(tableName, fields, options) { + if (fields.length && (fields[0].name !== "coverageFormat" || fields[0].value === 1)) { + for (var i = 0;i < fields.length; i += 1) { + var field = fields[i]; + this[field.name] = field.value; + } + } + this.tableName = tableName; + this.fields = fields; + if (options) { + var optionKeys = Object.keys(options); + for (var i$1 = 0;i$1 < optionKeys.length; i$1 += 1) { + var k2 = optionKeys[i$1]; + var v = options[k2]; + if (this[k2] !== undefined) { + this[k2] = v; + } + } + } +} +Table.prototype.encode = function() { + return encode.TABLE(this); +}; +Table.prototype.sizeOf = function() { + return sizeOf.TABLE(this); +}; +function ushortList(itemName, list, count) { + if (count === undefined) { + count = list.length; + } + var fields = new Array(list.length + 1); + fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; + for (var i = 0;i < list.length; i++) { + fields[i + 1] = { name: itemName + i, type: "USHORT", value: list[i] }; + } + return fields; +} +function tableList(itemName, records, itemCallback) { + var count = records.length; + var fields = new Array(count + 1); + fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; + for (var i = 0;i < count; i++) { + fields[i + 1] = { name: itemName + i, type: "TABLE", value: itemCallback(records[i], i) }; + } + return fields; +} +function recordList(itemName, records, itemCallback) { + var count = records.length; + var fields = []; + fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; + for (var i = 0;i < count; i++) { + fields = fields.concat(itemCallback(records[i], i)); + } + return fields; +} +function Coverage(coverageTable) { + if (coverageTable.format === 1) { + Table.call(this, "coverageTable", [{ name: "coverageFormat", type: "USHORT", value: 1 }].concat(ushortList("glyph", coverageTable.glyphs))); + } else if (coverageTable.format === 2) { + Table.call(this, "coverageTable", [{ name: "coverageFormat", type: "USHORT", value: 2 }].concat(recordList("rangeRecord", coverageTable.ranges, function(RangeRecord) { + return [ + { name: "startGlyphID", type: "USHORT", value: RangeRecord.start }, + { name: "endGlyphID", type: "USHORT", value: RangeRecord.end }, + { name: "startCoverageIndex", type: "USHORT", value: RangeRecord.index } + ]; + }))); + } else { + check.assert(false, "Coverage format must be 1 or 2."); + } +} +Coverage.prototype = Object.create(Table.prototype); +Coverage.prototype.constructor = Coverage; +function ScriptList(scriptListTable) { + Table.call(this, "scriptListTable", recordList("scriptRecord", scriptListTable, function(scriptRecord, i) { + var script = scriptRecord.script; + var defaultLangSys = script.defaultLangSys; + check.assert(!!defaultLangSys, "Unable to write GSUB: script " + scriptRecord.tag + " has no default language system."); + return [ + { name: "scriptTag" + i, type: "TAG", value: scriptRecord.tag }, + { name: "script" + i, type: "TABLE", value: new Table("scriptTable", [ + { name: "defaultLangSys", type: "TABLE", value: new Table("defaultLangSys", [ + { name: "lookupOrder", type: "USHORT", value: 0 }, + { name: "reqFeatureIndex", type: "USHORT", value: defaultLangSys.reqFeatureIndex } + ].concat(ushortList("featureIndex", defaultLangSys.featureIndexes))) } + ].concat(recordList("langSys", script.langSysRecords, function(langSysRecord, i2) { + var langSys = langSysRecord.langSys; + return [ + { name: "langSysTag" + i2, type: "TAG", value: langSysRecord.tag }, + { name: "langSys" + i2, type: "TABLE", value: new Table("langSys", [ + { name: "lookupOrder", type: "USHORT", value: 0 }, + { name: "reqFeatureIndex", type: "USHORT", value: langSys.reqFeatureIndex } + ].concat(ushortList("featureIndex", langSys.featureIndexes))) } + ]; + }))) } + ]; + })); +} +ScriptList.prototype = Object.create(Table.prototype); +ScriptList.prototype.constructor = ScriptList; +function FeatureList(featureListTable) { + Table.call(this, "featureListTable", recordList("featureRecord", featureListTable, function(featureRecord, i) { + var feature = featureRecord.feature; + return [ + { name: "featureTag" + i, type: "TAG", value: featureRecord.tag }, + { name: "feature" + i, type: "TABLE", value: new Table("featureTable", [ + { name: "featureParams", type: "USHORT", value: feature.featureParams } + ].concat(ushortList("lookupListIndex", feature.lookupListIndexes))) } + ]; + })); +} +FeatureList.prototype = Object.create(Table.prototype); +FeatureList.prototype.constructor = FeatureList; +function LookupList(lookupListTable, subtableMakers) { + Table.call(this, "lookupListTable", tableList("lookup", lookupListTable, function(lookupTable) { + var subtableCallback = subtableMakers[lookupTable.lookupType]; + check.assert(!!subtableCallback, "Unable to write GSUB lookup type " + lookupTable.lookupType + " tables."); + return new Table("lookupTable", [ + { name: "lookupType", type: "USHORT", value: lookupTable.lookupType }, + { name: "lookupFlag", type: "USHORT", value: lookupTable.lookupFlag } + ].concat(tableList("subtable", lookupTable.subtables, subtableCallback))); + })); +} +LookupList.prototype = Object.create(Table.prototype); +LookupList.prototype.constructor = LookupList; +var table = { + Table, + Record: Table, + Coverage, + ScriptList, + FeatureList, + LookupList, + ushortList, + tableList, + recordList +}; +function getByte(dataView, offset) { + return dataView.getUint8(offset); +} +function getUShort(dataView, offset) { + return dataView.getUint16(offset, false); +} +function getShort(dataView, offset) { + return dataView.getInt16(offset, false); +} +function getULong(dataView, offset) { + return dataView.getUint32(offset, false); +} +function getFixed(dataView, offset) { + var decimal = dataView.getInt16(offset, false); + var fraction = dataView.getUint16(offset + 2, false); + return decimal + fraction / 65535; +} +function getTag(dataView, offset) { + var tag = ""; + for (var i = offset;i < offset + 4; i += 1) { + tag += String.fromCharCode(dataView.getInt8(i)); + } + return tag; +} +function getOffset(dataView, offset, offSize) { + var v = 0; + for (var i = 0;i < offSize; i += 1) { + v <<= 8; + v += dataView.getUint8(offset + i); + } + return v; +} +function getBytes(dataView, startOffset, endOffset) { + var bytes = []; + for (var i = startOffset;i < endOffset; i += 1) { + bytes.push(dataView.getUint8(i)); + } + return bytes; +} +function bytesToString(bytes) { + var s = ""; + for (var i = 0;i < bytes.length; i += 1) { + s += String.fromCharCode(bytes[i]); + } + return s; +} +var typeOffsets = { + byte: 1, + uShort: 2, + short: 2, + uLong: 4, + fixed: 4, + longDateTime: 8, + tag: 4 +}; +function Parser(data2, offset) { + this.data = data2; + this.offset = offset; + this.relativeOffset = 0; +} +Parser.prototype.parseByte = function() { + var v = this.data.getUint8(this.offset + this.relativeOffset); + this.relativeOffset += 1; + return v; +}; +Parser.prototype.parseChar = function() { + var v = this.data.getInt8(this.offset + this.relativeOffset); + this.relativeOffset += 1; + return v; +}; +Parser.prototype.parseCard8 = Parser.prototype.parseByte; +Parser.prototype.parseUShort = function() { + var v = this.data.getUint16(this.offset + this.relativeOffset); + this.relativeOffset += 2; + return v; +}; +Parser.prototype.parseCard16 = Parser.prototype.parseUShort; +Parser.prototype.parseSID = Parser.prototype.parseUShort; +Parser.prototype.parseOffset16 = Parser.prototype.parseUShort; +Parser.prototype.parseShort = function() { + var v = this.data.getInt16(this.offset + this.relativeOffset); + this.relativeOffset += 2; + return v; +}; +Parser.prototype.parseF2Dot14 = function() { + var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384; + this.relativeOffset += 2; + return v; +}; +Parser.prototype.parseULong = function() { + var v = getULong(this.data, this.offset + this.relativeOffset); + this.relativeOffset += 4; + return v; +}; +Parser.prototype.parseOffset32 = Parser.prototype.parseULong; +Parser.prototype.parseFixed = function() { + var v = getFixed(this.data, this.offset + this.relativeOffset); + this.relativeOffset += 4; + return v; +}; +Parser.prototype.parseString = function(length2) { + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + var string = ""; + this.relativeOffset += length2; + for (var i = 0;i < length2; i++) { + string += String.fromCharCode(dataView.getUint8(offset + i)); + } + return string; +}; +Parser.prototype.parseTag = function() { + return this.parseString(4); +}; +Parser.prototype.parseLongDateTime = function() { + var v = getULong(this.data, this.offset + this.relativeOffset + 4); + v -= 2082844800; + this.relativeOffset += 8; + return v; +}; +Parser.prototype.parseVersion = function(minorBase) { + var major = getUShort(this.data, this.offset + this.relativeOffset); + var minor = getUShort(this.data, this.offset + this.relativeOffset + 2); + this.relativeOffset += 4; + if (minorBase === undefined) { + minorBase = 4096; + } + return major + minor / minorBase / 10; +}; +Parser.prototype.skip = function(type, amount) { + if (amount === undefined) { + amount = 1; + } + this.relativeOffset += typeOffsets[type] * amount; +}; +Parser.prototype.parseULongList = function(count) { + if (count === undefined) { + count = this.parseULong(); + } + var offsets = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0;i < count; i++) { + offsets[i] = dataView.getUint32(offset); + offset += 4; + } + this.relativeOffset += count * 4; + return offsets; +}; +Parser.prototype.parseOffset16List = Parser.prototype.parseUShortList = function(count) { + if (count === undefined) { + count = this.parseUShort(); + } + var offsets = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0;i < count; i++) { + offsets[i] = dataView.getUint16(offset); + offset += 2; + } + this.relativeOffset += count * 2; + return offsets; +}; +Parser.prototype.parseShortList = function(count) { + var list = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0;i < count; i++) { + list[i] = dataView.getInt16(offset); + offset += 2; + } + this.relativeOffset += count * 2; + return list; +}; +Parser.prototype.parseByteList = function(count) { + var list = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0;i < count; i++) { + list[i] = dataView.getUint8(offset++); + } + this.relativeOffset += count; + return list; +}; +Parser.prototype.parseList = function(count, itemCallback) { + if (!itemCallback) { + itemCallback = count; + count = this.parseUShort(); + } + var list = new Array(count); + for (var i = 0;i < count; i++) { + list[i] = itemCallback.call(this); + } + return list; +}; +Parser.prototype.parseList32 = function(count, itemCallback) { + if (!itemCallback) { + itemCallback = count; + count = this.parseULong(); + } + var list = new Array(count); + for (var i = 0;i < count; i++) { + list[i] = itemCallback.call(this); + } + return list; +}; +Parser.prototype.parseRecordList = function(count, recordDescription) { + if (!recordDescription) { + recordDescription = count; + count = this.parseUShort(); + } + var records = new Array(count); + var fields = Object.keys(recordDescription); + for (var i = 0;i < count; i++) { + var rec = {}; + for (var j2 = 0;j2 < fields.length; j2++) { + var fieldName = fields[j2]; + var fieldType = recordDescription[fieldName]; + rec[fieldName] = fieldType.call(this); + } + records[i] = rec; + } + return records; +}; +Parser.prototype.parseRecordList32 = function(count, recordDescription) { + if (!recordDescription) { + recordDescription = count; + count = this.parseULong(); + } + var records = new Array(count); + var fields = Object.keys(recordDescription); + for (var i = 0;i < count; i++) { + var rec = {}; + for (var j2 = 0;j2 < fields.length; j2++) { + var fieldName = fields[j2]; + var fieldType = recordDescription[fieldName]; + rec[fieldName] = fieldType.call(this); + } + records[i] = rec; + } + return records; +}; +Parser.prototype.parseStruct = function(description) { + if (typeof description === "function") { + return description.call(this); + } else { + var fields = Object.keys(description); + var struct = {}; + for (var j2 = 0;j2 < fields.length; j2++) { + var fieldName = fields[j2]; + var fieldType = description[fieldName]; + struct[fieldName] = fieldType.call(this); + } + return struct; + } +}; +Parser.prototype.parseValueRecord = function(valueFormat) { + if (valueFormat === undefined) { + valueFormat = this.parseUShort(); + } + if (valueFormat === 0) { + return; + } + var valueRecord = {}; + if (valueFormat & 1) { + valueRecord.xPlacement = this.parseShort(); + } + if (valueFormat & 2) { + valueRecord.yPlacement = this.parseShort(); + } + if (valueFormat & 4) { + valueRecord.xAdvance = this.parseShort(); + } + if (valueFormat & 8) { + valueRecord.yAdvance = this.parseShort(); + } + if (valueFormat & 16) { + valueRecord.xPlaDevice = undefined; + this.parseShort(); + } + if (valueFormat & 32) { + valueRecord.yPlaDevice = undefined; + this.parseShort(); + } + if (valueFormat & 64) { + valueRecord.xAdvDevice = undefined; + this.parseShort(); + } + if (valueFormat & 128) { + valueRecord.yAdvDevice = undefined; + this.parseShort(); + } + return valueRecord; +}; +Parser.prototype.parseValueRecordList = function() { + var valueFormat = this.parseUShort(); + var valueCount = this.parseUShort(); + var values2 = new Array(valueCount); + for (var i = 0;i < valueCount; i++) { + values2[i] = this.parseValueRecord(valueFormat); + } + return values2; +}; +Parser.prototype.parsePointer = function(description) { + var structOffset = this.parseOffset16(); + if (structOffset > 0) { + return new Parser(this.data, this.offset + structOffset).parseStruct(description); + } + return; +}; +Parser.prototype.parsePointer32 = function(description) { + var structOffset = this.parseOffset32(); + if (structOffset > 0) { + return new Parser(this.data, this.offset + structOffset).parseStruct(description); + } + return; +}; +Parser.prototype.parseListOfLists = function(itemCallback) { + var offsets = this.parseOffset16List(); + var count = offsets.length; + var relativeOffset = this.relativeOffset; + var list = new Array(count); + for (var i = 0;i < count; i++) { + var start = offsets[i]; + if (start === 0) { + list[i] = undefined; + continue; + } + this.relativeOffset = start; + if (itemCallback) { + var subOffsets = this.parseOffset16List(); + var subList = new Array(subOffsets.length); + for (var j2 = 0;j2 < subOffsets.length; j2++) { + this.relativeOffset = start + subOffsets[j2]; + subList[j2] = itemCallback.call(this); + } + list[i] = subList; + } else { + list[i] = this.parseUShortList(); + } + } + this.relativeOffset = relativeOffset; + return list; +}; +Parser.prototype.parseCoverage = function() { + var startOffset = this.offset + this.relativeOffset; + var format = this.parseUShort(); + var count = this.parseUShort(); + if (format === 1) { + return { + format: 1, + glyphs: this.parseUShortList(count) + }; + } else if (format === 2) { + var ranges = new Array(count); + for (var i = 0;i < count; i++) { + ranges[i] = { + start: this.parseUShort(), + end: this.parseUShort(), + index: this.parseUShort() + }; + } + return { + format: 2, + ranges + }; + } + throw new Error("0x" + startOffset.toString(16) + ": Coverage format must be 1 or 2."); +}; +Parser.prototype.parseClassDef = function() { + var startOffset = this.offset + this.relativeOffset; + var format = this.parseUShort(); + if (format === 1) { + return { + format: 1, + startGlyph: this.parseUShort(), + classes: this.parseUShortList() + }; + } else if (format === 2) { + return { + format: 2, + ranges: this.parseRecordList({ + start: Parser.uShort, + end: Parser.uShort, + classId: Parser.uShort + }) + }; + } + throw new Error("0x" + startOffset.toString(16) + ": ClassDef format must be 1 or 2."); +}; +Parser.list = function(count, itemCallback) { + return function() { + return this.parseList(count, itemCallback); + }; +}; +Parser.list32 = function(count, itemCallback) { + return function() { + return this.parseList32(count, itemCallback); + }; +}; +Parser.recordList = function(count, recordDescription) { + return function() { + return this.parseRecordList(count, recordDescription); + }; +}; +Parser.recordList32 = function(count, recordDescription) { + return function() { + return this.parseRecordList32(count, recordDescription); + }; +}; +Parser.pointer = function(description) { + return function() { + return this.parsePointer(description); + }; +}; +Parser.pointer32 = function(description) { + return function() { + return this.parsePointer32(description); + }; +}; +Parser.tag = Parser.prototype.parseTag; +Parser.byte = Parser.prototype.parseByte; +Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort; +Parser.uShortList = Parser.prototype.parseUShortList; +Parser.uLong = Parser.offset32 = Parser.prototype.parseULong; +Parser.uLongList = Parser.prototype.parseULongList; +Parser.struct = Parser.prototype.parseStruct; +Parser.coverage = Parser.prototype.parseCoverage; +Parser.classDef = Parser.prototype.parseClassDef; +var langSysTable = { + reserved: Parser.uShort, + reqFeatureIndex: Parser.uShort, + featureIndexes: Parser.uShortList +}; +Parser.prototype.parseScriptList = function() { + return this.parsePointer(Parser.recordList({ + tag: Parser.tag, + script: Parser.pointer({ + defaultLangSys: Parser.pointer(langSysTable), + langSysRecords: Parser.recordList({ + tag: Parser.tag, + langSys: Parser.pointer(langSysTable) + }) + }) + })) || []; +}; +Parser.prototype.parseFeatureList = function() { + return this.parsePointer(Parser.recordList({ + tag: Parser.tag, + feature: Parser.pointer({ + featureParams: Parser.offset16, + lookupListIndexes: Parser.uShortList + }) + })) || []; +}; +Parser.prototype.parseLookupList = function(lookupTableParsers) { + return this.parsePointer(Parser.list(Parser.pointer(function() { + var lookupType = this.parseUShort(); + check.argument(1 <= lookupType && lookupType <= 9, "GPOS/GSUB lookup type " + lookupType + " unknown."); + var lookupFlag = this.parseUShort(); + var useMarkFilteringSet = lookupFlag & 16; + return { + lookupType, + lookupFlag, + subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])), + markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined + }; + }))) || []; +}; +Parser.prototype.parseFeatureVariationsList = function() { + return this.parsePointer32(function() { + var majorVersion = this.parseUShort(); + var minorVersion = this.parseUShort(); + check.argument(majorVersion === 1 && minorVersion < 1, "GPOS/GSUB feature variations table unknown."); + var featureVariations = this.parseRecordList32({ + conditionSetOffset: Parser.offset32, + featureTableSubstitutionOffset: Parser.offset32 + }); + return featureVariations; + }) || []; +}; +var parse = { + getByte, + getCard8: getByte, + getUShort, + getCard16: getUShort, + getShort, + getULong, + getFixed, + getTag, + getOffset, + getBytes, + bytesToString, + Parser +}; +function parseCmapTableFormat12(cmap, p) { + p.parseUShort(); + cmap.length = p.parseULong(); + cmap.language = p.parseULong(); + var groupCount; + cmap.groupCount = groupCount = p.parseULong(); + cmap.glyphIndexMap = {}; + for (var i = 0;i < groupCount; i += 1) { + var startCharCode = p.parseULong(); + var endCharCode = p.parseULong(); + var startGlyphId = p.parseULong(); + for (var c = startCharCode;c <= endCharCode; c += 1) { + cmap.glyphIndexMap[c] = startGlyphId; + startGlyphId++; + } + } +} +function parseCmapTableFormat4(cmap, p, data2, start, offset) { + cmap.length = p.parseUShort(); + cmap.language = p.parseUShort(); + var segCount; + cmap.segCount = segCount = p.parseUShort() >> 1; + p.skip("uShort", 3); + cmap.glyphIndexMap = {}; + var endCountParser = new parse.Parser(data2, start + offset + 14); + var startCountParser = new parse.Parser(data2, start + offset + 16 + segCount * 2); + var idDeltaParser = new parse.Parser(data2, start + offset + 16 + segCount * 4); + var idRangeOffsetParser = new parse.Parser(data2, start + offset + 16 + segCount * 6); + var glyphIndexOffset = start + offset + 16 + segCount * 8; + for (var i = 0;i < segCount - 1; i += 1) { + var glyphIndex = undefined; + var endCount = endCountParser.parseUShort(); + var startCount = startCountParser.parseUShort(); + var idDelta = idDeltaParser.parseShort(); + var idRangeOffset = idRangeOffsetParser.parseUShort(); + for (var c = startCount;c <= endCount; c += 1) { + if (idRangeOffset !== 0) { + glyphIndexOffset = idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2; + glyphIndexOffset += idRangeOffset; + glyphIndexOffset += (c - startCount) * 2; + glyphIndex = parse.getUShort(data2, glyphIndexOffset); + if (glyphIndex !== 0) { + glyphIndex = glyphIndex + idDelta & 65535; + } + } else { + glyphIndex = c + idDelta & 65535; + } + cmap.glyphIndexMap[c] = glyphIndex; + } + } +} +function parseCmapTable(data2, start) { + var cmap = {}; + cmap.version = parse.getUShort(data2, start); + check.argument(cmap.version === 0, "cmap table version should be 0."); + cmap.numTables = parse.getUShort(data2, start + 2); + var offset = -1; + for (var i = cmap.numTables - 1;i >= 0; i -= 1) { + var platformId = parse.getUShort(data2, start + 4 + i * 8); + var encodingId = parse.getUShort(data2, start + 4 + i * 8 + 2); + if (platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10) || platformId === 0 && (encodingId === 0 || encodingId === 1 || encodingId === 2 || encodingId === 3 || encodingId === 4)) { + offset = parse.getULong(data2, start + 4 + i * 8 + 4); + break; + } + } + if (offset === -1) { + throw new Error("No valid cmap sub-tables found."); + } + var p = new parse.Parser(data2, start + offset); + cmap.format = p.parseUShort(); + if (cmap.format === 12) { + parseCmapTableFormat12(cmap, p); + } else if (cmap.format === 4) { + parseCmapTableFormat4(cmap, p, data2, start, offset); + } else { + throw new Error("Only format 4 and 12 cmap tables are supported (found format " + cmap.format + ")."); + } + return cmap; +} +function addSegment(t2, code, glyphIndex) { + t2.segments.push({ + end: code, + start: code, + delta: -(code - glyphIndex), + offset: 0, + glyphIndex + }); +} +function addTerminatorSegment(t2) { + t2.segments.push({ + end: 65535, + start: 65535, + delta: 1, + offset: 0 + }); +} +function makeCmapTable(glyphs) { + var isPlan0Only = true; + var i; + for (i = glyphs.length - 1;i > 0; i -= 1) { + var g3 = glyphs.get(i); + if (g3.unicode > 65535) { + console.log("Adding CMAP format 12 (needed!)"); + isPlan0Only = false; + break; + } + } + var cmapTable = [ + { name: "version", type: "USHORT", value: 0 }, + { name: "numTables", type: "USHORT", value: isPlan0Only ? 1 : 2 }, + { name: "platformID", type: "USHORT", value: 3 }, + { name: "encodingID", type: "USHORT", value: 1 }, + { name: "offset", type: "ULONG", value: isPlan0Only ? 12 : 12 + 8 } + ]; + if (!isPlan0Only) { + cmapTable = cmapTable.concat([ + { name: "cmap12PlatformID", type: "USHORT", value: 3 }, + { name: "cmap12EncodingID", type: "USHORT", value: 10 }, + { name: "cmap12Offset", type: "ULONG", value: 0 } + ]); + } + cmapTable = cmapTable.concat([ + { name: "format", type: "USHORT", value: 4 }, + { name: "cmap4Length", type: "USHORT", value: 0 }, + { name: "language", type: "USHORT", value: 0 }, + { name: "segCountX2", type: "USHORT", value: 0 }, + { name: "searchRange", type: "USHORT", value: 0 }, + { name: "entrySelector", type: "USHORT", value: 0 }, + { name: "rangeShift", type: "USHORT", value: 0 } + ]); + var t2 = new table.Table("cmap", cmapTable); + t2.segments = []; + for (i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + for (var j2 = 0;j2 < glyph.unicodes.length; j2 += 1) { + addSegment(t2, glyph.unicodes[j2], i); + } + t2.segments = t2.segments.sort(function(a, b) { + return a.start - b.start; + }); + } + addTerminatorSegment(t2); + var segCount = t2.segments.length; + var segCountToRemove = 0; + var endCounts = []; + var startCounts = []; + var idDeltas = []; + var idRangeOffsets = []; + var glyphIds = []; + var cmap12Groups = []; + for (i = 0;i < segCount; i += 1) { + var segment = t2.segments[i]; + if (segment.end <= 65535 && segment.start <= 65535) { + endCounts = endCounts.concat({ name: "end_" + i, type: "USHORT", value: segment.end }); + startCounts = startCounts.concat({ name: "start_" + i, type: "USHORT", value: segment.start }); + idDeltas = idDeltas.concat({ name: "idDelta_" + i, type: "SHORT", value: segment.delta }); + idRangeOffsets = idRangeOffsets.concat({ name: "idRangeOffset_" + i, type: "USHORT", value: segment.offset }); + if (segment.glyphId !== undefined) { + glyphIds = glyphIds.concat({ name: "glyph_" + i, type: "USHORT", value: segment.glyphId }); + } + } else { + segCountToRemove += 1; + } + if (!isPlan0Only && segment.glyphIndex !== undefined) { + cmap12Groups = cmap12Groups.concat({ name: "cmap12Start_" + i, type: "ULONG", value: segment.start }); + cmap12Groups = cmap12Groups.concat({ name: "cmap12End_" + i, type: "ULONG", value: segment.end }); + cmap12Groups = cmap12Groups.concat({ name: "cmap12Glyph_" + i, type: "ULONG", value: segment.glyphIndex }); + } + } + t2.segCountX2 = (segCount - segCountToRemove) * 2; + t2.searchRange = Math.pow(2, Math.floor(Math.log(segCount - segCountToRemove) / Math.log(2))) * 2; + t2.entrySelector = Math.log(t2.searchRange / 2) / Math.log(2); + t2.rangeShift = t2.segCountX2 - t2.searchRange; + t2.fields = t2.fields.concat(endCounts); + t2.fields.push({ name: "reservedPad", type: "USHORT", value: 0 }); + t2.fields = t2.fields.concat(startCounts); + t2.fields = t2.fields.concat(idDeltas); + t2.fields = t2.fields.concat(idRangeOffsets); + t2.fields = t2.fields.concat(glyphIds); + t2.cmap4Length = 14 + endCounts.length * 2 + 2 + startCounts.length * 2 + idDeltas.length * 2 + idRangeOffsets.length * 2 + glyphIds.length * 2; + if (!isPlan0Only) { + var cmap12Length = 16 + cmap12Groups.length * 4; + t2.cmap12Offset = 12 + 2 * 2 + 4 + t2.cmap4Length; + t2.fields = t2.fields.concat([ + { name: "cmap12Format", type: "USHORT", value: 12 }, + { name: "cmap12Reserved", type: "USHORT", value: 0 }, + { name: "cmap12Length", type: "ULONG", value: cmap12Length }, + { name: "cmap12Language", type: "ULONG", value: 0 }, + { name: "cmap12nGroups", type: "ULONG", value: cmap12Groups.length / 3 } + ]); + t2.fields = t2.fields.concat(cmap12Groups); + } + return t2; +} +var cmap = { parse: parseCmapTable, make: makeCmapTable }; +var cffStandardStrings = [ + ".notdef", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quoteright", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "quoteleft", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "exclamdown", + "cent", + "sterling", + "fraction", + "yen", + "florin", + "section", + "currency", + "quotesingle", + "quotedblleft", + "guillemotleft", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "endash", + "dagger", + "daggerdbl", + "periodcentered", + "paragraph", + "bullet", + "quotesinglbase", + "quotedblbase", + "quotedblright", + "guillemotright", + "ellipsis", + "perthousand", + "questiondown", + "grave", + "acute", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "dieresis", + "ring", + "cedilla", + "hungarumlaut", + "ogonek", + "caron", + "emdash", + "AE", + "ordfeminine", + "Lslash", + "Oslash", + "OE", + "ordmasculine", + "ae", + "dotlessi", + "lslash", + "oslash", + "oe", + "germandbls", + "onesuperior", + "logicalnot", + "mu", + "trademark", + "Eth", + "onehalf", + "plusminus", + "Thorn", + "onequarter", + "divide", + "brokenbar", + "degree", + "thorn", + "threequarters", + "twosuperior", + "registered", + "minus", + "eth", + "multiply", + "threesuperior", + "copyright", + "Aacute", + "Acircumflex", + "Adieresis", + "Agrave", + "Aring", + "Atilde", + "Ccedilla", + "Eacute", + "Ecircumflex", + "Edieresis", + "Egrave", + "Iacute", + "Icircumflex", + "Idieresis", + "Igrave", + "Ntilde", + "Oacute", + "Ocircumflex", + "Odieresis", + "Ograve", + "Otilde", + "Scaron", + "Uacute", + "Ucircumflex", + "Udieresis", + "Ugrave", + "Yacute", + "Ydieresis", + "Zcaron", + "aacute", + "acircumflex", + "adieresis", + "agrave", + "aring", + "atilde", + "ccedilla", + "eacute", + "ecircumflex", + "edieresis", + "egrave", + "iacute", + "icircumflex", + "idieresis", + "igrave", + "ntilde", + "oacute", + "ocircumflex", + "odieresis", + "ograve", + "otilde", + "scaron", + "uacute", + "ucircumflex", + "udieresis", + "ugrave", + "yacute", + "ydieresis", + "zcaron", + "exclamsmall", + "Hungarumlautsmall", + "dollaroldstyle", + "dollarsuperior", + "ampersandsmall", + "Acutesmall", + "parenleftsuperior", + "parenrightsuperior", + "266 ff", + "onedotenleader", + "zerooldstyle", + "oneoldstyle", + "twooldstyle", + "threeoldstyle", + "fouroldstyle", + "fiveoldstyle", + "sixoldstyle", + "sevenoldstyle", + "eightoldstyle", + "nineoldstyle", + "commasuperior", + "threequartersemdash", + "periodsuperior", + "questionsmall", + "asuperior", + "bsuperior", + "centsuperior", + "dsuperior", + "esuperior", + "isuperior", + "lsuperior", + "msuperior", + "nsuperior", + "osuperior", + "rsuperior", + "ssuperior", + "tsuperior", + "ff", + "ffi", + "ffl", + "parenleftinferior", + "parenrightinferior", + "Circumflexsmall", + "hyphensuperior", + "Gravesmall", + "Asmall", + "Bsmall", + "Csmall", + "Dsmall", + "Esmall", + "Fsmall", + "Gsmall", + "Hsmall", + "Ismall", + "Jsmall", + "Ksmall", + "Lsmall", + "Msmall", + "Nsmall", + "Osmall", + "Psmall", + "Qsmall", + "Rsmall", + "Ssmall", + "Tsmall", + "Usmall", + "Vsmall", + "Wsmall", + "Xsmall", + "Ysmall", + "Zsmall", + "colonmonetary", + "onefitted", + "rupiah", + "Tildesmall", + "exclamdownsmall", + "centoldstyle", + "Lslashsmall", + "Scaronsmall", + "Zcaronsmall", + "Dieresissmall", + "Brevesmall", + "Caronsmall", + "Dotaccentsmall", + "Macronsmall", + "figuredash", + "hypheninferior", + "Ogoneksmall", + "Ringsmall", + "Cedillasmall", + "questiondownsmall", + "oneeighth", + "threeeighths", + "fiveeighths", + "seveneighths", + "onethird", + "twothirds", + "zerosuperior", + "foursuperior", + "fivesuperior", + "sixsuperior", + "sevensuperior", + "eightsuperior", + "ninesuperior", + "zeroinferior", + "oneinferior", + "twoinferior", + "threeinferior", + "fourinferior", + "fiveinferior", + "sixinferior", + "seveninferior", + "eightinferior", + "nineinferior", + "centinferior", + "dollarinferior", + "periodinferior", + "commainferior", + "Agravesmall", + "Aacutesmall", + "Acircumflexsmall", + "Atildesmall", + "Adieresissmall", + "Aringsmall", + "AEsmall", + "Ccedillasmall", + "Egravesmall", + "Eacutesmall", + "Ecircumflexsmall", + "Edieresissmall", + "Igravesmall", + "Iacutesmall", + "Icircumflexsmall", + "Idieresissmall", + "Ethsmall", + "Ntildesmall", + "Ogravesmall", + "Oacutesmall", + "Ocircumflexsmall", + "Otildesmall", + "Odieresissmall", + "OEsmall", + "Oslashsmall", + "Ugravesmall", + "Uacutesmall", + "Ucircumflexsmall", + "Udieresissmall", + "Yacutesmall", + "Thornsmall", + "Ydieresissmall", + "001.000", + "001.001", + "001.002", + "001.003", + "Black", + "Bold", + "Book", + "Light", + "Medium", + "Regular", + "Roman", + "Semibold" +]; +var cffStandardEncoding = [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quoteright", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "quoteleft", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "exclamdown", + "cent", + "sterling", + "fraction", + "yen", + "florin", + "section", + "currency", + "quotesingle", + "quotedblleft", + "guillemotleft", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "", + "endash", + "dagger", + "daggerdbl", + "periodcentered", + "", + "paragraph", + "bullet", + "quotesinglbase", + "quotedblbase", + "quotedblright", + "guillemotright", + "ellipsis", + "perthousand", + "", + "questiondown", + "", + "grave", + "acute", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "dieresis", + "", + "ring", + "cedilla", + "", + "hungarumlaut", + "ogonek", + "caron", + "emdash", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "AE", + "", + "ordfeminine", + "", + "", + "", + "", + "Lslash", + "Oslash", + "OE", + "ordmasculine", + "", + "", + "", + "", + "", + "ae", + "", + "", + "", + "dotlessi", + "", + "", + "lslash", + "oslash", + "oe", + "germandbls" +]; +var cffExpertEncoding = [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "space", + "exclamsmall", + "Hungarumlautsmall", + "", + "dollaroldstyle", + "dollarsuperior", + "ampersandsmall", + "Acutesmall", + "parenleftsuperior", + "parenrightsuperior", + "twodotenleader", + "onedotenleader", + "comma", + "hyphen", + "period", + "fraction", + "zerooldstyle", + "oneoldstyle", + "twooldstyle", + "threeoldstyle", + "fouroldstyle", + "fiveoldstyle", + "sixoldstyle", + "sevenoldstyle", + "eightoldstyle", + "nineoldstyle", + "colon", + "semicolon", + "commasuperior", + "threequartersemdash", + "periodsuperior", + "questionsmall", + "", + "asuperior", + "bsuperior", + "centsuperior", + "dsuperior", + "esuperior", + "", + "", + "isuperior", + "", + "", + "lsuperior", + "msuperior", + "nsuperior", + "osuperior", + "", + "", + "rsuperior", + "ssuperior", + "tsuperior", + "", + "ff", + "fi", + "fl", + "ffi", + "ffl", + "parenleftinferior", + "", + "parenrightinferior", + "Circumflexsmall", + "hyphensuperior", + "Gravesmall", + "Asmall", + "Bsmall", + "Csmall", + "Dsmall", + "Esmall", + "Fsmall", + "Gsmall", + "Hsmall", + "Ismall", + "Jsmall", + "Ksmall", + "Lsmall", + "Msmall", + "Nsmall", + "Osmall", + "Psmall", + "Qsmall", + "Rsmall", + "Ssmall", + "Tsmall", + "Usmall", + "Vsmall", + "Wsmall", + "Xsmall", + "Ysmall", + "Zsmall", + "colonmonetary", + "onefitted", + "rupiah", + "Tildesmall", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "exclamdownsmall", + "centoldstyle", + "Lslashsmall", + "", + "", + "Scaronsmall", + "Zcaronsmall", + "Dieresissmall", + "Brevesmall", + "Caronsmall", + "", + "Dotaccentsmall", + "", + "", + "Macronsmall", + "", + "", + "figuredash", + "hypheninferior", + "", + "", + "Ogoneksmall", + "Ringsmall", + "Cedillasmall", + "", + "", + "", + "onequarter", + "onehalf", + "threequarters", + "questiondownsmall", + "oneeighth", + "threeeighths", + "fiveeighths", + "seveneighths", + "onethird", + "twothirds", + "", + "", + "zerosuperior", + "onesuperior", + "twosuperior", + "threesuperior", + "foursuperior", + "fivesuperior", + "sixsuperior", + "sevensuperior", + "eightsuperior", + "ninesuperior", + "zeroinferior", + "oneinferior", + "twoinferior", + "threeinferior", + "fourinferior", + "fiveinferior", + "sixinferior", + "seveninferior", + "eightinferior", + "nineinferior", + "centinferior", + "dollarinferior", + "periodinferior", + "commainferior", + "Agravesmall", + "Aacutesmall", + "Acircumflexsmall", + "Atildesmall", + "Adieresissmall", + "Aringsmall", + "AEsmall", + "Ccedillasmall", + "Egravesmall", + "Eacutesmall", + "Ecircumflexsmall", + "Edieresissmall", + "Igravesmall", + "Iacutesmall", + "Icircumflexsmall", + "Idieresissmall", + "Ethsmall", + "Ntildesmall", + "Ogravesmall", + "Oacutesmall", + "Ocircumflexsmall", + "Otildesmall", + "Odieresissmall", + "OEsmall", + "Oslashsmall", + "Ugravesmall", + "Uacutesmall", + "Ucircumflexsmall", + "Udieresissmall", + "Yacutesmall", + "Thornsmall", + "Ydieresissmall" +]; +var standardNames = [ + ".notdef", + ".null", + "nonmarkingreturn", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quotesingle", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "grave", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "Adieresis", + "Aring", + "Ccedilla", + "Eacute", + "Ntilde", + "Odieresis", + "Udieresis", + "aacute", + "agrave", + "acircumflex", + "adieresis", + "atilde", + "aring", + "ccedilla", + "eacute", + "egrave", + "ecircumflex", + "edieresis", + "iacute", + "igrave", + "icircumflex", + "idieresis", + "ntilde", + "oacute", + "ograve", + "ocircumflex", + "odieresis", + "otilde", + "uacute", + "ugrave", + "ucircumflex", + "udieresis", + "dagger", + "degree", + "cent", + "sterling", + "section", + "bullet", + "paragraph", + "germandbls", + "registered", + "copyright", + "trademark", + "acute", + "dieresis", + "notequal", + "AE", + "Oslash", + "infinity", + "plusminus", + "lessequal", + "greaterequal", + "yen", + "mu", + "partialdiff", + "summation", + "product", + "pi", + "integral", + "ordfeminine", + "ordmasculine", + "Omega", + "ae", + "oslash", + "questiondown", + "exclamdown", + "logicalnot", + "radical", + "florin", + "approxequal", + "Delta", + "guillemotleft", + "guillemotright", + "ellipsis", + "nonbreakingspace", + "Agrave", + "Atilde", + "Otilde", + "OE", + "oe", + "endash", + "emdash", + "quotedblleft", + "quotedblright", + "quoteleft", + "quoteright", + "divide", + "lozenge", + "ydieresis", + "Ydieresis", + "fraction", + "currency", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "daggerdbl", + "periodcentered", + "quotesinglbase", + "quotedblbase", + "perthousand", + "Acircumflex", + "Ecircumflex", + "Aacute", + "Edieresis", + "Egrave", + "Iacute", + "Icircumflex", + "Idieresis", + "Igrave", + "Oacute", + "Ocircumflex", + "apple", + "Ograve", + "Uacute", + "Ucircumflex", + "Ugrave", + "dotlessi", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "ring", + "cedilla", + "hungarumlaut", + "ogonek", + "caron", + "Lslash", + "lslash", + "Scaron", + "scaron", + "Zcaron", + "zcaron", + "brokenbar", + "Eth", + "eth", + "Yacute", + "yacute", + "Thorn", + "thorn", + "minus", + "multiply", + "onesuperior", + "twosuperior", + "threesuperior", + "onehalf", + "onequarter", + "threequarters", + "franc", + "Gbreve", + "gbreve", + "Idotaccent", + "Scedilla", + "scedilla", + "Cacute", + "cacute", + "Ccaron", + "ccaron", + "dcroat" +]; +function DefaultEncoding(font) { + this.font = font; +} +DefaultEncoding.prototype.charToGlyphIndex = function(c) { + var code = c.codePointAt(0); + var glyphs = this.font.glyphs; + if (glyphs) { + for (var i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + for (var j2 = 0;j2 < glyph.unicodes.length; j2 += 1) { + if (glyph.unicodes[j2] === code) { + return i; + } + } + } + } + return null; +}; +function CmapEncoding(cmap2) { + this.cmap = cmap2; +} +CmapEncoding.prototype.charToGlyphIndex = function(c) { + return this.cmap.glyphIndexMap[c.codePointAt(0)] || 0; +}; +function CffEncoding(encoding, charset) { + this.encoding = encoding; + this.charset = charset; +} +CffEncoding.prototype.charToGlyphIndex = function(s) { + var code = s.codePointAt(0); + var charName = this.encoding[code]; + return this.charset.indexOf(charName); +}; +function GlyphNames(post) { + switch (post.version) { + case 1: + this.names = standardNames.slice(); + break; + case 2: + this.names = new Array(post.numberOfGlyphs); + for (var i = 0;i < post.numberOfGlyphs; i++) { + if (post.glyphNameIndex[i] < standardNames.length) { + this.names[i] = standardNames[post.glyphNameIndex[i]]; + } else { + this.names[i] = post.names[post.glyphNameIndex[i] - standardNames.length]; + } + } + break; + case 2.5: + this.names = new Array(post.numberOfGlyphs); + for (var i$1 = 0;i$1 < post.numberOfGlyphs; i$1++) { + this.names[i$1] = standardNames[i$1 + post.glyphNameIndex[i$1]]; + } + break; + case 3: + this.names = []; + break; + default: + this.names = []; + break; + } +} +GlyphNames.prototype.nameToGlyphIndex = function(name2) { + return this.names.indexOf(name2); +}; +GlyphNames.prototype.glyphIndexToName = function(gid) { + return this.names[gid]; +}; +function line(ctx, x1, y1, x2, y2) { + ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.stroke(); +} +var draw = { line }; +function getPathDefinition(glyph, path) { + var _path = path || new Path2; + return { + configurable: true, + get: function() { + if (typeof _path === "function") { + _path = _path(); + } + return _path; + }, + set: function(p) { + _path = p; + } + }; +} +function Glyph(options) { + this.bindConstructorValues(options); +} +Glyph.prototype.bindConstructorValues = function(options) { + this.index = options.index || 0; + this.name = options.name || null; + this.unicode = options.unicode || undefined; + this.unicodes = options.unicodes || options.unicode !== undefined ? [options.unicode] : []; + if ("xMin" in options) { + this.xMin = options.xMin; + } + if ("yMin" in options) { + this.yMin = options.yMin; + } + if ("xMax" in options) { + this.xMax = options.xMax; + } + if ("yMax" in options) { + this.yMax = options.yMax; + } + if ("advanceWidth" in options) { + this.advanceWidth = options.advanceWidth; + } + Object.defineProperty(this, "path", getPathDefinition(this, options.path)); +}; +Glyph.prototype.addUnicode = function(unicode) { + if (this.unicodes.length === 0) { + this.unicode = unicode; + } + this.unicodes.push(unicode); +}; +Glyph.prototype.getBoundingBox = function() { + return this.path.getBoundingBox(); +}; +Glyph.prototype.getPath = function(x2, y, fontSize, options, font) { + x2 = x2 !== undefined ? x2 : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 72; + var commands; + var hPoints; + if (!options) { + options = {}; + } + var xScale = options.xScale; + var yScale = options.yScale; + if (options.hinting && font && font.hinting) { + hPoints = this.path && font.hinting.exec(this, fontSize); + } + if (hPoints) { + commands = font.hinting.getCommands(hPoints); + x2 = Math.round(x2); + y = Math.round(y); + xScale = yScale = 1; + } else { + commands = this.path.commands; + var scale2 = 1 / (this.path.unitsPerEm || 1000) * fontSize; + if (xScale === undefined) { + xScale = scale2; + } + if (yScale === undefined) { + yScale = scale2; + } + } + var p = new Path2; + for (var i = 0;i < commands.length; i += 1) { + var cmd = commands[i]; + if (cmd.type === "M") { + p.moveTo(x2 + cmd.x * xScale, y + -cmd.y * yScale); + } else if (cmd.type === "L") { + p.lineTo(x2 + cmd.x * xScale, y + -cmd.y * yScale); + } else if (cmd.type === "Q") { + p.quadraticCurveTo(x2 + cmd.x1 * xScale, y + -cmd.y1 * yScale, x2 + cmd.x * xScale, y + -cmd.y * yScale); + } else if (cmd.type === "C") { + p.curveTo(x2 + cmd.x1 * xScale, y + -cmd.y1 * yScale, x2 + cmd.x2 * xScale, y + -cmd.y2 * yScale, x2 + cmd.x * xScale, y + -cmd.y * yScale); + } else if (cmd.type === "Z") { + p.closePath(); + } + } + return p; +}; +Glyph.prototype.getContours = function() { + if (this.points === undefined) { + return []; + } + var contours = []; + var currentContour = []; + for (var i = 0;i < this.points.length; i += 1) { + var pt = this.points[i]; + currentContour.push(pt); + if (pt.lastPointOfContour) { + contours.push(currentContour); + currentContour = []; + } + } + check.argument(currentContour.length === 0, "There are still points left in the current contour."); + return contours; +}; +Glyph.prototype.getMetrics = function() { + var commands = this.path.commands; + var xCoords = []; + var yCoords = []; + for (var i = 0;i < commands.length; i += 1) { + var cmd = commands[i]; + if (cmd.type !== "Z") { + xCoords.push(cmd.x); + yCoords.push(cmd.y); + } + if (cmd.type === "Q" || cmd.type === "C") { + xCoords.push(cmd.x1); + yCoords.push(cmd.y1); + } + if (cmd.type === "C") { + xCoords.push(cmd.x2); + yCoords.push(cmd.y2); + } + } + var metrics = { + xMin: Math.min.apply(null, xCoords), + yMin: Math.min.apply(null, yCoords), + xMax: Math.max.apply(null, xCoords), + yMax: Math.max.apply(null, yCoords), + leftSideBearing: this.leftSideBearing + }; + if (!isFinite(metrics.xMin)) { + metrics.xMin = 0; + } + if (!isFinite(metrics.xMax)) { + metrics.xMax = this.advanceWidth; + } + if (!isFinite(metrics.yMin)) { + metrics.yMin = 0; + } + if (!isFinite(metrics.yMax)) { + metrics.yMax = 0; + } + metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin); + return metrics; +}; +Glyph.prototype.draw = function(ctx, x2, y, fontSize, options) { + this.getPath(x2, y, fontSize, options).draw(ctx); +}; +Glyph.prototype.drawPoints = function(ctx, x2, y, fontSize) { + function drawCircles(l2, x3, y2, scale3) { + ctx.beginPath(); + for (var j2 = 0;j2 < l2.length; j2 += 1) { + ctx.moveTo(x3 + l2[j2].x * scale3, y2 + l2[j2].y * scale3); + ctx.arc(x3 + l2[j2].x * scale3, y2 + l2[j2].y * scale3, 2, 0, Math.PI * 2, false); + } + ctx.closePath(); + ctx.fill(); + } + x2 = x2 !== undefined ? x2 : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 24; + var scale2 = 1 / this.path.unitsPerEm * fontSize; + var blueCircles = []; + var redCircles = []; + var path = this.path; + for (var i = 0;i < path.commands.length; i += 1) { + var cmd = path.commands[i]; + if (cmd.x !== undefined) { + blueCircles.push({ x: cmd.x, y: -cmd.y }); + } + if (cmd.x1 !== undefined) { + redCircles.push({ x: cmd.x1, y: -cmd.y1 }); + } + if (cmd.x2 !== undefined) { + redCircles.push({ x: cmd.x2, y: -cmd.y2 }); + } + } + ctx.fillStyle = "blue"; + drawCircles(blueCircles, x2, y, scale2); + ctx.fillStyle = "red"; + drawCircles(redCircles, x2, y, scale2); +}; +Glyph.prototype.drawMetrics = function(ctx, x2, y, fontSize) { + var scale2; + x2 = x2 !== undefined ? x2 : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 24; + scale2 = 1 / this.path.unitsPerEm * fontSize; + ctx.lineWidth = 1; + ctx.strokeStyle = "black"; + draw.line(ctx, x2, -1e4, x2, 1e4); + draw.line(ctx, -1e4, y, 1e4, y); + var xMin = this.xMin || 0; + var yMin = this.yMin || 0; + var xMax = this.xMax || 0; + var yMax = this.yMax || 0; + var advanceWidth = this.advanceWidth || 0; + ctx.strokeStyle = "blue"; + draw.line(ctx, x2 + xMin * scale2, -1e4, x2 + xMin * scale2, 1e4); + draw.line(ctx, x2 + xMax * scale2, -1e4, x2 + xMax * scale2, 1e4); + draw.line(ctx, -1e4, y + -yMin * scale2, 1e4, y + -yMin * scale2); + draw.line(ctx, -1e4, y + -yMax * scale2, 1e4, y + -yMax * scale2); + ctx.strokeStyle = "green"; + draw.line(ctx, x2 + advanceWidth * scale2, -1e4, x2 + advanceWidth * scale2, 1e4); +}; +function defineDependentProperty(glyph, externalName, internalName) { + Object.defineProperty(glyph, externalName, { + get: function() { + glyph.path; + return glyph[internalName]; + }, + set: function(newValue) { + glyph[internalName] = newValue; + }, + enumerable: true, + configurable: true + }); +} +function GlyphSet(font, glyphs) { + this.font = font; + this.glyphs = {}; + if (Array.isArray(glyphs)) { + for (var i = 0;i < glyphs.length; i++) { + var glyph = glyphs[i]; + glyph.path.unitsPerEm = font.unitsPerEm; + this.glyphs[i] = glyph; + } + } + this.length = glyphs && glyphs.length || 0; +} +GlyphSet.prototype.get = function(index2) { + if (this.glyphs[index2] === undefined) { + this.font._push(index2); + if (typeof this.glyphs[index2] === "function") { + this.glyphs[index2] = this.glyphs[index2](); + } + var glyph = this.glyphs[index2]; + var unicodeObj = this.font._IndexToUnicodeMap[index2]; + if (unicodeObj) { + for (var j2 = 0;j2 < unicodeObj.unicodes.length; j2++) { + glyph.addUnicode(unicodeObj.unicodes[j2]); + } + } + if (this.font.cffEncoding) { + if (this.font.isCIDFont) { + glyph.name = "gid" + index2; + } else { + glyph.name = this.font.cffEncoding.charset[index2]; + } + } else if (this.font.glyphNames.names) { + glyph.name = this.font.glyphNames.glyphIndexToName(index2); + } + this.glyphs[index2].advanceWidth = this.font._hmtxTableData[index2].advanceWidth; + this.glyphs[index2].leftSideBearing = this.font._hmtxTableData[index2].leftSideBearing; + } else { + if (typeof this.glyphs[index2] === "function") { + this.glyphs[index2] = this.glyphs[index2](); + } + } + return this.glyphs[index2]; +}; +GlyphSet.prototype.push = function(index2, loader) { + this.glyphs[index2] = loader; + this.length++; +}; +function glyphLoader(font, index2) { + return new Glyph({ index: index2, font }); +} +function ttfGlyphLoader(font, index2, parseGlyph, data2, position2, buildPath) { + return function() { + var glyph = new Glyph({ index: index2, font }); + glyph.path = function() { + parseGlyph(glyph, data2, position2); + var path = buildPath(font.glyphs, glyph); + path.unitsPerEm = font.unitsPerEm; + return path; + }; + defineDependentProperty(glyph, "xMin", "_xMin"); + defineDependentProperty(glyph, "xMax", "_xMax"); + defineDependentProperty(glyph, "yMin", "_yMin"); + defineDependentProperty(glyph, "yMax", "_yMax"); + return glyph; + }; +} +function cffGlyphLoader(font, index2, parseCFFCharstring, charstring) { + return function() { + var glyph = new Glyph({ index: index2, font }); + glyph.path = function() { + var path = parseCFFCharstring(font, glyph, charstring); + path.unitsPerEm = font.unitsPerEm; + return path; + }; + return glyph; + }; +} +var glyphset = { GlyphSet, glyphLoader, ttfGlyphLoader, cffGlyphLoader }; +function equals2(a, b) { + if (a === b) { + return true; + } else if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return false; + } + for (var i = 0;i < a.length; i += 1) { + if (!equals2(a[i], b[i])) { + return false; + } + } + return true; + } else { + return false; + } +} +function calcCFFSubroutineBias(subrs) { + var bias; + if (subrs.length < 1240) { + bias = 107; + } else if (subrs.length < 33900) { + bias = 1131; + } else { + bias = 32768; + } + return bias; +} +function parseCFFIndex(data2, start, conversionFn) { + var offsets = []; + var objects = []; + var count = parse.getCard16(data2, start); + var objectOffset; + var endOffset; + if (count !== 0) { + var offsetSize = parse.getByte(data2, start + 2); + objectOffset = start + (count + 1) * offsetSize + 2; + var pos = start + 3; + for (var i = 0;i < count + 1; i += 1) { + offsets.push(parse.getOffset(data2, pos, offsetSize)); + pos += offsetSize; + } + endOffset = objectOffset + offsets[count]; + } else { + endOffset = start + 2; + } + for (var i$1 = 0;i$1 < offsets.length - 1; i$1 += 1) { + var value2 = parse.getBytes(data2, objectOffset + offsets[i$1], objectOffset + offsets[i$1 + 1]); + if (conversionFn) { + value2 = conversionFn(value2); + } + objects.push(value2); + } + return { objects, startOffset: start, endOffset }; +} +function parseCFFIndexLowMemory(data2, start) { + var offsets = []; + var count = parse.getCard16(data2, start); + var objectOffset; + var endOffset; + if (count !== 0) { + var offsetSize = parse.getByte(data2, start + 2); + objectOffset = start + (count + 1) * offsetSize + 2; + var pos = start + 3; + for (var i = 0;i < count + 1; i += 1) { + offsets.push(parse.getOffset(data2, pos, offsetSize)); + pos += offsetSize; + } + endOffset = objectOffset + offsets[count]; + } else { + endOffset = start + 2; + } + return { offsets, startOffset: start, endOffset }; +} +function getCffIndexObject(i, offsets, data2, start, conversionFn) { + var count = parse.getCard16(data2, start); + var objectOffset = 0; + if (count !== 0) { + var offsetSize = parse.getByte(data2, start + 2); + objectOffset = start + (count + 1) * offsetSize + 2; + } + var value2 = parse.getBytes(data2, objectOffset + offsets[i], objectOffset + offsets[i + 1]); + if (conversionFn) { + value2 = conversionFn(value2); + } + return value2; +} +function parseFloatOperand(parser) { + var s = ""; + var eof = 15; + var lookup = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "E", "E-", null, "-"]; + while (true) { + var b = parser.parseByte(); + var n1 = b >> 4; + var n2 = b & 15; + if (n1 === eof) { + break; + } + s += lookup[n1]; + if (n2 === eof) { + break; + } + s += lookup[n2]; + } + return parseFloat(s); +} +function parseOperand(parser, b0) { + var b1; + var b2; + var b3; + var b4; + if (b0 === 28) { + b1 = parser.parseByte(); + b2 = parser.parseByte(); + return b1 << 8 | b2; + } + if (b0 === 29) { + b1 = parser.parseByte(); + b2 = parser.parseByte(); + b3 = parser.parseByte(); + b4 = parser.parseByte(); + return b1 << 24 | b2 << 16 | b3 << 8 | b4; + } + if (b0 === 30) { + return parseFloatOperand(parser); + } + if (b0 >= 32 && b0 <= 246) { + return b0 - 139; + } + if (b0 >= 247 && b0 <= 250) { + b1 = parser.parseByte(); + return (b0 - 247) * 256 + b1 + 108; + } + if (b0 >= 251 && b0 <= 254) { + b1 = parser.parseByte(); + return -(b0 - 251) * 256 - b1 - 108; + } + throw new Error("Invalid b0 " + b0); +} +function entriesToObject(entries) { + var o = {}; + for (var i = 0;i < entries.length; i += 1) { + var key2 = entries[i][0]; + var values2 = entries[i][1]; + var value2 = undefined; + if (values2.length === 1) { + value2 = values2[0]; + } else { + value2 = values2; + } + if (o.hasOwnProperty(key2) && !isNaN(o[key2])) { + throw new Error("Object " + o + " already has key " + key2); + } + o[key2] = value2; + } + return o; +} +function parseCFFDict(data2, start, size) { + start = start !== undefined ? start : 0; + var parser = new parse.Parser(data2, start); + var entries = []; + var operands = []; + size = size !== undefined ? size : data2.length; + while (parser.relativeOffset < size) { + var op = parser.parseByte(); + if (op <= 21) { + if (op === 12) { + op = 1200 + parser.parseByte(); + } + entries.push([op, operands]); + operands = []; + } else { + operands.push(parseOperand(parser, op)); + } + } + return entriesToObject(entries); +} +function getCFFString(strings, index2) { + if (index2 <= 390) { + index2 = cffStandardStrings[index2]; + } else { + index2 = strings[index2 - 391]; + } + return index2; +} +function interpretDict(dict, meta, strings) { + var newDict = {}; + var value2; + for (var i = 0;i < meta.length; i += 1) { + var m = meta[i]; + if (Array.isArray(m.type)) { + var values2 = []; + values2.length = m.type.length; + for (var j2 = 0;j2 < m.type.length; j2++) { + value2 = dict[m.op] !== undefined ? dict[m.op][j2] : undefined; + if (value2 === undefined) { + value2 = m.value !== undefined && m.value[j2] !== undefined ? m.value[j2] : null; + } + if (m.type[j2] === "SID") { + value2 = getCFFString(strings, value2); + } + values2[j2] = value2; + } + newDict[m.name] = values2; + } else { + value2 = dict[m.op]; + if (value2 === undefined) { + value2 = m.value !== undefined ? m.value : null; + } + if (m.type === "SID") { + value2 = getCFFString(strings, value2); + } + newDict[m.name] = value2; + } + } + return newDict; +} +function parseCFFHeader(data2, start) { + var header = {}; + header.formatMajor = parse.getCard8(data2, start); + header.formatMinor = parse.getCard8(data2, start + 1); + header.size = parse.getCard8(data2, start + 2); + header.offsetSize = parse.getCard8(data2, start + 3); + header.startOffset = start; + header.endOffset = start + 4; + return header; +} +var TOP_DICT_META = [ + { name: "version", op: 0, type: "SID" }, + { name: "notice", op: 1, type: "SID" }, + { name: "copyright", op: 1200, type: "SID" }, + { name: "fullName", op: 2, type: "SID" }, + { name: "familyName", op: 3, type: "SID" }, + { name: "weight", op: 4, type: "SID" }, + { name: "isFixedPitch", op: 1201, type: "number", value: 0 }, + { name: "italicAngle", op: 1202, type: "number", value: 0 }, + { name: "underlinePosition", op: 1203, type: "number", value: -100 }, + { name: "underlineThickness", op: 1204, type: "number", value: 50 }, + { name: "paintType", op: 1205, type: "number", value: 0 }, + { name: "charstringType", op: 1206, type: "number", value: 2 }, + { + name: "fontMatrix", + op: 1207, + type: ["real", "real", "real", "real", "real", "real"], + value: [0.001, 0, 0, 0.001, 0, 0] + }, + { name: "uniqueId", op: 13, type: "number" }, + { name: "fontBBox", op: 5, type: ["number", "number", "number", "number"], value: [0, 0, 0, 0] }, + { name: "strokeWidth", op: 1208, type: "number", value: 0 }, + { name: "xuid", op: 14, type: [], value: null }, + { name: "charset", op: 15, type: "offset", value: 0 }, + { name: "encoding", op: 16, type: "offset", value: 0 }, + { name: "charStrings", op: 17, type: "offset", value: 0 }, + { name: "private", op: 18, type: ["number", "offset"], value: [0, 0] }, + { name: "ros", op: 1230, type: ["SID", "SID", "number"] }, + { name: "cidFontVersion", op: 1231, type: "number", value: 0 }, + { name: "cidFontRevision", op: 1232, type: "number", value: 0 }, + { name: "cidFontType", op: 1233, type: "number", value: 0 }, + { name: "cidCount", op: 1234, type: "number", value: 8720 }, + { name: "uidBase", op: 1235, type: "number" }, + { name: "fdArray", op: 1236, type: "offset" }, + { name: "fdSelect", op: 1237, type: "offset" }, + { name: "fontName", op: 1238, type: "SID" } +]; +var PRIVATE_DICT_META = [ + { name: "subrs", op: 19, type: "offset", value: 0 }, + { name: "defaultWidthX", op: 20, type: "number", value: 0 }, + { name: "nominalWidthX", op: 21, type: "number", value: 0 } +]; +function parseCFFTopDict(data2, strings) { + var dict = parseCFFDict(data2, 0, data2.byteLength); + return interpretDict(dict, TOP_DICT_META, strings); +} +function parseCFFPrivateDict(data2, start, size, strings) { + var dict = parseCFFDict(data2, start, size); + return interpretDict(dict, PRIVATE_DICT_META, strings); +} +function gatherCFFTopDicts(data2, start, cffIndex, strings) { + var topDictArray = []; + for (var iTopDict = 0;iTopDict < cffIndex.length; iTopDict += 1) { + var topDictData = new DataView(new Uint8Array(cffIndex[iTopDict]).buffer); + var topDict = parseCFFTopDict(topDictData, strings); + topDict._subrs = []; + topDict._subrsBias = 0; + topDict._defaultWidthX = 0; + topDict._nominalWidthX = 0; + var privateSize = topDict.private[0]; + var privateOffset = topDict.private[1]; + if (privateSize !== 0 && privateOffset !== 0) { + var privateDict = parseCFFPrivateDict(data2, privateOffset + start, privateSize, strings); + topDict._defaultWidthX = privateDict.defaultWidthX; + topDict._nominalWidthX = privateDict.nominalWidthX; + if (privateDict.subrs !== 0) { + var subrOffset = privateOffset + privateDict.subrs; + var subrIndex = parseCFFIndex(data2, subrOffset + start); + topDict._subrs = subrIndex.objects; + topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs); + } + topDict._privateDict = privateDict; + } + topDictArray.push(topDict); + } + return topDictArray; +} +function parseCFFCharset(data2, start, nGlyphs, strings) { + var sid; + var count; + var parser = new parse.Parser(data2, start); + nGlyphs -= 1; + var charset = [".notdef"]; + var format = parser.parseCard8(); + if (format === 0) { + for (var i = 0;i < nGlyphs; i += 1) { + sid = parser.parseSID(); + charset.push(getCFFString(strings, sid)); + } + } else if (format === 1) { + while (charset.length <= nGlyphs) { + sid = parser.parseSID(); + count = parser.parseCard8(); + for (var i$1 = 0;i$1 <= count; i$1 += 1) { + charset.push(getCFFString(strings, sid)); + sid += 1; + } + } + } else if (format === 2) { + while (charset.length <= nGlyphs) { + sid = parser.parseSID(); + count = parser.parseCard16(); + for (var i$2 = 0;i$2 <= count; i$2 += 1) { + charset.push(getCFFString(strings, sid)); + sid += 1; + } + } + } else { + throw new Error("Unknown charset format " + format); + } + return charset; +} +function parseCFFEncoding(data2, start, charset) { + var code; + var enc = {}; + var parser = new parse.Parser(data2, start); + var format = parser.parseCard8(); + if (format === 0) { + var nCodes = parser.parseCard8(); + for (var i = 0;i < nCodes; i += 1) { + code = parser.parseCard8(); + enc[code] = i; + } + } else if (format === 1) { + var nRanges = parser.parseCard8(); + code = 1; + for (var i$1 = 0;i$1 < nRanges; i$1 += 1) { + var first2 = parser.parseCard8(); + var nLeft = parser.parseCard8(); + for (var j2 = first2;j2 <= first2 + nLeft; j2 += 1) { + enc[j2] = code; + code += 1; + } + } + } else { + throw new Error("Unknown encoding format " + format); + } + return new CffEncoding(enc, charset); +} +function parseCFFCharstring(font, glyph, code) { + var c1x; + var c1y; + var c2x; + var c2y; + var p = new Path2; + var stack = []; + var nStems = 0; + var haveWidth = false; + var open = false; + var x2 = 0; + var y = 0; + var subrs; + var subrsBias; + var defaultWidthX; + var nominalWidthX; + if (font.isCIDFont) { + var fdIndex = font.tables.cff.topDict._fdSelect[glyph.index]; + var fdDict = font.tables.cff.topDict._fdArray[fdIndex]; + subrs = fdDict._subrs; + subrsBias = fdDict._subrsBias; + defaultWidthX = fdDict._defaultWidthX; + nominalWidthX = fdDict._nominalWidthX; + } else { + subrs = font.tables.cff.topDict._subrs; + subrsBias = font.tables.cff.topDict._subrsBias; + defaultWidthX = font.tables.cff.topDict._defaultWidthX; + nominalWidthX = font.tables.cff.topDict._nominalWidthX; + } + var width2 = defaultWidthX; + function newContour(x3, y2) { + if (open) { + p.closePath(); + } + p.moveTo(x3, y2); + open = true; + } + function parseStems() { + var hasWidthArg; + hasWidthArg = stack.length % 2 !== 0; + if (hasWidthArg && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + } + nStems += stack.length >> 1; + stack.length = 0; + haveWidth = true; + } + function parse2(code2) { + var b1; + var b2; + var b3; + var b4; + var codeIndex; + var subrCode; + var jpx; + var jpy; + var c3x; + var c3y; + var c4x; + var c4y; + var i = 0; + while (i < code2.length) { + var v = code2[i]; + i += 1; + switch (v) { + case 1: + parseStems(); + break; + case 3: + parseStems(); + break; + case 4: + if (stack.length > 1 && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + haveWidth = true; + } + y += stack.pop(); + newContour(x2, y); + break; + case 5: + while (stack.length > 0) { + x2 += stack.shift(); + y += stack.shift(); + p.lineTo(x2, y); + } + break; + case 6: + while (stack.length > 0) { + x2 += stack.shift(); + p.lineTo(x2, y); + if (stack.length === 0) { + break; + } + y += stack.shift(); + p.lineTo(x2, y); + } + break; + case 7: + while (stack.length > 0) { + y += stack.shift(); + p.lineTo(x2, y); + if (stack.length === 0) { + break; + } + x2 += stack.shift(); + p.lineTo(x2, y); + } + break; + case 8: + while (stack.length > 0) { + c1x = x2 + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + } + break; + case 10: + codeIndex = stack.pop() + subrsBias; + subrCode = subrs[codeIndex]; + if (subrCode) { + parse2(subrCode); + } + break; + case 11: + return; + case 12: + v = code2[i]; + i += 1; + switch (v) { + case 35: + c1x = x2 + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + jpx = c2x + stack.shift(); + jpy = c2y + stack.shift(); + c3x = jpx + stack.shift(); + c3y = jpy + stack.shift(); + c4x = c3x + stack.shift(); + c4y = c3y + stack.shift(); + x2 = c4x + stack.shift(); + y = c4y + stack.shift(); + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x2, y); + break; + case 34: + c1x = x2 + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + jpx = c2x + stack.shift(); + jpy = c2y; + c3x = jpx + stack.shift(); + c3y = c2y; + c4x = c3x + stack.shift(); + c4y = y; + x2 = c4x + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x2, y); + break; + case 36: + c1x = x2 + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + jpx = c2x + stack.shift(); + jpy = c2y; + c3x = jpx + stack.shift(); + c3y = c2y; + c4x = c3x + stack.shift(); + c4y = c3y + stack.shift(); + x2 = c4x + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x2, y); + break; + case 37: + c1x = x2 + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + jpx = c2x + stack.shift(); + jpy = c2y + stack.shift(); + c3x = jpx + stack.shift(); + c3y = jpy + stack.shift(); + c4x = c3x + stack.shift(); + c4y = c3y + stack.shift(); + if (Math.abs(c4x - x2) > Math.abs(c4y - y)) { + x2 = c4x + stack.shift(); + } else { + y = c4y + stack.shift(); + } + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x2, y); + break; + default: + console.log("Glyph " + glyph.index + ": unknown operator " + 1200 + v); + stack.length = 0; + } + break; + case 14: + if (stack.length > 0 && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + haveWidth = true; + } + if (open) { + p.closePath(); + open = false; + } + break; + case 18: + parseStems(); + break; + case 19: + case 20: + parseStems(); + i += nStems + 7 >> 3; + break; + case 21: + if (stack.length > 2 && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + haveWidth = true; + } + y += stack.pop(); + x2 += stack.pop(); + newContour(x2, y); + break; + case 22: + if (stack.length > 1 && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + haveWidth = true; + } + x2 += stack.pop(); + newContour(x2, y); + break; + case 23: + parseStems(); + break; + case 24: + while (stack.length > 2) { + c1x = x2 + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + } + x2 += stack.shift(); + y += stack.shift(); + p.lineTo(x2, y); + break; + case 25: + while (stack.length > 6) { + x2 += stack.shift(); + y += stack.shift(); + p.lineTo(x2, y); + } + c1x = x2 + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + break; + case 26: + if (stack.length % 2) { + x2 += stack.shift(); + } + while (stack.length > 0) { + c1x = x2; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x; + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + } + break; + case 27: + if (stack.length % 2) { + y += stack.shift(); + } + while (stack.length > 0) { + c1x = x2 + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y = c2y; + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + } + break; + case 28: + b1 = code2[i]; + b2 = code2[i + 1]; + stack.push((b1 << 24 | b2 << 16) >> 16); + i += 2; + break; + case 29: + codeIndex = stack.pop() + font.gsubrsBias; + subrCode = font.gsubrs[codeIndex]; + if (subrCode) { + parse2(subrCode); + } + break; + case 30: + while (stack.length > 0) { + c1x = x2; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y = c2y + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + if (stack.length === 0) { + break; + } + c1x = x2 + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + y = c2y + stack.shift(); + x2 = c2x + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + } + break; + case 31: + while (stack.length > 0) { + c1x = x2 + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + y = c2y + stack.shift(); + x2 = c2x + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + if (stack.length === 0) { + break; + } + c1x = x2; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y = c2y + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + } + break; + default: + if (v < 32) { + console.log("Glyph " + glyph.index + ": unknown operator " + v); + } else if (v < 247) { + stack.push(v - 139); + } else if (v < 251) { + b1 = code2[i]; + i += 1; + stack.push((v - 247) * 256 + b1 + 108); + } else if (v < 255) { + b1 = code2[i]; + i += 1; + stack.push(-(v - 251) * 256 - b1 - 108); + } else { + b1 = code2[i]; + b2 = code2[i + 1]; + b3 = code2[i + 2]; + b4 = code2[i + 3]; + i += 4; + stack.push((b1 << 24 | b2 << 16 | b3 << 8 | b4) / 65536); + } + } + } + } + parse2(code); + glyph.advanceWidth = width2; + return p; +} +function parseCFFFDSelect(data2, start, nGlyphs, fdArrayCount) { + var fdSelect = []; + var fdIndex; + var parser = new parse.Parser(data2, start); + var format = parser.parseCard8(); + if (format === 0) { + for (var iGid = 0;iGid < nGlyphs; iGid++) { + fdIndex = parser.parseCard8(); + if (fdIndex >= fdArrayCount) { + throw new Error("CFF table CID Font FDSelect has bad FD index value " + fdIndex + " (FD count " + fdArrayCount + ")"); + } + fdSelect.push(fdIndex); + } + } else if (format === 3) { + var nRanges = parser.parseCard16(); + var first2 = parser.parseCard16(); + if (first2 !== 0) { + throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID " + first2); + } + var next; + for (var iRange = 0;iRange < nRanges; iRange++) { + fdIndex = parser.parseCard8(); + next = parser.parseCard16(); + if (fdIndex >= fdArrayCount) { + throw new Error("CFF table CID Font FDSelect has bad FD index value " + fdIndex + " (FD count " + fdArrayCount + ")"); + } + if (next > nGlyphs) { + throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID " + next); + } + for (;first2 < next; first2++) { + fdSelect.push(fdIndex); + } + first2 = next; + } + if (next !== nGlyphs) { + throw new Error("CFF Table CID Font FDSelect format 3 range has bad final GID " + next); + } + } else { + throw new Error("CFF Table CID Font FDSelect table has unsupported format " + format); + } + return fdSelect; +} +function parseCFFTable(data2, start, font, opt) { + font.tables.cff = {}; + var header = parseCFFHeader(data2, start); + var nameIndex = parseCFFIndex(data2, header.endOffset, parse.bytesToString); + var topDictIndex = parseCFFIndex(data2, nameIndex.endOffset); + var stringIndex = parseCFFIndex(data2, topDictIndex.endOffset, parse.bytesToString); + var globalSubrIndex = parseCFFIndex(data2, stringIndex.endOffset); + font.gsubrs = globalSubrIndex.objects; + font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs); + var topDictArray = gatherCFFTopDicts(data2, start, topDictIndex.objects, stringIndex.objects); + if (topDictArray.length !== 1) { + throw new Error("CFF table has too many fonts in 'FontSet' - count of fonts NameIndex.length = " + topDictArray.length); + } + var topDict = topDictArray[0]; + font.tables.cff.topDict = topDict; + if (topDict._privateDict) { + font.defaultWidthX = topDict._privateDict.defaultWidthX; + font.nominalWidthX = topDict._privateDict.nominalWidthX; + } + if (topDict.ros[0] !== undefined && topDict.ros[1] !== undefined) { + font.isCIDFont = true; + } + if (font.isCIDFont) { + var fdArrayOffset = topDict.fdArray; + var fdSelectOffset = topDict.fdSelect; + if (fdArrayOffset === 0 || fdSelectOffset === 0) { + throw new Error("Font is marked as a CID font, but FDArray and/or FDSelect information is missing"); + } + fdArrayOffset += start; + var fdArrayIndex = parseCFFIndex(data2, fdArrayOffset); + var fdArray = gatherCFFTopDicts(data2, start, fdArrayIndex.objects, stringIndex.objects); + topDict._fdArray = fdArray; + fdSelectOffset += start; + topDict._fdSelect = parseCFFFDSelect(data2, fdSelectOffset, font.numGlyphs, fdArray.length); + } + var privateDictOffset = start + topDict.private[1]; + var privateDict = parseCFFPrivateDict(data2, privateDictOffset, topDict.private[0], stringIndex.objects); + font.defaultWidthX = privateDict.defaultWidthX; + font.nominalWidthX = privateDict.nominalWidthX; + if (privateDict.subrs !== 0) { + var subrOffset = privateDictOffset + privateDict.subrs; + var subrIndex = parseCFFIndex(data2, subrOffset); + font.subrs = subrIndex.objects; + font.subrsBias = calcCFFSubroutineBias(font.subrs); + } else { + font.subrs = []; + font.subrsBias = 0; + } + var charStringsIndex; + if (opt.lowMemory) { + charStringsIndex = parseCFFIndexLowMemory(data2, start + topDict.charStrings); + font.nGlyphs = charStringsIndex.offsets.length; + } else { + charStringsIndex = parseCFFIndex(data2, start + topDict.charStrings); + font.nGlyphs = charStringsIndex.objects.length; + } + var charset = parseCFFCharset(data2, start + topDict.charset, font.nGlyphs, stringIndex.objects); + if (topDict.encoding === 0) { + font.cffEncoding = new CffEncoding(cffStandardEncoding, charset); + } else if (topDict.encoding === 1) { + font.cffEncoding = new CffEncoding(cffExpertEncoding, charset); + } else { + font.cffEncoding = parseCFFEncoding(data2, start + topDict.encoding, charset); + } + font.encoding = font.encoding || font.cffEncoding; + font.glyphs = new glyphset.GlyphSet(font); + if (opt.lowMemory) { + font._push = function(i2) { + var charString2 = getCffIndexObject(i2, charStringsIndex.offsets, data2, start + topDict.charStrings); + font.glyphs.push(i2, glyphset.cffGlyphLoader(font, i2, parseCFFCharstring, charString2)); + }; + } else { + for (var i = 0;i < font.nGlyphs; i += 1) { + var charString = charStringsIndex.objects[i]; + font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); + } + } +} +function encodeString(s, strings) { + var sid; + var i = cffStandardStrings.indexOf(s); + if (i >= 0) { + sid = i; + } + i = strings.indexOf(s); + if (i >= 0) { + sid = i + cffStandardStrings.length; + } else { + sid = cffStandardStrings.length + strings.length; + strings.push(s); + } + return sid; +} +function makeHeader() { + return new table.Record("Header", [ + { name: "major", type: "Card8", value: 1 }, + { name: "minor", type: "Card8", value: 0 }, + { name: "hdrSize", type: "Card8", value: 4 }, + { name: "major", type: "Card8", value: 1 } + ]); +} +function makeNameIndex(fontNames) { + var t2 = new table.Record("Name INDEX", [ + { name: "names", type: "INDEX", value: [] } + ]); + t2.names = []; + for (var i = 0;i < fontNames.length; i += 1) { + t2.names.push({ name: "name_" + i, type: "NAME", value: fontNames[i] }); + } + return t2; +} +function makeDict(meta, attrs, strings) { + var m = {}; + for (var i = 0;i < meta.length; i += 1) { + var entry = meta[i]; + var value2 = attrs[entry.name]; + if (value2 !== undefined && !equals2(value2, entry.value)) { + if (entry.type === "SID") { + value2 = encodeString(value2, strings); + } + m[entry.op] = { name: entry.name, type: entry.type, value: value2 }; + } + } + return m; +} +function makeTopDict(attrs, strings) { + var t2 = new table.Record("Top DICT", [ + { name: "dict", type: "DICT", value: {} } + ]); + t2.dict = makeDict(TOP_DICT_META, attrs, strings); + return t2; +} +function makeTopDictIndex(topDict) { + var t2 = new table.Record("Top DICT INDEX", [ + { name: "topDicts", type: "INDEX", value: [] } + ]); + t2.topDicts = [{ name: "topDict_0", type: "TABLE", value: topDict }]; + return t2; +} +function makeStringIndex(strings) { + var t2 = new table.Record("String INDEX", [ + { name: "strings", type: "INDEX", value: [] } + ]); + t2.strings = []; + for (var i = 0;i < strings.length; i += 1) { + t2.strings.push({ name: "string_" + i, type: "STRING", value: strings[i] }); + } + return t2; +} +function makeGlobalSubrIndex() { + return new table.Record("Global Subr INDEX", [ + { name: "subrs", type: "INDEX", value: [] } + ]); +} +function makeCharsets(glyphNames, strings) { + var t2 = new table.Record("Charsets", [ + { name: "format", type: "Card8", value: 0 } + ]); + for (var i = 0;i < glyphNames.length; i += 1) { + var glyphName = glyphNames[i]; + var glyphSID = encodeString(glyphName, strings); + t2.fields.push({ name: "glyph_" + i, type: "SID", value: glyphSID }); + } + return t2; +} +function glyphToOps(glyph) { + var ops = []; + var path = glyph.path; + ops.push({ name: "width", type: "NUMBER", value: glyph.advanceWidth }); + var x2 = 0; + var y = 0; + for (var i = 0;i < path.commands.length; i += 1) { + var dx = undefined; + var dy = undefined; + var cmd = path.commands[i]; + if (cmd.type === "Q") { + var _13 = 1 / 3; + var _23 = 2 / 3; + cmd = { + type: "C", + x: cmd.x, + y: cmd.y, + x1: Math.round(_13 * x2 + _23 * cmd.x1), + y1: Math.round(_13 * y + _23 * cmd.y1), + x2: Math.round(_13 * cmd.x + _23 * cmd.x1), + y2: Math.round(_13 * cmd.y + _23 * cmd.y1) + }; + } + if (cmd.type === "M") { + dx = Math.round(cmd.x - x2); + dy = Math.round(cmd.y - y); + ops.push({ name: "dx", type: "NUMBER", value: dx }); + ops.push({ name: "dy", type: "NUMBER", value: dy }); + ops.push({ name: "rmoveto", type: "OP", value: 21 }); + x2 = Math.round(cmd.x); + y = Math.round(cmd.y); + } else if (cmd.type === "L") { + dx = Math.round(cmd.x - x2); + dy = Math.round(cmd.y - y); + ops.push({ name: "dx", type: "NUMBER", value: dx }); + ops.push({ name: "dy", type: "NUMBER", value: dy }); + ops.push({ name: "rlineto", type: "OP", value: 5 }); + x2 = Math.round(cmd.x); + y = Math.round(cmd.y); + } else if (cmd.type === "C") { + var dx1 = Math.round(cmd.x1 - x2); + var dy1 = Math.round(cmd.y1 - y); + var dx2 = Math.round(cmd.x2 - cmd.x1); + var dy2 = Math.round(cmd.y2 - cmd.y1); + dx = Math.round(cmd.x - cmd.x2); + dy = Math.round(cmd.y - cmd.y2); + ops.push({ name: "dx1", type: "NUMBER", value: dx1 }); + ops.push({ name: "dy1", type: "NUMBER", value: dy1 }); + ops.push({ name: "dx2", type: "NUMBER", value: dx2 }); + ops.push({ name: "dy2", type: "NUMBER", value: dy2 }); + ops.push({ name: "dx", type: "NUMBER", value: dx }); + ops.push({ name: "dy", type: "NUMBER", value: dy }); + ops.push({ name: "rrcurveto", type: "OP", value: 8 }); + x2 = Math.round(cmd.x); + y = Math.round(cmd.y); + } + } + ops.push({ name: "endchar", type: "OP", value: 14 }); + return ops; +} +function makeCharStringsIndex(glyphs) { + var t2 = new table.Record("CharStrings INDEX", [ + { name: "charStrings", type: "INDEX", value: [] } + ]); + for (var i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + var ops = glyphToOps(glyph); + t2.charStrings.push({ name: glyph.name, type: "CHARSTRING", value: ops }); + } + return t2; +} +function makePrivateDict(attrs, strings) { + var t2 = new table.Record("Private DICT", [ + { name: "dict", type: "DICT", value: {} } + ]); + t2.dict = makeDict(PRIVATE_DICT_META, attrs, strings); + return t2; +} +function makeCFFTable(glyphs, options) { + var t2 = new table.Table("CFF ", [ + { name: "header", type: "RECORD" }, + { name: "nameIndex", type: "RECORD" }, + { name: "topDictIndex", type: "RECORD" }, + { name: "stringIndex", type: "RECORD" }, + { name: "globalSubrIndex", type: "RECORD" }, + { name: "charsets", type: "RECORD" }, + { name: "charStringsIndex", type: "RECORD" }, + { name: "privateDict", type: "RECORD" } + ]); + var fontScale = 1 / options.unitsPerEm; + var attrs = { + version: options.version, + fullName: options.fullName, + familyName: options.familyName, + weight: options.weightName, + fontBBox: options.fontBBox || [0, 0, 0, 0], + fontMatrix: [fontScale, 0, 0, fontScale, 0, 0], + charset: 999, + encoding: 0, + charStrings: 999, + private: [0, 999] + }; + var privateAttrs = {}; + var glyphNames = []; + var glyph; + for (var i = 1;i < glyphs.length; i += 1) { + glyph = glyphs.get(i); + glyphNames.push(glyph.name); + } + var strings = []; + t2.header = makeHeader(); + t2.nameIndex = makeNameIndex([options.postScriptName]); + var topDict = makeTopDict(attrs, strings); + t2.topDictIndex = makeTopDictIndex(topDict); + t2.globalSubrIndex = makeGlobalSubrIndex(); + t2.charsets = makeCharsets(glyphNames, strings); + t2.charStringsIndex = makeCharStringsIndex(glyphs); + t2.privateDict = makePrivateDict(privateAttrs, strings); + t2.stringIndex = makeStringIndex(strings); + var startOffset = t2.header.sizeOf() + t2.nameIndex.sizeOf() + t2.topDictIndex.sizeOf() + t2.stringIndex.sizeOf() + t2.globalSubrIndex.sizeOf(); + attrs.charset = startOffset; + attrs.encoding = 0; + attrs.charStrings = attrs.charset + t2.charsets.sizeOf(); + attrs.private[1] = attrs.charStrings + t2.charStringsIndex.sizeOf(); + topDict = makeTopDict(attrs, strings); + t2.topDictIndex = makeTopDictIndex(topDict); + return t2; +} +var cff = { parse: parseCFFTable, make: makeCFFTable }; +function parseHeadTable(data2, start) { + var head = {}; + var p = new parse.Parser(data2, start); + head.version = p.parseVersion(); + head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000; + head.checkSumAdjustment = p.parseULong(); + head.magicNumber = p.parseULong(); + check.argument(head.magicNumber === 1594834165, "Font header has wrong magic number."); + head.flags = p.parseUShort(); + head.unitsPerEm = p.parseUShort(); + head.created = p.parseLongDateTime(); + head.modified = p.parseLongDateTime(); + head.xMin = p.parseShort(); + head.yMin = p.parseShort(); + head.xMax = p.parseShort(); + head.yMax = p.parseShort(); + head.macStyle = p.parseUShort(); + head.lowestRecPPEM = p.parseUShort(); + head.fontDirectionHint = p.parseShort(); + head.indexToLocFormat = p.parseShort(); + head.glyphDataFormat = p.parseShort(); + return head; +} +function makeHeadTable(options) { + var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800; + var createdTimestamp = timestamp; + if (options.createdTimestamp) { + createdTimestamp = options.createdTimestamp + 2082844800; + } + return new table.Table("head", [ + { name: "version", type: "FIXED", value: 65536 }, + { name: "fontRevision", type: "FIXED", value: 65536 }, + { name: "checkSumAdjustment", type: "ULONG", value: 0 }, + { name: "magicNumber", type: "ULONG", value: 1594834165 }, + { name: "flags", type: "USHORT", value: 0 }, + { name: "unitsPerEm", type: "USHORT", value: 1000 }, + { name: "created", type: "LONGDATETIME", value: createdTimestamp }, + { name: "modified", type: "LONGDATETIME", value: timestamp }, + { name: "xMin", type: "SHORT", value: 0 }, + { name: "yMin", type: "SHORT", value: 0 }, + { name: "xMax", type: "SHORT", value: 0 }, + { name: "yMax", type: "SHORT", value: 0 }, + { name: "macStyle", type: "USHORT", value: 0 }, + { name: "lowestRecPPEM", type: "USHORT", value: 0 }, + { name: "fontDirectionHint", type: "SHORT", value: 2 }, + { name: "indexToLocFormat", type: "SHORT", value: 0 }, + { name: "glyphDataFormat", type: "SHORT", value: 0 } + ], options); +} +var head = { parse: parseHeadTable, make: makeHeadTable }; +function parseHheaTable(data2, start) { + var hhea = {}; + var p = new parse.Parser(data2, start); + hhea.version = p.parseVersion(); + hhea.ascender = p.parseShort(); + hhea.descender = p.parseShort(); + hhea.lineGap = p.parseShort(); + hhea.advanceWidthMax = p.parseUShort(); + hhea.minLeftSideBearing = p.parseShort(); + hhea.minRightSideBearing = p.parseShort(); + hhea.xMaxExtent = p.parseShort(); + hhea.caretSlopeRise = p.parseShort(); + hhea.caretSlopeRun = p.parseShort(); + hhea.caretOffset = p.parseShort(); + p.relativeOffset += 8; + hhea.metricDataFormat = p.parseShort(); + hhea.numberOfHMetrics = p.parseUShort(); + return hhea; +} +function makeHheaTable(options) { + return new table.Table("hhea", [ + { name: "version", type: "FIXED", value: 65536 }, + { name: "ascender", type: "FWORD", value: 0 }, + { name: "descender", type: "FWORD", value: 0 }, + { name: "lineGap", type: "FWORD", value: 0 }, + { name: "advanceWidthMax", type: "UFWORD", value: 0 }, + { name: "minLeftSideBearing", type: "FWORD", value: 0 }, + { name: "minRightSideBearing", type: "FWORD", value: 0 }, + { name: "xMaxExtent", type: "FWORD", value: 0 }, + { name: "caretSlopeRise", type: "SHORT", value: 1 }, + { name: "caretSlopeRun", type: "SHORT", value: 0 }, + { name: "caretOffset", type: "SHORT", value: 0 }, + { name: "reserved1", type: "SHORT", value: 0 }, + { name: "reserved2", type: "SHORT", value: 0 }, + { name: "reserved3", type: "SHORT", value: 0 }, + { name: "reserved4", type: "SHORT", value: 0 }, + { name: "metricDataFormat", type: "SHORT", value: 0 }, + { name: "numberOfHMetrics", type: "USHORT", value: 0 } + ], options); +} +var hhea = { parse: parseHheaTable, make: makeHheaTable }; +function parseHmtxTableAll(data2, start, numMetrics, numGlyphs, glyphs) { + var advanceWidth; + var leftSideBearing; + var p = new parse.Parser(data2, start); + for (var i = 0;i < numGlyphs; i += 1) { + if (i < numMetrics) { + advanceWidth = p.parseUShort(); + leftSideBearing = p.parseShort(); + } + var glyph = glyphs.get(i); + glyph.advanceWidth = advanceWidth; + glyph.leftSideBearing = leftSideBearing; + } +} +function parseHmtxTableOnLowMemory(font, data2, start, numMetrics, numGlyphs) { + font._hmtxTableData = {}; + var advanceWidth; + var leftSideBearing; + var p = new parse.Parser(data2, start); + for (var i = 0;i < numGlyphs; i += 1) { + if (i < numMetrics) { + advanceWidth = p.parseUShort(); + leftSideBearing = p.parseShort(); + } + font._hmtxTableData[i] = { + advanceWidth, + leftSideBearing + }; + } +} +function parseHmtxTable(font, data2, start, numMetrics, numGlyphs, glyphs, opt) { + if (opt.lowMemory) { + parseHmtxTableOnLowMemory(font, data2, start, numMetrics, numGlyphs); + } else { + parseHmtxTableAll(data2, start, numMetrics, numGlyphs, glyphs); + } +} +function makeHmtxTable(glyphs) { + var t2 = new table.Table("hmtx", []); + for (var i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + var advanceWidth = glyph.advanceWidth || 0; + var leftSideBearing = glyph.leftSideBearing || 0; + t2.fields.push({ name: "advanceWidth_" + i, type: "USHORT", value: advanceWidth }); + t2.fields.push({ name: "leftSideBearing_" + i, type: "SHORT", value: leftSideBearing }); + } + return t2; +} +var hmtx = { parse: parseHmtxTable, make: makeHmtxTable }; +function makeLtagTable(tags) { + var result = new table.Table("ltag", [ + { name: "version", type: "ULONG", value: 1 }, + { name: "flags", type: "ULONG", value: 0 }, + { name: "numTags", type: "ULONG", value: tags.length } + ]); + var stringPool = ""; + var stringPoolOffset = 12 + tags.length * 4; + for (var i = 0;i < tags.length; ++i) { + var pos = stringPool.indexOf(tags[i]); + if (pos < 0) { + pos = stringPool.length; + stringPool += tags[i]; + } + result.fields.push({ name: "offset " + i, type: "USHORT", value: stringPoolOffset + pos }); + result.fields.push({ name: "length " + i, type: "USHORT", value: tags[i].length }); + } + result.fields.push({ name: "stringPool", type: "CHARARRAY", value: stringPool }); + return result; +} +function parseLtagTable(data2, start) { + var p = new parse.Parser(data2, start); + var tableVersion = p.parseULong(); + check.argument(tableVersion === 1, "Unsupported ltag table version."); + p.skip("uLong", 1); + var numTags = p.parseULong(); + var tags = []; + for (var i = 0;i < numTags; i++) { + var tag = ""; + var offset = start + p.parseUShort(); + var length2 = p.parseUShort(); + for (var j2 = offset;j2 < offset + length2; ++j2) { + tag += String.fromCharCode(data2.getInt8(j2)); + } + tags.push(tag); + } + return tags; +} +var ltag = { make: makeLtagTable, parse: parseLtagTable }; +function parseMaxpTable(data2, start) { + var maxp = {}; + var p = new parse.Parser(data2, start); + maxp.version = p.parseVersion(); + maxp.numGlyphs = p.parseUShort(); + if (maxp.version === 1) { + maxp.maxPoints = p.parseUShort(); + maxp.maxContours = p.parseUShort(); + maxp.maxCompositePoints = p.parseUShort(); + maxp.maxCompositeContours = p.parseUShort(); + maxp.maxZones = p.parseUShort(); + maxp.maxTwilightPoints = p.parseUShort(); + maxp.maxStorage = p.parseUShort(); + maxp.maxFunctionDefs = p.parseUShort(); + maxp.maxInstructionDefs = p.parseUShort(); + maxp.maxStackElements = p.parseUShort(); + maxp.maxSizeOfInstructions = p.parseUShort(); + maxp.maxComponentElements = p.parseUShort(); + maxp.maxComponentDepth = p.parseUShort(); + } + return maxp; +} +function makeMaxpTable(numGlyphs) { + return new table.Table("maxp", [ + { name: "version", type: "FIXED", value: 20480 }, + { name: "numGlyphs", type: "USHORT", value: numGlyphs } + ]); +} +var maxp = { parse: parseMaxpTable, make: makeMaxpTable }; +var nameTableNames = [ + "copyright", + "fontFamily", + "fontSubfamily", + "uniqueID", + "fullName", + "version", + "postScriptName", + "trademark", + "manufacturer", + "designer", + "description", + "manufacturerURL", + "designerURL", + "license", + "licenseURL", + "reserved", + "preferredFamily", + "preferredSubfamily", + "compatibleFullName", + "sampleText", + "postScriptFindFontName", + "wwsFamily", + "wwsSubfamily" +]; +var macLanguages = { + 0: "en", + 1: "fr", + 2: "de", + 3: "it", + 4: "nl", + 5: "sv", + 6: "es", + 7: "da", + 8: "pt", + 9: "no", + 10: "he", + 11: "ja", + 12: "ar", + 13: "fi", + 14: "el", + 15: "is", + 16: "mt", + 17: "tr", + 18: "hr", + 19: "zh-Hant", + 20: "ur", + 21: "hi", + 22: "th", + 23: "ko", + 24: "lt", + 25: "pl", + 26: "hu", + 27: "es", + 28: "lv", + 29: "se", + 30: "fo", + 31: "fa", + 32: "ru", + 33: "zh", + 34: "nl-BE", + 35: "ga", + 36: "sq", + 37: "ro", + 38: "cz", + 39: "sk", + 40: "si", + 41: "yi", + 42: "sr", + 43: "mk", + 44: "bg", + 45: "uk", + 46: "be", + 47: "uz", + 48: "kk", + 49: "az-Cyrl", + 50: "az-Arab", + 51: "hy", + 52: "ka", + 53: "mo", + 54: "ky", + 55: "tg", + 56: "tk", + 57: "mn-CN", + 58: "mn", + 59: "ps", + 60: "ks", + 61: "ku", + 62: "sd", + 63: "bo", + 64: "ne", + 65: "sa", + 66: "mr", + 67: "bn", + 68: "as", + 69: "gu", + 70: "pa", + 71: "or", + 72: "ml", + 73: "kn", + 74: "ta", + 75: "te", + 76: "si", + 77: "my", + 78: "km", + 79: "lo", + 80: "vi", + 81: "id", + 82: "tl", + 83: "ms", + 84: "ms-Arab", + 85: "am", + 86: "ti", + 87: "om", + 88: "so", + 89: "sw", + 90: "rw", + 91: "rn", + 92: "ny", + 93: "mg", + 94: "eo", + 128: "cy", + 129: "eu", + 130: "ca", + 131: "la", + 132: "qu", + 133: "gn", + 134: "ay", + 135: "tt", + 136: "ug", + 137: "dz", + 138: "jv", + 139: "su", + 140: "gl", + 141: "af", + 142: "br", + 143: "iu", + 144: "gd", + 145: "gv", + 146: "ga", + 147: "to", + 148: "el-polyton", + 149: "kl", + 150: "az", + 151: "nn" +}; +var macLanguageToScript = { + 0: 0, + 1: 0, + 2: 0, + 3: 0, + 4: 0, + 5: 0, + 6: 0, + 7: 0, + 8: 0, + 9: 0, + 10: 5, + 11: 1, + 12: 4, + 13: 0, + 14: 6, + 15: 0, + 16: 0, + 17: 0, + 18: 0, + 19: 2, + 20: 4, + 21: 9, + 22: 21, + 23: 3, + 24: 29, + 25: 29, + 26: 29, + 27: 29, + 28: 29, + 29: 0, + 30: 0, + 31: 4, + 32: 7, + 33: 25, + 34: 0, + 35: 0, + 36: 0, + 37: 0, + 38: 29, + 39: 29, + 40: 0, + 41: 5, + 42: 7, + 43: 7, + 44: 7, + 45: 7, + 46: 7, + 47: 7, + 48: 7, + 49: 7, + 50: 4, + 51: 24, + 52: 23, + 53: 7, + 54: 7, + 55: 7, + 56: 7, + 57: 27, + 58: 7, + 59: 4, + 60: 4, + 61: 4, + 62: 4, + 63: 26, + 64: 9, + 65: 9, + 66: 9, + 67: 13, + 68: 13, + 69: 11, + 70: 10, + 71: 12, + 72: 17, + 73: 16, + 74: 14, + 75: 15, + 76: 18, + 77: 19, + 78: 20, + 79: 22, + 80: 30, + 81: 0, + 82: 0, + 83: 0, + 84: 4, + 85: 28, + 86: 28, + 87: 28, + 88: 0, + 89: 0, + 90: 0, + 91: 0, + 92: 0, + 93: 0, + 94: 0, + 128: 0, + 129: 0, + 130: 0, + 131: 0, + 132: 0, + 133: 0, + 134: 0, + 135: 7, + 136: 4, + 137: 26, + 138: 0, + 139: 0, + 140: 0, + 141: 0, + 142: 0, + 143: 28, + 144: 0, + 145: 0, + 146: 0, + 147: 0, + 148: 6, + 149: 0, + 150: 0, + 151: 0 +}; +var windowsLanguages = { + 1078: "af", + 1052: "sq", + 1156: "gsw", + 1118: "am", + 5121: "ar-DZ", + 15361: "ar-BH", + 3073: "ar", + 2049: "ar-IQ", + 11265: "ar-JO", + 13313: "ar-KW", + 12289: "ar-LB", + 4097: "ar-LY", + 6145: "ary", + 8193: "ar-OM", + 16385: "ar-QA", + 1025: "ar-SA", + 10241: "ar-SY", + 7169: "aeb", + 14337: "ar-AE", + 9217: "ar-YE", + 1067: "hy", + 1101: "as", + 2092: "az-Cyrl", + 1068: "az", + 1133: "ba", + 1069: "eu", + 1059: "be", + 2117: "bn", + 1093: "bn-IN", + 8218: "bs-Cyrl", + 5146: "bs", + 1150: "br", + 1026: "bg", + 1027: "ca", + 3076: "zh-HK", + 5124: "zh-MO", + 2052: "zh", + 4100: "zh-SG", + 1028: "zh-TW", + 1155: "co", + 1050: "hr", + 4122: "hr-BA", + 1029: "cs", + 1030: "da", + 1164: "prs", + 1125: "dv", + 2067: "nl-BE", + 1043: "nl", + 3081: "en-AU", + 10249: "en-BZ", + 4105: "en-CA", + 9225: "en-029", + 16393: "en-IN", + 6153: "en-IE", + 8201: "en-JM", + 17417: "en-MY", + 5129: "en-NZ", + 13321: "en-PH", + 18441: "en-SG", + 7177: "en-ZA", + 11273: "en-TT", + 2057: "en-GB", + 1033: "en", + 12297: "en-ZW", + 1061: "et", + 1080: "fo", + 1124: "fil", + 1035: "fi", + 2060: "fr-BE", + 3084: "fr-CA", + 1036: "fr", + 5132: "fr-LU", + 6156: "fr-MC", + 4108: "fr-CH", + 1122: "fy", + 1110: "gl", + 1079: "ka", + 3079: "de-AT", + 1031: "de", + 5127: "de-LI", + 4103: "de-LU", + 2055: "de-CH", + 1032: "el", + 1135: "kl", + 1095: "gu", + 1128: "ha", + 1037: "he", + 1081: "hi", + 1038: "hu", + 1039: "is", + 1136: "ig", + 1057: "id", + 1117: "iu", + 2141: "iu-Latn", + 2108: "ga", + 1076: "xh", + 1077: "zu", + 1040: "it", + 2064: "it-CH", + 1041: "ja", + 1099: "kn", + 1087: "kk", + 1107: "km", + 1158: "quc", + 1159: "rw", + 1089: "sw", + 1111: "kok", + 1042: "ko", + 1088: "ky", + 1108: "lo", + 1062: "lv", + 1063: "lt", + 2094: "dsb", + 1134: "lb", + 1071: "mk", + 2110: "ms-BN", + 1086: "ms", + 1100: "ml", + 1082: "mt", + 1153: "mi", + 1146: "arn", + 1102: "mr", + 1148: "moh", + 1104: "mn", + 2128: "mn-CN", + 1121: "ne", + 1044: "nb", + 2068: "nn", + 1154: "oc", + 1096: "or", + 1123: "ps", + 1045: "pl", + 1046: "pt", + 2070: "pt-PT", + 1094: "pa", + 1131: "qu-BO", + 2155: "qu-EC", + 3179: "qu", + 1048: "ro", + 1047: "rm", + 1049: "ru", + 9275: "smn", + 4155: "smj-NO", + 5179: "smj", + 3131: "se-FI", + 1083: "se", + 2107: "se-SE", + 8251: "sms", + 6203: "sma-NO", + 7227: "sms", + 1103: "sa", + 7194: "sr-Cyrl-BA", + 3098: "sr", + 6170: "sr-Latn-BA", + 2074: "sr-Latn", + 1132: "nso", + 1074: "tn", + 1115: "si", + 1051: "sk", + 1060: "sl", + 11274: "es-AR", + 16394: "es-BO", + 13322: "es-CL", + 9226: "es-CO", + 5130: "es-CR", + 7178: "es-DO", + 12298: "es-EC", + 17418: "es-SV", + 4106: "es-GT", + 18442: "es-HN", + 2058: "es-MX", + 19466: "es-NI", + 6154: "es-PA", + 15370: "es-PY", + 10250: "es-PE", + 20490: "es-PR", + 3082: "es", + 1034: "es", + 21514: "es-US", + 14346: "es-UY", + 8202: "es-VE", + 2077: "sv-FI", + 1053: "sv", + 1114: "syr", + 1064: "tg", + 2143: "tzm", + 1097: "ta", + 1092: "tt", + 1098: "te", + 1054: "th", + 1105: "bo", + 1055: "tr", + 1090: "tk", + 1152: "ug", + 1058: "uk", + 1070: "hsb", + 1056: "ur", + 2115: "uz-Cyrl", + 1091: "uz", + 1066: "vi", + 1106: "cy", + 1160: "wo", + 1157: "sah", + 1144: "ii", + 1130: "yo" +}; +function getLanguageCode(platformID, languageID, ltag2) { + switch (platformID) { + case 0: + if (languageID === 65535) { + return "und"; + } else if (ltag2) { + return ltag2[languageID]; + } + break; + case 1: + return macLanguages[languageID]; + case 3: + return windowsLanguages[languageID]; + } + return; +} +var utf16 = "utf-16"; +var macScriptEncodings = { + 0: "macintosh", + 1: "x-mac-japanese", + 2: "x-mac-chinesetrad", + 3: "x-mac-korean", + 6: "x-mac-greek", + 7: "x-mac-cyrillic", + 9: "x-mac-devanagai", + 10: "x-mac-gurmukhi", + 11: "x-mac-gujarati", + 12: "x-mac-oriya", + 13: "x-mac-bengali", + 14: "x-mac-tamil", + 15: "x-mac-telugu", + 16: "x-mac-kannada", + 17: "x-mac-malayalam", + 18: "x-mac-sinhalese", + 19: "x-mac-burmese", + 20: "x-mac-khmer", + 21: "x-mac-thai", + 22: "x-mac-lao", + 23: "x-mac-georgian", + 24: "x-mac-armenian", + 25: "x-mac-chinesesimp", + 26: "x-mac-tibetan", + 27: "x-mac-mongolian", + 28: "x-mac-ethiopic", + 29: "x-mac-ce", + 30: "x-mac-vietnamese", + 31: "x-mac-extarabic" +}; +var macLanguageEncodings = { + 15: "x-mac-icelandic", + 17: "x-mac-turkish", + 18: "x-mac-croatian", + 24: "x-mac-ce", + 25: "x-mac-ce", + 26: "x-mac-ce", + 27: "x-mac-ce", + 28: "x-mac-ce", + 30: "x-mac-icelandic", + 37: "x-mac-romanian", + 38: "x-mac-ce", + 39: "x-mac-ce", + 40: "x-mac-ce", + 143: "x-mac-inuit", + 146: "x-mac-gaelic" +}; +function getEncoding(platformID, encodingID, languageID) { + switch (platformID) { + case 0: + return utf16; + case 1: + return macLanguageEncodings[languageID] || macScriptEncodings[encodingID]; + case 3: + if (encodingID === 1 || encodingID === 10) { + return utf16; + } + break; + } + return; +} +function parseNameTable(data2, start, ltag2) { + var name2 = {}; + var p = new parse.Parser(data2, start); + var format = p.parseUShort(); + var count = p.parseUShort(); + var stringOffset = p.offset + p.parseUShort(); + for (var i = 0;i < count; i++) { + var platformID = p.parseUShort(); + var encodingID = p.parseUShort(); + var languageID = p.parseUShort(); + var nameID = p.parseUShort(); + var property2 = nameTableNames[nameID] || nameID; + var byteLength = p.parseUShort(); + var offset = p.parseUShort(); + var language = getLanguageCode(platformID, languageID, ltag2); + var encoding = getEncoding(platformID, encodingID, languageID); + if (encoding !== undefined && language !== undefined) { + var text2 = undefined; + if (encoding === utf16) { + text2 = decode.UTF16(data2, stringOffset + offset, byteLength); + } else { + text2 = decode.MACSTRING(data2, stringOffset + offset, byteLength, encoding); + } + if (text2) { + var translations = name2[property2]; + if (translations === undefined) { + translations = name2[property2] = {}; + } + translations[language] = text2; + } + } + } + var langTagCount = 0; + if (format === 1) { + langTagCount = p.parseUShort(); + } + return name2; +} +function reverseDict(dict) { + var result = {}; + for (var key2 in dict) { + result[dict[key2]] = parseInt(key2); + } + return result; +} +function makeNameRecord(platformID, encodingID, languageID, nameID, length2, offset) { + return new table.Record("NameRecord", [ + { name: "platformID", type: "USHORT", value: platformID }, + { name: "encodingID", type: "USHORT", value: encodingID }, + { name: "languageID", type: "USHORT", value: languageID }, + { name: "nameID", type: "USHORT", value: nameID }, + { name: "length", type: "USHORT", value: length2 }, + { name: "offset", type: "USHORT", value: offset } + ]); +} +function findSubArray(needle, haystack) { + var needleLength = needle.length; + var limit = haystack.length - needleLength + 1; + loop: + for (var pos = 0;pos < limit; pos++) { + for (;pos < limit; pos++) { + for (var k2 = 0;k2 < needleLength; k2++) { + if (haystack[pos + k2] !== needle[k2]) { + continue loop; + } + } + return pos; + } + } + return -1; +} +function addStringToPool(s, pool) { + var offset = findSubArray(s, pool); + if (offset < 0) { + offset = pool.length; + var i = 0; + var len = s.length; + for (;i < len; ++i) { + pool.push(s[i]); + } + } + return offset; +} +function makeNameTable(names, ltag2) { + var nameID; + var nameIDs = []; + var namesWithNumericKeys = {}; + var nameTableIds = reverseDict(nameTableNames); + for (var key2 in names) { + var id = nameTableIds[key2]; + if (id === undefined) { + id = key2; + } + nameID = parseInt(id); + if (isNaN(nameID)) { + throw new Error('Name table entry "' + key2 + '" does not exist, see nameTableNames for complete list.'); + } + namesWithNumericKeys[nameID] = names[key2]; + nameIDs.push(nameID); + } + var macLanguageIds = reverseDict(macLanguages); + var windowsLanguageIds = reverseDict(windowsLanguages); + var nameRecords = []; + var stringPool = []; + for (var i = 0;i < nameIDs.length; i++) { + nameID = nameIDs[i]; + var translations = namesWithNumericKeys[nameID]; + for (var lang in translations) { + var text2 = translations[lang]; + var macPlatform = 1; + var macLanguage = macLanguageIds[lang]; + var macScript = macLanguageToScript[macLanguage]; + var macEncoding = getEncoding(macPlatform, macScript, macLanguage); + var macName = encode.MACSTRING(text2, macEncoding); + if (macName === undefined) { + macPlatform = 0; + macLanguage = ltag2.indexOf(lang); + if (macLanguage < 0) { + macLanguage = ltag2.length; + ltag2.push(lang); + } + macScript = 4; + macName = encode.UTF16(text2); + } + var macNameOffset = addStringToPool(macName, stringPool); + nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage, nameID, macName.length, macNameOffset)); + var winLanguage = windowsLanguageIds[lang]; + if (winLanguage !== undefined) { + var winName = encode.UTF16(text2); + var winNameOffset = addStringToPool(winName, stringPool); + nameRecords.push(makeNameRecord(3, 1, winLanguage, nameID, winName.length, winNameOffset)); + } + } + } + nameRecords.sort(function(a, b) { + return a.platformID - b.platformID || a.encodingID - b.encodingID || a.languageID - b.languageID || a.nameID - b.nameID; + }); + var t2 = new table.Table("name", [ + { name: "format", type: "USHORT", value: 0 }, + { name: "count", type: "USHORT", value: nameRecords.length }, + { name: "stringOffset", type: "USHORT", value: 6 + nameRecords.length * 12 } + ]); + for (var r = 0;r < nameRecords.length; r++) { + t2.fields.push({ name: "record_" + r, type: "RECORD", value: nameRecords[r] }); + } + t2.fields.push({ name: "strings", type: "LITERAL", value: stringPool }); + return t2; +} +var _name = { parse: parseNameTable, make: makeNameTable }; +var unicodeRanges = [ + { begin: 0, end: 127 }, + { begin: 128, end: 255 }, + { begin: 256, end: 383 }, + { begin: 384, end: 591 }, + { begin: 592, end: 687 }, + { begin: 688, end: 767 }, + { begin: 768, end: 879 }, + { begin: 880, end: 1023 }, + { begin: 11392, end: 11519 }, + { begin: 1024, end: 1279 }, + { begin: 1328, end: 1423 }, + { begin: 1424, end: 1535 }, + { begin: 42240, end: 42559 }, + { begin: 1536, end: 1791 }, + { begin: 1984, end: 2047 }, + { begin: 2304, end: 2431 }, + { begin: 2432, end: 2559 }, + { begin: 2560, end: 2687 }, + { begin: 2688, end: 2815 }, + { begin: 2816, end: 2943 }, + { begin: 2944, end: 3071 }, + { begin: 3072, end: 3199 }, + { begin: 3200, end: 3327 }, + { begin: 3328, end: 3455 }, + { begin: 3584, end: 3711 }, + { begin: 3712, end: 3839 }, + { begin: 4256, end: 4351 }, + { begin: 6912, end: 7039 }, + { begin: 4352, end: 4607 }, + { begin: 7680, end: 7935 }, + { begin: 7936, end: 8191 }, + { begin: 8192, end: 8303 }, + { begin: 8304, end: 8351 }, + { begin: 8352, end: 8399 }, + { begin: 8400, end: 8447 }, + { begin: 8448, end: 8527 }, + { begin: 8528, end: 8591 }, + { begin: 8592, end: 8703 }, + { begin: 8704, end: 8959 }, + { begin: 8960, end: 9215 }, + { begin: 9216, end: 9279 }, + { begin: 9280, end: 9311 }, + { begin: 9312, end: 9471 }, + { begin: 9472, end: 9599 }, + { begin: 9600, end: 9631 }, + { begin: 9632, end: 9727 }, + { begin: 9728, end: 9983 }, + { begin: 9984, end: 10175 }, + { begin: 12288, end: 12351 }, + { begin: 12352, end: 12447 }, + { begin: 12448, end: 12543 }, + { begin: 12544, end: 12591 }, + { begin: 12592, end: 12687 }, + { begin: 43072, end: 43135 }, + { begin: 12800, end: 13055 }, + { begin: 13056, end: 13311 }, + { begin: 44032, end: 55215 }, + { begin: 55296, end: 57343 }, + { begin: 67840, end: 67871 }, + { begin: 19968, end: 40959 }, + { begin: 57344, end: 63743 }, + { begin: 12736, end: 12783 }, + { begin: 64256, end: 64335 }, + { begin: 64336, end: 65023 }, + { begin: 65056, end: 65071 }, + { begin: 65040, end: 65055 }, + { begin: 65104, end: 65135 }, + { begin: 65136, end: 65279 }, + { begin: 65280, end: 65519 }, + { begin: 65520, end: 65535 }, + { begin: 3840, end: 4095 }, + { begin: 1792, end: 1871 }, + { begin: 1920, end: 1983 }, + { begin: 3456, end: 3583 }, + { begin: 4096, end: 4255 }, + { begin: 4608, end: 4991 }, + { begin: 5024, end: 5119 }, + { begin: 5120, end: 5759 }, + { begin: 5760, end: 5791 }, + { begin: 5792, end: 5887 }, + { begin: 6016, end: 6143 }, + { begin: 6144, end: 6319 }, + { begin: 10240, end: 10495 }, + { begin: 40960, end: 42127 }, + { begin: 5888, end: 5919 }, + { begin: 66304, end: 66351 }, + { begin: 66352, end: 66383 }, + { begin: 66560, end: 66639 }, + { begin: 118784, end: 119039 }, + { begin: 119808, end: 120831 }, + { begin: 1044480, end: 1048573 }, + { begin: 65024, end: 65039 }, + { begin: 917504, end: 917631 }, + { begin: 6400, end: 6479 }, + { begin: 6480, end: 6527 }, + { begin: 6528, end: 6623 }, + { begin: 6656, end: 6687 }, + { begin: 11264, end: 11359 }, + { begin: 11568, end: 11647 }, + { begin: 19904, end: 19967 }, + { begin: 43008, end: 43055 }, + { begin: 65536, end: 65663 }, + { begin: 65856, end: 65935 }, + { begin: 66432, end: 66463 }, + { begin: 66464, end: 66527 }, + { begin: 66640, end: 66687 }, + { begin: 66688, end: 66735 }, + { begin: 67584, end: 67647 }, + { begin: 68096, end: 68191 }, + { begin: 119552, end: 119647 }, + { begin: 73728, end: 74751 }, + { begin: 119648, end: 119679 }, + { begin: 7040, end: 7103 }, + { begin: 7168, end: 7247 }, + { begin: 7248, end: 7295 }, + { begin: 43136, end: 43231 }, + { begin: 43264, end: 43311 }, + { begin: 43312, end: 43359 }, + { begin: 43520, end: 43615 }, + { begin: 65936, end: 65999 }, + { begin: 66000, end: 66047 }, + { begin: 66208, end: 66271 }, + { begin: 127024, end: 127135 } +]; +function getUnicodeRange(unicode) { + for (var i = 0;i < unicodeRanges.length; i += 1) { + var range = unicodeRanges[i]; + if (unicode >= range.begin && unicode < range.end) { + return i; + } + } + return -1; +} +function parseOS2Table(data2, start) { + var os2 = {}; + var p = new parse.Parser(data2, start); + os2.version = p.parseUShort(); + os2.xAvgCharWidth = p.parseShort(); + os2.usWeightClass = p.parseUShort(); + os2.usWidthClass = p.parseUShort(); + os2.fsType = p.parseUShort(); + os2.ySubscriptXSize = p.parseShort(); + os2.ySubscriptYSize = p.parseShort(); + os2.ySubscriptXOffset = p.parseShort(); + os2.ySubscriptYOffset = p.parseShort(); + os2.ySuperscriptXSize = p.parseShort(); + os2.ySuperscriptYSize = p.parseShort(); + os2.ySuperscriptXOffset = p.parseShort(); + os2.ySuperscriptYOffset = p.parseShort(); + os2.yStrikeoutSize = p.parseShort(); + os2.yStrikeoutPosition = p.parseShort(); + os2.sFamilyClass = p.parseShort(); + os2.panose = []; + for (var i = 0;i < 10; i++) { + os2.panose[i] = p.parseByte(); + } + os2.ulUnicodeRange1 = p.parseULong(); + os2.ulUnicodeRange2 = p.parseULong(); + os2.ulUnicodeRange3 = p.parseULong(); + os2.ulUnicodeRange4 = p.parseULong(); + os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte()); + os2.fsSelection = p.parseUShort(); + os2.usFirstCharIndex = p.parseUShort(); + os2.usLastCharIndex = p.parseUShort(); + os2.sTypoAscender = p.parseShort(); + os2.sTypoDescender = p.parseShort(); + os2.sTypoLineGap = p.parseShort(); + os2.usWinAscent = p.parseUShort(); + os2.usWinDescent = p.parseUShort(); + if (os2.version >= 1) { + os2.ulCodePageRange1 = p.parseULong(); + os2.ulCodePageRange2 = p.parseULong(); + } + if (os2.version >= 2) { + os2.sxHeight = p.parseShort(); + os2.sCapHeight = p.parseShort(); + os2.usDefaultChar = p.parseUShort(); + os2.usBreakChar = p.parseUShort(); + os2.usMaxContent = p.parseUShort(); + } + return os2; +} +function makeOS2Table(options) { + return new table.Table("OS/2", [ + { name: "version", type: "USHORT", value: 3 }, + { name: "xAvgCharWidth", type: "SHORT", value: 0 }, + { name: "usWeightClass", type: "USHORT", value: 0 }, + { name: "usWidthClass", type: "USHORT", value: 0 }, + { name: "fsType", type: "USHORT", value: 0 }, + { name: "ySubscriptXSize", type: "SHORT", value: 650 }, + { name: "ySubscriptYSize", type: "SHORT", value: 699 }, + { name: "ySubscriptXOffset", type: "SHORT", value: 0 }, + { name: "ySubscriptYOffset", type: "SHORT", value: 140 }, + { name: "ySuperscriptXSize", type: "SHORT", value: 650 }, + { name: "ySuperscriptYSize", type: "SHORT", value: 699 }, + { name: "ySuperscriptXOffset", type: "SHORT", value: 0 }, + { name: "ySuperscriptYOffset", type: "SHORT", value: 479 }, + { name: "yStrikeoutSize", type: "SHORT", value: 49 }, + { name: "yStrikeoutPosition", type: "SHORT", value: 258 }, + { name: "sFamilyClass", type: "SHORT", value: 0 }, + { name: "bFamilyType", type: "BYTE", value: 0 }, + { name: "bSerifStyle", type: "BYTE", value: 0 }, + { name: "bWeight", type: "BYTE", value: 0 }, + { name: "bProportion", type: "BYTE", value: 0 }, + { name: "bContrast", type: "BYTE", value: 0 }, + { name: "bStrokeVariation", type: "BYTE", value: 0 }, + { name: "bArmStyle", type: "BYTE", value: 0 }, + { name: "bLetterform", type: "BYTE", value: 0 }, + { name: "bMidline", type: "BYTE", value: 0 }, + { name: "bXHeight", type: "BYTE", value: 0 }, + { name: "ulUnicodeRange1", type: "ULONG", value: 0 }, + { name: "ulUnicodeRange2", type: "ULONG", value: 0 }, + { name: "ulUnicodeRange3", type: "ULONG", value: 0 }, + { name: "ulUnicodeRange4", type: "ULONG", value: 0 }, + { name: "achVendID", type: "CHARARRAY", value: "XXXX" }, + { name: "fsSelection", type: "USHORT", value: 0 }, + { name: "usFirstCharIndex", type: "USHORT", value: 0 }, + { name: "usLastCharIndex", type: "USHORT", value: 0 }, + { name: "sTypoAscender", type: "SHORT", value: 0 }, + { name: "sTypoDescender", type: "SHORT", value: 0 }, + { name: "sTypoLineGap", type: "SHORT", value: 0 }, + { name: "usWinAscent", type: "USHORT", value: 0 }, + { name: "usWinDescent", type: "USHORT", value: 0 }, + { name: "ulCodePageRange1", type: "ULONG", value: 0 }, + { name: "ulCodePageRange2", type: "ULONG", value: 0 }, + { name: "sxHeight", type: "SHORT", value: 0 }, + { name: "sCapHeight", type: "SHORT", value: 0 }, + { name: "usDefaultChar", type: "USHORT", value: 0 }, + { name: "usBreakChar", type: "USHORT", value: 0 }, + { name: "usMaxContext", type: "USHORT", value: 0 } + ], options); +} +var os2 = { parse: parseOS2Table, make: makeOS2Table, unicodeRanges, getUnicodeRange }; +function parsePostTable(data2, start) { + var post = {}; + var p = new parse.Parser(data2, start); + post.version = p.parseVersion(); + post.italicAngle = p.parseFixed(); + post.underlinePosition = p.parseShort(); + post.underlineThickness = p.parseShort(); + post.isFixedPitch = p.parseULong(); + post.minMemType42 = p.parseULong(); + post.maxMemType42 = p.parseULong(); + post.minMemType1 = p.parseULong(); + post.maxMemType1 = p.parseULong(); + switch (post.version) { + case 1: + post.names = standardNames.slice(); + break; + case 2: + post.numberOfGlyphs = p.parseUShort(); + post.glyphNameIndex = new Array(post.numberOfGlyphs); + for (var i = 0;i < post.numberOfGlyphs; i++) { + post.glyphNameIndex[i] = p.parseUShort(); + } + post.names = []; + for (var i$1 = 0;i$1 < post.numberOfGlyphs; i$1++) { + if (post.glyphNameIndex[i$1] >= standardNames.length) { + var nameLength = p.parseChar(); + post.names.push(p.parseString(nameLength)); + } + } + break; + case 2.5: + post.numberOfGlyphs = p.parseUShort(); + post.offset = new Array(post.numberOfGlyphs); + for (var i$2 = 0;i$2 < post.numberOfGlyphs; i$2++) { + post.offset[i$2] = p.parseChar(); + } + break; + } + return post; +} +function makePostTable() { + return new table.Table("post", [ + { name: "version", type: "FIXED", value: 196608 }, + { name: "italicAngle", type: "FIXED", value: 0 }, + { name: "underlinePosition", type: "FWORD", value: 0 }, + { name: "underlineThickness", type: "FWORD", value: 0 }, + { name: "isFixedPitch", type: "ULONG", value: 0 }, + { name: "minMemType42", type: "ULONG", value: 0 }, + { name: "maxMemType42", type: "ULONG", value: 0 }, + { name: "minMemType1", type: "ULONG", value: 0 }, + { name: "maxMemType1", type: "ULONG", value: 0 } + ]); +} +var post = { parse: parsePostTable, make: makePostTable }; +var subtableParsers = new Array(9); +subtableParsers[1] = function parseLookup1() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat: 1, + coverage: this.parsePointer(Parser.coverage), + deltaGlyphId: this.parseUShort() + }; + } else if (substFormat === 2) { + return { + substFormat: 2, + coverage: this.parsePointer(Parser.coverage), + substitute: this.parseOffset16List() + }; + } + check.assert(false, "0x" + start.toString(16) + ": lookup type 1 format must be 1 or 2."); +}; +subtableParsers[2] = function parseLookup2() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB Multiple Substitution Subtable identifier-format must be 1"); + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + sequences: this.parseListOfLists() + }; +}; +subtableParsers[3] = function parseLookup3() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB Alternate Substitution Subtable identifier-format must be 1"); + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + alternateSets: this.parseListOfLists() + }; +}; +subtableParsers[4] = function parseLookup4() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB ligature table identifier-format must be 1"); + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + ligatureSets: this.parseListOfLists(function() { + return { + ligGlyph: this.parseUShort(), + components: this.parseUShortList(this.parseUShort() - 1) + }; + }) + }; +}; +var lookupRecordDesc = { + sequenceIndex: Parser.uShort, + lookupListIndex: Parser.uShort +}; +subtableParsers[5] = function parseLookup5() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + ruleSets: this.parseListOfLists(function() { + var glyphCount2 = this.parseUShort(); + var substCount2 = this.parseUShort(); + return { + input: this.parseUShortList(glyphCount2 - 1), + lookupRecords: this.parseRecordList(substCount2, lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 2) { + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + classDef: this.parsePointer(Parser.classDef), + classSets: this.parseListOfLists(function() { + var glyphCount2 = this.parseUShort(); + var substCount2 = this.parseUShort(); + return { + classes: this.parseUShortList(glyphCount2 - 1), + lookupRecords: this.parseRecordList(substCount2, lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 3) { + var glyphCount = this.parseUShort(); + var substCount = this.parseUShort(); + return { + substFormat, + coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)), + lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) + }; + } + check.assert(false, "0x" + start.toString(16) + ": lookup type 5 format must be 1, 2 or 3."); +}; +subtableParsers[6] = function parseLookup6() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat: 1, + coverage: this.parsePointer(Parser.coverage), + chainRuleSets: this.parseListOfLists(function() { + return { + backtrack: this.parseUShortList(), + input: this.parseUShortList(this.parseShort() - 1), + lookahead: this.parseUShortList(), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 2) { + return { + substFormat: 2, + coverage: this.parsePointer(Parser.coverage), + backtrackClassDef: this.parsePointer(Parser.classDef), + inputClassDef: this.parsePointer(Parser.classDef), + lookaheadClassDef: this.parsePointer(Parser.classDef), + chainClassSet: this.parseListOfLists(function() { + return { + backtrack: this.parseUShortList(), + input: this.parseUShortList(this.parseShort() - 1), + lookahead: this.parseUShortList(), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 3) { + return { + substFormat: 3, + backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), + inputCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + } + check.assert(false, "0x" + start.toString(16) + ": lookup type 6 format must be 1, 2 or 3."); +}; +subtableParsers[7] = function parseLookup7() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB Extension Substitution subtable identifier-format must be 1"); + var extensionLookupType = this.parseUShort(); + var extensionParser = new Parser(this.data, this.offset + this.parseULong()); + return { + substFormat: 1, + lookupType: extensionLookupType, + extension: subtableParsers[extensionLookupType].call(extensionParser) + }; +}; +subtableParsers[8] = function parseLookup8() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1"); + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), + substitutes: this.parseUShortList() + }; +}; +function parseGsubTable(data2, start) { + start = start || 0; + var p = new Parser(data2, start); + var tableVersion = p.parseVersion(1); + check.argument(tableVersion === 1 || tableVersion === 1.1, "Unsupported GSUB table version."); + if (tableVersion === 1) { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers) + }; + } else { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers), + variations: p.parseFeatureVariationsList() + }; + } +} +var subtableMakers = new Array(9); +subtableMakers[1] = function makeLookup1(subtable) { + if (subtable.substFormat === 1) { + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 1 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }, + { name: "deltaGlyphID", type: "USHORT", value: subtable.deltaGlyphId } + ]); + } else { + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 2 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.ushortList("substitute", subtable.substitute))); + } +}; +subtableMakers[2] = function makeLookup2(subtable) { + check.assert(subtable.substFormat === 1, "Lookup type 2 substFormat must be 1."); + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 1 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.tableList("seqSet", subtable.sequences, function(sequenceSet) { + return new table.Table("sequenceSetTable", table.ushortList("sequence", sequenceSet)); + }))); +}; +subtableMakers[3] = function makeLookup3(subtable) { + check.assert(subtable.substFormat === 1, "Lookup type 3 substFormat must be 1."); + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 1 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.tableList("altSet", subtable.alternateSets, function(alternateSet) { + return new table.Table("alternateSetTable", table.ushortList("alternate", alternateSet)); + }))); +}; +subtableMakers[4] = function makeLookup4(subtable) { + check.assert(subtable.substFormat === 1, "Lookup type 4 substFormat must be 1."); + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 1 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.tableList("ligSet", subtable.ligatureSets, function(ligatureSet) { + return new table.Table("ligatureSetTable", table.tableList("ligature", ligatureSet, function(ligature) { + return new table.Table("ligatureTable", [{ name: "ligGlyph", type: "USHORT", value: ligature.ligGlyph }].concat(table.ushortList("component", ligature.components, ligature.components.length + 1))); + })); + }))); +}; +subtableMakers[6] = function makeLookup6(subtable) { + if (subtable.substFormat === 1) { + var returnTable = new table.Table("chainContextTable", [ + { name: "substFormat", type: "USHORT", value: subtable.substFormat }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.tableList("chainRuleSet", subtable.chainRuleSets, function(chainRuleSet) { + return new table.Table("chainRuleSetTable", table.tableList("chainRule", chainRuleSet, function(chainRule) { + var tableData2 = table.ushortList("backtrackGlyph", chainRule.backtrack, chainRule.backtrack.length).concat(table.ushortList("inputGlyph", chainRule.input, chainRule.input.length + 1)).concat(table.ushortList("lookaheadGlyph", chainRule.lookahead, chainRule.lookahead.length)).concat(table.ushortList("substitution", [], chainRule.lookupRecords.length)); + chainRule.lookupRecords.forEach(function(record, i) { + tableData2 = tableData2.concat({ name: "sequenceIndex" + i, type: "USHORT", value: record.sequenceIndex }).concat({ name: "lookupListIndex" + i, type: "USHORT", value: record.lookupListIndex }); + }); + return new table.Table("chainRuleTable", tableData2); + })); + }))); + return returnTable; + } else if (subtable.substFormat === 2) { + check.assert(false, "lookup type 6 format 2 is not yet supported."); + } else if (subtable.substFormat === 3) { + var tableData = [ + { name: "substFormat", type: "USHORT", value: subtable.substFormat } + ]; + tableData.push({ name: "backtrackGlyphCount", type: "USHORT", value: subtable.backtrackCoverage.length }); + subtable.backtrackCoverage.forEach(function(coverage, i) { + tableData.push({ name: "backtrackCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) }); + }); + tableData.push({ name: "inputGlyphCount", type: "USHORT", value: subtable.inputCoverage.length }); + subtable.inputCoverage.forEach(function(coverage, i) { + tableData.push({ name: "inputCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) }); + }); + tableData.push({ name: "lookaheadGlyphCount", type: "USHORT", value: subtable.lookaheadCoverage.length }); + subtable.lookaheadCoverage.forEach(function(coverage, i) { + tableData.push({ name: "lookaheadCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) }); + }); + tableData.push({ name: "substitutionCount", type: "USHORT", value: subtable.lookupRecords.length }); + subtable.lookupRecords.forEach(function(record, i) { + tableData = tableData.concat({ name: "sequenceIndex" + i, type: "USHORT", value: record.sequenceIndex }).concat({ name: "lookupListIndex" + i, type: "USHORT", value: record.lookupListIndex }); + }); + var returnTable$1 = new table.Table("chainContextTable", tableData); + return returnTable$1; + } + check.assert(false, "lookup type 6 format must be 1, 2 or 3."); +}; +function makeGsubTable(gsub) { + return new table.Table("GSUB", [ + { name: "version", type: "ULONG", value: 65536 }, + { name: "scripts", type: "TABLE", value: new table.ScriptList(gsub.scripts) }, + { name: "features", type: "TABLE", value: new table.FeatureList(gsub.features) }, + { name: "lookups", type: "TABLE", value: new table.LookupList(gsub.lookups, subtableMakers) } + ]); +} +var gsub = { parse: parseGsubTable, make: makeGsubTable }; +function parseMetaTable(data2, start) { + var p = new parse.Parser(data2, start); + var tableVersion = p.parseULong(); + check.argument(tableVersion === 1, "Unsupported META table version."); + p.parseULong(); + p.parseULong(); + var numDataMaps = p.parseULong(); + var tags = {}; + for (var i = 0;i < numDataMaps; i++) { + var tag = p.parseTag(); + var dataOffset = p.parseULong(); + var dataLength = p.parseULong(); + var text2 = decode.UTF8(data2, start + dataOffset, dataLength); + tags[tag] = text2; + } + return tags; +} +function makeMetaTable(tags) { + var numTags = Object.keys(tags).length; + var stringPool = ""; + var stringPoolOffset = 16 + numTags * 12; + var result = new table.Table("meta", [ + { name: "version", type: "ULONG", value: 1 }, + { name: "flags", type: "ULONG", value: 0 }, + { name: "offset", type: "ULONG", value: stringPoolOffset }, + { name: "numTags", type: "ULONG", value: numTags } + ]); + for (var tag in tags) { + var pos = stringPool.length; + stringPool += tags[tag]; + result.fields.push({ name: "tag " + tag, type: "TAG", value: tag }); + result.fields.push({ name: "offset " + tag, type: "ULONG", value: stringPoolOffset + pos }); + result.fields.push({ name: "length " + tag, type: "ULONG", value: tags[tag].length }); + } + result.fields.push({ name: "stringPool", type: "CHARARRAY", value: stringPool }); + return result; +} +var meta = { parse: parseMetaTable, make: makeMetaTable }; +function parseColrTable(data2, start) { + var p = new Parser(data2, start); + var version = p.parseUShort(); + check.argument(version === 0, "Only COLRv0 supported."); + var numBaseGlyphRecords = p.parseUShort(); + var baseGlyphRecordsOffset = p.parseOffset32(); + var layerRecordsOffset = p.parseOffset32(); + var numLayerRecords = p.parseUShort(); + p.relativeOffset = baseGlyphRecordsOffset; + var baseGlyphRecords = p.parseRecordList(numBaseGlyphRecords, { + glyphID: Parser.uShort, + firstLayerIndex: Parser.uShort, + numLayers: Parser.uShort + }); + p.relativeOffset = layerRecordsOffset; + var layerRecords = p.parseRecordList(numLayerRecords, { + glyphID: Parser.uShort, + paletteIndex: Parser.uShort + }); + return { + version, + baseGlyphRecords, + layerRecords + }; +} +function makeColrTable(ref) { + var version = ref.version; + if (version === undefined) + version = 0; + var baseGlyphRecords = ref.baseGlyphRecords; + if (baseGlyphRecords === undefined) + baseGlyphRecords = []; + var layerRecords = ref.layerRecords; + if (layerRecords === undefined) + layerRecords = []; + check.argument(version === 0, "Only COLRv0 supported."); + var baseGlyphRecordsOffset = 14; + var layerRecordsOffset = baseGlyphRecordsOffset + baseGlyphRecords.length * 6; + return new table.Table("COLR", [ + { name: "version", type: "USHORT", value: version }, + { name: "numBaseGlyphRecords", type: "USHORT", value: baseGlyphRecords.length }, + { name: "baseGlyphRecordsOffset", type: "ULONG", value: baseGlyphRecordsOffset }, + { name: "layerRecordsOffset", type: "ULONG", value: layerRecordsOffset }, + { name: "numLayerRecords", type: "USHORT", value: layerRecords.length } + ].concat(baseGlyphRecords.map(function(glyph, i) { + return [ + { name: "glyphID_" + i, type: "USHORT", value: glyph.glyphID }, + { name: "firstLayerIndex_" + i, type: "USHORT", value: glyph.firstLayerIndex }, + { name: "numLayers_" + i, type: "USHORT", value: glyph.numLayers } + ]; + }).flat(), layerRecords.map(function(layer, i) { + return [ + { name: "LayerGlyphID_" + i, type: "USHORT", value: layer.glyphID }, + { name: "paletteIndex_" + i, type: "USHORT", value: layer.paletteIndex } + ]; + }).flat())); +} +var colr = { parse: parseColrTable, make: makeColrTable }; +function parseCpalTable(data2, start) { + var p = new Parser(data2, start); + var version = p.parseShort(); + var numPaletteEntries = p.parseShort(); + var numPalettes = p.parseShort(); + var numColorRecords = p.parseShort(); + var colorRecordsArrayOffset = p.parseOffset32(); + var colorRecordIndices = p.parseUShortList(numPalettes); + p.relativeOffset = colorRecordsArrayOffset; + var colorRecords = p.parseULongList(numColorRecords); + return { + version, + numPaletteEntries, + colorRecords, + colorRecordIndices + }; +} +function makeCpalTable(ref) { + var version = ref.version; + if (version === undefined) + version = 0; + var numPaletteEntries = ref.numPaletteEntries; + if (numPaletteEntries === undefined) + numPaletteEntries = 0; + var colorRecords = ref.colorRecords; + if (colorRecords === undefined) + colorRecords = []; + var colorRecordIndices = ref.colorRecordIndices; + if (colorRecordIndices === undefined) + colorRecordIndices = [0]; + check.argument(version === 0, "Only CPALv0 are supported."); + check.argument(colorRecords.length, "No colorRecords given."); + check.argument(colorRecordIndices.length, "No colorRecordIndices given."); + check.argument(!numPaletteEntries && colorRecordIndices.length == 1, "Can't infer numPaletteEntries on multiple colorRecordIndices"); + return new table.Table("CPAL", [ + { name: "version", type: "USHORT", value: version }, + { name: "numPaletteEntries", type: "USHORT", value: numPaletteEntries || colorRecords.length }, + { name: "numPalettes", type: "USHORT", value: colorRecordIndices.length }, + { name: "numColorRecords", type: "USHORT", value: colorRecords.length }, + { name: "colorRecordsArrayOffset", type: "ULONG", value: 12 + 2 * colorRecordIndices.length } + ].concat(colorRecordIndices.map(function(palette, i) { + return { name: "colorRecordIndices_" + i, type: "USHORT", value: palette }; + }), colorRecords.map(function(color, i) { + return { name: "colorRecords_" + i, type: "ULONG", value: color }; + }))); +} +var cpal = { parse: parseCpalTable, make: makeCpalTable }; +function log2(v) { + return Math.log(v) / Math.log(2) | 0; +} +function computeCheckSum(bytes) { + while (bytes.length % 4 !== 0) { + bytes.push(0); + } + var sum2 = 0; + for (var i = 0;i < bytes.length; i += 4) { + sum2 += (bytes[i] << 24) + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + bytes[i + 3]; + } + sum2 %= Math.pow(2, 32); + return sum2; +} +function makeTableRecord(tag, checkSum, offset, length2) { + return new table.Record("Table Record", [ + { name: "tag", type: "TAG", value: tag !== undefined ? tag : "" }, + { name: "checkSum", type: "ULONG", value: checkSum !== undefined ? checkSum : 0 }, + { name: "offset", type: "ULONG", value: offset !== undefined ? offset : 0 }, + { name: "length", type: "ULONG", value: length2 !== undefined ? length2 : 0 } + ]); +} +function makeSfntTable(tables) { + var sfnt = new table.Table("sfnt", [ + { name: "version", type: "TAG", value: "OTTO" }, + { name: "numTables", type: "USHORT", value: 0 }, + { name: "searchRange", type: "USHORT", value: 0 }, + { name: "entrySelector", type: "USHORT", value: 0 }, + { name: "rangeShift", type: "USHORT", value: 0 } + ]); + sfnt.tables = tables; + sfnt.numTables = tables.length; + var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables)); + sfnt.searchRange = 16 * highestPowerOf2; + sfnt.entrySelector = log2(highestPowerOf2); + sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange; + var recordFields = []; + var tableFields = []; + var offset = sfnt.sizeOf() + makeTableRecord().sizeOf() * sfnt.numTables; + while (offset % 4 !== 0) { + offset += 1; + tableFields.push({ name: "padding", type: "BYTE", value: 0 }); + } + for (var i = 0;i < tables.length; i += 1) { + var t2 = tables[i]; + check.argument(t2.tableName.length === 4, "Table name" + t2.tableName + " is invalid."); + var tableLength = t2.sizeOf(); + var tableRecord = makeTableRecord(t2.tableName, computeCheckSum(t2.encode()), offset, tableLength); + recordFields.push({ name: tableRecord.tag + " Table Record", type: "RECORD", value: tableRecord }); + tableFields.push({ name: t2.tableName + " table", type: "RECORD", value: t2 }); + offset += tableLength; + check.argument(!isNaN(offset), "Something went wrong calculating the offset."); + while (offset % 4 !== 0) { + offset += 1; + tableFields.push({ name: "padding", type: "BYTE", value: 0 }); + } + } + recordFields.sort(function(r1, r2) { + if (r1.value.tag > r2.value.tag) { + return 1; + } else { + return -1; + } + }); + sfnt.fields = sfnt.fields.concat(recordFields); + sfnt.fields = sfnt.fields.concat(tableFields); + return sfnt; +} +function metricsForChar(font, chars, notFoundMetrics) { + for (var i = 0;i < chars.length; i += 1) { + var glyphIndex = font.charToGlyphIndex(chars[i]); + if (glyphIndex > 0) { + var glyph = font.glyphs.get(glyphIndex); + return glyph.getMetrics(); + } + } + return notFoundMetrics; +} +function average(vs) { + var sum2 = 0; + for (var i = 0;i < vs.length; i += 1) { + sum2 += vs[i]; + } + return sum2 / vs.length; +} +function fontToSfntTable(font) { + var xMins = []; + var yMins = []; + var xMaxs = []; + var yMaxs = []; + var advanceWidths = []; + var leftSideBearings = []; + var rightSideBearings = []; + var firstCharIndex; + var lastCharIndex = 0; + var ulUnicodeRange1 = 0; + var ulUnicodeRange2 = 0; + var ulUnicodeRange3 = 0; + var ulUnicodeRange4 = 0; + for (var i = 0;i < font.glyphs.length; i += 1) { + var glyph = font.glyphs.get(i); + var unicode = glyph.unicode | 0; + if (isNaN(glyph.advanceWidth)) { + throw new Error("Glyph " + glyph.name + " (" + i + "): advanceWidth is not a number."); + } + if (firstCharIndex > unicode || firstCharIndex === undefined) { + if (unicode > 0) { + firstCharIndex = unicode; + } + } + if (lastCharIndex < unicode) { + lastCharIndex = unicode; + } + var position2 = os2.getUnicodeRange(unicode); + if (position2 < 32) { + ulUnicodeRange1 |= 1 << position2; + } else if (position2 < 64) { + ulUnicodeRange2 |= 1 << position2 - 32; + } else if (position2 < 96) { + ulUnicodeRange3 |= 1 << position2 - 64; + } else if (position2 < 123) { + ulUnicodeRange4 |= 1 << position2 - 96; + } else { + throw new Error("Unicode ranges bits > 123 are reserved for internal usage"); + } + if (glyph.name === ".notdef") { + continue; + } + var metrics = glyph.getMetrics(); + xMins.push(metrics.xMin); + yMins.push(metrics.yMin); + xMaxs.push(metrics.xMax); + yMaxs.push(metrics.yMax); + leftSideBearings.push(metrics.leftSideBearing); + rightSideBearings.push(metrics.rightSideBearing); + advanceWidths.push(glyph.advanceWidth); + } + var globals = { + xMin: Math.min.apply(null, xMins), + yMin: Math.min.apply(null, yMins), + xMax: Math.max.apply(null, xMaxs), + yMax: Math.max.apply(null, yMaxs), + advanceWidthMax: Math.max.apply(null, advanceWidths), + advanceWidthAvg: average(advanceWidths), + minLeftSideBearing: Math.min.apply(null, leftSideBearings), + maxLeftSideBearing: Math.max.apply(null, leftSideBearings), + minRightSideBearing: Math.min.apply(null, rightSideBearings) + }; + globals.ascender = font.ascender; + globals.descender = font.descender; + var headTable = head.make({ + flags: 3, + unitsPerEm: font.unitsPerEm, + xMin: globals.xMin, + yMin: globals.yMin, + xMax: globals.xMax, + yMax: globals.yMax, + lowestRecPPEM: 3, + createdTimestamp: font.createdTimestamp + }); + var hheaTable = hhea.make({ + ascender: globals.ascender, + descender: globals.descender, + advanceWidthMax: globals.advanceWidthMax, + minLeftSideBearing: globals.minLeftSideBearing, + minRightSideBearing: globals.minRightSideBearing, + xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin), + numberOfHMetrics: font.glyphs.length + }); + var maxpTable = maxp.make(font.glyphs.length); + var os2Table = os2.make(Object.assign({ + xAvgCharWidth: Math.round(globals.advanceWidthAvg), + usFirstCharIndex: firstCharIndex, + usLastCharIndex: lastCharIndex, + ulUnicodeRange1, + ulUnicodeRange2, + ulUnicodeRange3, + ulUnicodeRange4, + sTypoAscender: globals.ascender, + sTypoDescender: globals.descender, + sTypoLineGap: 0, + usWinAscent: globals.yMax, + usWinDescent: Math.abs(globals.yMin), + ulCodePageRange1: 1, + sxHeight: metricsForChar(font, "xyvw", { yMax: Math.round(globals.ascender / 2) }).yMax, + sCapHeight: metricsForChar(font, "HIKLEFJMNTZBDPRAGOQSUVWXY", globals).yMax, + usDefaultChar: font.hasChar(" ") ? 32 : 0, + usBreakChar: font.hasChar(" ") ? 32 : 0 + }, font.tables.os2)); + var hmtxTable = hmtx.make(font.glyphs); + var cmapTable = cmap.make(font.glyphs); + var englishFamilyName = font.getEnglishName("fontFamily"); + var englishStyleName = font.getEnglishName("fontSubfamily"); + var englishFullName = englishFamilyName + " " + englishStyleName; + var postScriptName = font.getEnglishName("postScriptName"); + if (!postScriptName) { + postScriptName = englishFamilyName.replace(/\s/g, "") + "-" + englishStyleName; + } + var names = {}; + for (var n2 in font.names) { + names[n2] = font.names[n2]; + } + if (!names.uniqueID) { + names.uniqueID = { en: font.getEnglishName("manufacturer") + ":" + englishFullName }; + } + if (!names.postScriptName) { + names.postScriptName = { en: postScriptName }; + } + if (!names.preferredFamily) { + names.preferredFamily = font.names.fontFamily; + } + if (!names.preferredSubfamily) { + names.preferredSubfamily = font.names.fontSubfamily; + } + var languageTags = []; + var nameTable = _name.make(names, languageTags); + var ltagTable = languageTags.length > 0 ? ltag.make(languageTags) : undefined; + var postTable = post.make(); + var cffTable = cff.make(font.glyphs, { + version: font.getEnglishName("version"), + fullName: englishFullName, + familyName: englishFamilyName, + weightName: englishStyleName, + postScriptName, + unitsPerEm: font.unitsPerEm, + fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax] + }); + var metaTable = font.metas && Object.keys(font.metas).length > 0 ? meta.make(font.metas) : undefined; + var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable]; + if (ltagTable) { + tables.push(ltagTable); + } + if (font.tables.gsub) { + tables.push(gsub.make(font.tables.gsub)); + } + if (font.tables.cpal) { + tables.push(cpal.make(font.tables.cpal)); + } + if (font.tables.colr) { + tables.push(colr.make(font.tables.colr)); + } + if (metaTable) { + tables.push(metaTable); + } + var sfntTable = makeSfntTable(tables); + var bytes = sfntTable.encode(); + var checkSum = computeCheckSum(bytes); + var tableFields = sfntTable.fields; + var checkSumAdjusted = false; + for (var i$1 = 0;i$1 < tableFields.length; i$1 += 1) { + if (tableFields[i$1].name === "head table") { + tableFields[i$1].value.checkSumAdjustment = 2981146554 - checkSum; + checkSumAdjusted = true; + break; + } + } + if (!checkSumAdjusted) { + throw new Error("Could not find head table with checkSum to adjust."); + } + return sfntTable; +} +var sfnt = { make: makeSfntTable, fontToTable: fontToSfntTable, computeCheckSum }; +function searchTag(arr, tag) { + var imin = 0; + var imax = arr.length - 1; + while (imin <= imax) { + var imid = imin + imax >>> 1; + var val2 = arr[imid].tag; + if (val2 === tag) { + return imid; + } else if (val2 < tag) { + imin = imid + 1; + } else { + imax = imid - 1; + } + } + return -imin - 1; +} +function binSearch(arr, value2) { + var imin = 0; + var imax = arr.length - 1; + while (imin <= imax) { + var imid = imin + imax >>> 1; + var val2 = arr[imid]; + if (val2 === value2) { + return imid; + } else if (val2 < value2) { + imin = imid + 1; + } else { + imax = imid - 1; + } + } + return -imin - 1; +} +function searchRange(ranges, value2) { + var range; + var imin = 0; + var imax = ranges.length - 1; + while (imin <= imax) { + var imid = imin + imax >>> 1; + range = ranges[imid]; + var start = range.start; + if (start === value2) { + return range; + } else if (start < value2) { + imin = imid + 1; + } else { + imax = imid - 1; + } + } + if (imin > 0) { + range = ranges[imin - 1]; + if (value2 > range.end) { + return 0; + } + return range; + } +} +function Layout(font, tableName) { + this.font = font; + this.tableName = tableName; +} +Layout.prototype = { + searchTag, + binSearch, + getTable: function(create) { + var layout = this.font.tables[this.tableName]; + if (!layout && create) { + layout = this.font.tables[this.tableName] = this.createDefaultTable(); + } + return layout; + }, + getScriptNames: function() { + var layout = this.getTable(); + if (!layout) { + return []; + } + return layout.scripts.map(function(script) { + return script.tag; + }); + }, + getDefaultScriptName: function() { + var layout = this.getTable(); + if (!layout) { + return; + } + var hasLatn = false; + for (var i = 0;i < layout.scripts.length; i++) { + var name2 = layout.scripts[i].tag; + if (name2 === "DFLT") { + return name2; + } + if (name2 === "latn") { + hasLatn = true; + } + } + if (hasLatn) { + return "latn"; + } + }, + getScriptTable: function(script, create) { + var layout = this.getTable(create); + if (layout) { + script = script || "DFLT"; + var scripts = layout.scripts; + var pos = searchTag(layout.scripts, script); + if (pos >= 0) { + return scripts[pos].script; + } else if (create) { + var scr = { + tag: script, + script: { + defaultLangSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] }, + langSysRecords: [] + } + }; + scripts.splice(-1 - pos, 0, scr); + return scr.script; + } + } + }, + getLangSysTable: function(script, language, create) { + var scriptTable = this.getScriptTable(script, create); + if (scriptTable) { + if (!language || language === "dflt" || language === "DFLT") { + return scriptTable.defaultLangSys; + } + var pos = searchTag(scriptTable.langSysRecords, language); + if (pos >= 0) { + return scriptTable.langSysRecords[pos].langSys; + } else if (create) { + var langSysRecord = { + tag: language, + langSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] } + }; + scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord); + return langSysRecord.langSys; + } + } + }, + getFeatureTable: function(script, language, feature, create) { + var langSysTable2 = this.getLangSysTable(script, language, create); + if (langSysTable2) { + var featureRecord; + var featIndexes = langSysTable2.featureIndexes; + var allFeatures = this.font.tables[this.tableName].features; + for (var i = 0;i < featIndexes.length; i++) { + featureRecord = allFeatures[featIndexes[i]]; + if (featureRecord.tag === feature) { + return featureRecord.feature; + } + } + if (create) { + var index2 = allFeatures.length; + check.assert(index2 === 0 || feature >= allFeatures[index2 - 1].tag, "Features must be added in alphabetical order."); + featureRecord = { + tag: feature, + feature: { params: 0, lookupListIndexes: [] } + }; + allFeatures.push(featureRecord); + featIndexes.push(index2); + return featureRecord.feature; + } + } + }, + getLookupTables: function(script, language, feature, lookupType, create) { + var featureTable = this.getFeatureTable(script, language, feature, create); + var tables = []; + if (featureTable) { + var lookupTable; + var lookupListIndexes = featureTable.lookupListIndexes; + var allLookups = this.font.tables[this.tableName].lookups; + for (var i = 0;i < lookupListIndexes.length; i++) { + lookupTable = allLookups[lookupListIndexes[i]]; + if (lookupTable.lookupType === lookupType) { + tables.push(lookupTable); + } + } + if (tables.length === 0 && create) { + lookupTable = { + lookupType, + lookupFlag: 0, + subtables: [], + markFilteringSet: undefined + }; + var index2 = allLookups.length; + allLookups.push(lookupTable); + lookupListIndexes.push(index2); + return [lookupTable]; + } + } + return tables; + }, + getGlyphClass: function(classDefTable, glyphIndex) { + switch (classDefTable.format) { + case 1: + if (classDefTable.startGlyph <= glyphIndex && glyphIndex < classDefTable.startGlyph + classDefTable.classes.length) { + return classDefTable.classes[glyphIndex - classDefTable.startGlyph]; + } + return 0; + case 2: + var range = searchRange(classDefTable.ranges, glyphIndex); + return range ? range.classId : 0; + } + }, + getCoverageIndex: function(coverageTable, glyphIndex) { + switch (coverageTable.format) { + case 1: + var index2 = binSearch(coverageTable.glyphs, glyphIndex); + return index2 >= 0 ? index2 : -1; + case 2: + var range = searchRange(coverageTable.ranges, glyphIndex); + return range ? range.index + glyphIndex - range.start : -1; + } + }, + expandCoverage: function(coverageTable) { + if (coverageTable.format === 1) { + return coverageTable.glyphs; + } else { + var glyphs = []; + var ranges = coverageTable.ranges; + for (var i = 0;i < ranges.length; i++) { + var range = ranges[i]; + var start = range.start; + var end = range.end; + for (var j2 = start;j2 <= end; j2++) { + glyphs.push(j2); + } + } + return glyphs; + } + } +}; +function Position(font) { + Layout.call(this, font, "gpos"); +} +Position.prototype = Layout.prototype; +Position.prototype.init = function() { + var script = this.getDefaultScriptName(); + this.defaultKerningTables = this.getKerningTables(script); +}; +Position.prototype.getKerningValue = function(kerningLookups, leftIndex, rightIndex) { + for (var i = 0;i < kerningLookups.length; i++) { + var subtables = kerningLookups[i].subtables; + for (var j2 = 0;j2 < subtables.length; j2++) { + var subtable = subtables[j2]; + var covIndex = this.getCoverageIndex(subtable.coverage, leftIndex); + if (covIndex < 0) { + continue; + } + switch (subtable.posFormat) { + case 1: + var pairSet = subtable.pairSets[covIndex]; + for (var k2 = 0;k2 < pairSet.length; k2++) { + var pair = pairSet[k2]; + if (pair.secondGlyph === rightIndex) { + return pair.value1 && pair.value1.xAdvance || 0; + } + } + break; + case 2: + var class1 = this.getGlyphClass(subtable.classDef1, leftIndex); + var class2 = this.getGlyphClass(subtable.classDef2, rightIndex); + var pair$1 = subtable.classRecords[class1][class2]; + return pair$1.value1 && pair$1.value1.xAdvance || 0; + } + } + } + return 0; +}; +Position.prototype.getKerningTables = function(script, language) { + if (this.font.tables.gpos) { + return this.getLookupTables(script, language, "kern", 2); + } +}; +function Substitution(font) { + Layout.call(this, font, "gsub"); +} +function arraysEqual2(ar1, ar2) { + var n2 = ar1.length; + if (n2 !== ar2.length) { + return false; + } + for (var i = 0;i < n2; i++) { + if (ar1[i] !== ar2[i]) { + return false; + } + } + return true; +} +function getSubstFormat(lookupTable, format, defaultSubtable) { + var subtables = lookupTable.subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + if (subtable.substFormat === format) { + return subtable; + } + } + if (defaultSubtable) { + subtables.push(defaultSubtable); + return defaultSubtable; + } + return; +} +Substitution.prototype = Layout.prototype; +Substitution.prototype.createDefaultTable = function() { + return { + version: 1, + scripts: [{ + tag: "DFLT", + script: { + defaultLangSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] }, + langSysRecords: [] + } + }], + features: [], + lookups: [] + }; +}; +Substitution.prototype.getSingle = function(feature, script, language) { + var substitutions = []; + var lookupTables = this.getLookupTables(script, language, feature, 1); + for (var idx = 0;idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var j2 = undefined; + if (subtable.substFormat === 1) { + var delta = subtable.deltaGlyphId; + for (j2 = 0;j2 < glyphs.length; j2++) { + var glyph = glyphs[j2]; + substitutions.push({ sub: glyph, by: glyph + delta }); + } + } else { + var substitute = subtable.substitute; + for (j2 = 0;j2 < glyphs.length; j2++) { + substitutions.push({ sub: glyphs[j2], by: substitute[j2] }); + } + } + } + } + return substitutions; +}; +Substitution.prototype.getMultiple = function(feature, script, language) { + var substitutions = []; + var lookupTables = this.getLookupTables(script, language, feature, 2); + for (var idx = 0;idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var j2 = undefined; + for (j2 = 0;j2 < glyphs.length; j2++) { + var glyph = glyphs[j2]; + var replacements = subtable.sequences[j2]; + substitutions.push({ sub: glyph, by: replacements }); + } + } + } + return substitutions; +}; +Substitution.prototype.getAlternates = function(feature, script, language) { + var alternates = []; + var lookupTables = this.getLookupTables(script, language, feature, 3); + for (var idx = 0;idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var alternateSets = subtable.alternateSets; + for (var j2 = 0;j2 < glyphs.length; j2++) { + alternates.push({ sub: glyphs[j2], by: alternateSets[j2] }); + } + } + } + return alternates; +}; +Substitution.prototype.getLigatures = function(feature, script, language) { + var ligatures = []; + var lookupTables = this.getLookupTables(script, language, feature, 4); + for (var idx = 0;idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var ligatureSets = subtable.ligatureSets; + for (var j2 = 0;j2 < glyphs.length; j2++) { + var startGlyph = glyphs[j2]; + var ligSet = ligatureSets[j2]; + for (var k2 = 0;k2 < ligSet.length; k2++) { + var lig = ligSet[k2]; + ligatures.push({ + sub: [startGlyph].concat(lig.components), + by: lig.ligGlyph + }); + } + } + } + } + return ligatures; +}; +Substitution.prototype.addSingle = function(feature, substitution, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 1, true)[0]; + var subtable = getSubstFormat(lookupTable, 2, { + substFormat: 2, + coverage: { format: 1, glyphs: [] }, + substitute: [] + }); + check.assert(subtable.coverage.format === 1, "Single: unable to modify coverage table format " + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.substitute.splice(pos, 0, 0); + } + subtable.substitute[pos] = substitution.by; +}; +Substitution.prototype.addMultiple = function(feature, substitution, script, language) { + check.assert(substitution.by instanceof Array && substitution.by.length > 1, 'Multiple: "by" must be an array of two or more ids'); + var lookupTable = this.getLookupTables(script, language, feature, 2, true)[0]; + var subtable = getSubstFormat(lookupTable, 1, { + substFormat: 1, + coverage: { format: 1, glyphs: [] }, + sequences: [] + }); + check.assert(subtable.coverage.format === 1, "Multiple: unable to modify coverage table format " + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.sequences.splice(pos, 0, 0); + } + subtable.sequences[pos] = substitution.by; +}; +Substitution.prototype.addAlternate = function(feature, substitution, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 3, true)[0]; + var subtable = getSubstFormat(lookupTable, 1, { + substFormat: 1, + coverage: { format: 1, glyphs: [] }, + alternateSets: [] + }); + check.assert(subtable.coverage.format === 1, "Alternate: unable to modify coverage table format " + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.alternateSets.splice(pos, 0, 0); + } + subtable.alternateSets[pos] = substitution.by; +}; +Substitution.prototype.addLigature = function(feature, ligature, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 4, true)[0]; + var subtable = lookupTable.subtables[0]; + if (!subtable) { + subtable = { + substFormat: 1, + coverage: { format: 1, glyphs: [] }, + ligatureSets: [] + }; + lookupTable.subtables[0] = subtable; + } + check.assert(subtable.coverage.format === 1, "Ligature: unable to modify coverage table format " + subtable.coverage.format); + var coverageGlyph = ligature.sub[0]; + var ligComponents = ligature.sub.slice(1); + var ligatureTable = { + ligGlyph: ligature.by, + components: ligComponents + }; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos >= 0) { + var ligatureSet = subtable.ligatureSets[pos]; + for (var i = 0;i < ligatureSet.length; i++) { + if (arraysEqual2(ligatureSet[i].components, ligComponents)) { + return; + } + } + ligatureSet.push(ligatureTable); + } else { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.ligatureSets.splice(pos, 0, [ligatureTable]); + } +}; +Substitution.prototype.getFeature = function(feature, script, language) { + if (/ss\d\d/.test(feature)) { + return this.getSingle(feature, script, language); + } + switch (feature) { + case "aalt": + case "salt": + return this.getSingle(feature, script, language).concat(this.getAlternates(feature, script, language)); + case "dlig": + case "liga": + case "rlig": + return this.getLigatures(feature, script, language); + case "ccmp": + return this.getMultiple(feature, script, language).concat(this.getLigatures(feature, script, language)); + case "stch": + return this.getMultiple(feature, script, language); + } + return; +}; +Substitution.prototype.add = function(feature, sub2, script, language) { + if (/ss\d\d/.test(feature)) { + return this.addSingle(feature, sub2, script, language); + } + switch (feature) { + case "aalt": + case "salt": + if (typeof sub2.by === "number") { + return this.addSingle(feature, sub2, script, language); + } + return this.addAlternate(feature, sub2, script, language); + case "dlig": + case "liga": + case "rlig": + return this.addLigature(feature, sub2, script, language); + case "ccmp": + if (sub2.by instanceof Array) { + return this.addMultiple(feature, sub2, script, language); + } + return this.addLigature(feature, sub2, script, language); + } + return; +}; +function checkArgument(expression, message) { + if (!expression) { + throw message; + } +} +function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { + var v; + if ((flag & shortVectorBitMask) > 0) { + v = p.parseByte(); + if ((flag & sameBitMask) === 0) { + v = -v; + } + v = previousValue + v; + } else { + if ((flag & sameBitMask) > 0) { + v = previousValue; + } else { + v = previousValue + p.parseShort(); + } + } + return v; +} +function parseGlyph(glyph, data2, start) { + var p = new parse.Parser(data2, start); + glyph.numberOfContours = p.parseShort(); + glyph._xMin = p.parseShort(); + glyph._yMin = p.parseShort(); + glyph._xMax = p.parseShort(); + glyph._yMax = p.parseShort(); + var flags; + var flag; + if (glyph.numberOfContours > 0) { + var endPointIndices = glyph.endPointIndices = []; + for (var i = 0;i < glyph.numberOfContours; i += 1) { + endPointIndices.push(p.parseUShort()); + } + glyph.instructionLength = p.parseUShort(); + glyph.instructions = []; + for (var i$1 = 0;i$1 < glyph.instructionLength; i$1 += 1) { + glyph.instructions.push(p.parseByte()); + } + var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; + flags = []; + for (var i$2 = 0;i$2 < numberOfCoordinates; i$2 += 1) { + flag = p.parseByte(); + flags.push(flag); + if ((flag & 8) > 0) { + var repeatCount = p.parseByte(); + for (var j2 = 0;j2 < repeatCount; j2 += 1) { + flags.push(flag); + i$2 += 1; + } + } + } + check.argument(flags.length === numberOfCoordinates, "Bad flags."); + if (endPointIndices.length > 0) { + var points = []; + var point; + if (numberOfCoordinates > 0) { + for (var i$3 = 0;i$3 < numberOfCoordinates; i$3 += 1) { + flag = flags[i$3]; + point = {}; + point.onCurve = !!(flag & 1); + point.lastPointOfContour = endPointIndices.indexOf(i$3) >= 0; + points.push(point); + } + var px2 = 0; + for (var i$4 = 0;i$4 < numberOfCoordinates; i$4 += 1) { + flag = flags[i$4]; + point = points[i$4]; + point.x = parseGlyphCoordinate(p, flag, px2, 2, 16); + px2 = point.x; + } + var py2 = 0; + for (var i$5 = 0;i$5 < numberOfCoordinates; i$5 += 1) { + flag = flags[i$5]; + point = points[i$5]; + point.y = parseGlyphCoordinate(p, flag, py2, 4, 32); + py2 = point.y; + } + } + glyph.points = points; + } else { + glyph.points = []; + } + } else if (glyph.numberOfContours === 0) { + glyph.points = []; + } else { + glyph.isComposite = true; + glyph.points = []; + glyph.components = []; + var moreComponents = true; + while (moreComponents) { + flags = p.parseUShort(); + var component = { + glyphIndex: p.parseUShort(), + xScale: 1, + scale01: 0, + scale10: 0, + yScale: 1, + dx: 0, + dy: 0 + }; + if ((flags & 1) > 0) { + if ((flags & 2) > 0) { + component.dx = p.parseShort(); + component.dy = p.parseShort(); + } else { + component.matchedPoints = [p.parseUShort(), p.parseUShort()]; + } + } else { + if ((flags & 2) > 0) { + component.dx = p.parseChar(); + component.dy = p.parseChar(); + } else { + component.matchedPoints = [p.parseByte(), p.parseByte()]; + } + } + if ((flags & 8) > 0) { + component.xScale = component.yScale = p.parseF2Dot14(); + } else if ((flags & 64) > 0) { + component.xScale = p.parseF2Dot14(); + component.yScale = p.parseF2Dot14(); + } else if ((flags & 128) > 0) { + component.xScale = p.parseF2Dot14(); + component.scale01 = p.parseF2Dot14(); + component.scale10 = p.parseF2Dot14(); + component.yScale = p.parseF2Dot14(); + } + glyph.components.push(component); + moreComponents = !!(flags & 32); + } + if (flags & 256) { + glyph.instructionLength = p.parseUShort(); + glyph.instructions = []; + for (var i$6 = 0;i$6 < glyph.instructionLength; i$6 += 1) { + glyph.instructions.push(p.parseByte()); + } + } + } +} +function transformPoints(points, transform2) { + var newPoints = []; + for (var i = 0;i < points.length; i += 1) { + var pt = points[i]; + var newPt = { + x: transform2.xScale * pt.x + transform2.scale01 * pt.y + transform2.dx, + y: transform2.scale10 * pt.x + transform2.yScale * pt.y + transform2.dy, + onCurve: pt.onCurve, + lastPointOfContour: pt.lastPointOfContour + }; + newPoints.push(newPt); + } + return newPoints; +} +function getContours(points) { + var contours = []; + var currentContour = []; + for (var i = 0;i < points.length; i += 1) { + var pt = points[i]; + currentContour.push(pt); + if (pt.lastPointOfContour) { + contours.push(currentContour); + currentContour = []; + } + } + check.argument(currentContour.length === 0, "There are still points left in the current contour."); + return contours; +} +function getPath(points) { + var p = new Path2; + if (!points) { + return p; + } + var contours = getContours(points); + for (var contourIndex = 0;contourIndex < contours.length; ++contourIndex) { + var contour = contours[contourIndex]; + var prev = null; + var curr = contour[contour.length - 1]; + var next = contour[0]; + if (curr.onCurve) { + p.moveTo(curr.x, curr.y); + } else { + if (next.onCurve) { + p.moveTo(next.x, next.y); + } else { + var start = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 }; + p.moveTo(start.x, start.y); + } + } + for (var i = 0;i < contour.length; ++i) { + prev = curr; + curr = next; + next = contour[(i + 1) % contour.length]; + if (curr.onCurve) { + p.lineTo(curr.x, curr.y); + } else { + var prev2 = prev; + var next2 = next; + if (!prev.onCurve) { + prev2 = { x: (curr.x + prev.x) * 0.5, y: (curr.y + prev.y) * 0.5 }; + } + if (!next.onCurve) { + next2 = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 }; + } + p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y); + } + } + p.closePath(); + } + return p; +} +function buildPath(glyphs, glyph) { + if (glyph.isComposite) { + for (var j2 = 0;j2 < glyph.components.length; j2 += 1) { + var component = glyph.components[j2]; + var componentGlyph = glyphs.get(component.glyphIndex); + componentGlyph.getPath(); + if (componentGlyph.points) { + var transformedPoints = undefined; + if (component.matchedPoints === undefined) { + transformedPoints = transformPoints(componentGlyph.points, component); + } else { + if (component.matchedPoints[0] > glyph.points.length - 1 || component.matchedPoints[1] > componentGlyph.points.length - 1) { + throw Error("Matched points out of range in " + glyph.name); + } + var firstPt = glyph.points[component.matchedPoints[0]]; + var secondPt = componentGlyph.points[component.matchedPoints[1]]; + var transform2 = { + xScale: component.xScale, + scale01: component.scale01, + scale10: component.scale10, + yScale: component.yScale, + dx: 0, + dy: 0 + }; + secondPt = transformPoints([secondPt], transform2)[0]; + transform2.dx = firstPt.x - secondPt.x; + transform2.dy = firstPt.y - secondPt.y; + transformedPoints = transformPoints(componentGlyph.points, transform2); + } + glyph.points = glyph.points.concat(transformedPoints); + } + } + } + return getPath(glyph.points); +} +function parseGlyfTableAll(data2, start, loca, font) { + var glyphs = new glyphset.GlyphSet(font); + for (var i = 0;i < loca.length - 1; i += 1) { + var offset = loca[i]; + var nextOffset = loca[i + 1]; + if (offset !== nextOffset) { + glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data2, start + offset, buildPath)); + } else { + glyphs.push(i, glyphset.glyphLoader(font, i)); + } + } + return glyphs; +} +function parseGlyfTableOnLowMemory(data2, start, loca, font) { + var glyphs = new glyphset.GlyphSet(font); + font._push = function(i) { + var offset = loca[i]; + var nextOffset = loca[i + 1]; + if (offset !== nextOffset) { + glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data2, start + offset, buildPath)); + } else { + glyphs.push(i, glyphset.glyphLoader(font, i)); + } + }; + return glyphs; +} +function parseGlyfTable(data2, start, loca, font, opt) { + if (opt.lowMemory) { + return parseGlyfTableOnLowMemory(data2, start, loca, font); + } else { + return parseGlyfTableAll(data2, start, loca, font); + } +} +var glyf = { getPath, parse: parseGlyfTable }; +var instructionTable; +var exec; +var execGlyph; +var execComponent; +function Hinting(font) { + this.font = font; + this.getCommands = function(hPoints) { + return glyf.getPath(hPoints).commands; + }; + this._fpgmState = this._prepState = undefined; + this._errorState = 0; +} +function roundOff(v) { + return v; +} +function roundToGrid(v) { + return Math.sign(v) * Math.round(Math.abs(v)); +} +function roundToDoubleGrid(v) { + return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2; +} +function roundToHalfGrid(v) { + return Math.sign(v) * (Math.round(Math.abs(v) + 0.5) - 0.5); +} +function roundUpToGrid(v) { + return Math.sign(v) * Math.ceil(Math.abs(v)); +} +function roundDownToGrid(v) { + return Math.sign(v) * Math.floor(Math.abs(v)); +} +var roundSuper = function(v) { + var period = this.srPeriod; + var phase = this.srPhase; + var threshold = this.srThreshold; + var sign2 = 1; + if (v < 0) { + v = -v; + sign2 = -1; + } + v += threshold - phase; + v = Math.trunc(v / period) * period; + v += phase; + if (v < 0) { + return phase * sign2; + } + return v * sign2; +}; +var xUnitVector = { + x: 1, + y: 0, + axis: "x", + distance: function(p1, p2, o1, o2) { + return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x); + }, + interpolate: function(p, rp1, rp2, pv) { + var do1; + var do2; + var doa1; + var doa2; + var dm1; + var dm2; + var dt; + if (!pv || pv === this) { + do1 = p.xo - rp1.xo; + do2 = p.xo - rp2.xo; + dm1 = rp1.x - rp1.xo; + dm2 = rp2.x - rp2.xo; + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + p.x = p.xo + (dm1 + dm2) / 2; + return; + } + p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt; + return; + } + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); + }, + normalSlope: Number.NEGATIVE_INFINITY, + setRelative: function(p, rp, d, pv, org) { + if (!pv || pv === this) { + p.x = (org ? rp.xo : rp.x) + d; + return; + } + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + p.x = rpdx + (p.y - rpdy) / pv.normalSlope; + }, + slope: 0, + touch: function(p) { + p.xTouched = true; + }, + touched: function(p) { + return p.xTouched; + }, + untouch: function(p) { + p.xTouched = false; + } +}; +var yUnitVector = { + x: 0, + y: 1, + axis: "y", + distance: function(p1, p2, o1, o2) { + return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y); + }, + interpolate: function(p, rp1, rp2, pv) { + var do1; + var do2; + var doa1; + var doa2; + var dm1; + var dm2; + var dt; + if (!pv || pv === this) { + do1 = p.yo - rp1.yo; + do2 = p.yo - rp2.yo; + dm1 = rp1.y - rp1.yo; + dm2 = rp2.y - rp2.yo; + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + p.y = p.yo + (dm1 + dm2) / 2; + return; + } + p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt; + return; + } + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); + }, + normalSlope: 0, + setRelative: function(p, rp, d, pv, org) { + if (!pv || pv === this) { + p.y = (org ? rp.yo : rp.y) + d; + return; + } + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + p.y = rpdy + pv.normalSlope * (p.x - rpdx); + }, + slope: Number.POSITIVE_INFINITY, + touch: function(p) { + p.yTouched = true; + }, + touched: function(p) { + return p.yTouched; + }, + untouch: function(p) { + p.yTouched = false; + } +}; +Object.freeze(xUnitVector); +Object.freeze(yUnitVector); +function UnitVector(x2, y) { + this.x = x2; + this.y = y; + this.axis = undefined; + this.slope = y / x2; + this.normalSlope = -x2 / y; + Object.freeze(this); +} +UnitVector.prototype.distance = function(p1, p2, o1, o2) { + return this.x * xUnitVector.distance(p1, p2, o1, o2) + this.y * yUnitVector.distance(p1, p2, o1, o2); +}; +UnitVector.prototype.interpolate = function(p, rp1, rp2, pv) { + var dm1; + var dm2; + var do1; + var do2; + var doa1; + var doa2; + var dt; + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + this.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); +}; +UnitVector.prototype.setRelative = function(p, rp, d, pv, org) { + pv = pv || this; + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + var pvns = pv.normalSlope; + var fvs = this.slope; + var px2 = p.x; + var py2 = p.y; + p.x = (fvs * px2 - pvns * rpdx + rpdy - py2) / (fvs - pvns); + p.y = fvs * (p.x - px2) + py2; +}; +UnitVector.prototype.touch = function(p) { + p.xTouched = true; + p.yTouched = true; +}; +function getUnitVector(x2, y) { + var d = Math.sqrt(x2 * x2 + y * y); + x2 /= d; + y /= d; + if (x2 === 1 && y === 0) { + return xUnitVector; + } else if (x2 === 0 && y === 1) { + return yUnitVector; + } else { + return new UnitVector(x2, y); + } +} +function HPoint(x2, y, lastPointOfContour, onCurve) { + this.x = this.xo = Math.round(x2 * 64) / 64; + this.y = this.yo = Math.round(y * 64) / 64; + this.lastPointOfContour = lastPointOfContour; + this.onCurve = onCurve; + this.prevPointOnContour = undefined; + this.nextPointOnContour = undefined; + this.xTouched = false; + this.yTouched = false; + Object.preventExtensions(this); +} +HPoint.prototype.nextTouched = function(v) { + var p = this.nextPointOnContour; + while (!v.touched(p) && p !== this) { + p = p.nextPointOnContour; + } + return p; +}; +HPoint.prototype.prevTouched = function(v) { + var p = this.prevPointOnContour; + while (!v.touched(p) && p !== this) { + p = p.prevPointOnContour; + } + return p; +}; +var HPZero = Object.freeze(new HPoint(0, 0)); +var defaultState = { + cvCutIn: 17 / 16, + deltaBase: 9, + deltaShift: 0.125, + loop: 1, + minDis: 1, + autoFlip: true +}; +function State(env, prog) { + this.env = env; + this.stack = []; + this.prog = prog; + switch (env) { + case "glyf": + this.zp0 = this.zp1 = this.zp2 = 1; + this.rp0 = this.rp1 = this.rp2 = 0; + case "prep": + this.fv = this.pv = this.dpv = xUnitVector; + this.round = roundToGrid; + } +} +Hinting.prototype.exec = function(glyph, ppem) { + if (typeof ppem !== "number") { + throw new Error("Point size is not a number!"); + } + if (this._errorState > 2) { + return; + } + var font = this.font; + var prepState = this._prepState; + if (!prepState || prepState.ppem !== ppem) { + var fpgmState = this._fpgmState; + if (!fpgmState) { + State.prototype = defaultState; + fpgmState = this._fpgmState = new State("fpgm", font.tables.fpgm); + fpgmState.funcs = []; + fpgmState.font = font; + if (exports_opentype_module.DEBUG) { + console.log("---EXEC FPGM---"); + fpgmState.step = -1; + } + try { + exec(fpgmState); + } catch (e) { + console.log("Hinting error in FPGM:" + e); + this._errorState = 3; + return; + } + } + State.prototype = fpgmState; + prepState = this._prepState = new State("prep", font.tables.prep); + prepState.ppem = ppem; + var oCvt = font.tables.cvt; + if (oCvt) { + var cvt = prepState.cvt = new Array(oCvt.length); + var scale2 = ppem / font.unitsPerEm; + for (var c = 0;c < oCvt.length; c++) { + cvt[c] = oCvt[c] * scale2; + } + } else { + prepState.cvt = []; + } + if (exports_opentype_module.DEBUG) { + console.log("---EXEC PREP---"); + prepState.step = -1; + } + try { + exec(prepState); + } catch (e) { + if (this._errorState < 2) { + console.log("Hinting error in PREP:" + e); + } + this._errorState = 2; + } + } + if (this._errorState > 1) { + return; + } + try { + return execGlyph(glyph, prepState); + } catch (e) { + if (this._errorState < 1) { + console.log("Hinting error:" + e); + console.log("Note: further hinting errors are silenced"); + } + this._errorState = 1; + return; + } +}; +execGlyph = function(glyph, prepState) { + var xScale = prepState.ppem / prepState.font.unitsPerEm; + var yScale = xScale; + var components = glyph.components; + var contours; + var gZone; + var state; + State.prototype = prepState; + if (!components) { + state = new State("glyf", glyph.instructions); + if (exports_opentype_module.DEBUG) { + console.log("---EXEC GLYPH---"); + state.step = -1; + } + execComponent(glyph, state, xScale, yScale); + gZone = state.gZone; + } else { + var font = prepState.font; + gZone = []; + contours = []; + for (var i = 0;i < components.length; i++) { + var c = components[i]; + var cg = font.glyphs.get(c.glyphIndex); + state = new State("glyf", cg.instructions); + if (exports_opentype_module.DEBUG) { + console.log("---EXEC COMP " + i + "---"); + state.step = -1; + } + execComponent(cg, state, xScale, yScale); + var dx = Math.round(c.dx * xScale); + var dy = Math.round(c.dy * yScale); + var gz = state.gZone; + var cc = state.contours; + for (var pi2 = 0;pi2 < gz.length; pi2++) { + var p = gz[pi2]; + p.xTouched = p.yTouched = false; + p.xo = p.x = p.x + dx; + p.yo = p.y = p.y + dy; + } + var gLen = gZone.length; + gZone.push.apply(gZone, gz); + for (var j2 = 0;j2 < cc.length; j2++) { + contours.push(cc[j2] + gLen); + } + } + if (glyph.instructions && !state.inhibitGridFit) { + state = new State("glyf", glyph.instructions); + state.gZone = state.z0 = state.z1 = state.z2 = gZone; + state.contours = contours; + gZone.push(new HPoint(0, 0), new HPoint(Math.round(glyph.advanceWidth * xScale), 0)); + if (exports_opentype_module.DEBUG) { + console.log("---EXEC COMPOSITE---"); + state.step = -1; + } + exec(state); + gZone.length -= 2; + } + } + return gZone; +}; +execComponent = function(glyph, state, xScale, yScale) { + var points = glyph.points || []; + var pLen = points.length; + var gZone = state.gZone = state.z0 = state.z1 = state.z2 = []; + var contours = state.contours = []; + var cp; + for (var i = 0;i < pLen; i++) { + cp = points[i]; + gZone[i] = new HPoint(cp.x * xScale, cp.y * yScale, cp.lastPointOfContour, cp.onCurve); + } + var sp; + var np; + for (var i$1 = 0;i$1 < pLen; i$1++) { + cp = gZone[i$1]; + if (!sp) { + sp = cp; + contours.push(i$1); + } + if (cp.lastPointOfContour) { + cp.nextPointOnContour = sp; + sp.prevPointOnContour = cp; + sp = undefined; + } else { + np = gZone[i$1 + 1]; + cp.nextPointOnContour = np; + np.prevPointOnContour = cp; + } + } + if (state.inhibitGridFit) { + return; + } + if (exports_opentype_module.DEBUG) { + console.log("PROCESSING GLYPH", state.stack); + for (var i$2 = 0;i$2 < pLen; i$2++) { + console.log(i$2, gZone[i$2].x, gZone[i$2].y); + } + } + gZone.push(new HPoint(0, 0), new HPoint(Math.round(glyph.advanceWidth * xScale), 0)); + exec(state); + gZone.length -= 2; + if (exports_opentype_module.DEBUG) { + console.log("FINISHED GLYPH", state.stack); + for (var i$3 = 0;i$3 < pLen; i$3++) { + console.log(i$3, gZone[i$3].x, gZone[i$3].y); + } + } +}; +exec = function(state) { + var prog = state.prog; + if (!prog) { + return; + } + var pLen = prog.length; + var ins; + for (state.ip = 0;state.ip < pLen; state.ip++) { + if (exports_opentype_module.DEBUG) { + state.step++; + } + ins = instructionTable[prog[state.ip]]; + if (!ins) { + throw new Error("unknown instruction: 0x" + Number(prog[state.ip]).toString(16)); + } + ins(state); + } +}; +function initTZone(state) { + var tZone = state.tZone = new Array(state.gZone.length); + for (var i = 0;i < tZone.length; i++) { + tZone[i] = new HPoint(0, 0); + } +} +function skip(state, handleElse) { + var prog = state.prog; + var ip = state.ip; + var nesting = 1; + var ins; + do { + ins = prog[++ip]; + if (ins === 88) { + nesting++; + } else if (ins === 89) { + nesting--; + } else if (ins === 64) { + ip += prog[ip + 1] + 1; + } else if (ins === 65) { + ip += 2 * prog[ip + 1] + 1; + } else if (ins >= 176 && ins <= 183) { + ip += ins - 176 + 1; + } else if (ins >= 184 && ins <= 191) { + ip += (ins - 184 + 1) * 2; + } else if (handleElse && nesting === 1 && ins === 27) { + break; + } + } while (nesting > 0); + state.ip = ip; +} +function SVTCA(v, state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SVTCA[" + v.axis + "]"); + } + state.fv = state.pv = state.dpv = v; +} +function SPVTCA(v, state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SPVTCA[" + v.axis + "]"); + } + state.pv = state.dpv = v; +} +function SFVTCA(v, state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SFVTCA[" + v.axis + "]"); + } + state.fv = v; +} +function SPVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + if (exports_opentype_module.DEBUG) { + console.log("SPVTL[" + a + "]", p2i, p1i); + } + var dx; + var dy; + if (!a) { + dx = p1.x - p2.x; + dy = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy = p1.x - p2.x; + } + state.pv = state.dpv = getUnitVector(dx, dy); +} +function SFVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + if (exports_opentype_module.DEBUG) { + console.log("SFVTL[" + a + "]", p2i, p1i); + } + var dx; + var dy; + if (!a) { + dx = p1.x - p2.x; + dy = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy = p1.x - p2.x; + } + state.fv = getUnitVector(dx, dy); +} +function SPVFS(state) { + var stack = state.stack; + var y = stack.pop(); + var x2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SPVFS[]", y, x2); + } + state.pv = state.dpv = getUnitVector(x2, y); +} +function SFVFS(state) { + var stack = state.stack; + var y = stack.pop(); + var x2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SPVFS[]", y, x2); + } + state.fv = getUnitVector(x2, y); +} +function GPV(state) { + var stack = state.stack; + var pv = state.pv; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GPV[]"); + } + stack.push(pv.x * 16384); + stack.push(pv.y * 16384); +} +function GFV(state) { + var stack = state.stack; + var fv = state.fv; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GFV[]"); + } + stack.push(fv.x * 16384); + stack.push(fv.y * 16384); +} +function SFVTPV(state) { + state.fv = state.pv; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SFVTPV[]"); + } +} +function ISECT(state) { + var stack = state.stack; + var pa0i = stack.pop(); + var pa1i = stack.pop(); + var pb0i = stack.pop(); + var pb1i = stack.pop(); + var pi2 = stack.pop(); + var z0 = state.z0; + var z1 = state.z1; + var pa0 = z0[pa0i]; + var pa1 = z0[pa1i]; + var pb0 = z1[pb0i]; + var pb1 = z1[pb1i]; + var p = state.z2[pi2]; + if (exports_opentype_module.DEBUG) { + console.log("ISECT[], ", pa0i, pa1i, pb0i, pb1i, pi2); + } + var x1 = pa0.x; + var y1 = pa0.y; + var x2 = pa1.x; + var y2 = pa1.y; + var x3 = pb0.x; + var y3 = pb0.y; + var x4 = pb1.x; + var y4 = pb1.y; + var div2 = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); + var f1 = x1 * y2 - y1 * x2; + var f2 = x3 * y4 - y3 * x4; + p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div2; + p.y = (f1 * (y3 - y4) - f2 * (y1 - y2)) / div2; +} +function SRP0(state) { + state.rp0 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SRP0[]", state.rp0); + } +} +function SRP1(state) { + state.rp1 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SRP1[]", state.rp1); + } +} +function SRP2(state) { + state.rp2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SRP2[]", state.rp2); + } +} +function SZP0(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SZP0[]", n2); + } + state.zp0 = n2; + switch (n2) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z0 = state.tZone; + break; + case 1: + state.z0 = state.gZone; + break; + default: + throw new Error("Invalid zone pointer"); + } +} +function SZP1(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SZP1[]", n2); + } + state.zp1 = n2; + switch (n2) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z1 = state.tZone; + break; + case 1: + state.z1 = state.gZone; + break; + default: + throw new Error("Invalid zone pointer"); + } +} +function SZP2(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SZP2[]", n2); + } + state.zp2 = n2; + switch (n2) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z2 = state.tZone; + break; + case 1: + state.z2 = state.gZone; + break; + default: + throw new Error("Invalid zone pointer"); + } +} +function SZPS(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SZPS[]", n2); + } + state.zp0 = state.zp1 = state.zp2 = n2; + switch (n2) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z0 = state.z1 = state.z2 = state.tZone; + break; + case 1: + state.z0 = state.z1 = state.z2 = state.gZone; + break; + default: + throw new Error("Invalid zone pointer"); + } +} +function SLOOP(state) { + state.loop = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SLOOP[]", state.loop); + } +} +function RTG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RTG[]"); + } + state.round = roundToGrid; +} +function RTHG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RTHG[]"); + } + state.round = roundToHalfGrid; +} +function SMD(state) { + var d = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SMD[]", d); + } + state.minDis = d / 64; +} +function ELSE(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ELSE[]"); + } + skip(state, false); +} +function JMPR(state) { + var o = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "JMPR[]", o); + } + state.ip += o - 1; +} +function SCVTCI(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SCVTCI[]", n2); + } + state.cvCutIn = n2 / 64; +} +function DUP(state) { + var stack = state.stack; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DUP[]"); + } + stack.push(stack[stack.length - 1]); +} +function POP(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "POP[]"); + } + state.stack.pop(); +} +function CLEAR(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "CLEAR[]"); + } + state.stack.length = 0; +} +function SWAP(state) { + var stack = state.stack; + var a = stack.pop(); + var b = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SWAP[]"); + } + stack.push(a); + stack.push(b); +} +function DEPTH(state) { + var stack = state.stack; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DEPTH[]"); + } + stack.push(stack.length); +} +function LOOPCALL(state) { + var stack = state.stack; + var fn = stack.pop(); + var c = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "LOOPCALL[]", fn, c); + } + var cip = state.ip; + var cprog = state.prog; + state.prog = state.funcs[fn]; + for (var i = 0;i < c; i++) { + exec(state); + if (exports_opentype_module.DEBUG) { + console.log(++state.step, i + 1 < c ? "next loopcall" : "done loopcall", i); + } + } + state.ip = cip; + state.prog = cprog; +} +function CALL(state) { + var fn = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "CALL[]", fn); + } + var cip = state.ip; + var cprog = state.prog; + state.prog = state.funcs[fn]; + exec(state); + state.ip = cip; + state.prog = cprog; + if (exports_opentype_module.DEBUG) { + console.log(++state.step, "returning from", fn); + } +} +function CINDEX(state) { + var stack = state.stack; + var k2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "CINDEX[]", k2); + } + stack.push(stack[stack.length - k2]); +} +function MINDEX(state) { + var stack = state.stack; + var k2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MINDEX[]", k2); + } + stack.push(stack.splice(stack.length - k2, 1)[0]); +} +function FDEF(state) { + if (state.env !== "fpgm") { + throw new Error("FDEF not allowed here"); + } + var stack = state.stack; + var prog = state.prog; + var ip = state.ip; + var fn = stack.pop(); + var ipBegin = ip; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "FDEF[]", fn); + } + while (prog[++ip] !== 45) { + } + state.ip = ip; + state.funcs[fn] = prog.slice(ipBegin + 1, ip); +} +function MDAP(round, state) { + var pi2 = state.stack.pop(); + var p = state.z0[pi2]; + var fv = state.fv; + var pv = state.pv; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MDAP[" + round + "]", pi2); + } + var d = pv.distance(p, HPZero); + if (round) { + d = state.round(d); + } + fv.setRelative(p, HPZero, d, pv); + fv.touch(p); + state.rp0 = state.rp1 = pi2; +} +function IUP(v, state) { + var z2 = state.z2; + var pLen = z2.length - 2; + var cp; + var pp; + var np; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "IUP[" + v.axis + "]"); + } + for (var i = 0;i < pLen; i++) { + cp = z2[i]; + if (v.touched(cp)) { + continue; + } + pp = cp.prevTouched(v); + if (pp === cp) { + continue; + } + np = cp.nextTouched(v); + if (pp === np) { + v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true); + } + v.interpolate(cp, pp, np, v); + } +} +function SHP(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1)[rpi]; + var fv = state.fv; + var pv = state.pv; + var loop = state.loop; + var z2 = state.z2; + while (loop--) { + var pi2 = stack.pop(); + var p = z2[pi2]; + var d = pv.distance(rp, rp, false, true); + fv.setRelative(p, p, d, pv); + fv.touch(p); + if (exports_opentype_module.DEBUG) { + console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "SHP[" + (a ? "rp1" : "rp2") + "]", pi2); + } + } + state.loop = 1; +} +function SHC(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1)[rpi]; + var fv = state.fv; + var pv = state.pv; + var ci = stack.pop(); + var sp = state.z2[state.contours[ci]]; + var p = sp; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SHC[" + a + "]", ci); + } + var d = pv.distance(rp, rp, false, true); + do { + if (p !== rp) { + fv.setRelative(p, p, d, pv); + } + p = p.nextPointOnContour; + } while (p !== sp); +} +function SHZ(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1)[rpi]; + var fv = state.fv; + var pv = state.pv; + var e = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SHZ[" + a + "]", e); + } + var z; + switch (e) { + case 0: + z = state.tZone; + break; + case 1: + z = state.gZone; + break; + default: + throw new Error("Invalid zone"); + } + var p; + var d = pv.distance(rp, rp, false, true); + var pLen = z.length - 2; + for (var i = 0;i < pLen; i++) { + p = z[i]; + fv.setRelative(p, p, d, pv); + } +} +function SHPIX(state) { + var stack = state.stack; + var loop = state.loop; + var fv = state.fv; + var d = stack.pop() / 64; + var z2 = state.z2; + while (loop--) { + var pi2 = stack.pop(); + var p = z2[pi2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "SHPIX[]", pi2, d); + } + fv.setRelative(p, p, d); + fv.touch(p); + } + state.loop = 1; +} +function IP(state) { + var stack = state.stack; + var rp1i = state.rp1; + var rp2i = state.rp2; + var loop = state.loop; + var rp1 = state.z0[rp1i]; + var rp2 = state.z1[rp2i]; + var fv = state.fv; + var pv = state.dpv; + var z2 = state.z2; + while (loop--) { + var pi2 = stack.pop(); + var p = z2[pi2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "IP[]", pi2, rp1i, "<->", rp2i); + } + fv.interpolate(p, rp1, rp2, pv); + fv.touch(p); + } + state.loop = 1; +} +function MSIRP(a, state) { + var stack = state.stack; + var d = stack.pop() / 64; + var pi2 = stack.pop(); + var p = state.z1[pi2]; + var rp0 = state.z0[state.rp0]; + var fv = state.fv; + var pv = state.pv; + fv.setRelative(p, rp0, d, pv); + fv.touch(p); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MSIRP[" + a + "]", d, pi2); + } + state.rp1 = state.rp0; + state.rp2 = pi2; + if (a) { + state.rp0 = pi2; + } +} +function ALIGNRP(state) { + var stack = state.stack; + var rp0i = state.rp0; + var rp0 = state.z0[rp0i]; + var loop = state.loop; + var fv = state.fv; + var pv = state.pv; + var z1 = state.z1; + while (loop--) { + var pi2 = stack.pop(); + var p = z1[pi2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "ALIGNRP[]", pi2); + } + fv.setRelative(p, rp0, 0, pv); + fv.touch(p); + } + state.loop = 1; +} +function RTDG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RTDG[]"); + } + state.round = roundToDoubleGrid; +} +function MIAP(round, state) { + var stack = state.stack; + var n2 = stack.pop(); + var pi2 = stack.pop(); + var p = state.z0[pi2]; + var fv = state.fv; + var pv = state.pv; + var cv = state.cvt[n2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MIAP[" + round + "]", n2, "(", cv, ")", pi2); + } + var d = pv.distance(p, HPZero); + if (round) { + if (Math.abs(d - cv) < state.cvCutIn) { + d = cv; + } + d = state.round(d); + } + fv.setRelative(p, HPZero, d, pv); + if (state.zp0 === 0) { + p.xo = p.x; + p.yo = p.y; + } + fv.touch(p); + state.rp0 = state.rp1 = pi2; +} +function NPUSHB(state) { + var prog = state.prog; + var ip = state.ip; + var stack = state.stack; + var n2 = prog[++ip]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NPUSHB[]", n2); + } + for (var i = 0;i < n2; i++) { + stack.push(prog[++ip]); + } + state.ip = ip; +} +function NPUSHW(state) { + var ip = state.ip; + var prog = state.prog; + var stack = state.stack; + var n2 = prog[++ip]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NPUSHW[]", n2); + } + for (var i = 0;i < n2; i++) { + var w = prog[++ip] << 8 | prog[++ip]; + if (w & 32768) { + w = -((w ^ 65535) + 1); + } + stack.push(w); + } + state.ip = ip; +} +function WS(state) { + var stack = state.stack; + var store = state.store; + if (!store) { + store = state.store = []; + } + var v = stack.pop(); + var l2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "WS", v, l2); + } + store[l2] = v; +} +function RS(state) { + var stack = state.stack; + var store = state.store; + var l2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RS", l2); + } + var v = store && store[l2] || 0; + stack.push(v); +} +function WCVTP(state) { + var stack = state.stack; + var v = stack.pop(); + var l2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "WCVTP", v, l2); + } + state.cvt[l2] = v / 64; +} +function RCVT(state) { + var stack = state.stack; + var cvte = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RCVT", cvte); + } + stack.push(state.cvt[cvte] * 64); +} +function GC(a, state) { + var stack = state.stack; + var pi2 = stack.pop(); + var p = state.z2[pi2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GC[" + a + "]", pi2); + } + stack.push(state.dpv.distance(p, HPZero, a, false) * 64); +} +function MD(a, state) { + var stack = state.stack; + var pi2 = stack.pop(); + var pi1 = stack.pop(); + var p2 = state.z1[pi2]; + var p1 = state.z0[pi1]; + var d = state.dpv.distance(p1, p2, a, a); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MD[" + a + "]", pi2, pi1, "->", d); + } + state.stack.push(Math.round(d * 64)); +} +function MPPEM(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MPPEM[]"); + } + state.stack.push(state.ppem); +} +function FLIPON(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "FLIPON[]"); + } + state.autoFlip = true; +} +function LT(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "LT[]", e2, e1); + } + stack.push(e1 < e2 ? 1 : 0); +} +function LTEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "LTEQ[]", e2, e1); + } + stack.push(e1 <= e2 ? 1 : 0); +} +function GT(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GT[]", e2, e1); + } + stack.push(e1 > e2 ? 1 : 0); +} +function GTEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GTEQ[]", e2, e1); + } + stack.push(e1 >= e2 ? 1 : 0); +} +function EQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "EQ[]", e2, e1); + } + stack.push(e2 === e1 ? 1 : 0); +} +function NEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NEQ[]", e2, e1); + } + stack.push(e2 !== e1 ? 1 : 0); +} +function ODD(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ODD[]", n2); + } + stack.push(Math.trunc(n2) % 2 ? 1 : 0); +} +function EVEN(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "EVEN[]", n2); + } + stack.push(Math.trunc(n2) % 2 ? 0 : 1); +} +function IF(state) { + var test = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "IF[]", test); + } + if (!test) { + skip(state, true); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "EIF[]"); + } + } +} +function EIF(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "EIF[]"); + } +} +function AND(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "AND[]", e2, e1); + } + stack.push(e2 && e1 ? 1 : 0); +} +function OR(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "OR[]", e2, e1); + } + stack.push(e2 || e1 ? 1 : 0); +} +function NOT(state) { + var stack = state.stack; + var e = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NOT[]", e); + } + stack.push(e ? 0 : 1); +} +function DELTAP123(b, state) { + var stack = state.stack; + var n2 = stack.pop(); + var fv = state.fv; + var pv = state.pv; + var ppem = state.ppem; + var base = state.deltaBase + (b - 1) * 16; + var ds = state.deltaShift; + var z0 = state.z0; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DELTAP[" + b + "]", n2, stack); + } + for (var i = 0;i < n2; i++) { + var pi2 = stack.pop(); + var arg = stack.pop(); + var appem = base + ((arg & 240) >> 4); + if (appem !== ppem) { + continue; + } + var mag = (arg & 15) - 8; + if (mag >= 0) { + mag++; + } + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DELTAPFIX", pi2, "by", mag * ds); + } + var p = z0[pi2]; + fv.setRelative(p, p, mag * ds, pv); + } +} +function SDB(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SDB[]", n2); + } + state.deltaBase = n2; +} +function SDS(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SDS[]", n2); + } + state.deltaShift = Math.pow(0.5, n2); +} +function ADD(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ADD[]", n2, n1); + } + stack.push(n1 + n2); +} +function SUB(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SUB[]", n2, n1); + } + stack.push(n1 - n2); +} +function DIV(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DIV[]", n2, n1); + } + stack.push(n1 * 64 / n2); +} +function MUL(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MUL[]", n2, n1); + } + stack.push(n1 * n2 / 64); +} +function ABS(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ABS[]", n2); + } + stack.push(Math.abs(n2)); +} +function NEG(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NEG[]", n2); + } + stack.push(-n2); +} +function FLOOR(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "FLOOR[]", n2); + } + stack.push(Math.floor(n2 / 64) * 64); +} +function CEILING(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "CEILING[]", n2); + } + stack.push(Math.ceil(n2 / 64) * 64); +} +function ROUND(dt, state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ROUND[]"); + } + stack.push(state.round(n2 / 64) * 64); +} +function WCVTF(state) { + var stack = state.stack; + var v = stack.pop(); + var l2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "WCVTF[]", v, l2); + } + state.cvt[l2] = v * state.ppem / state.font.unitsPerEm; +} +function DELTAC123(b, state) { + var stack = state.stack; + var n2 = stack.pop(); + var ppem = state.ppem; + var base = state.deltaBase + (b - 1) * 16; + var ds = state.deltaShift; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DELTAC[" + b + "]", n2, stack); + } + for (var i = 0;i < n2; i++) { + var c = stack.pop(); + var arg = stack.pop(); + var appem = base + ((arg & 240) >> 4); + if (appem !== ppem) { + continue; + } + var mag = (arg & 15) - 8; + if (mag >= 0) { + mag++; + } + var delta = mag * ds; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DELTACFIX", c, "by", delta); + } + state.cvt[c] += delta; + } +} +function SROUND(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SROUND[]", n2); + } + state.round = roundSuper; + var period; + switch (n2 & 192) { + case 0: + period = 0.5; + break; + case 64: + period = 1; + break; + case 128: + period = 2; + break; + default: + throw new Error("invalid SROUND value"); + } + state.srPeriod = period; + switch (n2 & 48) { + case 0: + state.srPhase = 0; + break; + case 16: + state.srPhase = 0.25 * period; + break; + case 32: + state.srPhase = 0.5 * period; + break; + case 48: + state.srPhase = 0.75 * period; + break; + default: + throw new Error("invalid SROUND value"); + } + n2 &= 15; + if (n2 === 0) { + state.srThreshold = 0; + } else { + state.srThreshold = (n2 / 8 - 0.5) * period; + } +} +function S45ROUND(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "S45ROUND[]", n2); + } + state.round = roundSuper; + var period; + switch (n2 & 192) { + case 0: + period = Math.sqrt(2) / 2; + break; + case 64: + period = Math.sqrt(2); + break; + case 128: + period = 2 * Math.sqrt(2); + break; + default: + throw new Error("invalid S45ROUND value"); + } + state.srPeriod = period; + switch (n2 & 48) { + case 0: + state.srPhase = 0; + break; + case 16: + state.srPhase = 0.25 * period; + break; + case 32: + state.srPhase = 0.5 * period; + break; + case 48: + state.srPhase = 0.75 * period; + break; + default: + throw new Error("invalid S45ROUND value"); + } + n2 &= 15; + if (n2 === 0) { + state.srThreshold = 0; + } else { + state.srThreshold = (n2 / 8 - 0.5) * period; + } +} +function ROFF(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ROFF[]"); + } + state.round = roundOff; +} +function RUTG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RUTG[]"); + } + state.round = roundUpToGrid; +} +function RDTG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RDTG[]"); + } + state.round = roundDownToGrid; +} +function SCANCTRL(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SCANCTRL[]", n2); + } +} +function SDPVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SDPVTL[" + a + "]", p2i, p1i); + } + var dx; + var dy; + if (!a) { + dx = p1.x - p2.x; + dy = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy = p1.x - p2.x; + } + state.dpv = getUnitVector(dx, dy); +} +function GETINFO(state) { + var stack = state.stack; + var sel = stack.pop(); + var r = 0; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GETINFO[]", sel); + } + if (sel & 1) { + r = 35; + } + if (sel & 32) { + r |= 4096; + } + stack.push(r); +} +function ROLL(state) { + var stack = state.stack; + var a = stack.pop(); + var b = stack.pop(); + var c = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ROLL[]"); + } + stack.push(b); + stack.push(a); + stack.push(c); +} +function MAX(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MAX[]", e2, e1); + } + stack.push(Math.max(e1, e2)); +} +function MIN(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MIN[]", e2, e1); + } + stack.push(Math.min(e1, e2)); +} +function SCANTYPE(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SCANTYPE[]", n2); + } +} +function INSTCTRL(state) { + var s = state.stack.pop(); + var v = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "INSTCTRL[]", s, v); + } + switch (s) { + case 1: + state.inhibitGridFit = !!v; + return; + case 2: + state.ignoreCvt = !!v; + return; + default: + throw new Error("invalid INSTCTRL[] selector"); + } +} +function PUSHB(n2, state) { + var stack = state.stack; + var prog = state.prog; + var ip = state.ip; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "PUSHB[" + n2 + "]"); + } + for (var i = 0;i < n2; i++) { + stack.push(prog[++ip]); + } + state.ip = ip; +} +function PUSHW(n2, state) { + var ip = state.ip; + var prog = state.prog; + var stack = state.stack; + if (exports_opentype_module.DEBUG) { + console.log(state.ip, "PUSHW[" + n2 + "]"); + } + for (var i = 0;i < n2; i++) { + var w = prog[++ip] << 8 | prog[++ip]; + if (w & 32768) { + w = -((w ^ 65535) + 1); + } + stack.push(w); + } + state.ip = ip; +} +function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) { + var stack = state.stack; + var cvte = indirect && stack.pop(); + var pi2 = stack.pop(); + var rp0i = state.rp0; + var rp = state.z0[rp0i]; + var p = state.z1[pi2]; + var md = state.minDis; + var fv = state.fv; + var pv = state.dpv; + var od; + var d; + var sign2; + var cv; + d = od = pv.distance(p, rp, true, true); + sign2 = d >= 0 ? 1 : -1; + d = Math.abs(d); + if (indirect) { + cv = state.cvt[cvte]; + if (ro && Math.abs(d - cv) < state.cvCutIn) { + d = cv; + } + } + if (keepD && d < md) { + d = md; + } + if (ro) { + d = state.round(d); + } + fv.setRelative(p, rp, sign2 * d, pv); + fv.touch(p); + if (exports_opentype_module.DEBUG) { + console.log(state.step, (indirect ? "MIRP[" : "MDRP[") + (setRp0 ? "M" : "m") + (keepD ? ">" : "_") + (ro ? "R" : "_") + (dt === 0 ? "Gr" : dt === 1 ? "Bl" : dt === 2 ? "Wh" : "") + "]", indirect ? cvte + "(" + state.cvt[cvte] + "," + cv + ")" : "", pi2, "(d =", od, "->", sign2 * d, ")"); + } + state.rp1 = state.rp0; + state.rp2 = pi2; + if (setRp0) { + state.rp0 = pi2; + } +} +instructionTable = [ + SVTCA.bind(undefined, yUnitVector), + SVTCA.bind(undefined, xUnitVector), + SPVTCA.bind(undefined, yUnitVector), + SPVTCA.bind(undefined, xUnitVector), + SFVTCA.bind(undefined, yUnitVector), + SFVTCA.bind(undefined, xUnitVector), + SPVTL.bind(undefined, 0), + SPVTL.bind(undefined, 1), + SFVTL.bind(undefined, 0), + SFVTL.bind(undefined, 1), + SPVFS, + SFVFS, + GPV, + GFV, + SFVTPV, + ISECT, + SRP0, + SRP1, + SRP2, + SZP0, + SZP1, + SZP2, + SZPS, + SLOOP, + RTG, + RTHG, + SMD, + ELSE, + JMPR, + SCVTCI, + undefined, + undefined, + DUP, + POP, + CLEAR, + SWAP, + DEPTH, + CINDEX, + MINDEX, + undefined, + undefined, + undefined, + LOOPCALL, + CALL, + FDEF, + undefined, + MDAP.bind(undefined, 0), + MDAP.bind(undefined, 1), + IUP.bind(undefined, yUnitVector), + IUP.bind(undefined, xUnitVector), + SHP.bind(undefined, 0), + SHP.bind(undefined, 1), + SHC.bind(undefined, 0), + SHC.bind(undefined, 1), + SHZ.bind(undefined, 0), + SHZ.bind(undefined, 1), + SHPIX, + IP, + MSIRP.bind(undefined, 0), + MSIRP.bind(undefined, 1), + ALIGNRP, + RTDG, + MIAP.bind(undefined, 0), + MIAP.bind(undefined, 1), + NPUSHB, + NPUSHW, + WS, + RS, + WCVTP, + RCVT, + GC.bind(undefined, 0), + GC.bind(undefined, 1), + undefined, + MD.bind(undefined, 0), + MD.bind(undefined, 1), + MPPEM, + undefined, + FLIPON, + undefined, + undefined, + LT, + LTEQ, + GT, + GTEQ, + EQ, + NEQ, + ODD, + EVEN, + IF, + EIF, + AND, + OR, + NOT, + DELTAP123.bind(undefined, 1), + SDB, + SDS, + ADD, + SUB, + DIV, + MUL, + ABS, + NEG, + FLOOR, + CEILING, + ROUND.bind(undefined, 0), + ROUND.bind(undefined, 1), + ROUND.bind(undefined, 2), + ROUND.bind(undefined, 3), + undefined, + undefined, + undefined, + undefined, + WCVTF, + DELTAP123.bind(undefined, 2), + DELTAP123.bind(undefined, 3), + DELTAC123.bind(undefined, 1), + DELTAC123.bind(undefined, 2), + DELTAC123.bind(undefined, 3), + SROUND, + S45ROUND, + undefined, + undefined, + ROFF, + undefined, + RUTG, + RDTG, + POP, + POP, + undefined, + undefined, + undefined, + undefined, + undefined, + SCANCTRL, + SDPVTL.bind(undefined, 0), + SDPVTL.bind(undefined, 1), + GETINFO, + undefined, + ROLL, + MAX, + MIN, + SCANTYPE, + INSTCTRL, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + PUSHB.bind(undefined, 1), + PUSHB.bind(undefined, 2), + PUSHB.bind(undefined, 3), + PUSHB.bind(undefined, 4), + PUSHB.bind(undefined, 5), + PUSHB.bind(undefined, 6), + PUSHB.bind(undefined, 7), + PUSHB.bind(undefined, 8), + PUSHW.bind(undefined, 1), + PUSHW.bind(undefined, 2), + PUSHW.bind(undefined, 3), + PUSHW.bind(undefined, 4), + PUSHW.bind(undefined, 5), + PUSHW.bind(undefined, 6), + PUSHW.bind(undefined, 7), + PUSHW.bind(undefined, 8), + MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 0), + MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 1), + MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 2), + MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 3), + MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 0), + MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 1), + MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 2), + MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 3), + MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 0), + MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 1), + MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 2), + MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 3), + MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 0), + MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 1), + MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 2), + MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 3), + MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 0), + MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 1), + MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 2), + MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 3), + MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 0), + MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 1), + MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 2), + MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 3), + MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 0), + MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 1), + MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 2), + MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 3), + MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 0), + MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 1), + MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 2), + MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 3), + MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 0), + MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 1), + MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 2), + MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 3), + MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 0), + MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 1), + MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 2), + MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 3), + MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 0), + MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 1), + MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 2), + MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 3), + MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 0), + MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 1), + MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 2), + MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 3), + MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 0), + MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 1), + MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 2), + MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 3), + MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 0), + MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 1), + MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 2), + MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 3), + MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 0), + MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 1), + MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 2), + MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 3), + MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 0), + MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 1), + MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 2), + MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 3) +]; +function Token(char) { + this.char = char; + this.state = {}; + this.activeState = null; +} +function ContextRange(startIndex, endOffset, contextName) { + this.contextName = contextName; + this.startIndex = startIndex; + this.endOffset = endOffset; +} +function ContextChecker(contextName, checkStart, checkEnd) { + this.contextName = contextName; + this.openRange = null; + this.ranges = []; + this.checkStart = checkStart; + this.checkEnd = checkEnd; +} +function ContextParams(context, currentIndex) { + this.context = context; + this.index = currentIndex; + this.length = context.length; + this.current = context[currentIndex]; + this.backtrack = context.slice(0, currentIndex); + this.lookahead = context.slice(currentIndex + 1); +} +function Event(eventId) { + this.eventId = eventId; + this.subscribers = []; +} +function initializeCoreEvents(events) { + var this$1 = this; + var coreEvents = [ + "start", + "end", + "next", + "newToken", + "contextStart", + "contextEnd", + "insertToken", + "removeToken", + "removeRange", + "replaceToken", + "replaceRange", + "composeRUD", + "updateContextsRanges" + ]; + coreEvents.forEach(function(eventId) { + Object.defineProperty(this$1.events, eventId, { + value: new Event(eventId) + }); + }); + if (!!events) { + coreEvents.forEach(function(eventId) { + var event = events[eventId]; + if (typeof event === "function") { + this$1.events[eventId].subscribe(event); + } + }); + } + var requiresContextUpdate = [ + "insertToken", + "removeToken", + "removeRange", + "replaceToken", + "replaceRange", + "composeRUD" + ]; + requiresContextUpdate.forEach(function(eventId) { + this$1.events[eventId].subscribe(this$1.updateContextsRanges); + }); +} +function Tokenizer(events) { + this.tokens = []; + this.registeredContexts = {}; + this.contextCheckers = []; + this.events = {}; + this.registeredModifiers = []; + initializeCoreEvents.call(this, events); +} +Token.prototype.setState = function(key2, value2) { + this.state[key2] = value2; + this.activeState = { key: key2, value: this.state[key2] }; + return this.activeState; +}; +Token.prototype.getState = function(stateId) { + return this.state[stateId] || null; +}; +Tokenizer.prototype.inboundIndex = function(index2) { + return index2 >= 0 && index2 < this.tokens.length; +}; +Tokenizer.prototype.composeRUD = function(RUDs) { + var this$1 = this; + var silent = true; + var state = RUDs.map(function(RUD) { + return this$1[RUD[0]].apply(this$1, RUD.slice(1).concat(silent)); + }); + var hasFAILObject = function(obj) { + return typeof obj === "object" && obj.hasOwnProperty("FAIL"); + }; + if (state.every(hasFAILObject)) { + return { + FAIL: "composeRUD: one or more operations hasn't completed successfully", + report: state.filter(hasFAILObject) + }; + } + this.dispatch("composeRUD", [state.filter(function(op) { + return !hasFAILObject(op); + })]); +}; +Tokenizer.prototype.replaceRange = function(startIndex, offset, tokens, silent) { + offset = offset !== null ? offset : this.tokens.length; + var isTokenType = tokens.every(function(token) { + return token instanceof Token; + }); + if (!isNaN(startIndex) && this.inboundIndex(startIndex) && isTokenType) { + var replaced = this.tokens.splice.apply(this.tokens, [startIndex, offset].concat(tokens)); + if (!silent) { + this.dispatch("replaceToken", [startIndex, offset, tokens]); + } + return [replaced, tokens]; + } else { + return { FAIL: "replaceRange: invalid tokens or startIndex." }; + } +}; +Tokenizer.prototype.replaceToken = function(index2, token, silent) { + if (!isNaN(index2) && this.inboundIndex(index2) && token instanceof Token) { + var replaced = this.tokens.splice(index2, 1, token); + if (!silent) { + this.dispatch("replaceToken", [index2, token]); + } + return [replaced[0], token]; + } else { + return { FAIL: "replaceToken: invalid token or index." }; + } +}; +Tokenizer.prototype.removeRange = function(startIndex, offset, silent) { + offset = !isNaN(offset) ? offset : this.tokens.length; + var tokens = this.tokens.splice(startIndex, offset); + if (!silent) { + this.dispatch("removeRange", [tokens, startIndex, offset]); + } + return tokens; +}; +Tokenizer.prototype.removeToken = function(index2, silent) { + if (!isNaN(index2) && this.inboundIndex(index2)) { + var token = this.tokens.splice(index2, 1); + if (!silent) { + this.dispatch("removeToken", [token, index2]); + } + return token; + } else { + return { FAIL: "removeToken: invalid token index." }; + } +}; +Tokenizer.prototype.insertToken = function(tokens, index2, silent) { + var tokenType = tokens.every(function(token) { + return token instanceof Token; + }); + if (tokenType) { + this.tokens.splice.apply(this.tokens, [index2, 0].concat(tokens)); + if (!silent) { + this.dispatch("insertToken", [tokens, index2]); + } + return tokens; + } else { + return { FAIL: "insertToken: invalid token(s)." }; + } +}; +Tokenizer.prototype.registerModifier = function(modifierId, condition, modifier) { + this.events.newToken.subscribe(function(token, contextParams) { + var conditionParams = [token, contextParams]; + var canApplyModifier = condition === null || condition.apply(this, conditionParams) === true; + var modifierParams = [token, contextParams]; + if (canApplyModifier) { + var newStateValue = modifier.apply(this, modifierParams); + token.setState(modifierId, newStateValue); + } + }); + this.registeredModifiers.push(modifierId); +}; +Event.prototype.subscribe = function(eventHandler) { + if (typeof eventHandler === "function") { + return this.subscribers.push(eventHandler) - 1; + } else { + return { FAIL: "invalid '" + this.eventId + "' event handler" }; + } +}; +Event.prototype.unsubscribe = function(subsId) { + this.subscribers.splice(subsId, 1); +}; +ContextParams.prototype.setCurrentIndex = function(index2) { + this.index = index2; + this.current = this.context[index2]; + this.backtrack = this.context.slice(0, index2); + this.lookahead = this.context.slice(index2 + 1); +}; +ContextParams.prototype.get = function(offset) { + switch (true) { + case offset === 0: + return this.current; + case (offset < 0 && Math.abs(offset) <= this.backtrack.length): + return this.backtrack.slice(offset)[0]; + case (offset > 0 && offset <= this.lookahead.length): + return this.lookahead[offset - 1]; + default: + return null; + } +}; +Tokenizer.prototype.rangeToText = function(range) { + if (range instanceof ContextRange) { + return this.getRangeTokens(range).map(function(token) { + return token.char; + }).join(""); + } +}; +Tokenizer.prototype.getText = function() { + return this.tokens.map(function(token) { + return token.char; + }).join(""); +}; +Tokenizer.prototype.getContext = function(contextName) { + var context = this.registeredContexts[contextName]; + return context ? context : null; +}; +Tokenizer.prototype.on = function(eventName, eventHandler) { + var event = this.events[eventName]; + if (!!event) { + return event.subscribe(eventHandler); + } else { + return null; + } +}; +Tokenizer.prototype.dispatch = function(eventName, args) { + var this$1 = this; + var event = this.events[eventName]; + if (event instanceof Event) { + event.subscribers.forEach(function(subscriber) { + subscriber.apply(this$1, args || []); + }); + } +}; +Tokenizer.prototype.registerContextChecker = function(contextName, contextStartCheck, contextEndCheck) { + if (!!this.getContext(contextName)) { + return { + FAIL: "context name '" + contextName + "' is already registered." + }; + } + if (typeof contextStartCheck !== "function") { + return { + FAIL: "missing context start check." + }; + } + if (typeof contextEndCheck !== "function") { + return { + FAIL: "missing context end check." + }; + } + var contextCheckers = new ContextChecker(contextName, contextStartCheck, contextEndCheck); + this.registeredContexts[contextName] = contextCheckers; + this.contextCheckers.push(contextCheckers); + return contextCheckers; +}; +Tokenizer.prototype.getRangeTokens = function(range) { + var endIndex = range.startIndex + range.endOffset; + return [].concat(this.tokens.slice(range.startIndex, endIndex)); +}; +Tokenizer.prototype.getContextRanges = function(contextName) { + var context = this.getContext(contextName); + if (!!context) { + return context.ranges; + } else { + return { FAIL: "context checker '" + contextName + "' is not registered." }; + } +}; +Tokenizer.prototype.resetContextsRanges = function() { + var registeredContexts = this.registeredContexts; + for (var contextName in registeredContexts) { + if (registeredContexts.hasOwnProperty(contextName)) { + var context = registeredContexts[contextName]; + context.ranges = []; + } + } +}; +Tokenizer.prototype.updateContextsRanges = function() { + this.resetContextsRanges(); + var chars = this.tokens.map(function(token) { + return token.char; + }); + for (var i = 0;i < chars.length; i++) { + var contextParams = new ContextParams(chars, i); + this.runContextCheck(contextParams); + } + this.dispatch("updateContextsRanges", [this.registeredContexts]); +}; +Tokenizer.prototype.setEndOffset = function(offset, contextName) { + var startIndex = this.getContext(contextName).openRange.startIndex; + var range = new ContextRange(startIndex, offset, contextName); + var ranges = this.getContext(contextName).ranges; + range.rangeId = contextName + "." + ranges.length; + ranges.push(range); + this.getContext(contextName).openRange = null; + return range; +}; +Tokenizer.prototype.runContextCheck = function(contextParams) { + var this$1 = this; + var index2 = contextParams.index; + this.contextCheckers.forEach(function(contextChecker) { + var contextName = contextChecker.contextName; + var openRange = this$1.getContext(contextName).openRange; + if (!openRange && contextChecker.checkStart(contextParams)) { + openRange = new ContextRange(index2, null, contextName); + this$1.getContext(contextName).openRange = openRange; + this$1.dispatch("contextStart", [contextName, index2]); + } + if (!!openRange && contextChecker.checkEnd(contextParams)) { + var offset = index2 - openRange.startIndex + 1; + var range = this$1.setEndOffset(offset, contextName); + this$1.dispatch("contextEnd", [contextName, range]); + } + }); +}; +Tokenizer.prototype.tokenize = function(text2) { + this.tokens = []; + this.resetContextsRanges(); + var chars = Array.from(text2); + this.dispatch("start"); + for (var i = 0;i < chars.length; i++) { + var char = chars[i]; + var contextParams = new ContextParams(chars, i); + this.dispatch("next", [contextParams]); + this.runContextCheck(contextParams); + var token = new Token(char); + this.tokens.push(token); + this.dispatch("newToken", [token, contextParams]); + } + this.dispatch("end", [this.tokens]); + return this.tokens; +}; +function isArabicChar(c) { + return /[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(c); +} +function isIsolatedArabicChar(char) { + return /[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(char); +} +function isTashkeelArabicChar(char) { + return /[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(char); +} +function isLatinChar(c) { + return /[A-z]/.test(c); +} +function isWhiteSpace(c) { + return /\s/.test(c); +} +function FeatureQuery(font) { + this.font = font; + this.features = {}; +} +function SubstitutionAction(action) { + this.id = action.id; + this.tag = action.tag; + this.substitution = action.substitution; +} +function lookupCoverage(glyphIndex, coverage) { + if (!glyphIndex) { + return -1; + } + switch (coverage.format) { + case 1: + return coverage.glyphs.indexOf(glyphIndex); + case 2: + var ranges = coverage.ranges; + for (var i = 0;i < ranges.length; i++) { + var range = ranges[i]; + if (glyphIndex >= range.start && glyphIndex <= range.end) { + var offset = glyphIndex - range.start; + return range.index + offset; + } + } + break; + default: + return -1; + } + return -1; +} +function singleSubstitutionFormat1(glyphIndex, subtable) { + var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (substituteIndex === -1) { + return null; + } + return glyphIndex + subtable.deltaGlyphId; +} +function singleSubstitutionFormat2(glyphIndex, subtable) { + var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (substituteIndex === -1) { + return null; + } + return subtable.substitute[substituteIndex]; +} +function lookupCoverageList(coverageList, contextParams) { + var lookupList = []; + for (var i = 0;i < coverageList.length; i++) { + var coverage = coverageList[i]; + var glyphIndex = contextParams.current; + glyphIndex = Array.isArray(glyphIndex) ? glyphIndex[0] : glyphIndex; + var lookupIndex = lookupCoverage(glyphIndex, coverage); + if (lookupIndex !== -1) { + lookupList.push(lookupIndex); + } + } + if (lookupList.length !== coverageList.length) { + return -1; + } + return lookupList; +} +function chainingSubstitutionFormat3(contextParams, subtable) { + var lookupsCount = subtable.inputCoverage.length + subtable.lookaheadCoverage.length + subtable.backtrackCoverage.length; + if (contextParams.context.length < lookupsCount) { + return []; + } + var inputLookups = lookupCoverageList(subtable.inputCoverage, contextParams); + if (inputLookups === -1) { + return []; + } + var lookaheadOffset = subtable.inputCoverage.length - 1; + if (contextParams.lookahead.length < subtable.lookaheadCoverage.length) { + return []; + } + var lookaheadContext = contextParams.lookahead.slice(lookaheadOffset); + while (lookaheadContext.length && isTashkeelArabicChar(lookaheadContext[0].char)) { + lookaheadContext.shift(); + } + var lookaheadParams = new ContextParams(lookaheadContext, 0); + var lookaheadLookups = lookupCoverageList(subtable.lookaheadCoverage, lookaheadParams); + var backtrackContext = [].concat(contextParams.backtrack); + backtrackContext.reverse(); + while (backtrackContext.length && isTashkeelArabicChar(backtrackContext[0].char)) { + backtrackContext.shift(); + } + if (backtrackContext.length < subtable.backtrackCoverage.length) { + return []; + } + var backtrackParams = new ContextParams(backtrackContext, 0); + var backtrackLookups = lookupCoverageList(subtable.backtrackCoverage, backtrackParams); + var contextRulesMatch = inputLookups.length === subtable.inputCoverage.length && lookaheadLookups.length === subtable.lookaheadCoverage.length && backtrackLookups.length === subtable.backtrackCoverage.length; + var substitutions = []; + if (contextRulesMatch) { + for (var i = 0;i < subtable.lookupRecords.length; i++) { + var lookupRecord = subtable.lookupRecords[i]; + var lookupListIndex = lookupRecord.lookupListIndex; + var lookupTable = this.getLookupByIndex(lookupListIndex); + for (var s = 0;s < lookupTable.subtables.length; s++) { + var subtable$1 = lookupTable.subtables[s]; + var lookup = this.getLookupMethod(lookupTable, subtable$1); + var substitutionType = this.getSubstitutionType(lookupTable, subtable$1); + if (substitutionType === "12") { + for (var n2 = 0;n2 < inputLookups.length; n2++) { + var glyphIndex = contextParams.get(n2); + var substitution = lookup(glyphIndex); + if (substitution) { + substitutions.push(substitution); + } + } + } + } + } + } + return substitutions; +} +function ligatureSubstitutionFormat1(contextParams, subtable) { + var glyphIndex = contextParams.current; + var ligSetIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (ligSetIndex === -1) { + return null; + } + var ligature; + var ligatureSet = subtable.ligatureSets[ligSetIndex]; + for (var s = 0;s < ligatureSet.length; s++) { + ligature = ligatureSet[s]; + for (var l2 = 0;l2 < ligature.components.length; l2++) { + var lookaheadItem = contextParams.lookahead[l2]; + var component = ligature.components[l2]; + if (lookaheadItem !== component) { + break; + } + if (l2 === ligature.components.length - 1) { + return ligature; + } + } + } + return null; +} +function decompositionSubstitutionFormat1(glyphIndex, subtable) { + var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (substituteIndex === -1) { + return null; + } + return subtable.sequences[substituteIndex]; +} +FeatureQuery.prototype.getDefaultScriptFeaturesIndexes = function() { + var scripts = this.font.tables.gsub.scripts; + for (var s = 0;s < scripts.length; s++) { + var script = scripts[s]; + if (script.tag === "DFLT") { + return script.script.defaultLangSys.featureIndexes; + } + } + return []; +}; +FeatureQuery.prototype.getScriptFeaturesIndexes = function(scriptTag) { + var tables = this.font.tables; + if (!tables.gsub) { + return []; + } + if (!scriptTag) { + return this.getDefaultScriptFeaturesIndexes(); + } + var scripts = this.font.tables.gsub.scripts; + for (var i = 0;i < scripts.length; i++) { + var script = scripts[i]; + if (script.tag === scriptTag && script.script.defaultLangSys) { + return script.script.defaultLangSys.featureIndexes; + } else { + var langSysRecords = script.langSysRecords; + if (!!langSysRecords) { + for (var j2 = 0;j2 < langSysRecords.length; j2++) { + var langSysRecord = langSysRecords[j2]; + if (langSysRecord.tag === scriptTag) { + var langSys = langSysRecord.langSys; + return langSys.featureIndexes; + } + } + } + } + } + return this.getDefaultScriptFeaturesIndexes(); +}; +FeatureQuery.prototype.mapTagsToFeatures = function(features, scriptTag) { + var tags = {}; + for (var i = 0;i < features.length; i++) { + var tag = features[i].tag; + var feature = features[i].feature; + tags[tag] = feature; + } + this.features[scriptTag].tags = tags; +}; +FeatureQuery.prototype.getScriptFeatures = function(scriptTag) { + var features = this.features[scriptTag]; + if (this.features.hasOwnProperty(scriptTag)) { + return features; + } + var featuresIndexes = this.getScriptFeaturesIndexes(scriptTag); + if (!featuresIndexes) { + return null; + } + var gsub2 = this.font.tables.gsub; + features = featuresIndexes.map(function(index2) { + return gsub2.features[index2]; + }); + this.features[scriptTag] = features; + this.mapTagsToFeatures(features, scriptTag); + return features; +}; +FeatureQuery.prototype.getSubstitutionType = function(lookupTable, subtable) { + var lookupType = lookupTable.lookupType.toString(); + var substFormat = subtable.substFormat.toString(); + return lookupType + substFormat; +}; +FeatureQuery.prototype.getLookupMethod = function(lookupTable, subtable) { + var this$1 = this; + var substitutionType = this.getSubstitutionType(lookupTable, subtable); + switch (substitutionType) { + case "11": + return function(glyphIndex) { + return singleSubstitutionFormat1.apply(this$1, [glyphIndex, subtable]); + }; + case "12": + return function(glyphIndex) { + return singleSubstitutionFormat2.apply(this$1, [glyphIndex, subtable]); + }; + case "63": + return function(contextParams) { + return chainingSubstitutionFormat3.apply(this$1, [contextParams, subtable]); + }; + case "41": + return function(contextParams) { + return ligatureSubstitutionFormat1.apply(this$1, [contextParams, subtable]); + }; + case "21": + return function(glyphIndex) { + return decompositionSubstitutionFormat1.apply(this$1, [glyphIndex, subtable]); + }; + default: + throw new Error("lookupType: " + lookupTable.lookupType + " - " + "substFormat: " + subtable.substFormat + " " + "is not yet supported"); + } +}; +FeatureQuery.prototype.lookupFeature = function(query) { + var contextParams = query.contextParams; + var currentIndex = contextParams.index; + var feature = this.getFeature({ + tag: query.tag, + script: query.script + }); + if (!feature) { + return new Error("font '" + this.font.names.fullName.en + "' " + "doesn't support feature '" + query.tag + "' " + "for script '" + query.script + "'."); + } + var lookups = this.getFeatureLookups(feature); + var substitutions = [].concat(contextParams.context); + for (var l2 = 0;l2 < lookups.length; l2++) { + var lookupTable = lookups[l2]; + var subtables = this.getLookupSubtables(lookupTable); + for (var s = 0;s < subtables.length; s++) { + var subtable = subtables[s]; + var substType = this.getSubstitutionType(lookupTable, subtable); + var lookup = this.getLookupMethod(lookupTable, subtable); + var substitution = undefined; + switch (substType) { + case "11": + substitution = lookup(contextParams.current); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 11, + tag: query.tag, + substitution + })); + } + break; + case "12": + substitution = lookup(contextParams.current); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 12, + tag: query.tag, + substitution + })); + } + break; + case "63": + substitution = lookup(contextParams); + if (Array.isArray(substitution) && substitution.length) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 63, + tag: query.tag, + substitution + })); + } + break; + case "41": + substitution = lookup(contextParams); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 41, + tag: query.tag, + substitution + })); + } + break; + case "21": + substitution = lookup(contextParams.current); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 21, + tag: query.tag, + substitution + })); + } + break; + } + contextParams = new ContextParams(substitutions, currentIndex); + if (Array.isArray(substitution) && !substitution.length) { + continue; + } + substitution = null; + } + } + return substitutions.length ? substitutions : null; +}; +FeatureQuery.prototype.supports = function(query) { + if (!query.script) { + return false; + } + this.getScriptFeatures(query.script); + var supportedScript = this.features.hasOwnProperty(query.script); + if (!query.tag) { + return supportedScript; + } + var supportedFeature = this.features[query.script].some(function(feature) { + return feature.tag === query.tag; + }); + return supportedScript && supportedFeature; +}; +FeatureQuery.prototype.getLookupSubtables = function(lookupTable) { + return lookupTable.subtables || null; +}; +FeatureQuery.prototype.getLookupByIndex = function(index2) { + var lookups = this.font.tables.gsub.lookups; + return lookups[index2] || null; +}; +FeatureQuery.prototype.getFeatureLookups = function(feature) { + return feature.lookupListIndexes.map(this.getLookupByIndex.bind(this)); +}; +FeatureQuery.prototype.getFeature = function getFeature(query) { + if (!this.font) { + return { FAIL: "No font was found" }; + } + if (!this.features.hasOwnProperty(query.script)) { + this.getScriptFeatures(query.script); + } + var scriptFeatures = this.features[query.script]; + if (!scriptFeatures) { + return { FAIL: "No feature for script " + query.script }; + } + if (!scriptFeatures.tags[query.tag]) { + return null; + } + return this.features[query.script].tags[query.tag]; +}; +function arabicWordStartCheck(contextParams) { + var char = contextParams.current; + var prevChar = contextParams.get(-1); + return prevChar === null && isArabicChar(char) || !isArabicChar(prevChar) && isArabicChar(char); +} +function arabicWordEndCheck(contextParams) { + var nextChar = contextParams.get(1); + return nextChar === null || !isArabicChar(nextChar); +} +var arabicWordCheck = { + startCheck: arabicWordStartCheck, + endCheck: arabicWordEndCheck +}; +function arabicSentenceStartCheck(contextParams) { + var char = contextParams.current; + var prevChar = contextParams.get(-1); + return (isArabicChar(char) || isTashkeelArabicChar(char)) && !isArabicChar(prevChar); +} +function arabicSentenceEndCheck(contextParams) { + var nextChar = contextParams.get(1); + switch (true) { + case nextChar === null: + return true; + case (!isArabicChar(nextChar) && !isTashkeelArabicChar(nextChar)): + var nextIsWhitespace = isWhiteSpace(nextChar); + if (!nextIsWhitespace) { + return true; + } + if (nextIsWhitespace) { + var arabicCharAhead = false; + arabicCharAhead = contextParams.lookahead.some(function(c) { + return isArabicChar(c) || isTashkeelArabicChar(c); + }); + if (!arabicCharAhead) { + return true; + } + } + break; + default: + return false; + } +} +var arabicSentenceCheck = { + startCheck: arabicSentenceStartCheck, + endCheck: arabicSentenceEndCheck +}; +function singleSubstitutionFormat1$1(action, tokens, index2) { + tokens[index2].setState(action.tag, action.substitution); +} +function singleSubstitutionFormat2$1(action, tokens, index2) { + tokens[index2].setState(action.tag, action.substitution); +} +function chainingSubstitutionFormat3$1(action, tokens, index2) { + action.substitution.forEach(function(subst, offset) { + var token = tokens[index2 + offset]; + token.setState(action.tag, subst); + }); +} +function ligatureSubstitutionFormat1$1(action, tokens, index2) { + var token = tokens[index2]; + token.setState(action.tag, action.substitution.ligGlyph); + var compsCount = action.substitution.components.length; + for (var i = 0;i < compsCount; i++) { + token = tokens[index2 + i + 1]; + token.setState("deleted", true); + } +} +var SUBSTITUTIONS = { + 11: singleSubstitutionFormat1$1, + 12: singleSubstitutionFormat2$1, + 63: chainingSubstitutionFormat3$1, + 41: ligatureSubstitutionFormat1$1 +}; +function applySubstitution(action, tokens, index2) { + if (action instanceof SubstitutionAction && SUBSTITUTIONS[action.id]) { + SUBSTITUTIONS[action.id](action, tokens, index2); + } +} +function willConnectPrev(charContextParams) { + var backtrack = [].concat(charContextParams.backtrack); + for (var i = backtrack.length - 1;i >= 0; i--) { + var prevChar = backtrack[i]; + var isolated = isIsolatedArabicChar(prevChar); + var tashkeel = isTashkeelArabicChar(prevChar); + if (!isolated && !tashkeel) { + return true; + } + if (isolated) { + return false; + } + } + return false; +} +function willConnectNext(charContextParams) { + if (isIsolatedArabicChar(charContextParams.current)) { + return false; + } + for (var i = 0;i < charContextParams.lookahead.length; i++) { + var nextChar = charContextParams.lookahead[i]; + var tashkeel = isTashkeelArabicChar(nextChar); + if (!tashkeel) { + return true; + } + } + return false; +} +function arabicPresentationForms(range) { + var this$1 = this; + var script = "arab"; + var tags = this.featuresTags[script]; + var tokens = this.tokenizer.getRangeTokens(range); + if (tokens.length === 1) { + return; + } + var contextParams = new ContextParams(tokens.map(function(token) { + return token.getState("glyphIndex"); + }), 0); + var charContextParams = new ContextParams(tokens.map(function(token) { + return token.char; + }), 0); + tokens.forEach(function(token, index2) { + if (isTashkeelArabicChar(token.char)) { + return; + } + contextParams.setCurrentIndex(index2); + charContextParams.setCurrentIndex(index2); + var CONNECT = 0; + if (willConnectPrev(charContextParams)) { + CONNECT |= 1; + } + if (willConnectNext(charContextParams)) { + CONNECT |= 2; + } + var tag; + switch (CONNECT) { + case 1: + tag = "fina"; + break; + case 2: + tag = "init"; + break; + case 3: + tag = "medi"; + break; + } + if (tags.indexOf(tag) === -1) { + return; + } + var substitutions = this$1.query.lookupFeature({ + tag, + script, + contextParams + }); + if (substitutions instanceof Error) { + return console.info(substitutions.message); + } + substitutions.forEach(function(action, index3) { + if (action instanceof SubstitutionAction) { + applySubstitution(action, tokens, index3); + contextParams.context[index3] = action.substitution; + } + }); + }); +} +function getContextParams(tokens, index2) { + var context = tokens.map(function(token) { + return token.activeState.value; + }); + return new ContextParams(context, index2 || 0); +} +function arabicRequiredLigatures(range) { + var this$1 = this; + var script = "arab"; + var tokens = this.tokenizer.getRangeTokens(range); + var contextParams = getContextParams(tokens); + contextParams.context.forEach(function(glyphIndex, index2) { + contextParams.setCurrentIndex(index2); + var substitutions = this$1.query.lookupFeature({ + tag: "rlig", + script, + contextParams + }); + if (substitutions.length) { + substitutions.forEach(function(action) { + return applySubstitution(action, tokens, index2); + }); + contextParams = getContextParams(tokens); + } + }); +} +function latinWordStartCheck(contextParams) { + var char = contextParams.current; + var prevChar = contextParams.get(-1); + return prevChar === null && isLatinChar(char) || !isLatinChar(prevChar) && isLatinChar(char); +} +function latinWordEndCheck(contextParams) { + var nextChar = contextParams.get(1); + return nextChar === null || !isLatinChar(nextChar); +} +var latinWordCheck = { + startCheck: latinWordStartCheck, + endCheck: latinWordEndCheck +}; +function getContextParams$1(tokens, index2) { + var context = tokens.map(function(token) { + return token.activeState.value; + }); + return new ContextParams(context, index2 || 0); +} +function latinLigature(range) { + var this$1 = this; + var script = "latn"; + var tokens = this.tokenizer.getRangeTokens(range); + var contextParams = getContextParams$1(tokens); + contextParams.context.forEach(function(glyphIndex, index2) { + contextParams.setCurrentIndex(index2); + var substitutions = this$1.query.lookupFeature({ + tag: "liga", + script, + contextParams + }); + if (substitutions.length) { + substitutions.forEach(function(action) { + return applySubstitution(action, tokens, index2); + }); + contextParams = getContextParams$1(tokens); + } + }); +} +function Bidi(baseDir) { + this.baseDir = baseDir || "ltr"; + this.tokenizer = new Tokenizer; + this.featuresTags = {}; +} +Bidi.prototype.setText = function(text2) { + this.text = text2; +}; +Bidi.prototype.contextChecks = { + latinWordCheck, + arabicWordCheck, + arabicSentenceCheck +}; +function registerContextChecker(checkId) { + var check2 = this.contextChecks[checkId + "Check"]; + return this.tokenizer.registerContextChecker(checkId, check2.startCheck, check2.endCheck); +} +function tokenizeText() { + registerContextChecker.call(this, "latinWord"); + registerContextChecker.call(this, "arabicWord"); + registerContextChecker.call(this, "arabicSentence"); + return this.tokenizer.tokenize(this.text); +} +function reverseArabicSentences() { + var this$1 = this; + var ranges = this.tokenizer.getContextRanges("arabicSentence"); + ranges.forEach(function(range) { + var rangeTokens = this$1.tokenizer.getRangeTokens(range); + this$1.tokenizer.replaceRange(range.startIndex, range.endOffset, rangeTokens.reverse()); + }); +} +Bidi.prototype.registerFeatures = function(script, tags) { + var this$1 = this; + var supportedTags = tags.filter(function(tag) { + return this$1.query.supports({ script, tag }); + }); + if (!this.featuresTags.hasOwnProperty(script)) { + this.featuresTags[script] = supportedTags; + } else { + this.featuresTags[script] = this.featuresTags[script].concat(supportedTags); + } +}; +Bidi.prototype.applyFeatures = function(font, features) { + if (!font) { + throw new Error("No valid font was provided to apply features"); + } + if (!this.query) { + this.query = new FeatureQuery(font); + } + for (var f = 0;f < features.length; f++) { + var feature = features[f]; + if (!this.query.supports({ script: feature.script })) { + continue; + } + this.registerFeatures(feature.script, feature.tags); + } +}; +Bidi.prototype.registerModifier = function(modifierId, condition, modifier) { + this.tokenizer.registerModifier(modifierId, condition, modifier); +}; +function checkGlyphIndexStatus() { + if (this.tokenizer.registeredModifiers.indexOf("glyphIndex") === -1) { + throw new Error("glyphIndex modifier is required to apply " + "arabic presentation features."); + } +} +function applyArabicPresentationForms() { + var this$1 = this; + var script = "arab"; + if (!this.featuresTags.hasOwnProperty(script)) { + return; + } + checkGlyphIndexStatus.call(this); + var ranges = this.tokenizer.getContextRanges("arabicWord"); + ranges.forEach(function(range) { + arabicPresentationForms.call(this$1, range); + }); +} +function applyArabicRequireLigatures() { + var this$1 = this; + var script = "arab"; + if (!this.featuresTags.hasOwnProperty(script)) { + return; + } + var tags = this.featuresTags[script]; + if (tags.indexOf("rlig") === -1) { + return; + } + checkGlyphIndexStatus.call(this); + var ranges = this.tokenizer.getContextRanges("arabicWord"); + ranges.forEach(function(range) { + arabicRequiredLigatures.call(this$1, range); + }); +} +function applyLatinLigatures() { + var this$1 = this; + var script = "latn"; + if (!this.featuresTags.hasOwnProperty(script)) { + return; + } + var tags = this.featuresTags[script]; + if (tags.indexOf("liga") === -1) { + return; + } + checkGlyphIndexStatus.call(this); + var ranges = this.tokenizer.getContextRanges("latinWord"); + ranges.forEach(function(range) { + latinLigature.call(this$1, range); + }); +} +Bidi.prototype.checkContextReady = function(contextId) { + return !!this.tokenizer.getContext(contextId); +}; +Bidi.prototype.applyFeaturesToContexts = function() { + if (this.checkContextReady("arabicWord")) { + applyArabicPresentationForms.call(this); + applyArabicRequireLigatures.call(this); + } + if (this.checkContextReady("latinWord")) { + applyLatinLigatures.call(this); + } + if (this.checkContextReady("arabicSentence")) { + reverseArabicSentences.call(this); + } +}; +Bidi.prototype.processText = function(text2) { + if (!this.text || this.text !== text2) { + this.setText(text2); + tokenizeText.call(this); + this.applyFeaturesToContexts(); + } +}; +Bidi.prototype.getBidiText = function(text2) { + this.processText(text2); + return this.tokenizer.getText(); +}; +Bidi.prototype.getTextGlyphs = function(text2) { + this.processText(text2); + var indexes = []; + for (var i = 0;i < this.tokenizer.tokens.length; i++) { + var token = this.tokenizer.tokens[i]; + if (token.state.deleted) { + continue; + } + var index2 = token.activeState.value; + indexes.push(Array.isArray(index2) ? index2[0] : index2); + } + return indexes; +}; +function Font(options) { + options = options || {}; + options.tables = options.tables || {}; + if (!options.empty) { + checkArgument(options.familyName, "When creating a new Font object, familyName is required."); + checkArgument(options.styleName, "When creating a new Font object, styleName is required."); + checkArgument(options.unitsPerEm, "When creating a new Font object, unitsPerEm is required."); + checkArgument(options.ascender, "When creating a new Font object, ascender is required."); + checkArgument(options.descender <= 0, "When creating a new Font object, negative descender value is required."); + this.names = { + fontFamily: { en: options.familyName || " " }, + fontSubfamily: { en: options.styleName || " " }, + fullName: { en: options.fullName || options.familyName + " " + options.styleName }, + postScriptName: { en: options.postScriptName || (options.familyName + options.styleName).replace(/\s/g, "") }, + designer: { en: options.designer || " " }, + designerURL: { en: options.designerURL || " " }, + manufacturer: { en: options.manufacturer || " " }, + manufacturerURL: { en: options.manufacturerURL || " " }, + license: { en: options.license || " " }, + licenseURL: { en: options.licenseURL || " " }, + version: { en: options.version || "Version 0.1" }, + description: { en: options.description || " " }, + copyright: { en: options.copyright || " " }, + trademark: { en: options.trademark || " " } + }; + this.unitsPerEm = options.unitsPerEm || 1000; + this.ascender = options.ascender; + this.descender = options.descender; + this.createdTimestamp = options.createdTimestamp; + this.tables = Object.assign(options.tables, { + os2: Object.assign({ + usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM, + usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM, + fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR + }, options.tables.os2) + }); + } + this.supported = true; + this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []); + this.encoding = new DefaultEncoding(this); + this.position = new Position(this); + this.substitution = new Substitution(this); + this.tables = this.tables || {}; + this._push = null; + this._hmtxTableData = {}; + Object.defineProperty(this, "hinting", { + get: function() { + if (this._hinting) { + return this._hinting; + } + if (this.outlinesFormat === "truetype") { + return this._hinting = new Hinting(this); + } + } + }); +} +Font.prototype.hasChar = function(c) { + return this.encoding.charToGlyphIndex(c) !== null; +}; +Font.prototype.charToGlyphIndex = function(s) { + return this.encoding.charToGlyphIndex(s); +}; +Font.prototype.charToGlyph = function(c) { + var glyphIndex = this.charToGlyphIndex(c); + var glyph = this.glyphs.get(glyphIndex); + if (!glyph) { + glyph = this.glyphs.get(0); + } + return glyph; +}; +Font.prototype.updateFeatures = function(options) { + return this.defaultRenderOptions.features.map(function(feature) { + if (feature.script === "latn") { + return { + script: "latn", + tags: feature.tags.filter(function(tag) { + return options[tag]; + }) + }; + } else { + return feature; + } + }); +}; +Font.prototype.stringToGlyphs = function(s, options) { + var this$1 = this; + var bidi = new Bidi; + var charToGlyphIndexMod = function(token) { + return this$1.charToGlyphIndex(token.char); + }; + bidi.registerModifier("glyphIndex", null, charToGlyphIndexMod); + var features = options ? this.updateFeatures(options.features) : this.defaultRenderOptions.features; + bidi.applyFeatures(this, features); + var indexes = bidi.getTextGlyphs(s); + var length2 = indexes.length; + var glyphs = new Array(length2); + var notdef = this.glyphs.get(0); + for (var i = 0;i < length2; i += 1) { + glyphs[i] = this.glyphs.get(indexes[i]) || notdef; + } + return glyphs; +}; +Font.prototype.nameToGlyphIndex = function(name2) { + return this.glyphNames.nameToGlyphIndex(name2); +}; +Font.prototype.nameToGlyph = function(name2) { + var glyphIndex = this.nameToGlyphIndex(name2); + var glyph = this.glyphs.get(glyphIndex); + if (!glyph) { + glyph = this.glyphs.get(0); + } + return glyph; +}; +Font.prototype.glyphIndexToName = function(gid) { + if (!this.glyphNames.glyphIndexToName) { + return ""; + } + return this.glyphNames.glyphIndexToName(gid); +}; +Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) { + leftGlyph = leftGlyph.index || leftGlyph; + rightGlyph = rightGlyph.index || rightGlyph; + var gposKerning = this.position.defaultKerningTables; + if (gposKerning) { + return this.position.getKerningValue(gposKerning, leftGlyph, rightGlyph); + } + return this.kerningPairs[leftGlyph + "," + rightGlyph] || 0; +}; +Font.prototype.defaultRenderOptions = { + kerning: true, + features: [ + { script: "arab", tags: ["init", "medi", "fina", "rlig"] }, + { script: "latn", tags: ["liga", "rlig"] } + ] +}; +Font.prototype.forEachGlyph = function(text2, x2, y, fontSize, options, callback) { + x2 = x2 !== undefined ? x2 : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 72; + options = Object.assign({}, this.defaultRenderOptions, options); + var fontScale = 1 / this.unitsPerEm * fontSize; + var glyphs = this.stringToGlyphs(text2, options); + var kerningLookups; + if (options.kerning) { + var script = options.script || this.position.getDefaultScriptName(); + kerningLookups = this.position.getKerningTables(script, options.language); + } + for (var i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs[i]; + callback.call(this, glyph, x2, y, fontSize, options); + if (glyph.advanceWidth) { + x2 += glyph.advanceWidth * fontScale; + } + if (options.kerning && i < glyphs.length - 1) { + var kerningValue = kerningLookups ? this.position.getKerningValue(kerningLookups, glyph.index, glyphs[i + 1].index) : this.getKerningValue(glyph, glyphs[i + 1]); + x2 += kerningValue * fontScale; + } + if (options.letterSpacing) { + x2 += options.letterSpacing * fontSize; + } else if (options.tracking) { + x2 += options.tracking / 1000 * fontSize; + } + } + return x2; +}; +Font.prototype.getPath = function(text2, x2, y, fontSize, options) { + var fullPath = new Path2; + this.forEachGlyph(text2, x2, y, fontSize, options, function(glyph, gX, gY, gFontSize) { + var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); + fullPath.extend(glyphPath); + }); + return fullPath; +}; +Font.prototype.getPaths = function(text2, x2, y, fontSize, options) { + var glyphPaths = []; + this.forEachGlyph(text2, x2, y, fontSize, options, function(glyph, gX, gY, gFontSize) { + var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); + glyphPaths.push(glyphPath); + }); + return glyphPaths; +}; +Font.prototype.getAdvanceWidth = function(text2, fontSize, options) { + return this.forEachGlyph(text2, 0, 0, fontSize, options, function() { + }); +}; +Font.prototype.draw = function(ctx, text2, x2, y, fontSize, options) { + this.getPath(text2, x2, y, fontSize, options).draw(ctx); +}; +Font.prototype.drawPoints = function(ctx, text2, x2, y, fontSize, options) { + this.forEachGlyph(text2, x2, y, fontSize, options, function(glyph, gX, gY, gFontSize) { + glyph.drawPoints(ctx, gX, gY, gFontSize); + }); +}; +Font.prototype.drawMetrics = function(ctx, text2, x2, y, fontSize, options) { + this.forEachGlyph(text2, x2, y, fontSize, options, function(glyph, gX, gY, gFontSize) { + glyph.drawMetrics(ctx, gX, gY, gFontSize); + }); +}; +Font.prototype.getEnglishName = function(name2) { + var translations = this.names[name2]; + if (translations) { + return translations.en; + } +}; +Font.prototype.validate = function() { + var _this = this; + function assert(predicate, message) { + } + function assertNamePresent(name2) { + var englishName = _this.getEnglishName(name2); + assert(englishName && englishName.trim().length > 0); + } + assertNamePresent("fontFamily"); + assertNamePresent("weightName"); + assertNamePresent("manufacturer"); + assertNamePresent("copyright"); + assertNamePresent("version"); + assert(this.unitsPerEm > 0); +}; +Font.prototype.toTables = function() { + return sfnt.fontToTable(this); +}; +Font.prototype.toBuffer = function() { + console.warn("Font.toBuffer is deprecated. Use Font.toArrayBuffer instead."); + return this.toArrayBuffer(); +}; +Font.prototype.toArrayBuffer = function() { + var sfntTable = this.toTables(); + var bytes = sfntTable.encode(); + var buffer = new ArrayBuffer(bytes.length); + var intArray = new Uint8Array(buffer); + for (var i = 0;i < bytes.length; i++) { + intArray[i] = bytes[i]; + } + return buffer; +}; +Font.prototype.download = function(fileName) { + var familyName = this.getEnglishName("fontFamily"); + var styleName = this.getEnglishName("fontSubfamily"); + fileName = fileName || familyName.replace(/\s/g, "") + "-" + styleName + ".otf"; + var arrayBuffer = this.toArrayBuffer(); + window.URL = window.URL || window.webkitURL; + if (window.URL) { + var dataView = new DataView(arrayBuffer); + var blob = new Blob([dataView], { type: "font/opentype" }); + var link = document.createElement("a"); + link.href = window.URL.createObjectURL(blob); + link.download = fileName; + var event = document.createEvent("MouseEvents"); + event.initEvent("click", true, false); + link.dispatchEvent(event); + } else { + console.warn("Font file could not be downloaded. Try using a different browser."); + } +}; +Font.prototype.fsSelectionValues = { + ITALIC: 1, + UNDERSCORE: 2, + NEGATIVE: 4, + OUTLINED: 8, + STRIKEOUT: 16, + BOLD: 32, + REGULAR: 64, + USER_TYPO_METRICS: 128, + WWS: 256, + OBLIQUE: 512 +}; +Font.prototype.usWidthClasses = { + ULTRA_CONDENSED: 1, + EXTRA_CONDENSED: 2, + CONDENSED: 3, + SEMI_CONDENSED: 4, + MEDIUM: 5, + SEMI_EXPANDED: 6, + EXPANDED: 7, + EXTRA_EXPANDED: 8, + ULTRA_EXPANDED: 9 +}; +Font.prototype.usWeightClasses = { + THIN: 100, + EXTRA_LIGHT: 200, + LIGHT: 300, + NORMAL: 400, + MEDIUM: 500, + SEMI_BOLD: 600, + BOLD: 700, + EXTRA_BOLD: 800, + BLACK: 900 +}; +var subtableParsers$1 = new Array(10); +subtableParsers$1[1] = function parseLookup12() { + var start = this.offset + this.relativeOffset; + var posformat = this.parseUShort(); + if (posformat === 1) { + return { + posFormat: 1, + coverage: this.parsePointer(Parser.coverage), + value: this.parseValueRecord() + }; + } else if (posformat === 2) { + return { + posFormat: 2, + coverage: this.parsePointer(Parser.coverage), + values: this.parseValueRecordList() + }; + } + check.assert(false, "0x" + start.toString(16) + ": GPOS lookup type 1 format must be 1 or 2."); +}; +subtableParsers$1[2] = function parseLookup22() { + var start = this.offset + this.relativeOffset; + var posFormat = this.parseUShort(); + check.assert(posFormat === 1 || posFormat === 2, "0x" + start.toString(16) + ": GPOS lookup type 2 format must be 1 or 2."); + var coverage = this.parsePointer(Parser.coverage); + var valueFormat1 = this.parseUShort(); + var valueFormat2 = this.parseUShort(); + if (posFormat === 1) { + return { + posFormat, + coverage, + valueFormat1, + valueFormat2, + pairSets: this.parseList(Parser.pointer(Parser.list(function() { + return { + secondGlyph: this.parseUShort(), + value1: this.parseValueRecord(valueFormat1), + value2: this.parseValueRecord(valueFormat2) + }; + }))) + }; + } else if (posFormat === 2) { + var classDef1 = this.parsePointer(Parser.classDef); + var classDef2 = this.parsePointer(Parser.classDef); + var class1Count = this.parseUShort(); + var class2Count = this.parseUShort(); + return { + posFormat, + coverage, + valueFormat1, + valueFormat2, + classDef1, + classDef2, + class1Count, + class2Count, + classRecords: this.parseList(class1Count, Parser.list(class2Count, function() { + return { + value1: this.parseValueRecord(valueFormat1), + value2: this.parseValueRecord(valueFormat2) + }; + })) + }; + } +}; +subtableParsers$1[3] = function parseLookup32() { + return { error: "GPOS Lookup 3 not supported" }; +}; +subtableParsers$1[4] = function parseLookup42() { + return { error: "GPOS Lookup 4 not supported" }; +}; +subtableParsers$1[5] = function parseLookup52() { + return { error: "GPOS Lookup 5 not supported" }; +}; +subtableParsers$1[6] = function parseLookup62() { + return { error: "GPOS Lookup 6 not supported" }; +}; +subtableParsers$1[7] = function parseLookup72() { + return { error: "GPOS Lookup 7 not supported" }; +}; +subtableParsers$1[8] = function parseLookup82() { + return { error: "GPOS Lookup 8 not supported" }; +}; +subtableParsers$1[9] = function parseLookup9() { + return { error: "GPOS Lookup 9 not supported" }; +}; +var subtableMakers$1 = new Array(10); +// node_modules/three/examples/jsm/libs/chevrotain.module.min.js +/*! chevrotain - v9.0.1 */ +var R2 = (t2, e) => () => (e || (e = { exports: {} }, t2(e.exports, e)), e.exports); +var Er2 = R2((Pt) => { + Object.defineProperty(Pt, "__esModule", { value: true }); + Pt.VERSION = undefined; + Pt.VERSION = "9.0.1"; +}); +var k2 = R2((exports, module) => { + var __spreadArray = exports && exports.__spreadArray || function(t2, e) { + for (var r = 0, n2 = e.length, i = t2.length;r < n2; r++, i++) + t2[i] = e[r]; + return t2; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toFastProperties = exports.timer = exports.peek = exports.isES2015MapSupported = exports.PRINT_WARNING = exports.PRINT_ERROR = exports.packArray = exports.IDENTITY = exports.NOOP = exports.merge = exports.groupBy = exports.defaults = exports.assignNoOverwrite = exports.assign = exports.zipObject = exports.sortBy = exports.indexOf = exports.some = exports.difference = exports.every = exports.isObject = exports.isRegExp = exports.isArray = exports.partial = exports.uniq = exports.compact = exports.reduce = exports.findAll = exports.find = exports.cloneObj = exports.cloneArr = exports.contains = exports.has = exports.pick = exports.reject = exports.filter = exports.dropRight = exports.drop = exports.isFunction = exports.isUndefined = exports.isString = exports.forEach = exports.last = exports.first = exports.flatten = exports.map = exports.mapValues = exports.values = exports.keys = exports.isEmpty = undefined; + function isEmpty(t2) { + return t2 && t2.length === 0; + } + exports.isEmpty = isEmpty; + function keys(t2) { + return t2 == null ? [] : Object.keys(t2); + } + exports.keys = keys; + function values(t2) { + for (var e = [], r = Object.keys(t2), n2 = 0;n2 < r.length; n2++) + e.push(t2[r[n2]]); + return e; + } + exports.values = values; + function mapValues(t2, e) { + for (var r = [], n2 = keys(t2), i = 0;i < n2.length; i++) { + var a = n2[i]; + r.push(e.call(null, t2[a], a)); + } + return r; + } + exports.mapValues = mapValues; + function map(t2, e) { + for (var r = [], n2 = 0;n2 < t2.length; n2++) + r.push(e.call(null, t2[n2], n2)); + return r; + } + exports.map = map; + function flatten(t2) { + for (var e = [], r = 0;r < t2.length; r++) { + var n2 = t2[r]; + Array.isArray(n2) ? e = e.concat(flatten(n2)) : e.push(n2); + } + return e; + } + exports.flatten = flatten; + function first(t2) { + return isEmpty(t2) ? undefined : t2[0]; + } + exports.first = first; + function last(t2) { + var e = t2 && t2.length; + return e ? t2[e - 1] : undefined; + } + exports.last = last; + function forEach(t2, e) { + if (Array.isArray(t2)) + for (var r = 0;r < t2.length; r++) + e.call(null, t2[r], r); + else if (isObject(t2)) + for (var n2 = keys(t2), r = 0;r < n2.length; r++) { + var i = n2[r], a = t2[i]; + e.call(null, a, i); + } + else + throw Error("non exhaustive match"); + } + exports.forEach = forEach; + function isString(t2) { + return typeof t2 == "string"; + } + exports.isString = isString; + function isUndefined(t2) { + return t2 === undefined; + } + exports.isUndefined = isUndefined; + function isFunction(t2) { + return t2 instanceof Function; + } + exports.isFunction = isFunction; + function drop(t2, e) { + return e === undefined && (e = 1), t2.slice(e, t2.length); + } + exports.drop = drop; + function dropRight(t2, e) { + return e === undefined && (e = 1), t2.slice(0, t2.length - e); + } + exports.dropRight = dropRight; + function filter(t2, e) { + var r = []; + if (Array.isArray(t2)) + for (var n2 = 0;n2 < t2.length; n2++) { + var i = t2[n2]; + e.call(null, i) && r.push(i); + } + return r; + } + exports.filter = filter; + function reject(t2, e) { + return filter(t2, function(r) { + return !e(r); + }); + } + exports.reject = reject; + function pick(t2, e) { + for (var r = Object.keys(t2), n2 = {}, i = 0;i < r.length; i++) { + var a = r[i], o = t2[a]; + e(o) && (n2[a] = o); + } + return n2; + } + exports.pick = pick; + function has(t2, e) { + return isObject(t2) ? t2.hasOwnProperty(e) : false; + } + exports.has = has; + function contains(t2, e) { + return find(t2, function(r) { + return r === e; + }) !== undefined; + } + exports.contains = contains; + function cloneArr(t2) { + for (var e = [], r = 0;r < t2.length; r++) + e.push(t2[r]); + return e; + } + exports.cloneArr = cloneArr; + function cloneObj(t2) { + var e = {}; + for (var r in t2) + Object.prototype.hasOwnProperty.call(t2, r) && (e[r] = t2[r]); + return e; + } + exports.cloneObj = cloneObj; + function find(t2, e) { + for (var r = 0;r < t2.length; r++) { + var n2 = t2[r]; + if (e.call(null, n2)) + return n2; + } + } + exports.find = find; + function findAll(t2, e) { + for (var r = [], n2 = 0;n2 < t2.length; n2++) { + var i = t2[n2]; + e.call(null, i) && r.push(i); + } + return r; + } + exports.findAll = findAll; + function reduce(t2, e, r) { + for (var n2 = Array.isArray(t2), i = n2 ? t2 : values(t2), a = n2 ? [] : keys(t2), o = r, s = 0;s < i.length; s++) + o = e.call(null, o, i[s], n2 ? s : a[s]); + return o; + } + exports.reduce = reduce; + function compact(t2) { + return reject(t2, function(e) { + return e == null; + }); + } + exports.compact = compact; + function uniq(t2, e) { + e === undefined && (e = function(n2) { + return n2; + }); + var r = []; + return reduce(t2, function(n2, i) { + var a = e(i); + return contains(r, a) ? n2 : (r.push(a), n2.concat(i)); + }, []); + } + exports.uniq = uniq; + function partial(t2) { + for (var e = [], r = 1;r < arguments.length; r++) + e[r - 1] = arguments[r]; + var n2 = [null], i = n2.concat(e); + return Function.bind.apply(t2, i); + } + exports.partial = partial; + function isArray(t2) { + return Array.isArray(t2); + } + exports.isArray = isArray; + function isRegExp(t2) { + return t2 instanceof RegExp; + } + exports.isRegExp = isRegExp; + function isObject(t2) { + return t2 instanceof Object; + } + exports.isObject = isObject; + function every(t2, e) { + for (var r = 0;r < t2.length; r++) + if (!e(t2[r], r)) + return false; + return true; + } + exports.every = every; + function difference(t2, e) { + return reject(t2, function(r) { + return contains(e, r); + }); + } + exports.difference = difference; + function some(t2, e) { + for (var r = 0;r < t2.length; r++) + if (e(t2[r])) + return true; + return false; + } + exports.some = some; + function indexOf(t2, e) { + for (var r = 0;r < t2.length; r++) + if (t2[r] === e) + return r; + return -1; + } + exports.indexOf = indexOf; + function sortBy(t2, e) { + var r = cloneArr(t2); + return r.sort(function(n2, i) { + return e(n2) - e(i); + }), r; + } + exports.sortBy = sortBy; + function zipObject(t2, e) { + if (t2.length !== e.length) + throw Error("can't zipObject with different number of keys and values!"); + for (var r = {}, n2 = 0;n2 < t2.length; n2++) + r[t2[n2]] = e[n2]; + return r; + } + exports.zipObject = zipObject; + function assign(t2) { + for (var e = [], r = 1;r < arguments.length; r++) + e[r - 1] = arguments[r]; + for (var n2 = 0;n2 < e.length; n2++) + for (var i = e[n2], a = keys(i), o = 0;o < a.length; o++) { + var s = a[o]; + t2[s] = i[s]; + } + return t2; + } + exports.assign = assign; + function assignNoOverwrite(t2) { + for (var e = [], r = 1;r < arguments.length; r++) + e[r - 1] = arguments[r]; + for (var n2 = 0;n2 < e.length; n2++) + for (var i = e[n2], a = keys(i), o = 0;o < a.length; o++) { + var s = a[o]; + has(t2, s) || (t2[s] = i[s]); + } + return t2; + } + exports.assignNoOverwrite = assignNoOverwrite; + function defaults() { + for (var t2 = [], e = 0;e < arguments.length; e++) + t2[e] = arguments[e]; + return assignNoOverwrite.apply(undefined, __spreadArray([{}], t2)); + } + exports.defaults = defaults; + function groupBy(t2, e) { + var r = {}; + return forEach(t2, function(n2) { + var i = e(n2), a = r[i]; + a ? a.push(n2) : r[i] = [n2]; + }), r; + } + exports.groupBy = groupBy; + function merge(t2, e) { + for (var r = cloneObj(t2), n2 = keys(e), i = 0;i < n2.length; i++) { + var a = n2[i], o = e[a]; + r[a] = o; + } + return r; + } + exports.merge = merge; + function NOOP() { + } + exports.NOOP = NOOP; + function IDENTITY(t2) { + return t2; + } + exports.IDENTITY = IDENTITY; + function packArray(t2) { + for (var e = [], r = 0;r < t2.length; r++) { + var n2 = t2[r]; + e.push(n2 !== undefined ? n2 : undefined); + } + return e; + } + exports.packArray = packArray; + function PRINT_ERROR(t2) { + console && console.error && console.error("Error: " + t2); + } + exports.PRINT_ERROR = PRINT_ERROR; + function PRINT_WARNING(t2) { + console && console.warn && console.warn("Warning: " + t2); + } + exports.PRINT_WARNING = PRINT_WARNING; + function isES2015MapSupported() { + return typeof Map == "function"; + } + exports.isES2015MapSupported = isES2015MapSupported; + function peek(t2) { + return t2[t2.length - 1]; + } + exports.peek = peek; + function timer(t2) { + var e = new Date().getTime(), r = t2(), n2 = new Date().getTime(), i = n2 - e; + return { time: i, value: r }; + } + exports.timer = timer; + function toFastProperties(toBecomeFast) { + function FakeConstructor() { + } + FakeConstructor.prototype = toBecomeFast; + var fakeInstance = new FakeConstructor; + function fakeAccess() { + return typeof fakeInstance.bar; + } + return fakeAccess(), fakeAccess(), toBecomeFast; + eval(toBecomeFast); + } + exports.toFastProperties = toFastProperties; +}); +var xt3 = R2((sn, St) => { + (function(t2, e) { + typeof define == "function" && define.amd ? define([], e) : typeof St == "object" && St.exports ? St.exports = e() : t2.regexpToAst = e(); + })(typeof self != "undefined" ? self : sn, function() { + function t2() { + } + t2.prototype.saveState = function() { + return { idx: this.idx, input: this.input, groupIdx: this.groupIdx }; + }, t2.prototype.restoreState = function(u2) { + this.idx = u2.idx, this.input = u2.input, this.groupIdx = u2.groupIdx; + }, t2.prototype.pattern = function(u2) { + this.idx = 0, this.input = u2, this.groupIdx = 0, this.consumeChar("/"); + var d = this.disjunction(); + this.consumeChar("/"); + for (var A2 = { type: "Flags", loc: { begin: this.idx, end: u2.length }, global: false, ignoreCase: false, multiLine: false, unicode: false, sticky: false };this.isRegExpFlag(); ) + switch (this.popChar()) { + case "g": + o(A2, "global"); + break; + case "i": + o(A2, "ignoreCase"); + break; + case "m": + o(A2, "multiLine"); + break; + case "u": + o(A2, "unicode"); + break; + case "y": + o(A2, "sticky"); + break; + } + if (this.idx !== this.input.length) + throw Error("Redundant input: " + this.input.substring(this.idx)); + return { type: "Pattern", flags: A2, value: d, loc: this.loc(0) }; + }, t2.prototype.disjunction = function() { + var u2 = [], d = this.idx; + for (u2.push(this.alternative());this.peekChar() === "|"; ) + this.consumeChar("|"), u2.push(this.alternative()); + return { type: "Disjunction", value: u2, loc: this.loc(d) }; + }, t2.prototype.alternative = function() { + for (var u2 = [], d = this.idx;this.isTerm(); ) + u2.push(this.term()); + return { type: "Alternative", value: u2, loc: this.loc(d) }; + }, t2.prototype.term = function() { + return this.isAssertion() ? this.assertion() : this.atom(); + }, t2.prototype.assertion = function() { + var u2 = this.idx; + switch (this.popChar()) { + case "^": + return { type: "StartAnchor", loc: this.loc(u2) }; + case "$": + return { type: "EndAnchor", loc: this.loc(u2) }; + case "\\": + switch (this.popChar()) { + case "b": + return { type: "WordBoundary", loc: this.loc(u2) }; + case "B": + return { type: "NonWordBoundary", loc: this.loc(u2) }; + } + throw Error("Invalid Assertion Escape"); + case "(": + this.consumeChar("?"); + var d; + switch (this.popChar()) { + case "=": + d = "Lookahead"; + break; + case "!": + d = "NegativeLookahead"; + break; + } + s(d); + var A2 = this.disjunction(); + return this.consumeChar(")"), { type: d, value: A2, loc: this.loc(u2) }; + } + c(); + }, t2.prototype.quantifier = function(u2) { + var d, A2 = this.idx; + switch (this.popChar()) { + case "*": + d = { atLeast: 0, atMost: Infinity }; + break; + case "+": + d = { atLeast: 1, atMost: Infinity }; + break; + case "?": + d = { atLeast: 0, atMost: 1 }; + break; + case "{": + var _2 = this.integerIncludingZero(); + switch (this.popChar()) { + case "}": + d = { atLeast: _2, atMost: _2 }; + break; + case ",": + var g3; + this.isDigit() ? (g3 = this.integerIncludingZero(), d = { atLeast: _2, atMost: g3 }) : d = { atLeast: _2, atMost: Infinity }, this.consumeChar("}"); + break; + } + if (u2 === true && d === undefined) + return; + s(d); + break; + } + if (!(u2 === true && d === undefined)) + return s(d), this.peekChar(0) === "?" ? (this.consumeChar("?"), d.greedy = false) : d.greedy = true, d.type = "Quantifier", d.loc = this.loc(A2), d; + }, t2.prototype.atom = function() { + var u2, d = this.idx; + switch (this.peekChar()) { + case ".": + u2 = this.dotAll(); + break; + case "\\": + u2 = this.atomEscape(); + break; + case "[": + u2 = this.characterClass(); + break; + case "(": + u2 = this.group(); + break; + } + return u2 === undefined && this.isPatternCharacter() && (u2 = this.patternCharacter()), s(u2), u2.loc = this.loc(d), this.isQuantifier() && (u2.quantifier = this.quantifier()), u2; + }, t2.prototype.dotAll = function() { + return this.consumeChar("."), { type: "Set", complement: true, value: [i(` +`), i("\r"), i("\u2028"), i("\u2029")] }; + }, t2.prototype.atomEscape = function() { + switch (this.consumeChar("\\"), this.peekChar()) { + case "1": + case "2": + case "3": + case "4": + case "5": + case "6": + case "7": + case "8": + case "9": + return this.decimalEscapeAtom(); + case "d": + case "D": + case "s": + case "S": + case "w": + case "W": + return this.characterClassEscape(); + case "f": + case "n": + case "r": + case "t": + case "v": + return this.controlEscapeAtom(); + case "c": + return this.controlLetterEscapeAtom(); + case "0": + return this.nulCharacterAtom(); + case "x": + return this.hexEscapeSequenceAtom(); + case "u": + return this.regExpUnicodeEscapeSequenceAtom(); + default: + return this.identityEscapeAtom(); + } + }, t2.prototype.decimalEscapeAtom = function() { + var u2 = this.positiveInteger(); + return { type: "GroupBackReference", value: u2 }; + }, t2.prototype.characterClassEscape = function() { + var u2, d = false; + switch (this.popChar()) { + case "d": + u2 = p; + break; + case "D": + u2 = p, d = true; + break; + case "s": + u2 = m; + break; + case "S": + u2 = m, d = true; + break; + case "w": + u2 = l2; + break; + case "W": + u2 = l2, d = true; + break; + } + return s(u2), { type: "Set", value: u2, complement: d }; + }, t2.prototype.controlEscapeAtom = function() { + var u2; + switch (this.popChar()) { + case "f": + u2 = i("\f"); + break; + case "n": + u2 = i(` +`); + break; + case "r": + u2 = i("\r"); + break; + case "t": + u2 = i("\t"); + break; + case "v": + u2 = i("\v"); + break; + } + return s(u2), { type: "Character", value: u2 }; + }, t2.prototype.controlLetterEscapeAtom = function() { + this.consumeChar("c"); + var u2 = this.popChar(); + if (/[a-zA-Z]/.test(u2) === false) + throw Error("Invalid "); + var d = u2.toUpperCase().charCodeAt(0) - 64; + return { type: "Character", value: d }; + }, t2.prototype.nulCharacterAtom = function() { + return this.consumeChar("0"), { type: "Character", value: i("\x00") }; + }, t2.prototype.hexEscapeSequenceAtom = function() { + return this.consumeChar("x"), this.parseHexDigits(2); + }, t2.prototype.regExpUnicodeEscapeSequenceAtom = function() { + return this.consumeChar("u"), this.parseHexDigits(4); + }, t2.prototype.identityEscapeAtom = function() { + var u2 = this.popChar(); + return { type: "Character", value: i(u2) }; + }, t2.prototype.classPatternCharacterAtom = function() { + switch (this.peekChar()) { + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + case "\\": + case "]": + throw Error("TBD"); + default: + var u2 = this.popChar(); + return { type: "Character", value: i(u2) }; + } + }, t2.prototype.characterClass = function() { + var u2 = [], d = false; + for (this.consumeChar("["), this.peekChar(0) === "^" && (this.consumeChar("^"), d = true);this.isClassAtom(); ) { + var A2 = this.classAtom(), _2 = A2.type === "Character"; + if (_2 && this.isRangeDash()) { + this.consumeChar("-"); + var g3 = this.classAtom(), y = g3.type === "Character"; + if (y) { + if (g3.value < A2.value) + throw Error("Range out of order in character class"); + u2.push({ from: A2.value, to: g3.value }); + } else + a(A2.value, u2), u2.push(i("-")), a(g3.value, u2); + } else + a(A2.value, u2); + } + return this.consumeChar("]"), { type: "Set", complement: d, value: u2 }; + }, t2.prototype.classAtom = function() { + switch (this.peekChar()) { + case "]": + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + throw Error("TBD"); + case "\\": + return this.classEscape(); + default: + return this.classPatternCharacterAtom(); + } + }, t2.prototype.classEscape = function() { + switch (this.consumeChar("\\"), this.peekChar()) { + case "b": + return this.consumeChar("b"), { type: "Character", value: i("\b") }; + case "d": + case "D": + case "s": + case "S": + case "w": + case "W": + return this.characterClassEscape(); + case "f": + case "n": + case "r": + case "t": + case "v": + return this.controlEscapeAtom(); + case "c": + return this.controlLetterEscapeAtom(); + case "0": + return this.nulCharacterAtom(); + case "x": + return this.hexEscapeSequenceAtom(); + case "u": + return this.regExpUnicodeEscapeSequenceAtom(); + default: + return this.identityEscapeAtom(); + } + }, t2.prototype.group = function() { + var u2 = true; + switch (this.consumeChar("("), this.peekChar(0)) { + case "?": + this.consumeChar("?"), this.consumeChar(":"), u2 = false; + break; + default: + this.groupIdx++; + break; + } + var d = this.disjunction(); + this.consumeChar(")"); + var A2 = { type: "Group", capturing: u2, value: d }; + return u2 && (A2.idx = this.groupIdx), A2; + }, t2.prototype.positiveInteger = function() { + var u2 = this.popChar(); + if (n2.test(u2) === false) + throw Error("Expecting a positive integer"); + for (;r.test(this.peekChar(0)); ) + u2 += this.popChar(); + return parseInt(u2, 10); + }, t2.prototype.integerIncludingZero = function() { + var u2 = this.popChar(); + if (r.test(u2) === false) + throw Error("Expecting an integer"); + for (;r.test(this.peekChar(0)); ) + u2 += this.popChar(); + return parseInt(u2, 10); + }, t2.prototype.patternCharacter = function() { + var u2 = this.popChar(); + switch (u2) { + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + case "^": + case "$": + case "\\": + case ".": + case "*": + case "+": + case "?": + case "(": + case ")": + case "[": + case "|": + throw Error("TBD"); + default: + return { type: "Character", value: i(u2) }; + } + }, t2.prototype.isRegExpFlag = function() { + switch (this.peekChar(0)) { + case "g": + case "i": + case "m": + case "u": + case "y": + return true; + default: + return false; + } + }, t2.prototype.isRangeDash = function() { + return this.peekChar() === "-" && this.isClassAtom(1); + }, t2.prototype.isDigit = function() { + return r.test(this.peekChar(0)); + }, t2.prototype.isClassAtom = function(u2) { + switch (u2 === undefined && (u2 = 0), this.peekChar(u2)) { + case "]": + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + return false; + default: + return true; + } + }, t2.prototype.isTerm = function() { + return this.isAtom() || this.isAssertion(); + }, t2.prototype.isAtom = function() { + if (this.isPatternCharacter()) + return true; + switch (this.peekChar(0)) { + case ".": + case "\\": + case "[": + case "(": + return true; + default: + return false; + } + }, t2.prototype.isAssertion = function() { + switch (this.peekChar(0)) { + case "^": + case "$": + return true; + case "\\": + switch (this.peekChar(1)) { + case "b": + case "B": + return true; + default: + return false; + } + case "(": + return this.peekChar(1) === "?" && (this.peekChar(2) === "=" || this.peekChar(2) === "!"); + default: + return false; + } + }, t2.prototype.isQuantifier = function() { + var u2 = this.saveState(); + try { + return this.quantifier(true) !== undefined; + } catch (d) { + return false; + } finally { + this.restoreState(u2); + } + }, t2.prototype.isPatternCharacter = function() { + switch (this.peekChar()) { + case "^": + case "$": + case "\\": + case ".": + case "*": + case "+": + case "?": + case "(": + case ")": + case "[": + case "|": + case "/": + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + return false; + default: + return true; + } + }, t2.prototype.parseHexDigits = function(u2) { + for (var d = "", A2 = 0;A2 < u2; A2++) { + var _2 = this.popChar(); + if (e.test(_2) === false) + throw Error("Expecting a HexDecimal digits"); + d += _2; + } + var g3 = parseInt(d, 16); + return { type: "Character", value: g3 }; + }, t2.prototype.peekChar = function(u2) { + return u2 === undefined && (u2 = 0), this.input[this.idx + u2]; + }, t2.prototype.popChar = function() { + var u2 = this.peekChar(0); + return this.consumeChar(), u2; + }, t2.prototype.consumeChar = function(u2) { + if (u2 !== undefined && this.input[this.idx] !== u2) + throw Error("Expected: '" + u2 + "' but found: '" + this.input[this.idx] + "' at offset: " + this.idx); + if (this.idx >= this.input.length) + throw Error("Unexpected end of input"); + this.idx++; + }, t2.prototype.loc = function(u2) { + return { begin: u2, end: this.idx }; + }; + var e = /[0-9a-fA-F]/, r = /[0-9]/, n2 = /[1-9]/; + function i(u2) { + return u2.charCodeAt(0); + } + function a(u2, d) { + u2.length !== undefined ? u2.forEach(function(A2) { + d.push(A2); + }) : d.push(u2); + } + function o(u2, d) { + if (u2[d] === true) + throw "duplicate flag " + d; + u2[d] = true; + } + function s(u2) { + if (u2 === undefined) + throw Error("Internal Error - Should never get here!"); + } + function c() { + throw Error("Internal Error - Should never get here!"); + } + var f, p = []; + for (f = i("0");f <= i("9"); f++) + p.push(f); + var l2 = [i("_")].concat(p); + for (f = i("a");f <= i("z"); f++) + l2.push(f); + for (f = i("A");f <= i("Z"); f++) + l2.push(f); + var m = [i(" "), i("\f"), i(` +`), i("\r"), i("\t"), i("\v"), i("\t"), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i("\u2028"), i("\u2029"), i(" "), i(" "), i(" "), i("\uFEFF")]; + function v() { + } + return v.prototype.visitChildren = function(u2) { + for (var d in u2) { + var A2 = u2[d]; + u2.hasOwnProperty(d) && (A2.type !== undefined ? this.visit(A2) : Array.isArray(A2) && A2.forEach(function(_2) { + this.visit(_2); + }, this)); + } + }, v.prototype.visit = function(u2) { + switch (u2.type) { + case "Pattern": + this.visitPattern(u2); + break; + case "Flags": + this.visitFlags(u2); + break; + case "Disjunction": + this.visitDisjunction(u2); + break; + case "Alternative": + this.visitAlternative(u2); + break; + case "StartAnchor": + this.visitStartAnchor(u2); + break; + case "EndAnchor": + this.visitEndAnchor(u2); + break; + case "WordBoundary": + this.visitWordBoundary(u2); + break; + case "NonWordBoundary": + this.visitNonWordBoundary(u2); + break; + case "Lookahead": + this.visitLookahead(u2); + break; + case "NegativeLookahead": + this.visitNegativeLookahead(u2); + break; + case "Character": + this.visitCharacter(u2); + break; + case "Set": + this.visitSet(u2); + break; + case "Group": + this.visitGroup(u2); + break; + case "GroupBackReference": + this.visitGroupBackReference(u2); + break; + case "Quantifier": + this.visitQuantifier(u2); + break; + } + this.visitChildren(u2); + }, v.prototype.visitPattern = function(u2) { + }, v.prototype.visitFlags = function(u2) { + }, v.prototype.visitDisjunction = function(u2) { + }, v.prototype.visitAlternative = function(u2) { + }, v.prototype.visitStartAnchor = function(u2) { + }, v.prototype.visitEndAnchor = function(u2) { + }, v.prototype.visitWordBoundary = function(u2) { + }, v.prototype.visitNonWordBoundary = function(u2) { + }, v.prototype.visitLookahead = function(u2) { + }, v.prototype.visitNegativeLookahead = function(u2) { + }, v.prototype.visitCharacter = function(u2) { + }, v.prototype.visitSet = function(u2) { + }, v.prototype.visitGroup = function(u2) { + }, v.prototype.visitGroupBackReference = function(u2) { + }, v.prototype.visitQuantifier = function(u2) { + }, { RegExpParser: t2, BaseRegExpVisitor: v, VERSION: "0.5.0" }; + }); +}); +var Lt = R2((He2) => { + Object.defineProperty(He2, "__esModule", { value: true }); + He2.clearRegExpParserCache = He2.getRegExpAst = undefined; + var Ga = xt3(), Ct2 = {}, Wa = new Ga.RegExpParser; + function Ba(t2) { + var e = t2.toString(); + if (Ct2.hasOwnProperty(e)) + return Ct2[e]; + var r = Wa.pattern(e); + return Ct2[e] = r, r; + } + He2.getRegExpAst = Ba; + function qa() { + Ct2 = {}; + } + He2.clearRegExpParserCache = qa; +}); +var pn = R2((re) => { + var ja = re && re.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(re, "__esModule", { value: true }); + re.canMatchCharCode = re.firstCharOptimizedIndices = re.getOptimizedStartCodesIndices = re.failedOptimizationPrefixMsg = undefined; + var un = xt3(), pe2 = k2(), cn = Lt(), Ce = Tr(), ln = "Complement Sets are not supported for first char optimization"; + re.failedOptimizationPrefixMsg = `Unable to use "first char" lexer optimizations: +`; + function Va(t2, e) { + e === undefined && (e = false); + try { + var r = cn.getRegExpAst(t2), n2 = Mt(r.value, {}, r.flags.ignoreCase); + return n2; + } catch (a) { + if (a.message === ln) + e && pe2.PRINT_WARNING("" + re.failedOptimizationPrefixMsg + ("\tUnable to optimize: < " + t2.toString() + ` > +`) + ` Complement Sets cannot be automatically optimized. + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`); + else { + var i = ""; + e && (i = ` + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`), pe2.PRINT_ERROR(re.failedOptimizationPrefixMsg + ` +` + ("\tFailed parsing: < " + t2.toString() + ` > +`) + ("\tUsing the regexp-to-ast library version: " + un.VERSION + ` +`) + "\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues" + i); + } + } + return []; + } + re.getOptimizedStartCodesIndices = Va; + function Mt(t2, e, r) { + switch (t2.type) { + case "Disjunction": + for (var n2 = 0;n2 < t2.value.length; n2++) + Mt(t2.value[n2], e, r); + break; + case "Alternative": + for (var i = t2.value, n2 = 0;n2 < i.length; n2++) { + var a = i[n2]; + switch (a.type) { + case "EndAnchor": + case "GroupBackReference": + case "Lookahead": + case "NegativeLookahead": + case "StartAnchor": + case "WordBoundary": + case "NonWordBoundary": + continue; + } + var o = a; + switch (o.type) { + case "Character": + bt(o.value, e, r); + break; + case "Set": + if (o.complement === true) + throw Error(ln); + pe2.forEach(o.value, function(f) { + if (typeof f == "number") + bt(f, e, r); + else { + var p = f; + if (r === true) + for (var l2 = p.from;l2 <= p.to; l2++) + bt(l2, e, r); + else { + for (var l2 = p.from;l2 <= p.to && l2 < Ce.minOptimizationVal; l2++) + bt(l2, e, r); + if (p.to >= Ce.minOptimizationVal) + for (var m = p.from >= Ce.minOptimizationVal ? p.from : Ce.minOptimizationVal, v = p.to, u2 = Ce.charCodeToOptimizedIndex(m), d = Ce.charCodeToOptimizedIndex(v), A2 = u2;A2 <= d; A2++) + e[A2] = A2; + } + } + }); + break; + case "Group": + Mt(o.value, e, r); + break; + default: + throw Error("Non Exhaustive Match"); + } + var s = o.quantifier !== undefined && o.quantifier.atLeast === 0; + if (o.type === "Group" && yr(o) === false || o.type !== "Group" && s === false) + break; + } + break; + default: + throw Error("non exhaustive match!"); + } + return pe2.values(e); + } + re.firstCharOptimizedIndices = Mt; + function bt(t2, e, r) { + var n2 = Ce.charCodeToOptimizedIndex(t2); + e[n2] = n2, r === true && Ka(t2, e); + } + function Ka(t2, e) { + var r = String.fromCharCode(t2), n2 = r.toUpperCase(); + if (n2 !== r) { + var i = Ce.charCodeToOptimizedIndex(n2.charCodeAt(0)); + e[i] = i; + } else { + var a = r.toLowerCase(); + if (a !== r) { + var i = Ce.charCodeToOptimizedIndex(a.charCodeAt(0)); + e[i] = i; + } + } + } + function fn(t2, e) { + return pe2.find(t2.value, function(r) { + if (typeof r == "number") + return pe2.contains(e, r); + var n2 = r; + return pe2.find(e, function(i) { + return n2.from <= i && i <= n2.to; + }) !== undefined; + }); + } + function yr(t2) { + return t2.quantifier && t2.quantifier.atLeast === 0 ? true : t2.value ? pe2.isArray(t2.value) ? pe2.every(t2.value, yr) : yr(t2.value) : false; + } + var za = function(t2) { + ja(e, t2); + function e(r) { + var n2 = t2.call(this) || this; + return n2.targetCharCodes = r, n2.found = false, n2; + } + return e.prototype.visitChildren = function(r) { + if (this.found !== true) { + switch (r.type) { + case "Lookahead": + this.visitLookahead(r); + return; + case "NegativeLookahead": + this.visitNegativeLookahead(r); + return; + } + t2.prototype.visitChildren.call(this, r); + } + }, e.prototype.visitCharacter = function(r) { + pe2.contains(this.targetCharCodes, r.value) && (this.found = true); + }, e.prototype.visitSet = function(r) { + r.complement ? fn(r, this.targetCharCodes) === undefined && (this.found = true) : fn(r, this.targetCharCodes) !== undefined && (this.found = true); + }, e; + }(un.BaseRegExpVisitor); + function Ha(t2, e) { + if (e instanceof RegExp) { + var r = cn.getRegExpAst(e), n2 = new za(t2); + return n2.visit(r), n2.found; + } else + return pe2.find(e, function(i) { + return pe2.contains(t2, i.charCodeAt(0)); + }) !== undefined; + } + re.canMatchCharCode = Ha; +}); +var Tr = R2((T2) => { + var hn = T2 && T2.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(T2, "__esModule", { value: true }); + T2.charCodeToOptimizedIndex = T2.minOptimizationVal = T2.buildLineBreakIssueMessage = T2.LineTerminatorOptimizedTester = T2.isShortPattern = T2.isCustomPattern = T2.cloneEmptyGroups = T2.performWarningRuntimeChecks = T2.performRuntimeChecks = T2.addStickyFlag = T2.addStartOfInput = T2.findUnreachablePatterns = T2.findModesThatDoNotExist = T2.findInvalidGroupType = T2.findDuplicatePatterns = T2.findUnsupportedFlags = T2.findStartOfInputAnchor = T2.findEmptyMatchRegExps = T2.findEndOfInputAnchor = T2.findInvalidPatterns = T2.findMissingPatterns = T2.validatePatterns = T2.analyzeTokenTypes = T2.enableSticky = T2.disableSticky = T2.SUPPORT_STICKY = T2.MODES = T2.DEFAULT_MODE = undefined; + var dn = xt3(), F = ft(), h = k2(), Ye = pn(), vn = Lt(), Ae2 = "PATTERN"; + T2.DEFAULT_MODE = "defaultMode"; + T2.MODES = "modes"; + T2.SUPPORT_STICKY = typeof new RegExp("(?:)").sticky == "boolean"; + function Ya() { + T2.SUPPORT_STICKY = false; + } + T2.disableSticky = Ya; + function Xa() { + T2.SUPPORT_STICKY = true; + } + T2.enableSticky = Xa; + function Za(t2, e) { + e = h.defaults(e, { useSticky: T2.SUPPORT_STICKY, debug: false, safeMode: false, positionTracking: "full", lineTerminatorCharacters: ["\r", ` +`], tracer: function(g3, y) { + return y(); + } }); + var r = e.tracer; + r("initCharCodeToOptimizedIndexMap", function() { + $a(); + }); + var n2; + r("Reject Lexer.NA", function() { + n2 = h.reject(t2, function(g3) { + return g3[Ae2] === F.Lexer.NA; + }); + }); + var i = false, a; + r("Transform Patterns", function() { + i = false, a = h.map(n2, function(g3) { + var y = g3[Ae2]; + if (h.isRegExp(y)) { + var b = y.source; + return b.length === 1 && b !== "^" && b !== "$" && b !== "." && !y.ignoreCase ? b : b.length === 2 && b[0] === "\\" && !h.contains(["d", "D", "s", "S", "t", "r", "n", "t", "0", "c", "b", "B", "f", "v", "w", "W"], b[1]) ? b[1] : e.useSticky ? gr(y) : _r(y); + } else { + if (h.isFunction(y)) + return i = true, { exec: y }; + if (h.has(y, "exec")) + return i = true, y; + if (typeof y == "string") { + if (y.length === 1) + return y; + var L = y.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"), se2 = new RegExp(L); + return e.useSticky ? gr(se2) : _r(se2); + } else + throw Error("non exhaustive match"); + } + }); + }); + var o, s, c, f, p; + r("misc mapping", function() { + o = h.map(n2, function(g3) { + return g3.tokenTypeIdx; + }), s = h.map(n2, function(g3) { + var y = g3.GROUP; + if (y !== F.Lexer.SKIPPED) { + if (h.isString(y)) + return y; + if (h.isUndefined(y)) + return false; + throw Error("non exhaustive match"); + } + }), c = h.map(n2, function(g3) { + var y = g3.LONGER_ALT; + if (y) { + var b = h.indexOf(n2, y); + return b; + } + }), f = h.map(n2, function(g3) { + return g3.PUSH_MODE; + }), p = h.map(n2, function(g3) { + return h.has(g3, "POP_MODE"); + }); + }); + var l2; + r("Line Terminator Handling", function() { + var g3 = Tn(e.lineTerminatorCharacters); + l2 = h.map(n2, function(y) { + return false; + }), e.positionTracking !== "onlyOffset" && (l2 = h.map(n2, function(y) { + if (h.has(y, "LINE_BREAKS")) + return y.LINE_BREAKS; + if (En(y, g3) === false) + return Ye.canMatchCharCode(g3, y.PATTERN); + })); + }); + var m, v, u2, d; + r("Misc Mapping #2", function() { + m = h.map(n2, Ar), v = h.map(a, mn), u2 = h.reduce(n2, function(g3, y) { + var b = y.GROUP; + return h.isString(b) && b !== F.Lexer.SKIPPED && (g3[b] = []), g3; + }, {}), d = h.map(a, function(g3, y) { + return { pattern: a[y], longerAlt: c[y], canLineTerminator: l2[y], isCustom: m[y], short: v[y], group: s[y], push: f[y], pop: p[y], tokenTypeIdx: o[y], tokenType: n2[y] }; + }); + }); + var A2 = true, _2 = []; + return e.safeMode || r("First Char Optimization", function() { + _2 = h.reduce(n2, function(g3, y, b) { + if (typeof y.PATTERN == "string") { + var L = y.PATTERN.charCodeAt(0), se2 = Or(L); + Rr(g3, se2, d[b]); + } else if (h.isArray(y.START_CHARS_HINT)) { + var fe; + h.forEach(y.START_CHARS_HINT, function(ue3) { + var Q2 = typeof ue3 == "string" ? ue3.charCodeAt(0) : ue3, te3 = Or(Q2); + fe !== te3 && (fe = te3, Rr(g3, te3, d[b])); + }); + } else if (h.isRegExp(y.PATTERN)) + if (y.PATTERN.unicode) + A2 = false, e.ensureOptimizations && h.PRINT_ERROR("" + Ye.failedOptimizationPrefixMsg + ("\tUnable to analyze < " + y.PATTERN.toString() + ` > pattern. +`) + ` The regexp unicode flag is not currently supported by the regexp-to-ast library. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`); + else { + var Z2 = Ye.getOptimizedStartCodesIndices(y.PATTERN, e.ensureOptimizations); + h.isEmpty(Z2) && (A2 = false), h.forEach(Z2, function(ue3) { + Rr(g3, ue3, d[b]); + }); + } + else + e.ensureOptimizations && h.PRINT_ERROR("" + Ye.failedOptimizationPrefixMsg + ("\tTokenType: <" + y.name + `> is using a custom token pattern without providing parameter. +`) + ` This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`), A2 = false; + return g3; + }, []); + }), r("ArrayPacking", function() { + _2 = h.packArray(_2); + }), { emptyGroups: u2, patternIdxToConfig: d, charCodeToPatternIdxToConfig: _2, hasCustom: i, canBeOptimized: A2 }; + } + T2.analyzeTokenTypes = Za; + function Ja(t2, e) { + var r = [], n2 = yn(t2); + r = r.concat(n2.errors); + var i = _n(n2.valid), a = i.valid; + return r = r.concat(i.errors), r = r.concat(Qa(a)), r = r.concat(gn(a)), r = r.concat(An(a, e)), r = r.concat(Rn(a)), r; + } + T2.validatePatterns = Ja; + function Qa(t2) { + var e = [], r = h.filter(t2, function(n2) { + return h.isRegExp(n2[Ae2]); + }); + return e = e.concat(On(r)), e = e.concat(In2(r)), e = e.concat(kn(r)), e = e.concat(Pn(r)), e = e.concat(Nn(r)), e; + } + function yn(t2) { + var e = h.filter(t2, function(i) { + return !h.has(i, Ae2); + }), r = h.map(e, function(i) { + return { message: "Token Type: ->" + i.name + "<- missing static 'PATTERN' property", type: F.LexerDefinitionErrorType.MISSING_PATTERN, tokenTypes: [i] }; + }), n2 = h.difference(t2, e); + return { errors: r, valid: n2 }; + } + T2.findMissingPatterns = yn; + function _n(t2) { + var e = h.filter(t2, function(i) { + var a = i[Ae2]; + return !h.isRegExp(a) && !h.isFunction(a) && !h.has(a, "exec") && !h.isString(a); + }), r = h.map(e, function(i) { + return { message: "Token Type: ->" + i.name + "<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.", type: F.LexerDefinitionErrorType.INVALID_PATTERN, tokenTypes: [i] }; + }), n2 = h.difference(t2, e); + return { errors: r, valid: n2 }; + } + T2.findInvalidPatterns = _n; + var eo = /[^\\][\$]/; + function On(t2) { + var e = function(i) { + hn(a, i); + function a() { + var o = i !== null && i.apply(this, arguments) || this; + return o.found = false, o; + } + return a.prototype.visitEndAnchor = function(o) { + this.found = true; + }, a; + }(dn.BaseRegExpVisitor), r = h.filter(t2, function(i) { + var a = i[Ae2]; + try { + var o = vn.getRegExpAst(a), s = new e; + return s.visit(o), s.found; + } catch (c) { + return eo.test(a.source); + } + }), n2 = h.map(r, function(i) { + return { message: `Unexpected RegExp Anchor Error: + Token Type: ->` + i.name + `<- static 'PATTERN' cannot contain end of input anchor '$' + See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`, type: F.LexerDefinitionErrorType.EOI_ANCHOR_FOUND, tokenTypes: [i] }; + }); + return n2; + } + T2.findEndOfInputAnchor = On; + function Nn(t2) { + var e = h.filter(t2, function(n2) { + var i = n2[Ae2]; + return i.test(""); + }), r = h.map(e, function(n2) { + return { message: "Token Type: ->" + n2.name + "<- static 'PATTERN' must not match an empty string", type: F.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN, tokenTypes: [n2] }; + }); + return r; + } + T2.findEmptyMatchRegExps = Nn; + var to = /[^\\[][\^]|^\^/; + function In2(t2) { + var e = function(i) { + hn(a, i); + function a() { + var o = i !== null && i.apply(this, arguments) || this; + return o.found = false, o; + } + return a.prototype.visitStartAnchor = function(o) { + this.found = true; + }, a; + }(dn.BaseRegExpVisitor), r = h.filter(t2, function(i) { + var a = i[Ae2]; + try { + var o = vn.getRegExpAst(a), s = new e; + return s.visit(o), s.found; + } catch (c) { + return to.test(a.source); + } + }), n2 = h.map(r, function(i) { + return { message: `Unexpected RegExp Anchor Error: + Token Type: ->` + i.name + `<- static 'PATTERN' cannot contain start of input anchor '^' + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`, type: F.LexerDefinitionErrorType.SOI_ANCHOR_FOUND, tokenTypes: [i] }; + }); + return n2; + } + T2.findStartOfInputAnchor = In2; + function kn(t2) { + var e = h.filter(t2, function(n2) { + var i = n2[Ae2]; + return i instanceof RegExp && (i.multiline || i.global); + }), r = h.map(e, function(n2) { + return { message: "Token Type: ->" + n2.name + "<- static 'PATTERN' may NOT contain global('g') or multiline('m')", type: F.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND, tokenTypes: [n2] }; + }); + return r; + } + T2.findUnsupportedFlags = kn; + function Pn(t2) { + var e = [], r = h.map(t2, function(a) { + return h.reduce(t2, function(o, s) { + return a.PATTERN.source === s.PATTERN.source && !h.contains(e, s) && s.PATTERN !== F.Lexer.NA && (e.push(s), o.push(s)), o; + }, []); + }); + r = h.compact(r); + var n2 = h.filter(r, function(a) { + return a.length > 1; + }), i = h.map(n2, function(a) { + var o = h.map(a, function(c) { + return c.name; + }), s = h.first(a).PATTERN; + return { message: "The same RegExp pattern ->" + s + "<-" + ("has been used in all of the following Token Types: " + o.join(", ") + " <-"), type: F.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND, tokenTypes: a }; + }); + return i; + } + T2.findDuplicatePatterns = Pn; + function gn(t2) { + var e = h.filter(t2, function(n2) { + if (!h.has(n2, "GROUP")) + return false; + var i = n2.GROUP; + return i !== F.Lexer.SKIPPED && i !== F.Lexer.NA && !h.isString(i); + }), r = h.map(e, function(n2) { + return { message: "Token Type: ->" + n2.name + "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String", type: F.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND, tokenTypes: [n2] }; + }); + return r; + } + T2.findInvalidGroupType = gn; + function An(t2, e) { + var r = h.filter(t2, function(i) { + return i.PUSH_MODE !== undefined && !h.contains(e, i.PUSH_MODE); + }), n2 = h.map(r, function(i) { + var a = "Token Type: ->" + i.name + "<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->" + i.PUSH_MODE + "<-which does not exist"; + return { message: a, type: F.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST, tokenTypes: [i] }; + }); + return n2; + } + T2.findModesThatDoNotExist = An; + function Rn(t2) { + var e = [], r = h.reduce(t2, function(n2, i, a) { + var o = i.PATTERN; + return o === F.Lexer.NA || (h.isString(o) ? n2.push({ str: o, idx: a, tokenType: i }) : h.isRegExp(o) && no(o) && n2.push({ str: o.source, idx: a, tokenType: i })), n2; + }, []); + return h.forEach(t2, function(n2, i) { + h.forEach(r, function(a) { + var { str: o, idx: s, tokenType: c } = a; + if (i < s && ro(o, n2.PATTERN)) { + var f = "Token: ->" + c.name + `<- can never be matched. +` + ("Because it appears AFTER the Token Type ->" + n2.name + "<-") + `in the lexer's definition. +See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`; + e.push({ message: f, type: F.LexerDefinitionErrorType.UNREACHABLE_PATTERN, tokenTypes: [n2, c] }); + } + }); + }), e; + } + T2.findUnreachablePatterns = Rn; + function ro(t2, e) { + if (h.isRegExp(e)) { + var r = e.exec(t2); + return r !== null && r.index === 0; + } else { + if (h.isFunction(e)) + return e(t2, 0, [], {}); + if (h.has(e, "exec")) + return e.exec(t2, 0, [], {}); + if (typeof e == "string") + return e === t2; + throw Error("non exhaustive match"); + } + } + function no(t2) { + var e = [".", "\\", "[", "]", "|", "^", "$", "(", ")", "?", "*", "+", "{"]; + return h.find(e, function(r) { + return t2.source.indexOf(r) !== -1; + }) === undefined; + } + function _r(t2) { + var e = t2.ignoreCase ? "i" : ""; + return new RegExp("^(?:" + t2.source + ")", e); + } + T2.addStartOfInput = _r; + function gr(t2) { + var e = t2.ignoreCase ? "iy" : "y"; + return new RegExp("" + t2.source, e); + } + T2.addStickyFlag = gr; + function io(t2, e, r) { + var n2 = []; + return h.has(t2, T2.DEFAULT_MODE) || n2.push({ message: "A MultiMode Lexer cannot be initialized without a <" + T2.DEFAULT_MODE + `> property in its definition +`, type: F.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE }), h.has(t2, T2.MODES) || n2.push({ message: "A MultiMode Lexer cannot be initialized without a <" + T2.MODES + `> property in its definition +`, type: F.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY }), h.has(t2, T2.MODES) && h.has(t2, T2.DEFAULT_MODE) && !h.has(t2.modes, t2.defaultMode) && n2.push({ message: "A MultiMode Lexer cannot be initialized with a " + T2.DEFAULT_MODE + ": <" + t2.defaultMode + `>which does not exist +`, type: F.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST }), h.has(t2, T2.MODES) && h.forEach(t2.modes, function(i, a) { + h.forEach(i, function(o, s) { + h.isUndefined(o) && n2.push({ message: "A Lexer cannot be initialized using an undefined Token Type. Mode:" + ("<" + a + "> at index: <" + s + `> +`), type: F.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED }); + }); + }), n2; + } + T2.performRuntimeChecks = io; + function ao(t2, e, r) { + var n2 = [], i = false, a = h.compact(h.flatten(h.mapValues(t2.modes, function(c) { + return c; + }))), o = h.reject(a, function(c) { + return c[Ae2] === F.Lexer.NA; + }), s = Tn(r); + return e && h.forEach(o, function(c) { + var f = En(c, s); + if (f !== false) { + var p = Sn2(c, f), l2 = { message: p, type: f.issue, tokenType: c }; + n2.push(l2); + } else + h.has(c, "LINE_BREAKS") ? c.LINE_BREAKS === true && (i = true) : Ye.canMatchCharCode(s, c.PATTERN) && (i = true); + }), e && !i && n2.push({ message: `Warning: No LINE_BREAKS Found. + This Lexer has been defined to track line and column information, + But none of the Token Types can be identified as matching a line terminator. + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS + for details.`, type: F.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS }), n2; + } + T2.performWarningRuntimeChecks = ao; + function oo(t2) { + var e = {}, r = h.keys(t2); + return h.forEach(r, function(n2) { + var i = t2[n2]; + if (h.isArray(i)) + e[n2] = []; + else + throw Error("non exhaustive match"); + }), e; + } + T2.cloneEmptyGroups = oo; + function Ar(t2) { + var e = t2.PATTERN; + if (h.isRegExp(e)) + return false; + if (h.isFunction(e)) + return true; + if (h.has(e, "exec")) + return true; + if (h.isString(e)) + return false; + throw Error("non exhaustive match"); + } + T2.isCustomPattern = Ar; + function mn(t2) { + return h.isString(t2) && t2.length === 1 ? t2.charCodeAt(0) : false; + } + T2.isShortPattern = mn; + T2.LineTerminatorOptimizedTester = { test: function(t2) { + for (var e = t2.length, r = this.lastIndex;r < e; r++) { + var n2 = t2.charCodeAt(r); + if (n2 === 10) + return this.lastIndex = r + 1, true; + if (n2 === 13) + return t2.charCodeAt(r + 1) === 10 ? this.lastIndex = r + 2 : this.lastIndex = r + 1, true; + } + return false; + }, lastIndex: 0 }; + function En(t2, e) { + if (h.has(t2, "LINE_BREAKS")) + return false; + if (h.isRegExp(t2.PATTERN)) { + try { + Ye.canMatchCharCode(e, t2.PATTERN); + } catch (r) { + return { issue: F.LexerDefinitionErrorType.IDENTIFY_TERMINATOR, errMsg: r.message }; + } + return false; + } else { + if (h.isString(t2.PATTERN)) + return false; + if (Ar(t2)) + return { issue: F.LexerDefinitionErrorType.CUSTOM_LINE_BREAK }; + throw Error("non exhaustive match"); + } + } + function Sn2(t2, e) { + if (e.issue === F.LexerDefinitionErrorType.IDENTIFY_TERMINATOR) + return `Warning: unable to identify line terminator usage in pattern. +` + ("\tThe problem is in the <" + t2.name + `> Token Type +`) + ("\t Root cause: " + e.errMsg + `. +`) + "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR"; + if (e.issue === F.LexerDefinitionErrorType.CUSTOM_LINE_BREAK) + return `Warning: A Custom Token Pattern should specify the option. +` + ("\tThe problem is in the <" + t2.name + `> Token Type +`) + "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK"; + throw Error("non exhaustive match"); + } + T2.buildLineBreakIssueMessage = Sn2; + function Tn(t2) { + var e = h.map(t2, function(r) { + return h.isString(r) && r.length > 0 ? r.charCodeAt(0) : r; + }); + return e; + } + function Rr(t2, e, r) { + t2[e] === undefined ? t2[e] = [r] : t2[e].push(r); + } + T2.minOptimizationVal = 256; + var Ft2 = []; + function Or(t2) { + return t2 < T2.minOptimizationVal ? t2 : Ft2[t2]; + } + T2.charCodeToOptimizedIndex = Or; + function $a() { + if (h.isEmpty(Ft2)) { + Ft2 = new Array(65536); + for (var t2 = 0;t2 < 65536; t2++) + Ft2[t2] = t2 > 255 ? 255 + ~~(t2 / 255) : t2; + } + } +}); +var Xe = R2((N) => { + Object.defineProperty(N, "__esModule", { value: true }); + N.isTokenType = N.hasExtendingTokensTypesMapProperty = N.hasExtendingTokensTypesProperty = N.hasCategoriesProperty = N.hasShortKeyProperty = N.singleAssignCategoriesToksMap = N.assignCategoriesMapProp = N.assignCategoriesTokensProp = N.assignTokenDefaultProps = N.expandCategories = N.augmentTokenTypes = N.tokenIdxToClass = N.tokenShortNameIdx = N.tokenStructuredMatcherNoCategories = N.tokenStructuredMatcher = undefined; + var V2 = k2(); + function so(t2, e) { + var r = t2.tokenTypeIdx; + return r === e.tokenTypeIdx ? true : e.isParent === true && e.categoryMatchesMap[r] === true; + } + N.tokenStructuredMatcher = so; + function uo(t2, e) { + return t2.tokenTypeIdx === e.tokenTypeIdx; + } + N.tokenStructuredMatcherNoCategories = uo; + N.tokenShortNameIdx = 1; + N.tokenIdxToClass = {}; + function co(t2) { + var e = xn(t2); + Cn(e), Mn(e), Ln(e), V2.forEach(e, function(r) { + r.isParent = r.categoryMatches.length > 0; + }); + } + N.augmentTokenTypes = co; + function xn(t2) { + for (var e = V2.cloneArr(t2), r = t2, n2 = true;n2; ) { + r = V2.compact(V2.flatten(V2.map(r, function(a) { + return a.CATEGORIES; + }))); + var i = V2.difference(r, e); + e = e.concat(i), V2.isEmpty(i) ? n2 = false : r = i; + } + return e; + } + N.expandCategories = xn; + function Cn(t2) { + V2.forEach(t2, function(e) { + bn(e) || (N.tokenIdxToClass[N.tokenShortNameIdx] = e, e.tokenTypeIdx = N.tokenShortNameIdx++), Nr(e) && !V2.isArray(e.CATEGORIES) && (e.CATEGORIES = [e.CATEGORIES]), Nr(e) || (e.CATEGORIES = []), Fn(e) || (e.categoryMatches = []), wn(e) || (e.categoryMatchesMap = {}); + }); + } + N.assignTokenDefaultProps = Cn; + function Ln(t2) { + V2.forEach(t2, function(e) { + e.categoryMatches = [], V2.forEach(e.categoryMatchesMap, function(r, n2) { + e.categoryMatches.push(N.tokenIdxToClass[n2].tokenTypeIdx); + }); + }); + } + N.assignCategoriesTokensProp = Ln; + function Mn(t2) { + V2.forEach(t2, function(e) { + Ir([], e); + }); + } + N.assignCategoriesMapProp = Mn; + function Ir(t2, e) { + V2.forEach(t2, function(r) { + e.categoryMatchesMap[r.tokenTypeIdx] = true; + }), V2.forEach(e.CATEGORIES, function(r) { + var n2 = t2.concat(e); + V2.contains(n2, r) || Ir(n2, r); + }); + } + N.singleAssignCategoriesToksMap = Ir; + function bn(t2) { + return V2.has(t2, "tokenTypeIdx"); + } + N.hasShortKeyProperty = bn; + function Nr(t2) { + return V2.has(t2, "CATEGORIES"); + } + N.hasCategoriesProperty = Nr; + function Fn(t2) { + return V2.has(t2, "categoryMatches"); + } + N.hasExtendingTokensTypesProperty = Fn; + function wn(t2) { + return V2.has(t2, "categoryMatchesMap"); + } + N.hasExtendingTokensTypesMapProperty = wn; + function lo(t2) { + return V2.has(t2, "tokenTypeIdx"); + } + N.isTokenType = lo; +}); +var kr = R2((wt2) => { + Object.defineProperty(wt2, "__esModule", { value: true }); + wt2.defaultLexerErrorProvider = undefined; + wt2.defaultLexerErrorProvider = { buildUnableToPopLexerModeMessage: function(t2) { + return "Unable to pop Lexer Mode after encountering Token ->" + t2.image + "<- The Mode Stack is empty"; + }, buildUnexpectedCharactersMessage: function(t2, e, r, n2, i) { + return "unexpected character: ->" + t2.charAt(e) + "<- at offset: " + e + "," + (" skipped " + r + " characters."); + } }; +}); +var ft = R2((qe) => { + Object.defineProperty(qe, "__esModule", { value: true }); + qe.Lexer = qe.LexerDefinitionErrorType = undefined; + var Ee = Tr(), w = k2(), fo = Xe(), po = kr(), ho = Lt(), vo; + (function(t2) { + t2[t2.MISSING_PATTERN = 0] = "MISSING_PATTERN", t2[t2.INVALID_PATTERN = 1] = "INVALID_PATTERN", t2[t2.EOI_ANCHOR_FOUND = 2] = "EOI_ANCHOR_FOUND", t2[t2.UNSUPPORTED_FLAGS_FOUND = 3] = "UNSUPPORTED_FLAGS_FOUND", t2[t2.DUPLICATE_PATTERNS_FOUND = 4] = "DUPLICATE_PATTERNS_FOUND", t2[t2.INVALID_GROUP_TYPE_FOUND = 5] = "INVALID_GROUP_TYPE_FOUND", t2[t2.PUSH_MODE_DOES_NOT_EXIST = 6] = "PUSH_MODE_DOES_NOT_EXIST", t2[t2.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE = 7] = "MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE", t2[t2.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY = 8] = "MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY", t2[t2.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST = 9] = "MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST", t2[t2.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED = 10] = "LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED", t2[t2.SOI_ANCHOR_FOUND = 11] = "SOI_ANCHOR_FOUND", t2[t2.EMPTY_MATCH_PATTERN = 12] = "EMPTY_MATCH_PATTERN", t2[t2.NO_LINE_BREAKS_FLAGS = 13] = "NO_LINE_BREAKS_FLAGS", t2[t2.UNREACHABLE_PATTERN = 14] = "UNREACHABLE_PATTERN", t2[t2.IDENTIFY_TERMINATOR = 15] = "IDENTIFY_TERMINATOR", t2[t2.CUSTOM_LINE_BREAK = 16] = "CUSTOM_LINE_BREAK"; + })(vo = qe.LexerDefinitionErrorType || (qe.LexerDefinitionErrorType = {})); + var pt = { deferDefinitionErrorsHandling: false, positionTracking: "full", lineTerminatorsPattern: /\n|\r\n?/g, lineTerminatorCharacters: [` +`, "\r"], ensureOptimizations: false, safeMode: false, errorMessageProvider: po.defaultLexerErrorProvider, traceInitPerf: false, skipValidations: false }; + Object.freeze(pt); + var mo = function() { + function t2(e, r) { + var n2 = this; + if (r === undefined && (r = pt), this.lexerDefinition = e, this.lexerDefinitionErrors = [], this.lexerDefinitionWarning = [], this.patternIdxToConfig = {}, this.charCodeToPatternIdxToConfig = {}, this.modes = [], this.emptyGroups = {}, this.config = undefined, this.trackStartLines = true, this.trackEndLines = true, this.hasCustom = false, this.canModeBeOptimized = {}, typeof r == "boolean") + throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. +a boolean 2nd argument is no longer supported`); + this.config = w.merge(pt, r); + var i = this.config.traceInitPerf; + i === true ? (this.traceInitMaxIdent = Infinity, this.traceInitPerf = true) : typeof i == "number" && (this.traceInitMaxIdent = i, this.traceInitPerf = true), this.traceInitIndent = -1, this.TRACE_INIT("Lexer Constructor", function() { + var a, o = true; + n2.TRACE_INIT("Lexer Config handling", function() { + if (n2.config.lineTerminatorsPattern === pt.lineTerminatorsPattern) + n2.config.lineTerminatorsPattern = Ee.LineTerminatorOptimizedTester; + else if (n2.config.lineTerminatorCharacters === pt.lineTerminatorCharacters) + throw Error(`Error: Missing property on the Lexer config. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`); + if (r.safeMode && r.ensureOptimizations) + throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.'); + n2.trackStartLines = /full|onlyStart/i.test(n2.config.positionTracking), n2.trackEndLines = /full/i.test(n2.config.positionTracking), w.isArray(e) ? (a = { modes: {} }, a.modes[Ee.DEFAULT_MODE] = w.cloneArr(e), a[Ee.DEFAULT_MODE] = Ee.DEFAULT_MODE) : (o = false, a = w.cloneObj(e)); + }), n2.config.skipValidations === false && (n2.TRACE_INIT("performRuntimeChecks", function() { + n2.lexerDefinitionErrors = n2.lexerDefinitionErrors.concat(Ee.performRuntimeChecks(a, n2.trackStartLines, n2.config.lineTerminatorCharacters)); + }), n2.TRACE_INIT("performWarningRuntimeChecks", function() { + n2.lexerDefinitionWarning = n2.lexerDefinitionWarning.concat(Ee.performWarningRuntimeChecks(a, n2.trackStartLines, n2.config.lineTerminatorCharacters)); + })), a.modes = a.modes ? a.modes : {}, w.forEach(a.modes, function(p, l2) { + a.modes[l2] = w.reject(p, function(m) { + return w.isUndefined(m); + }); + }); + var s = w.keys(a.modes); + if (w.forEach(a.modes, function(p, l2) { + n2.TRACE_INIT("Mode: <" + l2 + "> processing", function() { + if (n2.modes.push(l2), n2.config.skipValidations === false && n2.TRACE_INIT("validatePatterns", function() { + n2.lexerDefinitionErrors = n2.lexerDefinitionErrors.concat(Ee.validatePatterns(p, s)); + }), w.isEmpty(n2.lexerDefinitionErrors)) { + fo.augmentTokenTypes(p); + var m; + n2.TRACE_INIT("analyzeTokenTypes", function() { + m = Ee.analyzeTokenTypes(p, { lineTerminatorCharacters: n2.config.lineTerminatorCharacters, positionTracking: r.positionTracking, ensureOptimizations: r.ensureOptimizations, safeMode: r.safeMode, tracer: n2.TRACE_INIT.bind(n2) }); + }), n2.patternIdxToConfig[l2] = m.patternIdxToConfig, n2.charCodeToPatternIdxToConfig[l2] = m.charCodeToPatternIdxToConfig, n2.emptyGroups = w.merge(n2.emptyGroups, m.emptyGroups), n2.hasCustom = m.hasCustom || n2.hasCustom, n2.canModeBeOptimized[l2] = m.canBeOptimized; + } + }); + }), n2.defaultMode = a.defaultMode, !w.isEmpty(n2.lexerDefinitionErrors) && !n2.config.deferDefinitionErrorsHandling) { + var c = w.map(n2.lexerDefinitionErrors, function(p) { + return p.message; + }), f = c.join(`----------------------- +`); + throw new Error(`Errors detected in definition of Lexer: +` + f); + } + w.forEach(n2.lexerDefinitionWarning, function(p) { + w.PRINT_WARNING(p.message); + }), n2.TRACE_INIT("Choosing sub-methods implementations", function() { + if (Ee.SUPPORT_STICKY ? (n2.chopInput = w.IDENTITY, n2.match = n2.matchWithTest) : (n2.updateLastIndex = w.NOOP, n2.match = n2.matchWithExec), o && (n2.handleModes = w.NOOP), n2.trackStartLines === false && (n2.computeNewColumn = w.IDENTITY), n2.trackEndLines === false && (n2.updateTokenEndLineColumnLocation = w.NOOP), /full/i.test(n2.config.positionTracking)) + n2.createTokenInstance = n2.createFullToken; + else if (/onlyStart/i.test(n2.config.positionTracking)) + n2.createTokenInstance = n2.createStartOnlyToken; + else if (/onlyOffset/i.test(n2.config.positionTracking)) + n2.createTokenInstance = n2.createOffsetOnlyToken; + else + throw Error('Invalid config option: "' + n2.config.positionTracking + '"'); + n2.hasCustom ? (n2.addToken = n2.addTokenUsingPush, n2.handlePayload = n2.handlePayloadWithCustom) : (n2.addToken = n2.addTokenUsingMemberAccess, n2.handlePayload = n2.handlePayloadNoCustom); + }), n2.TRACE_INIT("Failed Optimization Warnings", function() { + var p = w.reduce(n2.canModeBeOptimized, function(l2, m, v) { + return m === false && l2.push(v), l2; + }, []); + if (r.ensureOptimizations && !w.isEmpty(p)) + throw Error("Lexer Modes: < " + p.join(", ") + ` > cannot be optimized. + Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. + Or inspect the console log for details on how to resolve these issues.`); + }), n2.TRACE_INIT("clearRegExpParserCache", function() { + ho.clearRegExpParserCache(); + }), n2.TRACE_INIT("toFastProperties", function() { + w.toFastProperties(n2); + }); + }); + } + return t2.prototype.tokenize = function(e, r) { + if (r === undefined && (r = this.defaultMode), !w.isEmpty(this.lexerDefinitionErrors)) { + var n2 = w.map(this.lexerDefinitionErrors, function(o) { + return o.message; + }), i = n2.join(`----------------------- +`); + throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: +` + i); + } + var a = this.tokenizeInternal(e, r); + return a; + }, t2.prototype.tokenizeInternal = function(e, r) { + var n2 = this, i, a, o, s, c, f, p, l2, m, v, u2, d, A2, _2, g3, y = e, b = y.length, L = 0, se2 = 0, fe = this.hasCustom ? 0 : Math.floor(e.length / 10), Z2 = new Array(fe), ue3 = [], Q2 = this.trackStartLines ? 1 : undefined, te3 = this.trackStartLines ? 1 : undefined, xe = Ee.cloneEmptyGroups(this.emptyGroups), it2 = this.trackStartLines, at = this.config.lineTerminatorsPattern, Ke2 = 0, we2 = [], ot = [], It = [], Qr2 = []; + Object.freeze(Qr2); + var st = undefined; + function Jr2() { + return we2; + } + function en(J2) { + var lt = Ee.charCodeToOptimizedIndex(J2), ze = ot[lt]; + return ze === undefined ? Qr2 : ze; + } + var wa = function(J2) { + if (It.length === 1 && J2.tokenType.PUSH_MODE === undefined) { + var lt = n2.config.errorMessageProvider.buildUnableToPopLexerModeMessage(J2); + ue3.push({ offset: J2.startOffset, line: J2.startLine !== undefined ? J2.startLine : undefined, column: J2.startColumn !== undefined ? J2.startColumn : undefined, length: J2.image.length, message: lt }); + } else { + It.pop(); + var ze = w.last(It); + we2 = n2.patternIdxToConfig[ze], ot = n2.charCodeToPatternIdxToConfig[ze], Ke2 = we2.length; + var Ua = n2.canModeBeOptimized[ze] && n2.config.safeMode === false; + ot && Ua ? st = en : st = Jr2; + } + }; + function tn2(J2) { + It.push(J2), ot = this.charCodeToPatternIdxToConfig[J2], we2 = this.patternIdxToConfig[J2], Ke2 = we2.length, Ke2 = we2.length; + var lt = this.canModeBeOptimized[J2] && this.config.safeMode === false; + ot && lt ? st = en : st = Jr2; + } + tn2.call(this, r); + for (var me;L < b; ) { + c = null; + var rn2 = y.charCodeAt(L), nn = st(rn2), Da = nn.length; + for (i = 0;i < Da; i++) { + me = nn[i]; + var De = me.pattern; + f = null; + var ut2 = me.short; + if (ut2 !== false ? rn2 === ut2 && (c = De) : me.isCustom === true ? (g3 = De.exec(y, L, Z2, xe), g3 !== null ? (c = g3[0], g3.payload !== undefined && (f = g3.payload)) : c = null) : (this.updateLastIndex(De, L), c = this.match(De, e, L)), c !== null) { + if (s = me.longerAlt, s !== undefined) { + var fr = we2[s], pr = fr.pattern; + p = null, fr.isCustom === true ? (g3 = pr.exec(y, L, Z2, xe), g3 !== null ? (o = g3[0], g3.payload !== undefined && (p = g3.payload)) : o = null) : (this.updateLastIndex(pr, L), o = this.match(pr, e, L)), o && o.length > c.length && (c = o, f = p, me = fr); + } + break; + } + } + if (c !== null) { + if (l2 = c.length, m = me.group, m !== undefined && (v = me.tokenTypeIdx, u2 = this.createTokenInstance(c, L, v, me.tokenType, Q2, te3, l2), this.handlePayload(u2, f), m === false ? se2 = this.addToken(Z2, se2, u2) : xe[m].push(u2)), e = this.chopInput(e, l2), L = L + l2, te3 = this.computeNewColumn(te3, l2), it2 === true && me.canLineTerminator === true) { + var kt = 0, hr = undefined, dr = undefined; + at.lastIndex = 0; + do + hr = at.test(c), hr === true && (dr = at.lastIndex - 1, kt++); + while (hr === true); + kt !== 0 && (Q2 = Q2 + kt, te3 = l2 - dr, this.updateTokenEndLineColumnLocation(u2, m, dr, kt, Q2, te3, l2)); + } + this.handleModes(me, wa, tn2, u2); + } else { + for (var vr = L, an = Q2, on = te3, ct2 = false;!ct2 && L < b; ) + for (A2 = y.charCodeAt(L), e = this.chopInput(e, 1), L++, a = 0;a < Ke2; a++) { + var mr = we2[a], De = mr.pattern, ut2 = mr.short; + if (ut2 !== false ? y.charCodeAt(L) === ut2 && (ct2 = true) : mr.isCustom === true ? ct2 = De.exec(y, L, Z2, xe) !== null : (this.updateLastIndex(De, L), ct2 = De.exec(e) !== null), ct2 === true) + break; + } + d = L - vr, _2 = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(y, vr, d, an, on), ue3.push({ offset: vr, line: an, column: on, length: d, message: _2 }); + } + } + return this.hasCustom || (Z2.length = se2), { tokens: Z2, groups: xe, errors: ue3 }; + }, t2.prototype.handleModes = function(e, r, n2, i) { + if (e.pop === true) { + var a = e.push; + r(i), a !== undefined && n2.call(this, a); + } else + e.push !== undefined && n2.call(this, e.push); + }, t2.prototype.chopInput = function(e, r) { + return e.substring(r); + }, t2.prototype.updateLastIndex = function(e, r) { + e.lastIndex = r; + }, t2.prototype.updateTokenEndLineColumnLocation = function(e, r, n2, i, a, o, s) { + var c, f; + r !== undefined && (c = n2 === s - 1, f = c ? -1 : 0, i === 1 && c === true || (e.endLine = a + f, e.endColumn = o - 1 + -f)); + }, t2.prototype.computeNewColumn = function(e, r) { + return e + r; + }, t2.prototype.createTokenInstance = function() { + for (var e = [], r = 0;r < arguments.length; r++) + e[r] = arguments[r]; + return null; + }, t2.prototype.createOffsetOnlyToken = function(e, r, n2, i) { + return { image: e, startOffset: r, tokenTypeIdx: n2, tokenType: i }; + }, t2.prototype.createStartOnlyToken = function(e, r, n2, i, a, o) { + return { image: e, startOffset: r, startLine: a, startColumn: o, tokenTypeIdx: n2, tokenType: i }; + }, t2.prototype.createFullToken = function(e, r, n2, i, a, o, s) { + return { image: e, startOffset: r, endOffset: r + s - 1, startLine: a, endLine: a, startColumn: o, endColumn: o + s - 1, tokenTypeIdx: n2, tokenType: i }; + }, t2.prototype.addToken = function(e, r, n2) { + return 666; + }, t2.prototype.addTokenUsingPush = function(e, r, n2) { + return e.push(n2), r; + }, t2.prototype.addTokenUsingMemberAccess = function(e, r, n2) { + return e[r] = n2, r++, r; + }, t2.prototype.handlePayload = function(e, r) { + }, t2.prototype.handlePayloadNoCustom = function(e, r) { + }, t2.prototype.handlePayloadWithCustom = function(e, r) { + r !== null && (e.payload = r); + }, t2.prototype.match = function(e, r, n2) { + return null; + }, t2.prototype.matchWithTest = function(e, r, n2) { + var i = e.test(r); + return i === true ? r.substring(n2, e.lastIndex) : null; + }, t2.prototype.matchWithExec = function(e, r) { + var n2 = e.exec(r); + return n2 !== null ? n2[0] : n2; + }, t2.prototype.TRACE_INIT = function(e, r) { + if (this.traceInitPerf === true) { + this.traceInitIndent++; + var n2 = new Array(this.traceInitIndent + 1).join("\t"); + this.traceInitIndent < this.traceInitMaxIdent && console.log(n2 + "--> <" + e + ">"); + var i = w.timer(r), a = i.time, o = i.value, s = a > 10 ? console.warn : console.log; + return this.traceInitIndent < this.traceInitMaxIdent && s(n2 + "<-- <" + e + "> time: " + a + "ms"), this.traceInitIndent--, o; + } else + return r(); + }, t2.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.", t2.NA = /NOT_APPLICABLE/, t2; + }(); + qe.Lexer = mo; +}); +var Ue = R2((H) => { + Object.defineProperty(H, "__esModule", { value: true }); + H.tokenMatcher = H.createTokenInstance = H.EOF = H.createToken = H.hasTokenLabel = H.tokenName = H.tokenLabel = undefined; + var Te = k2(), Eo = ft(), Pr = Xe(); + function To(t2) { + return Dn(t2) ? t2.LABEL : t2.name; + } + H.tokenLabel = To; + function yo(t2) { + return t2.name; + } + H.tokenName = yo; + function Dn(t2) { + return Te.isString(t2.LABEL) && t2.LABEL !== ""; + } + H.hasTokenLabel = Dn; + var _o = "parent", Un = "categories", Gn = "label", Wn = "group", Bn = "push_mode", qn = "pop_mode", jn = "longer_alt", Vn = "line_breaks", Kn = "start_chars_hint"; + function zn(t2) { + return go(t2); + } + H.createToken = zn; + function go(t2) { + var e = t2.pattern, r = {}; + if (r.name = t2.name, Te.isUndefined(e) || (r.PATTERN = e), Te.has(t2, _o)) + throw `The parent property is no longer supported. +See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.`; + return Te.has(t2, Un) && (r.CATEGORIES = t2[Un]), Pr.augmentTokenTypes([r]), Te.has(t2, Gn) && (r.LABEL = t2[Gn]), Te.has(t2, Wn) && (r.GROUP = t2[Wn]), Te.has(t2, qn) && (r.POP_MODE = t2[qn]), Te.has(t2, Bn) && (r.PUSH_MODE = t2[Bn]), Te.has(t2, jn) && (r.LONGER_ALT = t2[jn]), Te.has(t2, Vn) && (r.LINE_BREAKS = t2[Vn]), Te.has(t2, Kn) && (r.START_CHARS_HINT = t2[Kn]), r; + } + H.EOF = zn({ name: "EOF", pattern: Eo.Lexer.NA }); + Pr.augmentTokenTypes([H.EOF]); + function Ao(t2, e, r, n2, i, a, o, s) { + return { image: e, startOffset: r, endOffset: n2, startLine: i, endLine: a, startColumn: o, endColumn: s, tokenTypeIdx: t2.tokenTypeIdx, tokenType: t2 }; + } + H.createTokenInstance = Ao; + function Ro(t2, e) { + return Pr.tokenStructuredMatcher(t2, e); + } + H.tokenMatcher = Ro; +}); +var ne = R2((S) => { + var Le = S && S.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(S, "__esModule", { value: true }); + S.serializeProduction = S.serializeGrammar = S.Terminal = S.Alternation = S.RepetitionWithSeparator = S.Repetition = S.RepetitionMandatoryWithSeparator = S.RepetitionMandatory = S.Option = S.Alternative = S.Rule = S.NonTerminal = S.AbstractProduction = undefined; + var G2 = k2(), Oo = Ue(), Re = function() { + function t2(e) { + this._definition = e; + } + return Object.defineProperty(t2.prototype, "definition", { get: function() { + return this._definition; + }, set: function(e) { + this._definition = e; + }, enumerable: false, configurable: true }), t2.prototype.accept = function(e) { + e.visit(this), G2.forEach(this.definition, function(r) { + r.accept(e); + }); + }, t2; + }(); + S.AbstractProduction = Re; + var Hn = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, []) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return Object.defineProperty(e.prototype, "definition", { get: function() { + return this.referencedRule !== undefined ? this.referencedRule.definition : []; + }, set: function(r) { + }, enumerable: false, configurable: true }), e.prototype.accept = function(r) { + r.visit(this); + }, e; + }(Re); + S.NonTerminal = Hn; + var Yn = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.orgText = "", G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.Rule = Yn; + var Xn = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.ignoreAmbiguities = false, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.Alternative = Xn; + var $n = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.Option = $n; + var Zn = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.RepetitionMandatory = Zn; + var Qn = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.RepetitionMandatoryWithSeparator = Qn; + var Jn = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.Repetition = Jn; + var ei = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.RepetitionWithSeparator = ei; + var ti = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.idx = 1, n2.ignoreAmbiguities = false, n2.hasPredicates = false, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return Object.defineProperty(e.prototype, "definition", { get: function() { + return this._definition; + }, set: function(r) { + this._definition = r; + }, enumerable: false, configurable: true }), e; + }(Re); + S.Alternation = ti; + var Dt = function() { + function t2(e) { + this.idx = 1, G2.assign(this, G2.pick(e, function(r) { + return r !== undefined; + })); + } + return t2.prototype.accept = function(e) { + e.visit(this); + }, t2; + }(); + S.Terminal = Dt; + function No(t2) { + return G2.map(t2, ht); + } + S.serializeGrammar = No; + function ht(t2) { + function e(i) { + return G2.map(i, ht); + } + if (t2 instanceof Hn) + return { type: "NonTerminal", name: t2.nonTerminalName, idx: t2.idx }; + if (t2 instanceof Xn) + return { type: "Alternative", definition: e(t2.definition) }; + if (t2 instanceof $n) + return { type: "Option", idx: t2.idx, definition: e(t2.definition) }; + if (t2 instanceof Zn) + return { type: "RepetitionMandatory", idx: t2.idx, definition: e(t2.definition) }; + if (t2 instanceof Qn) + return { type: "RepetitionMandatoryWithSeparator", idx: t2.idx, separator: ht(new Dt({ terminalType: t2.separator })), definition: e(t2.definition) }; + if (t2 instanceof ei) + return { type: "RepetitionWithSeparator", idx: t2.idx, separator: ht(new Dt({ terminalType: t2.separator })), definition: e(t2.definition) }; + if (t2 instanceof Jn) + return { type: "Repetition", idx: t2.idx, definition: e(t2.definition) }; + if (t2 instanceof ti) + return { type: "Alternation", idx: t2.idx, definition: e(t2.definition) }; + if (t2 instanceof Dt) { + var r = { type: "Terminal", name: t2.terminalType.name, label: Oo.tokenLabel(t2.terminalType), idx: t2.idx }, n2 = t2.terminalType.PATTERN; + return t2.terminalType.PATTERN && (r.pattern = G2.isRegExp(n2) ? n2.source : n2), r; + } else { + if (t2 instanceof Yn) + return { type: "Rule", name: t2.name, orgText: t2.orgText, definition: e(t2.definition) }; + throw Error("non exhaustive match"); + } + } + S.serializeProduction = ht; +}); +var Gt = R2((Ut2) => { + Object.defineProperty(Ut2, "__esModule", { value: true }); + Ut2.RestWalker = undefined; + var Sr = k2(), ie = ne(), Io = function() { + function t2() { + } + return t2.prototype.walk = function(e, r) { + var n2 = this; + r === undefined && (r = []), Sr.forEach(e.definition, function(i, a) { + var o = Sr.drop(e.definition, a + 1); + if (i instanceof ie.NonTerminal) + n2.walkProdRef(i, o, r); + else if (i instanceof ie.Terminal) + n2.walkTerminal(i, o, r); + else if (i instanceof ie.Alternative) + n2.walkFlat(i, o, r); + else if (i instanceof ie.Option) + n2.walkOption(i, o, r); + else if (i instanceof ie.RepetitionMandatory) + n2.walkAtLeastOne(i, o, r); + else if (i instanceof ie.RepetitionMandatoryWithSeparator) + n2.walkAtLeastOneSep(i, o, r); + else if (i instanceof ie.RepetitionWithSeparator) + n2.walkManySep(i, o, r); + else if (i instanceof ie.Repetition) + n2.walkMany(i, o, r); + else if (i instanceof ie.Alternation) + n2.walkOr(i, o, r); + else + throw Error("non exhaustive match"); + }); + }, t2.prototype.walkTerminal = function(e, r, n2) { + }, t2.prototype.walkProdRef = function(e, r, n2) { + }, t2.prototype.walkFlat = function(e, r, n2) { + var i = r.concat(n2); + this.walk(e, i); + }, t2.prototype.walkOption = function(e, r, n2) { + var i = r.concat(n2); + this.walk(e, i); + }, t2.prototype.walkAtLeastOne = function(e, r, n2) { + var i = [new ie.Option({ definition: e.definition })].concat(r, n2); + this.walk(e, i); + }, t2.prototype.walkAtLeastOneSep = function(e, r, n2) { + var i = ri(e, r, n2); + this.walk(e, i); + }, t2.prototype.walkMany = function(e, r, n2) { + var i = [new ie.Option({ definition: e.definition })].concat(r, n2); + this.walk(e, i); + }, t2.prototype.walkManySep = function(e, r, n2) { + var i = ri(e, r, n2); + this.walk(e, i); + }, t2.prototype.walkOr = function(e, r, n2) { + var i = this, a = r.concat(n2); + Sr.forEach(e.definition, function(o) { + var s = new ie.Alternative({ definition: [o] }); + i.walk(s, a); + }); + }, t2; + }(); + Ut2.RestWalker = Io; + function ri(t2, e, r) { + var n2 = [new ie.Option({ definition: [new ie.Terminal({ terminalType: t2.separator })].concat(t2.definition) })], i = n2.concat(e, r); + return i; + } +}); +var $e = R2((Wt) => { + Object.defineProperty(Wt, "__esModule", { value: true }); + Wt.GAstVisitor = undefined; + var Oe = ne(), ko = function() { + function t2() { + } + return t2.prototype.visit = function(e) { + var r = e; + switch (r.constructor) { + case Oe.NonTerminal: + return this.visitNonTerminal(r); + case Oe.Alternative: + return this.visitAlternative(r); + case Oe.Option: + return this.visitOption(r); + case Oe.RepetitionMandatory: + return this.visitRepetitionMandatory(r); + case Oe.RepetitionMandatoryWithSeparator: + return this.visitRepetitionMandatoryWithSeparator(r); + case Oe.RepetitionWithSeparator: + return this.visitRepetitionWithSeparator(r); + case Oe.Repetition: + return this.visitRepetition(r); + case Oe.Alternation: + return this.visitAlternation(r); + case Oe.Terminal: + return this.visitTerminal(r); + case Oe.Rule: + return this.visitRule(r); + default: + throw Error("non exhaustive match"); + } + }, t2.prototype.visitNonTerminal = function(e) { + }, t2.prototype.visitAlternative = function(e) { + }, t2.prototype.visitOption = function(e) { + }, t2.prototype.visitRepetition = function(e) { + }, t2.prototype.visitRepetitionMandatory = function(e) { + }, t2.prototype.visitRepetitionMandatoryWithSeparator = function(e) { + }, t2.prototype.visitRepetitionWithSeparator = function(e) { + }, t2.prototype.visitAlternation = function(e) { + }, t2.prototype.visitTerminal = function(e) { + }, t2.prototype.visitRule = function(e) { + }, t2; + }(); + Wt.GAstVisitor = ko; +}); +var vt = R2((X) => { + var Po = X && X.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(X, "__esModule", { value: true }); + X.collectMethods = X.DslMethodsCollectorVisitor = X.getProductionDslName = X.isBranchingProd = X.isOptionalProd = X.isSequenceProd = undefined; + var dt = k2(), W = ne(), So = $e(); + function xo(t2) { + return t2 instanceof W.Alternative || t2 instanceof W.Option || t2 instanceof W.Repetition || t2 instanceof W.RepetitionMandatory || t2 instanceof W.RepetitionMandatoryWithSeparator || t2 instanceof W.RepetitionWithSeparator || t2 instanceof W.Terminal || t2 instanceof W.Rule; + } + X.isSequenceProd = xo; + function xr(t2, e) { + e === undefined && (e = []); + var r = t2 instanceof W.Option || t2 instanceof W.Repetition || t2 instanceof W.RepetitionWithSeparator; + return r ? true : t2 instanceof W.Alternation ? dt.some(t2.definition, function(n2) { + return xr(n2, e); + }) : t2 instanceof W.NonTerminal && dt.contains(e, t2) ? false : t2 instanceof W.AbstractProduction ? (t2 instanceof W.NonTerminal && e.push(t2), dt.every(t2.definition, function(n2) { + return xr(n2, e); + })) : false; + } + X.isOptionalProd = xr; + function Co(t2) { + return t2 instanceof W.Alternation; + } + X.isBranchingProd = Co; + function Lo(t2) { + if (t2 instanceof W.NonTerminal) + return "SUBRULE"; + if (t2 instanceof W.Option) + return "OPTION"; + if (t2 instanceof W.Alternation) + return "OR"; + if (t2 instanceof W.RepetitionMandatory) + return "AT_LEAST_ONE"; + if (t2 instanceof W.RepetitionMandatoryWithSeparator) + return "AT_LEAST_ONE_SEP"; + if (t2 instanceof W.RepetitionWithSeparator) + return "MANY_SEP"; + if (t2 instanceof W.Repetition) + return "MANY"; + if (t2 instanceof W.Terminal) + return "CONSUME"; + throw Error("non exhaustive match"); + } + X.getProductionDslName = Lo; + var ni = function(t2) { + Po(e, t2); + function e() { + var r = t2 !== null && t2.apply(this, arguments) || this; + return r.separator = "-", r.dslMethods = { option: [], alternation: [], repetition: [], repetitionWithSeparator: [], repetitionMandatory: [], repetitionMandatoryWithSeparator: [] }, r; + } + return e.prototype.reset = function() { + this.dslMethods = { option: [], alternation: [], repetition: [], repetitionWithSeparator: [], repetitionMandatory: [], repetitionMandatoryWithSeparator: [] }; + }, e.prototype.visitTerminal = function(r) { + var n2 = r.terminalType.name + this.separator + "Terminal"; + dt.has(this.dslMethods, n2) || (this.dslMethods[n2] = []), this.dslMethods[n2].push(r); + }, e.prototype.visitNonTerminal = function(r) { + var n2 = r.nonTerminalName + this.separator + "Terminal"; + dt.has(this.dslMethods, n2) || (this.dslMethods[n2] = []), this.dslMethods[n2].push(r); + }, e.prototype.visitOption = function(r) { + this.dslMethods.option.push(r); + }, e.prototype.visitRepetitionWithSeparator = function(r) { + this.dslMethods.repetitionWithSeparator.push(r); + }, e.prototype.visitRepetitionMandatory = function(r) { + this.dslMethods.repetitionMandatory.push(r); + }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) { + this.dslMethods.repetitionMandatoryWithSeparator.push(r); + }, e.prototype.visitRepetition = function(r) { + this.dslMethods.repetition.push(r); + }, e.prototype.visitAlternation = function(r) { + this.dslMethods.alternation.push(r); + }, e; + }(So.GAstVisitor); + X.DslMethodsCollectorVisitor = ni; + var Bt = new ni; + function Mo2(t2) { + Bt.reset(), t2.accept(Bt); + var e = Bt.dslMethods; + return Bt.reset(), e; + } + X.collectMethods = Mo2; +}); +var Lr = R2((Ne) => { + Object.defineProperty(Ne, "__esModule", { value: true }); + Ne.firstForTerminal = Ne.firstForBranching = Ne.firstForSequence = Ne.first = undefined; + var qt = k2(), ii = ne(), Cr2 = vt(); + function jt(t2) { + if (t2 instanceof ii.NonTerminal) + return jt(t2.referencedRule); + if (t2 instanceof ii.Terminal) + return si(t2); + if (Cr2.isSequenceProd(t2)) + return ai(t2); + if (Cr2.isBranchingProd(t2)) + return oi(t2); + throw Error("non exhaustive match"); + } + Ne.first = jt; + function ai(t2) { + for (var e = [], r = t2.definition, n2 = 0, i = r.length > n2, a, o = true;i && o; ) + a = r[n2], o = Cr2.isOptionalProd(a), e = e.concat(jt(a)), n2 = n2 + 1, i = r.length > n2; + return qt.uniq(e); + } + Ne.firstForSequence = ai; + function oi(t2) { + var e = qt.map(t2.definition, function(r) { + return jt(r); + }); + return qt.uniq(qt.flatten(e)); + } + Ne.firstForBranching = oi; + function si(t2) { + return [t2.terminalType]; + } + Ne.firstForTerminal = si; +}); +var Mr = R2((Vt) => { + Object.defineProperty(Vt, "__esModule", { value: true }); + Vt.IN = undefined; + Vt.IN = "_~IN~_"; +}); +var pi2 = R2((he) => { + var bo = he && he.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(he, "__esModule", { value: true }); + he.buildInProdFollowPrefix = he.buildBetweenProdsFollowPrefix = he.computeAllProdsFollows = he.ResyncFollowsWalker = undefined; + var Fo = Gt(), wo = Lr(), ui = k2(), ci = Mr(), Do = ne(), fi = function(t2) { + bo(e, t2); + function e(r) { + var n2 = t2.call(this) || this; + return n2.topProd = r, n2.follows = {}, n2; + } + return e.prototype.startWalking = function() { + return this.walk(this.topProd), this.follows; + }, e.prototype.walkTerminal = function(r, n2, i) { + }, e.prototype.walkProdRef = function(r, n2, i) { + var a = li(r.referencedRule, r.idx) + this.topProd.name, o = n2.concat(i), s = new Do.Alternative({ definition: o }), c = wo.first(s); + this.follows[a] = c; + }, e; + }(Fo.RestWalker); + he.ResyncFollowsWalker = fi; + function Uo(t2) { + var e = {}; + return ui.forEach(t2, function(r) { + var n2 = new fi(r).startWalking(); + ui.assign(e, n2); + }), e; + } + he.computeAllProdsFollows = Uo; + function li(t2, e) { + return t2.name + e + ci.IN; + } + he.buildBetweenProdsFollowPrefix = li; + function Go(t2) { + var e = t2.terminalType.name; + return e + t2.idx + ci.IN; + } + he.buildInProdFollowPrefix = Go; +}); +var mt = R2((Me) => { + Object.defineProperty(Me, "__esModule", { value: true }); + Me.defaultGrammarValidatorErrorProvider = Me.defaultGrammarResolverErrorProvider = Me.defaultParserErrorProvider = undefined; + var Ze2 = Ue(), Wo = k2(), ye = k2(), br = ne(), hi = vt(); + Me.defaultParserErrorProvider = { buildMismatchTokenMessage: function(t2) { + var { expected: e, actual: r, previous: n2, ruleName: i } = t2, a = Ze2.hasTokenLabel(e), o = a ? "--> " + Ze2.tokenLabel(e) + " <--" : "token of type --> " + e.name + " <--", s = "Expecting " + o + " but found --> '" + r.image + "' <--"; + return s; + }, buildNotAllInputParsedMessage: function(t2) { + var { firstRedundant: e, ruleName: r } = t2; + return "Redundant input, expecting EOF but found: " + e.image; + }, buildNoViableAltMessage: function(t2) { + var { expectedPathsPerAlt: e, actual: r, previous: n2, customUserDescription: i, ruleName: a } = t2, o = "Expecting: ", s = ye.first(r).image, c = ` +but found: '` + s + "'"; + if (i) + return o + i + c; + var f = ye.reduce(e, function(v, u2) { + return v.concat(u2); + }, []), p = ye.map(f, function(v) { + return "[" + ye.map(v, function(u2) { + return Ze2.tokenLabel(u2); + }).join(", ") + "]"; + }), l2 = ye.map(p, function(v, u2) { + return " " + (u2 + 1) + ". " + v; + }), m = `one of these possible Token sequences: +` + l2.join(` +`); + return o + m + c; + }, buildEarlyExitMessage: function(t2) { + var { expectedIterationPaths: e, actual: r, customUserDescription: n2, ruleName: i } = t2, a = "Expecting: ", o = ye.first(r).image, s = ` +but found: '` + o + "'"; + if (n2) + return a + n2 + s; + var c = ye.map(e, function(p) { + return "[" + ye.map(p, function(l2) { + return Ze2.tokenLabel(l2); + }).join(",") + "]"; + }), f = `expecting at least one iteration which starts with one of these possible Token sequences:: + ` + ("<" + c.join(" ,") + ">"); + return a + f + s; + } }; + Object.freeze(Me.defaultParserErrorProvider); + Me.defaultGrammarResolverErrorProvider = { buildRuleNotFoundError: function(t2, e) { + var r = "Invalid grammar, reference to a rule which is not defined: ->" + e.nonTerminalName + `<- +inside top level rule: ->` + t2.name + "<-"; + return r; + } }; + Me.defaultGrammarValidatorErrorProvider = { buildDuplicateFoundError: function(t2, e) { + function r(p) { + return p instanceof br.Terminal ? p.terminalType.name : p instanceof br.NonTerminal ? p.nonTerminalName : ""; + } + var n2 = t2.name, i = ye.first(e), a = i.idx, o = hi.getProductionDslName(i), s = r(i), c = a > 0, f = "->" + o + (c ? a : "") + "<- " + (s ? "with argument: ->" + s + "<-" : "") + ` + appears more than once (` + e.length + " times) in the top level rule: ->" + n2 + `<-. + For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES + `; + return f = f.replace(/[ \t]+/g, " "), f = f.replace(/\s\s+/g, ` +`), f; + }, buildNamespaceConflictError: function(t2) { + var e = `Namespace conflict found in grammar. +` + ("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <" + t2.name + `>. +`) + `To resolve this make sure each Terminal and Non-Terminal names are unique +This is easy to accomplish by using the convention that Terminal names start with an uppercase letter +and Non-Terminal names start with a lower case letter.`; + return e; + }, buildAlternationPrefixAmbiguityError: function(t2) { + var e = ye.map(t2.prefixPath, function(i) { + return Ze2.tokenLabel(i); + }).join(", "), r = t2.alternation.idx === 0 ? "" : t2.alternation.idx, n2 = "Ambiguous alternatives: <" + t2.ambiguityIndices.join(" ,") + `> due to common lookahead prefix +` + ("in inside <" + t2.topLevelRule.name + `> Rule, +`) + ("<" + e + `> may appears as a prefix path in all these alternatives. +`) + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX +For Further details.`; + return n2; + }, buildAlternationAmbiguityError: function(t2) { + var e = ye.map(t2.prefixPath, function(i) { + return Ze2.tokenLabel(i); + }).join(", "), r = t2.alternation.idx === 0 ? "" : t2.alternation.idx, n2 = "Ambiguous Alternatives Detected: <" + t2.ambiguityIndices.join(" ,") + "> in " + (" inside <" + t2.topLevelRule.name + `> Rule, +`) + ("<" + e + `> may appears as a prefix path in all these alternatives. +`); + return n2 = n2 + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`, n2; + }, buildEmptyRepetitionError: function(t2) { + var e = hi.getProductionDslName(t2.repetition); + t2.repetition.idx !== 0 && (e += t2.repetition.idx); + var r = "The repetition <" + e + "> within Rule <" + t2.topLevelRule.name + `> can never consume any tokens. +This could lead to an infinite loop.`; + return r; + }, buildTokenNameError: function(t2) { + return "deprecated"; + }, buildEmptyAlternationError: function(t2) { + var e = "Ambiguous empty alternative: <" + (t2.emptyChoiceIdx + 1) + ">" + (" in inside <" + t2.topLevelRule.name + `> Rule. +`) + "Only the last alternative may be an empty alternative."; + return e; + }, buildTooManyAlternativesError: function(t2) { + var e = `An Alternation cannot have more than 256 alternatives: +` + (" inside <" + t2.topLevelRule.name + `> Rule. + has ` + (t2.alternation.definition.length + 1) + " alternatives."); + return e; + }, buildLeftRecursionError: function(t2) { + var e = t2.topLevelRule.name, r = Wo.map(t2.leftRecursionPath, function(a) { + return a.name; + }), n2 = e + " --> " + r.concat([e]).join(" --> "), i = `Left Recursion found in grammar. +` + ("rule: <" + e + `> can be invoked from itself (directly or indirectly) +`) + (`without consuming any Tokens. The grammar path that causes this is: + ` + n2 + ` +`) + ` To fix this refactor your grammar to remove the left recursion. +see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring.`; + return i; + }, buildInvalidRuleNameError: function(t2) { + return "deprecated"; + }, buildDuplicateRuleNameError: function(t2) { + var e; + t2.topLevelRule instanceof br.Rule ? e = t2.topLevelRule.name : e = t2.topLevelRule; + var r = "Duplicate definition, rule: ->" + e + "<- is already defined in the grammar: ->" + t2.grammarName + "<-"; + return r; + } }; +}); +var mi = R2((Ge) => { + var Bo = Ge && Ge.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(Ge, "__esModule", { value: true }); + Ge.GastRefResolverVisitor = Ge.resolveGrammar = undefined; + var qo = ce2(), di2 = k2(), jo = $e(); + function Vo(t2, e) { + var r = new vi(t2, e); + return r.resolveRefs(), r.errors; + } + Ge.resolveGrammar = Vo; + var vi = function(t2) { + Bo(e, t2); + function e(r, n2) { + var i = t2.call(this) || this; + return i.nameToTopRule = r, i.errMsgProvider = n2, i.errors = [], i; + } + return e.prototype.resolveRefs = function() { + var r = this; + di2.forEach(di2.values(this.nameToTopRule), function(n2) { + r.currTopLevel = n2, n2.accept(r); + }); + }, e.prototype.visitNonTerminal = function(r) { + var n2 = this.nameToTopRule[r.nonTerminalName]; + if (n2) + r.referencedRule = n2; + else { + var i = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, r); + this.errors.push({ message: i, type: qo.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF, ruleName: this.currTopLevel.name, unresolvedRefName: r.nonTerminalName }); + } + }, e; + }(jo.GAstVisitor); + Ge.GastRefResolverVisitor = vi; +}); +var Tt2 = R2((j2) => { + var je = j2 && j2.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(j2, "__esModule", { value: true }); + j2.nextPossibleTokensAfter = j2.possiblePathsFrom = j2.NextTerminalAfterAtLeastOneSepWalker = j2.NextTerminalAfterAtLeastOneWalker = j2.NextTerminalAfterManySepWalker = j2.NextTerminalAfterManyWalker = j2.AbstractNextTerminalAfterProductionWalker = j2.NextAfterTokenWalker = j2.AbstractNextPossibleTokensWalker = undefined; + var Ei = Gt(), I3 = k2(), Ko = Lr(), O = ne(), Ti2 = function(t2) { + je(e, t2); + function e(r, n2) { + var i = t2.call(this) || this; + return i.topProd = r, i.path = n2, i.possibleTokTypes = [], i.nextProductionName = "", i.nextProductionOccurrence = 0, i.found = false, i.isAtEndOfPath = false, i; + } + return e.prototype.startWalking = function() { + if (this.found = false, this.path.ruleStack[0] !== this.topProd.name) + throw Error("The path does not start with the walker's top Rule!"); + return this.ruleStack = I3.cloneArr(this.path.ruleStack).reverse(), this.occurrenceStack = I3.cloneArr(this.path.occurrenceStack).reverse(), this.ruleStack.pop(), this.occurrenceStack.pop(), this.updateExpectedNext(), this.walk(this.topProd), this.possibleTokTypes; + }, e.prototype.walk = function(r, n2) { + n2 === undefined && (n2 = []), this.found || t2.prototype.walk.call(this, r, n2); + }, e.prototype.walkProdRef = function(r, n2, i) { + if (r.referencedRule.name === this.nextProductionName && r.idx === this.nextProductionOccurrence) { + var a = n2.concat(i); + this.updateExpectedNext(), this.walk(r.referencedRule, a); + } + }, e.prototype.updateExpectedNext = function() { + I3.isEmpty(this.ruleStack) ? (this.nextProductionName = "", this.nextProductionOccurrence = 0, this.isAtEndOfPath = true) : (this.nextProductionName = this.ruleStack.pop(), this.nextProductionOccurrence = this.occurrenceStack.pop()); + }, e; + }(Ei.RestWalker); + j2.AbstractNextPossibleTokensWalker = Ti2; + var zo = function(t2) { + je(e, t2); + function e(r, n2) { + var i = t2.call(this, r, n2) || this; + return i.path = n2, i.nextTerminalName = "", i.nextTerminalOccurrence = 0, i.nextTerminalName = i.path.lastTok.name, i.nextTerminalOccurrence = i.path.lastTokOccurrence, i; + } + return e.prototype.walkTerminal = function(r, n2, i) { + if (this.isAtEndOfPath && r.terminalType.name === this.nextTerminalName && r.idx === this.nextTerminalOccurrence && !this.found) { + var a = n2.concat(i), o = new O.Alternative({ definition: a }); + this.possibleTokTypes = Ko.first(o), this.found = true; + } + }, e; + }(Ti2); + j2.NextAfterTokenWalker = zo; + var Et2 = function(t2) { + je(e, t2); + function e(r, n2) { + var i = t2.call(this) || this; + return i.topRule = r, i.occurrence = n2, i.result = { token: undefined, occurrence: undefined, isEndOfRule: undefined }, i; + } + return e.prototype.startWalking = function() { + return this.walk(this.topRule), this.result; + }, e; + }(Ei.RestWalker); + j2.AbstractNextTerminalAfterProductionWalker = Et2; + var Ho = function(t2) { + je(e, t2); + function e() { + return t2 !== null && t2.apply(this, arguments) || this; + } + return e.prototype.walkMany = function(r, n2, i) { + if (r.idx === this.occurrence) { + var a = I3.first(n2.concat(i)); + this.result.isEndOfRule = a === undefined, a instanceof O.Terminal && (this.result.token = a.terminalType, this.result.occurrence = a.idx); + } else + t2.prototype.walkMany.call(this, r, n2, i); + }, e; + }(Et2); + j2.NextTerminalAfterManyWalker = Ho; + var Yo = function(t2) { + je(e, t2); + function e() { + return t2 !== null && t2.apply(this, arguments) || this; + } + return e.prototype.walkManySep = function(r, n2, i) { + if (r.idx === this.occurrence) { + var a = I3.first(n2.concat(i)); + this.result.isEndOfRule = a === undefined, a instanceof O.Terminal && (this.result.token = a.terminalType, this.result.occurrence = a.idx); + } else + t2.prototype.walkManySep.call(this, r, n2, i); + }, e; + }(Et2); + j2.NextTerminalAfterManySepWalker = Yo; + var Xo = function(t2) { + je(e, t2); + function e() { + return t2 !== null && t2.apply(this, arguments) || this; + } + return e.prototype.walkAtLeastOne = function(r, n2, i) { + if (r.idx === this.occurrence) { + var a = I3.first(n2.concat(i)); + this.result.isEndOfRule = a === undefined, a instanceof O.Terminal && (this.result.token = a.terminalType, this.result.occurrence = a.idx); + } else + t2.prototype.walkAtLeastOne.call(this, r, n2, i); + }, e; + }(Et2); + j2.NextTerminalAfterAtLeastOneWalker = Xo; + var $o = function(t2) { + je(e, t2); + function e() { + return t2 !== null && t2.apply(this, arguments) || this; + } + return e.prototype.walkAtLeastOneSep = function(r, n2, i) { + if (r.idx === this.occurrence) { + var a = I3.first(n2.concat(i)); + this.result.isEndOfRule = a === undefined, a instanceof O.Terminal && (this.result.token = a.terminalType, this.result.occurrence = a.idx); + } else + t2.prototype.walkAtLeastOneSep.call(this, r, n2, i); + }, e; + }(Et2); + j2.NextTerminalAfterAtLeastOneSepWalker = $o; + function yi(t2, e, r) { + r === undefined && (r = []), r = I3.cloneArr(r); + var n2 = [], i = 0; + function a(f) { + return f.concat(I3.drop(t2, i + 1)); + } + function o(f) { + var p = yi(a(f), e, r); + return n2.concat(p); + } + for (;r.length < e && i < t2.length; ) { + var s = t2[i]; + if (s instanceof O.Alternative) + return o(s.definition); + if (s instanceof O.NonTerminal) + return o(s.definition); + if (s instanceof O.Option) + n2 = o(s.definition); + else if (s instanceof O.RepetitionMandatory) { + var c = s.definition.concat([new O.Repetition({ definition: s.definition })]); + return o(c); + } else if (s instanceof O.RepetitionMandatoryWithSeparator) { + var c = [new O.Alternative({ definition: s.definition }), new O.Repetition({ definition: [new O.Terminal({ terminalType: s.separator })].concat(s.definition) })]; + return o(c); + } else if (s instanceof O.RepetitionWithSeparator) { + var c = s.definition.concat([new O.Repetition({ definition: [new O.Terminal({ terminalType: s.separator })].concat(s.definition) })]); + n2 = o(c); + } else if (s instanceof O.Repetition) { + var c = s.definition.concat([new O.Repetition({ definition: s.definition })]); + n2 = o(c); + } else { + if (s instanceof O.Alternation) + return I3.forEach(s.definition, function(f) { + I3.isEmpty(f.definition) === false && (n2 = o(f.definition)); + }), n2; + if (s instanceof O.Terminal) + r.push(s.terminalType); + else + throw Error("non exhaustive match"); + } + i++; + } + return n2.push({ partialPath: r, suffixDef: I3.drop(t2, i) }), n2; + } + j2.possiblePathsFrom = yi; + function Qo(t2, e, r, n2) { + var i = "EXIT_NONE_TERMINAL", a = [i], o = "EXIT_ALTERNATIVE", s = false, c = e.length, f = c - n2 - 1, p = [], l2 = []; + for (l2.push({ idx: -1, def: t2, ruleStack: [], occurrenceStack: [] });!I3.isEmpty(l2); ) { + var m = l2.pop(); + if (m === o) { + s && I3.last(l2).idx <= f && l2.pop(); + continue; + } + var { def: v, idx: u2, ruleStack: d, occurrenceStack: A2 } = m; + if (!I3.isEmpty(v)) { + var _2 = v[0]; + if (_2 === i) { + var g3 = { idx: u2, def: I3.drop(v), ruleStack: I3.dropRight(d), occurrenceStack: I3.dropRight(A2) }; + l2.push(g3); + } else if (_2 instanceof O.Terminal) + if (u2 < c - 1) { + var y = u2 + 1, b = e[y]; + if (r(b, _2.terminalType)) { + var g3 = { idx: y, def: I3.drop(v), ruleStack: d, occurrenceStack: A2 }; + l2.push(g3); + } + } else if (u2 === c - 1) + p.push({ nextTokenType: _2.terminalType, nextTokenOccurrence: _2.idx, ruleStack: d, occurrenceStack: A2 }), s = true; + else + throw Error("non exhaustive match"); + else if (_2 instanceof O.NonTerminal) { + var L = I3.cloneArr(d); + L.push(_2.nonTerminalName); + var se2 = I3.cloneArr(A2); + se2.push(_2.idx); + var g3 = { idx: u2, def: _2.definition.concat(a, I3.drop(v)), ruleStack: L, occurrenceStack: se2 }; + l2.push(g3); + } else if (_2 instanceof O.Option) { + var fe = { idx: u2, def: I3.drop(v), ruleStack: d, occurrenceStack: A2 }; + l2.push(fe), l2.push(o); + var Z2 = { idx: u2, def: _2.definition.concat(I3.drop(v)), ruleStack: d, occurrenceStack: A2 }; + l2.push(Z2); + } else if (_2 instanceof O.RepetitionMandatory) { + var ue3 = new O.Repetition({ definition: _2.definition, idx: _2.idx }), Q2 = _2.definition.concat([ue3], I3.drop(v)), g3 = { idx: u2, def: Q2, ruleStack: d, occurrenceStack: A2 }; + l2.push(g3); + } else if (_2 instanceof O.RepetitionMandatoryWithSeparator) { + var te3 = new O.Terminal({ terminalType: _2.separator }), ue3 = new O.Repetition({ definition: [te3].concat(_2.definition), idx: _2.idx }), Q2 = _2.definition.concat([ue3], I3.drop(v)), g3 = { idx: u2, def: Q2, ruleStack: d, occurrenceStack: A2 }; + l2.push(g3); + } else if (_2 instanceof O.RepetitionWithSeparator) { + var fe = { idx: u2, def: I3.drop(v), ruleStack: d, occurrenceStack: A2 }; + l2.push(fe), l2.push(o); + var te3 = new O.Terminal({ terminalType: _2.separator }), xe = new O.Repetition({ definition: [te3].concat(_2.definition), idx: _2.idx }), Q2 = _2.definition.concat([xe], I3.drop(v)), Z2 = { idx: u2, def: Q2, ruleStack: d, occurrenceStack: A2 }; + l2.push(Z2); + } else if (_2 instanceof O.Repetition) { + var fe = { idx: u2, def: I3.drop(v), ruleStack: d, occurrenceStack: A2 }; + l2.push(fe), l2.push(o); + var xe = new O.Repetition({ definition: _2.definition, idx: _2.idx }), Q2 = _2.definition.concat([xe], I3.drop(v)), Z2 = { idx: u2, def: Q2, ruleStack: d, occurrenceStack: A2 }; + l2.push(Z2); + } else if (_2 instanceof O.Alternation) + for (var it2 = _2.definition.length - 1;it2 >= 0; it2--) { + var at = _2.definition[it2], Ke2 = { idx: u2, def: at.definition.concat(I3.drop(v)), ruleStack: d, occurrenceStack: A2 }; + l2.push(Ke2), l2.push(o); + } + else if (_2 instanceof O.Alternative) + l2.push({ idx: u2, def: _2.definition.concat(I3.drop(v)), ruleStack: d, occurrenceStack: A2 }); + else if (_2 instanceof O.Rule) + l2.push(Zo(_2, u2, d, A2)); + else + throw Error("non exhaustive match"); + } + } + return p; + } + j2.nextPossibleTokensAfter = Qo; + function Zo(t2, e, r, n2) { + var i = I3.cloneArr(r); + i.push(t2.name); + var a = I3.cloneArr(n2); + return a.push(1), { idx: e, def: t2.definition, ruleStack: i, occurrenceStack: a }; + } +}); +var yt2 = R2((C4) => { + var _i = C4 && C4.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(C4, "__esModule", { value: true }); + C4.areTokenCategoriesNotUsed = C4.isStrictPrefixOfPath = C4.containsPath = C4.getLookaheadPathsForOptionalProd = C4.getLookaheadPathsForOr = C4.lookAheadSequenceFromAlternatives = C4.buildSingleAlternativeLookaheadFunction = C4.buildAlternativesLookAheadFunc = C4.buildLookaheadFuncForOptionalProd = C4.buildLookaheadFuncForOr = C4.getProdType = C4.PROD_TYPE = undefined; + var D = k2(), gi = Tt2(), Jo2 = Gt(), Kt = Xe(), We = ne(), es = $e(), z; + (function(t2) { + t2[t2.OPTION = 0] = "OPTION", t2[t2.REPETITION = 1] = "REPETITION", t2[t2.REPETITION_MANDATORY = 2] = "REPETITION_MANDATORY", t2[t2.REPETITION_MANDATORY_WITH_SEPARATOR = 3] = "REPETITION_MANDATORY_WITH_SEPARATOR", t2[t2.REPETITION_WITH_SEPARATOR = 4] = "REPETITION_WITH_SEPARATOR", t2[t2.ALTERNATION = 5] = "ALTERNATION"; + })(z = C4.PROD_TYPE || (C4.PROD_TYPE = {})); + function ts(t2) { + if (t2 instanceof We.Option) + return z.OPTION; + if (t2 instanceof We.Repetition) + return z.REPETITION; + if (t2 instanceof We.RepetitionMandatory) + return z.REPETITION_MANDATORY; + if (t2 instanceof We.RepetitionMandatoryWithSeparator) + return z.REPETITION_MANDATORY_WITH_SEPARATOR; + if (t2 instanceof We.RepetitionWithSeparator) + return z.REPETITION_WITH_SEPARATOR; + if (t2 instanceof We.Alternation) + return z.ALTERNATION; + throw Error("non exhaustive match"); + } + C4.getProdType = ts; + function rs(t2, e, r, n2, i, a) { + var o = Ai(t2, e, r), s = Fr(o) ? Kt.tokenStructuredMatcherNoCategories : Kt.tokenStructuredMatcher; + return a(o, n2, s, i); + } + C4.buildLookaheadFuncForOr = rs; + function ns(t2, e, r, n2, i, a) { + var o = Ri(t2, e, i, r), s = Fr(o) ? Kt.tokenStructuredMatcherNoCategories : Kt.tokenStructuredMatcher; + return a(o[0], s, n2); + } + C4.buildLookaheadFuncForOptionalProd = ns; + function is(t2, e, r, n2) { + var i = t2.length, a = D.every(t2, function(c) { + return D.every(c, function(f) { + return f.length === 1; + }); + }); + if (e) + return function(c) { + for (var f = D.map(c, function(y) { + return y.GATE; + }), p = 0;p < i; p++) { + var l2 = t2[p], m = l2.length, v = f[p]; + if (v !== undefined && v.call(this) === false) + continue; + e: + for (var u2 = 0;u2 < m; u2++) { + for (var d = l2[u2], A2 = d.length, _2 = 0;_2 < A2; _2++) { + var g3 = this.LA(_2 + 1); + if (r(g3, d[_2]) === false) + continue e; + } + return p; + } + } + }; + if (a && !n2) { + var o = D.map(t2, function(c) { + return D.flatten(c); + }), s = D.reduce(o, function(c, f, p) { + return D.forEach(f, function(l2) { + D.has(c, l2.tokenTypeIdx) || (c[l2.tokenTypeIdx] = p), D.forEach(l2.categoryMatches, function(m) { + D.has(c, m) || (c[m] = p); + }); + }), c; + }, []); + return function() { + var c = this.LA(1); + return s[c.tokenTypeIdx]; + }; + } else + return function() { + for (var c = 0;c < i; c++) { + var f = t2[c], p = f.length; + e: + for (var l2 = 0;l2 < p; l2++) { + for (var m = f[l2], v = m.length, u2 = 0;u2 < v; u2++) { + var d = this.LA(u2 + 1); + if (r(d, m[u2]) === false) + continue e; + } + return c; + } + } + }; + } + C4.buildAlternativesLookAheadFunc = is; + function as(t2, e, r) { + var n2 = D.every(t2, function(f) { + return f.length === 1; + }), i = t2.length; + if (n2 && !r) { + var a = D.flatten(t2); + if (a.length === 1 && D.isEmpty(a[0].categoryMatches)) { + var o = a[0], s = o.tokenTypeIdx; + return function() { + return this.LA(1).tokenTypeIdx === s; + }; + } else { + var c = D.reduce(a, function(f, p, l2) { + return f[p.tokenTypeIdx] = true, D.forEach(p.categoryMatches, function(m) { + f[m] = true; + }), f; + }, []); + return function() { + var f = this.LA(1); + return c[f.tokenTypeIdx] === true; + }; + } + } else + return function() { + e: + for (var f = 0;f < i; f++) { + for (var p = t2[f], l2 = p.length, m = 0;m < l2; m++) { + var v = this.LA(m + 1); + if (e(v, p[m]) === false) + continue e; + } + return true; + } + return false; + }; + } + C4.buildSingleAlternativeLookaheadFunction = as; + var os = function(t2) { + _i(e, t2); + function e(r, n2, i) { + var a = t2.call(this) || this; + return a.topProd = r, a.targetOccurrence = n2, a.targetProdType = i, a; + } + return e.prototype.startWalking = function() { + return this.walk(this.topProd), this.restDef; + }, e.prototype.checkIsTarget = function(r, n2, i, a) { + return r.idx === this.targetOccurrence && this.targetProdType === n2 ? (this.restDef = i.concat(a), true) : false; + }, e.prototype.walkOption = function(r, n2, i) { + this.checkIsTarget(r, z.OPTION, n2, i) || t2.prototype.walkOption.call(this, r, n2, i); + }, e.prototype.walkAtLeastOne = function(r, n2, i) { + this.checkIsTarget(r, z.REPETITION_MANDATORY, n2, i) || t2.prototype.walkOption.call(this, r, n2, i); + }, e.prototype.walkAtLeastOneSep = function(r, n2, i) { + this.checkIsTarget(r, z.REPETITION_MANDATORY_WITH_SEPARATOR, n2, i) || t2.prototype.walkOption.call(this, r, n2, i); + }, e.prototype.walkMany = function(r, n2, i) { + this.checkIsTarget(r, z.REPETITION, n2, i) || t2.prototype.walkOption.call(this, r, n2, i); + }, e.prototype.walkManySep = function(r, n2, i) { + this.checkIsTarget(r, z.REPETITION_WITH_SEPARATOR, n2, i) || t2.prototype.walkOption.call(this, r, n2, i); + }, e; + }(Jo2.RestWalker), Oi2 = function(t2) { + _i(e, t2); + function e(r, n2, i) { + var a = t2.call(this) || this; + return a.targetOccurrence = r, a.targetProdType = n2, a.targetRef = i, a.result = [], a; + } + return e.prototype.checkIsTarget = function(r, n2) { + r.idx === this.targetOccurrence && this.targetProdType === n2 && (this.targetRef === undefined || r === this.targetRef) && (this.result = r.definition); + }, e.prototype.visitOption = function(r) { + this.checkIsTarget(r, z.OPTION); + }, e.prototype.visitRepetition = function(r) { + this.checkIsTarget(r, z.REPETITION); + }, e.prototype.visitRepetitionMandatory = function(r) { + this.checkIsTarget(r, z.REPETITION_MANDATORY); + }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) { + this.checkIsTarget(r, z.REPETITION_MANDATORY_WITH_SEPARATOR); + }, e.prototype.visitRepetitionWithSeparator = function(r) { + this.checkIsTarget(r, z.REPETITION_WITH_SEPARATOR); + }, e.prototype.visitAlternation = function(r) { + this.checkIsTarget(r, z.ALTERNATION); + }, e; + }(es.GAstVisitor); + function Ni(t2) { + for (var e = new Array(t2), r = 0;r < t2; r++) + e[r] = []; + return e; + } + function wr(t2) { + for (var e = [""], r = 0;r < t2.length; r++) { + for (var n2 = t2[r], i = [], a = 0;a < e.length; a++) { + var o = e[a]; + i.push(o + "_" + n2.tokenTypeIdx); + for (var s = 0;s < n2.categoryMatches.length; s++) { + var c = "_" + n2.categoryMatches[s]; + i.push(o + c); + } + } + e = i; + } + return e; + } + function ss(t2, e, r) { + for (var n2 = 0;n2 < t2.length; n2++) + if (n2 !== r) + for (var i = t2[n2], a = 0;a < e.length; a++) { + var o = e[a]; + if (i[o] === true) + return false; + } + return true; + } + function Dr(t2, e) { + for (var r = D.map(t2, function(p) { + return gi.possiblePathsFrom([p], 1); + }), n2 = Ni(r.length), i = D.map(r, function(p) { + var l2 = {}; + return D.forEach(p, function(m) { + var v = wr(m.partialPath); + D.forEach(v, function(u2) { + l2[u2] = true; + }); + }), l2; + }), a = r, o = 1;o <= e; o++) { + var s = a; + a = Ni(s.length); + for (var c = function(p) { + for (var l2 = s[p], m = 0;m < l2.length; m++) { + var v = l2[m].partialPath, u2 = l2[m].suffixDef, d = wr(v), A2 = ss(i, d, p); + if (A2 || D.isEmpty(u2) || v.length === e) { + var _2 = n2[p]; + if (Ii2(_2, v) === false) { + _2.push(v); + for (var g3 = 0;g3 < d.length; g3++) { + var y = d[g3]; + i[p][y] = true; + } + } + } else { + var b = gi.possiblePathsFrom(u2, o + 1, v); + a[p] = a[p].concat(b), D.forEach(b, function(L) { + var se2 = wr(L.partialPath); + D.forEach(se2, function(fe) { + i[p][fe] = true; + }); + }); + } + } + }, f = 0;f < s.length; f++) + c(f); + } + return n2; + } + C4.lookAheadSequenceFromAlternatives = Dr; + function Ai(t2, e, r, n2) { + var i = new Oi2(t2, z.ALTERNATION, n2); + return e.accept(i), Dr(i.result, r); + } + C4.getLookaheadPathsForOr = Ai; + function Ri(t2, e, r, n2) { + var i = new Oi2(t2, r); + e.accept(i); + var a = i.result, o = new os(e, t2, r), s = o.startWalking(), c = new We.Alternative({ definition: a }), f = new We.Alternative({ definition: s }); + return Dr([c, f], n2); + } + C4.getLookaheadPathsForOptionalProd = Ri; + function Ii2(t2, e) { + e: + for (var r = 0;r < t2.length; r++) { + var n2 = t2[r]; + if (n2.length === e.length) { + for (var i = 0;i < n2.length; i++) { + var a = e[i], o = n2[i], s = a === o || o.categoryMatchesMap[a.tokenTypeIdx] !== undefined; + if (s === false) + continue e; + } + return true; + } + } + return false; + } + C4.containsPath = Ii2; + function us(t2, e) { + return t2.length < e.length && D.every(t2, function(r, n2) { + var i = e[n2]; + return r === i || i.categoryMatchesMap[r.tokenTypeIdx]; + }); + } + C4.isStrictPrefixOfPath = us; + function Fr(t2) { + return D.every(t2, function(e) { + return D.every(e, function(r) { + return D.every(r, function(n2) { + return D.isEmpty(n2.categoryMatches); + }); + }); + }); + } + C4.areTokenCategoriesNotUsed = Fr; +}); +var jr = R2((x2) => { + var Ur = x2 && x2.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(x2, "__esModule", { value: true }); + x2.checkPrefixAlternativesAmbiguities = x2.validateSomeNonEmptyLookaheadPath = x2.validateTooManyAlts = x2.RepetionCollector = x2.validateAmbiguousAlternationAlternatives = x2.validateEmptyOrAlternative = x2.getFirstNoneTerminal = x2.validateNoLeftRecursion = x2.validateRuleIsOverridden = x2.validateRuleDoesNotAlreadyExist = x2.OccurrenceValidationCollector = x2.identifyProductionForDuplicates = x2.validateGrammar = undefined; + var M = k2(), B2 = k2(), Ie = ce2(), Gr = vt(), Qe = yt2(), cs = Tt2(), _e = ne(), Wr = $e(); + function ps(t2, e, r, n2, i) { + var a = M.map(t2, function(v) { + return ls(v, n2); + }), o = M.map(t2, function(v) { + return Br(v, v, n2); + }), s = [], c = [], f = []; + B2.every(o, B2.isEmpty) && (s = B2.map(t2, function(v) { + return Pi3(v, n2); + }), c = B2.map(t2, function(v) { + return Si2(v, e, n2); + }), f = Ci(t2, e, n2)); + var p = fs(t2, r, n2), l2 = B2.map(t2, function(v) { + return xi(v, n2); + }), m = B2.map(t2, function(v) { + return ki(v, t2, i, n2); + }); + return M.flatten(a.concat(f, o, s, c, p, l2, m)); + } + x2.validateGrammar = ps; + function ls(t2, e) { + var r = new bi; + t2.accept(r); + var n2 = r.allProductions, i = M.groupBy(n2, Li), a = M.pick(i, function(s) { + return s.length > 1; + }), o = M.map(M.values(a), function(s) { + var c = M.first(s), f = e.buildDuplicateFoundError(t2, s), p = Gr.getProductionDslName(c), l2 = { message: f, type: Ie.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS, ruleName: t2.name, dslName: p, occurrence: c.idx }, m = Mi(c); + return m && (l2.parameter = m), l2; + }); + return o; + } + function Li(t2) { + return Gr.getProductionDslName(t2) + "_#_" + t2.idx + "_#_" + Mi(t2); + } + x2.identifyProductionForDuplicates = Li; + function Mi(t2) { + return t2 instanceof _e.Terminal ? t2.terminalType.name : t2 instanceof _e.NonTerminal ? t2.nonTerminalName : ""; + } + var bi = function(t2) { + Ur(e, t2); + function e() { + var r = t2 !== null && t2.apply(this, arguments) || this; + return r.allProductions = [], r; + } + return e.prototype.visitNonTerminal = function(r) { + this.allProductions.push(r); + }, e.prototype.visitOption = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionWithSeparator = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionMandatory = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetition = function(r) { + this.allProductions.push(r); + }, e.prototype.visitAlternation = function(r) { + this.allProductions.push(r); + }, e.prototype.visitTerminal = function(r) { + this.allProductions.push(r); + }, e; + }(Wr.GAstVisitor); + x2.OccurrenceValidationCollector = bi; + function ki(t2, e, r, n2) { + var i = [], a = B2.reduce(e, function(s, c) { + return c.name === t2.name ? s + 1 : s; + }, 0); + if (a > 1) { + var o = n2.buildDuplicateRuleNameError({ topLevelRule: t2, grammarName: r }); + i.push({ message: o, type: Ie.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, ruleName: t2.name }); + } + return i; + } + x2.validateRuleDoesNotAlreadyExist = ki; + function hs(t2, e, r) { + var n2 = [], i; + return M.contains(e, t2) || (i = "Invalid rule override, rule: ->" + t2 + "<- cannot be overridden in the grammar: ->" + r + "<-as it is not defined in any of the super grammars ", n2.push({ message: i, type: Ie.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE, ruleName: t2 })), n2; + } + x2.validateRuleIsOverridden = hs; + function Br(t2, e, r, n2) { + n2 === undefined && (n2 = []); + var i = [], a = _t(e.definition); + if (M.isEmpty(a)) + return []; + var o = t2.name, s = M.contains(a, t2); + s && i.push({ message: r.buildLeftRecursionError({ topLevelRule: t2, leftRecursionPath: n2 }), type: Ie.ParserDefinitionErrorType.LEFT_RECURSION, ruleName: o }); + var c = M.difference(a, n2.concat([t2])), f = M.map(c, function(p) { + var l2 = M.cloneArr(n2); + return l2.push(p), Br(t2, p, r, l2); + }); + return i.concat(M.flatten(f)); + } + x2.validateNoLeftRecursion = Br; + function _t(t2) { + var e = []; + if (M.isEmpty(t2)) + return e; + var r = M.first(t2); + if (r instanceof _e.NonTerminal) + e.push(r.referencedRule); + else if (r instanceof _e.Alternative || r instanceof _e.Option || r instanceof _e.RepetitionMandatory || r instanceof _e.RepetitionMandatoryWithSeparator || r instanceof _e.RepetitionWithSeparator || r instanceof _e.Repetition) + e = e.concat(_t(r.definition)); + else if (r instanceof _e.Alternation) + e = M.flatten(M.map(r.definition, function(o) { + return _t(o.definition); + })); + else if (!(r instanceof _e.Terminal)) + throw Error("non exhaustive match"); + var n2 = Gr.isOptionalProd(r), i = t2.length > 1; + if (n2 && i) { + var a = M.drop(t2); + return e.concat(_t(a)); + } else + return e; + } + x2.getFirstNoneTerminal = _t; + var qr2 = function(t2) { + Ur(e, t2); + function e() { + var r = t2 !== null && t2.apply(this, arguments) || this; + return r.alternations = [], r; + } + return e.prototype.visitAlternation = function(r) { + this.alternations.push(r); + }, e; + }(Wr.GAstVisitor); + function Pi3(t2, e) { + var r = new qr2; + t2.accept(r); + var n2 = r.alternations, i = M.reduce(n2, function(a, o) { + var s = M.dropRight(o.definition), c = M.map(s, function(f, p) { + var l2 = cs.nextPossibleTokensAfter([f], [], null, 1); + return M.isEmpty(l2) ? { message: e.buildEmptyAlternationError({ topLevelRule: t2, alternation: o, emptyChoiceIdx: p }), type: Ie.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT, ruleName: t2.name, occurrence: o.idx, alternative: p + 1 } : null; + }); + return a.concat(M.compact(c)); + }, []); + return i; + } + x2.validateEmptyOrAlternative = Pi3; + function Si2(t2, e, r) { + var n2 = new qr2; + t2.accept(n2); + var i = n2.alternations; + i = B2.reject(i, function(o) { + return o.ignoreAmbiguities === true; + }); + var a = M.reduce(i, function(o, s) { + var c = s.idx, f = s.maxLookahead || e, p = Qe.getLookaheadPathsForOr(c, t2, f, s), l2 = ds(p, s, t2, r), m = Fi2(p, s, t2, r); + return o.concat(l2, m); + }, []); + return a; + } + x2.validateAmbiguousAlternationAlternatives = Si2; + var wi = function(t2) { + Ur(e, t2); + function e() { + var r = t2 !== null && t2.apply(this, arguments) || this; + return r.allProductions = [], r; + } + return e.prototype.visitRepetitionWithSeparator = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionMandatory = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetition = function(r) { + this.allProductions.push(r); + }, e; + }(Wr.GAstVisitor); + x2.RepetionCollector = wi; + function xi(t2, e) { + var r = new qr2; + t2.accept(r); + var n2 = r.alternations, i = M.reduce(n2, function(a, o) { + return o.definition.length > 255 && a.push({ message: e.buildTooManyAlternativesError({ topLevelRule: t2, alternation: o }), type: Ie.ParserDefinitionErrorType.TOO_MANY_ALTS, ruleName: t2.name, occurrence: o.idx }), a; + }, []); + return i; + } + x2.validateTooManyAlts = xi; + function Ci(t2, e, r) { + var n2 = []; + return B2.forEach(t2, function(i) { + var a = new wi; + i.accept(a); + var o = a.allProductions; + B2.forEach(o, function(s) { + var c = Qe.getProdType(s), f = s.maxLookahead || e, p = s.idx, l2 = Qe.getLookaheadPathsForOptionalProd(p, i, c, f), m = l2[0]; + if (B2.isEmpty(B2.flatten(m))) { + var v = r.buildEmptyRepetitionError({ topLevelRule: i, repetition: s }); + n2.push({ message: v, type: Ie.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD, ruleName: i.name }); + } + }); + }), n2; + } + x2.validateSomeNonEmptyLookaheadPath = Ci; + function ds(t2, e, r, n2) { + var i = [], a = B2.reduce(t2, function(s, c, f) { + return e.definition[f].ignoreAmbiguities === true || B2.forEach(c, function(p) { + var l2 = [f]; + B2.forEach(t2, function(m, v) { + f !== v && Qe.containsPath(m, p) && e.definition[v].ignoreAmbiguities !== true && l2.push(v); + }), l2.length > 1 && !Qe.containsPath(i, p) && (i.push(p), s.push({ alts: l2, path: p })); + }), s; + }, []), o = M.map(a, function(s) { + var c = B2.map(s.alts, function(p) { + return p + 1; + }), f = n2.buildAlternationAmbiguityError({ topLevelRule: r, alternation: e, ambiguityIndices: c, prefixPath: s.path }); + return { message: f, type: Ie.ParserDefinitionErrorType.AMBIGUOUS_ALTS, ruleName: r.name, occurrence: e.idx, alternatives: [s.alts] }; + }); + return o; + } + function Fi2(t2, e, r, n2) { + var i = [], a = B2.reduce(t2, function(o, s, c) { + var f = B2.map(s, function(p) { + return { idx: c, path: p }; + }); + return o.concat(f); + }, []); + return B2.forEach(a, function(o) { + var s = e.definition[o.idx]; + if (s.ignoreAmbiguities !== true) { + var { idx: c, path: f } = o, p = B2.findAll(a, function(m) { + return e.definition[m.idx].ignoreAmbiguities !== true && m.idx < c && Qe.isStrictPrefixOfPath(m.path, f); + }), l2 = B2.map(p, function(m) { + var v = [m.idx + 1, c + 1], u2 = e.idx === 0 ? "" : e.idx, d = n2.buildAlternationPrefixAmbiguityError({ topLevelRule: r, alternation: e, ambiguityIndices: v, prefixPath: m.path }); + return { message: d, type: Ie.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS, ruleName: r.name, occurrence: u2, alternatives: v }; + }); + i = i.concat(l2); + } + }), i; + } + x2.checkPrefixAlternativesAmbiguities = Fi2; + function fs(t2, e, r) { + var n2 = [], i = B2.map(e, function(a) { + return a.name; + }); + return B2.forEach(t2, function(a) { + var o = a.name; + if (B2.contains(i, o)) { + var s = r.buildNamespaceConflictError(a); + n2.push({ message: s, type: Ie.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE, ruleName: o }); + } + }), n2; + } +}); +var Ui = R2((Je) => { + Object.defineProperty(Je, "__esModule", { value: true }); + Je.validateGrammar = Je.resolveGrammar = undefined; + var Vr = k2(), vs = mi(), ms = jr(), Di = mt(); + function Es(t2) { + t2 = Vr.defaults(t2, { errMsgProvider: Di.defaultGrammarResolverErrorProvider }); + var e = {}; + return Vr.forEach(t2.rules, function(r) { + e[r.name] = r; + }), vs.resolveGrammar(e, t2.errMsgProvider); + } + Je.resolveGrammar = Es; + function Ts(t2) { + return t2 = Vr.defaults(t2, { errMsgProvider: Di.defaultGrammarValidatorErrorProvider }), ms.validateGrammar(t2.rules, t2.maxLookahead, t2.tokenTypes, t2.errMsgProvider, t2.grammarName); + } + Je.validateGrammar = Ts; +}); +var et3 = R2((ae3) => { + var gt = ae3 && ae3.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(ae3, "__esModule", { value: true }); + ae3.EarlyExitException = ae3.NotAllInputParsedException = ae3.NoViableAltException = ae3.MismatchedTokenException = ae3.isRecognitionException = undefined; + var ys = k2(), Gi2 = "MismatchedTokenException", Wi3 = "NoViableAltException", Bi = "EarlyExitException", qi = "NotAllInputParsedException", ji = [Gi2, Wi3, Bi, qi]; + Object.freeze(ji); + function _s(t2) { + return ys.contains(ji, t2.name); + } + ae3.isRecognitionException = _s; + var zt = function(t2) { + gt(e, t2); + function e(r, n2) { + var i = this.constructor, a = t2.call(this, r) || this; + return a.token = n2, a.resyncedTokens = [], Object.setPrototypeOf(a, i.prototype), Error.captureStackTrace && Error.captureStackTrace(a, a.constructor), a; + } + return e; + }(Error), gs = function(t2) { + gt(e, t2); + function e(r, n2, i) { + var a = t2.call(this, r, n2) || this; + return a.previousToken = i, a.name = Gi2, a; + } + return e; + }(zt); + ae3.MismatchedTokenException = gs; + var As = function(t2) { + gt(e, t2); + function e(r, n2, i) { + var a = t2.call(this, r, n2) || this; + return a.previousToken = i, a.name = Wi3, a; + } + return e; + }(zt); + ae3.NoViableAltException = As; + var Rs = function(t2) { + gt(e, t2); + function e(r, n2) { + var i = t2.call(this, r, n2) || this; + return i.name = qi, i; + } + return e; + }(zt); + ae3.NotAllInputParsedException = Rs; + var Os = function(t2) { + gt(e, t2); + function e(r, n2, i) { + var a = t2.call(this, r, n2) || this; + return a.previousToken = i, a.name = Bi, a; + } + return e; + }(zt); + ae3.EarlyExitException = Os; +}); +var zr = R2(($2) => { + Object.defineProperty($2, "__esModule", { value: true }); + $2.attemptInRepetitionRecovery = $2.Recoverable = $2.InRuleRecoveryException = $2.IN_RULE_RECOVERY_EXCEPTION = $2.EOF_FOLLOW_KEY = undefined; + var Ht = Ue(), de = k2(), Ns = et3(), Is = Mr(), ks = ce2(); + $2.EOF_FOLLOW_KEY = {}; + $2.IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException"; + function Kr2(t2) { + this.name = $2.IN_RULE_RECOVERY_EXCEPTION, this.message = t2; + } + $2.InRuleRecoveryException = Kr2; + Kr2.prototype = Error.prototype; + var Ps = function() { + function t2() { + } + return t2.prototype.initRecoverable = function(e) { + this.firstAfterRepMap = {}, this.resyncFollows = {}, this.recoveryEnabled = de.has(e, "recoveryEnabled") ? e.recoveryEnabled : ks.DEFAULT_PARSER_CONFIG.recoveryEnabled, this.recoveryEnabled && (this.attemptInRepetitionRecovery = Vi); + }, t2.prototype.getTokenToInsert = function(e) { + var r = Ht.createTokenInstance(e, "", NaN, NaN, NaN, NaN, NaN, NaN); + return r.isInsertedInRecovery = true, r; + }, t2.prototype.canTokenTypeBeInsertedInRecovery = function(e) { + return true; + }, t2.prototype.tryInRepetitionRecovery = function(e, r, n2, i) { + for (var a = this, o = this.findReSyncTokenType(), s = this.exportLexerState(), c = [], f = false, p = this.LA(1), l2 = this.LA(1), m = function() { + var v = a.LA(0), u2 = a.errorMessageProvider.buildMismatchTokenMessage({ expected: i, actual: p, previous: v, ruleName: a.getCurrRuleFullName() }), d = new Ns.MismatchedTokenException(u2, p, a.LA(0)); + d.resyncedTokens = de.dropRight(c), a.SAVE_ERROR(d); + };!f; ) + if (this.tokenMatcher(l2, i)) { + m(); + return; + } else if (n2.call(this)) { + m(), e.apply(this, r); + return; + } else + this.tokenMatcher(l2, o) ? f = true : (l2 = this.SKIP_TOKEN(), this.addToResyncTokens(l2, c)); + this.importLexerState(s); + }, t2.prototype.shouldInRepetitionRecoveryBeTried = function(e, r, n2) { + return !(n2 === false || e === undefined || r === undefined || this.tokenMatcher(this.LA(1), e) || this.isBackTracking() || this.canPerformInRuleRecovery(e, this.getFollowsForInRuleRecovery(e, r))); + }, t2.prototype.getFollowsForInRuleRecovery = function(e, r) { + var n2 = this.getCurrentGrammarPath(e, r), i = this.getNextPossibleTokenTypes(n2); + return i; + }, t2.prototype.tryInRuleRecovery = function(e, r) { + if (this.canRecoverWithSingleTokenInsertion(e, r)) { + var n2 = this.getTokenToInsert(e); + return n2; + } + if (this.canRecoverWithSingleTokenDeletion(e)) { + var i = this.SKIP_TOKEN(); + return this.consumeToken(), i; + } + throw new Kr2("sad sad panda"); + }, t2.prototype.canPerformInRuleRecovery = function(e, r) { + return this.canRecoverWithSingleTokenInsertion(e, r) || this.canRecoverWithSingleTokenDeletion(e); + }, t2.prototype.canRecoverWithSingleTokenInsertion = function(e, r) { + var n2 = this; + if (!this.canTokenTypeBeInsertedInRecovery(e) || de.isEmpty(r)) + return false; + var i = this.LA(1), a = de.find(r, function(o) { + return n2.tokenMatcher(i, o); + }) !== undefined; + return a; + }, t2.prototype.canRecoverWithSingleTokenDeletion = function(e) { + var r = this.tokenMatcher(this.LA(2), e); + return r; + }, t2.prototype.isInCurrentRuleReSyncSet = function(e) { + var r = this.getCurrFollowKey(), n2 = this.getFollowSetFromFollowKey(r); + return de.contains(n2, e); + }, t2.prototype.findReSyncTokenType = function() { + for (var e = this.flattenFollowSet(), r = this.LA(1), n2 = 2;; ) { + var i = r.tokenType; + if (de.contains(e, i)) + return i; + r = this.LA(n2), n2++; + } + }, t2.prototype.getCurrFollowKey = function() { + if (this.RULE_STACK.length === 1) + return $2.EOF_FOLLOW_KEY; + var e = this.getLastExplicitRuleShortName(), r = this.getLastExplicitRuleOccurrenceIndex(), n2 = this.getPreviousExplicitRuleShortName(); + return { ruleName: this.shortRuleNameToFullName(e), idxInCallingRule: r, inRule: this.shortRuleNameToFullName(n2) }; + }, t2.prototype.buildFullFollowKeyStack = function() { + var e = this, r = this.RULE_STACK, n2 = this.RULE_OCCURRENCE_STACK; + return de.map(r, function(i, a) { + return a === 0 ? $2.EOF_FOLLOW_KEY : { ruleName: e.shortRuleNameToFullName(i), idxInCallingRule: n2[a], inRule: e.shortRuleNameToFullName(r[a - 1]) }; + }); + }, t2.prototype.flattenFollowSet = function() { + var e = this, r = de.map(this.buildFullFollowKeyStack(), function(n2) { + return e.getFollowSetFromFollowKey(n2); + }); + return de.flatten(r); + }, t2.prototype.getFollowSetFromFollowKey = function(e) { + if (e === $2.EOF_FOLLOW_KEY) + return [Ht.EOF]; + var r = e.ruleName + e.idxInCallingRule + Is.IN + e.inRule; + return this.resyncFollows[r]; + }, t2.prototype.addToResyncTokens = function(e, r) { + return this.tokenMatcher(e, Ht.EOF) || r.push(e), r; + }, t2.prototype.reSyncTo = function(e) { + for (var r = [], n2 = this.LA(1);this.tokenMatcher(n2, e) === false; ) + n2 = this.SKIP_TOKEN(), this.addToResyncTokens(n2, r); + return de.dropRight(r); + }, t2.prototype.attemptInRepetitionRecovery = function(e, r, n2, i, a, o, s) { + }, t2.prototype.getCurrentGrammarPath = function(e, r) { + var n2 = this.getHumanReadableRuleStack(), i = de.cloneArr(this.RULE_OCCURRENCE_STACK), a = { ruleStack: n2, occurrenceStack: i, lastTok: e, lastTokOccurrence: r }; + return a; + }, t2.prototype.getHumanReadableRuleStack = function() { + var e = this; + return de.map(this.RULE_STACK, function(r) { + return e.shortRuleNameToFullName(r); + }); + }, t2; + }(); + $2.Recoverable = Ps; + function Vi(t2, e, r, n2, i, a, o) { + var s = this.getKeyForAutomaticLookahead(n2, i), c = this.firstAfterRepMap[s]; + if (c === undefined) { + var f = this.getCurrRuleFullName(), p = this.getGAstProductions()[f], l2 = new a(p, i); + c = l2.startWalking(), this.firstAfterRepMap[s] = c; + } + var { token: m, occurrence: v, isEndOfRule: u2 } = c; + this.RULE_STACK.length === 1 && u2 && m === undefined && (m = Ht.EOF, v = 1), this.shouldInRepetitionRecoveryBeTried(m, v, o) && this.tryInRepetitionRecovery(t2, e, r, m); + } + $2.attemptInRepetitionRecovery = Vi; +}); +var Yt = R2((P) => { + Object.defineProperty(P, "__esModule", { value: true }); + P.getKeyForAutomaticLookahead = P.AT_LEAST_ONE_SEP_IDX = P.MANY_SEP_IDX = P.AT_LEAST_ONE_IDX = P.MANY_IDX = P.OPTION_IDX = P.OR_IDX = P.BITS_FOR_ALT_IDX = P.BITS_FOR_RULE_IDX = P.BITS_FOR_OCCURRENCE_IDX = P.BITS_FOR_METHOD_TYPE = undefined; + P.BITS_FOR_METHOD_TYPE = 4; + P.BITS_FOR_OCCURRENCE_IDX = 8; + P.BITS_FOR_RULE_IDX = 12; + P.BITS_FOR_ALT_IDX = 8; + P.OR_IDX = 1 << P.BITS_FOR_OCCURRENCE_IDX; + P.OPTION_IDX = 2 << P.BITS_FOR_OCCURRENCE_IDX; + P.MANY_IDX = 3 << P.BITS_FOR_OCCURRENCE_IDX; + P.AT_LEAST_ONE_IDX = 4 << P.BITS_FOR_OCCURRENCE_IDX; + P.MANY_SEP_IDX = 5 << P.BITS_FOR_OCCURRENCE_IDX; + P.AT_LEAST_ONE_SEP_IDX = 6 << P.BITS_FOR_OCCURRENCE_IDX; + function Ss(t2, e, r) { + return r | e | t2; + } + P.getKeyForAutomaticLookahead = Ss; + var ic = 32 - P.BITS_FOR_ALT_IDX; +}); +var zi = R2((Xt) => { + Object.defineProperty(Xt, "__esModule", { value: true }); + Xt.LooksAhead = undefined; + var be = yt2(), ge2 = k2(), Ki = ce2(), Fe = Yt(), Ve = vt(), xs = function() { + function t2() { + } + return t2.prototype.initLooksAhead = function(e) { + this.dynamicTokensEnabled = ge2.has(e, "dynamicTokensEnabled") ? e.dynamicTokensEnabled : Ki.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled, this.maxLookahead = ge2.has(e, "maxLookahead") ? e.maxLookahead : Ki.DEFAULT_PARSER_CONFIG.maxLookahead, this.lookAheadFuncsCache = ge2.isES2015MapSupported() ? new Map : [], ge2.isES2015MapSupported() ? (this.getLaFuncFromCache = this.getLaFuncFromMap, this.setLaFuncCache = this.setLaFuncCacheUsingMap) : (this.getLaFuncFromCache = this.getLaFuncFromObj, this.setLaFuncCache = this.setLaFuncUsingObj); + }, t2.prototype.preComputeLookaheadFunctions = function(e) { + var r = this; + ge2.forEach(e, function(n2) { + r.TRACE_INIT(n2.name + " Rule Lookahead", function() { + var i = Ve.collectMethods(n2), a = i.alternation, o = i.repetition, s = i.option, c = i.repetitionMandatory, f = i.repetitionMandatoryWithSeparator, p = i.repetitionWithSeparator; + ge2.forEach(a, function(l2) { + var m = l2.idx === 0 ? "" : l2.idx; + r.TRACE_INIT("" + Ve.getProductionDslName(l2) + m, function() { + var v = be.buildLookaheadFuncForOr(l2.idx, n2, l2.maxLookahead || r.maxLookahead, l2.hasPredicates, r.dynamicTokensEnabled, r.lookAheadBuilderForAlternatives), u2 = Fe.getKeyForAutomaticLookahead(r.fullRuleNameToShort[n2.name], Fe.OR_IDX, l2.idx); + r.setLaFuncCache(u2, v); + }); + }), ge2.forEach(o, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.MANY_IDX, be.PROD_TYPE.REPETITION, l2.maxLookahead, Ve.getProductionDslName(l2)); + }), ge2.forEach(s, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.OPTION_IDX, be.PROD_TYPE.OPTION, l2.maxLookahead, Ve.getProductionDslName(l2)); + }), ge2.forEach(c, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.AT_LEAST_ONE_IDX, be.PROD_TYPE.REPETITION_MANDATORY, l2.maxLookahead, Ve.getProductionDslName(l2)); + }), ge2.forEach(f, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.AT_LEAST_ONE_SEP_IDX, be.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, l2.maxLookahead, Ve.getProductionDslName(l2)); + }), ge2.forEach(p, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.MANY_SEP_IDX, be.PROD_TYPE.REPETITION_WITH_SEPARATOR, l2.maxLookahead, Ve.getProductionDslName(l2)); + }); + }); + }); + }, t2.prototype.computeLookaheadFunc = function(e, r, n2, i, a, o) { + var s = this; + this.TRACE_INIT("" + o + (r === 0 ? "" : r), function() { + var c = be.buildLookaheadFuncForOptionalProd(r, e, a || s.maxLookahead, s.dynamicTokensEnabled, i, s.lookAheadBuilderForOptional), f = Fe.getKeyForAutomaticLookahead(s.fullRuleNameToShort[e.name], n2, r); + s.setLaFuncCache(f, c); + }); + }, t2.prototype.lookAheadBuilderForOptional = function(e, r, n2) { + return be.buildSingleAlternativeLookaheadFunction(e, r, n2); + }, t2.prototype.lookAheadBuilderForAlternatives = function(e, r, n2, i) { + return be.buildAlternativesLookAheadFunc(e, r, n2, i); + }, t2.prototype.getKeyForAutomaticLookahead = function(e, r) { + var n2 = this.getLastExplicitRuleShortName(); + return Fe.getKeyForAutomaticLookahead(n2, e, r); + }, t2.prototype.getLaFuncFromCache = function(e) { + }, t2.prototype.getLaFuncFromMap = function(e) { + return this.lookAheadFuncsCache.get(e); + }, t2.prototype.getLaFuncFromObj = function(e) { + return this.lookAheadFuncsCache[e]; + }, t2.prototype.setLaFuncCache = function(e, r) { + }, t2.prototype.setLaFuncCacheUsingMap = function(e, r) { + this.lookAheadFuncsCache.set(e, r); + }, t2.prototype.setLaFuncUsingObj = function(e, r) { + this.lookAheadFuncsCache[e] = r; + }, t2; + }(); + Xt.LooksAhead = xs; +}); +var Hi = R2((ke) => { + Object.defineProperty(ke, "__esModule", { value: true }); + ke.addNoneTerminalToCst = ke.addTerminalToCst = ke.setNodeLocationFull = ke.setNodeLocationOnlyOffset = undefined; + function Cs(t2, e) { + isNaN(t2.startOffset) === true ? (t2.startOffset = e.startOffset, t2.endOffset = e.endOffset) : t2.endOffset < e.endOffset && (t2.endOffset = e.endOffset); + } + ke.setNodeLocationOnlyOffset = Cs; + function Ls(t2, e) { + isNaN(t2.startOffset) === true ? (t2.startOffset = e.startOffset, t2.startColumn = e.startColumn, t2.startLine = e.startLine, t2.endOffset = e.endOffset, t2.endColumn = e.endColumn, t2.endLine = e.endLine) : t2.endOffset < e.endOffset && (t2.endOffset = e.endOffset, t2.endColumn = e.endColumn, t2.endLine = e.endLine); + } + ke.setNodeLocationFull = Ls; + function Ms(t2, e, r) { + t2.children[r] === undefined ? t2.children[r] = [e] : t2.children[r].push(e); + } + ke.addTerminalToCst = Ms; + function bs(t2, e, r) { + t2.children[e] === undefined ? t2.children[e] = [r] : t2.children[e].push(r); + } + ke.addNoneTerminalToCst = bs; +}); +var Hr = R2((Be) => { + Object.defineProperty(Be, "__esModule", { value: true }); + Be.defineNameProp = Be.functionName = Be.classNameFromInstance = undefined; + var Fs = k2(); + function ws(t2) { + return Yi(t2.constructor); + } + Be.classNameFromInstance = ws; + var Xi = "name"; + function Yi(t2) { + var e = t2.name; + return e || "anonymous"; + } + Be.functionName = Yi; + function Ds(t2, e) { + var r = Object.getOwnPropertyDescriptor(t2, Xi); + return Fs.isUndefined(r) || r.configurable ? (Object.defineProperty(t2, Xi, { enumerable: false, configurable: true, writable: false, value: e }), true) : false; + } + Be.defineNameProp = Ds; +}); +var ea = R2((Y) => { + Object.defineProperty(Y, "__esModule", { value: true }); + Y.validateRedundantMethods = Y.validateMissingCstMethods = Y.validateVisitor = Y.CstVisitorDefinitionError = Y.createBaseVisitorConstructorWithDefaults = Y.createBaseSemanticVisitorConstructor = Y.defaultVisit = undefined; + var ve = k2(), At2 = Hr(); + function $i(t2, e) { + for (var r = ve.keys(t2), n2 = r.length, i = 0;i < n2; i++) + for (var a = r[i], o = t2[a], s = o.length, c = 0;c < s; c++) { + var f = o[c]; + f.tokenTypeIdx === undefined && this[f.name](f.children, e); + } + } + Y.defaultVisit = $i; + function Us(t2, e) { + var r = function() { + }; + At2.defineNameProp(r, t2 + "BaseSemantics"); + var n2 = { visit: function(i, a) { + if (ve.isArray(i) && (i = i[0]), !ve.isUndefined(i)) + return this[i.name](i.children, a); + }, validateVisitor: function() { + var i = Zi(this, e); + if (!ve.isEmpty(i)) { + var a = ve.map(i, function(o) { + return o.msg; + }); + throw Error("Errors Detected in CST Visitor <" + At2.functionName(this.constructor) + `>: + ` + ("" + a.join(` + +`).replace(/\n/g, ` + `))); + } + } }; + return r.prototype = n2, r.prototype.constructor = r, r._RULE_NAMES = e, r; + } + Y.createBaseSemanticVisitorConstructor = Us; + function Gs(t2, e, r) { + var n2 = function() { + }; + At2.defineNameProp(n2, t2 + "BaseSemanticsWithDefaults"); + var i = Object.create(r.prototype); + return ve.forEach(e, function(a) { + i[a] = $i; + }), n2.prototype = i, n2.prototype.constructor = n2, n2; + } + Y.createBaseVisitorConstructorWithDefaults = Gs; + var Yr; + (function(t2) { + t2[t2.REDUNDANT_METHOD = 0] = "REDUNDANT_METHOD", t2[t2.MISSING_METHOD = 1] = "MISSING_METHOD"; + })(Yr = Y.CstVisitorDefinitionError || (Y.CstVisitorDefinitionError = {})); + function Zi(t2, e) { + var r = Qi(t2, e), n2 = Ji(t2, e); + return r.concat(n2); + } + Y.validateVisitor = Zi; + function Qi(t2, e) { + var r = ve.map(e, function(n2) { + if (!ve.isFunction(t2[n2])) + return { msg: "Missing visitor method: <" + n2 + "> on " + At2.functionName(t2.constructor) + " CST Visitor.", type: Yr.MISSING_METHOD, methodName: n2 }; + }); + return ve.compact(r); + } + Y.validateMissingCstMethods = Qi; + var Ws = ["constructor", "visit", "validateVisitor"]; + function Ji(t2, e) { + var r = []; + for (var n2 in t2) + ve.isFunction(t2[n2]) && !ve.contains(Ws, n2) && !ve.contains(e, n2) && r.push({ msg: "Redundant visitor method: <" + n2 + "> on " + At2.functionName(t2.constructor) + ` CST Visitor +There is no Grammar Rule corresponding to this method's name. +`, type: Yr.REDUNDANT_METHOD, methodName: n2 }); + return r; + } + Y.validateRedundantMethods = Ji; +}); +var ra = R2(($t) => { + Object.defineProperty($t, "__esModule", { value: true }); + $t.TreeBuilder = undefined; + var tt3 = Hi(), K = k2(), ta = ea(), Bs = ce2(), qs = function() { + function t2() { + } + return t2.prototype.initTreeBuilder = function(e) { + if (this.CST_STACK = [], this.outputCst = e.outputCst, this.nodeLocationTracking = K.has(e, "nodeLocationTracking") ? e.nodeLocationTracking : Bs.DEFAULT_PARSER_CONFIG.nodeLocationTracking, !this.outputCst) + this.cstInvocationStateUpdate = K.NOOP, this.cstFinallyStateUpdate = K.NOOP, this.cstPostTerminal = K.NOOP, this.cstPostNonTerminal = K.NOOP, this.cstPostRule = K.NOOP; + else if (/full/i.test(this.nodeLocationTracking)) + this.recoveryEnabled ? (this.setNodeLocationFromToken = tt3.setNodeLocationFull, this.setNodeLocationFromNode = tt3.setNodeLocationFull, this.cstPostRule = K.NOOP, this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery) : (this.setNodeLocationFromToken = K.NOOP, this.setNodeLocationFromNode = K.NOOP, this.cstPostRule = this.cstPostRuleFull, this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular); + else if (/onlyOffset/i.test(this.nodeLocationTracking)) + this.recoveryEnabled ? (this.setNodeLocationFromToken = tt3.setNodeLocationOnlyOffset, this.setNodeLocationFromNode = tt3.setNodeLocationOnlyOffset, this.cstPostRule = K.NOOP, this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery) : (this.setNodeLocationFromToken = K.NOOP, this.setNodeLocationFromNode = K.NOOP, this.cstPostRule = this.cstPostRuleOnlyOffset, this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular); + else if (/none/i.test(this.nodeLocationTracking)) + this.setNodeLocationFromToken = K.NOOP, this.setNodeLocationFromNode = K.NOOP, this.cstPostRule = K.NOOP, this.setInitialNodeLocation = K.NOOP; + else + throw Error('Invalid config option: "' + e.nodeLocationTracking + '"'); + }, t2.prototype.setInitialNodeLocationOnlyOffsetRecovery = function(e) { + e.location = { startOffset: NaN, endOffset: NaN }; + }, t2.prototype.setInitialNodeLocationOnlyOffsetRegular = function(e) { + e.location = { startOffset: this.LA(1).startOffset, endOffset: NaN }; + }, t2.prototype.setInitialNodeLocationFullRecovery = function(e) { + e.location = { startOffset: NaN, startLine: NaN, startColumn: NaN, endOffset: NaN, endLine: NaN, endColumn: NaN }; + }, t2.prototype.setInitialNodeLocationFullRegular = function(e) { + var r = this.LA(1); + e.location = { startOffset: r.startOffset, startLine: r.startLine, startColumn: r.startColumn, endOffset: NaN, endLine: NaN, endColumn: NaN }; + }, t2.prototype.cstInvocationStateUpdate = function(e, r) { + var n2 = { name: e, children: {} }; + this.setInitialNodeLocation(n2), this.CST_STACK.push(n2); + }, t2.prototype.cstFinallyStateUpdate = function() { + this.CST_STACK.pop(); + }, t2.prototype.cstPostRuleFull = function(e) { + var r = this.LA(0), n2 = e.location; + n2.startOffset <= r.startOffset ? (n2.endOffset = r.endOffset, n2.endLine = r.endLine, n2.endColumn = r.endColumn) : (n2.startOffset = NaN, n2.startLine = NaN, n2.startColumn = NaN); + }, t2.prototype.cstPostRuleOnlyOffset = function(e) { + var r = this.LA(0), n2 = e.location; + n2.startOffset <= r.startOffset ? n2.endOffset = r.endOffset : n2.startOffset = NaN; + }, t2.prototype.cstPostTerminal = function(e, r) { + var n2 = this.CST_STACK[this.CST_STACK.length - 1]; + tt3.addTerminalToCst(n2, r, e), this.setNodeLocationFromToken(n2.location, r); + }, t2.prototype.cstPostNonTerminal = function(e, r) { + var n2 = this.CST_STACK[this.CST_STACK.length - 1]; + tt3.addNoneTerminalToCst(n2, r, e), this.setNodeLocationFromNode(n2.location, e.location); + }, t2.prototype.getBaseCstVisitorConstructor = function() { + if (K.isUndefined(this.baseCstVisitorConstructor)) { + var e = ta.createBaseSemanticVisitorConstructor(this.className, K.keys(this.gastProductionsCache)); + return this.baseCstVisitorConstructor = e, e; + } + return this.baseCstVisitorConstructor; + }, t2.prototype.getBaseCstVisitorConstructorWithDefaults = function() { + if (K.isUndefined(this.baseCstVisitorWithDefaultsConstructor)) { + var e = ta.createBaseVisitorConstructorWithDefaults(this.className, K.keys(this.gastProductionsCache), this.getBaseCstVisitorConstructor()); + return this.baseCstVisitorWithDefaultsConstructor = e, e; + } + return this.baseCstVisitorWithDefaultsConstructor; + }, t2.prototype.getLastExplicitRuleShortName = function() { + var e = this.RULE_STACK; + return e[e.length - 1]; + }, t2.prototype.getPreviousExplicitRuleShortName = function() { + var e = this.RULE_STACK; + return e[e.length - 2]; + }, t2.prototype.getLastExplicitRuleOccurrenceIndex = function() { + var e = this.RULE_OCCURRENCE_STACK; + return e[e.length - 1]; + }, t2; + }(); + $t.TreeBuilder = qs; +}); +var ia = R2((Zt) => { + Object.defineProperty(Zt, "__esModule", { value: true }); + Zt.LexerAdapter = undefined; + var na = ce2(), js = function() { + function t2() { + } + return t2.prototype.initLexerAdapter = function() { + this.tokVector = [], this.tokVectorLength = 0, this.currIdx = -1; + }, Object.defineProperty(t2.prototype, "input", { get: function() { + return this.tokVector; + }, set: function(e) { + if (this.selfAnalysisDone !== true) + throw Error("Missing invocation at the end of the Parser's constructor."); + this.reset(), this.tokVector = e, this.tokVectorLength = e.length; + }, enumerable: false, configurable: true }), t2.prototype.SKIP_TOKEN = function() { + return this.currIdx <= this.tokVector.length - 2 ? (this.consumeToken(), this.LA(1)) : na.END_OF_FILE; + }, t2.prototype.LA = function(e) { + var r = this.currIdx + e; + return r < 0 || this.tokVectorLength <= r ? na.END_OF_FILE : this.tokVector[r]; + }, t2.prototype.consumeToken = function() { + this.currIdx++; + }, t2.prototype.exportLexerState = function() { + return this.currIdx; + }, t2.prototype.importLexerState = function(e) { + this.currIdx = e; + }, t2.prototype.resetLexerState = function() { + this.currIdx = -1; + }, t2.prototype.moveToTerminatedState = function() { + this.currIdx = this.tokVector.length - 1; + }, t2.prototype.getLexerPosition = function() { + return this.exportLexerState(); + }, t2; + }(); + Zt.LexerAdapter = js; +}); +var oa = R2((Qt) => { + Object.defineProperty(Qt, "__esModule", { value: true }); + Qt.RecognizerApi = undefined; + var aa = k2(), Vs = et3(), Xr = ce2(), Ks = mt(), zs = jr(), Hs = ne(), Ys = function() { + function t2() { + } + return t2.prototype.ACTION = function(e) { + return e.call(this); + }, t2.prototype.consume = function(e, r, n2) { + return this.consumeInternal(r, e, n2); + }, t2.prototype.subrule = function(e, r, n2) { + return this.subruleInternal(r, e, n2); + }, t2.prototype.option = function(e, r) { + return this.optionInternal(r, e); + }, t2.prototype.or = function(e, r) { + return this.orInternal(r, e); + }, t2.prototype.many = function(e, r) { + return this.manyInternal(e, r); + }, t2.prototype.atLeastOne = function(e, r) { + return this.atLeastOneInternal(e, r); + }, t2.prototype.CONSUME = function(e, r) { + return this.consumeInternal(e, 0, r); + }, t2.prototype.CONSUME1 = function(e, r) { + return this.consumeInternal(e, 1, r); + }, t2.prototype.CONSUME2 = function(e, r) { + return this.consumeInternal(e, 2, r); + }, t2.prototype.CONSUME3 = function(e, r) { + return this.consumeInternal(e, 3, r); + }, t2.prototype.CONSUME4 = function(e, r) { + return this.consumeInternal(e, 4, r); + }, t2.prototype.CONSUME5 = function(e, r) { + return this.consumeInternal(e, 5, r); + }, t2.prototype.CONSUME6 = function(e, r) { + return this.consumeInternal(e, 6, r); + }, t2.prototype.CONSUME7 = function(e, r) { + return this.consumeInternal(e, 7, r); + }, t2.prototype.CONSUME8 = function(e, r) { + return this.consumeInternal(e, 8, r); + }, t2.prototype.CONSUME9 = function(e, r) { + return this.consumeInternal(e, 9, r); + }, t2.prototype.SUBRULE = function(e, r) { + return this.subruleInternal(e, 0, r); + }, t2.prototype.SUBRULE1 = function(e, r) { + return this.subruleInternal(e, 1, r); + }, t2.prototype.SUBRULE2 = function(e, r) { + return this.subruleInternal(e, 2, r); + }, t2.prototype.SUBRULE3 = function(e, r) { + return this.subruleInternal(e, 3, r); + }, t2.prototype.SUBRULE4 = function(e, r) { + return this.subruleInternal(e, 4, r); + }, t2.prototype.SUBRULE5 = function(e, r) { + return this.subruleInternal(e, 5, r); + }, t2.prototype.SUBRULE6 = function(e, r) { + return this.subruleInternal(e, 6, r); + }, t2.prototype.SUBRULE7 = function(e, r) { + return this.subruleInternal(e, 7, r); + }, t2.prototype.SUBRULE8 = function(e, r) { + return this.subruleInternal(e, 8, r); + }, t2.prototype.SUBRULE9 = function(e, r) { + return this.subruleInternal(e, 9, r); + }, t2.prototype.OPTION = function(e) { + return this.optionInternal(e, 0); + }, t2.prototype.OPTION1 = function(e) { + return this.optionInternal(e, 1); + }, t2.prototype.OPTION2 = function(e) { + return this.optionInternal(e, 2); + }, t2.prototype.OPTION3 = function(e) { + return this.optionInternal(e, 3); + }, t2.prototype.OPTION4 = function(e) { + return this.optionInternal(e, 4); + }, t2.prototype.OPTION5 = function(e) { + return this.optionInternal(e, 5); + }, t2.prototype.OPTION6 = function(e) { + return this.optionInternal(e, 6); + }, t2.prototype.OPTION7 = function(e) { + return this.optionInternal(e, 7); + }, t2.prototype.OPTION8 = function(e) { + return this.optionInternal(e, 8); + }, t2.prototype.OPTION9 = function(e) { + return this.optionInternal(e, 9); + }, t2.prototype.OR = function(e) { + return this.orInternal(e, 0); + }, t2.prototype.OR1 = function(e) { + return this.orInternal(e, 1); + }, t2.prototype.OR2 = function(e) { + return this.orInternal(e, 2); + }, t2.prototype.OR3 = function(e) { + return this.orInternal(e, 3); + }, t2.prototype.OR4 = function(e) { + return this.orInternal(e, 4); + }, t2.prototype.OR5 = function(e) { + return this.orInternal(e, 5); + }, t2.prototype.OR6 = function(e) { + return this.orInternal(e, 6); + }, t2.prototype.OR7 = function(e) { + return this.orInternal(e, 7); + }, t2.prototype.OR8 = function(e) { + return this.orInternal(e, 8); + }, t2.prototype.OR9 = function(e) { + return this.orInternal(e, 9); + }, t2.prototype.MANY = function(e) { + this.manyInternal(0, e); + }, t2.prototype.MANY1 = function(e) { + this.manyInternal(1, e); + }, t2.prototype.MANY2 = function(e) { + this.manyInternal(2, e); + }, t2.prototype.MANY3 = function(e) { + this.manyInternal(3, e); + }, t2.prototype.MANY4 = function(e) { + this.manyInternal(4, e); + }, t2.prototype.MANY5 = function(e) { + this.manyInternal(5, e); + }, t2.prototype.MANY6 = function(e) { + this.manyInternal(6, e); + }, t2.prototype.MANY7 = function(e) { + this.manyInternal(7, e); + }, t2.prototype.MANY8 = function(e) { + this.manyInternal(8, e); + }, t2.prototype.MANY9 = function(e) { + this.manyInternal(9, e); + }, t2.prototype.MANY_SEP = function(e) { + this.manySepFirstInternal(0, e); + }, t2.prototype.MANY_SEP1 = function(e) { + this.manySepFirstInternal(1, e); + }, t2.prototype.MANY_SEP2 = function(e) { + this.manySepFirstInternal(2, e); + }, t2.prototype.MANY_SEP3 = function(e) { + this.manySepFirstInternal(3, e); + }, t2.prototype.MANY_SEP4 = function(e) { + this.manySepFirstInternal(4, e); + }, t2.prototype.MANY_SEP5 = function(e) { + this.manySepFirstInternal(5, e); + }, t2.prototype.MANY_SEP6 = function(e) { + this.manySepFirstInternal(6, e); + }, t2.prototype.MANY_SEP7 = function(e) { + this.manySepFirstInternal(7, e); + }, t2.prototype.MANY_SEP8 = function(e) { + this.manySepFirstInternal(8, e); + }, t2.prototype.MANY_SEP9 = function(e) { + this.manySepFirstInternal(9, e); + }, t2.prototype.AT_LEAST_ONE = function(e) { + this.atLeastOneInternal(0, e); + }, t2.prototype.AT_LEAST_ONE1 = function(e) { + return this.atLeastOneInternal(1, e); + }, t2.prototype.AT_LEAST_ONE2 = function(e) { + this.atLeastOneInternal(2, e); + }, t2.prototype.AT_LEAST_ONE3 = function(e) { + this.atLeastOneInternal(3, e); + }, t2.prototype.AT_LEAST_ONE4 = function(e) { + this.atLeastOneInternal(4, e); + }, t2.prototype.AT_LEAST_ONE5 = function(e) { + this.atLeastOneInternal(5, e); + }, t2.prototype.AT_LEAST_ONE6 = function(e) { + this.atLeastOneInternal(6, e); + }, t2.prototype.AT_LEAST_ONE7 = function(e) { + this.atLeastOneInternal(7, e); + }, t2.prototype.AT_LEAST_ONE8 = function(e) { + this.atLeastOneInternal(8, e); + }, t2.prototype.AT_LEAST_ONE9 = function(e) { + this.atLeastOneInternal(9, e); + }, t2.prototype.AT_LEAST_ONE_SEP = function(e) { + this.atLeastOneSepFirstInternal(0, e); + }, t2.prototype.AT_LEAST_ONE_SEP1 = function(e) { + this.atLeastOneSepFirstInternal(1, e); + }, t2.prototype.AT_LEAST_ONE_SEP2 = function(e) { + this.atLeastOneSepFirstInternal(2, e); + }, t2.prototype.AT_LEAST_ONE_SEP3 = function(e) { + this.atLeastOneSepFirstInternal(3, e); + }, t2.prototype.AT_LEAST_ONE_SEP4 = function(e) { + this.atLeastOneSepFirstInternal(4, e); + }, t2.prototype.AT_LEAST_ONE_SEP5 = function(e) { + this.atLeastOneSepFirstInternal(5, e); + }, t2.prototype.AT_LEAST_ONE_SEP6 = function(e) { + this.atLeastOneSepFirstInternal(6, e); + }, t2.prototype.AT_LEAST_ONE_SEP7 = function(e) { + this.atLeastOneSepFirstInternal(7, e); + }, t2.prototype.AT_LEAST_ONE_SEP8 = function(e) { + this.atLeastOneSepFirstInternal(8, e); + }, t2.prototype.AT_LEAST_ONE_SEP9 = function(e) { + this.atLeastOneSepFirstInternal(9, e); + }, t2.prototype.RULE = function(e, r, n2) { + if (n2 === undefined && (n2 = Xr.DEFAULT_RULE_CONFIG), aa.contains(this.definedRulesNames, e)) { + var i = Ks.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({ topLevelRule: e, grammarName: this.className }), a = { message: i, type: Xr.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, ruleName: e }; + this.definitionErrors.push(a); + } + this.definedRulesNames.push(e); + var o = this.defineRule(e, r, n2); + return this[e] = o, o; + }, t2.prototype.OVERRIDE_RULE = function(e, r, n2) { + n2 === undefined && (n2 = Xr.DEFAULT_RULE_CONFIG); + var i = []; + i = i.concat(zs.validateRuleIsOverridden(e, this.definedRulesNames, this.className)), this.definitionErrors = this.definitionErrors.concat(i); + var a = this.defineRule(e, r, n2); + return this[e] = a, a; + }, t2.prototype.BACKTRACK = function(e, r) { + return function() { + this.isBackTrackingStack.push(1); + var n2 = this.saveRecogState(); + try { + return e.apply(this, r), true; + } catch (i) { + if (Vs.isRecognitionException(i)) + return false; + throw i; + } finally { + this.reloadRecogState(n2), this.isBackTrackingStack.pop(); + } + }; + }, t2.prototype.getGAstProductions = function() { + return this.gastProductionsCache; + }, t2.prototype.getSerializedGastProductions = function() { + return Hs.serializeGrammar(aa.values(this.gastProductionsCache)); + }, t2; + }(); + Qt.RecognizerApi = Ys; +}); +var la = R2((Jt) => { + Object.defineProperty(Jt, "__esModule", { value: true }); + Jt.RecognizerEngine = undefined; + var q2 = k2(), le = Yt(), er = et3(), sa = yt2(), rt2 = Tt2(), ua = ce2(), Xs = zr(), ca = Ue(), Rt = Xe(), $s = Hr(), Zs = function() { + function t2() { + } + return t2.prototype.initRecognizerEngine = function(e, r) { + if (this.className = $s.classNameFromInstance(this), this.shortRuleNameToFull = {}, this.fullRuleNameToShort = {}, this.ruleShortNameIdx = 256, this.tokenMatcher = Rt.tokenStructuredMatcherNoCategories, this.definedRulesNames = [], this.tokensMap = {}, this.isBackTrackingStack = [], this.RULE_STACK = [], this.RULE_OCCURRENCE_STACK = [], this.gastProductionsCache = {}, q2.has(r, "serializedGrammar")) + throw Error(`The Parser's configuration can no longer contain a property. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 + For Further details.`); + if (q2.isArray(e)) { + if (q2.isEmpty(e)) + throw Error(`A Token Vocabulary cannot be empty. + Note that the first argument for the parser constructor + is no longer a Token vector (since v4.0).`); + if (typeof e[0].startOffset == "number") + throw Error(`The Parser constructor no longer accepts a token vector as the first argument. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 + For Further details.`); + } + if (q2.isArray(e)) + this.tokensMap = q2.reduce(e, function(o, s) { + return o[s.name] = s, o; + }, {}); + else if (q2.has(e, "modes") && q2.every(q2.flatten(q2.values(e.modes)), Rt.isTokenType)) { + var n2 = q2.flatten(q2.values(e.modes)), i = q2.uniq(n2); + this.tokensMap = q2.reduce(i, function(o, s) { + return o[s.name] = s, o; + }, {}); + } else if (q2.isObject(e)) + this.tokensMap = q2.cloneObj(e); + else + throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition"); + this.tokensMap.EOF = ca.EOF; + var a = q2.every(q2.values(e), function(o) { + return q2.isEmpty(o.categoryMatches); + }); + this.tokenMatcher = a ? Rt.tokenStructuredMatcherNoCategories : Rt.tokenStructuredMatcher, Rt.augmentTokenTypes(q2.values(this.tokensMap)); + }, t2.prototype.defineRule = function(e, r, n2) { + if (this.selfAnalysisDone) + throw Error("Grammar rule <" + e + `> may not be defined after the 'performSelfAnalysis' method has been called' +Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`); + var i = q2.has(n2, "resyncEnabled") ? n2.resyncEnabled : ua.DEFAULT_RULE_CONFIG.resyncEnabled, a = q2.has(n2, "recoveryValueFunc") ? n2.recoveryValueFunc : ua.DEFAULT_RULE_CONFIG.recoveryValueFunc, o = this.ruleShortNameIdx << le.BITS_FOR_METHOD_TYPE + le.BITS_FOR_OCCURRENCE_IDX; + this.ruleShortNameIdx++, this.shortRuleNameToFull[o] = e, this.fullRuleNameToShort[e] = o; + function s(p) { + try { + if (this.outputCst === true) { + r.apply(this, p); + var l2 = this.CST_STACK[this.CST_STACK.length - 1]; + return this.cstPostRule(l2), l2; + } else + return r.apply(this, p); + } catch (m) { + return this.invokeRuleCatch(m, i, a); + } finally { + this.ruleFinallyStateUpdate(); + } + } + var c = function(p, l2) { + return p === undefined && (p = 0), this.ruleInvocationStateUpdate(o, e, p), s.call(this, l2); + }, f = "ruleName"; + return c[f] = e, c.originalGrammarAction = r, c; + }, t2.prototype.invokeRuleCatch = function(e, r, n2) { + var i = this.RULE_STACK.length === 1, a = r && !this.isBackTracking() && this.recoveryEnabled; + if (er.isRecognitionException(e)) { + var o = e; + if (a) { + var s = this.findReSyncTokenType(); + if (this.isInCurrentRuleReSyncSet(s)) + if (o.resyncedTokens = this.reSyncTo(s), this.outputCst) { + var c = this.CST_STACK[this.CST_STACK.length - 1]; + return c.recoveredNode = true, c; + } else + return n2(); + else { + if (this.outputCst) { + var c = this.CST_STACK[this.CST_STACK.length - 1]; + c.recoveredNode = true, o.partialCstResult = c; + } + throw o; + } + } else { + if (i) + return this.moveToTerminatedState(), n2(); + throw o; + } + } else + throw e; + }, t2.prototype.optionInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.OPTION_IDX, r); + return this.optionInternalLogic(e, r, n2); + }, t2.prototype.optionInternalLogic = function(e, r, n2) { + var i = this, a = this.getLaFuncFromCache(n2), o, s; + if (e.DEF !== undefined) { + if (o = e.DEF, s = e.GATE, s !== undefined) { + var c = a; + a = function() { + return s.call(i) && c.call(i); + }; + } + } else + o = e; + if (a.call(this) === true) + return o.call(this); + }, t2.prototype.atLeastOneInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.AT_LEAST_ONE_IDX, e); + return this.atLeastOneInternalLogic(e, r, n2); + }, t2.prototype.atLeastOneInternalLogic = function(e, r, n2) { + var i = this, a = this.getLaFuncFromCache(n2), o, s; + if (r.DEF !== undefined) { + if (o = r.DEF, s = r.GATE, s !== undefined) { + var c = a; + a = function() { + return s.call(i) && c.call(i); + }; + } + } else + o = r; + if (a.call(this) === true) + for (var f = this.doSingleRepetition(o);a.call(this) === true && f === true; ) + f = this.doSingleRepetition(o); + else + throw this.raiseEarlyExitException(e, sa.PROD_TYPE.REPETITION_MANDATORY, r.ERR_MSG); + this.attemptInRepetitionRecovery(this.atLeastOneInternal, [e, r], a, le.AT_LEAST_ONE_IDX, e, rt2.NextTerminalAfterAtLeastOneWalker); + }, t2.prototype.atLeastOneSepFirstInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.AT_LEAST_ONE_SEP_IDX, e); + this.atLeastOneSepFirstInternalLogic(e, r, n2); + }, t2.prototype.atLeastOneSepFirstInternalLogic = function(e, r, n2) { + var i = this, a = r.DEF, o = r.SEP, s = this.getLaFuncFromCache(n2); + if (s.call(this) === true) { + a.call(this); + for (var c = function() { + return i.tokenMatcher(i.LA(1), o); + };this.tokenMatcher(this.LA(1), o) === true; ) + this.CONSUME(o), a.call(this); + this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [e, o, c, a, rt2.NextTerminalAfterAtLeastOneSepWalker], c, le.AT_LEAST_ONE_SEP_IDX, e, rt2.NextTerminalAfterAtLeastOneSepWalker); + } else + throw this.raiseEarlyExitException(e, sa.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, r.ERR_MSG); + }, t2.prototype.manyInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.MANY_IDX, e); + return this.manyInternalLogic(e, r, n2); + }, t2.prototype.manyInternalLogic = function(e, r, n2) { + var i = this, a = this.getLaFuncFromCache(n2), o, s; + if (r.DEF !== undefined) { + if (o = r.DEF, s = r.GATE, s !== undefined) { + var c = a; + a = function() { + return s.call(i) && c.call(i); + }; + } + } else + o = r; + for (var f = true;a.call(this) === true && f === true; ) + f = this.doSingleRepetition(o); + this.attemptInRepetitionRecovery(this.manyInternal, [e, r], a, le.MANY_IDX, e, rt2.NextTerminalAfterManyWalker, f); + }, t2.prototype.manySepFirstInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.MANY_SEP_IDX, e); + this.manySepFirstInternalLogic(e, r, n2); + }, t2.prototype.manySepFirstInternalLogic = function(e, r, n2) { + var i = this, a = r.DEF, o = r.SEP, s = this.getLaFuncFromCache(n2); + if (s.call(this) === true) { + a.call(this); + for (var c = function() { + return i.tokenMatcher(i.LA(1), o); + };this.tokenMatcher(this.LA(1), o) === true; ) + this.CONSUME(o), a.call(this); + this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [e, o, c, a, rt2.NextTerminalAfterManySepWalker], c, le.MANY_SEP_IDX, e, rt2.NextTerminalAfterManySepWalker); + } + }, t2.prototype.repetitionSepSecondInternal = function(e, r, n2, i, a) { + for (;n2(); ) + this.CONSUME(r), i.call(this); + this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [e, r, n2, i, a], n2, le.AT_LEAST_ONE_SEP_IDX, e, a); + }, t2.prototype.doSingleRepetition = function(e) { + var r = this.getLexerPosition(); + e.call(this); + var n2 = this.getLexerPosition(); + return n2 > r; + }, t2.prototype.orInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.OR_IDX, r), i = q2.isArray(e) ? e : e.DEF, a = this.getLaFuncFromCache(n2), o = a.call(this, i); + if (o !== undefined) { + var s = i[o]; + return s.ALT.call(this); + } + this.raiseNoAltException(r, e.ERR_MSG); + }, t2.prototype.ruleFinallyStateUpdate = function() { + if (this.RULE_STACK.pop(), this.RULE_OCCURRENCE_STACK.pop(), this.cstFinallyStateUpdate(), this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) { + var e = this.LA(1), r = this.errorMessageProvider.buildNotAllInputParsedMessage({ firstRedundant: e, ruleName: this.getCurrRuleFullName() }); + this.SAVE_ERROR(new er.NotAllInputParsedException(r, e)); + } + }, t2.prototype.subruleInternal = function(e, r, n2) { + var i; + try { + var a = n2 !== undefined ? n2.ARGS : undefined; + return i = e.call(this, r, a), this.cstPostNonTerminal(i, n2 !== undefined && n2.LABEL !== undefined ? n2.LABEL : e.ruleName), i; + } catch (o) { + this.subruleInternalError(o, n2, e.ruleName); + } + }, t2.prototype.subruleInternalError = function(e, r, n2) { + throw er.isRecognitionException(e) && e.partialCstResult !== undefined && (this.cstPostNonTerminal(e.partialCstResult, r !== undefined && r.LABEL !== undefined ? r.LABEL : n2), delete e.partialCstResult), e; + }, t2.prototype.consumeInternal = function(e, r, n2) { + var i; + try { + var a = this.LA(1); + this.tokenMatcher(a, e) === true ? (this.consumeToken(), i = a) : this.consumeInternalError(e, a, n2); + } catch (o) { + i = this.consumeInternalRecovery(e, r, o); + } + return this.cstPostTerminal(n2 !== undefined && n2.LABEL !== undefined ? n2.LABEL : e.name, i), i; + }, t2.prototype.consumeInternalError = function(e, r, n2) { + var i, a = this.LA(0); + throw n2 !== undefined && n2.ERR_MSG ? i = n2.ERR_MSG : i = this.errorMessageProvider.buildMismatchTokenMessage({ expected: e, actual: r, previous: a, ruleName: this.getCurrRuleFullName() }), this.SAVE_ERROR(new er.MismatchedTokenException(i, r, a)); + }, t2.prototype.consumeInternalRecovery = function(e, r, n2) { + if (this.recoveryEnabled && n2.name === "MismatchedTokenException" && !this.isBackTracking()) { + var i = this.getFollowsForInRuleRecovery(e, r); + try { + return this.tryInRuleRecovery(e, i); + } catch (a) { + throw a.name === Xs.IN_RULE_RECOVERY_EXCEPTION ? n2 : a; + } + } else + throw n2; + }, t2.prototype.saveRecogState = function() { + var e = this.errors, r = q2.cloneArr(this.RULE_STACK); + return { errors: e, lexerState: this.exportLexerState(), RULE_STACK: r, CST_STACK: this.CST_STACK }; + }, t2.prototype.reloadRecogState = function(e) { + this.errors = e.errors, this.importLexerState(e.lexerState), this.RULE_STACK = e.RULE_STACK; + }, t2.prototype.ruleInvocationStateUpdate = function(e, r, n2) { + this.RULE_OCCURRENCE_STACK.push(n2), this.RULE_STACK.push(e), this.cstInvocationStateUpdate(r, e); + }, t2.prototype.isBackTracking = function() { + return this.isBackTrackingStack.length !== 0; + }, t2.prototype.getCurrRuleFullName = function() { + var e = this.getLastExplicitRuleShortName(); + return this.shortRuleNameToFull[e]; + }, t2.prototype.shortRuleNameToFullName = function(e) { + return this.shortRuleNameToFull[e]; + }, t2.prototype.isAtEndOfInput = function() { + return this.tokenMatcher(this.LA(1), ca.EOF); + }, t2.prototype.reset = function() { + this.resetLexerState(), this.isBackTrackingStack = [], this.errors = [], this.RULE_STACK = [], this.CST_STACK = [], this.RULE_OCCURRENCE_STACK = []; + }, t2; + }(); + Jt.RecognizerEngine = Zs; +}); +var pa = R2((tr) => { + Object.defineProperty(tr, "__esModule", { value: true }); + tr.ErrorHandler = undefined; + var $r2 = et3(), Zr = k2(), fa = yt2(), Qs = ce2(), Js = function() { + function t2() { + } + return t2.prototype.initErrorHandler = function(e) { + this._errors = [], this.errorMessageProvider = Zr.has(e, "errorMessageProvider") ? e.errorMessageProvider : Qs.DEFAULT_PARSER_CONFIG.errorMessageProvider; + }, t2.prototype.SAVE_ERROR = function(e) { + if ($r2.isRecognitionException(e)) + return e.context = { ruleStack: this.getHumanReadableRuleStack(), ruleOccurrenceStack: Zr.cloneArr(this.RULE_OCCURRENCE_STACK) }, this._errors.push(e), e; + throw Error("Trying to save an Error which is not a RecognitionException"); + }, Object.defineProperty(t2.prototype, "errors", { get: function() { + return Zr.cloneArr(this._errors); + }, set: function(e) { + this._errors = e; + }, enumerable: false, configurable: true }), t2.prototype.raiseEarlyExitException = function(e, r, n2) { + for (var i = this.getCurrRuleFullName(), a = this.getGAstProductions()[i], o = fa.getLookaheadPathsForOptionalProd(e, a, r, this.maxLookahead), s = o[0], c = [], f = 1;f <= this.maxLookahead; f++) + c.push(this.LA(f)); + var p = this.errorMessageProvider.buildEarlyExitMessage({ expectedIterationPaths: s, actual: c, previous: this.LA(0), customUserDescription: n2, ruleName: i }); + throw this.SAVE_ERROR(new $r2.EarlyExitException(p, this.LA(1), this.LA(0))); + }, t2.prototype.raiseNoAltException = function(e, r) { + for (var n2 = this.getCurrRuleFullName(), i = this.getGAstProductions()[n2], a = fa.getLookaheadPathsForOr(e, i, this.maxLookahead), o = [], s = 1;s <= this.maxLookahead; s++) + o.push(this.LA(s)); + var c = this.LA(0), f = this.errorMessageProvider.buildNoViableAltMessage({ expectedPathsPerAlt: a, actual: o, previous: c, customUserDescription: r, ruleName: this.getCurrRuleFullName() }); + throw this.SAVE_ERROR(new $r2.NoViableAltException(f, this.LA(1), c)); + }, t2; + }(); + tr.ErrorHandler = Js; +}); +var va = R2((rr) => { + Object.defineProperty(rr, "__esModule", { value: true }); + rr.ContentAssist = undefined; + var ha = Tt2(), da = k2(), eu = function() { + function t2() { + } + return t2.prototype.initContentAssist = function() { + }, t2.prototype.computeContentAssist = function(e, r) { + var n2 = this.gastProductionsCache[e]; + if (da.isUndefined(n2)) + throw Error("Rule ->" + e + "<- does not exist in this grammar."); + return ha.nextPossibleTokensAfter([n2], r, this.tokenMatcher, this.maxLookahead); + }, t2.prototype.getNextPossibleTokenTypes = function(e) { + var r = da.first(e.ruleStack), n2 = this.getGAstProductions(), i = n2[r], a = new ha.NextAfterTokenWalker(i, e).startWalking(); + return a; + }, t2; + }(); + rr.ContentAssist = eu; +}); +var Ra = R2((nr) => { + Object.defineProperty(nr, "__esModule", { value: true }); + nr.GastRecorder = undefined; + var oe = k2(), Pe = ne(), tu = ft(), ma = Xe(), Ea = Ue(), ru = ce2(), nu = Yt(), ir2 = { description: "This Object indicates the Parser is during Recording Phase" }; + Object.freeze(ir2); + var Ta = true, ya = Math.pow(2, nu.BITS_FOR_OCCURRENCE_IDX) - 1, _a2 = Ea.createToken({ name: "RECORDING_PHASE_TOKEN", pattern: tu.Lexer.NA }); + ma.augmentTokenTypes([_a2]); + var ga = Ea.createTokenInstance(_a2, `This IToken indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`, -1, -1, -1, -1, -1, -1); + Object.freeze(ga); + var iu = { name: `This CSTNode indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`, children: {} }, ou = function() { + function t2() { + } + return t2.prototype.initGastRecorder = function(e) { + this.recordingProdStack = [], this.RECORDING_PHASE = false; + }, t2.prototype.enableRecording = function() { + var e = this; + this.RECORDING_PHASE = true, this.TRACE_INIT("Enable Recording", function() { + for (var r = function(i) { + var a = i > 0 ? i : ""; + e["CONSUME" + a] = function(o, s) { + return this.consumeInternalRecord(o, i, s); + }, e["SUBRULE" + a] = function(o, s) { + return this.subruleInternalRecord(o, i, s); + }, e["OPTION" + a] = function(o) { + return this.optionInternalRecord(o, i); + }, e["OR" + a] = function(o) { + return this.orInternalRecord(o, i); + }, e["MANY" + a] = function(o) { + this.manyInternalRecord(i, o); + }, e["MANY_SEP" + a] = function(o) { + this.manySepFirstInternalRecord(i, o); + }, e["AT_LEAST_ONE" + a] = function(o) { + this.atLeastOneInternalRecord(i, o); + }, e["AT_LEAST_ONE_SEP" + a] = function(o) { + this.atLeastOneSepFirstInternalRecord(i, o); + }; + }, n2 = 0;n2 < 10; n2++) + r(n2); + e.consume = function(i, a, o) { + return this.consumeInternalRecord(a, i, o); + }, e.subrule = function(i, a, o) { + return this.subruleInternalRecord(a, i, o); + }, e.option = function(i, a) { + return this.optionInternalRecord(a, i); + }, e.or = function(i, a) { + return this.orInternalRecord(a, i); + }, e.many = function(i, a) { + this.manyInternalRecord(i, a); + }, e.atLeastOne = function(i, a) { + this.atLeastOneInternalRecord(i, a); + }, e.ACTION = e.ACTION_RECORD, e.BACKTRACK = e.BACKTRACK_RECORD, e.LA = e.LA_RECORD; + }); + }, t2.prototype.disableRecording = function() { + var e = this; + this.RECORDING_PHASE = false, this.TRACE_INIT("Deleting Recording methods", function() { + for (var r = 0;r < 10; r++) { + var n2 = r > 0 ? r : ""; + delete e["CONSUME" + n2], delete e["SUBRULE" + n2], delete e["OPTION" + n2], delete e["OR" + n2], delete e["MANY" + n2], delete e["MANY_SEP" + n2], delete e["AT_LEAST_ONE" + n2], delete e["AT_LEAST_ONE_SEP" + n2]; + } + delete e.consume, delete e.subrule, delete e.option, delete e.or, delete e.many, delete e.atLeastOne, delete e.ACTION, delete e.BACKTRACK, delete e.LA; + }); + }, t2.prototype.ACTION_RECORD = function(e) { + }, t2.prototype.BACKTRACK_RECORD = function(e, r) { + return function() { + return true; + }; + }, t2.prototype.LA_RECORD = function(e) { + return ru.END_OF_FILE; + }, t2.prototype.topLevelRuleRecord = function(e, r) { + try { + var n2 = new Pe.Rule({ definition: [], name: e }); + return n2.name = e, this.recordingProdStack.push(n2), r.call(this), this.recordingProdStack.pop(), n2; + } catch (i) { + if (i.KNOWN_RECORDER_ERROR !== true) + try { + i.message = i.message + ` + This error was thrown during the "grammar recording phase" For more info see: + https://chevrotain.io/docs/guide/internals.html#grammar-recording`; + } catch (a) { + throw i; + } + throw i; + } + }, t2.prototype.optionInternalRecord = function(e, r) { + return Ot.call(this, Pe.Option, e, r); + }, t2.prototype.atLeastOneInternalRecord = function(e, r) { + Ot.call(this, Pe.RepetitionMandatory, r, e); + }, t2.prototype.atLeastOneSepFirstInternalRecord = function(e, r) { + Ot.call(this, Pe.RepetitionMandatoryWithSeparator, r, e, Ta); + }, t2.prototype.manyInternalRecord = function(e, r) { + Ot.call(this, Pe.Repetition, r, e); + }, t2.prototype.manySepFirstInternalRecord = function(e, r) { + Ot.call(this, Pe.RepetitionWithSeparator, r, e, Ta); + }, t2.prototype.orInternalRecord = function(e, r) { + return au.call(this, e, r); + }, t2.prototype.subruleInternalRecord = function(e, r, n2) { + if (ar(r), !e || oe.has(e, "ruleName") === false) { + var i = new Error(" argument is invalid" + (" expecting a Parser method reference but got: <" + JSON.stringify(e) + ">") + (` + inside top level rule: <` + this.recordingProdStack[0].name + ">")); + throw i.KNOWN_RECORDER_ERROR = true, i; + } + var a = oe.peek(this.recordingProdStack), o = e.ruleName, s = new Pe.NonTerminal({ idx: r, nonTerminalName: o, referencedRule: undefined }); + return a.definition.push(s), this.outputCst ? iu : ir2; + }, t2.prototype.consumeInternalRecord = function(e, r, n2) { + if (ar(r), !ma.hasShortKeyProperty(e)) { + var i = new Error(" argument is invalid" + (" expecting a TokenType reference but got: <" + JSON.stringify(e) + ">") + (` + inside top level rule: <` + this.recordingProdStack[0].name + ">")); + throw i.KNOWN_RECORDER_ERROR = true, i; + } + var a = oe.peek(this.recordingProdStack), o = new Pe.Terminal({ idx: r, terminalType: e }); + return a.definition.push(o), ga; + }, t2; + }(); + nr.GastRecorder = ou; + function Ot(t2, e, r, n2) { + n2 === undefined && (n2 = false), ar(r); + var i = oe.peek(this.recordingProdStack), a = oe.isFunction(e) ? e : e.DEF, o = new t2({ definition: [], idx: r }); + return n2 && (o.separator = e.SEP), oe.has(e, "MAX_LOOKAHEAD") && (o.maxLookahead = e.MAX_LOOKAHEAD), this.recordingProdStack.push(o), a.call(this), i.definition.push(o), this.recordingProdStack.pop(), ir2; + } + function au(t2, e) { + var r = this; + ar(e); + var n2 = oe.peek(this.recordingProdStack), i = oe.isArray(t2) === false, a = i === false ? t2 : t2.DEF, o = new Pe.Alternation({ definition: [], idx: e, ignoreAmbiguities: i && t2.IGNORE_AMBIGUITIES === true }); + oe.has(t2, "MAX_LOOKAHEAD") && (o.maxLookahead = t2.MAX_LOOKAHEAD); + var s = oe.some(a, function(c) { + return oe.isFunction(c.GATE); + }); + return o.hasPredicates = s, n2.definition.push(o), oe.forEach(a, function(c) { + var f = new Pe.Alternative({ definition: [] }); + o.definition.push(f), oe.has(c, "IGNORE_AMBIGUITIES") ? f.ignoreAmbiguities = c.IGNORE_AMBIGUITIES : oe.has(c, "GATE") && (f.ignoreAmbiguities = true), r.recordingProdStack.push(f), c.ALT.call(r), r.recordingProdStack.pop(); + }), ir2; + } + function Aa(t2) { + return t2 === 0 ? "" : "" + t2; + } + function ar(t2) { + if (t2 < 0 || t2 > ya) { + var e = new Error("Invalid DSL Method idx value: <" + t2 + `> + ` + ("Idx value must be a none negative value smaller than " + (ya + 1))); + throw e.KNOWN_RECORDER_ERROR = true, e; + } + } +}); +var Na = R2((or) => { + Object.defineProperty(or, "__esModule", { value: true }); + or.PerformanceTracer = undefined; + var Oa = k2(), su = ce2(), uu = function() { + function t2() { + } + return t2.prototype.initPerformanceTracer = function(e) { + if (Oa.has(e, "traceInitPerf")) { + var r = e.traceInitPerf, n2 = typeof r == "number"; + this.traceInitMaxIdent = n2 ? r : Infinity, this.traceInitPerf = n2 ? r > 0 : r; + } else + this.traceInitMaxIdent = 0, this.traceInitPerf = su.DEFAULT_PARSER_CONFIG.traceInitPerf; + this.traceInitIndent = -1; + }, t2.prototype.TRACE_INIT = function(e, r) { + if (this.traceInitPerf === true) { + this.traceInitIndent++; + var n2 = new Array(this.traceInitIndent + 1).join("\t"); + this.traceInitIndent < this.traceInitMaxIdent && console.log(n2 + "--> <" + e + ">"); + var i = Oa.timer(r), a = i.time, o = i.value, s = a > 10 ? console.warn : console.log; + return this.traceInitIndent < this.traceInitMaxIdent && s(n2 + "<-- <" + e + "> time: " + a + "ms"), this.traceInitIndent--, o; + } else + return r(); + }, t2; + }(); + or.PerformanceTracer = uu; +}); +var Ia = R2((sr) => { + Object.defineProperty(sr, "__esModule", { value: true }); + sr.applyMixins = undefined; + function cu(t2, e) { + e.forEach(function(r) { + var n2 = r.prototype; + Object.getOwnPropertyNames(n2).forEach(function(i) { + if (i !== "constructor") { + var a = Object.getOwnPropertyDescriptor(n2, i); + a && (a.get || a.set) ? Object.defineProperty(t2.prototype, i, a) : t2.prototype[i] = r.prototype[i]; + } + }); + }); + } + sr.applyMixins = cu; +}); +var ce2 = R2((U) => { + var ka = U && U.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(U, "__esModule", { value: true }); + U.EmbeddedActionsParser = U.CstParser = U.Parser = U.EMPTY_ALT = U.ParserDefinitionErrorType = U.DEFAULT_RULE_CONFIG = U.DEFAULT_PARSER_CONFIG = U.END_OF_FILE = undefined; + var ee = k2(), lu = pi2(), Pa = Ue(), Sa = mt(), xa = Ui(), fu = zr(), pu = zi(), hu = ra(), du = ia(), vu = oa(), mu = la(), Eu = pa(), Tu = va(), yu = Ra(), _u = Na(), gu = Ia(); + U.END_OF_FILE = Pa.createTokenInstance(Pa.EOF, "", NaN, NaN, NaN, NaN, NaN, NaN); + Object.freeze(U.END_OF_FILE); + U.DEFAULT_PARSER_CONFIG = Object.freeze({ recoveryEnabled: false, maxLookahead: 3, dynamicTokensEnabled: false, outputCst: true, errorMessageProvider: Sa.defaultParserErrorProvider, nodeLocationTracking: "none", traceInitPerf: false, skipValidations: false }); + U.DEFAULT_RULE_CONFIG = Object.freeze({ recoveryValueFunc: function() { + }, resyncEnabled: true }); + var Au; + (function(t2) { + t2[t2.INVALID_RULE_NAME = 0] = "INVALID_RULE_NAME", t2[t2.DUPLICATE_RULE_NAME = 1] = "DUPLICATE_RULE_NAME", t2[t2.INVALID_RULE_OVERRIDE = 2] = "INVALID_RULE_OVERRIDE", t2[t2.DUPLICATE_PRODUCTIONS = 3] = "DUPLICATE_PRODUCTIONS", t2[t2.UNRESOLVED_SUBRULE_REF = 4] = "UNRESOLVED_SUBRULE_REF", t2[t2.LEFT_RECURSION = 5] = "LEFT_RECURSION", t2[t2.NONE_LAST_EMPTY_ALT = 6] = "NONE_LAST_EMPTY_ALT", t2[t2.AMBIGUOUS_ALTS = 7] = "AMBIGUOUS_ALTS", t2[t2.CONFLICT_TOKENS_RULES_NAMESPACE = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE", t2[t2.INVALID_TOKEN_NAME = 9] = "INVALID_TOKEN_NAME", t2[t2.NO_NON_EMPTY_LOOKAHEAD = 10] = "NO_NON_EMPTY_LOOKAHEAD", t2[t2.AMBIGUOUS_PREFIX_ALTS = 11] = "AMBIGUOUS_PREFIX_ALTS", t2[t2.TOO_MANY_ALTS = 12] = "TOO_MANY_ALTS"; + })(Au = U.ParserDefinitionErrorType || (U.ParserDefinitionErrorType = {})); + function Ru(t2) { + return t2 === undefined && (t2 = undefined), function() { + return t2; + }; + } + U.EMPTY_ALT = Ru; + var ur = function() { + function t2(e, r) { + this.definitionErrors = [], this.selfAnalysisDone = false; + var n2 = this; + if (n2.initErrorHandler(r), n2.initLexerAdapter(), n2.initLooksAhead(r), n2.initRecognizerEngine(e, r), n2.initRecoverable(r), n2.initTreeBuilder(r), n2.initContentAssist(), n2.initGastRecorder(r), n2.initPerformanceTracer(r), ee.has(r, "ignoredIssues")) + throw new Error(`The IParserConfig property has been deprecated. + Please use the flag on the relevant DSL method instead. + See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES + For further details.`); + this.skipValidations = ee.has(r, "skipValidations") ? r.skipValidations : U.DEFAULT_PARSER_CONFIG.skipValidations; + } + return t2.performSelfAnalysis = function(e) { + throw Error("The **static** `performSelfAnalysis` method has been deprecated.\t\nUse the **instance** method with the same name instead."); + }, t2.prototype.performSelfAnalysis = function() { + var e = this; + this.TRACE_INIT("performSelfAnalysis", function() { + var r; + e.selfAnalysisDone = true; + var n2 = e.className; + e.TRACE_INIT("toFastProps", function() { + ee.toFastProperties(e); + }), e.TRACE_INIT("Grammar Recording", function() { + try { + e.enableRecording(), ee.forEach(e.definedRulesNames, function(a) { + var o = e[a], s = o.originalGrammarAction, c = undefined; + e.TRACE_INIT(a + " Rule", function() { + c = e.topLevelRuleRecord(a, s); + }), e.gastProductionsCache[a] = c; + }); + } finally { + e.disableRecording(); + } + }); + var i = []; + if (e.TRACE_INIT("Grammar Resolving", function() { + i = xa.resolveGrammar({ rules: ee.values(e.gastProductionsCache) }), e.definitionErrors = e.definitionErrors.concat(i); + }), e.TRACE_INIT("Grammar Validations", function() { + if (ee.isEmpty(i) && e.skipValidations === false) { + var a = xa.validateGrammar({ rules: ee.values(e.gastProductionsCache), maxLookahead: e.maxLookahead, tokenTypes: ee.values(e.tokensMap), errMsgProvider: Sa.defaultGrammarValidatorErrorProvider, grammarName: n2 }); + e.definitionErrors = e.definitionErrors.concat(a); + } + }), ee.isEmpty(e.definitionErrors) && (e.recoveryEnabled && e.TRACE_INIT("computeAllProdsFollows", function() { + var a = lu.computeAllProdsFollows(ee.values(e.gastProductionsCache)); + e.resyncFollows = a; + }), e.TRACE_INIT("ComputeLookaheadFunctions", function() { + e.preComputeLookaheadFunctions(ee.values(e.gastProductionsCache)); + })), !t2.DEFER_DEFINITION_ERRORS_HANDLING && !ee.isEmpty(e.definitionErrors)) + throw r = ee.map(e.definitionErrors, function(a) { + return a.message; + }), new Error(`Parser Definition Errors detected: + ` + r.join(` +------------------------------- +`)); + }); + }, t2.DEFER_DEFINITION_ERRORS_HANDLING = false, t2; + }(); + U.Parser = ur; + gu.applyMixins(ur, [fu.Recoverable, pu.LooksAhead, hu.TreeBuilder, du.LexerAdapter, mu.RecognizerEngine, vu.RecognizerApi, Eu.ErrorHandler, Tu.ContentAssist, yu.GastRecorder, _u.PerformanceTracer]); + var Ou = function(t2) { + ka(e, t2); + function e(r, n2) { + n2 === undefined && (n2 = U.DEFAULT_PARSER_CONFIG); + var i = this, a = ee.cloneObj(n2); + return a.outputCst = true, i = t2.call(this, r, a) || this, i; + } + return e; + }(ur); + U.CstParser = Ou; + var Nu = function(t2) { + ka(e, t2); + function e(r, n2) { + n2 === undefined && (n2 = U.DEFAULT_PARSER_CONFIG); + var i = this, a = ee.cloneObj(n2); + return a.outputCst = false, i = t2.call(this, r, a) || this, i; + } + return e; + }(ur); + U.EmbeddedActionsParser = Nu; +}); +var La = R2((cr) => { + Object.defineProperty(cr, "__esModule", { value: true }); + cr.createSyntaxDiagramsCode = undefined; + var Ca = Er2(); + function Iu(t2, e) { + var r = e === undefined ? {} : e, n2 = r.resourceBase, i = n2 === undefined ? "https://unpkg.com/chevrotain@" + Ca.VERSION + "/diagrams/" : n2, a = r.css, o = a === undefined ? "https://unpkg.com/chevrotain@" + Ca.VERSION + "/diagrams/diagrams.css" : a, s = ` + + + + + +`, c = ` + +`, f = ` + + + + +`, p = ` +
+`, l2 = ` + +`, m = ` + +`; + return s + c + f + p + l2 + m; + } + cr.createSyntaxDiagramsCode = Iu; +}); +var Fa = R2((E2) => { + Object.defineProperty(E2, "__esModule", { value: true }); + E2.Parser = E2.createSyntaxDiagramsCode = E2.clearCache = E2.GAstVisitor = E2.serializeProduction = E2.serializeGrammar = E2.Terminal = E2.Rule = E2.RepetitionWithSeparator = E2.RepetitionMandatoryWithSeparator = E2.RepetitionMandatory = E2.Repetition = E2.Option = E2.NonTerminal = E2.Alternative = E2.Alternation = E2.defaultLexerErrorProvider = E2.NoViableAltException = E2.NotAllInputParsedException = E2.MismatchedTokenException = E2.isRecognitionException = E2.EarlyExitException = E2.defaultParserErrorProvider = E2.tokenName = E2.tokenMatcher = E2.tokenLabel = E2.EOF = E2.createTokenInstance = E2.createToken = E2.LexerDefinitionErrorType = E2.Lexer = E2.EMPTY_ALT = E2.ParserDefinitionErrorType = E2.EmbeddedActionsParser = E2.CstParser = E2.VERSION = undefined; + var ku = Er2(); + Object.defineProperty(E2, "VERSION", { enumerable: true, get: function() { + return ku.VERSION; + } }); + var lr = ce2(); + Object.defineProperty(E2, "CstParser", { enumerable: true, get: function() { + return lr.CstParser; + } }); + Object.defineProperty(E2, "EmbeddedActionsParser", { enumerable: true, get: function() { + return lr.EmbeddedActionsParser; + } }); + Object.defineProperty(E2, "ParserDefinitionErrorType", { enumerable: true, get: function() { + return lr.ParserDefinitionErrorType; + } }); + Object.defineProperty(E2, "EMPTY_ALT", { enumerable: true, get: function() { + return lr.EMPTY_ALT; + } }); + var Ma = ft(); + Object.defineProperty(E2, "Lexer", { enumerable: true, get: function() { + return Ma.Lexer; + } }); + Object.defineProperty(E2, "LexerDefinitionErrorType", { enumerable: true, get: function() { + return Ma.LexerDefinitionErrorType; + } }); + var nt2 = Ue(); + Object.defineProperty(E2, "createToken", { enumerable: true, get: function() { + return nt2.createToken; + } }); + Object.defineProperty(E2, "createTokenInstance", { enumerable: true, get: function() { + return nt2.createTokenInstance; + } }); + Object.defineProperty(E2, "EOF", { enumerable: true, get: function() { + return nt2.EOF; + } }); + Object.defineProperty(E2, "tokenLabel", { enumerable: true, get: function() { + return nt2.tokenLabel; + } }); + Object.defineProperty(E2, "tokenMatcher", { enumerable: true, get: function() { + return nt2.tokenMatcher; + } }); + Object.defineProperty(E2, "tokenName", { enumerable: true, get: function() { + return nt2.tokenName; + } }); + var Pu = mt(); + Object.defineProperty(E2, "defaultParserErrorProvider", { enumerable: true, get: function() { + return Pu.defaultParserErrorProvider; + } }); + var Nt = et3(); + Object.defineProperty(E2, "EarlyExitException", { enumerable: true, get: function() { + return Nt.EarlyExitException; + } }); + Object.defineProperty(E2, "isRecognitionException", { enumerable: true, get: function() { + return Nt.isRecognitionException; + } }); + Object.defineProperty(E2, "MismatchedTokenException", { enumerable: true, get: function() { + return Nt.MismatchedTokenException; + } }); + Object.defineProperty(E2, "NotAllInputParsedException", { enumerable: true, get: function() { + return Nt.NotAllInputParsedException; + } }); + Object.defineProperty(E2, "NoViableAltException", { enumerable: true, get: function() { + return Nt.NoViableAltException; + } }); + var Su = kr(); + Object.defineProperty(E2, "defaultLexerErrorProvider", { enumerable: true, get: function() { + return Su.defaultLexerErrorProvider; + } }); + var Se2 = ne(); + Object.defineProperty(E2, "Alternation", { enumerable: true, get: function() { + return Se2.Alternation; + } }); + Object.defineProperty(E2, "Alternative", { enumerable: true, get: function() { + return Se2.Alternative; + } }); + Object.defineProperty(E2, "NonTerminal", { enumerable: true, get: function() { + return Se2.NonTerminal; + } }); + Object.defineProperty(E2, "Option", { enumerable: true, get: function() { + return Se2.Option; + } }); + Object.defineProperty(E2, "Repetition", { enumerable: true, get: function() { + return Se2.Repetition; + } }); + Object.defineProperty(E2, "RepetitionMandatory", { enumerable: true, get: function() { + return Se2.RepetitionMandatory; + } }); + Object.defineProperty(E2, "RepetitionMandatoryWithSeparator", { enumerable: true, get: function() { + return Se2.RepetitionMandatoryWithSeparator; + } }); + Object.defineProperty(E2, "RepetitionWithSeparator", { enumerable: true, get: function() { + return Se2.RepetitionWithSeparator; + } }); + Object.defineProperty(E2, "Rule", { enumerable: true, get: function() { + return Se2.Rule; + } }); + Object.defineProperty(E2, "Terminal", { enumerable: true, get: function() { + return Se2.Terminal; + } }); + var ba = ne(); + Object.defineProperty(E2, "serializeGrammar", { enumerable: true, get: function() { + return ba.serializeGrammar; + } }); + Object.defineProperty(E2, "serializeProduction", { enumerable: true, get: function() { + return ba.serializeProduction; + } }); + var xu = $e(); + Object.defineProperty(E2, "GAstVisitor", { enumerable: true, get: function() { + return xu.GAstVisitor; + } }); + function Cu() { + console.warn(`The clearCache function was 'soft' removed from the Chevrotain API. + It performs no action other than printing this message. + Please avoid using it as it will be completely removed in the future`); + } + E2.clearCache = Cu; + var Lu = La(); + Object.defineProperty(E2, "createSyntaxDiagramsCode", { enumerable: true, get: function() { + return Lu.createSyntaxDiagramsCode; + } }); + var Mu = function() { + function t2() { + throw new Error(`The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead. +See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_7-0-0`); + } + return t2; + }(); + E2.Parser = Mu; +}); +var chevrotain_module_min_default = Fa(); + +// node_modules/three/examples/jsm/loaders/VRMLLoader.js +var CstParser = chevrotain_module_min_default.CstParser; +// node_modules/three/examples/jsm/materials/MeshGouraudMaterial.js +var GouraudShader = { + name: "GouraudShader", + uniforms: UniformsUtils.merge([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: new Color(0) } + } + ]), + vertexShader: ` + + #define GOURAUD + + varying vec3 vLightFront; + varying vec3 vIndirectFront; + + #ifdef DOUBLE_SIDED + varying vec3 vLightBack; + varying vec3 vIndirectBack; + #endif + + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + void main() { + + #include + #include + #include + + #include + #include + #include + #include + #include + + #include + #include + #include + #include + #include + #include + + #include + #include + + // inlining legacy + + vec3 diffuse = vec3( 1.0 ); + + vec3 geometryPosition = mvPosition.xyz; + vec3 geometryNormal = normalize( transformedNormal ); + vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz ); + + vec3 backGeometryNormal = - geometryNormal; + + vLightFront = vec3( 0.0 ); + vIndirectFront = vec3( 0.0 ); + #ifdef DOUBLE_SIDED + vLightBack = vec3( 0.0 ); + vIndirectBack = vec3( 0.0 ); + #endif + + IncidentLight directLight; + float dotNL; + vec3 directLightColor_Diffuse; + + vIndirectFront += getAmbientLightIrradiance( ambientLightColor ); + + #if defined( USE_LIGHT_PROBES ) + + vIndirectFront += getLightProbeIrradiance( lightProbe, geometryNormal ); + + #endif + + #ifdef DOUBLE_SIDED + + vIndirectBack += getAmbientLightIrradiance( ambientLightColor ); + + #if defined( USE_LIGHT_PROBES ) + + vIndirectBack += getLightProbeIrradiance( lightProbe, backGeometryNormal ); + + #endif + + #endif + + #if NUM_POINT_LIGHTS > 0 + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + + getPointLightInfo( pointLights[ i ], geometryPosition, directLight ); + + dotNL = dot( geometryNormal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + + #ifdef DOUBLE_SIDED + + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + + #endif + + } + #pragma unroll_loop_end + + #endif + + #if NUM_SPOT_LIGHTS > 0 + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + + getSpotLightInfo( spotLights[ i ], geometryPosition, directLight ); + + dotNL = dot( geometryNormal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + + #ifdef DOUBLE_SIDED + + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + + #endif + } + #pragma unroll_loop_end + + #endif + + #if NUM_DIR_LIGHTS > 0 + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + getDirectionalLightInfo( directionalLights[ i ], directLight ); + + dotNL = dot( geometryNormal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + + #ifdef DOUBLE_SIDED + + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + + #endif + + } + #pragma unroll_loop_end + + #endif + + #if NUM_HEMI_LIGHTS > 0 + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + + vIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + + #ifdef DOUBLE_SIDED + + vIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometryNormal ); + + #endif + + } + #pragma unroll_loop_end + + #endif + + #include + #include + + }`, + fragmentShader: ` + + #define GOURAUD + + uniform vec3 diffuse; + uniform vec3 emissive; + uniform float opacity; + + varying vec3 vLightFront; + varying vec3 vIndirectFront; + + #ifdef DOUBLE_SIDED + varying vec3 vLightBack; + varying vec3 vIndirectBack; + #endif + + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + void main() { + + #include + + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + + #include + #include + #include + #include + #include + #include + #include + + // accumulation + + #ifdef DOUBLE_SIDED + + reflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack; + + #else + + reflectedLight.indirectDiffuse += vIndirectFront; + + #endif + + #ifdef USE_LIGHTMAP + + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + reflectedLight.indirectDiffuse += lightMapIrradiance; + + #endif + + reflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb ); + + #ifdef DOUBLE_SIDED + + reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack; + + #else + + reflectedLight.directDiffuse = vLightFront; + + #endif + + reflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask(); + + // modulation + + #include + + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + + #include + + #include + #include + #include + #include + #include + #include + + }` +}; +// node_modules/three/examples/jsm/math/Capsule.js +class Capsule { + constructor(start = new Vector3(0, 0, 0), end = new Vector3(0, 1, 0), radius = 1) { + this.start = start; + this.end = end; + this.radius = radius; + } + clone() { + return new Capsule(this.start.clone(), this.end.clone(), this.radius); + } + set(start, end, radius) { + this.start.copy(start); + this.end.copy(end); + this.radius = radius; + } + copy(capsule) { + this.start.copy(capsule.start); + this.end.copy(capsule.end); + this.radius = capsule.radius; + } + getCenter(target) { + return target.copy(this.end).add(this.start).multiplyScalar(0.5); + } + translate(v) { + this.start.add(v); + this.end.add(v); + } + checkAABBAxis(p1x, p1y, p2x, p2y, minx, maxx, miny, maxy, radius) { + return (minx - p1x < radius || minx - p2x < radius) && (p1x - maxx < radius || p2x - maxx < radius) && (miny - p1y < radius || miny - p2y < radius) && (p1y - maxy < radius || p2y - maxy < radius); + } + intersectsBox(box) { + return this.checkAABBAxis(this.start.x, this.start.y, this.end.x, this.end.y, box.min.x, box.max.x, box.min.y, box.max.y, this.radius) && this.checkAABBAxis(this.start.x, this.start.z, this.end.x, this.end.z, box.min.x, box.max.x, box.min.z, box.max.z, this.radius) && this.checkAABBAxis(this.start.y, this.start.z, this.end.y, this.end.z, box.min.y, box.max.y, box.min.z, box.max.z, this.radius); + } +} +// node_modules/three/examples/jsm/math/ImprovedNoise.js +var _p = [ + 151, + 160, + 137, + 91, + 90, + 15, + 131, + 13, + 201, + 95, + 96, + 53, + 194, + 233, + 7, + 225, + 140, + 36, + 103, + 30, + 69, + 142, + 8, + 99, + 37, + 240, + 21, + 10, + 23, + 190, + 6, + 148, + 247, + 120, + 234, + 75, + 0, + 26, + 197, + 62, + 94, + 252, + 219, + 203, + 117, + 35, + 11, + 32, + 57, + 177, + 33, + 88, + 237, + 149, + 56, + 87, + 174, + 20, + 125, + 136, + 171, + 168, + 68, + 175, + 74, + 165, + 71, + 134, + 139, + 48, + 27, + 166, + 77, + 146, + 158, + 231, + 83, + 111, + 229, + 122, + 60, + 211, + 133, + 230, + 220, + 105, + 92, + 41, + 55, + 46, + 245, + 40, + 244, + 102, + 143, + 54, + 65, + 25, + 63, + 161, + 1, + 216, + 80, + 73, + 209, + 76, + 132, + 187, + 208, + 89, + 18, + 169, + 200, + 196, + 135, + 130, + 116, + 188, + 159, + 86, + 164, + 100, + 109, + 198, + 173, + 186, + 3, + 64, + 52, + 217, + 226, + 250, + 124, + 123, + 5, + 202, + 38, + 147, + 118, + 126, + 255, + 82, + 85, + 212, + 207, + 206, + 59, + 227, + 47, + 16, + 58, + 17, + 182, + 189, + 28, + 42, + 223, + 183, + 170, + 213, + 119, + 248, + 152, + 2, + 44, + 154, + 163, + 70, + 221, + 153, + 101, + 155, + 167, + 43, + 172, + 9, + 129, + 22, + 39, + 253, + 19, + 98, + 108, + 110, + 79, + 113, + 224, + 232, + 178, + 185, + 112, + 104, + 218, + 246, + 97, + 228, + 251, + 34, + 242, + 193, + 238, + 210, + 144, + 12, + 191, + 179, + 162, + 241, + 81, + 51, + 145, + 235, + 249, + 14, + 239, + 107, + 49, + 192, + 214, + 31, + 181, + 199, + 106, + 157, + 184, + 84, + 204, + 176, + 115, + 121, + 50, + 45, + 127, + 4, + 150, + 254, + 138, + 236, + 205, + 93, + 222, + 114, + 67, + 29, + 24, + 72, + 243, + 141, + 128, + 195, + 78, + 66, + 215, + 61, + 156, + 180 +]; +for (let i = 0;i < 256; i++) { + _p[256 + i] = _p[i]; +} +// node_modules/three/examples/jsm/math/MeshSurfaceSampler.js +var _face = new Triangle; +var _color6 = new Vector3; +var _uva = new Vector2; +var _uvb = new Vector2; +var _uvc = new Vector2; +// node_modules/three/examples/jsm/math/OBB.js +var a = { + c: null, + u: [new Vector3, new Vector3, new Vector3], + e: [] +}; +var b = { + c: null, + u: [new Vector3, new Vector3, new Vector3], + e: [] +}; +var R3 = [[], [], []]; +var AbsR = [[], [], []]; +var t2 = []; +var xAxis = new Vector3; +var yAxis = new Vector3; +var zAxis = new Vector3; +var v1 = new Vector3; +var size = new Vector3; +var closestPoint = new Vector3; +var rotationMatrix = new Matrix3; +var aabb = new Box3; +var matrix = new Matrix4; +var inverse = new Matrix4; +var localRay = new Ray; + +class OBB { + constructor(center = new Vector3, halfSize = new Vector3, rotation2 = new Matrix3) { + this.center = center; + this.halfSize = halfSize; + this.rotation = rotation2; + } + set(center, halfSize, rotation2) { + this.center = center; + this.halfSize = halfSize; + this.rotation = rotation2; + return this; + } + copy(obb) { + this.center.copy(obb.center); + this.halfSize.copy(obb.halfSize); + this.rotation.copy(obb.rotation); + return this; + } + clone() { + return new this.constructor().copy(this); + } + getSize(result) { + return result.copy(this.halfSize).multiplyScalar(2); + } + clampPoint(point, result) { + const halfSize = this.halfSize; + v1.subVectors(point, this.center); + this.rotation.extractBasis(xAxis, yAxis, zAxis); + result.copy(this.center); + const x2 = MathUtils.clamp(v1.dot(xAxis), -halfSize.x, halfSize.x); + result.add(xAxis.multiplyScalar(x2)); + const y = MathUtils.clamp(v1.dot(yAxis), -halfSize.y, halfSize.y); + result.add(yAxis.multiplyScalar(y)); + const z = MathUtils.clamp(v1.dot(zAxis), -halfSize.z, halfSize.z); + result.add(zAxis.multiplyScalar(z)); + return result; + } + containsPoint(point) { + v1.subVectors(point, this.center); + this.rotation.extractBasis(xAxis, yAxis, zAxis); + return Math.abs(v1.dot(xAxis)) <= this.halfSize.x && Math.abs(v1.dot(yAxis)) <= this.halfSize.y && Math.abs(v1.dot(zAxis)) <= this.halfSize.z; + } + intersectsBox3(box3) { + return this.intersectsOBB(obb.fromBox3(box3)); + } + intersectsSphere(sphere) { + this.clampPoint(sphere.center, closestPoint); + return closestPoint.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; + } + intersectsOBB(obb, epsilon = Number.EPSILON) { + a.c = this.center; + a.e[0] = this.halfSize.x; + a.e[1] = this.halfSize.y; + a.e[2] = this.halfSize.z; + this.rotation.extractBasis(a.u[0], a.u[1], a.u[2]); + b.c = obb.center; + b.e[0] = obb.halfSize.x; + b.e[1] = obb.halfSize.y; + b.e[2] = obb.halfSize.z; + obb.rotation.extractBasis(b.u[0], b.u[1], b.u[2]); + for (let i = 0;i < 3; i++) { + for (let j2 = 0;j2 < 3; j2++) { + R3[i][j2] = a.u[i].dot(b.u[j2]); + } + } + v1.subVectors(b.c, a.c); + t2[0] = v1.dot(a.u[0]); + t2[1] = v1.dot(a.u[1]); + t2[2] = v1.dot(a.u[2]); + for (let i = 0;i < 3; i++) { + for (let j2 = 0;j2 < 3; j2++) { + AbsR[i][j2] = Math.abs(R3[i][j2]) + epsilon; + } + } + let ra2, rb; + for (let i = 0;i < 3; i++) { + ra2 = a.e[i]; + rb = b.e[0] * AbsR[i][0] + b.e[1] * AbsR[i][1] + b.e[2] * AbsR[i][2]; + if (Math.abs(t2[i]) > ra2 + rb) + return false; + } + for (let i = 0;i < 3; i++) { + ra2 = a.e[0] * AbsR[0][i] + a.e[1] * AbsR[1][i] + a.e[2] * AbsR[2][i]; + rb = b.e[i]; + if (Math.abs(t2[0] * R3[0][i] + t2[1] * R3[1][i] + t2[2] * R3[2][i]) > ra2 + rb) + return false; + } + ra2 = a.e[1] * AbsR[2][0] + a.e[2] * AbsR[1][0]; + rb = b.e[1] * AbsR[0][2] + b.e[2] * AbsR[0][1]; + if (Math.abs(t2[2] * R3[1][0] - t2[1] * R3[2][0]) > ra2 + rb) + return false; + ra2 = a.e[1] * AbsR[2][1] + a.e[2] * AbsR[1][1]; + rb = b.e[0] * AbsR[0][2] + b.e[2] * AbsR[0][0]; + if (Math.abs(t2[2] * R3[1][1] - t2[1] * R3[2][1]) > ra2 + rb) + return false; + ra2 = a.e[1] * AbsR[2][2] + a.e[2] * AbsR[1][2]; + rb = b.e[0] * AbsR[0][1] + b.e[1] * AbsR[0][0]; + if (Math.abs(t2[2] * R3[1][2] - t2[1] * R3[2][2]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[2][0] + a.e[2] * AbsR[0][0]; + rb = b.e[1] * AbsR[1][2] + b.e[2] * AbsR[1][1]; + if (Math.abs(t2[0] * R3[2][0] - t2[2] * R3[0][0]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[2][1] + a.e[2] * AbsR[0][1]; + rb = b.e[0] * AbsR[1][2] + b.e[2] * AbsR[1][0]; + if (Math.abs(t2[0] * R3[2][1] - t2[2] * R3[0][1]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[2][2] + a.e[2] * AbsR[0][2]; + rb = b.e[0] * AbsR[1][1] + b.e[1] * AbsR[1][0]; + if (Math.abs(t2[0] * R3[2][2] - t2[2] * R3[0][2]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[1][0] + a.e[1] * AbsR[0][0]; + rb = b.e[1] * AbsR[2][2] + b.e[2] * AbsR[2][1]; + if (Math.abs(t2[1] * R3[0][0] - t2[0] * R3[1][0]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[1][1] + a.e[1] * AbsR[0][1]; + rb = b.e[0] * AbsR[2][2] + b.e[2] * AbsR[2][0]; + if (Math.abs(t2[1] * R3[0][1] - t2[0] * R3[1][1]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[1][2] + a.e[1] * AbsR[0][2]; + rb = b.e[0] * AbsR[2][1] + b.e[1] * AbsR[2][0]; + if (Math.abs(t2[1] * R3[0][2] - t2[0] * R3[1][2]) > ra2 + rb) + return false; + return true; + } + intersectsPlane(plane) { + this.rotation.extractBasis(xAxis, yAxis, zAxis); + const r = this.halfSize.x * Math.abs(plane.normal.dot(xAxis)) + this.halfSize.y * Math.abs(plane.normal.dot(yAxis)) + this.halfSize.z * Math.abs(plane.normal.dot(zAxis)); + const d = plane.normal.dot(this.center) - plane.constant; + return Math.abs(d) <= r; + } + intersectRay(ray, result) { + this.getSize(size); + aabb.setFromCenterAndSize(v1.set(0, 0, 0), size); + matrix.setFromMatrix3(this.rotation); + matrix.setPosition(this.center); + inverse.copy(matrix).invert(); + localRay.copy(ray).applyMatrix4(inverse); + if (localRay.intersectBox(aabb, result)) { + return result.applyMatrix4(matrix); + } else { + return null; + } + } + intersectsRay(ray) { + return this.intersectRay(ray, v1) !== null; + } + fromBox3(box3) { + box3.getCenter(this.center); + box3.getSize(this.halfSize).multiplyScalar(0.5); + this.rotation.identity(); + return this; + } + equals(obb) { + return obb.center.equals(this.center) && obb.halfSize.equals(this.halfSize) && obb.rotation.equals(this.rotation); + } + applyMatrix4(matrix2) { + const e = matrix2.elements; + let sx = v1.set(e[0], e[1], e[2]).length(); + const sy = v1.set(e[4], e[5], e[6]).length(); + const sz = v1.set(e[8], e[9], e[10]).length(); + const det = matrix2.determinant(); + if (det < 0) + sx = -sx; + rotationMatrix.setFromMatrix4(matrix2); + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + rotationMatrix.elements[0] *= invSX; + rotationMatrix.elements[1] *= invSX; + rotationMatrix.elements[2] *= invSX; + rotationMatrix.elements[3] *= invSY; + rotationMatrix.elements[4] *= invSY; + rotationMatrix.elements[5] *= invSY; + rotationMatrix.elements[6] *= invSZ; + rotationMatrix.elements[7] *= invSZ; + rotationMatrix.elements[8] *= invSZ; + this.rotation.multiply(rotationMatrix); + this.halfSize.x *= sx; + this.halfSize.y *= sy; + this.halfSize.z *= sz; + v1.setFromMatrixPosition(matrix2); + this.center.add(v1); + return this; + } +} +var obb = new OBB; +// node_modules/three/examples/jsm/math/Octree.js +var _v16 = new Vector3; +var _v26 = new Vector3; +var _point1 = new Vector3; +var _point2 = new Vector3; +var _plane4 = new Plane; +var _line1 = new Line3; +var _line2 = new Line3; +var _sphere3 = new Sphere; +var _capsule = new Capsule; +var _temp1 = new Vector3; +var _temp2 = new Vector3; +var _temp3 = new Vector3; +// node_modules/three/examples/jsm/math/SimplexNoise.js +class SimplexNoise { + constructor(r = Math) { + this.grad3 = [ + [1, 1, 0], + [-1, 1, 0], + [1, -1, 0], + [-1, -1, 0], + [1, 0, 1], + [-1, 0, 1], + [1, 0, -1], + [-1, 0, -1], + [0, 1, 1], + [0, -1, 1], + [0, 1, -1], + [0, -1, -1] + ]; + this.grad4 = [ + [0, 1, 1, 1], + [0, 1, 1, -1], + [0, 1, -1, 1], + [0, 1, -1, -1], + [0, -1, 1, 1], + [0, -1, 1, -1], + [0, -1, -1, 1], + [0, -1, -1, -1], + [1, 0, 1, 1], + [1, 0, 1, -1], + [1, 0, -1, 1], + [1, 0, -1, -1], + [-1, 0, 1, 1], + [-1, 0, 1, -1], + [-1, 0, -1, 1], + [-1, 0, -1, -1], + [1, 1, 0, 1], + [1, 1, 0, -1], + [1, -1, 0, 1], + [1, -1, 0, -1], + [-1, 1, 0, 1], + [-1, 1, 0, -1], + [-1, -1, 0, 1], + [-1, -1, 0, -1], + [1, 1, 1, 0], + [1, 1, -1, 0], + [1, -1, 1, 0], + [1, -1, -1, 0], + [-1, 1, 1, 0], + [-1, 1, -1, 0], + [-1, -1, 1, 0], + [-1, -1, -1, 0] + ]; + this.p = []; + for (let i = 0;i < 256; i++) { + this.p[i] = Math.floor(r.random() * 256); + } + this.perm = []; + for (let i = 0;i < 512; i++) { + this.perm[i] = this.p[i & 255]; + } + this.simplex = [ + [0, 1, 2, 3], + [0, 1, 3, 2], + [0, 0, 0, 0], + [0, 2, 3, 1], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 2, 3, 0], + [0, 2, 1, 3], + [0, 0, 0, 0], + [0, 3, 1, 2], + [0, 3, 2, 1], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 3, 2, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 2, 0, 3], + [0, 0, 0, 0], + [1, 3, 0, 2], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [2, 3, 0, 1], + [2, 3, 1, 0], + [1, 0, 2, 3], + [1, 0, 3, 2], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [2, 0, 3, 1], + [0, 0, 0, 0], + [2, 1, 3, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [2, 0, 1, 3], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [3, 0, 1, 2], + [3, 0, 2, 1], + [0, 0, 0, 0], + [3, 1, 2, 0], + [2, 1, 0, 3], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [3, 1, 0, 2], + [0, 0, 0, 0], + [3, 2, 0, 1], + [3, 2, 1, 0] + ]; + } + dot(g3, x2, y) { + return g3[0] * x2 + g3[1] * y; + } + dot3(g3, x2, y, z) { + return g3[0] * x2 + g3[1] * y + g3[2] * z; + } + dot4(g3, x2, y, z, w) { + return g3[0] * x2 + g3[1] * y + g3[2] * z + g3[3] * w; + } + noise(xin, yin) { + let n0; + let n1; + let n2; + const F2 = 0.5 * (Math.sqrt(3) - 1); + const s = (xin + yin) * F2; + const i = Math.floor(xin + s); + const j2 = Math.floor(yin + s); + const G2 = (3 - Math.sqrt(3)) / 6; + const t3 = (i + j2) * G2; + const X0 = i - t3; + const Y0 = j2 - t3; + const x0 = xin - X0; + const y0 = yin - Y0; + let i1; + let j1; + if (x0 > y0) { + i1 = 1; + j1 = 0; + } else { + i1 = 0; + j1 = 1; + } + const x1 = x0 - i1 + G2; + const y1 = y0 - j1 + G2; + const x2 = x0 - 1 + 2 * G2; + const y2 = y0 - 1 + 2 * G2; + const ii = i & 255; + const jj = j2 & 255; + const gi0 = this.perm[ii + this.perm[jj]] % 12; + const gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12; + const gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12; + let t0 = 0.5 - x0 * x0 - y0 * y0; + if (t0 < 0) + n0 = 0; + else { + t0 *= t0; + n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0); + } + let t1 = 0.5 - x1 * x1 - y1 * y1; + if (t1 < 0) + n1 = 0; + else { + t1 *= t1; + n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1); + } + let t22 = 0.5 - x2 * x2 - y2 * y2; + if (t22 < 0) + n2 = 0; + else { + t22 *= t22; + n2 = t22 * t22 * this.dot(this.grad3[gi2], x2, y2); + } + return 70 * (n0 + n1 + n2); + } + noise3d(xin, yin, zin) { + let n0; + let n1; + let n2; + let n3; + const F3 = 1 / 3; + const s = (xin + yin + zin) * F3; + const i = Math.floor(xin + s); + const j2 = Math.floor(yin + s); + const k3 = Math.floor(zin + s); + const G3 = 1 / 6; + const t3 = (i + j2 + k3) * G3; + const X0 = i - t3; + const Y0 = j2 - t3; + const Z0 = k3 - t3; + const x0 = xin - X0; + const y0 = yin - Y0; + const z0 = zin - Z0; + let i1; + let j1; + let k1; + let i2; + let j22; + let k22; + if (x0 >= y0) { + if (y0 >= z0) { + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j22 = 1; + k22 = 0; + } else if (x0 >= z0) { + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j22 = 0; + k22 = 1; + } else { + i1 = 0; + j1 = 0; + k1 = 1; + i2 = 1; + j22 = 0; + k22 = 1; + } + } else { + if (y0 < z0) { + i1 = 0; + j1 = 0; + k1 = 1; + i2 = 0; + j22 = 1; + k22 = 1; + } else if (x0 < z0) { + i1 = 0; + j1 = 1; + k1 = 0; + i2 = 0; + j22 = 1; + k22 = 1; + } else { + i1 = 0; + j1 = 1; + k1 = 0; + i2 = 1; + j22 = 1; + k22 = 0; + } + } + const x1 = x0 - i1 + G3; + const y1 = y0 - j1 + G3; + const z1 = z0 - k1 + G3; + const x2 = x0 - i2 + 2 * G3; + const y2 = y0 - j22 + 2 * G3; + const z2 = z0 - k22 + 2 * G3; + const x3 = x0 - 1 + 3 * G3; + const y3 = y0 - 1 + 3 * G3; + const z3 = z0 - 1 + 3 * G3; + const ii = i & 255; + const jj = j2 & 255; + const kk = k3 & 255; + const gi0 = this.perm[ii + this.perm[jj + this.perm[kk]]] % 12; + const gi1 = this.perm[ii + i1 + this.perm[jj + j1 + this.perm[kk + k1]]] % 12; + const gi2 = this.perm[ii + i2 + this.perm[jj + j22 + this.perm[kk + k22]]] % 12; + const gi3 = this.perm[ii + 1 + this.perm[jj + 1 + this.perm[kk + 1]]] % 12; + let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0; + if (t0 < 0) + n0 = 0; + else { + t0 *= t0; + n0 = t0 * t0 * this.dot3(this.grad3[gi0], x0, y0, z0); + } + let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1; + if (t1 < 0) + n1 = 0; + else { + t1 *= t1; + n1 = t1 * t1 * this.dot3(this.grad3[gi1], x1, y1, z1); + } + let t22 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2; + if (t22 < 0) + n2 = 0; + else { + t22 *= t22; + n2 = t22 * t22 * this.dot3(this.grad3[gi2], x2, y2, z2); + } + let t32 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3; + if (t32 < 0) + n3 = 0; + else { + t32 *= t32; + n3 = t32 * t32 * this.dot3(this.grad3[gi3], x3, y3, z3); + } + return 32 * (n0 + n1 + n2 + n3); + } + noise4d(x2, y, z, w) { + const grad4 = this.grad4; + const simplex = this.simplex; + const perm = this.perm; + const F4 = (Math.sqrt(5) - 1) / 4; + const G4 = (5 - Math.sqrt(5)) / 20; + let n0; + let n1; + let n2; + let n3; + let n4; + const s = (x2 + y + z + w) * F4; + const i = Math.floor(x2 + s); + const j2 = Math.floor(y + s); + const k3 = Math.floor(z + s); + const l2 = Math.floor(w + s); + const t3 = (i + j2 + k3 + l2) * G4; + const X0 = i - t3; + const Y0 = j2 - t3; + const Z0 = k3 - t3; + const W0 = l2 - t3; + const x0 = x2 - X0; + const y0 = y - Y0; + const z0 = z - Z0; + const w0 = w - W0; + const c1 = x0 > y0 ? 32 : 0; + const c2 = x0 > z0 ? 16 : 0; + const c3 = y0 > z0 ? 8 : 0; + const c4 = x0 > w0 ? 4 : 0; + const c5 = y0 > w0 ? 2 : 0; + const c6 = z0 > w0 ? 1 : 0; + const c = c1 + c2 + c3 + c4 + c5 + c6; + const i1 = simplex[c][0] >= 3 ? 1 : 0; + const j1 = simplex[c][1] >= 3 ? 1 : 0; + const k1 = simplex[c][2] >= 3 ? 1 : 0; + const l1 = simplex[c][3] >= 3 ? 1 : 0; + const i2 = simplex[c][0] >= 2 ? 1 : 0; + const j22 = simplex[c][1] >= 2 ? 1 : 0; + const k22 = simplex[c][2] >= 2 ? 1 : 0; + const l22 = simplex[c][3] >= 2 ? 1 : 0; + const i3 = simplex[c][0] >= 1 ? 1 : 0; + const j3 = simplex[c][1] >= 1 ? 1 : 0; + const k32 = simplex[c][2] >= 1 ? 1 : 0; + const l3 = simplex[c][3] >= 1 ? 1 : 0; + const x1 = x0 - i1 + G4; + const y1 = y0 - j1 + G4; + const z1 = z0 - k1 + G4; + const w1 = w0 - l1 + G4; + const x22 = x0 - i2 + 2 * G4; + const y2 = y0 - j22 + 2 * G4; + const z2 = z0 - k22 + 2 * G4; + const w2 = w0 - l22 + 2 * G4; + const x3 = x0 - i3 + 3 * G4; + const y3 = y0 - j3 + 3 * G4; + const z3 = z0 - k32 + 3 * G4; + const w3 = w0 - l3 + 3 * G4; + const x4 = x0 - 1 + 4 * G4; + const y4 = y0 - 1 + 4 * G4; + const z4 = z0 - 1 + 4 * G4; + const w4 = w0 - 1 + 4 * G4; + const ii = i & 255; + const jj = j2 & 255; + const kk = k3 & 255; + const ll = l2 & 255; + const gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; + const gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; + const gi2 = perm[ii + i2 + perm[jj + j22 + perm[kk + k22 + perm[ll + l22]]]] % 32; + const gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k32 + perm[ll + l3]]]] % 32; + const gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; + let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; + if (t0 < 0) + n0 = 0; + else { + t0 *= t0; + n0 = t0 * t0 * this.dot4(grad4[gi0], x0, y0, z0, w0); + } + let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; + if (t1 < 0) + n1 = 0; + else { + t1 *= t1; + n1 = t1 * t1 * this.dot4(grad4[gi1], x1, y1, z1, w1); + } + let t22 = 0.6 - x22 * x22 - y2 * y2 - z2 * z2 - w2 * w2; + if (t22 < 0) + n2 = 0; + else { + t22 *= t22; + n2 = t22 * t22 * this.dot4(grad4[gi2], x22, y2, z2, w2); + } + let t32 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; + if (t32 < 0) + n3 = 0; + else { + t32 *= t32; + n3 = t32 * t32 * this.dot4(grad4[gi3], x3, y3, z3, w3); + } + let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; + if (t4 < 0) + n4 = 0; + else { + t4 *= t4; + n4 = t4 * t4 * this.dot4(grad4[gi4], x4, y4, z4, w4); + } + return 27 * (n0 + n1 + n2 + n3 + n4); + } +} +// node_modules/three/examples/jsm/misc/ConvexObjectBreaker.js +var _v17 = new Vector3; +// node_modules/three/examples/jsm/misc/Gyroscope.js +var _translationObject = new Vector3; +var _quaternionObject = new Quaternion; +var _scaleObject = new Vector3; +var _translationWorld = new Vector3; +var _quaternionWorld = new Quaternion; +var _scaleWorld = new Vector3; +// node_modules/three/examples/jsm/modifiers/CurveModifier.js +var matrix2 = new Matrix4; +// node_modules/three/examples/jsm/modifiers/EdgeSplitModifier.js +var _A = new Vector3; +var _B = new Vector3; +var _C = new Vector3; +// node_modules/three/examples/jsm/modifiers/SimplifyModifier.js +var _cb2 = new Vector3; +var _ab2 = new Vector3; +// node_modules/three/examples/jsm/objects/Lensflare.js +class Lensflare extends Mesh { + constructor() { + super(Lensflare.Geometry, new MeshBasicMaterial({ opacity: 0, transparent: true })); + this.isLensflare = true; + this.type = "Lensflare"; + this.frustumCulled = false; + this.renderOrder = Infinity; + const positionScreen = new Vector3; + const positionView = new Vector3; + const tempMap = new FramebufferTexture(16, 16); + const occlusionMap = new FramebufferTexture(16, 16); + let currentType = UnsignedByteType; + const geometry = Lensflare.Geometry; + const material1a = new RawShaderMaterial({ + uniforms: { + scale: { value: null }, + screenPosition: { value: null } + }, + vertexShader: ` + + precision highp float; + + uniform vec3 screenPosition; + uniform vec2 scale; + + attribute vec3 position; + + void main() { + + gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); + + }`, + fragmentShader: ` + + precision highp float; + + void main() { + + gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 ); + + }`, + depthTest: true, + depthWrite: false, + transparent: false + }); + const material1b = new RawShaderMaterial({ + uniforms: { + map: { value: tempMap }, + scale: { value: null }, + screenPosition: { value: null } + }, + vertexShader: ` + + precision highp float; + + uniform vec3 screenPosition; + uniform vec2 scale; + + attribute vec3 position; + attribute vec2 uv; + + varying vec2 vUV; + + void main() { + + vUV = uv; + + gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); + + }`, + fragmentShader: ` + + precision highp float; + + uniform sampler2D map; + + varying vec2 vUV; + + void main() { + + gl_FragColor = texture2D( map, vUV ); + + }`, + depthTest: false, + depthWrite: false, + transparent: false + }); + const mesh1 = new Mesh(geometry, material1a); + const elements = []; + const shader = LensflareElement.Shader; + const material2 = new RawShaderMaterial({ + name: shader.name, + uniforms: { + map: { value: null }, + occlusionMap: { value: occlusionMap }, + color: { value: new Color(16777215) }, + scale: { value: new Vector2 }, + screenPosition: { value: new Vector3 } + }, + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + blending: AdditiveBlending, + transparent: true, + depthWrite: false + }); + const mesh2 = new Mesh(geometry, material2); + this.addElement = function(element) { + elements.push(element); + }; + const scale2 = new Vector2; + const screenPositionPixels = new Vector2; + const validArea = new Box2; + const viewport = new Vector4; + this.onBeforeRender = function(renderer2, scene, camera) { + renderer2.getCurrentViewport(viewport); + const renderTarget = renderer2.getRenderTarget(); + const type = renderTarget !== null ? renderTarget.texture.type : UnsignedByteType; + if (currentType !== type) { + tempMap.dispose(); + occlusionMap.dispose(); + tempMap.type = occlusionMap.type = type; + currentType = type; + } + const invAspect = viewport.w / viewport.z; + const halfViewportWidth = viewport.z / 2; + const halfViewportHeight = viewport.w / 2; + let size2 = 16 / viewport.w; + scale2.set(size2 * invAspect, size2); + validArea.min.set(viewport.x, viewport.y); + validArea.max.set(viewport.x + (viewport.z - 16), viewport.y + (viewport.w - 16)); + positionView.setFromMatrixPosition(this.matrixWorld); + positionView.applyMatrix4(camera.matrixWorldInverse); + if (positionView.z > 0) + return; + positionScreen.copy(positionView).applyMatrix4(camera.projectionMatrix); + screenPositionPixels.x = viewport.x + positionScreen.x * halfViewportWidth + halfViewportWidth - 8; + screenPositionPixels.y = viewport.y + positionScreen.y * halfViewportHeight + halfViewportHeight - 8; + if (validArea.containsPoint(screenPositionPixels)) { + renderer2.copyFramebufferToTexture(tempMap, screenPositionPixels); + let uniforms = material1a.uniforms; + uniforms["scale"].value = scale2; + uniforms["screenPosition"].value = positionScreen; + renderer2.renderBufferDirect(camera, null, geometry, material1a, mesh1, null); + renderer2.copyFramebufferToTexture(occlusionMap, screenPositionPixels); + uniforms = material1b.uniforms; + uniforms["scale"].value = scale2; + uniforms["screenPosition"].value = positionScreen; + renderer2.renderBufferDirect(camera, null, geometry, material1b, mesh1, null); + const vecX = -positionScreen.x * 2; + const vecY = -positionScreen.y * 2; + for (let i = 0, l2 = elements.length;i < l2; i++) { + const element = elements[i]; + const uniforms2 = material2.uniforms; + uniforms2["color"].value.copy(element.color); + uniforms2["map"].value = element.texture; + uniforms2["screenPosition"].value.x = positionScreen.x + vecX * element.distance; + uniforms2["screenPosition"].value.y = positionScreen.y + vecY * element.distance; + size2 = element.size / viewport.w; + const invAspect2 = viewport.w / viewport.z; + uniforms2["scale"].value.set(size2 * invAspect2, size2); + material2.uniformsNeedUpdate = true; + renderer2.renderBufferDirect(camera, null, geometry, material2, mesh2, null); + } + } + }; + this.dispose = function() { + material1a.dispose(); + material1b.dispose(); + material2.dispose(); + tempMap.dispose(); + occlusionMap.dispose(); + for (let i = 0, l2 = elements.length;i < l2; i++) { + elements[i].texture.dispose(); + } + }; + } +} + +class LensflareElement { + constructor(texture, size2 = 1, distance = 0, color = new Color(16777215)) { + this.texture = texture; + this.size = size2; + this.distance = distance; + this.color = color; + } +} +LensflareElement.Shader = { + name: "LensflareElementShader", + uniforms: { + map: { value: null }, + occlusionMap: { value: null }, + color: { value: null }, + scale: { value: null }, + screenPosition: { value: null } + }, + vertexShader: ` + + precision highp float; + + uniform vec3 screenPosition; + uniform vec2 scale; + + uniform sampler2D occlusionMap; + + attribute vec3 position; + attribute vec2 uv; + + varying vec2 vUV; + varying float vVisibility; + + void main() { + + vUV = uv; + + vec2 pos = position.xy; + + vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ); + visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) ); + visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) ); + visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ); + visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) ); + visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ); + visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) ); + visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ); + visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) ); + + vVisibility = visibility.r / 9.0; + vVisibility *= 1.0 - visibility.g / 9.0; + vVisibility *= visibility.b / 9.0; + + gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 ); + + }`, + fragmentShader: ` + + precision highp float; + + uniform sampler2D map; + uniform vec3 color; + + varying vec2 vUV; + varying float vVisibility; + + void main() { + + vec4 texture = texture2D( map, vUV ); + texture.a *= vVisibility; + gl_FragColor = texture; + gl_FragColor.rgb *= color; + + }` +}; +Lensflare.Geometry = function() { + const geometry = new BufferGeometry; + const float32Array = new Float32Array([ + -1, + -1, + 0, + 0, + 0, + 1, + -1, + 0, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + -1, + 1, + 0, + 0, + 1 + ]); + const interleavedBuffer = new InterleavedBuffer(float32Array, 5); + geometry.setIndex([0, 1, 2, 0, 2, 3]); + geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false)); + geometry.setAttribute("uv", new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false)); + return geometry; +}(); +// node_modules/three/examples/jsm/objects/MarchingCubes.js +var edgeTable = new Int32Array([ + 0, + 265, + 515, + 778, + 1030, + 1295, + 1541, + 1804, + 2060, + 2309, + 2575, + 2822, + 3082, + 3331, + 3593, + 3840, + 400, + 153, + 915, + 666, + 1430, + 1183, + 1941, + 1692, + 2460, + 2197, + 2975, + 2710, + 3482, + 3219, + 3993, + 3728, + 560, + 825, + 51, + 314, + 1590, + 1855, + 1077, + 1340, + 2620, + 2869, + 2111, + 2358, + 3642, + 3891, + 3129, + 3376, + 928, + 681, + 419, + 170, + 1958, + 1711, + 1445, + 1196, + 2988, + 2725, + 2479, + 2214, + 4010, + 3747, + 3497, + 3232, + 1120, + 1385, + 1635, + 1898, + 102, + 367, + 613, + 876, + 3180, + 3429, + 3695, + 3942, + 2154, + 2403, + 2665, + 2912, + 1520, + 1273, + 2035, + 1786, + 502, + 255, + 1013, + 764, + 3580, + 3317, + 4095, + 3830, + 2554, + 2291, + 3065, + 2800, + 1616, + 1881, + 1107, + 1370, + 598, + 863, + 85, + 348, + 3676, + 3925, + 3167, + 3414, + 2650, + 2899, + 2137, + 2384, + 1984, + 1737, + 1475, + 1226, + 966, + 719, + 453, + 204, + 4044, + 3781, + 3535, + 3270, + 3018, + 2755, + 2505, + 2240, + 2240, + 2505, + 2755, + 3018, + 3270, + 3535, + 3781, + 4044, + 204, + 453, + 719, + 966, + 1226, + 1475, + 1737, + 1984, + 2384, + 2137, + 2899, + 2650, + 3414, + 3167, + 3925, + 3676, + 348, + 85, + 863, + 598, + 1370, + 1107, + 1881, + 1616, + 2800, + 3065, + 2291, + 2554, + 3830, + 4095, + 3317, + 3580, + 764, + 1013, + 255, + 502, + 1786, + 2035, + 1273, + 1520, + 2912, + 2665, + 2403, + 2154, + 3942, + 3695, + 3429, + 3180, + 876, + 613, + 367, + 102, + 1898, + 1635, + 1385, + 1120, + 3232, + 3497, + 3747, + 4010, + 2214, + 2479, + 2725, + 2988, + 1196, + 1445, + 1711, + 1958, + 170, + 419, + 681, + 928, + 3376, + 3129, + 3891, + 3642, + 2358, + 2111, + 2869, + 2620, + 1340, + 1077, + 1855, + 1590, + 314, + 51, + 825, + 560, + 3728, + 3993, + 3219, + 3482, + 2710, + 2975, + 2197, + 2460, + 1692, + 1941, + 1183, + 1430, + 666, + 915, + 153, + 400, + 3840, + 3593, + 3331, + 3082, + 2822, + 2575, + 2309, + 2060, + 1804, + 1541, + 1295, + 1030, + 778, + 515, + 265, + 0 +]); +var triTable = new Int32Array([ + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 8, + 3, + 9, + 8, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 1, + 2, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 2, + 10, + 0, + 2, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 8, + 3, + 2, + 10, + 8, + 10, + 9, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 11, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 11, + 2, + 8, + 11, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 9, + 0, + 2, + 3, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 11, + 2, + 1, + 9, + 11, + 9, + 8, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 10, + 1, + 11, + 10, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 10, + 1, + 0, + 8, + 10, + 8, + 11, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 9, + 0, + 3, + 11, + 9, + 11, + 10, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 8, + 10, + 10, + 8, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 7, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 3, + 0, + 7, + 3, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 8, + 4, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 1, + 9, + 4, + 7, + 1, + 7, + 3, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 8, + 4, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 4, + 7, + 3, + 0, + 4, + 1, + 2, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 2, + 10, + 9, + 0, + 2, + 8, + 4, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 10, + 9, + 2, + 9, + 7, + 2, + 7, + 3, + 7, + 9, + 4, + -1, + -1, + -1, + -1, + 8, + 4, + 7, + 3, + 11, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 4, + 7, + 11, + 2, + 4, + 2, + 0, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 0, + 1, + 8, + 4, + 7, + 2, + 3, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 7, + 11, + 9, + 4, + 11, + 9, + 11, + 2, + 9, + 2, + 1, + -1, + -1, + -1, + -1, + 3, + 10, + 1, + 3, + 11, + 10, + 7, + 8, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 11, + 10, + 1, + 4, + 11, + 1, + 0, + 4, + 7, + 11, + 4, + -1, + -1, + -1, + -1, + 4, + 7, + 8, + 9, + 0, + 11, + 9, + 11, + 10, + 11, + 0, + 3, + -1, + -1, + -1, + -1, + 4, + 7, + 11, + 4, + 11, + 9, + 9, + 11, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + 0, + 8, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 5, + 4, + 1, + 5, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 5, + 4, + 8, + 3, + 5, + 3, + 1, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 9, + 5, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 8, + 1, + 2, + 10, + 4, + 9, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 2, + 10, + 5, + 4, + 2, + 4, + 0, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 10, + 5, + 3, + 2, + 5, + 3, + 5, + 4, + 3, + 4, + 8, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + 2, + 3, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 11, + 2, + 0, + 8, + 11, + 4, + 9, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 5, + 4, + 0, + 1, + 5, + 2, + 3, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 1, + 5, + 2, + 5, + 8, + 2, + 8, + 11, + 4, + 8, + 5, + -1, + -1, + -1, + -1, + 10, + 3, + 11, + 10, + 1, + 3, + 9, + 5, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 9, + 5, + 0, + 8, + 1, + 8, + 10, + 1, + 8, + 11, + 10, + -1, + -1, + -1, + -1, + 5, + 4, + 0, + 5, + 0, + 11, + 5, + 11, + 10, + 11, + 0, + 3, + -1, + -1, + -1, + -1, + 5, + 4, + 8, + 5, + 8, + 10, + 10, + 8, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 7, + 8, + 5, + 7, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 3, + 0, + 9, + 5, + 3, + 5, + 7, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 7, + 8, + 0, + 1, + 7, + 1, + 5, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 5, + 3, + 3, + 5, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 7, + 8, + 9, + 5, + 7, + 10, + 1, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 1, + 2, + 9, + 5, + 0, + 5, + 3, + 0, + 5, + 7, + 3, + -1, + -1, + -1, + -1, + 8, + 0, + 2, + 8, + 2, + 5, + 8, + 5, + 7, + 10, + 5, + 2, + -1, + -1, + -1, + -1, + 2, + 10, + 5, + 2, + 5, + 3, + 3, + 5, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 9, + 5, + 7, + 8, + 9, + 3, + 11, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 7, + 9, + 7, + 2, + 9, + 2, + 0, + 2, + 7, + 11, + -1, + -1, + -1, + -1, + 2, + 3, + 11, + 0, + 1, + 8, + 1, + 7, + 8, + 1, + 5, + 7, + -1, + -1, + -1, + -1, + 11, + 2, + 1, + 11, + 1, + 7, + 7, + 1, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 8, + 8, + 5, + 7, + 10, + 1, + 3, + 10, + 3, + 11, + -1, + -1, + -1, + -1, + 5, + 7, + 0, + 5, + 0, + 9, + 7, + 11, + 0, + 1, + 0, + 10, + 11, + 10, + 0, + -1, + 11, + 10, + 0, + 11, + 0, + 3, + 10, + 5, + 0, + 8, + 0, + 7, + 5, + 7, + 0, + -1, + 11, + 10, + 5, + 7, + 11, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 6, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 0, + 1, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 8, + 3, + 1, + 9, + 8, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 6, + 5, + 2, + 6, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 6, + 5, + 1, + 2, + 6, + 3, + 0, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 6, + 5, + 9, + 0, + 6, + 0, + 2, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 9, + 8, + 5, + 8, + 2, + 5, + 2, + 6, + 3, + 2, + 8, + -1, + -1, + -1, + -1, + 2, + 3, + 11, + 10, + 6, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 0, + 8, + 11, + 2, + 0, + 10, + 6, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 2, + 3, + 11, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 10, + 6, + 1, + 9, + 2, + 9, + 11, + 2, + 9, + 8, + 11, + -1, + -1, + -1, + -1, + 6, + 3, + 11, + 6, + 5, + 3, + 5, + 1, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 11, + 0, + 11, + 5, + 0, + 5, + 1, + 5, + 11, + 6, + -1, + -1, + -1, + -1, + 3, + 11, + 6, + 0, + 3, + 6, + 0, + 6, + 5, + 0, + 5, + 9, + -1, + -1, + -1, + -1, + 6, + 5, + 9, + 6, + 9, + 11, + 11, + 9, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 10, + 6, + 4, + 7, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 3, + 0, + 4, + 7, + 3, + 6, + 5, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 9, + 0, + 5, + 10, + 6, + 8, + 4, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 6, + 5, + 1, + 9, + 7, + 1, + 7, + 3, + 7, + 9, + 4, + -1, + -1, + -1, + -1, + 6, + 1, + 2, + 6, + 5, + 1, + 4, + 7, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 5, + 5, + 2, + 6, + 3, + 0, + 4, + 3, + 4, + 7, + -1, + -1, + -1, + -1, + 8, + 4, + 7, + 9, + 0, + 5, + 0, + 6, + 5, + 0, + 2, + 6, + -1, + -1, + -1, + -1, + 7, + 3, + 9, + 7, + 9, + 4, + 3, + 2, + 9, + 5, + 9, + 6, + 2, + 6, + 9, + -1, + 3, + 11, + 2, + 7, + 8, + 4, + 10, + 6, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 10, + 6, + 4, + 7, + 2, + 4, + 2, + 0, + 2, + 7, + 11, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 4, + 7, + 8, + 2, + 3, + 11, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + 9, + 2, + 1, + 9, + 11, + 2, + 9, + 4, + 11, + 7, + 11, + 4, + 5, + 10, + 6, + -1, + 8, + 4, + 7, + 3, + 11, + 5, + 3, + 5, + 1, + 5, + 11, + 6, + -1, + -1, + -1, + -1, + 5, + 1, + 11, + 5, + 11, + 6, + 1, + 0, + 11, + 7, + 11, + 4, + 0, + 4, + 11, + -1, + 0, + 5, + 9, + 0, + 6, + 5, + 0, + 3, + 6, + 11, + 6, + 3, + 8, + 4, + 7, + -1, + 6, + 5, + 9, + 6, + 9, + 11, + 4, + 7, + 9, + 7, + 11, + 9, + -1, + -1, + -1, + -1, + 10, + 4, + 9, + 6, + 4, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 10, + 6, + 4, + 9, + 10, + 0, + 8, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 0, + 1, + 10, + 6, + 0, + 6, + 4, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 3, + 1, + 8, + 1, + 6, + 8, + 6, + 4, + 6, + 1, + 10, + -1, + -1, + -1, + -1, + 1, + 4, + 9, + 1, + 2, + 4, + 2, + 6, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 8, + 1, + 2, + 9, + 2, + 4, + 9, + 2, + 6, + 4, + -1, + -1, + -1, + -1, + 0, + 2, + 4, + 4, + 2, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 3, + 2, + 8, + 2, + 4, + 4, + 2, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 4, + 9, + 10, + 6, + 4, + 11, + 2, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 2, + 2, + 8, + 11, + 4, + 9, + 10, + 4, + 10, + 6, + -1, + -1, + -1, + -1, + 3, + 11, + 2, + 0, + 1, + 6, + 0, + 6, + 4, + 6, + 1, + 10, + -1, + -1, + -1, + -1, + 6, + 4, + 1, + 6, + 1, + 10, + 4, + 8, + 1, + 2, + 1, + 11, + 8, + 11, + 1, + -1, + 9, + 6, + 4, + 9, + 3, + 6, + 9, + 1, + 3, + 11, + 6, + 3, + -1, + -1, + -1, + -1, + 8, + 11, + 1, + 8, + 1, + 0, + 11, + 6, + 1, + 9, + 1, + 4, + 6, + 4, + 1, + -1, + 3, + 11, + 6, + 3, + 6, + 0, + 0, + 6, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 6, + 4, + 8, + 11, + 6, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 10, + 6, + 7, + 8, + 10, + 8, + 9, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 7, + 3, + 0, + 10, + 7, + 0, + 9, + 10, + 6, + 7, + 10, + -1, + -1, + -1, + -1, + 10, + 6, + 7, + 1, + 10, + 7, + 1, + 7, + 8, + 1, + 8, + 0, + -1, + -1, + -1, + -1, + 10, + 6, + 7, + 10, + 7, + 1, + 1, + 7, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 6, + 1, + 6, + 8, + 1, + 8, + 9, + 8, + 6, + 7, + -1, + -1, + -1, + -1, + 2, + 6, + 9, + 2, + 9, + 1, + 6, + 7, + 9, + 0, + 9, + 3, + 7, + 3, + 9, + -1, + 7, + 8, + 0, + 7, + 0, + 6, + 6, + 0, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 3, + 2, + 6, + 7, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 3, + 11, + 10, + 6, + 8, + 10, + 8, + 9, + 8, + 6, + 7, + -1, + -1, + -1, + -1, + 2, + 0, + 7, + 2, + 7, + 11, + 0, + 9, + 7, + 6, + 7, + 10, + 9, + 10, + 7, + -1, + 1, + 8, + 0, + 1, + 7, + 8, + 1, + 10, + 7, + 6, + 7, + 10, + 2, + 3, + 11, + -1, + 11, + 2, + 1, + 11, + 1, + 7, + 10, + 6, + 1, + 6, + 7, + 1, + -1, + -1, + -1, + -1, + 8, + 9, + 6, + 8, + 6, + 7, + 9, + 1, + 6, + 11, + 6, + 3, + 1, + 3, + 6, + -1, + 0, + 9, + 1, + 11, + 6, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 8, + 0, + 7, + 0, + 6, + 3, + 11, + 0, + 11, + 6, + 0, + -1, + -1, + -1, + -1, + 7, + 11, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 6, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 8, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 1, + 9, + 8, + 3, + 1, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 1, + 2, + 6, + 11, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 3, + 0, + 8, + 6, + 11, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 9, + 0, + 2, + 10, + 9, + 6, + 11, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 6, + 11, + 7, + 2, + 10, + 3, + 10, + 8, + 3, + 10, + 9, + 8, + -1, + -1, + -1, + -1, + 7, + 2, + 3, + 6, + 2, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 0, + 8, + 7, + 6, + 0, + 6, + 2, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 7, + 6, + 2, + 3, + 7, + 0, + 1, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 6, + 2, + 1, + 8, + 6, + 1, + 9, + 8, + 8, + 7, + 6, + -1, + -1, + -1, + -1, + 10, + 7, + 6, + 10, + 1, + 7, + 1, + 3, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 7, + 6, + 1, + 7, + 10, + 1, + 8, + 7, + 1, + 0, + 8, + -1, + -1, + -1, + -1, + 0, + 3, + 7, + 0, + 7, + 10, + 0, + 10, + 9, + 6, + 10, + 7, + -1, + -1, + -1, + -1, + 7, + 6, + 10, + 7, + 10, + 8, + 8, + 10, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 6, + 8, + 4, + 11, + 8, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 6, + 11, + 3, + 0, + 6, + 0, + 4, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 6, + 11, + 8, + 4, + 6, + 9, + 0, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 4, + 6, + 9, + 6, + 3, + 9, + 3, + 1, + 11, + 3, + 6, + -1, + -1, + -1, + -1, + 6, + 8, + 4, + 6, + 11, + 8, + 2, + 10, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 3, + 0, + 11, + 0, + 6, + 11, + 0, + 4, + 6, + -1, + -1, + -1, + -1, + 4, + 11, + 8, + 4, + 6, + 11, + 0, + 2, + 9, + 2, + 10, + 9, + -1, + -1, + -1, + -1, + 10, + 9, + 3, + 10, + 3, + 2, + 9, + 4, + 3, + 11, + 3, + 6, + 4, + 6, + 3, + -1, + 8, + 2, + 3, + 8, + 4, + 2, + 4, + 6, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 4, + 2, + 4, + 6, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 9, + 0, + 2, + 3, + 4, + 2, + 4, + 6, + 4, + 3, + 8, + -1, + -1, + -1, + -1, + 1, + 9, + 4, + 1, + 4, + 2, + 2, + 4, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 1, + 3, + 8, + 6, + 1, + 8, + 4, + 6, + 6, + 10, + 1, + -1, + -1, + -1, + -1, + 10, + 1, + 0, + 10, + 0, + 6, + 6, + 0, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 6, + 3, + 4, + 3, + 8, + 6, + 10, + 3, + 0, + 3, + 9, + 10, + 9, + 3, + -1, + 10, + 9, + 4, + 6, + 10, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 9, + 5, + 7, + 6, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 4, + 9, + 5, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 0, + 1, + 5, + 4, + 0, + 7, + 6, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 7, + 6, + 8, + 3, + 4, + 3, + 5, + 4, + 3, + 1, + 5, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + 10, + 1, + 2, + 7, + 6, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 6, + 11, + 7, + 1, + 2, + 10, + 0, + 8, + 3, + 4, + 9, + 5, + -1, + -1, + -1, + -1, + 7, + 6, + 11, + 5, + 4, + 10, + 4, + 2, + 10, + 4, + 0, + 2, + -1, + -1, + -1, + -1, + 3, + 4, + 8, + 3, + 5, + 4, + 3, + 2, + 5, + 10, + 5, + 2, + 11, + 7, + 6, + -1, + 7, + 2, + 3, + 7, + 6, + 2, + 5, + 4, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + 0, + 8, + 6, + 0, + 6, + 2, + 6, + 8, + 7, + -1, + -1, + -1, + -1, + 3, + 6, + 2, + 3, + 7, + 6, + 1, + 5, + 0, + 5, + 4, + 0, + -1, + -1, + -1, + -1, + 6, + 2, + 8, + 6, + 8, + 7, + 2, + 1, + 8, + 4, + 8, + 5, + 1, + 5, + 8, + -1, + 9, + 5, + 4, + 10, + 1, + 6, + 1, + 7, + 6, + 1, + 3, + 7, + -1, + -1, + -1, + -1, + 1, + 6, + 10, + 1, + 7, + 6, + 1, + 0, + 7, + 8, + 7, + 0, + 9, + 5, + 4, + -1, + 4, + 0, + 10, + 4, + 10, + 5, + 0, + 3, + 10, + 6, + 10, + 7, + 3, + 7, + 10, + -1, + 7, + 6, + 10, + 7, + 10, + 8, + 5, + 4, + 10, + 4, + 8, + 10, + -1, + -1, + -1, + -1, + 6, + 9, + 5, + 6, + 11, + 9, + 11, + 8, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 6, + 11, + 0, + 6, + 3, + 0, + 5, + 6, + 0, + 9, + 5, + -1, + -1, + -1, + -1, + 0, + 11, + 8, + 0, + 5, + 11, + 0, + 1, + 5, + 5, + 6, + 11, + -1, + -1, + -1, + -1, + 6, + 11, + 3, + 6, + 3, + 5, + 5, + 3, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 9, + 5, + 11, + 9, + 11, + 8, + 11, + 5, + 6, + -1, + -1, + -1, + -1, + 0, + 11, + 3, + 0, + 6, + 11, + 0, + 9, + 6, + 5, + 6, + 9, + 1, + 2, + 10, + -1, + 11, + 8, + 5, + 11, + 5, + 6, + 8, + 0, + 5, + 10, + 5, + 2, + 0, + 2, + 5, + -1, + 6, + 11, + 3, + 6, + 3, + 5, + 2, + 10, + 3, + 10, + 5, + 3, + -1, + -1, + -1, + -1, + 5, + 8, + 9, + 5, + 2, + 8, + 5, + 6, + 2, + 3, + 8, + 2, + -1, + -1, + -1, + -1, + 9, + 5, + 6, + 9, + 6, + 0, + 0, + 6, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 5, + 8, + 1, + 8, + 0, + 5, + 6, + 8, + 3, + 8, + 2, + 6, + 2, + 8, + -1, + 1, + 5, + 6, + 2, + 1, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 3, + 6, + 1, + 6, + 10, + 3, + 8, + 6, + 5, + 6, + 9, + 8, + 9, + 6, + -1, + 10, + 1, + 0, + 10, + 0, + 6, + 9, + 5, + 0, + 5, + 6, + 0, + -1, + -1, + -1, + -1, + 0, + 3, + 8, + 5, + 6, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 5, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 5, + 10, + 7, + 5, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 5, + 10, + 11, + 7, + 5, + 8, + 3, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 11, + 7, + 5, + 10, + 11, + 1, + 9, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 7, + 5, + 10, + 11, + 7, + 9, + 8, + 1, + 8, + 3, + 1, + -1, + -1, + -1, + -1, + 11, + 1, + 2, + 11, + 7, + 1, + 7, + 5, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 1, + 2, + 7, + 1, + 7, + 5, + 7, + 2, + 11, + -1, + -1, + -1, + -1, + 9, + 7, + 5, + 9, + 2, + 7, + 9, + 0, + 2, + 2, + 11, + 7, + -1, + -1, + -1, + -1, + 7, + 5, + 2, + 7, + 2, + 11, + 5, + 9, + 2, + 3, + 2, + 8, + 9, + 8, + 2, + -1, + 2, + 5, + 10, + 2, + 3, + 5, + 3, + 7, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 2, + 0, + 8, + 5, + 2, + 8, + 7, + 5, + 10, + 2, + 5, + -1, + -1, + -1, + -1, + 9, + 0, + 1, + 5, + 10, + 3, + 5, + 3, + 7, + 3, + 10, + 2, + -1, + -1, + -1, + -1, + 9, + 8, + 2, + 9, + 2, + 1, + 8, + 7, + 2, + 10, + 2, + 5, + 7, + 5, + 2, + -1, + 1, + 3, + 5, + 3, + 7, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 7, + 0, + 7, + 1, + 1, + 7, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 0, + 3, + 9, + 3, + 5, + 5, + 3, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 8, + 7, + 5, + 9, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 8, + 4, + 5, + 10, + 8, + 10, + 11, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 0, + 4, + 5, + 11, + 0, + 5, + 10, + 11, + 11, + 3, + 0, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 8, + 4, + 10, + 8, + 10, + 11, + 10, + 4, + 5, + -1, + -1, + -1, + -1, + 10, + 11, + 4, + 10, + 4, + 5, + 11, + 3, + 4, + 9, + 4, + 1, + 3, + 1, + 4, + -1, + 2, + 5, + 1, + 2, + 8, + 5, + 2, + 11, + 8, + 4, + 5, + 8, + -1, + -1, + -1, + -1, + 0, + 4, + 11, + 0, + 11, + 3, + 4, + 5, + 11, + 2, + 11, + 1, + 5, + 1, + 11, + -1, + 0, + 2, + 5, + 0, + 5, + 9, + 2, + 11, + 5, + 4, + 5, + 8, + 11, + 8, + 5, + -1, + 9, + 4, + 5, + 2, + 11, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 5, + 10, + 3, + 5, + 2, + 3, + 4, + 5, + 3, + 8, + 4, + -1, + -1, + -1, + -1, + 5, + 10, + 2, + 5, + 2, + 4, + 4, + 2, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 10, + 2, + 3, + 5, + 10, + 3, + 8, + 5, + 4, + 5, + 8, + 0, + 1, + 9, + -1, + 5, + 10, + 2, + 5, + 2, + 4, + 1, + 9, + 2, + 9, + 4, + 2, + -1, + -1, + -1, + -1, + 8, + 4, + 5, + 8, + 5, + 3, + 3, + 5, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 4, + 5, + 1, + 0, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 4, + 5, + 8, + 5, + 3, + 9, + 0, + 5, + 0, + 3, + 5, + -1, + -1, + -1, + -1, + 9, + 4, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 11, + 7, + 4, + 9, + 11, + 9, + 10, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 4, + 9, + 7, + 9, + 11, + 7, + 9, + 10, + 11, + -1, + -1, + -1, + -1, + 1, + 10, + 11, + 1, + 11, + 4, + 1, + 4, + 0, + 7, + 4, + 11, + -1, + -1, + -1, + -1, + 3, + 1, + 4, + 3, + 4, + 8, + 1, + 10, + 4, + 7, + 4, + 11, + 10, + 11, + 4, + -1, + 4, + 11, + 7, + 9, + 11, + 4, + 9, + 2, + 11, + 9, + 1, + 2, + -1, + -1, + -1, + -1, + 9, + 7, + 4, + 9, + 11, + 7, + 9, + 1, + 11, + 2, + 11, + 1, + 0, + 8, + 3, + -1, + 11, + 7, + 4, + 11, + 4, + 2, + 2, + 4, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 7, + 4, + 11, + 4, + 2, + 8, + 3, + 4, + 3, + 2, + 4, + -1, + -1, + -1, + -1, + 2, + 9, + 10, + 2, + 7, + 9, + 2, + 3, + 7, + 7, + 4, + 9, + -1, + -1, + -1, + -1, + 9, + 10, + 7, + 9, + 7, + 4, + 10, + 2, + 7, + 8, + 7, + 0, + 2, + 0, + 7, + -1, + 3, + 7, + 10, + 3, + 10, + 2, + 7, + 4, + 10, + 1, + 10, + 0, + 4, + 0, + 10, + -1, + 1, + 10, + 2, + 8, + 7, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 9, + 1, + 4, + 1, + 7, + 7, + 1, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 9, + 1, + 4, + 1, + 7, + 0, + 8, + 1, + 8, + 7, + 1, + -1, + -1, + -1, + -1, + 4, + 0, + 3, + 7, + 4, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 8, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 10, + 8, + 10, + 11, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 9, + 3, + 9, + 11, + 11, + 9, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 10, + 0, + 10, + 8, + 8, + 10, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 1, + 10, + 11, + 3, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 11, + 1, + 11, + 9, + 9, + 11, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 9, + 3, + 9, + 11, + 1, + 2, + 9, + 2, + 11, + 9, + -1, + -1, + -1, + -1, + 0, + 2, + 11, + 8, + 0, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 2, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 3, + 8, + 2, + 8, + 10, + 10, + 8, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 10, + 2, + 0, + 9, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 3, + 8, + 2, + 8, + 10, + 0, + 1, + 8, + 1, + 10, + 8, + -1, + -1, + -1, + -1, + 1, + 10, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 3, + 8, + 9, + 1, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 9, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 3, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1 +]); +// node_modules/three/examples/jsm/objects/Reflector.js +class Reflector extends Mesh { + constructor(geometry, options = {}) { + super(geometry); + this.isReflector = true; + this.type = "Reflector"; + this.camera = new PerspectiveCamera; + const scope = this; + const color = options.color !== undefined ? new Color(options.color) : new Color(8355711); + const textureWidth = options.textureWidth || 512; + const textureHeight = options.textureHeight || 512; + const clipBias = options.clipBias || 0; + const shader = options.shader || Reflector.ReflectorShader; + const multisample = options.multisample !== undefined ? options.multisample : 4; + const reflectorPlane = new Plane; + const normal = new Vector3; + const reflectorWorldPosition = new Vector3; + const cameraWorldPosition = new Vector3; + const rotationMatrix2 = new Matrix4; + const lookAtPosition = new Vector3(0, 0, -1); + const clipPlane = new Vector4; + const view = new Vector3; + const target = new Vector3; + const q2 = new Vector4; + const textureMatrix = new Matrix4; + const virtualCamera = this.camera; + const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, { samples: multisample, type: HalfFloatType }); + const material = new ShaderMaterial({ + name: shader.name !== undefined ? shader.name : "unspecified", + uniforms: UniformsUtils.clone(shader.uniforms), + fragmentShader: shader.fragmentShader, + vertexShader: shader.vertexShader + }); + material.uniforms["tDiffuse"].value = renderTarget.texture; + material.uniforms["color"].value = color; + material.uniforms["textureMatrix"].value = textureMatrix; + this.material = material; + this.onBeforeRender = function(renderer2, scene, camera) { + reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld); + cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); + rotationMatrix2.extractRotation(scope.matrixWorld); + normal.set(0, 0, 1); + normal.applyMatrix4(rotationMatrix2); + view.subVectors(reflectorWorldPosition, cameraWorldPosition); + if (view.dot(normal) > 0) + return; + view.reflect(normal).negate(); + view.add(reflectorWorldPosition); + rotationMatrix2.extractRotation(camera.matrixWorld); + lookAtPosition.set(0, 0, -1); + lookAtPosition.applyMatrix4(rotationMatrix2); + lookAtPosition.add(cameraWorldPosition); + target.subVectors(reflectorWorldPosition, lookAtPosition); + target.reflect(normal).negate(); + target.add(reflectorWorldPosition); + virtualCamera.position.copy(view); + virtualCamera.up.set(0, 1, 0); + virtualCamera.up.applyMatrix4(rotationMatrix2); + virtualCamera.up.reflect(normal); + virtualCamera.lookAt(target); + virtualCamera.far = camera.far; + virtualCamera.updateMatrixWorld(); + virtualCamera.projectionMatrix.copy(camera.projectionMatrix); + textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + textureMatrix.multiply(virtualCamera.projectionMatrix); + textureMatrix.multiply(virtualCamera.matrixWorldInverse); + textureMatrix.multiply(scope.matrixWorld); + reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition); + reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse); + clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant); + const projectionMatrix = virtualCamera.projectionMatrix; + q2.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; + q2.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; + q2.z = -1; + q2.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; + clipPlane.multiplyScalar(2 / clipPlane.dot(q2)); + projectionMatrix.elements[2] = clipPlane.x; + projectionMatrix.elements[6] = clipPlane.y; + projectionMatrix.elements[10] = clipPlane.z + 1 - clipBias; + projectionMatrix.elements[14] = clipPlane.w; + scope.visible = false; + const currentRenderTarget = renderer2.getRenderTarget(); + const currentXrEnabled = renderer2.xr.enabled; + const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate; + renderer2.xr.enabled = false; + renderer2.shadowMap.autoUpdate = false; + renderer2.setRenderTarget(renderTarget); + renderer2.state.buffers.depth.setMask(true); + if (renderer2.autoClear === false) + renderer2.clear(); + renderer2.render(scene, virtualCamera); + renderer2.xr.enabled = currentXrEnabled; + renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate; + renderer2.setRenderTarget(currentRenderTarget); + const viewport = camera.viewport; + if (viewport !== undefined) { + renderer2.state.viewport(viewport); + } + scope.visible = true; + }; + this.getRenderTarget = function() { + return renderTarget; + }; + this.dispose = function() { + renderTarget.dispose(); + scope.material.dispose(); + }; + } +} +Reflector.ReflectorShader = { + name: "ReflectorShader", + uniforms: { + color: { + value: null + }, + tDiffuse: { + value: null + }, + textureMatrix: { + value: null + } + }, + vertexShader: ` + uniform mat4 textureMatrix; + varying vec4 vUv; + + #include + #include + + void main() { + + vUv = textureMatrix * vec4( position, 1.0 ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + #include + + }`, + fragmentShader: ` + uniform vec3 color; + uniform sampler2D tDiffuse; + varying vec4 vUv; + + #include + + float blendOverlay( float base, float blend ) { + + return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); + + } + + vec3 blendOverlay( vec3 base, vec3 blend ) { + + return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); + + } + + void main() { + + #include + + vec4 base = texture2DProj( tDiffuse, vUv ); + gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); + + #include + #include + + }` +}; +// node_modules/three/examples/jsm/objects/ReflectorForSSRPass.js +class ReflectorForSSRPass extends Mesh { + constructor(geometry, options = {}) { + super(geometry); + this.isReflectorForSSRPass = true; + this.type = "ReflectorForSSRPass"; + const scope = this; + const color = options.color !== undefined ? new Color(options.color) : new Color(8355711); + const textureWidth = options.textureWidth || 512; + const textureHeight = options.textureHeight || 512; + const clipBias = options.clipBias || 0; + const shader = options.shader || ReflectorForSSRPass.ReflectorShader; + const useDepthTexture = options.useDepthTexture === true; + const yAxis2 = new Vector3(0, 1, 0); + const vecTemp0 = new Vector3; + const vecTemp1 = new Vector3; + scope.needsUpdate = false; + scope.maxDistance = ReflectorForSSRPass.ReflectorShader.uniforms.maxDistance.value; + scope.opacity = ReflectorForSSRPass.ReflectorShader.uniforms.opacity.value; + scope.color = color; + scope.resolution = options.resolution || new Vector2(window.innerWidth, window.innerHeight); + scope._distanceAttenuation = ReflectorForSSRPass.ReflectorShader.defines.DISTANCE_ATTENUATION; + Object.defineProperty(scope, "distanceAttenuation", { + get() { + return scope._distanceAttenuation; + }, + set(val2) { + if (scope._distanceAttenuation === val2) + return; + scope._distanceAttenuation = val2; + scope.material.defines.DISTANCE_ATTENUATION = val2; + scope.material.needsUpdate = true; + } + }); + scope._fresnel = ReflectorForSSRPass.ReflectorShader.defines.FRESNEL; + Object.defineProperty(scope, "fresnel", { + get() { + return scope._fresnel; + }, + set(val2) { + if (scope._fresnel === val2) + return; + scope._fresnel = val2; + scope.material.defines.FRESNEL = val2; + scope.material.needsUpdate = true; + } + }); + const normal = new Vector3; + const reflectorWorldPosition = new Vector3; + const cameraWorldPosition = new Vector3; + const rotationMatrix2 = new Matrix4; + const lookAtPosition = new Vector3(0, 0, -1); + const view = new Vector3; + const target = new Vector3; + const textureMatrix = new Matrix4; + const virtualCamera = new PerspectiveCamera; + let depthTexture; + if (useDepthTexture) { + depthTexture = new DepthTexture; + depthTexture.type = UnsignedShortType; + depthTexture.minFilter = NearestFilter; + depthTexture.magFilter = NearestFilter; + } + const parameters = { + depthTexture: useDepthTexture ? depthTexture : null, + type: HalfFloatType + }; + const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, parameters); + const material = new ShaderMaterial({ + name: shader.name !== undefined ? shader.name : "unspecified", + transparent: useDepthTexture, + defines: Object.assign({}, ReflectorForSSRPass.ReflectorShader.defines, { + useDepthTexture + }), + uniforms: UniformsUtils.clone(shader.uniforms), + fragmentShader: shader.fragmentShader, + vertexShader: shader.vertexShader + }); + material.uniforms["tDiffuse"].value = renderTarget.texture; + material.uniforms["color"].value = scope.color; + material.uniforms["textureMatrix"].value = textureMatrix; + if (useDepthTexture) { + material.uniforms["tDepth"].value = renderTarget.depthTexture; + } + this.material = material; + const globalPlane = new Plane(new Vector3(0, 1, 0), clipBias); + const globalPlanes = [globalPlane]; + this.doRender = function(renderer2, scene, camera) { + material.uniforms["maxDistance"].value = scope.maxDistance; + material.uniforms["color"].value = scope.color; + material.uniforms["opacity"].value = scope.opacity; + vecTemp0.copy(camera.position).normalize(); + vecTemp1.copy(vecTemp0).reflect(yAxis2); + material.uniforms["fresnelCoe"].value = (vecTemp0.dot(vecTemp1) + 1) / 2; + reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld); + cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); + rotationMatrix2.extractRotation(scope.matrixWorld); + normal.set(0, 0, 1); + normal.applyMatrix4(rotationMatrix2); + view.subVectors(reflectorWorldPosition, cameraWorldPosition); + if (view.dot(normal) > 0) + return; + view.reflect(normal).negate(); + view.add(reflectorWorldPosition); + rotationMatrix2.extractRotation(camera.matrixWorld); + lookAtPosition.set(0, 0, -1); + lookAtPosition.applyMatrix4(rotationMatrix2); + lookAtPosition.add(cameraWorldPosition); + target.subVectors(reflectorWorldPosition, lookAtPosition); + target.reflect(normal).negate(); + target.add(reflectorWorldPosition); + virtualCamera.position.copy(view); + virtualCamera.up.set(0, 1, 0); + virtualCamera.up.applyMatrix4(rotationMatrix2); + virtualCamera.up.reflect(normal); + virtualCamera.lookAt(target); + virtualCamera.far = camera.far; + virtualCamera.updateMatrixWorld(); + virtualCamera.projectionMatrix.copy(camera.projectionMatrix); + material.uniforms["virtualCameraNear"].value = camera.near; + material.uniforms["virtualCameraFar"].value = camera.far; + material.uniforms["virtualCameraMatrixWorld"].value = virtualCamera.matrixWorld; + material.uniforms["virtualCameraProjectionMatrix"].value = camera.projectionMatrix; + material.uniforms["virtualCameraProjectionMatrixInverse"].value = camera.projectionMatrixInverse; + material.uniforms["resolution"].value = scope.resolution; + textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + textureMatrix.multiply(virtualCamera.projectionMatrix); + textureMatrix.multiply(virtualCamera.matrixWorldInverse); + textureMatrix.multiply(scope.matrixWorld); + const currentRenderTarget = renderer2.getRenderTarget(); + const currentXrEnabled = renderer2.xr.enabled; + const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate; + const currentClippingPlanes = renderer2.clippingPlanes; + renderer2.xr.enabled = false; + renderer2.shadowMap.autoUpdate = false; + renderer2.clippingPlanes = globalPlanes; + renderer2.setRenderTarget(renderTarget); + renderer2.state.buffers.depth.setMask(true); + if (renderer2.autoClear === false) + renderer2.clear(); + renderer2.render(scene, virtualCamera); + renderer2.xr.enabled = currentXrEnabled; + renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate; + renderer2.clippingPlanes = currentClippingPlanes; + renderer2.setRenderTarget(currentRenderTarget); + const viewport = camera.viewport; + if (viewport !== undefined) { + renderer2.state.viewport(viewport); + } + }; + this.getRenderTarget = function() { + return renderTarget; + }; + } +} +ReflectorForSSRPass.ReflectorShader = { + name: "ReflectorShader", + defines: { + DISTANCE_ATTENUATION: true, + FRESNEL: true + }, + uniforms: { + color: { value: null }, + tDiffuse: { value: null }, + tDepth: { value: null }, + textureMatrix: { value: new Matrix4 }, + maxDistance: { value: 180 }, + opacity: { value: 0.5 }, + fresnelCoe: { value: null }, + virtualCameraNear: { value: null }, + virtualCameraFar: { value: null }, + virtualCameraProjectionMatrix: { value: new Matrix4 }, + virtualCameraMatrixWorld: { value: new Matrix4 }, + virtualCameraProjectionMatrixInverse: { value: new Matrix4 }, + resolution: { value: new Vector2 } + }, + vertexShader: ` + uniform mat4 textureMatrix; + varying vec4 vUv; + + void main() { + + vUv = textureMatrix * vec4( position, 1.0 ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + uniform vec3 color; + uniform sampler2D tDiffuse; + uniform sampler2D tDepth; + uniform float maxDistance; + uniform float opacity; + uniform float fresnelCoe; + uniform float virtualCameraNear; + uniform float virtualCameraFar; + uniform mat4 virtualCameraProjectionMatrix; + uniform mat4 virtualCameraProjectionMatrixInverse; + uniform mat4 virtualCameraMatrixWorld; + uniform vec2 resolution; + varying vec4 vUv; + #include + float blendOverlay( float base, float blend ) { + return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); + } + vec3 blendOverlay( vec3 base, vec3 blend ) { + return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); + } + float getDepth( const in vec2 uv ) { + return texture2D( tDepth, uv ).x; + } + float getViewZ( const in float depth ) { + return perspectiveDepthToViewZ( depth, virtualCameraNear, virtualCameraFar ); + } + vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { + vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc + clipPosition *= clipW; //clip + return ( virtualCameraProjectionMatrixInverse * clipPosition ).xyz;//view + } + void main() { + vec4 base = texture2DProj( tDiffuse, vUv ); + #ifdef useDepthTexture + vec2 uv=(gl_FragCoord.xy-.5)/resolution.xy; + uv.x=1.-uv.x; + float depth = texture2DProj( tDepth, vUv ).r; + float viewZ = getViewZ( depth ); + float clipW = virtualCameraProjectionMatrix[2][3] * viewZ+virtualCameraProjectionMatrix[3][3]; + vec3 viewPosition=getViewPosition( uv, depth, clipW ); + vec3 worldPosition=(virtualCameraMatrixWorld*vec4(viewPosition,1)).xyz; + if(worldPosition.y>maxDistance) discard; + float op=opacity; + #ifdef DISTANCE_ATTENUATION + float ratio=1.-(worldPosition.y/maxDistance); + float attenuation=ratio*ratio; + op=opacity*attenuation; + #endif + #ifdef FRESNEL + op*=fresnelCoe; + #endif + gl_FragColor = vec4( blendOverlay( base.rgb, color ), op ); + #else + gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); + #endif + } + ` +}; +// node_modules/three/examples/jsm/objects/Refractor.js +class Refractor extends Mesh { + constructor(geometry, options = {}) { + super(geometry); + this.isRefractor = true; + this.type = "Refractor"; + this.camera = new PerspectiveCamera; + const scope = this; + const color = options.color !== undefined ? new Color(options.color) : new Color(8355711); + const textureWidth = options.textureWidth || 512; + const textureHeight = options.textureHeight || 512; + const clipBias = options.clipBias || 0; + const shader = options.shader || Refractor.RefractorShader; + const multisample = options.multisample !== undefined ? options.multisample : 4; + const virtualCamera = this.camera; + virtualCamera.matrixAutoUpdate = false; + virtualCamera.userData.refractor = true; + const refractorPlane = new Plane; + const textureMatrix = new Matrix4; + const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, { samples: multisample, type: HalfFloatType }); + this.material = new ShaderMaterial({ + name: shader.name !== undefined ? shader.name : "unspecified", + uniforms: UniformsUtils.clone(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + transparent: true + }); + this.material.uniforms["color"].value = color; + this.material.uniforms["tDiffuse"].value = renderTarget.texture; + this.material.uniforms["textureMatrix"].value = textureMatrix; + const visible = function() { + const refractorWorldPosition = new Vector3; + const cameraWorldPosition = new Vector3; + const rotationMatrix2 = new Matrix4; + const view = new Vector3; + const normal = new Vector3; + return function visible(camera) { + refractorWorldPosition.setFromMatrixPosition(scope.matrixWorld); + cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); + view.subVectors(refractorWorldPosition, cameraWorldPosition); + rotationMatrix2.extractRotation(scope.matrixWorld); + normal.set(0, 0, 1); + normal.applyMatrix4(rotationMatrix2); + return view.dot(normal) < 0; + }; + }(); + const updateRefractorPlane = function() { + const normal = new Vector3; + const position2 = new Vector3; + const quaternion = new Quaternion; + const scale2 = new Vector3; + return function updateRefractorPlane() { + scope.matrixWorld.decompose(position2, quaternion, scale2); + normal.set(0, 0, 1).applyQuaternion(quaternion).normalize(); + normal.negate(); + refractorPlane.setFromNormalAndCoplanarPoint(normal, position2); + }; + }(); + const updateVirtualCamera = function() { + const clipPlane = new Plane; + const clipVector = new Vector4; + const q2 = new Vector4; + return function updateVirtualCamera(camera) { + virtualCamera.matrixWorld.copy(camera.matrixWorld); + virtualCamera.matrixWorldInverse.copy(virtualCamera.matrixWorld).invert(); + virtualCamera.projectionMatrix.copy(camera.projectionMatrix); + virtualCamera.far = camera.far; + clipPlane.copy(refractorPlane); + clipPlane.applyMatrix4(virtualCamera.matrixWorldInverse); + clipVector.set(clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.constant); + const projectionMatrix = virtualCamera.projectionMatrix; + q2.x = (Math.sign(clipVector.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; + q2.y = (Math.sign(clipVector.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; + q2.z = -1; + q2.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; + clipVector.multiplyScalar(2 / clipVector.dot(q2)); + projectionMatrix.elements[2] = clipVector.x; + projectionMatrix.elements[6] = clipVector.y; + projectionMatrix.elements[10] = clipVector.z + 1 - clipBias; + projectionMatrix.elements[14] = clipVector.w; + }; + }(); + function updateTextureMatrix(camera) { + textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + textureMatrix.multiply(camera.projectionMatrix); + textureMatrix.multiply(camera.matrixWorldInverse); + textureMatrix.multiply(scope.matrixWorld); + } + function render(renderer2, scene, camera) { + scope.visible = false; + const currentRenderTarget = renderer2.getRenderTarget(); + const currentXrEnabled = renderer2.xr.enabled; + const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate; + renderer2.xr.enabled = false; + renderer2.shadowMap.autoUpdate = false; + renderer2.setRenderTarget(renderTarget); + if (renderer2.autoClear === false) + renderer2.clear(); + renderer2.render(scene, virtualCamera); + renderer2.xr.enabled = currentXrEnabled; + renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate; + renderer2.setRenderTarget(currentRenderTarget); + const viewport = camera.viewport; + if (viewport !== undefined) { + renderer2.state.viewport(viewport); + } + scope.visible = true; + } + this.onBeforeRender = function(renderer2, scene, camera) { + if (camera.userData.refractor === true) + return; + if (!visible(camera) === true) + return; + updateRefractorPlane(); + updateTextureMatrix(camera); + updateVirtualCamera(camera); + render(renderer2, scene, camera); + }; + this.getRenderTarget = function() { + return renderTarget; + }; + this.dispose = function() { + renderTarget.dispose(); + scope.material.dispose(); + }; + } +} +Refractor.RefractorShader = { + name: "RefractorShader", + uniforms: { + color: { + value: null + }, + tDiffuse: { + value: null + }, + textureMatrix: { + value: null + } + }, + vertexShader: ` + + uniform mat4 textureMatrix; + + varying vec4 vUv; + + void main() { + + vUv = textureMatrix * vec4( position, 1.0 ); + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform vec3 color; + uniform sampler2D tDiffuse; + + varying vec4 vUv; + + float blendOverlay( float base, float blend ) { + + return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); + + } + + vec3 blendOverlay( vec3 base, vec3 blend ) { + + return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); + + } + + void main() { + + vec4 base = texture2DProj( tDiffuse, vUv ); + gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); + + #include + #include + + }` +}; +// node_modules/three/examples/jsm/objects/ShadowMesh.js +var _shadowMatrix = new Matrix4; +// node_modules/three/examples/jsm/objects/Sky.js +class Sky extends Mesh { + constructor() { + const shader = Sky.SkyShader; + const material = new ShaderMaterial({ + name: shader.name, + uniforms: UniformsUtils.clone(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + depthWrite: false + }); + super(new BoxGeometry(1, 1, 1), material); + this.isSky = true; + } +} +Sky.SkyShader = { + name: "SkyShader", + uniforms: { + turbidity: { value: 2 }, + rayleigh: { value: 1 }, + mieCoefficient: { value: 0.005 }, + mieDirectionalG: { value: 0.8 }, + sunPosition: { value: new Vector3 }, + up: { value: new Vector3(0, 1, 0) } + }, + vertexShader: ` + uniform vec3 sunPosition; + uniform float rayleigh; + uniform float turbidity; + uniform float mieCoefficient; + uniform vec3 up; + + varying vec3 vWorldPosition; + varying vec3 vSunDirection; + varying float vSunfade; + varying vec3 vBetaR; + varying vec3 vBetaM; + varying float vSunE; + + // constants for atmospheric scattering + const float e = 2.71828182845904523536028747135266249775724709369995957; + const float pi = 3.141592653589793238462643383279502884197169; + + // wavelength of used primaries, according to preetham + const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 ); + // this pre-calculation replaces older TotalRayleigh(vec3 lambda) function: + // (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn)) + const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 ); + + // mie stuff + // K coefficient for the primaries + const float v = 4.0; + const vec3 K = vec3( 0.686, 0.678, 0.666 ); + // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K + const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 ); + + // earth shadow hack + // cutoffAngle = pi / 1.95; + const float cutoffAngle = 1.6110731556870734; + const float steepness = 1.5; + const float EE = 1000.0; + + float sunIntensity( float zenithAngleCos ) { + zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 ); + return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) ); + } + + vec3 totalMie( float T ) { + float c = ( 0.2 * T ) * 10E-18; + return 0.434 * c * MieConst; + } + + void main() { + + vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); + vWorldPosition = worldPosition.xyz; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + gl_Position.z = gl_Position.w; // set z to camera.far + + vSunDirection = normalize( sunPosition ); + + vSunE = sunIntensity( dot( vSunDirection, up ) ); + + vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 ); + + float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) ); + + // extinction (absorption + out scattering) + // rayleigh coefficients + vBetaR = totalRayleigh * rayleighCoefficient; + + // mie coefficients + vBetaM = totalMie( turbidity ) * mieCoefficient; + + }`, + fragmentShader: ` + varying vec3 vWorldPosition; + varying vec3 vSunDirection; + varying float vSunfade; + varying vec3 vBetaR; + varying vec3 vBetaM; + varying float vSunE; + + uniform float mieDirectionalG; + uniform vec3 up; + + // constants for atmospheric scattering + const float pi = 3.141592653589793238462643383279502884197169; + + const float n = 1.0003; // refractive index of air + const float N = 2.545E25; // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius) + + // optical length at zenith for molecules + const float rayleighZenithLength = 8.4E3; + const float mieZenithLength = 1.25E3; + // 66 arc seconds -> degrees, and the cosine of that + const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324; + + // 3.0 / ( 16.0 * pi ) + const float THREE_OVER_SIXTEENPI = 0.05968310365946075; + // 1.0 / ( 4.0 * pi ) + const float ONE_OVER_FOURPI = 0.07957747154594767; + + float rayleighPhase( float cosTheta ) { + return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) ); + } + + float hgPhase( float cosTheta, float g ) { + float g2 = pow( g, 2.0 ); + float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 ); + return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse ); + } + + void main() { + + vec3 direction = normalize( vWorldPosition - cameraPosition ); + + // optical length + // cutoff angle at 90 to avoid singularity in next formula. + float zenithAngle = acos( max( 0.0, dot( up, direction ) ) ); + float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) ); + float sR = rayleighZenithLength * inverse; + float sM = mieZenithLength * inverse; + + // combined extinction factor + vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) ); + + // in scattering + float cosTheta = dot( direction, vSunDirection ); + + float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 ); + vec3 betaRTheta = vBetaR * rPhase; + + float mPhase = hgPhase( cosTheta, mieDirectionalG ); + vec3 betaMTheta = vBetaM * mPhase; + + vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) ); + Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) ); + + // nightsky + float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2] + float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2] + vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 ); + vec3 L0 = vec3( 0.1 ) * Fex; + + // composition + solar disc + float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta ); + L0 += ( vSunE * 19000.0 * Fex ) * sundisk; + + vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 ); + + vec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) ); + + gl_FragColor = vec4( retColor, 1.0 ); + + #include + #include + + }` +}; +// node_modules/three/examples/jsm/objects/Water2.js +class Water extends Mesh { + constructor(geometry, options = {}) { + super(geometry); + this.isWater = true; + this.type = "Water"; + const scope = this; + const color = options.color !== undefined ? new Color(options.color) : new Color(16777215); + const textureWidth = options.textureWidth !== undefined ? options.textureWidth : 512; + const textureHeight = options.textureHeight !== undefined ? options.textureHeight : 512; + const clipBias = options.clipBias !== undefined ? options.clipBias : 0; + const flowDirection = options.flowDirection !== undefined ? options.flowDirection : new Vector2(1, 0); + const flowSpeed = options.flowSpeed !== undefined ? options.flowSpeed : 0.03; + const reflectivity = options.reflectivity !== undefined ? options.reflectivity : 0.02; + const scale2 = options.scale !== undefined ? options.scale : 1; + const shader = options.shader !== undefined ? options.shader : Water.WaterShader; + const textureLoader = new TextureLoader; + const flowMap = options.flowMap || undefined; + const normalMap0 = options.normalMap0 || textureLoader.load("textures/water/Water_1_M_Normal.jpg"); + const normalMap1 = options.normalMap1 || textureLoader.load("textures/water/Water_2_M_Normal.jpg"); + const cycle = 0.15; + const halfCycle = cycle * 0.5; + const textureMatrix = new Matrix4; + const clock = new Clock; + if (Reflector === undefined) { + console.error("THREE.Water: Required component Reflector not found."); + return; + } + if (Refractor === undefined) { + console.error("THREE.Water: Required component Refractor not found."); + return; + } + const reflector = new Reflector(geometry, { + textureWidth, + textureHeight, + clipBias + }); + const refractor = new Refractor(geometry, { + textureWidth, + textureHeight, + clipBias + }); + reflector.matrixAutoUpdate = false; + refractor.matrixAutoUpdate = false; + this.material = new ShaderMaterial({ + name: shader.name, + uniforms: UniformsUtils.merge([ + UniformsLib["fog"], + shader.uniforms + ]), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + transparent: true, + fog: true + }); + if (flowMap !== undefined) { + this.material.defines.USE_FLOWMAP = ""; + this.material.uniforms["tFlowMap"] = { + type: "t", + value: flowMap + }; + } else { + this.material.uniforms["flowDirection"] = { + type: "v2", + value: flowDirection + }; + } + normalMap0.wrapS = normalMap0.wrapT = RepeatWrapping; + normalMap1.wrapS = normalMap1.wrapT = RepeatWrapping; + this.material.uniforms["tReflectionMap"].value = reflector.getRenderTarget().texture; + this.material.uniforms["tRefractionMap"].value = refractor.getRenderTarget().texture; + this.material.uniforms["tNormalMap0"].value = normalMap0; + this.material.uniforms["tNormalMap1"].value = normalMap1; + this.material.uniforms["color"].value = color; + this.material.uniforms["reflectivity"].value = reflectivity; + this.material.uniforms["textureMatrix"].value = textureMatrix; + this.material.uniforms["config"].value.x = 0; + this.material.uniforms["config"].value.y = halfCycle; + this.material.uniforms["config"].value.z = halfCycle; + this.material.uniforms["config"].value.w = scale2; + function updateTextureMatrix(camera) { + textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + textureMatrix.multiply(camera.projectionMatrix); + textureMatrix.multiply(camera.matrixWorldInverse); + textureMatrix.multiply(scope.matrixWorld); + } + function updateFlow() { + const delta = clock.getDelta(); + const config = scope.material.uniforms["config"]; + config.value.x += flowSpeed * delta; + config.value.y = config.value.x + halfCycle; + if (config.value.x >= cycle) { + config.value.x = 0; + config.value.y = halfCycle; + } else if (config.value.y >= cycle) { + config.value.y = config.value.y - cycle; + } + } + this.onBeforeRender = function(renderer2, scene, camera) { + updateTextureMatrix(camera); + updateFlow(); + scope.visible = false; + reflector.matrixWorld.copy(scope.matrixWorld); + refractor.matrixWorld.copy(scope.matrixWorld); + reflector.onBeforeRender(renderer2, scene, camera); + refractor.onBeforeRender(renderer2, scene, camera); + scope.visible = true; + }; + } +} +Water.WaterShader = { + name: "WaterShader", + uniforms: { + color: { + type: "c", + value: null + }, + reflectivity: { + type: "f", + value: 0 + }, + tReflectionMap: { + type: "t", + value: null + }, + tRefractionMap: { + type: "t", + value: null + }, + tNormalMap0: { + type: "t", + value: null + }, + tNormalMap1: { + type: "t", + value: null + }, + textureMatrix: { + type: "m4", + value: null + }, + config: { + type: "v4", + value: new Vector4 + } + }, + vertexShader: ` + + #include + #include + #include + + uniform mat4 textureMatrix; + + varying vec4 vCoord; + varying vec2 vUv; + varying vec3 vToEye; + + void main() { + + vUv = uv; + vCoord = textureMatrix * vec4( position, 1.0 ); + + vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); + vToEye = cameraPosition - worldPosition.xyz; + + vec4 mvPosition = viewMatrix * worldPosition; // used in fog_vertex + gl_Position = projectionMatrix * mvPosition; + + #include + #include + + }`, + fragmentShader: ` + + #include + #include + #include + + uniform sampler2D tReflectionMap; + uniform sampler2D tRefractionMap; + uniform sampler2D tNormalMap0; + uniform sampler2D tNormalMap1; + + #ifdef USE_FLOWMAP + uniform sampler2D tFlowMap; + #else + uniform vec2 flowDirection; + #endif + + uniform vec3 color; + uniform float reflectivity; + uniform vec4 config; + + varying vec4 vCoord; + varying vec2 vUv; + varying vec3 vToEye; + + void main() { + + #include + + float flowMapOffset0 = config.x; + float flowMapOffset1 = config.y; + float halfCycle = config.z; + float scale = config.w; + + vec3 toEye = normalize( vToEye ); + + // determine flow direction + vec2 flow; + #ifdef USE_FLOWMAP + flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0; + #else + flow = flowDirection; + #endif + flow.x *= - 1.0; + + // sample normal maps (distort uvs with flowdata) + vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 ); + vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 ); + + // linear interpolate to get the final normal color + float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle; + vec4 normalColor = mix( normalColor0, normalColor1, flowLerp ); + + // calculate normal vector + vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) ); + + // calculate the fresnel term to blend reflection and refraction maps + float theta = max( dot( toEye, normal ), 0.0 ); + float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 ); + + // calculate final uv coords + vec3 coord = vCoord.xyz / vCoord.w; + vec2 uv = coord.xy + coord.z * normal.xz * 0.05; + + vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) ); + vec4 refractColor = texture2D( tRefractionMap, uv ); + + // multiply water color with the mix of both textures + gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance ); + + #include + #include + #include + + }` +}; +// node_modules/three/examples/jsm/physics/RapierPhysics.js +var _scale3 = new Vector3(1, 1, 1); +var ZERO = new Vector3; +// node_modules/three/examples/jsm/shaders/CopyShader.js +var CopyShader = { + name: "CopyShader", + uniforms: { + tDiffuse: { value: null }, + opacity: { value: 1 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform float opacity; + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + gl_FragColor = opacity * texel; + + + }` +}; +// node_modules/three/examples/jsm/shaders/ConvolutionShader.js +var ConvolutionShader = { + name: "ConvolutionShader", + defines: { + KERNEL_SIZE_FLOAT: "25.0", + KERNEL_SIZE_INT: "25" + }, + uniforms: { + tDiffuse: { value: null }, + uImageIncrement: { value: new Vector2(0.001953125, 0) }, + cKernel: { value: [] } + }, + vertexShader: ` + + uniform vec2 uImageIncrement; + + varying vec2 vUv; + + void main() { + + vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform float cKernel[ KERNEL_SIZE_INT ]; + + uniform sampler2D tDiffuse; + uniform vec2 uImageIncrement; + + varying vec2 vUv; + + void main() { + + vec2 imageCoord = vUv; + vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 ); + + for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) { + + sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ]; + imageCoord += uImageIncrement; + + } + + gl_FragColor = sum; + + }`, + buildKernel: function(sigma) { + const kMaxKernelSize = 25; + let kernelSize = 2 * Math.ceil(sigma * 3) + 1; + if (kernelSize > kMaxKernelSize) + kernelSize = kMaxKernelSize; + const halfWidth = (kernelSize - 1) * 0.5; + const values2 = new Array(kernelSize); + let sum2 = 0; + for (let i = 0;i < kernelSize; ++i) { + values2[i] = gauss(i - halfWidth, sigma); + sum2 += values2[i]; + } + for (let i = 0;i < kernelSize; ++i) + values2[i] /= sum2; + return values2; + } +}; +function gauss(x2, sigma) { + return Math.exp(-(x2 * x2) / (2 * sigma * sigma)); +} + +// node_modules/three/examples/jsm/postprocessing/BloomPass.js +class BloomPass extends Pass { + constructor(strength = 1, kernelSize = 25, sigma = 4) { + super(); + this.renderTargetX = new WebGLRenderTarget(1, 1, { type: HalfFloatType }); + this.renderTargetX.texture.name = "BloomPass.x"; + this.renderTargetY = new WebGLRenderTarget(1, 1, { type: HalfFloatType }); + this.renderTargetY.texture.name = "BloomPass.y"; + this.combineUniforms = UniformsUtils.clone(CombineShader.uniforms); + this.combineUniforms["strength"].value = strength; + this.materialCombine = new ShaderMaterial({ + name: CombineShader.name, + uniforms: this.combineUniforms, + vertexShader: CombineShader.vertexShader, + fragmentShader: CombineShader.fragmentShader, + blending: AdditiveBlending, + transparent: true + }); + const convolutionShader = ConvolutionShader; + this.convolutionUniforms = UniformsUtils.clone(convolutionShader.uniforms); + this.convolutionUniforms["uImageIncrement"].value = BloomPass.blurX; + this.convolutionUniforms["cKernel"].value = ConvolutionShader.buildKernel(sigma); + this.materialConvolution = new ShaderMaterial({ + name: convolutionShader.name, + uniforms: this.convolutionUniforms, + vertexShader: convolutionShader.vertexShader, + fragmentShader: convolutionShader.fragmentShader, + defines: { + KERNEL_SIZE_FLOAT: kernelSize.toFixed(1), + KERNEL_SIZE_INT: kernelSize.toFixed(0) + } + }); + this.needsSwap = false; + this.fsQuad = new FullScreenQuad(null); + } + render(renderer2, writeBuffer, readBuffer, deltaTime, maskActive) { + if (maskActive) + renderer2.state.buffers.stencil.setTest(false); + this.fsQuad.material = this.materialConvolution; + this.convolutionUniforms["tDiffuse"].value = readBuffer.texture; + this.convolutionUniforms["uImageIncrement"].value = BloomPass.blurX; + renderer2.setRenderTarget(this.renderTargetX); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.convolutionUniforms["tDiffuse"].value = this.renderTargetX.texture; + this.convolutionUniforms["uImageIncrement"].value = BloomPass.blurY; + renderer2.setRenderTarget(this.renderTargetY); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.materialCombine; + this.combineUniforms["tDiffuse"].value = this.renderTargetY.texture; + if (maskActive) + renderer2.state.buffers.stencil.setTest(true); + renderer2.setRenderTarget(readBuffer); + if (this.clear) + renderer2.clear(); + this.fsQuad.render(renderer2); + } + setSize(width2, height2) { + this.renderTargetX.setSize(width2, height2); + this.renderTargetY.setSize(width2, height2); + } + dispose() { + this.renderTargetX.dispose(); + this.renderTargetY.dispose(); + this.materialCombine.dispose(); + this.materialConvolution.dispose(); + this.fsQuad.dispose(); + } +} +var CombineShader = { + name: "CombineShader", + uniforms: { + tDiffuse: { value: null }, + strength: { value: 1 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform float strength; + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + gl_FragColor = strength * texel; + + }` +}; +BloomPass.blurX = new Vector2(0.001953125, 0); +BloomPass.blurY = new Vector2(0, 0.001953125); +// node_modules/three/examples/jsm/shaders/DotScreenShader.js +var DotScreenShader = { + name: "DotScreenShader", + uniforms: { + tDiffuse: { value: null }, + tSize: { value: new Vector2(256, 256) }, + center: { value: new Vector2(0.5, 0.5) }, + angle: { value: 1.57 }, + scale: { value: 1 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform vec2 center; + uniform float angle; + uniform float scale; + uniform vec2 tSize; + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + float pattern() { + + float s = sin( angle ), c = cos( angle ); + + vec2 tex = vUv * tSize - center; + vec2 point = vec2( c * tex.x - s * tex.y, s * tex.x + c * tex.y ) * scale; + + return ( sin( point.x ) * sin( point.y ) ) * 4.0; + + } + + void main() { + + vec4 color = texture2D( tDiffuse, vUv ); + + float average = ( color.r + color.g + color.b ) / 3.0; + + gl_FragColor = vec4( vec3( average * 10.0 - 5.0 + pattern() ), color.a ); + + }` +}; +// node_modules/three/examples/jsm/shaders/GTAOShader.js +var GTAOShader = { + name: "GTAOShader", + defines: { + PERSPECTIVE_CAMERA: 1, + SAMPLES: 16, + NORMAL_VECTOR_TYPE: 1, + DEPTH_SWIZZLING: "x", + SCREEN_SPACE_RADIUS: 0, + SCREEN_SPACE_RADIUS_SCALE: 100, + SCENE_CLIP_BOX: 0 + }, + uniforms: { + tNormal: { value: null }, + tDepth: { value: null }, + tNoise: { value: null }, + resolution: { value: new Vector2 }, + cameraNear: { value: null }, + cameraFar: { value: null }, + cameraProjectionMatrix: { value: new Matrix4 }, + cameraProjectionMatrixInverse: { value: new Matrix4 }, + cameraWorldMatrix: { value: new Matrix4 }, + radius: { value: 0.25 }, + distanceExponent: { value: 1 }, + thickness: { value: 1 }, + distanceFallOff: { value: 1 }, + scale: { value: 1 }, + sceneBoxMin: { value: new Vector3(-1, -1, -1) }, + sceneBoxMax: { value: new Vector3(1, 1, 1) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + varying vec2 vUv; + uniform highp sampler2D tNormal; + uniform highp sampler2D tDepth; + uniform sampler2D tNoise; + uniform vec2 resolution; + uniform float cameraNear; + uniform float cameraFar; + uniform mat4 cameraProjectionMatrix; + uniform mat4 cameraProjectionMatrixInverse; + uniform mat4 cameraWorldMatrix; + uniform float radius; + uniform float distanceExponent; + uniform float thickness; + uniform float distanceFallOff; + uniform float scale; + #if SCENE_CLIP_BOX == 1 + uniform vec3 sceneBoxMin; + uniform vec3 sceneBoxMax; + #endif + + #include + #include + + #ifndef FRAGMENT_OUTPUT + #define FRAGMENT_OUTPUT vec4(vec3(ao), 1.) + #endif + + vec3 getViewPosition(const in vec2 screenPosition, const in float depth) { + vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); + vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; + return viewSpacePosition.xyz / viewSpacePosition.w; + } + + float getDepth(const vec2 uv) { + return textureLod(tDepth, uv.xy, 0.0).DEPTH_SWIZZLING; + } + + float fetchDepth(const ivec2 uv) { + return texelFetch(tDepth, uv.xy, 0).DEPTH_SWIZZLING; + } + + float getViewZ(const in float depth) { + #if PERSPECTIVE_CAMERA == 1 + return perspectiveDepthToViewZ(depth, cameraNear, cameraFar); + #else + return orthographicDepthToViewZ(depth, cameraNear, cameraFar); + #endif + } + + vec3 computeNormalFromDepth(const vec2 uv) { + vec2 size = vec2(textureSize(tDepth, 0)); + ivec2 p = ivec2(uv * size); + float c0 = fetchDepth(p); + float l2 = fetchDepth(p - ivec2(2, 0)); + float l1 = fetchDepth(p - ivec2(1, 0)); + float r1 = fetchDepth(p + ivec2(1, 0)); + float r2 = fetchDepth(p + ivec2(2, 0)); + float b2 = fetchDepth(p - ivec2(0, 2)); + float b1 = fetchDepth(p - ivec2(0, 1)); + float t1 = fetchDepth(p + ivec2(0, 1)); + float t2 = fetchDepth(p + ivec2(0, 2)); + float dl = abs((2.0 * l1 - l2) - c0); + float dr = abs((2.0 * r1 - r2) - c0); + float db = abs((2.0 * b1 - b2) - c0); + float dt = abs((2.0 * t1 - t2) - c0); + vec3 ce = getViewPosition(uv, c0).xyz; + vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; + vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; + return normalize(cross(dpdx, dpdy)); + } + + vec3 getViewNormal(const vec2 uv) { + #if NORMAL_VECTOR_TYPE == 2 + return normalize(textureLod(tNormal, uv, 0.).rgb); + #elif NORMAL_VECTOR_TYPE == 1 + return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); + #else + return computeNormalFromDepth(uv); + #endif + } + + vec3 getSceneUvAndDepth(vec3 sampleViewPos) { + vec4 sampleClipPos = cameraProjectionMatrix * vec4(sampleViewPos, 1.); + vec2 sampleUv = sampleClipPos.xy / sampleClipPos.w * 0.5 + 0.5; + float sampleSceneDepth = getDepth(sampleUv); + return vec3(sampleUv, sampleSceneDepth); + } + + void main() { + float depth = getDepth(vUv.xy); + if (depth >= 1.0) { + discard; + return; + } + vec3 viewPos = getViewPosition(vUv, depth); + vec3 viewNormal = getViewNormal(vUv); + + float radiusToUse = radius; + float distanceFalloffToUse = thickness; + #if SCREEN_SPACE_RADIUS == 1 + float radiusScale = getViewPosition(vec2(0.5 + float(SCREEN_SPACE_RADIUS_SCALE) / resolution.x, 0.0), depth).x; + radiusToUse *= radiusScale; + distanceFalloffToUse *= radiusScale; + #endif + + #if SCENE_CLIP_BOX == 1 + vec3 worldPos = (cameraWorldMatrix * vec4(viewPos, 1.0)).xyz; + float boxDistance = length(max(vec3(0.0), max(sceneBoxMin - worldPos, worldPos - sceneBoxMax))); + if (boxDistance > radiusToUse) { + discard; + return; + } + #endif + + vec2 noiseResolution = vec2(textureSize(tNoise, 0)); + vec2 noiseUv = vUv * resolution / noiseResolution; + vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); + vec3 randomVec = noiseTexel.xyz * 2.0 - 1.0; + vec3 tangent = normalize(vec3(randomVec.xy, 0.)); + vec3 bitangent = vec3(-tangent.y, tangent.x, 0.); + mat3 kernelMatrix = mat3(tangent, bitangent, vec3(0., 0., 1.)); + + const int DIRECTIONS = SAMPLES < 30 ? 3 : 5; + const int STEPS = (SAMPLES + DIRECTIONS - 1) / DIRECTIONS; + float ao = 0.0; + for (int i = 0; i < DIRECTIONS; ++i) { + + float angle = float(i) / float(DIRECTIONS) * PI; + vec4 sampleDir = vec4(cos(angle), sin(angle), 0., 0.5 + 0.5 * noiseTexel.w); + sampleDir.xyz = normalize(kernelMatrix * sampleDir.xyz); + + vec3 viewDir = normalize(-viewPos.xyz); + vec3 sliceBitangent = normalize(cross(sampleDir.xyz, viewDir)); + vec3 sliceTangent = cross(sliceBitangent, viewDir); + vec3 normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent)); + + vec3 tangentToNormalInSlice = cross(normalInSlice, sliceBitangent); + vec2 cosHorizons = vec2(dot(viewDir, tangentToNormalInSlice), dot(viewDir, -tangentToNormalInSlice)); + + for (int j = 0; j < STEPS; ++j) { + vec3 sampleViewOffset = sampleDir.xyz * radiusToUse * sampleDir.w * pow(float(j + 1) / float(STEPS), distanceExponent); + + vec3 sampleSceneUvDepth = getSceneUvAndDepth(viewPos + sampleViewOffset); + vec3 sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); + vec3 viewDelta = sampleSceneViewPos - viewPos; + if (abs(viewDelta.z) < thickness) { + float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); + cosHorizons.x += max(0., (sampleCosHorizon - cosHorizons.x) * mix(1., 2. / float(j + 2), distanceFallOff)); + } + + sampleSceneUvDepth = getSceneUvAndDepth(viewPos - sampleViewOffset); + sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); + viewDelta = sampleSceneViewPos - viewPos; + if (abs(viewDelta.z) < thickness) { + float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); + cosHorizons.y += max(0., (sampleCosHorizon - cosHorizons.y) * mix(1., 2. / float(j + 2), distanceFallOff)); + } + } + + vec2 sinHorizons = sqrt(1. - cosHorizons * cosHorizons); + float nx = dot(normalInSlice, sliceTangent); + float ny = dot(normalInSlice, viewDir); + float nxb = 1. / 2. * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y); + float nyb = 1. / 2. * (2. - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y); + float occlusion = nx * nxb + ny * nyb; + ao += occlusion; + } + + ao = clamp(ao / float(DIRECTIONS), 0., 1.); + #if SCENE_CLIP_BOX == 1 + ao = mix(ao, 1., smoothstep(0., radiusToUse, boxDistance)); + #endif + ao = pow(ao, scale); + + gl_FragColor = FRAGMENT_OUTPUT; + }` +}; +var GTAODepthShader = { + name: "GTAODepthShader", + defines: { + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDepth: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null } + }, + vertexShader: ` + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + uniform sampler2D tDepth; + uniform float cameraNear; + uniform float cameraFar; + varying vec2 vUv; + + #include + + float getLinearDepth( const in vec2 screenPosition ) { + #if PERSPECTIVE_CAMERA == 1 + float fragCoordZ = texture2D( tDepth, screenPosition ).x; + float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); + return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + #else + return texture2D( tDepth, screenPosition ).x; + #endif + } + + void main() { + float depth = getLinearDepth( vUv ); + gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); + + }` +}; +var GTAOBlendShader = { + name: "GTAOBlendShader", + uniforms: { + tDiffuse: { value: null }, + intensity: { value: 1 } + }, + vertexShader: ` + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + uniform float intensity; + uniform sampler2D tDiffuse; + varying vec2 vUv; + + void main() { + vec4 texel = texture2D( tDiffuse, vUv ); + gl_FragColor = vec4(mix(vec3(1.), texel.rgb, intensity), texel.a); + }` +}; +function generateMagicSquareNoise(size2 = 5) { + const noiseSize = Math.floor(size2) % 2 === 0 ? Math.floor(size2) + 1 : Math.floor(size2); + const magicSquare = generateMagicSquare(noiseSize); + const noiseSquareSize = magicSquare.length; + const data2 = new Uint8Array(noiseSquareSize * 4); + for (let inx = 0;inx < noiseSquareSize; ++inx) { + const iAng = magicSquare[inx]; + const angle = 2 * Math.PI * iAng / noiseSquareSize; + const randomVec = new Vector3(Math.cos(angle), Math.sin(angle), 0).normalize(); + data2[inx * 4] = (randomVec.x * 0.5 + 0.5) * 255; + data2[inx * 4 + 1] = (randomVec.y * 0.5 + 0.5) * 255; + data2[inx * 4 + 2] = 127; + data2[inx * 4 + 3] = 255; + } + const noiseTexture = new DataTexture(data2, noiseSize, noiseSize); + noiseTexture.wrapS = RepeatWrapping; + noiseTexture.wrapT = RepeatWrapping; + noiseTexture.needsUpdate = true; + return noiseTexture; +} +function generateMagicSquare(size2) { + const noiseSize = Math.floor(size2) % 2 === 0 ? Math.floor(size2) + 1 : Math.floor(size2); + const noiseSquareSize = noiseSize * noiseSize; + const magicSquare = Array(noiseSquareSize).fill(0); + let i = Math.floor(noiseSize / 2); + let j2 = noiseSize - 1; + for (let num = 1;num <= noiseSquareSize; ) { + if (i === -1 && j2 === noiseSize) { + j2 = noiseSize - 2; + i = 0; + } else { + if (j2 === noiseSize) { + j2 = 0; + } + if (i < 0) { + i = noiseSize - 1; + } + } + if (magicSquare[i * noiseSize + j2] !== 0) { + j2 -= 2; + i++; + continue; + } else { + magicSquare[i * noiseSize + j2] = num++; + } + j2++; + i--; + } + return magicSquare; +} + +// node_modules/three/examples/jsm/shaders/PoissonDenoiseShader.js +var PoissonDenoiseShader = { + name: "PoissonDenoiseShader", + defines: { + SAMPLES: 16, + SAMPLE_VECTORS: generatePdSamplePointInitializer(16, 2, 1), + NORMAL_VECTOR_TYPE: 1, + DEPTH_VALUE_SOURCE: 0 + }, + uniforms: { + tDiffuse: { value: null }, + tNormal: { value: null }, + tDepth: { value: null }, + tNoise: { value: null }, + resolution: { value: new Vector2 }, + cameraProjectionMatrixInverse: { value: new Matrix4 }, + lumaPhi: { value: 5 }, + depthPhi: { value: 5 }, + normalPhi: { value: 5 }, + radius: { value: 4 }, + index: { value: 0 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + + varying vec2 vUv; + + uniform sampler2D tDiffuse; + uniform sampler2D tNormal; + uniform sampler2D tDepth; + uniform sampler2D tNoise; + uniform vec2 resolution; + uniform mat4 cameraProjectionMatrixInverse; + uniform float lumaPhi; + uniform float depthPhi; + uniform float normalPhi; + uniform float radius; + uniform int index; + + #include + #include + + #ifndef SAMPLE_LUMINANCE + #define SAMPLE_LUMINANCE dot(vec3(0.2125, 0.7154, 0.0721), a) + #endif + + #ifndef FRAGMENT_OUTPUT + #define FRAGMENT_OUTPUT vec4(denoised, 1.) + #endif + + float getLuminance(const in vec3 a) { + return SAMPLE_LUMINANCE; + } + + const vec3 poissonDisk[SAMPLES] = SAMPLE_VECTORS; + + vec3 getViewPosition(const in vec2 screenPosition, const in float depth) { + vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); + vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; + return viewSpacePosition.xyz / viewSpacePosition.w; + } + + float getDepth(const vec2 uv) { + #if DEPTH_VALUE_SOURCE == 1 + return textureLod(tDepth, uv.xy, 0.0).a; + #else + return textureLod(tDepth, uv.xy, 0.0).r; + #endif + } + + float fetchDepth(const ivec2 uv) { + #if DEPTH_VALUE_SOURCE == 1 + return texelFetch(tDepth, uv.xy, 0).a; + #else + return texelFetch(tDepth, uv.xy, 0).r; + #endif + } + + vec3 computeNormalFromDepth(const vec2 uv) { + vec2 size = vec2(textureSize(tDepth, 0)); + ivec2 p = ivec2(uv * size); + float c0 = fetchDepth(p); + float l2 = fetchDepth(p - ivec2(2, 0)); + float l1 = fetchDepth(p - ivec2(1, 0)); + float r1 = fetchDepth(p + ivec2(1, 0)); + float r2 = fetchDepth(p + ivec2(2, 0)); + float b2 = fetchDepth(p - ivec2(0, 2)); + float b1 = fetchDepth(p - ivec2(0, 1)); + float t1 = fetchDepth(p + ivec2(0, 1)); + float t2 = fetchDepth(p + ivec2(0, 2)); + float dl = abs((2.0 * l1 - l2) - c0); + float dr = abs((2.0 * r1 - r2) - c0); + float db = abs((2.0 * b1 - b2) - c0); + float dt = abs((2.0 * t1 - t2) - c0); + vec3 ce = getViewPosition(uv, c0).xyz; + vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz + : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; + vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz + : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; + return normalize(cross(dpdx, dpdy)); + } + + vec3 getViewNormal(const vec2 uv) { + #if NORMAL_VECTOR_TYPE == 2 + return normalize(textureLod(tNormal, uv, 0.).rgb); + #elif NORMAL_VECTOR_TYPE == 1 + return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); + #else + return computeNormalFromDepth(uv); + #endif + } + + void denoiseSample(in vec3 center, in vec3 viewNormal, in vec3 viewPos, in vec2 sampleUv, inout vec3 denoised, inout float totalWeight) { + vec4 sampleTexel = textureLod(tDiffuse, sampleUv, 0.0); + float sampleDepth = getDepth(sampleUv); + vec3 sampleNormal = getViewNormal(sampleUv); + vec3 neighborColor = sampleTexel.rgb; + vec3 viewPosSample = getViewPosition(sampleUv, sampleDepth); + + float normalDiff = dot(viewNormal, sampleNormal); + float normalSimilarity = pow(max(normalDiff, 0.), normalPhi); + float lumaDiff = abs(getLuminance(neighborColor) - getLuminance(center)); + float lumaSimilarity = max(1.0 - lumaDiff / lumaPhi, 0.0); + float depthDiff = abs(dot(viewPos - viewPosSample, viewNormal)); + float depthSimilarity = max(1. - depthDiff / depthPhi, 0.); + float w = lumaSimilarity * depthSimilarity * normalSimilarity; + + denoised += w * neighborColor; + totalWeight += w; + } + + void main() { + float depth = getDepth(vUv.xy); + vec3 viewNormal = getViewNormal(vUv); + if (depth == 1. || dot(viewNormal, viewNormal) == 0.) { + discard; + return; + } + vec4 texel = textureLod(tDiffuse, vUv, 0.0); + vec3 center = texel.rgb; + vec3 viewPos = getViewPosition(vUv, depth); + + vec2 noiseResolution = vec2(textureSize(tNoise, 0)); + vec2 noiseUv = vUv * resolution / noiseResolution; + vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); + vec2 noiseVec = vec2(sin(noiseTexel[index % 4] * 2. * PI), cos(noiseTexel[index % 4] * 2. * PI)); + mat2 rotationMatrix = mat2(noiseVec.x, -noiseVec.y, noiseVec.x, noiseVec.y); + + float totalWeight = 1.0; + vec3 denoised = texel.rgb; + for (int i = 0; i < SAMPLES; i++) { + vec3 sampleDir = poissonDisk[i]; + vec2 offset = rotationMatrix * (sampleDir.xy * (1. + sampleDir.z * (radius - 1.)) / resolution); + vec2 sampleUv = vUv + offset; + denoiseSample(center, viewNormal, viewPos, sampleUv, denoised, totalWeight); + } + + if (totalWeight > 0.) { + denoised /= totalWeight; + } + gl_FragColor = FRAGMENT_OUTPUT; + }` +}; +function generatePdSamplePointInitializer(samples, rings, radiusExponent) { + const poissonDisk = generateDenoiseSamples(samples, rings, radiusExponent); + let glslCode = "vec3[SAMPLES]("; + for (let i = 0;i < samples; i++) { + const sample = poissonDisk[i]; + glslCode += `vec3(${sample.x}, ${sample.y}, ${sample.z})${i < samples - 1 ? "," : ")"}`; + } + return glslCode; +} +function generateDenoiseSamples(numSamples, numRings, radiusExponent) { + const samples = []; + for (let i = 0;i < numSamples; i++) { + const angle = 2 * Math.PI * numRings * i / numSamples; + const radius = Math.pow(i / (numSamples - 1), radiusExponent); + samples.push(new Vector3(Math.cos(angle), Math.sin(angle), radius)); + } + return samples; +} + +// node_modules/three/examples/jsm/postprocessing/GTAOPass.js +class GTAOPass extends Pass { + constructor(scene, camera, width2, height2, parameters, aoParameters, pdParameters) { + super(); + this.width = width2 !== undefined ? width2 : 512; + this.height = height2 !== undefined ? height2 : 512; + this.clear = true; + this.camera = camera; + this.scene = scene; + this.output = 0; + this._renderGBuffer = true; + this._visibilityCache = new Map; + this.blendIntensity = 1; + this.pdRings = 2; + this.pdRadiusExponent = 2; + this.pdSamples = 16; + this.gtaoNoiseTexture = generateMagicSquareNoise(); + this.pdNoiseTexture = this.generateNoise(); + this.gtaoRenderTarget = new WebGLRenderTarget(this.width, this.height, { type: HalfFloatType }); + this.pdRenderTarget = this.gtaoRenderTarget.clone(); + this.gtaoMaterial = new ShaderMaterial({ + defines: Object.assign({}, GTAOShader.defines), + uniforms: UniformsUtils.clone(GTAOShader.uniforms), + vertexShader: GTAOShader.vertexShader, + fragmentShader: GTAOShader.fragmentShader, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + this.gtaoMaterial.defines.PERSPECTIVE_CAMERA = this.camera.isPerspectiveCamera ? 1 : 0; + this.gtaoMaterial.uniforms.tNoise.value = this.gtaoNoiseTexture; + this.gtaoMaterial.uniforms.resolution.value.set(this.width, this.height); + this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near; + this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far; + this.normalMaterial = new MeshNormalMaterial; + this.normalMaterial.blending = NoBlending; + this.pdMaterial = new ShaderMaterial({ + defines: Object.assign({}, PoissonDenoiseShader.defines), + uniforms: UniformsUtils.clone(PoissonDenoiseShader.uniforms), + vertexShader: PoissonDenoiseShader.vertexShader, + fragmentShader: PoissonDenoiseShader.fragmentShader, + depthTest: false, + depthWrite: false + }); + this.pdMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture; + this.pdMaterial.uniforms.tNoise.value = this.pdNoiseTexture; + this.pdMaterial.uniforms.resolution.value.set(this.width, this.height); + this.pdMaterial.uniforms.lumaPhi.value = 10; + this.pdMaterial.uniforms.depthPhi.value = 2; + this.pdMaterial.uniforms.normalPhi.value = 3; + this.pdMaterial.uniforms.radius.value = 8; + this.depthRenderMaterial = new ShaderMaterial({ + defines: Object.assign({}, GTAODepthShader.defines), + uniforms: UniformsUtils.clone(GTAODepthShader.uniforms), + vertexShader: GTAODepthShader.vertexShader, + fragmentShader: GTAODepthShader.fragmentShader, + blending: NoBlending + }); + this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near; + this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far; + this.copyMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(CopyShader.uniforms), + vertexShader: CopyShader.vertexShader, + fragmentShader: CopyShader.fragmentShader, + transparent: true, + depthTest: false, + depthWrite: false, + blendSrc: DstColorFactor, + blendDst: ZeroFactor, + blendEquation: AddEquation, + blendSrcAlpha: DstAlphaFactor, + blendDstAlpha: ZeroFactor, + blendEquationAlpha: AddEquation + }); + this.blendMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(GTAOBlendShader.uniforms), + vertexShader: GTAOBlendShader.vertexShader, + fragmentShader: GTAOBlendShader.fragmentShader, + transparent: true, + depthTest: false, + depthWrite: false, + blending: CustomBlending, + blendSrc: DstColorFactor, + blendDst: ZeroFactor, + blendEquation: AddEquation, + blendSrcAlpha: DstAlphaFactor, + blendDstAlpha: ZeroFactor, + blendEquationAlpha: AddEquation + }); + this.fsQuad = new FullScreenQuad(null); + this.originalClearColor = new Color; + this.setGBuffer(parameters ? parameters.depthTexture : undefined, parameters ? parameters.normalTexture : undefined); + if (aoParameters !== undefined) { + this.updateGtaoMaterial(aoParameters); + } + if (pdParameters !== undefined) { + this.updatePdMaterial(pdParameters); + } + } + dispose() { + this.gtaoNoiseTexture.dispose(); + this.pdNoiseTexture.dispose(); + this.normalRenderTarget.dispose(); + this.gtaoRenderTarget.dispose(); + this.pdRenderTarget.dispose(); + this.normalMaterial.dispose(); + this.pdMaterial.dispose(); + this.copyMaterial.dispose(); + this.depthRenderMaterial.dispose(); + this.fsQuad.dispose(); + } + get gtaoMap() { + return this.pdRenderTarget.texture; + } + setGBuffer(depthTexture, normalTexture) { + if (depthTexture !== undefined) { + this.depthTexture = depthTexture; + this.normalTexture = normalTexture; + this._renderGBuffer = false; + } else { + this.depthTexture = new DepthTexture; + this.depthTexture.format = DepthStencilFormat; + this.depthTexture.type = UnsignedInt248Type; + this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType, + depthTexture: this.depthTexture + }); + this.normalTexture = this.normalRenderTarget.texture; + this._renderGBuffer = true; + } + const normalVectorType = this.normalTexture ? 1 : 0; + const depthValueSource = this.depthTexture === this.normalTexture ? "w" : "x"; + this.gtaoMaterial.defines.NORMAL_VECTOR_TYPE = normalVectorType; + this.gtaoMaterial.defines.DEPTH_SWIZZLING = depthValueSource; + this.gtaoMaterial.uniforms.tNormal.value = this.normalTexture; + this.gtaoMaterial.uniforms.tDepth.value = this.depthTexture; + this.pdMaterial.defines.NORMAL_VECTOR_TYPE = normalVectorType; + this.pdMaterial.defines.DEPTH_SWIZZLING = depthValueSource; + this.pdMaterial.uniforms.tNormal.value = this.normalTexture; + this.pdMaterial.uniforms.tDepth.value = this.depthTexture; + this.depthRenderMaterial.uniforms.tDepth.value = this.normalRenderTarget.depthTexture; + } + setSceneClipBox(box) { + if (box) { + this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX !== 1; + this.gtaoMaterial.defines.SCENE_CLIP_BOX = 1; + this.gtaoMaterial.uniforms.sceneBoxMin.value.copy(box.min); + this.gtaoMaterial.uniforms.sceneBoxMax.value.copy(box.max); + } else { + this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX === 0; + this.gtaoMaterial.defines.SCENE_CLIP_BOX = 0; + } + } + updateGtaoMaterial(parameters) { + if (parameters.radius !== undefined) { + this.gtaoMaterial.uniforms.radius.value = parameters.radius; + } + if (parameters.distanceExponent !== undefined) { + this.gtaoMaterial.uniforms.distanceExponent.value = parameters.distanceExponent; + } + if (parameters.thickness !== undefined) { + this.gtaoMaterial.uniforms.thickness.value = parameters.thickness; + } + if (parameters.distanceFallOff !== undefined) { + this.gtaoMaterial.uniforms.distanceFallOff.value = parameters.distanceFallOff; + this.gtaoMaterial.needsUpdate = true; + } + if (parameters.scale !== undefined) { + this.gtaoMaterial.uniforms.scale.value = parameters.scale; + } + if (parameters.samples !== undefined && parameters.samples !== this.gtaoMaterial.defines.SAMPLES) { + this.gtaoMaterial.defines.SAMPLES = parameters.samples; + this.gtaoMaterial.needsUpdate = true; + } + if (parameters.screenSpaceRadius !== undefined && (parameters.screenSpaceRadius ? 1 : 0) !== this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS) { + this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS = parameters.screenSpaceRadius ? 1 : 0; + this.gtaoMaterial.needsUpdate = true; + } + } + updatePdMaterial(parameters) { + let updateShader = false; + if (parameters.lumaPhi !== undefined) { + this.pdMaterial.uniforms.lumaPhi.value = parameters.lumaPhi; + } + if (parameters.depthPhi !== undefined) { + this.pdMaterial.uniforms.depthPhi.value = parameters.depthPhi; + } + if (parameters.normalPhi !== undefined) { + this.pdMaterial.uniforms.normalPhi.value = parameters.normalPhi; + } + if (parameters.radius !== undefined && parameters.radius !== this.radius) { + this.pdMaterial.uniforms.radius.value = parameters.radius; + } + if (parameters.radiusExponent !== undefined && parameters.radiusExponent !== this.pdRadiusExponent) { + this.pdRadiusExponent = parameters.radiusExponent; + updateShader = true; + } + if (parameters.rings !== undefined && parameters.rings !== this.pdRings) { + this.pdRings = parameters.rings; + updateShader = true; + } + if (parameters.samples !== undefined && parameters.samples !== this.pdSamples) { + this.pdSamples = parameters.samples; + updateShader = true; + } + if (updateShader) { + this.pdMaterial.defines.SAMPLES = this.pdSamples; + this.pdMaterial.defines.SAMPLE_VECTORS = generatePdSamplePointInitializer(this.pdSamples, this.pdRings, this.pdRadiusExponent); + this.pdMaterial.needsUpdate = true; + } + } + render(renderer2, writeBuffer, readBuffer) { + if (this._renderGBuffer) { + this.overrideVisibility(); + this.renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 7829503, 1); + this.restoreVisibility(); + } + this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near; + this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far; + this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix); + this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); + this.gtaoMaterial.uniforms.cameraWorldMatrix.value.copy(this.camera.matrixWorld); + this.renderPass(renderer2, this.gtaoMaterial, this.gtaoRenderTarget, 16777215, 1); + this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); + this.renderPass(renderer2, this.pdMaterial, this.pdRenderTarget, 16777215, 1); + switch (this.output) { + case GTAOPass.OUTPUT.Off: + break; + case GTAOPass.OUTPUT.Diffuse: + this.copyMaterial.uniforms.tDiffuse.value = readBuffer.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.AO: + this.copyMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.Denoise: + this.copyMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.Depth: + this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near; + this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far; + this.renderPass(renderer2, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.Normal: + this.copyMaterial.uniforms.tDiffuse.value = this.normalRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.Default: + this.copyMaterial.uniforms.tDiffuse.value = readBuffer.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + this.blendMaterial.uniforms.intensity.value = this.blendIntensity; + this.blendMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture; + this.renderPass(renderer2, this.blendMaterial, this.renderToScreen ? null : writeBuffer); + break; + default: + console.warn("THREE.GTAOPass: Unknown output type."); + } + } + renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.fsQuad.material = passMaterial; + this.fsQuad.render(renderer2); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.overrideMaterial = overrideMaterial; + renderer2.render(this.scene, this.camera); + this.scene.overrideMaterial = null; + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + setSize(width2, height2) { + this.width = width2; + this.height = height2; + this.gtaoRenderTarget.setSize(width2, height2); + this.normalRenderTarget.setSize(width2, height2); + this.pdRenderTarget.setSize(width2, height2); + this.gtaoMaterial.uniforms.resolution.value.set(width2, height2); + this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix); + this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); + this.pdMaterial.uniforms.resolution.value.set(width2, height2); + this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); + } + overrideVisibility() { + const scene = this.scene; + const cache = this._visibilityCache; + scene.traverse(function(object) { + cache.set(object, object.visible); + if (object.isPoints || object.isLine) + object.visible = false; + }); + } + restoreVisibility() { + const scene = this.scene; + const cache = this._visibilityCache; + scene.traverse(function(object) { + const visible = cache.get(object); + object.visible = visible; + }); + cache.clear(); + } + generateNoise(size2 = 64) { + const simplex = new SimplexNoise; + const arraySize = size2 * size2 * 4; + const data2 = new Uint8Array(arraySize); + for (let i = 0;i < size2; i++) { + for (let j2 = 0;j2 < size2; j2++) { + const x2 = i; + const y = j2; + data2[(i * size2 + j2) * 4] = (simplex.noise(x2, y) * 0.5 + 0.5) * 255; + data2[(i * size2 + j2) * 4 + 1] = (simplex.noise(x2 + size2, y) * 0.5 + 0.5) * 255; + data2[(i * size2 + j2) * 4 + 2] = (simplex.noise(x2, y + size2) * 0.5 + 0.5) * 255; + data2[(i * size2 + j2) * 4 + 3] = (simplex.noise(x2 + size2, y + size2) * 0.5 + 0.5) * 255; + } + } + const noiseTexture = new DataTexture(data2, size2, size2, RGBAFormat, UnsignedByteType); + noiseTexture.wrapS = RepeatWrapping; + noiseTexture.wrapT = RepeatWrapping; + noiseTexture.needsUpdate = true; + return noiseTexture; + } +} +GTAOPass.OUTPUT = { + Off: -1, + Default: 0, + Diffuse: 1, + Depth: 2, + Normal: 3, + AO: 4, + Denoise: 5 +}; +// node_modules/three/examples/jsm/shaders/HalftoneShader.js +var HalftoneShader = { + name: "HalftoneShader", + uniforms: { + tDiffuse: { value: null }, + shape: { value: 1 }, + radius: { value: 4 }, + rotateR: { value: Math.PI / 12 * 1 }, + rotateG: { value: Math.PI / 12 * 2 }, + rotateB: { value: Math.PI / 12 * 3 }, + scatter: { value: 0 }, + width: { value: 1 }, + height: { value: 1 }, + blending: { value: 1 }, + blendingMode: { value: 1 }, + greyscale: { value: false }, + disable: { value: false } + }, + vertexShader: ` + + varying vec2 vUV; + + void main() { + + vUV = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + + }`, + fragmentShader: ` + + #define SQRT2_MINUS_ONE 0.41421356 + #define SQRT2_HALF_MINUS_ONE 0.20710678 + #define PI2 6.28318531 + #define SHAPE_DOT 1 + #define SHAPE_ELLIPSE 2 + #define SHAPE_LINE 3 + #define SHAPE_SQUARE 4 + #define BLENDING_LINEAR 1 + #define BLENDING_MULTIPLY 2 + #define BLENDING_ADD 3 + #define BLENDING_LIGHTER 4 + #define BLENDING_DARKER 5 + uniform sampler2D tDiffuse; + uniform float radius; + uniform float rotateR; + uniform float rotateG; + uniform float rotateB; + uniform float scatter; + uniform float width; + uniform float height; + uniform int shape; + uniform bool disable; + uniform float blending; + uniform int blendingMode; + varying vec2 vUV; + uniform bool greyscale; + const int samples = 8; + + float blend( float a, float b, float t ) { + + // linear blend + return a * ( 1.0 - t ) + b * t; + + } + + float hypot( float x, float y ) { + + // vector magnitude + return sqrt( x * x + y * y ); + + } + + float rand( vec2 seed ){ + + // get pseudo-random number + return fract( sin( dot( seed.xy, vec2( 12.9898, 78.233 ) ) ) * 43758.5453 ); + + } + + float distanceToDotRadius( float channel, vec2 coord, vec2 normal, vec2 p, float angle, float rad_max ) { + + // apply shape-specific transforms + float dist = hypot( coord.x - p.x, coord.y - p.y ); + float rad = channel; + + if ( shape == SHAPE_DOT ) { + + rad = pow( abs( rad ), 1.125 ) * rad_max; + + } else if ( shape == SHAPE_ELLIPSE ) { + + rad = pow( abs( rad ), 1.125 ) * rad_max; + + if ( dist != 0.0 ) { + float dot_p = abs( ( p.x - coord.x ) / dist * normal.x + ( p.y - coord.y ) / dist * normal.y ); + dist = ( dist * ( 1.0 - SQRT2_HALF_MINUS_ONE ) ) + dot_p * dist * SQRT2_MINUS_ONE; + } + + } else if ( shape == SHAPE_LINE ) { + + rad = pow( abs( rad ), 1.5) * rad_max; + float dot_p = ( p.x - coord.x ) * normal.x + ( p.y - coord.y ) * normal.y; + dist = hypot( normal.x * dot_p, normal.y * dot_p ); + + } else if ( shape == SHAPE_SQUARE ) { + + float theta = atan( p.y - coord.y, p.x - coord.x ) - angle; + float sin_t = abs( sin( theta ) ); + float cos_t = abs( cos( theta ) ); + rad = pow( abs( rad ), 1.4 ); + rad = rad_max * ( rad + ( ( sin_t > cos_t ) ? rad - sin_t * rad : rad - cos_t * rad ) ); + + } + + return rad - dist; + + } + + struct Cell { + + // grid sample positions + vec2 normal; + vec2 p1; + vec2 p2; + vec2 p3; + vec2 p4; + float samp2; + float samp1; + float samp3; + float samp4; + + }; + + vec4 getSample( vec2 point ) { + + // multi-sampled point + vec4 tex = texture2D( tDiffuse, vec2( point.x / width, point.y / height ) ); + float base = rand( vec2( floor( point.x ), floor( point.y ) ) ) * PI2; + float step = PI2 / float( samples ); + float dist = radius * 0.66; + + for ( int i = 0; i < samples; ++i ) { + + float r = base + step * float( i ); + vec2 coord = point + vec2( cos( r ) * dist, sin( r ) * dist ); + tex += texture2D( tDiffuse, vec2( coord.x / width, coord.y / height ) ); + + } + + tex /= float( samples ) + 1.0; + return tex; + + } + + float getDotColour( Cell c, vec2 p, int channel, float angle, float aa ) { + + // get colour for given point + float dist_c_1, dist_c_2, dist_c_3, dist_c_4, res; + + if ( channel == 0 ) { + + c.samp1 = getSample( c.p1 ).r; + c.samp2 = getSample( c.p2 ).r; + c.samp3 = getSample( c.p3 ).r; + c.samp4 = getSample( c.p4 ).r; + + } else if (channel == 1) { + + c.samp1 = getSample( c.p1 ).g; + c.samp2 = getSample( c.p2 ).g; + c.samp3 = getSample( c.p3 ).g; + c.samp4 = getSample( c.p4 ).g; + + } else { + + c.samp1 = getSample( c.p1 ).b; + c.samp3 = getSample( c.p3 ).b; + c.samp2 = getSample( c.p2 ).b; + c.samp4 = getSample( c.p4 ).b; + + } + + dist_c_1 = distanceToDotRadius( c.samp1, c.p1, c.normal, p, angle, radius ); + dist_c_2 = distanceToDotRadius( c.samp2, c.p2, c.normal, p, angle, radius ); + dist_c_3 = distanceToDotRadius( c.samp3, c.p3, c.normal, p, angle, radius ); + dist_c_4 = distanceToDotRadius( c.samp4, c.p4, c.normal, p, angle, radius ); + res = ( dist_c_1 > 0.0 ) ? clamp( dist_c_1 / aa, 0.0, 1.0 ) : 0.0; + res += ( dist_c_2 > 0.0 ) ? clamp( dist_c_2 / aa, 0.0, 1.0 ) : 0.0; + res += ( dist_c_3 > 0.0 ) ? clamp( dist_c_3 / aa, 0.0, 1.0 ) : 0.0; + res += ( dist_c_4 > 0.0 ) ? clamp( dist_c_4 / aa, 0.0, 1.0 ) : 0.0; + res = clamp( res, 0.0, 1.0 ); + + return res; + + } + + Cell getReferenceCell( vec2 p, vec2 origin, float grid_angle, float step ) { + + // get containing cell + Cell c; + + // calc grid + vec2 n = vec2( cos( grid_angle ), sin( grid_angle ) ); + float threshold = step * 0.5; + float dot_normal = n.x * ( p.x - origin.x ) + n.y * ( p.y - origin.y ); + float dot_line = -n.y * ( p.x - origin.x ) + n.x * ( p.y - origin.y ); + vec2 offset = vec2( n.x * dot_normal, n.y * dot_normal ); + float offset_normal = mod( hypot( offset.x, offset.y ), step ); + float normal_dir = ( dot_normal < 0.0 ) ? 1.0 : -1.0; + float normal_scale = ( ( offset_normal < threshold ) ? -offset_normal : step - offset_normal ) * normal_dir; + float offset_line = mod( hypot( ( p.x - offset.x ) - origin.x, ( p.y - offset.y ) - origin.y ), step ); + float line_dir = ( dot_line < 0.0 ) ? 1.0 : -1.0; + float line_scale = ( ( offset_line < threshold ) ? -offset_line : step - offset_line ) * line_dir; + + // get closest corner + c.normal = n; + c.p1.x = p.x - n.x * normal_scale + n.y * line_scale; + c.p1.y = p.y - n.y * normal_scale - n.x * line_scale; + + // scatter + if ( scatter != 0.0 ) { + + float off_mag = scatter * threshold * 0.5; + float off_angle = rand( vec2( floor( c.p1.x ), floor( c.p1.y ) ) ) * PI2; + c.p1.x += cos( off_angle ) * off_mag; + c.p1.y += sin( off_angle ) * off_mag; + + } + + // find corners + float normal_step = normal_dir * ( ( offset_normal < threshold ) ? step : -step ); + float line_step = line_dir * ( ( offset_line < threshold ) ? step : -step ); + c.p2.x = c.p1.x - n.x * normal_step; + c.p2.y = c.p1.y - n.y * normal_step; + c.p3.x = c.p1.x + n.y * line_step; + c.p3.y = c.p1.y - n.x * line_step; + c.p4.x = c.p1.x - n.x * normal_step + n.y * line_step; + c.p4.y = c.p1.y - n.y * normal_step - n.x * line_step; + + return c; + + } + + float blendColour( float a, float b, float t ) { + + // blend colours + if ( blendingMode == BLENDING_LINEAR ) { + return blend( a, b, 1.0 - t ); + } else if ( blendingMode == BLENDING_ADD ) { + return blend( a, min( 1.0, a + b ), t ); + } else if ( blendingMode == BLENDING_MULTIPLY ) { + return blend( a, max( 0.0, a * b ), t ); + } else if ( blendingMode == BLENDING_LIGHTER ) { + return blend( a, max( a, b ), t ); + } else if ( blendingMode == BLENDING_DARKER ) { + return blend( a, min( a, b ), t ); + } else { + return blend( a, b, 1.0 - t ); + } + + } + + void main() { + + if ( ! disable ) { + + // setup + vec2 p = vec2( vUV.x * width, vUV.y * height ); + vec2 origin = vec2( 0, 0 ); + float aa = ( radius < 2.5 ) ? radius * 0.5 : 1.25; + + // get channel samples + Cell cell_r = getReferenceCell( p, origin, rotateR, radius ); + Cell cell_g = getReferenceCell( p, origin, rotateG, radius ); + Cell cell_b = getReferenceCell( p, origin, rotateB, radius ); + float r = getDotColour( cell_r, p, 0, rotateR, aa ); + float g = getDotColour( cell_g, p, 1, rotateG, aa ); + float b = getDotColour( cell_b, p, 2, rotateB, aa ); + + // blend with original + vec4 colour = texture2D( tDiffuse, vUV ); + r = blendColour( r, colour.r, blending ); + g = blendColour( g, colour.g, blending ); + b = blendColour( b, colour.b, blending ); + + if ( greyscale ) { + r = g = b = (r + b + g) / 3.0; + } + + gl_FragColor = vec4( r, g, b, 1.0 ); + + } else { + + gl_FragColor = texture2D( tDiffuse, vUV ); + + } + + }` +}; +// node_modules/three/examples/jsm/postprocessing/OutlinePass.js +class OutlinePass extends Pass { + constructor(resolution, scene, camera, selectedObjects) { + super(); + this.renderScene = scene; + this.renderCamera = camera; + this.selectedObjects = selectedObjects !== undefined ? selectedObjects : []; + this.visibleEdgeColor = new Color(1, 1, 1); + this.hiddenEdgeColor = new Color(0.1, 0.04, 0.02); + this.edgeGlow = 0; + this.usePatternTexture = false; + this.edgeThickness = 1; + this.edgeStrength = 3; + this.downSampleRatio = 2; + this.pulsePeriod = 0; + this._visibilityCache = new Map; + this._selectionCache = new Set; + this.resolution = resolution !== undefined ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256); + const resx = Math.round(this.resolution.x / this.downSampleRatio); + const resy = Math.round(this.resolution.y / this.downSampleRatio); + this.renderTargetMaskBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y); + this.renderTargetMaskBuffer.texture.name = "OutlinePass.mask"; + this.renderTargetMaskBuffer.texture.generateMipmaps = false; + this.depthMaterial = new MeshDepthMaterial; + this.depthMaterial.side = DoubleSide; + this.depthMaterial.depthPacking = RGBADepthPacking; + this.depthMaterial.blending = NoBlending; + this.prepareMaskMaterial = this.getPrepareMaskMaterial(); + this.prepareMaskMaterial.side = DoubleSide; + this.prepareMaskMaterial.fragmentShader = replaceDepthToViewZ(this.prepareMaskMaterial.fragmentShader, this.renderCamera); + this.renderTargetDepthBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { type: HalfFloatType }); + this.renderTargetDepthBuffer.texture.name = "OutlinePass.depth"; + this.renderTargetDepthBuffer.texture.generateMipmaps = false; + this.renderTargetMaskDownSampleBuffer = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + this.renderTargetMaskDownSampleBuffer.texture.name = "OutlinePass.depthDownSample"; + this.renderTargetMaskDownSampleBuffer.texture.generateMipmaps = false; + this.renderTargetBlurBuffer1 = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + this.renderTargetBlurBuffer1.texture.name = "OutlinePass.blur1"; + this.renderTargetBlurBuffer1.texture.generateMipmaps = false; + this.renderTargetBlurBuffer2 = new WebGLRenderTarget(Math.round(resx / 2), Math.round(resy / 2), { type: HalfFloatType }); + this.renderTargetBlurBuffer2.texture.name = "OutlinePass.blur2"; + this.renderTargetBlurBuffer2.texture.generateMipmaps = false; + this.edgeDetectionMaterial = this.getEdgeDetectionMaterial(); + this.renderTargetEdgeBuffer1 = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + this.renderTargetEdgeBuffer1.texture.name = "OutlinePass.edge1"; + this.renderTargetEdgeBuffer1.texture.generateMipmaps = false; + this.renderTargetEdgeBuffer2 = new WebGLRenderTarget(Math.round(resx / 2), Math.round(resy / 2), { type: HalfFloatType }); + this.renderTargetEdgeBuffer2.texture.name = "OutlinePass.edge2"; + this.renderTargetEdgeBuffer2.texture.generateMipmaps = false; + const MAX_EDGE_THICKNESS = 4; + const MAX_EDGE_GLOW = 4; + this.separableBlurMaterial1 = this.getSeparableBlurMaterial(MAX_EDGE_THICKNESS); + this.separableBlurMaterial1.uniforms["texSize"].value.set(resx, resy); + this.separableBlurMaterial1.uniforms["kernelRadius"].value = 1; + this.separableBlurMaterial2 = this.getSeparableBlurMaterial(MAX_EDGE_GLOW); + this.separableBlurMaterial2.uniforms["texSize"].value.set(Math.round(resx / 2), Math.round(resy / 2)); + this.separableBlurMaterial2.uniforms["kernelRadius"].value = MAX_EDGE_GLOW; + this.overlayMaterial = this.getOverlayMaterial(); + const copyShader = CopyShader; + this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); + this.materialCopy = new ShaderMaterial({ + uniforms: this.copyUniforms, + vertexShader: copyShader.vertexShader, + fragmentShader: copyShader.fragmentShader, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + this.enabled = true; + this.needsSwap = false; + this._oldClearColor = new Color; + this.oldClearAlpha = 1; + this.fsQuad = new FullScreenQuad(null); + this.tempPulseColor1 = new Color; + this.tempPulseColor2 = new Color; + this.textureMatrix = new Matrix4; + function replaceDepthToViewZ(string, camera2) { + const type = camera2.isPerspectiveCamera ? "perspective" : "orthographic"; + return string.replace(/DEPTH_TO_VIEW_Z/g, type + "DepthToViewZ"); + } + } + dispose() { + this.renderTargetMaskBuffer.dispose(); + this.renderTargetDepthBuffer.dispose(); + this.renderTargetMaskDownSampleBuffer.dispose(); + this.renderTargetBlurBuffer1.dispose(); + this.renderTargetBlurBuffer2.dispose(); + this.renderTargetEdgeBuffer1.dispose(); + this.renderTargetEdgeBuffer2.dispose(); + this.depthMaterial.dispose(); + this.prepareMaskMaterial.dispose(); + this.edgeDetectionMaterial.dispose(); + this.separableBlurMaterial1.dispose(); + this.separableBlurMaterial2.dispose(); + this.overlayMaterial.dispose(); + this.materialCopy.dispose(); + this.fsQuad.dispose(); + } + setSize(width2, height2) { + this.renderTargetMaskBuffer.setSize(width2, height2); + this.renderTargetDepthBuffer.setSize(width2, height2); + let resx = Math.round(width2 / this.downSampleRatio); + let resy = Math.round(height2 / this.downSampleRatio); + this.renderTargetMaskDownSampleBuffer.setSize(resx, resy); + this.renderTargetBlurBuffer1.setSize(resx, resy); + this.renderTargetEdgeBuffer1.setSize(resx, resy); + this.separableBlurMaterial1.uniforms["texSize"].value.set(resx, resy); + resx = Math.round(resx / 2); + resy = Math.round(resy / 2); + this.renderTargetBlurBuffer2.setSize(resx, resy); + this.renderTargetEdgeBuffer2.setSize(resx, resy); + this.separableBlurMaterial2.uniforms["texSize"].value.set(resx, resy); + } + updateSelectionCache() { + const cache = this._selectionCache; + function gatherSelectedMeshesCallBack(object) { + if (object.isMesh) + cache.add(object); + } + cache.clear(); + for (let i = 0;i < this.selectedObjects.length; i++) { + const selectedObject = this.selectedObjects[i]; + selectedObject.traverse(gatherSelectedMeshesCallBack); + } + } + changeVisibilityOfSelectedObjects(bVisible) { + const cache = this._visibilityCache; + for (const mesh of this._selectionCache) { + if (bVisible === true) { + mesh.visible = cache.get(mesh); + } else { + cache.set(mesh, mesh.visible); + mesh.visible = bVisible; + } + } + } + changeVisibilityOfNonSelectedObjects(bVisible) { + const visibilityCache = this._visibilityCache; + const selectionCache = this._selectionCache; + function VisibilityChangeCallBack(object) { + if (object.isMesh || object.isSprite) { + if (!selectionCache.has(object)) { + const visibility = object.visible; + if (bVisible === false || visibilityCache.get(object) === true) { + object.visible = bVisible; + } + visibilityCache.set(object, visibility); + } + } else if (object.isPoints || object.isLine) { + if (bVisible === true) { + object.visible = visibilityCache.get(object); + } else { + visibilityCache.set(object, object.visible); + object.visible = bVisible; + } + } + } + this.renderScene.traverse(VisibilityChangeCallBack); + } + updateTextureMatrix() { + this.textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + this.textureMatrix.multiply(this.renderCamera.projectionMatrix); + this.textureMatrix.multiply(this.renderCamera.matrixWorldInverse); + } + render(renderer2, writeBuffer, readBuffer, deltaTime, maskActive) { + if (this.selectedObjects.length > 0) { + renderer2.getClearColor(this._oldClearColor); + this.oldClearAlpha = renderer2.getClearAlpha(); + const oldAutoClear = renderer2.autoClear; + renderer2.autoClear = false; + if (maskActive) + renderer2.state.buffers.stencil.setTest(false); + renderer2.setClearColor(16777215, 1); + this.updateSelectionCache(); + this.changeVisibilityOfSelectedObjects(false); + const currentBackground = this.renderScene.background; + this.renderScene.background = null; + this.renderScene.overrideMaterial = this.depthMaterial; + renderer2.setRenderTarget(this.renderTargetDepthBuffer); + renderer2.clear(); + renderer2.render(this.renderScene, this.renderCamera); + this.changeVisibilityOfSelectedObjects(true); + this._visibilityCache.clear(); + this.updateTextureMatrix(); + this.changeVisibilityOfNonSelectedObjects(false); + this.renderScene.overrideMaterial = this.prepareMaskMaterial; + this.prepareMaskMaterial.uniforms["cameraNearFar"].value.set(this.renderCamera.near, this.renderCamera.far); + this.prepareMaskMaterial.uniforms["depthTexture"].value = this.renderTargetDepthBuffer.texture; + this.prepareMaskMaterial.uniforms["textureMatrix"].value = this.textureMatrix; + renderer2.setRenderTarget(this.renderTargetMaskBuffer); + renderer2.clear(); + renderer2.render(this.renderScene, this.renderCamera); + this.renderScene.overrideMaterial = null; + this.changeVisibilityOfNonSelectedObjects(true); + this._visibilityCache.clear(); + this._selectionCache.clear(); + this.renderScene.background = currentBackground; + this.fsQuad.material = this.materialCopy; + this.copyUniforms["tDiffuse"].value = this.renderTargetMaskBuffer.texture; + renderer2.setRenderTarget(this.renderTargetMaskDownSampleBuffer); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.tempPulseColor1.copy(this.visibleEdgeColor); + this.tempPulseColor2.copy(this.hiddenEdgeColor); + if (this.pulsePeriod > 0) { + const scalar = (1 + 0.25) / 2 + Math.cos(performance.now() * 0.01 / this.pulsePeriod) * (1 - 0.25) / 2; + this.tempPulseColor1.multiplyScalar(scalar); + this.tempPulseColor2.multiplyScalar(scalar); + } + this.fsQuad.material = this.edgeDetectionMaterial; + this.edgeDetectionMaterial.uniforms["maskTexture"].value = this.renderTargetMaskDownSampleBuffer.texture; + this.edgeDetectionMaterial.uniforms["texSize"].value.set(this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height); + this.edgeDetectionMaterial.uniforms["visibleEdgeColor"].value = this.tempPulseColor1; + this.edgeDetectionMaterial.uniforms["hiddenEdgeColor"].value = this.tempPulseColor2; + renderer2.setRenderTarget(this.renderTargetEdgeBuffer1); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.separableBlurMaterial1; + this.separableBlurMaterial1.uniforms["colorTexture"].value = this.renderTargetEdgeBuffer1.texture; + this.separableBlurMaterial1.uniforms["direction"].value = OutlinePass.BlurDirectionX; + this.separableBlurMaterial1.uniforms["kernelRadius"].value = this.edgeThickness; + renderer2.setRenderTarget(this.renderTargetBlurBuffer1); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.separableBlurMaterial1.uniforms["colorTexture"].value = this.renderTargetBlurBuffer1.texture; + this.separableBlurMaterial1.uniforms["direction"].value = OutlinePass.BlurDirectionY; + renderer2.setRenderTarget(this.renderTargetEdgeBuffer1); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.separableBlurMaterial2; + this.separableBlurMaterial2.uniforms["colorTexture"].value = this.renderTargetEdgeBuffer1.texture; + this.separableBlurMaterial2.uniforms["direction"].value = OutlinePass.BlurDirectionX; + renderer2.setRenderTarget(this.renderTargetBlurBuffer2); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.separableBlurMaterial2.uniforms["colorTexture"].value = this.renderTargetBlurBuffer2.texture; + this.separableBlurMaterial2.uniforms["direction"].value = OutlinePass.BlurDirectionY; + renderer2.setRenderTarget(this.renderTargetEdgeBuffer2); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.overlayMaterial; + this.overlayMaterial.uniforms["maskTexture"].value = this.renderTargetMaskBuffer.texture; + this.overlayMaterial.uniforms["edgeTexture1"].value = this.renderTargetEdgeBuffer1.texture; + this.overlayMaterial.uniforms["edgeTexture2"].value = this.renderTargetEdgeBuffer2.texture; + this.overlayMaterial.uniforms["patternTexture"].value = this.patternTexture; + this.overlayMaterial.uniforms["edgeStrength"].value = this.edgeStrength; + this.overlayMaterial.uniforms["edgeGlow"].value = this.edgeGlow; + this.overlayMaterial.uniforms["usePatternTexture"].value = this.usePatternTexture; + if (maskActive) + renderer2.state.buffers.stencil.setTest(true); + renderer2.setRenderTarget(readBuffer); + this.fsQuad.render(renderer2); + renderer2.setClearColor(this._oldClearColor, this.oldClearAlpha); + renderer2.autoClear = oldAutoClear; + } + if (this.renderToScreen) { + this.fsQuad.material = this.materialCopy; + this.copyUniforms["tDiffuse"].value = readBuffer.texture; + renderer2.setRenderTarget(null); + this.fsQuad.render(renderer2); + } + } + getPrepareMaskMaterial() { + return new ShaderMaterial({ + uniforms: { + depthTexture: { value: null }, + cameraNearFar: { value: new Vector2(0.5, 0.5) }, + textureMatrix: { value: null } + }, + vertexShader: `#include + #include + + varying vec4 projTexCoord; + varying vec4 vPosition; + uniform mat4 textureMatrix; + + void main() { + + #include + #include + #include + #include + #include + + vPosition = mvPosition; + + vec4 worldPosition = vec4( transformed, 1.0 ); + + #ifdef USE_INSTANCING + + worldPosition = instanceMatrix * worldPosition; + + #endif + + worldPosition = modelMatrix * worldPosition; + + projTexCoord = textureMatrix * worldPosition; + + }`, + fragmentShader: `#include + varying vec4 vPosition; + varying vec4 projTexCoord; + uniform sampler2D depthTexture; + uniform vec2 cameraNearFar; + + void main() { + + float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord )); + float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y ); + float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0; + gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0); + + }` + }); + } + getEdgeDetectionMaterial() { + return new ShaderMaterial({ + uniforms: { + maskTexture: { value: null }, + texSize: { value: new Vector2(0.5, 0.5) }, + visibleEdgeColor: { value: new Vector3(1, 1, 1) }, + hiddenEdgeColor: { value: new Vector3(1, 1, 1) } + }, + vertexShader: `varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `varying vec2 vUv; + + uniform sampler2D maskTexture; + uniform vec2 texSize; + uniform vec3 visibleEdgeColor; + uniform vec3 hiddenEdgeColor; + + void main() { + vec2 invSize = 1.0 / texSize; + vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize); + vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy); + vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy); + vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw); + vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw); + float diff1 = (c1.r - c2.r)*0.5; + float diff2 = (c3.r - c4.r)*0.5; + float d = length( vec2(diff1, diff2) ); + float a1 = min(c1.g, c2.g); + float a2 = min(c3.g, c4.g); + float visibilityFactor = min(a1, a2); + vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor; + gl_FragColor = vec4(edgeColor, 1.0) * vec4(d); + }` + }); + } + getSeparableBlurMaterial(maxRadius) { + return new ShaderMaterial({ + defines: { + MAX_RADIUS: maxRadius + }, + uniforms: { + colorTexture: { value: null }, + texSize: { value: new Vector2(0.5, 0.5) }, + direction: { value: new Vector2(0.5, 0.5) }, + kernelRadius: { value: 1 } + }, + vertexShader: `varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `#include + varying vec2 vUv; + uniform sampler2D colorTexture; + uniform vec2 texSize; + uniform vec2 direction; + uniform float kernelRadius; + + float gaussianPdf(in float x, in float sigma) { + return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma; + } + + void main() { + vec2 invSize = 1.0 / texSize; + float sigma = kernelRadius/2.0; + float weightSum = gaussianPdf(0.0, sigma); + vec4 diffuseSum = texture2D( colorTexture, vUv) * weightSum; + vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS); + vec2 uvOffset = delta; + for( int i = 1; i <= MAX_RADIUS; i ++ ) { + float x = kernelRadius * float(i) / float(MAX_RADIUS); + float w = gaussianPdf(x, sigma); + vec4 sample1 = texture2D( colorTexture, vUv + uvOffset); + vec4 sample2 = texture2D( colorTexture, vUv - uvOffset); + diffuseSum += ((sample1 + sample2) * w); + weightSum += (2.0 * w); + uvOffset += delta; + } + gl_FragColor = diffuseSum/weightSum; + }` + }); + } + getOverlayMaterial() { + return new ShaderMaterial({ + uniforms: { + maskTexture: { value: null }, + edgeTexture1: { value: null }, + edgeTexture2: { value: null }, + patternTexture: { value: null }, + edgeStrength: { value: 1 }, + edgeGlow: { value: 1 }, + usePatternTexture: { value: 0 } + }, + vertexShader: `varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `varying vec2 vUv; + + uniform sampler2D maskTexture; + uniform sampler2D edgeTexture1; + uniform sampler2D edgeTexture2; + uniform sampler2D patternTexture; + uniform float edgeStrength; + uniform float edgeGlow; + uniform bool usePatternTexture; + + void main() { + vec4 edgeValue1 = texture2D(edgeTexture1, vUv); + vec4 edgeValue2 = texture2D(edgeTexture2, vUv); + vec4 maskColor = texture2D(maskTexture, vUv); + vec4 patternColor = texture2D(patternTexture, 6.0 * vUv); + float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5; + vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow; + vec4 finalColor = edgeStrength * maskColor.r * edgeValue; + if(usePatternTexture) + finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r); + gl_FragColor = finalColor; + }`, + blending: AdditiveBlending, + depthTest: false, + depthWrite: false, + transparent: true + }); + } +} +OutlinePass.BlurDirectionX = new Vector2(1, 0); +OutlinePass.BlurDirectionY = new Vector2(0, 1); +// node_modules/three/examples/jsm/shaders/SAOShader.js +var SAOShader = { + name: "SAOShader", + defines: { + NUM_SAMPLES: 7, + NUM_RINGS: 4, + DIFFUSE_TEXTURE: 0, + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDepth: { value: null }, + tDiffuse: { value: null }, + tNormal: { value: null }, + size: { value: new Vector2(512, 512) }, + cameraNear: { value: 1 }, + cameraFar: { value: 100 }, + cameraProjectionMatrix: { value: new Matrix4 }, + cameraInverseProjectionMatrix: { value: new Matrix4 }, + scale: { value: 1 }, + intensity: { value: 0.1 }, + bias: { value: 0.5 }, + minResolution: { value: 0 }, + kernelRadius: { value: 100 }, + randomSeed: { value: 0 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + #include + + varying vec2 vUv; + + #if DIFFUSE_TEXTURE == 1 + uniform sampler2D tDiffuse; + #endif + + uniform highp sampler2D tDepth; + uniform highp sampler2D tNormal; + + uniform float cameraNear; + uniform float cameraFar; + uniform mat4 cameraProjectionMatrix; + uniform mat4 cameraInverseProjectionMatrix; + + uniform float scale; + uniform float intensity; + uniform float bias; + uniform float kernelRadius; + uniform float minResolution; + uniform vec2 size; + uniform float randomSeed; + + // RGBA depth + + #include + + vec4 getDefaultColor( const in vec2 screenPosition ) { + #if DIFFUSE_TEXTURE == 1 + return texture2D( tDiffuse, vUv ); + #else + return vec4( 1.0 ); + #endif + } + + float getDepth( const in vec2 screenPosition ) { + return texture2D( tDepth, screenPosition ).x; + } + + float getViewZ( const in float depth ) { + #if PERSPECTIVE_CAMERA == 1 + return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + #else + return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + #endif + } + + vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) { + float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3]; + vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 ); + clipPosition *= clipW; // unprojection. + + return ( cameraInverseProjectionMatrix * clipPosition ).xyz; + } + + vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPosition ) { + return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); + } + + float scaleDividedByCameraFar; + float minResolutionMultipliedByCameraFar; + + float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) { + vec3 viewDelta = sampleViewPosition - centerViewPosition; + float viewDistance = length( viewDelta ); + float scaledScreenDistance = scaleDividedByCameraFar * viewDistance; + + return max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - bias) / (1.0 + pow2( scaledScreenDistance ) ); + } + + // moving costly divides into consts + const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES ); + const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES ); + + float getAmbientOcclusion( const in vec3 centerViewPosition ) { + // precompute some variables require in getOcclusion. + scaleDividedByCameraFar = scale / cameraFar; + minResolutionMultipliedByCameraFar = minResolution * cameraFar; + vec3 centerViewNormal = getViewNormal( centerViewPosition, vUv ); + + // jsfiddle that shows sample pattern: https://jsfiddle.net/a16ff1p7/ + float angle = rand( vUv + randomSeed ) * PI2; + vec2 radius = vec2( kernelRadius * INV_NUM_SAMPLES ) / size; + vec2 radiusStep = radius; + + float occlusionSum = 0.0; + float weightSum = 0.0; + + for( int i = 0; i < NUM_SAMPLES; i ++ ) { + vec2 sampleUv = vUv + vec2( cos( angle ), sin( angle ) ) * radius; + radius += radiusStep; + angle += ANGLE_STEP; + + float sampleDepth = getDepth( sampleUv ); + if( sampleDepth >= ( 1.0 - EPSILON ) ) { + continue; + } + + float sampleViewZ = getViewZ( sampleDepth ); + vec3 sampleViewPosition = getViewPosition( sampleUv, sampleDepth, sampleViewZ ); + occlusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition ); + weightSum += 1.0; + } + + if( weightSum == 0.0 ) discard; + + return occlusionSum * ( intensity / weightSum ); + } + + void main() { + float centerDepth = getDepth( vUv ); + if( centerDepth >= ( 1.0 - EPSILON ) ) { + discard; + } + + float centerViewZ = getViewZ( centerDepth ); + vec3 viewPosition = getViewPosition( vUv, centerDepth, centerViewZ ); + + float ambientOcclusion = getAmbientOcclusion( viewPosition ); + + gl_FragColor = getDefaultColor( vUv ); + gl_FragColor.xyz *= 1.0 - ambientOcclusion; + }` +}; + +// node_modules/three/examples/jsm/shaders/DepthLimitedBlurShader.js +var DepthLimitedBlurShader = { + name: "DepthLimitedBlurShader", + defines: { + KERNEL_RADIUS: 4, + DEPTH_PACKING: 1, + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDiffuse: { value: null }, + size: { value: new Vector2(512, 512) }, + sampleUvOffsets: { value: [new Vector2(0, 0)] }, + sampleWeights: { value: [1] }, + tDepth: { value: null }, + cameraNear: { value: 10 }, + cameraFar: { value: 1000 }, + depthCutoff: { value: 10 } + }, + vertexShader: ` + + #include + + uniform vec2 size; + + varying vec2 vUv; + varying vec2 vInvSize; + + void main() { + vUv = uv; + vInvSize = 1.0 / size; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + + #include + #include + + uniform sampler2D tDiffuse; + uniform sampler2D tDepth; + + uniform float cameraNear; + uniform float cameraFar; + uniform float depthCutoff; + + uniform vec2 sampleUvOffsets[ KERNEL_RADIUS + 1 ]; + uniform float sampleWeights[ KERNEL_RADIUS + 1 ]; + + varying vec2 vUv; + varying vec2 vInvSize; + + float getDepth( const in vec2 screenPosition ) { + #if DEPTH_PACKING == 1 + return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) ); + #else + return texture2D( tDepth, screenPosition ).x; + #endif + } + + float getViewZ( const in float depth ) { + #if PERSPECTIVE_CAMERA == 1 + return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + #else + return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + #endif + } + + void main() { + float depth = getDepth( vUv ); + if( depth >= ( 1.0 - EPSILON ) ) { + discard; + } + + float centerViewZ = -getViewZ( depth ); + bool rBreak = false, lBreak = false; + + float weightSum = sampleWeights[0]; + vec4 diffuseSum = texture2D( tDiffuse, vUv ) * weightSum; + + for( int i = 1; i <= KERNEL_RADIUS; i ++ ) { + + float sampleWeight = sampleWeights[i]; + vec2 sampleUvOffset = sampleUvOffsets[i] * vInvSize; + + vec2 sampleUv = vUv + sampleUvOffset; + float viewZ = -getViewZ( getDepth( sampleUv ) ); + + if( abs( viewZ - centerViewZ ) > depthCutoff ) rBreak = true; + + if( ! rBreak ) { + diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight; + weightSum += sampleWeight; + } + + sampleUv = vUv - sampleUvOffset; + viewZ = -getViewZ( getDepth( sampleUv ) ); + + if( abs( viewZ - centerViewZ ) > depthCutoff ) lBreak = true; + + if( ! lBreak ) { + diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight; + weightSum += sampleWeight; + } + + } + + gl_FragColor = diffuseSum / weightSum; + }` +}; +var BlurShaderUtils = { + createSampleWeights: function(kernelRadius, stdDev) { + const weights = []; + for (let i = 0;i <= kernelRadius; i++) { + weights.push(gaussian(i, stdDev)); + } + return weights; + }, + createSampleOffsets: function(kernelRadius, uvIncrement) { + const offsets = []; + for (let i = 0;i <= kernelRadius; i++) { + offsets.push(uvIncrement.clone().multiplyScalar(i)); + } + return offsets; + }, + configure: function(material, kernelRadius, stdDev, uvIncrement) { + material.defines["KERNEL_RADIUS"] = kernelRadius; + material.uniforms["sampleUvOffsets"].value = BlurShaderUtils.createSampleOffsets(kernelRadius, uvIncrement); + material.uniforms["sampleWeights"].value = BlurShaderUtils.createSampleWeights(kernelRadius, stdDev); + material.needsUpdate = true; + } +}; +function gaussian(x2, stdDev) { + return Math.exp(-(x2 * x2) / (2 * (stdDev * stdDev))) / (Math.sqrt(2 * Math.PI) * stdDev); +} + +// node_modules/three/examples/jsm/postprocessing/SAOPass.js +class SAOPass extends Pass { + constructor(scene, camera, resolution = new Vector2(256, 256)) { + super(); + this.scene = scene; + this.camera = camera; + this.clear = true; + this.needsSwap = false; + this.originalClearColor = new Color; + this._oldClearColor = new Color; + this.oldClearAlpha = 1; + this.params = { + output: 0, + saoBias: 0.5, + saoIntensity: 0.18, + saoScale: 1, + saoKernelRadius: 100, + saoMinResolution: 0, + saoBlur: true, + saoBlurRadius: 8, + saoBlurStdDev: 4, + saoBlurDepthCutoff: 0.01 + }; + this.resolution = new Vector2(resolution.x, resolution.y); + this.saoRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { type: HalfFloatType }); + this.blurIntermediateRenderTarget = this.saoRenderTarget.clone(); + const depthTexture = new DepthTexture; + depthTexture.format = DepthStencilFormat; + depthTexture.type = UnsignedInt248Type; + this.normalRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType, + depthTexture + }); + this.normalMaterial = new MeshNormalMaterial; + this.normalMaterial.blending = NoBlending; + this.saoMaterial = new ShaderMaterial({ + defines: Object.assign({}, SAOShader.defines), + fragmentShader: SAOShader.fragmentShader, + vertexShader: SAOShader.vertexShader, + uniforms: UniformsUtils.clone(SAOShader.uniforms) + }); + this.saoMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0; + this.saoMaterial.uniforms["tDepth"].value = depthTexture; + this.saoMaterial.uniforms["tNormal"].value = this.normalRenderTarget.texture; + this.saoMaterial.uniforms["size"].value.set(this.resolution.x, this.resolution.y); + this.saoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.saoMaterial.uniforms["cameraProjectionMatrix"].value = this.camera.projectionMatrix; + this.saoMaterial.blending = NoBlending; + this.vBlurMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(DepthLimitedBlurShader.uniforms), + defines: Object.assign({}, DepthLimitedBlurShader.defines), + vertexShader: DepthLimitedBlurShader.vertexShader, + fragmentShader: DepthLimitedBlurShader.fragmentShader + }); + this.vBlurMaterial.defines["DEPTH_PACKING"] = 0; + this.vBlurMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0; + this.vBlurMaterial.uniforms["tDiffuse"].value = this.saoRenderTarget.texture; + this.vBlurMaterial.uniforms["tDepth"].value = depthTexture; + this.vBlurMaterial.uniforms["size"].value.set(this.resolution.x, this.resolution.y); + this.vBlurMaterial.blending = NoBlending; + this.hBlurMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(DepthLimitedBlurShader.uniforms), + defines: Object.assign({}, DepthLimitedBlurShader.defines), + vertexShader: DepthLimitedBlurShader.vertexShader, + fragmentShader: DepthLimitedBlurShader.fragmentShader + }); + this.hBlurMaterial.defines["DEPTH_PACKING"] = 0; + this.hBlurMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0; + this.hBlurMaterial.uniforms["tDiffuse"].value = this.blurIntermediateRenderTarget.texture; + this.hBlurMaterial.uniforms["tDepth"].value = depthTexture; + this.hBlurMaterial.uniforms["size"].value.set(this.resolution.x, this.resolution.y); + this.hBlurMaterial.blending = NoBlending; + this.materialCopy = new ShaderMaterial({ + uniforms: UniformsUtils.clone(CopyShader.uniforms), + vertexShader: CopyShader.vertexShader, + fragmentShader: CopyShader.fragmentShader, + blending: NoBlending + }); + this.materialCopy.transparent = true; + this.materialCopy.depthTest = false; + this.materialCopy.depthWrite = false; + this.materialCopy.blending = CustomBlending; + this.materialCopy.blendSrc = DstColorFactor; + this.materialCopy.blendDst = ZeroFactor; + this.materialCopy.blendEquation = AddEquation; + this.materialCopy.blendSrcAlpha = DstAlphaFactor; + this.materialCopy.blendDstAlpha = ZeroFactor; + this.materialCopy.blendEquationAlpha = AddEquation; + this.fsQuad = new FullScreenQuad(null); + } + render(renderer2, writeBuffer, readBuffer) { + if (this.renderToScreen) { + this.materialCopy.blending = NoBlending; + this.materialCopy.uniforms["tDiffuse"].value = readBuffer.texture; + this.materialCopy.needsUpdate = true; + this.renderPass(renderer2, this.materialCopy, null); + } + renderer2.getClearColor(this._oldClearColor); + this.oldClearAlpha = renderer2.getClearAlpha(); + const oldAutoClear = renderer2.autoClear; + renderer2.autoClear = false; + this.saoMaterial.uniforms["bias"].value = this.params.saoBias; + this.saoMaterial.uniforms["intensity"].value = this.params.saoIntensity; + this.saoMaterial.uniforms["scale"].value = this.params.saoScale; + this.saoMaterial.uniforms["kernelRadius"].value = this.params.saoKernelRadius; + this.saoMaterial.uniforms["minResolution"].value = this.params.saoMinResolution; + this.saoMaterial.uniforms["cameraNear"].value = this.camera.near; + this.saoMaterial.uniforms["cameraFar"].value = this.camera.far; + const depthCutoff = this.params.saoBlurDepthCutoff * (this.camera.far - this.camera.near); + this.vBlurMaterial.uniforms["depthCutoff"].value = depthCutoff; + this.hBlurMaterial.uniforms["depthCutoff"].value = depthCutoff; + this.vBlurMaterial.uniforms["cameraNear"].value = this.camera.near; + this.vBlurMaterial.uniforms["cameraFar"].value = this.camera.far; + this.hBlurMaterial.uniforms["cameraNear"].value = this.camera.near; + this.hBlurMaterial.uniforms["cameraFar"].value = this.camera.far; + this.params.saoBlurRadius = Math.floor(this.params.saoBlurRadius); + if (this.prevStdDev !== this.params.saoBlurStdDev || this.prevNumSamples !== this.params.saoBlurRadius) { + BlurShaderUtils.configure(this.vBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2(0, 1)); + BlurShaderUtils.configure(this.hBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2(1, 0)); + this.prevStdDev = this.params.saoBlurStdDev; + this.prevNumSamples = this.params.saoBlurRadius; + } + this.renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 7829503, 1); + this.renderPass(renderer2, this.saoMaterial, this.saoRenderTarget, 16777215, 1); + if (this.params.saoBlur) { + this.renderPass(renderer2, this.vBlurMaterial, this.blurIntermediateRenderTarget, 16777215, 1); + this.renderPass(renderer2, this.hBlurMaterial, this.saoRenderTarget, 16777215, 1); + } + const outputMaterial = this.materialCopy; + if (this.params.output === SAOPass.OUTPUT.Normal) { + this.materialCopy.uniforms["tDiffuse"].value = this.normalRenderTarget.texture; + this.materialCopy.needsUpdate = true; + } else { + this.materialCopy.uniforms["tDiffuse"].value = this.saoRenderTarget.texture; + this.materialCopy.needsUpdate = true; + } + if (this.params.output === SAOPass.OUTPUT.Default) { + outputMaterial.blending = CustomBlending; + } else { + outputMaterial.blending = NoBlending; + } + this.renderPass(renderer2, outputMaterial, this.renderToScreen ? null : readBuffer); + renderer2.setClearColor(this._oldClearColor, this.oldClearAlpha); + renderer2.autoClear = oldAutoClear; + } + renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.fsQuad.material = passMaterial; + this.fsQuad.render(renderer2); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.overrideMaterial = overrideMaterial; + renderer2.render(this.scene, this.camera); + this.scene.overrideMaterial = null; + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + setSize(width2, height2) { + this.saoRenderTarget.setSize(width2, height2); + this.blurIntermediateRenderTarget.setSize(width2, height2); + this.normalRenderTarget.setSize(width2, height2); + this.saoMaterial.uniforms["size"].value.set(width2, height2); + this.saoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.saoMaterial.uniforms["cameraProjectionMatrix"].value = this.camera.projectionMatrix; + this.saoMaterial.needsUpdate = true; + this.vBlurMaterial.uniforms["size"].value.set(width2, height2); + this.vBlurMaterial.needsUpdate = true; + this.hBlurMaterial.uniforms["size"].value.set(width2, height2); + this.hBlurMaterial.needsUpdate = true; + } + dispose() { + this.saoRenderTarget.dispose(); + this.blurIntermediateRenderTarget.dispose(); + this.normalRenderTarget.dispose(); + this.normalMaterial.dispose(); + this.saoMaterial.dispose(); + this.vBlurMaterial.dispose(); + this.hBlurMaterial.dispose(); + this.materialCopy.dispose(); + this.fsQuad.dispose(); + } +} +SAOPass.OUTPUT = { + Default: 0, + SAO: 1, + Normal: 2 +}; +// node_modules/three/examples/jsm/shaders/SMAAShader.js +var SMAAEdgesShader = { + name: "SMAAEdgesShader", + defines: { + SMAA_THRESHOLD: "0.1" + }, + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2(1 / 1024, 1 / 512) } + }, + vertexShader: ` + + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 3 ]; + + void SMAAEdgeDetectionVS( vec2 texcoord ) { + vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component + vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component + vOffset[ 2 ] = texcoord.xyxy + resolution.xyxy * vec4( -2.0, 0.0, 0.0, 2.0 ); // WebGL port note: Changed sign in W component + } + + void main() { + + vUv = uv; + + SMAAEdgeDetectionVS( vUv ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + varying vec4 vOffset[ 3 ]; + + vec4 SMAAColorEdgeDetectionPS( vec2 texcoord, vec4 offset[3], sampler2D colorTex ) { + vec2 threshold = vec2( SMAA_THRESHOLD, SMAA_THRESHOLD ); + + // Calculate color deltas: + vec4 delta; + vec3 C = texture2D( colorTex, texcoord ).rgb; + + vec3 Cleft = texture2D( colorTex, offset[0].xy ).rgb; + vec3 t = abs( C - Cleft ); + delta.x = max( max( t.r, t.g ), t.b ); + + vec3 Ctop = texture2D( colorTex, offset[0].zw ).rgb; + t = abs( C - Ctop ); + delta.y = max( max( t.r, t.g ), t.b ); + + // We do the usual threshold: + vec2 edges = step( threshold, delta.xy ); + + // Then discard if there is no edge: + if ( dot( edges, vec2( 1.0, 1.0 ) ) == 0.0 ) + discard; + + // Calculate right and bottom deltas: + vec3 Cright = texture2D( colorTex, offset[1].xy ).rgb; + t = abs( C - Cright ); + delta.z = max( max( t.r, t.g ), t.b ); + + vec3 Cbottom = texture2D( colorTex, offset[1].zw ).rgb; + t = abs( C - Cbottom ); + delta.w = max( max( t.r, t.g ), t.b ); + + // Calculate the maximum delta in the direct neighborhood: + float maxDelta = max( max( max( delta.x, delta.y ), delta.z ), delta.w ); + + // Calculate left-left and top-top deltas: + vec3 Cleftleft = texture2D( colorTex, offset[2].xy ).rgb; + t = abs( C - Cleftleft ); + delta.z = max( max( t.r, t.g ), t.b ); + + vec3 Ctoptop = texture2D( colorTex, offset[2].zw ).rgb; + t = abs( C - Ctoptop ); + delta.w = max( max( t.r, t.g ), t.b ); + + // Calculate the final maximum delta: + maxDelta = max( max( maxDelta, delta.z ), delta.w ); + + // Local contrast adaptation in action: + edges.xy *= step( 0.5 * maxDelta, delta.xy ); + + return vec4( edges, 0.0, 0.0 ); + } + + void main() { + + gl_FragColor = SMAAColorEdgeDetectionPS( vUv, vOffset, tDiffuse ); + + }` +}; +var SMAAWeightsShader = { + name: "SMAAWeightsShader", + defines: { + SMAA_MAX_SEARCH_STEPS: "8", + SMAA_AREATEX_MAX_DISTANCE: "16", + SMAA_AREATEX_PIXEL_SIZE: "( 1.0 / vec2( 160.0, 560.0 ) )", + SMAA_AREATEX_SUBTEX_SIZE: "( 1.0 / 7.0 )" + }, + uniforms: { + tDiffuse: { value: null }, + tArea: { value: null }, + tSearch: { value: null }, + resolution: { value: new Vector2(1 / 1024, 1 / 512) } + }, + vertexShader: ` + + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 3 ]; + varying vec2 vPixcoord; + + void SMAABlendingWeightCalculationVS( vec2 texcoord ) { + vPixcoord = texcoord / resolution; + + // We will use these offsets for the searches later on (see @PSEUDO_GATHER4): + vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.25, 0.125, 1.25, 0.125 ); // WebGL port note: Changed sign in Y and W components + vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.125, 0.25, -0.125, -1.25 ); // WebGL port note: Changed sign in Y and W components + + // And these for the searches, they indicate the ends of the loops: + vOffset[ 2 ] = vec4( vOffset[ 0 ].xz, vOffset[ 1 ].yw ) + vec4( -2.0, 2.0, -2.0, 2.0 ) * resolution.xxyy * float( SMAA_MAX_SEARCH_STEPS ); + + } + + void main() { + + vUv = uv; + + SMAABlendingWeightCalculationVS( vUv ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + #define SMAASampleLevelZeroOffset( tex, coord, offset ) texture2D( tex, coord + float( offset ) * resolution, 0.0 ) + + uniform sampler2D tDiffuse; + uniform sampler2D tArea; + uniform sampler2D tSearch; + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[3]; + varying vec2 vPixcoord; + + #if __VERSION__ == 100 + vec2 round( vec2 x ) { + return sign( x ) * floor( abs( x ) + 0.5 ); + } + #endif + + float SMAASearchLength( sampler2D searchTex, vec2 e, float bias, float scale ) { + // Not required if searchTex accesses are set to point: + // float2 SEARCH_TEX_PIXEL_SIZE = 1.0 / float2(66.0, 33.0); + // e = float2(bias, 0.0) + 0.5 * SEARCH_TEX_PIXEL_SIZE + + // e * float2(scale, 1.0) * float2(64.0, 32.0) * SEARCH_TEX_PIXEL_SIZE; + e.r = bias + e.r * scale; + return 255.0 * texture2D( searchTex, e, 0.0 ).r; + } + + float SMAASearchXLeft( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + /** + * @PSEUDO_GATHER4 + * This texcoord has been offset by (-0.25, -0.125) in the vertex shader to + * sample between edge, thus fetching four edges in a row. + * Sampling with different offsets in each direction allows to disambiguate + * which edges are active from the four fetched ones. + */ + vec2 e = vec2( 0.0, 1.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord -= vec2( 2.0, 0.0 ) * resolution; + if ( ! ( texcoord.x > end && e.g > 0.8281 && e.r == 0.0 ) ) break; + } + + // We correct the previous (-0.25, -0.125) offset we applied: + texcoord.x += 0.25 * resolution.x; + + // The searches are bias by 1, so adjust the coords accordingly: + texcoord.x += resolution.x; + + // Disambiguate the length added by the last step: + texcoord.x += 2.0 * resolution.x; // Undo last step + texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5); + + return texcoord.x; + } + + float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + vec2 e = vec2( 0.0, 1.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord += vec2( 2.0, 0.0 ) * resolution; + if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break; + } + + texcoord.x -= 0.25 * resolution.x; + texcoord.x -= resolution.x; + texcoord.x -= 2.0 * resolution.x; + texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 ); + + return texcoord.x; + } + + float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + vec2 e = vec2( 1.0, 0.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord += vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign + if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break; + } + + texcoord.y -= 0.25 * resolution.y; // WebGL port note: Changed sign + texcoord.y -= resolution.y; // WebGL port note: Changed sign + texcoord.y -= 2.0 * resolution.y; // WebGL port note: Changed sign + texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 ); // WebGL port note: Changed sign + + return texcoord.y; + } + + float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + vec2 e = vec2( 1.0, 0.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord -= vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign + if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break; + } + + texcoord.y += 0.25 * resolution.y; // WebGL port note: Changed sign + texcoord.y += resolution.y; // WebGL port note: Changed sign + texcoord.y += 2.0 * resolution.y; // WebGL port note: Changed sign + texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 ); // WebGL port note: Changed sign + + return texcoord.y; + } + + vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) { + // Rounding prevents precision errors of bilinear filtering: + vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist; + + // We do a scale and bias for mapping to texel space: + texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE ); + + // Move to proper place, according to the subpixel offset: + texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset; + + return texture2D( areaTex, texcoord, 0.0 ).rg; + } + + vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) { + vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 ); + + vec2 e = texture2D( edgesTex, texcoord ).rg; + + if ( e.g > 0.0 ) { // Edge at north + vec2 d; + + // Find the distance to the left: + vec2 coords; + coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x ); + coords.y = offset[ 1 ].y; // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET) + d.x = coords.x; + + // Now fetch the left crossing edges, two at a time using bilinear + // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to + // discern what value each edge has: + float e1 = texture2D( edgesTex, coords, 0.0 ).r; + + // Find the distance to the right: + coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y ); + d.y = coords.x; + + // We want the distances to be in pixel units (doing this here allow to + // better interleave arithmetic and memory accesses): + d = d / resolution.x - pixcoord.x; + + // SMAAArea below needs a sqrt, as the areas texture is compressed + // quadratically: + vec2 sqrt_d = sqrt( abs( d ) ); + + // Fetch the right crossing edges: + coords.y -= 1.0 * resolution.y; // WebGL port note: Added + float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r; + + // Ok, we know how this pattern looks like, now it is time for getting + // the actual area: + weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) ); + } + + if ( e.r > 0.0 ) { // Edge at west + vec2 d; + + // Find the distance to the top: + vec2 coords; + + coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z ); + coords.x = offset[ 0 ].x; // offset[1].x = texcoord.x - 0.25 * resolution.x; + d.x = coords.y; + + // Fetch the top crossing edges: + float e1 = texture2D( edgesTex, coords, 0.0 ).g; + + // Find the distance to the bottom: + coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w ); + d.y = coords.y; + + // We want the distances to be in pixel units: + d = d / resolution.y - pixcoord.y; + + // SMAAArea below needs a sqrt, as the areas texture is compressed + // quadratically: + vec2 sqrt_d = sqrt( abs( d ) ); + + // Fetch the bottom crossing edges: + coords.y -= 1.0 * resolution.y; // WebGL port note: Added + float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g; + + // Get the area for this direction: + weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) ); + } + + return weights; + } + + void main() { + + gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) ); + + }` +}; +var SMAABlendShader = { + name: "SMAABlendShader", + uniforms: { + tDiffuse: { value: null }, + tColor: { value: null }, + resolution: { value: new Vector2(1 / 1024, 1 / 512) } + }, + vertexShader: ` + + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 2 ]; + + void SMAANeighborhoodBlendingVS( vec2 texcoord ) { + vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component + vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component + } + + void main() { + + vUv = uv; + + SMAANeighborhoodBlendingVS( vUv ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform sampler2D tColor; + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 2 ]; + + vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) { + // Fetch the blending weights for current pixel: + vec4 a; + a.xz = texture2D( blendTex, texcoord ).xz; + a.y = texture2D( blendTex, offset[ 1 ].zw ).g; + a.w = texture2D( blendTex, offset[ 1 ].xy ).a; + + // Is there any blending weight with a value greater than 0.0? + if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) { + return texture2D( colorTex, texcoord, 0.0 ); + } else { + // Up to 4 lines can be crossing a pixel (one through each edge). We + // favor blending by choosing the line with the maximum weight for each + // direction: + vec2 offset; + offset.x = a.a > a.b ? a.a : -a.b; // left vs. right + offset.y = a.g > a.r ? -a.g : a.r; // top vs. bottom // WebGL port note: Changed signs + + // Then we go in the direction that has the maximum weight: + if ( abs( offset.x ) > abs( offset.y )) { // horizontal vs. vertical + offset.y = 0.0; + } else { + offset.x = 0.0; + } + + // Fetch the opposite color and lerp by hand: + vec4 C = texture2D( colorTex, texcoord, 0.0 ); + texcoord += sign( offset ) * resolution; + vec4 Cop = texture2D( colorTex, texcoord, 0.0 ); + float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y ); + + // WebGL port note: Added gamma correction + C.xyz = pow(C.xyz, vec3(2.2)); + Cop.xyz = pow(Cop.xyz, vec3(2.2)); + vec4 mixed = mix(C, Cop, s); + mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2)); + + return mixed; + } + } + + void main() { + + gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse ); + + }` +}; +// node_modules/three/examples/jsm/shaders/SSAOShader.js +var SSAOShader = { + name: "SSAOShader", + defines: { + PERSPECTIVE_CAMERA: 1, + KERNEL_SIZE: 32 + }, + uniforms: { + tNormal: { value: null }, + tDepth: { value: null }, + tNoise: { value: null }, + kernel: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null }, + resolution: { value: new Vector2 }, + cameraProjectionMatrix: { value: new Matrix4 }, + cameraInverseProjectionMatrix: { value: new Matrix4 }, + kernelRadius: { value: 8 }, + minDistance: { value: 0.005 }, + maxDistance: { value: 0.05 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + uniform highp sampler2D tNormal; + uniform highp sampler2D tDepth; + uniform sampler2D tNoise; + + uniform vec3 kernel[ KERNEL_SIZE ]; + + uniform vec2 resolution; + + uniform float cameraNear; + uniform float cameraFar; + uniform mat4 cameraProjectionMatrix; + uniform mat4 cameraInverseProjectionMatrix; + + uniform float kernelRadius; + uniform float minDistance; // avoid artifacts caused by neighbour fragments with minimal depth difference + uniform float maxDistance; // avoid the influence of fragments which are too far away + + varying vec2 vUv; + + #include + + float getDepth( const in vec2 screenPosition ) { + + return texture2D( tDepth, screenPosition ).x; + + } + + float getLinearDepth( const in vec2 screenPosition ) { + + #if PERSPECTIVE_CAMERA == 1 + + float fragCoordZ = texture2D( tDepth, screenPosition ).x; + float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); + return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + + #else + + return texture2D( tDepth, screenPosition ).x; + + #endif + + } + + float getViewZ( const in float depth ) { + + #if PERSPECTIVE_CAMERA == 1 + + return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + + #else + + return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + + #endif + + } + + vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) { + + float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3]; + + vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 ); + + clipPosition *= clipW; // unprojection. + + return ( cameraInverseProjectionMatrix * clipPosition ).xyz; + + } + + vec3 getViewNormal( const in vec2 screenPosition ) { + + return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); + + } + + void main() { + + float depth = getDepth( vUv ); + + if ( depth == 1.0 ) { + + gl_FragColor = vec4( 1.0 ); // don't influence background + + } else { + + float viewZ = getViewZ( depth ); + + vec3 viewPosition = getViewPosition( vUv, depth, viewZ ); + vec3 viewNormal = getViewNormal( vUv ); + + vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 ); + vec3 random = vec3( texture2D( tNoise, vUv * noiseScale ).r ); + + // compute matrix used to reorient a kernel vector + + vec3 tangent = normalize( random - viewNormal * dot( random, viewNormal ) ); + vec3 bitangent = cross( viewNormal, tangent ); + mat3 kernelMatrix = mat3( tangent, bitangent, viewNormal ); + + float occlusion = 0.0; + + for ( int i = 0; i < KERNEL_SIZE; i ++ ) { + + vec3 sampleVector = kernelMatrix * kernel[ i ]; // reorient sample vector in view space + vec3 samplePoint = viewPosition + ( sampleVector * kernelRadius ); // calculate sample point + + vec4 samplePointNDC = cameraProjectionMatrix * vec4( samplePoint, 1.0 ); // project point and calculate NDC + samplePointNDC /= samplePointNDC.w; + + vec2 samplePointUv = samplePointNDC.xy * 0.5 + 0.5; // compute uv coordinates + + float realDepth = getLinearDepth( samplePointUv ); // get linear depth from depth texture + float sampleDepth = viewZToOrthographicDepth( samplePoint.z, cameraNear, cameraFar ); // compute linear depth of the sample view Z value + float delta = sampleDepth - realDepth; + + if ( delta > minDistance && delta < maxDistance ) { // if fragment is before sample point, increase occlusion + + occlusion += 1.0; + + } + + } + + occlusion = clamp( occlusion / float( KERNEL_SIZE ), 0.0, 1.0 ); + + gl_FragColor = vec4( vec3( 1.0 - occlusion ), 1.0 ); + + } + + }` +}; +var SSAODepthShader = { + name: "SSAODepthShader", + defines: { + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDepth: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null } + }, + vertexShader: `varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: `uniform sampler2D tDepth; + + uniform float cameraNear; + uniform float cameraFar; + + varying vec2 vUv; + + #include + + float getLinearDepth( const in vec2 screenPosition ) { + + #if PERSPECTIVE_CAMERA == 1 + + float fragCoordZ = texture2D( tDepth, screenPosition ).x; + float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); + return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + + #else + + return texture2D( tDepth, screenPosition ).x; + + #endif + + } + + void main() { + + float depth = getLinearDepth( vUv ); + gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); + + }` +}; +var SSAOBlurShader = { + name: "SSAOBlurShader", + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2 } + }, + vertexShader: `varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: `uniform sampler2D tDiffuse; + + uniform vec2 resolution; + + varying vec2 vUv; + + void main() { + + vec2 texelSize = ( 1.0 / resolution ); + float result = 0.0; + + for ( int i = - 2; i <= 2; i ++ ) { + + for ( int j = - 2; j <= 2; j ++ ) { + + vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize; + result += texture2D( tDiffuse, vUv + offset ).r; + + } + + } + + gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 ); + + }` +}; + +// node_modules/three/examples/jsm/postprocessing/SSAOPass.js +class SSAOPass extends Pass { + constructor(scene, camera, width2, height2, kernelSize = 32) { + super(); + this.width = width2 !== undefined ? width2 : 512; + this.height = height2 !== undefined ? height2 : 512; + this.clear = true; + this.needsSwap = false; + this.camera = camera; + this.scene = scene; + this.kernelRadius = 8; + this.kernel = []; + this.noiseTexture = null; + this.output = 0; + this.minDistance = 0.005; + this.maxDistance = 0.1; + this._visibilityCache = new Map; + this.generateSampleKernel(kernelSize); + this.generateRandomKernelRotations(); + const depthTexture = new DepthTexture; + depthTexture.format = DepthStencilFormat; + depthTexture.type = UnsignedInt248Type; + this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType, + depthTexture + }); + this.ssaoRenderTarget = new WebGLRenderTarget(this.width, this.height, { type: HalfFloatType }); + this.blurRenderTarget = this.ssaoRenderTarget.clone(); + this.ssaoMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSAOShader.defines), + uniforms: UniformsUtils.clone(SSAOShader.uniforms), + vertexShader: SSAOShader.vertexShader, + fragmentShader: SSAOShader.fragmentShader, + blending: NoBlending + }); + this.ssaoMaterial.defines["KERNEL_SIZE"] = kernelSize; + this.ssaoMaterial.uniforms["tNormal"].value = this.normalRenderTarget.texture; + this.ssaoMaterial.uniforms["tDepth"].value = this.normalRenderTarget.depthTexture; + this.ssaoMaterial.uniforms["tNoise"].value = this.noiseTexture; + this.ssaoMaterial.uniforms["kernel"].value = this.kernel; + this.ssaoMaterial.uniforms["cameraNear"].value = this.camera.near; + this.ssaoMaterial.uniforms["cameraFar"].value = this.camera.far; + this.ssaoMaterial.uniforms["resolution"].value.set(this.width, this.height); + this.ssaoMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); + this.ssaoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.normalMaterial = new MeshNormalMaterial; + this.normalMaterial.blending = NoBlending; + this.blurMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSAOBlurShader.defines), + uniforms: UniformsUtils.clone(SSAOBlurShader.uniforms), + vertexShader: SSAOBlurShader.vertexShader, + fragmentShader: SSAOBlurShader.fragmentShader + }); + this.blurMaterial.uniforms["tDiffuse"].value = this.ssaoRenderTarget.texture; + this.blurMaterial.uniforms["resolution"].value.set(this.width, this.height); + this.depthRenderMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSAODepthShader.defines), + uniforms: UniformsUtils.clone(SSAODepthShader.uniforms), + vertexShader: SSAODepthShader.vertexShader, + fragmentShader: SSAODepthShader.fragmentShader, + blending: NoBlending + }); + this.depthRenderMaterial.uniforms["tDepth"].value = this.normalRenderTarget.depthTexture; + this.depthRenderMaterial.uniforms["cameraNear"].value = this.camera.near; + this.depthRenderMaterial.uniforms["cameraFar"].value = this.camera.far; + this.copyMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(CopyShader.uniforms), + vertexShader: CopyShader.vertexShader, + fragmentShader: CopyShader.fragmentShader, + transparent: true, + depthTest: false, + depthWrite: false, + blendSrc: DstColorFactor, + blendDst: ZeroFactor, + blendEquation: AddEquation, + blendSrcAlpha: DstAlphaFactor, + blendDstAlpha: ZeroFactor, + blendEquationAlpha: AddEquation + }); + this.fsQuad = new FullScreenQuad(null); + this.originalClearColor = new Color; + } + dispose() { + this.normalRenderTarget.dispose(); + this.ssaoRenderTarget.dispose(); + this.blurRenderTarget.dispose(); + this.normalMaterial.dispose(); + this.blurMaterial.dispose(); + this.copyMaterial.dispose(); + this.depthRenderMaterial.dispose(); + this.fsQuad.dispose(); + } + render(renderer2, writeBuffer, readBuffer) { + this.overrideVisibility(); + this.renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 7829503, 1); + this.restoreVisibility(); + this.ssaoMaterial.uniforms["kernelRadius"].value = this.kernelRadius; + this.ssaoMaterial.uniforms["minDistance"].value = this.minDistance; + this.ssaoMaterial.uniforms["maxDistance"].value = this.maxDistance; + this.renderPass(renderer2, this.ssaoMaterial, this.ssaoRenderTarget); + this.renderPass(renderer2, this.blurMaterial, this.blurRenderTarget); + switch (this.output) { + case SSAOPass.OUTPUT.SSAO: + this.copyMaterial.uniforms["tDiffuse"].value = this.ssaoRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer); + break; + case SSAOPass.OUTPUT.Blur: + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer); + break; + case SSAOPass.OUTPUT.Depth: + this.renderPass(renderer2, this.depthRenderMaterial, this.renderToScreen ? null : readBuffer); + break; + case SSAOPass.OUTPUT.Normal: + this.copyMaterial.uniforms["tDiffuse"].value = this.normalRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer); + break; + case SSAOPass.OUTPUT.Default: + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget.texture; + this.copyMaterial.blending = CustomBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer); + break; + default: + console.warn("THREE.SSAOPass: Unknown output type."); + } + } + renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.fsQuad.material = passMaterial; + this.fsQuad.render(renderer2); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.overrideMaterial = overrideMaterial; + renderer2.render(this.scene, this.camera); + this.scene.overrideMaterial = null; + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + setSize(width2, height2) { + this.width = width2; + this.height = height2; + this.ssaoRenderTarget.setSize(width2, height2); + this.normalRenderTarget.setSize(width2, height2); + this.blurRenderTarget.setSize(width2, height2); + this.ssaoMaterial.uniforms["resolution"].value.set(width2, height2); + this.ssaoMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); + this.ssaoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.blurMaterial.uniforms["resolution"].value.set(width2, height2); + } + generateSampleKernel(kernelSize) { + const kernel = this.kernel; + for (let i = 0;i < kernelSize; i++) { + const sample = new Vector3; + sample.x = Math.random() * 2 - 1; + sample.y = Math.random() * 2 - 1; + sample.z = Math.random(); + sample.normalize(); + let scale2 = i / kernelSize; + scale2 = MathUtils.lerp(0.1, 1, scale2 * scale2); + sample.multiplyScalar(scale2); + kernel.push(sample); + } + } + generateRandomKernelRotations() { + const width2 = 4, height2 = 4; + const simplex = new SimplexNoise; + const size2 = width2 * height2; + const data2 = new Float32Array(size2); + for (let i = 0;i < size2; i++) { + const x2 = Math.random() * 2 - 1; + const y = Math.random() * 2 - 1; + const z = 0; + data2[i] = simplex.noise3d(x2, y, z); + } + this.noiseTexture = new DataTexture(data2, width2, height2, RedFormat, FloatType); + this.noiseTexture.wrapS = RepeatWrapping; + this.noiseTexture.wrapT = RepeatWrapping; + this.noiseTexture.needsUpdate = true; + } + overrideVisibility() { + const scene = this.scene; + const cache = this._visibilityCache; + scene.traverse(function(object) { + cache.set(object, object.visible); + if (object.isPoints || object.isLine) + object.visible = false; + }); + } + restoreVisibility() { + const scene = this.scene; + const cache = this._visibilityCache; + scene.traverse(function(object) { + const visible = cache.get(object); + object.visible = visible; + }); + cache.clear(); + } +} +SSAOPass.OUTPUT = { + Default: 0, + SSAO: 1, + Blur: 2, + Depth: 3, + Normal: 4 +}; +// node_modules/three/examples/jsm/shaders/SSRShader.js +var SSRShader = { + name: "SSRShader", + defines: { + MAX_STEP: 0, + PERSPECTIVE_CAMERA: true, + DISTANCE_ATTENUATION: true, + FRESNEL: true, + INFINITE_THICK: false, + SELECTIVE: false + }, + uniforms: { + tDiffuse: { value: null }, + tNormal: { value: null }, + tMetalness: { value: null }, + tDepth: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null }, + resolution: { value: new Vector2 }, + cameraProjectionMatrix: { value: new Matrix4 }, + cameraInverseProjectionMatrix: { value: new Matrix4 }, + opacity: { value: 0.5 }, + maxDistance: { value: 180 }, + cameraRange: { value: 0 }, + thickness: { value: 0.018 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + } + + `, + fragmentShader: ` + // precision highp float; + precision highp sampler2D; + varying vec2 vUv; + uniform sampler2D tDepth; + uniform sampler2D tNormal; + uniform sampler2D tMetalness; + uniform sampler2D tDiffuse; + uniform float cameraRange; + uniform vec2 resolution; + uniform float opacity; + uniform float cameraNear; + uniform float cameraFar; + uniform float maxDistance; + uniform float thickness; + uniform mat4 cameraProjectionMatrix; + uniform mat4 cameraInverseProjectionMatrix; + #include + float pointToLineDistance(vec3 x0, vec3 x1, vec3 x2) { + //x0: point, x1: linePointA, x2: linePointB + //https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html + return length(cross(x0-x1,x0-x2))/length(x2-x1); + } + float pointPlaneDistance(vec3 point,vec3 planePoint,vec3 planeNormal){ + // https://mathworld.wolfram.com/Point-PlaneDistance.html + //// https://en.wikipedia.org/wiki/Plane_(geometry) + //// http://paulbourke.net/geometry/pointlineplane/ + float a=planeNormal.x,b=planeNormal.y,c=planeNormal.z; + float x0=point.x,y0=point.y,z0=point.z; + float x=planePoint.x,y=planePoint.y,z=planePoint.z; + float d=-(a*x+b*y+c*z); + float distance=(a*x0+b*y0+c*z0+d)/sqrt(a*a+b*b+c*c); + return distance; + } + float getDepth( const in vec2 uv ) { + return texture2D( tDepth, uv ).x; + } + float getViewZ( const in float depth ) { + #ifdef PERSPECTIVE_CAMERA + return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + #else + return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + #endif + } + vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { + vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc + clipPosition *= clipW; //clip + return ( cameraInverseProjectionMatrix * clipPosition ).xyz;//view + } + vec3 getViewNormal( const in vec2 uv ) { + return unpackRGBToNormal( texture2D( tNormal, uv ).xyz ); + } + vec2 viewPositionToXY(vec3 viewPosition){ + vec2 xy; + vec4 clip=cameraProjectionMatrix*vec4(viewPosition,1); + xy=clip.xy;//clip + float clipW=clip.w; + xy/=clipW;//NDC + xy=(xy+1.)/2.;//uv + xy*=resolution;//screen + return xy; + } + void main(){ + #ifdef SELECTIVE + float metalness=texture2D(tMetalness,vUv).r; + if(metalness==0.) return; + #endif + + float depth = getDepth( vUv ); + float viewZ = getViewZ( depth ); + if(-viewZ>=cameraFar) return; + + float clipW = cameraProjectionMatrix[2][3] * viewZ+cameraProjectionMatrix[3][3]; + vec3 viewPosition=getViewPosition( vUv, depth, clipW ); + + vec2 d0=gl_FragCoord.xy; + vec2 d1; + + vec3 viewNormal=getViewNormal( vUv ); + + #ifdef PERSPECTIVE_CAMERA + vec3 viewIncidentDir=normalize(viewPosition); + vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal); + #else + vec3 viewIncidentDir=vec3(0,0,-1); + vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal); + #endif + + float maxReflectRayLen=maxDistance/dot(-viewIncidentDir,viewNormal); + // dot(a,b)==length(a)*length(b)*cos(theta) // https://www.mathsisfun.com/algebra/vectors-dot-product.html + // if(a.isNormalized&&b.isNormalized) dot(a,b)==cos(theta) + // maxDistance/maxReflectRayLen=cos(theta) + // maxDistance/maxReflectRayLen==dot(a,b) + // maxReflectRayLen==maxDistance/dot(a,b) + + vec3 d1viewPosition=viewPosition+viewReflectDir*maxReflectRayLen; + #ifdef PERSPECTIVE_CAMERA + if(d1viewPosition.z>-cameraNear){ + //https://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx + float t=(-cameraNear-viewPosition.z)/viewReflectDir.z; + d1viewPosition=viewPosition+viewReflectDir*t; + } + #endif + d1=viewPositionToXY(d1viewPosition); + + float totalLen=length(d1-d0); + float xLen=d1.x-d0.x; + float yLen=d1.y-d0.y; + float totalStep=max(abs(xLen),abs(yLen)); + float xSpan=xLen/totalStep; + float ySpan=yLen/totalStep; + for(float i=0.;i=totalStep) break; + vec2 xy=vec2(d0.x+i*xSpan,d0.y+i*ySpan); + if(xy.x<0.||xy.x>resolution.x||xy.y<0.||xy.y>resolution.y) break; + float s=length(xy-d0)/totalLen; + vec2 uv=xy/resolution; + + float d = getDepth(uv); + float vZ = getViewZ( d ); + if(-vZ>=cameraFar) continue; + float cW = cameraProjectionMatrix[2][3] * vZ+cameraProjectionMatrix[3][3]; + vec3 vP=getViewPosition( uv, d, cW ); + + #ifdef PERSPECTIVE_CAMERA + // https://comp.nus.edu.sg/~lowkl/publications/lowk_persp_interp_techrep.pdf + float recipVPZ=1./viewPosition.z; + float viewReflectRayZ=1./(recipVPZ+s*(1./d1viewPosition.z-recipVPZ)); + #else + float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z); + #endif + + // if(viewReflectRayZ>vZ) continue; // will cause "npm run make-screenshot webgl_postprocessing_ssr" high probability hang. + // https://github.com/mrdoob/three.js/pull/21539#issuecomment-821061164 + if(viewReflectRayZ<=vZ){ + + bool hit; + #ifdef INFINITE_THICK + hit=true; + #else + float away=pointToLineDistance(vP,viewPosition,d1viewPosition); + + float minThickness; + vec2 xyNeighbor=xy; + xyNeighbor.x+=1.; + vec2 uvNeighbor=xyNeighbor/resolution; + vec3 vPNeighbor=getViewPosition(uvNeighbor,d,cW); + minThickness=vPNeighbor.x-vP.x; + minThickness*=3.; + float tk=max(minThickness,thickness); + + hit=away<=tk; + #endif + + if(hit){ + vec3 vN=getViewNormal( uv ); + if(dot(viewReflectDir,vN)>=0.) continue; + float distance=pointPlaneDistance(vP,viewPosition,viewNormal); + if(distance>maxDistance) break; + float op=opacity; + #ifdef DISTANCE_ATTENUATION + float ratio=1.-(distance/maxDistance); + float attenuation=ratio*ratio; + op=opacity*attenuation; + #endif + #ifdef FRESNEL + float fresnelCoe=(dot(viewIncidentDir,viewReflectDir)+1.)/2.; + op*=fresnelCoe; + #endif + vec4 reflectColor=texture2D(tDiffuse,uv); + gl_FragColor.xyz=reflectColor.xyz; + gl_FragColor.a=op; + break; + } + } + } + } + ` +}; +var SSRDepthShader = { + name: "SSRDepthShader", + defines: { + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDepth: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + } + + `, + fragmentShader: ` + + uniform sampler2D tDepth; + + uniform float cameraNear; + uniform float cameraFar; + + varying vec2 vUv; + + #include + + float getLinearDepth( const in vec2 uv ) { + + #if PERSPECTIVE_CAMERA == 1 + + float fragCoordZ = texture2D( tDepth, uv ).x; + float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); + return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + + #else + + return texture2D( tDepth, uv ).x; + + #endif + + } + + void main() { + + float depth = getLinearDepth( vUv ); + float d = 1.0 - depth; + // d=(d-.999)*1000.; + gl_FragColor = vec4( vec3( d ), 1.0 ); + + } + + ` +}; +var SSRBlurShader = { + name: "SSRBlurShader", + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2 }, + opacity: { value: 0.5 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + } + + `, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform vec2 resolution; + varying vec2 vUv; + void main() { + //reverse engineering from PhotoShop blur filter, then change coefficient + + vec2 texelSize = ( 1.0 / resolution ); + + vec4 c=texture2D(tDiffuse,vUv); + + vec2 offset; + + offset=(vec2(-1,0))*texelSize; + vec4 cl=texture2D(tDiffuse,vUv+offset); + + offset=(vec2(1,0))*texelSize; + vec4 cr=texture2D(tDiffuse,vUv+offset); + + offset=(vec2(0,-1))*texelSize; + vec4 cb=texture2D(tDiffuse,vUv+offset); + + offset=(vec2(0,1))*texelSize; + vec4 ct=texture2D(tDiffuse,vUv+offset); + + // float coeCenter=.5; + // float coeSide=.125; + float coeCenter=.2; + float coeSide=.2; + float a=c.a*coeCenter+cl.a*coeSide+cr.a*coeSide+cb.a*coeSide+ct.a*coeSide; + vec3 rgb=(c.rgb*c.a*coeCenter+cl.rgb*cl.a*coeSide+cr.rgb*cr.a*coeSide+cb.rgb*cb.a*coeSide+ct.rgb*ct.a*coeSide)/a; + gl_FragColor=vec4(rgb,a); + + } + ` +}; + +// node_modules/three/examples/jsm/postprocessing/SSRPass.js +class SSRPass extends Pass { + constructor({ renderer: renderer2, scene, camera, width: width2, height: height2, selects, bouncing = false, groundReflector }) { + super(); + this.width = width2 !== undefined ? width2 : 512; + this.height = height2 !== undefined ? height2 : 512; + this.clear = true; + this.renderer = renderer2; + this.scene = scene; + this.camera = camera; + this.groundReflector = groundReflector; + this.opacity = SSRShader.uniforms.opacity.value; + this.output = 0; + this.maxDistance = SSRShader.uniforms.maxDistance.value; + this.thickness = SSRShader.uniforms.thickness.value; + this.tempColor = new Color; + this._selects = selects; + this.selective = Array.isArray(this._selects); + Object.defineProperty(this, "selects", { + get() { + return this._selects; + }, + set(val2) { + if (this._selects === val2) + return; + this._selects = val2; + if (Array.isArray(val2)) { + this.selective = true; + this.ssrMaterial.defines.SELECTIVE = true; + this.ssrMaterial.needsUpdate = true; + } else { + this.selective = false; + this.ssrMaterial.defines.SELECTIVE = false; + this.ssrMaterial.needsUpdate = true; + } + } + }); + this._bouncing = bouncing; + Object.defineProperty(this, "bouncing", { + get() { + return this._bouncing; + }, + set(val2) { + if (this._bouncing === val2) + return; + this._bouncing = val2; + if (val2) { + this.ssrMaterial.uniforms["tDiffuse"].value = this.prevRenderTarget.texture; + } else { + this.ssrMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + } + } + }); + this.blur = true; + this._distanceAttenuation = SSRShader.defines.DISTANCE_ATTENUATION; + Object.defineProperty(this, "distanceAttenuation", { + get() { + return this._distanceAttenuation; + }, + set(val2) { + if (this._distanceAttenuation === val2) + return; + this._distanceAttenuation = val2; + this.ssrMaterial.defines.DISTANCE_ATTENUATION = val2; + this.ssrMaterial.needsUpdate = true; + } + }); + this._fresnel = SSRShader.defines.FRESNEL; + Object.defineProperty(this, "fresnel", { + get() { + return this._fresnel; + }, + set(val2) { + if (this._fresnel === val2) + return; + this._fresnel = val2; + this.ssrMaterial.defines.FRESNEL = val2; + this.ssrMaterial.needsUpdate = true; + } + }); + this._infiniteThick = SSRShader.defines.INFINITE_THICK; + Object.defineProperty(this, "infiniteThick", { + get() { + return this._infiniteThick; + }, + set(val2) { + if (this._infiniteThick === val2) + return; + this._infiniteThick = val2; + this.ssrMaterial.defines.INFINITE_THICK = val2; + this.ssrMaterial.needsUpdate = true; + } + }); + const depthTexture = new DepthTexture; + depthTexture.type = UnsignedShortType; + depthTexture.minFilter = NearestFilter; + depthTexture.magFilter = NearestFilter; + this.beautyRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType, + depthTexture, + depthBuffer: true + }); + this.prevRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter + }); + this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType + }); + this.metalnessRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType + }); + this.ssrRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter + }); + this.blurRenderTarget = this.ssrRenderTarget.clone(); + this.blurRenderTarget2 = this.ssrRenderTarget.clone(); + this.ssrMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSRShader.defines, { + MAX_STEP: Math.sqrt(this.width * this.width + this.height * this.height) + }), + uniforms: UniformsUtils.clone(SSRShader.uniforms), + vertexShader: SSRShader.vertexShader, + fragmentShader: SSRShader.fragmentShader, + blending: NoBlending + }); + this.ssrMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.ssrMaterial.uniforms["tNormal"].value = this.normalRenderTarget.texture; + this.ssrMaterial.defines.SELECTIVE = this.selective; + this.ssrMaterial.needsUpdate = true; + this.ssrMaterial.uniforms["tMetalness"].value = this.metalnessRenderTarget.texture; + this.ssrMaterial.uniforms["tDepth"].value = this.beautyRenderTarget.depthTexture; + this.ssrMaterial.uniforms["cameraNear"].value = this.camera.near; + this.ssrMaterial.uniforms["cameraFar"].value = this.camera.far; + this.ssrMaterial.uniforms["thickness"].value = this.thickness; + this.ssrMaterial.uniforms["resolution"].value.set(this.width, this.height); + this.ssrMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); + this.ssrMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.normalMaterial = new MeshNormalMaterial; + this.normalMaterial.blending = NoBlending; + this.metalnessOnMaterial = new MeshBasicMaterial({ + color: "white" + }); + this.metalnessOffMaterial = new MeshBasicMaterial({ + color: "black" + }); + this.blurMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSRBlurShader.defines), + uniforms: UniformsUtils.clone(SSRBlurShader.uniforms), + vertexShader: SSRBlurShader.vertexShader, + fragmentShader: SSRBlurShader.fragmentShader + }); + this.blurMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.blurMaterial.uniforms["resolution"].value.set(this.width, this.height); + this.blurMaterial2 = new ShaderMaterial({ + defines: Object.assign({}, SSRBlurShader.defines), + uniforms: UniformsUtils.clone(SSRBlurShader.uniforms), + vertexShader: SSRBlurShader.vertexShader, + fragmentShader: SSRBlurShader.fragmentShader + }); + this.blurMaterial2.uniforms["tDiffuse"].value = this.blurRenderTarget.texture; + this.blurMaterial2.uniforms["resolution"].value.set(this.width, this.height); + this.depthRenderMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSRDepthShader.defines), + uniforms: UniformsUtils.clone(SSRDepthShader.uniforms), + vertexShader: SSRDepthShader.vertexShader, + fragmentShader: SSRDepthShader.fragmentShader, + blending: NoBlending + }); + this.depthRenderMaterial.uniforms["tDepth"].value = this.beautyRenderTarget.depthTexture; + this.depthRenderMaterial.uniforms["cameraNear"].value = this.camera.near; + this.depthRenderMaterial.uniforms["cameraFar"].value = this.camera.far; + this.copyMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(CopyShader.uniforms), + vertexShader: CopyShader.vertexShader, + fragmentShader: CopyShader.fragmentShader, + transparent: true, + depthTest: false, + depthWrite: false, + blendSrc: SrcAlphaFactor, + blendDst: OneMinusSrcAlphaFactor, + blendEquation: AddEquation, + blendSrcAlpha: SrcAlphaFactor, + blendDstAlpha: OneMinusSrcAlphaFactor, + blendEquationAlpha: AddEquation + }); + this.fsQuad = new FullScreenQuad(null); + this.originalClearColor = new Color; + } + dispose() { + this.beautyRenderTarget.dispose(); + this.prevRenderTarget.dispose(); + this.normalRenderTarget.dispose(); + this.metalnessRenderTarget.dispose(); + this.ssrRenderTarget.dispose(); + this.blurRenderTarget.dispose(); + this.blurRenderTarget2.dispose(); + this.normalMaterial.dispose(); + this.metalnessOnMaterial.dispose(); + this.metalnessOffMaterial.dispose(); + this.blurMaterial.dispose(); + this.blurMaterial2.dispose(); + this.copyMaterial.dispose(); + this.depthRenderMaterial.dispose(); + this.fsQuad.dispose(); + } + render(renderer2, writeBuffer) { + renderer2.setRenderTarget(this.beautyRenderTarget); + renderer2.clear(); + if (this.groundReflector) { + this.groundReflector.visible = false; + this.groundReflector.doRender(this.renderer, this.scene, this.camera); + this.groundReflector.visible = true; + } + renderer2.render(this.scene, this.camera); + if (this.groundReflector) + this.groundReflector.visible = false; + this.renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 0, 0); + if (this.selective) { + this.renderMetalness(renderer2, this.metalnessOnMaterial, this.metalnessRenderTarget, 0, 0); + } + this.ssrMaterial.uniforms["opacity"].value = this.opacity; + this.ssrMaterial.uniforms["maxDistance"].value = this.maxDistance; + this.ssrMaterial.uniforms["thickness"].value = this.thickness; + this.renderPass(renderer2, this.ssrMaterial, this.ssrRenderTarget); + if (this.blur) { + this.renderPass(renderer2, this.blurMaterial, this.blurRenderTarget); + this.renderPass(renderer2, this.blurMaterial2, this.blurRenderTarget2); + } + switch (this.output) { + case SSRPass.OUTPUT.Default: + if (this.bouncing) { + this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.prevRenderTarget); + if (this.blur) + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture; + else + this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.copyMaterial.blending = NormalBlending; + this.renderPass(renderer2, this.copyMaterial, this.prevRenderTarget); + this.copyMaterial.uniforms["tDiffuse"].value = this.prevRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + } else { + this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + if (this.blur) + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture; + else + this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.copyMaterial.blending = NormalBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + } + break; + case SSRPass.OUTPUT.SSR: + if (this.blur) + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture; + else + this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + if (this.bouncing) { + if (this.blur) + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture; + else + this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.prevRenderTarget); + this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.copyMaterial.blending = NormalBlending; + this.renderPass(renderer2, this.copyMaterial, this.prevRenderTarget); + } + break; + case SSRPass.OUTPUT.Beauty: + this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case SSRPass.OUTPUT.Depth: + this.renderPass(renderer2, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer); + break; + case SSRPass.OUTPUT.Normal: + this.copyMaterial.uniforms["tDiffuse"].value = this.normalRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case SSRPass.OUTPUT.Metalness: + this.copyMaterial.uniforms["tDiffuse"].value = this.metalnessRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + default: + console.warn("THREE.SSRPass: Unknown output type."); + } + } + renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) { + this.originalClearColor.copy(renderer2.getClearColor(this.tempColor)); + const originalClearAlpha = renderer2.getClearAlpha(this.tempColor); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.fsQuad.material = passMaterial; + this.fsQuad.render(renderer2); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + this.originalClearColor.copy(renderer2.getClearColor(this.tempColor)); + const originalClearAlpha = renderer2.getClearAlpha(this.tempColor); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.overrideMaterial = overrideMaterial; + renderer2.render(this.scene, this.camera); + this.scene.overrideMaterial = null; + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderMetalness(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + this.originalClearColor.copy(renderer2.getClearColor(this.tempColor)); + const originalClearAlpha = renderer2.getClearAlpha(this.tempColor); + const originalAutoClear = renderer2.autoClear; + const originalBackground = this.scene.background; + const originalFog = this.scene.fog; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + this.scene.background = null; + this.scene.fog = null; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.traverseVisible((child) => { + child._SSRPassBackupMaterial = child.material; + if (this._selects.includes(child)) { + child.material = this.metalnessOnMaterial; + } else { + child.material = this.metalnessOffMaterial; + } + }); + renderer2.render(this.scene, this.camera); + this.scene.traverseVisible((child) => { + child.material = child._SSRPassBackupMaterial; + }); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + this.scene.background = originalBackground; + this.scene.fog = originalFog; + } + setSize(width2, height2) { + this.width = width2; + this.height = height2; + this.ssrMaterial.defines.MAX_STEP = Math.sqrt(width2 * width2 + height2 * height2); + this.ssrMaterial.needsUpdate = true; + this.beautyRenderTarget.setSize(width2, height2); + this.prevRenderTarget.setSize(width2, height2); + this.ssrRenderTarget.setSize(width2, height2); + this.normalRenderTarget.setSize(width2, height2); + this.metalnessRenderTarget.setSize(width2, height2); + this.blurRenderTarget.setSize(width2, height2); + this.blurRenderTarget2.setSize(width2, height2); + this.ssrMaterial.uniforms["resolution"].value.set(width2, height2); + this.ssrMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); + this.ssrMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.blurMaterial.uniforms["resolution"].value.set(width2, height2); + this.blurMaterial2.uniforms["resolution"].value.set(width2, height2); + } +} +SSRPass.OUTPUT = { + Default: 0, + SSR: 1, + Beauty: 3, + Depth: 4, + Normal: 5, + Metalness: 7 +}; +// node_modules/three/examples/jsm/shaders/LuminosityHighPassShader.js +var LuminosityHighPassShader = { + name: "LuminosityHighPassShader", + shaderID: "luminosityHighPass", + uniforms: { + tDiffuse: { value: null }, + luminosityThreshold: { value: 1 }, + smoothWidth: { value: 1 }, + defaultColor: { value: new Color(0) }, + defaultOpacity: { value: 0 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform vec3 defaultColor; + uniform float defaultOpacity; + uniform float luminosityThreshold; + uniform float smoothWidth; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + + float v = luminance( texel.xyz ); + + vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity ); + + float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v ); + + gl_FragColor = mix( outputColor, texel, alpha ); + + }` +}; + +// node_modules/three/examples/jsm/postprocessing/UnrealBloomPass.js +class UnrealBloomPass extends Pass { + constructor(resolution, strength, radius, threshold) { + super(); + this.strength = strength !== undefined ? strength : 1; + this.radius = radius; + this.threshold = threshold; + this.resolution = resolution !== undefined ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256); + this.clearColor = new Color(0, 0, 0); + this.renderTargetsHorizontal = []; + this.renderTargetsVertical = []; + this.nMips = 5; + let resx = Math.round(this.resolution.x / 2); + let resy = Math.round(this.resolution.y / 2); + this.renderTargetBright = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + this.renderTargetBright.texture.name = "UnrealBloomPass.bright"; + this.renderTargetBright.texture.generateMipmaps = false; + for (let i = 0;i < this.nMips; i++) { + const renderTargetHorizontal = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + renderTargetHorizontal.texture.name = "UnrealBloomPass.h" + i; + renderTargetHorizontal.texture.generateMipmaps = false; + this.renderTargetsHorizontal.push(renderTargetHorizontal); + const renderTargetVertical = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + renderTargetVertical.texture.name = "UnrealBloomPass.v" + i; + renderTargetVertical.texture.generateMipmaps = false; + this.renderTargetsVertical.push(renderTargetVertical); + resx = Math.round(resx / 2); + resy = Math.round(resy / 2); + } + const highPassShader = LuminosityHighPassShader; + this.highPassUniforms = UniformsUtils.clone(highPassShader.uniforms); + this.highPassUniforms["luminosityThreshold"].value = threshold; + this.highPassUniforms["smoothWidth"].value = 0.01; + this.materialHighPassFilter = new ShaderMaterial({ + uniforms: this.highPassUniforms, + vertexShader: highPassShader.vertexShader, + fragmentShader: highPassShader.fragmentShader + }); + this.separableBlurMaterials = []; + const kernelSizeArray = [3, 5, 7, 9, 11]; + resx = Math.round(this.resolution.x / 2); + resy = Math.round(this.resolution.y / 2); + for (let i = 0;i < this.nMips; i++) { + this.separableBlurMaterials.push(this.getSeparableBlurMaterial(kernelSizeArray[i])); + this.separableBlurMaterials[i].uniforms["invSize"].value = new Vector2(1 / resx, 1 / resy); + resx = Math.round(resx / 2); + resy = Math.round(resy / 2); + } + this.compositeMaterial = this.getCompositeMaterial(this.nMips); + this.compositeMaterial.uniforms["blurTexture1"].value = this.renderTargetsVertical[0].texture; + this.compositeMaterial.uniforms["blurTexture2"].value = this.renderTargetsVertical[1].texture; + this.compositeMaterial.uniforms["blurTexture3"].value = this.renderTargetsVertical[2].texture; + this.compositeMaterial.uniforms["blurTexture4"].value = this.renderTargetsVertical[3].texture; + this.compositeMaterial.uniforms["blurTexture5"].value = this.renderTargetsVertical[4].texture; + this.compositeMaterial.uniforms["bloomStrength"].value = strength; + this.compositeMaterial.uniforms["bloomRadius"].value = 0.1; + const bloomFactors = [1, 0.8, 0.6, 0.4, 0.2]; + this.compositeMaterial.uniforms["bloomFactors"].value = bloomFactors; + this.bloomTintColors = [new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1)]; + this.compositeMaterial.uniforms["bloomTintColors"].value = this.bloomTintColors; + const copyShader = CopyShader; + this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); + this.blendMaterial = new ShaderMaterial({ + uniforms: this.copyUniforms, + vertexShader: copyShader.vertexShader, + fragmentShader: copyShader.fragmentShader, + blending: AdditiveBlending, + depthTest: false, + depthWrite: false, + transparent: true + }); + this.enabled = true; + this.needsSwap = false; + this._oldClearColor = new Color; + this.oldClearAlpha = 1; + this.basic = new MeshBasicMaterial; + this.fsQuad = new FullScreenQuad(null); + } + dispose() { + for (let i = 0;i < this.renderTargetsHorizontal.length; i++) { + this.renderTargetsHorizontal[i].dispose(); + } + for (let i = 0;i < this.renderTargetsVertical.length; i++) { + this.renderTargetsVertical[i].dispose(); + } + this.renderTargetBright.dispose(); + for (let i = 0;i < this.separableBlurMaterials.length; i++) { + this.separableBlurMaterials[i].dispose(); + } + this.compositeMaterial.dispose(); + this.blendMaterial.dispose(); + this.basic.dispose(); + this.fsQuad.dispose(); + } + setSize(width2, height2) { + let resx = Math.round(width2 / 2); + let resy = Math.round(height2 / 2); + this.renderTargetBright.setSize(resx, resy); + for (let i = 0;i < this.nMips; i++) { + this.renderTargetsHorizontal[i].setSize(resx, resy); + this.renderTargetsVertical[i].setSize(resx, resy); + this.separableBlurMaterials[i].uniforms["invSize"].value = new Vector2(1 / resx, 1 / resy); + resx = Math.round(resx / 2); + resy = Math.round(resy / 2); + } + } + render(renderer2, writeBuffer, readBuffer, deltaTime, maskActive) { + renderer2.getClearColor(this._oldClearColor); + this.oldClearAlpha = renderer2.getClearAlpha(); + const oldAutoClear = renderer2.autoClear; + renderer2.autoClear = false; + renderer2.setClearColor(this.clearColor, 0); + if (maskActive) + renderer2.state.buffers.stencil.setTest(false); + if (this.renderToScreen) { + this.fsQuad.material = this.basic; + this.basic.map = readBuffer.texture; + renderer2.setRenderTarget(null); + renderer2.clear(); + this.fsQuad.render(renderer2); + } + this.highPassUniforms["tDiffuse"].value = readBuffer.texture; + this.highPassUniforms["luminosityThreshold"].value = this.threshold; + this.fsQuad.material = this.materialHighPassFilter; + renderer2.setRenderTarget(this.renderTargetBright); + renderer2.clear(); + this.fsQuad.render(renderer2); + let inputRenderTarget = this.renderTargetBright; + for (let i = 0;i < this.nMips; i++) { + this.fsQuad.material = this.separableBlurMaterials[i]; + this.separableBlurMaterials[i].uniforms["colorTexture"].value = inputRenderTarget.texture; + this.separableBlurMaterials[i].uniforms["direction"].value = UnrealBloomPass.BlurDirectionX; + renderer2.setRenderTarget(this.renderTargetsHorizontal[i]); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.separableBlurMaterials[i].uniforms["colorTexture"].value = this.renderTargetsHorizontal[i].texture; + this.separableBlurMaterials[i].uniforms["direction"].value = UnrealBloomPass.BlurDirectionY; + renderer2.setRenderTarget(this.renderTargetsVertical[i]); + renderer2.clear(); + this.fsQuad.render(renderer2); + inputRenderTarget = this.renderTargetsVertical[i]; + } + this.fsQuad.material = this.compositeMaterial; + this.compositeMaterial.uniforms["bloomStrength"].value = this.strength; + this.compositeMaterial.uniforms["bloomRadius"].value = this.radius; + this.compositeMaterial.uniforms["bloomTintColors"].value = this.bloomTintColors; + renderer2.setRenderTarget(this.renderTargetsHorizontal[0]); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.blendMaterial; + this.copyUniforms["tDiffuse"].value = this.renderTargetsHorizontal[0].texture; + if (maskActive) + renderer2.state.buffers.stencil.setTest(true); + if (this.renderToScreen) { + renderer2.setRenderTarget(null); + this.fsQuad.render(renderer2); + } else { + renderer2.setRenderTarget(readBuffer); + this.fsQuad.render(renderer2); + } + renderer2.setClearColor(this._oldClearColor, this.oldClearAlpha); + renderer2.autoClear = oldAutoClear; + } + getSeparableBlurMaterial(kernelRadius) { + const coefficients = []; + for (let i = 0;i < kernelRadius; i++) { + coefficients.push(0.39894 * Math.exp(-0.5 * i * i / (kernelRadius * kernelRadius)) / kernelRadius); + } + return new ShaderMaterial({ + defines: { + KERNEL_RADIUS: kernelRadius + }, + uniforms: { + colorTexture: { value: null }, + invSize: { value: new Vector2(0.5, 0.5) }, + direction: { value: new Vector2(0.5, 0.5) }, + gaussianCoefficients: { value: coefficients } + }, + vertexShader: `varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `#include + varying vec2 vUv; + uniform sampler2D colorTexture; + uniform vec2 invSize; + uniform vec2 direction; + uniform float gaussianCoefficients[KERNEL_RADIUS]; + + void main() { + float weightSum = gaussianCoefficients[0]; + vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum; + for( int i = 1; i < KERNEL_RADIUS; i ++ ) { + float x = float(i); + float w = gaussianCoefficients[i]; + vec2 uvOffset = direction * invSize * x; + vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb; + vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb; + diffuseSum += (sample1 + sample2) * w; + weightSum += 2.0 * w; + } + gl_FragColor = vec4(diffuseSum/weightSum, 1.0); + }` + }); + } + getCompositeMaterial(nMips) { + return new ShaderMaterial({ + defines: { + NUM_MIPS: nMips + }, + uniforms: { + blurTexture1: { value: null }, + blurTexture2: { value: null }, + blurTexture3: { value: null }, + blurTexture4: { value: null }, + blurTexture5: { value: null }, + bloomStrength: { value: 1 }, + bloomFactors: { value: null }, + bloomTintColors: { value: null }, + bloomRadius: { value: 0 } + }, + vertexShader: `varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `varying vec2 vUv; + uniform sampler2D blurTexture1; + uniform sampler2D blurTexture2; + uniform sampler2D blurTexture3; + uniform sampler2D blurTexture4; + uniform sampler2D blurTexture5; + uniform float bloomStrength; + uniform float bloomRadius; + uniform float bloomFactors[NUM_MIPS]; + uniform vec3 bloomTintColors[NUM_MIPS]; + + float lerpBloomFactor(const in float factor) { + float mirrorFactor = 1.2 - factor; + return mix(factor, mirrorFactor, bloomRadius); + } + + void main() { + gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + + lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + + lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + + lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + + lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) ); + }` + }); + } +} +UnrealBloomPass.BlurDirectionX = new Vector2(1, 0); +UnrealBloomPass.BlurDirectionY = new Vector2(0, 1); +// node_modules/three/examples/jsm/renderers/CSS2DRenderer.js +var _vector8 = new Vector3; +var _viewMatrix = new Matrix4; +var _viewProjectionMatrix = new Matrix4; +var _a2 = new Vector3; +var _b2 = new Vector3; +// node_modules/three/examples/jsm/renderers/CSS3DRenderer.js +var _position2 = new Vector3; +var _quaternion4 = new Quaternion; +var _scale4 = new Vector3; +var _matrix5 = new Matrix4; +var _matrix22 = new Matrix4; +// node_modules/three/examples/jsm/shaders/BokehShader2.js +var BokehShader2 = { + name: "BokehShader", + uniforms: { + textureWidth: { value: 1 }, + textureHeight: { value: 1 }, + focalDepth: { value: 1 }, + focalLength: { value: 24 }, + fstop: { value: 0.9 }, + tColor: { value: null }, + tDepth: { value: null }, + maxblur: { value: 1 }, + showFocus: { value: 0 }, + manualdof: { value: 0 }, + vignetting: { value: 0 }, + depthblur: { value: 0 }, + threshold: { value: 0.5 }, + gain: { value: 2 }, + bias: { value: 0.5 }, + fringe: { value: 0.7 }, + znear: { value: 0.1 }, + zfar: { value: 100 }, + noise: { value: 1 }, + dithering: { value: 0.0001 }, + pentagon: { value: 0 }, + shaderFocus: { value: 1 }, + focusCoords: { value: new Vector2 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + #include + + varying vec2 vUv; + + uniform sampler2D tColor; + uniform sampler2D tDepth; + uniform float textureWidth; + uniform float textureHeight; + + uniform float focalDepth; //focal distance value in meters, but you may use autofocus option below + uniform float focalLength; //focal length in mm + uniform float fstop; //f-stop value + uniform bool showFocus; //show debug focus point and focal range (red = focal point, green = focal range) + + /* + make sure that these two values are the same for your camera, otherwise distances will be wrong. + */ + + uniform float znear; // camera clipping start + uniform float zfar; // camera clipping end + + //------------------------------------------ + //user variables + + const int samples = SAMPLES; //samples on the first ring + const int rings = RINGS; //ring count + + const int maxringsamples = rings * samples; + + uniform bool manualdof; // manual dof calculation + float ndofstart = 1.0; // near dof blur start + float ndofdist = 2.0; // near dof blur falloff distance + float fdofstart = 1.0; // far dof blur start + float fdofdist = 3.0; // far dof blur falloff distance + + float CoC = 0.03; //circle of confusion size in mm (35mm film = 0.03mm) + + uniform bool vignetting; // use optical lens vignetting + + float vignout = 1.3; // vignetting outer border + float vignin = 0.0; // vignetting inner border + float vignfade = 22.0; // f-stops till vignette fades + + uniform bool shaderFocus; + // disable if you use external focalDepth value + + uniform vec2 focusCoords; + // autofocus point on screen (0.0,0.0 - left lower corner, 1.0,1.0 - upper right) + // if center of screen use vec2(0.5, 0.5); + + uniform float maxblur; + //clamp value of max blur (0.0 = no blur, 1.0 default) + + uniform float threshold; // highlight threshold; + uniform float gain; // highlight gain; + + uniform float bias; // bokeh edge bias + uniform float fringe; // bokeh chromatic aberration / fringing + + uniform bool noise; //use noise instead of pattern for sample dithering + + uniform float dithering; + + uniform bool depthblur; // blur the depth buffer + float dbsize = 1.25; // depth blur size + + /* + next part is experimental + not looking good with small sample and ring count + looks okay starting from samples = 4, rings = 4 + */ + + uniform bool pentagon; //use pentagon as bokeh shape? + float feather = 0.4; //pentagon shape feather + + //------------------------------------------ + + float penta(vec2 coords) { + //pentagonal shape + float scale = float(rings) - 1.3; + vec4 HS0 = vec4( 1.0, 0.0, 0.0, 1.0); + vec4 HS1 = vec4( 0.309016994, 0.951056516, 0.0, 1.0); + vec4 HS2 = vec4(-0.809016994, 0.587785252, 0.0, 1.0); + vec4 HS3 = vec4(-0.809016994,-0.587785252, 0.0, 1.0); + vec4 HS4 = vec4( 0.309016994,-0.951056516, 0.0, 1.0); + vec4 HS5 = vec4( 0.0 ,0.0 , 1.0, 1.0); + + vec4 one = vec4( 1.0 ); + + vec4 P = vec4((coords),vec2(scale, scale)); + + vec4 dist = vec4(0.0); + float inorout = -4.0; + + dist.x = dot( P, HS0 ); + dist.y = dot( P, HS1 ); + dist.z = dot( P, HS2 ); + dist.w = dot( P, HS3 ); + + dist = smoothstep( -feather, feather, dist ); + + inorout += dot( dist, one ); + + dist.x = dot( P, HS4 ); + dist.y = HS5.w - abs( P.z ); + + dist = smoothstep( -feather, feather, dist ); + inorout += dist.x; + + return clamp( inorout, 0.0, 1.0 ); + } + + float bdepth(vec2 coords) { + // Depth buffer blur + float d = 0.0; + float kernel[9]; + vec2 offset[9]; + + vec2 wh = vec2(1.0/textureWidth,1.0/textureHeight) * dbsize; + + offset[0] = vec2(-wh.x,-wh.y); + offset[1] = vec2( 0.0, -wh.y); + offset[2] = vec2( wh.x -wh.y); + + offset[3] = vec2(-wh.x, 0.0); + offset[4] = vec2( 0.0, 0.0); + offset[5] = vec2( wh.x, 0.0); + + offset[6] = vec2(-wh.x, wh.y); + offset[7] = vec2( 0.0, wh.y); + offset[8] = vec2( wh.x, wh.y); + + kernel[0] = 1.0/16.0; kernel[1] = 2.0/16.0; kernel[2] = 1.0/16.0; + kernel[3] = 2.0/16.0; kernel[4] = 4.0/16.0; kernel[5] = 2.0/16.0; + kernel[6] = 1.0/16.0; kernel[7] = 2.0/16.0; kernel[8] = 1.0/16.0; + + + for( int i=0; i<9; i++ ) { + float tmp = texture2D(tDepth, coords + offset[i]).r; + d += tmp * kernel[i]; + } + + return d; + } + + + vec3 color(vec2 coords,float blur) { + //processing the sample + + vec3 col = vec3(0.0); + vec2 texel = vec2(1.0/textureWidth,1.0/textureHeight); + + col.r = texture2D(tColor,coords + vec2(0.0,1.0)*texel*fringe*blur).r; + col.g = texture2D(tColor,coords + vec2(-0.866,-0.5)*texel*fringe*blur).g; + col.b = texture2D(tColor,coords + vec2(0.866,-0.5)*texel*fringe*blur).b; + + vec3 lumcoeff = vec3(0.299,0.587,0.114); + float lum = dot(col.rgb, lumcoeff); + float thresh = max((lum-threshold)*gain, 0.0); + return col+mix(vec3(0.0),col,thresh*blur); + } + + vec3 debugFocus(vec3 col, float blur, float depth) { + float edge = 0.002*depth; //distance based edge smoothing + float m = clamp(smoothstep(0.0,edge,blur),0.0,1.0); + float e = clamp(smoothstep(1.0-edge,1.0,blur),0.0,1.0); + + col = mix(col,vec3(1.0,0.5,0.0),(1.0-m)*0.6); + col = mix(col,vec3(0.0,0.5,1.0),((1.0-e)-(1.0-m))*0.2); + + return col; + } + + float linearize(float depth) { + return -zfar * znear / (depth * (zfar - znear) - zfar); + } + + float vignette() { + float dist = distance(vUv.xy, vec2(0.5,0.5)); + dist = smoothstep(vignout+(fstop/vignfade), vignin+(fstop/vignfade), dist); + return clamp(dist,0.0,1.0); + } + + float gather(float i, float j, int ringsamples, inout vec3 col, float w, float h, float blur) { + float rings2 = float(rings); + float step = PI*2.0 / float(ringsamples); + float pw = cos(j*step)*i; + float ph = sin(j*step)*i; + float p = 1.0; + if (pentagon) { + p = penta(vec2(pw,ph)); + } + col += color(vUv.xy + vec2(pw*w,ph*h), blur) * mix(1.0, i/rings2, bias) * p; + return 1.0 * mix(1.0, i /rings2, bias) * p; + } + + void main() { + //scene depth calculation + + float depth = linearize(texture2D(tDepth,vUv.xy).x); + + // Blur depth? + if ( depthblur ) { + depth = linearize(bdepth(vUv.xy)); + } + + //focal plane calculation + + float fDepth = focalDepth; + + if (shaderFocus) { + + fDepth = linearize(texture2D(tDepth,focusCoords).x); + + } + + // dof blur factor calculation + + float blur = 0.0; + + if (manualdof) { + float a = depth-fDepth; // Focal plane + float b = (a-fdofstart)/fdofdist; // Far DoF + float c = (-a-ndofstart)/ndofdist; // Near Dof + blur = (a>0.0) ? b : c; + } else { + float f = focalLength; // focal length in mm + float d = fDepth*1000.0; // focal plane in mm + float o = depth*1000.0; // depth in mm + + float a = (o*f)/(o-f); + float b = (d*f)/(d-f); + float c = (d-f)/(d*fstop*CoC); + + blur = abs(a-b)*c; + } + + blur = clamp(blur,0.0,1.0); + + // calculation of pattern for dithering + + vec2 noise = vec2(rand(vUv.xy), rand( vUv.xy + vec2( 0.4, 0.6 ) ) )*dithering*blur; + + // getting blur x and y step factor + + float w = (1.0/textureWidth)*blur*maxblur+noise.x; + float h = (1.0/textureHeight)*blur*maxblur+noise.y; + + // calculation of final color + + vec3 col = vec3(0.0); + + if(blur < 0.05) { + //some optimization thingy + col = texture2D(tColor, vUv.xy).rgb; + } else { + col = texture2D(tColor, vUv.xy).rgb; + float s = 1.0; + int ringsamples; + + for (int i = 1; i <= rings; i++) { + /*unboxstart*/ + ringsamples = i * samples; + + for (int j = 0 ; j < maxringsamples ; j++) { + if (j >= ringsamples) break; + s += gather(float(i), float(j), ringsamples, col, w, h, blur); + } + /*unboxend*/ + } + + col /= s; //divide by sample count + } + + if (showFocus) { + col = debugFocus(col, blur, depth); + } + + if (vignetting) { + col *= vignette(); + } + + gl_FragColor.rgb = col; + gl_FragColor.a = 1.0; + + #include + #include + }` +}; +// node_modules/three/examples/jsm/shaders/ColorCorrectionShader.js +var ColorCorrectionShader = { + name: "ColorCorrectionShader", + uniforms: { + tDiffuse: { value: null }, + powRGB: { value: new Vector3(2, 2, 2) }, + mulRGB: { value: new Vector3(1, 1, 1) }, + addRGB: { value: new Vector3(0, 0, 0) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform vec3 powRGB; + uniform vec3 mulRGB; + uniform vec3 addRGB; + + varying vec2 vUv; + + void main() { + + gl_FragColor = texture2D( tDiffuse, vUv ); + gl_FragColor.rgb = mulRGB * pow( ( gl_FragColor.rgb + addRGB ), powRGB ); + + }` +}; +// node_modules/three/examples/jsm/shaders/ColorifyShader.js +var ColorifyShader = { + name: "ColorifyShader", + uniforms: { + tDiffuse: { value: null }, + color: { value: new Color(16777215) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform vec3 color; + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + + float v = luminance( texel.xyz ); + + gl_FragColor = vec4( v * color, texel.w ); + + }` +}; +// node_modules/three/examples/jsm/shaders/FXAAShader.js +var FXAAShader = { + name: "FXAAShader", + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2(1 / 1024, 1 / 512) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + // FXAA algorithm from NVIDIA, C# implementation by Jasper Flick, GLSL port by Dave Hoskins + // http://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf + // https://catlikecoding.com/unity/tutorials/advanced-rendering/fxaa/ + + uniform sampler2D tDiffuse; + uniform vec2 resolution; + varying vec2 vUv; + + #define EDGE_STEP_COUNT 6 + #define EDGE_GUESS 8.0 + #define EDGE_STEPS 1.0, 1.5, 2.0, 2.0, 2.0, 4.0 + const float edgeSteps[EDGE_STEP_COUNT] = float[EDGE_STEP_COUNT]( EDGE_STEPS ); + + float _ContrastThreshold = 0.0312; + float _RelativeThreshold = 0.063; + float _SubpixelBlending = 1.0; + + vec4 Sample( sampler2D tex2D, vec2 uv ) { + + return texture( tex2D, uv ); + + } + + float SampleLuminance( sampler2D tex2D, vec2 uv ) { + + return dot( Sample( tex2D, uv ).rgb, vec3( 0.3, 0.59, 0.11 ) ); + + } + + float SampleLuminance( sampler2D tex2D, vec2 texSize, vec2 uv, float uOffset, float vOffset ) { + + uv += texSize * vec2(uOffset, vOffset); + return SampleLuminance(tex2D, uv); + + } + + struct LuminanceData { + + float m, n, e, s, w; + float ne, nw, se, sw; + float highest, lowest, contrast; + + }; + + LuminanceData SampleLuminanceNeighborhood( sampler2D tex2D, vec2 texSize, vec2 uv ) { + + LuminanceData l; + l.m = SampleLuminance( tex2D, uv ); + l.n = SampleLuminance( tex2D, texSize, uv, 0.0, 1.0 ); + l.e = SampleLuminance( tex2D, texSize, uv, 1.0, 0.0 ); + l.s = SampleLuminance( tex2D, texSize, uv, 0.0, -1.0 ); + l.w = SampleLuminance( tex2D, texSize, uv, -1.0, 0.0 ); + + l.ne = SampleLuminance( tex2D, texSize, uv, 1.0, 1.0 ); + l.nw = SampleLuminance( tex2D, texSize, uv, -1.0, 1.0 ); + l.se = SampleLuminance( tex2D, texSize, uv, 1.0, -1.0 ); + l.sw = SampleLuminance( tex2D, texSize, uv, -1.0, -1.0 ); + + l.highest = max( max( max( max( l.n, l.e ), l.s ), l.w ), l.m ); + l.lowest = min( min( min( min( l.n, l.e ), l.s ), l.w ), l.m ); + l.contrast = l.highest - l.lowest; + return l; + + } + + bool ShouldSkipPixel( LuminanceData l ) { + + float threshold = max( _ContrastThreshold, _RelativeThreshold * l.highest ); + return l.contrast < threshold; + + } + + float DeterminePixelBlendFactor( LuminanceData l ) { + + float f = 2.0 * ( l.n + l.e + l.s + l.w ); + f += l.ne + l.nw + l.se + l.sw; + f *= 1.0 / 12.0; + f = abs( f - l.m ); + f = clamp( f / l.contrast, 0.0, 1.0 ); + + float blendFactor = smoothstep( 0.0, 1.0, f ); + return blendFactor * blendFactor * _SubpixelBlending; + + } + + struct EdgeData { + + bool isHorizontal; + float pixelStep; + float oppositeLuminance, gradient; + + }; + + EdgeData DetermineEdge( vec2 texSize, LuminanceData l ) { + + EdgeData e; + float horizontal = + abs( l.n + l.s - 2.0 * l.m ) * 2.0 + + abs( l.ne + l.se - 2.0 * l.e ) + + abs( l.nw + l.sw - 2.0 * l.w ); + float vertical = + abs( l.e + l.w - 2.0 * l.m ) * 2.0 + + abs( l.ne + l.nw - 2.0 * l.n ) + + abs( l.se + l.sw - 2.0 * l.s ); + e.isHorizontal = horizontal >= vertical; + + float pLuminance = e.isHorizontal ? l.n : l.e; + float nLuminance = e.isHorizontal ? l.s : l.w; + float pGradient = abs( pLuminance - l.m ); + float nGradient = abs( nLuminance - l.m ); + + e.pixelStep = e.isHorizontal ? texSize.y : texSize.x; + + if (pGradient < nGradient) { + + e.pixelStep = -e.pixelStep; + e.oppositeLuminance = nLuminance; + e.gradient = nGradient; + + } else { + + e.oppositeLuminance = pLuminance; + e.gradient = pGradient; + + } + + return e; + + } + + float DetermineEdgeBlendFactor( sampler2D tex2D, vec2 texSize, LuminanceData l, EdgeData e, vec2 uv ) { + + vec2 uvEdge = uv; + vec2 edgeStep; + if (e.isHorizontal) { + + uvEdge.y += e.pixelStep * 0.5; + edgeStep = vec2( texSize.x, 0.0 ); + + } else { + + uvEdge.x += e.pixelStep * 0.5; + edgeStep = vec2( 0.0, texSize.y ); + + } + + float edgeLuminance = ( l.m + e.oppositeLuminance ) * 0.5; + float gradientThreshold = e.gradient * 0.25; + + vec2 puv = uvEdge + edgeStep * edgeSteps[0]; + float pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; + bool pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; + + for ( int i = 1; i < EDGE_STEP_COUNT && !pAtEnd; i++ ) { + + puv += edgeStep * edgeSteps[i]; + pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; + pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; + + } + + if ( !pAtEnd ) { + + puv += edgeStep * EDGE_GUESS; + + } + + vec2 nuv = uvEdge - edgeStep * edgeSteps[0]; + float nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; + bool nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; + + for ( int i = 1; i < EDGE_STEP_COUNT && !nAtEnd; i++ ) { + + nuv -= edgeStep * edgeSteps[i]; + nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; + nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; + + } + + if ( !nAtEnd ) { + + nuv -= edgeStep * EDGE_GUESS; + + } + + float pDistance, nDistance; + if ( e.isHorizontal ) { + + pDistance = puv.x - uv.x; + nDistance = uv.x - nuv.x; + + } else { + + pDistance = puv.y - uv.y; + nDistance = uv.y - nuv.y; + + } + + float shortestDistance; + bool deltaSign; + if ( pDistance <= nDistance ) { + + shortestDistance = pDistance; + deltaSign = pLuminanceDelta >= 0.0; + + } else { + + shortestDistance = nDistance; + deltaSign = nLuminanceDelta >= 0.0; + + } + + if ( deltaSign == ( l.m - edgeLuminance >= 0.0 ) ) { + + return 0.0; + + } + + return 0.5 - shortestDistance / ( pDistance + nDistance ); + + } + + vec4 ApplyFXAA( sampler2D tex2D, vec2 texSize, vec2 uv ) { + + LuminanceData luminance = SampleLuminanceNeighborhood( tex2D, texSize, uv ); + if ( ShouldSkipPixel( luminance ) ) { + + return Sample( tex2D, uv ); + + } + + float pixelBlend = DeterminePixelBlendFactor( luminance ); + EdgeData edge = DetermineEdge( texSize, luminance ); + float edgeBlend = DetermineEdgeBlendFactor( tex2D, texSize, luminance, edge, uv ); + float finalBlend = max( pixelBlend, edgeBlend ); + + if (edge.isHorizontal) { + + uv.y += edge.pixelStep * finalBlend; + + } else { + + uv.x += edge.pixelStep * finalBlend; + + } + + return Sample( tex2D, uv ); + + } + + void main() { + + gl_FragColor = ApplyFXAA( tDiffuse, resolution.xy, vUv ); + + }` +}; +// node_modules/three/examples/jsm/shaders/FreiChenShader.js +var FreiChenShader = { + name: "FreiChenShader", + uniforms: { + tDiffuse: { value: null }, + aspect: { value: new Vector2(512, 512) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + varying vec2 vUv; + + uniform vec2 aspect; + + vec2 texel = vec2( 1.0 / aspect.x, 1.0 / aspect.y ); + + + mat3 G[9]; + + // hard coded matrix values!!!! as suggested in https://github.com/neilmendoza/ofxPostProcessing/blob/master/src/EdgePass.cpp#L45 + + const mat3 g0 = mat3( 0.3535533845424652, 0, -0.3535533845424652, 0.5, 0, -0.5, 0.3535533845424652, 0, -0.3535533845424652 ); + const mat3 g1 = mat3( 0.3535533845424652, 0.5, 0.3535533845424652, 0, 0, 0, -0.3535533845424652, -0.5, -0.3535533845424652 ); + const mat3 g2 = mat3( 0, 0.3535533845424652, -0.5, -0.3535533845424652, 0, 0.3535533845424652, 0.5, -0.3535533845424652, 0 ); + const mat3 g3 = mat3( 0.5, -0.3535533845424652, 0, -0.3535533845424652, 0, 0.3535533845424652, 0, 0.3535533845424652, -0.5 ); + const mat3 g4 = mat3( 0, -0.5, 0, 0.5, 0, 0.5, 0, -0.5, 0 ); + const mat3 g5 = mat3( -0.5, 0, 0.5, 0, 0, 0, 0.5, 0, -0.5 ); + const mat3 g6 = mat3( 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.6666666865348816, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204 ); + const mat3 g7 = mat3( -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, 0.6666666865348816, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408 ); + const mat3 g8 = mat3( 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408 ); + + void main(void) + { + + G[0] = g0, + G[1] = g1, + G[2] = g2, + G[3] = g3, + G[4] = g4, + G[5] = g5, + G[6] = g6, + G[7] = g7, + G[8] = g8; + + mat3 I; + float cnv[9]; + vec3 sample; + + /* fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */ + for (float i=0.0; i<3.0; i++) { + for (float j=0.0; j<3.0; j++) { + sample = texture2D(tDiffuse, vUv + texel * vec2(i-1.0,j-1.0) ).rgb; + I[int(i)][int(j)] = length(sample); + } + } + + /* calculate the convolution values for all the masks */ + for (int i=0; i<9; i++) { + float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]); + cnv[i] = dp3 * dp3; + } + + float M = (cnv[0] + cnv[1]) + (cnv[2] + cnv[3]); + float S = (cnv[4] + cnv[5]) + (cnv[6] + cnv[7]) + (cnv[8] + M); + + gl_FragColor = vec4(vec3(sqrt(M/S)), 1.0); + }` +}; +// node_modules/three/examples/jsm/shaders/GodRaysShader.js +var GodRaysGenerateShader = { + name: "GodRaysGenerateShader", + uniforms: { + tInput: { + value: null + }, + fStepSize: { + value: 1 + }, + vSunPositionScreenSpace: { + value: new Vector3 + } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + #define TAPS_PER_PASS 6.0 + + varying vec2 vUv; + + uniform sampler2D tInput; + + uniform vec3 vSunPositionScreenSpace; + uniform float fStepSize; // filter step size + + void main() { + + // delta from current pixel to "sun" position + + vec2 delta = vSunPositionScreenSpace.xy - vUv; + float dist = length( delta ); + + // Step vector (uv space) + + vec2 stepv = fStepSize * delta / dist; + + // Number of iterations between pixel and sun + + float iters = dist/fStepSize; + + vec2 uv = vUv.xy; + float col = 0.0; + + // This breaks ANGLE in Chrome 22 + // - see http://code.google.com/p/chromium/issues/detail?id=153105 + + /* + // Unrolling didn't do much on my hardware (ATI Mobility Radeon 3450), + // so i've just left the loop + + "for ( float i = 0.0; i < TAPS_PER_PASS; i += 1.0 ) {", + + // Accumulate samples, making sure we don't walk past the light source. + + // The check for uv.y < 1 would not be necessary with "border" UV wrap + // mode, with a black border color. I don't think this is currently + // exposed by three.js. As a result there might be artifacts when the + // sun is to the left, right or bottom of screen as these cases are + // not specifically handled. + + " col += ( i <= iters && uv.y < 1.0 ? texture2D( tInput, uv ).r : 0.0 );", + " uv += stepv;", + + "}", + */ + + // Unrolling loop manually makes it work in ANGLE + + float f = min( 1.0, max( vSunPositionScreenSpace.z / 1000.0, 0.0 ) ); // used to fade out godrays + + if ( 0.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 1.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 2.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 3.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 4.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 5.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + // Should technically be dividing by 'iters but 'TAPS_PER_PASS' smooths out + // objectionable artifacts, in particular near the sun position. The side + // effect is that the result is darker than it should be around the sun, as + // TAPS_PER_PASS is greater than the number of samples actually accumulated. + // When the result is inverted (in the shader 'godrays_combine this produces + // a slight bright spot at the position of the sun, even when it is occluded. + + gl_FragColor = vec4( col/TAPS_PER_PASS ); + gl_FragColor.a = 1.0; + + }` +}; +var GodRaysFakeSunShader = { + name: "GodRaysFakeSunShader", + uniforms: { + vSunPositionScreenSpace: { + value: new Vector3 + }, + fAspect: { + value: 1 + }, + sunColor: { + value: new Color(16772608) + }, + bgColor: { + value: new Color(0) + } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + varying vec2 vUv; + + uniform vec3 vSunPositionScreenSpace; + uniform float fAspect; + + uniform vec3 sunColor; + uniform vec3 bgColor; + + void main() { + + vec2 diff = vUv - vSunPositionScreenSpace.xy; + + // Correct for aspect ratio + + diff.x *= fAspect; + + float prop = clamp( length( diff ) / 0.5, 0.0, 1.0 ); + prop = 0.35 * pow( 1.0 - prop, 3.0 ); + + gl_FragColor.xyz = ( vSunPositionScreenSpace.z > 0.0 ) ? mix( sunColor, bgColor, 1.0 - prop ) : bgColor; + gl_FragColor.w = 1.0; + + }` +}; +// node_modules/three/examples/jsm/shaders/HorizontalBlurShader.js +var HorizontalBlurShader = { + name: "HorizontalBlurShader", + uniforms: { + tDiffuse: { value: null }, + h: { value: 1 / 512 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform float h; + + varying vec2 vUv; + + void main() { + + vec4 sum = vec4( 0.0 ); + + sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ) * 0.051; + sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; + sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ) * 0.051; + + gl_FragColor = sum; + + }` +}; +// node_modules/three/examples/jsm/shaders/HorizontalTiltShiftShader.js +var HorizontalTiltShiftShader = { + name: "HorizontalTiltShiftShader", + uniforms: { + tDiffuse: { value: null }, + h: { value: 1 / 512 }, + r: { value: 0.35 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform float h; + uniform float r; + + varying vec2 vUv; + + void main() { + + vec4 sum = vec4( 0.0 ); + + float hh = h * abs( r - vUv.y ); + + sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * hh, vUv.y ) ) * 0.051; + sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * hh, vUv.y ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * hh, vUv.y ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * hh, vUv.y ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; + sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * hh, vUv.y ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * hh, vUv.y ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * hh, vUv.y ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * hh, vUv.y ) ) * 0.051; + + gl_FragColor = sum; + + }` +}; +// node_modules/three/examples/jsm/shaders/NormalMapShader.js +var NormalMapShader = { + name: "NormalMapShader", + uniforms: { + heightMap: { value: null }, + resolution: { value: new Vector2(512, 512) }, + scale: { value: new Vector2(1, 1) }, + height: { value: 0.05 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform float height; + uniform vec2 resolution; + uniform sampler2D heightMap; + + varying vec2 vUv; + + void main() { + + float val = texture2D( heightMap, vUv ).x; + + float valU = texture2D( heightMap, vUv + vec2( 1.0 / resolution.x, 0.0 ) ).x; + float valV = texture2D( heightMap, vUv + vec2( 0.0, 1.0 / resolution.y ) ).x; + + gl_FragColor = vec4( ( 0.5 * normalize( vec3( val - valU, val - valV, height ) ) + 0.5 ), 1.0 ); + + }` +}; +// node_modules/three/examples/jsm/shaders/SobelOperatorShader.js +var SobelOperatorShader = { + name: "SobelOperatorShader", + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform vec2 resolution; + varying vec2 vUv; + + void main() { + + vec2 texel = vec2( 1.0 / resolution.x, 1.0 / resolution.y ); + + // kernel definition (in glsl matrices are filled in column-major order) + + const mat3 Gx = mat3( -1, -2, -1, 0, 0, 0, 1, 2, 1 ); // x direction kernel + const mat3 Gy = mat3( -1, 0, 1, -2, 0, 2, -1, 0, 1 ); // y direction kernel + + // fetch the 3x3 neighbourhood of a fragment + + // first column + + float tx0y0 = texture2D( tDiffuse, vUv + texel * vec2( -1, -1 ) ).r; + float tx0y1 = texture2D( tDiffuse, vUv + texel * vec2( -1, 0 ) ).r; + float tx0y2 = texture2D( tDiffuse, vUv + texel * vec2( -1, 1 ) ).r; + + // second column + + float tx1y0 = texture2D( tDiffuse, vUv + texel * vec2( 0, -1 ) ).r; + float tx1y1 = texture2D( tDiffuse, vUv + texel * vec2( 0, 0 ) ).r; + float tx1y2 = texture2D( tDiffuse, vUv + texel * vec2( 0, 1 ) ).r; + + // third column + + float tx2y0 = texture2D( tDiffuse, vUv + texel * vec2( 1, -1 ) ).r; + float tx2y1 = texture2D( tDiffuse, vUv + texel * vec2( 1, 0 ) ).r; + float tx2y2 = texture2D( tDiffuse, vUv + texel * vec2( 1, 1 ) ).r; + + // gradient value in x direction + + float valueGx = Gx[0][0] * tx0y0 + Gx[1][0] * tx1y0 + Gx[2][0] * tx2y0 + + Gx[0][1] * tx0y1 + Gx[1][1] * tx1y1 + Gx[2][1] * tx2y1 + + Gx[0][2] * tx0y2 + Gx[1][2] * tx1y2 + Gx[2][2] * tx2y2; + + // gradient value in y direction + + float valueGy = Gy[0][0] * tx0y0 + Gy[1][0] * tx1y0 + Gy[2][0] * tx2y0 + + Gy[0][1] * tx0y1 + Gy[1][1] * tx1y1 + Gy[2][1] * tx2y1 + + Gy[0][2] * tx0y2 + Gy[1][2] * tx1y2 + Gy[2][2] * tx2y2; + + // magnitude of the total gradient + + float G = sqrt( ( valueGx * valueGx ) + ( valueGy * valueGy ) ); + + gl_FragColor = vec4( vec3( G ), 1 ); + + }` +}; +// node_modules/three/examples/jsm/shaders/SubsurfaceScatteringShader.js +function replaceAll(string, find2, replace) { + return string.split(find2).join(replace); +} +var meshphong_frag_head = ShaderChunk["meshphong_frag"].slice(0, ShaderChunk["meshphong_frag"].indexOf("void main() {")); +var meshphong_frag_body = ShaderChunk["meshphong_frag"].slice(ShaderChunk["meshphong_frag"].indexOf("void main() {")); +var SubsurfaceScatteringShader = { + name: "SubsurfaceScatteringShader", + uniforms: UniformsUtils.merge([ + ShaderLib["phong"].uniforms, + { + thicknessMap: { value: null }, + thicknessColor: { value: new Color(16777215) }, + thicknessDistortion: { value: 0.1 }, + thicknessAmbient: { value: 0 }, + thicknessAttenuation: { value: 0.1 }, + thicknessPower: { value: 2 }, + thicknessScale: { value: 10 } + } + ]), + vertexShader: [ + "#define USE_UV", + ShaderChunk["meshphong_vert"] + ].join(` +`), + fragmentShader: [ + "#define USE_UV", + "#define SUBSURFACE", + meshphong_frag_head, + "uniform sampler2D thicknessMap;", + "uniform float thicknessPower;", + "uniform float thicknessScale;", + "uniform float thicknessDistortion;", + "uniform float thicknessAmbient;", + "uniform float thicknessAttenuation;", + "uniform vec3 thicknessColor;", + "void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, inout ReflectedLight reflectedLight) {", + "\tvec3 thickness = thicknessColor * texture2D(thicknessMap, uv).r;", + "\tvec3 scatteringHalf = normalize(directLight.direction + (geometryNormal * thicknessDistortion));", + "\tfloat scatteringDot = pow(saturate(dot(geometryViewDir, -scatteringHalf)), thicknessPower) * thicknessScale;", + "\tvec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;", + "\treflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;", + "}", + meshphong_frag_body.replace("#include ", replaceAll(ShaderChunk["lights_fragment_begin"], "RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );", [ + "RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );", + "#if defined( SUBSURFACE ) && defined( USE_UV )", + " RE_Direct_Scattering(directLight, vUv, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, reflectedLight);", + "#endif" + ].join(` +`))) + ].join(` +`) +}; +// node_modules/three/examples/jsm/shaders/ToonShader.js +var ToonShader1 = { + uniforms: { + uDirLightPos: { value: new Vector3 }, + uDirLightColor: { value: new Color(15658734) }, + uAmbientLightColor: { value: new Color(328965) }, + uBaseColor: { value: new Color(16777215) } + }, + vertexShader: ` + + varying vec3 vNormal; + varying vec3 vRefract; + + void main() { + + vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); + vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); + vec3 worldNormal = normalize ( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal ); + + vNormal = normalize( normalMatrix * normal ); + + vec3 I = worldPosition.xyz - cameraPosition; + vRefract = refract( normalize( I ), worldNormal, 1.02 ); + + gl_Position = projectionMatrix * mvPosition; + + }`, + fragmentShader: ` + + uniform vec3 uBaseColor; + + uniform vec3 uDirLightPos; + uniform vec3 uDirLightColor; + + uniform vec3 uAmbientLightColor; + + varying vec3 vNormal; + + varying vec3 vRefract; + + void main() { + + float directionalLightWeighting = max( dot( normalize( vNormal ), uDirLightPos ), 0.0); + vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; + + float intensity = smoothstep( - 0.5, 1.0, pow( length(lightWeighting), 20.0 ) ); + intensity += length(lightWeighting) * 0.2; + + float cameraWeighting = dot( normalize( vNormal ), vRefract ); + intensity += pow( 1.0 - length( cameraWeighting ), 6.0 ); + intensity = intensity * 0.2 + 0.3; + + if ( intensity < 0.50 ) { + + gl_FragColor = vec4( 2.0 * intensity * uBaseColor, 1.0 ); + + } else { + + gl_FragColor = vec4( 1.0 - 2.0 * ( 1.0 - intensity ) * ( 1.0 - uBaseColor ), 1.0 ); + + } + + #include + + }` +}; +var ToonShader2 = { + uniforms: { + uDirLightPos: { value: new Vector3 }, + uDirLightColor: { value: new Color(15658734) }, + uAmbientLightColor: { value: new Color(328965) }, + uBaseColor: { value: new Color(15658734) }, + uLineColor1: { value: new Color(8421504) }, + uLineColor2: { value: new Color(0) }, + uLineColor3: { value: new Color(0) }, + uLineColor4: { value: new Color(0) } + }, + vertexShader: ` + + varying vec3 vNormal; + + void main() { + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + vNormal = normalize( normalMatrix * normal ); + + }`, + fragmentShader: ` + + uniform vec3 uBaseColor; + uniform vec3 uLineColor1; + uniform vec3 uLineColor2; + uniform vec3 uLineColor3; + uniform vec3 uLineColor4; + + uniform vec3 uDirLightPos; + uniform vec3 uDirLightColor; + + uniform vec3 uAmbientLightColor; + + varying vec3 vNormal; + + void main() { + + float camera = max( dot( normalize( vNormal ), vec3( 0.0, 0.0, 1.0 ) ), 0.4); + float light = max( dot( normalize( vNormal ), uDirLightPos ), 0.0); + + gl_FragColor = vec4( uBaseColor, 1.0 ); + + if ( length(uAmbientLightColor + uDirLightColor * light) < 1.00 ) { + + gl_FragColor *= vec4( uLineColor1, 1.0 ); + + } + + if ( length(uAmbientLightColor + uDirLightColor * camera) < 0.50 ) { + + gl_FragColor *= vec4( uLineColor2, 1.0 ); + + } + + #include + + }` +}; +var ToonShaderHatching = { + uniforms: { + uDirLightPos: { value: new Vector3 }, + uDirLightColor: { value: new Color(15658734) }, + uAmbientLightColor: { value: new Color(328965) }, + uBaseColor: { value: new Color(16777215) }, + uLineColor1: { value: new Color(0) }, + uLineColor2: { value: new Color(0) }, + uLineColor3: { value: new Color(0) }, + uLineColor4: { value: new Color(0) } + }, + vertexShader: ` + + varying vec3 vNormal; + + void main() { + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + vNormal = normalize( normalMatrix * normal ); + + }`, + fragmentShader: ` + + uniform vec3 uBaseColor; + uniform vec3 uLineColor1; + uniform vec3 uLineColor2; + uniform vec3 uLineColor3; + uniform vec3 uLineColor4; + + uniform vec3 uDirLightPos; + uniform vec3 uDirLightColor; + + uniform vec3 uAmbientLightColor; + + varying vec3 vNormal; + + void main() { + + float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0); + vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; + + gl_FragColor = vec4( uBaseColor, 1.0 ); + + if ( length(lightWeighting) < 1.00 ) { + + if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) { + + gl_FragColor = vec4( uLineColor1, 1.0 ); + + } + + } + + if ( length(lightWeighting) < 0.75 ) { + + if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) { + + gl_FragColor = vec4( uLineColor2, 1.0 ); + + } + + } + + if ( length(lightWeighting) < 0.50 ) { + + if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) { + + gl_FragColor = vec4( uLineColor3, 1.0 ); + + } + + } + + if ( length(lightWeighting) < 0.3465 ) { + + if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) { + + gl_FragColor = vec4( uLineColor4, 1.0 ); + + } + + } + + #include + + }` +}; +var ToonShaderDotted = { + uniforms: { + uDirLightPos: { value: new Vector3 }, + uDirLightColor: { value: new Color(15658734) }, + uAmbientLightColor: { value: new Color(328965) }, + uBaseColor: { value: new Color(16777215) }, + uLineColor1: { value: new Color(0) } + }, + vertexShader: ` + + varying vec3 vNormal; + + void main() { + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + vNormal = normalize( normalMatrix * normal ); + + }`, + fragmentShader: ` + + uniform vec3 uBaseColor; + uniform vec3 uLineColor1; + uniform vec3 uLineColor2; + uniform vec3 uLineColor3; + uniform vec3 uLineColor4; + + uniform vec3 uDirLightPos; + uniform vec3 uDirLightColor; + + uniform vec3 uAmbientLightColor; + + varying vec3 vNormal; + + void main() { + + float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0); + vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; + + gl_FragColor = vec4( uBaseColor, 1.0 ); + + if ( length(lightWeighting) < 1.00 ) { + + if ( ( mod(gl_FragCoord.x, 4.001) + mod(gl_FragCoord.y, 4.0) ) > 6.00 ) { + + gl_FragColor = vec4( uLineColor1, 1.0 ); + + } + + } + + if ( length(lightWeighting) < 0.50 ) { + + if ( ( mod(gl_FragCoord.x + 2.0, 4.001) + mod(gl_FragCoord.y + 2.0, 4.0) ) > 6.00 ) { + + gl_FragColor = vec4( uLineColor1, 1.0 ); + + } + + } + + #include + + }` +}; +// node_modules/three/examples/jsm/shaders/TriangleBlurShader.js +var TriangleBlurShader = { + name: "TriangleBlurShader", + uniforms: { + texture: { value: null }, + delta: { value: new Vector2(1, 1) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + #include + + #define ITERATIONS 10.0 + + uniform sampler2D texture; + uniform vec2 delta; + + varying vec2 vUv; + + void main() { + + vec4 color = vec4( 0.0 ); + + float total = 0.0; + + // randomize the lookup values to hide the fixed number of samples + + float offset = rand( vUv ); + + for ( float t = -ITERATIONS; t <= ITERATIONS; t ++ ) { + + float percent = ( t + offset - 0.5 ) / ITERATIONS; + float weight = 1.0 - abs( percent ); + + color += texture2D( texture, vUv + delta * percent ) * weight; + total += weight; + + } + + gl_FragColor = color / total; + + }` +}; +// node_modules/three/examples/jsm/shaders/VelocityShader.js +var VelocityShader = { + name: "VelocityShader", + uniforms: UniformsUtils.merge([ + UniformsLib.common, + UniformsLib.displacementmap, + { + modelMatrixPrev: { value: new Matrix4 }, + currentProjectionViewMatrix: { value: new Matrix4 }, + previousProjectionViewMatrix: { value: new Matrix4 } + } + ]), + vertexShader: ` +#define NORMAL + +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + + varying vec3 vViewPosition; + +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +uniform mat4 previousProjectionViewMatrix; +uniform mat4 currentProjectionViewMatrix; + +uniform mat4 modelMatrixPrev; + +varying vec4 clipPositionCurrent; +varying vec4 clipPositionPrevious; + +void main() { + + + #include + + #include + #include + #include + #include + #include + #include + + #include + #include + #include + #include + #include + +#ifdef USE_SKINNING + + vec4 mvPosition = modelViewMatrix * skinned; + clipPositionCurrent = currentProjectionViewMatrix * modelMatrix * skinned; + clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * skinned; + +#else + + vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 ); + clipPositionCurrent = currentProjectionViewMatrix * modelMatrix * vec4( transformed, 1.0 ); + clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * vec4( transformed, 1.0 ); + +#endif + + gl_Position = projectionMatrix * mvPosition; + + #include + #include +} +`, + fragmentShader: ` +#define NORMAL + +uniform float opacity; + +#include +#include +#include +#include +#include +#include +#include + +varying vec4 clipPositionCurrent; +varying vec4 clipPositionPrevious; + +void main() { + + vec4 diffuseColor = vec4( 1.0 ); + diffuseColor.a = opacity; + + #include + #include + #include + + vec2 ndcPositionCurrent = clipPositionCurrent.xy/clipPositionCurrent.w; + vec2 ndcPositionPrevious = clipPositionPrevious.xy/clipPositionPrevious.w; + vec2 vel = ( ndcPositionCurrent - ndcPositionPrevious ) * 0.5; + vel = vel * 0.5 + 0.5; + vec2 v1 = packDepthToRG(vel.x); + vec2 v2 = packDepthToRG(vel.y); + gl_FragColor = vec4(v1.x, v1.y, v2.x, v2.y); + + #include + +} + +` +}; +// node_modules/three/examples/jsm/shaders/VerticalBlurShader.js +var VerticalBlurShader = { + name: "VerticalBlurShader", + uniforms: { + tDiffuse: { value: null }, + v: { value: 1 / 512 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform float v; + + varying vec2 vUv; + + void main() { + + vec4 sum = vec4( 0.0 ); + + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ) * 0.051; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ) * 0.051; + + gl_FragColor = sum; + + }` +}; +// node_modules/three/examples/jsm/shaders/VerticalTiltShiftShader.js +var VerticalTiltShiftShader = { + name: "VerticalTiltShiftShader", + uniforms: { + tDiffuse: { value: null }, + v: { value: 1 / 512 }, + r: { value: 0.35 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform float v; + uniform float r; + + varying vec2 vUv; + + void main() { + + vec4 sum = vec4( 0.0 ); + + float vv = v * abs( r - vUv.y ); + + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * vv ) ) * 0.051; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * vv ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * vv ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * vv ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * vv ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * vv ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * vv ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * vv ) ) * 0.051; + + gl_FragColor = sum; + + }` +}; +// node_modules/three/examples/jsm/shaders/VolumeShader.js +var VolumeRenderShader1 = { + uniforms: { + u_size: { value: new Vector3(1, 1, 1) }, + u_renderstyle: { value: 0 }, + u_renderthreshold: { value: 0.5 }, + u_clim: { value: new Vector2(1, 1) }, + u_data: { value: null }, + u_cmdata: { value: null } + }, + vertexShader: ` + + varying vec4 v_nearpos; + varying vec4 v_farpos; + varying vec3 v_position; + + void main() { + // Prepare transforms to map to "camera view". See also: + // https://threejs.org/docs/#api/renderers/webgl/WebGLProgram + mat4 viewtransformf = modelViewMatrix; + mat4 viewtransformi = inverse(modelViewMatrix); + + // Project local vertex coordinate to camera position. Then do a step + // backward (in cam coords) to the near clipping plane, and project back. Do + // the same for the far clipping plane. This gives us all the information we + // need to calculate the ray and truncate it to the viewing cone. + vec4 position4 = vec4(position, 1.0); + vec4 pos_in_cam = viewtransformf * position4; + + // Intersection of ray and near clipping plane (z = -1 in clip coords) + pos_in_cam.z = -pos_in_cam.w; + v_nearpos = viewtransformi * pos_in_cam; + + // Intersection of ray and far clipping plane (z = +1 in clip coords) + pos_in_cam.z = pos_in_cam.w; + v_farpos = viewtransformi * pos_in_cam; + + // Set varyings and output pos + v_position = position; + gl_Position = projectionMatrix * viewMatrix * modelMatrix * position4; + }`, + fragmentShader: ` + + precision highp float; + precision mediump sampler3D; + + uniform vec3 u_size; + uniform int u_renderstyle; + uniform float u_renderthreshold; + uniform vec2 u_clim; + + uniform sampler3D u_data; + uniform sampler2D u_cmdata; + + varying vec3 v_position; + varying vec4 v_nearpos; + varying vec4 v_farpos; + + // The maximum distance through our rendering volume is sqrt(3). + const int MAX_STEPS = 887; // 887 for 512^3, 1774 for 1024^3 + const int REFINEMENT_STEPS = 4; + const float relative_step_size = 1.0; + const vec4 ambient_color = vec4(0.2, 0.4, 0.2, 1.0); + const vec4 diffuse_color = vec4(0.8, 0.2, 0.2, 1.0); + const vec4 specular_color = vec4(1.0, 1.0, 1.0, 1.0); + const float shininess = 40.0; + + void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray); + void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray); + + float sample1(vec3 texcoords); + vec4 apply_colormap(float val); + vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray); + + + void main() { + // Normalize clipping plane info + vec3 farpos = v_farpos.xyz / v_farpos.w; + vec3 nearpos = v_nearpos.xyz / v_nearpos.w; + + // Calculate unit vector pointing in the view direction through this fragment. + vec3 view_ray = normalize(nearpos.xyz - farpos.xyz); + + // Compute the (negative) distance to the front surface or near clipping plane. + // v_position is the back face of the cuboid, so the initial distance calculated in the dot + // product below is the distance from near clip plane to the back of the cuboid + float distance = dot(nearpos - v_position, view_ray); + distance = max(distance, min((-0.5 - v_position.x) / view_ray.x, + (u_size.x - 0.5 - v_position.x) / view_ray.x)); + distance = max(distance, min((-0.5 - v_position.y) / view_ray.y, + (u_size.y - 0.5 - v_position.y) / view_ray.y)); + distance = max(distance, min((-0.5 - v_position.z) / view_ray.z, + (u_size.z - 0.5 - v_position.z) / view_ray.z)); + + // Now we have the starting position on the front surface + vec3 front = v_position + view_ray * distance; + + // Decide how many steps to take + int nsteps = int(-distance / relative_step_size + 0.5); + if ( nsteps < 1 ) + discard; + + // Get starting location and step vector in texture coordinates + vec3 step = ((v_position - front) / u_size) / float(nsteps); + vec3 start_loc = front / u_size; + + // For testing: show the number of steps. This helps to establish + // whether the rays are correctly oriented + //'gl_FragColor = vec4(0.0, float(nsteps) / 1.0 / u_size.x, 1.0, 1.0); + //'return; + + if (u_renderstyle == 0) + cast_mip(start_loc, step, nsteps, view_ray); + else if (u_renderstyle == 1) + cast_iso(start_loc, step, nsteps, view_ray); + + if (gl_FragColor.a < 0.05) + discard; + } + + + float sample1(vec3 texcoords) { + /* Sample float value from a 3D texture. Assumes intensity data. */ + return texture(u_data, texcoords.xyz).r; + } + + + vec4 apply_colormap(float val) { + val = (val - u_clim[0]) / (u_clim[1] - u_clim[0]); + return texture2D(u_cmdata, vec2(val, 0.5)); + } + + + void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) { + + float max_val = -1e6; + int max_i = 100; + vec3 loc = start_loc; + + // Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with + // non-constant expression. So we use a hard-coded max, and an additional condition + // inside the loop. + for (int iter=0; iter= nsteps) + break; + // Sample from the 3D texture + float val = sample1(loc); + // Apply MIP operation + if (val > max_val) { + max_val = val; + max_i = iter; + } + // Advance location deeper into the volume + loc += step; + } + + // Refine location, gives crispier images + vec3 iloc = start_loc + step * (float(max_i) - 0.5); + vec3 istep = step / float(REFINEMENT_STEPS); + for (int i=0; i= nsteps) + break; + + // Sample from the 3D texture + float val = sample1(loc); + + if (val > low_threshold) { + // Take the last interval in smaller steps + vec3 iloc = loc - 0.5 * step; + vec3 istep = step / float(REFINEMENT_STEPS); + for (int i=0; i u_renderthreshold) { + gl_FragColor = add_lighting(val, iloc, dstep, view_ray); + return; + } + iloc += istep; + } + } + + // Advance location deeper into the volume + loc += step; + } + } + + + vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray) + { + // Calculate color by incorporating lighting + + // View direction + vec3 V = normalize(view_ray); + + // calculate normal vector from gradient + vec3 N; + float val1, val2; + val1 = sample1(loc + vec3(-step[0], 0.0, 0.0)); + val2 = sample1(loc + vec3(+step[0], 0.0, 0.0)); + N[0] = val1 - val2; + val = max(max(val1, val2), val); + val1 = sample1(loc + vec3(0.0, -step[1], 0.0)); + val2 = sample1(loc + vec3(0.0, +step[1], 0.0)); + N[1] = val1 - val2; + val = max(max(val1, val2), val); + val1 = sample1(loc + vec3(0.0, 0.0, -step[2])); + val2 = sample1(loc + vec3(0.0, 0.0, +step[2])); + N[2] = val1 - val2; + val = max(max(val1, val2), val); + + float gm = length(N); // gradient magnitude + N = normalize(N); + + // Flip normal so it points towards viewer + float Nselect = float(dot(N, V) > 0.0); + N = (2.0 * Nselect - 1.0) * N; // == Nselect * N - (1.0-Nselect)*N; + + // Init colors + vec4 ambient_color = vec4(0.0, 0.0, 0.0, 0.0); + vec4 diffuse_color = vec4(0.0, 0.0, 0.0, 0.0); + vec4 specular_color = vec4(0.0, 0.0, 0.0, 0.0); + + // note: could allow multiple lights + for (int i=0; i<1; i++) + { + // Get light direction (make sure to prevent zero devision) + vec3 L = normalize(view_ray); //lightDirs[i]; + float lightEnabled = float( length(L) > 0.0 ); + L = normalize(L + (1.0 - lightEnabled)); + + // Calculate lighting properties + float lambertTerm = clamp(dot(N, L), 0.0, 1.0); + vec3 H = normalize(L+V); // Halfway vector + float specularTerm = pow(max(dot(H, N), 0.0), shininess); + + // Calculate mask + float mask1 = lightEnabled; + + // Calculate colors + ambient_color += mask1 * ambient_color; // * gl_LightSource[i].ambient; + diffuse_color += mask1 * lambertTerm; + specular_color += mask1 * specularTerm * specular_color; + } + + // Calculate final color by componing different components + vec4 final_color; + vec4 color = apply_colormap(val); + final_color = color * (ambient_color + diffuse_color) + specular_color; + final_color.a = color.a; + return final_color; + }` +}; +// node_modules/three/examples/jsm/utils/SkeletonUtils.js +var exports_SkeletonUtils = {}; +__export(exports_SkeletonUtils, { + retargetClip: () => retargetClip, + retarget: () => retarget, + clone: () => clone +}); +function getBoneName(bone, options) { + if (options.getBoneName !== undefined) { + return options.getBoneName(bone); + } + return options.names[bone.name]; +} +function retarget(target, source, options = {}) { + const quat = new Quaternion, scale2 = new Vector3, relativeMatrix = new Matrix4, globalMatrix = new Matrix4; + options.preserveBoneMatrix = options.preserveBoneMatrix !== undefined ? options.preserveBoneMatrix : true; + options.preserveBonePositions = options.preserveBonePositions !== undefined ? options.preserveBonePositions : true; + options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false; + options.hip = options.hip !== undefined ? options.hip : "hip"; + options.hipInfluence = options.hipInfluence !== undefined ? options.hipInfluence : new Vector3(1, 1, 1); + options.scale = options.scale !== undefined ? options.scale : 1; + options.names = options.names || {}; + const sourceBones = source.isObject3D ? source.skeleton.bones : getBones(source), bones = target.isObject3D ? target.skeleton.bones : getBones(target); + let bone, name2, boneTo, bonesPosition; + if (target.isObject3D) { + target.skeleton.pose(); + } else { + options.useTargetMatrix = true; + options.preserveBoneMatrix = false; + } + if (options.preserveBonePositions) { + bonesPosition = []; + for (let i = 0;i < bones.length; i++) { + bonesPosition.push(bones[i].position.clone()); + } + } + if (options.preserveBoneMatrix) { + target.updateMatrixWorld(); + target.matrixWorld.identity(); + for (let i = 0;i < target.children.length; ++i) { + target.children[i].updateMatrixWorld(true); + } + } + for (let i = 0;i < bones.length; ++i) { + bone = bones[i]; + name2 = getBoneName(bone, options); + boneTo = getBoneByName(name2, sourceBones); + globalMatrix.copy(bone.matrixWorld); + if (boneTo) { + boneTo.updateMatrixWorld(); + if (options.useTargetMatrix) { + relativeMatrix.copy(boneTo.matrixWorld); + } else { + relativeMatrix.copy(target.matrixWorld).invert(); + relativeMatrix.multiply(boneTo.matrixWorld); + } + scale2.setFromMatrixScale(relativeMatrix); + relativeMatrix.scale(scale2.set(1 / scale2.x, 1 / scale2.y, 1 / scale2.z)); + globalMatrix.makeRotationFromQuaternion(quat.setFromRotationMatrix(relativeMatrix)); + if (target.isObject3D) { + if (options.localOffsets) { + if (options.localOffsets[bone.name]) { + globalMatrix.multiply(options.localOffsets[bone.name]); + } + } + } + globalMatrix.copyPosition(relativeMatrix); + } + if (name2 === options.hip) { + globalMatrix.elements[12] *= options.scale * options.hipInfluence.x; + globalMatrix.elements[13] *= options.scale * options.hipInfluence.y; + globalMatrix.elements[14] *= options.scale * options.hipInfluence.z; + if (options.hipPosition !== undefined) { + globalMatrix.elements[12] += options.hipPosition.x * options.scale; + globalMatrix.elements[13] += options.hipPosition.y * options.scale; + globalMatrix.elements[14] += options.hipPosition.z * options.scale; + } + } + if (bone.parent) { + bone.matrix.copy(bone.parent.matrixWorld).invert(); + bone.matrix.multiply(globalMatrix); + } else { + bone.matrix.copy(globalMatrix); + } + bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); + bone.updateMatrixWorld(); + } + if (options.preserveBonePositions) { + for (let i = 0;i < bones.length; ++i) { + bone = bones[i]; + name2 = getBoneName(bone, options) || bone.name; + if (name2 !== options.hip) { + bone.position.copy(bonesPosition[i]); + } + } + } + if (options.preserveBoneMatrix) { + target.updateMatrixWorld(true); + } +} +function retargetClip(target, source, clip, options = {}) { + options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false; + options.fps = options.fps !== undefined ? options.fps : Math.max(...clip.tracks.map((track) => track.times.length)) / clip.duration; + options.names = options.names || []; + if (!source.isObject3D) { + source = getHelperFromSkeleton(source); + } + const numFrames = Math.round(clip.duration * (options.fps / 1000) * 1000), delta = clip.duration / (numFrames - 1), convertedTracks = [], mixer = new AnimationMixer(source), bones = getBones(target.skeleton), boneDatas = []; + let positionOffset, bone, boneTo, boneData, name2; + mixer.clipAction(clip).play(); + let start = 0, end = numFrames; + if (options.trim !== undefined) { + start = Math.round(options.trim[0] * options.fps); + end = Math.min(Math.round(options.trim[1] * options.fps), numFrames) - start; + mixer.update(options.trim[0]); + } else { + mixer.update(0); + } + source.updateMatrixWorld(); + for (let frame = 0;frame < end; ++frame) { + const time2 = frame * delta; + retarget(target, source, options); + for (let j2 = 0;j2 < bones.length; ++j2) { + bone = bones[j2]; + name2 = getBoneName(bone, options) || bone.name; + boneTo = getBoneByName(name2, source.skeleton); + if (boneTo) { + boneData = boneDatas[j2] = boneDatas[j2] || { bone }; + if (options.hip === name2) { + if (!boneData.pos) { + boneData.pos = { + times: new Float32Array(end), + values: new Float32Array(end * 3) + }; + } + if (options.useFirstFramePosition) { + if (frame === 0) { + positionOffset = bone.position.clone(); + } + bone.position.sub(positionOffset); + } + boneData.pos.times[frame] = time2; + bone.position.toArray(boneData.pos.values, frame * 3); + } + if (!boneData.quat) { + boneData.quat = { + times: new Float32Array(end), + values: new Float32Array(end * 4) + }; + } + boneData.quat.times[frame] = time2; + bone.quaternion.toArray(boneData.quat.values, frame * 4); + } + } + if (frame === end - 2) { + mixer.update(delta - 0.0000001); + } else { + mixer.update(delta); + } + source.updateMatrixWorld(); + } + for (let i = 0;i < boneDatas.length; ++i) { + boneData = boneDatas[i]; + if (boneData) { + if (boneData.pos) { + convertedTracks.push(new VectorKeyframeTrack(".bones[" + boneData.bone.name + "].position", boneData.pos.times, boneData.pos.values)); + } + convertedTracks.push(new QuaternionKeyframeTrack(".bones[" + boneData.bone.name + "].quaternion", boneData.quat.times, boneData.quat.values)); + } + } + mixer.uncacheAction(clip); + return new AnimationClip(clip.name, -1, convertedTracks); +} +function clone(source) { + const sourceLookup = new Map; + const cloneLookup = new Map; + const clone2 = source.clone(); + parallelTraverse(source, clone2, function(sourceNode, clonedNode) { + sourceLookup.set(clonedNode, sourceNode); + cloneLookup.set(sourceNode, clonedNode); + }); + clone2.traverse(function(node) { + if (!node.isSkinnedMesh) + return; + const clonedMesh = node; + const sourceMesh = sourceLookup.get(node); + const sourceBones = sourceMesh.skeleton.bones; + clonedMesh.skeleton = sourceMesh.skeleton.clone(); + clonedMesh.bindMatrix.copy(sourceMesh.bindMatrix); + clonedMesh.skeleton.bones = sourceBones.map(function(bone) { + return cloneLookup.get(bone); + }); + clonedMesh.bind(clonedMesh.skeleton, clonedMesh.bindMatrix); + }); + return clone2; +} +function getBoneByName(name2, skeleton) { + for (let i = 0, bones = getBones(skeleton);i < bones.length; i++) { + if (name2 === bones[i].name) + return bones[i]; + } +} +function getBones(skeleton) { + return Array.isArray(skeleton) ? skeleton : skeleton.bones; +} +function getHelperFromSkeleton(skeleton) { + const source = new SkeletonHelper(skeleton.bones[0]); + source.skeleton = skeleton; + return source; +} +function parallelTraverse(a2, b2, callback) { + callback(a2, b2); + for (let i = 0;i < a2.children.length; i++) { + parallelTraverse(a2.children[i], b2.children[i], callback); + } +} +// node_modules/three/examples/jsm/utils/SortUtils.js +var POWER = 3; +var BIT_MAX = 32; +var BIN_BITS = 1 << POWER; +var BIN_SIZE = 1 << BIN_BITS; +var BIN_MAX = BIN_SIZE - 1; +var ITERATIONS = BIT_MAX / BIN_BITS; +var bins = new Array(ITERATIONS); +var bins_buffer = new ArrayBuffer((ITERATIONS + 1) * BIN_SIZE * 4); +var c = 0; +for (let i = 0;i < ITERATIONS + 1; i++) { + bins[i] = new Uint32Array(bins_buffer, c, BIN_SIZE); + c += BIN_SIZE * 4; +} +// node_modules/three/examples/jsm/webxr/VRButton.js +class VRButton { + static createButton(renderer2, sessionInit = {}) { + const button = document.createElement("button"); + function showEnterVR() { + let currentSession = null; + async function onSessionStarted(session) { + session.addEventListener("end", onSessionEnded); + await renderer2.xr.setSession(session); + button.textContent = "EXIT VR"; + currentSession = session; + } + function onSessionEnded() { + currentSession.removeEventListener("end", onSessionEnded); + button.textContent = "ENTER VR"; + currentSession = null; + } + button.style.display = ""; + button.style.cursor = "pointer"; + button.style.left = "calc(50% - 50px)"; + button.style.width = "100px"; + button.textContent = "ENTER VR"; + const sessionOptions = { + ...sessionInit, + optionalFeatures: [ + "local-floor", + "bounded-floor", + "layers", + ...sessionInit.optionalFeatures || [] + ] + }; + button.onmouseenter = function() { + button.style.opacity = "1.0"; + }; + button.onmouseleave = function() { + button.style.opacity = "0.5"; + }; + button.onclick = function() { + if (currentSession === null) { + navigator.xr.requestSession("immersive-vr", sessionOptions).then(onSessionStarted); + } else { + currentSession.end(); + if (navigator.xr.offerSession !== undefined) { + navigator.xr.offerSession("immersive-vr", sessionOptions).then(onSessionStarted).catch((err) => { + console.warn(err); + }); + } + } + }; + if (navigator.xr.offerSession !== undefined) { + navigator.xr.offerSession("immersive-vr", sessionOptions).then(onSessionStarted).catch((err) => { + console.warn(err); + }); + } + } + function disableButton() { + button.style.display = ""; + button.style.cursor = "auto"; + button.style.left = "calc(50% - 75px)"; + button.style.width = "150px"; + button.onmouseenter = null; + button.onmouseleave = null; + button.onclick = null; + } + function showWebXRNotFound() { + disableButton(); + button.textContent = "VR NOT SUPPORTED"; + } + function showVRNotAllowed(exception) { + disableButton(); + console.warn("Exception when trying to call xr.isSessionSupported", exception); + button.textContent = "VR NOT ALLOWED"; + } + function stylizeElement(element) { + element.style.position = "absolute"; + element.style.bottom = "20px"; + element.style.padding = "12px 6px"; + element.style.border = "1px solid #fff"; + element.style.borderRadius = "4px"; + element.style.background = "rgba(0,0,0,0.1)"; + element.style.color = "#fff"; + element.style.font = "normal 13px sans-serif"; + element.style.textAlign = "center"; + element.style.opacity = "0.5"; + element.style.outline = "none"; + element.style.zIndex = "999"; + } + if ("xr" in navigator) { + button.id = "VRButton"; + button.style.display = "none"; + stylizeElement(button); + navigator.xr.isSessionSupported("immersive-vr").then(function(supported) { + supported ? showEnterVR() : showWebXRNotFound(); + if (supported && VRButton.xrSessionIsGranted) { + button.click(); + } + }).catch(showVRNotAllowed); + return button; + } else { + const message = document.createElement("a"); + if (window.isSecureContext === false) { + message.href = document.location.href.replace(/^http:/, "https:"); + message.innerHTML = "WEBXR NEEDS HTTPS"; + } else { + message.href = "https://immersiveweb.dev/"; + message.innerHTML = "WEBXR NOT AVAILABLE"; + } + message.style.left = "calc(50% - 90px)"; + message.style.width = "180px"; + message.style.textDecoration = "none"; + stylizeElement(message); + return message; + } + } + static registerSessionGrantedListener() { + if (typeof navigator !== "undefined" && "xr" in navigator) { + if (/WebXRViewer\//i.test(navigator.userAgent)) + return; + navigator.xr.addEventListener("sessiongranted", () => { + VRButton.xrSessionIsGranted = true; + }); + } + } +} +VRButton.xrSessionIsGranted = false; +VRButton.registerSessionGrantedListener(); +// node_modules/three/examples/jsm/libs/motion-controllers.module.js +var Constants = { + Handedness: Object.freeze({ + NONE: "none", + LEFT: "left", + RIGHT: "right" + }), + ComponentState: Object.freeze({ + DEFAULT: "default", + TOUCHED: "touched", + PRESSED: "pressed" + }), + ComponentProperty: Object.freeze({ + BUTTON: "button", + X_AXIS: "xAxis", + Y_AXIS: "yAxis", + STATE: "state" + }), + ComponentType: Object.freeze({ + TRIGGER: "trigger", + SQUEEZE: "squeeze", + TOUCHPAD: "touchpad", + THUMBSTICK: "thumbstick", + BUTTON: "button" + }), + ButtonTouchThreshold: 0.05, + AxisTouchThreshold: 0.1, + VisualResponseProperty: Object.freeze({ + TRANSFORM: "transform", + VISIBILITY: "visibility" + }) +}; +var defaultComponentValues = { + xAxis: 0, + yAxis: 0, + button: 0, + state: Constants.ComponentState.DEFAULT +}; +// node_modules/three/examples/jsm/webxr/XRHandPrimitiveModel.js +var _matrix7 = new Matrix4; +var _vector9 = new Vector3; +// src/util/ModelLoader.ts +//! NOTE: THIS ASSUMES THE ROOT IS THE PUBLIC FOLDER +var root = "/"; +var setRoot = (newRoot) => { + root = newRoot; +}; +var gltfLoader = new GLTFLoader; +var imageLoader = new ImageBitmapLoader; +function makeModelPath(gender, modelName) { + return `${root}assets/models/miiBody${gender}_${modelName}.glb`; +} +async function loadBodyModel(modelPath) { + const model = await gltfLoader.loadAsync(modelPath); + var mixer = new AnimationMixer(model.scene); + const scene = model.scene; + if (model.animations.length > 0) { + const idleClip = model.animations[0]; + const idleAnim = mixer.clipAction(idleClip, scene); + idleAnim.stop(); + try { + const clip = model.animations.find((a2) => a2.name === "Pose.01"); + const anim = mixer.clipAction(clip, scene); + anim.play(); + anim.timeScale = 0; + anim.paused = true; + mixer.update(0); + } catch (e) { + } + } else + console.warn("Body model has no animations"); + return model; +} +var bodyType = "wiiu"; +async function loadBodyModels(input, alsoLoadStreetPass = false) { + if (Object.keys(bodyModels).length > 0) { + bodyModels = {}; + } + bodyType = input || await import_localforage2.default.getItem("settings_bodyModel") || "wiiu"; + bodyModelName = bodyType; + if (bodyType === "streetpass" /* StreetPass */) { + isStreetPassBody = true; + } + if (bodyModels.highM) { + bodyModels.highM.scene.traverse((o) => { + if (o.isMesh) { + o.dispose(); + } + }); + } + if (bodyModels.highF) { + bodyModels.highF.scene.traverse((o) => { + if (o.isMesh) { + o.dispose(); + } + }); + } + bodyModels.highM = await loadBodyModel(makeModelPath("M", bodyType)); + bodyModels.highF = await loadBodyModel(makeModelPath("F", bodyType)); + if (alsoLoadStreetPass) { + bodyModels.lowM = await loadBodyModel(makeModelPath("M", "streetpass")); + bodyModels.lowF = await loadBodyModel(makeModelPath("F", "streetpass")); + } +} +async function loadHatModels() { + hatModels = []; + const data2 = await fetch(root + "assets/models/hat_models_bundle.zip").then((j2) => j2.blob()); + const zip = await import_jszip.default.loadAsync(data2); + let promises = []; + const fileList = Object.keys(zip.files); + for (const file of fileList) { + promises.push(zip.files[file].async("blob")); + } + const resolves = await Promise.all(promises); + for (let i = 0;i < fileList.length; i++) { + console.log("File:", fileList[i]); + const url = URL.createObjectURL(resolves[i]); + const gltf = await gltfLoader.loadAsync(url); + hatModels[i] = gltf.scene; + URL.revokeObjectURL(url); + } +} +async function loadClothesTextures() { + clothesTextures = {}; + imageLoader.setOptions({ imageOrientation: "flipY" }); + const data2 = await fetch(root + "assets/images/mii_clothes_textures_bundle.zip").then((j2) => j2.blob()); + console.log("Got it"); + const zip = await import_jszip.default.loadAsync(data2); + console.log("Got zip"); + let promises = []; + const fileList = Object.keys(zip.files); + for (const file of fileList) { + promises.push(zip.files[file].async("blob")); + } + const resolves = await Promise.all(promises); + console.log("Got files"); + for (let i = 0;i < fileList.length; i++) { + const url = URL.createObjectURL(resolves[i]); + let result; + console.log("Loading texture"); + result = new CanvasTexture(await imageLoader.loadAsync(url)); + console.log("Loading texture done"); + const fileName = fileList[i].split("."); + fileName.pop(); + clothesTextures[fileName.join(".")] = result; + console.log("Loading " + fileName.join(".")); + URL.revokeObjectURL(url); + } + console.log("Done"); +} +var bodyModels = { + highM: null, + highF: null, + lowM: null, + lowF: null +}; +var bodyModelName = "wiiu"; +var hatModels = []; +var clothesTextures = {}; +var isStreetPassBody = false; +var isStreetPass = () => isStreetPassBody; +var getBodyModels = () => bodyModels; +var getHatModels = () => hatModels; +var getLoadedBodyModelName = () => bodyModelName; +var getClothesTextures = () => clothesTextures; + +// src/constants/Extensions.ts +var ExtHatNameList = [ + "Cap", + "Beanie", + "Top Hat", + "Ribbon", + "Bow", + "Cat Ears", + "Straw Hat", + "Hijab", + "Bike Helmet" +]; +var ExtClothesList = ["LS+Pants", "SS+Shorts", "TT+Shorts"]; +var HatTypeList = [ + 1 /* HAT */, + 1 /* HAT */, + 1 /* HAT */, + 4 /* SIDE */, + 4 /* SIDE */, + 0 /* HEAD */, + 1 /* HAT */, + 6 /* BALD */, + 1 /* HAT */ +]; +var ClothesTypeList = [ + 0 /* COLOR_MIXED */, + 0 /* COLOR_MIXED */, + 0 /* COLOR_MIXED */, + 0 /* COLOR_MIXED */ +]; + +// src/util/allocateArray.ts +function allocateArray(size2, data2) { + if (data2.length > size2) + throw new RangeError(`Tried to fill ${data2.length} bytes into a ${size2}-byte array`); + let array = new Uint8Array(size2); + for (var i = 0;i < data2.length; i++) { + array[i] = data2[i]; + } + return array; +} + +// src/util/dataConvert.ts +function dataToBase64(data2) { + return btoa(String.fromCharCode.apply(null, data2)); +} +function dataToHex(data2) { + return Array.from(data2, (i) => i.toString(16).padStart(2, "0")).join(""); +} +function encodeUTF16LE(str) { + const buffer = new ArrayBuffer(str.length * 2); + const view = new DataView(buffer); + for (let i = 0;i < str.length; i++) { + view.setUint16(i * 2, str.charCodeAt(i), true); + } + return new Uint8Array(buffer); +} +function decodeUTF16LE(bytes) { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let result = ""; + for (let i = 0;i < view.byteLength; i += 2) { + result += String.fromCharCode(view.getUint16(i, true)); + } + return result; +} + +// src/util/Numbers.ts +var ArrayNum = (number) => Array.from(Array(number).keys()); +var RandomInt = (max) => Math.floor(Math.random() * max); +function randomizeUint8Array(arr) { + if (!(arr instanceof Uint8Array)) { + throw new TypeError("Expected a Uint8Array"); + } + function randomize() { + for (let i = 0;i < arr.length; i++) { + arr[i] = Math.floor(Math.random() * 256); + } + } + if (typeof window !== "undefined") { + if (window.crypto && window.crypto.getRandomValues) { + window.crypto.getRandomValues(arr); + } else + randomize(); + } else { + randomize(); + } + return arr; +} + +// src/class/struct/FFLStoreData.ts +var import_struct_fu = __toESM(require_struct_fu(), 1); +var FFLiCreateID = import_struct_fu.default.struct([ + import_struct_fu.default.ubit("flag_normal", 1), + import_struct_fu.default.ubit("flag_1", 1), + import_struct_fu.default.ubit("flag_temporary", 1), + import_struct_fu.default.ubit("flag_3", 1), + import_struct_fu.default.ubit("create_date1", 14), + import_struct_fu.default.ubit("create_date2", 14), + import_struct_fu.default.byte("base", 6) +]); +var FFLiAuthorID = import_struct_fu.default.struct([import_struct_fu.default.byte("data", 8)]); +var Ver3StoreData = import_struct_fu.default.struct([ + import_struct_fu.default.ubitLE("mii_version", 8), + import_struct_fu.default.ubitLE("copyable", 1), + import_struct_fu.default.ubitLE("ng_word", 1), + import_struct_fu.default.ubitLE("region_move", 2), + import_struct_fu.default.ubitLE("font_region", 2), + import_struct_fu.default.ubitLE("reserved_0", 2), + import_struct_fu.default.ubitLE("room_index", 4), + import_struct_fu.default.ubitLE("position_in_room", 4), + import_struct_fu.default.ubitLE("author_type", 4), + import_struct_fu.default.ubitLE("birth_platform", 3), + import_struct_fu.default.ubitLE("reserved_1"), + import_struct_fu.default.struct("author_id", [FFLiAuthorID]), + import_struct_fu.default.struct("create_id", [FFLiCreateID]), + import_struct_fu.default.byte("reserved_2", 2), + import_struct_fu.default.ubitLE("gender", 1), + import_struct_fu.default.ubitLE("birth_month", 4), + import_struct_fu.default.ubitLE("birth_day", 5), + import_struct_fu.default.ubitLE("favorite_color", 4), + import_struct_fu.default.ubitLE("favorite", 1), + import_struct_fu.default.ubitLE("padding_0", 1), + import_struct_fu.default.char16le("name", 20), + import_struct_fu.default.uint8("height"), + import_struct_fu.default.uint8("build"), + import_struct_fu.default.ubitLE("localonly", 1), + import_struct_fu.default.ubitLE("face_type", 4), + import_struct_fu.default.ubitLE("face_color", 3), + import_struct_fu.default.ubitLE("face_tex", 4), + import_struct_fu.default.ubitLE("face_make", 4), + import_struct_fu.default.ubitLE("hair_type", 8), + import_struct_fu.default.ubitLE("hair_color", 3), + import_struct_fu.default.ubitLE("hair_flip", 1), + import_struct_fu.default.ubitLE("padding_1", 4), + import_struct_fu.default.ubitLE("eye_type", 6), + import_struct_fu.default.ubitLE("eye_color", 3), + import_struct_fu.default.ubitLE("eye_scale", 4), + import_struct_fu.default.ubitLE("eye_aspect", 3), + import_struct_fu.default.ubitLE("eye_rotate", 5), + import_struct_fu.default.ubitLE("eye_x", 4), + import_struct_fu.default.ubitLE("eye_y", 5), + import_struct_fu.default.ubitLE("padding_2", 2), + import_struct_fu.default.ubitLE("eyebrow_type", 5), + import_struct_fu.default.ubitLE("eyebrow_color", 3), + import_struct_fu.default.ubitLE("eyebrow_scale", 4), + import_struct_fu.default.ubitLE("eyebrow_aspect", 3), + import_struct_fu.default.ubitLE("padding_3", 1), + import_struct_fu.default.ubitLE("eyebrow_rotate", 5), + import_struct_fu.default.ubitLE("eyebrow_x", 4), + import_struct_fu.default.ubitLE("eyebrow_y", 5), + import_struct_fu.default.ubitLE("padding_4", 2), + import_struct_fu.default.ubitLE("nose_type", 5), + import_struct_fu.default.ubitLE("nose_scale", 4), + import_struct_fu.default.ubitLE("nose_y", 5), + import_struct_fu.default.ubitLE("padding_5", 2), + import_struct_fu.default.ubitLE("mouth_type", 6), + import_struct_fu.default.ubitLE("mouth_color", 3), + import_struct_fu.default.ubitLE("mouth_scale", 4), + import_struct_fu.default.ubitLE("mouth_aspect", 3), + import_struct_fu.default.ubitLE("mouth_y", 5), + import_struct_fu.default.ubitLE("mustache_type", 3), + import_struct_fu.default.ubitLE("padding_6", 8), + import_struct_fu.default.ubitLE("beard_type", 3), + import_struct_fu.default.ubitLE("beard_color", 3), + import_struct_fu.default.ubitLE("beard_scale", 4), + import_struct_fu.default.ubitLE("beard_y", 5), + import_struct_fu.default.ubitLE("padding_7", 1), + import_struct_fu.default.ubitLE("glasses_type", 4), + import_struct_fu.default.ubitLE("glasses_color", 3), + import_struct_fu.default.ubitLE("glasses_scale", 4), + import_struct_fu.default.ubitLE("glass_y", 5), + import_struct_fu.default.ubitLE("mole_type", 1), + import_struct_fu.default.ubitLE("mole_scale", 4), + import_struct_fu.default.ubitLE("mole_x", 5), + import_struct_fu.default.ubitLE("mole_y", 5), + import_struct_fu.default.ubitLE("padding_8", 1), + import_struct_fu.default.char16le("creator", 20), + import_struct_fu.default.uint16le("padding_9"), + import_struct_fu.default.uint16("checksum") +]); +function calculateCRC16(storeData) { + const data2 = storeData.subarray(0, 94); + console.log(data2); + let crc = 0; + for (const byte of data2) { + for (let bit = 7;bit >= 0; bit--) { + const flag = (crc & 32768) != 0; + crc = (crc << 1 | byte >> bit & 1) ^ (flag ? 4129 : 0); + } + } + for (let i = 16;i > 0; i--) { + const flag = (crc & 32768) != 0; + crc = crc << 1 ^ (flag ? 4129 : 0); + } + return crc & 65535; +} + +// src/class/struct/MiiCreatorV3Data.ts +var import_struct_fu4 = __toESM(require_struct_fu(), 1); + +// src/class/struct/MiiCreatorV4Data.ts +var import_struct_fu3 = __toESM(require_struct_fu(), 1); + +// src/class/struct/RFLStoreData.ts +var import_struct_fu2 = __toESM(require_struct_fu(), 1); + +// src/constants/ColorTables.ts +var MiiFavoriteColorLookupTable = { + 0: 13770260, + 1: 16739865, + 2: 16767008, + 3: 7918112, + 4: 30768, + 5: 673980, + 6: 3975902, + 7: 16079485, + 8: 7547053, + 9: 4732952, + 10: 14737632, + 11: 1579028 +}; +var MiiFavoriteColorVec3Table = { + 0: [0.8235294117647058, 0.11764705882352941, 0.0784313725490196], + 1: [1, 0.43137254901960786, 0.09803921568627451], + 2: [1, 0.8470588235294118, 0.12549019607843137], + 3: [0.47058823529411764, 0.8235294117647058, 0.12549019607843137], + 4: [0, 0.47058823529411764, 0.18823529411764706], + 5: [0.0392156862745098, 0.2823529411764706, 0.7372549019607844], + 6: [0.23529411764705882, 0.6666666666666666, 0.8705882352941177], + 7: [0.9607843137254902, 0.35294117647058826, 0.49019607843137253], + 8: [0.45098039215686275, 0.1568627450980392, 0.6784313725490196], + 9: [0.2823529411764706, 0.2196078431372549, 0.09411764705882353], + 10: [0.8784313725490196, 0.8784313725490196, 0.8784313725490196], + 11: [0.09411764705882353, 0.09411764705882353, 0.0784313725490196] +}; +var MiiFavoriteColorIconTable = { + 0: { top: "#d21e14", bottom: "#630e09" }, + 1: { top: "#ff6e19", bottom: "#78340c" }, + 2: { top: "#ffd820", bottom: "#78660f" }, + 3: { top: "#78d220", bottom: "#38630f" }, + 4: { top: "#007830", bottom: "#003817" }, + 5: { top: "#0a48bc", bottom: "#052258" }, + 6: { top: "#3caade", bottom: "#1c5068" }, + 7: { top: "#f55a7d", bottom: "#732a3b" }, + 8: { top: "#7328ad", bottom: "#361351" }, + 9: { top: "#483818", bottom: "#221a0b" }, + 10: { top: "#e0e0e0", bottom: "#696969" }, + 11: { top: "#181814", bottom: "#0b0b09" } +}; +var MiiSkinColorTable = { + 0: "#FFD3AD", + 1: "#FEB66B", + 2: "#DE7942", + 3: "#FFAA8C", + 4: "#AD5129", + 5: "#632C18", + 6: "#ffbea5", + 7: "#ffc58f", + 8: "#8c3c23", + 9: "#3c2d23" +}; +var SwitchMiiColorTable = [ + "#2d2828", + "#402010", + "#5c180a", + "#7c3a14", + "#787880", + "#4e3e10", + "#885818", + "#d0a04a", + "#000000", + "#6c7070", + "#663c2c", + "#605e30", + "#4654a8", + "#387058", + "#603810", + "#a81008", + "#203068", + "#a86000", + "#787068", + "#d85208", + "#f00c08", + "#f54848", + "#f09a74", + "#8c5040", + "#842626", + "#ff7366", + "#ffa6a6", + "#ffc0ba", + "#732e3b", + "#991f3d", + "#8a173e", + "#b53e42", + "#c71e56", + "#b05381", + "#c7546e", + "#fa7597", + "#fcacc9", + "#ffc9d8", + "#311c40", + "#37283d", + "#4c184d", + "#6f42b3", + "#855cb8", + "#c083cc", + "#a893c9", + "#c5ace6", + "#eebefa", + "#d2c5ed", + "#191f40", + "#123f66", + "#2a82d4", + "#57b4f2", + "#7ac5de", + "#89a6fa", + "#84bdfa", + "#a1e3ff", + "#0b2e36", + "#013d3b", + "#0d4f59", + "#236663", + "#307e8c", + "#4faeb0", + "#7ac49e", + "#7fd4c0", + "#87e5b6", + "#0a4a35", + "#437a00", + "#027562", + "#369970", + "#4bad1a", + "#92bf0a", + "#63c788", + "#9ee042", + "#96de7e", + "#bbf2aa", + "#99932b", + "#a69563", + "#ccc039", + "#ccb987", + "#d9cc82", + "#d5d96f", + "#d5e683", + "#d8fa9d", + "#7d4500", + "#e6bb7a", + "#fee24a", + "#fade82", + "#f7ea9c", + "#faf89b", + "#a64d1e", + "#ff960d", + "#d19b69", + "#ffb266", + "#ffc28c", + "#e5cfb1", + "#414141", + "#9b9b9b", + "#bebebe", + "#dcd7cd", + "#ffffff" +]; +var SwitchMiiColorTableLip = [ + "#171414", + "#201008", + "#2e0c05", + "#4a230c", + "#54545a", + "#271f08", + "#52350e", + "#b18028", + "#000000", + "#4c4e4e", + "#331e16", + "#3a381d", + "#2a3265", + "#274e3e", + "#301c08", + "#650a05", + "#101834", + "#764300", + "#544e49", + "#823018", + "#780c0c", + "#882028", + "#dc7850", + "#461e0a", + "#4f1717", + "#99453d", + "#e68585", + "#e6a19b", + "#451c23", + "#5c1325", + "#530e25", + "#6d2528", + "#771234", + "#6a324d", + "#773242", + "#af526a", + "#e38cac", + "#e6abbb", + "#190e20", + "#1c141f", + "#260c27", + "#43286b", + "#50376e", + "#865c8f", + "#76678d", + "#ab90cf", + "#d4a0e1", + "#b8aad5", + "#0d1020", + "#092033", + "#1d5b94", + "#3297da", + "#5cadc8", + "#6786e1", + "#629fe1", + "#80c7e6", + "#06171b", + "#011f1e", + "#07282d", + "#184745", + "#225862", + "#308b8d", + "#60b087", + "#63bfa9", + "#69ce9b", + "#05251b", + "#284900", + "#01463b", + "#266b4e", + "#2c8a00", + "#6e9900", + "#47b36f", + "#82ca1f", + "#7ac860", + "#9eda8c", + "#6b671e", + "#746845", + "#a39816", + "#b8a36d", + "#c3b565", + "#bfc351", + "#bdcf64", + "#bce17d", + "#4b2900", + "#cfa15a", + "#e5c622", + "#e1c35f", + "#ded07c", + "#e1df7a", + "#642e12", + "#cc780a", + "#bc824c", + "#e69240", + "#e6a469", + "#ceb696", + "#212121", + "#7c7c7c", + "#ababab", + "#c6c1b6", + "#d9d9d9" +]; +var SwitchMiiColorTableSRGB = [ + [0.1764706, 0.1568628, 0.1568628], + [0.2509804, 0.1254902, 0.0627451], + [0.3607844, 0.0941177, 0.0392157], + [0.4862746, 0.227451, 0.0784314], + [0.4705883, 0.4705883, 0.5019608], + [0.3058824, 0.2431373, 0.0627451], + [0.5333334, 0.3450981, 0.0941177], + [0.8156863, 0.627451, 0.2901961], + [0, 0, 0], + [0.4235295, 0.4392157, 0.4392157], + [0.4, 0.2352942, 0.1725491], + [0.3764706, 0.3686275, 0.1882353], + [0.2745099, 0.3294118, 0.6588236], + [0.2196079, 0.4392157, 0.3450981], + [0.3764706, 0.2196079, 0.0627451], + [0.6588236, 0.0627451, 0.0313726], + [0.1254902, 0.1882353, 0.4078432], + [0.6588236, 0.3764706, 0], + [0.4705883, 0.4392157, 0.4078432], + [0.8470589, 0.3215687, 0.0313726], + [0.9411765, 0.0470589, 0.0313726], + [0.9607844, 0.282353, 0.282353], + [0.9411765, 0.6039216, 0.454902], + [0.5490197, 0.3137255, 0.2509804], + [0.5176471, 0.1490197, 0.1490197], + [1, 0.4509804, 0.4], + [1, 0.6509804, 0.6509804], + [1, 0.7529412, 0.7294118], + [0.4509804, 0.1803922, 0.2313726], + [0.6, 0.1215687, 0.2392157], + [0.5411765, 0.0901961, 0.2431373], + [0.709804, 0.2431373, 0.2588236], + [0.7803922, 0.1176471, 0.337255], + [0.6901961, 0.3254902, 0.5058824], + [0.7803922, 0.3294118, 0.4313726], + [0.9803922, 0.4588236, 0.5921569], + [0.9882353, 0.6745099, 0.7882353], + [1, 0.7882353, 0.8470589], + [0.1921569, 0.109804, 0.2509804], + [0.2156863, 0.1568628, 0.2392157], + [0.2980393, 0.0941177, 0.3019608], + [0.4352942, 0.2588236, 0.7019608], + [0.5215687, 0.3607844, 0.7215687], + [0.7529412, 0.5137255, 0.8], + [0.6588236, 0.5764706, 0.7882353], + [0.7725491, 0.6745099, 0.9019608], + [0.9333334, 0.7450981, 0.9803922], + [0.8235295, 0.7725491, 0.9294118], + [0.0980393, 0.1215687, 0.2509804], + [0.0705883, 0.2470589, 0.4], + [0.1647059, 0.509804, 0.8313726], + [0.3411765, 0.7058824, 0.9490197], + [0.4784314, 0.7725491, 0.8705883], + [0.537255, 0.6509804, 0.9803922], + [0.5176471, 0.7411765, 0.9803922], + [0.6313726, 0.8901961, 1], + [0.0431373, 0.1803922, 0.2117648], + [0.0039216, 0.2392157, 0.2313726], + [0.0509804, 0.309804, 0.3490197], + [0.137255, 0.4, 0.3882353], + [0.1882353, 0.4941177, 0.5490197], + [0.309804, 0.682353, 0.6901961], + [0.4784314, 0.7686275, 0.6196079], + [0.4980393, 0.8313726, 0.7529412], + [0.5294118, 0.8980393, 0.7137255], + [0.0392157, 0.2901961, 0.2078432], + [0.2627451, 0.4784314, 0], + [0.0078432, 0.4588236, 0.3843138], + [0.2117648, 0.6, 0.4392157], + [0.2941177, 0.6784314, 0.1019608], + [0.5725491, 0.7490197, 0.0392157], + [0.3882353, 0.7803922, 0.5333334], + [0.6196079, 0.8784314, 0.2588236], + [0.5882353, 0.8705883, 0.4941177], + [0.7333334, 0.9490197, 0.6666667], + [0.6, 0.5764706, 0.1686275], + [0.6509804, 0.5843138, 0.3882353], + [0.8, 0.7529412, 0.2235295], + [0.8, 0.7254902, 0.5294118], + [0.8509804, 0.8, 0.509804], + [0.8352942, 0.8509804, 0.4352942], + [0.8352942, 0.9019608, 0.5137255], + [0.8470589, 0.9803922, 0.6156863], + [0.4901961, 0.2705883, 0], + [0.9019608, 0.7333334, 0.4784314], + [0.9960785, 0.8862746, 0.2901961], + [0.9803922, 0.8705883, 0.509804], + [0.9686275, 0.9176471, 0.6117648], + [0.9803922, 0.9725491, 0.6078432], + [0.6509804, 0.3019608, 0.1176471], + [1, 0.5882353, 0.0509804], + [0.8196079, 0.6078432, 0.4117648], + [1, 0.6980393, 0.4], + [1, 0.7607844, 0.5490197], + [0.8980393, 0.8117648, 0.6941177], + [0.254902, 0.254902, 0.254902], + [0.6078432, 0.6078432, 0.6078432], + [0.7450981, 0.7450981, 0.7450981], + [0.8627451, 0.8431373, 0.8039216], + [1, 1, 1] +]; +var MiiSwitchSkinColorList = { + 0: "#ffd3ad", + 1: "#ffb66b", + 2: "#de7942", + 3: "#ffaa8c", + 4: "#ad5129", + 5: "#632c18", + 6: "#ffbea5", + 7: "#ffc58f", + 8: "#8c3c23", + 9: "#3c2d23" +}; +var MiiSwitchSkinColorSRGB = [ + [1, 0.8274509906768799, 0.6784313917160034], + [1, 0.7137255072593689, 0.41960790753364563], + [0.8705883026123047, 0.4745098948478699, 0.25882360339164734], + [1, 0.6666666865348816, 0.5490196943283081], + [0.6784313917160034, 0.3176470994949341, 0.16078439354896545], + [0.38823530077934265, 0.17254909873008728, 0.09411770105361938], + [1, 0.7450981140136719, 0.64705890417099], + [1, 0.7725490927696228, 0.5607843995094299], + [0.5490196943283081, 0.2352941930294037, 0.137254998087883], + [0.2352941930294037, 0.1764705926179886, 0.137254998087883] +]; +var ToVer3GlassTypeTable = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 1, + 2, + 1, + 3, + 7, + 7, + 6, + 7, + 8, + 7, + 7 +]; +var ToVer3HairColorTable = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 0, + 4, + 3, + 5, + 4, + 4, + 6, + 2, + 0, + 6, + 4, + 3, + 2, + 2, + 7, + 3, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 0, + 0, + 4, + 4, + 4, + 4, + 4, + 4, + 0, + 0, + 0, + 4, + 4, + 4, + 4, + 4, + 4, + 5, + 5, + 5, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 5, + 7, + 5, + 7, + 7, + 7, + 7, + 7, + 6, + 7, + 7, + 7, + 7, + 7, + 3, + 7, + 7, + 7, + 7, + 7, + 0, + 4, + 4, + 4, + 4 +]; +var ToVer3EyeColorTable = [ + 0, + 2, + 2, + 2, + 1, + 3, + 2, + 3, + 0, + 1, + 2, + 3, + 4, + 5, + 2, + 2, + 4, + 2, + 1, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 0, + 0, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 1, + 0, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 0, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 2, + 2, + 3, + 3, + 3, + 3, + 2, + 2, + 2, + 2, + 2, + 1, + 1, + 1, + 1, + 1, + 1 +]; +var ToVer3MouthColorTable = [ + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 3, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 1, + 4, + 4, + 4, + 0, + 1, + 2, + 3, + 4, + 4, + 2, + 3, + 3, + 4, + 4, + 4, + 4, + 1, + 4, + 4, + 2, + 3, + 3, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 3, + 3, + 3, + 4, + 4, + 4, + 3, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 4, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 3, + 3, + 3, + 3, + 3, + 3, + 4, + 4, + 3, + 3, + 3, + 3, + 3, + 3, + 4, + 3, + 3, + 3, + 3, + 3, + 4, + 0, + 3, + 3, + 3, + 3, + 4, + 3, + 3, + 3, + 3 +]; +var ToVer3GlassColorTable = [ + 0, + 1, + 1, + 1, + 5, + 1, + 1, + 4, + 0, + 5, + 1, + 1, + 3, + 5, + 1, + 2, + 3, + 4, + 5, + 4, + 2, + 2, + 4, + 4, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 0, + 0, + 0, + 5, + 5, + 5, + 5, + 5, + 5, + 0, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 1, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 5, + 5, + 5, + 5, + 5, + 5 +]; +var ToVer3FacelineColorTable = [0, 1, 2, 3, 4, 5, 0, 1, 5, 5]; +var Ver3FacelineColorTable = [0, 1, 2, 3, 4, 5]; +var Ver3HairColorTable = [8, 1, 2, 3, 4, 5, 6, 7]; +var Ver3EyeColorTable = [8, 9, 10, 11, 12, 13]; +var Ver3MouthColorTable = [19, 20, 21, 22, 23]; +var Ver3GlassColorTable = [8, 14, 15, 16, 17, 18, 0]; +var ForbiddenShirtPantColors = [, 7, 22, 78, 79, 84, 91, 92, 93, 94]; + +// src/class/struct/RFLStoreData.ts +var RFLCreateID = import_struct_fu2.default.struct([import_struct_fu2.default.uint8("data", 8)]); +var RFLCharData = import_struct_fu2.default.struct([ + import_struct_fu2.default.ubit("padding0", 1), + import_struct_fu2.default.ubit("gender", 1), + import_struct_fu2.default.ubit("birthMonth", 4), + import_struct_fu2.default.ubit("birthDay", 5), + import_struct_fu2.default.ubit("favoriteColor", 4), + import_struct_fu2.default.ubit("favorite", 1), + import_struct_fu2.default.char16be("name", 20), + import_struct_fu2.default.uint8("height"), + import_struct_fu2.default.uint8("build"), + import_struct_fu2.default.struct("create_id", [RFLCreateID]), + import_struct_fu2.default.ubit("faceType", 3), + import_struct_fu2.default.ubit("faceColor", 3), + import_struct_fu2.default.ubit("faceTex", 4), + import_struct_fu2.default.ubit("padding_2", 3), + import_struct_fu2.default.ubit("localonly", 1), + import_struct_fu2.default.ubit("type", 2), + import_struct_fu2.default.ubit("hairType", 7), + import_struct_fu2.default.ubit("hairColor", 3), + import_struct_fu2.default.ubit("hairFlip", 1), + import_struct_fu2.default.ubit("padding_3", 5), + import_struct_fu2.default.ubit("eyebrowType", 5), + import_struct_fu2.default.ubit("eyebrowRotate", 5), + import_struct_fu2.default.ubit("padding_4", 6), + import_struct_fu2.default.ubit("eyebrowColor", 3), + import_struct_fu2.default.ubit("eyebrowScale", 4), + import_struct_fu2.default.ubit("eyebrowY", 5), + import_struct_fu2.default.ubit("eyebrowX", 4), + import_struct_fu2.default.ubit("eyeType", 6), + import_struct_fu2.default.ubit("eyeRotate", 5), + import_struct_fu2.default.ubit("eyeY", 5), + import_struct_fu2.default.ubit("eyeColor", 3), + import_struct_fu2.default.ubit("eyeScale", 4), + import_struct_fu2.default.ubit("eyeX", 4), + import_struct_fu2.default.ubit("padding_5", 5), + import_struct_fu2.default.ubit("noseType", 4), + import_struct_fu2.default.ubit("noseScale", 4), + import_struct_fu2.default.ubit("noseY", 5), + import_struct_fu2.default.ubit("padding_6", 3), + import_struct_fu2.default.ubit("mouthType", 5), + import_struct_fu2.default.ubit("mouthColor", 2), + import_struct_fu2.default.ubit("mouthScale", 4), + import_struct_fu2.default.ubit("mouthY", 5), + import_struct_fu2.default.ubit("glassType", 4), + import_struct_fu2.default.ubit("glassColor", 3), + import_struct_fu2.default.ubit("glassScale", 4), + import_struct_fu2.default.ubit("glassY", 5), + import_struct_fu2.default.ubit("mustacheType", 2), + import_struct_fu2.default.ubit("beardType", 2), + import_struct_fu2.default.ubit("beardColor", 3), + import_struct_fu2.default.ubit("beardScale", 4), + import_struct_fu2.default.ubit("beardY", 5), + import_struct_fu2.default.ubit("moleType", 1), + import_struct_fu2.default.ubit("moleScale", 4), + import_struct_fu2.default.ubit("moleY", 5), + import_struct_fu2.default.ubit("moleX", 5), + import_struct_fu2.default.ubit("padding_8", 1), + import_struct_fu2.default.char16be("creatorName", 20) +]); +var RFLStoreData = import_struct_fu2.default.struct([ + import_struct_fu2.default.struct([RFLCharData]), + import_struct_fu2.default.uint16("checksum") +]); +var Ver1ToVer3FacelineTex = [ + [0, 0], + [1, 0], + [6, 0], + [9, 0], + [0, 5], + [0, 2], + [0, 3], + [0, 7], + [0, 8], + [10, 0], + [0, 9], + [0, 11] +]; +function RFLStoreDataToMiiCreatorV4Data(input) { + const output = EmptyMiiCreatorV4Data(); + console.log("input rfl data:", input); + output.beardColor = Ver3HairColorTable[input.beardColor]; + output.beardType = input.beardType; + output.birthDay = input.birthDay; + output.birthMonth = input.birthMonth; + output.build = input.build; + output.createId.set(RFLCreateID.pack(input.create_id), 0); + output.creator = input.creatorName; + output.eyeColor = Ver3EyeColorTable[input.eyeColor]; + output.eyeRotate = input.eyeRotate; + output.eyeScale = input.eyeScale; + output.eyeType = input.eyeType; + output.eyeX = input.eyeX; + output.eyeY = input.eyeY; + output.eyebrowColor = Ver3HairColorTable[input.eyebrowColor]; + output.eyebrowRotate = input.eyebrowRotate; + output.eyebrowScale = input.eyebrowScale; + output.eyebrowType = input.eyebrowType; + output.eyebrowX = input.eyebrowX; + output.eyebrowY = input.eyebrowY; + output.facelineColor = Ver3FacelineColorTable[input.faceColor]; + output.facelineType = input.faceType; + output.facelineMake = Ver1ToVer3FacelineTex[input.faceTex][0]; + output.facelineWrinkle = Ver1ToVer3FacelineTex[input.faceTex][1]; + output.favorite = input.favorite; + output.favoriteColor = input.favoriteColor; + output.gender = input.gender; + output.glassColor = Ver3GlassColorTable[input.glassColor]; + output.glassScale = input.glassScale; + output.glassType = input.glassType; + output.glassY = input.glassY; + output.hairColor = Ver3HairColorTable[input.hairColor]; + output.hairFlip = input.hairFlip; + output.hairType = input.hairType; + output.height = input.height; + output.moleScale = input.moleScale; + output.moleType = input.moleType; + output.moleX = input.moleX; + output.moleY = input.moleY; + output.mouthColor = Ver3MouthColorTable[input.mouthColor]; + output.mouthScale = input.mouthScale; + output.mouthType = input.mouthType; + output.mouthY = input.mouthY; + output.mustacheScale = input.beardScale; + output.mustacheType = input.mustacheType; + output.mustacheY = input.beardY; + output.noseScale = input.noseScale; + output.noseType = input.noseType; + output.noseY = input.noseY; + output.nickname = input.name; + output.creator = input.creatorName; + output.facePaintColor = -1; + output.hatCommonColor = -1; + output.hatFavoriteColor = -1; + output.hatType = -1; + output.wigType = -1; + output.pantsColor = -1; + output.personality = -1; + output.shirtColor = -1; + return output; +} + +// src/class/struct/MiiCreatorV4Data.ts +var MiiCreatorV4Data = import_struct_fu3.default.struct([ + import_struct_fu3.default.uint8("miicVersion"), + import_struct_fu3.default.uint8("originPlatform"), + import_struct_fu3.default.byte("authorId", 8), + import_struct_fu3.default.byte("createId", 10), + import_struct_fu3.default.char16le("creator", 20), + import_struct_fu3.default.char16le("nickname", 20), + import_struct_fu3.default.uint8("beardColor"), + import_struct_fu3.default.uint8("beardType"), + import_struct_fu3.default.uint8("birthDay"), + import_struct_fu3.default.uint8("birthMonth"), + import_struct_fu3.default.uint16("birthYear"), + import_struct_fu3.default.uint8("build"), + import_struct_fu3.default.uint8("eyeAspect"), + import_struct_fu3.default.uint8("eyebrowAspect"), + import_struct_fu3.default.uint8("eyebrowColor"), + import_struct_fu3.default.uint8("eyebrowRotate"), + import_struct_fu3.default.uint8("eyebrowScale"), + import_struct_fu3.default.uint8("eyebrowType"), + import_struct_fu3.default.uint8("eyebrowX"), + import_struct_fu3.default.uint8("eyebrowY"), + import_struct_fu3.default.uint8("eyeColor"), + import_struct_fu3.default.uint8("eyeRotate"), + import_struct_fu3.default.uint8("eyeScale"), + import_struct_fu3.default.uint8("eyeType"), + import_struct_fu3.default.uint8("eyeX"), + import_struct_fu3.default.uint8("eyeY"), + import_struct_fu3.default.uint8("facelineColor"), + import_struct_fu3.default.uint8("facelineMake"), + import_struct_fu3.default.uint8("facelineType"), + import_struct_fu3.default.uint8("facelineWrinkle"), + import_struct_fu3.default.uint8("facePaintColor"), + import_struct_fu3.default.uint8("favorite"), + import_struct_fu3.default.uint8("favoriteColor"), + import_struct_fu3.default.uint8("fontRegion"), + import_struct_fu3.default.uint8("gender"), + import_struct_fu3.default.uint8("glassColor"), + import_struct_fu3.default.uint8("glassScale"), + import_struct_fu3.default.uint8("glassType"), + import_struct_fu3.default.uint8("glassY"), + import_struct_fu3.default.uint8("hairColor"), + import_struct_fu3.default.uint8("hairFlip"), + import_struct_fu3.default.uint8("hairType"), + import_struct_fu3.default.uint8("hatFavoriteColor"), + import_struct_fu3.default.uint8("hatCommonColor"), + import_struct_fu3.default.uint8("hatType"), + import_struct_fu3.default.uint8("height"), + import_struct_fu3.default.uint8("wigType"), + import_struct_fu3.default.uint8("moleScale"), + import_struct_fu3.default.uint8("moleType"), + import_struct_fu3.default.uint8("moleX"), + import_struct_fu3.default.uint8("moleY"), + import_struct_fu3.default.uint8("mouthAspect"), + import_struct_fu3.default.uint8("mouthColor"), + import_struct_fu3.default.uint8("mouthScale"), + import_struct_fu3.default.uint8("mouthType"), + import_struct_fu3.default.uint8("mouthY"), + import_struct_fu3.default.uint8("mustacheScale"), + import_struct_fu3.default.uint8("mustacheType"), + import_struct_fu3.default.uint8("mustacheY"), + import_struct_fu3.default.uint8("noseScale"), + import_struct_fu3.default.uint8("noseType"), + import_struct_fu3.default.uint8("noseY"), + import_struct_fu3.default.uint8("pantsColor"), + import_struct_fu3.default.uint8("personality"), + import_struct_fu3.default.uint8("regionMove"), + import_struct_fu3.default.uint8("shirtColor"), + import_struct_fu3.default.uint8("special"), + import_struct_fu3.default.uint8("temporary"), + import_struct_fu3.default.uint8("eyeSclera"), + import_struct_fu3.default.uint8("clothesType"), + import_struct_fu3.default.uint8("shoesColor") +]); +var MiiCreatorV4AppendData = import_struct_fu3.default.struct([ + import_struct_fu3.default.uint8("miicVersion"), + import_struct_fu3.default.uint8("eyebrowColor"), + import_struct_fu3.default.uint8("eyeColor"), + import_struct_fu3.default.uint8("facelineColor"), + import_struct_fu3.default.uint8("glassColor"), + import_struct_fu3.default.uint8("glassType"), + import_struct_fu3.default.uint8("hairColor"), + import_struct_fu3.default.uint8("mouthColor"), + import_struct_fu3.default.uint8("hatType"), + import_struct_fu3.default.uint8("facePaintColor"), + import_struct_fu3.default.uint8("hatCommonColor"), + import_struct_fu3.default.uint8("hatFavoriteColor"), + import_struct_fu3.default.uint8("pantsColor"), + import_struct_fu3.default.uint8("personality"), + import_struct_fu3.default.uint8("shirtColor"), + import_struct_fu3.default.uint8("birthYear"), + import_struct_fu3.default.uint8("wigType"), + import_struct_fu3.default.uint8("originPlatform"), + import_struct_fu3.default.uint8("eyeSclera"), + import_struct_fu3.default.uint8("clothesType"), + import_struct_fu3.default.uint8("shoesColor") +]); +var EmptyMiiCreatorData = { + miicVersion: 4, + originPlatform: 5 /* Mii_Creator_v4 */, + authorId: new Uint8Array(8), + createId: new Uint8Array(10), + creator: "???", + nickname: "MISSING", + beardColor: 0, + beardType: 0, + birthDay: 0, + birthMonth: 0, + birthYear: 0, + build: 0, + eyebrowAspect: 3, + eyebrowColor: 0, + eyebrowRotate: 0, + eyebrowScale: 0, + eyebrowType: 0, + eyebrowX: 0, + eyebrowY: 0, + eyeAspect: 3, + eyeColor: 0, + eyeRotate: 0, + eyeScale: 0, + eyeType: 0, + eyeX: 0, + eyeY: 0, + facelineColor: 0, + facelineMake: 0, + facelineType: 0, + facelineWrinkle: 0, + facePaintColor: -1, + favorite: 0, + favoriteColor: 0, + fontRegion: 0, + gender: 0, + glassColor: 0, + glassScale: 0, + glassType: 0, + glassY: 0, + hairColor: 0, + hairFlip: 0, + hairType: 0, + hatFavoriteColor: -1, + hatCommonColor: -1, + hatType: -1, + height: 0, + wigType: -1, + moleScale: 0, + moleType: 0, + moleX: 0, + moleY: 0, + mouthAspect: 3, + mouthColor: 0, + mouthScale: 0, + mouthType: 0, + mouthY: 0, + mustacheScale: 0, + mustacheType: 0, + mustacheY: 0, + noseScale: 0, + noseType: 0, + noseY: 0, + pantsColor: -1, + personality: -1, + regionMove: 0, + shirtColor: -1, + special: 0, + temporary: 0, + eyeSclera: 0, + clothesType: -1, + shoesColor: -1 +}; +var EmptyMiiCreatorV4Data = () => ({ ...EmptyMiiCreatorData }); +function MiiCreatorV4DataToFFSD(input, pack = false, appendBytes = false) { + const output = { + author_id: FFLiAuthorID.unpack(input.authorId), + author_type: 0, + beard_color: ToVer3HairColorTable[input.beardColor], + beard_scale: input.mustacheScale, + beard_type: input.beardType, + beard_y: input.mustacheY, + birth_day: input.birthDay, + birth_month: input.birthMonth, + birth_platform: Math.max(2, Math.min(input.originPlatform, 3 /* FFL_Wii_U */)), + build: input.build, + checksum: 0, + copyable: 1, + create_id: FFLiCreateID.unpack(input.createId), + creator: input.creator, + eye_aspect: input.eyeAspect, + eye_color: ToVer3EyeColorTable[input.eyeColor], + eye_rotate: input.eyeRotate, + eye_scale: input.eyeScale, + eye_type: input.eyeType, + eye_x: input.eyeX, + eye_y: input.eyeY, + eyebrow_aspect: input.eyebrowAspect, + eyebrow_color: ToVer3HairColorTable[input.eyebrowColor], + eyebrow_rotate: input.eyebrowRotate, + eyebrow_scale: input.eyebrowScale, + eyebrow_type: input.eyebrowType, + eyebrow_x: input.eyebrowX, + eyebrow_y: input.eyebrowY, + face_color: ToVer3FacelineColorTable[input.facelineColor], + face_make: input.facelineMake, + face_tex: input.facelineWrinkle, + face_type: input.facelineType, + favorite: input.favorite, + favorite_color: input.favoriteColor, + font_region: input.fontRegion, + gender: input.gender, + glass_y: input.glassY, + glasses_color: ToVer3GlassColorTable[input.glassColor], + glasses_scale: input.glassScale, + glasses_type: ToVer3GlassTypeTable[input.glassType], + hair_color: ToVer3HairColorTable[input.hairColor], + hair_flip: input.hairFlip, + hair_type: input.hairType, + height: input.height, + localonly: 0, + mii_version: 3 /* FFL_Wii_U */, + mole_scale: input.moleScale, + mole_type: input.moleType, + mole_x: input.moleX, + mole_y: input.moleY, + mouth_aspect: input.mouthAspect, + mouth_color: ToVer3MouthColorTable[input.mouthColor], + mouth_scale: input.mouthScale, + mouth_type: input.mouthType, + mouth_y: input.mouthY, + mustache_type: input.mustacheType, + name: input.nickname, + ng_word: 0, + nose_scale: input.noseScale, + nose_type: input.noseType, + nose_y: input.noseY, + position_in_room: 0, + room_index: 0, + region_move: 0 + }; + output.create_id.flag_normal = Number(!input.special); + output.checksum = calculateCRC16(Ver3StoreData.pack(output)); + if (pack) { + if (appendBytes) { + const ffsdOutput = Ver3StoreData.pack(output); + const appendedBytes = MiiCreatorV4AppendData.pack(input); + const finalArray = new Uint8Array(ffsdOutput.length + appendedBytes.length); + finalArray.set(ffsdOutput, 0); + finalArray.set(appendedBytes, ffsdOutput.length); + return finalArray; + } + return Ver3StoreData.pack(output); + } else + return output; +} +var validationThing = { + beardColor: { type: 0 /* Number */, default: 0, min: 0, max: 99 }, + beardType: { type: 0 /* Number */, default: 0, min: 0, max: 5 }, + build: { type: 0 /* Number */, default: 64, min: 0, max: 127 }, + eyeAspect: { type: 0 /* Number */, default: 3, min: 0, max: 6 }, + eyeColor: { type: 0 /* Number */, default: 8, min: 0, max: 99 }, + eyeRotate: { type: 0 /* Number */, default: 4, min: 0, max: 7 }, + eyeScale: { type: 0 /* Number */, default: 4, min: 0, max: 7 }, + eyeSclera: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + eyeType: { type: 0 /* Number */, default: 2, min: 0, max: 59 }, + eyeX: { type: 0 /* Number */, default: 2, min: 0, max: 12 }, + eyeY: { type: 0 /* Number */, default: 12, min: 0, max: 18 }, + eyebrowAspect: { type: 0 /* Number */, default: 3, min: 0, max: 6 }, + eyebrowColor: { type: 0 /* Number */, default: 1, min: 0, max: 99 }, + eyebrowRotate: { type: 0 /* Number */, default: 6, min: 0, max: 11 }, + eyebrowScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + eyebrowType: { type: 0 /* Number */, default: 6, min: 0, max: 24 }, + eyebrowX: { type: 0 /* Number */, default: 2, min: 0, max: 12 }, + eyebrowY: { type: 0 /* Number */, default: 10, min: 3, max: 18 }, + facelineColor: { type: 0 /* Number */, default: 0, min: 0, max: 9 }, + facelineMake: { type: 0 /* Number */, default: 0, min: 0, max: 11 }, + facelineType: { type: 0 /* Number */, default: 0, min: 0, max: 11 }, + facelineWrinkle: { type: 0 /* Number */, default: 0, min: 0, max: 11 }, + favoriteColor: { type: 0 /* Number */, default: 0, min: 0, max: 11 }, + fontRegion: { type: 0 /* Number */, default: 0, min: 0, max: 3 }, + gender: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + glassColor: { type: 0 /* Number */, default: 8, min: 0, max: 99 }, + glassScale: { type: 0 /* Number */, default: 4, min: 0, max: 7 }, + glassType: { type: 0 /* Number */, default: 0, min: 0, max: 19 }, + glassY: { type: 0 /* Number */, default: 10, min: 0, max: 20 }, + hairColor: { type: 0 /* Number */, default: 1, min: 0, max: 99 }, + hairFlip: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + hairType: { type: 0 /* Number */, default: 33, min: 0, max: 131 }, + height: { type: 0 /* Number */, default: 64, min: 0, max: 127 }, + miicVersion: { type: 0 /* Number */, default: 4, min: 0, max: 4 }, + moleScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + moleType: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + moleX: { type: 0 /* Number */, default: 2, min: 0, max: 16 }, + moleY: { type: 0 /* Number */, default: 20, min: 0, max: 30 }, + mouthAspect: { type: 0 /* Number */, default: 3, min: 0, max: 6 }, + mouthColor: { type: 0 /* Number */, default: 19, min: 0, max: 99 }, + mouthScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + mouthType: { type: 0 /* Number */, default: 23, min: 0, max: 35 }, + mouthY: { type: 0 /* Number */, default: 13, min: 0, max: 18 }, + mustacheScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + mustacheType: { type: 0 /* Number */, default: 0, min: 0, max: 5 }, + mustacheY: { type: 0 /* Number */, default: 10, min: 0, max: 16 }, + creator: { type: 1 /* String */, default: "", min: 0, max: 10 }, + nickname: { type: 1 /* String */, default: "Mii", min: 1, max: 10 }, + noseScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + noseType: { type: 0 /* Number */, default: 1, min: 0, max: 17 }, + noseY: { type: 0 /* Number */, default: 9, min: 0, max: 18 }, + regionMove: { type: 0 /* Number */, default: 0, min: 0, max: 3 }, + authorId: { + type: 2 /* Array */, + default: [0, 0, 0, 0, 0, 0, 0, 0], + size: 8, + min: 0, + max: 255 + }, + birthDay: { type: 0 /* Number */, default: 0, min: 0, max: 31 }, + birthMonth: { type: 0 /* Number */, default: 0, min: 0, max: 12 }, + birthYear: { type: 0 /* Number */, default: 0, min: 0, max: 9999 }, + createId: { + type: 2 /* Array */, + default: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + size: 10, + min: 0, + max: 255 + }, + facePaintColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + favorite: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + hatCommonColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + hatFavoriteColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + hatType: { type: 0 /* Number */, default: -1, min: -1, max: 9 }, + wigType: { type: 0 /* Number */, default: -1, min: -1, max: 254 }, + clothesType: { type: 0 /* Number */, default: -1, min: -1, max: 254 }, + shoesColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + originPlatform: { + type: 0 /* Number */, + default: 5 /* Mii_Creator_v4 */, + min: 0, + max: 6 /* Origin_Platform_Max */ + }, + pantsColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + personality: { type: 0 /* Number */, default: -1, min: -1, max: 255 }, + shirtColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + special: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + temporary: { type: 0 /* Number */, default: 0, min: 0, max: 1 } +}; +function validate(input) { + let valid = true, reasons = []; + Object.keys(input).forEach((i) => { + function fail2(reason = i) { + valid = false; + reasons.push(reason); + } + const prop = validationThing[i]; + if (!prop) { + alert("A prop is missing: " + i); + return; + } + }); + if (valid) + reasons.push("Valid"); + return { valid, reasons }; +} + +// src/class/struct/MiiCreatorV3Data.ts +var MiiCreatorV3Data = import_struct_fu4.default.struct([ + import_struct_fu4.default.struct([Ver3StoreData]), + import_struct_fu4.default.uint8("ext_faceline_color"), + import_struct_fu4.default.uint8("ext_hair_color"), + import_struct_fu4.default.uint8("ext_eye_color"), + import_struct_fu4.default.uint8("ext_eyebrow_color"), + import_struct_fu4.default.uint8("ext_mouth_color"), + import_struct_fu4.default.uint8("ext_beard_color"), + import_struct_fu4.default.uint8("ext_glass_color"), + import_struct_fu4.default.uint8("ext_glass_type"), + import_struct_fu4.default.uint8("ext_hat_type"), + import_struct_fu4.default.uint8("ext_hat_color"), + import_struct_fu4.default.uint8("ext_face_paint_color"), + import_struct_fu4.default.uint8("ext_shirt_color") +]); +function MiiCreatorV3DataToMiiCreatorV4Data(input) { + const data2 = EmptyMiiCreatorV4Data(); + switch (input.birth_platform) { + case 0: + data2.originPlatform = 0 /* RFL_Wii */; + break; + case 1: + data2.originPlatform = 1 /* NFL_DS */; + break; + case 2: + data2.originPlatform = 2 /* CFL_3DS */; + break; + case 3: + data2.originPlatform = 3 /* FFL_Wii_U */; + break; + } + if (input.ext_beard_color || input.ext_eye_color || input.ext_eyebrow_color || input.ext_face_paint_color || input.ext_faceline_color || input.ext_glass_color || input.ext_glass_type || input.ext_hair_color || input.ext_hat_color || input.ext_hat_type || input.ext_mouth_color || input.ext_shirt_color) { + data2.originPlatform = 5 /* Mii_Creator_v3 */; + } + data2.authorId = input.author_id.data; + data2.beardColor = input.ext_beard_color || Ver3HairColorTable[input.beard_color]; + data2.beardType = input.beard_type; + data2.birthDay = input.birth_day; + data2.birthMonth = input.birth_month; + data2.build = input.build; + data2.createId = FFLiCreateID.pack(input.create_id); + data2.creator = input.creator; + data2.eyeAspect = input.eye_aspect; + data2.eyebrowAspect = input.eyebrow_aspect; + data2.eyebrowColor = input.ext_eyebrow_color || Ver3HairColorTable[input.eyebrow_color]; + data2.eyebrowRotate = input.eyebrow_rotate; + data2.eyebrowScale = input.eyebrow_scale; + data2.eyebrowType = input.eyebrow_type; + data2.eyebrowX = input.eyebrow_x; + data2.eyebrowY = input.eyebrow_y; + data2.eyeColor = input.ext_eye_color || Ver3EyeColorTable[input.eye_color]; + data2.eyeRotate = input.eye_rotate; + data2.eyeScale = input.eye_scale; + data2.eyeType = input.eye_type; + data2.eyeX = input.eye_x; + data2.eyeY = input.eye_y; + data2.facelineColor = input.face_color; + data2.facelineMake = input.face_make; + data2.facelineType = input.face_type; + data2.facelineWrinkle = input.face_tex; + data2.facePaintColor = input.ext_face_paint_color - 1 || -1; + data2.favorite = input.favorite; + data2.favoriteColor = input.favorite_color; + data2.fontRegion = input.font_region; + data2.gender = input.gender; + data2.glassColor = input.ext_glass_color || Ver3GlassColorTable[input.glasses_color]; + data2.glassScale = input.glasses_scale; + data2.glassType = input.ext_glass_type || input.glasses_type; + data2.glassY = input.glass_y; + data2.hairColor = input.ext_hair_color || Ver3HairColorTable[input.hair_color]; + data2.hairFlip = input.hair_flip; + data2.hairType = input.hair_type; + data2.hatFavoriteColor = input.ext_hat_color !== 0 ? input.ext_hat_color - 1 : -1; + data2.hatType = input.ext_hat_type !== 0 ? input.ext_hat_type - 1 : -1; + data2.height = input.height; + data2.moleScale = input.mole_scale; + data2.moleType = input.mole_type; + data2.moleX = input.mole_x; + data2.moleY = input.mole_y; + data2.mouthAspect = input.mouth_aspect; + data2.mouthColor = input.ext_mouth_color || Ver3MouthColorTable[input.mouth_color]; + data2.mouthScale = input.mouth_scale; + data2.mouthType = input.mouth_type; + data2.mouthY = input.mouth_y; + data2.mustacheScale = input.beard_scale; + data2.mustacheType = input.mustache_type; + data2.mustacheY = input.beard_y; + data2.nickname = input.name; + data2.noseScale = input.nose_scale; + data2.noseType = input.nose_type; + data2.noseY = input.nose_y; + data2.regionMove = input.region_move; + if (input.create_id.flag_temporary !== 0) + data2.special = Number(!input.create_id.flag_normal); + data2.temporary = Number(input.create_id.flag_temporary); + return data2; +} + +// src/class/struct/NnMiiCharInfo.ts +var import_struct_fu5 = __toESM(require_struct_fu(), 1); +var NnMiiCharInfo = import_struct_fu5.default.struct([ + import_struct_fu5.default.byte("createId", 16), + import_struct_fu5.default.char16le("nickname", 22), + import_struct_fu5.default.uint8("fontRegion"), + import_struct_fu5.default.uint8("favoriteColor"), + import_struct_fu5.default.uint8("gender"), + import_struct_fu5.default.uint8("height"), + import_struct_fu5.default.uint8("build"), + import_struct_fu5.default.uint8("type"), + import_struct_fu5.default.uint8("regionMove"), + import_struct_fu5.default.uint8("facelineType"), + import_struct_fu5.default.uint8("facelineColor"), + import_struct_fu5.default.uint8("facelineWrinkle"), + import_struct_fu5.default.uint8("facelineMake"), + import_struct_fu5.default.uint8("hairType"), + import_struct_fu5.default.uint8("hairColor"), + import_struct_fu5.default.uint8("hairFlip"), + import_struct_fu5.default.uint8("eyeType"), + import_struct_fu5.default.uint8("eyeColor"), + import_struct_fu5.default.uint8("eyeScale"), + import_struct_fu5.default.uint8("eyeAspect"), + import_struct_fu5.default.uint8("eyeRotate"), + import_struct_fu5.default.uint8("eyeX"), + import_struct_fu5.default.uint8("eyeY"), + import_struct_fu5.default.uint8("eyebrowType"), + import_struct_fu5.default.uint8("eyebrowColor"), + import_struct_fu5.default.uint8("eyebrowScale"), + import_struct_fu5.default.uint8("eyebrowAspect"), + import_struct_fu5.default.uint8("eyebrowRotate"), + import_struct_fu5.default.uint8("eyebrowX"), + import_struct_fu5.default.uint8("eyebrowY"), + import_struct_fu5.default.uint8("noseType"), + import_struct_fu5.default.uint8("noseScale"), + import_struct_fu5.default.uint8("noseY"), + import_struct_fu5.default.uint8("mouthType"), + import_struct_fu5.default.uint8("mouthColor"), + import_struct_fu5.default.uint8("mouthScale"), + import_struct_fu5.default.uint8("mouthAspect"), + import_struct_fu5.default.uint8("mouthY"), + import_struct_fu5.default.uint8("beardColor"), + import_struct_fu5.default.uint8("beardType"), + import_struct_fu5.default.uint8("mustacheType"), + import_struct_fu5.default.uint8("mustacheScale"), + import_struct_fu5.default.uint8("mustacheY"), + import_struct_fu5.default.uint8("glassType"), + import_struct_fu5.default.uint8("glassColor"), + import_struct_fu5.default.uint8("glassScale"), + import_struct_fu5.default.uint8("glassY"), + import_struct_fu5.default.uint8("moleType"), + import_struct_fu5.default.uint8("moleScale"), + import_struct_fu5.default.uint8("moleX"), + import_struct_fu5.default.uint8("moleY"), + import_struct_fu5.default.uint8("reserved") +]); + +// src/class/struct/StudioData.ts +var import_struct_fu6 = __toESM(require_struct_fu(), 1); +var StudioData = import_struct_fu6.default.struct([ + import_struct_fu6.default.uint8("beardColor"), + import_struct_fu6.default.uint8("beardType"), + import_struct_fu6.default.uint8("build"), + import_struct_fu6.default.uint8("eyeAspect"), + import_struct_fu6.default.uint8("eyeColor"), + import_struct_fu6.default.uint8("eyeRotate"), + import_struct_fu6.default.uint8("eyeScale"), + import_struct_fu6.default.uint8("eyeType"), + import_struct_fu6.default.uint8("eyeX"), + import_struct_fu6.default.uint8("eyeY"), + import_struct_fu6.default.uint8("eyebrowAspect"), + import_struct_fu6.default.uint8("eyebrowColor"), + import_struct_fu6.default.uint8("eyebrowRotate"), + import_struct_fu6.default.uint8("eyebrowScale"), + import_struct_fu6.default.uint8("eyebrowType"), + import_struct_fu6.default.uint8("eyebrowX"), + import_struct_fu6.default.uint8("eyebrowY"), + import_struct_fu6.default.uint8("facelineColor"), + import_struct_fu6.default.uint8("facelineMake"), + import_struct_fu6.default.uint8("facelineType"), + import_struct_fu6.default.uint8("facelineWrinkle"), + import_struct_fu6.default.uint8("favoriteColor"), + import_struct_fu6.default.uint8("gender"), + import_struct_fu6.default.uint8("glassColor"), + import_struct_fu6.default.uint8("glassScale"), + import_struct_fu6.default.uint8("glassType"), + import_struct_fu6.default.uint8("glassY"), + import_struct_fu6.default.uint8("hairColor"), + import_struct_fu6.default.uint8("hairFlip"), + import_struct_fu6.default.uint8("hairType"), + import_struct_fu6.default.uint8("height"), + import_struct_fu6.default.uint8("moleScale"), + import_struct_fu6.default.uint8("moleType"), + import_struct_fu6.default.uint8("moleX"), + import_struct_fu6.default.uint8("moleY"), + import_struct_fu6.default.uint8("mouthAspect"), + import_struct_fu6.default.uint8("mouthColor"), + import_struct_fu6.default.uint8("mouthScale"), + import_struct_fu6.default.uint8("mouthType"), + import_struct_fu6.default.uint8("mouthY"), + import_struct_fu6.default.uint8("mustacheScale"), + import_struct_fu6.default.uint8("mustacheType"), + import_struct_fu6.default.uint8("mustacheY"), + import_struct_fu6.default.uint8("noseScale"), + import_struct_fu6.default.uint8("noseType"), + import_struct_fu6.default.uint8("noseY") +]); + +// node_modules/gettext.js/lib/gettext.js +/*! gettext.js - Guillaume Potier - MIT Licensed */ +var i18n = function(options) { + options = options || {}; + this && (this.__version = "2.0.0"); + var defaults2 = { + domain: "messages", + locale: (typeof document !== "undefined" ? document.documentElement.getAttribute("lang") : false) || "en", + plural_func: function(n2) { + return { nplurals: 2, plural: n2 != 1 ? 1 : 0 }; + }, + ctxt_delimiter: String.fromCharCode(4) + }; + var _8 = { + isObject: function(obj) { + var type = typeof obj; + return type === "function" || type === "object" && !!obj; + }, + isArray: function(obj) { + return toString.call(obj) === "[object Array]"; + } + }; + var _plural_funcs = {}, _locale = options.locale || defaults2.locale, _domain = options.domain || defaults2.domain, _dictionary = {}, _plural_forms = {}, _ctxt_delimiter = options.ctxt_delimiter || defaults2.ctxt_delimiter; + if (options.messages) { + _dictionary[_domain] = {}; + _dictionary[_domain][_locale] = options.messages; + } + if (options.plural_forms) { + _plural_forms[_locale] = options.plural_forms; + } + var strfmt = function(fmt) { + var args = arguments; + return fmt.replace(/%%/g, "%% ").replace(/%(\d+)/g, function(str, p1) { + return args[p1]; + }).replace(/%% /g, "%"); + }; + var removeContext = function(str) { + if (str.indexOf(_ctxt_delimiter) !== -1) { + var parts = str.split(_ctxt_delimiter); + return parts[1]; + } + return str; + }; + var expand_locale = function(locale) { + var locales = [locale], i = locale.lastIndexOf("-"); + while (i > 0) { + locale = locale.slice(0, i); + locales.push(locale); + i = locale.lastIndexOf("-"); + } + return locales; + }; + var normalizeLocale = function(locale) { + locale = locale.replace("_", "-"); + var i = locale.search(/[.@]/); + if (i != -1) + locale = locale.slice(0, i); + return locale; + }; + var getPluralFunc = function(plural_form) { + var pf_re = new RegExp("^\\s*nplurals\\s*=\\s*[0-9]+\\s*;\\s*plural\\s*=\\s*(?:\\s|[-\\?\\|&=!<>+*/%:;n0-9_()])+"); + var match = plural_form.match(pf_re); + if (!match || match[0] !== plural_form) + throw new Error(strfmt('The plural form "%1" is not valid', plural_form)); + return new Function("n", "var plural, nplurals; " + plural_form + " return { nplurals: nplurals, plural: (plural === true ? 1 : (plural ? plural : 0)) };"); + }; + var t3 = function(messages, n2, options2) { + if (!options2.plural_form) + return strfmt.apply(this, [removeContext(messages[0])].concat(Array.prototype.slice.call(arguments, 3))); + var plural; + if (options2.plural_func) { + plural = options2.plural_func(n2); + } else if (!_plural_funcs[_locale]) { + _plural_funcs[_locale] = getPluralFunc(_plural_forms[_locale]); + plural = _plural_funcs[_locale](n2); + } else { + plural = _plural_funcs[_locale](n2); + } + if (typeof plural.plural === "undefined" || plural.plural > plural.nplurals || messages.length <= plural.plural) + plural.plural = 0; + return strfmt.apply(this, [removeContext(messages[plural.plural])].concat(Array.prototype.slice.call(arguments, 3))); + }; + return { + strfmt, + expand_locale, + __: function() { + return this.gettext.apply(this, arguments); + }, + _n: function() { + return this.ngettext.apply(this, arguments); + }, + _p: function() { + return this.pgettext.apply(this, arguments); + }, + setMessages: function(domain, locale, messages, plural_forms) { + if (!domain || !locale || !messages) + throw new Error("You must provide a domain, a locale and messages"); + if (typeof domain !== "string" || typeof locale !== "string" || !_8.isObject(messages)) + throw new Error("Invalid arguments"); + locale = normalizeLocale(locale); + if (plural_forms) + _plural_forms[locale] = plural_forms; + if (!_dictionary[domain]) + _dictionary[domain] = {}; + _dictionary[domain][locale] = messages; + return this; + }, + loadJSON: function(jsonData, domain) { + if (!_8.isObject(jsonData)) + jsonData = JSON.parse(jsonData); + if (!jsonData[""] || !jsonData[""]["language"] || !jsonData[""]["plural-forms"]) + throw new Error('Wrong JSON, it must have an empty key ("") with "language" and "plural-forms" information'); + var headers = jsonData[""]; + delete jsonData[""]; + return this.setMessages(domain || defaults2.domain, headers["language"], jsonData, headers["plural-forms"]); + }, + setLocale: function(locale) { + _locale = normalizeLocale(locale); + return this; + }, + getLocale: function() { + return _locale; + }, + textdomain: function(domain) { + if (!domain) + return _domain; + _domain = domain; + return this; + }, + gettext: function(msgid) { + return this.dcnpgettext.apply(this, [undefined, undefined, msgid, undefined, undefined].concat(Array.prototype.slice.call(arguments, 1))); + }, + ngettext: function(msgid, msgid_plural, n2) { + return this.dcnpgettext.apply(this, [undefined, undefined, msgid, msgid_plural, n2].concat(Array.prototype.slice.call(arguments, 3))); + }, + pgettext: function(msgctxt, msgid) { + return this.dcnpgettext.apply(this, [undefined, msgctxt, msgid, undefined, undefined].concat(Array.prototype.slice.call(arguments, 2))); + }, + dcnpgettext: function(domain, msgctxt, msgid, msgid_plural, n2) { + domain = domain || _domain; + if (typeof msgid !== "string") + throw new Error(this.strfmt('Msgid "%1" is not a valid translatable string', msgid)); + var translation, options2 = { plural_form: false }, key2 = msgctxt ? msgctxt + _ctxt_delimiter + msgid : msgid, exist, locale, locales = expand_locale(_locale); + for (var i in locales) { + locale = locales[i]; + exist = _dictionary[domain] && _dictionary[domain][locale] && _dictionary[domain][locale][key2]; + if (msgid_plural) { + exist = exist && typeof _dictionary[domain][locale][key2] !== "string"; + } else { + exist = exist && typeof _dictionary[domain][locale][key2] === "string"; + } + if (exist) { + break; + } + } + if (!exist) { + translation = msgid; + options2.plural_func = defaults2.plural_func; + } else { + translation = _dictionary[domain][locale][key2]; + } + if (!msgid_plural) + return t3.apply(this, [[translation], n2, options2].concat(Array.prototype.slice.call(arguments, 5))); + options2.plural_form = true; + return t3.apply(this, [exist ? translation : [msgid, msgid_plural], n2, options2].concat(Array.prototype.slice.call(arguments, 5))); + } + }; +}; +var gettext_default = i18n; + +// src/util/Lang.ts +var localization = gettext_default(); +var _8 = () => localization.gettext.bind(localization); + +// src/class/MiiData.ts +var __ = _8(); + +class Mii { + miicVersion; + originPlatform; + authorId; + createId; + creator; + nickname; + beardColor; + beardType; + birthDay; + birthMonth; + birthYear; + build; + clothesType; + eyeAspect; + eyebrowAspect; + eyebrowColor; + eyebrowRotate; + eyebrowScale; + eyebrowType; + eyebrowX; + eyebrowY; + eyeColor; + eyeRotate; + eyeScale; + eyeSclera; + eyeType; + eyeX; + eyeY; + facelineColor; + facelineMake; + facelineType; + facelineWrinkle; + facePaintColor; + favorite; + favoriteColor; + fontRegion; + gender; + glassColor; + glassScale; + glassType; + glassY; + hairColor; + hairFlip; + hairType; + hatCommonColor; + hatFavoriteColor; + hatType; + height; + wigType; + moleScale; + moleType; + moleX; + moleY; + mouthAspect; + mouthColor; + mouthScale; + mouthType; + mouthY; + mustacheScale; + mustacheType; + mustacheY; + temporary; + noseScale; + noseType; + noseY; + pantsColor; + personality; + regionMove; + shirtColor; + shoesColor; + special; + valid; + constructor(initData) { + let importData; + if (typeof initData === "string") + importData = parseHexOrB64ToUint8Array(initData); + else + importData = initData; + this.import(Mii.parseData(importData)); + } + static parseData(input) { + let data2 = EmptyMiiCreatorV4Data(); + let tempArray; + switch (input.length) { + case 46: + case 47: + tempArray = allocateArray(48, input); + data2 = { ...EmptyMiiCreatorV4Data(), ...StudioData.unpack(tempArray) }; + data2.originPlatform = 5 /* Mii_Creator_v4 */; + data2.nickname = "Mii"; + data2.creator = ""; + break; + case 74: + case 76: + tempArray = allocateArray(96, input); + data2 = RFLStoreDataToMiiCreatorV4Data(RFLStoreData.unpack(tempArray)); + break; + case 87: + case 88: + tempArray = allocateArray(88, input); + const d = NnMiiCharInfo.unpack(tempArray); + var tmpCreateId = new Uint8Array(10); + tmpCreateId.set(d.createId.slice(0, 10), 0); + d.createId = tmpCreateId; + data2 = { ...data2, ...d }; + data2.createId.set(d.createId.slice(0, 10), 0); + data2.authorId.set(d.createId.slice(10), 0); + data2.creator = ""; + data2.originPlatform = 4 /* nn_mii_Switch */; + break; + case 92: + case 96: + tempArray = allocateArray(108, input); + data2 = MiiCreatorV3DataToMiiCreatorV4Data(MiiCreatorV3Data.unpack(MiiCreatorV3Data.pack(Ver3StoreData.unpack(tempArray)))); + break; + case 104: + case 106: + case 108: + tempArray = allocateArray(108, input); + data2 = MiiCreatorV3DataToMiiCreatorV4Data(MiiCreatorV3Data.unpack(tempArray)); + break; + case 114: + tempArray = allocateArray(123, input); + data2 = MiiCreatorV3DataToMiiCreatorV4Data(MiiCreatorV3Data.unpack(MiiCreatorV3Data.pack(Ver3StoreData.unpack(tempArray)))); + break; + case 122: + case 123: + case 124: + case 125: + case 126: + tempArray = allocateArray(126, input); + data2 = MiiCreatorV4Data.unpack(tempArray); + if (input.length < 126) { + data2.shoesColor = -1; + } + if (input.length < 125) { + data2.clothesType = -1; + } + break; + default: + throw new Error(__("Mii data type not supported (%1 bytes)", input.length)); + } + if (data2.facePaintColor === 255) + data2.facePaintColor = -1; + if (data2.hatCommonColor === 255) + data2.hatCommonColor = -1; + if (data2.hatFavoriteColor === 255) + data2.hatFavoriteColor = -1; + if (data2.hatType === 255) + data2.hatType = -1; + if (data2.pantsColor === 255) + data2.pantsColor = -1; + if (data2.personality === 255) + data2.personality = -1; + if (data2.shirtColor === 255) + data2.shirtColor = -1; + if (data2.wigType === 255) + data2.wigType = -1; + if (data2.clothesType === 255) + data2.clothesType = -1; + if (data2.shoesColor === 255) + data2.shoesColor = -1; + return data2; + } + static parseDataBinary(input) { + const data2 = Mii.parseData(input); + return MiiCreatorV4Data.pack(data2); + } + #getObject(override = null) { + return { + miicVersion: this.miicVersion, + originPlatform: this.originPlatform, + authorId: this.authorId, + createId: this.createId, + creator: this.creator, + nickname: this.nickname, + beardColor: this.beardColor, + beardType: this.beardType, + birthDay: this.birthDay, + birthMonth: this.birthMonth, + birthYear: this.birthYear, + build: this.build, + clothesType: this.clothesType, + eyeAspect: this.eyeAspect, + eyebrowAspect: this.eyebrowAspect, + eyebrowColor: this.eyebrowColor, + eyebrowRotate: this.eyebrowRotate, + eyebrowScale: this.eyebrowScale, + eyebrowType: this.eyebrowType, + eyebrowX: this.eyebrowX, + eyebrowY: this.eyebrowY, + eyeColor: this.eyeColor, + eyeRotate: this.eyeRotate, + eyeScale: this.eyeScale, + eyeSclera: this.eyeSclera, + eyeType: this.eyeType, + eyeX: this.eyeX, + eyeY: this.eyeY, + facelineColor: this.facelineColor, + facelineMake: this.facelineMake, + facelineType: this.facelineType, + facelineWrinkle: this.facelineWrinkle, + facePaintColor: this.facePaintColor, + favorite: this.favorite, + favoriteColor: this.favoriteColor, + fontRegion: this.fontRegion, + gender: this.gender, + glassColor: this.glassColor, + glassScale: this.glassScale, + glassType: this.glassType, + glassY: this.glassY, + hairColor: this.hairColor, + hairFlip: this.hairFlip, + hairType: this.hairType, + hatCommonColor: this.hatCommonColor, + hatFavoriteColor: this.hatFavoriteColor, + hatType: this.hatType, + height: this.height, + wigType: this.wigType, + moleScale: this.moleScale, + moleType: this.moleType, + moleX: this.moleX, + moleY: this.moleY, + mouthAspect: this.mouthAspect, + mouthColor: this.mouthColor, + mouthScale: this.mouthScale, + mouthType: this.mouthType, + mouthY: this.mouthY, + mustacheScale: this.mustacheScale, + mustacheType: this.mustacheType, + mustacheY: this.mustacheY, + temporary: this.temporary, + noseScale: this.noseScale, + noseType: this.noseType, + noseY: this.noseY, + pantsColor: this.pantsColor, + personality: this.personality, + regionMove: this.regionMove, + shirtColor: this.shirtColor, + shoesColor: this.shoesColor, + special: this.special, + ...override + }; + } + #getNicknameSafe() { + if (this.nickname.trim() !== "") + return this.nickname; + else + return "A Mii"; + } + verify() { + return validate(this.#getObject()); + } + validate() { + const verify = this.verify(); + if (verify.valid === true) + this.valid = true; + else { + this.valid = false; + console.warn(`${this.#getNicknameSafe()} has invalid data:`, verify.reasons.join(", ")); + console.warn(this.export()); + throw new Error(`Mii data for ${this.nickname} is not valid: ${verify.reasons.join(", ")}`); + } + } + import(data2) { + this.miicVersion = data2.miicVersion; + this.originPlatform = data2.originPlatform; + this.authorId = data2.authorId; + this.createId = data2.createId; + this.creator = data2.creator; + this.nickname = data2.nickname; + this.beardColor = data2.beardColor; + this.beardType = data2.beardType; + this.birthDay = data2.birthDay; + this.birthMonth = data2.birthMonth; + this.birthYear = data2.birthYear; + this.build = data2.build; + this.clothesType = data2.clothesType; + this.eyeAspect = data2.eyeAspect; + this.eyebrowAspect = data2.eyebrowAspect; + this.eyebrowColor = data2.eyebrowColor; + this.eyebrowRotate = data2.eyebrowRotate; + this.eyebrowScale = data2.eyebrowScale; + this.eyebrowType = data2.eyebrowType; + this.eyebrowX = data2.eyebrowX; + this.eyebrowY = data2.eyebrowY; + this.eyeColor = data2.eyeColor; + this.eyeRotate = data2.eyeRotate; + this.eyeScale = data2.eyeScale; + this.eyeSclera = data2.eyeSclera; + this.eyeType = data2.eyeType; + this.eyeX = data2.eyeX; + this.eyeY = data2.eyeY; + this.facelineColor = data2.facelineColor; + this.facelineMake = data2.facelineMake; + this.facelineType = data2.facelineType; + this.facelineWrinkle = data2.facelineWrinkle; + this.facePaintColor = data2.facePaintColor; + this.favorite = data2.favorite; + this.favoriteColor = data2.favoriteColor; + this.fontRegion = data2.fontRegion; + this.gender = data2.gender; + this.glassColor = data2.glassColor; + this.glassScale = data2.glassScale; + this.glassType = data2.glassType; + this.glassY = data2.glassY; + this.hairColor = data2.hairColor; + this.hairFlip = data2.hairFlip; + this.hairType = data2.hairType; + this.hatFavoriteColor = data2.hatFavoriteColor; + this.hatCommonColor = data2.hatCommonColor; + this.hatType = data2.hatType; + this.height = data2.height; + this.wigType = data2.wigType; + this.moleScale = data2.moleScale; + this.moleType = data2.moleType; + this.moleX = data2.moleX; + this.moleY = data2.moleY; + this.mouthAspect = data2.mouthAspect; + this.mouthColor = data2.mouthColor; + this.mouthScale = data2.mouthScale; + this.mouthType = data2.mouthType; + this.mouthY = data2.mouthY; + this.mustacheScale = data2.mustacheScale; + this.mustacheType = data2.mustacheType; + this.mustacheY = data2.mustacheY; + this.noseScale = data2.noseScale; + this.noseType = data2.noseType; + this.noseY = data2.noseY; + this.pantsColor = data2.pantsColor; + this.personality = data2.personality; + this.regionMove = data2.regionMove; + this.shirtColor = data2.shirtColor; + this.special = data2.special; + this.shoesColor = data2.shoesColor; + this.temporary = data2.temporary; + if (this.originPlatform === 2 /* CFL_3DS */ || this.originPlatform === 3 /* FFL_Wii_U */) { + const createId = FFLiCreateID.unpack(this.createId); + if (!createId.flag_normal) { + this.special = 1; + } + if (createId.flag_temporary) { + this.special = 0; + this.temporary = 1; + } + } + this.fixInternalIDs(); + } + export(outputFormat = "miic") { + this.fixInternalIDs(); + switch (outputFormat) { + case "rsd": + throw new Error("RSD format is not yet supported."); + default: + case "miic": + return MiiCreatorV4Data.pack(this.#getObject()); + case "studioData": + return StudioData.pack(this.#getObject({ + facelineColor: this.facePaintColor !== -1 ? this.facePaintColor + 10 : this.facelineColor + })); + case "switchCharInfo": + return NnMiiCharInfo.pack(this.#getObject()); + case "ffsd": + return MiiCreatorV4DataToFFSD(this.#getObject(), true); + case "ffsd_append_miic": + return MiiCreatorV4DataToFFSD(this.#getObject(), true, true); + } + } + exportHex(outputFormat) { + const data2 = this.export(outputFormat); + return dataToHex(data2); + } + exportBase64(outputFormat) { + const data2 = this.export(outputFormat); + return dataToBase64(data2); + } + hasExtendedColors() { + return false; + } + fixInternalIDs() { + const createId = FFLiCreateID.unpack(this.createId); + const authorId = this.authorId; + if (Array.from(createId.base).every((e) => e === 0)) { + createId.base = randomizeUint8Array(createId.base); + } + if (Array.from(authorId).every((e) => e === 0)) { + this.authorId = randomizeUint8Array(authorId); + } + if (createId.flag_normal === 0 && this.special === 0) { + createId.flag_normal = 1; + } + if (createId.flag_normal === 1 && this.special === 1) { + createId.flag_normal = 0; + } + if (createId.flag_temporary === 0 && this.temporary === 1) { + createId.flag_temporary = 1; + } + if (createId.flag_temporary === 1 && this.temporary === 0) { + createId.flag_temporary = 0; + } + this.createId = FFLiCreateID.pack(createId); + } +} + +// src/util/camera.js +var ViewType2 = { + Face: 0, + MakeIcon: 1, + IconFovy45: 2, + AllBody: 3, + AllBodySugar: 4, + CreditIcon: 5 +}; +function getCameraForViewType(viewType, width2 = 1, height2 = 1, miiHeight = 1) { + const aspect2 = width2 / height2; + switch (viewType) { + case ViewType2.Face: { + const fovy = 15; + const camera = new PerspectiveCamera(fovy, aspect2, 0.1, 1000); + camera.position.set(0, 34.5, 380); + camera.lookAt(0, 34.3, 0); + return camera; + } + case ViewType2.MakeIcon: { + const fovy = 9.8762; + const camera = new PerspectiveCamera(fovy, aspect2, 500, 1000); + camera.position.set(0, 34.5, 600); + camera.lookAt(0, 34.5, 0); + return camera; + } + case ViewType2.IconFovy45: { + const camera = new PerspectiveCamera(45, aspect2, 50, 1000); + camera.position.set(0, 34, 110); + camera.lookAt(0, 34, 0); + return camera; + } + case ViewType2.AllBody: { + const fovy = 15; + const camera = new PerspectiveCamera(fovy, aspect2, 50, 1500); + camera.position.set(0, 50, 900); + camera.lookAt(0, 105, 0); + return camera; + } + case ViewType2.AllBodySugar: { + const fovy = 15; + const camera = new PerspectiveCamera(fovy, aspect2, 50, 15000); + const posStart = new Vector3(0, 65, 550); + const atStart = new Vector3(0, 65, 0); + const posEnd = new Vector3(0, 75, 850); + const atEnd = new Vector3(0, 88, 0); + const t3 = (miiHeight - 0.5) / (1.264 - 0.5); + const pos = new Vector3(posStart.x + t3 * (posEnd.x - posStart.x), posStart.y + t3 * (posEnd.y - posStart.y), posStart.z + t3 * (posEnd.z - posStart.z)); + const at = new Vector3(atStart.x + t3 * (atEnd.x - atStart.x), atStart.y + t3 * (atEnd.y - atStart.y), atStart.z + t3 * (atEnd.z - atStart.z)); + camera.position.copy(pos); + camera.lookAt(at); + return camera; + } + case ViewType2.CreditIcon: { + const fovy = 15; + const camera = new PerspectiveCamera(fovy, aspect2, 0.1, 1000); + camera.position.set(-60, 34.5, 380); + camera.lookAt(0, 34.3, 0); + return camera; + } + default: + throw new Error("getCameraForViewType: not implemented"); + } +} + +// src/util/rendertarget.js +var isWorker = false; +if (typeof window === "undefined") { + isWorker = true; +} +function renderTargetToDataURL(renderTarget, renderer2, flipY = false, blob = true) { + return new Promise((resolve) => { + const scene = new Scene; + scene.background = null; + const material = new MeshBasicMaterial({ + side: DoubleSide, + map: renderTarget.texture, + transparent: true + }); + const plane = new PlaneGeometry(2, 2); + const mesh = new Mesh(plane, material); + scene.add(mesh); + const camera = getIdentCamera(flipY); + const prevTarget = renderer2.getRenderTarget(); + const prevColorSpace = renderer2.outputColorSpace; + const size2 = new Vector2; + renderer2.getSize(size2); + renderer2.setRenderTarget(null); + renderer2.outputColorSpace = ColorManagement ? ColorManagement.workingColorSpace : null; + renderer2.setSize(renderTarget.width, renderTarget.height, false); + renderer2.render(scene, camera); + function cleanup() { + material.dispose(); + plane.dispose(); + scene.remove(mesh); + renderer2.outputColorSpace = prevColorSpace; + renderer2.setSize(size2.x, size2.y, false); + renderer2.setRenderTarget(prevTarget); + } + if (blob) { + const ok = (blob2) => { + resolve({ type: "blob", result: blob2 }); + cleanup(); + }; + if (isWorker) { + renderer2.domElement.convertToBlob({ type: "image/png" }).then(ok); + } else { + renderer2.domElement.toBlob(ok); + } + } else { + const result = renderer2.domElement.toDataURL("image/png"); + resolve({ type: "dataURL", result }); + cleanup(); + } + }); +} +async function renderTargetToDataTexture(renderTarget, renderer2, flipY = false, filtering = true) { + const { width: width2, height: height2 } = renderTarget; + let buf = new Uint8Array(width2 * height2 * 4); + await renderer2.readRenderTargetPixelsAsync(renderTarget, 0, 0, width2, height2, buf); + const dataTexture = new DataTexture(buf, width2, height2, RGBAFormat, UnsignedByteType); + dataTexture.needsUpdate = true; + if (flipY) { + dataTexture.flipY = true; + } + if (filtering) { + dataTexture.minFilter = LinearFilter; + dataTexture.magFilter = LinearFilter; + } + return dataTexture; +} + +// src/class/3d/shader/ColorMix.ts +function ColorMixShaderMaterial(texture, r, g3, b2) { + return new ShaderMaterial({ + uniforms: { + u_texture: { value: texture }, + u_const1: { value: r }, + u_const2: { value: g3 }, + u_const3: { value: b2 } + }, + vertexShader: ` + varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + } + `, + fragmentShader: ` + uniform sampler2D u_texture; + uniform vec4 u_const1; + uniform vec4 u_const2; + uniform vec4 u_const3; + varying vec2 vUv; + + void main() { + vec4 texColor = texture2D(u_texture, vUv); + + // Optionally discard low-alpha texture pixels. + if (texColor.a <= 0.2) { + discard; + } + +// Mix RGB channels using each constant’s color (rgb) +vec3 mixedColor = texColor.r * u_const1.rgb + + texColor.g * u_const2.rgb + + texColor.b * u_const3.rgb; + +// Use the texture's own alpha +float mixedAlpha = texColor.a; + +// Premultiply the mixed color by its alpha +gl_FragColor = vec4(mixedColor * mixedAlpha, mixedAlpha); + } + ` + }); +} +function colorMixTexture(tex, constR = new Vector4(0, 1, 1, 1), constG = new Vector4(1, 1, 0, 1), constB = new Vector4(1, 1, 0, 1), constA, rendererMain, textureResolution) { + return new Promise((resolve) => { + const scene = new Scene; + let width2, height2; + if (tex instanceof ImageBitmap) { + width2 = tex.width; + height2 = tex.height; + } else { + width2 = tex.image.width; + height2 = tex.image.height; + } + if (textureResolution) { + let aspect2 = width2 / height2; + width2 = textureResolution; + height2 = textureResolution / aspect2; + } + console.log("HI ITS ME CLOTHING TEX RENDERER, IDK WTF I DID", width2, height2); + const renderSize = new Vector2(0, 0); + rendererMain.getSize(renderSize); + console.log("[CMT DEBUG] width, height", width2, height2); + const camera = new OrthographicCamera(width2 / -2, width2 / 2, height2 / 2, height2 / -2, 0.1, 1000); + camera.position.z = 1; + console.log("[CMT DEBUG] camera Created!"); + const renderer2 = rendererMain; + console.log("[CMT DEBUG] renderer Created!"); + let oldClearColor = new Color; + renderer2.getClearColor(oldClearColor); + let oldClearAlpha = renderer2.getClearAlpha(); + renderer2.setClearColor(constA, 1); + console.log("[CMT DEBUG] using red for alpha."); + renderer2.setSize(width2, height2, false); + console.log("[CMT DEBUG] set renderer size OK."); + if (typeof window !== "undefined") + window.camera = camera; + const geometry = new PlaneGeometry(width2, height2); + console.log("[CMT DEBUG] create geometry OK"); + const plane = new Mesh(geometry, ColorMixShaderMaterial(tex, constR, constG, constB)); + console.log("[CMT DEBUG] create mesh OK"); + scene.add(plane); + console.log("[CMT DEBUG] add mesh to scene"); + function render() { + console.log("[CMT DEBUG] render scene OK"); + function finalize(blob) { + if (blob === null) + return console.error("blob is null???"); + resolve(blob); + renderer2.setClearColor(0); + renderer2.setClearAlpha(0); + geometry.dispose(); + plane.material.dispose(); + console.log("[CMT DEBUG] disposed of scene OK"); + } + renderer2.setSize(width2, height2, false); + renderer2.render(scene, camera); + renderer2.setClearAlpha(0); + if (typeof document === "undefined") { + renderer2.domElement.convertToBlob({ type: "image/png" }).then(finalize); + } else { + renderer2.domElement.toBlob(finalize); + } + } + console.log("[CMT DEBUG] preparing render"); + render(); + }); +} + +// src/ui/pages/library/util/3DModel.ts +function loadBlobTexture(blob) { + return new Promise((resolve) => { + var texture = new Texture; + var url = URL.createObjectURL(blob); + var image = new Image; + image.src = url; + image.onload = function() { + texture.image = image; + texture.needsUpdate = true; + resolve(texture); + setTimeout(() => { + URL.revokeObjectURL(url); + }, 1e4); + }; + }); +} +function loadBlobTextureWorker(blob, width2 = 512, height2 = 512) { + return new Promise((resolve) => { + createImageBitmap(blob, 0, 0, width2, height2).then((r) => { + console.log("bitmap canvas texture created"); + return resolve(new CanvasTexture(r)); + }); + }); +} + +// src/util/IconRendering.ts +var import_FFLShaderMaterial3 = __toESM(require_FFLShaderMaterial(), 1); +var defaultParams = { + type: ViewType2.Face, + expression: 0, + characterYRotate: 0, + modelFlag: FFLCharModelDescDefault, + drawBody: true +}; +function createMiiRender(request) { + return new Promise(async (resolve) => { + let dataInput; + if (typeof request.data === "string") + dataInput = parseHexOrB64ToUint8Array(request.data); + else + dataInput = request.data; + let scene = new Scene; + const isTemporary = request.isTemporary !== false; + const mii = new Mii(dataInput); + const localModule = request.module; + if (localModule === undefined) + throw new Error("Module NOT ready."); + let modelFlag = FFLModelFlag.NORMAL; + if (request.additionalInfo.hatType !== -1) { + switch (HatTypeList[request.additionalInfo.hatType]) { + case 1 /* HAT */: + modelFlag = FFLModelFlag.HAT; + break; + case 2 /* FACE_ONLY */: + modelFlag = FFLModelFlag.FACE_ONLY; + break; + case 6 /* BALD */: + mii.hairType = 30; + dataInput = mii.export("studioData"); + break; + } + } + console.log("miic additional info:", JSON.stringify(request.additionalInfo)); + const shaderMaterial = await getShaderMaterialFromShaderType(request.shaderType); + const isUsingShader = await isShaderMaterial(request.shaderType); + let lights = await getSimpleMaterialAddLights(request.shaderType); + if (lights) { + lights(scene); + } + let texResolution = request.texResolution || 512; + if (request.size > 512) { + texResolution = 1024; + } else if (request.size > 1024) { + texResolution = 2048; + } + let expressions = []; + if (Array.isArray(request.expression)) { + expressions.push(...request.expression); + } else { + expressions.push(isNaN(request.expression) ? FFLExpression.NORMAL : request.expression); + } + const charModel = createCharModel(dataInput, { + resolution: texResolution, + resourceType: FFLResourceType.HIGH, + allExpressionFlag: makeExpressionFlag(expressions), + modelFlag + }, shaderMaterial, localModule, false); + charModel._materialTextureClass = import_FFLShaderMaterial3.default; + charModel._materialClass = shaderMaterial; + if (request.additionalInfo.eyeSclera === 1 && mii.eyeColor !== 8) { + self.eyeScleraHack = true; + } + initCharModelTextures(charModel, request.renderer, charModel._materialTextureClass); + if (request.additionalInfo.eyeSclera === 1 && mii.eyeColor !== 8) { + self.eyeScleraHack = false; + } + let miiGroup, headModel; + if (isTemporary) { + miiGroup = scene; + miiGroup.background = null; + } else { + miiGroup = new Group; + headModel = new Group; + } + const gender = charModel._model.charInfo.personal.gender; + const bodyScale = charModel.getBodyScale(); + let hatModel; + if (request.additionalInfo.hatType !== -1) { + let hatColor = [0, 0, 0]; + if (isTemporary) + hatModel = getHatModels()[request.additionalInfo.hatType].clone(true); + else + hatModel = getHatModels()[request.additionalInfo.hatType].clone(true); + hatColor = MiiFavoriteColorVec3Table[mii.favoriteColor % Object.keys(MiiFavoriteColorVec3Table).length]; + if (request.additionalInfo.hatFavoriteColor !== -1) { + hatColor = MiiFavoriteColorVec3Table[request.additionalInfo.hatFavoriteColor]; + } + if (request.additionalInfo.hatCommonColor !== -1) { + hatColor = SwitchMiiColorTableSRGB[request.additionalInfo.hatCommonColor]; + } + console.log("additional info:", request.additionalInfo, "hat model:", hatModel); + hatModel.traverse((m) => { + if (m.isMesh) { + const oldMat = m.material.map; + let modulate = isUsingShader ? { + modulateType: 5 /* FFL_MODULATE_TYPE_SHAPE_CAP */, + modulateMode: 2 + } : {}; + m.material = new shaderMaterial({ + ...modulate, + color: new Color(...hatColor), + opacity: 1, + map: oldMat + }); + } + }); + if (isTemporary) { + miiGroup.add(hatModel); + } else { + headModel.add(hatModel); + } + const shiftPos = charModel.partsTransform.hatTranslate.y; + if (request.drawBody) { + if (isTemporary) { + hatModel.position.set(0, bodyScale.y * 75 + shiftPos, 0); + } else { + hatModel.position.set(0, shiftPos, 0); + } + } else { + charModel.partsTransform.hatTranslate.y; + hatModel.position.set(0, shiftPos, 0); + } + } + const headMesh = charModel.meshes.clone(); + if (isTemporary) { + miiGroup.add(headMesh); + } else { + headModel.add(headMesh); + } + let iconCamera; + if (isTemporary) + iconCamera = getCameraForViewType(request.type, undefined, undefined, bodyScale.y); + let bodyModel, bodyModelBody, bodyModelHands, bodyModelLegs, bodyModelAnims; + if (headModel !== undefined) { + miiGroup.add(headModel); + } + let prefix = "high"; + if (request.bodyModelType !== undefined) { + prefix = request.bodyModelType; + } + if (request.drawBody && getBodyModels()[prefix + "M"] !== null) { + switch (gender) { + case 0: { + if (isTemporary) + bodyModel = getBodyModels()[prefix + "M"].scene; + else + bodyModel = exports_SkeletonUtils.clone(getBodyModels()[prefix + "M"].scene); + if (bodyModel === null) + throw "Tried to make an icon before body models were loaded."; + bodyModelBody = bodyModel.getObjectByName("body_m"); + bodyModelHands = bodyModel.getObjectByName("hands_m"); + bodyModelLegs = bodyModel.getObjectByName("legs_m"); + if (!isTemporary) + bodyModelAnims = getBodyModels()[prefix + "M"].animations; + break; + } + case 1: { + if (isTemporary) + bodyModel = getBodyModels()[prefix + "F"].scene; + else + bodyModel = exports_SkeletonUtils.clone(getBodyModels()[prefix + "F"].scene); + if (bodyModel === null) + throw "Tried to make an icon before body models were loaded."; + bodyModelBody = bodyModel.getObjectByName("body_f"); + bodyModelHands = bodyModel.getObjectByName("hands_f"); + bodyModelLegs = bodyModel.getObjectByName("legs_f"); + if (!isTemporary) + bodyModelAnims = getBodyModels()[prefix + "F"].animations; + break; + } + default: + throw new Error(`Gender ${gender} is outisde range 0, 1`); + } + bodyModel.scale.set(bodyScale.x * 7, bodyScale.y * 7, bodyScale.z * 7); + bodyModel.position.set(0, 0, 0); + miiGroup.add(bodyModel); + var shirtColor = MiiFavoriteColorVec3Table[mii.favoriteColor % Object.keys(MiiFavoriteColorVec3Table).length]; + if (request.additionalInfo.shirtColor !== -1 && !ForbiddenShirtPantColors.includes(request.additionalInfo.shirtColor)) { + shirtColor = SwitchMiiColorTableSRGB[request.additionalInfo.shirtColor]; + } + let modulate = isUsingShader ? { + modulateType: 9 /* FFL_MODULATE_TYPE_SHAPE_BODY */, + modulateMode: 0 + } : {}; + bodyModelBody.material = new charModel._materialClass({ + ...modulate, + color: new Color(...shirtColor), + opacity: 1 + }); + if (bodyModelHands) + bodyModelHands.material = bodyModelBody.material; + var pantsColor = cPantsColorGray; + if (request.additionalInfo.favorite === 1) { + pantsColor = cPantsColorRed; + } + if (request.additionalInfo.special === 1) { + pantsColor = cPantsColorGold; + } + if (request.additionalInfo.temporary === 1) { + pantsColor = cPantsColorBlue; + } + if (request.additionalInfo.pantsColor !== -1 && !ForbiddenShirtPantColors.includes(request.additionalInfo.pantsColor)) { + pantsColor = SwitchMiiColorTableSRGB[request.additionalInfo.pantsColor]; + } + modulate = isUsingShader ? { + modulateType: 10 /* FFL_MODULATE_TYPE_SHAPE_PANTS */, + modulateMode: 0 + } : {}; + bodyModelLegs.material = new charModel._materialClass({ + ...modulate, + color: new Color(...pantsColor), + opacity: 1 + }); + const nBody = bodyModelBody; + const nLegs = bodyModelLegs; + ColorManagement.enabled = false; + if (request.additionalInfo.clothesType !== undefined && request.additionalInfo.clothesType !== -1 && request.bodyModelType !== "low" /* low */ && getLoadedBodyModelName() === "wiiu" && request.additionalInfo.clothesType < ExtClothesList.length) { + console.log("clothing update"); + let shirtTexture, pantsTexture = null; + const suffix = mii.gender == 1 ? "F" : ""; + let key2 = `${getLoadedBodyModelName()}_${ExtClothesList[request.additionalInfo.clothesType]}${suffix}`; + let shirtKey = key2; + if (getLoadedBodyModelName() === "miitomo") { + shirtKey = key2 + "_Top"; + } + let shoesColor = request.additionalInfo.shoesColor !== -1 && request.additionalInfo.shoesColor < 100 ? SwitchMiiColorTableSRGB[request.additionalInfo.shoesColor] : [1, 1, 1]; + switch (ClothesTypeList[request.additionalInfo.clothesType]) { + case 0 /* COLOR_MIXED */: { + const colorMixR = new Vector4(...shirtColor, 1), colorMixG = new Vector4(...shoesColor, 1), colorMixB = new Vector4(...pantsColor, 1), colorMixA = charModel ? request.clothingLinearColors !== true ? charModel.facelineColor : charModel.facelineColor.convertSRGBToLinear() : 16711680; + let tex = await colorMixTexture(getClothesTextures()[shirtKey], colorMixR, colorMixG, colorMixB, colorMixA, request.textureRenderer || request.renderer, request.texResolution); + shirtTexture = await loadBlobTextureWorker(tex, request.texResolution, request.texResolution); + break; + } + case 1 /* TEXTURE_COLOR */: { + shirtTexture = getClothesTextures()[shirtKey + suffix]; + break; + } + default: + alert("Something isn't right here"); + throw "???"; + } + request.renderer.initTexture(shirtTexture); + let nBodyMat = nBody.material; + let nLegsMat = nLegs.material; + nBodyMat.dispose(); + nLegsMat.dispose(); + let modulate2 = isUsingShader ? { + modulateType: 9, + modulateMode: 1, + color: new Color(0) + } : { color: new Color(16777215) }; + const params = { + ...modulate2, + map: shirtTexture + }; + const newBodyMat = new (await getShaderMaterialFromShaderType(request.shaderType))(params); + if (getLoadedBodyModelName() !== "miitomo") { + nBody.material = newBodyMat; + nLegs.material = newBodyMat; + } + console.log("mat changed!", newBodyMat, nBody, nLegs); + } + if (isTemporary) { + headMesh.position.set(0, bodyScale.y * 75, 0); + } else { + headModel.position.set(0, bodyScale.y * 75, 0); + } + if (isTemporary) + switch (request.type) { + case ViewType2.Face: + case ViewType2.MakeIcon: + case ViewType2.IconFovy45: + case ViewType2.CreditIcon: { + iconCamera.position.y += bodyScale.y * 76; + } + } + if (request.bodyModelType === "low" /* low */) { + bodyModelHands.visible = false; + } + if (isStreetPass()) { + console.log("is streetpass"); + var scaleVec = new Vector3; + bodyModel.getWorldScale(scaleVec); + const handScaleX = 1 / scaleVec.x * 5; + const handScaleY = 1 / scaleVec.y * 5; + console.log(handScaleX, handScaleY); + bodyModel.getObjectByName("handLPs").scale.set(handScaleX, handScaleY, handScaleX); + bodyModel.getObjectByName("handRPs").scale.set(handScaleX, handScaleY, handScaleX); + } else { + console.log("not streetpass"); + } + } + if (isTemporary) { + const target = createAndRenderToTarget(miiGroup, iconCamera, request.renderer, request.size, request.size); + setTimeout(() => { + const dataURL = renderTargetToDataURL(target, request.renderer); + target.dispose(); + charModel.dispose(); + if (request.drawBody) { + bodyModelBody.material.dispose(); + bodyModelLegs.material.dispose(); + } + if (hatModel) { + hatModel.traverse((n2) => { + if (!n2.isMesh) + return; + n2.geometry.dispose(); + n2.material.dispose(); + }); + } + resolve(dataURL); + }, 0); + } else { + return resolve({ + bodyModel, + bodyModelBody, + bodyModelHands, + bodyModelLegs, + charModel, + headModel, + miiGroup, + bodyModelAnims + }); + } + }); +} + +// node_modules/@datkat21/html/dist/html.js +/*! +Html library by datkat21 on GitHub. Licensed under MIT +https://github.com/datkat21/html +!*/ + +class Html { + elm; + constructor(elm) { + if (elm instanceof HTMLElement) + this.elm = elm; + else + this.elm = document.createElement(elm || "div"); + } + text(val2) { + this.elm.innerText = val2; + return this; + } + html(val2) { + this.elm.innerHTML = val2; + return this; + } + cleanup() { + this.elm.remove(); + return this; + } + query(selector) { + return this.elm.querySelector(selector); + } + qs(query) { + if (this.elm.querySelector(query)) + return Html.from(this.elm.querySelector(query)); + else + return null; + } + qsa(query) { + if (this.elm.querySelector(query)) + return Array.from(this.elm.querySelectorAll(query)).map((e) => Html.from(e)); + else + return null; + } + id(val2) { + this.elm.id = val2; + return this; + } + class(...val2) { + for (let i = 0;i < val2.length; i++) + this.elm.classList.toggle(val2[i]); + return this; + } + classOn(...val2) { + for (let i = 0;i < val2.length; i++) + this.elm.classList.add(val2[i]); + return this; + } + classOff(...val2) { + for (let i = 0;i < val2.length; i++) + this.elm.classList.remove(val2[i]); + return this; + } + style(obj) { + for (const key2 of Object.keys(obj)) + this.elm.style.setProperty(key2, obj[key2]); + return this; + } + styleJs(obj) { + for (const key2 of Object.keys(obj)) + this.elm.style[key2] = obj[key2]; + return this; + } + on(ev, cb) { + this.elm.addEventListener(ev, cb); + return this; + } + un(ev, cb) { + this.elm.removeEventListener(ev, cb); + return this; + } + getElement(element) { + let p = element instanceof Html ? element.elm : element; + if (typeof element === "string") + p = document.querySelector(element); + if (p instanceof HTMLElement) + return p; + else + throw new Error("Invalid element type."); + } + appendTo(parent2) { + let p = this.getElement(parent2); + if (p instanceof HTMLElement) + p.appendChild(this.elm); + else + throw new Error("Invalid parent element, exausted 3 checks."); + return this; + } + prependTo(parent2) { + let p = this.getElement(parent2); + if (p instanceof HTMLElement) + p.prepend(this.elm); + return this; + } + append(elem2) { + let e = this.getElement(elem2); + if (e instanceof HTMLElement) + this.elm.appendChild(e); + else if (typeof elem2 === "string") { + const newElem = document.createElement(elem2); + this.elm.appendChild(newElem); + return new Html(newElem.tagName); + } + return this; + } + prepend(elem2) { + let e = this.getElement(elem2); + if (e instanceof HTMLElement) + this.elm.prepend(e); + else if (typeof elem2 === "string") { + const newElem = document.createElement(elem2); + this.elm.prepend(newElem); + return new Html(newElem.tagName); + } + return this; + } + appendMany(...elements) { + for (const elem2 of elements) + this.append(elem2); + return this; + } + prependMany(...elements) { + for (const elem2 of elements) + this.prepend(elem2); + return this; + } + clear() { + this.elm.innerHTML = ""; + return this; + } + attr(obj) { + for (let key2 in obj) + if (obj[key2] !== null && obj[key2] !== undefined) + this.elm.setAttribute(key2, obj[key2]); + else + this.elm.removeAttribute(key2); + return this; + } + val(str) { + this.elm.value = str; + return this; + } + getText() { + return this.elm.innerText; + } + getHtml() { + return this.elm.innerHTML; + } + getValue() { + return this.elm.value; + } + swapRef(elm) { + this.elm = elm; + return this; + } + static from(elm) { + const qs = () => Html.qs(elm); + if (typeof elm === "string") + return qs(); + return new Html(elm); + } + static qs(query) { + if (document.querySelector(query)) + return Html.from(document.querySelector(query)); + return null; + } + static qsa(query) { + if (document.querySelector(query)) + return Array.from(document.querySelectorAll(query)).map((e) => Html.from(e)); + return null; + } +} + +// src/external/mii-selector/selector_misc.ts +var css = `* { + font-family: 'nintendo_NTLG-DB_001' !important; + --default-selector-width: 750px; + --default-selector-height: 520px; +} + +#mii-creator-selector-modal *:focus-visible:not(.mii.selected:focus-visible){ + outline: none; + box-shadow: 0px 0px 0px 3px #00c6f6 !important; +} + +#mii-creator-selector-modal { + width: 100%; + height: 100%; + position: fixed; + top: 0; + left: 0; + display: flex; + background-color: rgba(0, 0, 0, 0.5); + justify-content: center; + align-items: center; + overflow: hidden; + line-height: 1.5; +} + +@keyframes slideUp { + 0% { + top: 100%; + } + 85% { + top: -3%; /* Slight overshoot */ + } + 95% { + top: 1%; /* Small bounce back */ + } + 100% { + top: 0%; /* Settle at final position */ + } +} + +@keyframes slideDown { + 0% { + top: 0%; + } + 85% { + top: 103%; /* Slight overshoot downward */ + } + 95% { + top: 99%; /* Small bounce back upward */ + } + 100% { + top: 100%; /* Settle at final position */ + } + } + + + +#mii-creator-selector-modal .selector { + width: var(--default-selector-width); + height: var(--default-selector-height); + background: #ecf8f0; + border-radius: 20px; + box-shadow: inset 0px 0px 8px 1px #00000063; + border: 2px solid #ecf8f0; + box-sizing: border-box; + position: relative; + animation: slideUp 0.55s ease-in-out; + overflow: hidden; +} + +#mii-creator-selector-modal .selector.finish { + animation: slideDown 0.55s ease-in-out forwards !important; +} + +#mii-creator-selector-modal .button-navi { + position: absolute; + margin-top: 135px; + top: 0; + width: 100%; + left: 0; +} + +#mii-creator-selector-modal .button-navi button { + height: 180px; + font-size: 40px; + text-shadow: 1px 2px #fff; + color: #141914; + width: 55px; + border: 1.5px solid #68776d; + cursor: pointer; + transition: 0.02s; + background: linear-gradient(#d3e1d3, #95aa95); +} + +#mii-creator-selector-modal .button-navi button:active:not(:disabled) { + text-shadow: 1px 2px #141914; + background: linear-gradient(#24402f, #7d937f); + color: #fff; + border-color: #3e5846; + width: 50px; +} + +#mii-creator-selector-modal .button-navi button.prev{ + position: absolute; + top: 0; + left: 0; + box-shadow: 2px 0px 3px 1px rgba(0, 0, 0, 0.30); + border-top-right-radius: 13px; + border-bottom-right-radius: 13px; + border-left: none; +} + +#mii-creator-selector-modal .button-navi button.next{ + position: absolute; + top: 0; + right: 0; + box-shadow: -2px 1px 3px 1px rgba(0, 0, 0, 0.30); + border-top-left-radius: 13px; + border-bottom-left-radius: 13px; + border-right: none; +} + +#mii-creator-selector-modal .selector>h1 { + text-align: center; + margin: 5px; + font-weight: normal; + font-size: 32px; +} + + +#mii-creator-selector-modal .selector .mii-container { + height: 60%; + background: #fff; + width: 90%; + box-shadow: 0px 0px 3px 1px #d5dbd6; + border-radius: 10px; + margin: auto; + margin-top: 25px; + display: flex; + align-content: center; + flex-wrap: wrap; + flex-direction: row; + justify-content: center; + left: 0px; + position: relative; +} + +#mii-creator-selector-modal .selector .mii-container.slideleft { + animation: slideLeft 0.25s ease-in forwards; +} + +#mii-creator-selector-modal .selector .mii-container.slideright { + animation: slideRight 0.25s ease-in forwards; +} + +#mii-creator-selector-modal .selector .mii-container.slideleftb { + animation: slideLeftB 0.25s ease-in forwards; +} + +#mii-creator-selector-modal .selector .mii-container.sliderightb { + animation: slideRightB 0.25s ease-in forwards; +} + +@keyframes slideLeft { + from { + left: 0%; + } + to { + left: -100%; + } +} + +@keyframes slideRight { + from { + left: 0%; + } + to { + left: 100%; + } +} + +@keyframes slideLeftB { + from { + left: 100%; + } + to { + left: 0%; + } +} + +@keyframes slideRightB { + from { + left: -100%; + } + to { + left: 0%; + } +} + +#mii-creator-selector-modal .selector .mii-container.guest { + padding-left: 32%; + box-sizing: border-box; +} + +#mii-creator-selector-modal .selector .mii-container.transition { + top: -60%; + left: 100%; + margin-top: 0; +} + +#mii-creator-selector-modal .selector .mii-container.guest .guest-label{ + width: 230px; + height: 280px; + text-align: center; + display: flex +; + background: #e2f3e0; + border-radius: 10px; + position: absolute; + left: 0; + top: auto; + margin-top: 15px; + margin-left: 55px; + color: #505050; + justify-content: center; + font-size: 30px; + align-items: center; +} + +#mii-creator-selector-modal .selector .mii-page-counter { + margin-top: 15px; + margin-right: 30px; + position: absolute; + right: 0; + top: 75%; + z-index: 5; + width: auto; + padding: 0px 20px; + border-radius: 8px; + font-size: 28px; + box-shadow: -2px -2px 3px 1px rgba(255, 255, 255, 0.80) inset, 1px 1px 3px 1px rgb(0 0 0 / 22%) inset, 0px 0px 0px 1px rgb(0 0 0 / 33%); + text-align: center; + background: rgba(0, 0, 0, 0.10); +} + +#mii-creator-selector-modal .selector .mii-page-counter>span>b{ + color: #0096ff; + font-weight: normal; + padding: 0px 12px; +} + +#mii-creator-selector-modal .selector .mii-container .mii { + width: 110px; + margin: 5px; + background: #e6f0e8; + height: 130px; + border: 3.5px solid #a0ad9e; + border-radius: 10px; + position: relative; + cursor: pointer; +} + +#mii-creator-selector-modal .selector .mii-container .mii:focus-visible { + outline: none; +} + +#mii-creator-selector-modal .selector .mii-container .mii.selected { + border-color: #ffaf31; + animation: glow 0.1s forwards ease-in-out; + background: #fbbeaa; +} + +@keyframes glow{ + 0% { + box-shadow: 1px 1px 4px #ffaf31 inset, 0px 0px 2px 0px #e5910f, inset 0px 0px 2px 2px #f2980a; + } + 50% { + box-shadow: 1px 1px 4px #ffaf31 inset, 0px 0px 6px 2px #e5910f, inset 0px 0px 2px 2px #f2980a; + } + 100% { + box-shadow: 1px 1px 4px #ffaf31 inset, 0px 0px 4px 1px #e5910f, inset 0px 0px 2px 2px #f2980a, inset 0px 0px 6px 2px #00000043; + } +} + +#mii-creator-selector-modal .selector .mii-container .mii>img { + /* width: 120px; */ + position: absolute; + /* left: -5px; */ + bottom: 0; + pointer-events: none; + -webkit-tap-highlight-color: transparent; + -webkit-user-drag: none; + user-select: none; + outline: none; + animation: fadeIn 0.15s ease-in-out forwards; + transform: translate(-50%, 0); + width: 100%; + height: 100%; + left: 50%; + object-fit: cover; +} + +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +#mii-creator-selector-modal .selector .mii-container .mii>p svg { + width: 36px; + height: 36px; +} +#mii-creator-selector-modal .selector .mii-container .mii>p { + display: flex; + justify-content: center; + align-items: center; + gap: 8px; + position: absolute; + top: -35px; + left: 50%; + transform: translateX(-50%); + margin: auto; + border-radius: 5px; + width: auto; + white-space: nowrap; + font-size: 28px; + min-width: 100px; + padding: 3px 16px; + z-index: 10; + box-shadow: 0px 0px 1px 1.5px #9e9e9e, inset 0px 0px 5px 0px #afafaf; + background: #fff; + -webkit-user-drag: none; + user-select: none; + z-index: 10; + + color:#233f2e; +} + +#mii-creator-selector-modal .selector .mii-container .mii>p::before { + content: ""; + background-image: url("data:image/svg+xml,%3Csvg width='9' height='11' viewBox='0 0 9 11' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0.5 11L4.5 2L8.5 11H0.5Z' fill='url(%23paint0_linear_1939_2)'/%3E%3Cpath d='M4.49997 3.23111L8 11H9L4.49997 0.76889L0 11H1L4.49997 3.23111Z' fill='%23A0A0A0'/%3E%3Cdefs%3E%3ClinearGradient id='paint0_linear_1939_2' x1='4.5' y1='2' x2='4.5' y2='11' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0.865385' stop-color='white'/%3E%3Cstop offset='1' stop-color='%23AFAFAF'/%3E%3C/linearGradient%3E%3C/defs%3E%3C/svg%3E"); + position: absolute; + width: 20px; + height: 24px; + background-size: cover; + left: 50%; + transform: translateX(-50%) rotate(180deg); + top: 100%; + z-index: -1; +} + +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(1)>p, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(6)>p { + left: -10%; + transform: none; +} + +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(5)>p, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(10)>p { + right: -10%; + left: auto; + transform: none; +} + + +/* +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(1)>p::before, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(6)>p::before { + top: -100% !important; + left: -10% !important; + width: 100%; + transform: translateY(100%) rotate(0deg) !important; + background-size: contain; + background-position: center; + background-repeat: no-repeat; +} +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(5)>p::before, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(10)>p::before { + top: -100% !important; + left: -9% !important; + width: 100%; + transform: translateY(100%) rotate(0deg) !important; + background-size: contain; + background-position: center; + background-repeat: no-repeat; +} + +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(5)>p::before { + top: 100% !important; + left: 50% !important; + transform: translateX(-57%) rotate(180deg) !important; +} +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(1)>p::before { + top: 100% !important; + left: 50% !important; + transform: translateX(-57%) rotate(180deg) !important; +} +*/ + +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(6)>p, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(7)>p, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(8)>p, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(9)>p, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(10)>p { + top: auto; + bottom: -33px; +} + +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(6)>p::before, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(7)>p::before, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(8)>p::before, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(9)>p::before, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(10)>p::before { + transform: translateX(-50%) translateY(100%); + top: -100%; +} + +#mii-creator-selector-modal .selector .button-container { + width: 100%; + position: absolute; + display: flex; + bottom: 0; + left: 0; + border-bottom-left-radius: 20px; + border-bottom-right-radius: 20px; + background: linear-gradient(#cfddcf, #889488); + flex-direction: row; + flex-wrap: nowrap; +} + +#mii-creator-selector-modal .selector .button-container button{ + width: 50%; + margin: 0; + padding: 0; + border: 0; + background: none; + text-shadow: 0px 2px #fff; + font-size: 29px; + height: 55px; + border-top: 2px solid #44524b; + box-sizing: border-box; + transition: 0.02s; + cursor: pointer; + + color: #141914; +} + +#mii-creator-selector-modal .selector .button-container button:active:not(:disabled){ + text-shadow: 0px -2px #fff; + background: linear-gradient(#879287, #bfd2bf); +} + +#mii-creator-selector-modal .selector .button-container button.cancel{ + border-right: 1.5px solid #54625a; + border-bottom-left-radius: 20px; +} + +#mii-creator-selector-modal .selector .button-container button.confirm{ + border-left: 1.5px solid #54625a; + border-bottom-right-radius: 20px; +} + +#mii-creator-selector-modal .selector .button-container button.confirm:disabled{ + pointer-events: none; + border-color: #aaaaaa; + background: #bebebe; + color: #adadad; + text-shadow: none; +} + +@media only screen and (max-width: 600px) { + #mii-creator-selector-modal .selector { + width: 90%; + } +}`; +var miiIconFavorite = ``; +var miiIconSpecial = ``; +var miiIconPersonal = ``; + +// src/external/mii-selector/selector.js +function escapeHTML(str) { + return new Option(str).innerHTML; +} +var lang = "es"; +var MiiSelector = { + loc: { + en: [ + "Select a Mii.", + "Guests", + "Cancel", + "Confirm", + "Search", + "Matches for:", + "results", + "No matches found.", + "Guest " + ], + es: [ + "Selecciona un Mii.", + "Invitados", + "Cancelar", + "Confirmar", + "Buscar", + "Resultados para:", + "resultados", + "No hay resultados.", + "Invitado " + ] + }, + open: async function(miiArray, selectorParam) { + return new Promise((resolve, reject2) => { + if (selectorParam.personalMii) { + miiArray.unshift({ + miiData: selectorParam.personalMii, + type: 3 /* Personal */ + }); + } + let guestMiis = []; + if (selectorParam.guestData) { + guestMiis.push(...selectorParam.guestData.map((guest, index2) => { + let guestMii = new Mii(guest); + guestMii.nickname = getLoc(8) + String.fromCharCode(65 + index2); + return { miiData: guestMii.export() }; + })); + } + miiArray.unshift(...guestMiis); + function getLoc(index2) { + return MiiSelector.loc[lang][index2]; + } + var check2 = document.querySelector("#mii-creator-selector-modal"); + if (check2 != null || check2 != null) { + check2.remove(); + } + var pages = 0; + var currentPage = 1; + var canPreloadCharIcon = miiArray.length <= 100; + console.log("canPreloadCharIcon: " + canPreloadCharIcon); + var selectedMii = null; + if (selectorParam) { + if (selectorParam.preload === false) { + canPreloadCharIcon = false; + } + } + miiArray.forEach((mii, index2) => { + if (index2 % 10 === 0) { + pages++; + } + }); + const container = '
' + '" + "
"; + document.body.insertAdjacentHTML("beforeend", container); + check2 = document.querySelector("#mii-creator-selector-modal"); + var selCont = check2.querySelector(".selector"); + var pagesEl = check2.querySelector(".mii-page-counter span>span"); + var pagesCurEl = check2.querySelector(".mii-page-counter span>b"); + pagesEl.innerText = "/ " + pages; + var arrowLeft = check2.querySelector(".prev"); + var arrowRight = check2.querySelector(".next"); + var confirmButton = check2.querySelector(".confirm"); + var cancelButton = check2.querySelector(".cancel"); + var miiCoUser = check2.querySelector(".mii-container:not(.transition):not(.guest)"); + var miiTrs = check2.querySelector(".mii-container.transition"); + if (pages > 1) { + arrowRight.style.display = "block"; + } + const dataArray = []; + if (canPreloadCharIcon) { + const iconPromises = miiArray.map((mii, index2) => { + return new Promise(async (resolve2) => { + const miiData = new Mii(mii.miiData); + const data2 = miiData.export("studioData"); + const icon = await createMiiRender({ + data: data2, + drawBody: true, + size: 124, + module: fflModule, + additionalInfo: getAdditionalInfoFromMii(miiData), + shaderType: "wiiu_blinn", + renderer: renderer2, + bodyModelType: "low", + texResolution: 128, + type: 0 + }); + var iconURL = URL.createObjectURL(icon.result); + resolve2({ img: iconURL, name: miiData.nickname, type: mii.type }); + }); + }); + Promise.all(iconPromises).then(async (icons) => { + console.log("REAL"); + icons.forEach((e) => dataArray.push(e)); + fillMiiContainer(miiArray, currentPage).then((data2) => { + miiCoUser.innerHTML = data2; + selCont.style.display = "block"; + updateMiiListener(); + initButtonListener(); + }); + }); + } else { + fillMiiContainer(miiArray, currentPage).then((data2) => { + miiCoUser.innerHTML = data2; + selCont.style.display = "block"; + updateMiiListener(); + initButtonListener(); + }); + } + async function fillMiiContainer(miiArray2, page) { + console.log(page); + const miisPerPage = 10; + const startIndex = (page - 1) * miisPerPage; + const selectedMiis = miiArray2.slice(startIndex, startIndex + miisPerPage); + if (canPreloadCharIcon) { + var pageData = dataArray.slice(startIndex, startIndex + miisPerPage); + } else { + dataArray.length = 0; + var pageDataPromises = selectedMiis.map((mii) => { + return new Promise(async (resolve2) => { + const miiData = new Mii(mii.miiData); + const data2 = miiData.export("studioData"); + const icon = await createMiiRender({ + data: data2, + drawBody: true, + size: 124, + module: fflModule, + additionalInfo: getAdditionalInfoFromMii(miiData), + shaderType: "wiiu_blinn", + renderer: renderer2, + bodyModelType: "low", + texResolution: 128, + type: 0 + }); + var iconURL = URL.createObjectURL(icon.result); + const miiPageData = { + img: iconURL, + name: miiData.nickname, + type: mii.type + }; + dataArray.push(miiPageData); + return resolve2(miiPageData); + }); + }); + console.log("page data promises list", pageDataPromises); + pageData = await Promise.all(pageDataPromises); + console.log("page data overwrite promises", pageData); + } + while (pageData.length < miisPerPage) { + pageData.push({ img: "", name: "" }); + } + return pageData.map((mii, i) => { + const overallIndex = startIndex + i; + const dataAttr = mii.img && mii.name ? ` data-mii-index="${overallIndex}"` : ""; + let icon = ""; + switch (mii.type) { + case 1 /* Favorite */: + icon = miiIconFavorite; + break; + case 2 /* Special */: + icon = miiIconSpecial; + break; + case 3 /* Personal */: + icon = miiIconPersonal; + break; + } + return `
` + (mii.img ? `` : "") + (mii.name ? `

${icon}${escapeHTML(mii.name)}

` : "") + `
`; + }).join(""); + } + function miiSelect(el) { + var target = el; + if (el.classList.contains("selected")) { + return; + } + check2.querySelectorAll(".mii").forEach((mii) => { + mii.classList.remove("selected"); + mii.querySelectorAll("p").forEach((m) => { + m.style.display = "none"; + }); + }); + target.classList.add("selected"); + if (target.hasAttribute("data-mii-index")) { + selectedMii = { + index: target.getAttribute("data-mii-index"), + data: miiArray[parseInt(target.getAttribute("data-mii-index"))] + }; + console.log(selectedMii); + target.querySelector("p").style.display = ""; + confirmButton.disabled = false; + } else { + selectedMii = null; + confirmButton.disabled = true; + } + if (selectorParam.soundManager) { + selectorParam.soundManager.playSound("3ds_mii_selector_select"); + } + } + function updateMiiListener() { + check2.querySelectorAll(".mii").forEach(function(mii) { + mii.addEventListener("click", function(event) { + miiSelect(this); + }); + mii.addEventListener("focus", function(event) { + miiSelect(this); + }); + }); + } + function initButtonListener() { + arrowRight.addEventListener("click", function() { + lockArrowsForNation(); + miiCoUser.classList.add("slideleft"); + miiTrs.style.display = ""; + miiTrs.classList.add("slideleftb"); + miiTrs.addEventListener("animationend", function onAnimationEnd() { + miiTrs.removeEventListener("animationend", onAnimationEnd); + setTimeout(function() { + miiCoUser.classList.remove("slideleft"); + miiTrs.classList.remove("slideleftb"); + miiTrs.style.display = "none"; + miiCoUser.innerHTML = ""; + currentPage++; + fillMiiContainer(miiArray, currentPage).then((data2) => { + miiCoUser.innerHTML = data2; + updateMiiListener(); + pagesCurEl.innerText = currentPage; + doTrioAtPaginEnd(); + }); + }, 0); + }, { once: true }); + }); + arrowLeft.addEventListener("click", function() { + lockArrowsForNation(); + miiCoUser.classList.add("slideright"); + miiTrs.style.display = ""; + miiTrs.classList.add("sliderightb"); + miiTrs.addEventListener("animationend", function onAnimationEnd() { + miiTrs.removeEventListener("animationend", onAnimationEnd); + setTimeout(function() { + miiCoUser.classList.remove("slideright"); + miiTrs.classList.remove("sliderightb"); + miiTrs.style.display = "none"; + miiCoUser.innerHTML = ""; + currentPage--; + fillMiiContainer(miiArray, currentPage).then((data2) => { + miiCoUser.innerHTML = data2; + updateMiiListener(); + pagesCurEl.innerText = currentPage; + doTrioAtPaginEnd(); + }); + }, 0); + }, { once: true }); + }); + confirmButton.addEventListener("click", function onConfirm() { + console.log("Confirm"); + if (selectorParam.soundManager) { + selectorParam.soundManager.playSound("3ds_mii_selector_confirm"); + } + check2.style.pointerEvents = "none"; + confirmButton.removeEventListener("click", onConfirm); + selCont.classList.add("finish"); + selCont.addEventListener("animationend", function onAnimationEnd() { + selCont.removeEventListener("animationend", onAnimationEnd); + setTimeout(function() { + check2.remove(); + if (selectedMii != null) { + resolve({ mii: selectedMii.data }); + } else { + reject2("User hasnt selected Mii"); + } + }, 0); + }, { once: true }); + }); + cancelButton.addEventListener("click", function onCancel() { + check2.style.pointerEvents = "none"; + cancelButton.removeEventListener("click", onCancel); + selCont.classList.add("finish"); + if (selectorParam.soundManager) { + selectorParam.soundManager.playSound("3ds_mii_selector_cancel"); + } + selCont.addEventListener("animationend", function onAnimationEnd() { + selCont.removeEventListener("animationend", onAnimationEnd); + setTimeout(function() { + check2.remove(); + reject2("No Mii data selected by user."); + }, 0); + }, { once: true }); + }); + } + function doTrioAtPaginEnd() { + ifSelectedMiiRestore(); + updateArrowsForNation(); + unlockArrowsForNation(); + } + function updateArrowsForNation() { + if (currentPage === pages) { + arrowRight.style.display = "none"; + arrowLeft.style.display = ""; + } else if (currentPage === 1) { + arrowLeft.style.display = "none"; + arrowRight.style.display = ""; + } else { + arrowLeft.style.display = ""; + arrowRight.style.display = ""; + } + } + function ifSelectedMiiRestore() { + if (selectedMii != null && check2.querySelector('.mii[data-mii-index="' + selectedMii.index + '"]') && selectedMii.index) { + check2.querySelector('.mii[data-mii-index="' + selectedMii.index + '"]').classList.add("selected"); + check2.querySelector('.mii[data-mii-index="' + selectedMii.index + '"]').querySelector("p").style.display = ""; + check2.querySelector('.mii[data-mii-index="' + selectedMii.index + '"]').focus(); + } + } + function lockArrowsForNation() { + if (selectorParam.soundManager) { + selectorParam.soundManager.playSound("3ds_mii_selector_page"); + } + arrowRight.disabled = true; + arrowLeft.disabled = true; + arrowLeft.style.opacity = "0.5"; + arrowLeft.style.filter = "grayscale(100%)"; + arrowRight.style.opacity = "0.5"; + arrowRight.style.filter = "grayscale(100%)"; + } + function unlockArrowsForNation() { + arrowLeft.style.opacity = "1"; + arrowLeft.style.filter = "none"; + arrowRight.style.opacity = "1"; + arrowRight.style.filter = "none"; + arrowRight.disabled = false; + arrowLeft.disabled = false; + } + }); + } +}; +function miiSelectorSetFflModule(module2) { + fflModule = module2; +} +function miiSelectorSetRenderer(r) { + renderer2 = r; +} +var fflModule; +var renderer2; + +// src/class/audio/SoundManager.ts +var import_jszip2 = __toESM(require_lib(), 1); +var getSoundManager = () => sm; +var playSound = (sound) => getSoundManager().playSound(sound); + +class SoundManager { + soundBufs; + audioContext; + gainNode; + muted; + previousVolume; + constructor() { + this.soundBufs = {}; + this.audioContext = new (window.AudioContext || window.webkitAudioContext); + this.gainNode = this.audioContext.createGain(); + this.gainNode.connect(this.audioContext.destination); + this.muted = false; + this.previousVolume = 0.28; + this.queue = new Set; + const theme = document.documentElement.dataset.theme; + let currentTheme = theme; + document.addEventListener("theme-change", () => { + const theme2 = document.documentElement.dataset.theme; + if (theme2 !== currentTheme) { + loadBaseSounds("./assets/audio/miiMakerSwitch.zip"); + this.previousVolume = 0.28; + this.setVolume(0.28); + this.previousVolume = 0.28; + } + currentTheme = theme2; + }); + } + async loadSound(url, name2) { + const response = await fetch(url); + const arrayBuffer = await response.arrayBuffer(); + const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer); + this.soundBufs[name2] = audioBuffer; + } + async loadSoundBuffer(arrayBuffer, name2) { + const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer); + this.soundBufs[name2] = audioBuffer; + } + queue; + playSound(name2) { + const soundBuffer = this.soundBufs[name2]; + if (!soundBuffer) { + console.error(`Sound "${name2}" not found.`); + return; + } + if (this.queue.has(name2)) + return; + const source = this.audioContext.createBufferSource(); + source.buffer = soundBuffer; + source.connect(this.gainNode); + source.start(); + this.queue.add(name2); + setTimeout(() => { + this.queue.delete(name2); + }, 50); + } + setVolume(volume) { + if (this.muted) + return; + this.gainNode.gain.value = volume; + } + mute() { + if (this.muted) + return; + this.previousVolume = this.gainNode.gain.value; + this.setVolume(0); + this.muted = true; + } + unmute() { + if (this.muted === false) + return; + this.muted = false; + this.setVolume(this.previousVolume); + } +} +var sm = new SoundManager; +var loadBaseSounds = async (path = "./assets/audio/miiMakerSwitch.zip", smRef = sm) => { + const data2 = await fetch(path).then((j2) => j2.blob()); + const zip = await import_jszip2.default.loadAsync(data2); + let promises = []; + const fileList = Object.keys(zip.files); + for (const file of fileList) { + promises.push(zip.files[file].async("arraybuffer")); + } + const resolves = await Promise.all(promises); + for (let i = 0;i < fileList.length; i++) { + const fileName = fileList[i].split("."); + fileName.pop(); + await smRef.loadSoundBuffer(resolves[i], fileName.join(".")); + } +}; + +// src/helper.ts +var FFLModule; +var userData; +var helperRenderer = new WebGLRenderer({ alpha: true }); +var GUEST_MII_DATA = [ + "BAM5i2G9mwPpOoAAAADs/4LSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEEAAAAAAAAACAAAAAAAQAMDCAYEBgIKCAQEAgIMBAAAAP8ABAAACAQACggARP///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAOFdPR8ZsuhdoAAAAHs/4LSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEIAAAAAAAAACAAAAAAAQAMDBgYEBgIKDAQEAgIMAAAAAP8ABQAACAQACgYAN////0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAM2I3afbKlshYAAAALs/4LSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEMAAAAAAAAACAAAAAAAQAMDAQYEBgIKCAQEAgIMAQAAAP8AAAAACAQACgEAIf///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAN9s2CERcxd8IAAAAPs/4LSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEQAAAAAAAAACAAAAAAAQAMDCAYEAAIKCAMEBAIMAgAAAP8AAgABCAQACggAGP///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAP3BYyHQ6gZsoAAAATs/4LSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEUAAAAAAAAACAAAAAAAQAMDBwYEAAIKDQMEBAIMAAAAAP8ABgABCAQACgcADv///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BANfFfqpycZfsoAAAAXs/4LSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEYAAAAAAAAACAAAAAAAQAMDAQYEAAIKCAMEBAIMAAAAAP8ABwABCAQACgEADP///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAVIEyyDkVU1GYD/cJm7kTTHqf8AAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEcAAAAAAAAACAAAAAAAQAMDCAYEBgIKCAQEAgIMBQAAAP8ACwAACAQACggAKv///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAWUIlPmHJkY0oD/cJmB+j7p1g8AAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEgAAAAAAAAACAAAAAAAQAMDDgYEBgIKCQQEAgIMBwAAAP8ACQAACAQACg4APv///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAVlJYmsV8fzIID/cJmJvGY0ejIAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEkAAAAAAAAACAAAAAAAQAMDAwYEBgIKCAQEAgIMBgAAAP8AAQAACAQACgMAef///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BABEp+/5p6E6GoDfGZofZsl0BT8AAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEoAAAAAAAAACAAAAAAAQAMDCAYEAAIKCAMEBAIMCAAAAP8AAwABCAQACggAB////0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BABEp+/5p6E6GoDfGZofZsl0BT8AAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEsAAAAAAAAACAAAAAAAQAMDDgYEAAIKCwMEBAIMBwAAAP8ACgABCAQACg4AX////0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BABEp+/5p6E6GoDfGZofZsl0BT8AAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEwAAAAAAAAACAAAAAAAQAMDBgYEAAIKCAMEBAIMBgAAAP8ACAABCAQACgYADP///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==" +]; +function getFFLModule() { + return FFLModule; +} +var getAdditionalInfoFromMii = (miiData) => ({ + hatCommonColor: miiData.hatCommonColor, + hatFavoriteColor: miiData.hatFavoriteColor, + hatType: miiData.hatType, + pantsColor: miiData.pantsColor, + shirtColor: miiData.shirtColor, + favorite: miiData.favorite, + special: miiData.special, + temporary: miiData.temporary, + eyeSclera: miiData.eyeSclera, + clothesType: miiData.clothesType, + shoesColor: miiData.shoesColor, + wigType: miiData.wigType +}); +var root2; +try { + if (import.meta) { + root2 = new URL(import.meta.url); + } else { + throw new Error("HUH"); + } +} catch (e) { + alert("SCRIPT SCOPE"); +} +var soundManager; +async function loadAssets(resourcePath, bodyType2 = "wiiu") { + setRoot(root2.origin + "/"); + console.debug("Loading body models.."); + await loadBodyModels(bodyType2, true); + console.debug("Loading hat models.."); + await loadHatModels(); + console.debug("Loading clothing textures.."); + await loadClothesTextures(); + soundManager = new SoundManager; + console.debug("Loading sounds."); + await loadBaseSounds(root2.origin + "/assets/audio/miiSelector.zip", soundManager); + console.debug("Loaded all resources."); + FFLModule = (await Promise.resolve().then(() => __toESM(require_ffl_emscripten(), 1))).default; + FFLModule = await FFLModule({ + locateFile: (path) => { + return root2.origin + "/dist/" + path; + } + }); + let m = await initializeFFLWithResource(FFLModule, resourcePath); + FFLModule = m.module; + console.debug("Loaded FFL.js!"); +} + +class MiiCreatorCharModel { + miiGroup; + charModel; + headModel; + bodyModel; + bodyModelBody; + bodyModelHands; + bodyModelLegs; + mixer; + clips; + constructor() { + } + init(request) { + return new Promise((resolve) => { + setTimeout(async () => { + const { + bodyModel, + bodyModelAnims, + bodyModelBody, + bodyModelHands, + bodyModelLegs, + charModel, + headModel, + miiGroup + } = await createMiiRender({ + ...request, + module: FFLModule, + isTemporary: false, + renderer: request.renderer, + textureRenderer: helperRenderer, + clothingLinearColors: request.clothingLinearColors === undefined ? true : request.clothingLinearColors + }); + this.bodyModel = bodyModel; + this.bodyModelBody = bodyModelBody; + this.bodyModelHands = bodyModelHands; + this.bodyModelLegs = bodyModelLegs; + this.charModel = charModel; + this.headModel = headModel; + this.miiGroup = miiGroup; + if (request.useAnimation) { + this.mixer = new AnimationMixer(bodyModel); + this.clips = new Map; + for (const clip of bodyModelAnims) { + this.clips.set(clip.name, this.mixer.clipAction(clip)); + } + } + resolve(); + }, 0); + }); + } + subPosition; + subScale; + position; + quaternion; + scale; + mixerUpdate(delta) { + if (!this.subPosition) + this.subPosition = new Vector3; + if (!this.subScale) + this.subScale = new Vector3; + if (!this.position) + this.position = new Vector3; + if (!this.quaternion) + this.quaternion = new Quaternion; + if (!this.scale) + this.scale = new Vector3; + this.mixer.update(delta); + this.bodyModel.updateMatrixWorld(true); + let headBone = this.bodyModel.getObjectByName("head"); + if (headBone === undefined) + headBone = this.bodyModel.getObjectByName("Head"); + if (!headBone) + return alert("???"); + headBone.updateMatrixWorld(true); + this.miiGroup.getWorldPosition(this.subPosition); + headBone.matrixWorld.decompose(this.position, this.quaternion, this.scale); + if (this.headModel) { + this.headModel.position.copy(this.position); + this.miiGroup.worldToLocal(this.headModel.position); + this.headModel.setRotationFromQuaternion(this.quaternion); + } + } + setExpression(expression, force = false) { + if (force) { + this.headModel.traverse((n2) => { + const m = n2; + if (!m.isMesh) + return; + if (m.geometry.userData.modulateType !== FFLiShapeType.XLU_MASK) + return; + m.material.map = this.charModel._maskTargets[expression].texture; + }); + } else { + this.charModel.setExpression(expression); + } + } + getExpressions() { + return this.charModel._maskTargets.map((n2, i) => n2 !== null ? i : undefined).filter((n2) => n2 !== undefined); + } +} +function centerPopupWindow(url, title, w, h) { + const left = screen.width / 2 - w / 2; + const top = screen.height / 2 - h / 2; + return window.open(url, title, `width=${w}, height=${h}, top=${top}, left=${left}`); +} +var RequestType; +((RequestType2) => { + RequestType2["Library"] = "library"; + RequestType2["PersonalMiiOnly"] = "personal_mii_only"; +})(RequestType ||= {}); +function requestUserData(type, pageTitle = document.title) { + return new Promise((resolve) => { + let append = new URLSearchParams; + switch (type) { + case "library" /* Library */: + append.set("type", "library" /* Library */); + append.set("page_title", pageTitle); + break; + case "personal_mii_only" /* PersonalMiiOnly */: + append.set("type", "personal_mii_only" /* PersonalMiiOnly */); + append.set("page_title", pageTitle); + break; + default: + throw new Error("Invalid request type."); + } + centerPopupWindow(root2.origin + "/popup.html?" + append.toString(), "Mii Creator Login", 800, 600); + const messageListener = (event) => { + if (event.data === undefined) + return; + if (event.data.type === undefined) + return; + if (event.data.type !== "miic-auth-finalize") + return; + if (event.data.canceled === true) + return resolve({ canceled: true, data: null }); + window.removeEventListener("message", messageListener); + userData = event.data.data; + resolve({ canceled: false, data: event.data.data }); + }; + window.addEventListener("message", messageListener); + }); +} +function injectCss() { + if (Html.qs("head>#mii-creator-helper-styles") === null) { + new Html("style").id("mii-creator-helper-styles").html(css).appendTo("head"); + } +} +function requestMiiSelection() { + console.log("userData:", userData); + return new Promise((resolve) => { + if (userData === undefined) + return resolve(false); + if (userData.library === null) + return resolve(false); + injectCss(); + new Html("div").id("mii-creator-selector-modal").appendTo("body"); + miiSelectorSetFflModule(FFLModule); + miiSelectorSetRenderer(helperRenderer); + MiiSelector.open(userData.library.map((n2) => { + let type = 0 /* Regular */; + let mii = new Mii(n2.mii); + if (mii.favorite === 1) + type = 1 /* Favorite */; + if (mii.special === 1) + type = 2 /* Special */; + return { miiData: mii.export(), type }; + }), { + guestData: GUEST_MII_DATA, + soundManager, + personalMii: userData.personal_mii.data + }).then((MiiResult) => { + resolve(MiiResult); + }); + }); +} +export { + soundManager, + requestUserData, + parseHexOrB64ToUint8Array, + requestMiiSelection as miiSelect, + loadAssets, + getFFLModule, + getAdditionalInfoFromMii, + dataToHex, + dataToBase64, + createMiiRender, + ShaderType, + RequestType, + MiiCreatorCharModel, + Mii, + GUEST_MII_DATA, + ForbiddenShirtPantColors, + ExtHatNameList, + BodyType +}; diff --git a/public/dist/icons.json b/public/dist/icons.json index f915f9c..642179b 100644 --- a/public/dist/icons.json +++ b/public/dist/icons.json @@ -1,17 +1,17 @@ { "face": [ - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n" + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" ], "makeup": [ "\r\n\r\n\r\n\r\n\r\n", @@ -42,92 +42,92 @@ "\r\n\r\n\r\n\r\n\r\n" ], "eyebrows": [ - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n" + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n" ], "eyes": [ - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n" + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", + "\n\n\n\n\n\n\n\n\n\n\n\n" ], "nose": [ "\r\n\r\n\r\n\r\n\r\n", @@ -188,154 +188,154 @@ "\r\n\r\n\r\n\r\n\r\n" ], "mustache": [ - "\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n" + "\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" ], "goatee": [ - "\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n\n" + "\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n" ], "hair": [ - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n", - "\n\n\n\n\n\n\n\n\n" + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n", + "\n\n\n\n\n\n\n\n\n" ], "glasses": [ "\r\n\r\n\r\n\r\n\r\n", @@ -348,7 +348,7 @@ "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n\r\n\r\n\r\n\r\n\r\n", - "\n\n\n\n\n\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n\r\n\r\n\r\n\r\n\r\n", "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n", @@ -360,14 +360,15 @@ "\r\n\r\n\r\n\r\n\r\n\r\n" ], "hat": [ - "\n\n\n\n\n\n", - "\n\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n\n", - "\n\n\n\n", - "\n\n \n \n \n \n
\n", - "\n \n \n \n \n", - "\n\n \n \n \n \n", - "\n \n \n \n \n" + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n\r\n", + "\r\n\r\n\r\n\r\n", + "\r\n\r\n \r\n \r\n \r\n \r\n \r\n", + "\r\n \r\n \r\n \r\n \r\n", + "\r\n\r\n \r\n \r\n \r\n \r\n", + "\r\n \r\n \r\n \r\n \r\n", + "\r\n \r\n \r\n\r\n" ] } \ No newline at end of file diff --git a/public/dist/lang/en_US.js b/public/dist/lang/en_US.js deleted file mode 100644 index b716c96..0000000 --- a/public/dist/lang/en_US.js +++ /dev/null @@ -1,2 +0,0 @@ -var b={languages:{en_US:"English (US)"},actions:{disable:"Disable",enable:"Enable",edit:"Edit",delete:"Delete",export_download:"Export/Download",render:"Render",no:"No",yes:"Yes",save_and_exit:"Save & Exit",exit_without_saving:"Exit without Saving",download:"Download"},generic:{app_title:"Mii Creator",camera:"Camera",useMouseOrTouch:"Use mouse or touch to move the camera.",pose:"Pose",expression:"Expression",render:"Render",resolution_width:"Width",resolution_height:"Height",camera_field_of_view:"Camera FOV"},alert:{audio_requires_action:{title:"Audio needs action",description:"Music will start playing on first click. You can press V to change sound volume (default is 0.35)"},delete_confirmation:{title:"Warning",description:"Are you sure you want to delete this Mii?"},choice:"What would you like to do?"},pages:{mainMenu:{title:"Main Menu"},library:{title:"Mii Library",options:"Mii Options",credits:{title:"Credits",view:"View Credits",datkat21:"Source code by datkat21",ariankordi:"Mii Rendering API by ariankordi",objecty:"Mii Maker Music by objecty",localization:"%lang% by %author%",general:"General",translators:"Translators"},export:{title:"Mii Export",description:"How would you like to save the Mii?",get_ffsd_hex:"Get FFSD (Hex)",get_ffsd_b64:"Get FFSD (Base64)",save_ffsd_file:"Save FFSD (file)",save_miic_file:"Save MiiCreator data",get_mii_studio_data:"Get Mii Studio data",ffsd_modal:"FFSD code",mii_studio_data_modal:"Mii Studio data",generate_qr:"Generate QR code",render_image:"Render an image",render_headshot:"Headshot",render_full_body:"Full body",render_head_only:"Head only",custom_render:"Make your own render"},custom_render:{title:"Prepare Render",head:"Head",full_body:"Full Body",pose_unfinished_warning:"This section is a bit unfinished, the poses are custom-made recreations so they are not fully accurate. Pose 3 also has a rotation issue with the head since it has been changed to be pretending to be attached to the body to prevent weird scaling issues. There is also nothing done after pose 4 currently. I'm working on a way to add the Wii U poses directly.",render_unfinished_warning:"Render resolution options will be here when the feature is ready.",idle:"Idle",pose:"Pose %n%"}},editor:{choice:{color:"Color",favorite:"Favorite",gender:"Gender",goatee:"Goatee",hat_color:"Hat Color",hat:"Hat",mustache:"Mustache",normal:"Normal",position:"Position",special:"Special",type:"Type"},quit:{title:"Quitting Editor",description_no_changes:"No changes were made. Are you sure you want to exit?",description_changes_made:"Would you like to save?"},warning_custom:`%custom% is a CUSTOM property, and will not transfer to any other data formats. -It is purely visual and provided for the ability to use in renders.`},saveData:{title:"Save Data",import:"Import Save Data",export:"Export Save Data"},settings:{title:"Settings",settings_bgm:"Background Music",settings_sfx:"Sound Effects"}}};export{b as default}; diff --git a/public/dist/lang/es.json b/public/dist/lang/es.json new file mode 100644 index 0000000..9c8517c --- /dev/null +++ b/public/dist/lang/es.json @@ -0,0 +1 @@ +{"":{"content-type":"text/plain; charset=UTF-8"},"(Default)":[null,""],"(Open the camera for more options)":[null,""],"(Random)":[null,""],"%1 is a CUSTOM property, and will not transfer to any other data formats.":[null,""],"2D":[null,""],"3D":[null,""],"3DS/Wii U QR Code":[null,""],"Adult":[null,""],"Age":[null,""],"All of the options here are what Nintendo originally programmed in. Please let me know if you want more options added.":[null,""],"all_body":[null,""],"Allow using camera in QR scanner":[null,""],"An error occurred when reading the data.\nPlease check the console for more information.":[null,""],"Animation":[null,""],"Are you sure you want to delete this Mii?":[null,""],"Arian":[null,""],"Asian":[null,""],"Auburn":[null,""],"Austin☆²¹ / Kat21":[null,""],"Auto-close custom render menu":[null,""],"Auto-close QR scan menu":[null,""],"Back Camera (default)":[null,""],"Black":[null,""],"Blue":[null,""],"Body Model":[null,""],"Brown":[null,""],"Camera":[null,""],"Camera is disabled in settings.\n\nUpload an image:":[null,""],"Center horizontally":[null,""],"Center vertically":[null,""],"Change the Body Model option in Settings to get many different options of poses!":[null,""],"Change the lighting used in icons, renders and the editor.":[null,""],"Changes the default edit mode option.":[null,""],"Check out the people behind Mii Creator!":[null,""],"Child":[null,""],"Choose a look-alike":[null,""],"Click any to reroll":[null,""],"Click here":[null,""],"Close":[null,""],"Color hands to skin tone":[null,""],"Composed the music for Mii Creator":[null,""],"Confirm":[null,""],"Control the animation speed.":[null,""],"Couldn't get Mii: $1":[null,""],"Create Mii":[null,""],"Creator of Mii Renderer (REAL), made FFL.js and ported Miitomo shader, and was a big help with debugging many issues":[null,""],"Credits":[null,""],"Custom":[null,""],"Cyan":[null,""],"David J.":[null,""],"Delete":[null,""],"Disabled":[null,""],"Discord":[null,""],"Do you like the Mii that does the poses? His name is \"dummy\".":[null,""],"Done":[null,""],"Down":[null,""],"Download 3D model":[null,""],"Download a copy":[null,""],"Download a copy (Base64 encoded)":[null,""],"Download PNG":[null,""],"E-mail (Preferred)":[null,""],"Editing Mode":[null,""],"Elder":[null,""],"Enable accessibility features":[null,""],"Enable background music":[null,""],"Enable sound effects":[null,""],"Enter Nintendo Network ID":[null,""],"Enter NNID of user..":[null,""],"Enter NNID/PNID":[null,""],"Enter PNID of user..":[null,""],"Enter Pretendo Network ID":[null,""],"Error":[null,""],"Export":[null,""],"Expression":[null,""],"Eye color":[null,""],"Failed to load %1's icon":[null,""],"Favorite color":[null,""],"Female":[null,""],"File an issue on GitHub":[null,""],"From Scratch":[null,""],"Gender":[null,""],"Gray":[null,""],"Green":[null,""],"Hair color":[null,""],"Hat":[null,""],"Hat color":[null,""],"Hat Color":[null,""],"Hat type":[null,""],"Hazel":[null,""],"Helped with design, localization, and created the Wii U theme":[null,""],"Here's where you can contact the author, Kat21":[null,""],"How would you like to create the Mii?":[null,""],"Icons won't be affected until you reload.":[null,""],"Import":[null,""],"Import Mii data file(s) here. Supported formats: .ffsd/.cfsd, .miic, .charinfo, .rsd":[null,""],"Invalid Mii data: $1":[null,""],"Is this OK?":[null,""],"It appears that %1 of your Miis have failed to load. Their data may be corrupted.\n\nIf you'd like to try and recover the Mii data, you can select the Miis with errors and choose to either save a copy or delete them.":[null,""],"Lead developer of Mii Creator":[null,""],"Left":[null,""],"Light-blonde":[null,""],"Lime":[null,""],"Major Update":[null,""],"Male":[null,""],"Medium-blonde":[null,""],"Mii Creator":[null,""],"Mii Creator (Special Mii)":[null,""],"Mii Creator is loading assets, please wait...":[null,""],"Mii Creator QR Code":[null,""],"Mii data file":[null,""],"Mii data files import":[null,""],"Mii data type not supported ($1 bytes)":[null,""],"Mii QR Scanned":[null,""],"Mii Renderer (REAL)":[null,""],"Miitomo":[null,""],"Modeled many of the custom hats and helped with debugging":[null,""],"Nintendo Network ID":[null,""],"No":[null,""],"No Lighting":[null,""],"Normal":[null,""],"Not implemented yet.":[null,""],"Notice":[null,""],"obj":[null,""],"Olive":[null,""],"Or upload an image:":[null,""],"Orange":[null,""],"Pause Animation":[null,""],"Pink":[null,""],"Play Animation":[null,""],"Pose":[null,""],"Pose selections are different depending on the body model you use.":[null,""],"Position":[null,""],"Pretendo Network ID":[null,""],"Purple":[null,""],"QR Code":[null,""],"Random NNID":[null,""],"Red":[null,""],"Refresh to apply changes":[null,""],"Reset":[null,""],"Review update notice":[null,""],"Revise":[null,""],"Right":[null,""],"Rotate":[null,""],"Save Data":[null,""],"Scan QR Code":[null,""],"secret?":[null,""],"Select a service to look up":[null,""],"Select camera:":[null,""],"Select the Mii's gender":[null,""],"Selection library is currently not implemented yet":[null,""],"Settings":[null,""],"Shader Type":[null,""],"Skin tone":[null,""],"Sorry, but you can't use this feature because 3D mode is disabled at the moment.":[null,""],"Start camera":[null,""],"Stop camera":[null,""],"Switch (WIP)":[null,""],"The custom render menu will automatically close when pressing save.":[null,""],"The custom render will have a solid color background.":[null,""],"The editor UI will be tweaked to be more accessible.":[null,""],"The hands of the body will match the Mii's skin tone.":[null,""],"The QR code scanner will disappear after a successful scan.":[null,""],"Theme":[null,""],"This Mii is using extended Switch colors and/or Mii Creator features, but those features will be lost when converting to FFSD.\nUse \"Save Mii Creator data\" if you want to keep the data.\nIs this OK?":[null,""],"This Mii is using extended Switch colors, but those colors will never show up if you scan this QR Code anywhere outside of this app. Is this OK?":[null,""],"This Mii might be corrupted. Choose an option below.":[null,""],"This site is not affiliated with Nintendo.":[null,""],"Timothy":[null,""],"to obtain him in your library :)":[null,""],"Toggle background music depending on the theme.":[null,""],"Toggle sound effects for buttons and inputs.":[null,""],"Tomodachi Life QR codes aren't supported yet. Use $1 to scan it.":[null,""],"Toon":[null,""],"Up":[null,""],"Update Notices":[null,""],"Use background in custom render":[null,""],"Use mouse or touch to move the camera around.\nUsing touch, rotate the camera around with one finger, and drag with two fingers to pan. Pinch with two fingers to zoom.\nIf you like this site, please consider sharing it with others and credit me or the site when you post your renders! 🙂":[null,""],"User/Front Facing Camera":[null,""],"Username":[null,""],"View the last update notice if you missed it.":[null,""],"Warning":[null,""],"When this is disabled, the camera won't be used and some errors may not appear.":[null,""],"When this is set to Normal, your device's color theme preferences will be used.":[null,""],"White":[null,""],"Wii U":[null,""],"Wii U (Blinn)":[null,""],"Wii U (Bright)":[null,""],"Yellow":[null,""],"Yes":[null,""],"You can't use this feature":[null,""],"You have no Miis yet. Create one to get started!":[null,""],"You're using Mii Creator under Firefox. Using the Firefox browser WILL experience slowdowns and lag.":[null,""],"Your browser doesn't support OffscreenCanvas, so Mii Creator may experience lag.":[null,""],"Your browser doesn't support Web Workers, so Mii Creator may experience lag.":[null,""]} \ No newline at end of file diff --git a/public/dist/main.css b/public/dist/main.css index 11ac329..31fc9a8 100644 --- a/public/dist/main.css +++ b/public/dist/main.css @@ -1,334 +1,3 @@ -:root[data-theme=wiiu] { - background-image: url(../assets/images/bg_qr_wiiu.png) !important; - background-repeat: no-repeat !important; - background-size: cover !important; - height: 100% !important; -} -:root[data-theme=wiiu] html, -:root[data-theme=wiiu] body { - background-color: transparent !important; - --root: #ffffff; - --text: #000000; - --label: #666666; - --stroke: #dddddd; - --stroke-rgb: 221, 221, 221; - --container: #eeeeee; - --sub-container: #ececec; - --hover: #dddddd; - --focus: #e7e7e7; - --icon-face-fill: #ffffff; - --icon-face-stroke: #6f6f6f; - --icon-face-detail: #8d8d8d; - --icon-face-makeup: #ffbaba; - --icon-face-wrinkles: #996d54; - --icon-head-fill: #ffffff; - --icon-head-stroke: #999999; - --icon-hair-fill: currentColor; - --icon-eyebrow-fill: currentColor; - --icon-facial-hair-fill: currentColor; - --icon-mouth-tooth: #ffffff; - --icon-glasses-fill: #000000; - --icon-glasses-shade: #606060; - --icon-lip-color-top: #712a04; - --icon-lip-color-bottom: #be4e26; - color: black !important; -} -:root[data-theme=wiiu] div::-webkit-scrollbar-thumb { - border-radius: 10px !important; - background-color: rgb(51, 183, 53) !important; -} -:root[data-theme=wiiu] div::-webkit-scrollbar-track { - border-radius: 10px !important; - background-color: transparent !important; -} -:root[data-theme=wiiu] .modal .modal-content { - min-width: 300px !important; -} -:root[data-theme=wiiu] .modal .modal-content button { - font-size: 17px !important; -} -:root[data-theme=wiiu] .modal .modal-content .modal-header { - background: linear-gradient(0deg, #6b6b6b 3%, #9d9d9d 0%, #b1b1b1 100%) !important; - padding-bottom: 10px !important; - color: #fff !important; - text-shadow: 0px -1px 0px #4e4e4e !important; - font-size: 1.15rem !important; -} -:root[data-theme=wiiu] .modal .modal-content .modal-header .close-button { - background: var(--error-color) !important; - box-shadow: #ff2b2b 0px 0px 2px 1px inset, 0px -1px 0px 0px rgb(255, 255, 255) !important; - position: absolute !important; -} -:root[data-theme=wiiu] .modal .modal-content .modal-body img { - box-shadow: 0px 0.5px 4px 1px rgba(0, 0, 0, 0.25); - background: linear-gradient(#f6f6f6 0%, #ffffff 15%, #ffffff 45%, #f6f6f6 45%, #fcfcfc 100%) !important; - margin: 5px; - border-radius: 7px !important; -} -:root[data-theme=wiiu] .flex-group { - gap: 1rem !important; -} -:root[data-theme=wiiu] button { - background: linear-gradient(#d1d1d1 5%, #ffffff 100%) !important; - border: none !important; - text-shadow: 0px 1px #fff !important; - box-shadow: #d1d1d1 0px 2px 3px 1px inset, 0px 0.5px 3px 1px rgba(133, 133, 133, 0.71) !important; - position: relative; - z-index: 1 !important; - font-size: 18px !important; - transition: 0.1s !important; -} -:root[data-theme=wiiu] button:not(.close-button):before { - content: ""; - width: 100%; - display: block; - top: 0; - left: 0; - position: absolute; - height: 40%; - border-radius: 20px; - border-bottom-left-radius: 30px; - border-bottom-right-radius: 30px; - background: linear-gradient(rgb(243, 243, 243), rgb(243, 243, 243)); - z-index: -1; -} -:root[data-theme=wiiu] button:focus { - box-shadow: #d1d1d1 0px 2px 3px 1px inset, 0px 0.5px 3px 1px rgba(133, 133, 133, 0.71) !important; -} -:root[data-theme=wiiu] input { - box-shadow: 0px 2px 3px -1px #d2d2d2 inset; - border: 2px solid #bcbcbc; -} -:root[data-theme=wiiu] input:hover { - background-color: #f5f5f5; - outline: 0; -} -:root[data-theme=wiiu] input[type=range] { - box-shadow: none; -} -:root[data-theme=wiiu] .ui-base { - background-color: unset !important; -} -@media screen and (max-width: 960px) { - :root[data-theme=wiiu] .ui-base .tab-list { - background: linear-gradient(#a6ff5e 5%, #02f21c 100%) !important; - } -} -:root[data-theme=wiiu] .ui-base .mii-holder { - background-color: rgba(255, 255, 255, 0.2) !important; - backdrop-filter: blur(3px) !important; - margin-bottom: -1rem; -} -:root[data-theme=wiiu] .ui-base .tab-list { - grid-area: tabList !important; - background: linear-gradient(to right, #a6ff5e 5%, #02f21c 100%) !important; - box-shadow: #2bd500 0px 0px 4px 2px inset, 0px 0.5px 3px 1px rgba(133, 133, 133, 0.42) !important; -} -:root[data-theme=wiiu] .ui-base .tab-list .tab:hover { - background-color: rgba(0, 0, 0, 0.15) !important; -} -:root[data-theme=wiiu] .ui-base .tab-list .tab.tab-square > svg { - color: #ffffff !important; - filter: drop-shadow(0px -2px 0px #1e9500) !important; -} -:root[data-theme=wiiu] .ui-base .tab-list .tab.tab-square.active { - background-color: #42f839 !important; - box-shadow: 0 0 0 0.3rem rgb(51, 183, 53) !important; -} -:root[data-theme=wiiu] .ui-base .tab-list .tab.tab-square.active { - box-shadow: 0 0 0 0.3rem rgb(51, 183, 53) !important; -} -:root[data-theme=wiiu] .ui-base .tab-list .tab.tab-save { - background: linear-gradient(#e6e600 5%, #fffb7e 100%) !important; - text-shadow: 0 1px #f3ff6a !important; - border: none !important; - box-shadow: #d1d1d1 0px 2px 3px 1px inset, 0px 0.5px 3px 1px rgba(133, 133, 133, 0.71) !important; - position: relative; - z-index: 1 !important; - font-size: 18px !important; - transition: 0.1s !important; - color: #000000 !important; -} -:root[data-theme=wiiu] .ui-base .tab-list .tab.tab-save span { - text-shadow: 0 2px 0px rgba(255, 255, 255, 0.3333333333) !important; -} -:root[data-theme=wiiu] .ui-base .tab-list .tab.tab-save svg { - color: #000000 !important; - filter: drop-shadow(0 2px 0px rgba(255, 255, 255, 0.3333333333)) !important; -} -:root[data-theme=wiiu] .ui-base .tab-list .tab.tab-save::before { - content: ""; - width: 100%; - display: block; - top: 0; - left: 0; - position: absolute; - height: 40%; - border-radius: 20px; - border-bottom-left-radius: 30px; - border-bottom-right-radius: 30px; - background: linear-gradient(rgb(255, 251, 183), rgb(251, 255, 114)) !important; - z-index: -1; -} -:root[data-theme=wiiu] .ui-base .tab-list .tab.tab-save::after { - background-color: rgba(0, 0, 0, 0.45) !important; -} -:root[data-theme=wiiu] .ui-base .tab-content .feature-set-container .tab-list { - position: relative !important; - z-index: 2 !important; - border-radius: 5px !important; - background: linear-gradient(#e6e600 5%, #fffb7e 100%) !important; - box-shadow: #f1da00 0px 1px 3px 4px inset, 0px 0.5px 3px 1px rgba(133, 133, 133, 0.42) !important; -} -:root[data-theme=wiiu] .ui-base .tab-content .feature-set-container .tab-list::before { - content: "" !important; - width: 98.5% !important; - display: block !important; - top: 4px !important; - left: 3px !important; - position: absolute !important; - height: 40% !important; - border-radius: 5px !important; - border-bottom-left-radius: 30px !important; - border-bottom-right-radius: 30px !important; - background: linear-gradient(rgb(255, 251, 183), rgb(251, 255, 114)) !important; - z-index: -1 !important; -} -:root[data-theme=wiiu] .ui-base .tab::after { - background-color: rgba(0, 0, 0, 0.45) !important; -} -:root[data-theme=wiiu] .tab-content { - background-color: transparent !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group { - gap: 18px !important; - padding-top: 20px !important; - padding-bottom: 40px !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-set-header { - background: rgba(225, 225, 225, 0.25) !important; - backdrop-filter: blur(8px) !important; - border: 1px solid #a2a2a2 !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-switch .feature-switch-left, -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-switch .feature-switch-right { - padding: 8px 20px !important; - border-right-width: unset !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-switch .feature-switch-left.active, -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-switch .feature-switch-right.active { - background: linear-gradient(#e6e600 5%, #fffb7e 100%) !important; - box-shadow: #f1da00 0px 1px 3px 4px inset, 0px 0.5px 3px 1px rgba(133, 133, 133, 0.42) !important; -} -:root[data-theme=wiiu] button.selected, -:root[data-theme=wiiu] button.selected-setting { - background: linear-gradient(#e6e600 5%, #fffb7e 100%) !important; - text-shadow: 0 1px #f3ff6a !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-switch .feature-switch-left:before, -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-switch .feature-switch-right:before { - content: "" !important; - width: 93% !important; - display: block !important; - top: 4px !important; - left: 3px !important; - position: absolute !important; - height: 40% !important; - border-radius: 5px !important; - border-bottom-left-radius: 30px !important; - border-bottom-right-radius: 30px !important; - z-index: -1 !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-switch .feature-switch-left.active:before, -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-switch .feature-switch-right.active:before, -:root[data-theme=wiiu] button.selected::before, -:root[data-theme=wiiu] button.selected-setting::before { - background: linear-gradient(rgb(255, 251, 183), rgb(251, 255, 114)) !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-switch .feature-switch-left svg, -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-switch .feature-switch-right svg { - width: 60px; - height: 60px; - filter: drop-shadow(0px -2px 0px #fff) !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-switch .feature-switch-left.active svg, -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-switch .feature-switch-right.active svg { - filter: drop-shadow(0px -2px 0px rgb(251, 255, 114)) !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-item { - min-width: 66px !important; - min-height: 66px !important; - cursor: unset !important; - background: linear-gradient(#dedede 0%, #ffffff 50%) !important; - box-shadow: 0px -2px #fff, 0px 2px #aeaeae, 0px 0px 4px #8c8c8c !important; - transition: 0.1s !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-item > svg { - width: 65px !important; - height: 65px !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-item:hover { - transform: scale(1.1) !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-item.active { - background: linear-gradient(#7cff55 0%, #dbffbf 50%) !important; - box-shadow: 0px -2px 0px #d9ffd9, 0px 2px 0px #00bc09, 0px 0px 4px #8c8c8c !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-slider span, -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-range span { - background: linear-gradient(#dedede 0%, #ffffff 50%) !important; - box-shadow: 0px -2px #fff, 0px 2px #aeaeae, 0px 0px 4px #8c8c8c !important; - transition: 0.1s !important; - border-radius: 5px !important; - padding: 3px 6px !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-slider span:active, -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-range span:active { - transform: scale(1.1) !important; -} -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-slider span svg, -:root[data-theme=wiiu] .tab-content .feature-set-group .feature-range span svg { - filter: drop-shadow(0px -2px 0px #fff) !important; -} -:root[data-theme=wiiu] .mii-library .library-sidebar { - background: rgba(255, 255, 255, 0.5) !important; - box-shadow: 1px 0px 3px rgba(0, 0, 0, 0.15) !important; - backdrop-filter: blur(5px) !important; -} -:root[data-theme=wiiu] .mii-library .library-sidebar > h1 { - text-shadow: 0px 5px rgba(0, 0, 0, 0.08) !important; -} -:root[data-theme=wiiu] .mii-library .library-sidebar .sidebar-credits span { - font-size: 1rem !important; - padding-top: 4px !important; - padding-bottom: 4px !important; - margin-bottom: 3px !important; - width: 100% !important; - border-bottom: 1.5px dashed var(--label) !important; -} -:root[data-theme=wiiu] .mii-library .library-list .library-list-mii { - position: relative !important; - background: linear-gradient(#f6f6f6 0%, #ffffff 15%, #ffffff 45%, #f6f6f6 45%, #fcfcfc 100%) !important; - z-index: 10; - box-shadow: 0px 0px 4px 1px rgba(0, 0, 0, 0.2); -} -:root[data-theme=wiiu] .mii-library .library-list .library-list-mii.highlight { - box-shadow: 0px 0px 4px 1px rgba(0, 0, 0, 0.2), 0 0 0 0.3rem var(--selection-color) !important; -} -:root[data-theme=wiiu] .mii-library .library-list .library-list-mii span { - background: #707070 !important; - color: #fff !important; - text-shadow: 0px -2px #373737 !important; - box-shadow: 0px 0px 5px 0px #2d2d2d inset !important; -} -@media screen and (max-width: 960px) { - :root[data-theme=wiiu] .mii-library .library-sidebar button:not(.close-button):before { - border-radius: 10px !important; - border-bottom-left-radius: 30px !important; - border-bottom-right-radius: 30px !important; - } -} - @font-face { font-family: "NTLG"; src: url("../assets/fonts/NTLG.woff2"); @@ -543,22 +212,42 @@ h6 { opacity: 1; } } -@keyframes shortSlideUp { +@keyframes fadeOut { from { - transform: translateY(-25%); + opacity: 1; } to { - transform: translateY(0); + opacity: 0; } } -@keyframes fadeOut { +@keyframes slideIn { from { + transform: translateX(-100%); + opacity: 0; + } + to { + transform: translateX(0); + opacity: 1; + } +} +@keyframes slideOut { + from { + transform: translateX(0); opacity: 1; } to { + transform: translateX(-50%); opacity: 0; } } +@keyframes shortSlideUp { + from { + transform: translateY(-25%); + } + to { + transform: translateY(0); + } +} @keyframes shortSlideDown { from { transform: translateY(0); @@ -673,7 +362,8 @@ h6 { text-align: center; } .modal.random-mii-grid .modal-content { - max-height: 720px; + height: 720px; + max-height: 100vh; width: 1280px; } .modal.random-mii-grid .modal-content .modal-body .random-mii-container { @@ -832,6 +522,16 @@ select[type=checkbox]:checked { animation: fadeOut 0.8s cubic-bezier(0.16, 1, 0.3, 1) !important; } +.slideIn { + pointer-events: none; + animation: slideIn 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) forwards; +} + +.slideOut { + pointer-events: none; + animation: slideOut 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) forwards; +} + .loader { position: absolute; top: 50%; @@ -874,6 +574,30 @@ select[type=checkbox]:checked { margin: 0; } +.separator-gap-thin-laptop { + display: none; +} + +@media screen and (min-width: 1556px) { + .separator-gap-thin-laptop { + display: block !important; + width: 100%; + height: 0; + margin: 0; + } +} +.separator-gap-thin-desktop { + display: none; +} + +@media screen and (min-width: 1875px) { + .separator-gap-thin-desktop { + display: block !important; + width: 100%; + height: 0; + margin: 0; + } +} .ui-base { position: fixed; top: 0; @@ -895,7 +619,7 @@ select[type=checkbox]:checked { pointer-events: none; animation: fadeOut 0.8s cubic-bezier(0.16, 1, 0.3, 1) !important; } -@media screen and (max-width: 960px) { +@media screen and (max-width: 959px) { .ui-base { grid-template-areas: "mii" "tabList" "tabContent"; grid-template-columns: auto; @@ -925,7 +649,7 @@ select[type=checkbox]:checked { max-height: 30vmax; } } -@media screen and (min-width: 960px) and (max-width: 1280px) { +@media screen and (min-width: 960px) and (max-width: 1875px) { .ui-base { grid-template-areas: "tabList tabList" "mii tabContent"; grid-template-columns: 1fr 1fr; @@ -980,6 +704,14 @@ select[type=checkbox]:checked { border: 2px solid var(--stroke-dim); } +canvas.scene { + width: 100% !important; + height: 100% !important; + object-fit: contain; + overflow: hidden; + transition: opacity 0.5s cubic-bezier(0.215, 0.61, 0.355, 1); +} + .tab-save { width: max-content !important; gap: 8px; @@ -1249,6 +981,9 @@ select[type=checkbox]:checked { width: 100%; object-fit: contain; aspect-ratio: 1/1; + --scale: 0.1rem; + --blur: 0; + --color: rgba(255,255,255); } .mii-library .library-list .library-list-mii span { width: 100%; @@ -1269,7 +1004,7 @@ select[type=checkbox]:checked { background-image: linear-gradient(180deg, rgba(255, 255, 255, 0.4666666667), rgba(255, 255, 255, 0.4666666667)); } } -@media screen and (max-width: 960px) { +@media screen and (max-width: 959px) { .mii-library { grid-template-areas: "miiList miiList" "sidebar sidebar"; grid-template-rows: 1fr auto; @@ -1295,4 +1030,43 @@ select[type=checkbox]:checked { .responsive-row-lg { flex-direction: row !important; } +} +.notify-box { + display: flex; + flex-direction: column-reverse; + position: fixed; + z-index: 9999999999; + top: 1.5rem; + left: 1.5rem; + gap: 1rem; +} +.notify-box > .notify { + background-color: var(--container); + border: 0.125rem solid var(--stroke); + border-radius: 0.32rem; + padding: 0.9rem 1rem; + min-width: 18rem; + display: flex; + flex-direction: column; + gap: 0.5rem; + backdrop-filter: blur(0.5rem) brightness(0.5) contrast(1.05); + pointer-events: all; + width: max-content; +} +.notify-box > .notify .notify-title { + font-size: 1.25rem; + color: var(--text); +} +.notify-box > .notify .notify-description { + /* . . . */ + opacity: 1; +} + +.disable-item { + width: 120px; + font-size: 20px; + min-height: 48px; + display: flex; + justify-content: center; + align-items: center; } \ No newline at end of file diff --git a/public/dist/main.js b/public/dist/main.js index 93985da..d646edd 100644 --- a/public/dist/main.js +++ b/public/dist/main.js @@ -1,11312 +1,182899 @@ -var Bo=Object.create;var{getPrototypeOf:Xo,defineProperty:zY,getOwnPropertyNames:rM,getOwnPropertyDescriptor:Eo}=Object,tM=Object.prototype.hasOwnProperty;var j2=(A,Q,J)=>{J=A!=null?Bo(Xo(A)):{};let K=Q||!A||!A.__esModule?zY(J,"default",{value:A,enumerable:!0}):J;for(let C of rM(A))if(!tM.call(K,C))zY(K,C,{get:()=>A[C],enumerable:!0});return K},aM=/*@__PURE__*/new WeakMap,y4=(A)=>{var Q=aM.get(A),J;if(Q)return Q;if(Q=zY({},"__esModule",{value:!0}),A&&typeof A==="object"||typeof A==="function")rM(A).map((K)=>!tM.call(Q,K)&&zY(Q,K,{get:()=>A[K],enumerable:!(J=Eo(A,K))||J.enumerable}));return aM.set(A,Q),Q},B0=(A,Q)=>()=>(Q||A((Q={exports:{}}).exports,Q),Q.exports);var z3=(A,Q)=>{for(var J in Q)zY(A,J,{get:Q[J],enumerable:!0,configurable:!0,set:(K)=>Q[J]=()=>K})};var hJ=(A,Q)=>()=>(A&&(Q=A(A=0)),Q);var KX=/*@__PURE__*/((A)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(A,{get:(Q,J)=>(typeof require!=="undefined"?require:Q)[J]}):A)(function(A){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+A+'" is not supported')});var Qw=B0((No)=>{No.byteLength=Ho;No.toByteArray=Wo;No.fromByteArray=Oo;var h5=[],F9=[],$o=typeof Uint8Array!=="undefined"?Uint8Array:Array,gI="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(h4=0,eM=gI.length;h40)throw new Error("Invalid string. Length must be a multiple of 4");var J=A.indexOf("=");if(J===-1)J=Q;var K=J===Q?0:4-J%4;return[J,K]}function Ho(A){var Q=Aw(A),J=Q[0],K=Q[1];return(J+K)*3/4-K}function Go(A,Q,J){return(Q+J)*3/4-J}function Wo(A){var Q,J=Aw(A),K=J[0],C=J[1],U=new $o(Go(A,K,C)),Y=0,Z=C>0?K-4:K,X;for(X=0;X>16&255,U[Y++]=Q>>8&255,U[Y++]=Q&255;if(C===2)Q=F9[A.charCodeAt(X)]<<2|F9[A.charCodeAt(X+1)]>>4,U[Y++]=Q&255;if(C===1)Q=F9[A.charCodeAt(X)]<<10|F9[A.charCodeAt(X+1)]<<4|F9[A.charCodeAt(X+2)]>>2,U[Y++]=Q>>8&255,U[Y++]=Q&255;return U}function Io(A){return h5[A>>18&63]+h5[A>>12&63]+h5[A>>6&63]+h5[A&63]}function qo(A,Q,J){var K,C=[];for(var U=Q;UZ?Z:Y+U));if(K===1)Q=A[J-1],C.push(h5[Q>>2]+h5[Q<<4&63]+"==");else if(K===2)Q=(A[J-2]<<8)+A[J-1],C.push(h5[Q>>10]+h5[Q>>4&63]+h5[Q<<2&63]+"=");return C.join("")}});var Jw=B0((zo)=>{/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */zo.read=function(A,Q,J,K,C){var U,Y,Z=C*8-K-1,X=(1<>1,H=-7,$=J?C-1:0,I=J?-1:1,N=A[Q+$];$+=I,U=N&(1<<-H)-1,N>>=-H,H+=Z;for(;H>0;U=U*256+A[Q+$],$+=I,H-=8);Y=U&(1<<-H)-1,U>>=-H,H+=K;for(;H>0;Y=Y*256+A[Q+$],$+=I,H-=8);if(U===0)U=1-E;else if(U===X)return Y?NaN:(N?-1:1)*(1/0);else Y=Y+Math.pow(2,K),U=U-E;return(N?-1:1)*Y*Math.pow(2,U-K)};zo.write=function(A,Q,J,K,C,U){var Y,Z,X,E=U*8-C-1,H=(1<>1,I=C===23?Math.pow(2,-24)-Math.pow(2,-77):0,N=K?0:U-1,F=K?1:-1,V=Q<0||Q===0&&1/Q<0?1:0;if(Q=Math.abs(Q),isNaN(Q)||Q===1/0)Z=isNaN(Q)?1:0,Y=H;else{if(Y=Math.floor(Math.log(Q)/Math.LN2),Q*(X=Math.pow(2,-Y))<1)Y--,X*=2;if(Y+$>=1)Q+=I/X;else Q+=I*Math.pow(2,1-$);if(Q*X>=2)Y++,X/=2;if(Y+$>=H)Z=0,Y=H;else if(Y+$>=1)Z=(Q*X-1)*Math.pow(2,C),Y=Y+$;else Z=Q*Math.pow(2,$-1)*Math.pow(2,C),Y=0}for(;C>=8;A[J+N]=Z&255,N+=F,Z/=256,C-=8);Y=Y<0;A[J+N]=Y&255,N+=F,Y/=256,E-=8);A[J+N-F]|=V*128}});var u8=B0((Fw,sI)=>{/*! - localForage -- Offline Storage, Improved - Version 1.10.0 - https://localforage.github.io/localForage - (c) 2013-2017 Mozilla, Apache License 2.0 -*/(function(A){if(typeof Fw==="object"&&typeof sI!=="undefined")sI.exports=A();else if(typeof define==="function"&&define.amd)define([],A);else{var Q;if(typeof window!=="undefined")Q=window;else if(typeof global!=="undefined")Q=global;else if(typeof self!=="undefined")Q=self;else Q=this;Q.localforage=A()}})(function(){var A,Q,J;return function K(C,U,Y){function Z(H,$){if(!U[H]){if(!C[H]){var I=KX;if(!$&&I)return I(H,!0);if(X)return X(H,!0);var N=new Error("Cannot find module '"+H+"'");throw N.code="MODULE_NOT_FOUND",N}var F=U[H]={exports:{}};C[H][0].call(F.exports,function(V){var D=C[H][1][V];return Z(D?D:V)},F,F.exports,K,C,U,Y)}return U[H].exports}var X=KX;for(var E=0;E=43)}}).catch(function(){return!1})}function u(P1){if(typeof R==="boolean")return I.resolve(R);return f(P1).then(function(x1){return R=x1,R})}function d(P1){var x1=M[P1.name],v1={};if(v1.promise=new I(function(u1,o1){v1.resolve=u1,v1.reject=o1}),x1.deferredOperations.push(v1),!x1.dbReady)x1.dbReady=v1.promise;else x1.dbReady=x1.dbReady.then(function(){return v1.promise})}function n(P1){var x1=M[P1.name],v1=x1.deferredOperations.pop();if(v1)return v1.resolve(),v1.promise}function B(P1,x1){var v1=M[P1.name],u1=v1.deferredOperations.pop();if(u1)return u1.reject(x1),u1.promise}function q(P1,x1){return new I(function(v1,u1){if(M[P1.name]=M[P1.name]||p(),P1.db)if(x1)d(P1),P1.db.close();else return v1(P1.db);var o1=[P1.name];if(x1)o1.push(P1.version);var n1=E.open.apply(E,o1);if(x1)n1.onupgradeneeded=function(E0){var F0=n1.result;try{if(F0.createObjectStore(P1.storeName),E0.oldVersion<=1)F0.createObjectStore(L)}catch(I0){if(I0.name==="ConstraintError")console.warn('The database "'+P1.name+'" has been upgraded from version '+E0.oldVersion+" to version "+E0.newVersion+', but the storage "'+P1.storeName+'" already exists.');else throw I0}};n1.onerror=function(E0){E0.preventDefault(),u1(n1.error)},n1.onsuccess=function(){var E0=n1.result;E0.onversionchange=function(F0){F0.target.close()},v1(E0),n(P1)}})}function P(P1){return q(P1,!1)}function O(P1){return q(P1,!0)}function w(P1,x1){if(!P1.db)return!0;var v1=!P1.db.objectStoreNames.contains(P1.storeName),u1=P1.versionP1.db.version;if(u1){if(P1.version!==x1)console.warn('The database "'+P1.name+`" can't be downgraded from version `+P1.db.version+" to version "+P1.version+".");P1.version=P1.db.version}if(o1||v1){if(v1){var n1=P1.db.version+1;if(n1>P1.version)P1.version=n1}return!0}return!1}function k(P1){return new I(function(x1,v1){var u1=new FileReader;u1.onerror=v1,u1.onloadend=function(o1){var n1=btoa(o1.target.result||"");x1({__local_forage_encoded_blob:!0,data:n1,type:P1.type})},u1.readAsBinaryString(P1)})}function S(P1){var x1=g(atob(P1.data));return $([x1],{type:P1.type})}function _(P1){return P1&&P1.__local_forage_encoded_blob}function W(P1){var x1=this,v1=x1._initReady().then(function(){var u1=M[x1._dbInfo.name];if(u1&&u1.dbReady)return u1.dbReady});return F(v1,P1,P1),v1}function j(P1){d(P1);var x1=M[P1.name],v1=x1.forages;for(var u1=0;u10&&(!P1.db||n1.name==="InvalidStateError"||n1.name==="NotFoundError"))return I.resolve().then(function(){if(!P1.db||n1.name==="NotFoundError"&&!P1.db.objectStoreNames.contains(P1.storeName)&&P1.version<=P1.db.version){if(P1.db)P1.version=P1.db.version+1;return O(P1)}}).then(function(){return j(P1).then(function(){b(P1,x1,v1,u1-1)})}).catch(v1);v1(n1)}}function p(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function s(P1){var x1=this,v1={db:null};if(P1)for(var u1 in P1)v1[u1]=P1[u1];var o1=M[v1.name];if(!o1)o1=p(),M[v1.name]=o1;if(o1.forages.push(x1),!x1._initReady)x1._initReady=x1.ready,x1.ready=W;var n1=[];function E0(){return I.resolve()}for(var F0=0;F0>4,w0[o1++]=(E0&15)<<4|F0>>2,w0[o1++]=(F0&3)<<6|I0&63;return z0}function R1(P1){var x1=new Uint8Array(P1),v1="",u1;for(u1=0;u1>2],v1+=o[(x1[u1]&3)<<4|x1[u1+1]>>4],v1+=o[(x1[u1+1]&15)<<2|x1[u1+2]>>6],v1+=o[x1[u1+2]&63];if(x1.length%3===2)v1=v1.substring(0,v1.length-1)+"=";else if(x1.length%3===1)v1=v1.substring(0,v1.length-2)+"==";return v1}function X1(P1,x1){var v1="";if(P1)v1=K1.call(P1);if(P1&&(v1==="[object ArrayBuffer]"||P1.buffer&&K1.call(P1.buffer)==="[object ArrayBuffer]")){var u1,o1=Z1;if(P1 instanceof ArrayBuffer)u1=P1,o1+=H1;else if(u1=P1.buffer,v1==="[object Int8Array]")o1+=k1;else if(v1==="[object Uint8Array]")o1+=D1;else if(v1==="[object Uint8ClampedArray]")o1+=G1;else if(v1==="[object Int16Array]")o1+=w1;else if(v1==="[object Uint16Array]")o1+=z;else if(v1==="[object Int32Array]")o1+=G;else if(v1==="[object Uint32Array]")o1+=x;else if(v1==="[object Float32Array]")o1+=m;else if(v1==="[object Float64Array]")o1+=l;else x1(new Error("Failed to get type for BinaryArray"));x1(o1+R1(u1))}else if(v1==="[object Blob]"){var n1=new FileReader;n1.onload=function(){var E0=C1+P1.type+"~"+R1(this.result);x1(Z1+B1+E0)},n1.readAsArrayBuffer(P1)}else try{x1(JSON.stringify(P1))}catch(E0){console.error("Couldn't convert value into a JSON string: ",P1),x1(null,E0)}}function W1(P1){if(P1.substring(0,j1)!==Z1)return JSON.parse(P1);var x1=P1.substring(a),v1=P1.substring(j1,a),u1;if(v1===B1&&q1.test(x1)){var o1=x1.match(q1);u1=o1[1],x1=x1.substring(o1[0].length)}var n1=F1(x1);switch(v1){case H1:return n1;case B1:return $([n1],{type:u1});case k1:return new Int8Array(n1);case D1:return new Uint8Array(n1);case G1:return new Uint8ClampedArray(n1);case w1:return new Int16Array(n1);case z:return new Uint16Array(n1);case G:return new Int32Array(n1);case x:return new Uint32Array(n1);case m:return new Float32Array(n1);case l:return new Float64Array(n1);default:throw new Error("Unkown type: "+v1)}}var $1={serialize:X1,deserialize:W1,stringToBuffer:F1,bufferToString:R1};function N1(P1,x1,v1,u1){P1.executeSql("CREATE TABLE IF NOT EXISTS "+x1.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],v1,u1)}function _1(P1){var x1=this,v1={db:null};if(P1)for(var u1 in P1)v1[u1]=typeof P1[u1]!=="string"?P1[u1].toString():P1[u1];var o1=new I(function(n1,E0){try{v1.db=openDatabase(v1.name,String(v1.version),v1.description,v1.size)}catch(F0){return E0(F0)}v1.db.transaction(function(F0){N1(F0,v1,function(){x1._dbInfo=v1,n1()},function(I0,z0){E0(z0)})},E0)});return v1.serializer=$1,o1}function J1(P1,x1,v1,u1,o1,n1){P1.executeSql(v1,u1,o1,function(E0,F0){if(F0.code===F0.SYNTAX_ERR)E0.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[x1.storeName],function(I0,z0){if(!z0.rows.length)N1(I0,x1,function(){I0.executeSql(v1,u1,o1,n1)},n1);else n1(I0,F0)},n1);else n1(E0,F0)},n1)}function z1(P1,x1){var v1=this;P1=V(P1);var u1=new I(function(o1,n1){v1.ready().then(function(){var E0=v1._dbInfo;E0.db.transaction(function(F0){J1(F0,E0,"SELECT * FROM "+E0.storeName+" WHERE key = ? LIMIT 1",[P1],function(I0,z0){var w0=z0.rows.length?z0.rows.item(0).value:null;if(w0)w0=E0.serializer.deserialize(w0);o1(w0)},function(I0,z0){n1(z0)})})}).catch(n1)});return N(u1,x1),u1}function M1(P1,x1){var v1=this,u1=new I(function(o1,n1){v1.ready().then(function(){var E0=v1._dbInfo;E0.db.transaction(function(F0){J1(F0,E0,"SELECT * FROM "+E0.storeName,[],function(I0,z0){var w0=z0.rows,x0=w0.length;for(var ZA=0;ZA0){E0(L1.apply(o1,[P1,I0,v1,u1-1]));return}F0(ZA)}})})}).catch(F0)});return N(n1,v1),n1}function V1(P1,x1,v1){return L1.apply(this,[P1,x1,v1,1])}function S1(P1,x1){var v1=this;P1=V(P1);var u1=new I(function(o1,n1){v1.ready().then(function(){var E0=v1._dbInfo;E0.db.transaction(function(F0){J1(F0,E0,"DELETE FROM "+E0.storeName+" WHERE key = ?",[P1],function(){o1()},function(I0,z0){n1(z0)})})}).catch(n1)});return N(u1,x1),u1}function O0(P1){var x1=this,v1=new I(function(u1,o1){x1.ready().then(function(){var n1=x1._dbInfo;n1.db.transaction(function(E0){J1(E0,n1,"DELETE FROM "+n1.storeName,[],function(){u1()},function(F0,I0){o1(I0)})})}).catch(o1)});return N(v1,P1),v1}function h1(P1){var x1=this,v1=new I(function(u1,o1){x1.ready().then(function(){var n1=x1._dbInfo;n1.db.transaction(function(E0){J1(E0,n1,"SELECT COUNT(key) as c FROM "+n1.storeName,[],function(F0,I0){var z0=I0.rows.item(0).c;u1(z0)},function(F0,I0){o1(I0)})})}).catch(o1)});return N(v1,P1),v1}function b1(P1,x1){var v1=this,u1=new I(function(o1,n1){v1.ready().then(function(){var E0=v1._dbInfo;E0.db.transaction(function(F0){J1(F0,E0,"SELECT key FROM "+E0.storeName+" WHERE id = ? LIMIT 1",[P1+1],function(I0,z0){var w0=z0.rows.length?z0.rows.item(0).key:null;o1(w0)},function(I0,z0){n1(z0)})})}).catch(n1)});return N(u1,x1),u1}function f0(P1){var x1=this,v1=new I(function(u1,o1){x1.ready().then(function(){var n1=x1._dbInfo;n1.db.transaction(function(E0){J1(E0,n1,"SELECT key FROM "+n1.storeName,[],function(F0,I0){var z0=[];for(var w0=0;w0 '__WebKitDatabaseInfoTable__'",[],function(o1,n1){var E0=[];for(var F0=0;F00}function J0(P1){var x1=this,v1={};if(P1)for(var u1 in P1)v1[u1]=P1[u1];if(v1.keyPrefix=r1(P1,x1._defaultConfig),!K0())return I.reject();return x1._dbInfo=v1,v1.serializer=$1,I.resolve()}function qA(P1){var x1=this,v1=x1.ready().then(function(){var u1=x1._dbInfo.keyPrefix;for(var o1=localStorage.length-1;o1>=0;o1--){var n1=localStorage.key(o1);if(n1.indexOf(u1)===0)localStorage.removeItem(n1)}});return N(v1,P1),v1}function Q0(P1,x1){var v1=this;P1=V(P1);var u1=v1.ready().then(function(){var o1=v1._dbInfo,n1=localStorage.getItem(o1.keyPrefix+P1);if(n1)n1=o1.serializer.deserialize(n1);return n1});return N(u1,x1),u1}function A0(P1,x1){var v1=this,u1=v1.ready().then(function(){var o1=v1._dbInfo,n1=o1.keyPrefix,E0=n1.length,F0=localStorage.length,I0=1;for(var z0=0;z0=0;E0--){var F0=localStorage.key(E0);if(F0.indexOf(n1)===0)localStorage.removeItem(F0)}});return N(o1,x1),o1}var m1={_driver:"localStorageWrapper",_initStorage:J0,_support:a1(),iterate:A0,getItem:Q0,setItem:E2,removeItem:X2,clear:qA,length:EA,key:hA,keys:r0,dropInstance:T1},i1=function P1(x1,v1){return x1===v1||typeof x1==="number"&&typeof v1==="number"&&isNaN(x1)&&isNaN(v1)},t1=function P1(x1,v1){var u1=x1.length,o1=0;while(o1xw});var ro,ZX,to,eo,Ai,Qi,Ji=(A,Q)=>()=>(A&&(Q=A(A=0)),Q),Y2=(A,Q)=>()=>(Q||A((Q={exports:{}}).exports,Q),Q.exports),Vw=(A,Q)=>{for(var J in Q)ZX(A,J,{get:Q[J],enumerable:!0})},YX=(A,Q,J,K)=>{if(Q&&typeof Q=="object"||typeof Q=="function")for(let C of eo(Q))!Qi.call(A,C)&&C!==J&&ZX(A,C,{get:()=>Q[C],enumerable:!(K=to(Q,C))||K.enumerable});return A},Mw=(A,Q,J)=>(YX(A,Q,"default"),J&&YX(J,Q,"default")),UX=(A,Q,J)=>(J=A!=null?ro(Ai(A)):{},YX(Q||!A||!A.__esModule?ZX(J,"default",{value:A,enumerable:!0}):J,A)),b4=(A)=>YX(ZX({},"__esModule",{value:!0}),A),Ki,Ci,y7,q8,V3,oI,k6,BX,Dw,w3,ww,f4,p4,u4,Yi,pJ,iI,aI,rI,Ui,tI,Zi,Bi,Pw,XX,_w,Xi,M3,Tw,kw,eI,Ei,Sw,$i,jw,vw,xw;var $X=hJ(()=>{ro=Object.create,ZX=Object.defineProperty,to=Object.getOwnPropertyDescriptor,eo=Object.getOwnPropertyNames,Ai=Object.getPrototypeOf,Qi=Object.prototype.hasOwnProperty,Ki=Y2((A)=>{A.byteLength=X,A.toByteArray=H,A.fromByteArray=N;var Q=[],J=[],K=typeof Uint8Array<"u"?Uint8Array:Array,C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(U=0,Y=C.length;U0)throw new Error("Invalid string. Length must be a multiple of 4");var D=F.indexOf("=");D===-1&&(D=V);var L=D===V?0:4-D%4;return[D,L]}function X(F){var V=Z(F),D=V[0],L=V[1];return(D+L)*3/4-L}function E(F,V,D){return(V+D)*3/4-D}function H(F){var V,D=Z(F),L=D[0],R=D[1],M=new K(E(F,L,R)),T=0,h=R>0?L-4:L,y;for(y=0;y>16&255,M[T++]=V>>8&255,M[T++]=V&255;return R===2&&(V=J[F.charCodeAt(y)]<<2|J[F.charCodeAt(y+1)]>>4,M[T++]=V&255),R===1&&(V=J[F.charCodeAt(y)]<<10|J[F.charCodeAt(y+1)]<<4|J[F.charCodeAt(y+2)]>>2,M[T++]=V>>8&255,M[T++]=V&255),M}function $(F){return Q[F>>18&63]+Q[F>>12&63]+Q[F>>6&63]+Q[F&63]}function I(F,V,D){for(var L,R=[],M=V;Mh?h:T+M));return L===1?(V=F[D-1],R.push(Q[V>>2]+Q[V<<4&63]+"==")):L===2&&(V=(F[D-2]<<8)+F[D-1],R.push(Q[V>>10]+Q[V>>4&63]+Q[V<<2&63]+"=")),R.join("")}}),Ci=Y2((A)=>{A.read=function(Q,J,K,C,U){var Y,Z,X=U*8-C-1,E=(1<>1,$=-7,I=K?U-1:0,N=K?-1:1,F=Q[J+I];for(I+=N,Y=F&(1<<-$)-1,F>>=-$,$+=X;$>0;Y=Y*256+Q[J+I],I+=N,$-=8);for(Z=Y&(1<<-$)-1,Y>>=-$,$+=C;$>0;Z=Z*256+Q[J+I],I+=N,$-=8);if(Y===0)Y=1-H;else{if(Y===E)return Z?NaN:(F?-1:1)*(1/0);Z=Z+Math.pow(2,C),Y=Y-H}return(F?-1:1)*Z*Math.pow(2,Y-C)},A.write=function(Q,J,K,C,U,Y){var Z,X,E,H=Y*8-U-1,$=(1<>1,N=U===23?Math.pow(2,-24)-Math.pow(2,-77):0,F=C?0:Y-1,V=C?1:-1,D=J<0||J===0&&1/J<0?1:0;for(J=Math.abs(J),isNaN(J)||J===1/0?(X=isNaN(J)?1:0,Z=$):(Z=Math.floor(Math.log(J)/Math.LN2),J*(E=Math.pow(2,-Z))<1&&(Z--,E*=2),Z+I>=1?J+=N/E:J+=N*Math.pow(2,1-I),J*E>=2&&(Z++,E/=2),Z+I>=$?(X=0,Z=$):Z+I>=1?(X=(J*E-1)*Math.pow(2,U),Z=Z+I):(X=J*Math.pow(2,I-1)*Math.pow(2,U),Z=0));U>=8;Q[K+F]=X&255,F+=V,X/=256,U-=8);for(Z=Z<0;Q[K+F]=Z&255,F+=V,Z/=256,H-=8);Q[K+F-V]|=D*128}}),y7=Y2((A)=>{var Q=Ki(),J=Ci(),K=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;A.Buffer=Z,A.SlowBuffer=R,A.INSPECT_MAX_BYTES=50;var C=2147483647;A.kMaxLength=C,Z.TYPED_ARRAY_SUPPORT=U(),!Z.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function U(){try{let G=new Uint8Array(1),z={foo:function(){return 42}};return Object.setPrototypeOf(z,Uint8Array.prototype),Object.setPrototypeOf(G,z),G.foo()===42}catch{return!1}}Object.defineProperty(Z.prototype,"parent",{enumerable:!0,get:function(){if(Z.isBuffer(this))return this.buffer}}),Object.defineProperty(Z.prototype,"offset",{enumerable:!0,get:function(){if(Z.isBuffer(this))return this.byteOffset}});function Y(G){if(G>C)throw new RangeError('The value "'+G+'" is invalid for option "size"');let z=new Uint8Array(G);return Object.setPrototypeOf(z,Z.prototype),z}function Z(G,z,x){if(typeof G=="number"){if(typeof z=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return $(G)}return X(G,z,x)}Z.poolSize=8192;function X(G,z,x){if(typeof G=="string")return I(G,z);if(ArrayBuffer.isView(G))return F(G);if(G==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof G);if(B1(G,ArrayBuffer)||G&&B1(G.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(B1(G,SharedArrayBuffer)||G&&B1(G.buffer,SharedArrayBuffer)))return V(G,z,x);if(typeof G=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let m=G.valueOf&&G.valueOf();if(m!=null&&m!==G)return Z.from(m,z,x);let l=D(G);if(l)return l;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof G[Symbol.toPrimitive]=="function")return Z.from(G[Symbol.toPrimitive]("string"),z,x);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof G)}Z.from=function(G,z,x){return X(G,z,x)},Object.setPrototypeOf(Z.prototype,Uint8Array.prototype),Object.setPrototypeOf(Z,Uint8Array);function E(G){if(typeof G!="number")throw new TypeError('"size" argument must be of type number');if(G<0)throw new RangeError('The value "'+G+'" is invalid for option "size"')}function H(G,z,x){return E(G),G<=0?Y(G):z!==void 0?typeof x=="string"?Y(G).fill(z,x):Y(G).fill(z):Y(G)}Z.alloc=function(G,z,x){return H(G,z,x)};function $(G){return E(G),Y(G<0?0:L(G)|0)}Z.allocUnsafe=function(G){return $(G)},Z.allocUnsafeSlow=function(G){return $(G)};function I(G,z){if((typeof z!="string"||z==="")&&(z="utf8"),!Z.isEncoding(z))throw new TypeError("Unknown encoding: "+z);let x=M(G,z)|0,m=Y(x),l=m.write(G,z);return l!==x&&(m=m.slice(0,l)),m}function N(G){let z=G.length<0?0:L(G.length)|0,x=Y(z);for(let m=0;m=C)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+C.toString(16)+" bytes");return G|0}function R(G){return+G!=G&&(G=0),Z.alloc(+G)}Z.isBuffer=function(G){return G!=null&&G._isBuffer===!0&&G!==Z.prototype},Z.compare=function(G,z){if(B1(G,Uint8Array)&&(G=Z.from(G,G.offset,G.byteLength)),B1(z,Uint8Array)&&(z=Z.from(z,z.offset,z.byteLength)),!Z.isBuffer(G)||!Z.isBuffer(z))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(G===z)return 0;let x=G.length,m=z.length;for(let l=0,a=Math.min(x,m);lm.length?(Z.isBuffer(a)||(a=Z.from(a)),a.copy(m,l)):Uint8Array.prototype.set.call(m,a,l);else if(Z.isBuffer(a))a.copy(m,l);else throw new TypeError('"list" argument must be an Array of Buffers');l+=a.length}return m};function M(G,z){if(Z.isBuffer(G))return G.length;if(ArrayBuffer.isView(G)||B1(G,ArrayBuffer))return G.byteLength;if(typeof G!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof G);let x=G.length,m=arguments.length>2&&arguments[2]===!0;if(!m&&x===0)return 0;let l=!1;for(;;)switch(z){case"ascii":case"latin1":case"binary":return x;case"utf8":case"utf-8":return C1(G).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x*2;case"hex":return x>>>1;case"base64":return j1(G).length;default:if(l)return m?-1:C1(G).length;z=(""+z).toLowerCase(),l=!0}}Z.byteLength=M;function T(G,z,x){let m=!1;if((z===void 0||z<0)&&(z=0),z>this.length||((x===void 0||x>this.length)&&(x=this.length),x<=0)||(x>>>=0,z>>>=0,x<=z))return"";for(G||(G="utf8");;)switch(G){case"hex":return _(this,z,x);case"utf8":case"utf-8":return P(this,z,x);case"ascii":return k(this,z,x);case"latin1":case"binary":return S(this,z,x);case"base64":return q(this,z,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,z,x);default:if(m)throw new TypeError("Unknown encoding: "+G);G=(G+"").toLowerCase(),m=!0}}Z.prototype._isBuffer=!0;function h(G,z,x){let m=G[z];G[z]=G[x],G[x]=m}Z.prototype.swap16=function(){let G=this.length;if(G%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let z=0;zz&&(G+=" ... "),""},K&&(Z.prototype[K]=Z.prototype.inspect),Z.prototype.compare=function(G,z,x,m,l){if(B1(G,Uint8Array)&&(G=Z.from(G,G.offset,G.byteLength)),!Z.isBuffer(G))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof G);if(z===void 0&&(z=0),x===void 0&&(x=G?G.length:0),m===void 0&&(m=0),l===void 0&&(l=this.length),z<0||x>G.length||m<0||l>this.length)throw new RangeError("out of range index");if(m>=l&&z>=x)return 0;if(m>=l)return-1;if(z>=x)return 1;if(z>>>=0,x>>>=0,m>>>=0,l>>>=0,this===G)return 0;let a=l-m,K1=x-z,F1=Math.min(a,K1),R1=this.slice(m,l),X1=G.slice(z,x);for(let W1=0;W12147483647?x=2147483647:x<-2147483648&&(x=-2147483648),x=+x,k1(x)&&(x=l?0:G.length-1),x<0&&(x=G.length+x),x>=G.length){if(l)return-1;x=G.length-1}else if(x<0)if(l)x=0;else return-1;if(typeof z=="string"&&(z=Z.from(z,m)),Z.isBuffer(z))return z.length===0?-1:g(G,z,x,m,l);if(typeof z=="number")return z=z&255,typeof Uint8Array.prototype.indexOf=="function"?l?Uint8Array.prototype.indexOf.call(G,z,x):Uint8Array.prototype.lastIndexOf.call(G,z,x):g(G,[z],x,m,l);throw new TypeError("val must be string, number or Buffer")}function g(G,z,x,m,l){let a=1,K1=G.length,F1=z.length;if(m!==void 0&&(m=String(m).toLowerCase(),m==="ucs2"||m==="ucs-2"||m==="utf16le"||m==="utf-16le")){if(G.length<2||z.length<2)return-1;a=2,K1/=2,F1/=2,x/=2}function R1(W1,$1){return a===1?W1[$1]:W1.readUInt16BE($1*a)}let X1;if(l){let W1=-1;for(X1=x;X1K1&&(x=K1-F1),X1=x;X1>=0;X1--){let W1=!0;for(let $1=0;$1l&&(m=l)):m=l;let a=z.length;m>a/2&&(m=a/2);let K1;for(K1=0;K1>>0,isFinite(x)?(x=x>>>0,m===void 0&&(m="utf8")):(m=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let l=this.length-z;if((x===void 0||x>l)&&(x=l),G.length>0&&(x<0||z<0)||z>this.length)throw new RangeError("Attempt to write outside buffer bounds");m||(m="utf8");let a=!1;for(;;)switch(m){case"hex":return f(this,G,z,x);case"utf8":case"utf-8":return u(this,G,z,x);case"ascii":case"latin1":case"binary":return d(this,G,z,x);case"base64":return n(this,G,z,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,G,z,x);default:if(a)throw new TypeError("Unknown encoding: "+m);m=(""+m).toLowerCase(),a=!0}},Z.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function q(G,z,x){return z===0&&x===G.length?Q.fromByteArray(G):Q.fromByteArray(G.slice(z,x))}function P(G,z,x){x=Math.min(G.length,x);let m=[],l=z;for(;l239?4:a>223?3:a>191?2:1;if(l+F1<=x){let R1,X1,W1,$1;switch(F1){case 1:a<128&&(K1=a);break;case 2:R1=G[l+1],(R1&192)===128&&($1=(a&31)<<6|R1&63,$1>127&&(K1=$1));break;case 3:R1=G[l+1],X1=G[l+2],(R1&192)===128&&(X1&192)===128&&($1=(a&15)<<12|(R1&63)<<6|X1&63,$1>2047&&($1<55296||$1>57343)&&(K1=$1));break;case 4:R1=G[l+1],X1=G[l+2],W1=G[l+3],(R1&192)===128&&(X1&192)===128&&(W1&192)===128&&($1=(a&15)<<18|(R1&63)<<12|(X1&63)<<6|W1&63,$1>65535&&$1<1114112&&(K1=$1))}}K1===null?(K1=65533,F1=1):K1>65535&&(K1-=65536,m.push(K1>>>10&1023|55296),K1=56320|K1&1023),m.push(K1),l+=F1}return w(m)}var O=4096;function w(G){let z=G.length;if(z<=O)return String.fromCharCode.apply(String,G);let x="",m=0;for(;mm)&&(x=m);let l="";for(let a=z;ax&&(G=x),z<0?(z+=x,z<0&&(z=0)):z>x&&(z=x),zx)throw new RangeError("Trying to access beyond buffer length")}Z.prototype.readUintLE=Z.prototype.readUIntLE=function(G,z,x){G=G>>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G],l=1,a=0;for(;++a>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G+--z],l=1;for(;z>0&&(l*=256);)m+=this[G+--z]*l;return m},Z.prototype.readUint8=Z.prototype.readUInt8=function(G,z){return G=G>>>0,z||j(G,1,this.length),this[G]},Z.prototype.readUint16LE=Z.prototype.readUInt16LE=function(G,z){return G=G>>>0,z||j(G,2,this.length),this[G]|this[G+1]<<8},Z.prototype.readUint16BE=Z.prototype.readUInt16BE=function(G,z){return G=G>>>0,z||j(G,2,this.length),this[G]<<8|this[G+1]},Z.prototype.readUint32LE=Z.prototype.readUInt32LE=function(G,z){return G=G>>>0,z||j(G,4,this.length),(this[G]|this[G+1]<<8|this[G+2]<<16)+this[G+3]*16777216},Z.prototype.readUint32BE=Z.prototype.readUInt32BE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]*16777216+(this[G+1]<<16|this[G+2]<<8|this[G+3])},Z.prototype.readBigUInt64LE=G1(function(G){G=G>>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=z+this[++G]*256+this[++G]*65536+this[++G]*16777216,l=this[++G]+this[++G]*256+this[++G]*65536+x*16777216;return BigInt(m)+(BigInt(l)<>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=z*16777216+this[++G]*65536+this[++G]*256+this[++G],l=this[++G]*16777216+this[++G]*65536+this[++G]*256+x;return(BigInt(m)<>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G],l=1,a=0;for(;++a=l&&(m-=Math.pow(2,8*z)),m},Z.prototype.readIntBE=function(G,z,x){G=G>>>0,z=z>>>0,x||j(G,z,this.length);let m=z,l=1,a=this[G+--m];for(;m>0&&(l*=256);)a+=this[G+--m]*l;return l*=128,a>=l&&(a-=Math.pow(2,8*z)),a},Z.prototype.readInt8=function(G,z){return G=G>>>0,z||j(G,1,this.length),this[G]&128?(255-this[G]+1)*-1:this[G]},Z.prototype.readInt16LE=function(G,z){G=G>>>0,z||j(G,2,this.length);let x=this[G]|this[G+1]<<8;return x&32768?x|4294901760:x},Z.prototype.readInt16BE=function(G,z){G=G>>>0,z||j(G,2,this.length);let x=this[G+1]|this[G]<<8;return x&32768?x|4294901760:x},Z.prototype.readInt32LE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]|this[G+1]<<8|this[G+2]<<16|this[G+3]<<24},Z.prototype.readInt32BE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]<<24|this[G+1]<<16|this[G+2]<<8|this[G+3]},Z.prototype.readBigInt64LE=G1(function(G){G=G>>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=this[G+4]+this[G+5]*256+this[G+6]*65536+(x<<24);return(BigInt(m)<>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=(z<<24)+this[++G]*65536+this[++G]*256+this[++G];return(BigInt(m)<>>0,z||j(G,4,this.length),J.read(this,G,!0,23,4)},Z.prototype.readFloatBE=function(G,z){return G=G>>>0,z||j(G,4,this.length),J.read(this,G,!1,23,4)},Z.prototype.readDoubleLE=function(G,z){return G=G>>>0,z||j(G,8,this.length),J.read(this,G,!0,52,8)},Z.prototype.readDoubleBE=function(G,z){return G=G>>>0,z||j(G,8,this.length),J.read(this,G,!1,52,8)};function b(G,z,x,m,l,a){if(!Z.isBuffer(G))throw new TypeError('"buffer" argument must be a Buffer instance');if(z>l||zG.length)throw new RangeError("Index out of range")}Z.prototype.writeUintLE=Z.prototype.writeUIntLE=function(G,z,x,m){if(G=+G,z=z>>>0,x=x>>>0,!m){let K1=Math.pow(2,8*x)-1;b(this,G,z,x,K1,0)}let l=1,a=0;for(this[z]=G&255;++a>>0,x=x>>>0,!m){let K1=Math.pow(2,8*x)-1;b(this,G,z,x,K1,0)}let l=x-1,a=1;for(this[z+l]=G&255;--l>=0&&(a*=256);)this[z+l]=G/a&255;return z+x},Z.prototype.writeUint8=Z.prototype.writeUInt8=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,1,255,0),this[z]=G&255,z+1},Z.prototype.writeUint16LE=Z.prototype.writeUInt16LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,65535,0),this[z]=G&255,this[z+1]=G>>>8,z+2},Z.prototype.writeUint16BE=Z.prototype.writeUInt16BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,65535,0),this[z]=G>>>8,this[z+1]=G&255,z+2},Z.prototype.writeUint32LE=Z.prototype.writeUInt32LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,4294967295,0),this[z+3]=G>>>24,this[z+2]=G>>>16,this[z+1]=G>>>8,this[z]=G&255,z+4},Z.prototype.writeUint32BE=Z.prototype.writeUInt32BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,4294967295,0),this[z]=G>>>24,this[z+1]=G>>>16,this[z+2]=G>>>8,this[z+3]=G&255,z+4};function p(G,z,x,m,l){E1(z,m,l,G,x,7);let a=Number(z&BigInt(4294967295));G[x++]=a,a=a>>8,G[x++]=a,a=a>>8,G[x++]=a,a=a>>8,G[x++]=a;let K1=Number(z>>BigInt(32)&BigInt(4294967295));return G[x++]=K1,K1=K1>>8,G[x++]=K1,K1=K1>>8,G[x++]=K1,K1=K1>>8,G[x++]=K1,x}function s(G,z,x,m,l){E1(z,m,l,G,x,7);let a=Number(z&BigInt(4294967295));G[x+7]=a,a=a>>8,G[x+6]=a,a=a>>8,G[x+5]=a,a=a>>8,G[x+4]=a;let K1=Number(z>>BigInt(32)&BigInt(4294967295));return G[x+3]=K1,K1=K1>>8,G[x+2]=K1,K1=K1>>8,G[x+1]=K1,K1=K1>>8,G[x]=K1,x+8}Z.prototype.writeBigUInt64LE=G1(function(G,z=0){return p(this,G,z,BigInt(0),BigInt("0xffffffffffffffff"))}),Z.prototype.writeBigUInt64BE=G1(function(G,z=0){return s(this,G,z,BigInt(0),BigInt("0xffffffffffffffff"))}),Z.prototype.writeIntLE=function(G,z,x,m){if(G=+G,z=z>>>0,!m){let F1=Math.pow(2,8*x-1);b(this,G,z,x,F1-1,-F1)}let l=0,a=1,K1=0;for(this[z]=G&255;++l>0)-K1&255;return z+x},Z.prototype.writeIntBE=function(G,z,x,m){if(G=+G,z=z>>>0,!m){let F1=Math.pow(2,8*x-1);b(this,G,z,x,F1-1,-F1)}let l=x-1,a=1,K1=0;for(this[z+l]=G&255;--l>=0&&(a*=256);)G<0&&K1===0&&this[z+l+1]!==0&&(K1=1),this[z+l]=(G/a>>0)-K1&255;return z+x},Z.prototype.writeInt8=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,1,127,-128),G<0&&(G=255+G+1),this[z]=G&255,z+1},Z.prototype.writeInt16LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,32767,-32768),this[z]=G&255,this[z+1]=G>>>8,z+2},Z.prototype.writeInt16BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,32767,-32768),this[z]=G>>>8,this[z+1]=G&255,z+2},Z.prototype.writeInt32LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,2147483647,-2147483648),this[z]=G&255,this[z+1]=G>>>8,this[z+2]=G>>>16,this[z+3]=G>>>24,z+4},Z.prototype.writeInt32BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,2147483647,-2147483648),G<0&&(G=4294967295+G+1),this[z]=G>>>24,this[z+1]=G>>>16,this[z+2]=G>>>8,this[z+3]=G&255,z+4},Z.prototype.writeBigInt64LE=G1(function(G,z=0){return p(this,G,z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),Z.prototype.writeBigInt64BE=G1(function(G,z=0){return s(this,G,z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function r(G,z,x,m,l,a){if(x+m>G.length)throw new RangeError("Index out of range");if(x<0)throw new RangeError("Index out of range")}function A1(G,z,x,m,l){return z=+z,x=x>>>0,l||r(G,z,x,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000),J.write(G,z,x,m,23,4),x+4}Z.prototype.writeFloatLE=function(G,z,x){return A1(this,G,z,!0,x)},Z.prototype.writeFloatBE=function(G,z,x){return A1(this,G,z,!1,x)};function Q1(G,z,x,m,l){return z=+z,x=x>>>0,l||r(G,z,x,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000),J.write(G,z,x,m,52,8),x+8}Z.prototype.writeDoubleLE=function(G,z,x){return Q1(this,G,z,!0,x)},Z.prototype.writeDoubleBE=function(G,z,x){return Q1(this,G,z,!1,x)},Z.prototype.copy=function(G,z,x,m){if(!Z.isBuffer(G))throw new TypeError("argument should be a Buffer");if(x||(x=0),!m&&m!==0&&(m=this.length),z>=G.length&&(z=G.length),z||(z=0),m>0&&m=this.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("sourceEnd out of bounds");m>this.length&&(m=this.length),G.length-z>>0,x=x===void 0?this.length:x>>>0,G||(G=0);let l;if(typeof G=="number")for(l=z;l4294967296?l=U1(String(x)):typeof x=="bigint"&&(l=String(x),(x>BigInt(2)**BigInt(32)||x<-(BigInt(2)**BigInt(32)))&&(l=U1(l)),l+="n"),m+=` It must be ${z}. Received ${l}`,m},RangeError);function U1(G){let z="",x=G.length,m=G[0]==="-"?1:0;for(;x>=m+4;x-=3)z=`_${G.slice(x-3,x)}${z}`;return`${G.slice(0,x)}${z}`}function O1(G,z,x){Y1(z,"offset"),(G[z]===void 0||G[z+x]===void 0)&&i(z,G.length-(x+1))}function E1(G,z,x,m,l,a){if(G>x||G3?z===0||z===BigInt(0)?F1=`>= 0${K1} and < 2${K1} ** ${(a+1)*8}${K1}`:F1=`>= -(2${K1} ** ${(a+1)*8-1}${K1}) and < 2 ** ${(a+1)*8-1}${K1}`:F1=`>= ${z}${K1} and <= ${x}${K1}`,new e.ERR_OUT_OF_RANGE("value",F1,G)}O1(m,l,a)}function Y1(G,z){if(typeof G!="number")throw new e.ERR_INVALID_ARG_TYPE(z,"number",G)}function i(G,z,x){throw Math.floor(G)!==G?(Y1(G,x),new e.ERR_OUT_OF_RANGE(x||"offset","an integer",G)):z<0?new e.ERR_BUFFER_OUT_OF_BOUNDS:new e.ERR_OUT_OF_RANGE(x||"offset",`>= ${x?1:0} and <= ${z}`,G)}var c=/[^+/0-9A-Za-z-_]/g;function o(G){if(G=G.split("=")[0],G=G.trim().replace(c,""),G.length<2)return"";for(;G.length%4!==0;)G=G+"=";return G}function C1(G,z){z=z||1/0;let x,m=G.length,l=null,a=[];for(let K1=0;K155295&&x<57344){if(!l){if(x>56319){(z-=3)>-1&&a.push(239,191,189);continue}else if(K1+1===m){(z-=3)>-1&&a.push(239,191,189);continue}l=x;continue}if(x<56320){(z-=3)>-1&&a.push(239,191,189),l=x;continue}x=(l-55296<<10|x-56320)+65536}else l&&(z-=3)>-1&&a.push(239,191,189);if(l=null,x<128){if((z-=1)<0)break;a.push(x)}else if(x<2048){if((z-=2)<0)break;a.push(x>>6|192,x&63|128)}else if(x<65536){if((z-=3)<0)break;a.push(x>>12|224,x>>6&63|128,x&63|128)}else if(x<1114112){if((z-=4)<0)break;a.push(x>>18|240,x>>12&63|128,x>>6&63|128,x&63|128)}else throw new Error("Invalid code point")}return a}function q1(G){let z=[];for(let x=0;x>8,l=x%256,a.push(l),a.push(m);return a}function j1(G){return Q.toByteArray(o(G))}function H1(G,z,x,m){let l;for(l=0;l=z.length||l>=G.length);++l)z[l+x]=G[l];return l}function B1(G,z){return G instanceof z||G!=null&&G.constructor!=null&&G.constructor.name!=null&&G.constructor.name===z.name}function k1(G){return G!==G}var D1=function(){let G="0123456789abcdef",z=new Array(256);for(let x=0;x<16;++x){let m=x*16;for(let l=0;l<16;++l)z[m+l]=G[x]+G[l]}return z}();function G1(G){return typeof BigInt>"u"?w1:G}function w1(){throw new Error("BigInt not supported")}}),q8=Y2((A,Q)=>{Q.exports={ArrayIsArray(J){return Array.isArray(J)},ArrayPrototypeIncludes(J,K){return J.includes(K)},ArrayPrototypeIndexOf(J,K){return J.indexOf(K)},ArrayPrototypeJoin(J,K){return J.join(K)},ArrayPrototypeMap(J,K){return J.map(K)},ArrayPrototypePop(J,K){return J.pop(K)},ArrayPrototypePush(J,K){return J.push(K)},ArrayPrototypeSlice(J,K,C){return J.slice(K,C)},Error,FunctionPrototypeCall(J,K,...C){return J.call(K,...C)},FunctionPrototypeSymbolHasInstance(J,K){return Function.prototype[Symbol.hasInstance].call(J,K)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(J,K){return Object.defineProperties(J,K)},ObjectDefineProperty(J,K,C){return Object.defineProperty(J,K,C)},ObjectGetOwnPropertyDescriptor(J,K){return Object.getOwnPropertyDescriptor(J,K)},ObjectKeys(J){return Object.keys(J)},ObjectSetPrototypeOf(J,K){return Object.setPrototypeOf(J,K)},Promise,PromisePrototypeCatch(J,K){return J.catch(K)},PromisePrototypeThen(J,K,C){return J.then(K,C)},PromiseReject(J){return Promise.reject(J)},ReflectApply:Reflect.apply,RegExpPrototypeTest(J,K){return J.test(K)},SafeSet:Set,String,StringPrototypeSlice(J,K,C){return J.slice(K,C)},StringPrototypeToLowerCase(J){return J.toLowerCase()},StringPrototypeToUpperCase(J){return J.toUpperCase()},StringPrototypeTrim(J){return J.trim()},Symbol,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,TypedArrayPrototypeSet(J,K,C){return J.set(K,C)},Uint8Array}}),V3=Y2((A,Q)=>{var J=y7(),K=Object.getPrototypeOf(async function(){}).constructor,C=globalThis.Blob||J.Blob,U=typeof C<"u"?function(Z){return Z instanceof C}:function(Z){return!1},Y=class extends Error{constructor(Z){if(!Array.isArray(Z))throw new TypeError(`Expected input to be an Array, got ${typeof Z}`);let X="";for(let E=0;E{Z=E,X=H}),resolve:Z,reject:X}},promisify(Z){return new Promise((X,E)=>{Z((H,...$)=>H?E(H):X(...$))})},debuglog(){return function(){}},format(Z,...X){return Z.replace(/%([sdifj])/g,function(...[E,H]){let $=X.shift();return H==="f"?$.toFixed(6):H==="j"?JSON.stringify($):H==="s"&&typeof $=="object"?`${$.constructor!==Object?$.constructor.name:""} {}`.trim():$.toString()})},inspect(Z){switch(typeof Z){case"string":if(Z.includes("'"))if(Z.includes('"')){if(!Z.includes("`")&&!Z.includes("${"))return`\`${Z}\``}else return`"${Z}"`;return`'${Z}'`;case"number":return isNaN(Z)?"NaN":Object.is(Z,-0)?String(Z):Z;case"bigint":return`${String(Z)}n`;case"boolean":case"undefined":return String(Z);case"object":return"{}"}},types:{isAsyncFunction(Z){return Z instanceof K},isArrayBufferView(Z){return ArrayBuffer.isView(Z)}},isBlob:U},Q.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),oI=Y2((A,Q)=>{var{AbortController:J,AbortSignal:K}=typeof self<"u"?self:typeof window<"u"?window:void 0;Q.exports=J,Q.exports.AbortSignal=K,Q.exports.default=J}),k6=Y2((A,Q)=>{var{format:J,inspect:K,AggregateError:C}=V3(),U=globalThis.AggregateError||C,Y=Symbol("kIsNodeError"),Z=["string","function","number","object","Function","Object","boolean","bigint","symbol"],X=/^([A-Z][a-z0-9]*)+$/,E="__node_internal_",H={};function $(R,M){if(!R)throw new H.ERR_INTERNAL_ASSERTION(M)}function I(R){let M="",T=R.length,h=R[0]==="-"?1:0;for(;T>=h+4;T-=3)M=`_${R.slice(T-3,T)}${M}`;return`${R.slice(0,T)}${M}`}function N(R,M,T){if(typeof M=="function")return $(M.length<=T.length,`Code: ${R}; The provided arguments length (${T.length}) does not match the required ones (${M.length}).`),M(...T);let h=(M.match(/%[dfijoOs]/g)||[]).length;return $(h===T.length,`Code: ${R}; The provided arguments length (${T.length}) does not match the required ones (${h}).`),T.length===0?M:J(M,...T)}function F(R,M,T){T||(T=Error);class h extends T{constructor(...y){super(N(R,M,y))}toString(){return`${this.name} [${R}]: ${this.message}`}}Object.defineProperties(h.prototype,{name:{value:T.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${R}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),h.prototype.code=R,h.prototype[Y]=!0,H[R]=h}function V(R){let M=E+R.name;return Object.defineProperty(R,"name",{value:M}),R}function D(R,M){if(R&&M&&R!==M){if(Array.isArray(M.errors))return M.errors.push(R),M;let T=new U([M,R],M.message);return T.code=M.code,T}return R||M}var L=class extends Error{constructor(R="The operation was aborted",M=void 0){if(M!==void 0&&typeof M!="object")throw new H.ERR_INVALID_ARG_TYPE("options","Object",M);super(R,M),this.code="ABORT_ERR",this.name="AbortError"}};F("ERR_ASSERTION","%s",Error),F("ERR_INVALID_ARG_TYPE",(R,M,T)=>{$(typeof R=="string","'name' must be a string"),Array.isArray(M)||(M=[M]);let h="The ";R.endsWith(" argument")?h+=`${R} `:h+=`"${R}" ${R.includes(".")?"property":"argument"} `,h+="must be ";let y=[],g=[],f=[];for(let d of M)$(typeof d=="string","All expected entries have to be of type string"),Z.includes(d)?y.push(d.toLowerCase()):X.test(d)?g.push(d):($(d!=="object",'The value "object" should be written as "Object"'),f.push(d));if(g.length>0){let d=y.indexOf("object");d!==-1&&(y.splice(y,d,1),g.push("Object"))}if(y.length>0){switch(y.length){case 1:h+=`of type ${y[0]}`;break;case 2:h+=`one of type ${y[0]} or ${y[1]}`;break;default:{let d=y.pop();h+=`one of type ${y.join(", ")}, or ${d}`}}(g.length>0||f.length>0)&&(h+=" or ")}if(g.length>0){switch(g.length){case 1:h+=`an instance of ${g[0]}`;break;case 2:h+=`an instance of ${g[0]} or ${g[1]}`;break;default:{let d=g.pop();h+=`an instance of ${g.join(", ")}, or ${d}`}}f.length>0&&(h+=" or ")}switch(f.length){case 0:break;case 1:f[0].toLowerCase()!==f[0]&&(h+="an "),h+=`${f[0]}`;break;case 2:h+=`one of ${f[0]} or ${f[1]}`;break;default:{let d=f.pop();h+=`one of ${f.join(", ")}, or ${d}`}}if(T==null)h+=`. Received ${T}`;else if(typeof T=="function"&&T.name)h+=`. Received function ${T.name}`;else if(typeof T=="object"){var u;(u=T.constructor)!==null&&u!==void 0&&u.name?h+=`. Received an instance of ${T.constructor.name}`:h+=`. Received ${K(T,{depth:-1})}`}else{let d=K(T,{colors:!1});d.length>25&&(d=`${d.slice(0,25)}...`),h+=`. Received type ${typeof T} (${d})`}return h},TypeError),F("ERR_INVALID_ARG_VALUE",(R,M,T="is invalid")=>{let h=K(M);return h.length>128&&(h=h.slice(0,128)+"..."),`The ${R.includes(".")?"property":"argument"} '${R}' ${T}. Received ${h}`},TypeError),F("ERR_INVALID_RETURN_VALUE",(R,M,T)=>{var h;let y=T!=null&&(h=T.constructor)!==null&&h!==void 0&&h.name?`instance of ${T.constructor.name}`:`type ${typeof T}`;return`Expected ${R} to be returned from the "${M}" function but got ${y}.`},TypeError),F("ERR_MISSING_ARGS",(...R)=>{$(R.length>0,"At least one arg needs to be specified");let M,T=R.length;switch(R=(Array.isArray(R)?R:[R]).map((h)=>`"${h}"`).join(" or "),T){case 1:M+=`The ${R[0]} argument`;break;case 2:M+=`The ${R[0]} and ${R[1]} arguments`;break;default:{let h=R.pop();M+=`The ${R.join(", ")}, and ${h} arguments`}break}return`${M} must be specified`},TypeError),F("ERR_OUT_OF_RANGE",(R,M,T)=>{$(M,'Missing "range" argument');let h;return Number.isInteger(T)&&Math.abs(T)>4294967296?h=I(String(T)):typeof T=="bigint"?(h=String(T),(T>2n**32n||T<-(2n**32n))&&(h=I(h)),h+="n"):h=K(T),`The value of "${R}" is out of range. It must be ${M}. Received ${h}`},RangeError),F("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),F("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),F("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),F("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),F("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),F("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),F("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),F("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),F("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),F("ERR_STREAM_WRITE_AFTER_END","write after end",Error),F("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),Q.exports={AbortError:L,aggregateTwoErrors:V(D),hideStackFrames:V,codes:H}}),BX=Y2((A,Q)=>{var{ArrayIsArray:J,ArrayPrototypeIncludes:K,ArrayPrototypeJoin:C,ArrayPrototypeMap:U,NumberIsInteger:Y,NumberIsNaN:Z,NumberMAX_SAFE_INTEGER:X,NumberMIN_SAFE_INTEGER:E,NumberParseInt:H,ObjectPrototypeHasOwnProperty:$,RegExpPrototypeExec:I,String:N,StringPrototypeToUpperCase:F,StringPrototypeTrim:V}=q8(),{hideStackFrames:D,codes:{ERR_SOCKET_BAD_PORT:L,ERR_INVALID_ARG_TYPE:R,ERR_INVALID_ARG_VALUE:M,ERR_OUT_OF_RANGE:T,ERR_UNKNOWN_SIGNAL:h}}=k6(),{normalizeEncoding:y}=V3(),{isAsyncFunction:g,isArrayBufferView:f}=V3().types,u={};function d(i){return i===(i|0)}function n(i){return i===i>>>0}var B=/^[0-7]+$/,q="must be a 32-bit unsigned integer or an octal string";function P(i,c,o){if(typeof i>"u"&&(i=o),typeof i=="string"){if(I(B,i)===null)throw new M(c,i,q);i=H(i,8)}return k(i,c),i}var O=D((i,c,o=E,C1=X)=>{if(typeof i!="number")throw new R(c,"number",i);if(!Y(i))throw new T(c,"an integer",i);if(iC1)throw new T(c,`>= ${o} && <= ${C1}`,i)}),w=D((i,c,o=-2147483648,C1=2147483647)=>{if(typeof i!="number")throw new R(c,"number",i);if(!Y(i))throw new T(c,"an integer",i);if(iC1)throw new T(c,`>= ${o} && <= ${C1}`,i)}),k=D((i,c,o=!1)=>{if(typeof i!="number")throw new R(c,"number",i);if(!Y(i))throw new T(c,"an integer",i);let C1=o?1:0,q1=4294967295;if(iq1)throw new T(c,`>= ${C1} && <= ${q1}`,i)});function S(i,c){if(typeof i!="string")throw new R(c,"string",i)}function _(i,c,o=void 0,C1){if(typeof i!="number")throw new R(c,"number",i);if(o!=null&&iC1||(o!=null||C1!=null)&&Z(i))throw new T(c,`${o!=null?`>= ${o}`:""}${o!=null&&C1!=null?" && ":""}${C1!=null?`<= ${C1}`:""}`,i)}var W=D((i,c,o)=>{if(!K(o,i)){let C1=C(U(o,(Z1)=>typeof Z1=="string"?`'${Z1}'`:N(Z1)),", "),q1="must be one of: "+C1;throw new M(c,i,q1)}});function j(i,c){if(typeof i!="boolean")throw new R(c,"boolean",i)}function b(i,c,o){return i==null||!$(i,c)?o:i[c]}var p=D((i,c,o=null)=>{let C1=b(o,"allowArray",!1),q1=b(o,"allowFunction",!1);if(!b(o,"nullable",!1)&&i===null||!C1&&J(i)||typeof i!="object"&&(!q1||typeof i!="function"))throw new R(c,"Object",i)}),s=D((i,c,o=0)=>{if(!J(i))throw new R(c,"Array",i);if(i.length{if(!f(i))throw new R(c,["Buffer","TypedArray","DataView"],i)});function Q1(i,c){let o=y(c),C1=i.length;if(o==="hex"&&C1%2!==0)throw new M("encoding",c,`is invalid for data of length ${C1}`)}function e(i,c="Port",o=!0){if(typeof i!="number"&&typeof i!="string"||typeof i=="string"&&V(i).length===0||+i!==+i>>>0||i>65535||i===0&&!o)throw new L(c,i,o);return i|0}var t=D((i,c)=>{if(i!==void 0&&(i===null||typeof i!="object"||!("aborted"in i)))throw new R(c,"AbortSignal",i)}),U1=D((i,c)=>{if(typeof i!="function")throw new R(c,"Function",i)}),O1=D((i,c)=>{if(typeof i!="function"||g(i))throw new R(c,"Function",i)}),E1=D((i,c)=>{if(i!==void 0)throw new R(c,"undefined",i)});function Y1(i,c,o){if(!K(o,i))throw new R(c,`('${C(o,"|")}')`,i)}Q.exports={isInt32:d,isUint32:n,parseFileMode:P,validateArray:s,validateBoolean:j,validateBuffer:A1,validateEncoding:Q1,validateFunction:U1,validateInt32:w,validateInteger:O,validateNumber:_,validateObject:p,validateOneOf:W,validatePlainFunction:O1,validatePort:e,validateSignalName:r,validateString:S,validateUint32:k,validateUndefined:E1,validateUnion:Y1,validateAbortSignal:t}}),Dw=Y2((A,Q)=>{var J=Q.exports={},K,C;function U(){throw new Error("setTimeout has not been defined")}function Y(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?K=setTimeout:K=U}catch{K=U}try{typeof clearTimeout=="function"?C=clearTimeout:C=Y}catch{C=Y}})();function Z(L){if(K===setTimeout)return setTimeout(L,0);if((K===U||!K)&&setTimeout)return K=setTimeout,setTimeout(L,0);try{return K(L,0)}catch{try{return K.call(null,L,0)}catch{return K.call(this,L,0)}}}function X(L){if(C===clearTimeout)return clearTimeout(L);if((C===Y||!C)&&clearTimeout)return C=clearTimeout,clearTimeout(L);try{return C(L)}catch{try{return C.call(null,L)}catch{return C.call(this,L)}}}var E=[],H=!1,$,I=-1;function N(){!H||!$||(H=!1,$.length?E=$.concat(E):I=-1,E.length&&F())}function F(){if(!H){var L=Z(N);H=!0;for(var R=E.length;R;){for($=E,E=[];++I1)for(var M=1;Mww});f4=Ji(()=>{Mw(w3,UX(Dw())),ww=UX(Dw())}),p4=Y2((A,Q)=>{var{Symbol:J,SymbolAsyncIterator:K,SymbolIterator:C}=q8(),U=J("kDestroyed"),Y=J("kIsErrored"),Z=J("kIsReadable"),X=J("kIsDisturbed");function E(O,w=!1){var k;return!!(O&&typeof O.pipe=="function"&&typeof O.on=="function"&&(!w||typeof O.pause=="function"&&typeof O.resume=="function")&&(!O._writableState||((k=O._readableState)===null||k===void 0?void 0:k.readable)!==!1)&&(!O._writableState||O._readableState))}function H(O){var w;return!!(O&&typeof O.write=="function"&&typeof O.on=="function"&&(!O._readableState||((w=O._writableState)===null||w===void 0?void 0:w.writable)!==!1))}function $(O){return!!(O&&typeof O.pipe=="function"&&O._readableState&&typeof O.on=="function"&&typeof O.write=="function")}function I(O){return O&&(O._readableState||O._writableState||typeof O.write=="function"&&typeof O.on=="function"||typeof O.pipe=="function"&&typeof O.on=="function")}function N(O,w){return O==null?!1:w===!0?typeof O[K]=="function":w===!1?typeof O[C]=="function":typeof O[K]=="function"||typeof O[C]=="function"}function F(O){if(!I(O))return null;let{_writableState:w,_readableState:k}=O,S=w||k;return!!(O.destroyed||O[U]||S!=null&&S.destroyed)}function V(O){if(!H(O))return null;if(O.writableEnded===!0)return!0;let w=O._writableState;return w!=null&&w.errored?!1:typeof w?.ended!="boolean"?null:w.ended}function D(O,w){if(!H(O))return null;if(O.writableFinished===!0)return!0;let k=O._writableState;return k!=null&&k.errored?!1:typeof k?.finished!="boolean"?null:!!(k.finished||w===!1&&k.ended===!0&&k.length===0)}function L(O){if(!E(O))return null;if(O.readableEnded===!0)return!0;let w=O._readableState;return!w||w.errored?!1:typeof w?.ended!="boolean"?null:w.ended}function R(O,w){if(!E(O))return null;let k=O._readableState;return k!=null&&k.errored?!1:typeof k?.endEmitted!="boolean"?null:!!(k.endEmitted||w===!1&&k.ended===!0&&k.length===0)}function M(O){return O&&O[Z]!=null?O[Z]:typeof O?.readable!="boolean"?null:F(O)?!1:E(O)&&O.readable&&!R(O)}function T(O){return typeof O?.writable!="boolean"?null:F(O)?!1:H(O)&&O.writable&&!V(O)}function h(O,w){return I(O)?F(O)?!0:!(w?.readable!==!1&&M(O)||w?.writable!==!1&&T(O)):null}function y(O){var w,k;return I(O)?O.writableErrored?O.writableErrored:(w=(k=O._writableState)===null||k===void 0?void 0:k.errored)!==null&&w!==void 0?w:null:null}function g(O){var w,k;return I(O)?O.readableErrored?O.readableErrored:(w=(k=O._readableState)===null||k===void 0?void 0:k.errored)!==null&&w!==void 0?w:null:null}function f(O){if(!I(O))return null;if(typeof O.closed=="boolean")return O.closed;let{_writableState:w,_readableState:k}=O;return typeof w?.closed=="boolean"||typeof k?.closed=="boolean"?w?.closed||k?.closed:typeof O._closed=="boolean"&&u(O)?O._closed:null}function u(O){return typeof O._closed=="boolean"&&typeof O._defaultKeepAlive=="boolean"&&typeof O._removedConnection=="boolean"&&typeof O._removedContLen=="boolean"}function d(O){return typeof O._sent100=="boolean"&&u(O)}function n(O){var w;return typeof O._consuming=="boolean"&&typeof O._dumped=="boolean"&&((w=O.req)===null||w===void 0?void 0:w.upgradeOrConnect)===void 0}function B(O){if(!I(O))return null;let{_writableState:w,_readableState:k}=O,S=w||k;return!S&&d(O)||!!(S&&S.autoDestroy&&S.emitClose&&S.closed===!1)}function q(O){var w;return!!(O&&((w=O[X])!==null&&w!==void 0?w:O.readableDidRead||O.readableAborted))}function P(O){var w,k,S,_,W,j,b,p,s,r;return!!(O&&((w=(k=(S=(_=(W=(j=O[Y])!==null&&j!==void 0?j:O.readableErrored)!==null&&W!==void 0?W:O.writableErrored)!==null&&_!==void 0?_:(b=O._readableState)===null||b===void 0?void 0:b.errorEmitted)!==null&&S!==void 0?S:(p=O._writableState)===null||p===void 0?void 0:p.errorEmitted)!==null&&k!==void 0?k:(s=O._readableState)===null||s===void 0?void 0:s.errored)!==null&&w!==void 0?w:(r=O._writableState)===null||r===void 0?void 0:r.errored))}Q.exports={kDestroyed:U,isDisturbed:q,kIsDisturbed:X,isErrored:P,kIsErrored:Y,isReadable:M,kIsReadable:Z,isClosed:f,isDestroyed:F,isDuplexNodeStream:$,isFinished:h,isIterable:N,isReadableNodeStream:E,isReadableEnded:L,isReadableFinished:R,isReadableErrored:g,isNodeStream:I,isWritable:T,isWritableNodeStream:H,isWritableEnded:V,isWritableFinished:D,isWritableErrored:y,isServerRequest:n,isServerResponse:d,willEmitClose:B}}),u4=Y2((A,Q)=>{var J=(f4(),b4(w3)),{AbortError:K,codes:C}=k6(),{ERR_INVALID_ARG_TYPE:U,ERR_STREAM_PREMATURE_CLOSE:Y}=C,{kEmptyObject:Z,once:X}=V3(),{validateAbortSignal:E,validateFunction:H,validateObject:$}=BX(),{Promise:I}=q8(),{isClosed:N,isReadable:F,isReadableNodeStream:V,isReadableFinished:D,isReadableErrored:L,isWritable:R,isWritableNodeStream:M,isWritableFinished:T,isWritableErrored:h,isNodeStream:y,willEmitClose:g}=p4();function f(B){return B.setHeader&&typeof B.abort=="function"}var u=()=>{};function d(B,q,P){var O,w;arguments.length===2?(P=q,q=Z):q==null?q=Z:$(q,"options"),H(P,"callback"),E(q.signal,"options.signal"),P=X(P);let k=(O=q.readable)!==null&&O!==void 0?O:V(B),S=(w=q.writable)!==null&&w!==void 0?w:M(B);if(!y(B))throw new U("stream","Stream",B);let{_writableState:_,_readableState:W}=B,j=()=>{B.writable||s()},b=g(B)&&V(B)===k&&M(B)===S,p=T(B,!1),s=()=>{p=!0,B.destroyed&&(b=!1),!(b&&(!B.readable||k))&&(!k||r)&&P.call(B)},r=D(B,!1),A1=()=>{r=!0,B.destroyed&&(b=!1),!(b&&(!B.writable||S))&&(!S||p)&&P.call(B)},Q1=(E1)=>{P.call(B,E1)},e=N(B),t=()=>{e=!0;let E1=h(B)||L(B);if(E1&&typeof E1!="boolean")return P.call(B,E1);if(k&&!r&&V(B,!0)&&!D(B,!1))return P.call(B,new Y);if(S&&!p&&!T(B,!1))return P.call(B,new Y);P.call(B)},U1=()=>{B.req.on("finish",s)};f(B)?(B.on("complete",s),b||B.on("abort",t),B.req?U1():B.on("request",U1)):S&&!_&&(B.on("end",j),B.on("close",j)),!b&&typeof B.aborted=="boolean"&&B.on("aborted",t),B.on("end",A1),B.on("finish",s),q.error!==!1&&B.on("error",Q1),B.on("close",t),e?J.nextTick(t):_!=null&&_.errorEmitted||W!=null&&W.errorEmitted?b||J.nextTick(t):(!k&&(!b||F(B))&&(p||R(B)===!1)||!S&&(!b||R(B))&&(r||F(B)===!1)||W&&B.req&&B.aborted)&&J.nextTick(t);let O1=()=>{P=u,B.removeListener("aborted",t),B.removeListener("complete",s),B.removeListener("abort",t),B.removeListener("request",U1),B.req&&B.req.removeListener("finish",s),B.removeListener("end",j),B.removeListener("close",j),B.removeListener("finish",s),B.removeListener("end",A1),B.removeListener("error",Q1),B.removeListener("close",t)};if(q.signal&&!e){let E1=()=>{let Y1=P;O1(),Y1.call(B,new K(void 0,{cause:q.signal.reason}))};if(q.signal.aborted)J.nextTick(E1);else{let Y1=P;P=X((...i)=>{q.signal.removeEventListener("abort",E1),Y1.apply(B,i)}),q.signal.addEventListener("abort",E1)}}return O1}function n(B,q){return new I((P,O)=>{d(B,q,(w)=>{w?O(w):P()})})}Q.exports=d,Q.exports.finished=n}),Yi=Y2((A,Q)=>{var J=globalThis.AbortController||oI().AbortController,{codes:{ERR_INVALID_ARG_TYPE:K,ERR_MISSING_ARGS:C,ERR_OUT_OF_RANGE:U},AbortError:Y}=k6(),{validateAbortSignal:Z,validateInteger:X,validateObject:E}=BX(),H=q8().Symbol("kWeak"),{finished:$}=u4(),{ArrayPrototypePush:I,MathFloor:N,Number:F,NumberIsNaN:V,Promise:D,PromiseReject:L,PromisePrototypeThen:R,Symbol:M}=q8(),T=M("kEmpty"),h=M("kEof");function y(W,j){if(typeof W!="function")throw new K("fn",["Function","AsyncFunction"],W);j!=null&&E(j,"options"),j?.signal!=null&&Z(j.signal,"options.signal");let b=1;return j?.concurrency!=null&&(b=N(j.concurrency)),X(b,"concurrency",1),async function*(){var p,s;let r=new J,A1=this,Q1=[],e=r.signal,t={signal:e},U1=()=>r.abort();j!=null&&(p=j.signal)!==null&&p!==void 0&&p.aborted&&U1(),j==null||(s=j.signal)===null||s===void 0||s.addEventListener("abort",U1);let O1,E1,Y1=!1;function i(){Y1=!0}async function c(){try{for await(let q1 of A1){var o;if(Y1)return;if(e.aborted)throw new Y;try{q1=W(q1,t)}catch(Z1){q1=L(Z1)}q1!==T&&(typeof((o=q1)===null||o===void 0?void 0:o.catch)=="function"&&q1.catch(i),Q1.push(q1),O1&&(O1(),O1=null),!Y1&&Q1.length&&Q1.length>=b&&await new D((Z1)=>{E1=Z1}))}Q1.push(h)}catch(q1){let Z1=L(q1);R(Z1,void 0,i),Q1.push(Z1)}finally{var C1;Y1=!0,O1&&(O1(),O1=null),j==null||(C1=j.signal)===null||C1===void 0||C1.removeEventListener("abort",U1)}}c();try{for(;;){for(;Q1.length>0;){let o=await Q1[0];if(o===h)return;if(e.aborted)throw new Y;o!==T&&(yield o),Q1.shift(),E1&&(E1(),E1=null)}await new D((o)=>{O1=o})}}finally{r.abort(),Y1=!0,E1&&(E1(),E1=null)}}.call(this)}function g(W=void 0){return W!=null&&E(W,"options"),W?.signal!=null&&Z(W.signal,"options.signal"),async function*(){let j=0;for await(let p of this){var b;if(W!=null&&(b=W.signal)!==null&&b!==void 0&&b.aborted)throw new Y({cause:W.signal.reason});yield[j++,p]}}.call(this)}async function f(W,j=void 0){for await(let b of B.call(this,W,j))return!0;return!1}async function u(W,j=void 0){if(typeof W!="function")throw new K("fn",["Function","AsyncFunction"],W);return!await f.call(this,async(...b)=>!await W(...b),j)}async function d(W,j){for await(let b of B.call(this,W,j))return b}async function n(W,j){if(typeof W!="function")throw new K("fn",["Function","AsyncFunction"],W);async function b(p,s){return await W(p,s),T}for await(let p of y.call(this,b,j));}function B(W,j){if(typeof W!="function")throw new K("fn",["Function","AsyncFunction"],W);async function b(p,s){return await W(p,s)?p:T}return y.call(this,b,j)}var q=class extends C{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function P(W,j,b){var p;if(typeof W!="function")throw new K("reducer",["Function","AsyncFunction"],W);b!=null&&E(b,"options"),b?.signal!=null&&Z(b.signal,"options.signal");let s=arguments.length>1;if(b!=null&&(p=b.signal)!==null&&p!==void 0&&p.aborted){let t=new Y(void 0,{cause:b.signal.reason});throw this.once("error",()=>{}),await $(this.destroy(t)),t}let r=new J,A1=r.signal;if(b!=null&&b.signal){let t={once:!0,[H]:this};b.signal.addEventListener("abort",()=>r.abort(),t)}let Q1=!1;try{for await(let t of this){var e;if(Q1=!0,b!=null&&(e=b.signal)!==null&&e!==void 0&&e.aborted)throw new Y;s?j=await W(j,t,{signal:A1}):(j=t,s=!0)}if(!Q1&&!s)throw new q}finally{r.abort()}return j}async function O(W){W!=null&&E(W,"options"),W?.signal!=null&&Z(W.signal,"options.signal");let j=[];for await(let p of this){var b;if(W!=null&&(b=W.signal)!==null&&b!==void 0&&b.aborted)throw new Y(void 0,{cause:W.signal.reason});I(j,p)}return j}function w(W,j){let b=y.call(this,W,j);return async function*(){for await(let p of b)yield*p}.call(this)}function k(W){if(W=F(W),V(W))return 0;if(W<0)throw new U("number",">= 0",W);return W}function S(W,j=void 0){return j!=null&&E(j,"options"),j?.signal!=null&&Z(j.signal,"options.signal"),W=k(W),async function*(){var b;if(j!=null&&(b=j.signal)!==null&&b!==void 0&&b.aborted)throw new Y;for await(let s of this){var p;if(j!=null&&(p=j.signal)!==null&&p!==void 0&&p.aborted)throw new Y;W--<=0&&(yield s)}}.call(this)}function _(W,j=void 0){return j!=null&&E(j,"options"),j?.signal!=null&&Z(j.signal,"options.signal"),W=k(W),async function*(){var b;if(j!=null&&(b=j.signal)!==null&&b!==void 0&&b.aborted)throw new Y;for await(let s of this){var p;if(j!=null&&(p=j.signal)!==null&&p!==void 0&&p.aborted)throw new Y;if(W-- >0)yield s;else return}}.call(this)}Q.exports.streamReturningOperators={asIndexedPairs:g,drop:S,filter:B,flatMap:w,map:y,take:_},Q.exports.promiseReturningOperators={every:u,forEach:n,reduce:P,toArray:O,some:f,find:d}}),pJ=Y2((A,Q)=>{var J=(f4(),b4(w3)),{aggregateTwoErrors:K,codes:{ERR_MULTIPLE_CALLBACK:C},AbortError:U}=k6(),{Symbol:Y}=q8(),{kDestroyed:Z,isDestroyed:X,isFinished:E,isServerRequest:H}=p4(),$=Y("kDestroy"),I=Y("kConstruct");function N(B,q,P){B&&(B.stack,q&&!q.errored&&(q.errored=B),P&&!P.errored&&(P.errored=B))}function F(B,q){let P=this._readableState,O=this._writableState,w=O||P;return O&&O.destroyed||P&&P.destroyed?(typeof q=="function"&&q(),this):(N(B,O,P),O&&(O.destroyed=!0),P&&(P.destroyed=!0),w.constructed?V(this,B,q):this.once($,function(k){V(this,K(k,B),q)}),this)}function V(B,q,P){let O=!1;function w(k){if(O)return;O=!0;let{_readableState:S,_writableState:_}=B;N(k,_,S),_&&(_.closed=!0),S&&(S.closed=!0),typeof P=="function"&&P(k),k?J.nextTick(D,B,k):J.nextTick(L,B)}try{B._destroy(q||null,w)}catch(k){w(k)}}function D(B,q){R(B,q),L(B)}function L(B){let{_readableState:q,_writableState:P}=B;P&&(P.closeEmitted=!0),q&&(q.closeEmitted=!0),(P&&P.emitClose||q&&q.emitClose)&&B.emit("close")}function R(B,q){let{_readableState:P,_writableState:O}=B;O&&O.errorEmitted||P&&P.errorEmitted||(O&&(O.errorEmitted=!0),P&&(P.errorEmitted=!0),B.emit("error",q))}function M(){let B=this._readableState,q=this._writableState;B&&(B.constructed=!0,B.closed=!1,B.closeEmitted=!1,B.destroyed=!1,B.errored=null,B.errorEmitted=!1,B.reading=!1,B.ended=B.readable===!1,B.endEmitted=B.readable===!1),q&&(q.constructed=!0,q.destroyed=!1,q.closed=!1,q.closeEmitted=!1,q.errored=null,q.errorEmitted=!1,q.finalCalled=!1,q.prefinished=!1,q.ended=q.writable===!1,q.ending=q.writable===!1,q.finished=q.writable===!1)}function T(B,q,P){let{_readableState:O,_writableState:w}=B;if(w&&w.destroyed||O&&O.destroyed)return this;O&&O.autoDestroy||w&&w.autoDestroy?B.destroy(q):q&&(q.stack,w&&!w.errored&&(w.errored=q),O&&!O.errored&&(O.errored=q),P?J.nextTick(R,B,q):R(B,q))}function h(B,q){if(typeof B._construct!="function")return;let{_readableState:P,_writableState:O}=B;P&&(P.constructed=!1),O&&(O.constructed=!1),B.once(I,q),!(B.listenerCount(I)>1)&&J.nextTick(y,B)}function y(B){let q=!1;function P(O){if(q){T(B,O??new C);return}q=!0;let{_readableState:w,_writableState:k}=B,S=k||w;w&&(w.constructed=!0),k&&(k.constructed=!0),S.destroyed?B.emit($,O):O?T(B,O,!0):J.nextTick(g,B)}try{B._construct(P)}catch(O){P(O)}}function g(B){B.emit(I)}function f(B){return B&&B.setHeader&&typeof B.abort=="function"}function u(B){B.emit("close")}function d(B,q){B.emit("error",q),J.nextTick(u,B)}function n(B,q){!B||X(B)||(!q&&!E(B)&&(q=new U),H(B)?(B.socket=null,B.destroy(q)):f(B)?B.abort():f(B.req)?B.req.abort():typeof B.destroy=="function"?B.destroy(q):typeof B.close=="function"?B.close():q?J.nextTick(d,B,q):J.nextTick(u,B),B.destroyed||(B[Z]=!0))}Q.exports={construct:h,destroyer:n,destroy:F,undestroy:M,errorOrDestroy:T}}),iI=Y2((A,Q)=>{var J=typeof Reflect=="object"?Reflect:null,K=J&&typeof J.apply=="function"?J.apply:function(y,g,f){return Function.prototype.apply.call(y,g,f)},C;J&&typeof J.ownKeys=="function"?C=J.ownKeys:Object.getOwnPropertySymbols?C=function(y){return Object.getOwnPropertyNames(y).concat(Object.getOwnPropertySymbols(y))}:C=function(y){return Object.getOwnPropertyNames(y)};function U(y){console&&console.warn&&console.warn(y)}var Y=Number.isNaN||function(y){return y!==y};function Z(){Z.init.call(this)}Q.exports=Z,Q.exports.once=M,Z.EventEmitter=Z,Z.prototype._events=void 0,Z.prototype._eventsCount=0,Z.prototype._maxListeners=void 0;var X=10;function E(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(Z,"defaultMaxListeners",{enumerable:!0,get:function(){return X},set:function(y){if(typeof y!="number"||y<0||Y(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");X=y}}),Z.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Z.prototype.setMaxListeners=function(y){if(typeof y!="number"||y<0||Y(y))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+y+".");return this._maxListeners=y,this};function H(y){return y._maxListeners===void 0?Z.defaultMaxListeners:y._maxListeners}Z.prototype.getMaxListeners=function(){return H(this)},Z.prototype.emit=function(y){for(var g=[],f=1;f0&&(n=g[0]),n instanceof Error)throw n;var B=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw B.context=n,B}var q=d[y];if(q===void 0)return!1;if(typeof q=="function")K(q,this,g);else for(var P=q.length,O=D(q,P),f=0;f0&&B.length>d&&!B.warned){B.warned=!0;var q=new Error("Possible EventEmitter memory leak detected. "+B.length+" "+String(g)+" listeners added. Use emitter.setMaxListeners() to increase limit");q.name="MaxListenersExceededWarning",q.emitter=y,q.type=g,q.count=B.length,U(q)}return y}Z.prototype.addListener=function(y,g){return $(this,y,g,!1)},Z.prototype.on=Z.prototype.addListener,Z.prototype.prependListener=function(y,g){return $(this,y,g,!0)};function I(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function N(y,g,f){var u={fired:!1,wrapFn:void 0,target:y,type:g,listener:f},d=I.bind(u);return d.listener=f,u.wrapFn=d,d}Z.prototype.once=function(y,g){return E(g),this.on(y,N(this,y,g)),this},Z.prototype.prependOnceListener=function(y,g){return E(g),this.prependListener(y,N(this,y,g)),this},Z.prototype.removeListener=function(y,g){var f,u,d,n,B;if(E(g),u=this._events,u===void 0)return this;if(f=u[y],f===void 0)return this;if(f===g||f.listener===g)--this._eventsCount===0?this._events=Object.create(null):(delete u[y],u.removeListener&&this.emit("removeListener",y,f.listener||g));else if(typeof f!="function"){for(d=-1,n=f.length-1;n>=0;n--)if(f[n]===g||f[n].listener===g){B=f[n].listener,d=n;break}if(d<0)return this;d===0?f.shift():L(f,d),f.length===1&&(u[y]=f[0]),u.removeListener!==void 0&&this.emit("removeListener",y,B||g)}return this},Z.prototype.off=Z.prototype.removeListener,Z.prototype.removeAllListeners=function(y){var g,f,u;if(f=this._events,f===void 0)return this;if(f.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):f[y]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete f[y]),this;if(arguments.length===0){var d=Object.keys(f),n;for(u=0;u=0;u--)this.removeListener(y,g[u]);return this};function F(y,g,f){var u=y._events;if(u===void 0)return[];var d=u[g];return d===void 0?[]:typeof d=="function"?f?[d.listener||d]:[d]:f?R(d):D(d,d.length)}Z.prototype.listeners=function(y){return F(this,y,!0)},Z.prototype.rawListeners=function(y){return F(this,y,!1)},Z.listenerCount=function(y,g){return typeof y.listenerCount=="function"?y.listenerCount(g):V.call(y,g)},Z.prototype.listenerCount=V;function V(y){var g=this._events;if(g!==void 0){var f=g[y];if(typeof f=="function")return 1;if(f!==void 0)return f.length}return 0}Z.prototype.eventNames=function(){return this._eventsCount>0?C(this._events):[]};function D(y,g){for(var f=new Array(g),u=0;u{var{ArrayIsArray:J,ObjectSetPrototypeOf:K}=q8(),{EventEmitter:C}=iI();function U(Z){C.call(this,Z)}K(U.prototype,C.prototype),K(U,C),U.prototype.pipe=function(Z,X){let E=this;function H(L){Z.writable&&Z.write(L)===!1&&E.pause&&E.pause()}E.on("data",H);function $(){E.readable&&E.resume&&E.resume()}Z.on("drain",$),!Z._isStdio&&(!X||X.end!==!1)&&(E.on("end",N),E.on("close",F));let I=!1;function N(){I||(I=!0,Z.end())}function F(){I||(I=!0,typeof Z.destroy=="function"&&Z.destroy())}function V(L){D(),C.listenerCount(this,"error")===0&&this.emit("error",L)}Y(E,"error",V),Y(Z,"error",V);function D(){E.removeListener("data",H),Z.removeListener("drain",$),E.removeListener("end",N),E.removeListener("close",F),E.removeListener("error",V),Z.removeListener("error",V),E.removeListener("end",D),E.removeListener("close",D),Z.removeListener("close",D)}return E.on("end",D),E.on("close",D),Z.on("close",D),Z.emit("pipe",E),Z};function Y(Z,X,E){if(typeof Z.prependListener=="function")return Z.prependListener(X,E);!Z._events||!Z._events[X]?Z.on(X,E):J(Z._events[X])?Z._events[X].unshift(E):Z._events[X]=[E,Z._events[X]]}Q.exports={Stream:U,prependListener:Y}}),rI=Y2((A,Q)=>{var{AbortError:J,codes:K}=k6(),C=u4(),{ERR_INVALID_ARG_TYPE:U}=K,Y=(X,E)=>{if(typeof X!="object"||!("aborted"in X))throw new U(E,"AbortSignal",X)};function Z(X){return!!(X&&typeof X.pipe=="function")}Q.exports.addAbortSignal=function(X,E){if(Y(X,"signal"),!Z(E))throw new U("stream","stream.Stream",E);return Q.exports.addAbortSignalNoValidate(X,E)},Q.exports.addAbortSignalNoValidate=function(X,E){if(typeof X!="object"||!("aborted"in X))return E;let H=()=>{E.destroy(new J(void 0,{cause:X.reason}))};return X.aborted?H():(X.addEventListener("abort",H),C(E,()=>X.removeEventListener("abort",H))),E}}),Ui=Y2((A,Q)=>{var{StringPrototypeSlice:J,SymbolIterator:K,TypedArrayPrototypeSet:C,Uint8Array:U}=q8(),{Buffer:Y}=y7(),{inspect:Z}=V3();Q.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(X){let E={data:X,next:null};this.length>0?this.tail.next=E:this.head=E,this.tail=E,++this.length}unshift(X){let E={data:X,next:this.head};this.length===0&&(this.tail=E),this.head=E,++this.length}shift(){if(this.length===0)return;let X=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,X}clear(){this.head=this.tail=null,this.length=0}join(X){if(this.length===0)return"";let E=this.head,H=""+E.data;for(;(E=E.next)!==null;)H+=X+E.data;return H}concat(X){if(this.length===0)return Y.alloc(0);let E=Y.allocUnsafe(X>>>0),H=this.head,$=0;for(;H;)C(E,H.data,$),$+=H.data.length,H=H.next;return E}consume(X,E){let H=this.head.data;if(XI.length)E+=I,X-=I.length;else{X===I.length?(E+=I,++$,H.next?this.head=H.next:this.head=this.tail=null):(E+=J(I,0,X),this.head=H,H.data=J(I,X));break}++$}while((H=H.next)!==null);return this.length-=$,E}_getBuffer(X){let E=Y.allocUnsafe(X),H=X,$=this.head,I=0;do{let N=$.data;if(X>N.length)C(E,N,H-X),X-=N.length;else{X===N.length?(C(E,N,H-X),++I,$.next?this.head=$.next:this.head=this.tail=null):(C(E,new U(N.buffer,N.byteOffset,X),H-X),this.head=$,$.data=N.slice(X));break}++I}while(($=$.next)!==null);return this.length-=I,E}[Symbol.for("nodejs.util.inspect.custom")](X,E){return Z(this,{...E,depth:0,customInspect:!1})}}}),tI=Y2((A,Q)=>{var{MathFloor:J,NumberIsInteger:K}=q8(),{ERR_INVALID_ARG_VALUE:C}=k6().codes;function U(X,E,H){return X.highWaterMark!=null?X.highWaterMark:E?X[H]:null}function Y(X){return X?16:16384}function Z(X,E,H,$){let I=U(E,$,H);if(I!=null){if(!K(I)||I<0){let N=$?`options.${H}`:"options.highWaterMark";throw new C(N,I)}return J(I)}return Y(X.objectMode)}Q.exports={getHighWaterMark:Z,getDefaultHighWaterMark:Y}}),Zi=Y2((A,Q)=>{var J=y7(),K=J.Buffer;function C(Y,Z){for(var X in Y)Z[X]=Y[X]}K.from&&K.alloc&&K.allocUnsafe&&K.allocUnsafeSlow?Q.exports=J:(C(J,A),A.Buffer=U);function U(Y,Z,X){return K(Y,Z,X)}U.prototype=Object.create(K.prototype),C(K,U),U.from=function(Y,Z,X){if(typeof Y=="number")throw new TypeError("Argument must not be a number");return K(Y,Z,X)},U.alloc=function(Y,Z,X){if(typeof Y!="number")throw new TypeError("Argument must be a number");var E=K(Y);return Z!==void 0?typeof X=="string"?E.fill(Z,X):E.fill(Z):E.fill(0),E},U.allocUnsafe=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return K(Y)},U.allocUnsafeSlow=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return J.SlowBuffer(Y)}}),Bi=Y2((A)=>{var Q=Zi().Buffer,J=Q.isEncoding||function(R){switch(R=""+R,R&&R.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function K(R){if(!R)return"utf8";for(var M;;)switch(R){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return R;default:if(M)return;R=(""+R).toLowerCase(),M=!0}}function C(R){var M=K(R);if(typeof M!="string"&&(Q.isEncoding===J||!J(R)))throw new Error("Unknown encoding: "+R);return M||R}A.StringDecoder=U;function U(R){this.encoding=C(R);var M;switch(this.encoding){case"utf16le":this.text=I,this.end=N,M=4;break;case"utf8":this.fillLast=E,M=4;break;case"base64":this.text=F,this.end=V,M=3;break;default:this.write=D,this.end=L;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Q.allocUnsafe(M)}U.prototype.write=function(R){if(R.length===0)return"";var M,T;if(this.lastNeed){if(M=this.fillLast(R),M===void 0)return"";T=this.lastNeed,this.lastNeed=0}else T=0;return T>5===6?2:R>>4===14?3:R>>3===30?4:R>>6===2?-1:-2}function Z(R,M,T){var h=M.length-1;if(h=0?(y>0&&(R.lastNeed=y-1),y):--h=0?(y>0&&(R.lastNeed=y-2),y):--h=0?(y>0&&(y===2?y=0:R.lastNeed=y-3),y):0))}function X(R,M,T){if((M[0]&192)!==128)return R.lastNeed=0,"�";if(R.lastNeed>1&&M.length>1){if((M[1]&192)!==128)return R.lastNeed=1,"�";if(R.lastNeed>2&&M.length>2&&(M[2]&192)!==128)return R.lastNeed=2,"�"}}function E(R){var M=this.lastTotal-this.lastNeed,T=X(this,R,M);if(T!==void 0)return T;if(this.lastNeed<=R.length)return R.copy(this.lastChar,M,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);R.copy(this.lastChar,M,0,R.length),this.lastNeed-=R.length}function H(R,M){var T=Z(this,R,M);if(!this.lastNeed)return R.toString("utf8",M);this.lastTotal=T;var h=R.length-(T-this.lastNeed);return R.copy(this.lastChar,0,h),R.toString("utf8",M,h)}function $(R){var M=R&&R.length?this.write(R):"";return this.lastNeed?M+"�":M}function I(R,M){if((R.length-M)%2===0){var T=R.toString("utf16le",M);if(T){var h=T.charCodeAt(T.length-1);if(h>=55296&&h<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=R[R.length-2],this.lastChar[1]=R[R.length-1],T.slice(0,-1)}return T}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=R[R.length-1],R.toString("utf16le",M,R.length-1)}function N(R){var M=R&&R.length?this.write(R):"";if(this.lastNeed){var T=this.lastTotal-this.lastNeed;return M+this.lastChar.toString("utf16le",0,T)}return M}function F(R,M){var T=(R.length-M)%3;return T===0?R.toString("base64",M):(this.lastNeed=3-T,this.lastTotal=3,T===1?this.lastChar[0]=R[R.length-1]:(this.lastChar[0]=R[R.length-2],this.lastChar[1]=R[R.length-1]),R.toString("base64",M,R.length-T))}function V(R){var M=R&&R.length?this.write(R):"";return this.lastNeed?M+this.lastChar.toString("base64",0,3-this.lastNeed):M}function D(R){return R.toString(this.encoding)}function L(R){return R&&R.length?this.write(R):""}}),Pw=Y2((A,Q)=>{var J=(f4(),b4(w3)),{PromisePrototypeThen:K,SymbolAsyncIterator:C,SymbolIterator:U}=q8(),{Buffer:Y}=y7(),{ERR_INVALID_ARG_TYPE:Z,ERR_STREAM_NULL_VALUES:X}=k6().codes;function E(H,$,I){let N;if(typeof $=="string"||$ instanceof Y)return new H({objectMode:!0,...I,read(){this.push($),this.push(null)}});let F;if($&&$[C])F=!0,N=$[C]();else if($&&$[U])F=!1,N=$[U]();else throw new Z("iterable",["Iterable"],$);let V=new H({objectMode:!0,highWaterMark:1,...I}),D=!1;V._read=function(){D||(D=!0,R())},V._destroy=function(M,T){K(L(M),()=>J.nextTick(T,M),(h)=>J.nextTick(T,h||M))};async function L(M){let T=M!=null,h=typeof N.throw=="function";if(T&&h){let{value:y,done:g}=await N.throw(M);if(await y,g)return}if(typeof N.return=="function"){let{value:y}=await N.return();await y}}async function R(){for(;;){try{let{value:M,done:T}=F?await N.next():N.next();if(T)V.push(null);else{let h=M&&typeof M.then=="function"?await M:M;if(h===null)throw D=!1,new X;if(V.push(h))continue;D=!1}}catch(M){V.destroy(M)}break}}return V}Q.exports=E}),XX=Y2((A,Q)=>{var J=(f4(),b4(w3)),{ArrayPrototypeIndexOf:K,NumberIsInteger:C,NumberIsNaN:U,NumberParseInt:Y,ObjectDefineProperties:Z,ObjectKeys:X,ObjectSetPrototypeOf:E,Promise:H,SafeSet:$,SymbolAsyncIterator:I,Symbol:N}=q8();Q.exports=b,b.ReadableState=j;var{EventEmitter:F}=iI(),{Stream:V,prependListener:D}=aI(),{Buffer:L}=y7(),{addAbortSignal:R}=rI(),M=u4(),T=V3().debuglog("stream",(G)=>{T=G}),h=Ui(),y=pJ(),{getHighWaterMark:g,getDefaultHighWaterMark:f}=tI(),{aggregateTwoErrors:u,codes:{ERR_INVALID_ARG_TYPE:d,ERR_METHOD_NOT_IMPLEMENTED:n,ERR_OUT_OF_RANGE:B,ERR_STREAM_PUSH_AFTER_EOF:q,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:P}}=k6(),{validateObject:O}=BX(),w=N("kPaused"),{StringDecoder:k}=Bi(),S=Pw();E(b.prototype,V.prototype),E(b,V);var _=()=>{},{errorOrDestroy:W}=y;function j(G,z,x){typeof x!="boolean"&&(x=z instanceof M3()),this.objectMode=!!(G&&G.objectMode),x&&(this.objectMode=this.objectMode||!!(G&&G.readableObjectMode)),this.highWaterMark=G?g(this,G,"readableHighWaterMark",x):f(!1),this.buffer=new h,this.length=0,this.pipes=[],this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.constructed=!0,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this[w]=null,this.errorEmitted=!1,this.emitClose=!G||G.emitClose!==!1,this.autoDestroy=!G||G.autoDestroy!==!1,this.destroyed=!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this.defaultEncoding=G&&G.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.multiAwaitDrain=!1,this.readingMore=!1,this.dataEmitted=!1,this.decoder=null,this.encoding=null,G&&G.encoding&&(this.decoder=new k(G.encoding),this.encoding=G.encoding)}function b(G){if(!(this instanceof b))return new b(G);let z=this instanceof M3();this._readableState=new j(G,this,z),G&&(typeof G.read=="function"&&(this._read=G.read),typeof G.destroy=="function"&&(this._destroy=G.destroy),typeof G.construct=="function"&&(this._construct=G.construct),G.signal&&!z&&R(G.signal,this)),V.call(this,G),y.construct(this,()=>{this._readableState.needReadable&&O1(this,this._readableState)})}b.prototype.destroy=y.destroy,b.prototype._undestroy=y.undestroy,b.prototype._destroy=function(G,z){z(G)},b.prototype[F.captureRejectionSymbol]=function(G){this.destroy(G)},b.prototype.push=function(G,z){return p(this,G,z,!1)},b.prototype.unshift=function(G,z){return p(this,G,z,!0)};function p(G,z,x,m){T("readableAddChunk",z);let l=G._readableState,a;if(l.objectMode||(typeof z=="string"?(x=x||l.defaultEncoding,l.encoding!==x&&(m&&l.encoding?z=L.from(z,x).toString(l.encoding):(z=L.from(z,x),x=""))):z instanceof L?x="":V._isUint8Array(z)?(z=V._uint8ArrayToBuffer(z),x=""):z!=null&&(a=new d("chunk",["string","Buffer","Uint8Array"],z))),a)W(G,a);else if(z===null)l.reading=!1,e(G,l);else if(l.objectMode||z&&z.length>0)if(m)if(l.endEmitted)W(G,new P);else{if(l.destroyed||l.errored)return!1;s(G,l,z,!0)}else if(l.ended)W(G,new q);else{if(l.destroyed||l.errored)return!1;l.reading=!1,l.decoder&&!x?(z=l.decoder.write(z),l.objectMode||z.length!==0?s(G,l,z,!1):O1(G,l)):s(G,l,z,!1)}else m||(l.reading=!1,O1(G,l));return!l.ended&&(l.length0?(z.multiAwaitDrain?z.awaitDrainWriters.clear():z.awaitDrainWriters=null,z.dataEmitted=!0,G.emit("data",x)):(z.length+=z.objectMode?1:x.length,m?z.buffer.unshift(x):z.buffer.push(x),z.needReadable&&t(G)),O1(G,z)}b.prototype.isPaused=function(){let G=this._readableState;return G[w]===!0||G.flowing===!1},b.prototype.setEncoding=function(G){let z=new k(G);this._readableState.decoder=z,this._readableState.encoding=this._readableState.decoder.encoding;let x=this._readableState.buffer,m="";for(let l of x)m+=z.write(l);return x.clear(),m!==""&&x.push(m),this._readableState.length=m.length,this};var r=1073741824;function A1(G){if(G>r)throw new B("size","<= 1GiB",G);return G--,G|=G>>>1,G|=G>>>2,G|=G>>>4,G|=G>>>8,G|=G>>>16,G++,G}function Q1(G,z){return G<=0||z.length===0&&z.ended?0:z.objectMode?1:U(G)?z.flowing&&z.length?z.buffer.first().length:z.length:G<=z.length?G:z.ended?z.length:0}b.prototype.read=function(G){T("read",G),G===void 0?G=NaN:C(G)||(G=Y(G,10));let z=this._readableState,x=G;if(G>z.highWaterMark&&(z.highWaterMark=A1(G)),G!==0&&(z.emittedReadable=!1),G===0&&z.needReadable&&((z.highWaterMark!==0?z.length>=z.highWaterMark:z.length>0)||z.ended))return T("read: emitReadable",z.length,z.ended),z.length===0&&z.ended?B1(this):t(this),null;if(G=Q1(G,z),G===0&&z.ended)return z.length===0&&B1(this),null;let m=z.needReadable;if(T("need readable",m),(z.length===0||z.length-G0?l=H1(G,z):l=null,l===null?(z.needReadable=z.length<=z.highWaterMark,G=0):(z.length-=G,z.multiAwaitDrain?z.awaitDrainWriters.clear():z.awaitDrainWriters=null),z.length===0&&(z.ended||(z.needReadable=!0),x!==G&&z.ended&&B1(this)),l!==null&&!z.errorEmitted&&!z.closeEmitted&&(z.dataEmitted=!0,this.emit("data",l)),l};function e(G,z){if(T("onEofChunk"),!z.ended){if(z.decoder){let x=z.decoder.end();x&&x.length&&(z.buffer.push(x),z.length+=z.objectMode?1:x.length)}z.ended=!0,z.sync?t(G):(z.needReadable=!1,z.emittedReadable=!0,U1(G))}}function t(G){let z=G._readableState;T("emitReadable",z.needReadable,z.emittedReadable),z.needReadable=!1,z.emittedReadable||(T("emitReadable",z.flowing),z.emittedReadable=!0,J.nextTick(U1,G))}function U1(G){let z=G._readableState;T("emitReadable_",z.destroyed,z.length,z.ended),!z.destroyed&&!z.errored&&(z.length||z.ended)&&(G.emit("readable"),z.emittedReadable=!1),z.needReadable=!z.flowing&&!z.ended&&z.length<=z.highWaterMark,q1(G)}function O1(G,z){!z.readingMore&&z.constructed&&(z.readingMore=!0,J.nextTick(E1,G,z))}function E1(G,z){for(;!z.reading&&!z.ended&&(z.length1&&m.pipes.includes(G)&&(T("false write response, pause",m.awaitDrainWriters.size),m.awaitDrainWriters.add(G)),x.pause()),F1||(F1=Y1(x,G),G.on("drain",F1))}x.on("data",$1);function $1(M1){T("ondata");let L1=G.write(M1);T("dest.write",L1),L1===!1&&W1()}function N1(M1){if(T("onerror",M1),z1(),G.removeListener("error",N1),G.listenerCount("error")===0){let L1=G._writableState||G._readableState;L1&&!L1.errorEmitted?W(G,M1):G.emit("error",M1)}}D(G,"error",N1);function _1(){G.removeListener("finish",J1),z1()}G.once("close",_1);function J1(){T("onfinish"),G.removeListener("close",_1),z1()}G.once("finish",J1);function z1(){T("unpipe"),x.unpipe(G)}return G.emit("pipe",x),G.writableNeedDrain===!0?m.flowing&&W1():m.flowing||(T("pipe resume"),x.resume()),G};function Y1(G,z){return function(){let x=G._readableState;x.awaitDrainWriters===z?(T("pipeOnDrain",1),x.awaitDrainWriters=null):x.multiAwaitDrain&&(T("pipeOnDrain",x.awaitDrainWriters.size),x.awaitDrainWriters.delete(z)),(!x.awaitDrainWriters||x.awaitDrainWriters.size===0)&&G.listenerCount("data")&&G.resume()}}b.prototype.unpipe=function(G){let z=this._readableState,x={hasUnpiped:!1};if(z.pipes.length===0)return this;if(!G){let l=z.pipes;z.pipes=[],this.pause();for(let a=0;a0,m.flowing!==!1&&this.resume()):G==="readable"&&!m.endEmitted&&!m.readableListening&&(m.readableListening=m.needReadable=!0,m.flowing=!1,m.emittedReadable=!1,T("on readable",m.length,m.reading),m.length?t(this):m.reading||J.nextTick(c,this)),x},b.prototype.addListener=b.prototype.on,b.prototype.removeListener=function(G,z){let x=V.prototype.removeListener.call(this,G,z);return G==="readable"&&J.nextTick(i,this),x},b.prototype.off=b.prototype.removeListener,b.prototype.removeAllListeners=function(G){let z=V.prototype.removeAllListeners.apply(this,arguments);return(G==="readable"||G===void 0)&&J.nextTick(i,this),z};function i(G){let z=G._readableState;z.readableListening=G.listenerCount("readable")>0,z.resumeScheduled&&z[w]===!1?z.flowing=!0:G.listenerCount("data")>0?G.resume():z.readableListening||(z.flowing=null)}function c(G){T("readable nexttick read 0"),G.read(0)}b.prototype.resume=function(){let G=this._readableState;return G.flowing||(T("resume"),G.flowing=!G.readableListening,o(this,G)),G[w]=!1,this};function o(G,z){z.resumeScheduled||(z.resumeScheduled=!0,J.nextTick(C1,G,z))}function C1(G,z){T("resume",z.reading),z.reading||G.read(0),z.resumeScheduled=!1,G.emit("resume"),q1(G),z.flowing&&!z.reading&&G.read(0)}b.prototype.pause=function(){return T("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(T("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[w]=!0,this};function q1(G){let z=G._readableState;for(T("flow",z.flowing);z.flowing&&G.read()!==null;);}b.prototype.wrap=function(G){let z=!1;G.on("data",(m)=>{!this.push(m)&&G.pause&&(z=!0,G.pause())}),G.on("end",()=>{this.push(null)}),G.on("error",(m)=>{W(this,m)}),G.on("close",()=>{this.destroy()}),G.on("destroy",()=>{this.destroy()}),this._read=()=>{z&&G.resume&&(z=!1,G.resume())};let x=X(G);for(let m=1;m{l=K1?u(l,K1):null,x(),x=_});try{for(;;){let K1=G.destroyed?null:G.read();if(K1!==null)yield K1;else{if(l)throw l;if(l===null)return;await new H(m)}}}catch(K1){throw l=u(l,K1),l}finally{(l||z?.destroyOnReturn!==!1)&&(l===void 0||G._readableState.autoDestroy)?y.destroyer(G,null):(G.off("readable",m),a())}}Z(b.prototype,{readable:{__proto__:null,get(){let G=this._readableState;return!!G&&G.readable!==!1&&!G.destroyed&&!G.errorEmitted&&!G.endEmitted},set(G){this._readableState&&(this._readableState.readable=!!G)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(G){this._readableState&&(this._readableState.flowing=G)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(G){!this._readableState||(this._readableState.destroyed=G)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),Z(j.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[w]!==!1},set(G){this[w]=!!G}}}),b._fromList=H1;function H1(G,z){if(z.length===0)return null;let x;return z.objectMode?x=z.buffer.shift():!G||G>=z.length?(z.decoder?x=z.buffer.join(""):z.buffer.length===1?x=z.buffer.first():x=z.buffer.concat(z.length),z.buffer.clear()):x=z.buffer.consume(G,z.decoder),x}function B1(G){let z=G._readableState;T("endReadable",z.endEmitted),z.endEmitted||(z.ended=!0,J.nextTick(k1,z,G))}function k1(G,z){if(T("endReadableNT",G.endEmitted,G.length),!G.errored&&!G.closeEmitted&&!G.endEmitted&&G.length===0){if(G.endEmitted=!0,z.emit("end"),z.writable&&z.allowHalfOpen===!1)J.nextTick(D1,z);else if(G.autoDestroy){let x=z._writableState;(!x||x.autoDestroy&&(x.finished||x.writable===!1))&&z.destroy()}}}function D1(G){G.writable&&!G.writableEnded&&!G.destroyed&&G.end()}b.from=function(G,z){return S(b,G,z)};var G1;function w1(){return G1===void 0&&(G1={}),G1}b.fromWeb=function(G,z){return w1().newStreamReadableFromReadableStream(G,z)},b.toWeb=function(G,z){return w1().newReadableStreamFromStreamReadable(G,z)},b.wrap=function(G,z){var x,m;return new b({objectMode:(x=(m=G.readableObjectMode)!==null&&m!==void 0?m:G.objectMode)!==null&&x!==void 0?x:!0,...z,destroy(l,a){y.destroyer(G,l),a(l)}}).wrap(G)}}),_w=Y2((A,Q)=>{var J=(f4(),b4(w3)),{ArrayPrototypeSlice:K,Error:C,FunctionPrototypeSymbolHasInstance:U,ObjectDefineProperty:Y,ObjectDefineProperties:Z,ObjectSetPrototypeOf:X,StringPrototypeToLowerCase:E,Symbol:H,SymbolHasInstance:$}=q8();Q.exports=k,k.WritableState=O;var{EventEmitter:I}=iI(),N=aI().Stream,{Buffer:F}=y7(),V=pJ(),{addAbortSignal:D}=rI(),{getHighWaterMark:L,getDefaultHighWaterMark:R}=tI(),{ERR_INVALID_ARG_TYPE:M,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_MULTIPLE_CALLBACK:h,ERR_STREAM_CANNOT_PIPE:y,ERR_STREAM_DESTROYED:g,ERR_STREAM_ALREADY_FINISHED:f,ERR_STREAM_NULL_VALUES:u,ERR_STREAM_WRITE_AFTER_END:d,ERR_UNKNOWN_ENCODING:n}=k6().codes,{errorOrDestroy:B}=V;X(k.prototype,N.prototype),X(k,N);function q(){}var P=H("kOnFinished");function O(c,o,C1){typeof C1!="boolean"&&(C1=o instanceof M3()),this.objectMode=!!(c&&c.objectMode),C1&&(this.objectMode=this.objectMode||!!(c&&c.writableObjectMode)),this.highWaterMark=c?L(this,c,"writableHighWaterMark",C1):R(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let q1=!!(c&&c.decodeStrings===!1);this.decodeStrings=!q1,this.defaultEncoding=c&&c.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=b.bind(void 0,o),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,w(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!c||c.emitClose!==!1,this.autoDestroy=!c||c.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[P]=[]}function w(c){c.buffered=[],c.bufferedIndex=0,c.allBuffers=!0,c.allNoop=!0}O.prototype.getBuffer=function(){return K(this.buffered,this.bufferedIndex)},Y(O.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function k(c){let o=this instanceof M3();if(!o&&!U(k,this))return new k(c);this._writableState=new O(c,this,o),c&&(typeof c.write=="function"&&(this._write=c.write),typeof c.writev=="function"&&(this._writev=c.writev),typeof c.destroy=="function"&&(this._destroy=c.destroy),typeof c.final=="function"&&(this._final=c.final),typeof c.construct=="function"&&(this._construct=c.construct),c.signal&&D(c.signal,this)),N.call(this,c),V.construct(this,()=>{let C1=this._writableState;C1.writing||A1(this,C1),U1(this,C1)})}Y(k,$,{__proto__:null,value:function(c){return U(this,c)?!0:this!==k?!1:c&&c._writableState instanceof O}}),k.prototype.pipe=function(){B(this,new y)};function S(c,o,C1,q1){let Z1=c._writableState;if(typeof C1=="function")q1=C1,C1=Z1.defaultEncoding;else{if(!C1)C1=Z1.defaultEncoding;else if(C1!=="buffer"&&!F.isEncoding(C1))throw new n(C1);typeof q1!="function"&&(q1=q)}if(o===null)throw new u;if(!Z1.objectMode)if(typeof o=="string")Z1.decodeStrings!==!1&&(o=F.from(o,C1),C1="buffer");else if(o instanceof F)C1="buffer";else if(N._isUint8Array(o))o=N._uint8ArrayToBuffer(o),C1="buffer";else throw new M("chunk",["string","Buffer","Uint8Array"],o);let j1;return Z1.ending?j1=new d:Z1.destroyed&&(j1=new g("write")),j1?(J.nextTick(q1,j1),B(c,j1,!0),j1):(Z1.pendingcb++,_(c,Z1,o,C1,q1))}k.prototype.write=function(c,o,C1){return S(this,c,o,C1)===!0},k.prototype.cork=function(){this._writableState.corked++},k.prototype.uncork=function(){let c=this._writableState;c.corked&&(c.corked--,c.writing||A1(this,c))},k.prototype.setDefaultEncoding=function(c){if(typeof c=="string"&&(c=E(c)),!F.isEncoding(c))throw new n(c);return this._writableState.defaultEncoding=c,this};function _(c,o,C1,q1,Z1){let j1=o.objectMode?1:C1.length;o.length+=j1;let H1=o.lengthC1.bufferedIndex&&A1(c,C1),q1?C1.afterWriteTickInfo!==null&&C1.afterWriteTickInfo.cb===Z1?C1.afterWriteTickInfo.count++:(C1.afterWriteTickInfo={count:1,cb:Z1,stream:c,state:C1},J.nextTick(p,C1.afterWriteTickInfo)):s(c,C1,1,Z1))}function p({stream:c,state:o,count:C1,cb:q1}){return o.afterWriteTickInfo=null,s(c,o,C1,q1)}function s(c,o,C1,q1){for(!o.ending&&!c.destroyed&&o.length===0&&o.needDrain&&(o.needDrain=!1,c.emit("drain"));C1-- >0;)o.pendingcb--,q1();o.destroyed&&r(o),U1(c,o)}function r(c){if(c.writing)return;for(let Z1=c.bufferedIndex;Z11&&c._writev){o.pendingcb-=j1-1;let B1=o.allNoop?q:(D1)=>{for(let G1=H1;G1256?(C1.splice(0,H1),o.bufferedIndex=0):o.bufferedIndex=H1}o.bufferProcessing=!1}k.prototype._write=function(c,o,C1){if(this._writev)this._writev([{chunk:c,encoding:o}],C1);else throw new T("_write()")},k.prototype._writev=null,k.prototype.end=function(c,o,C1){let q1=this._writableState;typeof c=="function"?(C1=c,c=null,o=null):typeof o=="function"&&(C1=o,o=null);let Z1;if(c!=null){let j1=S(this,c,o);j1 instanceof C&&(Z1=j1)}return q1.corked&&(q1.corked=1,this.uncork()),Z1||(!q1.errored&&!q1.ending?(q1.ending=!0,U1(this,q1,!0),q1.ended=!0):q1.finished?Z1=new f("end"):q1.destroyed&&(Z1=new g("end"))),typeof C1=="function"&&(Z1||q1.finished?J.nextTick(C1,Z1):q1[P].push(C1)),this};function Q1(c){return c.ending&&!c.destroyed&&c.constructed&&c.length===0&&!c.errored&&c.buffered.length===0&&!c.finished&&!c.writing&&!c.errorEmitted&&!c.closeEmitted}function e(c,o){let C1=!1;function q1(Z1){if(C1){B(c,Z1??h());return}if(C1=!0,o.pendingcb--,Z1){let j1=o[P].splice(0);for(let H1=0;H1{Q1(Z1)?O1(q1,Z1):Z1.pendingcb--},c,o)):Q1(o)&&(o.pendingcb++,O1(c,o))))}function O1(c,o){o.pendingcb--,o.finished=!0;let C1=o[P].splice(0);for(let q1=0;q1{var J=(f4(),b4(w3)),K=y7(),{isReadable:C,isWritable:U,isIterable:Y,isNodeStream:Z,isReadableNodeStream:X,isWritableNodeStream:E,isDuplexNodeStream:H}=p4(),$=u4(),{AbortError:I,codes:{ERR_INVALID_ARG_TYPE:N,ERR_INVALID_RETURN_VALUE:F}}=k6(),{destroyer:V}=pJ(),D=M3(),L=XX(),{createDeferredPromise:R}=V3(),M=Pw(),T=globalThis.Blob||K.Blob,h=typeof T<"u"?function(n){return n instanceof T}:function(n){return!1},y=globalThis.AbortController||oI().AbortController,{FunctionPrototypeCall:g}=q8(),f=class extends D{constructor(n){super(n),n?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),n?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};Q.exports=function n(B,q){if(H(B))return B;if(X(B))return d({readable:B});if(E(B))return d({writable:B});if(Z(B))return d({writable:!1,readable:!1});if(typeof B=="function"){let{value:O,write:w,final:k,destroy:S}=u(B);if(Y(O))return M(f,O,{objectMode:!0,write:w,final:k,destroy:S});let _=O?.then;if(typeof _=="function"){let W,j=g(_,O,(b)=>{if(b!=null)throw new F("nully","body",b)},(b)=>{V(W,b)});return W=new f({objectMode:!0,readable:!1,write:w,final(b){k(async()=>{try{await j,J.nextTick(b,null)}catch(p){J.nextTick(b,p)}})},destroy:S})}throw new F("Iterable, AsyncIterable or AsyncFunction",q,O)}if(h(B))return n(B.arrayBuffer());if(Y(B))return M(f,B,{objectMode:!0,writable:!1});if(typeof B?.writable=="object"||typeof B?.readable=="object"){let O=B!=null&&B.readable?X(B?.readable)?B?.readable:n(B.readable):void 0,w=B!=null&&B.writable?E(B?.writable)?B?.writable:n(B.writable):void 0;return d({readable:O,writable:w})}let P=B?.then;if(typeof P=="function"){let O;return g(P,B,(w)=>{w!=null&&O.push(w),O.push(null)},(w)=>{V(O,w)}),O=new f({objectMode:!0,writable:!1,read(){}})}throw new N(q,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],B)};function u(n){let{promise:B,resolve:q}=R(),P=new y,O=P.signal;return{value:n(async function*(){for(;;){let w=B;B=null;let{chunk:k,done:S,cb:_}=await w;if(J.nextTick(_),S)return;if(O.aborted)throw new I(void 0,{cause:O.reason});({promise:B,resolve:q}=R()),yield k}}(),{signal:O}),write(w,k,S){let _=q;q=null,_({chunk:w,done:!1,cb:S})},final(w){let k=q;q=null,k({done:!0,cb:w})},destroy(w,k){P.abort(),k(w)}}}function d(n){let B=n.readable&&typeof n.readable.read!="function"?L.wrap(n.readable):n.readable,q=n.writable,P=!!C(B),O=!!U(q),w,k,S,_,W;function j(b){let p=_;_=null,p?p(b):b?W.destroy(b):!P&&!O&&W.destroy()}return W=new f({readableObjectMode:!!(B!=null&&B.readableObjectMode),writableObjectMode:!!(q!=null&&q.writableObjectMode),readable:P,writable:O}),O&&($(q,(b)=>{O=!1,b&&V(B,b),j(b)}),W._write=function(b,p,s){q.write(b,p)?s():w=s},W._final=function(b){q.end(),k=b},q.on("drain",function(){if(w){let b=w;w=null,b()}}),q.on("finish",function(){if(k){let b=k;k=null,b()}})),P&&($(B,(b)=>{P=!1,b&&V(B,b),j(b)}),B.on("readable",function(){if(S){let b=S;S=null,b()}}),B.on("end",function(){W.push(null)}),W._read=function(){for(;;){let b=B.read();if(b===null){S=W._read;return}if(!W.push(b))return}}),W._destroy=function(b,p){!b&&_!==null&&(b=new I),S=null,w=null,k=null,_===null?p(b):(_=p,V(q,b),V(B,b))},W}}),M3=Y2((A,Q)=>{var{ObjectDefineProperties:J,ObjectGetOwnPropertyDescriptor:K,ObjectKeys:C,ObjectSetPrototypeOf:U}=q8();Q.exports=X;var Y=XX(),Z=_w();U(X.prototype,Y.prototype),U(X,Y);{let I=C(Z.prototype);for(let N=0;N{var{ObjectSetPrototypeOf:J,Symbol:K}=q8();Q.exports=X;var{ERR_METHOD_NOT_IMPLEMENTED:C}=k6().codes,U=M3(),{getHighWaterMark:Y}=tI();J(X.prototype,U.prototype),J(X,U);var Z=K("kCallback");function X($){if(!(this instanceof X))return new X($);let I=$?Y(this,$,"readableHighWaterMark",!0):null;I===0&&($={...$,highWaterMark:null,readableHighWaterMark:I,writableHighWaterMark:$.writableHighWaterMark||0}),U.call(this,$),this._readableState.sync=!1,this[Z]=null,$&&(typeof $.transform=="function"&&(this._transform=$.transform),typeof $.flush=="function"&&(this._flush=$.flush)),this.on("prefinish",H)}function E($){typeof this._flush=="function"&&!this.destroyed?this._flush((I,N)=>{if(I){$?$(I):this.destroy(I);return}N!=null&&this.push(N),this.push(null),$&&$()}):(this.push(null),$&&$())}function H(){this._final!==E&&E.call(this)}X.prototype._final=E,X.prototype._transform=function($,I,N){throw new C("_transform()")},X.prototype._write=function($,I,N){let F=this._readableState,V=this._writableState,D=F.length;this._transform($,I,(L,R)=>{if(L){N(L);return}R!=null&&this.push(R),V.ended||D===F.length||F.length{var{ObjectSetPrototypeOf:J}=q8();Q.exports=C;var K=Tw();J(C.prototype,K.prototype),J(C,K);function C(U){if(!(this instanceof C))return new C(U);K.call(this,U)}C.prototype._transform=function(U,Y,Z){Z(null,U)}}),eI=Y2((A,Q)=>{var J=(f4(),b4(w3)),{ArrayIsArray:K,Promise:C,SymbolAsyncIterator:U}=q8(),Y=u4(),{once:Z}=V3(),X=pJ(),E=M3(),{aggregateTwoErrors:H,codes:{ERR_INVALID_ARG_TYPE:$,ERR_INVALID_RETURN_VALUE:I,ERR_MISSING_ARGS:N,ERR_STREAM_DESTROYED:F,ERR_STREAM_PREMATURE_CLOSE:V},AbortError:D}=k6(),{validateFunction:L,validateAbortSignal:R}=BX(),{isIterable:M,isReadable:T,isReadableNodeStream:h,isNodeStream:y}=p4(),g=globalThis.AbortController||oI().AbortController,f,u;function d(S,_,W){let j=!1;S.on("close",()=>{j=!0});let b=Y(S,{readable:_,writable:W},(p)=>{j=!p});return{destroy:(p)=>{j||(j=!0,X.destroyer(S,p||new F("pipe")))},cleanup:b}}function n(S){return L(S[S.length-1],"streams[stream.length - 1]"),S.pop()}function B(S){if(M(S))return S;if(h(S))return q(S);throw new $("val",["Readable","Iterable","AsyncIterable"],S)}async function*q(S){u||(u=XX()),yield*u.prototype[U].call(S)}async function P(S,_,W,{end:j}){let b,p=null,s=(Q1)=>{if(Q1&&(b=Q1),p){let e=p;p=null,e()}},r=()=>new C((Q1,e)=>{b?e(b):p=()=>{b?e(b):Q1()}});_.on("drain",s);let A1=Y(_,{readable:!1},s);try{_.writableNeedDrain&&await r();for await(let Q1 of S)_.write(Q1)||await r();j&&_.end(),await r(),W()}catch(Q1){W(b!==Q1?H(b,Q1):Q1)}finally{A1(),_.off("drain",s)}}function O(...S){return w(S,Z(n(S)))}function w(S,_,W){if(S.length===1&&K(S[0])&&(S=S[0]),S.length<2)throw new N("streams");let j=new g,b=j.signal,p=W?.signal,s=[];R(p,"options.signal");function r(){O1(new D)}p?.addEventListener("abort",r);let A1,Q1,e=[],t=0;function U1(c){O1(c,--t===0)}function O1(c,o){if(c&&(!A1||A1.code==="ERR_STREAM_PREMATURE_CLOSE")&&(A1=c),!(!A1&&!o)){for(;e.length;)e.shift()(A1);p?.removeEventListener("abort",r),j.abort(),o&&(A1||s.forEach((C1)=>C1()),J.nextTick(_,A1,Q1))}}let E1;for(let c=0;c0,Z1=C1||W?.end!==!1,j1=c===S.length-1;if(y(o)){let H1=function(B1){B1&&B1.name!=="AbortError"&&B1.code!=="ERR_STREAM_PREMATURE_CLOSE"&&U1(B1)};var Y1=H1;if(Z1){let{destroy:B1,cleanup:k1}=d(o,C1,q1);e.push(B1),T(o)&&j1&&s.push(k1)}o.on("error",H1),T(o)&&j1&&s.push(()=>{o.removeListener("error",H1)})}if(c===0)if(typeof o=="function"){if(E1=o({signal:b}),!M(E1))throw new I("Iterable, AsyncIterable or Stream","source",E1)}else M(o)||h(o)?E1=o:E1=E.from(o);else if(typeof o=="function")if(E1=B(E1),E1=o(E1,{signal:b}),C1){if(!M(E1,!0))throw new I("AsyncIterable",`transform[${c-1}]`,E1)}else{var i;f||(f=kw());let H1=new f({objectMode:!0}),B1=(i=E1)===null||i===void 0?void 0:i.then;if(typeof B1=="function")t++,B1.call(E1,(G1)=>{Q1=G1,G1!=null&&H1.write(G1),Z1&&H1.end(),J.nextTick(U1)},(G1)=>{H1.destroy(G1),J.nextTick(U1,G1)});else if(M(E1,!0))t++,P(E1,H1,U1,{end:Z1});else throw new I("AsyncIterable or Promise","destination",E1);E1=H1;let{destroy:k1,cleanup:D1}=d(E1,!1,!0);e.push(k1),j1&&s.push(D1)}else if(y(o)){if(h(E1)){t+=2;let H1=k(E1,o,U1,{end:Z1});T(o)&&j1&&s.push(H1)}else if(M(E1))t++,P(E1,o,U1,{end:Z1});else throw new $("val",["Readable","Iterable","AsyncIterable"],E1);E1=o}else E1=E.from(o)}return(b!=null&&b.aborted||p!=null&&p.aborted)&&J.nextTick(r),E1}function k(S,_,W,{end:j}){let b=!1;return _.on("close",()=>{b||W(new V)}),S.pipe(_,{end:j}),j?S.once("end",()=>{b=!0,_.end()}):W(),Y(S,{readable:!0,writable:!1},(p)=>{let s=S._readableState;p&&p.code==="ERR_STREAM_PREMATURE_CLOSE"&&s&&s.ended&&!s.errored&&!s.errorEmitted?S.once("end",W).once("error",W):W(p)}),Y(_,{readable:!1,writable:!0},W)}Q.exports={pipelineImpl:w,pipeline:O}}),Ei=Y2((A,Q)=>{var{pipeline:J}=eI(),K=M3(),{destroyer:C}=pJ(),{isNodeStream:U,isReadable:Y,isWritable:Z}=p4(),{AbortError:X,codes:{ERR_INVALID_ARG_VALUE:E,ERR_MISSING_ARGS:H}}=k6();Q.exports=function(...$){if($.length===0)throw new H("streams");if($.length===1)return K.from($[0]);let I=[...$];if(typeof $[0]=="function"&&($[0]=K.from($[0])),typeof $[$.length-1]=="function"){let g=$.length-1;$[g]=K.from($[g])}for(let g=0;g<$.length;++g)if(U($[g])){if(g<$.length-1&&!Y($[g]))throw new E(`streams[${g}]`,I[g],"must be readable");if(g>0&&!Z($[g]))throw new E(`streams[${g}]`,I[g],"must be writable")}let N,F,V,D,L;function R(g){let f=D;D=null,f?f(g):g?L.destroy(g):!y&&!h&&L.destroy()}let M=$[0],T=J($,R),h=!!Z(M),y=!!Y(T);return L=new K({writableObjectMode:!!(M!=null&&M.writableObjectMode),readableObjectMode:!!(T!=null&&T.writableObjectMode),writable:h,readable:y}),h&&(L._write=function(g,f,u){M.write(g,f)?u():N=u},L._final=function(g){M.end(),F=g},M.on("drain",function(){if(N){let g=N;N=null,g()}}),T.on("finish",function(){if(F){let g=F;F=null,g()}})),y&&(T.on("readable",function(){if(V){let g=V;V=null,g()}}),T.on("end",function(){L.push(null)}),L._read=function(){for(;;){let g=T.read();if(g===null){V=L._read;return}if(!L.push(g))return}}),L._destroy=function(g,f){!g&&D!==null&&(g=new X),V=null,N=null,F=null,D===null?f(g):(D=f,C(T,g))},L}}),Sw=Y2((A,Q)=>{var{ArrayPrototypePop:J,Promise:K}=q8(),{isIterable:C,isNodeStream:U}=p4(),{pipelineImpl:Y}=eI(),{finished:Z}=u4();function X(...E){return new K((H,$)=>{let I,N,F=E[E.length-1];if(F&&typeof F=="object"&&!U(F)&&!C(F)){let V=J(E);I=V.signal,N=V.end}Y(E,(V,D)=>{V?$(V):H(D)},{signal:I,end:N})})}Q.exports={finished:Z,pipeline:X}}),$i=Y2((A,Q)=>{var{Buffer:J}=y7(),{ObjectDefineProperty:K,ObjectKeys:C,ReflectApply:U}=q8(),{promisify:{custom:Y}}=V3(),{streamReturningOperators:Z,promiseReturningOperators:X}=Yi(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:E}}=k6(),H=Ei(),{pipeline:$}=eI(),{destroyer:I}=pJ(),N=u4(),F=Sw(),V=p4(),D=Q.exports=aI().Stream;D.isDisturbed=V.isDisturbed,D.isErrored=V.isErrored,D.isReadable=V.isReadable,D.Readable=XX();for(let M of C(Z)){let T=function(...y){if(new.target)throw E();return D.Readable.from(U(h,this,y))};L=T;let h=Z[M];K(T,"name",{__proto__:null,value:h.name}),K(T,"length",{__proto__:null,value:h.length}),K(D.Readable.prototype,M,{__proto__:null,value:T,enumerable:!1,configurable:!0,writable:!0})}var L;for(let M of C(X)){let T=function(...y){if(new.target)throw E();return U(h,this,y)};L=T;let h=X[M];K(T,"name",{__proto__:null,value:h.name}),K(T,"length",{__proto__:null,value:h.length}),K(D.Readable.prototype,M,{__proto__:null,value:T,enumerable:!1,configurable:!0,writable:!0})}var L;D.Writable=_w(),D.Duplex=M3(),D.Transform=Tw(),D.PassThrough=kw(),D.pipeline=$;var{addAbortSignal:R}=rI();D.addAbortSignal=R,D.finished=N,D.destroy=I,D.compose=H,K(D,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return F}}),K($,Y,{__proto__:null,enumerable:!0,get(){return F.pipeline}}),K(N,Y,{__proto__:null,enumerable:!0,get(){return F.finished}}),D.Stream=D,D._isUint8Array=function(M){return M instanceof Uint8Array},D._uint8ArrayToBuffer=function(M){return J.from(M.buffer,M.byteOffset,M.byteLength)}}),jw=Y2((A,Q)=>{var J=$i(),K=Sw(),C=J.Readable.destroy;Q.exports=J.Readable,Q.exports._uint8ArrayToBuffer=J._uint8ArrayToBuffer,Q.exports._isUint8Array=J._isUint8Array,Q.exports.isDisturbed=J.isDisturbed,Q.exports.isErrored=J.isErrored,Q.exports.isReadable=J.isReadable,Q.exports.Readable=J.Readable,Q.exports.Writable=J.Writable,Q.exports.Duplex=J.Duplex,Q.exports.Transform=J.Transform,Q.exports.PassThrough=J.PassThrough,Q.exports.addAbortSignal=J.addAbortSignal,Q.exports.finished=J.finished,Q.exports.destroy=J.destroy,Q.exports.destroy=C,Q.exports.pipeline=J.pipeline,Q.exports.compose=J.compose,Object.defineProperty(J,"promises",{configurable:!0,enumerable:!0,get(){return K}}),Q.exports.Stream=J.Stream,Q.exports.default=Q.exports}),vw={};Vw(vw,{default:()=>xw});Mw(vw,UX(jw()));xw=UX(jw());/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *//*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *//*! safe-buffer. MIT License. Feross Aboukhadijeh */});var P3=B0((Gi)=>{Gi.base64=!0;Gi.array=!0;Gi.string=!0;Gi.arraybuffer=typeof ArrayBuffer!=="undefined"&&typeof Uint8Array!=="undefined";Gi.nodebuffer=typeof Buffer!=="undefined";Gi.uint8array=typeof Uint8Array!=="undefined";if(typeof ArrayBuffer==="undefined")Gi.blob=!1;else{Qq=new ArrayBuffer(0);try{Gi.blob=new Blob([Qq],{type:"application/zip"}).size===0}catch(A){try{yw=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,Jq=new yw,Jq.append(Qq),Gi.blob=Jq.getBlob("application/zip").size===0}catch(Q){Gi.blob=!1}}}var Qq,yw,Jq;try{Gi.nodestream=!!($X(),y4(EX)).Readable}catch(A){Gi.nodestream=!1}});var Kq=B0((zi)=>{var Fi=l2(),Ri=P3(),b5="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";zi.encode=function(A){var Q=[],J,K,C,U,Y,Z,X,E=0,H=A.length,$=H,I=Fi.getTypeOf(A)!=="string";while(E>2,Y=(J&3)<<4|K>>4,Z=$>1?(K&15)<<2|C>>6:64,X=$>2?C&63:64,Q.push(b5.charAt(U)+b5.charAt(Y)+b5.charAt(Z)+b5.charAt(X))}return Q.join("")};zi.decode=function(A){var Q,J,K,C,U,Y,Z,X=0,E=0,H="data:";if(A.substr(0,H.length)===H)throw new Error("Invalid base64 input, it looks like a data url.");A=A.replace(/[^A-Za-z0-9+/=]/g,"");var $=A.length*3/4;if(A.charAt(A.length-1)===b5.charAt(64))$--;if(A.charAt(A.length-2)===b5.charAt(64))$--;if($%1!==0)throw new Error("Invalid base64 input, bad content length.");var I;if(Ri.uint8array)I=new Uint8Array($|0);else I=new Array($|0);while(X>4,J=(U&15)<<4|Y>>2,K=(Y&3)<<6|Z,I[E++]=Q,Y!==64)I[E++]=J;if(Z!==64)I[E++]=K}return I}});var VY=B0((aq1,hw)=>{hw.exports={isNode:typeof Buffer!=="undefined",newBufferFrom:function(A,Q){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(A,Q);else{if(typeof A==="number")throw new Error('The "data" argument must not be a number');return new Buffer(A,Q)}},allocBuffer:function(A){if(Buffer.alloc)return Buffer.alloc(A);else{var Q=new Buffer(A);return Q.fill(0),Q}},isBuffer:function(A){return Buffer.isBuffer(A)},isStream:function(A){return A&&typeof A.on==="function"&&typeof A.pause==="function"&&typeof A.resume==="function"}}});var pw=B0((rq1,fw)=>{var gw=global.MutationObserver||global.WebKitMutationObserver,MY;if(gw)Cq=0,bw=new gw(HX),Yq=global.document.createTextNode(""),bw.observe(Yq,{characterData:!0}),MY=function(){Yq.data=Cq=++Cq%2};else if(!global.setImmediate&&typeof global.MessageChannel!=="undefined")Uq=new global.MessageChannel,Uq.port1.onmessage=HX,MY=function(){Uq.port2.postMessage(0)};else if("document"in global&&"onreadystatechange"in global.document.createElement("script"))MY=function(){var A=global.document.createElement("script");A.onreadystatechange=function(){HX(),A.onreadystatechange=null,A.parentNode.removeChild(A),A=null},global.document.documentElement.appendChild(A)};else MY=function(){setTimeout(HX,0)};var Cq,bw,Yq,Uq,Zq,wY=[];function HX(){Zq=!0;var A,Q,J=wY.length;while(J){Q=wY,wY=[],A=-1;while(++A{var wi=pw();function uJ(){}var r8={},uw=["REJECTED"],Bq=["FULFILLED"],mw=["PENDING"];lw.exports=h7;function h7(A){if(typeof A!=="function")throw new TypeError("resolver must be a function");if(this.state=mw,this.queue=[],this.outcome=void 0,A!==uJ)cw(this,A)}h7.prototype.finally=function(A){if(typeof A!=="function")return this;var Q=this.constructor;return this.then(J,K);function J(C){function U(){return C}return Q.resolve(A()).then(U)}function K(C){function U(){throw C}return Q.resolve(A()).then(U)}};h7.prototype.catch=function(A){return this.then(null,A)};h7.prototype.then=function(A,Q){if(typeof A!=="function"&&this.state===Bq||typeof Q!=="function"&&this.state===uw)return this;var J=new this.constructor(uJ);if(this.state!==mw){var K=this.state===Bq?A:Q;Xq(J,K,this.outcome)}else this.queue.push(new PY(J,A,Q));return J};function PY(A,Q,J){if(this.promise=A,typeof Q==="function")this.onFulfilled=Q,this.callFulfilled=this.otherCallFulfilled;if(typeof J==="function")this.onRejected=J,this.callRejected=this.otherCallRejected}PY.prototype.callFulfilled=function(A){r8.resolve(this.promise,A)};PY.prototype.otherCallFulfilled=function(A){Xq(this.promise,this.onFulfilled,A)};PY.prototype.callRejected=function(A){r8.reject(this.promise,A)};PY.prototype.otherCallRejected=function(A){Xq(this.promise,this.onRejected,A)};function Xq(A,Q,J){wi(function(){var K;try{K=Q(J)}catch(C){return r8.reject(A,C)}if(K===A)r8.reject(A,new TypeError("Cannot resolve promise with itself"));else r8.resolve(A,K)})}r8.resolve=function(A,Q){var J=dw(Pi,Q);if(J.status==="error")return r8.reject(A,J.value);var K=J.value;if(K)cw(A,K);else{A.state=Bq,A.outcome=Q;var C=-1,U=A.queue.length;while(++C{var Eq=null;if(typeof Promise!=="undefined")Eq=Promise;else Eq=nw();sw.exports={Promise:Eq}});var iw=B0((ow)=>{(function(A,Q){if(A.setImmediate)return;var J=1,K={},C=!1,U=A.document,Y;function Z(R){if(typeof R!=="function")R=new Function(""+R);var M=new Array(arguments.length-1);for(var T=0;T{var g7=P3(),ji=Kq(),cJ=VY(),$q=mJ();iw();function vi(A){var Q=null;if(g7.uint8array)Q=new Uint8Array(A.length);else Q=new Array(A.length);return WX(A,Q)}xi.newBlob=function(A,Q){xi.checkSupport("blob");try{return new Blob([A],{type:Q})}catch(C){try{var J=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,K=new J;return K.append(A),K.getBlob(Q)}catch(U){throw new Error("Bug : can't construct the Blob.")}}};function _Y(A){return A}function WX(A,Q){for(var J=0;J1)try{return GX.stringifyByChunk(A,J,Q)}catch(C){Q=Math.floor(Q/2)}return GX.stringifyByChar(A)}xi.applyFromCharCode=TY;function IX(A,Q){for(var J=0;J{function tw(A){this.name=A||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}tw.prototype={push:function(A){this.emit("data",A)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(A){this.emit("error",A)}return!0},error:function(A){if(this.isFinished)return!1;if(this.isPaused)this.generatedError=A;else{if(this.isFinished=!0,this.emit("error",A),this.previous)this.previous.error(A);this.cleanUp()}return!0},on:function(A,Q){return this._listeners[A].push(Q),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(A,Q){if(this._listeners[A])for(var J=0;J "+A;else return A}};ew.exports=tw});var lJ=B0((ii)=>{var dJ=l2(),m4=P3(),li=VY(),qX=t6(),kY=new Array(256);for(_3=0;_3<256;_3++)kY[_3]=_3>=252?6:_3>=248?5:_3>=240?4:_3>=224?3:_3>=192?2:1;var _3;kY[254]=kY[254]=1;var ni=function(A){var Q,J,K,C,U,Y=A.length,Z=0;for(C=0;C>>6,Q[U++]=128|J&63;else if(J<65536)Q[U++]=224|J>>>12,Q[U++]=128|J>>>6&63,Q[U++]=128|J&63;else Q[U++]=240|J>>>18,Q[U++]=128|J>>>12&63,Q[U++]=128|J>>>6&63,Q[U++]=128|J&63}return Q},si=function(A,Q){var J;if(Q=Q||A.length,Q>A.length)Q=A.length;J=Q-1;while(J>=0&&(A[J]&192)===128)J--;if(J<0)return Q;if(J===0)return Q;return J+kY[A[J]]>Q?J:Q},oi=function(A){var Q,J,K,C,U=A.length,Y=new Array(U*2);for(J=0,Q=0;Q4){Y[J++]=65533,Q+=C-1;continue}K&=C===2?31:C===3?15:7;while(C>1&&Q1){Y[J++]=65533;continue}if(K<65536)Y[J++]=K;else K-=65536,Y[J++]=55296|K>>10&1023,Y[J++]=56320|K&1023}if(Y.length!==J)if(Y.subarray)Y=Y.subarray(0,J);else Y.length=J;return dJ.applyFromCharCode(Y)};ii.utf8encode=function A(Q){if(m4.nodebuffer)return li.newBufferFrom(Q,"utf-8");return ni(Q)};ii.utf8decode=function A(Q){if(m4.nodebuffer)return dJ.transformTo("nodebuffer",Q).toString("utf-8");return Q=dJ.transformTo(m4.uint8array?"uint8array":"array",Q),oi(Q)};function OX(){qX.call(this,"utf-8 decode"),this.leftOver=null}dJ.inherits(OX,qX);OX.prototype.processChunk=function(A){var Q=dJ.transformTo(m4.uint8array?"uint8array":"array",A.data);if(this.leftOver&&this.leftOver.length){if(m4.uint8array){var J=Q;Q=new Uint8Array(J.length+this.leftOver.length),Q.set(this.leftOver,0),Q.set(J,this.leftOver.length)}else Q=this.leftOver.concat(Q);this.leftOver=null}var K=si(Q),C=Q;if(K!==Q.length)if(m4.uint8array)C=Q.subarray(0,K),this.leftOver=Q.subarray(K,Q.length);else C=Q.slice(0,K),this.leftOver=Q.slice(K,Q.length);this.push({data:ii.utf8decode(C),meta:A.meta})};OX.prototype.flush=function(){if(this.leftOver&&this.leftOver.length)this.push({data:ii.utf8decode(this.leftOver),meta:{}}),this.leftOver=null};ii.Utf8DecodeWorker=OX;function Gq(){qX.call(this,"utf-8 encode")}dJ.inherits(Gq,qX);Gq.prototype.processChunk=function(A){this.push({data:ii.utf8encode(A.data),meta:A.meta})};ii.Utf8EncodeWorker=Gq});var CP=B0((CO1,KP)=>{var QP=t6(),JP=l2();function Iq(A){QP.call(this,"ConvertWorker to "+A),this.destType=A}JP.inherits(Iq,QP);Iq.prototype.processChunk=function(A){this.push({data:JP.transformTo(this.destType,A.data),meta:A.meta})};KP.exports=Iq});var ZP=B0((YO1,UP)=>{var YP=($X(),y4(EX)).Readable,ti=l2();ti.inherits(qq,YP);function qq(A,Q,J){YP.call(this,Q),this._helper=A;var K=this;A.on("data",function(C,U){if(!K.push(C))K._helper.pause();if(J)J(U)}).on("error",function(C){K.emit("error",C)}).on("end",function(){K.push(null)})}qq.prototype._read=function(){this._helper.resume()};UP.exports=qq});var Oq=B0((UO1,EP)=>{var c4=l2(),ei=CP(),Aa=t6(),Qa=Kq(),Ja=P3(),Ka=mJ(),BP=null;if(Ja.nodestream)try{BP=ZP()}catch(A){}function Ca(A,Q,J){switch(A){case"blob":return c4.newBlob(c4.transformTo("arraybuffer",Q),J);case"base64":return Qa.encode(Q);default:return c4.transformTo(A,Q)}}function Ya(A,Q){var J,K=0,C=null,U=0;for(J=0;J{Za.base64=!1;Za.binary=!1;Za.dir=!1;Za.createFolders=!0;Za.date=null;Za.compression=null;Za.compressionOptions=null;Za.comment=null;Za.unixPermissions=null;Za.dosPermissions=null});var Lq=B0((BO1,$P)=>{var NX=l2(),LX=t6(),Na=16384;function nJ(A){LX.call(this,"DataWorker");var Q=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,A.then(function(J){if(Q.dataIsReady=!0,Q.data=J,Q.max=J&&J.length||0,Q.type=NX.getTypeOf(J),!Q.isPaused)Q._tickAndRepeat()},function(J){Q.error(J)})}NX.inherits(nJ,LX);nJ.prototype.cleanUp=function(){LX.prototype.cleanUp.call(this),this.data=null};nJ.prototype.resume=function(){if(!LX.prototype.resume.call(this))return!1;if(!this._tickScheduled&&this.dataIsReady)this._tickScheduled=!0,NX.delay(this._tickAndRepeat,[],this);return!0};nJ.prototype._tickAndRepeat=function(){if(this._tickScheduled=!1,this.isPaused||this.isFinished)return;if(this._tick(),!this.isFinished)NX.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0};nJ.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var A=Na,Q=null,J=Math.min(this.max,this.index+A);if(this.index>=this.max)return this.end();else{switch(this.type){case"string":Q=this.data.substring(this.index,J);break;case"uint8array":Q=this.data.subarray(this.index,J);break;case"array":case"nodebuffer":Q=this.data.slice(this.index,J);break}return this.index=J,this.push({data:Q,meta:{percent:this.max?this.index/this.max*100:0}})}};$P.exports=nJ});var FX=B0((XO1,GP)=>{var La=l2();function Fa(){var A,Q=[];for(var J=0;J<256;J++){A=J;for(var K=0;K<8;K++)A=A&1?3988292384^A>>>1:A>>>1;Q[J]=A}return Q}var HP=Fa();function Ra(A,Q,J,K){var C=HP,U=K+J;A=A^-1;for(var Y=K;Y>>8^C[(A^Q[Y])&255];return A^-1}function za(A,Q,J,K){var C=HP,U=K+J;A=A^-1;for(var Y=K;Y>>8^C[(A^Q.charCodeAt(Y))&255];return A^-1}GP.exports=function A(Q,J){if(typeof Q==="undefined"||!Q.length)return 0;var K=La.getTypeOf(Q)!=="string";if(K)return Ra(J|0,Q,Q.length,0);else return za(J|0,Q,Q.length,0)}});var Rq=B0((EO1,IP)=>{var WP=t6(),Da=FX(),Va=l2();function Fq(){WP.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}Va.inherits(Fq,WP);Fq.prototype.processChunk=function(A){this.streamInfo.crc32=Da(A.data,this.streamInfo.crc32||0),this.push(A)};IP.exports=Fq});var OP=B0(($O1,qP)=>{var Ma=l2(),zq=t6();function Dq(A){zq.call(this,"DataLengthProbe for "+A),this.propName=A,this.withStreamInfo(A,0)}Ma.inherits(Dq,zq);Dq.prototype.processChunk=function(A){if(A){var Q=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=Q+A.data.length}zq.prototype.processChunk.call(this,A)};qP.exports=Dq});var RX=B0((HO1,FP)=>{var NP=mJ(),LP=Lq(),wa=Rq(),Vq=OP();function Mq(A,Q,J,K,C){this.compressedSize=A,this.uncompressedSize=Q,this.crc32=J,this.compression=K,this.compressedContent=C}Mq.prototype={getContentWorker:function(){var A=new LP(NP.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new Vq("data_length")),Q=this;return A.on("end",function(){if(this.streamInfo.data_length!==Q.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),A},getCompressedWorker:function(){return new LP(NP.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}};Mq.createWorkerFrom=function(A,Q,J){return A.pipe(new wa).pipe(new Vq("uncompressedSize")).pipe(Q.compressWorker(J)).pipe(new Vq("compressedSize")).withStreamInfo("compression",Q)};FP.exports=Mq});var VP=B0((GO1,DP)=>{var Pa=Oq(),_a=Lq(),wq=lJ(),Pq=RX(),RP=t6(),_q=function(A,Q,J){this.name=A,this.dir=J.dir,this.date=J.date,this.comment=J.comment,this.unixPermissions=J.unixPermissions,this.dosPermissions=J.dosPermissions,this._data=Q,this._dataBinary=J.binary,this.options={compression:J.compression,compressionOptions:J.compressionOptions}};_q.prototype={internalStream:function(A){var Q=null,J="string";try{if(!A)throw new Error("No output type specified.");J=A.toLowerCase();var K=J==="string"||J==="text";if(J==="binarystring"||J==="text")J="string";Q=this._decompressWorker();var C=!this._dataBinary;if(C&&!K)Q=Q.pipe(new wq.Utf8EncodeWorker);if(!C&&K)Q=Q.pipe(new wq.Utf8DecodeWorker)}catch(U){Q=new RP("error"),Q.error(U)}return new Pa(Q,J,"")},async:function(A,Q){return this.internalStream(A).accumulate(Q)},nodeStream:function(A,Q){return this.internalStream(A||"nodebuffer").toNodejsStream(Q)},_compressWorker:function(A,Q){if(this._data instanceof Pq&&this._data.compression.magic===A.magic)return this._data.getCompressedWorker();else{var J=this._decompressWorker();if(!this._dataBinary)J=J.pipe(new wq.Utf8EncodeWorker);return Pq.createWorkerFrom(J,A,Q)}},_decompressWorker:function(){if(this._data instanceof Pq)return this._data.getContentWorker();else if(this._data instanceof RP)return this._data;else return new _a(this._data)}};var zP=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],Ta=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")};for(zX=0;zX{var va=typeof Uint8Array!=="undefined"&&typeof Uint16Array!=="undefined"&&typeof Int32Array!=="undefined";function xa(A,Q){return Object.prototype.hasOwnProperty.call(A,Q)}Tq.assign=function(A){var Q=Array.prototype.slice.call(arguments,1);while(Q.length){var J=Q.shift();if(!J)continue;if(typeof J!=="object")throw new TypeError(J+"must be non-object");for(var K in J)if(xa(J,K))A[K]=J[K]}return A};Tq.shrinkBuf=function(A,Q){if(A.length===Q)return A;if(A.subarray)return A.subarray(0,Q);return A.length=Q,A};var ya={arraySet:function(A,Q,J,K,C){if(Q.subarray&&A.subarray){A.set(Q.subarray(J,J+K),C);return}for(var U=0;U{var ba=T3(),fa=4,wP=0,PP=1,pa=2;function oJ(A){var Q=A.length;while(--Q>=0)A[Q]=0}var ua=0,vP=1,ma=2,ca=3,da=258,gq=29,hY=256,jY=hY+1+gq,sJ=30,bq=19,xP=2*jY+1,d4=15,Sq=16,la=7,fq=256,yP=16,hP=17,gP=18,yq=[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],DX=[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],na=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],bP=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],sa=512,k3=new Array((jY+2)*2);oJ(k3);var SY=new Array(sJ*2);oJ(SY);var vY=new Array(sa);oJ(vY);var xY=new Array(da-ca+1);oJ(xY);var pq=new Array(gq);oJ(pq);var VX=new Array(sJ);oJ(VX);function jq(A,Q,J,K,C){this.static_tree=A,this.extra_bits=Q,this.extra_base=J,this.elems=K,this.max_length=C,this.has_stree=A&&A.length}var fP,pP,uP;function vq(A,Q){this.dyn_tree=A,this.max_code=0,this.stat_desc=Q}function mP(A){return A<256?vY[A]:vY[256+(A>>>7)]}function yY(A,Q){A.pending_buf[A.pending++]=Q&255,A.pending_buf[A.pending++]=Q>>>8&255}function S6(A,Q,J){if(A.bi_valid>Sq-J)A.bi_buf|=Q<>Sq-A.bi_valid,A.bi_valid+=J-Sq;else A.bi_buf|=Q<>>=1,J<<=1;while(--Q>0);return J>>>1}function oa(A){if(A.bi_valid===16)yY(A,A.bi_buf),A.bi_buf=0,A.bi_valid=0;else if(A.bi_valid>=8)A.pending_buf[A.pending++]=A.bi_buf&255,A.bi_buf>>=8,A.bi_valid-=8}function ia(A,Q){var{dyn_tree:J,max_code:K}=Q,C=Q.stat_desc.static_tree,U=Q.stat_desc.has_stree,Y=Q.stat_desc.extra_bits,Z=Q.stat_desc.extra_base,X=Q.stat_desc.max_length,E,H,$,I,N,F,V=0;for(I=0;I<=d4;I++)A.bl_count[I]=0;J[A.heap[A.heap_max]*2+1]=0;for(E=A.heap_max+1;EX)I=X,V++;if(J[H*2+1]=I,H>K)continue;if(A.bl_count[I]++,N=0,H>=Z)N=Y[H-Z];if(F=J[H*2],A.opt_len+=F*(I+N),U)A.static_len+=F*(C[H*2+1]+N)}if(V===0)return;do{I=X-1;while(A.bl_count[I]===0)I--;A.bl_count[I]--,A.bl_count[I+1]+=2,A.bl_count[X]--,V-=2}while(V>0);for(I=X;I!==0;I--){H=A.bl_count[I];while(H!==0){if($=A.heap[--E],$>K)continue;if(J[$*2+1]!==I)A.opt_len+=(I-J[$*2+1])*J[$*2],J[$*2+1]=I;H--}}}function dP(A,Q,J){var K=new Array(d4+1),C=0,U,Y;for(U=1;U<=d4;U++)K[U]=C=C+J[U-1]<<1;for(Y=0;Y<=Q;Y++){var Z=A[Y*2+1];if(Z===0)continue;A[Y*2]=cP(K[Z]++,Z)}}function aa(){var A,Q,J,K,C,U=new Array(d4+1);J=0;for(K=0;K>=7;for(;K8)yY(A,A.bi_buf);else if(A.bi_valid>0)A.pending_buf[A.pending++]=A.bi_buf;A.bi_buf=0,A.bi_valid=0}function ra(A,Q,J,K){if(nP(A),K)yY(A,J),yY(A,~J);ba.arraySet(A.pending_buf,A.window,Q,J,A.pending),A.pending+=J}function _P(A,Q,J,K){var C=Q*2,U=J*2;return A[C]>1;Y>=1;Y--)xq(A,J,Y);E=U;do Y=A.heap[1],A.heap[1]=A.heap[A.heap_len--],xq(A,J,1),Z=A.heap[1],A.heap[--A.heap_max]=Y,A.heap[--A.heap_max]=Z,J[E*2]=J[Y*2]+J[Z*2],A.depth[E]=(A.depth[Y]>=A.depth[Z]?A.depth[Y]:A.depth[Z])+1,J[Y*2+1]=J[Z*2+1]=E,A.heap[1]=E++,xq(A,J,1);while(A.heap_len>=2);A.heap[--A.heap_max]=A.heap[1],ia(A,Q),dP(J,X,A.bl_count)}function kP(A,Q,J){var K,C=-1,U,Y=Q[1],Z=0,X=7,E=4;if(Y===0)X=138,E=3;Q[(J+1)*2+1]=65535;for(K=0;K<=J;K++){if(U=Y,Y=Q[(K+1)*2+1],++Z=3;Q--)if(A.bl_tree[bP[Q]*2+1]!==0)break;return A.opt_len+=3*(Q+1)+5+5+4,Q}function ea(A,Q,J,K){var C;S6(A,Q-257,5),S6(A,J-1,5),S6(A,K-4,4);for(C=0;C>>=1)if(Q&1&&A.dyn_ltree[J*2]!==0)return wP;if(A.dyn_ltree[18]!==0||A.dyn_ltree[20]!==0||A.dyn_ltree[26]!==0)return PP;for(J=32;J0){if(A.strm.data_type===pa)A.strm.data_type=Ar(A);if(hq(A,A.l_desc),hq(A,A.d_desc),Y=ta(A),C=A.opt_len+3+7>>>3,U=A.static_len+3+7>>>3,U<=C)C=U}else C=U=J+5;if(J+4<=C&&Q!==-1)sP(A,Q,J,K);else if(A.strategy===fa||U===C)S6(A,(vP<<1)+(K?1:0),3),TP(A,k3,SY);else S6(A,(ma<<1)+(K?1:0),3),ea(A,A.l_desc.max_code+1,A.d_desc.max_code+1,Y+1),TP(A,A.dyn_ltree,A.dyn_dtree);if(lP(A),K)nP(A)}function Cr(A,Q,J){if(A.pending_buf[A.d_buf+A.last_lit*2]=Q>>>8&255,A.pending_buf[A.d_buf+A.last_lit*2+1]=Q&255,A.pending_buf[A.l_buf+A.last_lit]=J&255,A.last_lit++,Q===0)A.dyn_ltree[J*2]++;else A.matches++,Q--,A.dyn_ltree[(xY[J]+hY+1)*2]++,A.dyn_dtree[mP(Q)*2]++;return A.last_lit===A.lit_bufsize-1}Yr._tr_init=Qr;Yr._tr_stored_block=sP;Yr._tr_flush_block=Kr;Yr._tr_tally=Cr;Yr._tr_align=Jr});var uq=B0((qO1,iP)=>{function $r(A,Q,J,K){var C=A&65535|0,U=A>>>16&65535|0,Y=0;while(J!==0){Y=J>2000?2000:J,J-=Y;do C=C+Q[K++]|0,U=U+C|0;while(--Y);C%=65521,U%=65521}return C|U<<16|0}iP.exports=$r});var mq=B0((OO1,aP)=>{function Hr(){var A,Q=[];for(var J=0;J<256;J++){A=J;for(var K=0;K<8;K++)A=A&1?3988292384^A>>>1:A>>>1;Q[J]=A}return Q}var Gr=Hr();function Wr(A,Q,J,K){var C=Gr,U=K+J;A^=-1;for(var Y=K;Y>>8^C[(A^Q[Y])&255];return A^-1}aP.exports=Wr});var MX=B0((NO1,rP)=>{rP.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var U_=B0((sr)=>{var I6=T3(),R9=oP(),Q_=uq(),f7=mq(),Ir=MX(),o4=0,qr=1,Or=3,d7=4,tP=5,u5=0,eP=1,z9=-2,Nr=-3,cq=-5,Lr=-1,Fr=1,wX=2,Rr=3,zr=4,Dr=0,Vr=2,kX=8,Mr=9,wr=15,Pr=8,_r=29,Tr=256,lq=Tr+1+_r,kr=30,Sr=19,jr=2*lq+1,vr=15,iA=3,m7=258,J5=m7+iA+1,xr=32,SX=42,nq=69,PX=73,_X=91,TX=103,l4=113,bY=666,O8=1,fY=2,n4=3,rJ=4,yr=3;function c7(A,Q){return A.msg=Ir[Q],Q}function A_(A){return(A<<1)-(A>4?9:0)}function u7(A){var Q=A.length;while(--Q>=0)A[Q]=0}function p7(A){var Q=A.state,J=Q.pending;if(J>A.avail_out)J=A.avail_out;if(J===0)return;if(I6.arraySet(A.output,Q.pending_buf,Q.pending_out,J,A.next_out),A.next_out+=J,Q.pending_out+=J,A.total_out+=J,A.avail_out-=J,Q.pending-=J,Q.pending===0)Q.pending_out=0}function c8(A,Q){R9._tr_flush_block(A,A.block_start>=0?A.block_start:-1,A.strstart-A.block_start,Q),A.block_start=A.strstart,p7(A.strm)}function U2(A,Q){A.pending_buf[A.pending++]=Q}function gY(A,Q){A.pending_buf[A.pending++]=Q>>>8&255,A.pending_buf[A.pending++]=Q&255}function hr(A,Q,J,K){var C=A.avail_in;if(C>K)C=K;if(C===0)return 0;if(A.avail_in-=C,I6.arraySet(Q,A.input,A.next_in,C,J),A.state.wrap===1)A.adler=Q_(A.adler,Q,C,J);else if(A.state.wrap===2)A.adler=f7(A.adler,Q,C,J);return A.next_in+=C,A.total_in+=C,C}function J_(A,Q){var{max_chain_length:J,strstart:K}=A,C,U,Y=A.prev_length,Z=A.nice_match,X=A.strstart>A.w_size-J5?A.strstart-(A.w_size-J5):0,E=A.window,H=A.w_mask,$=A.prev,I=A.strstart+m7,N=E[K+Y-1],F=E[K+Y];if(A.prev_length>=A.good_match)J>>=2;if(Z>A.lookahead)Z=A.lookahead;do{if(C=Q,E[C+Y]!==F||E[C+Y-1]!==N||E[C]!==E[K]||E[++C]!==E[K+1])continue;K+=2,C++;do;while(E[++K]===E[++C]&&E[++K]===E[++C]&&E[++K]===E[++C]&&E[++K]===E[++C]&&E[++K]===E[++C]&&E[++K]===E[++C]&&E[++K]===E[++C]&&E[++K]===E[++C]&&KY){if(A.match_start=Q,Y=U,U>=Z)break;N=E[K+Y-1],F=E[K+Y]}}while((Q=$[Q&H])>X&&--J!==0);if(Y<=A.lookahead)return Y;return A.lookahead}function s4(A){var Q=A.w_size,J,K,C,U,Y;do{if(U=A.window_size-A.lookahead-A.strstart,A.strstart>=Q+(Q-J5)){I6.arraySet(A.window,A.window,Q,Q,0),A.match_start-=Q,A.strstart-=Q,A.block_start-=Q,K=A.hash_size,J=K;do C=A.head[--J],A.head[J]=C>=Q?C-Q:0;while(--K);K=Q,J=K;do C=A.prev[--J],A.prev[J]=C>=Q?C-Q:0;while(--K);U+=Q}if(A.strm.avail_in===0)break;if(K=hr(A.strm,A.window,A.strstart+A.lookahead,U),A.lookahead+=K,A.lookahead+A.insert>=iA){Y=A.strstart-A.insert,A.ins_h=A.window[Y],A.ins_h=(A.ins_h<A.pending_buf_size-5)J=A.pending_buf_size-5;for(;;){if(A.lookahead<=1){if(s4(A),A.lookahead===0&&Q===o4)return O8;if(A.lookahead===0)break}A.strstart+=A.lookahead,A.lookahead=0;var K=A.block_start+J;if(A.strstart===0||A.strstart>=K){if(A.lookahead=A.strstart-K,A.strstart=K,c8(A,!1),A.strm.avail_out===0)return O8}if(A.strstart-A.block_start>=A.w_size-J5){if(c8(A,!1),A.strm.avail_out===0)return O8}}if(A.insert=0,Q===d7){if(c8(A,!0),A.strm.avail_out===0)return n4;return rJ}if(A.strstart>A.block_start){if(c8(A,!1),A.strm.avail_out===0)return O8}return O8}function dq(A,Q){var J,K;for(;;){if(A.lookahead=iA)A.ins_h=(A.ins_h<=iA)if(K=R9._tr_tally(A,A.strstart-A.match_start,A.match_length-iA),A.lookahead-=A.match_length,A.match_length<=A.max_lazy_match&&A.lookahead>=iA){A.match_length--;do A.strstart++,A.ins_h=(A.ins_h<=iA)A.ins_h=(A.ins_h<4096))A.match_length=iA-1}if(A.prev_length>=iA&&A.match_length<=A.prev_length){C=A.strstart+A.lookahead-iA,K=R9._tr_tally(A,A.strstart-1-A.prev_match,A.prev_length-iA),A.lookahead-=A.prev_length-1,A.prev_length-=2;do if(++A.strstart<=C)A.ins_h=(A.ins_h<=iA&&A.strstart>0){if(C=A.strstart-1,K=Y[C],K===Y[++C]&&K===Y[++C]&&K===Y[++C]){U=A.strstart+m7;do;while(K===Y[++C]&&K===Y[++C]&&K===Y[++C]&&K===Y[++C]&&K===Y[++C]&&K===Y[++C]&&K===Y[++C]&&K===Y[++C]&&CA.lookahead)A.match_length=A.lookahead}}if(A.match_length>=iA)J=R9._tr_tally(A,1,A.match_length-iA),A.lookahead-=A.match_length,A.strstart+=A.match_length,A.match_length=0;else J=R9._tr_tally(A,0,A.window[A.strstart]),A.lookahead--,A.strstart++;if(J){if(c8(A,!1),A.strm.avail_out===0)return O8}}if(A.insert=0,Q===d7){if(c8(A,!0),A.strm.avail_out===0)return n4;return rJ}if(A.last_lit){if(c8(A,!1),A.strm.avail_out===0)return O8}return fY}function fr(A,Q){var J;for(;;){if(A.lookahead===0){if(s4(A),A.lookahead===0){if(Q===o4)return O8;break}}if(A.match_length=0,J=R9._tr_tally(A,0,A.window[A.strstart]),A.lookahead--,A.strstart++,J){if(c8(A,!1),A.strm.avail_out===0)return O8}}if(A.insert=0,Q===d7){if(c8(A,!0),A.strm.avail_out===0)return n4;return rJ}if(A.last_lit){if(c8(A,!1),A.strm.avail_out===0)return O8}return fY}function p5(A,Q,J,K,C){this.good_length=A,this.max_lazy=Q,this.nice_length=J,this.max_chain=K,this.func=C}var aJ;aJ=[new p5(0,0,0,0,gr),new p5(4,4,8,4,dq),new p5(4,5,16,8,dq),new p5(4,6,32,32,dq),new p5(4,4,16,16,iJ),new p5(8,16,32,32,iJ),new p5(8,16,128,128,iJ),new p5(8,32,128,256,iJ),new p5(32,128,258,1024,iJ),new p5(32,258,258,4096,iJ)];function pr(A){A.window_size=2*A.w_size,u7(A.head),A.max_lazy_match=aJ[A.level].max_lazy,A.good_match=aJ[A.level].good_length,A.nice_match=aJ[A.level].nice_length,A.max_chain_length=aJ[A.level].max_chain,A.strstart=0,A.block_start=0,A.lookahead=0,A.insert=0,A.match_length=A.prev_length=iA-1,A.match_available=0,A.ins_h=0}function ur(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=kX,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new I6.Buf16(jr*2),this.dyn_dtree=new I6.Buf16((2*kr+1)*2),this.bl_tree=new I6.Buf16((2*Sr+1)*2),u7(this.dyn_ltree),u7(this.dyn_dtree),u7(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new I6.Buf16(vr+1),this.heap=new I6.Buf16(2*lq+1),u7(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new I6.Buf16(2*lq+1),u7(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function K_(A){var Q;if(!A||!A.state)return c7(A,z9);if(A.total_in=A.total_out=0,A.data_type=Vr,Q=A.state,Q.pending=0,Q.pending_out=0,Q.wrap<0)Q.wrap=-Q.wrap;return Q.status=Q.wrap?SX:l4,A.adler=Q.wrap===2?0:1,Q.last_flush=o4,R9._tr_init(Q),u5}function C_(A){var Q=K_(A);if(Q===u5)pr(A.state);return Q}function mr(A,Q){if(!A||!A.state)return z9;if(A.state.wrap!==2)return z9;return A.state.gzhead=Q,u5}function Y_(A,Q,J,K,C,U){if(!A)return z9;var Y=1;if(Q===Lr)Q=6;if(K<0)Y=0,K=-K;else if(K>15)Y=2,K-=16;if(C<1||C>Mr||J!==kX||K<8||K>15||Q<0||Q>9||U<0||U>zr)return c7(A,z9);if(K===8)K=9;var Z=new ur;return A.state=Z,Z.strm=A,Z.wrap=Y,Z.gzhead=null,Z.w_bits=K,Z.w_size=1<tP||Q<0)return A?c7(A,z9):z9;if(K=A.state,!A.output||!A.input&&A.avail_in!==0||K.status===bY&&Q!==d7)return c7(A,A.avail_out===0?cq:z9);if(K.strm=A,J=K.last_flush,K.last_flush=Q,K.status===SX)if(K.wrap===2)if(A.adler=0,U2(K,31),U2(K,139),U2(K,8),!K.gzhead)U2(K,0),U2(K,0),U2(K,0),U2(K,0),U2(K,0),U2(K,K.level===9?2:K.strategy>=wX||K.level<2?4:0),U2(K,yr),K.status=l4;else{if(U2(K,(K.gzhead.text?1:0)+(K.gzhead.hcrc?2:0)+(!K.gzhead.extra?0:4)+(!K.gzhead.name?0:8)+(!K.gzhead.comment?0:16)),U2(K,K.gzhead.time&255),U2(K,K.gzhead.time>>8&255),U2(K,K.gzhead.time>>16&255),U2(K,K.gzhead.time>>24&255),U2(K,K.level===9?2:K.strategy>=wX||K.level<2?4:0),U2(K,K.gzhead.os&255),K.gzhead.extra&&K.gzhead.extra.length)U2(K,K.gzhead.extra.length&255),U2(K,K.gzhead.extra.length>>8&255);if(K.gzhead.hcrc)A.adler=f7(A.adler,K.pending_buf,K.pending,0);K.gzindex=0,K.status=nq}else{var Y=kX+(K.w_bits-8<<4)<<8,Z=-1;if(K.strategy>=wX||K.level<2)Z=0;else if(K.level<6)Z=1;else if(K.level===6)Z=2;else Z=3;if(Y|=Z<<6,K.strstart!==0)Y|=xr;if(Y+=31-Y%31,K.status=l4,gY(K,Y),K.strstart!==0)gY(K,A.adler>>>16),gY(K,A.adler&65535);A.adler=1}if(K.status===nq)if(K.gzhead.extra){C=K.pending;while(K.gzindex<(K.gzhead.extra.length&65535)){if(K.pending===K.pending_buf_size){if(K.gzhead.hcrc&&K.pending>C)A.adler=f7(A.adler,K.pending_buf,K.pending-C,C);if(p7(A),C=K.pending,K.pending===K.pending_buf_size)break}U2(K,K.gzhead.extra[K.gzindex]&255),K.gzindex++}if(K.gzhead.hcrc&&K.pending>C)A.adler=f7(A.adler,K.pending_buf,K.pending-C,C);if(K.gzindex===K.gzhead.extra.length)K.gzindex=0,K.status=PX}else K.status=PX;if(K.status===PX)if(K.gzhead.name){C=K.pending;do{if(K.pending===K.pending_buf_size){if(K.gzhead.hcrc&&K.pending>C)A.adler=f7(A.adler,K.pending_buf,K.pending-C,C);if(p7(A),C=K.pending,K.pending===K.pending_buf_size){U=1;break}}if(K.gzindexC)A.adler=f7(A.adler,K.pending_buf,K.pending-C,C);if(U===0)K.gzindex=0,K.status=_X}else K.status=_X;if(K.status===_X)if(K.gzhead.comment){C=K.pending;do{if(K.pending===K.pending_buf_size){if(K.gzhead.hcrc&&K.pending>C)A.adler=f7(A.adler,K.pending_buf,K.pending-C,C);if(p7(A),C=K.pending,K.pending===K.pending_buf_size){U=1;break}}if(K.gzindexC)A.adler=f7(A.adler,K.pending_buf,K.pending-C,C);if(U===0)K.status=TX}else K.status=TX;if(K.status===TX)if(K.gzhead.hcrc){if(K.pending+2>K.pending_buf_size)p7(A);if(K.pending+2<=K.pending_buf_size)U2(K,A.adler&255),U2(K,A.adler>>8&255),A.adler=0,K.status=l4}else K.status=l4;if(K.pending!==0){if(p7(A),A.avail_out===0)return K.last_flush=-1,u5}else if(A.avail_in===0&&A_(Q)<=A_(J)&&Q!==d7)return c7(A,cq);if(K.status===bY&&A.avail_in!==0)return c7(A,cq);if(A.avail_in!==0||K.lookahead!==0||Q!==o4&&K.status!==bY){var X=K.strategy===wX?fr(K,Q):K.strategy===Rr?br(K,Q):aJ[K.level].func(K,Q);if(X===n4||X===rJ)K.status=bY;if(X===O8||X===n4){if(A.avail_out===0)K.last_flush=-1;return u5}if(X===fY){if(Q===qr)R9._tr_align(K);else if(Q!==tP){if(R9._tr_stored_block(K,0,0,!1),Q===Or){if(u7(K.head),K.lookahead===0)K.strstart=0,K.block_start=0,K.insert=0}}if(p7(A),A.avail_out===0)return K.last_flush=-1,u5}}if(Q!==d7)return u5;if(K.wrap<=0)return eP;if(K.wrap===2)U2(K,A.adler&255),U2(K,A.adler>>8&255),U2(K,A.adler>>16&255),U2(K,A.adler>>24&255),U2(K,A.total_in&255),U2(K,A.total_in>>8&255),U2(K,A.total_in>>16&255),U2(K,A.total_in>>24&255);else gY(K,A.adler>>>16),gY(K,A.adler&65535);if(p7(A),K.wrap>0)K.wrap=-K.wrap;return K.pending!==0?u5:eP}function lr(A){var Q;if(!A||!A.state)return z9;if(Q=A.state.status,Q!==SX&&Q!==nq&&Q!==PX&&Q!==_X&&Q!==TX&&Q!==l4&&Q!==bY)return c7(A,z9);return A.state=null,Q===l4?c7(A,Nr):u5}function nr(A,Q){var J=Q.length,K,C,U,Y,Z,X,E,H;if(!A||!A.state)return z9;if(K=A.state,Y=K.wrap,Y===2||Y===1&&K.status!==SX||K.lookahead)return z9;if(Y===1)A.adler=Q_(A.adler,Q,J,0);if(K.wrap=0,J>=K.w_size){if(Y===0)u7(K.head),K.strstart=0,K.block_start=0,K.insert=0;H=new I6.Buf8(K.w_size),I6.arraySet(H,Q,J-K.w_size,K.w_size,0),Q=H,J=K.w_size}Z=A.avail_in,X=A.next_in,E=A.input,A.avail_in=J,A.next_in=0,A.input=Q,s4(K);while(K.lookahead>=iA){C=K.strstart,U=K.lookahead-(iA-1);do K.ins_h=(K.ins_h<{var jX=T3(),Z_=!0,B_=!0;try{String.fromCharCode.apply(null,[0])}catch(A){Z_=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(A){B_=!1}var pY=new jX.Buf8(256);for(S3=0;S3<256;S3++)pY[S3]=S3>=252?6:S3>=248?5:S3>=240?4:S3>=224?3:S3>=192?2:1;var S3;pY[254]=pY[254]=1;Kt.string2buf=function(A){var Q,J,K,C,U,Y=A.length,Z=0;for(C=0;C>>6,Q[U++]=128|J&63;else if(J<65536)Q[U++]=224|J>>>12,Q[U++]=128|J>>>6&63,Q[U++]=128|J&63;else Q[U++]=240|J>>>18,Q[U++]=128|J>>>12&63,Q[U++]=128|J>>>6&63,Q[U++]=128|J&63}return Q};function X_(A,Q){if(Q<65534){if(A.subarray&&B_||!A.subarray&&Z_)return String.fromCharCode.apply(null,jX.shrinkBuf(A,Q))}var J="";for(var K=0;K4){Z[K++]=65533,J+=U-1;continue}C&=U===2?31:U===3?15:7;while(U>1&&J1){Z[K++]=65533;continue}if(C<65536)Z[K++]=C;else C-=65536,Z[K++]=55296|C>>10&1023,Z[K++]=56320|C&1023}return X_(Z,K)};Kt.utf8border=function(A,Q){var J;if(Q=Q||A.length,Q>A.length)Q=A.length;J=Q-1;while(J>=0&&(A[J]&192)===128)J--;if(J<0)return Q;if(J===0)return Q;return J+pY[A[J]]>Q?J:Q}});var oq=B0((RO1,E_)=>{function Xt(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}E_.exports=Xt});var W_=B0((Ot)=>{var uY=U_(),mY=T3(),aq=sq(),rq=MX(),Et=oq(),G_=Object.prototype.toString,$t=0,iq=4,tJ=0,$_=1,H_=2,Ht=-1,Gt=0,Wt=8;function i4(A){if(!(this instanceof i4))return new i4(A);this.options=mY.assign({level:Ht,method:Wt,chunkSize:16384,windowBits:15,memLevel:8,strategy:Gt,to:""},A||{});var Q=this.options;if(Q.raw&&Q.windowBits>0)Q.windowBits=-Q.windowBits;else if(Q.gzip&&Q.windowBits>0&&Q.windowBits<16)Q.windowBits+=16;this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Et,this.strm.avail_out=0;var J=uY.deflateInit2(this.strm,Q.level,Q.method,Q.windowBits,Q.memLevel,Q.strategy);if(J!==tJ)throw new Error(rq[J]);if(Q.header)uY.deflateSetHeader(this.strm,Q.header);if(Q.dictionary){var K;if(typeof Q.dictionary==="string")K=aq.string2buf(Q.dictionary);else if(G_.call(Q.dictionary)==="[object ArrayBuffer]")K=new Uint8Array(Q.dictionary);else K=Q.dictionary;if(J=uY.deflateSetDictionary(this.strm,K),J!==tJ)throw new Error(rq[J]);this._dict_set=!0}}i4.prototype.push=function(A,Q){var J=this.strm,K=this.options.chunkSize,C,U;if(this.ended)return!1;if(U=Q===~~Q?Q:Q===!0?iq:$t,typeof A==="string")J.input=aq.string2buf(A);else if(G_.call(A)==="[object ArrayBuffer]")J.input=new Uint8Array(A);else J.input=A;J.next_in=0,J.avail_in=J.input.length;do{if(J.avail_out===0)J.output=new mY.Buf8(K),J.next_out=0,J.avail_out=K;if(C=uY.deflate(J,U),C!==$_&&C!==tJ)return this.onEnd(C),this.ended=!0,!1;if(J.avail_out===0||J.avail_in===0&&(U===iq||U===H_))if(this.options.to==="string")this.onData(aq.buf2binstring(mY.shrinkBuf(J.output,J.next_out)));else this.onData(mY.shrinkBuf(J.output,J.next_out))}while((J.avail_in>0||J.avail_out===0)&&C!==$_);if(U===iq)return C=uY.deflateEnd(this.strm),this.onEnd(C),this.ended=!0,C===tJ;if(U===H_)return this.onEnd(tJ),J.avail_out=0,!0;return!0};i4.prototype.onData=function(A){this.chunks.push(A)};i4.prototype.onEnd=function(A){if(A===tJ)if(this.options.to==="string")this.result=this.chunks.join("");else this.result=mY.flattenChunks(this.chunks);this.chunks=[],this.err=A,this.msg=this.strm.msg};function tq(A,Q){var J=new i4(Q);if(J.push(A,!0),J.err)throw J.msg||rq[J.err];return J.result}function It(A,Q){return Q=Q||{},Q.raw=!0,tq(A,Q)}function qt(A,Q){return Q=Q||{},Q.gzip=!0,tq(A,Q)}Ot.Deflate=i4;Ot.deflate=tq;Ot.deflateRaw=It;Ot.gzip=qt});var q_=B0((DO1,I_)=>{var vX=30,zt=12;I_.exports=function A(Q,J){var K,C,U,Y,Z,X,E,H,$,I,N,F,V,D,L,R,M,T,h,y,g,f,u,d,n;K=Q.state,C=Q.next_in,d=Q.input,U=C+(Q.avail_in-5),Y=Q.next_out,n=Q.output,Z=Y-(J-Q.avail_out),X=Y+(Q.avail_out-257),E=K.dmax,H=K.wsize,$=K.whave,I=K.wnext,N=K.window,F=K.hold,V=K.bits,D=K.lencode,L=K.distcode,R=(1<>>24,F>>>=h,V-=h,h=T>>>16&255,h===0)n[Y++]=T&65535;else if(h&16){if(y=T&65535,h&=15,h){if(V>>=h,V-=h}if(V<15)F+=d[C++]<>>24,F>>>=h,V-=h,h=T>>>16&255,h&16){if(g=T&65535,h&=15,VE){Q.msg="invalid distance too far back",K.mode=vX;break A}if(F>>>=h,V-=h,h=Y-Z,g>h){if(h=g-h,h>$){if(K.sane){Q.msg="invalid distance too far back",K.mode=vX;break A}}if(f=0,u=N,I===0){if(f+=H-h,h2)n[Y++]=u[f++],n[Y++]=u[f++],n[Y++]=u[f++],y-=3;if(y){if(n[Y++]=u[f++],y>1)n[Y++]=u[f++]}}else{f=Y-g;do n[Y++]=n[f++],n[Y++]=n[f++],n[Y++]=n[f++],y-=3;while(y>2);if(y){if(n[Y++]=n[f++],y>1)n[Y++]=n[f++]}}}else if((h&64)===0){T=L[(T&65535)+(F&(1<>3,C-=y,V-=y<<3,F&=(1<{var O_=T3(),eJ=15,N_=852,L_=592,F_=0,eq=1,R_=2,Dt=[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],Vt=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],Mt=[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,0,0],wt=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];z_.exports=function A(Q,J,K,C,U,Y,Z,X){var E=X.bits,H=0,$=0,I=0,N=0,F=0,V=0,D=0,L=0,R=0,M=0,T,h,y,g,f,u=null,d=0,n,B=new O_.Buf16(eJ+1),q=new O_.Buf16(eJ+1),P=null,O=0,w,k,S;for(H=0;H<=eJ;H++)B[H]=0;for($=0;$=1;N--)if(B[N]!==0)break;if(F>N)F=N;if(N===0)return U[Y++]=20971520,U[Y++]=20971520,X.bits=1,0;for(I=1;I0&&(Q===F_||N!==1))return-1;q[1]=0;for(H=1;HN_||Q===R_&&R>L_)return 1;for(;;){if(w=H-D,Z[$]n)k=P[O+Z[$]],S=u[d+Z[$]];else k=96,S=0;T=1<>D)+h]=w<<24|k<<16|S|0;while(h!==0);T=1<>=1;if(T!==0)M&=T-1,M+=T;else M=0;if($++,--B[H]===0){if(H===N)break;H=J[K+Z[$]]}if(H>F&&(M&g)!==y){if(D===0)D=F;f+=I,V=H-D,L=1<N_||Q===R_&&R>L_)return 1;y=M&g,U[y]=F<<24|V<<16|f-Y|0}}if(M!==0)U[f+M]=H-D<<24|4194304|0;return X.bits=F,0}});var CT=B0((lt)=>{var e6=T3(),YO=uq(),m5=mq(),Pt=q_(),cY=D_(),_t=0,i_=1,a_=2,V_=4,Tt=5,xX=6,a4=0,kt=1,St=2,D9=-2,r_=-3,UO=-4,jt=-5,M_=8,t_=1,w_=2,P_=3,__=4,T_=5,k_=6,S_=7,j_=8,v_=9,x_=10,gX=11,j3=12,AO=13,y_=14,QO=15,h_=16,g_=17,b_=18,f_=19,yX=20,hX=21,p_=22,u_=23,m_=24,c_=25,d_=26,JO=27,l_=28,n_=29,c2=30,ZO=31,vt=32,xt=852,yt=592,ht=15,gt=ht;function s_(A){return(A>>>24&255)+(A>>>8&65280)+((A&65280)<<8)+((A&255)<<24)}function bt(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new e6.Buf16(320),this.work=new e6.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function e_(A){var Q;if(!A||!A.state)return D9;if(Q=A.state,A.total_in=A.total_out=Q.total=0,A.msg="",Q.wrap)A.adler=Q.wrap&1;return Q.mode=t_,Q.last=0,Q.havedict=0,Q.dmax=32768,Q.head=null,Q.hold=0,Q.bits=0,Q.lencode=Q.lendyn=new e6.Buf32(xt),Q.distcode=Q.distdyn=new e6.Buf32(yt),Q.sane=1,Q.back=-1,a4}function AT(A){var Q;if(!A||!A.state)return D9;return Q=A.state,Q.wsize=0,Q.whave=0,Q.wnext=0,e_(A)}function QT(A,Q){var J,K;if(!A||!A.state)return D9;if(K=A.state,Q<0)J=0,Q=-Q;else if(J=(Q>>4)+1,Q<48)Q&=15;if(Q&&(Q<8||Q>15))return D9;if(K.window!==null&&K.wbits!==Q)K.window=null;return K.wrap=J,K.wbits=Q,AT(A)}function JT(A,Q){var J,K;if(!A)return D9;if(K=new bt,A.state=K,K.window=null,J=QT(A,Q),J!==a4)A.state=null;return J}function ft(A){return JT(A,gt)}var o_=!0,KO,CO;function pt(A){if(o_){var Q;KO=new e6.Buf32(512),CO=new e6.Buf32(32),Q=0;while(Q<144)A.lens[Q++]=8;while(Q<256)A.lens[Q++]=9;while(Q<280)A.lens[Q++]=7;while(Q<288)A.lens[Q++]=8;cY(i_,A.lens,0,288,KO,0,A.work,{bits:9}),Q=0;while(Q<32)A.lens[Q++]=5;cY(a_,A.lens,0,32,CO,0,A.work,{bits:5}),o_=!1}A.lencode=KO,A.lenbits=9,A.distcode=CO,A.distbits=5}function KT(A,Q,J,K){var C,U=A.state;if(U.window===null)U.wsize=1<=U.wsize)e6.arraySet(U.window,Q,J-U.wsize,U.wsize,0),U.wnext=0,U.whave=U.wsize;else{if(C=U.wsize-U.wnext,C>K)C=K;if(e6.arraySet(U.window,Q,J-K,C,U.wnext),K-=C,K)e6.arraySet(U.window,Q,J-K,K,0),U.wnext=K,U.whave=U.wsize;else{if(U.wnext+=C,U.wnext===U.wsize)U.wnext=0;if(U.whave>>8&255,J.check=m5(J.check,u,2,0),E=0,H=0,J.mode=w_;break}if(J.flags=0,J.head)J.head.done=!1;if(!(J.wrap&1)||(((E&255)<<8)+(E>>8))%31){A.msg="incorrect header check",J.mode=c2;break}if((E&15)!==M_){A.msg="unknown compression method",J.mode=c2;break}if(E>>>=4,H-=4,g=(E&15)+8,J.wbits===0)J.wbits=g;else if(g>J.wbits){A.msg="invalid window size",J.mode=c2;break}J.dmax=1<>8&1;if(J.flags&512)u[0]=E&255,u[1]=E>>>8&255,J.check=m5(J.check,u,2,0);E=0,H=0,J.mode=P_;case P_:while(H<32){if(Z===0)break A;Z--,E+=K[U++]<>>8&255,u[2]=E>>>16&255,u[3]=E>>>24&255,J.check=m5(J.check,u,4,0);E=0,H=0,J.mode=__;case __:while(H<16){if(Z===0)break A;Z--,E+=K[U++]<>8;if(J.flags&512)u[0]=E&255,u[1]=E>>>8&255,J.check=m5(J.check,u,2,0);E=0,H=0,J.mode=T_;case T_:if(J.flags&1024){while(H<16){if(Z===0)break A;Z--,E+=K[U++]<>>8&255,J.check=m5(J.check,u,2,0);E=0,H=0}else if(J.head)J.head.extra=null;J.mode=k_;case k_:if(J.flags&1024){if(N=J.length,N>Z)N=Z;if(N){if(J.head){if(g=J.head.extra_len-J.length,!J.head.extra)J.head.extra=new Array(J.head.extra_len);e6.arraySet(J.head.extra,K,U,N,g)}if(J.flags&512)J.check=m5(J.check,K,N,U);Z-=N,U+=N,J.length-=N}if(J.length)break A}J.length=0,J.mode=S_;case S_:if(J.flags&2048){if(Z===0)break A;N=0;do if(g=K[U+N++],J.head&&g&&J.length<65536)J.head.name+=String.fromCharCode(g);while(g&&N>9&1,J.head.done=!0;A.adler=J.check=0,J.mode=j3;break;case x_:while(H<32){if(Z===0)break A;Z--,E+=K[U++]<>>=H&7,H-=H&7,J.mode=JO;break}while(H<3){if(Z===0)break A;Z--,E+=K[U++]<>>=1,H-=1,E&3){case 0:J.mode=y_;break;case 1:if(pt(J),J.mode=yX,Q===xX){E>>>=2,H-=2;break A}break;case 2:J.mode=g_;break;case 3:A.msg="invalid block type",J.mode=c2}E>>>=2,H-=2;break;case y_:E>>>=H&7,H-=H&7;while(H<32){if(Z===0)break A;Z--,E+=K[U++]<>>16^65535)){A.msg="invalid stored block lengths",J.mode=c2;break}if(J.length=E&65535,E=0,H=0,J.mode=QO,Q===xX)break A;case QO:J.mode=h_;case h_:if(N=J.length,N){if(N>Z)N=Z;if(N>X)N=X;if(N===0)break A;e6.arraySet(C,K,U,N,Y),Z-=N,U+=N,X-=N,Y+=N,J.length-=N;break}J.mode=j3;break;case g_:while(H<14){if(Z===0)break A;Z--,E+=K[U++]<>>=5,H-=5,J.ndist=(E&31)+1,E>>>=5,H-=5,J.ncode=(E&15)+4,E>>>=4,H-=4,J.nlen>286||J.ndist>30){A.msg="too many length or distance symbols",J.mode=c2;break}J.have=0,J.mode=b_;case b_:while(J.have>>=3,H-=3}while(J.have<19)J.lens[B[J.have++]]=0;if(J.lencode=J.lendyn,J.lenbits=7,d={bits:J.lenbits},f=cY(_t,J.lens,0,19,J.lencode,0,J.work,d),J.lenbits=d.bits,f){A.msg="invalid code lengths set",J.mode=c2;break}J.have=0,J.mode=f_;case f_:while(J.have>>24,R=D>>>16&255,M=D&65535,L<=H)break;if(Z===0)break A;Z--,E+=K[U++]<>>=L,H-=L,J.lens[J.have++]=M;else{if(M===16){n=L+2;while(H>>=L,H-=L,J.have===0){A.msg="invalid bit length repeat",J.mode=c2;break}g=J.lens[J.have-1],N=3+(E&3),E>>>=2,H-=2}else if(M===17){n=L+3;while(H>>=L,H-=L,g=0,N=3+(E&7),E>>>=3,H-=3}else{n=L+7;while(H>>=L,H-=L,g=0,N=11+(E&127),E>>>=7,H-=7}if(J.have+N>J.nlen+J.ndist){A.msg="invalid bit length repeat",J.mode=c2;break}while(N--)J.lens[J.have++]=g}}if(J.mode===c2)break;if(J.lens[256]===0){A.msg="invalid code -- missing end-of-block",J.mode=c2;break}if(J.lenbits=9,d={bits:J.lenbits},f=cY(i_,J.lens,0,J.nlen,J.lencode,0,J.work,d),J.lenbits=d.bits,f){A.msg="invalid literal/lengths set",J.mode=c2;break}if(J.distbits=6,J.distcode=J.distdyn,d={bits:J.distbits},f=cY(a_,J.lens,J.nlen,J.ndist,J.distcode,0,J.work,d),J.distbits=d.bits,f){A.msg="invalid distances set",J.mode=c2;break}if(J.mode=yX,Q===xX)break A;case yX:J.mode=hX;case hX:if(Z>=6&&X>=258){if(A.next_out=Y,A.avail_out=X,A.next_in=U,A.avail_in=Z,J.hold=E,J.bits=H,Pt(A,I),Y=A.next_out,C=A.output,X=A.avail_out,U=A.next_in,K=A.input,Z=A.avail_in,E=J.hold,H=J.bits,J.mode===j3)J.back=-1;break}J.back=0;for(;;){if(D=J.lencode[E&(1<>>24,R=D>>>16&255,M=D&65535,L<=H)break;if(Z===0)break A;Z--,E+=K[U++]<>T)],L=D>>>24,R=D>>>16&255,M=D&65535,T+L<=H)break;if(Z===0)break A;Z--,E+=K[U++]<>>=T,H-=T,J.back+=T}if(E>>>=L,H-=L,J.back+=L,J.length=M,R===0){J.mode=d_;break}if(R&32){J.back=-1,J.mode=j3;break}if(R&64){A.msg="invalid literal/length code",J.mode=c2;break}J.extra=R&15,J.mode=p_;case p_:if(J.extra){n=J.extra;while(H>>=J.extra,H-=J.extra,J.back+=J.extra}J.was=J.length,J.mode=u_;case u_:for(;;){if(D=J.distcode[E&(1<>>24,R=D>>>16&255,M=D&65535,L<=H)break;if(Z===0)break A;Z--,E+=K[U++]<>T)],L=D>>>24,R=D>>>16&255,M=D&65535,T+L<=H)break;if(Z===0)break A;Z--,E+=K[U++]<>>=T,H-=T,J.back+=T}if(E>>>=L,H-=L,J.back+=L,R&64){A.msg="invalid distance code",J.mode=c2;break}J.offset=M,J.extra=R&15,J.mode=m_;case m_:if(J.extra){n=J.extra;while(H>>=J.extra,H-=J.extra,J.back+=J.extra}if(J.offset>J.dmax){A.msg="invalid distance too far back",J.mode=c2;break}J.mode=c_;case c_:if(X===0)break A;if(N=I-X,J.offset>N){if(N=J.offset-N,N>J.whave){if(J.sane){A.msg="invalid distance too far back",J.mode=c2;break}}if(N>J.wnext)N-=J.wnext,F=J.wsize-N;else F=J.wnext-N;if(N>J.length)N=J.length;V=J.window}else V=C,F=Y-J.offset,N=J.length;if(N>X)N=X;X-=N,J.length-=N;do C[Y++]=V[F++];while(--N);if(J.length===0)J.mode=hX;break;case d_:if(X===0)break A;C[Y++]=J.length,X--,J.mode=hX;break;case JO:if(J.wrap){while(H<32){if(Z===0)break A;Z--,E|=K[U++]<{YT.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var ZT=B0((PO1,UT)=>{function Je(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}UT.exports=Je});var XT=B0((Ue)=>{var AK=CT(),dY=T3(),bX=sq(),U8=BO(),XO=MX(),Ke=oq(),Ce=ZT(),BT=Object.prototype.toString;function r4(A){if(!(this instanceof r4))return new r4(A);this.options=dY.assign({chunkSize:16384,windowBits:0,to:""},A||{});var Q=this.options;if(Q.raw&&Q.windowBits>=0&&Q.windowBits<16){if(Q.windowBits=-Q.windowBits,Q.windowBits===0)Q.windowBits=-15}if(Q.windowBits>=0&&Q.windowBits<16&&!(A&&A.windowBits))Q.windowBits+=32;if(Q.windowBits>15&&Q.windowBits<48){if((Q.windowBits&15)===0)Q.windowBits|=15}this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Ke,this.strm.avail_out=0;var J=AK.inflateInit2(this.strm,Q.windowBits);if(J!==U8.Z_OK)throw new Error(XO[J]);if(this.header=new Ce,AK.inflateGetHeader(this.strm,this.header),Q.dictionary){if(typeof Q.dictionary==="string")Q.dictionary=bX.string2buf(Q.dictionary);else if(BT.call(Q.dictionary)==="[object ArrayBuffer]")Q.dictionary=new Uint8Array(Q.dictionary);if(Q.raw){if(J=AK.inflateSetDictionary(this.strm,Q.dictionary),J!==U8.Z_OK)throw new Error(XO[J])}}}r4.prototype.push=function(A,Q){var J=this.strm,K=this.options.chunkSize,C=this.options.dictionary,U,Y,Z,X,E,H=!1;if(this.ended)return!1;if(Y=Q===~~Q?Q:Q===!0?U8.Z_FINISH:U8.Z_NO_FLUSH,typeof A==="string")J.input=bX.binstring2buf(A);else if(BT.call(A)==="[object ArrayBuffer]")J.input=new Uint8Array(A);else J.input=A;J.next_in=0,J.avail_in=J.input.length;do{if(J.avail_out===0)J.output=new dY.Buf8(K),J.next_out=0,J.avail_out=K;if(U=AK.inflate(J,U8.Z_NO_FLUSH),U===U8.Z_NEED_DICT&&C)U=AK.inflateSetDictionary(this.strm,C);if(U===U8.Z_BUF_ERROR&&H===!0)U=U8.Z_OK,H=!1;if(U!==U8.Z_STREAM_END&&U!==U8.Z_OK)return this.onEnd(U),this.ended=!0,!1;if(J.next_out){if(J.avail_out===0||U===U8.Z_STREAM_END||J.avail_in===0&&(Y===U8.Z_FINISH||Y===U8.Z_SYNC_FLUSH))if(this.options.to==="string"){if(Z=bX.utf8border(J.output,J.next_out),X=J.next_out-Z,E=bX.buf2string(J.output,Z),J.next_out=X,J.avail_out=K-X,X)dY.arraySet(J.output,J.output,Z,X,0);this.onData(E)}else this.onData(dY.shrinkBuf(J.output,J.next_out))}if(J.avail_in===0&&J.avail_out===0)H=!0}while((J.avail_in>0||J.avail_out===0)&&U!==U8.Z_STREAM_END);if(U===U8.Z_STREAM_END)Y=U8.Z_FINISH;if(Y===U8.Z_FINISH)return U=AK.inflateEnd(this.strm),this.onEnd(U),this.ended=!0,U===U8.Z_OK;if(Y===U8.Z_SYNC_FLUSH)return this.onEnd(U8.Z_OK),J.avail_out=0,!0;return!0};r4.prototype.onData=function(A){this.chunks.push(A)};r4.prototype.onEnd=function(A){if(A===U8.Z_OK)if(this.options.to==="string")this.result=this.chunks.join("");else this.result=dY.flattenChunks(this.chunks);this.chunks=[],this.err=A,this.msg=this.strm.msg};function EO(A,Q){var J=new r4(Q);if(J.push(A,!0),J.err)throw J.msg||XO[J.err];return J.result}function Ye(A,Q){return Q=Q||{},Q.raw=!0,EO(A,Q)}Ue.Inflate=r4;Ue.inflate=EO;Ue.inflateRaw=Ye;Ue.ungzip=EO});var HT=B0((TO1,$T)=>{var $e=T3().assign,He=W_(),Ge=XT(),We=BO(),ET={};$e(ET,He,Ge,We);$T.exports=ET});var WT=B0((Ne)=>{var Ie=typeof Uint8Array!=="undefined"&&typeof Uint16Array!=="undefined"&&typeof Uint32Array!=="undefined",qe=HT(),GT=l2(),fX=t6(),Oe=Ie?"uint8array":"array";Ne.magic="\b\x00";function t4(A,Q){fX.call(this,"FlateWorker/"+A),this._pako=null,this._pakoAction=A,this._pakoOptions=Q,this.meta={}}GT.inherits(t4,fX);t4.prototype.processChunk=function(A){if(this.meta=A.meta,this._pako===null)this._createPako();this._pako.push(GT.transformTo(Oe,A.data),!1)};t4.prototype.flush=function(){if(fX.prototype.flush.call(this),this._pako===null)this._createPako();this._pako.push([],!0)};t4.prototype.cleanUp=function(){fX.prototype.cleanUp.call(this),this._pako=null};t4.prototype._createPako=function(){this._pako=new qe[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var A=this;this._pako.onData=function(Q){A.push({data:Q,meta:A.meta})}};Ne.compressWorker=function(A){return new t4("Deflate",A)};Ne.uncompressWorker=function(){return new t4("Inflate",{})}});var $O=B0((ze)=>{var IT=t6();ze.STORE={magic:"\x00\x00",compressWorker:function(){return new IT("STORE compression")},uncompressWorker:function(){return new IT("STORE decompression")}};ze.DEFLATE=WT()});var HO=B0((Me)=>{Me.LOCAL_FILE_HEADER="PK\x03\x04";Me.CENTRAL_FILE_HEADER="PK\x01\x02";Me.CENTRAL_DIRECTORY_END="PK\x05\x06";Me.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x06\x07";Me.ZIP64_CENTRAL_DIRECTORY_END="PK\x06\x06";Me.DATA_DESCRIPTOR="PK\x07\b"});var LT=B0((vO1,NT)=>{var QK=l2(),JK=t6(),GO=lJ(),qT=FX(),pX=HO(),v2=function(A,Q){var J="",K;for(K=0;K>>8;return J},je=function(A,Q){var J=A;if(!A)J=Q?16893:33204;return(J&65535)<<16},ve=function(A){return(A||0)&63},OT=function(A,Q,J,K,C,U){var{file:Y,compression:Z}=A,X=U!==GO.utf8encode,E=QK.transformTo("string",U(Y.name)),H=QK.transformTo("string",GO.utf8encode(Y.name)),$=Y.comment,I=QK.transformTo("string",U($)),N=QK.transformTo("string",GO.utf8encode($)),F=H.length!==Y.name.length,V=N.length!==$.length,D,L,R="",M="",T="",h=Y.dir,y=Y.date,g={crc32:0,compressedSize:0,uncompressedSize:0};if(!Q||J)g.crc32=A.crc32,g.compressedSize=A.compressedSize,g.uncompressedSize=A.uncompressedSize;var f=0;if(Q)f|=8;if(!X&&(F||V))f|=2048;var u=0,d=0;if(h)u|=16;if(C==="UNIX")d=798,u|=je(Y.unixPermissions,h);else d=20,u|=ve(Y.dosPermissions,h);if(D=y.getUTCHours(),D=D<<6,D=D|y.getUTCMinutes(),D=D<<5,D=D|y.getUTCSeconds()/2,L=y.getUTCFullYear()-1980,L=L<<4,L=L|y.getUTCMonth()+1,L=L<<5,L=L|y.getUTCDate(),F)M=v2(1,1)+v2(qT(E),4)+H,R+="up"+v2(M.length,2)+M;if(V)T=v2(1,1)+v2(qT(I),4)+N,R+="uc"+v2(T.length,2)+T;var n="";n+=` -\x00`,n+=v2(f,2),n+=Z.magic,n+=v2(D,2),n+=v2(L,2),n+=v2(g.crc32,4),n+=v2(g.compressedSize,4),n+=v2(g.uncompressedSize,4),n+=v2(E.length,2),n+=v2(R.length,2);var B=pX.LOCAL_FILE_HEADER+n+E+R,q=pX.CENTRAL_FILE_HEADER+v2(d,2)+n+v2(I.length,2)+"\x00\x00\x00\x00"+v2(u,4)+v2(K,4)+E+R+I;return{fileRecord:B,dirRecord:q}},xe=function(A,Q,J,K,C){var U="",Y=QK.transformTo("string",C(K));return U=pX.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+v2(A,2)+v2(A,2)+v2(Q,4)+v2(J,4)+v2(Y.length,2)+Y,U},ye=function(A){var Q="";return Q=pX.DATA_DESCRIPTOR+v2(A.crc32,4)+v2(A.compressedSize,4)+v2(A.uncompressedSize,4),Q};function K5(A,Q,J,K){JK.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=Q,this.zipPlatform=J,this.encodeFileName=K,this.streamFiles=A,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}QK.inherits(K5,JK);K5.prototype.push=function(A){var Q=A.meta.percent||0,J=this.entriesCount,K=this._sources.length;if(this.accumulate)this.contentBuffer.push(A);else this.bytesWritten+=A.data.length,JK.prototype.push.call(this,{data:A.data,meta:{currentFile:this.currentFile,percent:J?(Q+100*(J-K-1))/J:100}})};K5.prototype.openedSource=function(A){this.currentSourceOffset=this.bytesWritten,this.currentFile=A.file.name;var Q=this.streamFiles&&!A.file.dir;if(Q){var J=OT(A,Q,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:J.fileRecord,meta:{percent:0}})}else this.accumulate=!0};K5.prototype.closedSource=function(A){this.accumulate=!1;var Q=this.streamFiles&&!A.file.dir,J=OT(A,Q,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(J.dirRecord),Q)this.push({data:ye(A),meta:{percent:100}});else{this.push({data:J.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};K5.prototype.flush=function(){var A=this.bytesWritten;for(var Q=0;Q{var he=$O(),ge=LT(),be=function(A,Q){var J=A||Q,K=he[J];if(!K)throw new Error(J+" is not a valid compression method !");return K};fe.generateWorker=function(A,Q,J){var K=new ge(Q.streamFiles,J,Q.platform,Q.encodeFileName),C=0;try{A.forEach(function(U,Y){C++;var Z=be(Y.options.compression,Q.compression),X=Y.options.compressionOptions||Q.compressionOptions||{},E=Y.dir,H=Y.date;Y._compressWorker(Z,X).withStreamInfo("file",{name:U,dir:E,date:H,comment:Y.comment||"",unixPermissions:Y.unixPermissions,dosPermissions:Y.dosPermissions}).pipe(K)}),K.entriesCount=C}catch(U){K.error(U)}return K}});var zT=B0((yO1,RT)=>{var ue=l2(),uX=t6();function lY(A,Q){uX.call(this,"Nodejs stream input adapter for "+A),this._upstreamEnded=!1,this._bindStream(Q)}ue.inherits(lY,uX);lY.prototype._bindStream=function(A){var Q=this;this._stream=A,A.pause(),A.on("data",function(J){Q.push({data:J,meta:{percent:0}})}).on("error",function(J){if(Q.isPaused)this.generatedError=J;else Q.error(J)}).on("end",function(){if(Q.isPaused)Q._upstreamEnded=!0;else Q.end()})};lY.prototype.pause=function(){if(!uX.prototype.pause.call(this))return!1;return this._stream.pause(),!0};lY.prototype.resume=function(){if(!uX.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};RT.exports=lY});var jT=B0((hO1,ST)=>{var me=lJ(),nY=l2(),wT=t6(),ce=Oq(),PT=Nq(),DT=RX(),de=VP(),le=FT(),VT=VY(),ne=zT(),_T=function(A,Q,J){var K=nY.getTypeOf(Q),C,U=nY.extend(J||{},PT);if(U.date=U.date||/*@__PURE__*/new Date,U.compression!==null)U.compression=U.compression.toUpperCase();if(typeof U.unixPermissions==="string")U.unixPermissions=parseInt(U.unixPermissions,8);if(U.unixPermissions&&U.unixPermissions&16384)U.dir=!0;if(U.dosPermissions&&U.dosPermissions&16)U.dir=!0;if(U.dir)A=TT(A);if(U.createFolders&&(C=se(A)))kT.call(this,C,!0);var Y=K==="string"&&U.binary===!1&&U.base64===!1;if(!J||typeof J.binary==="undefined")U.binary=!Y;var Z=Q instanceof DT&&Q.uncompressedSize===0;if(Z||U.dir||!Q||Q.length===0)U.base64=!1,U.binary=!0,Q="",U.compression="STORE",K="string";var X=null;if(Q instanceof DT||Q instanceof wT)X=Q;else if(VT.isNode&&VT.isStream(Q))X=new ne(A,Q);else X=nY.prepareContent(A,Q,U.binary,U.optimizedBinaryString,U.base64);var E=new de(A,X,U);this.files[A]=E},se=function(A){if(A.slice(-1)==="/")A=A.substring(0,A.length-1);var Q=A.lastIndexOf("/");return Q>0?A.substring(0,Q):""},TT=function(A){if(A.slice(-1)!=="/")A+="/";return A},kT=function(A,Q){if(Q=typeof Q!=="undefined"?Q:PT.createFolders,A=TT(A),!this.files[A])_T.call(this,A,null,{dir:!0,createFolders:Q});return this.files[A]};function MT(A){return Object.prototype.toString.call(A)==="[object RegExp]"}var oe={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(A){var Q,J,K;for(Q in this.files)if(K=this.files[Q],J=Q.slice(this.root.length,Q.length),J&&Q.slice(0,this.root.length)===this.root)A(J,K)},filter:function(A){var Q=[];return this.forEach(function(J,K){if(A(J,K))Q.push(K)}),Q},file:function(A,Q,J){if(arguments.length===1)if(MT(A)){var K=A;return this.filter(function(U,Y){return!Y.dir&&K.test(U)})}else{var C=this.files[this.root+A];if(C&&!C.dir)return C;else return null}else A=this.root+A,_T.call(this,A,Q,J);return this},folder:function(A){if(!A)return this;if(MT(A))return this.filter(function(C,U){return U.dir&&A.test(C)});var Q=this.root+A,J=kT.call(this,Q),K=this.clone();return K.root=J.name,K},remove:function(A){A=this.root+A;var Q=this.files[A];if(!Q){if(A.slice(-1)!=="/")A+="/";Q=this.files[A]}if(Q&&!Q.dir)delete this.files[A];else{var J=this.filter(function(C,U){return U.name.slice(0,A.length)===A});for(var K=0;K{var ie=l2();function vT(A){this.data=A,this.length=A.length,this.index=0,this.zero=0}vT.prototype={checkOffset:function(A){this.checkIndex(this.index+A)},checkIndex:function(A){if(this.length=this.index;J--)Q=(Q<<8)+this.byteAt(J);return this.index+=A,Q},readString:function(A){return ie.transformTo("string",this.readData(A))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var A=this.readInt(4);return new Date(Date.UTC((A>>25&127)+1980,(A>>21&15)-1,A>>16&31,A>>11&31,A>>5&63,(A&31)<<1))}};xT.exports=vT});var IO=B0((bO1,hT)=>{var yT=WO(),ae=l2();function KK(A){yT.call(this,A);for(var Q=0;Q=0;--U)if(this.data[U]===Q&&this.data[U+1]===J&&this.data[U+2]===K&&this.data[U+3]===C)return U-this.zero;return-1};KK.prototype.readAndCheckSignature=function(A){var Q=A.charCodeAt(0),J=A.charCodeAt(1),K=A.charCodeAt(2),C=A.charCodeAt(3),U=this.readData(4);return Q===U[0]&&J===U[1]&&K===U[2]&&C===U[3]};KK.prototype.readData=function(A){if(this.checkOffset(A),A===0)return[];var Q=this.data.slice(this.zero+this.index,this.zero+this.index+A);return this.index+=A,Q};hT.exports=KK});var fT=B0((fO1,bT)=>{var gT=WO(),re=l2();function CK(A){gT.call(this,A)}re.inherits(CK,gT);CK.prototype.byteAt=function(A){return this.data.charCodeAt(this.zero+A)};CK.prototype.lastIndexOfSignature=function(A){return this.data.lastIndexOf(A)-this.zero};CK.prototype.readAndCheckSignature=function(A){var Q=this.readData(4);return A===Q};CK.prototype.readData=function(A){this.checkOffset(A);var Q=this.data.slice(this.zero+this.index,this.zero+this.index+A);return this.index+=A,Q};bT.exports=CK});var OO=B0((pO1,uT)=>{var pT=IO(),te=l2();function qO(A){pT.call(this,A)}te.inherits(qO,pT);qO.prototype.readData=function(A){if(this.checkOffset(A),A===0)return new Uint8Array(0);var Q=this.data.subarray(this.zero+this.index,this.zero+this.index+A);return this.index+=A,Q};uT.exports=qO});var dT=B0((uO1,cT)=>{var mT=OO(),ee=l2();function NO(A){mT.call(this,A)}ee.inherits(NO,mT);NO.prototype.readData=function(A){this.checkOffset(A);var Q=this.data.slice(this.zero+this.index,this.zero+this.index+A);return this.index+=A,Q};cT.exports=NO});var LO=B0((mO1,nT)=>{var mX=l2(),lT=P3(),A11=IO(),Q11=fT(),J11=dT(),K11=OO();nT.exports=function(A){var Q=mX.getTypeOf(A);if(mX.checkSupport(Q),Q==="string"&&!lT.uint8array)return new Q11(A);if(Q==="nodebuffer")return new J11(A);if(lT.uint8array)return new K11(mX.transformTo("uint8array",A));return new A11(mX.transformTo("array",A))}});var aT=B0((cO1,iT)=>{var FO=LO(),l7=l2(),C11=RX(),sT=FX(),cX=lJ(),dX=$O(),Y11=P3(),U11=0,Z11=3,B11=function(A){for(var Q in dX){if(!Object.prototype.hasOwnProperty.call(dX,Q))continue;if(dX[Q].magic===A)return dX[Q]}return null};function oT(A,Q){this.options=A,this.loadOptions=Q}oT.prototype={isEncrypted:function(){return(this.bitFlag&1)===1},useUTF8:function(){return(this.bitFlag&2048)===2048},readLocalPart:function(A){var Q,J;if(A.skip(22),this.fileNameLength=A.readInt(2),J=A.readInt(2),this.fileName=A.readData(this.fileNameLength),A.skip(J),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(Q=B11(this.compressionMethod),Q===null)throw new Error("Corrupted zip : compression "+l7.pretty(this.compressionMethod)+" unknown (inner file : "+l7.transformTo("string",this.fileName)+")");this.decompressed=new C11(this.compressedSize,this.uncompressedSize,this.crc32,Q,A.readData(this.compressedSize))},readCentralPart:function(A){this.versionMadeBy=A.readInt(2),A.skip(2),this.bitFlag=A.readInt(2),this.compressionMethod=A.readString(2),this.date=A.readDate(),this.crc32=A.readInt(4),this.compressedSize=A.readInt(4),this.uncompressedSize=A.readInt(4);var Q=A.readInt(2);if(this.extraFieldsLength=A.readInt(2),this.fileCommentLength=A.readInt(2),this.diskNumberStart=A.readInt(2),this.internalFileAttributes=A.readInt(2),this.externalFileAttributes=A.readInt(4),this.localHeaderOffset=A.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");A.skip(Q),this.readExtraFields(A),this.parseZIP64ExtraField(A),this.fileComment=A.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var A=this.versionMadeBy>>8;if(this.dir=this.externalFileAttributes&16?!0:!1,A===U11)this.dosPermissions=this.externalFileAttributes&63;if(A===Z11)this.unixPermissions=this.externalFileAttributes>>16&65535;if(!this.dir&&this.fileNameStr.slice(-1)==="/")this.dir=!0},parseZIP64ExtraField:function(){if(!this.extraFields[1])return;var A=FO(this.extraFields[1].value);if(this.uncompressedSize===l7.MAX_VALUE_32BITS)this.uncompressedSize=A.readInt(8);if(this.compressedSize===l7.MAX_VALUE_32BITS)this.compressedSize=A.readInt(8);if(this.localHeaderOffset===l7.MAX_VALUE_32BITS)this.localHeaderOffset=A.readInt(8);if(this.diskNumberStart===l7.MAX_VALUE_32BITS)this.diskNumberStart=A.readInt(4)},readExtraFields:function(A){var Q=A.index+this.extraFieldsLength,J,K,C;if(!this.extraFields)this.extraFields={};while(A.index+4{var X11=LO(),v3=l2(),C5=HO(),E11=aT(),$11=P3();function rT(A){this.files=[],this.loadOptions=A}rT.prototype={checkSignature:function(A){if(!this.reader.readAndCheckSignature(A)){this.reader.index-=4;var Q=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+v3.pretty(Q)+", expected "+v3.pretty(A)+")")}},isSignature:function(A,Q){var J=this.reader.index;this.reader.setIndex(A);var K=this.reader.readString(4),C=K===Q;return this.reader.setIndex(J),C},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var A=this.reader.readData(this.zipCommentLength),Q=$11.uint8array?"uint8array":"array",J=v3.transformTo(Q,A);this.zipComment=this.loadOptions.decodeFileName(J)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};var A=this.zip64EndOfCentralSize-44,Q=0,J,K,C;while(Q1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var A,Q;for(A=0;A0)if(this.isSignature(J,C5.CENTRAL_FILE_HEADER));else this.reader.zero=C;else if(C<0)throw new Error("Corrupted zip: missing "+Math.abs(C)+" bytes.")},prepareReader:function(A){this.reader=X11(A)},load:function(A){this.prepareReader(A),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}};tT.exports=rT});var Jk=B0((lO1,Qk)=>{var RO=l2(),lX=mJ(),H11=lJ(),G11=eT(),W11=Rq(),Ak=VY();function I11(A){return new lX.Promise(function(Q,J){var K=A.decompressed.getContentWorker().pipe(new W11);K.on("error",function(C){J(C)}).on("end",function(){if(K.streamInfo.crc32!==A.decompressed.crc32)J(new Error("Corrupted zip : CRC32 mismatch"));else Q()}).resume()})}Qk.exports=function(A,Q){var J=this;if(Q=RO.extend(Q||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:H11.utf8decode}),Ak.isNode&&Ak.isStream(A))return lX.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file."));return RO.prepareContent("the loaded zip file",A,!0,Q.optimizedBinaryString,Q.base64).then(function(K){var C=new G11(Q);return C.load(K),C}).then(function K(C){var U=[lX.Promise.resolve(C)],Y=C.files;if(Q.checkCRC32)for(var Z=0;Z{function V9(){if(!(this instanceof V9))return new V9;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var A=new V9;for(var Q in this)if(typeof this[Q]!=="function")A[Q]=this[Q];return A}}V9.prototype=jT();V9.prototype.loadAsync=Jk();V9.support=P3();V9.defaults=Nq();V9.version="3.10.1";V9.loadAsync=function(A,Q){return new V9().loadAsync(A,Q)};V9.external=mJ();Kk.exports=V9});var Ek=B0((QN1,Xk)=>{(function(){var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Q={rotl:function(J,K){return J<>>32-K},rotr:function(J,K){return J<<32-K|J>>>K},endian:function(J){if(J.constructor==Number)return Q.rotl(J,8)&16711935|Q.rotl(J,24)&4278255360;for(var K=0;K0;J--)K.push(Math.floor(Math.random()*256));return K},bytesToWords:function(J){for(var K=[],C=0,U=0;C>>5]|=J[C]<<24-U%32;return K},wordsToBytes:function(J){for(var K=[],C=0;C>>5]>>>24-C%32&255);return K},bytesToHex:function(J){for(var K=[],C=0;C>>4).toString(16)),K.push((J[C]&15).toString(16));return K.join("")},hexToBytes:function(J){for(var K=[],C=0;C>>6*(3-Y)&63));else K.push("=")}return K.join("")},base64ToBytes:function(J){J=J.replace(/[^A-Z0-9+\/]/ig,"");for(var K=[],C=0,U=0;C>>6-U*2)}return K}};Xk.exports=Q})()});var VO=B0((JN1,$k)=>{var DO={utf8:{stringToBytes:function(A){return DO.bin.stringToBytes(unescape(encodeURIComponent(A)))},bytesToString:function(A){return decodeURIComponent(escape(DO.bin.bytesToString(A)))}},bin:{stringToBytes:function(A){for(var Q=[],J=0;J{/*! - * Determine if an object is a Buffer - * - * @author Feross Aboukhadijeh - * @license MIT - */Gk.exports=function(A){return A!=null&&(Hk(A)||O11(A)||!!A._isBuffer)};function Hk(A){return!!A.constructor&&typeof A.constructor.isBuffer==="function"&&A.constructor.isBuffer(A)}function O11(A){return typeof A.readFloatLE==="function"&&typeof A.slice==="function"&&Hk(A.slice(0,0))}});var MO=B0((CN1,Ik)=>{(function(){var A=Ek(),Q=VO().utf8,J=Wk(),K=VO().bin,C=function(U,Y){if(U.constructor==String)if(Y&&Y.encoding==="binary")U=K.stringToBytes(U);else U=Q.stringToBytes(U);else if(J(U))U=Array.prototype.slice.call(U,0);else if(!Array.isArray(U)&&U.constructor!==Uint8Array)U=U.toString();var Z=A.bytesToWords(U),X=U.length*8,E=1732584193,H=-271733879,$=-1732584194,I=271733878;for(var N=0;N>>24)&16711935|(Z[N]<<24|Z[N]>>>8)&4278255360;Z[X>>>5]|=128<>>9<<4)+14]=X;var{_ff:F,_gg:V,_hh:D,_ii:L}=C;for(var N=0;N>>0,H=H+M>>>0,$=$+T>>>0,I=I+h>>>0}return A.endian([E,H,$,I])};C._ff=function(U,Y,Z,X,E,H,$){var I=U+(Y&Z|~Y&X)+(E>>>0)+$;return(I<>>32-H)+Y},C._gg=function(U,Y,Z,X,E,H,$){var I=U+(Y&X|Z&~X)+(E>>>0)+$;return(I<>>32-H)+Y},C._hh=function(U,Y,Z,X,E,H,$){var I=U+(Y^Z^X)+(E>>>0)+$;return(I<>>32-H)+Y},C._ii=function(U,Y,Z,X,E,H,$){var I=U+(Z^(Y|~X))+(E>>>0)+$;return(I<>>32-H)+Y},C._blocksize=16,C._digestsize=16,Ik.exports=function(U,Y){if(U===void 0||U===null)throw new Error("Illegal argument "+U);var Z=A.wordsToBytes(C(U,Y));return Y&&Y.asBytes?Z:Y&&Y.asString?K.bytesToString(Z):A.bytesToHex(Z)}})()});var nX=B0(($N1,Ok)=>{Ok.exports=function A(){if(typeof Symbol!=="function"||typeof Object.getOwnPropertySymbols!=="function")return!1;if(typeof Symbol.iterator==="symbol")return!0;var Q={},J=Symbol("test"),K=Object(J);if(typeof J==="string")return!1;if(Object.prototype.toString.call(J)!=="[object Symbol]")return!1;if(Object.prototype.toString.call(K)!=="[object Symbol]")return!1;var C=42;Q[J]=C;for(J in Q)return!1;if(typeof Object.keys==="function"&&Object.keys(Q).length!==0)return!1;if(typeof Object.getOwnPropertyNames==="function"&&Object.getOwnPropertyNames(Q).length!==0)return!1;var U=Object.getOwnPropertySymbols(Q);if(U.length!==1||U[0]!==J)return!1;if(!Object.prototype.propertyIsEnumerable.call(Q,J))return!1;if(typeof Object.getOwnPropertyDescriptor==="function"){var Y=Object.getOwnPropertyDescriptor(Q,J);if(Y.value!==C||Y.enumerable!==!0)return!1}return!0}});var sX=B0((HN1,Nk)=>{var D11=nX();Nk.exports=function A(){return D11()&&!!Symbol.toStringTag}});var Fk=B0((GN1,Lk)=>{Lk.exports=Error});var zk=B0((WN1,Rk)=>{Rk.exports=EvalError});var Vk=B0((IN1,Dk)=>{Dk.exports=RangeError});var wk=B0((qN1,Mk)=>{Mk.exports=ReferenceError});var wO=B0((ON1,Pk)=>{Pk.exports=SyntaxError});var oY=B0((NN1,_k)=>{_k.exports=TypeError});var kk=B0((LN1,Tk)=>{Tk.exports=URIError});var vk=B0((FN1,jk)=>{var Sk=typeof Symbol!=="undefined"&&Symbol,V11=nX();jk.exports=function A(){if(typeof Sk!=="function")return!1;if(typeof Symbol!=="function")return!1;if(typeof Sk("foo")!=="symbol")return!1;if(typeof Symbol("bar")!=="symbol")return!1;return V11()}});var yk=B0((RN1,xk)=>{var PO={__proto__:null,foo:{}},M11=Object;xk.exports=function A(){return{__proto__:PO}.foo===PO.foo&&!(PO instanceof M11)}});var bk=B0((zN1,gk)=>{var w11="Function.prototype.bind called on incompatible ",P11=Object.prototype.toString,_11=Math.max,T11="[object Function]",hk=function A(Q,J){var K=[];for(var C=0;C{var j11=bk();fk.exports=Function.prototype.bind||j11});var uk=B0((VN1,pk)=>{var v11=Function.prototype.call,x11=Object.prototype.hasOwnProperty,y11=oX();pk.exports=y11.call(v11,x11)});var XK=B0((MN1,nk)=>{var oA,h11=Fk(),g11=zk(),b11=Vk(),f11=wk(),BK=wO(),ZK=oY(),p11=kk(),lk=Function,_O=function(A){try{return lk('"use strict"; return ('+A+").constructor;")()}catch(Q){}},e4=Object.getOwnPropertyDescriptor;if(e4)try{e4({},"")}catch(A){e4=null}var TO=function(){throw new ZK},u11=e4?function(){try{return arguments.callee,TO}catch(A){try{return e4(arguments,"callee").get}catch(Q){return TO}}}():TO,YK=vk()(),m11=yk()(),x8=Object.getPrototypeOf||(m11?function(A){return A.__proto__}:null),UK={},c11=typeof Uint8Array==="undefined"||!x8?oA:x8(Uint8Array),AQ={__proto__:null,"%AggregateError%":typeof AggregateError==="undefined"?oA:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer==="undefined"?oA:ArrayBuffer,"%ArrayIteratorPrototype%":YK&&x8?x8([][Symbol.iterator]()):oA,"%AsyncFromSyncIteratorPrototype%":oA,"%AsyncFunction%":UK,"%AsyncGenerator%":UK,"%AsyncGeneratorFunction%":UK,"%AsyncIteratorPrototype%":UK,"%Atomics%":typeof Atomics==="undefined"?oA:Atomics,"%BigInt%":typeof BigInt==="undefined"?oA:BigInt,"%BigInt64Array%":typeof BigInt64Array==="undefined"?oA:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array==="undefined"?oA:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView==="undefined"?oA:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":h11,"%eval%":eval,"%EvalError%":g11,"%Float32Array%":typeof Float32Array==="undefined"?oA:Float32Array,"%Float64Array%":typeof Float64Array==="undefined"?oA:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry==="undefined"?oA:FinalizationRegistry,"%Function%":lk,"%GeneratorFunction%":UK,"%Int8Array%":typeof Int8Array==="undefined"?oA:Int8Array,"%Int16Array%":typeof Int16Array==="undefined"?oA:Int16Array,"%Int32Array%":typeof Int32Array==="undefined"?oA:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":YK&&x8?x8(x8([][Symbol.iterator]())):oA,"%JSON%":typeof JSON==="object"?JSON:oA,"%Map%":typeof Map==="undefined"?oA:Map,"%MapIteratorPrototype%":typeof Map==="undefined"||!YK||!x8?oA:x8((/*@__PURE__*/new Map())[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise==="undefined"?oA:Promise,"%Proxy%":typeof Proxy==="undefined"?oA:Proxy,"%RangeError%":b11,"%ReferenceError%":f11,"%Reflect%":typeof Reflect==="undefined"?oA:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set==="undefined"?oA:Set,"%SetIteratorPrototype%":typeof Set==="undefined"||!YK||!x8?oA:x8((/*@__PURE__*/new Set())[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer==="undefined"?oA:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":YK&&x8?x8(""[Symbol.iterator]()):oA,"%Symbol%":YK?Symbol:oA,"%SyntaxError%":BK,"%ThrowTypeError%":u11,"%TypedArray%":c11,"%TypeError%":ZK,"%Uint8Array%":typeof Uint8Array==="undefined"?oA:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray==="undefined"?oA:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array==="undefined"?oA:Uint16Array,"%Uint32Array%":typeof Uint32Array==="undefined"?oA:Uint32Array,"%URIError%":p11,"%WeakMap%":typeof WeakMap==="undefined"?oA:WeakMap,"%WeakRef%":typeof WeakRef==="undefined"?oA:WeakRef,"%WeakSet%":typeof WeakSet==="undefined"?oA:WeakSet};if(x8)try{null.error}catch(A){mk=x8(x8(A)),AQ["%Error.prototype%"]=mk}var mk,d11=function A(Q){var J;if(Q==="%AsyncFunction%")J=_O("async function () {}");else if(Q==="%GeneratorFunction%")J=_O("function* () {}");else if(Q==="%AsyncGeneratorFunction%")J=_O("async function* () {}");else if(Q==="%AsyncGenerator%"){var K=A("%AsyncGeneratorFunction%");if(K)J=K.prototype}else if(Q==="%AsyncIteratorPrototype%"){var C=A("%AsyncGenerator%");if(C&&x8)J=x8(C.prototype)}return AQ[Q]=J,J},ck={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},iY=oX(),iX=uk(),l11=iY.call(Function.call,Array.prototype.concat),n11=iY.call(Function.apply,Array.prototype.splice),dk=iY.call(Function.call,String.prototype.replace),aX=iY.call(Function.call,String.prototype.slice),s11=iY.call(Function.call,RegExp.prototype.exec),o11=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,i11=/\\(\\)?/g,a11=function A(Q){var J=aX(Q,0,1),K=aX(Q,-1);if(J==="%"&&K!=="%")throw new BK("invalid intrinsic syntax, expected closing `%`");else if(K==="%"&&J!=="%")throw new BK("invalid intrinsic syntax, expected opening `%`");var C=[];return dk(Q,o11,function(U,Y,Z,X){C[C.length]=Z?dk(X,i11,"$1"):Y||U}),C},r11=function A(Q,J){var K=Q,C;if(iX(ck,K))C=ck[K],K="%"+C[0]+"%";if(iX(AQ,K)){var U=AQ[K];if(U===UK)U=d11(K);if(typeof U==="undefined"&&!J)throw new ZK("intrinsic "+Q+" exists, but is not available. Please file an issue!");return{alias:C,name:K,value:U}}throw new BK("intrinsic "+Q+" does not exist!")};nk.exports=function A(Q,J){if(typeof Q!=="string"||Q.length===0)throw new ZK("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof J!=="boolean")throw new ZK('"allowMissing" argument must be a boolean');if(s11(/^%?[^%]*%?$/,Q)===null)throw new BK("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var K=a11(Q),C=K.length>0?K[0]:"",U=r11("%"+C+"%",J),Y=U.name,Z=U.value,X=!1,E=U.alias;if(E)C=E[0],n11(K,l11([0,1],E));for(var H=1,$=!0;H=K.length){var V=e4(Z,I);if($=!!V,$&&"get"in V&&!("originalValue"in V.get))Z=V.get;else Z=Z[I]}else $=iX(Z,I),Z=Z[I];if($&&!X)AQ[Y]=Z}}return Z}});var tX=B0((wN1,sk)=>{var t11=XK(),rX=t11("%Object.defineProperty%",!0)||!1;if(rX)try{rX({},"a",{value:1})}catch(A){rX=!1}sk.exports=rX});var AE=B0((PN1,ok)=>{var e11=XK(),eX=e11("%Object.getOwnPropertyDescriptor%",!0);if(eX)try{eX([],"length")}catch(A){eX=null}ok.exports=eX});var kO=B0((_N1,rk)=>{var ik=tX(),A01=wO(),EK=oY(),ak=AE();rk.exports=function A(Q,J,K){if(!Q||typeof Q!=="object"&&typeof Q!=="function")throw new EK("`obj` must be an object or a function`");if(typeof J!=="string"&&typeof J!=="symbol")throw new EK("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!=="boolean"&&arguments[3]!==null)throw new EK("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!=="boolean"&&arguments[4]!==null)throw new EK("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!=="boolean"&&arguments[5]!==null)throw new EK("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!=="boolean")throw new EK("`loose`, if provided, must be a boolean");var C=arguments.length>3?arguments[3]:null,U=arguments.length>4?arguments[4]:null,Y=arguments.length>5?arguments[5]:null,Z=arguments.length>6?arguments[6]:!1,X=!!ak&&ak(Q,J);if(ik)ik(Q,J,{configurable:Y===null&&X?X.configurable:!Y,enumerable:C===null&&X?X.enumerable:!C,value:K,writable:U===null&&X?X.writable:!U});else if(Z||!C&&!U&&!Y)Q[J]=K;else throw new A01("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var jO=B0((TN1,ek)=>{var SO=tX(),tk=function A(){return!!SO};tk.hasArrayLengthDefineBug=function A(){if(!SO)return null;try{return SO([],"length",{value:1}).length!==1}catch(Q){return!0}};ek.exports=tk});var CS=B0((kN1,KS)=>{var Q01=XK(),AS=kO(),J01=jO()(),QS=AE(),JS=oY(),K01=Q01("%Math.floor%");KS.exports=function A(Q,J){if(typeof Q!=="function")throw new JS("`fn` is not a function");if(typeof J!=="number"||J<0||J>4294967295||K01(J)!==J)throw new JS("`length` must be a positive 32-bit integer");var K=arguments.length>2&&!!arguments[2],C=!0,U=!0;if("length"in Q&&QS){var Y=QS(Q,"length");if(Y&&!Y.configurable)C=!1;if(Y&&!Y.writable)U=!1}if(C||U||!K)if(J01)AS(Q,"length",J,!0,!0);else AS(Q,"length",J);return Q}});var aY=B0((SN1,QE)=>{var vO=oX(),JE=XK(),C01=CS(),Y01=oY(),ZS=JE("%Function.prototype.apply%"),BS=JE("%Function.prototype.call%"),XS=JE("%Reflect.apply%",!0)||vO.call(BS,ZS),YS=tX(),U01=JE("%Math.max%");QE.exports=function A(Q){if(typeof Q!=="function")throw new Y01("a function is required");var J=XS(vO,BS,arguments);return C01(J,1+U01(0,Q.length-(arguments.length-1)),!0)};var US=function A(){return XS(vO,ZS,arguments)};if(YS)YS(QE.exports,"apply",{value:US});else QE.exports.apply=US});var rY=B0((jN1,HS)=>{var ES=XK(),$S=aY(),Z01=$S(ES("String.prototype.indexOf"));HS.exports=function A(Q,J){var K=ES(Q,!!J);if(typeof K==="function"&&Z01(Q,".prototype.")>-1)return $S(K);return K}});var IS=B0((vN1,WS)=>{var B01=sX()(),X01=rY(),xO=X01("Object.prototype.toString"),KE=function A(Q){if(B01&&Q&&typeof Q==="object"&&Symbol.toStringTag in Q)return!1;return xO(Q)==="[object Arguments]"},GS=function A(Q){if(KE(Q))return!0;return Q!==null&&typeof Q==="object"&&typeof Q.length==="number"&&Q.length>=0&&xO(Q)!=="[object Array]"&&xO(Q.callee)==="[object Function]"},E01=function(){return KE(arguments)}();KE.isLegacyArguments=GS;WS.exports=E01?KE:GS});var NS=B0((xN1,OS)=>{var $01=Object.prototype.toString,H01=Function.prototype.toString,G01=/^\s*(?:function)?\*/,qS=sX()(),yO=Object.getPrototypeOf,W01=function(){if(!qS)return!1;try{return Function("return function*() {}")()}catch(A){}},hO;OS.exports=function A(Q){if(typeof Q!=="function")return!1;if(G01.test(H01.call(Q)))return!0;if(!qS){var J=$01.call(Q);return J==="[object GeneratorFunction]"}if(!yO)return!1;if(typeof hO==="undefined"){var K=W01();hO=K?yO(K):!1}return yO(Q)===hO}});var zS=B0((yN1,RS)=>{var FS=Function.prototype.toString,$K=typeof Reflect==="object"&&Reflect!==null&&Reflect.apply,bO,CE;if(typeof $K==="function"&&typeof Object.defineProperty==="function")try{bO=Object.defineProperty({},"length",{get:function(){throw CE}}),CE={},$K(function(){throw 42},null,bO)}catch(A){if(A!==CE)$K=null}else $K=null;var I01=/^\s*class\b/,fO=function A(Q){try{var J=FS.call(Q);return I01.test(J)}catch(K){return!1}},gO=function A(Q){try{if(fO(Q))return!1;return FS.call(Q),!0}catch(J){return!1}},YE=Object.prototype.toString,q01="[object Object]",O01="[object Function]",N01="[object GeneratorFunction]",L01="[object HTMLAllCollection]",F01="[object HTML document.all class]",R01="[object HTMLCollection]",z01=typeof Symbol==="function"&&!!Symbol.toStringTag,D01=!(0 in[,]),pO=function A(){return!1};if(typeof document==="object"){if(LS=document.all,YE.call(LS)===YE.call(document.all))pO=function A(Q){if((D01||!Q)&&(typeof Q==="undefined"||typeof Q==="object"))try{var J=YE.call(Q);return(J===L01||J===F01||J===R01||J===q01)&&Q("")==null}catch(K){}return!1}}var LS;RS.exports=$K?function A(Q){if(pO(Q))return!0;if(!Q)return!1;if(typeof Q!=="function"&&typeof Q!=="object")return!1;try{$K(Q,null,bO)}catch(J){if(J!==CE)return!1}return!fO(Q)&&gO(Q)}:function A(Q){if(pO(Q))return!0;if(!Q)return!1;if(typeof Q!=="function"&&typeof Q!=="object")return!1;if(z01)return gO(Q);if(fO(Q))return!1;var J=YE.call(Q);if(J!==O01&&J!==N01&&!/^\[object HTML/.test(J))return!1;return gO(Q)}});var MS=B0((hN1,VS)=>{var V01=zS(),M01=Object.prototype.toString,DS=Object.prototype.hasOwnProperty,w01=function A(Q,J,K){for(var C=0,U=Q.length;C=3)C=K;if(M01.call(Q)==="[object Array]")w01(Q,J,C);else if(typeof Q==="string")P01(Q,J,C);else _01(Q,J,C)};VS.exports=T01});var PS=B0((gN1,wS)=>{wS.exports=["Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]});var TS=B0((bN1,_S)=>{var uO=PS(),k01=typeof globalThis==="undefined"?global:globalThis;_S.exports=function A(){var Q=[];for(var J=0;J{var ZE=MS(),S01=TS(),kS=aY(),dO=rY(),UE=AE(),j01=dO("Object.prototype.toString"),jS=sX()(),SS=typeof globalThis==="undefined"?global:globalThis,cO=S01(),lO=dO("String.prototype.slice"),mO=Object.getPrototypeOf,v01=dO("Array.prototype.indexOf",!0)||function A(Q,J){for(var K=0;K-1)return J;if(J!=="Object")return!1;return y01(Q)}if(!UE)return null;return x01(Q)}});var yS=B0((pN1,xS)=>{var h01=nO();xS.exports=function A(Q){return!!h01(Q)}});var aS=B0((iS)=>{var g01=IS(),b01=NS(),Y5=nO(),hS=yS();function HK(A){return A.call.bind(A)}var gS=typeof BigInt!=="undefined",bS=typeof Symbol!=="undefined",M9=HK(Object.prototype.toString),f01=HK(Number.prototype.valueOf),p01=HK(String.prototype.valueOf),u01=HK(Boolean.prototype.valueOf);if(gS)fS=HK(BigInt.prototype.valueOf);var fS;if(bS)pS=HK(Symbol.prototype.valueOf);var pS;function eY(A,Q){if(typeof A!=="object")return!1;try{return Q(A),!0}catch(J){return!1}}iS.isArgumentsObject=g01;iS.isGeneratorFunction=b01;iS.isTypedArray=hS;function m01(A){return typeof Promise!=="undefined"&&A instanceof Promise||A!==null&&typeof A==="object"&&typeof A.then==="function"&&typeof A.catch==="function"}iS.isPromise=m01;function c01(A){if(typeof ArrayBuffer!=="undefined"&&ArrayBuffer.isView)return ArrayBuffer.isView(A);return hS(A)||mS(A)}iS.isArrayBufferView=c01;function d01(A){return Y5(A)==="Uint8Array"}iS.isUint8Array=d01;function l01(A){return Y5(A)==="Uint8ClampedArray"}iS.isUint8ClampedArray=l01;function n01(A){return Y5(A)==="Uint16Array"}iS.isUint16Array=n01;function s01(A){return Y5(A)==="Uint32Array"}iS.isUint32Array=s01;function o01(A){return Y5(A)==="Int8Array"}iS.isInt8Array=o01;function i01(A){return Y5(A)==="Int16Array"}iS.isInt16Array=i01;function a01(A){return Y5(A)==="Int32Array"}iS.isInt32Array=a01;function r01(A){return Y5(A)==="Float32Array"}iS.isFloat32Array=r01;function t01(A){return Y5(A)==="Float64Array"}iS.isFloat64Array=t01;function e01(A){return Y5(A)==="BigInt64Array"}iS.isBigInt64Array=e01;function AA1(A){return Y5(A)==="BigUint64Array"}iS.isBigUint64Array=AA1;function XE(A){return M9(A)==="[object Map]"}XE.working=typeof Map!=="undefined"&&XE(/*@__PURE__*/new Map);function QA1(A){if(typeof Map==="undefined")return!1;return XE.working?XE(A):A instanceof Map}iS.isMap=QA1;function EE(A){return M9(A)==="[object Set]"}EE.working=typeof Set!=="undefined"&&EE(/*@__PURE__*/new Set);function JA1(A){if(typeof Set==="undefined")return!1;return EE.working?EE(A):A instanceof Set}iS.isSet=JA1;function $E(A){return M9(A)==="[object WeakMap]"}$E.working=typeof WeakMap!=="undefined"&&$E(/*@__PURE__*/new WeakMap);function KA1(A){if(typeof WeakMap==="undefined")return!1;return $E.working?$E(A):A instanceof WeakMap}iS.isWeakMap=KA1;function oO(A){return M9(A)==="[object WeakSet]"}oO.working=typeof WeakSet!=="undefined"&&oO(/*@__PURE__*/new WeakSet);function CA1(A){return oO(A)}iS.isWeakSet=CA1;function HE(A){return M9(A)==="[object ArrayBuffer]"}HE.working=typeof ArrayBuffer!=="undefined"&&HE(new ArrayBuffer);function uS(A){if(typeof ArrayBuffer==="undefined")return!1;return HE.working?HE(A):A instanceof ArrayBuffer}iS.isArrayBuffer=uS;function GE(A){return M9(A)==="[object DataView]"}GE.working=typeof ArrayBuffer!=="undefined"&&typeof DataView!=="undefined"&&GE(new DataView(new ArrayBuffer(1),0,1));function mS(A){if(typeof DataView==="undefined")return!1;return GE.working?GE(A):A instanceof DataView}iS.isDataView=mS;var sO=typeof SharedArrayBuffer!=="undefined"?SharedArrayBuffer:void 0;function tY(A){return M9(A)==="[object SharedArrayBuffer]"}function cS(A){if(typeof sO==="undefined")return!1;if(typeof tY.working==="undefined")tY.working=tY(new sO);return tY.working?tY(A):A instanceof sO}iS.isSharedArrayBuffer=cS;function YA1(A){return M9(A)==="[object AsyncFunction]"}iS.isAsyncFunction=YA1;function UA1(A){return M9(A)==="[object Map Iterator]"}iS.isMapIterator=UA1;function ZA1(A){return M9(A)==="[object Set Iterator]"}iS.isSetIterator=ZA1;function BA1(A){return M9(A)==="[object Generator]"}iS.isGeneratorObject=BA1;function XA1(A){return M9(A)==="[object WebAssembly.Module]"}iS.isWebAssemblyCompiledModule=XA1;function dS(A){return eY(A,f01)}iS.isNumberObject=dS;function lS(A){return eY(A,p01)}iS.isStringObject=lS;function nS(A){return eY(A,u01)}iS.isBooleanObject=nS;function sS(A){return gS&&eY(A,fS)}iS.isBigIntObject=sS;function oS(A){return bS&&eY(A,pS)}iS.isSymbolObject=oS;function EA1(A){return dS(A)||lS(A)||nS(A)||sS(A)||oS(A)}iS.isBoxedPrimitive=EA1;function $A1(A){return typeof Uint8Array!=="undefined"&&(uS(A)||cS(A))}iS.isAnyArrayBuffer=$A1;["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(A){Object.defineProperty(iS,A,{enumerable:!1,value:function(){throw new Error(A+" is not supported in userland")}})})});var tS=B0((mN1,rS)=>{rS.exports=function A(Q){return Q&&typeof Q==="object"&&typeof Q.copy==="function"&&typeof Q.fill==="function"&&typeof Q.readUInt8==="function"}});var eS=B0((cN1,iO)=>{if(typeof Object.create==="function")iO.exports=function A(Q,J){if(J)Q.super_=J,Q.prototype=Object.create(J.prototype,{constructor:{value:Q,enumerable:!1,writable:!0,configurable:!0}})};else iO.exports=function A(Q,J){if(J){Q.super_=J;var K=function(){};K.prototype=J.prototype,Q.prototype=new K,Q.prototype.constructor=Q}}});var WK=B0((QN)=>{var Qj=Object.getOwnPropertyDescriptors||function A(Q){var J=Object.keys(Q),K={};for(var C=0;C=C)return Z;switch(Z){case"%s":return String(K[J++]);case"%d":return Number(K[J++]);case"%j":try{return JSON.stringify(K[J++])}catch(X){return"[Circular]"}default:return Z}});for(var Y=K[J];J=3)J.depth=arguments[2];if(arguments.length>=4)J.colors=arguments[3];if(eO(Q))J.showHidden=Q;else if(Q)QN._extend(J,Q);if(JQ(J.showHidden))J.showHidden=!1;if(JQ(J.depth))J.depth=2;if(JQ(J.colors))J.colors=!1;if(JQ(J.customInspect))J.customInspect=!0;if(J.colors)J.stylize=oA1;return OE(J,A,J.depth)}QN.inspect=n7;n7.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};n7.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function oA1(A,Q){var J=n7.styles[Q];if(J)return"\x1B["+n7.colors[J][0]+"m"+A+"\x1B["+n7.colors[J][1]+"m";else return A}function iA1(A,Q){return A}function aA1(A){var Q={};return A.forEach(function(J,K){Q[J]=!0}),Q}function OE(A,Q,J){if(A.customInspect&&Q&&qE(Q.inspect)&&Q.inspect!==QN.inspect&&!(Q.constructor&&Q.constructor.prototype===Q)){var K=Q.inspect(J,A);if(!FE(K))K=OE(A,K,J);return K}var C=rA1(A,Q);if(C)return C;var U=Object.keys(Q),Y=aA1(U);if(A.showHidden)U=Object.getOwnPropertyNames(Q);if(QU(Q)&&(U.indexOf("message")>=0||U.indexOf("description")>=0))return aO(Q);if(U.length===0){if(qE(Q)){var Z=Q.name?": "+Q.name:"";return A.stylize("[Function"+Z+"]","special")}if(AU(Q))return A.stylize(RegExp.prototype.toString.call(Q),"regexp");if(NE(Q))return A.stylize(Date.prototype.toString.call(Q),"date");if(QU(Q))return aO(Q)}var X="",E=!1,H=["{","}"];if(Kj(Q))E=!0,H=["[","]"];if(qE(Q)){var $=Q.name?": "+Q.name:"";X=" [Function"+$+"]"}if(AU(Q))X=" "+RegExp.prototype.toString.call(Q);if(NE(Q))X=" "+Date.prototype.toUTCString.call(Q);if(QU(Q))X=" "+aO(Q);if(U.length===0&&(!E||Q.length==0))return H[0]+X+H[1];if(J<0)if(AU(Q))return A.stylize(RegExp.prototype.toString.call(Q),"regexp");else return A.stylize("[Object]","special");A.seen.push(Q);var I;if(E)I=tA1(A,Q,J,Y,U);else I=U.map(function(N){return tO(A,Q,J,Y,N,E)});return A.seen.pop(),eA1(I,X,H)}function rA1(A,Q){if(JQ(Q))return A.stylize("undefined","undefined");if(FE(Q)){var J="'"+JSON.stringify(Q).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return A.stylize(J,"string")}if(Cj(Q))return A.stylize(""+Q,"number");if(eO(Q))return A.stylize(""+Q,"boolean");if(LE(Q))return A.stylize("null","null")}function aO(A){return"["+Error.prototype.toString.call(A)+"]"}function tA1(A,Q,J,K,C){var U=[];for(var Y=0,Z=Q.length;Y-1)if(U)Z=Z.split(` -`).map(function(E){return" "+E}).join(` -`).slice(2);else Z=` -`+Z.split(` -`).map(function(E){return" "+E}).join(` -`)}else Z=A.stylize("[Circular]","special");if(JQ(Y)){if(U&&C.match(/^\d+$/))return Z;if(Y=JSON.stringify(""+C),Y.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/))Y=Y.slice(1,-1),Y=A.stylize(Y,"name");else Y=Y.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),Y=A.stylize(Y,"string")}return Y+": "+Z}function eA1(A,Q,J){var K=0,C=A.reduce(function(U,Y){if(K++,Y.indexOf(` -`)>=0)K++;return U+Y.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(C>60)return J[0]+(Q===""?"":Q+` - `)+" "+A.join(`, - `)+" "+J[1];return J[0]+Q+" "+A.join(", ")+" "+J[1]}QN.types=aS();function Kj(A){return Array.isArray(A)}QN.isArray=Kj;function eO(A){return typeof A==="boolean"}QN.isBoolean=eO;function LE(A){return A===null}QN.isNull=LE;function A21(A){return A==null}QN.isNullOrUndefined=A21;function Cj(A){return typeof A==="number"}QN.isNumber=Cj;function FE(A){return typeof A==="string"}QN.isString=FE;function Q21(A){return typeof A==="symbol"}QN.isSymbol=Q21;function JQ(A){return A===void 0}QN.isUndefined=JQ;function AU(A){return GK(A)&&AN(A)==="[object RegExp]"}QN.isRegExp=AU;QN.types.isRegExp=AU;function GK(A){return typeof A==="object"&&A!==null}QN.isObject=GK;function NE(A){return GK(A)&&AN(A)==="[object Date]"}QN.isDate=NE;QN.types.isDate=NE;function QU(A){return GK(A)&&(AN(A)==="[object Error]"||A instanceof Error)}QN.isError=QU;QN.types.isNativeError=QU;function qE(A){return typeof A==="function"}QN.isFunction=qE;function J21(A){return A===null||typeof A==="boolean"||typeof A==="number"||typeof A==="string"||typeof A==="symbol"||typeof A==="undefined"}QN.isPrimitive=J21;QN.isBuffer=tS();function AN(A){return Object.prototype.toString.call(A)}function rO(A){return A<10?"0"+A.toString(10):A.toString(10)}var K21=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function C21(){var A=/*@__PURE__*/new Date,Q=[rO(A.getHours()),rO(A.getMinutes()),rO(A.getSeconds())].join(":");return[A.getDate(),K21[A.getMonth()],Q].join(" ")}QN.log=function(){console.log("%s - %s",C21(),QN.format.apply(QN,arguments))};QN.inherits=eS();QN._extend=function(A,Q){if(!Q||!GK(Q))return A;var J=Object.keys(Q),K=J.length;while(K--)A[J[K]]=Q[J[K]];return A};function Yj(A,Q){return Object.prototype.hasOwnProperty.call(A,Q)}var QQ=typeof Symbol!=="undefined"?Symbol("util.promisify.custom"):void 0;QN.promisify=function A(Q){if(typeof Q!=="function")throw new TypeError('The "original" argument must be of type Function');if(QQ&&Q[QQ]){var J=Q[QQ];if(typeof J!=="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(J,QQ,{value:J,enumerable:!1,writable:!1,configurable:!0}),J}function J(){var K,C,U=new Promise(function(X,E){K=X,C=E}),Y=[];for(var Z=0;Z{function s7(A){return s7=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Q){return typeof Q}:function(Q){return Q&&typeof Symbol=="function"&&Q.constructor===Symbol&&Q!==Symbol.prototype?"symbol":typeof Q},s7(A)}function Bj(A,Q){for(var J=0;J2)return"one of ".concat(Q," ").concat(A.slice(0,J-1).join(", "),", or ")+A[J-1];else if(J===2)return"one of ".concat(Q," ").concat(A[0]," or ").concat(A[1]);else return"of ".concat(Q," ").concat(A[0])}else return"of ".concat(Q," ").concat(String(A))}function h21(A,Q,J){return A.substr(!J||J<0?0:+J,Q.length)===Q}function g21(A,Q,J){if(J===void 0||J>A.length)J=A.length;return A.substring(J-Q.length,J)===Q}function b21(A,Q,J){if(typeof J!=="number")J=0;if(J+Q.length>A.length)return!1;else return A.indexOf(Q,J)!==-1}JU("ERR_AMBIGUOUS_ARGUMENT",'The "%s" argument is ambiguous. %s',TypeError);JU("ERR_INVALID_ARG_TYPE",function(A,Q,J){if(IK===void 0)IK=DE();IK(typeof A==="string","'name' must be a string");var K;if(typeof Q==="string"&&h21(Q,"not "))K="must not be",Q=Q.replace(/^not /,"");else K="must be";var C;if(g21(A," argument"))C="The ".concat(A," ").concat(K," ").concat(Xj(Q,"type"));else{var U=b21(A,".")?"property":"argument";C='The "'.concat(A,'" ').concat(U," ").concat(K," ").concat(Xj(Q,"type"))}return C+=". Received type ".concat(s7(J)),C},TypeError);JU("ERR_INVALID_ARG_VALUE",function(A,Q){var J=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"is invalid";if(KN===void 0)KN=WK();var K=KN.inspect(Q);if(K.length>128)K="".concat(K.slice(0,128),"...");return"The argument '".concat(A,"' ").concat(J,". Received ").concat(K)},TypeError,RangeError);JU("ERR_INVALID_RETURN_VALUE",function(A,Q,J){var K;if(J&&J.constructor&&J.constructor.name)K="instance of ".concat(J.constructor.name);else K="type ".concat(s7(J));return"Expected ".concat(A,' to be returned from the "').concat(Q,'"')+" function but got ".concat(K,".")},TypeError);JU("ERR_MISSING_ARGS",function(){for(var A=arguments.length,Q=new Array(A),J=0;J0,"At least one arg needs to be specified");var K="The ",C=Q.length;switch(Q=Q.map(function(U){return'"'.concat(U,'"')}),C){case 1:K+="".concat(Q[0]," argument");break;case 2:K+="".concat(Q[0]," and ").concat(Q[1]," arguments");break;default:K+=Q.slice(0,C-1).join(", "),K+=", and ".concat(Q[C-1]," arguments");break}return"".concat(K," must be specified")},TypeError);f21.codes=Ej});var Rj=B0((lN1,Fj)=>{function Hj(A,Q){var J=Object.keys(A);if(Object.getOwnPropertySymbols){var K=Object.getOwnPropertySymbols(A);Q&&(K=K.filter(function(C){return Object.getOwnPropertyDescriptor(A,C).enumerable})),J.push.apply(J,K)}return J}function Gj(A){for(var Q=1;QA.length)J=A.length;return A.substring(J-Q.length,J)===Q}function r21(A,Q){if(Q=Math.floor(Q),A.length==0||Q==0)return"";var J=A.length*Q;Q=Math.floor(Math.log(Q)/Math.log(2));while(Q)A+=A,Q--;return A+=A.substring(0,J-A.length),A}var U5="",KU="",CU="",d8="",KQ={deepStrictEqual:"Expected values to be strictly deep-equal:",strictEqual:"Expected values to be strictly equal:",strictEqualObject:'Expected "actual" to be reference-equal to "expected":',deepEqual:"Expected values to be loosely deep-equal:",equal:"Expected values to be loosely equal:",notDeepStrictEqual:'Expected "actual" not to be strictly deep-equal to:',notStrictEqual:'Expected "actual" to be strictly unequal to:',notStrictEqualObject:'Expected "actual" not to be reference-equal to "expected":',notDeepEqual:'Expected "actual" not to be loosely deep-equal to:',notEqual:'Expected "actual" to be loosely unequal to:',notIdentical:"Values identical but not reference-equal:"},t21=10;function qj(A){var Q=Object.keys(A),J=Object.create(Object.getPrototypeOf(A));return Q.forEach(function(K){J[K]=A[K]}),Object.defineProperty(J,"message",{value:A.message}),J}function YU(A){return BN(A,{compact:!1,customInspect:!1,depth:1000,maxArrayLength:1/0,showHidden:!1,breakLength:1/0,showProxy:!1,sorted:!0,getters:!0})}function e21(A,Q,J){var K="",C="",U=0,Y="",Z=!1,X=YU(A),E=X.split(` -`),H=YU(Q).split(` -`),$=0,I="";if(J==="strictEqual"&&j6(A)==="object"&&j6(Q)==="object"&&A!==null&&Q!==null)J="strictEqualObject";if(E.length===1&&H.length===1&&E[0]!==H[0]){var N=E[0].length+H[0].length;if(N<=t21){if((j6(A)!=="object"||A===null)&&(j6(Q)!=="object"||Q===null)&&(A!==0||Q!==0))return"".concat(KQ[J],` - -`)+"".concat(E[0]," !== ").concat(H[0],` -`)}else if(J!=="strictEqualObject"){var F=process.stderr&&process.stderr.isTTY?process.stderr.columns:80;if(N2)I=` - `.concat(r21(" ",$),"^"),$=0}}}var V=E[E.length-1],D=H[H.length-1];while(V===D){if($++<2)Y=` - `.concat(V).concat(Y);else K=V;if(E.pop(),H.pop(),E.length===0||H.length===0)break;V=E[E.length-1],D=H[H.length-1]}var L=Math.max(E.length,H.length);if(L===0){var R=X.split(` -`);if(R.length>30){R[26]="".concat(U5,"...").concat(d8);while(R.length>27)R.pop()}return"".concat(KQ.notIdentical,` - -`).concat(R.join(` -`),` -`)}if($>3)Y=` -`.concat(U5,"...").concat(d8).concat(Y),Z=!0;if(K!=="")Y=` - `.concat(K).concat(Y),K="";var M=0,T=KQ[J]+` -`.concat(KU,"+ actual").concat(d8," ").concat(CU,"- expected").concat(d8),h=" ".concat(U5,"...").concat(d8," Lines skipped");for($=0;$1&&$>2){if(y>4)C+=` -`.concat(U5,"...").concat(d8),Z=!0;else if(y>3)C+=` - `.concat(H[$-2]),M++;C+=` - `.concat(H[$-1]),M++}U=$,K+=` -`.concat(CU,"-").concat(d8," ").concat(H[$]),M++}else if(H.length<$+1){if(y>1&&$>2){if(y>4)C+=` -`.concat(U5,"...").concat(d8),Z=!0;else if(y>3)C+=` - `.concat(E[$-2]),M++;C+=` - `.concat(E[$-1]),M++}U=$,C+=` -`.concat(KU,"+").concat(d8," ").concat(E[$]),M++}else{var g=H[$],f=E[$],u=f!==g&&(!Ij(f,",")||f.slice(0,-1)!==g);if(u&&Ij(g,",")&&g.slice(0,-1)===f)u=!1,f+=",";if(u){if(y>1&&$>2){if(y>4)C+=` -`.concat(U5,"...").concat(d8),Z=!0;else if(y>3)C+=` - `.concat(E[$-2]),M++;C+=` - `.concat(E[$-1]),M++}U=$,C+=` -`.concat(KU,"+").concat(d8," ").concat(f),K+=` -`.concat(CU,"-").concat(d8," ").concat(g),M+=2}else if(C+=K,K="",y===1||$===0)C+=` - `.concat(f),M++}if(M>20&&$30){N[26]="".concat(U5,"...").concat(d8);while(N.length>27)N.pop()}if(N.length===1)U=J.call(this,"".concat(I," ").concat(N[0]));else U=J.call(this,"".concat(I,` - -`).concat(N.join(` -`),` -`))}else{var F=YU(E),V="",D=KQ[Z];if(Z==="notDeepEqual"||Z==="notEqual"){if(F="".concat(KQ[Z],` - -`).concat(F),F.length>1024)F="".concat(F.slice(0,1021),"...")}else{if(V="".concat(YU(H)),F.length>512)F="".concat(F.slice(0,509),"...");if(V.length>512)V="".concat(V.slice(0,509),"...");if(Z==="deepEqual"||Z==="equal")F="".concat(D,` - -`).concat(F,` - -should equal - -`);else V=" ".concat(Z," ").concat(V)}U=J.call(this,"".concat(F).concat(V))}}if(Error.stackTraceLimit=$,U.generatedMessage=!Y,Object.defineProperty(UN(U),"name",{value:"AssertionError [ERR_ASSERTION]",enumerable:!1,writable:!0,configurable:!0}),U.code="ERR_ASSERTION",U.actual=E,U.expected=H,U.operator=Z,Error.captureStackTrace)Error.captureStackTrace(UN(U),X);return U.stack,U.name="AssertionError",Nj(U)}return c21(K,[{key:"toString",value:function C(){return"".concat(this.name," [").concat(this.code,"]: ").concat(this.message)}},{key:Q,value:function C(U,Y){return BN(this,Gj(Gj({},Y),{},{customInspect:!1,depth:0}))}}]),K}(/*@__PURE__*/ZN(Error),BN.custom);Fj.exports=A81});var XN=B0((nN1,Dj)=>{var zj=Object.prototype.toString;Dj.exports=function A(Q){var J=zj.call(Q),K=J==="[object Arguments]";if(!K)K=J!=="[object Array]"&&Q!==null&&typeof Q==="object"&&typeof Q.length==="number"&&Q.length>=0&&zj.call(Q.callee)==="[object Function]";return K}});var jj=B0((sN1,Sj)=>{var kj;if(!Object.keys)BU=Object.prototype.hasOwnProperty,EN=Object.prototype.toString,Vj=XN(),$N=Object.prototype.propertyIsEnumerable,Mj=!$N.call({toString:null},"toString"),wj=$N.call(function(){},"prototype"),XU=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],ME=function(A){var Q=A.constructor;return Q&&Q.prototype===A},Pj={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},_j=function(){if(typeof window==="undefined")return!1;for(var A in window)try{if(!Pj["$"+A]&&BU.call(window,A)&&window[A]!==null&&typeof window[A]==="object")try{ME(window[A])}catch(Q){return!0}}catch(Q){return!0}return!1}(),Tj=function(A){if(typeof window==="undefined"||!_j)return ME(A);try{return ME(A)}catch(Q){return!1}},kj=function A(Q){var J=Q!==null&&typeof Q==="object",K=EN.call(Q)==="[object Function]",C=Vj(Q),U=J&&EN.call(Q)==="[object String]",Y=[];if(!J&&!K&&!C)throw new TypeError("Object.keys called on a non-object");var Z=wj&&K;if(U&&Q.length>0&&!BU.call(Q,0))for(var X=0;X0)for(var E=0;E{var Q81=Array.prototype.slice,J81=XN(),vj=Object.keys,wE=vj?function A(Q){return vj(Q)}:jj(),xj=Object.keys;wE.shim=function A(){if(Object.keys){var Q=function(){var J=Object.keys(arguments);return J&&J.length===arguments.length}(1,2);if(!Q)Object.keys=function J(K){if(J81(K))return xj(Q81.call(K));return xj(K)}}else Object.keys=wE;return Object.keys||wE};yj.exports=wE});var uj=B0((iN1,pj)=>{var K81=HN(),bj=nX()(),fj=rY(),hj=Object,C81=fj("Array.prototype.push"),gj=fj("Object.prototype.propertyIsEnumerable"),Y81=bj?Object.getOwnPropertySymbols:null;pj.exports=function A(Q,J){if(Q==null)throw new TypeError("target must be an object");var K=hj(Q);if(arguments.length===1)return K;for(var C=1;C{var GN=uj(),U81=function(){if(!Object.assign)return!1;var A="abcdefghijklmnopqrst",Q=A.split(""),J={};for(var K=0;K{var dj=function(A){return A!==A};lj.exports=function A(Q,J){if(Q===0&&J===0)return 1/Q===1/J;if(Q===J)return!0;if(dj(Q)&&dj(J))return!0;return!1}});var PE=B0((tN1,nj)=>{var B81=WN();nj.exports=function A(){return typeof Object.is==="function"?Object.is:B81}});var EU=B0((eN1,aj)=>{var X81=HN(),E81=typeof Symbol==="function"&&typeof Symbol("foo")==="symbol",$81=Object.prototype.toString,H81=Array.prototype.concat,sj=kO(),G81=function(A){return typeof A==="function"&&$81.call(A)==="[object Function]"},oj=jO()(),W81=function(A,Q,J,K){if(Q in A){if(K===!0){if(A[Q]===J)return}else if(!G81(K)||!K())return}if(oj)sj(A,Q,J,!0);else sj(A,Q,J)},ij=function(A,Q){var J=arguments.length>2?arguments[2]:{},K=X81(Q);if(E81)K=H81.call(K,Object.getOwnPropertySymbols(Q));for(var C=0;C{var I81=PE(),q81=EU();rj.exports=function A(){var Q=I81();return q81(Object,{is:Q},{is:function J(){return Object.is!==Q}}),Q}});var Jv=B0((QL1,Qv)=>{var O81=EU(),N81=aY(),L81=WN(),ej=PE(),F81=tj(),Av=N81(ej(),Object);O81(Av,{getPolyfill:ej,implementation:L81,shim:F81});Qv.exports=Av});var IN=B0((JL1,Kv)=>{Kv.exports=function A(Q){return Q!==Q}});var qN=B0((KL1,Cv)=>{var R81=IN();Cv.exports=function A(){if(Number.isNaN&&Number.isNaN(NaN)&&!Number.isNaN("a"))return Number.isNaN;return R81}});var Uv=B0((CL1,Yv)=>{var z81=EU(),D81=qN();Yv.exports=function A(){var Q=D81();return z81(Number,{isNaN:Q},{isNaN:function J(){return Number.isNaN!==Q}}),Q}});var Ev=B0((YL1,Xv)=>{var V81=aY(),M81=EU(),w81=IN(),Zv=qN(),P81=Uv(),Bv=V81(Zv(),Number);M81(Bv,{getPolyfill:Zv,implementation:w81,shim:P81});Xv.exports=Bv});var kv=B0((UL1,Tv)=>{function $v(A,Q){return S81(A)||k81(A,Q)||T81(A,Q)||_81()}function _81(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function T81(A,Q){if(!A)return;if(typeof A==="string")return Hv(A,Q);var J=Object.prototype.toString.call(A).slice(8,-1);if(J==="Object"&&A.constructor)J=A.constructor.name;if(J==="Map"||J==="Set")return Array.from(A);if(J==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(J))return Hv(A,Q)}function Hv(A,Q){if(Q==null||Q>A.length)Q=A.length;for(var J=0,K=new Array(Q);J10)return!0;for(var Q=0;Q57)return!0}return A.length===10&&A>=Math.pow(2,32)}function kE(A){return Object.keys(A).filter(p81).concat(jE(A).filter(Object.prototype.propertyIsEnumerable.bind(A)))}/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */function Mv(A,Q){if(A===Q)return 0;var J=A.length,K=Q.length;for(var C=0,U=Math.min(J,K);C{function Z5(A){return Z5=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Q){return typeof Q}:function(Q){return Q&&typeof Symbol=="function"&&Q.constructor===Symbol&&Q!==Symbol.prototype?"symbol":typeof Q},Z5(A)}function Sv(A,Q){for(var J=0;J1?J-1:0),C=1;C1?J-1:0),C=1;C1?J-1:0),C=1;C1?J-1:0),C=1;C{(function(A,Q,J){typeof define=="function"&&define.amd?define([],J):typeof cE=="object"&&cE.exports?cE.exports=J():A.QRCode=J()})(Bx,0,function(){for(var A=[null,[[10,7,17,13],[1,1,1,1],[]],[[16,10,28,22],[1,1,1,1],[4,16]],[[26,15,22,18],[1,1,2,2],[4,20]],[[18,20,16,26],[2,1,4,2],[4,24]],[[24,26,22,18],[2,1,4,4],[4,28]],[[16,18,28,24],[4,2,4,4],[4,32]],[[18,20,26,18],[4,2,5,6],[4,20,36]],[[22,24,26,22],[4,2,6,6],[4,22,40]],[[22,30,24,20],[5,2,8,8],[4,24,44]],[[26,18,28,24],[5,4,8,8],[4,26,48]],[[30,20,24,28],[5,4,11,8],[4,28,52]],[[22,24,28,26],[8,4,11,10],[4,30,56]],[[22,26,22,24],[9,4,16,12],[4,32,60]],[[24,30,24,20],[9,4,16,16],[4,24,44,64]],[[24,22,24,30],[10,6,18,12],[4,24,46,68]],[[28,24,30,24],[10,6,16,17],[4,24,48,72]],[[28,28,28,28],[11,6,19,16],[4,28,52,76]],[[26,30,28,28],[13,6,21,18],[4,28,54,80]],[[26,28,26,26],[14,7,25,21],[4,28,56,84]],[[26,28,28,30],[16,8,25,20],[4,32,60,88]],[[26,28,30,28],[17,8,25,23],[4,26,48,70,92]],[[28,28,24,30],[17,9,34,23],[4,24,48,72,96]],[[28,30,30,30],[18,9,30,25],[4,28,52,76,100]],[[28,30,30,30],[20,10,32,27],[4,26,52,78,104]],[[28,26,30,30],[21,12,35,29],[4,30,56,82,108]],[[28,28,30,28],[23,12,37,34],[4,28,56,84,112]],[[28,30,30,30],[25,12,40,34],[4,32,60,88,116]],[[28,30,30,30],[26,13,42,35],[4,24,48,72,96,120]],[[28,30,30,30],[28,14,45,38],[4,28,52,76,100,124]],[[28,30,30,30],[29,15,48,40],[4,24,50,76,102,128]],[[28,30,30,30],[31,16,51,43],[4,28,54,80,106,132]],[[28,30,30,30],[33,17,54,45],[4,32,58,84,110,136]],[[28,30,30,30],[35,18,57,48],[4,28,56,84,112,140]],[[28,30,30,30],[37,19,60,51],[4,32,60,88,116,144]],[[28,30,30,30],[38,19,63,53],[4,28,52,76,100,124,148]],[[28,30,30,30],[40,20,66,56],[4,22,48,74,100,126,152]],[[28,30,30,30],[43,21,70,59],[4,26,52,78,104,130,156]],[[28,30,30,30],[45,22,74,62],[4,30,56,82,108,134,160]],[[28,30,30,30],[47,24,77,65],[4,24,52,80,108,136,164]],[[28,30,30,30],[49,25,81,68],[4,28,56,84,112,140,168]]],Q=/^\d*$/,J=/^[A-Za-z0-9 $%*+\-./:]*$/,K=/^[A-Z0-9 $%*+\-./:]*$/,C=[],U=[-1],Y=0,Z=1;Y<255;++Y)C.push(Z),U[Z]=Y,Z=2*Z^(Z>=128?285:0);var X=[[]];for(Y=0;Y<30;++Y){for(var E=X[Y],H=[],$=0;$<=Y;++$){var I=$6},L=function(n,B){var q=-8&function(O){var w=A[O],k=16*O*O+128*O+64;return D(O)&&(k-=36),w[2].length&&(k-=25*w[2].length*w[2].length-10*w[2].length-55),k}(n),P=A[n];return q-=8*P[0][B]*P[1][B]},R=function(n,B){switch(B){case 1:return n<10?10:n<27?12:14;case 2:return n<10?9:n<27?11:13;case 4:return n<10?8:16;case 8:return n<10?8:n<27?10:12}},M=function(n,B,q){var P=L(n,q)-4-R(n,B);switch(B){case 1:return 3*(P/10|0)+(P%10<4?0:P%10<7?1:2);case 2:return 2*(P/11|0)+(P%11<6?0:1);case 4:return P/8|0;case 8:return P/13|0}},T=function(n,B){for(var q=n.slice(0),P=n.length,O=B.length,w=0;w=0)for(var S=0;S=0;--w)O>>P+w&1&&(O^=q<>k&1}return n},f=function(n){for(var B=function(p){for(var s=0,r=0;r=5&&(s+=p[r]-5+3);for(r=5;r=4*A1||p[r+1]>=4*A1)&&(s+=40)}return s},q=n.length,P=0,O=0,w=0;w=U1){for(e.push(t|c>>(o-=U1));o>=8;)e.push(c>>(o-=8)&255);t=0,U1=8}o>0&&(t|=(c&(1<>3);k=function(s,r,A1){for(var Q1=[],e=s.length/r|0,t=0,U1=r-s.length%r,O1=0;O1>k1&1,e[C1+B1][q1+k1]=1};for(U1(0,0,9,9,[127,65,93,93,93,65,383,0,64]),U1(A1-8,0,8,9,[256,127,65,93,93,93,65,127]),U1(0,A1-8,9,8,[254,130,186,186,186,130,254,0,0]),t=9;t>o++&1,e[t][A1-11+i]=e[A1-11+i][t]=1}return{matrix:Q1,reserved:e}}(B),_=S.matrix,W=S.reserved;if(function(s,r,A1){for(var Q1=s.length,e=0,t=-1,U1=Q1-1;U1>=0;U1-=2){U1==6&&--U1;for(var O1=t<0?Q1-1:0,E1=0;E1U1-2;--Y1)r[O1][Y1]||(s[O1][Y1]=A1[e>>3]>>(7&~e)&1,++e);O1+=t}t=-t}}(_,W,k),O<0){y(_,W,0),g(_,0,P,0);var j=0,b=f(_);for(y(_,W,0),O=1;O<8;++O){y(_,W,O),g(_,0,P,O);var p=f(_);b>p&&(b=p,j=O),y(_,W,O)}O=j}return y(_,W,O),g(_,0,P,O),_},d={generate:function(n,B){var q={numeric:1,alphanumeric:2,octet:4},P={L:1,M:0,Q:3,H:2},O=(B=B||{}).version||-1,w=P[(B.ecclevel||"L").toUpperCase()],k=B.mode?q[B.mode.toLowerCase()]:-1,S="mask"in B?B.mask:-1;if(k<0)k=typeof n=="string"?n.match(Q)?1:n.match(K)?2:4:4;else if(k!=1&&k!=2&&k!=4)throw"invalid or unsupported mode";if(n=function(_,W){switch(_){case 1:return W.match(Q)?W:null;case 2:return W.match(J)?W.toUpperCase():null;case 4:if(typeof W=="string"){for(var j=[],b=0;b>6,128|63&p):p<65536?j.push(224|p>>12,128|p>>6&63,128|63&p):j.push(240|p>>18,128|p>>12&63,128|p>>6&63,128|63&p)}return j}return W}}(k,n),n===null)throw"invalid data format";if(w<0||w>3)throw"invalid ECC level";if(O<0){for(O=1;O<=40&&!(n.length<=M(O,k,w));++O);if(O>40)throw"too large data"}else if(O<1||O>40)throw"invalid version";if(S!=-1&&(S<0||S>8))throw"invalid mask";return u(n,O,k,w,S)},generateHTML:function(n,B){B=B||{};for(var q=d.generate(n,B),P=Math.max(B.modulesize||5,0.5),O=B.unit||"px",w=B.ratio||1,k=Math.max(B.margin!==null?B.margin:4,0),S=document.createElement("div"),_=q.length,W=[''],j=0;j<_;++j){W.push("");for(var b=0;b<_;++b){let p=O!=="px"?"width:"+P*w+O+"; height:"+P*w+O:"width:"+P+"px;height:"+P+"px";W.push('')}W.push("")}return S.className="qrcode",S.innerHTML=W.join("")+"
",S},generateSVG:function(n,B){B=B||{};var q=d.generate(n,B),P=q.length,O=Math.max(B.modulesize||5,0.5),w=Math.max(B.margin!==null?B.margin:4,0),k=O*(P+2*w),S=' class= "fg" width="'+O+'" height="'+O+'"/>',_=document.createElementNS("http://www.w3.org/2000/svg","svg");_.setAttribute("viewBox","0 0 "+k+" "+k),_.setAttribute("style","shape-rendering:crispEdges"),B.modulesize&&(_.setAttribute("width",k),_.setAttribute("height",k));for(var W=["",''],j=w*O,b=0;bCL,timingSafeEqual:()=>OU,scryptSync:()=>Q$,scrypt:()=>J$,randomUUID:()=>JL,getRandomValues:()=>QL,getCurves:()=>KL,default:()=>Vy,DEFAULT_ENCODING:()=>DK});function KL(){return G51}var j61,nE,v61,x61,y61,h61,PN=(A,Q)=>()=>(A&&(Q=A(A=0)),Q),l1=(A,Q)=>()=>(Q||A((Q={exports:{}}).exports,Q),Q.exports),sE=(A,Q)=>{for(var J in Q)nE(A,J,{get:Q[J],enumerable:!0})},dE=(A,Q,J,K)=>{if(Q&&typeof Q=="object"||typeof Q=="function")for(let C of x61(Q))!h61.call(A,C)&&C!==J&&nE(A,C,{get:()=>Q[C],enumerable:!(K=v61(Q,C))||K.enumerable});return A},_N=(A,Q,J)=>(dE(A,Q,"default"),J&&dE(J,Q,"default")),CQ=(A,Q,J)=>(J=A!=null?j61(y61(A)):{},dE(Q||!A||!A.__esModule?nE(J,"default",{value:A,enumerable:!0}):J,A)),_9=(A)=>dE(nE({},"__esModule",{value:!0}),A),g61,b61,A6,bA,VK,MA,YQ,Rx,oE,f61,zx,MK,Dx,Vx,Mx,RK,TN,IU,wN,lE,kN,p61,u61,wx,Px,m61,c61,d61,_x,SN,jN,wK,l61,n61,Tx,s61,kx,o61,vN,N8,b3,xN,v6,iE,Nx,p3,Sx,UQ,ZQ,BQ,i61,PK,yN,hN,a61,gN,jx,aE,vx,r61,f3,xx,yx,bN,t61,hx,e61,Lx,fN,gx,A91,t7,NU,Q91,bx,fx,px,J91,ux,mx,cx,dx,K91,lx,nx,T9,pN,sx,C91,Y91,U91,Z91,B91,LU,X91,E91,$91,H91,G91,ox,Fx,ix,uN,rE,W91,ax,rx,tE,I91,q91,mN,O91,N91,XQ,tx,L91,F91,cN,ex,Ay,R91,z91,D91,Qy,V91,Jy,_K,Ky,Cy,zK,dN,M91,w91,Yy,Uy,P91,_91,T91,lN,nN,k91,u3,Zy,k9,eE,S91,j91,v91,By,d5,FU,Xy,x91,Ey,y91,$y,h91,g91,b91,f91,sN,p91,oN,u91,m91,c91,d91,l91,n91,s91,iN,Hy,aN,rN,qU,tN,eN,Gy,o91,Wy,Iy,i91,qy,a91,r91,t91,Oy,e91,A51,Q51,J51,A$,Ny,K51,C51,Y51,U51,Z51,Ly,Fy,AL,Ry,B51,X51,E51,$51,zy,Dy,H51,DK="buffer",QL=(A)=>crypto.getRandomValues(A),JL=()=>crypto.randomUUID(),G51,OU,Q$,J$,CL,Vy;var wy=hJ(()=>{j61=Object.create,nE=Object.defineProperty,v61=Object.getOwnPropertyDescriptor,x61=Object.getOwnPropertyNames,y61=Object.getPrototypeOf,h61=Object.prototype.hasOwnProperty,g61=l1((A)=>{A.byteLength=X,A.toByteArray=H,A.fromByteArray=N;var Q=[],J=[],K=typeof Uint8Array<"u"?Uint8Array:Array,C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(U=0,Y=C.length;U0)throw new Error("Invalid string. Length must be a multiple of 4");var D=F.indexOf("=");D===-1&&(D=V);var L=D===V?0:4-D%4;return[D,L]}function X(F){var V=Z(F),D=V[0],L=V[1];return(D+L)*3/4-L}function E(F,V,D){return(V+D)*3/4-D}function H(F){var V,D=Z(F),L=D[0],R=D[1],M=new K(E(F,L,R)),T=0,h=R>0?L-4:L,y;for(y=0;y>16&255,M[T++]=V>>8&255,M[T++]=V&255;return R===2&&(V=J[F.charCodeAt(y)]<<2|J[F.charCodeAt(y+1)]>>4,M[T++]=V&255),R===1&&(V=J[F.charCodeAt(y)]<<10|J[F.charCodeAt(y+1)]<<4|J[F.charCodeAt(y+2)]>>2,M[T++]=V>>8&255,M[T++]=V&255),M}function $(F){return Q[F>>18&63]+Q[F>>12&63]+Q[F>>6&63]+Q[F&63]}function I(F,V,D){for(var L,R=[],M=V;Mh?h:T+M));return L===1?(V=F[D-1],R.push(Q[V>>2]+Q[V<<4&63]+"==")):L===2&&(V=(F[D-2]<<8)+F[D-1],R.push(Q[V>>10]+Q[V>>4&63]+Q[V<<2&63]+"=")),R.join("")}}),b61=l1((A)=>{A.read=function(Q,J,K,C,U){var Y,Z,X=U*8-C-1,E=(1<>1,$=-7,I=K?U-1:0,N=K?-1:1,F=Q[J+I];for(I+=N,Y=F&(1<<-$)-1,F>>=-$,$+=X;$>0;Y=Y*256+Q[J+I],I+=N,$-=8);for(Z=Y&(1<<-$)-1,Y>>=-$,$+=C;$>0;Z=Z*256+Q[J+I],I+=N,$-=8);if(Y===0)Y=1-H;else{if(Y===E)return Z?NaN:(F?-1:1)*(1/0);Z=Z+Math.pow(2,C),Y=Y-H}return(F?-1:1)*Z*Math.pow(2,Y-C)},A.write=function(Q,J,K,C,U,Y){var Z,X,E,H=Y*8-U-1,$=(1<>1,N=U===23?Math.pow(2,-24)-Math.pow(2,-77):0,F=C?0:Y-1,V=C?1:-1,D=J<0||J===0&&1/J<0?1:0;for(J=Math.abs(J),isNaN(J)||J===1/0?(X=isNaN(J)?1:0,Z=$):(Z=Math.floor(Math.log(J)/Math.LN2),J*(E=Math.pow(2,-Z))<1&&(Z--,E*=2),Z+I>=1?J+=N/E:J+=N*Math.pow(2,1-I),J*E>=2&&(Z++,E/=2),Z+I>=$?(X=0,Z=$):Z+I>=1?(X=(J*E-1)*Math.pow(2,U),Z=Z+I):(X=J*Math.pow(2,I-1)*Math.pow(2,U),Z=0));U>=8;Q[K+F]=X&255,F+=V,X/=256,U-=8);for(Z=Z<0;Q[K+F]=Z&255,F+=V,Z/=256,H-=8);Q[K+F-V]|=D*128}}),A6=l1((A)=>{var Q=g61(),J=b61(),K=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;A.Buffer=Z,A.SlowBuffer=R,A.INSPECT_MAX_BYTES=50;var C=2147483647;A.kMaxLength=C,Z.TYPED_ARRAY_SUPPORT=U(),!Z.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function U(){try{let G=new Uint8Array(1),z={foo:function(){return 42}};return Object.setPrototypeOf(z,Uint8Array.prototype),Object.setPrototypeOf(G,z),G.foo()===42}catch{return!1}}Object.defineProperty(Z.prototype,"parent",{enumerable:!0,get:function(){if(Z.isBuffer(this))return this.buffer}}),Object.defineProperty(Z.prototype,"offset",{enumerable:!0,get:function(){if(Z.isBuffer(this))return this.byteOffset}});function Y(G){if(G>C)throw new RangeError('The value "'+G+'" is invalid for option "size"');let z=new Uint8Array(G);return Object.setPrototypeOf(z,Z.prototype),z}function Z(G,z,x){if(typeof G=="number"){if(typeof z=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return $(G)}return X(G,z,x)}Z.poolSize=8192;function X(G,z,x){if(typeof G=="string")return I(G,z);if(ArrayBuffer.isView(G))return F(G);if(G==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof G);if(B1(G,ArrayBuffer)||G&&B1(G.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(B1(G,SharedArrayBuffer)||G&&B1(G.buffer,SharedArrayBuffer)))return V(G,z,x);if(typeof G=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let m=G.valueOf&&G.valueOf();if(m!=null&&m!==G)return Z.from(m,z,x);let l=D(G);if(l)return l;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof G[Symbol.toPrimitive]=="function")return Z.from(G[Symbol.toPrimitive]("string"),z,x);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof G)}Z.from=function(G,z,x){return X(G,z,x)},Object.setPrototypeOf(Z.prototype,Uint8Array.prototype),Object.setPrototypeOf(Z,Uint8Array);function E(G){if(typeof G!="number")throw new TypeError('"size" argument must be of type number');if(G<0)throw new RangeError('The value "'+G+'" is invalid for option "size"')}function H(G,z,x){return E(G),G<=0?Y(G):z!==void 0?typeof x=="string"?Y(G).fill(z,x):Y(G).fill(z):Y(G)}Z.alloc=function(G,z,x){return H(G,z,x)};function $(G){return E(G),Y(G<0?0:L(G)|0)}Z.allocUnsafe=function(G){return $(G)},Z.allocUnsafeSlow=function(G){return $(G)};function I(G,z){if((typeof z!="string"||z==="")&&(z="utf8"),!Z.isEncoding(z))throw new TypeError("Unknown encoding: "+z);let x=M(G,z)|0,m=Y(x),l=m.write(G,z);return l!==x&&(m=m.slice(0,l)),m}function N(G){let z=G.length<0?0:L(G.length)|0,x=Y(z);for(let m=0;m=C)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+C.toString(16)+" bytes");return G|0}function R(G){return+G!=G&&(G=0),Z.alloc(+G)}Z.isBuffer=function(G){return G!=null&&G._isBuffer===!0&&G!==Z.prototype},Z.compare=function(G,z){if(B1(G,Uint8Array)&&(G=Z.from(G,G.offset,G.byteLength)),B1(z,Uint8Array)&&(z=Z.from(z,z.offset,z.byteLength)),!Z.isBuffer(G)||!Z.isBuffer(z))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(G===z)return 0;let x=G.length,m=z.length;for(let l=0,a=Math.min(x,m);lm.length?(Z.isBuffer(a)||(a=Z.from(a)),a.copy(m,l)):Uint8Array.prototype.set.call(m,a,l);else if(Z.isBuffer(a))a.copy(m,l);else throw new TypeError('"list" argument must be an Array of Buffers');l+=a.length}return m};function M(G,z){if(Z.isBuffer(G))return G.length;if(ArrayBuffer.isView(G)||B1(G,ArrayBuffer))return G.byteLength;if(typeof G!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof G);let x=G.length,m=arguments.length>2&&arguments[2]===!0;if(!m&&x===0)return 0;let l=!1;for(;;)switch(z){case"ascii":case"latin1":case"binary":return x;case"utf8":case"utf-8":return C1(G).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x*2;case"hex":return x>>>1;case"base64":return j1(G).length;default:if(l)return m?-1:C1(G).length;z=(""+z).toLowerCase(),l=!0}}Z.byteLength=M;function T(G,z,x){let m=!1;if((z===void 0||z<0)&&(z=0),z>this.length||((x===void 0||x>this.length)&&(x=this.length),x<=0)||(x>>>=0,z>>>=0,x<=z))return"";for(G||(G="utf8");;)switch(G){case"hex":return _(this,z,x);case"utf8":case"utf-8":return P(this,z,x);case"ascii":return k(this,z,x);case"latin1":case"binary":return S(this,z,x);case"base64":return q(this,z,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,z,x);default:if(m)throw new TypeError("Unknown encoding: "+G);G=(G+"").toLowerCase(),m=!0}}Z.prototype._isBuffer=!0;function h(G,z,x){let m=G[z];G[z]=G[x],G[x]=m}Z.prototype.swap16=function(){let G=this.length;if(G%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let z=0;zz&&(G+=" ... "),""},K&&(Z.prototype[K]=Z.prototype.inspect),Z.prototype.compare=function(G,z,x,m,l){if(B1(G,Uint8Array)&&(G=Z.from(G,G.offset,G.byteLength)),!Z.isBuffer(G))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof G);if(z===void 0&&(z=0),x===void 0&&(x=G?G.length:0),m===void 0&&(m=0),l===void 0&&(l=this.length),z<0||x>G.length||m<0||l>this.length)throw new RangeError("out of range index");if(m>=l&&z>=x)return 0;if(m>=l)return-1;if(z>=x)return 1;if(z>>>=0,x>>>=0,m>>>=0,l>>>=0,this===G)return 0;let a=l-m,K1=x-z,F1=Math.min(a,K1),R1=this.slice(m,l),X1=G.slice(z,x);for(let W1=0;W12147483647?x=2147483647:x<-2147483648&&(x=-2147483648),x=+x,k1(x)&&(x=l?0:G.length-1),x<0&&(x=G.length+x),x>=G.length){if(l)return-1;x=G.length-1}else if(x<0)if(l)x=0;else return-1;if(typeof z=="string"&&(z=Z.from(z,m)),Z.isBuffer(z))return z.length===0?-1:g(G,z,x,m,l);if(typeof z=="number")return z=z&255,typeof Uint8Array.prototype.indexOf=="function"?l?Uint8Array.prototype.indexOf.call(G,z,x):Uint8Array.prototype.lastIndexOf.call(G,z,x):g(G,[z],x,m,l);throw new TypeError("val must be string, number or Buffer")}function g(G,z,x,m,l){let a=1,K1=G.length,F1=z.length;if(m!==void 0&&(m=String(m).toLowerCase(),m==="ucs2"||m==="ucs-2"||m==="utf16le"||m==="utf-16le")){if(G.length<2||z.length<2)return-1;a=2,K1/=2,F1/=2,x/=2}function R1(W1,$1){return a===1?W1[$1]:W1.readUInt16BE($1*a)}let X1;if(l){let W1=-1;for(X1=x;X1K1&&(x=K1-F1),X1=x;X1>=0;X1--){let W1=!0;for(let $1=0;$1l&&(m=l)):m=l;let a=z.length;m>a/2&&(m=a/2);let K1;for(K1=0;K1>>0,isFinite(x)?(x=x>>>0,m===void 0&&(m="utf8")):(m=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let l=this.length-z;if((x===void 0||x>l)&&(x=l),G.length>0&&(x<0||z<0)||z>this.length)throw new RangeError("Attempt to write outside buffer bounds");m||(m="utf8");let a=!1;for(;;)switch(m){case"hex":return f(this,G,z,x);case"utf8":case"utf-8":return u(this,G,z,x);case"ascii":case"latin1":case"binary":return d(this,G,z,x);case"base64":return n(this,G,z,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,G,z,x);default:if(a)throw new TypeError("Unknown encoding: "+m);m=(""+m).toLowerCase(),a=!0}},Z.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function q(G,z,x){return z===0&&x===G.length?Q.fromByteArray(G):Q.fromByteArray(G.slice(z,x))}function P(G,z,x){x=Math.min(G.length,x);let m=[],l=z;for(;l239?4:a>223?3:a>191?2:1;if(l+F1<=x){let R1,X1,W1,$1;switch(F1){case 1:a<128&&(K1=a);break;case 2:R1=G[l+1],(R1&192)===128&&($1=(a&31)<<6|R1&63,$1>127&&(K1=$1));break;case 3:R1=G[l+1],X1=G[l+2],(R1&192)===128&&(X1&192)===128&&($1=(a&15)<<12|(R1&63)<<6|X1&63,$1>2047&&($1<55296||$1>57343)&&(K1=$1));break;case 4:R1=G[l+1],X1=G[l+2],W1=G[l+3],(R1&192)===128&&(X1&192)===128&&(W1&192)===128&&($1=(a&15)<<18|(R1&63)<<12|(X1&63)<<6|W1&63,$1>65535&&$1<1114112&&(K1=$1))}}K1===null?(K1=65533,F1=1):K1>65535&&(K1-=65536,m.push(K1>>>10&1023|55296),K1=56320|K1&1023),m.push(K1),l+=F1}return w(m)}var O=4096;function w(G){let z=G.length;if(z<=O)return String.fromCharCode.apply(String,G);let x="",m=0;for(;mm)&&(x=m);let l="";for(let a=z;ax&&(G=x),z<0?(z+=x,z<0&&(z=0)):z>x&&(z=x),zx)throw new RangeError("Trying to access beyond buffer length")}Z.prototype.readUintLE=Z.prototype.readUIntLE=function(G,z,x){G=G>>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G],l=1,a=0;for(;++a>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G+--z],l=1;for(;z>0&&(l*=256);)m+=this[G+--z]*l;return m},Z.prototype.readUint8=Z.prototype.readUInt8=function(G,z){return G=G>>>0,z||j(G,1,this.length),this[G]},Z.prototype.readUint16LE=Z.prototype.readUInt16LE=function(G,z){return G=G>>>0,z||j(G,2,this.length),this[G]|this[G+1]<<8},Z.prototype.readUint16BE=Z.prototype.readUInt16BE=function(G,z){return G=G>>>0,z||j(G,2,this.length),this[G]<<8|this[G+1]},Z.prototype.readUint32LE=Z.prototype.readUInt32LE=function(G,z){return G=G>>>0,z||j(G,4,this.length),(this[G]|this[G+1]<<8|this[G+2]<<16)+this[G+3]*16777216},Z.prototype.readUint32BE=Z.prototype.readUInt32BE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]*16777216+(this[G+1]<<16|this[G+2]<<8|this[G+3])},Z.prototype.readBigUInt64LE=G1(function(G){G=G>>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=z+this[++G]*256+this[++G]*65536+this[++G]*16777216,l=this[++G]+this[++G]*256+this[++G]*65536+x*16777216;return BigInt(m)+(BigInt(l)<>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=z*16777216+this[++G]*65536+this[++G]*256+this[++G],l=this[++G]*16777216+this[++G]*65536+this[++G]*256+x;return(BigInt(m)<>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G],l=1,a=0;for(;++a=l&&(m-=Math.pow(2,8*z)),m},Z.prototype.readIntBE=function(G,z,x){G=G>>>0,z=z>>>0,x||j(G,z,this.length);let m=z,l=1,a=this[G+--m];for(;m>0&&(l*=256);)a+=this[G+--m]*l;return l*=128,a>=l&&(a-=Math.pow(2,8*z)),a},Z.prototype.readInt8=function(G,z){return G=G>>>0,z||j(G,1,this.length),this[G]&128?(255-this[G]+1)*-1:this[G]},Z.prototype.readInt16LE=function(G,z){G=G>>>0,z||j(G,2,this.length);let x=this[G]|this[G+1]<<8;return x&32768?x|4294901760:x},Z.prototype.readInt16BE=function(G,z){G=G>>>0,z||j(G,2,this.length);let x=this[G+1]|this[G]<<8;return x&32768?x|4294901760:x},Z.prototype.readInt32LE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]|this[G+1]<<8|this[G+2]<<16|this[G+3]<<24},Z.prototype.readInt32BE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]<<24|this[G+1]<<16|this[G+2]<<8|this[G+3]},Z.prototype.readBigInt64LE=G1(function(G){G=G>>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=this[G+4]+this[G+5]*256+this[G+6]*65536+(x<<24);return(BigInt(m)<>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=(z<<24)+this[++G]*65536+this[++G]*256+this[++G];return(BigInt(m)<>>0,z||j(G,4,this.length),J.read(this,G,!0,23,4)},Z.prototype.readFloatBE=function(G,z){return G=G>>>0,z||j(G,4,this.length),J.read(this,G,!1,23,4)},Z.prototype.readDoubleLE=function(G,z){return G=G>>>0,z||j(G,8,this.length),J.read(this,G,!0,52,8)},Z.prototype.readDoubleBE=function(G,z){return G=G>>>0,z||j(G,8,this.length),J.read(this,G,!1,52,8)};function b(G,z,x,m,l,a){if(!Z.isBuffer(G))throw new TypeError('"buffer" argument must be a Buffer instance');if(z>l||zG.length)throw new RangeError("Index out of range")}Z.prototype.writeUintLE=Z.prototype.writeUIntLE=function(G,z,x,m){if(G=+G,z=z>>>0,x=x>>>0,!m){let K1=Math.pow(2,8*x)-1;b(this,G,z,x,K1,0)}let l=1,a=0;for(this[z]=G&255;++a>>0,x=x>>>0,!m){let K1=Math.pow(2,8*x)-1;b(this,G,z,x,K1,0)}let l=x-1,a=1;for(this[z+l]=G&255;--l>=0&&(a*=256);)this[z+l]=G/a&255;return z+x},Z.prototype.writeUint8=Z.prototype.writeUInt8=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,1,255,0),this[z]=G&255,z+1},Z.prototype.writeUint16LE=Z.prototype.writeUInt16LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,65535,0),this[z]=G&255,this[z+1]=G>>>8,z+2},Z.prototype.writeUint16BE=Z.prototype.writeUInt16BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,65535,0),this[z]=G>>>8,this[z+1]=G&255,z+2},Z.prototype.writeUint32LE=Z.prototype.writeUInt32LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,4294967295,0),this[z+3]=G>>>24,this[z+2]=G>>>16,this[z+1]=G>>>8,this[z]=G&255,z+4},Z.prototype.writeUint32BE=Z.prototype.writeUInt32BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,4294967295,0),this[z]=G>>>24,this[z+1]=G>>>16,this[z+2]=G>>>8,this[z+3]=G&255,z+4};function p(G,z,x,m,l){E1(z,m,l,G,x,7);let a=Number(z&BigInt(4294967295));G[x++]=a,a=a>>8,G[x++]=a,a=a>>8,G[x++]=a,a=a>>8,G[x++]=a;let K1=Number(z>>BigInt(32)&BigInt(4294967295));return G[x++]=K1,K1=K1>>8,G[x++]=K1,K1=K1>>8,G[x++]=K1,K1=K1>>8,G[x++]=K1,x}function s(G,z,x,m,l){E1(z,m,l,G,x,7);let a=Number(z&BigInt(4294967295));G[x+7]=a,a=a>>8,G[x+6]=a,a=a>>8,G[x+5]=a,a=a>>8,G[x+4]=a;let K1=Number(z>>BigInt(32)&BigInt(4294967295));return G[x+3]=K1,K1=K1>>8,G[x+2]=K1,K1=K1>>8,G[x+1]=K1,K1=K1>>8,G[x]=K1,x+8}Z.prototype.writeBigUInt64LE=G1(function(G,z=0){return p(this,G,z,BigInt(0),BigInt("0xffffffffffffffff"))}),Z.prototype.writeBigUInt64BE=G1(function(G,z=0){return s(this,G,z,BigInt(0),BigInt("0xffffffffffffffff"))}),Z.prototype.writeIntLE=function(G,z,x,m){if(G=+G,z=z>>>0,!m){let F1=Math.pow(2,8*x-1);b(this,G,z,x,F1-1,-F1)}let l=0,a=1,K1=0;for(this[z]=G&255;++l>0)-K1&255;return z+x},Z.prototype.writeIntBE=function(G,z,x,m){if(G=+G,z=z>>>0,!m){let F1=Math.pow(2,8*x-1);b(this,G,z,x,F1-1,-F1)}let l=x-1,a=1,K1=0;for(this[z+l]=G&255;--l>=0&&(a*=256);)G<0&&K1===0&&this[z+l+1]!==0&&(K1=1),this[z+l]=(G/a>>0)-K1&255;return z+x},Z.prototype.writeInt8=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,1,127,-128),G<0&&(G=255+G+1),this[z]=G&255,z+1},Z.prototype.writeInt16LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,32767,-32768),this[z]=G&255,this[z+1]=G>>>8,z+2},Z.prototype.writeInt16BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,32767,-32768),this[z]=G>>>8,this[z+1]=G&255,z+2},Z.prototype.writeInt32LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,2147483647,-2147483648),this[z]=G&255,this[z+1]=G>>>8,this[z+2]=G>>>16,this[z+3]=G>>>24,z+4},Z.prototype.writeInt32BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,2147483647,-2147483648),G<0&&(G=4294967295+G+1),this[z]=G>>>24,this[z+1]=G>>>16,this[z+2]=G>>>8,this[z+3]=G&255,z+4},Z.prototype.writeBigInt64LE=G1(function(G,z=0){return p(this,G,z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),Z.prototype.writeBigInt64BE=G1(function(G,z=0){return s(this,G,z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function r(G,z,x,m,l,a){if(x+m>G.length)throw new RangeError("Index out of range");if(x<0)throw new RangeError("Index out of range")}function A1(G,z,x,m,l){return z=+z,x=x>>>0,l||r(G,z,x,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000),J.write(G,z,x,m,23,4),x+4}Z.prototype.writeFloatLE=function(G,z,x){return A1(this,G,z,!0,x)},Z.prototype.writeFloatBE=function(G,z,x){return A1(this,G,z,!1,x)};function Q1(G,z,x,m,l){return z=+z,x=x>>>0,l||r(G,z,x,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000),J.write(G,z,x,m,52,8),x+8}Z.prototype.writeDoubleLE=function(G,z,x){return Q1(this,G,z,!0,x)},Z.prototype.writeDoubleBE=function(G,z,x){return Q1(this,G,z,!1,x)},Z.prototype.copy=function(G,z,x,m){if(!Z.isBuffer(G))throw new TypeError("argument should be a Buffer");if(x||(x=0),!m&&m!==0&&(m=this.length),z>=G.length&&(z=G.length),z||(z=0),m>0&&m=this.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("sourceEnd out of bounds");m>this.length&&(m=this.length),G.length-z>>0,x=x===void 0?this.length:x>>>0,G||(G=0);let l;if(typeof G=="number")for(l=z;l4294967296?l=U1(String(x)):typeof x=="bigint"&&(l=String(x),(x>BigInt(2)**BigInt(32)||x<-(BigInt(2)**BigInt(32)))&&(l=U1(l)),l+="n"),m+=` It must be ${z}. Received ${l}`,m},RangeError);function U1(G){let z="",x=G.length,m=G[0]==="-"?1:0;for(;x>=m+4;x-=3)z=`_${G.slice(x-3,x)}${z}`;return`${G.slice(0,x)}${z}`}function O1(G,z,x){Y1(z,"offset"),(G[z]===void 0||G[z+x]===void 0)&&i(z,G.length-(x+1))}function E1(G,z,x,m,l,a){if(G>x||G3?z===0||z===BigInt(0)?F1=`>= 0${K1} and < 2${K1} ** ${(a+1)*8}${K1}`:F1=`>= -(2${K1} ** ${(a+1)*8-1}${K1}) and < 2 ** ${(a+1)*8-1}${K1}`:F1=`>= ${z}${K1} and <= ${x}${K1}`,new e.ERR_OUT_OF_RANGE("value",F1,G)}O1(m,l,a)}function Y1(G,z){if(typeof G!="number")throw new e.ERR_INVALID_ARG_TYPE(z,"number",G)}function i(G,z,x){throw Math.floor(G)!==G?(Y1(G,x),new e.ERR_OUT_OF_RANGE(x||"offset","an integer",G)):z<0?new e.ERR_BUFFER_OUT_OF_BOUNDS:new e.ERR_OUT_OF_RANGE(x||"offset",`>= ${x?1:0} and <= ${z}`,G)}var c=/[^+/0-9A-Za-z-_]/g;function o(G){if(G=G.split("=")[0],G=G.trim().replace(c,""),G.length<2)return"";for(;G.length%4!==0;)G=G+"=";return G}function C1(G,z){z=z||1/0;let x,m=G.length,l=null,a=[];for(let K1=0;K155295&&x<57344){if(!l){if(x>56319){(z-=3)>-1&&a.push(239,191,189);continue}else if(K1+1===m){(z-=3)>-1&&a.push(239,191,189);continue}l=x;continue}if(x<56320){(z-=3)>-1&&a.push(239,191,189),l=x;continue}x=(l-55296<<10|x-56320)+65536}else l&&(z-=3)>-1&&a.push(239,191,189);if(l=null,x<128){if((z-=1)<0)break;a.push(x)}else if(x<2048){if((z-=2)<0)break;a.push(x>>6|192,x&63|128)}else if(x<65536){if((z-=3)<0)break;a.push(x>>12|224,x>>6&63|128,x&63|128)}else if(x<1114112){if((z-=4)<0)break;a.push(x>>18|240,x>>12&63|128,x>>6&63|128,x&63|128)}else throw new Error("Invalid code point")}return a}function q1(G){let z=[];for(let x=0;x>8,l=x%256,a.push(l),a.push(m);return a}function j1(G){return Q.toByteArray(o(G))}function H1(G,z,x,m){let l;for(l=0;l=z.length||l>=G.length);++l)z[l+x]=G[l];return l}function B1(G,z){return G instanceof z||G!=null&&G.constructor!=null&&G.constructor.name!=null&&G.constructor.name===z.name}function k1(G){return G!==G}var D1=function(){let G="0123456789abcdef",z=new Array(256);for(let x=0;x<16;++x){let m=x*16;for(let l=0;l<16;++l)z[m+l]=G[x]+G[l]}return z}();function G1(G){return typeof BigInt>"u"?w1:G}function w1(){throw new Error("BigInt not supported")}}),bA=l1((A,Q)=>{var J=A6(),K=J.Buffer;function C(Y,Z){for(var X in Y)Z[X]=Y[X]}K.from&&K.alloc&&K.allocUnsafe&&K.allocUnsafeSlow?Q.exports=J:(C(J,A),A.Buffer=U);function U(Y,Z,X){return K(Y,Z,X)}U.prototype=Object.create(K.prototype),C(K,U),U.from=function(Y,Z,X){if(typeof Y=="number")throw new TypeError("Argument must not be a number");return K(Y,Z,X)},U.alloc=function(Y,Z,X){if(typeof Y!="number")throw new TypeError("Argument must be a number");var E=K(Y);return Z!==void 0?typeof X=="string"?E.fill(Z,X):E.fill(Z):E.fill(0),E},U.allocUnsafe=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return K(Y)},U.allocUnsafeSlow=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return J.SlowBuffer(Y)}}),VK=l1((A,Q)=>{var J=65536,K=4294967295;function C(){throw new Error(`Secure random number generation is not supported by this browser. -Use Chrome, Firefox or Internet Explorer 11`)}var U=bA().Buffer,Y=global.crypto||global.msCrypto;Y&&Y.getRandomValues?Q.exports=Z:Q.exports=C;function Z(X,E){if(X>K)throw new RangeError("requested too many random bytes");var H=U.allocUnsafe(X);if(X>0)if(X>J)for(var $=0;${typeof Object.create=="function"?Q.exports=function(J,K){K&&(J.super_=K,J.prototype=Object.create(K.prototype,{constructor:{value:J,enumerable:!1,writable:!0,configurable:!0}}))}:Q.exports=function(J,K){if(K){J.super_=K;var C=function(){};C.prototype=K.prototype,J.prototype=new C,J.prototype.constructor=J}}}),YQ=l1((A,Q)=>{var J=typeof Reflect=="object"?Reflect:null,K=J&&typeof J.apply=="function"?J.apply:function(y,g,f){return Function.prototype.apply.call(y,g,f)},C;J&&typeof J.ownKeys=="function"?C=J.ownKeys:Object.getOwnPropertySymbols?C=function(y){return Object.getOwnPropertyNames(y).concat(Object.getOwnPropertySymbols(y))}:C=function(y){return Object.getOwnPropertyNames(y)};function U(y){console&&console.warn&&console.warn(y)}var Y=Number.isNaN||function(y){return y!==y};function Z(){Z.init.call(this)}Q.exports=Z,Q.exports.once=M,Z.EventEmitter=Z,Z.prototype._events=void 0,Z.prototype._eventsCount=0,Z.prototype._maxListeners=void 0;var X=10;function E(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(Z,"defaultMaxListeners",{enumerable:!0,get:function(){return X},set:function(y){if(typeof y!="number"||y<0||Y(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");X=y}}),Z.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Z.prototype.setMaxListeners=function(y){if(typeof y!="number"||y<0||Y(y))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+y+".");return this._maxListeners=y,this};function H(y){return y._maxListeners===void 0?Z.defaultMaxListeners:y._maxListeners}Z.prototype.getMaxListeners=function(){return H(this)},Z.prototype.emit=function(y){for(var g=[],f=1;f0&&(n=g[0]),n instanceof Error)throw n;var B=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw B.context=n,B}var q=d[y];if(q===void 0)return!1;if(typeof q=="function")K(q,this,g);else for(var P=q.length,O=D(q,P),f=0;f0&&B.length>d&&!B.warned){B.warned=!0;var q=new Error("Possible EventEmitter memory leak detected. "+B.length+" "+String(g)+" listeners added. Use emitter.setMaxListeners() to increase limit");q.name="MaxListenersExceededWarning",q.emitter=y,q.type=g,q.count=B.length,U(q)}return y}Z.prototype.addListener=function(y,g){return $(this,y,g,!1)},Z.prototype.on=Z.prototype.addListener,Z.prototype.prependListener=function(y,g){return $(this,y,g,!0)};function I(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function N(y,g,f){var u={fired:!1,wrapFn:void 0,target:y,type:g,listener:f},d=I.bind(u);return d.listener=f,u.wrapFn=d,d}Z.prototype.once=function(y,g){return E(g),this.on(y,N(this,y,g)),this},Z.prototype.prependOnceListener=function(y,g){return E(g),this.prependListener(y,N(this,y,g)),this},Z.prototype.removeListener=function(y,g){var f,u,d,n,B;if(E(g),u=this._events,u===void 0)return this;if(f=u[y],f===void 0)return this;if(f===g||f.listener===g)--this._eventsCount===0?this._events=Object.create(null):(delete u[y],u.removeListener&&this.emit("removeListener",y,f.listener||g));else if(typeof f!="function"){for(d=-1,n=f.length-1;n>=0;n--)if(f[n]===g||f[n].listener===g){B=f[n].listener,d=n;break}if(d<0)return this;d===0?f.shift():L(f,d),f.length===1&&(u[y]=f[0]),u.removeListener!==void 0&&this.emit("removeListener",y,B||g)}return this},Z.prototype.off=Z.prototype.removeListener,Z.prototype.removeAllListeners=function(y){var g,f,u;if(f=this._events,f===void 0)return this;if(f.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):f[y]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete f[y]),this;if(arguments.length===0){var d=Object.keys(f),n;for(u=0;u=0;u--)this.removeListener(y,g[u]);return this};function F(y,g,f){var u=y._events;if(u===void 0)return[];var d=u[g];return d===void 0?[]:typeof d=="function"?f?[d.listener||d]:[d]:f?R(d):D(d,d.length)}Z.prototype.listeners=function(y){return F(this,y,!0)},Z.prototype.rawListeners=function(y){return F(this,y,!1)},Z.listenerCount=function(y,g){return typeof y.listenerCount=="function"?y.listenerCount(g):V.call(y,g)},Z.prototype.listenerCount=V;function V(y){var g=this._events;if(g!==void 0){var f=g[y];if(typeof f=="function")return 1;if(f!==void 0)return f.length}return 0}Z.prototype.eventNames=function(){return this._eventsCount>0?C(this._events):[]};function D(y,g){for(var f=new Array(g),u=0;u{Q.exports=YQ().EventEmitter}),oE=l1(()=>{}),f61=l1((A,Q)=>{function J(F,V){var D=Object.keys(F);if(Object.getOwnPropertySymbols){var L=Object.getOwnPropertySymbols(F);V&&(L=L.filter(function(R){return Object.getOwnPropertyDescriptor(F,R).enumerable})),D.push.apply(D,L)}return D}function K(F){for(var V=1;V0?this.tail.next=D:this.head=D,this.tail=D,++this.length}},{key:"unshift",value:function(V){var D={data:V,next:this.head};this.length===0&&(this.tail=D),this.head=D,++this.length}},{key:"shift",value:function(){if(this.length!==0){var V=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,V}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(V){if(this.length===0)return"";for(var D=this.head,L=""+D.data;D=D.next;)L+=V+D.data;return L}},{key:"concat",value:function(V){if(this.length===0)return E.alloc(0);for(var D=E.allocUnsafe(V>>>0),L=this.head,R=0;L;)N(L.data,D,R),R+=L.data.length,L=L.next;return D}},{key:"consume",value:function(V,D){var L;return VM.length?M.length:V;if(T===M.length?R+=M:R+=M.slice(0,V),V-=T,V===0){T===M.length?(++L,D.next?this.head=D.next:this.head=this.tail=null):(this.head=D,D.data=M.slice(T));break}++L}return this.length-=L,R}},{key:"_getBuffer",value:function(V){var D=E.allocUnsafe(V),L=this.head,R=1;for(L.data.copy(D),V-=L.data.length;L=L.next;){var M=L.data,T=V>M.length?M.length:V;if(M.copy(D,D.length-V,0,T),V-=T,V===0){T===M.length?(++R,L.next?this.head=L.next:this.head=this.tail=null):(this.head=L,L.data=M.slice(T));break}++R}return this.length-=R,D}},{key:I,value:function(V,D){return $(this,K({},D,{depth:0,customInspect:!1}))}}]),F}()}),zx=l1((A,Q)=>{function J(X,E){var H=this,$=this._readableState&&this._readableState.destroyed,I=this._writableState&&this._writableState.destroyed;return $||I?(E?E(X):X&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(Y,this,X)):process.nextTick(Y,this,X)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(X||null,function(N){!E&&N?H._writableState?H._writableState.errorEmitted?process.nextTick(C,H):(H._writableState.errorEmitted=!0,process.nextTick(K,H,N)):process.nextTick(K,H,N):E?(process.nextTick(C,H),E(N)):process.nextTick(C,H)}),this)}function K(X,E){Y(X,E),C(X)}function C(X){X._writableState&&!X._writableState.emitClose||X._readableState&&!X._readableState.emitClose||X.emit("close")}function U(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function Y(X,E){X.emit("error",E)}function Z(X,E){var{_readableState:H,_writableState:$}=X;H&&H.autoDestroy||$&&$.autoDestroy?X.destroy(E):X.emit("error",E)}Q.exports={destroy:J,undestroy:U,errorOrDestroy:Z}}),MK=l1((A,Q)=>{function J(E,H){E.prototype=Object.create(H.prototype),E.prototype.constructor=E,E.__proto__=H}var K={};function C(E,H,$){$||($=Error);function I(F,V,D){return typeof H=="string"?H:H(F,V,D)}var N=function(F){J(V,F);function V(D,L,R){return F.call(this,I(D,L,R))||this}return V}($);N.prototype.name=$.name,N.prototype.code=E,K[E]=N}function U(E,H){if(Array.isArray(E)){var $=E.length;return E=E.map(function(I){return String(I)}),$>2?"one of ".concat(H," ").concat(E.slice(0,$-1).join(", "),", or ")+E[$-1]:$===2?"one of ".concat(H," ").concat(E[0]," or ").concat(E[1]):"of ".concat(H," ").concat(E[0])}else return"of ".concat(H," ").concat(String(E))}function Y(E,H,$){return E.substr(!$||$<0?0:+$,H.length)===H}function Z(E,H,$){return($===void 0||$>E.length)&&($=E.length),E.substring($-H.length,$)===H}function X(E,H,$){return typeof $!="number"&&($=0),$+H.length>E.length?!1:E.indexOf(H,$)!==-1}C("ERR_INVALID_OPT_VALUE",function(E,H){return'The value "'+H+'" is invalid for option "'+E+'"'},TypeError),C("ERR_INVALID_ARG_TYPE",function(E,H,$){var I;typeof H=="string"&&Y(H,"not ")?(I="must not be",H=H.replace(/^not /,"")):I="must be";var N;if(Z(E," argument"))N="The ".concat(E," ").concat(I," ").concat(U(H,"type"));else{var F=X(E,".")?"property":"argument";N='The "'.concat(E,'" ').concat(F," ").concat(I," ").concat(U(H,"type"))}return N+=". Received type ".concat(typeof $),N},TypeError),C("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),C("ERR_METHOD_NOT_IMPLEMENTED",function(E){return"The "+E+" method is not implemented"}),C("ERR_STREAM_PREMATURE_CLOSE","Premature close"),C("ERR_STREAM_DESTROYED",function(E){return"Cannot call "+E+" after a stream was destroyed"}),C("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),C("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),C("ERR_STREAM_WRITE_AFTER_END","write after end"),C("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),C("ERR_UNKNOWN_ENCODING",function(E){return"Unknown encoding: "+E},TypeError),C("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Q.exports.codes=K}),Dx=l1((A,Q)=>{var J=MK().codes.ERR_INVALID_OPT_VALUE;function K(U,Y,Z){return U.highWaterMark!=null?U.highWaterMark:Y?U[Z]:null}function C(U,Y,Z,X){var E=K(Y,X,Z);if(E!=null){if(!(isFinite(E)&&Math.floor(E)===E)||E<0){var H=X?Z:"highWaterMark";throw new J(H,E)}return Math.floor(E)}return U.objectMode?16:16384}Q.exports={getHighWaterMark:C}}),Vx=l1((A,Q)=>{Q.exports=J;function J(C,U){if(K("noDeprecation"))return C;var Y=!1;function Z(){if(!Y){if(K("throwDeprecation"))throw new Error(U);K("traceDeprecation")?console.trace(U):console.warn(U),Y=!0}return C.apply(this,arguments)}return Z}function K(C){try{if(!global.localStorage)return!1}catch{return!1}var U=global.localStorage[C];return U==null?!1:String(U).toLowerCase()==="true"}}),Mx=l1((A,Q)=>{Q.exports=d;function J(e){var t=this;this.next=null,this.entry=null,this.finish=function(){Q1(t,e)}}var K;d.WritableState=f;var C={deprecate:Vx()},U=Rx(),Y=A6().Buffer,Z=global.Uint8Array||function(){};function X(e){return Y.from(e)}function E(e){return Y.isBuffer(e)||e instanceof Z}var H=zx(),$=Dx(),I=$.getHighWaterMark,N=MK().codes,F=N.ERR_INVALID_ARG_TYPE,V=N.ERR_METHOD_NOT_IMPLEMENTED,D=N.ERR_MULTIPLE_CALLBACK,L=N.ERR_STREAM_CANNOT_PIPE,R=N.ERR_STREAM_DESTROYED,M=N.ERR_STREAM_NULL_VALUES,T=N.ERR_STREAM_WRITE_AFTER_END,h=N.ERR_UNKNOWN_ENCODING,y=H.errorOrDestroy;MA()(d,U);function g(){}function f(e,t,U1){K=K||RK(),e=e||{},typeof U1!="boolean"&&(U1=t instanceof K),this.objectMode=!!e.objectMode,U1&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=I(this,e,"writableHighWaterMark",U1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var O1=e.decodeStrings===!1;this.decodeStrings=!O1,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(E1){S(t,E1)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new J(this)}f.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(f.prototype,"buffer",{get:C.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var u;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(u=Function.prototype[Symbol.hasInstance],Object.defineProperty(d,Symbol.hasInstance,{value:function(e){return u.call(this,e)?!0:this!==d?!1:e&&e._writableState instanceof f}})):u=function(e){return e instanceof this};function d(e){K=K||RK();var t=this instanceof K;if(!t&&!u.call(d,this))return new d(e);this._writableState=new f(e,this,t),this.writable=!0,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),U.call(this)}d.prototype.pipe=function(){y(this,new L)};function n(e,t){var U1=new T;y(e,U1),process.nextTick(t,U1)}function B(e,t,U1,O1){var E1;return U1===null?E1=new M:typeof U1!="string"&&!t.objectMode&&(E1=new F("chunk",["string","Buffer"],U1)),E1?(y(e,E1),process.nextTick(O1,E1),!1):!0}d.prototype.write=function(e,t,U1){var O1=this._writableState,E1=!1,Y1=!O1.objectMode&&E(e);return Y1&&!Y.isBuffer(e)&&(e=X(e)),typeof t=="function"&&(U1=t,t=null),Y1?t="buffer":t||(t=O1.defaultEncoding),typeof U1!="function"&&(U1=g),O1.ending?n(this,U1):(Y1||B(this,O1,e,U1))&&(O1.pendingcb++,E1=P(this,O1,Y1,e,t,U1)),E1},d.prototype.cork=function(){this._writableState.corked++},d.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&j(this,e))},d.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new h(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(d.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function q(e,t,U1){return!e.objectMode&&e.decodeStrings!==!1&&typeof t=="string"&&(t=Y.from(t,U1)),t}Object.defineProperty(d.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function P(e,t,U1,O1,E1,Y1){if(!U1){var i=q(t,O1,E1);O1!==i&&(U1=!0,E1="buffer",O1=i)}var c=t.objectMode?1:O1.length;t.length+=c;var o=t.length{var J=Object.keys||function($){var I=[];for(var N in $)I.push(N);return I};Q.exports=X;var K=wx(),C=Mx();MA()(X,K);for(U=J(C.prototype),Z=0;Z{var Q=bA().Buffer,J=Q.isEncoding||function(R){switch(R=""+R,R&&R.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function K(R){if(!R)return"utf8";for(var M;;)switch(R){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return R;default:if(M)return;R=(""+R).toLowerCase(),M=!0}}function C(R){var M=K(R);if(typeof M!="string"&&(Q.isEncoding===J||!J(R)))throw new Error("Unknown encoding: "+R);return M||R}A.StringDecoder=U;function U(R){this.encoding=C(R);var M;switch(this.encoding){case"utf16le":this.text=I,this.end=N,M=4;break;case"utf8":this.fillLast=E,M=4;break;case"base64":this.text=F,this.end=V,M=3;break;default:this.write=D,this.end=L;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Q.allocUnsafe(M)}U.prototype.write=function(R){if(R.length===0)return"";var M,T;if(this.lastNeed){if(M=this.fillLast(R),M===void 0)return"";T=this.lastNeed,this.lastNeed=0}else T=0;return T>5===6?2:R>>4===14?3:R>>3===30?4:R>>6===2?-1:-2}function Z(R,M,T){var h=M.length-1;if(h=0?(y>0&&(R.lastNeed=y-1),y):--h=0?(y>0&&(R.lastNeed=y-2),y):--h=0?(y>0&&(y===2?y=0:R.lastNeed=y-3),y):0))}function X(R,M,T){if((M[0]&192)!==128)return R.lastNeed=0,"�";if(R.lastNeed>1&&M.length>1){if((M[1]&192)!==128)return R.lastNeed=1,"�";if(R.lastNeed>2&&M.length>2&&(M[2]&192)!==128)return R.lastNeed=2,"�"}}function E(R){var M=this.lastTotal-this.lastNeed,T=X(this,R,M);if(T!==void 0)return T;if(this.lastNeed<=R.length)return R.copy(this.lastChar,M,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);R.copy(this.lastChar,M,0,R.length),this.lastNeed-=R.length}function H(R,M){var T=Z(this,R,M);if(!this.lastNeed)return R.toString("utf8",M);this.lastTotal=T;var h=R.length-(T-this.lastNeed);return R.copy(this.lastChar,0,h),R.toString("utf8",M,h)}function $(R){var M=R&&R.length?this.write(R):"";return this.lastNeed?M+"�":M}function I(R,M){if((R.length-M)%2===0){var T=R.toString("utf16le",M);if(T){var h=T.charCodeAt(T.length-1);if(h>=55296&&h<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=R[R.length-2],this.lastChar[1]=R[R.length-1],T.slice(0,-1)}return T}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=R[R.length-1],R.toString("utf16le",M,R.length-1)}function N(R){var M=R&&R.length?this.write(R):"";if(this.lastNeed){var T=this.lastTotal-this.lastNeed;return M+this.lastChar.toString("utf16le",0,T)}return M}function F(R,M){var T=(R.length-M)%3;return T===0?R.toString("base64",M):(this.lastNeed=3-T,this.lastTotal=3,T===1?this.lastChar[0]=R[R.length-1]:(this.lastChar[0]=R[R.length-2],this.lastChar[1]=R[R.length-1]),R.toString("base64",M,R.length-T))}function V(R){var M=R&&R.length?this.write(R):"";return this.lastNeed?M+this.lastChar.toString("base64",0,3-this.lastNeed):M}function D(R){return R.toString(this.encoding)}function L(R){return R&&R.length?this.write(R):""}}),IU={};sE(IU,{StringDecoder:()=>wN.StringDecoder,default:()=>wN.StringDecoder});lE=PN(()=>{wN=CQ(TN())}),kN=l1((A,Q)=>{var J=MK().codes.ERR_STREAM_PREMATURE_CLOSE;function K(Z){var X=!1;return function(){if(!X){X=!0;for(var E=arguments.length,H=new Array(E),$=0;${var J;function K(M,T,h){return T in M?Object.defineProperty(M,T,{value:h,enumerable:!0,configurable:!0,writable:!0}):M[T]=h,M}var C=kN(),U=Symbol("lastResolve"),Y=Symbol("lastReject"),Z=Symbol("error"),X=Symbol("ended"),E=Symbol("lastPromise"),H=Symbol("handlePromise"),$=Symbol("stream");function I(M,T){return{value:M,done:T}}function N(M){var T=M[U];if(T!==null){var h=M[$].read();h!==null&&(M[E]=null,M[U]=null,M[Y]=null,T(I(h,!1)))}}function F(M){process.nextTick(N,M)}function V(M,T){return function(h,y){M.then(function(){if(T[X]){h(I(void 0,!0));return}T[H](h,y)},y)}}var D=Object.getPrototypeOf(function(){}),L=Object.setPrototypeOf((J={get stream(){return this[$]},next:function(){var M=this,T=this[Z];if(T!==null)return Promise.reject(T);if(this[X])return Promise.resolve(I(void 0,!0));if(this[$].destroyed)return new Promise(function(f,u){process.nextTick(function(){M[Z]?u(M[Z]):f(I(void 0,!0))})});var h=this[E],y;if(h)y=new Promise(V(h,this));else{var g=this[$].read();if(g!==null)return Promise.resolve(I(g,!1));y=new Promise(this[H])}return this[E]=y,y}},K(J,Symbol.asyncIterator,function(){return this}),K(J,"return",function(){var M=this;return new Promise(function(T,h){M[$].destroy(null,function(y){if(y){h(y);return}T(I(void 0,!0))})})}),J),D),R=function(M){var T,h=Object.create(L,(T={},K(T,$,{value:M,writable:!0}),K(T,U,{value:null,writable:!0}),K(T,Y,{value:null,writable:!0}),K(T,Z,{value:null,writable:!0}),K(T,X,{value:M._readableState.endEmitted,writable:!0}),K(T,H,{value:function(y,g){var f=h[$].read();f?(h[E]=null,h[U]=null,h[Y]=null,y(I(f,!1))):(h[U]=y,h[Y]=g)},writable:!0}),T));return h[E]=null,C(M,function(y){if(y&&y.code!=="ERR_STREAM_PREMATURE_CLOSE"){var g=h[Y];g!==null&&(h[E]=null,h[U]=null,h[Y]=null,g(y)),h[Z]=y;return}var f=h[U];f!==null&&(h[E]=null,h[U]=null,h[Y]=null,f(I(void 0,!0))),h[X]=!0}),M.on("readable",F.bind(null,h)),h};Q.exports=R}),u61=l1((A,Q)=>{Q.exports=function(){throw new Error("Readable.from is not available in the browser")}}),wx=l1((A,Q)=>{Q.exports=B;var J;B.ReadableState=n;var K=YQ().EventEmitter,C=function(i,c){return i.listeners(c).length},U=Rx(),Y=A6().Buffer,Z=global.Uint8Array||function(){};function X(i){return Y.from(i)}function E(i){return Y.isBuffer(i)||i instanceof Z}var H=oE(),$;H&&H.debuglog?$=H.debuglog("stream"):$=function(){};var I=f61(),N=zx(),F=Dx(),V=F.getHighWaterMark,D=MK().codes,L=D.ERR_INVALID_ARG_TYPE,R=D.ERR_STREAM_PUSH_AFTER_EOF,M=D.ERR_METHOD_NOT_IMPLEMENTED,T=D.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,h,y,g;MA()(B,U);var f=N.errorOrDestroy,u=["error","close","destroy","pause","resume"];function d(i,c,o){if(typeof i.prependListener=="function")return i.prependListener(c,o);!i._events||!i._events[c]?i.on(c,o):Array.isArray(i._events[c])?i._events[c].unshift(o):i._events[c]=[o,i._events[c]]}function n(i,c,o){J=J||RK(),i=i||{},typeof o!="boolean"&&(o=c instanceof J),this.objectMode=!!i.objectMode,o&&(this.objectMode=this.objectMode||!!i.readableObjectMode),this.highWaterMark=V(this,i,"readableHighWaterMark",o),this.buffer=new I,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=i.emitClose!==!1,this.autoDestroy=!!i.autoDestroy,this.destroyed=!1,this.defaultEncoding=i.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,i.encoding&&(h||(h=(lE(),_9(IU)).StringDecoder),this.decoder=new h(i.encoding),this.encoding=i.encoding)}function B(i){if(J=J||RK(),!(this instanceof B))return new B(i);var c=this instanceof J;this._readableState=new n(i,this,c),this.readable=!0,i&&(typeof i.read=="function"&&(this._read=i.read),typeof i.destroy=="function"&&(this._destroy=i.destroy)),U.call(this)}Object.defineProperty(B.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(i){!this._readableState||(this._readableState.destroyed=i)}}),B.prototype.destroy=N.destroy,B.prototype._undestroy=N.undestroy,B.prototype._destroy=function(i,c){c(i)},B.prototype.push=function(i,c){var o=this._readableState,C1;return o.objectMode?C1=!0:typeof i=="string"&&(c=c||o.defaultEncoding,c!==o.encoding&&(i=Y.from(i,c),c=""),C1=!0),q(this,i,c,!1,C1)},B.prototype.unshift=function(i){return q(this,i,null,!0,!1)};function q(i,c,o,C1,q1){$("readableAddChunk",c);var Z1=i._readableState;if(c===null)Z1.reading=!1,_(i,Z1);else{var j1;if(q1||(j1=O(Z1,c)),j1)f(i,j1);else if(Z1.objectMode||c&&c.length>0)if(typeof c!="string"&&!Z1.objectMode&&Object.getPrototypeOf(c)!==Y.prototype&&(c=X(c)),C1)Z1.endEmitted?f(i,new T):P(i,Z1,c,!0);else if(Z1.ended)f(i,new R);else{if(Z1.destroyed)return!1;Z1.reading=!1,Z1.decoder&&!o?(c=Z1.decoder.write(c),Z1.objectMode||c.length!==0?P(i,Z1,c,!1):b(i,Z1)):P(i,Z1,c,!1)}else C1||(Z1.reading=!1,b(i,Z1))}return!Z1.ended&&(Z1.length=w?i=w:(i--,i|=i>>>1,i|=i>>>2,i|=i>>>4,i|=i>>>8,i|=i>>>16,i++),i}function S(i,c){return i<=0||c.length===0&&c.ended?0:c.objectMode?1:i!==i?c.flowing&&c.length?c.buffer.head.data.length:c.length:(i>c.highWaterMark&&(c.highWaterMark=k(i)),i<=c.length?i:c.ended?c.length:(c.needReadable=!0,0))}B.prototype.read=function(i){$("read",i),i=parseInt(i,10);var c=this._readableState,o=i;if(i!==0&&(c.emittedReadable=!1),i===0&&c.needReadable&&((c.highWaterMark!==0?c.length>=c.highWaterMark:c.length>0)||c.ended))return $("read: emitReadable",c.length,c.ended),c.length===0&&c.ended?O1(this):W(this),null;if(i=S(i,c),i===0&&c.ended)return c.length===0&&O1(this),null;var C1=c.needReadable;$("need readable",C1),(c.length===0||c.length-i0?q1=U1(i,c):q1=null,q1===null?(c.needReadable=c.length<=c.highWaterMark,i=0):(c.length-=i,c.awaitDrain=0),c.length===0&&(c.ended||(c.needReadable=!0),o!==i&&c.ended&&O1(this)),q1!==null&&this.emit("data",q1),q1};function _(i,c){if($("onEofChunk"),!c.ended){if(c.decoder){var o=c.decoder.end();o&&o.length&&(c.buffer.push(o),c.length+=c.objectMode?1:o.length)}c.ended=!0,c.sync?W(i):(c.needReadable=!1,c.emittedReadable||(c.emittedReadable=!0,j(i)))}}function W(i){var c=i._readableState;$("emitReadable",c.needReadable,c.emittedReadable),c.needReadable=!1,c.emittedReadable||($("emitReadable",c.flowing),c.emittedReadable=!0,process.nextTick(j,i))}function j(i){var c=i._readableState;$("emitReadable_",c.destroyed,c.length,c.ended),!c.destroyed&&(c.length||c.ended)&&(i.emit("readable"),c.emittedReadable=!1),c.needReadable=!c.flowing&&!c.ended&&c.length<=c.highWaterMark,t(i)}function b(i,c){c.readingMore||(c.readingMore=!0,process.nextTick(p,i,c))}function p(i,c){for(;!c.reading&&!c.ended&&(c.length1&&Y1(C1.pipes,i)!==-1)&&!k1&&($("false write response, pause",C1.awaitDrain),C1.awaitDrain++),o.pause())}function w1(m){$("onerror",m),x(),i.removeListener("error",w1),C(i,"error")===0&&f(i,m)}d(i,"error",w1);function G(){i.removeListener("finish",z),x()}i.once("close",G);function z(){$("onfinish"),i.removeListener("close",G),x()}i.once("finish",z);function x(){$("unpipe"),o.unpipe(i)}return i.emit("pipe",o),C1.flowing||($("pipe resume"),o.resume()),i};function s(i){return function(){var c=i._readableState;$("pipeOnDrain",c.awaitDrain),c.awaitDrain&&c.awaitDrain--,c.awaitDrain===0&&C(i,"data")&&(c.flowing=!0,t(i))}}B.prototype.unpipe=function(i){var c=this._readableState,o={hasUnpiped:!1};if(c.pipesCount===0)return this;if(c.pipesCount===1)return i&&i!==c.pipes?this:(i||(i=c.pipes),c.pipes=null,c.pipesCount=0,c.flowing=!1,i&&i.emit("unpipe",this,o),this);if(!i){var{pipes:C1,pipesCount:q1}=c;c.pipes=null,c.pipesCount=0,c.flowing=!1;for(var Z1=0;Z10,C1.flowing!==!1&&this.resume()):i==="readable"&&!C1.endEmitted&&!C1.readableListening&&(C1.readableListening=C1.needReadable=!0,C1.flowing=!1,C1.emittedReadable=!1,$("on readable",C1.length,C1.reading),C1.length?W(this):C1.reading||process.nextTick(A1,this)),o},B.prototype.addListener=B.prototype.on,B.prototype.removeListener=function(i,c){var o=U.prototype.removeListener.call(this,i,c);return i==="readable"&&process.nextTick(r,this),o},B.prototype.removeAllListeners=function(i){var c=U.prototype.removeAllListeners.apply(this,arguments);return(i==="readable"||i===void 0)&&process.nextTick(r,this),c};function r(i){var c=i._readableState;c.readableListening=i.listenerCount("readable")>0,c.resumeScheduled&&!c.paused?c.flowing=!0:i.listenerCount("data")>0&&i.resume()}function A1(i){$("readable nexttick read 0"),i.read(0)}B.prototype.resume=function(){var i=this._readableState;return i.flowing||($("resume"),i.flowing=!i.readableListening,Q1(this,i)),i.paused=!1,this};function Q1(i,c){c.resumeScheduled||(c.resumeScheduled=!0,process.nextTick(e,i,c))}function e(i,c){$("resume",c.reading),c.reading||i.read(0),c.resumeScheduled=!1,i.emit("resume"),t(i),c.flowing&&!c.reading&&i.read(0)}B.prototype.pause=function(){return $("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&($("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function t(i){var c=i._readableState;for($("flow",c.flowing);c.flowing&&i.read()!==null;);}B.prototype.wrap=function(i){var c=this,o=this._readableState,C1=!1;i.on("end",function(){if($("wrapped end"),o.decoder&&!o.ended){var j1=o.decoder.end();j1&&j1.length&&c.push(j1)}c.push(null)}),i.on("data",function(j1){if($("wrapped data"),o.decoder&&(j1=o.decoder.write(j1)),!(o.objectMode&&j1==null)&&!(!o.objectMode&&(!j1||!j1.length))){var H1=c.push(j1);H1||(C1=!0,i.pause())}});for(var q1 in i)this[q1]===void 0&&typeof i[q1]=="function"&&(this[q1]=function(j1){return function(){return i[j1].apply(i,arguments)}}(q1));for(var Z1=0;Z1=c.length?(c.decoder?o=c.buffer.join(""):c.buffer.length===1?o=c.buffer.first():o=c.buffer.concat(c.length),c.buffer.clear()):o=c.buffer.consume(i,c.decoder),o}function O1(i){var c=i._readableState;$("endReadable",c.endEmitted),c.endEmitted||(c.ended=!0,process.nextTick(E1,c,i))}function E1(i,c){if($("endReadableNT",i.endEmitted,i.length),!i.endEmitted&&i.length===0&&(i.endEmitted=!0,c.readable=!1,c.emit("end"),i.autoDestroy)){var o=c._writableState;(!o||o.autoDestroy&&o.finished)&&c.destroy()}}typeof Symbol=="function"&&(B.from=function(i,c){return g===void 0&&(g=u61()),g(B,i,c)});function Y1(i,c){for(var o=0,C1=i.length;o{Q.exports=E;var J=MK().codes,K=J.ERR_METHOD_NOT_IMPLEMENTED,C=J.ERR_MULTIPLE_CALLBACK,U=J.ERR_TRANSFORM_ALREADY_TRANSFORMING,Y=J.ERR_TRANSFORM_WITH_LENGTH_0,Z=RK();MA()(E,Z);function X(I,N){var F=this._transformState;F.transforming=!1;var V=F.writecb;if(V===null)return this.emit("error",new C);F.writechunk=null,F.writecb=null,N!=null&&this.push(N),V(I);var D=this._readableState;D.reading=!1,(D.needReadable||D.length{Q.exports=K;var J=Px();MA()(K,J);function K(C){if(!(this instanceof K))return new K(C);J.call(this,C)}K.prototype._transform=function(C,U,Y){Y(null,C)}}),c61=l1((A,Q)=>{var J;function K(F){var V=!1;return function(){V||(V=!0,F.apply(void 0,arguments))}}var C=MK().codes,U=C.ERR_MISSING_ARGS,Y=C.ERR_STREAM_DESTROYED;function Z(F){if(F)throw F}function X(F){return F.setHeader&&typeof F.abort=="function"}function E(F,V,D,L){L=K(L);var R=!1;F.on("close",function(){R=!0}),J===void 0&&(J=kN()),J(F,{readable:V,writable:D},function(T){if(T)return L(T);R=!0,L()});var M=!1;return function(T){if(!R&&!M){if(M=!0,X(F))return F.abort();if(typeof F.destroy=="function")return F.destroy();L(T||new Y("pipe"))}}}function H(F){F()}function $(F,V){return F.pipe(V)}function I(F){return!F.length||typeof F[F.length-1]!="function"?Z:F.pop()}function N(){for(var F=arguments.length,V=new Array(F),D=0;D0;return E(T,y,g,function(f){R||(R=f),f&&M.forEach(H),!y&&(M.forEach(H),L(R))})});return V.reduce($)}Q.exports=N}),d61=l1((A,Q)=>{A=Q.exports=wx(),A.Stream=A,A.Readable=A,A.Writable=Mx(),A.Duplex=RK(),A.Transform=Px(),A.PassThrough=m61(),A.finished=kN(),A.pipeline=c61()}),_x=l1((A,Q)=>{var J=bA().Buffer,K=d61().Transform,C=MA();function U(Z,X){if(!J.isBuffer(Z)&&typeof Z!="string")throw new TypeError(X+" must be a string or a buffer")}function Y(Z){K.call(this),this._block=J.allocUnsafe(Z),this._blockSize=Z,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}C(Y,K),Y.prototype._transform=function(Z,X,E){var H=null;try{this.update(Z,X)}catch($){H=$}E(H)},Y.prototype._flush=function(Z){var X=null;try{this.push(this.digest())}catch(E){X=E}Z(X)},Y.prototype.update=function(Z,X){if(U(Z,"Data"),this._finalized)throw new Error("Digest already called");J.isBuffer(Z)||(Z=J.from(Z,X));for(var E=this._block,H=0;this._blockOffset+Z.length-H>=this._blockSize;){for(var $=this._blockOffset;$0;++I)this._length[I]+=N,N=this._length[I]/4294967296|0,N>0&&(this._length[I]-=4294967296*N);return this},Y.prototype._update=function(){throw new Error("_update is not implemented")},Y.prototype.digest=function(Z){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var X=this._digest();Z!==void 0&&(X=X.toString(Z)),this._block.fill(0),this._blockOffset=0;for(var E=0;E<4;++E)this._length[E]=0;return X},Y.prototype._digest=function(){throw new Error("_digest is not implemented")},Q.exports=Y}),SN=l1((A,Q)=>{var J=MA(),K=_x(),C=bA().Buffer,U=new Array(16);function Y(){K.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}J(Y,K),Y.prototype._update=function(){for(var I=U,N=0;N<16;++N)I[N]=this._block.readInt32LE(N*4);var F=this._a,V=this._b,D=this._c,L=this._d;F=X(F,V,D,L,I[0],3614090360,7),L=X(L,F,V,D,I[1],3905402710,12),D=X(D,L,F,V,I[2],606105819,17),V=X(V,D,L,F,I[3],3250441966,22),F=X(F,V,D,L,I[4],4118548399,7),L=X(L,F,V,D,I[5],1200080426,12),D=X(D,L,F,V,I[6],2821735955,17),V=X(V,D,L,F,I[7],4249261313,22),F=X(F,V,D,L,I[8],1770035416,7),L=X(L,F,V,D,I[9],2336552879,12),D=X(D,L,F,V,I[10],4294925233,17),V=X(V,D,L,F,I[11],2304563134,22),F=X(F,V,D,L,I[12],1804603682,7),L=X(L,F,V,D,I[13],4254626195,12),D=X(D,L,F,V,I[14],2792965006,17),V=X(V,D,L,F,I[15],1236535329,22),F=E(F,V,D,L,I[1],4129170786,5),L=E(L,F,V,D,I[6],3225465664,9),D=E(D,L,F,V,I[11],643717713,14),V=E(V,D,L,F,I[0],3921069994,20),F=E(F,V,D,L,I[5],3593408605,5),L=E(L,F,V,D,I[10],38016083,9),D=E(D,L,F,V,I[15],3634488961,14),V=E(V,D,L,F,I[4],3889429448,20),F=E(F,V,D,L,I[9],568446438,5),L=E(L,F,V,D,I[14],3275163606,9),D=E(D,L,F,V,I[3],4107603335,14),V=E(V,D,L,F,I[8],1163531501,20),F=E(F,V,D,L,I[13],2850285829,5),L=E(L,F,V,D,I[2],4243563512,9),D=E(D,L,F,V,I[7],1735328473,14),V=E(V,D,L,F,I[12],2368359562,20),F=H(F,V,D,L,I[5],4294588738,4),L=H(L,F,V,D,I[8],2272392833,11),D=H(D,L,F,V,I[11],1839030562,16),V=H(V,D,L,F,I[14],4259657740,23),F=H(F,V,D,L,I[1],2763975236,4),L=H(L,F,V,D,I[4],1272893353,11),D=H(D,L,F,V,I[7],4139469664,16),V=H(V,D,L,F,I[10],3200236656,23),F=H(F,V,D,L,I[13],681279174,4),L=H(L,F,V,D,I[0],3936430074,11),D=H(D,L,F,V,I[3],3572445317,16),V=H(V,D,L,F,I[6],76029189,23),F=H(F,V,D,L,I[9],3654602809,4),L=H(L,F,V,D,I[12],3873151461,11),D=H(D,L,F,V,I[15],530742520,16),V=H(V,D,L,F,I[2],3299628645,23),F=$(F,V,D,L,I[0],4096336452,6),L=$(L,F,V,D,I[7],1126891415,10),D=$(D,L,F,V,I[14],2878612391,15),V=$(V,D,L,F,I[5],4237533241,21),F=$(F,V,D,L,I[12],1700485571,6),L=$(L,F,V,D,I[3],2399980690,10),D=$(D,L,F,V,I[10],4293915773,15),V=$(V,D,L,F,I[1],2240044497,21),F=$(F,V,D,L,I[8],1873313359,6),L=$(L,F,V,D,I[15],4264355552,10),D=$(D,L,F,V,I[6],2734768916,15),V=$(V,D,L,F,I[13],1309151649,21),F=$(F,V,D,L,I[4],4149444226,6),L=$(L,F,V,D,I[11],3174756917,10),D=$(D,L,F,V,I[2],718787259,15),V=$(V,D,L,F,I[9],3951481745,21),this._a=this._a+F|0,this._b=this._b+V|0,this._c=this._c+D|0,this._d=this._d+L|0},Y.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var I=C.allocUnsafe(16);return I.writeInt32LE(this._a,0),I.writeInt32LE(this._b,4),I.writeInt32LE(this._c,8),I.writeInt32LE(this._d,12),I};function Z(I,N){return I<>>32-N}function X(I,N,F,V,D,L,R){return Z(I+(N&F|~N&V)+D+L|0,R)+N|0}function E(I,N,F,V,D,L,R){return Z(I+(N&V|F&~V)+D+L|0,R)+N|0}function H(I,N,F,V,D,L,R){return Z(I+(N^F^V)+D+L|0,R)+N|0}function $(I,N,F,V,D,L,R){return Z(I+(F^(N|~V))+D+L|0,R)+N|0}Q.exports=Y}),jN=l1((A,Q)=>{var J=A6().Buffer,K=MA(),C=_x(),U=new Array(16),Y=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],Z=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],X=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],E=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],H=[0,1518500249,1859775393,2400959708,2840853838],$=[1352829926,1548603684,1836072691,2053994217,0];function I(){C.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}K(I,C),I.prototype._update=function(){for(var M=U,T=0;T<16;++T)M[T]=this._block.readInt32LE(T*4);for(var h=this._a|0,y=this._b|0,g=this._c|0,f=this._d|0,u=this._e|0,d=this._a|0,n=this._b|0,B=this._c|0,q=this._d|0,P=this._e|0,O=0;O<80;O+=1){var w,k;O<16?(w=F(h,y,g,f,u,M[Y[O]],H[0],X[O]),k=R(d,n,B,q,P,M[Z[O]],$[0],E[O])):O<32?(w=V(h,y,g,f,u,M[Y[O]],H[1],X[O]),k=L(d,n,B,q,P,M[Z[O]],$[1],E[O])):O<48?(w=D(h,y,g,f,u,M[Y[O]],H[2],X[O]),k=D(d,n,B,q,P,M[Z[O]],$[2],E[O])):O<64?(w=L(h,y,g,f,u,M[Y[O]],H[3],X[O]),k=V(d,n,B,q,P,M[Z[O]],$[3],E[O])):(w=R(h,y,g,f,u,M[Y[O]],H[4],X[O]),k=F(d,n,B,q,P,M[Z[O]],$[4],E[O])),h=u,u=f,f=N(g,10),g=y,y=w,d=P,P=q,q=N(B,10),B=n,n=k}var S=this._b+g+q|0;this._b=this._c+f+P|0,this._c=this._d+u+d|0,this._d=this._e+h+n|0,this._e=this._a+y+B|0,this._a=S},I.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var M=J.alloc?J.alloc(20):new J(20);return M.writeInt32LE(this._a,0),M.writeInt32LE(this._b,4),M.writeInt32LE(this._c,8),M.writeInt32LE(this._d,12),M.writeInt32LE(this._e,16),M};function N(M,T){return M<>>32-T}function F(M,T,h,y,g,f,u,d){return N(M+(T^h^y)+f+u|0,d)+g|0}function V(M,T,h,y,g,f,u,d){return N(M+(T&h|~T&y)+f+u|0,d)+g|0}function D(M,T,h,y,g,f,u,d){return N(M+((T|~h)^y)+f+u|0,d)+g|0}function L(M,T,h,y,g,f,u,d){return N(M+(T&y|h&~y)+f+u|0,d)+g|0}function R(M,T,h,y,g,f,u,d){return N(M+(T^(h|~y))+f+u|0,d)+g|0}Q.exports=I}),wK=l1((A,Q)=>{var J=bA().Buffer;function K(C,U){this._block=J.alloc(C),this._finalSize=U,this._blockSize=C,this._len=0}K.prototype.update=function(C,U){typeof C=="string"&&(U=U||"utf8",C=J.from(C,U));for(var Y=this._block,Z=this._blockSize,X=C.length,E=this._len,H=0;H=this._finalSize&&(this._update(this._block),this._block.fill(0));var Y=this._len*8;if(Y<=4294967295)this._block.writeUInt32BE(Y,this._blockSize-4);else{var Z=(Y&4294967295)>>>0,X=(Y-Z)/4294967296;this._block.writeUInt32BE(X,this._blockSize-8),this._block.writeUInt32BE(Z,this._blockSize-4)}this._update(this._block);var E=this._hash();return C?E.toString(C):E},K.prototype._update=function(){throw new Error("_update must be implemented by subclass")},Q.exports=K}),l61=l1((A,Q)=>{var J=MA(),K=wK(),C=bA().Buffer,U=[1518500249,1859775393,-1894007588,-899497514],Y=new Array(80);function Z(){this.init(),this._w=Y,K.call(this,64,56)}J(Z,K),Z.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function X($){return $<<5|$>>>27}function E($){return $<<30|$>>>2}function H($,I,N,F){return $===0?I&N|~I&F:$===2?I&N|I&F|N&F:I^N^F}Z.prototype._update=function($){for(var I=this._w,N=this._a|0,F=this._b|0,V=this._c|0,D=this._d|0,L=this._e|0,R=0;R<16;++R)I[R]=$.readInt32BE(R*4);for(;R<80;++R)I[R]=I[R-3]^I[R-8]^I[R-14]^I[R-16];for(var M=0;M<80;++M){var T=~~(M/20),h=X(N)+H(T,F,V,D)+L+I[M]+U[T]|0;L=D,D=V,V=E(F),F=N,N=h}this._a=N+this._a|0,this._b=F+this._b|0,this._c=V+this._c|0,this._d=D+this._d|0,this._e=L+this._e|0},Z.prototype._hash=function(){var $=C.allocUnsafe(20);return $.writeInt32BE(this._a|0,0),$.writeInt32BE(this._b|0,4),$.writeInt32BE(this._c|0,8),$.writeInt32BE(this._d|0,12),$.writeInt32BE(this._e|0,16),$},Q.exports=Z}),n61=l1((A,Q)=>{var J=MA(),K=wK(),C=bA().Buffer,U=[1518500249,1859775393,-1894007588,-899497514],Y=new Array(80);function Z(){this.init(),this._w=Y,K.call(this,64,56)}J(Z,K),Z.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function X(I){return I<<1|I>>>31}function E(I){return I<<5|I>>>27}function H(I){return I<<30|I>>>2}function $(I,N,F,V){return I===0?N&F|~N&V:I===2?N&F|N&V|F&V:N^F^V}Z.prototype._update=function(I){for(var N=this._w,F=this._a|0,V=this._b|0,D=this._c|0,L=this._d|0,R=this._e|0,M=0;M<16;++M)N[M]=I.readInt32BE(M*4);for(;M<80;++M)N[M]=X(N[M-3]^N[M-8]^N[M-14]^N[M-16]);for(var T=0;T<80;++T){var h=~~(T/20),y=E(F)+$(h,V,D,L)+R+N[T]+U[h]|0;R=L,L=D,D=H(V),V=F,F=y}this._a=F+this._a|0,this._b=V+this._b|0,this._c=D+this._c|0,this._d=L+this._d|0,this._e=R+this._e|0},Z.prototype._hash=function(){var I=C.allocUnsafe(20);return I.writeInt32BE(this._a|0,0),I.writeInt32BE(this._b|0,4),I.writeInt32BE(this._c|0,8),I.writeInt32BE(this._d|0,12),I.writeInt32BE(this._e|0,16),I},Q.exports=Z}),Tx=l1((A,Q)=>{var J=MA(),K=wK(),C=bA().Buffer,U=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Y=new Array(64);function Z(){this.init(),this._w=Y,K.call(this,64,56)}J(Z,K),Z.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function X(F,V,D){return D^F&(V^D)}function E(F,V,D){return F&V|D&(F|V)}function H(F){return(F>>>2|F<<30)^(F>>>13|F<<19)^(F>>>22|F<<10)}function $(F){return(F>>>6|F<<26)^(F>>>11|F<<21)^(F>>>25|F<<7)}function I(F){return(F>>>7|F<<25)^(F>>>18|F<<14)^F>>>3}function N(F){return(F>>>17|F<<15)^(F>>>19|F<<13)^F>>>10}Z.prototype._update=function(F){for(var V=this._w,D=this._a|0,L=this._b|0,R=this._c|0,M=this._d|0,T=this._e|0,h=this._f|0,y=this._g|0,g=this._h|0,f=0;f<16;++f)V[f]=F.readInt32BE(f*4);for(;f<64;++f)V[f]=N(V[f-2])+V[f-7]+I(V[f-15])+V[f-16]|0;for(var u=0;u<64;++u){var d=g+$(T)+X(T,h,y)+U[u]+V[u]|0,n=H(D)+E(D,L,R)|0;g=y,y=h,h=T,T=M+d|0,M=R,R=L,L=D,D=d+n|0}this._a=D+this._a|0,this._b=L+this._b|0,this._c=R+this._c|0,this._d=M+this._d|0,this._e=T+this._e|0,this._f=h+this._f|0,this._g=y+this._g|0,this._h=g+this._h|0},Z.prototype._hash=function(){var F=C.allocUnsafe(32);return F.writeInt32BE(this._a,0),F.writeInt32BE(this._b,4),F.writeInt32BE(this._c,8),F.writeInt32BE(this._d,12),F.writeInt32BE(this._e,16),F.writeInt32BE(this._f,20),F.writeInt32BE(this._g,24),F.writeInt32BE(this._h,28),F},Q.exports=Z}),s61=l1((A,Q)=>{var J=MA(),K=Tx(),C=wK(),U=bA().Buffer,Y=new Array(64);function Z(){this.init(),this._w=Y,C.call(this,64,56)}J(Z,K),Z.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this},Z.prototype._hash=function(){var X=U.allocUnsafe(28);return X.writeInt32BE(this._a,0),X.writeInt32BE(this._b,4),X.writeInt32BE(this._c,8),X.writeInt32BE(this._d,12),X.writeInt32BE(this._e,16),X.writeInt32BE(this._f,20),X.writeInt32BE(this._g,24),X},Q.exports=Z}),kx=l1((A,Q)=>{var J=MA(),K=wK(),C=bA().Buffer,U=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],Y=new Array(160);function Z(){this.init(),this._w=Y,K.call(this,128,112)}J(Z,K),Z.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function X(L,R,M){return M^L&(R^M)}function E(L,R,M){return L&R|M&(L|R)}function H(L,R){return(L>>>28|R<<4)^(R>>>2|L<<30)^(R>>>7|L<<25)}function $(L,R){return(L>>>14|R<<18)^(L>>>18|R<<14)^(R>>>9|L<<23)}function I(L,R){return(L>>>1|R<<31)^(L>>>8|R<<24)^L>>>7}function N(L,R){return(L>>>1|R<<31)^(L>>>8|R<<24)^(L>>>7|R<<25)}function F(L,R){return(L>>>19|R<<13)^(R>>>29|L<<3)^L>>>6}function V(L,R){return(L>>>19|R<<13)^(R>>>29|L<<3)^(L>>>6|R<<26)}function D(L,R){return L>>>0>>0?1:0}Z.prototype._update=function(L){for(var R=this._w,M=this._ah|0,T=this._bh|0,h=this._ch|0,y=this._dh|0,g=this._eh|0,f=this._fh|0,u=this._gh|0,d=this._hh|0,n=this._al|0,B=this._bl|0,q=this._cl|0,P=this._dl|0,O=this._el|0,w=this._fl|0,k=this._gl|0,S=this._hl|0,_=0;_<32;_+=2)R[_]=L.readInt32BE(_*4),R[_+1]=L.readInt32BE(_*4+4);for(;_<160;_+=2){var W=R[_-30],j=R[_-30+1],b=I(W,j),p=N(j,W);W=R[_-4],j=R[_-4+1];var s=F(W,j),r=V(j,W),A1=R[_-14],Q1=R[_-14+1],e=R[_-32],t=R[_-32+1],U1=p+Q1|0,O1=b+A1+D(U1,p)|0;U1=U1+r|0,O1=O1+s+D(U1,r)|0,U1=U1+t|0,O1=O1+e+D(U1,t)|0,R[_]=O1,R[_+1]=U1}for(var E1=0;E1<160;E1+=2){O1=R[E1],U1=R[E1+1];var Y1=E(M,T,h),i=E(n,B,q),c=H(M,n),o=H(n,M),C1=$(g,O),q1=$(O,g),Z1=U[E1],j1=U[E1+1],H1=X(g,f,u),B1=X(O,w,k),k1=S+q1|0,D1=d+C1+D(k1,S)|0;k1=k1+B1|0,D1=D1+H1+D(k1,B1)|0,k1=k1+j1|0,D1=D1+Z1+D(k1,j1)|0,k1=k1+U1|0,D1=D1+O1+D(k1,U1)|0;var G1=o+i|0,w1=c+Y1+D(G1,o)|0;d=u,S=k,u=f,k=w,f=g,w=O,O=P+k1|0,g=y+D1+D(O,P)|0,y=h,P=q,h=T,q=B,T=M,B=n,n=k1+G1|0,M=D1+w1+D(n,k1)|0}this._al=this._al+n|0,this._bl=this._bl+B|0,this._cl=this._cl+q|0,this._dl=this._dl+P|0,this._el=this._el+O|0,this._fl=this._fl+w|0,this._gl=this._gl+k|0,this._hl=this._hl+S|0,this._ah=this._ah+M+D(this._al,n)|0,this._bh=this._bh+T+D(this._bl,B)|0,this._ch=this._ch+h+D(this._cl,q)|0,this._dh=this._dh+y+D(this._dl,P)|0,this._eh=this._eh+g+D(this._el,O)|0,this._fh=this._fh+f+D(this._fl,w)|0,this._gh=this._gh+u+D(this._gl,k)|0,this._hh=this._hh+d+D(this._hl,S)|0},Z.prototype._hash=function(){var L=C.allocUnsafe(64);function R(M,T,h){L.writeInt32BE(M,h),L.writeInt32BE(T,h+4)}return R(this._ah,this._al,0),R(this._bh,this._bl,8),R(this._ch,this._cl,16),R(this._dh,this._dl,24),R(this._eh,this._el,32),R(this._fh,this._fl,40),R(this._gh,this._gl,48),R(this._hh,this._hl,56),L},Q.exports=Z}),o61=l1((A,Q)=>{var J=MA(),K=kx(),C=wK(),U=bA().Buffer,Y=new Array(160);function Z(){this.init(),this._w=Y,C.call(this,128,112)}J(Z,K),Z.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this},Z.prototype._hash=function(){var X=U.allocUnsafe(48);function E(H,$,I){X.writeInt32BE(H,I),X.writeInt32BE($,I+4)}return E(this._ah,this._al,0),E(this._bh,this._bl,8),E(this._ch,this._cl,16),E(this._dh,this._dl,24),E(this._eh,this._el,32),E(this._fh,this._fl,40),X},Q.exports=Z}),vN=l1((J,Q)=>{var J=Q.exports=function(K){K=K.toLowerCase();var C=J[K];if(!C)throw new Error(K+" is not supported (we accept pull requests)");return new C};J.sha=l61(),J.sha1=n61(),J.sha224=s61(),J.sha256=Tx(),J.sha384=o61(),J.sha512=kx()}),N8=l1((A,Q)=>{Q.exports={ArrayIsArray(J){return Array.isArray(J)},ArrayPrototypeIncludes(J,K){return J.includes(K)},ArrayPrototypeIndexOf(J,K){return J.indexOf(K)},ArrayPrototypeJoin(J,K){return J.join(K)},ArrayPrototypeMap(J,K){return J.map(K)},ArrayPrototypePop(J,K){return J.pop(K)},ArrayPrototypePush(J,K){return J.push(K)},ArrayPrototypeSlice(J,K,C){return J.slice(K,C)},Error,FunctionPrototypeCall(J,K,...C){return J.call(K,...C)},FunctionPrototypeSymbolHasInstance(J,K){return Function.prototype[Symbol.hasInstance].call(J,K)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(J,K){return Object.defineProperties(J,K)},ObjectDefineProperty(J,K,C){return Object.defineProperty(J,K,C)},ObjectGetOwnPropertyDescriptor(J,K){return Object.getOwnPropertyDescriptor(J,K)},ObjectKeys(J){return Object.keys(J)},ObjectSetPrototypeOf(J,K){return Object.setPrototypeOf(J,K)},Promise,PromisePrototypeCatch(J,K){return J.catch(K)},PromisePrototypeThen(J,K,C){return J.then(K,C)},PromiseReject(J){return Promise.reject(J)},ReflectApply:Reflect.apply,RegExpPrototypeTest(J,K){return J.test(K)},SafeSet:Set,String,StringPrototypeSlice(J,K,C){return J.slice(K,C)},StringPrototypeToLowerCase(J){return J.toLowerCase()},StringPrototypeToUpperCase(J){return J.toUpperCase()},StringPrototypeTrim(J){return J.trim()},Symbol,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,TypedArrayPrototypeSet(J,K,C){return J.set(K,C)},Uint8Array}}),b3=l1((A,Q)=>{var J=A6(),K=Object.getPrototypeOf(async function(){}).constructor,C=globalThis.Blob||J.Blob,U=typeof C<"u"?function(Z){return Z instanceof C}:function(Z){return!1},Y=class extends Error{constructor(Z){if(!Array.isArray(Z))throw new TypeError(`Expected input to be an Array, got ${typeof Z}`);let X="";for(let E=0;E{Z=E,X=H}),resolve:Z,reject:X}},promisify(Z){return new Promise((X,E)=>{Z((H,...$)=>H?E(H):X(...$))})},debuglog(){return function(){}},format(Z,...X){return Z.replace(/%([sdifj])/g,function(...[E,H]){let $=X.shift();return H==="f"?$.toFixed(6):H==="j"?JSON.stringify($):H==="s"&&typeof $=="object"?`${$.constructor!==Object?$.constructor.name:""} {}`.trim():$.toString()})},inspect(Z){switch(typeof Z){case"string":if(Z.includes("'"))if(Z.includes('"')){if(!Z.includes("`")&&!Z.includes("${"))return`\`${Z}\``}else return`"${Z}"`;return`'${Z}'`;case"number":return isNaN(Z)?"NaN":Object.is(Z,-0)?String(Z):Z;case"bigint":return`${String(Z)}n`;case"boolean":case"undefined":return String(Z);case"object":return"{}"}},types:{isAsyncFunction(Z){return Z instanceof K},isArrayBufferView(Z){return ArrayBuffer.isView(Z)}},isBlob:U},Q.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),xN=l1((A,Q)=>{var{AbortController:J,AbortSignal:K}=typeof self<"u"?self:typeof window<"u"?window:void 0;Q.exports=J,Q.exports.AbortSignal=K,Q.exports.default=J}),v6=l1((A,Q)=>{var{format:J,inspect:K,AggregateError:C}=b3(),U=globalThis.AggregateError||C,Y=Symbol("kIsNodeError"),Z=["string","function","number","object","Function","Object","boolean","bigint","symbol"],X=/^([A-Z][a-z0-9]*)+$/,E="__node_internal_",H={};function $(R,M){if(!R)throw new H.ERR_INTERNAL_ASSERTION(M)}function I(R){let M="",T=R.length,h=R[0]==="-"?1:0;for(;T>=h+4;T-=3)M=`_${R.slice(T-3,T)}${M}`;return`${R.slice(0,T)}${M}`}function N(R,M,T){if(typeof M=="function")return $(M.length<=T.length,`Code: ${R}; The provided arguments length (${T.length}) does not match the required ones (${M.length}).`),M(...T);let h=(M.match(/%[dfijoOs]/g)||[]).length;return $(h===T.length,`Code: ${R}; The provided arguments length (${T.length}) does not match the required ones (${h}).`),T.length===0?M:J(M,...T)}function F(R,M,T){T||(T=Error);class h extends T{constructor(...y){super(N(R,M,y))}toString(){return`${this.name} [${R}]: ${this.message}`}}Object.defineProperties(h.prototype,{name:{value:T.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${R}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),h.prototype.code=R,h.prototype[Y]=!0,H[R]=h}function V(R){let M=E+R.name;return Object.defineProperty(R,"name",{value:M}),R}function D(R,M){if(R&&M&&R!==M){if(Array.isArray(M.errors))return M.errors.push(R),M;let T=new U([M,R],M.message);return T.code=M.code,T}return R||M}var L=class extends Error{constructor(R="The operation was aborted",M=void 0){if(M!==void 0&&typeof M!="object")throw new H.ERR_INVALID_ARG_TYPE("options","Object",M);super(R,M),this.code="ABORT_ERR",this.name="AbortError"}};F("ERR_ASSERTION","%s",Error),F("ERR_INVALID_ARG_TYPE",(R,M,T)=>{$(typeof R=="string","'name' must be a string"),Array.isArray(M)||(M=[M]);let h="The ";R.endsWith(" argument")?h+=`${R} `:h+=`"${R}" ${R.includes(".")?"property":"argument"} `,h+="must be ";let y=[],g=[],f=[];for(let d of M)$(typeof d=="string","All expected entries have to be of type string"),Z.includes(d)?y.push(d.toLowerCase()):X.test(d)?g.push(d):($(d!=="object",'The value "object" should be written as "Object"'),f.push(d));if(g.length>0){let d=y.indexOf("object");d!==-1&&(y.splice(y,d,1),g.push("Object"))}if(y.length>0){switch(y.length){case 1:h+=`of type ${y[0]}`;break;case 2:h+=`one of type ${y[0]} or ${y[1]}`;break;default:{let d=y.pop();h+=`one of type ${y.join(", ")}, or ${d}`}}(g.length>0||f.length>0)&&(h+=" or ")}if(g.length>0){switch(g.length){case 1:h+=`an instance of ${g[0]}`;break;case 2:h+=`an instance of ${g[0]} or ${g[1]}`;break;default:{let d=g.pop();h+=`an instance of ${g.join(", ")}, or ${d}`}}f.length>0&&(h+=" or ")}switch(f.length){case 0:break;case 1:f[0].toLowerCase()!==f[0]&&(h+="an "),h+=`${f[0]}`;break;case 2:h+=`one of ${f[0]} or ${f[1]}`;break;default:{let d=f.pop();h+=`one of ${f.join(", ")}, or ${d}`}}if(T==null)h+=`. Received ${T}`;else if(typeof T=="function"&&T.name)h+=`. Received function ${T.name}`;else if(typeof T=="object"){var u;(u=T.constructor)!==null&&u!==void 0&&u.name?h+=`. Received an instance of ${T.constructor.name}`:h+=`. Received ${K(T,{depth:-1})}`}else{let d=K(T,{colors:!1});d.length>25&&(d=`${d.slice(0,25)}...`),h+=`. Received type ${typeof T} (${d})`}return h},TypeError),F("ERR_INVALID_ARG_VALUE",(R,M,T="is invalid")=>{let h=K(M);return h.length>128&&(h=h.slice(0,128)+"..."),`The ${R.includes(".")?"property":"argument"} '${R}' ${T}. Received ${h}`},TypeError),F("ERR_INVALID_RETURN_VALUE",(R,M,T)=>{var h;let y=T!=null&&(h=T.constructor)!==null&&h!==void 0&&h.name?`instance of ${T.constructor.name}`:`type ${typeof T}`;return`Expected ${R} to be returned from the "${M}" function but got ${y}.`},TypeError),F("ERR_MISSING_ARGS",(...R)=>{$(R.length>0,"At least one arg needs to be specified");let M,T=R.length;switch(R=(Array.isArray(R)?R:[R]).map((h)=>`"${h}"`).join(" or "),T){case 1:M+=`The ${R[0]} argument`;break;case 2:M+=`The ${R[0]} and ${R[1]} arguments`;break;default:{let h=R.pop();M+=`The ${R.join(", ")}, and ${h} arguments`}break}return`${M} must be specified`},TypeError),F("ERR_OUT_OF_RANGE",(R,M,T)=>{$(M,'Missing "range" argument');let h;return Number.isInteger(T)&&Math.abs(T)>4294967296?h=I(String(T)):typeof T=="bigint"?(h=String(T),(T>2n**32n||T<-(2n**32n))&&(h=I(h)),h+="n"):h=K(T),`The value of "${R}" is out of range. It must be ${M}. Received ${h}`},RangeError),F("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),F("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),F("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),F("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),F("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),F("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),F("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),F("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),F("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),F("ERR_STREAM_WRITE_AFTER_END","write after end",Error),F("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),Q.exports={AbortError:L,aggregateTwoErrors:V(D),hideStackFrames:V,codes:H}}),iE=l1((A,Q)=>{var{ArrayIsArray:J,ArrayPrototypeIncludes:K,ArrayPrototypeJoin:C,ArrayPrototypeMap:U,NumberIsInteger:Y,NumberIsNaN:Z,NumberMAX_SAFE_INTEGER:X,NumberMIN_SAFE_INTEGER:E,NumberParseInt:H,ObjectPrototypeHasOwnProperty:$,RegExpPrototypeExec:I,String:N,StringPrototypeToUpperCase:F,StringPrototypeTrim:V}=N8(),{hideStackFrames:D,codes:{ERR_SOCKET_BAD_PORT:L,ERR_INVALID_ARG_TYPE:R,ERR_INVALID_ARG_VALUE:M,ERR_OUT_OF_RANGE:T,ERR_UNKNOWN_SIGNAL:h}}=v6(),{normalizeEncoding:y}=b3(),{isAsyncFunction:g,isArrayBufferView:f}=b3().types,u={};function d(i){return i===(i|0)}function n(i){return i===i>>>0}var B=/^[0-7]+$/,q="must be a 32-bit unsigned integer or an octal string";function P(i,c,o){if(typeof i>"u"&&(i=o),typeof i=="string"){if(I(B,i)===null)throw new M(c,i,q);i=H(i,8)}return k(i,c),i}var O=D((i,c,o=E,C1=X)=>{if(typeof i!="number")throw new R(c,"number",i);if(!Y(i))throw new T(c,"an integer",i);if(iC1)throw new T(c,`>= ${o} && <= ${C1}`,i)}),w=D((i,c,o=-2147483648,C1=2147483647)=>{if(typeof i!="number")throw new R(c,"number",i);if(!Y(i))throw new T(c,"an integer",i);if(iC1)throw new T(c,`>= ${o} && <= ${C1}`,i)}),k=D((i,c,o=!1)=>{if(typeof i!="number")throw new R(c,"number",i);if(!Y(i))throw new T(c,"an integer",i);let C1=o?1:0,q1=4294967295;if(iq1)throw new T(c,`>= ${C1} && <= ${q1}`,i)});function S(i,c){if(typeof i!="string")throw new R(c,"string",i)}function _(i,c,o=void 0,C1){if(typeof i!="number")throw new R(c,"number",i);if(o!=null&&iC1||(o!=null||C1!=null)&&Z(i))throw new T(c,`${o!=null?`>= ${o}`:""}${o!=null&&C1!=null?" && ":""}${C1!=null?`<= ${C1}`:""}`,i)}var W=D((i,c,o)=>{if(!K(o,i)){let C1=C(U(o,(Z1)=>typeof Z1=="string"?`'${Z1}'`:N(Z1)),", "),q1="must be one of: "+C1;throw new M(c,i,q1)}});function j(i,c){if(typeof i!="boolean")throw new R(c,"boolean",i)}function b(i,c,o){return i==null||!$(i,c)?o:i[c]}var p=D((i,c,o=null)=>{let C1=b(o,"allowArray",!1),q1=b(o,"allowFunction",!1);if(!b(o,"nullable",!1)&&i===null||!C1&&J(i)||typeof i!="object"&&(!q1||typeof i!="function"))throw new R(c,"Object",i)}),s=D((i,c,o=0)=>{if(!J(i))throw new R(c,"Array",i);if(i.length{if(!f(i))throw new R(c,["Buffer","TypedArray","DataView"],i)});function Q1(i,c){let o=y(c),C1=i.length;if(o==="hex"&&C1%2!==0)throw new M("encoding",c,`is invalid for data of length ${C1}`)}function e(i,c="Port",o=!0){if(typeof i!="number"&&typeof i!="string"||typeof i=="string"&&V(i).length===0||+i!==+i>>>0||i>65535||i===0&&!o)throw new L(c,i,o);return i|0}var t=D((i,c)=>{if(i!==void 0&&(i===null||typeof i!="object"||!("aborted"in i)))throw new R(c,"AbortSignal",i)}),U1=D((i,c)=>{if(typeof i!="function")throw new R(c,"Function",i)}),O1=D((i,c)=>{if(typeof i!="function"||g(i))throw new R(c,"Function",i)}),E1=D((i,c)=>{if(i!==void 0)throw new R(c,"undefined",i)});function Y1(i,c,o){if(!K(o,i))throw new R(c,`('${C(o,"|")}')`,i)}Q.exports={isInt32:d,isUint32:n,parseFileMode:P,validateArray:s,validateBoolean:j,validateBuffer:A1,validateEncoding:Q1,validateFunction:U1,validateInt32:w,validateInteger:O,validateNumber:_,validateObject:p,validateOneOf:W,validatePlainFunction:O1,validatePort:e,validateSignalName:r,validateString:S,validateUint32:k,validateUndefined:E1,validateUnion:Y1,validateAbortSignal:t}}),Nx=l1((A,Q)=>{var J=Q.exports={},K,C;function U(){throw new Error("setTimeout has not been defined")}function Y(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?K=setTimeout:K=U}catch{K=U}try{typeof clearTimeout=="function"?C=clearTimeout:C=Y}catch{C=Y}})();function Z(L){if(K===setTimeout)return setTimeout(L,0);if((K===U||!K)&&setTimeout)return K=setTimeout,setTimeout(L,0);try{return K(L,0)}catch{try{return K.call(null,L,0)}catch{return K.call(this,L,0)}}}function X(L){if(C===clearTimeout)return clearTimeout(L);if((C===Y||!C)&&clearTimeout)return C=clearTimeout,clearTimeout(L);try{return C(L)}catch{try{return C.call(null,L)}catch{return C.call(this,L)}}}var E=[],H=!1,$,I=-1;function N(){!H||!$||(H=!1,$.length?E=$.concat(E):I=-1,E.length&&F())}function F(){if(!H){var L=Z(N);H=!0;for(var R=E.length;R;){for($=E,E=[];++I1)for(var M=1;MSx});UQ=PN(()=>{_N(p3,CQ(Nx())),Sx=CQ(Nx())}),ZQ=l1((A,Q)=>{var{Symbol:J,SymbolAsyncIterator:K,SymbolIterator:C}=N8(),U=J("kDestroyed"),Y=J("kIsErrored"),Z=J("kIsReadable"),X=J("kIsDisturbed");function E(O,w=!1){var k;return!!(O&&typeof O.pipe=="function"&&typeof O.on=="function"&&(!w||typeof O.pause=="function"&&typeof O.resume=="function")&&(!O._writableState||((k=O._readableState)===null||k===void 0?void 0:k.readable)!==!1)&&(!O._writableState||O._readableState))}function H(O){var w;return!!(O&&typeof O.write=="function"&&typeof O.on=="function"&&(!O._readableState||((w=O._writableState)===null||w===void 0?void 0:w.writable)!==!1))}function $(O){return!!(O&&typeof O.pipe=="function"&&O._readableState&&typeof O.on=="function"&&typeof O.write=="function")}function I(O){return O&&(O._readableState||O._writableState||typeof O.write=="function"&&typeof O.on=="function"||typeof O.pipe=="function"&&typeof O.on=="function")}function N(O,w){return O==null?!1:w===!0?typeof O[K]=="function":w===!1?typeof O[C]=="function":typeof O[K]=="function"||typeof O[C]=="function"}function F(O){if(!I(O))return null;let{_writableState:w,_readableState:k}=O,S=w||k;return!!(O.destroyed||O[U]||S!=null&&S.destroyed)}function V(O){if(!H(O))return null;if(O.writableEnded===!0)return!0;let w=O._writableState;return w!=null&&w.errored?!1:typeof w?.ended!="boolean"?null:w.ended}function D(O,w){if(!H(O))return null;if(O.writableFinished===!0)return!0;let k=O._writableState;return k!=null&&k.errored?!1:typeof k?.finished!="boolean"?null:!!(k.finished||w===!1&&k.ended===!0&&k.length===0)}function L(O){if(!E(O))return null;if(O.readableEnded===!0)return!0;let w=O._readableState;return!w||w.errored?!1:typeof w?.ended!="boolean"?null:w.ended}function R(O,w){if(!E(O))return null;let k=O._readableState;return k!=null&&k.errored?!1:typeof k?.endEmitted!="boolean"?null:!!(k.endEmitted||w===!1&&k.ended===!0&&k.length===0)}function M(O){return O&&O[Z]!=null?O[Z]:typeof O?.readable!="boolean"?null:F(O)?!1:E(O)&&O.readable&&!R(O)}function T(O){return typeof O?.writable!="boolean"?null:F(O)?!1:H(O)&&O.writable&&!V(O)}function h(O,w){return I(O)?F(O)?!0:!(w?.readable!==!1&&M(O)||w?.writable!==!1&&T(O)):null}function y(O){var w,k;return I(O)?O.writableErrored?O.writableErrored:(w=(k=O._writableState)===null||k===void 0?void 0:k.errored)!==null&&w!==void 0?w:null:null}function g(O){var w,k;return I(O)?O.readableErrored?O.readableErrored:(w=(k=O._readableState)===null||k===void 0?void 0:k.errored)!==null&&w!==void 0?w:null:null}function f(O){if(!I(O))return null;if(typeof O.closed=="boolean")return O.closed;let{_writableState:w,_readableState:k}=O;return typeof w?.closed=="boolean"||typeof k?.closed=="boolean"?w?.closed||k?.closed:typeof O._closed=="boolean"&&u(O)?O._closed:null}function u(O){return typeof O._closed=="boolean"&&typeof O._defaultKeepAlive=="boolean"&&typeof O._removedConnection=="boolean"&&typeof O._removedContLen=="boolean"}function d(O){return typeof O._sent100=="boolean"&&u(O)}function n(O){var w;return typeof O._consuming=="boolean"&&typeof O._dumped=="boolean"&&((w=O.req)===null||w===void 0?void 0:w.upgradeOrConnect)===void 0}function B(O){if(!I(O))return null;let{_writableState:w,_readableState:k}=O,S=w||k;return!S&&d(O)||!!(S&&S.autoDestroy&&S.emitClose&&S.closed===!1)}function q(O){var w;return!!(O&&((w=O[X])!==null&&w!==void 0?w:O.readableDidRead||O.readableAborted))}function P(O){var w,k,S,_,W,j,b,p,s,r;return!!(O&&((w=(k=(S=(_=(W=(j=O[Y])!==null&&j!==void 0?j:O.readableErrored)!==null&&W!==void 0?W:O.writableErrored)!==null&&_!==void 0?_:(b=O._readableState)===null||b===void 0?void 0:b.errorEmitted)!==null&&S!==void 0?S:(p=O._writableState)===null||p===void 0?void 0:p.errorEmitted)!==null&&k!==void 0?k:(s=O._readableState)===null||s===void 0?void 0:s.errored)!==null&&w!==void 0?w:(r=O._writableState)===null||r===void 0?void 0:r.errored))}Q.exports={kDestroyed:U,isDisturbed:q,kIsDisturbed:X,isErrored:P,kIsErrored:Y,isReadable:M,kIsReadable:Z,isClosed:f,isDestroyed:F,isDuplexNodeStream:$,isFinished:h,isIterable:N,isReadableNodeStream:E,isReadableEnded:L,isReadableFinished:R,isReadableErrored:g,isNodeStream:I,isWritable:T,isWritableNodeStream:H,isWritableEnded:V,isWritableFinished:D,isWritableErrored:y,isServerRequest:n,isServerResponse:d,willEmitClose:B}}),BQ=l1((A,Q)=>{var J=(UQ(),_9(p3)),{AbortError:K,codes:C}=v6(),{ERR_INVALID_ARG_TYPE:U,ERR_STREAM_PREMATURE_CLOSE:Y}=C,{kEmptyObject:Z,once:X}=b3(),{validateAbortSignal:E,validateFunction:H,validateObject:$}=iE(),{Promise:I}=N8(),{isClosed:N,isReadable:F,isReadableNodeStream:V,isReadableFinished:D,isReadableErrored:L,isWritable:R,isWritableNodeStream:M,isWritableFinished:T,isWritableErrored:h,isNodeStream:y,willEmitClose:g}=ZQ();function f(B){return B.setHeader&&typeof B.abort=="function"}var u=()=>{};function d(B,q,P){var O,w;arguments.length===2?(P=q,q=Z):q==null?q=Z:$(q,"options"),H(P,"callback"),E(q.signal,"options.signal"),P=X(P);let k=(O=q.readable)!==null&&O!==void 0?O:V(B),S=(w=q.writable)!==null&&w!==void 0?w:M(B);if(!y(B))throw new U("stream","Stream",B);let{_writableState:_,_readableState:W}=B,j=()=>{B.writable||s()},b=g(B)&&V(B)===k&&M(B)===S,p=T(B,!1),s=()=>{p=!0,B.destroyed&&(b=!1),!(b&&(!B.readable||k))&&(!k||r)&&P.call(B)},r=D(B,!1),A1=()=>{r=!0,B.destroyed&&(b=!1),!(b&&(!B.writable||S))&&(!S||p)&&P.call(B)},Q1=(E1)=>{P.call(B,E1)},e=N(B),t=()=>{e=!0;let E1=h(B)||L(B);if(E1&&typeof E1!="boolean")return P.call(B,E1);if(k&&!r&&V(B,!0)&&!D(B,!1))return P.call(B,new Y);if(S&&!p&&!T(B,!1))return P.call(B,new Y);P.call(B)},U1=()=>{B.req.on("finish",s)};f(B)?(B.on("complete",s),b||B.on("abort",t),B.req?U1():B.on("request",U1)):S&&!_&&(B.on("end",j),B.on("close",j)),!b&&typeof B.aborted=="boolean"&&B.on("aborted",t),B.on("end",A1),B.on("finish",s),q.error!==!1&&B.on("error",Q1),B.on("close",t),e?J.nextTick(t):_!=null&&_.errorEmitted||W!=null&&W.errorEmitted?b||J.nextTick(t):(!k&&(!b||F(B))&&(p||R(B)===!1)||!S&&(!b||R(B))&&(r||F(B)===!1)||W&&B.req&&B.aborted)&&J.nextTick(t);let O1=()=>{P=u,B.removeListener("aborted",t),B.removeListener("complete",s),B.removeListener("abort",t),B.removeListener("request",U1),B.req&&B.req.removeListener("finish",s),B.removeListener("end",j),B.removeListener("close",j),B.removeListener("finish",s),B.removeListener("end",A1),B.removeListener("error",Q1),B.removeListener("close",t)};if(q.signal&&!e){let E1=()=>{let Y1=P;O1(),Y1.call(B,new K(void 0,{cause:q.signal.reason}))};if(q.signal.aborted)J.nextTick(E1);else{let Y1=P;P=X((...i)=>{q.signal.removeEventListener("abort",E1),Y1.apply(B,i)}),q.signal.addEventListener("abort",E1)}}return O1}function n(B,q){return new I((P,O)=>{d(B,q,(w)=>{w?O(w):P()})})}Q.exports=d,Q.exports.finished=n}),i61=l1((A,Q)=>{var J=globalThis.AbortController||xN().AbortController,{codes:{ERR_INVALID_ARG_TYPE:K,ERR_MISSING_ARGS:C,ERR_OUT_OF_RANGE:U},AbortError:Y}=v6(),{validateAbortSignal:Z,validateInteger:X,validateObject:E}=iE(),H=N8().Symbol("kWeak"),{finished:$}=BQ(),{ArrayPrototypePush:I,MathFloor:N,Number:F,NumberIsNaN:V,Promise:D,PromiseReject:L,PromisePrototypeThen:R,Symbol:M}=N8(),T=M("kEmpty"),h=M("kEof");function y(W,j){if(typeof W!="function")throw new K("fn",["Function","AsyncFunction"],W);j!=null&&E(j,"options"),j?.signal!=null&&Z(j.signal,"options.signal");let b=1;return j?.concurrency!=null&&(b=N(j.concurrency)),X(b,"concurrency",1),async function*(){var p,s;let r=new J,A1=this,Q1=[],e=r.signal,t={signal:e},U1=()=>r.abort();j!=null&&(p=j.signal)!==null&&p!==void 0&&p.aborted&&U1(),j==null||(s=j.signal)===null||s===void 0||s.addEventListener("abort",U1);let O1,E1,Y1=!1;function i(){Y1=!0}async function c(){try{for await(let q1 of A1){var o;if(Y1)return;if(e.aborted)throw new Y;try{q1=W(q1,t)}catch(Z1){q1=L(Z1)}q1!==T&&(typeof((o=q1)===null||o===void 0?void 0:o.catch)=="function"&&q1.catch(i),Q1.push(q1),O1&&(O1(),O1=null),!Y1&&Q1.length&&Q1.length>=b&&await new D((Z1)=>{E1=Z1}))}Q1.push(h)}catch(q1){let Z1=L(q1);R(Z1,void 0,i),Q1.push(Z1)}finally{var C1;Y1=!0,O1&&(O1(),O1=null),j==null||(C1=j.signal)===null||C1===void 0||C1.removeEventListener("abort",U1)}}c();try{for(;;){for(;Q1.length>0;){let o=await Q1[0];if(o===h)return;if(e.aborted)throw new Y;o!==T&&(yield o),Q1.shift(),E1&&(E1(),E1=null)}await new D((o)=>{O1=o})}}finally{r.abort(),Y1=!0,E1&&(E1(),E1=null)}}.call(this)}function g(W=void 0){return W!=null&&E(W,"options"),W?.signal!=null&&Z(W.signal,"options.signal"),async function*(){let j=0;for await(let p of this){var b;if(W!=null&&(b=W.signal)!==null&&b!==void 0&&b.aborted)throw new Y({cause:W.signal.reason});yield[j++,p]}}.call(this)}async function f(W,j=void 0){for await(let b of B.call(this,W,j))return!0;return!1}async function u(W,j=void 0){if(typeof W!="function")throw new K("fn",["Function","AsyncFunction"],W);return!await f.call(this,async(...b)=>!await W(...b),j)}async function d(W,j){for await(let b of B.call(this,W,j))return b}async function n(W,j){if(typeof W!="function")throw new K("fn",["Function","AsyncFunction"],W);async function b(p,s){return await W(p,s),T}for await(let p of y.call(this,b,j));}function B(W,j){if(typeof W!="function")throw new K("fn",["Function","AsyncFunction"],W);async function b(p,s){return await W(p,s)?p:T}return y.call(this,b,j)}var q=class extends C{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function P(W,j,b){var p;if(typeof W!="function")throw new K("reducer",["Function","AsyncFunction"],W);b!=null&&E(b,"options"),b?.signal!=null&&Z(b.signal,"options.signal");let s=arguments.length>1;if(b!=null&&(p=b.signal)!==null&&p!==void 0&&p.aborted){let t=new Y(void 0,{cause:b.signal.reason});throw this.once("error",()=>{}),await $(this.destroy(t)),t}let r=new J,A1=r.signal;if(b!=null&&b.signal){let t={once:!0,[H]:this};b.signal.addEventListener("abort",()=>r.abort(),t)}let Q1=!1;try{for await(let t of this){var e;if(Q1=!0,b!=null&&(e=b.signal)!==null&&e!==void 0&&e.aborted)throw new Y;s?j=await W(j,t,{signal:A1}):(j=t,s=!0)}if(!Q1&&!s)throw new q}finally{r.abort()}return j}async function O(W){W!=null&&E(W,"options"),W?.signal!=null&&Z(W.signal,"options.signal");let j=[];for await(let p of this){var b;if(W!=null&&(b=W.signal)!==null&&b!==void 0&&b.aborted)throw new Y(void 0,{cause:W.signal.reason});I(j,p)}return j}function w(W,j){let b=y.call(this,W,j);return async function*(){for await(let p of b)yield*p}.call(this)}function k(W){if(W=F(W),V(W))return 0;if(W<0)throw new U("number",">= 0",W);return W}function S(W,j=void 0){return j!=null&&E(j,"options"),j?.signal!=null&&Z(j.signal,"options.signal"),W=k(W),async function*(){var b;if(j!=null&&(b=j.signal)!==null&&b!==void 0&&b.aborted)throw new Y;for await(let s of this){var p;if(j!=null&&(p=j.signal)!==null&&p!==void 0&&p.aborted)throw new Y;W--<=0&&(yield s)}}.call(this)}function _(W,j=void 0){return j!=null&&E(j,"options"),j?.signal!=null&&Z(j.signal,"options.signal"),W=k(W),async function*(){var b;if(j!=null&&(b=j.signal)!==null&&b!==void 0&&b.aborted)throw new Y;for await(let s of this){var p;if(j!=null&&(p=j.signal)!==null&&p!==void 0&&p.aborted)throw new Y;if(W-- >0)yield s;else return}}.call(this)}Q.exports.streamReturningOperators={asIndexedPairs:g,drop:S,filter:B,flatMap:w,map:y,take:_},Q.exports.promiseReturningOperators={every:u,forEach:n,reduce:P,toArray:O,some:f,find:d}}),PK=l1((A,Q)=>{var J=(UQ(),_9(p3)),{aggregateTwoErrors:K,codes:{ERR_MULTIPLE_CALLBACK:C},AbortError:U}=v6(),{Symbol:Y}=N8(),{kDestroyed:Z,isDestroyed:X,isFinished:E,isServerRequest:H}=ZQ(),$=Y("kDestroy"),I=Y("kConstruct");function N(B,q,P){B&&(B.stack,q&&!q.errored&&(q.errored=B),P&&!P.errored&&(P.errored=B))}function F(B,q){let P=this._readableState,O=this._writableState,w=O||P;return O&&O.destroyed||P&&P.destroyed?(typeof q=="function"&&q(),this):(N(B,O,P),O&&(O.destroyed=!0),P&&(P.destroyed=!0),w.constructed?V(this,B,q):this.once($,function(k){V(this,K(k,B),q)}),this)}function V(B,q,P){let O=!1;function w(k){if(O)return;O=!0;let{_readableState:S,_writableState:_}=B;N(k,_,S),_&&(_.closed=!0),S&&(S.closed=!0),typeof P=="function"&&P(k),k?J.nextTick(D,B,k):J.nextTick(L,B)}try{B._destroy(q||null,w)}catch(k){w(k)}}function D(B,q){R(B,q),L(B)}function L(B){let{_readableState:q,_writableState:P}=B;P&&(P.closeEmitted=!0),q&&(q.closeEmitted=!0),(P&&P.emitClose||q&&q.emitClose)&&B.emit("close")}function R(B,q){let{_readableState:P,_writableState:O}=B;O&&O.errorEmitted||P&&P.errorEmitted||(O&&(O.errorEmitted=!0),P&&(P.errorEmitted=!0),B.emit("error",q))}function M(){let B=this._readableState,q=this._writableState;B&&(B.constructed=!0,B.closed=!1,B.closeEmitted=!1,B.destroyed=!1,B.errored=null,B.errorEmitted=!1,B.reading=!1,B.ended=B.readable===!1,B.endEmitted=B.readable===!1),q&&(q.constructed=!0,q.destroyed=!1,q.closed=!1,q.closeEmitted=!1,q.errored=null,q.errorEmitted=!1,q.finalCalled=!1,q.prefinished=!1,q.ended=q.writable===!1,q.ending=q.writable===!1,q.finished=q.writable===!1)}function T(B,q,P){let{_readableState:O,_writableState:w}=B;if(w&&w.destroyed||O&&O.destroyed)return this;O&&O.autoDestroy||w&&w.autoDestroy?B.destroy(q):q&&(q.stack,w&&!w.errored&&(w.errored=q),O&&!O.errored&&(O.errored=q),P?J.nextTick(R,B,q):R(B,q))}function h(B,q){if(typeof B._construct!="function")return;let{_readableState:P,_writableState:O}=B;P&&(P.constructed=!1),O&&(O.constructed=!1),B.once(I,q),!(B.listenerCount(I)>1)&&J.nextTick(y,B)}function y(B){let q=!1;function P(O){if(q){T(B,O??new C);return}q=!0;let{_readableState:w,_writableState:k}=B,S=k||w;w&&(w.constructed=!0),k&&(k.constructed=!0),S.destroyed?B.emit($,O):O?T(B,O,!0):J.nextTick(g,B)}try{B._construct(P)}catch(O){P(O)}}function g(B){B.emit(I)}function f(B){return B&&B.setHeader&&typeof B.abort=="function"}function u(B){B.emit("close")}function d(B,q){B.emit("error",q),J.nextTick(u,B)}function n(B,q){!B||X(B)||(!q&&!E(B)&&(q=new U),H(B)?(B.socket=null,B.destroy(q)):f(B)?B.abort():f(B.req)?B.req.abort():typeof B.destroy=="function"?B.destroy(q):typeof B.close=="function"?B.close():q?J.nextTick(d,B,q):J.nextTick(u,B),B.destroyed||(B[Z]=!0))}Q.exports={construct:h,destroyer:n,destroy:F,undestroy:M,errorOrDestroy:T}}),yN=l1((A,Q)=>{var{ArrayIsArray:J,ObjectSetPrototypeOf:K}=N8(),{EventEmitter:C}=YQ();function U(Z){C.call(this,Z)}K(U.prototype,C.prototype),K(U,C),U.prototype.pipe=function(Z,X){let E=this;function H(L){Z.writable&&Z.write(L)===!1&&E.pause&&E.pause()}E.on("data",H);function $(){E.readable&&E.resume&&E.resume()}Z.on("drain",$),!Z._isStdio&&(!X||X.end!==!1)&&(E.on("end",N),E.on("close",F));let I=!1;function N(){I||(I=!0,Z.end())}function F(){I||(I=!0,typeof Z.destroy=="function"&&Z.destroy())}function V(L){D(),C.listenerCount(this,"error")===0&&this.emit("error",L)}Y(E,"error",V),Y(Z,"error",V);function D(){E.removeListener("data",H),Z.removeListener("drain",$),E.removeListener("end",N),E.removeListener("close",F),E.removeListener("error",V),Z.removeListener("error",V),E.removeListener("end",D),E.removeListener("close",D),Z.removeListener("close",D)}return E.on("end",D),E.on("close",D),Z.on("close",D),Z.emit("pipe",E),Z};function Y(Z,X,E){if(typeof Z.prependListener=="function")return Z.prependListener(X,E);!Z._events||!Z._events[X]?Z.on(X,E):J(Z._events[X])?Z._events[X].unshift(E):Z._events[X]=[E,Z._events[X]]}Q.exports={Stream:U,prependListener:Y}}),hN=l1((A,Q)=>{var{AbortError:J,codes:K}=v6(),C=BQ(),{ERR_INVALID_ARG_TYPE:U}=K,Y=(X,E)=>{if(typeof X!="object"||!("aborted"in X))throw new U(E,"AbortSignal",X)};function Z(X){return!!(X&&typeof X.pipe=="function")}Q.exports.addAbortSignal=function(X,E){if(Y(X,"signal"),!Z(E))throw new U("stream","stream.Stream",E);return Q.exports.addAbortSignalNoValidate(X,E)},Q.exports.addAbortSignalNoValidate=function(X,E){if(typeof X!="object"||!("aborted"in X))return E;let H=()=>{E.destroy(new J(void 0,{cause:X.reason}))};return X.aborted?H():(X.addEventListener("abort",H),C(E,()=>X.removeEventListener("abort",H))),E}}),a61=l1((A,Q)=>{var{StringPrototypeSlice:J,SymbolIterator:K,TypedArrayPrototypeSet:C,Uint8Array:U}=N8(),{Buffer:Y}=A6(),{inspect:Z}=b3();Q.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(X){let E={data:X,next:null};this.length>0?this.tail.next=E:this.head=E,this.tail=E,++this.length}unshift(X){let E={data:X,next:this.head};this.length===0&&(this.tail=E),this.head=E,++this.length}shift(){if(this.length===0)return;let X=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,X}clear(){this.head=this.tail=null,this.length=0}join(X){if(this.length===0)return"";let E=this.head,H=""+E.data;for(;(E=E.next)!==null;)H+=X+E.data;return H}concat(X){if(this.length===0)return Y.alloc(0);let E=Y.allocUnsafe(X>>>0),H=this.head,$=0;for(;H;)C(E,H.data,$),$+=H.data.length,H=H.next;return E}consume(X,E){let H=this.head.data;if(XI.length)E+=I,X-=I.length;else{X===I.length?(E+=I,++$,H.next?this.head=H.next:this.head=this.tail=null):(E+=J(I,0,X),this.head=H,H.data=J(I,X));break}++$}while((H=H.next)!==null);return this.length-=$,E}_getBuffer(X){let E=Y.allocUnsafe(X),H=X,$=this.head,I=0;do{let N=$.data;if(X>N.length)C(E,N,H-X),X-=N.length;else{X===N.length?(C(E,N,H-X),++I,$.next?this.head=$.next:this.head=this.tail=null):(C(E,new U(N.buffer,N.byteOffset,X),H-X),this.head=$,$.data=N.slice(X));break}++I}while(($=$.next)!==null);return this.length-=I,E}[Symbol.for("nodejs.util.inspect.custom")](X,E){return Z(this,{...E,depth:0,customInspect:!1})}}}),gN=l1((A,Q)=>{var{MathFloor:J,NumberIsInteger:K}=N8(),{ERR_INVALID_ARG_VALUE:C}=v6().codes;function U(X,E,H){return X.highWaterMark!=null?X.highWaterMark:E?X[H]:null}function Y(X){return X?16:16384}function Z(X,E,H,$){let I=U(E,$,H);if(I!=null){if(!K(I)||I<0){let N=$?`options.${H}`:"options.highWaterMark";throw new C(N,I)}return J(I)}return Y(X.objectMode)}Q.exports={getHighWaterMark:Z,getDefaultHighWaterMark:Y}}),jx=l1((A,Q)=>{var J=(UQ(),_9(p3)),{PromisePrototypeThen:K,SymbolAsyncIterator:C,SymbolIterator:U}=N8(),{Buffer:Y}=A6(),{ERR_INVALID_ARG_TYPE:Z,ERR_STREAM_NULL_VALUES:X}=v6().codes;function E(H,$,I){let N;if(typeof $=="string"||$ instanceof Y)return new H({objectMode:!0,...I,read(){this.push($),this.push(null)}});let F;if($&&$[C])F=!0,N=$[C]();else if($&&$[U])F=!1,N=$[U]();else throw new Z("iterable",["Iterable"],$);let V=new H({objectMode:!0,highWaterMark:1,...I}),D=!1;V._read=function(){D||(D=!0,R())},V._destroy=function(M,T){K(L(M),()=>J.nextTick(T,M),(h)=>J.nextTick(T,h||M))};async function L(M){let T=M!=null,h=typeof N.throw=="function";if(T&&h){let{value:y,done:g}=await N.throw(M);if(await y,g)return}if(typeof N.return=="function"){let{value:y}=await N.return();await y}}async function R(){for(;;){try{let{value:M,done:T}=F?await N.next():N.next();if(T)V.push(null);else{let h=M&&typeof M.then=="function"?await M:M;if(h===null)throw D=!1,new X;if(V.push(h))continue;D=!1}}catch(M){V.destroy(M)}break}}return V}Q.exports=E}),aE=l1((A,Q)=>{var J=(UQ(),_9(p3)),{ArrayPrototypeIndexOf:K,NumberIsInteger:C,NumberIsNaN:U,NumberParseInt:Y,ObjectDefineProperties:Z,ObjectKeys:X,ObjectSetPrototypeOf:E,Promise:H,SafeSet:$,SymbolAsyncIterator:I,Symbol:N}=N8();Q.exports=b,b.ReadableState=j;var{EventEmitter:F}=YQ(),{Stream:V,prependListener:D}=yN(),{Buffer:L}=A6(),{addAbortSignal:R}=hN(),M=BQ(),T=b3().debuglog("stream",(G)=>{T=G}),h=a61(),y=PK(),{getHighWaterMark:g,getDefaultHighWaterMark:f}=gN(),{aggregateTwoErrors:u,codes:{ERR_INVALID_ARG_TYPE:d,ERR_METHOD_NOT_IMPLEMENTED:n,ERR_OUT_OF_RANGE:B,ERR_STREAM_PUSH_AFTER_EOF:q,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:P}}=v6(),{validateObject:O}=iE(),w=N("kPaused"),{StringDecoder:k}=TN(),S=jx();E(b.prototype,V.prototype),E(b,V);var _=()=>{},{errorOrDestroy:W}=y;function j(G,z,x){typeof x!="boolean"&&(x=z instanceof f3()),this.objectMode=!!(G&&G.objectMode),x&&(this.objectMode=this.objectMode||!!(G&&G.readableObjectMode)),this.highWaterMark=G?g(this,G,"readableHighWaterMark",x):f(!1),this.buffer=new h,this.length=0,this.pipes=[],this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.constructed=!0,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this[w]=null,this.errorEmitted=!1,this.emitClose=!G||G.emitClose!==!1,this.autoDestroy=!G||G.autoDestroy!==!1,this.destroyed=!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this.defaultEncoding=G&&G.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.multiAwaitDrain=!1,this.readingMore=!1,this.dataEmitted=!1,this.decoder=null,this.encoding=null,G&&G.encoding&&(this.decoder=new k(G.encoding),this.encoding=G.encoding)}function b(G){if(!(this instanceof b))return new b(G);let z=this instanceof f3();this._readableState=new j(G,this,z),G&&(typeof G.read=="function"&&(this._read=G.read),typeof G.destroy=="function"&&(this._destroy=G.destroy),typeof G.construct=="function"&&(this._construct=G.construct),G.signal&&!z&&R(G.signal,this)),V.call(this,G),y.construct(this,()=>{this._readableState.needReadable&&O1(this,this._readableState)})}b.prototype.destroy=y.destroy,b.prototype._undestroy=y.undestroy,b.prototype._destroy=function(G,z){z(G)},b.prototype[F.captureRejectionSymbol]=function(G){this.destroy(G)},b.prototype.push=function(G,z){return p(this,G,z,!1)},b.prototype.unshift=function(G,z){return p(this,G,z,!0)};function p(G,z,x,m){T("readableAddChunk",z);let l=G._readableState,a;if(l.objectMode||(typeof z=="string"?(x=x||l.defaultEncoding,l.encoding!==x&&(m&&l.encoding?z=L.from(z,x).toString(l.encoding):(z=L.from(z,x),x=""))):z instanceof L?x="":V._isUint8Array(z)?(z=V._uint8ArrayToBuffer(z),x=""):z!=null&&(a=new d("chunk",["string","Buffer","Uint8Array"],z))),a)W(G,a);else if(z===null)l.reading=!1,e(G,l);else if(l.objectMode||z&&z.length>0)if(m)if(l.endEmitted)W(G,new P);else{if(l.destroyed||l.errored)return!1;s(G,l,z,!0)}else if(l.ended)W(G,new q);else{if(l.destroyed||l.errored)return!1;l.reading=!1,l.decoder&&!x?(z=l.decoder.write(z),l.objectMode||z.length!==0?s(G,l,z,!1):O1(G,l)):s(G,l,z,!1)}else m||(l.reading=!1,O1(G,l));return!l.ended&&(l.length0?(z.multiAwaitDrain?z.awaitDrainWriters.clear():z.awaitDrainWriters=null,z.dataEmitted=!0,G.emit("data",x)):(z.length+=z.objectMode?1:x.length,m?z.buffer.unshift(x):z.buffer.push(x),z.needReadable&&t(G)),O1(G,z)}b.prototype.isPaused=function(){let G=this._readableState;return G[w]===!0||G.flowing===!1},b.prototype.setEncoding=function(G){let z=new k(G);this._readableState.decoder=z,this._readableState.encoding=this._readableState.decoder.encoding;let x=this._readableState.buffer,m="";for(let l of x)m+=z.write(l);return x.clear(),m!==""&&x.push(m),this._readableState.length=m.length,this};var r=1073741824;function A1(G){if(G>r)throw new B("size","<= 1GiB",G);return G--,G|=G>>>1,G|=G>>>2,G|=G>>>4,G|=G>>>8,G|=G>>>16,G++,G}function Q1(G,z){return G<=0||z.length===0&&z.ended?0:z.objectMode?1:U(G)?z.flowing&&z.length?z.buffer.first().length:z.length:G<=z.length?G:z.ended?z.length:0}b.prototype.read=function(G){T("read",G),G===void 0?G=NaN:C(G)||(G=Y(G,10));let z=this._readableState,x=G;if(G>z.highWaterMark&&(z.highWaterMark=A1(G)),G!==0&&(z.emittedReadable=!1),G===0&&z.needReadable&&((z.highWaterMark!==0?z.length>=z.highWaterMark:z.length>0)||z.ended))return T("read: emitReadable",z.length,z.ended),z.length===0&&z.ended?B1(this):t(this),null;if(G=Q1(G,z),G===0&&z.ended)return z.length===0&&B1(this),null;let m=z.needReadable;if(T("need readable",m),(z.length===0||z.length-G0?l=H1(G,z):l=null,l===null?(z.needReadable=z.length<=z.highWaterMark,G=0):(z.length-=G,z.multiAwaitDrain?z.awaitDrainWriters.clear():z.awaitDrainWriters=null),z.length===0&&(z.ended||(z.needReadable=!0),x!==G&&z.ended&&B1(this)),l!==null&&!z.errorEmitted&&!z.closeEmitted&&(z.dataEmitted=!0,this.emit("data",l)),l};function e(G,z){if(T("onEofChunk"),!z.ended){if(z.decoder){let x=z.decoder.end();x&&x.length&&(z.buffer.push(x),z.length+=z.objectMode?1:x.length)}z.ended=!0,z.sync?t(G):(z.needReadable=!1,z.emittedReadable=!0,U1(G))}}function t(G){let z=G._readableState;T("emitReadable",z.needReadable,z.emittedReadable),z.needReadable=!1,z.emittedReadable||(T("emitReadable",z.flowing),z.emittedReadable=!0,J.nextTick(U1,G))}function U1(G){let z=G._readableState;T("emitReadable_",z.destroyed,z.length,z.ended),!z.destroyed&&!z.errored&&(z.length||z.ended)&&(G.emit("readable"),z.emittedReadable=!1),z.needReadable=!z.flowing&&!z.ended&&z.length<=z.highWaterMark,q1(G)}function O1(G,z){!z.readingMore&&z.constructed&&(z.readingMore=!0,J.nextTick(E1,G,z))}function E1(G,z){for(;!z.reading&&!z.ended&&(z.length1&&m.pipes.includes(G)&&(T("false write response, pause",m.awaitDrainWriters.size),m.awaitDrainWriters.add(G)),x.pause()),F1||(F1=Y1(x,G),G.on("drain",F1))}x.on("data",$1);function $1(M1){T("ondata");let L1=G.write(M1);T("dest.write",L1),L1===!1&&W1()}function N1(M1){if(T("onerror",M1),z1(),G.removeListener("error",N1),G.listenerCount("error")===0){let L1=G._writableState||G._readableState;L1&&!L1.errorEmitted?W(G,M1):G.emit("error",M1)}}D(G,"error",N1);function _1(){G.removeListener("finish",J1),z1()}G.once("close",_1);function J1(){T("onfinish"),G.removeListener("close",_1),z1()}G.once("finish",J1);function z1(){T("unpipe"),x.unpipe(G)}return G.emit("pipe",x),G.writableNeedDrain===!0?m.flowing&&W1():m.flowing||(T("pipe resume"),x.resume()),G};function Y1(G,z){return function(){let x=G._readableState;x.awaitDrainWriters===z?(T("pipeOnDrain",1),x.awaitDrainWriters=null):x.multiAwaitDrain&&(T("pipeOnDrain",x.awaitDrainWriters.size),x.awaitDrainWriters.delete(z)),(!x.awaitDrainWriters||x.awaitDrainWriters.size===0)&&G.listenerCount("data")&&G.resume()}}b.prototype.unpipe=function(G){let z=this._readableState,x={hasUnpiped:!1};if(z.pipes.length===0)return this;if(!G){let l=z.pipes;z.pipes=[],this.pause();for(let a=0;a0,m.flowing!==!1&&this.resume()):G==="readable"&&!m.endEmitted&&!m.readableListening&&(m.readableListening=m.needReadable=!0,m.flowing=!1,m.emittedReadable=!1,T("on readable",m.length,m.reading),m.length?t(this):m.reading||J.nextTick(c,this)),x},b.prototype.addListener=b.prototype.on,b.prototype.removeListener=function(G,z){let x=V.prototype.removeListener.call(this,G,z);return G==="readable"&&J.nextTick(i,this),x},b.prototype.off=b.prototype.removeListener,b.prototype.removeAllListeners=function(G){let z=V.prototype.removeAllListeners.apply(this,arguments);return(G==="readable"||G===void 0)&&J.nextTick(i,this),z};function i(G){let z=G._readableState;z.readableListening=G.listenerCount("readable")>0,z.resumeScheduled&&z[w]===!1?z.flowing=!0:G.listenerCount("data")>0?G.resume():z.readableListening||(z.flowing=null)}function c(G){T("readable nexttick read 0"),G.read(0)}b.prototype.resume=function(){let G=this._readableState;return G.flowing||(T("resume"),G.flowing=!G.readableListening,o(this,G)),G[w]=!1,this};function o(G,z){z.resumeScheduled||(z.resumeScheduled=!0,J.nextTick(C1,G,z))}function C1(G,z){T("resume",z.reading),z.reading||G.read(0),z.resumeScheduled=!1,G.emit("resume"),q1(G),z.flowing&&!z.reading&&G.read(0)}b.prototype.pause=function(){return T("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(T("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[w]=!0,this};function q1(G){let z=G._readableState;for(T("flow",z.flowing);z.flowing&&G.read()!==null;);}b.prototype.wrap=function(G){let z=!1;G.on("data",(m)=>{!this.push(m)&&G.pause&&(z=!0,G.pause())}),G.on("end",()=>{this.push(null)}),G.on("error",(m)=>{W(this,m)}),G.on("close",()=>{this.destroy()}),G.on("destroy",()=>{this.destroy()}),this._read=()=>{z&&G.resume&&(z=!1,G.resume())};let x=X(G);for(let m=1;m{l=K1?u(l,K1):null,x(),x=_});try{for(;;){let K1=G.destroyed?null:G.read();if(K1!==null)yield K1;else{if(l)throw l;if(l===null)return;await new H(m)}}}catch(K1){throw l=u(l,K1),l}finally{(l||z?.destroyOnReturn!==!1)&&(l===void 0||G._readableState.autoDestroy)?y.destroyer(G,null):(G.off("readable",m),a())}}Z(b.prototype,{readable:{__proto__:null,get(){let G=this._readableState;return!!G&&G.readable!==!1&&!G.destroyed&&!G.errorEmitted&&!G.endEmitted},set(G){this._readableState&&(this._readableState.readable=!!G)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(G){this._readableState&&(this._readableState.flowing=G)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(G){!this._readableState||(this._readableState.destroyed=G)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),Z(j.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[w]!==!1},set(G){this[w]=!!G}}}),b._fromList=H1;function H1(G,z){if(z.length===0)return null;let x;return z.objectMode?x=z.buffer.shift():!G||G>=z.length?(z.decoder?x=z.buffer.join(""):z.buffer.length===1?x=z.buffer.first():x=z.buffer.concat(z.length),z.buffer.clear()):x=z.buffer.consume(G,z.decoder),x}function B1(G){let z=G._readableState;T("endReadable",z.endEmitted),z.endEmitted||(z.ended=!0,J.nextTick(k1,z,G))}function k1(G,z){if(T("endReadableNT",G.endEmitted,G.length),!G.errored&&!G.closeEmitted&&!G.endEmitted&&G.length===0){if(G.endEmitted=!0,z.emit("end"),z.writable&&z.allowHalfOpen===!1)J.nextTick(D1,z);else if(G.autoDestroy){let x=z._writableState;(!x||x.autoDestroy&&(x.finished||x.writable===!1))&&z.destroy()}}}function D1(G){G.writable&&!G.writableEnded&&!G.destroyed&&G.end()}b.from=function(G,z){return S(b,G,z)};var G1;function w1(){return G1===void 0&&(G1={}),G1}b.fromWeb=function(G,z){return w1().newStreamReadableFromReadableStream(G,z)},b.toWeb=function(G,z){return w1().newReadableStreamFromStreamReadable(G,z)},b.wrap=function(G,z){var x,m;return new b({objectMode:(x=(m=G.readableObjectMode)!==null&&m!==void 0?m:G.objectMode)!==null&&x!==void 0?x:!0,...z,destroy(l,a){y.destroyer(G,l),a(l)}}).wrap(G)}}),vx=l1((A,Q)=>{var J=(UQ(),_9(p3)),{ArrayPrototypeSlice:K,Error:C,FunctionPrototypeSymbolHasInstance:U,ObjectDefineProperty:Y,ObjectDefineProperties:Z,ObjectSetPrototypeOf:X,StringPrototypeToLowerCase:E,Symbol:H,SymbolHasInstance:$}=N8();Q.exports=k,k.WritableState=O;var{EventEmitter:I}=YQ(),N=yN().Stream,{Buffer:F}=A6(),V=PK(),{addAbortSignal:D}=hN(),{getHighWaterMark:L,getDefaultHighWaterMark:R}=gN(),{ERR_INVALID_ARG_TYPE:M,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_MULTIPLE_CALLBACK:h,ERR_STREAM_CANNOT_PIPE:y,ERR_STREAM_DESTROYED:g,ERR_STREAM_ALREADY_FINISHED:f,ERR_STREAM_NULL_VALUES:u,ERR_STREAM_WRITE_AFTER_END:d,ERR_UNKNOWN_ENCODING:n}=v6().codes,{errorOrDestroy:B}=V;X(k.prototype,N.prototype),X(k,N);function q(){}var P=H("kOnFinished");function O(c,o,C1){typeof C1!="boolean"&&(C1=o instanceof f3()),this.objectMode=!!(c&&c.objectMode),C1&&(this.objectMode=this.objectMode||!!(c&&c.writableObjectMode)),this.highWaterMark=c?L(this,c,"writableHighWaterMark",C1):R(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let q1=!!(c&&c.decodeStrings===!1);this.decodeStrings=!q1,this.defaultEncoding=c&&c.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=b.bind(void 0,o),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,w(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!c||c.emitClose!==!1,this.autoDestroy=!c||c.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[P]=[]}function w(c){c.buffered=[],c.bufferedIndex=0,c.allBuffers=!0,c.allNoop=!0}O.prototype.getBuffer=function(){return K(this.buffered,this.bufferedIndex)},Y(O.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function k(c){let o=this instanceof f3();if(!o&&!U(k,this))return new k(c);this._writableState=new O(c,this,o),c&&(typeof c.write=="function"&&(this._write=c.write),typeof c.writev=="function"&&(this._writev=c.writev),typeof c.destroy=="function"&&(this._destroy=c.destroy),typeof c.final=="function"&&(this._final=c.final),typeof c.construct=="function"&&(this._construct=c.construct),c.signal&&D(c.signal,this)),N.call(this,c),V.construct(this,()=>{let C1=this._writableState;C1.writing||A1(this,C1),U1(this,C1)})}Y(k,$,{__proto__:null,value:function(c){return U(this,c)?!0:this!==k?!1:c&&c._writableState instanceof O}}),k.prototype.pipe=function(){B(this,new y)};function S(c,o,C1,q1){let Z1=c._writableState;if(typeof C1=="function")q1=C1,C1=Z1.defaultEncoding;else{if(!C1)C1=Z1.defaultEncoding;else if(C1!=="buffer"&&!F.isEncoding(C1))throw new n(C1);typeof q1!="function"&&(q1=q)}if(o===null)throw new u;if(!Z1.objectMode)if(typeof o=="string")Z1.decodeStrings!==!1&&(o=F.from(o,C1),C1="buffer");else if(o instanceof F)C1="buffer";else if(N._isUint8Array(o))o=N._uint8ArrayToBuffer(o),C1="buffer";else throw new M("chunk",["string","Buffer","Uint8Array"],o);let j1;return Z1.ending?j1=new d:Z1.destroyed&&(j1=new g("write")),j1?(J.nextTick(q1,j1),B(c,j1,!0),j1):(Z1.pendingcb++,_(c,Z1,o,C1,q1))}k.prototype.write=function(c,o,C1){return S(this,c,o,C1)===!0},k.prototype.cork=function(){this._writableState.corked++},k.prototype.uncork=function(){let c=this._writableState;c.corked&&(c.corked--,c.writing||A1(this,c))},k.prototype.setDefaultEncoding=function(c){if(typeof c=="string"&&(c=E(c)),!F.isEncoding(c))throw new n(c);return this._writableState.defaultEncoding=c,this};function _(c,o,C1,q1,Z1){let j1=o.objectMode?1:C1.length;o.length+=j1;let H1=o.lengthC1.bufferedIndex&&A1(c,C1),q1?C1.afterWriteTickInfo!==null&&C1.afterWriteTickInfo.cb===Z1?C1.afterWriteTickInfo.count++:(C1.afterWriteTickInfo={count:1,cb:Z1,stream:c,state:C1},J.nextTick(p,C1.afterWriteTickInfo)):s(c,C1,1,Z1))}function p({stream:c,state:o,count:C1,cb:q1}){return o.afterWriteTickInfo=null,s(c,o,C1,q1)}function s(c,o,C1,q1){for(!o.ending&&!c.destroyed&&o.length===0&&o.needDrain&&(o.needDrain=!1,c.emit("drain"));C1-- >0;)o.pendingcb--,q1();o.destroyed&&r(o),U1(c,o)}function r(c){if(c.writing)return;for(let Z1=c.bufferedIndex;Z11&&c._writev){o.pendingcb-=j1-1;let B1=o.allNoop?q:(D1)=>{for(let G1=H1;G1256?(C1.splice(0,H1),o.bufferedIndex=0):o.bufferedIndex=H1}o.bufferProcessing=!1}k.prototype._write=function(c,o,C1){if(this._writev)this._writev([{chunk:c,encoding:o}],C1);else throw new T("_write()")},k.prototype._writev=null,k.prototype.end=function(c,o,C1){let q1=this._writableState;typeof c=="function"?(C1=c,c=null,o=null):typeof o=="function"&&(C1=o,o=null);let Z1;if(c!=null){let j1=S(this,c,o);j1 instanceof C&&(Z1=j1)}return q1.corked&&(q1.corked=1,this.uncork()),Z1||(!q1.errored&&!q1.ending?(q1.ending=!0,U1(this,q1,!0),q1.ended=!0):q1.finished?Z1=new f("end"):q1.destroyed&&(Z1=new g("end"))),typeof C1=="function"&&(Z1||q1.finished?J.nextTick(C1,Z1):q1[P].push(C1)),this};function Q1(c){return c.ending&&!c.destroyed&&c.constructed&&c.length===0&&!c.errored&&c.buffered.length===0&&!c.finished&&!c.writing&&!c.errorEmitted&&!c.closeEmitted}function e(c,o){let C1=!1;function q1(Z1){if(C1){B(c,Z1??h());return}if(C1=!0,o.pendingcb--,Z1){let j1=o[P].splice(0);for(let H1=0;H1{Q1(Z1)?O1(q1,Z1):Z1.pendingcb--},c,o)):Q1(o)&&(o.pendingcb++,O1(c,o))))}function O1(c,o){o.pendingcb--,o.finished=!0;let C1=o[P].splice(0);for(let q1=0;q1{var J=(UQ(),_9(p3)),K=A6(),{isReadable:C,isWritable:U,isIterable:Y,isNodeStream:Z,isReadableNodeStream:X,isWritableNodeStream:E,isDuplexNodeStream:H}=ZQ(),$=BQ(),{AbortError:I,codes:{ERR_INVALID_ARG_TYPE:N,ERR_INVALID_RETURN_VALUE:F}}=v6(),{destroyer:V}=PK(),D=f3(),L=aE(),{createDeferredPromise:R}=b3(),M=jx(),T=globalThis.Blob||K.Blob,h=typeof T<"u"?function(n){return n instanceof T}:function(n){return!1},y=globalThis.AbortController||xN().AbortController,{FunctionPrototypeCall:g}=N8(),f=class extends D{constructor(n){super(n),n?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),n?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};Q.exports=function n(B,q){if(H(B))return B;if(X(B))return d({readable:B});if(E(B))return d({writable:B});if(Z(B))return d({writable:!1,readable:!1});if(typeof B=="function"){let{value:O,write:w,final:k,destroy:S}=u(B);if(Y(O))return M(f,O,{objectMode:!0,write:w,final:k,destroy:S});let _=O?.then;if(typeof _=="function"){let W,j=g(_,O,(b)=>{if(b!=null)throw new F("nully","body",b)},(b)=>{V(W,b)});return W=new f({objectMode:!0,readable:!1,write:w,final(b){k(async()=>{try{await j,J.nextTick(b,null)}catch(p){J.nextTick(b,p)}})},destroy:S})}throw new F("Iterable, AsyncIterable or AsyncFunction",q,O)}if(h(B))return n(B.arrayBuffer());if(Y(B))return M(f,B,{objectMode:!0,writable:!1});if(typeof B?.writable=="object"||typeof B?.readable=="object"){let O=B!=null&&B.readable?X(B?.readable)?B?.readable:n(B.readable):void 0,w=B!=null&&B.writable?E(B?.writable)?B?.writable:n(B.writable):void 0;return d({readable:O,writable:w})}let P=B?.then;if(typeof P=="function"){let O;return g(P,B,(w)=>{w!=null&&O.push(w),O.push(null)},(w)=>{V(O,w)}),O=new f({objectMode:!0,writable:!1,read(){}})}throw new N(q,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],B)};function u(n){let{promise:B,resolve:q}=R(),P=new y,O=P.signal;return{value:n(async function*(){for(;;){let w=B;B=null;let{chunk:k,done:S,cb:_}=await w;if(J.nextTick(_),S)return;if(O.aborted)throw new I(void 0,{cause:O.reason});({promise:B,resolve:q}=R()),yield k}}(),{signal:O}),write(w,k,S){let _=q;q=null,_({chunk:w,done:!1,cb:S})},final(w){let k=q;q=null,k({done:!0,cb:w})},destroy(w,k){P.abort(),k(w)}}}function d(n){let B=n.readable&&typeof n.readable.read!="function"?L.wrap(n.readable):n.readable,q=n.writable,P=!!C(B),O=!!U(q),w,k,S,_,W;function j(b){let p=_;_=null,p?p(b):b?W.destroy(b):!P&&!O&&W.destroy()}return W=new f({readableObjectMode:!!(B!=null&&B.readableObjectMode),writableObjectMode:!!(q!=null&&q.writableObjectMode),readable:P,writable:O}),O&&($(q,(b)=>{O=!1,b&&V(B,b),j(b)}),W._write=function(b,p,s){q.write(b,p)?s():w=s},W._final=function(b){q.end(),k=b},q.on("drain",function(){if(w){let b=w;w=null,b()}}),q.on("finish",function(){if(k){let b=k;k=null,b()}})),P&&($(B,(b)=>{P=!1,b&&V(B,b),j(b)}),B.on("readable",function(){if(S){let b=S;S=null,b()}}),B.on("end",function(){W.push(null)}),W._read=function(){for(;;){let b=B.read();if(b===null){S=W._read;return}if(!W.push(b))return}}),W._destroy=function(b,p){!b&&_!==null&&(b=new I),S=null,w=null,k=null,_===null?p(b):(_=p,V(q,b),V(B,b))},W}}),f3=l1((A,Q)=>{var{ObjectDefineProperties:J,ObjectGetOwnPropertyDescriptor:K,ObjectKeys:C,ObjectSetPrototypeOf:U}=N8();Q.exports=X;var Y=aE(),Z=vx();U(X.prototype,Y.prototype),U(X,Y);{let I=C(Z.prototype);for(let N=0;N{var{ObjectSetPrototypeOf:J,Symbol:K}=N8();Q.exports=X;var{ERR_METHOD_NOT_IMPLEMENTED:C}=v6().codes,U=f3(),{getHighWaterMark:Y}=gN();J(X.prototype,U.prototype),J(X,U);var Z=K("kCallback");function X($){if(!(this instanceof X))return new X($);let I=$?Y(this,$,"readableHighWaterMark",!0):null;I===0&&($={...$,highWaterMark:null,readableHighWaterMark:I,writableHighWaterMark:$.writableHighWaterMark||0}),U.call(this,$),this._readableState.sync=!1,this[Z]=null,$&&(typeof $.transform=="function"&&(this._transform=$.transform),typeof $.flush=="function"&&(this._flush=$.flush)),this.on("prefinish",H)}function E($){typeof this._flush=="function"&&!this.destroyed?this._flush((I,N)=>{if(I){$?$(I):this.destroy(I);return}N!=null&&this.push(N),this.push(null),$&&$()}):(this.push(null),$&&$())}function H(){this._final!==E&&E.call(this)}X.prototype._final=E,X.prototype._transform=function($,I,N){throw new C("_transform()")},X.prototype._write=function($,I,N){let F=this._readableState,V=this._writableState,D=F.length;this._transform($,I,(L,R)=>{if(L){N(L);return}R!=null&&this.push(R),V.ended||D===F.length||F.length{var{ObjectSetPrototypeOf:J}=N8();Q.exports=C;var K=xx();J(C.prototype,K.prototype),J(C,K);function C(U){if(!(this instanceof C))return new C(U);K.call(this,U)}C.prototype._transform=function(U,Y,Z){Z(null,U)}}),bN=l1((A,Q)=>{var J=(UQ(),_9(p3)),{ArrayIsArray:K,Promise:C,SymbolAsyncIterator:U}=N8(),Y=BQ(),{once:Z}=b3(),X=PK(),E=f3(),{aggregateTwoErrors:H,codes:{ERR_INVALID_ARG_TYPE:$,ERR_INVALID_RETURN_VALUE:I,ERR_MISSING_ARGS:N,ERR_STREAM_DESTROYED:F,ERR_STREAM_PREMATURE_CLOSE:V},AbortError:D}=v6(),{validateFunction:L,validateAbortSignal:R}=iE(),{isIterable:M,isReadable:T,isReadableNodeStream:h,isNodeStream:y}=ZQ(),g=globalThis.AbortController||xN().AbortController,f,u;function d(S,_,W){let j=!1;S.on("close",()=>{j=!0});let b=Y(S,{readable:_,writable:W},(p)=>{j=!p});return{destroy:(p)=>{j||(j=!0,X.destroyer(S,p||new F("pipe")))},cleanup:b}}function n(S){return L(S[S.length-1],"streams[stream.length - 1]"),S.pop()}function B(S){if(M(S))return S;if(h(S))return q(S);throw new $("val",["Readable","Iterable","AsyncIterable"],S)}async function*q(S){u||(u=aE()),yield*u.prototype[U].call(S)}async function P(S,_,W,{end:j}){let b,p=null,s=(Q1)=>{if(Q1&&(b=Q1),p){let e=p;p=null,e()}},r=()=>new C((Q1,e)=>{b?e(b):p=()=>{b?e(b):Q1()}});_.on("drain",s);let A1=Y(_,{readable:!1},s);try{_.writableNeedDrain&&await r();for await(let Q1 of S)_.write(Q1)||await r();j&&_.end(),await r(),W()}catch(Q1){W(b!==Q1?H(b,Q1):Q1)}finally{A1(),_.off("drain",s)}}function O(...S){return w(S,Z(n(S)))}function w(S,_,W){if(S.length===1&&K(S[0])&&(S=S[0]),S.length<2)throw new N("streams");let j=new g,b=j.signal,p=W?.signal,s=[];R(p,"options.signal");function r(){O1(new D)}p?.addEventListener("abort",r);let A1,Q1,e=[],t=0;function U1(c){O1(c,--t===0)}function O1(c,o){if(c&&(!A1||A1.code==="ERR_STREAM_PREMATURE_CLOSE")&&(A1=c),!(!A1&&!o)){for(;e.length;)e.shift()(A1);p?.removeEventListener("abort",r),j.abort(),o&&(A1||s.forEach((C1)=>C1()),J.nextTick(_,A1,Q1))}}let E1;for(let c=0;c0,Z1=C1||W?.end!==!1,j1=c===S.length-1;if(y(o)){let H1=function(B1){B1&&B1.name!=="AbortError"&&B1.code!=="ERR_STREAM_PREMATURE_CLOSE"&&U1(B1)};var Y1=H1;if(Z1){let{destroy:B1,cleanup:k1}=d(o,C1,q1);e.push(B1),T(o)&&j1&&s.push(k1)}o.on("error",H1),T(o)&&j1&&s.push(()=>{o.removeListener("error",H1)})}if(c===0)if(typeof o=="function"){if(E1=o({signal:b}),!M(E1))throw new I("Iterable, AsyncIterable or Stream","source",E1)}else M(o)||h(o)?E1=o:E1=E.from(o);else if(typeof o=="function")if(E1=B(E1),E1=o(E1,{signal:b}),C1){if(!M(E1,!0))throw new I("AsyncIterable",`transform[${c-1}]`,E1)}else{var i;f||(f=yx());let H1=new f({objectMode:!0}),B1=(i=E1)===null||i===void 0?void 0:i.then;if(typeof B1=="function")t++,B1.call(E1,(G1)=>{Q1=G1,G1!=null&&H1.write(G1),Z1&&H1.end(),J.nextTick(U1)},(G1)=>{H1.destroy(G1),J.nextTick(U1,G1)});else if(M(E1,!0))t++,P(E1,H1,U1,{end:Z1});else throw new I("AsyncIterable or Promise","destination",E1);E1=H1;let{destroy:k1,cleanup:D1}=d(E1,!1,!0);e.push(k1),j1&&s.push(D1)}else if(y(o)){if(h(E1)){t+=2;let H1=k(E1,o,U1,{end:Z1});T(o)&&j1&&s.push(H1)}else if(M(E1))t++,P(E1,o,U1,{end:Z1});else throw new $("val",["Readable","Iterable","AsyncIterable"],E1);E1=o}else E1=E.from(o)}return(b!=null&&b.aborted||p!=null&&p.aborted)&&J.nextTick(r),E1}function k(S,_,W,{end:j}){let b=!1;return _.on("close",()=>{b||W(new V)}),S.pipe(_,{end:j}),j?S.once("end",()=>{b=!0,_.end()}):W(),Y(S,{readable:!0,writable:!1},(p)=>{let s=S._readableState;p&&p.code==="ERR_STREAM_PREMATURE_CLOSE"&&s&&s.ended&&!s.errored&&!s.errorEmitted?S.once("end",W).once("error",W):W(p)}),Y(_,{readable:!1,writable:!0},W)}Q.exports={pipelineImpl:w,pipeline:O}}),t61=l1((A,Q)=>{var{pipeline:J}=bN(),K=f3(),{destroyer:C}=PK(),{isNodeStream:U,isReadable:Y,isWritable:Z}=ZQ(),{AbortError:X,codes:{ERR_INVALID_ARG_VALUE:E,ERR_MISSING_ARGS:H}}=v6();Q.exports=function(...$){if($.length===0)throw new H("streams");if($.length===1)return K.from($[0]);let I=[...$];if(typeof $[0]=="function"&&($[0]=K.from($[0])),typeof $[$.length-1]=="function"){let g=$.length-1;$[g]=K.from($[g])}for(let g=0;g<$.length;++g)if(U($[g])){if(g<$.length-1&&!Y($[g]))throw new E(`streams[${g}]`,I[g],"must be readable");if(g>0&&!Z($[g]))throw new E(`streams[${g}]`,I[g],"must be writable")}let N,F,V,D,L;function R(g){let f=D;D=null,f?f(g):g?L.destroy(g):!y&&!h&&L.destroy()}let M=$[0],T=J($,R),h=!!Z(M),y=!!Y(T);return L=new K({writableObjectMode:!!(M!=null&&M.writableObjectMode),readableObjectMode:!!(T!=null&&T.writableObjectMode),writable:h,readable:y}),h&&(L._write=function(g,f,u){M.write(g,f)?u():N=u},L._final=function(g){M.end(),F=g},M.on("drain",function(){if(N){let g=N;N=null,g()}}),T.on("finish",function(){if(F){let g=F;F=null,g()}})),y&&(T.on("readable",function(){if(V){let g=V;V=null,g()}}),T.on("end",function(){L.push(null)}),L._read=function(){for(;;){let g=T.read();if(g===null){V=L._read;return}if(!L.push(g))return}}),L._destroy=function(g,f){!g&&D!==null&&(g=new X),V=null,N=null,F=null,D===null?f(g):(D=f,C(T,g))},L}}),hx=l1((A,Q)=>{var{ArrayPrototypePop:J,Promise:K}=N8(),{isIterable:C,isNodeStream:U}=ZQ(),{pipelineImpl:Y}=bN(),{finished:Z}=BQ();function X(...E){return new K((H,$)=>{let I,N,F=E[E.length-1];if(F&&typeof F=="object"&&!U(F)&&!C(F)){let V=J(E);I=V.signal,N=V.end}Y(E,(V,D)=>{V?$(V):H(D)},{signal:I,end:N})})}Q.exports={finished:Z,pipeline:X}}),e61=l1((A,Q)=>{var{Buffer:J}=A6(),{ObjectDefineProperty:K,ObjectKeys:C,ReflectApply:U}=N8(),{promisify:{custom:Y}}=b3(),{streamReturningOperators:Z,promiseReturningOperators:X}=i61(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:E}}=v6(),H=t61(),{pipeline:$}=bN(),{destroyer:I}=PK(),N=BQ(),F=hx(),V=ZQ(),D=Q.exports=yN().Stream;D.isDisturbed=V.isDisturbed,D.isErrored=V.isErrored,D.isReadable=V.isReadable,D.Readable=aE();for(let M of C(Z)){let T=function(...y){if(new.target)throw E();return D.Readable.from(U(h,this,y))};L=T;let h=Z[M];K(T,"name",{__proto__:null,value:h.name}),K(T,"length",{__proto__:null,value:h.length}),K(D.Readable.prototype,M,{__proto__:null,value:T,enumerable:!1,configurable:!0,writable:!0})}var L;for(let M of C(X)){let T=function(...y){if(new.target)throw E();return U(h,this,y)};L=T;let h=X[M];K(T,"name",{__proto__:null,value:h.name}),K(T,"length",{__proto__:null,value:h.length}),K(D.Readable.prototype,M,{__proto__:null,value:T,enumerable:!1,configurable:!0,writable:!0})}var L;D.Writable=vx(),D.Duplex=f3(),D.Transform=xx(),D.PassThrough=yx(),D.pipeline=$;var{addAbortSignal:R}=hN();D.addAbortSignal=R,D.finished=N,D.destroy=I,D.compose=H,K(D,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return F}}),K($,Y,{__proto__:null,enumerable:!0,get(){return F.pipeline}}),K(N,Y,{__proto__:null,enumerable:!0,get(){return F.finished}}),D.Stream=D,D._isUint8Array=function(M){return M instanceof Uint8Array},D._uint8ArrayToBuffer=function(M){return J.from(M.buffer,M.byteOffset,M.byteLength)}}),Lx=l1((A,Q)=>{var J=e61(),K=hx(),C=J.Readable.destroy;Q.exports=J.Readable,Q.exports._uint8ArrayToBuffer=J._uint8ArrayToBuffer,Q.exports._isUint8Array=J._isUint8Array,Q.exports.isDisturbed=J.isDisturbed,Q.exports.isErrored=J.isErrored,Q.exports.isReadable=J.isReadable,Q.exports.Readable=J.Readable,Q.exports.Writable=J.Writable,Q.exports.Duplex=J.Duplex,Q.exports.Transform=J.Transform,Q.exports.PassThrough=J.PassThrough,Q.exports.addAbortSignal=J.addAbortSignal,Q.exports.finished=J.finished,Q.exports.destroy=J.destroy,Q.exports.destroy=C,Q.exports.pipeline=J.pipeline,Q.exports.compose=J.compose,Object.defineProperty(J,"promises",{configurable:!0,enumerable:!0,get(){return K}}),Q.exports.Stream=J.Stream,Q.exports.default=Q.exports}),fN={};sE(fN,{default:()=>gx});A91=PN(()=>{_N(fN,CQ(Lx())),gx=CQ(Lx())}),t7=l1((A,Q)=>{var J=bA().Buffer,K=(A91(),_9(fN)).Transform,C=TN().StringDecoder,U=MA();function Y(Z){K.call(this),this.hashMode=typeof Z=="string",this.hashMode?this[Z]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}U(Y,K),Y.prototype.update=function(Z,X,E){typeof Z=="string"&&(Z=J.from(Z,X));var H=this._update(Z);return this.hashMode?this:(E&&(H=this._toString(H,E)),H)},Y.prototype.setAutoPadding=function(){},Y.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")},Y.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")},Y.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")},Y.prototype._transform=function(Z,X,E){var H;try{this.hashMode?this._update(Z):this.push(this._update(Z))}catch($){H=$}finally{E(H)}},Y.prototype._flush=function(Z){var X;try{this.push(this.__final())}catch(E){X=E}Z(X)},Y.prototype._finalOrDigest=function(Z){var X=this.__final()||J.alloc(0);return Z&&(X=this._toString(X,Z,!0)),X},Y.prototype._toString=function(Z,X,E){if(this._decoder||(this._decoder=new C(X),this._encoding=X),this._encoding!==X)throw new Error("can't switch encodings");var H=this._decoder.write(Z);return E&&(H+=this._decoder.end()),H},Q.exports=Y}),NU=l1((A,Q)=>{var J=MA(),K=SN(),C=jN(),U=vN(),Y=t7();function Z(X){Y.call(this,"digest"),this._hash=X}J(Z,Y),Z.prototype._update=function(X){this._hash.update(X)},Z.prototype._final=function(){return this._hash.digest()},Q.exports=function(X){return X=X.toLowerCase(),X==="md5"?new K:X==="rmd160"||X==="ripemd160"?new C:new Z(U(X))}}),Q91=l1((A,Q)=>{var J=MA(),K=bA().Buffer,C=t7(),U=K.alloc(128),Y=64;function Z(X,E){C.call(this,"digest"),typeof E=="string"&&(E=K.from(E)),this._alg=X,this._key=E,E.length>Y?E=X(E):E.length{var J=SN();Q.exports=function(K){return new J().update(K).digest()}}),fx=l1((A,Q)=>{var J=MA(),K=Q91(),C=t7(),U=bA().Buffer,Y=bx(),Z=jN(),X=vN(),E=U.alloc(128);function H($,I){C.call(this,"digest"),typeof I=="string"&&(I=U.from(I));var N=$==="sha512"||$==="sha384"?128:64;if(this._alg=$,this._key=I,I.length>N){var F=$==="rmd160"?new Z:X($);I=F.update(I).digest()}else I.length{Q.exports={sha224WithRSAEncryption:{sign:"rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},"RSA-SHA224":{sign:"ecdsa/rsa",hash:"sha224",id:"302d300d06096086480165030402040500041c"},sha256WithRSAEncryption:{sign:"rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},"RSA-SHA256":{sign:"ecdsa/rsa",hash:"sha256",id:"3031300d060960864801650304020105000420"},sha384WithRSAEncryption:{sign:"rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},"RSA-SHA384":{sign:"ecdsa/rsa",hash:"sha384",id:"3041300d060960864801650304020205000430"},sha512WithRSAEncryption:{sign:"rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA512":{sign:"ecdsa/rsa",hash:"sha512",id:"3051300d060960864801650304020305000440"},"RSA-SHA1":{sign:"rsa",hash:"sha1",id:"3021300906052b0e03021a05000414"},"ecdsa-with-SHA1":{sign:"ecdsa",hash:"sha1",id:""},sha256:{sign:"ecdsa",hash:"sha256",id:""},sha224:{sign:"ecdsa",hash:"sha224",id:""},sha384:{sign:"ecdsa",hash:"sha384",id:""},sha512:{sign:"ecdsa",hash:"sha512",id:""},"DSA-SHA":{sign:"dsa",hash:"sha1",id:""},"DSA-SHA1":{sign:"dsa",hash:"sha1",id:""},DSA:{sign:"dsa",hash:"sha1",id:""},"DSA-WITH-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-SHA224":{sign:"dsa",hash:"sha224",id:""},"DSA-WITH-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-SHA256":{sign:"dsa",hash:"sha256",id:""},"DSA-WITH-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-SHA384":{sign:"dsa",hash:"sha384",id:""},"DSA-WITH-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-SHA512":{sign:"dsa",hash:"sha512",id:""},"DSA-RIPEMD160":{sign:"dsa",hash:"rmd160",id:""},ripemd160WithRSA:{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},"RSA-RIPEMD160":{sign:"rsa",hash:"rmd160",id:"3021300906052b2403020105000414"},md5WithRSAEncryption:{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"},"RSA-MD5":{sign:"rsa",hash:"md5",id:"3020300c06082a864886f70d020505000410"}}}),J91=l1((A,Q)=>{Q.exports=px()}),ux=l1((A,Q)=>{var J=Math.pow(2,30)-1;Q.exports=function(K,C){if(typeof K!="number")throw new TypeError("Iterations not a number");if(K<0)throw new TypeError("Bad iterations");if(typeof C!="number")throw new TypeError("Key length not a number");if(C<0||C>J||C!==C)throw new TypeError("Bad key length")}}),mx=l1((A,Q)=>{var J;global.process&&global.process.browser?J="utf-8":global.process&&global.process.version?(K=parseInt(process.version.split(".")[0].slice(1),10),J=K>=6?"utf-8":"binary"):J="utf-8";var K;Q.exports=J}),cx=l1((A,Q)=>{var J=bA().Buffer;Q.exports=function(K,C,U){if(J.isBuffer(K))return K;if(typeof K=="string")return J.from(K,C);if(ArrayBuffer.isView(K))return J.from(K.buffer);throw new TypeError(U+" must be a string, a Buffer, a typed array or a DataView")}}),dx=l1((A,Q)=>{var J=bx(),K=jN(),C=vN(),U=bA().Buffer,Y=ux(),Z=mx(),X=cx(),E=U.alloc(128),H={md5:16,sha1:20,sha224:28,sha256:32,sha384:48,sha512:64,rmd160:20,ripemd160:20};function $(F,V,D){var L=I(F),R=F==="sha512"||F==="sha384"?128:64;V.length>R?V=L(V):V.length{var J=bA().Buffer,K=ux(),C=mx(),U=dx(),Y=cx(),Z,X=global.crypto&&global.crypto.subtle,E={sha:"SHA-1","sha-1":"SHA-1",sha1:"SHA-1",sha256:"SHA-256","sha-256":"SHA-256",sha384:"SHA-384","sha-384":"SHA-384","sha-512":"SHA-512",sha512:"SHA-512"},H=[];function $(D){if(global.process&&!global.process.browser||!X||!X.importKey||!X.deriveBits)return Promise.resolve(!1);if(H[D]!==void 0)return H[D];Z=Z||J.alloc(8);var L=F(Z,Z,10,128,D).then(function(){return!0}).catch(function(){return!1});return H[D]=L,L}var I;function N(){return I||(global.process&&global.process.nextTick?I=global.process.nextTick:global.queueMicrotask?I=global.queueMicrotask:global.setImmediate?I=global.setImmediate:I=global.setTimeout,I)}function F(D,L,R,M,T){return X.importKey("raw",D,{name:"PBKDF2"},!1,["deriveBits"]).then(function(h){return X.deriveBits({name:"PBKDF2",salt:L,iterations:R,hash:{name:T}},h,M<<3)}).then(function(h){return J.from(h)})}function V(D,L){D.then(function(R){N()(function(){L(null,R)})},function(R){N()(function(){L(R)})})}Q.exports=function(D,L,R,M,T,h){typeof T=="function"&&(h=T,T=void 0),T=T||"sha1";var y=E[T.toLowerCase()];if(!y||typeof global.Promise!="function"){N()(function(){var g;try{g=U(D,L,R,M,T)}catch(f){return h(f)}h(null,g)});return}if(K(R,M),D=Y(D,C,"Password"),L=Y(L,C,"Salt"),typeof h!="function")throw new Error("No callback provided to pbkdf2");V($(y).then(function(g){return g?F(D,L,R,M,y):U(D,L,R,M,T)}),h)}}),lx=l1((A)=>{A.pbkdf2=K91(),A.pbkdf2Sync=dx()}),nx=l1((A)=>{A.readUInt32BE=function(C,U){var Y=C[0+U]<<24|C[1+U]<<16|C[2+U]<<8|C[3+U];return Y>>>0},A.writeUInt32BE=function(C,U,Y){C[0+Y]=U>>>24,C[1+Y]=U>>>16&255,C[2+Y]=U>>>8&255,C[3+Y]=U&255},A.ip=function(C,U,Y,Z){for(var X=0,E=0,H=6;H>=0;H-=2){for(var $=0;$<=24;$+=8)X<<=1,X|=U>>>$+H&1;for(var $=0;$<=24;$+=8)X<<=1,X|=C>>>$+H&1}for(var H=6;H>=0;H-=2){for(var $=1;$<=25;$+=8)E<<=1,E|=U>>>$+H&1;for(var $=1;$<=25;$+=8)E<<=1,E|=C>>>$+H&1}Y[Z+0]=X>>>0,Y[Z+1]=E>>>0},A.rip=function(C,U,Y,Z){for(var X=0,E=0,H=0;H<4;H++)for(var $=24;$>=0;$-=8)X<<=1,X|=U>>>$+H&1,X<<=1,X|=C>>>$+H&1;for(var H=4;H<8;H++)for(var $=24;$>=0;$-=8)E<<=1,E|=U>>>$+H&1,E<<=1,E|=C>>>$+H&1;Y[Z+0]=X>>>0,Y[Z+1]=E>>>0},A.pc1=function(C,U,Y,Z){for(var X=0,E=0,H=7;H>=5;H--){for(var $=0;$<=24;$+=8)X<<=1,X|=U>>$+H&1;for(var $=0;$<=24;$+=8)X<<=1,X|=C>>$+H&1}for(var $=0;$<=24;$+=8)X<<=1,X|=U>>$+H&1;for(var H=1;H<=3;H++){for(var $=0;$<=24;$+=8)E<<=1,E|=U>>$+H&1;for(var $=0;$<=24;$+=8)E<<=1,E|=C>>$+H&1}for(var $=0;$<=24;$+=8)E<<=1,E|=C>>$+H&1;Y[Z+0]=X>>>0,Y[Z+1]=E>>>0},A.r28shl=function(C,U){return C<>>28-U};var Q=[14,11,17,4,27,23,25,0,13,22,7,18,5,9,16,24,2,20,12,21,1,8,15,26,15,4,25,19,9,1,26,16,5,11,23,8,12,7,17,0,22,3,10,14,6,20,27,24];A.pc2=function(C,U,Y,Z){for(var X=0,E=0,H=Q.length>>>1,$=0;$>>Q[$]&1;for(var $=H;$>>Q[$]&1;Y[Z+0]=X>>>0,Y[Z+1]=E>>>0},A.expand=function(C,U,Y){var Z=0,X=0;Z=(C&1)<<5|C>>>27;for(var E=23;E>=15;E-=4)Z<<=6,Z|=C>>>E&63;for(var E=11;E>=3;E-=4)X|=C>>>E&63,X<<=6;X|=(C&31)<<1|C>>>31,U[Y+0]=Z>>>0,U[Y+1]=X>>>0};var J=[14,0,4,15,13,7,1,4,2,14,15,2,11,13,8,1,3,10,10,6,6,12,12,11,5,9,9,5,0,3,7,8,4,15,1,12,14,8,8,2,13,4,6,9,2,1,11,7,15,5,12,11,9,3,7,14,3,10,10,0,5,6,0,13,15,3,1,13,8,4,14,7,6,15,11,2,3,8,4,14,9,12,7,0,2,1,13,10,12,6,0,9,5,11,10,5,0,13,14,8,7,10,11,1,10,3,4,15,13,4,1,2,5,11,8,6,12,7,6,12,9,0,3,5,2,14,15,9,10,13,0,7,9,0,14,9,6,3,3,4,15,6,5,10,1,2,13,8,12,5,7,14,11,12,4,11,2,15,8,1,13,1,6,10,4,13,9,0,8,6,15,9,3,8,0,7,11,4,1,15,2,14,12,3,5,11,10,5,14,2,7,12,7,13,13,8,14,11,3,5,0,6,6,15,9,0,10,3,1,4,2,7,8,2,5,12,11,1,12,10,4,14,15,9,10,3,6,15,9,0,0,6,12,10,11,1,7,13,13,8,15,9,1,4,3,5,14,11,5,12,2,7,8,2,4,14,2,14,12,11,4,2,1,12,7,4,10,7,11,13,6,1,8,5,5,0,3,15,15,10,13,3,0,9,14,8,9,6,4,11,2,8,1,12,11,7,10,1,13,14,7,2,8,13,15,6,9,15,12,0,5,9,6,10,3,4,0,5,14,3,12,10,1,15,10,4,15,2,9,7,2,12,6,9,8,5,0,6,13,1,3,13,4,14,14,0,7,11,5,3,11,8,9,4,14,3,15,2,5,12,2,9,8,5,12,15,3,10,7,11,0,14,4,1,10,7,1,6,13,0,11,8,6,13,4,13,11,0,2,11,14,7,15,4,0,9,8,1,13,10,3,14,12,3,9,5,7,12,5,2,10,15,6,8,1,6,1,6,4,11,11,13,13,8,12,1,3,4,7,10,14,7,10,9,15,5,6,0,8,15,0,14,5,2,9,3,2,12,13,1,2,15,8,13,4,8,6,10,15,3,11,7,1,4,10,12,9,5,3,6,14,11,5,0,0,14,12,9,7,2,7,2,11,1,4,14,1,7,9,4,12,10,14,8,2,13,0,15,6,12,10,9,13,0,15,3,3,5,5,6,8,11];A.substitute=function(C,U){for(var Y=0,Z=0;Z<4;Z++){var X=C>>>18-Z*6&63,E=J[Z*64+X];Y<<=4,Y|=E}for(var Z=0;Z<4;Z++){var X=U>>>18-Z*6&63,E=J[256+Z*64+X];Y<<=4,Y|=E}return Y>>>0};var K=[16,25,12,11,3,20,4,15,31,17,9,6,27,14,1,22,30,24,8,18,0,5,29,23,13,19,2,26,10,21,28,7];A.permute=function(C){for(var U=0,Y=0;Y>>K[Y]&1;return U>>>0},A.padSplit=function(C,U,Y){for(var Z=C.toString(2);Z.length{Q.exports=J;function J(K,C){if(!K)throw new Error(C||"Assertion failed")}J.equal=function(K,C,U){if(K!=C)throw new Error(U||"Assertion failed: "+K+" != "+C)}}),pN=l1((A,Q)=>{var J=T9();function K(C){this.options=C,this.type=this.options.type,this.blockSize=8,this._init(),this.buffer=new Array(this.blockSize),this.bufferOff=0}Q.exports=K,K.prototype._init=function(){},K.prototype.update=function(C){return C.length===0?[]:this.type==="decrypt"?this._updateDecrypt(C):this._updateEncrypt(C)},K.prototype._buffer=function(C,U){for(var Y=Math.min(this.buffer.length-this.bufferOff,C.length-U),Z=0;Z0;Z--)U+=this._buffer(C,U),Y+=this._flushBuffer(X,Y);return U+=this._buffer(C,U),X},K.prototype.final=function(C){var U;C&&(U=this.update(C));var Y;return this.type==="encrypt"?Y=this._finalEncrypt():Y=this._finalDecrypt(),U?U.concat(Y):Y},K.prototype._pad=function(C,U){if(U===0)return!1;for(;U{var J=T9(),K=MA(),C=nx(),U=pN();function Y(){this.tmp=new Array(2),this.keys=null}function Z(E){U.call(this,E);var H=new Y;this._desState=H,this.deriveKeys(H,E.key)}K(Z,U),Q.exports=Z,Z.create=function(E){return new Z(E)};var X=[1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1];Z.prototype.deriveKeys=function(E,H){E.keys=new Array(32),J.equal(H.length,this.blockSize,"Invalid key length");var $=C.readUInt32BE(H,0),I=C.readUInt32BE(H,4);C.pc1($,I,E.tmp,0),$=E.tmp[0],I=E.tmp[1];for(var N=0;N>>1];$=C.r28shl($,F),I=C.r28shl(I,F),C.pc2($,I,E.keys,N)}},Z.prototype._update=function(E,H,$,I){var N=this._desState,F=C.readUInt32BE(E,H),V=C.readUInt32BE(E,H+4);C.ip(F,V,N.tmp,0),F=N.tmp[0],V=N.tmp[1],this.type==="encrypt"?this._encrypt(N,F,V,N.tmp,0):this._decrypt(N,F,V,N.tmp,0),F=N.tmp[0],V=N.tmp[1],C.writeUInt32BE($,F,I),C.writeUInt32BE($,V,I+4)},Z.prototype._pad=function(E,H){for(var $=E.length-H,I=H;I>>0,F=h}C.rip(V,F,I,N)},Z.prototype._decrypt=function(E,H,$,I,N){for(var F=$,V=H,D=E.keys.length-2;D>=0;D-=2){var L=E.keys[D],R=E.keys[D+1];C.expand(F,E.tmp,0),L^=E.tmp[0],R^=E.tmp[1];var M=C.substitute(L,R),T=C.permute(M),h=F;F=(V^T)>>>0,V=h}C.rip(F,V,I,N)}}),C91=l1((A)=>{var Q=T9(),J=MA(),K={};function C(Y){Q.equal(Y.length,8,"Invalid IV length"),this.iv=new Array(8);for(var Z=0;Z{var J=T9(),K=MA(),C=pN(),U=sx();function Y(X,E){J.equal(E.length,24,"Invalid key length");var H=E.slice(0,8),$=E.slice(8,16),I=E.slice(16,24);X==="encrypt"?this.ciphers=[U.create({type:"encrypt",key:H}),U.create({type:"decrypt",key:$}),U.create({type:"encrypt",key:I})]:this.ciphers=[U.create({type:"decrypt",key:I}),U.create({type:"encrypt",key:$}),U.create({type:"decrypt",key:H})]}function Z(X){C.call(this,X);var E=new Y(this.type,this.options.key);this._edeState=E}K(Z,C),Q.exports=Z,Z.create=function(X){return new Z(X)},Z.prototype._update=function(X,E,H,$){var I=this._edeState;I.ciphers[0]._update(X,E,H,$),I.ciphers[1]._update(H,$,H,$),I.ciphers[2]._update(H,$,H,$)},Z.prototype._pad=U.prototype._pad,Z.prototype._unpad=U.prototype._unpad}),U91=l1((A)=>{A.utils=nx(),A.Cipher=pN(),A.DES=sx(),A.CBC=C91(),A.EDE=Y91()}),Z91=l1((A,Q)=>{var J=t7(),K=U91(),C=MA(),U=bA().Buffer,Y={"des-ede3-cbc":K.CBC.instantiate(K.EDE),"des-ede3":K.EDE,"des-ede-cbc":K.CBC.instantiate(K.EDE),"des-ede":K.EDE,"des-cbc":K.CBC.instantiate(K.DES),"des-ecb":K.DES};Y.des=Y["des-cbc"],Y.des3=Y["des-ede3-cbc"],Q.exports=Z,C(Z,J);function Z(X){J.call(this);var E=X.mode.toLowerCase(),H=Y[E],$;X.decrypt?$="decrypt":$="encrypt";var I=X.key;U.isBuffer(I)||(I=U.from(I)),(E==="des-ede"||E==="des-ede-cbc")&&(I=U.concat([I,I.slice(0,8)]));var N=X.iv;U.isBuffer(N)||(N=U.from(N)),this._des=H.create({key:I,iv:N,type:$})}Z.prototype._update=function(X){return U.from(this._des.update(X))},Z.prototype._final=function(){return U.from(this._des.final())}}),B91=l1((A)=>{A.encrypt=function(Q,J){return Q._cipher.encryptBlock(J)},A.decrypt=function(Q,J){return Q._cipher.decryptBlock(J)}}),LU=l1((A,Q)=>{Q.exports=function(J,K){for(var C=Math.min(J.length,K.length),U=new Buffer(C),Y=0;Y{var Q=LU();A.encrypt=function(J,K){var C=Q(K,J._prev);return J._prev=J._cipher.encryptBlock(C),J._prev},A.decrypt=function(J,K){var C=J._prev;J._prev=K;var U=J._cipher.decryptBlock(K);return Q(U,C)}}),E91=l1((A)=>{var Q=bA().Buffer,J=LU();function K(C,U,Y){var Z=U.length,X=J(U,C._cache);return C._cache=C._cache.slice(Z),C._prev=Q.concat([C._prev,Y?U:X]),X}A.encrypt=function(C,U,Y){for(var Z=Q.allocUnsafe(0),X;U.length;)if(C._cache.length===0&&(C._cache=C._cipher.encryptBlock(C._prev),C._prev=Q.allocUnsafe(0)),C._cache.length<=U.length)X=C._cache.length,Z=Q.concat([Z,K(C,U.slice(0,X),Y)]),U=U.slice(X);else{Z=Q.concat([Z,K(C,U,Y)]);break}return Z}}),$91=l1((A)=>{var Q=bA().Buffer;function J(K,C,U){var Y=K._cipher.encryptBlock(K._prev),Z=Y[0]^C;return K._prev=Q.concat([K._prev.slice(1),Q.from([U?C:Z])]),Z}A.encrypt=function(K,C,U){for(var Y=C.length,Z=Q.allocUnsafe(Y),X=-1;++X{var Q=bA().Buffer;function J(C,U,Y){for(var Z,X=-1,E=8,H=0,$,I;++X>X%8,C._prev=K(C._prev,Y?$:I);return H}function K(C,U){var Y=C.length,Z=-1,X=Q.allocUnsafe(C.length);for(C=Q.concat([C,Q.from([U])]);++Z>7;return X}A.encrypt=function(C,U,Y){for(var Z=U.length,X=Q.allocUnsafe(Z),E=-1;++E{var Q=LU();function J(K){return K._prev=K._cipher.encryptBlock(K._prev),K._prev}A.encrypt=function(K,C){for(;K._cache.length{function J(K){for(var C=K.length,U;C--;)if(U=K.readUInt8(C),U===255)K.writeUInt8(0,C);else{U++,K.writeUInt8(U,C);break}}Q.exports=J}),Fx=l1((A)=>{var Q=LU(),J=bA().Buffer,K=ox();function C(Y){var Z=Y._cipher.encryptBlockRaw(Y._prev);return K(Y._prev),Z}var U=16;A.encrypt=function(Y,Z){var X=Math.ceil(Z.length/U),E=Y._cache.length;Y._cache=J.concat([Y._cache,J.allocUnsafe(X*U)]);for(var H=0;H{Q.exports={"aes-128-ecb":{cipher:"AES",key:128,iv:0,mode:"ECB",type:"block"},"aes-192-ecb":{cipher:"AES",key:192,iv:0,mode:"ECB",type:"block"},"aes-256-ecb":{cipher:"AES",key:256,iv:0,mode:"ECB",type:"block"},"aes-128-cbc":{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},"aes-192-cbc":{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},"aes-256-cbc":{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},aes128:{cipher:"AES",key:128,iv:16,mode:"CBC",type:"block"},aes192:{cipher:"AES",key:192,iv:16,mode:"CBC",type:"block"},aes256:{cipher:"AES",key:256,iv:16,mode:"CBC",type:"block"},"aes-128-cfb":{cipher:"AES",key:128,iv:16,mode:"CFB",type:"stream"},"aes-192-cfb":{cipher:"AES",key:192,iv:16,mode:"CFB",type:"stream"},"aes-256-cfb":{cipher:"AES",key:256,iv:16,mode:"CFB",type:"stream"},"aes-128-cfb8":{cipher:"AES",key:128,iv:16,mode:"CFB8",type:"stream"},"aes-192-cfb8":{cipher:"AES",key:192,iv:16,mode:"CFB8",type:"stream"},"aes-256-cfb8":{cipher:"AES",key:256,iv:16,mode:"CFB8",type:"stream"},"aes-128-cfb1":{cipher:"AES",key:128,iv:16,mode:"CFB1",type:"stream"},"aes-192-cfb1":{cipher:"AES",key:192,iv:16,mode:"CFB1",type:"stream"},"aes-256-cfb1":{cipher:"AES",key:256,iv:16,mode:"CFB1",type:"stream"},"aes-128-ofb":{cipher:"AES",key:128,iv:16,mode:"OFB",type:"stream"},"aes-192-ofb":{cipher:"AES",key:192,iv:16,mode:"OFB",type:"stream"},"aes-256-ofb":{cipher:"AES",key:256,iv:16,mode:"OFB",type:"stream"},"aes-128-ctr":{cipher:"AES",key:128,iv:16,mode:"CTR",type:"stream"},"aes-192-ctr":{cipher:"AES",key:192,iv:16,mode:"CTR",type:"stream"},"aes-256-ctr":{cipher:"AES",key:256,iv:16,mode:"CTR",type:"stream"},"aes-128-gcm":{cipher:"AES",key:128,iv:12,mode:"GCM",type:"auth"},"aes-192-gcm":{cipher:"AES",key:192,iv:12,mode:"GCM",type:"auth"},"aes-256-gcm":{cipher:"AES",key:256,iv:12,mode:"GCM",type:"auth"}}}),uN=l1((A,Q)=>{var J={ECB:B91(),CBC:X91(),CFB:E91(),CFB8:$91(),CFB1:H91(),OFB:G91(),CTR:Fx(),GCM:Fx()},K=ix();for(C in K)K[C].module=J[K[C].mode];var C;Q.exports=K}),rE=l1((A,Q)=>{var J=bA().Buffer;function K(E){J.isBuffer(E)||(E=J.from(E));for(var H=E.length/4|0,$=new Array(H),I=0;I>>24]^V[M>>>16&255]^D[T>>>8&255]^L[h&255]^H[d++],g=F[M>>>24]^V[T>>>16&255]^D[h>>>8&255]^L[R&255]^H[d++],f=F[T>>>24]^V[h>>>16&255]^D[R>>>8&255]^L[M&255]^H[d++],u=F[h>>>24]^V[R>>>16&255]^D[M>>>8&255]^L[T&255]^H[d++],R=y,M=g,T=f,h=u;return y=(I[R>>>24]<<24|I[M>>>16&255]<<16|I[T>>>8&255]<<8|I[h&255])^H[d++],g=(I[M>>>24]<<24|I[T>>>16&255]<<16|I[h>>>8&255]<<8|I[R&255])^H[d++],f=(I[T>>>24]<<24|I[h>>>16&255]<<16|I[R>>>8&255]<<8|I[M&255])^H[d++],u=(I[h>>>24]<<24|I[R>>>16&255]<<16|I[M>>>8&255]<<8|I[T&255])^H[d++],y=y>>>0,g=g>>>0,f=f>>>0,u=u>>>0,[y,g,f,u]}var Y=[0,1,2,4,8,16,32,64,128,27,54],Z=function(){for(var E=new Array(256),H=0;H<256;H++)H<128?E[H]=H<<1:E[H]=H<<1^283;for(var $=[],I=[],N=[[],[],[],[]],F=[[],[],[],[]],V=0,D=0,L=0;L<256;++L){var R=D^D<<1^D<<2^D<<3^D<<4;R=R>>>8^R&255^99,$[V]=R,I[R]=V;var M=E[V],T=E[M],h=E[T],y=E[R]*257^R*16843008;N[0][V]=y<<24|y>>>8,N[1][V]=y<<16|y>>>16,N[2][V]=y<<8|y>>>24,N[3][V]=y,y=h*16843009^T*65537^M*257^V*16843008,F[0][R]=y<<24|y>>>8,F[1][R]=y<<16|y>>>16,F[2][R]=y<<8|y>>>24,F[3][R]=y,V===0?V=D=1:(V=M^E[E[E[h^M]]],D^=E[E[D]])}return{SBOX:$,INV_SBOX:I,SUB_MIX:N,INV_SUB_MIX:F}}();function X(E){this._key=K(E),this._reset()}X.blockSize=16,X.keySize=32,X.prototype.blockSize=X.blockSize,X.prototype.keySize=X.keySize,X.prototype._reset=function(){for(var E=this._key,H=E.length,$=H+6,I=($+1)*4,N=[],F=0;F>>24,V=Z.SBOX[V>>>24]<<24|Z.SBOX[V>>>16&255]<<16|Z.SBOX[V>>>8&255]<<8|Z.SBOX[V&255],V^=Y[F/H|0]<<24):H>6&&F%H===4&&(V=Z.SBOX[V>>>24]<<24|Z.SBOX[V>>>16&255]<<16|Z.SBOX[V>>>8&255]<<8|Z.SBOX[V&255]),N[F]=N[F-H]^V}for(var D=[],L=0;L>>24]]^Z.INV_SUB_MIX[1][Z.SBOX[M>>>16&255]]^Z.INV_SUB_MIX[2][Z.SBOX[M>>>8&255]]^Z.INV_SUB_MIX[3][Z.SBOX[M&255]]}this._nRounds=$,this._keySchedule=N,this._invKeySchedule=D},X.prototype.encryptBlockRaw=function(E){return E=K(E),U(E,this._keySchedule,Z.SUB_MIX,Z.SBOX,this._nRounds)},X.prototype.encryptBlock=function(E){var H=this.encryptBlockRaw(E),$=J.allocUnsafe(16);return $.writeUInt32BE(H[0],0),$.writeUInt32BE(H[1],4),$.writeUInt32BE(H[2],8),$.writeUInt32BE(H[3],12),$},X.prototype.decryptBlock=function(E){E=K(E);var H=E[1];E[1]=E[3],E[3]=H;var $=U(E,this._invKeySchedule,Z.INV_SUB_MIX,Z.INV_SBOX,this._nRounds),I=J.allocUnsafe(16);return I.writeUInt32BE($[0],0),I.writeUInt32BE($[3],4),I.writeUInt32BE($[2],8),I.writeUInt32BE($[1],12),I},X.prototype.scrub=function(){C(this._keySchedule),C(this._invKeySchedule),C(this._key)},Q.exports.AES=X}),W91=l1((A,Q)=>{var J=bA().Buffer,K=J.alloc(16,0);function C(Z){return[Z.readUInt32BE(0),Z.readUInt32BE(4),Z.readUInt32BE(8),Z.readUInt32BE(12)]}function U(Z){var X=J.allocUnsafe(16);return X.writeUInt32BE(Z[0]>>>0,0),X.writeUInt32BE(Z[1]>>>0,4),X.writeUInt32BE(Z[2]>>>0,8),X.writeUInt32BE(Z[3]>>>0,12),X}function Y(Z){this.h=Z,this.state=J.alloc(16,0),this.cache=J.allocUnsafe(0)}Y.prototype.ghash=function(Z){for(var X=-1;++X0;E--)Z[E]=Z[E]>>>1|(Z[E-1]&1)<<31;Z[0]=Z[0]>>>1,$&&(Z[0]=Z[0]^-520093696)}this.state=U(X)},Y.prototype.update=function(Z){this.cache=J.concat([this.cache,Z]);for(var X;this.cache.length>=16;)X=this.cache.slice(0,16),this.cache=this.cache.slice(16),this.ghash(X)},Y.prototype.final=function(Z,X){return this.cache.length&&this.ghash(J.concat([this.cache,K],16)),this.ghash(U([0,Z,0,X])),this.state},Q.exports=Y}),ax=l1((A,Q)=>{var J=rE(),K=bA().Buffer,C=t7(),U=MA(),Y=W91(),Z=LU(),X=ox();function E(I,N){var F=0;I.length!==N.length&&F++;for(var V=Math.min(I.length,N.length),D=0;D{var J=rE(),K=bA().Buffer,C=t7(),U=MA();function Y(Z,X,E,H){C.call(this),this._cipher=new J.AES(X),this._prev=K.from(E),this._cache=K.allocUnsafe(0),this._secCache=K.allocUnsafe(0),this._decrypt=H,this._mode=Z}U(Y,C),Y.prototype._update=function(Z){return this._mode.encrypt(this,Z,this._decrypt)},Y.prototype._final=function(){this._cipher.scrub()},Q.exports=Y}),tE=l1((A,Q)=>{var J=bA().Buffer,K=SN();function C(U,Y,Z,X){if(J.isBuffer(U)||(U=J.from(U,"binary")),Y&&(J.isBuffer(Y)||(Y=J.from(Y,"binary")),Y.length!==8))throw new RangeError("salt should be Buffer with 8 byte length");for(var E=Z/8,H=J.alloc(E),$=J.alloc(X||0),I=J.alloc(0);E>0||X>0;){var N=new K;N.update(I),N.update(U),Y&&N.update(Y),I=N.digest();var F=0;if(E>0){var V=H.length-E;F=Math.min(E,I.length),I.copy(H,V,0,F),E-=F}if(F0){var D=$.length-X,L=Math.min(X,I.length-F);I.copy($,D,F,F+L),X-=L}}return I.fill(0),{key:H,iv:$}}Q.exports=C}),I91=l1((A)=>{var Q=uN(),J=ax(),K=bA().Buffer,C=rx(),U=t7(),Y=rE(),Z=tE(),X=MA();function E(F,V,D){U.call(this),this._cache=new $,this._cipher=new Y.AES(V),this._prev=K.from(D),this._mode=F,this._autopadding=!0}X(E,U),E.prototype._update=function(F){this._cache.add(F);for(var V,D,L=[];V=this._cache.get();)D=this._mode.encrypt(this,V),L.push(D);return K.concat(L)};var H=K.alloc(16,16);E.prototype._final=function(){var F=this._cache.flush();if(this._autopadding)return F=this._mode.encrypt(this,F),this._cipher.scrub(),F;if(!F.equals(H))throw this._cipher.scrub(),new Error("data not multiple of block length")},E.prototype.setAutoPadding=function(F){return this._autopadding=!!F,this};function $(){this.cache=K.allocUnsafe(0)}$.prototype.add=function(F){this.cache=K.concat([this.cache,F])},$.prototype.get=function(){if(this.cache.length>15){var F=this.cache.slice(0,16);return this.cache=this.cache.slice(16),F}return null},$.prototype.flush=function(){for(var F=16-this.cache.length,V=K.allocUnsafe(F),D=-1;++D{var Q=ax(),J=bA().Buffer,K=uN(),C=rx(),U=t7(),Y=rE(),Z=tE(),X=MA();function E(F,V,D){U.call(this),this._cache=new H,this._last=void 0,this._cipher=new Y.AES(V),this._prev=J.from(D),this._mode=F,this._autopadding=!0}X(E,U),E.prototype._update=function(F){this._cache.add(F);for(var V,D,L=[];V=this._cache.get(this._autopadding);)D=this._mode.decrypt(this,V),L.push(D);return J.concat(L)},E.prototype._final=function(){var F=this._cache.flush();if(this._autopadding)return $(this._mode.decrypt(this,F));if(F)throw new Error("data not multiple of block length")},E.prototype.setAutoPadding=function(F){return this._autopadding=!!F,this};function H(){this.cache=J.allocUnsafe(0)}H.prototype.add=function(F){this.cache=J.concat([this.cache,F])},H.prototype.get=function(F){var V;if(F){if(this.cache.length>16)return V=this.cache.slice(0,16),this.cache=this.cache.slice(16),V}else if(this.cache.length>=16)return V=this.cache.slice(0,16),this.cache=this.cache.slice(16),V;return null},H.prototype.flush=function(){if(this.cache.length)return this.cache};function $(F){var V=F[15];if(V<1||V>16)throw new Error("unable to decrypt data");for(var D=-1;++D{var Q=I91(),J=q91(),K=ix();function C(){return Object.keys(K)}A.createCipher=A.Cipher=Q.createCipher,A.createCipheriv=A.Cipheriv=Q.createCipheriv,A.createDecipher=A.Decipher=J.createDecipher,A.createDecipheriv=A.Decipheriv=J.createDecipheriv,A.listCiphers=A.getCiphers=C}),O91=l1((A)=>{A["des-ecb"]={key:8,iv:0},A["des-cbc"]=A.des={key:8,iv:8},A["des-ede3-cbc"]=A.des3={key:24,iv:8},A["des-ede3"]={key:24,iv:0},A["des-ede-cbc"]={key:16,iv:8},A["des-ede"]={key:16,iv:0}}),N91=l1((A)=>{var Q=Z91(),J=mN(),K=uN(),C=O91(),U=tE();function Y($,I){$=$.toLowerCase();var N,F;if(K[$])N=K[$].key,F=K[$].iv;else if(C[$])N=C[$].key*8,F=C[$].iv;else throw new TypeError("invalid suite type");var V=U(I,!1,N,F);return X($,V.key,V.iv)}function Z($,I){$=$.toLowerCase();var N,F;if(K[$])N=K[$].key,F=K[$].iv;else if(C[$])N=C[$].key*8,F=C[$].iv;else throw new TypeError("invalid suite type");var V=U(I,!1,N,F);return E($,V.key,V.iv)}function X($,I,N){if($=$.toLowerCase(),K[$])return J.createCipheriv($,I,N);if(C[$])return new Q({key:I,iv:N,mode:$});throw new TypeError("invalid suite type")}function E($,I,N){if($=$.toLowerCase(),K[$])return J.createDecipheriv($,I,N);if(C[$])return new Q({key:I,iv:N,mode:$,decrypt:!0});throw new TypeError("invalid suite type")}function H(){return Object.keys(C).concat(J.getCiphers())}A.createCipher=A.Cipher=Y,A.createCipheriv=A.Cipheriv=X,A.createDecipher=A.Decipher=Z,A.createDecipheriv=A.Decipheriv=E,A.listCiphers=A.getCiphers=H}),XQ=l1(()=>{}),tx=l1((A,Q)=>{(function(J,K){function C(B,q){if(!B)throw new Error(q||"Assertion failed")}function U(B,q){B.super_=q;var P=function(){};P.prototype=q.prototype,B.prototype=new P,B.prototype.constructor=B}function Y(B,q,P){if(Y.isBN(B))return B;this.negative=0,this.words=null,this.length=0,this.red=null,B!==null&&((q==="le"||q==="be")&&(P=q,q=10),this._init(B||0,q||10,P||"be"))}typeof J=="object"?J.exports=Y:K.BN=Y,Y.BN=Y,Y.wordSize=26;var Z;try{typeof window<"u"&&typeof window.Buffer<"u"?Z=window.Buffer:Z=XQ().Buffer}catch{}Y.isBN=function(B){return B instanceof Y?!0:B!==null&&typeof B=="object"&&B.constructor.wordSize===Y.wordSize&&Array.isArray(B.words)},Y.max=function(B,q){return B.cmp(q)>0?B:q},Y.min=function(B,q){return B.cmp(q)<0?B:q},Y.prototype._init=function(B,q,P){if(typeof B=="number")return this._initNumber(B,q,P);if(typeof B=="object")return this._initArray(B,q,P);q==="hex"&&(q=16),C(q===(q|0)&&q>=2&&q<=36),B=B.toString().replace(/\s+/g,"");var O=0;B[0]==="-"&&(O++,this.negative=1),O=0;O-=3)k=B[O]|B[O-1]<<8|B[O-2]<<16,this.words[w]|=k<>>26-S&67108863,S+=24,S>=26&&(S-=26,w++);else if(P==="le")for(O=0,w=0;O>>26-S&67108863,S+=24,S>=26&&(S-=26,w++);return this.strip()};function X(B,q){var P=B.charCodeAt(q);return P>=65&&P<=70?P-55:P>=97&&P<=102?P-87:P-48&15}function E(B,q,P){var O=X(B,P);return P-1>=q&&(O|=X(B,P-1)<<4),O}Y.prototype._parseHex=function(B,q,P){this.length=Math.ceil((B.length-q)/6),this.words=new Array(this.length);for(var O=0;O=q;O-=2)S=E(B,q,O)<=18?(w-=18,k+=1,this.words[k]|=S>>>26):w+=8;else{var _=B.length-q;for(O=_%2===0?q+1:q;O=18?(w-=18,k+=1,this.words[k]|=S>>>26):w+=8}this.strip()};function H(B,q,P,O){for(var w=0,k=Math.min(B.length,P),S=q;S=49?w+=_-49+10:_>=17?w+=_-17+10:w+=_}return w}Y.prototype._parseBase=function(B,q,P){this.words=[0],this.length=1;for(var O=0,w=1;w<=67108863;w*=q)O++;O--,w=w/q|0;for(var k=B.length-P,S=k%O,_=Math.min(k,k-S)+P,W=0,j=P;j<_;j+=O)W=H(B,j,j+O,q),this.imuln(w),this.words[0]+W<67108864?this.words[0]+=W:this._iaddn(W);if(S!==0){var b=1;for(W=H(B,j,B.length,q),j=0;j1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},Y.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},Y.prototype.inspect=function(){return(this.red?""};var $=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],I=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],N=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];Y.prototype.toString=function(B,q){B=B||10,q=q|0||1;var P;if(B===16||B==="hex"){P="";for(var O=0,w=0,k=0;k>>24-O&16777215,w!==0||k!==this.length-1?P=$[6-_.length]+_+P:P=_+P,O+=2,O>=26&&(O-=26,k--)}for(w!==0&&(P=w.toString(16)+P);P.length%q!==0;)P="0"+P;return this.negative!==0&&(P="-"+P),P}if(B===(B|0)&&B>=2&&B<=36){var W=I[B],j=N[B];P="";var b=this.clone();for(b.negative=0;!b.isZero();){var p=b.modn(j).toString(B);b=b.idivn(j),b.isZero()?P=p+P:P=$[W-p.length]+p+P}for(this.isZero()&&(P="0"+P);P.length%q!==0;)P="0"+P;return this.negative!==0&&(P="-"+P),P}C(!1,"Base should be between 2 and 36")},Y.prototype.toNumber=function(){var B=this.words[0];return this.length===2?B+=this.words[1]*67108864:this.length===3&&this.words[2]===1?B+=4503599627370496+this.words[1]*67108864:this.length>2&&C(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-B:B},Y.prototype.toJSON=function(){return this.toString(16)},Y.prototype.toBuffer=function(B,q){return C(typeof Z<"u"),this.toArrayLike(Z,B,q)},Y.prototype.toArray=function(B,q){return this.toArrayLike(Array,B,q)},Y.prototype.toArrayLike=function(B,q,P){var O=this.byteLength(),w=P||Math.max(1,O);C(O<=w,"byte array longer than desired length"),C(w>0,"Requested array length <= 0"),this.strip();var k=q==="le",S=new B(w),_,W,j=this.clone();if(k){for(W=0;!j.isZero();W++)_=j.andln(255),j.iushrn(8),S[W]=_;for(;W=4096&&(P+=13,q>>>=13),q>=64&&(P+=7,q>>>=7),q>=8&&(P+=4,q>>>=4),q>=2&&(P+=2,q>>>=2),P+q},Y.prototype._zeroBits=function(B){if(B===0)return 26;var q=B,P=0;return(q&8191)===0&&(P+=13,q>>>=13),(q&127)===0&&(P+=7,q>>>=7),(q&15)===0&&(P+=4,q>>>=4),(q&3)===0&&(P+=2,q>>>=2),(q&1)===0&&P++,P},Y.prototype.bitLength=function(){var B=this.words[this.length-1],q=this._countBits(B);return(this.length-1)*26+q};function F(B){for(var q=new Array(B.bitLength()),P=0;P>>w}return q}Y.prototype.zeroBits=function(){if(this.isZero())return 0;for(var B=0,q=0;qB.length?this.clone().ior(B):B.clone().ior(this)},Y.prototype.uor=function(B){return this.length>B.length?this.clone().iuor(B):B.clone().iuor(this)},Y.prototype.iuand=function(B){var q;this.length>B.length?q=B:q=this;for(var P=0;PB.length?this.clone().iand(B):B.clone().iand(this)},Y.prototype.uand=function(B){return this.length>B.length?this.clone().iuand(B):B.clone().iuand(this)},Y.prototype.iuxor=function(B){var q,P;this.length>B.length?(q=this,P=B):(q=B,P=this);for(var O=0;OB.length?this.clone().ixor(B):B.clone().ixor(this)},Y.prototype.uxor=function(B){return this.length>B.length?this.clone().iuxor(B):B.clone().iuxor(this)},Y.prototype.inotn=function(B){C(typeof B=="number"&&B>=0);var q=Math.ceil(B/26)|0,P=B%26;this._expand(q),P>0&&q--;for(var O=0;O0&&(this.words[O]=~this.words[O]&67108863>>26-P),this.strip()},Y.prototype.notn=function(B){return this.clone().inotn(B)},Y.prototype.setn=function(B,q){C(typeof B=="number"&&B>=0);var P=B/26|0,O=B%26;return this._expand(P+1),q?this.words[P]=this.words[P]|1<B.length?(P=this,O=B):(P=B,O=this);for(var w=0,k=0;k>>26;for(;w!==0&&k>>26;if(this.length=P.length,w!==0)this.words[this.length]=w,this.length++;else if(P!==this)for(;kB.length?this.clone().iadd(B):B.clone().iadd(this)},Y.prototype.isub=function(B){if(B.negative!==0){B.negative=0;var q=this.iadd(B);return B.negative=1,q._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(B),this.negative=1,this._normSign();var P=this.cmp(B);if(P===0)return this.negative=0,this.length=1,this.words[0]=0,this;var O,w;P>0?(O=this,w=B):(O=B,w=this);for(var k=0,S=0;S>26,this.words[S]=q&67108863;for(;k!==0&&S>26,this.words[S]=q&67108863;if(k===0&&S>>26,p=W&67108863,s=Math.min(j,q.length-1),r=Math.max(0,j-B.length+1);r<=s;r++){var A1=j-r|0;w=B.words[A1]|0,k=q.words[r]|0,S=w*k+p,b+=S/67108864|0,p=S&67108863}P.words[j]=p|0,W=b|0}return W!==0?P.words[j]=W|0:P.length--,P.strip()}var D=function(B,q,P){var O=B.words,w=q.words,k=P.words,S=0,_,W,j,b=O[0]|0,p=b&8191,s=b>>>13,r=O[1]|0,A1=r&8191,Q1=r>>>13,e=O[2]|0,t=e&8191,U1=e>>>13,O1=O[3]|0,E1=O1&8191,Y1=O1>>>13,i=O[4]|0,c=i&8191,o=i>>>13,C1=O[5]|0,q1=C1&8191,Z1=C1>>>13,j1=O[6]|0,H1=j1&8191,B1=j1>>>13,k1=O[7]|0,D1=k1&8191,G1=k1>>>13,w1=O[8]|0,G=w1&8191,z=w1>>>13,x=O[9]|0,m=x&8191,l=x>>>13,a=w[0]|0,K1=a&8191,F1=a>>>13,R1=w[1]|0,X1=R1&8191,W1=R1>>>13,$1=w[2]|0,N1=$1&8191,_1=$1>>>13,J1=w[3]|0,z1=J1&8191,M1=J1>>>13,L1=w[4]|0,V1=L1&8191,S1=L1>>>13,O0=w[5]|0,h1=O0&8191,b1=O0>>>13,f0=w[6]|0,e1=f0&8191,s1=f0>>>13,o0=w[7]|0,a1=o0&8191,r1=o0>>>13,FA=w[8]|0,K0=FA&8191,J0=FA>>>13,qA=w[9]|0,Q0=qA&8191,A0=qA>>>13;P.negative=B.negative^q.negative,P.length=19,_=Math.imul(p,K1),W=Math.imul(p,F1),W=W+Math.imul(s,K1)|0,j=Math.imul(s,F1);var hA=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(hA>>>26)|0,hA&=67108863,_=Math.imul(A1,K1),W=Math.imul(A1,F1),W=W+Math.imul(Q1,K1)|0,j=Math.imul(Q1,F1),_=_+Math.imul(p,X1)|0,W=W+Math.imul(p,W1)|0,W=W+Math.imul(s,X1)|0,j=j+Math.imul(s,W1)|0;var r0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(r0>>>26)|0,r0&=67108863,_=Math.imul(t,K1),W=Math.imul(t,F1),W=W+Math.imul(U1,K1)|0,j=Math.imul(U1,F1),_=_+Math.imul(A1,X1)|0,W=W+Math.imul(A1,W1)|0,W=W+Math.imul(Q1,X1)|0,j=j+Math.imul(Q1,W1)|0,_=_+Math.imul(p,N1)|0,W=W+Math.imul(p,_1)|0,W=W+Math.imul(s,N1)|0,j=j+Math.imul(s,_1)|0;var EA=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(EA>>>26)|0,EA&=67108863,_=Math.imul(E1,K1),W=Math.imul(E1,F1),W=W+Math.imul(Y1,K1)|0,j=Math.imul(Y1,F1),_=_+Math.imul(t,X1)|0,W=W+Math.imul(t,W1)|0,W=W+Math.imul(U1,X1)|0,j=j+Math.imul(U1,W1)|0,_=_+Math.imul(A1,N1)|0,W=W+Math.imul(A1,_1)|0,W=W+Math.imul(Q1,N1)|0,j=j+Math.imul(Q1,_1)|0,_=_+Math.imul(p,z1)|0,W=W+Math.imul(p,M1)|0,W=W+Math.imul(s,z1)|0,j=j+Math.imul(s,M1)|0;var X2=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(X2>>>26)|0,X2&=67108863,_=Math.imul(c,K1),W=Math.imul(c,F1),W=W+Math.imul(o,K1)|0,j=Math.imul(o,F1),_=_+Math.imul(E1,X1)|0,W=W+Math.imul(E1,W1)|0,W=W+Math.imul(Y1,X1)|0,j=j+Math.imul(Y1,W1)|0,_=_+Math.imul(t,N1)|0,W=W+Math.imul(t,_1)|0,W=W+Math.imul(U1,N1)|0,j=j+Math.imul(U1,_1)|0,_=_+Math.imul(A1,z1)|0,W=W+Math.imul(A1,M1)|0,W=W+Math.imul(Q1,z1)|0,j=j+Math.imul(Q1,M1)|0,_=_+Math.imul(p,V1)|0,W=W+Math.imul(p,S1)|0,W=W+Math.imul(s,V1)|0,j=j+Math.imul(s,S1)|0;var E2=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(E2>>>26)|0,E2&=67108863,_=Math.imul(q1,K1),W=Math.imul(q1,F1),W=W+Math.imul(Z1,K1)|0,j=Math.imul(Z1,F1),_=_+Math.imul(c,X1)|0,W=W+Math.imul(c,W1)|0,W=W+Math.imul(o,X1)|0,j=j+Math.imul(o,W1)|0,_=_+Math.imul(E1,N1)|0,W=W+Math.imul(E1,_1)|0,W=W+Math.imul(Y1,N1)|0,j=j+Math.imul(Y1,_1)|0,_=_+Math.imul(t,z1)|0,W=W+Math.imul(t,M1)|0,W=W+Math.imul(U1,z1)|0,j=j+Math.imul(U1,M1)|0,_=_+Math.imul(A1,V1)|0,W=W+Math.imul(A1,S1)|0,W=W+Math.imul(Q1,V1)|0,j=j+Math.imul(Q1,S1)|0,_=_+Math.imul(p,h1)|0,W=W+Math.imul(p,b1)|0,W=W+Math.imul(s,h1)|0,j=j+Math.imul(s,b1)|0;var T1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(T1>>>26)|0,T1&=67108863,_=Math.imul(H1,K1),W=Math.imul(H1,F1),W=W+Math.imul(B1,K1)|0,j=Math.imul(B1,F1),_=_+Math.imul(q1,X1)|0,W=W+Math.imul(q1,W1)|0,W=W+Math.imul(Z1,X1)|0,j=j+Math.imul(Z1,W1)|0,_=_+Math.imul(c,N1)|0,W=W+Math.imul(c,_1)|0,W=W+Math.imul(o,N1)|0,j=j+Math.imul(o,_1)|0,_=_+Math.imul(E1,z1)|0,W=W+Math.imul(E1,M1)|0,W=W+Math.imul(Y1,z1)|0,j=j+Math.imul(Y1,M1)|0,_=_+Math.imul(t,V1)|0,W=W+Math.imul(t,S1)|0,W=W+Math.imul(U1,V1)|0,j=j+Math.imul(U1,S1)|0,_=_+Math.imul(A1,h1)|0,W=W+Math.imul(A1,b1)|0,W=W+Math.imul(Q1,h1)|0,j=j+Math.imul(Q1,b1)|0,_=_+Math.imul(p,e1)|0,W=W+Math.imul(p,s1)|0,W=W+Math.imul(s,e1)|0,j=j+Math.imul(s,s1)|0;var m1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(m1>>>26)|0,m1&=67108863,_=Math.imul(D1,K1),W=Math.imul(D1,F1),W=W+Math.imul(G1,K1)|0,j=Math.imul(G1,F1),_=_+Math.imul(H1,X1)|0,W=W+Math.imul(H1,W1)|0,W=W+Math.imul(B1,X1)|0,j=j+Math.imul(B1,W1)|0,_=_+Math.imul(q1,N1)|0,W=W+Math.imul(q1,_1)|0,W=W+Math.imul(Z1,N1)|0,j=j+Math.imul(Z1,_1)|0,_=_+Math.imul(c,z1)|0,W=W+Math.imul(c,M1)|0,W=W+Math.imul(o,z1)|0,j=j+Math.imul(o,M1)|0,_=_+Math.imul(E1,V1)|0,W=W+Math.imul(E1,S1)|0,W=W+Math.imul(Y1,V1)|0,j=j+Math.imul(Y1,S1)|0,_=_+Math.imul(t,h1)|0,W=W+Math.imul(t,b1)|0,W=W+Math.imul(U1,h1)|0,j=j+Math.imul(U1,b1)|0,_=_+Math.imul(A1,e1)|0,W=W+Math.imul(A1,s1)|0,W=W+Math.imul(Q1,e1)|0,j=j+Math.imul(Q1,s1)|0,_=_+Math.imul(p,a1)|0,W=W+Math.imul(p,r1)|0,W=W+Math.imul(s,a1)|0,j=j+Math.imul(s,r1)|0;var i1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(i1>>>26)|0,i1&=67108863,_=Math.imul(G,K1),W=Math.imul(G,F1),W=W+Math.imul(z,K1)|0,j=Math.imul(z,F1),_=_+Math.imul(D1,X1)|0,W=W+Math.imul(D1,W1)|0,W=W+Math.imul(G1,X1)|0,j=j+Math.imul(G1,W1)|0,_=_+Math.imul(H1,N1)|0,W=W+Math.imul(H1,_1)|0,W=W+Math.imul(B1,N1)|0,j=j+Math.imul(B1,_1)|0,_=_+Math.imul(q1,z1)|0,W=W+Math.imul(q1,M1)|0,W=W+Math.imul(Z1,z1)|0,j=j+Math.imul(Z1,M1)|0,_=_+Math.imul(c,V1)|0,W=W+Math.imul(c,S1)|0,W=W+Math.imul(o,V1)|0,j=j+Math.imul(o,S1)|0,_=_+Math.imul(E1,h1)|0,W=W+Math.imul(E1,b1)|0,W=W+Math.imul(Y1,h1)|0,j=j+Math.imul(Y1,b1)|0,_=_+Math.imul(t,e1)|0,W=W+Math.imul(t,s1)|0,W=W+Math.imul(U1,e1)|0,j=j+Math.imul(U1,s1)|0,_=_+Math.imul(A1,a1)|0,W=W+Math.imul(A1,r1)|0,W=W+Math.imul(Q1,a1)|0,j=j+Math.imul(Q1,r1)|0,_=_+Math.imul(p,K0)|0,W=W+Math.imul(p,J0)|0,W=W+Math.imul(s,K0)|0,j=j+Math.imul(s,J0)|0;var t1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(t1>>>26)|0,t1&=67108863,_=Math.imul(m,K1),W=Math.imul(m,F1),W=W+Math.imul(l,K1)|0,j=Math.imul(l,F1),_=_+Math.imul(G,X1)|0,W=W+Math.imul(G,W1)|0,W=W+Math.imul(z,X1)|0,j=j+Math.imul(z,W1)|0,_=_+Math.imul(D1,N1)|0,W=W+Math.imul(D1,_1)|0,W=W+Math.imul(G1,N1)|0,j=j+Math.imul(G1,_1)|0,_=_+Math.imul(H1,z1)|0,W=W+Math.imul(H1,M1)|0,W=W+Math.imul(B1,z1)|0,j=j+Math.imul(B1,M1)|0,_=_+Math.imul(q1,V1)|0,W=W+Math.imul(q1,S1)|0,W=W+Math.imul(Z1,V1)|0,j=j+Math.imul(Z1,S1)|0,_=_+Math.imul(c,h1)|0,W=W+Math.imul(c,b1)|0,W=W+Math.imul(o,h1)|0,j=j+Math.imul(o,b1)|0,_=_+Math.imul(E1,e1)|0,W=W+Math.imul(E1,s1)|0,W=W+Math.imul(Y1,e1)|0,j=j+Math.imul(Y1,s1)|0,_=_+Math.imul(t,a1)|0,W=W+Math.imul(t,r1)|0,W=W+Math.imul(U1,a1)|0,j=j+Math.imul(U1,r1)|0,_=_+Math.imul(A1,K0)|0,W=W+Math.imul(A1,J0)|0,W=W+Math.imul(Q1,K0)|0,j=j+Math.imul(Q1,J0)|0,_=_+Math.imul(p,Q0)|0,W=W+Math.imul(p,A0)|0,W=W+Math.imul(s,Q0)|0,j=j+Math.imul(s,A0)|0;var d1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(d1>>>26)|0,d1&=67108863,_=Math.imul(m,X1),W=Math.imul(m,W1),W=W+Math.imul(l,X1)|0,j=Math.imul(l,W1),_=_+Math.imul(G,N1)|0,W=W+Math.imul(G,_1)|0,W=W+Math.imul(z,N1)|0,j=j+Math.imul(z,_1)|0,_=_+Math.imul(D1,z1)|0,W=W+Math.imul(D1,M1)|0,W=W+Math.imul(G1,z1)|0,j=j+Math.imul(G1,M1)|0,_=_+Math.imul(H1,V1)|0,W=W+Math.imul(H1,S1)|0,W=W+Math.imul(B1,V1)|0,j=j+Math.imul(B1,S1)|0,_=_+Math.imul(q1,h1)|0,W=W+Math.imul(q1,b1)|0,W=W+Math.imul(Z1,h1)|0,j=j+Math.imul(Z1,b1)|0,_=_+Math.imul(c,e1)|0,W=W+Math.imul(c,s1)|0,W=W+Math.imul(o,e1)|0,j=j+Math.imul(o,s1)|0,_=_+Math.imul(E1,a1)|0,W=W+Math.imul(E1,r1)|0,W=W+Math.imul(Y1,a1)|0,j=j+Math.imul(Y1,r1)|0,_=_+Math.imul(t,K0)|0,W=W+Math.imul(t,J0)|0,W=W+Math.imul(U1,K0)|0,j=j+Math.imul(U1,J0)|0,_=_+Math.imul(A1,Q0)|0,W=W+Math.imul(A1,A0)|0,W=W+Math.imul(Q1,Q0)|0,j=j+Math.imul(Q1,A0)|0;var H0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(H0>>>26)|0,H0&=67108863,_=Math.imul(m,N1),W=Math.imul(m,_1),W=W+Math.imul(l,N1)|0,j=Math.imul(l,_1),_=_+Math.imul(G,z1)|0,W=W+Math.imul(G,M1)|0,W=W+Math.imul(z,z1)|0,j=j+Math.imul(z,M1)|0,_=_+Math.imul(D1,V1)|0,W=W+Math.imul(D1,S1)|0,W=W+Math.imul(G1,V1)|0,j=j+Math.imul(G1,S1)|0,_=_+Math.imul(H1,h1)|0,W=W+Math.imul(H1,b1)|0,W=W+Math.imul(B1,h1)|0,j=j+Math.imul(B1,b1)|0,_=_+Math.imul(q1,e1)|0,W=W+Math.imul(q1,s1)|0,W=W+Math.imul(Z1,e1)|0,j=j+Math.imul(Z1,s1)|0,_=_+Math.imul(c,a1)|0,W=W+Math.imul(c,r1)|0,W=W+Math.imul(o,a1)|0,j=j+Math.imul(o,r1)|0,_=_+Math.imul(E1,K0)|0,W=W+Math.imul(E1,J0)|0,W=W+Math.imul(Y1,K0)|0,j=j+Math.imul(Y1,J0)|0,_=_+Math.imul(t,Q0)|0,W=W+Math.imul(t,A0)|0,W=W+Math.imul(U1,Q0)|0,j=j+Math.imul(U1,A0)|0;var R0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(R0>>>26)|0,R0&=67108863,_=Math.imul(m,z1),W=Math.imul(m,M1),W=W+Math.imul(l,z1)|0,j=Math.imul(l,M1),_=_+Math.imul(G,V1)|0,W=W+Math.imul(G,S1)|0,W=W+Math.imul(z,V1)|0,j=j+Math.imul(z,S1)|0,_=_+Math.imul(D1,h1)|0,W=W+Math.imul(D1,b1)|0,W=W+Math.imul(G1,h1)|0,j=j+Math.imul(G1,b1)|0,_=_+Math.imul(H1,e1)|0,W=W+Math.imul(H1,s1)|0,W=W+Math.imul(B1,e1)|0,j=j+Math.imul(B1,s1)|0,_=_+Math.imul(q1,a1)|0,W=W+Math.imul(q1,r1)|0,W=W+Math.imul(Z1,a1)|0,j=j+Math.imul(Z1,r1)|0,_=_+Math.imul(c,K0)|0,W=W+Math.imul(c,J0)|0,W=W+Math.imul(o,K0)|0,j=j+Math.imul(o,J0)|0,_=_+Math.imul(E1,Q0)|0,W=W+Math.imul(E1,A0)|0,W=W+Math.imul(Y1,Q0)|0,j=j+Math.imul(Y1,A0)|0;var D0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(D0>>>26)|0,D0&=67108863,_=Math.imul(m,V1),W=Math.imul(m,S1),W=W+Math.imul(l,V1)|0,j=Math.imul(l,S1),_=_+Math.imul(G,h1)|0,W=W+Math.imul(G,b1)|0,W=W+Math.imul(z,h1)|0,j=j+Math.imul(z,b1)|0,_=_+Math.imul(D1,e1)|0,W=W+Math.imul(D1,s1)|0,W=W+Math.imul(G1,e1)|0,j=j+Math.imul(G1,s1)|0,_=_+Math.imul(H1,a1)|0,W=W+Math.imul(H1,r1)|0,W=W+Math.imul(B1,a1)|0,j=j+Math.imul(B1,r1)|0,_=_+Math.imul(q1,K0)|0,W=W+Math.imul(q1,J0)|0,W=W+Math.imul(Z1,K0)|0,j=j+Math.imul(Z1,J0)|0,_=_+Math.imul(c,Q0)|0,W=W+Math.imul(c,A0)|0,W=W+Math.imul(o,Q0)|0,j=j+Math.imul(o,A0)|0;var P0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(P0>>>26)|0,P0&=67108863,_=Math.imul(m,h1),W=Math.imul(m,b1),W=W+Math.imul(l,h1)|0,j=Math.imul(l,b1),_=_+Math.imul(G,e1)|0,W=W+Math.imul(G,s1)|0,W=W+Math.imul(z,e1)|0,j=j+Math.imul(z,s1)|0,_=_+Math.imul(D1,a1)|0,W=W+Math.imul(D1,r1)|0,W=W+Math.imul(G1,a1)|0,j=j+Math.imul(G1,r1)|0,_=_+Math.imul(H1,K0)|0,W=W+Math.imul(H1,J0)|0,W=W+Math.imul(B1,K0)|0,j=j+Math.imul(B1,J0)|0,_=_+Math.imul(q1,Q0)|0,W=W+Math.imul(q1,A0)|0,W=W+Math.imul(Z1,Q0)|0,j=j+Math.imul(Z1,A0)|0;var j0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(j0>>>26)|0,j0&=67108863,_=Math.imul(m,e1),W=Math.imul(m,s1),W=W+Math.imul(l,e1)|0,j=Math.imul(l,s1),_=_+Math.imul(G,a1)|0,W=W+Math.imul(G,r1)|0,W=W+Math.imul(z,a1)|0,j=j+Math.imul(z,r1)|0,_=_+Math.imul(D1,K0)|0,W=W+Math.imul(D1,J0)|0,W=W+Math.imul(G1,K0)|0,j=j+Math.imul(G1,J0)|0,_=_+Math.imul(H1,Q0)|0,W=W+Math.imul(H1,A0)|0,W=W+Math.imul(B1,Q0)|0,j=j+Math.imul(B1,A0)|0;var v0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(v0>>>26)|0,v0&=67108863,_=Math.imul(m,a1),W=Math.imul(m,r1),W=W+Math.imul(l,a1)|0,j=Math.imul(l,r1),_=_+Math.imul(G,K0)|0,W=W+Math.imul(G,J0)|0,W=W+Math.imul(z,K0)|0,j=j+Math.imul(z,J0)|0,_=_+Math.imul(D1,Q0)|0,W=W+Math.imul(D1,A0)|0,W=W+Math.imul(G1,Q0)|0,j=j+Math.imul(G1,A0)|0;var S0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(S0>>>26)|0,S0&=67108863,_=Math.imul(m,K0),W=Math.imul(m,J0),W=W+Math.imul(l,K0)|0,j=Math.imul(l,J0),_=_+Math.imul(G,Q0)|0,W=W+Math.imul(G,A0)|0,W=W+Math.imul(z,Q0)|0,j=j+Math.imul(z,A0)|0;var n0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(n0>>>26)|0,n0&=67108863,_=Math.imul(m,Q0),W=Math.imul(m,A0),W=W+Math.imul(l,Q0)|0,j=Math.imul(l,A0);var i0=(S+_|0)+((W&8191)<<13)|0;return S=(j+(W>>>13)|0)+(i0>>>26)|0,i0&=67108863,k[0]=hA,k[1]=r0,k[2]=EA,k[3]=X2,k[4]=E2,k[5]=T1,k[6]=m1,k[7]=i1,k[8]=t1,k[9]=d1,k[10]=H0,k[11]=R0,k[12]=D0,k[13]=P0,k[14]=j0,k[15]=v0,k[16]=S0,k[17]=n0,k[18]=i0,S!==0&&(k[19]=S,P.length++),P};Math.imul||(D=V);function L(B,q,P){P.negative=q.negative^B.negative,P.length=B.length+q.length;for(var O=0,w=0,k=0;k>>26)|0,w+=S>>>26,S&=67108863}P.words[k]=_,O=S,S=w}return O!==0?P.words[k]=O:P.length--,P.strip()}function R(B,q,P){var O=new M;return O.mulp(B,q,P)}Y.prototype.mulTo=function(B,q){var P,O=this.length+B.length;return this.length===10&&B.length===10?P=D(this,B,q):O<63?P=V(this,B,q):O<1024?P=L(this,B,q):P=R(this,B,q),P};function M(B,q){this.x=B,this.y=q}M.prototype.makeRBT=function(B){for(var q=new Array(B),P=Y.prototype._countBits(B)-1,O=0;O>=1;return O},M.prototype.permute=function(B,q,P,O,w,k){for(var S=0;S>>1)w++;return 1<>>13,P[2*k+1]=w&8191,w=w>>>13;for(k=2*q;k>=26,q+=O/67108864|0,q+=w>>>26,this.words[P]=w&67108863}return q!==0&&(this.words[P]=q,this.length++),this},Y.prototype.muln=function(B){return this.clone().imuln(B)},Y.prototype.sqr=function(){return this.mul(this)},Y.prototype.isqr=function(){return this.imul(this.clone())},Y.prototype.pow=function(B){var q=F(B);if(q.length===0)return new Y(1);for(var P=this,O=0;O=0);var q=B%26,P=(B-q)/26,O=67108863>>>26-q<<26-q,w;if(q!==0){var k=0;for(w=0;w>>26-q}k&&(this.words[w]=k,this.length++)}if(P!==0){for(w=this.length-1;w>=0;w--)this.words[w+P]=this.words[w];for(w=0;w=0);var O;q?O=(q-q%26)/26:O=0;var w=B%26,k=Math.min((B-w)/26,this.length),S=67108863^67108863>>>w<k)for(this.length-=k,W=0;W=0&&(j!==0||W>=O);W--){var b=this.words[W]|0;this.words[W]=j<<26-w|b>>>w,j=b&S}return _&&j!==0&&(_.words[_.length++]=j),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},Y.prototype.ishrn=function(B,q,P){return C(this.negative===0),this.iushrn(B,q,P)},Y.prototype.shln=function(B){return this.clone().ishln(B)},Y.prototype.ushln=function(B){return this.clone().iushln(B)},Y.prototype.shrn=function(B){return this.clone().ishrn(B)},Y.prototype.ushrn=function(B){return this.clone().iushrn(B)},Y.prototype.testn=function(B){C(typeof B=="number"&&B>=0);var q=B%26,P=(B-q)/26,O=1<=0);var q=B%26,P=(B-q)/26;if(C(this.negative===0,"imaskn works only with positive numbers"),this.length<=P)return this;if(q!==0&&P++,this.length=Math.min(P,this.length),q!==0){var O=67108863^67108863>>>q<=67108864;q++)this.words[q]-=67108864,q===this.length-1?this.words[q+1]=1:this.words[q+1]++;return this.length=Math.max(this.length,q+1),this},Y.prototype.isubn=function(B){if(C(typeof B=="number"),C(B<67108864),B<0)return this.iaddn(-B);if(this.negative!==0)return this.negative=0,this.iaddn(B),this.negative=1,this;if(this.words[0]-=B,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var q=0;q>26)-(_/67108864|0),this.words[w+P]=k&67108863}for(;w>26,this.words[w+P]=k&67108863;if(S===0)return this.strip();for(C(S===-1),S=0,w=0;w>26,this.words[w]=k&67108863;return this.negative=1,this.strip()},Y.prototype._wordDiv=function(B,q){var P=this.length-B.length,O=this.clone(),w=B,k=w.words[w.length-1]|0,S=this._countBits(k);P=26-S,P!==0&&(w=w.ushln(P),O.iushln(P),k=w.words[w.length-1]|0);var _=O.length-w.length,W;if(q!=="mod"){W=new Y(null),W.length=_+1,W.words=new Array(W.length);for(var j=0;j=0;p--){var s=(O.words[w.length+p]|0)*67108864+(O.words[w.length+p-1]|0);for(s=Math.min(s/k|0,67108863),O._ishlnsubmul(w,s,p);O.negative!==0;)s--,O.negative=0,O._ishlnsubmul(w,1,p),O.isZero()||(O.negative^=1);W&&(W.words[p]=s)}return W&&W.strip(),O.strip(),q!=="div"&&P!==0&&O.iushrn(P),{div:W||null,mod:O}},Y.prototype.divmod=function(B,q,P){if(C(!B.isZero()),this.isZero())return{div:new Y(0),mod:new Y(0)};var O,w,k;return this.negative!==0&&B.negative===0?(k=this.neg().divmod(B,q),q!=="mod"&&(O=k.div.neg()),q!=="div"&&(w=k.mod.neg(),P&&w.negative!==0&&w.iadd(B)),{div:O,mod:w}):this.negative===0&&B.negative!==0?(k=this.divmod(B.neg(),q),q!=="mod"&&(O=k.div.neg()),{div:O,mod:k.mod}):(this.negative&B.negative)!==0?(k=this.neg().divmod(B.neg(),q),q!=="div"&&(w=k.mod.neg(),P&&w.negative!==0&&w.isub(B)),{div:k.div,mod:w}):B.length>this.length||this.cmp(B)<0?{div:new Y(0),mod:this}:B.length===1?q==="div"?{div:this.divn(B.words[0]),mod:null}:q==="mod"?{div:null,mod:new Y(this.modn(B.words[0]))}:{div:this.divn(B.words[0]),mod:new Y(this.modn(B.words[0]))}:this._wordDiv(B,q)},Y.prototype.div=function(B){return this.divmod(B,"div",!1).div},Y.prototype.mod=function(B){return this.divmod(B,"mod",!1).mod},Y.prototype.umod=function(B){return this.divmod(B,"mod",!0).mod},Y.prototype.divRound=function(B){var q=this.divmod(B);if(q.mod.isZero())return q.div;var P=q.div.negative!==0?q.mod.isub(B):q.mod,O=B.ushrn(1),w=B.andln(1),k=P.cmp(O);return k<0||w===1&&k===0?q.div:q.div.negative!==0?q.div.isubn(1):q.div.iaddn(1)},Y.prototype.modn=function(B){C(B<=67108863);for(var q=67108864%B,P=0,O=this.length-1;O>=0;O--)P=(q*P+(this.words[O]|0))%B;return P},Y.prototype.idivn=function(B){C(B<=67108863);for(var q=0,P=this.length-1;P>=0;P--){var O=(this.words[P]|0)+q*67108864;this.words[P]=O/B|0,q=O%B}return this.strip()},Y.prototype.divn=function(B){return this.clone().idivn(B)},Y.prototype.egcd=function(B){C(B.negative===0),C(!B.isZero());var q=this,P=B.clone();q.negative!==0?q=q.umod(B):q=q.clone();for(var O=new Y(1),w=new Y(0),k=new Y(0),S=new Y(1),_=0;q.isEven()&&P.isEven();)q.iushrn(1),P.iushrn(1),++_;for(var W=P.clone(),j=q.clone();!q.isZero();){for(var b=0,p=1;(q.words[0]&p)===0&&b<26;++b,p<<=1);if(b>0)for(q.iushrn(b);b-- >0;)(O.isOdd()||w.isOdd())&&(O.iadd(W),w.isub(j)),O.iushrn(1),w.iushrn(1);for(var s=0,r=1;(P.words[0]&r)===0&&s<26;++s,r<<=1);if(s>0)for(P.iushrn(s);s-- >0;)(k.isOdd()||S.isOdd())&&(k.iadd(W),S.isub(j)),k.iushrn(1),S.iushrn(1);q.cmp(P)>=0?(q.isub(P),O.isub(k),w.isub(S)):(P.isub(q),k.isub(O),S.isub(w))}return{a:k,b:S,gcd:P.iushln(_)}},Y.prototype._invmp=function(B){C(B.negative===0),C(!B.isZero());var q=this,P=B.clone();q.negative!==0?q=q.umod(B):q=q.clone();for(var O=new Y(1),w=new Y(0),k=P.clone();q.cmpn(1)>0&&P.cmpn(1)>0;){for(var S=0,_=1;(q.words[0]&_)===0&&S<26;++S,_<<=1);if(S>0)for(q.iushrn(S);S-- >0;)O.isOdd()&&O.iadd(k),O.iushrn(1);for(var W=0,j=1;(P.words[0]&j)===0&&W<26;++W,j<<=1);if(W>0)for(P.iushrn(W);W-- >0;)w.isOdd()&&w.iadd(k),w.iushrn(1);q.cmp(P)>=0?(q.isub(P),O.isub(w)):(P.isub(q),w.isub(O))}var b;return q.cmpn(1)===0?b=O:b=w,b.cmpn(0)<0&&b.iadd(B),b},Y.prototype.gcd=function(B){if(this.isZero())return B.abs();if(B.isZero())return this.abs();var q=this.clone(),P=B.clone();q.negative=0,P.negative=0;for(var O=0;q.isEven()&&P.isEven();O++)q.iushrn(1),P.iushrn(1);do{for(;q.isEven();)q.iushrn(1);for(;P.isEven();)P.iushrn(1);var w=q.cmp(P);if(w<0){var k=q;q=P,P=k}else if(w===0||P.cmpn(1)===0)break;q.isub(P)}while(!0);return P.iushln(O)},Y.prototype.invm=function(B){return this.egcd(B).a.umod(B)},Y.prototype.isEven=function(){return(this.words[0]&1)===0},Y.prototype.isOdd=function(){return(this.words[0]&1)===1},Y.prototype.andln=function(B){return this.words[0]&B},Y.prototype.bincn=function(B){C(typeof B=="number");var q=B%26,P=(B-q)/26,O=1<>>26,S&=67108863,this.words[k]=S}return w!==0&&(this.words[k]=w,this.length++),this},Y.prototype.isZero=function(){return this.length===1&&this.words[0]===0},Y.prototype.cmpn=function(B){var q=B<0;if(this.negative!==0&&!q)return-1;if(this.negative===0&&q)return 1;this.strip();var P;if(this.length>1)P=1;else{q&&(B=-B),C(B<=67108863,"Number is too big");var O=this.words[0]|0;P=O===B?0:OB.length)return 1;if(this.length=0;P--){var O=this.words[P]|0,w=B.words[P]|0;if(O!==w){Ow&&(q=1);break}}return q},Y.prototype.gtn=function(B){return this.cmpn(B)===1},Y.prototype.gt=function(B){return this.cmp(B)===1},Y.prototype.gten=function(B){return this.cmpn(B)>=0},Y.prototype.gte=function(B){return this.cmp(B)>=0},Y.prototype.ltn=function(B){return this.cmpn(B)===-1},Y.prototype.lt=function(B){return this.cmp(B)===-1},Y.prototype.lten=function(B){return this.cmpn(B)<=0},Y.prototype.lte=function(B){return this.cmp(B)<=0},Y.prototype.eqn=function(B){return this.cmpn(B)===0},Y.prototype.eq=function(B){return this.cmp(B)===0},Y.red=function(B){return new d(B)},Y.prototype.toRed=function(B){return C(!this.red,"Already a number in reduction context"),C(this.negative===0,"red works only with positives"),B.convertTo(this)._forceRed(B)},Y.prototype.fromRed=function(){return C(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},Y.prototype._forceRed=function(B){return this.red=B,this},Y.prototype.forceRed=function(B){return C(!this.red,"Already a number in reduction context"),this._forceRed(B)},Y.prototype.redAdd=function(B){return C(this.red,"redAdd works only with red numbers"),this.red.add(this,B)},Y.prototype.redIAdd=function(B){return C(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,B)},Y.prototype.redSub=function(B){return C(this.red,"redSub works only with red numbers"),this.red.sub(this,B)},Y.prototype.redISub=function(B){return C(this.red,"redISub works only with red numbers"),this.red.isub(this,B)},Y.prototype.redShl=function(B){return C(this.red,"redShl works only with red numbers"),this.red.shl(this,B)},Y.prototype.redMul=function(B){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.mul(this,B)},Y.prototype.redIMul=function(B){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.imul(this,B)},Y.prototype.redSqr=function(){return C(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},Y.prototype.redISqr=function(){return C(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},Y.prototype.redSqrt=function(){return C(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},Y.prototype.redInvm=function(){return C(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},Y.prototype.redNeg=function(){return C(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},Y.prototype.redPow=function(B){return C(this.red&&!B.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,B)};var T={k256:null,p224:null,p192:null,p25519:null};function h(B,q){this.name=B,this.p=new Y(q,16),this.n=this.p.bitLength(),this.k=new Y(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}h.prototype._tmp=function(){var B=new Y(null);return B.words=new Array(Math.ceil(this.n/13)),B},h.prototype.ireduce=function(B){var q=B,P;do this.split(q,this.tmp),q=this.imulK(q),q=q.iadd(this.tmp),P=q.bitLength();while(P>this.n);var O=P0?q.isub(this.p):q.strip!==void 0?q.strip():q._strip(),q},h.prototype.split=function(B,q){B.iushrn(this.n,0,q)},h.prototype.imulK=function(B){return B.imul(this.k)};function y(){h.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}U(y,h),y.prototype.split=function(B,q){for(var P=4194303,O=Math.min(B.length,9),w=0;w>>22,k=S}k>>>=22,B.words[w-10]=k,k===0&&B.length>10?B.length-=10:B.length-=9},y.prototype.imulK=function(B){B.words[B.length]=0,B.words[B.length+1]=0,B.length+=2;for(var q=0,P=0;P>>=26,B.words[P]=w,q=O}return q!==0&&(B.words[B.length++]=q),B},Y._prime=function(B){if(T[B])return T[B];var q;if(B==="k256")q=new y;else if(B==="p224")q=new g;else if(B==="p192")q=new f;else if(B==="p25519")q=new u;else throw new Error("Unknown prime "+B);return T[B]=q,q};function d(B){if(typeof B=="string"){var q=Y._prime(B);this.m=q.p,this.prime=q}else C(B.gtn(1),"modulus must be greater than 1"),this.m=B,this.prime=null}d.prototype._verify1=function(B){C(B.negative===0,"red works only with positives"),C(B.red,"red works only with red numbers")},d.prototype._verify2=function(B,q){C((B.negative|q.negative)===0,"red works only with positives"),C(B.red&&B.red===q.red,"red works only with red numbers")},d.prototype.imod=function(B){return this.prime?this.prime.ireduce(B)._forceRed(this):B.umod(this.m)._forceRed(this)},d.prototype.neg=function(B){return B.isZero()?B.clone():this.m.sub(B)._forceRed(this)},d.prototype.add=function(B,q){this._verify2(B,q);var P=B.add(q);return P.cmp(this.m)>=0&&P.isub(this.m),P._forceRed(this)},d.prototype.iadd=function(B,q){this._verify2(B,q);var P=B.iadd(q);return P.cmp(this.m)>=0&&P.isub(this.m),P},d.prototype.sub=function(B,q){this._verify2(B,q);var P=B.sub(q);return P.cmpn(0)<0&&P.iadd(this.m),P._forceRed(this)},d.prototype.isub=function(B,q){this._verify2(B,q);var P=B.isub(q);return P.cmpn(0)<0&&P.iadd(this.m),P},d.prototype.shl=function(B,q){return this._verify1(B),this.imod(B.ushln(q))},d.prototype.imul=function(B,q){return this._verify2(B,q),this.imod(B.imul(q))},d.prototype.mul=function(B,q){return this._verify2(B,q),this.imod(B.mul(q))},d.prototype.isqr=function(B){return this.imul(B,B.clone())},d.prototype.sqr=function(B){return this.mul(B,B)},d.prototype.sqrt=function(B){if(B.isZero())return B.clone();var q=this.m.andln(3);if(C(q%2===1),q===3){var P=this.m.add(new Y(1)).iushrn(2);return this.pow(B,P)}for(var O=this.m.subn(1),w=0;!O.isZero()&&O.andln(1)===0;)w++,O.iushrn(1);C(!O.isZero());var k=new Y(1).toRed(this),S=k.redNeg(),_=this.m.subn(1).iushrn(1),W=this.m.bitLength();for(W=new Y(2*W*W).toRed(this);this.pow(W,_).cmp(S)!==0;)W.redIAdd(S);for(var j=this.pow(W,O),b=this.pow(B,O.addn(1).iushrn(1)),p=this.pow(B,O),s=w;p.cmp(k)!==0;){for(var r=p,A1=0;r.cmp(k)!==0;A1++)r=r.redSqr();C(A1=0;w--){for(var j=q.words[w],b=W-1;b>=0;b--){var p=j>>b&1;if(k!==O[0]&&(k=this.sqr(k)),p===0&&S===0){_=0;continue}S<<=1,S|=p,_++,!(_!==P&&(w!==0||b!==0))&&(k=this.mul(k,O[S]),_=0,S=0)}W=26}return k},d.prototype.convertTo=function(B){var q=B.umod(this.m);return q===B?q.clone():q},d.prototype.convertFrom=function(B){var q=B.clone();return q.red=null,q},Y.mont=function(B){return new n(B)};function n(B){d.call(this,B),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new Y(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}U(n,d),n.prototype.convertTo=function(B){return this.imod(B.ushln(this.shift))},n.prototype.convertFrom=function(B){var q=this.imod(B.mul(this.rinv));return q.red=null,q},n.prototype.imul=function(B,q){if(B.isZero()||q.isZero())return B.words[0]=0,B.length=1,B;var P=B.imul(q),O=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=P.isub(O).iushrn(this.shift),k=w;return w.cmp(this.m)>=0?k=w.isub(this.m):w.cmpn(0)<0&&(k=w.iadd(this.m)),k._forceRed(this)},n.prototype.mul=function(B,q){if(B.isZero()||q.isZero())return new Y(0)._forceRed(this);var P=B.mul(q),O=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=P.isub(O).iushrn(this.shift),k=w;return w.cmp(this.m)>=0?k=w.isub(this.m):w.cmpn(0)<0&&(k=w.iadd(this.m)),k._forceRed(this)},n.prototype.invm=function(B){var q=this.imod(B._invmp(this.m).mul(this.r2));return q._forceRed(this)}})(typeof Q>"u"||Q,A)}),L91=l1((A,Q)=>{(function(J,K){function C(B,q){if(!B)throw new Error(q||"Assertion failed")}function U(B,q){B.super_=q;var P=function(){};P.prototype=q.prototype,B.prototype=new P,B.prototype.constructor=B}function Y(B,q,P){if(Y.isBN(B))return B;this.negative=0,this.words=null,this.length=0,this.red=null,B!==null&&((q==="le"||q==="be")&&(P=q,q=10),this._init(B||0,q||10,P||"be"))}typeof J=="object"?J.exports=Y:K.BN=Y,Y.BN=Y,Y.wordSize=26;var Z;try{typeof window<"u"&&typeof window.Buffer<"u"?Z=window.Buffer:Z=XQ().Buffer}catch{}Y.isBN=function(B){return B instanceof Y?!0:B!==null&&typeof B=="object"&&B.constructor.wordSize===Y.wordSize&&Array.isArray(B.words)},Y.max=function(B,q){return B.cmp(q)>0?B:q},Y.min=function(B,q){return B.cmp(q)<0?B:q},Y.prototype._init=function(B,q,P){if(typeof B=="number")return this._initNumber(B,q,P);if(typeof B=="object")return this._initArray(B,q,P);q==="hex"&&(q=16),C(q===(q|0)&&q>=2&&q<=36),B=B.toString().replace(/\s+/g,"");var O=0;B[0]==="-"&&(O++,this.negative=1),O=0;O-=3)k=B[O]|B[O-1]<<8|B[O-2]<<16,this.words[w]|=k<>>26-S&67108863,S+=24,S>=26&&(S-=26,w++);else if(P==="le")for(O=0,w=0;O>>26-S&67108863,S+=24,S>=26&&(S-=26,w++);return this.strip()};function X(B,q){var P=B.charCodeAt(q);return P>=65&&P<=70?P-55:P>=97&&P<=102?P-87:P-48&15}function E(B,q,P){var O=X(B,P);return P-1>=q&&(O|=X(B,P-1)<<4),O}Y.prototype._parseHex=function(B,q,P){this.length=Math.ceil((B.length-q)/6),this.words=new Array(this.length);for(var O=0;O=q;O-=2)S=E(B,q,O)<=18?(w-=18,k+=1,this.words[k]|=S>>>26):w+=8;else{var _=B.length-q;for(O=_%2===0?q+1:q;O=18?(w-=18,k+=1,this.words[k]|=S>>>26):w+=8}this.strip()};function H(B,q,P,O){for(var w=0,k=Math.min(B.length,P),S=q;S=49?w+=_-49+10:_>=17?w+=_-17+10:w+=_}return w}Y.prototype._parseBase=function(B,q,P){this.words=[0],this.length=1;for(var O=0,w=1;w<=67108863;w*=q)O++;O--,w=w/q|0;for(var k=B.length-P,S=k%O,_=Math.min(k,k-S)+P,W=0,j=P;j<_;j+=O)W=H(B,j,j+O,q),this.imuln(w),this.words[0]+W<67108864?this.words[0]+=W:this._iaddn(W);if(S!==0){var b=1;for(W=H(B,j,B.length,q),j=0;j1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},Y.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},Y.prototype.inspect=function(){return(this.red?""};var $=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],I=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],N=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];Y.prototype.toString=function(B,q){B=B||10,q=q|0||1;var P;if(B===16||B==="hex"){P="";for(var O=0,w=0,k=0;k>>24-O&16777215,w!==0||k!==this.length-1?P=$[6-_.length]+_+P:P=_+P,O+=2,O>=26&&(O-=26,k--)}for(w!==0&&(P=w.toString(16)+P);P.length%q!==0;)P="0"+P;return this.negative!==0&&(P="-"+P),P}if(B===(B|0)&&B>=2&&B<=36){var W=I[B],j=N[B];P="";var b=this.clone();for(b.negative=0;!b.isZero();){var p=b.modn(j).toString(B);b=b.idivn(j),b.isZero()?P=p+P:P=$[W-p.length]+p+P}for(this.isZero()&&(P="0"+P);P.length%q!==0;)P="0"+P;return this.negative!==0&&(P="-"+P),P}C(!1,"Base should be between 2 and 36")},Y.prototype.toNumber=function(){var B=this.words[0];return this.length===2?B+=this.words[1]*67108864:this.length===3&&this.words[2]===1?B+=4503599627370496+this.words[1]*67108864:this.length>2&&C(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-B:B},Y.prototype.toJSON=function(){return this.toString(16)},Y.prototype.toBuffer=function(B,q){return C(typeof Z<"u"),this.toArrayLike(Z,B,q)},Y.prototype.toArray=function(B,q){return this.toArrayLike(Array,B,q)},Y.prototype.toArrayLike=function(B,q,P){var O=this.byteLength(),w=P||Math.max(1,O);C(O<=w,"byte array longer than desired length"),C(w>0,"Requested array length <= 0"),this.strip();var k=q==="le",S=new B(w),_,W,j=this.clone();if(k){for(W=0;!j.isZero();W++)_=j.andln(255),j.iushrn(8),S[W]=_;for(;W=4096&&(P+=13,q>>>=13),q>=64&&(P+=7,q>>>=7),q>=8&&(P+=4,q>>>=4),q>=2&&(P+=2,q>>>=2),P+q},Y.prototype._zeroBits=function(B){if(B===0)return 26;var q=B,P=0;return(q&8191)===0&&(P+=13,q>>>=13),(q&127)===0&&(P+=7,q>>>=7),(q&15)===0&&(P+=4,q>>>=4),(q&3)===0&&(P+=2,q>>>=2),(q&1)===0&&P++,P},Y.prototype.bitLength=function(){var B=this.words[this.length-1],q=this._countBits(B);return(this.length-1)*26+q};function F(B){for(var q=new Array(B.bitLength()),P=0;P>>w}return q}Y.prototype.zeroBits=function(){if(this.isZero())return 0;for(var B=0,q=0;qB.length?this.clone().ior(B):B.clone().ior(this)},Y.prototype.uor=function(B){return this.length>B.length?this.clone().iuor(B):B.clone().iuor(this)},Y.prototype.iuand=function(B){var q;this.length>B.length?q=B:q=this;for(var P=0;PB.length?this.clone().iand(B):B.clone().iand(this)},Y.prototype.uand=function(B){return this.length>B.length?this.clone().iuand(B):B.clone().iuand(this)},Y.prototype.iuxor=function(B){var q,P;this.length>B.length?(q=this,P=B):(q=B,P=this);for(var O=0;OB.length?this.clone().ixor(B):B.clone().ixor(this)},Y.prototype.uxor=function(B){return this.length>B.length?this.clone().iuxor(B):B.clone().iuxor(this)},Y.prototype.inotn=function(B){C(typeof B=="number"&&B>=0);var q=Math.ceil(B/26)|0,P=B%26;this._expand(q),P>0&&q--;for(var O=0;O0&&(this.words[O]=~this.words[O]&67108863>>26-P),this.strip()},Y.prototype.notn=function(B){return this.clone().inotn(B)},Y.prototype.setn=function(B,q){C(typeof B=="number"&&B>=0);var P=B/26|0,O=B%26;return this._expand(P+1),q?this.words[P]=this.words[P]|1<B.length?(P=this,O=B):(P=B,O=this);for(var w=0,k=0;k>>26;for(;w!==0&&k>>26;if(this.length=P.length,w!==0)this.words[this.length]=w,this.length++;else if(P!==this)for(;kB.length?this.clone().iadd(B):B.clone().iadd(this)},Y.prototype.isub=function(B){if(B.negative!==0){B.negative=0;var q=this.iadd(B);return B.negative=1,q._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(B),this.negative=1,this._normSign();var P=this.cmp(B);if(P===0)return this.negative=0,this.length=1,this.words[0]=0,this;var O,w;P>0?(O=this,w=B):(O=B,w=this);for(var k=0,S=0;S>26,this.words[S]=q&67108863;for(;k!==0&&S>26,this.words[S]=q&67108863;if(k===0&&S>>26,p=W&67108863,s=Math.min(j,q.length-1),r=Math.max(0,j-B.length+1);r<=s;r++){var A1=j-r|0;w=B.words[A1]|0,k=q.words[r]|0,S=w*k+p,b+=S/67108864|0,p=S&67108863}P.words[j]=p|0,W=b|0}return W!==0?P.words[j]=W|0:P.length--,P.strip()}var D=function(B,q,P){var O=B.words,w=q.words,k=P.words,S=0,_,W,j,b=O[0]|0,p=b&8191,s=b>>>13,r=O[1]|0,A1=r&8191,Q1=r>>>13,e=O[2]|0,t=e&8191,U1=e>>>13,O1=O[3]|0,E1=O1&8191,Y1=O1>>>13,i=O[4]|0,c=i&8191,o=i>>>13,C1=O[5]|0,q1=C1&8191,Z1=C1>>>13,j1=O[6]|0,H1=j1&8191,B1=j1>>>13,k1=O[7]|0,D1=k1&8191,G1=k1>>>13,w1=O[8]|0,G=w1&8191,z=w1>>>13,x=O[9]|0,m=x&8191,l=x>>>13,a=w[0]|0,K1=a&8191,F1=a>>>13,R1=w[1]|0,X1=R1&8191,W1=R1>>>13,$1=w[2]|0,N1=$1&8191,_1=$1>>>13,J1=w[3]|0,z1=J1&8191,M1=J1>>>13,L1=w[4]|0,V1=L1&8191,S1=L1>>>13,O0=w[5]|0,h1=O0&8191,b1=O0>>>13,f0=w[6]|0,e1=f0&8191,s1=f0>>>13,o0=w[7]|0,a1=o0&8191,r1=o0>>>13,FA=w[8]|0,K0=FA&8191,J0=FA>>>13,qA=w[9]|0,Q0=qA&8191,A0=qA>>>13;P.negative=B.negative^q.negative,P.length=19,_=Math.imul(p,K1),W=Math.imul(p,F1),W=W+Math.imul(s,K1)|0,j=Math.imul(s,F1);var hA=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(hA>>>26)|0,hA&=67108863,_=Math.imul(A1,K1),W=Math.imul(A1,F1),W=W+Math.imul(Q1,K1)|0,j=Math.imul(Q1,F1),_=_+Math.imul(p,X1)|0,W=W+Math.imul(p,W1)|0,W=W+Math.imul(s,X1)|0,j=j+Math.imul(s,W1)|0;var r0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(r0>>>26)|0,r0&=67108863,_=Math.imul(t,K1),W=Math.imul(t,F1),W=W+Math.imul(U1,K1)|0,j=Math.imul(U1,F1),_=_+Math.imul(A1,X1)|0,W=W+Math.imul(A1,W1)|0,W=W+Math.imul(Q1,X1)|0,j=j+Math.imul(Q1,W1)|0,_=_+Math.imul(p,N1)|0,W=W+Math.imul(p,_1)|0,W=W+Math.imul(s,N1)|0,j=j+Math.imul(s,_1)|0;var EA=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(EA>>>26)|0,EA&=67108863,_=Math.imul(E1,K1),W=Math.imul(E1,F1),W=W+Math.imul(Y1,K1)|0,j=Math.imul(Y1,F1),_=_+Math.imul(t,X1)|0,W=W+Math.imul(t,W1)|0,W=W+Math.imul(U1,X1)|0,j=j+Math.imul(U1,W1)|0,_=_+Math.imul(A1,N1)|0,W=W+Math.imul(A1,_1)|0,W=W+Math.imul(Q1,N1)|0,j=j+Math.imul(Q1,_1)|0,_=_+Math.imul(p,z1)|0,W=W+Math.imul(p,M1)|0,W=W+Math.imul(s,z1)|0,j=j+Math.imul(s,M1)|0;var X2=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(X2>>>26)|0,X2&=67108863,_=Math.imul(c,K1),W=Math.imul(c,F1),W=W+Math.imul(o,K1)|0,j=Math.imul(o,F1),_=_+Math.imul(E1,X1)|0,W=W+Math.imul(E1,W1)|0,W=W+Math.imul(Y1,X1)|0,j=j+Math.imul(Y1,W1)|0,_=_+Math.imul(t,N1)|0,W=W+Math.imul(t,_1)|0,W=W+Math.imul(U1,N1)|0,j=j+Math.imul(U1,_1)|0,_=_+Math.imul(A1,z1)|0,W=W+Math.imul(A1,M1)|0,W=W+Math.imul(Q1,z1)|0,j=j+Math.imul(Q1,M1)|0,_=_+Math.imul(p,V1)|0,W=W+Math.imul(p,S1)|0,W=W+Math.imul(s,V1)|0,j=j+Math.imul(s,S1)|0;var E2=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(E2>>>26)|0,E2&=67108863,_=Math.imul(q1,K1),W=Math.imul(q1,F1),W=W+Math.imul(Z1,K1)|0,j=Math.imul(Z1,F1),_=_+Math.imul(c,X1)|0,W=W+Math.imul(c,W1)|0,W=W+Math.imul(o,X1)|0,j=j+Math.imul(o,W1)|0,_=_+Math.imul(E1,N1)|0,W=W+Math.imul(E1,_1)|0,W=W+Math.imul(Y1,N1)|0,j=j+Math.imul(Y1,_1)|0,_=_+Math.imul(t,z1)|0,W=W+Math.imul(t,M1)|0,W=W+Math.imul(U1,z1)|0,j=j+Math.imul(U1,M1)|0,_=_+Math.imul(A1,V1)|0,W=W+Math.imul(A1,S1)|0,W=W+Math.imul(Q1,V1)|0,j=j+Math.imul(Q1,S1)|0,_=_+Math.imul(p,h1)|0,W=W+Math.imul(p,b1)|0,W=W+Math.imul(s,h1)|0,j=j+Math.imul(s,b1)|0;var T1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(T1>>>26)|0,T1&=67108863,_=Math.imul(H1,K1),W=Math.imul(H1,F1),W=W+Math.imul(B1,K1)|0,j=Math.imul(B1,F1),_=_+Math.imul(q1,X1)|0,W=W+Math.imul(q1,W1)|0,W=W+Math.imul(Z1,X1)|0,j=j+Math.imul(Z1,W1)|0,_=_+Math.imul(c,N1)|0,W=W+Math.imul(c,_1)|0,W=W+Math.imul(o,N1)|0,j=j+Math.imul(o,_1)|0,_=_+Math.imul(E1,z1)|0,W=W+Math.imul(E1,M1)|0,W=W+Math.imul(Y1,z1)|0,j=j+Math.imul(Y1,M1)|0,_=_+Math.imul(t,V1)|0,W=W+Math.imul(t,S1)|0,W=W+Math.imul(U1,V1)|0,j=j+Math.imul(U1,S1)|0,_=_+Math.imul(A1,h1)|0,W=W+Math.imul(A1,b1)|0,W=W+Math.imul(Q1,h1)|0,j=j+Math.imul(Q1,b1)|0,_=_+Math.imul(p,e1)|0,W=W+Math.imul(p,s1)|0,W=W+Math.imul(s,e1)|0,j=j+Math.imul(s,s1)|0;var m1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(m1>>>26)|0,m1&=67108863,_=Math.imul(D1,K1),W=Math.imul(D1,F1),W=W+Math.imul(G1,K1)|0,j=Math.imul(G1,F1),_=_+Math.imul(H1,X1)|0,W=W+Math.imul(H1,W1)|0,W=W+Math.imul(B1,X1)|0,j=j+Math.imul(B1,W1)|0,_=_+Math.imul(q1,N1)|0,W=W+Math.imul(q1,_1)|0,W=W+Math.imul(Z1,N1)|0,j=j+Math.imul(Z1,_1)|0,_=_+Math.imul(c,z1)|0,W=W+Math.imul(c,M1)|0,W=W+Math.imul(o,z1)|0,j=j+Math.imul(o,M1)|0,_=_+Math.imul(E1,V1)|0,W=W+Math.imul(E1,S1)|0,W=W+Math.imul(Y1,V1)|0,j=j+Math.imul(Y1,S1)|0,_=_+Math.imul(t,h1)|0,W=W+Math.imul(t,b1)|0,W=W+Math.imul(U1,h1)|0,j=j+Math.imul(U1,b1)|0,_=_+Math.imul(A1,e1)|0,W=W+Math.imul(A1,s1)|0,W=W+Math.imul(Q1,e1)|0,j=j+Math.imul(Q1,s1)|0,_=_+Math.imul(p,a1)|0,W=W+Math.imul(p,r1)|0,W=W+Math.imul(s,a1)|0,j=j+Math.imul(s,r1)|0;var i1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(i1>>>26)|0,i1&=67108863,_=Math.imul(G,K1),W=Math.imul(G,F1),W=W+Math.imul(z,K1)|0,j=Math.imul(z,F1),_=_+Math.imul(D1,X1)|0,W=W+Math.imul(D1,W1)|0,W=W+Math.imul(G1,X1)|0,j=j+Math.imul(G1,W1)|0,_=_+Math.imul(H1,N1)|0,W=W+Math.imul(H1,_1)|0,W=W+Math.imul(B1,N1)|0,j=j+Math.imul(B1,_1)|0,_=_+Math.imul(q1,z1)|0,W=W+Math.imul(q1,M1)|0,W=W+Math.imul(Z1,z1)|0,j=j+Math.imul(Z1,M1)|0,_=_+Math.imul(c,V1)|0,W=W+Math.imul(c,S1)|0,W=W+Math.imul(o,V1)|0,j=j+Math.imul(o,S1)|0,_=_+Math.imul(E1,h1)|0,W=W+Math.imul(E1,b1)|0,W=W+Math.imul(Y1,h1)|0,j=j+Math.imul(Y1,b1)|0,_=_+Math.imul(t,e1)|0,W=W+Math.imul(t,s1)|0,W=W+Math.imul(U1,e1)|0,j=j+Math.imul(U1,s1)|0,_=_+Math.imul(A1,a1)|0,W=W+Math.imul(A1,r1)|0,W=W+Math.imul(Q1,a1)|0,j=j+Math.imul(Q1,r1)|0,_=_+Math.imul(p,K0)|0,W=W+Math.imul(p,J0)|0,W=W+Math.imul(s,K0)|0,j=j+Math.imul(s,J0)|0;var t1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(t1>>>26)|0,t1&=67108863,_=Math.imul(m,K1),W=Math.imul(m,F1),W=W+Math.imul(l,K1)|0,j=Math.imul(l,F1),_=_+Math.imul(G,X1)|0,W=W+Math.imul(G,W1)|0,W=W+Math.imul(z,X1)|0,j=j+Math.imul(z,W1)|0,_=_+Math.imul(D1,N1)|0,W=W+Math.imul(D1,_1)|0,W=W+Math.imul(G1,N1)|0,j=j+Math.imul(G1,_1)|0,_=_+Math.imul(H1,z1)|0,W=W+Math.imul(H1,M1)|0,W=W+Math.imul(B1,z1)|0,j=j+Math.imul(B1,M1)|0,_=_+Math.imul(q1,V1)|0,W=W+Math.imul(q1,S1)|0,W=W+Math.imul(Z1,V1)|0,j=j+Math.imul(Z1,S1)|0,_=_+Math.imul(c,h1)|0,W=W+Math.imul(c,b1)|0,W=W+Math.imul(o,h1)|0,j=j+Math.imul(o,b1)|0,_=_+Math.imul(E1,e1)|0,W=W+Math.imul(E1,s1)|0,W=W+Math.imul(Y1,e1)|0,j=j+Math.imul(Y1,s1)|0,_=_+Math.imul(t,a1)|0,W=W+Math.imul(t,r1)|0,W=W+Math.imul(U1,a1)|0,j=j+Math.imul(U1,r1)|0,_=_+Math.imul(A1,K0)|0,W=W+Math.imul(A1,J0)|0,W=W+Math.imul(Q1,K0)|0,j=j+Math.imul(Q1,J0)|0,_=_+Math.imul(p,Q0)|0,W=W+Math.imul(p,A0)|0,W=W+Math.imul(s,Q0)|0,j=j+Math.imul(s,A0)|0;var d1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(d1>>>26)|0,d1&=67108863,_=Math.imul(m,X1),W=Math.imul(m,W1),W=W+Math.imul(l,X1)|0,j=Math.imul(l,W1),_=_+Math.imul(G,N1)|0,W=W+Math.imul(G,_1)|0,W=W+Math.imul(z,N1)|0,j=j+Math.imul(z,_1)|0,_=_+Math.imul(D1,z1)|0,W=W+Math.imul(D1,M1)|0,W=W+Math.imul(G1,z1)|0,j=j+Math.imul(G1,M1)|0,_=_+Math.imul(H1,V1)|0,W=W+Math.imul(H1,S1)|0,W=W+Math.imul(B1,V1)|0,j=j+Math.imul(B1,S1)|0,_=_+Math.imul(q1,h1)|0,W=W+Math.imul(q1,b1)|0,W=W+Math.imul(Z1,h1)|0,j=j+Math.imul(Z1,b1)|0,_=_+Math.imul(c,e1)|0,W=W+Math.imul(c,s1)|0,W=W+Math.imul(o,e1)|0,j=j+Math.imul(o,s1)|0,_=_+Math.imul(E1,a1)|0,W=W+Math.imul(E1,r1)|0,W=W+Math.imul(Y1,a1)|0,j=j+Math.imul(Y1,r1)|0,_=_+Math.imul(t,K0)|0,W=W+Math.imul(t,J0)|0,W=W+Math.imul(U1,K0)|0,j=j+Math.imul(U1,J0)|0,_=_+Math.imul(A1,Q0)|0,W=W+Math.imul(A1,A0)|0,W=W+Math.imul(Q1,Q0)|0,j=j+Math.imul(Q1,A0)|0;var H0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(H0>>>26)|0,H0&=67108863,_=Math.imul(m,N1),W=Math.imul(m,_1),W=W+Math.imul(l,N1)|0,j=Math.imul(l,_1),_=_+Math.imul(G,z1)|0,W=W+Math.imul(G,M1)|0,W=W+Math.imul(z,z1)|0,j=j+Math.imul(z,M1)|0,_=_+Math.imul(D1,V1)|0,W=W+Math.imul(D1,S1)|0,W=W+Math.imul(G1,V1)|0,j=j+Math.imul(G1,S1)|0,_=_+Math.imul(H1,h1)|0,W=W+Math.imul(H1,b1)|0,W=W+Math.imul(B1,h1)|0,j=j+Math.imul(B1,b1)|0,_=_+Math.imul(q1,e1)|0,W=W+Math.imul(q1,s1)|0,W=W+Math.imul(Z1,e1)|0,j=j+Math.imul(Z1,s1)|0,_=_+Math.imul(c,a1)|0,W=W+Math.imul(c,r1)|0,W=W+Math.imul(o,a1)|0,j=j+Math.imul(o,r1)|0,_=_+Math.imul(E1,K0)|0,W=W+Math.imul(E1,J0)|0,W=W+Math.imul(Y1,K0)|0,j=j+Math.imul(Y1,J0)|0,_=_+Math.imul(t,Q0)|0,W=W+Math.imul(t,A0)|0,W=W+Math.imul(U1,Q0)|0,j=j+Math.imul(U1,A0)|0;var R0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(R0>>>26)|0,R0&=67108863,_=Math.imul(m,z1),W=Math.imul(m,M1),W=W+Math.imul(l,z1)|0,j=Math.imul(l,M1),_=_+Math.imul(G,V1)|0,W=W+Math.imul(G,S1)|0,W=W+Math.imul(z,V1)|0,j=j+Math.imul(z,S1)|0,_=_+Math.imul(D1,h1)|0,W=W+Math.imul(D1,b1)|0,W=W+Math.imul(G1,h1)|0,j=j+Math.imul(G1,b1)|0,_=_+Math.imul(H1,e1)|0,W=W+Math.imul(H1,s1)|0,W=W+Math.imul(B1,e1)|0,j=j+Math.imul(B1,s1)|0,_=_+Math.imul(q1,a1)|0,W=W+Math.imul(q1,r1)|0,W=W+Math.imul(Z1,a1)|0,j=j+Math.imul(Z1,r1)|0,_=_+Math.imul(c,K0)|0,W=W+Math.imul(c,J0)|0,W=W+Math.imul(o,K0)|0,j=j+Math.imul(o,J0)|0,_=_+Math.imul(E1,Q0)|0,W=W+Math.imul(E1,A0)|0,W=W+Math.imul(Y1,Q0)|0,j=j+Math.imul(Y1,A0)|0;var D0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(D0>>>26)|0,D0&=67108863,_=Math.imul(m,V1),W=Math.imul(m,S1),W=W+Math.imul(l,V1)|0,j=Math.imul(l,S1),_=_+Math.imul(G,h1)|0,W=W+Math.imul(G,b1)|0,W=W+Math.imul(z,h1)|0,j=j+Math.imul(z,b1)|0,_=_+Math.imul(D1,e1)|0,W=W+Math.imul(D1,s1)|0,W=W+Math.imul(G1,e1)|0,j=j+Math.imul(G1,s1)|0,_=_+Math.imul(H1,a1)|0,W=W+Math.imul(H1,r1)|0,W=W+Math.imul(B1,a1)|0,j=j+Math.imul(B1,r1)|0,_=_+Math.imul(q1,K0)|0,W=W+Math.imul(q1,J0)|0,W=W+Math.imul(Z1,K0)|0,j=j+Math.imul(Z1,J0)|0,_=_+Math.imul(c,Q0)|0,W=W+Math.imul(c,A0)|0,W=W+Math.imul(o,Q0)|0,j=j+Math.imul(o,A0)|0;var P0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(P0>>>26)|0,P0&=67108863,_=Math.imul(m,h1),W=Math.imul(m,b1),W=W+Math.imul(l,h1)|0,j=Math.imul(l,b1),_=_+Math.imul(G,e1)|0,W=W+Math.imul(G,s1)|0,W=W+Math.imul(z,e1)|0,j=j+Math.imul(z,s1)|0,_=_+Math.imul(D1,a1)|0,W=W+Math.imul(D1,r1)|0,W=W+Math.imul(G1,a1)|0,j=j+Math.imul(G1,r1)|0,_=_+Math.imul(H1,K0)|0,W=W+Math.imul(H1,J0)|0,W=W+Math.imul(B1,K0)|0,j=j+Math.imul(B1,J0)|0,_=_+Math.imul(q1,Q0)|0,W=W+Math.imul(q1,A0)|0,W=W+Math.imul(Z1,Q0)|0,j=j+Math.imul(Z1,A0)|0;var j0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(j0>>>26)|0,j0&=67108863,_=Math.imul(m,e1),W=Math.imul(m,s1),W=W+Math.imul(l,e1)|0,j=Math.imul(l,s1),_=_+Math.imul(G,a1)|0,W=W+Math.imul(G,r1)|0,W=W+Math.imul(z,a1)|0,j=j+Math.imul(z,r1)|0,_=_+Math.imul(D1,K0)|0,W=W+Math.imul(D1,J0)|0,W=W+Math.imul(G1,K0)|0,j=j+Math.imul(G1,J0)|0,_=_+Math.imul(H1,Q0)|0,W=W+Math.imul(H1,A0)|0,W=W+Math.imul(B1,Q0)|0,j=j+Math.imul(B1,A0)|0;var v0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(v0>>>26)|0,v0&=67108863,_=Math.imul(m,a1),W=Math.imul(m,r1),W=W+Math.imul(l,a1)|0,j=Math.imul(l,r1),_=_+Math.imul(G,K0)|0,W=W+Math.imul(G,J0)|0,W=W+Math.imul(z,K0)|0,j=j+Math.imul(z,J0)|0,_=_+Math.imul(D1,Q0)|0,W=W+Math.imul(D1,A0)|0,W=W+Math.imul(G1,Q0)|0,j=j+Math.imul(G1,A0)|0;var S0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(S0>>>26)|0,S0&=67108863,_=Math.imul(m,K0),W=Math.imul(m,J0),W=W+Math.imul(l,K0)|0,j=Math.imul(l,J0),_=_+Math.imul(G,Q0)|0,W=W+Math.imul(G,A0)|0,W=W+Math.imul(z,Q0)|0,j=j+Math.imul(z,A0)|0;var n0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(n0>>>26)|0,n0&=67108863,_=Math.imul(m,Q0),W=Math.imul(m,A0),W=W+Math.imul(l,Q0)|0,j=Math.imul(l,A0);var i0=(S+_|0)+((W&8191)<<13)|0;return S=(j+(W>>>13)|0)+(i0>>>26)|0,i0&=67108863,k[0]=hA,k[1]=r0,k[2]=EA,k[3]=X2,k[4]=E2,k[5]=T1,k[6]=m1,k[7]=i1,k[8]=t1,k[9]=d1,k[10]=H0,k[11]=R0,k[12]=D0,k[13]=P0,k[14]=j0,k[15]=v0,k[16]=S0,k[17]=n0,k[18]=i0,S!==0&&(k[19]=S,P.length++),P};Math.imul||(D=V);function L(B,q,P){P.negative=q.negative^B.negative,P.length=B.length+q.length;for(var O=0,w=0,k=0;k>>26)|0,w+=S>>>26,S&=67108863}P.words[k]=_,O=S,S=w}return O!==0?P.words[k]=O:P.length--,P.strip()}function R(B,q,P){var O=new M;return O.mulp(B,q,P)}Y.prototype.mulTo=function(B,q){var P,O=this.length+B.length;return this.length===10&&B.length===10?P=D(this,B,q):O<63?P=V(this,B,q):O<1024?P=L(this,B,q):P=R(this,B,q),P};function M(B,q){this.x=B,this.y=q}M.prototype.makeRBT=function(B){for(var q=new Array(B),P=Y.prototype._countBits(B)-1,O=0;O>=1;return O},M.prototype.permute=function(B,q,P,O,w,k){for(var S=0;S>>1)w++;return 1<>>13,P[2*k+1]=w&8191,w=w>>>13;for(k=2*q;k>=26,q+=O/67108864|0,q+=w>>>26,this.words[P]=w&67108863}return q!==0&&(this.words[P]=q,this.length++),this},Y.prototype.muln=function(B){return this.clone().imuln(B)},Y.prototype.sqr=function(){return this.mul(this)},Y.prototype.isqr=function(){return this.imul(this.clone())},Y.prototype.pow=function(B){var q=F(B);if(q.length===0)return new Y(1);for(var P=this,O=0;O=0);var q=B%26,P=(B-q)/26,O=67108863>>>26-q<<26-q,w;if(q!==0){var k=0;for(w=0;w>>26-q}k&&(this.words[w]=k,this.length++)}if(P!==0){for(w=this.length-1;w>=0;w--)this.words[w+P]=this.words[w];for(w=0;w=0);var O;q?O=(q-q%26)/26:O=0;var w=B%26,k=Math.min((B-w)/26,this.length),S=67108863^67108863>>>w<k)for(this.length-=k,W=0;W=0&&(j!==0||W>=O);W--){var b=this.words[W]|0;this.words[W]=j<<26-w|b>>>w,j=b&S}return _&&j!==0&&(_.words[_.length++]=j),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},Y.prototype.ishrn=function(B,q,P){return C(this.negative===0),this.iushrn(B,q,P)},Y.prototype.shln=function(B){return this.clone().ishln(B)},Y.prototype.ushln=function(B){return this.clone().iushln(B)},Y.prototype.shrn=function(B){return this.clone().ishrn(B)},Y.prototype.ushrn=function(B){return this.clone().iushrn(B)},Y.prototype.testn=function(B){C(typeof B=="number"&&B>=0);var q=B%26,P=(B-q)/26,O=1<=0);var q=B%26,P=(B-q)/26;if(C(this.negative===0,"imaskn works only with positive numbers"),this.length<=P)return this;if(q!==0&&P++,this.length=Math.min(P,this.length),q!==0){var O=67108863^67108863>>>q<=67108864;q++)this.words[q]-=67108864,q===this.length-1?this.words[q+1]=1:this.words[q+1]++;return this.length=Math.max(this.length,q+1),this},Y.prototype.isubn=function(B){if(C(typeof B=="number"),C(B<67108864),B<0)return this.iaddn(-B);if(this.negative!==0)return this.negative=0,this.iaddn(B),this.negative=1,this;if(this.words[0]-=B,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var q=0;q>26)-(_/67108864|0),this.words[w+P]=k&67108863}for(;w>26,this.words[w+P]=k&67108863;if(S===0)return this.strip();for(C(S===-1),S=0,w=0;w>26,this.words[w]=k&67108863;return this.negative=1,this.strip()},Y.prototype._wordDiv=function(B,q){var P=this.length-B.length,O=this.clone(),w=B,k=w.words[w.length-1]|0,S=this._countBits(k);P=26-S,P!==0&&(w=w.ushln(P),O.iushln(P),k=w.words[w.length-1]|0);var _=O.length-w.length,W;if(q!=="mod"){W=new Y(null),W.length=_+1,W.words=new Array(W.length);for(var j=0;j=0;p--){var s=(O.words[w.length+p]|0)*67108864+(O.words[w.length+p-1]|0);for(s=Math.min(s/k|0,67108863),O._ishlnsubmul(w,s,p);O.negative!==0;)s--,O.negative=0,O._ishlnsubmul(w,1,p),O.isZero()||(O.negative^=1);W&&(W.words[p]=s)}return W&&W.strip(),O.strip(),q!=="div"&&P!==0&&O.iushrn(P),{div:W||null,mod:O}},Y.prototype.divmod=function(B,q,P){if(C(!B.isZero()),this.isZero())return{div:new Y(0),mod:new Y(0)};var O,w,k;return this.negative!==0&&B.negative===0?(k=this.neg().divmod(B,q),q!=="mod"&&(O=k.div.neg()),q!=="div"&&(w=k.mod.neg(),P&&w.negative!==0&&w.iadd(B)),{div:O,mod:w}):this.negative===0&&B.negative!==0?(k=this.divmod(B.neg(),q),q!=="mod"&&(O=k.div.neg()),{div:O,mod:k.mod}):(this.negative&B.negative)!==0?(k=this.neg().divmod(B.neg(),q),q!=="div"&&(w=k.mod.neg(),P&&w.negative!==0&&w.isub(B)),{div:k.div,mod:w}):B.length>this.length||this.cmp(B)<0?{div:new Y(0),mod:this}:B.length===1?q==="div"?{div:this.divn(B.words[0]),mod:null}:q==="mod"?{div:null,mod:new Y(this.modn(B.words[0]))}:{div:this.divn(B.words[0]),mod:new Y(this.modn(B.words[0]))}:this._wordDiv(B,q)},Y.prototype.div=function(B){return this.divmod(B,"div",!1).div},Y.prototype.mod=function(B){return this.divmod(B,"mod",!1).mod},Y.prototype.umod=function(B){return this.divmod(B,"mod",!0).mod},Y.prototype.divRound=function(B){var q=this.divmod(B);if(q.mod.isZero())return q.div;var P=q.div.negative!==0?q.mod.isub(B):q.mod,O=B.ushrn(1),w=B.andln(1),k=P.cmp(O);return k<0||w===1&&k===0?q.div:q.div.negative!==0?q.div.isubn(1):q.div.iaddn(1)},Y.prototype.modn=function(B){C(B<=67108863);for(var q=67108864%B,P=0,O=this.length-1;O>=0;O--)P=(q*P+(this.words[O]|0))%B;return P},Y.prototype.idivn=function(B){C(B<=67108863);for(var q=0,P=this.length-1;P>=0;P--){var O=(this.words[P]|0)+q*67108864;this.words[P]=O/B|0,q=O%B}return this.strip()},Y.prototype.divn=function(B){return this.clone().idivn(B)},Y.prototype.egcd=function(B){C(B.negative===0),C(!B.isZero());var q=this,P=B.clone();q.negative!==0?q=q.umod(B):q=q.clone();for(var O=new Y(1),w=new Y(0),k=new Y(0),S=new Y(1),_=0;q.isEven()&&P.isEven();)q.iushrn(1),P.iushrn(1),++_;for(var W=P.clone(),j=q.clone();!q.isZero();){for(var b=0,p=1;(q.words[0]&p)===0&&b<26;++b,p<<=1);if(b>0)for(q.iushrn(b);b-- >0;)(O.isOdd()||w.isOdd())&&(O.iadd(W),w.isub(j)),O.iushrn(1),w.iushrn(1);for(var s=0,r=1;(P.words[0]&r)===0&&s<26;++s,r<<=1);if(s>0)for(P.iushrn(s);s-- >0;)(k.isOdd()||S.isOdd())&&(k.iadd(W),S.isub(j)),k.iushrn(1),S.iushrn(1);q.cmp(P)>=0?(q.isub(P),O.isub(k),w.isub(S)):(P.isub(q),k.isub(O),S.isub(w))}return{a:k,b:S,gcd:P.iushln(_)}},Y.prototype._invmp=function(B){C(B.negative===0),C(!B.isZero());var q=this,P=B.clone();q.negative!==0?q=q.umod(B):q=q.clone();for(var O=new Y(1),w=new Y(0),k=P.clone();q.cmpn(1)>0&&P.cmpn(1)>0;){for(var S=0,_=1;(q.words[0]&_)===0&&S<26;++S,_<<=1);if(S>0)for(q.iushrn(S);S-- >0;)O.isOdd()&&O.iadd(k),O.iushrn(1);for(var W=0,j=1;(P.words[0]&j)===0&&W<26;++W,j<<=1);if(W>0)for(P.iushrn(W);W-- >0;)w.isOdd()&&w.iadd(k),w.iushrn(1);q.cmp(P)>=0?(q.isub(P),O.isub(w)):(P.isub(q),w.isub(O))}var b;return q.cmpn(1)===0?b=O:b=w,b.cmpn(0)<0&&b.iadd(B),b},Y.prototype.gcd=function(B){if(this.isZero())return B.abs();if(B.isZero())return this.abs();var q=this.clone(),P=B.clone();q.negative=0,P.negative=0;for(var O=0;q.isEven()&&P.isEven();O++)q.iushrn(1),P.iushrn(1);do{for(;q.isEven();)q.iushrn(1);for(;P.isEven();)P.iushrn(1);var w=q.cmp(P);if(w<0){var k=q;q=P,P=k}else if(w===0||P.cmpn(1)===0)break;q.isub(P)}while(!0);return P.iushln(O)},Y.prototype.invm=function(B){return this.egcd(B).a.umod(B)},Y.prototype.isEven=function(){return(this.words[0]&1)===0},Y.prototype.isOdd=function(){return(this.words[0]&1)===1},Y.prototype.andln=function(B){return this.words[0]&B},Y.prototype.bincn=function(B){C(typeof B=="number");var q=B%26,P=(B-q)/26,O=1<>>26,S&=67108863,this.words[k]=S}return w!==0&&(this.words[k]=w,this.length++),this},Y.prototype.isZero=function(){return this.length===1&&this.words[0]===0},Y.prototype.cmpn=function(B){var q=B<0;if(this.negative!==0&&!q)return-1;if(this.negative===0&&q)return 1;this.strip();var P;if(this.length>1)P=1;else{q&&(B=-B),C(B<=67108863,"Number is too big");var O=this.words[0]|0;P=O===B?0:OB.length)return 1;if(this.length=0;P--){var O=this.words[P]|0,w=B.words[P]|0;if(O!==w){Ow&&(q=1);break}}return q},Y.prototype.gtn=function(B){return this.cmpn(B)===1},Y.prototype.gt=function(B){return this.cmp(B)===1},Y.prototype.gten=function(B){return this.cmpn(B)>=0},Y.prototype.gte=function(B){return this.cmp(B)>=0},Y.prototype.ltn=function(B){return this.cmpn(B)===-1},Y.prototype.lt=function(B){return this.cmp(B)===-1},Y.prototype.lten=function(B){return this.cmpn(B)<=0},Y.prototype.lte=function(B){return this.cmp(B)<=0},Y.prototype.eqn=function(B){return this.cmpn(B)===0},Y.prototype.eq=function(B){return this.cmp(B)===0},Y.red=function(B){return new d(B)},Y.prototype.toRed=function(B){return C(!this.red,"Already a number in reduction context"),C(this.negative===0,"red works only with positives"),B.convertTo(this)._forceRed(B)},Y.prototype.fromRed=function(){return C(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},Y.prototype._forceRed=function(B){return this.red=B,this},Y.prototype.forceRed=function(B){return C(!this.red,"Already a number in reduction context"),this._forceRed(B)},Y.prototype.redAdd=function(B){return C(this.red,"redAdd works only with red numbers"),this.red.add(this,B)},Y.prototype.redIAdd=function(B){return C(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,B)},Y.prototype.redSub=function(B){return C(this.red,"redSub works only with red numbers"),this.red.sub(this,B)},Y.prototype.redISub=function(B){return C(this.red,"redISub works only with red numbers"),this.red.isub(this,B)},Y.prototype.redShl=function(B){return C(this.red,"redShl works only with red numbers"),this.red.shl(this,B)},Y.prototype.redMul=function(B){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.mul(this,B)},Y.prototype.redIMul=function(B){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.imul(this,B)},Y.prototype.redSqr=function(){return C(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},Y.prototype.redISqr=function(){return C(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},Y.prototype.redSqrt=function(){return C(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},Y.prototype.redInvm=function(){return C(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},Y.prototype.redNeg=function(){return C(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},Y.prototype.redPow=function(B){return C(this.red&&!B.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,B)};var T={k256:null,p224:null,p192:null,p25519:null};function h(B,q){this.name=B,this.p=new Y(q,16),this.n=this.p.bitLength(),this.k=new Y(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}h.prototype._tmp=function(){var B=new Y(null);return B.words=new Array(Math.ceil(this.n/13)),B},h.prototype.ireduce=function(B){var q=B,P;do this.split(q,this.tmp),q=this.imulK(q),q=q.iadd(this.tmp),P=q.bitLength();while(P>this.n);var O=P0?q.isub(this.p):q.strip!==void 0?q.strip():q._strip(),q},h.prototype.split=function(B,q){B.iushrn(this.n,0,q)},h.prototype.imulK=function(B){return B.imul(this.k)};function y(){h.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}U(y,h),y.prototype.split=function(B,q){for(var P=4194303,O=Math.min(B.length,9),w=0;w>>22,k=S}k>>>=22,B.words[w-10]=k,k===0&&B.length>10?B.length-=10:B.length-=9},y.prototype.imulK=function(B){B.words[B.length]=0,B.words[B.length+1]=0,B.length+=2;for(var q=0,P=0;P>>=26,B.words[P]=w,q=O}return q!==0&&(B.words[B.length++]=q),B},Y._prime=function(B){if(T[B])return T[B];var q;if(B==="k256")q=new y;else if(B==="p224")q=new g;else if(B==="p192")q=new f;else if(B==="p25519")q=new u;else throw new Error("Unknown prime "+B);return T[B]=q,q};function d(B){if(typeof B=="string"){var q=Y._prime(B);this.m=q.p,this.prime=q}else C(B.gtn(1),"modulus must be greater than 1"),this.m=B,this.prime=null}d.prototype._verify1=function(B){C(B.negative===0,"red works only with positives"),C(B.red,"red works only with red numbers")},d.prototype._verify2=function(B,q){C((B.negative|q.negative)===0,"red works only with positives"),C(B.red&&B.red===q.red,"red works only with red numbers")},d.prototype.imod=function(B){return this.prime?this.prime.ireduce(B)._forceRed(this):B.umod(this.m)._forceRed(this)},d.prototype.neg=function(B){return B.isZero()?B.clone():this.m.sub(B)._forceRed(this)},d.prototype.add=function(B,q){this._verify2(B,q);var P=B.add(q);return P.cmp(this.m)>=0&&P.isub(this.m),P._forceRed(this)},d.prototype.iadd=function(B,q){this._verify2(B,q);var P=B.iadd(q);return P.cmp(this.m)>=0&&P.isub(this.m),P},d.prototype.sub=function(B,q){this._verify2(B,q);var P=B.sub(q);return P.cmpn(0)<0&&P.iadd(this.m),P._forceRed(this)},d.prototype.isub=function(B,q){this._verify2(B,q);var P=B.isub(q);return P.cmpn(0)<0&&P.iadd(this.m),P},d.prototype.shl=function(B,q){return this._verify1(B),this.imod(B.ushln(q))},d.prototype.imul=function(B,q){return this._verify2(B,q),this.imod(B.imul(q))},d.prototype.mul=function(B,q){return this._verify2(B,q),this.imod(B.mul(q))},d.prototype.isqr=function(B){return this.imul(B,B.clone())},d.prototype.sqr=function(B){return this.mul(B,B)},d.prototype.sqrt=function(B){if(B.isZero())return B.clone();var q=this.m.andln(3);if(C(q%2===1),q===3){var P=this.m.add(new Y(1)).iushrn(2);return this.pow(B,P)}for(var O=this.m.subn(1),w=0;!O.isZero()&&O.andln(1)===0;)w++,O.iushrn(1);C(!O.isZero());var k=new Y(1).toRed(this),S=k.redNeg(),_=this.m.subn(1).iushrn(1),W=this.m.bitLength();for(W=new Y(2*W*W).toRed(this);this.pow(W,_).cmp(S)!==0;)W.redIAdd(S);for(var j=this.pow(W,O),b=this.pow(B,O.addn(1).iushrn(1)),p=this.pow(B,O),s=w;p.cmp(k)!==0;){for(var r=p,A1=0;r.cmp(k)!==0;A1++)r=r.redSqr();C(A1=0;w--){for(var j=q.words[w],b=W-1;b>=0;b--){var p=j>>b&1;if(k!==O[0]&&(k=this.sqr(k)),p===0&&S===0){_=0;continue}S<<=1,S|=p,_++,!(_!==P&&(w!==0||b!==0))&&(k=this.mul(k,O[S]),_=0,S=0)}W=26}return k},d.prototype.convertTo=function(B){var q=B.umod(this.m);return q===B?q.clone():q},d.prototype.convertFrom=function(B){var q=B.clone();return q.red=null,q},Y.mont=function(B){return new n(B)};function n(B){d.call(this,B),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new Y(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}U(n,d),n.prototype.convertTo=function(B){return this.imod(B.ushln(this.shift))},n.prototype.convertFrom=function(B){var q=this.imod(B.mul(this.rinv));return q.red=null,q},n.prototype.imul=function(B,q){if(B.isZero()||q.isZero())return B.words[0]=0,B.length=1,B;var P=B.imul(q),O=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=P.isub(O).iushrn(this.shift),k=w;return w.cmp(this.m)>=0?k=w.isub(this.m):w.cmpn(0)<0&&(k=w.iadd(this.m)),k._forceRed(this)},n.prototype.mul=function(B,q){if(B.isZero()||q.isZero())return new Y(0)._forceRed(this);var P=B.mul(q),O=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=P.isub(O).iushrn(this.shift),k=w;return w.cmp(this.m)>=0?k=w.isub(this.m):w.cmpn(0)<0&&(k=w.iadd(this.m)),k._forceRed(this)},n.prototype.invm=function(B){var q=this.imod(B._invmp(this.m).mul(this.r2));return q._forceRed(this)}})(typeof Q>"u"||Q,A)}),F91=l1(()=>{}),cN=l1((A,Q)=>{var J;Q.exports=function(U){return J||(J=new K(null)),J.generate(U)};function K(U){this.rand=U}if(Q.exports.Rand=K,K.prototype.generate=function(U){return this._rand(U)},K.prototype._rand=function(U){if(this.rand.getBytes)return this.rand.getBytes(U);for(var Y=new Uint8Array(U),Z=0;Z{var J=L91(),K=cN();function C(U){this.rand=U||new K.Rand}Q.exports=C,C.create=function(U){return new C(U)},C.prototype._randbelow=function(U){var Y=U.bitLength(),Z=Math.ceil(Y/8);do var X=new J(this.rand.generate(Z));while(X.cmp(U)>=0);return X},C.prototype._randrange=function(U,Y){var Z=Y.sub(U);return U.add(this._randbelow(Z))},C.prototype.test=function(U,Y,Z){var X=U.bitLength(),E=J.mont(U),H=new J(1).toRed(E);Y||(Y=Math.max(1,X/48|0));for(var $=U.subn(1),I=0;!$.testn(I);I++);for(var N=U.shrn(I),F=$.toRed(E),V=!0;Y>0;Y--){var D=this._randrange(new J(2),$);Z&&Z(D);var L=D.toRed(E).redPow(N);if(!(L.cmp(H)===0||L.cmp(F)===0)){for(var R=1;R0;Y--){var F=this._randrange(new J(2),H),V=U.gcd(F);if(V.cmpn(1)!==0)return V;var D=F.toRed(X).redPow(I);if(!(D.cmp(E)===0||D.cmp(N)===0)){for(var L=1;L<$;L++){if(D=D.redSqr(),D.cmp(E)===0)return D.fromRed().subn(1).gcd(U);if(D.cmp(N)===0)break}if(L===$)return D=D.redSqr(),D.fromRed().subn(1).gcd(U)}}return!1}}),Ay=l1((A,Q)=>{var J=VK();Q.exports=y,y.simpleSieve=T,y.fermatTest=h;var K=tx(),C=new K(24),U=ex(),Y=new U,Z=new K(1),X=new K(2),E=new K(5),H=new K(16),$=new K(8),I=new K(10),N=new K(3),F=new K(7),V=new K(11),D=new K(4),L=new K(12),R=null;function M(){if(R!==null)return R;var g=1048576,f=[];f[0]=2;for(var u=1,d=3;dg;)u.ishrn(1);if(u.isEven()&&u.iadd(Z),u.testn(1)||u.iadd(X),f.cmp(X)){if(!f.cmp(E))for(;u.mod(I).cmp(N);)u.iadd(D)}else for(;u.mod(C).cmp(V);)u.iadd(D);if(d=u.shrn(1),T(d)&&T(u)&&h(d)&&h(u)&&Y.test(d)&&Y.test(u))return u}}}),R91=l1((A,Q)=>{Q.exports={modp1:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"},modp2:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"},modp5:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"},modp14:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"},modp15:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"},modp16:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"},modp17:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"},modp18:{gen:"02",prime:"ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"}}}),z91=l1((A,Q)=>{var J=tx(),K=ex(),C=new K,U=new J(24),Y=new J(11),Z=new J(10),X=new J(3),E=new J(7),H=Ay(),$=VK();Q.exports=D;function I(R,M){return M=M||"utf8",Buffer.isBuffer(R)||(R=new Buffer(R,M)),this._pub=new J(R),this}function N(R,M){return M=M||"utf8",Buffer.isBuffer(R)||(R=new Buffer(R,M)),this._priv=new J(R),this}var F={};function V(R,M){var T=M.toString("hex"),h=[T,R.toString(16)].join("_");if(h in F)return F[h];var y=0;if(R.isEven()||!H.simpleSieve||!H.fermatTest(R)||!C.test(R))return y+=1,T==="02"||T==="05"?y+=8:y+=4,F[h]=y,y;C.test(R.shrn(1))||(y+=2);var g;switch(T){case"02":R.mod(U).cmp(Y)&&(y+=8);break;case"05":g=R.mod(Z),g.cmp(X)&&g.cmp(E)&&(y+=8);break;default:y+=4}return F[h]=y,y}function D(R,M,T){this.setGenerator(M),this.__prime=new J(R),this._prime=J.mont(this.__prime),this._primeLen=R.length,this._pub=void 0,this._priv=void 0,this._primeCode=void 0,T?(this.setPublicKey=I,this.setPrivateKey=N):this._primeCode=8}Object.defineProperty(D.prototype,"verifyError",{enumerable:!0,get:function(){return typeof this._primeCode!="number"&&(this._primeCode=V(this.__prime,this.__gen)),this._primeCode}}),D.prototype.generateKeys=function(){return this._priv||(this._priv=new J($(this._primeLen))),this._pub=this._gen.toRed(this._prime).redPow(this._priv).fromRed(),this.getPublicKey()},D.prototype.computeSecret=function(R){R=new J(R),R=R.toRed(this._prime);var M=R.redPow(this._priv).fromRed(),T=new Buffer(M.toArray()),h=this.getPrime();if(T.length{var Q=Ay(),J=R91(),K=z91();function C(Z){var X=new Buffer(J[Z].prime,"hex"),E=new Buffer(J[Z].gen,"hex");return new K(X,E)}var U={binary:!0,hex:!0,base64:!0};function Y(Z,X,E,H){return Buffer.isBuffer(X)||U[X]===void 0?Y(Z,"binary",X,E):(X=X||"binary",H=H||"binary",E=E||new Buffer([2]),Buffer.isBuffer(E)||(E=new Buffer(E,H)),typeof Z=="number"?new K(Q(Z,E),E,!0):(Buffer.isBuffer(Z)||(Z=new Buffer(Z,X)),new K(Z,E,!0)))}A.DiffieHellmanGroup=A.createDiffieHellmanGroup=A.getDiffieHellman=C,A.createDiffieHellman=A.DiffieHellman=Y}),Qy=l1((A,Q)=>{Q.exports=YQ().EventEmitter}),V91=l1((A,Q)=>{function J(F,V){var D=Object.keys(F);if(Object.getOwnPropertySymbols){var L=Object.getOwnPropertySymbols(F);V&&(L=L.filter(function(R){return Object.getOwnPropertyDescriptor(F,R).enumerable})),D.push.apply(D,L)}return D}function K(F){for(var V=1;V0?this.tail.next=D:this.head=D,this.tail=D,++this.length}},{key:"unshift",value:function(V){var D={data:V,next:this.head};this.length===0&&(this.tail=D),this.head=D,++this.length}},{key:"shift",value:function(){if(this.length!==0){var V=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,V}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(V){if(this.length===0)return"";for(var D=this.head,L=""+D.data;D=D.next;)L+=V+D.data;return L}},{key:"concat",value:function(V){if(this.length===0)return E.alloc(0);for(var D=E.allocUnsafe(V>>>0),L=this.head,R=0;L;)N(L.data,D,R),R+=L.data.length,L=L.next;return D}},{key:"consume",value:function(V,D){var L;return VM.length?M.length:V;if(T===M.length?R+=M:R+=M.slice(0,V),V-=T,V===0){T===M.length?(++L,D.next?this.head=D.next:this.head=this.tail=null):(this.head=D,D.data=M.slice(T));break}++L}return this.length-=L,R}},{key:"_getBuffer",value:function(V){var D=E.allocUnsafe(V),L=this.head,R=1;for(L.data.copy(D),V-=L.data.length;L=L.next;){var M=L.data,T=V>M.length?M.length:V;if(M.copy(D,D.length-V,0,T),V-=T,V===0){T===M.length?(++R,L.next?this.head=L.next:this.head=this.tail=null):(this.head=L,L.data=M.slice(T));break}++R}return this.length-=R,D}},{key:I,value:function(V,D){return $(this,K({},D,{depth:0,customInspect:!1}))}}]),F}()}),Jy=l1((A,Q)=>{function J(X,E){var H=this,$=this._readableState&&this._readableState.destroyed,I=this._writableState&&this._writableState.destroyed;return $||I?(E?E(X):X&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(Y,this,X)):process.nextTick(Y,this,X)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(X||null,function(N){!E&&N?H._writableState?H._writableState.errorEmitted?process.nextTick(C,H):(H._writableState.errorEmitted=!0,process.nextTick(K,H,N)):process.nextTick(K,H,N):E?(process.nextTick(C,H),E(N)):process.nextTick(C,H)}),this)}function K(X,E){Y(X,E),C(X)}function C(X){X._writableState&&!X._writableState.emitClose||X._readableState&&!X._readableState.emitClose||X.emit("close")}function U(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function Y(X,E){X.emit("error",E)}function Z(X,E){var{_readableState:H,_writableState:$}=X;H&&H.autoDestroy||$&&$.autoDestroy?X.destroy(E):X.emit("error",E)}Q.exports={destroy:J,undestroy:U,errorOrDestroy:Z}}),_K=l1((A,Q)=>{function J(E,H){E.prototype=Object.create(H.prototype),E.prototype.constructor=E,E.__proto__=H}var K={};function C(E,H,$){$||($=Error);function I(F,V,D){return typeof H=="string"?H:H(F,V,D)}var N=function(F){J(V,F);function V(D,L,R){return F.call(this,I(D,L,R))||this}return V}($);N.prototype.name=$.name,N.prototype.code=E,K[E]=N}function U(E,H){if(Array.isArray(E)){var $=E.length;return E=E.map(function(I){return String(I)}),$>2?"one of ".concat(H," ").concat(E.slice(0,$-1).join(", "),", or ")+E[$-1]:$===2?"one of ".concat(H," ").concat(E[0]," or ").concat(E[1]):"of ".concat(H," ").concat(E[0])}else return"of ".concat(H," ").concat(String(E))}function Y(E,H,$){return E.substr(!$||$<0?0:+$,H.length)===H}function Z(E,H,$){return($===void 0||$>E.length)&&($=E.length),E.substring($-H.length,$)===H}function X(E,H,$){return typeof $!="number"&&($=0),$+H.length>E.length?!1:E.indexOf(H,$)!==-1}C("ERR_INVALID_OPT_VALUE",function(E,H){return'The value "'+H+'" is invalid for option "'+E+'"'},TypeError),C("ERR_INVALID_ARG_TYPE",function(E,H,$){var I;typeof H=="string"&&Y(H,"not ")?(I="must not be",H=H.replace(/^not /,"")):I="must be";var N;if(Z(E," argument"))N="The ".concat(E," ").concat(I," ").concat(U(H,"type"));else{var F=X(E,".")?"property":"argument";N='The "'.concat(E,'" ').concat(F," ").concat(I," ").concat(U(H,"type"))}return N+=". Received type ".concat(typeof $),N},TypeError),C("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),C("ERR_METHOD_NOT_IMPLEMENTED",function(E){return"The "+E+" method is not implemented"}),C("ERR_STREAM_PREMATURE_CLOSE","Premature close"),C("ERR_STREAM_DESTROYED",function(E){return"Cannot call "+E+" after a stream was destroyed"}),C("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),C("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),C("ERR_STREAM_WRITE_AFTER_END","write after end"),C("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),C("ERR_UNKNOWN_ENCODING",function(E){return"Unknown encoding: "+E},TypeError),C("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),Q.exports.codes=K}),Ky=l1((A,Q)=>{var J=_K().codes.ERR_INVALID_OPT_VALUE;function K(U,Y,Z){return U.highWaterMark!=null?U.highWaterMark:Y?U[Z]:null}function C(U,Y,Z,X){var E=K(Y,X,Z);if(E!=null){if(!(isFinite(E)&&Math.floor(E)===E)||E<0){var H=X?Z:"highWaterMark";throw new J(H,E)}return Math.floor(E)}return U.objectMode?16:16384}Q.exports={getHighWaterMark:C}}),Cy=l1((A,Q)=>{Q.exports=d;function J(e){var t=this;this.next=null,this.entry=null,this.finish=function(){Q1(t,e)}}var K;d.WritableState=f;var C={deprecate:Vx()},U=Qy(),Y=A6().Buffer,Z=global.Uint8Array||function(){};function X(e){return Y.from(e)}function E(e){return Y.isBuffer(e)||e instanceof Z}var H=Jy(),$=Ky(),I=$.getHighWaterMark,N=_K().codes,F=N.ERR_INVALID_ARG_TYPE,V=N.ERR_METHOD_NOT_IMPLEMENTED,D=N.ERR_MULTIPLE_CALLBACK,L=N.ERR_STREAM_CANNOT_PIPE,R=N.ERR_STREAM_DESTROYED,M=N.ERR_STREAM_NULL_VALUES,T=N.ERR_STREAM_WRITE_AFTER_END,h=N.ERR_UNKNOWN_ENCODING,y=H.errorOrDestroy;MA()(d,U);function g(){}function f(e,t,U1){K=K||zK(),e=e||{},typeof U1!="boolean"&&(U1=t instanceof K),this.objectMode=!!e.objectMode,U1&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=I(this,e,"writableHighWaterMark",U1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var O1=e.decodeStrings===!1;this.decodeStrings=!O1,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(E1){S(t,E1)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=e.emitClose!==!1,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new J(this)}f.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(f.prototype,"buffer",{get:C.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var u;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(u=Function.prototype[Symbol.hasInstance],Object.defineProperty(d,Symbol.hasInstance,{value:function(e){return u.call(this,e)?!0:this!==d?!1:e&&e._writableState instanceof f}})):u=function(e){return e instanceof this};function d(e){K=K||zK();var t=this instanceof K;if(!t&&!u.call(d,this))return new d(e);this._writableState=new f(e,this,t),this.writable=!0,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),U.call(this)}d.prototype.pipe=function(){y(this,new L)};function n(e,t){var U1=new T;y(e,U1),process.nextTick(t,U1)}function B(e,t,U1,O1){var E1;return U1===null?E1=new M:typeof U1!="string"&&!t.objectMode&&(E1=new F("chunk",["string","Buffer"],U1)),E1?(y(e,E1),process.nextTick(O1,E1),!1):!0}d.prototype.write=function(e,t,U1){var O1=this._writableState,E1=!1,Y1=!O1.objectMode&&E(e);return Y1&&!Y.isBuffer(e)&&(e=X(e)),typeof t=="function"&&(U1=t,t=null),Y1?t="buffer":t||(t=O1.defaultEncoding),typeof U1!="function"&&(U1=g),O1.ending?n(this,U1):(Y1||B(this,O1,e,U1))&&(O1.pendingcb++,E1=P(this,O1,Y1,e,t,U1)),E1},d.prototype.cork=function(){this._writableState.corked++},d.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&j(this,e))},d.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new h(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(d.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function q(e,t,U1){return!e.objectMode&&e.decodeStrings!==!1&&typeof t=="string"&&(t=Y.from(t,U1)),t}Object.defineProperty(d.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function P(e,t,U1,O1,E1,Y1){if(!U1){var i=q(t,O1,E1);O1!==i&&(U1=!0,E1="buffer",O1=i)}var c=t.objectMode?1:O1.length;t.length+=c;var o=t.length{var J=Object.keys||function($){var I=[];for(var N in $)I.push(N);return I};Q.exports=X;var K=Yy(),C=Cy();MA()(X,K);for(U=J(C.prototype),Z=0;Z{var J=_K().codes.ERR_STREAM_PREMATURE_CLOSE;function K(Z){var X=!1;return function(){if(!X){X=!0;for(var E=arguments.length,H=new Array(E),$=0;${var J;function K(M,T,h){return T in M?Object.defineProperty(M,T,{value:h,enumerable:!0,configurable:!0,writable:!0}):M[T]=h,M}var C=dN(),U=Symbol("lastResolve"),Y=Symbol("lastReject"),Z=Symbol("error"),X=Symbol("ended"),E=Symbol("lastPromise"),H=Symbol("handlePromise"),$=Symbol("stream");function I(M,T){return{value:M,done:T}}function N(M){var T=M[U];if(T!==null){var h=M[$].read();h!==null&&(M[E]=null,M[U]=null,M[Y]=null,T(I(h,!1)))}}function F(M){process.nextTick(N,M)}function V(M,T){return function(h,y){M.then(function(){if(T[X]){h(I(void 0,!0));return}T[H](h,y)},y)}}var D=Object.getPrototypeOf(function(){}),L=Object.setPrototypeOf((J={get stream(){return this[$]},next:function(){var M=this,T=this[Z];if(T!==null)return Promise.reject(T);if(this[X])return Promise.resolve(I(void 0,!0));if(this[$].destroyed)return new Promise(function(f,u){process.nextTick(function(){M[Z]?u(M[Z]):f(I(void 0,!0))})});var h=this[E],y;if(h)y=new Promise(V(h,this));else{var g=this[$].read();if(g!==null)return Promise.resolve(I(g,!1));y=new Promise(this[H])}return this[E]=y,y}},K(J,Symbol.asyncIterator,function(){return this}),K(J,"return",function(){var M=this;return new Promise(function(T,h){M[$].destroy(null,function(y){if(y){h(y);return}T(I(void 0,!0))})})}),J),D),R=function(M){var T,h=Object.create(L,(T={},K(T,$,{value:M,writable:!0}),K(T,U,{value:null,writable:!0}),K(T,Y,{value:null,writable:!0}),K(T,Z,{value:null,writable:!0}),K(T,X,{value:M._readableState.endEmitted,writable:!0}),K(T,H,{value:function(y,g){var f=h[$].read();f?(h[E]=null,h[U]=null,h[Y]=null,y(I(f,!1))):(h[U]=y,h[Y]=g)},writable:!0}),T));return h[E]=null,C(M,function(y){if(y&&y.code!=="ERR_STREAM_PREMATURE_CLOSE"){var g=h[Y];g!==null&&(h[E]=null,h[U]=null,h[Y]=null,g(y)),h[Z]=y;return}var f=h[U];f!==null&&(h[E]=null,h[U]=null,h[Y]=null,f(I(void 0,!0))),h[X]=!0}),M.on("readable",F.bind(null,h)),h};Q.exports=R}),w91=l1((A,Q)=>{Q.exports=function(){throw new Error("Readable.from is not available in the browser")}}),Yy=l1((A,Q)=>{Q.exports=B;var J;B.ReadableState=n;var K=YQ().EventEmitter,C=function(i,c){return i.listeners(c).length},U=Qy(),Y=A6().Buffer,Z=global.Uint8Array||function(){};function X(i){return Y.from(i)}function E(i){return Y.isBuffer(i)||i instanceof Z}var H=oE(),$;H&&H.debuglog?$=H.debuglog("stream"):$=function(){};var I=V91(),N=Jy(),F=Ky(),V=F.getHighWaterMark,D=_K().codes,L=D.ERR_INVALID_ARG_TYPE,R=D.ERR_STREAM_PUSH_AFTER_EOF,M=D.ERR_METHOD_NOT_IMPLEMENTED,T=D.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,h,y,g;MA()(B,U);var f=N.errorOrDestroy,u=["error","close","destroy","pause","resume"];function d(i,c,o){if(typeof i.prependListener=="function")return i.prependListener(c,o);!i._events||!i._events[c]?i.on(c,o):Array.isArray(i._events[c])?i._events[c].unshift(o):i._events[c]=[o,i._events[c]]}function n(i,c,o){J=J||zK(),i=i||{},typeof o!="boolean"&&(o=c instanceof J),this.objectMode=!!i.objectMode,o&&(this.objectMode=this.objectMode||!!i.readableObjectMode),this.highWaterMark=V(this,i,"readableHighWaterMark",o),this.buffer=new I,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=i.emitClose!==!1,this.autoDestroy=!!i.autoDestroy,this.destroyed=!1,this.defaultEncoding=i.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,i.encoding&&(h||(h=(lE(),_9(IU)).StringDecoder),this.decoder=new h(i.encoding),this.encoding=i.encoding)}function B(i){if(J=J||zK(),!(this instanceof B))return new B(i);var c=this instanceof J;this._readableState=new n(i,this,c),this.readable=!0,i&&(typeof i.read=="function"&&(this._read=i.read),typeof i.destroy=="function"&&(this._destroy=i.destroy)),U.call(this)}Object.defineProperty(B.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(i){!this._readableState||(this._readableState.destroyed=i)}}),B.prototype.destroy=N.destroy,B.prototype._undestroy=N.undestroy,B.prototype._destroy=function(i,c){c(i)},B.prototype.push=function(i,c){var o=this._readableState,C1;return o.objectMode?C1=!0:typeof i=="string"&&(c=c||o.defaultEncoding,c!==o.encoding&&(i=Y.from(i,c),c=""),C1=!0),q(this,i,c,!1,C1)},B.prototype.unshift=function(i){return q(this,i,null,!0,!1)};function q(i,c,o,C1,q1){$("readableAddChunk",c);var Z1=i._readableState;if(c===null)Z1.reading=!1,_(i,Z1);else{var j1;if(q1||(j1=O(Z1,c)),j1)f(i,j1);else if(Z1.objectMode||c&&c.length>0)if(typeof c!="string"&&!Z1.objectMode&&Object.getPrototypeOf(c)!==Y.prototype&&(c=X(c)),C1)Z1.endEmitted?f(i,new T):P(i,Z1,c,!0);else if(Z1.ended)f(i,new R);else{if(Z1.destroyed)return!1;Z1.reading=!1,Z1.decoder&&!o?(c=Z1.decoder.write(c),Z1.objectMode||c.length!==0?P(i,Z1,c,!1):b(i,Z1)):P(i,Z1,c,!1)}else C1||(Z1.reading=!1,b(i,Z1))}return!Z1.ended&&(Z1.length=w?i=w:(i--,i|=i>>>1,i|=i>>>2,i|=i>>>4,i|=i>>>8,i|=i>>>16,i++),i}function S(i,c){return i<=0||c.length===0&&c.ended?0:c.objectMode?1:i!==i?c.flowing&&c.length?c.buffer.head.data.length:c.length:(i>c.highWaterMark&&(c.highWaterMark=k(i)),i<=c.length?i:c.ended?c.length:(c.needReadable=!0,0))}B.prototype.read=function(i){$("read",i),i=parseInt(i,10);var c=this._readableState,o=i;if(i!==0&&(c.emittedReadable=!1),i===0&&c.needReadable&&((c.highWaterMark!==0?c.length>=c.highWaterMark:c.length>0)||c.ended))return $("read: emitReadable",c.length,c.ended),c.length===0&&c.ended?O1(this):W(this),null;if(i=S(i,c),i===0&&c.ended)return c.length===0&&O1(this),null;var C1=c.needReadable;$("need readable",C1),(c.length===0||c.length-i0?q1=U1(i,c):q1=null,q1===null?(c.needReadable=c.length<=c.highWaterMark,i=0):(c.length-=i,c.awaitDrain=0),c.length===0&&(c.ended||(c.needReadable=!0),o!==i&&c.ended&&O1(this)),q1!==null&&this.emit("data",q1),q1};function _(i,c){if($("onEofChunk"),!c.ended){if(c.decoder){var o=c.decoder.end();o&&o.length&&(c.buffer.push(o),c.length+=c.objectMode?1:o.length)}c.ended=!0,c.sync?W(i):(c.needReadable=!1,c.emittedReadable||(c.emittedReadable=!0,j(i)))}}function W(i){var c=i._readableState;$("emitReadable",c.needReadable,c.emittedReadable),c.needReadable=!1,c.emittedReadable||($("emitReadable",c.flowing),c.emittedReadable=!0,process.nextTick(j,i))}function j(i){var c=i._readableState;$("emitReadable_",c.destroyed,c.length,c.ended),!c.destroyed&&(c.length||c.ended)&&(i.emit("readable"),c.emittedReadable=!1),c.needReadable=!c.flowing&&!c.ended&&c.length<=c.highWaterMark,t(i)}function b(i,c){c.readingMore||(c.readingMore=!0,process.nextTick(p,i,c))}function p(i,c){for(;!c.reading&&!c.ended&&(c.length1&&Y1(C1.pipes,i)!==-1)&&!k1&&($("false write response, pause",C1.awaitDrain),C1.awaitDrain++),o.pause())}function w1(m){$("onerror",m),x(),i.removeListener("error",w1),C(i,"error")===0&&f(i,m)}d(i,"error",w1);function G(){i.removeListener("finish",z),x()}i.once("close",G);function z(){$("onfinish"),i.removeListener("close",G),x()}i.once("finish",z);function x(){$("unpipe"),o.unpipe(i)}return i.emit("pipe",o),C1.flowing||($("pipe resume"),o.resume()),i};function s(i){return function(){var c=i._readableState;$("pipeOnDrain",c.awaitDrain),c.awaitDrain&&c.awaitDrain--,c.awaitDrain===0&&C(i,"data")&&(c.flowing=!0,t(i))}}B.prototype.unpipe=function(i){var c=this._readableState,o={hasUnpiped:!1};if(c.pipesCount===0)return this;if(c.pipesCount===1)return i&&i!==c.pipes?this:(i||(i=c.pipes),c.pipes=null,c.pipesCount=0,c.flowing=!1,i&&i.emit("unpipe",this,o),this);if(!i){var{pipes:C1,pipesCount:q1}=c;c.pipes=null,c.pipesCount=0,c.flowing=!1;for(var Z1=0;Z10,C1.flowing!==!1&&this.resume()):i==="readable"&&!C1.endEmitted&&!C1.readableListening&&(C1.readableListening=C1.needReadable=!0,C1.flowing=!1,C1.emittedReadable=!1,$("on readable",C1.length,C1.reading),C1.length?W(this):C1.reading||process.nextTick(A1,this)),o},B.prototype.addListener=B.prototype.on,B.prototype.removeListener=function(i,c){var o=U.prototype.removeListener.call(this,i,c);return i==="readable"&&process.nextTick(r,this),o},B.prototype.removeAllListeners=function(i){var c=U.prototype.removeAllListeners.apply(this,arguments);return(i==="readable"||i===void 0)&&process.nextTick(r,this),c};function r(i){var c=i._readableState;c.readableListening=i.listenerCount("readable")>0,c.resumeScheduled&&!c.paused?c.flowing=!0:i.listenerCount("data")>0&&i.resume()}function A1(i){$("readable nexttick read 0"),i.read(0)}B.prototype.resume=function(){var i=this._readableState;return i.flowing||($("resume"),i.flowing=!i.readableListening,Q1(this,i)),i.paused=!1,this};function Q1(i,c){c.resumeScheduled||(c.resumeScheduled=!0,process.nextTick(e,i,c))}function e(i,c){$("resume",c.reading),c.reading||i.read(0),c.resumeScheduled=!1,i.emit("resume"),t(i),c.flowing&&!c.reading&&i.read(0)}B.prototype.pause=function(){return $("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&($("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function t(i){var c=i._readableState;for($("flow",c.flowing);c.flowing&&i.read()!==null;);}B.prototype.wrap=function(i){var c=this,o=this._readableState,C1=!1;i.on("end",function(){if($("wrapped end"),o.decoder&&!o.ended){var j1=o.decoder.end();j1&&j1.length&&c.push(j1)}c.push(null)}),i.on("data",function(j1){if($("wrapped data"),o.decoder&&(j1=o.decoder.write(j1)),!(o.objectMode&&j1==null)&&!(!o.objectMode&&(!j1||!j1.length))){var H1=c.push(j1);H1||(C1=!0,i.pause())}});for(var q1 in i)this[q1]===void 0&&typeof i[q1]=="function"&&(this[q1]=function(j1){return function(){return i[j1].apply(i,arguments)}}(q1));for(var Z1=0;Z1=c.length?(c.decoder?o=c.buffer.join(""):c.buffer.length===1?o=c.buffer.first():o=c.buffer.concat(c.length),c.buffer.clear()):o=c.buffer.consume(i,c.decoder),o}function O1(i){var c=i._readableState;$("endReadable",c.endEmitted),c.endEmitted||(c.ended=!0,process.nextTick(E1,c,i))}function E1(i,c){if($("endReadableNT",i.endEmitted,i.length),!i.endEmitted&&i.length===0&&(i.endEmitted=!0,c.readable=!1,c.emit("end"),i.autoDestroy)){var o=c._writableState;(!o||o.autoDestroy&&o.finished)&&c.destroy()}}typeof Symbol=="function"&&(B.from=function(i,c){return g===void 0&&(g=w91()),g(B,i,c)});function Y1(i,c){for(var o=0,C1=i.length;o{Q.exports=E;var J=_K().codes,K=J.ERR_METHOD_NOT_IMPLEMENTED,C=J.ERR_MULTIPLE_CALLBACK,U=J.ERR_TRANSFORM_ALREADY_TRANSFORMING,Y=J.ERR_TRANSFORM_WITH_LENGTH_0,Z=zK();MA()(E,Z);function X(I,N){var F=this._transformState;F.transforming=!1;var V=F.writecb;if(V===null)return this.emit("error",new C);F.writechunk=null,F.writecb=null,N!=null&&this.push(N),V(I);var D=this._readableState;D.reading=!1,(D.needReadable||D.length{Q.exports=K;var J=Uy();MA()(K,J);function K(C){if(!(this instanceof K))return new K(C);J.call(this,C)}K.prototype._transform=function(C,U,Y){Y(null,C)}}),_91=l1((A,Q)=>{var J;function K(F){var V=!1;return function(){V||(V=!0,F.apply(void 0,arguments))}}var C=_K().codes,U=C.ERR_MISSING_ARGS,Y=C.ERR_STREAM_DESTROYED;function Z(F){if(F)throw F}function X(F){return F.setHeader&&typeof F.abort=="function"}function E(F,V,D,L){L=K(L);var R=!1;F.on("close",function(){R=!0}),J===void 0&&(J=dN()),J(F,{readable:V,writable:D},function(T){if(T)return L(T);R=!0,L()});var M=!1;return function(T){if(!R&&!M){if(M=!0,X(F))return F.abort();if(typeof F.destroy=="function")return F.destroy();L(T||new Y("pipe"))}}}function H(F){F()}function $(F,V){return F.pipe(V)}function I(F){return!F.length||typeof F[F.length-1]!="function"?Z:F.pop()}function N(){for(var F=arguments.length,V=new Array(F),D=0;D0;return E(T,y,g,function(f){R||(R=f),f&&M.forEach(H),!y&&(M.forEach(H),L(R))})});return V.reduce($)}Q.exports=N}),T91=l1((A,Q)=>{A=Q.exports=Yy(),A.Stream=A,A.Readable=A,A.Writable=Cy(),A.Duplex=zK(),A.Transform=Uy(),A.PassThrough=P91(),A.finished=dN(),A.pipeline=_91()}),lN=l1((A,Q)=>{(function(J,K){function C(O,w){if(!O)throw new Error(w||"Assertion failed")}function U(O,w){O.super_=w;var k=function(){};k.prototype=w.prototype,O.prototype=new k,O.prototype.constructor=O}function Y(O,w,k){if(Y.isBN(O))return O;this.negative=0,this.words=null,this.length=0,this.red=null,O!==null&&((w==="le"||w==="be")&&(k=w,w=10),this._init(O||0,w||10,k||"be"))}typeof J=="object"?J.exports=Y:K.BN=Y,Y.BN=Y,Y.wordSize=26;var Z;try{typeof window<"u"&&typeof window.Buffer<"u"?Z=window.Buffer:Z=XQ().Buffer}catch{}Y.isBN=function(O){return O instanceof Y?!0:O!==null&&typeof O=="object"&&O.constructor.wordSize===Y.wordSize&&Array.isArray(O.words)},Y.max=function(O,w){return O.cmp(w)>0?O:w},Y.min=function(O,w){return O.cmp(w)<0?O:w},Y.prototype._init=function(O,w,k){if(typeof O=="number")return this._initNumber(O,w,k);if(typeof O=="object")return this._initArray(O,w,k);w==="hex"&&(w=16),C(w===(w|0)&&w>=2&&w<=36),O=O.toString().replace(/\s+/g,"");var S=0;O[0]==="-"&&(S++,this.negative=1),S=0;S-=3)W=O[S]|O[S-1]<<8|O[S-2]<<16,this.words[_]|=W<>>26-j&67108863,j+=24,j>=26&&(j-=26,_++);else if(k==="le")for(S=0,_=0;S>>26-j&67108863,j+=24,j>=26&&(j-=26,_++);return this._strip()};function X(O,w){var k=O.charCodeAt(w);if(k>=48&&k<=57)return k-48;if(k>=65&&k<=70)return k-55;if(k>=97&&k<=102)return k-87;C(!1,"Invalid character in "+O)}function E(O,w,k){var S=X(O,k);return k-1>=w&&(S|=X(O,k-1)<<4),S}Y.prototype._parseHex=function(O,w,k){this.length=Math.ceil((O.length-w)/6),this.words=new Array(this.length);for(var S=0;S=w;S-=2)j=E(O,w,S)<<_,this.words[W]|=j&67108863,_>=18?(_-=18,W+=1,this.words[W]|=j>>>26):_+=8;else{var b=O.length-w;for(S=b%2===0?w+1:w;S=18?(_-=18,W+=1,this.words[W]|=j>>>26):_+=8}this._strip()};function H(O,w,k,S){for(var _=0,W=0,j=Math.min(O.length,k),b=w;b=49?W=p-49+10:p>=17?W=p-17+10:W=p,C(p>=0&&W1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},Y.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},typeof Symbol<"u"&&typeof Symbol.for=="function")try{Y.prototype[Symbol.for("nodejs.util.inspect.custom")]=I}catch{Y.prototype.inspect=I}else Y.prototype.inspect=I;function I(){return(this.red?""}var N=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],F=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],V=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];Y.prototype.toString=function(O,w){O=O||10,w=w|0||1;var k;if(O===16||O==="hex"){k="";for(var S=0,_=0,W=0;W>>24-S&16777215,S+=2,S>=26&&(S-=26,W--),_!==0||W!==this.length-1?k=N[6-b.length]+b+k:k=b+k}for(_!==0&&(k=_.toString(16)+k);k.length%w!==0;)k="0"+k;return this.negative!==0&&(k="-"+k),k}if(O===(O|0)&&O>=2&&O<=36){var p=F[O],s=V[O];k="";var r=this.clone();for(r.negative=0;!r.isZero();){var A1=r.modrn(s).toString(O);r=r.idivn(s),r.isZero()?k=A1+k:k=N[p-A1.length]+A1+k}for(this.isZero()&&(k="0"+k);k.length%w!==0;)k="0"+k;return this.negative!==0&&(k="-"+k),k}C(!1,"Base should be between 2 and 36")},Y.prototype.toNumber=function(){var O=this.words[0];return this.length===2?O+=this.words[1]*67108864:this.length===3&&this.words[2]===1?O+=4503599627370496+this.words[1]*67108864:this.length>2&&C(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-O:O},Y.prototype.toJSON=function(){return this.toString(16,2)},Z&&(Y.prototype.toBuffer=function(O,w){return this.toArrayLike(Z,O,w)}),Y.prototype.toArray=function(O,w){return this.toArrayLike(Array,O,w)};var D=function(O,w){return O.allocUnsafe?O.allocUnsafe(w):new O(w)};Y.prototype.toArrayLike=function(O,w,k){this._strip();var S=this.byteLength(),_=k||Math.max(1,S);C(S<=_,"byte array longer than desired length"),C(_>0,"Requested array length <= 0");var W=D(O,_),j=w==="le"?"LE":"BE";return this["_toArrayLike"+j](W,S),W},Y.prototype._toArrayLikeLE=function(O,w){for(var k=0,S=0,_=0,W=0;_>8&255),k>16&255),W===6?(k>24&255),S=0,W=0):(S=j>>>24,W+=2)}if(k=0&&(O[k--]=j>>8&255),k>=0&&(O[k--]=j>>16&255),W===6?(k>=0&&(O[k--]=j>>24&255),S=0,W=0):(S=j>>>24,W+=2)}if(k>=0)for(O[k--]=S;k>=0;)O[k--]=0},Math.clz32?Y.prototype._countBits=function(O){return 32-Math.clz32(O)}:Y.prototype._countBits=function(O){var w=O,k=0;return w>=4096&&(k+=13,w>>>=13),w>=64&&(k+=7,w>>>=7),w>=8&&(k+=4,w>>>=4),w>=2&&(k+=2,w>>>=2),k+w},Y.prototype._zeroBits=function(O){if(O===0)return 26;var w=O,k=0;return(w&8191)===0&&(k+=13,w>>>=13),(w&127)===0&&(k+=7,w>>>=7),(w&15)===0&&(k+=4,w>>>=4),(w&3)===0&&(k+=2,w>>>=2),(w&1)===0&&k++,k},Y.prototype.bitLength=function(){var O=this.words[this.length-1],w=this._countBits(O);return(this.length-1)*26+w};function L(O){for(var w=new Array(O.bitLength()),k=0;k>>_&1}return w}Y.prototype.zeroBits=function(){if(this.isZero())return 0;for(var O=0,w=0;wO.length?this.clone().ior(O):O.clone().ior(this)},Y.prototype.uor=function(O){return this.length>O.length?this.clone().iuor(O):O.clone().iuor(this)},Y.prototype.iuand=function(O){var w;this.length>O.length?w=O:w=this;for(var k=0;kO.length?this.clone().iand(O):O.clone().iand(this)},Y.prototype.uand=function(O){return this.length>O.length?this.clone().iuand(O):O.clone().iuand(this)},Y.prototype.iuxor=function(O){var w,k;this.length>O.length?(w=this,k=O):(w=O,k=this);for(var S=0;SO.length?this.clone().ixor(O):O.clone().ixor(this)},Y.prototype.uxor=function(O){return this.length>O.length?this.clone().iuxor(O):O.clone().iuxor(this)},Y.prototype.inotn=function(O){C(typeof O=="number"&&O>=0);var w=Math.ceil(O/26)|0,k=O%26;this._expand(w),k>0&&w--;for(var S=0;S0&&(this.words[S]=~this.words[S]&67108863>>26-k),this._strip()},Y.prototype.notn=function(O){return this.clone().inotn(O)},Y.prototype.setn=function(O,w){C(typeof O=="number"&&O>=0);var k=O/26|0,S=O%26;return this._expand(k+1),w?this.words[k]=this.words[k]|1<O.length?(k=this,S=O):(k=O,S=this);for(var _=0,W=0;W>>26;for(;_!==0&&W>>26;if(this.length=k.length,_!==0)this.words[this.length]=_,this.length++;else if(k!==this)for(;WO.length?this.clone().iadd(O):O.clone().iadd(this)},Y.prototype.isub=function(O){if(O.negative!==0){O.negative=0;var w=this.iadd(O);return O.negative=1,w._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(O),this.negative=1,this._normSign();var k=this.cmp(O);if(k===0)return this.negative=0,this.length=1,this.words[0]=0,this;var S,_;k>0?(S=this,_=O):(S=O,_=this);for(var W=0,j=0;j<_.length;j++)w=(S.words[j]|0)-(_.words[j]|0)+W,W=w>>26,this.words[j]=w&67108863;for(;W!==0&&j>26,this.words[j]=w&67108863;if(W===0&&j>>26,A1=p&67108863,Q1=Math.min(s,w.length-1),e=Math.max(0,s-O.length+1);e<=Q1;e++){var t=s-e|0;_=O.words[t]|0,W=w.words[e]|0,j=_*W+A1,r+=j/67108864|0,A1=j&67108863}k.words[s]=A1|0,p=r|0}return p!==0?k.words[s]=p|0:k.length--,k._strip()}var M=function(O,w,k){var S=O.words,_=w.words,W=k.words,j=0,b,p,s,r=S[0]|0,A1=r&8191,Q1=r>>>13,e=S[1]|0,t=e&8191,U1=e>>>13,O1=S[2]|0,E1=O1&8191,Y1=O1>>>13,i=S[3]|0,c=i&8191,o=i>>>13,C1=S[4]|0,q1=C1&8191,Z1=C1>>>13,j1=S[5]|0,H1=j1&8191,B1=j1>>>13,k1=S[6]|0,D1=k1&8191,G1=k1>>>13,w1=S[7]|0,G=w1&8191,z=w1>>>13,x=S[8]|0,m=x&8191,l=x>>>13,a=S[9]|0,K1=a&8191,F1=a>>>13,R1=_[0]|0,X1=R1&8191,W1=R1>>>13,$1=_[1]|0,N1=$1&8191,_1=$1>>>13,J1=_[2]|0,z1=J1&8191,M1=J1>>>13,L1=_[3]|0,V1=L1&8191,S1=L1>>>13,O0=_[4]|0,h1=O0&8191,b1=O0>>>13,f0=_[5]|0,e1=f0&8191,s1=f0>>>13,o0=_[6]|0,a1=o0&8191,r1=o0>>>13,FA=_[7]|0,K0=FA&8191,J0=FA>>>13,qA=_[8]|0,Q0=qA&8191,A0=qA>>>13,hA=_[9]|0,r0=hA&8191,EA=hA>>>13;k.negative=O.negative^w.negative,k.length=19,b=Math.imul(A1,X1),p=Math.imul(A1,W1),p=p+Math.imul(Q1,X1)|0,s=Math.imul(Q1,W1);var X2=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(X2>>>26)|0,X2&=67108863,b=Math.imul(t,X1),p=Math.imul(t,W1),p=p+Math.imul(U1,X1)|0,s=Math.imul(U1,W1),b=b+Math.imul(A1,N1)|0,p=p+Math.imul(A1,_1)|0,p=p+Math.imul(Q1,N1)|0,s=s+Math.imul(Q1,_1)|0;var E2=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(E2>>>26)|0,E2&=67108863,b=Math.imul(E1,X1),p=Math.imul(E1,W1),p=p+Math.imul(Y1,X1)|0,s=Math.imul(Y1,W1),b=b+Math.imul(t,N1)|0,p=p+Math.imul(t,_1)|0,p=p+Math.imul(U1,N1)|0,s=s+Math.imul(U1,_1)|0,b=b+Math.imul(A1,z1)|0,p=p+Math.imul(A1,M1)|0,p=p+Math.imul(Q1,z1)|0,s=s+Math.imul(Q1,M1)|0;var T1=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(T1>>>26)|0,T1&=67108863,b=Math.imul(c,X1),p=Math.imul(c,W1),p=p+Math.imul(o,X1)|0,s=Math.imul(o,W1),b=b+Math.imul(E1,N1)|0,p=p+Math.imul(E1,_1)|0,p=p+Math.imul(Y1,N1)|0,s=s+Math.imul(Y1,_1)|0,b=b+Math.imul(t,z1)|0,p=p+Math.imul(t,M1)|0,p=p+Math.imul(U1,z1)|0,s=s+Math.imul(U1,M1)|0,b=b+Math.imul(A1,V1)|0,p=p+Math.imul(A1,S1)|0,p=p+Math.imul(Q1,V1)|0,s=s+Math.imul(Q1,S1)|0;var m1=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(m1>>>26)|0,m1&=67108863,b=Math.imul(q1,X1),p=Math.imul(q1,W1),p=p+Math.imul(Z1,X1)|0,s=Math.imul(Z1,W1),b=b+Math.imul(c,N1)|0,p=p+Math.imul(c,_1)|0,p=p+Math.imul(o,N1)|0,s=s+Math.imul(o,_1)|0,b=b+Math.imul(E1,z1)|0,p=p+Math.imul(E1,M1)|0,p=p+Math.imul(Y1,z1)|0,s=s+Math.imul(Y1,M1)|0,b=b+Math.imul(t,V1)|0,p=p+Math.imul(t,S1)|0,p=p+Math.imul(U1,V1)|0,s=s+Math.imul(U1,S1)|0,b=b+Math.imul(A1,h1)|0,p=p+Math.imul(A1,b1)|0,p=p+Math.imul(Q1,h1)|0,s=s+Math.imul(Q1,b1)|0;var i1=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(i1>>>26)|0,i1&=67108863,b=Math.imul(H1,X1),p=Math.imul(H1,W1),p=p+Math.imul(B1,X1)|0,s=Math.imul(B1,W1),b=b+Math.imul(q1,N1)|0,p=p+Math.imul(q1,_1)|0,p=p+Math.imul(Z1,N1)|0,s=s+Math.imul(Z1,_1)|0,b=b+Math.imul(c,z1)|0,p=p+Math.imul(c,M1)|0,p=p+Math.imul(o,z1)|0,s=s+Math.imul(o,M1)|0,b=b+Math.imul(E1,V1)|0,p=p+Math.imul(E1,S1)|0,p=p+Math.imul(Y1,V1)|0,s=s+Math.imul(Y1,S1)|0,b=b+Math.imul(t,h1)|0,p=p+Math.imul(t,b1)|0,p=p+Math.imul(U1,h1)|0,s=s+Math.imul(U1,b1)|0,b=b+Math.imul(A1,e1)|0,p=p+Math.imul(A1,s1)|0,p=p+Math.imul(Q1,e1)|0,s=s+Math.imul(Q1,s1)|0;var t1=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(t1>>>26)|0,t1&=67108863,b=Math.imul(D1,X1),p=Math.imul(D1,W1),p=p+Math.imul(G1,X1)|0,s=Math.imul(G1,W1),b=b+Math.imul(H1,N1)|0,p=p+Math.imul(H1,_1)|0,p=p+Math.imul(B1,N1)|0,s=s+Math.imul(B1,_1)|0,b=b+Math.imul(q1,z1)|0,p=p+Math.imul(q1,M1)|0,p=p+Math.imul(Z1,z1)|0,s=s+Math.imul(Z1,M1)|0,b=b+Math.imul(c,V1)|0,p=p+Math.imul(c,S1)|0,p=p+Math.imul(o,V1)|0,s=s+Math.imul(o,S1)|0,b=b+Math.imul(E1,h1)|0,p=p+Math.imul(E1,b1)|0,p=p+Math.imul(Y1,h1)|0,s=s+Math.imul(Y1,b1)|0,b=b+Math.imul(t,e1)|0,p=p+Math.imul(t,s1)|0,p=p+Math.imul(U1,e1)|0,s=s+Math.imul(U1,s1)|0,b=b+Math.imul(A1,a1)|0,p=p+Math.imul(A1,r1)|0,p=p+Math.imul(Q1,a1)|0,s=s+Math.imul(Q1,r1)|0;var d1=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(d1>>>26)|0,d1&=67108863,b=Math.imul(G,X1),p=Math.imul(G,W1),p=p+Math.imul(z,X1)|0,s=Math.imul(z,W1),b=b+Math.imul(D1,N1)|0,p=p+Math.imul(D1,_1)|0,p=p+Math.imul(G1,N1)|0,s=s+Math.imul(G1,_1)|0,b=b+Math.imul(H1,z1)|0,p=p+Math.imul(H1,M1)|0,p=p+Math.imul(B1,z1)|0,s=s+Math.imul(B1,M1)|0,b=b+Math.imul(q1,V1)|0,p=p+Math.imul(q1,S1)|0,p=p+Math.imul(Z1,V1)|0,s=s+Math.imul(Z1,S1)|0,b=b+Math.imul(c,h1)|0,p=p+Math.imul(c,b1)|0,p=p+Math.imul(o,h1)|0,s=s+Math.imul(o,b1)|0,b=b+Math.imul(E1,e1)|0,p=p+Math.imul(E1,s1)|0,p=p+Math.imul(Y1,e1)|0,s=s+Math.imul(Y1,s1)|0,b=b+Math.imul(t,a1)|0,p=p+Math.imul(t,r1)|0,p=p+Math.imul(U1,a1)|0,s=s+Math.imul(U1,r1)|0,b=b+Math.imul(A1,K0)|0,p=p+Math.imul(A1,J0)|0,p=p+Math.imul(Q1,K0)|0,s=s+Math.imul(Q1,J0)|0;var H0=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(H0>>>26)|0,H0&=67108863,b=Math.imul(m,X1),p=Math.imul(m,W1),p=p+Math.imul(l,X1)|0,s=Math.imul(l,W1),b=b+Math.imul(G,N1)|0,p=p+Math.imul(G,_1)|0,p=p+Math.imul(z,N1)|0,s=s+Math.imul(z,_1)|0,b=b+Math.imul(D1,z1)|0,p=p+Math.imul(D1,M1)|0,p=p+Math.imul(G1,z1)|0,s=s+Math.imul(G1,M1)|0,b=b+Math.imul(H1,V1)|0,p=p+Math.imul(H1,S1)|0,p=p+Math.imul(B1,V1)|0,s=s+Math.imul(B1,S1)|0,b=b+Math.imul(q1,h1)|0,p=p+Math.imul(q1,b1)|0,p=p+Math.imul(Z1,h1)|0,s=s+Math.imul(Z1,b1)|0,b=b+Math.imul(c,e1)|0,p=p+Math.imul(c,s1)|0,p=p+Math.imul(o,e1)|0,s=s+Math.imul(o,s1)|0,b=b+Math.imul(E1,a1)|0,p=p+Math.imul(E1,r1)|0,p=p+Math.imul(Y1,a1)|0,s=s+Math.imul(Y1,r1)|0,b=b+Math.imul(t,K0)|0,p=p+Math.imul(t,J0)|0,p=p+Math.imul(U1,K0)|0,s=s+Math.imul(U1,J0)|0,b=b+Math.imul(A1,Q0)|0,p=p+Math.imul(A1,A0)|0,p=p+Math.imul(Q1,Q0)|0,s=s+Math.imul(Q1,A0)|0;var R0=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(R0>>>26)|0,R0&=67108863,b=Math.imul(K1,X1),p=Math.imul(K1,W1),p=p+Math.imul(F1,X1)|0,s=Math.imul(F1,W1),b=b+Math.imul(m,N1)|0,p=p+Math.imul(m,_1)|0,p=p+Math.imul(l,N1)|0,s=s+Math.imul(l,_1)|0,b=b+Math.imul(G,z1)|0,p=p+Math.imul(G,M1)|0,p=p+Math.imul(z,z1)|0,s=s+Math.imul(z,M1)|0,b=b+Math.imul(D1,V1)|0,p=p+Math.imul(D1,S1)|0,p=p+Math.imul(G1,V1)|0,s=s+Math.imul(G1,S1)|0,b=b+Math.imul(H1,h1)|0,p=p+Math.imul(H1,b1)|0,p=p+Math.imul(B1,h1)|0,s=s+Math.imul(B1,b1)|0,b=b+Math.imul(q1,e1)|0,p=p+Math.imul(q1,s1)|0,p=p+Math.imul(Z1,e1)|0,s=s+Math.imul(Z1,s1)|0,b=b+Math.imul(c,a1)|0,p=p+Math.imul(c,r1)|0,p=p+Math.imul(o,a1)|0,s=s+Math.imul(o,r1)|0,b=b+Math.imul(E1,K0)|0,p=p+Math.imul(E1,J0)|0,p=p+Math.imul(Y1,K0)|0,s=s+Math.imul(Y1,J0)|0,b=b+Math.imul(t,Q0)|0,p=p+Math.imul(t,A0)|0,p=p+Math.imul(U1,Q0)|0,s=s+Math.imul(U1,A0)|0,b=b+Math.imul(A1,r0)|0,p=p+Math.imul(A1,EA)|0,p=p+Math.imul(Q1,r0)|0,s=s+Math.imul(Q1,EA)|0;var D0=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(D0>>>26)|0,D0&=67108863,b=Math.imul(K1,N1),p=Math.imul(K1,_1),p=p+Math.imul(F1,N1)|0,s=Math.imul(F1,_1),b=b+Math.imul(m,z1)|0,p=p+Math.imul(m,M1)|0,p=p+Math.imul(l,z1)|0,s=s+Math.imul(l,M1)|0,b=b+Math.imul(G,V1)|0,p=p+Math.imul(G,S1)|0,p=p+Math.imul(z,V1)|0,s=s+Math.imul(z,S1)|0,b=b+Math.imul(D1,h1)|0,p=p+Math.imul(D1,b1)|0,p=p+Math.imul(G1,h1)|0,s=s+Math.imul(G1,b1)|0,b=b+Math.imul(H1,e1)|0,p=p+Math.imul(H1,s1)|0,p=p+Math.imul(B1,e1)|0,s=s+Math.imul(B1,s1)|0,b=b+Math.imul(q1,a1)|0,p=p+Math.imul(q1,r1)|0,p=p+Math.imul(Z1,a1)|0,s=s+Math.imul(Z1,r1)|0,b=b+Math.imul(c,K0)|0,p=p+Math.imul(c,J0)|0,p=p+Math.imul(o,K0)|0,s=s+Math.imul(o,J0)|0,b=b+Math.imul(E1,Q0)|0,p=p+Math.imul(E1,A0)|0,p=p+Math.imul(Y1,Q0)|0,s=s+Math.imul(Y1,A0)|0,b=b+Math.imul(t,r0)|0,p=p+Math.imul(t,EA)|0,p=p+Math.imul(U1,r0)|0,s=s+Math.imul(U1,EA)|0;var P0=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(P0>>>26)|0,P0&=67108863,b=Math.imul(K1,z1),p=Math.imul(K1,M1),p=p+Math.imul(F1,z1)|0,s=Math.imul(F1,M1),b=b+Math.imul(m,V1)|0,p=p+Math.imul(m,S1)|0,p=p+Math.imul(l,V1)|0,s=s+Math.imul(l,S1)|0,b=b+Math.imul(G,h1)|0,p=p+Math.imul(G,b1)|0,p=p+Math.imul(z,h1)|0,s=s+Math.imul(z,b1)|0,b=b+Math.imul(D1,e1)|0,p=p+Math.imul(D1,s1)|0,p=p+Math.imul(G1,e1)|0,s=s+Math.imul(G1,s1)|0,b=b+Math.imul(H1,a1)|0,p=p+Math.imul(H1,r1)|0,p=p+Math.imul(B1,a1)|0,s=s+Math.imul(B1,r1)|0,b=b+Math.imul(q1,K0)|0,p=p+Math.imul(q1,J0)|0,p=p+Math.imul(Z1,K0)|0,s=s+Math.imul(Z1,J0)|0,b=b+Math.imul(c,Q0)|0,p=p+Math.imul(c,A0)|0,p=p+Math.imul(o,Q0)|0,s=s+Math.imul(o,A0)|0,b=b+Math.imul(E1,r0)|0,p=p+Math.imul(E1,EA)|0,p=p+Math.imul(Y1,r0)|0,s=s+Math.imul(Y1,EA)|0;var j0=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(j0>>>26)|0,j0&=67108863,b=Math.imul(K1,V1),p=Math.imul(K1,S1),p=p+Math.imul(F1,V1)|0,s=Math.imul(F1,S1),b=b+Math.imul(m,h1)|0,p=p+Math.imul(m,b1)|0,p=p+Math.imul(l,h1)|0,s=s+Math.imul(l,b1)|0,b=b+Math.imul(G,e1)|0,p=p+Math.imul(G,s1)|0,p=p+Math.imul(z,e1)|0,s=s+Math.imul(z,s1)|0,b=b+Math.imul(D1,a1)|0,p=p+Math.imul(D1,r1)|0,p=p+Math.imul(G1,a1)|0,s=s+Math.imul(G1,r1)|0,b=b+Math.imul(H1,K0)|0,p=p+Math.imul(H1,J0)|0,p=p+Math.imul(B1,K0)|0,s=s+Math.imul(B1,J0)|0,b=b+Math.imul(q1,Q0)|0,p=p+Math.imul(q1,A0)|0,p=p+Math.imul(Z1,Q0)|0,s=s+Math.imul(Z1,A0)|0,b=b+Math.imul(c,r0)|0,p=p+Math.imul(c,EA)|0,p=p+Math.imul(o,r0)|0,s=s+Math.imul(o,EA)|0;var v0=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(v0>>>26)|0,v0&=67108863,b=Math.imul(K1,h1),p=Math.imul(K1,b1),p=p+Math.imul(F1,h1)|0,s=Math.imul(F1,b1),b=b+Math.imul(m,e1)|0,p=p+Math.imul(m,s1)|0,p=p+Math.imul(l,e1)|0,s=s+Math.imul(l,s1)|0,b=b+Math.imul(G,a1)|0,p=p+Math.imul(G,r1)|0,p=p+Math.imul(z,a1)|0,s=s+Math.imul(z,r1)|0,b=b+Math.imul(D1,K0)|0,p=p+Math.imul(D1,J0)|0,p=p+Math.imul(G1,K0)|0,s=s+Math.imul(G1,J0)|0,b=b+Math.imul(H1,Q0)|0,p=p+Math.imul(H1,A0)|0,p=p+Math.imul(B1,Q0)|0,s=s+Math.imul(B1,A0)|0,b=b+Math.imul(q1,r0)|0,p=p+Math.imul(q1,EA)|0,p=p+Math.imul(Z1,r0)|0,s=s+Math.imul(Z1,EA)|0;var S0=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(S0>>>26)|0,S0&=67108863,b=Math.imul(K1,e1),p=Math.imul(K1,s1),p=p+Math.imul(F1,e1)|0,s=Math.imul(F1,s1),b=b+Math.imul(m,a1)|0,p=p+Math.imul(m,r1)|0,p=p+Math.imul(l,a1)|0,s=s+Math.imul(l,r1)|0,b=b+Math.imul(G,K0)|0,p=p+Math.imul(G,J0)|0,p=p+Math.imul(z,K0)|0,s=s+Math.imul(z,J0)|0,b=b+Math.imul(D1,Q0)|0,p=p+Math.imul(D1,A0)|0,p=p+Math.imul(G1,Q0)|0,s=s+Math.imul(G1,A0)|0,b=b+Math.imul(H1,r0)|0,p=p+Math.imul(H1,EA)|0,p=p+Math.imul(B1,r0)|0,s=s+Math.imul(B1,EA)|0;var n0=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(n0>>>26)|0,n0&=67108863,b=Math.imul(K1,a1),p=Math.imul(K1,r1),p=p+Math.imul(F1,a1)|0,s=Math.imul(F1,r1),b=b+Math.imul(m,K0)|0,p=p+Math.imul(m,J0)|0,p=p+Math.imul(l,K0)|0,s=s+Math.imul(l,J0)|0,b=b+Math.imul(G,Q0)|0,p=p+Math.imul(G,A0)|0,p=p+Math.imul(z,Q0)|0,s=s+Math.imul(z,A0)|0,b=b+Math.imul(D1,r0)|0,p=p+Math.imul(D1,EA)|0,p=p+Math.imul(G1,r0)|0,s=s+Math.imul(G1,EA)|0;var i0=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(i0>>>26)|0,i0&=67108863,b=Math.imul(K1,K0),p=Math.imul(K1,J0),p=p+Math.imul(F1,K0)|0,s=Math.imul(F1,J0),b=b+Math.imul(m,Q0)|0,p=p+Math.imul(m,A0)|0,p=p+Math.imul(l,Q0)|0,s=s+Math.imul(l,A0)|0,b=b+Math.imul(G,r0)|0,p=p+Math.imul(G,EA)|0,p=p+Math.imul(z,r0)|0,s=s+Math.imul(z,EA)|0;var S2=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(S2>>>26)|0,S2&=67108863,b=Math.imul(K1,Q0),p=Math.imul(K1,A0),p=p+Math.imul(F1,Q0)|0,s=Math.imul(F1,A0),b=b+Math.imul(m,r0)|0,p=p+Math.imul(m,EA)|0,p=p+Math.imul(l,r0)|0,s=s+Math.imul(l,EA)|0;var z2=(j+b|0)+((p&8191)<<13)|0;j=(s+(p>>>13)|0)+(z2>>>26)|0,z2&=67108863,b=Math.imul(K1,r0),p=Math.imul(K1,EA),p=p+Math.imul(F1,r0)|0,s=Math.imul(F1,EA);var P1=(j+b|0)+((p&8191)<<13)|0;return j=(s+(p>>>13)|0)+(P1>>>26)|0,P1&=67108863,W[0]=X2,W[1]=E2,W[2]=T1,W[3]=m1,W[4]=i1,W[5]=t1,W[6]=d1,W[7]=H0,W[8]=R0,W[9]=D0,W[10]=P0,W[11]=j0,W[12]=v0,W[13]=S0,W[14]=n0,W[15]=i0,W[16]=S2,W[17]=z2,W[18]=P1,j!==0&&(W[19]=j,k.length++),k};Math.imul||(M=R);function T(O,w,k){k.negative=w.negative^O.negative,k.length=O.length+w.length;for(var S=0,_=0,W=0;W>>26)|0,_+=j>>>26,j&=67108863}k.words[W]=b,S=j,j=_}return S!==0?k.words[W]=S:k.length--,k._strip()}function h(O,w,k){return T(O,w,k)}Y.prototype.mulTo=function(O,w){var k,S=this.length+O.length;return this.length===10&&O.length===10?k=M(this,O,w):S<63?k=R(this,O,w):S<1024?k=T(this,O,w):k=h(this,O,w),k};function y(O,w){this.x=O,this.y=w}y.prototype.makeRBT=function(O){for(var w=new Array(O),k=Y.prototype._countBits(O)-1,S=0;S>=1;return S},y.prototype.permute=function(O,w,k,S,_,W){for(var j=0;j>>1)_++;return 1<<_+1+S},y.prototype.conjugate=function(O,w,k){if(!(k<=1))for(var S=0;S>>13,k[2*W+1]=_&8191,_=_>>>13;for(W=2*w;W>=26,k+=_/67108864|0,k+=W>>>26,this.words[S]=W&67108863}return k!==0&&(this.words[S]=k,this.length++),w?this.ineg():this},Y.prototype.muln=function(O){return this.clone().imuln(O)},Y.prototype.sqr=function(){return this.mul(this)},Y.prototype.isqr=function(){return this.imul(this.clone())},Y.prototype.pow=function(O){var w=L(O);if(w.length===0)return new Y(1);for(var k=this,S=0;S=0);var w=O%26,k=(O-w)/26,S=67108863>>>26-w<<26-w,_;if(w!==0){var W=0;for(_=0;_>>26-w}W&&(this.words[_]=W,this.length++)}if(k!==0){for(_=this.length-1;_>=0;_--)this.words[_+k]=this.words[_];for(_=0;_=0);var S;w?S=(w-w%26)/26:S=0;var _=O%26,W=Math.min((O-_)/26,this.length),j=67108863^67108863>>>_<<_,b=k;if(S-=W,S=Math.max(0,S),b){for(var p=0;pW)for(this.length-=W,p=0;p=0&&(s!==0||p>=S);p--){var r=this.words[p]|0;this.words[p]=s<<26-_|r>>>_,s=r&j}return b&&s!==0&&(b.words[b.length++]=s),this.length===0&&(this.words[0]=0,this.length=1),this._strip()},Y.prototype.ishrn=function(O,w,k){return C(this.negative===0),this.iushrn(O,w,k)},Y.prototype.shln=function(O){return this.clone().ishln(O)},Y.prototype.ushln=function(O){return this.clone().iushln(O)},Y.prototype.shrn=function(O){return this.clone().ishrn(O)},Y.prototype.ushrn=function(O){return this.clone().iushrn(O)},Y.prototype.testn=function(O){C(typeof O=="number"&&O>=0);var w=O%26,k=(O-w)/26,S=1<=0);var w=O%26,k=(O-w)/26;if(C(this.negative===0,"imaskn works only with positive numbers"),this.length<=k)return this;if(w!==0&&k++,this.length=Math.min(k,this.length),w!==0){var S=67108863^67108863>>>w<=67108864;w++)this.words[w]-=67108864,w===this.length-1?this.words[w+1]=1:this.words[w+1]++;return this.length=Math.max(this.length,w+1),this},Y.prototype.isubn=function(O){if(C(typeof O=="number"),C(O<67108864),O<0)return this.iaddn(-O);if(this.negative!==0)return this.negative=0,this.iaddn(O),this.negative=1,this;if(this.words[0]-=O,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var w=0;w>26)-(b/67108864|0),this.words[_+k]=W&67108863}for(;_>26,this.words[_+k]=W&67108863;if(j===0)return this._strip();for(C(j===-1),j=0,_=0;_>26,this.words[_]=W&67108863;return this.negative=1,this._strip()},Y.prototype._wordDiv=function(O,w){var k=this.length-O.length,S=this.clone(),_=O,W=_.words[_.length-1]|0,j=this._countBits(W);k=26-j,k!==0&&(_=_.ushln(k),S.iushln(k),W=_.words[_.length-1]|0);var b=S.length-_.length,p;if(w!=="mod"){p=new Y(null),p.length=b+1,p.words=new Array(p.length);for(var s=0;s=0;A1--){var Q1=(S.words[_.length+A1]|0)*67108864+(S.words[_.length+A1-1]|0);for(Q1=Math.min(Q1/W|0,67108863),S._ishlnsubmul(_,Q1,A1);S.negative!==0;)Q1--,S.negative=0,S._ishlnsubmul(_,1,A1),S.isZero()||(S.negative^=1);p&&(p.words[A1]=Q1)}return p&&p._strip(),S._strip(),w!=="div"&&k!==0&&S.iushrn(k),{div:p||null,mod:S}},Y.prototype.divmod=function(O,w,k){if(C(!O.isZero()),this.isZero())return{div:new Y(0),mod:new Y(0)};var S,_,W;return this.negative!==0&&O.negative===0?(W=this.neg().divmod(O,w),w!=="mod"&&(S=W.div.neg()),w!=="div"&&(_=W.mod.neg(),k&&_.negative!==0&&_.iadd(O)),{div:S,mod:_}):this.negative===0&&O.negative!==0?(W=this.divmod(O.neg(),w),w!=="mod"&&(S=W.div.neg()),{div:S,mod:W.mod}):(this.negative&O.negative)!==0?(W=this.neg().divmod(O.neg(),w),w!=="div"&&(_=W.mod.neg(),k&&_.negative!==0&&_.isub(O)),{div:W.div,mod:_}):O.length>this.length||this.cmp(O)<0?{div:new Y(0),mod:this}:O.length===1?w==="div"?{div:this.divn(O.words[0]),mod:null}:w==="mod"?{div:null,mod:new Y(this.modrn(O.words[0]))}:{div:this.divn(O.words[0]),mod:new Y(this.modrn(O.words[0]))}:this._wordDiv(O,w)},Y.prototype.div=function(O){return this.divmod(O,"div",!1).div},Y.prototype.mod=function(O){return this.divmod(O,"mod",!1).mod},Y.prototype.umod=function(O){return this.divmod(O,"mod",!0).mod},Y.prototype.divRound=function(O){var w=this.divmod(O);if(w.mod.isZero())return w.div;var k=w.div.negative!==0?w.mod.isub(O):w.mod,S=O.ushrn(1),_=O.andln(1),W=k.cmp(S);return W<0||_===1&&W===0?w.div:w.div.negative!==0?w.div.isubn(1):w.div.iaddn(1)},Y.prototype.modrn=function(O){var w=O<0;w&&(O=-O),C(O<=67108863);for(var k=67108864%O,S=0,_=this.length-1;_>=0;_--)S=(k*S+(this.words[_]|0))%O;return w?-S:S},Y.prototype.modn=function(O){return this.modrn(O)},Y.prototype.idivn=function(O){var w=O<0;w&&(O=-O),C(O<=67108863);for(var k=0,S=this.length-1;S>=0;S--){var _=(this.words[S]|0)+k*67108864;this.words[S]=_/O|0,k=_%O}return this._strip(),w?this.ineg():this},Y.prototype.divn=function(O){return this.clone().idivn(O)},Y.prototype.egcd=function(O){C(O.negative===0),C(!O.isZero());var w=this,k=O.clone();w.negative!==0?w=w.umod(O):w=w.clone();for(var S=new Y(1),_=new Y(0),W=new Y(0),j=new Y(1),b=0;w.isEven()&&k.isEven();)w.iushrn(1),k.iushrn(1),++b;for(var p=k.clone(),s=w.clone();!w.isZero();){for(var r=0,A1=1;(w.words[0]&A1)===0&&r<26;++r,A1<<=1);if(r>0)for(w.iushrn(r);r-- >0;)(S.isOdd()||_.isOdd())&&(S.iadd(p),_.isub(s)),S.iushrn(1),_.iushrn(1);for(var Q1=0,e=1;(k.words[0]&e)===0&&Q1<26;++Q1,e<<=1);if(Q1>0)for(k.iushrn(Q1);Q1-- >0;)(W.isOdd()||j.isOdd())&&(W.iadd(p),j.isub(s)),W.iushrn(1),j.iushrn(1);w.cmp(k)>=0?(w.isub(k),S.isub(W),_.isub(j)):(k.isub(w),W.isub(S),j.isub(_))}return{a:W,b:j,gcd:k.iushln(b)}},Y.prototype._invmp=function(O){C(O.negative===0),C(!O.isZero());var w=this,k=O.clone();w.negative!==0?w=w.umod(O):w=w.clone();for(var S=new Y(1),_=new Y(0),W=k.clone();w.cmpn(1)>0&&k.cmpn(1)>0;){for(var j=0,b=1;(w.words[0]&b)===0&&j<26;++j,b<<=1);if(j>0)for(w.iushrn(j);j-- >0;)S.isOdd()&&S.iadd(W),S.iushrn(1);for(var p=0,s=1;(k.words[0]&s)===0&&p<26;++p,s<<=1);if(p>0)for(k.iushrn(p);p-- >0;)_.isOdd()&&_.iadd(W),_.iushrn(1);w.cmp(k)>=0?(w.isub(k),S.isub(_)):(k.isub(w),_.isub(S))}var r;return w.cmpn(1)===0?r=S:r=_,r.cmpn(0)<0&&r.iadd(O),r},Y.prototype.gcd=function(O){if(this.isZero())return O.abs();if(O.isZero())return this.abs();var w=this.clone(),k=O.clone();w.negative=0,k.negative=0;for(var S=0;w.isEven()&&k.isEven();S++)w.iushrn(1),k.iushrn(1);do{for(;w.isEven();)w.iushrn(1);for(;k.isEven();)k.iushrn(1);var _=w.cmp(k);if(_<0){var W=w;w=k,k=W}else if(_===0||k.cmpn(1)===0)break;w.isub(k)}while(!0);return k.iushln(S)},Y.prototype.invm=function(O){return this.egcd(O).a.umod(O)},Y.prototype.isEven=function(){return(this.words[0]&1)===0},Y.prototype.isOdd=function(){return(this.words[0]&1)===1},Y.prototype.andln=function(O){return this.words[0]&O},Y.prototype.bincn=function(O){C(typeof O=="number");var w=O%26,k=(O-w)/26,S=1<>>26,j&=67108863,this.words[W]=j}return _!==0&&(this.words[W]=_,this.length++),this},Y.prototype.isZero=function(){return this.length===1&&this.words[0]===0},Y.prototype.cmpn=function(O){var w=O<0;if(this.negative!==0&&!w)return-1;if(this.negative===0&&w)return 1;this._strip();var k;if(this.length>1)k=1;else{w&&(O=-O),C(O<=67108863,"Number is too big");var S=this.words[0]|0;k=S===O?0:SO.length)return 1;if(this.length=0;k--){var S=this.words[k]|0,_=O.words[k]|0;if(S!==_){S<_?w=-1:S>_&&(w=1);break}}return w},Y.prototype.gtn=function(O){return this.cmpn(O)===1},Y.prototype.gt=function(O){return this.cmp(O)===1},Y.prototype.gten=function(O){return this.cmpn(O)>=0},Y.prototype.gte=function(O){return this.cmp(O)>=0},Y.prototype.ltn=function(O){return this.cmpn(O)===-1},Y.prototype.lt=function(O){return this.cmp(O)===-1},Y.prototype.lten=function(O){return this.cmpn(O)<=0},Y.prototype.lte=function(O){return this.cmp(O)<=0},Y.prototype.eqn=function(O){return this.cmpn(O)===0},Y.prototype.eq=function(O){return this.cmp(O)===0},Y.red=function(O){return new q(O)},Y.prototype.toRed=function(O){return C(!this.red,"Already a number in reduction context"),C(this.negative===0,"red works only with positives"),O.convertTo(this)._forceRed(O)},Y.prototype.fromRed=function(){return C(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},Y.prototype._forceRed=function(O){return this.red=O,this},Y.prototype.forceRed=function(O){return C(!this.red,"Already a number in reduction context"),this._forceRed(O)},Y.prototype.redAdd=function(O){return C(this.red,"redAdd works only with red numbers"),this.red.add(this,O)},Y.prototype.redIAdd=function(O){return C(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,O)},Y.prototype.redSub=function(O){return C(this.red,"redSub works only with red numbers"),this.red.sub(this,O)},Y.prototype.redISub=function(O){return C(this.red,"redISub works only with red numbers"),this.red.isub(this,O)},Y.prototype.redShl=function(O){return C(this.red,"redShl works only with red numbers"),this.red.shl(this,O)},Y.prototype.redMul=function(O){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,O),this.red.mul(this,O)},Y.prototype.redIMul=function(O){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,O),this.red.imul(this,O)},Y.prototype.redSqr=function(){return C(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},Y.prototype.redISqr=function(){return C(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},Y.prototype.redSqrt=function(){return C(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},Y.prototype.redInvm=function(){return C(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},Y.prototype.redNeg=function(){return C(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},Y.prototype.redPow=function(O){return C(this.red&&!O.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,O)};var g={k256:null,p224:null,p192:null,p25519:null};function f(O,w){this.name=O,this.p=new Y(w,16),this.n=this.p.bitLength(),this.k=new Y(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}f.prototype._tmp=function(){var O=new Y(null);return O.words=new Array(Math.ceil(this.n/13)),O},f.prototype.ireduce=function(O){var w=O,k;do this.split(w,this.tmp),w=this.imulK(w),w=w.iadd(this.tmp),k=w.bitLength();while(k>this.n);var S=k0?w.isub(this.p):w.strip!==void 0?w.strip():w._strip(),w},f.prototype.split=function(O,w){O.iushrn(this.n,0,w)},f.prototype.imulK=function(O){return O.imul(this.k)};function u(){f.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}U(u,f),u.prototype.split=function(O,w){for(var k=4194303,S=Math.min(O.length,9),_=0;_>>22,W=j}W>>>=22,O.words[_-10]=W,W===0&&O.length>10?O.length-=10:O.length-=9},u.prototype.imulK=function(O){O.words[O.length]=0,O.words[O.length+1]=0,O.length+=2;for(var w=0,k=0;k>>=26,O.words[k]=_,w=S}return w!==0&&(O.words[O.length++]=w),O},Y._prime=function(O){if(g[O])return g[O];var w;if(O==="k256")w=new u;else if(O==="p224")w=new d;else if(O==="p192")w=new n;else if(O==="p25519")w=new B;else throw new Error("Unknown prime "+O);return g[O]=w,w};function q(O){if(typeof O=="string"){var w=Y._prime(O);this.m=w.p,this.prime=w}else C(O.gtn(1),"modulus must be greater than 1"),this.m=O,this.prime=null}q.prototype._verify1=function(O){C(O.negative===0,"red works only with positives"),C(O.red,"red works only with red numbers")},q.prototype._verify2=function(O,w){C((O.negative|w.negative)===0,"red works only with positives"),C(O.red&&O.red===w.red,"red works only with red numbers")},q.prototype.imod=function(O){return this.prime?this.prime.ireduce(O)._forceRed(this):($(O,O.umod(this.m)._forceRed(this)),O)},q.prototype.neg=function(O){return O.isZero()?O.clone():this.m.sub(O)._forceRed(this)},q.prototype.add=function(O,w){this._verify2(O,w);var k=O.add(w);return k.cmp(this.m)>=0&&k.isub(this.m),k._forceRed(this)},q.prototype.iadd=function(O,w){this._verify2(O,w);var k=O.iadd(w);return k.cmp(this.m)>=0&&k.isub(this.m),k},q.prototype.sub=function(O,w){this._verify2(O,w);var k=O.sub(w);return k.cmpn(0)<0&&k.iadd(this.m),k._forceRed(this)},q.prototype.isub=function(O,w){this._verify2(O,w);var k=O.isub(w);return k.cmpn(0)<0&&k.iadd(this.m),k},q.prototype.shl=function(O,w){return this._verify1(O),this.imod(O.ushln(w))},q.prototype.imul=function(O,w){return this._verify2(O,w),this.imod(O.imul(w))},q.prototype.mul=function(O,w){return this._verify2(O,w),this.imod(O.mul(w))},q.prototype.isqr=function(O){return this.imul(O,O.clone())},q.prototype.sqr=function(O){return this.mul(O,O)},q.prototype.sqrt=function(O){if(O.isZero())return O.clone();var w=this.m.andln(3);if(C(w%2===1),w===3){var k=this.m.add(new Y(1)).iushrn(2);return this.pow(O,k)}for(var S=this.m.subn(1),_=0;!S.isZero()&&S.andln(1)===0;)_++,S.iushrn(1);C(!S.isZero());var W=new Y(1).toRed(this),j=W.redNeg(),b=this.m.subn(1).iushrn(1),p=this.m.bitLength();for(p=new Y(2*p*p).toRed(this);this.pow(p,b).cmp(j)!==0;)p.redIAdd(j);for(var s=this.pow(p,S),r=this.pow(O,S.addn(1).iushrn(1)),A1=this.pow(O,S),Q1=_;A1.cmp(W)!==0;){for(var e=A1,t=0;e.cmp(W)!==0;t++)e=e.redSqr();C(t=0;_--){for(var s=w.words[_],r=p-1;r>=0;r--){var A1=s>>r&1;if(W!==S[0]&&(W=this.sqr(W)),A1===0&&j===0){b=0;continue}j<<=1,j|=A1,b++,!(b!==k&&(_!==0||r!==0))&&(W=this.mul(W,S[j]),b=0,j=0)}p=26}return W},q.prototype.convertTo=function(O){var w=O.umod(this.m);return w===O?w.clone():w},q.prototype.convertFrom=function(O){var w=O.clone();return w.red=null,w},Y.mont=function(O){return new P(O)};function P(O){q.call(this,O),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new Y(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}U(P,q),P.prototype.convertTo=function(O){return this.imod(O.ushln(this.shift))},P.prototype.convertFrom=function(O){var w=this.imod(O.mul(this.rinv));return w.red=null,w},P.prototype.imul=function(O,w){if(O.isZero()||w.isZero())return O.words[0]=0,O.length=1,O;var k=O.imul(w),S=k.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),_=k.isub(S).iushrn(this.shift),W=_;return _.cmp(this.m)>=0?W=_.isub(this.m):_.cmpn(0)<0&&(W=_.iadd(this.m)),W._forceRed(this)},P.prototype.mul=function(O,w){if(O.isZero()||w.isZero())return new Y(0)._forceRed(this);var k=O.mul(w),S=k.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),_=k.isub(S).iushrn(this.shift),W=_;return _.cmp(this.m)>=0?W=_.isub(this.m):_.cmpn(0)<0&&(W=_.iadd(this.m)),W._forceRed(this)},P.prototype.invm=function(O){var w=this.imod(O._invmp(this.m).mul(this.r2));return w._forceRed(this)}})(typeof Q>"u"||Q,A)}),nN=l1((A,Q)=>{var J=lN(),K=VK();function C(Z){var X=U(Z),E=X.toRed(J.mont(Z.modulus)).redPow(new J(Z.publicExponent)).fromRed();return{blinder:E,unblinder:X.invm(Z.modulus)}}function U(Z){var X=Z.modulus.byteLength(),E;do E=new J(K(X));while(E.cmp(Z.modulus)>=0||!E.umod(Z.prime1)||!E.umod(Z.prime2));return E}function Y(Z,X){var E=C(X),H=X.modulus.byteLength(),$=new J(Z).mul(E.blinder).umod(X.modulus),I=$.toRed(J.mont(X.prime1)),N=$.toRed(J.mont(X.prime2)),F=X.coefficient,V=X.prime1,D=X.prime2,L=I.redPow(X.exponent1).fromRed(),R=N.redPow(X.exponent2).fromRed(),M=L.isub(R).imul(F).umod(V).imul(D);return R.iadd(M).imul(E.unblinder).umod(X.modulus).toArrayLike(Buffer,"be",H)}Y.getr=U,Q.exports=Y}),k91=l1((A,Q)=>{Q.exports={name:"elliptic",version:"6.5.4",description:"EC cryptography",main:"lib/elliptic.js",files:["lib"],scripts:{lint:"eslint lib test","lint:fix":"npm run lint -- --fix",unit:"istanbul test _mocha --reporter=spec test/index.js",test:"npm run lint && npm run unit",version:"grunt dist && git add dist/"},repository:{type:"git",url:"git@github.com:indutny/elliptic"},keywords:["EC","Elliptic","curve","Cryptography"],author:"Fedor Indutny ",license:"MIT",bugs:{url:"https://github.com/indutny/elliptic/issues"},homepage:"https://github.com/indutny/elliptic",devDependencies:{brfs:"^2.0.2",coveralls:"^3.1.0",eslint:"^7.6.0",grunt:"^1.2.1","grunt-browserify":"^5.3.0","grunt-cli":"^1.3.2","grunt-contrib-connect":"^3.0.0","grunt-contrib-copy":"^1.0.0","grunt-contrib-uglify":"^5.0.0","grunt-mocha-istanbul":"^5.0.2","grunt-saucelabs":"^9.0.1",istanbul:"^0.4.5",mocha:"^8.0.1"},dependencies:{"bn.js":"^4.11.9",brorand:"^1.1.0","hash.js":"^1.0.0","hmac-drbg":"^1.0.1",inherits:"^2.0.4","minimalistic-assert":"^1.0.1","minimalistic-crypto-utils":"^1.0.1"}}}),u3=l1((A,Q)=>{(function(J,K){function C(B,q){if(!B)throw new Error(q||"Assertion failed")}function U(B,q){B.super_=q;var P=function(){};P.prototype=q.prototype,B.prototype=new P,B.prototype.constructor=B}function Y(B,q,P){if(Y.isBN(B))return B;this.negative=0,this.words=null,this.length=0,this.red=null,B!==null&&((q==="le"||q==="be")&&(P=q,q=10),this._init(B||0,q||10,P||"be"))}typeof J=="object"?J.exports=Y:K.BN=Y,Y.BN=Y,Y.wordSize=26;var Z;try{typeof window<"u"&&typeof window.Buffer<"u"?Z=window.Buffer:Z=XQ().Buffer}catch{}Y.isBN=function(B){return B instanceof Y?!0:B!==null&&typeof B=="object"&&B.constructor.wordSize===Y.wordSize&&Array.isArray(B.words)},Y.max=function(B,q){return B.cmp(q)>0?B:q},Y.min=function(B,q){return B.cmp(q)<0?B:q},Y.prototype._init=function(B,q,P){if(typeof B=="number")return this._initNumber(B,q,P);if(typeof B=="object")return this._initArray(B,q,P);q==="hex"&&(q=16),C(q===(q|0)&&q>=2&&q<=36),B=B.toString().replace(/\s+/g,"");var O=0;B[0]==="-"&&(O++,this.negative=1),O=0;O-=3)k=B[O]|B[O-1]<<8|B[O-2]<<16,this.words[w]|=k<>>26-S&67108863,S+=24,S>=26&&(S-=26,w++);else if(P==="le")for(O=0,w=0;O>>26-S&67108863,S+=24,S>=26&&(S-=26,w++);return this.strip()};function X(B,q){var P=B.charCodeAt(q);return P>=65&&P<=70?P-55:P>=97&&P<=102?P-87:P-48&15}function E(B,q,P){var O=X(B,P);return P-1>=q&&(O|=X(B,P-1)<<4),O}Y.prototype._parseHex=function(B,q,P){this.length=Math.ceil((B.length-q)/6),this.words=new Array(this.length);for(var O=0;O=q;O-=2)S=E(B,q,O)<=18?(w-=18,k+=1,this.words[k]|=S>>>26):w+=8;else{var _=B.length-q;for(O=_%2===0?q+1:q;O=18?(w-=18,k+=1,this.words[k]|=S>>>26):w+=8}this.strip()};function H(B,q,P,O){for(var w=0,k=Math.min(B.length,P),S=q;S=49?w+=_-49+10:_>=17?w+=_-17+10:w+=_}return w}Y.prototype._parseBase=function(B,q,P){this.words=[0],this.length=1;for(var O=0,w=1;w<=67108863;w*=q)O++;O--,w=w/q|0;for(var k=B.length-P,S=k%O,_=Math.min(k,k-S)+P,W=0,j=P;j<_;j+=O)W=H(B,j,j+O,q),this.imuln(w),this.words[0]+W<67108864?this.words[0]+=W:this._iaddn(W);if(S!==0){var b=1;for(W=H(B,j,B.length,q),j=0;j1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},Y.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},Y.prototype.inspect=function(){return(this.red?""};var $=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],I=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],N=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];Y.prototype.toString=function(B,q){B=B||10,q=q|0||1;var P;if(B===16||B==="hex"){P="";for(var O=0,w=0,k=0;k>>24-O&16777215,w!==0||k!==this.length-1?P=$[6-_.length]+_+P:P=_+P,O+=2,O>=26&&(O-=26,k--)}for(w!==0&&(P=w.toString(16)+P);P.length%q!==0;)P="0"+P;return this.negative!==0&&(P="-"+P),P}if(B===(B|0)&&B>=2&&B<=36){var W=I[B],j=N[B];P="";var b=this.clone();for(b.negative=0;!b.isZero();){var p=b.modn(j).toString(B);b=b.idivn(j),b.isZero()?P=p+P:P=$[W-p.length]+p+P}for(this.isZero()&&(P="0"+P);P.length%q!==0;)P="0"+P;return this.negative!==0&&(P="-"+P),P}C(!1,"Base should be between 2 and 36")},Y.prototype.toNumber=function(){var B=this.words[0];return this.length===2?B+=this.words[1]*67108864:this.length===3&&this.words[2]===1?B+=4503599627370496+this.words[1]*67108864:this.length>2&&C(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-B:B},Y.prototype.toJSON=function(){return this.toString(16)},Y.prototype.toBuffer=function(B,q){return C(typeof Z<"u"),this.toArrayLike(Z,B,q)},Y.prototype.toArray=function(B,q){return this.toArrayLike(Array,B,q)},Y.prototype.toArrayLike=function(B,q,P){var O=this.byteLength(),w=P||Math.max(1,O);C(O<=w,"byte array longer than desired length"),C(w>0,"Requested array length <= 0"),this.strip();var k=q==="le",S=new B(w),_,W,j=this.clone();if(k){for(W=0;!j.isZero();W++)_=j.andln(255),j.iushrn(8),S[W]=_;for(;W=4096&&(P+=13,q>>>=13),q>=64&&(P+=7,q>>>=7),q>=8&&(P+=4,q>>>=4),q>=2&&(P+=2,q>>>=2),P+q},Y.prototype._zeroBits=function(B){if(B===0)return 26;var q=B,P=0;return(q&8191)===0&&(P+=13,q>>>=13),(q&127)===0&&(P+=7,q>>>=7),(q&15)===0&&(P+=4,q>>>=4),(q&3)===0&&(P+=2,q>>>=2),(q&1)===0&&P++,P},Y.prototype.bitLength=function(){var B=this.words[this.length-1],q=this._countBits(B);return(this.length-1)*26+q};function F(B){for(var q=new Array(B.bitLength()),P=0;P>>w}return q}Y.prototype.zeroBits=function(){if(this.isZero())return 0;for(var B=0,q=0;qB.length?this.clone().ior(B):B.clone().ior(this)},Y.prototype.uor=function(B){return this.length>B.length?this.clone().iuor(B):B.clone().iuor(this)},Y.prototype.iuand=function(B){var q;this.length>B.length?q=B:q=this;for(var P=0;PB.length?this.clone().iand(B):B.clone().iand(this)},Y.prototype.uand=function(B){return this.length>B.length?this.clone().iuand(B):B.clone().iuand(this)},Y.prototype.iuxor=function(B){var q,P;this.length>B.length?(q=this,P=B):(q=B,P=this);for(var O=0;OB.length?this.clone().ixor(B):B.clone().ixor(this)},Y.prototype.uxor=function(B){return this.length>B.length?this.clone().iuxor(B):B.clone().iuxor(this)},Y.prototype.inotn=function(B){C(typeof B=="number"&&B>=0);var q=Math.ceil(B/26)|0,P=B%26;this._expand(q),P>0&&q--;for(var O=0;O0&&(this.words[O]=~this.words[O]&67108863>>26-P),this.strip()},Y.prototype.notn=function(B){return this.clone().inotn(B)},Y.prototype.setn=function(B,q){C(typeof B=="number"&&B>=0);var P=B/26|0,O=B%26;return this._expand(P+1),q?this.words[P]=this.words[P]|1<B.length?(P=this,O=B):(P=B,O=this);for(var w=0,k=0;k>>26;for(;w!==0&&k>>26;if(this.length=P.length,w!==0)this.words[this.length]=w,this.length++;else if(P!==this)for(;kB.length?this.clone().iadd(B):B.clone().iadd(this)},Y.prototype.isub=function(B){if(B.negative!==0){B.negative=0;var q=this.iadd(B);return B.negative=1,q._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(B),this.negative=1,this._normSign();var P=this.cmp(B);if(P===0)return this.negative=0,this.length=1,this.words[0]=0,this;var O,w;P>0?(O=this,w=B):(O=B,w=this);for(var k=0,S=0;S>26,this.words[S]=q&67108863;for(;k!==0&&S>26,this.words[S]=q&67108863;if(k===0&&S>>26,p=W&67108863,s=Math.min(j,q.length-1),r=Math.max(0,j-B.length+1);r<=s;r++){var A1=j-r|0;w=B.words[A1]|0,k=q.words[r]|0,S=w*k+p,b+=S/67108864|0,p=S&67108863}P.words[j]=p|0,W=b|0}return W!==0?P.words[j]=W|0:P.length--,P.strip()}var D=function(B,q,P){var O=B.words,w=q.words,k=P.words,S=0,_,W,j,b=O[0]|0,p=b&8191,s=b>>>13,r=O[1]|0,A1=r&8191,Q1=r>>>13,e=O[2]|0,t=e&8191,U1=e>>>13,O1=O[3]|0,E1=O1&8191,Y1=O1>>>13,i=O[4]|0,c=i&8191,o=i>>>13,C1=O[5]|0,q1=C1&8191,Z1=C1>>>13,j1=O[6]|0,H1=j1&8191,B1=j1>>>13,k1=O[7]|0,D1=k1&8191,G1=k1>>>13,w1=O[8]|0,G=w1&8191,z=w1>>>13,x=O[9]|0,m=x&8191,l=x>>>13,a=w[0]|0,K1=a&8191,F1=a>>>13,R1=w[1]|0,X1=R1&8191,W1=R1>>>13,$1=w[2]|0,N1=$1&8191,_1=$1>>>13,J1=w[3]|0,z1=J1&8191,M1=J1>>>13,L1=w[4]|0,V1=L1&8191,S1=L1>>>13,O0=w[5]|0,h1=O0&8191,b1=O0>>>13,f0=w[6]|0,e1=f0&8191,s1=f0>>>13,o0=w[7]|0,a1=o0&8191,r1=o0>>>13,FA=w[8]|0,K0=FA&8191,J0=FA>>>13,qA=w[9]|0,Q0=qA&8191,A0=qA>>>13;P.negative=B.negative^q.negative,P.length=19,_=Math.imul(p,K1),W=Math.imul(p,F1),W=W+Math.imul(s,K1)|0,j=Math.imul(s,F1);var hA=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(hA>>>26)|0,hA&=67108863,_=Math.imul(A1,K1),W=Math.imul(A1,F1),W=W+Math.imul(Q1,K1)|0,j=Math.imul(Q1,F1),_=_+Math.imul(p,X1)|0,W=W+Math.imul(p,W1)|0,W=W+Math.imul(s,X1)|0,j=j+Math.imul(s,W1)|0;var r0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(r0>>>26)|0,r0&=67108863,_=Math.imul(t,K1),W=Math.imul(t,F1),W=W+Math.imul(U1,K1)|0,j=Math.imul(U1,F1),_=_+Math.imul(A1,X1)|0,W=W+Math.imul(A1,W1)|0,W=W+Math.imul(Q1,X1)|0,j=j+Math.imul(Q1,W1)|0,_=_+Math.imul(p,N1)|0,W=W+Math.imul(p,_1)|0,W=W+Math.imul(s,N1)|0,j=j+Math.imul(s,_1)|0;var EA=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(EA>>>26)|0,EA&=67108863,_=Math.imul(E1,K1),W=Math.imul(E1,F1),W=W+Math.imul(Y1,K1)|0,j=Math.imul(Y1,F1),_=_+Math.imul(t,X1)|0,W=W+Math.imul(t,W1)|0,W=W+Math.imul(U1,X1)|0,j=j+Math.imul(U1,W1)|0,_=_+Math.imul(A1,N1)|0,W=W+Math.imul(A1,_1)|0,W=W+Math.imul(Q1,N1)|0,j=j+Math.imul(Q1,_1)|0,_=_+Math.imul(p,z1)|0,W=W+Math.imul(p,M1)|0,W=W+Math.imul(s,z1)|0,j=j+Math.imul(s,M1)|0;var X2=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(X2>>>26)|0,X2&=67108863,_=Math.imul(c,K1),W=Math.imul(c,F1),W=W+Math.imul(o,K1)|0,j=Math.imul(o,F1),_=_+Math.imul(E1,X1)|0,W=W+Math.imul(E1,W1)|0,W=W+Math.imul(Y1,X1)|0,j=j+Math.imul(Y1,W1)|0,_=_+Math.imul(t,N1)|0,W=W+Math.imul(t,_1)|0,W=W+Math.imul(U1,N1)|0,j=j+Math.imul(U1,_1)|0,_=_+Math.imul(A1,z1)|0,W=W+Math.imul(A1,M1)|0,W=W+Math.imul(Q1,z1)|0,j=j+Math.imul(Q1,M1)|0,_=_+Math.imul(p,V1)|0,W=W+Math.imul(p,S1)|0,W=W+Math.imul(s,V1)|0,j=j+Math.imul(s,S1)|0;var E2=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(E2>>>26)|0,E2&=67108863,_=Math.imul(q1,K1),W=Math.imul(q1,F1),W=W+Math.imul(Z1,K1)|0,j=Math.imul(Z1,F1),_=_+Math.imul(c,X1)|0,W=W+Math.imul(c,W1)|0,W=W+Math.imul(o,X1)|0,j=j+Math.imul(o,W1)|0,_=_+Math.imul(E1,N1)|0,W=W+Math.imul(E1,_1)|0,W=W+Math.imul(Y1,N1)|0,j=j+Math.imul(Y1,_1)|0,_=_+Math.imul(t,z1)|0,W=W+Math.imul(t,M1)|0,W=W+Math.imul(U1,z1)|0,j=j+Math.imul(U1,M1)|0,_=_+Math.imul(A1,V1)|0,W=W+Math.imul(A1,S1)|0,W=W+Math.imul(Q1,V1)|0,j=j+Math.imul(Q1,S1)|0,_=_+Math.imul(p,h1)|0,W=W+Math.imul(p,b1)|0,W=W+Math.imul(s,h1)|0,j=j+Math.imul(s,b1)|0;var T1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(T1>>>26)|0,T1&=67108863,_=Math.imul(H1,K1),W=Math.imul(H1,F1),W=W+Math.imul(B1,K1)|0,j=Math.imul(B1,F1),_=_+Math.imul(q1,X1)|0,W=W+Math.imul(q1,W1)|0,W=W+Math.imul(Z1,X1)|0,j=j+Math.imul(Z1,W1)|0,_=_+Math.imul(c,N1)|0,W=W+Math.imul(c,_1)|0,W=W+Math.imul(o,N1)|0,j=j+Math.imul(o,_1)|0,_=_+Math.imul(E1,z1)|0,W=W+Math.imul(E1,M1)|0,W=W+Math.imul(Y1,z1)|0,j=j+Math.imul(Y1,M1)|0,_=_+Math.imul(t,V1)|0,W=W+Math.imul(t,S1)|0,W=W+Math.imul(U1,V1)|0,j=j+Math.imul(U1,S1)|0,_=_+Math.imul(A1,h1)|0,W=W+Math.imul(A1,b1)|0,W=W+Math.imul(Q1,h1)|0,j=j+Math.imul(Q1,b1)|0,_=_+Math.imul(p,e1)|0,W=W+Math.imul(p,s1)|0,W=W+Math.imul(s,e1)|0,j=j+Math.imul(s,s1)|0;var m1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(m1>>>26)|0,m1&=67108863,_=Math.imul(D1,K1),W=Math.imul(D1,F1),W=W+Math.imul(G1,K1)|0,j=Math.imul(G1,F1),_=_+Math.imul(H1,X1)|0,W=W+Math.imul(H1,W1)|0,W=W+Math.imul(B1,X1)|0,j=j+Math.imul(B1,W1)|0,_=_+Math.imul(q1,N1)|0,W=W+Math.imul(q1,_1)|0,W=W+Math.imul(Z1,N1)|0,j=j+Math.imul(Z1,_1)|0,_=_+Math.imul(c,z1)|0,W=W+Math.imul(c,M1)|0,W=W+Math.imul(o,z1)|0,j=j+Math.imul(o,M1)|0,_=_+Math.imul(E1,V1)|0,W=W+Math.imul(E1,S1)|0,W=W+Math.imul(Y1,V1)|0,j=j+Math.imul(Y1,S1)|0,_=_+Math.imul(t,h1)|0,W=W+Math.imul(t,b1)|0,W=W+Math.imul(U1,h1)|0,j=j+Math.imul(U1,b1)|0,_=_+Math.imul(A1,e1)|0,W=W+Math.imul(A1,s1)|0,W=W+Math.imul(Q1,e1)|0,j=j+Math.imul(Q1,s1)|0,_=_+Math.imul(p,a1)|0,W=W+Math.imul(p,r1)|0,W=W+Math.imul(s,a1)|0,j=j+Math.imul(s,r1)|0;var i1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(i1>>>26)|0,i1&=67108863,_=Math.imul(G,K1),W=Math.imul(G,F1),W=W+Math.imul(z,K1)|0,j=Math.imul(z,F1),_=_+Math.imul(D1,X1)|0,W=W+Math.imul(D1,W1)|0,W=W+Math.imul(G1,X1)|0,j=j+Math.imul(G1,W1)|0,_=_+Math.imul(H1,N1)|0,W=W+Math.imul(H1,_1)|0,W=W+Math.imul(B1,N1)|0,j=j+Math.imul(B1,_1)|0,_=_+Math.imul(q1,z1)|0,W=W+Math.imul(q1,M1)|0,W=W+Math.imul(Z1,z1)|0,j=j+Math.imul(Z1,M1)|0,_=_+Math.imul(c,V1)|0,W=W+Math.imul(c,S1)|0,W=W+Math.imul(o,V1)|0,j=j+Math.imul(o,S1)|0,_=_+Math.imul(E1,h1)|0,W=W+Math.imul(E1,b1)|0,W=W+Math.imul(Y1,h1)|0,j=j+Math.imul(Y1,b1)|0,_=_+Math.imul(t,e1)|0,W=W+Math.imul(t,s1)|0,W=W+Math.imul(U1,e1)|0,j=j+Math.imul(U1,s1)|0,_=_+Math.imul(A1,a1)|0,W=W+Math.imul(A1,r1)|0,W=W+Math.imul(Q1,a1)|0,j=j+Math.imul(Q1,r1)|0,_=_+Math.imul(p,K0)|0,W=W+Math.imul(p,J0)|0,W=W+Math.imul(s,K0)|0,j=j+Math.imul(s,J0)|0;var t1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(t1>>>26)|0,t1&=67108863,_=Math.imul(m,K1),W=Math.imul(m,F1),W=W+Math.imul(l,K1)|0,j=Math.imul(l,F1),_=_+Math.imul(G,X1)|0,W=W+Math.imul(G,W1)|0,W=W+Math.imul(z,X1)|0,j=j+Math.imul(z,W1)|0,_=_+Math.imul(D1,N1)|0,W=W+Math.imul(D1,_1)|0,W=W+Math.imul(G1,N1)|0,j=j+Math.imul(G1,_1)|0,_=_+Math.imul(H1,z1)|0,W=W+Math.imul(H1,M1)|0,W=W+Math.imul(B1,z1)|0,j=j+Math.imul(B1,M1)|0,_=_+Math.imul(q1,V1)|0,W=W+Math.imul(q1,S1)|0,W=W+Math.imul(Z1,V1)|0,j=j+Math.imul(Z1,S1)|0,_=_+Math.imul(c,h1)|0,W=W+Math.imul(c,b1)|0,W=W+Math.imul(o,h1)|0,j=j+Math.imul(o,b1)|0,_=_+Math.imul(E1,e1)|0,W=W+Math.imul(E1,s1)|0,W=W+Math.imul(Y1,e1)|0,j=j+Math.imul(Y1,s1)|0,_=_+Math.imul(t,a1)|0,W=W+Math.imul(t,r1)|0,W=W+Math.imul(U1,a1)|0,j=j+Math.imul(U1,r1)|0,_=_+Math.imul(A1,K0)|0,W=W+Math.imul(A1,J0)|0,W=W+Math.imul(Q1,K0)|0,j=j+Math.imul(Q1,J0)|0,_=_+Math.imul(p,Q0)|0,W=W+Math.imul(p,A0)|0,W=W+Math.imul(s,Q0)|0,j=j+Math.imul(s,A0)|0;var d1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(d1>>>26)|0,d1&=67108863,_=Math.imul(m,X1),W=Math.imul(m,W1),W=W+Math.imul(l,X1)|0,j=Math.imul(l,W1),_=_+Math.imul(G,N1)|0,W=W+Math.imul(G,_1)|0,W=W+Math.imul(z,N1)|0,j=j+Math.imul(z,_1)|0,_=_+Math.imul(D1,z1)|0,W=W+Math.imul(D1,M1)|0,W=W+Math.imul(G1,z1)|0,j=j+Math.imul(G1,M1)|0,_=_+Math.imul(H1,V1)|0,W=W+Math.imul(H1,S1)|0,W=W+Math.imul(B1,V1)|0,j=j+Math.imul(B1,S1)|0,_=_+Math.imul(q1,h1)|0,W=W+Math.imul(q1,b1)|0,W=W+Math.imul(Z1,h1)|0,j=j+Math.imul(Z1,b1)|0,_=_+Math.imul(c,e1)|0,W=W+Math.imul(c,s1)|0,W=W+Math.imul(o,e1)|0,j=j+Math.imul(o,s1)|0,_=_+Math.imul(E1,a1)|0,W=W+Math.imul(E1,r1)|0,W=W+Math.imul(Y1,a1)|0,j=j+Math.imul(Y1,r1)|0,_=_+Math.imul(t,K0)|0,W=W+Math.imul(t,J0)|0,W=W+Math.imul(U1,K0)|0,j=j+Math.imul(U1,J0)|0,_=_+Math.imul(A1,Q0)|0,W=W+Math.imul(A1,A0)|0,W=W+Math.imul(Q1,Q0)|0,j=j+Math.imul(Q1,A0)|0;var H0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(H0>>>26)|0,H0&=67108863,_=Math.imul(m,N1),W=Math.imul(m,_1),W=W+Math.imul(l,N1)|0,j=Math.imul(l,_1),_=_+Math.imul(G,z1)|0,W=W+Math.imul(G,M1)|0,W=W+Math.imul(z,z1)|0,j=j+Math.imul(z,M1)|0,_=_+Math.imul(D1,V1)|0,W=W+Math.imul(D1,S1)|0,W=W+Math.imul(G1,V1)|0,j=j+Math.imul(G1,S1)|0,_=_+Math.imul(H1,h1)|0,W=W+Math.imul(H1,b1)|0,W=W+Math.imul(B1,h1)|0,j=j+Math.imul(B1,b1)|0,_=_+Math.imul(q1,e1)|0,W=W+Math.imul(q1,s1)|0,W=W+Math.imul(Z1,e1)|0,j=j+Math.imul(Z1,s1)|0,_=_+Math.imul(c,a1)|0,W=W+Math.imul(c,r1)|0,W=W+Math.imul(o,a1)|0,j=j+Math.imul(o,r1)|0,_=_+Math.imul(E1,K0)|0,W=W+Math.imul(E1,J0)|0,W=W+Math.imul(Y1,K0)|0,j=j+Math.imul(Y1,J0)|0,_=_+Math.imul(t,Q0)|0,W=W+Math.imul(t,A0)|0,W=W+Math.imul(U1,Q0)|0,j=j+Math.imul(U1,A0)|0;var R0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(R0>>>26)|0,R0&=67108863,_=Math.imul(m,z1),W=Math.imul(m,M1),W=W+Math.imul(l,z1)|0,j=Math.imul(l,M1),_=_+Math.imul(G,V1)|0,W=W+Math.imul(G,S1)|0,W=W+Math.imul(z,V1)|0,j=j+Math.imul(z,S1)|0,_=_+Math.imul(D1,h1)|0,W=W+Math.imul(D1,b1)|0,W=W+Math.imul(G1,h1)|0,j=j+Math.imul(G1,b1)|0,_=_+Math.imul(H1,e1)|0,W=W+Math.imul(H1,s1)|0,W=W+Math.imul(B1,e1)|0,j=j+Math.imul(B1,s1)|0,_=_+Math.imul(q1,a1)|0,W=W+Math.imul(q1,r1)|0,W=W+Math.imul(Z1,a1)|0,j=j+Math.imul(Z1,r1)|0,_=_+Math.imul(c,K0)|0,W=W+Math.imul(c,J0)|0,W=W+Math.imul(o,K0)|0,j=j+Math.imul(o,J0)|0,_=_+Math.imul(E1,Q0)|0,W=W+Math.imul(E1,A0)|0,W=W+Math.imul(Y1,Q0)|0,j=j+Math.imul(Y1,A0)|0;var D0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(D0>>>26)|0,D0&=67108863,_=Math.imul(m,V1),W=Math.imul(m,S1),W=W+Math.imul(l,V1)|0,j=Math.imul(l,S1),_=_+Math.imul(G,h1)|0,W=W+Math.imul(G,b1)|0,W=W+Math.imul(z,h1)|0,j=j+Math.imul(z,b1)|0,_=_+Math.imul(D1,e1)|0,W=W+Math.imul(D1,s1)|0,W=W+Math.imul(G1,e1)|0,j=j+Math.imul(G1,s1)|0,_=_+Math.imul(H1,a1)|0,W=W+Math.imul(H1,r1)|0,W=W+Math.imul(B1,a1)|0,j=j+Math.imul(B1,r1)|0,_=_+Math.imul(q1,K0)|0,W=W+Math.imul(q1,J0)|0,W=W+Math.imul(Z1,K0)|0,j=j+Math.imul(Z1,J0)|0,_=_+Math.imul(c,Q0)|0,W=W+Math.imul(c,A0)|0,W=W+Math.imul(o,Q0)|0,j=j+Math.imul(o,A0)|0;var P0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(P0>>>26)|0,P0&=67108863,_=Math.imul(m,h1),W=Math.imul(m,b1),W=W+Math.imul(l,h1)|0,j=Math.imul(l,b1),_=_+Math.imul(G,e1)|0,W=W+Math.imul(G,s1)|0,W=W+Math.imul(z,e1)|0,j=j+Math.imul(z,s1)|0,_=_+Math.imul(D1,a1)|0,W=W+Math.imul(D1,r1)|0,W=W+Math.imul(G1,a1)|0,j=j+Math.imul(G1,r1)|0,_=_+Math.imul(H1,K0)|0,W=W+Math.imul(H1,J0)|0,W=W+Math.imul(B1,K0)|0,j=j+Math.imul(B1,J0)|0,_=_+Math.imul(q1,Q0)|0,W=W+Math.imul(q1,A0)|0,W=W+Math.imul(Z1,Q0)|0,j=j+Math.imul(Z1,A0)|0;var j0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(j0>>>26)|0,j0&=67108863,_=Math.imul(m,e1),W=Math.imul(m,s1),W=W+Math.imul(l,e1)|0,j=Math.imul(l,s1),_=_+Math.imul(G,a1)|0,W=W+Math.imul(G,r1)|0,W=W+Math.imul(z,a1)|0,j=j+Math.imul(z,r1)|0,_=_+Math.imul(D1,K0)|0,W=W+Math.imul(D1,J0)|0,W=W+Math.imul(G1,K0)|0,j=j+Math.imul(G1,J0)|0,_=_+Math.imul(H1,Q0)|0,W=W+Math.imul(H1,A0)|0,W=W+Math.imul(B1,Q0)|0,j=j+Math.imul(B1,A0)|0;var v0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(v0>>>26)|0,v0&=67108863,_=Math.imul(m,a1),W=Math.imul(m,r1),W=W+Math.imul(l,a1)|0,j=Math.imul(l,r1),_=_+Math.imul(G,K0)|0,W=W+Math.imul(G,J0)|0,W=W+Math.imul(z,K0)|0,j=j+Math.imul(z,J0)|0,_=_+Math.imul(D1,Q0)|0,W=W+Math.imul(D1,A0)|0,W=W+Math.imul(G1,Q0)|0,j=j+Math.imul(G1,A0)|0;var S0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(S0>>>26)|0,S0&=67108863,_=Math.imul(m,K0),W=Math.imul(m,J0),W=W+Math.imul(l,K0)|0,j=Math.imul(l,J0),_=_+Math.imul(G,Q0)|0,W=W+Math.imul(G,A0)|0,W=W+Math.imul(z,Q0)|0,j=j+Math.imul(z,A0)|0;var n0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(n0>>>26)|0,n0&=67108863,_=Math.imul(m,Q0),W=Math.imul(m,A0),W=W+Math.imul(l,Q0)|0,j=Math.imul(l,A0);var i0=(S+_|0)+((W&8191)<<13)|0;return S=(j+(W>>>13)|0)+(i0>>>26)|0,i0&=67108863,k[0]=hA,k[1]=r0,k[2]=EA,k[3]=X2,k[4]=E2,k[5]=T1,k[6]=m1,k[7]=i1,k[8]=t1,k[9]=d1,k[10]=H0,k[11]=R0,k[12]=D0,k[13]=P0,k[14]=j0,k[15]=v0,k[16]=S0,k[17]=n0,k[18]=i0,S!==0&&(k[19]=S,P.length++),P};Math.imul||(D=V);function L(B,q,P){P.negative=q.negative^B.negative,P.length=B.length+q.length;for(var O=0,w=0,k=0;k>>26)|0,w+=S>>>26,S&=67108863}P.words[k]=_,O=S,S=w}return O!==0?P.words[k]=O:P.length--,P.strip()}function R(B,q,P){var O=new M;return O.mulp(B,q,P)}Y.prototype.mulTo=function(B,q){var P,O=this.length+B.length;return this.length===10&&B.length===10?P=D(this,B,q):O<63?P=V(this,B,q):O<1024?P=L(this,B,q):P=R(this,B,q),P};function M(B,q){this.x=B,this.y=q}M.prototype.makeRBT=function(B){for(var q=new Array(B),P=Y.prototype._countBits(B)-1,O=0;O>=1;return O},M.prototype.permute=function(B,q,P,O,w,k){for(var S=0;S>>1)w++;return 1<>>13,P[2*k+1]=w&8191,w=w>>>13;for(k=2*q;k>=26,q+=O/67108864|0,q+=w>>>26,this.words[P]=w&67108863}return q!==0&&(this.words[P]=q,this.length++),this},Y.prototype.muln=function(B){return this.clone().imuln(B)},Y.prototype.sqr=function(){return this.mul(this)},Y.prototype.isqr=function(){return this.imul(this.clone())},Y.prototype.pow=function(B){var q=F(B);if(q.length===0)return new Y(1);for(var P=this,O=0;O=0);var q=B%26,P=(B-q)/26,O=67108863>>>26-q<<26-q,w;if(q!==0){var k=0;for(w=0;w>>26-q}k&&(this.words[w]=k,this.length++)}if(P!==0){for(w=this.length-1;w>=0;w--)this.words[w+P]=this.words[w];for(w=0;w=0);var O;q?O=(q-q%26)/26:O=0;var w=B%26,k=Math.min((B-w)/26,this.length),S=67108863^67108863>>>w<k)for(this.length-=k,W=0;W=0&&(j!==0||W>=O);W--){var b=this.words[W]|0;this.words[W]=j<<26-w|b>>>w,j=b&S}return _&&j!==0&&(_.words[_.length++]=j),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},Y.prototype.ishrn=function(B,q,P){return C(this.negative===0),this.iushrn(B,q,P)},Y.prototype.shln=function(B){return this.clone().ishln(B)},Y.prototype.ushln=function(B){return this.clone().iushln(B)},Y.prototype.shrn=function(B){return this.clone().ishrn(B)},Y.prototype.ushrn=function(B){return this.clone().iushrn(B)},Y.prototype.testn=function(B){C(typeof B=="number"&&B>=0);var q=B%26,P=(B-q)/26,O=1<=0);var q=B%26,P=(B-q)/26;if(C(this.negative===0,"imaskn works only with positive numbers"),this.length<=P)return this;if(q!==0&&P++,this.length=Math.min(P,this.length),q!==0){var O=67108863^67108863>>>q<=67108864;q++)this.words[q]-=67108864,q===this.length-1?this.words[q+1]=1:this.words[q+1]++;return this.length=Math.max(this.length,q+1),this},Y.prototype.isubn=function(B){if(C(typeof B=="number"),C(B<67108864),B<0)return this.iaddn(-B);if(this.negative!==0)return this.negative=0,this.iaddn(B),this.negative=1,this;if(this.words[0]-=B,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var q=0;q>26)-(_/67108864|0),this.words[w+P]=k&67108863}for(;w>26,this.words[w+P]=k&67108863;if(S===0)return this.strip();for(C(S===-1),S=0,w=0;w>26,this.words[w]=k&67108863;return this.negative=1,this.strip()},Y.prototype._wordDiv=function(B,q){var P=this.length-B.length,O=this.clone(),w=B,k=w.words[w.length-1]|0,S=this._countBits(k);P=26-S,P!==0&&(w=w.ushln(P),O.iushln(P),k=w.words[w.length-1]|0);var _=O.length-w.length,W;if(q!=="mod"){W=new Y(null),W.length=_+1,W.words=new Array(W.length);for(var j=0;j=0;p--){var s=(O.words[w.length+p]|0)*67108864+(O.words[w.length+p-1]|0);for(s=Math.min(s/k|0,67108863),O._ishlnsubmul(w,s,p);O.negative!==0;)s--,O.negative=0,O._ishlnsubmul(w,1,p),O.isZero()||(O.negative^=1);W&&(W.words[p]=s)}return W&&W.strip(),O.strip(),q!=="div"&&P!==0&&O.iushrn(P),{div:W||null,mod:O}},Y.prototype.divmod=function(B,q,P){if(C(!B.isZero()),this.isZero())return{div:new Y(0),mod:new Y(0)};var O,w,k;return this.negative!==0&&B.negative===0?(k=this.neg().divmod(B,q),q!=="mod"&&(O=k.div.neg()),q!=="div"&&(w=k.mod.neg(),P&&w.negative!==0&&w.iadd(B)),{div:O,mod:w}):this.negative===0&&B.negative!==0?(k=this.divmod(B.neg(),q),q!=="mod"&&(O=k.div.neg()),{div:O,mod:k.mod}):(this.negative&B.negative)!==0?(k=this.neg().divmod(B.neg(),q),q!=="div"&&(w=k.mod.neg(),P&&w.negative!==0&&w.isub(B)),{div:k.div,mod:w}):B.length>this.length||this.cmp(B)<0?{div:new Y(0),mod:this}:B.length===1?q==="div"?{div:this.divn(B.words[0]),mod:null}:q==="mod"?{div:null,mod:new Y(this.modn(B.words[0]))}:{div:this.divn(B.words[0]),mod:new Y(this.modn(B.words[0]))}:this._wordDiv(B,q)},Y.prototype.div=function(B){return this.divmod(B,"div",!1).div},Y.prototype.mod=function(B){return this.divmod(B,"mod",!1).mod},Y.prototype.umod=function(B){return this.divmod(B,"mod",!0).mod},Y.prototype.divRound=function(B){var q=this.divmod(B);if(q.mod.isZero())return q.div;var P=q.div.negative!==0?q.mod.isub(B):q.mod,O=B.ushrn(1),w=B.andln(1),k=P.cmp(O);return k<0||w===1&&k===0?q.div:q.div.negative!==0?q.div.isubn(1):q.div.iaddn(1)},Y.prototype.modn=function(B){C(B<=67108863);for(var q=67108864%B,P=0,O=this.length-1;O>=0;O--)P=(q*P+(this.words[O]|0))%B;return P},Y.prototype.idivn=function(B){C(B<=67108863);for(var q=0,P=this.length-1;P>=0;P--){var O=(this.words[P]|0)+q*67108864;this.words[P]=O/B|0,q=O%B}return this.strip()},Y.prototype.divn=function(B){return this.clone().idivn(B)},Y.prototype.egcd=function(B){C(B.negative===0),C(!B.isZero());var q=this,P=B.clone();q.negative!==0?q=q.umod(B):q=q.clone();for(var O=new Y(1),w=new Y(0),k=new Y(0),S=new Y(1),_=0;q.isEven()&&P.isEven();)q.iushrn(1),P.iushrn(1),++_;for(var W=P.clone(),j=q.clone();!q.isZero();){for(var b=0,p=1;(q.words[0]&p)===0&&b<26;++b,p<<=1);if(b>0)for(q.iushrn(b);b-- >0;)(O.isOdd()||w.isOdd())&&(O.iadd(W),w.isub(j)),O.iushrn(1),w.iushrn(1);for(var s=0,r=1;(P.words[0]&r)===0&&s<26;++s,r<<=1);if(s>0)for(P.iushrn(s);s-- >0;)(k.isOdd()||S.isOdd())&&(k.iadd(W),S.isub(j)),k.iushrn(1),S.iushrn(1);q.cmp(P)>=0?(q.isub(P),O.isub(k),w.isub(S)):(P.isub(q),k.isub(O),S.isub(w))}return{a:k,b:S,gcd:P.iushln(_)}},Y.prototype._invmp=function(B){C(B.negative===0),C(!B.isZero());var q=this,P=B.clone();q.negative!==0?q=q.umod(B):q=q.clone();for(var O=new Y(1),w=new Y(0),k=P.clone();q.cmpn(1)>0&&P.cmpn(1)>0;){for(var S=0,_=1;(q.words[0]&_)===0&&S<26;++S,_<<=1);if(S>0)for(q.iushrn(S);S-- >0;)O.isOdd()&&O.iadd(k),O.iushrn(1);for(var W=0,j=1;(P.words[0]&j)===0&&W<26;++W,j<<=1);if(W>0)for(P.iushrn(W);W-- >0;)w.isOdd()&&w.iadd(k),w.iushrn(1);q.cmp(P)>=0?(q.isub(P),O.isub(w)):(P.isub(q),w.isub(O))}var b;return q.cmpn(1)===0?b=O:b=w,b.cmpn(0)<0&&b.iadd(B),b},Y.prototype.gcd=function(B){if(this.isZero())return B.abs();if(B.isZero())return this.abs();var q=this.clone(),P=B.clone();q.negative=0,P.negative=0;for(var O=0;q.isEven()&&P.isEven();O++)q.iushrn(1),P.iushrn(1);do{for(;q.isEven();)q.iushrn(1);for(;P.isEven();)P.iushrn(1);var w=q.cmp(P);if(w<0){var k=q;q=P,P=k}else if(w===0||P.cmpn(1)===0)break;q.isub(P)}while(!0);return P.iushln(O)},Y.prototype.invm=function(B){return this.egcd(B).a.umod(B)},Y.prototype.isEven=function(){return(this.words[0]&1)===0},Y.prototype.isOdd=function(){return(this.words[0]&1)===1},Y.prototype.andln=function(B){return this.words[0]&B},Y.prototype.bincn=function(B){C(typeof B=="number");var q=B%26,P=(B-q)/26,O=1<>>26,S&=67108863,this.words[k]=S}return w!==0&&(this.words[k]=w,this.length++),this},Y.prototype.isZero=function(){return this.length===1&&this.words[0]===0},Y.prototype.cmpn=function(B){var q=B<0;if(this.negative!==0&&!q)return-1;if(this.negative===0&&q)return 1;this.strip();var P;if(this.length>1)P=1;else{q&&(B=-B),C(B<=67108863,"Number is too big");var O=this.words[0]|0;P=O===B?0:OB.length)return 1;if(this.length=0;P--){var O=this.words[P]|0,w=B.words[P]|0;if(O!==w){Ow&&(q=1);break}}return q},Y.prototype.gtn=function(B){return this.cmpn(B)===1},Y.prototype.gt=function(B){return this.cmp(B)===1},Y.prototype.gten=function(B){return this.cmpn(B)>=0},Y.prototype.gte=function(B){return this.cmp(B)>=0},Y.prototype.ltn=function(B){return this.cmpn(B)===-1},Y.prototype.lt=function(B){return this.cmp(B)===-1},Y.prototype.lten=function(B){return this.cmpn(B)<=0},Y.prototype.lte=function(B){return this.cmp(B)<=0},Y.prototype.eqn=function(B){return this.cmpn(B)===0},Y.prototype.eq=function(B){return this.cmp(B)===0},Y.red=function(B){return new d(B)},Y.prototype.toRed=function(B){return C(!this.red,"Already a number in reduction context"),C(this.negative===0,"red works only with positives"),B.convertTo(this)._forceRed(B)},Y.prototype.fromRed=function(){return C(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},Y.prototype._forceRed=function(B){return this.red=B,this},Y.prototype.forceRed=function(B){return C(!this.red,"Already a number in reduction context"),this._forceRed(B)},Y.prototype.redAdd=function(B){return C(this.red,"redAdd works only with red numbers"),this.red.add(this,B)},Y.prototype.redIAdd=function(B){return C(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,B)},Y.prototype.redSub=function(B){return C(this.red,"redSub works only with red numbers"),this.red.sub(this,B)},Y.prototype.redISub=function(B){return C(this.red,"redISub works only with red numbers"),this.red.isub(this,B)},Y.prototype.redShl=function(B){return C(this.red,"redShl works only with red numbers"),this.red.shl(this,B)},Y.prototype.redMul=function(B){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.mul(this,B)},Y.prototype.redIMul=function(B){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.imul(this,B)},Y.prototype.redSqr=function(){return C(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},Y.prototype.redISqr=function(){return C(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},Y.prototype.redSqrt=function(){return C(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},Y.prototype.redInvm=function(){return C(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},Y.prototype.redNeg=function(){return C(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},Y.prototype.redPow=function(B){return C(this.red&&!B.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,B)};var T={k256:null,p224:null,p192:null,p25519:null};function h(B,q){this.name=B,this.p=new Y(q,16),this.n=this.p.bitLength(),this.k=new Y(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}h.prototype._tmp=function(){var B=new Y(null);return B.words=new Array(Math.ceil(this.n/13)),B},h.prototype.ireduce=function(B){var q=B,P;do this.split(q,this.tmp),q=this.imulK(q),q=q.iadd(this.tmp),P=q.bitLength();while(P>this.n);var O=P0?q.isub(this.p):q.strip!==void 0?q.strip():q._strip(),q},h.prototype.split=function(B,q){B.iushrn(this.n,0,q)},h.prototype.imulK=function(B){return B.imul(this.k)};function y(){h.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}U(y,h),y.prototype.split=function(B,q){for(var P=4194303,O=Math.min(B.length,9),w=0;w>>22,k=S}k>>>=22,B.words[w-10]=k,k===0&&B.length>10?B.length-=10:B.length-=9},y.prototype.imulK=function(B){B.words[B.length]=0,B.words[B.length+1]=0,B.length+=2;for(var q=0,P=0;P>>=26,B.words[P]=w,q=O}return q!==0&&(B.words[B.length++]=q),B},Y._prime=function(B){if(T[B])return T[B];var q;if(B==="k256")q=new y;else if(B==="p224")q=new g;else if(B==="p192")q=new f;else if(B==="p25519")q=new u;else throw new Error("Unknown prime "+B);return T[B]=q,q};function d(B){if(typeof B=="string"){var q=Y._prime(B);this.m=q.p,this.prime=q}else C(B.gtn(1),"modulus must be greater than 1"),this.m=B,this.prime=null}d.prototype._verify1=function(B){C(B.negative===0,"red works only with positives"),C(B.red,"red works only with red numbers")},d.prototype._verify2=function(B,q){C((B.negative|q.negative)===0,"red works only with positives"),C(B.red&&B.red===q.red,"red works only with red numbers")},d.prototype.imod=function(B){return this.prime?this.prime.ireduce(B)._forceRed(this):B.umod(this.m)._forceRed(this)},d.prototype.neg=function(B){return B.isZero()?B.clone():this.m.sub(B)._forceRed(this)},d.prototype.add=function(B,q){this._verify2(B,q);var P=B.add(q);return P.cmp(this.m)>=0&&P.isub(this.m),P._forceRed(this)},d.prototype.iadd=function(B,q){this._verify2(B,q);var P=B.iadd(q);return P.cmp(this.m)>=0&&P.isub(this.m),P},d.prototype.sub=function(B,q){this._verify2(B,q);var P=B.sub(q);return P.cmpn(0)<0&&P.iadd(this.m),P._forceRed(this)},d.prototype.isub=function(B,q){this._verify2(B,q);var P=B.isub(q);return P.cmpn(0)<0&&P.iadd(this.m),P},d.prototype.shl=function(B,q){return this._verify1(B),this.imod(B.ushln(q))},d.prototype.imul=function(B,q){return this._verify2(B,q),this.imod(B.imul(q))},d.prototype.mul=function(B,q){return this._verify2(B,q),this.imod(B.mul(q))},d.prototype.isqr=function(B){return this.imul(B,B.clone())},d.prototype.sqr=function(B){return this.mul(B,B)},d.prototype.sqrt=function(B){if(B.isZero())return B.clone();var q=this.m.andln(3);if(C(q%2===1),q===3){var P=this.m.add(new Y(1)).iushrn(2);return this.pow(B,P)}for(var O=this.m.subn(1),w=0;!O.isZero()&&O.andln(1)===0;)w++,O.iushrn(1);C(!O.isZero());var k=new Y(1).toRed(this),S=k.redNeg(),_=this.m.subn(1).iushrn(1),W=this.m.bitLength();for(W=new Y(2*W*W).toRed(this);this.pow(W,_).cmp(S)!==0;)W.redIAdd(S);for(var j=this.pow(W,O),b=this.pow(B,O.addn(1).iushrn(1)),p=this.pow(B,O),s=w;p.cmp(k)!==0;){for(var r=p,A1=0;r.cmp(k)!==0;A1++)r=r.redSqr();C(A1=0;w--){for(var j=q.words[w],b=W-1;b>=0;b--){var p=j>>b&1;if(k!==O[0]&&(k=this.sqr(k)),p===0&&S===0){_=0;continue}S<<=1,S|=p,_++,!(_!==P&&(w!==0||b!==0))&&(k=this.mul(k,O[S]),_=0,S=0)}W=26}return k},d.prototype.convertTo=function(B){var q=B.umod(this.m);return q===B?q.clone():q},d.prototype.convertFrom=function(B){var q=B.clone();return q.red=null,q},Y.mont=function(B){return new n(B)};function n(B){d.call(this,B),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new Y(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}U(n,d),n.prototype.convertTo=function(B){return this.imod(B.ushln(this.shift))},n.prototype.convertFrom=function(B){var q=this.imod(B.mul(this.rinv));return q.red=null,q},n.prototype.imul=function(B,q){if(B.isZero()||q.isZero())return B.words[0]=0,B.length=1,B;var P=B.imul(q),O=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=P.isub(O).iushrn(this.shift),k=w;return w.cmp(this.m)>=0?k=w.isub(this.m):w.cmpn(0)<0&&(k=w.iadd(this.m)),k._forceRed(this)},n.prototype.mul=function(B,q){if(B.isZero()||q.isZero())return new Y(0)._forceRed(this);var P=B.mul(q),O=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=P.isub(O).iushrn(this.shift),k=w;return w.cmp(this.m)>=0?k=w.isub(this.m):w.cmpn(0)<0&&(k=w.iadd(this.m)),k._forceRed(this)},n.prototype.invm=function(B){var q=this.imod(B._invmp(this.m).mul(this.r2));return q._forceRed(this)}})(typeof Q>"u"||Q,A)}),Zy=l1((A)=>{var Q=A;function J(U,Y){if(Array.isArray(U))return U.slice();if(!U)return[];var Z=[];if(typeof U!="string"){for(var X=0;X>8,$=E&255;H?Z.push(H,$):Z.push($)}return Z}Q.toArray=J;function K(U){return U.length===1?"0"+U:U}Q.zero2=K;function C(U){for(var Y="",Z=0;Z{var Q=A,J=u3(),K=T9(),C=Zy();Q.assert=K,Q.toArray=C.toArray,Q.zero2=C.zero2,Q.toHex=C.toHex,Q.encode=C.encode;function U(H,$,I){var N=new Array(Math.max(H.bitLength(),I)+1);N.fill(0);for(var F=1<<$+1,V=H.clone(),D=0;D(F>>1)-1?L=(F>>1)-R:L=R,V.isubn(L)):L=0,N[D]=L,V.iushrn(1)}return N}Q.getNAF=U;function Y(H,$){var I=[[],[]];H=H.clone(),$=$.clone();for(var N=0,F=0,V;H.cmpn(-N)>0||$.cmpn(-F)>0;){var D=H.andln(3)+N&3,L=$.andln(3)+F&3;D===3&&(D=-1),L===3&&(L=-1);var R;(D&1)===0?R=0:(V=H.andln(7)+N&7,(V===3||V===5)&&L===2?R=-D:R=D),I[0].push(R);var M;(L&1)===0?M=0:(V=$.andln(7)+F&7,(V===3||V===5)&&D===2?M=-L:M=L),I[1].push(M),2*N===R+1&&(N=1-N),2*F===M+1&&(F=1-F),H.iushrn(1),$.iushrn(1)}return I}Q.getJSF=Y;function Z(H,$,I){var N="_"+$;H.prototype[$]=function(){return this[N]!==void 0?this[N]:this[N]=I.call(this)}}Q.cachedProperty=Z;function X(H){return typeof H=="string"?Q.toArray(H,"hex"):H}Q.parseBytes=X;function E(H){return new J(H,"hex","le")}Q.intFromLE=E}),eE=l1((A,Q)=>{var J=u3(),K=k9(),C=K.getNAF,U=K.getJSF,Y=K.assert;function Z(E,H){this.type=E,this.p=new J(H.p,16),this.red=H.prime?J.red(H.prime):J.mont(this.p),this.zero=new J(0).toRed(this.red),this.one=new J(1).toRed(this.red),this.two=new J(2).toRed(this.red),this.n=H.n&&new J(H.n,16),this.g=H.g&&this.pointFromJSON(H.g,H.gRed),this._wnafT1=new Array(4),this._wnafT2=new Array(4),this._wnafT3=new Array(4),this._wnafT4=new Array(4),this._bitLength=this.n?this.n.bitLength():0;var $=this.n&&this.p.div(this.n);!$||$.cmpn(100)>0?this.redN=null:(this._maxwellTrick=!0,this.redN=this.n.toRed(this.red))}Q.exports=Z,Z.prototype.point=function(){throw new Error("Not implemented")},Z.prototype.validate=function(){throw new Error("Not implemented")},Z.prototype._fixedNafMul=function(E,H){Y(E.precomputed);var $=E._getDoubles(),I=C(H,1,this._bitLength),N=(1<<$.step+1)-($.step%2===0?2:1);N/=3;var F=[],V,D;for(V=0;V=V;L--)D=(D<<1)+I[L];F.push(D)}for(var R=this.jpoint(null,null,null),M=this.jpoint(null,null,null),T=N;T>0;T--){for(V=0;V=0;D--){for(var L=0;D>=0&&F[D]===0;D--)L++;if(D>=0&&L++,V=V.dblp(L),D<0)break;var R=F[D];Y(R!==0),E.type==="affine"?R>0?V=V.mixedAdd(N[R-1>>1]):V=V.mixedAdd(N[-R-1>>1].neg()):R>0?V=V.add(N[R-1>>1]):V=V.add(N[-R-1>>1].neg())}return E.type==="affine"?V.toP():V},Z.prototype._wnafMulAdd=function(E,H,$,I,N){var F=this._wnafT1,V=this._wnafT2,D=this._wnafT3,L=0,R,M,T;for(R=0;R=1;R-=2){var y=R-1,g=R;if(F[y]!==1||F[g]!==1){D[y]=C($[y],F[y],this._bitLength),D[g]=C($[g],F[g],this._bitLength),L=Math.max(D[y].length,L),L=Math.max(D[g].length,L);continue}var f=[H[y],null,null,H[g]];H[y].y.cmp(H[g].y)===0?(f[1]=H[y].add(H[g]),f[2]=H[y].toJ().mixedAdd(H[g].neg())):H[y].y.cmp(H[g].y.redNeg())===0?(f[1]=H[y].toJ().mixedAdd(H[g]),f[2]=H[y].add(H[g].neg())):(f[1]=H[y].toJ().mixedAdd(H[g]),f[2]=H[y].toJ().mixedAdd(H[g].neg()));var u=[-3,-1,-5,-7,0,7,5,1,3],d=U($[y],$[g]);for(L=Math.max(d[0].length,L),D[y]=new Array(L),D[g]=new Array(L),M=0;M=0;R--){for(var O=0;R>=0;){var w=!0;for(M=0;M=0&&O++,q=q.dblp(O),R<0)break;for(M=0;M0?T=V[M][k-1>>1]:k<0&&(T=V[M][-k-1>>1].neg()),T.type==="affine"?q=q.mixedAdd(T):q=q.add(T))}}for(R=0;R=Math.ceil((E.bitLength()+1)/H.step):!1},X.prototype._getDoubles=function(E,H){if(this.precomputed&&this.precomputed.doubles)return this.precomputed.doubles;for(var $=[this],I=this,N=0;N{var J=k9(),K=u3(),C=MA(),U=eE(),Y=J.assert;function Z(H){U.call(this,"short",H),this.a=new K(H.a,16).toRed(this.red),this.b=new K(H.b,16).toRed(this.red),this.tinv=this.two.redInvm(),this.zeroA=this.a.fromRed().cmpn(0)===0,this.threeA=this.a.fromRed().sub(this.p).cmpn(-3)===0,this.endo=this._getEndomorphism(H),this._endoWnafT1=new Array(4),this._endoWnafT2=new Array(4)}C(Z,U),Q.exports=Z,Z.prototype._getEndomorphism=function(H){if(!(!this.zeroA||!this.g||!this.n||this.p.modn(3)!==1)){var $,I;if(H.beta)$=new K(H.beta,16).toRed(this.red);else{var N=this._getEndoRoots(this.p);$=N[0].cmp(N[1])<0?N[0]:N[1],$=$.toRed(this.red)}if(H.lambda)I=new K(H.lambda,16);else{var F=this._getEndoRoots(this.n);this.g.mul(F[0]).x.cmp(this.g.x.redMul($))===0?I=F[0]:(I=F[1],Y(this.g.mul(I).x.cmp(this.g.x.redMul($))===0))}var V;return H.basis?V=H.basis.map(function(D){return{a:new K(D.a,16),b:new K(D.b,16)}}):V=this._getEndoBasis(I),{beta:$,lambda:I,basis:V}}},Z.prototype._getEndoRoots=function(H){var $=H===this.p?this.red:K.mont(H),I=new K(2).toRed($).redInvm(),N=I.redNeg(),F=new K(3).toRed($).redNeg().redSqrt().redMul(I),V=N.redAdd(F).fromRed(),D=N.redSub(F).fromRed();return[V,D]},Z.prototype._getEndoBasis=function(H){for(var $=this.n.ushrn(Math.floor(this.n.bitLength()/2)),I=H,N=this.n.clone(),F=new K(1),V=new K(0),D=new K(0),L=new K(1),R,M,T,h,y,g,f,u=0,d,n;I.cmpn(0)!==0;){var B=N.div(I);d=N.sub(B.mul(I)),n=D.sub(B.mul(F));var q=L.sub(B.mul(V));if(!T&&d.cmp($)<0)R=f.neg(),M=F,T=d.neg(),h=n;else if(T&&++u===2)break;f=d,N=I,I=d,D=F,F=n,L=V,V=q}y=d.neg(),g=n;var P=T.sqr().add(h.sqr()),O=y.sqr().add(g.sqr());return O.cmp(P)>=0&&(y=R,g=M),T.negative&&(T=T.neg(),h=h.neg()),y.negative&&(y=y.neg(),g=g.neg()),[{a:T,b:h},{a:y,b:g}]},Z.prototype._endoSplit=function(H){var $=this.endo.basis,I=$[0],N=$[1],F=N.b.mul(H).divRound(this.n),V=I.b.neg().mul(H).divRound(this.n),D=F.mul(I.a),L=V.mul(N.a),R=F.mul(I.b),M=V.mul(N.b),T=H.sub(D).sub(L),h=R.add(M).neg();return{k1:T,k2:h}},Z.prototype.pointFromX=function(H,$){H=new K(H,16),H.red||(H=H.toRed(this.red));var I=H.redSqr().redMul(H).redIAdd(H.redMul(this.a)).redIAdd(this.b),N=I.redSqrt();if(N.redSqr().redSub(I).cmp(this.zero)!==0)throw new Error("invalid point");var F=N.fromRed().isOdd();return($&&!F||!$&&F)&&(N=N.redNeg()),this.point(H,N)},Z.prototype.validate=function(H){if(H.inf)return!0;var{x:$,y:I}=H,N=this.a.redMul($),F=$.redSqr().redMul($).redIAdd(N).redIAdd(this.b);return I.redSqr().redISub(F).cmpn(0)===0},Z.prototype._endoWnafMulAdd=function(H,$,I){for(var N=this._endoWnafT1,F=this._endoWnafT2,V=0;V":""},X.prototype.isInfinity=function(){return this.inf},X.prototype.add=function(H){if(this.inf)return H;if(H.inf)return this;if(this.eq(H))return this.dbl();if(this.neg().eq(H))return this.curve.point(null,null);if(this.x.cmp(H.x)===0)return this.curve.point(null,null);var $=this.y.redSub(H.y);$.cmpn(0)!==0&&($=$.redMul(this.x.redSub(H.x).redInvm()));var I=$.redSqr().redISub(this.x).redISub(H.x),N=$.redMul(this.x.redSub(I)).redISub(this.y);return this.curve.point(I,N)},X.prototype.dbl=function(){if(this.inf)return this;var H=this.y.redAdd(this.y);if(H.cmpn(0)===0)return this.curve.point(null,null);var $=this.curve.a,I=this.x.redSqr(),N=H.redInvm(),F=I.redAdd(I).redIAdd(I).redIAdd($).redMul(N),V=F.redSqr().redISub(this.x.redAdd(this.x)),D=F.redMul(this.x.redSub(V)).redISub(this.y);return this.curve.point(V,D)},X.prototype.getX=function(){return this.x.fromRed()},X.prototype.getY=function(){return this.y.fromRed()},X.prototype.mul=function(H){return H=new K(H,16),this.isInfinity()?this:this._hasDoubles(H)?this.curve._fixedNafMul(this,H):this.curve.endo?this.curve._endoWnafMulAdd([this],[H]):this.curve._wnafMul(this,H)},X.prototype.mulAdd=function(H,$,I){var N=[this,$],F=[H,I];return this.curve.endo?this.curve._endoWnafMulAdd(N,F):this.curve._wnafMulAdd(1,N,F,2)},X.prototype.jmulAdd=function(H,$,I){var N=[this,$],F=[H,I];return this.curve.endo?this.curve._endoWnafMulAdd(N,F,!0):this.curve._wnafMulAdd(1,N,F,2,!0)},X.prototype.eq=function(H){return this===H||this.inf===H.inf&&(this.inf||this.x.cmp(H.x)===0&&this.y.cmp(H.y)===0)},X.prototype.neg=function(H){if(this.inf)return this;var $=this.curve.point(this.x,this.y.redNeg());if(H&&this.precomputed){var I=this.precomputed,N=function(F){return F.neg()};$.precomputed={naf:I.naf&&{wnd:I.naf.wnd,points:I.naf.points.map(N)},doubles:I.doubles&&{step:I.doubles.step,points:I.doubles.points.map(N)}}}return $},X.prototype.toJ=function(){if(this.inf)return this.curve.jpoint(null,null,null);var H=this.curve.jpoint(this.x,this.y,this.curve.one);return H};function E(H,$,I,N){U.BasePoint.call(this,H,"jacobian"),$===null&&I===null&&N===null?(this.x=this.curve.one,this.y=this.curve.one,this.z=new K(0)):(this.x=new K($,16),this.y=new K(I,16),this.z=new K(N,16)),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.zOne=this.z===this.curve.one}C(E,U.BasePoint),Z.prototype.jpoint=function(H,$,I){return new E(this,H,$,I)},E.prototype.toP=function(){if(this.isInfinity())return this.curve.point(null,null);var H=this.z.redInvm(),$=H.redSqr(),I=this.x.redMul($),N=this.y.redMul($).redMul(H);return this.curve.point(I,N)},E.prototype.neg=function(){return this.curve.jpoint(this.x,this.y.redNeg(),this.z)},E.prototype.add=function(H){if(this.isInfinity())return H;if(H.isInfinity())return this;var $=H.z.redSqr(),I=this.z.redSqr(),N=this.x.redMul($),F=H.x.redMul(I),V=this.y.redMul($.redMul(H.z)),D=H.y.redMul(I.redMul(this.z)),L=N.redSub(F),R=V.redSub(D);if(L.cmpn(0)===0)return R.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var M=L.redSqr(),T=M.redMul(L),h=N.redMul(M),y=R.redSqr().redIAdd(T).redISub(h).redISub(h),g=R.redMul(h.redISub(y)).redISub(V.redMul(T)),f=this.z.redMul(H.z).redMul(L);return this.curve.jpoint(y,g,f)},E.prototype.mixedAdd=function(H){if(this.isInfinity())return H.toJ();if(H.isInfinity())return this;var $=this.z.redSqr(),I=this.x,N=H.x.redMul($),F=this.y,V=H.y.redMul($).redMul(this.z),D=I.redSub(N),L=F.redSub(V);if(D.cmpn(0)===0)return L.cmpn(0)!==0?this.curve.jpoint(null,null,null):this.dbl();var R=D.redSqr(),M=R.redMul(D),T=I.redMul(R),h=L.redSqr().redIAdd(M).redISub(T).redISub(T),y=L.redMul(T.redISub(h)).redISub(F.redMul(M)),g=this.z.redMul(D);return this.curve.jpoint(h,y,g)},E.prototype.dblp=function(H){if(H===0)return this;if(this.isInfinity())return this;if(!H)return this.dbl();var $;if(this.curve.zeroA||this.curve.threeA){var I=this;for($=0;$=0)return!1;if(I.redIAdd(F),this.x.cmp(I)===0)return!0}},E.prototype.inspect=function(){return this.isInfinity()?"":""},E.prototype.isInfinity=function(){return this.z.cmpn(0)===0}}),j91=l1((A,Q)=>{var J=u3(),K=MA(),C=eE(),U=k9();function Y(X){C.call(this,"mont",X),this.a=new J(X.a,16).toRed(this.red),this.b=new J(X.b,16).toRed(this.red),this.i4=new J(4).toRed(this.red).redInvm(),this.two=new J(2).toRed(this.red),this.a24=this.i4.redMul(this.a.redAdd(this.two))}K(Y,C),Q.exports=Y,Y.prototype.validate=function(X){var E=X.normalize().x,H=E.redSqr(),$=H.redMul(E).redAdd(H.redMul(this.a)).redAdd(E),I=$.redSqrt();return I.redSqr().cmp($)===0};function Z(X,E,H){C.BasePoint.call(this,X,"projective"),E===null&&H===null?(this.x=this.curve.one,this.z=this.curve.zero):(this.x=new J(E,16),this.z=new J(H,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)))}K(Z,C.BasePoint),Y.prototype.decodePoint=function(X,E){return this.point(U.toArray(X,E),1)},Y.prototype.point=function(X,E){return new Z(this,X,E)},Y.prototype.pointFromJSON=function(X){return Z.fromJSON(this,X)},Z.prototype.precompute=function(){},Z.prototype._encode=function(){return this.getX().toArray("be",this.curve.p.byteLength())},Z.fromJSON=function(X,E){return new Z(X,E[0],E[1]||X.one)},Z.prototype.inspect=function(){return this.isInfinity()?"":""},Z.prototype.isInfinity=function(){return this.z.cmpn(0)===0},Z.prototype.dbl=function(){var X=this.x.redAdd(this.z),E=X.redSqr(),H=this.x.redSub(this.z),$=H.redSqr(),I=E.redSub($),N=E.redMul($),F=I.redMul($.redAdd(this.curve.a24.redMul(I)));return this.curve.point(N,F)},Z.prototype.add=function(){throw new Error("Not supported on Montgomery curve")},Z.prototype.diffAdd=function(X,E){var H=this.x.redAdd(this.z),$=this.x.redSub(this.z),I=X.x.redAdd(X.z),N=X.x.redSub(X.z),F=N.redMul(H),V=I.redMul($),D=E.z.redMul(F.redAdd(V).redSqr()),L=E.x.redMul(F.redISub(V).redSqr());return this.curve.point(D,L)},Z.prototype.mul=function(X){for(var E=X.clone(),H=this,$=this.curve.point(null,null),I=this,N=[];E.cmpn(0)!==0;E.iushrn(1))N.push(E.andln(1));for(var F=N.length-1;F>=0;F--)N[F]===0?(H=H.diffAdd($,I),$=$.dbl()):($=H.diffAdd($,I),H=H.dbl());return $},Z.prototype.mulAdd=function(){throw new Error("Not supported on Montgomery curve")},Z.prototype.jumlAdd=function(){throw new Error("Not supported on Montgomery curve")},Z.prototype.eq=function(X){return this.getX().cmp(X.getX())===0},Z.prototype.normalize=function(){return this.x=this.x.redMul(this.z.redInvm()),this.z=this.curve.one,this},Z.prototype.getX=function(){return this.normalize(),this.x.fromRed()}}),v91=l1((A,Q)=>{var J=k9(),K=u3(),C=MA(),U=eE(),Y=J.assert;function Z(E){this.twisted=(E.a|0)!==1,this.mOneA=this.twisted&&(E.a|0)===-1,this.extended=this.mOneA,U.call(this,"edwards",E),this.a=new K(E.a,16).umod(this.red.m),this.a=this.a.toRed(this.red),this.c=new K(E.c,16).toRed(this.red),this.c2=this.c.redSqr(),this.d=new K(E.d,16).toRed(this.red),this.dd=this.d.redAdd(this.d),Y(!this.twisted||this.c.fromRed().cmpn(1)===0),this.oneC=(E.c|0)===1}C(Z,U),Q.exports=Z,Z.prototype._mulA=function(E){return this.mOneA?E.redNeg():this.a.redMul(E)},Z.prototype._mulC=function(E){return this.oneC?E:this.c.redMul(E)},Z.prototype.jpoint=function(E,H,$,I){return this.point(E,H,$,I)},Z.prototype.pointFromX=function(E,H){E=new K(E,16),E.red||(E=E.toRed(this.red));var $=E.redSqr(),I=this.c2.redSub(this.a.redMul($)),N=this.one.redSub(this.c2.redMul(this.d).redMul($)),F=I.redMul(N.redInvm()),V=F.redSqrt();if(V.redSqr().redSub(F).cmp(this.zero)!==0)throw new Error("invalid point");var D=V.fromRed().isOdd();return(H&&!D||!H&&D)&&(V=V.redNeg()),this.point(E,V)},Z.prototype.pointFromY=function(E,H){E=new K(E,16),E.red||(E=E.toRed(this.red));var $=E.redSqr(),I=$.redSub(this.c2),N=$.redMul(this.d).redMul(this.c2).redSub(this.a),F=I.redMul(N.redInvm());if(F.cmp(this.zero)===0){if(H)throw new Error("invalid point");return this.point(this.zero,E)}var V=F.redSqrt();if(V.redSqr().redSub(F).cmp(this.zero)!==0)throw new Error("invalid point");return V.fromRed().isOdd()!==H&&(V=V.redNeg()),this.point(V,E)},Z.prototype.validate=function(E){if(E.isInfinity())return!0;E.normalize();var H=E.x.redSqr(),$=E.y.redSqr(),I=H.redMul(this.a).redAdd($),N=this.c2.redMul(this.one.redAdd(this.d.redMul(H).redMul($)));return I.cmp(N)===0};function X(E,H,$,I,N){U.BasePoint.call(this,E,"projective"),H===null&&$===null&&I===null?(this.x=this.curve.zero,this.y=this.curve.one,this.z=this.curve.one,this.t=this.curve.zero,this.zOne=!0):(this.x=new K(H,16),this.y=new K($,16),this.z=I?new K(I,16):this.curve.one,this.t=N&&new K(N,16),this.x.red||(this.x=this.x.toRed(this.curve.red)),this.y.red||(this.y=this.y.toRed(this.curve.red)),this.z.red||(this.z=this.z.toRed(this.curve.red)),this.t&&!this.t.red&&(this.t=this.t.toRed(this.curve.red)),this.zOne=this.z===this.curve.one,this.curve.extended&&!this.t&&(this.t=this.x.redMul(this.y),this.zOne||(this.t=this.t.redMul(this.z.redInvm()))))}C(X,U.BasePoint),Z.prototype.pointFromJSON=function(E){return X.fromJSON(this,E)},Z.prototype.point=function(E,H,$,I){return new X(this,E,H,$,I)},X.fromJSON=function(E,H){return new X(E,H[0],H[1],H[2])},X.prototype.inspect=function(){return this.isInfinity()?"":""},X.prototype.isInfinity=function(){return this.x.cmpn(0)===0&&(this.y.cmp(this.z)===0||this.zOne&&this.y.cmp(this.curve.c)===0)},X.prototype._extDbl=function(){var E=this.x.redSqr(),H=this.y.redSqr(),$=this.z.redSqr();$=$.redIAdd($);var I=this.curve._mulA(E),N=this.x.redAdd(this.y).redSqr().redISub(E).redISub(H),F=I.redAdd(H),V=F.redSub($),D=I.redSub(H),L=N.redMul(V),R=F.redMul(D),M=N.redMul(D),T=V.redMul(F);return this.curve.point(L,R,T,M)},X.prototype._projDbl=function(){var E=this.x.redAdd(this.y).redSqr(),H=this.x.redSqr(),$=this.y.redSqr(),I,N,F,V,D,L;if(this.curve.twisted){V=this.curve._mulA(H);var R=V.redAdd($);this.zOne?(I=E.redSub(H).redSub($).redMul(R.redSub(this.curve.two)),N=R.redMul(V.redSub($)),F=R.redSqr().redSub(R).redSub(R)):(D=this.z.redSqr(),L=R.redSub(D).redISub(D),I=E.redSub(H).redISub($).redMul(L),N=R.redMul(V.redSub($)),F=R.redMul(L))}else V=H.redAdd($),D=this.curve._mulC(this.z).redSqr(),L=V.redSub(D).redSub(D),I=this.curve._mulC(E.redISub(V)).redMul(L),N=this.curve._mulC(V).redMul(H.redISub($)),F=V.redMul(L);return this.curve.point(I,N,F)},X.prototype.dbl=function(){return this.isInfinity()?this:this.curve.extended?this._extDbl():this._projDbl()},X.prototype._extAdd=function(E){var H=this.y.redSub(this.x).redMul(E.y.redSub(E.x)),$=this.y.redAdd(this.x).redMul(E.y.redAdd(E.x)),I=this.t.redMul(this.curve.dd).redMul(E.t),N=this.z.redMul(E.z.redAdd(E.z)),F=$.redSub(H),V=N.redSub(I),D=N.redAdd(I),L=$.redAdd(H),R=F.redMul(V),M=D.redMul(L),T=F.redMul(L),h=V.redMul(D);return this.curve.point(R,M,h,T)},X.prototype._projAdd=function(E){var H=this.z.redMul(E.z),$=H.redSqr(),I=this.x.redMul(E.x),N=this.y.redMul(E.y),F=this.curve.d.redMul(I).redMul(N),V=$.redSub(F),D=$.redAdd(F),L=this.x.redAdd(this.y).redMul(E.x.redAdd(E.y)).redISub(I).redISub(N),R=H.redMul(V).redMul(L),M,T;return this.curve.twisted?(M=H.redMul(D).redMul(N.redSub(this.curve._mulA(I))),T=V.redMul(D)):(M=H.redMul(D).redMul(N.redSub(I)),T=this.curve._mulC(V).redMul(D)),this.curve.point(R,M,T)},X.prototype.add=function(E){return this.isInfinity()?E:E.isInfinity()?this:this.curve.extended?this._extAdd(E):this._projAdd(E)},X.prototype.mul=function(E){return this._hasDoubles(E)?this.curve._fixedNafMul(this,E):this.curve._wnafMul(this,E)},X.prototype.mulAdd=function(E,H,$){return this.curve._wnafMulAdd(1,[this,H],[E,$],2,!1)},X.prototype.jmulAdd=function(E,H,$){return this.curve._wnafMulAdd(1,[this,H],[E,$],2,!0)},X.prototype.normalize=function(){if(this.zOne)return this;var E=this.z.redInvm();return this.x=this.x.redMul(E),this.y=this.y.redMul(E),this.t&&(this.t=this.t.redMul(E)),this.z=this.curve.one,this.zOne=!0,this},X.prototype.neg=function(){return this.curve.point(this.x.redNeg(),this.y,this.z,this.t&&this.t.redNeg())},X.prototype.getX=function(){return this.normalize(),this.x.fromRed()},X.prototype.getY=function(){return this.normalize(),this.y.fromRed()},X.prototype.eq=function(E){return this===E||this.getX().cmp(E.getX())===0&&this.getY().cmp(E.getY())===0},X.prototype.eqXToP=function(E){var H=E.toRed(this.curve.red).redMul(this.z);if(this.x.cmp(H)===0)return!0;for(var $=E.clone(),I=this.curve.redN.redMul(this.z);;){if($.iadd(this.curve.n),$.cmp(this.curve.p)>=0)return!1;if(H.redIAdd(I),this.x.cmp(H)===0)return!0}},X.prototype.toP=X.prototype.normalize,X.prototype.mixedAdd=X.prototype.add}),By=l1((A)=>{var Q=A;Q.base=eE(),Q.short=S91(),Q.mont=j91(),Q.edwards=v91()}),d5=l1((A)=>{var Q=T9(),J=MA();A.inherits=J;function K(q,P){return(q.charCodeAt(P)&64512)!==55296||P<0||P+1>=q.length?!1:(q.charCodeAt(P+1)&64512)===56320}function C(q,P){if(Array.isArray(q))return q.slice();if(!q)return[];var O=[];if(typeof q=="string")if(P){if(P==="hex")for(q=q.replace(/[^a-z0-9]+/ig,""),q.length%2!==0&&(q="0"+q),k=0;k>6|192,O[w++]=S&63|128):K(q,k)?(S=65536+((S&1023)<<10)+(q.charCodeAt(++k)&1023),O[w++]=S>>18|240,O[w++]=S>>12&63|128,O[w++]=S>>6&63|128,O[w++]=S&63|128):(O[w++]=S>>12|224,O[w++]=S>>6&63|128,O[w++]=S&63|128)}else for(k=0;k>>24|q>>>8&65280|q<<8&16711680|(q&255)<<24;return P>>>0}A.htonl=Y;function Z(q,P){for(var O="",w=0;w>>0}return S}A.join32=H;function $(q,P){for(var O=new Array(q.length*4),w=0,k=0;w>>24,O[k+1]=S>>>16&255,O[k+2]=S>>>8&255,O[k+3]=S&255):(O[k+3]=S>>>24,O[k+2]=S>>>16&255,O[k+1]=S>>>8&255,O[k]=S&255)}return O}A.split32=$;function I(q,P){return q>>>P|q<<32-P}A.rotr32=I;function N(q,P){return q<>>32-P}A.rotl32=N;function F(q,P){return q+P>>>0}A.sum32=F;function V(q,P,O){return q+P+O>>>0}A.sum32_3=V;function D(q,P,O,w){return q+P+O+w>>>0}A.sum32_4=D;function L(q,P,O,w,k){return q+P+O+w+k>>>0}A.sum32_5=L;function R(q,P,O,w){var k=q[P],S=q[P+1],_=w+S>>>0,W=(_>>0,q[P+1]=_}A.sum64=R;function M(q,P,O,w){var k=P+w>>>0,S=(k>>0}A.sum64_hi=M;function T(q,P,O,w){var k=P+w;return k>>>0}A.sum64_lo=T;function h(q,P,O,w,k,S,_,W){var j=0,b=P;b=b+w>>>0,j+=b>>0,j+=b>>0,j+=b>>0}A.sum64_4_hi=h;function y(q,P,O,w,k,S,_,W){var j=P+w+S+W;return j>>>0}A.sum64_4_lo=y;function g(q,P,O,w,k,S,_,W,j,b){var p=0,s=P;s=s+w>>>0,p+=s>>0,p+=s>>0,p+=s>>0,p+=s>>0}A.sum64_5_hi=g;function f(q,P,O,w,k,S,_,W,j,b){var p=P+w+S+W+b;return p>>>0}A.sum64_5_lo=f;function u(q,P,O){var w=P<<32-O|q>>>O;return w>>>0}A.rotr64_hi=u;function d(q,P,O){var w=q<<32-O|P>>>O;return w>>>0}A.rotr64_lo=d;function n(q,P,O){return q>>>O}A.shr64_hi=n;function B(q,P,O){var w=q<<32-O|P>>>O;return w>>>0}A.shr64_lo=B}),FU=l1((A)=>{var Q=d5(),J=T9();function K(){this.pending=null,this.pendingTotal=0,this.blockSize=this.constructor.blockSize,this.outSize=this.constructor.outSize,this.hmacStrength=this.constructor.hmacStrength,this.padLength=this.constructor.padLength/8,this.endian="big",this._delta8=this.blockSize/8,this._delta32=this.blockSize/32}A.BlockHash=K,K.prototype.update=function(C,U){if(C=Q.toArray(C,U),this.pending?this.pending=this.pending.concat(C):this.pending=C,this.pendingTotal+=C.length,this.pending.length>=this._delta8){C=this.pending;var Y=C.length%this._delta8;this.pending=C.slice(C.length-Y,C.length),this.pending.length===0&&(this.pending=null),C=Q.join32(C,0,C.length-Y,this.endian);for(var Z=0;Z>>24&255,Z[X++]=C>>>16&255,Z[X++]=C>>>8&255,Z[X++]=C&255}else for(Z[X++]=C&255,Z[X++]=C>>>8&255,Z[X++]=C>>>16&255,Z[X++]=C>>>24&255,Z[X++]=0,Z[X++]=0,Z[X++]=0,Z[X++]=0,E=8;E{var Q=d5(),J=Q.rotr32;function K($,I,N,F){if($===0)return C(I,N,F);if($===1||$===3)return Y(I,N,F);if($===2)return U(I,N,F)}A.ft_1=K;function C($,I,N){return $&I^~$&N}A.ch32=C;function U($,I,N){return $&I^$&N^I&N}A.maj32=U;function Y($,I,N){return $^I^N}A.p32=Y;function Z($){return J($,2)^J($,13)^J($,22)}A.s0_256=Z;function X($){return J($,6)^J($,11)^J($,25)}A.s1_256=X;function E($){return J($,7)^J($,18)^$>>>3}A.g0_256=E;function H($){return J($,17)^J($,19)^$>>>10}A.g1_256=H}),x91=l1((A,Q)=>{var J=d5(),K=FU(),C=Xy(),U=J.rotl32,Y=J.sum32,Z=J.sum32_5,X=C.ft_1,E=K.BlockHash,H=[1518500249,1859775393,2400959708,3395469782];function $(){if(!(this instanceof $))return new $;E.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.W=new Array(80)}J.inherits($,E),Q.exports=$,$.blockSize=512,$.outSize=160,$.hmacStrength=80,$.padLength=64,$.prototype._update=function(I,N){for(var F=this.W,V=0;V<16;V++)F[V]=I[N+V];for(;V{var J=d5(),K=FU(),C=Xy(),U=T9(),Y=J.sum32,Z=J.sum32_4,X=J.sum32_5,E=C.ch32,H=C.maj32,$=C.s0_256,I=C.s1_256,N=C.g0_256,F=C.g1_256,V=K.BlockHash,D=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function L(){if(!(this instanceof L))return new L;V.call(this),this.h=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],this.k=D,this.W=new Array(64)}J.inherits(L,V),Q.exports=L,L.blockSize=512,L.outSize=256,L.hmacStrength=192,L.padLength=64,L.prototype._update=function(R,M){for(var T=this.W,h=0;h<16;h++)T[h]=R[M+h];for(;h{var J=d5(),K=Ey();function C(){if(!(this instanceof C))return new C;K.call(this),this.h=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]}J.inherits(C,K),Q.exports=C,C.blockSize=512,C.outSize=224,C.hmacStrength=192,C.padLength=64,C.prototype._digest=function(U){return U==="hex"?J.toHex32(this.h.slice(0,7),"big"):J.split32(this.h.slice(0,7),"big")}}),$y=l1((A,Q)=>{var J=d5(),K=FU(),C=T9(),U=J.rotr64_hi,Y=J.rotr64_lo,Z=J.shr64_hi,X=J.shr64_lo,E=J.sum64,H=J.sum64_hi,$=J.sum64_lo,I=J.sum64_4_hi,N=J.sum64_4_lo,F=J.sum64_5_hi,V=J.sum64_5_lo,D=K.BlockHash,L=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function R(){if(!(this instanceof R))return new R;D.call(this),this.h=[1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209],this.k=L,this.W=new Array(160)}J.inherits(R,D),Q.exports=R,R.blockSize=1024,R.outSize=512,R.hmacStrength=192,R.padLength=128,R.prototype._prepareBlock=function(O,w){for(var k=this.W,S=0;S<32;S++)k[S]=O[w+S];for(;S{var J=d5(),K=$y();function C(){if(!(this instanceof C))return new C;K.call(this),this.h=[3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]}J.inherits(C,K),Q.exports=C,C.blockSize=1024,C.outSize=384,C.hmacStrength=192,C.padLength=128,C.prototype._digest=function(U){return U==="hex"?J.toHex32(this.h.slice(0,12),"big"):J.split32(this.h.slice(0,12),"big")}}),g91=l1((A)=>{A.sha1=x91(),A.sha224=y91(),A.sha256=Ey(),A.sha384=h91(),A.sha512=$y()}),b91=l1((A)=>{var Q=d5(),J=FU(),K=Q.rotl32,C=Q.sum32,U=Q.sum32_3,Y=Q.sum32_4,Z=J.BlockHash;function X(){if(!(this instanceof X))return new X;Z.call(this),this.h=[1732584193,4023233417,2562383102,271733878,3285377520],this.endian="little"}Q.inherits(X,Z),A.ripemd160=X,X.blockSize=512,X.outSize=160,X.hmacStrength=192,X.padLength=64,X.prototype._update=function(D,L){for(var R=this.h[0],M=this.h[1],T=this.h[2],h=this.h[3],y=this.h[4],g=R,f=M,u=T,d=h,n=y,B=0;B<80;B++){var q=C(K(Y(R,E(B,M,T,h),D[I[B]+L],H(B)),F[B]),y);R=y,y=h,h=K(T,10),T=M,M=q,q=C(K(Y(g,E(79-B,f,u,d),D[N[B]+L],$(B)),V[B]),n),g=n,n=d,d=K(u,10),u=f,f=q}q=U(this.h[1],T,d),this.h[1]=U(this.h[2],h,n),this.h[2]=U(this.h[3],y,g),this.h[3]=U(this.h[4],R,f),this.h[4]=U(this.h[0],M,u),this.h[0]=q},X.prototype._digest=function(D){return D==="hex"?Q.toHex32(this.h,"little"):Q.split32(this.h,"little")};function E(D,L,R,M){return D<=15?L^R^M:D<=31?L&R|~L&M:D<=47?(L|~R)^M:D<=63?L&M|R&~M:L^(R|~M)}function H(D){return D<=15?0:D<=31?1518500249:D<=47?1859775393:D<=63?2400959708:2840853838}function $(D){return D<=15?1352829926:D<=31?1548603684:D<=47?1836072691:D<=63?2053994217:0}var I=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],N=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],F=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],V=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]}),f91=l1((A,Q)=>{var J=d5(),K=T9();function C(U,Y,Z){if(!(this instanceof C))return new C(U,Y,Z);this.Hash=U,this.blockSize=U.blockSize/8,this.outSize=U.outSize/8,this.inner=null,this.outer=null,this._init(J.toArray(Y,Z))}Q.exports=C,C.prototype._init=function(U){U.length>this.blockSize&&(U=new this.Hash().update(U).digest()),K(U.length<=this.blockSize);for(var Y=U.length;Y{var Q=A;Q.utils=d5(),Q.common=FU(),Q.sha=g91(),Q.ripemd=b91(),Q.hmac=f91(),Q.sha1=Q.sha.sha1,Q.sha256=Q.sha.sha256,Q.sha224=Q.sha.sha224,Q.sha384=Q.sha.sha384,Q.sha512=Q.sha.sha512,Q.ripemd160=Q.ripemd.ripemd160}),p91=l1((A,Q)=>{Q.exports={doubles:{step:4,points:[["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a","f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"],["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508","11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"],["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739","d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"],["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640","4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"],["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c","4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"],["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda","96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"],["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa","5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"],["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0","cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"],["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d","9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"],["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d","e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"],["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1","9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"],["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0","5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"],["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047","10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"],["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862","283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"],["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7","7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"],["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd","56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"],["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83","7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"],["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a","53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"],["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8","bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"],["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d","4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"],["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725","7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"],["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754","4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"],["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c","17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"],["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6","6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"],["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39","c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"],["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891","893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"],["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b","febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"],["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03","2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"],["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d","eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"],["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070","7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"],["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4","e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"],["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da","662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"],["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11","1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"],["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e","efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"],["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41","2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"],["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef","67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"],["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8","db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"],["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d","648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"],["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96","35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"],["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd","ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"],["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5","9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"],["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266","40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"],["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71","34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"],["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac","c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"],["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751","1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"],["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e","493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"],["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241","c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"],["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3","be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"],["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f","4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"],["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19","aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"],["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be","b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"],["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9","6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"],["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2","8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"],["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13","7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"],["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c","ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"],["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba","2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"],["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151","e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"],["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073","d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"],["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458","38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"],["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b","69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"],["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366","d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"],["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa","40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"],["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0","620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"],["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787","7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"],["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e","ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]]},naf:{wnd:7,points:[["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9","388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"],["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4","d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"],["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"],["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe","cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"],["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"],["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8","ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"],["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e","581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"],["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34","4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"],["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c","85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"],["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5","321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"],["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f","2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"],["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714","73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"],["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729","a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"],["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db","2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"],["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4","e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"],["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5","b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"],["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479","2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"],["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d","80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"],["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f","1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"],["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb","d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"],["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9","eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"],["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963","758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"],["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74","958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"],["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530","e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"],["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b","5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"],["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247","cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"],["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1","cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"],["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120","4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"],["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435","91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"],["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18","673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"],["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8","59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"],["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb","3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"],["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f","55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"],["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143","efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"],["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba","e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"],["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45","f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"],["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a","744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"],["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e","c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"],["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8","e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"],["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c","30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"],["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519","e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"],["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab","100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"],["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca","ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"],["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf","8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"],["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610","68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"],["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4","f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"],["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c","d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"],["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940","edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"],["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980","a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"],["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3","66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"],["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf","9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"],["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63","4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"],["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448","fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"],["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf","5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"],["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5","8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"],["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6","8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"],["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5","5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"],["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99","f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"],["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51","f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"],["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5","42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"],["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5","204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"],["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997","4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"],["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881","73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"],["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5","39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"],["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66","d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"],["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726","ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"],["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede","6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"],["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94","60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"],["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31","3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"],["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51","b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"],["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252","ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"],["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5","cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"],["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b","6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"],["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4","322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"],["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f","6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"],["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889","2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"],["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246","b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"],["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984","998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"],["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a","b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"],["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030","bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"],["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197","6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"],["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593","c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"],["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef","21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"],["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38","60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"],["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a","49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"],["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111","5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"],["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502","7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"],["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea","be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"],["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26","8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"],["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986","39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"],["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e","62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"],["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4","25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"],["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda","ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"],["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859","cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"],["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f","f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"],["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c","6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"],["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942","fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"],["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a","1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"],["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80","5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"],["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d","438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"],["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1","cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"],["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63","c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"],["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352","6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"],["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193","ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"],["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00","9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"],["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58","ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"],["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7","d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"],["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8","c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"],["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e","67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"],["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d","cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"],["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b","299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"],["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f","f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"],["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6","462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"],["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297","62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"],["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a","7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"],["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c","ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"],["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52","4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"],["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb","bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"],["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065","bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"],["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917","603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"],["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9","cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"],["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3","553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"],["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57","712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"],["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66","ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"],["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8","9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"],["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721","9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"],["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180","4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]]}}}),oN=l1((A)=>{var Q=A,J=sN(),K=By(),C=k9(),U=C.assert;function Y(E){E.type==="short"?this.curve=new K.short(E):E.type==="edwards"?this.curve=new K.edwards(E):this.curve=new K.mont(E),this.g=this.curve.g,this.n=this.curve.n,this.hash=E.hash,U(this.g.validate(),"Invalid curve"),U(this.g.mul(this.n).isInfinity(),"Invalid curve, G*N != O")}Q.PresetCurve=Y;function Z(E,H){Object.defineProperty(Q,E,{configurable:!0,enumerable:!0,get:function(){var $=new Y(H);return Object.defineProperty(Q,E,{configurable:!0,enumerable:!0,value:$}),$}})}Z("p192",{type:"short",prime:"p192",p:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff",a:"ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc",b:"64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1",n:"ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831",hash:J.sha256,gRed:!1,g:["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012","07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"]}),Z("p224",{type:"short",prime:"p224",p:"ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001",a:"ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe",b:"b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4",n:"ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d",hash:J.sha256,gRed:!1,g:["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21","bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"]}),Z("p256",{type:"short",prime:null,p:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff",a:"ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc",b:"5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b",n:"ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551",hash:J.sha256,gRed:!1,g:["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296","4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"]}),Z("p384",{type:"short",prime:null,p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff",a:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc",b:"b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef",n:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973",hash:J.sha384,gRed:!1,g:["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7","3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"]}),Z("p521",{type:"short",prime:null,p:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff",a:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc",b:"00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00",n:"000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409",hash:J.sha512,gRed:!1,g:["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66","00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"]}),Z("curve25519",{type:"mont",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"76d06",b:"1",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:J.sha256,gRed:!1,g:["9"]}),Z("ed25519",{type:"edwards",prime:"p25519",p:"7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed",a:"-1",c:"1",d:"52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3",n:"1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed",hash:J.sha256,gRed:!1,g:["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a","6666666666666666666666666666666666666666666666666666666666666658"]});var X;try{X=p91()}catch{X=void 0}Z("secp256k1",{type:"short",prime:"k256",p:"ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f",a:"0",b:"7",n:"ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141",h:"1",hash:J.sha256,beta:"7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee",lambda:"5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72",basis:[{a:"3086d221a7d46bcde86c90e49284eb15",b:"-e4437ed6010e88286f547fa90abfe4c3"},{a:"114ca50f7a8e2f3f657c1108d9d44cfd8",b:"3086d221a7d46bcde86c90e49284eb15"}],gRed:!1,g:["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8",X]})}),u91=l1((A,Q)=>{var J=sN(),K=Zy(),C=T9();function U(Y){if(!(this instanceof U))return new U(Y);this.hash=Y.hash,this.predResist=!!Y.predResist,this.outLen=this.hash.outSize,this.minEntropy=Y.minEntropy||this.hash.hmacStrength,this._reseed=null,this.reseedInterval=null,this.K=null,this.V=null;var Z=K.toArray(Y.entropy,Y.entropyEnc||"hex"),X=K.toArray(Y.nonce,Y.nonceEnc||"hex"),E=K.toArray(Y.pers,Y.persEnc||"hex");C(Z.length>=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._init(Z,X,E)}Q.exports=U,U.prototype._init=function(Y,Z,X){var E=Y.concat(Z).concat(X);this.K=new Array(this.outLen/8),this.V=new Array(this.outLen/8);for(var H=0;H=this.minEntropy/8,"Not enough entropy. Minimum is: "+this.minEntropy+" bits"),this._update(Y.concat(X||[])),this._reseed=1},U.prototype.generate=function(Y,Z,X,E){if(this._reseed>this.reseedInterval)throw new Error("Reseed is required");typeof Z!="string"&&(E=X,X=Z,Z=null),X&&(X=K.toArray(X,E||"hex"),this._update(X));for(var H=[];H.length{var J=u3(),K=k9(),C=K.assert;function U(Y,Z){this.ec=Y,this.priv=null,this.pub=null,Z.priv&&this._importPrivate(Z.priv,Z.privEnc),Z.pub&&this._importPublic(Z.pub,Z.pubEnc)}Q.exports=U,U.fromPublic=function(Y,Z,X){return Z instanceof U?Z:new U(Y,{pub:Z,pubEnc:X})},U.fromPrivate=function(Y,Z,X){return Z instanceof U?Z:new U(Y,{priv:Z,privEnc:X})},U.prototype.validate=function(){var Y=this.getPublic();return Y.isInfinity()?{result:!1,reason:"Invalid public key"}:Y.validate()?Y.mul(this.ec.curve.n).isInfinity()?{result:!0,reason:null}:{result:!1,reason:"Public key * N != O"}:{result:!1,reason:"Public key is not a point"}},U.prototype.getPublic=function(Y,Z){return typeof Y=="string"&&(Z=Y,Y=null),this.pub||(this.pub=this.ec.g.mul(this.priv)),Z?this.pub.encode(Z,Y):this.pub},U.prototype.getPrivate=function(Y){return Y==="hex"?this.priv.toString(16,2):this.priv},U.prototype._importPrivate=function(Y,Z){this.priv=new J(Y,Z||16),this.priv=this.priv.umod(this.ec.curve.n)},U.prototype._importPublic=function(Y,Z){if(Y.x||Y.y){this.ec.curve.type==="mont"?C(Y.x,"Need x coordinate"):(this.ec.curve.type==="short"||this.ec.curve.type==="edwards")&&C(Y.x&&Y.y,"Need both x and y coordinate"),this.pub=this.ec.curve.point(Y.x,Y.y);return}this.pub=this.ec.curve.decodePoint(Y,Z)},U.prototype.derive=function(Y){return Y.validate()||C(Y.validate(),"public point not validated"),Y.mul(this.priv).getX()},U.prototype.sign=function(Y,Z,X){return this.ec.sign(Y,this,Z,X)},U.prototype.verify=function(Y,Z){return this.ec.verify(Y,Z,this)},U.prototype.inspect=function(){return""}}),c91=l1((A,Q)=>{var J=u3(),K=k9(),C=K.assert;function U(H,$){if(H instanceof U)return H;this._importDER(H,$)||(C(H.r&&H.s,"Signature without r or s"),this.r=new J(H.r,16),this.s=new J(H.s,16),H.recoveryParam===void 0?this.recoveryParam=null:this.recoveryParam=H.recoveryParam)}Q.exports=U;function Y(){this.place=0}function Z(H,$){var I=H[$.place++];if(!(I&128))return I;var N=I&15;if(N===0||N>4)return!1;for(var F=0,V=0,D=$.place;V>>=0;return F<=127?!1:($.place=D,F)}function X(H){for(var $=0,I=H.length-1;!H[$]&&!(H[$+1]&128)&&$>>3);for(H.push(I|128);--I;)H.push($>>>(I<<3)&255);H.push($)}U.prototype.toDER=function(H){var $=this.r.toArray(),I=this.s.toArray();for($[0]&128&&($=[0].concat($)),I[0]&128&&(I=[0].concat(I)),$=X($),I=X(I);!I[0]&&!(I[1]&128);)I=I.slice(1);var N=[2];E(N,$.length),N=N.concat($),N.push(2),E(N,I.length);var F=N.concat(I),V=[48];return E(V,F.length),V=V.concat(F),K.encode(V,H)}}),d91=l1((A,Q)=>{var J=u3(),K=u91(),C=k9(),U=oN(),Y=cN(),Z=C.assert,X=m91(),E=c91();function H($){if(!(this instanceof H))return new H($);typeof $=="string"&&(Z(Object.prototype.hasOwnProperty.call(U,$),"Unknown curve "+$),$=U[$]),$ instanceof U.PresetCurve&&($={curve:$}),this.curve=$.curve.curve,this.n=this.curve.n,this.nh=this.n.ushrn(1),this.g=this.curve.g,this.g=$.curve.g,this.g.precompute($.curve.n.bitLength()+1),this.hash=$.hash||$.curve.hash}Q.exports=H,H.prototype.keyPair=function($){return new X(this,$)},H.prototype.keyFromPrivate=function($,I){return X.fromPrivate(this,$,I)},H.prototype.keyFromPublic=function($,I){return X.fromPublic(this,$,I)},H.prototype.genKeyPair=function($){$||($={});for(var I=new K({hash:this.hash,pers:$.pers,persEnc:$.persEnc||"utf8",entropy:$.entropy||Y(this.hash.hmacStrength),entropyEnc:$.entropy&&$.entropyEnc||"utf8",nonce:this.n.toArray()}),N=this.n.byteLength(),F=this.n.sub(new J(2));;){var V=new J(I.generate(N));if(!(V.cmp(F)>0))return V.iaddn(1),this.keyFromPrivate(V)}},H.prototype._truncateToN=function($,I){var N=$.byteLength()*8-this.n.bitLength();return N>0&&($=$.ushrn(N)),!I&&$.cmp(this.n)>=0?$.sub(this.n):$},H.prototype.sign=function($,I,N,F){typeof N=="object"&&(F=N,N=null),F||(F={}),I=this.keyFromPrivate(I,N),$=this._truncateToN(new J($,16));for(var V=this.n.byteLength(),D=I.getPrivate().toArray("be",V),L=$.toArray("be",V),R=new K({hash:this.hash,entropy:D,nonce:L,pers:F.pers,persEnc:F.persEnc||"utf8"}),M=this.n.sub(new J(1)),T=0;;T++){var h=F.k?F.k(T):new J(R.generate(this.n.byteLength()));if(h=this._truncateToN(h,!0),!(h.cmpn(1)<=0||h.cmp(M)>=0)){var y=this.g.mul(h);if(!y.isInfinity()){var g=y.getX(),f=g.umod(this.n);if(f.cmpn(0)!==0){var u=h.invm(this.n).mul(f.mul(I.getPrivate()).iadd($));if(u=u.umod(this.n),u.cmpn(0)!==0){var d=(y.getY().isOdd()?1:0)|(g.cmp(f)!==0?2:0);return F.canonical&&u.cmp(this.nh)>0&&(u=this.n.sub(u),d^=1),new E({r:f,s:u,recoveryParam:d})}}}}}},H.prototype.verify=function($,I,N,F){$=this._truncateToN(new J($,16)),N=this.keyFromPublic(N,F),I=new E(I,"hex");var{r:V,s:D}=I;if(V.cmpn(1)<0||V.cmp(this.n)>=0||D.cmpn(1)<0||D.cmp(this.n)>=0)return!1;var L=D.invm(this.n),R=L.mul($).umod(this.n),M=L.mul(V).umod(this.n),T;return this.curve._maxwellTrick?(T=this.g.jmulAdd(R,N.getPublic(),M),T.isInfinity()?!1:T.eqXToP(V)):(T=this.g.mulAdd(R,N.getPublic(),M),T.isInfinity()?!1:T.getX().umod(this.n).cmp(V)===0)},H.prototype.recoverPubKey=function($,I,N,F){Z((3&N)===N,"The recovery param is more than two bits"),I=new E(I,F);var V=this.n,D=new J($),L=I.r,R=I.s,M=N&1,T=N>>1;if(L.cmp(this.curve.p.umod(this.curve.n))>=0&&T)throw new Error("Unable to find sencond key candinate");T?L=this.curve.pointFromX(L.add(this.curve.n),M):L=this.curve.pointFromX(L,M);var h=I.r.invm(V),y=V.sub(D).mul(h).umod(V),g=R.mul(h).umod(V);return this.g.mulAdd(y,L,g)},H.prototype.getKeyRecoveryParam=function($,I,N,F){if(I=new E(I,F),I.recoveryParam!==null)return I.recoveryParam;for(var V=0;V<4;V++){var D;try{D=this.recoverPubKey($,I,V)}catch{continue}if(D.eq(N))return V}throw new Error("Unable to find valid recovery factor")}}),l91=l1((A,Q)=>{var J=k9(),K=J.assert,C=J.parseBytes,U=J.cachedProperty;function Y(Z,X){this.eddsa=Z,this._secret=C(X.secret),Z.isPoint(X.pub)?this._pub=X.pub:this._pubBytes=C(X.pub)}Y.fromPublic=function(Z,X){return X instanceof Y?X:new Y(Z,{pub:X})},Y.fromSecret=function(Z,X){return X instanceof Y?X:new Y(Z,{secret:X})},Y.prototype.secret=function(){return this._secret},U(Y,"pubBytes",function(){return this.eddsa.encodePoint(this.pub())}),U(Y,"pub",function(){return this._pubBytes?this.eddsa.decodePoint(this._pubBytes):this.eddsa.g.mul(this.priv())}),U(Y,"privBytes",function(){var Z=this.eddsa,X=this.hash(),E=Z.encodingLength-1,H=X.slice(0,Z.encodingLength);return H[0]&=248,H[E]&=127,H[E]|=64,H}),U(Y,"priv",function(){return this.eddsa.decodeInt(this.privBytes())}),U(Y,"hash",function(){return this.eddsa.hash().update(this.secret()).digest()}),U(Y,"messagePrefix",function(){return this.hash().slice(this.eddsa.encodingLength)}),Y.prototype.sign=function(Z){return K(this._secret,"KeyPair can only verify"),this.eddsa.sign(Z,this)},Y.prototype.verify=function(Z,X){return this.eddsa.verify(Z,X,this)},Y.prototype.getSecret=function(Z){return K(this._secret,"KeyPair is public only"),J.encode(this.secret(),Z)},Y.prototype.getPublic=function(Z){return J.encode(this.pubBytes(),Z)},Q.exports=Y}),n91=l1((A,Q)=>{var J=u3(),K=k9(),C=K.assert,U=K.cachedProperty,Y=K.parseBytes;function Z(X,E){this.eddsa=X,typeof E!="object"&&(E=Y(E)),Array.isArray(E)&&(E={R:E.slice(0,X.encodingLength),S:E.slice(X.encodingLength)}),C(E.R&&E.S,"Signature without R or S"),X.isPoint(E.R)&&(this._R=E.R),E.S instanceof J&&(this._S=E.S),this._Rencoded=Array.isArray(E.R)?E.R:E.Rencoded,this._Sencoded=Array.isArray(E.S)?E.S:E.Sencoded}U(Z,"S",function(){return this.eddsa.decodeInt(this.Sencoded())}),U(Z,"R",function(){return this.eddsa.decodePoint(this.Rencoded())}),U(Z,"Rencoded",function(){return this.eddsa.encodePoint(this.R())}),U(Z,"Sencoded",function(){return this.eddsa.encodeInt(this.S())}),Z.prototype.toBytes=function(){return this.Rencoded().concat(this.Sencoded())},Z.prototype.toHex=function(){return K.encode(this.toBytes(),"hex").toUpperCase()},Q.exports=Z}),s91=l1((A,Q)=>{var J=sN(),K=oN(),C=k9(),U=C.assert,Y=C.parseBytes,Z=l91(),X=n91();function E(H){if(U(H==="ed25519","only tested with ed25519 so far"),!(this instanceof E))return new E(H);H=K[H].curve,this.curve=H,this.g=H.g,this.g.precompute(H.n.bitLength()+1),this.pointClass=H.point().constructor,this.encodingLength=Math.ceil(H.n.bitLength()/8),this.hash=J.sha512}Q.exports=E,E.prototype.sign=function(H,$){H=Y(H);var I=this.keyFromSecret($),N=this.hashInt(I.messagePrefix(),H),F=this.g.mul(N),V=this.encodePoint(F),D=this.hashInt(V,I.pubBytes(),H).mul(I.priv()),L=N.add(D).umod(this.curve.n);return this.makeSignature({R:F,S:L,Rencoded:V})},E.prototype.verify=function(H,$,I){H=Y(H),$=this.makeSignature($);var N=this.keyFromPublic(I),F=this.hashInt($.Rencoded(),N.pubBytes(),H),V=this.g.mul($.S()),D=$.R().add(N.pub().mul(F));return D.eq(V)},E.prototype.hashInt=function(){for(var H=this.hash(),$=0;${var Q=A;Q.version=k91().version,Q.utils=k9(),Q.rand=cN(),Q.curve=By(),Q.curves=oN(),Q.ec=d91(),Q.eddsa=s91()}),Hy=l1((A,Q)=>{(function(J,K){function C(B,q){if(!B)throw new Error(q||"Assertion failed")}function U(B,q){B.super_=q;var P=function(){};P.prototype=q.prototype,B.prototype=new P,B.prototype.constructor=B}function Y(B,q,P){if(Y.isBN(B))return B;this.negative=0,this.words=null,this.length=0,this.red=null,B!==null&&((q==="le"||q==="be")&&(P=q,q=10),this._init(B||0,q||10,P||"be"))}typeof J=="object"?J.exports=Y:K.BN=Y,Y.BN=Y,Y.wordSize=26;var Z;try{typeof window<"u"&&typeof window.Buffer<"u"?Z=window.Buffer:Z=XQ().Buffer}catch{}Y.isBN=function(B){return B instanceof Y?!0:B!==null&&typeof B=="object"&&B.constructor.wordSize===Y.wordSize&&Array.isArray(B.words)},Y.max=function(B,q){return B.cmp(q)>0?B:q},Y.min=function(B,q){return B.cmp(q)<0?B:q},Y.prototype._init=function(B,q,P){if(typeof B=="number")return this._initNumber(B,q,P);if(typeof B=="object")return this._initArray(B,q,P);q==="hex"&&(q=16),C(q===(q|0)&&q>=2&&q<=36),B=B.toString().replace(/\s+/g,"");var O=0;B[0]==="-"&&(O++,this.negative=1),O=0;O-=3)k=B[O]|B[O-1]<<8|B[O-2]<<16,this.words[w]|=k<>>26-S&67108863,S+=24,S>=26&&(S-=26,w++);else if(P==="le")for(O=0,w=0;O>>26-S&67108863,S+=24,S>=26&&(S-=26,w++);return this.strip()};function X(B,q){var P=B.charCodeAt(q);return P>=65&&P<=70?P-55:P>=97&&P<=102?P-87:P-48&15}function E(B,q,P){var O=X(B,P);return P-1>=q&&(O|=X(B,P-1)<<4),O}Y.prototype._parseHex=function(B,q,P){this.length=Math.ceil((B.length-q)/6),this.words=new Array(this.length);for(var O=0;O=q;O-=2)S=E(B,q,O)<=18?(w-=18,k+=1,this.words[k]|=S>>>26):w+=8;else{var _=B.length-q;for(O=_%2===0?q+1:q;O=18?(w-=18,k+=1,this.words[k]|=S>>>26):w+=8}this.strip()};function H(B,q,P,O){for(var w=0,k=Math.min(B.length,P),S=q;S=49?w+=_-49+10:_>=17?w+=_-17+10:w+=_}return w}Y.prototype._parseBase=function(B,q,P){this.words=[0],this.length=1;for(var O=0,w=1;w<=67108863;w*=q)O++;O--,w=w/q|0;for(var k=B.length-P,S=k%O,_=Math.min(k,k-S)+P,W=0,j=P;j<_;j+=O)W=H(B,j,j+O,q),this.imuln(w),this.words[0]+W<67108864?this.words[0]+=W:this._iaddn(W);if(S!==0){var b=1;for(W=H(B,j,B.length,q),j=0;j1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},Y.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},Y.prototype.inspect=function(){return(this.red?""};var $=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],I=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],N=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];Y.prototype.toString=function(B,q){B=B||10,q=q|0||1;var P;if(B===16||B==="hex"){P="";for(var O=0,w=0,k=0;k>>24-O&16777215,w!==0||k!==this.length-1?P=$[6-_.length]+_+P:P=_+P,O+=2,O>=26&&(O-=26,k--)}for(w!==0&&(P=w.toString(16)+P);P.length%q!==0;)P="0"+P;return this.negative!==0&&(P="-"+P),P}if(B===(B|0)&&B>=2&&B<=36){var W=I[B],j=N[B];P="";var b=this.clone();for(b.negative=0;!b.isZero();){var p=b.modn(j).toString(B);b=b.idivn(j),b.isZero()?P=p+P:P=$[W-p.length]+p+P}for(this.isZero()&&(P="0"+P);P.length%q!==0;)P="0"+P;return this.negative!==0&&(P="-"+P),P}C(!1,"Base should be between 2 and 36")},Y.prototype.toNumber=function(){var B=this.words[0];return this.length===2?B+=this.words[1]*67108864:this.length===3&&this.words[2]===1?B+=4503599627370496+this.words[1]*67108864:this.length>2&&C(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-B:B},Y.prototype.toJSON=function(){return this.toString(16)},Y.prototype.toBuffer=function(B,q){return C(typeof Z<"u"),this.toArrayLike(Z,B,q)},Y.prototype.toArray=function(B,q){return this.toArrayLike(Array,B,q)},Y.prototype.toArrayLike=function(B,q,P){var O=this.byteLength(),w=P||Math.max(1,O);C(O<=w,"byte array longer than desired length"),C(w>0,"Requested array length <= 0"),this.strip();var k=q==="le",S=new B(w),_,W,j=this.clone();if(k){for(W=0;!j.isZero();W++)_=j.andln(255),j.iushrn(8),S[W]=_;for(;W=4096&&(P+=13,q>>>=13),q>=64&&(P+=7,q>>>=7),q>=8&&(P+=4,q>>>=4),q>=2&&(P+=2,q>>>=2),P+q},Y.prototype._zeroBits=function(B){if(B===0)return 26;var q=B,P=0;return(q&8191)===0&&(P+=13,q>>>=13),(q&127)===0&&(P+=7,q>>>=7),(q&15)===0&&(P+=4,q>>>=4),(q&3)===0&&(P+=2,q>>>=2),(q&1)===0&&P++,P},Y.prototype.bitLength=function(){var B=this.words[this.length-1],q=this._countBits(B);return(this.length-1)*26+q};function F(B){for(var q=new Array(B.bitLength()),P=0;P>>w}return q}Y.prototype.zeroBits=function(){if(this.isZero())return 0;for(var B=0,q=0;qB.length?this.clone().ior(B):B.clone().ior(this)},Y.prototype.uor=function(B){return this.length>B.length?this.clone().iuor(B):B.clone().iuor(this)},Y.prototype.iuand=function(B){var q;this.length>B.length?q=B:q=this;for(var P=0;PB.length?this.clone().iand(B):B.clone().iand(this)},Y.prototype.uand=function(B){return this.length>B.length?this.clone().iuand(B):B.clone().iuand(this)},Y.prototype.iuxor=function(B){var q,P;this.length>B.length?(q=this,P=B):(q=B,P=this);for(var O=0;OB.length?this.clone().ixor(B):B.clone().ixor(this)},Y.prototype.uxor=function(B){return this.length>B.length?this.clone().iuxor(B):B.clone().iuxor(this)},Y.prototype.inotn=function(B){C(typeof B=="number"&&B>=0);var q=Math.ceil(B/26)|0,P=B%26;this._expand(q),P>0&&q--;for(var O=0;O0&&(this.words[O]=~this.words[O]&67108863>>26-P),this.strip()},Y.prototype.notn=function(B){return this.clone().inotn(B)},Y.prototype.setn=function(B,q){C(typeof B=="number"&&B>=0);var P=B/26|0,O=B%26;return this._expand(P+1),q?this.words[P]=this.words[P]|1<B.length?(P=this,O=B):(P=B,O=this);for(var w=0,k=0;k>>26;for(;w!==0&&k>>26;if(this.length=P.length,w!==0)this.words[this.length]=w,this.length++;else if(P!==this)for(;kB.length?this.clone().iadd(B):B.clone().iadd(this)},Y.prototype.isub=function(B){if(B.negative!==0){B.negative=0;var q=this.iadd(B);return B.negative=1,q._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(B),this.negative=1,this._normSign();var P=this.cmp(B);if(P===0)return this.negative=0,this.length=1,this.words[0]=0,this;var O,w;P>0?(O=this,w=B):(O=B,w=this);for(var k=0,S=0;S>26,this.words[S]=q&67108863;for(;k!==0&&S>26,this.words[S]=q&67108863;if(k===0&&S>>26,p=W&67108863,s=Math.min(j,q.length-1),r=Math.max(0,j-B.length+1);r<=s;r++){var A1=j-r|0;w=B.words[A1]|0,k=q.words[r]|0,S=w*k+p,b+=S/67108864|0,p=S&67108863}P.words[j]=p|0,W=b|0}return W!==0?P.words[j]=W|0:P.length--,P.strip()}var D=function(B,q,P){var O=B.words,w=q.words,k=P.words,S=0,_,W,j,b=O[0]|0,p=b&8191,s=b>>>13,r=O[1]|0,A1=r&8191,Q1=r>>>13,e=O[2]|0,t=e&8191,U1=e>>>13,O1=O[3]|0,E1=O1&8191,Y1=O1>>>13,i=O[4]|0,c=i&8191,o=i>>>13,C1=O[5]|0,q1=C1&8191,Z1=C1>>>13,j1=O[6]|0,H1=j1&8191,B1=j1>>>13,k1=O[7]|0,D1=k1&8191,G1=k1>>>13,w1=O[8]|0,G=w1&8191,z=w1>>>13,x=O[9]|0,m=x&8191,l=x>>>13,a=w[0]|0,K1=a&8191,F1=a>>>13,R1=w[1]|0,X1=R1&8191,W1=R1>>>13,$1=w[2]|0,N1=$1&8191,_1=$1>>>13,J1=w[3]|0,z1=J1&8191,M1=J1>>>13,L1=w[4]|0,V1=L1&8191,S1=L1>>>13,O0=w[5]|0,h1=O0&8191,b1=O0>>>13,f0=w[6]|0,e1=f0&8191,s1=f0>>>13,o0=w[7]|0,a1=o0&8191,r1=o0>>>13,FA=w[8]|0,K0=FA&8191,J0=FA>>>13,qA=w[9]|0,Q0=qA&8191,A0=qA>>>13;P.negative=B.negative^q.negative,P.length=19,_=Math.imul(p,K1),W=Math.imul(p,F1),W=W+Math.imul(s,K1)|0,j=Math.imul(s,F1);var hA=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(hA>>>26)|0,hA&=67108863,_=Math.imul(A1,K1),W=Math.imul(A1,F1),W=W+Math.imul(Q1,K1)|0,j=Math.imul(Q1,F1),_=_+Math.imul(p,X1)|0,W=W+Math.imul(p,W1)|0,W=W+Math.imul(s,X1)|0,j=j+Math.imul(s,W1)|0;var r0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(r0>>>26)|0,r0&=67108863,_=Math.imul(t,K1),W=Math.imul(t,F1),W=W+Math.imul(U1,K1)|0,j=Math.imul(U1,F1),_=_+Math.imul(A1,X1)|0,W=W+Math.imul(A1,W1)|0,W=W+Math.imul(Q1,X1)|0,j=j+Math.imul(Q1,W1)|0,_=_+Math.imul(p,N1)|0,W=W+Math.imul(p,_1)|0,W=W+Math.imul(s,N1)|0,j=j+Math.imul(s,_1)|0;var EA=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(EA>>>26)|0,EA&=67108863,_=Math.imul(E1,K1),W=Math.imul(E1,F1),W=W+Math.imul(Y1,K1)|0,j=Math.imul(Y1,F1),_=_+Math.imul(t,X1)|0,W=W+Math.imul(t,W1)|0,W=W+Math.imul(U1,X1)|0,j=j+Math.imul(U1,W1)|0,_=_+Math.imul(A1,N1)|0,W=W+Math.imul(A1,_1)|0,W=W+Math.imul(Q1,N1)|0,j=j+Math.imul(Q1,_1)|0,_=_+Math.imul(p,z1)|0,W=W+Math.imul(p,M1)|0,W=W+Math.imul(s,z1)|0,j=j+Math.imul(s,M1)|0;var X2=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(X2>>>26)|0,X2&=67108863,_=Math.imul(c,K1),W=Math.imul(c,F1),W=W+Math.imul(o,K1)|0,j=Math.imul(o,F1),_=_+Math.imul(E1,X1)|0,W=W+Math.imul(E1,W1)|0,W=W+Math.imul(Y1,X1)|0,j=j+Math.imul(Y1,W1)|0,_=_+Math.imul(t,N1)|0,W=W+Math.imul(t,_1)|0,W=W+Math.imul(U1,N1)|0,j=j+Math.imul(U1,_1)|0,_=_+Math.imul(A1,z1)|0,W=W+Math.imul(A1,M1)|0,W=W+Math.imul(Q1,z1)|0,j=j+Math.imul(Q1,M1)|0,_=_+Math.imul(p,V1)|0,W=W+Math.imul(p,S1)|0,W=W+Math.imul(s,V1)|0,j=j+Math.imul(s,S1)|0;var E2=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(E2>>>26)|0,E2&=67108863,_=Math.imul(q1,K1),W=Math.imul(q1,F1),W=W+Math.imul(Z1,K1)|0,j=Math.imul(Z1,F1),_=_+Math.imul(c,X1)|0,W=W+Math.imul(c,W1)|0,W=W+Math.imul(o,X1)|0,j=j+Math.imul(o,W1)|0,_=_+Math.imul(E1,N1)|0,W=W+Math.imul(E1,_1)|0,W=W+Math.imul(Y1,N1)|0,j=j+Math.imul(Y1,_1)|0,_=_+Math.imul(t,z1)|0,W=W+Math.imul(t,M1)|0,W=W+Math.imul(U1,z1)|0,j=j+Math.imul(U1,M1)|0,_=_+Math.imul(A1,V1)|0,W=W+Math.imul(A1,S1)|0,W=W+Math.imul(Q1,V1)|0,j=j+Math.imul(Q1,S1)|0,_=_+Math.imul(p,h1)|0,W=W+Math.imul(p,b1)|0,W=W+Math.imul(s,h1)|0,j=j+Math.imul(s,b1)|0;var T1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(T1>>>26)|0,T1&=67108863,_=Math.imul(H1,K1),W=Math.imul(H1,F1),W=W+Math.imul(B1,K1)|0,j=Math.imul(B1,F1),_=_+Math.imul(q1,X1)|0,W=W+Math.imul(q1,W1)|0,W=W+Math.imul(Z1,X1)|0,j=j+Math.imul(Z1,W1)|0,_=_+Math.imul(c,N1)|0,W=W+Math.imul(c,_1)|0,W=W+Math.imul(o,N1)|0,j=j+Math.imul(o,_1)|0,_=_+Math.imul(E1,z1)|0,W=W+Math.imul(E1,M1)|0,W=W+Math.imul(Y1,z1)|0,j=j+Math.imul(Y1,M1)|0,_=_+Math.imul(t,V1)|0,W=W+Math.imul(t,S1)|0,W=W+Math.imul(U1,V1)|0,j=j+Math.imul(U1,S1)|0,_=_+Math.imul(A1,h1)|0,W=W+Math.imul(A1,b1)|0,W=W+Math.imul(Q1,h1)|0,j=j+Math.imul(Q1,b1)|0,_=_+Math.imul(p,e1)|0,W=W+Math.imul(p,s1)|0,W=W+Math.imul(s,e1)|0,j=j+Math.imul(s,s1)|0;var m1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(m1>>>26)|0,m1&=67108863,_=Math.imul(D1,K1),W=Math.imul(D1,F1),W=W+Math.imul(G1,K1)|0,j=Math.imul(G1,F1),_=_+Math.imul(H1,X1)|0,W=W+Math.imul(H1,W1)|0,W=W+Math.imul(B1,X1)|0,j=j+Math.imul(B1,W1)|0,_=_+Math.imul(q1,N1)|0,W=W+Math.imul(q1,_1)|0,W=W+Math.imul(Z1,N1)|0,j=j+Math.imul(Z1,_1)|0,_=_+Math.imul(c,z1)|0,W=W+Math.imul(c,M1)|0,W=W+Math.imul(o,z1)|0,j=j+Math.imul(o,M1)|0,_=_+Math.imul(E1,V1)|0,W=W+Math.imul(E1,S1)|0,W=W+Math.imul(Y1,V1)|0,j=j+Math.imul(Y1,S1)|0,_=_+Math.imul(t,h1)|0,W=W+Math.imul(t,b1)|0,W=W+Math.imul(U1,h1)|0,j=j+Math.imul(U1,b1)|0,_=_+Math.imul(A1,e1)|0,W=W+Math.imul(A1,s1)|0,W=W+Math.imul(Q1,e1)|0,j=j+Math.imul(Q1,s1)|0,_=_+Math.imul(p,a1)|0,W=W+Math.imul(p,r1)|0,W=W+Math.imul(s,a1)|0,j=j+Math.imul(s,r1)|0;var i1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(i1>>>26)|0,i1&=67108863,_=Math.imul(G,K1),W=Math.imul(G,F1),W=W+Math.imul(z,K1)|0,j=Math.imul(z,F1),_=_+Math.imul(D1,X1)|0,W=W+Math.imul(D1,W1)|0,W=W+Math.imul(G1,X1)|0,j=j+Math.imul(G1,W1)|0,_=_+Math.imul(H1,N1)|0,W=W+Math.imul(H1,_1)|0,W=W+Math.imul(B1,N1)|0,j=j+Math.imul(B1,_1)|0,_=_+Math.imul(q1,z1)|0,W=W+Math.imul(q1,M1)|0,W=W+Math.imul(Z1,z1)|0,j=j+Math.imul(Z1,M1)|0,_=_+Math.imul(c,V1)|0,W=W+Math.imul(c,S1)|0,W=W+Math.imul(o,V1)|0,j=j+Math.imul(o,S1)|0,_=_+Math.imul(E1,h1)|0,W=W+Math.imul(E1,b1)|0,W=W+Math.imul(Y1,h1)|0,j=j+Math.imul(Y1,b1)|0,_=_+Math.imul(t,e1)|0,W=W+Math.imul(t,s1)|0,W=W+Math.imul(U1,e1)|0,j=j+Math.imul(U1,s1)|0,_=_+Math.imul(A1,a1)|0,W=W+Math.imul(A1,r1)|0,W=W+Math.imul(Q1,a1)|0,j=j+Math.imul(Q1,r1)|0,_=_+Math.imul(p,K0)|0,W=W+Math.imul(p,J0)|0,W=W+Math.imul(s,K0)|0,j=j+Math.imul(s,J0)|0;var t1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(t1>>>26)|0,t1&=67108863,_=Math.imul(m,K1),W=Math.imul(m,F1),W=W+Math.imul(l,K1)|0,j=Math.imul(l,F1),_=_+Math.imul(G,X1)|0,W=W+Math.imul(G,W1)|0,W=W+Math.imul(z,X1)|0,j=j+Math.imul(z,W1)|0,_=_+Math.imul(D1,N1)|0,W=W+Math.imul(D1,_1)|0,W=W+Math.imul(G1,N1)|0,j=j+Math.imul(G1,_1)|0,_=_+Math.imul(H1,z1)|0,W=W+Math.imul(H1,M1)|0,W=W+Math.imul(B1,z1)|0,j=j+Math.imul(B1,M1)|0,_=_+Math.imul(q1,V1)|0,W=W+Math.imul(q1,S1)|0,W=W+Math.imul(Z1,V1)|0,j=j+Math.imul(Z1,S1)|0,_=_+Math.imul(c,h1)|0,W=W+Math.imul(c,b1)|0,W=W+Math.imul(o,h1)|0,j=j+Math.imul(o,b1)|0,_=_+Math.imul(E1,e1)|0,W=W+Math.imul(E1,s1)|0,W=W+Math.imul(Y1,e1)|0,j=j+Math.imul(Y1,s1)|0,_=_+Math.imul(t,a1)|0,W=W+Math.imul(t,r1)|0,W=W+Math.imul(U1,a1)|0,j=j+Math.imul(U1,r1)|0,_=_+Math.imul(A1,K0)|0,W=W+Math.imul(A1,J0)|0,W=W+Math.imul(Q1,K0)|0,j=j+Math.imul(Q1,J0)|0,_=_+Math.imul(p,Q0)|0,W=W+Math.imul(p,A0)|0,W=W+Math.imul(s,Q0)|0,j=j+Math.imul(s,A0)|0;var d1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(d1>>>26)|0,d1&=67108863,_=Math.imul(m,X1),W=Math.imul(m,W1),W=W+Math.imul(l,X1)|0,j=Math.imul(l,W1),_=_+Math.imul(G,N1)|0,W=W+Math.imul(G,_1)|0,W=W+Math.imul(z,N1)|0,j=j+Math.imul(z,_1)|0,_=_+Math.imul(D1,z1)|0,W=W+Math.imul(D1,M1)|0,W=W+Math.imul(G1,z1)|0,j=j+Math.imul(G1,M1)|0,_=_+Math.imul(H1,V1)|0,W=W+Math.imul(H1,S1)|0,W=W+Math.imul(B1,V1)|0,j=j+Math.imul(B1,S1)|0,_=_+Math.imul(q1,h1)|0,W=W+Math.imul(q1,b1)|0,W=W+Math.imul(Z1,h1)|0,j=j+Math.imul(Z1,b1)|0,_=_+Math.imul(c,e1)|0,W=W+Math.imul(c,s1)|0,W=W+Math.imul(o,e1)|0,j=j+Math.imul(o,s1)|0,_=_+Math.imul(E1,a1)|0,W=W+Math.imul(E1,r1)|0,W=W+Math.imul(Y1,a1)|0,j=j+Math.imul(Y1,r1)|0,_=_+Math.imul(t,K0)|0,W=W+Math.imul(t,J0)|0,W=W+Math.imul(U1,K0)|0,j=j+Math.imul(U1,J0)|0,_=_+Math.imul(A1,Q0)|0,W=W+Math.imul(A1,A0)|0,W=W+Math.imul(Q1,Q0)|0,j=j+Math.imul(Q1,A0)|0;var H0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(H0>>>26)|0,H0&=67108863,_=Math.imul(m,N1),W=Math.imul(m,_1),W=W+Math.imul(l,N1)|0,j=Math.imul(l,_1),_=_+Math.imul(G,z1)|0,W=W+Math.imul(G,M1)|0,W=W+Math.imul(z,z1)|0,j=j+Math.imul(z,M1)|0,_=_+Math.imul(D1,V1)|0,W=W+Math.imul(D1,S1)|0,W=W+Math.imul(G1,V1)|0,j=j+Math.imul(G1,S1)|0,_=_+Math.imul(H1,h1)|0,W=W+Math.imul(H1,b1)|0,W=W+Math.imul(B1,h1)|0,j=j+Math.imul(B1,b1)|0,_=_+Math.imul(q1,e1)|0,W=W+Math.imul(q1,s1)|0,W=W+Math.imul(Z1,e1)|0,j=j+Math.imul(Z1,s1)|0,_=_+Math.imul(c,a1)|0,W=W+Math.imul(c,r1)|0,W=W+Math.imul(o,a1)|0,j=j+Math.imul(o,r1)|0,_=_+Math.imul(E1,K0)|0,W=W+Math.imul(E1,J0)|0,W=W+Math.imul(Y1,K0)|0,j=j+Math.imul(Y1,J0)|0,_=_+Math.imul(t,Q0)|0,W=W+Math.imul(t,A0)|0,W=W+Math.imul(U1,Q0)|0,j=j+Math.imul(U1,A0)|0;var R0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(R0>>>26)|0,R0&=67108863,_=Math.imul(m,z1),W=Math.imul(m,M1),W=W+Math.imul(l,z1)|0,j=Math.imul(l,M1),_=_+Math.imul(G,V1)|0,W=W+Math.imul(G,S1)|0,W=W+Math.imul(z,V1)|0,j=j+Math.imul(z,S1)|0,_=_+Math.imul(D1,h1)|0,W=W+Math.imul(D1,b1)|0,W=W+Math.imul(G1,h1)|0,j=j+Math.imul(G1,b1)|0,_=_+Math.imul(H1,e1)|0,W=W+Math.imul(H1,s1)|0,W=W+Math.imul(B1,e1)|0,j=j+Math.imul(B1,s1)|0,_=_+Math.imul(q1,a1)|0,W=W+Math.imul(q1,r1)|0,W=W+Math.imul(Z1,a1)|0,j=j+Math.imul(Z1,r1)|0,_=_+Math.imul(c,K0)|0,W=W+Math.imul(c,J0)|0,W=W+Math.imul(o,K0)|0,j=j+Math.imul(o,J0)|0,_=_+Math.imul(E1,Q0)|0,W=W+Math.imul(E1,A0)|0,W=W+Math.imul(Y1,Q0)|0,j=j+Math.imul(Y1,A0)|0;var D0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(D0>>>26)|0,D0&=67108863,_=Math.imul(m,V1),W=Math.imul(m,S1),W=W+Math.imul(l,V1)|0,j=Math.imul(l,S1),_=_+Math.imul(G,h1)|0,W=W+Math.imul(G,b1)|0,W=W+Math.imul(z,h1)|0,j=j+Math.imul(z,b1)|0,_=_+Math.imul(D1,e1)|0,W=W+Math.imul(D1,s1)|0,W=W+Math.imul(G1,e1)|0,j=j+Math.imul(G1,s1)|0,_=_+Math.imul(H1,a1)|0,W=W+Math.imul(H1,r1)|0,W=W+Math.imul(B1,a1)|0,j=j+Math.imul(B1,r1)|0,_=_+Math.imul(q1,K0)|0,W=W+Math.imul(q1,J0)|0,W=W+Math.imul(Z1,K0)|0,j=j+Math.imul(Z1,J0)|0,_=_+Math.imul(c,Q0)|0,W=W+Math.imul(c,A0)|0,W=W+Math.imul(o,Q0)|0,j=j+Math.imul(o,A0)|0;var P0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(P0>>>26)|0,P0&=67108863,_=Math.imul(m,h1),W=Math.imul(m,b1),W=W+Math.imul(l,h1)|0,j=Math.imul(l,b1),_=_+Math.imul(G,e1)|0,W=W+Math.imul(G,s1)|0,W=W+Math.imul(z,e1)|0,j=j+Math.imul(z,s1)|0,_=_+Math.imul(D1,a1)|0,W=W+Math.imul(D1,r1)|0,W=W+Math.imul(G1,a1)|0,j=j+Math.imul(G1,r1)|0,_=_+Math.imul(H1,K0)|0,W=W+Math.imul(H1,J0)|0,W=W+Math.imul(B1,K0)|0,j=j+Math.imul(B1,J0)|0,_=_+Math.imul(q1,Q0)|0,W=W+Math.imul(q1,A0)|0,W=W+Math.imul(Z1,Q0)|0,j=j+Math.imul(Z1,A0)|0;var j0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(j0>>>26)|0,j0&=67108863,_=Math.imul(m,e1),W=Math.imul(m,s1),W=W+Math.imul(l,e1)|0,j=Math.imul(l,s1),_=_+Math.imul(G,a1)|0,W=W+Math.imul(G,r1)|0,W=W+Math.imul(z,a1)|0,j=j+Math.imul(z,r1)|0,_=_+Math.imul(D1,K0)|0,W=W+Math.imul(D1,J0)|0,W=W+Math.imul(G1,K0)|0,j=j+Math.imul(G1,J0)|0,_=_+Math.imul(H1,Q0)|0,W=W+Math.imul(H1,A0)|0,W=W+Math.imul(B1,Q0)|0,j=j+Math.imul(B1,A0)|0;var v0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(v0>>>26)|0,v0&=67108863,_=Math.imul(m,a1),W=Math.imul(m,r1),W=W+Math.imul(l,a1)|0,j=Math.imul(l,r1),_=_+Math.imul(G,K0)|0,W=W+Math.imul(G,J0)|0,W=W+Math.imul(z,K0)|0,j=j+Math.imul(z,J0)|0,_=_+Math.imul(D1,Q0)|0,W=W+Math.imul(D1,A0)|0,W=W+Math.imul(G1,Q0)|0,j=j+Math.imul(G1,A0)|0;var S0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(S0>>>26)|0,S0&=67108863,_=Math.imul(m,K0),W=Math.imul(m,J0),W=W+Math.imul(l,K0)|0,j=Math.imul(l,J0),_=_+Math.imul(G,Q0)|0,W=W+Math.imul(G,A0)|0,W=W+Math.imul(z,Q0)|0,j=j+Math.imul(z,A0)|0;var n0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(n0>>>26)|0,n0&=67108863,_=Math.imul(m,Q0),W=Math.imul(m,A0),W=W+Math.imul(l,Q0)|0,j=Math.imul(l,A0);var i0=(S+_|0)+((W&8191)<<13)|0;return S=(j+(W>>>13)|0)+(i0>>>26)|0,i0&=67108863,k[0]=hA,k[1]=r0,k[2]=EA,k[3]=X2,k[4]=E2,k[5]=T1,k[6]=m1,k[7]=i1,k[8]=t1,k[9]=d1,k[10]=H0,k[11]=R0,k[12]=D0,k[13]=P0,k[14]=j0,k[15]=v0,k[16]=S0,k[17]=n0,k[18]=i0,S!==0&&(k[19]=S,P.length++),P};Math.imul||(D=V);function L(B,q,P){P.negative=q.negative^B.negative,P.length=B.length+q.length;for(var O=0,w=0,k=0;k>>26)|0,w+=S>>>26,S&=67108863}P.words[k]=_,O=S,S=w}return O!==0?P.words[k]=O:P.length--,P.strip()}function R(B,q,P){var O=new M;return O.mulp(B,q,P)}Y.prototype.mulTo=function(B,q){var P,O=this.length+B.length;return this.length===10&&B.length===10?P=D(this,B,q):O<63?P=V(this,B,q):O<1024?P=L(this,B,q):P=R(this,B,q),P};function M(B,q){this.x=B,this.y=q}M.prototype.makeRBT=function(B){for(var q=new Array(B),P=Y.prototype._countBits(B)-1,O=0;O>=1;return O},M.prototype.permute=function(B,q,P,O,w,k){for(var S=0;S>>1)w++;return 1<>>13,P[2*k+1]=w&8191,w=w>>>13;for(k=2*q;k>=26,q+=O/67108864|0,q+=w>>>26,this.words[P]=w&67108863}return q!==0&&(this.words[P]=q,this.length++),this},Y.prototype.muln=function(B){return this.clone().imuln(B)},Y.prototype.sqr=function(){return this.mul(this)},Y.prototype.isqr=function(){return this.imul(this.clone())},Y.prototype.pow=function(B){var q=F(B);if(q.length===0)return new Y(1);for(var P=this,O=0;O=0);var q=B%26,P=(B-q)/26,O=67108863>>>26-q<<26-q,w;if(q!==0){var k=0;for(w=0;w>>26-q}k&&(this.words[w]=k,this.length++)}if(P!==0){for(w=this.length-1;w>=0;w--)this.words[w+P]=this.words[w];for(w=0;w=0);var O;q?O=(q-q%26)/26:O=0;var w=B%26,k=Math.min((B-w)/26,this.length),S=67108863^67108863>>>w<k)for(this.length-=k,W=0;W=0&&(j!==0||W>=O);W--){var b=this.words[W]|0;this.words[W]=j<<26-w|b>>>w,j=b&S}return _&&j!==0&&(_.words[_.length++]=j),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},Y.prototype.ishrn=function(B,q,P){return C(this.negative===0),this.iushrn(B,q,P)},Y.prototype.shln=function(B){return this.clone().ishln(B)},Y.prototype.ushln=function(B){return this.clone().iushln(B)},Y.prototype.shrn=function(B){return this.clone().ishrn(B)},Y.prototype.ushrn=function(B){return this.clone().iushrn(B)},Y.prototype.testn=function(B){C(typeof B=="number"&&B>=0);var q=B%26,P=(B-q)/26,O=1<=0);var q=B%26,P=(B-q)/26;if(C(this.negative===0,"imaskn works only with positive numbers"),this.length<=P)return this;if(q!==0&&P++,this.length=Math.min(P,this.length),q!==0){var O=67108863^67108863>>>q<=67108864;q++)this.words[q]-=67108864,q===this.length-1?this.words[q+1]=1:this.words[q+1]++;return this.length=Math.max(this.length,q+1),this},Y.prototype.isubn=function(B){if(C(typeof B=="number"),C(B<67108864),B<0)return this.iaddn(-B);if(this.negative!==0)return this.negative=0,this.iaddn(B),this.negative=1,this;if(this.words[0]-=B,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var q=0;q>26)-(_/67108864|0),this.words[w+P]=k&67108863}for(;w>26,this.words[w+P]=k&67108863;if(S===0)return this.strip();for(C(S===-1),S=0,w=0;w>26,this.words[w]=k&67108863;return this.negative=1,this.strip()},Y.prototype._wordDiv=function(B,q){var P=this.length-B.length,O=this.clone(),w=B,k=w.words[w.length-1]|0,S=this._countBits(k);P=26-S,P!==0&&(w=w.ushln(P),O.iushln(P),k=w.words[w.length-1]|0);var _=O.length-w.length,W;if(q!=="mod"){W=new Y(null),W.length=_+1,W.words=new Array(W.length);for(var j=0;j=0;p--){var s=(O.words[w.length+p]|0)*67108864+(O.words[w.length+p-1]|0);for(s=Math.min(s/k|0,67108863),O._ishlnsubmul(w,s,p);O.negative!==0;)s--,O.negative=0,O._ishlnsubmul(w,1,p),O.isZero()||(O.negative^=1);W&&(W.words[p]=s)}return W&&W.strip(),O.strip(),q!=="div"&&P!==0&&O.iushrn(P),{div:W||null,mod:O}},Y.prototype.divmod=function(B,q,P){if(C(!B.isZero()),this.isZero())return{div:new Y(0),mod:new Y(0)};var O,w,k;return this.negative!==0&&B.negative===0?(k=this.neg().divmod(B,q),q!=="mod"&&(O=k.div.neg()),q!=="div"&&(w=k.mod.neg(),P&&w.negative!==0&&w.iadd(B)),{div:O,mod:w}):this.negative===0&&B.negative!==0?(k=this.divmod(B.neg(),q),q!=="mod"&&(O=k.div.neg()),{div:O,mod:k.mod}):(this.negative&B.negative)!==0?(k=this.neg().divmod(B.neg(),q),q!=="div"&&(w=k.mod.neg(),P&&w.negative!==0&&w.isub(B)),{div:k.div,mod:w}):B.length>this.length||this.cmp(B)<0?{div:new Y(0),mod:this}:B.length===1?q==="div"?{div:this.divn(B.words[0]),mod:null}:q==="mod"?{div:null,mod:new Y(this.modn(B.words[0]))}:{div:this.divn(B.words[0]),mod:new Y(this.modn(B.words[0]))}:this._wordDiv(B,q)},Y.prototype.div=function(B){return this.divmod(B,"div",!1).div},Y.prototype.mod=function(B){return this.divmod(B,"mod",!1).mod},Y.prototype.umod=function(B){return this.divmod(B,"mod",!0).mod},Y.prototype.divRound=function(B){var q=this.divmod(B);if(q.mod.isZero())return q.div;var P=q.div.negative!==0?q.mod.isub(B):q.mod,O=B.ushrn(1),w=B.andln(1),k=P.cmp(O);return k<0||w===1&&k===0?q.div:q.div.negative!==0?q.div.isubn(1):q.div.iaddn(1)},Y.prototype.modn=function(B){C(B<=67108863);for(var q=67108864%B,P=0,O=this.length-1;O>=0;O--)P=(q*P+(this.words[O]|0))%B;return P},Y.prototype.idivn=function(B){C(B<=67108863);for(var q=0,P=this.length-1;P>=0;P--){var O=(this.words[P]|0)+q*67108864;this.words[P]=O/B|0,q=O%B}return this.strip()},Y.prototype.divn=function(B){return this.clone().idivn(B)},Y.prototype.egcd=function(B){C(B.negative===0),C(!B.isZero());var q=this,P=B.clone();q.negative!==0?q=q.umod(B):q=q.clone();for(var O=new Y(1),w=new Y(0),k=new Y(0),S=new Y(1),_=0;q.isEven()&&P.isEven();)q.iushrn(1),P.iushrn(1),++_;for(var W=P.clone(),j=q.clone();!q.isZero();){for(var b=0,p=1;(q.words[0]&p)===0&&b<26;++b,p<<=1);if(b>0)for(q.iushrn(b);b-- >0;)(O.isOdd()||w.isOdd())&&(O.iadd(W),w.isub(j)),O.iushrn(1),w.iushrn(1);for(var s=0,r=1;(P.words[0]&r)===0&&s<26;++s,r<<=1);if(s>0)for(P.iushrn(s);s-- >0;)(k.isOdd()||S.isOdd())&&(k.iadd(W),S.isub(j)),k.iushrn(1),S.iushrn(1);q.cmp(P)>=0?(q.isub(P),O.isub(k),w.isub(S)):(P.isub(q),k.isub(O),S.isub(w))}return{a:k,b:S,gcd:P.iushln(_)}},Y.prototype._invmp=function(B){C(B.negative===0),C(!B.isZero());var q=this,P=B.clone();q.negative!==0?q=q.umod(B):q=q.clone();for(var O=new Y(1),w=new Y(0),k=P.clone();q.cmpn(1)>0&&P.cmpn(1)>0;){for(var S=0,_=1;(q.words[0]&_)===0&&S<26;++S,_<<=1);if(S>0)for(q.iushrn(S);S-- >0;)O.isOdd()&&O.iadd(k),O.iushrn(1);for(var W=0,j=1;(P.words[0]&j)===0&&W<26;++W,j<<=1);if(W>0)for(P.iushrn(W);W-- >0;)w.isOdd()&&w.iadd(k),w.iushrn(1);q.cmp(P)>=0?(q.isub(P),O.isub(w)):(P.isub(q),w.isub(O))}var b;return q.cmpn(1)===0?b=O:b=w,b.cmpn(0)<0&&b.iadd(B),b},Y.prototype.gcd=function(B){if(this.isZero())return B.abs();if(B.isZero())return this.abs();var q=this.clone(),P=B.clone();q.negative=0,P.negative=0;for(var O=0;q.isEven()&&P.isEven();O++)q.iushrn(1),P.iushrn(1);do{for(;q.isEven();)q.iushrn(1);for(;P.isEven();)P.iushrn(1);var w=q.cmp(P);if(w<0){var k=q;q=P,P=k}else if(w===0||P.cmpn(1)===0)break;q.isub(P)}while(!0);return P.iushln(O)},Y.prototype.invm=function(B){return this.egcd(B).a.umod(B)},Y.prototype.isEven=function(){return(this.words[0]&1)===0},Y.prototype.isOdd=function(){return(this.words[0]&1)===1},Y.prototype.andln=function(B){return this.words[0]&B},Y.prototype.bincn=function(B){C(typeof B=="number");var q=B%26,P=(B-q)/26,O=1<>>26,S&=67108863,this.words[k]=S}return w!==0&&(this.words[k]=w,this.length++),this},Y.prototype.isZero=function(){return this.length===1&&this.words[0]===0},Y.prototype.cmpn=function(B){var q=B<0;if(this.negative!==0&&!q)return-1;if(this.negative===0&&q)return 1;this.strip();var P;if(this.length>1)P=1;else{q&&(B=-B),C(B<=67108863,"Number is too big");var O=this.words[0]|0;P=O===B?0:OB.length)return 1;if(this.length=0;P--){var O=this.words[P]|0,w=B.words[P]|0;if(O!==w){Ow&&(q=1);break}}return q},Y.prototype.gtn=function(B){return this.cmpn(B)===1},Y.prototype.gt=function(B){return this.cmp(B)===1},Y.prototype.gten=function(B){return this.cmpn(B)>=0},Y.prototype.gte=function(B){return this.cmp(B)>=0},Y.prototype.ltn=function(B){return this.cmpn(B)===-1},Y.prototype.lt=function(B){return this.cmp(B)===-1},Y.prototype.lten=function(B){return this.cmpn(B)<=0},Y.prototype.lte=function(B){return this.cmp(B)<=0},Y.prototype.eqn=function(B){return this.cmpn(B)===0},Y.prototype.eq=function(B){return this.cmp(B)===0},Y.red=function(B){return new d(B)},Y.prototype.toRed=function(B){return C(!this.red,"Already a number in reduction context"),C(this.negative===0,"red works only with positives"),B.convertTo(this)._forceRed(B)},Y.prototype.fromRed=function(){return C(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},Y.prototype._forceRed=function(B){return this.red=B,this},Y.prototype.forceRed=function(B){return C(!this.red,"Already a number in reduction context"),this._forceRed(B)},Y.prototype.redAdd=function(B){return C(this.red,"redAdd works only with red numbers"),this.red.add(this,B)},Y.prototype.redIAdd=function(B){return C(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,B)},Y.prototype.redSub=function(B){return C(this.red,"redSub works only with red numbers"),this.red.sub(this,B)},Y.prototype.redISub=function(B){return C(this.red,"redISub works only with red numbers"),this.red.isub(this,B)},Y.prototype.redShl=function(B){return C(this.red,"redShl works only with red numbers"),this.red.shl(this,B)},Y.prototype.redMul=function(B){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.mul(this,B)},Y.prototype.redIMul=function(B){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.imul(this,B)},Y.prototype.redSqr=function(){return C(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},Y.prototype.redISqr=function(){return C(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},Y.prototype.redSqrt=function(){return C(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},Y.prototype.redInvm=function(){return C(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},Y.prototype.redNeg=function(){return C(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},Y.prototype.redPow=function(B){return C(this.red&&!B.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,B)};var T={k256:null,p224:null,p192:null,p25519:null};function h(B,q){this.name=B,this.p=new Y(q,16),this.n=this.p.bitLength(),this.k=new Y(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}h.prototype._tmp=function(){var B=new Y(null);return B.words=new Array(Math.ceil(this.n/13)),B},h.prototype.ireduce=function(B){var q=B,P;do this.split(q,this.tmp),q=this.imulK(q),q=q.iadd(this.tmp),P=q.bitLength();while(P>this.n);var O=P0?q.isub(this.p):q.strip!==void 0?q.strip():q._strip(),q},h.prototype.split=function(B,q){B.iushrn(this.n,0,q)},h.prototype.imulK=function(B){return B.imul(this.k)};function y(){h.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}U(y,h),y.prototype.split=function(B,q){for(var P=4194303,O=Math.min(B.length,9),w=0;w>>22,k=S}k>>>=22,B.words[w-10]=k,k===0&&B.length>10?B.length-=10:B.length-=9},y.prototype.imulK=function(B){B.words[B.length]=0,B.words[B.length+1]=0,B.length+=2;for(var q=0,P=0;P>>=26,B.words[P]=w,q=O}return q!==0&&(B.words[B.length++]=q),B},Y._prime=function(B){if(T[B])return T[B];var q;if(B==="k256")q=new y;else if(B==="p224")q=new g;else if(B==="p192")q=new f;else if(B==="p25519")q=new u;else throw new Error("Unknown prime "+B);return T[B]=q,q};function d(B){if(typeof B=="string"){var q=Y._prime(B);this.m=q.p,this.prime=q}else C(B.gtn(1),"modulus must be greater than 1"),this.m=B,this.prime=null}d.prototype._verify1=function(B){C(B.negative===0,"red works only with positives"),C(B.red,"red works only with red numbers")},d.prototype._verify2=function(B,q){C((B.negative|q.negative)===0,"red works only with positives"),C(B.red&&B.red===q.red,"red works only with red numbers")},d.prototype.imod=function(B){return this.prime?this.prime.ireduce(B)._forceRed(this):B.umod(this.m)._forceRed(this)},d.prototype.neg=function(B){return B.isZero()?B.clone():this.m.sub(B)._forceRed(this)},d.prototype.add=function(B,q){this._verify2(B,q);var P=B.add(q);return P.cmp(this.m)>=0&&P.isub(this.m),P._forceRed(this)},d.prototype.iadd=function(B,q){this._verify2(B,q);var P=B.iadd(q);return P.cmp(this.m)>=0&&P.isub(this.m),P},d.prototype.sub=function(B,q){this._verify2(B,q);var P=B.sub(q);return P.cmpn(0)<0&&P.iadd(this.m),P._forceRed(this)},d.prototype.isub=function(B,q){this._verify2(B,q);var P=B.isub(q);return P.cmpn(0)<0&&P.iadd(this.m),P},d.prototype.shl=function(B,q){return this._verify1(B),this.imod(B.ushln(q))},d.prototype.imul=function(B,q){return this._verify2(B,q),this.imod(B.imul(q))},d.prototype.mul=function(B,q){return this._verify2(B,q),this.imod(B.mul(q))},d.prototype.isqr=function(B){return this.imul(B,B.clone())},d.prototype.sqr=function(B){return this.mul(B,B)},d.prototype.sqrt=function(B){if(B.isZero())return B.clone();var q=this.m.andln(3);if(C(q%2===1),q===3){var P=this.m.add(new Y(1)).iushrn(2);return this.pow(B,P)}for(var O=this.m.subn(1),w=0;!O.isZero()&&O.andln(1)===0;)w++,O.iushrn(1);C(!O.isZero());var k=new Y(1).toRed(this),S=k.redNeg(),_=this.m.subn(1).iushrn(1),W=this.m.bitLength();for(W=new Y(2*W*W).toRed(this);this.pow(W,_).cmp(S)!==0;)W.redIAdd(S);for(var j=this.pow(W,O),b=this.pow(B,O.addn(1).iushrn(1)),p=this.pow(B,O),s=w;p.cmp(k)!==0;){for(var r=p,A1=0;r.cmp(k)!==0;A1++)r=r.redSqr();C(A1=0;w--){for(var j=q.words[w],b=W-1;b>=0;b--){var p=j>>b&1;if(k!==O[0]&&(k=this.sqr(k)),p===0&&S===0){_=0;continue}S<<=1,S|=p,_++,!(_!==P&&(w!==0||b!==0))&&(k=this.mul(k,O[S]),_=0,S=0)}W=26}return k},d.prototype.convertTo=function(B){var q=B.umod(this.m);return q===B?q.clone():q},d.prototype.convertFrom=function(B){var q=B.clone();return q.red=null,q},Y.mont=function(B){return new n(B)};function n(B){d.call(this,B),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new Y(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}U(n,d),n.prototype.convertTo=function(B){return this.imod(B.ushln(this.shift))},n.prototype.convertFrom=function(B){var q=this.imod(B.mul(this.rinv));return q.red=null,q},n.prototype.imul=function(B,q){if(B.isZero()||q.isZero())return B.words[0]=0,B.length=1,B;var P=B.imul(q),O=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=P.isub(O).iushrn(this.shift),k=w;return w.cmp(this.m)>=0?k=w.isub(this.m):w.cmpn(0)<0&&(k=w.iadd(this.m)),k._forceRed(this)},n.prototype.mul=function(B,q){if(B.isZero()||q.isZero())return new Y(0)._forceRed(this);var P=B.mul(q),O=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=P.isub(O).iushrn(this.shift),k=w;return w.cmp(this.m)>=0?k=w.isub(this.m):w.cmpn(0)<0&&(k=w.iadd(this.m)),k._forceRed(this)},n.prototype.invm=function(B){var q=this.imod(B._invmp(this.m).mul(this.r2));return q._forceRed(this)}})(typeof Q>"u"||Q,A)}),aN=l1((A,Q)=>{var J=A6(),K=J.Buffer,C={},U;for(U in J)!J.hasOwnProperty(U)||U==="SlowBuffer"||U==="Buffer"||(C[U]=J[U]);var Y=C.Buffer={};for(U in K)!K.hasOwnProperty(U)||U==="allocUnsafe"||U==="allocUnsafeSlow"||(Y[U]=K[U]);if(C.Buffer.prototype=K.prototype,(!Y.from||Y.from===Uint8Array.from)&&(Y.from=function(Z,X,E){if(typeof Z=="number")throw new TypeError('The "value" argument must not be of type number. Received type '+typeof Z);if(Z&&typeof Z.length>"u")throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof Z);return K(Z,X,E)}),Y.alloc||(Y.alloc=function(Z,X,E){if(typeof Z!="number")throw new TypeError('The "size" argument must be of type number. Received type '+typeof Z);if(Z<0||Z>=2147483648)throw new RangeError('The value "'+Z+'" is invalid for option "size"');var H=K(Z);return!X||X.length===0?H.fill(0):typeof E=="string"?H.fill(X,E):H.fill(X),H}),!C.kStringMaxLength)try{C.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch{}C.constants||(C.constants={MAX_LENGTH:C.kMaxLength},C.kStringMaxLength&&(C.constants.MAX_STRING_LENGTH=C.kStringMaxLength)),Q.exports=C}),rN=l1((A)=>{var Q=MA();function J(C){this._reporterState={obj:null,path:[],options:C||{},errors:[]}}A.Reporter=J,J.prototype.isError=function(C){return C instanceof K},J.prototype.save=function(){let C=this._reporterState;return{obj:C.obj,pathLen:C.path.length}},J.prototype.restore=function(C){let U=this._reporterState;U.obj=C.obj,U.path=U.path.slice(0,C.pathLen)},J.prototype.enterKey=function(C){return this._reporterState.path.push(C)},J.prototype.exitKey=function(C){let U=this._reporterState;U.path=U.path.slice(0,C-1)},J.prototype.leaveKey=function(C,U,Y){let Z=this._reporterState;this.exitKey(C),Z.obj!==null&&(Z.obj[U]=Y)},J.prototype.path=function(){return this._reporterState.path.join("/")},J.prototype.enterObject=function(){let C=this._reporterState,U=C.obj;return C.obj={},U},J.prototype.leaveObject=function(C){let U=this._reporterState,Y=U.obj;return U.obj=C,Y},J.prototype.error=function(C){let U,Y=this._reporterState,Z=C instanceof K;if(Z?U=C:U=new K(Y.path.map(function(X){return"["+JSON.stringify(X)+"]"}).join(""),C.message||C,C.stack),!Y.options.partial)throw U;return Z||Y.errors.push(U),U},J.prototype.wrapResult=function(C){let U=this._reporterState;return U.options.partial?{result:this.isError(C)?null:C,errors:U.errors}:C};function K(C,U){this.path=C,this.rethrow(U)}Q(K,Error),K.prototype.rethrow=function(C){if(this.message=C+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,K),!this.stack)try{throw new Error(this.message)}catch(U){this.stack=U.stack}return this}}),qU=l1((A)=>{var Q=MA(),J=rN().Reporter,K=aN().Buffer;function C(Y,Z){if(J.call(this,Z),!K.isBuffer(Y)){this.error("Input not Buffer");return}this.base=Y,this.offset=0,this.length=Y.length}Q(C,J),A.DecoderBuffer=C,C.isDecoderBuffer=function(Y){return Y instanceof C?!0:typeof Y=="object"&&K.isBuffer(Y.base)&&Y.constructor.name==="DecoderBuffer"&&typeof Y.offset=="number"&&typeof Y.length=="number"&&typeof Y.save=="function"&&typeof Y.restore=="function"&&typeof Y.isEmpty=="function"&&typeof Y.readUInt8=="function"&&typeof Y.skip=="function"&&typeof Y.raw=="function"},C.prototype.save=function(){return{offset:this.offset,reporter:J.prototype.save.call(this)}},C.prototype.restore=function(Y){let Z=new C(this.base);return Z.offset=Y.offset,Z.length=this.offset,this.offset=Y.offset,J.prototype.restore.call(this,Y.reporter),Z},C.prototype.isEmpty=function(){return this.offset===this.length},C.prototype.readUInt8=function(Y){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(Y||"DecoderBuffer overrun")},C.prototype.skip=function(Y,Z){if(!(this.offset+Y<=this.length))return this.error(Z||"DecoderBuffer overrun");let X=new C(this.base);return X._reporterState=this._reporterState,X.offset=this.offset,X.length=this.offset+Y,this.offset+=Y,X},C.prototype.raw=function(Y){return this.base.slice(Y?Y.offset:this.offset,this.length)};function U(Y,Z){if(Array.isArray(Y))this.length=0,this.value=Y.map(function(X){return U.isEncoderBuffer(X)||(X=new U(X,Z)),this.length+=X.length,X},this);else if(typeof Y=="number"){if(!(0<=Y&&Y<=255))return Z.error("non-byte EncoderBuffer value");this.value=Y,this.length=1}else if(typeof Y=="string")this.value=Y,this.length=K.byteLength(Y);else if(K.isBuffer(Y))this.value=Y,this.length=Y.length;else return Z.error("Unsupported type: "+typeof Y)}A.EncoderBuffer=U,U.isEncoderBuffer=function(Y){return Y instanceof U?!0:typeof Y=="object"&&Y.constructor.name==="EncoderBuffer"&&typeof Y.length=="number"&&typeof Y.join=="function"},U.prototype.join=function(Y,Z){return Y||(Y=K.alloc(this.length)),Z||(Z=0),this.length===0||(Array.isArray(this.value)?this.value.forEach(function(X){X.join(Y,Z),Z+=X.length}):(typeof this.value=="number"?Y[Z]=this.value:typeof this.value=="string"?Y.write(this.value,Z):K.isBuffer(this.value)&&this.value.copy(Y,Z),Z+=this.length)),Y}}),tN=l1((A,Q)=>{var J=rN().Reporter,K=qU().EncoderBuffer,C=qU().DecoderBuffer,U=T9(),Y=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"],Z=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(Y),X=["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"];function E($,I,N){let F={};this._baseState=F,F.name=N,F.enc=$,F.parent=I||null,F.children=null,F.tag=null,F.args=null,F.reverseArgs=null,F.choice=null,F.optional=!1,F.any=!1,F.obj=!1,F.use=null,F.useDecoder=null,F.key=null,F.default=null,F.explicit=null,F.implicit=null,F.contains=null,F.parent||(F.children=[],this._wrap())}Q.exports=E;var H=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];E.prototype.clone=function(){let $=this._baseState,I={};H.forEach(function(F){I[F]=$[F]});let N=new this.constructor(I.parent);return N._baseState=I,N},E.prototype._wrap=function(){let $=this._baseState;Z.forEach(function(I){this[I]=function(){let N=new this.constructor(this);return $.children.push(N),N[I].apply(N,arguments)}},this)},E.prototype._init=function($){let I=this._baseState;U(I.parent===null),$.call(this),I.children=I.children.filter(function(N){return N._baseState.parent===this},this),U.equal(I.children.length,1,"Root node can have only one child")},E.prototype._useArgs=function($){let I=this._baseState,N=$.filter(function(F){return F instanceof this.constructor},this);$=$.filter(function(F){return!(F instanceof this.constructor)},this),N.length!==0&&(U(I.children===null),I.children=N,N.forEach(function(F){F._baseState.parent=this},this)),$.length!==0&&(U(I.args===null),I.args=$,I.reverseArgs=$.map(function(F){if(typeof F!="object"||F.constructor!==Object)return F;let V={};return Object.keys(F).forEach(function(D){D==(D|0)&&(D|=0);let L=F[D];V[L]=D}),V}))},X.forEach(function($){E.prototype[$]=function(){let I=this._baseState;throw new Error($+" not implemented for encoding: "+I.enc)}}),Y.forEach(function($){E.prototype[$]=function(){let I=this._baseState,N=Array.prototype.slice.call(arguments);return U(I.tag===null),I.tag=$,this._useArgs(N),this}}),E.prototype.use=function($){U($);let I=this._baseState;return U(I.use===null),I.use=$,this},E.prototype.optional=function(){let $=this._baseState;return $.optional=!0,this},E.prototype.def=function($){let I=this._baseState;return U(I.default===null),I.default=$,I.optional=!0,this},E.prototype.explicit=function($){let I=this._baseState;return U(I.explicit===null&&I.implicit===null),I.explicit=$,this},E.prototype.implicit=function($){let I=this._baseState;return U(I.explicit===null&&I.implicit===null),I.implicit=$,this},E.prototype.obj=function(){let $=this._baseState,I=Array.prototype.slice.call(arguments);return $.obj=!0,I.length!==0&&this._useArgs(I),this},E.prototype.key=function($){let I=this._baseState;return U(I.key===null),I.key=$,this},E.prototype.any=function(){let $=this._baseState;return $.any=!0,this},E.prototype.choice=function($){let I=this._baseState;return U(I.choice===null),I.choice=$,this._useArgs(Object.keys($).map(function(N){return $[N]})),this},E.prototype.contains=function($){let I=this._baseState;return U(I.use===null),I.contains=$,this},E.prototype._decode=function($,I){let N=this._baseState;if(N.parent===null)return $.wrapResult(N.children[0]._decode($,I));let F=N.default,V=!0,D=null;if(N.key!==null&&(D=$.enterKey(N.key)),N.optional){let R=null;if(N.explicit!==null?R=N.explicit:N.implicit!==null?R=N.implicit:N.tag!==null&&(R=N.tag),R===null&&!N.any){let M=$.save();try{N.choice===null?this._decodeGeneric(N.tag,$,I):this._decodeChoice($,I),V=!0}catch{V=!1}$.restore(M)}else if(V=this._peekTag($,R,N.any),$.isError(V))return V}let L;if(N.obj&&V&&(L=$.enterObject()),V){if(N.explicit!==null){let M=this._decodeTag($,N.explicit);if($.isError(M))return M;$=M}let R=$.offset;if(N.use===null&&N.choice===null){let M;N.any&&(M=$.save());let T=this._decodeTag($,N.implicit!==null?N.implicit:N.tag,N.any);if($.isError(T))return T;N.any?F=$.raw(M):$=T}if(I&&I.track&&N.tag!==null&&I.track($.path(),R,$.length,"tagged"),I&&I.track&&N.tag!==null&&I.track($.path(),$.offset,$.length,"content"),N.any||(N.choice===null?F=this._decodeGeneric(N.tag,$,I):F=this._decodeChoice($,I)),$.isError(F))return F;if(!N.any&&N.choice===null&&N.children!==null&&N.children.forEach(function(M){M._decode($,I)}),N.contains&&(N.tag==="octstr"||N.tag==="bitstr")){let M=new C(F);F=this._getUse(N.contains,$._reporterState.obj)._decode(M,I)}}return N.obj&&V&&(F=$.leaveObject(L)),N.key!==null&&(F!==null||V===!0)?$.leaveKey(D,N.key,F):D!==null&&$.exitKey(D),F},E.prototype._decodeGeneric=function($,I,N){let F=this._baseState;return $==="seq"||$==="set"?null:$==="seqof"||$==="setof"?this._decodeList(I,$,F.args[0],N):/str$/.test($)?this._decodeStr(I,$,N):$==="objid"&&F.args?this._decodeObjid(I,F.args[0],F.args[1],N):$==="objid"?this._decodeObjid(I,null,null,N):$==="gentime"||$==="utctime"?this._decodeTime(I,$,N):$==="null_"?this._decodeNull(I,N):$==="bool"?this._decodeBool(I,N):$==="objDesc"?this._decodeStr(I,$,N):$==="int"||$==="enum"?this._decodeInt(I,F.args&&F.args[0],N):F.use!==null?this._getUse(F.use,I._reporterState.obj)._decode(I,N):I.error("unknown tag: "+$)},E.prototype._getUse=function($,I){let N=this._baseState;return N.useDecoder=this._use($,I),U(N.useDecoder._baseState.parent===null),N.useDecoder=N.useDecoder._baseState.children[0],N.implicit!==N.useDecoder._baseState.implicit&&(N.useDecoder=N.useDecoder.clone(),N.useDecoder._baseState.implicit=N.implicit),N.useDecoder},E.prototype._decodeChoice=function($,I){let N=this._baseState,F=null,V=!1;return Object.keys(N.choice).some(function(D){let L=$.save(),R=N.choice[D];try{let M=R._decode($,I);if($.isError(M))return!1;F={type:D,value:M},V=!0}catch{return $.restore(L),!1}return!0},this),V?F:$.error("Choice not matched")},E.prototype._createEncoderBuffer=function($){return new K($,this.reporter)},E.prototype._encode=function($,I,N){let F=this._baseState;if(F.default!==null&&F.default===$)return;let V=this._encodeValue($,I,N);if(V!==void 0&&!this._skipDefault(V,I,N))return V},E.prototype._encodeValue=function($,I,N){let F=this._baseState;if(F.parent===null)return F.children[0]._encode($,I||new J);let V=null;if(this.reporter=I,F.optional&&$===void 0)if(F.default!==null)$=F.default;else return;let D=null,L=!1;if(F.any)V=this._createEncoderBuffer($);else if(F.choice)V=this._encodeChoice($,I);else if(F.contains)D=this._getUse(F.contains,N)._encode($,I),L=!0;else if(F.children)D=F.children.map(function(R){if(R._baseState.tag==="null_")return R._encode(null,I,$);if(R._baseState.key===null)return I.error("Child should have a key");let M=I.enterKey(R._baseState.key);if(typeof $!="object")return I.error("Child expected, but input is not object");let T=R._encode($[R._baseState.key],I,$);return I.leaveKey(M),T},this).filter(function(R){return R}),D=this._createEncoderBuffer(D);else if(F.tag==="seqof"||F.tag==="setof"){if(!(F.args&&F.args.length===1))return I.error("Too many args for : "+F.tag);if(!Array.isArray($))return I.error("seqof/setof, but data is not Array");let R=this.clone();R._baseState.implicit=null,D=this._createEncoderBuffer($.map(function(M){let T=this._baseState;return this._getUse(T.args[0],$)._encode(M,I)},R))}else F.use!==null?V=this._getUse(F.use,N)._encode($,I):(D=this._encodePrimitive(F.tag,$),L=!0);if(!F.any&&F.choice===null){let R=F.implicit!==null?F.implicit:F.tag,M=F.implicit===null?"universal":"context";R===null?F.use===null&&I.error("Tag could be omitted only for .use()"):F.use===null&&(V=this._encodeComposite(R,L,M,D))}return F.explicit!==null&&(V=this._encodeComposite(F.explicit,!1,"context",V)),V},E.prototype._encodeChoice=function($,I){let N=this._baseState,F=N.choice[$.type];return F||U(!1,$.type+" not found in "+JSON.stringify(Object.keys(N.choice))),F._encode($.value,I)},E.prototype._encodePrimitive=function($,I){let N=this._baseState;if(/str$/.test($))return this._encodeStr(I,$);if($==="objid"&&N.args)return this._encodeObjid(I,N.reverseArgs[0],N.args[1]);if($==="objid")return this._encodeObjid(I,null,null);if($==="gentime"||$==="utctime")return this._encodeTime(I,$);if($==="null_")return this._encodeNull();if($==="int"||$==="enum")return this._encodeInt(I,N.args&&N.reverseArgs[0]);if($==="bool")return this._encodeBool(I);if($==="objDesc")return this._encodeStr(I,$);throw new Error("Unsupported tag: "+$)},E.prototype._isNumstr=function($){return/^[0-9 ]*$/.test($)},E.prototype._isPrintstr=function($){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test($)}}),eN=l1((A)=>{function Q(J){let K={};return Object.keys(J).forEach(function(C){(C|0)==C&&(C=C|0);let U=J[C];K[U]=C}),K}A.tagClass={0:"universal",1:"application",2:"context",3:"private"},A.tagClassByName=Q(A.tagClass),A.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},A.tagByName=Q(A.tag)}),Gy=l1((A,Q)=>{var J=MA(),K=aN().Buffer,C=tN(),U=eN();function Y(H){this.enc="der",this.name=H.name,this.entity=H,this.tree=new Z,this.tree._init(H.body)}Q.exports=Y,Y.prototype.encode=function(H,$){return this.tree._encode(H,$).join()};function Z(H){C.call(this,"der",H)}J(Z,C),Z.prototype._encodeComposite=function(H,$,I,N){let F=E(H,$,I,this.reporter);if(N.length<128){let L=K.alloc(2);return L[0]=F,L[1]=N.length,this._createEncoderBuffer([L,N])}let V=1;for(let L=N.length;L>=256;L>>=8)V++;let D=K.alloc(2+V);D[0]=F,D[1]=128|V;for(let L=1+V,R=N.length;R>0;L--,R>>=8)D[L]=R&255;return this._createEncoderBuffer([D,N])},Z.prototype._encodeStr=function(H,$){if($==="bitstr")return this._createEncoderBuffer([H.unused|0,H.data]);if($==="bmpstr"){let I=K.alloc(H.length*2);for(let N=0;N=40)return this.reporter.error("Second objid identifier OOB");H.splice(0,2,H[0]*40+H[1])}let N=0;for(let D=0;D=128;L>>=7)N++}let F=K.alloc(N),V=F.length-1;for(let D=H.length-1;D>=0;D--){let L=H[D];for(F[V--]=L&127;(L>>=7)>0;)F[V--]=128|L&127}return this._createEncoderBuffer(F)};function X(H){return H<10?"0"+H:H}Z.prototype._encodeTime=function(H,$){let I,N=new Date(H);return $==="gentime"?I=[X(N.getUTCFullYear()),X(N.getUTCMonth()+1),X(N.getUTCDate()),X(N.getUTCHours()),X(N.getUTCMinutes()),X(N.getUTCSeconds()),"Z"].join(""):$==="utctime"?I=[X(N.getUTCFullYear()%100),X(N.getUTCMonth()+1),X(N.getUTCDate()),X(N.getUTCHours()),X(N.getUTCMinutes()),X(N.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+$+" time is not supported yet"),this._encodeStr(I,"octstr")},Z.prototype._encodeNull=function(){return this._createEncoderBuffer("")},Z.prototype._encodeInt=function(H,$){if(typeof H=="string"){if(!$)return this.reporter.error("String int or enum given, but no values map");if(!$.hasOwnProperty(H))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(H));H=$[H]}if(typeof H!="number"&&!K.isBuffer(H)){let F=H.toArray();!H.sign&&F[0]&128&&F.unshift(0),H=K.from(F)}if(K.isBuffer(H)){let F=H.length;H.length===0&&F++;let V=K.alloc(F);return H.copy(V),H.length===0&&(V[0]=0),this._createEncoderBuffer(V)}if(H<128)return this._createEncoderBuffer(H);if(H<256)return this._createEncoderBuffer([0,H]);let I=1;for(let F=H;F>=256;F>>=8)I++;let N=new Array(I);for(let F=N.length-1;F>=0;F--)N[F]=H&255,H>>=8;return N[0]&128&&N.unshift(0),this._createEncoderBuffer(K.from(N))},Z.prototype._encodeBool=function(H){return this._createEncoderBuffer(H?255:0)},Z.prototype._use=function(H,$){return typeof H=="function"&&(H=H($)),H._getEncoder("der").tree},Z.prototype._skipDefault=function(H,$,I){let N=this._baseState,F;if(N.default===null)return!1;let V=H.join();if(N.defaultBuffer===void 0&&(N.defaultBuffer=this._encodeValue(N.default,$,I).join()),V.length!==N.defaultBuffer.length)return!1;for(F=0;F=31?N.error("Multi-octet tag encoding unsupported"):($||(F|=32),F|=U.tagClassByName[I||"universal"]<<6,F)}}),o91=l1((A,Q)=>{var J=MA(),K=Gy();function C(U){K.call(this,U),this.enc="pem"}J(C,K),Q.exports=C,C.prototype.encode=function(U,Y){let Z=K.prototype.encode.call(this,U).toString("base64"),X=["-----BEGIN "+Y.label+"-----"];for(let E=0;E{var Q=A;Q.der=Gy(),Q.pem=o91()}),Iy=l1((A,Q)=>{var J=MA(),K=Hy(),C=qU().DecoderBuffer,U=tN(),Y=eN();function Z($){this.enc="der",this.name=$.name,this.entity=$,this.tree=new X,this.tree._init($.body)}Q.exports=Z,Z.prototype.decode=function($,I){return C.isDecoderBuffer($)||($=new C($,I)),this.tree._decode($,I)};function X($){U.call(this,"der",$)}J(X,U),X.prototype._peekTag=function($,I,N){if($.isEmpty())return!1;let F=$.save(),V=E($,'Failed to peek tag: "'+I+'"');return $.isError(V)?V:($.restore(F),V.tag===I||V.tagStr===I||V.tagStr+"of"===I||N)},X.prototype._decodeTag=function($,I,N){let F=E($,'Failed to decode tag of "'+I+'"');if($.isError(F))return F;let V=H($,F.primitive,'Failed to get length of "'+I+'"');if($.isError(V))return V;if(!N&&F.tag!==I&&F.tagStr!==I&&F.tagStr+"of"!==I)return $.error('Failed to match tag: "'+I+'"');if(F.primitive||V!==null)return $.skip(V,'Failed to match body of: "'+I+'"');let D=$.save(),L=this._skipUntilEnd($,'Failed to skip indefinite length body: "'+this.tag+'"');return $.isError(L)?L:(V=$.offset-D.offset,$.restore(D),$.skip(V,'Failed to match body of: "'+I+'"'))},X.prototype._skipUntilEnd=function($,I){for(;;){let N=E($,I);if($.isError(N))return N;let F=H($,N.primitive,I);if($.isError(F))return F;let V;if(N.primitive||F!==null?V=$.skip(F):V=this._skipUntilEnd($,I),$.isError(V))return V;if(N.tagStr==="end")break}},X.prototype._decodeList=function($,I,N,F){let V=[];for(;!$.isEmpty();){let D=this._peekTag($,"end");if($.isError(D))return D;let L=N.decode($,"der",F);if($.isError(L)&&D)break;V.push(L)}return V},X.prototype._decodeStr=function($,I){if(I==="bitstr"){let N=$.readUInt8();return $.isError(N)?N:{unused:N,data:$.raw()}}else if(I==="bmpstr"){let N=$.raw();if(N.length%2===1)return $.error("Decoding of string type: bmpstr length mismatch");let F="";for(let V=0;V>6],V=(N&32)===0;if((N&31)===31){let L=N;for(N=0;(L&128)===128;){if(L=$.readUInt8(I),$.isError(L))return L;N<<=7,N|=L&127}}else N&=31;let D=Y.tag[N];return{cls:F,primitive:V,tag:N,tagStr:D}}function H($,I,N){let F=$.readUInt8(N);if($.isError(F))return F;if(!I&&F===128)return null;if((F&128)===0)return F;let V=F&127;if(V>4)return $.error("length octect is too long");F=0;for(let D=0;D{var J=MA(),K=aN().Buffer,C=Iy();function U(Y){C.call(this,Y),this.enc="pem"}J(U,C),Q.exports=U,U.prototype.decode=function(Y,Z){let X=Y.toString().split(/[\r\n]+/g),E=Z.label.toUpperCase(),H=/^-----(BEGIN|END) ([^-]+)-----$/,$=-1,I=-1;for(let V=0;V{var Q=A;Q.der=Iy(),Q.pem=i91()}),a91=l1((A)=>{var Q=Wy(),J=qy(),K=MA(),C=A;C.define=function(Y,Z){return new U(Y,Z)};function U(Y,Z){this.name=Y,this.body=Z,this.decoders={},this.encoders={}}U.prototype._createNamed=function(Y){let Z=this.name;function X(E){this._initNamed(E,Z)}return K(X,Y),X.prototype._initNamed=function(E,H){Y.call(this,E,H)},new X(this)},U.prototype._getDecoder=function(Y){return Y=Y||"der",this.decoders.hasOwnProperty(Y)||(this.decoders[Y]=this._createNamed(J[Y])),this.decoders[Y]},U.prototype.decode=function(Y,Z,X){return this._getDecoder(Z).decode(Y,X)},U.prototype._getEncoder=function(Y){return Y=Y||"der",this.encoders.hasOwnProperty(Y)||(this.encoders[Y]=this._createNamed(Q[Y])),this.encoders[Y]},U.prototype.encode=function(Y,Z,X){return this._getEncoder(Z).encode(Y,X)}}),r91=l1((A)=>{var Q=A;Q.Reporter=rN().Reporter,Q.DecoderBuffer=qU().DecoderBuffer,Q.EncoderBuffer=qU().EncoderBuffer,Q.Node=tN()}),t91=l1((A)=>{var Q=A;Q._reverse=function(J){let K={};return Object.keys(J).forEach(function(C){(C|0)==C&&(C=C|0);let U=J[C];K[U]=C}),K},Q.der=eN()}),Oy=l1((A)=>{var Q=A;Q.bignum=Hy(),Q.define=a91().define,Q.base=r91(),Q.constants=t91(),Q.decoders=qy(),Q.encoders=Wy()}),e91=l1((A,Q)=>{var J=Oy(),K=J.define("Time",function(){this.choice({utcTime:this.utctime(),generalTime:this.gentime()})}),C=J.define("AttributeTypeValue",function(){this.seq().obj(this.key("type").objid(),this.key("value").any())}),U=J.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("parameters").optional(),this.key("curve").objid().optional())}),Y=J.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(U),this.key("subjectPublicKey").bitstr())}),Z=J.define("RelativeDistinguishedName",function(){this.setof(C)}),X=J.define("RDNSequence",function(){this.seqof(Z)}),E=J.define("Name",function(){this.choice({rdnSequence:this.use(X)})}),H=J.define("Validity",function(){this.seq().obj(this.key("notBefore").use(K),this.key("notAfter").use(K))}),$=J.define("Extension",function(){this.seq().obj(this.key("extnID").objid(),this.key("critical").bool().def(!1),this.key("extnValue").octstr())}),I=J.define("TBSCertificate",function(){this.seq().obj(this.key("version").explicit(0).int().optional(),this.key("serialNumber").int(),this.key("signature").use(U),this.key("issuer").use(E),this.key("validity").use(H),this.key("subject").use(E),this.key("subjectPublicKeyInfo").use(Y),this.key("issuerUniqueID").implicit(1).bitstr().optional(),this.key("subjectUniqueID").implicit(2).bitstr().optional(),this.key("extensions").explicit(3).seqof($).optional())}),N=J.define("X509Certificate",function(){this.seq().obj(this.key("tbsCertificate").use(I),this.key("signatureAlgorithm").use(U),this.key("signatureValue").bitstr())});Q.exports=N}),A51=l1((A)=>{var Q=Oy();A.certificate=e91();var J=Q.define("RSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("modulus").int(),this.key("publicExponent").int(),this.key("privateExponent").int(),this.key("prime1").int(),this.key("prime2").int(),this.key("exponent1").int(),this.key("exponent2").int(),this.key("coefficient").int())});A.RSAPrivateKey=J;var K=Q.define("RSAPublicKey",function(){this.seq().obj(this.key("modulus").int(),this.key("publicExponent").int())});A.RSAPublicKey=K;var C=Q.define("SubjectPublicKeyInfo",function(){this.seq().obj(this.key("algorithm").use(U),this.key("subjectPublicKey").bitstr())});A.PublicKey=C;var U=Q.define("AlgorithmIdentifier",function(){this.seq().obj(this.key("algorithm").objid(),this.key("none").null_().optional(),this.key("curve").objid().optional(),this.key("params").seq().obj(this.key("p").int(),this.key("q").int(),this.key("g").int()).optional())}),Y=Q.define("PrivateKeyInfo",function(){this.seq().obj(this.key("version").int(),this.key("algorithm").use(U),this.key("subjectPrivateKey").octstr())});A.PrivateKey=Y;var Z=Q.define("EncryptedPrivateKeyInfo",function(){this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(),this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(),this.key("kdeparams").seq().obj(this.key("salt").octstr(),this.key("iters").int())),this.key("cipher").seq().obj(this.key("algo").objid(),this.key("iv").octstr()))),this.key("subjectPrivateKey").octstr())});A.EncryptedPrivateKey=Z;var X=Q.define("DSAPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("p").int(),this.key("q").int(),this.key("g").int(),this.key("pub_key").int(),this.key("priv_key").int())});A.DSAPrivateKey=X,A.DSAparam=Q.define("DSAparam",function(){this.int()});var E=Q.define("ECPrivateKey",function(){this.seq().obj(this.key("version").int(),this.key("privateKey").octstr(),this.key("parameters").optional().explicit(0).use(H),this.key("publicKey").optional().explicit(1).bitstr())});A.ECPrivateKey=E;var H=Q.define("ECParameters",function(){this.choice({namedCurve:this.objid()})});A.signature=Q.define("signature",function(){this.seq().obj(this.key("r").int(),this.key("s").int())})}),Q51=l1((A,Q)=>{Q.exports={"2.16.840.1.101.3.4.1.1":"aes-128-ecb","2.16.840.1.101.3.4.1.2":"aes-128-cbc","2.16.840.1.101.3.4.1.3":"aes-128-ofb","2.16.840.1.101.3.4.1.4":"aes-128-cfb","2.16.840.1.101.3.4.1.21":"aes-192-ecb","2.16.840.1.101.3.4.1.22":"aes-192-cbc","2.16.840.1.101.3.4.1.23":"aes-192-ofb","2.16.840.1.101.3.4.1.24":"aes-192-cfb","2.16.840.1.101.3.4.1.41":"aes-256-ecb","2.16.840.1.101.3.4.1.42":"aes-256-cbc","2.16.840.1.101.3.4.1.43":"aes-256-ofb","2.16.840.1.101.3.4.1.44":"aes-256-cfb"}}),J51=l1((A,Q)=>{var J=/Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m,K=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m,C=/^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m,U=tE(),Y=mN(),Z=bA().Buffer;Q.exports=function(X,E){var H=X.toString(),$=H.match(J),I;if($){var N="aes"+$[1],F=Z.from($[2],"hex"),V=Z.from($[3].replace(/[\r\n]/g,""),"base64"),D=U(E,F.slice(0,8),parseInt($[1],10)).key,L=[],R=Y.createDecipheriv(N,D,F);L.push(R.update(V)),L.push(R.final()),I=Z.concat(L)}else{var M=H.match(C);I=Z.from(M[2].replace(/[\r\n]/g,""),"base64")}var T=H.match(K)[1];return{tag:T,data:I}}}),A$=l1((A,Q)=>{var J=A51(),K=Q51(),C=J51(),U=mN(),Y=lx(),Z=bA().Buffer;Q.exports=X;function X(H){var $;typeof H=="object"&&!Z.isBuffer(H)&&($=H.passphrase,H=H.key),typeof H=="string"&&(H=Z.from(H));var I=C(H,$),N=I.tag,F=I.data,V,D;switch(N){case"CERTIFICATE":D=J.certificate.decode(F,"der").tbsCertificate.subjectPublicKeyInfo;case"PUBLIC KEY":switch(D||(D=J.PublicKey.decode(F,"der")),V=D.algorithm.algorithm.join("."),V){case"1.2.840.113549.1.1.1":return J.RSAPublicKey.decode(D.subjectPublicKey.data,"der");case"1.2.840.10045.2.1":return D.subjectPrivateKey=D.subjectPublicKey,{type:"ec",data:D};case"1.2.840.10040.4.1":return D.algorithm.params.pub_key=J.DSAparam.decode(D.subjectPublicKey.data,"der"),{type:"dsa",data:D.algorithm.params};default:throw new Error("unknown key id "+V)}case"ENCRYPTED PRIVATE KEY":F=J.EncryptedPrivateKey.decode(F,"der"),F=E(F,$);case"PRIVATE KEY":switch(D=J.PrivateKey.decode(F,"der"),V=D.algorithm.algorithm.join("."),V){case"1.2.840.113549.1.1.1":return J.RSAPrivateKey.decode(D.subjectPrivateKey,"der");case"1.2.840.10045.2.1":return{curve:D.algorithm.curve,privateKey:J.ECPrivateKey.decode(D.subjectPrivateKey,"der").privateKey};case"1.2.840.10040.4.1":return D.algorithm.params.priv_key=J.DSAparam.decode(D.subjectPrivateKey,"der"),{type:"dsa",params:D.algorithm.params};default:throw new Error("unknown key id "+V)}case"RSA PUBLIC KEY":return J.RSAPublicKey.decode(F,"der");case"RSA PRIVATE KEY":return J.RSAPrivateKey.decode(F,"der");case"DSA PRIVATE KEY":return{type:"dsa",params:J.DSAPrivateKey.decode(F,"der")};case"EC PRIVATE KEY":return F=J.ECPrivateKey.decode(F,"der"),{curve:F.parameters.value,privateKey:F.privateKey};default:throw new Error("unknown key type "+N)}}X.signature=J.signature;function E(H,$){var I=H.algorithm.decrypt.kde.kdeparams.salt,N=parseInt(H.algorithm.decrypt.kde.kdeparams.iters.toString(),10),F=K[H.algorithm.decrypt.cipher.algo.join(".")],V=H.algorithm.decrypt.cipher.iv,D=H.subjectPrivateKey,L=parseInt(F.split("-")[1],10)/8,R=Y.pbkdf2Sync($,I,N,L,"sha1"),M=U.createDecipheriv(F,R,V),T=[];return T.push(M.update(D)),T.push(M.final()),Z.concat(T)}}),Ny=l1((A,Q)=>{Q.exports={"1.3.132.0.10":"secp256k1","1.3.132.0.33":"p224","1.2.840.10045.3.1.1":"p192","1.2.840.10045.3.1.7":"p256","1.3.132.0.34":"p384","1.3.132.0.35":"p521"}}),K51=l1((A,Q)=>{var J=bA().Buffer,K=fx(),C=nN(),U=iN().ec,Y=lN(),Z=A$(),X=Ny();function E(R,M,T,h,y){var g=Z(M);if(g.curve){if(h!=="ecdsa"&&h!=="ecdsa/rsa")throw new Error("wrong private key type");return H(R,g)}else if(g.type==="dsa"){if(h!=="dsa")throw new Error("wrong private key type");return $(R,g,T)}else if(h!=="rsa"&&h!=="ecdsa/rsa")throw new Error("wrong private key type");R=J.concat([y,R]);for(var f=g.modulus.byteLength(),u=[0,1];R.length+u.length+10&&T.ishrn(h),T}function V(R,M){R=F(R,M),R=R.mod(M);var T=J.from(R.toArray());if(T.length{var J=bA().Buffer,K=lN(),C=iN().ec,U=A$(),Y=Ny();function Z($,I,N,F,V){var D=U(N);if(D.type==="ec"){if(F!=="ecdsa"&&F!=="ecdsa/rsa")throw new Error("wrong public key type");return X($,I,D)}else if(D.type==="dsa"){if(F!=="dsa")throw new Error("wrong public key type");return E($,I,D)}else if(F!=="rsa"&&F!=="ecdsa/rsa")throw new Error("wrong public key type");I=J.concat([V,I]);for(var L=D.modulus.byteLength(),R=[1],M=0;I.length+R.length+2=I)throw new Error("invalid sig")}Q.exports=Z}),Y51=l1((A,Q)=>{var J=bA().Buffer,K=NU(),C=T91(),U=MA(),Y=K51(),Z=C51(),X=px();Object.keys(X).forEach(function(N){X[N].id=J.from(X[N].id,"hex"),X[N.toLowerCase()]=X[N]});function E(N){C.Writable.call(this);var F=X[N];if(!F)throw new Error("Unknown message digest");this._hashType=F.hash,this._hash=K(F.hash),this._tag=F.id,this._signType=F.sign}U(E,C.Writable),E.prototype._write=function(N,F,V){this._hash.update(N),V()},E.prototype.update=function(N,F){return typeof N=="string"&&(N=J.from(N,F)),this._hash.update(N),this},E.prototype.sign=function(N,F){this.end();var V=this._hash.digest(),D=Y(V,N,this._hashType,this._signType,this._tag);return F?D.toString(F):D};function H(N){C.Writable.call(this);var F=X[N];if(!F)throw new Error("Unknown message digest");this._hash=K(F.hash),this._tag=F.id,this._signType=F.sign}U(H,C.Writable),H.prototype._write=function(N,F,V){this._hash.update(N),V()},H.prototype.update=function(N,F){return typeof N=="string"&&(N=J.from(N,F)),this._hash.update(N),this},H.prototype.verify=function(N,F,V){typeof F=="string"&&(F=J.from(F,V)),this.end();var D=this._hash.digest();return Z(F,D,N,this._signType,this._tag)};function $(N){return new E(N)}function I(N){return new H(N)}Q.exports={Sign:$,Verify:I,createSign:$,createVerify:I}}),U51=l1((A,Q)=>{(function(J,K){function C(B,q){if(!B)throw new Error(q||"Assertion failed")}function U(B,q){B.super_=q;var P=function(){};P.prototype=q.prototype,B.prototype=new P,B.prototype.constructor=B}function Y(B,q,P){if(Y.isBN(B))return B;this.negative=0,this.words=null,this.length=0,this.red=null,B!==null&&((q==="le"||q==="be")&&(P=q,q=10),this._init(B||0,q||10,P||"be"))}typeof J=="object"?J.exports=Y:K.BN=Y,Y.BN=Y,Y.wordSize=26;var Z;try{typeof window<"u"&&typeof window.Buffer<"u"?Z=window.Buffer:Z=XQ().Buffer}catch{}Y.isBN=function(B){return B instanceof Y?!0:B!==null&&typeof B=="object"&&B.constructor.wordSize===Y.wordSize&&Array.isArray(B.words)},Y.max=function(B,q){return B.cmp(q)>0?B:q},Y.min=function(B,q){return B.cmp(q)<0?B:q},Y.prototype._init=function(B,q,P){if(typeof B=="number")return this._initNumber(B,q,P);if(typeof B=="object")return this._initArray(B,q,P);q==="hex"&&(q=16),C(q===(q|0)&&q>=2&&q<=36),B=B.toString().replace(/\s+/g,"");var O=0;B[0]==="-"&&(O++,this.negative=1),O=0;O-=3)k=B[O]|B[O-1]<<8|B[O-2]<<16,this.words[w]|=k<>>26-S&67108863,S+=24,S>=26&&(S-=26,w++);else if(P==="le")for(O=0,w=0;O>>26-S&67108863,S+=24,S>=26&&(S-=26,w++);return this.strip()};function X(B,q){var P=B.charCodeAt(q);return P>=65&&P<=70?P-55:P>=97&&P<=102?P-87:P-48&15}function E(B,q,P){var O=X(B,P);return P-1>=q&&(O|=X(B,P-1)<<4),O}Y.prototype._parseHex=function(B,q,P){this.length=Math.ceil((B.length-q)/6),this.words=new Array(this.length);for(var O=0;O=q;O-=2)S=E(B,q,O)<=18?(w-=18,k+=1,this.words[k]|=S>>>26):w+=8;else{var _=B.length-q;for(O=_%2===0?q+1:q;O=18?(w-=18,k+=1,this.words[k]|=S>>>26):w+=8}this.strip()};function H(B,q,P,O){for(var w=0,k=Math.min(B.length,P),S=q;S=49?w+=_-49+10:_>=17?w+=_-17+10:w+=_}return w}Y.prototype._parseBase=function(B,q,P){this.words=[0],this.length=1;for(var O=0,w=1;w<=67108863;w*=q)O++;O--,w=w/q|0;for(var k=B.length-P,S=k%O,_=Math.min(k,k-S)+P,W=0,j=P;j<_;j+=O)W=H(B,j,j+O,q),this.imuln(w),this.words[0]+W<67108864?this.words[0]+=W:this._iaddn(W);if(S!==0){var b=1;for(W=H(B,j,B.length,q),j=0;j1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},Y.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},Y.prototype.inspect=function(){return(this.red?""};var $=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],I=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],N=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];Y.prototype.toString=function(B,q){B=B||10,q=q|0||1;var P;if(B===16||B==="hex"){P="";for(var O=0,w=0,k=0;k>>24-O&16777215,w!==0||k!==this.length-1?P=$[6-_.length]+_+P:P=_+P,O+=2,O>=26&&(O-=26,k--)}for(w!==0&&(P=w.toString(16)+P);P.length%q!==0;)P="0"+P;return this.negative!==0&&(P="-"+P),P}if(B===(B|0)&&B>=2&&B<=36){var W=I[B],j=N[B];P="";var b=this.clone();for(b.negative=0;!b.isZero();){var p=b.modn(j).toString(B);b=b.idivn(j),b.isZero()?P=p+P:P=$[W-p.length]+p+P}for(this.isZero()&&(P="0"+P);P.length%q!==0;)P="0"+P;return this.negative!==0&&(P="-"+P),P}C(!1,"Base should be between 2 and 36")},Y.prototype.toNumber=function(){var B=this.words[0];return this.length===2?B+=this.words[1]*67108864:this.length===3&&this.words[2]===1?B+=4503599627370496+this.words[1]*67108864:this.length>2&&C(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-B:B},Y.prototype.toJSON=function(){return this.toString(16)},Y.prototype.toBuffer=function(B,q){return C(typeof Z<"u"),this.toArrayLike(Z,B,q)},Y.prototype.toArray=function(B,q){return this.toArrayLike(Array,B,q)},Y.prototype.toArrayLike=function(B,q,P){var O=this.byteLength(),w=P||Math.max(1,O);C(O<=w,"byte array longer than desired length"),C(w>0,"Requested array length <= 0"),this.strip();var k=q==="le",S=new B(w),_,W,j=this.clone();if(k){for(W=0;!j.isZero();W++)_=j.andln(255),j.iushrn(8),S[W]=_;for(;W=4096&&(P+=13,q>>>=13),q>=64&&(P+=7,q>>>=7),q>=8&&(P+=4,q>>>=4),q>=2&&(P+=2,q>>>=2),P+q},Y.prototype._zeroBits=function(B){if(B===0)return 26;var q=B,P=0;return(q&8191)===0&&(P+=13,q>>>=13),(q&127)===0&&(P+=7,q>>>=7),(q&15)===0&&(P+=4,q>>>=4),(q&3)===0&&(P+=2,q>>>=2),(q&1)===0&&P++,P},Y.prototype.bitLength=function(){var B=this.words[this.length-1],q=this._countBits(B);return(this.length-1)*26+q};function F(B){for(var q=new Array(B.bitLength()),P=0;P>>w}return q}Y.prototype.zeroBits=function(){if(this.isZero())return 0;for(var B=0,q=0;qB.length?this.clone().ior(B):B.clone().ior(this)},Y.prototype.uor=function(B){return this.length>B.length?this.clone().iuor(B):B.clone().iuor(this)},Y.prototype.iuand=function(B){var q;this.length>B.length?q=B:q=this;for(var P=0;PB.length?this.clone().iand(B):B.clone().iand(this)},Y.prototype.uand=function(B){return this.length>B.length?this.clone().iuand(B):B.clone().iuand(this)},Y.prototype.iuxor=function(B){var q,P;this.length>B.length?(q=this,P=B):(q=B,P=this);for(var O=0;OB.length?this.clone().ixor(B):B.clone().ixor(this)},Y.prototype.uxor=function(B){return this.length>B.length?this.clone().iuxor(B):B.clone().iuxor(this)},Y.prototype.inotn=function(B){C(typeof B=="number"&&B>=0);var q=Math.ceil(B/26)|0,P=B%26;this._expand(q),P>0&&q--;for(var O=0;O0&&(this.words[O]=~this.words[O]&67108863>>26-P),this.strip()},Y.prototype.notn=function(B){return this.clone().inotn(B)},Y.prototype.setn=function(B,q){C(typeof B=="number"&&B>=0);var P=B/26|0,O=B%26;return this._expand(P+1),q?this.words[P]=this.words[P]|1<B.length?(P=this,O=B):(P=B,O=this);for(var w=0,k=0;k>>26;for(;w!==0&&k>>26;if(this.length=P.length,w!==0)this.words[this.length]=w,this.length++;else if(P!==this)for(;kB.length?this.clone().iadd(B):B.clone().iadd(this)},Y.prototype.isub=function(B){if(B.negative!==0){B.negative=0;var q=this.iadd(B);return B.negative=1,q._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(B),this.negative=1,this._normSign();var P=this.cmp(B);if(P===0)return this.negative=0,this.length=1,this.words[0]=0,this;var O,w;P>0?(O=this,w=B):(O=B,w=this);for(var k=0,S=0;S>26,this.words[S]=q&67108863;for(;k!==0&&S>26,this.words[S]=q&67108863;if(k===0&&S>>26,p=W&67108863,s=Math.min(j,q.length-1),r=Math.max(0,j-B.length+1);r<=s;r++){var A1=j-r|0;w=B.words[A1]|0,k=q.words[r]|0,S=w*k+p,b+=S/67108864|0,p=S&67108863}P.words[j]=p|0,W=b|0}return W!==0?P.words[j]=W|0:P.length--,P.strip()}var D=function(B,q,P){var O=B.words,w=q.words,k=P.words,S=0,_,W,j,b=O[0]|0,p=b&8191,s=b>>>13,r=O[1]|0,A1=r&8191,Q1=r>>>13,e=O[2]|0,t=e&8191,U1=e>>>13,O1=O[3]|0,E1=O1&8191,Y1=O1>>>13,i=O[4]|0,c=i&8191,o=i>>>13,C1=O[5]|0,q1=C1&8191,Z1=C1>>>13,j1=O[6]|0,H1=j1&8191,B1=j1>>>13,k1=O[7]|0,D1=k1&8191,G1=k1>>>13,w1=O[8]|0,G=w1&8191,z=w1>>>13,x=O[9]|0,m=x&8191,l=x>>>13,a=w[0]|0,K1=a&8191,F1=a>>>13,R1=w[1]|0,X1=R1&8191,W1=R1>>>13,$1=w[2]|0,N1=$1&8191,_1=$1>>>13,J1=w[3]|0,z1=J1&8191,M1=J1>>>13,L1=w[4]|0,V1=L1&8191,S1=L1>>>13,O0=w[5]|0,h1=O0&8191,b1=O0>>>13,f0=w[6]|0,e1=f0&8191,s1=f0>>>13,o0=w[7]|0,a1=o0&8191,r1=o0>>>13,FA=w[8]|0,K0=FA&8191,J0=FA>>>13,qA=w[9]|0,Q0=qA&8191,A0=qA>>>13;P.negative=B.negative^q.negative,P.length=19,_=Math.imul(p,K1),W=Math.imul(p,F1),W=W+Math.imul(s,K1)|0,j=Math.imul(s,F1);var hA=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(hA>>>26)|0,hA&=67108863,_=Math.imul(A1,K1),W=Math.imul(A1,F1),W=W+Math.imul(Q1,K1)|0,j=Math.imul(Q1,F1),_=_+Math.imul(p,X1)|0,W=W+Math.imul(p,W1)|0,W=W+Math.imul(s,X1)|0,j=j+Math.imul(s,W1)|0;var r0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(r0>>>26)|0,r0&=67108863,_=Math.imul(t,K1),W=Math.imul(t,F1),W=W+Math.imul(U1,K1)|0,j=Math.imul(U1,F1),_=_+Math.imul(A1,X1)|0,W=W+Math.imul(A1,W1)|0,W=W+Math.imul(Q1,X1)|0,j=j+Math.imul(Q1,W1)|0,_=_+Math.imul(p,N1)|0,W=W+Math.imul(p,_1)|0,W=W+Math.imul(s,N1)|0,j=j+Math.imul(s,_1)|0;var EA=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(EA>>>26)|0,EA&=67108863,_=Math.imul(E1,K1),W=Math.imul(E1,F1),W=W+Math.imul(Y1,K1)|0,j=Math.imul(Y1,F1),_=_+Math.imul(t,X1)|0,W=W+Math.imul(t,W1)|0,W=W+Math.imul(U1,X1)|0,j=j+Math.imul(U1,W1)|0,_=_+Math.imul(A1,N1)|0,W=W+Math.imul(A1,_1)|0,W=W+Math.imul(Q1,N1)|0,j=j+Math.imul(Q1,_1)|0,_=_+Math.imul(p,z1)|0,W=W+Math.imul(p,M1)|0,W=W+Math.imul(s,z1)|0,j=j+Math.imul(s,M1)|0;var X2=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(X2>>>26)|0,X2&=67108863,_=Math.imul(c,K1),W=Math.imul(c,F1),W=W+Math.imul(o,K1)|0,j=Math.imul(o,F1),_=_+Math.imul(E1,X1)|0,W=W+Math.imul(E1,W1)|0,W=W+Math.imul(Y1,X1)|0,j=j+Math.imul(Y1,W1)|0,_=_+Math.imul(t,N1)|0,W=W+Math.imul(t,_1)|0,W=W+Math.imul(U1,N1)|0,j=j+Math.imul(U1,_1)|0,_=_+Math.imul(A1,z1)|0,W=W+Math.imul(A1,M1)|0,W=W+Math.imul(Q1,z1)|0,j=j+Math.imul(Q1,M1)|0,_=_+Math.imul(p,V1)|0,W=W+Math.imul(p,S1)|0,W=W+Math.imul(s,V1)|0,j=j+Math.imul(s,S1)|0;var E2=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(E2>>>26)|0,E2&=67108863,_=Math.imul(q1,K1),W=Math.imul(q1,F1),W=W+Math.imul(Z1,K1)|0,j=Math.imul(Z1,F1),_=_+Math.imul(c,X1)|0,W=W+Math.imul(c,W1)|0,W=W+Math.imul(o,X1)|0,j=j+Math.imul(o,W1)|0,_=_+Math.imul(E1,N1)|0,W=W+Math.imul(E1,_1)|0,W=W+Math.imul(Y1,N1)|0,j=j+Math.imul(Y1,_1)|0,_=_+Math.imul(t,z1)|0,W=W+Math.imul(t,M1)|0,W=W+Math.imul(U1,z1)|0,j=j+Math.imul(U1,M1)|0,_=_+Math.imul(A1,V1)|0,W=W+Math.imul(A1,S1)|0,W=W+Math.imul(Q1,V1)|0,j=j+Math.imul(Q1,S1)|0,_=_+Math.imul(p,h1)|0,W=W+Math.imul(p,b1)|0,W=W+Math.imul(s,h1)|0,j=j+Math.imul(s,b1)|0;var T1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(T1>>>26)|0,T1&=67108863,_=Math.imul(H1,K1),W=Math.imul(H1,F1),W=W+Math.imul(B1,K1)|0,j=Math.imul(B1,F1),_=_+Math.imul(q1,X1)|0,W=W+Math.imul(q1,W1)|0,W=W+Math.imul(Z1,X1)|0,j=j+Math.imul(Z1,W1)|0,_=_+Math.imul(c,N1)|0,W=W+Math.imul(c,_1)|0,W=W+Math.imul(o,N1)|0,j=j+Math.imul(o,_1)|0,_=_+Math.imul(E1,z1)|0,W=W+Math.imul(E1,M1)|0,W=W+Math.imul(Y1,z1)|0,j=j+Math.imul(Y1,M1)|0,_=_+Math.imul(t,V1)|0,W=W+Math.imul(t,S1)|0,W=W+Math.imul(U1,V1)|0,j=j+Math.imul(U1,S1)|0,_=_+Math.imul(A1,h1)|0,W=W+Math.imul(A1,b1)|0,W=W+Math.imul(Q1,h1)|0,j=j+Math.imul(Q1,b1)|0,_=_+Math.imul(p,e1)|0,W=W+Math.imul(p,s1)|0,W=W+Math.imul(s,e1)|0,j=j+Math.imul(s,s1)|0;var m1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(m1>>>26)|0,m1&=67108863,_=Math.imul(D1,K1),W=Math.imul(D1,F1),W=W+Math.imul(G1,K1)|0,j=Math.imul(G1,F1),_=_+Math.imul(H1,X1)|0,W=W+Math.imul(H1,W1)|0,W=W+Math.imul(B1,X1)|0,j=j+Math.imul(B1,W1)|0,_=_+Math.imul(q1,N1)|0,W=W+Math.imul(q1,_1)|0,W=W+Math.imul(Z1,N1)|0,j=j+Math.imul(Z1,_1)|0,_=_+Math.imul(c,z1)|0,W=W+Math.imul(c,M1)|0,W=W+Math.imul(o,z1)|0,j=j+Math.imul(o,M1)|0,_=_+Math.imul(E1,V1)|0,W=W+Math.imul(E1,S1)|0,W=W+Math.imul(Y1,V1)|0,j=j+Math.imul(Y1,S1)|0,_=_+Math.imul(t,h1)|0,W=W+Math.imul(t,b1)|0,W=W+Math.imul(U1,h1)|0,j=j+Math.imul(U1,b1)|0,_=_+Math.imul(A1,e1)|0,W=W+Math.imul(A1,s1)|0,W=W+Math.imul(Q1,e1)|0,j=j+Math.imul(Q1,s1)|0,_=_+Math.imul(p,a1)|0,W=W+Math.imul(p,r1)|0,W=W+Math.imul(s,a1)|0,j=j+Math.imul(s,r1)|0;var i1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(i1>>>26)|0,i1&=67108863,_=Math.imul(G,K1),W=Math.imul(G,F1),W=W+Math.imul(z,K1)|0,j=Math.imul(z,F1),_=_+Math.imul(D1,X1)|0,W=W+Math.imul(D1,W1)|0,W=W+Math.imul(G1,X1)|0,j=j+Math.imul(G1,W1)|0,_=_+Math.imul(H1,N1)|0,W=W+Math.imul(H1,_1)|0,W=W+Math.imul(B1,N1)|0,j=j+Math.imul(B1,_1)|0,_=_+Math.imul(q1,z1)|0,W=W+Math.imul(q1,M1)|0,W=W+Math.imul(Z1,z1)|0,j=j+Math.imul(Z1,M1)|0,_=_+Math.imul(c,V1)|0,W=W+Math.imul(c,S1)|0,W=W+Math.imul(o,V1)|0,j=j+Math.imul(o,S1)|0,_=_+Math.imul(E1,h1)|0,W=W+Math.imul(E1,b1)|0,W=W+Math.imul(Y1,h1)|0,j=j+Math.imul(Y1,b1)|0,_=_+Math.imul(t,e1)|0,W=W+Math.imul(t,s1)|0,W=W+Math.imul(U1,e1)|0,j=j+Math.imul(U1,s1)|0,_=_+Math.imul(A1,a1)|0,W=W+Math.imul(A1,r1)|0,W=W+Math.imul(Q1,a1)|0,j=j+Math.imul(Q1,r1)|0,_=_+Math.imul(p,K0)|0,W=W+Math.imul(p,J0)|0,W=W+Math.imul(s,K0)|0,j=j+Math.imul(s,J0)|0;var t1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(t1>>>26)|0,t1&=67108863,_=Math.imul(m,K1),W=Math.imul(m,F1),W=W+Math.imul(l,K1)|0,j=Math.imul(l,F1),_=_+Math.imul(G,X1)|0,W=W+Math.imul(G,W1)|0,W=W+Math.imul(z,X1)|0,j=j+Math.imul(z,W1)|0,_=_+Math.imul(D1,N1)|0,W=W+Math.imul(D1,_1)|0,W=W+Math.imul(G1,N1)|0,j=j+Math.imul(G1,_1)|0,_=_+Math.imul(H1,z1)|0,W=W+Math.imul(H1,M1)|0,W=W+Math.imul(B1,z1)|0,j=j+Math.imul(B1,M1)|0,_=_+Math.imul(q1,V1)|0,W=W+Math.imul(q1,S1)|0,W=W+Math.imul(Z1,V1)|0,j=j+Math.imul(Z1,S1)|0,_=_+Math.imul(c,h1)|0,W=W+Math.imul(c,b1)|0,W=W+Math.imul(o,h1)|0,j=j+Math.imul(o,b1)|0,_=_+Math.imul(E1,e1)|0,W=W+Math.imul(E1,s1)|0,W=W+Math.imul(Y1,e1)|0,j=j+Math.imul(Y1,s1)|0,_=_+Math.imul(t,a1)|0,W=W+Math.imul(t,r1)|0,W=W+Math.imul(U1,a1)|0,j=j+Math.imul(U1,r1)|0,_=_+Math.imul(A1,K0)|0,W=W+Math.imul(A1,J0)|0,W=W+Math.imul(Q1,K0)|0,j=j+Math.imul(Q1,J0)|0,_=_+Math.imul(p,Q0)|0,W=W+Math.imul(p,A0)|0,W=W+Math.imul(s,Q0)|0,j=j+Math.imul(s,A0)|0;var d1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(d1>>>26)|0,d1&=67108863,_=Math.imul(m,X1),W=Math.imul(m,W1),W=W+Math.imul(l,X1)|0,j=Math.imul(l,W1),_=_+Math.imul(G,N1)|0,W=W+Math.imul(G,_1)|0,W=W+Math.imul(z,N1)|0,j=j+Math.imul(z,_1)|0,_=_+Math.imul(D1,z1)|0,W=W+Math.imul(D1,M1)|0,W=W+Math.imul(G1,z1)|0,j=j+Math.imul(G1,M1)|0,_=_+Math.imul(H1,V1)|0,W=W+Math.imul(H1,S1)|0,W=W+Math.imul(B1,V1)|0,j=j+Math.imul(B1,S1)|0,_=_+Math.imul(q1,h1)|0,W=W+Math.imul(q1,b1)|0,W=W+Math.imul(Z1,h1)|0,j=j+Math.imul(Z1,b1)|0,_=_+Math.imul(c,e1)|0,W=W+Math.imul(c,s1)|0,W=W+Math.imul(o,e1)|0,j=j+Math.imul(o,s1)|0,_=_+Math.imul(E1,a1)|0,W=W+Math.imul(E1,r1)|0,W=W+Math.imul(Y1,a1)|0,j=j+Math.imul(Y1,r1)|0,_=_+Math.imul(t,K0)|0,W=W+Math.imul(t,J0)|0,W=W+Math.imul(U1,K0)|0,j=j+Math.imul(U1,J0)|0,_=_+Math.imul(A1,Q0)|0,W=W+Math.imul(A1,A0)|0,W=W+Math.imul(Q1,Q0)|0,j=j+Math.imul(Q1,A0)|0;var H0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(H0>>>26)|0,H0&=67108863,_=Math.imul(m,N1),W=Math.imul(m,_1),W=W+Math.imul(l,N1)|0,j=Math.imul(l,_1),_=_+Math.imul(G,z1)|0,W=W+Math.imul(G,M1)|0,W=W+Math.imul(z,z1)|0,j=j+Math.imul(z,M1)|0,_=_+Math.imul(D1,V1)|0,W=W+Math.imul(D1,S1)|0,W=W+Math.imul(G1,V1)|0,j=j+Math.imul(G1,S1)|0,_=_+Math.imul(H1,h1)|0,W=W+Math.imul(H1,b1)|0,W=W+Math.imul(B1,h1)|0,j=j+Math.imul(B1,b1)|0,_=_+Math.imul(q1,e1)|0,W=W+Math.imul(q1,s1)|0,W=W+Math.imul(Z1,e1)|0,j=j+Math.imul(Z1,s1)|0,_=_+Math.imul(c,a1)|0,W=W+Math.imul(c,r1)|0,W=W+Math.imul(o,a1)|0,j=j+Math.imul(o,r1)|0,_=_+Math.imul(E1,K0)|0,W=W+Math.imul(E1,J0)|0,W=W+Math.imul(Y1,K0)|0,j=j+Math.imul(Y1,J0)|0,_=_+Math.imul(t,Q0)|0,W=W+Math.imul(t,A0)|0,W=W+Math.imul(U1,Q0)|0,j=j+Math.imul(U1,A0)|0;var R0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(R0>>>26)|0,R0&=67108863,_=Math.imul(m,z1),W=Math.imul(m,M1),W=W+Math.imul(l,z1)|0,j=Math.imul(l,M1),_=_+Math.imul(G,V1)|0,W=W+Math.imul(G,S1)|0,W=W+Math.imul(z,V1)|0,j=j+Math.imul(z,S1)|0,_=_+Math.imul(D1,h1)|0,W=W+Math.imul(D1,b1)|0,W=W+Math.imul(G1,h1)|0,j=j+Math.imul(G1,b1)|0,_=_+Math.imul(H1,e1)|0,W=W+Math.imul(H1,s1)|0,W=W+Math.imul(B1,e1)|0,j=j+Math.imul(B1,s1)|0,_=_+Math.imul(q1,a1)|0,W=W+Math.imul(q1,r1)|0,W=W+Math.imul(Z1,a1)|0,j=j+Math.imul(Z1,r1)|0,_=_+Math.imul(c,K0)|0,W=W+Math.imul(c,J0)|0,W=W+Math.imul(o,K0)|0,j=j+Math.imul(o,J0)|0,_=_+Math.imul(E1,Q0)|0,W=W+Math.imul(E1,A0)|0,W=W+Math.imul(Y1,Q0)|0,j=j+Math.imul(Y1,A0)|0;var D0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(D0>>>26)|0,D0&=67108863,_=Math.imul(m,V1),W=Math.imul(m,S1),W=W+Math.imul(l,V1)|0,j=Math.imul(l,S1),_=_+Math.imul(G,h1)|0,W=W+Math.imul(G,b1)|0,W=W+Math.imul(z,h1)|0,j=j+Math.imul(z,b1)|0,_=_+Math.imul(D1,e1)|0,W=W+Math.imul(D1,s1)|0,W=W+Math.imul(G1,e1)|0,j=j+Math.imul(G1,s1)|0,_=_+Math.imul(H1,a1)|0,W=W+Math.imul(H1,r1)|0,W=W+Math.imul(B1,a1)|0,j=j+Math.imul(B1,r1)|0,_=_+Math.imul(q1,K0)|0,W=W+Math.imul(q1,J0)|0,W=W+Math.imul(Z1,K0)|0,j=j+Math.imul(Z1,J0)|0,_=_+Math.imul(c,Q0)|0,W=W+Math.imul(c,A0)|0,W=W+Math.imul(o,Q0)|0,j=j+Math.imul(o,A0)|0;var P0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(P0>>>26)|0,P0&=67108863,_=Math.imul(m,h1),W=Math.imul(m,b1),W=W+Math.imul(l,h1)|0,j=Math.imul(l,b1),_=_+Math.imul(G,e1)|0,W=W+Math.imul(G,s1)|0,W=W+Math.imul(z,e1)|0,j=j+Math.imul(z,s1)|0,_=_+Math.imul(D1,a1)|0,W=W+Math.imul(D1,r1)|0,W=W+Math.imul(G1,a1)|0,j=j+Math.imul(G1,r1)|0,_=_+Math.imul(H1,K0)|0,W=W+Math.imul(H1,J0)|0,W=W+Math.imul(B1,K0)|0,j=j+Math.imul(B1,J0)|0,_=_+Math.imul(q1,Q0)|0,W=W+Math.imul(q1,A0)|0,W=W+Math.imul(Z1,Q0)|0,j=j+Math.imul(Z1,A0)|0;var j0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(j0>>>26)|0,j0&=67108863,_=Math.imul(m,e1),W=Math.imul(m,s1),W=W+Math.imul(l,e1)|0,j=Math.imul(l,s1),_=_+Math.imul(G,a1)|0,W=W+Math.imul(G,r1)|0,W=W+Math.imul(z,a1)|0,j=j+Math.imul(z,r1)|0,_=_+Math.imul(D1,K0)|0,W=W+Math.imul(D1,J0)|0,W=W+Math.imul(G1,K0)|0,j=j+Math.imul(G1,J0)|0,_=_+Math.imul(H1,Q0)|0,W=W+Math.imul(H1,A0)|0,W=W+Math.imul(B1,Q0)|0,j=j+Math.imul(B1,A0)|0;var v0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(v0>>>26)|0,v0&=67108863,_=Math.imul(m,a1),W=Math.imul(m,r1),W=W+Math.imul(l,a1)|0,j=Math.imul(l,r1),_=_+Math.imul(G,K0)|0,W=W+Math.imul(G,J0)|0,W=W+Math.imul(z,K0)|0,j=j+Math.imul(z,J0)|0,_=_+Math.imul(D1,Q0)|0,W=W+Math.imul(D1,A0)|0,W=W+Math.imul(G1,Q0)|0,j=j+Math.imul(G1,A0)|0;var S0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(S0>>>26)|0,S0&=67108863,_=Math.imul(m,K0),W=Math.imul(m,J0),W=W+Math.imul(l,K0)|0,j=Math.imul(l,J0),_=_+Math.imul(G,Q0)|0,W=W+Math.imul(G,A0)|0,W=W+Math.imul(z,Q0)|0,j=j+Math.imul(z,A0)|0;var n0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(n0>>>26)|0,n0&=67108863,_=Math.imul(m,Q0),W=Math.imul(m,A0),W=W+Math.imul(l,Q0)|0,j=Math.imul(l,A0);var i0=(S+_|0)+((W&8191)<<13)|0;return S=(j+(W>>>13)|0)+(i0>>>26)|0,i0&=67108863,k[0]=hA,k[1]=r0,k[2]=EA,k[3]=X2,k[4]=E2,k[5]=T1,k[6]=m1,k[7]=i1,k[8]=t1,k[9]=d1,k[10]=H0,k[11]=R0,k[12]=D0,k[13]=P0,k[14]=j0,k[15]=v0,k[16]=S0,k[17]=n0,k[18]=i0,S!==0&&(k[19]=S,P.length++),P};Math.imul||(D=V);function L(B,q,P){P.negative=q.negative^B.negative,P.length=B.length+q.length;for(var O=0,w=0,k=0;k>>26)|0,w+=S>>>26,S&=67108863}P.words[k]=_,O=S,S=w}return O!==0?P.words[k]=O:P.length--,P.strip()}function R(B,q,P){var O=new M;return O.mulp(B,q,P)}Y.prototype.mulTo=function(B,q){var P,O=this.length+B.length;return this.length===10&&B.length===10?P=D(this,B,q):O<63?P=V(this,B,q):O<1024?P=L(this,B,q):P=R(this,B,q),P};function M(B,q){this.x=B,this.y=q}M.prototype.makeRBT=function(B){for(var q=new Array(B),P=Y.prototype._countBits(B)-1,O=0;O>=1;return O},M.prototype.permute=function(B,q,P,O,w,k){for(var S=0;S>>1)w++;return 1<>>13,P[2*k+1]=w&8191,w=w>>>13;for(k=2*q;k>=26,q+=O/67108864|0,q+=w>>>26,this.words[P]=w&67108863}return q!==0&&(this.words[P]=q,this.length++),this},Y.prototype.muln=function(B){return this.clone().imuln(B)},Y.prototype.sqr=function(){return this.mul(this)},Y.prototype.isqr=function(){return this.imul(this.clone())},Y.prototype.pow=function(B){var q=F(B);if(q.length===0)return new Y(1);for(var P=this,O=0;O=0);var q=B%26,P=(B-q)/26,O=67108863>>>26-q<<26-q,w;if(q!==0){var k=0;for(w=0;w>>26-q}k&&(this.words[w]=k,this.length++)}if(P!==0){for(w=this.length-1;w>=0;w--)this.words[w+P]=this.words[w];for(w=0;w=0);var O;q?O=(q-q%26)/26:O=0;var w=B%26,k=Math.min((B-w)/26,this.length),S=67108863^67108863>>>w<k)for(this.length-=k,W=0;W=0&&(j!==0||W>=O);W--){var b=this.words[W]|0;this.words[W]=j<<26-w|b>>>w,j=b&S}return _&&j!==0&&(_.words[_.length++]=j),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},Y.prototype.ishrn=function(B,q,P){return C(this.negative===0),this.iushrn(B,q,P)},Y.prototype.shln=function(B){return this.clone().ishln(B)},Y.prototype.ushln=function(B){return this.clone().iushln(B)},Y.prototype.shrn=function(B){return this.clone().ishrn(B)},Y.prototype.ushrn=function(B){return this.clone().iushrn(B)},Y.prototype.testn=function(B){C(typeof B=="number"&&B>=0);var q=B%26,P=(B-q)/26,O=1<=0);var q=B%26,P=(B-q)/26;if(C(this.negative===0,"imaskn works only with positive numbers"),this.length<=P)return this;if(q!==0&&P++,this.length=Math.min(P,this.length),q!==0){var O=67108863^67108863>>>q<=67108864;q++)this.words[q]-=67108864,q===this.length-1?this.words[q+1]=1:this.words[q+1]++;return this.length=Math.max(this.length,q+1),this},Y.prototype.isubn=function(B){if(C(typeof B=="number"),C(B<67108864),B<0)return this.iaddn(-B);if(this.negative!==0)return this.negative=0,this.iaddn(B),this.negative=1,this;if(this.words[0]-=B,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var q=0;q>26)-(_/67108864|0),this.words[w+P]=k&67108863}for(;w>26,this.words[w+P]=k&67108863;if(S===0)return this.strip();for(C(S===-1),S=0,w=0;w>26,this.words[w]=k&67108863;return this.negative=1,this.strip()},Y.prototype._wordDiv=function(B,q){var P=this.length-B.length,O=this.clone(),w=B,k=w.words[w.length-1]|0,S=this._countBits(k);P=26-S,P!==0&&(w=w.ushln(P),O.iushln(P),k=w.words[w.length-1]|0);var _=O.length-w.length,W;if(q!=="mod"){W=new Y(null),W.length=_+1,W.words=new Array(W.length);for(var j=0;j=0;p--){var s=(O.words[w.length+p]|0)*67108864+(O.words[w.length+p-1]|0);for(s=Math.min(s/k|0,67108863),O._ishlnsubmul(w,s,p);O.negative!==0;)s--,O.negative=0,O._ishlnsubmul(w,1,p),O.isZero()||(O.negative^=1);W&&(W.words[p]=s)}return W&&W.strip(),O.strip(),q!=="div"&&P!==0&&O.iushrn(P),{div:W||null,mod:O}},Y.prototype.divmod=function(B,q,P){if(C(!B.isZero()),this.isZero())return{div:new Y(0),mod:new Y(0)};var O,w,k;return this.negative!==0&&B.negative===0?(k=this.neg().divmod(B,q),q!=="mod"&&(O=k.div.neg()),q!=="div"&&(w=k.mod.neg(),P&&w.negative!==0&&w.iadd(B)),{div:O,mod:w}):this.negative===0&&B.negative!==0?(k=this.divmod(B.neg(),q),q!=="mod"&&(O=k.div.neg()),{div:O,mod:k.mod}):(this.negative&B.negative)!==0?(k=this.neg().divmod(B.neg(),q),q!=="div"&&(w=k.mod.neg(),P&&w.negative!==0&&w.isub(B)),{div:k.div,mod:w}):B.length>this.length||this.cmp(B)<0?{div:new Y(0),mod:this}:B.length===1?q==="div"?{div:this.divn(B.words[0]),mod:null}:q==="mod"?{div:null,mod:new Y(this.modn(B.words[0]))}:{div:this.divn(B.words[0]),mod:new Y(this.modn(B.words[0]))}:this._wordDiv(B,q)},Y.prototype.div=function(B){return this.divmod(B,"div",!1).div},Y.prototype.mod=function(B){return this.divmod(B,"mod",!1).mod},Y.prototype.umod=function(B){return this.divmod(B,"mod",!0).mod},Y.prototype.divRound=function(B){var q=this.divmod(B);if(q.mod.isZero())return q.div;var P=q.div.negative!==0?q.mod.isub(B):q.mod,O=B.ushrn(1),w=B.andln(1),k=P.cmp(O);return k<0||w===1&&k===0?q.div:q.div.negative!==0?q.div.isubn(1):q.div.iaddn(1)},Y.prototype.modn=function(B){C(B<=67108863);for(var q=67108864%B,P=0,O=this.length-1;O>=0;O--)P=(q*P+(this.words[O]|0))%B;return P},Y.prototype.idivn=function(B){C(B<=67108863);for(var q=0,P=this.length-1;P>=0;P--){var O=(this.words[P]|0)+q*67108864;this.words[P]=O/B|0,q=O%B}return this.strip()},Y.prototype.divn=function(B){return this.clone().idivn(B)},Y.prototype.egcd=function(B){C(B.negative===0),C(!B.isZero());var q=this,P=B.clone();q.negative!==0?q=q.umod(B):q=q.clone();for(var O=new Y(1),w=new Y(0),k=new Y(0),S=new Y(1),_=0;q.isEven()&&P.isEven();)q.iushrn(1),P.iushrn(1),++_;for(var W=P.clone(),j=q.clone();!q.isZero();){for(var b=0,p=1;(q.words[0]&p)===0&&b<26;++b,p<<=1);if(b>0)for(q.iushrn(b);b-- >0;)(O.isOdd()||w.isOdd())&&(O.iadd(W),w.isub(j)),O.iushrn(1),w.iushrn(1);for(var s=0,r=1;(P.words[0]&r)===0&&s<26;++s,r<<=1);if(s>0)for(P.iushrn(s);s-- >0;)(k.isOdd()||S.isOdd())&&(k.iadd(W),S.isub(j)),k.iushrn(1),S.iushrn(1);q.cmp(P)>=0?(q.isub(P),O.isub(k),w.isub(S)):(P.isub(q),k.isub(O),S.isub(w))}return{a:k,b:S,gcd:P.iushln(_)}},Y.prototype._invmp=function(B){C(B.negative===0),C(!B.isZero());var q=this,P=B.clone();q.negative!==0?q=q.umod(B):q=q.clone();for(var O=new Y(1),w=new Y(0),k=P.clone();q.cmpn(1)>0&&P.cmpn(1)>0;){for(var S=0,_=1;(q.words[0]&_)===0&&S<26;++S,_<<=1);if(S>0)for(q.iushrn(S);S-- >0;)O.isOdd()&&O.iadd(k),O.iushrn(1);for(var W=0,j=1;(P.words[0]&j)===0&&W<26;++W,j<<=1);if(W>0)for(P.iushrn(W);W-- >0;)w.isOdd()&&w.iadd(k),w.iushrn(1);q.cmp(P)>=0?(q.isub(P),O.isub(w)):(P.isub(q),w.isub(O))}var b;return q.cmpn(1)===0?b=O:b=w,b.cmpn(0)<0&&b.iadd(B),b},Y.prototype.gcd=function(B){if(this.isZero())return B.abs();if(B.isZero())return this.abs();var q=this.clone(),P=B.clone();q.negative=0,P.negative=0;for(var O=0;q.isEven()&&P.isEven();O++)q.iushrn(1),P.iushrn(1);do{for(;q.isEven();)q.iushrn(1);for(;P.isEven();)P.iushrn(1);var w=q.cmp(P);if(w<0){var k=q;q=P,P=k}else if(w===0||P.cmpn(1)===0)break;q.isub(P)}while(!0);return P.iushln(O)},Y.prototype.invm=function(B){return this.egcd(B).a.umod(B)},Y.prototype.isEven=function(){return(this.words[0]&1)===0},Y.prototype.isOdd=function(){return(this.words[0]&1)===1},Y.prototype.andln=function(B){return this.words[0]&B},Y.prototype.bincn=function(B){C(typeof B=="number");var q=B%26,P=(B-q)/26,O=1<>>26,S&=67108863,this.words[k]=S}return w!==0&&(this.words[k]=w,this.length++),this},Y.prototype.isZero=function(){return this.length===1&&this.words[0]===0},Y.prototype.cmpn=function(B){var q=B<0;if(this.negative!==0&&!q)return-1;if(this.negative===0&&q)return 1;this.strip();var P;if(this.length>1)P=1;else{q&&(B=-B),C(B<=67108863,"Number is too big");var O=this.words[0]|0;P=O===B?0:OB.length)return 1;if(this.length=0;P--){var O=this.words[P]|0,w=B.words[P]|0;if(O!==w){Ow&&(q=1);break}}return q},Y.prototype.gtn=function(B){return this.cmpn(B)===1},Y.prototype.gt=function(B){return this.cmp(B)===1},Y.prototype.gten=function(B){return this.cmpn(B)>=0},Y.prototype.gte=function(B){return this.cmp(B)>=0},Y.prototype.ltn=function(B){return this.cmpn(B)===-1},Y.prototype.lt=function(B){return this.cmp(B)===-1},Y.prototype.lten=function(B){return this.cmpn(B)<=0},Y.prototype.lte=function(B){return this.cmp(B)<=0},Y.prototype.eqn=function(B){return this.cmpn(B)===0},Y.prototype.eq=function(B){return this.cmp(B)===0},Y.red=function(B){return new d(B)},Y.prototype.toRed=function(B){return C(!this.red,"Already a number in reduction context"),C(this.negative===0,"red works only with positives"),B.convertTo(this)._forceRed(B)},Y.prototype.fromRed=function(){return C(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},Y.prototype._forceRed=function(B){return this.red=B,this},Y.prototype.forceRed=function(B){return C(!this.red,"Already a number in reduction context"),this._forceRed(B)},Y.prototype.redAdd=function(B){return C(this.red,"redAdd works only with red numbers"),this.red.add(this,B)},Y.prototype.redIAdd=function(B){return C(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,B)},Y.prototype.redSub=function(B){return C(this.red,"redSub works only with red numbers"),this.red.sub(this,B)},Y.prototype.redISub=function(B){return C(this.red,"redISub works only with red numbers"),this.red.isub(this,B)},Y.prototype.redShl=function(B){return C(this.red,"redShl works only with red numbers"),this.red.shl(this,B)},Y.prototype.redMul=function(B){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.mul(this,B)},Y.prototype.redIMul=function(B){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.imul(this,B)},Y.prototype.redSqr=function(){return C(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},Y.prototype.redISqr=function(){return C(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},Y.prototype.redSqrt=function(){return C(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},Y.prototype.redInvm=function(){return C(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},Y.prototype.redNeg=function(){return C(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},Y.prototype.redPow=function(B){return C(this.red&&!B.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,B)};var T={k256:null,p224:null,p192:null,p25519:null};function h(B,q){this.name=B,this.p=new Y(q,16),this.n=this.p.bitLength(),this.k=new Y(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}h.prototype._tmp=function(){var B=new Y(null);return B.words=new Array(Math.ceil(this.n/13)),B},h.prototype.ireduce=function(B){var q=B,P;do this.split(q,this.tmp),q=this.imulK(q),q=q.iadd(this.tmp),P=q.bitLength();while(P>this.n);var O=P0?q.isub(this.p):q.strip!==void 0?q.strip():q._strip(),q},h.prototype.split=function(B,q){B.iushrn(this.n,0,q)},h.prototype.imulK=function(B){return B.imul(this.k)};function y(){h.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}U(y,h),y.prototype.split=function(B,q){for(var P=4194303,O=Math.min(B.length,9),w=0;w>>22,k=S}k>>>=22,B.words[w-10]=k,k===0&&B.length>10?B.length-=10:B.length-=9},y.prototype.imulK=function(B){B.words[B.length]=0,B.words[B.length+1]=0,B.length+=2;for(var q=0,P=0;P>>=26,B.words[P]=w,q=O}return q!==0&&(B.words[B.length++]=q),B},Y._prime=function(B){if(T[B])return T[B];var q;if(B==="k256")q=new y;else if(B==="p224")q=new g;else if(B==="p192")q=new f;else if(B==="p25519")q=new u;else throw new Error("Unknown prime "+B);return T[B]=q,q};function d(B){if(typeof B=="string"){var q=Y._prime(B);this.m=q.p,this.prime=q}else C(B.gtn(1),"modulus must be greater than 1"),this.m=B,this.prime=null}d.prototype._verify1=function(B){C(B.negative===0,"red works only with positives"),C(B.red,"red works only with red numbers")},d.prototype._verify2=function(B,q){C((B.negative|q.negative)===0,"red works only with positives"),C(B.red&&B.red===q.red,"red works only with red numbers")},d.prototype.imod=function(B){return this.prime?this.prime.ireduce(B)._forceRed(this):B.umod(this.m)._forceRed(this)},d.prototype.neg=function(B){return B.isZero()?B.clone():this.m.sub(B)._forceRed(this)},d.prototype.add=function(B,q){this._verify2(B,q);var P=B.add(q);return P.cmp(this.m)>=0&&P.isub(this.m),P._forceRed(this)},d.prototype.iadd=function(B,q){this._verify2(B,q);var P=B.iadd(q);return P.cmp(this.m)>=0&&P.isub(this.m),P},d.prototype.sub=function(B,q){this._verify2(B,q);var P=B.sub(q);return P.cmpn(0)<0&&P.iadd(this.m),P._forceRed(this)},d.prototype.isub=function(B,q){this._verify2(B,q);var P=B.isub(q);return P.cmpn(0)<0&&P.iadd(this.m),P},d.prototype.shl=function(B,q){return this._verify1(B),this.imod(B.ushln(q))},d.prototype.imul=function(B,q){return this._verify2(B,q),this.imod(B.imul(q))},d.prototype.mul=function(B,q){return this._verify2(B,q),this.imod(B.mul(q))},d.prototype.isqr=function(B){return this.imul(B,B.clone())},d.prototype.sqr=function(B){return this.mul(B,B)},d.prototype.sqrt=function(B){if(B.isZero())return B.clone();var q=this.m.andln(3);if(C(q%2===1),q===3){var P=this.m.add(new Y(1)).iushrn(2);return this.pow(B,P)}for(var O=this.m.subn(1),w=0;!O.isZero()&&O.andln(1)===0;)w++,O.iushrn(1);C(!O.isZero());var k=new Y(1).toRed(this),S=k.redNeg(),_=this.m.subn(1).iushrn(1),W=this.m.bitLength();for(W=new Y(2*W*W).toRed(this);this.pow(W,_).cmp(S)!==0;)W.redIAdd(S);for(var j=this.pow(W,O),b=this.pow(B,O.addn(1).iushrn(1)),p=this.pow(B,O),s=w;p.cmp(k)!==0;){for(var r=p,A1=0;r.cmp(k)!==0;A1++)r=r.redSqr();C(A1=0;w--){for(var j=q.words[w],b=W-1;b>=0;b--){var p=j>>b&1;if(k!==O[0]&&(k=this.sqr(k)),p===0&&S===0){_=0;continue}S<<=1,S|=p,_++,!(_!==P&&(w!==0||b!==0))&&(k=this.mul(k,O[S]),_=0,S=0)}W=26}return k},d.prototype.convertTo=function(B){var q=B.umod(this.m);return q===B?q.clone():q},d.prototype.convertFrom=function(B){var q=B.clone();return q.red=null,q},Y.mont=function(B){return new n(B)};function n(B){d.call(this,B),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new Y(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}U(n,d),n.prototype.convertTo=function(B){return this.imod(B.ushln(this.shift))},n.prototype.convertFrom=function(B){var q=this.imod(B.mul(this.rinv));return q.red=null,q},n.prototype.imul=function(B,q){if(B.isZero()||q.isZero())return B.words[0]=0,B.length=1,B;var P=B.imul(q),O=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=P.isub(O).iushrn(this.shift),k=w;return w.cmp(this.m)>=0?k=w.isub(this.m):w.cmpn(0)<0&&(k=w.iadd(this.m)),k._forceRed(this)},n.prototype.mul=function(B,q){if(B.isZero()||q.isZero())return new Y(0)._forceRed(this);var P=B.mul(q),O=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=P.isub(O).iushrn(this.shift),k=w;return w.cmp(this.m)>=0?k=w.isub(this.m):w.cmpn(0)<0&&(k=w.iadd(this.m)),k._forceRed(this)},n.prototype.invm=function(B){var q=this.imod(B._invmp(this.m).mul(this.r2));return q._forceRed(this)}})(typeof Q>"u"||Q,A)}),Z51=l1((A,Q)=>{var J=iN(),K=U51();Q.exports=function(Z){return new U(Z)};var C={secp256k1:{name:"secp256k1",byteLength:32},secp224r1:{name:"p224",byteLength:28},prime256v1:{name:"p256",byteLength:32},prime192v1:{name:"p192",byteLength:24},ed25519:{name:"ed25519",byteLength:32},secp384r1:{name:"p384",byteLength:48},secp521r1:{name:"p521",byteLength:66}};C.p224=C.secp224r1,C.p256=C.secp256r1=C.prime256v1,C.p192=C.secp192r1=C.prime192v1,C.p384=C.secp384r1,C.p521=C.secp521r1;function U(Z){this.curveType=C[Z],this.curveType||(this.curveType={name:Z}),this.curve=new J.ec(this.curveType.name),this.keys=void 0}U.prototype.generateKeys=function(Z,X){return this.keys=this.curve.genKeyPair(),this.getPublicKey(Z,X)},U.prototype.computeSecret=function(Z,X,E){X=X||"utf8",Buffer.isBuffer(Z)||(Z=new Buffer(Z,X));var H=this.curve.keyFromPublic(Z).getPublic(),$=H.mul(this.keys.getPrivate()).getX();return Y($,E,this.curveType.byteLength)},U.prototype.getPublicKey=function(Z,X){var E=this.keys.getPublic(X==="compressed",!0);return X==="hybrid"&&(E[E.length-1]%2?E[0]=7:E[0]=6),Y(E,Z)},U.prototype.getPrivateKey=function(Z){return Y(this.keys.getPrivate(),Z)},U.prototype.setPublicKey=function(Z,X){return X=X||"utf8",Buffer.isBuffer(Z)||(Z=new Buffer(Z,X)),this.keys._importPublic(Z),this},U.prototype.setPrivateKey=function(Z,X){X=X||"utf8",Buffer.isBuffer(Z)||(Z=new Buffer(Z,X));var E=new K(Z);return E=E.toString(16),this.keys=this.curve.genKeyPair(),this.keys._importPrivate(E),this};function Y(Z,X,E){Array.isArray(Z)||(Z=Z.toArray());var H=new Buffer(Z);if(E&&H.length{var J=NU(),K=bA().Buffer;Q.exports=function(U,Y){for(var Z=K.alloc(0),X=0,E;Z.length{Q.exports=function(J,K){for(var C=J.length,U=-1;++U{(function(J,K){function C(B,q){if(!B)throw new Error(q||"Assertion failed")}function U(B,q){B.super_=q;var P=function(){};P.prototype=q.prototype,B.prototype=new P,B.prototype.constructor=B}function Y(B,q,P){if(Y.isBN(B))return B;this.negative=0,this.words=null,this.length=0,this.red=null,B!==null&&((q==="le"||q==="be")&&(P=q,q=10),this._init(B||0,q||10,P||"be"))}typeof J=="object"?J.exports=Y:K.BN=Y,Y.BN=Y,Y.wordSize=26;var Z;try{typeof window<"u"&&typeof window.Buffer<"u"?Z=window.Buffer:Z=XQ().Buffer}catch{}Y.isBN=function(B){return B instanceof Y?!0:B!==null&&typeof B=="object"&&B.constructor.wordSize===Y.wordSize&&Array.isArray(B.words)},Y.max=function(B,q){return B.cmp(q)>0?B:q},Y.min=function(B,q){return B.cmp(q)<0?B:q},Y.prototype._init=function(B,q,P){if(typeof B=="number")return this._initNumber(B,q,P);if(typeof B=="object")return this._initArray(B,q,P);q==="hex"&&(q=16),C(q===(q|0)&&q>=2&&q<=36),B=B.toString().replace(/\s+/g,"");var O=0;B[0]==="-"&&(O++,this.negative=1),O=0;O-=3)k=B[O]|B[O-1]<<8|B[O-2]<<16,this.words[w]|=k<>>26-S&67108863,S+=24,S>=26&&(S-=26,w++);else if(P==="le")for(O=0,w=0;O>>26-S&67108863,S+=24,S>=26&&(S-=26,w++);return this.strip()};function X(B,q){var P=B.charCodeAt(q);return P>=65&&P<=70?P-55:P>=97&&P<=102?P-87:P-48&15}function E(B,q,P){var O=X(B,P);return P-1>=q&&(O|=X(B,P-1)<<4),O}Y.prototype._parseHex=function(B,q,P){this.length=Math.ceil((B.length-q)/6),this.words=new Array(this.length);for(var O=0;O=q;O-=2)S=E(B,q,O)<=18?(w-=18,k+=1,this.words[k]|=S>>>26):w+=8;else{var _=B.length-q;for(O=_%2===0?q+1:q;O=18?(w-=18,k+=1,this.words[k]|=S>>>26):w+=8}this.strip()};function H(B,q,P,O){for(var w=0,k=Math.min(B.length,P),S=q;S=49?w+=_-49+10:_>=17?w+=_-17+10:w+=_}return w}Y.prototype._parseBase=function(B,q,P){this.words=[0],this.length=1;for(var O=0,w=1;w<=67108863;w*=q)O++;O--,w=w/q|0;for(var k=B.length-P,S=k%O,_=Math.min(k,k-S)+P,W=0,j=P;j<_;j+=O)W=H(B,j,j+O,q),this.imuln(w),this.words[0]+W<67108864?this.words[0]+=W:this._iaddn(W);if(S!==0){var b=1;for(W=H(B,j,B.length,q),j=0;j1&&this.words[this.length-1]===0;)this.length--;return this._normSign()},Y.prototype._normSign=function(){return this.length===1&&this.words[0]===0&&(this.negative=0),this},Y.prototype.inspect=function(){return(this.red?""};var $=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],I=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],N=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64000000,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,24300000,28629151,33554432,39135393,45435424,52521875,60466176];Y.prototype.toString=function(B,q){B=B||10,q=q|0||1;var P;if(B===16||B==="hex"){P="";for(var O=0,w=0,k=0;k>>24-O&16777215,w!==0||k!==this.length-1?P=$[6-_.length]+_+P:P=_+P,O+=2,O>=26&&(O-=26,k--)}for(w!==0&&(P=w.toString(16)+P);P.length%q!==0;)P="0"+P;return this.negative!==0&&(P="-"+P),P}if(B===(B|0)&&B>=2&&B<=36){var W=I[B],j=N[B];P="";var b=this.clone();for(b.negative=0;!b.isZero();){var p=b.modn(j).toString(B);b=b.idivn(j),b.isZero()?P=p+P:P=$[W-p.length]+p+P}for(this.isZero()&&(P="0"+P);P.length%q!==0;)P="0"+P;return this.negative!==0&&(P="-"+P),P}C(!1,"Base should be between 2 and 36")},Y.prototype.toNumber=function(){var B=this.words[0];return this.length===2?B+=this.words[1]*67108864:this.length===3&&this.words[2]===1?B+=4503599627370496+this.words[1]*67108864:this.length>2&&C(!1,"Number can only safely store up to 53 bits"),this.negative!==0?-B:B},Y.prototype.toJSON=function(){return this.toString(16)},Y.prototype.toBuffer=function(B,q){return C(typeof Z<"u"),this.toArrayLike(Z,B,q)},Y.prototype.toArray=function(B,q){return this.toArrayLike(Array,B,q)},Y.prototype.toArrayLike=function(B,q,P){var O=this.byteLength(),w=P||Math.max(1,O);C(O<=w,"byte array longer than desired length"),C(w>0,"Requested array length <= 0"),this.strip();var k=q==="le",S=new B(w),_,W,j=this.clone();if(k){for(W=0;!j.isZero();W++)_=j.andln(255),j.iushrn(8),S[W]=_;for(;W=4096&&(P+=13,q>>>=13),q>=64&&(P+=7,q>>>=7),q>=8&&(P+=4,q>>>=4),q>=2&&(P+=2,q>>>=2),P+q},Y.prototype._zeroBits=function(B){if(B===0)return 26;var q=B,P=0;return(q&8191)===0&&(P+=13,q>>>=13),(q&127)===0&&(P+=7,q>>>=7),(q&15)===0&&(P+=4,q>>>=4),(q&3)===0&&(P+=2,q>>>=2),(q&1)===0&&P++,P},Y.prototype.bitLength=function(){var B=this.words[this.length-1],q=this._countBits(B);return(this.length-1)*26+q};function F(B){for(var q=new Array(B.bitLength()),P=0;P>>w}return q}Y.prototype.zeroBits=function(){if(this.isZero())return 0;for(var B=0,q=0;qB.length?this.clone().ior(B):B.clone().ior(this)},Y.prototype.uor=function(B){return this.length>B.length?this.clone().iuor(B):B.clone().iuor(this)},Y.prototype.iuand=function(B){var q;this.length>B.length?q=B:q=this;for(var P=0;PB.length?this.clone().iand(B):B.clone().iand(this)},Y.prototype.uand=function(B){return this.length>B.length?this.clone().iuand(B):B.clone().iuand(this)},Y.prototype.iuxor=function(B){var q,P;this.length>B.length?(q=this,P=B):(q=B,P=this);for(var O=0;OB.length?this.clone().ixor(B):B.clone().ixor(this)},Y.prototype.uxor=function(B){return this.length>B.length?this.clone().iuxor(B):B.clone().iuxor(this)},Y.prototype.inotn=function(B){C(typeof B=="number"&&B>=0);var q=Math.ceil(B/26)|0,P=B%26;this._expand(q),P>0&&q--;for(var O=0;O0&&(this.words[O]=~this.words[O]&67108863>>26-P),this.strip()},Y.prototype.notn=function(B){return this.clone().inotn(B)},Y.prototype.setn=function(B,q){C(typeof B=="number"&&B>=0);var P=B/26|0,O=B%26;return this._expand(P+1),q?this.words[P]=this.words[P]|1<B.length?(P=this,O=B):(P=B,O=this);for(var w=0,k=0;k>>26;for(;w!==0&&k>>26;if(this.length=P.length,w!==0)this.words[this.length]=w,this.length++;else if(P!==this)for(;kB.length?this.clone().iadd(B):B.clone().iadd(this)},Y.prototype.isub=function(B){if(B.negative!==0){B.negative=0;var q=this.iadd(B);return B.negative=1,q._normSign()}else if(this.negative!==0)return this.negative=0,this.iadd(B),this.negative=1,this._normSign();var P=this.cmp(B);if(P===0)return this.negative=0,this.length=1,this.words[0]=0,this;var O,w;P>0?(O=this,w=B):(O=B,w=this);for(var k=0,S=0;S>26,this.words[S]=q&67108863;for(;k!==0&&S>26,this.words[S]=q&67108863;if(k===0&&S>>26,p=W&67108863,s=Math.min(j,q.length-1),r=Math.max(0,j-B.length+1);r<=s;r++){var A1=j-r|0;w=B.words[A1]|0,k=q.words[r]|0,S=w*k+p,b+=S/67108864|0,p=S&67108863}P.words[j]=p|0,W=b|0}return W!==0?P.words[j]=W|0:P.length--,P.strip()}var D=function(B,q,P){var O=B.words,w=q.words,k=P.words,S=0,_,W,j,b=O[0]|0,p=b&8191,s=b>>>13,r=O[1]|0,A1=r&8191,Q1=r>>>13,e=O[2]|0,t=e&8191,U1=e>>>13,O1=O[3]|0,E1=O1&8191,Y1=O1>>>13,i=O[4]|0,c=i&8191,o=i>>>13,C1=O[5]|0,q1=C1&8191,Z1=C1>>>13,j1=O[6]|0,H1=j1&8191,B1=j1>>>13,k1=O[7]|0,D1=k1&8191,G1=k1>>>13,w1=O[8]|0,G=w1&8191,z=w1>>>13,x=O[9]|0,m=x&8191,l=x>>>13,a=w[0]|0,K1=a&8191,F1=a>>>13,R1=w[1]|0,X1=R1&8191,W1=R1>>>13,$1=w[2]|0,N1=$1&8191,_1=$1>>>13,J1=w[3]|0,z1=J1&8191,M1=J1>>>13,L1=w[4]|0,V1=L1&8191,S1=L1>>>13,O0=w[5]|0,h1=O0&8191,b1=O0>>>13,f0=w[6]|0,e1=f0&8191,s1=f0>>>13,o0=w[7]|0,a1=o0&8191,r1=o0>>>13,FA=w[8]|0,K0=FA&8191,J0=FA>>>13,qA=w[9]|0,Q0=qA&8191,A0=qA>>>13;P.negative=B.negative^q.negative,P.length=19,_=Math.imul(p,K1),W=Math.imul(p,F1),W=W+Math.imul(s,K1)|0,j=Math.imul(s,F1);var hA=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(hA>>>26)|0,hA&=67108863,_=Math.imul(A1,K1),W=Math.imul(A1,F1),W=W+Math.imul(Q1,K1)|0,j=Math.imul(Q1,F1),_=_+Math.imul(p,X1)|0,W=W+Math.imul(p,W1)|0,W=W+Math.imul(s,X1)|0,j=j+Math.imul(s,W1)|0;var r0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(r0>>>26)|0,r0&=67108863,_=Math.imul(t,K1),W=Math.imul(t,F1),W=W+Math.imul(U1,K1)|0,j=Math.imul(U1,F1),_=_+Math.imul(A1,X1)|0,W=W+Math.imul(A1,W1)|0,W=W+Math.imul(Q1,X1)|0,j=j+Math.imul(Q1,W1)|0,_=_+Math.imul(p,N1)|0,W=W+Math.imul(p,_1)|0,W=W+Math.imul(s,N1)|0,j=j+Math.imul(s,_1)|0;var EA=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(EA>>>26)|0,EA&=67108863,_=Math.imul(E1,K1),W=Math.imul(E1,F1),W=W+Math.imul(Y1,K1)|0,j=Math.imul(Y1,F1),_=_+Math.imul(t,X1)|0,W=W+Math.imul(t,W1)|0,W=W+Math.imul(U1,X1)|0,j=j+Math.imul(U1,W1)|0,_=_+Math.imul(A1,N1)|0,W=W+Math.imul(A1,_1)|0,W=W+Math.imul(Q1,N1)|0,j=j+Math.imul(Q1,_1)|0,_=_+Math.imul(p,z1)|0,W=W+Math.imul(p,M1)|0,W=W+Math.imul(s,z1)|0,j=j+Math.imul(s,M1)|0;var X2=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(X2>>>26)|0,X2&=67108863,_=Math.imul(c,K1),W=Math.imul(c,F1),W=W+Math.imul(o,K1)|0,j=Math.imul(o,F1),_=_+Math.imul(E1,X1)|0,W=W+Math.imul(E1,W1)|0,W=W+Math.imul(Y1,X1)|0,j=j+Math.imul(Y1,W1)|0,_=_+Math.imul(t,N1)|0,W=W+Math.imul(t,_1)|0,W=W+Math.imul(U1,N1)|0,j=j+Math.imul(U1,_1)|0,_=_+Math.imul(A1,z1)|0,W=W+Math.imul(A1,M1)|0,W=W+Math.imul(Q1,z1)|0,j=j+Math.imul(Q1,M1)|0,_=_+Math.imul(p,V1)|0,W=W+Math.imul(p,S1)|0,W=W+Math.imul(s,V1)|0,j=j+Math.imul(s,S1)|0;var E2=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(E2>>>26)|0,E2&=67108863,_=Math.imul(q1,K1),W=Math.imul(q1,F1),W=W+Math.imul(Z1,K1)|0,j=Math.imul(Z1,F1),_=_+Math.imul(c,X1)|0,W=W+Math.imul(c,W1)|0,W=W+Math.imul(o,X1)|0,j=j+Math.imul(o,W1)|0,_=_+Math.imul(E1,N1)|0,W=W+Math.imul(E1,_1)|0,W=W+Math.imul(Y1,N1)|0,j=j+Math.imul(Y1,_1)|0,_=_+Math.imul(t,z1)|0,W=W+Math.imul(t,M1)|0,W=W+Math.imul(U1,z1)|0,j=j+Math.imul(U1,M1)|0,_=_+Math.imul(A1,V1)|0,W=W+Math.imul(A1,S1)|0,W=W+Math.imul(Q1,V1)|0,j=j+Math.imul(Q1,S1)|0,_=_+Math.imul(p,h1)|0,W=W+Math.imul(p,b1)|0,W=W+Math.imul(s,h1)|0,j=j+Math.imul(s,b1)|0;var T1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(T1>>>26)|0,T1&=67108863,_=Math.imul(H1,K1),W=Math.imul(H1,F1),W=W+Math.imul(B1,K1)|0,j=Math.imul(B1,F1),_=_+Math.imul(q1,X1)|0,W=W+Math.imul(q1,W1)|0,W=W+Math.imul(Z1,X1)|0,j=j+Math.imul(Z1,W1)|0,_=_+Math.imul(c,N1)|0,W=W+Math.imul(c,_1)|0,W=W+Math.imul(o,N1)|0,j=j+Math.imul(o,_1)|0,_=_+Math.imul(E1,z1)|0,W=W+Math.imul(E1,M1)|0,W=W+Math.imul(Y1,z1)|0,j=j+Math.imul(Y1,M1)|0,_=_+Math.imul(t,V1)|0,W=W+Math.imul(t,S1)|0,W=W+Math.imul(U1,V1)|0,j=j+Math.imul(U1,S1)|0,_=_+Math.imul(A1,h1)|0,W=W+Math.imul(A1,b1)|0,W=W+Math.imul(Q1,h1)|0,j=j+Math.imul(Q1,b1)|0,_=_+Math.imul(p,e1)|0,W=W+Math.imul(p,s1)|0,W=W+Math.imul(s,e1)|0,j=j+Math.imul(s,s1)|0;var m1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(m1>>>26)|0,m1&=67108863,_=Math.imul(D1,K1),W=Math.imul(D1,F1),W=W+Math.imul(G1,K1)|0,j=Math.imul(G1,F1),_=_+Math.imul(H1,X1)|0,W=W+Math.imul(H1,W1)|0,W=W+Math.imul(B1,X1)|0,j=j+Math.imul(B1,W1)|0,_=_+Math.imul(q1,N1)|0,W=W+Math.imul(q1,_1)|0,W=W+Math.imul(Z1,N1)|0,j=j+Math.imul(Z1,_1)|0,_=_+Math.imul(c,z1)|0,W=W+Math.imul(c,M1)|0,W=W+Math.imul(o,z1)|0,j=j+Math.imul(o,M1)|0,_=_+Math.imul(E1,V1)|0,W=W+Math.imul(E1,S1)|0,W=W+Math.imul(Y1,V1)|0,j=j+Math.imul(Y1,S1)|0,_=_+Math.imul(t,h1)|0,W=W+Math.imul(t,b1)|0,W=W+Math.imul(U1,h1)|0,j=j+Math.imul(U1,b1)|0,_=_+Math.imul(A1,e1)|0,W=W+Math.imul(A1,s1)|0,W=W+Math.imul(Q1,e1)|0,j=j+Math.imul(Q1,s1)|0,_=_+Math.imul(p,a1)|0,W=W+Math.imul(p,r1)|0,W=W+Math.imul(s,a1)|0,j=j+Math.imul(s,r1)|0;var i1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(i1>>>26)|0,i1&=67108863,_=Math.imul(G,K1),W=Math.imul(G,F1),W=W+Math.imul(z,K1)|0,j=Math.imul(z,F1),_=_+Math.imul(D1,X1)|0,W=W+Math.imul(D1,W1)|0,W=W+Math.imul(G1,X1)|0,j=j+Math.imul(G1,W1)|0,_=_+Math.imul(H1,N1)|0,W=W+Math.imul(H1,_1)|0,W=W+Math.imul(B1,N1)|0,j=j+Math.imul(B1,_1)|0,_=_+Math.imul(q1,z1)|0,W=W+Math.imul(q1,M1)|0,W=W+Math.imul(Z1,z1)|0,j=j+Math.imul(Z1,M1)|0,_=_+Math.imul(c,V1)|0,W=W+Math.imul(c,S1)|0,W=W+Math.imul(o,V1)|0,j=j+Math.imul(o,S1)|0,_=_+Math.imul(E1,h1)|0,W=W+Math.imul(E1,b1)|0,W=W+Math.imul(Y1,h1)|0,j=j+Math.imul(Y1,b1)|0,_=_+Math.imul(t,e1)|0,W=W+Math.imul(t,s1)|0,W=W+Math.imul(U1,e1)|0,j=j+Math.imul(U1,s1)|0,_=_+Math.imul(A1,a1)|0,W=W+Math.imul(A1,r1)|0,W=W+Math.imul(Q1,a1)|0,j=j+Math.imul(Q1,r1)|0,_=_+Math.imul(p,K0)|0,W=W+Math.imul(p,J0)|0,W=W+Math.imul(s,K0)|0,j=j+Math.imul(s,J0)|0;var t1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(t1>>>26)|0,t1&=67108863,_=Math.imul(m,K1),W=Math.imul(m,F1),W=W+Math.imul(l,K1)|0,j=Math.imul(l,F1),_=_+Math.imul(G,X1)|0,W=W+Math.imul(G,W1)|0,W=W+Math.imul(z,X1)|0,j=j+Math.imul(z,W1)|0,_=_+Math.imul(D1,N1)|0,W=W+Math.imul(D1,_1)|0,W=W+Math.imul(G1,N1)|0,j=j+Math.imul(G1,_1)|0,_=_+Math.imul(H1,z1)|0,W=W+Math.imul(H1,M1)|0,W=W+Math.imul(B1,z1)|0,j=j+Math.imul(B1,M1)|0,_=_+Math.imul(q1,V1)|0,W=W+Math.imul(q1,S1)|0,W=W+Math.imul(Z1,V1)|0,j=j+Math.imul(Z1,S1)|0,_=_+Math.imul(c,h1)|0,W=W+Math.imul(c,b1)|0,W=W+Math.imul(o,h1)|0,j=j+Math.imul(o,b1)|0,_=_+Math.imul(E1,e1)|0,W=W+Math.imul(E1,s1)|0,W=W+Math.imul(Y1,e1)|0,j=j+Math.imul(Y1,s1)|0,_=_+Math.imul(t,a1)|0,W=W+Math.imul(t,r1)|0,W=W+Math.imul(U1,a1)|0,j=j+Math.imul(U1,r1)|0,_=_+Math.imul(A1,K0)|0,W=W+Math.imul(A1,J0)|0,W=W+Math.imul(Q1,K0)|0,j=j+Math.imul(Q1,J0)|0,_=_+Math.imul(p,Q0)|0,W=W+Math.imul(p,A0)|0,W=W+Math.imul(s,Q0)|0,j=j+Math.imul(s,A0)|0;var d1=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(d1>>>26)|0,d1&=67108863,_=Math.imul(m,X1),W=Math.imul(m,W1),W=W+Math.imul(l,X1)|0,j=Math.imul(l,W1),_=_+Math.imul(G,N1)|0,W=W+Math.imul(G,_1)|0,W=W+Math.imul(z,N1)|0,j=j+Math.imul(z,_1)|0,_=_+Math.imul(D1,z1)|0,W=W+Math.imul(D1,M1)|0,W=W+Math.imul(G1,z1)|0,j=j+Math.imul(G1,M1)|0,_=_+Math.imul(H1,V1)|0,W=W+Math.imul(H1,S1)|0,W=W+Math.imul(B1,V1)|0,j=j+Math.imul(B1,S1)|0,_=_+Math.imul(q1,h1)|0,W=W+Math.imul(q1,b1)|0,W=W+Math.imul(Z1,h1)|0,j=j+Math.imul(Z1,b1)|0,_=_+Math.imul(c,e1)|0,W=W+Math.imul(c,s1)|0,W=W+Math.imul(o,e1)|0,j=j+Math.imul(o,s1)|0,_=_+Math.imul(E1,a1)|0,W=W+Math.imul(E1,r1)|0,W=W+Math.imul(Y1,a1)|0,j=j+Math.imul(Y1,r1)|0,_=_+Math.imul(t,K0)|0,W=W+Math.imul(t,J0)|0,W=W+Math.imul(U1,K0)|0,j=j+Math.imul(U1,J0)|0,_=_+Math.imul(A1,Q0)|0,W=W+Math.imul(A1,A0)|0,W=W+Math.imul(Q1,Q0)|0,j=j+Math.imul(Q1,A0)|0;var H0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(H0>>>26)|0,H0&=67108863,_=Math.imul(m,N1),W=Math.imul(m,_1),W=W+Math.imul(l,N1)|0,j=Math.imul(l,_1),_=_+Math.imul(G,z1)|0,W=W+Math.imul(G,M1)|0,W=W+Math.imul(z,z1)|0,j=j+Math.imul(z,M1)|0,_=_+Math.imul(D1,V1)|0,W=W+Math.imul(D1,S1)|0,W=W+Math.imul(G1,V1)|0,j=j+Math.imul(G1,S1)|0,_=_+Math.imul(H1,h1)|0,W=W+Math.imul(H1,b1)|0,W=W+Math.imul(B1,h1)|0,j=j+Math.imul(B1,b1)|0,_=_+Math.imul(q1,e1)|0,W=W+Math.imul(q1,s1)|0,W=W+Math.imul(Z1,e1)|0,j=j+Math.imul(Z1,s1)|0,_=_+Math.imul(c,a1)|0,W=W+Math.imul(c,r1)|0,W=W+Math.imul(o,a1)|0,j=j+Math.imul(o,r1)|0,_=_+Math.imul(E1,K0)|0,W=W+Math.imul(E1,J0)|0,W=W+Math.imul(Y1,K0)|0,j=j+Math.imul(Y1,J0)|0,_=_+Math.imul(t,Q0)|0,W=W+Math.imul(t,A0)|0,W=W+Math.imul(U1,Q0)|0,j=j+Math.imul(U1,A0)|0;var R0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(R0>>>26)|0,R0&=67108863,_=Math.imul(m,z1),W=Math.imul(m,M1),W=W+Math.imul(l,z1)|0,j=Math.imul(l,M1),_=_+Math.imul(G,V1)|0,W=W+Math.imul(G,S1)|0,W=W+Math.imul(z,V1)|0,j=j+Math.imul(z,S1)|0,_=_+Math.imul(D1,h1)|0,W=W+Math.imul(D1,b1)|0,W=W+Math.imul(G1,h1)|0,j=j+Math.imul(G1,b1)|0,_=_+Math.imul(H1,e1)|0,W=W+Math.imul(H1,s1)|0,W=W+Math.imul(B1,e1)|0,j=j+Math.imul(B1,s1)|0,_=_+Math.imul(q1,a1)|0,W=W+Math.imul(q1,r1)|0,W=W+Math.imul(Z1,a1)|0,j=j+Math.imul(Z1,r1)|0,_=_+Math.imul(c,K0)|0,W=W+Math.imul(c,J0)|0,W=W+Math.imul(o,K0)|0,j=j+Math.imul(o,J0)|0,_=_+Math.imul(E1,Q0)|0,W=W+Math.imul(E1,A0)|0,W=W+Math.imul(Y1,Q0)|0,j=j+Math.imul(Y1,A0)|0;var D0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(D0>>>26)|0,D0&=67108863,_=Math.imul(m,V1),W=Math.imul(m,S1),W=W+Math.imul(l,V1)|0,j=Math.imul(l,S1),_=_+Math.imul(G,h1)|0,W=W+Math.imul(G,b1)|0,W=W+Math.imul(z,h1)|0,j=j+Math.imul(z,b1)|0,_=_+Math.imul(D1,e1)|0,W=W+Math.imul(D1,s1)|0,W=W+Math.imul(G1,e1)|0,j=j+Math.imul(G1,s1)|0,_=_+Math.imul(H1,a1)|0,W=W+Math.imul(H1,r1)|0,W=W+Math.imul(B1,a1)|0,j=j+Math.imul(B1,r1)|0,_=_+Math.imul(q1,K0)|0,W=W+Math.imul(q1,J0)|0,W=W+Math.imul(Z1,K0)|0,j=j+Math.imul(Z1,J0)|0,_=_+Math.imul(c,Q0)|0,W=W+Math.imul(c,A0)|0,W=W+Math.imul(o,Q0)|0,j=j+Math.imul(o,A0)|0;var P0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(P0>>>26)|0,P0&=67108863,_=Math.imul(m,h1),W=Math.imul(m,b1),W=W+Math.imul(l,h1)|0,j=Math.imul(l,b1),_=_+Math.imul(G,e1)|0,W=W+Math.imul(G,s1)|0,W=W+Math.imul(z,e1)|0,j=j+Math.imul(z,s1)|0,_=_+Math.imul(D1,a1)|0,W=W+Math.imul(D1,r1)|0,W=W+Math.imul(G1,a1)|0,j=j+Math.imul(G1,r1)|0,_=_+Math.imul(H1,K0)|0,W=W+Math.imul(H1,J0)|0,W=W+Math.imul(B1,K0)|0,j=j+Math.imul(B1,J0)|0,_=_+Math.imul(q1,Q0)|0,W=W+Math.imul(q1,A0)|0,W=W+Math.imul(Z1,Q0)|0,j=j+Math.imul(Z1,A0)|0;var j0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(j0>>>26)|0,j0&=67108863,_=Math.imul(m,e1),W=Math.imul(m,s1),W=W+Math.imul(l,e1)|0,j=Math.imul(l,s1),_=_+Math.imul(G,a1)|0,W=W+Math.imul(G,r1)|0,W=W+Math.imul(z,a1)|0,j=j+Math.imul(z,r1)|0,_=_+Math.imul(D1,K0)|0,W=W+Math.imul(D1,J0)|0,W=W+Math.imul(G1,K0)|0,j=j+Math.imul(G1,J0)|0,_=_+Math.imul(H1,Q0)|0,W=W+Math.imul(H1,A0)|0,W=W+Math.imul(B1,Q0)|0,j=j+Math.imul(B1,A0)|0;var v0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(v0>>>26)|0,v0&=67108863,_=Math.imul(m,a1),W=Math.imul(m,r1),W=W+Math.imul(l,a1)|0,j=Math.imul(l,r1),_=_+Math.imul(G,K0)|0,W=W+Math.imul(G,J0)|0,W=W+Math.imul(z,K0)|0,j=j+Math.imul(z,J0)|0,_=_+Math.imul(D1,Q0)|0,W=W+Math.imul(D1,A0)|0,W=W+Math.imul(G1,Q0)|0,j=j+Math.imul(G1,A0)|0;var S0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(S0>>>26)|0,S0&=67108863,_=Math.imul(m,K0),W=Math.imul(m,J0),W=W+Math.imul(l,K0)|0,j=Math.imul(l,J0),_=_+Math.imul(G,Q0)|0,W=W+Math.imul(G,A0)|0,W=W+Math.imul(z,Q0)|0,j=j+Math.imul(z,A0)|0;var n0=(S+_|0)+((W&8191)<<13)|0;S=(j+(W>>>13)|0)+(n0>>>26)|0,n0&=67108863,_=Math.imul(m,Q0),W=Math.imul(m,A0),W=W+Math.imul(l,Q0)|0,j=Math.imul(l,A0);var i0=(S+_|0)+((W&8191)<<13)|0;return S=(j+(W>>>13)|0)+(i0>>>26)|0,i0&=67108863,k[0]=hA,k[1]=r0,k[2]=EA,k[3]=X2,k[4]=E2,k[5]=T1,k[6]=m1,k[7]=i1,k[8]=t1,k[9]=d1,k[10]=H0,k[11]=R0,k[12]=D0,k[13]=P0,k[14]=j0,k[15]=v0,k[16]=S0,k[17]=n0,k[18]=i0,S!==0&&(k[19]=S,P.length++),P};Math.imul||(D=V);function L(B,q,P){P.negative=q.negative^B.negative,P.length=B.length+q.length;for(var O=0,w=0,k=0;k>>26)|0,w+=S>>>26,S&=67108863}P.words[k]=_,O=S,S=w}return O!==0?P.words[k]=O:P.length--,P.strip()}function R(B,q,P){var O=new M;return O.mulp(B,q,P)}Y.prototype.mulTo=function(B,q){var P,O=this.length+B.length;return this.length===10&&B.length===10?P=D(this,B,q):O<63?P=V(this,B,q):O<1024?P=L(this,B,q):P=R(this,B,q),P};function M(B,q){this.x=B,this.y=q}M.prototype.makeRBT=function(B){for(var q=new Array(B),P=Y.prototype._countBits(B)-1,O=0;O>=1;return O},M.prototype.permute=function(B,q,P,O,w,k){for(var S=0;S>>1)w++;return 1<>>13,P[2*k+1]=w&8191,w=w>>>13;for(k=2*q;k>=26,q+=O/67108864|0,q+=w>>>26,this.words[P]=w&67108863}return q!==0&&(this.words[P]=q,this.length++),this},Y.prototype.muln=function(B){return this.clone().imuln(B)},Y.prototype.sqr=function(){return this.mul(this)},Y.prototype.isqr=function(){return this.imul(this.clone())},Y.prototype.pow=function(B){var q=F(B);if(q.length===0)return new Y(1);for(var P=this,O=0;O=0);var q=B%26,P=(B-q)/26,O=67108863>>>26-q<<26-q,w;if(q!==0){var k=0;for(w=0;w>>26-q}k&&(this.words[w]=k,this.length++)}if(P!==0){for(w=this.length-1;w>=0;w--)this.words[w+P]=this.words[w];for(w=0;w=0);var O;q?O=(q-q%26)/26:O=0;var w=B%26,k=Math.min((B-w)/26,this.length),S=67108863^67108863>>>w<k)for(this.length-=k,W=0;W=0&&(j!==0||W>=O);W--){var b=this.words[W]|0;this.words[W]=j<<26-w|b>>>w,j=b&S}return _&&j!==0&&(_.words[_.length++]=j),this.length===0&&(this.words[0]=0,this.length=1),this.strip()},Y.prototype.ishrn=function(B,q,P){return C(this.negative===0),this.iushrn(B,q,P)},Y.prototype.shln=function(B){return this.clone().ishln(B)},Y.prototype.ushln=function(B){return this.clone().iushln(B)},Y.prototype.shrn=function(B){return this.clone().ishrn(B)},Y.prototype.ushrn=function(B){return this.clone().iushrn(B)},Y.prototype.testn=function(B){C(typeof B=="number"&&B>=0);var q=B%26,P=(B-q)/26,O=1<=0);var q=B%26,P=(B-q)/26;if(C(this.negative===0,"imaskn works only with positive numbers"),this.length<=P)return this;if(q!==0&&P++,this.length=Math.min(P,this.length),q!==0){var O=67108863^67108863>>>q<=67108864;q++)this.words[q]-=67108864,q===this.length-1?this.words[q+1]=1:this.words[q+1]++;return this.length=Math.max(this.length,q+1),this},Y.prototype.isubn=function(B){if(C(typeof B=="number"),C(B<67108864),B<0)return this.iaddn(-B);if(this.negative!==0)return this.negative=0,this.iaddn(B),this.negative=1,this;if(this.words[0]-=B,this.length===1&&this.words[0]<0)this.words[0]=-this.words[0],this.negative=1;else for(var q=0;q>26)-(_/67108864|0),this.words[w+P]=k&67108863}for(;w>26,this.words[w+P]=k&67108863;if(S===0)return this.strip();for(C(S===-1),S=0,w=0;w>26,this.words[w]=k&67108863;return this.negative=1,this.strip()},Y.prototype._wordDiv=function(B,q){var P=this.length-B.length,O=this.clone(),w=B,k=w.words[w.length-1]|0,S=this._countBits(k);P=26-S,P!==0&&(w=w.ushln(P),O.iushln(P),k=w.words[w.length-1]|0);var _=O.length-w.length,W;if(q!=="mod"){W=new Y(null),W.length=_+1,W.words=new Array(W.length);for(var j=0;j=0;p--){var s=(O.words[w.length+p]|0)*67108864+(O.words[w.length+p-1]|0);for(s=Math.min(s/k|0,67108863),O._ishlnsubmul(w,s,p);O.negative!==0;)s--,O.negative=0,O._ishlnsubmul(w,1,p),O.isZero()||(O.negative^=1);W&&(W.words[p]=s)}return W&&W.strip(),O.strip(),q!=="div"&&P!==0&&O.iushrn(P),{div:W||null,mod:O}},Y.prototype.divmod=function(B,q,P){if(C(!B.isZero()),this.isZero())return{div:new Y(0),mod:new Y(0)};var O,w,k;return this.negative!==0&&B.negative===0?(k=this.neg().divmod(B,q),q!=="mod"&&(O=k.div.neg()),q!=="div"&&(w=k.mod.neg(),P&&w.negative!==0&&w.iadd(B)),{div:O,mod:w}):this.negative===0&&B.negative!==0?(k=this.divmod(B.neg(),q),q!=="mod"&&(O=k.div.neg()),{div:O,mod:k.mod}):(this.negative&B.negative)!==0?(k=this.neg().divmod(B.neg(),q),q!=="div"&&(w=k.mod.neg(),P&&w.negative!==0&&w.isub(B)),{div:k.div,mod:w}):B.length>this.length||this.cmp(B)<0?{div:new Y(0),mod:this}:B.length===1?q==="div"?{div:this.divn(B.words[0]),mod:null}:q==="mod"?{div:null,mod:new Y(this.modn(B.words[0]))}:{div:this.divn(B.words[0]),mod:new Y(this.modn(B.words[0]))}:this._wordDiv(B,q)},Y.prototype.div=function(B){return this.divmod(B,"div",!1).div},Y.prototype.mod=function(B){return this.divmod(B,"mod",!1).mod},Y.prototype.umod=function(B){return this.divmod(B,"mod",!0).mod},Y.prototype.divRound=function(B){var q=this.divmod(B);if(q.mod.isZero())return q.div;var P=q.div.negative!==0?q.mod.isub(B):q.mod,O=B.ushrn(1),w=B.andln(1),k=P.cmp(O);return k<0||w===1&&k===0?q.div:q.div.negative!==0?q.div.isubn(1):q.div.iaddn(1)},Y.prototype.modn=function(B){C(B<=67108863);for(var q=67108864%B,P=0,O=this.length-1;O>=0;O--)P=(q*P+(this.words[O]|0))%B;return P},Y.prototype.idivn=function(B){C(B<=67108863);for(var q=0,P=this.length-1;P>=0;P--){var O=(this.words[P]|0)+q*67108864;this.words[P]=O/B|0,q=O%B}return this.strip()},Y.prototype.divn=function(B){return this.clone().idivn(B)},Y.prototype.egcd=function(B){C(B.negative===0),C(!B.isZero());var q=this,P=B.clone();q.negative!==0?q=q.umod(B):q=q.clone();for(var O=new Y(1),w=new Y(0),k=new Y(0),S=new Y(1),_=0;q.isEven()&&P.isEven();)q.iushrn(1),P.iushrn(1),++_;for(var W=P.clone(),j=q.clone();!q.isZero();){for(var b=0,p=1;(q.words[0]&p)===0&&b<26;++b,p<<=1);if(b>0)for(q.iushrn(b);b-- >0;)(O.isOdd()||w.isOdd())&&(O.iadd(W),w.isub(j)),O.iushrn(1),w.iushrn(1);for(var s=0,r=1;(P.words[0]&r)===0&&s<26;++s,r<<=1);if(s>0)for(P.iushrn(s);s-- >0;)(k.isOdd()||S.isOdd())&&(k.iadd(W),S.isub(j)),k.iushrn(1),S.iushrn(1);q.cmp(P)>=0?(q.isub(P),O.isub(k),w.isub(S)):(P.isub(q),k.isub(O),S.isub(w))}return{a:k,b:S,gcd:P.iushln(_)}},Y.prototype._invmp=function(B){C(B.negative===0),C(!B.isZero());var q=this,P=B.clone();q.negative!==0?q=q.umod(B):q=q.clone();for(var O=new Y(1),w=new Y(0),k=P.clone();q.cmpn(1)>0&&P.cmpn(1)>0;){for(var S=0,_=1;(q.words[0]&_)===0&&S<26;++S,_<<=1);if(S>0)for(q.iushrn(S);S-- >0;)O.isOdd()&&O.iadd(k),O.iushrn(1);for(var W=0,j=1;(P.words[0]&j)===0&&W<26;++W,j<<=1);if(W>0)for(P.iushrn(W);W-- >0;)w.isOdd()&&w.iadd(k),w.iushrn(1);q.cmp(P)>=0?(q.isub(P),O.isub(w)):(P.isub(q),w.isub(O))}var b;return q.cmpn(1)===0?b=O:b=w,b.cmpn(0)<0&&b.iadd(B),b},Y.prototype.gcd=function(B){if(this.isZero())return B.abs();if(B.isZero())return this.abs();var q=this.clone(),P=B.clone();q.negative=0,P.negative=0;for(var O=0;q.isEven()&&P.isEven();O++)q.iushrn(1),P.iushrn(1);do{for(;q.isEven();)q.iushrn(1);for(;P.isEven();)P.iushrn(1);var w=q.cmp(P);if(w<0){var k=q;q=P,P=k}else if(w===0||P.cmpn(1)===0)break;q.isub(P)}while(!0);return P.iushln(O)},Y.prototype.invm=function(B){return this.egcd(B).a.umod(B)},Y.prototype.isEven=function(){return(this.words[0]&1)===0},Y.prototype.isOdd=function(){return(this.words[0]&1)===1},Y.prototype.andln=function(B){return this.words[0]&B},Y.prototype.bincn=function(B){C(typeof B=="number");var q=B%26,P=(B-q)/26,O=1<>>26,S&=67108863,this.words[k]=S}return w!==0&&(this.words[k]=w,this.length++),this},Y.prototype.isZero=function(){return this.length===1&&this.words[0]===0},Y.prototype.cmpn=function(B){var q=B<0;if(this.negative!==0&&!q)return-1;if(this.negative===0&&q)return 1;this.strip();var P;if(this.length>1)P=1;else{q&&(B=-B),C(B<=67108863,"Number is too big");var O=this.words[0]|0;P=O===B?0:OB.length)return 1;if(this.length=0;P--){var O=this.words[P]|0,w=B.words[P]|0;if(O!==w){Ow&&(q=1);break}}return q},Y.prototype.gtn=function(B){return this.cmpn(B)===1},Y.prototype.gt=function(B){return this.cmp(B)===1},Y.prototype.gten=function(B){return this.cmpn(B)>=0},Y.prototype.gte=function(B){return this.cmp(B)>=0},Y.prototype.ltn=function(B){return this.cmpn(B)===-1},Y.prototype.lt=function(B){return this.cmp(B)===-1},Y.prototype.lten=function(B){return this.cmpn(B)<=0},Y.prototype.lte=function(B){return this.cmp(B)<=0},Y.prototype.eqn=function(B){return this.cmpn(B)===0},Y.prototype.eq=function(B){return this.cmp(B)===0},Y.red=function(B){return new d(B)},Y.prototype.toRed=function(B){return C(!this.red,"Already a number in reduction context"),C(this.negative===0,"red works only with positives"),B.convertTo(this)._forceRed(B)},Y.prototype.fromRed=function(){return C(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},Y.prototype._forceRed=function(B){return this.red=B,this},Y.prototype.forceRed=function(B){return C(!this.red,"Already a number in reduction context"),this._forceRed(B)},Y.prototype.redAdd=function(B){return C(this.red,"redAdd works only with red numbers"),this.red.add(this,B)},Y.prototype.redIAdd=function(B){return C(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,B)},Y.prototype.redSub=function(B){return C(this.red,"redSub works only with red numbers"),this.red.sub(this,B)},Y.prototype.redISub=function(B){return C(this.red,"redISub works only with red numbers"),this.red.isub(this,B)},Y.prototype.redShl=function(B){return C(this.red,"redShl works only with red numbers"),this.red.shl(this,B)},Y.prototype.redMul=function(B){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.mul(this,B)},Y.prototype.redIMul=function(B){return C(this.red,"redMul works only with red numbers"),this.red._verify2(this,B),this.red.imul(this,B)},Y.prototype.redSqr=function(){return C(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},Y.prototype.redISqr=function(){return C(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},Y.prototype.redSqrt=function(){return C(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},Y.prototype.redInvm=function(){return C(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},Y.prototype.redNeg=function(){return C(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},Y.prototype.redPow=function(B){return C(this.red&&!B.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,B)};var T={k256:null,p224:null,p192:null,p25519:null};function h(B,q){this.name=B,this.p=new Y(q,16),this.n=this.p.bitLength(),this.k=new Y(1).iushln(this.n).isub(this.p),this.tmp=this._tmp()}h.prototype._tmp=function(){var B=new Y(null);return B.words=new Array(Math.ceil(this.n/13)),B},h.prototype.ireduce=function(B){var q=B,P;do this.split(q,this.tmp),q=this.imulK(q),q=q.iadd(this.tmp),P=q.bitLength();while(P>this.n);var O=P0?q.isub(this.p):q.strip!==void 0?q.strip():q._strip(),q},h.prototype.split=function(B,q){B.iushrn(this.n,0,q)},h.prototype.imulK=function(B){return B.imul(this.k)};function y(){h.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}U(y,h),y.prototype.split=function(B,q){for(var P=4194303,O=Math.min(B.length,9),w=0;w>>22,k=S}k>>>=22,B.words[w-10]=k,k===0&&B.length>10?B.length-=10:B.length-=9},y.prototype.imulK=function(B){B.words[B.length]=0,B.words[B.length+1]=0,B.length+=2;for(var q=0,P=0;P>>=26,B.words[P]=w,q=O}return q!==0&&(B.words[B.length++]=q),B},Y._prime=function(B){if(T[B])return T[B];var q;if(B==="k256")q=new y;else if(B==="p224")q=new g;else if(B==="p192")q=new f;else if(B==="p25519")q=new u;else throw new Error("Unknown prime "+B);return T[B]=q,q};function d(B){if(typeof B=="string"){var q=Y._prime(B);this.m=q.p,this.prime=q}else C(B.gtn(1),"modulus must be greater than 1"),this.m=B,this.prime=null}d.prototype._verify1=function(B){C(B.negative===0,"red works only with positives"),C(B.red,"red works only with red numbers")},d.prototype._verify2=function(B,q){C((B.negative|q.negative)===0,"red works only with positives"),C(B.red&&B.red===q.red,"red works only with red numbers")},d.prototype.imod=function(B){return this.prime?this.prime.ireduce(B)._forceRed(this):B.umod(this.m)._forceRed(this)},d.prototype.neg=function(B){return B.isZero()?B.clone():this.m.sub(B)._forceRed(this)},d.prototype.add=function(B,q){this._verify2(B,q);var P=B.add(q);return P.cmp(this.m)>=0&&P.isub(this.m),P._forceRed(this)},d.prototype.iadd=function(B,q){this._verify2(B,q);var P=B.iadd(q);return P.cmp(this.m)>=0&&P.isub(this.m),P},d.prototype.sub=function(B,q){this._verify2(B,q);var P=B.sub(q);return P.cmpn(0)<0&&P.iadd(this.m),P._forceRed(this)},d.prototype.isub=function(B,q){this._verify2(B,q);var P=B.isub(q);return P.cmpn(0)<0&&P.iadd(this.m),P},d.prototype.shl=function(B,q){return this._verify1(B),this.imod(B.ushln(q))},d.prototype.imul=function(B,q){return this._verify2(B,q),this.imod(B.imul(q))},d.prototype.mul=function(B,q){return this._verify2(B,q),this.imod(B.mul(q))},d.prototype.isqr=function(B){return this.imul(B,B.clone())},d.prototype.sqr=function(B){return this.mul(B,B)},d.prototype.sqrt=function(B){if(B.isZero())return B.clone();var q=this.m.andln(3);if(C(q%2===1),q===3){var P=this.m.add(new Y(1)).iushrn(2);return this.pow(B,P)}for(var O=this.m.subn(1),w=0;!O.isZero()&&O.andln(1)===0;)w++,O.iushrn(1);C(!O.isZero());var k=new Y(1).toRed(this),S=k.redNeg(),_=this.m.subn(1).iushrn(1),W=this.m.bitLength();for(W=new Y(2*W*W).toRed(this);this.pow(W,_).cmp(S)!==0;)W.redIAdd(S);for(var j=this.pow(W,O),b=this.pow(B,O.addn(1).iushrn(1)),p=this.pow(B,O),s=w;p.cmp(k)!==0;){for(var r=p,A1=0;r.cmp(k)!==0;A1++)r=r.redSqr();C(A1=0;w--){for(var j=q.words[w],b=W-1;b>=0;b--){var p=j>>b&1;if(k!==O[0]&&(k=this.sqr(k)),p===0&&S===0){_=0;continue}S<<=1,S|=p,_++,!(_!==P&&(w!==0||b!==0))&&(k=this.mul(k,O[S]),_=0,S=0)}W=26}return k},d.prototype.convertTo=function(B){var q=B.umod(this.m);return q===B?q.clone():q},d.prototype.convertFrom=function(B){var q=B.clone();return q.red=null,q},Y.mont=function(B){return new n(B)};function n(B){d.call(this,B),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new Y(1).iushln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv=this.minv.umod(this.r),this.minv=this.r.sub(this.minv)}U(n,d),n.prototype.convertTo=function(B){return this.imod(B.ushln(this.shift))},n.prototype.convertFrom=function(B){var q=this.imod(B.mul(this.rinv));return q.red=null,q},n.prototype.imul=function(B,q){if(B.isZero()||q.isZero())return B.words[0]=0,B.length=1,B;var P=B.imul(q),O=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=P.isub(O).iushrn(this.shift),k=w;return w.cmp(this.m)>=0?k=w.isub(this.m):w.cmpn(0)<0&&(k=w.iadd(this.m)),k._forceRed(this)},n.prototype.mul=function(B,q){if(B.isZero()||q.isZero())return new Y(0)._forceRed(this);var P=B.mul(q),O=P.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),w=P.isub(O).iushrn(this.shift),k=w;return w.cmp(this.m)>=0?k=w.isub(this.m):w.cmpn(0)<0&&(k=w.iadd(this.m)),k._forceRed(this)},n.prototype.invm=function(B){var q=this.imod(B._invmp(this.m).mul(this.r2));return q._forceRed(this)}})(typeof Q>"u"||Q,A)}),Ry=l1((A,Q)=>{var J=AL(),K=bA().Buffer;function C(U,Y){return K.from(U.toRed(J.mont(Y.modulus)).redPow(new J(Y.publicExponent)).fromRed().toArray())}Q.exports=C}),B51=l1((A,Q)=>{var J=A$(),K=VK(),C=NU(),U=Ly(),Y=Fy(),Z=AL(),X=Ry(),E=nN(),H=bA().Buffer;Q.exports=function(F,V,D){var L;F.padding?L=F.padding:D?L=1:L=4;var R=J(F),M;if(L===4)M=$(R,V);else if(L===1)M=I(R,V,D);else if(L===3){if(M=new Z(V),M.cmp(R.modulus)>=0)throw new Error("data too long for modulus")}else throw new Error("unknown padding");return D?E(M,R):X(M,R)};function $(F,V){var D=F.modulus.byteLength(),L=V.length,R=C("sha1").update(H.alloc(0)).digest(),M=R.length,T=2*M;if(L>D-T-2)throw new Error("message too long");var h=H.alloc(D-L-T-2),y=D-M-1,g=K(M),f=Y(H.concat([R,h,H.alloc(1,1),V],y),U(g,y)),u=Y(g,U(f,M));return new Z(H.concat([H.alloc(1),u,f],D))}function I(F,V,D){var L=V.length,R=F.modulus.byteLength();if(L>R-11)throw new Error("message too long");var M;return D?M=H.alloc(R-L-3,255):M=N(R-L-3),new Z(H.concat([H.from([0,D?1:2]),M,H.alloc(1),V],R))}function N(F){for(var V=H.allocUnsafe(F),D=0,L=K(F*2),R=0,M;D{var J=A$(),K=Ly(),C=Fy(),U=AL(),Y=nN(),Z=NU(),X=Ry(),E=bA().Buffer;Q.exports=function(N,F,V){var D;N.padding?D=N.padding:V?D=1:D=4;var L=J(N),R=L.modulus.byteLength();if(F.length>R||new U(F).cmp(L.modulus)>=0)throw new Error("decryption error");var M;V?M=X(new U(F),L):M=Y(F,L);var T=E.alloc(R-M.length);if(M=E.concat([T,M],R),D===4)return H(L,M);if(D===1)return $(L,M,V);if(D===3)return M;throw new Error("unknown padding")};function H(N,F){var V=N.modulus.byteLength(),D=Z("sha1").update(E.alloc(0)).digest(),L=D.length;if(F[0]!==0)throw new Error("decryption error");var R=F.slice(1,L+1),M=F.slice(L+1),T=C(R,K(M,L)),h=C(M,K(T,V-L-1));if(I(D,h.slice(0,L)))throw new Error("decryption error");for(var y=L;h[y]===0;)y++;if(h[y++]!==1)throw new Error("decryption error");return h.slice(y)}function $(N,F,V){for(var D=F.slice(0,2),L=2,R=0;F[L++]!==0;)if(L>=F.length){R++;break}var M=F.slice(2,L-1);if((D.toString("hex")!=="0002"&&!V||D.toString("hex")!=="0001"&&V)&&R++,M.length<8&&R++,R)throw new Error("decryption error");return F.slice(L)}function I(N,F){N=E.from(N),F=E.from(F);var V=0,D=N.length;N.length!==F.length&&(V++,D=Math.min(N.length,F.length));for(var L=-1;++L{A.publicEncrypt=B51(),A.privateDecrypt=X51(),A.privateEncrypt=function(Q,J){return A.publicEncrypt(Q,J,!0)},A.publicDecrypt=function(Q,J){return A.privateDecrypt(Q,J,!0)}}),$51=l1((A)=>{function Q(){throw new Error(`secure random number generation not supported by this browser -use chrome, FireFox or Internet Explorer 11`)}var J=bA(),K=VK(),C=J.Buffer,U=J.kMaxLength,Y=global.crypto||global.msCrypto,Z=Math.pow(2,32)-1;function X(N,F){if(typeof N!="number"||N!==N)throw new TypeError("offset must be a number");if(N>Z||N<0)throw new TypeError("offset must be a uint32");if(N>U||N>F)throw new RangeError("offset out of range")}function E(N,F,V){if(typeof N!="number"||N!==N)throw new TypeError("size must be a number");if(N>Z||N<0)throw new TypeError("size must be a uint32");if(N+F>V||N>U)throw new RangeError("buffer too small")}Y&&Y.getRandomValues?(A.randomFill=H,A.randomFillSync=I):(A.randomFill=Q,A.randomFillSync=Q);function H(N,F,V,D){if(!C.isBuffer(N)&&!(N instanceof global.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');if(typeof F=="function")D=F,F=0,V=N.length;else if(typeof V=="function")D=V,V=N.length-F;else if(typeof D!="function")throw new TypeError('"cb" argument must be a function');return X(F,N.length),E(V,F,N.length),$(N,F,V,D)}function $(N,F,V,D){var L=N.buffer,R=new Uint8Array(L,F,V);if(Y.getRandomValues(R),D){process.nextTick(function(){D(null,N)});return}return N;var M}function I(N,F,V){if(typeof F>"u"&&(F=0),!C.isBuffer(N)&&!(N instanceof global.Uint8Array))throw new TypeError('"buf" argument must be a Buffer or Uint8Array');return X(F,N.length),V===void 0&&(V=N.length-F),E(V,F,N.length),$(N,F,V)}}),zy=l1((A)=>{A.randomBytes=A.rng=A.pseudoRandomBytes=A.prng=VK(),A.createHash=A.Hash=NU(),A.createHmac=A.Hmac=fx();var Q=J91(),J=Object.keys(Q),K=["sha1","sha224","sha256","sha384","sha512","md5","rmd160"].concat(J);A.getHashes=function(){return K};var C=lx();A.pbkdf2=C.pbkdf2,A.pbkdf2Sync=C.pbkdf2Sync;var U=N91();A.Cipher=U.Cipher,A.createCipher=U.createCipher,A.Cipheriv=U.Cipheriv,A.createCipheriv=U.createCipheriv,A.Decipher=U.Decipher,A.createDecipher=U.createDecipher,A.Decipheriv=U.Decipheriv,A.createDecipheriv=U.createDecipheriv,A.getCiphers=U.getCiphers,A.listCiphers=U.listCiphers;var Y=D91();A.DiffieHellmanGroup=Y.DiffieHellmanGroup,A.createDiffieHellmanGroup=Y.createDiffieHellmanGroup,A.getDiffieHellman=Y.getDiffieHellman,A.createDiffieHellman=Y.createDiffieHellman,A.DiffieHellman=Y.DiffieHellman;var Z=Y51();A.createSign=Z.createSign,A.Sign=Z.Sign,A.createVerify=Z.createVerify,A.Verify=Z.Verify,A.createECDH=Z51();var X=E51();A.publicEncrypt=X.publicEncrypt,A.privateEncrypt=X.privateEncrypt,A.publicDecrypt=X.publicDecrypt,A.privateDecrypt=X.privateDecrypt;var E=$51();A.randomFill=E.randomFill,A.randomFillSync=E.randomFillSync,A.createCredentials=function(){throw new Error(["sorry, createCredentials is not implemented yet","we accept pull requests","https://github.com/crypto-browserify/crypto-browserify"].join(` -`))},A.constants={DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,NPN_ENABLED:1,ALPN_ENABLED:1,RSA_PKCS1_PADDING:1,RSA_SSLV23_PADDING:2,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}}),Dy={};sE(Dy,{DEFAULT_ENCODING:()=>DK,default:()=>Vy,getCurves:()=>KL,getRandomValues:()=>QL,randomUUID:()=>JL,scrypt:()=>J$,scryptSync:()=>Q$,timingSafeEqual:()=>OU,webcrypto:()=>CL});_N(Dy,CQ(zy()));H51=CQ(zy()),G51=["p192","p224","p256","p384","p521","curve25519","ed25519","secp256k1","secp224r1","prime256v1","prime192v1","ed25519","secp384r1","secp521r1"];OU="timingSafeEqual"in crypto?(A,Q)=>{let{byteLength:J}=A,{byteLength:K}=Q;if(typeof J!="number"||typeof K!="number")throw new TypeError("Input must be an array buffer view");if(J!==K)throw new RangeError("Input buffers must have the same length");return crypto.timingSafeEqual(A,Q)}:void 0,Q$="scryptSync"in crypto?(A,Q,J,K)=>{let C=crypto.scryptSync(A,Q,J,K);return DK!=="buffer"?new Buffer(C).toString(DK):new Buffer(C)}:void 0,J$="scryptSync"in crypto?function(A,Q,J,K,C){if(typeof K=="function"&&(C=K,K=void 0),typeof C!="function"){var U=new TypeError("callback must be a function");throw U.code="ERR_INVALID_CALLBACK",U}try{let Y=crypto.scryptSync(A,Q,J,K);process.nextTick(C,null,DK!=="buffer"?new Buffer(Y).toString(DK):new Buffer(Y))}catch(Y){throw Y}}:void 0;OU&&(Object.defineProperty(OU,"name",{value:"::bunternal::"}),Object.defineProperty(J$,"name",{value:"::bunternal::"}),Object.defineProperty(Q$,"name",{value:"::bunternal::"}));CL=crypto,Vy={...H51,getRandomValues:QL,randomUUID:JL,timingSafeEqual:OU,scryptSync:Q$,scrypt:J$,webcrypto:CL,getCurves:KL};/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *//*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *//*! safe-buffer. MIT License. Feross Aboukhadijeh */});var bp=B0((dz1,kG)=>{/*! - * The following is a version of the struct-fu library - * fork by ariankordi: https://github.com/ariankordi/struct-fu - * with the following changes made for code size: - * Added: _.uintptr, mapping to _.uint32le (with WASM in mind) - * Added (TODO): add JSDoc StructInstance template - * Removed: Polyfills Function.prototype.bind, TextEncoder/TextDecoder - * Removed: bitfield, bitfieldLE... - * Removed: char16be, swapBytesPairs - * Removed: 64-bit types, 16-bit float - * Modified: addField (no bit handling), _.struct (rm "aligned bitfield" message) - */var K8={};function SG(A){return new Uint8Array(new ArrayBuffer(A))}function Cz(A){var Q=Array.prototype.slice.call(arguments,1);return Q.forEach(function(J){Object.keys(J).forEach(function(K){A[K]=J[K]})}),A}function F4(A,Q){return A.bytes+=Q.size,A}function jG(A,Q){var J=typeof Q==="number"?Cz({name:A.name,field:A,valueFromBytes:function(K,C){C||(C={bytes:0,bits:0});var U=new Array(Q);for(var Y=0,Z=U.length;Y>8&255}return J}});function u9(A,Q,J){var K="get"+A,C="set"+A;return Q||(Q=+A.match(/\d+/)[0]/8),function(U,Y){if(typeof U!=="string")Y=U,U=null;return jG({valueFromBytes:function(Z,X){X||(X={bytes:0});var E=Z instanceof ArrayBuffer?new Uint8Array(Z):Z,H=new DataView(E.buffer,E.byteOffset,E.byteLength),$=H[K](X.bytes,J);return F4(X,this),$},bytesFromValue:function(Z,X,E){Z||(Z=0),X||(X=SG(this.size)),E||(E={bytes:0});var H=X instanceof ArrayBuffer?new Uint8Array(X):X,$=new DataView(H.buffer,H.byteOffset,H.byteLength);return $[C](E.bytes,Z,J),F4(E,this),X},size:Q,name:U},Y)}}K8.uint8=u9("Uint8",1,!1);K8.uint16=u9("Uint16",2,!1);K8.uint32=u9("Uint32",4,!1);K8.uint16le=u9("Uint16",2,!0);K8.uint32le=u9("Uint32",4,!0);K8.uintptr=K8.uint32le;K8.int8=u9("Int8",1,!1);K8.int16=u9("Int16",2,!1);K8.int32=u9("Int32",4,!1);K8.int16le=u9("Int16",2,!0);K8.int32le=u9("Int32",4,!0);K8.float32=u9("Float32",4,!1);K8.float32le=u9("Float32",4,!0);K8.derive=function(A,Q,J){return function(K,C){if(typeof K!=="string")C=K,K=null;return jG(Cz({valueFromBytes:function(U,Y){return J(A.valueFromBytes(U,Y))},bytesFromValue:function(U,Y,Z){return A.bytesFromValue(Q(U),Y,Z)},name:K},"width"in A?{width:A.width}:{size:A.size}),C)}};if(typeof kG!=="undefined"&&kG.exports)kG.exports=K8;else window._=K8});var dc={};z3(dc,{createWorker:()=>QE1});var QE1=()=>new Worker(URL.createObjectURL(new Blob([`class x{constructor(a,b){this.width=b;this.height=a.length/b;this.data=a}static createEmpty(a,b){return new x(new Uint8ClampedArray(a*b),a)}get(a,b){return 0>a||a>=this.width||0>b||b>=this.height?!1:!!this.data[b*this.width+a]}set(a,b,c){this.data[b*this.width+a]=c?1:0}setRegion(a,b,c,d,e){for(let f=b;fa||32this.available())throw Error("Cannot read "+a.toString()+" bits");var b=0;if(0>8-c<>b;a-=c;this.bitOffset+=c;8===this.bitOffset&&(this.bitOffset=0,this.byteOffset++)}if(0>c<>c, -this.bitOffset+=a)}return b}available(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset}}var B,C=B||(B={});C.Numeric="numeric";C.Alphanumeric="alphanumeric";C.Byte="byte";C.Kanji="kanji";C.ECI="eci";C.StructuredAppend="structuredappend";var D,E=D||(D={});E[E.Terminator=0]="Terminator";E[E.Numeric=1]="Numeric";E[E.Alphanumeric=2]="Alphanumeric";E[E.Byte=4]="Byte";E[E.Kanji=8]="Kanji";E[E.ECI=7]="ECI";E[E.StructuredAppend=3]="StructuredAppend";let F="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:".split(""); -function ca(a,b){let c=[],d="";b=a.readBits([8,16,16][b]);for(let e=0;e\`%\${("0"+e.toString(16)).substr(-2)}\`).join(""))}catch(e){}return{bytes:c,text:d}} -function da(a,b){a=new ba(a);let c=9>=b?0:26>=b?1:2;for(b={text:"",bytes:[],chunks:[],version:b};4<=a.available();){var d=a.readBits(4);if(d===D.Terminator)return b;if(d===D.ECI)0===a.readBits(1)?b.chunks.push({type:B.ECI,assignmentNumber:a.readBits(7)}):0===a.readBits(1)?b.chunks.push({type:B.ECI,assignmentNumber:a.readBits(14)}):0===a.readBits(1)?b.chunks.push({type:B.ECI,assignmentNumber:a.readBits(21)}):b.chunks.push({type:B.ECI,assignmentNumber:-1});else if(d===D.Numeric){var e=a,f=[];d="";for(var g= -e.readBits([10,12,14][c]);3<=g;){var h=e.readBits(10);if(1E3<=h)throw Error("Invalid numeric value above 999");var k=Math.floor(h/100),m=Math.floor(h/10)%10;h%=10;f.push(48+k,48+m,48+h);d+=k.toString()+m.toString()+h.toString();g-=3}if(2===g){g=e.readBits(7);if(100<=g)throw Error("Invalid numeric value above 99");e=Math.floor(g/10);g%=10;f.push(48+e,48+g);d+=e.toString()+g.toString()}else if(1===g){e=e.readBits(4);if(10<=e)throw Error("Invalid numeric value above 9");f.push(48+e);d+=e.toString()}b.text+= -d;b.bytes.push(...f);b.chunks.push({type:B.Numeric,text:d})}else if(d===D.Alphanumeric){e=a;f=[];d="";for(g=e.readBits([9,11,13][c]);2<=g;)m=e.readBits(11),k=Math.floor(m/45),m%=45,f.push(F[k].charCodeAt(0),F[m].charCodeAt(0)),d+=F[k]+F[m],g-=2;1===g&&(e=e.readBits(6),f.push(F[e].charCodeAt(0)),d+=F[e]);b.text+=d;b.bytes.push(...f);b.chunks.push({type:B.Alphanumeric,text:d})}else if(d===D.Byte)d=ca(a,c),b.text+=d.text,b.bytes.push(...d.bytes),b.chunks.push({type:B.Byte,bytes:d.bytes,text:d.text}); -else if(d===D.Kanji){f=a;d=[];e=f.readBits([8,10,12][c]);for(g=0;gk?k+33088:k+49472,d.push(k>>8,k&255);f=(new TextDecoder("shift-jis")).decode(Uint8Array.from(d));b.text+=f;b.bytes.push(...d);b.chunks.push({type:B.Kanji,bytes:d,text:f})}else d===D.StructuredAppend&&b.chunks.push({type:B.StructuredAppend,currentSequence:a.readBits(4),totalSequence:a.readBits(4),parity:a.readBits(8)})}if(0===a.available()||0===a.readBits(a.available()))return b} -class G{constructor(a,b){if(0===b.length)throw Error("No coefficients.");this.field=a;let c=b.length;if(1a.length&&([b,a]=[a,b]);let c=new Uint8ClampedArray(a.length),d=a.length-b.length;for(var e=0;ea)throw Error("Invalid degree less than 0");if(0===b)return this.field.zero;let c=this.coefficients.length;a=new Uint8ClampedArray(c+a);for(let d=0;d{b^=d}),b;b=this.coefficients[0];for(let d=1;d=this.size&&(a=(a^this.primitive)&this.size-1);for(a=0;aa)throw Error("Invalid monomial degree less than 0");if(0===b)return this.zero;a=new Uint8ClampedArray(a+1);a[0]=b;return new G(this,a)}log(a){if(0===a)throw Error("Can't take log(0)");return this.logTable[a]}exp(a){return this.expTable[a]}} -function fa(a,b,c,d){b.degree()=d/2;){var g=b;let h=e;b=c;e=f;if(b.isZero())return null;c=g;f=a.zero;g=b.getCoefficient(b.degree());for(g=a.inverse(g);c.degree()>=b.degree()&&!c.isZero();){let k=c.degree()-b.degree(),m=a.multiply(c.getCoefficient(c.degree()),g);f=f.addOrSubtract(a.buildMonomial(k,m));c=c.addOrSubtract(b.multiplyByMonomial(k,m))}f=f.multiplyPoly(e).addOrSubtract(h);if(c.degree()>=b.degree())return null}d=f.getCoefficient(0); -if(0===d)return null;a=a.inverse(d);return[f.multiply(a),c.multiply(a)]} -function ha(a,b){let c=new Uint8ClampedArray(a.length);c.set(a);a=new ea(285,256,0);var d=new G(a,c),e=new Uint8ClampedArray(b),f=!1;for(var g=0;gf)return null;c[f]^=d[e]}return c} -let I=[{infoBits:null,versionNumber:1,alignmentPatternCenters:[],errorCorrectionLevels:[{ecCodewordsPerBlock:7,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:19}]},{ecCodewordsPerBlock:10,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:16}]},{ecCodewordsPerBlock:13,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:13}]},{ecCodewordsPerBlock:17,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:9}]}]},{infoBits:null,versionNumber:2,alignmentPatternCenters:[6,18],errorCorrectionLevels:[{ecCodewordsPerBlock:10,ecBlocks:[{numBlocks:1, -dataCodewordsPerBlock:34}]},{ecCodewordsPerBlock:16,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:28}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:22}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:16}]}]},{infoBits:null,versionNumber:3,alignmentPatternCenters:[6,22],errorCorrectionLevels:[{ecCodewordsPerBlock:15,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:55}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:44}]},{ecCodewordsPerBlock:18, -ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:17}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:13}]}]},{infoBits:null,versionNumber:4,alignmentPatternCenters:[6,26],errorCorrectionLevels:[{ecCodewordsPerBlock:20,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:80}]},{ecCodewordsPerBlock:18,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:32}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:24}]},{ecCodewordsPerBlock:16,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:9}]}]}, -{infoBits:null,versionNumber:5,alignmentPatternCenters:[6,30],errorCorrectionLevels:[{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:108}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:43}]},{ecCodewordsPerBlock:18,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:15},{numBlocks:2,dataCodewordsPerBlock:16}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:11},{numBlocks:2,dataCodewordsPerBlock:12}]}]},{infoBits:null,versionNumber:6,alignmentPatternCenters:[6, -34],errorCorrectionLevels:[{ecCodewordsPerBlock:18,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:68}]},{ecCodewordsPerBlock:16,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:27}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:19}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:15}]}]},{infoBits:31892,versionNumber:7,alignmentPatternCenters:[6,22,38],errorCorrectionLevels:[{ecCodewordsPerBlock:20,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:78}]},{ecCodewordsPerBlock:18, -ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:31}]},{ecCodewordsPerBlock:18,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:14},{numBlocks:4,dataCodewordsPerBlock:15}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:13},{numBlocks:1,dataCodewordsPerBlock:14}]}]},{infoBits:34236,versionNumber:8,alignmentPatternCenters:[6,24,42],errorCorrectionLevels:[{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:97}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:38}, -{numBlocks:2,dataCodewordsPerBlock:39}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:18},{numBlocks:2,dataCodewordsPerBlock:19}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:14},{numBlocks:2,dataCodewordsPerBlock:15}]}]},{infoBits:39577,versionNumber:9,alignmentPatternCenters:[6,26,46],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:116}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:36}, -{numBlocks:2,dataCodewordsPerBlock:37}]},{ecCodewordsPerBlock:20,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:16},{numBlocks:4,dataCodewordsPerBlock:17}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:12},{numBlocks:4,dataCodewordsPerBlock:13}]}]},{infoBits:42195,versionNumber:10,alignmentPatternCenters:[6,28,50],errorCorrectionLevels:[{ecCodewordsPerBlock:18,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:68},{numBlocks:2,dataCodewordsPerBlock:69}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:4, -dataCodewordsPerBlock:43},{numBlocks:1,dataCodewordsPerBlock:44}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:6,dataCodewordsPerBlock:19},{numBlocks:2,dataCodewordsPerBlock:20}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:6,dataCodewordsPerBlock:15},{numBlocks:2,dataCodewordsPerBlock:16}]}]},{infoBits:48118,versionNumber:11,alignmentPatternCenters:[6,30,54],errorCorrectionLevels:[{ecCodewordsPerBlock:20,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:81}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:1, -dataCodewordsPerBlock:50},{numBlocks:4,dataCodewordsPerBlock:51}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:22},{numBlocks:4,dataCodewordsPerBlock:23}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:12},{numBlocks:8,dataCodewordsPerBlock:13}]}]},{infoBits:51042,versionNumber:12,alignmentPatternCenters:[6,32,58],errorCorrectionLevels:[{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:92},{numBlocks:2,dataCodewordsPerBlock:93}]}, -{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:6,dataCodewordsPerBlock:36},{numBlocks:2,dataCodewordsPerBlock:37}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:20},{numBlocks:6,dataCodewordsPerBlock:21}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:7,dataCodewordsPerBlock:14},{numBlocks:4,dataCodewordsPerBlock:15}]}]},{infoBits:55367,versionNumber:13,alignmentPatternCenters:[6,34,62],errorCorrectionLevels:[{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:107}]}, -{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:8,dataCodewordsPerBlock:37},{numBlocks:1,dataCodewordsPerBlock:38}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:8,dataCodewordsPerBlock:20},{numBlocks:4,dataCodewordsPerBlock:21}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:12,dataCodewordsPerBlock:11},{numBlocks:4,dataCodewordsPerBlock:12}]}]},{infoBits:58893,versionNumber:14,alignmentPatternCenters:[6,26,46,66],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:115}, -{numBlocks:1,dataCodewordsPerBlock:116}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:40},{numBlocks:5,dataCodewordsPerBlock:41}]},{ecCodewordsPerBlock:20,ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:16},{numBlocks:5,dataCodewordsPerBlock:17}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:12},{numBlocks:5,dataCodewordsPerBlock:13}]}]},{infoBits:63784,versionNumber:15,alignmentPatternCenters:[6,26,48,70],errorCorrectionLevels:[{ecCodewordsPerBlock:22, -ecBlocks:[{numBlocks:5,dataCodewordsPerBlock:87},{numBlocks:1,dataCodewordsPerBlock:88}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:5,dataCodewordsPerBlock:41},{numBlocks:5,dataCodewordsPerBlock:42}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:5,dataCodewordsPerBlock:24},{numBlocks:7,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:12},{numBlocks:7,dataCodewordsPerBlock:13}]}]},{infoBits:68472,versionNumber:16,alignmentPatternCenters:[6,26,50, -74],errorCorrectionLevels:[{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:5,dataCodewordsPerBlock:98},{numBlocks:1,dataCodewordsPerBlock:99}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:7,dataCodewordsPerBlock:45},{numBlocks:3,dataCodewordsPerBlock:46}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:15,dataCodewordsPerBlock:19},{numBlocks:2,dataCodewordsPerBlock:20}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:15},{numBlocks:13,dataCodewordsPerBlock:16}]}]},{infoBits:70749, -versionNumber:17,alignmentPatternCenters:[6,30,54,78],errorCorrectionLevels:[{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:107},{numBlocks:5,dataCodewordsPerBlock:108}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:10,dataCodewordsPerBlock:46},{numBlocks:1,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:22},{numBlocks:15,dataCodewordsPerBlock:23}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:14},{numBlocks:17, -dataCodewordsPerBlock:15}]}]},{infoBits:76311,versionNumber:18,alignmentPatternCenters:[6,30,56,82],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:5,dataCodewordsPerBlock:120},{numBlocks:1,dataCodewordsPerBlock:121}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:9,dataCodewordsPerBlock:43},{numBlocks:4,dataCodewordsPerBlock:44}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:22},{numBlocks:1,dataCodewordsPerBlock:23}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:2, -dataCodewordsPerBlock:14},{numBlocks:19,dataCodewordsPerBlock:15}]}]},{infoBits:79154,versionNumber:19,alignmentPatternCenters:[6,30,58,86],errorCorrectionLevels:[{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:113},{numBlocks:4,dataCodewordsPerBlock:114}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:44},{numBlocks:11,dataCodewordsPerBlock:45}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:21},{numBlocks:4,dataCodewordsPerBlock:22}]}, -{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:9,dataCodewordsPerBlock:13},{numBlocks:16,dataCodewordsPerBlock:14}]}]},{infoBits:84390,versionNumber:20,alignmentPatternCenters:[6,34,62,90],errorCorrectionLevels:[{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:107},{numBlocks:5,dataCodewordsPerBlock:108}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:41},{numBlocks:13,dataCodewordsPerBlock:42}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:15,dataCodewordsPerBlock:24}, -{numBlocks:5,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:15,dataCodewordsPerBlock:15},{numBlocks:10,dataCodewordsPerBlock:16}]}]},{infoBits:87683,versionNumber:21,alignmentPatternCenters:[6,28,50,72,94],errorCorrectionLevels:[{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:116},{numBlocks:4,dataCodewordsPerBlock:117}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:42}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:22}, -{numBlocks:6,dataCodewordsPerBlock:23}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:19,dataCodewordsPerBlock:16},{numBlocks:6,dataCodewordsPerBlock:17}]}]},{infoBits:92361,versionNumber:22,alignmentPatternCenters:[6,26,50,74,98],errorCorrectionLevels:[{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:111},{numBlocks:7,dataCodewordsPerBlock:112}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:46}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:7,dataCodewordsPerBlock:24}, -{numBlocks:16,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:34,dataCodewordsPerBlock:13}]}]},{infoBits:96236,versionNumber:23,alignmentPatternCenters:[6,30,54,74,102],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:121},{numBlocks:5,dataCodewordsPerBlock:122}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:47},{numBlocks:14,dataCodewordsPerBlock:48}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:24}, -{numBlocks:14,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:16,dataCodewordsPerBlock:15},{numBlocks:14,dataCodewordsPerBlock:16}]}]},{infoBits:102084,versionNumber:24,alignmentPatternCenters:[6,28,54,80,106],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:6,dataCodewordsPerBlock:117},{numBlocks:4,dataCodewordsPerBlock:118}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:6,dataCodewordsPerBlock:45},{numBlocks:14,dataCodewordsPerBlock:46}]},{ecCodewordsPerBlock:30, -ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:24},{numBlocks:16,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:30,dataCodewordsPerBlock:16},{numBlocks:2,dataCodewordsPerBlock:17}]}]},{infoBits:102881,versionNumber:25,alignmentPatternCenters:[6,32,58,84,110],errorCorrectionLevels:[{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:8,dataCodewordsPerBlock:106},{numBlocks:4,dataCodewordsPerBlock:107}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:8,dataCodewordsPerBlock:47},{numBlocks:13, -dataCodewordsPerBlock:48}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:7,dataCodewordsPerBlock:24},{numBlocks:22,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:22,dataCodewordsPerBlock:15},{numBlocks:13,dataCodewordsPerBlock:16}]}]},{infoBits:110507,versionNumber:26,alignmentPatternCenters:[6,30,58,86,114],errorCorrectionLevels:[{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:10,dataCodewordsPerBlock:114},{numBlocks:2,dataCodewordsPerBlock:115}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:19, -dataCodewordsPerBlock:46},{numBlocks:4,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:28,dataCodewordsPerBlock:22},{numBlocks:6,dataCodewordsPerBlock:23}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:33,dataCodewordsPerBlock:16},{numBlocks:4,dataCodewordsPerBlock:17}]}]},{infoBits:110734,versionNumber:27,alignmentPatternCenters:[6,34,62,90,118],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:8,dataCodewordsPerBlock:122},{numBlocks:4,dataCodewordsPerBlock:123}]}, -{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:22,dataCodewordsPerBlock:45},{numBlocks:3,dataCodewordsPerBlock:46}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:8,dataCodewordsPerBlock:23},{numBlocks:26,dataCodewordsPerBlock:24}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:12,dataCodewordsPerBlock:15},{numBlocks:28,dataCodewordsPerBlock:16}]}]},{infoBits:117786,versionNumber:28,alignmentPatternCenters:[6,26,50,74,98,122],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:117}, -{numBlocks:10,dataCodewordsPerBlock:118}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:45},{numBlocks:23,dataCodewordsPerBlock:46}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:24},{numBlocks:31,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:15},{numBlocks:31,dataCodewordsPerBlock:16}]}]},{infoBits:119615,versionNumber:29,alignmentPatternCenters:[6,30,54,78,102,126],errorCorrectionLevels:[{ecCodewordsPerBlock:30, -ecBlocks:[{numBlocks:7,dataCodewordsPerBlock:116},{numBlocks:7,dataCodewordsPerBlock:117}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:21,dataCodewordsPerBlock:45},{numBlocks:7,dataCodewordsPerBlock:46}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:23},{numBlocks:37,dataCodewordsPerBlock:24}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:19,dataCodewordsPerBlock:15},{numBlocks:26,dataCodewordsPerBlock:16}]}]},{infoBits:126325,versionNumber:30,alignmentPatternCenters:[6, -26,52,78,104,130],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:5,dataCodewordsPerBlock:115},{numBlocks:10,dataCodewordsPerBlock:116}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:19,dataCodewordsPerBlock:47},{numBlocks:10,dataCodewordsPerBlock:48}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:15,dataCodewordsPerBlock:24},{numBlocks:25,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:23,dataCodewordsPerBlock:15},{numBlocks:25,dataCodewordsPerBlock:16}]}]}, -{infoBits:127568,versionNumber:31,alignmentPatternCenters:[6,30,56,82,108,134],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:13,dataCodewordsPerBlock:115},{numBlocks:3,dataCodewordsPerBlock:116}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:46},{numBlocks:29,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:42,dataCodewordsPerBlock:24},{numBlocks:1,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:23,dataCodewordsPerBlock:15}, -{numBlocks:28,dataCodewordsPerBlock:16}]}]},{infoBits:133589,versionNumber:32,alignmentPatternCenters:[6,34,60,86,112,138],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:115}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:10,dataCodewordsPerBlock:46},{numBlocks:23,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:10,dataCodewordsPerBlock:24},{numBlocks:35,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:19, -dataCodewordsPerBlock:15},{numBlocks:35,dataCodewordsPerBlock:16}]}]},{infoBits:136944,versionNumber:33,alignmentPatternCenters:[6,30,58,86,114,142],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:115},{numBlocks:1,dataCodewordsPerBlock:116}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:14,dataCodewordsPerBlock:46},{numBlocks:21,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:29,dataCodewordsPerBlock:24},{numBlocks:19,dataCodewordsPerBlock:25}]}, -{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:15},{numBlocks:46,dataCodewordsPerBlock:16}]}]},{infoBits:141498,versionNumber:34,alignmentPatternCenters:[6,34,62,90,118,146],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:13,dataCodewordsPerBlock:115},{numBlocks:6,dataCodewordsPerBlock:116}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:14,dataCodewordsPerBlock:46},{numBlocks:23,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:44, -dataCodewordsPerBlock:24},{numBlocks:7,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:59,dataCodewordsPerBlock:16},{numBlocks:1,dataCodewordsPerBlock:17}]}]},{infoBits:145311,versionNumber:35,alignmentPatternCenters:[6,30,54,78,102,126,150],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:12,dataCodewordsPerBlock:121},{numBlocks:7,dataCodewordsPerBlock:122}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:12,dataCodewordsPerBlock:47},{numBlocks:26,dataCodewordsPerBlock:48}]}, -{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:39,dataCodewordsPerBlock:24},{numBlocks:14,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:22,dataCodewordsPerBlock:15},{numBlocks:41,dataCodewordsPerBlock:16}]}]},{infoBits:150283,versionNumber:36,alignmentPatternCenters:[6,24,50,76,102,128,154],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:6,dataCodewordsPerBlock:121},{numBlocks:14,dataCodewordsPerBlock:122}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:6, -dataCodewordsPerBlock:47},{numBlocks:34,dataCodewordsPerBlock:48}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:46,dataCodewordsPerBlock:24},{numBlocks:10,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:15},{numBlocks:64,dataCodewordsPerBlock:16}]}]},{infoBits:152622,versionNumber:37,alignmentPatternCenters:[6,28,54,80,106,132,158],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:122},{numBlocks:4,dataCodewordsPerBlock:123}]}, -{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:29,dataCodewordsPerBlock:46},{numBlocks:14,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:49,dataCodewordsPerBlock:24},{numBlocks:10,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:24,dataCodewordsPerBlock:15},{numBlocks:46,dataCodewordsPerBlock:16}]}]},{infoBits:158308,versionNumber:38,alignmentPatternCenters:[6,32,58,84,110,136,162],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:4, -dataCodewordsPerBlock:122},{numBlocks:18,dataCodewordsPerBlock:123}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:13,dataCodewordsPerBlock:46},{numBlocks:32,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:48,dataCodewordsPerBlock:24},{numBlocks:14,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:42,dataCodewordsPerBlock:15},{numBlocks:32,dataCodewordsPerBlock:16}]}]},{infoBits:161089,versionNumber:39,alignmentPatternCenters:[6,26,54,82,110,138,166], -errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:20,dataCodewordsPerBlock:117},{numBlocks:4,dataCodewordsPerBlock:118}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:40,dataCodewordsPerBlock:47},{numBlocks:7,dataCodewordsPerBlock:48}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:43,dataCodewordsPerBlock:24},{numBlocks:22,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:10,dataCodewordsPerBlock:15},{numBlocks:67,dataCodewordsPerBlock:16}]}]},{infoBits:167017, -versionNumber:40,alignmentPatternCenters:[6,30,58,86,114,142,170],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:19,dataCodewordsPerBlock:118},{numBlocks:6,dataCodewordsPerBlock:119}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:18,dataCodewordsPerBlock:47},{numBlocks:31,dataCodewordsPerBlock:48}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:34,dataCodewordsPerBlock:24},{numBlocks:34,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:20,dataCodewordsPerBlock:15}, -{numBlocks:61,dataCodewordsPerBlock:16}]}]}];function J(a,b){a^=b;for(b=0;a;)b++,a&=a-1;return b}function K(a,b){return b<<1|a} -let ia=[{bits:21522,formatInfo:{errorCorrectionLevel:1,dataMask:0}},{bits:20773,formatInfo:{errorCorrectionLevel:1,dataMask:1}},{bits:24188,formatInfo:{errorCorrectionLevel:1,dataMask:2}},{bits:23371,formatInfo:{errorCorrectionLevel:1,dataMask:3}},{bits:17913,formatInfo:{errorCorrectionLevel:1,dataMask:4}},{bits:16590,formatInfo:{errorCorrectionLevel:1,dataMask:5}},{bits:20375,formatInfo:{errorCorrectionLevel:1,dataMask:6}},{bits:19104,formatInfo:{errorCorrectionLevel:1,dataMask:7}},{bits:30660,formatInfo:{errorCorrectionLevel:0, -dataMask:0}},{bits:29427,formatInfo:{errorCorrectionLevel:0,dataMask:1}},{bits:32170,formatInfo:{errorCorrectionLevel:0,dataMask:2}},{bits:30877,formatInfo:{errorCorrectionLevel:0,dataMask:3}},{bits:26159,formatInfo:{errorCorrectionLevel:0,dataMask:4}},{bits:25368,formatInfo:{errorCorrectionLevel:0,dataMask:5}},{bits:27713,formatInfo:{errorCorrectionLevel:0,dataMask:6}},{bits:26998,formatInfo:{errorCorrectionLevel:0,dataMask:7}},{bits:5769,formatInfo:{errorCorrectionLevel:3,dataMask:0}},{bits:5054, -formatInfo:{errorCorrectionLevel:3,dataMask:1}},{bits:7399,formatInfo:{errorCorrectionLevel:3,dataMask:2}},{bits:6608,formatInfo:{errorCorrectionLevel:3,dataMask:3}},{bits:1890,formatInfo:{errorCorrectionLevel:3,dataMask:4}},{bits:597,formatInfo:{errorCorrectionLevel:3,dataMask:5}},{bits:3340,formatInfo:{errorCorrectionLevel:3,dataMask:6}},{bits:2107,formatInfo:{errorCorrectionLevel:3,dataMask:7}},{bits:13663,formatInfo:{errorCorrectionLevel:2,dataMask:0}},{bits:12392,formatInfo:{errorCorrectionLevel:2, -dataMask:1}},{bits:16177,formatInfo:{errorCorrectionLevel:2,dataMask:2}},{bits:14854,formatInfo:{errorCorrectionLevel:2,dataMask:3}},{bits:9396,formatInfo:{errorCorrectionLevel:2,dataMask:4}},{bits:8579,formatInfo:{errorCorrectionLevel:2,dataMask:5}},{bits:11994,formatInfo:{errorCorrectionLevel:2,dataMask:6}},{bits:11245,formatInfo:{errorCorrectionLevel:2,dataMask:7}}],ja=[a=>0===(a.y+a.x)%2,a=>0===a.y%2,a=>0===a.x%3,a=>0===(a.y+a.x)%3,a=>0===(Math.floor(a.y/2)+Math.floor(a.x/3))%2,a=>0===a.x*a.y% -2+a.x*a.y%3,a=>0===(a.y*a.x%2+a.y*a.x%3)%2,a=>0===((a.y+a.x)%2+a.y*a.x%3)%2]; -function ka(a,b,c){c=ja[c.dataMask];let d=a.height;var e=17+4*b.versionNumber;let f=x.createEmpty(e,e);f.setRegion(0,0,9,9,!0);f.setRegion(e-8,0,8,9,!0);f.setRegion(0,e-8,9,8,!0);for(var g of b.alignmentPatternCenters)for(var h of b.alignmentPatternCenters)6===g&&6===h||6===g&&h===e-7||g===e-7&&6===h||f.setRegion(g-2,h-2,5,5,!0);f.setRegion(6,9,1,e-17,!0);f.setRegion(9,6,e-17,1,!0);6n;n++){let q=k-n;if(!f.get(q,l)){h++;let r=a.get(q,l);c({y:l,x:q})&&(r=!r);g=g<<1|r;8===h&&(b.push(g),g=h=0)}}}e=!e}return b} -function la(a){var b=a.height,c=Math.floor((b-17)/4);if(6>=c)return I[c-1];c=0;for(var d=5;0<=d;d--)for(var e=b-9;e>=b-11;e--)c=K(a.get(e,d),c);d=0;for(e=5;0<=e;e--)for(let g=b-9;g>=b-11;g--)d=K(a.get(e,g),d);a=Infinity;let f;for(let g of I){if(g.infoBits===c||g.infoBits===d)return g;b=J(c,g.infoBits);b=a)return f} -function ma(a){let b=0;for(var c=0;8>=c;c++)6!==c&&(b=K(a.get(c,8),b));for(c=7;0<=c;c--)6!==c&&(b=K(a.get(8,c),b));var d=a.height;c=0;for(var e=d-1;e>=d-7;e--)c=K(a.get(8,e),c);for(e=d-8;e=a?d:null} -function na(a,b,c){let d=b.errorCorrectionLevels[c],e=[],f=0;d.ecBlocks.forEach(h=>{for(let k=0;ke+f.numDataCodewords,0);c=new Uint8ClampedArray(c);a=0;for(let e of d){d=ha(e.codewords,e.codewords.length-e.numDataCodewords);if(!d)return null;for(let f=0;f{const p=g*r+m*u+q;return{x:(e*r+h*u+l)/p,y:(f*r+k*u+n)/p}};for(let r=0;rMath.sqrt(Math.pow(b.x-a.x,2)+Math.pow(b.y-a.y,2));function O(a){return a.reduce((b,c)=>b+c)} -function qa(a,b,c){let d=N(a,b),e=N(b,c),f=N(a,c),g,h,k;e>=d&&e>=f?[g,h,k]=[b,a,c]:f>=e&&f>=d?[g,h,k]=[a,b,c]:[g,h,k]=[a,c,b];0>(k.x-h.x)*(g.y-h.y)-(k.y-h.y)*(g.x-h.x)&&([g,k]=[k,g]);return{bottomLeft:g,topLeft:h,topRight:k}} -function ra(a,b,c,d){d=(O(P(a,c,d,5))/7+O(P(a,b,d,5))/7+O(P(c,a,d,5))/7+O(P(b,a,d,5))/7)/4;if(1>d)throw Error("Invalid module size");b=Math.round(N(a,b)/d);a=Math.round(N(a,c)/d);a=Math.floor((b+a)/2)+7;switch(a%4){case 0:a++;break;case 2:a--}return{dimension:a,moduleSize:d}} -function Q(a,b,c,d){let e=[{x:Math.floor(a.x),y:Math.floor(a.y)}];var f=Math.abs(b.y-a.y)>Math.abs(b.x-a.x);if(f){var g=Math.floor(a.y);var h=Math.floor(a.x);a=Math.floor(b.y);b=Math.floor(b.x)}else g=Math.floor(a.x),h=Math.floor(a.y),a=Math.floor(b.x),b=Math.floor(b.y);let k=Math.abs(a-g),m=Math.abs(b-h),l=Math.floor(-k/2),n=g{d+=Math.pow(a[f]-e*c,2)});return{averageSize:c,error:d}} -function S(a,b,c){try{let d=P(a,{x:-1,y:a.y},c,b.length),e=P(a,{x:a.x,y:-1},c,b.length),f=P(a,{x:Math.max(0,a.x-a.y)-1,y:Math.max(0,a.y-a.x)-1},c,b.length),g=P(a,{x:Math.min(c.width,a.x+a.y)+1,y:Math.min(c.height,a.y+a.x)+1},c,b.length),h=R(d,b),k=R(e,b),m=R(f,b),l=R(g,b),n=(h.averageSize+k.averageSize+m.averageSize+l.averageSize)/4;return Math.sqrt(h.error*h.error+k.error*k.error+m.error*m.error+l.error*l.error)+(Math.pow(h.averageSize-n,2)+Math.pow(k.averageSize-n,2)+Math.pow(m.averageSize-n,2)+ -Math.pow(l.averageSize-n,2))/n}catch(d){return Infinity}}function T(a,b){for(var c=Math.round(b.x);a.get(c,Math.round(b.y));)c--;for(var d=Math.round(b.x);a.get(d,Math.round(b.y));)d++;c=(c+d)/2;for(d=Math.round(b.y);a.get(Math.round(c),d);)d--;for(b=Math.round(b.y);a.get(Math.round(c),b);)b++;return{x:c,y:(d+b)/2}} -function sa(a){var b=[],c=[];let d=[];var e=[];for(let p=0;p<=a.height;p++){var f=0,g=!1;let t=[0,0,0,0,0];for(let v=-1;v<=a.width;v++){var h=a.get(v,p);if(h===g)f++;else{t=[t[1],t[2],t[3],t[4],f];f=1;g=h;var k=O(t)/7;k=Math.abs(t[0]-k)y>=w.bottom.startX&& -y<=w.bottom.endX||z>=w.bottom.startX&&y<=w.bottom.endX||y<=w.bottom.startX&&z>=w.bottom.endX&&1.5>t[2]/(w.bottom.endX-w.bottom.startX)&&.5y>=w.bottom.startX&&y<=w.bottom.endX||z>=w.bottom.startX&&y<=w.bottom.endX||y<=w.bottom.startX&&z>=w.bottom.endX&&1.5>t[2]/(w.bottom.endX-w.bottom.startX)&&.5v.bottom.y!==p&&2<=v.bottom.y-v.top.y));c=c.filter(v=>v.bottom.y===p);d.push(...e.filter(v=>v.bottom.y!==p));e=e.filter(v=>v.bottom.y===p)}b.push(...c.filter(p=>2<=p.bottom.y-p.top.y));d.push(...e);c=[];for(var l of b)2>l.bottom.y-l.top.y||(b=(l.top.startX+l.top.endX+l.bottom.startX+l.bottom.endX)/4,e=(l.top.y+l.bottom.y+1)/2,a.get(Math.round(b),Math.round(e))&&(f=[l.top.endX-l.top.startX,l.bottom.endX-l.bottom.startX,l.bottom.y-l.top.y+ -1],f=O(f)/f.length,g=S({x:Math.round(b),y:Math.round(e)},[1,1,3,1,1],a),c.push({score:g,x:b,y:e,size:f})));if(3>c.length)return null;c.sort((p,t)=>p.score-t.score);l=[];for(b=0;bp.score-t.score);l.push({points:[e,f[0],f[1]],score:e.score+f[0].score+f[1].score})}l.sort((p,t)=>p.score-t.score);let {topRight:q,topLeft:r,bottomLeft:u}=qa(...l[0].points); -l=U(a,d,q,r,u);n=[];l&&n.push({alignmentPattern:{x:l.alignmentPattern.x,y:l.alignmentPattern.y},bottomLeft:{x:u.x,y:u.y},dimension:l.dimension,topLeft:{x:r.x,y:r.y},topRight:{x:q.x,y:q.y}});l=T(a,q);b=T(a,r);c=T(a,u);(a=U(a,d,l,b,c))&&n.push({alignmentPattern:{x:a.alignmentPattern.x,y:a.alignmentPattern.y},bottomLeft:{x:c.x,y:c.y},topLeft:{x:b.x,y:b.y},topRight:{x:l.x,y:l.y},dimension:a.dimension});return 0===n.length?null:n} -function U(a,b,c,d,e){let f,g;try{({dimension:f,moduleSize:g}=ra(d,c,e,a))}catch(l){return null}var h=c.x-d.x+e.x,k=c.y-d.y+e.y;c=(N(d,e)+N(d,c))/2/g;e=1-3/c;let m={x:d.x+e*(h-d.x),y:d.y+e*(k-d.y)};b=b.map(l=>{const n=(l.top.startX+l.top.endX+l.bottom.startX+l.bottom.endX)/4;l=(l.top.y+l.bottom.y+1)/2;if(a.get(Math.floor(n),Math.floor(l))){var q=S({x:Math.floor(n),y:Math.floor(l)},[1,1,1],a)+N({x:n,y:l},m);return{x:n,y:l,score:q}}}).filter(l=>!!l).sort((l,n)=>l.score-n.score);return{alignmentPattern:15<= -c&&b.length?b[0]:m,dimension:f}} -function V(a){var b=sa(a);if(!b)return null;for(let e of b){b=pa(a,e);var c=b.matrix;if(null==c)c=null;else{var d=L(c);if(d)c=d;else{for(d=0;d{a[c]=b[c]})} -function X(a,b,c,d={}){let e=Object.create(null);W(e,ta);W(e,d);d="onlyInvert"===e.inversionAttempts||"invertFirst"===e.inversionAttempts;var f="attemptBoth"===e.inversionAttempts||d;var g=e.greyScaleWeights,h=e.canOverwriteImage,k=b*c;if(a.length!==4*k)throw Error("Malformed data passed to binarizer.");var m=0;if(h){var l=new Uint8ClampedArray(a.buffer,m,k);m+=k}l=new A(b,c,l);if(g.useIntegerApproximation)for(var n=0;n>8)}else for(n=0;nv;v++)for(let w=0;8>w;w++){let aa=l.get(8*r+w,8*q+v);p=Math.min(p,aa);t=Math.max(t,aa)}v=(p+t)/2;v=Math.min(255,1.11*v);24>=t-p&&(v=p/2,0a?2:a>c?c:a;h=n-3;h=2>b?2:b>h?h:b;k=0;for(m=-2;2>=m;m++)for(p=-2;2>=p;p++)k+=u.get(c+m,h+p);c=k/25;for(h=0;8>h;h++)for(k=0;8>k;k++)m=8*a+h,p=8*b+k,t=l.get(m,p),q.set(m,p,t<=c),f&&r.set(m,p,!(t<=c))}f=f?{binarized:q,inverted:r}:{binarized:q};let {binarized:z,inverted:y}=f;(f=V(d? -y:z))||"attemptBoth"!==e.inversionAttempts&&"invertFirst"!==e.inversionAttempts||(f=V(d?z:y));return f}X.default=X;let Y="dontInvert",Z={red:77,green:150,blue:29,useIntegerApproximation:!0}; -self.onmessage=a=>{let b=a.data.id,c=a.data.data;switch(a.data.type){case "decode":(a=X(c.data,c.width,c.height,{inversionAttempts:Y,greyScaleWeights:Z}))?self.postMessage({id:b,type:"qrResult",data:a.data,bytes:a.binaryData,cornerPoints:[a.location.topLeftCorner,a.location.topRightCorner,a.location.bottomRightCorner,a.location.bottomLeftCorner]}):self.postMessage({id:b,type:"qrResult",data:null});break;case "grayscaleWeights":Z.red=c.red;Z.green=c.green;Z.blue=c.blue;Z.useIntegerApproximation=c.useIntegerApproximation; -break;case "inversionMode":switch(c){case "original":Y="dontInvert";break;case "invert":Y="onlyInvert";break;case "both":Y="attemptBoth";break;default:throw Error("Invalid inversion mode");}break;case "close":self.close()}} -`]),{type:"application/javascript"}));var lc=B0((MD,wD)=>{(function(A,Q){typeof MD==="object"&&typeof wD!=="undefined"?wD.exports=Q():typeof define==="function"&&define.amd?define(Q):(A=typeof globalThis!=="undefined"?globalThis:A||self,A.QrScanner=Q())})(MD,function(){class A{constructor(Q,J,K,C,U){this._legacyCanvasSize=A.DEFAULT_CANVAS_SIZE,this._preferredCamera="environment",this._maxScansPerSecond=25,this._lastScanTimestamp=-1,this._destroyed=this._flashOn=this._paused=this._active=!1,this.$video=Q,this.$canvas=document.createElement("canvas"),K&&typeof K==="object"?this._onDecode=J:(K||C||U?console.warn("You're using a deprecated version of the QrScanner constructor which will be removed in the future"):console.warn("Note that the type of the scan result passed to onDecode will change in the future. To already switch to the new api today, you can pass returnDetailedScanResult: true."),this._legacyOnDecode=J),J=typeof K==="object"?K:{},this._onDecodeError=J.onDecodeError||(typeof K==="function"?K:this._onDecodeError),this._calculateScanRegion=J.calculateScanRegion||(typeof C==="function"?C:this._calculateScanRegion),this._preferredCamera=J.preferredCamera||U||this._preferredCamera,this._legacyCanvasSize=typeof K==="number"?K:typeof C==="number"?C:this._legacyCanvasSize,this._maxScansPerSecond=J.maxScansPerSecond||this._maxScansPerSecond,this._onPlay=this._onPlay.bind(this),this._onLoadedMetaData=this._onLoadedMetaData.bind(this),this._onVisibilityChange=this._onVisibilityChange.bind(this),this._updateOverlay=this._updateOverlay.bind(this),Q.disablePictureInPicture=!0,Q.playsInline=!0,Q.muted=!0;let Y=!1;if(Q.hidden&&(Q.hidden=!1,Y=!0),document.body.contains(Q)||(document.body.appendChild(Q),Y=!0),K=Q.parentElement,J.highlightScanRegion||J.highlightCodeOutline){if(C=!!J.overlay,this.$overlay=J.overlay||document.createElement("div"),U=this.$overlay.style,U.position="absolute",U.display="none",U.pointerEvents="none",this.$overlay.classList.add("scan-region-highlight"),!C&&J.highlightScanRegion){this.$overlay.innerHTML='';try{this.$overlay.firstElementChild.animate({transform:["scale(.98)","scale(1.01)"]},{duration:400,iterations:1/0,direction:"alternate",easing:"ease-in-out"})}catch(Z){}K.insertBefore(this.$overlay,this.$video.nextSibling)}J.highlightCodeOutline&&(this.$overlay.insertAdjacentHTML("beforeend",''),this.$codeOutlineHighlight=this.$overlay.lastElementChild)}this._scanRegion=this._calculateScanRegion(Q),requestAnimationFrame(()=>{let Z=window.getComputedStyle(Q);Z.display==="none"&&(Q.style.setProperty("display","block","important"),Y=!0),Z.visibility!=="visible"&&(Q.style.setProperty("visibility","visible","important"),Y=!0),Y&&(console.warn("QrScanner has overwritten the video hiding style to avoid Safari stopping the playback."),Q.style.opacity="0",Q.style.width="0",Q.style.height="0",this.$overlay&&this.$overlay.parentElement&&this.$overlay.parentElement.removeChild(this.$overlay),delete this.$overlay,delete this.$codeOutlineHighlight),this.$overlay&&this._updateOverlay()}),Q.addEventListener("play",this._onPlay),Q.addEventListener("loadedmetadata",this._onLoadedMetaData),document.addEventListener("visibilitychange",this._onVisibilityChange),window.addEventListener("resize",this._updateOverlay),this._qrEnginePromise=A.createQrEngine()}static set WORKER_PATH(Q){console.warn("Setting QrScanner.WORKER_PATH is not required and not supported anymore. Have a look at the README for new setup instructions.")}static async hasCamera(){try{return!!(await A.listCameras(!1)).length}catch(Q){return!1}}static async listCameras(Q=!1){if(!navigator.mediaDevices)return[];let J=async()=>(await navigator.mediaDevices.enumerateDevices()).filter((C)=>C.kind==="videoinput"),K;try{Q&&(await J()).every((C)=>!C.label)&&(K=await navigator.mediaDevices.getUserMedia({audio:!1,video:!0}))}catch(C){}try{return(await J()).map((C,U)=>({id:C.deviceId,label:C.label||(U===0?"Default Camera":`Camera ${U+1}`)}))}finally{K&&(console.warn("Call listCameras after successfully starting a QR scanner to avoid creating a temporary video stream"),A._stopVideoStream(K))}}async hasFlash(){let Q;try{if(this.$video.srcObject){if(!(this.$video.srcObject instanceof MediaStream))return!1;Q=this.$video.srcObject}else Q=(await this._getCameraStream()).stream;return"torch"in Q.getVideoTracks()[0].getSettings()}catch(J){return!1}finally{Q&&Q!==this.$video.srcObject&&(console.warn("Call hasFlash after successfully starting the scanner to avoid creating a temporary video stream"),A._stopVideoStream(Q))}}isFlashOn(){return this._flashOn}async toggleFlash(){this._flashOn?await this.turnFlashOff():await this.turnFlashOn()}async turnFlashOn(){if(!this._flashOn&&!this._destroyed&&(this._flashOn=!0,this._active&&!this._paused))try{if(!await this.hasFlash())throw"No flash available";await this.$video.srcObject.getVideoTracks()[0].applyConstraints({advanced:[{torch:!0}]})}catch(Q){throw this._flashOn=!1,Q}}async turnFlashOff(){this._flashOn&&(this._flashOn=!1,await this._restartVideoStream())}destroy(){this.$video.removeEventListener("loadedmetadata",this._onLoadedMetaData),this.$video.removeEventListener("play",this._onPlay),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("resize",this._updateOverlay),this._destroyed=!0,this._flashOn=!1,this.stop(),A._postWorkerMessage(this._qrEnginePromise,"close")}async start(){if(this._destroyed)throw Error("The QR scanner can not be started as it had been destroyed.");if(!this._active||this._paused){if(window.location.protocol!=="https:"&&console.warn("The camera stream is only accessible if the page is transferred via https."),this._active=!0,!document.hidden)if(this._paused=!1,this.$video.srcObject)await this.$video.play();else try{let{stream:Q,facingMode:J}=await this._getCameraStream();!this._active||this._paused?A._stopVideoStream(Q):(this._setVideoMirror(J),this.$video.srcObject=Q,await this.$video.play(),this._flashOn&&(this._flashOn=!1,this.turnFlashOn().catch(()=>{})))}catch(Q){if(!this._paused)throw this._active=!1,Q}}}stop(){this.pause(),this._active=!1}async pause(Q=!1){if(this._paused=!0,!this._active)return!0;this.$video.pause(),this.$overlay&&(this.$overlay.style.display="none");let J=()=>{this.$video.srcObject instanceof MediaStream&&(A._stopVideoStream(this.$video.srcObject),this.$video.srcObject=null)};if(Q)return J(),!0;if(await new Promise((K)=>setTimeout(K,300)),!this._paused)return!1;return J(),!0}async setCamera(Q){Q!==this._preferredCamera&&(this._preferredCamera=Q,await this._restartVideoStream())}static async scanImage(Q,J,K,C,U=!1,Y=!1){let Z,X=!1;J&&(("scanRegion"in J)||("qrEngine"in J)||("canvas"in J)||("disallowCanvasResizing"in J)||("alsoTryWithoutScanRegion"in J)||("returnDetailedScanResult"in J))?(Z=J.scanRegion,K=J.qrEngine,C=J.canvas,U=J.disallowCanvasResizing||!1,Y=J.alsoTryWithoutScanRegion||!1,X=!0):J||K||C||U||Y?console.warn("You're using a deprecated api for scanImage which will be removed in the future."):console.warn("Note that the return type of scanImage will change in the future. To already switch to the new api today, you can pass returnDetailedScanResult: true."),J=!!K;try{let E,H;[K,E]=await Promise.all([K||A.createQrEngine(),A._loadImage(Q)]),[C,H]=A._drawToCanvas(E,Z,C,U);let $;if(K instanceof Worker){let I=K;J||A._postWorkerMessageSync(I,"inversionMode","both"),$=await new Promise((N,F)=>{let V,D,L,R=-1;D=(T)=>{T.data.id===R&&(I.removeEventListener("message",D),I.removeEventListener("error",L),clearTimeout(V),T.data.data!==null?N({data:T.data.data,cornerPoints:A._convertPoints(T.data.cornerPoints,Z),bytes:T.data.bytes}):F(A.NO_QR_CODE_FOUND))},L=(T)=>{I.removeEventListener("message",D),I.removeEventListener("error",L),clearTimeout(V),F("Scanner error: "+(T?T.message||T:"Unknown Error"))},I.addEventListener("message",D),I.addEventListener("error",L),V=setTimeout(()=>L("timeout"),1e4);let M=H.getImageData(0,0,C.width,C.height);R=A._postWorkerMessageSync(I,"decode",M,[M.data.buffer])})}else $=await Promise.race([new Promise((I,N)=>window.setTimeout(()=>N("Scanner error: timeout"),1e4)),(async()=>{try{var[I]=await K.detect(C);return{noQrCode:!I,data:I.rawValue,cornerPoints:A._convertPoints(I.cornerPoints,Z),bytes:I.rawValue.split("").map((N)=>N.charCodeAt(0))}}catch(N){if(I=N.message||N,/not implemented|service unavailable/.test(I))return A._disableBarcodeDetector=!0,A.scanImage(Q,{scanRegion:Z,canvas:C,disallowCanvasResizing:U,alsoTryWithoutScanRegion:Y});throw`Scanner error: ${I}`}})()]);return X?$:$.data}catch(E){if(!Z||!Y)throw E;let H=await A.scanImage(Q,{qrEngine:K,canvas:C,disallowCanvasResizing:U});return X?H:H.data}finally{J||A._postWorkerMessage(K,"close")}}setGrayscaleWeights(Q,J,K,C=!0){A._postWorkerMessage(this._qrEnginePromise,"grayscaleWeights",{red:Q,green:J,blue:K,useIntegerApproximation:C})}setInversionMode(Q){A._postWorkerMessage(this._qrEnginePromise,"inversionMode",Q)}static async createQrEngine(Q){return Q&&console.warn("Specifying a worker path is not required and not supported anymore."),!A._disableBarcodeDetector&&"BarcodeDetector"in window&&BarcodeDetector.getSupportedFormats&&(await BarcodeDetector.getSupportedFormats()).includes("qr_code")?new BarcodeDetector({formats:["qr_code"]}):Promise.resolve().then(() => dc).then((J)=>J.createWorker())}_onPlay(){this._scanRegion=this._calculateScanRegion(this.$video),this._updateOverlay(),this.$overlay&&(this.$overlay.style.display=""),this._scanFrame()}_onLoadedMetaData(){this._scanRegion=this._calculateScanRegion(this.$video),this._updateOverlay()}_onVisibilityChange(){document.hidden?this.pause():this._active&&this.start()}_calculateScanRegion(Q){let J=Math.round(0.6666666666666666*Math.min(Q.videoWidth,Q.videoHeight));return{x:Math.round((Q.videoWidth-J)/2),y:Math.round((Q.videoHeight-J)/2),width:J,height:J,downScaledWidth:this._legacyCanvasSize,downScaledHeight:this._legacyCanvasSize}}_updateOverlay(){requestAnimationFrame(()=>{if(this.$overlay){var Q=this.$video,J=Q.videoWidth,K=Q.videoHeight,C=Q.offsetWidth,U=Q.offsetHeight,Y=Q.offsetLeft,Z=Q.offsetTop,X=window.getComputedStyle(Q),E=X.objectFit,H=J/K,$=C/U;switch(E){case"none":var I=J,N=K;break;case"fill":I=C,N=U;break;default:(E==="cover"?H>$:H<$)?(N=U,I=N*H):(I=C,N=I/H),E==="scale-down"&&(I=Math.min(I,J),N=Math.min(N,K))}var[F,V]=X.objectPosition.split(" ").map((L,R)=>{let M=parseFloat(L);return L.endsWith("%")?(R?U-N:C-I)*M/100:M});X=this._scanRegion.width||J,$=this._scanRegion.height||K,E=this._scanRegion.x||0;var D=this._scanRegion.y||0;H=this.$overlay.style,H.width=`${X/J*I}px`,H.height=`${$/K*N}px`,H.top=`${Z+V+D/K*N}px`,K=/scaleX\(-1\)/.test(Q.style.transform),H.left=`${Y+(K?C-F-I:F)+(K?J-E-X:E)/J*I}px`,H.transform=Q.style.transform}})}static _convertPoints(Q,J){if(!J)return Q;let K=J.x||0,C=J.y||0,U=J.width&&J.downScaledWidth?J.width/J.downScaledWidth:1;J=J.height&&J.downScaledHeight?J.height/J.downScaledHeight:1;for(let Y of Q)Y.x=Y.x*U+K,Y.y=Y.y*J+C;return Q}_scanFrame(){!this._active||this.$video.paused||this.$video.ended||("requestVideoFrameCallback"in this.$video?this.$video.requestVideoFrameCallback.bind(this.$video):requestAnimationFrame)(async()=>{if(!(1>=this.$video.readyState)){var Q=Date.now()-this._lastScanTimestamp,J=1000/this._maxScansPerSecond;QsetTimeout(C,J-Q)),this._lastScanTimestamp=Date.now();try{var K=await A.scanImage(this.$video,{scanRegion:this._scanRegion,qrEngine:this._qrEnginePromise,canvas:this.$canvas})}catch(C){if(!this._active)return;this._onDecodeError(C)}!A._disableBarcodeDetector||await this._qrEnginePromise instanceof Worker||(this._qrEnginePromise=A.createQrEngine()),K?(this._onDecode?this._onDecode(K):this._legacyOnDecode&&this._legacyOnDecode(K.data),this.$codeOutlineHighlight&&(clearTimeout(this._codeOutlineHighlightRemovalTimeout),this._codeOutlineHighlightRemovalTimeout=void 0,this.$codeOutlineHighlight.setAttribute("viewBox",`${this._scanRegion.x||0} ${this._scanRegion.y||0} ${this._scanRegion.width||this.$video.videoWidth} ${this._scanRegion.height||this.$video.videoHeight}`),this.$codeOutlineHighlight.firstElementChild.setAttribute("points",K.cornerPoints.map(({x:C,y:U})=>`${C},${U}`).join(" ")),this.$codeOutlineHighlight.style.display="")):this.$codeOutlineHighlight&&!this._codeOutlineHighlightRemovalTimeout&&(this._codeOutlineHighlightRemovalTimeout=setTimeout(()=>this.$codeOutlineHighlight.style.display="none",100))}this._scanFrame()})}_onDecodeError(Q){Q!==A.NO_QR_CODE_FOUND&&console.log(Q)}async _getCameraStream(){if(!navigator.mediaDevices)throw"Camera not found.";let Q=/^(environment|user)$/.test(this._preferredCamera)?"facingMode":"deviceId",J=[{width:{min:1024}},{width:{min:768}},{}],K=J.map((C)=>Object.assign({},C,{[Q]:{exact:this._preferredCamera}}));for(let C of[...K,...J])try{let U=await navigator.mediaDevices.getUserMedia({video:C,audio:!1}),Y=this._getFacingMode(U)||(C.facingMode?this._preferredCamera:this._preferredCamera==="environment"?"user":"environment");return{stream:U,facingMode:Y}}catch(U){}throw"Camera not found."}async _restartVideoStream(){let Q=this._paused;await this.pause(!0)&&!Q&&this._active&&await this.start()}static _stopVideoStream(Q){for(let J of Q.getTracks())J.stop(),Q.removeTrack(J)}_setVideoMirror(Q){this.$video.style.transform="scaleX("+(Q==="user"?-1:1)+")"}_getFacingMode(Q){return(Q=Q.getVideoTracks()[0])?/rear|back|environment/i.test(Q.label)?"environment":/front|user|face/i.test(Q.label)?"user":null:null}static _drawToCanvas(Q,J,K,C=!1){K=K||document.createElement("canvas");let U=J&&J.x?J.x:0,Y=J&&J.y?J.y:0,Z=J&&J.width?J.width:Q.videoWidth||Q.width,X=J&&J.height?J.height:Q.videoHeight||Q.height;return C||(C=J&&J.downScaledWidth?J.downScaledWidth:Z,J=J&&J.downScaledHeight?J.downScaledHeight:X,K.width!==C&&(K.width=C),K.height!==J&&(K.height=J)),J=K.getContext("2d",{alpha:!1}),J.imageSmoothingEnabled=!1,J.drawImage(Q,U,Y,Z,X,0,0,K.width,K.height),[K,J]}static async _loadImage(Q){if(Q instanceof Image)return await A._awaitImageLoad(Q),Q;if(Q instanceof HTMLVideoElement||Q instanceof HTMLCanvasElement||Q instanceof SVGImageElement||"OffscreenCanvas"in window&&Q instanceof OffscreenCanvas||"ImageBitmap"in window&&Q instanceof ImageBitmap)return Q;if(Q instanceof File||Q instanceof Blob||Q instanceof URL||typeof Q==="string"){let J=new Image;J.src=Q instanceof File||Q instanceof Blob?URL.createObjectURL(Q):Q.toString();try{return await A._awaitImageLoad(J),J}finally{(Q instanceof File||Q instanceof Blob)&&URL.revokeObjectURL(J.src)}}else throw"Unsupported image type."}static async _awaitImageLoad(Q){Q.complete&&Q.naturalWidth!==0||await new Promise((J,K)=>{let C=(U)=>{Q.removeEventListener("load",C),Q.removeEventListener("error",C),U instanceof ErrorEvent?K("Image load error"):J()};Q.addEventListener("load",C),Q.addEventListener("error",C)})}static async _postWorkerMessage(Q,J,K,C){return A._postWorkerMessageSync(await Q,J,K,C)}static _postWorkerMessageSync(Q,J,K,C){if(!(Q instanceof Worker))return-1;let U=A._workerMessageId++;return Q.postMessage({id:U,type:J,data:K},C),U}}return A.DEFAULT_CANVAS_SIZE=400,A.NO_QR_CODE_FOUND="No QR code found",A._disableBarcodeDetector=!1,A._workerMessageId=0,A})});var jd={};z3(jd,{transcode:()=>Sd,resolveObjectURL:()=>kd,kStringMaxLength:()=>wW,isUtf8:()=>_d,isAscii:()=>Pd,default:()=>jE1,createObjectURL:()=>wd,constants:()=>Td,btoa:()=>Md,atob:()=>Vd,File:()=>Dd,Buffer:()=>SE1,Blob:()=>zd});function kd(A){throw new Error("Not implemented")}function Sd(A,Q,J){throw new Error("Not implemented")}var zE1,yD,DE1,VE1,ME1,wE1,hD=(A,Q)=>()=>(Q||A((Q={exports:{}}).exports,Q),Q.exports),PE1=(A,Q)=>{for(var J in Q)yD(A,J,{get:Q[J],enumerable:!0})},xD=(A,Q,J,K)=>{if(Q&&typeof Q=="object"||typeof Q=="function")for(let C of VE1(Q))!wE1.call(A,C)&&C!==J&&yD(A,C,{get:()=>Q[C],enumerable:!(K=DE1(Q,C))||K.enumerable});return A},_E1=(A,Q,J)=>(xD(A,Q,"default"),J&&xD(J,Q,"default")),gD=(A,Q,J)=>(J=A!=null?zE1(ME1(A)):{},xD(Q||!A||!A.__esModule?yD(J,"default",{value:A,enumerable:!0}):J,A)),TE1,kE1,bD,Ld,Fd,Rd,wW=4294967295,zd,Dd,Vd,Md,wd,Pd=(A)=>ArrayBuffer.isView(A)?A.every((Q)=>Q<128):A.split("").every((Q)=>Q.charCodeAt(0)<128),_d=(A)=>{throw new Error("Not implemented")},Td,SE1,jE1;var vd=hJ(()=>{zE1=Object.create,yD=Object.defineProperty,DE1=Object.getOwnPropertyDescriptor,VE1=Object.getOwnPropertyNames,ME1=Object.getPrototypeOf,wE1=Object.prototype.hasOwnProperty,TE1=hD((A)=>{A.byteLength=X,A.toByteArray=H,A.fromByteArray=N;var Q=[],J=[],K=typeof Uint8Array<"u"?Uint8Array:Array,C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(U=0,Y=C.length;U0)throw new Error("Invalid string. Length must be a multiple of 4");var D=F.indexOf("=");D===-1&&(D=V);var L=D===V?0:4-D%4;return[D,L]}function X(F){var V=Z(F),D=V[0],L=V[1];return(D+L)*3/4-L}function E(F,V,D){return(V+D)*3/4-D}function H(F){var V,D=Z(F),L=D[0],R=D[1],M=new K(E(F,L,R)),T=0,h=R>0?L-4:L,y;for(y=0;y>16&255,M[T++]=V>>8&255,M[T++]=V&255;return R===2&&(V=J[F.charCodeAt(y)]<<2|J[F.charCodeAt(y+1)]>>4,M[T++]=V&255),R===1&&(V=J[F.charCodeAt(y)]<<10|J[F.charCodeAt(y+1)]<<4|J[F.charCodeAt(y+2)]>>2,M[T++]=V>>8&255,M[T++]=V&255),M}function $(F){return Q[F>>18&63]+Q[F>>12&63]+Q[F>>6&63]+Q[F&63]}function I(F,V,D){for(var L,R=[],M=V;Mh?h:T+M));return L===1?(V=F[D-1],R.push(Q[V>>2]+Q[V<<4&63]+"==")):L===2&&(V=(F[D-2]<<8)+F[D-1],R.push(Q[V>>10]+Q[V>>4&63]+Q[V<<2&63]+"=")),R.join("")}}),kE1=hD((A)=>{A.read=function(Q,J,K,C,U){var Y,Z,X=U*8-C-1,E=(1<>1,$=-7,I=K?U-1:0,N=K?-1:1,F=Q[J+I];for(I+=N,Y=F&(1<<-$)-1,F>>=-$,$+=X;$>0;Y=Y*256+Q[J+I],I+=N,$-=8);for(Z=Y&(1<<-$)-1,Y>>=-$,$+=C;$>0;Z=Z*256+Q[J+I],I+=N,$-=8);if(Y===0)Y=1-H;else{if(Y===E)return Z?NaN:(F?-1:1)*(1/0);Z=Z+Math.pow(2,C),Y=Y-H}return(F?-1:1)*Z*Math.pow(2,Y-C)},A.write=function(Q,J,K,C,U,Y){var Z,X,E,H=Y*8-U-1,$=(1<>1,N=U===23?Math.pow(2,-24)-Math.pow(2,-77):0,F=C?0:Y-1,V=C?1:-1,D=J<0||J===0&&1/J<0?1:0;for(J=Math.abs(J),isNaN(J)||J===1/0?(X=isNaN(J)?1:0,Z=$):(Z=Math.floor(Math.log(J)/Math.LN2),J*(E=Math.pow(2,-Z))<1&&(Z--,E*=2),Z+I>=1?J+=N/E:J+=N*Math.pow(2,1-I),J*E>=2&&(Z++,E/=2),Z+I>=$?(X=0,Z=$):Z+I>=1?(X=(J*E-1)*Math.pow(2,U),Z=Z+I):(X=J*Math.pow(2,I-1)*Math.pow(2,U),Z=0));U>=8;Q[K+F]=X&255,F+=V,X/=256,U-=8);for(Z=Z<0;Q[K+F]=Z&255,F+=V,Z/=256,H-=8);Q[K+F-V]|=D*128}}),bD=hD((A)=>{var Q=TE1(),J=kE1(),K=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;A.Buffer=Z,A.SlowBuffer=R,A.INSPECT_MAX_BYTES=50;var C=2147483647;A.kMaxLength=C,Z.TYPED_ARRAY_SUPPORT=U(),!Z.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function U(){try{let G=new Uint8Array(1),z={foo:function(){return 42}};return Object.setPrototypeOf(z,Uint8Array.prototype),Object.setPrototypeOf(G,z),G.foo()===42}catch{return!1}}Object.defineProperty(Z.prototype,"parent",{enumerable:!0,get:function(){if(Z.isBuffer(this))return this.buffer}}),Object.defineProperty(Z.prototype,"offset",{enumerable:!0,get:function(){if(Z.isBuffer(this))return this.byteOffset}});function Y(G){if(G>C)throw new RangeError('The value "'+G+'" is invalid for option "size"');let z=new Uint8Array(G);return Object.setPrototypeOf(z,Z.prototype),z}function Z(G,z,x){if(typeof G=="number"){if(typeof z=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return $(G)}return X(G,z,x)}Z.poolSize=8192;function X(G,z,x){if(typeof G=="string")return I(G,z);if(ArrayBuffer.isView(G))return F(G);if(G==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof G);if(B1(G,ArrayBuffer)||G&&B1(G.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(B1(G,SharedArrayBuffer)||G&&B1(G.buffer,SharedArrayBuffer)))return V(G,z,x);if(typeof G=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let m=G.valueOf&&G.valueOf();if(m!=null&&m!==G)return Z.from(m,z,x);let l=D(G);if(l)return l;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof G[Symbol.toPrimitive]=="function")return Z.from(G[Symbol.toPrimitive]("string"),z,x);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof G)}Z.from=function(G,z,x){return X(G,z,x)},Object.setPrototypeOf(Z.prototype,Uint8Array.prototype),Object.setPrototypeOf(Z,Uint8Array);function E(G){if(typeof G!="number")throw new TypeError('"size" argument must be of type number');if(G<0)throw new RangeError('The value "'+G+'" is invalid for option "size"')}function H(G,z,x){return E(G),G<=0?Y(G):z!==void 0?typeof x=="string"?Y(G).fill(z,x):Y(G).fill(z):Y(G)}Z.alloc=function(G,z,x){return H(G,z,x)};function $(G){return E(G),Y(G<0?0:L(G)|0)}Z.allocUnsafe=function(G){return $(G)},Z.allocUnsafeSlow=function(G){return $(G)};function I(G,z){if((typeof z!="string"||z==="")&&(z="utf8"),!Z.isEncoding(z))throw new TypeError("Unknown encoding: "+z);let x=M(G,z)|0,m=Y(x),l=m.write(G,z);return l!==x&&(m=m.slice(0,l)),m}function N(G){let z=G.length<0?0:L(G.length)|0,x=Y(z);for(let m=0;m=C)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+C.toString(16)+" bytes");return G|0}function R(G){return+G!=G&&(G=0),Z.alloc(+G)}Z.isBuffer=function(G){return G!=null&&G._isBuffer===!0&&G!==Z.prototype},Z.compare=function(G,z){if(B1(G,Uint8Array)&&(G=Z.from(G,G.offset,G.byteLength)),B1(z,Uint8Array)&&(z=Z.from(z,z.offset,z.byteLength)),!Z.isBuffer(G)||!Z.isBuffer(z))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(G===z)return 0;let x=G.length,m=z.length;for(let l=0,a=Math.min(x,m);lm.length?(Z.isBuffer(a)||(a=Z.from(a)),a.copy(m,l)):Uint8Array.prototype.set.call(m,a,l);else if(Z.isBuffer(a))a.copy(m,l);else throw new TypeError('"list" argument must be an Array of Buffers');l+=a.length}return m};function M(G,z){if(Z.isBuffer(G))return G.length;if(ArrayBuffer.isView(G)||B1(G,ArrayBuffer))return G.byteLength;if(typeof G!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof G);let x=G.length,m=arguments.length>2&&arguments[2]===!0;if(!m&&x===0)return 0;let l=!1;for(;;)switch(z){case"ascii":case"latin1":case"binary":return x;case"utf8":case"utf-8":return C1(G).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x*2;case"hex":return x>>>1;case"base64":return j1(G).length;default:if(l)return m?-1:C1(G).length;z=(""+z).toLowerCase(),l=!0}}Z.byteLength=M;function T(G,z,x){let m=!1;if((z===void 0||z<0)&&(z=0),z>this.length||((x===void 0||x>this.length)&&(x=this.length),x<=0)||(x>>>=0,z>>>=0,x<=z))return"";for(G||(G="utf8");;)switch(G){case"hex":return _(this,z,x);case"utf8":case"utf-8":return P(this,z,x);case"ascii":return k(this,z,x);case"latin1":case"binary":return S(this,z,x);case"base64":return q(this,z,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,z,x);default:if(m)throw new TypeError("Unknown encoding: "+G);G=(G+"").toLowerCase(),m=!0}}Z.prototype._isBuffer=!0;function h(G,z,x){let m=G[z];G[z]=G[x],G[x]=m}Z.prototype.swap16=function(){let G=this.length;if(G%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let z=0;zz&&(G+=" ... "),""},K&&(Z.prototype[K]=Z.prototype.inspect),Z.prototype.compare=function(G,z,x,m,l){if(B1(G,Uint8Array)&&(G=Z.from(G,G.offset,G.byteLength)),!Z.isBuffer(G))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof G);if(z===void 0&&(z=0),x===void 0&&(x=G?G.length:0),m===void 0&&(m=0),l===void 0&&(l=this.length),z<0||x>G.length||m<0||l>this.length)throw new RangeError("out of range index");if(m>=l&&z>=x)return 0;if(m>=l)return-1;if(z>=x)return 1;if(z>>>=0,x>>>=0,m>>>=0,l>>>=0,this===G)return 0;let a=l-m,K1=x-z,F1=Math.min(a,K1),R1=this.slice(m,l),X1=G.slice(z,x);for(let W1=0;W12147483647?x=2147483647:x<-2147483648&&(x=-2147483648),x=+x,k1(x)&&(x=l?0:G.length-1),x<0&&(x=G.length+x),x>=G.length){if(l)return-1;x=G.length-1}else if(x<0)if(l)x=0;else return-1;if(typeof z=="string"&&(z=Z.from(z,m)),Z.isBuffer(z))return z.length===0?-1:g(G,z,x,m,l);if(typeof z=="number")return z=z&255,typeof Uint8Array.prototype.indexOf=="function"?l?Uint8Array.prototype.indexOf.call(G,z,x):Uint8Array.prototype.lastIndexOf.call(G,z,x):g(G,[z],x,m,l);throw new TypeError("val must be string, number or Buffer")}function g(G,z,x,m,l){let a=1,K1=G.length,F1=z.length;if(m!==void 0&&(m=String(m).toLowerCase(),m==="ucs2"||m==="ucs-2"||m==="utf16le"||m==="utf-16le")){if(G.length<2||z.length<2)return-1;a=2,K1/=2,F1/=2,x/=2}function R1(W1,$1){return a===1?W1[$1]:W1.readUInt16BE($1*a)}let X1;if(l){let W1=-1;for(X1=x;X1K1&&(x=K1-F1),X1=x;X1>=0;X1--){let W1=!0;for(let $1=0;$1l&&(m=l)):m=l;let a=z.length;m>a/2&&(m=a/2);let K1;for(K1=0;K1>>0,isFinite(x)?(x=x>>>0,m===void 0&&(m="utf8")):(m=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let l=this.length-z;if((x===void 0||x>l)&&(x=l),G.length>0&&(x<0||z<0)||z>this.length)throw new RangeError("Attempt to write outside buffer bounds");m||(m="utf8");let a=!1;for(;;)switch(m){case"hex":return f(this,G,z,x);case"utf8":case"utf-8":return u(this,G,z,x);case"ascii":case"latin1":case"binary":return d(this,G,z,x);case"base64":return n(this,G,z,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,G,z,x);default:if(a)throw new TypeError("Unknown encoding: "+m);m=(""+m).toLowerCase(),a=!0}},Z.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function q(G,z,x){return z===0&&x===G.length?Q.fromByteArray(G):Q.fromByteArray(G.slice(z,x))}function P(G,z,x){x=Math.min(G.length,x);let m=[],l=z;for(;l239?4:a>223?3:a>191?2:1;if(l+F1<=x){let R1,X1,W1,$1;switch(F1){case 1:a<128&&(K1=a);break;case 2:R1=G[l+1],(R1&192)===128&&($1=(a&31)<<6|R1&63,$1>127&&(K1=$1));break;case 3:R1=G[l+1],X1=G[l+2],(R1&192)===128&&(X1&192)===128&&($1=(a&15)<<12|(R1&63)<<6|X1&63,$1>2047&&($1<55296||$1>57343)&&(K1=$1));break;case 4:R1=G[l+1],X1=G[l+2],W1=G[l+3],(R1&192)===128&&(X1&192)===128&&(W1&192)===128&&($1=(a&15)<<18|(R1&63)<<12|(X1&63)<<6|W1&63,$1>65535&&$1<1114112&&(K1=$1))}}K1===null?(K1=65533,F1=1):K1>65535&&(K1-=65536,m.push(K1>>>10&1023|55296),K1=56320|K1&1023),m.push(K1),l+=F1}return w(m)}var O=4096;function w(G){let z=G.length;if(z<=O)return String.fromCharCode.apply(String,G);let x="",m=0;for(;mm)&&(x=m);let l="";for(let a=z;ax&&(G=x),z<0?(z+=x,z<0&&(z=0)):z>x&&(z=x),zx)throw new RangeError("Trying to access beyond buffer length")}Z.prototype.readUintLE=Z.prototype.readUIntLE=function(G,z,x){G=G>>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G],l=1,a=0;for(;++a>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G+--z],l=1;for(;z>0&&(l*=256);)m+=this[G+--z]*l;return m},Z.prototype.readUint8=Z.prototype.readUInt8=function(G,z){return G=G>>>0,z||j(G,1,this.length),this[G]},Z.prototype.readUint16LE=Z.prototype.readUInt16LE=function(G,z){return G=G>>>0,z||j(G,2,this.length),this[G]|this[G+1]<<8},Z.prototype.readUint16BE=Z.prototype.readUInt16BE=function(G,z){return G=G>>>0,z||j(G,2,this.length),this[G]<<8|this[G+1]},Z.prototype.readUint32LE=Z.prototype.readUInt32LE=function(G,z){return G=G>>>0,z||j(G,4,this.length),(this[G]|this[G+1]<<8|this[G+2]<<16)+this[G+3]*16777216},Z.prototype.readUint32BE=Z.prototype.readUInt32BE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]*16777216+(this[G+1]<<16|this[G+2]<<8|this[G+3])},Z.prototype.readBigUInt64LE=G1(function(G){G=G>>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=z+this[++G]*256+this[++G]*65536+this[++G]*16777216,l=this[++G]+this[++G]*256+this[++G]*65536+x*16777216;return BigInt(m)+(BigInt(l)<>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=z*16777216+this[++G]*65536+this[++G]*256+this[++G],l=this[++G]*16777216+this[++G]*65536+this[++G]*256+x;return(BigInt(m)<>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G],l=1,a=0;for(;++a=l&&(m-=Math.pow(2,8*z)),m},Z.prototype.readIntBE=function(G,z,x){G=G>>>0,z=z>>>0,x||j(G,z,this.length);let m=z,l=1,a=this[G+--m];for(;m>0&&(l*=256);)a+=this[G+--m]*l;return l*=128,a>=l&&(a-=Math.pow(2,8*z)),a},Z.prototype.readInt8=function(G,z){return G=G>>>0,z||j(G,1,this.length),this[G]&128?(255-this[G]+1)*-1:this[G]},Z.prototype.readInt16LE=function(G,z){G=G>>>0,z||j(G,2,this.length);let x=this[G]|this[G+1]<<8;return x&32768?x|4294901760:x},Z.prototype.readInt16BE=function(G,z){G=G>>>0,z||j(G,2,this.length);let x=this[G+1]|this[G]<<8;return x&32768?x|4294901760:x},Z.prototype.readInt32LE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]|this[G+1]<<8|this[G+2]<<16|this[G+3]<<24},Z.prototype.readInt32BE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]<<24|this[G+1]<<16|this[G+2]<<8|this[G+3]},Z.prototype.readBigInt64LE=G1(function(G){G=G>>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=this[G+4]+this[G+5]*256+this[G+6]*65536+(x<<24);return(BigInt(m)<>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=(z<<24)+this[++G]*65536+this[++G]*256+this[++G];return(BigInt(m)<>>0,z||j(G,4,this.length),J.read(this,G,!0,23,4)},Z.prototype.readFloatBE=function(G,z){return G=G>>>0,z||j(G,4,this.length),J.read(this,G,!1,23,4)},Z.prototype.readDoubleLE=function(G,z){return G=G>>>0,z||j(G,8,this.length),J.read(this,G,!0,52,8)},Z.prototype.readDoubleBE=function(G,z){return G=G>>>0,z||j(G,8,this.length),J.read(this,G,!1,52,8)};function b(G,z,x,m,l,a){if(!Z.isBuffer(G))throw new TypeError('"buffer" argument must be a Buffer instance');if(z>l||zG.length)throw new RangeError("Index out of range")}Z.prototype.writeUintLE=Z.prototype.writeUIntLE=function(G,z,x,m){if(G=+G,z=z>>>0,x=x>>>0,!m){let K1=Math.pow(2,8*x)-1;b(this,G,z,x,K1,0)}let l=1,a=0;for(this[z]=G&255;++a>>0,x=x>>>0,!m){let K1=Math.pow(2,8*x)-1;b(this,G,z,x,K1,0)}let l=x-1,a=1;for(this[z+l]=G&255;--l>=0&&(a*=256);)this[z+l]=G/a&255;return z+x},Z.prototype.writeUint8=Z.prototype.writeUInt8=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,1,255,0),this[z]=G&255,z+1},Z.prototype.writeUint16LE=Z.prototype.writeUInt16LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,65535,0),this[z]=G&255,this[z+1]=G>>>8,z+2},Z.prototype.writeUint16BE=Z.prototype.writeUInt16BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,65535,0),this[z]=G>>>8,this[z+1]=G&255,z+2},Z.prototype.writeUint32LE=Z.prototype.writeUInt32LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,4294967295,0),this[z+3]=G>>>24,this[z+2]=G>>>16,this[z+1]=G>>>8,this[z]=G&255,z+4},Z.prototype.writeUint32BE=Z.prototype.writeUInt32BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,4294967295,0),this[z]=G>>>24,this[z+1]=G>>>16,this[z+2]=G>>>8,this[z+3]=G&255,z+4};function p(G,z,x,m,l){E1(z,m,l,G,x,7);let a=Number(z&BigInt(4294967295));G[x++]=a,a=a>>8,G[x++]=a,a=a>>8,G[x++]=a,a=a>>8,G[x++]=a;let K1=Number(z>>BigInt(32)&BigInt(4294967295));return G[x++]=K1,K1=K1>>8,G[x++]=K1,K1=K1>>8,G[x++]=K1,K1=K1>>8,G[x++]=K1,x}function s(G,z,x,m,l){E1(z,m,l,G,x,7);let a=Number(z&BigInt(4294967295));G[x+7]=a,a=a>>8,G[x+6]=a,a=a>>8,G[x+5]=a,a=a>>8,G[x+4]=a;let K1=Number(z>>BigInt(32)&BigInt(4294967295));return G[x+3]=K1,K1=K1>>8,G[x+2]=K1,K1=K1>>8,G[x+1]=K1,K1=K1>>8,G[x]=K1,x+8}Z.prototype.writeBigUInt64LE=G1(function(G,z=0){return p(this,G,z,BigInt(0),BigInt("0xffffffffffffffff"))}),Z.prototype.writeBigUInt64BE=G1(function(G,z=0){return s(this,G,z,BigInt(0),BigInt("0xffffffffffffffff"))}),Z.prototype.writeIntLE=function(G,z,x,m){if(G=+G,z=z>>>0,!m){let F1=Math.pow(2,8*x-1);b(this,G,z,x,F1-1,-F1)}let l=0,a=1,K1=0;for(this[z]=G&255;++l>0)-K1&255;return z+x},Z.prototype.writeIntBE=function(G,z,x,m){if(G=+G,z=z>>>0,!m){let F1=Math.pow(2,8*x-1);b(this,G,z,x,F1-1,-F1)}let l=x-1,a=1,K1=0;for(this[z+l]=G&255;--l>=0&&(a*=256);)G<0&&K1===0&&this[z+l+1]!==0&&(K1=1),this[z+l]=(G/a>>0)-K1&255;return z+x},Z.prototype.writeInt8=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,1,127,-128),G<0&&(G=255+G+1),this[z]=G&255,z+1},Z.prototype.writeInt16LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,32767,-32768),this[z]=G&255,this[z+1]=G>>>8,z+2},Z.prototype.writeInt16BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,32767,-32768),this[z]=G>>>8,this[z+1]=G&255,z+2},Z.prototype.writeInt32LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,2147483647,-2147483648),this[z]=G&255,this[z+1]=G>>>8,this[z+2]=G>>>16,this[z+3]=G>>>24,z+4},Z.prototype.writeInt32BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,2147483647,-2147483648),G<0&&(G=4294967295+G+1),this[z]=G>>>24,this[z+1]=G>>>16,this[z+2]=G>>>8,this[z+3]=G&255,z+4},Z.prototype.writeBigInt64LE=G1(function(G,z=0){return p(this,G,z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),Z.prototype.writeBigInt64BE=G1(function(G,z=0){return s(this,G,z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function r(G,z,x,m,l,a){if(x+m>G.length)throw new RangeError("Index out of range");if(x<0)throw new RangeError("Index out of range")}function A1(G,z,x,m,l){return z=+z,x=x>>>0,l||r(G,z,x,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000),J.write(G,z,x,m,23,4),x+4}Z.prototype.writeFloatLE=function(G,z,x){return A1(this,G,z,!0,x)},Z.prototype.writeFloatBE=function(G,z,x){return A1(this,G,z,!1,x)};function Q1(G,z,x,m,l){return z=+z,x=x>>>0,l||r(G,z,x,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000),J.write(G,z,x,m,52,8),x+8}Z.prototype.writeDoubleLE=function(G,z,x){return Q1(this,G,z,!0,x)},Z.prototype.writeDoubleBE=function(G,z,x){return Q1(this,G,z,!1,x)},Z.prototype.copy=function(G,z,x,m){if(!Z.isBuffer(G))throw new TypeError("argument should be a Buffer");if(x||(x=0),!m&&m!==0&&(m=this.length),z>=G.length&&(z=G.length),z||(z=0),m>0&&m=this.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("sourceEnd out of bounds");m>this.length&&(m=this.length),G.length-z>>0,x=x===void 0?this.length:x>>>0,G||(G=0);let l;if(typeof G=="number")for(l=z;l4294967296?l=U1(String(x)):typeof x=="bigint"&&(l=String(x),(x>BigInt(2)**BigInt(32)||x<-(BigInt(2)**BigInt(32)))&&(l=U1(l)),l+="n"),m+=` It must be ${z}. Received ${l}`,m},RangeError);function U1(G){let z="",x=G.length,m=G[0]==="-"?1:0;for(;x>=m+4;x-=3)z=`_${G.slice(x-3,x)}${z}`;return`${G.slice(0,x)}${z}`}function O1(G,z,x){Y1(z,"offset"),(G[z]===void 0||G[z+x]===void 0)&&i(z,G.length-(x+1))}function E1(G,z,x,m,l,a){if(G>x||G3?z===0||z===BigInt(0)?F1=`>= 0${K1} and < 2${K1} ** ${(a+1)*8}${K1}`:F1=`>= -(2${K1} ** ${(a+1)*8-1}${K1}) and < 2 ** ${(a+1)*8-1}${K1}`:F1=`>= ${z}${K1} and <= ${x}${K1}`,new e.ERR_OUT_OF_RANGE("value",F1,G)}O1(m,l,a)}function Y1(G,z){if(typeof G!="number")throw new e.ERR_INVALID_ARG_TYPE(z,"number",G)}function i(G,z,x){throw Math.floor(G)!==G?(Y1(G,x),new e.ERR_OUT_OF_RANGE(x||"offset","an integer",G)):z<0?new e.ERR_BUFFER_OUT_OF_BOUNDS:new e.ERR_OUT_OF_RANGE(x||"offset",`>= ${x?1:0} and <= ${z}`,G)}var c=/[^+/0-9A-Za-z-_]/g;function o(G){if(G=G.split("=")[0],G=G.trim().replace(c,""),G.length<2)return"";for(;G.length%4!==0;)G=G+"=";return G}function C1(G,z){z=z||1/0;let x,m=G.length,l=null,a=[];for(let K1=0;K155295&&x<57344){if(!l){if(x>56319){(z-=3)>-1&&a.push(239,191,189);continue}else if(K1+1===m){(z-=3)>-1&&a.push(239,191,189);continue}l=x;continue}if(x<56320){(z-=3)>-1&&a.push(239,191,189),l=x;continue}x=(l-55296<<10|x-56320)+65536}else l&&(z-=3)>-1&&a.push(239,191,189);if(l=null,x<128){if((z-=1)<0)break;a.push(x)}else if(x<2048){if((z-=2)<0)break;a.push(x>>6|192,x&63|128)}else if(x<65536){if((z-=3)<0)break;a.push(x>>12|224,x>>6&63|128,x&63|128)}else if(x<1114112){if((z-=4)<0)break;a.push(x>>18|240,x>>12&63|128,x>>6&63|128,x&63|128)}else throw new Error("Invalid code point")}return a}function q1(G){let z=[];for(let x=0;x>8,l=x%256,a.push(l),a.push(m);return a}function j1(G){return Q.toByteArray(o(G))}function H1(G,z,x,m){let l;for(l=0;l=z.length||l>=G.length);++l)z[l+x]=G[l];return l}function B1(G,z){return G instanceof z||G!=null&&G.constructor!=null&&G.constructor.name!=null&&G.constructor.name===z.name}function k1(G){return G!==G}var D1=function(){let G="0123456789abcdef",z=new Array(256);for(let x=0;x<16;++x){let m=x*16;for(let l=0;l<16;++l)z[m+l]=G[x]+G[l]}return z}();function G1(G){return typeof BigInt>"u"?w1:G}function w1(){throw new Error("BigInt not supported")}}),Ld={};PE1(Ld,{Blob:()=>zd,Buffer:()=>Rd.Buffer,File:()=>Dd,atob:()=>Vd,btoa:()=>Md,constants:()=>Td,createObjectURL:()=>wd,default:()=>Fd.Buffer,isAscii:()=>Pd,isUtf8:()=>_d,kStringMaxLength:()=>wW,resolveObjectURL:()=>kd,transcode:()=>Sd});_E1(Ld,gD(bD()));Fd=gD(bD()),Rd=gD(bD()),{Blob:zd,File:Dd,atob:Vd,btoa:Md}=globalThis,{createObjectURL:wd}=URL,Td={__proto__:null,MAX_LENGTH:wW,MAX_STRING_LENGTH:wW,BYTES_PER_ELEMENT:1};SE1=Rd.Buffer,jE1=Fd.Buffer;/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *//*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */});var F7=B0((ks1,xd)=>{var PW=(vd(),y4(jd)),ZY=PW.Buffer,s9={},o9;for(o9 in PW){if(!PW.hasOwnProperty(o9))continue;if(o9==="SlowBuffer"||o9==="Buffer")continue;s9[o9]=PW[o9]}var BY=s9.Buffer={};for(o9 in ZY){if(!ZY.hasOwnProperty(o9))continue;if(o9==="allocUnsafe"||o9==="allocUnsafeSlow")continue;BY[o9]=ZY[o9]}s9.Buffer.prototype=ZY.prototype;if(!BY.from||BY.from===Uint8Array.from)BY.from=function(A,Q,J){if(typeof A==="number")throw new TypeError('The "value" argument must not be of type number. Received type '+typeof A);if(A&&typeof A.length==="undefined")throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof A);return ZY(A,Q,J)};if(!BY.alloc)BY.alloc=function(A,Q,J){if(typeof A!=="number")throw new TypeError('The "size" argument must be of type number. Received type '+typeof A);if(A<0||A>=2147483648)throw new RangeError('The value "'+A+'" is invalid for option "size"');var K=ZY(A);if(!Q||Q.length===0)K.fill(0);else if(typeof J==="string")K.fill(Q,J);else K.fill(Q);return K};if(!s9.kStringMaxLength)try{s9.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(A){}if(!s9.constants){if(s9.constants={MAX_LENGTH:s9.kMaxLength},s9.kStringMaxLength)s9.constants.MAX_STRING_LENGTH=s9.kStringMaxLength}xd.exports=s9});var hd=B0((vE1)=>{var yd="\uFEFF";vE1.PrependBOM=fD;function fD(A,Q){this.encoder=A,this.addBOM=!0}fD.prototype.write=function(A){if(this.addBOM)A=yd+A,this.addBOM=!1;return this.encoder.write(A)};fD.prototype.end=function(){return this.encoder.end()};vE1.StripBOM=pD;function pD(A,Q){this.decoder=A,this.pass=!1,this.options=Q||{}}pD.prototype.write=function(A){var Q=this.decoder.write(A);if(this.pass||!Q)return Q;if(Q[0]===yd){if(Q=Q.slice(1),typeof this.options.stripBOM==="function")this.options.stripBOM()}return this.pass=!0,Q};pD.prototype.end=function(){return this.decoder.end()}});var fd={};z3(fd,{default:()=>iE1,StringDecoder:()=>oE1});var hE1,gd,gE1,bE1,fE1,pE1,fB=(A,Q)=>()=>(Q||A((Q={exports:{}}).exports,Q),Q.exports),uE1=(A,Q,J,K)=>{if(Q&&typeof Q=="object"||typeof Q=="function")for(let C of bE1(Q))!pE1.call(A,C)&&C!==J&&gd(A,C,{get:()=>Q[C],enumerable:!(K=gE1(Q,C))||K.enumerable});return A},mE1=(A,Q,J)=>(J=A!=null?hE1(fE1(A)):{},uE1(Q||!A||!A.__esModule?gd(J,"default",{value:A,enumerable:!0}):J,A)),cE1,dE1,lE1,nE1,sE1,bd,oE1,iE1;var pd=hJ(()=>{hE1=Object.create,gd=Object.defineProperty,gE1=Object.getOwnPropertyDescriptor,bE1=Object.getOwnPropertyNames,fE1=Object.getPrototypeOf,pE1=Object.prototype.hasOwnProperty,cE1=fB((A)=>{A.byteLength=X,A.toByteArray=H,A.fromByteArray=N;var Q=[],J=[],K=typeof Uint8Array<"u"?Uint8Array:Array,C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(U=0,Y=C.length;U0)throw new Error("Invalid string. Length must be a multiple of 4");var D=F.indexOf("=");D===-1&&(D=V);var L=D===V?0:4-D%4;return[D,L]}function X(F){var V=Z(F),D=V[0],L=V[1];return(D+L)*3/4-L}function E(F,V,D){return(V+D)*3/4-D}function H(F){var V,D=Z(F),L=D[0],R=D[1],M=new K(E(F,L,R)),T=0,h=R>0?L-4:L,y;for(y=0;y>16&255,M[T++]=V>>8&255,M[T++]=V&255;return R===2&&(V=J[F.charCodeAt(y)]<<2|J[F.charCodeAt(y+1)]>>4,M[T++]=V&255),R===1&&(V=J[F.charCodeAt(y)]<<10|J[F.charCodeAt(y+1)]<<4|J[F.charCodeAt(y+2)]>>2,M[T++]=V>>8&255,M[T++]=V&255),M}function $(F){return Q[F>>18&63]+Q[F>>12&63]+Q[F>>6&63]+Q[F&63]}function I(F,V,D){for(var L,R=[],M=V;Mh?h:T+M));return L===1?(V=F[D-1],R.push(Q[V>>2]+Q[V<<4&63]+"==")):L===2&&(V=(F[D-2]<<8)+F[D-1],R.push(Q[V>>10]+Q[V>>4&63]+Q[V<<2&63]+"=")),R.join("")}}),dE1=fB((A)=>{A.read=function(Q,J,K,C,U){var Y,Z,X=U*8-C-1,E=(1<>1,$=-7,I=K?U-1:0,N=K?-1:1,F=Q[J+I];for(I+=N,Y=F&(1<<-$)-1,F>>=-$,$+=X;$>0;Y=Y*256+Q[J+I],I+=N,$-=8);for(Z=Y&(1<<-$)-1,Y>>=-$,$+=C;$>0;Z=Z*256+Q[J+I],I+=N,$-=8);if(Y===0)Y=1-H;else{if(Y===E)return Z?NaN:(F?-1:1)*(1/0);Z=Z+Math.pow(2,C),Y=Y-H}return(F?-1:1)*Z*Math.pow(2,Y-C)},A.write=function(Q,J,K,C,U,Y){var Z,X,E,H=Y*8-U-1,$=(1<>1,N=U===23?Math.pow(2,-24)-Math.pow(2,-77):0,F=C?0:Y-1,V=C?1:-1,D=J<0||J===0&&1/J<0?1:0;for(J=Math.abs(J),isNaN(J)||J===1/0?(X=isNaN(J)?1:0,Z=$):(Z=Math.floor(Math.log(J)/Math.LN2),J*(E=Math.pow(2,-Z))<1&&(Z--,E*=2),Z+I>=1?J+=N/E:J+=N*Math.pow(2,1-I),J*E>=2&&(Z++,E/=2),Z+I>=$?(X=0,Z=$):Z+I>=1?(X=(J*E-1)*Math.pow(2,U),Z=Z+I):(X=J*Math.pow(2,I-1)*Math.pow(2,U),Z=0));U>=8;Q[K+F]=X&255,F+=V,X/=256,U-=8);for(Z=Z<0;Q[K+F]=Z&255,F+=V,Z/=256,H-=8);Q[K+F-V]|=D*128}}),lE1=fB((A)=>{var Q=cE1(),J=dE1(),K=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;A.Buffer=Z,A.SlowBuffer=R,A.INSPECT_MAX_BYTES=50;var C=2147483647;A.kMaxLength=C,Z.TYPED_ARRAY_SUPPORT=U(),!Z.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function U(){try{let G=new Uint8Array(1),z={foo:function(){return 42}};return Object.setPrototypeOf(z,Uint8Array.prototype),Object.setPrototypeOf(G,z),G.foo()===42}catch{return!1}}Object.defineProperty(Z.prototype,"parent",{enumerable:!0,get:function(){if(Z.isBuffer(this))return this.buffer}}),Object.defineProperty(Z.prototype,"offset",{enumerable:!0,get:function(){if(Z.isBuffer(this))return this.byteOffset}});function Y(G){if(G>C)throw new RangeError('The value "'+G+'" is invalid for option "size"');let z=new Uint8Array(G);return Object.setPrototypeOf(z,Z.prototype),z}function Z(G,z,x){if(typeof G=="number"){if(typeof z=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return $(G)}return X(G,z,x)}Z.poolSize=8192;function X(G,z,x){if(typeof G=="string")return I(G,z);if(ArrayBuffer.isView(G))return F(G);if(G==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof G);if(B1(G,ArrayBuffer)||G&&B1(G.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(B1(G,SharedArrayBuffer)||G&&B1(G.buffer,SharedArrayBuffer)))return V(G,z,x);if(typeof G=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let m=G.valueOf&&G.valueOf();if(m!=null&&m!==G)return Z.from(m,z,x);let l=D(G);if(l)return l;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof G[Symbol.toPrimitive]=="function")return Z.from(G[Symbol.toPrimitive]("string"),z,x);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof G)}Z.from=function(G,z,x){return X(G,z,x)},Object.setPrototypeOf(Z.prototype,Uint8Array.prototype),Object.setPrototypeOf(Z,Uint8Array);function E(G){if(typeof G!="number")throw new TypeError('"size" argument must be of type number');if(G<0)throw new RangeError('The value "'+G+'" is invalid for option "size"')}function H(G,z,x){return E(G),G<=0?Y(G):z!==void 0?typeof x=="string"?Y(G).fill(z,x):Y(G).fill(z):Y(G)}Z.alloc=function(G,z,x){return H(G,z,x)};function $(G){return E(G),Y(G<0?0:L(G)|0)}Z.allocUnsafe=function(G){return $(G)},Z.allocUnsafeSlow=function(G){return $(G)};function I(G,z){if((typeof z!="string"||z==="")&&(z="utf8"),!Z.isEncoding(z))throw new TypeError("Unknown encoding: "+z);let x=M(G,z)|0,m=Y(x),l=m.write(G,z);return l!==x&&(m=m.slice(0,l)),m}function N(G){let z=G.length<0?0:L(G.length)|0,x=Y(z);for(let m=0;m=C)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+C.toString(16)+" bytes");return G|0}function R(G){return+G!=G&&(G=0),Z.alloc(+G)}Z.isBuffer=function(G){return G!=null&&G._isBuffer===!0&&G!==Z.prototype},Z.compare=function(G,z){if(B1(G,Uint8Array)&&(G=Z.from(G,G.offset,G.byteLength)),B1(z,Uint8Array)&&(z=Z.from(z,z.offset,z.byteLength)),!Z.isBuffer(G)||!Z.isBuffer(z))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(G===z)return 0;let x=G.length,m=z.length;for(let l=0,a=Math.min(x,m);lm.length?(Z.isBuffer(a)||(a=Z.from(a)),a.copy(m,l)):Uint8Array.prototype.set.call(m,a,l);else if(Z.isBuffer(a))a.copy(m,l);else throw new TypeError('"list" argument must be an Array of Buffers');l+=a.length}return m};function M(G,z){if(Z.isBuffer(G))return G.length;if(ArrayBuffer.isView(G)||B1(G,ArrayBuffer))return G.byteLength;if(typeof G!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof G);let x=G.length,m=arguments.length>2&&arguments[2]===!0;if(!m&&x===0)return 0;let l=!1;for(;;)switch(z){case"ascii":case"latin1":case"binary":return x;case"utf8":case"utf-8":return C1(G).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x*2;case"hex":return x>>>1;case"base64":return j1(G).length;default:if(l)return m?-1:C1(G).length;z=(""+z).toLowerCase(),l=!0}}Z.byteLength=M;function T(G,z,x){let m=!1;if((z===void 0||z<0)&&(z=0),z>this.length||((x===void 0||x>this.length)&&(x=this.length),x<=0)||(x>>>=0,z>>>=0,x<=z))return"";for(G||(G="utf8");;)switch(G){case"hex":return _(this,z,x);case"utf8":case"utf-8":return P(this,z,x);case"ascii":return k(this,z,x);case"latin1":case"binary":return S(this,z,x);case"base64":return q(this,z,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,z,x);default:if(m)throw new TypeError("Unknown encoding: "+G);G=(G+"").toLowerCase(),m=!0}}Z.prototype._isBuffer=!0;function h(G,z,x){let m=G[z];G[z]=G[x],G[x]=m}Z.prototype.swap16=function(){let G=this.length;if(G%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let z=0;zz&&(G+=" ... "),""},K&&(Z.prototype[K]=Z.prototype.inspect),Z.prototype.compare=function(G,z,x,m,l){if(B1(G,Uint8Array)&&(G=Z.from(G,G.offset,G.byteLength)),!Z.isBuffer(G))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof G);if(z===void 0&&(z=0),x===void 0&&(x=G?G.length:0),m===void 0&&(m=0),l===void 0&&(l=this.length),z<0||x>G.length||m<0||l>this.length)throw new RangeError("out of range index");if(m>=l&&z>=x)return 0;if(m>=l)return-1;if(z>=x)return 1;if(z>>>=0,x>>>=0,m>>>=0,l>>>=0,this===G)return 0;let a=l-m,K1=x-z,F1=Math.min(a,K1),R1=this.slice(m,l),X1=G.slice(z,x);for(let W1=0;W12147483647?x=2147483647:x<-2147483648&&(x=-2147483648),x=+x,k1(x)&&(x=l?0:G.length-1),x<0&&(x=G.length+x),x>=G.length){if(l)return-1;x=G.length-1}else if(x<0)if(l)x=0;else return-1;if(typeof z=="string"&&(z=Z.from(z,m)),Z.isBuffer(z))return z.length===0?-1:g(G,z,x,m,l);if(typeof z=="number")return z=z&255,typeof Uint8Array.prototype.indexOf=="function"?l?Uint8Array.prototype.indexOf.call(G,z,x):Uint8Array.prototype.lastIndexOf.call(G,z,x):g(G,[z],x,m,l);throw new TypeError("val must be string, number or Buffer")}function g(G,z,x,m,l){let a=1,K1=G.length,F1=z.length;if(m!==void 0&&(m=String(m).toLowerCase(),m==="ucs2"||m==="ucs-2"||m==="utf16le"||m==="utf-16le")){if(G.length<2||z.length<2)return-1;a=2,K1/=2,F1/=2,x/=2}function R1(W1,$1){return a===1?W1[$1]:W1.readUInt16BE($1*a)}let X1;if(l){let W1=-1;for(X1=x;X1K1&&(x=K1-F1),X1=x;X1>=0;X1--){let W1=!0;for(let $1=0;$1l&&(m=l)):m=l;let a=z.length;m>a/2&&(m=a/2);let K1;for(K1=0;K1>>0,isFinite(x)?(x=x>>>0,m===void 0&&(m="utf8")):(m=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let l=this.length-z;if((x===void 0||x>l)&&(x=l),G.length>0&&(x<0||z<0)||z>this.length)throw new RangeError("Attempt to write outside buffer bounds");m||(m="utf8");let a=!1;for(;;)switch(m){case"hex":return f(this,G,z,x);case"utf8":case"utf-8":return u(this,G,z,x);case"ascii":case"latin1":case"binary":return d(this,G,z,x);case"base64":return n(this,G,z,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,G,z,x);default:if(a)throw new TypeError("Unknown encoding: "+m);m=(""+m).toLowerCase(),a=!0}},Z.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function q(G,z,x){return z===0&&x===G.length?Q.fromByteArray(G):Q.fromByteArray(G.slice(z,x))}function P(G,z,x){x=Math.min(G.length,x);let m=[],l=z;for(;l239?4:a>223?3:a>191?2:1;if(l+F1<=x){let R1,X1,W1,$1;switch(F1){case 1:a<128&&(K1=a);break;case 2:R1=G[l+1],(R1&192)===128&&($1=(a&31)<<6|R1&63,$1>127&&(K1=$1));break;case 3:R1=G[l+1],X1=G[l+2],(R1&192)===128&&(X1&192)===128&&($1=(a&15)<<12|(R1&63)<<6|X1&63,$1>2047&&($1<55296||$1>57343)&&(K1=$1));break;case 4:R1=G[l+1],X1=G[l+2],W1=G[l+3],(R1&192)===128&&(X1&192)===128&&(W1&192)===128&&($1=(a&15)<<18|(R1&63)<<12|(X1&63)<<6|W1&63,$1>65535&&$1<1114112&&(K1=$1))}}K1===null?(K1=65533,F1=1):K1>65535&&(K1-=65536,m.push(K1>>>10&1023|55296),K1=56320|K1&1023),m.push(K1),l+=F1}return w(m)}var O=4096;function w(G){let z=G.length;if(z<=O)return String.fromCharCode.apply(String,G);let x="",m=0;for(;mm)&&(x=m);let l="";for(let a=z;ax&&(G=x),z<0?(z+=x,z<0&&(z=0)):z>x&&(z=x),zx)throw new RangeError("Trying to access beyond buffer length")}Z.prototype.readUintLE=Z.prototype.readUIntLE=function(G,z,x){G=G>>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G],l=1,a=0;for(;++a>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G+--z],l=1;for(;z>0&&(l*=256);)m+=this[G+--z]*l;return m},Z.prototype.readUint8=Z.prototype.readUInt8=function(G,z){return G=G>>>0,z||j(G,1,this.length),this[G]},Z.prototype.readUint16LE=Z.prototype.readUInt16LE=function(G,z){return G=G>>>0,z||j(G,2,this.length),this[G]|this[G+1]<<8},Z.prototype.readUint16BE=Z.prototype.readUInt16BE=function(G,z){return G=G>>>0,z||j(G,2,this.length),this[G]<<8|this[G+1]},Z.prototype.readUint32LE=Z.prototype.readUInt32LE=function(G,z){return G=G>>>0,z||j(G,4,this.length),(this[G]|this[G+1]<<8|this[G+2]<<16)+this[G+3]*16777216},Z.prototype.readUint32BE=Z.prototype.readUInt32BE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]*16777216+(this[G+1]<<16|this[G+2]<<8|this[G+3])},Z.prototype.readBigUInt64LE=G1(function(G){G=G>>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=z+this[++G]*256+this[++G]*65536+this[++G]*16777216,l=this[++G]+this[++G]*256+this[++G]*65536+x*16777216;return BigInt(m)+(BigInt(l)<>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=z*16777216+this[++G]*65536+this[++G]*256+this[++G],l=this[++G]*16777216+this[++G]*65536+this[++G]*256+x;return(BigInt(m)<>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G],l=1,a=0;for(;++a=l&&(m-=Math.pow(2,8*z)),m},Z.prototype.readIntBE=function(G,z,x){G=G>>>0,z=z>>>0,x||j(G,z,this.length);let m=z,l=1,a=this[G+--m];for(;m>0&&(l*=256);)a+=this[G+--m]*l;return l*=128,a>=l&&(a-=Math.pow(2,8*z)),a},Z.prototype.readInt8=function(G,z){return G=G>>>0,z||j(G,1,this.length),this[G]&128?(255-this[G]+1)*-1:this[G]},Z.prototype.readInt16LE=function(G,z){G=G>>>0,z||j(G,2,this.length);let x=this[G]|this[G+1]<<8;return x&32768?x|4294901760:x},Z.prototype.readInt16BE=function(G,z){G=G>>>0,z||j(G,2,this.length);let x=this[G+1]|this[G]<<8;return x&32768?x|4294901760:x},Z.prototype.readInt32LE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]|this[G+1]<<8|this[G+2]<<16|this[G+3]<<24},Z.prototype.readInt32BE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]<<24|this[G+1]<<16|this[G+2]<<8|this[G+3]},Z.prototype.readBigInt64LE=G1(function(G){G=G>>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=this[G+4]+this[G+5]*256+this[G+6]*65536+(x<<24);return(BigInt(m)<>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=(z<<24)+this[++G]*65536+this[++G]*256+this[++G];return(BigInt(m)<>>0,z||j(G,4,this.length),J.read(this,G,!0,23,4)},Z.prototype.readFloatBE=function(G,z){return G=G>>>0,z||j(G,4,this.length),J.read(this,G,!1,23,4)},Z.prototype.readDoubleLE=function(G,z){return G=G>>>0,z||j(G,8,this.length),J.read(this,G,!0,52,8)},Z.prototype.readDoubleBE=function(G,z){return G=G>>>0,z||j(G,8,this.length),J.read(this,G,!1,52,8)};function b(G,z,x,m,l,a){if(!Z.isBuffer(G))throw new TypeError('"buffer" argument must be a Buffer instance');if(z>l||zG.length)throw new RangeError("Index out of range")}Z.prototype.writeUintLE=Z.prototype.writeUIntLE=function(G,z,x,m){if(G=+G,z=z>>>0,x=x>>>0,!m){let K1=Math.pow(2,8*x)-1;b(this,G,z,x,K1,0)}let l=1,a=0;for(this[z]=G&255;++a>>0,x=x>>>0,!m){let K1=Math.pow(2,8*x)-1;b(this,G,z,x,K1,0)}let l=x-1,a=1;for(this[z+l]=G&255;--l>=0&&(a*=256);)this[z+l]=G/a&255;return z+x},Z.prototype.writeUint8=Z.prototype.writeUInt8=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,1,255,0),this[z]=G&255,z+1},Z.prototype.writeUint16LE=Z.prototype.writeUInt16LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,65535,0),this[z]=G&255,this[z+1]=G>>>8,z+2},Z.prototype.writeUint16BE=Z.prototype.writeUInt16BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,65535,0),this[z]=G>>>8,this[z+1]=G&255,z+2},Z.prototype.writeUint32LE=Z.prototype.writeUInt32LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,4294967295,0),this[z+3]=G>>>24,this[z+2]=G>>>16,this[z+1]=G>>>8,this[z]=G&255,z+4},Z.prototype.writeUint32BE=Z.prototype.writeUInt32BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,4294967295,0),this[z]=G>>>24,this[z+1]=G>>>16,this[z+2]=G>>>8,this[z+3]=G&255,z+4};function p(G,z,x,m,l){E1(z,m,l,G,x,7);let a=Number(z&BigInt(4294967295));G[x++]=a,a=a>>8,G[x++]=a,a=a>>8,G[x++]=a,a=a>>8,G[x++]=a;let K1=Number(z>>BigInt(32)&BigInt(4294967295));return G[x++]=K1,K1=K1>>8,G[x++]=K1,K1=K1>>8,G[x++]=K1,K1=K1>>8,G[x++]=K1,x}function s(G,z,x,m,l){E1(z,m,l,G,x,7);let a=Number(z&BigInt(4294967295));G[x+7]=a,a=a>>8,G[x+6]=a,a=a>>8,G[x+5]=a,a=a>>8,G[x+4]=a;let K1=Number(z>>BigInt(32)&BigInt(4294967295));return G[x+3]=K1,K1=K1>>8,G[x+2]=K1,K1=K1>>8,G[x+1]=K1,K1=K1>>8,G[x]=K1,x+8}Z.prototype.writeBigUInt64LE=G1(function(G,z=0){return p(this,G,z,BigInt(0),BigInt("0xffffffffffffffff"))}),Z.prototype.writeBigUInt64BE=G1(function(G,z=0){return s(this,G,z,BigInt(0),BigInt("0xffffffffffffffff"))}),Z.prototype.writeIntLE=function(G,z,x,m){if(G=+G,z=z>>>0,!m){let F1=Math.pow(2,8*x-1);b(this,G,z,x,F1-1,-F1)}let l=0,a=1,K1=0;for(this[z]=G&255;++l>0)-K1&255;return z+x},Z.prototype.writeIntBE=function(G,z,x,m){if(G=+G,z=z>>>0,!m){let F1=Math.pow(2,8*x-1);b(this,G,z,x,F1-1,-F1)}let l=x-1,a=1,K1=0;for(this[z+l]=G&255;--l>=0&&(a*=256);)G<0&&K1===0&&this[z+l+1]!==0&&(K1=1),this[z+l]=(G/a>>0)-K1&255;return z+x},Z.prototype.writeInt8=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,1,127,-128),G<0&&(G=255+G+1),this[z]=G&255,z+1},Z.prototype.writeInt16LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,32767,-32768),this[z]=G&255,this[z+1]=G>>>8,z+2},Z.prototype.writeInt16BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,32767,-32768),this[z]=G>>>8,this[z+1]=G&255,z+2},Z.prototype.writeInt32LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,2147483647,-2147483648),this[z]=G&255,this[z+1]=G>>>8,this[z+2]=G>>>16,this[z+3]=G>>>24,z+4},Z.prototype.writeInt32BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,2147483647,-2147483648),G<0&&(G=4294967295+G+1),this[z]=G>>>24,this[z+1]=G>>>16,this[z+2]=G>>>8,this[z+3]=G&255,z+4},Z.prototype.writeBigInt64LE=G1(function(G,z=0){return p(this,G,z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),Z.prototype.writeBigInt64BE=G1(function(G,z=0){return s(this,G,z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function r(G,z,x,m,l,a){if(x+m>G.length)throw new RangeError("Index out of range");if(x<0)throw new RangeError("Index out of range")}function A1(G,z,x,m,l){return z=+z,x=x>>>0,l||r(G,z,x,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000),J.write(G,z,x,m,23,4),x+4}Z.prototype.writeFloatLE=function(G,z,x){return A1(this,G,z,!0,x)},Z.prototype.writeFloatBE=function(G,z,x){return A1(this,G,z,!1,x)};function Q1(G,z,x,m,l){return z=+z,x=x>>>0,l||r(G,z,x,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000),J.write(G,z,x,m,52,8),x+8}Z.prototype.writeDoubleLE=function(G,z,x){return Q1(this,G,z,!0,x)},Z.prototype.writeDoubleBE=function(G,z,x){return Q1(this,G,z,!1,x)},Z.prototype.copy=function(G,z,x,m){if(!Z.isBuffer(G))throw new TypeError("argument should be a Buffer");if(x||(x=0),!m&&m!==0&&(m=this.length),z>=G.length&&(z=G.length),z||(z=0),m>0&&m=this.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("sourceEnd out of bounds");m>this.length&&(m=this.length),G.length-z>>0,x=x===void 0?this.length:x>>>0,G||(G=0);let l;if(typeof G=="number")for(l=z;l4294967296?l=U1(String(x)):typeof x=="bigint"&&(l=String(x),(x>BigInt(2)**BigInt(32)||x<-(BigInt(2)**BigInt(32)))&&(l=U1(l)),l+="n"),m+=` It must be ${z}. Received ${l}`,m},RangeError);function U1(G){let z="",x=G.length,m=G[0]==="-"?1:0;for(;x>=m+4;x-=3)z=`_${G.slice(x-3,x)}${z}`;return`${G.slice(0,x)}${z}`}function O1(G,z,x){Y1(z,"offset"),(G[z]===void 0||G[z+x]===void 0)&&i(z,G.length-(x+1))}function E1(G,z,x,m,l,a){if(G>x||G3?z===0||z===BigInt(0)?F1=`>= 0${K1} and < 2${K1} ** ${(a+1)*8}${K1}`:F1=`>= -(2${K1} ** ${(a+1)*8-1}${K1}) and < 2 ** ${(a+1)*8-1}${K1}`:F1=`>= ${z}${K1} and <= ${x}${K1}`,new e.ERR_OUT_OF_RANGE("value",F1,G)}O1(m,l,a)}function Y1(G,z){if(typeof G!="number")throw new e.ERR_INVALID_ARG_TYPE(z,"number",G)}function i(G,z,x){throw Math.floor(G)!==G?(Y1(G,x),new e.ERR_OUT_OF_RANGE(x||"offset","an integer",G)):z<0?new e.ERR_BUFFER_OUT_OF_BOUNDS:new e.ERR_OUT_OF_RANGE(x||"offset",`>= ${x?1:0} and <= ${z}`,G)}var c=/[^+/0-9A-Za-z-_]/g;function o(G){if(G=G.split("=")[0],G=G.trim().replace(c,""),G.length<2)return"";for(;G.length%4!==0;)G=G+"=";return G}function C1(G,z){z=z||1/0;let x,m=G.length,l=null,a=[];for(let K1=0;K155295&&x<57344){if(!l){if(x>56319){(z-=3)>-1&&a.push(239,191,189);continue}else if(K1+1===m){(z-=3)>-1&&a.push(239,191,189);continue}l=x;continue}if(x<56320){(z-=3)>-1&&a.push(239,191,189),l=x;continue}x=(l-55296<<10|x-56320)+65536}else l&&(z-=3)>-1&&a.push(239,191,189);if(l=null,x<128){if((z-=1)<0)break;a.push(x)}else if(x<2048){if((z-=2)<0)break;a.push(x>>6|192,x&63|128)}else if(x<65536){if((z-=3)<0)break;a.push(x>>12|224,x>>6&63|128,x&63|128)}else if(x<1114112){if((z-=4)<0)break;a.push(x>>18|240,x>>12&63|128,x>>6&63|128,x&63|128)}else throw new Error("Invalid code point")}return a}function q1(G){let z=[];for(let x=0;x>8,l=x%256,a.push(l),a.push(m);return a}function j1(G){return Q.toByteArray(o(G))}function H1(G,z,x,m){let l;for(l=0;l=z.length||l>=G.length);++l)z[l+x]=G[l];return l}function B1(G,z){return G instanceof z||G!=null&&G.constructor!=null&&G.constructor.name!=null&&G.constructor.name===z.name}function k1(G){return G!==G}var D1=function(){let G="0123456789abcdef",z=new Array(256);for(let x=0;x<16;++x){let m=x*16;for(let l=0;l<16;++l)z[m+l]=G[x]+G[l]}return z}();function G1(G){return typeof BigInt>"u"?w1:G}function w1(){throw new Error("BigInt not supported")}}),nE1=fB((A,Q)=>{var J=lE1(),K=J.Buffer;function C(Y,Z){for(var X in Y)Z[X]=Y[X]}K.from&&K.alloc&&K.allocUnsafe&&K.allocUnsafeSlow?Q.exports=J:(C(J,A),A.Buffer=U);function U(Y,Z,X){return K(Y,Z,X)}U.prototype=Object.create(K.prototype),C(K,U),U.from=function(Y,Z,X){if(typeof Y=="number")throw new TypeError("Argument must not be a number");return K(Y,Z,X)},U.alloc=function(Y,Z,X){if(typeof Y!="number")throw new TypeError("Argument must be a number");var E=K(Y);return Z!==void 0?typeof X=="string"?E.fill(Z,X):E.fill(Z):E.fill(0),E},U.allocUnsafe=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return K(Y)},U.allocUnsafeSlow=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return J.SlowBuffer(Y)}}),sE1=fB((A)=>{var Q=nE1().Buffer,J=Q.isEncoding||function(R){switch(R=""+R,R&&R.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function K(R){if(!R)return"utf8";for(var M;;)switch(R){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return R;default:if(M)return;R=(""+R).toLowerCase(),M=!0}}function C(R){var M=K(R);if(typeof M!="string"&&(Q.isEncoding===J||!J(R)))throw new Error("Unknown encoding: "+R);return M||R}A.StringDecoder=U;function U(R){this.encoding=C(R);var M;switch(this.encoding){case"utf16le":this.text=I,this.end=N,M=4;break;case"utf8":this.fillLast=E,M=4;break;case"base64":this.text=F,this.end=V,M=3;break;default:this.write=D,this.end=L;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Q.allocUnsafe(M)}U.prototype.write=function(R){if(R.length===0)return"";var M,T;if(this.lastNeed){if(M=this.fillLast(R),M===void 0)return"";T=this.lastNeed,this.lastNeed=0}else T=0;return T>5===6?2:R>>4===14?3:R>>3===30?4:R>>6===2?-1:-2}function Z(R,M,T){var h=M.length-1;if(h=0?(y>0&&(R.lastNeed=y-1),y):--h=0?(y>0&&(R.lastNeed=y-2),y):--h=0?(y>0&&(y===2?y=0:R.lastNeed=y-3),y):0))}function X(R,M,T){if((M[0]&192)!==128)return R.lastNeed=0,"�";if(R.lastNeed>1&&M.length>1){if((M[1]&192)!==128)return R.lastNeed=1,"�";if(R.lastNeed>2&&M.length>2&&(M[2]&192)!==128)return R.lastNeed=2,"�"}}function E(R){var M=this.lastTotal-this.lastNeed,T=X(this,R,M);if(T!==void 0)return T;if(this.lastNeed<=R.length)return R.copy(this.lastChar,M,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);R.copy(this.lastChar,M,0,R.length),this.lastNeed-=R.length}function H(R,M){var T=Z(this,R,M);if(!this.lastNeed)return R.toString("utf8",M);this.lastTotal=T;var h=R.length-(T-this.lastNeed);return R.copy(this.lastChar,0,h),R.toString("utf8",M,h)}function $(R){var M=R&&R.length?this.write(R):"";return this.lastNeed?M+"�":M}function I(R,M){if((R.length-M)%2===0){var T=R.toString("utf16le",M);if(T){var h=T.charCodeAt(T.length-1);if(h>=55296&&h<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=R[R.length-2],this.lastChar[1]=R[R.length-1],T.slice(0,-1)}return T}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=R[R.length-1],R.toString("utf16le",M,R.length-1)}function N(R){var M=R&&R.length?this.write(R):"";if(this.lastNeed){var T=this.lastTotal-this.lastNeed;return M+this.lastChar.toString("utf16le",0,T)}return M}function F(R,M){var T=(R.length-M)%3;return T===0?R.toString("base64",M):(this.lastNeed=3-T,this.lastTotal=3,T===1?this.lastChar[0]=R[R.length-1]:(this.lastChar[0]=R[R.length-2],this.lastChar[1]=R[R.length-1]),R.toString("base64",M,R.length-T))}function V(R){var M=R&&R.length?this.write(R):"";return this.lastNeed?M+this.lastChar.toString("base64",0,3-this.lastNeed):M}function D(R){return R.toString(this.encoding)}function L(R){return R&&R.length?this.write(R):""}}),bd=mE1(sE1()),oE1=bd.StringDecoder,iE1=bd.StringDecoder;/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *//*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *//*! safe-buffer. MIT License. Feross Aboukhadijeh */});var md=B0((vs1,ud)=>{var FJ=F7().Buffer;ud.exports={utf8:{type:"_internal",bomAware:!0},cesu8:{type:"_internal",bomAware:!0},unicode11utf8:"utf8",ucs2:{type:"_internal",bomAware:!0},utf16le:"ucs2",binary:{type:"_internal"},base64:{type:"_internal"},hex:{type:"_internal"},_internal:mD};function mD(A,Q){if(this.enc=A.encodingName,this.bomAware=A.bomAware,this.enc==="base64")this.encoder=lD;else if(this.enc==="cesu8"){if(this.enc="utf8",this.encoder=nD,FJ.from("eda0bdedb2a9","hex").toString()!=="\uD83D\uDCA9")this.decoder=sD,this.defaultCharUnicode=Q.defaultCharUnicode}}mD.prototype.encoder=dD;mD.prototype.decoder=cD;var uD=(pd(),y4(fd)).StringDecoder;if(!uD.prototype.end)uD.prototype.end=function(){};function cD(A,Q){this.decoder=new uD(Q.enc)}cD.prototype.write=function(A){if(!FJ.isBuffer(A))A=FJ.from(A);return this.decoder.write(A)};cD.prototype.end=function(){return this.decoder.end()};function dD(A,Q){this.enc=Q.enc}dD.prototype.write=function(A){return FJ.from(A,this.enc)};dD.prototype.end=function(){};function lD(A,Q){this.prevStr=""}lD.prototype.write=function(A){A=this.prevStr+A;var Q=A.length-A.length%4;return this.prevStr=A.slice(Q),A=A.slice(0,Q),FJ.from(A,"base64")};lD.prototype.end=function(){return FJ.from(this.prevStr,"base64")};function nD(A,Q){}nD.prototype.write=function(A){var Q=FJ.alloc(A.length*3),J=0;for(var K=0;K>>6),Q[J++]=128+(C&63);else Q[J++]=224+(C>>>12),Q[J++]=128+(C>>>6&63),Q[J++]=128+(C&63)}return Q.slice(0,J)};nD.prototype.end=function(){};function sD(A,Q){this.acc=0,this.contBytes=0,this.accBytes=0,this.defaultCharUnicode=Q.defaultCharUnicode}sD.prototype.write=function(A){var Q=this.acc,J=this.contBytes,K=this.accBytes,C="";for(var U=0;U0)C+=this.defaultCharUnicode,J=0;if(Y<128)C+=String.fromCharCode(Y);else if(Y<224)Q=Y&31,J=1,K=1;else if(Y<240)Q=Y&15,J=2,K=1;else C+=this.defaultCharUnicode}else if(J>0){if(Q=Q<<6|Y&63,J--,K++,J===0)if(K===2&&Q<128&&Q>0)C+=this.defaultCharUnicode;else if(K===3&&Q<2048)C+=this.defaultCharUnicode;else C+=String.fromCharCode(Q)}else C+=this.defaultCharUnicode}return this.acc=Q,this.contBytes=J,this.accBytes=K,C};sD.prototype.end=function(){var A=0;if(this.contBytes>0)A+=this.defaultCharUnicode;return A}});var ld=B0((aE1)=>{var _W=F7().Buffer;aE1._utf32=oD;function oD(A,Q){this.iconv=Q,this.bomAware=!0,this.isLE=A.isLE}aE1.utf32le={type:"_utf32",isLE:!0};aE1.utf32be={type:"_utf32",isLE:!1};aE1.ucs4le="utf32le";aE1.ucs4be="utf32be";oD.prototype.encoder=iD;oD.prototype.decoder=aD;function iD(A,Q){this.isLE=Q.isLE,this.highSurrogate=0}iD.prototype.write=function(A){var Q=_W.from(A,"ucs2"),J=_W.alloc(Q.length*2),K=this.isLE?J.writeUInt32LE:J.writeUInt32BE,C=0;for(var U=0;U0){for(;Q1114111)J=K;if(J>=65536){J-=65536;var C=55296|J>>10;A[Q++]=C&255,A[Q++]=C>>8;var J=56320|J&1023}return A[Q++]=J&255,A[Q++]=J>>8,Q}aD.prototype.end=function(){this.overflow.length=0};aE1.utf32=rD;aE1.ucs4="utf32";function rD(A,Q){this.iconv=Q}rD.prototype.encoder=tD;rD.prototype.decoder=eD;function tD(A,Q){if(A=A||{},A.addBOM===void 0)A.addBOM=!0;this.encoder=Q.iconv.getEncoder(A.defaultEncoding||"utf-32le",A)}tD.prototype.write=function(A){return this.encoder.write(A)};tD.prototype.end=function(){return this.encoder.end()};function eD(A,Q){this.decoder=null,this.initialBufs=[],this.initialBufsLen=0,this.options=A||{},this.iconv=Q.iconv}eD.prototype.write=function(A){if(!this.decoder){if(this.initialBufs.push(A),this.initialBufsLen+=A.length,this.initialBufsLen<32)return"";var Q=dd(this.initialBufs,this.options.defaultEncoding);this.decoder=this.iconv.getDecoder(Q,this.options);var J="";for(var K=0;K16)U++;if(J[3]!==0||J[2]>16)C++;if(J[0]===0&&J[1]===0&&(J[2]!==0||J[3]!==0))Z++;if((J[0]!==0||J[1]!==0)&&J[2]===0&&J[3]===0)Y++;if(J.length=0,K++,K>=100)break A}}if(Z-U>Y-C)return"utf-32be";if(Z-U{var nd=F7().Buffer;C$1.utf16be=TW;function TW(){}TW.prototype.encoder=AV;TW.prototype.decoder=QV;TW.prototype.bomAware=!0;function AV(){}AV.prototype.write=function(A){var Q=nd.from(A,"ucs2");for(var J=0;J=100)break A}}if(U>C)return"utf-16be";if(U{var G3=F7().Buffer;E$1.utf7=kW;E$1.unicode11utf7="utf7";function kW(A,Q){this.iconv=Q}kW.prototype.encoder=UV;kW.prototype.decoder=ZV;kW.prototype.bomAware=!0;var Z$1=/[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;function UV(A,Q){this.iconv=Q.iconv}UV.prototype.write=function(A){return G3.from(A.replace(Z$1,function(Q){return"+"+(Q==="+"?"":this.iconv.encode(Q,"utf16-be").toString("base64").replace(/=+$/,""))+"-"}.bind(this)))};UV.prototype.end=function(){};function ZV(A,Q){this.iconv=Q.iconv,this.inBase64=!1,this.base64Accum=""}var B$1=/[A-Za-z0-9\/+]/,BV=[];for(pB=0;pB<256;pB++)BV[pB]=B$1.test(String.fromCharCode(pB));var pB,X$1=43,RJ=45,YV=38;ZV.prototype.write=function(A){var Q="",J=0,K=this.inBase64,C=this.base64Accum;for(var U=0;U0)A=this.iconv.decode(G3.from(this.base64Accum,"base64"),"utf16-be");return this.inBase64=!1,this.base64Accum="",A};E$1.utf7imap=SW;function SW(A,Q){this.iconv=Q}SW.prototype.encoder=XV;SW.prototype.decoder=EV;SW.prototype.bomAware=!0;function XV(A,Q){this.iconv=Q.iconv,this.inBase64=!1,this.base64Accum=G3.alloc(6),this.base64AccumIdx=0}XV.prototype.write=function(A){var Q=this.inBase64,J=this.base64Accum,K=this.base64AccumIdx,C=G3.alloc(A.length*5+10),U=0;for(var Y=0;Y0)U+=C.write(J.slice(0,K).toString("base64").replace(/\//g,",").replace(/=+$/,""),U),K=0;C[U++]=RJ,Q=!1}if(!Q){if(C[U++]=Z,Z===YV)C[U++]=RJ}}else{if(!Q)C[U++]=YV,Q=!0;if(Q){if(J[K++]=Z>>8,J[K++]=Z&255,K==J.length)U+=C.write(J.toString("base64").replace(/\//g,","),U),K=0}}}return this.inBase64=Q,this.base64AccumIdx=K,C.slice(0,U)};XV.prototype.end=function(){var A=G3.alloc(10),Q=0;if(this.inBase64){if(this.base64AccumIdx>0)Q+=A.write(this.base64Accum.slice(0,this.base64AccumIdx).toString("base64").replace(/\//g,",").replace(/=+$/,""),Q),this.base64AccumIdx=0;A[Q++]=RJ,this.inBase64=!1}return A.slice(0,Q)};function EV(A,Q){this.iconv=Q.iconv,this.inBase64=!1,this.base64Accum=""}var id=BV.slice();id[44]=!0;EV.prototype.write=function(A){var Q="",J=0,K=this.inBase64,C=this.base64Accum;for(var U=0;U0)A=this.iconv.decode(G3.from(this.base64Accum,"base64"),"utf16-be");return this.inBase64=!1,this.base64Accum="",A}});var rd=B0((W$1)=>{var jW=F7().Buffer;W$1._sbcs=$V;function $V(A,Q){if(!A)throw new Error("SBCS codec is called without the data.");if(!A.chars||A.chars.length!==128&&A.chars.length!==256)throw new Error("Encoding '"+A.type+"' has incorrect 'chars' (must be of len 128 or 256)");if(A.chars.length===128){var J="";for(var K=0;K<128;K++)J+=String.fromCharCode(K);A.chars=J+A.chars}this.decodeBuf=jW.from(A.chars,"ucs2");var C=jW.alloc(65536,Q.defaultCharSingleByte.charCodeAt(0));for(var K=0;K{td.exports={"10029":"maccenteuro",maccenteuro:{type:"_sbcs",chars:"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ"},"808":"cp808",ibm808:"cp808",cp808:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ "},mik:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},cp720:{type:"_sbcs",chars:"€éâ„à†çêëèïّْô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡ًٌٍَُِ≈°∙·√ⁿ²■ "},ascii8bit:"ascii",usascii:"ascii",ansix34:"ascii",ansix341968:"ascii",ansix341986:"ascii",csascii:"ascii",cp367:"ascii",ibm367:"ascii",isoir6:"ascii",iso646us:"ascii",iso646irv:"ascii",us:"ascii",latin1:"iso88591",latin2:"iso88592",latin3:"iso88593",latin4:"iso88594",latin5:"iso88599",latin6:"iso885910",latin7:"iso885913",latin8:"iso885914",latin9:"iso885915",latin10:"iso885916",csisolatin1:"iso88591",csisolatin2:"iso88592",csisolatin3:"iso88593",csisolatin4:"iso88594",csisolatincyrillic:"iso88595",csisolatinarabic:"iso88596",csisolatingreek:"iso88597",csisolatinhebrew:"iso88598",csisolatin5:"iso88599",csisolatin6:"iso885910",l1:"iso88591",l2:"iso88592",l3:"iso88593",l4:"iso88594",l5:"iso88599",l6:"iso885910",l7:"iso885913",l8:"iso885914",l9:"iso885915",l10:"iso885916",isoir14:"iso646jp",isoir57:"iso646cn",isoir100:"iso88591",isoir101:"iso88592",isoir109:"iso88593",isoir110:"iso88594",isoir144:"iso88595",isoir127:"iso88596",isoir126:"iso88597",isoir138:"iso88598",isoir148:"iso88599",isoir157:"iso885910",isoir166:"tis620",isoir179:"iso885913",isoir199:"iso885914",isoir203:"iso885915",isoir226:"iso885916",cp819:"iso88591",ibm819:"iso88591",cyrillic:"iso88595",arabic:"iso88596",arabic8:"iso88596",ecma114:"iso88596",asmo708:"iso88596",greek:"iso88597",greek8:"iso88597",ecma118:"iso88597",elot928:"iso88597",hebrew:"iso88598",hebrew8:"iso88598",turkish:"iso88599",turkish8:"iso88599",thai:"iso885911",thai8:"iso885911",celtic:"iso885914",celtic8:"iso885914",isoceltic:"iso885914",tis6200:"tis620",tis62025291:"tis620",tis62025330:"tis620","10000":"macroman","10006":"macgreek","10007":"maccyrillic","10079":"maciceland","10081":"macturkish",cspc8codepage437:"cp437",cspc775baltic:"cp775",cspc850multilingual:"cp850",cspcp852:"cp852",cspc862latinhebrew:"cp862",cpgr:"cp869",msee:"cp1250",mscyrl:"cp1251",msansi:"cp1252",msgreek:"cp1253",msturk:"cp1254",mshebr:"cp1255",msarab:"cp1256",winbaltrim:"cp1257",cp20866:"koi8r","20866":"koi8r",ibm878:"koi8r",cskoi8r:"koi8r",cp21866:"koi8u","21866":"koi8u",ibm1168:"koi8u",strk10482002:"rk1048",tcvn5712:"tcvn",tcvn57121:"tcvn",gb198880:"iso646cn",cn:"iso646cn",csiso14jisc6220ro:"iso646jp",jisc62201969ro:"iso646jp",jp:"iso646jp",cshproman8:"hproman8",r8:"hproman8",roman8:"hproman8",xroman8:"hproman8",ibm1051:"hproman8",mac:"macintosh",csmacintosh:"macintosh"}});var Ql=B0((fs1,Al)=>{Al.exports={"437":"cp437","737":"cp737","775":"cp775","850":"cp850","852":"cp852","855":"cp855","856":"cp856","857":"cp857","858":"cp858","860":"cp860","861":"cp861","862":"cp862","863":"cp863","864":"cp864","865":"cp865","866":"cp866","869":"cp869","874":"windows874","922":"cp922","1046":"cp1046","1124":"cp1124","1125":"cp1125","1129":"cp1129","1133":"cp1133","1161":"cp1161","1162":"cp1162","1163":"cp1163","1250":"windows1250","1251":"windows1251","1252":"windows1252","1253":"windows1253","1254":"windows1254","1255":"windows1255","1256":"windows1256","1257":"windows1257","1258":"windows1258","28591":"iso88591","28592":"iso88592","28593":"iso88593","28594":"iso88594","28595":"iso88595","28596":"iso88596","28597":"iso88597","28598":"iso88598","28599":"iso88599","28600":"iso885910","28601":"iso885911","28603":"iso885913","28604":"iso885914","28605":"iso885915","28606":"iso885916",windows874:{type:"_sbcs",chars:"€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"},win874:"windows874",cp874:"windows874",windows1250:{type:"_sbcs",chars:"€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"},win1250:"windows1250",cp1250:"windows1250",windows1251:{type:"_sbcs",chars:"ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"},win1251:"windows1251",cp1251:"windows1251",windows1252:{type:"_sbcs",chars:"€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},win1252:"windows1252",cp1252:"windows1252",windows1253:{type:"_sbcs",chars:"€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"},win1253:"windows1253",cp1253:"windows1253",windows1254:{type:"_sbcs",chars:"€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"},win1254:"windows1254",cp1254:"windows1254",windows1255:{type:"_sbcs",chars:"€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"},win1255:"windows1255",cp1255:"windows1255",windows1256:{type:"_sbcs",chars:"€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے"},win1256:"windows1256",cp1256:"windows1256",windows1257:{type:"_sbcs",chars:"€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙"},win1257:"windows1257",cp1257:"windows1257",windows1258:{type:"_sbcs",chars:"€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},win1258:"windows1258",cp1258:"windows1258",iso88591:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},cp28591:"iso88591",iso88592:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"},cp28592:"iso88592",iso88593:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙"},cp28593:"iso88593",iso88594:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙"},cp28594:"iso88594",iso88595:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ"},cp28595:"iso88595",iso88596:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������"},cp28596:"iso88596",iso88597:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"},cp28597:"iso88597",iso88598:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"},cp28598:"iso88598",iso88599:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"},cp28599:"iso88599",iso885910:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ"},cp28600:"iso885910",iso885911:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"},cp28601:"iso885911",iso885913:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’"},cp28603:"iso885913",iso885914:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ"},cp28604:"iso885914",iso885915:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},cp28605:"iso885915",iso885916:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ"},cp28606:"iso885916",cp437:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm437:"cp437",csibm437:"cp437",cp737:{type:"_sbcs",chars:"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ "},ibm737:"cp737",csibm737:"cp737",cp775:{type:"_sbcs",chars:"ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ "},ibm775:"cp775",csibm775:"cp775",cp850:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "},ibm850:"cp850",csibm850:"cp850",cp852:{type:"_sbcs",chars:"ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ "},ibm852:"cp852",csibm852:"cp852",cp855:{type:"_sbcs",chars:"ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ "},ibm855:"cp855",csibm855:"cp855",cp856:{type:"_sbcs",chars:"אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ "},ibm856:"cp856",csibm856:"cp856",cp857:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ "},ibm857:"cp857",csibm857:"cp857",cp858:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "},ibm858:"cp858",csibm858:"cp858",cp860:{type:"_sbcs",chars:"ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm860:"cp860",csibm860:"cp860",cp861:{type:"_sbcs",chars:"ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm861:"cp861",csibm861:"cp861",cp862:{type:"_sbcs",chars:"אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm862:"cp862",csibm862:"cp862",cp863:{type:"_sbcs",chars:"ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm863:"cp863",csibm863:"cp863",cp864:{type:"_sbcs",chars:`\x00\x01\x02\x03\x04\x05\x06\x07\b -\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�`},ibm864:"cp864",csibm864:"cp864",cp865:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm865:"cp865",csibm865:"cp865",cp866:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "},ibm866:"cp866",csibm866:"cp866",cp869:{type:"_sbcs",chars:"������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ "},ibm869:"cp869",csibm869:"cp869",cp922:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"},ibm922:"cp922",csibm922:"cp922",cp1046:{type:"_sbcs",chars:"ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"},ibm1046:"cp1046",csibm1046:"cp1046",cp1124:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"},ibm1124:"cp1124",csibm1124:"cp1124",cp1125:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "},ibm1125:"cp1125",csibm1125:"cp1125",cp1129:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},ibm1129:"cp1129",csibm1129:"cp1129",cp1133:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"},ibm1133:"cp1133",csibm1133:"cp1133",cp1161:{type:"_sbcs",chars:"��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "},ibm1161:"cp1161",csibm1161:"cp1161",cp1162:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"},ibm1162:"cp1162",csibm1162:"cp1162",cp1163:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},ibm1163:"cp1163",csibm1163:"cp1163",maccroatian:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ"},maccyrillic:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"},macgreek:{type:"_sbcs",chars:"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�"},maciceland:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},macroman:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},macromania:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},macthai:{type:"_sbcs",chars:"«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู\uFEFF​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����"},macturkish:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ"},macukraine:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"},koi8r:{type:"_sbcs",chars:"─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"},koi8u:{type:"_sbcs",chars:"─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"},koi8ru:{type:"_sbcs",chars:"─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"},koi8t:{type:"_sbcs",chars:"қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"},armscii8:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�"},rk1048:{type:"_sbcs",chars:"ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"},tcvn:{type:"_sbcs",chars:`\x00ÚỤ\x03ỪỬỮ\x07\b -\v\f\r\x0E\x0F\x10ỨỰỲỶỸÝỴ\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ`},georgianacademy:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},georgianps:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},pt154:{type:"_sbcs",chars:"ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"},viscii:{type:"_sbcs",chars:`\x00\x01Ẳ\x03\x04ẴẪ\x07\b -\v\f\r\x0E\x0F\x10\x11\x12\x13Ỷ\x15\x16\x17\x18Ỹ\x1A\x1B\x1C\x1DỴ\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ`},iso646cn:{type:"_sbcs",chars:`\x00\x01\x02\x03\x04\x05\x06\x07\b -\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������`},iso646jp:{type:"_sbcs",chars:`\x00\x01\x02\x03\x04\x05\x06\x07\b -\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_\`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������`},hproman8:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�"},macintosh:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},ascii:{type:"_sbcs",chars:"��������������������������������������������������������������������������������������������������������������������������������"},tis620:{type:"_sbcs",chars:"���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"}}});var Kl=B0((q$1)=>{var WV=F7().Buffer;q$1._dbcs=R7;var a8=-1,Jl=-2,i9=-10,D6=-1000,XY=new Array(256),uB=-1;for(vW=0;vW<256;vW++)XY[vW]=a8;var vW;function R7(A,Q){if(this.encodingName=A.encodingName,!A)throw new Error("DBCS codec is called without the data.");if(!A.table)throw new Error("Encoding '"+this.encodingName+"' has no data.");var J=A.table();this.decodeTables=[],this.decodeTables[0]=XY.slice(0),this.decodeTableSeq=[];for(var K=0;KD6)throw new Error("gb18030 decode tables conflict at byte 2");var E=this.decodeTables[D6-Z[X]];for(var H=129;H<=254;H++){if(E[H]===a8)E[H]=D6-U;else if(E[H]===D6-U)continue;else if(E[H]>D6)throw new Error("gb18030 decode tables conflict at byte 3");var $=this.decodeTables[D6-E[H]];for(var I=48;I<=57;I++)if($[I]===a8)$[I]=Jl}}}}this.defaultCharUnicode=Q.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var N={};if(A.encodeSkipVals)for(var K=0;K0;A>>>=8)Q.push(A&255);if(Q.length==0)Q.push(0);var J=this.decodeTables[0];for(var K=Q.length-1;K>0;K--){var C=J[Q[K]];if(C==a8)J[Q[K]]=D6-this.decodeTables.length,this.decodeTables.push(J=XY.slice(0));else if(C<=D6)J=this.decodeTables[D6-C];else throw new Error("Overwrite byte in "+this.encodingName+", addr: "+A.toString(16))}return J};R7.prototype._addDecodeChunk=function(A){var Q=parseInt(A[0],16),J=this._getDecodeTrieNode(Q);Q=Q&255;for(var K=1;K255)throw new Error("Incorrect chunk in "+this.encodingName+" at addr "+A[0]+": too long"+Q)};R7.prototype._getEncodeBucket=function(A){var Q=A>>8;if(this.encodeTable[Q]===void 0)this.encodeTable[Q]=XY.slice(0);return this.encodeTable[Q]};R7.prototype._setEncodeChar=function(A,Q){var J=this._getEncodeBucket(A),K=A&255;if(J[K]<=i9)this.encodeTableSeq[i9-J[K]][uB]=Q;else if(J[K]==a8)J[K]=Q};R7.prototype._setEncodeSequence=function(A,Q){var J=A[0],K=this._getEncodeBucket(J),C=J&255,U;if(K[C]<=i9)U=this.encodeTableSeq[i9-K[C]];else{if(U={},K[C]!==a8)U[uB]=K[C];K[C]=i9-this.encodeTableSeq.length,this.encodeTableSeq.push(U)}for(var Y=1;Y=0)this._setEncodeChar(Z,X),C=!0;else if(Z<=D6){var E=D6-Z;if(!U[E]){var H=X<<8>>>0;if(this._fillEncodeTable(E,H,J))C=!0;else U[E]=!0}}else if(Z<=i9)this._setEncodeSequence(this.decodeTableSeq[i9-Z],X),C=!0}return C};function xW(A,Q){this.leadSurrogate=-1,this.seqObj=void 0,this.encodeTable=Q.encodeTable,this.encodeTableSeq=Q.encodeTableSeq,this.defaultCharSingleByte=Q.defCharSB,this.gb18030=Q.gb18030}xW.prototype.write=function(A){var Q=WV.alloc(A.length*(this.gb18030?4:3)),J=this.leadSurrogate,K=this.seqObj,C=-1,U=0,Y=0;while(!0){if(C===-1){if(U==A.length)break;var Z=A.charCodeAt(U++)}else{var Z=C;C=-1}if(55296<=Z&&Z<57344)if(Z<56320)if(J===-1){J=Z;continue}else J=Z,Z=a8;else if(J!==-1)Z=65536+(J-55296)*1024+(Z-56320),J=-1;else Z=a8;else if(J!==-1)C=Z,Z=a8,J=-1;var X=a8;if(K!==void 0&&Z!=a8){var E=K[Z];if(typeof E==="object"){K=E;continue}else if(typeof E=="number")X=E;else if(E==null){if(E=K[uB],E!==void 0)X=E,C=Z}K=void 0}else if(Z>=0){var H=this.encodeTable[Z>>8];if(H!==void 0)X=H[Z&255];if(X<=i9){K=this.encodeTableSeq[i9-X];continue}if(X==a8&&this.gb18030){var $=qV(this.gb18030.uChars,Z);if($!=-1){var X=this.gb18030.gbChars[$]+(Z-this.gb18030.uChars[$]);Q[Y++]=129+Math.floor(X/12600),X=X%12600,Q[Y++]=48+Math.floor(X/1260),X=X%1260,Q[Y++]=129+Math.floor(X/10),X=X%10,Q[Y++]=48+X;continue}}}if(X===a8)X=this.defaultCharSingleByte;if(X<256)Q[Y++]=X;else if(X<65536)Q[Y++]=X>>8,Q[Y++]=X&255;else if(X<16777216)Q[Y++]=X>>16,Q[Y++]=X>>8&255,Q[Y++]=X&255;else Q[Y++]=X>>>24,Q[Y++]=X>>>16&255,Q[Y++]=X>>>8&255,Q[Y++]=X&255}return this.seqObj=K,this.leadSurrogate=J,Q.slice(0,Y)};xW.prototype.end=function(){if(this.leadSurrogate===-1&&this.seqObj===void 0)return;var A=WV.alloc(10),Q=0;if(this.seqObj){var J=this.seqObj[uB];if(J!==void 0)if(J<256)A[Q++]=J;else A[Q++]=J>>8,A[Q++]=J&255;this.seqObj=void 0}if(this.leadSurrogate!==-1)A[Q++]=this.defaultCharSingleByte,this.leadSurrogate=-1;return A.slice(0,Q)};xW.prototype.findIdx=qV;function IV(A,Q){this.nodeIdx=0,this.prevBytes=[],this.decodeTables=Q.decodeTables,this.decodeTableSeq=Q.decodeTableSeq,this.defaultCharUnicode=Q.defaultCharUnicode,this.gb18030=Q.gb18030}IV.prototype.write=function(A){var Q=WV.alloc(A.length*2),J=this.nodeIdx,K=this.prevBytes,C=this.prevBytes.length,U=-this.prevBytes.length,Y;for(var Z=0,X=0;Z=0?A[Z]:K[Z+C],Y=this.decodeTables[J][E];if(Y>=0);else if(Y===a8)Y=this.defaultCharUnicode.charCodeAt(0),Z=U;else if(Y===Jl){if(Z>=3)var H=(A[Z-3]-129)*12600+(A[Z-2]-48)*1260+(A[Z-1]-129)*10+(E-48);else var H=(K[Z-3+C]-129)*12600+((Z-2>=0?A[Z-2]:K[Z-2+C])-48)*1260+((Z-1>=0?A[Z-1]:K[Z-1+C])-129)*10+(E-48);var $=qV(this.gb18030.gbChars,H);Y=this.gb18030.uChars[$]+H-this.gb18030.gbChars[$]}else if(Y<=D6){J=D6-Y;continue}else if(Y<=i9){var I=this.decodeTableSeq[i9-Y];for(var N=0;N>8;Y=I[I.length-1]}else throw new Error("iconv-lite internal error: invalid decoding table value "+Y+" at "+J+"/"+E);if(Y>=65536){Y-=65536;var F=55296|Y>>10;Q[X++]=F&255,Q[X++]=F>>8,Y=56320|Y&1023}Q[X++]=Y&255,Q[X++]=Y>>8,J=0,U=Z+1}return this.nodeIdx=J,this.prevBytes=U>=0?Array.prototype.slice.call(A,U):K.slice(U+C).concat(Array.prototype.slice.call(A)),Q.slice(0,X).toString("ucs2")};IV.prototype.end=function(){var A="";while(this.prevBytes.length>0){A+=this.defaultCharUnicode;var Q=this.prevBytes.slice(1);if(this.prevBytes=[],this.nodeIdx=0,Q.length>0)A+=this.write(Q)}return this.prevBytes=[],this.nodeIdx=0,A};function qV(A,Q){if(A[0]>Q)return-1;var J=0,K=A.length;while(J>1);if(A[C]<=Q)J=C;else K=C}return J}});var Cl=B0((us1,N$1)=>{N$1.exports=[["0","\x00",128],["a1","。",62],["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"],["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"],["81b8","∈∋⊆⊇⊂⊃∪∩"],["81c8","∧∨¬⇒⇔∀∃"],["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"],["81f0","ʼn♯♭♪†‡¶"],["81fc","◯"],["824f","0",9],["8260","A",25],["8281","a",25],["829f","ぁ",82],["8340","ァ",62],["8380","ム",22],["839f","Α",16,"Σ",6],["83bf","α",16,"σ",6],["8440","А",5,"ЁЖ",25],["8470","а",5,"ёж",7],["8480","о",17],["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"],["8740","①",19,"Ⅰ",9],["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"],["877e","㍻"],["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"],["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"],["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"],["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"],["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"],["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"],["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"],["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"],["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"],["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"],["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"],["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"],["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"],["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"],["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"],["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"],["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"],["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"],["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"],["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"],["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"],["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"],["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"],["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"],["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"],["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"],["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"],["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"],["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"],["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"],["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"],["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"],["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"],["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"],["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"],["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"],["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"],["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"],["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"],["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"],["eeef","ⅰ",9,"¬¦'""],["f040","",62],["f080","",124],["f140","",62],["f180","",124],["f240","",62],["f280","",124],["f340","",62],["f380","",124],["f440","",62],["f480","",124],["f540","",62],["f580","",124],["f640","",62],["f680","",124],["f740","",62],["f780","",124],["f840","",62],["f880","",124],["f940",""],["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"],["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"],["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"],["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"],["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"]]});var Yl=B0((ms1,L$1)=>{L$1.exports=[["0","\x00",127],["8ea1","。",62],["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"],["a2a1","◆□■△▲▽▼※〒→←↑↓〓"],["a2ba","∈∋⊆⊇⊂⊃∪∩"],["a2ca","∧∨¬⇒⇔∀∃"],["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"],["a2f2","ʼn♯♭♪†‡¶"],["a2fe","◯"],["a3b0","0",9],["a3c1","A",25],["a3e1","a",25],["a4a1","ぁ",82],["a5a1","ァ",85],["a6a1","Α",16,"Σ",6],["a6c1","α",16,"σ",6],["a7a1","А",5,"ЁЖ",25],["a7d1","а",5,"ёж",25],["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"],["ada1","①",19,"Ⅰ",9],["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"],["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"],["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"],["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"],["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"],["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"],["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"],["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"],["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"],["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"],["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"],["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"],["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"],["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"],["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"],["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"],["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"],["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"],["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"],["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"],["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"],["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"],["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"],["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"],["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"],["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"],["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"],["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"],["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"],["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"],["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"],["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"],["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"],["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"],["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"],["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"],["f4a1","堯槇遙瑤凜熙"],["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"],["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"],["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"],["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"],["fcf1","ⅰ",9,"¬¦'""],["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"],["8fa2c2","¡¦¿"],["8fa2eb","ºª©®™¤№"],["8fa6e1","ΆΈΉΊΪ"],["8fa6e7","Ό"],["8fa6e9","ΎΫ"],["8fa6ec","Ώ"],["8fa6f1","άέήίϊΐόςύϋΰώ"],["8fa7c2","Ђ",10,"ЎЏ"],["8fa7f2","ђ",10,"ўџ"],["8fa9a1","ÆĐ"],["8fa9a4","Ħ"],["8fa9a6","IJ"],["8fa9a8","ŁĿ"],["8fa9ab","ŊØŒ"],["8fa9af","ŦÞ"],["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"],["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"],["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"],["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"],["8fabbd","ġĥíìïîǐ"],["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"],["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"],["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"],["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"],["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"],["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"],["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"],["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"],["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"],["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"],["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"],["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"],["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"],["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"],["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"],["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"],["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"],["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"],["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"],["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"],["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"],["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"],["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"],["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"],["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"],["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"],["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"],["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"],["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"],["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"],["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"],["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"],["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"],["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"],["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"],["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5],["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"],["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"],["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"],["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"],["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"],["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"],["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"],["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"],["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"],["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"],["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"],["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"],["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"],["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"],["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"],["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"],["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"],["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"],["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"],["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"],["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"],["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"],["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4],["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"],["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"],["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"],["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"]]});var yW=B0((cs1,F$1)=>{F$1.exports=[["0","\x00",127,"€"],["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"],["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"],["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11],["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"],["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"],["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5],["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"],["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"],["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"],["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"],["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"],["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"],["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4],["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6],["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"],["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7],["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"],["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"],["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"],["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5],["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"],["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6],["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"],["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4],["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4],["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"],["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"],["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6],["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"],["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"],["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"],["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6],["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"],["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"],["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"],["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"],["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"],["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"],["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8],["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"],["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"],["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"],["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"],["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5],["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"],["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"],["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"],["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"],["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5],["9980","檧檨檪檭",114,"欥欦欨",6],["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"],["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"],["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"],["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"],["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"],["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5],["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"],["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"],["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6],["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"],["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"],["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4],["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19],["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"],["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"],["a2a1","ⅰ",9],["a2b1","⒈",19,"⑴",19,"①",9],["a2e5","㈠",9],["a2f1","Ⅰ",11],["a3a1","!"#¥%",88," ̄"],["a4a1","ぁ",82],["a5a1","ァ",85],["a6a1","Α",16,"Σ",6],["a6c1","α",16,"σ",6],["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"],["a6ee","︻︼︷︸︱"],["a6f4","︳︴"],["a7a1","А",5,"ЁЖ",25],["a7d1","а",5,"ёж",25],["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6],["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"],["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"],["a8bd","ńň"],["a8c0","ɡ"],["a8c5","ㄅ",36],["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"],["a959","℡㈱"],["a95c","‐"],["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8],["a980","﹢",4,"﹨﹩﹪﹫"],["a996","〇"],["a9a4","─",75],["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8],["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"],["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4],["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4],["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11],["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"],["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12],["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"],["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"],["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"],["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"],["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"],["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"],["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"],["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"],["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"],["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4],["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"],["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"],["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"],["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9],["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"],["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"],["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"],["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"],["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"],["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16],["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"],["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"],["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"],["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"],["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"],["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"],["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"],["bb40","籃",9,"籎",36,"籵",5,"籾",9],["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"],["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5],["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"],["bd40","紷",54,"絯",7],["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"],["be40","継",12,"綧",6,"綯",42],["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"],["bf40","緻",62],["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"],["c040","繞",35,"纃",23,"纜纝纞"],["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"],["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"],["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"],["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"],["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"],["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"],["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"],["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"],["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"],["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"],["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"],["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"],["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"],["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"],["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"],["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"],["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"],["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"],["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"],["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10],["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"],["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"],["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"],["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"],["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"],["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"],["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"],["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"],["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"],["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9],["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"],["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"],["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"],["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5],["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"],["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"],["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"],["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6],["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"],["d440","訞",31,"訿",8,"詉",21],["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"],["d540","誁",7,"誋",7,"誔",46],["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"],["d640","諤",34,"謈",27],["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"],["d740","譆",31,"譧",4,"譭",25],["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"],["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"],["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"],["d940","貮",62],["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"],["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"],["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"],["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"],["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"],["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7],["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"],["dd40","軥",62],["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"],["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"],["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"],["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"],["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"],["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"],["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"],["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"],["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"],["e240","釦",62],["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"],["e340","鉆",45,"鉵",16],["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"],["e440","銨",5,"銯",24,"鋉",31],["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"],["e540","錊",51,"錿",10],["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"],["e640","鍬",34,"鎐",27],["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"],["e740","鏎",7,"鏗",54],["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"],["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"],["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"],["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42],["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"],["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"],["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"],["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"],["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"],["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7],["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"],["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46],["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"],["ee40","頏",62],["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"],["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4],["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"],["f040","餈",4,"餎餏餑",28,"餯",26],["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"],["f140","馌馎馚",10,"馦馧馩",47],["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"],["f240","駺",62],["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"],["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"],["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"],["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5],["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"],["f540","魼",62],["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"],["f640","鯜",62],["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"],["f740","鰼",62],["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"],["f840","鳣",62],["f880","鴢",32],["f940","鵃",62],["f980","鶂",32],["fa40","鶣",62],["fa80","鷢",32],["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"],["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"],["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6],["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"],["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38],["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"],["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"]]});var OV=B0((ds1,R$1)=>{R$1.exports=[["a140","",62],["a180","",32],["a240","",62],["a280","",32],["a2ab","",5],["a2e3","€"],["a2ef",""],["a2fd",""],["a340","",62],["a380","",31," "],["a440","",62],["a480","",32],["a4f4","",10],["a540","",62],["a580","",32],["a5f7","",7],["a640","",62],["a680","",32],["a6b9","",7],["a6d9","",6],["a6ec",""],["a6f3",""],["a6f6","",8],["a740","",62],["a780","",32],["a7c2","",14],["a7f2","",12],["a896","",10],["a8bc","ḿ"],["a8bf","ǹ"],["a8c1",""],["a8ea","",20],["a958",""],["a95b",""],["a95d",""],["a989","〾⿰",11],["a997","",12],["a9f0","",14],["aaa1","",93],["aba1","",93],["aca1","",93],["ada1","",93],["aea1","",93],["afa1","",93],["d7fa","",4],["f8a1","",93],["f9a1","",93],["faa1","",93],["fba1","",93],["fca1","",93],["fda1","",93],["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"],["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93],["8135f437",""]]});var Ul=B0((ls1,z$1)=>{z$1.exports={uChars:[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],gbChars:[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]}});var Zl=B0((ns1,D$1)=>{D$1.exports=[["0","\x00",127],["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"],["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"],["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"],["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5],["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"],["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18],["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7],["8361","긝",18,"긲긳긵긶긹긻긼"],["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8],["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8],["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18],["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"],["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4],["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"],["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"],["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"],["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10],["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"],["8741","놞",9,"놩",15],["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"],["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4],["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4],["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"],["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"],["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"],["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"],["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15],["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"],["8a61","둧",4,"둭",18,"뒁뒂"],["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"],["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"],["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8],["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18],["8c41","똀",15,"똒똓똕똖똗똙",4],["8c61","똞",6,"똦",5,"똭",6,"똵",5],["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16],["8d41","뛃",16,"뛕",8],["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"],["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"],["8e41","랟랡",6,"랪랮",5,"랶랷랹",8],["8e61","럂",4,"럈럊",19],["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7],["8f41","뢅",7,"뢎",17],["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4],["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5],["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"],["9061","륾",5,"릆릈릋릌릏",15],["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"],["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5],["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5],["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6],["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"],["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4],["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"],["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"],["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8],["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"],["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8],["9461","봞",5,"봥",6,"봭",12],["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24],["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"],["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"],["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14],["9641","뺸",23,"뻒뻓"],["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8],["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44],["9741","뾃",16,"뾕",8],["9761","뾞",17,"뾱",7],["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"],["9841","쁀",16,"쁒",5,"쁙쁚쁛"],["9861","쁝쁞쁟쁡",6,"쁪",15],["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"],["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"],["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"],["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"],["9a41","숤숥숦숧숪숬숮숰숳숵",16],["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"],["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"],["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8],["9b61","쌳",17,"썆",7],["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"],["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5],["9c61","쏿",8,"쐉",6,"쐑",9],["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12],["9d41","쒪",13,"쒹쒺쒻쒽",8],["9d61","쓆",25],["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"],["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"],["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"],["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"],["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"],["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"],["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"],["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"],["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13],["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"],["a141","좥좦좧좩",18,"좾좿죀죁"],["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"],["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"],["a241","줐줒",5,"줙",18],["a261","줭",6,"줵",18],["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"],["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"],["a361","즑",6,"즚즜즞",16],["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"],["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"],["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12],["a481","쨦쨧쨨쨪",28,"ㄱ",93],["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"],["a561","쩫",17,"쩾",5,"쪅쪆"],["a581","쪇",16,"쪙",14,"ⅰ",9],["a5b0","Ⅰ",9],["a5c1","Α",16,"Σ",6],["a5e1","α",16,"σ",6],["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"],["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6],["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7],["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7],["a761","쬪",22,"쭂쭃쭄"],["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"],["a841","쭭",10,"쭺",14],["a861","쮉",18,"쮝",6],["a881","쮤",19,"쮹",11,"ÆÐªĦ"],["a8a6","IJ"],["a8a8","ĿŁØŒºÞŦŊ"],["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"],["a941","쯅",14,"쯕",10],["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18],["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"],["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"],["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"],["aa81","챳챴챶",29,"ぁ",82],["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"],["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5],["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85],["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"],["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4],["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25],["acd1","а",5,"ёж",25],["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7],["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"],["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"],["ae41","췆",5,"췍췎췏췑",16],["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4],["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"],["af41","츬츭츮츯츲츴츶",19],["af61","칊",13,"칚칛칝칞칢",5,"칪칬"],["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"],["b041","캚",5,"캢캦",5,"캮",12],["b061","캻",5,"컂",19],["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"],["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"],["b161","켥",6,"켮켲",5,"켹",11],["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"],["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"],["b261","쾎",18,"쾢",5,"쾩"],["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"],["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"],["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5],["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"],["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5],["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"],["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"],["b541","킕",14,"킦킧킩킪킫킭",5],["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4],["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"],["b641","턅",7,"턎",17],["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"],["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"],["b741","텮",13,"텽",6,"톅톆톇톉톊"],["b761","톋",20,"톢톣톥톦톧"],["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"],["b841","퇐",7,"퇙",17],["b861","퇫",8,"퇵퇶퇷퇹",13],["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"],["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"],["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"],["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"],["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"],["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5],["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"],["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"],["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"],["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"],["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"],["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"],["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"],["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"],["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13],["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"],["be41","퐸",7,"푁푂푃푅",14],["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"],["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"],["bf41","풞",10,"풪",14],["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"],["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"],["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5],["c061","픞",25],["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"],["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"],["c161","햌햍햎햏햑",19,"햦햧"],["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"],["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"],["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"],["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"],["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4],["c361","홢",4,"홨홪",5,"홲홳홵",11],["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"],["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"],["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4],["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"],["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"],["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4],["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"],["c641","힍힎힏힑",6,"힚힜힞",5],["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"],["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"],["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"],["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"],["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"],["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"],["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"],["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"],["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"],["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"],["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"],["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"],["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"],["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"],["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"],["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"],["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"],["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"],["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"],["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"],["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"],["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"],["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"],["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"],["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"],["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"],["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"],["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"],["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"],["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"],["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"],["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"],["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"],["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"],["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"],["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"],["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"],["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"],["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"],["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"],["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"],["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"],["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"],["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"],["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"],["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"],["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"],["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"],["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"],["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"],["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"],["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"],["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"],["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"],["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"]]});var NV=B0((ss1,V$1)=>{V$1.exports=[["0","\x00",127],["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"],["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"],["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"],["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21],["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10],["a3a1","ㄐ",25,"˙ˉˊˇˋ"],["a3e1","€"],["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"],["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"],["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"],["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"],["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"],["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"],["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"],["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"],["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"],["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"],["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"],["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"],["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"],["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"],["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"],["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"],["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"],["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"],["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"],["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"],["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"],["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"],["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"],["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"],["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"],["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"],["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"],["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"],["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"],["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"],["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"],["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"],["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"],["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"],["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"],["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"],["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"],["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"],["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"],["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"],["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"],["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"],["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"],["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"],["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"],["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"],["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"],["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"],["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"],["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"],["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"],["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"],["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"],["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"],["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"],["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"],["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"],["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"],["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"],["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"],["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"],["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"],["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"],["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"],["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"],["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"],["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"],["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"],["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"],["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"],["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"],["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"],["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"],["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"],["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"],["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"],["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"],["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"],["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"],["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"],["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"],["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"],["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"],["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"],["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"],["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"],["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"],["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"],["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"],["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"],["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"],["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"],["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"],["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"],["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"],["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"],["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"],["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"],["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"],["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"],["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"],["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"],["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"],["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"],["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"],["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"],["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"],["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"],["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"],["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"],["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"],["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"],["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"],["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"],["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"],["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"],["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"],["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"],["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"],["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"],["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"],["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"],["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"],["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"],["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"],["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"],["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"],["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"],["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"],["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"],["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"],["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"],["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"],["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"],["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"],["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"],["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"],["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"],["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"],["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"],["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"],["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"],["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"],["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"],["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"],["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"],["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"],["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"],["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"],["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"],["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"],["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"],["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"],["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"],["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"],["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"],["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"],["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"],["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"],["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"],["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"],["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"],["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"],["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"],["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"],["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"],["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"]]});var Bl=B0((os1,M$1)=>{M$1.exports=[["8740","䏰䰲䘃䖦䕸\uD85C\uDE67䵷䖳\uD85F\uDCB1䳢\uD85F\uDCC5㮕䜶䝄䱇䱀\uD850\uDEBF\uD84D\uDE17\uD85C\uDF52\uD85B\uDE8B\uD85C\uDCD2䱗\uD868\uDF51䝏䗚䲅\uD85F\uDC6C䴇䪤䚡\uD85A\uDF23爥\uD856\uDE54\uD846\uDE63\uD84F\uDE06\uD84F\uDF61晍囻"],["8767","綕夝\uD862\uDFB9㷴霴\uD85E\uDFEF寛\uD847\uDD5E媤㘥\uD867\uDEB0嫑宷峼杮薓\uD866\uDD45瑡璝㡵\uD847\uDD53\uD84D\uDE9E\uD858\uDC21㻬"],["87a1","\uD856\uDCDE㫵竼龗\uD850\uDD61\uD862\uDD0D\uD84C\uDDEA\uD842\uDE8A\uD84C\uDE5E䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄\uD857\uDDB9瓆鿇垳䤯呌䄱\uD84D\uDE8E堘穲\uD85E\uDF65讏䚮\uD85B\uDE88䆁\uD857\uDD99箮\uD849\uDCBC鿈\uD849\uDCC1\uD849\uDCC9\uD849\uDCCC鿉蔄\uD84D\uDDBB䂴鿊䓡\uD86B\uDDFF拁灮鿋"],["8840","㇀",4,"\uD840\uDD0C㇅\uD840\uDCD1\uD840\uDCCD㇆㇇\uD840\uDCCB\uD847\uDFE8㇈\uD840\uDCCA㇉㇊㇋㇌\uD840\uDD0E㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"],["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"],["8940","\uD868\uDFA9\uD844\uDD45"],["8943","攊"],["8946","丽滝鵎釟"],["894c","\uD85D\uDF35撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"],["89a1","琑糼緍楆竉刧"],["89ab","醌碸酞肼"],["89b0","贋胶\uD842\uDDE7"],["89b5","肟黇䳍鷉鸌䰾\uD867\uDDF6\uD85C\uDC0E鸊\uD868\uDD33㗁"],["89c1","溚舾甙"],["89c5","䤑马骏龙禇\uD861\uDC6C\uD847\uDDCA\uD841\uDDD0\uD84A\uDEE6两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"],["8a40","\uD85F\uDD84唥"],["8a43","\uD843\uDC42\uD843\uDD15\uD854\uDD2B喐\uD84B\uDCC6㧬\uD840\uDF41蹆\uD853\uDDB8\uD865\uDCE5䁓\uD860\uDCBE睺\uD84B\uDC38㨴䟕\uD860\uDD5D\uD85A\uDDF2\uD853\uDDEA擝\uD843\uDD7C\uD843\uDFB4\uD843\uDCD5\uD844\uDCF4撍蹾\uD843\uDE96\uD843\uDC0B\uD843\uDF64\uD84B\uDCA9\uD860\uDE56\uD851\uDCD3"],["8a64","\uD843\uDD46\uD866\uDE4D\uD860\uDCE9䟴\uD853\uDEA7\uD84B\uDCC2骲㩧\uD865\uDDF4㿭㔆\uD854\uDEC7\uD865\uDFD4\uD85E\uDCC8\uD84B\uDD44鵮頕"],["8a76","䏙\uD858\uDCA5撴哣\uD84B\uDD4C\uD84A\uDFCA\uD844\uDC77㧻\uD844\uDC6F"],["8aa1","\uD859\uDEDA\uD859\uDF16\uD85E\uDDA0擪\uD854\uDC52\uD843\uDC43蹨\uD848\uDDA1\uD862\uDF4C\uD841\uDF31"],["8aac","䠋\uD840\uDDA9㿺塳\uD84B\uDD8D"],["8ab2","\uD851\uDDC8\uD841\uDCFC\uD858\uDC97\uD843\uDF4C\uD843\uDD96啹䂻䎺"],["8abb","䪴\uD84A\uDE66\uD844\uDC9D膪飵\uD843\uDD9C捹㧾\uD849\uDF75跀嚡摼㹃"],["8ac9","\uD869\uDE01\uD843\uDE09\uD84A\uDECF\uD84B\uDCC9"],["8ace","\uD844\uDCC8\uD84E\uDDC2㦒㨆\uD860\uDE9B㕸\uD857\uDE49\uD848\uDCC7噒\uD843\uDF31\uD84B\uDCB2\uD865\uDF20㒼氽\uD853\uDE3B"],["8adf","\uD85D\uDD74\uD84B\uDE8B\uD848\uDE08\uD869\uDE5B\uD863\uDCCD\uD843\uDE7A\uD843\uDC34\uD85A\uDC1C羓\uD844\uDCCF\uD84A\uDC03\uD84A\uDD39㗻\uD854\uDDE3\uD843\uDE8C\uD843\uDF8D\uD843\uDEAA㾓\uD843\uDF30\uD843\uDD47\uD844\uDD4F\uD843\uDE4C"],["8af6","\uD843\uDEAB\uD842\uDFA9\uD843\uDD48\uD844\uDCC0\uD844\uDD3D㿹\uD849\uDE96搲\uD843\uDFAD"],["8b40","\uD84C\uDFF4\uD85D\uDE39\uD84A\uDFCE\uD843\uDD7E\uD843\uDD7F\uD84B\uDC51\uD84B\uDC55㨘\uD843\uDE98\uD844\uDCC7\uD843\uDF2E\uD869\uDE32\uD85A\uDF50\uD863\uDCD2\uD863\uDD99\uD863\uDCCA閪哌苄喹"],["8b55","\uD867\uDEC3鰦骶\uD85D\uDF5E\uD84B\uDDEE煀腭胬尜\uD859\uDD72脴㞗卟\uD860\uDCBD醶\uD843\uDEFA\uD843\uDE0F\uD843\uDE77\uD843\uDEFB㗝\uD853\uDDEB㘉\uD843\uDCD6嚯\uD849\uDFB5\uD844\uDCC9\uD843\uDE10\uD843\uDE78\uD844\uDC78\uD844\uDD48\uD860\uDE07\uD845\uDC55\uD843\uDE79\uD853\uDE50\uD84B\uDDA4婔\uD844\uDC1D\uD844\uDC1E\uD844\uDCF5\uD844\uDCF6垜\uD843\uDE11"],["8ba1","\uD85D\uDE94\uD860\uDECD\uD843\uDFB5\uD843\uDE7B\uD854\uDD7E㜃\uD843\uDFB6\uD844\uDD80\uD854\uDED8\uD868\uDEBD\uD852\uDDDA\uD846\uDC3A\uD850\uDD77\uD860\uDE7C墙剨㘚\uD855\uDF3D箲孨䠀䬬鼧䧧鰟鮍\uD856\uDF74\uD84C\uDD3D嗻㗲嚉丨夂\uD846\uDFC1\uD87E\uDC78靑\uD840\uDC86乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭\uD852\uDCE9罒礻糹罓\uD858\uDE6A㓁"],["8bde","\uD858\uDF4B耂肀\uD859\uDE12\uD85A\uDD51卝衤见\uD85E\uDCB2讠贝钅镸长门\uD863\uDE0F韦页风飞饣\uD866\uDC10鱼鸟黄歯龜丷\uD840\uDC87阝户钢"],["8c40","倻淾\uD867\uDC73龦㷉袏\uD850\uDD4E灷峵䬠\uD854\uDDCD㕙\uD857\uDD30愢\uD862\uDE32辧釶熑朙玺\uD84C\uDE81\uD868\uDD07㲋\uD846\uDD80䬐磤琂冮\uD861\uDF0F䀉橣\uD868\uDEBA䈣蘏\uD842\uDE6F稪\uD866\uDD47\uD862\uDEEA靕灍匤\uD848\uDC7E鏴盙\uD862\uDDE3龧矝亣俰傼丯众龨吴綋墒壐\uD847\uDDB6庒庙忂\uD849\uDF12斋"],["8ca1","\uD84C\uDFF9椙橃\uD84F\uDC63泿"],["8ca7","爀\uD851\uDD05玌㻛\uD852\uDE13嬕璹讃\uD857\uDCA4\uD855\uDE95窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬\uD863\uDDB9\uD845\uDC3F䁱䊢娚"],["8cc9","顨杫䉶圽"],["8cce","藖\uD852\uDD7B芿\uD85C\uDD0D䲁\uD85B\uDD74嵻\uD85A\uDF15\uD85B\uDFBE龭龮宖龯曧繛湗秊㶈䓃\uD84C\uDE56\uD849\uDF96䎚䔶"],["8ce6","峕\uD84E\uDF1A諹屸㴒\uD84D\uDD51嵸龲煗䕘\uD850\uDCEC\uD847\uDE23䱷㥸㑊\uD840\uDDA4\uD85B\uDC41諌侴\uD840\uDE39妿腬顖\uD866\uDCFA弻"],["8d40","\uD842\uDF9F"],["8d42","\uD848\uDDC1\uD862\uDD6D䄂䚻\uD864\uDC79㼇龳\uD868\uDDB5䃸㟖䛷\uD85B\uDC46䅼\uD861\uDEB2\uD85C\uDFFF䕭㣔\uD855\uDC9A䕡䔛䶉䱻䵶䗪㿈\uD852\uDF0F㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"],["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆\uD862\uDDC0溻滢滚齿滨滩漤漴㵆\uD84F\uDF41澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉\uD840\uDF25䏁㗱\uD843\uDED8"],["8e40","\uD84F\uDED7垾\uD85B\uDED3焾\uD855\uDFE0㙎榢\uD862\uDFE9孴穉\uD856\uDCE1\uD865\uDCD9穥穽\uD856\uDDAC窻窰竂竃燑\uD859\uDC8D䇊竚竝竪䇯咲\uD857\uDC01笋筕笩\uD854\uDF0E\uD857\uDCFE箢筯莜\uD856\uDFB4\uD85B\uDC7F篐萡箒箸\uD857\uDD20㶭\uD857\uDC65蒒篺簆簵\uD857\uDCC1籄粃\uD852\uDC82粦晽\uD851\uDD78糉糇糦籴糳糵糎"],["8ea1","繧䔝\uD85B\uDE44絝\uD85B\uDED6璍綉綫焵綳緒\uD850\uDC57\uD858\uDC29緤㴓緵\uD845\uDFF9緥\uD860\uDF6D縝\uD858\uDD21\uD858\uDD5A繮纒䌫鑬縧罀罁罇礶\uD858\uDED0駡羗\uD858\uDF51羣\uD845\uDE61\uD840\uDC68䕜\uD84D\uDF66䔃\uD860\uDF3A翺\uD859\uDC89者耈耝耨耯\uD868\uDC87\uD85B\uDCC3耻耼聡\uD849\uDF14䦉\uD859\uDE26\uD84F\uDDE3\uD859\uDEE8朥肧\uD862\uDE48脇脚墰\uD849\uDEF6汿\uD859\uDC98\uD853\uDFB8擧\uD845\uDC8A舘\uD846\uDC5E橓\uD852\uDE65\uD852\uDE95䑺舩\uD842\uDF0D\uD85A\uDE52\uD84F\uDD7E俹\uD845\uDCFD蓢荢\uD85A\uDF0A\uD852\uDDA7\uD84D\uDD30\uD845\uDF73\uD84F\uDDF8芪椛\uD87E\uDD94䇛"],["8f40","蕋苐茚\uD843\uDE16\uD845\uDFB4㛁\uD84C\uDD7D\uD84D\uDD5A艻苢茘\uD84F\uDE8B\uD85B\uDDA3\uD85A\uDF05\uD85A\uDF97\uD84D\uDDCE㶿茝嗬莅䔋\uD85B\uDDA5莬菁菓㑾\uD85B\uDED4橗蕚㒖\uD85B\uDE42\uD84B\uDEEF葘\uD856\uDFE4葱㷓䓤檧葊\uD84F\uDCB5祘蒨\uD85A\uDF96\uD85B\uDE77\uD85B\uDE43蓞萏莑䒠蒓蓤\uD857\uDC91䉀\uD857\uDCC0䕃蔴嫲\uD85B\uDE99䔧蕳䔖枿蘖"],["8fa1","\uD861\uDE25\uD861\uDE3B藁\uD85C\uDC88蘂\uD845\uDD82\uD85C\uDCCD\uD87E\uDDB2䕪蘨㙈\uD846\uDCA2号\uD85C\uDF9A虾蝱\uD868\uDCF8蟮\uD84B\uDC27螱蟚蠏噡虬桖䘏衅衆\uD85D\uDDE0\uD84F\uDDB9\uD85D\uDDE4衞袜䙛袴袵揁装睷\uD85D\uDF0F覇覊覦覩覧覼\uD862\uDE25觧\uD85E\uDD24\uD85E\uDEBD誜瞓釾誐\uD85E\uDE59竩\uD85E\uDF3A\uD84F\uDF8F䜓\uD85E\uDF38煼謌謟\uD855\uDC30\uD855\uDD65謿譌譍誩\uD852\uDE7A讐讛誯\uD845\uDEDF䘕衏貛\uD85F\uDD54\uD85F\uDD8F\uD87E\uDDD4㜥\uD85F\uDD53賖\uD85F\uDD98\uD85F\uDDBD贒贃\uD846\uDD10賛灜贑\uD853\uDCC9㻐起"],["9040","趩\uD860\uDC02\uD844\uDC14\uD852\uDD8A㭼\uD860\uDDBC\uD85C\uDD0C竧躭躶軃鋔輙輭\uD860\uDF65\uD861\uDC12辥錃\uD868\uDE9F\uD842\uDE50辳䤪\uD862\uDDDE\uD861\uDD3D\uD84F\uDDBB廸\uD84C\uDE62迹\uD868\uDC14\uD861\uDEBC\uD861\uDD01\uD848\uDF25㦀\uD85B\uDED7逷\uD861\uDD3C\uD85E\uDEBE遡\uD861\uDD6C\uD861\uDE0B邨\uD861\uDF13郄\uD861\uDEE6邮都酧㫰醩釄粬\uD862\uDD33\uD847\uDE89鈎沟鉁鉢\uD855\uDDB9銹\uD862\uDEC6\uD84F\uDC9B\uD862\uDF0C\uD855\uDDDB"],["90a1","\uD843\uDD31錬鍫\uD862\uDEE1\uD862\uDFEB炏嫃\uD862\uDEE2\uD862\uDEE5䥥鉄\uD862\uDFEC\uD863\uDC39\uD862\uDFFF鍳鑛躼閅閦鐦閠濶䊹\uD849\uDE7A\uD861\uDED8\uD844\uDE7C\uD84F\uDE2E䧟氜陻隖䅬隣\uD85B\uDED5懚隶磵\uD862\uDEE0隽双䦡\uD85B\uDCB8\uD840\uDE74\uD859\uDC10\uD864\uDCAF\uD864\uDCE5\uD852\uDED1\uD846\uDD15\uD84C\uDF0A霱虂霶䨏䔽䖅\uD852\uDEE9灵孁霛靜\uD864\uDDD5靗孊\uD864\uDDEB靟鐥僐\uD84C\uDCB7\uD84C\uDCBC鞉鞟鞱鞾韀韒韠\uD855\uDC6C韮琜\uD865\uDC33響韵\uD865\uDC1D\uD85E\uDD7A䫑頴頳顋顦㬎\uD85C\uDD75㵑\uD841\uDE30\uD850\uDD5C"],["9140","\uD855\uDF06飊颷飈飇䫿\uD85B\uDD27\uD845\uDED3喰飡飦飬鍸餹\uD852\uDE29䭲\uD866\uDC57\uD866\uDD05駵騌騻騐驘\uD855\uDF25㛄\uD864\uDCB1\uD866\uDFD5髠髢\uD866\uDF05髴䰎鬔鬭\uD861\uDE00倴鬴\uD85A\uDDA8㣃\uD84C\uDC7D魐魀\uD867\uDD3E婅\uD846\uDC63鮎\uD850\uDE4B鰂鯿鰌\uD867\uDE68鷔\uD867\uDFB7\uD868\uDD92\uD868\uDDAB\uD868\uDCE1\uD868\uDD23\uD868\uDDDF鵾鶃\uD868\uDD34鸎梈"],["91a1","鷄\uD848\uDD5B\uD868\uDD93\uD868\uDE20\uD846\uDD3B\uD868\uDE33鴹\uD868\uDCB9\uD868\uDEB4麐麕麞麢䴴麪麯\uD850\uDF64黁㭠㧥㴝伲㞾\uD863\uDC2B鼂鼈䮖鐤\uD85B\uDDA2鼗鼖鼹嚟嚊齅馸\uD864\uDC8B韲葿齢齩竜龎爖䮾\uD852\uDD75\uD852\uDDBB煷\uD852\uDDF8\uD850\uDF48\uD852\uDE51玞\uD862\uDFDA\uD846\uDCFA禟\uD862\uDD7E\uD863\uDE36鍩鏳\uD862\uDE44鋬鎁鏋\uD862\uDD6C\uD851\uDCB9爗㻫睲穃烐\uD851\uDC73\uD850\uDFF8煾\uD845\uDFEF炣\uD846\uDCBE\uD84D\uDD99㻇\uD846\uDC85\uD855\uDC2F\uD845\uDFF8㜢\uD845\uDEFB\uD846\uDC39㛡\uD845\uDF74\uD846\uDCD1\uD857\uDF4B㜣\uD845\uDEC0坛\uD852\uDE25\uD844\uDFFE\uD844\uDEA8"],["9240","\uD844\uDFC6\uD845\uDCB6蔃\uD84D\uDEA6蔃葕\uD852\uDD94\uD85C\uDD65\uD84F\uDE31\uD855\uDD5C\uD84F\uDEFB\uD85C\uDC52䓴\uD84D\uDEEE\uD866\uDD9D\uD85B\uDF26柹㜳㰕㷧塬\uD846\uDD22栐䁗\uD84D\uDF3F\uD850\uDCE1\uD850\uDC8B\uD850\uDD0F\uD85B\uDC21哋嚞\uD859\uDEB1嚒\uD843\uDFDF\uD842\uDFA8\uD843\uDE0D鏆\uD862\uDF13鎜仸儫㠙\uD851\uDC36亼\uD841\uDC65\uD840\uDF7F佋侊\uD855\uDE51婨\uD840\uDDAB\uD840\uDFCB㦙\uD840\uDF0A\uD841\uDC14㐵伩\uD840\uDEC0\uD863\uDEB3\uD840\uDE75諚\uD840\uDE0C亘"],["92a1","働儍侢伃\uD852\uDE0E\uD84F\uDE8A佂倮偬傁俌俥偘僼兙兛兝兞湶\uD84D\uDD95\uD84F\uDE39\uD84F\uDEBF浲\uD846\uDC84\uD84F\uDE89冨凃\uD841\uDDE0䓝\uD841\uDCA3\uD841\uDC92\uD841\uDC91赺\uD862\uDE9C\uD841\uDF0E剙劤\uD842\uDC73勡鍮䙺熌\uD850\uDF8C\uD843\uDC20\uD852\uDDAC\uD844\uDCE4槑\uD843\uDE1D瑹㻞璙琔瑖玘䮎\uD852\uDEBC\uD850\uDC8D叐㖄爏\uD850\uDCC9喴\uD840\uDF45响\uD842\uDFC6圝鉝雴鍦埝垍坿㘾壋媙\uD862\uDE46\uD845\uDEFA\uD845\uDF6F\uD845\uDF10娬妸銏婾嫏娒\uD856\uDD46\uD846\uDDF3\uD846\uDC61\uD850\uDE95㛵洅瑃娡\uD857\uDE83"],["9340","媁\uD862\uDFD7\uD841\uDC13鏠璌\uD844\uDF03焅䥲鐈\uD862\uDDFB鎽㞠尞岞幞幈\uD846\uDD96\uD846\uDD7C\uD84E\uDEEE廍孏\uD846\uDD03\uD846\uDD04㜁\uD846\uDCA0㛝\uD845\uDEFE㛓脪\uD862\uDE47\uD847\uDDBA\uD84D\uDC72\uD862\uDDA8弌弎\uD846\uDD27\uD845\uDFAB婫\uD845\uDF3B孄蘔\uD85D\uDDFD衠恾\uD84A\uDC60\uD849\uDE2B忛㺸\uD849\uDDAF\uD849\uDDBE\uD864\uDC88\uD85B\uDF73懀\uD840\uDC3E\uD840\uDC46\uD849\uDE1B憙憘恵\uD84B\uDC9B\uD84B\uDD07\uD851\uDED4\uD864\uDD4D"],["93a1","摱\uD851\uDE65\uD84A\uDF6A㨩\uD84A\uDF22\uD84D\uDC50\uD866\uDCEA\uD84B\uDE78挷\uD869\uDC5B撶挱揑\uD852\uDDE3\uD84B\uDD67护\uD84B\uDCA1搻敫楲㯴\uD84C\uDC8E\uD84C\uDEAD\uD852\uDD89\uD84C\uDEAB唍\uD84C\uDEE0\uD846\uDCD9\uD865\uDC3F曎\uD84C\uDE89\uD84C\uDDB3㫠䆐\uD855\uDD84\uD862\uDF22\uD855\uDD8F\uD845\uDEFC\uD855\uDD5B\uD855\uDC25磮\uD84C\uDD03\uD846\uDC2A\uD84C\uDE34㑤\uD84C\uDE0F\uD84C\uDD82\uD850\uDEC9暎\uD85B\uDD24晫䮓昰\uD85E\uDC70\uD847\uDDEB晣\uD84C\uDED2\uD84C\uDEE1昞\uD856\uDC72㣑\uD84E\uDC3A\uD84D\uDFBC㮙\uD84D\uDFA2\uD84C\uDFFE瓐㮖枏\uD851\uDE2A梶栞㯄檾㡣\uD84D\uDFD5\uD851\uDC87樳橒櫉欅\uD846\uDD12攑梘橌㯗橺歗\uD84F\uDFC0\uD84F\uDC9A鎠鋲\uD862\uDFEA\uD862\uDECB"],["9440","銉\uD860\uDC1E\uD862\uDDDC鑧涥漋\uD852\uDDEC浧\uD84F\uDF7F㶏渄\uD850\uDC3C娽渊塇洤硂焻\uD850\uDF1A\uD850\uDE76烱牐犇犔\uD851\uDF8F\uD851\uDF25兹\uD852\uDEA4\uD841\uDDEB瑺\uD84F\uDEF8\uD84D\uDE5F\uD852\uDE4A\uD852\uDD17\uD857\uDFE1㼆㺱\uD852\uDEDF\uD863\uDC23\uD84F\uDF35悧㻳瓌琼鎇琷䒟\uD85B\uDDEA䕑疃㽣\uD853\uDCD9\uD853\uDD06㽘畕癳\uD869\uDDC6㬙瑨\uD862\uDECC\uD852\uDDAB\uD852\uDD8E㫻"],["94a1","㷍\uD852\uDE4E㻿\uD852\uDDC5\uD852\uDCF3釺圲鍂\uD862\uDEE3\uD846\uDC64僟\uD854\uDE21\uD854\uDDE7睸\uD84C\uDE32眎眏睻\uD851\uDE97\uD84D\uDF81㩞\uD852\uDCF0琸璛㺿\uD852\uDEBA\uD852\uDEC7䃈\uD852\uDE96\uD858\uDDAE錇\uD855\uDD81砞碍碈磒珐祙\uD85D\uDF41\uD855\uDEE3䄎禛蒖禥樭\uD84F\uDEFA稺秴䅮\uD845\uDEE6䄲鈵秱\uD843\uDD4C\uD852\uDD8C\uD840\uDE99\uD84F\uDDBA\uD845\uDF6E㖗啫㕰㚪\uD840\uDDD4\uD843\uDC0D竢婙\uD849\uDEF5\uD856\uDEAF\uD856\uDE9C娍\uD840\uDE5B磰娪\uD856\uDFC6竾䇹籝籭䈑\uD856\uDFB3\uD857\uDEBC\uD857\uDEA6糍\uD852\uDDF9\uD845\uDFB0粎籼粮檲緜縇緓罎\uD858\uDE61"],["9540","\uD858\uDD5C\uD85E\uDF48綗\uD857\uDE82䉪\uD85A\uDF75\uD842\uDD16柖\uD840\uDC4E\uD84D\uDDCF埄\uD859\uDC12\uD858\uDFF8\uD852\uDD62翝笧\uD842\uDC2C\uD856\uDEE9\uD857\uDD43笌\uD857\uDE0E駦虅驣樜\uD84D\uDC3F㧢\uD852\uDDF7\uD859\uDDAD騟\uD859\uDDA0蒀\uD85C\uDD27\uD85B\uDCD1䓪脷䐂胆脉腂\uD859\uDFB4飃\uD85A\uDE42艢艥\uD85A\uDE51葓\uD85B\uDDA7蘐\uD85C\uDE1B媆䅿\uD846\uDC40嬫\uD846\uDCA1嫤\uD846\uDCD8蚠\uD87E\uDDBC\uD84F\uDD8F蠭\uD85D\uDC22娂"],["95a1","衮佅袇袿裦襥襍\uD855\uDE83襔\uD85D\uDF85\uD85D\uDF84\uD862\uDFF5\uD862\uDFD9\uD862\uDF9C\uD862\uDDF9㺭蒣䛵䛏㟲訽訜\uD865\uDC48彍鈫\uD850\uDE84旔焩烄\uD846\uDC45鵭貟賩\uD85F\uDDDC妚矃姰䍮㛔踪躧\uD853\uDC09輰轊䋴汘澻\uD848\uDF21䢛潹溋\uD845\uDFDA鯩㚵\uD852\uDD2F邻邗啱䤆醻鐄\uD862\uDE4B䁢\uD862\uDEFC鐧\uD863\uDC1D\uD863\uDC3B蓥訫閙閧閗閖\uD863\uDD34瑅㻂\uD852\uDCFF\uD852\uDE42\uD850\uDFEA㻧\uD84C\uDE25随\uD863\uDEE7\uD863\uDE66\uD863\uDE65㻌\uD852\uDDED\uD852\uDE78\uD84F\uDFEE琒瑫㻼靁\uD864\uDCB0"],["9640","桇䨝\uD864\uDC93\uD855\uDFDF靝鍨\uD862\uDD89\uD863\uDC26\uD862\uDF2F\uD858\uDFBE銺嬑譩䤼珹\uD850\uDE1B鞛靱餸\uD843\uDF26巁\uD862\uDFC5\uD852\uDEB2頟\uD865\uDCDA鋶\uD865\uDDD7釥䓀\uD862\uDF50\uD852\uDE67\uD862\uDF64飜\uD862\uDE45㼀鈪䤥萔餻饍\uD85E\uDF06㷽馛䭯馪驜\uD862\uDF65\uD856\uDCC8檏騡嫾騯\uD866\uDCF1䮐\uD866\uDD48馼䮽䮗鍽塲\uD844\uDF02堢\uD852\uDDB8"],["96a1","\uD845\uDCE8硄\uD849\uDF1F\uD84F\uDDB8棅㵽鑘㤧慐\uD849\uDF81\uD84A\uDD6B愇鱏鱓鱻鰵鰐魿鯏\uD867\uDE2D鮟\uD868\uDDF5\uD868\uDCFE鴡䲮\uD850\uDD04鸘䲰鴌\uD868\uDDB4\uD868\uDCED\uD868\uDCF3\uD866\uDD2F鶥蒽\uD85B\uDE12\uD85B\uDFDF\uD85A\uDF82藼䔳\uD85B\uDDA4\uD85B\uDE84\uD85B\uDDF0萠藮\uD85B\uDE00\uD84D\uDFD7\uD858\uDC64秢\uD84D\uDD9C\uD84D\uDE40䤭\uD852\uDDDE㵢鏛銾鍈\uD840\uDEBF碹鉷鑍俤㑀遤\uD855\uDD5D砽硔碶硋\uD845\uDF57\uD84C\uDDC9\uD852\uDD41㚚佲濚濙瀞瀞吔\uD850\uDDB5垻壳垊鴖埗焴㒯\uD850\uDDAC燫\uD85B\uDC40\uD853\uDF97嬨\uD845\uDFB5\uD862\uDE49"],["9740","愌嫎娋䊼\uD851\uDC88㜬䭻\uD862\uDDFC鎻鎸\uD846\uDCD6\uD843\uDF1D葲\uD85B\uDCC0\uD845\uDC13\uD850\uDEFA\uD84B\uDC26\uD850\uDFC1妔\uD84F\uDDB7\uD859\uDF41綨\uD858\uDD5B\uD858\uDCA4\uD852\uDDB9\uD852\uDD8B\uD862\uDDFA鋥珢㻩璴\uD862\uDF63\uD846\uDC9F㻡\uD852\uDEB3櫘珳珻㻖\uD852\uDE3E\uD852\uDE94\uD845\uDFD9\uD852\uDE66\uD840\uDFA7\uD845\uDC24\uD852\uDDE5瑈\uD852\uDD16炥\uD852\uDD76銄珦鍟\uD841\uDCFE錱\uD862\uDECE\uD862\uDE16鎆\uD862\uDFE7\uD855\uDDD5䤵\uD862\uDE82煫"],["97a1","\uD852\uDD43\uD843\uDCFF嚤\uD841\uDE1A\uD842\uDFEB\uD843\uDCB8唂秄\uD845\uDFFA緾\uD845\uDEC2\uD852\uDE50\uD846\uDC52䔮鐁㜊\uD862\uDEC0\uD852\uDDAD妰\uD846\uDCBF\uD846\uDC83\uD85D\uDC84媡㛢\uD84F\uDD5B㚰鉟婹\uD862\uDE81\uD846\uDC62鍴㳍\uD842\uDEB4䪖㦊僴㵩㵌\uD844\uDF9C煵䋻\uD860\uDE18渏\uD864\uDCE4䓫浗\uD85F\uDE4F灧沯㳖\uD84F\uDFED\uD84F\uDE2D渂漌㵯\uD840\uDFF5畑㚼㓈䚀㻚䡱姄鉮䤾轁\uD863\uDC1C\uD85A\uDFC0堒埈㛖\uD845\uDC52烾\uD850\uDF62\uD852\uDE71\uD84B\uDFE3\uD844\uDEB0\uD848\uDFBD梹楧\uD844\uDF98\uD84D\uDCE5\uD85E\uDFF4\uD84D\uDEDF\uD862\uDE83\uD84D\uDFD6\uD84C\uDFFA\uD853\uDC9F樚\uD84D\uDEAD\uD85B\uDCB7萾䓟䓎"],["9840","\uD85B\uDD26\uD85B\uDD51\uD85B\uDC82\uD85B\uDFDE漗\uD85C\uDD09茽\uD845\uDF3A菭\uD85B\uDC80\uD85C\uDC53\uD845\uDFDB妉媂\uD845\uDFB3婡婱\uD846\uDD05\uD850\uDDFC㜭姯\uD845\uDF3C㛇熎鎐暚\uD850\uDEA5婮娫\uD850\uDE93樫\uD84F\uDEF9\uD85D\uDF36\uD851\uDC5B\uD850\uDECA焝\uD850\uDE59\uD862\uDDE1侰\uD85B\uDD28峂\uD851\uDCCE\uD85F\uDE4D\uD850\uDFBD樌\uD850\uDE56\uD844\uDF04炦焳\uD850\uDFE9㶥泟\uD87E\uDC25\uD852\uDE4F繥姫崯㷳彜\uD852\uDE5D\uD845\uDFDF綤萦"],["98a1","咅\uD84E\uDEFA\uD84C\uDF00\uD840\uDE14坾\uD842\uDCD5\uD841\uDE19㿥\uD847\uDF9E\uD868\uDEB6瀃\uD864\uDD5B嵰玏糓\uD862\uDE59\uD865\uDC20俈翧狍猐\uD85E\uDEF4猸猹\uD855\uDEF6獁獈㺩\uD85E\uDF18遬燵\uD852\uDCF2珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発\uD853\uDF5C熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈\uD855\uDD35礳栃礲䄃"],["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀\uD843\uDCCF総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"],["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑\uD85E\uDD67訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"],["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯\uD846\uDFC2鵉鰺"],["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄\uD840\uDC94\uD840\uDEB7\uD840\uDFA0椚铃妬\uD841\uDCD7塀铁㞹\uD841\uDDD5\uD841\uDE15\uD841\uDE76\uD845\uDEBA块煳\uD842\uDEC2\uD842\uDECD\uD842\uDFBF呪\uD87E\uDC3B\uD842\uDFCB咞\uD842\uDFFB\uD843\uDC3B\uD843\uDC53\uD843\uDC65\uD843\uDC7C惧\uD843\uDC8D噺\uD843\uDCB5\uD843\uDCDD\uD843\uDCED\uD843\uDD6F\uD843\uDDB2\uD843\uDDC8楕鰯螥\uD843\uDE04\uD843\uDE0E\uD843\uDED7\uD843\uDF90\uD843\uDF2D\uD843\uDE73尠\uD843\uDFBC帋\uD844\uDC5C\uD844\uDC4F\uD844\uDC76朞\uD844\uDC7B\uD844\uDC88\uD844\uDC96㙇\uD844\uDCBF\uD844\uDCD3\uD844\uDD2F\uD844\uDD3B卤蒭\uD844\uDEE3\uD844\uDF75\uD844\uDF36讁\uD845\uDD77\uD845\uDE19\uD845\uDFC3\uD845\uDFC7乸炻\uD846\uDC2D\uD846\uDD6A"],["9b40","\uD846\uDE2D\uD846\uDE45\uD847\uDC2A\uD847\uDC70\uD847\uDCAC\uD847\uDEC8拃\uD847\uDED5\uD847\uDF15熘桕\uD848\uDC45槩㛈\uD848\uDE7C\uD848\uDFD7\uD848\uDFFA\uD849\uDF2A\uD84A\uDC71\uD84A\uDD4F苽\uD84A\uDD67\uD84A\uDD93\uD84A\uDED5覥\uD84A\uDEE8辠\uD84A\uDF0E鞸\uD84A\uDF3F顇骽\uD84B\uDC4C"],["9b62","\uD84B\uDC88\uD84B\uDCB7\uD856\uDFE8\uD84B\uDD08\uD84B\uDD12\uD84B\uDDB7\uD84B\uDD95\uD84B\uDE42\uD84B\uDF74\uD84B\uDFCC\uD84C\uDC33\uD84C\uDC66\uD84C\uDF1F\uD84C\uDFDE徱晈暿\uD85E\uDE79\uD84D\uDD67\uD84D\uDDF3爁\uD852\uDDBA矗\uD84D\uDE1A\uD84D\uDF16纇\uD840\uDF46墵朎"],["9ba1","椘\uD84E\uDEA7\uD85D\uDE57\uD857\uDFE2\uD84F\uDE11\uD84F\uDEB9\uD85D\uDDFE\uD848\uDC9A䣐䪸\uD850\uDD19\uD862\uDE9A\uD850\uDEEE\uD850\uDF0D\uD850\uDC3B\uD850\uDF34\uD850\uDF96\uD852\uDE45\uD841\uDDCA凒\uD841\uDE11妟\uD847\uDEA8㮾\uD84F\uDCFF\uD851\uDC04\uD851\uDCD6垈\uD851\uDE74㦛\uD851\uDF2F\uD861\uDDE8\uD866\uDDC9㝢\uD848\uDDC3譞\uD862\uDF4E駖\uD852\uDC12\uD852\uDCFB\uD852\uDE15爉\uD852\uDEC0\uD843\uDC78奥\uD853\uDEA5\uD853\uDF86\uD841\uDF79軚\uD854\uDC2C劏圿煱\uD854\uDE99\uD855\uDC19\uD84F\uDF4A\uD852\uDEA7喼\uD855\uDC46\uD855\uDC6E\uD85A\uDF52釔㑳\uD855\uDD3F\uD85D\uDE32\uD855\uDD5E䜘\uD855\uDD62\uD855\uDD66\uD855\uDFC7\uD852\uDD3F\uD856\uDC5D偦㓻\uD84C\uDFCC惞\uD856\uDD03䝼\uD862\uDD48\uD856\uDEAE\uD856\uDF89\uD857\uDC06\uD847\uDD90垡煑澶\uD858\uDD02\uD85F\uDC12遖\uD858\uDDB2\uD853\uDF9A譢\uD859\uDC02\uD859\uDC4A"],["9c40","嵛\uD85A\uDFF7輶\uD859\uDC84\uD846\uDD1C諪\uD852\uDDF6\uD859\uDC88\uD84F\uDFEF\uD859\uDD12䯀\uD859\uDDBF\uD859\uDEB5\uD849\uDF1B鑥\uD855\uDFE1憕娧\uD87E\uDCCD侻嚹\uD851\uDD21\uD859\uDEFC乪\uD852\uDD34陖涏\uD85B\uDCBD㘘襷\uD859\uDF99\uD85A\uDC6E\uD859\uDC11\uD85A\uDC5E營\uD85A\uDCC7筂\uD864\uDCC0\uD842\uDE11\uD85A\uDD26鄄\uD85A\uDD39穅鷰\uD85A\uDDFA騦\uD85A\uDE2D㙟\uD859\uDC69\uD840\uDC21禃\uD85A\uDE34\uD85A\uDF5B崬\uD84D\uDD19菏\uD85A\uDF9D䛐\uD85B\uDCA4画补\uD85B\uDDAE墶"],["9ca1","㜜\uD849\uDD8D\uD85C\uDC4B\uD85C\uDDCD㱔\uD85C\uDE80\uD85C\uDE85銁\uD848\uDD7A\uD85C\uDE8B錰\uD85C\uDEE6\uD852\uDDD0氹钟\uD85D\uDC50\uD843\uDEF8蠧裵\uD84A\uDD26\uD861\uDC73\uD845\uDFB1溸\uD852\uDE2A\uD846\uDC20㦤㚹尐秣䔿暶\uD867\uDCAD\uD866\uDCA4襃\uD85D\uDFCC\uD85E\uDC58囖䃟\uD845\uDE0A㦡\uD84D\uDF2F\uD860\uDCE8\uD844\uDFC5熭荦\uD85E\uDDDD\uD864\uDDA8婧䲷\uD85C\uDCAF\uD862\uDDAB\uD85E\uDDFD\uD85E\uDE0A\uD85E\uDF0B\uD85F\uDD66\uD850\uDD7A筃祾\uD860\uDC09澵\uD868\uDEDF樃\uD860\uDF18厢\uD85B\uDE07鎿栶靝\uD860\uDD6F\uD860\uDC23\uD85A\uDDB5\uD844\uDFED\uD84C\uDE2F\uD860\uDC48嶅\uD863\uDC30\uD860\uDC83圕頣\uD862\uDD49嶫\uD852\uDD88斾槕叒\uD852\uDEA5\uD84F\uDF81㰑朶\uD860\uDC90\uD860\uDCF4\uD860\uDD2E\uD847\uDFA1\uD860\uDD4F"],["9d40","\uD860\uDD89\uD860\uDDAF\uD860\uDE1A\uD860\uDF06\uD860\uDF2F\uD860\uDF8A㗊\uD861\uDC68\uD861\uDEAA䣺揦\uD862\uDD56砈鉕\uD862\uDDB8䏲\uD862\uDDE7䏟\uD862\uDDE8\uD862\uDF46\uD862\uDFD4姸\uD863\uDC09輋\uD863\uDFC5\uD864\uDCEC筑\uD864\uDD10\uD864\uDD3C㷷\uD864\uDD5E\uD852\uDECA运犏嚋\uD865\uDCE7\uD865\uDDE9\uD865\uDDB0\uD865\uDDB8\uD865\uDF32\uD866\uDCD1\uD866\uDD49\uD866\uDD6A\uD866\uDDC3\uD866\uDE28\uD866\uDF0E\uD867\uDD5A\uD867\uDD9B纟\uD867\uDEF8\uD867\uDF23䲤镇\uD868\uDE93熢\uD868\uDEFF䶑递\uD869\uDDCB䶜\uD843\uDC9C达嗁"],["9da1","辺\uD849\uDCB0边\uD852\uDE93䔉繿潖檱仪㓤\uD862\uDF2C\uD85E\uDC9D㜺躀\uD845\uDFF5\uD860\uDC24\uD862\uDF6C\uD862\uDF99\uD85E\uDE3E\uD859\uDEAF㷫\uD85D\uDE55\uD84F\uDCB7\uD855\uDE35\uD856\uDD56亚\uD857\uDE81\uD858\uDE58嚿\uD843\uDE6D踎孭\uD84F\uDE88\uD853\uDC9E揞拐\uD845\uDFF6\uD846\uDC7B攰嘭\uD857\uDC4A吚\uD854\uDF11㷆\uD867\uDD98䱽嘢嘞罉\uD857\uDED8奵\uD84F\uDD40蝰东\uD843\uDFEA\uD843\uDD49\uD84D\uDEBA脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖\uD843\uDE9D㗎嘅嗱曱\uD860\uDEE2㘭甴嗰喺咗啲\uD843\uDC41\uD843\uDC96廐\uD854\uDD48\uD843\uDE76\uD84B\uDC62"],["9e40","\uD843\uDEA2麫絚嗞\uD844\uDC75抝靭咔賍燶酶揼掹揾啩\uD84A\uDF43鱲\uD84B\uDEB3冚㓟\uD843\uDDA7冧呍唞唓癦踭\uD85A\uDC8A疱肶蠄螆裇膶萜\uD844\uDCC1䓬猄\uD851\uDF06宐茋\uD85A\uDC93噻\uD849\uDEF4\uD85F\uDD2F\uD850\uDDA3\uD85F\uDD73\uD85B\uDED0\uD85C\uDEB6酰\uD844\uDDD9鈈\uD84F\uDCFC\uD869\uDEA9\uD843\uDEAC\uD843\uDEF9牦\uD847\uDCA2䝎\uD853\uDFC2\uD85F\uDFF9\uD843\uDFEB䃺"],["9ea1","鱝攟\uD84B\uDDA0䣳\uD851\uDFE0\uD867\uDD7C\uD843\uDFEC\uD843\uDE0A恢\uD85D\uDDA3\uD843\uDFED"],["9ead","\uD858\uDC48\uD844\uDD87熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥\uD851\uDE18墚\uD852\uDF6E舭呋垪\uD856\uDE95\uD842\uDD79"],["9ec5","㩒\uD849\uDC65獴\uD867\uDEAC䴉鯭\uD84F\uDCFE\uD867\uDF30䱛\uD853\uDFA9\uD865\uDD9E\uD867\uDFDE葜\uD84F\uDDB6\uD85C\uDEB2\uD859\uDFB3\uD84D\uDF20挮紥\uD84F\uDEF7\uD84F\uDE2C㨪逈勌㹴㙺䗩\uD841\uDC8E癀嫰\uD843\uDEB6硺\uD85F\uDF2E墧䂿噼鮋嵴癔\uD869\uDC34麅䳡痹㟻愙\uD84C\uDCDA\uD850\uDFF2"],["9ef5","噝\uD844\uDEA9垧\uD852\uDD63\uD867\uDE06刴\uD85C\uDCAE㖭汊鵼"],["9f40","籖鬹埞\uD845\uDF6C屓擓\uD865\uDCD0\uD858\uDF35\uD85C\uDD64蚭\uD843\uDD28\uD85B\uDD22\uD852\uDEE2\uD843\uDD71"],["9f4f","凾\uD847\uDF0F嶎霃\uD847\uDDD1麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛\uD852\uDD3E齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"],["9fa1","椬叚鰊鴂䰻陁榀傦畆\uD845\uDF6D駚剳"],["9fae","酙隁酜"],["9fb2","酑\uD863\uDE97捿\uD85B\uDD23櫊嘑醎畺抅\uD840\uDFFC獏籰\uD857\uDC21\uD84F\uDCFD"],["9fc1","\uD852\uDD19盖鮝个\uD843\uDCD4莾衂"],["9fc9","届槀僭坺刟巵从氱\uD840\uDDF2伹咜哚劚趂㗾弌㗳"],["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"],["9fe7","毺蠘罸"],["9feb","嘠\uD869\uDE4A蹷齓"],["9ff0","跔蹏鸜踁抂\uD860\uDF7D踨蹵竓\uD852\uDE77稾磘泪詧瘇"],["a040","\uD862\uDE5A鼦泎蟖痃\uD868\uDEB2硓\uD87E\uDC40贌狢獱謭猂瓱賫\uD852\uDEBB蘯徺袠䒷"],["a055","\uD846\uDC3B\uD85B\uDE05"],["a058","詾\uD849\uDD1B"],["a05b","惽癧髗鵄鍮鮏蟵"],["a063","蠏賷猬霡鮰㗖犲䰇籑饊\uD858\uDD59慙䰄麖慽"],["a073","坟慯抦戹拎㩜懢厪\uD84C\uDFF5捤栂㗒"],["a0a1","嵗\uD862\uDFC2迚\uD863\uDE39"],["a0a6","僙\uD847\uDD46礆匲阸\uD843\uDF3B䁥"],["a0ae","矾"],["a0b0","糂\uD857\uDF1A糚稭聦聣絍甅瓲覔舚朌聢\uD85D\uDC86聛瓰脃眤覉\uD859\uDFCC畓\uD85B\uDED1螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"],["a0d4","覩瑨涹蟁\uD850\uDC11瓧㷛煶悤憜㳑煢恷"],["a0e2","罱\uD862\uDF2D牐惩䭾删㰘\uD84F\uDCC7\uD857\uDED7\uD85D\uDE56\uD855\uDD31\uD846\uDD44\uD844\uDEFE\uD866\uDD03\uD85B\uDDDC\uD85C\uDCAD峁\uD858\uDDAD\uD862\uDE0F\uD84D\uDE77\uD840\uDCEE\uD85A\uDC46\uD853\uDF0E䕢嬟\uD858\uDF4C齐麦\uD858\uDE6B"],["a3c0","␀",31,"␡"],["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23],["c740","す",58,"ァアィイ"],["c7a1","ゥ",81,"А",5,"ЁЖ",4],["c840","Л",26,"ёж",25,"⇧↸↹㇏\uD840\uDCCC乚\uD840\uDC8A刂䒑"],["c8a1","龰冈龱\uD85D\uDE07"],["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"],["c8f5","ʃɐɛɔɵœøŋʊɪ"],["f9fe","■"],["fa40","\uD841\uDD47鋛\uD841\uDDDF\uD84F\uDFC5蕌䊵珯况㙉\uD852\uDD42\uD862\uDDE4鍄\uD846\uDDDB苮\uD84F\uDCC8砼杄拟\uD852\uDD33\uD862\uDDAA\uD840\uDEA0\uD85A\uDFB3\uD844\uDF05侫\uD849\uDCED倈\uD85B\uDD29\uD85E\uDE84\uD84D\uDE00\uD852\uDEB1\uD849\uDD13倩\uD840\uDF7E徤\uD840\uDF80\uD840\uDF47滛\uD841\uDC1F偽儁㑺儎顬㝃萖\uD852\uDDA4\uD841\uDC87兠\uD84C\uDFB4兪\uD842\uDFFF\uD848\uDCFC\uD840\uDEE5\uD849\uDD30\uD841\uDD8E\uD84C\uDE33\uD846\uDD83宂蝽\uD841\uDDB3\uD84F\uDC99冲冸"],["faa1","鴴凉减凑㳜凓\uD852\uDEA6决凢卂凭菍椾\uD84D\uDF2D彻刋刦刼劵剗劔効勅簕蕂勠蘍\uD85A\uDF13包\uD862\uDEDE啉滙\uD84F\uDF80\uD842\uDD54\uD84F\uDFEC匳卄\uD842\uDFE2泋\uD845\uDF26栛珕恊㺪㣌\uD845\uDEE8燝䒢卭却\uD861\uDEAB卾卿\uD845\uDD96\uD845\uDE13矦厓\uD862\uDE9B厠厫厮玧\uD855\uDF72㽙玜叁叅汉义埾叙㪫\uD842\uDF8F叠\uD84F\uDFEB\uD84B\uDDA3叶\uD843\uDC77吓灹唫晗浛呭\uD85A\uDF53\uD843\uDD74啝咏咤䞦\uD845\uDF0D\uD843\uDEDD㶴\uD843\uDD4D"],["fb40","\uD862\uDDBC\uD849\uDE98啇䳭启琗喆喩嘅\uD846\uDCD7\uD850\uDC3A䕒\uD851\uDC35暳\uD844\uDCB4嘷曍\uD84C\uDE8A暤暭噍噏磱囱鞇叾圀囯园\uD862\uDF66㘣\uD844\uDE4F坆\uD850\uDDA5汮炋坂㚱\uD85B\uDC7E埦\uD845\uDC16堃\uD845\uDC54\uD850\uDF63堦\uD852\uDFF5塜墪㕡壠壜\uD844\uDE3C壻寿坃\uD868\uDD50\uD850\uDE78鏓㖡够梦㛃湙"],["fba1","\uD845\uDE3E娤啓\uD845\uDE92蔅姉\uD843\uDD4E\uD85B\uDC81\uD85B\uDD2A\uD845\uDFDC姙\uD845\uDFFB\uD845\uDFB2\uD85B\uDDA6浱\uD846\uDC28\uD845\uDED5姹\uD85B\uDE45媫婣㛦\uD852\uDDA9婷㜈媖瑥嫓\uD85B\uDFA1\uD849\uDD54㶅\uD846\uDD11㜲\uD845\uDEB8広勐孶斈孼\uD85E\uDE0E䀄䡝\uD840\uDE04寕慠\uD846\uDE34\uD856\uDDCC\uD841\uDDA5寳宝䴐尅\uD846\uDF44尓珎尔\uD847\uDCA5\uD85A\uDF28屉䣝岅峩峯嶋\uD847\uDDF9\uD847\uDE37崐崘嵆\uD847\uDEA4岺巗苼㠭\uD852\uDD01\uD848\uDC49\uD848\uDD73芇㠶㯂帮檊幵幺\uD851\uDCBC\uD843\uDCD3厦亷廐厨\uD845\uDF71帉廴\uD861\uDC82"],["fc40","廹廻㢠廼栾鐛弍\uD840\uDDC1\uD87E\uDC94㫞䢮\uD844\uDF3A强\uD85A\uDC88\uD848\uDFD0彘\uD849\uDC71彣鞽\uD85B\uDE6E彲鍀\uD862\uDE36徧嶶㵟\uD854\uDE50\uD847\uDF6A\uD85C\uDCF8\uD849\uDE68釖\uD840\uDE9E\uD862\uDE29怱暅\uD846\uDC77㥣㷇㘹垐\uD849\uDFB4祱㹀悞悤悳\uD852\uDD82\uD852\uDD8F\uD85E\uDE53璤僡媠慤萤慂\uD87E\uDCA6\uD85B\uDED2憁凴\uD841\uDE56憇宪\uD84F\uDFB7"],["fca1","\uD84A\uDC5F懓\uD862\uDF9D\uD866\uDD5D懐㤲\uD84A\uDD80\uD84A\uDCC1怣慜攞掋\uD840\uDD18担\uD845\uDF70拕\uD84B\uDE0D捬\uD852\uDDDF㨗搸揸\uD844\uDF8E\uD845\uDFFC撐澊\uD84B\uDE36頔\uD850\uDC8C\uD855\uDF1D擡擥鑻㩦携㩗敍漖\uD852\uDE28\uD852\uDE23斅敭敟\uD84C\uDC7E斵\uD852\uDD40䬷旑䃘\uD846\uDC29无旣忟\uD84D\uDC00昘\uD84C\uDDF7\uD84C\uDDF8晄\uD84C\uDDA4\uD84C\uDDA5晋\uD843\uDE75晧\uD854\uDDE6晳晴\uD847\uDE3D\uD84C\uDE31\uD861\uDDF4\uD84C\uDDC8\uD854\uDF13矅\uD84A\uDCF7馤朂\uD850\uDF9C\uD852\uDE21㬫槺\uD84D\uDFC2杞杧杢\uD850\uDDCD\uD864\uDCED柗䓩栢湐鈼栁\uD84C\uDFE6\uD85B\uDDA0桝"],["fd40","\uD84D\uDC6F槡樋\uD862\uDEDF楳棃\uD84D\uDDCD椁椀㴲㨁\uD84D\uDE3C㮀枬楡\uD862\uDE4A䋼椶榘㮡\uD840\uDFC9荣傐槹\uD84D\uDE59\uD848\uDD2A橅\uD84D\uDF03檝㯳枱櫈\uD864\uDD9C㰍欝\uD842\uDD23惞欵歴\uD849\uDFCD溵\uD84E\uDEDB\uD840\uDFB5\uD846\uDD58㝀吡\uD84E\uDF5A毡\uD84F\uDEFC毜氷\uD849\uDC8B\uD852\uDCF1\uD85A\uDF51汚舦汹\uD84F\uDDBC䓅\uD84F\uDDBD\uD850\uDDA4\uD852\uDD0C\uD852\uDD00"],["fda1","\uD84F\uDCC9㛥㳫\uD843\uDD32鮃\uD84C\uDDF9\uD849\uDC91羏样\uD85B\uDD25\uD85B\uDDA1\uD85B\uDDEB涖浜湼漄\uD852\uDD7F\uD850\uDC85\uD85B\uDE72蔳\uD85B\uDF74凇沜渝萮\uD862\uDF21港\uD84F\uDE2F瑓\uD84F\uDF82秌湏媑\uD84C\uDC4B濸㜍澝\uD84F\uDE30滺\uD845\uDC97\uD850\uDC3D䕕鏰潄潜㵎潴\uD864\uDD70㴻澟\uD850\uDD44濓\uD850\uDC91\uD850\uDD55\uD850\uDC39\uD84F\uDFF0\uD84F\uDFB4\uD850\uDD3F凟\uD850\uDD56\uD850\uDD57\uD850\uDD40\uD858\uDDDD灋灾炧炁烌烕烖烟䄄㷨熴熖\uD850\uDE77焫煅媈煊煮岜\uD850\uDF65煏鍢\uD850\uDEC1焬\uD851\uDC5A\uD852\uDE27\uD852\uDE22熺\uD862\uDFE8炽爎"],["fe40","鑂爕夑鑃爤鍁\uD855\uDE05爮牀\uD852\uDD74梽牕牗㹕\uD84C\uDC44栍漽犂猪猫\uD852\uDC23\uD862\uDC2B䣭\uD862\uDC04猨献珏玪\uD843\uDC3A\uD85A\uDE2E珉瑉\uD850\uDDE2\uD845\uDEE7\uD852\uDE24昣㛅\uD852\uDDB7\uD852\uDD8D\uD852\uDDFB珷琕椃\uD852\uDE26琹\uD841\uDDC3㻗瑜\uD84A\uDCAD瑠\uD863\uDEB2瑇珤瑶莹瑬㜰瑴鏱樬璂䥓\uD852\uDE8C"],["fea1","\uD850\uDD5F\uD852\uDE79\uD862\uDF8F孆\uD863\uDC03\uD846\uDC9E瓈\uD846\uDD88甎瓩甞\uD863\uDED9\uD846\uDE4B寗\uD863\uDEAC鎅畍畊畧畮\uD853\uDF82㼄\uD853\uDD13疎瑝疞疴瘂瘬癑癏癯癶\uD858\uDFF5皐臯㟸\uD85A\uDD11\uD85A\uDD0E皡皥皷盌\uD85B\uDF9F葢\uD854\uDC9D\uD854\uDD7D\uD847\uDE1C眞眦着撯\uD854\uDE20睘\uD84C\uDEAC瞯\uD862\uDD64\uD862\uDD68\uD845\uDEC1矴砉\uD844\uDF76\uD852\uDE12棊碯磇磓隥礮\uD855\uDDE0磗礴碱\uD85D\uDE0C辸袄\uD862\uDF2B\uD858\uDC83\uD849\uDE1C禆褀椂禀\uD856\uDC57禝\uD85E\uDF39礼禩渪\uD85C\uDD26㺨秆\uD864\uDD0D秔"]]});var El=B0((is1,Xl)=>{Xl.exports={shiftjis:{type:"_dbcs",table:function(){return Cl()},encodeAdd:{"¥":92,"‾":126},encodeSkipVals:[{from:60736,to:63808}]},csshiftjis:"shiftjis",mskanji:"shiftjis",sjis:"shiftjis",windows31j:"shiftjis",ms31j:"shiftjis",xsjis:"shiftjis",windows932:"shiftjis",ms932:"shiftjis","932":"shiftjis",cp932:"shiftjis",eucjp:{type:"_dbcs",table:function(){return Yl()},encodeAdd:{"¥":92,"‾":126}},gb2312:"cp936",gb231280:"cp936",gb23121980:"cp936",csgb2312:"cp936",csiso58gb231280:"cp936",euccn:"cp936",windows936:"cp936",ms936:"cp936","936":"cp936",cp936:{type:"_dbcs",table:function(){return yW()}},gbk:{type:"_dbcs",table:function(){return yW().concat(OV())}},xgbk:"gbk",isoir58:"gbk",gb18030:{type:"_dbcs",table:function(){return yW().concat(OV())},gb18030:function(){return Ul()},encodeSkipVals:[128],encodeAdd:{"€":41699}},chinese:"gb18030",windows949:"cp949",ms949:"cp949","949":"cp949",cp949:{type:"_dbcs",table:function(){return Zl()}},cseuckr:"cp949",csksc56011987:"cp949",euckr:"cp949",isoir149:"cp949",korean:"cp949",ksc56011987:"cp949",ksc56011989:"cp949",ksc5601:"cp949",windows950:"cp950",ms950:"cp950","950":"cp950",cp950:{type:"_dbcs",table:function(){return NV()}},big5:"big5hkscs",big5hkscs:{type:"_dbcs",table:function(){return NV().concat(Bl())},encodeSkipVals:[36457,36463,36478,36523,36532,36557,36560,36695,36713,36718,36811,36862,36973,36986,37060,37084,37105,37311,37551,37552,37553,37554,37585,37959,38090,38361,38652,39285,39798,39800,39803,39878,39902,39916,39926,40002,40019,40034,40040,40043,40055,40124,40125,40144,40279,40282,40388,40431,40443,40617,40687,40701,40800,40907,41079,41180,41183,36812,37576,38468,38637,41636,41637,41639,41638,41676,41678]},cnbig5:"big5hkscs",csbig5:"big5hkscs",xxbig5:"big5hkscs"}});var Gl=B0((Hl,EY)=>{var $l=[md(),ld(),od(),ad(),rd(),ed(),Ql(),Kl(),El()];for(hW=0;hW<$l.length;hW++){EY=$l[hW];for(gW in EY)if(Object.prototype.hasOwnProperty.call(EY,gW))Hl[gW]=EY[gW]}var EY,gW,hW});var ql=B0((as1,Il)=>{var Wl=F7().Buffer;Il.exports=function(A){var Q=A.Transform;function J(C,U){this.conv=C,U=U||{},U.decodeStrings=!1,Q.call(this,U)}J.prototype=Object.create(Q.prototype,{constructor:{value:J}}),J.prototype._transform=function(C,U,Y){if(typeof C!="string")return Y(new Error("Iconv encoding stream needs strings as its input."));try{var Z=this.conv.write(C);if(Z&&Z.length)this.push(Z);Y()}catch(X){Y(X)}},J.prototype._flush=function(C){try{var U=this.conv.end();if(U&&U.length)this.push(U);C()}catch(Y){C(Y)}},J.prototype.collect=function(C){var U=[];return this.on("error",C),this.on("data",function(Y){U.push(Y)}),this.on("end",function(){C(null,Wl.concat(U))}),this};function K(C,U){this.conv=C,U=U||{},U.encoding=this.encoding="utf8",Q.call(this,U)}return K.prototype=Object.create(Q.prototype,{constructor:{value:K}}),K.prototype._transform=function(C,U,Y){if(!Wl.isBuffer(C)&&!(C instanceof Uint8Array))return Y(new Error("Iconv decoding stream needs buffers as its input."));try{var Z=this.conv.write(C);if(Z&&Z.length)this.push(Z,this.encoding);Y()}catch(X){Y(X)}},K.prototype._flush=function(C){try{var U=this.conv.end();if(U&&U.length)this.push(U,this.encoding);C()}catch(Y){C(Y)}},K.prototype.collect=function(C){var U="";return this.on("error",C),this.on("data",function(Y){U+=Y}),this.on("end",function(){C(null,U)}),this},{IconvLiteEncoderStream:J,IconvLiteDecoderStream:K}}});var Fl=B0((rs1,Ll)=>{var Ol=F7().Buffer,Nl=hd(),PA=rs1;PA.encodings=null;PA.defaultCharUnicode="�";PA.defaultCharSingleByte="?";PA.encode=function A(Q,J,K){Q=""+(Q||"");var C=PA.getEncoder(J,K),U=C.write(Q),Y=C.end();return Y&&Y.length>0?Ol.concat([U,Y]):U};PA.decode=function A(Q,J,K){if(typeof Q==="string"){if(!PA.skipDecodeWarning)console.error("Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding"),PA.skipDecodeWarning=!0;Q=Ol.from(""+(Q||""),"binary")}var C=PA.getDecoder(J,K),U=C.write(Q),Y=C.end();return Y?U+Y:U};PA.encodingExists=function A(Q){try{return PA.getCodec(Q),!0}catch(J){return!1}};PA.toEncoding=PA.encode;PA.fromEncoding=PA.decode;PA._codecDataCache={};PA.getCodec=function A(Q){if(!PA.encodings)PA.encodings=Gl();var J=PA._canonicalizeEncoding(Q),K={};while(!0){var C=PA._codecDataCache[J];if(C)return C;var U=PA.encodings[J];switch(typeof U){case"string":J=U;break;case"object":for(var Y in U)K[Y]=U[Y];if(!K.encodingName)K.encodingName=J;J=U.type;break;case"function":if(!K.encodingName)K.encodingName=J;return C=new U(K,PA),PA._codecDataCache[K.encodingName]=C,C;default:throw new Error("Encoding not recognized: '"+Q+"' (searched as: '"+J+"')")}}};PA._canonicalizeEncoding=function(A){return(""+A).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g,"")};PA.getEncoder=function A(Q,J){var K=PA.getCodec(Q),C=new K.encoder(J,K);if(K.bomAware&&J&&J.addBOM)C=new Nl.PrependBOM(C,J);return C};PA.getDecoder=function A(Q,J){var K=PA.getCodec(Q),C=new K.decoder(J,K);if(K.bomAware&&!(J&&J.stripBOM===!1))C=new Nl.StripBOM(C,J);return C};PA.enableStreamingAPI=function A(Q){if(PA.supportsStreams)return;var J=ql()(Q);PA.IconvLiteEncoderStream=J.IconvLiteEncoderStream,PA.IconvLiteDecoderStream=J.IconvLiteDecoderStream,PA.encodeStream=function K(C,U){return new PA.IconvLiteEncoderStream(PA.getEncoder(C,U),U)},PA.decodeStream=function K(C,U){return new PA.IconvLiteDecoderStream(PA.getDecoder(C,U),U)},PA.supportsStreams=!0};var bW;try{bW=($X(),y4(EX))}catch(A){}if(bW&&bW.Transform)PA.enableStreamingAPI(bW);else PA.encodeStream=PA.decodeStream=function(){throw new Error("iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it.")}});var il={};z3(il,{default:()=>ol});var w$1,uW,P$1,_$1,T$1,k$1,RV=(A,Q)=>()=>(A&&(Q=A(A=0)),Q),k0=(A,Q)=>()=>(Q||A((Q={exports:{}}).exports,Q),Q.exports),mW=(A,Q)=>{for(var J in Q)uW(A,J,{get:Q[J],enumerable:!0})},fW=(A,Q,J,K)=>{if(Q&&typeof Q=="object"||typeof Q=="function")for(let C of _$1(Q))!k$1.call(A,C)&&C!==J&&uW(A,C,{get:()=>Q[C],enumerable:!(K=P$1(Q,C))||K.enumerable});return A},cW=(A,Q,J)=>(fW(A,Q,"default"),J&&fW(J,Q,"default")),zJ=(A,Q,J)=>(J=A!=null?w$1(T$1(A)):{},fW(Q||!A||!A.__esModule?uW(J,"default",{value:A,enumerable:!0}):J,A)),N9=(A)=>fW(uW({},"__esModule",{value:!0}),A),S$1,j$1,W3,P8,z7,zV,o6,dW,Rl,V7,Dl,VJ,MJ,wJ,v$1,$Y,DV,VV,MV,x$1,wV,y$1,h$1,Vl,lW,Ml,g$1,D7,wl,Pl,PV,b$1,_l,f$1,zl,_V,Tl,p$1,kl,nW,u$1,m$1,TV,c$1,sW,kV,SV,d$1,l$1,n$1,Sl,jl,vl,xl,s$1,o$1,i$1,a$1,yl,DJ,LV,FV,hl,mB,gl,r$1,t$1,bl,e$1,AH1,QH1,oW,fl,pl,JH1,ul,ml,cl,KH1,CH1,YH1,pW,UH1,iW,ZH1,dl,ll,BH1,XH1,EH1,$H1,HH1,GH1,WH1,nl,sl,ol;var al=hJ(()=>{w$1=Object.create,uW=Object.defineProperty,P$1=Object.getOwnPropertyDescriptor,_$1=Object.getOwnPropertyNames,T$1=Object.getPrototypeOf,k$1=Object.prototype.hasOwnProperty,S$1=k0((A)=>{A.byteLength=X,A.toByteArray=H,A.fromByteArray=N;var Q=[],J=[],K=typeof Uint8Array<"u"?Uint8Array:Array,C="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(U=0,Y=C.length;U0)throw new Error("Invalid string. Length must be a multiple of 4");var D=F.indexOf("=");D===-1&&(D=V);var L=D===V?0:4-D%4;return[D,L]}function X(F){var V=Z(F),D=V[0],L=V[1];return(D+L)*3/4-L}function E(F,V,D){return(V+D)*3/4-D}function H(F){var V,D=Z(F),L=D[0],R=D[1],M=new K(E(F,L,R)),T=0,h=R>0?L-4:L,y;for(y=0;y>16&255,M[T++]=V>>8&255,M[T++]=V&255;return R===2&&(V=J[F.charCodeAt(y)]<<2|J[F.charCodeAt(y+1)]>>4,M[T++]=V&255),R===1&&(V=J[F.charCodeAt(y)]<<10|J[F.charCodeAt(y+1)]<<4|J[F.charCodeAt(y+2)]>>2,M[T++]=V>>8&255,M[T++]=V&255),M}function $(F){return Q[F>>18&63]+Q[F>>12&63]+Q[F>>6&63]+Q[F&63]}function I(F,V,D){for(var L,R=[],M=V;Mh?h:T+M));return L===1?(V=F[D-1],R.push(Q[V>>2]+Q[V<<4&63]+"==")):L===2&&(V=(F[D-2]<<8)+F[D-1],R.push(Q[V>>10]+Q[V>>4&63]+Q[V<<2&63]+"=")),R.join("")}}),j$1=k0((A)=>{A.read=function(Q,J,K,C,U){var Y,Z,X=U*8-C-1,E=(1<>1,$=-7,I=K?U-1:0,N=K?-1:1,F=Q[J+I];for(I+=N,Y=F&(1<<-$)-1,F>>=-$,$+=X;$>0;Y=Y*256+Q[J+I],I+=N,$-=8);for(Z=Y&(1<<-$)-1,Y>>=-$,$+=C;$>0;Z=Z*256+Q[J+I],I+=N,$-=8);if(Y===0)Y=1-H;else{if(Y===E)return Z?NaN:(F?-1:1)*(1/0);Z=Z+Math.pow(2,C),Y=Y-H}return(F?-1:1)*Z*Math.pow(2,Y-C)},A.write=function(Q,J,K,C,U,Y){var Z,X,E,H=Y*8-U-1,$=(1<>1,N=U===23?Math.pow(2,-24)-Math.pow(2,-77):0,F=C?0:Y-1,V=C?1:-1,D=J<0||J===0&&1/J<0?1:0;for(J=Math.abs(J),isNaN(J)||J===1/0?(X=isNaN(J)?1:0,Z=$):(Z=Math.floor(Math.log(J)/Math.LN2),J*(E=Math.pow(2,-Z))<1&&(Z--,E*=2),Z+I>=1?J+=N/E:J+=N*Math.pow(2,1-I),J*E>=2&&(Z++,E/=2),Z+I>=$?(X=0,Z=$):Z+I>=1?(X=(J*E-1)*Math.pow(2,U),Z=Z+I):(X=J*Math.pow(2,I-1)*Math.pow(2,U),Z=0));U>=8;Q[K+F]=X&255,F+=V,X/=256,U-=8);for(Z=Z<0;Q[K+F]=Z&255,F+=V,Z/=256,H-=8);Q[K+F-V]|=D*128}}),W3=k0((A)=>{var Q=S$1(),J=j$1(),K=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;A.Buffer=Z,A.SlowBuffer=R,A.INSPECT_MAX_BYTES=50;var C=2147483647;A.kMaxLength=C,Z.TYPED_ARRAY_SUPPORT=U(),!Z.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function U(){try{let G=new Uint8Array(1),z={foo:function(){return 42}};return Object.setPrototypeOf(z,Uint8Array.prototype),Object.setPrototypeOf(G,z),G.foo()===42}catch{return!1}}Object.defineProperty(Z.prototype,"parent",{enumerable:!0,get:function(){if(Z.isBuffer(this))return this.buffer}}),Object.defineProperty(Z.prototype,"offset",{enumerable:!0,get:function(){if(Z.isBuffer(this))return this.byteOffset}});function Y(G){if(G>C)throw new RangeError('The value "'+G+'" is invalid for option "size"');let z=new Uint8Array(G);return Object.setPrototypeOf(z,Z.prototype),z}function Z(G,z,x){if(typeof G=="number"){if(typeof z=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return $(G)}return X(G,z,x)}Z.poolSize=8192;function X(G,z,x){if(typeof G=="string")return I(G,z);if(ArrayBuffer.isView(G))return F(G);if(G==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof G);if(B1(G,ArrayBuffer)||G&&B1(G.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(B1(G,SharedArrayBuffer)||G&&B1(G.buffer,SharedArrayBuffer)))return V(G,z,x);if(typeof G=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let m=G.valueOf&&G.valueOf();if(m!=null&&m!==G)return Z.from(m,z,x);let l=D(G);if(l)return l;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof G[Symbol.toPrimitive]=="function")return Z.from(G[Symbol.toPrimitive]("string"),z,x);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof G)}Z.from=function(G,z,x){return X(G,z,x)},Object.setPrototypeOf(Z.prototype,Uint8Array.prototype),Object.setPrototypeOf(Z,Uint8Array);function E(G){if(typeof G!="number")throw new TypeError('"size" argument must be of type number');if(G<0)throw new RangeError('The value "'+G+'" is invalid for option "size"')}function H(G,z,x){return E(G),G<=0?Y(G):z!==void 0?typeof x=="string"?Y(G).fill(z,x):Y(G).fill(z):Y(G)}Z.alloc=function(G,z,x){return H(G,z,x)};function $(G){return E(G),Y(G<0?0:L(G)|0)}Z.allocUnsafe=function(G){return $(G)},Z.allocUnsafeSlow=function(G){return $(G)};function I(G,z){if((typeof z!="string"||z==="")&&(z="utf8"),!Z.isEncoding(z))throw new TypeError("Unknown encoding: "+z);let x=M(G,z)|0,m=Y(x),l=m.write(G,z);return l!==x&&(m=m.slice(0,l)),m}function N(G){let z=G.length<0?0:L(G.length)|0,x=Y(z);for(let m=0;m=C)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+C.toString(16)+" bytes");return G|0}function R(G){return+G!=G&&(G=0),Z.alloc(+G)}Z.isBuffer=function(G){return G!=null&&G._isBuffer===!0&&G!==Z.prototype},Z.compare=function(G,z){if(B1(G,Uint8Array)&&(G=Z.from(G,G.offset,G.byteLength)),B1(z,Uint8Array)&&(z=Z.from(z,z.offset,z.byteLength)),!Z.isBuffer(G)||!Z.isBuffer(z))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(G===z)return 0;let x=G.length,m=z.length;for(let l=0,a=Math.min(x,m);lm.length?(Z.isBuffer(a)||(a=Z.from(a)),a.copy(m,l)):Uint8Array.prototype.set.call(m,a,l);else if(Z.isBuffer(a))a.copy(m,l);else throw new TypeError('"list" argument must be an Array of Buffers');l+=a.length}return m};function M(G,z){if(Z.isBuffer(G))return G.length;if(ArrayBuffer.isView(G)||B1(G,ArrayBuffer))return G.byteLength;if(typeof G!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof G);let x=G.length,m=arguments.length>2&&arguments[2]===!0;if(!m&&x===0)return 0;let l=!1;for(;;)switch(z){case"ascii":case"latin1":case"binary":return x;case"utf8":case"utf-8":return C1(G).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x*2;case"hex":return x>>>1;case"base64":return j1(G).length;default:if(l)return m?-1:C1(G).length;z=(""+z).toLowerCase(),l=!0}}Z.byteLength=M;function T(G,z,x){let m=!1;if((z===void 0||z<0)&&(z=0),z>this.length||((x===void 0||x>this.length)&&(x=this.length),x<=0)||(x>>>=0,z>>>=0,x<=z))return"";for(G||(G="utf8");;)switch(G){case"hex":return _(this,z,x);case"utf8":case"utf-8":return P(this,z,x);case"ascii":return k(this,z,x);case"latin1":case"binary":return S(this,z,x);case"base64":return q(this,z,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return W(this,z,x);default:if(m)throw new TypeError("Unknown encoding: "+G);G=(G+"").toLowerCase(),m=!0}}Z.prototype._isBuffer=!0;function h(G,z,x){let m=G[z];G[z]=G[x],G[x]=m}Z.prototype.swap16=function(){let G=this.length;if(G%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let z=0;zz&&(G+=" ... "),""},K&&(Z.prototype[K]=Z.prototype.inspect),Z.prototype.compare=function(G,z,x,m,l){if(B1(G,Uint8Array)&&(G=Z.from(G,G.offset,G.byteLength)),!Z.isBuffer(G))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof G);if(z===void 0&&(z=0),x===void 0&&(x=G?G.length:0),m===void 0&&(m=0),l===void 0&&(l=this.length),z<0||x>G.length||m<0||l>this.length)throw new RangeError("out of range index");if(m>=l&&z>=x)return 0;if(m>=l)return-1;if(z>=x)return 1;if(z>>>=0,x>>>=0,m>>>=0,l>>>=0,this===G)return 0;let a=l-m,K1=x-z,F1=Math.min(a,K1),R1=this.slice(m,l),X1=G.slice(z,x);for(let W1=0;W12147483647?x=2147483647:x<-2147483648&&(x=-2147483648),x=+x,k1(x)&&(x=l?0:G.length-1),x<0&&(x=G.length+x),x>=G.length){if(l)return-1;x=G.length-1}else if(x<0)if(l)x=0;else return-1;if(typeof z=="string"&&(z=Z.from(z,m)),Z.isBuffer(z))return z.length===0?-1:g(G,z,x,m,l);if(typeof z=="number")return z=z&255,typeof Uint8Array.prototype.indexOf=="function"?l?Uint8Array.prototype.indexOf.call(G,z,x):Uint8Array.prototype.lastIndexOf.call(G,z,x):g(G,[z],x,m,l);throw new TypeError("val must be string, number or Buffer")}function g(G,z,x,m,l){let a=1,K1=G.length,F1=z.length;if(m!==void 0&&(m=String(m).toLowerCase(),m==="ucs2"||m==="ucs-2"||m==="utf16le"||m==="utf-16le")){if(G.length<2||z.length<2)return-1;a=2,K1/=2,F1/=2,x/=2}function R1(W1,$1){return a===1?W1[$1]:W1.readUInt16BE($1*a)}let X1;if(l){let W1=-1;for(X1=x;X1K1&&(x=K1-F1),X1=x;X1>=0;X1--){let W1=!0;for(let $1=0;$1l&&(m=l)):m=l;let a=z.length;m>a/2&&(m=a/2);let K1;for(K1=0;K1>>0,isFinite(x)?(x=x>>>0,m===void 0&&(m="utf8")):(m=x,x=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let l=this.length-z;if((x===void 0||x>l)&&(x=l),G.length>0&&(x<0||z<0)||z>this.length)throw new RangeError("Attempt to write outside buffer bounds");m||(m="utf8");let a=!1;for(;;)switch(m){case"hex":return f(this,G,z,x);case"utf8":case"utf-8":return u(this,G,z,x);case"ascii":case"latin1":case"binary":return d(this,G,z,x);case"base64":return n(this,G,z,x);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return B(this,G,z,x);default:if(a)throw new TypeError("Unknown encoding: "+m);m=(""+m).toLowerCase(),a=!0}},Z.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function q(G,z,x){return z===0&&x===G.length?Q.fromByteArray(G):Q.fromByteArray(G.slice(z,x))}function P(G,z,x){x=Math.min(G.length,x);let m=[],l=z;for(;l239?4:a>223?3:a>191?2:1;if(l+F1<=x){let R1,X1,W1,$1;switch(F1){case 1:a<128&&(K1=a);break;case 2:R1=G[l+1],(R1&192)===128&&($1=(a&31)<<6|R1&63,$1>127&&(K1=$1));break;case 3:R1=G[l+1],X1=G[l+2],(R1&192)===128&&(X1&192)===128&&($1=(a&15)<<12|(R1&63)<<6|X1&63,$1>2047&&($1<55296||$1>57343)&&(K1=$1));break;case 4:R1=G[l+1],X1=G[l+2],W1=G[l+3],(R1&192)===128&&(X1&192)===128&&(W1&192)===128&&($1=(a&15)<<18|(R1&63)<<12|(X1&63)<<6|W1&63,$1>65535&&$1<1114112&&(K1=$1))}}K1===null?(K1=65533,F1=1):K1>65535&&(K1-=65536,m.push(K1>>>10&1023|55296),K1=56320|K1&1023),m.push(K1),l+=F1}return w(m)}var O=4096;function w(G){let z=G.length;if(z<=O)return String.fromCharCode.apply(String,G);let x="",m=0;for(;mm)&&(x=m);let l="";for(let a=z;ax&&(G=x),z<0?(z+=x,z<0&&(z=0)):z>x&&(z=x),zx)throw new RangeError("Trying to access beyond buffer length")}Z.prototype.readUintLE=Z.prototype.readUIntLE=function(G,z,x){G=G>>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G],l=1,a=0;for(;++a>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G+--z],l=1;for(;z>0&&(l*=256);)m+=this[G+--z]*l;return m},Z.prototype.readUint8=Z.prototype.readUInt8=function(G,z){return G=G>>>0,z||j(G,1,this.length),this[G]},Z.prototype.readUint16LE=Z.prototype.readUInt16LE=function(G,z){return G=G>>>0,z||j(G,2,this.length),this[G]|this[G+1]<<8},Z.prototype.readUint16BE=Z.prototype.readUInt16BE=function(G,z){return G=G>>>0,z||j(G,2,this.length),this[G]<<8|this[G+1]},Z.prototype.readUint32LE=Z.prototype.readUInt32LE=function(G,z){return G=G>>>0,z||j(G,4,this.length),(this[G]|this[G+1]<<8|this[G+2]<<16)+this[G+3]*16777216},Z.prototype.readUint32BE=Z.prototype.readUInt32BE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]*16777216+(this[G+1]<<16|this[G+2]<<8|this[G+3])},Z.prototype.readBigUInt64LE=G1(function(G){G=G>>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=z+this[++G]*256+this[++G]*65536+this[++G]*16777216,l=this[++G]+this[++G]*256+this[++G]*65536+x*16777216;return BigInt(m)+(BigInt(l)<>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=z*16777216+this[++G]*65536+this[++G]*256+this[++G],l=this[++G]*16777216+this[++G]*65536+this[++G]*256+x;return(BigInt(m)<>>0,z=z>>>0,x||j(G,z,this.length);let m=this[G],l=1,a=0;for(;++a=l&&(m-=Math.pow(2,8*z)),m},Z.prototype.readIntBE=function(G,z,x){G=G>>>0,z=z>>>0,x||j(G,z,this.length);let m=z,l=1,a=this[G+--m];for(;m>0&&(l*=256);)a+=this[G+--m]*l;return l*=128,a>=l&&(a-=Math.pow(2,8*z)),a},Z.prototype.readInt8=function(G,z){return G=G>>>0,z||j(G,1,this.length),this[G]&128?(255-this[G]+1)*-1:this[G]},Z.prototype.readInt16LE=function(G,z){G=G>>>0,z||j(G,2,this.length);let x=this[G]|this[G+1]<<8;return x&32768?x|4294901760:x},Z.prototype.readInt16BE=function(G,z){G=G>>>0,z||j(G,2,this.length);let x=this[G+1]|this[G]<<8;return x&32768?x|4294901760:x},Z.prototype.readInt32LE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]|this[G+1]<<8|this[G+2]<<16|this[G+3]<<24},Z.prototype.readInt32BE=function(G,z){return G=G>>>0,z||j(G,4,this.length),this[G]<<24|this[G+1]<<16|this[G+2]<<8|this[G+3]},Z.prototype.readBigInt64LE=G1(function(G){G=G>>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=this[G+4]+this[G+5]*256+this[G+6]*65536+(x<<24);return(BigInt(m)<>>0,Y1(G,"offset");let z=this[G],x=this[G+7];(z===void 0||x===void 0)&&i(G,this.length-8);let m=(z<<24)+this[++G]*65536+this[++G]*256+this[++G];return(BigInt(m)<>>0,z||j(G,4,this.length),J.read(this,G,!0,23,4)},Z.prototype.readFloatBE=function(G,z){return G=G>>>0,z||j(G,4,this.length),J.read(this,G,!1,23,4)},Z.prototype.readDoubleLE=function(G,z){return G=G>>>0,z||j(G,8,this.length),J.read(this,G,!0,52,8)},Z.prototype.readDoubleBE=function(G,z){return G=G>>>0,z||j(G,8,this.length),J.read(this,G,!1,52,8)};function b(G,z,x,m,l,a){if(!Z.isBuffer(G))throw new TypeError('"buffer" argument must be a Buffer instance');if(z>l||zG.length)throw new RangeError("Index out of range")}Z.prototype.writeUintLE=Z.prototype.writeUIntLE=function(G,z,x,m){if(G=+G,z=z>>>0,x=x>>>0,!m){let K1=Math.pow(2,8*x)-1;b(this,G,z,x,K1,0)}let l=1,a=0;for(this[z]=G&255;++a>>0,x=x>>>0,!m){let K1=Math.pow(2,8*x)-1;b(this,G,z,x,K1,0)}let l=x-1,a=1;for(this[z+l]=G&255;--l>=0&&(a*=256);)this[z+l]=G/a&255;return z+x},Z.prototype.writeUint8=Z.prototype.writeUInt8=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,1,255,0),this[z]=G&255,z+1},Z.prototype.writeUint16LE=Z.prototype.writeUInt16LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,65535,0),this[z]=G&255,this[z+1]=G>>>8,z+2},Z.prototype.writeUint16BE=Z.prototype.writeUInt16BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,65535,0),this[z]=G>>>8,this[z+1]=G&255,z+2},Z.prototype.writeUint32LE=Z.prototype.writeUInt32LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,4294967295,0),this[z+3]=G>>>24,this[z+2]=G>>>16,this[z+1]=G>>>8,this[z]=G&255,z+4},Z.prototype.writeUint32BE=Z.prototype.writeUInt32BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,4294967295,0),this[z]=G>>>24,this[z+1]=G>>>16,this[z+2]=G>>>8,this[z+3]=G&255,z+4};function p(G,z,x,m,l){E1(z,m,l,G,x,7);let a=Number(z&BigInt(4294967295));G[x++]=a,a=a>>8,G[x++]=a,a=a>>8,G[x++]=a,a=a>>8,G[x++]=a;let K1=Number(z>>BigInt(32)&BigInt(4294967295));return G[x++]=K1,K1=K1>>8,G[x++]=K1,K1=K1>>8,G[x++]=K1,K1=K1>>8,G[x++]=K1,x}function s(G,z,x,m,l){E1(z,m,l,G,x,7);let a=Number(z&BigInt(4294967295));G[x+7]=a,a=a>>8,G[x+6]=a,a=a>>8,G[x+5]=a,a=a>>8,G[x+4]=a;let K1=Number(z>>BigInt(32)&BigInt(4294967295));return G[x+3]=K1,K1=K1>>8,G[x+2]=K1,K1=K1>>8,G[x+1]=K1,K1=K1>>8,G[x]=K1,x+8}Z.prototype.writeBigUInt64LE=G1(function(G,z=0){return p(this,G,z,BigInt(0),BigInt("0xffffffffffffffff"))}),Z.prototype.writeBigUInt64BE=G1(function(G,z=0){return s(this,G,z,BigInt(0),BigInt("0xffffffffffffffff"))}),Z.prototype.writeIntLE=function(G,z,x,m){if(G=+G,z=z>>>0,!m){let F1=Math.pow(2,8*x-1);b(this,G,z,x,F1-1,-F1)}let l=0,a=1,K1=0;for(this[z]=G&255;++l>0)-K1&255;return z+x},Z.prototype.writeIntBE=function(G,z,x,m){if(G=+G,z=z>>>0,!m){let F1=Math.pow(2,8*x-1);b(this,G,z,x,F1-1,-F1)}let l=x-1,a=1,K1=0;for(this[z+l]=G&255;--l>=0&&(a*=256);)G<0&&K1===0&&this[z+l+1]!==0&&(K1=1),this[z+l]=(G/a>>0)-K1&255;return z+x},Z.prototype.writeInt8=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,1,127,-128),G<0&&(G=255+G+1),this[z]=G&255,z+1},Z.prototype.writeInt16LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,32767,-32768),this[z]=G&255,this[z+1]=G>>>8,z+2},Z.prototype.writeInt16BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,2,32767,-32768),this[z]=G>>>8,this[z+1]=G&255,z+2},Z.prototype.writeInt32LE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,2147483647,-2147483648),this[z]=G&255,this[z+1]=G>>>8,this[z+2]=G>>>16,this[z+3]=G>>>24,z+4},Z.prototype.writeInt32BE=function(G,z,x){return G=+G,z=z>>>0,x||b(this,G,z,4,2147483647,-2147483648),G<0&&(G=4294967295+G+1),this[z]=G>>>24,this[z+1]=G>>>16,this[z+2]=G>>>8,this[z+3]=G&255,z+4},Z.prototype.writeBigInt64LE=G1(function(G,z=0){return p(this,G,z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),Z.prototype.writeBigInt64BE=G1(function(G,z=0){return s(this,G,z,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function r(G,z,x,m,l,a){if(x+m>G.length)throw new RangeError("Index out of range");if(x<0)throw new RangeError("Index out of range")}function A1(G,z,x,m,l){return z=+z,x=x>>>0,l||r(G,z,x,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000),J.write(G,z,x,m,23,4),x+4}Z.prototype.writeFloatLE=function(G,z,x){return A1(this,G,z,!0,x)},Z.prototype.writeFloatBE=function(G,z,x){return A1(this,G,z,!1,x)};function Q1(G,z,x,m,l){return z=+z,x=x>>>0,l||r(G,z,x,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000),J.write(G,z,x,m,52,8),x+8}Z.prototype.writeDoubleLE=function(G,z,x){return Q1(this,G,z,!0,x)},Z.prototype.writeDoubleBE=function(G,z,x){return Q1(this,G,z,!1,x)},Z.prototype.copy=function(G,z,x,m){if(!Z.isBuffer(G))throw new TypeError("argument should be a Buffer");if(x||(x=0),!m&&m!==0&&(m=this.length),z>=G.length&&(z=G.length),z||(z=0),m>0&&m=this.length)throw new RangeError("Index out of range");if(m<0)throw new RangeError("sourceEnd out of bounds");m>this.length&&(m=this.length),G.length-z>>0,x=x===void 0?this.length:x>>>0,G||(G=0);let l;if(typeof G=="number")for(l=z;l4294967296?l=U1(String(x)):typeof x=="bigint"&&(l=String(x),(x>BigInt(2)**BigInt(32)||x<-(BigInt(2)**BigInt(32)))&&(l=U1(l)),l+="n"),m+=` It must be ${z}. Received ${l}`,m},RangeError);function U1(G){let z="",x=G.length,m=G[0]==="-"?1:0;for(;x>=m+4;x-=3)z=`_${G.slice(x-3,x)}${z}`;return`${G.slice(0,x)}${z}`}function O1(G,z,x){Y1(z,"offset"),(G[z]===void 0||G[z+x]===void 0)&&i(z,G.length-(x+1))}function E1(G,z,x,m,l,a){if(G>x||G3?z===0||z===BigInt(0)?F1=`>= 0${K1} and < 2${K1} ** ${(a+1)*8}${K1}`:F1=`>= -(2${K1} ** ${(a+1)*8-1}${K1}) and < 2 ** ${(a+1)*8-1}${K1}`:F1=`>= ${z}${K1} and <= ${x}${K1}`,new e.ERR_OUT_OF_RANGE("value",F1,G)}O1(m,l,a)}function Y1(G,z){if(typeof G!="number")throw new e.ERR_INVALID_ARG_TYPE(z,"number",G)}function i(G,z,x){throw Math.floor(G)!==G?(Y1(G,x),new e.ERR_OUT_OF_RANGE(x||"offset","an integer",G)):z<0?new e.ERR_BUFFER_OUT_OF_BOUNDS:new e.ERR_OUT_OF_RANGE(x||"offset",`>= ${x?1:0} and <= ${z}`,G)}var c=/[^+/0-9A-Za-z-_]/g;function o(G){if(G=G.split("=")[0],G=G.trim().replace(c,""),G.length<2)return"";for(;G.length%4!==0;)G=G+"=";return G}function C1(G,z){z=z||1/0;let x,m=G.length,l=null,a=[];for(let K1=0;K155295&&x<57344){if(!l){if(x>56319){(z-=3)>-1&&a.push(239,191,189);continue}else if(K1+1===m){(z-=3)>-1&&a.push(239,191,189);continue}l=x;continue}if(x<56320){(z-=3)>-1&&a.push(239,191,189),l=x;continue}x=(l-55296<<10|x-56320)+65536}else l&&(z-=3)>-1&&a.push(239,191,189);if(l=null,x<128){if((z-=1)<0)break;a.push(x)}else if(x<2048){if((z-=2)<0)break;a.push(x>>6|192,x&63|128)}else if(x<65536){if((z-=3)<0)break;a.push(x>>12|224,x>>6&63|128,x&63|128)}else if(x<1114112){if((z-=4)<0)break;a.push(x>>18|240,x>>12&63|128,x>>6&63|128,x&63|128)}else throw new Error("Invalid code point")}return a}function q1(G){let z=[];for(let x=0;x>8,l=x%256,a.push(l),a.push(m);return a}function j1(G){return Q.toByteArray(o(G))}function H1(G,z,x,m){let l;for(l=0;l=z.length||l>=G.length);++l)z[l+x]=G[l];return l}function B1(G,z){return G instanceof z||G!=null&&G.constructor!=null&&G.constructor.name!=null&&G.constructor.name===z.name}function k1(G){return G!==G}var D1=function(){let G="0123456789abcdef",z=new Array(256);for(let x=0;x<16;++x){let m=x*16;for(let l=0;l<16;++l)z[m+l]=G[x]+G[l]}return z}();function G1(G){return typeof BigInt>"u"?w1:G}function w1(){throw new Error("BigInt not supported")}}),P8=k0((A,Q)=>{Q.exports={ArrayIsArray(J){return Array.isArray(J)},ArrayPrototypeIncludes(J,K){return J.includes(K)},ArrayPrototypeIndexOf(J,K){return J.indexOf(K)},ArrayPrototypeJoin(J,K){return J.join(K)},ArrayPrototypeMap(J,K){return J.map(K)},ArrayPrototypePop(J,K){return J.pop(K)},ArrayPrototypePush(J,K){return J.push(K)},ArrayPrototypeSlice(J,K,C){return J.slice(K,C)},Error,FunctionPrototypeCall(J,K,...C){return J.call(K,...C)},FunctionPrototypeSymbolHasInstance(J,K){return Function.prototype[Symbol.hasInstance].call(J,K)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(J,K){return Object.defineProperties(J,K)},ObjectDefineProperty(J,K,C){return Object.defineProperty(J,K,C)},ObjectGetOwnPropertyDescriptor(J,K){return Object.getOwnPropertyDescriptor(J,K)},ObjectKeys(J){return Object.keys(J)},ObjectSetPrototypeOf(J,K){return Object.setPrototypeOf(J,K)},Promise,PromisePrototypeCatch(J,K){return J.catch(K)},PromisePrototypeThen(J,K,C){return J.then(K,C)},PromiseReject(J){return Promise.reject(J)},ReflectApply:Reflect.apply,RegExpPrototypeTest(J,K){return J.test(K)},SafeSet:Set,String,StringPrototypeSlice(J,K,C){return J.slice(K,C)},StringPrototypeToLowerCase(J){return J.toLowerCase()},StringPrototypeToUpperCase(J){return J.toUpperCase()},StringPrototypeTrim(J){return J.trim()},Symbol,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,TypedArrayPrototypeSet(J,K,C){return J.set(K,C)},Uint8Array}}),z7=k0((A,Q)=>{var J=W3(),K=Object.getPrototypeOf(async function(){}).constructor,C=globalThis.Blob||J.Blob,U=typeof C<"u"?function(Z){return Z instanceof C}:function(Z){return!1},Y=class extends Error{constructor(Z){if(!Array.isArray(Z))throw new TypeError(`Expected input to be an Array, got ${typeof Z}`);let X="";for(let E=0;E{Z=E,X=H}),resolve:Z,reject:X}},promisify(Z){return new Promise((X,E)=>{Z((H,...$)=>H?E(H):X(...$))})},debuglog(){return function(){}},format(Z,...X){return Z.replace(/%([sdifj])/g,function(...[E,H]){let $=X.shift();return H==="f"?$.toFixed(6):H==="j"?JSON.stringify($):H==="s"&&typeof $=="object"?`${$.constructor!==Object?$.constructor.name:""} {}`.trim():$.toString()})},inspect(Z){switch(typeof Z){case"string":if(Z.includes("'"))if(Z.includes('"')){if(!Z.includes("`")&&!Z.includes("${"))return`\`${Z}\``}else return`"${Z}"`;return`'${Z}'`;case"number":return isNaN(Z)?"NaN":Object.is(Z,-0)?String(Z):Z;case"bigint":return`${String(Z)}n`;case"boolean":case"undefined":return String(Z);case"object":return"{}"}},types:{isAsyncFunction(Z){return Z instanceof K},isArrayBufferView(Z){return ArrayBuffer.isView(Z)}},isBlob:U},Q.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")}),zV=k0((A,Q)=>{var{AbortController:J,AbortSignal:K}=typeof self<"u"?self:typeof window<"u"?window:void 0;Q.exports=J,Q.exports.AbortSignal=K,Q.exports.default=J}),o6=k0((A,Q)=>{var{format:J,inspect:K,AggregateError:C}=z7(),U=globalThis.AggregateError||C,Y=Symbol("kIsNodeError"),Z=["string","function","number","object","Function","Object","boolean","bigint","symbol"],X=/^([A-Z][a-z0-9]*)+$/,E="__node_internal_",H={};function $(R,M){if(!R)throw new H.ERR_INTERNAL_ASSERTION(M)}function I(R){let M="",T=R.length,h=R[0]==="-"?1:0;for(;T>=h+4;T-=3)M=`_${R.slice(T-3,T)}${M}`;return`${R.slice(0,T)}${M}`}function N(R,M,T){if(typeof M=="function")return $(M.length<=T.length,`Code: ${R}; The provided arguments length (${T.length}) does not match the required ones (${M.length}).`),M(...T);let h=(M.match(/%[dfijoOs]/g)||[]).length;return $(h===T.length,`Code: ${R}; The provided arguments length (${T.length}) does not match the required ones (${h}).`),T.length===0?M:J(M,...T)}function F(R,M,T){T||(T=Error);class h extends T{constructor(...y){super(N(R,M,y))}toString(){return`${this.name} [${R}]: ${this.message}`}}Object.defineProperties(h.prototype,{name:{value:T.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${R}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),h.prototype.code=R,h.prototype[Y]=!0,H[R]=h}function V(R){let M=E+R.name;return Object.defineProperty(R,"name",{value:M}),R}function D(R,M){if(R&&M&&R!==M){if(Array.isArray(M.errors))return M.errors.push(R),M;let T=new U([M,R],M.message);return T.code=M.code,T}return R||M}var L=class extends Error{constructor(R="The operation was aborted",M=void 0){if(M!==void 0&&typeof M!="object")throw new H.ERR_INVALID_ARG_TYPE("options","Object",M);super(R,M),this.code="ABORT_ERR",this.name="AbortError"}};F("ERR_ASSERTION","%s",Error),F("ERR_INVALID_ARG_TYPE",(R,M,T)=>{$(typeof R=="string","'name' must be a string"),Array.isArray(M)||(M=[M]);let h="The ";R.endsWith(" argument")?h+=`${R} `:h+=`"${R}" ${R.includes(".")?"property":"argument"} `,h+="must be ";let y=[],g=[],f=[];for(let d of M)$(typeof d=="string","All expected entries have to be of type string"),Z.includes(d)?y.push(d.toLowerCase()):X.test(d)?g.push(d):($(d!=="object",'The value "object" should be written as "Object"'),f.push(d));if(g.length>0){let d=y.indexOf("object");d!==-1&&(y.splice(y,d,1),g.push("Object"))}if(y.length>0){switch(y.length){case 1:h+=`of type ${y[0]}`;break;case 2:h+=`one of type ${y[0]} or ${y[1]}`;break;default:{let d=y.pop();h+=`one of type ${y.join(", ")}, or ${d}`}}(g.length>0||f.length>0)&&(h+=" or ")}if(g.length>0){switch(g.length){case 1:h+=`an instance of ${g[0]}`;break;case 2:h+=`an instance of ${g[0]} or ${g[1]}`;break;default:{let d=g.pop();h+=`an instance of ${g.join(", ")}, or ${d}`}}f.length>0&&(h+=" or ")}switch(f.length){case 0:break;case 1:f[0].toLowerCase()!==f[0]&&(h+="an "),h+=`${f[0]}`;break;case 2:h+=`one of ${f[0]} or ${f[1]}`;break;default:{let d=f.pop();h+=`one of ${f.join(", ")}, or ${d}`}}if(T==null)h+=`. Received ${T}`;else if(typeof T=="function"&&T.name)h+=`. Received function ${T.name}`;else if(typeof T=="object"){var u;(u=T.constructor)!==null&&u!==void 0&&u.name?h+=`. Received an instance of ${T.constructor.name}`:h+=`. Received ${K(T,{depth:-1})}`}else{let d=K(T,{colors:!1});d.length>25&&(d=`${d.slice(0,25)}...`),h+=`. Received type ${typeof T} (${d})`}return h},TypeError),F("ERR_INVALID_ARG_VALUE",(R,M,T="is invalid")=>{let h=K(M);return h.length>128&&(h=h.slice(0,128)+"..."),`The ${R.includes(".")?"property":"argument"} '${R}' ${T}. Received ${h}`},TypeError),F("ERR_INVALID_RETURN_VALUE",(R,M,T)=>{var h;let y=T!=null&&(h=T.constructor)!==null&&h!==void 0&&h.name?`instance of ${T.constructor.name}`:`type ${typeof T}`;return`Expected ${R} to be returned from the "${M}" function but got ${y}.`},TypeError),F("ERR_MISSING_ARGS",(...R)=>{$(R.length>0,"At least one arg needs to be specified");let M,T=R.length;switch(R=(Array.isArray(R)?R:[R]).map((h)=>`"${h}"`).join(" or "),T){case 1:M+=`The ${R[0]} argument`;break;case 2:M+=`The ${R[0]} and ${R[1]} arguments`;break;default:{let h=R.pop();M+=`The ${R.join(", ")}, and ${h} arguments`}break}return`${M} must be specified`},TypeError),F("ERR_OUT_OF_RANGE",(R,M,T)=>{$(M,'Missing "range" argument');let h;return Number.isInteger(T)&&Math.abs(T)>4294967296?h=I(String(T)):typeof T=="bigint"?(h=String(T),(T>2n**32n||T<-(2n**32n))&&(h=I(h)),h+="n"):h=K(T),`The value of "${R}" is out of range. It must be ${M}. Received ${h}`},RangeError),F("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),F("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),F("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),F("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),F("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),F("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),F("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),F("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),F("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),F("ERR_STREAM_WRITE_AFTER_END","write after end",Error),F("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),Q.exports={AbortError:L,aggregateTwoErrors:V(D),hideStackFrames:V,codes:H}}),dW=k0((A,Q)=>{var{ArrayIsArray:J,ArrayPrototypeIncludes:K,ArrayPrototypeJoin:C,ArrayPrototypeMap:U,NumberIsInteger:Y,NumberIsNaN:Z,NumberMAX_SAFE_INTEGER:X,NumberMIN_SAFE_INTEGER:E,NumberParseInt:H,ObjectPrototypeHasOwnProperty:$,RegExpPrototypeExec:I,String:N,StringPrototypeToUpperCase:F,StringPrototypeTrim:V}=P8(),{hideStackFrames:D,codes:{ERR_SOCKET_BAD_PORT:L,ERR_INVALID_ARG_TYPE:R,ERR_INVALID_ARG_VALUE:M,ERR_OUT_OF_RANGE:T,ERR_UNKNOWN_SIGNAL:h}}=o6(),{normalizeEncoding:y}=z7(),{isAsyncFunction:g,isArrayBufferView:f}=z7().types,u={};function d(i){return i===(i|0)}function n(i){return i===i>>>0}var B=/^[0-7]+$/,q="must be a 32-bit unsigned integer or an octal string";function P(i,c,o){if(typeof i>"u"&&(i=o),typeof i=="string"){if(I(B,i)===null)throw new M(c,i,q);i=H(i,8)}return k(i,c),i}var O=D((i,c,o=E,C1=X)=>{if(typeof i!="number")throw new R(c,"number",i);if(!Y(i))throw new T(c,"an integer",i);if(iC1)throw new T(c,`>= ${o} && <= ${C1}`,i)}),w=D((i,c,o=-2147483648,C1=2147483647)=>{if(typeof i!="number")throw new R(c,"number",i);if(!Y(i))throw new T(c,"an integer",i);if(iC1)throw new T(c,`>= ${o} && <= ${C1}`,i)}),k=D((i,c,o=!1)=>{if(typeof i!="number")throw new R(c,"number",i);if(!Y(i))throw new T(c,"an integer",i);let C1=o?1:0,q1=4294967295;if(iq1)throw new T(c,`>= ${C1} && <= ${q1}`,i)});function S(i,c){if(typeof i!="string")throw new R(c,"string",i)}function _(i,c,o=void 0,C1){if(typeof i!="number")throw new R(c,"number",i);if(o!=null&&iC1||(o!=null||C1!=null)&&Z(i))throw new T(c,`${o!=null?`>= ${o}`:""}${o!=null&&C1!=null?" && ":""}${C1!=null?`<= ${C1}`:""}`,i)}var W=D((i,c,o)=>{if(!K(o,i)){let C1=C(U(o,(Z1)=>typeof Z1=="string"?`'${Z1}'`:N(Z1)),", "),q1="must be one of: "+C1;throw new M(c,i,q1)}});function j(i,c){if(typeof i!="boolean")throw new R(c,"boolean",i)}function b(i,c,o){return i==null||!$(i,c)?o:i[c]}var p=D((i,c,o=null)=>{let C1=b(o,"allowArray",!1),q1=b(o,"allowFunction",!1);if(!b(o,"nullable",!1)&&i===null||!C1&&J(i)||typeof i!="object"&&(!q1||typeof i!="function"))throw new R(c,"Object",i)}),s=D((i,c,o=0)=>{if(!J(i))throw new R(c,"Array",i);if(i.length{if(!f(i))throw new R(c,["Buffer","TypedArray","DataView"],i)});function Q1(i,c){let o=y(c),C1=i.length;if(o==="hex"&&C1%2!==0)throw new M("encoding",c,`is invalid for data of length ${C1}`)}function e(i,c="Port",o=!0){if(typeof i!="number"&&typeof i!="string"||typeof i=="string"&&V(i).length===0||+i!==+i>>>0||i>65535||i===0&&!o)throw new L(c,i,o);return i|0}var t=D((i,c)=>{if(i!==void 0&&(i===null||typeof i!="object"||!("aborted"in i)))throw new R(c,"AbortSignal",i)}),U1=D((i,c)=>{if(typeof i!="function")throw new R(c,"Function",i)}),O1=D((i,c)=>{if(typeof i!="function"||g(i))throw new R(c,"Function",i)}),E1=D((i,c)=>{if(i!==void 0)throw new R(c,"undefined",i)});function Y1(i,c,o){if(!K(o,i))throw new R(c,`('${C(o,"|")}')`,i)}Q.exports={isInt32:d,isUint32:n,parseFileMode:P,validateArray:s,validateBoolean:j,validateBuffer:A1,validateEncoding:Q1,validateFunction:U1,validateInt32:w,validateInteger:O,validateNumber:_,validateObject:p,validateOneOf:W,validatePlainFunction:O1,validatePort:e,validateSignalName:r,validateString:S,validateUint32:k,validateUndefined:E1,validateUnion:Y1,validateAbortSignal:t}}),Rl=k0((A,Q)=>{var J=Q.exports={},K,C;function U(){throw new Error("setTimeout has not been defined")}function Y(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?K=setTimeout:K=U}catch{K=U}try{typeof clearTimeout=="function"?C=clearTimeout:C=Y}catch{C=Y}})();function Z(L){if(K===setTimeout)return setTimeout(L,0);if((K===U||!K)&&setTimeout)return K=setTimeout,setTimeout(L,0);try{return K(L,0)}catch{try{return K.call(null,L,0)}catch{return K.call(this,L,0)}}}function X(L){if(C===clearTimeout)return clearTimeout(L);if((C===Y||!C)&&clearTimeout)return C=clearTimeout,clearTimeout(L);try{return C(L)}catch{try{return C.call(null,L)}catch{return C.call(this,L)}}}var E=[],H=!1,$,I=-1;function N(){!H||!$||(H=!1,$.length?E=$.concat(E):I=-1,E.length&&F())}function F(){if(!H){var L=Z(N);H=!0;for(var R=E.length;R;){for($=E,E=[];++I1)for(var M=1;MDl});VJ=RV(()=>{cW(V7,zJ(Rl())),Dl=zJ(Rl())}),MJ=k0((A,Q)=>{var{Symbol:J,SymbolAsyncIterator:K,SymbolIterator:C}=P8(),U=J("kDestroyed"),Y=J("kIsErrored"),Z=J("kIsReadable"),X=J("kIsDisturbed");function E(O,w=!1){var k;return!!(O&&typeof O.pipe=="function"&&typeof O.on=="function"&&(!w||typeof O.pause=="function"&&typeof O.resume=="function")&&(!O._writableState||((k=O._readableState)===null||k===void 0?void 0:k.readable)!==!1)&&(!O._writableState||O._readableState))}function H(O){var w;return!!(O&&typeof O.write=="function"&&typeof O.on=="function"&&(!O._readableState||((w=O._writableState)===null||w===void 0?void 0:w.writable)!==!1))}function $(O){return!!(O&&typeof O.pipe=="function"&&O._readableState&&typeof O.on=="function"&&typeof O.write=="function")}function I(O){return O&&(O._readableState||O._writableState||typeof O.write=="function"&&typeof O.on=="function"||typeof O.pipe=="function"&&typeof O.on=="function")}function N(O,w){return O==null?!1:w===!0?typeof O[K]=="function":w===!1?typeof O[C]=="function":typeof O[K]=="function"||typeof O[C]=="function"}function F(O){if(!I(O))return null;let{_writableState:w,_readableState:k}=O,S=w||k;return!!(O.destroyed||O[U]||S!=null&&S.destroyed)}function V(O){if(!H(O))return null;if(O.writableEnded===!0)return!0;let w=O._writableState;return w!=null&&w.errored?!1:typeof w?.ended!="boolean"?null:w.ended}function D(O,w){if(!H(O))return null;if(O.writableFinished===!0)return!0;let k=O._writableState;return k!=null&&k.errored?!1:typeof k?.finished!="boolean"?null:!!(k.finished||w===!1&&k.ended===!0&&k.length===0)}function L(O){if(!E(O))return null;if(O.readableEnded===!0)return!0;let w=O._readableState;return!w||w.errored?!1:typeof w?.ended!="boolean"?null:w.ended}function R(O,w){if(!E(O))return null;let k=O._readableState;return k!=null&&k.errored?!1:typeof k?.endEmitted!="boolean"?null:!!(k.endEmitted||w===!1&&k.ended===!0&&k.length===0)}function M(O){return O&&O[Z]!=null?O[Z]:typeof O?.readable!="boolean"?null:F(O)?!1:E(O)&&O.readable&&!R(O)}function T(O){return typeof O?.writable!="boolean"?null:F(O)?!1:H(O)&&O.writable&&!V(O)}function h(O,w){return I(O)?F(O)?!0:!(w?.readable!==!1&&M(O)||w?.writable!==!1&&T(O)):null}function y(O){var w,k;return I(O)?O.writableErrored?O.writableErrored:(w=(k=O._writableState)===null||k===void 0?void 0:k.errored)!==null&&w!==void 0?w:null:null}function g(O){var w,k;return I(O)?O.readableErrored?O.readableErrored:(w=(k=O._readableState)===null||k===void 0?void 0:k.errored)!==null&&w!==void 0?w:null:null}function f(O){if(!I(O))return null;if(typeof O.closed=="boolean")return O.closed;let{_writableState:w,_readableState:k}=O;return typeof w?.closed=="boolean"||typeof k?.closed=="boolean"?w?.closed||k?.closed:typeof O._closed=="boolean"&&u(O)?O._closed:null}function u(O){return typeof O._closed=="boolean"&&typeof O._defaultKeepAlive=="boolean"&&typeof O._removedConnection=="boolean"&&typeof O._removedContLen=="boolean"}function d(O){return typeof O._sent100=="boolean"&&u(O)}function n(O){var w;return typeof O._consuming=="boolean"&&typeof O._dumped=="boolean"&&((w=O.req)===null||w===void 0?void 0:w.upgradeOrConnect)===void 0}function B(O){if(!I(O))return null;let{_writableState:w,_readableState:k}=O,S=w||k;return!S&&d(O)||!!(S&&S.autoDestroy&&S.emitClose&&S.closed===!1)}function q(O){var w;return!!(O&&((w=O[X])!==null&&w!==void 0?w:O.readableDidRead||O.readableAborted))}function P(O){var w,k,S,_,W,j,b,p,s,r;return!!(O&&((w=(k=(S=(_=(W=(j=O[Y])!==null&&j!==void 0?j:O.readableErrored)!==null&&W!==void 0?W:O.writableErrored)!==null&&_!==void 0?_:(b=O._readableState)===null||b===void 0?void 0:b.errorEmitted)!==null&&S!==void 0?S:(p=O._writableState)===null||p===void 0?void 0:p.errorEmitted)!==null&&k!==void 0?k:(s=O._readableState)===null||s===void 0?void 0:s.errored)!==null&&w!==void 0?w:(r=O._writableState)===null||r===void 0?void 0:r.errored))}Q.exports={kDestroyed:U,isDisturbed:q,kIsDisturbed:X,isErrored:P,kIsErrored:Y,isReadable:M,kIsReadable:Z,isClosed:f,isDestroyed:F,isDuplexNodeStream:$,isFinished:h,isIterable:N,isReadableNodeStream:E,isReadableEnded:L,isReadableFinished:R,isReadableErrored:g,isNodeStream:I,isWritable:T,isWritableNodeStream:H,isWritableEnded:V,isWritableFinished:D,isWritableErrored:y,isServerRequest:n,isServerResponse:d,willEmitClose:B}}),wJ=k0((A,Q)=>{var J=(VJ(),N9(V7)),{AbortError:K,codes:C}=o6(),{ERR_INVALID_ARG_TYPE:U,ERR_STREAM_PREMATURE_CLOSE:Y}=C,{kEmptyObject:Z,once:X}=z7(),{validateAbortSignal:E,validateFunction:H,validateObject:$}=dW(),{Promise:I}=P8(),{isClosed:N,isReadable:F,isReadableNodeStream:V,isReadableFinished:D,isReadableErrored:L,isWritable:R,isWritableNodeStream:M,isWritableFinished:T,isWritableErrored:h,isNodeStream:y,willEmitClose:g}=MJ();function f(B){return B.setHeader&&typeof B.abort=="function"}var u=()=>{};function d(B,q,P){var O,w;arguments.length===2?(P=q,q=Z):q==null?q=Z:$(q,"options"),H(P,"callback"),E(q.signal,"options.signal"),P=X(P);let k=(O=q.readable)!==null&&O!==void 0?O:V(B),S=(w=q.writable)!==null&&w!==void 0?w:M(B);if(!y(B))throw new U("stream","Stream",B);let{_writableState:_,_readableState:W}=B,j=()=>{B.writable||s()},b=g(B)&&V(B)===k&&M(B)===S,p=T(B,!1),s=()=>{p=!0,B.destroyed&&(b=!1),!(b&&(!B.readable||k))&&(!k||r)&&P.call(B)},r=D(B,!1),A1=()=>{r=!0,B.destroyed&&(b=!1),!(b&&(!B.writable||S))&&(!S||p)&&P.call(B)},Q1=(E1)=>{P.call(B,E1)},e=N(B),t=()=>{e=!0;let E1=h(B)||L(B);if(E1&&typeof E1!="boolean")return P.call(B,E1);if(k&&!r&&V(B,!0)&&!D(B,!1))return P.call(B,new Y);if(S&&!p&&!T(B,!1))return P.call(B,new Y);P.call(B)},U1=()=>{B.req.on("finish",s)};f(B)?(B.on("complete",s),b||B.on("abort",t),B.req?U1():B.on("request",U1)):S&&!_&&(B.on("end",j),B.on("close",j)),!b&&typeof B.aborted=="boolean"&&B.on("aborted",t),B.on("end",A1),B.on("finish",s),q.error!==!1&&B.on("error",Q1),B.on("close",t),e?J.nextTick(t):_!=null&&_.errorEmitted||W!=null&&W.errorEmitted?b||J.nextTick(t):(!k&&(!b||F(B))&&(p||R(B)===!1)||!S&&(!b||R(B))&&(r||F(B)===!1)||W&&B.req&&B.aborted)&&J.nextTick(t);let O1=()=>{P=u,B.removeListener("aborted",t),B.removeListener("complete",s),B.removeListener("abort",t),B.removeListener("request",U1),B.req&&B.req.removeListener("finish",s),B.removeListener("end",j),B.removeListener("close",j),B.removeListener("finish",s),B.removeListener("end",A1),B.removeListener("error",Q1),B.removeListener("close",t)};if(q.signal&&!e){let E1=()=>{let Y1=P;O1(),Y1.call(B,new K(void 0,{cause:q.signal.reason}))};if(q.signal.aborted)J.nextTick(E1);else{let Y1=P;P=X((...i)=>{q.signal.removeEventListener("abort",E1),Y1.apply(B,i)}),q.signal.addEventListener("abort",E1)}}return O1}function n(B,q){return new I((P,O)=>{d(B,q,(w)=>{w?O(w):P()})})}Q.exports=d,Q.exports.finished=n}),v$1=k0((A,Q)=>{var J=globalThis.AbortController||zV().AbortController,{codes:{ERR_INVALID_ARG_TYPE:K,ERR_MISSING_ARGS:C,ERR_OUT_OF_RANGE:U},AbortError:Y}=o6(),{validateAbortSignal:Z,validateInteger:X,validateObject:E}=dW(),H=P8().Symbol("kWeak"),{finished:$}=wJ(),{ArrayPrototypePush:I,MathFloor:N,Number:F,NumberIsNaN:V,Promise:D,PromiseReject:L,PromisePrototypeThen:R,Symbol:M}=P8(),T=M("kEmpty"),h=M("kEof");function y(W,j){if(typeof W!="function")throw new K("fn",["Function","AsyncFunction"],W);j!=null&&E(j,"options"),j?.signal!=null&&Z(j.signal,"options.signal");let b=1;return j?.concurrency!=null&&(b=N(j.concurrency)),X(b,"concurrency",1),async function*(){var p,s;let r=new J,A1=this,Q1=[],e=r.signal,t={signal:e},U1=()=>r.abort();j!=null&&(p=j.signal)!==null&&p!==void 0&&p.aborted&&U1(),j==null||(s=j.signal)===null||s===void 0||s.addEventListener("abort",U1);let O1,E1,Y1=!1;function i(){Y1=!0}async function c(){try{for await(let q1 of A1){var o;if(Y1)return;if(e.aborted)throw new Y;try{q1=W(q1,t)}catch(Z1){q1=L(Z1)}q1!==T&&(typeof((o=q1)===null||o===void 0?void 0:o.catch)=="function"&&q1.catch(i),Q1.push(q1),O1&&(O1(),O1=null),!Y1&&Q1.length&&Q1.length>=b&&await new D((Z1)=>{E1=Z1}))}Q1.push(h)}catch(q1){let Z1=L(q1);R(Z1,void 0,i),Q1.push(Z1)}finally{var C1;Y1=!0,O1&&(O1(),O1=null),j==null||(C1=j.signal)===null||C1===void 0||C1.removeEventListener("abort",U1)}}c();try{for(;;){for(;Q1.length>0;){let o=await Q1[0];if(o===h)return;if(e.aborted)throw new Y;o!==T&&(yield o),Q1.shift(),E1&&(E1(),E1=null)}await new D((o)=>{O1=o})}}finally{r.abort(),Y1=!0,E1&&(E1(),E1=null)}}.call(this)}function g(W=void 0){return W!=null&&E(W,"options"),W?.signal!=null&&Z(W.signal,"options.signal"),async function*(){let j=0;for await(let p of this){var b;if(W!=null&&(b=W.signal)!==null&&b!==void 0&&b.aborted)throw new Y({cause:W.signal.reason});yield[j++,p]}}.call(this)}async function f(W,j=void 0){for await(let b of B.call(this,W,j))return!0;return!1}async function u(W,j=void 0){if(typeof W!="function")throw new K("fn",["Function","AsyncFunction"],W);return!await f.call(this,async(...b)=>!await W(...b),j)}async function d(W,j){for await(let b of B.call(this,W,j))return b}async function n(W,j){if(typeof W!="function")throw new K("fn",["Function","AsyncFunction"],W);async function b(p,s){return await W(p,s),T}for await(let p of y.call(this,b,j));}function B(W,j){if(typeof W!="function")throw new K("fn",["Function","AsyncFunction"],W);async function b(p,s){return await W(p,s)?p:T}return y.call(this,b,j)}var q=class extends C{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function P(W,j,b){var p;if(typeof W!="function")throw new K("reducer",["Function","AsyncFunction"],W);b!=null&&E(b,"options"),b?.signal!=null&&Z(b.signal,"options.signal");let s=arguments.length>1;if(b!=null&&(p=b.signal)!==null&&p!==void 0&&p.aborted){let t=new Y(void 0,{cause:b.signal.reason});throw this.once("error",()=>{}),await $(this.destroy(t)),t}let r=new J,A1=r.signal;if(b!=null&&b.signal){let t={once:!0,[H]:this};b.signal.addEventListener("abort",()=>r.abort(),t)}let Q1=!1;try{for await(let t of this){var e;if(Q1=!0,b!=null&&(e=b.signal)!==null&&e!==void 0&&e.aborted)throw new Y;s?j=await W(j,t,{signal:A1}):(j=t,s=!0)}if(!Q1&&!s)throw new q}finally{r.abort()}return j}async function O(W){W!=null&&E(W,"options"),W?.signal!=null&&Z(W.signal,"options.signal");let j=[];for await(let p of this){var b;if(W!=null&&(b=W.signal)!==null&&b!==void 0&&b.aborted)throw new Y(void 0,{cause:W.signal.reason});I(j,p)}return j}function w(W,j){let b=y.call(this,W,j);return async function*(){for await(let p of b)yield*p}.call(this)}function k(W){if(W=F(W),V(W))return 0;if(W<0)throw new U("number",">= 0",W);return W}function S(W,j=void 0){return j!=null&&E(j,"options"),j?.signal!=null&&Z(j.signal,"options.signal"),W=k(W),async function*(){var b;if(j!=null&&(b=j.signal)!==null&&b!==void 0&&b.aborted)throw new Y;for await(let s of this){var p;if(j!=null&&(p=j.signal)!==null&&p!==void 0&&p.aborted)throw new Y;W--<=0&&(yield s)}}.call(this)}function _(W,j=void 0){return j!=null&&E(j,"options"),j?.signal!=null&&Z(j.signal,"options.signal"),W=k(W),async function*(){var b;if(j!=null&&(b=j.signal)!==null&&b!==void 0&&b.aborted)throw new Y;for await(let s of this){var p;if(j!=null&&(p=j.signal)!==null&&p!==void 0&&p.aborted)throw new Y;if(W-- >0)yield s;else return}}.call(this)}Q.exports.streamReturningOperators={asIndexedPairs:g,drop:S,filter:B,flatMap:w,map:y,take:_},Q.exports.promiseReturningOperators={every:u,forEach:n,reduce:P,toArray:O,some:f,find:d}}),$Y=k0((A,Q)=>{var J=(VJ(),N9(V7)),{aggregateTwoErrors:K,codes:{ERR_MULTIPLE_CALLBACK:C},AbortError:U}=o6(),{Symbol:Y}=P8(),{kDestroyed:Z,isDestroyed:X,isFinished:E,isServerRequest:H}=MJ(),$=Y("kDestroy"),I=Y("kConstruct");function N(B,q,P){B&&(B.stack,q&&!q.errored&&(q.errored=B),P&&!P.errored&&(P.errored=B))}function F(B,q){let P=this._readableState,O=this._writableState,w=O||P;return O&&O.destroyed||P&&P.destroyed?(typeof q=="function"&&q(),this):(N(B,O,P),O&&(O.destroyed=!0),P&&(P.destroyed=!0),w.constructed?V(this,B,q):this.once($,function(k){V(this,K(k,B),q)}),this)}function V(B,q,P){let O=!1;function w(k){if(O)return;O=!0;let{_readableState:S,_writableState:_}=B;N(k,_,S),_&&(_.closed=!0),S&&(S.closed=!0),typeof P=="function"&&P(k),k?J.nextTick(D,B,k):J.nextTick(L,B)}try{B._destroy(q||null,w)}catch(k){w(k)}}function D(B,q){R(B,q),L(B)}function L(B){let{_readableState:q,_writableState:P}=B;P&&(P.closeEmitted=!0),q&&(q.closeEmitted=!0),(P&&P.emitClose||q&&q.emitClose)&&B.emit("close")}function R(B,q){let{_readableState:P,_writableState:O}=B;O&&O.errorEmitted||P&&P.errorEmitted||(O&&(O.errorEmitted=!0),P&&(P.errorEmitted=!0),B.emit("error",q))}function M(){let B=this._readableState,q=this._writableState;B&&(B.constructed=!0,B.closed=!1,B.closeEmitted=!1,B.destroyed=!1,B.errored=null,B.errorEmitted=!1,B.reading=!1,B.ended=B.readable===!1,B.endEmitted=B.readable===!1),q&&(q.constructed=!0,q.destroyed=!1,q.closed=!1,q.closeEmitted=!1,q.errored=null,q.errorEmitted=!1,q.finalCalled=!1,q.prefinished=!1,q.ended=q.writable===!1,q.ending=q.writable===!1,q.finished=q.writable===!1)}function T(B,q,P){let{_readableState:O,_writableState:w}=B;if(w&&w.destroyed||O&&O.destroyed)return this;O&&O.autoDestroy||w&&w.autoDestroy?B.destroy(q):q&&(q.stack,w&&!w.errored&&(w.errored=q),O&&!O.errored&&(O.errored=q),P?J.nextTick(R,B,q):R(B,q))}function h(B,q){if(typeof B._construct!="function")return;let{_readableState:P,_writableState:O}=B;P&&(P.constructed=!1),O&&(O.constructed=!1),B.once(I,q),!(B.listenerCount(I)>1)&&J.nextTick(y,B)}function y(B){let q=!1;function P(O){if(q){T(B,O??new C);return}q=!0;let{_readableState:w,_writableState:k}=B,S=k||w;w&&(w.constructed=!0),k&&(k.constructed=!0),S.destroyed?B.emit($,O):O?T(B,O,!0):J.nextTick(g,B)}try{B._construct(P)}catch(O){P(O)}}function g(B){B.emit(I)}function f(B){return B&&B.setHeader&&typeof B.abort=="function"}function u(B){B.emit("close")}function d(B,q){B.emit("error",q),J.nextTick(u,B)}function n(B,q){!B||X(B)||(!q&&!E(B)&&(q=new U),H(B)?(B.socket=null,B.destroy(q)):f(B)?B.abort():f(B.req)?B.req.abort():typeof B.destroy=="function"?B.destroy(q):typeof B.close=="function"?B.close():q?J.nextTick(d,B,q):J.nextTick(u,B),B.destroyed||(B[Z]=!0))}Q.exports={construct:h,destroyer:n,destroy:F,undestroy:M,errorOrDestroy:T}}),DV=k0((A,Q)=>{var J=typeof Reflect=="object"?Reflect:null,K=J&&typeof J.apply=="function"?J.apply:function(y,g,f){return Function.prototype.apply.call(y,g,f)},C;J&&typeof J.ownKeys=="function"?C=J.ownKeys:Object.getOwnPropertySymbols?C=function(y){return Object.getOwnPropertyNames(y).concat(Object.getOwnPropertySymbols(y))}:C=function(y){return Object.getOwnPropertyNames(y)};function U(y){console&&console.warn&&console.warn(y)}var Y=Number.isNaN||function(y){return y!==y};function Z(){Z.init.call(this)}Q.exports=Z,Q.exports.once=M,Z.EventEmitter=Z,Z.prototype._events=void 0,Z.prototype._eventsCount=0,Z.prototype._maxListeners=void 0;var X=10;function E(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(Z,"defaultMaxListeners",{enumerable:!0,get:function(){return X},set:function(y){if(typeof y!="number"||y<0||Y(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");X=y}}),Z.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Z.prototype.setMaxListeners=function(y){if(typeof y!="number"||y<0||Y(y))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+y+".");return this._maxListeners=y,this};function H(y){return y._maxListeners===void 0?Z.defaultMaxListeners:y._maxListeners}Z.prototype.getMaxListeners=function(){return H(this)},Z.prototype.emit=function(y){for(var g=[],f=1;f0&&(n=g[0]),n instanceof Error)throw n;var B=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw B.context=n,B}var q=d[y];if(q===void 0)return!1;if(typeof q=="function")K(q,this,g);else for(var P=q.length,O=D(q,P),f=0;f0&&B.length>d&&!B.warned){B.warned=!0;var q=new Error("Possible EventEmitter memory leak detected. "+B.length+" "+String(g)+" listeners added. Use emitter.setMaxListeners() to increase limit");q.name="MaxListenersExceededWarning",q.emitter=y,q.type=g,q.count=B.length,U(q)}return y}Z.prototype.addListener=function(y,g){return $(this,y,g,!1)},Z.prototype.on=Z.prototype.addListener,Z.prototype.prependListener=function(y,g){return $(this,y,g,!0)};function I(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function N(y,g,f){var u={fired:!1,wrapFn:void 0,target:y,type:g,listener:f},d=I.bind(u);return d.listener=f,u.wrapFn=d,d}Z.prototype.once=function(y,g){return E(g),this.on(y,N(this,y,g)),this},Z.prototype.prependOnceListener=function(y,g){return E(g),this.prependListener(y,N(this,y,g)),this},Z.prototype.removeListener=function(y,g){var f,u,d,n,B;if(E(g),u=this._events,u===void 0)return this;if(f=u[y],f===void 0)return this;if(f===g||f.listener===g)--this._eventsCount===0?this._events=Object.create(null):(delete u[y],u.removeListener&&this.emit("removeListener",y,f.listener||g));else if(typeof f!="function"){for(d=-1,n=f.length-1;n>=0;n--)if(f[n]===g||f[n].listener===g){B=f[n].listener,d=n;break}if(d<0)return this;d===0?f.shift():L(f,d),f.length===1&&(u[y]=f[0]),u.removeListener!==void 0&&this.emit("removeListener",y,B||g)}return this},Z.prototype.off=Z.prototype.removeListener,Z.prototype.removeAllListeners=function(y){var g,f,u;if(f=this._events,f===void 0)return this;if(f.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):f[y]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete f[y]),this;if(arguments.length===0){var d=Object.keys(f),n;for(u=0;u=0;u--)this.removeListener(y,g[u]);return this};function F(y,g,f){var u=y._events;if(u===void 0)return[];var d=u[g];return d===void 0?[]:typeof d=="function"?f?[d.listener||d]:[d]:f?R(d):D(d,d.length)}Z.prototype.listeners=function(y){return F(this,y,!0)},Z.prototype.rawListeners=function(y){return F(this,y,!1)},Z.listenerCount=function(y,g){return typeof y.listenerCount=="function"?y.listenerCount(g):V.call(y,g)},Z.prototype.listenerCount=V;function V(y){var g=this._events;if(g!==void 0){var f=g[y];if(typeof f=="function")return 1;if(f!==void 0)return f.length}return 0}Z.prototype.eventNames=function(){return this._eventsCount>0?C(this._events):[]};function D(y,g){for(var f=new Array(g),u=0;u{var{ArrayIsArray:J,ObjectSetPrototypeOf:K}=P8(),{EventEmitter:C}=DV();function U(Z){C.call(this,Z)}K(U.prototype,C.prototype),K(U,C),U.prototype.pipe=function(Z,X){let E=this;function H(L){Z.writable&&Z.write(L)===!1&&E.pause&&E.pause()}E.on("data",H);function $(){E.readable&&E.resume&&E.resume()}Z.on("drain",$),!Z._isStdio&&(!X||X.end!==!1)&&(E.on("end",N),E.on("close",F));let I=!1;function N(){I||(I=!0,Z.end())}function F(){I||(I=!0,typeof Z.destroy=="function"&&Z.destroy())}function V(L){D(),C.listenerCount(this,"error")===0&&this.emit("error",L)}Y(E,"error",V),Y(Z,"error",V);function D(){E.removeListener("data",H),Z.removeListener("drain",$),E.removeListener("end",N),E.removeListener("close",F),E.removeListener("error",V),Z.removeListener("error",V),E.removeListener("end",D),E.removeListener("close",D),Z.removeListener("close",D)}return E.on("end",D),E.on("close",D),Z.on("close",D),Z.emit("pipe",E),Z};function Y(Z,X,E){if(typeof Z.prependListener=="function")return Z.prependListener(X,E);!Z._events||!Z._events[X]?Z.on(X,E):J(Z._events[X])?Z._events[X].unshift(E):Z._events[X]=[E,Z._events[X]]}Q.exports={Stream:U,prependListener:Y}}),MV=k0((A,Q)=>{var{AbortError:J,codes:K}=o6(),C=wJ(),{ERR_INVALID_ARG_TYPE:U}=K,Y=(X,E)=>{if(typeof X!="object"||!("aborted"in X))throw new U(E,"AbortSignal",X)};function Z(X){return!!(X&&typeof X.pipe=="function")}Q.exports.addAbortSignal=function(X,E){if(Y(X,"signal"),!Z(E))throw new U("stream","stream.Stream",E);return Q.exports.addAbortSignalNoValidate(X,E)},Q.exports.addAbortSignalNoValidate=function(X,E){if(typeof X!="object"||!("aborted"in X))return E;let H=()=>{E.destroy(new J(void 0,{cause:X.reason}))};return X.aborted?H():(X.addEventListener("abort",H),C(E,()=>X.removeEventListener("abort",H))),E}}),x$1=k0((A,Q)=>{var{StringPrototypeSlice:J,SymbolIterator:K,TypedArrayPrototypeSet:C,Uint8Array:U}=P8(),{Buffer:Y}=W3(),{inspect:Z}=z7();Q.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(X){let E={data:X,next:null};this.length>0?this.tail.next=E:this.head=E,this.tail=E,++this.length}unshift(X){let E={data:X,next:this.head};this.length===0&&(this.tail=E),this.head=E,++this.length}shift(){if(this.length===0)return;let X=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,X}clear(){this.head=this.tail=null,this.length=0}join(X){if(this.length===0)return"";let E=this.head,H=""+E.data;for(;(E=E.next)!==null;)H+=X+E.data;return H}concat(X){if(this.length===0)return Y.alloc(0);let E=Y.allocUnsafe(X>>>0),H=this.head,$=0;for(;H;)C(E,H.data,$),$+=H.data.length,H=H.next;return E}consume(X,E){let H=this.head.data;if(XI.length)E+=I,X-=I.length;else{X===I.length?(E+=I,++$,H.next?this.head=H.next:this.head=this.tail=null):(E+=J(I,0,X),this.head=H,H.data=J(I,X));break}++$}while((H=H.next)!==null);return this.length-=$,E}_getBuffer(X){let E=Y.allocUnsafe(X),H=X,$=this.head,I=0;do{let N=$.data;if(X>N.length)C(E,N,H-X),X-=N.length;else{X===N.length?(C(E,N,H-X),++I,$.next?this.head=$.next:this.head=this.tail=null):(C(E,new U(N.buffer,N.byteOffset,X),H-X),this.head=$,$.data=N.slice(X));break}++I}while(($=$.next)!==null);return this.length-=I,E}[Symbol.for("nodejs.util.inspect.custom")](X,E){return Z(this,{...E,depth:0,customInspect:!1})}}}),wV=k0((A,Q)=>{var{MathFloor:J,NumberIsInteger:K}=P8(),{ERR_INVALID_ARG_VALUE:C}=o6().codes;function U(X,E,H){return X.highWaterMark!=null?X.highWaterMark:E?X[H]:null}function Y(X){return X?16:16384}function Z(X,E,H,$){let I=U(E,$,H);if(I!=null){if(!K(I)||I<0){let N=$?`options.${H}`:"options.highWaterMark";throw new C(N,I)}return J(I)}return Y(X.objectMode)}Q.exports={getHighWaterMark:Z,getDefaultHighWaterMark:Y}}),y$1=k0((A,Q)=>{var J=W3(),K=J.Buffer;function C(Y,Z){for(var X in Y)Z[X]=Y[X]}K.from&&K.alloc&&K.allocUnsafe&&K.allocUnsafeSlow?Q.exports=J:(C(J,A),A.Buffer=U);function U(Y,Z,X){return K(Y,Z,X)}U.prototype=Object.create(K.prototype),C(K,U),U.from=function(Y,Z,X){if(typeof Y=="number")throw new TypeError("Argument must not be a number");return K(Y,Z,X)},U.alloc=function(Y,Z,X){if(typeof Y!="number")throw new TypeError("Argument must be a number");var E=K(Y);return Z!==void 0?typeof X=="string"?E.fill(Z,X):E.fill(Z):E.fill(0),E},U.allocUnsafe=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return K(Y)},U.allocUnsafeSlow=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return J.SlowBuffer(Y)}}),h$1=k0((A)=>{var Q=y$1().Buffer,J=Q.isEncoding||function(R){switch(R=""+R,R&&R.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function K(R){if(!R)return"utf8";for(var M;;)switch(R){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return R;default:if(M)return;R=(""+R).toLowerCase(),M=!0}}function C(R){var M=K(R);if(typeof M!="string"&&(Q.isEncoding===J||!J(R)))throw new Error("Unknown encoding: "+R);return M||R}A.StringDecoder=U;function U(R){this.encoding=C(R);var M;switch(this.encoding){case"utf16le":this.text=I,this.end=N,M=4;break;case"utf8":this.fillLast=E,M=4;break;case"base64":this.text=F,this.end=V,M=3;break;default:this.write=D,this.end=L;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Q.allocUnsafe(M)}U.prototype.write=function(R){if(R.length===0)return"";var M,T;if(this.lastNeed){if(M=this.fillLast(R),M===void 0)return"";T=this.lastNeed,this.lastNeed=0}else T=0;return T>5===6?2:R>>4===14?3:R>>3===30?4:R>>6===2?-1:-2}function Z(R,M,T){var h=M.length-1;if(h=0?(y>0&&(R.lastNeed=y-1),y):--h=0?(y>0&&(R.lastNeed=y-2),y):--h=0?(y>0&&(y===2?y=0:R.lastNeed=y-3),y):0))}function X(R,M,T){if((M[0]&192)!==128)return R.lastNeed=0,"�";if(R.lastNeed>1&&M.length>1){if((M[1]&192)!==128)return R.lastNeed=1,"�";if(R.lastNeed>2&&M.length>2&&(M[2]&192)!==128)return R.lastNeed=2,"�"}}function E(R){var M=this.lastTotal-this.lastNeed,T=X(this,R,M);if(T!==void 0)return T;if(this.lastNeed<=R.length)return R.copy(this.lastChar,M,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);R.copy(this.lastChar,M,0,R.length),this.lastNeed-=R.length}function H(R,M){var T=Z(this,R,M);if(!this.lastNeed)return R.toString("utf8",M);this.lastTotal=T;var h=R.length-(T-this.lastNeed);return R.copy(this.lastChar,0,h),R.toString("utf8",M,h)}function $(R){var M=R&&R.length?this.write(R):"";return this.lastNeed?M+"�":M}function I(R,M){if((R.length-M)%2===0){var T=R.toString("utf16le",M);if(T){var h=T.charCodeAt(T.length-1);if(h>=55296&&h<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=R[R.length-2],this.lastChar[1]=R[R.length-1],T.slice(0,-1)}return T}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=R[R.length-1],R.toString("utf16le",M,R.length-1)}function N(R){var M=R&&R.length?this.write(R):"";if(this.lastNeed){var T=this.lastTotal-this.lastNeed;return M+this.lastChar.toString("utf16le",0,T)}return M}function F(R,M){var T=(R.length-M)%3;return T===0?R.toString("base64",M):(this.lastNeed=3-T,this.lastTotal=3,T===1?this.lastChar[0]=R[R.length-1]:(this.lastChar[0]=R[R.length-2],this.lastChar[1]=R[R.length-1]),R.toString("base64",M,R.length-T))}function V(R){var M=R&&R.length?this.write(R):"";return this.lastNeed?M+this.lastChar.toString("base64",0,3-this.lastNeed):M}function D(R){return R.toString(this.encoding)}function L(R){return R&&R.length?this.write(R):""}}),Vl=k0((A,Q)=>{var J=(VJ(),N9(V7)),{PromisePrototypeThen:K,SymbolAsyncIterator:C,SymbolIterator:U}=P8(),{Buffer:Y}=W3(),{ERR_INVALID_ARG_TYPE:Z,ERR_STREAM_NULL_VALUES:X}=o6().codes;function E(H,$,I){let N;if(typeof $=="string"||$ instanceof Y)return new H({objectMode:!0,...I,read(){this.push($),this.push(null)}});let F;if($&&$[C])F=!0,N=$[C]();else if($&&$[U])F=!1,N=$[U]();else throw new Z("iterable",["Iterable"],$);let V=new H({objectMode:!0,highWaterMark:1,...I}),D=!1;V._read=function(){D||(D=!0,R())},V._destroy=function(M,T){K(L(M),()=>J.nextTick(T,M),(h)=>J.nextTick(T,h||M))};async function L(M){let T=M!=null,h=typeof N.throw=="function";if(T&&h){let{value:y,done:g}=await N.throw(M);if(await y,g)return}if(typeof N.return=="function"){let{value:y}=await N.return();await y}}async function R(){for(;;){try{let{value:M,done:T}=F?await N.next():N.next();if(T)V.push(null);else{let h=M&&typeof M.then=="function"?await M:M;if(h===null)throw D=!1,new X;if(V.push(h))continue;D=!1}}catch(M){V.destroy(M)}break}}return V}Q.exports=E}),lW=k0((A,Q)=>{var J=(VJ(),N9(V7)),{ArrayPrototypeIndexOf:K,NumberIsInteger:C,NumberIsNaN:U,NumberParseInt:Y,ObjectDefineProperties:Z,ObjectKeys:X,ObjectSetPrototypeOf:E,Promise:H,SafeSet:$,SymbolAsyncIterator:I,Symbol:N}=P8();Q.exports=b,b.ReadableState=j;var{EventEmitter:F}=DV(),{Stream:V,prependListener:D}=VV(),{Buffer:L}=W3(),{addAbortSignal:R}=MV(),M=wJ(),T=z7().debuglog("stream",(G)=>{T=G}),h=x$1(),y=$Y(),{getHighWaterMark:g,getDefaultHighWaterMark:f}=wV(),{aggregateTwoErrors:u,codes:{ERR_INVALID_ARG_TYPE:d,ERR_METHOD_NOT_IMPLEMENTED:n,ERR_OUT_OF_RANGE:B,ERR_STREAM_PUSH_AFTER_EOF:q,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:P}}=o6(),{validateObject:O}=dW(),w=N("kPaused"),{StringDecoder:k}=h$1(),S=Vl();E(b.prototype,V.prototype),E(b,V);var _=()=>{},{errorOrDestroy:W}=y;function j(G,z,x){typeof x!="boolean"&&(x=z instanceof D7()),this.objectMode=!!(G&&G.objectMode),x&&(this.objectMode=this.objectMode||!!(G&&G.readableObjectMode)),this.highWaterMark=G?g(this,G,"readableHighWaterMark",x):f(!1),this.buffer=new h,this.length=0,this.pipes=[],this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.constructed=!0,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this[w]=null,this.errorEmitted=!1,this.emitClose=!G||G.emitClose!==!1,this.autoDestroy=!G||G.autoDestroy!==!1,this.destroyed=!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this.defaultEncoding=G&&G.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.multiAwaitDrain=!1,this.readingMore=!1,this.dataEmitted=!1,this.decoder=null,this.encoding=null,G&&G.encoding&&(this.decoder=new k(G.encoding),this.encoding=G.encoding)}function b(G){if(!(this instanceof b))return new b(G);let z=this instanceof D7();this._readableState=new j(G,this,z),G&&(typeof G.read=="function"&&(this._read=G.read),typeof G.destroy=="function"&&(this._destroy=G.destroy),typeof G.construct=="function"&&(this._construct=G.construct),G.signal&&!z&&R(G.signal,this)),V.call(this,G),y.construct(this,()=>{this._readableState.needReadable&&O1(this,this._readableState)})}b.prototype.destroy=y.destroy,b.prototype._undestroy=y.undestroy,b.prototype._destroy=function(G,z){z(G)},b.prototype[F.captureRejectionSymbol]=function(G){this.destroy(G)},b.prototype.push=function(G,z){return p(this,G,z,!1)},b.prototype.unshift=function(G,z){return p(this,G,z,!0)};function p(G,z,x,m){T("readableAddChunk",z);let l=G._readableState,a;if(l.objectMode||(typeof z=="string"?(x=x||l.defaultEncoding,l.encoding!==x&&(m&&l.encoding?z=L.from(z,x).toString(l.encoding):(z=L.from(z,x),x=""))):z instanceof L?x="":V._isUint8Array(z)?(z=V._uint8ArrayToBuffer(z),x=""):z!=null&&(a=new d("chunk",["string","Buffer","Uint8Array"],z))),a)W(G,a);else if(z===null)l.reading=!1,e(G,l);else if(l.objectMode||z&&z.length>0)if(m)if(l.endEmitted)W(G,new P);else{if(l.destroyed||l.errored)return!1;s(G,l,z,!0)}else if(l.ended)W(G,new q);else{if(l.destroyed||l.errored)return!1;l.reading=!1,l.decoder&&!x?(z=l.decoder.write(z),l.objectMode||z.length!==0?s(G,l,z,!1):O1(G,l)):s(G,l,z,!1)}else m||(l.reading=!1,O1(G,l));return!l.ended&&(l.length0?(z.multiAwaitDrain?z.awaitDrainWriters.clear():z.awaitDrainWriters=null,z.dataEmitted=!0,G.emit("data",x)):(z.length+=z.objectMode?1:x.length,m?z.buffer.unshift(x):z.buffer.push(x),z.needReadable&&t(G)),O1(G,z)}b.prototype.isPaused=function(){let G=this._readableState;return G[w]===!0||G.flowing===!1},b.prototype.setEncoding=function(G){let z=new k(G);this._readableState.decoder=z,this._readableState.encoding=this._readableState.decoder.encoding;let x=this._readableState.buffer,m="";for(let l of x)m+=z.write(l);return x.clear(),m!==""&&x.push(m),this._readableState.length=m.length,this};var r=1073741824;function A1(G){if(G>r)throw new B("size","<= 1GiB",G);return G--,G|=G>>>1,G|=G>>>2,G|=G>>>4,G|=G>>>8,G|=G>>>16,G++,G}function Q1(G,z){return G<=0||z.length===0&&z.ended?0:z.objectMode?1:U(G)?z.flowing&&z.length?z.buffer.first().length:z.length:G<=z.length?G:z.ended?z.length:0}b.prototype.read=function(G){T("read",G),G===void 0?G=NaN:C(G)||(G=Y(G,10));let z=this._readableState,x=G;if(G>z.highWaterMark&&(z.highWaterMark=A1(G)),G!==0&&(z.emittedReadable=!1),G===0&&z.needReadable&&((z.highWaterMark!==0?z.length>=z.highWaterMark:z.length>0)||z.ended))return T("read: emitReadable",z.length,z.ended),z.length===0&&z.ended?B1(this):t(this),null;if(G=Q1(G,z),G===0&&z.ended)return z.length===0&&B1(this),null;let m=z.needReadable;if(T("need readable",m),(z.length===0||z.length-G0?l=H1(G,z):l=null,l===null?(z.needReadable=z.length<=z.highWaterMark,G=0):(z.length-=G,z.multiAwaitDrain?z.awaitDrainWriters.clear():z.awaitDrainWriters=null),z.length===0&&(z.ended||(z.needReadable=!0),x!==G&&z.ended&&B1(this)),l!==null&&!z.errorEmitted&&!z.closeEmitted&&(z.dataEmitted=!0,this.emit("data",l)),l};function e(G,z){if(T("onEofChunk"),!z.ended){if(z.decoder){let x=z.decoder.end();x&&x.length&&(z.buffer.push(x),z.length+=z.objectMode?1:x.length)}z.ended=!0,z.sync?t(G):(z.needReadable=!1,z.emittedReadable=!0,U1(G))}}function t(G){let z=G._readableState;T("emitReadable",z.needReadable,z.emittedReadable),z.needReadable=!1,z.emittedReadable||(T("emitReadable",z.flowing),z.emittedReadable=!0,J.nextTick(U1,G))}function U1(G){let z=G._readableState;T("emitReadable_",z.destroyed,z.length,z.ended),!z.destroyed&&!z.errored&&(z.length||z.ended)&&(G.emit("readable"),z.emittedReadable=!1),z.needReadable=!z.flowing&&!z.ended&&z.length<=z.highWaterMark,q1(G)}function O1(G,z){!z.readingMore&&z.constructed&&(z.readingMore=!0,J.nextTick(E1,G,z))}function E1(G,z){for(;!z.reading&&!z.ended&&(z.length1&&m.pipes.includes(G)&&(T("false write response, pause",m.awaitDrainWriters.size),m.awaitDrainWriters.add(G)),x.pause()),F1||(F1=Y1(x,G),G.on("drain",F1))}x.on("data",$1);function $1(M1){T("ondata");let L1=G.write(M1);T("dest.write",L1),L1===!1&&W1()}function N1(M1){if(T("onerror",M1),z1(),G.removeListener("error",N1),G.listenerCount("error")===0){let L1=G._writableState||G._readableState;L1&&!L1.errorEmitted?W(G,M1):G.emit("error",M1)}}D(G,"error",N1);function _1(){G.removeListener("finish",J1),z1()}G.once("close",_1);function J1(){T("onfinish"),G.removeListener("close",_1),z1()}G.once("finish",J1);function z1(){T("unpipe"),x.unpipe(G)}return G.emit("pipe",x),G.writableNeedDrain===!0?m.flowing&&W1():m.flowing||(T("pipe resume"),x.resume()),G};function Y1(G,z){return function(){let x=G._readableState;x.awaitDrainWriters===z?(T("pipeOnDrain",1),x.awaitDrainWriters=null):x.multiAwaitDrain&&(T("pipeOnDrain",x.awaitDrainWriters.size),x.awaitDrainWriters.delete(z)),(!x.awaitDrainWriters||x.awaitDrainWriters.size===0)&&G.listenerCount("data")&&G.resume()}}b.prototype.unpipe=function(G){let z=this._readableState,x={hasUnpiped:!1};if(z.pipes.length===0)return this;if(!G){let l=z.pipes;z.pipes=[],this.pause();for(let a=0;a0,m.flowing!==!1&&this.resume()):G==="readable"&&!m.endEmitted&&!m.readableListening&&(m.readableListening=m.needReadable=!0,m.flowing=!1,m.emittedReadable=!1,T("on readable",m.length,m.reading),m.length?t(this):m.reading||J.nextTick(c,this)),x},b.prototype.addListener=b.prototype.on,b.prototype.removeListener=function(G,z){let x=V.prototype.removeListener.call(this,G,z);return G==="readable"&&J.nextTick(i,this),x},b.prototype.off=b.prototype.removeListener,b.prototype.removeAllListeners=function(G){let z=V.prototype.removeAllListeners.apply(this,arguments);return(G==="readable"||G===void 0)&&J.nextTick(i,this),z};function i(G){let z=G._readableState;z.readableListening=G.listenerCount("readable")>0,z.resumeScheduled&&z[w]===!1?z.flowing=!0:G.listenerCount("data")>0?G.resume():z.readableListening||(z.flowing=null)}function c(G){T("readable nexttick read 0"),G.read(0)}b.prototype.resume=function(){let G=this._readableState;return G.flowing||(T("resume"),G.flowing=!G.readableListening,o(this,G)),G[w]=!1,this};function o(G,z){z.resumeScheduled||(z.resumeScheduled=!0,J.nextTick(C1,G,z))}function C1(G,z){T("resume",z.reading),z.reading||G.read(0),z.resumeScheduled=!1,G.emit("resume"),q1(G),z.flowing&&!z.reading&&G.read(0)}b.prototype.pause=function(){return T("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(T("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[w]=!0,this};function q1(G){let z=G._readableState;for(T("flow",z.flowing);z.flowing&&G.read()!==null;);}b.prototype.wrap=function(G){let z=!1;G.on("data",(m)=>{!this.push(m)&&G.pause&&(z=!0,G.pause())}),G.on("end",()=>{this.push(null)}),G.on("error",(m)=>{W(this,m)}),G.on("close",()=>{this.destroy()}),G.on("destroy",()=>{this.destroy()}),this._read=()=>{z&&G.resume&&(z=!1,G.resume())};let x=X(G);for(let m=1;m{l=K1?u(l,K1):null,x(),x=_});try{for(;;){let K1=G.destroyed?null:G.read();if(K1!==null)yield K1;else{if(l)throw l;if(l===null)return;await new H(m)}}}catch(K1){throw l=u(l,K1),l}finally{(l||z?.destroyOnReturn!==!1)&&(l===void 0||G._readableState.autoDestroy)?y.destroyer(G,null):(G.off("readable",m),a())}}Z(b.prototype,{readable:{__proto__:null,get(){let G=this._readableState;return!!G&&G.readable!==!1&&!G.destroyed&&!G.errorEmitted&&!G.endEmitted},set(G){this._readableState&&(this._readableState.readable=!!G)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(G){this._readableState&&(this._readableState.flowing=G)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(G){!this._readableState||(this._readableState.destroyed=G)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}}),Z(j.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[w]!==!1},set(G){this[w]=!!G}}}),b._fromList=H1;function H1(G,z){if(z.length===0)return null;let x;return z.objectMode?x=z.buffer.shift():!G||G>=z.length?(z.decoder?x=z.buffer.join(""):z.buffer.length===1?x=z.buffer.first():x=z.buffer.concat(z.length),z.buffer.clear()):x=z.buffer.consume(G,z.decoder),x}function B1(G){let z=G._readableState;T("endReadable",z.endEmitted),z.endEmitted||(z.ended=!0,J.nextTick(k1,z,G))}function k1(G,z){if(T("endReadableNT",G.endEmitted,G.length),!G.errored&&!G.closeEmitted&&!G.endEmitted&&G.length===0){if(G.endEmitted=!0,z.emit("end"),z.writable&&z.allowHalfOpen===!1)J.nextTick(D1,z);else if(G.autoDestroy){let x=z._writableState;(!x||x.autoDestroy&&(x.finished||x.writable===!1))&&z.destroy()}}}function D1(G){G.writable&&!G.writableEnded&&!G.destroyed&&G.end()}b.from=function(G,z){return S(b,G,z)};var G1;function w1(){return G1===void 0&&(G1={}),G1}b.fromWeb=function(G,z){return w1().newStreamReadableFromReadableStream(G,z)},b.toWeb=function(G,z){return w1().newReadableStreamFromStreamReadable(G,z)},b.wrap=function(G,z){var x,m;return new b({objectMode:(x=(m=G.readableObjectMode)!==null&&m!==void 0?m:G.objectMode)!==null&&x!==void 0?x:!0,...z,destroy(l,a){y.destroyer(G,l),a(l)}}).wrap(G)}}),Ml=k0((A,Q)=>{var J=(VJ(),N9(V7)),{ArrayPrototypeSlice:K,Error:C,FunctionPrototypeSymbolHasInstance:U,ObjectDefineProperty:Y,ObjectDefineProperties:Z,ObjectSetPrototypeOf:X,StringPrototypeToLowerCase:E,Symbol:H,SymbolHasInstance:$}=P8();Q.exports=k,k.WritableState=O;var{EventEmitter:I}=DV(),N=VV().Stream,{Buffer:F}=W3(),V=$Y(),{addAbortSignal:D}=MV(),{getHighWaterMark:L,getDefaultHighWaterMark:R}=wV(),{ERR_INVALID_ARG_TYPE:M,ERR_METHOD_NOT_IMPLEMENTED:T,ERR_MULTIPLE_CALLBACK:h,ERR_STREAM_CANNOT_PIPE:y,ERR_STREAM_DESTROYED:g,ERR_STREAM_ALREADY_FINISHED:f,ERR_STREAM_NULL_VALUES:u,ERR_STREAM_WRITE_AFTER_END:d,ERR_UNKNOWN_ENCODING:n}=o6().codes,{errorOrDestroy:B}=V;X(k.prototype,N.prototype),X(k,N);function q(){}var P=H("kOnFinished");function O(c,o,C1){typeof C1!="boolean"&&(C1=o instanceof D7()),this.objectMode=!!(c&&c.objectMode),C1&&(this.objectMode=this.objectMode||!!(c&&c.writableObjectMode)),this.highWaterMark=c?L(this,c,"writableHighWaterMark",C1):R(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let q1=!!(c&&c.decodeStrings===!1);this.decodeStrings=!q1,this.defaultEncoding=c&&c.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=b.bind(void 0,o),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,w(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!c||c.emitClose!==!1,this.autoDestroy=!c||c.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[P]=[]}function w(c){c.buffered=[],c.bufferedIndex=0,c.allBuffers=!0,c.allNoop=!0}O.prototype.getBuffer=function(){return K(this.buffered,this.bufferedIndex)},Y(O.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function k(c){let o=this instanceof D7();if(!o&&!U(k,this))return new k(c);this._writableState=new O(c,this,o),c&&(typeof c.write=="function"&&(this._write=c.write),typeof c.writev=="function"&&(this._writev=c.writev),typeof c.destroy=="function"&&(this._destroy=c.destroy),typeof c.final=="function"&&(this._final=c.final),typeof c.construct=="function"&&(this._construct=c.construct),c.signal&&D(c.signal,this)),N.call(this,c),V.construct(this,()=>{let C1=this._writableState;C1.writing||A1(this,C1),U1(this,C1)})}Y(k,$,{__proto__:null,value:function(c){return U(this,c)?!0:this!==k?!1:c&&c._writableState instanceof O}}),k.prototype.pipe=function(){B(this,new y)};function S(c,o,C1,q1){let Z1=c._writableState;if(typeof C1=="function")q1=C1,C1=Z1.defaultEncoding;else{if(!C1)C1=Z1.defaultEncoding;else if(C1!=="buffer"&&!F.isEncoding(C1))throw new n(C1);typeof q1!="function"&&(q1=q)}if(o===null)throw new u;if(!Z1.objectMode)if(typeof o=="string")Z1.decodeStrings!==!1&&(o=F.from(o,C1),C1="buffer");else if(o instanceof F)C1="buffer";else if(N._isUint8Array(o))o=N._uint8ArrayToBuffer(o),C1="buffer";else throw new M("chunk",["string","Buffer","Uint8Array"],o);let j1;return Z1.ending?j1=new d:Z1.destroyed&&(j1=new g("write")),j1?(J.nextTick(q1,j1),B(c,j1,!0),j1):(Z1.pendingcb++,_(c,Z1,o,C1,q1))}k.prototype.write=function(c,o,C1){return S(this,c,o,C1)===!0},k.prototype.cork=function(){this._writableState.corked++},k.prototype.uncork=function(){let c=this._writableState;c.corked&&(c.corked--,c.writing||A1(this,c))},k.prototype.setDefaultEncoding=function(c){if(typeof c=="string"&&(c=E(c)),!F.isEncoding(c))throw new n(c);return this._writableState.defaultEncoding=c,this};function _(c,o,C1,q1,Z1){let j1=o.objectMode?1:C1.length;o.length+=j1;let H1=o.lengthC1.bufferedIndex&&A1(c,C1),q1?C1.afterWriteTickInfo!==null&&C1.afterWriteTickInfo.cb===Z1?C1.afterWriteTickInfo.count++:(C1.afterWriteTickInfo={count:1,cb:Z1,stream:c,state:C1},J.nextTick(p,C1.afterWriteTickInfo)):s(c,C1,1,Z1))}function p({stream:c,state:o,count:C1,cb:q1}){return o.afterWriteTickInfo=null,s(c,o,C1,q1)}function s(c,o,C1,q1){for(!o.ending&&!c.destroyed&&o.length===0&&o.needDrain&&(o.needDrain=!1,c.emit("drain"));C1-- >0;)o.pendingcb--,q1();o.destroyed&&r(o),U1(c,o)}function r(c){if(c.writing)return;for(let Z1=c.bufferedIndex;Z11&&c._writev){o.pendingcb-=j1-1;let B1=o.allNoop?q:(D1)=>{for(let G1=H1;G1256?(C1.splice(0,H1),o.bufferedIndex=0):o.bufferedIndex=H1}o.bufferProcessing=!1}k.prototype._write=function(c,o,C1){if(this._writev)this._writev([{chunk:c,encoding:o}],C1);else throw new T("_write()")},k.prototype._writev=null,k.prototype.end=function(c,o,C1){let q1=this._writableState;typeof c=="function"?(C1=c,c=null,o=null):typeof o=="function"&&(C1=o,o=null);let Z1;if(c!=null){let j1=S(this,c,o);j1 instanceof C&&(Z1=j1)}return q1.corked&&(q1.corked=1,this.uncork()),Z1||(!q1.errored&&!q1.ending?(q1.ending=!0,U1(this,q1,!0),q1.ended=!0):q1.finished?Z1=new f("end"):q1.destroyed&&(Z1=new g("end"))),typeof C1=="function"&&(Z1||q1.finished?J.nextTick(C1,Z1):q1[P].push(C1)),this};function Q1(c){return c.ending&&!c.destroyed&&c.constructed&&c.length===0&&!c.errored&&c.buffered.length===0&&!c.finished&&!c.writing&&!c.errorEmitted&&!c.closeEmitted}function e(c,o){let C1=!1;function q1(Z1){if(C1){B(c,Z1??h());return}if(C1=!0,o.pendingcb--,Z1){let j1=o[P].splice(0);for(let H1=0;H1{Q1(Z1)?O1(q1,Z1):Z1.pendingcb--},c,o)):Q1(o)&&(o.pendingcb++,O1(c,o))))}function O1(c,o){o.pendingcb--,o.finished=!0;let C1=o[P].splice(0);for(let q1=0;q1{var J=(VJ(),N9(V7)),K=W3(),{isReadable:C,isWritable:U,isIterable:Y,isNodeStream:Z,isReadableNodeStream:X,isWritableNodeStream:E,isDuplexNodeStream:H}=MJ(),$=wJ(),{AbortError:I,codes:{ERR_INVALID_ARG_TYPE:N,ERR_INVALID_RETURN_VALUE:F}}=o6(),{destroyer:V}=$Y(),D=D7(),L=lW(),{createDeferredPromise:R}=z7(),M=Vl(),T=globalThis.Blob||K.Blob,h=typeof T<"u"?function(n){return n instanceof T}:function(n){return!1},y=globalThis.AbortController||zV().AbortController,{FunctionPrototypeCall:g}=P8(),f=class extends D{constructor(n){super(n),n?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),n?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};Q.exports=function n(B,q){if(H(B))return B;if(X(B))return d({readable:B});if(E(B))return d({writable:B});if(Z(B))return d({writable:!1,readable:!1});if(typeof B=="function"){let{value:O,write:w,final:k,destroy:S}=u(B);if(Y(O))return M(f,O,{objectMode:!0,write:w,final:k,destroy:S});let _=O?.then;if(typeof _=="function"){let W,j=g(_,O,(b)=>{if(b!=null)throw new F("nully","body",b)},(b)=>{V(W,b)});return W=new f({objectMode:!0,readable:!1,write:w,final(b){k(async()=>{try{await j,J.nextTick(b,null)}catch(p){J.nextTick(b,p)}})},destroy:S})}throw new F("Iterable, AsyncIterable or AsyncFunction",q,O)}if(h(B))return n(B.arrayBuffer());if(Y(B))return M(f,B,{objectMode:!0,writable:!1});if(typeof B?.writable=="object"||typeof B?.readable=="object"){let O=B!=null&&B.readable?X(B?.readable)?B?.readable:n(B.readable):void 0,w=B!=null&&B.writable?E(B?.writable)?B?.writable:n(B.writable):void 0;return d({readable:O,writable:w})}let P=B?.then;if(typeof P=="function"){let O;return g(P,B,(w)=>{w!=null&&O.push(w),O.push(null)},(w)=>{V(O,w)}),O=new f({objectMode:!0,writable:!1,read(){}})}throw new N(q,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],B)};function u(n){let{promise:B,resolve:q}=R(),P=new y,O=P.signal;return{value:n(async function*(){for(;;){let w=B;B=null;let{chunk:k,done:S,cb:_}=await w;if(J.nextTick(_),S)return;if(O.aborted)throw new I(void 0,{cause:O.reason});({promise:B,resolve:q}=R()),yield k}}(),{signal:O}),write(w,k,S){let _=q;q=null,_({chunk:w,done:!1,cb:S})},final(w){let k=q;q=null,k({done:!0,cb:w})},destroy(w,k){P.abort(),k(w)}}}function d(n){let B=n.readable&&typeof n.readable.read!="function"?L.wrap(n.readable):n.readable,q=n.writable,P=!!C(B),O=!!U(q),w,k,S,_,W;function j(b){let p=_;_=null,p?p(b):b?W.destroy(b):!P&&!O&&W.destroy()}return W=new f({readableObjectMode:!!(B!=null&&B.readableObjectMode),writableObjectMode:!!(q!=null&&q.writableObjectMode),readable:P,writable:O}),O&&($(q,(b)=>{O=!1,b&&V(B,b),j(b)}),W._write=function(b,p,s){q.write(b,p)?s():w=s},W._final=function(b){q.end(),k=b},q.on("drain",function(){if(w){let b=w;w=null,b()}}),q.on("finish",function(){if(k){let b=k;k=null,b()}})),P&&($(B,(b)=>{P=!1,b&&V(B,b),j(b)}),B.on("readable",function(){if(S){let b=S;S=null,b()}}),B.on("end",function(){W.push(null)}),W._read=function(){for(;;){let b=B.read();if(b===null){S=W._read;return}if(!W.push(b))return}}),W._destroy=function(b,p){!b&&_!==null&&(b=new I),S=null,w=null,k=null,_===null?p(b):(_=p,V(q,b),V(B,b))},W}}),D7=k0((A,Q)=>{var{ObjectDefineProperties:J,ObjectGetOwnPropertyDescriptor:K,ObjectKeys:C,ObjectSetPrototypeOf:U}=P8();Q.exports=X;var Y=lW(),Z=Ml();U(X.prototype,Y.prototype),U(X,Y);{let I=C(Z.prototype);for(let N=0;N{var{ObjectSetPrototypeOf:J,Symbol:K}=P8();Q.exports=X;var{ERR_METHOD_NOT_IMPLEMENTED:C}=o6().codes,U=D7(),{getHighWaterMark:Y}=wV();J(X.prototype,U.prototype),J(X,U);var Z=K("kCallback");function X($){if(!(this instanceof X))return new X($);let I=$?Y(this,$,"readableHighWaterMark",!0):null;I===0&&($={...$,highWaterMark:null,readableHighWaterMark:I,writableHighWaterMark:$.writableHighWaterMark||0}),U.call(this,$),this._readableState.sync=!1,this[Z]=null,$&&(typeof $.transform=="function"&&(this._transform=$.transform),typeof $.flush=="function"&&(this._flush=$.flush)),this.on("prefinish",H)}function E($){typeof this._flush=="function"&&!this.destroyed?this._flush((I,N)=>{if(I){$?$(I):this.destroy(I);return}N!=null&&this.push(N),this.push(null),$&&$()}):(this.push(null),$&&$())}function H(){this._final!==E&&E.call(this)}X.prototype._final=E,X.prototype._transform=function($,I,N){throw new C("_transform()")},X.prototype._write=function($,I,N){let F=this._readableState,V=this._writableState,D=F.length;this._transform($,I,(L,R)=>{if(L){N(L);return}R!=null&&this.push(R),V.ended||D===F.length||F.length{var{ObjectSetPrototypeOf:J}=P8();Q.exports=C;var K=wl();J(C.prototype,K.prototype),J(C,K);function C(U){if(!(this instanceof C))return new C(U);K.call(this,U)}C.prototype._transform=function(U,Y,Z){Z(null,U)}}),PV=k0((A,Q)=>{var J=(VJ(),N9(V7)),{ArrayIsArray:K,Promise:C,SymbolAsyncIterator:U}=P8(),Y=wJ(),{once:Z}=z7(),X=$Y(),E=D7(),{aggregateTwoErrors:H,codes:{ERR_INVALID_ARG_TYPE:$,ERR_INVALID_RETURN_VALUE:I,ERR_MISSING_ARGS:N,ERR_STREAM_DESTROYED:F,ERR_STREAM_PREMATURE_CLOSE:V},AbortError:D}=o6(),{validateFunction:L,validateAbortSignal:R}=dW(),{isIterable:M,isReadable:T,isReadableNodeStream:h,isNodeStream:y}=MJ(),g=globalThis.AbortController||zV().AbortController,f,u;function d(S,_,W){let j=!1;S.on("close",()=>{j=!0});let b=Y(S,{readable:_,writable:W},(p)=>{j=!p});return{destroy:(p)=>{j||(j=!0,X.destroyer(S,p||new F("pipe")))},cleanup:b}}function n(S){return L(S[S.length-1],"streams[stream.length - 1]"),S.pop()}function B(S){if(M(S))return S;if(h(S))return q(S);throw new $("val",["Readable","Iterable","AsyncIterable"],S)}async function*q(S){u||(u=lW()),yield*u.prototype[U].call(S)}async function P(S,_,W,{end:j}){let b,p=null,s=(Q1)=>{if(Q1&&(b=Q1),p){let e=p;p=null,e()}},r=()=>new C((Q1,e)=>{b?e(b):p=()=>{b?e(b):Q1()}});_.on("drain",s);let A1=Y(_,{readable:!1},s);try{_.writableNeedDrain&&await r();for await(let Q1 of S)_.write(Q1)||await r();j&&_.end(),await r(),W()}catch(Q1){W(b!==Q1?H(b,Q1):Q1)}finally{A1(),_.off("drain",s)}}function O(...S){return w(S,Z(n(S)))}function w(S,_,W){if(S.length===1&&K(S[0])&&(S=S[0]),S.length<2)throw new N("streams");let j=new g,b=j.signal,p=W?.signal,s=[];R(p,"options.signal");function r(){O1(new D)}p?.addEventListener("abort",r);let A1,Q1,e=[],t=0;function U1(c){O1(c,--t===0)}function O1(c,o){if(c&&(!A1||A1.code==="ERR_STREAM_PREMATURE_CLOSE")&&(A1=c),!(!A1&&!o)){for(;e.length;)e.shift()(A1);p?.removeEventListener("abort",r),j.abort(),o&&(A1||s.forEach((C1)=>C1()),J.nextTick(_,A1,Q1))}}let E1;for(let c=0;c0,Z1=C1||W?.end!==!1,j1=c===S.length-1;if(y(o)){let H1=function(B1){B1&&B1.name!=="AbortError"&&B1.code!=="ERR_STREAM_PREMATURE_CLOSE"&&U1(B1)};var Y1=H1;if(Z1){let{destroy:B1,cleanup:k1}=d(o,C1,q1);e.push(B1),T(o)&&j1&&s.push(k1)}o.on("error",H1),T(o)&&j1&&s.push(()=>{o.removeListener("error",H1)})}if(c===0)if(typeof o=="function"){if(E1=o({signal:b}),!M(E1))throw new I("Iterable, AsyncIterable or Stream","source",E1)}else M(o)||h(o)?E1=o:E1=E.from(o);else if(typeof o=="function")if(E1=B(E1),E1=o(E1,{signal:b}),C1){if(!M(E1,!0))throw new I("AsyncIterable",`transform[${c-1}]`,E1)}else{var i;f||(f=Pl());let H1=new f({objectMode:!0}),B1=(i=E1)===null||i===void 0?void 0:i.then;if(typeof B1=="function")t++,B1.call(E1,(G1)=>{Q1=G1,G1!=null&&H1.write(G1),Z1&&H1.end(),J.nextTick(U1)},(G1)=>{H1.destroy(G1),J.nextTick(U1,G1)});else if(M(E1,!0))t++,P(E1,H1,U1,{end:Z1});else throw new I("AsyncIterable or Promise","destination",E1);E1=H1;let{destroy:k1,cleanup:D1}=d(E1,!1,!0);e.push(k1),j1&&s.push(D1)}else if(y(o)){if(h(E1)){t+=2;let H1=k(E1,o,U1,{end:Z1});T(o)&&j1&&s.push(H1)}else if(M(E1))t++,P(E1,o,U1,{end:Z1});else throw new $("val",["Readable","Iterable","AsyncIterable"],E1);E1=o}else E1=E.from(o)}return(b!=null&&b.aborted||p!=null&&p.aborted)&&J.nextTick(r),E1}function k(S,_,W,{end:j}){let b=!1;return _.on("close",()=>{b||W(new V)}),S.pipe(_,{end:j}),j?S.once("end",()=>{b=!0,_.end()}):W(),Y(S,{readable:!0,writable:!1},(p)=>{let s=S._readableState;p&&p.code==="ERR_STREAM_PREMATURE_CLOSE"&&s&&s.ended&&!s.errored&&!s.errorEmitted?S.once("end",W).once("error",W):W(p)}),Y(_,{readable:!1,writable:!0},W)}Q.exports={pipelineImpl:w,pipeline:O}}),b$1=k0((A,Q)=>{var{pipeline:J}=PV(),K=D7(),{destroyer:C}=$Y(),{isNodeStream:U,isReadable:Y,isWritable:Z}=MJ(),{AbortError:X,codes:{ERR_INVALID_ARG_VALUE:E,ERR_MISSING_ARGS:H}}=o6();Q.exports=function(...$){if($.length===0)throw new H("streams");if($.length===1)return K.from($[0]);let I=[...$];if(typeof $[0]=="function"&&($[0]=K.from($[0])),typeof $[$.length-1]=="function"){let g=$.length-1;$[g]=K.from($[g])}for(let g=0;g<$.length;++g)if(U($[g])){if(g<$.length-1&&!Y($[g]))throw new E(`streams[${g}]`,I[g],"must be readable");if(g>0&&!Z($[g]))throw new E(`streams[${g}]`,I[g],"must be writable")}let N,F,V,D,L;function R(g){let f=D;D=null,f?f(g):g?L.destroy(g):!y&&!h&&L.destroy()}let M=$[0],T=J($,R),h=!!Z(M),y=!!Y(T);return L=new K({writableObjectMode:!!(M!=null&&M.writableObjectMode),readableObjectMode:!!(T!=null&&T.writableObjectMode),writable:h,readable:y}),h&&(L._write=function(g,f,u){M.write(g,f)?u():N=u},L._final=function(g){M.end(),F=g},M.on("drain",function(){if(N){let g=N;N=null,g()}}),T.on("finish",function(){if(F){let g=F;F=null,g()}})),y&&(T.on("readable",function(){if(V){let g=V;V=null,g()}}),T.on("end",function(){L.push(null)}),L._read=function(){for(;;){let g=T.read();if(g===null){V=L._read;return}if(!L.push(g))return}}),L._destroy=function(g,f){!g&&D!==null&&(g=new X),V=null,N=null,F=null,D===null?f(g):(D=f,C(T,g))},L}}),_l=k0((A,Q)=>{var{ArrayPrototypePop:J,Promise:K}=P8(),{isIterable:C,isNodeStream:U}=MJ(),{pipelineImpl:Y}=PV(),{finished:Z}=wJ();function X(...E){return new K((H,$)=>{let I,N,F=E[E.length-1];if(F&&typeof F=="object"&&!U(F)&&!C(F)){let V=J(E);I=V.signal,N=V.end}Y(E,(V,D)=>{V?$(V):H(D)},{signal:I,end:N})})}Q.exports={finished:Z,pipeline:X}}),f$1=k0((A,Q)=>{var{Buffer:J}=W3(),{ObjectDefineProperty:K,ObjectKeys:C,ReflectApply:U}=P8(),{promisify:{custom:Y}}=z7(),{streamReturningOperators:Z,promiseReturningOperators:X}=v$1(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:E}}=o6(),H=b$1(),{pipeline:$}=PV(),{destroyer:I}=$Y(),N=wJ(),F=_l(),V=MJ(),D=Q.exports=VV().Stream;D.isDisturbed=V.isDisturbed,D.isErrored=V.isErrored,D.isReadable=V.isReadable,D.Readable=lW();for(let M of C(Z)){let T=function(...y){if(new.target)throw E();return D.Readable.from(U(h,this,y))};L=T;let h=Z[M];K(T,"name",{__proto__:null,value:h.name}),K(T,"length",{__proto__:null,value:h.length}),K(D.Readable.prototype,M,{__proto__:null,value:T,enumerable:!1,configurable:!0,writable:!0})}var L;for(let M of C(X)){let T=function(...y){if(new.target)throw E();return U(h,this,y)};L=T;let h=X[M];K(T,"name",{__proto__:null,value:h.name}),K(T,"length",{__proto__:null,value:h.length}),K(D.Readable.prototype,M,{__proto__:null,value:T,enumerable:!1,configurable:!0,writable:!0})}var L;D.Writable=Ml(),D.Duplex=D7(),D.Transform=wl(),D.PassThrough=Pl(),D.pipeline=$;var{addAbortSignal:R}=MV();D.addAbortSignal=R,D.finished=N,D.destroy=I,D.compose=H,K(D,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return F}}),K($,Y,{__proto__:null,enumerable:!0,get(){return F.pipeline}}),K(N,Y,{__proto__:null,enumerable:!0,get(){return F.finished}}),D.Stream=D,D._isUint8Array=function(M){return M instanceof Uint8Array},D._uint8ArrayToBuffer=function(M){return J.from(M.buffer,M.byteOffset,M.byteLength)}}),zl=k0((A,Q)=>{var J=f$1(),K=_l(),C=J.Readable.destroy;Q.exports=J.Readable,Q.exports._uint8ArrayToBuffer=J._uint8ArrayToBuffer,Q.exports._isUint8Array=J._isUint8Array,Q.exports.isDisturbed=J.isDisturbed,Q.exports.isErrored=J.isErrored,Q.exports.isReadable=J.isReadable,Q.exports.Readable=J.Readable,Q.exports.Writable=J.Writable,Q.exports.Duplex=J.Duplex,Q.exports.Transform=J.Transform,Q.exports.PassThrough=J.PassThrough,Q.exports.addAbortSignal=J.addAbortSignal,Q.exports.finished=J.finished,Q.exports.destroy=J.destroy,Q.exports.destroy=C,Q.exports.pipeline=J.pipeline,Q.exports.compose=J.compose,Object.defineProperty(J,"promises",{configurable:!0,enumerable:!0,get(){return K}}),Q.exports.Stream=J.Stream,Q.exports.default=Q.exports}),_V={};mW(_V,{default:()=>Tl});p$1=RV(()=>{cW(_V,zJ(zl())),Tl=zJ(zl())}),kl=k0((A,Q)=>{Q.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var J={},K=Symbol("test"),C=Object(K);if(typeof K=="string"||Object.prototype.toString.call(K)!=="[object Symbol]"||Object.prototype.toString.call(C)!=="[object Symbol]")return!1;var U=42;J[K]=U;for(K in J)return!1;if(typeof Object.keys=="function"&&Object.keys(J).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(J).length!==0)return!1;var Y=Object.getOwnPropertySymbols(J);if(Y.length!==1||Y[0]!==K||!Object.prototype.propertyIsEnumerable.call(J,K))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var Z=Object.getOwnPropertyDescriptor(J,K);if(Z.value!==U||Z.enumerable!==!0)return!1}return!0}}),nW=k0((A,Q)=>{var J=kl();Q.exports=function(){return J()&&!!Symbol.toStringTag}}),u$1=k0((A,Q)=>{var J=typeof Symbol<"u"&&Symbol,K=kl();Q.exports=function(){return typeof J!="function"||typeof Symbol!="function"||typeof J("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:K()}}),m$1=k0((A,Q)=>{var J="Function.prototype.bind called on incompatible ",K=Array.prototype.slice,C=Object.prototype.toString,U="[object Function]";Q.exports=function(Y){var Z=this;if(typeof Z!="function"||C.call(Z)!==U)throw new TypeError(J+Z);for(var X=K.call(arguments,1),E,H=function(){if(this instanceof E){var V=Z.apply(this,X.concat(K.call(arguments)));return Object(V)===V?V:this}else return Z.apply(Y,X.concat(K.call(arguments)))},$=Math.max(0,Z.length-X.length),I=[],N=0;N<$;N++)I.push("$"+N);if(E=Function("binder","return function ("+I.join(",")+"){ return binder.apply(this,arguments); }")(H),Z.prototype){var F=function(){};F.prototype=Z.prototype,E.prototype=new F,F.prototype=null}return E}}),TV=k0((A,Q)=>{var J=m$1();Q.exports=Function.prototype.bind||J}),c$1=k0((A,Q)=>{var J=TV();Q.exports=J.call(Function.call,Object.prototype.hasOwnProperty)}),sW=k0((A,Q)=>{var J,K=SyntaxError,C=Function,U=TypeError,Y=function(q){try{return C('"use strict"; return ('+q+").constructor;")()}catch{}},Z=Object.getOwnPropertyDescriptor;if(Z)try{Z({},"")}catch{Z=null}var X=function(){throw new U},E=Z?function(){try{return arguments.callee,X}catch{try{return Z(arguments,"callee").get}catch{return X}}}():X,H=u$1()(),$=Object.getPrototypeOf||function(q){return q.__proto__},I={},N=typeof Uint8Array>"u"?J:$(Uint8Array),F={"%AggregateError%":typeof AggregateError>"u"?J:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer>"u"?J:ArrayBuffer,"%ArrayIteratorPrototype%":H?$([][Symbol.iterator]()):J,"%AsyncFromSyncIteratorPrototype%":J,"%AsyncFunction%":I,"%AsyncGenerator%":I,"%AsyncGeneratorFunction%":I,"%AsyncIteratorPrototype%":I,"%Atomics%":typeof Atomics>"u"?J:Atomics,"%BigInt%":typeof BigInt>"u"?J:BigInt,"%BigInt64Array%":typeof BigInt64Array>"u"?J:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array>"u"?J:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView>"u"?J:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":typeof Float32Array>"u"?J:Float32Array,"%Float64Array%":typeof Float64Array>"u"?J:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry>"u"?J:FinalizationRegistry,"%Function%":C,"%GeneratorFunction%":I,"%Int8Array%":typeof Int8Array>"u"?J:Int8Array,"%Int16Array%":typeof Int16Array>"u"?J:Int16Array,"%Int32Array%":typeof Int32Array>"u"?J:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":H?$($([][Symbol.iterator]())):J,"%JSON%":typeof JSON=="object"?JSON:J,"%Map%":typeof Map>"u"?J:Map,"%MapIteratorPrototype%":typeof Map>"u"||!H?J:$((/*@__PURE__*/new Map())[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise>"u"?J:Promise,"%Proxy%":typeof Proxy>"u"?J:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":typeof Reflect>"u"?J:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set>"u"?J:Set,"%SetIteratorPrototype%":typeof Set>"u"||!H?J:$((/*@__PURE__*/new Set())[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer>"u"?J:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":H?$(""[Symbol.iterator]()):J,"%Symbol%":H?Symbol:J,"%SyntaxError%":K,"%ThrowTypeError%":E,"%TypedArray%":N,"%TypeError%":U,"%Uint8Array%":typeof Uint8Array>"u"?J:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray>"u"?J:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array>"u"?J:Uint16Array,"%Uint32Array%":typeof Uint32Array>"u"?J:Uint32Array,"%URIError%":URIError,"%WeakMap%":typeof WeakMap>"u"?J:WeakMap,"%WeakRef%":typeof WeakRef>"u"?J:WeakRef,"%WeakSet%":typeof WeakSet>"u"?J:WeakSet};try{null.error}catch(q){V=$($(q)),F["%Error.prototype%"]=V}var V,D=function q(P){var O;if(P==="%AsyncFunction%")O=Y("async function () {}");else if(P==="%GeneratorFunction%")O=Y("function* () {}");else if(P==="%AsyncGeneratorFunction%")O=Y("async function* () {}");else if(P==="%AsyncGenerator%"){var w=q("%AsyncGeneratorFunction%");w&&(O=w.prototype)}else if(P==="%AsyncIteratorPrototype%"){var k=q("%AsyncGenerator%");k&&(O=$(k.prototype))}return F[P]=O,O},L={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},R=TV(),M=c$1(),T=R.call(Function.call,Array.prototype.concat),h=R.call(Function.apply,Array.prototype.splice),y=R.call(Function.call,String.prototype.replace),g=R.call(Function.call,String.prototype.slice),f=R.call(Function.call,RegExp.prototype.exec),u=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,d=/\\(\\)?/g,n=function(q){var P=g(q,0,1),O=g(q,-1);if(P==="%"&&O!=="%")throw new K("invalid intrinsic syntax, expected closing `%`");if(O==="%"&&P!=="%")throw new K("invalid intrinsic syntax, expected opening `%`");var w=[];return y(q,u,function(k,S,_,W){w[w.length]=_?y(W,d,"$1"):S||k}),w},B=function(q,P){var O=q,w;if(M(L,O)&&(w=L[O],O="%"+w[0]+"%"),M(F,O)){var k=F[O];if(k===I&&(k=D(O)),typeof k>"u"&&!P)throw new U("intrinsic "+q+" exists, but is not available. Please file an issue!");return{alias:w,name:O,value:k}}throw new K("intrinsic "+q+" does not exist!")};Q.exports=function(q,P){if(typeof q!="string"||q.length===0)throw new U("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof P!="boolean")throw new U('"allowMissing" argument must be a boolean');if(f(/^%?[^%]*%?$/,q)===null)throw new K("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var O=n(q),w=O.length>0?O[0]:"",k=B("%"+w+"%",P),S=k.name,_=k.value,W=!1,j=k.alias;j&&(w=j[0],h(O,T([0,1],j)));for(var b=1,p=!0;b=O.length){var Q1=Z(_,s);p=!!Q1,p&&"get"in Q1&&!("originalValue"in Q1.get)?_=Q1.get:_=_[s]}else p=M(_,s),_=_[s];p&&!W&&(F[S]=_)}}return _}}),kV=k0((A,Q)=>{var J=TV(),K=sW(),C=K("%Function.prototype.apply%"),U=K("%Function.prototype.call%"),Y=K("%Reflect.apply%",!0)||J.call(U,C),Z=K("%Object.getOwnPropertyDescriptor%",!0),X=K("%Object.defineProperty%",!0),E=K("%Math.max%");if(X)try{X({},"a",{value:1})}catch{X=null}Q.exports=function($){var I=Y(J,U,arguments);if(Z&&X){var N=Z(I,"length");N.configurable&&X(I,"length",{value:1+E(0,$.length-(arguments.length-1))})}return I};var H=function(){return Y(J,C,arguments)};X?X(Q.exports,"apply",{value:H}):Q.exports.apply=H}),SV=k0((A,Q)=>{var J=sW(),K=kV(),C=K(J("String.prototype.indexOf"));Q.exports=function(U,Y){var Z=J(U,!!Y);return typeof Z=="function"&&C(U,".prototype.")>-1?K(Z):Z}}),d$1=k0((A,Q)=>{var J=nW()(),K=SV(),C=K("Object.prototype.toString"),U=function(X){return J&&X&&typeof X=="object"&&Symbol.toStringTag in X?!1:C(X)==="[object Arguments]"},Y=function(X){return U(X)?!0:X!==null&&typeof X=="object"&&typeof X.length=="number"&&X.length>=0&&C(X)!=="[object Array]"&&C(X.callee)==="[object Function]"},Z=function(){return U(arguments)}();U.isLegacyArguments=Y,Q.exports=Z?U:Y}),l$1=k0((A,Q)=>{var J=Object.prototype.toString,K=Function.prototype.toString,C=/^\s*(?:function)?\*/,U=nW()(),Y=Object.getPrototypeOf,Z=function(){if(!U)return!1;try{return Function("return function*() {}")()}catch{}},X;Q.exports=function(E){if(typeof E!="function")return!1;if(C.test(K.call(E)))return!0;if(!U){var H=J.call(E);return H==="[object GeneratorFunction]"}if(!Y)return!1;if(typeof X>"u"){var $=Z();X=$?Y($):!1}return Y(E)===X}}),n$1=k0((A,Q)=>{var J=Function.prototype.toString,K=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,C,U;if(typeof K=="function"&&typeof Object.defineProperty=="function")try{C=Object.defineProperty({},"length",{get:function(){throw U}}),U={},K(function(){throw 42},null,C)}catch(T){T!==U&&(K=null)}else K=null;var Y=/^\s*class\b/,Z=function(T){try{var h=J.call(T);return Y.test(h)}catch{return!1}},X=function(T){try{return Z(T)?!1:(J.call(T),!0)}catch{return!1}},E=Object.prototype.toString,H="[object Object]",$="[object Function]",I="[object GeneratorFunction]",N="[object HTMLAllCollection]",F="[object HTML document.all class]",V="[object HTMLCollection]",D=typeof Symbol=="function"&&!!Symbol.toStringTag,L=!(0 in[,]),R=function(){return!1};typeof document=="object"&&(M=document.all,E.call(M)===E.call(document.all)&&(R=function(T){if((L||!T)&&(typeof T>"u"||typeof T=="object"))try{var h=E.call(T);return(h===N||h===F||h===V||h===H)&&T("")==null}catch{}return!1}));var M;Q.exports=K?function(T){if(R(T))return!0;if(!T||typeof T!="function"&&typeof T!="object")return!1;try{K(T,null,C)}catch(h){if(h!==U)return!1}return!Z(T)&&X(T)}:function(T){if(R(T))return!0;if(!T||typeof T!="function"&&typeof T!="object")return!1;if(D)return X(T);if(Z(T))return!1;var h=E.call(T);return h!==$&&h!==I&&!/^\[object HTML/.test(h)?!1:X(T)}}),Sl=k0((A,Q)=>{var J=n$1(),K=Object.prototype.toString,C=Object.prototype.hasOwnProperty,U=function(E,H,$){for(var I=0,N=E.length;I=3&&(I=$),K.call(E)==="[object Array]"?U(E,H,I):typeof E=="string"?Y(E,H,I):Z(E,H,I)};Q.exports=X}),jl=k0((A,Q)=>{var J=["BigInt64Array","BigUint64Array","Float32Array","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray"],K=typeof globalThis>"u"?global:globalThis;Q.exports=function(){for(var C=[],U=0;U{var J=sW(),K=J("%Object.getOwnPropertyDescriptor%",!0);if(K)try{K([],"length")}catch{K=null}Q.exports=K}),xl=k0((A,Q)=>{var J=Sl(),K=jl(),C=SV(),U=C("Object.prototype.toString"),Y=nW()(),Z=vl(),X=typeof globalThis>"u"?global:globalThis,E=K(),H=C("Array.prototype.indexOf",!0)||function(V,D){for(var L=0;L-1}return Z?F(V):!1}}),s$1=k0((A,Q)=>{var J=Sl(),K=jl(),C=SV(),U=vl(),Y=C("Object.prototype.toString"),Z=nW()(),X=typeof globalThis>"u"?global:globalThis,E=K(),H=C("String.prototype.slice"),$={},I=Object.getPrototypeOf;Z&&U&&I&&J(E,function(V){if(typeof X[V]=="function"){var D=new X[V];if(Symbol.toStringTag in D){var L=I(D),R=U(L,Symbol.toStringTag);if(!R){var M=I(L);R=U(M,Symbol.toStringTag)}$[V]=R.get}}});var N=function(V){var D=!1;return J($,function(L,R){if(!D)try{var M=L.call(V);M===R&&(D=M)}catch{}}),D},F=xl();Q.exports=function(V){return F(V)?!Z||!(Symbol.toStringTag in V)?H(Y(V),8,-1):N(V):!1}}),o$1=k0((A)=>{var Q=d$1(),J=l$1(),K=s$1(),C=xl();function U(Z1){return Z1.call.bind(Z1)}var Y=typeof BigInt<"u",Z=typeof Symbol<"u",X=U(Object.prototype.toString),E=U(Number.prototype.valueOf),H=U(String.prototype.valueOf),$=U(Boolean.prototype.valueOf);Y&&(I=U(BigInt.prototype.valueOf));var I;Z&&(N=U(Symbol.prototype.valueOf));var N;function F(Z1,j1){if(typeof Z1!="object")return!1;try{return j1(Z1),!0}catch{return!1}}A.isArgumentsObject=Q,A.isGeneratorFunction=J,A.isTypedArray=C;function V(Z1){return typeof Promise<"u"&&Z1 instanceof Promise||Z1!==null&&typeof Z1=="object"&&typeof Z1.then=="function"&&typeof Z1.catch=="function"}A.isPromise=V;function D(Z1){return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?ArrayBuffer.isView(Z1):C(Z1)||p(Z1)}A.isArrayBufferView=D;function L(Z1){return K(Z1)==="Uint8Array"}A.isUint8Array=L;function R(Z1){return K(Z1)==="Uint8ClampedArray"}A.isUint8ClampedArray=R;function M(Z1){return K(Z1)==="Uint16Array"}A.isUint16Array=M;function T(Z1){return K(Z1)==="Uint32Array"}A.isUint32Array=T;function h(Z1){return K(Z1)==="Int8Array"}A.isInt8Array=h;function y(Z1){return K(Z1)==="Int16Array"}A.isInt16Array=y;function g(Z1){return K(Z1)==="Int32Array"}A.isInt32Array=g;function f(Z1){return K(Z1)==="Float32Array"}A.isFloat32Array=f;function u(Z1){return K(Z1)==="Float64Array"}A.isFloat64Array=u;function d(Z1){return K(Z1)==="BigInt64Array"}A.isBigInt64Array=d;function n(Z1){return K(Z1)==="BigUint64Array"}A.isBigUint64Array=n;function B(Z1){return X(Z1)==="[object Map]"}B.working=typeof Map<"u"&&B(/*@__PURE__*/new Map);function q(Z1){return typeof Map>"u"?!1:B.working?B(Z1):Z1 instanceof Map}A.isMap=q;function P(Z1){return X(Z1)==="[object Set]"}P.working=typeof Set<"u"&&P(/*@__PURE__*/new Set);function O(Z1){return typeof Set>"u"?!1:P.working?P(Z1):Z1 instanceof Set}A.isSet=O;function w(Z1){return X(Z1)==="[object WeakMap]"}w.working=typeof WeakMap<"u"&&w(/*@__PURE__*/new WeakMap);function k(Z1){return typeof WeakMap>"u"?!1:w.working?w(Z1):Z1 instanceof WeakMap}A.isWeakMap=k;function S(Z1){return X(Z1)==="[object WeakSet]"}S.working=typeof WeakSet<"u"&&S(/*@__PURE__*/new WeakSet);function _(Z1){return S(Z1)}A.isWeakSet=_;function W(Z1){return X(Z1)==="[object ArrayBuffer]"}W.working=typeof ArrayBuffer<"u"&&W(new ArrayBuffer);function j(Z1){return typeof ArrayBuffer>"u"?!1:W.working?W(Z1):Z1 instanceof ArrayBuffer}A.isArrayBuffer=j;function b(Z1){return X(Z1)==="[object DataView]"}b.working=typeof ArrayBuffer<"u"&&typeof DataView<"u"&&b(new DataView(new ArrayBuffer(1),0,1));function p(Z1){return typeof DataView>"u"?!1:b.working?b(Z1):Z1 instanceof DataView}A.isDataView=p;var s=typeof SharedArrayBuffer<"u"?SharedArrayBuffer:void 0;function r(Z1){return X(Z1)==="[object SharedArrayBuffer]"}function A1(Z1){return typeof s>"u"?!1:(typeof r.working>"u"&&(r.working=r(new s)),r.working?r(Z1):Z1 instanceof s)}A.isSharedArrayBuffer=A1;function Q1(Z1){return X(Z1)==="[object AsyncFunction]"}A.isAsyncFunction=Q1;function e(Z1){return X(Z1)==="[object Map Iterator]"}A.isMapIterator=e;function t(Z1){return X(Z1)==="[object Set Iterator]"}A.isSetIterator=t;function U1(Z1){return X(Z1)==="[object Generator]"}A.isGeneratorObject=U1;function O1(Z1){return X(Z1)==="[object WebAssembly.Module]"}A.isWebAssemblyCompiledModule=O1;function E1(Z1){return F(Z1,E)}A.isNumberObject=E1;function Y1(Z1){return F(Z1,H)}A.isStringObject=Y1;function i(Z1){return F(Z1,$)}A.isBooleanObject=i;function c(Z1){return Y&&F(Z1,I)}A.isBigIntObject=c;function o(Z1){return Z&&F(Z1,N)}A.isSymbolObject=o;function C1(Z1){return E1(Z1)||Y1(Z1)||i(Z1)||c(Z1)||o(Z1)}A.isBoxedPrimitive=C1;function q1(Z1){return typeof Uint8Array<"u"&&(j(Z1)||A1(Z1))}A.isAnyArrayBuffer=q1,["isProxy","isExternal","isModuleNamespaceObject"].forEach(function(Z1){Object.defineProperty(A,Z1,{enumerable:!1,value:function(){throw new Error(Z1+" is not supported in userland")}})})}),i$1=k0((A,Q)=>{Q.exports=function(J){return J&&typeof J=="object"&&typeof J.copy=="function"&&typeof J.fill=="function"&&typeof J.readUInt8=="function"}}),a$1=k0((A,Q)=>{typeof Object.create=="function"?Q.exports=function(J,K){K&&(J.super_=K,J.prototype=Object.create(K.prototype,{constructor:{value:J,enumerable:!1,writable:!0,configurable:!0}}))}:Q.exports=function(J,K){if(K){J.super_=K;var C=function(){};C.prototype=K.prototype,J.prototype=new C,J.prototype.constructor=J}}}),yl=k0((A)=>{var Q=Object.getOwnPropertyDescriptors||function(b){for(var p=Object.keys(b),s={},r=0;r=A1)return U1;switch(U1){case"%s":return String(r[s++]);case"%d":return Number(r[s++]);case"%j":try{return JSON.stringify(r[s++])}catch{return"[Circular]"}default:return U1}}),e=r[s];s"u")return function(){return A.deprecate(b,p).apply(this,arguments)};var s=!1;function r(){if(!s){if(process.throwDeprecation)throw new Error(p);process.traceDeprecation?console.trace(p):console.error(p),s=!0}return b.apply(this,arguments)}return r};var K={},C=/^$/;process.env.NODE_DEBUG&&(U=process.env.NODE_DEBUG,U=U.replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^").toUpperCase(),C=new RegExp("^"+U+"$","i"));var U;A.debuglog=function(b){if(b=b.toUpperCase(),!K[b])if(C.test(b)){var p=process.pid;K[b]=function(){var s=A.format.apply(A,arguments);console.error("%s %d: %s",b,p,s)}}else K[b]=function(){};return K[b]};function Y(b,p){var s={seen:[],stylize:X};return arguments.length>=3&&(s.depth=arguments[2]),arguments.length>=4&&(s.colors=arguments[3]),L(p)?s.showHidden=p:p&&A._extend(s,p),g(s.showHidden)&&(s.showHidden=!1),g(s.depth)&&(s.depth=2),g(s.colors)&&(s.colors=!1),g(s.customInspect)&&(s.customInspect=!0),s.colors&&(s.stylize=Z),H(s,b,s.depth)}A.inspect=Y,Y.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},Y.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Z(b,p){var s=Y.styles[p];return s?"\x1B["+Y.colors[s][0]+"m"+b+"\x1B["+Y.colors[s][1]+"m":b}function X(b,p){return b}function E(b){var p={};return b.forEach(function(s,r){p[s]=!0}),p}function H(b,p,s){if(b.customInspect&&p&&B(p.inspect)&&p.inspect!==A.inspect&&!(p.constructor&&p.constructor.prototype===p)){var r=p.inspect(s,b);return h(r)||(r=H(b,r,s)),r}var A1=$(b,p);if(A1)return A1;var Q1=Object.keys(p),e=E(Q1);if(b.showHidden&&(Q1=Object.getOwnPropertyNames(p)),n(p)&&(Q1.indexOf("message")>=0||Q1.indexOf("description")>=0))return I(p);if(Q1.length===0){if(B(p)){var t=p.name?": "+p.name:"";return b.stylize("[Function"+t+"]","special")}if(f(p))return b.stylize(RegExp.prototype.toString.call(p),"regexp");if(d(p))return b.stylize(Date.prototype.toString.call(p),"date");if(n(p))return I(p)}var U1="",O1=!1,E1=["{","}"];if(D(p)&&(O1=!0,E1=["[","]"]),B(p)){var Y1=p.name?": "+p.name:"";U1=" [Function"+Y1+"]"}if(f(p)&&(U1=" "+RegExp.prototype.toString.call(p)),d(p)&&(U1=" "+Date.prototype.toUTCString.call(p)),n(p)&&(U1=" "+I(p)),Q1.length===0&&(!O1||p.length==0))return E1[0]+U1+E1[1];if(s<0)return f(p)?b.stylize(RegExp.prototype.toString.call(p),"regexp"):b.stylize("[Object]","special");b.seen.push(p);var i;return O1?i=N(b,p,s,e,Q1):i=Q1.map(function(c){return F(b,p,s,e,c,O1)}),b.seen.pop(),V(i,U1,E1)}function $(b,p){if(g(p))return b.stylize("undefined","undefined");if(h(p)){var s="'"+JSON.stringify(p).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return b.stylize(s,"string")}if(T(p))return b.stylize(""+p,"number");if(L(p))return b.stylize(""+p,"boolean");if(R(p))return b.stylize("null","null")}function I(b){return"["+Error.prototype.toString.call(b)+"]"}function N(b,p,s,r,A1){for(var Q1=[],e=0,t=p.length;e-1&&(Q1?t=t.split(` -`).map(function(O1){return" "+O1}).join(` -`).slice(2):t=` -`+t.split(` -`).map(function(O1){return" "+O1}).join(` -`))):t=b.stylize("[Circular]","special")),g(e)){if(Q1&&A1.match(/^\d+$/))return t;e=JSON.stringify(""+A1),e.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(e=e.slice(1,-1),e=b.stylize(e,"name")):(e=e.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),e=b.stylize(e,"string"))}return e+": "+t}function V(b,p,s){var r=0,A1=b.reduce(function(Q1,e){return r++,e.indexOf(` -`)>=0&&r++,Q1+e.replace(/\u001b\[\d\d?m/g,"").length+1},0);return A1>60?s[0]+(p===""?"":p+` - `)+" "+b.join(`, - `)+" "+s[1]:s[0]+p+" "+b.join(", ")+" "+s[1]}A.types=o$1();function D(b){return Array.isArray(b)}A.isArray=D;function L(b){return typeof b=="boolean"}A.isBoolean=L;function R(b){return b===null}A.isNull=R;function M(b){return b==null}A.isNullOrUndefined=M;function T(b){return typeof b=="number"}A.isNumber=T;function h(b){return typeof b=="string"}A.isString=h;function y(b){return typeof b=="symbol"}A.isSymbol=y;function g(b){return b===void 0}A.isUndefined=g;function f(b){return u(b)&&P(b)==="[object RegExp]"}A.isRegExp=f,A.types.isRegExp=f;function u(b){return typeof b=="object"&&b!==null}A.isObject=u;function d(b){return u(b)&&P(b)==="[object Date]"}A.isDate=d,A.types.isDate=d;function n(b){return u(b)&&(P(b)==="[object Error]"||b instanceof Error)}A.isError=n,A.types.isNativeError=n;function B(b){return typeof b=="function"}A.isFunction=B;function q(b){return b===null||typeof b=="boolean"||typeof b=="number"||typeof b=="string"||typeof b=="symbol"||typeof b>"u"}A.isPrimitive=q,A.isBuffer=i$1();function P(b){return Object.prototype.toString.call(b)}function O(b){return b<10?"0"+b.toString(10):b.toString(10)}var w=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function k(){var b=/*@__PURE__*/new Date,p=[O(b.getHours()),O(b.getMinutes()),O(b.getSeconds())].join(":");return[b.getDate(),w[b.getMonth()],p].join(" ")}A.log=function(){console.log("%s - %s",k(),A.format.apply(A,arguments))},A.inherits=a$1(),A._extend=function(b,p){if(!p||!u(p))return b;for(var s=Object.keys(p),r=s.length;r--;)b[s[r]]=p[s[r]];return b};function S(b,p){return Object.prototype.hasOwnProperty.call(b,p)}var _=typeof Symbol<"u"?Symbol("util.promisify.custom"):void 0;A.promisify=function(b){if(typeof b!="function")throw new TypeError('The "original" argument must be of type Function');if(_&&b[_]){var p=b[_];if(typeof p!="function")throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(p,_,{value:p,enumerable:!1,writable:!1,configurable:!0}),p}function p(){for(var s,r,A1=new Promise(function(t,U1){s=t,r=U1}),Q1=[],e=0;eFV,TextEncoder:()=>LV,default:()=>hl});mB=RV(()=>{cW(DJ,zJ(yl())),LV=globalThis.TextEncoder,FV=globalThis.TextDecoder,hl={TextEncoder:LV,TextDecoder:FV}}),gl=k0((A,Q)=>{function J(L){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?J=function(R){return typeof R}:J=function(R){return R&&typeof Symbol=="function"&&R.constructor===Symbol&&R!==Symbol.prototype?"symbol":typeof R},J(L)}function K(L,R){if(!(L instanceof R))throw new TypeError("Cannot call a class as a function")}function C(L,R){return R&&(J(R)==="object"||typeof R=="function")?R:U(L)}function U(L){if(L===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return L}function Y(L){return Y=Object.setPrototypeOf?Object.getPrototypeOf:function(R){return R.__proto__||Object.getPrototypeOf(R)},Y(L)}function Z(L,R){if(typeof R!="function"&&R!==null)throw new TypeError("Super expression must either be null or a function");L.prototype=Object.create(R&&R.prototype,{constructor:{value:L,writable:!0,configurable:!0}}),R&&X(L,R)}function X(L,R){return X=Object.setPrototypeOf||function(M,T){return M.__proto__=T,M},X(L,R)}var E={},H,$;function I(L,R,M){M||(M=Error);function T(y,g,f){return typeof R=="string"?R:R(y,g,f)}var h=function(y){Z(g,y);function g(f,u,d){var n;return K(this,g),n=C(this,Y(g).call(this,T(f,u,d))),n.code=L,n}return g}(M);E[L]=h}function N(L,R){if(Array.isArray(L)){var M=L.length;return L=L.map(function(T){return String(T)}),M>2?"one of ".concat(R," ").concat(L.slice(0,M-1).join(", "),", or ")+L[M-1]:M===2?"one of ".concat(R," ").concat(L[0]," or ").concat(L[1]):"of ".concat(R," ").concat(L[0])}else return"of ".concat(R," ").concat(String(L))}function F(L,R,M){return L.substr(!M||M<0?0:+M,R.length)===R}function V(L,R,M){return(M===void 0||M>L.length)&&(M=L.length),L.substring(M-R.length,M)===R}function D(L,R,M){return typeof M!="number"&&(M=0),M+R.length>L.length?!1:L.indexOf(R,M)!==-1}I("ERR_AMBIGUOUS_ARGUMENT",'The "%s" argument is ambiguous. %s',TypeError),I("ERR_INVALID_ARG_TYPE",function(L,R,M){H===void 0&&(H=pW()),H(typeof L=="string","'name' must be a string");var T;typeof R=="string"&&F(R,"not ")?(T="must not be",R=R.replace(/^not /,"")):T="must be";var h;if(V(L," argument"))h="The ".concat(L," ").concat(T," ").concat(N(R,"type"));else{var y=D(L,".")?"property":"argument";h='The "'.concat(L,'" ').concat(y," ").concat(T," ").concat(N(R,"type"))}return h+=". Received type ".concat(J(M)),h},TypeError),I("ERR_INVALID_ARG_VALUE",function(L,R){var M=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"is invalid";$===void 0&&($=(mB(),N9(DJ)));var T=$.inspect(R);return T.length>128&&(T="".concat(T.slice(0,128),"...")),"The argument '".concat(L,"' ").concat(M,". Received ").concat(T)},TypeError,RangeError),I("ERR_INVALID_RETURN_VALUE",function(L,R,M){var T;return M&&M.constructor&&M.constructor.name?T="instance of ".concat(M.constructor.name):T="type ".concat(J(M)),"Expected ".concat(L,' to be returned from the "').concat(R,'"')+" function but got ".concat(T,".")},TypeError),I("ERR_MISSING_ARGS",function(){for(var L=arguments.length,R=new Array(L),M=0;M0,"At least one arg needs to be specified");var T="The ",h=R.length;switch(R=R.map(function(y){return'"'.concat(y,'"')}),h){case 1:T+="".concat(R[0]," argument");break;case 2:T+="".concat(R[0]," and ").concat(R[1]," arguments");break;default:T+=R.slice(0,h-1).join(", "),T+=", and ".concat(R[h-1]," arguments");break}return"".concat(T," must be specified")},TypeError),Q.exports.codes=E}),r$1=k0((A,Q)=>{function J(k){for(var S=1;S"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function I(k,S,_){return $()?I=Reflect.construct:I=function(W,j,b){var p=[null];p.push.apply(p,j);var s=Function.bind.apply(W,p),r=new s;return b&&F(r,b.prototype),r},I.apply(null,arguments)}function N(k){return Function.toString.call(k).indexOf("[native code]")!==-1}function F(k,S){return F=Object.setPrototypeOf||function(_,W){return _.__proto__=W,_},F(k,S)}function V(k){return V=Object.setPrototypeOf?Object.getPrototypeOf:function(S){return S.__proto__||Object.getPrototypeOf(S)},V(k)}function D(k){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?D=function(S){return typeof S}:D=function(S){return S&&typeof Symbol=="function"&&S.constructor===Symbol&&S!==Symbol.prototype?"symbol":typeof S},D(k)}var L=(mB(),N9(DJ)),R=L.inspect,M=gl(),T=M.codes.ERR_INVALID_ARG_TYPE;function h(k,S,_){return(_===void 0||_>k.length)&&(_=k.length),k.substring(_-S.length,_)===S}function y(k,S){if(S=Math.floor(S),k.length==0||S==0)return"";var _=k.length*S;for(S=Math.floor(Math.log(S)/Math.log(2));S;)k+=k,S--;return k+=k.substring(0,_-k.length),k}var g="",f="",u="",d="",n={deepStrictEqual:"Expected values to be strictly deep-equal:",strictEqual:"Expected values to be strictly equal:",strictEqualObject:'Expected "actual" to be reference-equal to "expected":',deepEqual:"Expected values to be loosely deep-equal:",equal:"Expected values to be loosely equal:",notDeepStrictEqual:'Expected "actual" not to be strictly deep-equal to:',notStrictEqual:'Expected "actual" to be strictly unequal to:',notStrictEqualObject:'Expected "actual" not to be reference-equal to "expected":',notDeepEqual:'Expected "actual" not to be loosely deep-equal to:',notEqual:'Expected "actual" to be loosely unequal to:',notIdentical:"Values identical but not reference-equal:"},B=10;function q(k){var S=Object.keys(k),_=Object.create(Object.getPrototypeOf(k));return S.forEach(function(W){_[W]=k[W]}),Object.defineProperty(_,"message",{value:k.message}),_}function P(k){return R(k,{compact:!1,customInspect:!1,depth:1000,maxArrayLength:1/0,showHidden:!1,breakLength:1/0,showProxy:!1,sorted:!0,getters:!0})}function O(k,S,_){var W="",j="",b=0,p="",s=!1,r=P(k),A1=r.split(` -`),Q1=P(S).split(` -`),e=0,t="";if(_==="strictEqual"&&D(k)==="object"&&D(S)==="object"&&k!==null&&S!==null&&(_="strictEqualObject"),A1.length===1&&Q1.length===1&&A1[0]!==Q1[0]){var U1=A1[0].length+Q1[0].length;if(U1<=B){if((D(k)!=="object"||k===null)&&(D(S)!=="object"||S===null)&&(k!==0||S!==0))return"".concat(n[_],` - -`)+"".concat(A1[0]," !== ").concat(Q1[0],` -`)}else if(_!=="strictEqualObject"){var O1=process.stderr&&process.stderr.isTTY?process.stderr.columns:80;if(U12&&(t=` - `.concat(y(" ",e),"^"),e=0)}}}for(var E1=A1[A1.length-1],Y1=Q1[Q1.length-1];E1===Y1&&(e++<2?p=` - `.concat(E1).concat(p):W=E1,A1.pop(),Q1.pop(),!(A1.length===0||Q1.length===0));)E1=A1[A1.length-1],Y1=Q1[Q1.length-1];var i=Math.max(A1.length,Q1.length);if(i===0){var c=r.split(` -`);if(c.length>30)for(c[26]="".concat(g,"...").concat(d);c.length>27;)c.pop();return"".concat(n.notIdentical,` - -`).concat(c.join(` -`),` -`)}e>3&&(p=` -`.concat(g,"...").concat(d).concat(p),s=!0),W!==""&&(p=` - `.concat(W).concat(p),W="");var o=0,C1=n[_]+` -`.concat(f,"+ actual").concat(d," ").concat(u,"- expected").concat(d),q1=" ".concat(g,"...").concat(d," Lines skipped");for(e=0;e1&&e>2&&(Z1>4?(j+=` -`.concat(g,"...").concat(d),s=!0):Z1>3&&(j+=` - `.concat(Q1[e-2]),o++),j+=` - `.concat(Q1[e-1]),o++),b=e,W+=` -`.concat(u,"-").concat(d," ").concat(Q1[e]),o++;else if(Q1.length1&&e>2&&(Z1>4?(j+=` -`.concat(g,"...").concat(d),s=!0):Z1>3&&(j+=` - `.concat(A1[e-2]),o++),j+=` - `.concat(A1[e-1]),o++),b=e,j+=` -`.concat(f,"+").concat(d," ").concat(A1[e]),o++;else{var j1=Q1[e],H1=A1[e],B1=H1!==j1&&(!h(H1,",")||H1.slice(0,-1)!==j1);B1&&h(j1,",")&&j1.slice(0,-1)===H1&&(B1=!1,H1+=","),B1?(Z1>1&&e>2&&(Z1>4?(j+=` -`.concat(g,"...").concat(d),s=!0):Z1>3&&(j+=` - `.concat(A1[e-2]),o++),j+=` - `.concat(A1[e-1]),o++),b=e,j+=` -`.concat(f,"+").concat(d," ").concat(H1),W+=` -`.concat(u,"-").concat(d," ").concat(j1),o+=2):(j+=W,W="",(Z1===1||e===0)&&(j+=` - `.concat(H1),o++))}if(o>20&&e30)for(e[26]="".concat(g,"...").concat(d);e.length>27;)e.pop();e.length===1?W=Z(this,V(S).call(this,"".concat(Q1," ").concat(e[0]))):W=Z(this,V(S).call(this,"".concat(Q1,` - -`).concat(e.join(` -`),` -`)))}else{var t=P(s),U1="",O1=n[b];b==="notDeepEqual"||b==="notEqual"?(t="".concat(n[b],` - -`).concat(t),t.length>1024&&(t="".concat(t.slice(0,1021),"..."))):(U1="".concat(P(r)),t.length>512&&(t="".concat(t.slice(0,509),"...")),U1.length>512&&(U1="".concat(U1.slice(0,509),"...")),b==="deepEqual"||b==="equal"?t="".concat(O1,` - -`).concat(t,` - -should equal - -`):U1=" ".concat(b," ").concat(U1)),W=Z(this,V(S).call(this,"".concat(t).concat(U1)))}return Error.stackTraceLimit=A1,W.generatedMessage=!j,Object.defineProperty(X(W),"name",{value:"AssertionError [ERR_ASSERTION]",enumerable:!1,writable:!0,configurable:!0}),W.code="ERR_ASSERTION",W.actual=s,W.expected=r,W.operator=b,Error.captureStackTrace&&Error.captureStackTrace(X(W),p),W.stack,W.name="AssertionError",Z(W)}return Y(S,[{key:"toString",value:function(){return"".concat(this.name," [").concat(this.code,"]: ").concat(this.message)}},{key:R.custom,value:function(_,W){return R(this,J({},W,{customInspect:!1,depth:0}))}}]),S}(H(Error));Q.exports=w}),t$1=k0((A,Q)=>{function J(C,U){if(C==null)throw new TypeError("Cannot convert first argument to object");for(var Y=Object(C),Z=1;Z{var J=Object.prototype.toString;Q.exports=function(K){var C=J.call(K),U=C==="[object Arguments]";return U||(U=C!=="[object Array]"&&K!==null&&typeof K=="object"&&typeof K.length=="number"&&K.length>=0&&J.call(K.callee)==="[object Function]"),U}}),e$1=k0((A,Q)=>{var J;Object.keys||(K=Object.prototype.hasOwnProperty,C=Object.prototype.toString,U=bl(),Y=Object.prototype.propertyIsEnumerable,Z=!Y.call({toString:null},"toString"),X=Y.call(function(){},"prototype"),E=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],H=function(F){var V=F.constructor;return V&&V.prototype===F},$={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},I=function(){if(typeof window>"u")return!1;for(var F in window)try{if(!$["$"+F]&&K.call(window,F)&&window[F]!==null&&typeof window[F]=="object")try{H(window[F])}catch{return!0}}catch{return!0}return!1}(),N=function(F){if(typeof window>"u"||!I)return H(F);try{return H(F)}catch{return!1}},J=function(F){var V=F!==null&&typeof F=="object",D=C.call(F)==="[object Function]",L=U(F),R=V&&C.call(F)==="[object String]",M=[];if(!V&&!D&&!L)throw new TypeError("Object.keys called on a non-object");var T=X&&D;if(R&&F.length>0&&!K.call(F,0))for(var h=0;h0)for(var y=0;y{var J=Array.prototype.slice,K=bl(),C=Object.keys,U=C?function(Z){return C(Z)}:e$1(),Y=Object.keys;U.shim=function(){if(Object.keys){var Z=function(){var X=Object.keys(arguments);return X&&X.length===arguments.length}(1,2);Z||(Object.keys=function(X){return K(X)?Y(J.call(X)):Y(X)})}else Object.keys=U;return Object.keys||U},Q.exports=U}),QH1=k0((A,Q)=>{var J=sW(),K=J("%Object.defineProperty%",!0),C=function(){if(K)try{return K({},"a",{value:1}),!0}catch{return!1}return!1};C.hasArrayLengthDefineBug=function(){if(!C())return null;try{return K([],"length",{value:1}).length!==1}catch{return!0}},Q.exports=C}),oW=k0((A,Q)=>{var J=AH1(),K=typeof Symbol=="function"&&typeof Symbol("foo")=="symbol",C=Object.prototype.toString,U=Array.prototype.concat,Y=Object.defineProperty,Z=function(I){return typeof I=="function"&&C.call(I)==="[object Function]"},X=QH1()(),E=Y&&X,H=function(I,N,F,V){if(N in I){if(V===!0){if(I[N]===F)return}else if(!Z(V)||!V())return}E?Y(I,N,{configurable:!0,enumerable:!1,value:F,writable:!0}):I[N]=F},$=function(I,N){var F=arguments.length>2?arguments[2]:{},V=J(N);K&&(V=U.call(V,Object.getOwnPropertySymbols(N)));for(var D=0;D{var J=function(K){return K!==K};Q.exports=function(K,C){return K===0&&C===0?1/K===1/C:!!(K===C||J(K)&&J(C))}}),pl=k0((A,Q)=>{var J=fl();Q.exports=function(){return typeof Object.is=="function"?Object.is:J}}),JH1=k0((A,Q)=>{var J=pl(),K=oW();Q.exports=function(){var C=J();return K(Object,{is:C},{is:function(){return Object.is!==C}}),C}}),ul=k0((A,Q)=>{var J=oW(),K=kV(),C=fl(),U=pl(),Y=JH1(),Z=K(U(),Object);J(Z,{getPolyfill:U,implementation:C,shim:Y}),Q.exports=Z}),ml=k0((A,Q)=>{Q.exports=function(J){return J!==J}}),cl=k0((A,Q)=>{var J=ml();Q.exports=function(){return Number.isNaN&&Number.isNaN(NaN)&&!Number.isNaN("a")?Number.isNaN:J}}),KH1=k0((A,Q)=>{var J=oW(),K=cl();Q.exports=function(){var C=K();return J(Number,{isNaN:C},{isNaN:function(){return Number.isNaN!==C}}),C}}),CH1=k0((A,Q)=>{var J=kV(),K=oW(),C=ml(),U=cl(),Y=KH1(),Z=J(U(),Number);K(Z,{getPolyfill:U,implementation:C,shim:Y}),Q.exports=Z}),YH1=k0((A,Q)=>{function J(G1,w1){return U(G1)||C(G1,w1)||K()}function K(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}function C(G1,w1){var G=[],z=!0,x=!1,m=void 0;try{for(var l=G1[Symbol.iterator](),a;!(z=(a=l.next()).done)&&(G.push(a.value),!(w1&&G.length===w1));z=!0);}catch(K1){x=!0,m=K1}finally{try{!z&&l.return!=null&&l.return()}finally{if(x)throw m}}return G}function U(G1){if(Array.isArray(G1))return G1}function Y(G1){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Y=function(w1){return typeof w1}:Y=function(w1){return w1&&typeof Symbol=="function"&&w1.constructor===Symbol&&w1!==Symbol.prototype?"symbol":typeof w1},Y(G1)}var Z=/a/g.flags!==void 0,X=function(G1){var w1=[];return G1.forEach(function(G){return w1.push(G)}),w1},E=function(G1){var w1=[];return G1.forEach(function(G,z){return w1.push([z,G])}),w1},H=Object.is?Object.is:ul(),$=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols:function(){return[]},I=Number.isNaN?Number.isNaN:CH1();function N(G1){return G1.call.bind(G1)}var F=N(Object.prototype.hasOwnProperty),V=N(Object.prototype.propertyIsEnumerable),D=N(Object.prototype.toString),L=(mB(),N9(DJ)).types,R=L.isAnyArrayBuffer,M=L.isArrayBufferView,T=L.isDate,h=L.isMap,y=L.isRegExp,g=L.isSet,f=L.isNativeError,u=L.isBoxedPrimitive,d=L.isNumberObject,n=L.isStringObject,B=L.isBooleanObject,q=L.isBigIntObject,P=L.isSymbolObject,O=L.isFloat32Array,w=L.isFloat64Array;function k(G1){if(G1.length===0||G1.length>10)return!0;for(var w1=0;w157)return!0}return G1.length===10&&G1>=Math.pow(2,32)}function S(G1){return Object.keys(G1).filter(k).concat($(G1).filter(Object.prototype.propertyIsEnumerable.bind(G1)))}function _(G1,w1){if(G1===w1)return 0;for(var G=G1.length,z=w1.length,x=0,m=Math.min(G,z);x{function J(p){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?J=function(s){return typeof s}:J=function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},J(p)}function K(p,s){if(!(p instanceof s))throw new TypeError("Cannot call a class as a function")}var C=gl(),U=C.codes,Y=U.ERR_AMBIGUOUS_ARGUMENT,Z=U.ERR_INVALID_ARG_TYPE,X=U.ERR_INVALID_ARG_VALUE,E=U.ERR_INVALID_RETURN_VALUE,H=U.ERR_MISSING_ARGS,$=r$1(),I=(mB(),N9(DJ)),N=I.inspect,F=(mB(),N9(DJ)).types,V=F.isPromise,D=F.isRegExp,L=Object.assign?Object.assign:t$1().assign,R=Object.is?Object.is:ul(),M,T;function h(){var p=YH1();M=p.isDeepEqual,T=p.isDeepStrictEqual}var y=!1,g=Q.exports=B,f={};function u(p){throw p.message instanceof Error?p.message:new $(p)}function d(p,s,r,A1,Q1){var e=arguments.length,t;if(e===0)t="Failed";else if(e===1)r=p,p=void 0;else{if(y===!1){y=!0;var U1=process.emitWarning?process.emitWarning:console.warn.bind(console);U1("assert.fail() with more than one argument is deprecated. Please use assert.strictEqual() instead or only pass a message.","DeprecationWarning","DEP0094")}e===2&&(A1="!=")}if(r instanceof Error)throw r;var O1={actual:p,expected:s,operator:A1===void 0?"fail":A1,stackStartFn:Q1||d};r!==void 0&&(O1.message=r);var E1=new $(O1);throw t&&(E1.message=t,E1.generatedMessage=!0),E1}g.fail=d,g.AssertionError=$;function n(p,s,r,A1){if(!r){var Q1=!1;if(s===0)Q1=!0,A1="No value argument passed to `assert.ok()`";else if(A1 instanceof Error)throw A1;var e=new $({actual:r,expected:!0,message:A1,operator:"==",stackStartFn:p});throw e.generatedMessage=Q1,e}}function B(){for(var p=arguments.length,s=new Array(p),r=0;r1?r-1:0),Q1=1;Q11?r-1:0),Q1=1;Q11?r-1:0),Q1=1;Q11?r-1:0),Q1=1;Q1{function J(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}Q.exports=J}),iW=k0((A)=>{var Q=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function J(U,Y){return Object.prototype.hasOwnProperty.call(U,Y)}A.assign=function(U){for(var Y=Array.prototype.slice.call(arguments,1);Y.length;){var Z=Y.shift();if(Z){if(typeof Z!="object")throw new TypeError(Z+"must be non-object");for(var X in Z)J(Z,X)&&(U[X]=Z[X])}}return U},A.shrinkBuf=function(U,Y){return U.length===Y?U:U.subarray?U.subarray(0,Y):(U.length=Y,U)};var K={arraySet:function(U,Y,Z,X,E){if(Y.subarray&&U.subarray){U.set(Y.subarray(Z,Z+X),E);return}for(var H=0;H{var Q=iW(),J=4,K=0,C=1,U=2;function Y(a){for(var K1=a.length;--K1>=0;)a[K1]=0}var Z=0,X=1,E=2,H=3,$=258,I=29,N=256,F=N+1+I,V=30,D=19,L=2*F+1,R=15,M=16,T=7,h=256,y=16,g=17,f=18,u=[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],d=[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=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],B=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],q=512,P=new Array((F+2)*2);Y(P);var O=new Array(V*2);Y(O);var w=new Array(q);Y(w);var k=new Array($-H+1);Y(k);var S=new Array(I);Y(S);var _=new Array(V);Y(_);function W(a,K1,F1,R1,X1){this.static_tree=a,this.extra_bits=K1,this.extra_base=F1,this.elems=R1,this.max_length=X1,this.has_stree=a&&a.length}var j,b,p;function s(a,K1){this.dyn_tree=a,this.max_code=0,this.stat_desc=K1}function r(a){return a<256?w[a]:w[256+(a>>>7)]}function A1(a,K1){a.pending_buf[a.pending++]=K1&255,a.pending_buf[a.pending++]=K1>>>8&255}function Q1(a,K1,F1){a.bi_valid>M-F1?(a.bi_buf|=K1<>M-a.bi_valid,a.bi_valid+=F1-M):(a.bi_buf|=K1<>>=1,F1<<=1;while(--K1>0);return F1>>>1}function U1(a){a.bi_valid===16?(A1(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=a.bi_buf&255,a.bi_buf>>=8,a.bi_valid-=8)}function O1(a,K1){var{dyn_tree:F1,max_code:R1}=K1,X1=K1.stat_desc.static_tree,W1=K1.stat_desc.has_stree,$1=K1.stat_desc.extra_bits,N1=K1.stat_desc.extra_base,_1=K1.stat_desc.max_length,J1,z1,M1,L1,V1,S1,O0=0;for(L1=0;L1<=R;L1++)a.bl_count[L1]=0;for(F1[a.heap[a.heap_max]*2+1]=0,J1=a.heap_max+1;J1_1&&(L1=_1,O0++),F1[z1*2+1]=L1,!(z1>R1)&&(a.bl_count[L1]++,V1=0,z1>=N1&&(V1=$1[z1-N1]),S1=F1[z1*2],a.opt_len+=S1*(L1+V1),W1&&(a.static_len+=S1*(X1[z1*2+1]+V1)));if(O0!==0){do{for(L1=_1-1;a.bl_count[L1]===0;)L1--;a.bl_count[L1]--,a.bl_count[L1+1]+=2,a.bl_count[_1]--,O0-=2}while(O0>0);for(L1=_1;L1!==0;L1--)for(z1=a.bl_count[L1];z1!==0;)M1=a.heap[--J1],!(M1>R1)&&(F1[M1*2+1]!==L1&&(a.opt_len+=(L1-F1[M1*2+1])*F1[M1*2],F1[M1*2+1]=L1),z1--)}}function E1(a,K1,F1){var R1=new Array(R+1),X1=0,W1,$1;for(W1=1;W1<=R;W1++)R1[W1]=X1=X1+F1[W1-1]<<1;for($1=0;$1<=K1;$1++){var N1=a[$1*2+1];N1!==0&&(a[$1*2]=t(R1[N1]++,N1))}}function Y1(){var a,K1,F1,R1,X1,W1=new Array(R+1);for(F1=0,R1=0;R1>=7;R18?A1(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function o(a,K1,F1,R1){c(a),R1&&(A1(a,F1),A1(a,~F1)),Q.arraySet(a.pending_buf,a.window,K1,F1,a.pending),a.pending+=F1}function C1(a,K1,F1,R1){var X1=K1*2,W1=F1*2;return a[X1]>1;$1>=1;$1--)q1(a,F1,$1);J1=W1;do $1=a.heap[1],a.heap[1]=a.heap[a.heap_len--],q1(a,F1,1),N1=a.heap[1],a.heap[--a.heap_max]=$1,a.heap[--a.heap_max]=N1,F1[J1*2]=F1[$1*2]+F1[N1*2],a.depth[J1]=(a.depth[$1]>=a.depth[N1]?a.depth[$1]:a.depth[N1])+1,F1[$1*2+1]=F1[N1*2+1]=J1,a.heap[1]=J1++,q1(a,F1,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],O1(a,K1),E1(F1,_1,a.bl_count)}function H1(a,K1,F1){var R1,X1=-1,W1,$1=K1[1],N1=0,_1=7,J1=4;for($1===0&&(_1=138,J1=3),K1[(F1+1)*2+1]=65535,R1=0;R1<=F1;R1++)W1=$1,$1=K1[(R1+1)*2+1],!(++N1<_1&&W1===$1)&&(N1=3&&a.bl_tree[B[K1]*2+1]===0;K1--);return a.opt_len+=3*(K1+1)+5+5+4,K1}function D1(a,K1,F1,R1){var X1;for(Q1(a,K1-257,5),Q1(a,F1-1,5),Q1(a,R1-4,4),X1=0;X1>>=1)if(K1&1&&a.dyn_ltree[F1*2]!==0)return K;if(a.dyn_ltree[18]!==0||a.dyn_ltree[20]!==0||a.dyn_ltree[26]!==0)return C;for(F1=32;F10?(a.strm.data_type===U&&(a.strm.data_type=G1(a)),j1(a,a.l_desc),j1(a,a.d_desc),$1=k1(a),X1=a.opt_len+3+7>>>3,W1=a.static_len+3+7>>>3,W1<=X1&&(X1=W1)):X1=W1=F1+5,F1+4<=X1&&K1!==-1?z(a,K1,F1,R1):a.strategy===J||W1===X1?(Q1(a,(X<<1)+(R1?1:0),3),Z1(a,P,O)):(Q1(a,(E<<1)+(R1?1:0),3),D1(a,a.l_desc.max_code+1,a.d_desc.max_code+1,$1+1),Z1(a,a.dyn_ltree,a.dyn_dtree)),i(a),R1&&c(a)}function l(a,K1,F1){return a.pending_buf[a.d_buf+a.last_lit*2]=K1>>>8&255,a.pending_buf[a.d_buf+a.last_lit*2+1]=K1&255,a.pending_buf[a.l_buf+a.last_lit]=F1&255,a.last_lit++,K1===0?a.dyn_ltree[F1*2]++:(a.matches++,K1--,a.dyn_ltree[(k[F1]+N+1)*2]++,a.dyn_dtree[r(K1)*2]++),a.last_lit===a.lit_bufsize-1}A._tr_init=G,A._tr_stored_block=z,A._tr_flush_block=m,A._tr_tally=l,A._tr_align=x}),dl=k0((A,Q)=>{function J(K,C,U,Y){for(var Z=K&65535|0,X=K>>>16&65535|0,E=0;U!==0;){E=U>2000?2000:U,U-=E;do Z=Z+C[Y++]|0,X=X+Z|0;while(--E);Z%=65521,X%=65521}return Z|X<<16|0}Q.exports=J}),ll=k0((A,Q)=>{function J(){for(var U,Y=[],Z=0;Z<256;Z++){U=Z;for(var X=0;X<8;X++)U=U&1?3988292384^U>>>1:U>>>1;Y[Z]=U}return Y}var K=J();function C(U,Y,Z,X){var E=K,H=X+Z;U^=-1;for(var $=X;$>>8^E[(U^Y[$])&255];return U^-1}Q.exports=C}),BH1=k0((A,Q)=>{Q.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}}),XH1=k0((A)=>{var Q=iW(),J=ZH1(),K=dl(),C=ll(),U=BH1(),Y=0,Z=1,X=3,E=4,H=5,$=0,I=1,N=-2,F=-3,V=-5,D=-1,L=1,R=2,M=3,T=4,h=0,y=2,g=8,f=9,u=15,d=8,n=29,B=256,q=B+1+n,P=30,O=19,w=2*q+1,k=15,S=3,_=258,W=_+S+1,j=32,b=42,p=69,s=73,r=91,A1=103,Q1=113,e=666,t=1,U1=2,O1=3,E1=4,Y1=3;function i(J1,z1){return J1.msg=U[z1],z1}function c(J1){return(J1<<1)-(J1>4?9:0)}function o(J1){for(var z1=J1.length;--z1>=0;)J1[z1]=0}function C1(J1){var z1=J1.state,M1=z1.pending;M1>J1.avail_out&&(M1=J1.avail_out),M1!==0&&(Q.arraySet(J1.output,z1.pending_buf,z1.pending_out,M1,J1.next_out),J1.next_out+=M1,z1.pending_out+=M1,J1.total_out+=M1,J1.avail_out-=M1,z1.pending-=M1,z1.pending===0&&(z1.pending_out=0))}function q1(J1,z1){J._tr_flush_block(J1,J1.block_start>=0?J1.block_start:-1,J1.strstart-J1.block_start,z1),J1.block_start=J1.strstart,C1(J1.strm)}function Z1(J1,z1){J1.pending_buf[J1.pending++]=z1}function j1(J1,z1){J1.pending_buf[J1.pending++]=z1>>>8&255,J1.pending_buf[J1.pending++]=z1&255}function H1(J1,z1,M1,L1){var V1=J1.avail_in;return V1>L1&&(V1=L1),V1===0?0:(J1.avail_in-=V1,Q.arraySet(z1,J1.input,J1.next_in,V1,M1),J1.state.wrap===1?J1.adler=K(J1.adler,z1,V1,M1):J1.state.wrap===2&&(J1.adler=C(J1.adler,z1,V1,M1)),J1.next_in+=V1,J1.total_in+=V1,V1)}function B1(J1,z1){var{max_chain_length:M1,strstart:L1}=J1,V1,S1,O0=J1.prev_length,h1=J1.nice_match,b1=J1.strstart>J1.w_size-W?J1.strstart-(J1.w_size-W):0,f0=J1.window,e1=J1.w_mask,s1=J1.prev,o0=J1.strstart+_,a1=f0[L1+O0-1],r1=f0[L1+O0];J1.prev_length>=J1.good_match&&(M1>>=2),h1>J1.lookahead&&(h1=J1.lookahead);do if(V1=z1,!(f0[V1+O0]!==r1||f0[V1+O0-1]!==a1||f0[V1]!==f0[L1]||f0[++V1]!==f0[L1+1])){L1+=2,V1++;do;while(f0[++L1]===f0[++V1]&&f0[++L1]===f0[++V1]&&f0[++L1]===f0[++V1]&&f0[++L1]===f0[++V1]&&f0[++L1]===f0[++V1]&&f0[++L1]===f0[++V1]&&f0[++L1]===f0[++V1]&&f0[++L1]===f0[++V1]&&L1O0){if(J1.match_start=z1,O0=S1,S1>=h1)break;a1=f0[L1+O0-1],r1=f0[L1+O0]}}while((z1=s1[z1&e1])>b1&&--M1!==0);return O0<=J1.lookahead?O0:J1.lookahead}function k1(J1){var z1=J1.w_size,M1,L1,V1,S1,O0;do{if(S1=J1.window_size-J1.lookahead-J1.strstart,J1.strstart>=z1+(z1-W)){Q.arraySet(J1.window,J1.window,z1,z1,0),J1.match_start-=z1,J1.strstart-=z1,J1.block_start-=z1,L1=J1.hash_size,M1=L1;do V1=J1.head[--M1],J1.head[M1]=V1>=z1?V1-z1:0;while(--L1);L1=z1,M1=L1;do V1=J1.prev[--M1],J1.prev[M1]=V1>=z1?V1-z1:0;while(--L1);S1+=z1}if(J1.strm.avail_in===0)break;if(L1=H1(J1.strm,J1.window,J1.strstart+J1.lookahead,S1),J1.lookahead+=L1,J1.lookahead+J1.insert>=S)for(O0=J1.strstart-J1.insert,J1.ins_h=J1.window[O0],J1.ins_h=(J1.ins_h<J1.pending_buf_size-5&&(M1=J1.pending_buf_size-5);;){if(J1.lookahead<=1){if(k1(J1),J1.lookahead===0&&z1===Y)return t;if(J1.lookahead===0)break}J1.strstart+=J1.lookahead,J1.lookahead=0;var L1=J1.block_start+M1;if((J1.strstart===0||J1.strstart>=L1)&&(J1.lookahead=J1.strstart-L1,J1.strstart=L1,q1(J1,!1),J1.strm.avail_out===0)||J1.strstart-J1.block_start>=J1.w_size-W&&(q1(J1,!1),J1.strm.avail_out===0))return t}return J1.insert=0,z1===E?(q1(J1,!0),J1.strm.avail_out===0?O1:E1):(J1.strstart>J1.block_start&&(q1(J1,!1),J1.strm.avail_out),t)}function G1(J1,z1){for(var M1,L1;;){if(J1.lookahead=S&&(J1.ins_h=(J1.ins_h<=S)if(L1=J._tr_tally(J1,J1.strstart-J1.match_start,J1.match_length-S),J1.lookahead-=J1.match_length,J1.match_length<=J1.max_lazy_match&&J1.lookahead>=S){J1.match_length--;do J1.strstart++,J1.ins_h=(J1.ins_h<=S&&(J1.ins_h=(J1.ins_h<4096)&&(J1.match_length=S-1)),J1.prev_length>=S&&J1.match_length<=J1.prev_length){V1=J1.strstart+J1.lookahead-S,L1=J._tr_tally(J1,J1.strstart-1-J1.prev_match,J1.prev_length-S),J1.lookahead-=J1.prev_length-1,J1.prev_length-=2;do++J1.strstart<=V1&&(J1.ins_h=(J1.ins_h<=S&&J1.strstart>0&&(V1=J1.strstart-1,L1=O0[V1],L1===O0[++V1]&&L1===O0[++V1]&&L1===O0[++V1])){S1=J1.strstart+_;do;while(L1===O0[++V1]&&L1===O0[++V1]&&L1===O0[++V1]&&L1===O0[++V1]&&L1===O0[++V1]&&L1===O0[++V1]&&L1===O0[++V1]&&L1===O0[++V1]&&V1J1.lookahead&&(J1.match_length=J1.lookahead)}if(J1.match_length>=S?(M1=J._tr_tally(J1,1,J1.match_length-S),J1.lookahead-=J1.match_length,J1.strstart+=J1.match_length,J1.match_length=0):(M1=J._tr_tally(J1,0,J1.window[J1.strstart]),J1.lookahead--,J1.strstart++),M1&&(q1(J1,!1),J1.strm.avail_out===0))return t}return J1.insert=0,z1===E?(q1(J1,!0),J1.strm.avail_out===0?O1:E1):J1.last_lit&&(q1(J1,!1),J1.strm.avail_out===0)?t:U1}function z(J1,z1){for(var M1;;){if(J1.lookahead===0&&(k1(J1),J1.lookahead===0)){if(z1===Y)return t;break}if(J1.match_length=0,M1=J._tr_tally(J1,0,J1.window[J1.strstart]),J1.lookahead--,J1.strstart++,M1&&(q1(J1,!1),J1.strm.avail_out===0))return t}return J1.insert=0,z1===E?(q1(J1,!0),J1.strm.avail_out===0?O1:E1):J1.last_lit&&(q1(J1,!1),J1.strm.avail_out===0)?t:U1}function x(J1,z1,M1,L1,V1){this.good_length=J1,this.max_lazy=z1,this.nice_length=M1,this.max_chain=L1,this.func=V1}var m=[new x(0,0,0,0,D1),new x(4,4,8,4,G1),new x(4,5,16,8,G1),new x(4,6,32,32,G1),new x(4,4,16,16,w1),new x(8,16,32,32,w1),new x(8,16,128,128,w1),new x(8,32,128,256,w1),new x(32,128,258,1024,w1),new x(32,258,258,4096,w1)];function l(J1){J1.window_size=2*J1.w_size,o(J1.head),J1.max_lazy_match=m[J1.level].max_lazy,J1.good_match=m[J1.level].good_length,J1.nice_match=m[J1.level].nice_length,J1.max_chain_length=m[J1.level].max_chain,J1.strstart=0,J1.block_start=0,J1.lookahead=0,J1.insert=0,J1.match_length=J1.prev_length=S-1,J1.match_available=0,J1.ins_h=0}function a(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=g,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Q.Buf16(w*2),this.dyn_dtree=new Q.Buf16((2*P+1)*2),this.bl_tree=new Q.Buf16((2*O+1)*2),o(this.dyn_ltree),o(this.dyn_dtree),o(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Q.Buf16(k+1),this.heap=new Q.Buf16(2*q+1),o(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Q.Buf16(2*q+1),o(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function K1(J1){var z1;return!J1||!J1.state?i(J1,N):(J1.total_in=J1.total_out=0,J1.data_type=y,z1=J1.state,z1.pending=0,z1.pending_out=0,z1.wrap<0&&(z1.wrap=-z1.wrap),z1.status=z1.wrap?b:Q1,J1.adler=z1.wrap===2?0:1,z1.last_flush=Y,J._tr_init(z1),$)}function F1(J1){var z1=K1(J1);return z1===$&&l(J1.state),z1}function R1(J1,z1){return!J1||!J1.state||J1.state.wrap!==2?N:(J1.state.gzhead=z1,$)}function X1(J1,z1,M1,L1,V1,S1){if(!J1)return N;var O0=1;if(z1===D&&(z1=6),L1<0?(O0=0,L1=-L1):L1>15&&(O0=2,L1-=16),V1<1||V1>f||M1!==g||L1<8||L1>15||z1<0||z1>9||S1<0||S1>T)return i(J1,N);L1===8&&(L1=9);var h1=new a;return J1.state=h1,h1.strm=J1,h1.wrap=O0,h1.gzhead=null,h1.w_bits=L1,h1.w_size=1<H||z1<0)return J1?i(J1,N):N;if(L1=J1.state,!J1.output||!J1.input&&J1.avail_in!==0||L1.status===e&&z1!==E)return i(J1,J1.avail_out===0?V:N);if(L1.strm=J1,M1=L1.last_flush,L1.last_flush=z1,L1.status===b)if(L1.wrap===2)J1.adler=0,Z1(L1,31),Z1(L1,139),Z1(L1,8),L1.gzhead?(Z1(L1,(L1.gzhead.text?1:0)+(L1.gzhead.hcrc?2:0)+(L1.gzhead.extra?4:0)+(L1.gzhead.name?8:0)+(L1.gzhead.comment?16:0)),Z1(L1,L1.gzhead.time&255),Z1(L1,L1.gzhead.time>>8&255),Z1(L1,L1.gzhead.time>>16&255),Z1(L1,L1.gzhead.time>>24&255),Z1(L1,L1.level===9?2:L1.strategy>=R||L1.level<2?4:0),Z1(L1,L1.gzhead.os&255),L1.gzhead.extra&&L1.gzhead.extra.length&&(Z1(L1,L1.gzhead.extra.length&255),Z1(L1,L1.gzhead.extra.length>>8&255)),L1.gzhead.hcrc&&(J1.adler=C(J1.adler,L1.pending_buf,L1.pending,0)),L1.gzindex=0,L1.status=p):(Z1(L1,0),Z1(L1,0),Z1(L1,0),Z1(L1,0),Z1(L1,0),Z1(L1,L1.level===9?2:L1.strategy>=R||L1.level<2?4:0),Z1(L1,Y1),L1.status=Q1);else{var O0=g+(L1.w_bits-8<<4)<<8,h1=-1;L1.strategy>=R||L1.level<2?h1=0:L1.level<6?h1=1:L1.level===6?h1=2:h1=3,O0|=h1<<6,L1.strstart!==0&&(O0|=j),O0+=31-O0%31,L1.status=Q1,j1(L1,O0),L1.strstart!==0&&(j1(L1,J1.adler>>>16),j1(L1,J1.adler&65535)),J1.adler=1}if(L1.status===p)if(L1.gzhead.extra){for(V1=L1.pending;L1.gzindex<(L1.gzhead.extra.length&65535)&&!(L1.pending===L1.pending_buf_size&&(L1.gzhead.hcrc&&L1.pending>V1&&(J1.adler=C(J1.adler,L1.pending_buf,L1.pending-V1,V1)),C1(J1),V1=L1.pending,L1.pending===L1.pending_buf_size));)Z1(L1,L1.gzhead.extra[L1.gzindex]&255),L1.gzindex++;L1.gzhead.hcrc&&L1.pending>V1&&(J1.adler=C(J1.adler,L1.pending_buf,L1.pending-V1,V1)),L1.gzindex===L1.gzhead.extra.length&&(L1.gzindex=0,L1.status=s)}else L1.status=s;if(L1.status===s)if(L1.gzhead.name){V1=L1.pending;do{if(L1.pending===L1.pending_buf_size&&(L1.gzhead.hcrc&&L1.pending>V1&&(J1.adler=C(J1.adler,L1.pending_buf,L1.pending-V1,V1)),C1(J1),V1=L1.pending,L1.pending===L1.pending_buf_size)){S1=1;break}L1.gzindexV1&&(J1.adler=C(J1.adler,L1.pending_buf,L1.pending-V1,V1)),S1===0&&(L1.gzindex=0,L1.status=r)}else L1.status=r;if(L1.status===r)if(L1.gzhead.comment){V1=L1.pending;do{if(L1.pending===L1.pending_buf_size&&(L1.gzhead.hcrc&&L1.pending>V1&&(J1.adler=C(J1.adler,L1.pending_buf,L1.pending-V1,V1)),C1(J1),V1=L1.pending,L1.pending===L1.pending_buf_size)){S1=1;break}L1.gzindexV1&&(J1.adler=C(J1.adler,L1.pending_buf,L1.pending-V1,V1)),S1===0&&(L1.status=A1)}else L1.status=A1;if(L1.status===A1&&(L1.gzhead.hcrc?(L1.pending+2>L1.pending_buf_size&&C1(J1),L1.pending+2<=L1.pending_buf_size&&(Z1(L1,J1.adler&255),Z1(L1,J1.adler>>8&255),J1.adler=0,L1.status=Q1)):L1.status=Q1),L1.pending!==0){if(C1(J1),J1.avail_out===0)return L1.last_flush=-1,$}else if(J1.avail_in===0&&c(z1)<=c(M1)&&z1!==E)return i(J1,V);if(L1.status===e&&J1.avail_in!==0)return i(J1,V);if(J1.avail_in!==0||L1.lookahead!==0||z1!==Y&&L1.status!==e){var b1=L1.strategy===R?z(L1,z1):L1.strategy===M?G(L1,z1):m[L1.level].func(L1,z1);if((b1===O1||b1===E1)&&(L1.status=e),b1===t||b1===O1)return J1.avail_out===0&&(L1.last_flush=-1),$;if(b1===U1&&(z1===Z?J._tr_align(L1):z1!==H&&(J._tr_stored_block(L1,0,0,!1),z1===X&&(o(L1.head),L1.lookahead===0&&(L1.strstart=0,L1.block_start=0,L1.insert=0))),C1(J1),J1.avail_out===0))return L1.last_flush=-1,$}return z1!==E?$:L1.wrap<=0?I:(L1.wrap===2?(Z1(L1,J1.adler&255),Z1(L1,J1.adler>>8&255),Z1(L1,J1.adler>>16&255),Z1(L1,J1.adler>>24&255),Z1(L1,J1.total_in&255),Z1(L1,J1.total_in>>8&255),Z1(L1,J1.total_in>>16&255),Z1(L1,J1.total_in>>24&255)):(j1(L1,J1.adler>>>16),j1(L1,J1.adler&65535)),C1(J1),L1.wrap>0&&(L1.wrap=-L1.wrap),L1.pending!==0?$:I)}function N1(J1){var z1;return!J1||!J1.state?N:(z1=J1.state.status,z1!==b&&z1!==p&&z1!==s&&z1!==r&&z1!==A1&&z1!==Q1&&z1!==e?i(J1,N):(J1.state=null,z1===Q1?i(J1,F):$))}function _1(J1,z1){var M1=z1.length,L1,V1,S1,O0,h1,b1,f0,e1;if(!J1||!J1.state||(L1=J1.state,O0=L1.wrap,O0===2||O0===1&&L1.status!==b||L1.lookahead))return N;for(O0===1&&(J1.adler=K(J1.adler,z1,M1,0)),L1.wrap=0,M1>=L1.w_size&&(O0===0&&(o(L1.head),L1.strstart=0,L1.block_start=0,L1.insert=0),e1=new Q.Buf8(L1.w_size),Q.arraySet(e1,z1,M1-L1.w_size,L1.w_size,0),z1=e1,M1=L1.w_size),h1=J1.avail_in,b1=J1.next_in,f0=J1.input,J1.avail_in=M1,J1.next_in=0,J1.input=z1,k1(L1);L1.lookahead>=S;){V1=L1.strstart,S1=L1.lookahead-(S-1);do L1.ins_h=(L1.ins_h<{var J=30,K=12;Q.exports=function(C,U){var Y,Z,X,E,H,$,I,N,F,V,D,L,R,M,T,h,y,g,f,u,d,n,B,q,P;Y=C.state,Z=C.next_in,q=C.input,X=Z+(C.avail_in-5),E=C.next_out,P=C.output,H=E-(U-C.avail_out),$=E+(C.avail_out-257),I=Y.dmax,N=Y.wsize,F=Y.whave,V=Y.wnext,D=Y.window,L=Y.hold,R=Y.bits,M=Y.lencode,T=Y.distcode,h=(1<>>24,L>>>=f,R-=f,f=g>>>16&255,f===0)P[E++]=g&65535;else if(f&16){u=g&65535,f&=15,f&&(R>>=f,R-=f),R<15&&(L+=q[Z++]<>>24,L>>>=f,R-=f,f=g>>>16&255,f&16){if(d=g&65535,f&=15,RI){C.msg="invalid distance too far back",Y.mode=J;break A}if(L>>>=f,R-=f,f=E-H,d>f){if(f=d-f,f>F&&Y.sane){C.msg="invalid distance too far back",Y.mode=J;break A}if(n=0,B=D,V===0){if(n+=N-f,f2;)P[E++]=B[n++],P[E++]=B[n++],P[E++]=B[n++],u-=3;u&&(P[E++]=B[n++],u>1&&(P[E++]=B[n++]))}else{n=E-d;do P[E++]=P[n++],P[E++]=P[n++],P[E++]=P[n++],u-=3;while(u>2);u&&(P[E++]=P[n++],u>1&&(P[E++]=P[n++]))}}else if((f&64)===0){g=T[(g&65535)+(L&(1<>3,Z-=u,R-=u<<3,L&=(1<{var J=iW(),K=15,C=852,U=592,Y=0,Z=1,X=2,E=[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=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],$=[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,0,0],I=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];Q.exports=function(N,F,V,D,L,R,M,T){var h=T.bits,y=0,g=0,f=0,u=0,d=0,n=0,B=0,q=0,P=0,O=0,w,k,S,_,W,j=null,b=0,p,s=new J.Buf16(K+1),r=new J.Buf16(K+1),A1=null,Q1=0,e,t,U1;for(y=0;y<=K;y++)s[y]=0;for(g=0;g=1&&s[u]===0;u--);if(d>u&&(d=u),u===0)return L[R++]=20971520,L[R++]=20971520,T.bits=1,0;for(f=1;f0&&(N===Y||u!==1))return-1;for(r[1]=0,y=1;yC||N===X&&P>U)return 1;for(;;){e=y-B,M[g]p?(t=A1[Q1+M[g]],U1=j[b+M[g]]):(t=96,U1=0),w=1<>B)+k]=e<<24|t<<16|U1|0;while(k!==0);for(w=1<>=1;if(w!==0?(O&=w-1,O+=w):O=0,g++,--s[y]===0){if(y===u)break;y=F[V+M[g]]}if(y>d&&(O&_)!==S){for(B===0&&(B=d),W+=f,n=y-B,q=1<C||N===X&&P>U)return 1;S=O&_,L[S]=d<<24|n<<16|W-R|0}}return O!==0&&(L[W+O]=y-B<<24|4194304|0),T.bits=d,0}}),HH1=k0((A)=>{var Q=iW(),J=dl(),K=ll(),C=EH1(),U=$H1(),Y=0,Z=1,X=2,E=4,H=5,$=6,I=0,N=1,F=2,V=-2,D=-3,L=-4,R=-5,M=8,T=1,h=2,y=3,g=4,f=5,u=6,d=7,n=8,B=9,q=10,P=11,O=12,w=13,k=14,S=15,_=16,W=17,j=18,b=19,p=20,s=21,r=22,A1=23,Q1=24,e=25,t=26,U1=27,O1=28,E1=29,Y1=30,i=31,c=32,o=852,C1=592,q1=15,Z1=q1;function j1(X1){return(X1>>>24&255)+(X1>>>8&65280)+((X1&65280)<<8)+((X1&255)<<24)}function H1(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Q.Buf16(320),this.work=new Q.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function B1(X1){var W1;return!X1||!X1.state?V:(W1=X1.state,X1.total_in=X1.total_out=W1.total=0,X1.msg="",W1.wrap&&(X1.adler=W1.wrap&1),W1.mode=T,W1.last=0,W1.havedict=0,W1.dmax=32768,W1.head=null,W1.hold=0,W1.bits=0,W1.lencode=W1.lendyn=new Q.Buf32(o),W1.distcode=W1.distdyn=new Q.Buf32(C1),W1.sane=1,W1.back=-1,I)}function k1(X1){var W1;return!X1||!X1.state?V:(W1=X1.state,W1.wsize=0,W1.whave=0,W1.wnext=0,B1(X1))}function D1(X1,W1){var $1,N1;return!X1||!X1.state||(N1=X1.state,W1<0?($1=0,W1=-W1):($1=(W1>>4)+1,W1<48&&(W1&=15)),W1&&(W1<8||W1>15))?V:(N1.window!==null&&N1.wbits!==W1&&(N1.window=null),N1.wrap=$1,N1.wbits=W1,k1(X1))}function G1(X1,W1){var $1,N1;return X1?(N1=new H1,X1.state=N1,N1.window=null,$1=D1(X1,W1),$1!==I&&(X1.state=null),$1):V}function w1(X1){return G1(X1,Z1)}var G=!0,z,x;function m(X1){if(G){var W1;for(z=new Q.Buf32(512),x=new Q.Buf32(32),W1=0;W1<144;)X1.lens[W1++]=8;for(;W1<256;)X1.lens[W1++]=9;for(;W1<280;)X1.lens[W1++]=7;for(;W1<288;)X1.lens[W1++]=8;for(U(Z,X1.lens,0,288,z,0,X1.work,{bits:9}),W1=0;W1<32;)X1.lens[W1++]=5;U(X,X1.lens,0,32,x,0,X1.work,{bits:5}),G=!1}X1.lencode=z,X1.lenbits=9,X1.distcode=x,X1.distbits=5}function l(X1,W1,$1,N1){var _1,J1=X1.state;return J1.window===null&&(J1.wsize=1<=J1.wsize?(Q.arraySet(J1.window,W1,$1-J1.wsize,J1.wsize,0),J1.wnext=0,J1.whave=J1.wsize):(_1=J1.wsize-J1.wnext,_1>N1&&(_1=N1),Q.arraySet(J1.window,W1,$1-N1,_1,J1.wnext),N1-=_1,N1?(Q.arraySet(J1.window,W1,$1-N1,N1,0),J1.wnext=N1,J1.whave=J1.wsize):(J1.wnext+=_1,J1.wnext===J1.wsize&&(J1.wnext=0),J1.whave>>8&255,$1.check=K($1.check,A0,2,0),V1=0,S1=0,$1.mode=h;break}if($1.flags=0,$1.head&&($1.head.done=!1),!($1.wrap&1)||(((V1&255)<<8)+(V1>>8))%31){X1.msg="incorrect header check",$1.mode=Y1;break}if((V1&15)!==M){X1.msg="unknown compression method",$1.mode=Y1;break}if(V1>>>=4,S1-=4,qA=(V1&15)+8,$1.wbits===0)$1.wbits=qA;else if(qA>$1.wbits){X1.msg="invalid window size",$1.mode=Y1;break}$1.dmax=1<>8&1),$1.flags&512&&(A0[0]=V1&255,A0[1]=V1>>>8&255,$1.check=K($1.check,A0,2,0)),V1=0,S1=0,$1.mode=y;case y:for(;S1<32;){if(M1===0)break A;M1--,V1+=N1[J1++]<>>8&255,A0[2]=V1>>>16&255,A0[3]=V1>>>24&255,$1.check=K($1.check,A0,4,0)),V1=0,S1=0,$1.mode=g;case g:for(;S1<16;){if(M1===0)break A;M1--,V1+=N1[J1++]<>8),$1.flags&512&&(A0[0]=V1&255,A0[1]=V1>>>8&255,$1.check=K($1.check,A0,2,0)),V1=0,S1=0,$1.mode=f;case f:if($1.flags&1024){for(;S1<16;){if(M1===0)break A;M1--,V1+=N1[J1++]<>>8&255,$1.check=K($1.check,A0,2,0)),V1=0,S1=0}else $1.head&&($1.head.extra=null);$1.mode=u;case u:if($1.flags&1024&&(b1=$1.length,b1>M1&&(b1=M1),b1&&($1.head&&(qA=$1.head.extra_len-$1.length,$1.head.extra||($1.head.extra=new Array($1.head.extra_len)),Q.arraySet($1.head.extra,N1,J1,b1,qA)),$1.flags&512&&($1.check=K($1.check,N1,b1,J1)),M1-=b1,J1+=b1,$1.length-=b1),$1.length))break A;$1.length=0,$1.mode=d;case d:if($1.flags&2048){if(M1===0)break A;b1=0;do qA=N1[J1+b1++],$1.head&&qA&&$1.length<65536&&($1.head.name+=String.fromCharCode(qA));while(qA&&b1>9&1,$1.head.done=!0),X1.adler=$1.check=0,$1.mode=O;break;case q:for(;S1<32;){if(M1===0)break A;M1--,V1+=N1[J1++]<>>=S1&7,S1-=S1&7,$1.mode=U1;break}for(;S1<3;){if(M1===0)break A;M1--,V1+=N1[J1++]<>>=1,S1-=1,V1&3){case 0:$1.mode=k;break;case 1:if(m($1),$1.mode=p,W1===$){V1>>>=2,S1-=2;break A}break;case 2:$1.mode=W;break;case 3:X1.msg="invalid block type",$1.mode=Y1}V1>>>=2,S1-=2;break;case k:for(V1>>>=S1&7,S1-=S1&7;S1<32;){if(M1===0)break A;M1--,V1+=N1[J1++]<>>16^65535)){X1.msg="invalid stored block lengths",$1.mode=Y1;break}if($1.length=V1&65535,V1=0,S1=0,$1.mode=S,W1===$)break A;case S:$1.mode=_;case _:if(b1=$1.length,b1){if(b1>M1&&(b1=M1),b1>L1&&(b1=L1),b1===0)break A;Q.arraySet(_1,N1,J1,b1,z1),M1-=b1,J1+=b1,L1-=b1,z1+=b1,$1.length-=b1;break}$1.mode=O;break;case W:for(;S1<14;){if(M1===0)break A;M1--,V1+=N1[J1++]<>>=5,S1-=5,$1.ndist=(V1&31)+1,V1>>>=5,S1-=5,$1.ncode=(V1&15)+4,V1>>>=4,S1-=4,$1.nlen>286||$1.ndist>30){X1.msg="too many length or distance symbols",$1.mode=Y1;break}$1.have=0,$1.mode=j;case j:for(;$1.have<$1.ncode;){for(;S1<3;){if(M1===0)break A;M1--,V1+=N1[J1++]<>>=3,S1-=3}for(;$1.have<19;)$1.lens[EA[$1.have++]]=0;if($1.lencode=$1.lendyn,$1.lenbits=7,hA={bits:$1.lenbits},Q0=U(Y,$1.lens,0,19,$1.lencode,0,$1.work,hA),$1.lenbits=hA.bits,Q0){X1.msg="invalid code lengths set",$1.mode=Y1;break}$1.have=0,$1.mode=b;case b:for(;$1.have<$1.nlen+$1.ndist;){for(;s1=$1.lencode[V1&(1<<$1.lenbits)-1],o0=s1>>>24,a1=s1>>>16&255,r1=s1&65535,!(o0<=S1);){if(M1===0)break A;M1--,V1+=N1[J1++]<>>=o0,S1-=o0,$1.lens[$1.have++]=r1;else{if(r1===16){for(r0=o0+2;S1>>=o0,S1-=o0,$1.have===0){X1.msg="invalid bit length repeat",$1.mode=Y1;break}qA=$1.lens[$1.have-1],b1=3+(V1&3),V1>>>=2,S1-=2}else if(r1===17){for(r0=o0+3;S1>>=o0,S1-=o0,qA=0,b1=3+(V1&7),V1>>>=3,S1-=3}else{for(r0=o0+7;S1>>=o0,S1-=o0,qA=0,b1=11+(V1&127),V1>>>=7,S1-=7}if($1.have+b1>$1.nlen+$1.ndist){X1.msg="invalid bit length repeat",$1.mode=Y1;break}for(;b1--;)$1.lens[$1.have++]=qA}}if($1.mode===Y1)break;if($1.lens[256]===0){X1.msg="invalid code -- missing end-of-block",$1.mode=Y1;break}if($1.lenbits=9,hA={bits:$1.lenbits},Q0=U(Z,$1.lens,0,$1.nlen,$1.lencode,0,$1.work,hA),$1.lenbits=hA.bits,Q0){X1.msg="invalid literal/lengths set",$1.mode=Y1;break}if($1.distbits=6,$1.distcode=$1.distdyn,hA={bits:$1.distbits},Q0=U(X,$1.lens,$1.nlen,$1.ndist,$1.distcode,0,$1.work,hA),$1.distbits=hA.bits,Q0){X1.msg="invalid distances set",$1.mode=Y1;break}if($1.mode=p,W1===$)break A;case p:$1.mode=s;case s:if(M1>=6&&L1>=258){X1.next_out=z1,X1.avail_out=L1,X1.next_in=J1,X1.avail_in=M1,$1.hold=V1,$1.bits=S1,C(X1,h1),z1=X1.next_out,_1=X1.output,L1=X1.avail_out,J1=X1.next_in,N1=X1.input,M1=X1.avail_in,V1=$1.hold,S1=$1.bits,$1.mode===O&&($1.back=-1);break}for($1.back=0;s1=$1.lencode[V1&(1<<$1.lenbits)-1],o0=s1>>>24,a1=s1>>>16&255,r1=s1&65535,!(o0<=S1);){if(M1===0)break A;M1--,V1+=N1[J1++]<>FA)],o0=s1>>>24,a1=s1>>>16&255,r1=s1&65535,!(FA+o0<=S1);){if(M1===0)break A;M1--,V1+=N1[J1++]<>>=FA,S1-=FA,$1.back+=FA}if(V1>>>=o0,S1-=o0,$1.back+=o0,$1.length=r1,a1===0){$1.mode=t;break}if(a1&32){$1.back=-1,$1.mode=O;break}if(a1&64){X1.msg="invalid literal/length code",$1.mode=Y1;break}$1.extra=a1&15,$1.mode=r;case r:if($1.extra){for(r0=$1.extra;S1>>=$1.extra,S1-=$1.extra,$1.back+=$1.extra}$1.was=$1.length,$1.mode=A1;case A1:for(;s1=$1.distcode[V1&(1<<$1.distbits)-1],o0=s1>>>24,a1=s1>>>16&255,r1=s1&65535,!(o0<=S1);){if(M1===0)break A;M1--,V1+=N1[J1++]<>FA)],o0=s1>>>24,a1=s1>>>16&255,r1=s1&65535,!(FA+o0<=S1);){if(M1===0)break A;M1--,V1+=N1[J1++]<>>=FA,S1-=FA,$1.back+=FA}if(V1>>>=o0,S1-=o0,$1.back+=o0,a1&64){X1.msg="invalid distance code",$1.mode=Y1;break}$1.offset=r1,$1.extra=a1&15,$1.mode=Q1;case Q1:if($1.extra){for(r0=$1.extra;S1>>=$1.extra,S1-=$1.extra,$1.back+=$1.extra}if($1.offset>$1.dmax){X1.msg="invalid distance too far back",$1.mode=Y1;break}$1.mode=e;case e:if(L1===0)break A;if(b1=h1-L1,$1.offset>b1){if(b1=$1.offset-b1,b1>$1.whave&&$1.sane){X1.msg="invalid distance too far back",$1.mode=Y1;break}b1>$1.wnext?(b1-=$1.wnext,f0=$1.wsize-b1):f0=$1.wnext-b1,b1>$1.length&&(b1=$1.length),e1=$1.window}else e1=_1,f0=z1-$1.offset,b1=$1.length;b1>L1&&(b1=L1),L1-=b1,$1.length-=b1;do _1[z1++]=e1[f0++];while(--b1);$1.length===0&&($1.mode=s);break;case t:if(L1===0)break A;_1[z1++]=$1.length,L1--,$1.mode=s;break;case U1:if($1.wrap){for(;S1<32;){if(M1===0)break A;M1--,V1|=N1[J1++]<{Q.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}}),WH1=k0((A)=>{var Q=pW(),J=UH1(),K=XH1(),C=HH1(),U=GH1();for(Y in U)A[Y]=U[Y];var Y;A.NONE=0,A.DEFLATE=1,A.INFLATE=2,A.GZIP=3,A.GUNZIP=4,A.DEFLATERAW=5,A.INFLATERAW=6,A.UNZIP=7;var Z=31,X=139;function E(H){if(typeof H!="number"||HA.UNZIP)throw new TypeError("Bad argument");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=H,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}E.prototype.close=function(){if(this.write_in_progress){this.pending_close=!0;return}this.pending_close=!1,Q(this.init_done,"close before init"),Q(this.mode<=A.UNZIP),this.mode===A.DEFLATE||this.mode===A.GZIP||this.mode===A.DEFLATERAW?K.deflateEnd(this.strm):(this.mode===A.INFLATE||this.mode===A.GUNZIP||this.mode===A.INFLATERAW||this.mode===A.UNZIP)&&C.inflateEnd(this.strm),this.mode=A.NONE,this.dictionary=null},E.prototype.write=function(H,$,I,N,F,V,D){return this._write(!0,H,$,I,N,F,V,D)},E.prototype.writeSync=function(H,$,I,N,F,V,D){return this._write(!1,H,$,I,N,F,V,D)},E.prototype._write=function(H,$,I,N,F,V,D,L){if(Q.equal(arguments.length,8),Q(this.init_done,"write before init"),Q(this.mode!==A.NONE,"already finalized"),Q.equal(!1,this.write_in_progress,"write already in progress"),Q.equal(!1,this.pending_close,"close is pending"),this.write_in_progress=!0,Q.equal(!1,$===void 0,"must provide flush value"),this.write_in_progress=!0,$!==A.Z_NO_FLUSH&&$!==A.Z_PARTIAL_FLUSH&&$!==A.Z_SYNC_FLUSH&&$!==A.Z_FULL_FLUSH&&$!==A.Z_FINISH&&$!==A.Z_BLOCK)throw new Error("Invalid flush value");if(I==null&&(I=Buffer.alloc(0),F=0,N=0),this.strm.avail_in=F,this.strm.input=I,this.strm.next_in=N,this.strm.avail_out=L,this.strm.output=V,this.strm.next_out=D,this.flush=$,!H)return this._process(),this._checkError()?this._afterSync():void 0;var R=this;return process.nextTick(function(){R._process(),R._after()}),this},E.prototype._afterSync=function(){var H=this.strm.avail_out,$=this.strm.avail_in;return this.write_in_progress=!1,[$,H]},E.prototype._process=function(){var H=null;switch(this.mode){case A.DEFLATE:case A.GZIP:case A.DEFLATERAW:this.err=K.deflate(this.strm,this.flush);break;case A.UNZIP:switch(this.strm.avail_in>0&&(H=this.strm.next_in),this.gzip_id_bytes_read){case 0:if(H===null)break;if(this.strm.input[H]===Z){if(this.gzip_id_bytes_read=1,H++,this.strm.avail_in===1)break}else{this.mode=A.INFLATE;break}case 1:if(H===null)break;this.strm.input[H]===X?(this.gzip_id_bytes_read=2,this.mode=A.GUNZIP):this.mode=A.INFLATE;break;default:throw new Error("invalid number of gzip magic number bytes read")}case A.INFLATE:case A.GUNZIP:case A.INFLATERAW:for(this.err=C.inflate(this.strm,this.flush),this.err===A.Z_NEED_DICT&&this.dictionary&&(this.err=C.inflateSetDictionary(this.strm,this.dictionary),this.err===A.Z_OK?this.err=C.inflate(this.strm,this.flush):this.err===A.Z_DATA_ERROR&&(this.err=A.Z_NEED_DICT));this.strm.avail_in>0&&this.mode===A.GUNZIP&&this.err===A.Z_STREAM_END&&this.strm.next_in[0]!==0;)this.reset(),this.err=C.inflate(this.strm,this.flush);break;default:throw new Error("Unknown mode "+this.mode)}},E.prototype._checkError=function(){switch(this.err){case A.Z_OK:case A.Z_BUF_ERROR:if(this.strm.avail_out!==0&&this.flush===A.Z_FINISH)return this._error("unexpected end of file"),!1;break;case A.Z_STREAM_END:break;case A.Z_NEED_DICT:return this.dictionary==null?this._error("Missing dictionary"):this._error("Bad dictionary"),!1;default:return this._error("Zlib error"),!1}return!0},E.prototype._after=function(){if(this._checkError()){var H=this.strm.avail_out,$=this.strm.avail_in;this.write_in_progress=!1,this.callback($,H),this.pending_close&&this.close()}},E.prototype._error=function(H){this.strm.msg&&(H=this.strm.msg),this.onerror(H,this.err),this.write_in_progress=!1,this.pending_close&&this.close()},E.prototype.init=function(H,$,I,N,F){Q(arguments.length===4||arguments.length===5,"init(windowBits, level, memLevel, strategy, [dictionary])"),Q(H>=8&&H<=15,"invalid windowBits"),Q($>=-1&&$<=9,"invalid compression level"),Q(I>=1&&I<=9,"invalid memlevel"),Q(N===A.Z_FILTERED||N===A.Z_HUFFMAN_ONLY||N===A.Z_RLE||N===A.Z_FIXED||N===A.Z_DEFAULT_STRATEGY,"invalid strategy"),this._init($,H,I,N,F),this._setDictionary()},E.prototype.params=function(){throw new Error("deflateParams Not supported")},E.prototype.reset=function(){this._reset(),this._setDictionary()},E.prototype._init=function(H,$,I,N,F){switch(this.level=H,this.windowBits=$,this.memLevel=I,this.strategy=N,this.flush=A.Z_NO_FLUSH,this.err=A.Z_OK,(this.mode===A.GZIP||this.mode===A.GUNZIP)&&(this.windowBits+=16),this.mode===A.UNZIP&&(this.windowBits+=32),(this.mode===A.DEFLATERAW||this.mode===A.INFLATERAW)&&(this.windowBits=-1*this.windowBits),this.strm=new J,this.mode){case A.DEFLATE:case A.GZIP:case A.DEFLATERAW:this.err=K.deflateInit2(this.strm,this.level,A.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case A.INFLATE:case A.GUNZIP:case A.INFLATERAW:case A.UNZIP:this.err=C.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}this.err!==A.Z_OK&&this._error("Init error"),this.dictionary=F,this.write_in_progress=!1,this.init_done=!0},E.prototype._setDictionary=function(){if(this.dictionary!=null){switch(this.err=A.Z_OK,this.mode){case A.DEFLATE:case A.DEFLATERAW:this.err=K.deflateSetDictionary(this.strm,this.dictionary);break;default:break}this.err!==A.Z_OK&&this._error("Failed to set dictionary")}},E.prototype._reset=function(){switch(this.err=A.Z_OK,this.mode){case A.DEFLATE:case A.DEFLATERAW:case A.GZIP:this.err=K.deflateReset(this.strm);break;case A.INFLATE:case A.INFLATERAW:case A.GUNZIP:this.err=C.inflateReset(this.strm);break;default:break}this.err!==A.Z_OK&&this._error("Failed to reset stream")},A.Zlib=E}),nl=k0((A)=>{var Q=W3().Buffer,J=(p$1(),N9(_V)).Transform,K=WH1(),C=yl(),U=pW().ok,Y=W3().kMaxLength,Z="Cannot create final Buffer. It would be larger than 0x"+Y.toString(16)+" bytes";K.Z_MIN_WINDOWBITS=8,K.Z_MAX_WINDOWBITS=15,K.Z_DEFAULT_WINDOWBITS=15,K.Z_MIN_CHUNK=64,K.Z_MAX_CHUNK=1/0,K.Z_DEFAULT_CHUNK=16384,K.Z_MIN_MEMLEVEL=1,K.Z_MAX_MEMLEVEL=9,K.Z_DEFAULT_MEMLEVEL=8,K.Z_MIN_LEVEL=-1,K.Z_MAX_LEVEL=9,K.Z_DEFAULT_LEVEL=K.Z_DEFAULT_COMPRESSION;var X=Object.keys(K);for(H=0;H=Y?j=new RangeError(Z):W=Q.concat(O,w),O=[],B.close(),P(j,W)}}function D(B,q){if(typeof q=="string"&&(q=Q.from(q)),!Q.isBuffer(q))throw new TypeError("Not a string or buffer");var P=B._finishFlushFlag;return B._processChunk(q,P)}function L(B){if(!(this instanceof L))return new L(B);u.call(this,B,K.DEFLATE)}function R(B){if(!(this instanceof R))return new R(B);u.call(this,B,K.INFLATE)}function M(B){if(!(this instanceof M))return new M(B);u.call(this,B,K.GZIP)}function T(B){if(!(this instanceof T))return new T(B);u.call(this,B,K.GUNZIP)}function h(B){if(!(this instanceof h))return new h(B);u.call(this,B,K.DEFLATERAW)}function y(B){if(!(this instanceof y))return new y(B);u.call(this,B,K.INFLATERAW)}function g(B){if(!(this instanceof g))return new g(B);u.call(this,B,K.UNZIP)}function f(B){return B===K.Z_NO_FLUSH||B===K.Z_PARTIAL_FLUSH||B===K.Z_SYNC_FLUSH||B===K.Z_FULL_FLUSH||B===K.Z_FINISH||B===K.Z_BLOCK}function u(B,q){var P=this;if(this._opts=B=B||{},this._chunkSize=B.chunkSize||A.Z_DEFAULT_CHUNK,J.call(this,B),B.flush&&!f(B.flush))throw new Error("Invalid flush flag: "+B.flush);if(B.finishFlush&&!f(B.finishFlush))throw new Error("Invalid flush flag: "+B.finishFlush);if(this._flushFlag=B.flush||K.Z_NO_FLUSH,this._finishFlushFlag=typeof B.finishFlush<"u"?B.finishFlush:K.Z_FINISH,B.chunkSize&&(B.chunkSizeA.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+B.chunkSize);if(B.windowBits&&(B.windowBitsA.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+B.windowBits);if(B.level&&(B.levelA.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+B.level);if(B.memLevel&&(B.memLevelA.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+B.memLevel);if(B.strategy&&B.strategy!=A.Z_FILTERED&&B.strategy!=A.Z_HUFFMAN_ONLY&&B.strategy!=A.Z_RLE&&B.strategy!=A.Z_FIXED&&B.strategy!=A.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+B.strategy);if(B.dictionary&&!Q.isBuffer(B.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._handle=new K.Zlib(q);var O=this;this._hadError=!1,this._handle.onerror=function(S,_){d(O),O._hadError=!0;var W=new Error(S);W.errno=_,W.code=A.codes[_],O.emit("error",W)};var w=A.Z_DEFAULT_COMPRESSION;typeof B.level=="number"&&(w=B.level);var k=A.Z_DEFAULT_STRATEGY;typeof B.strategy=="number"&&(k=B.strategy),this._handle.init(B.windowBits||A.Z_DEFAULT_WINDOWBITS,w,B.memLevel||A.Z_DEFAULT_MEMLEVEL,k,B.dictionary),this._buffer=Q.allocUnsafe(this._chunkSize),this._offset=0,this._level=w,this._strategy=k,this.once("end",this.close),Object.defineProperty(this,"_closed",{get:function(){return!P._handle},configurable:!0,enumerable:!0})}C.inherits(u,J),u.prototype.params=function(B,q,P){if(BA.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+B);if(q!=A.Z_FILTERED&&q!=A.Z_HUFFMAN_ONLY&&q!=A.Z_RLE&&q!=A.Z_FIXED&&q!=A.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+q);if(this._level!==B||this._strategy!==q){var O=this;this.flush(K.Z_SYNC_FLUSH,function(){U(O._handle,"zlib binding closed"),O._handle.params(B,q),O._hadError||(O._level=B,O._strategy=q,P&&P())})}else process.nextTick(P)},u.prototype.reset=function(){return U(this._handle,"zlib binding closed"),this._handle.reset()},u.prototype._flush=function(B){this._transform(Q.alloc(0),"",B)},u.prototype.flush=function(B,q){var P=this,O=this._writableState;(typeof B=="function"||B===void 0&&!q)&&(q=B,B=K.Z_FULL_FLUSH),O.ended?q&&process.nextTick(q):O.ending?q&&this.once("end",q):O.needDrain?q&&this.once("drain",function(){return P.flush(B,q)}):(this._flushFlag=B,this.write(Q.alloc(0),"",q))},u.prototype.close=function(B){d(this,B),process.nextTick(n,this)};function d(B,q){q&&process.nextTick(q),B._handle&&(B._handle.close(),B._handle=null)}function n(B){B.emit("close")}u.prototype._transform=function(B,q,P){var O,w=this._writableState,k=w.ending||w.ended,S=k&&(!B||w.length===B.length);if(B!==null&&!Q.isBuffer(B))return P(new Error("invalid input"));if(!this._handle)return P(new Error("zlib binding closed"));S?O=this._finishFlushFlag:(O=this._flushFlag,B.length>=w.length&&(this._flushFlag=this._opts.flush||K.Z_NO_FLUSH)),this._processChunk(B,O,P)},u.prototype._processChunk=function(B,q,P){var O=B&&B.length,w=this._chunkSize-this._offset,k=0,S=this,_=typeof P=="function";if(!_){var W=[],j=0,b;this.on("error",function(Q1){b=Q1}),U(this._handle,"zlib binding closed");do var p=this._handle.writeSync(q,B,k,O,this._buffer,this._offset,w);while(!this._hadError&&A1(p[0],p[1]));if(this._hadError)throw b;if(j>=Y)throw d(this),new RangeError(Z);var s=Q.concat(W,j);return d(this),s}U(this._handle,"zlib binding closed");var r=this._handle.write(q,B,k,O,this._buffer,this._offset,w);r.buffer=B,r.callback=A1;function A1(Q1,e){if(this&&(this.buffer=null,this.callback=null),!S._hadError){var t=w-e;if(U(t>=0,"have should not go down"),t>0){var U1=S._buffer.slice(S._offset,S._offset+t);S._offset+=t,_?S.push(U1):(W.push(U1),j+=U1.length)}if((e===0||S._offset>=S._chunkSize)&&(w=S._chunkSize,S._offset=0,S._buffer=Q.allocUnsafe(S._chunkSize)),e===0){if(k+=O-Q1,O=Q1,!_)return!0;var O1=S._handle.write(q,B,k,O,S._buffer,S._offset,S._chunkSize);O1.callback=A1,O1.buffer=B;return}if(!_)return!1;P()}}},C.inherits(L,u),C.inherits(R,u),C.inherits(M,u),C.inherits(T,u),C.inherits(h,u),C.inherits(y,u),C.inherits(g,u)}),sl={};mW(sl,{default:()=>ol});cW(sl,zJ(nl()));ol=zJ(nl());/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *//*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - *//*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *//*! safe-buffer. MIT License. Feross Aboukhadijeh */});var tl=B0((rl,aW)=>{(function(A,Q){typeof define=="function"&&define.amd?define([],Q):typeof aW=="object"&&aW.exports?aW.exports=Q():A.KaitaiStream=Q()})(typeof self!="undefined"?self:rl,function(){var A=function(E,H){this._byteOffset=H||0,E instanceof ArrayBuffer?this.buffer=E:typeof E=="object"?(this.dataView=E,H&&(this._byteOffset+=H)):this.buffer=new ArrayBuffer(E||1),this.pos=0,this.alignToByte()};A.prototype={},A.depUrls={zlib:void 0},A.prototype._byteLength=0,Object.defineProperty(A.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(E){this._buffer=E,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(A.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(E){this._byteOffset=E,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(A.prototype,"dataView",{get:function(){return this._dataView},set:function(E){this._byteOffset=E.byteOffset,this._buffer=E.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+E.byteLength}}),A.prototype._trimAlloc=function(){if(this._byteLength!==this._buffer.byteLength){var E=new ArrayBuffer(this._byteLength),H=new Uint8Array(E),$=new Uint8Array(this._buffer,0,H.length);H.set($),this.buffer=E}},A.prototype.isEof=function(){return this.pos>=this.size&&this.bitsLeft===0},A.prototype.seek=function(E){var H=Math.max(0,Math.min(this.size,E));this.pos=isNaN(H)||!isFinite(H)?0:H},Object.defineProperty(A.prototype,"size",{get:function(){return this._byteLength-this._byteOffset}}),A.prototype.readS1=function(){this.ensureBytesLeft(1);var E=this._dataView.getInt8(this.pos);return this.pos+=1,E},A.prototype.readS2be=function(){this.ensureBytesLeft(2);var E=this._dataView.getInt16(this.pos);return this.pos+=2,E},A.prototype.readS4be=function(){this.ensureBytesLeft(4);var E=this._dataView.getInt32(this.pos);return this.pos+=4,E},A.prototype.readS8be=function(){this.ensureBytesLeft(8);var E=this.readU4be(),H=this.readU4be();return(2147483648&E)!=0?-(4294967296*(4294967295^E)+(4294967295^H))-1:4294967296*E+H},A.prototype.readS2le=function(){this.ensureBytesLeft(2);var E=this._dataView.getInt16(this.pos,!0);return this.pos+=2,E},A.prototype.readS4le=function(){this.ensureBytesLeft(4);var E=this._dataView.getInt32(this.pos,!0);return this.pos+=4,E},A.prototype.readS8le=function(){this.ensureBytesLeft(8);var E=this.readU4le(),H=this.readU4le();return(2147483648&H)!=0?-(4294967296*(4294967295^H)+(4294967295^E))-1:4294967296*H+E},A.prototype.readU1=function(){this.ensureBytesLeft(1);var E=this._dataView.getUint8(this.pos);return this.pos+=1,E},A.prototype.readU2be=function(){this.ensureBytesLeft(2);var E=this._dataView.getUint16(this.pos);return this.pos+=2,E},A.prototype.readU4be=function(){this.ensureBytesLeft(4);var E=this._dataView.getUint32(this.pos);return this.pos+=4,E},A.prototype.readU8be=function(){return this.ensureBytesLeft(8),4294967296*this.readU4be()+this.readU4be()},A.prototype.readU2le=function(){this.ensureBytesLeft(2);var E=this._dataView.getUint16(this.pos,!0);return this.pos+=2,E},A.prototype.readU4le=function(){this.ensureBytesLeft(4);var E=this._dataView.getUint32(this.pos,!0);return this.pos+=4,E},A.prototype.readU8le=function(){this.ensureBytesLeft(8);var E=this.readU4le();return 4294967296*this.readU4le()+E},A.prototype.readF4be=function(){this.ensureBytesLeft(4);var E=this._dataView.getFloat32(this.pos);return this.pos+=4,E},A.prototype.readF8be=function(){this.ensureBytesLeft(8);var E=this._dataView.getFloat64(this.pos);return this.pos+=8,E},A.prototype.readF4le=function(){this.ensureBytesLeft(4);var E=this._dataView.getFloat32(this.pos,!0);return this.pos+=4,E},A.prototype.readF8le=function(){this.ensureBytesLeft(8);var E=this._dataView.getFloat64(this.pos,!0);return this.pos+=8,E},A.prototype.alignToByte=function(){this.bitsLeft=0,this.bits=0},A.prototype.readBitsIntBe=function(E){if(E>32)throw new RangeError("readBitsIntBe: the maximum supported bit length is 32 (tried to read "+E+" bits)");var H=0,$=E-this.bitsLeft;if(this.bitsLeft=7&-$,$>0){for(var I=1+($-1>>3),N=this.readBytes(I),F=0;F>>this.bitsLeft|this.bits<<$,this.bits=V}else H=this.bits>>>-$;var D=(1<>>0},A.prototype.readBitsInt=A.prototype.readBitsIntBe,A.prototype.readBitsIntLe=function(E){if(E>32)throw new RangeError("readBitsIntLe: the maximum supported bit length is 32 (tried to read "+E+" bits)");var H=0,$=E-this.bitsLeft;if($>0){for(var I=1+($-1>>3),N=this.readBytes(I),F=0;F>>$:0;H=H<>>=E;return(this.bitsLeft=7&-$,E<32)?H&=(1<>>=0,H},A.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,A.prototype.readBytes=function(E){return this.mapUint8Array(E)},A.prototype.readBytesFull=function(){return this.mapUint8Array(this.size-this.pos)},A.prototype.readBytesTerm=function(E,H,$,I){for(var N,F=this.size-this.pos,V=new Uint8Array(this._buffer,this._byteOffset+this.pos),D=0;D=N&&(F=0);return I},A.processRotateLeft=function(E,H,$){if($!==1)throw"unable to rotate group of "+$+" bytes yet";for(var I=-H&8*$-1,N=new Uint8Array(E.length),F=0;F>I;return N},A.processZlib=function(E){A.zlib===void 0&&(A.zlib=(al(),y4(il)));var H=A.zlib.inflateSync(Buffer.from(E.buffer.slice(E.byteOffset,E.byteOffset+E.byteLength)));return H},A.mod=function(E,H){if(H<=0)throw"mod divisor <= 0";var $=E%H;return $<0&&($+=H),$},A.arrayMin=function(E){for(var H,$=E[0],I=1,N=E.length;I$&&($=H);return $},A.byteArrayCompare=function(E,H){if(E===H)return 0;for(var $=E.length,I=H.length,N=$this.size)throw new Q(E,this.size-this.pos)},A.prototype.mapUint8Array=function(E){E|=0,this.ensureBytesLeft(E);var H=new Uint8Array(this._buffer,this.byteOffset+this.pos,E);return this.pos+=E,H},A.createStringFromArray=function(E){for(var H=32768,$=[],I=typeof E.subarray=="function",N=0;N{(function(A,Q){typeof jV=="object"&&typeof vV!="undefined"?vV.exports=Q():typeof define=="function"&&define.amd?define(Q):(A=typeof globalThis!="undefined"?globalThis:A||self).LazyLoad=Q()})(jV,function(){let A=typeof window!="undefined",Q=A&&!("onscroll"in window)||typeof navigator!="undefined"&&/(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent),J=A&&window.devicePixelRatio>1,K={elements_selector:".lazy",container:Q||A?document:null,threshold:300,thresholds:null,data_src:"src",data_srcset:"srcset",data_sizes:"sizes",data_bg:"bg",data_bg_hidpi:"bg-hidpi",data_bg_multi:"bg-multi",data_bg_multi_hidpi:"bg-multi-hidpi",data_bg_set:"bg-set",data_poster:"poster",class_applied:"applied",class_loading:"loading",class_loaded:"loaded",class_error:"error",class_entered:"entered",class_exited:"exited",unobserve_completed:!0,unobserve_entered:!1,cancel_on_exit:!0,callback_enter:null,callback_exit:null,callback_applied:null,callback_loading:null,callback_loaded:null,callback_error:null,callback_finish:null,callback_cancel:null,use_native:!1,restore_on_error:!1},C=(R1)=>Object.assign({},K,R1),U=function(R1,X1){let W1,$1="LazyLoad::Initialized",N1=new R1(X1);try{W1=new CustomEvent("LazyLoad::Initialized",{detail:{instance:N1}})}catch(_1){W1=document.createEvent("CustomEvent"),W1.initCustomEvent("LazyLoad::Initialized",!1,!1,{instance:N1})}window.dispatchEvent(W1)},M=(R1,X1)=>R1.getAttribute("data-"+X1),T=(R1)=>M(R1,"ll-status"),h=(R1,X1)=>((W1,$1,N1)=>{let _1="data-"+$1;N1!==null?W1.setAttribute(_1,N1):W1.removeAttribute(_1)})(R1,"ll-status",X1),y=(R1)=>h(R1,null),g=(R1)=>T(R1)===null,f=(R1)=>T(R1)==="native",u=["loading","loaded","applied","error"],d=(R1,X1,W1,$1)=>{R1&&typeof R1=="function"&&($1===void 0?W1===void 0?R1(X1):R1(X1,W1):R1(X1,W1,$1))},n=(R1,X1)=>{A&&X1!==""&&R1.classList.add(X1)},B=(R1,X1)=>{A&&X1!==""&&R1.classList.remove(X1)},q=(R1)=>R1.llTempImage,P=(R1,X1)=>{if(!X1)return;let W1=X1._observer;W1&&W1.unobserve(R1)},O=(R1,X1)=>{R1&&(R1.loadingCount+=X1)},w=(R1,X1)=>{R1&&(R1.toLoadCount=X1)},k=(R1)=>{let X1=[];for(let W1,$1=0;W1=R1.children[$1];$1+=1)W1.tagName==="SOURCE"&&X1.push(W1);return X1},S=(R1,X1)=>{let W1=R1.parentNode;W1&&W1.tagName==="PICTURE"&&k(W1).forEach(X1)},_=(R1,X1)=>{k(R1).forEach(X1)},W=["src"],j=["src","poster"],b=["src","srcset","sizes"],p=["data"],s=(R1)=>!!R1.llOriginalAttrs,r=(R1)=>R1.llOriginalAttrs,A1=(R1)=>delete R1.llOriginalAttrs,Q1=(R1,X1)=>{if(s(R1))return;let W1={};X1.forEach(($1)=>{W1[$1]=R1.getAttribute($1)}),R1.llOriginalAttrs=W1},e=(R1,X1)=>{if(!s(R1))return;let W1=r(R1);X1.forEach(($1)=>{((N1,_1,J1)=>{J1?N1.setAttribute(_1,J1):N1.removeAttribute(_1)})(R1,$1,W1[$1])})},t=(R1,X1,W1)=>{n(R1,X1.class_applied),h(R1,"applied"),W1&&(X1.unobserve_completed&&P(R1,X1),d(X1.callback_applied,R1,W1))},U1=(R1,X1,W1)=>{n(R1,X1.class_loading),h(R1,"loading"),W1&&(O(W1,1),d(X1.callback_loading,R1,W1))},O1=(R1,X1,W1)=>{W1&&R1.setAttribute(X1,W1)},E1=(R1,X1)=>{O1(R1,"sizes",M(R1,X1.data_sizes)),O1(R1,"srcset",M(R1,X1.data_srcset)),O1(R1,"src",M(R1,X1.data_src))},Y1={IMG:(R1,X1)=>{S(R1,(W1)=>{Q1(W1,b),E1(W1,X1)}),Q1(R1,b),E1(R1,X1)},IFRAME:(R1,X1)=>{Q1(R1,W),O1(R1,"src",M(R1,X1.data_src))},VIDEO:(R1,X1)=>{_(R1,(W1)=>{Q1(W1,W),O1(W1,"src",M(W1,X1.data_src))}),Q1(R1,j),O1(R1,"poster",M(R1,X1.data_poster)),O1(R1,"src",M(R1,X1.data_src)),R1.load()},OBJECT:(R1,X1)=>{Q1(R1,p),O1(R1,"data",M(R1,X1.data_src))}},i=["IMG","IFRAME","VIDEO","OBJECT"],c=(R1,X1)=>{!X1||((W1)=>W1.loadingCount>0)(X1)||((W1)=>W1.toLoadCount>0)(X1)||d(R1.callback_finish,X1)},o=(R1,X1,W1)=>{R1.addEventListener(X1,W1),R1.llEvLisnrs[X1]=W1},C1=(R1,X1,W1)=>{R1.removeEventListener(X1,W1)},q1=(R1)=>!!R1.llEvLisnrs,Z1=(R1)=>{if(!q1(R1))return;let X1=R1.llEvLisnrs;for(let W1 in X1){let $1=X1[W1];C1(R1,W1,$1)}delete R1.llEvLisnrs},j1=(R1,X1,W1)=>{(($1)=>{delete $1.llTempImage})(R1),O(W1,-1),(($1)=>{$1&&($1.toLoadCount-=1)})(W1),B(R1,X1.class_loading),X1.unobserve_completed&&P(R1,W1)},H1=(R1,X1,W1)=>{let $1=q(R1)||R1;q1($1)||((N1,_1,J1)=>{q1(N1)||(N1.llEvLisnrs={});let z1=N1.tagName==="VIDEO"?"loadeddata":"load";o(N1,z1,_1),o(N1,"error",J1)})($1,(N1)=>{((_1,J1,z1,M1)=>{let L1=f(J1);j1(J1,z1,M1),n(J1,z1.class_loaded),h(J1,"loaded"),d(z1.callback_loaded,J1,M1),L1||c(z1,M1)})(0,R1,X1,W1),Z1($1)},(N1)=>{((_1,J1,z1,M1)=>{let L1=f(J1);j1(J1,z1,M1),n(J1,z1.class_error),h(J1,"error"),d(z1.callback_error,J1,M1),z1.restore_on_error&&e(J1,b),L1||c(z1,M1)})(0,R1,X1,W1),Z1($1)})},B1=(R1,X1,W1)=>{(($1)=>i.indexOf($1.tagName)>-1)(R1)?(($1,N1,_1)=>{H1($1,N1,_1),((J1,z1,M1)=>{let L1=Y1[J1.tagName];L1&&(L1(J1,z1),U1(J1,z1,M1))})($1,N1,_1)})(R1,X1,W1):(($1,N1,_1)=>{((J1)=>{J1.llTempImage=document.createElement("IMG")})($1),H1($1,N1,_1),((J1)=>{s(J1)||(J1.llOriginalAttrs={backgroundImage:J1.style.backgroundImage})})($1),((J1,z1,M1)=>{let L1=M(J1,z1.data_bg),V1=M(J1,z1.data_bg_hidpi),S1=J&&V1?V1:L1;S1&&(J1.style.backgroundImage=`url("${S1}")`,q(J1).setAttribute("src",S1),U1(J1,z1,M1))})($1,N1,_1),((J1,z1,M1)=>{let L1=M(J1,z1.data_bg_multi),V1=M(J1,z1.data_bg_multi_hidpi),S1=J&&V1?V1:L1;S1&&(J1.style.backgroundImage=S1,t(J1,z1,M1))})($1,N1,_1),((J1,z1,M1)=>{let L1=M(J1,z1.data_bg_set);if(!L1)return;let V1=L1.split("|").map((S1)=>`image-set(${S1})`);J1.style.backgroundImage=V1.join(),t(J1,z1,M1)})($1,N1,_1)})(R1,X1,W1)},k1=(R1)=>{R1.removeAttribute("src"),R1.removeAttribute("srcset"),R1.removeAttribute("sizes")},D1=(R1)=>{S(R1,(X1)=>{e(X1,b)}),e(R1,b)},G1={IMG:D1,IFRAME:(R1)=>{e(R1,W)},VIDEO:(R1)=>{_(R1,(X1)=>{e(X1,W)}),e(R1,j),R1.load()},OBJECT:(R1)=>{e(R1,p)}},w1=(R1,X1)=>{((W1)=>{let $1=G1[W1.tagName];$1?$1(W1):((N1)=>{if(!s(N1))return;let _1=r(N1);N1.style.backgroundImage=_1.backgroundImage})(W1)})(R1),((W1,$1)=>{g(W1)||f(W1)||(B(W1,$1.class_entered),B(W1,$1.class_exited),B(W1,$1.class_applied),B(W1,$1.class_loading),B(W1,$1.class_loaded),B(W1,$1.class_error))})(R1,X1),y(R1),A1(R1)},G=["IMG","IFRAME","VIDEO"],z=(R1)=>R1.use_native&&("loading"in HTMLImageElement.prototype),x=(R1,X1,W1)=>{R1.forEach(($1)=>((N1)=>N1.isIntersecting||N1.intersectionRatio>0)($1)?((N1,_1,J1,z1)=>{let M1=((L1)=>u.indexOf(T(L1))>=0)(N1);h(N1,"entered"),n(N1,J1.class_entered),B(N1,J1.class_exited),((L1,V1,S1)=>{V1.unobserve_entered&&P(L1,S1)})(N1,J1,z1),d(J1.callback_enter,N1,_1,z1),M1||B1(N1,J1,z1)})($1.target,$1,X1,W1):((N1,_1,J1,z1)=>{g(N1)||(n(N1,J1.class_exited),((M1,L1,V1,S1)=>{V1.cancel_on_exit&&((O0)=>T(O0)==="loading")(M1)&&M1.tagName==="IMG"&&(Z1(M1),((O0)=>{S(O0,(h1)=>{k1(h1)}),k1(O0)})(M1),D1(M1),B(M1,V1.class_loading),O(S1,-1),y(M1),d(V1.callback_cancel,M1,L1,S1))})(N1,_1,J1,z1),d(J1.callback_exit,N1,_1,z1))})($1.target,$1,X1,W1))},m=(R1)=>Array.prototype.slice.call(R1),l=(R1)=>R1.container.querySelectorAll(R1.elements_selector),a=(R1)=>((X1)=>T(X1)==="error")(R1),K1=(R1,X1)=>((W1)=>m(W1).filter(g))(R1||l(X1)),F1=function(R1,X1){let W1=C(R1);this._settings=W1,this.loadingCount=0,(($1,N1)=>{z($1)||(N1._observer=new IntersectionObserver((_1)=>{x(_1,$1,N1)},((_1)=>({root:_1.container===document?null:_1.container,rootMargin:_1.thresholds||_1.threshold+"px"}))($1)))})(W1,this),(($1,N1)=>{A&&(N1._onlineHandler=()=>{((_1,J1)=>{var z1;(z1=l(_1),m(z1).filter(a)).forEach((M1)=>{B(M1,_1.class_error),y(M1)}),J1.update()})($1,N1)},window.addEventListener("online",N1._onlineHandler))})(W1,this),this.update(X1)};return F1.prototype={update:function(R1){let X1=this._settings,W1=K1(R1,X1);var $1,N1;w(this,W1.length),Q?this.loadAll(W1):z(X1)?((_1,J1,z1)=>{_1.forEach((M1)=>{G.indexOf(M1.tagName)!==-1&&((L1,V1,S1)=>{L1.setAttribute("loading","lazy"),H1(L1,V1,S1),((O0,h1)=>{let b1=Y1[O0.tagName];b1&&b1(O0,h1)})(L1,V1),h(L1,"native")})(M1,J1,z1)}),w(z1,0)})(W1,X1,this):(N1=W1,((_1)=>{_1.disconnect()})($1=this._observer),((_1,J1)=>{J1.forEach((z1)=>{_1.observe(z1)})})($1,N1))},destroy:function(){this._observer&&this._observer.disconnect(),A&&window.removeEventListener("online",this._onlineHandler),l(this._settings).forEach((R1)=>{A1(R1)}),delete this._observer,delete this._settings,delete this._onlineHandler,delete this.loadingCount,delete this.toLoadCount},loadAll:function(R1){let X1=this._settings;K1(R1,X1).forEach((W1)=>{P(W1,this),B1(W1,X1,this)})},restoreAll:function(){let R1=this._settings;l(R1).forEach((X1)=>{w1(X1,R1)})}},F1.load=(R1,X1)=>{let W1=C(X1);B1(R1,W1)},F1.resetStatus=(R1)=>{y(R1)},A&&((R1,X1)=>{if(X1)if(X1.length)for(let W1,$1=0;W1=X1[$1];$1+=1)U(R1,W1);else U(R1,X1)})(F1,window.lazyLoadOptions),F1})});var Ao={};z3(Ao,{default:()=>xq1});function CI1(A){if(U0.locateFile)return U0.locateFile(A,j7);return j7+A}function ns(){var A=jI.buffer;U0.HEAP8=UI1=new Int8Array(A),U0.HEAP16=ZI1=new Int16Array(A),U0.HEAPU8=sM=new Uint8Array(A),U0.HEAPU16=BI1=new Uint16Array(A),U0.HEAP32=XI1=new Int32Array(A),U0.HEAPU32=EI1=new Uint32Array(A),U0.HEAPF32=$I1=new Float32Array(A),U0.HEAPF64=HI1=new Float64Array(A)}function WI1(){if(U0.preRun){if(typeof U0.preRun=="function")U0.preRun=[U0.preRun];while(U0.preRun.length)OI1(U0.preRun.shift())}oM(ss)}function II1(){GI1=!0,oM(os)}function qI1(){if(U0.postRun){if(typeof U0.postRun=="function")U0.postRun=[U0.postRun];while(U0.postRun.length)LI1(U0.postRun.shift())}oM(is)}function OI1(A){ss.unshift(A)}function NI1(A){os.unshift(A)}function LI1(A){is.unshift(A)}function FI1(A){xJ++,U0.monitorRunDependencies?.(xJ)}function RI1(A){if(xJ--,U0.monitorRunDependencies?.(xJ),xJ==0){if(nM!==null)clearInterval(nM),nM=null;if(AX){var Q=AX;AX=null,Q()}}}function as(A){U0.onAbort?.(A),A="Aborted("+A+")",QX(A),ls=!0,YI1=1,A+=". Build with -sASSERTIONS for more info.";var Q=new WebAssembly.RuntimeError(A);throw Q}function DI1(){var A="/dist/ffl-emscripten.wasm";if(!rs(A))return CI1(A);return A}function fs(A){if(A==SI&&JX)return new Uint8Array(JX);if(bs)return bs(A);throw"both async and sync fetching of the wasm failed"}function VI1(A){if(!JX)return ds(A).then((Q)=>new Uint8Array(Q),()=>fs(A));return Promise.resolve().then(()=>fs(A))}function ps(A,Q,J){return VI1(A).then((K)=>WebAssembly.instantiate(K,Q)).then(J,(K)=>{QX(`failed to asynchronously prepare wasm: ${K}`),as(K)})}function MI1(A,Q,J,K){if(!A&&typeof WebAssembly.instantiateStreaming=="function"&&!rs(Q)&&typeof fetch=="function")return fetch(Q,{credentials:"same-origin"}).then((C)=>{var U=WebAssembly.instantiateStreaming(C,J);return U.then(K,function(Y){return QX(`wasm streaming compile failed: ${Y}`),QX("falling back to ArrayBuffer instantiation"),ps(Q,J,K)})});return ps(Q,J,K)}function wI1(){return{a:mI1}}function PI1(){var A=wI1();function Q(K,C){return IA=K.exports,jI=IA.e,ns(),yJ=IA.O,NI1(IA.f),RI1("wasm-instantiate"),IA}FI1("wasm-instantiate");function J(K){Q(K.instance)}if(U0.instantiateWasm)try{return U0.instantiateWasm(A,Q)}catch(K){return QX(`Module.instantiateWasm callback failed with error: ${K}`),!1}if(!SI)SI=DI1();return MI1(JX,SI,A,J),{}}function es(){if(xJ>0)return;if(WI1(),xJ>0)return;function A(){if(vI)return;if(vI=!0,U0.calledRun=!0,ls)return;II1(),U0.onRuntimeInitialized?.(),qI1()}if(U0.setStatus)U0.setStatus("Running..."),setTimeout(function(){setTimeout(function(){U0.setStatus("")},1),A()},1);else A()}var U0,AI1=!0,gs=!1,cs,QI1,JI1="./this.program",KI1=(A,Q)=>{throw Q},j7="",ds,bs,p00,QX,JX,jI,ls=!1,YI1,UI1,sM,ZI1,BI1,XI1,EI1,$I1,HI1,ss,os,is,GI1=!1,xJ=0,nM=null,AX=null,zI1="data:application/octet-stream;base64,",rs=(A)=>A.startsWith(zI1),SI,oM=(A)=>{while(A.length>0)A.shift()(U0)},u00,_I1=()=>{as("")},TI1=(A,Q,J)=>sM.copyWithin(A,Q,Q+J),kI1=()=>Math.random(),SI1=()=>2147483648,jI1=(A)=>{var Q=jI.buffer,J=(A-Q.byteLength+65535)/65536;try{return jI.grow(J),ns(),1}catch(K){}},vI1=(A)=>{var Q=sM.length;A>>>=0;var J=SI1();if(A>J)return!1;var K=(X,E)=>X+(E-X%E)%E;for(var C=1;C<=4;C*=2){var U=Q*(1+0.2/C);U=Math.min(U,A+100663296);var Y=Math.min(J,K(Math.max(A,U),65536)),Z=jI1(Y);if(Z)return!0}return!1},ts=(A,Q)=>{if(A<128)Q.push(A);else Q.push(A%128|128,A>>7)},xI1=(A)=>{var Q={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},J={parameters:[],results:A[0]=="v"?[]:[Q[A[0]]]};for(var K=1;K{var J=A.slice(0,1),K=A.slice(1),C={i:127,p:127,j:126,f:125,d:124,e:111};Q.push(96),ts(K.length,Q);for(var U=0;U{if(typeof WebAssembly.Function=="function")return new WebAssembly.Function(xI1(Q),A);var J=[1];yI1(Q,J);var K=[0,97,115,109,1,0,0,0,1];ts(J.length,K),K.push(...J),K.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var C=new WebAssembly.Module(new Uint8Array(K)),U=new WebAssembly.Instance(C,{e:{f:A}}),Y=U.exports.f;return Y},eB,yJ,gI1=(A)=>{var Q=eB[A];if(!Q){if(A>=eB.length)eB.length=A+1;eB[A]=Q=yJ.get(A)}return Q},bI1=(A,Q)=>{if(FY)for(var J=A;J{if(!FY)FY=/*@__PURE__*/new WeakMap,bI1(0,yJ.length);return FY.get(A)||0},us,pI1=()=>{if(us.length)return us.pop();try{yJ.grow(1)}catch(A){if(!(A instanceof RangeError))throw A;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return yJ.length-1},ms=(A,Q)=>{yJ.set(A,Q),eB[A]=yJ.get(A)},uI1=(A,Q)=>{var J=fI1(A);if(J)return J;var K=pI1();try{ms(K,A)}catch(U){if(!(U instanceof TypeError))throw U;var C=hI1(A,Q);ms(K,C)}return FY.set(A,K),K},mI1,IA,cI1,dI1,lI1,nI1,sI1,oI1,iI1,aI1,rI1,tI1,eI1,Aq1,Qq1,Jq1,Kq1,Cq1,Yq1,Uq1,Zq1,Bq1,Xq1,Eq1,$q1,Hq1,Gq1,Wq1,Iq1,qq1,Oq1,Nq1,Lq1,Fq1,Rq1,zq1,Dq1,Vq1,Mq1,wq1,Pq1,_q1,Tq1,kq1,Sq1,jq1,vq1,vI,xq1;var Qo=hJ(()=>{U0=typeof U0!="undefined"?U0:{},cs=Object.assign({},U0),QI1=[];if(AI1||gs){if(gs)j7=self.location.href;else if(typeof document!="undefined"&&document.currentScript)j7=document.currentScript.src;if(j7.startsWith("blob:"))j7="";else j7=j7.substr(0,j7.replace(/[?#].*/,"").lastIndexOf("/")+1);ds=(A)=>fetch(A,{credentials:"same-origin"}).then((Q)=>{if(Q.ok)return Q.arrayBuffer();return Promise.reject(new Error(Q.status+" : "+Q.url))})}p00=U0.print||console.log.bind(console),QX=U0.printErr||console.error.bind(console);Object.assign(U0,cs);cs=null;if(U0.arguments)QI1=U0.arguments;if(U0.thisProgram)JI1=U0.thisProgram;if(U0.quit)KI1=U0.quit;if(U0.wasmBinary)JX=U0.wasmBinary;ss=[],os=[],is=[];u00=U0.noExitRuntime||!0,eB=[],us=[],mI1={a:_I1,c:TI1,d:kI1,b:vI1},IA=PI1(),cI1=U0._FFLInitCharModelCPUStepWithCallback=(A,Q,J,K)=>(cI1=U0._FFLInitCharModelCPUStepWithCallback=IA.g)(A,Q,J,K),dI1=U0._FFLInitCharModelCPUStep=(A,Q,J)=>(dI1=U0._FFLInitCharModelCPUStep=IA.h)(A,Q,J),lI1=U0._FFLDeleteCharModel=(A)=>(lI1=U0._FFLDeleteCharModel=IA.i)(A),nI1=U0._FFLGetDrawParamOpaFaceline=(A)=>(nI1=U0._FFLGetDrawParamOpaFaceline=IA.j)(A),sI1=U0._FFLGetDrawParamOpaBeard=(A)=>(sI1=U0._FFLGetDrawParamOpaBeard=IA.k)(A),oI1=U0._FFLGetDrawParamOpaNose=(A)=>(oI1=U0._FFLGetDrawParamOpaNose=IA.l)(A),iI1=U0._FFLGetDrawParamOpaForehead=(A)=>(iI1=U0._FFLGetDrawParamOpaForehead=IA.m)(A),aI1=U0._FFLGetDrawParamOpaHair=(A)=>(aI1=U0._FFLGetDrawParamOpaHair=IA.n)(A),rI1=U0._FFLGetDrawParamOpaCap=(A)=>(rI1=U0._FFLGetDrawParamOpaCap=IA.o)(A),tI1=U0._FFLGetDrawParamXluMask=(A)=>(tI1=U0._FFLGetDrawParamXluMask=IA.p)(A),eI1=U0._FFLGetDrawParamXluNoseLine=(A)=>(eI1=U0._FFLGetDrawParamXluNoseLine=IA.q)(A),Aq1=U0._FFLGetDrawParamXluGlass=(A)=>(Aq1=U0._FFLGetDrawParamXluGlass=IA.r)(A),Qq1=U0._FFLSetExpression=(A,Q)=>(Qq1=U0._FFLSetExpression=IA.s)(A,Q),Jq1=U0._FFLGetExpression=(A)=>(Jq1=U0._FFLGetExpression=IA.t)(A),Kq1=U0._FFLSetViewModelType=(A,Q)=>(Kq1=U0._FFLSetViewModelType=IA.u)(A,Q),Cq1=U0._FFLGetBoundingBox=(A,Q)=>(Cq1=U0._FFLGetBoundingBox=IA.v)(A,Q),Yq1=U0._FFLIsAvailableExpression=(A,Q)=>(Yq1=U0._FFLIsAvailableExpression=IA.w)(A,Q),Uq1=U0._FFLSetCoordinate=(A,Q)=>(Uq1=U0._FFLSetCoordinate=IA.x)(A,Q),Zq1=U0._FFLSetScale=(A)=>(Zq1=U0._FFLSetScale=IA.y)(A),Bq1=U0._FFLiGetRandomCharInfo=(A,Q,J,K)=>(Bq1=U0._FFLiGetRandomCharInfo=IA.z)(A,Q,J,K),Xq1=U0._FFLpGetStoreDataFromCharInfo=(A,Q)=>(Xq1=U0._FFLpGetStoreDataFromCharInfo=IA.A)(A,Q),Eq1=U0._FFLpGetCharInfoFromStoreData=(A,Q)=>(Eq1=U0._FFLpGetCharInfoFromStoreData=IA.B)(A,Q),$q1=U0._FFLGetAdditionalInfo=(A,Q,J,K,C)=>($q1=U0._FFLGetAdditionalInfo=IA.C)(A,Q,J,K,C),Hq1=U0._FFLInitRes=(A,Q)=>(Hq1=U0._FFLInitRes=IA.D)(A,Q),Gq1=U0._FFLInitResGPUStep=()=>(Gq1=U0._FFLInitResGPUStep=IA.E)(),Wq1=U0._FFLExit=()=>(Wq1=U0._FFLExit=IA.F)(),Iq1=U0._FFLIsAvailable=()=>(Iq1=U0._FFLIsAvailable=IA.G)(),qq1=U0._FFLGetFavoriteColor=(A,Q)=>(qq1=U0._FFLGetFavoriteColor=IA.H)(A,Q),Oq1=U0._FFLSetLinearGammaMode=(A)=>(Oq1=U0._FFLSetLinearGammaMode=IA.I)(A),Nq1=U0._FFLGetFacelineColor=(A,Q)=>(Nq1=U0._FFLGetFacelineColor=IA.J)(A,Q),Lq1=U0._FFLSetTextureFlipY=(A)=>(Lq1=U0._FFLSetTextureFlipY=IA.K)(A),Fq1=U0._FFLSetNormalIsSnorm8_8_8_8=(A)=>(Fq1=U0._FFLSetNormalIsSnorm8_8_8_8=IA.L)(A),Rq1=U0._FFLSetFrontCullForFlipX=(A)=>(Rq1=U0._FFLSetFrontCullForFlipX=IA.M)(A),zq1=U0._FFLSetTextureCallback=(A)=>(zq1=U0._FFLSetTextureCallback=IA.N)(A),Dq1=U0._FFLiDeleteTempObjectMaskTextures=(A,Q,J)=>(Dq1=U0._FFLiDeleteTempObjectMaskTextures=IA.P)(A,Q,J),Vq1=U0._FFLiDeleteTempObjectFacelineTexture=(A,Q,J)=>(Vq1=U0._FFLiDeleteTempObjectFacelineTexture=IA.Q)(A,Q,J),Mq1=U0._FFLiDeleteTextureTempObject=(A)=>(Mq1=U0._FFLiDeleteTextureTempObject=IA.R)(A),wq1=U0._FFLiiGetEyeRotateOffset=(A)=>(wq1=U0._FFLiiGetEyeRotateOffset=IA.S)(A),Pq1=U0._FFLiiGetEyebrowRotateOffset=(A)=>(Pq1=U0._FFLiiGetEyebrowRotateOffset=IA.T)(A),_q1=U0._FFLiInvalidateTempObjectFacelineTexture=(A)=>(_q1=U0._FFLiInvalidateTempObjectFacelineTexture=IA.U)(A),Tq1=U0._FFLiInvalidatePartsTextures=(A)=>(Tq1=U0._FFLiInvalidatePartsTextures=IA.V)(A),kq1=U0._FFLiInvalidateRawMask=(A)=>(kq1=U0._FFLiInvalidateRawMask=IA.W)(A),Sq1=U0._FFLiVerifyCharInfoWithReason=(A,Q)=>(Sq1=U0._FFLiVerifyCharInfoWithReason=IA.X)(A,Q),jq1=U0._malloc=(A)=>(jq1=U0._malloc=IA.Y)(A),vq1=U0._free=(A)=>(vq1=U0._free=IA.Z)(A);U0.addFunction=uI1;AX=function A(){if(!vI)es();if(!vI)AX=A};if(U0.preInit){if(typeof U0.preInit=="function")U0.preInit=[U0.preInit];while(U0.preInit.length>0)U0.preInit.pop()()}es();xq1={Module:U0}});/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */var bI=Qw(),bJ=Jw(),Kw=typeof Symbol==="function"&&typeof Symbol.for==="function"?Symbol.for("nodejs.util.inspect.custom"):null;var QA=$0;var Lw=50;var fI=2147483647;$0.TYPED_ARRAY_SUPPORT=Mo();if(!$0.TYPED_ARRAY_SUPPORT&&typeof console!=="undefined"&&typeof console.error==="function")console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Mo(){try{let A=new Uint8Array(1),Q={foo:function(){return 42}};return Object.setPrototypeOf(Q,Uint8Array.prototype),Object.setPrototypeOf(A,Q),A.foo()===42}catch(A){return!1}}Object.defineProperty($0.prototype,"parent",{enumerable:!0,get:function(){if(!$0.isBuffer(this))return;return this.buffer}});Object.defineProperty($0.prototype,"offset",{enumerable:!0,get:function(){if(!$0.isBuffer(this))return;return this.byteOffset}});function D3(A){if(A>fI)throw new RangeError('The value "'+A+'" is invalid for option "size"');let Q=new Uint8Array(A);return Object.setPrototypeOf(Q,$0.prototype),Q}function $0(A,Q,J){if(typeof A==="number"){if(typeof Q==="string")throw new TypeError('The "string" argument must be of type string. Received type number');return cI(A)}return Zw(A,Q,J)}$0.poolSize=8192;function Zw(A,Q,J){if(typeof A==="string")return Po(A,Q);if(ArrayBuffer.isView(A))return _o(A);if(A==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof A);if(g5(A,ArrayBuffer)||A&&g5(A.buffer,ArrayBuffer))return uI(A,Q,J);if(typeof SharedArrayBuffer!=="undefined"&&(g5(A,SharedArrayBuffer)||A&&g5(A.buffer,SharedArrayBuffer)))return uI(A,Q,J);if(typeof A==="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let K=A.valueOf&&A.valueOf();if(K!=null&&K!==A)return $0.from(K,Q,J);let C=To(A);if(C)return C;if(typeof Symbol!=="undefined"&&Symbol.toPrimitive!=null&&typeof A[Symbol.toPrimitive]==="function")return $0.from(A[Symbol.toPrimitive]("string"),Q,J);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof A)}$0.from=function(A,Q,J){return Zw(A,Q,J)};Object.setPrototypeOf($0.prototype,Uint8Array.prototype);Object.setPrototypeOf($0,Uint8Array);function Bw(A){if(typeof A!=="number")throw new TypeError('"size" argument must be of type number');else if(A<0)throw new RangeError('The value "'+A+'" is invalid for option "size"')}function wo(A,Q,J){if(Bw(A),A<=0)return D3(A);if(Q!==void 0)return typeof J==="string"?D3(A).fill(Q,J):D3(A).fill(Q);return D3(A)}$0.alloc=function(A,Q,J){return wo(A,Q,J)};function cI(A){return Bw(A),D3(A<0?0:dI(A)|0)}$0.allocUnsafe=function(A){return cI(A)};$0.allocUnsafeSlow=function(A){return cI(A)};function Po(A,Q){if(typeof Q!=="string"||Q==="")Q="utf8";if(!$0.isEncoding(Q))throw new TypeError("Unknown encoding: "+Q);let J=Xw(A,Q)|0,K=D3(J),C=K.write(A,Q);if(C!==J)K=K.slice(0,C);return K}function pI(A){let Q=A.length<0?0:dI(A.length)|0,J=D3(Q);for(let K=0;K=fI)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+fI.toString(16)+" bytes");return A|0}$0.isBuffer=function A(Q){return Q!=null&&Q._isBuffer===!0&&Q!==$0.prototype};$0.compare=function A(Q,J){if(g5(Q,Uint8Array))Q=$0.from(Q,Q.offset,Q.byteLength);if(g5(J,Uint8Array))J=$0.from(J,J.offset,J.byteLength);if(!$0.isBuffer(Q)||!$0.isBuffer(J))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(Q===J)return 0;let K=Q.length,C=J.length;for(let U=0,Y=Math.min(K,C);UC.length){if(!$0.isBuffer(Y))Y=$0.from(Y);Y.copy(C,U)}else Uint8Array.prototype.set.call(C,Y,U);else if(!$0.isBuffer(Y))throw new TypeError('"list" argument must be an Array of Buffers');else Y.copy(C,U);U+=Y.length}return C};function Xw(A,Q){if($0.isBuffer(A))return A.length;if(ArrayBuffer.isView(A)||g5(A,ArrayBuffer))return A.byteLength;if(typeof A!=="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof A);let J=A.length,K=arguments.length>2&&arguments[2]===!0;if(!K&&J===0)return 0;let C=!1;for(;;)switch(Q){case"ascii":case"latin1":case"binary":return J;case"utf8":case"utf-8":return mI(A).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return J*2;case"hex":return J>>>1;case"base64":return Nw(A).length;default:if(C)return K?-1:mI(A).length;Q=(""+Q).toLowerCase(),C=!0}}$0.byteLength=Xw;function ko(A,Q,J){let K=!1;if(Q===void 0||Q<0)Q=0;if(Q>this.length)return"";if(J===void 0||J>this.length)J=this.length;if(J<=0)return"";if(J>>>=0,Q>>>=0,J<=Q)return"";if(!A)A="utf8";while(!0)switch(A){case"hex":return po(this,Q,J);case"utf8":case"utf-8":return $w(this,Q,J);case"ascii":return bo(this,Q,J);case"latin1":case"binary":return fo(this,Q,J);case"base64":return ho(this,Q,J);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return uo(this,Q,J);default:if(K)throw new TypeError("Unknown encoding: "+A);A=(A+"").toLowerCase(),K=!0}}$0.prototype._isBuffer=!0;function g4(A,Q,J){let K=A[Q];A[Q]=A[J],A[J]=K}$0.prototype.swap16=function A(){let Q=this.length;if(Q%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let J=0;JJ)Q+=" ... ";return""};if(Kw)$0.prototype[Kw]=$0.prototype.inspect;$0.prototype.compare=function A(Q,J,K,C,U){if(g5(Q,Uint8Array))Q=$0.from(Q,Q.offset,Q.byteLength);if(!$0.isBuffer(Q))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof Q);if(J===void 0)J=0;if(K===void 0)K=Q?Q.length:0;if(C===void 0)C=0;if(U===void 0)U=this.length;if(J<0||K>Q.length||C<0||U>this.length)throw new RangeError("out of range index");if(C>=U&&J>=K)return 0;if(C>=U)return-1;if(J>=K)return 1;if(J>>>=0,K>>>=0,C>>>=0,U>>>=0,this===Q)return 0;let Y=U-C,Z=K-J,X=Math.min(Y,Z),E=this.slice(C,U),H=Q.slice(J,K);for(let $=0;$2147483647)J=2147483647;else if(J<-2147483648)J=-2147483648;if(J=+J,nI(J))J=C?0:A.length-1;if(J<0)J=A.length+J;if(J>=A.length)if(C)return-1;else J=A.length-1;else if(J<0)if(C)J=0;else return-1;if(typeof Q==="string")Q=$0.from(Q,K);if($0.isBuffer(Q)){if(Q.length===0)return-1;return Cw(A,Q,J,K,C)}else if(typeof Q==="number"){if(Q=Q&255,typeof Uint8Array.prototype.indexOf==="function")if(C)return Uint8Array.prototype.indexOf.call(A,Q,J);else return Uint8Array.prototype.lastIndexOf.call(A,Q,J);return Cw(A,[Q],J,K,C)}throw new TypeError("val must be string, number or Buffer")}function Cw(A,Q,J,K,C){let U=1,Y=A.length,Z=Q.length;if(K!==void 0){if(K=String(K).toLowerCase(),K==="ucs2"||K==="ucs-2"||K==="utf16le"||K==="utf-16le"){if(A.length<2||Q.length<2)return-1;U=2,Y/=2,Z/=2,J/=2}}function X(H,$){if(U===1)return H[$];else return H.readUInt16BE($*U)}let E;if(C){let H=-1;for(E=J;EY)J=Y-Z;for(E=J;E>=0;E--){let H=!0;for(let $=0;$C)K=C;let U=Q.length;if(K>U/2)K=U/2;let Y;for(Y=0;Y>>0,isFinite(K)){if(K=K>>>0,C===void 0)C="utf8"}else C=K,K=void 0;else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let U=this.length-J;if(K===void 0||K>U)K=U;if(Q.length>0&&(K<0||J<0)||J>this.length)throw new RangeError("Attempt to write outside buffer bounds");if(!C)C="utf8";let Y=!1;for(;;)switch(C){case"hex":return So(this,Q,J,K);case"utf8":case"utf-8":return jo(this,Q,J,K);case"ascii":case"latin1":case"binary":return vo(this,Q,J,K);case"base64":return xo(this,Q,J,K);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return yo(this,Q,J,K);default:if(Y)throw new TypeError("Unknown encoding: "+C);C=(""+C).toLowerCase(),Y=!0}};$0.prototype.toJSON=function A(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function ho(A,Q,J){if(Q===0&&J===A.length)return bI.fromByteArray(A);else return bI.fromByteArray(A.slice(Q,J))}function $w(A,Q,J){J=Math.min(A.length,J);let K=[],C=Q;while(C239?4:U>223?3:U>191?2:1;if(C+Z<=J){let X,E,H,$;switch(Z){case 1:if(U<128)Y=U;break;case 2:if(X=A[C+1],(X&192)===128){if($=(U&31)<<6|X&63,$>127)Y=$}break;case 3:if(X=A[C+1],E=A[C+2],(X&192)===128&&(E&192)===128){if($=(U&15)<<12|(X&63)<<6|E&63,$>2047&&($<55296||$>57343))Y=$}break;case 4:if(X=A[C+1],E=A[C+2],H=A[C+3],(X&192)===128&&(E&192)===128&&(H&192)===128){if($=(U&15)<<18|(X&63)<<12|(E&63)<<6|H&63,$>65535&&$<1114112)Y=$}}}if(Y===null)Y=65533,Z=1;else if(Y>65535)Y-=65536,K.push(Y>>>10&1023|55296),Y=56320|Y&1023;K.push(Y),C+=Z}return go(K)}var Yw=4096;function go(A){let Q=A.length;if(Q<=Yw)return String.fromCharCode.apply(String,A);let J="",K=0;while(KK)J=K;let C="";for(let U=Q;UK)Q=K;if(J<0){if(J+=K,J<0)J=0}else if(J>K)J=K;if(JJ)throw new RangeError("Trying to access beyond buffer length")}$0.prototype.readUintLE=$0.prototype.readUIntLE=function A(Q,J,K){if(Q=Q>>>0,J=J>>>0,!K)v8(Q,J,this.length);let C=this[Q],U=1,Y=0;while(++Y>>0,J=J>>>0,!K)v8(Q,J,this.length);let C=this[Q+--J],U=1;while(J>0&&(U*=256))C+=this[Q+--J]*U;return C};$0.prototype.readUint8=$0.prototype.readUInt8=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,1,this.length);return this[Q]};$0.prototype.readUint16LE=$0.prototype.readUInt16LE=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,2,this.length);return this[Q]|this[Q+1]<<8};$0.prototype.readUint16BE=$0.prototype.readUInt16BE=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,2,this.length);return this[Q]<<8|this[Q+1]};$0.prototype.readUint32LE=$0.prototype.readUInt32LE=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,4,this.length);return(this[Q]|this[Q+1]<<8|this[Q+2]<<16)+this[Q+3]*16777216};$0.prototype.readUint32BE=$0.prototype.readUInt32BE=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,4,this.length);return this[Q]*16777216+(this[Q+1]<<16|this[Q+2]<<8|this[Q+3])};$0.prototype.readBigUInt64LE=x7(function A(Q){Q=Q>>>0,fJ(Q,"offset");let J=this[Q],K=this[Q+7];if(J===void 0||K===void 0)DY(Q,this.length-8);let C=J+this[++Q]*256+this[++Q]*65536+this[++Q]*16777216,U=this[++Q]+this[++Q]*256+this[++Q]*65536+K*16777216;return BigInt(C)+(BigInt(U)<>>0,fJ(Q,"offset");let J=this[Q],K=this[Q+7];if(J===void 0||K===void 0)DY(Q,this.length-8);let C=J*16777216+this[++Q]*65536+this[++Q]*256+this[++Q],U=this[++Q]*16777216+this[++Q]*65536+this[++Q]*256+K;return(BigInt(C)<>>0,J=J>>>0,!K)v8(Q,J,this.length);let C=this[Q],U=1,Y=0;while(++Y=U)C-=Math.pow(2,8*J);return C};$0.prototype.readIntBE=function A(Q,J,K){if(Q=Q>>>0,J=J>>>0,!K)v8(Q,J,this.length);let C=J,U=1,Y=this[Q+--C];while(C>0&&(U*=256))Y+=this[Q+--C]*U;if(U*=128,Y>=U)Y-=Math.pow(2,8*J);return Y};$0.prototype.readInt8=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,1,this.length);if(!(this[Q]&128))return this[Q];return(255-this[Q]+1)*-1};$0.prototype.readInt16LE=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,2,this.length);let K=this[Q]|this[Q+1]<<8;return K&32768?K|4294901760:K};$0.prototype.readInt16BE=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,2,this.length);let K=this[Q+1]|this[Q]<<8;return K&32768?K|4294901760:K};$0.prototype.readInt32LE=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,4,this.length);return this[Q]|this[Q+1]<<8|this[Q+2]<<16|this[Q+3]<<24};$0.prototype.readInt32BE=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,4,this.length);return this[Q]<<24|this[Q+1]<<16|this[Q+2]<<8|this[Q+3]};$0.prototype.readBigInt64LE=x7(function A(Q){Q=Q>>>0,fJ(Q,"offset");let J=this[Q],K=this[Q+7];if(J===void 0||K===void 0)DY(Q,this.length-8);let C=this[Q+4]+this[Q+5]*256+this[Q+6]*65536+(K<<24);return(BigInt(C)<>>0,fJ(Q,"offset");let J=this[Q],K=this[Q+7];if(J===void 0||K===void 0)DY(Q,this.length-8);let C=(J<<24)+this[++Q]*65536+this[++Q]*256+this[++Q];return(BigInt(C)<>>0,!J)v8(Q,4,this.length);return bJ.read(this,Q,!0,23,4)};$0.prototype.readFloatBE=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,4,this.length);return bJ.read(this,Q,!1,23,4)};$0.prototype.readDoubleLE=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,8,this.length);return bJ.read(this,Q,!0,52,8)};$0.prototype.readDoubleBE=function A(Q,J){if(Q=Q>>>0,!J)v8(Q,8,this.length);return bJ.read(this,Q,!1,52,8)};function T6(A,Q,J,K,C,U){if(!$0.isBuffer(A))throw new TypeError('"buffer" argument must be a Buffer instance');if(Q>C||QA.length)throw new RangeError("Index out of range")}$0.prototype.writeUintLE=$0.prototype.writeUIntLE=function A(Q,J,K,C){if(Q=+Q,J=J>>>0,K=K>>>0,!C){let Z=Math.pow(2,8*K)-1;T6(this,Q,J,K,Z,0)}let U=1,Y=0;this[J]=Q&255;while(++Y>>0,K=K>>>0,!C){let Z=Math.pow(2,8*K)-1;T6(this,Q,J,K,Z,0)}let U=K-1,Y=1;this[J+U]=Q&255;while(--U>=0&&(Y*=256))this[J+U]=Q/Y&255;return J+K};$0.prototype.writeUint8=$0.prototype.writeUInt8=function A(Q,J,K){if(Q=+Q,J=J>>>0,!K)T6(this,Q,J,1,255,0);return this[J]=Q&255,J+1};$0.prototype.writeUint16LE=$0.prototype.writeUInt16LE=function A(Q,J,K){if(Q=+Q,J=J>>>0,!K)T6(this,Q,J,2,65535,0);return this[J]=Q&255,this[J+1]=Q>>>8,J+2};$0.prototype.writeUint16BE=$0.prototype.writeUInt16BE=function A(Q,J,K){if(Q=+Q,J=J>>>0,!K)T6(this,Q,J,2,65535,0);return this[J]=Q>>>8,this[J+1]=Q&255,J+2};$0.prototype.writeUint32LE=$0.prototype.writeUInt32LE=function A(Q,J,K){if(Q=+Q,J=J>>>0,!K)T6(this,Q,J,4,4294967295,0);return this[J+3]=Q>>>24,this[J+2]=Q>>>16,this[J+1]=Q>>>8,this[J]=Q&255,J+4};$0.prototype.writeUint32BE=$0.prototype.writeUInt32BE=function A(Q,J,K){if(Q=+Q,J=J>>>0,!K)T6(this,Q,J,4,4294967295,0);return this[J]=Q>>>24,this[J+1]=Q>>>16,this[J+2]=Q>>>8,this[J+3]=Q&255,J+4};function Hw(A,Q,J,K,C){Ow(Q,K,C,A,J,7);let U=Number(Q&BigInt(4294967295));A[J++]=U,U=U>>8,A[J++]=U,U=U>>8,A[J++]=U,U=U>>8,A[J++]=U;let Y=Number(Q>>BigInt(32)&BigInt(4294967295));return A[J++]=Y,Y=Y>>8,A[J++]=Y,Y=Y>>8,A[J++]=Y,Y=Y>>8,A[J++]=Y,J}function Gw(A,Q,J,K,C){Ow(Q,K,C,A,J,7);let U=Number(Q&BigInt(4294967295));A[J+7]=U,U=U>>8,A[J+6]=U,U=U>>8,A[J+5]=U,U=U>>8,A[J+4]=U;let Y=Number(Q>>BigInt(32)&BigInt(4294967295));return A[J+3]=Y,Y=Y>>8,A[J+2]=Y,Y=Y>>8,A[J+1]=Y,Y=Y>>8,A[J]=Y,J+8}$0.prototype.writeBigUInt64LE=x7(function A(Q,J=0){return Hw(this,Q,J,BigInt(0),BigInt("0xffffffffffffffff"))});$0.prototype.writeBigUInt64BE=x7(function A(Q,J=0){return Gw(this,Q,J,BigInt(0),BigInt("0xffffffffffffffff"))});$0.prototype.writeIntLE=function A(Q,J,K,C){if(Q=+Q,J=J>>>0,!C){let X=Math.pow(2,8*K-1);T6(this,Q,J,K,X-1,-X)}let U=0,Y=1,Z=0;this[J]=Q&255;while(++U>0)-Z&255}return J+K};$0.prototype.writeIntBE=function A(Q,J,K,C){if(Q=+Q,J=J>>>0,!C){let X=Math.pow(2,8*K-1);T6(this,Q,J,K,X-1,-X)}let U=K-1,Y=1,Z=0;this[J+U]=Q&255;while(--U>=0&&(Y*=256)){if(Q<0&&Z===0&&this[J+U+1]!==0)Z=1;this[J+U]=(Q/Y>>0)-Z&255}return J+K};$0.prototype.writeInt8=function A(Q,J,K){if(Q=+Q,J=J>>>0,!K)T6(this,Q,J,1,127,-128);if(Q<0)Q=255+Q+1;return this[J]=Q&255,J+1};$0.prototype.writeInt16LE=function A(Q,J,K){if(Q=+Q,J=J>>>0,!K)T6(this,Q,J,2,32767,-32768);return this[J]=Q&255,this[J+1]=Q>>>8,J+2};$0.prototype.writeInt16BE=function A(Q,J,K){if(Q=+Q,J=J>>>0,!K)T6(this,Q,J,2,32767,-32768);return this[J]=Q>>>8,this[J+1]=Q&255,J+2};$0.prototype.writeInt32LE=function A(Q,J,K){if(Q=+Q,J=J>>>0,!K)T6(this,Q,J,4,2147483647,-2147483648);return this[J]=Q&255,this[J+1]=Q>>>8,this[J+2]=Q>>>16,this[J+3]=Q>>>24,J+4};$0.prototype.writeInt32BE=function A(Q,J,K){if(Q=+Q,J=J>>>0,!K)T6(this,Q,J,4,2147483647,-2147483648);if(Q<0)Q=4294967295+Q+1;return this[J]=Q>>>24,this[J+1]=Q>>>16,this[J+2]=Q>>>8,this[J+3]=Q&255,J+4};$0.prototype.writeBigInt64LE=x7(function A(Q,J=0){return Hw(this,Q,J,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});$0.prototype.writeBigInt64BE=x7(function A(Q,J=0){return Gw(this,Q,J,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Ww(A,Q,J,K,C,U){if(J+K>A.length)throw new RangeError("Index out of range");if(J<0)throw new RangeError("Index out of range")}function Iw(A,Q,J,K,C){if(Q=+Q,J=J>>>0,!C)Ww(A,Q,J,4,340282346638528860000000000000000000000,-340282346638528860000000000000000000000);return bJ.write(A,Q,J,K,23,4),J+4}$0.prototype.writeFloatLE=function A(Q,J,K){return Iw(this,Q,J,!0,K)};$0.prototype.writeFloatBE=function A(Q,J,K){return Iw(this,Q,J,!1,K)};function qw(A,Q,J,K,C){if(Q=+Q,J=J>>>0,!C)Ww(A,Q,J,8,179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000);return bJ.write(A,Q,J,K,52,8),J+8}$0.prototype.writeDoubleLE=function A(Q,J,K){return qw(this,Q,J,!0,K)};$0.prototype.writeDoubleBE=function A(Q,J,K){return qw(this,Q,J,!1,K)};$0.prototype.copy=function A(Q,J,K,C){if(!$0.isBuffer(Q))throw new TypeError("argument should be a Buffer");if(!K)K=0;if(!C&&C!==0)C=this.length;if(J>=Q.length)J=Q.length;if(!J)J=0;if(C>0&&C=this.length)throw new RangeError("Index out of range");if(C<0)throw new RangeError("sourceEnd out of bounds");if(C>this.length)C=this.length;if(Q.length-J>>0,K=K===void 0?this.length:K>>>0,!Q)Q=0;let U;if(typeof Q==="number")for(U=J;U4294967296)C=Uw(String(J));else if(typeof J==="bigint"){if(C=String(J),J>BigInt(2)**BigInt(32)||J<-(BigInt(2)**BigInt(32)))C=Uw(C);C+="n"}return K+=` It must be ${Q}. Received ${C}`,K},RangeError);function Uw(A){let Q="",J=A.length,K=A[0]==="-"?1:0;for(;J>=K+4;J-=3)Q=`_${A.slice(J-3,J)}${Q}`;return`${A.slice(0,J)}${Q}`}function mo(A,Q,J){if(fJ(Q,"offset"),A[Q]===void 0||A[Q+J]===void 0)DY(Q,A.length-(J+1))}function Ow(A,Q,J,K,C,U){if(A>J||A3)if(Q===0||Q===BigInt(0))Z=`>= 0${Y} and < 2${Y} ** ${(U+1)*8}${Y}`;else Z=`>= -(2${Y} ** ${(U+1)*8-1}${Y}) and < 2 ** ${(U+1)*8-1}${Y}`;else Z=`>= ${Q}${Y} and <= ${J}${Y}`;throw new gJ.ERR_OUT_OF_RANGE("value",Z,A)}mo(K,C,U)}function fJ(A,Q){if(typeof A!=="number")throw new gJ.ERR_INVALID_ARG_TYPE(Q,"number",A)}function DY(A,Q,J){if(Math.floor(A)!==A)throw fJ(A,J),new gJ.ERR_OUT_OF_RANGE(J||"offset","an integer",A);if(Q<0)throw new gJ.ERR_BUFFER_OUT_OF_BOUNDS;throw new gJ.ERR_OUT_OF_RANGE(J||"offset",`>= ${J?1:0} and <= ${Q}`,A)}var co=/[^+/0-9A-Za-z-_]/g;function lo(A){if(A=A.split("=")[0],A=A.trim().replace(co,""),A.length<2)return"";while(A.length%4!==0)A=A+"=";return A}function mI(A,Q){Q=Q||1/0;let J,K=A.length,C=null,U=[];for(let Y=0;Y55295&&J<57344){if(!C){if(J>56319){if((Q-=3)>-1)U.push(239,191,189);continue}else if(Y+1===K){if((Q-=3)>-1)U.push(239,191,189);continue}C=J;continue}if(J<56320){if((Q-=3)>-1)U.push(239,191,189);C=J;continue}J=(C-55296<<10|J-56320)+65536}else if(C){if((Q-=3)>-1)U.push(239,191,189)}if(C=null,J<128){if((Q-=1)<0)break;U.push(J)}else if(J<2048){if((Q-=2)<0)break;U.push(J>>6|192,J&63|128)}else if(J<65536){if((Q-=3)<0)break;U.push(J>>12|224,J>>6&63|128,J&63|128)}else if(J<1114112){if((Q-=4)<0)break;U.push(J>>18|240,J>>12&63|128,J>>6&63|128,J&63|128)}else throw new Error("Invalid code point")}return U}function no(A){let Q=[];for(let J=0;J>8,C=J%256,U.push(C),U.push(K)}return U}function Nw(A){return bI.toByteArray(lo(A))}function CX(A,Q,J,K){let C;for(C=0;C=Q.length||C>=A.length)break;Q[C+J]=A[C]}return C}function g5(A,Q){return A instanceof Q||A!=null&&A.constructor!=null&&A.constructor.name!=null&&A.constructor.name===Q.name}function nI(A){return A!==A}var oo=function(){let Q=new Array(256);for(let J=0;J<16;++J){let K=J*16;for(let C=0;C<16;++C)Q[K+C]="0123456789abcdef"[J]+"0123456789abcdef"[C]}return Q}();function x7(A){return typeof BigInt==="undefined"?io:A}function io(){throw new Error("BigInt not supported")}var An=j2(u8(),1);var Rw=j2(u8(),1),m8=()=>ao;class zw{SongBufs;audioContext;gainNode;muted;previousVolume;constructor(){this.SongBufs={},this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.muted=!1,this.previousVolume=0.28,setTimeout(()=>{let A="";document.addEventListener("theme-change",()=>{let Q=document.documentElement.dataset.theme;if(A!==Q)this.initMusic();A=Q})},2000),this.sources=[]}mainSource;editSource;mainGainNode;editGainNode;theme;async initMusic(){this.sources.forEach((Q)=>Q.stop());let A=document.documentElement.dataset.theme!==void 0?document.documentElement.dataset.theme:await Rw.default.getItem("settings_theme");if(this.theme===A)return;if(this.theme=A,console.error("initMusic()",A,document.documentElement.dataset.theme),A==="wiiu")this.setVolume(0.65),this.previousVolume=0.65,await this.loadSong("./assets/audio/ffl_app_menu.mp3","mii_creator_music"),await this.loadSong("./assets/audio/ffl_app_edit.mp3","mii_editor_music"),window.music=this;else this.setVolume(0.28),this.previousVolume=0.28,await this.loadSong("./assets/audio/miimakermusic.mp3","mii_creator_music");this.initMusicReady()}initMusicReady(){setTimeout(async()=>{if(this.audioContext.state==="suspended"){if(location.hostname==="localhost"||location.hostname==="127.0.0.1")this.playMusic()}document.onclick=()=>{document.onclick=null,this.playMusic()}},100)}started;playMusic(){if(this.mainSource)this.mainSource.stop();if(this.editSource)this.editSource.stop();if(this.playSong("mii_creator_music",0,100,!0,!0,(A,Q)=>{if(this.mainSource=A,this.started=!0,this.mainGainNode=Q,this.theme!=="wiiu")this.editSource=void 0,this.editGainNode=void 0;Q.gain.setValueAtTime(-1,this.audioContext.currentTime),Q.gain.linearRampToValueAtTime(-0.6,this.audioContext.currentTime+2)}),this.theme==="wiiu")this.playSong("mii_editor_music",0,100,!0,!0,(A,Q)=>{this.editSource=A,this.editGainNode=Q,Q.gain.setValueAtTime(-1,this.audioContext.currentTime)})}async loadSong(A,Q){let K=await(await fetch(A)).arrayBuffer(),C=await this.audioContext.decodeAudioData(K);this.SongBufs[Q]=C}sources;playSong(A,Q=null,J=null,K=!0,C=!0,U){try{let Y=this.SongBufs[A];if(!Y)return console.error(`Song "${A}" not found.`),null;let Z=this.audioContext.createBufferSource();if(Z.buffer=Y,Z.connect(this.gainNode),K===!0)Z.loop=!0;if(Q!==null)Z.loopStart=Q;if(J!==null)Z.loopEnd=J;this.sources.push(Z);let X=this.audioContext.createGain();if(Z.connect(X),X.connect(this.gainNode),U)U(Z,X);if(C)Z.start();return{source:Z,gainNode:X}}catch(Y){return console.log("OOPS",Y),null}}stopSong(){this.audioContext.suspend()}setVolume(A){if(this.muted)return;this.gainNode.gain.value=A}mute(){if(this.muted)return;this.previousVolume=this.gainNode.gain.value,this.setVolume(0),this.muted=!0}unmute(){if(this.muted===!1)return;this.muted=!1,this.setVolume(this.previousVolume)}}var ao=new zw;var Yk=j2(zO(),1),t8=()=>Zk,I2=(A)=>t8().playSound(A);class Uk{soundBufs;audioContext;gainNode;muted;previousVolume;constructor(){this.soundBufs={},this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.muted=!1,this.previousVolume=0.28,this.queue=/*@__PURE__*/new Set;let Q=document.documentElement.dataset.theme;document.addEventListener("theme-change",()=>{let J=document.documentElement.dataset.theme;if(J!==Q)if(J==="wiiu")Ck("./assets/audio/miiMakerU.zip"),this.previousVolume=0.75,this.setVolume(0.75),this.previousVolume=0.75;else Ck("./assets/audio/miiMakerSwitch.zip"),this.previousVolume=0.28,this.setVolume(0.28),this.previousVolume=0.28;Q=J})}async loadSound(A,Q){let K=await(await fetch(A)).arrayBuffer(),C=await this.audioContext.decodeAudioData(K);this.soundBufs[Q]=C}async loadSoundBuffer(A,Q){let J=await this.audioContext.decodeAudioData(A);this.soundBufs[Q]=J}queue;playSound(A){let Q=this.soundBufs[A];if(!Q){console.error(`Sound "${A}" not found.`);return}if(this.queue.has(A))return;let J=this.audioContext.createBufferSource();J.buffer=Q,J.connect(this.gainNode),J.start(),this.queue.add(A),setTimeout(()=>{this.queue.delete(A)},50)}setVolume(A){if(this.muted)return;this.gainNode.gain.value=A}mute(){if(this.muted)return;this.previousVolume=this.gainNode.gain.value,this.setVolume(0),this.muted=!0}unmute(){if(this.muted===!1)return;this.muted=!1,this.setVolume(this.previousVolume)}}var Zk=new Uk,Ck=async(A="./assets/audio/miiMakerSwitch.zip")=>{let Q=await fetch(A).then((Y)=>Y.blob()),J=await Yk.default.loadAsync(Q),K=[],C=Object.keys(J.files);for(let Y of C)K.push(J.files[Y].async("arraybuffer"));let U=await Promise.all(K);for(let Y=0;Yf1.from(Q));else return null}id(A){return this.elm.id=A,this}class(...A){for(let Q=0;Qf1.qs(A);if(typeof A==="string")return Q();return new f1(A)}static qs(A){if(document.querySelector(A))return f1.from(document.querySelector(A));return null}static qsa(A){if(document.querySelector(A))return Array.from(document.querySelectorAll(A)).map((Q)=>f1.from(Q));return null}}function f2(A,Q="hover",J="select"){return A.on("pointerenter",()=>{I2(Q)}),A.on("click",()=>{I2(J)}),A}var x3=[{callback(){},text:"Cancel"},{callback(){},text:"OK"}];function q11(A){A.qs(".modal-body").qsa("*").forEach((Q)=>Q.attr({disabled:!0,tabindex:"-1"}))}function Bk(A){A.class("closing"),q11(A),setTimeout(()=>{A.cleanup()},350)}var y0={modal:function(A,Q,J="body",...K){if(Q===void 0&&A)Q=""+A,A="Alert";let C=new f1("div").class("modal-content"),U=new f1("div").class("modal-header"),Y=new f1("div").class("modal-body");C.appendMany(U,Y);let Z=new f1("div").class("modal").append(C);if(new f1("span").text(A).appendTo(U),Q instanceof f1===!1)new f1("span").text(Q).appendTo(Y);else Q.appendTo(Y);if(K.length>0)new f1("div").class("flex-group").appendTo(Y);for(let H=0;H{let D=V.target;if(D==null)return;if(D.closest(".modal-content")&&!D.classList.contains("close-button"))return;if(N)return;I2("back"),N=!0,Z.classOn("closing"),setTimeout(()=>{if(Z.cleanup(),typeof $.callback==="function")$.callback(V)},350)};f2(new f1("button").class("close-button").appendTo(U).on("click",F),"hover","back"),Z.on("click",(V)=>{F(V)});continue}let I=f2(new f1("button").text($.text).on("click",(N)=>{Z.class("closing"),X(),setTimeout(()=>{if(Z.cleanup(),typeof $.callback==="function")$.callback(N)},350)}));if($.type&&$.type==="primary")I.class("primary");if($.type&&$.type==="danger")I.class("danger");I.appendTo(C.elm.querySelector(".flex-group"))}function X(){Z.qsa("a,button,div").forEach((H)=>H.attr({disabled:!0,tabindex:"-1"}))}Z.appendTo(J);let E;return requestAnimationFrame(()=>{let H=Z.elm.querySelectorAll('a[href], button, textarea, input[type="text"], input[type="checkbox"], input[type="radio"], select');if(E=Array.prototype.slice.call(H),E.forEach(($)=>{$.setAttribute("tabindex","0")}),E.length>0)E[0].addEventListener("keydown",($)=>{if($.key==="Tab"&&$.shiftKey)$.preventDefault(),E[E.length-1].focus()}),E[E.length-1].addEventListener("keydown",($)=>{if($.key==="Tab"&&!$.shiftKey)$.preventDefault(),E[0].focus()})}),requestAnimationFrame(()=>{Y.elm.querySelector("input")&&Y.elm.querySelector("input").focus()}),Z},alert:function(A,Q,J="body",K=!1){return new Promise((C,U)=>{let Y=J;if(K)new f1("div").class("modal-selectable").appendTo("body"),Y=".modal-selectable";this.modal(A,Q,Y,{text:"OK",callback:(Z)=>{C(!0),f1.qs(".modal-selectable")?.cleanup()}},{text:"Cancel",callback:(Z)=>{C(!1),f1.qs(".modal-selectable")?.cleanup()}})})},prompt:function(A,Q,J="body",K=!1){return new Promise((C,U)=>{var Y=this.modal(A,Q,J,{text:"Yes",type:K?"danger":"primary",callback:(Z)=>C(!0)},{text:"No",callback:(Z)=>C(!1)},{text:"Cancel",callback:(Z)=>C(!1)});Y.qs(".modal-body").classOn("flex-group")})},input:function(A,Q,J,K="body",C=!1,U=""){return new Promise((Y,Z)=>{let X=new f1("div").class("col"),E=this.modal(A,X,K,{text:"OK",type:"primary",callback:($)=>{Y(H.elm.value)}},{text:"Cancel",callback:($)=>Y(!1)});new f1("span").text(Q).appendTo(X);let H=new f1("input").attr({placeholder:J,value:U,type:C===!0?"password":"text"}).on("keyup",($)=>{if($.key==="Enter")E.class("closing"),setTimeout(()=>{E.cleanup(),Y(H.elm.value)},350)}).appendTo(X)})}};var gB=j2(u8(),1);var Zx=j2(MO(),1);class e8{constructor(A,Q,J){var K=A instanceof ArrayBuffer||typeof QA!=="undefined"&&A instanceof QA;if(!K)throw new Error("Must specify a valid ArrayBuffer or Buffer.");Q=Q||0,J=J||A.byteLength||A.length,this._view=new Uint8Array(A.buffer||A,Q,J),this.bigEndian=!1}_setBit(A,Q){if(Q)this._view[A>>3]|=1<<(A&7);else this._view[A>>3]&=~(1<<(A&7))}getBits(A,Q,J){var K=this._view.length*8-A;if(Q>K)throw new Error("Cannot get "+Q+" bit(s) from offset "+A+", "+K+" available");var C=0;for(var U=0;U>3],E=Math.min(Y,8-Z),H,$;if(this.bigEndian)H=~(255<>8-E-Z&H,C<<=E,C|=$;else H=~(255<>Z&H,C|=$<>>0}setBits(A,Q,J){var K=this._view.length*8-A;if(J>K)throw new Error("Cannot set "+J+" bit(s) from offset "+A+", "+K+" available");for(var C=0;C>3,X=Math.min(U,8-Y),E,H,$;if(this.bigEndian){E=~(-1<>J-C-X&E;var I=8-Y-X;$=~(E<>=X,$=~(E<this._length)throw new Error("Trying to read past the end of the stream");var J=this._view[A](this._index);return this._index+=Q,J}},h3=function(A,Q){return function(J){this._view[A](this._index,J),this._index+=Q}};function N11(A,Q){return qk(A,Q,!1)}function L11(A,Q){return qk(A,Q,!0)}function qk(A,Q,J){if(Q===0)return"";var K=0,C=[],U=!0,Y=!!Q;if(!Q)Q=Math.floor((A._length-A._index)/8);while(K>6|192),Q.push(K&63|128);else if(K<=65535)Q.push(K>>12|224),Q.push(K>>6&63|128),Q.push(K&63|128);else Q.push(K>>18|240),Q.push(K>>12&63|128),Q.push(K>>6&63|128),Q.push(K&63|128);return Q}class q2{constructor(A,Q,J){var K=A instanceof ArrayBuffer||typeof QA!=="undefined"&&A instanceof QA;if(!(A instanceof e8)&&!K)throw new Error("Must specify a valid BitView, ArrayBuffer or Buffer");if(K)this._view=new e8(A,Q,J);else this._view=A;this._index=0,this._startIndex=0,this._length=this._view.byteLength*8}readBits(A,Q){var J=this._view.getBits(this._index,A,Q);return this._index+=A,J}writeBits(A,Q){this._view.setBits(this._index,A,Q),this._index+=Q}readASCIIString(A){return N11(this,A)}readUTF8String(A){return L11(this,A)}writeASCIIString(A,Q){F11(this,A,Q)}writeUTF8String(A,Q){R11(this,A,Q)}readBitStream(A){var Q=new q2(this._view);return Q._startIndex=this._index,Q._index=this._index,Q.length=A,this._index+=A,Q}writeBitStream(A,Q){if(!Q)Q=A.bitsLeft;var J;while(Q>0)J=Math.min(Q,32),this.writeBits(A.readBits(J),J),Q-=J}readArrayBuffer(A){var Q=this._view.getArrayBuffer(this._index,A);return this._index+=A*8,Q}writeArrayBuffer(A,Q){this.writeBitStream(new q2(A),Q*8)}}Object.defineProperty(q2.prototype,"index",{get:function(){return this._index-this._startIndex},set:function(A){this._index=A+this._startIndex},enumerable:!0,configurable:!0});Object.defineProperty(q2.prototype,"length",{get:function(){return this._length-this._startIndex},set:function(A){this._length=A+this._startIndex},enumerable:!0,configurable:!0});Object.defineProperty(q2.prototype,"bitsLeft",{get:function(){return this._length-this._index},enumerable:!0,configurable:!0});Object.defineProperty(q2.prototype,"byteIndex",{get:function(){return Math.ceil(this._index/8)},set:function(A){this._index=A*8},enumerable:!0,configurable:!0});Object.defineProperty(q2.prototype,"buffer",{get:function(){return this._view.buffer},enumerable:!0,configurable:!1});Object.defineProperty(q2.prototype,"view",{get:function(){return this._view},enumerable:!0,configurable:!1});Object.defineProperty(q2.prototype,"bigEndian",{get:function(){return this._view.bigEndian},set:function(A){this._view.bigEndian=A},enumerable:!0,configurable:!1});q2.prototype.readBoolean=y3("getBoolean",1);q2.prototype.readInt8=y3("getInt8",8);q2.prototype.readUint8=y3("getUint8",8);q2.prototype.readInt16=y3("getInt16",16);q2.prototype.readUint16=y3("getUint16",16);q2.prototype.readInt32=y3("getInt32",32);q2.prototype.readUint32=y3("getUint32",32);q2.prototype.readFloat32=y3("getFloat32",32);q2.prototype.readFloat64=y3("getFloat64",64);q2.prototype.writeBoolean=h3("setBoolean",1);q2.prototype.writeInt8=h3("setInt8",8);q2.prototype.writeUint8=h3("setUint8",8);q2.prototype.writeInt16=h3("setInt16",16);q2.prototype.writeUint16=h3("setUint16",16);q2.prototype.writeInt32=h3("setInt32",32);q2.prototype.writeUint32=h3("setUint32",32);q2.prototype.writeFloat32=h3("setFloat32",32);q2.prototype.writeFloat64=h3("setFloat64",64);class sY extends q2{constructor(A){super(A,A.byteOffset,A.byteLength)}swapEndian(){this.bigEndian=!this.bigEndian}alignByte(){let Q=8*Math.ceil(this._index/8)-this._index;this.skipBits(Q)}bitSeek(A){this._index=A}skipBits(A){this._index+=A}skipBytes(A){let Q=A*8;this.skipBits(Q)}skipBit(){this.skipBits(1)}skipInt8(){this.skipBytes(1)}skipInt16(){this.skipBytes(2)}readBit(){return this.readBits(1)}readBytes(A){return Array(A).fill(0).map(()=>this.readUint8())}readBuffer(A){return QA.from(this.readBytes(A))}readUTF16String(A){return this.readBuffer(A).toString("utf16le").replace(/\0.*$/,"")}writeBit(A){this.writeBits(A,1)}writeBuffer(A){A.forEach((Q)=>this.writeUint8(Q))}writeUTF16String(A){let Q=QA.from(A,"utf16le"),J=QA.alloc(20);Q.copy(J),this.writeBuffer(J)}}class W0{static inRange(A,Q){return Q.includes(A)}static clamp(A,Q,J){if(J===void 0)J=Q,Q=0;return Math.min(Math.max(A,Q),J)}static range(A,Q){if(Q===void 0)Q=A,A=0;return Array.from({length:Q-A},(J,K)=>K+A)}}var b0=j2(DE(),1);var d0={renderer:{baseURL:"https://mii-renderer.nxw.pw/miis/image",useRendererServer:!1,fflResourcePath:"/FFLResHigh.dat",renderFFLMakeIcon:"https://mii-renderer.nxw.pw/miis/image.png?shaderType=miitomo&type=fflmakeicon&width=360&verifyCharInfo=0",renderHeadshotURL:"https://mii-renderer.nxw.pw/miis/image.png?shaderType=wiiu&type=face&width=260&verifyCharInfo=0",renderHeadshotURLNoParams:"https://mii-renderer.nxw.pw/miis/image.png",renderFullBodyURL:"https://mii-renderer.nxw.pw/miis/image.png?shaderType=wiiu&type=all_body_sugar&width=420&verifyCharInfo=0&scale=1",renderFullBodyAltURL:"https://mii-renderer.nxw.pw/miis/image.png?shaderType=wiiu&type=all_body_sugar&width=960&verifyCharInfo=0&scale=1",render3DHeadURL:"https://mii-renderer.nxw.pw/miis/image.glb?shaderType=wiiu&type=face&width=260&verifyCharInfo=0",renderFaceURL:"https://mii-renderer.nxw.pw/miis/image.png?scale=1&drawStageMode=mask_only&verifyCharInfo=0",hatTypeParam:"headwearIndex",hatTypeAdd:0,hatColorParam:"headwearColor",hatColorAdd:-1,allow3DMode:!0},apis:{nnidRandomURL:"https://mii-unsecure.ariankordi.net/mii_data_random",nnidFetchURL:(A)=>`https://mii-unsecure.ariankordi.net/mii_data/${A}`,pnidFetchURL:(A)=>`https://mii-unsecure.ariankordi.net/mii_data/${A}?api_id=1`,useSentry:!1,sentryURL:"ENTER_SENTRY_URL_HERE"},mii:{scalingMode:"scaleApply"},version:{string:"v0.9.3.1",name:"Patch Update",changelog:` -

v0.9.2 - QR Code and MiiC v3 Support

- -
- -
- Austin☆²¹ / Kat21 -
Let's go over the new changes!
-
-
- -
-

Please contact me (kat21) if you have any feedback, feature requests, or bug reports.

- (Some people are just not aware that kat21 made this app, not ariankordi. if you are one of those people you should know by now. Also this project is named "Mii Creator", not "Mii Creator Web," or any other "mii maker" thing. \uD83D\uDE42) -
- -

NEW: v0.9.3.1 - Extremely Small Patch Update

-
    -
  • Testing bringing back 3D mode, let's see how the server performs...
  • -
-

NEW: v0.9.3 - Very Small Patch Update

-
    -
  • Temporarily disabled 3D mode in the editor to save on bandwidth while I try and work around a solution
  • -
  • A lot of people are coming from FlipZ's tweet but that's OK, just know that I (kat21) made this website because the credit wasn't very clear
  • -
-

v0.9.2 - Small Patch Update

-
    -
  • A LOT of new faces have shown up over the past few days, if you come from X/Twitter or YouTube, say hi!
  • -
  • Some hat models have been improved! Beanie, cap and cat ears were properly fixed.
  • -
  • 2D renders now show hat textures!
  • -
  • Some broken expressions (blank face, cat face, dog face) work now
  • -
  • Bug fix Tomodachi Life QR codes not displaying the error message (they still do not work do not ask me about this)
  • -
  • Bug fix hats clipping the mask
  • -
  • More secret Special Miis added!
  • -
- -

v0.9.1 - Patch Update

- -
    -
  • Bug fix the contact menu not closing
  • -
  • Wii U theme small design tweaks to fix some stuff broken by the new UI
  • -
  • Rename "Glossy" shader to "Toon"
  • -
  • Fix a bug where the Wii U animations were sped up.
  • -
  • Secret Special Miis can be obtained through random menus (there is only 1 for now)
  • -
- -

The new changes

- -
    -
  • Update Mii Creator file format to version 3, still haven't decided the final feature to add to the miis to fill that last byte, my original idea was probably custom shirt color but that sounds a little bit boring.
  • -
      -
    • The "face paint" feature for changing color of the head (I really thought it was called face paint in Miitopia, but checking again it is called "foundation")
    • -
    -
  • I was testing default light direction previously but it looked a bit.. odd, so I got rid of it, if you want it as an option let me know
  • -
  • Add some new shader options (a few new ones based on the FFL shader)
  • -
  • Update readme and preview image
  • -
  • New way of displaying app updates (you're reading one right now)
  • -
  • Added my contact information inside the app! (please email me about problems \uD83E\uDD7A)
  • -
  • Subtle loading sound when each mii image loads in like the switch mii editor applet, just for fun
  • -
  • Functional QR code scanning
  • -
      -
    • It works with Wii U/3DS and mii creator qr codes, but unfortunately does not have fully compatibility with tomodachi life ones due to a weird bug where it isn't decrypting the extra data properly. The code to handle it is there, and once I find a fix, it will fully work with those Tomodachi Life Mii QR codes.
    • -
    • Camera scanning has a bug when you move away from the tab while scanning, don't do that
    • -
    -
  • The icons subtly change shader/body model in the background as you change the shader type or body model setting
  • -
  • Fixed most issues relating to the library duplication bugs by making it a single shutdown function
  • -
  • Display a version string in the sidebar on the main menu, (also helps to know which update you're on)
  • -
  • Miscellaneous settings related to QR code scanning
  • -
      -
    • Ability to disable closing of the QR code menu after you scan a QR code (the library will still refresh in the background if you click 'save')
    • -
    • Ability to completely disable camera for the QR scanner, so it just becomes a file input
    • -
    -
  • Fix a possible memory leak with the particle effects
  • -
  • Add Miitomo body model and animations
  • -
  • Option to color the hands like in Miitomo
  • -
  • Much more control in the custom render menu
  • -
  • Green-screen and other solid color background options for the custom render menu in Settings
  • -
  • Fix glTF textures exported using Wii U shader
  • -
  • And probably some more small changes that should improve the user experience
  • -
- -

Plans

-
    -
  • More theme options
  • -
  • Online account system for saving your mii data across devices
  • -
- -

Attributions / Acknowledgements

- -

These people helped me with the new update!

- -
-
- -
- Arian (@ariankordi) -
Wrote code for the new QR code feature, helped with Git, debugging, advice
-
-
-
- -
- Timothy (@Timimimi) -
Implemented the new .charinfo export format
-
-
-
- -
- obj (@objecty) -
Helped with designing some new icons
-
-
-
- -
- David J. (@dwyazzo90) -
Provided suggestions and ideas
-
-
-
- -
- justcamtro (@justcamtro) -
Tested the new update and gave feedback
-
-
-
- -

You can view this message again in Settings.

- `}};var c5={0:13770260,1:16739865,2:16767008,3:7918112,4:30768,5:673980,6:3975902,7:16079485,8:7547053,9:4732952,10:14737632,11:1579028},OK={0:[0.8235294117647058,0.11764705882352941,0.0784313725490196],1:[1,0.43137254901960786,0.09803921568627451],2:[1,0.8470588235294118,0.12549019607843137],3:[0.47058823529411764,0.8235294117647058,0.12549019607843137],4:[0,0.47058823529411764,0.18823529411764706],5:[0.0392156862745098,0.2823529411764706,0.7372549019607844],6:[0.23529411764705882,0.6666666666666666,0.8705882352941177],7:[0.9607843137254902,0.35294117647058826,0.49019607843137253],8:[0.45098039215686275,0.1568627450980392,0.6784313725490196],9:[0.2823529411764706,0.2196078431372549,0.09411764705882353],10:[0.8784313725490196,0.8784313725490196,0.8784313725490196],11:[0.09411764705882353,0.09411764705882353,0.0784313725490196]},r7={0:{top:"#d21e14",bottom:"#630e09"},1:{top:"#ff6e19",bottom:"#78340c"},2:{top:"#ffd820",bottom:"#78660f"},3:{top:"#78d220",bottom:"#38630f"},4:{top:"#007830",bottom:"#003817"},5:{top:"#0a48bc",bottom:"#052258"},6:{top:"#3caade",bottom:"#1c5068"},7:{top:"#f55a7d",bottom:"#732a3b"},8:{top:"#7328ad",bottom:"#361351"},9:{top:"#483818",bottom:"#221a0b"},10:{top:"#e0e0e0",bottom:"#696969"},11:{top:"#181814",bottom:"#0b0b09"}},iv={0:"#FFD3AD",1:"#FEB66B",2:"#DE7942",3:"#FFAA8C",4:"#AD5129",5:"#632C18",6:"#ffbea5",7:"#ffc58f",8:"#8c3c23",9:"#3c2d23"},pE={0:"#000000",1:"#402010",2:"#5C180A",3:"#7C3A14",4:"#787880",5:"#4E3E11",6:"#875917",7:"#D0A049"},uE={0:"#000000",1:"#717372",2:"#663C2C",3:"#686537",4:"#4B58A8",5:"#387059"},av={0:"#D04401",1:"#F30100",2:"#FD393A",3:"#F58862",4:"#1F1D1D"};var rv={0:"#000000",1:"#5d391a",2:"#a01612",3:"#2e3969",4:"#a4601e",5:"#766f67"},tv={0:{top:"#666666",bottom:"#606060"},1:{top:"#8d694a",bottom:"#e4c0a1"},2:{top:"#a01612",bottom:"#ff9d99"},3:{top:"#b5c0f0",bottom:"#b5c0f0"},4:{top:"#a4601e",bottom:"#ffe7a5"},5:{top:"#766f67",bottom:"#fdf6ee"}},n2=["#2d2828","#402010","#5c180a","#7c3a14","#787880","#4e3e10","#885818","#d0a04a","#000000","#6c7070","#663c2c","#605e30","#4654a8","#387058","#603810","#a81008","#203068","#a86000","#787068","#d85208","#f00c08","#f54848","#f09a74","#8c5040","#842626","#ff7366","#ffa6a6","#ffc0ba","#732e3b","#991f3d","#8a173e","#b53e42","#c71e56","#b05381","#c7546e","#fa7597","#fcacc9","#ffc9d8","#311c40","#37283d","#4c184d","#6f42b3","#855cb8","#c083cc","#a893c9","#c5ace6","#eebefa","#d2c5ed","#191f40","#123f66","#2a82d4","#57b4f2","#7ac5de","#89a6fa","#84bdfa","#a1e3ff","#0b2e36","#013d3b","#0d4f59","#236663","#307e8c","#4faeb0","#7ac49e","#7fd4c0","#87e5b6","#0a4a35","#437a00","#027562","#369970","#4bad1a","#92bf0a","#63c788","#9ee042","#96de7e","#bbf2aa","#99932b","#a69563","#ccc039","#ccb987","#d9cc82","#d5d96f","#d5e683","#d8fa9d","#7d4500","#e6bb7a","#fee24a","#fade82","#f7ea9c","#faf89b","#a64d1e","#ff960d","#d19b69","#ffb266","#ffc28c","#e5cfb1","#414141","#9b9b9b","#bebebe","#dcd7cd","#ffffff"],zN=["#171414","#201008","#2e0c05","#4a230c","#54545a","#271f08","#52350e","#b18028","#000000","#4c4e4e","#331e16","#3a381d","#2a3265","#274e3e","#301c08","#650a05","#101834","#764300","#544e49","#823018","#780c0c","#882028","#dc7850","#461e0a","#4f1717","#99453d","#e68585","#e6a19b","#451c23","#5c1325","#530e25","#6d2528","#771234","#6a324d","#773242","#af526a","#e38cac","#e6abbb","#190e20","#1c141f","#260c27","#43286b","#50376e","#865c8f","#76678d","#ab90cf","#d4a0e1","#b8aad5","#0d1020","#092033","#1d5b94","#3297da","#5cadc8","#6786e1","#629fe1","#80c7e6","#06171b","#011f1e","#07282d","#184745","#225862","#308b8d","#60b087","#63bfa9","#69ce9b","#05251b","#284900","#01463b","#266b4e","#2c8a00","#6e9900","#47b36f","#82ca1f","#7ac860","#9eda8c","#6b671e","#746845","#a39816","#b8a36d","#c3b565","#bfc351","#bdcf64","#bce17d","#4b2900","#cfa15a","#e5c622","#e1c35f","#ded07c","#e1df7a","#642e12","#cc780a","#bc824c","#e69240","#e6a469","#ceb696","#212121","#7c7c7c","#ababab","#c6c1b6","#d9d9d9"],ev=[[0.1764706,0.1568628,0.1568628],[0.2509804,0.1254902,0.0627451],[0.3607844,0.0941177,0.0392157],[0.4862746,0.227451,0.0784314],[0.4705883,0.4705883,0.5019608],[0.3058824,0.2431373,0.0627451],[0.5333334,0.3450981,0.0941177],[0.8156863,0.627451,0.2901961],[0,0,0],[0.4235295,0.4392157,0.4392157],[0.4,0.2352942,0.1725491],[0.3764706,0.3686275,0.1882353],[0.2745099,0.3294118,0.6588236],[0.2196079,0.4392157,0.3450981],[0.3764706,0.2196079,0.0627451],[0.6588236,0.0627451,0.0313726],[0.1254902,0.1882353,0.4078432],[0.6588236,0.3764706,0],[0.4705883,0.4392157,0.4078432],[0.8470589,0.3215687,0.0313726],[0.9411765,0.0470589,0.0313726],[0.9607844,0.282353,0.282353],[0.9411765,0.6039216,0.454902],[0.5490197,0.3137255,0.2509804],[0.5176471,0.1490197,0.1490197],[1,0.4509804,0.4],[1,0.6509804,0.6509804],[1,0.7529412,0.7294118],[0.4509804,0.1803922,0.2313726],[0.6,0.1215687,0.2392157],[0.5411765,0.0901961,0.2431373],[0.709804,0.2431373,0.2588236],[0.7803922,0.1176471,0.337255],[0.6901961,0.3254902,0.5058824],[0.7803922,0.3294118,0.4313726],[0.9803922,0.4588236,0.5921569],[0.9882353,0.6745099,0.7882353],[1,0.7882353,0.8470589],[0.1921569,0.109804,0.2509804],[0.2156863,0.1568628,0.2392157],[0.2980393,0.0941177,0.3019608],[0.4352942,0.2588236,0.7019608],[0.5215687,0.3607844,0.7215687],[0.7529412,0.5137255,0.8],[0.6588236,0.5764706,0.7882353],[0.7725491,0.6745099,0.9019608],[0.9333334,0.7450981,0.9803922],[0.8235295,0.7725491,0.9294118],[0.0980393,0.1215687,0.2509804],[0.0705883,0.2470589,0.4],[0.1647059,0.509804,0.8313726],[0.3411765,0.7058824,0.9490197],[0.4784314,0.7725491,0.8705883],[0.537255,0.6509804,0.9803922],[0.5176471,0.7411765,0.9803922],[0.6313726,0.8901961,1],[0.0431373,0.1803922,0.2117648],[0.0039216,0.2392157,0.2313726],[0.0509804,0.309804,0.3490197],[0.137255,0.4,0.3882353],[0.1882353,0.4941177,0.5490197],[0.309804,0.682353,0.6901961],[0.4784314,0.7686275,0.6196079],[0.4980393,0.8313726,0.7529412],[0.5294118,0.8980393,0.7137255],[0.0392157,0.2901961,0.2078432],[0.2627451,0.4784314,0],[0.0078432,0.4588236,0.3843138],[0.2117648,0.6,0.4392157],[0.2941177,0.6784314,0.1019608],[0.5725491,0.7490197,0.0392157],[0.3882353,0.7803922,0.5333334],[0.6196079,0.8784314,0.2588236],[0.5882353,0.8705883,0.4941177],[0.7333334,0.9490197,0.6666667],[0.6,0.5764706,0.1686275],[0.6509804,0.5843138,0.3882353],[0.8,0.7529412,0.2235295],[0.8,0.7254902,0.5294118],[0.8509804,0.8,0.509804],[0.8352942,0.8509804,0.4352942],[0.8352942,0.9019608,0.5137255],[0.8470589,0.9803922,0.6156863],[0.4901961,0.2705883,0],[0.9019608,0.7333334,0.4784314],[0.9960785,0.8862746,0.2901961],[0.9803922,0.8705883,0.509804],[0.9686275,0.9176471,0.6117648],[0.9803922,0.9725491,0.6078432],[0.6509804,0.3019608,0.1176471],[1,0.5882353,0.0509804],[0.8196079,0.6078432,0.4117648],[1,0.6980393,0.4],[1,0.7607844,0.5490197],[0.8980393,0.8117648,0.6941177],[0.254902,0.254902,0.254902],[0.6078432,0.6078432,0.6078432],[0.7450981,0.7450981,0.7450981],[0.8627451,0.8431373,0.8039216],[1,1,1]],Ax=[[0.02624122,0.02121902,0.02121902],[0.05126946,0.01444384,0.00518152],[0.1070232,0.00913407,0.00303527],[0.2015563,0.04231142,0.00699541],[0.1878208,0.1878208,0.2158605],[0.07618541,0.04817184,0.00518152],[0.2462014,0.09758739,0.00913407],[0.6307572,0.3515327,0.06847817],[0,0,0],[0.1499599,0.1620294,0.1620294],[0.1328683,0.04518623,0.02518688],[0.1169707,0.1119325,0.02955684],[0.0612461,0.08865561,0.3915726],[0.03954626,0.1620294,0.09758739],[0.1169707,0.03954626,0.00518152],[0.3915726,0.00518152,0.00242822],[0.01444384,0.02955684,0.1384317],[0.3915726,0.1169707,0],[0.1878208,0.1620294,0.1384317],[0.6866855,0.08437625,0.00242822],[0.8713672,0.00367651,0.00242822],[0.9130989,0.0648033,0.0648033],[0.8713672,0.3231433,0.1746474],[0.2622508,0.08021983,0.05126946],[0.2307401,0.01938238,0.01938238],[1,0.1714411,0.1328683],[1,0.3813261,0.3813261],[1,0.5271152,0.4910209],[0.1714411,0.0273209,0.04373505],[0.3185468,0.0137021,0.04666509],[0.2541521,0.00856813,0.04817184],[0.4620771,0.04817184,0.05448031],[0.571125,0.01298304,0.09305902],[0.4341537,0.08650047,0.2195262],[0.571125,0.08865561,0.1559265],[0.9559736,0.1778885,0.309469],[0.9734454,0.4125428,0.5840785],[1,0.5840785,0.6866855],[0.03071345,0.01161226,0.05126946],[0.03820438,0.02121902,0.04666509],[0.07227188,0.00913407,0.07421357],[0.1589609,0.05448031,0.4507858],[0.2345507,0.1070232,0.4793203],[0.5271152,0.2269659,0.6038274],[0.3915726,0.2917707,0.5840785],[0.5583405,0.4125428,0.791298],[0.8549928,0.5149179,0.9559736],[0.6444799,0.5583405,0.8468735],[0.00972123,0.0137021,0.05126946],[0.00604884,0.0497066,0.1328683],[0.02315337,0.2232281,0.658375],[0.09530749,0.4564111,0.8879234],[0.1946179,0.5583405,0.7304609],[0.2501584,0.3813261,0.9559736],[0.2307401,0.5088814,0.9559736],[0.3564002,0.7681512,1],[0.00334654,0.0273209,0.03688948],[0.00030353,0.04666509,0.04373505],[0.00402472,0.07818746,0.09989879],[0.0168074,0.1328683,0.1247718],[0.02955684,0.2086369,0.2622508],[0.07818746,0.4232678,0.4341537],[0.1946179,0.5520115,0.3419146],[0.2122308,0.658375,0.5271152],[0.2422812,0.783538,0.4677839],[0.00303527,0.06847817,0.03560133],[0.05612849,0.1946179,0],[0.00060706,0.1778885,0.1221388],[0.03688948,0.3185468,0.1620294],[0.07036012,0.4178851,0.01032982],[0.287441,0.5209957,0.00303527],[0.1247718,0.571125,0.2462014],[0.3419146,0.7454043,0.05448031],[0.3049874,0.7304609,0.2086369],[0.4969332,0.8879234,0.4019778],[0.3185468,0.2917707,0.02415765],[0.3813261,0.3005439,0.1247718],[0.6038274,0.5271152,0.04091523],[0.6038274,0.48515,0.2422812],[0.6938719,0.6038274,0.2232281],[0.6653875,0.6938719,0.1589609],[0.6653875,0.791298,0.2269659],[0.6866855,0.9559736,0.3371637],[0.2050788,0.05951127,0],[0.791298,0.4969332,0.1946179],[0.9911023,0.7605247,0.06847817],[0.9559736,0.7304609,0.2232281],[0.9301111,0.822786,0.3324517],[0.9559736,0.938686,0.3277782],[0.3813261,0.07421357,0.01298304],[1,0.3049874,0.00402472],[0.6375971,0.3277782,0.1412634],[1,0.4452013,0.1328683],[1,0.5394797,0.2622508],[0.783538,0.6239606,0.4396573],[0.05286067,0.05286067,0.05286067],[0.3277782,0.3277782,0.3277782],[0.5149179,0.5149179,0.5149179],[0.7156936,0.6795427,0.6104956],[1,1,1]],DN={0:"#ffd3ad",1:"#ffb66b",2:"#de7942",3:"#ffaa8c",4:"#ad5129",5:"#632c18",6:"#ffbea5",7:"#ffc58f",8:"#8c3c23",9:"#3c2d23"},Qx=[[1,0.8274509906768799,0.6784313917160034],[1,0.7137255072593689,0.41960790753364563],[0.8705883026123047,0.4745098948478699,0.25882360339164734],[1,0.6666666865348816,0.5490196943283081],[0.6784313917160034,0.3176470994949341,0.16078439354896545],[0.38823530077934265,0.17254909873008728,0.09411770105361938],[1,0.7450981140136719,0.64705890417099],[1,0.7725490927696228,0.5607843995094299],[0.5490196943283081,0.2352941930294037,0.137254998087883],[0.2352941930294037,0.1764705926179886,0.137254998087883]],Jx=[[1,0.6514056921005249,0.4178851544857025],[1,0.4677838385105133,0.14702732861042023],[0.7304610013961792,0.19120177626609802,0.054480310529470444],[1,0.40197786688804626,0.26225078105926514],[0.4178851544857025,0.08228272944688797,0.022173907607793808],[0.1247718408703804,0.02518688142299652,0.009134066291153431],[1,0.5149179100990295,0.3762623071670532],[1,0.5583406090736389,0.27467745542526245],[0.26225078105926514,0.04518624022603035,0.016807394102215767],[0.04518624022603035,0.026241222396492958,0.016807394102215767]];var Kx=[0,1,2,3,4,5,6,7,8,1,2,1,3,7,7,6,7,8,7,7],mE=[0,1,2,3,4,5,6,7,0,4,3,5,4,4,6,2,0,6,4,3,2,2,7,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,4,4,4,4,4,4,4,0,0,4,4,4,4,4,4,0,0,0,4,4,4,4,4,4,5,5,5,4,4,4,4,4,4,4,5,7,5,7,7,7,7,7,6,7,7,7,7,7,3,7,7,7,7,7,0,4,4,4,4],VN=[0,2,2,2,1,3,2,3,0,1,2,3,4,5,2,2,4,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,4,4,4,4,4,4,4,1,0,4,4,4,4,4,4,4,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3,3,3,3,3,3,3,3,2,2,3,3,3,3,2,2,2,2,2,1,1,1,1,1,1];var Cx=[0,1,1,1,5,1,1,4,0,5,1,1,3,5,1,2,3,4,5,4,2,2,4,4,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,0,0,5,5,5,5,5,5,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,1,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5],Yx=[0,1,2,3,4,5,0,1,5,5];var _A=(A)=>Array.from(Array(A).keys()),NK=(A)=>Math.floor(Math.random()*A);var H61=d0.renderer.baseURL,G61="https://mii-studio.akamaized.net/editor/1",Ux="webp",g3={type:"face",expression:"normal",width:96,bgColor:"FFFFFF00",clothesColor:"default",cameraXRotate:0,cameraYRotate:0,cameraZRotate:0,characterXRotate:0,characterYRotate:0,characterZRotate:0,lightXDirection:0,lightYDirection:0,lightZDirection:0,lightDirectionMode:"none",splitMode:"none",instanceCount:1,instanceRotationMode:"model"};var W61=["face","face_only","all_body"],I61=["normal","smile","anger","sorrow","surprise","blink","normal_open_mouth","smile_open_mouth","anger_open_mouth","surprise_open_mouth","sorrow_open_mouth","blink_open_mouth","wink_left","wink_right","wink_left_open_mouth","wink_right_open_mouth","like_wink_left","like_wink_right","frustrated"],q61=["default","red","orange","yellow","yellowgreen","green","blue","skyblue","pink","purple","brown","white","black"],O61=["none","zerox","flipx","camera","offset","set"],N61=["none","front","back","both"],L61=["model","camera","both"],F61=/^[0-9A-F]{8}$/;class mA{bitStream;version;allowCopying;profanityFlag;regionLock;characterSet;pageIndex;slotIndex;unknown1;deviceOrigin;systemId;normalMii;dsMii;nonUserMii;isValid;creationTime;consoleMAC;gender;birthMonth;birthDay;favoriteColor;favorite;miiName;height;build;disableSharing;faceType;fflSkinColor;trueSkinColor;get skinColor(){return this.trueSkinColor}set skinColor(A){if(A>5)this.fflSkinColor=Yx[A],this.extFacelineColor=A,this.trueSkinColor=A;else this.fflSkinColor=A,this.extFacelineColor=0,this.trueSkinColor=A}wrinklesType;makeupType;hairType;fflHairColor;trueHairColor;get hairColor(){return this.trueHairColor}set hairColor(A){if(A>7)console.log("hair color:",A,A-8),this.fflHairColor=mE[A-8],this.extHairColor=A-8,this.trueHairColor=A-8;else this.fflHairColor=A,this.extHairColor=0,this.trueHairColor=A}flipHair;eyeType;fflEyeColor;trueEyeColor;get eyeColor(){return this.trueEyeColor}set eyeColor(A){if(A>5)this.fflEyeColor=VN[A-6],this.extEyeColor=A-6,this.trueEyeColor=A;else if(this.fflEyeColor=A,A===0)this.extEyeColor=8,this.trueEyeColor=0;else this.extEyeColor=A+8,this.trueEyeColor=A}eyeScale;eyeVerticalStretch;eyeRotation;eyeSpacing;eyeYPosition;eyebrowType;fflEyebrowColor;trueEyebrowColor;get eyebrowColor(){return this.trueEyebrowColor}set eyebrowColor(A){if(A>7)this.fflEyebrowColor=mE[A-8],this.extEyebrowColor=A-8,this.trueEyebrowColor=A-8;else this.fflEyebrowColor=A,this.extEyebrowColor=0,this.trueEyebrowColor=A}eyebrowScale;eyebrowVerticalStretch;eyebrowRotation;eyebrowSpacing;eyebrowYPosition;noseType;noseScale;noseYPosition;mouthType;fflMouthColor;trueMouthColor;get mouthColor(){return this.trueMouthColor}set mouthColor(A){if(A>4){if(this.fflMouthColor=VN[A-5],this.extMouthColor=A-5,this.trueMouthColor=A,this.fflMouthColor>4)this.fflMouthColor=4}else this.fflMouthColor=A,this.extMouthColor=A+19,this.trueMouthColor=A}mouthScale;mouthHorizontalStretch;mouthYPosition;mustacheType;unknown2;beardType;fflFacialHairColor;trueFacialHairColor;get facialHairColor(){return this.trueFacialHairColor}set facialHairColor(A){if(A>7)this.fflFacialHairColor=mE[A-8],this.extBeardColor=A-8,this.trueFacialHairColor=A-8;else this.fflFacialHairColor=A,this.extBeardColor=0,this.trueFacialHairColor=A}mustacheScale;mustacheYPosition;fflGlassesType;trueGlassesType;get glassesType(){return this.trueGlassesType}set glassesType(A){if(A>8)this.fflGlassesType=Kx[A-9],this.extGlassType=A,this.trueGlassesType=A;else this.fflGlassesType=A,this.extGlassType=0,this.trueGlassesType=A}fflGlassesColor;trueGlassesColor;get glassesColor(){return this.trueGlassesColor}set glassesColor(A){if(A>5)this.fflGlassesColor=Cx[A-6],this.extGlassColor=A-6,this.trueGlassesColor=A-6;else this.fflGlassesColor=A,this.extGlassColor=0,this.trueGlassesColor=A}glassesScale;glassesYPosition;moleEnabled;moleScale;moleXPosition;moleYPosition;creatorName;checksum;extFacelineColor;extHairColor;extEyeColor;extEyebrowColor;extMouthColor;extBeardColor;extGlassColor;extGlassType;extHatType;extHatColor;extFacePaintColor;extShirtColor;initBuffer;constructor(A){if(this.isMiiCData=!1,A.byteLength===96)this.bitStream=new sY(QA.concat([A,new Uint8Array(12)]));else{let Q=108-A.byteLength,J;if(Q>0)J=QA.concat([A,new Uint8Array(Q)]);else J=A;if(this.bitStream=new sY(J),A.byteLength>96)this.isMiiCData=!0}this.initBuffer=A,this.decode()}isMiiCData;hasExtendedColors(){if(this.trueEyeColor>5||this.trueEyebrowColor>7||this.trueFacialHairColor>7||this.trueGlassesColor>5||this.trueGlassesType>8||this.trueHairColor>7||this.trueMouthColor>4||this.trueSkinColor>5)return!0;return!1}validate(){if(b0.default.ok(W0.inRange(this.bitStream.length/8,[96,104,105,106,108]),`Invalid Mii data size. Got ${this.bitStream.length/8}, expected 96 for FFSD, 104 for MiiC v1, or 106 for MiiC v2, or 108 for MiiC v3.`),b0.default.ok(this.version===0||this.version===3,`Invalid Mii version. Got ${this.version}, expected 0 or 3`),b0.default.strictEqual(typeof this.allowCopying,"boolean",`Invalid Mii allow copying. Got ${this.allowCopying}, expected true or false`),b0.default.strictEqual(typeof this.profanityFlag,"boolean",`Invalid Mii profanity flag. Got ${this.profanityFlag}, expected true or false`),b0.default.ok(W0.inRange(this.regionLock,W0.range(4)),`Invalid Mii region lock. Got ${this.regionLock}, expected 0-3`),b0.default.ok(W0.inRange(this.characterSet,W0.range(4)),`Invalid Mii region lock. Got ${this.characterSet}, expected 0-3`),b0.default.ok(W0.inRange(this.pageIndex,W0.range(10)),`Invalid Mii page index. Got ${this.pageIndex}, expected 0-9`),b0.default.ok(W0.inRange(this.slotIndex,W0.range(10)),`Invalid Mii slot index. Got ${this.slotIndex}, expected 0-9`),b0.default.ok(W0.inRange(this.deviceOrigin,W0.range(0,5)),`Invalid Mii device origin. Got ${this.deviceOrigin}, expected 1-4`),b0.default.strictEqual(this.systemId.length,8,`Invalid Mii system ID size. Got ${this.systemId.length}, system IDs must be 8 bytes long`),b0.default.strictEqual(typeof this.normalMii,"boolean",`Invalid normal Mii flag. Got ${this.normalMii}, expected true or false`),b0.default.strictEqual(typeof this.dsMii,"boolean",`Invalid DS Mii flag. Got ${this.dsMii}, expected true or false`),b0.default.strictEqual(typeof this.nonUserMii,"boolean",`Invalid non-user Mii flag. Got ${this.nonUserMii}, expected true or false`),b0.default.strictEqual(typeof this.isValid,"boolean",`Invalid Mii valid flag. Got ${this.isValid}, expected true or false`),b0.default.ok(this.creationTime<268435456,`Invalid Mii creation time. Got ${this.creationTime}, max value for 28 bit integer is 268,435,456`),b0.default.strictEqual(this.consoleMAC.length,6,`Invalid Mii console MAC address size. Got ${this.consoleMAC.length}, console MAC addresses must be 6 bytes long`),b0.default.ok(W0.inRange(this.gender,W0.range(2)),`Invalid Mii gender. Got ${this.gender}, expected 0 or 1`),b0.default.ok(W0.inRange(this.birthMonth,W0.range(13)),`Invalid Mii birth month. Got ${this.birthMonth}, expected 0-12`),b0.default.ok(W0.inRange(this.birthDay,W0.range(32)),`Invalid Mii birth day. Got ${this.birthDay}, expected 0-31`),b0.default.ok(W0.inRange(this.favoriteColor,W0.range(12)),`Invalid Mii favorite color. Got ${this.favoriteColor}, expected 0-11`),b0.default.strictEqual(typeof this.favorite,"boolean",`Invalid favorite Mii flag. Got ${this.favorite}, expected true or false`),b0.default.ok(QA.from(this.miiName,"utf16le").length<=20,`Invalid Mii name. Got ${this.miiName}, name may only be up to 10 characters`),b0.default.ok(W0.inRange(this.height,W0.range(128)),`Invalid Mii height. Got ${this.height}, expected 0-127`),b0.default.ok(W0.inRange(this.build,W0.range(128)),`Invalid Mii build. Got ${this.build}, expected 0-127`),b0.default.strictEqual(typeof this.disableSharing,"boolean",`Invalid disable sharing Mii flag. Got ${this.disableSharing}, expected true or false`),b0.default.ok(W0.inRange(this.faceType,W0.range(12)),`Invalid Mii face type. Got ${this.faceType}, expected 0-11`),b0.default.ok(W0.inRange(this.skinColor,W0.range(1000)),`Invalid Mii skin color. Got ${this.skinColor}, expected 0-10`),b0.default.ok(W0.inRange(this.extFacePaintColor,W0.range(110)),`Invalid Mii face paint color. Got ${this.skinColor}, expected 0-109`),b0.default.ok(W0.inRange(this.wrinklesType,W0.range(12)),`Invalid Mii wrinkles type. Got ${this.wrinklesType}, expected 0-11`),b0.default.ok(W0.inRange(this.makeupType,W0.range(12)),`Invalid Mii makeup type. Got ${this.makeupType}, expected 0-11`),b0.default.ok(W0.inRange(this.hairType,W0.range(132)),`Invalid Mii hair type. Got ${this.hairType}, expected 0-131`),b0.default.ok(W0.inRange(this.fflHairColor,W0.range(100)),`Invalid Mii hair color. Got ${this.fflHairColor}, expected 0-7`),b0.default.strictEqual(typeof this.flipHair,"boolean",`Invalid flip hair flag. Got ${this.flipHair}, expected true or false`),b0.default.ok(W0.inRange(this.eyeType,W0.range(60)),`Invalid Mii eye type. Got ${this.eyeType}, expected 0-59`),b0.default.ok(W0.inRange(this.fflEyeColor,W0.range(6)),`Invalid Mii eye color. Got ${this.fflEyeColor}, expected 0-5`),b0.default.ok(W0.inRange(this.eyeScale,W0.range(8)),`Invalid Mii eye scale. Got ${this.eyeScale}, expected 0-7`),b0.default.ok(W0.inRange(this.eyeVerticalStretch,W0.range(7)),`Invalid Mii eye vertical stretch. Got ${this.eyeVerticalStretch}, expected 0-6`),b0.default.ok(W0.inRange(this.eyeRotation,W0.range(8)),`Invalid Mii eye rotation. Got ${this.eyeRotation}, expected 0-7`),b0.default.ok(W0.inRange(this.eyeSpacing,W0.range(13)),`Invalid Mii eye spacing. Got ${this.eyeSpacing}, expected 0-12`),b0.default.ok(W0.inRange(this.eyeYPosition,W0.range(19)),`Invalid Mii eye Y position. Got ${this.eyeYPosition}, expected 0-18`),b0.default.ok(W0.inRange(this.eyebrowType,W0.range(24)),`Invalid Mii eyebrow type. Got ${this.eyebrowType}, expected 0-24`),b0.default.ok(W0.inRange(this.fflEyebrowColor,W0.range(8)),`Invalid Mii eyebrow color. Got ${this.fflEyebrowColor}, expected 0-7`),b0.default.ok(W0.inRange(this.eyebrowScale,W0.range(9)),`Invalid Mii eyebrow scale. Got ${this.eyebrowScale}, expected 0-8`),b0.default.ok(W0.inRange(this.eyebrowVerticalStretch,W0.range(7)),`Invalid Mii eyebrow vertical stretch. Got ${this.eyebrowVerticalStretch}, expected 0-6`),b0.default.ok(W0.inRange(this.eyebrowRotation,W0.range(12)),`Invalid Mii eyebrow rotation. Got ${this.eyebrowRotation}, expected 0-11`),b0.default.ok(W0.inRange(this.eyebrowSpacing,W0.range(13)),`Invalid Mii eyebrow spacing. Got ${this.eyebrowSpacing}, expected 0-12`),b0.default.ok(W0.inRange(this.eyebrowYPosition,W0.range(3,19)),`Invalid Mii eyebrow Y position. Got ${this.eyebrowYPosition}, expected 3-18`),b0.default.ok(W0.inRange(this.noseType,W0.range(18)),`Invalid Mii nose type. Got ${this.noseType}, expected 0-17`),b0.default.ok(W0.inRange(this.noseScale,W0.range(9)),`Invalid Mii nose scale. Got ${this.noseScale}, expected 0-8`),b0.default.ok(W0.inRange(this.noseYPosition,W0.range(19)),`Invalid Mii nose Y position. Got ${this.noseYPosition}, expected 0-18`),b0.default.ok(W0.inRange(this.mouthType,W0.range(36)),`Invalid Mii mouth type. Got ${this.mouthType}, expected 0-35`),b0.default.ok(W0.inRange(this.fflMouthColor,W0.range(5)),`Invalid Mii mouth color. Got ${this.fflMouthColor}, expected 0-4`),b0.default.ok(W0.inRange(this.mouthScale,W0.range(9)),`Invalid Mii mouth scale. Got ${this.mouthScale}, expected 0-8`),b0.default.ok(W0.inRange(this.mouthHorizontalStretch,W0.range(7)),`Invalid Mii mouth stretch. Got ${this.mouthHorizontalStretch}, expected 0-6`),b0.default.ok(W0.inRange(this.mouthYPosition,W0.range(19)),`Invalid Mii mouth Y position. Got ${this.mouthYPosition}, expected 0-18`),b0.default.ok(W0.inRange(this.mustacheType,W0.range(6)),`Invalid Mii mustache type. Got ${this.mustacheType}, expected 0-5`),b0.default.ok(W0.inRange(this.beardType,W0.range(6)),`Invalid Mii beard type. Got ${this.beardType}, expected 0-5`),b0.default.ok(W0.inRange(this.fflFacialHairColor,W0.range(8)),`Invalid Mii beard type. Got ${this.fflFacialHairColor}, expected 0-7`),b0.default.ok(W0.inRange(this.mustacheScale,W0.range(9)),`Invalid Mii mustache scale. Got ${this.mustacheScale}, expected 0-8`),b0.default.ok(W0.inRange(this.mustacheYPosition,W0.range(17)),`Invalid Mii mustache Y position. Got ${this.mustacheYPosition}, expected 0-16`),b0.default.ok(W0.inRange(this.fflGlassesType,W0.range(9)),`Invalid Mii glasses type. Got ${this.fflGlassesType}, expected 0-8`),b0.default.ok(W0.inRange(this.fflGlassesColor,W0.range(100)),`Invalid Mii glasses color. Got ${this.fflGlassesColor}, expected 0-5`),b0.default.ok(W0.inRange(this.glassesScale,W0.range(8)),`Invalid Mii glasses scale. Got ${this.glassesScale}, expected 0-7`),b0.default.ok(W0.inRange(this.glassesYPosition,W0.range(21)),`Invalid Mii glasses Y position. Got ${this.glassesYPosition}, expected 0-20`),b0.default.strictEqual(typeof this.moleEnabled,"boolean",`Invalid mole enabled flag. Got ${this.moleEnabled}, expected true or false`),b0.default.ok(W0.inRange(this.moleScale,W0.range(9)),`Invalid Mii mole scale. Got ${this.moleScale}, expected 0-8`),b0.default.ok(W0.inRange(this.moleXPosition,W0.range(17)),`Invalid Mii mole X position. Got ${this.moleXPosition}, expected 0-16`),b0.default.ok(W0.inRange(this.moleYPosition,W0.range(31)),`Invalid Mii mole Y position. Got ${this.moleYPosition}, expected 0-30`),this.nonUserMii&&(this.creationTime!==0||this.isValid||this.dsMii||this.normalMii))b0.default.fail("Non-user Mii's must have all other Mii ID bits set to 0");if(!this.normalMii&&!this.disableSharing)b0.default.fail("Special Miis must have sharing disabled")}decode(){if(this.version=this.bitStream.readUint8(),this.allowCopying=this.bitStream.readBoolean(),this.profanityFlag=this.bitStream.readBoolean(),this.regionLock=this.bitStream.readBits(2),this.characterSet=this.bitStream.readBits(2),this.bitStream.alignByte(),this.pageIndex=this.bitStream.readBits(4),this.slotIndex=this.bitStream.readBits(4),this.unknown1=this.bitStream.readBits(4),this.deviceOrigin=this.bitStream.readBits(3),this.bitStream.alignByte(),this.systemId=this.bitStream.readBuffer(8),this.bitStream.swapEndian(),this.normalMii=this.bitStream.readBoolean(),this.dsMii=this.bitStream.readBoolean(),this.nonUserMii=this.bitStream.readBoolean(),this.isValid=this.bitStream.readBoolean(),this.creationTime=this.bitStream.readBits(28),this.bitStream.swapEndian(),this.consoleMAC=this.bitStream.readBuffer(6),this.bitStream.skipInt16(),this.gender=this.bitStream.readBit(),this.birthMonth=this.bitStream.readBits(4),this.birthDay=this.bitStream.readBits(5),this.favoriteColor=this.bitStream.readBits(4),this.favorite=this.bitStream.readBoolean(),this.bitStream.alignByte(),this.miiName=this.bitStream.readUTF16String(20),this.height=this.bitStream.readUint8(),this.build=this.bitStream.readUint8(),this.disableSharing=this.bitStream.readBoolean(),this.faceType=this.bitStream.readBits(4),this.skinColor=this.bitStream.readBits(3),this.wrinklesType=this.bitStream.readBits(4),this.makeupType=this.bitStream.readBits(4),this.hairType=this.bitStream.readUint8(),this.hairColor=this.bitStream.readBits(3),this.flipHair=this.bitStream.readBoolean(),this.bitStream.alignByte(),this.eyeType=this.bitStream.readBits(6),this.eyeColor=this.bitStream.readBits(3),this.eyeScale=this.bitStream.readBits(4),this.eyeVerticalStretch=this.bitStream.readBits(3),this.eyeRotation=this.bitStream.readBits(5),this.eyeSpacing=this.bitStream.readBits(4),this.eyeYPosition=this.bitStream.readBits(5),this.bitStream.alignByte(),this.eyebrowType=this.bitStream.readBits(5),this.eyebrowColor=this.bitStream.readBits(3),this.eyebrowScale=this.bitStream.readBits(4),this.eyebrowVerticalStretch=this.bitStream.readBits(3),this.bitStream.skipBit(),this.eyebrowRotation=this.bitStream.readBits(4),this.bitStream.skipBit(),this.eyebrowSpacing=this.bitStream.readBits(4),this.eyebrowYPosition=this.bitStream.readBits(5),this.bitStream.alignByte(),this.noseType=this.bitStream.readBits(5),this.noseScale=this.bitStream.readBits(4),this.noseYPosition=this.bitStream.readBits(5),this.bitStream.alignByte(),this.mouthType=this.bitStream.readBits(6),this.mouthColor=this.bitStream.readBits(3),this.mouthScale=this.bitStream.readBits(4),this.mouthHorizontalStretch=this.bitStream.readBits(3),this.mouthYPosition=this.bitStream.readBits(5),this.mustacheType=this.bitStream.readBits(3),this.unknown2=this.bitStream.readUint8(),this.beardType=this.bitStream.readBits(3),this.facialHairColor=this.bitStream.readBits(3),this.mustacheScale=this.bitStream.readBits(4),this.mustacheYPosition=this.bitStream.readBits(5),this.bitStream.alignByte(),this.glassesType=this.bitStream.readBits(4),this.glassesColor=this.bitStream.readBits(3),this.glassesScale=this.bitStream.readBits(4),this.glassesYPosition=this.bitStream.readBits(5),this.moleEnabled=this.bitStream.readBoolean(),this.moleScale=this.bitStream.readBits(4),this.moleXPosition=this.bitStream.readBits(5),this.moleYPosition=this.bitStream.readBits(5),this.bitStream.alignByte(),this.creatorName=this.bitStream.readUTF16String(20),this.bitStream.skipInt16(),this.bitStream.swapEndian(),this.checksum=this.bitStream.readUint16(),this.bitStream.swapEndian(),this.bitStream.length/8>96)this.extFacelineColor=this.bitStream.readUint8(),this.extHairColor=this.bitStream.readUint8(),this.extEyeColor=this.bitStream.readUint8(),this.extEyebrowColor=this.bitStream.readUint8(),this.extMouthColor=this.bitStream.readUint8(),this.extBeardColor=this.bitStream.readUint8(),this.extGlassColor=this.bitStream.readUint8(),this.extGlassType=this.bitStream.readUint8();if(this.bitStream.length/8>104)this.extHatType=this.bitStream.readUint8();if(this.bitStream.length/8>105)this.extHatColor=this.bitStream.readUint8();if(this.bitStream.length/8>106)this.extFacePaintColor=this.bitStream.readUint8();else this.extFacePaintColor=0;if(this.bitStream.length/8>107)this.extShirtColor=this.bitStream.readUint8();else this.extShirtColor=0;if(this.extFacelineColor)this.trueSkinColor=this.extFacelineColor;if(this.extHairColor)this.trueHairColor=this.extHairColor;if(this.extEyeColor)this.trueEyeColor=this.extEyeColor;if(this.extEyebrowColor)this.trueEyebrowColor=this.extEyebrowColor;if(this.extMouthColor)this.trueMouthColor=this.extMouthColor;if(this.extBeardColor)this.trueFacialHairColor=this.extBeardColor;if(this.extGlassColor)this.trueGlassesColor=this.extGlassColor;if(this.extGlassType)this.trueGlassesType=this.extGlassType;if(this.validate(),this.checksum!==this.calculateCRC())throw new Error("Invalid Mii checksum")}encode(){return this.validate(),this.bitStream.bitSeek(0),this.bitStream.writeUint8(this.version),this.bitStream.writeBoolean(this.allowCopying),this.bitStream.writeBoolean(this.profanityFlag),this.bitStream.writeBits(this.regionLock,2),this.bitStream.writeBits(this.characterSet,2),this.bitStream.alignByte(),this.bitStream.writeBits(this.pageIndex,4),this.bitStream.writeBits(this.slotIndex,4),this.bitStream.writeBits(this.unknown1,4),this.bitStream.writeBits(this.deviceOrigin,3),this.bitStream.alignByte(),this.bitStream.writeBuffer(this.systemId),this.bitStream.swapEndian(),this.bitStream.writeBoolean(this.normalMii),this.bitStream.writeBoolean(this.dsMii),this.bitStream.writeBoolean(this.nonUserMii),this.bitStream.writeBoolean(this.isValid),this.bitStream.writeBits(this.creationTime,28),this.bitStream.swapEndian(),this.bitStream.writeBuffer(this.consoleMAC),this.bitStream.writeUint16(0),this.bitStream.writeBit(this.gender),this.bitStream.writeBits(this.birthMonth,4),this.bitStream.writeBits(this.birthDay,5),this.bitStream.writeBits(this.favoriteColor,4),this.bitStream.writeBoolean(this.favorite),this.bitStream.alignByte(),this.bitStream.writeUTF16String(this.miiName),this.bitStream.writeUint8(this.height),this.bitStream.writeUint8(this.build),this.bitStream.writeBoolean(this.disableSharing),this.bitStream.writeBits(this.faceType,4),this.bitStream.writeBits(this.fflSkinColor,3),this.bitStream.writeBits(this.wrinklesType,4),this.bitStream.writeBits(this.makeupType,4),this.bitStream.writeUint8(this.hairType),this.bitStream.writeBits(this.fflHairColor,3),this.bitStream.writeBoolean(this.flipHair),this.bitStream.alignByte(),this.bitStream.writeBits(this.eyeType,6),this.bitStream.writeBits(this.fflEyeColor,3),this.bitStream.writeBits(this.eyeScale,4),this.bitStream.writeBits(this.eyeVerticalStretch,3),this.bitStream.writeBits(this.eyeRotation,5),this.bitStream.writeBits(this.eyeSpacing,4),this.bitStream.writeBits(this.eyeYPosition,5),this.bitStream.alignByte(),this.bitStream.writeBits(this.eyebrowType,5),this.bitStream.writeBits(this.fflEyebrowColor,3),this.bitStream.writeBits(this.eyebrowScale,4),this.bitStream.writeBits(this.eyebrowVerticalStretch,3),this.bitStream.skipBit(),this.bitStream.writeBits(this.eyebrowRotation,4),this.bitStream.skipBit(),this.bitStream.writeBits(this.eyebrowSpacing,4),this.bitStream.writeBits(this.eyebrowYPosition,5),this.bitStream.alignByte(),this.bitStream.writeBits(this.noseType,5),this.bitStream.writeBits(this.noseScale,4),this.bitStream.writeBits(this.noseYPosition,5),this.bitStream.alignByte(),this.bitStream.writeBits(this.mouthType,6),this.bitStream.writeBits(this.fflMouthColor,3),this.bitStream.writeBits(this.mouthScale,4),this.bitStream.writeBits(this.mouthHorizontalStretch,3),this.bitStream.writeBits(this.mouthYPosition,5),this.bitStream.writeBits(this.mustacheType,3),this.bitStream.writeUint8(this.unknown2),this.bitStream.writeBits(this.beardType,3),this.bitStream.writeBits(this.fflFacialHairColor,3),this.bitStream.writeBits(this.mustacheScale,4),this.bitStream.writeBits(this.mustacheYPosition,5),this.bitStream.alignByte(),this.bitStream.writeBits(this.fflGlassesType,4),this.bitStream.writeBits(this.fflGlassesColor,3),this.bitStream.writeBits(this.glassesScale,4),this.bitStream.writeBits(this.glassesYPosition,5),this.bitStream.writeBoolean(this.moleEnabled),this.bitStream.writeBits(this.moleScale,4),this.bitStream.writeBits(this.moleXPosition,5),this.bitStream.writeBits(this.moleYPosition,5),this.bitStream.alignByte(),this.bitStream.writeUTF16String(this.creatorName),this.bitStream.writeUint16(0),this.bitStream.swapEndian(),this.bitStream.writeUint16(this.calculateCRC()),this.bitStream.swapEndian(),this.bitStream.writeUint8(this.extFacelineColor),this.bitStream.writeUint8(this.extHairColor),this.bitStream.writeUint8(this.extEyeColor),this.bitStream.writeUint8(this.extEyebrowColor),this.bitStream.writeUint8(this.extMouthColor),this.bitStream.writeUint8(this.extBeardColor),this.bitStream.writeUint8(this.extGlassColor),this.bitStream.writeUint8(this.extGlassType),this.bitStream.writeUint8(this.extHatType),this.bitStream.writeUint8(this.extHatColor),this.bitStream.writeUint8(this.extFacePaintColor),this.bitStream.writeUint8(this.extShirtColor),QA.from(this.bitStream.view._view)}encodeFFSD(){return this.validate(),this.bitStream.bitSeek(0),this.bitStream.writeUint8(this.version),this.bitStream.writeBoolean(this.allowCopying),this.bitStream.writeBoolean(this.profanityFlag),this.bitStream.writeBits(this.regionLock,2),this.bitStream.writeBits(this.characterSet,2),this.bitStream.alignByte(),this.bitStream.writeBits(this.pageIndex,4),this.bitStream.writeBits(this.slotIndex,4),this.bitStream.writeBits(this.unknown1,4),this.bitStream.writeBits(this.deviceOrigin,3),this.bitStream.alignByte(),this.bitStream.writeBuffer(this.systemId),this.bitStream.swapEndian(),this.bitStream.writeBoolean(this.normalMii),this.bitStream.writeBoolean(this.dsMii),this.bitStream.writeBoolean(this.nonUserMii),this.bitStream.writeBoolean(this.isValid),this.bitStream.writeBits(this.creationTime,28),this.bitStream.swapEndian(),this.bitStream.writeBuffer(this.consoleMAC),this.bitStream.writeUint16(0),this.bitStream.writeBit(this.gender),this.bitStream.writeBits(this.birthMonth,4),this.bitStream.writeBits(this.birthDay,5),this.bitStream.writeBits(this.favoriteColor,4),this.bitStream.writeBoolean(this.favorite),this.bitStream.alignByte(),this.bitStream.writeUTF16String(this.miiName),this.bitStream.writeUint8(this.height),this.bitStream.writeUint8(this.build),this.bitStream.writeBoolean(this.disableSharing),this.bitStream.writeBits(this.faceType,4),this.bitStream.writeBits(this.fflSkinColor,3),this.bitStream.writeBits(this.wrinklesType,4),this.bitStream.writeBits(this.makeupType,4),this.bitStream.writeUint8(this.hairType),this.bitStream.writeBits(this.fflHairColor,3),this.bitStream.writeBoolean(this.flipHair),this.bitStream.alignByte(),this.bitStream.writeBits(this.eyeType,6),this.bitStream.writeBits(this.fflEyeColor,3),this.bitStream.writeBits(this.eyeScale,4),this.bitStream.writeBits(this.eyeVerticalStretch,3),this.bitStream.writeBits(this.eyeRotation,5),this.bitStream.writeBits(this.eyeSpacing,4),this.bitStream.writeBits(this.eyeYPosition,5),this.bitStream.alignByte(),this.bitStream.writeBits(this.eyebrowType,5),this.bitStream.writeBits(this.fflEyebrowColor,3),this.bitStream.writeBits(this.eyebrowScale,4),this.bitStream.writeBits(this.eyebrowVerticalStretch,3),this.bitStream.skipBit(),this.bitStream.writeBits(this.eyebrowRotation,4),this.bitStream.skipBit(),this.bitStream.writeBits(this.eyebrowSpacing,4),this.bitStream.writeBits(this.eyebrowYPosition,5),this.bitStream.alignByte(),this.bitStream.writeBits(this.noseType,5),this.bitStream.writeBits(this.noseScale,4),this.bitStream.writeBits(this.noseYPosition,5),this.bitStream.alignByte(),this.bitStream.writeBits(this.mouthType,6),this.bitStream.writeBits(this.fflMouthColor,3),this.bitStream.writeBits(this.mouthScale,4),this.bitStream.writeBits(this.mouthHorizontalStretch,3),this.bitStream.writeBits(this.mouthYPosition,5),this.bitStream.writeBits(this.mustacheType,3),this.bitStream.writeUint8(this.unknown2),this.bitStream.writeBits(this.beardType,3),this.bitStream.writeBits(this.fflFacialHairColor,3),this.bitStream.writeBits(this.mustacheScale,4),this.bitStream.writeBits(this.mustacheYPosition,5),this.bitStream.alignByte(),this.bitStream.writeBits(this.glassesType,4),this.bitStream.writeBits(this.fflGlassesColor,3),this.bitStream.writeBits(this.glassesScale,4),this.bitStream.writeBits(this.glassesYPosition,5),this.bitStream.writeBoolean(this.moleEnabled),this.bitStream.writeBits(this.moleScale,4),this.bitStream.writeBits(this.moleXPosition,5),this.bitStream.writeBits(this.moleYPosition,5),this.bitStream.alignByte(),this.bitStream.writeUTF16String(this.creatorName),this.bitStream.writeUint16(0),this.bitStream.swapEndian(),this.bitStream.writeUint16(this.calculateCRC()),this.bitStream.swapEndian(),QA.from(this.bitStream.view._view).slice(0,96)}calculateCRC(){let Q=this.bitStream.view._view.subarray(0,94),J=0;for(let K of Q)for(let C=7;C>=0;C--){let U=(J&32768)!=0;J=(J<<1|K>>C&1)^(U?4129:0)}for(let K=16;K>0;K--){let C=(J&32768)!=0;J=J<<1^(C?4129:0)}return J&65535}encodeStudio(){this.validate();let A=QA.alloc(47),Q=256,J=1;function K(C){let U=(7+(C^Q))%256;Q=U,A.writeUInt8(U,J),J++}if(K(this.trueFacialHairColor),K(this.beardType),K(this.build),K(this.eyeVerticalStretch),this.trueEyeColor>5)K(this.extEyeColor);else K(this.fflEyeColor+8);if(K(this.eyeRotation),K(this.eyeScale),K(this.eyeType),K(this.eyeSpacing),K(this.eyeYPosition),K(this.eyebrowVerticalStretch),K(this.trueEyebrowColor),K(this.eyebrowRotation),K(this.eyebrowScale),K(this.eyebrowType),K(this.eyebrowSpacing),K(this.eyebrowYPosition),this.extFacePaintColor!==0)K(this.extFacePaintColor+9);else K(this.trueSkinColor);if(K(this.makeupType),K(this.faceType),K(this.wrinklesType),K(this.favoriteColor),K(this.gender),this.extGlassColor>0)K(this.trueGlassesColor);else if(this.fflGlassesColor===0)K(8);else K(this.fflGlassesColor+13);if(K(this.glassesScale),K(this.trueGlassesType),K(this.glassesYPosition),K(this.trueHairColor),K(this.flipHair?1:0),K(this.hairType),K(this.height),K(this.moleScale),K(this.moleEnabled?1:0),K(this.moleXPosition),K(this.moleYPosition),K(this.mouthHorizontalStretch),this.trueMouthColor>5)K(this.extMouthColor);else K(this.fflMouthColor+19);return K(this.mouthScale),K(this.mouthType),K(this.mouthYPosition),K(this.mustacheScale),K(this.mustacheType),K(this.mustacheYPosition),K(this.noseScale),K(this.noseType),K(this.noseYPosition),A}encodeCharInfoSwitch(){this.validate(),this.bitStream.bitSeek(0);for(let A=0;A<16;A++){let Q=NK(255);if(A==8)Q&=63,Q|=128;this.bitStream.writeUint8(Q)}if(this.bitStream.writeUTF16String(this.miiName),this.bitStream.writeUint8(0),this.bitStream.writeUint8(this.characterSet),this.bitStream.writeUint8(0),this.bitStream.writeUint8(this.favoriteColor),this.bitStream.writeUint8(this.gender),this.bitStream.writeUint8(this.height),this.bitStream.writeUint8(this.build),this.bitStream.writeUint8(!this.normalMii),this.bitStream.writeUint8(this.regionLock),this.bitStream.writeUint8(this.faceType),this.bitStream.writeUint8(this.trueSkinColor),this.bitStream.writeUint8(this.wrinklesType),this.bitStream.writeUint8(this.makeupType),this.bitStream.writeUint8(this.hairType),this.trueHairColor==0)this.bitStream.writeUint8(8);else this.bitStream.writeUint8(this.trueHairColor);if(this.bitStream.writeUint8(this.flipHair),this.bitStream.writeUint8(this.eyeType),this.trueEyeColor>5)this.bitStream.writeUint8(this.extEyeColor);else this.bitStream.writeUint8(this.fflEyeColor+8);if(this.bitStream.writeUint8(this.eyeScale),this.bitStream.writeUint8(this.eyeVerticalStretch),this.bitStream.writeUint8(this.eyeRotation),this.bitStream.writeUint8(this.eyeSpacing),this.bitStream.writeUint8(this.eyeYPosition),this.bitStream.writeUint8(this.eyebrowType),this.trueEyebrowColor==0)this.bitStream.writeUint8(8);else this.bitStream.writeUint8(this.trueEyebrowColor);if(this.bitStream.writeUint8(this.eyebrowScale),this.bitStream.writeUint8(this.eyebrowVerticalStretch),this.bitStream.writeUint8(this.eyebrowRotation),this.bitStream.writeUint8(this.eyebrowSpacing),this.bitStream.writeUint8(this.eyebrowYPosition),this.bitStream.writeUint8(this.noseType),this.bitStream.writeUint8(this.noseScale),this.bitStream.writeUint8(this.noseYPosition),this.bitStream.writeUint8(this.mouthType),this.trueMouthColor>5)this.bitStream.writeUint8(this.extMouthColor);else this.bitStream.writeUint8(this.fflMouthColor+19);if(this.bitStream.writeUint8(this.mouthScale),this.bitStream.writeUint8(this.mouthHorizontalStretch),this.bitStream.writeUint8(this.mouthYPosition),this.bitStream.writeUint8(this.trueFacialHairColor),this.bitStream.writeUint8(this.beardType),this.bitStream.writeUint8(this.mustacheType),this.bitStream.writeUint8(this.mustacheScale),this.bitStream.writeUint8(this.mustacheYPosition),this.bitStream.writeUint8(this.trueGlassesType),this.extGlassColor>0)this.bitStream.writeUint8(this.trueGlassesColor);else if(this.fflGlassesColor===0)this.bitStream.writeUint8(8);else this.bitStream.writeUint8(this.fflGlassesColor+13);return this.bitStream.writeUint8(this.glassesScale),this.bitStream.writeUint8(this.glassesYPosition),this.bitStream.writeUint8(this.moleEnabled),this.bitStream.writeUint8(this.moleScale),this.bitStream.writeUint8(this.moleXPosition),this.bitStream.writeUint8(this.moleYPosition),this.bitStream.writeUint8(0),QA.from(this.bitStream.view._view).slice(0,88)}studioUrl(A=g3){let Q={...g3,...A,data:this.encodeStudio().toString("hex"),shaderType:"default"},J="png";if(Q.ext)J=Q.ext,delete Q.ext;Q.type=W61.includes(Q.type)?Q.type:g3.type,Q.expression=I61.includes(Q.expression)?Q.expression:g3.expression,Q.width=W0.clamp(Q.width,512),Q.bgColor=F61.test(Q.bgColor)?Q.bgColor:g3.bgColor,Q.clothesColor=q61.includes(Q.clothesColor)?Q.clothesColor:g3.clothesColor,Q.cameraXRotate=W0.clamp(Q.cameraXRotate,359),Q.cameraYRotate=W0.clamp(Q.cameraYRotate,359),Q.cameraZRotate=W0.clamp(Q.cameraZRotate,359),Q.characterXRotate=W0.clamp(Q.characterXRotate,359),Q.characterYRotate=W0.clamp(Q.characterYRotate,359),Q.characterZRotate=W0.clamp(Q.characterZRotate,359),Q.lightXDirection=W0.clamp(Q.lightXDirection,359),Q.lightYDirection=W0.clamp(Q.lightYDirection,359),Q.lightZDirection=W0.clamp(Q.lightZDirection,359),Q.lightDirectionMode=O61.includes(Q.lightDirectionMode)?Q.lightDirectionMode:g3.lightDirectionMode,Q.splitMode=N61.includes(Q.splitMode)?Q.splitMode:g3.splitMode,Q.instanceCount=W0.clamp(Q.instanceCount,1,16),Q.instanceRotationMode=L61.includes(Q.instanceRotationMode)?Q.instanceRotationMode:g3.instanceRotationMode;let K=new URLSearchParams(Object.fromEntries(Object.entries(Q).map(([C,U])=>[C,U.toString()])));if(Q.lightDirectionMode==="none")K.delete("lightDirectionMode"),K.delete("lightXDirection"),K.delete("lightYDirection"),K.delete("lightZDirection");if(Q.splitMode==="none")K.delete("splitMode");return`${H61}.${J}?${K.toString()}`}studioAssetUrlBody(){return this.studioAssetUrl(`body/${this.gender}/${this.favoriteColor}`)}studioAssetUrlHead(){return this.studioAssetUrl(`face/${this.faceType}/${this.wrinklesType}/${this.makeupType}/${this.skinColor}`)}studioAssetUrlFace(){return this.studioAssetUrlHead()}studioAssetUrlEye(){return this.studioAssetUrl(`eye/${this.eyeType}/${this.eyeColor+8}`)}studioAssetUrlEyebrow(){let A=this.eyebrowColor;if(this.eyebrowColor===0)A=8;return this.studioAssetUrl(`eyebrow/${this.eyebrowType}/${A}`)}studioAssetUrlNose(){return this.studioAssetUrl(`nose/${this.noseType}/${this.skinColor}`)}studioAssetUrlMouth(){let A=0;if(this.mouthColor<4)A=this.mouthColor+19;return this.studioAssetUrl(`mouth/${this.mouthType}/${A}`)}studioAssetUrlHair(){let A,Q=this.hairColor;if(this.hairColor==0)Q=8;if(this.hairType===34||this.hairType===57)A=`hair/${this.hairType}/${this.faceType}/${this.favoriteColor}`;else A=`${this.flipHair?"hairflip":"hair"}/${this.hairType}/${this.faceType}/${Q}`;return this.studioAssetUrl(A)}studioAssetUrlBeard(){let A=this.facialHairColor;if(this.facialHairColor===0)A=8;return this.studioAssetUrl(`beard/${this.beardType}/${this.faceType}/${A}`)}studioAssetUrlMustache(){let A=this.facialHairColor;if(this.facialHairColor===0)A=8;return this.studioAssetUrl(`mustache/${this.mustacheType}/${A}`)}studioAssetUrlGlasses(){let A=0;if(this.glassesColor==0)A=8;else if(this.glassesColor<6)A=this.glassesColor+13;return this.studioAssetUrl(`glass/${this.glassesType}/${A}`)}studioAssetUrlMole(){return this.studioAssetUrl(`mole/${this.moleEnabled?1:0}`)}studioAssetUrl(A){this.validate();let Q=Zx.default(A),J=Q[0],K=Q[1],C=Q[2],U=Q.substring(3,12);return`${G61}/${Ux}/1024/${J}/${K}/${C}/${U}.${Ux}`}}var kc=j2(Xx(),1);var FK=[{className:"Gen1Wii",technicalName:"RFLCharData/RFLStoreData (Wii)",sizes:[74,76],toVer3Function:"convertWiiFieldsToVer3",toVer4Function:"convertVer3FieldsToVer4"},{className:"Gen3Switch",technicalName:"nn::mii::StoreData/nn::mii::CoreData (Switch)",sizes:[68,48],version:4,toVer3Function:"convertVer4FieldsToVer3",preConvertFromFunction:"correctFromVer4CoreDataFields"},{className:"Gen3Switchgame",technicalName:"nn::mii::CharInfo (Switch)",sizes:[88],version:4,encodeFunction:"encodeSwitchCharInfo",toVer3Function:"convertVer4FieldsToVer3"},{className:"Gen2Wiiu3dsMiitomo",sizes:[96,92,72],technicalName:"CFL/FFL/AFL/Ver3 (3DS/Wii U) StoreData",version:3,encodeFunction:"encodeVer3StoreData",toVer4Function:"convertVer3FieldsToVer4",postConvertToFunction:"forceEnableCopyingIfUndefined"},{className:"Gen2Wiiu3dsMiitomo",sizes:[104,106,108],technicalName:"Ver3StoreData + NfpStoreDataExtention (amiibo Data)",version:3,parseExtensionFunction:"parseNfpStoreDataExtention",toVer4Function:"useNfpStoreDataExtentionFieldsForVer4"},{className:"Gen2Wiiu3dsMiitomo",sizes:[336],technicalName:"CFLiMiiDataPacket + Tomodachi Life 3DS QR Data",version:3,parseExtensionFunction:"parseTomodachiLifeQRCodeData",toVer4Function:"applyHairDyeAsVer4HairColor"},{className:"Gen3Studio",sizes:[46,47],technicalName:"Mii Studio Data",version:4,encodeFunction:"encodeKaitaiStructToUint8Array",toVer3Function:"convertVer4FieldsToVer3",preConvertFromFunction:"gen3studioDefineFacialHairFromBeardFields",postConvertToFunction:"gen3studioDefineBeardFromFacialHairFields"}];var d2={},LK=(A)=>A===0?8:A,$x=(A)=>A+8,Hx=(A)=>{return[8,14,15,16,17,18,0][A]},Gx=(A)=>A+19;d2.convertVer3FieldsToVer4=(A)=>{Object.defineProperty(A,"facialHairColor",{value:LK(A.facialHairColor),configurable:!0}),Object.defineProperty(A,"eyeColor",{value:$x(A.eyeColor)}),Object.defineProperty(A,"eyebrowColor",{value:LK(A.eyebrowColor),configurable:!0}),Object.defineProperty(A,"glassesColor",{value:Hx(A.glassesColor)}),Object.defineProperty(A,"hairColor",{value:LK(A.hairColor),configurable:!0}),Object.defineProperty(A,"mouthColor",{value:Gx(A.mouthColor)})};var R61=[0,1,2,3,4,5,6,7,8,1,2,1,3,7,7,6,7,8,7,7],MN=[0,1,2,3,4,5,6,7,0,4,3,5,4,4,6,2,0,6,4,3,2,2,7,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,4,4,4,4,4,4,4,0,0,4,4,4,4,4,4,0,0,0,4,4,4,4,4,4,5,5,5,4,4,4,4,4,4,4,5,7,5,7,7,7,7,7,6,7,7,7,7,7,3,7,7,7,7,7,0,4,4,4,4],z61=[0,2,2,2,1,3,2,3,0,1,2,3,4,5,2,2,4,2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,4,4,4,4,4,4,4,1,0,4,4,4,4,4,4,4,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,3,3,3,3,3,3,3,3,2,2,3,3,3,3,2,2,2,2,2,1,1,1,1,1,1],D61=[4,4,4,4,4,4,4,3,4,4,4,4,4,4,4,1,4,4,4,0,1,2,3,4,4,2,3,3,4,4,4,4,1,4,4,2,3,3,4,4,4,4,4,4,4,3,3,3,4,4,4,3,3,3,3,3,4,4,4,4,4,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,3,3,3,3,3,3,4,3,3,3,3,3,4,0,3,3,3,3,4,3,3,3,3],V61=[0,1,1,1,5,1,1,4,0,5,1,1,3,5,1,2,3,4,5,4,2,2,4,4,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,0,0,5,5,5,5,5,5,0,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,1,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5],M61=[0,1,2,3,4,5,0,1,5,5];d2.convertVer4FieldsToVer3=(A)=>{A.faceColor=M61[A.faceColor],A.hairColor=MN[A.hairColor],A.eyeColor=z61[A.eyeColor],A.eyebrowColor=MN[A.eyebrowColor],A.mouthColor=D61[A.mouthColor],A.facialHairColor=MN[A.facialHairColor],A.glassesColor=V61[A.glassesColor],A.glassesType=R61[A.glassesType]};d2.parseNfpStoreDataExtention=(A,Q)=>{let J=96,K=-1;if(A.length>104)K=0;if(Q.extFacelineColor=A[J++],Q.extHairColor=A[J++],Q.extEyeColor=A[J++],Q.extEyebrowColor=A[J++],Q.extMouthColor=A[J++],Q.extBeardColor=A[J++],Q.extGlassColor=A[J++],Q.extGlassType=A[J++],Q.extFacelineColor===K)Q.extFacelineColor=Q.faceColor;if(Q.extHairColor===K)Q.extHairColor=LK(Q.hairColor);if(Q.extEyeColor===K)Q.extEyeColor=$x(Q.eyeColor);if(Q.extEyebrowColor===K)Q.extEyebrowColor=LK(Q.eyebrowColor);if(Q.extMouthColor===K)Q.extMouthColor=Gx(Q.mouthColor);if(Q.extBeardColor===K)Q.extBeardColor=LK(Q.facialHairColor);if(Q.extGlassColor===K)Q.extGlassColor=Hx(Q.glassesColor);if(Q.extGlassType===K)Q.extGlassType=Q.glassesType};d2.useNfpStoreDataExtentionFieldsForVer4=(A)=>{Object.defineProperty(A,"faceColor",{value:A.extFacelineColor}),Object.defineProperty(A,"hairColor",{value:A.extHairColor}),Object.defineProperty(A,"eyeColor",{value:A.extEyeColor}),Object.defineProperty(A,"eyebrowColor",{value:A.extEyebrowColor}),Object.defineProperty(A,"mouthColor",{value:A.extMouthColor}),Object.defineProperty(A,"facialHairColor",{value:A.extBeardColor}),Object.defineProperty(A,"glassesColor",{value:A.extGlassColor}),Object.defineProperty(A,"glassesType",{value:A.extGlassType})};var w61=(A,Q)=>{let K=window.TomodachiLifeQrCode,C=A.slice(96),U=new KaitaiStream(C),Y=new K(U),Z=[...Object.keys(Y),...Object.getOwnPropertyNames(Object.getPrototypeOf(Y))];for(let X of Z){if(X.startsWith("_"))continue;if(typeof Y[X]==="string")Y[X]=qx(Y[X]);Object.defineProperty(Q,X,{value:Y[X]})}};d2.parseTomodachiLifeQRCodeData=w61;d2.applyHairDyeAsVer4HairColor=(A)=>{if(d2.convertVer3FieldsToVer4(A),!A.hairDyeEnable)return;let J=[55,51,50,12,16,12,67,61,51,64,69,66,65,86,85,93,92,19,20,20,15,32,35,26,38,41,43,18,95,97,97,99][A.hairDye];Object.defineProperty(A,"hairColor",{value:J}),Object.defineProperty(A,"eyebrowColor",{value:J}),Object.defineProperty(A,"facialHairColor",{value:J})};d2.correctFromVer4CoreDataFields=(A,Q)=>{Q.eyebrowVertical+=3};d2.encodeKaitaiStructToUint8Array=(A)=>{let Q=[];for(let J in A){let K=A[J];switch(typeof K){case"number":Q.push(K);break;case"boolean":Q.push(Number(K));break;case"string":let C=new Uint8Array(new ArrayBuffer(20)),U=new DataView(C.buffer);for(let Y=0;Y<10;Y++){let Z=Y*2;U.setUint16(Z,K.charCodeAt(Y),!0)}K=[...C];case"object":if(!(K instanceof Array)){if(!J.startsWith("_"))console.warn("unknown field type on key object: "+J);continue}for(v of K)Q.push(v);break;default:if(!J.startsWith("_"))console.warn("unknown field type on key: "+J)}}return new Uint8Array(Q)};d2.encodeSwitchCharInfo=(A)=>{if(!A.unknownData||Ox(A.unknownData)){for(let Q=0;Q<16;Q++)A.unknownData[Q]=Math.floor(Math.random()*256);A.unknownData[8]&=191,A.unknownData[8]|=128}if(!A.miiName||Ix(A.miiName))A.miiName="Mii";return A.miiName=qx(A.miiName),d2.encodeKaitaiStructToUint8Array(A)};d2.gen3studioDefineFacialHairFromBeardFields=(A,Q)=>{let J=Q;if(J===void 0)J=A;if(J.facialHairBeard!==void 0||A.beardGoatee!==void 0)return;Object.defineProperty(A,"facialHairBeard",{value:J.beardGoatee}),Object.defineProperty(A,"facialHairSize",{value:J.beardSize}),Object.defineProperty(A,"facialHairMustache",{value:J.beardMustache}),Object.defineProperty(A,"facialHairVertical",{value:J.beardVertical})};d2.gen3studioDefineBeardFromFacialHairFields=(A,Q)=>{if(A.facialHairBeard!==void 0||Q.beardGoatee!==void 0)return;A.beardGoatee=Q.facialHairBeard,A.beardSize=Q.facialHairSize,A.beardMustache=Q.facialHairMustache,A.beardVertical=Q.facialHairVertical};d2.forceEnableCopyingIfUndefined=(A,Q)=>{if(Q.copying===void 0)Object.defineProperty(A,"copying",{value:!0})};var NL1=FK.find((A)=>A.className==="Gen3Studio"),LL1=FK.find((A)=>A.className==="Gen2Wiiu3dsMiitomo");d2.encodeVer3StoreData=(A,Q)=>{if(A.unknown1=3,Q||A.version===void 0||A.version<1)Object.defineProperty(A,"version",{value:3});if(!A.miiName||Ix(A.miiName))A.miiName="Mii";let J=(C)=>Array.from({length:C},()=>Math.floor(Math.random()*256));if(A.avatarId[0]&32)A.avatarId[0]&=-33;if(!A.avatarId||Ox(A.avatarId))A.avatarId=[128,0,0,0],A.clientId=J(6);if(Q)Object.defineProperty(A,"copying",{value:!0});let K=Boolean(Q);return k61(A,K)};var P61=(A)=>{for(let Q of FK)if(Q.sizes.includes(A))return Q;throw new Error("Input format is an unknown size of: "+A)},Ex=(A,Q)=>{let J=window[A.className];if(!J)throw new Error("Cannot find format class name in window: "+A.className);if(!J.prototype._read)throw new Error("Class does not have prototype._read and may not be generated from a Kaitai struct: "+A.className);let K=A.parseExtensionFunction!==void 0&&typeof d2[A.parseExtensionFunction]==="function",C;if(Q===void 0){if(A.sizes.length<1)throw new Error(`Trying to construct a blank instance of format ${A.className} but it does not have any defined sizes and no data was passed in.`);if(K)C=new KaitaiStream(Q);else{let Y=A.sizes[0];C=new KaitaiStream(new ArrayBuffer(Y))}}else if(A.sizes.length>0){let Y=A.sizes[0];if(Q.length{let J=[...Object.keys(Q),...Object.getOwnPropertyNames(Object.getPrototypeOf(Q))];for(let K of J)if(!K.startsWith("_")&&A[K]!==void 0)Object.defineProperty(Q,K,{value:A[K]})},T61=47,Wx=(A,Q,J,K)=>{let C;if(typeof J!=="string")C=P61(A.length);else C=FK.find((H)=>H.className===J);if(!C)throw new Error("Unknown input format name: "+J);if(A&&A.length===T61)A=S61(A);let U=Ex(C,A);if(!Q||Q.className===void 0)throw new Error("outputFormat is not a valid format object or does not have className");if(typeof Q.version!=="number")throw new Error(`Output format ${Q.className} does not have a version field or it is not a number.`);if(Q.encodeFunction===void 0||typeof d2[Q.encodeFunction]!=="function")throw new Error(`Output format ${Q.className} does not have a valid encodeFunction.`);let Y=!0,Z=!0;if(C.version===Q.version)Y=!1,Z=!1;if(Q.version<4)Z=!1;if(Q.version<3)Y=!1;if(Y&&C.toVer3Function!==void 0)d2[C.toVer3Function](U);if(Z&&C.toVer4Function!==void 0)d2[C.toVer4Function](U);let X=Ex(Q);if(C.preConvertFromFunction!==void 0)d2[C.preConvertFromFunction](X,U);if(_61(U,X),Q.postConvertToFunction!==void 0)d2[Q.postConvertToFunction](X,U);return d2[Q.encodeFunction](X,K)};var Ix=(A)=>A.split("").every((Q)=>Q==="\x00"),qx=(A)=>{let Q=A.indexOf("\x00");if(Q!==-1){let J=A.slice(0,Q+1),K="\x00".repeat(A.length-J.length);return J+K}return A},Ox=(A)=>A.every((Q)=>Q===0);d2.convertWiiFieldsToVer3=(A)=>{A.eyeStretch=3,A.mouthStretch=3,A.eyebrowStretch=3;let Q={1:1,2:6,3:9,9:10},J={4:5,5:2,6:3,7:7,8:8,10:9,11:11};if(Q.hasOwnProperty(A.facialFeature))A.faceMakeup=Q[A.facialFeature];if(J.hasOwnProperty(A.facialFeature))A.faceWrinkles=J[A.facialFeature]};var k61=(A,Q)=>{let J=new Uint8Array(96);if(J[0]=A.unknown1||0,J[1]=(A.characterSet||0)<<4|((A.regionLock||0)&3)<<2|(A.profanityFlag?1:0)<<1|(A.copying?1:0),J[2]=A.miiPositionPageIndex&15|(A.miiPositionSlotIndex&15)<<4,J[3]=A.version<<4|A.unknown3&15,A.systemId!==void 0)for(let N=0;N<8;N++)J[4+N]=A.systemId[N]||0;for(let N=0;N<4;N++)J[12+N]=A.avatarId[N]||0;if(A.clientId!==void 0)for(let N=0;N<6;N++)J[16+N]=A.clientId[N]||0;J[22]=A.padding&255,J[23]=A.padding>>8&255,J[24]=A.gender&1|(A.birthMonth&15)<<1|(A.birthDay&31)<<5,J[25]=A.birthDay>>3&3|(A.favoriteColor&15)<<2|(A.favorite?1:0)<<6;let K=new Uint8Array(new ArrayBuffer(20)),C=new DataView(K.buffer);for(let N=0;N<10;N++){let F=N*2;C.setUint16(F,A.miiName.charCodeAt(N),!0)}J.set(K,26),J[46]=A.bodyHeight||0,J[47]=A.bodyWeight||0,J[48]=(A.faceColor&7)<<5|(A.faceType&15)<<1|(A.mingle?1:0),J[49]=A.faceWrinkles&15|(A.faceMakeup&15)<<4,J[50]=A.hairType||0,J[51]=A.hairColor&7|(A.hairFlip?1:0)<<3|(A.unknown5&15)<<4;let U=A.eyeType&63|(A.eyeColor&7)<<6|(A.eyeSize&7)<<9|(A.eyeStretch&7)<<13|(A.eyeRotation&31)<<16|(A.eyeHorizontal&15)<<21|(A.eyeVertical&31)<<25;J[52]=U&255,J[53]=U>>8&255,J[54]=U>>16&255,J[55]=U>>24&255;let Y=A.eyebrowType&31|(A.eyebrowColor&7)<<5|(A.eyebrowSize&15)<<8|(A.eyebrowStretch&7)<<12|(A.eyebrowRotation&15)<<16|(A.eyebrowHorizontal&15)<<21|(A.eyebrowVertical&31)<<25;J[56]=Y&255,J[57]=Y>>8&255,J[58]=Y>>16&255,J[59]=Y>>24&255;let Z=A.noseType&31|(A.noseSize&15)<<5|(A.noseVertical&31)<<9;J[60]=Z&255,J[61]=Z>>8&255;let X=A.mouthType&63|(A.mouthColor&7)<<6|(A.mouthSize&15)<<9|(A.mouthStretch&7)<<13;J[62]=X&255,J[63]=X>>8&255;let E=A.mouthVertical&31|(A.facialHairMustache&7)<<5;J[64]=E&255,J[65]=E>>8&255;let H=A.facialHairBeard&7|(A.facialHairColor&7)<<3|(A.facialHairSize&15)<<6|(A.facialHairVertical&31)<<10;J[66]=H&255,J[67]=H>>8&255;let $=A.glassesType&15|(A.glassesColor&7)<<4|(A.glassesSize&15)<<7|A.glassesVertical<<11;J[68]=$&255,J[69]=$>>8&255;let I=A.moleEnable&1|(A.moleSize&15)<<1|(A.moleHorizontal&31)<<5|(A.moleVertical&31)<<10;if(J[70]=I&255,J[71]=I>>8&255,A.creatorName!==void 0){let N=new Uint8Array(new ArrayBuffer(20)),F=new DataView(N.buffer);for(let V=0;V<10;V++){let D=V*2;F.setUint16(D,A.creatorName.charCodeAt(V),!0)}J.set(N,72)}if(J[92]=A.padding2&255,J[93]=A.padding2>>8&255,!Q){let N=crc16(J.slice(0,94));J[94]=N>>8&255,J[95]=N&255}return J},S61=(A)=>{let Q=new Uint8Array(A),K=Q[0];for(let C=1;C<48;C++){let U=Q[C],Y=(U-7+256)%256;Q[C-1]=Y^K,K=U}return Q.slice(0,46)};var c1={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(A){this.toString=function(){return"CORRUPT: "+this.message},this.message=A},invalid:function(A){this.toString=function(){return"INVALID: "+this.message},this.message=A},bug:function(A){this.toString=function(){return"BUG: "+this.message},this.message=A},notReady:function(A){this.toString=function(){return"NOT READY: "+this.message},this.message=A}}};c1.cipher.aes=function(A){this.s[0][0][0]||this.O();var Q,J,K,C,U=this.s[0][4],Y=this.s[1];Q=A.length;var Z=1;if(Q!==4&&Q!==6&&Q!==8)throw new c1.exception.invalid("invalid aes key size");this.b=[K=A.slice(0),C=[]];for(A=Q;A<4*Q+28;A++){if(J=K[A-1],A%Q===0||Q===8&&A%Q===4)J=U[J>>>24]<<24^U[J>>16&255]<<16^U[J>>8&255]<<8^U[J&255],A%Q===0&&(J=J<<8^J>>>24^Z<<24,Z=Z<<1^283*(Z>>7));K[A]=K[A-Q]^J}for(Q=0;A;Q++,A--)J=K[Q&3?A:A-4],C[Q]=4>=A||4>Q?J:Y[0][U[J>>>24]]^Y[1][U[J>>16&255]]^Y[2][U[J>>8&255]]^Y[3][U[J&255]]};c1.cipher.aes.prototype={encrypt:function(A){return Py(this,A,0)},decrypt:function(A){return Py(this,A,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var A=this.s[0],Q=this.s[1],J=A[4],K=Q[4],C,U,Y,Z=[],X=[],E,H,$,I;for(C=0;256>C;C++)X[(Z[C]=C<<1^283*(C>>7))^C]=C;for(U=Y=0;!J[U];U^=E||1,Y=X[Y]||1)for($=Y^Y<<1^Y<<2^Y<<3^Y<<4,$=$>>8^$&255^99,J[U]=$,K[$]=U,H=Z[C=Z[E=Z[U]]],I=16843009*H^65537*C^257*E^16843008*U,H=257*Z[$]^16843008*$,C=0;4>C;C++)A[C][U]=H=H<<24^H>>>8,Q[C][$]=I=I<<24^I>>>8;for(C=0;5>C;C++)A[C]=A[C].slice(0),Q[C]=Q[C].slice(0)}};function Py(A,Q,J){if(Q.length!==4)throw new c1.exception.invalid("invalid aes block size");var K=A.b[J],C=Q[0]^K[0],U=Q[J?3:1]^K[1],Y=Q[2]^K[2];Q=Q[J?1:3]^K[3];var Z,X,E,H=K.length/4-2,$,I=4,N=[0,0,0,0];Z=A.s[J],A=Z[0];var F=Z[1],V=Z[2],D=Z[3],L=Z[4];for($=0;$>>24]^F[U>>16&255]^V[Y>>8&255]^D[Q&255]^K[I],X=A[U>>>24]^F[Y>>16&255]^V[Q>>8&255]^D[C&255]^K[I+1],E=A[Y>>>24]^F[Q>>16&255]^V[C>>8&255]^D[U&255]^K[I+2],Q=A[Q>>>24]^F[C>>16&255]^V[U>>8&255]^D[Y&255]^K[I+3],I+=4,C=Z,U=X,Y=E;for($=0;4>$;$++)N[J?3&-$:$]=L[C>>>24]<<24^L[U>>16&255]<<16^L[Y>>8&255]<<8^L[Q&255]^K[I++],Z=C,C=U,U=Y,Y=Q,Q=Z;return N}c1.bitArray={bitSlice:function(A,Q,J){return A=c1.bitArray.$(A.slice(Q/32),32-(Q&31)).slice(1),J===void 0?A:c1.bitArray.clamp(A,J-Q)},extract:function(A,Q,J){var K=Math.floor(-Q-J&31);return((Q+J-1^Q)&-32?A[Q/32|0]<<32-K^A[Q/32+1|0]>>>K:A[Q/32|0]>>>K)&(1<>Q-1,1)),A},partial:function(A,Q,J){return A===32?Q:(J?Q|0:Q<<32-A)+1099511627776*A},getPartial:function(A){return Math.round(A/1099511627776)||32},equal:function(A,Q){if(c1.bitArray.bitLength(A)!==c1.bitArray.bitLength(Q))return!1;var J=0,K;for(K=0;K>>Q),J=A[C]<<32-Q;return C=A.length?A[A.length-1]:0,A=c1.bitArray.getPartial(C),K.push(c1.bitArray.partial(Q+A&31,32>>24|J>>>8&65280|(J&65280)<<8|J<<24;return A}};c1.codec.utf8String={fromBits:function(A){var Q="",J=c1.bitArray.bitLength(A),K,C;for(K=0;K>>8>>>8>>>8),C<<=8;return decodeURIComponent(escape(Q))},toBits:function(A){A=unescape(encodeURIComponent(A));var Q=[],J,K=0;for(J=0;J>>Y)>>>C),YH){if(!Q)try{return c1.codec.base32hex.toBits(A)}catch(I){}throw new c1.exception.invalid("this isn't "+$+"!")}Z>C?(Z-=C,U.push(E^H>>>Z),E=H<>>C)>>>26),6>C?(Y=A[J]<<6-C,C+=26,J++):(Y<<=6,C-=6);for(;K.length&3&&!Q;)K+="=";return K},toBits:function(A,Q){A=A.replace(/\s|=/g,"");var J=[],K,C=0,U=c1.codec.base64.B,Y=0,Z;Q&&(U=U.substr(0,62)+"-_");for(K=0;KZ)throw new c1.exception.invalid("this isn't base64!");26>>C),Y=Z<<32-C):(C+=6,Y^=Z<<32-C)}return C&56&&J.push(c1.bitArray.partial(C&56,Y,1)),J}};c1.codec.base64url={fromBits:function(A){return c1.codec.base64.fromBits(A,1,1)},toBits:function(A){return c1.codec.base64.toBits(A,1)}};c1.hash.sha256=function(A){this.b[0]||this.O(),A?(this.F=A.F.slice(0),this.A=A.A.slice(0),this.l=A.l):this.reset()};c1.hash.sha256.hash=function(A){return new c1.hash.sha256().update(A).finalize()};c1.hash.sha256.prototype={blockSize:512,reset:function(){return this.F=this.Y.slice(0),this.A=[],this.l=0,this},update:function(A){typeof A==="string"&&(A=c1.codec.utf8String.toBits(A));var Q,J=this.A=c1.bitArray.concat(this.A,A);if(Q=this.l,A=this.l=Q+c1.bitArray.bitLength(A),9007199254740991Q;J++){C=!0;for(K=2;K*K<=J;K++)if(J%K===0){C=!1;break}C&&(8>Q&&(this.Y[Q]=A(Math.pow(J,0.5))),this.b[Q]=A(Math.pow(J,0.3333333333333333)),Q++)}}};function YL(A,Q){var J,K,C,U=A.F,Y=A.b,Z=U[0],X=U[1],E=U[2],H=U[3],$=U[4],I=U[5],N=U[6],F=U[7];for(J=0;64>J;J++)16>J?K=Q[J]:(K=Q[J+1&15],C=Q[J+14&15],K=Q[J&15]=(K>>>7^K>>>18^K>>>3^K<<25^K<<14)+(C>>>17^C>>>19^C>>>10^C<<15^C<<13)+Q[J&15]+Q[J+9&15]|0),K=K+F+($>>>6^$>>>11^$>>>25^$<<26^$<<21^$<<7)+(N^$&(I^N))+Y[J],F=N,N=I,I=$,$=H+K|0,H=E,E=X,X=Z,Z=K+(X&E^H&(X^E))+(X>>>2^X>>>13^X>>>22^X<<30^X<<19^X<<10)|0;U[0]=U[0]+Z|0,U[1]=U[1]+X|0,U[2]=U[2]+E|0,U[3]=U[3]+H|0,U[4]=U[4]+$|0,U[5]=U[5]+I|0,U[6]=U[6]+N|0,U[7]=U[7]+F|0}c1.mode.ccm={name:"ccm",G:[],listenProgress:function(A){c1.mode.ccm.G.push(A)},unListenProgress:function(A){A=c1.mode.ccm.G.indexOf(A),-1X)throw new c1.exception.invalid("ccm: iv must be at least 7 bytes");for(U=2;4>U&&E>>>8*U;U++);return U<15-X&&(U=15-X),J=Z.clamp(J,8*(15-U)),Q=c1.mode.ccm.V(A,Q,J,K,C,U),Y=c1.mode.ccm.C(A,Y,J,Q,C,U),Z.concat(Y.data,Y.tag)},decrypt:function(A,Q,J,K,C){C=C||64,K=K||[];var U=c1.bitArray,Y=U.bitLength(J)/8,E=U.bitLength(Q),Z=U.clamp(Q,E-C),X=U.bitSlice(Q,E-C),E=(E-C)/8;if(7>Y)throw new c1.exception.invalid("ccm: iv must be at least 7 bytes");for(Q=2;4>Q&&E>>>8*Q;Q++);if(Q<15-Y&&(Q=15-Y),J=U.clamp(J,8*(15-Q)),Z=c1.mode.ccm.C(A,Z,J,X,C,Q),A=c1.mode.ccm.V(A,Z.data,J,K,C,Q),!U.equal(Z.tag,A))throw new c1.exception.corrupt("ccm: tag doesn't match");return Z.data},na:function(A,Q,J,K,C,U){var Y=[],Z=c1.bitArray,X=Z.i;if(K=[Z.partial(8,(Q.length?64:0)|K-2<<2|U-1)],K=Z.concat(K,J),K[3]|=C,K=A.encrypt(K),Q.length)for(J=Z.bitLength(Q)/8,65279>=J?Y=[Z.partial(16,J)]:4294967295>=J&&(Y=Z.concat([Z.partial(16,65534)],[J])),Y=Z.concat(Y,Q),Q=0;QC||16H&&(c1.mode.ccm.fa(Y/X),H+=$),J[3]++,C=A.encrypt(J),Q[Y]^=C[0],Q[Y+1]^=C[1],Q[Y+2]^=C[2],Q[Y+3]^=C[3];return{tag:K,data:Z.clamp(Q,E)}}};c1.mode.ocb2={name:"ocb2",encrypt:function(A,Q,J,K,C,U){if(c1.bitArray.bitLength(J)!==128)throw new c1.exception.invalid("ocb iv must be 128 bits");var Y,Z=c1.mode.ocb2.S,X=c1.bitArray,E=X.i,H=[0,0,0,0];J=Z(A.encrypt(J));var $,I=[];K=K||[],C=C||64;for(Y=0;Y+4C.bitLength(J)&&(Z=U(Z,K(Z)),J=C.concat(J,[-2147483648,0,0,0])),Y=U(Y,J),A.encrypt(U(K(U(Z,K(Z))),Y))},S:function(A){return[A[0]<<1^A[1]>>>31,A[1]<<1^A[2]>>>31,A[2]<<1^A[3]>>>31,A[3]<<1^135*(A[0]>>>31)]}};c1.mode.gcm={name:"gcm",encrypt:function(A,Q,J,K,C){var U=Q.slice(0);return Q=c1.bitArray,K=K||[],A=c1.mode.gcm.C(!0,A,U,K,J,C||128),Q.concat(A.data,A.tag)},decrypt:function(A,Q,J,K,C){var U=Q.slice(0),Y=c1.bitArray,Z=Y.bitLength(U);if(C=C||128,K=K||[],C<=Z?(Q=Y.bitSlice(U,Z-C),U=Y.bitSlice(U,0,Z-C)):(Q=U,U=[]),A=c1.mode.gcm.C(!1,A,U,K,J,C),!Y.equal(A.tag,Q))throw new c1.exception.corrupt("gcm: tag doesn't match");return A.data},ka:function(A,Q){var J,K,C,U,Y,Z=c1.bitArray.i;C=[0,0,0,0],U=Q.slice(0);for(J=0;128>J;J++){(K=(A[Math.floor(J/32)]&1<<31-J%32)!==0)&&(C=Z(C,U)),Y=(U[3]&1)!==0;for(K=3;0>>1|(U[K-1]&1)<<31;U[0]>>>=1,Y&&(U[0]^=-520093696)}return C},j:function(A,Q,J){var K,C=J.length;Q=Q.slice(0);for(K=0;KC&&(A=Q.hash(A));for(K=0;KK||0>J)throw new c1.exception.invalid("invalid params to pbkdf2");typeof A==="string"&&(A=c1.codec.utf8String.toBits(A)),typeof Q==="string"&&(Q=c1.codec.utf8String.toBits(Q)),C=C||c1.misc.hmac,A=new C(A);var U,Y,Z,X,E=[],H=c1.bitArray;for(X=1;32*E.length<(K||1);X++){C=U=A.encrypt(H.concat(Q,[X]));for(Y=1;YY;Y++)C.push(4294967296*Math.random()|0);for(Y=0;Y=1<this.o&&(this.o=U),this.P++,this.b=c1.hash.sha256.hash(this.b.concat(C)),this.L=new c1.cipher.aes(this.b);for(K=0;4>K&&(this.h[K]=this.h[K]+1|0,!this.h[K]);K++);}for(K=0;K>>1;this.c[Y].update([K,this.N++,2,Q,U,A.length].concat(A))}break;case"string":Q===void 0&&(Q=A.length),this.c[Y].update([K,this.N++,3,Q,U,A.length]),this.c[Y].update(A);break;default:X=1}if(X)throw new c1.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[Y]+=Q,this.f+=Q,Z===this.u&&(this.isReady()!==this.u&&_y("seeded",Math.max(this.o,this.f)),_y("progress",this.getProgress()))},isReady:function(A){return A=this.T[A!==void 0?A:this.M],this.o&&this.o>=A?this.m[0]>this.ba&&(/*@__PURE__*/new Date()).valueOf()>this.Z?this.J|this.I:this.I:this.f>=A?this.J|this.u:this.u},getProgress:function(A){return A=this.T[A?A:this.M],this.o>=A?1:this.f>A?1:this.f/A},startCollectors:function(){if(!this.D){if(this.a={loadTimeCollector:zU(this,this.ma),mouseCollector:zU(this,this.oa),keyboardCollector:zU(this,this.la),accelerometerCollector:zU(this,this.ea),touchCollector:zU(this,this.qa)},window.addEventListener)window.addEventListener("load",this.a.loadTimeCollector,!1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("keypress",this.a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),window.addEventListener("touchmove",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new c1.exception.bug("can't attach event");this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener("keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function(A,Q){this.K[A][this.ga++]=Q},removeEventListener:function(A,Q){var J,K,C=this.K[A],U=[];for(K in C)C.hasOwnProperty(K)&&C[K]===Q&&U.push(K);for(J=0;JQ&&(A.h[Q]=A.h[Q]+1|0,!A.h[Q]);Q++);return A.L.encrypt(A.h)}function zU(A,Q){return function(){Q.apply(A,arguments)}}c1.random=new c1.prng(6);A:try{if(C$=typeof ky!=="undefined"&&PL1){try{Y$=(wy(),y4(My))}catch(A){Y$=null}C$=K$=Y$}if(C$&&K$.randomBytes)DU=K$.randomBytes(128),DU=new Uint32Array(new Uint8Array(DU).buffer),c1.random.addEntropy(DU,1024,"crypto['randomBytes']");else if(typeof window!=="undefined"&&typeof Uint32Array!=="undefined"){if(VU=new Uint32Array(32),window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(VU);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(VU);else break A;c1.random.addEntropy(VU,1024,"crypto['getRandomValues']")}}catch(A){typeof window!=="undefined"&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(A))}var DU,K$,VU,C$,Y$;c1.json={defaults:{v:1,iter:1e4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(A,Q,J,K){J=J||{},K=K||{};var C=c1.json,U=C.g({iv:c1.random.randomWords(4,0)},C.defaults),Y;if(C.g(U,J),J=U.adata,typeof U.salt==="string"&&(U.salt=c1.codec.base64.toBits(U.salt)),typeof U.iv==="string"&&(U.iv=c1.codec.base64.toBits(U.iv)),!c1.mode[U.mode]||!c1.cipher[U.cipher]||typeof A==="string"&&100>=U.iter||U.ts!==64&&U.ts!==96&&U.ts!==128||U.ks!==128&&U.ks!==192&&U.ks!==256||2>U.iv.length||4=Q.iter||Q.ts!==64&&Q.ts!==96&&Q.ts!==128||Q.ks!==128&&Q.ks!==192&&Q.ks!==256||!Q.iv||2>Q.iv.length||4>>24),C<<=8}return Q},toBits:function(A){var Q=[],J,K=0;for(J=0;J>8,C=J&255;for(let U=0;U>4,K=(C^Z>>3^Z<<4)&255,C=(Z^Z<<5)&255}return J=(K<<8)+C,J},Sy=(A)=>{let Q=A.slice(12,20);console.log("nonce:",Array.from(Q).map((D)=>D.toString(16)).join(""));let J=[...A.slice(0,12),...A.slice(20)];console.log("content:",J.map((D)=>D.toString(16)).join(""));let K=[...A.slice(0,12),...Q,...A.slice(20,-2)];console.log("checksumContent:",K.map((D)=>D.toString(16)).join(""));let C=W51(new Uint8Array(K));console.log("checksum:",C.toString(16));let U=[C>>8&255,C&255];J=[...J.slice(0,-2),...U];let Y=new Q6.cipher.aes([1509720446,1682369121,-1875608800,-373436846]),Z=new Uint8Array([...J,...new Array(8).fill(0)]),X=Q6.codec.bytes.toBits(Array.from(Z)),E=Q6.codec.bytes.toBits([...Q,0,0,0,0]),H=Q6.mode.ccm.encrypt(Y,X,E,[],128),$=Q6.codec.bytes.fromBits(H),I=$.length-8-16,N=$.slice(0,I),F=$.slice($.length-16);return[...Q,...N,...F]};var D5={};z3(D5,{createCanvasElement:()=>TF,ZeroStencilOp:()=>Ug,ZeroSlopeEnding:()=>eh,ZeroFactor:()=>g6,ZeroCurvatureEnding:()=>th,WrapAroundEnding:()=>Ag,WireframeGeometry:()=>IC,WebXRController:()=>BC,WebGPUCoordinateSystem:()=>Tg,WebGLUtils:()=>Tb,WebGLRenderer:()=>q4,WebGLRenderTarget:()=>s0,WebGLCubeRenderTarget:()=>BZ,WebGLCoordinateSystem:()=>jH,WebGLArrayRenderTarget:()=>kF,WebGL3DRenderTarget:()=>SF,VideoTexture:()=>bH,VideoFrameTexture:()=>hF,VectorKeyframeTrack:()=>h8,Vector4:()=>X0,Vector3:()=>I1,Vector2:()=>p1,VSMShadowMap:()=>W5,UnsignedShortType:()=>r5,UnsignedShort5551Type:()=>HH,UnsignedShort4444Type:()=>$H,UnsignedIntType:()=>TQ,UnsignedInt5999Type:()=>HF,UnsignedInt248Type:()=>C9,UnsignedByteType:()=>dA,UniformsUtils:()=>u0,UniformsLib:()=>M0,UniformsGroup:()=>aF,Uniform:()=>hZ,Uint8ClampedBufferAttribute:()=>jF,Uint8BufferAttribute:()=>UZ,Uint32BufferAttribute:()=>ZZ,Uint16BufferAttribute:()=>$4,UVMapping:()=>a5,TubeGeometry:()=>wZ,TrianglesDrawMode:()=>TH,TriangleStripDrawMode:()=>E4,TriangleFanDrawMode:()=>r3,Triangle:()=>W8,TorusKnotGeometry:()=>MZ,TorusGeometry:()=>WC,TimestampQuery:()=>kg,TextureUtils:()=>ig,TextureLoader:()=>J8,Texture:()=>J2,TetrahedronGeometry:()=>VZ,TangentSpaceNormalMap:()=>qF,TOUCH:()=>dU,SubtractiveBlending:()=>e$,SubtractEquation:()=>aL,StringKeyframeTrack:()=>J7,StreamReadUsage:()=>Vg,StreamDrawUsage:()=>Rg,StreamCopyUsage:()=>Pg,StereoCamera:()=>FC,StaticReadUsage:()=>zg,StaticDrawUsage:()=>Fg,StaticCopyUsage:()=>Mg,SrcColorFactor:()=>AF,SrcAlphaSaturateFactor:()=>KF,SrcAlphaFactor:()=>Z6,SpriteMaterial:()=>dQ,Sprite:()=>XC,SpotLightHelper:()=>eF,SpotLight:()=>L5,SplineCurve:()=>OZ,SphericalHarmonics3:()=>SZ,Spherical:()=>zC,SphereGeometry:()=>p6,Sphere:()=>O2,Source:()=>H5,SkinnedMesh:()=>e5,SkeletonHelper:()=>ZG,Skeleton:()=>g9,ShortType:()=>$F,ShapeUtils:()=>h6,ShapePath:()=>gZ,ShapeGeometry:()=>DZ,Shape:()=>n5,ShadowMaterial:()=>nH,ShaderMaterial:()=>T0,ShaderLib:()=>$6,ShaderChunk:()=>$A,Scene:()=>Q8,SRGBTransfer:()=>L2,SRGBColorSpace:()=>CA,SIGNED_RED_RGTC1_Format:()=>wH,SIGNED_RED_GREEN_RGTC2_Format:()=>_H,RingGeometry:()=>zZ,ReverseSubtractEquation:()=>rL,ReplaceStencilOp:()=>Bg,RepeatWrapping:()=>A2,RenderTargetArray:()=>iF,RenderTarget3D:()=>oF,RenderTarget:()=>UC,ReinhardToneMapping:()=>CH,RedIntegerFormat:()=>AZ,RedFormat:()=>E8,RectAreaLight:()=>kZ,Raycaster:()=>$9,Ray:()=>f6,RawShaderMaterial:()=>A7,RGIntegerFormat:()=>QZ,RGFormat:()=>Y9,RGDepthPacking:()=>Yg,RGB_S3TC_DXT1_Format:()=>AC,RGB_PVRTC_4BPPV1_Format:()=>jQ,RGB_PVRTC_2BPPV1_Format:()=>JZ,RGB_ETC2_Format:()=>JC,RGB_ETC1_Format:()=>xQ,RGB_BPTC_UNSIGNED_Format:()=>bQ,RGB_BPTC_SIGNED_Format:()=>CZ,RGBIntegerFormat:()=>sh,RGBFormat:()=>WF,RGBDepthPacking:()=>Cg,RGBA_S3TC_DXT5_Format:()=>B4,RGBA_S3TC_DXT3_Format:()=>QC,RGBA_S3TC_DXT1_Format:()=>SQ,RGBA_PVRTC_4BPPV1_Format:()=>vQ,RGBA_PVRTC_2BPPV1_Format:()=>KZ,RGBA_ETC2_EAC_Format:()=>KC,RGBA_BPTC_Format:()=>gQ,RGBA_ASTC_8x8_Format:()=>LH,RGBA_ASTC_8x6_Format:()=>NH,RGBA_ASTC_8x5_Format:()=>OH,RGBA_ASTC_6x6_Format:()=>hQ,RGBA_ASTC_6x5_Format:()=>qH,RGBA_ASTC_5x5_Format:()=>IH,RGBA_ASTC_5x4_Format:()=>WH,RGBA_ASTC_4x4_Format:()=>yQ,RGBA_ASTC_12x12_Format:()=>MH,RGBA_ASTC_12x10_Format:()=>VH,RGBA_ASTC_10x8_Format:()=>zH,RGBA_ASTC_10x6_Format:()=>RH,RGBA_ASTC_10x5_Format:()=>FH,RGBA_ASTC_10x10_Format:()=>DH,RGBAIntegerFormat:()=>GH,RGBAFormat:()=>xA,RGBADepthPacking:()=>CC,REVISION:()=>G5,RED_RGTC1_Format:()=>IF,RED_GREEN_RGTC2_Format:()=>PH,QuaternionLinearInterpolant:()=>tH,QuaternionKeyframeTrack:()=>s8,Quaternion:()=>t0,QuadraticBezierCurve3:()=>qZ,QuadraticBezierCurve:()=>IZ,PropertyMixer:()=>CG,PropertyBinding:()=>RA,PositionalAudio:()=>cF,PolyhedronGeometry:()=>e3,PolarGridHelper:()=>JR,PointsMaterial:()=>X6,Points:()=>F6,PointLightHelper:()=>AR,PointLight:()=>E9,PlaneHelper:()=>UR,PlaneGeometry:()=>g8,Plane:()=>V2,PerspectiveCamera:()=>kA,Path:()=>U4,PMREMGenerator:()=>WG,PCFSoftShadowMap:()=>iL,PCFShadowMap:()=>t$,OrthographicCamera:()=>o8,OneMinusSrcColorFactor:()=>QF,OneMinusSrcAlphaFactor:()=>j9,OneMinusDstColorFactor:()=>JF,OneMinusDstAlphaFactor:()=>wQ,OneMinusConstantColorFactor:()=>YF,OneMinusConstantAlphaFactor:()=>ZF,OneFactor:()=>F8,OctahedronGeometry:()=>nQ,ObjectSpaceNormalMap:()=>OF,ObjectLoader:()=>pF,Object3D:()=>AA,NumberKeyframeTrack:()=>Y6,NotEqualStencilFunc:()=>Og,NotEqualDepth:()=>rU,NotEqualCompare:()=>VF,NormalBlending:()=>s5,NormalAnimationBlendMode:()=>Qg,NoToneMapping:()=>i5,NoColorSpace:()=>P2,NoBlending:()=>XA,NeverStencilFunc:()=>Gg,NeverDepth:()=>lU,NeverCompare:()=>FF,NeutralToneMapping:()=>XH,NearestMipmapNearestFilter:()=>a3,NearestMipmapLinearFilter:()=>v9,NearestMipMapNearestFilter:()=>dh,NearestMipMapLinearFilter:()=>lh,NearestFilter:()=>YA,MultiplyOperation:()=>QH,MultiplyBlending:()=>AH,MixOperation:()=>BF,MirroredRepeatWrapping:()=>l8,MinEquation:()=>tL,MeshToonMaterial:()=>sH,MeshStandardMaterial:()=>p2,MeshPhysicalMaterial:()=>rA,MeshPhongMaterial:()=>u6,MeshNormalMaterial:()=>B9,MeshMatcapMaterial:()=>oH,MeshLambertMaterial:()=>Q7,MeshDistanceMaterial:()=>PZ,MeshDepthMaterial:()=>G4,MeshBasicMaterial:()=>BA,Mesh:()=>_0,MaxEquation:()=>eL,Matrix4:()=>Y0,Matrix3:()=>a0,Matrix2:()=>UG,MathUtils:()=>K2,MaterialLoader:()=>jZ,Material:()=>_2,MOUSE:()=>aK,LuminanceFormat:()=>kQ,LuminanceAlphaFormat:()=>tU,LoopRepeat:()=>ih,LoopPingPong:()=>ah,LoopOnce:()=>oh,LoadingManager:()=>OC,LoaderUtils:()=>A8,Loader:()=>JA,LinearTransfer:()=>YZ,LinearToneMapping:()=>KH,LinearSRGBColorSpace:()=>GA,LinearMipmapNearestFilter:()=>I5,LinearMipmapLinearFilter:()=>o2,LinearMipMapNearestFilter:()=>nh,LinearMipMapLinearFilter:()=>XF,LinearInterpolant:()=>_Z,LinearFilter:()=>HA,LineSegments:()=>T2,LineLoop:()=>H4,LineDashedMaterial:()=>iH,LineCurve3:()=>mH,LineCurve:()=>WZ,LineBasicMaterial:()=>pA,Line3:()=>R5,Line:()=>e2,LightProbe:()=>LC,Light:()=>C3,LessStencilFunc:()=>Wg,LessEqualStencilFunc:()=>Ig,LessEqualDepth:()=>rK,LessEqualCompare:()=>kH,LessDepth:()=>sU,LessCompare:()=>RF,Layers:()=>uQ,LatheGeometry:()=>$C,LOD:()=>hH,KeyframeTrack:()=>X9,KeepStencilOp:()=>Zg,InvertStencilOp:()=>Hg,InterpolateSmooth:()=>rh,InterpolateLinear:()=>t5,InterpolateDiscrete:()=>X4,Interpolant:()=>N5,InterleavedBufferAttribute:()=>B8,InterleavedBuffer:()=>L6,IntType:()=>EH,Int8BufferAttribute:()=>ZC,Int32BufferAttribute:()=>xH,Int16BufferAttribute:()=>vF,InstancedMesh:()=>A3,InstancedInterleavedBuffer:()=>RC,InstancedBufferGeometry:()=>vZ,InstancedBufferAttribute:()=>K9,IncrementWrapStencilOp:()=>Eg,IncrementStencilOp:()=>NF,ImageUtils:()=>vH,ImageLoader:()=>MQ,ImageBitmapLoader:()=>sQ,IcosahedronGeometry:()=>RZ,HemisphereLightHelper:()=>QR,HemisphereLight:()=>AG,HalfFloatType:()=>g0,Group:()=>cA,GridHelper:()=>BG,GreaterStencilFunc:()=>qg,GreaterEqualStencilFunc:()=>Ng,GreaterEqualDepth:()=>iU,GreaterEqualCompare:()=>MF,GreaterDepth:()=>aU,GreaterCompare:()=>DF,GLSL3:()=>SH,GLSL1:()=>_g,GLBufferAttribute:()=>rF,Frustum:()=>Q3,FrontSide:()=>M2,FramebufferTexture:()=>EC,FogExp2:()=>XZ,Fog:()=>EZ,FloatType:()=>aA,Float32BufferAttribute:()=>L0,Float16BufferAttribute:()=>xF,FileLoader:()=>KA,ExtrudeGeometry:()=>GC,EventDispatcher:()=>y9,Euler:()=>t2,EquirectangularRefractionMapping:()=>tK,EquirectangularReflectionMapping:()=>_Q,EqualStencilFunc:()=>LF,EqualDepth:()=>oU,EqualCompare:()=>zF,EllipseCurve:()=>lQ,EdgesGeometry:()=>dH,DynamicReadUsage:()=>Dg,DynamicDrawUsage:()=>YC,DynamicCopyUsage:()=>wg,DstColorFactor:()=>o5,DstAlphaFactor:()=>b6,DoubleSide:()=>VA,DodecahedronGeometry:()=>FZ,DiscreteInterpolant:()=>rH,DirectionalLightHelper:()=>KR,DirectionalLight:()=>R6,DetachedBindMode:()=>ch,DepthTexture:()=>E6,DepthStencilFormat:()=>x9,DepthFormat:()=>eU,DefaultLoadingManager:()=>eH,DecrementWrapStencilOp:()=>$g,DecrementStencilOp:()=>Xg,DataUtils:()=>U9,DataTextureLoader:()=>W4,DataTexture:()=>fA,DataArrayTexture:()=>pQ,Data3DTexture:()=>q5,Cylindrical:()=>tF,CylinderGeometry:()=>J3,CustomToneMapping:()=>ZH,CustomBlending:()=>y2,CurvePath:()=>cH,Curve:()=>n8,CullFaceNone:()=>sL,CullFaceFrontBack:()=>ph,CullFaceFront:()=>oL,CullFaceBack:()=>r$,CubicInterpolant:()=>aH,CubicBezierCurve3:()=>uH,CubicBezierCurve:()=>GZ,CubeUVReflectionMapping:()=>eK,CubeTextureLoader:()=>TZ,CubeTexture:()=>t3,CubeRefractionMapping:()=>Z4,CubeReflectionMapping:()=>PQ,CubeCamera:()=>yH,Controls:()=>z5,ConstantColorFactor:()=>CF,ConstantAlphaFactor:()=>UF,ConeGeometry:()=>HC,CompressedTextureLoader:()=>NC,CompressedTexture:()=>Z9,CompressedCubeTexture:()=>HZ,CompressedArrayTexture:()=>$Z,ColorManagement:()=>e0,ColorKeyframeTrack:()=>qC,Color:()=>y1,Clock:()=>Y3,ClampToEdgeWrapping:()=>N2,CircleGeometry:()=>LZ,CineonToneMapping:()=>YH,CatmullRomCurve3:()=>pH,CapsuleGeometry:()=>NZ,CanvasTexture:()=>O5,CameraHelper:()=>CR,Camera:()=>cQ,Cache:()=>l5,ByteType:()=>EF,BufferGeometryLoader:()=>xZ,BufferGeometry:()=>V0,BufferAttribute:()=>p0,BoxHelper:()=>YR,BoxGeometry:()=>R8,Box3Helper:()=>XG,Box3:()=>DA,Box2:()=>oQ,BooleanKeyframeTrack:()=>K3,Bone:()=>h9,BatchedMesh:()=>gH,BasicShadowMap:()=>uh,BasicDepthPacking:()=>Kg,BackSide:()=>w2,AxesHelper:()=>BR,AudioLoader:()=>uF,AudioListener:()=>mF,AudioContext:()=>yZ,AudioAnalyser:()=>dF,Audio:()=>KG,AttachedBindMode:()=>mh,ArrowHelper:()=>ZR,ArrayCamera:()=>JG,ArcCurve:()=>fH,AnimationUtils:()=>mg,AnimationObjectGroup:()=>sF,AnimationMixer:()=>F5,AnimationLoader:()=>fF,AnimationClip:()=>L8,AnimationAction:()=>YG,AmbientLight:()=>I4,AlwaysStencilFunc:()=>Lg,AlwaysDepth:()=>nU,AlwaysCompare:()=>wF,AlphaFormat:()=>GF,AgXToneMapping:()=>BH,AdditiveBlending:()=>U6,AdditiveAnimationBlendMode:()=>Jg,AddOperation:()=>JH,AddEquation:()=>X8,ACESFilmicToneMapping:()=>UH});var G5="173",aK={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},dU={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},sL=0,r$=1,oL=2,ph=3,uh=0,t$=1,iL=2,W5=3,M2=0,w2=1,VA=2,XA=0,s5=1,U6=2,e$=3,AH=4,y2=5,X8=100,aL=101,rL=102,tL=103,eL=104,g6=200,F8=201,AF=202,QF=203,Z6=204,j9=205,b6=206,wQ=207,o5=208,JF=209,KF=210,CF=211,YF=212,UF=213,ZF=214,lU=0,nU=1,sU=2,rK=3,oU=4,iU=5,aU=6,rU=7,QH=0,BF=1,JH=2,i5=0,KH=1,CH=2,YH=3,UH=4,ZH=5,BH=6,XH=7,mh="attached",ch="detached",a5=300,PQ=301,Z4=302,_Q=303,tK=304,eK=306,A2=1000,N2=1001,l8=1002,YA=1003,a3=1004,dh=1004,v9=1005,lh=1005,HA=1006,I5=1007,nh=1007,o2=1008,XF=1008,dA=1009,EF=1010,$F=1011,r5=1012,EH=1013,TQ=1014,aA=1015,g0=1016,$H=1017,HH=1018,C9=1020,HF=35902,GF=1021,WF=1022,xA=1023,kQ=1024,tU=1025,eU=1026,x9=1027,E8=1028,AZ=1029,Y9=1030,QZ=1031,sh=1032,GH=1033,AC=33776,SQ=33777,QC=33778,B4=33779,jQ=35840,JZ=35841,vQ=35842,KZ=35843,xQ=36196,JC=37492,KC=37496,yQ=37808,WH=37809,IH=37810,qH=37811,hQ=37812,OH=37813,NH=37814,LH=37815,FH=37816,RH=37817,zH=37818,DH=37819,VH=37820,MH=37821,gQ=36492,CZ=36494,bQ=36495,IF=36283,wH=36284,PH=36285,_H=36286,oh=2200,ih=2201,ah=2202,X4=2300,t5=2301,rh=2302,th=2400,eh=2401,Ag=2402,Qg=2500,Jg=2501,TH=0,E4=1,r3=2,Kg=3200,CC=3201,Cg=3202,Yg=3203,qF=0,OF=1,P2="",CA="srgb",GA="srgb-linear",YZ="linear",L2="srgb",Ug=0,Zg=7680,Bg=7681,NF=7682,Xg=7683,Eg=34055,$g=34056,Hg=5386,Gg=512,Wg=513,LF=514,Ig=515,qg=516,Og=517,Ng=518,Lg=519,FF=512,RF=513,zF=514,kH=515,DF=516,VF=517,MF=518,wF=519,Fg=35044,YC=35048,Rg=35040,zg=35045,Dg=35049,Vg=35041,Mg=35046,wg=35050,Pg=35042,_g="100",SH="300 es",jH=2000,Tg=2001,kg={COMPUTE:"compute",RENDER:"render"};class y9{addEventListener(A,Q){if(this._listeners===void 0)this._listeners={};let J=this._listeners;if(J[A]===void 0)J[A]=[];if(J[A].indexOf(Q)===-1)J[A].push(Q)}hasEventListener(A,Q){let J=this._listeners;if(J===void 0)return!1;return J[A]!==void 0&&J[A].indexOf(Q)!==-1}removeEventListener(A,Q){let J=this._listeners;if(J===void 0)return;let K=J[A];if(K!==void 0){let C=K.indexOf(Q);if(C!==-1)K.splice(C,1)}}dispatchEvent(A){let Q=this._listeners;if(Q===void 0)return;let J=Q[A.type];if(J!==void 0){A.target=this;let K=J.slice(0);for(let C=0,U=K.length;C>8&255]+J6[A>>16&255]+J6[A>>24&255]+"-"+J6[Q&255]+J6[Q>>8&255]+"-"+J6[Q>>16&15|64]+J6[Q>>24&255]+"-"+J6[J&63|128]+J6[J>>8&255]+"-"+J6[J>>16&255]+J6[J>>24&255]+J6[K&255]+J6[K>>8&255]+J6[K>>16&255]+J6[K>>24&255]).toLowerCase()}function zA(A,Q,J){return Math.max(Q,Math.min(J,A))}function PF(A,Q){return(A%Q+Q)%Q}function I51(A,Q,J,K,C){return K+(A-Q)*(C-K)/(J-Q)}function q51(A,Q,J){if(A!==Q)return(J-A)/(Q-A);else return 0}function bU(A,Q,J){return(1-J)*A+J*Q}function O51(A,Q,J,K){return bU(A,Q,1-Math.exp(-J*K))}function N51(A,Q=1){return Q-Math.abs(PF(A,Q*2)-Q)}function L51(A,Q,J){if(A<=Q)return 0;if(A>=J)return 1;return A=(A-Q)/(J-Q),A*A*(3-2*A)}function F51(A,Q,J){if(A<=Q)return 0;if(A>=J)return 1;return A=(A-Q)/(J-Q),A*A*A*(A*(A*6-15)+10)}function R51(A,Q){return A+Math.floor(Math.random()*(Q-A+1))}function z51(A,Q){return A+Math.random()*(Q-A)}function D51(A){return A*(0.5-Math.random())}function V51(A){if(A!==void 0)jy=A;let Q=jy+=1831565813;return Q=Math.imul(Q^Q>>>15,Q|1),Q^=Q+Math.imul(Q^Q>>>7,Q|61),((Q^Q>>>14)>>>0)/4294967296}function M51(A){return A*zQ}function w51(A){return A*DQ}function P51(A){return(A&A-1)===0&&A!==0}function _51(A){return Math.pow(2,Math.ceil(Math.log(A)/Math.LN2))}function T51(A){return Math.pow(2,Math.floor(Math.log(A)/Math.LN2))}function k51(A,Q,J,K,C){let{cos:U,sin:Y}=Math,Z=U(J/2),X=Y(J/2),E=U((Q+K)/2),H=Y((Q+K)/2),$=U((Q-K)/2),I=Y((Q-K)/2),N=U((K-Q)/2),F=Y((K-Q)/2);switch(C){case"XYX":A.set(Z*H,X*$,X*I,Z*E);break;case"YZY":A.set(X*I,Z*H,X*$,Z*E);break;case"ZXZ":A.set(X*$,X*I,Z*H,Z*E);break;case"XZX":A.set(Z*H,X*F,X*N,Z*E);break;case"YXY":A.set(X*N,Z*H,X*F,Z*E);break;case"ZYZ":A.set(X*F,X*N,Z*H,Z*E);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+C)}}function N6(A,Q){switch(Q.constructor){case Float32Array:return A;case Uint32Array:return A/4294967295;case Uint16Array:return A/65535;case Uint8Array:return A/255;case Int32Array:return Math.max(A/2147483647,-1);case Int16Array:return Math.max(A/32767,-1);case Int8Array:return Math.max(A/127,-1);default:throw new Error("Invalid component type.")}}function TA(A,Q){switch(Q.constructor){case Float32Array:return A;case Uint32Array:return Math.round(A*4294967295);case Uint16Array:return Math.round(A*65535);case Uint8Array:return Math.round(A*255);case Int32Array:return Math.round(A*2147483647);case Int16Array:return Math.round(A*32767);case Int8Array:return Math.round(A*127);default:throw new Error("Invalid component type.")}}var K2={DEG2RAD:zQ,RAD2DEG:DQ,generateUUID:J9,clamp:zA,euclideanModulo:PF,mapLinear:I51,inverseLerp:q51,lerp:bU,damp:O51,pingpong:N51,smoothstep:L51,smootherstep:F51,randInt:R51,randFloat:z51,randFloatSpread:D51,seededRandom:V51,degToRad:M51,radToDeg:w51,isPowerOfTwo:P51,ceilPowerOfTwo:_51,floorPowerOfTwo:T51,setQuaternionFromProperEuler:k51,normalize:TA,denormalize:N6};class p1{constructor(A=0,Q=0){p1.prototype.isVector2=!0,this.x=A,this.y=Q}get width(){return this.x}set width(A){this.x=A}get height(){return this.y}set height(A){this.y=A}set(A,Q){return this.x=A,this.y=Q,this}setScalar(A){return this.x=A,this.y=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setComponent(A,Q){switch(A){case 0:this.x=Q;break;case 1:this.y=Q;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y)}copy(A){return this.x=A.x,this.y=A.y,this}add(A){return this.x+=A.x,this.y+=A.y,this}addScalar(A){return this.x+=A,this.y+=A,this}addVectors(A,Q){return this.x=A.x+Q.x,this.y=A.y+Q.y,this}addScaledVector(A,Q){return this.x+=A.x*Q,this.y+=A.y*Q,this}sub(A){return this.x-=A.x,this.y-=A.y,this}subScalar(A){return this.x-=A,this.y-=A,this}subVectors(A,Q){return this.x=A.x-Q.x,this.y=A.y-Q.y,this}multiply(A){return this.x*=A.x,this.y*=A.y,this}multiplyScalar(A){return this.x*=A,this.y*=A,this}divide(A){return this.x/=A.x,this.y/=A.y,this}divideScalar(A){return this.multiplyScalar(1/A)}applyMatrix3(A){let Q=this.x,J=this.y,K=A.elements;return this.x=K[0]*Q+K[3]*J+K[6],this.y=K[1]*Q+K[4]*J+K[7],this}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this}clamp(A,Q){return this.x=zA(this.x,A.x,Q.x),this.y=zA(this.y,A.y,Q.y),this}clampScalar(A,Q){return this.x=zA(this.x,A,Q),this.y=zA(this.y,A,Q),this}clampLength(A,Q){let J=this.length();return this.divideScalar(J||1).multiplyScalar(zA(J,A,Q))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(A){return this.x*A.x+this.y*A.y}cross(A){return this.x*A.y-this.y*A.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(A){let Q=Math.sqrt(this.lengthSq()*A.lengthSq());if(Q===0)return Math.PI/2;let J=this.dot(A)/Q;return Math.acos(zA(J,-1,1))}distanceTo(A){return Math.sqrt(this.distanceToSquared(A))}distanceToSquared(A){let Q=this.x-A.x,J=this.y-A.y;return Q*Q+J*J}manhattanDistanceTo(A){return Math.abs(this.x-A.x)+Math.abs(this.y-A.y)}setLength(A){return this.normalize().multiplyScalar(A)}lerp(A,Q){return this.x+=(A.x-this.x)*Q,this.y+=(A.y-this.y)*Q,this}lerpVectors(A,Q,J){return this.x=A.x+(Q.x-A.x)*J,this.y=A.y+(Q.y-A.y)*J,this}equals(A){return A.x===this.x&&A.y===this.y}fromArray(A,Q=0){return this.x=A[Q],this.y=A[Q+1],this}toArray(A=[],Q=0){return A[Q]=this.x,A[Q+1]=this.y,A}fromBufferAttribute(A,Q){return this.x=A.getX(Q),this.y=A.getY(Q),this}rotateAround(A,Q){let J=Math.cos(Q),K=Math.sin(Q),C=this.x-A.x,U=this.y-A.y;return this.x=C*J-U*K+A.x,this.y=C*K+U*J+A.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class a0{constructor(A,Q,J,K,C,U,Y,Z,X){if(a0.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],A!==void 0)this.set(A,Q,J,K,C,U,Y,Z,X)}set(A,Q,J,K,C,U,Y,Z,X){let E=this.elements;return E[0]=A,E[1]=K,E[2]=Y,E[3]=Q,E[4]=C,E[5]=Z,E[6]=J,E[7]=U,E[8]=X,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(A){let Q=this.elements,J=A.elements;return Q[0]=J[0],Q[1]=J[1],Q[2]=J[2],Q[3]=J[3],Q[4]=J[4],Q[5]=J[5],Q[6]=J[6],Q[7]=J[7],Q[8]=J[8],this}extractBasis(A,Q,J){return A.setFromMatrix3Column(this,0),Q.setFromMatrix3Column(this,1),J.setFromMatrix3Column(this,2),this}setFromMatrix4(A){let Q=A.elements;return this.set(Q[0],Q[4],Q[8],Q[1],Q[5],Q[9],Q[2],Q[6],Q[10]),this}multiply(A){return this.multiplyMatrices(this,A)}premultiply(A){return this.multiplyMatrices(A,this)}multiplyMatrices(A,Q){let J=A.elements,K=Q.elements,C=this.elements,U=J[0],Y=J[3],Z=J[6],X=J[1],E=J[4],H=J[7],$=J[2],I=J[5],N=J[8],F=K[0],V=K[3],D=K[6],L=K[1],R=K[4],M=K[7],T=K[2],h=K[5],y=K[8];return C[0]=U*F+Y*L+Z*T,C[3]=U*V+Y*R+Z*h,C[6]=U*D+Y*M+Z*y,C[1]=X*F+E*L+H*T,C[4]=X*V+E*R+H*h,C[7]=X*D+E*M+H*y,C[2]=$*F+I*L+N*T,C[5]=$*V+I*R+N*h,C[8]=$*D+I*M+N*y,this}multiplyScalar(A){let Q=this.elements;return Q[0]*=A,Q[3]*=A,Q[6]*=A,Q[1]*=A,Q[4]*=A,Q[7]*=A,Q[2]*=A,Q[5]*=A,Q[8]*=A,this}determinant(){let A=this.elements,Q=A[0],J=A[1],K=A[2],C=A[3],U=A[4],Y=A[5],Z=A[6],X=A[7],E=A[8];return Q*U*E-Q*Y*X-J*C*E+J*Y*Z+K*C*X-K*U*Z}invert(){let A=this.elements,Q=A[0],J=A[1],K=A[2],C=A[3],U=A[4],Y=A[5],Z=A[6],X=A[7],E=A[8],H=E*U-Y*X,$=Y*Z-E*C,I=X*C-U*Z,N=Q*H+J*$+K*I;if(N===0)return this.set(0,0,0,0,0,0,0,0,0);let F=1/N;return A[0]=H*F,A[1]=(K*X-E*J)*F,A[2]=(Y*J-K*U)*F,A[3]=$*F,A[4]=(E*Q-K*Z)*F,A[5]=(K*C-Y*Q)*F,A[6]=I*F,A[7]=(J*Z-X*Q)*F,A[8]=(U*Q-J*C)*F,this}transpose(){let A,Q=this.elements;return A=Q[1],Q[1]=Q[3],Q[3]=A,A=Q[2],Q[2]=Q[6],Q[6]=A,A=Q[5],Q[5]=Q[7],Q[7]=A,this}getNormalMatrix(A){return this.setFromMatrix4(A).invert().transpose()}transposeIntoArray(A){let Q=this.elements;return A[0]=Q[0],A[1]=Q[3],A[2]=Q[6],A[3]=Q[1],A[4]=Q[4],A[5]=Q[7],A[6]=Q[2],A[7]=Q[5],A[8]=Q[8],this}setUvTransform(A,Q,J,K,C,U,Y){let Z=Math.cos(C),X=Math.sin(C);return this.set(J*Z,J*X,-J*(Z*U+X*Y)+U+A,-K*X,K*Z,-K*(-X*U+Z*Y)+Y+Q,0,0,1),this}scale(A,Q){return this.premultiply(ZL.makeScale(A,Q)),this}rotate(A){return this.premultiply(ZL.makeRotation(-A)),this}translate(A,Q){return this.premultiply(ZL.makeTranslation(A,Q)),this}makeTranslation(A,Q){if(A.isVector2)this.set(1,0,A.x,0,1,A.y,0,0,1);else this.set(1,0,A,0,1,Q,0,0,1);return this}makeRotation(A){let Q=Math.cos(A),J=Math.sin(A);return this.set(Q,-J,0,J,Q,0,0,0,1),this}makeScale(A,Q){return this.set(A,0,0,0,Q,0,0,0,1),this}equals(A){let Q=this.elements,J=A.elements;for(let K=0;K<9;K++)if(Q[K]!==J[K])return!1;return!0}fromArray(A,Q=0){for(let J=0;J<9;J++)this.elements[J]=A[J+Q];return this}toArray(A=[],Q=0){let J=this.elements;return A[Q]=J[0],A[Q+1]=J[1],A[Q+2]=J[2],A[Q+3]=J[3],A[Q+4]=J[4],A[Q+5]=J[5],A[Q+6]=J[6],A[Q+7]=J[7],A[Q+8]=J[8],A}clone(){return new this.constructor().fromArray(this.elements)}}var ZL=/*@__PURE__*/new a0;function _F(A){for(let Q=A.length-1;Q>=0;--Q)if(A[Q]>=65535)return!0;return!1}var S51={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function nK(A,Q){return new S51[A](Q)}function iK(A){return document.createElementNS("http://www.w3.org/1999/xhtml",A)}function TF(){let A=iK("canvas");return A.style.display="block",A}var vy={};function fQ(A){if(A in vy)return;vy[A]=!0,console.warn(A)}function Sg(A,Q,J){return new Promise(function(K,C){function U(){switch(A.clientWaitSync(Q,A.SYNC_FLUSH_COMMANDS_BIT,0)){case A.WAIT_FAILED:C();break;case A.TIMEOUT_EXPIRED:setTimeout(U,J);break;default:K()}}setTimeout(U,J)})}function jg(A){let Q=A.elements;Q[2]=0.5*Q[2]+0.5*Q[3],Q[6]=0.5*Q[6]+0.5*Q[7],Q[10]=0.5*Q[10]+0.5*Q[11],Q[14]=0.5*Q[14]+0.5*Q[15]}function vg(A){let Q=A.elements;if(Q[11]===-1)Q[10]=-Q[10]-1,Q[14]=-Q[14];else Q[10]=-Q[10],Q[14]=-Q[14]+1}var xy=/*@__PURE__*/new a0().set(0.4123908,0.3575843,0.1804808,0.212639,0.7151687,0.0721923,0.0193308,0.1191948,0.9505322),yy=/*@__PURE__*/new a0().set(3.2409699,-1.5373832,-0.4986108,-0.9692436,1.8759675,0.0415551,0.0556301,-0.203977,1.0569715);function j51(){let A={enabled:!0,workingColorSpace:"srgb-linear",spaces:{},convert:function(C,U,Y){if(this.enabled===!1||U===Y||!U||!Y)return C;if(this.spaces[U].transfer==="srgb")C.r=i3(C.r),C.g=i3(C.g),C.b=i3(C.b);if(this.spaces[U].primaries!==this.spaces[Y].primaries)C.applyMatrix3(this.spaces[U].toXYZ),C.applyMatrix3(this.spaces[Y].fromXYZ);if(this.spaces[Y].transfer==="srgb")C.r=oK(C.r),C.g=oK(C.g),C.b=oK(C.b);return C},fromWorkingColorSpace:function(C,U){return this.convert(C,this.workingColorSpace,U)},toWorkingColorSpace:function(C,U){return this.convert(C,U,this.workingColorSpace)},getPrimaries:function(C){return this.spaces[C].primaries},getTransfer:function(C){if(C==="")return"linear";return this.spaces[C].transfer},getLuminanceCoefficients:function(C,U=this.workingColorSpace){return C.fromArray(this.spaces[U].luminanceCoefficients)},define:function(C){Object.assign(this.spaces,C)},_getMatrix:function(C,U,Y){return C.copy(this.spaces[U].toXYZ).multiply(this.spaces[Y].fromXYZ)},_getDrawingBufferColorSpace:function(C){return this.spaces[C].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(C=this.workingColorSpace){return this.spaces[C].workingColorSpaceConfig.unpackColorSpace}},Q=[0.64,0.33,0.3,0.6,0.15,0.06],J=[0.2126,0.7152,0.0722],K=[0.3127,0.329];return A.define({["srgb-linear"]:{primaries:Q,whitePoint:K,transfer:"linear",toXYZ:xy,fromXYZ:yy,luminanceCoefficients:J,workingColorSpaceConfig:{unpackColorSpace:"srgb"},outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}},["srgb"]:{primaries:Q,whitePoint:K,transfer:"srgb",toXYZ:xy,fromXYZ:yy,luminanceCoefficients:J,outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}}}),A}var e0=/*@__PURE__*/j51();function i3(A){return A<0.04045?A*0.0773993808:Math.pow(A*0.9478672986+0.0521327014,2.4)}function oK(A){return A<0.0031308?A*12.92:1.055*Math.pow(A,0.41666)-0.055}var TK;class vH{static getDataURL(A){if(/^data:/i.test(A.src))return A.src;if(typeof HTMLCanvasElement==="undefined")return A.src;let Q;if(A instanceof HTMLCanvasElement)Q=A;else{if(TK===void 0)TK=iK("canvas");TK.width=A.width,TK.height=A.height;let J=TK.getContext("2d");if(A instanceof ImageData)J.putImageData(A,0,0);else J.drawImage(A,0,0,A.width,A.height);Q=TK}return Q.toDataURL("image/png")}static sRGBToLinear(A){if(typeof HTMLImageElement!=="undefined"&&A instanceof HTMLImageElement||typeof HTMLCanvasElement!=="undefined"&&A instanceof HTMLCanvasElement||typeof ImageBitmap!=="undefined"&&A instanceof ImageBitmap){let Q=iK("canvas");Q.width=A.width,Q.height=A.height;let J=Q.getContext("2d");J.drawImage(A,0,0,A.width,A.height);let K=J.getImageData(0,0,A.width,A.height),C=K.data;for(let U=0;U0)J.userData=this.userData;if(!Q)A.textures[this.uuid]=J;return J}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(A){if(this.mapping!==300)return A;if(A.applyMatrix3(this.matrix),A.x<0||A.x>1)switch(this.wrapS){case 1000:A.x=A.x-Math.floor(A.x);break;case 1001:A.x=A.x<0?0:1;break;case 1002:if(Math.abs(Math.floor(A.x)%2)===1)A.x=Math.ceil(A.x)-A.x;else A.x=A.x-Math.floor(A.x);break}if(A.y<0||A.y>1)switch(this.wrapT){case 1000:A.y=A.y-Math.floor(A.y);break;case 1001:A.y=A.y<0?0:1;break;case 1002:if(Math.abs(Math.floor(A.y)%2)===1)A.y=Math.ceil(A.y)-A.y;else A.y=A.y-Math.floor(A.y);break}if(this.flipY)A.y=1-A.y;return A}set needsUpdate(A){if(A===!0)this.version++,this.source.needsUpdate=!0}set needsPMREMUpdate(A){if(A===!0)this.pmremVersion++}}J2.DEFAULT_IMAGE=null;J2.DEFAULT_MAPPING=300;J2.DEFAULT_ANISOTROPY=1;class X0{constructor(A=0,Q=0,J=0,K=1){X0.prototype.isVector4=!0,this.x=A,this.y=Q,this.z=J,this.w=K}get width(){return this.z}set width(A){this.z=A}get height(){return this.w}set height(A){this.w=A}set(A,Q,J,K){return this.x=A,this.y=Q,this.z=J,this.w=K,this}setScalar(A){return this.x=A,this.y=A,this.z=A,this.w=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setZ(A){return this.z=A,this}setW(A){return this.w=A,this}setComponent(A,Q){switch(A){case 0:this.x=Q;break;case 1:this.y=Q;break;case 2:this.z=Q;break;case 3:this.w=Q;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(A){return this.x=A.x,this.y=A.y,this.z=A.z,this.w=A.w!==void 0?A.w:1,this}add(A){return this.x+=A.x,this.y+=A.y,this.z+=A.z,this.w+=A.w,this}addScalar(A){return this.x+=A,this.y+=A,this.z+=A,this.w+=A,this}addVectors(A,Q){return this.x=A.x+Q.x,this.y=A.y+Q.y,this.z=A.z+Q.z,this.w=A.w+Q.w,this}addScaledVector(A,Q){return this.x+=A.x*Q,this.y+=A.y*Q,this.z+=A.z*Q,this.w+=A.w*Q,this}sub(A){return this.x-=A.x,this.y-=A.y,this.z-=A.z,this.w-=A.w,this}subScalar(A){return this.x-=A,this.y-=A,this.z-=A,this.w-=A,this}subVectors(A,Q){return this.x=A.x-Q.x,this.y=A.y-Q.y,this.z=A.z-Q.z,this.w=A.w-Q.w,this}multiply(A){return this.x*=A.x,this.y*=A.y,this.z*=A.z,this.w*=A.w,this}multiplyScalar(A){return this.x*=A,this.y*=A,this.z*=A,this.w*=A,this}applyMatrix4(A){let Q=this.x,J=this.y,K=this.z,C=this.w,U=A.elements;return this.x=U[0]*Q+U[4]*J+U[8]*K+U[12]*C,this.y=U[1]*Q+U[5]*J+U[9]*K+U[13]*C,this.z=U[2]*Q+U[6]*J+U[10]*K+U[14]*C,this.w=U[3]*Q+U[7]*J+U[11]*K+U[15]*C,this}divide(A){return this.x/=A.x,this.y/=A.y,this.z/=A.z,this.w/=A.w,this}divideScalar(A){return this.multiplyScalar(1/A)}setAxisAngleFromQuaternion(A){this.w=2*Math.acos(A.w);let Q=Math.sqrt(1-A.w*A.w);if(Q<0.0001)this.x=1,this.y=0,this.z=0;else this.x=A.x/Q,this.y=A.y/Q,this.z=A.z/Q;return this}setAxisAngleFromRotationMatrix(A){let Q,J,K,C,U=0.01,Y=0.1,Z=A.elements,X=Z[0],E=Z[4],H=Z[8],$=Z[1],I=Z[5],N=Z[9],F=Z[2],V=Z[6],D=Z[10];if(Math.abs(E-$)<0.01&&Math.abs(H-F)<0.01&&Math.abs(N-V)<0.01){if(Math.abs(E+$)<0.1&&Math.abs(H+F)<0.1&&Math.abs(N+V)<0.1&&Math.abs(X+I+D-3)<0.1)return this.set(1,0,0,0),this;Q=Math.PI;let R=(X+1)/2,M=(I+1)/2,T=(D+1)/2,h=(E+$)/4,y=(H+F)/4,g=(N+V)/4;if(R>M&&R>T)if(R<0.01)J=0,K=0.707106781,C=0.707106781;else J=Math.sqrt(R),K=h/J,C=y/J;else if(M>T)if(M<0.01)J=0.707106781,K=0,C=0.707106781;else K=Math.sqrt(M),J=h/K,C=g/K;else if(T<0.01)J=0.707106781,K=0.707106781,C=0;else C=Math.sqrt(T),J=y/C,K=g/C;return this.set(J,K,C,Q),this}let L=Math.sqrt((V-N)*(V-N)+(H-F)*(H-F)+($-E)*($-E));if(Math.abs(L)<0.001)L=1;return this.x=(V-N)/L,this.y=(H-F)/L,this.z=($-E)/L,this.w=Math.acos((X+I+D-1)/2),this}setFromMatrixPosition(A){let Q=A.elements;return this.x=Q[12],this.y=Q[13],this.z=Q[14],this.w=Q[15],this}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this.z=Math.min(this.z,A.z),this.w=Math.min(this.w,A.w),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this.z=Math.max(this.z,A.z),this.w=Math.max(this.w,A.w),this}clamp(A,Q){return this.x=zA(this.x,A.x,Q.x),this.y=zA(this.y,A.y,Q.y),this.z=zA(this.z,A.z,Q.z),this.w=zA(this.w,A.w,Q.w),this}clampScalar(A,Q){return this.x=zA(this.x,A,Q),this.y=zA(this.y,A,Q),this.z=zA(this.z,A,Q),this.w=zA(this.w,A,Q),this}clampLength(A,Q){let J=this.length();return this.divideScalar(J||1).multiplyScalar(zA(J,A,Q))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(A){return this.x*A.x+this.y*A.y+this.z*A.z+this.w*A.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(A){return this.normalize().multiplyScalar(A)}lerp(A,Q){return this.x+=(A.x-this.x)*Q,this.y+=(A.y-this.y)*Q,this.z+=(A.z-this.z)*Q,this.w+=(A.w-this.w)*Q,this}lerpVectors(A,Q,J){return this.x=A.x+(Q.x-A.x)*J,this.y=A.y+(Q.y-A.y)*J,this.z=A.z+(Q.z-A.z)*J,this.w=A.w+(Q.w-A.w)*J,this}equals(A){return A.x===this.x&&A.y===this.y&&A.z===this.z&&A.w===this.w}fromArray(A,Q=0){return this.x=A[Q],this.y=A[Q+1],this.z=A[Q+2],this.w=A[Q+3],this}toArray(A=[],Q=0){return A[Q]=this.x,A[Q+1]=this.y,A[Q+2]=this.z,A[Q+3]=this.w,A}fromBufferAttribute(A,Q){return this.x=A.getX(Q),this.y=A.getY(Q),this.z=A.getZ(Q),this.w=A.getW(Q),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class UC extends y9{constructor(A=1,Q=1,J={}){super();this.isRenderTarget=!0,this.width=A,this.height=Q,this.depth=1,this.scissor=new X0(0,0,A,Q),this.scissorTest=!1,this.viewport=new X0(0,0,A,Q);let K={width:A,height:Q,depth:1};J=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:1006,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},J);let C=new J2(K,J.mapping,J.wrapS,J.wrapT,J.magFilter,J.minFilter,J.format,J.type,J.anisotropy,J.colorSpace);C.flipY=!1,C.generateMipmaps=J.generateMipmaps,C.internalFormat=J.internalFormat,this.textures=[];let U=J.count;for(let Y=0;Y=0?1:-1,R=1-D*D;if(R>Number.EPSILON){let T=Math.sqrt(R),h=Math.atan2(T,D*L);V=Math.sin(V*h)/T,Y=Math.sin(Y*h)/T}let M=Y*L;if(Z=Z*V+$*M,X=X*V+I*M,E=E*V+N*M,H=H*V+F*M,V===1-Y){let T=1/Math.sqrt(Z*Z+X*X+E*E+H*H);Z*=T,X*=T,E*=T,H*=T}}A[Q]=Z,A[Q+1]=X,A[Q+2]=E,A[Q+3]=H}static multiplyQuaternionsFlat(A,Q,J,K,C,U){let Y=J[K],Z=J[K+1],X=J[K+2],E=J[K+3],H=C[U],$=C[U+1],I=C[U+2],N=C[U+3];return A[Q]=Y*N+E*H+Z*I-X*$,A[Q+1]=Z*N+E*$+X*H-Y*I,A[Q+2]=X*N+E*I+Y*$-Z*H,A[Q+3]=E*N-Y*H-Z*$-X*I,A}get x(){return this._x}set x(A){this._x=A,this._onChangeCallback()}get y(){return this._y}set y(A){this._y=A,this._onChangeCallback()}get z(){return this._z}set z(A){this._z=A,this._onChangeCallback()}get w(){return this._w}set w(A){this._w=A,this._onChangeCallback()}set(A,Q,J,K){return this._x=A,this._y=Q,this._z=J,this._w=K,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(A){return this._x=A.x,this._y=A.y,this._z=A.z,this._w=A.w,this._onChangeCallback(),this}setFromEuler(A,Q=!0){let{_x:J,_y:K,_z:C,_order:U}=A,Y=Math.cos,Z=Math.sin,X=Y(J/2),E=Y(K/2),H=Y(C/2),$=Z(J/2),I=Z(K/2),N=Z(C/2);switch(U){case"XYZ":this._x=$*E*H+X*I*N,this._y=X*I*H-$*E*N,this._z=X*E*N+$*I*H,this._w=X*E*H-$*I*N;break;case"YXZ":this._x=$*E*H+X*I*N,this._y=X*I*H-$*E*N,this._z=X*E*N-$*I*H,this._w=X*E*H+$*I*N;break;case"ZXY":this._x=$*E*H-X*I*N,this._y=X*I*H+$*E*N,this._z=X*E*N+$*I*H,this._w=X*E*H-$*I*N;break;case"ZYX":this._x=$*E*H-X*I*N,this._y=X*I*H+$*E*N,this._z=X*E*N-$*I*H,this._w=X*E*H+$*I*N;break;case"YZX":this._x=$*E*H+X*I*N,this._y=X*I*H+$*E*N,this._z=X*E*N-$*I*H,this._w=X*E*H-$*I*N;break;case"XZY":this._x=$*E*H-X*I*N,this._y=X*I*H-$*E*N,this._z=X*E*N+$*I*H,this._w=X*E*H+$*I*N;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+U)}if(Q===!0)this._onChangeCallback();return this}setFromAxisAngle(A,Q){let J=Q/2,K=Math.sin(J);return this._x=A.x*K,this._y=A.y*K,this._z=A.z*K,this._w=Math.cos(J),this._onChangeCallback(),this}setFromRotationMatrix(A){let Q=A.elements,J=Q[0],K=Q[4],C=Q[8],U=Q[1],Y=Q[5],Z=Q[9],X=Q[2],E=Q[6],H=Q[10],$=J+Y+H;if($>0){let I=0.5/Math.sqrt($+1);this._w=0.25/I,this._x=(E-Z)*I,this._y=(C-X)*I,this._z=(U-K)*I}else if(J>Y&&J>H){let I=2*Math.sqrt(1+J-Y-H);this._w=(E-Z)/I,this._x=0.25*I,this._y=(K+U)/I,this._z=(C+X)/I}else if(Y>H){let I=2*Math.sqrt(1+Y-J-H);this._w=(C-X)/I,this._x=(K+U)/I,this._y=0.25*I,this._z=(Z+E)/I}else{let I=2*Math.sqrt(1+H-J-Y);this._w=(U-K)/I,this._x=(C+X)/I,this._y=(Z+E)/I,this._z=0.25*I}return this._onChangeCallback(),this}setFromUnitVectors(A,Q){let J=A.dot(Q)+1;if(JMath.abs(A.z))this._x=-A.y,this._y=A.x,this._z=0,this._w=J;else this._x=0,this._y=-A.z,this._z=A.y,this._w=J;else this._x=A.y*Q.z-A.z*Q.y,this._y=A.z*Q.x-A.x*Q.z,this._z=A.x*Q.y-A.y*Q.x,this._w=J;return this.normalize()}angleTo(A){return 2*Math.acos(Math.abs(zA(this.dot(A),-1,1)))}rotateTowards(A,Q){let J=this.angleTo(A);if(J===0)return this;let K=Math.min(1,Q/J);return this.slerp(A,K),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(A){return this._x*A._x+this._y*A._y+this._z*A._z+this._w*A._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let A=this.length();if(A===0)this._x=0,this._y=0,this._z=0,this._w=1;else A=1/A,this._x=this._x*A,this._y=this._y*A,this._z=this._z*A,this._w=this._w*A;return this._onChangeCallback(),this}multiply(A){return this.multiplyQuaternions(this,A)}premultiply(A){return this.multiplyQuaternions(A,this)}multiplyQuaternions(A,Q){let{_x:J,_y:K,_z:C,_w:U}=A,Y=Q._x,Z=Q._y,X=Q._z,E=Q._w;return this._x=J*E+U*Y+K*X-C*Z,this._y=K*E+U*Z+C*Y-J*X,this._z=C*E+U*X+J*Z-K*Y,this._w=U*E-J*Y-K*Z-C*X,this._onChangeCallback(),this}slerp(A,Q){if(Q===0)return this;if(Q===1)return this.copy(A);let J=this._x,K=this._y,C=this._z,U=this._w,Y=U*A._w+J*A._x+K*A._y+C*A._z;if(Y<0)this._w=-A._w,this._x=-A._x,this._y=-A._y,this._z=-A._z,Y=-Y;else this.copy(A);if(Y>=1)return this._w=U,this._x=J,this._y=K,this._z=C,this;let Z=1-Y*Y;if(Z<=Number.EPSILON){let I=1-Q;return this._w=I*U+Q*this._w,this._x=I*J+Q*this._x,this._y=I*K+Q*this._y,this._z=I*C+Q*this._z,this.normalize(),this}let X=Math.sqrt(Z),E=Math.atan2(X,Y),H=Math.sin((1-Q)*E)/X,$=Math.sin(Q*E)/X;return this._w=U*H+this._w*$,this._x=J*H+this._x*$,this._y=K*H+this._y*$,this._z=C*H+this._z*$,this._onChangeCallback(),this}slerpQuaternions(A,Q,J){return this.copy(A).slerp(Q,J)}random(){let A=2*Math.PI*Math.random(),Q=2*Math.PI*Math.random(),J=Math.random(),K=Math.sqrt(1-J),C=Math.sqrt(J);return this.set(K*Math.sin(A),K*Math.cos(A),C*Math.sin(Q),C*Math.cos(Q))}equals(A){return A._x===this._x&&A._y===this._y&&A._z===this._z&&A._w===this._w}fromArray(A,Q=0){return this._x=A[Q],this._y=A[Q+1],this._z=A[Q+2],this._w=A[Q+3],this._onChangeCallback(),this}toArray(A=[],Q=0){return A[Q]=this._x,A[Q+1]=this._y,A[Q+2]=this._z,A[Q+3]=this._w,A}fromBufferAttribute(A,Q){return this._x=A.getX(Q),this._y=A.getY(Q),this._z=A.getZ(Q),this._w=A.getW(Q),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(A){return this._onChangeCallback=A,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class I1{constructor(A=0,Q=0,J=0){I1.prototype.isVector3=!0,this.x=A,this.y=Q,this.z=J}set(A,Q,J){if(J===void 0)J=this.z;return this.x=A,this.y=Q,this.z=J,this}setScalar(A){return this.x=A,this.y=A,this.z=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setZ(A){return this.z=A,this}setComponent(A,Q){switch(A){case 0:this.x=Q;break;case 1:this.y=Q;break;case 2:this.z=Q;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(A){return this.x=A.x,this.y=A.y,this.z=A.z,this}add(A){return this.x+=A.x,this.y+=A.y,this.z+=A.z,this}addScalar(A){return this.x+=A,this.y+=A,this.z+=A,this}addVectors(A,Q){return this.x=A.x+Q.x,this.y=A.y+Q.y,this.z=A.z+Q.z,this}addScaledVector(A,Q){return this.x+=A.x*Q,this.y+=A.y*Q,this.z+=A.z*Q,this}sub(A){return this.x-=A.x,this.y-=A.y,this.z-=A.z,this}subScalar(A){return this.x-=A,this.y-=A,this.z-=A,this}subVectors(A,Q){return this.x=A.x-Q.x,this.y=A.y-Q.y,this.z=A.z-Q.z,this}multiply(A){return this.x*=A.x,this.y*=A.y,this.z*=A.z,this}multiplyScalar(A){return this.x*=A,this.y*=A,this.z*=A,this}multiplyVectors(A,Q){return this.x=A.x*Q.x,this.y=A.y*Q.y,this.z=A.z*Q.z,this}applyEuler(A){return this.applyQuaternion(hy.setFromEuler(A))}applyAxisAngle(A,Q){return this.applyQuaternion(hy.setFromAxisAngle(A,Q))}applyMatrix3(A){let Q=this.x,J=this.y,K=this.z,C=A.elements;return this.x=C[0]*Q+C[3]*J+C[6]*K,this.y=C[1]*Q+C[4]*J+C[7]*K,this.z=C[2]*Q+C[5]*J+C[8]*K,this}applyNormalMatrix(A){return this.applyMatrix3(A).normalize()}applyMatrix4(A){let Q=this.x,J=this.y,K=this.z,C=A.elements,U=1/(C[3]*Q+C[7]*J+C[11]*K+C[15]);return this.x=(C[0]*Q+C[4]*J+C[8]*K+C[12])*U,this.y=(C[1]*Q+C[5]*J+C[9]*K+C[13])*U,this.z=(C[2]*Q+C[6]*J+C[10]*K+C[14])*U,this}applyQuaternion(A){let Q=this.x,J=this.y,K=this.z,C=A.x,U=A.y,Y=A.z,Z=A.w,X=2*(U*K-Y*J),E=2*(Y*Q-C*K),H=2*(C*J-U*Q);return this.x=Q+Z*X+U*H-Y*E,this.y=J+Z*E+Y*X-C*H,this.z=K+Z*H+C*E-U*X,this}project(A){return this.applyMatrix4(A.matrixWorldInverse).applyMatrix4(A.projectionMatrix)}unproject(A){return this.applyMatrix4(A.projectionMatrixInverse).applyMatrix4(A.matrixWorld)}transformDirection(A){let Q=this.x,J=this.y,K=this.z,C=A.elements;return this.x=C[0]*Q+C[4]*J+C[8]*K,this.y=C[1]*Q+C[5]*J+C[9]*K,this.z=C[2]*Q+C[6]*J+C[10]*K,this.normalize()}divide(A){return this.x/=A.x,this.y/=A.y,this.z/=A.z,this}divideScalar(A){return this.multiplyScalar(1/A)}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this.z=Math.min(this.z,A.z),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this.z=Math.max(this.z,A.z),this}clamp(A,Q){return this.x=zA(this.x,A.x,Q.x),this.y=zA(this.y,A.y,Q.y),this.z=zA(this.z,A.z,Q.z),this}clampScalar(A,Q){return this.x=zA(this.x,A,Q),this.y=zA(this.y,A,Q),this.z=zA(this.z,A,Q),this}clampLength(A,Q){let J=this.length();return this.divideScalar(J||1).multiplyScalar(zA(J,A,Q))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(A){return this.x*A.x+this.y*A.y+this.z*A.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(A){return this.normalize().multiplyScalar(A)}lerp(A,Q){return this.x+=(A.x-this.x)*Q,this.y+=(A.y-this.y)*Q,this.z+=(A.z-this.z)*Q,this}lerpVectors(A,Q,J){return this.x=A.x+(Q.x-A.x)*J,this.y=A.y+(Q.y-A.y)*J,this.z=A.z+(Q.z-A.z)*J,this}cross(A){return this.crossVectors(this,A)}crossVectors(A,Q){let{x:J,y:K,z:C}=A,U=Q.x,Y=Q.y,Z=Q.z;return this.x=K*Z-C*Y,this.y=C*U-J*Z,this.z=J*Y-K*U,this}projectOnVector(A){let Q=A.lengthSq();if(Q===0)return this.set(0,0,0);let J=A.dot(this)/Q;return this.copy(A).multiplyScalar(J)}projectOnPlane(A){return XL.copy(this).projectOnVector(A),this.sub(XL)}reflect(A){return this.sub(XL.copy(A).multiplyScalar(2*this.dot(A)))}angleTo(A){let Q=Math.sqrt(this.lengthSq()*A.lengthSq());if(Q===0)return Math.PI/2;let J=this.dot(A)/Q;return Math.acos(zA(J,-1,1))}distanceTo(A){return Math.sqrt(this.distanceToSquared(A))}distanceToSquared(A){let Q=this.x-A.x,J=this.y-A.y,K=this.z-A.z;return Q*Q+J*J+K*K}manhattanDistanceTo(A){return Math.abs(this.x-A.x)+Math.abs(this.y-A.y)+Math.abs(this.z-A.z)}setFromSpherical(A){return this.setFromSphericalCoords(A.radius,A.phi,A.theta)}setFromSphericalCoords(A,Q,J){let K=Math.sin(Q)*A;return this.x=K*Math.sin(J),this.y=Math.cos(Q)*A,this.z=K*Math.cos(J),this}setFromCylindrical(A){return this.setFromCylindricalCoords(A.radius,A.theta,A.y)}setFromCylindricalCoords(A,Q,J){return this.x=A*Math.sin(Q),this.y=J,this.z=A*Math.cos(Q),this}setFromMatrixPosition(A){let Q=A.elements;return this.x=Q[12],this.y=Q[13],this.z=Q[14],this}setFromMatrixScale(A){let Q=this.setFromMatrixColumn(A,0).length(),J=this.setFromMatrixColumn(A,1).length(),K=this.setFromMatrixColumn(A,2).length();return this.x=Q,this.y=J,this.z=K,this}setFromMatrixColumn(A,Q){return this.fromArray(A.elements,Q*4)}setFromMatrix3Column(A,Q){return this.fromArray(A.elements,Q*3)}setFromEuler(A){return this.x=A._x,this.y=A._y,this.z=A._z,this}setFromColor(A){return this.x=A.r,this.y=A.g,this.z=A.b,this}equals(A){return A.x===this.x&&A.y===this.y&&A.z===this.z}fromArray(A,Q=0){return this.x=A[Q],this.y=A[Q+1],this.z=A[Q+2],this}toArray(A=[],Q=0){return A[Q]=this.x,A[Q+1]=this.y,A[Q+2]=this.z,A}fromBufferAttribute(A,Q){return this.x=A.getX(Q),this.y=A.getY(Q),this.z=A.getZ(Q),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let A=Math.random()*Math.PI*2,Q=Math.random()*2-1,J=Math.sqrt(1-Q*Q);return this.x=J*Math.cos(A),this.y=Q,this.z=J*Math.sin(A),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}var XL=/*@__PURE__*/new I1,hy=/*@__PURE__*/new t0;class DA{constructor(A=new I1(1/0,1/0,1/0),Q=new I1(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=A,this.max=Q}set(A,Q){return this.min.copy(A),this.max.copy(Q),this}setFromArray(A){this.makeEmpty();for(let Q=0,J=A.length;Q=this.min.x&&A.x<=this.max.x&&A.y>=this.min.y&&A.y<=this.max.y&&A.z>=this.min.z&&A.z<=this.max.z}containsBox(A){return this.min.x<=A.min.x&&A.max.x<=this.max.x&&this.min.y<=A.min.y&&A.max.y<=this.max.y&&this.min.z<=A.min.z&&A.max.z<=this.max.z}getParameter(A,Q){return Q.set((A.x-this.min.x)/(this.max.x-this.min.x),(A.y-this.min.y)/(this.max.y-this.min.y),(A.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(A){return A.max.x>=this.min.x&&A.min.x<=this.max.x&&A.max.y>=this.min.y&&A.min.y<=this.max.y&&A.max.z>=this.min.z&&A.min.z<=this.max.z}intersectsSphere(A){return this.clampPoint(A.center,X5),X5.distanceToSquared(A.center)<=A.radius*A.radius}intersectsPlane(A){let Q,J;if(A.normal.x>0)Q=A.normal.x*this.min.x,J=A.normal.x*this.max.x;else Q=A.normal.x*this.max.x,J=A.normal.x*this.min.x;if(A.normal.y>0)Q+=A.normal.y*this.min.y,J+=A.normal.y*this.max.y;else Q+=A.normal.y*this.max.y,J+=A.normal.y*this.min.y;if(A.normal.z>0)Q+=A.normal.z*this.min.z,J+=A.normal.z*this.max.z;else Q+=A.normal.z*this.max.z,J+=A.normal.z*this.min.z;return Q<=-A.constant&&J>=-A.constant}intersectsTriangle(A){if(this.isEmpty())return!1;this.getCenter(MU),Z$.subVectors(this.max,MU),kK.subVectors(A.a,MU),SK.subVectors(A.b,MU),jK.subVectors(A.c,MU),e7.subVectors(SK,kK),A4.subVectors(jK,SK),EQ.subVectors(kK,jK);let Q=[0,-e7.z,e7.y,0,-A4.z,A4.y,0,-EQ.z,EQ.y,e7.z,0,-e7.x,A4.z,0,-A4.x,EQ.z,0,-EQ.x,-e7.y,e7.x,0,-A4.y,A4.x,0,-EQ.y,EQ.x,0];if(!EL(Q,kK,SK,jK,Z$))return!1;if(Q=[1,0,0,0,1,0,0,0,1],!EL(Q,kK,SK,jK,Z$))return!1;return B$.crossVectors(e7,A4),Q=[B$.x,B$.y,B$.z],EL(Q,kK,SK,jK,Z$)}clampPoint(A,Q){return Q.copy(A).clamp(this.min,this.max)}distanceToPoint(A){return this.clampPoint(A,X5).distanceTo(A)}getBoundingSphere(A){if(this.isEmpty())A.makeEmpty();else this.getCenter(A.center),A.radius=this.getSize(X5).length()*0.5;return A}intersect(A){if(this.min.max(A.min),this.max.min(A.max),this.isEmpty())this.makeEmpty();return this}union(A){return this.min.min(A.min),this.max.max(A.max),this}applyMatrix4(A){if(this.isEmpty())return this;return m3[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(A),m3[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(A),m3[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(A),m3[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(A),m3[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(A),m3[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(A),m3[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(A),m3[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(A),this.setFromPoints(m3),this}translate(A){return this.min.add(A),this.max.add(A),this}equals(A){return A.min.equals(this.min)&&A.max.equals(this.max)}}var m3=[/*@__PURE__*/new I1,/*@__PURE__*/new I1,/*@__PURE__*/new I1,/*@__PURE__*/new I1,/*@__PURE__*/new I1,/*@__PURE__*/new I1,/*@__PURE__*/new I1,/*@__PURE__*/new I1],X5=/*@__PURE__*/new I1,U$=/*@__PURE__*/new DA,kK=/*@__PURE__*/new I1,SK=/*@__PURE__*/new I1,jK=/*@__PURE__*/new I1,e7=/*@__PURE__*/new I1,A4=/*@__PURE__*/new I1,EQ=/*@__PURE__*/new I1,MU=/*@__PURE__*/new I1,Z$=/*@__PURE__*/new I1,B$=/*@__PURE__*/new I1,$Q=/*@__PURE__*/new I1;function EL(A,Q,J,K,C){for(let U=0,Y=A.length-3;U<=Y;U+=3){$Q.fromArray(A,U);let Z=C.x*Math.abs($Q.x)+C.y*Math.abs($Q.y)+C.z*Math.abs($Q.z),X=Q.dot($Q),E=J.dot($Q),H=K.dot($Q);if(Math.max(-Math.max(X,E,H),Math.min(X,E,H))>Z)return!1}return!0}var y51=/*@__PURE__*/new DA,wU=/*@__PURE__*/new I1,$L=/*@__PURE__*/new I1;class O2{constructor(A=new I1,Q=-1){this.isSphere=!0,this.center=A,this.radius=Q}set(A,Q){return this.center.copy(A),this.radius=Q,this}setFromPoints(A,Q){let J=this.center;if(Q!==void 0)J.copy(Q);else y51.setFromPoints(A).getCenter(J);let K=0;for(let C=0,U=A.length;Cthis.radius*this.radius)Q.sub(this.center).normalize(),Q.multiplyScalar(this.radius).add(this.center);return Q}getBoundingBox(A){if(this.isEmpty())return A.makeEmpty(),A;return A.set(this.center,this.center),A.expandByScalar(this.radius),A}applyMatrix4(A){return this.center.applyMatrix4(A),this.radius=this.radius*A.getMaxScaleOnAxis(),this}translate(A){return this.center.add(A),this}expandByPoint(A){if(this.isEmpty())return this.center.copy(A),this.radius=0,this;wU.subVectors(A,this.center);let Q=wU.lengthSq();if(Q>this.radius*this.radius){let J=Math.sqrt(Q),K=(J-this.radius)*0.5;this.center.addScaledVector(wU,K/J),this.radius+=K}return this}union(A){if(A.isEmpty())return this;if(this.isEmpty())return this.copy(A),this;if(this.center.equals(A.center)===!0)this.radius=Math.max(this.radius,A.radius);else $L.subVectors(A.center,this.center).setLength(A.radius),this.expandByPoint(wU.copy(A.center).add($L)),this.expandByPoint(wU.copy(A.center).sub($L));return this}equals(A){return A.center.equals(this.center)&&A.radius===this.radius}clone(){return new this.constructor().copy(this)}}var c3=/*@__PURE__*/new I1,HL=/*@__PURE__*/new I1,X$=/*@__PURE__*/new I1,Q4=/*@__PURE__*/new I1,GL=/*@__PURE__*/new I1,E$=/*@__PURE__*/new I1,WL=/*@__PURE__*/new I1;class f6{constructor(A=new I1,Q=new I1(0,0,-1)){this.origin=A,this.direction=Q}set(A,Q){return this.origin.copy(A),this.direction.copy(Q),this}copy(A){return this.origin.copy(A.origin),this.direction.copy(A.direction),this}at(A,Q){return Q.copy(this.origin).addScaledVector(this.direction,A)}lookAt(A){return this.direction.copy(A).sub(this.origin).normalize(),this}recast(A){return this.origin.copy(this.at(A,c3)),this}closestPointToPoint(A,Q){Q.subVectors(A,this.origin);let J=Q.dot(this.direction);if(J<0)return Q.copy(this.origin);return Q.copy(this.origin).addScaledVector(this.direction,J)}distanceToPoint(A){return Math.sqrt(this.distanceSqToPoint(A))}distanceSqToPoint(A){let Q=c3.subVectors(A,this.origin).dot(this.direction);if(Q<0)return this.origin.distanceToSquared(A);return c3.copy(this.origin).addScaledVector(this.direction,Q),c3.distanceToSquared(A)}distanceSqToSegment(A,Q,J,K){HL.copy(A).add(Q).multiplyScalar(0.5),X$.copy(Q).sub(A).normalize(),Q4.copy(this.origin).sub(HL);let C=A.distanceTo(Q)*0.5,U=-this.direction.dot(X$),Y=Q4.dot(this.direction),Z=-Q4.dot(X$),X=Q4.lengthSq(),E=Math.abs(1-U*U),H,$,I,N;if(E>0)if(H=U*Z-Y,$=U*Y-Z,N=C*E,H>=0)if($>=-N)if($<=N){let F=1/E;H*=F,$*=F,I=H*(H+U*$+2*Y)+$*(U*H+$+2*Z)+X}else $=C,H=Math.max(0,-(U*$+Y)),I=-H*H+$*($+2*Z)+X;else $=-C,H=Math.max(0,-(U*$+Y)),I=-H*H+$*($+2*Z)+X;else if($<=-N)H=Math.max(0,-(-U*C+Y)),$=H>0?-C:Math.min(Math.max(-C,-Z),C),I=-H*H+$*($+2*Z)+X;else if($<=N)H=0,$=Math.min(Math.max(-C,-Z),C),I=$*($+2*Z)+X;else H=Math.max(0,-(U*C+Y)),$=H>0?C:Math.min(Math.max(-C,-Z),C),I=-H*H+$*($+2*Z)+X;else $=U>0?-C:C,H=Math.max(0,-(U*$+Y)),I=-H*H+$*($+2*Z)+X;if(J)J.copy(this.origin).addScaledVector(this.direction,H);if(K)K.copy(HL).addScaledVector(X$,$);return I}intersectSphere(A,Q){c3.subVectors(A.center,this.origin);let J=c3.dot(this.direction),K=c3.dot(c3)-J*J,C=A.radius*A.radius;if(K>C)return null;let U=Math.sqrt(C-K),Y=J-U,Z=J+U;if(Z<0)return null;if(Y<0)return this.at(Z,Q);return this.at(Y,Q)}intersectsSphere(A){return this.distanceSqToPoint(A.center)<=A.radius*A.radius}distanceToPlane(A){let Q=A.normal.dot(this.direction);if(Q===0){if(A.distanceToPoint(this.origin)===0)return 0;return null}let J=-(this.origin.dot(A.normal)+A.constant)/Q;return J>=0?J:null}intersectPlane(A,Q){let J=this.distanceToPlane(A);if(J===null)return null;return this.at(J,Q)}intersectsPlane(A){let Q=A.distanceToPoint(this.origin);if(Q===0)return!0;if(A.normal.dot(this.direction)*Q<0)return!0;return!1}intersectBox(A,Q){let J,K,C,U,Y,Z,X=1/this.direction.x,E=1/this.direction.y,H=1/this.direction.z,$=this.origin;if(X>=0)J=(A.min.x-$.x)*X,K=(A.max.x-$.x)*X;else J=(A.max.x-$.x)*X,K=(A.min.x-$.x)*X;if(E>=0)C=(A.min.y-$.y)*E,U=(A.max.y-$.y)*E;else C=(A.max.y-$.y)*E,U=(A.min.y-$.y)*E;if(J>U||C>K)return null;if(C>J||isNaN(J))J=C;if(U=0)Y=(A.min.z-$.z)*H,Z=(A.max.z-$.z)*H;else Y=(A.max.z-$.z)*H,Z=(A.min.z-$.z)*H;if(J>Z||Y>K)return null;if(Y>J||J!==J)J=Y;if(Z=0?J:K,Q)}intersectsBox(A){return this.intersectBox(A,c3)!==null}intersectTriangle(A,Q,J,K,C){GL.subVectors(Q,A),E$.subVectors(J,A),WL.crossVectors(GL,E$);let U=this.direction.dot(WL),Y;if(U>0){if(K)return null;Y=1}else if(U<0)Y=-1,U=-U;else return null;Q4.subVectors(this.origin,A);let Z=Y*this.direction.dot(E$.crossVectors(Q4,E$));if(Z<0)return null;let X=Y*this.direction.dot(GL.cross(Q4));if(X<0)return null;if(Z+X>U)return null;let E=-Y*Q4.dot(WL);if(E<0)return null;return this.at(E/U,C)}applyMatrix4(A){return this.origin.applyMatrix4(A),this.direction.transformDirection(A),this}equals(A){return A.origin.equals(this.origin)&&A.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Y0{constructor(A,Q,J,K,C,U,Y,Z,X,E,H,$,I,N,F,V){if(Y0.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],A!==void 0)this.set(A,Q,J,K,C,U,Y,Z,X,E,H,$,I,N,F,V)}set(A,Q,J,K,C,U,Y,Z,X,E,H,$,I,N,F,V){let D=this.elements;return D[0]=A,D[4]=Q,D[8]=J,D[12]=K,D[1]=C,D[5]=U,D[9]=Y,D[13]=Z,D[2]=X,D[6]=E,D[10]=H,D[14]=$,D[3]=I,D[7]=N,D[11]=F,D[15]=V,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Y0().fromArray(this.elements)}copy(A){let Q=this.elements,J=A.elements;return Q[0]=J[0],Q[1]=J[1],Q[2]=J[2],Q[3]=J[3],Q[4]=J[4],Q[5]=J[5],Q[6]=J[6],Q[7]=J[7],Q[8]=J[8],Q[9]=J[9],Q[10]=J[10],Q[11]=J[11],Q[12]=J[12],Q[13]=J[13],Q[14]=J[14],Q[15]=J[15],this}copyPosition(A){let Q=this.elements,J=A.elements;return Q[12]=J[12],Q[13]=J[13],Q[14]=J[14],this}setFromMatrix3(A){let Q=A.elements;return this.set(Q[0],Q[3],Q[6],0,Q[1],Q[4],Q[7],0,Q[2],Q[5],Q[8],0,0,0,0,1),this}extractBasis(A,Q,J){return A.setFromMatrixColumn(this,0),Q.setFromMatrixColumn(this,1),J.setFromMatrixColumn(this,2),this}makeBasis(A,Q,J){return this.set(A.x,Q.x,J.x,0,A.y,Q.y,J.y,0,A.z,Q.z,J.z,0,0,0,0,1),this}extractRotation(A){let Q=this.elements,J=A.elements,K=1/vK.setFromMatrixColumn(A,0).length(),C=1/vK.setFromMatrixColumn(A,1).length(),U=1/vK.setFromMatrixColumn(A,2).length();return Q[0]=J[0]*K,Q[1]=J[1]*K,Q[2]=J[2]*K,Q[3]=0,Q[4]=J[4]*C,Q[5]=J[5]*C,Q[6]=J[6]*C,Q[7]=0,Q[8]=J[8]*U,Q[9]=J[9]*U,Q[10]=J[10]*U,Q[11]=0,Q[12]=0,Q[13]=0,Q[14]=0,Q[15]=1,this}makeRotationFromEuler(A){let Q=this.elements,J=A.x,K=A.y,C=A.z,U=Math.cos(J),Y=Math.sin(J),Z=Math.cos(K),X=Math.sin(K),E=Math.cos(C),H=Math.sin(C);if(A.order==="XYZ"){let $=U*E,I=U*H,N=Y*E,F=Y*H;Q[0]=Z*E,Q[4]=-Z*H,Q[8]=X,Q[1]=I+N*X,Q[5]=$-F*X,Q[9]=-Y*Z,Q[2]=F-$*X,Q[6]=N+I*X,Q[10]=U*Z}else if(A.order==="YXZ"){let $=Z*E,I=Z*H,N=X*E,F=X*H;Q[0]=$+F*Y,Q[4]=N*Y-I,Q[8]=U*X,Q[1]=U*H,Q[5]=U*E,Q[9]=-Y,Q[2]=I*Y-N,Q[6]=F+$*Y,Q[10]=U*Z}else if(A.order==="ZXY"){let $=Z*E,I=Z*H,N=X*E,F=X*H;Q[0]=$-F*Y,Q[4]=-U*H,Q[8]=N+I*Y,Q[1]=I+N*Y,Q[5]=U*E,Q[9]=F-$*Y,Q[2]=-U*X,Q[6]=Y,Q[10]=U*Z}else if(A.order==="ZYX"){let $=U*E,I=U*H,N=Y*E,F=Y*H;Q[0]=Z*E,Q[4]=N*X-I,Q[8]=$*X+F,Q[1]=Z*H,Q[5]=F*X+$,Q[9]=I*X-N,Q[2]=-X,Q[6]=Y*Z,Q[10]=U*Z}else if(A.order==="YZX"){let $=U*Z,I=U*X,N=Y*Z,F=Y*X;Q[0]=Z*E,Q[4]=F-$*H,Q[8]=N*H+I,Q[1]=H,Q[5]=U*E,Q[9]=-Y*E,Q[2]=-X*E,Q[6]=I*H+N,Q[10]=$-F*H}else if(A.order==="XZY"){let $=U*Z,I=U*X,N=Y*Z,F=Y*X;Q[0]=Z*E,Q[4]=-H,Q[8]=X*E,Q[1]=$*H+F,Q[5]=U*E,Q[9]=I*H-N,Q[2]=N*H-I,Q[6]=Y*E,Q[10]=F*H+$}return Q[3]=0,Q[7]=0,Q[11]=0,Q[12]=0,Q[13]=0,Q[14]=0,Q[15]=1,this}makeRotationFromQuaternion(A){return this.compose(h51,A,g51)}lookAt(A,Q,J){let K=this.elements;if(A9.subVectors(A,Q),A9.lengthSq()===0)A9.z=1;if(A9.normalize(),J4.crossVectors(J,A9),J4.lengthSq()===0){if(Math.abs(J.z)===1)A9.x+=0.0001;else A9.z+=0.0001;A9.normalize(),J4.crossVectors(J,A9)}return J4.normalize(),$$.crossVectors(A9,J4),K[0]=J4.x,K[4]=$$.x,K[8]=A9.x,K[1]=J4.y,K[5]=$$.y,K[9]=A9.y,K[2]=J4.z,K[6]=$$.z,K[10]=A9.z,this}multiply(A){return this.multiplyMatrices(this,A)}premultiply(A){return this.multiplyMatrices(A,this)}multiplyMatrices(A,Q){let J=A.elements,K=Q.elements,C=this.elements,U=J[0],Y=J[4],Z=J[8],X=J[12],E=J[1],H=J[5],$=J[9],I=J[13],N=J[2],F=J[6],V=J[10],D=J[14],L=J[3],R=J[7],M=J[11],T=J[15],h=K[0],y=K[4],g=K[8],f=K[12],u=K[1],d=K[5],n=K[9],B=K[13],q=K[2],P=K[6],O=K[10],w=K[14],k=K[3],S=K[7],_=K[11],W=K[15];return C[0]=U*h+Y*u+Z*q+X*k,C[4]=U*y+Y*d+Z*P+X*S,C[8]=U*g+Y*n+Z*O+X*_,C[12]=U*f+Y*B+Z*w+X*W,C[1]=E*h+H*u+$*q+I*k,C[5]=E*y+H*d+$*P+I*S,C[9]=E*g+H*n+$*O+I*_,C[13]=E*f+H*B+$*w+I*W,C[2]=N*h+F*u+V*q+D*k,C[6]=N*y+F*d+V*P+D*S,C[10]=N*g+F*n+V*O+D*_,C[14]=N*f+F*B+V*w+D*W,C[3]=L*h+R*u+M*q+T*k,C[7]=L*y+R*d+M*P+T*S,C[11]=L*g+R*n+M*O+T*_,C[15]=L*f+R*B+M*w+T*W,this}multiplyScalar(A){let Q=this.elements;return Q[0]*=A,Q[4]*=A,Q[8]*=A,Q[12]*=A,Q[1]*=A,Q[5]*=A,Q[9]*=A,Q[13]*=A,Q[2]*=A,Q[6]*=A,Q[10]*=A,Q[14]*=A,Q[3]*=A,Q[7]*=A,Q[11]*=A,Q[15]*=A,this}determinant(){let A=this.elements,Q=A[0],J=A[4],K=A[8],C=A[12],U=A[1],Y=A[5],Z=A[9],X=A[13],E=A[2],H=A[6],$=A[10],I=A[14],N=A[3],F=A[7],V=A[11],D=A[15];return N*(+C*Z*H-K*X*H-C*Y*$+J*X*$+K*Y*I-J*Z*I)+F*(+Q*Z*I-Q*X*$+C*U*$-K*U*I+K*X*E-C*Z*E)+V*(+Q*X*H-Q*Y*I-C*U*H+J*U*I+C*Y*E-J*X*E)+D*(-K*Y*E-Q*Z*H+Q*Y*$+K*U*H-J*U*$+J*Z*E)}transpose(){let A=this.elements,Q;return Q=A[1],A[1]=A[4],A[4]=Q,Q=A[2],A[2]=A[8],A[8]=Q,Q=A[6],A[6]=A[9],A[9]=Q,Q=A[3],A[3]=A[12],A[12]=Q,Q=A[7],A[7]=A[13],A[13]=Q,Q=A[11],A[11]=A[14],A[14]=Q,this}setPosition(A,Q,J){let K=this.elements;if(A.isVector3)K[12]=A.x,K[13]=A.y,K[14]=A.z;else K[12]=A,K[13]=Q,K[14]=J;return this}invert(){let A=this.elements,Q=A[0],J=A[1],K=A[2],C=A[3],U=A[4],Y=A[5],Z=A[6],X=A[7],E=A[8],H=A[9],$=A[10],I=A[11],N=A[12],F=A[13],V=A[14],D=A[15],L=H*V*X-F*$*X+F*Z*I-Y*V*I-H*Z*D+Y*$*D,R=N*$*X-E*V*X-N*Z*I+U*V*I+E*Z*D-U*$*D,M=E*F*X-N*H*X+N*Y*I-U*F*I-E*Y*D+U*H*D,T=N*H*Z-E*F*Z-N*Y*$+U*F*$+E*Y*V-U*H*V,h=Q*L+J*R+K*M+C*T;if(h===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let y=1/h;return A[0]=L*y,A[1]=(F*$*C-H*V*C-F*K*I+J*V*I+H*K*D-J*$*D)*y,A[2]=(Y*V*C-F*Z*C+F*K*X-J*V*X-Y*K*D+J*Z*D)*y,A[3]=(H*Z*C-Y*$*C-H*K*X+J*$*X+Y*K*I-J*Z*I)*y,A[4]=R*y,A[5]=(E*V*C-N*$*C+N*K*I-Q*V*I-E*K*D+Q*$*D)*y,A[6]=(N*Z*C-U*V*C-N*K*X+Q*V*X+U*K*D-Q*Z*D)*y,A[7]=(U*$*C-E*Z*C+E*K*X-Q*$*X-U*K*I+Q*Z*I)*y,A[8]=M*y,A[9]=(N*H*C-E*F*C-N*J*I+Q*F*I+E*J*D-Q*H*D)*y,A[10]=(U*F*C-N*Y*C+N*J*X-Q*F*X-U*J*D+Q*Y*D)*y,A[11]=(E*Y*C-U*H*C-E*J*X+Q*H*X+U*J*I-Q*Y*I)*y,A[12]=T*y,A[13]=(E*F*K-N*H*K+N*J*$-Q*F*$-E*J*V+Q*H*V)*y,A[14]=(N*Y*K-U*F*K-N*J*Z+Q*F*Z+U*J*V-Q*Y*V)*y,A[15]=(U*H*K-E*Y*K+E*J*Z-Q*H*Z-U*J*$+Q*Y*$)*y,this}scale(A){let Q=this.elements,J=A.x,K=A.y,C=A.z;return Q[0]*=J,Q[4]*=K,Q[8]*=C,Q[1]*=J,Q[5]*=K,Q[9]*=C,Q[2]*=J,Q[6]*=K,Q[10]*=C,Q[3]*=J,Q[7]*=K,Q[11]*=C,this}getMaxScaleOnAxis(){let A=this.elements,Q=A[0]*A[0]+A[1]*A[1]+A[2]*A[2],J=A[4]*A[4]+A[5]*A[5]+A[6]*A[6],K=A[8]*A[8]+A[9]*A[9]+A[10]*A[10];return Math.sqrt(Math.max(Q,J,K))}makeTranslation(A,Q,J){if(A.isVector3)this.set(1,0,0,A.x,0,1,0,A.y,0,0,1,A.z,0,0,0,1);else this.set(1,0,0,A,0,1,0,Q,0,0,1,J,0,0,0,1);return this}makeRotationX(A){let Q=Math.cos(A),J=Math.sin(A);return this.set(1,0,0,0,0,Q,-J,0,0,J,Q,0,0,0,0,1),this}makeRotationY(A){let Q=Math.cos(A),J=Math.sin(A);return this.set(Q,0,J,0,0,1,0,0,-J,0,Q,0,0,0,0,1),this}makeRotationZ(A){let Q=Math.cos(A),J=Math.sin(A);return this.set(Q,-J,0,0,J,Q,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(A,Q){let J=Math.cos(Q),K=Math.sin(Q),C=1-J,U=A.x,Y=A.y,Z=A.z,X=C*U,E=C*Y;return this.set(X*U+J,X*Y-K*Z,X*Z+K*Y,0,X*Y+K*Z,E*Y+J,E*Z-K*U,0,X*Z-K*Y,E*Z+K*U,C*Z*Z+J,0,0,0,0,1),this}makeScale(A,Q,J){return this.set(A,0,0,0,0,Q,0,0,0,0,J,0,0,0,0,1),this}makeShear(A,Q,J,K,C,U){return this.set(1,J,C,0,A,1,U,0,Q,K,1,0,0,0,0,1),this}compose(A,Q,J){let K=this.elements,C=Q._x,U=Q._y,Y=Q._z,Z=Q._w,X=C+C,E=U+U,H=Y+Y,$=C*X,I=C*E,N=C*H,F=U*E,V=U*H,D=Y*H,L=Z*X,R=Z*E,M=Z*H,T=J.x,h=J.y,y=J.z;return K[0]=(1-(F+D))*T,K[1]=(I+M)*T,K[2]=(N-R)*T,K[3]=0,K[4]=(I-M)*h,K[5]=(1-($+D))*h,K[6]=(V+L)*h,K[7]=0,K[8]=(N+R)*y,K[9]=(V-L)*y,K[10]=(1-($+F))*y,K[11]=0,K[12]=A.x,K[13]=A.y,K[14]=A.z,K[15]=1,this}decompose(A,Q,J){let K=this.elements,C=vK.set(K[0],K[1],K[2]).length(),U=vK.set(K[4],K[5],K[6]).length(),Y=vK.set(K[8],K[9],K[10]).length();if(this.determinant()<0)C=-C;A.x=K[12],A.y=K[13],A.z=K[14],E5.copy(this);let X=1/C,E=1/U,H=1/Y;return E5.elements[0]*=X,E5.elements[1]*=X,E5.elements[2]*=X,E5.elements[4]*=E,E5.elements[5]*=E,E5.elements[6]*=E,E5.elements[8]*=H,E5.elements[9]*=H,E5.elements[10]*=H,Q.setFromRotationMatrix(E5),J.x=C,J.y=U,J.z=Y,this}makePerspective(A,Q,J,K,C,U,Y=2000){let Z=this.elements,X=2*C/(Q-A),E=2*C/(J-K),H=(Q+A)/(Q-A),$=(J+K)/(J-K),I,N;if(Y===2000)I=-(U+C)/(U-C),N=-2*U*C/(U-C);else if(Y===2001)I=-U/(U-C),N=-U*C/(U-C);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+Y);return Z[0]=X,Z[4]=0,Z[8]=H,Z[12]=0,Z[1]=0,Z[5]=E,Z[9]=$,Z[13]=0,Z[2]=0,Z[6]=0,Z[10]=I,Z[14]=N,Z[3]=0,Z[7]=0,Z[11]=-1,Z[15]=0,this}makeOrthographic(A,Q,J,K,C,U,Y=2000){let Z=this.elements,X=1/(Q-A),E=1/(J-K),H=1/(U-C),$=(Q+A)*X,I=(J+K)*E,N,F;if(Y===2000)N=(U+C)*H,F=-2*H;else if(Y===2001)N=C*H,F=-1*H;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+Y);return Z[0]=2*X,Z[4]=0,Z[8]=0,Z[12]=-$,Z[1]=0,Z[5]=2*E,Z[9]=0,Z[13]=-I,Z[2]=0,Z[6]=0,Z[10]=F,Z[14]=-N,Z[3]=0,Z[7]=0,Z[11]=0,Z[15]=1,this}equals(A){let Q=this.elements,J=A.elements;for(let K=0;K<16;K++)if(Q[K]!==J[K])return!1;return!0}fromArray(A,Q=0){for(let J=0;J<16;J++)this.elements[J]=A[J+Q];return this}toArray(A=[],Q=0){let J=this.elements;return A[Q]=J[0],A[Q+1]=J[1],A[Q+2]=J[2],A[Q+3]=J[3],A[Q+4]=J[4],A[Q+5]=J[5],A[Q+6]=J[6],A[Q+7]=J[7],A[Q+8]=J[8],A[Q+9]=J[9],A[Q+10]=J[10],A[Q+11]=J[11],A[Q+12]=J[12],A[Q+13]=J[13],A[Q+14]=J[14],A[Q+15]=J[15],A}}var vK=/*@__PURE__*/new I1,E5=/*@__PURE__*/new Y0,h51=/*@__PURE__*/new I1(0,0,0),g51=/*@__PURE__*/new I1(1,1,1),J4=/*@__PURE__*/new I1,$$=/*@__PURE__*/new I1,A9=/*@__PURE__*/new I1,gy=/*@__PURE__*/new Y0,by=/*@__PURE__*/new t0;class t2{constructor(A=0,Q=0,J=0,K=t2.DEFAULT_ORDER){this.isEuler=!0,this._x=A,this._y=Q,this._z=J,this._order=K}get x(){return this._x}set x(A){this._x=A,this._onChangeCallback()}get y(){return this._y}set y(A){this._y=A,this._onChangeCallback()}get z(){return this._z}set z(A){this._z=A,this._onChangeCallback()}get order(){return this._order}set order(A){this._order=A,this._onChangeCallback()}set(A,Q,J,K=this._order){return this._x=A,this._y=Q,this._z=J,this._order=K,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(A){return this._x=A._x,this._y=A._y,this._z=A._z,this._order=A._order,this._onChangeCallback(),this}setFromRotationMatrix(A,Q=this._order,J=!0){let K=A.elements,C=K[0],U=K[4],Y=K[8],Z=K[1],X=K[5],E=K[9],H=K[2],$=K[6],I=K[10];switch(Q){case"XYZ":if(this._y=Math.asin(zA(Y,-1,1)),Math.abs(Y)<0.9999999)this._x=Math.atan2(-E,I),this._z=Math.atan2(-U,C);else this._x=Math.atan2($,X),this._z=0;break;case"YXZ":if(this._x=Math.asin(-zA(E,-1,1)),Math.abs(E)<0.9999999)this._y=Math.atan2(Y,I),this._z=Math.atan2(Z,X);else this._y=Math.atan2(-H,C),this._z=0;break;case"ZXY":if(this._x=Math.asin(zA($,-1,1)),Math.abs($)<0.9999999)this._y=Math.atan2(-H,I),this._z=Math.atan2(-U,X);else this._y=0,this._z=Math.atan2(Z,C);break;case"ZYX":if(this._y=Math.asin(-zA(H,-1,1)),Math.abs(H)<0.9999999)this._x=Math.atan2($,I),this._z=Math.atan2(Z,C);else this._x=0,this._z=Math.atan2(-U,X);break;case"YZX":if(this._z=Math.asin(zA(Z,-1,1)),Math.abs(Z)<0.9999999)this._x=Math.atan2(-E,X),this._y=Math.atan2(-H,C);else this._x=0,this._y=Math.atan2(Y,I);break;case"XZY":if(this._z=Math.asin(-zA(U,-1,1)),Math.abs(U)<0.9999999)this._x=Math.atan2($,X),this._y=Math.atan2(Y,C);else this._x=Math.atan2(-E,I),this._y=0;break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+Q)}if(this._order=Q,J===!0)this._onChangeCallback();return this}setFromQuaternion(A,Q,J){return gy.makeRotationFromQuaternion(A),this.setFromRotationMatrix(gy,Q,J)}setFromVector3(A,Q=this._order){return this.set(A.x,A.y,A.z,Q)}reorder(A){return by.setFromEuler(this),this.setFromQuaternion(by,A)}equals(A){return A._x===this._x&&A._y===this._y&&A._z===this._z&&A._order===this._order}fromArray(A){if(this._x=A[0],this._y=A[1],this._z=A[2],A[3]!==void 0)this._order=A[3];return this._onChangeCallback(),this}toArray(A=[],Q=0){return A[Q]=this._x,A[Q+1]=this._y,A[Q+2]=this._z,A[Q+3]=this._order,A}_onChange(A){return this._onChangeCallback=A,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}t2.DEFAULT_ORDER="XYZ";class uQ{constructor(){this.mask=1}set(A){this.mask=(1<>>0}enable(A){this.mask|=1<1){for(let Q=0;Q1){for(let J=0;J0)K.userData=this.userData;if(K.layers=this.layers.mask,K.matrix=this.matrix.toArray(),K.up=this.up.toArray(),this.matrixAutoUpdate===!1)K.matrixAutoUpdate=!1;if(this.isInstancedMesh){if(K.type="InstancedMesh",K.count=this.count,K.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null)K.instanceColor=this.instanceColor.toJSON()}if(this.isBatchedMesh){if(K.type="BatchedMesh",K.perObjectFrustumCulled=this.perObjectFrustumCulled,K.sortObjects=this.sortObjects,K.drawRanges=this._drawRanges,K.reservedRanges=this._reservedRanges,K.visibility=this._visibility,K.active=this._active,K.bounds=this._bounds.map((Y)=>({boxInitialized:Y.boxInitialized,boxMin:Y.box.min.toArray(),boxMax:Y.box.max.toArray(),sphereInitialized:Y.sphereInitialized,sphereRadius:Y.sphere.radius,sphereCenter:Y.sphere.center.toArray()})),K.maxInstanceCount=this._maxInstanceCount,K.maxVertexCount=this._maxVertexCount,K.maxIndexCount=this._maxIndexCount,K.geometryInitialized=this._geometryInitialized,K.geometryCount=this._geometryCount,K.matricesTexture=this._matricesTexture.toJSON(A),this._colorsTexture!==null)K.colorsTexture=this._colorsTexture.toJSON(A);if(this.boundingSphere!==null)K.boundingSphere={center:K.boundingSphere.center.toArray(),radius:K.boundingSphere.radius};if(this.boundingBox!==null)K.boundingBox={min:K.boundingBox.min.toArray(),max:K.boundingBox.max.toArray()}}function C(Y,Z){if(Y[Z.uuid]===void 0)Y[Z.uuid]=Z.toJSON(A);return Z.uuid}if(this.isScene){if(this.background){if(this.background.isColor)K.background=this.background.toJSON();else if(this.background.isTexture)K.background=this.background.toJSON(A).uuid}if(this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0)K.environment=this.environment.toJSON(A).uuid}else if(this.isMesh||this.isLine||this.isPoints){K.geometry=C(A.geometries,this.geometry);let Y=this.geometry.parameters;if(Y!==void 0&&Y.shapes!==void 0){let Z=Y.shapes;if(Array.isArray(Z))for(let X=0,E=Z.length;X0){K.children=[];for(let Y=0;Y0){K.animations=[];for(let Y=0;Y0)J.geometries=Y;if(Z.length>0)J.materials=Z;if(X.length>0)J.textures=X;if(E.length>0)J.images=E;if(H.length>0)J.shapes=H;if($.length>0)J.skeletons=$;if(I.length>0)J.animations=I;if(N.length>0)J.nodes=N}return J.object=K,J;function U(Y){let Z=[];for(let X in Y){let E=Y[X];delete E.metadata,Z.push(E)}return Z}}clone(A){return new this.constructor().copy(this,A)}copy(A,Q=!0){if(this.name=A.name,this.up.copy(A.up),this.position.copy(A.position),this.rotation.order=A.rotation.order,this.quaternion.copy(A.quaternion),this.scale.copy(A.scale),this.matrix.copy(A.matrix),this.matrixWorld.copy(A.matrixWorld),this.matrixAutoUpdate=A.matrixAutoUpdate,this.matrixWorldAutoUpdate=A.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=A.matrixWorldNeedsUpdate,this.layers.mask=A.layers.mask,this.visible=A.visible,this.castShadow=A.castShadow,this.receiveShadow=A.receiveShadow,this.frustumCulled=A.frustumCulled,this.renderOrder=A.renderOrder,this.animations=A.animations.slice(),this.userData=JSON.parse(JSON.stringify(A.userData)),Q===!0)for(let J=0;J0)return K.multiplyScalar(1/Math.sqrt(C));return K.set(0,0,0)}static getBarycoord(A,Q,J,K,C){$5.subVectors(K,Q),l3.subVectors(J,Q),qL.subVectors(A,Q);let U=$5.dot($5),Y=$5.dot(l3),Z=$5.dot(qL),X=l3.dot(l3),E=l3.dot(qL),H=U*X-Y*Y;if(H===0)return C.set(0,0,0),null;let $=1/H,I=(X*Z-Y*E)*$,N=(U*E-Y*Z)*$;return C.set(1-I-N,N,I)}static containsPoint(A,Q,J,K){if(this.getBarycoord(A,Q,J,K,n3)===null)return!1;return n3.x>=0&&n3.y>=0&&n3.x+n3.y<=1}static getInterpolation(A,Q,J,K,C,U,Y,Z){if(this.getBarycoord(A,Q,J,K,n3)===null){if(Z.x=0,Z.y=0,"z"in Z)Z.z=0;if("w"in Z)Z.w=0;return null}return Z.setScalar(0),Z.addScaledVector(C,n3.x),Z.addScaledVector(U,n3.y),Z.addScaledVector(Y,n3.z),Z}static getInterpolatedAttribute(A,Q,J,K,C,U){return FL.setScalar(0),RL.setScalar(0),zL.setScalar(0),FL.fromBufferAttribute(A,Q),RL.fromBufferAttribute(A,J),zL.fromBufferAttribute(A,K),U.setScalar(0),U.addScaledVector(FL,C.x),U.addScaledVector(RL,C.y),U.addScaledVector(zL,C.z),U}static isFrontFacing(A,Q,J,K){return $5.subVectors(J,Q),l3.subVectors(A,Q),$5.cross(l3).dot(K)<0?!0:!1}set(A,Q,J){return this.a.copy(A),this.b.copy(Q),this.c.copy(J),this}setFromPointsAndIndices(A,Q,J,K){return this.a.copy(A[Q]),this.b.copy(A[J]),this.c.copy(A[K]),this}setFromAttributeAndIndices(A,Q,J,K){return this.a.fromBufferAttribute(A,Q),this.b.fromBufferAttribute(A,J),this.c.fromBufferAttribute(A,K),this}clone(){return new this.constructor().copy(this)}copy(A){return this.a.copy(A.a),this.b.copy(A.b),this.c.copy(A.c),this}getArea(){return $5.subVectors(this.c,this.b),l3.subVectors(this.a,this.b),$5.cross(l3).length()*0.5}getMidpoint(A){return A.addVectors(this.a,this.b).add(this.c).multiplyScalar(0.3333333333333333)}getNormal(A){return W8.getNormal(this.a,this.b,this.c,A)}getPlane(A){return A.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(A,Q){return W8.getBarycoord(A,this.a,this.b,this.c,Q)}getInterpolation(A,Q,J,K,C){return W8.getInterpolation(A,this.a,this.b,this.c,Q,J,K,C)}containsPoint(A){return W8.containsPoint(A,this.a,this.b,this.c)}isFrontFacing(A){return W8.isFrontFacing(this.a,this.b,this.c,A)}intersectsBox(A){return A.intersectsTriangle(this)}closestPointToPoint(A,Q){let J=this.a,K=this.b,C=this.c,U,Y;hK.subVectors(K,J),gK.subVectors(C,J),OL.subVectors(A,J);let Z=hK.dot(OL),X=gK.dot(OL);if(Z<=0&&X<=0)return Q.copy(J);NL.subVectors(A,K);let E=hK.dot(NL),H=gK.dot(NL);if(E>=0&&H<=E)return Q.copy(K);let $=Z*H-E*X;if($<=0&&Z>=0&&E<=0)return U=Z/(Z-E),Q.copy(J).addScaledVector(hK,U);LL.subVectors(A,C);let I=hK.dot(LL),N=gK.dot(LL);if(N>=0&&I<=N)return Q.copy(C);let F=I*X-Z*N;if(F<=0&&X>=0&&N<=0)return Y=X/(X-N),Q.copy(J).addScaledVector(gK,Y);let V=E*N-I*H;if(V<=0&&H-E>=0&&I-N>=0)return dy.subVectors(C,K),Y=(H-E)/(H-E+(I-N)),Q.copy(K).addScaledVector(dy,Y);let D=1/(V+F+$);return U=F*D,Y=$*D,Q.copy(J).addScaledVector(hK,U).addScaledVector(gK,Y)}equals(A){return A.a.equals(this.a)&&A.b.equals(this.b)&&A.c.equals(this.c)}}var xg={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},K4={h:0,s:0,l:0},G$={h:0,s:0,l:0};function DL(A,Q,J){if(J<0)J+=1;if(J>1)J-=1;if(J<0.16666666666666666)return A+(Q-A)*6*J;if(J<0.5)return Q;if(J<0.6666666666666666)return A+(Q-A)*6*(0.6666666666666666-J);return A}class y1{constructor(A,Q,J){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(A,Q,J)}set(A,Q,J){if(Q===void 0&&J===void 0){let K=A;if(K&&K.isColor)this.copy(K);else if(typeof K==="number")this.setHex(K);else if(typeof K==="string")this.setStyle(K)}else this.setRGB(A,Q,J);return this}setScalar(A){return this.r=A,this.g=A,this.b=A,this}setHex(A,Q="srgb"){return A=Math.floor(A),this.r=(A>>16&255)/255,this.g=(A>>8&255)/255,this.b=(A&255)/255,e0.toWorkingColorSpace(this,Q),this}setRGB(A,Q,J,K=e0.workingColorSpace){return this.r=A,this.g=Q,this.b=J,e0.toWorkingColorSpace(this,K),this}setHSL(A,Q,J,K=e0.workingColorSpace){if(A=PF(A,1),Q=zA(Q,0,1),J=zA(J,0,1),Q===0)this.r=this.g=this.b=J;else{let C=J<=0.5?J*(1+Q):J+Q-J*Q,U=2*J-C;this.r=DL(U,C,A+0.3333333333333333),this.g=DL(U,C,A),this.b=DL(U,C,A-0.3333333333333333)}return e0.toWorkingColorSpace(this,K),this}setStyle(A,Q="srgb"){function J(C){if(C===void 0)return;if(parseFloat(C)<1)console.warn("THREE.Color: Alpha component of "+A+" will be ignored.")}let K;if(K=/^(\w+)\(([^\)]*)\)/.exec(A)){let C,U=K[1],Y=K[2];switch(U){case"rgb":case"rgba":if(C=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(Y))return J(C[4]),this.setRGB(Math.min(255,parseInt(C[1],10))/255,Math.min(255,parseInt(C[2],10))/255,Math.min(255,parseInt(C[3],10))/255,Q);if(C=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(Y))return J(C[4]),this.setRGB(Math.min(100,parseInt(C[1],10))/100,Math.min(100,parseInt(C[2],10))/100,Math.min(100,parseInt(C[3],10))/100,Q);break;case"hsl":case"hsla":if(C=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(Y))return J(C[4]),this.setHSL(parseFloat(C[1])/360,parseFloat(C[2])/100,parseFloat(C[3])/100,Q);break;default:console.warn("THREE.Color: Unknown color model "+A)}}else if(K=/^\#([A-Fa-f\d]+)$/.exec(A)){let C=K[1],U=C.length;if(U===3)return this.setRGB(parseInt(C.charAt(0),16)/15,parseInt(C.charAt(1),16)/15,parseInt(C.charAt(2),16)/15,Q);else if(U===6)return this.setHex(parseInt(C,16),Q);else console.warn("THREE.Color: Invalid hex color "+A)}else if(A&&A.length>0)return this.setColorName(A,Q);return this}setColorName(A,Q="srgb"){let J=xg[A.toLowerCase()];if(J!==void 0)this.setHex(J,Q);else console.warn("THREE.Color: Unknown color "+A);return this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(A){return this.r=A.r,this.g=A.g,this.b=A.b,this}copySRGBToLinear(A){return this.r=i3(A.r),this.g=i3(A.g),this.b=i3(A.b),this}copyLinearToSRGB(A){return this.r=oK(A.r),this.g=oK(A.g),this.b=oK(A.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(A="srgb"){return e0.fromWorkingColorSpace(K6.copy(this),A),Math.round(zA(K6.r*255,0,255))*65536+Math.round(zA(K6.g*255,0,255))*256+Math.round(zA(K6.b*255,0,255))}getHexString(A="srgb"){return("000000"+this.getHex(A).toString(16)).slice(-6)}getHSL(A,Q=e0.workingColorSpace){e0.fromWorkingColorSpace(K6.copy(this),Q);let{r:J,g:K,b:C}=K6,U=Math.max(J,K,C),Y=Math.min(J,K,C),Z,X,E=(Y+U)/2;if(Y===U)Z=0,X=0;else{let H=U-Y;switch(X=E<=0.5?H/(U+Y):H/(2-U-Y),U){case J:Z=(K-C)/H+(K0!==A>0)this.version++;this._alphaTest=A}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(A){if(A===void 0)return;for(let Q in A){let J=A[Q];if(J===void 0){console.warn(`THREE.Material: parameter '${Q}' has value of undefined.`);continue}let K=this[Q];if(K===void 0){console.warn(`THREE.Material: '${Q}' is not a property of THREE.${this.type}.`);continue}if(K&&K.isColor)K.set(J);else if(K&&K.isVector3&&(J&&J.isVector3))K.copy(J);else this[Q]=J}}toJSON(A){let Q=A===void 0||typeof A==="string";if(Q)A={textures:{},images:{}};let J={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};if(J.uuid=this.uuid,J.type=this.type,this.name!=="")J.name=this.name;if(this.color&&this.color.isColor)J.color=this.color.getHex();if(this.roughness!==void 0)J.roughness=this.roughness;if(this.metalness!==void 0)J.metalness=this.metalness;if(this.sheen!==void 0)J.sheen=this.sheen;if(this.sheenColor&&this.sheenColor.isColor)J.sheenColor=this.sheenColor.getHex();if(this.sheenRoughness!==void 0)J.sheenRoughness=this.sheenRoughness;if(this.emissive&&this.emissive.isColor)J.emissive=this.emissive.getHex();if(this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1)J.emissiveIntensity=this.emissiveIntensity;if(this.specular&&this.specular.isColor)J.specular=this.specular.getHex();if(this.specularIntensity!==void 0)J.specularIntensity=this.specularIntensity;if(this.specularColor&&this.specularColor.isColor)J.specularColor=this.specularColor.getHex();if(this.shininess!==void 0)J.shininess=this.shininess;if(this.clearcoat!==void 0)J.clearcoat=this.clearcoat;if(this.clearcoatRoughness!==void 0)J.clearcoatRoughness=this.clearcoatRoughness;if(this.clearcoatMap&&this.clearcoatMap.isTexture)J.clearcoatMap=this.clearcoatMap.toJSON(A).uuid;if(this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture)J.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(A).uuid;if(this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture)J.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(A).uuid,J.clearcoatNormalScale=this.clearcoatNormalScale.toArray();if(this.dispersion!==void 0)J.dispersion=this.dispersion;if(this.iridescence!==void 0)J.iridescence=this.iridescence;if(this.iridescenceIOR!==void 0)J.iridescenceIOR=this.iridescenceIOR;if(this.iridescenceThicknessRange!==void 0)J.iridescenceThicknessRange=this.iridescenceThicknessRange;if(this.iridescenceMap&&this.iridescenceMap.isTexture)J.iridescenceMap=this.iridescenceMap.toJSON(A).uuid;if(this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture)J.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(A).uuid;if(this.anisotropy!==void 0)J.anisotropy=this.anisotropy;if(this.anisotropyRotation!==void 0)J.anisotropyRotation=this.anisotropyRotation;if(this.anisotropyMap&&this.anisotropyMap.isTexture)J.anisotropyMap=this.anisotropyMap.toJSON(A).uuid;if(this.map&&this.map.isTexture)J.map=this.map.toJSON(A).uuid;if(this.matcap&&this.matcap.isTexture)J.matcap=this.matcap.toJSON(A).uuid;if(this.alphaMap&&this.alphaMap.isTexture)J.alphaMap=this.alphaMap.toJSON(A).uuid;if(this.lightMap&&this.lightMap.isTexture)J.lightMap=this.lightMap.toJSON(A).uuid,J.lightMapIntensity=this.lightMapIntensity;if(this.aoMap&&this.aoMap.isTexture)J.aoMap=this.aoMap.toJSON(A).uuid,J.aoMapIntensity=this.aoMapIntensity;if(this.bumpMap&&this.bumpMap.isTexture)J.bumpMap=this.bumpMap.toJSON(A).uuid,J.bumpScale=this.bumpScale;if(this.normalMap&&this.normalMap.isTexture)J.normalMap=this.normalMap.toJSON(A).uuid,J.normalMapType=this.normalMapType,J.normalScale=this.normalScale.toArray();if(this.displacementMap&&this.displacementMap.isTexture)J.displacementMap=this.displacementMap.toJSON(A).uuid,J.displacementScale=this.displacementScale,J.displacementBias=this.displacementBias;if(this.roughnessMap&&this.roughnessMap.isTexture)J.roughnessMap=this.roughnessMap.toJSON(A).uuid;if(this.metalnessMap&&this.metalnessMap.isTexture)J.metalnessMap=this.metalnessMap.toJSON(A).uuid;if(this.emissiveMap&&this.emissiveMap.isTexture)J.emissiveMap=this.emissiveMap.toJSON(A).uuid;if(this.specularMap&&this.specularMap.isTexture)J.specularMap=this.specularMap.toJSON(A).uuid;if(this.specularIntensityMap&&this.specularIntensityMap.isTexture)J.specularIntensityMap=this.specularIntensityMap.toJSON(A).uuid;if(this.specularColorMap&&this.specularColorMap.isTexture)J.specularColorMap=this.specularColorMap.toJSON(A).uuid;if(this.envMap&&this.envMap.isTexture){if(J.envMap=this.envMap.toJSON(A).uuid,this.combine!==void 0)J.combine=this.combine}if(this.envMapRotation!==void 0)J.envMapRotation=this.envMapRotation.toArray();if(this.envMapIntensity!==void 0)J.envMapIntensity=this.envMapIntensity;if(this.reflectivity!==void 0)J.reflectivity=this.reflectivity;if(this.refractionRatio!==void 0)J.refractionRatio=this.refractionRatio;if(this.gradientMap&&this.gradientMap.isTexture)J.gradientMap=this.gradientMap.toJSON(A).uuid;if(this.transmission!==void 0)J.transmission=this.transmission;if(this.transmissionMap&&this.transmissionMap.isTexture)J.transmissionMap=this.transmissionMap.toJSON(A).uuid;if(this.thickness!==void 0)J.thickness=this.thickness;if(this.thicknessMap&&this.thicknessMap.isTexture)J.thicknessMap=this.thicknessMap.toJSON(A).uuid;if(this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0)J.attenuationDistance=this.attenuationDistance;if(this.attenuationColor!==void 0)J.attenuationColor=this.attenuationColor.getHex();if(this.size!==void 0)J.size=this.size;if(this.shadowSide!==null)J.shadowSide=this.shadowSide;if(this.sizeAttenuation!==void 0)J.sizeAttenuation=this.sizeAttenuation;if(this.blending!==1)J.blending=this.blending;if(this.side!==0)J.side=this.side;if(this.vertexColors===!0)J.vertexColors=!0;if(this.opacity<1)J.opacity=this.opacity;if(this.transparent===!0)J.transparent=!0;if(this.blendSrc!==204)J.blendSrc=this.blendSrc;if(this.blendDst!==205)J.blendDst=this.blendDst;if(this.blendEquation!==100)J.blendEquation=this.blendEquation;if(this.blendSrcAlpha!==null)J.blendSrcAlpha=this.blendSrcAlpha;if(this.blendDstAlpha!==null)J.blendDstAlpha=this.blendDstAlpha;if(this.blendEquationAlpha!==null)J.blendEquationAlpha=this.blendEquationAlpha;if(this.blendColor&&this.blendColor.isColor)J.blendColor=this.blendColor.getHex();if(this.blendAlpha!==0)J.blendAlpha=this.blendAlpha;if(this.depthFunc!==3)J.depthFunc=this.depthFunc;if(this.depthTest===!1)J.depthTest=this.depthTest;if(this.depthWrite===!1)J.depthWrite=this.depthWrite;if(this.colorWrite===!1)J.colorWrite=this.colorWrite;if(this.stencilWriteMask!==255)J.stencilWriteMask=this.stencilWriteMask;if(this.stencilFunc!==519)J.stencilFunc=this.stencilFunc;if(this.stencilRef!==0)J.stencilRef=this.stencilRef;if(this.stencilFuncMask!==255)J.stencilFuncMask=this.stencilFuncMask;if(this.stencilFail!==7680)J.stencilFail=this.stencilFail;if(this.stencilZFail!==7680)J.stencilZFail=this.stencilZFail;if(this.stencilZPass!==7680)J.stencilZPass=this.stencilZPass;if(this.stencilWrite===!0)J.stencilWrite=this.stencilWrite;if(this.rotation!==void 0&&this.rotation!==0)J.rotation=this.rotation;if(this.polygonOffset===!0)J.polygonOffset=!0;if(this.polygonOffsetFactor!==0)J.polygonOffsetFactor=this.polygonOffsetFactor;if(this.polygonOffsetUnits!==0)J.polygonOffsetUnits=this.polygonOffsetUnits;if(this.linewidth!==void 0&&this.linewidth!==1)J.linewidth=this.linewidth;if(this.dashSize!==void 0)J.dashSize=this.dashSize;if(this.gapSize!==void 0)J.gapSize=this.gapSize;if(this.scale!==void 0)J.scale=this.scale;if(this.dithering===!0)J.dithering=!0;if(this.alphaTest>0)J.alphaTest=this.alphaTest;if(this.alphaHash===!0)J.alphaHash=!0;if(this.alphaToCoverage===!0)J.alphaToCoverage=!0;if(this.premultipliedAlpha===!0)J.premultipliedAlpha=!0;if(this.forceSinglePass===!0)J.forceSinglePass=!0;if(this.wireframe===!0)J.wireframe=!0;if(this.wireframeLinewidth>1)J.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!=="round")J.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!=="round")J.wireframeLinejoin=this.wireframeLinejoin;if(this.flatShading===!0)J.flatShading=!0;if(this.visible===!1)J.visible=!1;if(this.toneMapped===!1)J.toneMapped=!1;if(this.fog===!1)J.fog=!1;if(Object.keys(this.userData).length>0)J.userData=this.userData;function K(C){let U=[];for(let Y in C){let Z=C[Y];delete Z.metadata,U.push(Z)}return U}if(Q){let C=K(A.textures),U=K(A.images);if(C.length>0)J.textures=C;if(U.length>0)J.images=U}return J}clone(){return new this.constructor().copy(this)}copy(A){this.name=A.name,this.blending=A.blending,this.side=A.side,this.vertexColors=A.vertexColors,this.opacity=A.opacity,this.transparent=A.transparent,this.blendSrc=A.blendSrc,this.blendDst=A.blendDst,this.blendEquation=A.blendEquation,this.blendSrcAlpha=A.blendSrcAlpha,this.blendDstAlpha=A.blendDstAlpha,this.blendEquationAlpha=A.blendEquationAlpha,this.blendColor.copy(A.blendColor),this.blendAlpha=A.blendAlpha,this.depthFunc=A.depthFunc,this.depthTest=A.depthTest,this.depthWrite=A.depthWrite,this.stencilWriteMask=A.stencilWriteMask,this.stencilFunc=A.stencilFunc,this.stencilRef=A.stencilRef,this.stencilFuncMask=A.stencilFuncMask,this.stencilFail=A.stencilFail,this.stencilZFail=A.stencilZFail,this.stencilZPass=A.stencilZPass,this.stencilWrite=A.stencilWrite;let Q=A.clippingPlanes,J=null;if(Q!==null){let K=Q.length;J=new Array(K);for(let C=0;C!==K;++C)J[C]=Q[C].clone()}return this.clippingPlanes=J,this.clipIntersection=A.clipIntersection,this.clipShadows=A.clipShadows,this.shadowSide=A.shadowSide,this.colorWrite=A.colorWrite,this.precision=A.precision,this.polygonOffset=A.polygonOffset,this.polygonOffsetFactor=A.polygonOffsetFactor,this.polygonOffsetUnits=A.polygonOffsetUnits,this.dithering=A.dithering,this.alphaTest=A.alphaTest,this.alphaHash=A.alphaHash,this.alphaToCoverage=A.alphaToCoverage,this.premultipliedAlpha=A.premultipliedAlpha,this.forceSinglePass=A.forceSinglePass,this.visible=A.visible,this.toneMapped=A.toneMapped,this.userData=JSON.parse(JSON.stringify(A.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(A){if(A===!0)this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class BA extends _2{constructor(A){super();this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new y1(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new t2,this.combine=0,this.reflectivity=1,this.refractionRatio=0.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.specularMap=A.specularMap,this.alphaMap=A.alphaMap,this.envMap=A.envMap,this.envMapRotation.copy(A.envMapRotation),this.combine=A.combine,this.reflectivity=A.reflectivity,this.refractionRatio=A.refractionRatio,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.fog=A.fog,this}}var o3=/*@__PURE__*/c51();function c51(){let A=new ArrayBuffer(4),Q=new Float32Array(A),J=new Uint32Array(A),K=new Uint32Array(512),C=new Uint32Array(512);for(let X=0;X<256;++X){let E=X-127;if(E<-27)K[X]=0,K[X|256]=32768,C[X]=24,C[X|256]=24;else if(E<-14)K[X]=1024>>-E-14,K[X|256]=1024>>-E-14|32768,C[X]=-E-1,C[X|256]=-E-1;else if(E<=15)K[X]=E+15<<10,K[X|256]=E+15<<10|32768,C[X]=13,C[X|256]=13;else if(E<128)K[X]=31744,K[X|256]=64512,C[X]=24,C[X|256]=24;else K[X]=31744,K[X|256]=64512,C[X]=13,C[X|256]=13}let U=new Uint32Array(2048),Y=new Uint32Array(64),Z=new Uint32Array(64);for(let X=1;X<1024;++X){let E=X<<13,H=0;while((E&8388608)===0)E<<=1,H-=8388608;E&=-8388609,H+=947912704,U[X]=E|H}for(let X=1024;X<2048;++X)U[X]=939524096+(X-1024<<13);for(let X=1;X<31;++X)Y[X]=X<<23;Y[31]=1199570944,Y[32]=2147483648;for(let X=33;X<63;++X)Y[X]=2147483648+(X-32<<23);Y[63]=3347054592;for(let X=1;X<64;++X)if(X!==32)Z[X]=1024;return{floatView:Q,uint32View:J,baseTable:K,shiftTable:C,mantissaTable:U,exponentTable:Y,offsetTable:Z}}function y6(A){if(Math.abs(A)>65504)console.warn("THREE.DataUtils.toHalfFloat(): Value out of range.");A=zA(A,-65504,65504),o3.floatView[0]=A;let Q=o3.uint32View[0],J=Q>>23&511;return o3.baseTable[J]+((Q&8388607)>>o3.shiftTable[J])}function gU(A){let Q=A>>10;return o3.uint32View[0]=o3.mantissaTable[o3.offsetTable[Q]+(A&1023)]+o3.exponentTable[Q],o3.floatView[0]}var U9={toHalfFloat:y6,fromHalfFloat:gU},G8=/*@__PURE__*/new I1,W$=/*@__PURE__*/new p1,d51=0;class p0{constructor(A,Q,J=!1){if(Array.isArray(A))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:d51++}),this.name="",this.array=A,this.itemSize=Q,this.count=A!==void 0?A.length/Q:0,this.normalized=J,this.usage=35044,this.updateRanges=[],this.gpuType=1015,this.version=0}onUploadCallback(){}set needsUpdate(A){if(A===!0)this.version++}setUsage(A){return this.usage=A,this}addUpdateRange(A,Q){this.updateRanges.push({start:A,count:Q})}clearUpdateRanges(){this.updateRanges.length=0}copy(A){return this.name=A.name,this.array=new A.array.constructor(A.array),this.itemSize=A.itemSize,this.count=A.count,this.normalized=A.normalized,this.usage=A.usage,this.gpuType=A.gpuType,this}copyAt(A,Q,J){A*=this.itemSize,J*=Q.itemSize;for(let K=0,C=this.itemSize;KQ.count)console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.");Q.needsUpdate=!0}return this}computeBoundingBox(){if(this.boundingBox===null)this.boundingBox=new DA;let A=this.attributes.position,Q=this.morphAttributes.position;if(A&&A.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new I1(-1/0,-1/0,-1/0),new I1(1/0,1/0,1/0));return}if(A!==void 0){if(this.boundingBox.setFromBufferAttribute(A),Q)for(let J=0,K=Q.length;J0)A.userData=this.userData;if(this.parameters!==void 0){let Z=this.parameters;for(let X in Z)if(Z[X]!==void 0)A[X]=Z[X];return A}A.data={attributes:{}};let Q=this.index;if(Q!==null)A.data.index={type:Q.array.constructor.name,array:Array.prototype.slice.call(Q.array)};let J=this.attributes;for(let Z in J){let X=J[Z];A.data.attributes[Z]=X.toJSON(A.data)}let K={},C=!1;for(let Z in this.morphAttributes){let X=this.morphAttributes[Z],E=[];for(let H=0,$=X.length;H<$;H++){let I=X[H];E.push(I.toJSON(A.data))}if(E.length>0)K[Z]=E,C=!0}if(C)A.data.morphAttributes=K,A.data.morphTargetsRelative=this.morphTargetsRelative;let U=this.groups;if(U.length>0)A.data.groups=JSON.parse(JSON.stringify(U));let Y=this.boundingSphere;if(Y!==null)A.data.boundingSphere={center:Y.center.toArray(),radius:Y.radius};return A}clone(){return new this.constructor().copy(this)}copy(A){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let Q={};this.name=A.name;let J=A.index;if(J!==null)this.setIndex(J.clone(Q));let K=A.attributes;for(let X in K){let E=K[X];this.setAttribute(X,E.clone(Q))}let C=A.morphAttributes;for(let X in C){let E=[],H=C[X];for(let $=0,I=H.length;$0){let K=Q[J[0]];if(K!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let C=0,U=K.length;C(A.far-A.near)**2)return}if(ly.copy(C).invert(),HQ.copy(A.ray).applyMatrix4(ly),J.boundingBox!==null){if(HQ.intersectsBox(J.boundingBox)===!1)return}this._computeIntersections(A,Q,HQ)}_computeIntersections(A,Q,J){let K,C=this.geometry,U=this.material,Y=C.index,Z=C.attributes.position,X=C.attributes.uv,E=C.attributes.uv1,H=C.attributes.normal,$=C.groups,I=C.drawRange;if(Y!==null)if(Array.isArray(U))for(let N=0,F=$.length;NJ.far)return null;return{distance:E,point:F$.clone(),object:A}}function R$(A,Q,J,K,C,U,Y,Z,X,E){A.getVertexPosition(Z,q$),A.getVertexPosition(X,O$),A.getVertexPosition(E,N$);let H=n51(A,Q,J,K,q$,O$,N$,sy);if(H){let $=new I1;if(W8.getBarycoord(sy,q$,O$,N$,$),C)H.uv=W8.getInterpolatedAttribute(C,Z,X,E,$,new p1);if(U)H.uv1=W8.getInterpolatedAttribute(U,Z,X,E,$,new p1);if(Y){if(H.normal=W8.getInterpolatedAttribute(Y,Z,X,E,$,new I1),H.normal.dot(K.direction)>0)H.normal.multiplyScalar(-1)}let I={a:Z,b:X,c:E,normal:new I1,materialIndex:0};W8.getNormal(q$,O$,N$,I.normal),H.face=I,H.barycoord=$}return H}class R8 extends V0{constructor(A=1,Q=1,J=1,K=1,C=1,U=1){super();this.type="BoxGeometry",this.parameters={width:A,height:Q,depth:J,widthSegments:K,heightSegments:C,depthSegments:U};let Y=this;K=Math.floor(K),C=Math.floor(C),U=Math.floor(U);let Z=[],X=[],E=[],H=[],$=0,I=0;N("z","y","x",-1,-1,J,Q,A,U,C,0),N("z","y","x",1,-1,J,Q,-A,U,C,1),N("x","z","y",1,1,A,J,Q,K,U,2),N("x","z","y",1,-1,A,J,-Q,K,U,3),N("x","y","z",1,-1,A,Q,J,K,C,4),N("x","y","z",-1,-1,A,Q,-J,K,C,5),this.setIndex(Z),this.setAttribute("position",new L0(X,3)),this.setAttribute("normal",new L0(E,3)),this.setAttribute("uv",new L0(H,2));function N(F,V,D,L,R,M,T,h,y,g,f){let u=M/y,d=T/g,n=M/2,B=T/2,q=h/2,P=y+1,O=g+1,w=0,k=0,S=new I1;for(let _=0;_0?1:-1,E.push(S.x,S.y,S.z),H.push(j/y),H.push(1-_/g),w+=1}}for(let _=0;_0)Q.defines=this.defines;Q.vertexShader=this.vertexShader,Q.fragmentShader=this.fragmentShader,Q.lights=this.lights,Q.clipping=this.clipping;let J={};for(let K in this.extensions)if(this.extensions[K]===!0)J[K]=!0;if(Object.keys(J).length>0)Q.extensions=J;return Q}}class cQ extends AA{constructor(){super();this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Y0,this.projectionMatrix=new Y0,this.projectionMatrixInverse=new Y0,this.coordinateSystem=2000}copy(A,Q){return super.copy(A,Q),this.matrixWorldInverse.copy(A.matrixWorldInverse),this.projectionMatrix.copy(A.projectionMatrix),this.projectionMatrixInverse.copy(A.projectionMatrixInverse),this.coordinateSystem=A.coordinateSystem,this}getWorldDirection(A){return super.getWorldDirection(A).negate()}updateMatrixWorld(A){super.updateMatrixWorld(A),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(A,Q){super.updateWorldMatrix(A,Q),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}var C4=/*@__PURE__*/new I1,oy=/*@__PURE__*/new p1,iy=/*@__PURE__*/new p1;class kA extends cQ{constructor(A=50,Q=1,J=0.1,K=2000){super();this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=A,this.zoom=1,this.near=J,this.far=K,this.focus=10,this.aspect=Q,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(A,Q){return super.copy(A,Q),this.fov=A.fov,this.zoom=A.zoom,this.near=A.near,this.far=A.far,this.focus=A.focus,this.aspect=A.aspect,this.view=A.view===null?null:Object.assign({},A.view),this.filmGauge=A.filmGauge,this.filmOffset=A.filmOffset,this}setFocalLength(A){let Q=0.5*this.getFilmHeight()/A;this.fov=DQ*2*Math.atan(Q),this.updateProjectionMatrix()}getFocalLength(){let A=Math.tan(zQ*0.5*this.fov);return 0.5*this.getFilmHeight()/A}getEffectiveFOV(){return DQ*2*Math.atan(Math.tan(zQ*0.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(A,Q,J){C4.set(-1,-1,0.5).applyMatrix4(this.projectionMatrixInverse),Q.set(C4.x,C4.y).multiplyScalar(-A/C4.z),C4.set(1,1,0.5).applyMatrix4(this.projectionMatrixInverse),J.set(C4.x,C4.y).multiplyScalar(-A/C4.z)}getViewSize(A,Q){return this.getViewBounds(A,oy,iy),Q.subVectors(iy,oy)}setViewOffset(A,Q,J,K,C,U){if(this.aspect=A/Q,this.view===null)this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1};this.view.enabled=!0,this.view.fullWidth=A,this.view.fullHeight=Q,this.view.offsetX=J,this.view.offsetY=K,this.view.width=C,this.view.height=U,this.updateProjectionMatrix()}clearViewOffset(){if(this.view!==null)this.view.enabled=!1;this.updateProjectionMatrix()}updateProjectionMatrix(){let A=this.near,Q=A*Math.tan(zQ*0.5*this.fov)/this.zoom,J=2*Q,K=this.aspect*J,C=-0.5*K,U=this.view;if(this.view!==null&&this.view.enabled){let{fullWidth:Z,fullHeight:X}=U;C+=U.offsetX*K/Z,Q-=U.offsetY*J/X,K*=U.width/Z,J*=U.height/X}let Y=this.filmOffset;if(Y!==0)C+=A*Y/this.getFilmWidth();this.projectionMatrix.makePerspective(C,C+K,Q,Q-J,A,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(A){let Q=super.toJSON(A);if(Q.object.fov=this.fov,Q.object.zoom=this.zoom,Q.object.near=this.near,Q.object.far=this.far,Q.object.focus=this.focus,Q.object.aspect=this.aspect,this.view!==null)Q.object.view=Object.assign({},this.view);return Q.object.filmGauge=this.filmGauge,Q.object.filmOffset=this.filmOffset,Q}}var fK=-90,pK=1;class yH extends AA{constructor(A,Q,J){super();this.type="CubeCamera",this.renderTarget=J,this.coordinateSystem=null,this.activeMipmapLevel=0;let K=new kA(fK,pK,A,Q);K.layers=this.layers,this.add(K);let C=new kA(fK,pK,A,Q);C.layers=this.layers,this.add(C);let U=new kA(fK,pK,A,Q);U.layers=this.layers,this.add(U);let Y=new kA(fK,pK,A,Q);Y.layers=this.layers,this.add(Y);let Z=new kA(fK,pK,A,Q);Z.layers=this.layers,this.add(Z);let X=new kA(fK,pK,A,Q);X.layers=this.layers,this.add(X)}updateCoordinateSystem(){let A=this.coordinateSystem,Q=this.children.concat(),[J,K,C,U,Y,Z]=Q;for(let X of Q)this.remove(X);if(A===2000)J.up.set(0,1,0),J.lookAt(1,0,0),K.up.set(0,1,0),K.lookAt(-1,0,0),C.up.set(0,0,-1),C.lookAt(0,1,0),U.up.set(0,0,1),U.lookAt(0,-1,0),Y.up.set(0,1,0),Y.lookAt(0,0,1),Z.up.set(0,1,0),Z.lookAt(0,0,-1);else if(A===2001)J.up.set(0,-1,0),J.lookAt(-1,0,0),K.up.set(0,-1,0),K.lookAt(1,0,0),C.up.set(0,0,1),C.lookAt(0,1,0),U.up.set(0,0,-1),U.lookAt(0,-1,0),Y.up.set(0,-1,0),Y.lookAt(0,0,1),Z.up.set(0,-1,0),Z.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+A);for(let X of Q)this.add(X),X.updateMatrixWorld()}update(A,Q){if(this.parent===null)this.updateMatrixWorld();let{renderTarget:J,activeMipmapLevel:K}=this;if(this.coordinateSystem!==A.coordinateSystem)this.coordinateSystem=A.coordinateSystem,this.updateCoordinateSystem();let[C,U,Y,Z,X,E]=this.children,H=A.getRenderTarget(),$=A.getActiveCubeFace(),I=A.getActiveMipmapLevel(),N=A.xr.enabled;A.xr.enabled=!1;let F=J.texture.generateMipmaps;J.texture.generateMipmaps=!1,A.setRenderTarget(J,0,K),A.render(Q,C),A.setRenderTarget(J,1,K),A.render(Q,U),A.setRenderTarget(J,2,K),A.render(Q,Y),A.setRenderTarget(J,3,K),A.render(Q,Z),A.setRenderTarget(J,4,K),A.render(Q,X),J.texture.generateMipmaps=F,A.setRenderTarget(J,5,K),A.render(Q,E),A.setRenderTarget(H,$,I),A.xr.enabled=N,J.texture.needsPMREMUpdate=!0}}class t3 extends J2{constructor(A,Q,J,K,C,U,Y,Z,X,E){A=A!==void 0?A:[],Q=Q!==void 0?Q:301;super(A,Q,J,K,C,U,Y,Z,X,E);this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(A){this.image=A}}class BZ extends s0{constructor(A=1,Q={}){super(A,A,Q);this.isWebGLCubeRenderTarget=!0;let J={width:A,height:A,depth:1},K=[J,J,J,J,J,J];this.texture=new t3(K,Q.mapping,Q.wrapS,Q.wrapT,Q.magFilter,Q.minFilter,Q.format,Q.type,Q.anisotropy,Q.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=Q.generateMipmaps!==void 0?Q.generateMipmaps:!1,this.texture.minFilter=Q.minFilter!==void 0?Q.minFilter:1006}fromEquirectangularTexture(A,Q){this.texture.type=Q.type,this.texture.colorSpace=Q.colorSpace,this.texture.generateMipmaps=Q.generateMipmaps,this.texture.minFilter=Q.minFilter,this.texture.magFilter=Q.magFilter;let J={uniforms:{tEquirect:{value:null}},vertexShader:` - - varying vec3 vWorldDirection; - - vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); - - } - - void main() { - - vWorldDirection = transformDirection( position, modelMatrix ); - - #include - #include - - } - `,fragmentShader:` - - uniform sampler2D tEquirect; - - varying vec3 vWorldDirection; - - #include - - void main() { - - vec3 direction = normalize( vWorldDirection ); - - vec2 sampleUV = equirectUv( direction ); - - gl_FragColor = texture2D( tEquirect, sampleUV ); - - } - `},K=new R8(5,5,5),C=new T0({name:"CubemapFromEquirect",uniforms:mQ(J.uniforms),vertexShader:J.vertexShader,fragmentShader:J.fragmentShader,side:1,blending:0});C.uniforms.tEquirect.value=Q;let U=new _0(K,C),Y=Q.minFilter;if(Q.minFilter===1008)Q.minFilter=1006;return new yH(1,10,this).update(A,U),Q.minFilter=Y,U.geometry.dispose(),U.material.dispose(),this}clear(A,Q,J,K){let C=A.getRenderTarget();for(let U=0;U<6;U++)A.setRenderTarget(this,U),A.clear(Q,J,K);A.setRenderTarget(C)}}class cA extends AA{constructor(){super();this.isGroup=!0,this.type="Group"}}var a51={type:"move"};class BC{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){if(this._hand===null)this._hand=new cA,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1};return this._hand}getTargetRaySpace(){if(this._targetRay===null)this._targetRay=new cA,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new I1,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new I1;return this._targetRay}getGripSpace(){if(this._grip===null)this._grip=new cA,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new I1,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new I1;return this._grip}dispatchEvent(A){if(this._targetRay!==null)this._targetRay.dispatchEvent(A);if(this._grip!==null)this._grip.dispatchEvent(A);if(this._hand!==null)this._hand.dispatchEvent(A);return this}connect(A){if(A&&A.hand){let Q=this._hand;if(Q)for(let J of A.hand.values())this._getHandJoint(Q,J)}return this.dispatchEvent({type:"connected",data:A}),this}disconnect(A){if(this.dispatchEvent({type:"disconnected",data:A}),this._targetRay!==null)this._targetRay.visible=!1;if(this._grip!==null)this._grip.visible=!1;if(this._hand!==null)this._hand.visible=!1;return this}update(A,Q,J){let K=null,C=null,U=null,Y=this._targetRay,Z=this._grip,X=this._hand;if(A&&Q.session.visibilityState!=="visible-blurred"){if(X&&A.hand){U=!0;for(let F of A.hand.values()){let V=Q.getJointPose(F,J),D=this._getHandJoint(X,F);if(V!==null)D.matrix.fromArray(V.transform.matrix),D.matrix.decompose(D.position,D.rotation,D.scale),D.matrixWorldNeedsUpdate=!0,D.jointRadius=V.radius;D.visible=V!==null}let E=X.joints["index-finger-tip"],H=X.joints["thumb-tip"],$=E.position.distanceTo(H.position),I=0.02,N=0.005;if(X.inputState.pinching&&$>I+N)X.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:A.handedness,target:this});else if(!X.inputState.pinching&&$<=I-N)X.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:A.handedness,target:this})}else if(Z!==null&&A.gripSpace){if(C=Q.getPose(A.gripSpace,J),C!==null){if(Z.matrix.fromArray(C.transform.matrix),Z.matrix.decompose(Z.position,Z.rotation,Z.scale),Z.matrixWorldNeedsUpdate=!0,C.linearVelocity)Z.hasLinearVelocity=!0,Z.linearVelocity.copy(C.linearVelocity);else Z.hasLinearVelocity=!1;if(C.angularVelocity)Z.hasAngularVelocity=!0,Z.angularVelocity.copy(C.angularVelocity);else Z.hasAngularVelocity=!1}}if(Y!==null){if(K=Q.getPose(A.targetRaySpace,J),K===null&&C!==null)K=C;if(K!==null){if(Y.matrix.fromArray(K.transform.matrix),Y.matrix.decompose(Y.position,Y.rotation,Y.scale),Y.matrixWorldNeedsUpdate=!0,K.linearVelocity)Y.hasLinearVelocity=!0,Y.linearVelocity.copy(K.linearVelocity);else Y.hasLinearVelocity=!1;if(K.angularVelocity)Y.hasAngularVelocity=!0,Y.angularVelocity.copy(K.angularVelocity);else Y.hasAngularVelocity=!1;this.dispatchEvent(a51)}}}if(Y!==null)Y.visible=K!==null;if(Z!==null)Z.visible=C!==null;if(X!==null)X.visible=U!==null;return this}_getHandJoint(A,Q){if(A.joints[Q.jointName]===void 0){let J=new cA;J.matrixAutoUpdate=!1,J.visible=!1,A.joints[Q.jointName]=J,A.add(J)}return A.joints[Q.jointName]}}class XZ{constructor(A,Q=0.00025){this.isFogExp2=!0,this.name="",this.color=new y1(A),this.density=Q}clone(){return new XZ(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class EZ{constructor(A,Q=1,J=1000){this.isFog=!0,this.name="",this.color=new y1(A),this.near=Q,this.far=J}clone(){return new EZ(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class Q8 extends AA{constructor(){super();if(this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new t2,this.environmentIntensity=1,this.environmentRotation=new t2,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__!=="undefined")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(A,Q){if(super.copy(A,Q),A.background!==null)this.background=A.background.clone();if(A.environment!==null)this.environment=A.environment.clone();if(A.fog!==null)this.fog=A.fog.clone();if(this.backgroundBlurriness=A.backgroundBlurriness,this.backgroundIntensity=A.backgroundIntensity,this.backgroundRotation.copy(A.backgroundRotation),this.environmentIntensity=A.environmentIntensity,this.environmentRotation.copy(A.environmentRotation),A.overrideMaterial!==null)this.overrideMaterial=A.overrideMaterial.clone();return this.matrixAutoUpdate=A.matrixAutoUpdate,this}toJSON(A){let Q=super.toJSON(A);if(this.fog!==null)Q.object.fog=this.fog.toJSON();if(this.backgroundBlurriness>0)Q.object.backgroundBlurriness=this.backgroundBlurriness;if(this.backgroundIntensity!==1)Q.object.backgroundIntensity=this.backgroundIntensity;if(Q.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1)Q.object.environmentIntensity=this.environmentIntensity;return Q.object.environmentRotation=this.environmentRotation.toArray(),Q}}class L6{constructor(A,Q){this.isInterleavedBuffer=!0,this.array=A,this.stride=Q,this.count=A!==void 0?A.length/Q:0,this.usage=35044,this.updateRanges=[],this.version=0,this.uuid=J9()}onUploadCallback(){}set needsUpdate(A){if(A===!0)this.version++}setUsage(A){return this.usage=A,this}addUpdateRange(A,Q){this.updateRanges.push({start:A,count:Q})}clearUpdateRanges(){this.updateRanges.length=0}copy(A){return this.array=new A.array.constructor(A.array),this.count=A.count,this.stride=A.stride,this.usage=A.usage,this}copyAt(A,Q,J){A*=this.stride,J*=Q.stride;for(let K=0,C=this.stride;KA.far)return;Q.push({distance:Z,point:TU.clone(),uv:W8.getInterpolation(TU,z$,SU,D$,ay,wL,ry,new p1),face:null,object:this})}copy(A,Q){if(super.copy(A,Q),A.center!==void 0)this.center.copy(A.center);return this.material=A.material,this}}function V$(A,Q,J,K,C,U){if(dK.subVectors(A,J).addScalar(0.5).multiply(K),C!==void 0)kU.x=U*dK.x-C*dK.y,kU.y=C*dK.x+U*dK.y;else kU.copy(dK);A.copy(Q),A.x+=kU.x,A.y+=kU.y,A.applyMatrix4(yg)}var M$=/*@__PURE__*/new I1,ty=/*@__PURE__*/new I1;class hH extends AA{constructor(){super();this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(A){super.copy(A,!1);let Q=A.levels;for(let J=0,K=Q.length;J0){let J,K;for(J=1,K=Q.length;J0){M$.setFromMatrixPosition(this.matrixWorld);let K=A.ray.origin.distanceTo(M$);this.getObjectForDistance(K).raycast(A,Q)}}update(A){let Q=this.levels;if(Q.length>1){M$.setFromMatrixPosition(A.matrixWorld),ty.setFromMatrixPosition(this.matrixWorld);let J=M$.distanceTo(ty)/A.zoom;Q[0].object.visible=!0;let K,C;for(K=1,C=Q.length;K=U)Q[K-1].object.visible=!1,Q[K].object.visible=!0;else break}this._currentLevel=K-1;for(;K1)return null;return Q.copy(A.start).addScaledVector(J,C)}intersectsLine(A){let Q=this.distanceToPoint(A.start),J=this.distanceToPoint(A.end);return Q<0&&J>0||J<0&&Q>0}intersectsBox(A){return A.intersectsPlane(this)}intersectsSphere(A){return A.intersectsPlane(this)}coplanarPoint(A){return A.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(A,Q){let J=Q||Q31.getNormalMatrix(A),K=this.coplanarPoint(TL).applyMatrix4(A),C=this.normal.applyMatrix3(J).normalize();return this.constant=-K.dot(C),this}translate(A){return this.constant-=A.dot(this.normal),this}equals(A){return A.normal.equals(this.normal)&&A.constant===this.constant}clone(){return new this.constructor().copy(this)}}var GQ=/*@__PURE__*/new O2,_$=/*@__PURE__*/new I1;class Q3{constructor(A=new V2,Q=new V2,J=new V2,K=new V2,C=new V2,U=new V2){this.planes=[A,Q,J,K,C,U]}set(A,Q,J,K,C,U){let Y=this.planes;return Y[0].copy(A),Y[1].copy(Q),Y[2].copy(J),Y[3].copy(K),Y[4].copy(C),Y[5].copy(U),this}copy(A){let Q=this.planes;for(let J=0;J<6;J++)Q[J].copy(A.planes[J]);return this}setFromProjectionMatrix(A,Q=2000){let J=this.planes,K=A.elements,C=K[0],U=K[1],Y=K[2],Z=K[3],X=K[4],E=K[5],H=K[6],$=K[7],I=K[8],N=K[9],F=K[10],V=K[11],D=K[12],L=K[13],R=K[14],M=K[15];if(J[0].setComponents(Z-C,$-X,V-I,M-D).normalize(),J[1].setComponents(Z+C,$+X,V+I,M+D).normalize(),J[2].setComponents(Z+U,$+E,V+N,M+L).normalize(),J[3].setComponents(Z-U,$-E,V-N,M-L).normalize(),J[4].setComponents(Z-Y,$-H,V-F,M-R).normalize(),Q===2000)J[5].setComponents(Z+Y,$+H,V+F,M+R).normalize();else if(Q===2001)J[5].setComponents(Y,H,F,R).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+Q);return this}intersectsObject(A){if(A.boundingSphere!==void 0){if(A.boundingSphere===null)A.computeBoundingSphere();GQ.copy(A.boundingSphere).applyMatrix4(A.matrixWorld)}else{let Q=A.geometry;if(Q.boundingSphere===null)Q.computeBoundingSphere();GQ.copy(Q.boundingSphere).applyMatrix4(A.matrixWorld)}return this.intersectsSphere(GQ)}intersectsSprite(A){return GQ.center.set(0,0,0),GQ.radius=0.7071067811865476,GQ.applyMatrix4(A.matrixWorld),this.intersectsSphere(GQ)}intersectsSphere(A){let Q=this.planes,J=A.center,K=-A.radius;for(let C=0;C<6;C++)if(Q[C].distanceToPoint(J)0?A.max.x:A.min.x,_$.y=K.normal.y>0?A.max.y:A.min.y,_$.z=K.normal.z>0?A.max.z:A.min.z,K.distanceToPoint(_$)<0)return!1}return!0}containsPoint(A){let Q=this.planes;for(let J=0;J<6;J++)if(Q[J].distanceToPoint(A)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function kL(A,Q){return A-Q}function J31(A,Q){return A.z-Q.z}function K31(A,Q){return Q.z-A.z}class hg{constructor(){this.index=0,this.pool=[],this.list=[]}push(A,Q,J,K){let C=this.pool,U=this.list;if(this.index>=C.length)C.push({start:-1,count:-1,z:-1,index:-1});let Y=C[this.index];U.push(Y),this.index++,Y.start=A,Y.count=Q,Y.z=J,Y.index=K}reset(){this.list.length=0,this.index=0}}var x6=/*@__PURE__*/new Y0,C31=/*@__PURE__*/new y1(1,1,1),SL=/*@__PURE__*/new Q3,T$=/*@__PURE__*/new DA,WQ=/*@__PURE__*/new O2,xU=/*@__PURE__*/new I1,Zh=/*@__PURE__*/new I1,Y31=/*@__PURE__*/new I1,jL=/*@__PURE__*/new hg,C6=/*@__PURE__*/new _0,k$=[];function U31(A,Q,J=0){let K=Q.itemSize;if(A.isInterleavedBufferAttribute||A.array.constructor!==Q.array.constructor){let C=A.count;for(let U=0;U65535?new Uint32Array(K):new Uint16Array(K);Q.setIndex(new p0(C,1))}this._geometryInitialized=!0}}_validateGeometry(A){let Q=this.geometry;if(Boolean(A.getIndex())!==Boolean(Q.getIndex()))throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(let J in Q.attributes){if(!A.hasAttribute(J))throw new Error(`THREE.BatchedMesh: Added geometry missing "${J}". All geometries must have consistent attributes.`);let K=A.getAttribute(J),C=Q.getAttribute(J);if(K.itemSize!==C.itemSize||K.normalized!==C.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(A){let Q=this._instanceInfo;if(A<0||A>=Q.length||Q[A].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${A}. Instance is either out of range or has been deleted.`)}validateGeometryId(A){let Q=this._geometryInfo;if(A<0||A>=Q.length||Q[A].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${A}. Geometry is either out of range or has been deleted.`)}setCustomSort(A){return this.customSort=A,this}computeBoundingBox(){if(this.boundingBox===null)this.boundingBox=new DA;let A=this.boundingBox,Q=this._instanceInfo;A.makeEmpty();for(let J=0,K=Q.length;J=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");let J={visible:!0,active:!0,geometryIndex:A},K=null;if(this._availableInstanceIds.length>0)this._availableInstanceIds.sort(kL),K=this._availableInstanceIds.shift(),this._instanceInfo[K]=J;else K=this._instanceInfo.length,this._instanceInfo.push(J);let C=this._matricesTexture;x6.identity().toArray(C.image.data,K*16),C.needsUpdate=!0;let U=this._colorsTexture;if(U)C31.toArray(U.image.data,K*4),U.needsUpdate=!0;return this._visibilityChanged=!0,K}addGeometry(A,Q=-1,J=-1){this._initializeGeometry(A),this._validateGeometry(A);let K={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},C=this._geometryInfo;K.vertexStart=this._nextVertexStart,K.reservedVertexCount=Q===-1?A.getAttribute("position").count:Q;let U=A.getIndex();if(U!==null)K.indexStart=this._nextIndexStart,K.reservedIndexCount=J===-1?U.count:J;if(K.indexStart!==-1&&K.indexStart+K.reservedIndexCount>this._maxIndexCount||K.vertexStart+K.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let Z;if(this._availableGeometryIds.length>0)this._availableGeometryIds.sort(kL),Z=this._availableGeometryIds.shift(),C[Z]=K;else Z=this._geometryCount,this._geometryCount++,C.push(K);return this.setGeometryAt(Z,A),this._nextIndexStart=K.indexStart+K.reservedIndexCount,this._nextVertexStart=K.vertexStart+K.reservedVertexCount,Z}setGeometryAt(A,Q){if(A>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(Q);let J=this.geometry,K=J.getIndex()!==null,C=J.getIndex(),U=Q.getIndex(),Y=this._geometryInfo[A];if(K&&U.count>Y.reservedIndexCount||Q.attributes.position.count>Y.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");let{vertexStart:Z,reservedVertexCount:X}=Y;Y.vertexCount=Q.getAttribute("position").count;for(let E in J.attributes){let H=Q.getAttribute(E),$=J.getAttribute(E);U31(H,$,Z);let I=H.itemSize;for(let N=H.count,F=X;N=Q.length||Q[A].active===!1)return this;let J=this._instanceInfo;for(let K=0,C=J.length;KY).sort((U,Y)=>{return J[U].vertexStart-J[Y].vertexStart}),C=this.geometry;for(let U=0,Y=J.length;U=this._geometryCount)return null;let J=this.geometry,K=this._geometryInfo[A];if(K.boundingBox===null){let C=new DA,U=J.index,Y=J.attributes.position;for(let Z=K.start,X=K.start+K.count;Z=this._geometryCount)return null;let J=this.geometry,K=this._geometryInfo[A];if(K.boundingSphere===null){let C=new O2;this.getBoundingBoxAt(A,T$),T$.getCenter(C.center);let U=J.index,Y=J.attributes.position,Z=0;for(let X=K.start,E=K.start+K.count;XY.active);if(Math.max(...J.map((Y)=>Y.vertexStart+Y.reservedVertexCount))>A)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${Q}. Cannot shrink further.`);if(this.geometry.index){if(Math.max(...J.map((Z)=>Z.indexStart+Z.reservedIndexCount))>Q)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${Q}. Cannot shrink further.`)}let C=this.geometry;if(C.dispose(),this._maxVertexCount=A,this._maxIndexCount=Q,this._geometryInitialized)this._geometryInitialized=!1,this.geometry=new V0,this._initializeGeometry(C);let U=this.geometry;if(C.index)IQ(C.index.array,U.index.array);for(let Y in C.attributes)IQ(C.attributes[Y].array,U.attributes[Y].array)}raycast(A,Q){let J=this._instanceInfo,K=this._geometryInfo,C=this.matrixWorld,U=this.geometry;if(C6.material=this.material,C6.geometry.index=U.index,C6.geometry.attributes=U.attributes,C6.geometry.boundingBox===null)C6.geometry.boundingBox=new DA;if(C6.geometry.boundingSphere===null)C6.geometry.boundingSphere=new O2;for(let Y=0,Z=J.length;Y({...Q,boundingBox:Q.boundingBox!==null?Q.boundingBox.clone():null,boundingSphere:Q.boundingSphere!==null?Q.boundingSphere.clone():null})),this._instanceInfo=A._instanceInfo.map((Q)=>({...Q})),this._maxInstanceCount=A._maxInstanceCount,this._maxVertexCount=A._maxVertexCount,this._maxIndexCount=A._maxIndexCount,this._geometryInitialized=A._geometryInitialized,this._geometryCount=A._geometryCount,this._multiDrawCounts=A._multiDrawCounts.slice(),this._multiDrawStarts=A._multiDrawStarts.slice(),this._matricesTexture=A._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null)this._colorsTexture=A._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice();return this}dispose(){if(this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null)this._colorsTexture.dispose(),this._colorsTexture=null;return this}onBeforeRender(A,Q,J,K,C){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;let U=K.getIndex(),Y=U===null?1:U.array.BYTES_PER_ELEMENT,Z=this._instanceInfo,X=this._multiDrawStarts,E=this._multiDrawCounts,H=this._geometryInfo,$=this.perObjectFrustumCulled,I=this._indirectTexture,N=I.image.data;if($)x6.multiplyMatrices(J.projectionMatrix,J.matrixWorldInverse).multiply(this.matrixWorld),SL.setFromProjectionMatrix(x6,A.coordinateSystem);let F=0;if(this.sortObjects){x6.copy(this.matrixWorld).invert(),xU.setFromMatrixPosition(J.matrixWorld).applyMatrix4(x6),Zh.set(0,0,-1).transformDirection(J.matrixWorld).transformDirection(x6);for(let L=0,R=Z.length;L0){let K=Q[J[0]];if(K!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let C=0,U=K.length;CK)return;vL.applyMatrix4(A.matrixWorld);let E=Q.ray.origin.distanceTo(vL);if(EQ.far)return;return{distance:E,point:Xh.clone().applyMatrix4(A.matrixWorld),index:Y,face:null,faceIndex:null,barycoord:null,object:A}}var Eh=/*@__PURE__*/new I1,$h=/*@__PURE__*/new I1;class T2 extends e2{constructor(A,Q){super(A,Q);this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let A=this.geometry;if(A.index===null){let Q=A.attributes.position,J=[];for(let K=0,C=Q.count;K0){let K=Q[J[0]];if(K!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let C=0,U=K.length;CC.far)return;U.push({distance:E,distanceToRay:Math.sqrt(Z),point:X,index:Q,face:null,faceIndex:null,barycoord:null,object:Y})}}class bH extends J2{constructor(A,Q,J,K,C,U,Y,Z,X){super(A,Q,J,K,C,U,Y,Z,X);this.isVideoTexture=!0,this.minFilter=U!==void 0?U:1006,this.magFilter=C!==void 0?C:1006,this.generateMipmaps=!1;let E=this;function H(){E.needsUpdate=!0,A.requestVideoFrameCallback(H)}if("requestVideoFrameCallback"in A)A.requestVideoFrameCallback(H)}clone(){return new this.constructor(this.image).copy(this)}update(){let A=this.image;if("requestVideoFrameCallback"in A===!1&&A.readyState>=A.HAVE_CURRENT_DATA)this.needsUpdate=!0}}class hF extends bH{constructor(A,Q,J,K,C,U,Y,Z){super({},A,Q,J,K,C,U,Y,Z);this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(A){this.image=A,this.needsUpdate=!0}}class EC extends J2{constructor(A,Q){super({width:A,height:Q});this.isFramebufferTexture=!0,this.magFilter=1003,this.minFilter=1003,this.generateMipmaps=!1,this.needsUpdate=!0}}class Z9 extends J2{constructor(A,Q,J,K,C,U,Y,Z,X,E,H,$){super(null,U,Y,Z,X,E,K,C,H,$);this.isCompressedTexture=!0,this.image={width:Q,height:J},this.mipmaps=A,this.flipY=!1,this.generateMipmaps=!1}}class $Z extends Z9{constructor(A,Q,J,K,C,U){super(A,Q,J,C,U);this.isCompressedArrayTexture=!0,this.image.depth=K,this.wrapR=1001,this.layerUpdates=/*@__PURE__*/new Set}addLayerUpdate(A){this.layerUpdates.add(A)}clearLayerUpdates(){this.layerUpdates.clear()}}class HZ extends Z9{constructor(A,Q,J){super(void 0,A[0].width,A[0].height,Q,J,301);this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=A}}class O5 extends J2{constructor(A,Q,J,K,C,U,Y,Z,X){super(A,Q,J,K,C,U,Y,Z,X);this.isCanvasTexture=!0,this.needsUpdate=!0}}class E6 extends J2{constructor(A,Q,J,K,C,U,Y,Z,X,E=1026){if(E!==1026&&E!==1027)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");if(J===void 0&&E===1026)J=1014;if(J===void 0&&E===1027)J=1020;super(null,K,C,U,Y,Z,E,J,X);this.isDepthTexture=!0,this.image={width:A,height:Q},this.magFilter=Y!==void 0?Y:1003,this.minFilter=Z!==void 0?Z:1003,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(A){return super.copy(A),this.compareFunction=A.compareFunction,this}toJSON(A){let Q=super.toJSON(A);if(this.compareFunction!==null)Q.compareFunction=this.compareFunction;return Q}}class n8{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(A,Q){let J=this.getUtoTmapping(A);return this.getPoint(J,Q)}getPoints(A=5){let Q=[];for(let J=0;J<=A;J++)Q.push(this.getPoint(J/A));return Q}getSpacedPoints(A=5){let Q=[];for(let J=0;J<=A;J++)Q.push(this.getPointAt(J/A));return Q}getLength(){let A=this.getLengths();return A[A.length-1]}getLengths(A=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===A+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;let Q=[],J,K=this.getPoint(0),C=0;Q.push(0);for(let U=1;U<=A;U++)J=this.getPoint(U/A),C+=J.distanceTo(K),Q.push(C),K=J;return this.cacheArcLengths=Q,Q}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(A,Q){let J=this.getLengths(),K=0,C=J.length,U;if(Q)U=Q;else U=A*J[C-1];let Y=0,Z=C-1,X;while(Y<=Z)if(K=Math.floor(Y+(Z-Y)/2),X=J[K]-U,X<0)Y=K+1;else if(X>0)Z=K-1;else{Z=K;break}if(K=Z,J[K]===U)return K/(C-1);let E=J[K],$=J[K+1]-E,I=(U-E)/$;return(K+I)/(C-1)}getTangent(A,Q){let K=A-0.0001,C=A+0.0001;if(K<0)K=0;if(C>1)C=1;let U=this.getPoint(K),Y=this.getPoint(C),Z=Q||(U.isVector2?new p1:new I1);return Z.copy(Y).sub(U).normalize(),Z}getTangentAt(A,Q){let J=this.getUtoTmapping(A);return this.getTangent(J,Q)}computeFrenetFrames(A,Q){let J=new I1,K=[],C=[],U=[],Y=new I1,Z=new Y0;for(let I=0;I<=A;I++){let N=I/A;K[I]=this.getTangentAt(N,new I1)}C[0]=new I1,U[0]=new I1;let X=Number.MAX_VALUE,E=Math.abs(K[0].x),H=Math.abs(K[0].y),$=Math.abs(K[0].z);if(E<=X)X=E,J.set(1,0,0);if(H<=X)X=H,J.set(0,1,0);if($<=X)J.set(0,0,1);Y.crossVectors(K[0],J).normalize(),C[0].crossVectors(K[0],Y),U[0].crossVectors(K[0],C[0]);for(let I=1;I<=A;I++){if(C[I]=C[I-1].clone(),U[I]=U[I-1].clone(),Y.crossVectors(K[I-1],K[I]),Y.length()>Number.EPSILON){Y.normalize();let N=Math.acos(zA(K[I-1].dot(K[I]),-1,1));C[I].applyMatrix4(Z.makeRotationAxis(Y,N))}U[I].crossVectors(K[I],C[I])}if(Q===!0){let I=Math.acos(zA(C[0].dot(C[A]),-1,1));if(I/=A,K[0].dot(Y.crossVectors(C[0],C[A]))>0)I=-I;for(let N=1;N<=A;N++)C[N].applyMatrix4(Z.makeRotationAxis(K[N],I*N)),U[N].crossVectors(K[N],C[N])}return{tangents:K,normals:C,binormals:U}}clone(){return new this.constructor().copy(this)}copy(A){return this.arcLengthDivisions=A.arcLengthDivisions,this}toJSON(){let A={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return A.arcLengthDivisions=this.arcLengthDivisions,A.type=this.type,A}fromJSON(A){return this.arcLengthDivisions=A.arcLengthDivisions,this}}class lQ extends n8{constructor(A=0,Q=0,J=1,K=1,C=0,U=Math.PI*2,Y=!1,Z=0){super();this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=A,this.aY=Q,this.xRadius=J,this.yRadius=K,this.aStartAngle=C,this.aEndAngle=U,this.aClockwise=Y,this.aRotation=Z}getPoint(A,Q=new p1){let J=Q,K=Math.PI*2,C=this.aEndAngle-this.aStartAngle,U=Math.abs(C)K)C-=K;if(C0?0:(Math.floor(Math.abs(Y)/C)+1)*C;else if(Z===0&&Y===C-1)Y=C-2,Z=1;let X,E;if(this.closed||Y>0)X=K[(Y-1)%C];else y$.subVectors(K[0],K[1]).add(K[0]),X=y$;let H=K[Y%C],$=K[(Y+1)%C];if(this.closed||Y+2K.length-2?K.length-1:U+1],H=K[U>K.length-3?K.length-1:U+2];return J.set(Wh(Y,Z.x,X.x,E.x,H.x),Wh(Y,Z.y,X.y,E.y,H.y)),J}copy(A){super.copy(A),this.points=[];for(let Q=0,J=A.points.length;Q=J){let U=K[C]-J,Y=this.curves[C],Z=Y.getLength(),X=Z===0?0:1-U/Z;return Y.getPointAt(X,Q)}C++}return null}getLength(){let A=this.getCurveLengths();return A[A.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;let A=[],Q=0;for(let J=0,K=this.curves.length;J1&&!Q[Q.length-1].equals(Q[0]))Q.push(Q[0]);return Q}copy(A){super.copy(A),this.curves=[];for(let Q=0,J=A.curves.length;Q0){let H=X.getPoint(0);if(!H.equals(this.currentPoint))this.lineTo(H.x,H.y)}this.curves.push(X);let E=X.getPoint(1);return this.currentPoint.copy(E),this}copy(A){return super.copy(A),this.currentPoint.copy(A.currentPoint),this}toJSON(){let A=super.toJSON();return A.currentPoint=this.currentPoint.toArray(),A}fromJSON(A){return super.fromJSON(A),this.currentPoint.fromArray(A.currentPoint),this}}class $C extends V0{constructor(A=[new p1(0,-0.5),new p1(0.5,0),new p1(0,0.5)],Q=12,J=0,K=Math.PI*2){super();this.type="LatheGeometry",this.parameters={points:A,segments:Q,phiStart:J,phiLength:K},Q=Math.floor(Q),K=zA(K,0,Math.PI*2);let C=[],U=[],Y=[],Z=[],X=[],E=1/Q,H=new I1,$=new p1,I=new I1,N=new I1,F=new I1,V=0,D=0;for(let L=0;L<=A.length-1;L++)switch(L){case 0:V=A[L+1].x-A[L].x,D=A[L+1].y-A[L].y,I.x=D*1,I.y=-V,I.z=D*0,F.copy(I),I.normalize(),Z.push(I.x,I.y,I.z);break;case A.length-1:Z.push(F.x,F.y,F.z);break;default:V=A[L+1].x-A[L].x,D=A[L+1].y-A[L].y,I.x=D*1,I.y=-V,I.z=D*0,N.copy(I),I.x+=F.x,I.y+=F.y,I.z+=F.z,I.normalize(),Z.push(I.x,I.y,I.z),F.copy(N)}for(let L=0;L<=Q;L++){let R=J+L*E*K,M=Math.sin(R),T=Math.cos(R);for(let h=0;h<=A.length-1;h++){H.x=A[h].x*M,H.y=A[h].y,H.z=A[h].x*T,U.push(H.x,H.y,H.z),$.x=L/Q,$.y=h/(A.length-1),Y.push($.x,$.y);let y=Z[3*h+0]*M,g=Z[3*h+1],f=Z[3*h+0]*T;X.push(y,g,f)}}for(let L=0;L0)R(!0);if(Q>0)R(!1)}this.setIndex(E),this.setAttribute("position",new L0(H,3)),this.setAttribute("normal",new L0($,3)),this.setAttribute("uv",new L0(I,2));function L(){let M=new I1,T=new I1,h=0,y=(Q-A)/J;for(let g=0;g<=C;g++){let f=[],u=g/C,d=u*(Q-A)+A;for(let n=0;n<=K;n++){let B=n/K,q=B*Z+Y,P=Math.sin(q),O=Math.cos(q);T.x=d*P,T.y=-u*J+V,T.z=d*O,H.push(T.x,T.y,T.z),M.set(P,y,O).normalize(),$.push(M.x,M.y,M.z),I.push(B,1-u),f.push(N++)}F.push(f)}for(let g=0;g0||f!==0)E.push(u,d,B),h+=3;if(Q>0||f!==C-1)E.push(d,n,B),h+=3}X.addGroup(D,h,0),D+=h}function R(M){let T=N,h=new p1,y=new I1,g=0,f=M===!0?A:Q,u=M===!0?1:-1;for(let n=1;n<=K;n++)H.push(0,V*u,0),$.push(0,u,0),I.push(0.5,0.5),N++;let d=N;for(let n=0;n<=K;n++){let q=n/K*Z+Y,P=Math.cos(q),O=Math.sin(q);y.x=f*O,y.y=V*u,y.z=f*P,H.push(y.x,y.y,y.z),$.push(0,u,0),h.x=P*0.5+0.5,h.y=O*0.5*u+0.5,I.push(h.x,h.y),N++}for(let n=0;n0.9&&y<0.1){if(R<0.2)U[L+0]+=1;if(M<0.2)U[L+2]+=1;if(T<0.2)U[L+4]+=1}}}function $(L){C.push(L.x,L.y,L.z)}function I(L,R){let M=L*3;R.x=A[M+0],R.y=A[M+1],R.z=A[M+2]}function N(){let L=new I1,R=new I1,M=new I1,T=new I1,h=new p1,y=new p1,g=new p1;for(let f=0,u=0;f80*J){Z=E=A[0],X=H=A[1];for(let F=J;FE)E=$;if(I>H)H=I}N=Math.max(E-Z,H-X),N=N!==0?32767/N:0}return uU(U,Y,J,Z,X,N,0),Y}};function gg(A,Q,J,K,C){let U,Y;if(C===k31(A,Q,J,K)>0)for(U=Q;U=Q;U-=K)Y=Ih(U,A[U],A[U+1],Y);if(Y&&lH(Y,Y.next))cU(Y),Y=Y.next;return Y}function VQ(A,Q){if(!A)return A;if(!Q)Q=A;let J=A,K;do if(K=!1,!J.steiner&&(lH(J,J.next)||s2(J.prev,J,J.next)===0)){if(cU(J),J=Q=J.prev,J===J.next)break;K=!0}else J=J.next;while(K||J!==Q);return Q}function uU(A,Q,J,K,C,U,Y){if(!A)return;if(!Y&&U)V31(A,K,C,U);let Z=A,X,E;while(A.prev!==A.next){if(X=A.prev,E=A.next,U?q31(A,K,C,U):I31(A)){Q.push(X.i/J|0),Q.push(A.i/J|0),Q.push(E.i/J|0),cU(A),A=E.next,Z=E.next;continue}if(A=E,A===Z){if(!Y)uU(VQ(A),Q,J,K,C,U,1);else if(Y===1)A=O31(VQ(A),Q,J),uU(A,Q,J,K,C,U,2);else if(Y===2)N31(A,Q,J,K,C,U);break}}}function I31(A){let Q=A.prev,J=A,K=A.next;if(s2(Q,J,K)>=0)return!1;let C=Q.x,U=J.x,Y=K.x,Z=Q.y,X=J.y,E=K.y,H=CU?C>Y?C:Y:U>Y?U:Y,N=Z>X?Z>E?Z:E:X>E?X:E,F=K.next;while(F!==Q){if(F.x>=H&&F.x<=I&&F.y>=$&&F.y<=N&&sK(C,Z,U,X,Y,E,F.x,F.y)&&s2(F.prev,F,F.next)>=0)return!1;F=F.next}return!0}function q31(A,Q,J,K){let C=A.prev,U=A,Y=A.next;if(s2(C,U,Y)>=0)return!1;let Z=C.x,X=U.x,E=Y.x,H=C.y,$=U.y,I=Y.y,N=ZX?Z>E?Z:E:X>E?X:E,D=H>$?H>I?H:I:$>I?$:I,L=cL(N,F,Q,J,K),R=cL(V,D,Q,J,K),M=A.prevZ,T=A.nextZ;while(M&&M.z>=L&&T&&T.z<=R){if(M.x>=N&&M.x<=V&&M.y>=F&&M.y<=D&&M!==C&&M!==Y&&sK(Z,H,X,$,E,I,M.x,M.y)&&s2(M.prev,M,M.next)>=0)return!1;if(M=M.prevZ,T.x>=N&&T.x<=V&&T.y>=F&&T.y<=D&&T!==C&&T!==Y&&sK(Z,H,X,$,E,I,T.x,T.y)&&s2(T.prev,T,T.next)>=0)return!1;T=T.nextZ}while(M&&M.z>=L){if(M.x>=N&&M.x<=V&&M.y>=F&&M.y<=D&&M!==C&&M!==Y&&sK(Z,H,X,$,E,I,M.x,M.y)&&s2(M.prev,M,M.next)>=0)return!1;M=M.prevZ}while(T&&T.z<=R){if(T.x>=N&&T.x<=V&&T.y>=F&&T.y<=D&&T!==C&&T!==Y&&sK(Z,H,X,$,E,I,T.x,T.y)&&s2(T.prev,T,T.next)>=0)return!1;T=T.nextZ}return!0}function O31(A,Q,J){let K=A;do{let C=K.prev,U=K.next.next;if(!lH(C,U)&&bg(C,K,K.next,U)&&mU(C,U)&&mU(U,C))Q.push(C.i/J|0),Q.push(K.i/J|0),Q.push(U.i/J|0),cU(K),cU(K.next),K=A=U;K=K.next}while(K!==A);return VQ(K)}function N31(A,Q,J,K,C,U){let Y=A;do{let Z=Y.next.next;while(Z!==Y.prev){if(Y.i!==Z.i&&P31(Y,Z)){let X=fg(Y,Z);Y=VQ(Y,Y.next),X=VQ(X,X.next),uU(Y,Q,J,K,C,U,0),uU(X,Q,J,K,C,U,0);return}Z=Z.next}Y=Y.next}while(Y!==A)}function L31(A,Q,J,K){let C=[],U,Y,Z,X,E;for(U=0,Y=Q.length;U=J.next.y&&J.next.y!==J.y){let I=J.x+(Y-J.y)*(J.next.x-J.x)/(J.next.y-J.y);if(I<=U&&I>K){if(K=I,C=J.x=J.x&&J.x>=X&&U!==J.x&&sK(YC.x||J.x===C.x&&D31(C,J))))C=J,H=$}J=J.next}while(J!==Z);return C}function D31(A,Q){return s2(A.prev,A,Q.prev)<0&&s2(Q.next,A,A.next)<0}function V31(A,Q,J,K){let C=A;do{if(C.z===0)C.z=cL(C.x,C.y,Q,J,K);C.prevZ=C.prev,C.nextZ=C.next,C=C.next}while(C!==A);C.prevZ.nextZ=null,C.prevZ=null,M31(C)}function M31(A){let Q,J,K,C,U,Y,Z,X,E=1;do{J=A,A=null,U=null,Y=0;while(J){Y++,K=J,Z=0;for(Q=0;Q0||X>0&&K){if(Z!==0&&(X===0||!K||J.z<=K.z))C=J,J=J.nextZ,Z--;else C=K,K=K.nextZ,X--;if(U)U.nextZ=C;else A=C;C.prevZ=U,U=C}J=K}U.nextZ=null,E*=2}while(Y>1);return A}function cL(A,Q,J,K,C){return A=(A-J)*C|0,Q=(Q-K)*C|0,A=(A|A<<8)&16711935,A=(A|A<<4)&252645135,A=(A|A<<2)&858993459,A=(A|A<<1)&1431655765,Q=(Q|Q<<8)&16711935,Q=(Q|Q<<4)&252645135,Q=(Q|Q<<2)&858993459,Q=(Q|Q<<1)&1431655765,A|Q<<1}function w31(A){let Q=A,J=A;do{if(Q.x=(A-Y)*(U-Z)&&(A-Y)*(K-Z)>=(J-Y)*(Q-Z)&&(J-Y)*(U-Z)>=(C-Y)*(K-Z)}function P31(A,Q){return A.next.i!==Q.i&&A.prev.i!==Q.i&&!_31(A,Q)&&(mU(A,Q)&&mU(Q,A)&&T31(A,Q)&&(s2(A.prev,A,Q.prev)||s2(A,Q.prev,Q))||lH(A,Q)&&s2(A.prev,A,A.next)>0&&s2(Q.prev,Q,Q.next)>0)}function s2(A,Q,J){return(Q.y-A.y)*(J.x-Q.x)-(Q.x-A.x)*(J.y-Q.y)}function lH(A,Q){return A.x===Q.x&&A.y===Q.y}function bg(A,Q,J,K){let C=p$(s2(A,Q,J)),U=p$(s2(A,Q,K)),Y=p$(s2(J,K,A)),Z=p$(s2(J,K,Q));if(C!==U&&Y!==Z)return!0;if(C===0&&f$(A,J,Q))return!0;if(U===0&&f$(A,K,Q))return!0;if(Y===0&&f$(J,A,K))return!0;if(Z===0&&f$(J,Q,K))return!0;return!1}function f$(A,Q,J){return Q.x<=Math.max(A.x,J.x)&&Q.x>=Math.min(A.x,J.x)&&Q.y<=Math.max(A.y,J.y)&&Q.y>=Math.min(A.y,J.y)}function p$(A){return A>0?1:A<0?-1:0}function _31(A,Q){let J=A;do{if(J.i!==A.i&&J.next.i!==A.i&&J.i!==Q.i&&J.next.i!==Q.i&&bg(J,J.next,A,Q))return!0;J=J.next}while(J!==A);return!1}function mU(A,Q){return s2(A.prev,A,A.next)<0?s2(A,Q,A.next)>=0&&s2(A,A.prev,Q)>=0:s2(A,Q,A.prev)<0||s2(A,A.next,Q)<0}function T31(A,Q){let J=A,K=!1,C=(A.x+Q.x)/2,U=(A.y+Q.y)/2;do{if(J.y>U!==J.next.y>U&&J.next.y!==J.y&&C<(J.next.x-J.x)*(U-J.y)/(J.next.y-J.y)+J.x)K=!K;J=J.next}while(J!==A);return K}function fg(A,Q){let J=new dL(A.i,A.x,A.y),K=new dL(Q.i,Q.x,Q.y),C=A.next,U=Q.prev;return A.next=Q,Q.prev=A,J.next=C,C.prev=J,K.next=J,J.prev=K,U.next=K,K.prev=U,K}function Ih(A,Q,J,K){let C=new dL(A,Q,J);if(!K)C.prev=C,C.next=C;else C.next=K.next,C.prev=K,K.next.prev=C,K.next=C;return C}function cU(A){if(A.next.prev=A.prev,A.prev.next=A.next,A.prevZ)A.prevZ.nextZ=A.nextZ;if(A.nextZ)A.nextZ.prevZ=A.prevZ}function dL(A,Q,J){this.i=A,this.x=Q,this.y=J,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function k31(A,Q,J,K){let C=0;for(let U=Q,Y=J-K;U2&&A[Q-1].equals(A[0]))A.pop()}function Oh(A,Q){for(let J=0;JNumber.EPSILON){let k1=Math.sqrt(H1),D1=Math.sqrt(Z1*Z1+j1*j1),G1=E1.x-q1/k1,w1=E1.y+C1/k1,G=Y1.x-j1/D1,z=Y1.y+Z1/D1,x=((G-G1)*j1-(z-w1)*Z1)/(C1*j1-q1*Z1);i=G1+C1*x-O1.x,c=w1+q1*x-O1.y;let m=i*i+c*c;if(m<=2)return new p1(i,c);else o=Math.sqrt(m/2)}else{let k1=!1;if(C1>Number.EPSILON){if(Z1>Number.EPSILON)k1=!0}else if(C1<-Number.EPSILON){if(Z1<-Number.EPSILON)k1=!0}else if(Math.sign(q1)===Math.sign(j1))k1=!0;if(k1)i=-q1,c=C1,o=Math.sqrt(H1);else i=C1,c=q1,o=Math.sqrt(H1/2)}return new p1(i/o,c/o)}let S=[];for(let O1=0,E1=q.length,Y1=E1-1,i=O1+1;O1=0;O1--){let E1=O1/V,Y1=I*Math.cos(E1*Math.PI/2),i=N*Math.sin(E1*Math.PI/2)+F;for(let c=0,o=q.length;c=0){let i=Y1,c=Y1-1;if(c<0)c=O1.length-1;for(let o=0,C1=E+V*2;o0)I.push(R,M,h);if(D!==J-1||Z0!==A>0)this.version++;this._anisotropy=A}get clearcoat(){return this._clearcoat}set clearcoat(A){if(this._clearcoat>0!==A>0)this.version++;this._clearcoat=A}get iridescence(){return this._iridescence}set iridescence(A){if(this._iridescence>0!==A>0)this.version++;this._iridescence=A}get dispersion(){return this._dispersion}set dispersion(A){if(this._dispersion>0!==A>0)this.version++;this._dispersion=A}get sheen(){return this._sheen}set sheen(A){if(this._sheen>0!==A>0)this.version++;this._sheen=A}get transmission(){return this._transmission}set transmission(A){if(this._transmission>0!==A>0)this.version++;this._transmission=A}copy(A){return super.copy(A),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=A.anisotropy,this.anisotropyRotation=A.anisotropyRotation,this.anisotropyMap=A.anisotropyMap,this.clearcoat=A.clearcoat,this.clearcoatMap=A.clearcoatMap,this.clearcoatRoughness=A.clearcoatRoughness,this.clearcoatRoughnessMap=A.clearcoatRoughnessMap,this.clearcoatNormalMap=A.clearcoatNormalMap,this.clearcoatNormalScale.copy(A.clearcoatNormalScale),this.dispersion=A.dispersion,this.ior=A.ior,this.iridescence=A.iridescence,this.iridescenceMap=A.iridescenceMap,this.iridescenceIOR=A.iridescenceIOR,this.iridescenceThicknessRange=[...A.iridescenceThicknessRange],this.iridescenceThicknessMap=A.iridescenceThicknessMap,this.sheen=A.sheen,this.sheenColor.copy(A.sheenColor),this.sheenColorMap=A.sheenColorMap,this.sheenRoughness=A.sheenRoughness,this.sheenRoughnessMap=A.sheenRoughnessMap,this.transmission=A.transmission,this.transmissionMap=A.transmissionMap,this.thickness=A.thickness,this.thicknessMap=A.thicknessMap,this.attenuationDistance=A.attenuationDistance,this.attenuationColor.copy(A.attenuationColor),this.specularIntensity=A.specularIntensity,this.specularIntensityMap=A.specularIntensityMap,this.specularColor.copy(A.specularColor),this.specularColorMap=A.specularColorMap,this}}class u6 extends _2{constructor(A){super();this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new y1(16777215),this.specular=new y1(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new y1(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new p1(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new t2,this.combine=0,this.reflectivity=1,this.refractionRatio=0.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.specular.copy(A.specular),this.shininess=A.shininess,this.map=A.map,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.emissive.copy(A.emissive),this.emissiveMap=A.emissiveMap,this.emissiveIntensity=A.emissiveIntensity,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.specularMap=A.specularMap,this.alphaMap=A.alphaMap,this.envMap=A.envMap,this.envMapRotation.copy(A.envMapRotation),this.combine=A.combine,this.reflectivity=A.reflectivity,this.refractionRatio=A.refractionRatio,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.flatShading=A.flatShading,this.fog=A.fog,this}}class sH extends _2{constructor(A){super();this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new y1(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new y1(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new p1(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.gradientMap=A.gradientMap,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.emissive.copy(A.emissive),this.emissiveMap=A.emissiveMap,this.emissiveIntensity=A.emissiveIntensity,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.alphaMap=A.alphaMap,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.fog=A.fog,this}}class B9 extends _2{constructor(A){super();this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new p1(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(A)}copy(A){return super.copy(A),this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.flatShading=A.flatShading,this}}class Q7 extends _2{constructor(A){super();this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new y1(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new y1(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new p1(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new t2,this.combine=0,this.reflectivity=1,this.refractionRatio=0.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.emissive.copy(A.emissive),this.emissiveMap=A.emissiveMap,this.emissiveIntensity=A.emissiveIntensity,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.specularMap=A.specularMap,this.alphaMap=A.alphaMap,this.envMap=A.envMap,this.envMapRotation.copy(A.envMapRotation),this.combine=A.combine,this.reflectivity=A.reflectivity,this.refractionRatio=A.refractionRatio,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.flatShading=A.flatShading,this.fog=A.fog,this}}class G4 extends _2{constructor(A){super();this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(A)}copy(A){return super.copy(A),this.depthPacking=A.depthPacking,this.map=A.map,this.alphaMap=A.alphaMap,this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this}}class PZ extends _2{constructor(A){super();this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(A)}copy(A){return super.copy(A),this.map=A.map,this.alphaMap=A.alphaMap,this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this}}class oH extends _2{constructor(A){super();this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new y1(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new p1(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.defines={MATCAP:""},this.color.copy(A.color),this.matcap=A.matcap,this.map=A.map,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.alphaMap=A.alphaMap,this.flatShading=A.flatShading,this.fog=A.fog,this}}class iH extends pA{constructor(A){super();this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(A)}copy(A){return super.copy(A),this.scale=A.scale,this.dashSize=A.dashSize,this.gapSize=A.gapSize,this}}function RQ(A,Q,J){if(!A||!J&&A.constructor===Q)return A;if(typeof Q.BYTES_PER_ELEMENT==="number")return new Q(A);return Array.prototype.slice.call(A)}function pg(A){return ArrayBuffer.isView(A)&&!(A instanceof DataView)}function ug(A){function Q(C,U){return A[C]-A[U]}let J=A.length,K=new Array(J);for(let C=0;C!==J;++C)K[C]=C;return K.sort(Q),K}function lL(A,Q,J){let K=A.length,C=new A.constructor(K);for(let U=0,Y=0;Y!==K;++U){let Z=J[U]*Q;for(let X=0;X!==Q;++X)C[Y++]=A[Z+X]}return C}function bF(A,Q,J,K){let C=1,U=A[0];while(U!==void 0&&U[K]===void 0)U=A[C++];if(U===void 0)return;let Y=U[K];if(Y===void 0)return;if(Array.isArray(Y))do{if(Y=U[K],Y!==void 0)Q.push(U.time),J.push.apply(J,Y);U=A[C++]}while(U!==void 0);else if(Y.toArray!==void 0)do{if(Y=U[K],Y!==void 0)Q.push(U.time),Y.toArray(J,J.length);U=A[C++]}while(U!==void 0);else do{if(Y=U[K],Y!==void 0)Q.push(U.time),J.push(Y);U=A[C++]}while(U!==void 0)}function x31(A,Q,J,K,C=30){let U=A.clone();U.name=Q;let Y=[];for(let X=0;X=K)continue;$.push(E.times[N]);for(let V=0;VU.tracks[X].times[0])Z=U.tracks[X].times[0];for(let X=0;X=Z.times[F]){let L=F*$+H,R=L+$-H;V=Z.values.slice(L,R)}else{let L=Z.createInterpolant(),R=H,M=$-H;L.evaluate(U),V=L.resultBuffer.slice(R,M)}if(X==="quaternion")new t0().fromArray(V).normalize().conjugate().toArray(V);let D=E.times.length;for(let L=0;L=C)){let Y=Q[1];if(A=C)break Q}U=J,J=0;break J}break A}while(J>>1;if(AQ)--U;if(++U,C!==0||U!==K){if(C>=U)U=Math.max(U,1),C=U-1;let Y=this.getValueSize();this.times=J.slice(C,U),this.values=this.values.slice(C*Y,U*Y)}return this}validate(){let A=!0,Q=this.getValueSize();if(Q-Math.floor(Q)!==0)console.error("THREE.KeyframeTrack: Invalid value size in track.",this),A=!1;let J=this.times,K=this.values,C=J.length;if(C===0)console.error("THREE.KeyframeTrack: Track is empty.",this),A=!1;let U=null;for(let Y=0;Y!==C;Y++){let Z=J[Y];if(typeof Z==="number"&&isNaN(Z)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,Y,Z),A=!1;break}if(U!==null&&U>Z){console.error("THREE.KeyframeTrack: Out of order keys.",this,Y,Z,U),A=!1;break}U=Z}if(K!==void 0){if(pg(K))for(let Y=0,Z=K.length;Y!==Z;++Y){let X=K[Y];if(isNaN(X)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,Y,X),A=!1;break}}}return A}optimize(){let A=this.times.slice(),Q=this.values.slice(),J=this.getValueSize(),K=this.getInterpolation()===2302,C=A.length-1,U=1;for(let Y=1;Y0){A[U]=A[C];for(let Y=C*J,Z=U*J,X=0;X!==J;++X)Q[Z+X]=Q[Y+X];++U}if(U!==A.length)this.times=A.slice(0,U),this.values=Q.slice(0,U*J);else this.times=A,this.values=Q;return this}clone(){let A=this.times.slice(),Q=this.values.slice(),K=new this.constructor(this.name,A,Q);return K.createInterpolant=this.createInterpolant,K}}X9.prototype.TimeBufferType=Float32Array;X9.prototype.ValueBufferType=Float32Array;X9.prototype.DefaultInterpolation=2301;class K3 extends X9{constructor(A,Q,J){super(A,Q,J)}}K3.prototype.ValueTypeName="bool";K3.prototype.ValueBufferType=Array;K3.prototype.DefaultInterpolation=2300;K3.prototype.InterpolantFactoryMethodLinear=void 0;K3.prototype.InterpolantFactoryMethodSmooth=void 0;class qC extends X9{}qC.prototype.ValueTypeName="color";class Y6 extends X9{}Y6.prototype.ValueTypeName="number";class tH extends N5{constructor(A,Q,J,K){super(A,Q,J,K)}interpolate_(A,Q,J,K){let C=this.resultBuffer,U=this.sampleValues,Y=this.valueSize,Z=(J-Q)/(K-Q),X=A*Y;for(let E=X+Y;X!==E;X+=4)t0.slerpFlat(C,0,U,X-Y,U,X,Z);return C}}class s8 extends X9{InterpolantFactoryMethodLinear(A){return new tH(this.times,this.values,this.getValueSize(),A)}}s8.prototype.ValueTypeName="quaternion";s8.prototype.InterpolantFactoryMethodSmooth=void 0;class J7 extends X9{constructor(A,Q,J){super(A,Q,J)}}J7.prototype.ValueTypeName="string";J7.prototype.ValueBufferType=Array;J7.prototype.DefaultInterpolation=2300;J7.prototype.InterpolantFactoryMethodLinear=void 0;J7.prototype.InterpolantFactoryMethodSmooth=void 0;class h8 extends X9{}h8.prototype.ValueTypeName="vector";class L8{constructor(A="",Q=-1,J=[],K=2500){if(this.name=A,this.tracks=J,this.duration=Q,this.blendMode=K,this.uuid=J9(),this.duration<0)this.resetDuration()}static parse(A){let Q=[],J=A.tracks,K=1/(A.fps||1);for(let U=0,Y=J.length;U!==Y;++U)Q.push(g31(J[U]).scale(K));let C=new this(A.name,A.duration,Q,A.blendMode);return C.uuid=A.uuid,C}static toJSON(A){let Q=[],J=A.tracks,K={name:A.name,duration:A.duration,tracks:Q,uuid:A.uuid,blendMode:A.blendMode};for(let C=0,U=J.length;C!==U;++C)Q.push(X9.toJSON(J[C]));return K}static CreateFromMorphTargetSequence(A,Q,J,K){let C=Q.length,U=[];for(let Y=0;Y1){let H=E[1],$=K[H];if(!$)K[H]=$=[];$.push(X)}}let U=[];for(let Y in K)U.push(this.CreateFromMorphTargetSequence(Y,K[Y],Q,J));return U}static parseAnimation(A,Q){if(!A)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;let J=function(H,$,I,N,F){if(I.length!==0){let V=[],D=[];if(bF(I,V,D,N),V.length!==0)F.push(new H($,V,D))}},K=[],C=A.name||"default",U=A.fps||30,Y=A.blendMode,Z=A.length||-1,X=A.hierarchy||[];for(let H=0;H{if(Q)Q(C);this.manager.itemEnd(A)},0),C;if(s3[A]!==void 0){s3[A].push({onLoad:Q,onProgress:J,onError:K});return}s3[A]=[],s3[A].push({onLoad:Q,onProgress:J,onError:K});let U=new Request(A,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),Y=this.mimeType,Z=this.responseType;fetch(U).then((X)=>{if(X.status===200||X.status===0){if(X.status===0)console.warn("THREE.FileLoader: HTTP Status 0 received.");if(typeof ReadableStream==="undefined"||X.body===void 0||X.body.getReader===void 0)return X;let E=s3[A],H=X.body.getReader(),$=X.headers.get("X-File-Size")||X.headers.get("Content-Length"),I=$?parseInt($):0,N=I!==0,F=0,V=new ReadableStream({start(D){L();function L(){H.read().then(({done:R,value:M})=>{if(R)D.close();else{F+=M.byteLength;let T=new ProgressEvent("progress",{lengthComputable:N,loaded:F,total:I});for(let h=0,y=E.length;h{D.error(R)})}}});return new Response(V)}else throw new cg(`fetch for "${X.url}" responded with ${X.status}: ${X.statusText}`,X)}).then((X)=>{switch(Z){case"arraybuffer":return X.arrayBuffer();case"blob":return X.blob();case"document":return X.text().then((E)=>{return new DOMParser().parseFromString(E,Y)});case"json":return X.json();default:if(Y===void 0)return X.text();else{let H=/charset="?([^;"\s]*)"?/i.exec(Y),$=H&&H[1]?H[1].toLowerCase():void 0,I=new TextDecoder($);return X.arrayBuffer().then((N)=>I.decode(N))}}}).then((X)=>{l5.add(A,X);let E=s3[A];delete s3[A];for(let H=0,$=E.length;H<$;H++){let I=E[H];if(I.onLoad)I.onLoad(X)}}).catch((X)=>{let E=s3[A];if(E===void 0)throw this.manager.itemError(A),X;delete s3[A];for(let H=0,$=E.length;H<$;H++){let I=E[H];if(I.onError)I.onError(X)}this.manager.itemError(A)}).finally(()=>{this.manager.itemEnd(A)}),this.manager.itemStart(A)}setResponseType(A){return this.responseType=A,this}setMimeType(A){return this.mimeType=A,this}}class fF extends JA{constructor(A){super(A)}load(A,Q,J,K){let C=this,U=new KA(this.manager);U.setPath(this.path),U.setRequestHeader(this.requestHeader),U.setWithCredentials(this.withCredentials),U.load(A,function(Y){try{Q(C.parse(JSON.parse(Y)))}catch(Z){if(K)K(Z);else console.error(Z);C.manager.itemError(A)}},J,K)}parse(A){let Q=[];for(let J=0;J0?!0:!1;else K.vertexColors=A.vertexColors;if(A.uniforms!==void 0)for(let C in A.uniforms){let U=A.uniforms[C];switch(K.uniforms[C]={},U.type){case"t":K.uniforms[C].value=J(U.value);break;case"c":K.uniforms[C].value=new y1().setHex(U.value);break;case"v2":K.uniforms[C].value=new p1().fromArray(U.value);break;case"v3":K.uniforms[C].value=new I1().fromArray(U.value);break;case"v4":K.uniforms[C].value=new X0().fromArray(U.value);break;case"m3":K.uniforms[C].value=new a0().fromArray(U.value);break;case"m4":K.uniforms[C].value=new Y0().fromArray(U.value);break;default:K.uniforms[C].value=U.value}}if(A.defines!==void 0)K.defines=A.defines;if(A.vertexShader!==void 0)K.vertexShader=A.vertexShader;if(A.fragmentShader!==void 0)K.fragmentShader=A.fragmentShader;if(A.glslVersion!==void 0)K.glslVersion=A.glslVersion;if(A.extensions!==void 0)for(let C in A.extensions)K.extensions[C]=A.extensions[C];if(A.lights!==void 0)K.lights=A.lights;if(A.clipping!==void 0)K.clipping=A.clipping;if(A.size!==void 0)K.size=A.size;if(A.sizeAttenuation!==void 0)K.sizeAttenuation=A.sizeAttenuation;if(A.map!==void 0)K.map=J(A.map);if(A.matcap!==void 0)K.matcap=J(A.matcap);if(A.alphaMap!==void 0)K.alphaMap=J(A.alphaMap);if(A.bumpMap!==void 0)K.bumpMap=J(A.bumpMap);if(A.bumpScale!==void 0)K.bumpScale=A.bumpScale;if(A.normalMap!==void 0)K.normalMap=J(A.normalMap);if(A.normalMapType!==void 0)K.normalMapType=A.normalMapType;if(A.normalScale!==void 0){let C=A.normalScale;if(Array.isArray(C)===!1)C=[C,C];K.normalScale=new p1().fromArray(C)}if(A.displacementMap!==void 0)K.displacementMap=J(A.displacementMap);if(A.displacementScale!==void 0)K.displacementScale=A.displacementScale;if(A.displacementBias!==void 0)K.displacementBias=A.displacementBias;if(A.roughnessMap!==void 0)K.roughnessMap=J(A.roughnessMap);if(A.metalnessMap!==void 0)K.metalnessMap=J(A.metalnessMap);if(A.emissiveMap!==void 0)K.emissiveMap=J(A.emissiveMap);if(A.emissiveIntensity!==void 0)K.emissiveIntensity=A.emissiveIntensity;if(A.specularMap!==void 0)K.specularMap=J(A.specularMap);if(A.specularIntensityMap!==void 0)K.specularIntensityMap=J(A.specularIntensityMap);if(A.specularColorMap!==void 0)K.specularColorMap=J(A.specularColorMap);if(A.envMap!==void 0)K.envMap=J(A.envMap);if(A.envMapRotation!==void 0)K.envMapRotation.fromArray(A.envMapRotation);if(A.envMapIntensity!==void 0)K.envMapIntensity=A.envMapIntensity;if(A.reflectivity!==void 0)K.reflectivity=A.reflectivity;if(A.refractionRatio!==void 0)K.refractionRatio=A.refractionRatio;if(A.lightMap!==void 0)K.lightMap=J(A.lightMap);if(A.lightMapIntensity!==void 0)K.lightMapIntensity=A.lightMapIntensity;if(A.aoMap!==void 0)K.aoMap=J(A.aoMap);if(A.aoMapIntensity!==void 0)K.aoMapIntensity=A.aoMapIntensity;if(A.gradientMap!==void 0)K.gradientMap=J(A.gradientMap);if(A.clearcoatMap!==void 0)K.clearcoatMap=J(A.clearcoatMap);if(A.clearcoatRoughnessMap!==void 0)K.clearcoatRoughnessMap=J(A.clearcoatRoughnessMap);if(A.clearcoatNormalMap!==void 0)K.clearcoatNormalMap=J(A.clearcoatNormalMap);if(A.clearcoatNormalScale!==void 0)K.clearcoatNormalScale=new p1().fromArray(A.clearcoatNormalScale);if(A.iridescenceMap!==void 0)K.iridescenceMap=J(A.iridescenceMap);if(A.iridescenceThicknessMap!==void 0)K.iridescenceThicknessMap=J(A.iridescenceThicknessMap);if(A.transmissionMap!==void 0)K.transmissionMap=J(A.transmissionMap);if(A.thicknessMap!==void 0)K.thicknessMap=J(A.thicknessMap);if(A.anisotropyMap!==void 0)K.anisotropyMap=J(A.anisotropyMap);if(A.sheenColorMap!==void 0)K.sheenColorMap=J(A.sheenColorMap);if(A.sheenRoughnessMap!==void 0)K.sheenRoughnessMap=J(A.sheenRoughnessMap);return K}setTextures(A){return this.textures=A,this}createMaterialFromType(A){return jZ.createMaterialFromType(A)}static createMaterialFromType(A){return new{ShadowMaterial:nH,SpriteMaterial:dQ,RawShaderMaterial:A7,ShaderMaterial:T0,PointsMaterial:X6,MeshPhysicalMaterial:rA,MeshStandardMaterial:p2,MeshPhongMaterial:u6,MeshToonMaterial:sH,MeshNormalMaterial:B9,MeshLambertMaterial:Q7,MeshDepthMaterial:G4,MeshDistanceMaterial:PZ,MeshBasicMaterial:BA,MeshMatcapMaterial:oH,LineDashedMaterial:iH,LineBasicMaterial:pA,Material:_2}[A]}}class A8{static decodeText(A){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),typeof TextDecoder!=="undefined")return(/*@__PURE__*/new TextDecoder()).decode(A);let Q="";for(let J=0,K=A.length;J0){let Z=new OC(Q);C=new MQ(Z),C.setCrossOrigin(this.crossOrigin);for(let X=0,E=A.length;X0){K=new MQ(this.manager),K.setCrossOrigin(this.crossOrigin);for(let U=0,Y=A.length;U{let V=new DA;V.min.fromArray(F.boxMin),V.max.fromArray(F.boxMax);let D=new O2;return D.radius=F.sphereRadius,D.center.fromArray(F.sphereCenter),{boxInitialized:F.boxInitialized,box:V,sphereInitialized:F.sphereInitialized,sphere:D}}),U._maxInstanceCount=A.maxInstanceCount,U._maxVertexCount=A.maxVertexCount,U._maxIndexCount=A.maxIndexCount,U._geometryInitialized=A.geometryInitialized,U._geometryCount=A.geometryCount,U._matricesTexture=X(A.matricesTexture.uuid),A.colorsTexture!==void 0)U._colorsTexture=X(A.colorsTexture.uuid);break;case"LOD":U=new hH;break;case"Line":U=new e2(Y(A.geometry),Z(A.material));break;case"LineLoop":U=new H4(Y(A.geometry),Z(A.material));break;case"LineSegments":U=new T2(Y(A.geometry),Z(A.material));break;case"PointCloud":case"Points":U=new F6(Y(A.geometry),Z(A.material));break;case"Sprite":U=new XC(Z(A.material));break;case"Group":U=new cA;break;case"Bone":U=new h9;break;default:U=new AA}if(U.uuid=A.uuid,A.name!==void 0)U.name=A.name;if(A.matrix!==void 0){if(U.matrix.fromArray(A.matrix),A.matrixAutoUpdate!==void 0)U.matrixAutoUpdate=A.matrixAutoUpdate;if(U.matrixAutoUpdate)U.matrix.decompose(U.position,U.quaternion,U.scale)}else{if(A.position!==void 0)U.position.fromArray(A.position);if(A.rotation!==void 0)U.rotation.fromArray(A.rotation);if(A.quaternion!==void 0)U.quaternion.fromArray(A.quaternion);if(A.scale!==void 0)U.scale.fromArray(A.scale)}if(A.up!==void 0)U.up.fromArray(A.up);if(A.castShadow!==void 0)U.castShadow=A.castShadow;if(A.receiveShadow!==void 0)U.receiveShadow=A.receiveShadow;if(A.shadow){if(A.shadow.intensity!==void 0)U.shadow.intensity=A.shadow.intensity;if(A.shadow.bias!==void 0)U.shadow.bias=A.shadow.bias;if(A.shadow.normalBias!==void 0)U.shadow.normalBias=A.shadow.normalBias;if(A.shadow.radius!==void 0)U.shadow.radius=A.shadow.radius;if(A.shadow.mapSize!==void 0)U.shadow.mapSize.fromArray(A.shadow.mapSize);if(A.shadow.camera!==void 0)U.shadow.camera=this.parseObject(A.shadow.camera)}if(A.visible!==void 0)U.visible=A.visible;if(A.frustumCulled!==void 0)U.frustumCulled=A.frustumCulled;if(A.renderOrder!==void 0)U.renderOrder=A.renderOrder;if(A.userData!==void 0)U.userData=A.userData;if(A.layers!==void 0)U.layers.mask=A.layers;if(A.children!==void 0){let $=A.children;for(let I=0;I<$.length;I++)U.add(this.parseObject($[I],Q,J,K,C))}if(A.animations!==void 0){let $=A.animations;for(let I=0;I<$.length;I++){let N=$[I];U.animations.push(C[N])}}if(A.type==="LOD"){if(A.autoUpdate!==void 0)U.autoUpdate=A.autoUpdate;let $=A.levels;for(let I=0;I<$.length;I++){let N=$[I],F=U.getObjectByProperty("uuid",N.object);if(F!==void 0)U.addLevel(F,N.distance,N.hysteresis)}}return U}bindSkeletons(A,Q){if(Object.keys(Q).length===0)return;A.traverse(function(J){if(J.isSkinnedMesh===!0&&J.skeleton!==void 0){let K=Q[J.skeleton];if(K===void 0)console.warn("THREE.ObjectLoader: No skeleton found with UUID:",J.skeleton);else J.bind(K,J.bindMatrix)}})}bindLightTargets(A){A.traverse(function(Q){if(Q.isDirectionalLight||Q.isSpotLight){let J=Q.target,K=A.getObjectByProperty("uuid",J);if(K!==void 0)Q.target=K;else Q.target=new AA}})}}var b31={UVMapping:300,CubeReflectionMapping:301,CubeRefractionMapping:302,EquirectangularReflectionMapping:303,EquirectangularRefractionMapping:304,CubeUVReflectionMapping:306},Dh={RepeatWrapping:1000,ClampToEdgeWrapping:1001,MirroredRepeatWrapping:1002},Vh={NearestFilter:1003,NearestMipmapNearestFilter:1004,NearestMipmapLinearFilter:1005,LinearFilter:1006,LinearMipmapNearestFilter:1007,LinearMipmapLinearFilter:1008};class sQ extends JA{constructor(A){super(A);if(this.isImageBitmapLoader=!0,typeof createImageBitmap==="undefined")console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported.");if(typeof fetch==="undefined")console.warn("THREE.ImageBitmapLoader: fetch() not supported.");this.options={premultiplyAlpha:"none"}}setOptions(A){return this.options=A,this}load(A,Q,J,K){if(A===void 0)A="";if(this.path!==void 0)A=this.path+A;A=this.manager.resolveURL(A);let C=this,U=l5.get(A);if(U!==void 0){if(C.manager.itemStart(A),U.then){U.then((X)=>{if(Q)Q(X);C.manager.itemEnd(A)}).catch((X)=>{if(K)K(X)});return}return setTimeout(function(){if(Q)Q(U);C.manager.itemEnd(A)},0),U}let Y={};Y.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",Y.headers=this.requestHeader;let Z=fetch(A,Y).then(function(X){return X.blob()}).then(function(X){return createImageBitmap(X,Object.assign(C.options,{colorSpaceConversion:"none"}))}).then(function(X){if(l5.add(A,X),Q)Q(X);return C.manager.itemEnd(A),X}).catch(function(X){if(K)K(X);l5.remove(A),C.manager.itemError(A),C.manager.itemEnd(A)});l5.add(A,Z),C.manager.itemStart(A)}}var u$;class yZ{static getContext(){if(u$===void 0)u$=new(window.AudioContext||window.webkitAudioContext);return u$}static setContext(A){u$=A}}class uF extends JA{constructor(A){super(A)}load(A,Q,J,K){let C=this,U=new KA(this.manager);U.setResponseType("arraybuffer"),U.setPath(this.path),U.setRequestHeader(this.requestHeader),U.setWithCredentials(this.withCredentials),U.load(A,function(Z){try{let X=Z.slice(0);yZ.getContext().decodeAudioData(X,function(H){Q(H)}).catch(Y)}catch(X){Y(X)}},J,K);function Y(Z){if(K)K(Z);else console.error(Z);C.manager.itemError(A)}}}var Mh=/*@__PURE__*/new Y0,wh=/*@__PURE__*/new Y0,qQ=/*@__PURE__*/new Y0;class FC{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=0.064,this.cameraL=new kA,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new kA,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(A){let Q=this._cache;if(Q.focus!==A.focus||Q.fov!==A.fov||Q.aspect!==A.aspect*this.aspect||Q.near!==A.near||Q.far!==A.far||Q.zoom!==A.zoom||Q.eyeSep!==this.eyeSep){Q.focus=A.focus,Q.fov=A.fov,Q.aspect=A.aspect*this.aspect,Q.near=A.near,Q.far=A.far,Q.zoom=A.zoom,Q.eyeSep=this.eyeSep,qQ.copy(A.projectionMatrix);let K=Q.eyeSep/2,C=K*Q.near/Q.focus,U=Q.near*Math.tan(zQ*Q.fov*0.5)/Q.zoom,Y,Z;wh.elements[12]=-K,Mh.elements[12]=K,Y=-U*Q.aspect+C,Z=U*Q.aspect+C,qQ.elements[0]=2*Q.near/(Z-Y),qQ.elements[8]=(Z+Y)/(Z-Y),this.cameraL.projectionMatrix.copy(qQ),Y=-U*Q.aspect-C,Z=U*Q.aspect-C,qQ.elements[0]=2*Q.near/(Z-Y),qQ.elements[8]=(Z+Y)/(Z-Y),this.cameraR.projectionMatrix.copy(qQ)}this.cameraL.matrixWorld.copy(A.matrixWorld).multiply(wh),this.cameraR.matrixWorld.copy(A.matrixWorld).multiply(Mh)}}class JG extends kA{constructor(A=[]){super();this.isArrayCamera=!0,this.cameras=A,this.index=0}}class Y3{constructor(A=!0){this.autoStart=A,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Ph(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let A=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){let Q=Ph();A=(Q-this.oldTime)/1000,this.oldTime=Q,this.elapsedTime+=A}return A}}function Ph(){return performance.now()}var OQ=/*@__PURE__*/new I1,_h=/*@__PURE__*/new t0,f31=/*@__PURE__*/new I1,NQ=/*@__PURE__*/new I1;class mF extends AA{constructor(){super();this.type="AudioListener",this.context=yZ.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Y3}getInput(){return this.gain}removeFilter(){if(this.filter!==null)this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null;return this}getFilter(){return this.filter}setFilter(A){if(this.filter!==null)this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination);else this.gain.disconnect(this.context.destination);return this.filter=A,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(A){return this.gain.gain.setTargetAtTime(A,this.context.currentTime,0.01),this}updateMatrixWorld(A){super.updateMatrixWorld(A);let Q=this.context.listener,J=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(OQ,_h,f31),NQ.set(0,0,-1).applyQuaternion(_h),Q.positionX){let K=this.context.currentTime+this.timeDelta;Q.positionX.linearRampToValueAtTime(OQ.x,K),Q.positionY.linearRampToValueAtTime(OQ.y,K),Q.positionZ.linearRampToValueAtTime(OQ.z,K),Q.forwardX.linearRampToValueAtTime(NQ.x,K),Q.forwardY.linearRampToValueAtTime(NQ.y,K),Q.forwardZ.linearRampToValueAtTime(NQ.z,K),Q.upX.linearRampToValueAtTime(J.x,K),Q.upY.linearRampToValueAtTime(J.y,K),Q.upZ.linearRampToValueAtTime(J.z,K)}else Q.setPosition(OQ.x,OQ.y,OQ.z),Q.setOrientation(NQ.x,NQ.y,NQ.z,J.x,J.y,J.z)}}class KG extends AA{constructor(A){super();this.type="Audio",this.listener=A,this.context=A.context,this.gain=this.context.createGain(),this.gain.connect(A.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(A){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=A,this.connect(),this}setMediaElementSource(A){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(A),this.connect(),this}setMediaStreamSource(A){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(A),this.connect(),this}setBuffer(A){if(this.buffer=A,this.sourceType="buffer",this.autoplay)this.play();return this}play(A=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+A;let Q=this.context.createBufferSource();return Q.buffer=this.buffer,Q.loop=this.loop,Q.loopStart=this.loopStart,Q.loopEnd=this.loopEnd,Q.onended=this.onEnded.bind(this),Q.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=Q,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}if(this.isPlaying===!0){if(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0)this._progress=this._progress%(this.duration||this.buffer.duration);this.source.stop(),this.source.onended=null,this.isPlaying=!1}return this}stop(A=0){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}if(this._progress=0,this.source!==null)this.source.stop(this.context.currentTime+A),this.source.onended=null;return this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let A=1,Q=this.filters.length;A0){this.source.disconnect(this.filters[0]);for(let A=1,Q=this.filters.length;A0)this._mixBufferRegionAdditive(J,K,this._addIndex*Q,1,Q);for(let Z=Q,X=Q+Q;Z!==X;++Z)if(J[Z]!==J[Z+Q]){Y.setValue(J,K);break}}saveOriginalState(){let A=this.binding,Q=this.buffer,J=this.valueSize,K=J*this._origIndex;A.getValue(Q,K);for(let C=J,U=K;C!==U;++C)Q[C]=Q[K+C%J];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let A=this.valueSize*3;this.binding.setValue(this.buffer,A)}_setAdditiveIdentityNumeric(){let A=this._addIndex*this.valueSize,Q=A+this.valueSize;for(let J=A;J=0.5)for(let U=0;U!==C;++U)A[Q+U]=A[J+U]}_slerp(A,Q,J,K){t0.slerpFlat(A,Q,A,Q,A,J,K)}_slerpAdditive(A,Q,J,K,C){let U=this._workIndex*C;t0.multiplyQuaternionsFlat(A,U,A,Q,A,J),t0.slerpFlat(A,Q,A,Q,A,U,K)}_lerp(A,Q,J,K,C){let U=1-K;for(let Y=0;Y!==C;++Y){let Z=Q+Y;A[Z]=A[Z]*U+A[J+Y]*K}}_lerpAdditive(A,Q,J,K,C){for(let U=0;U!==C;++U){let Y=Q+U;A[Y]=A[Y]+A[J+U]*K}}}var lF="\\[\\]\\.:\\/",u31=new RegExp("["+lF+"]","g"),nF="[^"+lF+"]",m31="[^"+lF.replace("\\.","")+"]",c31=/*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace("WC",nF),d31=/*@__PURE__*/ /(WCOD+)?/.source.replace("WCOD",m31),l31=/*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",nF),n31=/*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC",nF),s31=new RegExp("^"+c31+d31+l31+n31+"$"),o31=["material","materials","bones","map"];class sg{constructor(A,Q,J){let K=J||RA.parseTrackName(Q);this._targetGroup=A,this._bindings=A.subscribe_(Q,K)}getValue(A,Q){this.bind();let J=this._targetGroup.nCachedObjects_,K=this._bindings[J];if(K!==void 0)K.getValue(A,Q)}setValue(A,Q){let J=this._bindings;for(let K=this._targetGroup.nCachedObjects_,C=J.length;K!==C;++K)J[K].setValue(A,Q)}bind(){let A=this._bindings;for(let Q=this._targetGroup.nCachedObjects_,J=A.length;Q!==J;++Q)A[Q].bind()}unbind(){let A=this._bindings;for(let Q=this._targetGroup.nCachedObjects_,J=A.length;Q!==J;++Q)A[Q].unbind()}}class RA{constructor(A,Q,J){this.path=Q,this.parsedPath=J||RA.parseTrackName(Q),this.node=RA.findNode(A,this.parsedPath.nodeName),this.rootNode=A,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(A,Q,J){if(!(A&&A.isAnimationObjectGroup))return new RA(A,Q,J);else return new RA.Composite(A,Q,J)}static sanitizeNodeName(A){return A.replace(/\s/g,"_").replace(u31,"")}static parseTrackName(A){let Q=s31.exec(A);if(Q===null)throw new Error("PropertyBinding: Cannot parse trackName: "+A);let J={nodeName:Q[2],objectName:Q[3],objectIndex:Q[4],propertyName:Q[5],propertyIndex:Q[6]},K=J.nodeName&&J.nodeName.lastIndexOf(".");if(K!==void 0&&K!==-1){let C=J.nodeName.substring(K+1);if(o31.indexOf(C)!==-1)J.nodeName=J.nodeName.substring(0,K),J.objectName=C}if(J.propertyName===null||J.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+A);return J}static findNode(A,Q){if(Q===void 0||Q===""||Q==="."||Q===-1||Q===A.name||Q===A.uuid)return A;if(A.skeleton){let J=A.skeleton.getBoneByName(Q);if(J!==void 0)return J}if(A.children){let J=function(C){for(let U=0;U=C){let H=C++,$=A[H];Q[$.uuid]=E,A[E]=$,Q[X]=H,A[H]=Z;for(let I=0,N=K;I!==N;++I){let F=J[I],V=F[H],D=F[E];F[E]=V,F[H]=D}}}this.nCachedObjects_=C}uncache(){let A=this._objects,Q=this._indicesByUUID,J=this._bindings,K=J.length,C=this.nCachedObjects_,U=A.length;for(let Y=0,Z=arguments.length;Y!==Z;++Y){let X=arguments[Y],E=X.uuid,H=Q[E];if(H!==void 0)if(delete Q[E],H0)Q[I.uuid]=H;A[H]=I,A.pop();for(let N=0,F=K;N!==F;++N){let V=J[N];V[H]=V[$],V.pop()}}}this.nCachedObjects_=C}subscribe_(A,Q){let J=this._bindingsIndicesByPath,K=J[A],C=this._bindings;if(K!==void 0)return C[K];let U=this._paths,Y=this._parsedPaths,Z=this._objects,X=Z.length,E=this.nCachedObjects_,H=new Array(X);K=C.length,J[A]=K,U.push(A),Y.push(Q),C.push(H);for(let $=E,I=Z.length;$!==I;++$){let N=Z[$];H[$]=new RA(N,A,Q)}return H}unsubscribe_(A){let Q=this._bindingsIndicesByPath,J=Q[A];if(J!==void 0){let K=this._paths,C=this._parsedPaths,U=this._bindings,Y=U.length-1,Z=U[Y],X=A[Y];Q[X]=J,U[J]=Z,U.pop(),C[J]=C[Y],C.pop(),K[J]=K[Y],K.pop()}}}class YG{constructor(A,Q,J=null,K=Q.blendMode){this._mixer=A,this._clip=Q,this._localRoot=J,this.blendMode=K;let C=Q.tracks,U=C.length,Y=new Array(U),Z={endingStart:2400,endingEnd:2400};for(let X=0;X!==U;++X){let E=C[X].createInterpolant(null);Y[X]=E,E.settings=Z}this._interpolantSettings=Z,this._interpolants=Y,this._propertyBindings=new Array(U),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(A){return this._startTime=A,this}setLoop(A,Q){return this.loop=A,this.repetitions=Q,this}setEffectiveWeight(A){return this.weight=A,this._effectiveWeight=this.enabled?A:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(A){return this._scheduleFading(A,0,1)}fadeOut(A){return this._scheduleFading(A,1,0)}crossFadeFrom(A,Q,J){if(A.fadeOut(Q),this.fadeIn(Q),J){let K=this._clip.duration,C=A._clip.duration,U=C/K,Y=K/C;A.warp(1,U,Q),this.warp(Y,1,Q)}return this}crossFadeTo(A,Q,J){return A.crossFadeFrom(this,Q,J)}stopFading(){let A=this._weightInterpolant;if(A!==null)this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(A);return this}setEffectiveTimeScale(A){return this.timeScale=A,this._effectiveTimeScale=this.paused?0:A,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(A){return this.timeScale=this._clip.duration/A,this.stopWarping()}syncWith(A){return this.time=A.time,this.timeScale=A.timeScale,this.stopWarping()}halt(A){return this.warp(this._effectiveTimeScale,0,A)}warp(A,Q,J){let K=this._mixer,C=K.time,U=this.timeScale,Y=this._timeScaleInterpolant;if(Y===null)Y=K._lendControlInterpolant(),this._timeScaleInterpolant=Y;let{parameterPositions:Z,sampleValues:X}=Y;return Z[0]=C,Z[1]=C+J,X[0]=A/U,X[1]=Q/U,this}stopWarping(){let A=this._timeScaleInterpolant;if(A!==null)this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(A);return this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(A,Q,J,K){if(!this.enabled){this._updateWeight(A);return}let C=this._startTime;if(C!==null){let Z=(A-C)*J;if(Z<0||J===0)Q=0;else this._startTime=null,Q=J*Z}Q*=this._updateTimeScale(A);let U=this._updateTime(Q),Y=this._updateWeight(A);if(Y>0){let Z=this._interpolants,X=this._propertyBindings;switch(this.blendMode){case 2501:for(let E=0,H=Z.length;E!==H;++E)Z[E].evaluate(U),X[E].accumulateAdditive(Y);break;case 2500:default:for(let E=0,H=Z.length;E!==H;++E)Z[E].evaluate(U),X[E].accumulate(K,Y)}}}_updateWeight(A){let Q=0;if(this.enabled){Q=this.weight;let J=this._weightInterpolant;if(J!==null){let K=J.evaluate(A)[0];if(Q*=K,A>J.parameterPositions[1]){if(this.stopFading(),K===0)this.enabled=!1}}}return this._effectiveWeight=Q,Q}_updateTimeScale(A){let Q=0;if(!this.paused){Q=this.timeScale;let J=this._timeScaleInterpolant;if(J!==null){let K=J.evaluate(A)[0];if(Q*=K,A>J.parameterPositions[1])if(this.stopWarping(),Q===0)this.paused=!0;else this.timeScale=Q}}return this._effectiveTimeScale=Q,Q}_updateTime(A){let Q=this._clip.duration,J=this.loop,K=this.time+A,C=this._loopCount,U=J===2202;if(A===0){if(C===-1)return K;return U&&(C&1)===1?Q-K:K}if(J===2200){if(C===-1)this._loopCount=0,this._setEndings(!0,!0,!1);A:{if(K>=Q)K=Q;else if(K<0)K=0;else{this.time=K;break A}if(this.clampWhenFinished)this.paused=!0;else this.enabled=!1;this.time=K,this._mixer.dispatchEvent({type:"finished",action:this,direction:A<0?-1:1})}}else{if(C===-1)if(A>=0)C=0,this._setEndings(!0,this.repetitions===0,U);else this._setEndings(this.repetitions===0,!0,U);if(K>=Q||K<0){let Y=Math.floor(K/Q);K-=Q*Y,C+=Math.abs(Y);let Z=this.repetitions-C;if(Z<=0){if(this.clampWhenFinished)this.paused=!0;else this.enabled=!1;K=A>0?Q:0,this.time=K,this._mixer.dispatchEvent({type:"finished",action:this,direction:A>0?1:-1})}else{if(Z===1){let X=A<0;this._setEndings(X,!X,U)}else this._setEndings(!1,!1,U);this._loopCount=C,this.time=K,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:Y})}}else this.time=K;if(U&&(C&1)===1)return Q-K}return K}_setEndings(A,Q,J){let K=this._interpolantSettings;if(J)K.endingStart=2401,K.endingEnd=2401;else{if(A)K.endingStart=this.zeroSlopeAtStart?2401:2400;else K.endingStart=2402;if(Q)K.endingEnd=this.zeroSlopeAtEnd?2401:2400;else K.endingEnd=2402}}_scheduleFading(A,Q,J){let K=this._mixer,C=K.time,U=this._weightInterpolant;if(U===null)U=K._lendControlInterpolant(),this._weightInterpolant=U;let{parameterPositions:Y,sampleValues:Z}=U;return Y[0]=C,Z[0]=Q,Y[1]=C+A,Z[1]=J,this}}var i31=new Float32Array(1);class F5 extends y9{constructor(A){super();this._root=A,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(A,Q){let J=A._localRoot||this._root,K=A._clip.tracks,C=K.length,U=A._propertyBindings,Y=A._interpolants,Z=J.uuid,X=this._bindingsByRootAndName,E=X[Z];if(E===void 0)E={},X[Z]=E;for(let H=0;H!==C;++H){let $=K[H],I=$.name,N=E[I];if(N!==void 0)++N.referenceCount,U[H]=N;else{if(N=U[H],N!==void 0){if(N._cacheIndex===null)++N.referenceCount,this._addInactiveBinding(N,Z,I);continue}let F=Q&&Q._propertyBindings[H].binding.parsedPath;N=new CG(RA.create(J,I,F),$.ValueTypeName,$.getValueSize()),++N.referenceCount,this._addInactiveBinding(N,Z,I),U[H]=N}Y[H].resultBuffer=N.buffer}}_activateAction(A){if(!this._isActiveAction(A)){if(A._cacheIndex===null){let J=(A._localRoot||this._root).uuid,K=A._clip.uuid,C=this._actionsByClip[K];this._bindAction(A,C&&C.knownActions[0]),this._addInactiveAction(A,K,J)}let Q=A._propertyBindings;for(let J=0,K=Q.length;J!==K;++J){let C=Q[J];if(C.useCount++===0)this._lendBinding(C),C.saveOriginalState()}this._lendAction(A)}}_deactivateAction(A){if(this._isActiveAction(A)){let Q=A._propertyBindings;for(let J=0,K=Q.length;J!==K;++J){let C=Q[J];if(--C.useCount===0)C.restoreOriginalState(),this._takeBackBinding(C)}this._takeBackAction(A)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let A=this;this.stats={actions:{get total(){return A._actions.length},get inUse(){return A._nActiveActions}},bindings:{get total(){return A._bindings.length},get inUse(){return A._nActiveBindings}},controlInterpolants:{get total(){return A._controlInterpolants.length},get inUse(){return A._nActiveControlInterpolants}}}}_isActiveAction(A){let Q=A._cacheIndex;return Q!==null&&Q=0;--J)A[J].stop();return this}update(A){A*=this.timeScale;let Q=this._actions,J=this._nActiveActions,K=this.time+=A,C=Math.sign(A),U=this._accuIndex^=1;for(let X=0;X!==J;++X)Q[X]._update(K,A,C,U);let Y=this._bindings,Z=this._nActiveBindings;for(let X=0;X!==Z;++X)Y[X].apply(U);return this}setTime(A){this.time=0;for(let Q=0;Q=this.min.x&&A.x<=this.max.x&&A.y>=this.min.y&&A.y<=this.max.y}containsBox(A){return this.min.x<=A.min.x&&A.max.x<=this.max.x&&this.min.y<=A.min.y&&A.max.y<=this.max.y}getParameter(A,Q){return Q.set((A.x-this.min.x)/(this.max.x-this.min.x),(A.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(A){return A.max.x>=this.min.x&&A.min.x<=this.max.x&&A.max.y>=this.min.y&&A.min.y<=this.max.y}clampPoint(A,Q){return Q.copy(A).clamp(this.min,this.max)}distanceToPoint(A){return this.clampPoint(A,jh).distanceTo(A)}intersect(A){if(this.min.max(A.min),this.max.min(A.max),this.isEmpty())this.makeEmpty();return this}union(A){return this.min.min(A.min),this.max.max(A.max),this}translate(A){return this.min.add(A),this.max.add(A),this}equals(A){return A.min.equals(this.min)&&A.max.equals(this.max)}}var vh=/*@__PURE__*/new I1,m$=/*@__PURE__*/new I1;class R5{constructor(A=new I1,Q=new I1){this.start=A,this.end=Q}set(A,Q){return this.start.copy(A),this.end.copy(Q),this}copy(A){return this.start.copy(A.start),this.end.copy(A.end),this}getCenter(A){return A.addVectors(this.start,this.end).multiplyScalar(0.5)}delta(A){return A.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(A,Q){return this.delta(Q).multiplyScalar(A).add(this.start)}closestPointToPointParameter(A,Q){vh.subVectors(A,this.start),m$.subVectors(this.end,this.start);let J=m$.dot(m$),C=m$.dot(vh)/J;if(Q)C=zA(C,0,1);return C}closestPointToPoint(A,Q,J){let K=this.closestPointToPointParameter(A,Q);return this.delta(J).multiplyScalar(K).add(this.start)}applyMatrix4(A){return this.start.applyMatrix4(A),this.end.applyMatrix4(A),this}equals(A){return A.start.equals(this.start)&&A.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}var xh=/*@__PURE__*/new I1;class eF extends AA{constructor(A,Q){super();this.light=A,this.matrixAutoUpdate=!1,this.color=Q,this.type="SpotLightHelper";let J=new V0,K=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let U=0,Y=1,Z=32;U1)for(let H=0;H0.99999)this.quaternion.set(0,0,0,1);else if(A.y<-0.99999)this.quaternion.set(1,0,0,0);else{fh.set(A.z,0,-A.x).normalize();let Q=Math.acos(A.y);this.quaternion.setFromAxisAngle(fh,Q)}}setLength(A,Q=A*0.2,J=Q*0.2){this.line.scale.set(1,Math.max(0.0001,A-Q),1),this.line.updateMatrix(),this.cone.scale.set(J,Q,J),this.cone.position.y=A,this.cone.updateMatrix()}setColor(A){this.line.material.color.set(A),this.cone.material.color.set(A)}copy(A){return super.copy(A,!1),this.line.copy(A.line),this.cone.copy(A.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class BR extends T2{constructor(A=1){let Q=[0,0,0,A,0,0,0,0,0,0,A,0,0,0,0,0,0,A],J=[1,0,0,1,0.6,0,0,1,0,0.6,1,0,0,0,1,0,0.6,1],K=new V0;K.setAttribute("position",new L0(Q,3)),K.setAttribute("color",new L0(J,3));let C=new pA({vertexColors:!0,toneMapped:!1});super(K,C);this.type="AxesHelper"}setColors(A,Q,J){let K=new y1,C=this.geometry.attributes.color.array;return K.set(A),K.toArray(C,0),K.toArray(C,3),K.set(Q),K.toArray(C,6),K.toArray(C,9),K.set(J),K.toArray(C,12),K.toArray(C,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class gZ{constructor(){this.type="ShapePath",this.color=new y1,this.subPaths=[],this.currentPath=null}moveTo(A,Q){return this.currentPath=new U4,this.subPaths.push(this.currentPath),this.currentPath.moveTo(A,Q),this}lineTo(A,Q){return this.currentPath.lineTo(A,Q),this}quadraticCurveTo(A,Q,J,K){return this.currentPath.quadraticCurveTo(A,Q,J,K),this}bezierCurveTo(A,Q,J,K,C,U){return this.currentPath.bezierCurveTo(A,Q,J,K,C,U),this}splineThru(A){return this.currentPath.splineThru(A),this}toShapes(A){function Q(D){let L=[];for(let R=0,M=D.length;RNumber.EPSILON){if(u<0)y=L[h],f=-f,g=L[T],u=-u;if(D.yg.y)continue;if(D.y===y.y){if(D.x===y.x)return!0}else{let d=u*(D.x-y.x)-f*(D.y-y.y);if(d===0)return!0;if(d<0)continue;M=!M}}else{if(D.y!==y.y)continue;if(g.x<=D.x&&D.x<=y.x||y.x<=D.x&&D.x<=g.x)return!0}}return M}let K=h6.isClockWise,C=this.subPaths;if(C.length===0)return[];let U,Y,Z,X=[];if(C.length===1)return Y=C[0],Z=new n5,Z.curves=Y.curves,X.push(Z),X;let E=!K(C[0].getPoints());E=A?!E:E;let H=[],$=[],I=[],N=0,F;$[N]=void 0,I[N]=[];for(let D=0,L=C.length;D1){let D=!1,L=0;for(let R=0,M=$.length;R0&&D===!1)I=H}let V;for(let D=0,L=$.length;DQ)A.repeat.x=1,A.repeat.y=J/Q,A.offset.x=0,A.offset.y=(1-A.repeat.y)/2;else A.repeat.x=Q/J,A.repeat.y=1,A.offset.x=(1-A.repeat.x)/2,A.offset.y=0;return A}function e31(A,Q){let J=A.image&&A.image.width?A.image.width/A.image.height:1;if(J>Q)A.repeat.x=Q/J,A.repeat.y=1,A.offset.x=(1-A.repeat.x)/2,A.offset.y=0;else A.repeat.x=1,A.repeat.y=J/Q,A.offset.x=0,A.offset.y=(1-A.repeat.y)/2;return A}function A71(A){return A.repeat.x=1,A.repeat.y=1,A.offset.x=0,A.offset.y=0,A}function EG(A,Q,J,K){let C=Q71(K);switch(J){case 1021:return A*Q;case 1024:return A*Q;case 1025:return A*Q*2;case 1028:return A*Q/C.components*C.byteLength;case 1029:return A*Q/C.components*C.byteLength;case 1030:return A*Q*2/C.components*C.byteLength;case 1031:return A*Q*2/C.components*C.byteLength;case 1022:return A*Q*3/C.components*C.byteLength;case 1023:return A*Q*4/C.components*C.byteLength;case 1033:return A*Q*4/C.components*C.byteLength;case 33776:case 33777:return Math.floor((A+3)/4)*Math.floor((Q+3)/4)*8;case 33778:case 33779:return Math.floor((A+3)/4)*Math.floor((Q+3)/4)*16;case 35841:case 35843:return Math.max(A,16)*Math.max(Q,8)/4;case 35840:case 35842:return Math.max(A,8)*Math.max(Q,8)/2;case 36196:case 37492:return Math.floor((A+3)/4)*Math.floor((Q+3)/4)*8;case 37496:return Math.floor((A+3)/4)*Math.floor((Q+3)/4)*16;case 37808:return Math.floor((A+3)/4)*Math.floor((Q+3)/4)*16;case 37809:return Math.floor((A+4)/5)*Math.floor((Q+3)/4)*16;case 37810:return Math.floor((A+4)/5)*Math.floor((Q+4)/5)*16;case 37811:return Math.floor((A+5)/6)*Math.floor((Q+4)/5)*16;case 37812:return Math.floor((A+5)/6)*Math.floor((Q+5)/6)*16;case 37813:return Math.floor((A+7)/8)*Math.floor((Q+4)/5)*16;case 37814:return Math.floor((A+7)/8)*Math.floor((Q+5)/6)*16;case 37815:return Math.floor((A+7)/8)*Math.floor((Q+7)/8)*16;case 37816:return Math.floor((A+9)/10)*Math.floor((Q+4)/5)*16;case 37817:return Math.floor((A+9)/10)*Math.floor((Q+5)/6)*16;case 37818:return Math.floor((A+9)/10)*Math.floor((Q+7)/8)*16;case 37819:return Math.floor((A+9)/10)*Math.floor((Q+9)/10)*16;case 37820:return Math.floor((A+11)/12)*Math.floor((Q+9)/10)*16;case 37821:return Math.floor((A+11)/12)*Math.floor((Q+11)/12)*16;case 36492:case 36494:case 36495:return Math.ceil(A/4)*Math.ceil(Q/4)*16;case 36283:case 36284:return Math.ceil(A/4)*Math.ceil(Q/4)*8;case 36285:case 36286:return Math.ceil(A/4)*Math.ceil(Q/4)*16}throw new Error(`Unable to determine texture byte length for ${J} format.`)}function Q71(A){switch(A){case 1009:case 1010:return{byteLength:1,components:1};case 1012:case 1011:case 1016:return{byteLength:2,components:1};case 1017:case 1018:return{byteLength:2,components:4};case 1014:case 1013:case 1015:return{byteLength:4,components:1};case 35902:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${A}.`)}var ig={contain:t31,cover:e31,fill:A71,getByteLength:EG};if(typeof __THREE_DEVTOOLS__!=="undefined")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"173"}}));if(typeof window!=="undefined")if(window.__THREE__)console.warn("WARNING: Multiple instances of Three.js being imported.");else window.__THREE__="173";function Lb(){let A=null,Q=!1,J=null,K=null;function C(U,Y){J(U,Y),K=A.requestAnimationFrame(C)}return{start:function(){if(Q===!0)return;if(J===null)return;K=A.requestAnimationFrame(C),Q=!0},stop:function(){A.cancelAnimationFrame(K),Q=!1},setAnimationLoop:function(U){J=U},setContext:function(U){A=U}}}function J71(A){let Q=/*@__PURE__*/new WeakMap;function J(Z,X){let{array:E,usage:H}=Z,$=E.byteLength,I=A.createBuffer();A.bindBuffer(X,I),A.bufferData(X,E,H),Z.onUploadCallback();let N;if(E instanceof Float32Array)N=A.FLOAT;else if(E instanceof Uint16Array)if(Z.isFloat16BufferAttribute)N=A.HALF_FLOAT;else N=A.UNSIGNED_SHORT;else if(E instanceof Int16Array)N=A.SHORT;else if(E instanceof Uint32Array)N=A.UNSIGNED_INT;else if(E instanceof Int32Array)N=A.INT;else if(E instanceof Int8Array)N=A.BYTE;else if(E instanceof Uint8Array)N=A.UNSIGNED_BYTE;else if(E instanceof Uint8ClampedArray)N=A.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+E);return{buffer:I,type:N,bytesPerElement:E.BYTES_PER_ELEMENT,version:Z.version,size:$}}function K(Z,X,E){let{array:H,updateRanges:$}=X;if(A.bindBuffer(E,Z),$.length===0)A.bufferSubData(E,0,H);else{$.sort((N,F)=>N.start-F.start);let I=0;for(let N=1;N<$.length;N++){let F=$[I],V=$[N];if(V.start<=F.start+F.count+1)F.count=Math.max(F.count,V.start+V.count-F.start);else++I,$[I]=V}$.length=I+1;for(let N=0,F=$.length;N 0 - vec4 plane; - #ifdef ALPHA_TO_COVERAGE - float distanceToPlane, distanceGradient; - float clipOpacity = 1.0; - #pragma unroll_loop_start - for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; - distanceGradient = fwidth( distanceToPlane ) / 2.0; - clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); - if ( clipOpacity == 0.0 ) discard; - } - #pragma unroll_loop_end - #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES - float unionClipOpacity = 1.0; - #pragma unroll_loop_start - for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; - distanceGradient = fwidth( distanceToPlane ) / 2.0; - unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); - } - #pragma unroll_loop_end - clipOpacity *= 1.0 - unionClipOpacity; - #endif - diffuseColor.a *= clipOpacity; - if ( diffuseColor.a == 0.0 ) discard; - #else - #pragma unroll_loop_start - for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; - } - #pragma unroll_loop_end - #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES - bool clipped = true; - #pragma unroll_loop_start - for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; - } - #pragma unroll_loop_end - if ( clipped ) discard; - #endif - #endif -#endif`,L71=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; - uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; -#endif`,F71=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; -#endif`,R71=`#if NUM_CLIPPING_PLANES > 0 - vClipPosition = - mvPosition.xyz; -#endif`,z71=`#if defined( USE_COLOR_ALPHA ) - diffuseColor *= vColor; -#elif defined( USE_COLOR ) - diffuseColor.rgb *= vColor; -#endif`,D71=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) - varying vec3 vColor; -#endif`,V71=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - varying vec3 vColor; -#endif`,M71=`#if defined( USE_COLOR_ALPHA ) - vColor = vec4( 1.0 ); -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - vColor = vec3( 1.0 ); -#endif -#ifdef USE_COLOR - vColor *= color; -#endif -#ifdef USE_INSTANCING_COLOR - vColor.xyz *= instanceColor.xyz; -#endif -#ifdef USE_BATCHING_COLOR - vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); - vColor.xyz *= batchingColor.xyz; -#endif`,w71=`#define PI 3.141592653589793 -#define PI2 6.283185307179586 -#define PI_HALF 1.5707963267948966 -#define RECIPROCAL_PI 0.3183098861837907 -#define RECIPROCAL_PI2 0.15915494309189535 -#define EPSILON 1e-6 -#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -#define whiteComplement( a ) ( 1.0 - saturate( a ) ) -float pow2( const in float x ) { return x*x; } -vec3 pow2( const in vec3 x ) { return x*x; } -float pow3( const in float x ) { return x*x*x; } -float pow4( const in float x ) { float x2 = x*x; return x2*x2; } -float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } -float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } -highp float rand( const in vec2 uv ) { - const highp float a = 12.9898, b = 78.233, c = 43758.5453; - highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); - return fract( sin( sn ) * c ); -} -#ifdef HIGH_PRECISION - float precisionSafeLength( vec3 v ) { return length( v ); } -#else - float precisionSafeLength( vec3 v ) { - float maxComponent = max3( abs( v ) ); - return length( v / maxComponent ) * maxComponent; - } -#endif -struct IncidentLight { - vec3 color; - vec3 direction; - bool visible; -}; -struct ReflectedLight { - vec3 directDiffuse; - vec3 directSpecular; - vec3 indirectDiffuse; - vec3 indirectSpecular; -}; -#ifdef USE_ALPHAHASH - varying vec3 vPosition; -#endif -vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); -} -vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); -} -mat3 transposeMat3( const in mat3 m ) { - mat3 tmp; - tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); - tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); - tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); - return tmp; -} -bool isPerspectiveMatrix( mat4 m ) { - return m[ 2 ][ 3 ] == - 1.0; -} -vec2 equirectUv( in vec3 dir ) { - float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; - float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; - return vec2( u, v ); -} -vec3 BRDF_Lambert( const in vec3 diffuseColor ) { - return RECIPROCAL_PI * diffuseColor; -} -vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} -float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} // validated`,P71=`#ifdef ENVMAP_TYPE_CUBE_UV - #define cubeUV_minMipLevel 4.0 - #define cubeUV_minTileSize 16.0 - float getFace( vec3 direction ) { - vec3 absDirection = abs( direction ); - float face = - 1.0; - if ( absDirection.x > absDirection.z ) { - if ( absDirection.x > absDirection.y ) - face = direction.x > 0.0 ? 0.0 : 3.0; - else - face = direction.y > 0.0 ? 1.0 : 4.0; - } else { - if ( absDirection.z > absDirection.y ) - face = direction.z > 0.0 ? 2.0 : 5.0; - else - face = direction.y > 0.0 ? 1.0 : 4.0; - } - return face; - } - vec2 getUV( vec3 direction, float face ) { - vec2 uv; - if ( face == 0.0 ) { - uv = vec2( direction.z, direction.y ) / abs( direction.x ); - } else if ( face == 1.0 ) { - uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); - } else if ( face == 2.0 ) { - uv = vec2( - direction.x, direction.y ) / abs( direction.z ); - } else if ( face == 3.0 ) { - uv = vec2( - direction.z, direction.y ) / abs( direction.x ); - } else if ( face == 4.0 ) { - uv = vec2( - direction.x, direction.z ) / abs( direction.y ); - } else { - uv = vec2( direction.x, direction.y ) / abs( direction.z ); - } - return 0.5 * ( uv + 1.0 ); - } - vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { - float face = getFace( direction ); - float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); - mipInt = max( mipInt, cubeUV_minMipLevel ); - float faceSize = exp2( mipInt ); - highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; - if ( face > 2.0 ) { - uv.y += faceSize; - face -= 3.0; - } - uv.x += face * faceSize; - uv.x += filterInt * 3.0 * cubeUV_minTileSize; - uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); - uv.x *= CUBEUV_TEXEL_WIDTH; - uv.y *= CUBEUV_TEXEL_HEIGHT; - #ifdef texture2DGradEXT - return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; - #else - return texture2D( envMap, uv ).rgb; - #endif - } - #define cubeUV_r0 1.0 - #define cubeUV_m0 - 2.0 - #define cubeUV_r1 0.8 - #define cubeUV_m1 - 1.0 - #define cubeUV_r4 0.4 - #define cubeUV_m4 2.0 - #define cubeUV_r5 0.305 - #define cubeUV_m5 3.0 - #define cubeUV_r6 0.21 - #define cubeUV_m6 4.0 - float roughnessToMip( float roughness ) { - float mip = 0.0; - if ( roughness >= cubeUV_r1 ) { - mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; - } else if ( roughness >= cubeUV_r4 ) { - mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; - } else if ( roughness >= cubeUV_r5 ) { - mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; - } else if ( roughness >= cubeUV_r6 ) { - mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; - } else { - mip = - 2.0 * log2( 1.16 * roughness ); } - return mip; - } - vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { - float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); - float mipF = fract( mip ); - float mipInt = floor( mip ); - vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); - if ( mipF == 0.0 ) { - return vec4( color0, 1.0 ); - } else { - vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); - return vec4( mix( color0, color1, mipF ), 1.0 ); - } - } -#endif`,_71=`vec3 transformedNormal = objectNormal; -#ifdef USE_TANGENT - vec3 transformedTangent = objectTangent; -#endif -#ifdef USE_BATCHING - mat3 bm = mat3( batchingMatrix ); - transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); - transformedNormal = bm * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = bm * transformedTangent; - #endif -#endif -#ifdef USE_INSTANCING - mat3 im = mat3( instanceMatrix ); - transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); - transformedNormal = im * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = im * transformedTangent; - #endif -#endif -transformedNormal = normalMatrix * transformedNormal; -#ifdef FLIP_SIDED - transformedNormal = - transformedNormal; -#endif -#ifdef USE_TANGENT - transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; - #ifdef FLIP_SIDED - transformedTangent = - transformedTangent; - #endif -#endif`,T71=`#ifdef USE_DISPLACEMENTMAP - uniform sampler2D displacementMap; - uniform float displacementScale; - uniform float displacementBias; -#endif`,k71=`#ifdef USE_DISPLACEMENTMAP - transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); -#endif`,S71=`#ifdef USE_EMISSIVEMAP - vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); - #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE - emissiveColor = sRGBTransferEOTF( emissiveColor ); - #endif - totalEmissiveRadiance *= emissiveColor.rgb; -#endif`,j71=`#ifdef USE_EMISSIVEMAP - uniform sampler2D emissiveMap; -#endif`,v71="gl_FragColor = linearToOutputTexel( gl_FragColor );",x71=`vec4 LinearTransferOETF( in vec4 value ) { - return value; -} -vec4 sRGBTransferEOTF( in vec4 value ) { - return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); -} -vec4 sRGBTransferOETF( in vec4 value ) { - return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); -}`,y71=`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vec3 cameraToFrag; - if ( isOrthographic ) { - cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToFrag = normalize( vWorldPosition - cameraPosition ); - } - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vec3 reflectVec = reflect( cameraToFrag, worldNormal ); - #else - vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); - #endif - #else - vec3 reflectVec = vReflect; - #endif - #ifdef ENVMAP_TYPE_CUBE - vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); - #else - vec4 envColor = vec4( 0.0 ); - #endif - #ifdef ENVMAP_BLENDING_MULTIPLY - outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_MIX ) - outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_ADD ) - outgoingLight += envColor.xyz * specularStrength * reflectivity; - #endif -#endif`,h71=`#ifdef USE_ENVMAP - uniform float envMapIntensity; - uniform float flipEnvMap; - uniform mat3 envMapRotation; - #ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; - #else - uniform sampler2D envMap; - #endif - -#endif`,g71=`#ifdef USE_ENVMAP - uniform float reflectivity; - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) - #define ENV_WORLDPOS - #endif - #ifdef ENV_WORLDPOS - varying vec3 vWorldPosition; - uniform float refractionRatio; - #else - varying vec3 vReflect; - #endif -#endif`,b71=`#ifdef USE_ENVMAP - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) - #define ENV_WORLDPOS - #endif - #ifdef ENV_WORLDPOS - - varying vec3 vWorldPosition; - #else - varying vec3 vReflect; - uniform float refractionRatio; - #endif -#endif`,f71=`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vWorldPosition = worldPosition.xyz; - #else - vec3 cameraToVertex; - if ( isOrthographic ) { - cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); - } - vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vReflect = reflect( cameraToVertex, worldNormal ); - #else - vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); - #endif - #endif -#endif`,p71=`#ifdef USE_FOG - vFogDepth = - mvPosition.z; -#endif`,u71=`#ifdef USE_FOG - varying float vFogDepth; -#endif`,m71=`#ifdef USE_FOG - #ifdef FOG_EXP2 - float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); - #else - float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); - #endif - gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); -#endif`,c71=`#ifdef USE_FOG - uniform vec3 fogColor; - varying float vFogDepth; - #ifdef FOG_EXP2 - uniform float fogDensity; - #else - uniform float fogNear; - uniform float fogFar; - #endif -#endif`,d71=`#ifdef USE_GRADIENTMAP - uniform sampler2D gradientMap; -#endif -vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { - float dotNL = dot( normal, lightDirection ); - vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); - #ifdef USE_GRADIENTMAP - return vec3( texture2D( gradientMap, coord ).r ); - #else - vec2 fw = fwidth( coord ) * 0.5; - return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); - #endif -}`,l71=`#ifdef USE_LIGHTMAP - uniform sampler2D lightMap; - uniform float lightMapIntensity; -#endif`,n71=`LambertMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularStrength = specularStrength;`,s71=`varying vec3 vViewPosition; -struct LambertMaterial { - vec3 diffuseColor; - float specularStrength; -}; -void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_Lambert -#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,o71=`uniform bool receiveShadow; -uniform vec3 ambientLightColor; -#if defined( USE_LIGHT_PROBES ) - uniform vec3 lightProbe[ 9 ]; -#endif -vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { - float x = normal.x, y = normal.y, z = normal.z; - vec3 result = shCoefficients[ 0 ] * 0.886227; - result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; - result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; - result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; - result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; - result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; - result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); - result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; - result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); - return result; -} -vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); - return irradiance; -} -vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { - vec3 irradiance = ambientLightColor; - return irradiance; -} -float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { - float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); - if ( cutoffDistance > 0.0 ) { - distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); - } - return distanceFalloff; -} -float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { - return smoothstep( coneCosine, penumbraCosine, angleCosine ); -} -#if NUM_DIR_LIGHTS > 0 - struct DirectionalLight { - vec3 direction; - vec3 color; - }; - uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; - void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { - light.color = directionalLight.color; - light.direction = directionalLight.direction; - light.visible = true; - } -#endif -#if NUM_POINT_LIGHTS > 0 - struct PointLight { - vec3 position; - vec3 color; - float distance; - float decay; - }; - uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; - void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = pointLight.position - geometryPosition; - light.direction = normalize( lVector ); - float lightDistance = length( lVector ); - light.color = pointLight.color; - light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } -#endif -#if NUM_SPOT_LIGHTS > 0 - struct SpotLight { - vec3 position; - vec3 direction; - vec3 color; - float distance; - float decay; - float coneCos; - float penumbraCos; - }; - uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; - void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = spotLight.position - geometryPosition; - light.direction = normalize( lVector ); - float angleCos = dot( light.direction, spotLight.direction ); - float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); - if ( spotAttenuation > 0.0 ) { - float lightDistance = length( lVector ); - light.color = spotLight.color * spotAttenuation; - light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } else { - light.color = vec3( 0.0 ); - light.visible = false; - } - } -#endif -#if NUM_RECT_AREA_LIGHTS > 0 - struct RectAreaLight { - vec3 color; - vec3 position; - vec3 halfWidth; - vec3 halfHeight; - }; - uniform sampler2D ltc_1; uniform sampler2D ltc_2; - uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; -#endif -#if NUM_HEMI_LIGHTS > 0 - struct HemisphereLight { - vec3 direction; - vec3 skyColor; - vec3 groundColor; - }; - uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; - vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { - float dotNL = dot( normal, hemiLight.direction ); - float hemiDiffuseWeight = 0.5 * dotNL + 0.5; - vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); - return irradiance; - } -#endif`,i71=`#ifdef USE_ENVMAP - vec3 getIBLIrradiance( const in vec3 normal ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); - return PI * envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 reflectVec = reflect( - viewDir, normal ); - reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); - reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); - return envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - #ifdef USE_ANISOTROPY - vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 bentNormal = cross( bitangent, viewDir ); - bentNormal = normalize( cross( bentNormal, bitangent ) ); - bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); - return getIBLRadiance( viewDir, bentNormal, roughness ); - #else - return vec3( 0.0 ); - #endif - } - #endif -#endif`,a71=`ToonMaterial material; -material.diffuseColor = diffuseColor.rgb;`,r71=`varying vec3 vViewPosition; -struct ToonMaterial { - vec3 diffuseColor; -}; -void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { - vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_Toon -#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,t71=`BlinnPhongMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularColor = specular; -material.specularShininess = shininess; -material.specularStrength = specularStrength;`,e71=`varying vec3 vViewPosition; -struct BlinnPhongMaterial { - vec3 diffuseColor; - vec3 specularColor; - float specularShininess; - float specularStrength; -}; -void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); - reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; -} -void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_BlinnPhong -#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,A41=`PhysicalMaterial material; -material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); -vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); -float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); -material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; -material.roughness = min( material.roughness, 1.0 ); -#ifdef IOR - material.ior = ior; - #ifdef USE_SPECULAR - float specularIntensityFactor = specularIntensity; - vec3 specularColorFactor = specularColor; - #ifdef USE_SPECULAR_COLORMAP - specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; - #endif - material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); - #else - float specularIntensityFactor = 1.0; - vec3 specularColorFactor = vec3( 1.0 ); - material.specularF90 = 1.0; - #endif - material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); -#else - material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); - material.specularF90 = 1.0; -#endif -#ifdef USE_CLEARCOAT - material.clearcoat = clearcoat; - material.clearcoatRoughness = clearcoatRoughness; - material.clearcoatF0 = vec3( 0.04 ); - material.clearcoatF90 = 1.0; - #ifdef USE_CLEARCOATMAP - material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; - #endif - #ifdef USE_CLEARCOAT_ROUGHNESSMAP - material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; - #endif - material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); - material.clearcoatRoughness += geometryRoughness; - material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); -#endif -#ifdef USE_DISPERSION - material.dispersion = dispersion; -#endif -#ifdef USE_IRIDESCENCE - material.iridescence = iridescence; - material.iridescenceIOR = iridescenceIOR; - #ifdef USE_IRIDESCENCEMAP - material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; - #endif - #ifdef USE_IRIDESCENCE_THICKNESSMAP - material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; - #else - material.iridescenceThickness = iridescenceThicknessMaximum; - #endif -#endif -#ifdef USE_SHEEN - material.sheenColor = sheenColor; - #ifdef USE_SHEEN_COLORMAP - material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; - #endif - material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); - #ifdef USE_SHEEN_ROUGHNESSMAP - material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; - #endif -#endif -#ifdef USE_ANISOTROPY - #ifdef USE_ANISOTROPYMAP - mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); - vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; - vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; - #else - vec2 anisotropyV = anisotropyVector; - #endif - material.anisotropy = length( anisotropyV ); - if( material.anisotropy == 0.0 ) { - anisotropyV = vec2( 1.0, 0.0 ); - } else { - anisotropyV /= material.anisotropy; - material.anisotropy = saturate( material.anisotropy ); - } - material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); - material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; - material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; -#endif`,Q41=`struct PhysicalMaterial { - vec3 diffuseColor; - float roughness; - vec3 specularColor; - float specularF90; - float dispersion; - #ifdef USE_CLEARCOAT - float clearcoat; - float clearcoatRoughness; - vec3 clearcoatF0; - float clearcoatF90; - #endif - #ifdef USE_IRIDESCENCE - float iridescence; - float iridescenceIOR; - float iridescenceThickness; - vec3 iridescenceFresnel; - vec3 iridescenceF0; - #endif - #ifdef USE_SHEEN - vec3 sheenColor; - float sheenRoughness; - #endif - #ifdef IOR - float ior; - #endif - #ifdef USE_TRANSMISSION - float transmission; - float transmissionAlpha; - float thickness; - float attenuationDistance; - vec3 attenuationColor; - #endif - #ifdef USE_ANISOTROPY - float anisotropy; - float alphaT; - vec3 anisotropyT; - vec3 anisotropyB; - #endif -}; -vec3 clearcoatSpecularDirect = vec3( 0.0 ); -vec3 clearcoatSpecularIndirect = vec3( 0.0 ); -vec3 sheenSpecularDirect = vec3( 0.0 ); -vec3 sheenSpecularIndirect = vec3(0.0 ); -vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { - float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); - float x2 = x * x; - float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); - return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); -} -float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { - float a2 = pow2( alpha ); - float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); - float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); - return 0.5 / max( gv + gl, EPSILON ); -} -float D_GGX( const in float alpha, const in float dotNH ) { - float a2 = pow2( alpha ); - float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; - return RECIPROCAL_PI * a2 / pow2( denom ); -} -#ifdef USE_ANISOTROPY - float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { - float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); - float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); - float v = 0.5 / ( gv + gl ); - return saturate(v); - } - float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { - float a2 = alphaT * alphaB; - highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); - highp float v2 = dot( v, v ); - float w2 = a2 / v2; - return RECIPROCAL_PI * a2 * pow2 ( w2 ); - } -#endif -#ifdef USE_CLEARCOAT - vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { - vec3 f0 = material.clearcoatF0; - float f90 = material.clearcoatF90; - float roughness = material.clearcoatRoughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - return F * ( V * D ); - } -#endif -vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { - vec3 f0 = material.specularColor; - float f90 = material.specularF90; - float roughness = material.roughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - #ifdef USE_IRIDESCENCE - F = mix( F, material.iridescenceFresnel, material.iridescence ); - #endif - #ifdef USE_ANISOTROPY - float dotTL = dot( material.anisotropyT, lightDir ); - float dotTV = dot( material.anisotropyT, viewDir ); - float dotTH = dot( material.anisotropyT, halfDir ); - float dotBL = dot( material.anisotropyB, lightDir ); - float dotBV = dot( material.anisotropyB, viewDir ); - float dotBH = dot( material.anisotropyB, halfDir ); - float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); - float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); - #else - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - #endif - return F * ( V * D ); -} -vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { - const float LUT_SIZE = 64.0; - const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; - const float LUT_BIAS = 0.5 / LUT_SIZE; - float dotNV = saturate( dot( N, V ) ); - vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); - uv = uv * LUT_SCALE + LUT_BIAS; - return uv; -} -float LTC_ClippedSphereFormFactor( const in vec3 f ) { - float l = length( f ); - return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); -} -vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { - float x = dot( v1, v2 ); - float y = abs( x ); - float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; - float b = 3.4175940 + ( 4.1616724 + y ) * y; - float v = a / b; - float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; - return cross( v1, v2 ) * theta_sintheta; -} -vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { - vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; - vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; - vec3 lightNormal = cross( v1, v2 ); - if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); - vec3 T1, T2; - T1 = normalize( V - N * dot( V, N ) ); - T2 = - cross( N, T1 ); - mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); - vec3 coords[ 4 ]; - coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); - coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); - coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); - coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); - coords[ 0 ] = normalize( coords[ 0 ] ); - coords[ 1 ] = normalize( coords[ 1 ] ); - coords[ 2 ] = normalize( coords[ 2 ] ); - coords[ 3 ] = normalize( coords[ 3 ] ); - vec3 vectorFormFactor = vec3( 0.0 ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); - float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); - return vec3( result ); -} -#if defined( USE_SHEEN ) -float D_Charlie( float roughness, float dotNH ) { - float alpha = pow2( roughness ); - float invAlpha = 1.0 / alpha; - float cos2h = dotNH * dotNH; - float sin2h = max( 1.0 - cos2h, 0.0078125 ); - return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); -} -float V_Neubelt( float dotNV, float dotNL ) { - return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); -} -vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float D = D_Charlie( sheenRoughness, dotNH ); - float V = V_Neubelt( dotNV, dotNL ); - return sheenColor * ( D * V ); -} -#endif -float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - float r2 = roughness * roughness; - float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; - float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; - float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); - return saturate( DG * RECIPROCAL_PI ); -} -vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); - const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); - vec4 r = roughness * c0 + c1; - float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; - vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; - return fab; -} -vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { - vec2 fab = DFGApprox( normal, viewDir, roughness ); - return specularColor * fab.x + specularF90 * fab.y; -} -#ifdef USE_IRIDESCENCE -void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#else -void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#endif - vec2 fab = DFGApprox( normal, viewDir, roughness ); - #ifdef USE_IRIDESCENCE - vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); - #else - vec3 Fr = specularColor; - #endif - vec3 FssEss = Fr * fab.x + specularF90 * fab.y; - float Ess = fab.x + fab.y; - float Ems = 1.0 - Ess; - vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); - singleScatter += FssEss; - multiScatter += Fms * Ems; -} -#if NUM_RECT_AREA_LIGHTS > 0 - void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - vec3 normal = geometryNormal; - vec3 viewDir = geometryViewDir; - vec3 position = geometryPosition; - vec3 lightPos = rectAreaLight.position; - vec3 halfWidth = rectAreaLight.halfWidth; - vec3 halfHeight = rectAreaLight.halfHeight; - vec3 lightColor = rectAreaLight.color; - float roughness = material.roughness; - vec3 rectCoords[ 4 ]; - rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; - rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; - rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; - vec2 uv = LTC_Uv( normal, viewDir, roughness ); - vec4 t1 = texture2D( ltc_1, uv ); - vec4 t2 = texture2D( ltc_2, uv ); - mat3 mInv = mat3( - vec3( t1.x, 0, t1.y ), - vec3( 0, 1, 0 ), - vec3( t1.z, 0, t1.w ) - ); - vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); - reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); - reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); - } -#endif -void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - #ifdef USE_CLEARCOAT - float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); - vec3 ccIrradiance = dotNLcc * directLight.color; - clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); - #endif - #ifdef USE_SHEEN - sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); - #endif - reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { - #ifdef USE_CLEARCOAT - clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); - #endif - #ifdef USE_SHEEN - sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); - #endif - vec3 singleScattering = vec3( 0.0 ); - vec3 multiScattering = vec3( 0.0 ); - vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; - #ifdef USE_IRIDESCENCE - computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); - #else - computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); - #endif - vec3 totalScattering = singleScattering + multiScattering; - vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); - reflectedLight.indirectSpecular += radiance * singleScattering; - reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; - reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; -} -#define RE_Direct RE_Direct_Physical -#define RE_Direct_RectArea RE_Direct_RectArea_Physical -#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical -#define RE_IndirectSpecular RE_IndirectSpecular_Physical -float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { - return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); -}`,J41=` -vec3 geometryPosition = - vViewPosition; -vec3 geometryNormal = normal; -vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); -vec3 geometryClearcoatNormal = vec3( 0.0 ); -#ifdef USE_CLEARCOAT - geometryClearcoatNormal = clearcoatNormal; -#endif -#ifdef USE_IRIDESCENCE - float dotNVi = saturate( dot( normal, geometryViewDir ) ); - if ( material.iridescenceThickness == 0.0 ) { - material.iridescence = 0.0; - } else { - material.iridescence = saturate( material.iridescence ); - } - if ( material.iridescence > 0.0 ) { - material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); - material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); - } -#endif -IncidentLight directLight; -#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) - PointLight pointLight; - #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - pointLight = pointLights[ i ]; - getPointLightInfo( pointLight, geometryPosition, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) - pointLightShadow = pointLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) - SpotLight spotLight; - vec4 spotColor; - vec3 spotLightCoord; - bool inSpotLightMap; - #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - spotLight = spotLights[ i ]; - getSpotLightInfo( spotLight, geometryPosition, directLight ); - #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX - #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS - #else - #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #endif - #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) - spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; - inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); - spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); - directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; - #endif - #undef SPOT_LIGHT_MAP_INDEX - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - spotLightShadow = spotLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) - DirectionalLight directionalLight; - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) - RectAreaLight rectAreaLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { - rectAreaLight = rectAreaLights[ i ]; - RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if defined( RE_IndirectDiffuse ) - vec3 iblIrradiance = vec3( 0.0 ); - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); - #if defined( USE_LIGHT_PROBES ) - irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); - #endif - #if ( NUM_HEMI_LIGHTS > 0 ) - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); - } - #pragma unroll_loop_end - #endif -#endif -#if defined( RE_IndirectSpecular ) - vec3 radiance = vec3( 0.0 ); - vec3 clearcoatRadiance = vec3( 0.0 ); -#endif`,K41=`#if defined( RE_IndirectDiffuse ) - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; - irradiance += lightMapIrradiance; - #endif - #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) - iblIrradiance += getIBLIrradiance( geometryNormal ); - #endif -#endif -#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) - #ifdef USE_ANISOTROPY - radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); - #else - radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); - #endif - #ifdef USE_CLEARCOAT - clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); - #endif -#endif`,C41=`#if defined( RE_IndirectDiffuse ) - RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif -#if defined( RE_IndirectSpecular ) - RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif`,Y41=`#if defined( USE_LOGDEPTHBUF ) - gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; -#endif`,U41=`#if defined( USE_LOGDEPTHBUF ) - uniform float logDepthBufFC; - varying float vFragDepth; - varying float vIsPerspective; -#endif`,Z41=`#ifdef USE_LOGDEPTHBUF - varying float vFragDepth; - varying float vIsPerspective; -#endif`,B41=`#ifdef USE_LOGDEPTHBUF - vFragDepth = 1.0 + gl_Position.w; - vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); -#endif`,X41=`#ifdef USE_MAP - vec4 sampledDiffuseColor = texture2D( map, vMapUv ); - #ifdef DECODE_VIDEO_TEXTURE - sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); - #endif - diffuseColor *= sampledDiffuseColor; -#endif`,E41=`#ifdef USE_MAP - uniform sampler2D map; -#endif`,$41=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) - #if defined( USE_POINTS_UV ) - vec2 uv = vUv; - #else - vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; - #endif -#endif -#ifdef USE_MAP - diffuseColor *= texture2D( map, uv ); -#endif -#ifdef USE_ALPHAMAP - diffuseColor.a *= texture2D( alphaMap, uv ).g; -#endif`,H41=`#if defined( USE_POINTS_UV ) - varying vec2 vUv; -#else - #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) - uniform mat3 uvTransform; - #endif -#endif -#ifdef USE_MAP - uniform sampler2D map; -#endif -#ifdef USE_ALPHAMAP - uniform sampler2D alphaMap; -#endif`,G41=`float metalnessFactor = metalness; -#ifdef USE_METALNESSMAP - vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); - metalnessFactor *= texelMetalness.b; -#endif`,W41=`#ifdef USE_METALNESSMAP - uniform sampler2D metalnessMap; -#endif`,I41=`#ifdef USE_INSTANCING_MORPH - float morphTargetInfluences[ MORPHTARGETS_COUNT ]; - float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; - } -#endif`,q41=`#if defined( USE_MORPHCOLORS ) - vColor *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - #if defined( USE_COLOR_ALPHA ) - if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; - #elif defined( USE_COLOR ) - if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; - #endif - } -#endif`,O41=`#ifdef USE_MORPHNORMALS - objectNormal *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; - } -#endif`,N41=`#ifdef USE_MORPHTARGETS - #ifndef USE_INSTANCING_MORPH - uniform float morphTargetBaseInfluence; - uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; - #endif - uniform sampler2DArray morphTargetsTexture; - uniform ivec2 morphTargetsTextureSize; - vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { - int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; - int y = texelIndex / morphTargetsTextureSize.x; - int x = texelIndex - y * morphTargetsTextureSize.x; - ivec3 morphUV = ivec3( x, y, morphTargetIndex ); - return texelFetch( morphTargetsTexture, morphUV, 0 ); - } -#endif`,L41=`#ifdef USE_MORPHTARGETS - transformed *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; - } -#endif`,F41=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; -#ifdef FLAT_SHADED - vec3 fdx = dFdx( vViewPosition ); - vec3 fdy = dFdy( vViewPosition ); - vec3 normal = normalize( cross( fdx, fdy ) ); -#else - vec3 normal = normalize( vNormal ); - #ifdef DOUBLE_SIDED - normal *= faceDirection; - #endif -#endif -#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) - #ifdef USE_TANGENT - mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn = getTangentFrame( - vViewPosition, normal, - #if defined( USE_NORMALMAP ) - vNormalMapUv - #elif defined( USE_CLEARCOAT_NORMALMAP ) - vClearcoatNormalMapUv - #else - vUv - #endif - ); - #endif - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - tbn[0] *= faceDirection; - tbn[1] *= faceDirection; - #endif -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - #ifdef USE_TANGENT - mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); - #endif - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - tbn2[0] *= faceDirection; - tbn2[1] *= faceDirection; - #endif -#endif -vec3 nonPerturbedNormal = normal;`,R41=`#ifdef USE_NORMALMAP_OBJECTSPACE - normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - #ifdef FLIP_SIDED - normal = - normal; - #endif - #ifdef DOUBLE_SIDED - normal = normal * faceDirection; - #endif - normal = normalize( normalMatrix * normal ); -#elif defined( USE_NORMALMAP_TANGENTSPACE ) - vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - mapN.xy *= normalScale; - normal = normalize( tbn * mapN ); -#elif defined( USE_BUMPMAP ) - normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); -#endif`,z41=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,D41=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,V41=`#ifndef FLAT_SHADED - vNormal = normalize( transformedNormal ); - #ifdef USE_TANGENT - vTangent = normalize( transformedTangent ); - vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); - #endif -#endif`,M41=`#ifdef USE_NORMALMAP - uniform sampler2D normalMap; - uniform vec2 normalScale; -#endif -#ifdef USE_NORMALMAP_OBJECTSPACE - uniform mat3 normalMatrix; -#endif -#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) - mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { - vec3 q0 = dFdx( eye_pos.xyz ); - vec3 q1 = dFdy( eye_pos.xyz ); - vec2 st0 = dFdx( uv.st ); - vec2 st1 = dFdy( uv.st ); - vec3 N = surf_norm; - vec3 q1perp = cross( q1, N ); - vec3 q0perp = cross( N, q0 ); - vec3 T = q1perp * st0.x + q0perp * st1.x; - vec3 B = q1perp * st0.y + q0perp * st1.y; - float det = max( dot( T, T ), dot( B, B ) ); - float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); - return mat3( T * scale, B * scale, N ); - } -#endif`,w41=`#ifdef USE_CLEARCOAT - vec3 clearcoatNormal = nonPerturbedNormal; -#endif`,P41=`#ifdef USE_CLEARCOAT_NORMALMAP - vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; - clearcoatMapN.xy *= clearcoatNormalScale; - clearcoatNormal = normalize( tbn2 * clearcoatMapN ); -#endif`,_41=`#ifdef USE_CLEARCOATMAP - uniform sampler2D clearcoatMap; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - uniform sampler2D clearcoatNormalMap; - uniform vec2 clearcoatNormalScale; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - uniform sampler2D clearcoatRoughnessMap; -#endif`,T41=`#ifdef USE_IRIDESCENCEMAP - uniform sampler2D iridescenceMap; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform sampler2D iridescenceThicknessMap; -#endif`,k41=`#ifdef OPAQUE -diffuseColor.a = 1.0; -#endif -#ifdef USE_TRANSMISSION -diffuseColor.a *= material.transmissionAlpha; -#endif -gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,S41=`vec3 packNormalToRGB( const in vec3 normal ) { - return normalize( normal ) * 0.5 + 0.5; -} -vec3 unpackRGBToNormal( const in vec3 rgb ) { - return 2.0 * rgb.xyz - 1.0; -} -const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; -const float Inv255 = 1. / 255.; -const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); -const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); -const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); -const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); -vec4 packDepthToRGBA( const in float v ) { - if( v <= 0.0 ) - return vec4( 0., 0., 0., 0. ); - if( v >= 1.0 ) - return vec4( 1., 1., 1., 1. ); - float vuf; - float af = modf( v * PackFactors.a, vuf ); - float bf = modf( vuf * ShiftRight8, vuf ); - float gf = modf( vuf * ShiftRight8, vuf ); - return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); -} -vec3 packDepthToRGB( const in float v ) { - if( v <= 0.0 ) - return vec3( 0., 0., 0. ); - if( v >= 1.0 ) - return vec3( 1., 1., 1. ); - float vuf; - float bf = modf( v * PackFactors.b, vuf ); - float gf = modf( vuf * ShiftRight8, vuf ); - return vec3( vuf * Inv255, gf * PackUpscale, bf ); -} -vec2 packDepthToRG( const in float v ) { - if( v <= 0.0 ) - return vec2( 0., 0. ); - if( v >= 1.0 ) - return vec2( 1., 1. ); - float vuf; - float gf = modf( v * 256., vuf ); - return vec2( vuf * Inv255, gf ); -} -float unpackRGBAToDepth( const in vec4 v ) { - return dot( v, UnpackFactors4 ); -} -float unpackRGBToDepth( const in vec3 v ) { - return dot( v, UnpackFactors3 ); -} -float unpackRGToDepth( const in vec2 v ) { - return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; -} -vec4 pack2HalfToRGBA( const in vec2 v ) { - vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); - return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); -} -vec2 unpackRGBATo2Half( const in vec4 v ) { - return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); -} -float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { - return ( viewZ + near ) / ( near - far ); -} -float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { - return depth * ( near - far ) - near; -} -float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { - return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); -} -float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { - return ( near * far ) / ( ( far - near ) * depth - far ); -}`,j41=`#ifdef PREMULTIPLIED_ALPHA - gl_FragColor.rgb *= gl_FragColor.a; -#endif`,v41=`vec4 mvPosition = vec4( transformed, 1.0 ); -#ifdef USE_BATCHING - mvPosition = batchingMatrix * mvPosition; -#endif -#ifdef USE_INSTANCING - mvPosition = instanceMatrix * mvPosition; -#endif -mvPosition = modelViewMatrix * mvPosition; -gl_Position = projectionMatrix * mvPosition;`,x41=`#ifdef DITHERING - gl_FragColor.rgb = dithering( gl_FragColor.rgb ); -#endif`,y41=`#ifdef DITHERING - vec3 dithering( vec3 color ) { - float grid_position = rand( gl_FragCoord.xy ); - vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); - dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); - return color + dither_shift_RGB; - } -#endif`,h41=`float roughnessFactor = roughness; -#ifdef USE_ROUGHNESSMAP - vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); - roughnessFactor *= texelRoughness.g; -#endif`,g41=`#ifdef USE_ROUGHNESSMAP - uniform sampler2D roughnessMap; -#endif`,b41=`#if NUM_SPOT_LIGHT_COORDS > 0 - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#if NUM_SPOT_LIGHT_MAPS > 0 - uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; -#endif -#ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; - struct DirectionalLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; - struct SpotLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; - struct PointLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - float shadowCameraNear; - float shadowCameraFar; - }; - uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; - #endif - float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { - return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); - } - vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { - return unpackRGBATo2Half( texture2D( shadow, uv ) ); - } - float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ - float occlusion = 1.0; - vec2 distribution = texture2DDistribution( shadow, uv ); - float hard_shadow = step( compare , distribution.x ); - if (hard_shadow != 1.0 ) { - float distance = compare - distribution.x ; - float variance = max( 0.00000, distribution.y * distribution.y ); - float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); - } - return occlusion; - } - float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { - float shadow = 1.0; - shadowCoord.xyz /= shadowCoord.w; - shadowCoord.z += shadowBias; - bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; - bool frustumTest = inFrustum && shadowCoord.z <= 1.0; - if ( frustumTest ) { - #if defined( SHADOWMAP_TYPE_PCF ) - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - float dx0 = - texelSize.x * shadowRadius; - float dy0 = - texelSize.y * shadowRadius; - float dx1 = + texelSize.x * shadowRadius; - float dy1 = + texelSize.y * shadowRadius; - float dx2 = dx0 / 2.0; - float dy2 = dy0 / 2.0; - float dx3 = dx1 / 2.0; - float dy3 = dy1 / 2.0; - shadow = ( - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) - ) * ( 1.0 / 17.0 ); - #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - float dx = texelSize.x; - float dy = texelSize.y; - vec2 uv = shadowCoord.xy; - vec2 f = fract( uv * shadowMapSize + 0.5 ); - uv -= f * texelSize; - shadow = ( - texture2DCompare( shadowMap, uv, shadowCoord.z ) + - texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + - texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + - mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), - f.x ) + - mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), - f.x ) + - mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), - f.y ) + - mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), - f.y ) + - mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), - f.x ), - mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), - f.x ), - f.y ) - ) * ( 1.0 / 9.0 ); - #elif defined( SHADOWMAP_TYPE_VSM ) - shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); - #else - shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); - #endif - } - return mix( 1.0, shadow, shadowIntensity ); - } - vec2 cubeToUV( vec3 v, float texelSizeY ) { - vec3 absV = abs( v ); - float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); - absV *= scaleToCube; - v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); - vec2 planar = v.xy; - float almostATexel = 1.5 * texelSizeY; - float almostOne = 1.0 - almostATexel; - if ( absV.z >= almostOne ) { - if ( v.z > 0.0 ) - planar.x = 4.0 - v.x; - } else if ( absV.x >= almostOne ) { - float signX = sign( v.x ); - planar.x = v.z * signX + 2.0 * signX; - } else if ( absV.y >= almostOne ) { - float signY = sign( v.y ); - planar.x = v.x + 2.0 * signY + 2.0; - planar.y = v.z * signY - 2.0; - } - return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); - } - float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { - float shadow = 1.0; - vec3 lightToPosition = shadowCoord.xyz; - - float lightToPositionLength = length( lightToPosition ); - if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { - float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; - vec3 bd3D = normalize( lightToPosition ); - vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); - #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) - vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; - shadow = ( - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) - ) * ( 1.0 / 9.0 ); - #else - shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); - #endif - } - return mix( 1.0, shadow, shadowIntensity ); - } -#endif`,f41=`#if NUM_SPOT_LIGHT_COORDS > 0 - uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; - struct DirectionalLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - struct SpotLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; - struct PointLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - float shadowCameraNear; - float shadowCameraFar; - }; - uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; - #endif -#endif`,p41=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) - vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - vec4 shadowWorldPosition; -#endif -#if defined( USE_SHADOWMAP ) - #if NUM_DIR_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); - vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); - vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif -#endif -#if NUM_SPOT_LIGHT_COORDS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { - shadowWorldPosition = worldPosition; - #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; - #endif - vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end -#endif`,u41=`float getShadowMask() { - float shadow = 1.0; - #ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - directionalLight = directionalLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { - spotLight = spotLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - pointLight = pointLightShadows[ i ]; - shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; - } - #pragma unroll_loop_end - #endif - #endif - return shadow; -}`,m41=`#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); -#endif`,c41=`#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif`,d41=`#ifdef USE_SKINNING - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif`,l41=`#ifdef USE_SKINNING - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; - #ifdef USE_TANGENT - objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; - #endif -#endif`,n41=`float specularStrength; -#ifdef USE_SPECULARMAP - vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); - specularStrength = texelSpecular.r; -#else - specularStrength = 1.0; -#endif`,s41=`#ifdef USE_SPECULARMAP - uniform sampler2D specularMap; -#endif`,o41=`#if defined( TONE_MAPPING ) - gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); -#endif`,i41=`#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -uniform float toneMappingExposure; -vec3 LinearToneMapping( vec3 color ) { - return saturate( toneMappingExposure * color ); -} -vec3 ReinhardToneMapping( vec3 color ) { - color *= toneMappingExposure; - return saturate( color / ( vec3( 1.0 ) + color ) ); -} -vec3 CineonToneMapping( vec3 color ) { - color *= toneMappingExposure; - color = max( vec3( 0.0 ), color - 0.004 ); - return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); -} -vec3 RRTAndODTFit( vec3 v ) { - vec3 a = v * ( v + 0.0245786 ) - 0.000090537; - vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; - return a / b; -} -vec3 ACESFilmicToneMapping( vec3 color ) { - const mat3 ACESInputMat = mat3( - vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), - vec3( 0.04823, 0.01566, 0.83777 ) - ); - const mat3 ACESOutputMat = mat3( - vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), - vec3( -0.07367, -0.00605, 1.07602 ) - ); - color *= toneMappingExposure / 0.6; - color = ACESInputMat * color; - color = RRTAndODTFit( color ); - color = ACESOutputMat * color; - return saturate( color ); -} -const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( - vec3( 1.6605, - 0.1246, - 0.0182 ), - vec3( - 0.5876, 1.1329, - 0.1006 ), - vec3( - 0.0728, - 0.0083, 1.1187 ) -); -const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( - vec3( 0.6274, 0.0691, 0.0164 ), - vec3( 0.3293, 0.9195, 0.0880 ), - vec3( 0.0433, 0.0113, 0.8956 ) -); -vec3 agxDefaultContrastApprox( vec3 x ) { - vec3 x2 = x * x; - vec3 x4 = x2 * x2; - return + 15.5 * x4 * x2 - - 40.14 * x4 * x - + 31.96 * x4 - - 6.868 * x2 * x - + 0.4298 * x2 - + 0.1191 * x - - 0.00232; -} -vec3 AgXToneMapping( vec3 color ) { - const mat3 AgXInsetMatrix = mat3( - vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), - vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), - vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) - ); - const mat3 AgXOutsetMatrix = mat3( - vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), - vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), - vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) - ); - const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; - color *= toneMappingExposure; - color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; - color = AgXInsetMatrix * color; - color = max( color, 1e-10 ); color = log2( color ); - color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); - color = clamp( color, 0.0, 1.0 ); - color = agxDefaultContrastApprox( color ); - color = AgXOutsetMatrix * color; - color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); - color = LINEAR_REC2020_TO_LINEAR_SRGB * color; - color = clamp( color, 0.0, 1.0 ); - return color; -} -vec3 NeutralToneMapping( vec3 color ) { - const float StartCompression = 0.8 - 0.04; - const float Desaturation = 0.15; - color *= toneMappingExposure; - float x = min( color.r, min( color.g, color.b ) ); - float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; - color -= offset; - float peak = max( color.r, max( color.g, color.b ) ); - if ( peak < StartCompression ) return color; - float d = 1. - StartCompression; - float newPeak = 1. - d * d / ( peak + d - StartCompression ); - color *= newPeak / peak; - float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); - return mix( color, vec3( newPeak ), g ); -} -vec3 CustomToneMapping( vec3 color ) { return color; }`,a41=`#ifdef USE_TRANSMISSION - material.transmission = transmission; - material.transmissionAlpha = 1.0; - material.thickness = thickness; - material.attenuationDistance = attenuationDistance; - material.attenuationColor = attenuationColor; - #ifdef USE_TRANSMISSIONMAP - material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; - #endif - #ifdef USE_THICKNESSMAP - material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; - #endif - vec3 pos = vWorldPosition; - vec3 v = normalize( cameraPosition - pos ); - vec3 n = inverseTransformDirection( normal, viewMatrix ); - vec4 transmitted = getIBLVolumeRefraction( - n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, - pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, - material.attenuationColor, material.attenuationDistance ); - material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); - totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); -#endif`,r41=`#ifdef USE_TRANSMISSION - uniform float transmission; - uniform float thickness; - uniform float attenuationDistance; - uniform vec3 attenuationColor; - #ifdef USE_TRANSMISSIONMAP - uniform sampler2D transmissionMap; - #endif - #ifdef USE_THICKNESSMAP - uniform sampler2D thicknessMap; - #endif - uniform vec2 transmissionSamplerSize; - uniform sampler2D transmissionSamplerMap; - uniform mat4 modelMatrix; - uniform mat4 projectionMatrix; - varying vec3 vWorldPosition; - float w0( float a ) { - return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); - } - float w1( float a ) { - return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); - } - float w2( float a ){ - return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); - } - float w3( float a ) { - return ( 1.0 / 6.0 ) * ( a * a * a ); - } - float g0( float a ) { - return w0( a ) + w1( a ); - } - float g1( float a ) { - return w2( a ) + w3( a ); - } - float h0( float a ) { - return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); - } - float h1( float a ) { - return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); - } - vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { - uv = uv * texelSize.zw + 0.5; - vec2 iuv = floor( uv ); - vec2 fuv = fract( uv ); - float g0x = g0( fuv.x ); - float g1x = g1( fuv.x ); - float h0x = h0( fuv.x ); - float h1x = h1( fuv.x ); - float h0y = h0( fuv.y ); - float h1y = h1( fuv.y ); - vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; - vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; - vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; - vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; - return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + - g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); - } - vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { - vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); - vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); - vec2 fLodSizeInv = 1.0 / fLodSize; - vec2 cLodSizeInv = 1.0 / cLodSize; - vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); - vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); - return mix( fSample, cSample, fract( lod ) ); - } - vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { - vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); - vec3 modelScale; - modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); - modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); - modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); - return normalize( refractionVector ) * thickness * modelScale; - } - float applyIorToRoughness( const in float roughness, const in float ior ) { - return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); - } - vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { - float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); - return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); - } - vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { - if ( isinf( attenuationDistance ) ) { - return vec3( 1.0 ); - } else { - vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; - vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; - } - } - vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, - const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, - const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, - const in vec3 attenuationColor, const in float attenuationDistance ) { - vec4 transmittedLight; - vec3 transmittance; - #ifdef USE_DISPERSION - float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; - vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); - for ( int i = 0; i < 3; i ++ ) { - vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); - vec3 refractedRayExit = position + transmissionRay; - vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); - vec2 refractionCoords = ndcPos.xy / ndcPos.w; - refractionCoords += 1.0; - refractionCoords /= 2.0; - vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); - transmittedLight[ i ] = transmissionSample[ i ]; - transmittedLight.a += transmissionSample.a; - transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; - } - transmittedLight.a /= 3.0; - #else - vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); - vec3 refractedRayExit = position + transmissionRay; - vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); - vec2 refractionCoords = ndcPos.xy / ndcPos.w; - refractionCoords += 1.0; - refractionCoords /= 2.0; - transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); - transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); - #endif - vec3 attenuatedColor = transmittance * transmittedLight.rgb; - vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); - float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; - return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); - } -#endif`,t41=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - varying vec2 vUv; -#endif -#ifdef USE_MAP - varying vec2 vMapUv; -#endif -#ifdef USE_ALPHAMAP - varying vec2 vAlphaMapUv; -#endif -#ifdef USE_LIGHTMAP - varying vec2 vLightMapUv; -#endif -#ifdef USE_AOMAP - varying vec2 vAoMapUv; -#endif -#ifdef USE_BUMPMAP - varying vec2 vBumpMapUv; -#endif -#ifdef USE_NORMALMAP - varying vec2 vNormalMapUv; -#endif -#ifdef USE_EMISSIVEMAP - varying vec2 vEmissiveMapUv; -#endif -#ifdef USE_METALNESSMAP - varying vec2 vMetalnessMapUv; -#endif -#ifdef USE_ROUGHNESSMAP - varying vec2 vRoughnessMapUv; -#endif -#ifdef USE_ANISOTROPYMAP - varying vec2 vAnisotropyMapUv; -#endif -#ifdef USE_CLEARCOATMAP - varying vec2 vClearcoatMapUv; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - varying vec2 vClearcoatNormalMapUv; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - varying vec2 vClearcoatRoughnessMapUv; -#endif -#ifdef USE_IRIDESCENCEMAP - varying vec2 vIridescenceMapUv; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - varying vec2 vIridescenceThicknessMapUv; -#endif -#ifdef USE_SHEEN_COLORMAP - varying vec2 vSheenColorMapUv; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - varying vec2 vSheenRoughnessMapUv; -#endif -#ifdef USE_SPECULARMAP - varying vec2 vSpecularMapUv; -#endif -#ifdef USE_SPECULAR_COLORMAP - varying vec2 vSpecularColorMapUv; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - varying vec2 vSpecularIntensityMapUv; -#endif -#ifdef USE_TRANSMISSIONMAP - uniform mat3 transmissionMapTransform; - varying vec2 vTransmissionMapUv; -#endif -#ifdef USE_THICKNESSMAP - uniform mat3 thicknessMapTransform; - varying vec2 vThicknessMapUv; -#endif`,e41=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - varying vec2 vUv; -#endif -#ifdef USE_MAP - uniform mat3 mapTransform; - varying vec2 vMapUv; -#endif -#ifdef USE_ALPHAMAP - uniform mat3 alphaMapTransform; - varying vec2 vAlphaMapUv; -#endif -#ifdef USE_LIGHTMAP - uniform mat3 lightMapTransform; - varying vec2 vLightMapUv; -#endif -#ifdef USE_AOMAP - uniform mat3 aoMapTransform; - varying vec2 vAoMapUv; -#endif -#ifdef USE_BUMPMAP - uniform mat3 bumpMapTransform; - varying vec2 vBumpMapUv; -#endif -#ifdef USE_NORMALMAP - uniform mat3 normalMapTransform; - varying vec2 vNormalMapUv; -#endif -#ifdef USE_DISPLACEMENTMAP - uniform mat3 displacementMapTransform; - varying vec2 vDisplacementMapUv; -#endif -#ifdef USE_EMISSIVEMAP - uniform mat3 emissiveMapTransform; - varying vec2 vEmissiveMapUv; -#endif -#ifdef USE_METALNESSMAP - uniform mat3 metalnessMapTransform; - varying vec2 vMetalnessMapUv; -#endif -#ifdef USE_ROUGHNESSMAP - uniform mat3 roughnessMapTransform; - varying vec2 vRoughnessMapUv; -#endif -#ifdef USE_ANISOTROPYMAP - uniform mat3 anisotropyMapTransform; - varying vec2 vAnisotropyMapUv; -#endif -#ifdef USE_CLEARCOATMAP - uniform mat3 clearcoatMapTransform; - varying vec2 vClearcoatMapUv; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - uniform mat3 clearcoatNormalMapTransform; - varying vec2 vClearcoatNormalMapUv; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - uniform mat3 clearcoatRoughnessMapTransform; - varying vec2 vClearcoatRoughnessMapUv; -#endif -#ifdef USE_SHEEN_COLORMAP - uniform mat3 sheenColorMapTransform; - varying vec2 vSheenColorMapUv; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - uniform mat3 sheenRoughnessMapTransform; - varying vec2 vSheenRoughnessMapUv; -#endif -#ifdef USE_IRIDESCENCEMAP - uniform mat3 iridescenceMapTransform; - varying vec2 vIridescenceMapUv; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform mat3 iridescenceThicknessMapTransform; - varying vec2 vIridescenceThicknessMapUv; -#endif -#ifdef USE_SPECULARMAP - uniform mat3 specularMapTransform; - varying vec2 vSpecularMapUv; -#endif -#ifdef USE_SPECULAR_COLORMAP - uniform mat3 specularColorMapTransform; - varying vec2 vSpecularColorMapUv; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - uniform mat3 specularIntensityMapTransform; - varying vec2 vSpecularIntensityMapUv; -#endif -#ifdef USE_TRANSMISSIONMAP - uniform mat3 transmissionMapTransform; - varying vec2 vTransmissionMapUv; -#endif -#ifdef USE_THICKNESSMAP - uniform mat3 thicknessMapTransform; - varying vec2 vThicknessMapUv; -#endif`,AQ1=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - vUv = vec3( uv, 1 ).xy; -#endif -#ifdef USE_MAP - vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ALPHAMAP - vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_LIGHTMAP - vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_AOMAP - vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_BUMPMAP - vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_NORMALMAP - vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_DISPLACEMENTMAP - vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_EMISSIVEMAP - vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_METALNESSMAP - vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ROUGHNESSMAP - vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ANISOTROPYMAP - vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOATMAP - vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_IRIDESCENCEMAP - vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SHEEN_COLORMAP - vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULARMAP - vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULAR_COLORMAP - vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_TRANSMISSIONMAP - vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_THICKNESSMAP - vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; -#endif`,QQ1=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 - vec4 worldPosition = vec4( transformed, 1.0 ); - #ifdef USE_BATCHING - worldPosition = batchingMatrix * worldPosition; - #endif - #ifdef USE_INSTANCING - worldPosition = instanceMatrix * worldPosition; - #endif - worldPosition = modelMatrix * worldPosition; -#endif`,JQ1=`varying vec2 vUv; -uniform mat3 uvTransform; -void main() { - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - gl_Position = vec4( position.xy, 1.0, 1.0 ); -}`,KQ1=`uniform sampler2D t2D; -uniform float backgroundIntensity; -varying vec2 vUv; -void main() { - vec4 texColor = texture2D( t2D, vUv ); - #ifdef DECODE_VIDEO_TEXTURE - texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,CQ1=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,YQ1=`#ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; -#elif defined( ENVMAP_TYPE_CUBE_UV ) - uniform sampler2D envMap; -#endif -uniform float flipEnvMap; -uniform float backgroundBlurriness; -uniform float backgroundIntensity; -uniform mat3 backgroundRotation; -varying vec3 vWorldDirection; -#include -void main() { - #ifdef ENVMAP_TYPE_CUBE - vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); - #elif defined( ENVMAP_TYPE_CUBE_UV ) - vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); - #else - vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,UQ1=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,ZQ1=`uniform samplerCube tCube; -uniform float tFlip; -uniform float opacity; -varying vec3 vWorldDirection; -void main() { - vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); - gl_FragColor = texColor; - gl_FragColor.a *= opacity; - #include - #include -}`,BQ1=`#include -#include -#include -#include -#include -#include -#include -#include -varying vec2 vHighPrecisionZW; -void main() { - #include - #include - #include - #include - #ifdef USE_DISPLACEMENTMAP - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - vHighPrecisionZW = gl_Position.zw; -}`,XQ1=`#if DEPTH_PACKING == 3200 - uniform float opacity; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -varying vec2 vHighPrecisionZW; -void main() { - vec4 diffuseColor = vec4( 1.0 ); - #include - #if DEPTH_PACKING == 3200 - diffuseColor.a = opacity; - #endif - #include - #include - #include - #include - #include - float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; - #if DEPTH_PACKING == 3200 - gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); - #elif DEPTH_PACKING == 3201 - gl_FragColor = packDepthToRGBA( fragCoordZ ); - #elif DEPTH_PACKING == 3202 - gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); - #elif DEPTH_PACKING == 3203 - gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); - #endif -}`,EQ1=`#define DISTANCE -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #ifdef USE_DISPLACEMENTMAP - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - vWorldPosition = worldPosition.xyz; -}`,$Q1=`#define DISTANCE -uniform vec3 referencePosition; -uniform float nearDistance; -uniform float farDistance; -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -#include -void main () { - vec4 diffuseColor = vec4( 1.0 ); - #include - #include - #include - #include - #include - float dist = length( vWorldPosition - referencePosition ); - dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); - dist = saturate( dist ); - gl_FragColor = packDepthToRGBA( dist ); -}`,HQ1=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include -}`,GQ1=`uniform sampler2D tEquirect; -varying vec3 vWorldDirection; -#include -void main() { - vec3 direction = normalize( vWorldDirection ); - vec2 sampleUV = equirectUv( direction ); - gl_FragColor = texture2D( tEquirect, sampleUV ); - #include - #include -}`,WQ1=`uniform float scale; -attribute float lineDistance; -varying float vLineDistance; -#include -#include -#include -#include -#include -#include -#include -void main() { - vLineDistance = scale * lineDistance; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,IQ1=`uniform vec3 diffuse; -uniform float opacity; -uniform float dashSize; -uniform float totalSize; -varying float vLineDistance; -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - if ( mod( vLineDistance, totalSize ) > dashSize ) { - discard; - } - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include - #include -}`,qQ1=`#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) - #include - #include - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,OQ1=`uniform vec3 diffuse; -uniform float opacity; -#ifndef FLAT_SHADED - varying vec3 vNormal; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - #include - #include - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; - #else - reflectedLight.indirectDiffuse += vec3( 1.0 ); - #endif - #include - reflectedLight.indirectDiffuse *= diffuseColor.rgb; - vec3 outgoingLight = reflectedLight.indirectDiffuse; - #include - #include - #include - #include - #include - #include - #include -}`,NQ1=`#define LAMBERT -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include - #include -}`,LQ1=`#define LAMBERT -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,FQ1=`#define MATCAP -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; -}`,RQ1=`#define MATCAP -uniform vec3 diffuse; -uniform float opacity; -uniform sampler2D matcap; -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 viewDir = normalize( vViewPosition ); - vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); - vec3 y = cross( viewDir, x ); - vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; - #ifdef USE_MATCAP - vec4 matcapColor = texture2D( matcap, uv ); - #else - vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); - #endif - vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; - #include - #include - #include - #include - #include - #include -}`,zQ1=`#define NORMAL -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - vViewPosition = - mvPosition.xyz; -#endif -}`,DQ1=`#define NORMAL -uniform float opacity; -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); - #include - #include - #include - #include - gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); - #ifdef OPAQUE - gl_FragColor.a = 1.0; - #endif -}`,VQ1=`#define PHONG -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include - #include -}`,MQ1=`#define PHONG -uniform vec3 diffuse; -uniform vec3 emissive; -uniform vec3 specular; -uniform float shininess; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,wQ1=`#define STANDARD -varying vec3 vViewPosition; -#ifdef USE_TRANSMISSION - varying vec3 vWorldPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include -#ifdef USE_TRANSMISSION - vWorldPosition = worldPosition.xyz; -#endif -}`,PQ1=`#define STANDARD -#ifdef PHYSICAL - #define IOR - #define USE_SPECULAR -#endif -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float roughness; -uniform float metalness; -uniform float opacity; -#ifdef IOR - uniform float ior; -#endif -#ifdef USE_SPECULAR - uniform float specularIntensity; - uniform vec3 specularColor; - #ifdef USE_SPECULAR_COLORMAP - uniform sampler2D specularColorMap; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - uniform sampler2D specularIntensityMap; - #endif -#endif -#ifdef USE_CLEARCOAT - uniform float clearcoat; - uniform float clearcoatRoughness; -#endif -#ifdef USE_DISPERSION - uniform float dispersion; -#endif -#ifdef USE_IRIDESCENCE - uniform float iridescence; - uniform float iridescenceIOR; - uniform float iridescenceThicknessMinimum; - uniform float iridescenceThicknessMaximum; -#endif -#ifdef USE_SHEEN - uniform vec3 sheenColor; - uniform float sheenRoughness; - #ifdef USE_SHEEN_COLORMAP - uniform sampler2D sheenColorMap; - #endif - #ifdef USE_SHEEN_ROUGHNESSMAP - uniform sampler2D sheenRoughnessMap; - #endif -#endif -#ifdef USE_ANISOTROPY - uniform vec2 anisotropyVector; - #ifdef USE_ANISOTROPYMAP - uniform sampler2D anisotropyMap; - #endif -#endif -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; - vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; - #include - vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; - #ifdef USE_SHEEN - float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); - outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; - #endif - #ifdef USE_CLEARCOAT - float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); - vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); - outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; - #endif - #include - #include - #include - #include - #include - #include -}`,_Q1=`#define TOON -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include -}`,TQ1=`#define TOON -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include -}`,kQ1=`uniform float size; -uniform float scale; -#include -#include -#include -#include -#include -#include -#ifdef USE_POINTS_UV - varying vec2 vUv; - uniform mat3 uvTransform; -#endif -void main() { - #ifdef USE_POINTS_UV - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - #endif - #include - #include - #include - #include - #include - #include - gl_PointSize = size; - #ifdef USE_SIZEATTENUATION - bool isPerspective = isPerspectiveMatrix( projectionMatrix ); - if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); - #endif - #include - #include - #include - #include -}`,SQ1=`uniform vec3 diffuse; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include - #include -}`,jQ1=`#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,vQ1=`uniform vec3 color; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); - #include - #include - #include -}`,xQ1=`uniform float rotation; -uniform vec2 center; -#include -#include -#include -#include -#include -void main() { - #include - vec4 mvPosition = modelViewMatrix[ 3 ]; - vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); - #ifndef USE_SIZEATTENUATION - bool isPerspective = isPerspectiveMatrix( projectionMatrix ); - if ( isPerspective ) scale *= - mvPosition.z; - #endif - vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; - vec2 rotatedPosition; - rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; - rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; - mvPosition.xy += rotatedPosition; - gl_Position = projectionMatrix * mvPosition; - #include - #include - #include -}`,yQ1=`uniform vec3 diffuse; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include -}`,$A={alphahash_fragment:K71,alphahash_pars_fragment:C71,alphamap_fragment:Y71,alphamap_pars_fragment:U71,alphatest_fragment:Z71,alphatest_pars_fragment:B71,aomap_fragment:X71,aomap_pars_fragment:E71,batching_pars_vertex:$71,batching_vertex:H71,begin_vertex:G71,beginnormal_vertex:W71,bsdfs:I71,iridescence_fragment:q71,bumpmap_pars_fragment:O71,clipping_planes_fragment:N71,clipping_planes_pars_fragment:L71,clipping_planes_pars_vertex:F71,clipping_planes_vertex:R71,color_fragment:z71,color_pars_fragment:D71,color_pars_vertex:V71,color_vertex:M71,common:w71,cube_uv_reflection_fragment:P71,defaultnormal_vertex:_71,displacementmap_pars_vertex:T71,displacementmap_vertex:k71,emissivemap_fragment:S71,emissivemap_pars_fragment:j71,colorspace_fragment:v71,colorspace_pars_fragment:x71,envmap_fragment:y71,envmap_common_pars_fragment:h71,envmap_pars_fragment:g71,envmap_pars_vertex:b71,envmap_physical_pars_fragment:i71,envmap_vertex:f71,fog_vertex:p71,fog_pars_vertex:u71,fog_fragment:m71,fog_pars_fragment:c71,gradientmap_pars_fragment:d71,lightmap_pars_fragment:l71,lights_lambert_fragment:n71,lights_lambert_pars_fragment:s71,lights_pars_begin:o71,lights_toon_fragment:a71,lights_toon_pars_fragment:r71,lights_phong_fragment:t71,lights_phong_pars_fragment:e71,lights_physical_fragment:A41,lights_physical_pars_fragment:Q41,lights_fragment_begin:J41,lights_fragment_maps:K41,lights_fragment_end:C41,logdepthbuf_fragment:Y41,logdepthbuf_pars_fragment:U41,logdepthbuf_pars_vertex:Z41,logdepthbuf_vertex:B41,map_fragment:X41,map_pars_fragment:E41,map_particle_fragment:$41,map_particle_pars_fragment:H41,metalnessmap_fragment:G41,metalnessmap_pars_fragment:W41,morphinstance_vertex:I41,morphcolor_vertex:q41,morphnormal_vertex:O41,morphtarget_pars_vertex:N41,morphtarget_vertex:L41,normal_fragment_begin:F41,normal_fragment_maps:R41,normal_pars_fragment:z41,normal_pars_vertex:D41,normal_vertex:V41,normalmap_pars_fragment:M41,clearcoat_normal_fragment_begin:w41,clearcoat_normal_fragment_maps:P41,clearcoat_pars_fragment:_41,iridescence_pars_fragment:T41,opaque_fragment:k41,packing:S41,premultiplied_alpha_fragment:j41,project_vertex:v41,dithering_fragment:x41,dithering_pars_fragment:y41,roughnessmap_fragment:h41,roughnessmap_pars_fragment:g41,shadowmap_pars_fragment:b41,shadowmap_pars_vertex:f41,shadowmap_vertex:p41,shadowmask_pars_fragment:u41,skinbase_vertex:m41,skinning_pars_vertex:c41,skinning_vertex:d41,skinnormal_vertex:l41,specularmap_fragment:n41,specularmap_pars_fragment:s41,tonemapping_fragment:o41,tonemapping_pars_fragment:i41,transmission_fragment:a41,transmission_pars_fragment:r41,uv_pars_fragment:t41,uv_pars_vertex:e41,uv_vertex:AQ1,worldpos_vertex:QQ1,background_vert:JQ1,background_frag:KQ1,backgroundCube_vert:CQ1,backgroundCube_frag:YQ1,cube_vert:UQ1,cube_frag:ZQ1,depth_vert:BQ1,depth_frag:XQ1,distanceRGBA_vert:EQ1,distanceRGBA_frag:$Q1,equirect_vert:HQ1,equirect_frag:GQ1,linedashed_vert:WQ1,linedashed_frag:IQ1,meshbasic_vert:qQ1,meshbasic_frag:OQ1,meshlambert_vert:NQ1,meshlambert_frag:LQ1,meshmatcap_vert:FQ1,meshmatcap_frag:RQ1,meshnormal_vert:zQ1,meshnormal_frag:DQ1,meshphong_vert:VQ1,meshphong_frag:MQ1,meshphysical_vert:wQ1,meshphysical_frag:PQ1,meshtoon_vert:_Q1,meshtoon_frag:TQ1,points_vert:kQ1,points_frag:SQ1,shadow_vert:jQ1,shadow_frag:vQ1,sprite_vert:xQ1,sprite_frag:yQ1},M0={common:{diffuse:{value:/*@__PURE__*/new y1(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:/*@__PURE__*/new a0},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/new a0},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:/*@__PURE__*/new a0}},envmap:{envMap:{value:null},envMapRotation:{value:/*@__PURE__*/new a0},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:0.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:/*@__PURE__*/new a0}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:/*@__PURE__*/new a0}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:/*@__PURE__*/new a0},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:/*@__PURE__*/new a0},normalScale:{value:/*@__PURE__*/new p1(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:/*@__PURE__*/new a0},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:/*@__PURE__*/new a0}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:/*@__PURE__*/new a0}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:/*@__PURE__*/new a0}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:0.00025},fogNear:{value:1},fogFar:{value:2000},fogColor:{value:/*@__PURE__*/new y1(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:/*@__PURE__*/new y1(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/new a0},alphaTest:{value:0},uvTransform:{value:/*@__PURE__*/new a0}},sprite:{diffuse:{value:/*@__PURE__*/new y1(16777215)},opacity:{value:1},center:{value:/*@__PURE__*/new p1(0.5,0.5)},rotation:{value:0},map:{value:null},mapTransform:{value:/*@__PURE__*/new a0},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/new a0},alphaTest:{value:0}}},$6={basic:{uniforms:/*@__PURE__*/B6([M0.common,M0.specularmap,M0.envmap,M0.aomap,M0.lightmap,M0.fog]),vertexShader:$A.meshbasic_vert,fragmentShader:$A.meshbasic_frag},lambert:{uniforms:/*@__PURE__*/B6([M0.common,M0.specularmap,M0.envmap,M0.aomap,M0.lightmap,M0.emissivemap,M0.bumpmap,M0.normalmap,M0.displacementmap,M0.fog,M0.lights,{emissive:{value:/*@__PURE__*/new y1(0)}}]),vertexShader:$A.meshlambert_vert,fragmentShader:$A.meshlambert_frag},phong:{uniforms:/*@__PURE__*/B6([M0.common,M0.specularmap,M0.envmap,M0.aomap,M0.lightmap,M0.emissivemap,M0.bumpmap,M0.normalmap,M0.displacementmap,M0.fog,M0.lights,{emissive:{value:/*@__PURE__*/new y1(0)},specular:{value:/*@__PURE__*/new y1(1118481)},shininess:{value:30}}]),vertexShader:$A.meshphong_vert,fragmentShader:$A.meshphong_frag},standard:{uniforms:/*@__PURE__*/B6([M0.common,M0.envmap,M0.aomap,M0.lightmap,M0.emissivemap,M0.bumpmap,M0.normalmap,M0.displacementmap,M0.roughnessmap,M0.metalnessmap,M0.fog,M0.lights,{emissive:{value:/*@__PURE__*/new y1(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:$A.meshphysical_vert,fragmentShader:$A.meshphysical_frag},toon:{uniforms:/*@__PURE__*/B6([M0.common,M0.aomap,M0.lightmap,M0.emissivemap,M0.bumpmap,M0.normalmap,M0.displacementmap,M0.gradientmap,M0.fog,M0.lights,{emissive:{value:/*@__PURE__*/new y1(0)}}]),vertexShader:$A.meshtoon_vert,fragmentShader:$A.meshtoon_frag},matcap:{uniforms:/*@__PURE__*/B6([M0.common,M0.bumpmap,M0.normalmap,M0.displacementmap,M0.fog,{matcap:{value:null}}]),vertexShader:$A.meshmatcap_vert,fragmentShader:$A.meshmatcap_frag},points:{uniforms:/*@__PURE__*/B6([M0.points,M0.fog]),vertexShader:$A.points_vert,fragmentShader:$A.points_frag},dashed:{uniforms:/*@__PURE__*/B6([M0.common,M0.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:$A.linedashed_vert,fragmentShader:$A.linedashed_frag},depth:{uniforms:/*@__PURE__*/B6([M0.common,M0.displacementmap]),vertexShader:$A.depth_vert,fragmentShader:$A.depth_frag},normal:{uniforms:/*@__PURE__*/B6([M0.common,M0.bumpmap,M0.normalmap,M0.displacementmap,{opacity:{value:1}}]),vertexShader:$A.meshnormal_vert,fragmentShader:$A.meshnormal_frag},sprite:{uniforms:/*@__PURE__*/B6([M0.sprite,M0.fog]),vertexShader:$A.sprite_vert,fragmentShader:$A.sprite_frag},background:{uniforms:{uvTransform:{value:/*@__PURE__*/new a0},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:$A.background_vert,fragmentShader:$A.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:/*@__PURE__*/new a0}},vertexShader:$A.backgroundCube_vert,fragmentShader:$A.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:$A.cube_vert,fragmentShader:$A.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:$A.equirect_vert,fragmentShader:$A.equirect_frag},distanceRGBA:{uniforms:/*@__PURE__*/B6([M0.common,M0.displacementmap,{referencePosition:{value:/*@__PURE__*/new I1},nearDistance:{value:1},farDistance:{value:1000}}]),vertexShader:$A.distanceRGBA_vert,fragmentShader:$A.distanceRGBA_frag},shadow:{uniforms:/*@__PURE__*/B6([M0.lights,M0.fog,{color:{value:/*@__PURE__*/new y1(0)},opacity:{value:1}}]),vertexShader:$A.shadow_vert,fragmentShader:$A.shadow_frag}};$6.physical={uniforms:/*@__PURE__*/B6([$6.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:/*@__PURE__*/new a0},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:/*@__PURE__*/new a0},clearcoatNormalScale:{value:/*@__PURE__*/new p1(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:/*@__PURE__*/new a0},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:/*@__PURE__*/new a0},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:/*@__PURE__*/new a0},sheen:{value:0},sheenColor:{value:/*@__PURE__*/new y1(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:/*@__PURE__*/new a0},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:/*@__PURE__*/new a0},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:/*@__PURE__*/new a0},transmissionSamplerSize:{value:/*@__PURE__*/new p1},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:/*@__PURE__*/new a0},attenuationDistance:{value:0},attenuationColor:{value:/*@__PURE__*/new y1(0)},specularColor:{value:/*@__PURE__*/new y1(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:/*@__PURE__*/new a0},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:/*@__PURE__*/new a0},anisotropyVector:{value:/*@__PURE__*/new p1},anisotropyMap:{value:null},anisotropyMapTransform:{value:/*@__PURE__*/new a0}}]),vertexShader:$A.meshphysical_vert,fragmentShader:$A.meshphysical_frag};var $G={r:0,b:0,g:0},iQ=/*@__PURE__*/new t2,hQ1=/*@__PURE__*/new Y0;function gQ1(A,Q,J,K,C,U,Y){let Z=new y1(0),X=U===!0?0:1,E,H,$=null,I=0,N=null;function F(M){let T=M.isScene===!0?M.background:null;if(T&&T.isTexture)T=(M.backgroundBlurriness>0?J:Q).get(T);return T}function V(M){let T=!1,h=F(M);if(h===null)L(Z,X);else if(h&&h.isColor)L(h,1),T=!0;let y=A.xr.getEnvironmentBlendMode();if(y==="additive")K.buffers.color.setClear(0,0,0,1,Y);else if(y==="alpha-blend")K.buffers.color.setClear(0,0,0,0,Y);if(A.autoClear||T)K.buffers.depth.setTest(!0),K.buffers.depth.setMask(!0),K.buffers.color.setMask(!0),A.clear(A.autoClearColor,A.autoClearDepth,A.autoClearStencil)}function D(M,T){let h=F(T);if(h&&(h.isCubeTexture||h.mapping===eK)){if(H===void 0)H=new _0(new R8(1,1,1),new T0({name:"BackgroundCubeMaterial",uniforms:mQ($6.backgroundCube.uniforms),vertexShader:$6.backgroundCube.vertexShader,fragmentShader:$6.backgroundCube.fragmentShader,side:w2,depthTest:!1,depthWrite:!1,fog:!1})),H.geometry.deleteAttribute("normal"),H.geometry.deleteAttribute("uv"),H.onBeforeRender=function(y,g,f){this.matrixWorld.copyPosition(f.matrixWorld)},Object.defineProperty(H.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),C.update(H);if(iQ.copy(T.backgroundRotation),iQ.x*=-1,iQ.y*=-1,iQ.z*=-1,h.isCubeTexture&&h.isRenderTargetTexture===!1)iQ.y*=-1,iQ.z*=-1;if(H.material.uniforms.envMap.value=h,H.material.uniforms.flipEnvMap.value=h.isCubeTexture&&h.isRenderTargetTexture===!1?-1:1,H.material.uniforms.backgroundBlurriness.value=T.backgroundBlurriness,H.material.uniforms.backgroundIntensity.value=T.backgroundIntensity,H.material.uniforms.backgroundRotation.value.setFromMatrix4(hQ1.makeRotationFromEuler(iQ)),H.material.toneMapped=e0.getTransfer(h.colorSpace)!==L2,$!==h||I!==h.version||N!==A.toneMapping)H.material.needsUpdate=!0,$=h,I=h.version,N=A.toneMapping;H.layers.enableAll(),M.unshift(H,H.geometry,H.material,0,0,null)}else if(h&&h.isTexture){if(E===void 0)E=new _0(new g8(2,2),new T0({name:"BackgroundMaterial",uniforms:mQ($6.background.uniforms),vertexShader:$6.background.vertexShader,fragmentShader:$6.background.fragmentShader,side:M2,depthTest:!1,depthWrite:!1,fog:!1})),E.geometry.deleteAttribute("normal"),Object.defineProperty(E.material,"map",{get:function(){return this.uniforms.t2D.value}}),C.update(E);if(E.material.uniforms.t2D.value=h,E.material.uniforms.backgroundIntensity.value=T.backgroundIntensity,E.material.toneMapped=e0.getTransfer(h.colorSpace)!==L2,h.matrixAutoUpdate===!0)h.updateMatrix();if(E.material.uniforms.uvTransform.value.copy(h.matrix),$!==h||I!==h.version||N!==A.toneMapping)E.material.needsUpdate=!0,$=h,I=h.version,N=A.toneMapping;E.layers.enableAll(),M.unshift(E,E.geometry,E.material,0,0,null)}}function L(M,T){M.getRGB($G,yF(A)),K.buffers.color.setClear($G.r,$G.g,$G.b,T,Y)}function R(){if(H!==void 0)H.geometry.dispose(),H.material.dispose(),H=void 0;if(E!==void 0)E.geometry.dispose(),E.material.dispose(),E=void 0}return{getClearColor:function(){return Z},setClearColor:function(M,T=1){Z.set(M),X=T,L(Z,X)},getClearAlpha:function(){return X},setClearAlpha:function(M){X=M,L(Z,X)},render:V,addToRenderList:D,dispose:R}}function bQ1(A,Q){let J=A.getParameter(A.MAX_VERTEX_ATTRIBS),K={},C=I(null),U=C,Y=!1;function Z(d,n,B,q,P){let O=!1,w=$(q,B,n);if(U!==w)U=w,E(U.object);if(O=N(d,q,B,P),O)F(d,q,B,P);if(P!==null)Q.update(P,A.ELEMENT_ARRAY_BUFFER);if(O||Y){if(Y=!1,T(d,n,B,q),P!==null)A.bindBuffer(A.ELEMENT_ARRAY_BUFFER,Q.get(P).buffer)}}function X(){return A.createVertexArray()}function E(d){return A.bindVertexArray(d)}function H(d){return A.deleteVertexArray(d)}function $(d,n,B){let q=B.wireframe===!0,P=K[d.id];if(P===void 0)P={},K[d.id]=P;let O=P[n.id];if(O===void 0)O={},P[n.id]=O;let w=O[q];if(w===void 0)w=I(X()),O[q]=w;return w}function I(d){let n=[],B=[],q=[];for(let P=0;P=0){let W=P[S],j=O[S];if(j===void 0){if(S==="instanceMatrix"&&d.instanceMatrix)j=d.instanceMatrix;if(S==="instanceColor"&&d.instanceColor)j=d.instanceColor}if(W===void 0)return!0;if(W.attribute!==j)return!0;if(j&&W.data!==j.data)return!0;w++}if(U.attributesNum!==w)return!0;if(U.index!==q)return!0;return!1}function F(d,n,B,q){let P={},O=n.attributes,w=0,k=B.getAttributes();for(let S in k)if(k[S].location>=0){let W=O[S];if(W===void 0){if(S==="instanceMatrix"&&d.instanceMatrix)W=d.instanceMatrix;if(S==="instanceColor"&&d.instanceColor)W=d.instanceColor}let j={};if(j.attribute=W,W&&W.data)j.data=W.data;P[S]=j,w++}U.attributes=P,U.attributesNum=w,U.index=q}function V(){let d=U.newAttributes;for(let n=0,B=d.length;n=0){let _=P[k];if(_===void 0){if(k==="instanceMatrix"&&d.instanceMatrix)_=d.instanceMatrix;if(k==="instanceColor"&&d.instanceColor)_=d.instanceColor}if(_!==void 0){let{normalized:W,itemSize:j}=_,b=Q.get(_);if(b===void 0)continue;let{buffer:p,type:s,bytesPerElement:r}=b,A1=s===A.INT||s===A.UNSIGNED_INT||_.gpuType===EH;if(_.isInterleavedBufferAttribute){let Q1=_.data,e=Q1.stride,t=_.offset;if(Q1.isInstancedInterleavedBuffer){for(let U1=0;U10&&A.getShaderPrecisionFormat(A.FRAGMENT_SHADER,A.HIGH_FLOAT).precision>0)return"highp";g="mediump"}if(g==="mediump"){if(A.getShaderPrecisionFormat(A.VERTEX_SHADER,A.MEDIUM_FLOAT).precision>0&&A.getShaderPrecisionFormat(A.FRAGMENT_SHADER,A.MEDIUM_FLOAT).precision>0)return"mediump"}return"lowp"}let E=J.precision!==void 0?J.precision:"highp",H=X(E);if(H!==E)console.warn("THREE.WebGLRenderer:",E,"not supported, using",H,"instead."),E=H;let $=J.logarithmicDepthBuffer===!0,I=J.reverseDepthBuffer===!0&&Q.has("EXT_clip_control"),N=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS),F=A.getParameter(A.MAX_VERTEX_TEXTURE_IMAGE_UNITS),V=A.getParameter(A.MAX_TEXTURE_SIZE),D=A.getParameter(A.MAX_CUBE_MAP_TEXTURE_SIZE),L=A.getParameter(A.MAX_VERTEX_ATTRIBS),R=A.getParameter(A.MAX_VERTEX_UNIFORM_VECTORS),M=A.getParameter(A.MAX_VARYING_VECTORS),T=A.getParameter(A.MAX_FRAGMENT_UNIFORM_VECTORS),h=F>0,y=A.getParameter(A.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:U,getMaxPrecision:X,textureFormatReadable:Y,textureTypeReadable:Z,precision:E,logarithmicDepthBuffer:$,reverseDepthBuffer:I,maxTextures:N,maxVertexTextures:F,maxTextureSize:V,maxCubemapSize:D,maxAttributes:L,maxVertexUniforms:R,maxVaryings:M,maxFragmentUniforms:T,vertexTextures:h,maxSamples:y}}function uQ1(A){let Q=this,J=null,K=0,C=!1,U=!1,Y=new V2,Z=new a0,X={value:null,needsUpdate:!1};this.uniform=X,this.numPlanes=0,this.numIntersection=0,this.init=function($,I){let N=$.length!==0||I||K!==0||C;return C=I,K=$.length,N},this.beginShadows=function(){U=!0,H(null)},this.endShadows=function(){U=!1},this.setGlobalState=function($,I){J=H($,I,0)},this.setState=function($,I,N){let{clippingPlanes:F,clipIntersection:V,clipShadows:D}=$,L=A.get($);if(!C||F===null||F.length===0||U&&!D)if(U)H(null);else E();else{let R=U?0:K,M=R*4,T=L.clippingState||null;X.value=T,T=H(F,I,M,N);for(let h=0;h!==M;++h)T[h]=J[h];L.clippingState=T,this.numIntersection=V?this.numPlanes:0,this.numPlanes+=R}};function E(){if(X.value!==J)X.value=J,X.needsUpdate=K>0;Q.numPlanes=K,Q.numIntersection=0}function H($,I,N,F){let V=$!==null?$.length:0,D=null;if(V!==0){if(D=X.value,F!==!0||D===null){let L=N+V*4,R=I.matrixWorldInverse;if(Z.getNormalMatrix(R),D===null||D.length0){let E=new BZ(X.height);return E.fromEquirectangularTexture(A,Y),Q.set(Y,E),Y.addEventListener("dispose",C),J(E.texture,Y.mapping)}else return null}}return Y}function C(Y){let Z=Y.target;Z.removeEventListener("dispose",C);let X=Q.get(Z);if(X!==void 0)Q.delete(Z),X.dispose()}function U(){Q=/*@__PURE__*/new WeakMap}return{get:K,dispose:U}}var VC=4,ag=[0.125,0.215,0.35,0.446,0.526,0.582],tQ=20,XR=/*@__PURE__*/new o8,rg=/*@__PURE__*/new y1,ER=null,$R=0,HR=0,GR=!1,rQ=(1+Math.sqrt(5))/2,DC=1/rQ,tg=[/*@__PURE__*/new I1(-rQ,DC,0),/*@__PURE__*/new I1(rQ,DC,0),/*@__PURE__*/new I1(-DC,0,rQ),/*@__PURE__*/new I1(DC,0,rQ),/*@__PURE__*/new I1(0,rQ,-DC),/*@__PURE__*/new I1(0,rQ,DC),/*@__PURE__*/new I1(-1,1,-1),/*@__PURE__*/new I1(1,1,-1),/*@__PURE__*/new I1(-1,1,1),/*@__PURE__*/new I1(1,1,1)];class WG{constructor(A){this._renderer=A,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(A,Q=0,J=0.1,K=100){ER=this._renderer.getRenderTarget(),$R=this._renderer.getActiveCubeFace(),HR=this._renderer.getActiveMipmapLevel(),GR=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);let C=this._allocateTargets();if(C.depthBuffer=!0,this._sceneToCubeUV(A,J,K,C),Q>0)this._blur(C,0,0,Q);return this._applyPMREM(C),this._cleanup(C),C}fromEquirectangular(A,Q=null){return this._fromTexture(A,Q)}fromCubemap(A,Q=null){return this._fromTexture(A,Q)}compileCubemapShader(){if(this._cubemapMaterial===null)this._cubemapMaterial=Qb(),this._compileMaterial(this._cubemapMaterial)}compileEquirectangularShader(){if(this._equirectMaterial===null)this._equirectMaterial=Ab(),this._compileMaterial(this._equirectMaterial)}dispose(){if(this._dispose(),this._cubemapMaterial!==null)this._cubemapMaterial.dispose();if(this._equirectMaterial!==null)this._equirectMaterial.dispose()}_setSize(A){this._lodMax=Math.floor(Math.log2(A)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){if(this._blurMaterial!==null)this._blurMaterial.dispose();if(this._pingPongRenderTarget!==null)this._pingPongRenderTarget.dispose();for(let A=0;A2?R:0,R,R),E.setRenderTarget(K),F)E.render(N,Y);E.render(A,Y)}N.geometry.dispose(),N.material.dispose(),E.toneMapping=$,E.autoClear=H,A.background=V}_textureToCubeUV(A,Q){let J=this._renderer,K=A.mapping===PQ||A.mapping===Z4;if(K){if(this._cubemapMaterial===null)this._cubemapMaterial=Qb();this._cubemapMaterial.uniforms.flipEnvMap.value=A.isRenderTargetTexture===!1?-1:1}else if(this._equirectMaterial===null)this._equirectMaterial=Ab();let C=K?this._cubemapMaterial:this._equirectMaterial,U=new _0(this._lodPlanes[0],C),Y=C.uniforms;Y.envMap.value=A;let Z=this._cubeSize;HG(Q,0,0,3*Z,2*Z),J.setRenderTarget(Q),J.render(U,XR)}_applyPMREM(A){let Q=this._renderer,J=Q.autoClear;Q.autoClear=!1;let K=this._lodPlanes.length;for(let C=1;CtQ)console.warn(`sigmaRadians, ${C}, is too large and will clip, as it requested ${V} samples when the maximum is set to ${tQ}`);let D=[],L=0;for(let y=0;yR-VC?K-R+VC:0),h=4*(this._cubeSize-M);HG(Q,T,h,3*M,2*M),Z.setRenderTarget(Q),Z.render(H,XR)}}function cQ1(A){let Q=[],J=[],K=[],C=A,U=A-VC+1+ag.length;for(let Y=0;YA-VC)X=ag[Y-A+VC-1];else if(Y===0)X=0;K.push(X);let E=1/(Z-2),H=-E,$=1+E,I=[H,H,$,H,$,$,H,H,$,$,H,$],N=6,F=6,V=3,D=2,L=1,R=new Float32Array(V*F*N),M=new Float32Array(D*F*N),T=new Float32Array(L*F*N);for(let y=0;y2?0:-1,u=[g,f,0,g+0.6666666666666666,f,0,g+0.6666666666666666,f+1,0,g,f,0,g+0.6666666666666666,f+1,0,g,f+1,0];R.set(u,V*F*y),M.set(I,D*F*y);let d=[y,y,y,y,y,y];T.set(d,L*F*y)}let h=new V0;if(h.setAttribute("position",new p0(R,V)),h.setAttribute("uv",new p0(M,D)),h.setAttribute("faceIndex",new p0(T,L)),Q.push(h),C>VC)C--}return{lodPlanes:Q,sizeLods:J,sigmas:K}}function eg(A,Q,J){let K=new s0(A,Q,J);return K.texture.mapping=eK,K.texture.name="PMREM.cubeUv",K.scissorTest=!0,K}function HG(A,Q,J,K,C){A.viewport.set(Q,J,K,C),A.scissor.set(Q,J,K,C)}function dQ1(A,Q,J){let K=new Float32Array(tQ),C=new I1(0,1,0);return new T0({name:"SphericalGaussianBlur",defines:{n:tQ,CUBEUV_TEXEL_WIDTH:1/Q,CUBEUV_TEXEL_HEIGHT:1/J,CUBEUV_MAX_MIP:`${A}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:K},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:C}},vertexShader:qR(),fragmentShader:` - - precision mediump float; - precision mediump int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - uniform int samples; - uniform float weights[ n ]; - uniform bool latitudinal; - uniform float dTheta; - uniform float mipInt; - uniform vec3 poleAxis; - - #define ENVMAP_TYPE_CUBE_UV - #include - - vec3 getSample( float theta, vec3 axis ) { - - float cosTheta = cos( theta ); - // Rodrigues' axis-angle rotation - vec3 sampleDirection = vOutputDirection * cosTheta - + cross( axis, vOutputDirection ) * sin( theta ) - + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); - - return bilinearCubeUV( envMap, sampleDirection, mipInt ); - - } - - void main() { - - vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); - - if ( all( equal( axis, vec3( 0.0 ) ) ) ) { - - axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); - - } - - axis = normalize( axis ); - - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); - - for ( int i = 1; i < n; i++ ) { - - if ( i >= samples ) { - - break; - - } - - float theta = dTheta * float( i ); - gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); - gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); - - } - - } - `,blending:XA,depthTest:!1,depthWrite:!1})}function Ab(){return new T0({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:qR(),fragmentShader:` - - precision mediump float; - precision mediump int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - - #include - - void main() { - - vec3 outputDirection = normalize( vOutputDirection ); - vec2 uv = equirectUv( outputDirection ); - - gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); - - } - `,blending:XA,depthTest:!1,depthWrite:!1})}function Qb(){return new T0({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:qR(),fragmentShader:` - - precision mediump float; - precision mediump int; - - uniform float flipEnvMap; - - varying vec3 vOutputDirection; - - uniform samplerCube envMap; - - void main() { - - gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); - - } - `,blending:XA,depthTest:!1,depthWrite:!1})}function qR(){return` - - precision mediump float; - precision mediump int; - - attribute float faceIndex; - - varying vec3 vOutputDirection; - - // RH coordinate system; PMREM face-indexing convention - vec3 getDirection( vec2 uv, float face ) { - - uv = 2.0 * uv - 1.0; - - vec3 direction = vec3( uv, 1.0 ); - - if ( face == 0.0 ) { - - direction = direction.zyx; // ( 1, v, u ) pos x - - } else if ( face == 1.0 ) { - - direction = direction.xzy; - direction.xz *= -1.0; // ( -u, 1, -v ) pos y - - } else if ( face == 2.0 ) { - - direction.x *= -1.0; // ( -u, v, 1 ) pos z - - } else if ( face == 3.0 ) { - - direction = direction.zyx; - direction.xz *= -1.0; // ( -1, v, -u ) neg x - - } else if ( face == 4.0 ) { - - direction = direction.xzy; - direction.xy *= -1.0; // ( -u, -1, v ) neg y - - } else if ( face == 5.0 ) { - - direction.z *= -1.0; // ( u, v, -1 ) neg z - - } - - return direction; - - } - - void main() { - - vOutputDirection = getDirection( uv, faceIndex ); - gl_Position = vec4( position, 1.0 ); - - } - `}function lQ1(A){let Q=/*@__PURE__*/new WeakMap,J=null;function K(Z){if(Z&&Z.isTexture){let X=Z.mapping,E=X===_Q||X===tK,H=X===PQ||X===Z4;if(E||H){let $=Q.get(Z),I=$!==void 0?$.texture.pmremVersion:0;if(Z.isRenderTargetTexture&&Z.pmremVersion!==I){if(J===null)J=new WG(A);return $=E?J.fromEquirectangular(Z,$):J.fromCubemap(Z,$),$.texture.pmremVersion=Z.pmremVersion,Q.set(Z,$),$.texture}else if($!==void 0)return $.texture;else{let N=Z.image;if(E&&N&&N.height>0||H&&N&&C(N)){if(J===null)J=new WG(A);return $=E?J.fromEquirectangular(Z):J.fromCubemap(Z),$.texture.pmremVersion=Z.pmremVersion,Q.set(Z,$),Z.addEventListener("dispose",U),$.texture}else return null}}}return Z}function C(Z){let X=0,E=6;for(let H=0;HQ.maxTextureSize)h=Math.ceil(T/Q.maxTextureSize),T=Q.maxTextureSize;let y=new Float32Array(T*h*4*$),g=new pQ(y,T,h,$);g.type=aA,g.needsUpdate=!0;let f=M*4;for(let d=0;d<$;d++){let n=D[d],B=L[d],q=R[d],P=T*h*4*d;for(let O=0;O0)return A;let C=Q*J,U=Kb[C];if(U===void 0)U=new Float32Array(C),Kb[C]=U;if(Q!==0){K.toArray(U,0);for(let Y=1,Z=0;Y!==Q;++Y)Z+=J,A[Y].toArray(U,Z)}return U}function z8(A,Q){if(A.length!==Q.length)return!1;for(let J=0,K=A.length;J":" "} ${Z}: ${J[Y]}`)}return K.join(` -`)}var Eb=/*@__PURE__*/new a0;function mJ1(A){e0._getMatrix(Eb,e0.workingColorSpace,A);let Q=`mat3( ${Eb.elements.map((J)=>J.toFixed(4))} )`;switch(e0.getTransfer(A)){case YZ:return[Q,"LinearTransferOETF"];case L2:return[Q,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",A),[Q,"LinearTransferOETF"]}}function $b(A,Q,J){let K=A.getShaderParameter(Q,A.COMPILE_STATUS),C=A.getShaderInfoLog(Q).trim();if(K&&C==="")return"";let U=/ERROR: 0:(\d+)/.exec(C);if(U){let Y=parseInt(U[1]);return J.toUpperCase()+` - -`+C+` - -`+uJ1(A.getShaderSource(Q),Y)}else return C}function cJ1(A,Q){let J=mJ1(Q);return[`vec4 ${A}( vec4 value ) {`,` return ${J[1]}( vec4( value.rgb * ${J[0]}, value.a ) );`,"}"].join(` -`)}function dJ1(A,Q){let J;switch(Q){case KH:J="Linear";break;case CH:J="Reinhard";break;case YH:J="Cineon";break;case UH:J="ACESFilmic";break;case BH:J="AgX";break;case XH:J="Neutral";break;case ZH:J="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",Q),J="Linear"}return"vec3 "+A+"( vec3 color ) { return "+J+"ToneMapping( color ); }"}var GG=/*@__PURE__*/new I1;function lJ1(){e0.getLuminanceCoefficients(GG);let A=GG.x.toFixed(4),Q=GG.y.toFixed(4),J=GG.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${A}, ${Q}, ${J} );`,"\treturn dot( weights, rgb );","}"].join(` -`)}function nJ1(A){return[A.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",A.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(bZ).join(` -`)}function sJ1(A){let Q=[];for(let J in A){let K=A[J];if(K===!1)continue;Q.push("#define "+J+" "+K)}return Q.join(` -`)}function oJ1(A,Q){let J={},K=A.getProgramParameter(Q,A.ACTIVE_ATTRIBUTES);for(let C=0;C/gm;function IR(A){return A.replace(iJ1,rJ1)}var aJ1=/*@__PURE__*/new Map;function rJ1(A,Q){let J=$A[Q];if(J===void 0){let K=aJ1.get(Q);if(K!==void 0)J=$A[K],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',Q,K);else throw new Error("Can not resolve #include <"+Q+">")}return IR(J)}var tJ1=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Wb(A){return A.replace(tJ1,eJ1)}function eJ1(A,Q,J,K){let C="";for(let U=parseInt(Q);U0)D+=` -`;if(L=["#define SHADER_TYPE "+J.shaderType,"#define SHADER_NAME "+J.shaderName,F].filter(bZ).join(` -`),L.length>0)L+=` -`}else D=[Ib(J),"#define SHADER_TYPE "+J.shaderType,"#define SHADER_NAME "+J.shaderName,F,J.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",J.batching?"#define USE_BATCHING":"",J.batchingColor?"#define USE_BATCHING_COLOR":"",J.instancing?"#define USE_INSTANCING":"",J.instancingColor?"#define USE_INSTANCING_COLOR":"",J.instancingMorph?"#define USE_INSTANCING_MORPH":"",J.useFog&&J.fog?"#define USE_FOG":"",J.useFog&&J.fogExp2?"#define FOG_EXP2":"",J.map?"#define USE_MAP":"",J.envMap?"#define USE_ENVMAP":"",J.envMap?"#define "+H:"",J.lightMap?"#define USE_LIGHTMAP":"",J.aoMap?"#define USE_AOMAP":"",J.bumpMap?"#define USE_BUMPMAP":"",J.normalMap?"#define USE_NORMALMAP":"",J.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",J.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",J.displacementMap?"#define USE_DISPLACEMENTMAP":"",J.emissiveMap?"#define USE_EMISSIVEMAP":"",J.anisotropy?"#define USE_ANISOTROPY":"",J.anisotropyMap?"#define USE_ANISOTROPYMAP":"",J.clearcoatMap?"#define USE_CLEARCOATMAP":"",J.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",J.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",J.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",J.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",J.specularMap?"#define USE_SPECULARMAP":"",J.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",J.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",J.roughnessMap?"#define USE_ROUGHNESSMAP":"",J.metalnessMap?"#define USE_METALNESSMAP":"",J.alphaMap?"#define USE_ALPHAMAP":"",J.alphaHash?"#define USE_ALPHAHASH":"",J.transmission?"#define USE_TRANSMISSION":"",J.transmissionMap?"#define USE_TRANSMISSIONMAP":"",J.thicknessMap?"#define USE_THICKNESSMAP":"",J.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",J.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",J.mapUv?"#define MAP_UV "+J.mapUv:"",J.alphaMapUv?"#define ALPHAMAP_UV "+J.alphaMapUv:"",J.lightMapUv?"#define LIGHTMAP_UV "+J.lightMapUv:"",J.aoMapUv?"#define AOMAP_UV "+J.aoMapUv:"",J.emissiveMapUv?"#define EMISSIVEMAP_UV "+J.emissiveMapUv:"",J.bumpMapUv?"#define BUMPMAP_UV "+J.bumpMapUv:"",J.normalMapUv?"#define NORMALMAP_UV "+J.normalMapUv:"",J.displacementMapUv?"#define DISPLACEMENTMAP_UV "+J.displacementMapUv:"",J.metalnessMapUv?"#define METALNESSMAP_UV "+J.metalnessMapUv:"",J.roughnessMapUv?"#define ROUGHNESSMAP_UV "+J.roughnessMapUv:"",J.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+J.anisotropyMapUv:"",J.clearcoatMapUv?"#define CLEARCOATMAP_UV "+J.clearcoatMapUv:"",J.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+J.clearcoatNormalMapUv:"",J.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+J.clearcoatRoughnessMapUv:"",J.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+J.iridescenceMapUv:"",J.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+J.iridescenceThicknessMapUv:"",J.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+J.sheenColorMapUv:"",J.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+J.sheenRoughnessMapUv:"",J.specularMapUv?"#define SPECULARMAP_UV "+J.specularMapUv:"",J.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+J.specularColorMapUv:"",J.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+J.specularIntensityMapUv:"",J.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+J.transmissionMapUv:"",J.thicknessMapUv?"#define THICKNESSMAP_UV "+J.thicknessMapUv:"",J.vertexTangents&&J.flatShading===!1?"#define USE_TANGENT":"",J.vertexColors?"#define USE_COLOR":"",J.vertexAlphas?"#define USE_COLOR_ALPHA":"",J.vertexUv1s?"#define USE_UV1":"",J.vertexUv2s?"#define USE_UV2":"",J.vertexUv3s?"#define USE_UV3":"",J.pointsUvs?"#define USE_POINTS_UV":"",J.flatShading?"#define FLAT_SHADED":"",J.skinning?"#define USE_SKINNING":"",J.morphTargets?"#define USE_MORPHTARGETS":"",J.morphNormals&&J.flatShading===!1?"#define USE_MORPHNORMALS":"",J.morphColors?"#define USE_MORPHCOLORS":"",J.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+J.morphTextureStride:"",J.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+J.morphTargetsCount:"",J.doubleSided?"#define DOUBLE_SIDED":"",J.flipSided?"#define FLIP_SIDED":"",J.shadowMapEnabled?"#define USE_SHADOWMAP":"",J.shadowMapEnabled?"#define "+X:"",J.sizeAttenuation?"#define USE_SIZEATTENUATION":"",J.numLightProbes>0?"#define USE_LIGHT_PROBES":"",J.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",J.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif",` -`].filter(bZ).join(` -`),L=[Ib(J),"#define SHADER_TYPE "+J.shaderType,"#define SHADER_NAME "+J.shaderName,F,J.useFog&&J.fog?"#define USE_FOG":"",J.useFog&&J.fogExp2?"#define FOG_EXP2":"",J.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",J.map?"#define USE_MAP":"",J.matcap?"#define USE_MATCAP":"",J.envMap?"#define USE_ENVMAP":"",J.envMap?"#define "+E:"",J.envMap?"#define "+H:"",J.envMap?"#define "+$:"",I?"#define CUBEUV_TEXEL_WIDTH "+I.texelWidth:"",I?"#define CUBEUV_TEXEL_HEIGHT "+I.texelHeight:"",I?"#define CUBEUV_MAX_MIP "+I.maxMip+".0":"",J.lightMap?"#define USE_LIGHTMAP":"",J.aoMap?"#define USE_AOMAP":"",J.bumpMap?"#define USE_BUMPMAP":"",J.normalMap?"#define USE_NORMALMAP":"",J.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",J.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",J.emissiveMap?"#define USE_EMISSIVEMAP":"",J.anisotropy?"#define USE_ANISOTROPY":"",J.anisotropyMap?"#define USE_ANISOTROPYMAP":"",J.clearcoat?"#define USE_CLEARCOAT":"",J.clearcoatMap?"#define USE_CLEARCOATMAP":"",J.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",J.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",J.dispersion?"#define USE_DISPERSION":"",J.iridescence?"#define USE_IRIDESCENCE":"",J.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",J.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",J.specularMap?"#define USE_SPECULARMAP":"",J.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",J.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",J.roughnessMap?"#define USE_ROUGHNESSMAP":"",J.metalnessMap?"#define USE_METALNESSMAP":"",J.alphaMap?"#define USE_ALPHAMAP":"",J.alphaTest?"#define USE_ALPHATEST":"",J.alphaHash?"#define USE_ALPHAHASH":"",J.sheen?"#define USE_SHEEN":"",J.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",J.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",J.transmission?"#define USE_TRANSMISSION":"",J.transmissionMap?"#define USE_TRANSMISSIONMAP":"",J.thicknessMap?"#define USE_THICKNESSMAP":"",J.vertexTangents&&J.flatShading===!1?"#define USE_TANGENT":"",J.vertexColors||J.instancingColor||J.batchingColor?"#define USE_COLOR":"",J.vertexAlphas?"#define USE_COLOR_ALPHA":"",J.vertexUv1s?"#define USE_UV1":"",J.vertexUv2s?"#define USE_UV2":"",J.vertexUv3s?"#define USE_UV3":"",J.pointsUvs?"#define USE_POINTS_UV":"",J.gradientMap?"#define USE_GRADIENTMAP":"",J.flatShading?"#define FLAT_SHADED":"",J.doubleSided?"#define DOUBLE_SIDED":"",J.flipSided?"#define FLIP_SIDED":"",J.shadowMapEnabled?"#define USE_SHADOWMAP":"",J.shadowMapEnabled?"#define "+X:"",J.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",J.numLightProbes>0?"#define USE_LIGHT_PROBES":"",J.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",J.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",J.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",J.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",J.toneMapping!==i5?"#define TONE_MAPPING":"",J.toneMapping!==i5?$A.tonemapping_pars_fragment:"",J.toneMapping!==i5?dJ1("toneMapping",J.toneMapping):"",J.dithering?"#define DITHERING":"",J.opaque?"#define OPAQUE":"",$A.colorspace_pars_fragment,cJ1("linearToOutputTexel",J.outputColorSpace),lJ1(),J.useDepthPacking?"#define DEPTH_PACKING "+J.depthPacking:"",` -`].filter(bZ).join(` -`);if(Y=IR(Y),Y=Hb(Y,J),Y=Gb(Y,J),Z=IR(Z),Z=Hb(Z,J),Z=Gb(Z,J),Y=Wb(Y),Z=Wb(Z),J.isRawShaderMaterial!==!0)R=`#version 300 es -`,D=[N,"#define attribute in","#define varying out","#define texture2D texture"].join(` -`)+` -`+D,L=["#define varying in",J.glslVersion===SH?"":"layout(location = 0) out highp vec4 pc_fragColor;",J.glslVersion===SH?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` -`)+` -`+L;let M=R+D+Y,T=R+L+Z,h=Xb(C,C.VERTEX_SHADER,M),y=Xb(C,C.FRAGMENT_SHADER,T);if(C.attachShader(V,h),C.attachShader(V,y),J.index0AttributeName!==void 0)C.bindAttribLocation(V,0,J.index0AttributeName);else if(J.morphTargets===!0)C.bindAttribLocation(V,0,"position");C.linkProgram(V);function g(n){if(A.debug.checkShaderErrors){let B=C.getProgramInfoLog(V).trim(),q=C.getShaderInfoLog(h).trim(),P=C.getShaderInfoLog(y).trim(),O=!0,w=!0;if(C.getProgramParameter(V,C.LINK_STATUS)===!1)if(O=!1,typeof A.debug.onShaderError==="function")A.debug.onShaderError(C,V,h,y);else{let k=$b(C,h,"vertex"),S=$b(C,y,"fragment");console.error("THREE.WebGLProgram: Shader Error "+C.getError()+" - VALIDATE_STATUS "+C.getProgramParameter(V,C.VALIDATE_STATUS)+` - -Material Name: `+n.name+` -Material Type: `+n.type+` - -Program Info Log: `+B+` -`+k+` -`+S)}else if(B!=="")console.warn("THREE.WebGLProgram: Program Info Log:",B);else if(q===""||P==="")w=!1;if(w)n.diagnostics={runnable:O,programLog:B,vertexShader:{log:q,prefix:D},fragmentShader:{log:P,prefix:L}}}C.deleteShader(h),C.deleteShader(y),f=new fZ(C,V),u=oJ1(C,V)}let f;this.getUniforms=function(){if(f===void 0)g(this);return f};let u;this.getAttributes=function(){if(u===void 0)g(this);return u};let d=J.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){if(d===!1)d=C.getProgramParameter(V,fJ1);return d},this.destroy=function(){K.releaseStatesOfProgram(this),C.deleteProgram(V),this.program=void 0},this.type=J.shaderType,this.name=J.shaderName,this.id=pJ1++,this.cacheKey=Q,this.usedTimes=1,this.program=V,this.vertexShader=h,this.fragmentShader=y,this}var UK1=0;class Pb{constructor(){this.shaderCache=/*@__PURE__*/new Map,this.materialCache=/*@__PURE__*/new Map}update(A){let{vertexShader:Q,fragmentShader:J}=A,K=this._getShaderStage(Q),C=this._getShaderStage(J),U=this._getShaderCacheForMaterial(A);if(U.has(K)===!1)U.add(K),K.usedTimes++;if(U.has(C)===!1)U.add(C),C.usedTimes++;return this}remove(A){let Q=this.materialCache.get(A);for(let J of Q)if(J.usedTimes--,J.usedTimes===0)this.shaderCache.delete(J.code);return this.materialCache.delete(A),this}getVertexShaderID(A){return this._getShaderStage(A.vertexShader).id}getFragmentShaderID(A){return this._getShaderStage(A.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(A){let Q=this.materialCache,J=Q.get(A);if(J===void 0)J=/*@__PURE__*/new Set,Q.set(A,J);return J}_getShaderStage(A){let Q=this.shaderCache,J=Q.get(A);if(J===void 0)J=new _b(A),Q.set(A,J);return J}}class _b{constructor(A){this.id=UK1++,this.code=A,this.usedTimes=0}}function ZK1(A,Q,J,K,C,U,Y){let Z=new uQ,X=new Pb,E=/*@__PURE__*/new Set,H=[],$=C.logarithmicDepthBuffer,I=C.vertexTextures,N=C.precision,F={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function V(u){if(E.add(u),u===0)return"uv";return`uv${u}`}function D(u,d,n,B,q){let P=B.fog,O=q.geometry,w=u.isMeshStandardMaterial?B.environment:null,k=(u.isMeshStandardMaterial?J:Q).get(u.envMap||w),S=!!k&&k.mapping===eK?k.image.height:null,_=F[u.type];if(u.precision!==null){if(N=C.getMaxPrecision(u.precision),N!==u.precision)console.warn("THREE.WebGLProgram.getParameters:",u.precision,"not supported, using",N,"instead.")}let W=O.morphAttributes.position||O.morphAttributes.normal||O.morphAttributes.color,j=W!==void 0?W.length:0,b=0;if(O.morphAttributes.position!==void 0)b=1;if(O.morphAttributes.normal!==void 0)b=2;if(O.morphAttributes.color!==void 0)b=3;let p,s,r,A1;if(_){let h1=$6[_];p=h1.vertexShader,s=h1.fragmentShader}else p=u.vertexShader,s=u.fragmentShader,X.update(u),r=X.getVertexShaderID(u),A1=X.getFragmentShaderID(u);let Q1=A.getRenderTarget(),e=A.state.buffers.depth.getReversed(),t=q.isInstancedMesh===!0,U1=q.isBatchedMesh===!0,O1=!!u.map,E1=!!u.matcap,Y1=!!k,i=!!u.aoMap,c=!!u.lightMap,o=!!u.bumpMap,C1=!!u.normalMap,q1=!!u.displacementMap,Z1=!!u.emissiveMap,j1=!!u.metalnessMap,H1=!!u.roughnessMap,B1=u.anisotropy>0,k1=u.clearcoat>0,D1=u.dispersion>0,G1=u.iridescence>0,w1=u.sheen>0,G=u.transmission>0,z=B1&&!!u.anisotropyMap,x=k1&&!!u.clearcoatMap,m=k1&&!!u.clearcoatNormalMap,l=k1&&!!u.clearcoatRoughnessMap,a=G1&&!!u.iridescenceMap,K1=G1&&!!u.iridescenceThicknessMap,F1=w1&&!!u.sheenColorMap,R1=w1&&!!u.sheenRoughnessMap,X1=!!u.specularMap,W1=!!u.specularColorMap,$1=!!u.specularIntensityMap,N1=G&&!!u.transmissionMap,_1=G&&!!u.thicknessMap,J1=!!u.gradientMap,z1=!!u.alphaMap,M1=u.alphaTest>0,L1=!!u.alphaHash,V1=!!u.extensions,S1=i5;if(u.toneMapped){if(Q1===null||Q1.isXRRenderTarget===!0)S1=A.toneMapping}let O0={shaderID:_,shaderType:u.type,shaderName:u.name,vertexShader:p,fragmentShader:s,defines:u.defines,customVertexShaderID:r,customFragmentShaderID:A1,isRawShaderMaterial:u.isRawShaderMaterial===!0,glslVersion:u.glslVersion,precision:N,batching:U1,batchingColor:U1&&q._colorsTexture!==null,instancing:t,instancingColor:t&&q.instanceColor!==null,instancingMorph:t&&q.morphTexture!==null,supportsVertexTextures:I,outputColorSpace:Q1===null?A.outputColorSpace:Q1.isXRRenderTarget===!0?Q1.texture.colorSpace:GA,alphaToCoverage:!!u.alphaToCoverage,map:O1,matcap:E1,envMap:Y1,envMapMode:Y1&&k.mapping,envMapCubeUVHeight:S,aoMap:i,lightMap:c,bumpMap:o,normalMap:C1,displacementMap:I&&q1,emissiveMap:Z1,normalMapObjectSpace:C1&&u.normalMapType===OF,normalMapTangentSpace:C1&&u.normalMapType===qF,metalnessMap:j1,roughnessMap:H1,anisotropy:B1,anisotropyMap:z,clearcoat:k1,clearcoatMap:x,clearcoatNormalMap:m,clearcoatRoughnessMap:l,dispersion:D1,iridescence:G1,iridescenceMap:a,iridescenceThicknessMap:K1,sheen:w1,sheenColorMap:F1,sheenRoughnessMap:R1,specularMap:X1,specularColorMap:W1,specularIntensityMap:$1,transmission:G,transmissionMap:N1,thicknessMap:_1,gradientMap:J1,opaque:u.transparent===!1&&u.blending===s5&&u.alphaToCoverage===!1,alphaMap:z1,alphaTest:M1,alphaHash:L1,combine:u.combine,mapUv:O1&&V(u.map.channel),aoMapUv:i&&V(u.aoMap.channel),lightMapUv:c&&V(u.lightMap.channel),bumpMapUv:o&&V(u.bumpMap.channel),normalMapUv:C1&&V(u.normalMap.channel),displacementMapUv:q1&&V(u.displacementMap.channel),emissiveMapUv:Z1&&V(u.emissiveMap.channel),metalnessMapUv:j1&&V(u.metalnessMap.channel),roughnessMapUv:H1&&V(u.roughnessMap.channel),anisotropyMapUv:z&&V(u.anisotropyMap.channel),clearcoatMapUv:x&&V(u.clearcoatMap.channel),clearcoatNormalMapUv:m&&V(u.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:l&&V(u.clearcoatRoughnessMap.channel),iridescenceMapUv:a&&V(u.iridescenceMap.channel),iridescenceThicknessMapUv:K1&&V(u.iridescenceThicknessMap.channel),sheenColorMapUv:F1&&V(u.sheenColorMap.channel),sheenRoughnessMapUv:R1&&V(u.sheenRoughnessMap.channel),specularMapUv:X1&&V(u.specularMap.channel),specularColorMapUv:W1&&V(u.specularColorMap.channel),specularIntensityMapUv:$1&&V(u.specularIntensityMap.channel),transmissionMapUv:N1&&V(u.transmissionMap.channel),thicknessMapUv:_1&&V(u.thicknessMap.channel),alphaMapUv:z1&&V(u.alphaMap.channel),vertexTangents:!!O.attributes.tangent&&(C1||B1),vertexColors:u.vertexColors,vertexAlphas:u.vertexColors===!0&&!!O.attributes.color&&O.attributes.color.itemSize===4,pointsUvs:q.isPoints===!0&&!!O.attributes.uv&&(O1||z1),fog:!!P,useFog:u.fog===!0,fogExp2:!!P&&P.isFogExp2,flatShading:u.flatShading===!0,sizeAttenuation:u.sizeAttenuation===!0,logarithmicDepthBuffer:$,reverseDepthBuffer:e,skinning:q.isSkinnedMesh===!0,morphTargets:O.morphAttributes.position!==void 0,morphNormals:O.morphAttributes.normal!==void 0,morphColors:O.morphAttributes.color!==void 0,morphTargetsCount:j,morphTextureStride:b,numDirLights:d.directional.length,numPointLights:d.point.length,numSpotLights:d.spot.length,numSpotLightMaps:d.spotLightMap.length,numRectAreaLights:d.rectArea.length,numHemiLights:d.hemi.length,numDirLightShadows:d.directionalShadowMap.length,numPointLightShadows:d.pointShadowMap.length,numSpotLightShadows:d.spotShadowMap.length,numSpotLightShadowsWithMaps:d.numSpotLightShadowsWithMaps,numLightProbes:d.numLightProbes,numClippingPlanes:Y.numPlanes,numClipIntersection:Y.numIntersection,dithering:u.dithering,shadowMapEnabled:A.shadowMap.enabled&&n.length>0,shadowMapType:A.shadowMap.type,toneMapping:S1,decodeVideoTexture:O1&&u.map.isVideoTexture===!0&&e0.getTransfer(u.map.colorSpace)===L2,decodeVideoTextureEmissive:Z1&&u.emissiveMap.isVideoTexture===!0&&e0.getTransfer(u.emissiveMap.colorSpace)===L2,premultipliedAlpha:u.premultipliedAlpha,doubleSided:u.side===VA,flipSided:u.side===w2,useDepthPacking:u.depthPacking>=0,depthPacking:u.depthPacking||0,index0AttributeName:u.index0AttributeName,extensionClipCullDistance:V1&&u.extensions.clipCullDistance===!0&&K.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(V1&&u.extensions.multiDraw===!0||U1)&&K.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:K.has("KHR_parallel_shader_compile"),customProgramCacheKey:u.customProgramCacheKey()};return O0.vertexUv1s=E.has(1),O0.vertexUv2s=E.has(2),O0.vertexUv3s=E.has(3),E.clear(),O0}function L(u){let d=[];if(u.shaderID)d.push(u.shaderID);else d.push(u.customVertexShaderID),d.push(u.customFragmentShaderID);if(u.defines!==void 0)for(let n in u.defines)d.push(n),d.push(u.defines[n]);if(u.isRawShaderMaterial===!1)R(d,u),M(d,u),d.push(A.outputColorSpace);return d.push(u.customProgramCacheKey),d.join()}function R(u,d){u.push(d.precision),u.push(d.outputColorSpace),u.push(d.envMapMode),u.push(d.envMapCubeUVHeight),u.push(d.mapUv),u.push(d.alphaMapUv),u.push(d.lightMapUv),u.push(d.aoMapUv),u.push(d.bumpMapUv),u.push(d.normalMapUv),u.push(d.displacementMapUv),u.push(d.emissiveMapUv),u.push(d.metalnessMapUv),u.push(d.roughnessMapUv),u.push(d.anisotropyMapUv),u.push(d.clearcoatMapUv),u.push(d.clearcoatNormalMapUv),u.push(d.clearcoatRoughnessMapUv),u.push(d.iridescenceMapUv),u.push(d.iridescenceThicknessMapUv),u.push(d.sheenColorMapUv),u.push(d.sheenRoughnessMapUv),u.push(d.specularMapUv),u.push(d.specularColorMapUv),u.push(d.specularIntensityMapUv),u.push(d.transmissionMapUv),u.push(d.thicknessMapUv),u.push(d.combine),u.push(d.fogExp2),u.push(d.sizeAttenuation),u.push(d.morphTargetsCount),u.push(d.morphAttributeCount),u.push(d.numDirLights),u.push(d.numPointLights),u.push(d.numSpotLights),u.push(d.numSpotLightMaps),u.push(d.numHemiLights),u.push(d.numRectAreaLights),u.push(d.numDirLightShadows),u.push(d.numPointLightShadows),u.push(d.numSpotLightShadows),u.push(d.numSpotLightShadowsWithMaps),u.push(d.numLightProbes),u.push(d.shadowMapType),u.push(d.toneMapping),u.push(d.numClippingPlanes),u.push(d.numClipIntersection),u.push(d.depthPacking)}function M(u,d){if(Z.disableAll(),d.supportsVertexTextures)Z.enable(0);if(d.instancing)Z.enable(1);if(d.instancingColor)Z.enable(2);if(d.instancingMorph)Z.enable(3);if(d.matcap)Z.enable(4);if(d.envMap)Z.enable(5);if(d.normalMapObjectSpace)Z.enable(6);if(d.normalMapTangentSpace)Z.enable(7);if(d.clearcoat)Z.enable(8);if(d.iridescence)Z.enable(9);if(d.alphaTest)Z.enable(10);if(d.vertexColors)Z.enable(11);if(d.vertexAlphas)Z.enable(12);if(d.vertexUv1s)Z.enable(13);if(d.vertexUv2s)Z.enable(14);if(d.vertexUv3s)Z.enable(15);if(d.vertexTangents)Z.enable(16);if(d.anisotropy)Z.enable(17);if(d.alphaHash)Z.enable(18);if(d.batching)Z.enable(19);if(d.dispersion)Z.enable(20);if(d.batchingColor)Z.enable(21);if(u.push(Z.mask),Z.disableAll(),d.fog)Z.enable(0);if(d.useFog)Z.enable(1);if(d.flatShading)Z.enable(2);if(d.logarithmicDepthBuffer)Z.enable(3);if(d.reverseDepthBuffer)Z.enable(4);if(d.skinning)Z.enable(5);if(d.morphTargets)Z.enable(6);if(d.morphNormals)Z.enable(7);if(d.morphColors)Z.enable(8);if(d.premultipliedAlpha)Z.enable(9);if(d.shadowMapEnabled)Z.enable(10);if(d.doubleSided)Z.enable(11);if(d.flipSided)Z.enable(12);if(d.useDepthPacking)Z.enable(13);if(d.dithering)Z.enable(14);if(d.transmission)Z.enable(15);if(d.sheen)Z.enable(16);if(d.opaque)Z.enable(17);if(d.pointsUvs)Z.enable(18);if(d.decodeVideoTexture)Z.enable(19);if(d.decodeVideoTextureEmissive)Z.enable(20);if(d.alphaToCoverage)Z.enable(21);u.push(Z.mask)}function T(u){let d=F[u.type],n;if(d){let B=$6[d];n=u0.clone(B.uniforms)}else n=u.uniforms;return n}function h(u,d){let n;for(let B=0,q=H.length;B0)K.push(L);else if(N.transparent===!0)C.push(L);else J.push(L)}function X($,I,N,F,V,D){let L=Y($,I,N,F,V,D);if(N.transmission>0)K.unshift(L);else if(N.transparent===!0)C.unshift(L);else J.unshift(L)}function E($,I){if(J.length>1)J.sort($||XK1);if(K.length>1)K.sort(I||qb);if(C.length>1)C.sort(I||qb)}function H(){for(let $=Q,I=A.length;$=U.length)Y=new Ob,U.push(Y);else Y=U[C];return Y}function J(){A=/*@__PURE__*/new WeakMap}return{get:Q,dispose:J}}function $K1(){let A={};return{get:function(Q){if(A[Q.id]!==void 0)return A[Q.id];let J;switch(Q.type){case"DirectionalLight":J={direction:new I1,color:new y1};break;case"SpotLight":J={position:new I1,direction:new I1,color:new y1,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":J={position:new I1,color:new y1,distance:0,decay:0};break;case"HemisphereLight":J={direction:new I1,skyColor:new y1,groundColor:new y1};break;case"RectAreaLight":J={color:new y1,position:new I1,halfWidth:new I1,halfHeight:new I1};break}return A[Q.id]=J,J}}}function HK1(){let A={};return{get:function(Q){if(A[Q.id]!==void 0)return A[Q.id];let J;switch(Q.type){case"DirectionalLight":J={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new p1};break;case"SpotLight":J={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new p1};break;case"PointLight":J={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new p1,shadowCameraNear:1,shadowCameraFar:1000};break}return A[Q.id]=J,J}}}var GK1=0;function WK1(A,Q){return(Q.castShadow?2:0)-(A.castShadow?2:0)+(Q.map?1:0)-(A.map?1:0)}function IK1(A){let Q=new $K1,J=HK1(),K={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let E=0;E<9;E++)K.probe.push(new I1);let C=new I1,U=new Y0,Y=new Y0;function Z(E){let H=0,$=0,I=0;for(let u=0;u<9;u++)K.probe[u].set(0,0,0);let N=0,F=0,V=0,D=0,L=0,R=0,M=0,T=0,h=0,y=0,g=0;E.sort(WK1);for(let u=0,d=E.length;u0)if(A.has("OES_texture_float_linear")===!0)K.rectAreaLTC1=M0.LTC_FLOAT_1,K.rectAreaLTC2=M0.LTC_FLOAT_2;else K.rectAreaLTC1=M0.LTC_HALF_1,K.rectAreaLTC2=M0.LTC_HALF_2;K.ambient[0]=H,K.ambient[1]=$,K.ambient[2]=I;let f=K.hash;if(f.directionalLength!==N||f.pointLength!==F||f.spotLength!==V||f.rectAreaLength!==D||f.hemiLength!==L||f.numDirectionalShadows!==R||f.numPointShadows!==M||f.numSpotShadows!==T||f.numSpotMaps!==h||f.numLightProbes!==g)K.directional.length=N,K.spot.length=V,K.rectArea.length=D,K.point.length=F,K.hemi.length=L,K.directionalShadow.length=R,K.directionalShadowMap.length=R,K.pointShadow.length=M,K.pointShadowMap.length=M,K.spotShadow.length=T,K.spotShadowMap.length=T,K.directionalShadowMatrix.length=R,K.pointShadowMatrix.length=M,K.spotLightMatrix.length=T+h-y,K.spotLightMap.length=h,K.numSpotLightShadowsWithMaps=y,K.numLightProbes=g,f.directionalLength=N,f.pointLength=F,f.spotLength=V,f.rectAreaLength=D,f.hemiLength=L,f.numDirectionalShadows=R,f.numPointShadows=M,f.numSpotShadows=T,f.numSpotMaps=h,f.numLightProbes=g,K.version=GK1++}function X(E,H){let $=0,I=0,N=0,F=0,V=0,D=H.matrixWorldInverse;for(let L=0,R=E.length;L=Y.length)Z=new Nb(A),Y.push(Z);else Z=Y[U];return Z}function K(){Q=/*@__PURE__*/new WeakMap}return{get:J,dispose:K}}var OK1=`void main() { - gl_Position = vec4( position, 1.0 ); -}`,NK1=`uniform sampler2D shadow_pass; -uniform vec2 resolution; -uniform float radius; -#include -void main() { - const float samples = float( VSM_SAMPLES ); - float mean = 0.0; - float squared_mean = 0.0; - float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); - float uvStart = samples <= 1.0 ? 0.0 : - 1.0; - for ( float i = 0.0; i < samples; i ++ ) { - float uvOffset = uvStart + i * uvStride; - #ifdef HORIZONTAL_PASS - vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); - mean += distribution.x; - squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; - #else - float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); - mean += depth; - squared_mean += depth * depth; - #endif - } - mean = mean / samples; - squared_mean = squared_mean / samples; - float std_dev = sqrt( squared_mean - mean * mean ); - gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); -}`;function LK1(A,Q,J){let K=new Q3,C=new p1,U=new p1,Y=new X0,Z=new G4({depthPacking:CC}),X=new PZ,E={},H=J.maxTextureSize,$={[M2]:w2,[w2]:M2,[VA]:VA},I=new T0({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new p1},radius:{value:4}},vertexShader:OK1,fragmentShader:NK1}),N=I.clone();N.defines.HORIZONTAL_PASS=1;let F=new V0;F.setAttribute("position",new p0(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));let V=new _0(F,I),D=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=t$;let L=this.type;this.render=function(y,g,f){if(D.enabled===!1)return;if(D.autoUpdate===!1&&D.needsUpdate===!1)return;if(y.length===0)return;let u=A.getRenderTarget(),d=A.getActiveCubeFace(),n=A.getActiveMipmapLevel(),B=A.state;B.setBlending(XA),B.buffers.color.setClear(1,1,1,1),B.buffers.depth.setTest(!0),B.setScissorTest(!1);let q=L!==W5&&this.type===W5,P=L===W5&&this.type!==W5;for(let O=0,w=y.length;OH||C.y>H){if(C.x>H)U.x=Math.floor(H/_.x),C.x=U.x*_.x,S.mapSize.x=U.x;if(C.y>H)U.y=Math.floor(H/_.y),C.y=U.y*_.y,S.mapSize.y=U.y}if(S.map===null||q===!0||P===!0){let j=this.type!==W5?{minFilter:YA,magFilter:YA}:{};if(S.map!==null)S.map.dispose();S.map=new s0(C.x,C.y,j),S.map.texture.name=k.name+".shadowMap",S.camera.updateProjectionMatrix()}A.setRenderTarget(S.map),A.clear();let W=S.getViewportCount();for(let j=0;j0||g.map&&g.alphaTest>0){let B=d.uuid,q=g.uuid,P=E[B];if(P===void 0)P={},E[B]=P;let O=P[q];if(O===void 0)O=d.clone(),P[q]=O,g.addEventListener("dispose",h);d=O}if(d.visible=g.visible,d.wireframe=g.wireframe,u===W5)d.side=g.shadowSide!==null?g.shadowSide:g.side;else d.side=g.shadowSide!==null?g.shadowSide:$[g.side];if(d.alphaMap=g.alphaMap,d.alphaTest=g.alphaTest,d.map=g.map,d.clipShadows=g.clipShadows,d.clippingPlanes=g.clippingPlanes,d.clipIntersection=g.clipIntersection,d.displacementMap=g.displacementMap,d.displacementScale=g.displacementScale,d.displacementBias=g.displacementBias,d.wireframeLinewidth=g.wireframeLinewidth,d.linewidth=g.linewidth,f.isPointLight===!0&&d.isMeshDistanceMaterial===!0){let B=A.properties.get(d);B.light=f}return d}function T(y,g,f,u,d){if(y.visible===!1)return;if(y.layers.test(g.layers)&&(y.isMesh||y.isLine||y.isPoints)){if((y.castShadow||y.receiveShadow&&d===W5)&&(!y.frustumCulled||K.intersectsObject(y))){y.modelViewMatrix.multiplyMatrices(f.matrixWorldInverse,y.matrixWorld);let q=Q.update(y),P=y.material;if(Array.isArray(P)){let O=q.groups;for(let w=0,k=O.length;w=1;else if(S.indexOf("OpenGL ES")!==-1)k=parseFloat(/^OpenGL ES (\d)/.exec(S)[1]),w=k>=2;let _=null,W={},j=A.getParameter(A.SCISSOR_BOX),b=A.getParameter(A.VIEWPORT),p=new X0().fromArray(j),s=new X0().fromArray(b);function r(N1,_1,J1,z1){let M1=new Uint8Array(4),L1=A.createTexture();A.bindTexture(N1,L1),A.texParameteri(N1,A.TEXTURE_MIN_FILTER,A.NEAREST),A.texParameteri(N1,A.TEXTURE_MAG_FILTER,A.NEAREST);for(let V1=0;V1k1||G1.height>k1)D1=k1/Math.max(G1.width,G1.height);if(D1<1)if(typeof HTMLImageElement!=="undefined"&&H1 instanceof HTMLImageElement||typeof HTMLCanvasElement!=="undefined"&&H1 instanceof HTMLCanvasElement||typeof ImageBitmap!=="undefined"&&H1 instanceof ImageBitmap||typeof VideoFrame!=="undefined"&&H1 instanceof VideoFrame){let w1=Math.floor(D1*G1.width),G=Math.floor(D1*G1.height);if($===void 0)$=F(w1,G);let z=B1?F(w1,G):$;return z.width=w1,z.height=G,z.getContext("2d").drawImage(H1,0,0,w1,G),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+G1.width+"x"+G1.height+") to ("+w1+"x"+G+")."),z}else{if("data"in H1)console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+G1.width+"x"+G1.height+").");return H1}return H1}function D(H1){return H1.generateMipmaps}function L(H1){A.generateMipmap(H1)}function R(H1){if(H1.isWebGLCubeRenderTarget)return A.TEXTURE_CUBE_MAP;if(H1.isWebGL3DRenderTarget)return A.TEXTURE_3D;if(H1.isWebGLArrayRenderTarget||H1.isCompressedArrayTexture)return A.TEXTURE_2D_ARRAY;return A.TEXTURE_2D}function M(H1,B1,k1,D1,G1=!1){if(H1!==null){if(A[H1]!==void 0)return A[H1];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+H1+"'")}let w1=B1;if(B1===A.RED){if(k1===A.FLOAT)w1=A.R32F;if(k1===A.HALF_FLOAT)w1=A.R16F;if(k1===A.UNSIGNED_BYTE)w1=A.R8}if(B1===A.RED_INTEGER){if(k1===A.UNSIGNED_BYTE)w1=A.R8UI;if(k1===A.UNSIGNED_SHORT)w1=A.R16UI;if(k1===A.UNSIGNED_INT)w1=A.R32UI;if(k1===A.BYTE)w1=A.R8I;if(k1===A.SHORT)w1=A.R16I;if(k1===A.INT)w1=A.R32I}if(B1===A.RG){if(k1===A.FLOAT)w1=A.RG32F;if(k1===A.HALF_FLOAT)w1=A.RG16F;if(k1===A.UNSIGNED_BYTE)w1=A.RG8}if(B1===A.RG_INTEGER){if(k1===A.UNSIGNED_BYTE)w1=A.RG8UI;if(k1===A.UNSIGNED_SHORT)w1=A.RG16UI;if(k1===A.UNSIGNED_INT)w1=A.RG32UI;if(k1===A.BYTE)w1=A.RG8I;if(k1===A.SHORT)w1=A.RG16I;if(k1===A.INT)w1=A.RG32I}if(B1===A.RGB_INTEGER){if(k1===A.UNSIGNED_BYTE)w1=A.RGB8UI;if(k1===A.UNSIGNED_SHORT)w1=A.RGB16UI;if(k1===A.UNSIGNED_INT)w1=A.RGB32UI;if(k1===A.BYTE)w1=A.RGB8I;if(k1===A.SHORT)w1=A.RGB16I;if(k1===A.INT)w1=A.RGB32I}if(B1===A.RGBA_INTEGER){if(k1===A.UNSIGNED_BYTE)w1=A.RGBA8UI;if(k1===A.UNSIGNED_SHORT)w1=A.RGBA16UI;if(k1===A.UNSIGNED_INT)w1=A.RGBA32UI;if(k1===A.BYTE)w1=A.RGBA8I;if(k1===A.SHORT)w1=A.RGBA16I;if(k1===A.INT)w1=A.RGBA32I}if(B1===A.RGB){if(k1===A.UNSIGNED_INT_5_9_9_9_REV)w1=A.RGB9_E5}if(B1===A.RGBA){let G=G1?YZ:e0.getTransfer(D1);if(k1===A.FLOAT)w1=A.RGBA32F;if(k1===A.HALF_FLOAT)w1=A.RGBA16F;if(k1===A.UNSIGNED_BYTE)w1=G===L2?A.SRGB8_ALPHA8:A.RGBA8;if(k1===A.UNSIGNED_SHORT_4_4_4_4)w1=A.RGBA4;if(k1===A.UNSIGNED_SHORT_5_5_5_1)w1=A.RGB5_A1}if(w1===A.R16F||w1===A.R32F||w1===A.RG16F||w1===A.RG32F||w1===A.RGBA16F||w1===A.RGBA32F)Q.get("EXT_color_buffer_float");return w1}function T(H1,B1){let k1;if(H1){if(B1===null||B1===TQ||B1===C9)k1=A.DEPTH24_STENCIL8;else if(B1===aA)k1=A.DEPTH32F_STENCIL8;else if(B1===r5)k1=A.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")}else if(B1===null||B1===TQ||B1===C9)k1=A.DEPTH_COMPONENT24;else if(B1===aA)k1=A.DEPTH_COMPONENT32F;else if(B1===r5)k1=A.DEPTH_COMPONENT16;return k1}function h(H1,B1){if(D(H1)===!0||H1.isFramebufferTexture&&H1.minFilter!==YA&&H1.minFilter!==HA)return Math.log2(Math.max(B1.width,B1.height))+1;else if(H1.mipmaps!==void 0&&H1.mipmaps.length>0)return H1.mipmaps.length;else if(H1.isCompressedTexture&&Array.isArray(H1.image))return B1.mipmaps.length;else return 1}function y(H1){let B1=H1.target;if(B1.removeEventListener("dispose",y),f(B1),B1.isVideoTexture)H.delete(B1)}function g(H1){let B1=H1.target;B1.removeEventListener("dispose",g),d(B1)}function f(H1){let B1=K.get(H1);if(B1.__webglInit===void 0)return;let k1=H1.source,D1=I.get(k1);if(D1){let G1=D1[B1.__cacheKey];if(G1.usedTimes--,G1.usedTimes===0)u(H1);if(Object.keys(D1).length===0)I.delete(k1)}K.remove(H1)}function u(H1){let B1=K.get(H1);A.deleteTexture(B1.__webglTexture);let k1=H1.source,D1=I.get(k1);delete D1[B1.__cacheKey],Y.memory.textures--}function d(H1){let B1=K.get(H1);if(H1.depthTexture)H1.depthTexture.dispose(),K.remove(H1.depthTexture);if(H1.isWebGLCubeRenderTarget)for(let D1=0;D1<6;D1++){if(Array.isArray(B1.__webglFramebuffer[D1]))for(let G1=0;G1=C.maxTextures)console.warn("THREE.WebGLTextures: Trying to use "+H1+" texture units while this GPU supports only "+C.maxTextures);return n+=1,H1}function P(H1){let B1=[];return B1.push(H1.wrapS),B1.push(H1.wrapT),B1.push(H1.wrapR||0),B1.push(H1.magFilter),B1.push(H1.minFilter),B1.push(H1.anisotropy),B1.push(H1.internalFormat),B1.push(H1.format),B1.push(H1.type),B1.push(H1.generateMipmaps),B1.push(H1.premultiplyAlpha),B1.push(H1.flipY),B1.push(H1.unpackAlignment),B1.push(H1.colorSpace),B1.join()}function O(H1,B1){let k1=K.get(H1);if(H1.isVideoTexture)q1(H1);if(H1.isRenderTargetTexture===!1&&H1.version>0&&k1.__version!==H1.version){let D1=H1.image;if(D1===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(D1.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{s(k1,H1,B1);return}}J.bindTexture(A.TEXTURE_2D,k1.__webglTexture,A.TEXTURE0+B1)}function w(H1,B1){let k1=K.get(H1);if(H1.version>0&&k1.__version!==H1.version){s(k1,H1,B1);return}J.bindTexture(A.TEXTURE_2D_ARRAY,k1.__webglTexture,A.TEXTURE0+B1)}function k(H1,B1){let k1=K.get(H1);if(H1.version>0&&k1.__version!==H1.version){s(k1,H1,B1);return}J.bindTexture(A.TEXTURE_3D,k1.__webglTexture,A.TEXTURE0+B1)}function S(H1,B1){let k1=K.get(H1);if(H1.version>0&&k1.__version!==H1.version){r(k1,H1,B1);return}J.bindTexture(A.TEXTURE_CUBE_MAP,k1.__webglTexture,A.TEXTURE0+B1)}let _={[A2]:A.REPEAT,[N2]:A.CLAMP_TO_EDGE,[l8]:A.MIRRORED_REPEAT},W={[YA]:A.NEAREST,[a3]:A.NEAREST_MIPMAP_NEAREST,[v9]:A.NEAREST_MIPMAP_LINEAR,[HA]:A.LINEAR,[I5]:A.LINEAR_MIPMAP_NEAREST,[o2]:A.LINEAR_MIPMAP_LINEAR},j={[FF]:A.NEVER,[wF]:A.ALWAYS,[RF]:A.LESS,[kH]:A.LEQUAL,[zF]:A.EQUAL,[MF]:A.GEQUAL,[DF]:A.GREATER,[VF]:A.NOTEQUAL};function b(H1,B1){if(B1.type===aA&&Q.has("OES_texture_float_linear")===!1&&(B1.magFilter===HA||B1.magFilter===I5||B1.magFilter===v9||B1.magFilter===o2||B1.minFilter===HA||B1.minFilter===I5||B1.minFilter===v9||B1.minFilter===o2))console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.");if(A.texParameteri(H1,A.TEXTURE_WRAP_S,_[B1.wrapS]),A.texParameteri(H1,A.TEXTURE_WRAP_T,_[B1.wrapT]),H1===A.TEXTURE_3D||H1===A.TEXTURE_2D_ARRAY)A.texParameteri(H1,A.TEXTURE_WRAP_R,_[B1.wrapR]);if(A.texParameteri(H1,A.TEXTURE_MAG_FILTER,W[B1.magFilter]),A.texParameteri(H1,A.TEXTURE_MIN_FILTER,W[B1.minFilter]),B1.compareFunction)A.texParameteri(H1,A.TEXTURE_COMPARE_MODE,A.COMPARE_REF_TO_TEXTURE),A.texParameteri(H1,A.TEXTURE_COMPARE_FUNC,j[B1.compareFunction]);if(Q.has("EXT_texture_filter_anisotropic")===!0){if(B1.magFilter===YA)return;if(B1.minFilter!==v9&&B1.minFilter!==o2)return;if(B1.type===aA&&Q.has("OES_texture_float_linear")===!1)return;if(B1.anisotropy>1||K.get(B1).__currentAnisotropy){let k1=Q.get("EXT_texture_filter_anisotropic");A.texParameterf(H1,k1.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(B1.anisotropy,C.getMaxAnisotropy())),K.get(B1).__currentAnisotropy=B1.anisotropy}}}function p(H1,B1){let k1=!1;if(H1.__webglInit===void 0)H1.__webglInit=!0,B1.addEventListener("dispose",y);let D1=B1.source,G1=I.get(D1);if(G1===void 0)G1={},I.set(D1,G1);let w1=P(B1);if(w1!==H1.__cacheKey){if(G1[w1]===void 0)G1[w1]={texture:A.createTexture(),usedTimes:0},Y.memory.textures++,k1=!0;G1[w1].usedTimes++;let G=G1[H1.__cacheKey];if(G!==void 0){if(G1[H1.__cacheKey].usedTimes--,G.usedTimes===0)u(B1)}H1.__cacheKey=w1,H1.__webglTexture=G1[w1].texture}return k1}function s(H1,B1,k1){let D1=A.TEXTURE_2D;if(B1.isDataArrayTexture||B1.isCompressedArrayTexture)D1=A.TEXTURE_2D_ARRAY;if(B1.isData3DTexture)D1=A.TEXTURE_3D;let G1=p(H1,B1),w1=B1.source;J.bindTexture(D1,H1.__webglTexture,A.TEXTURE0+k1);let G=K.get(w1);if(w1.version!==G.__version||G1===!0){J.activeTexture(A.TEXTURE0+k1);let z=e0.getPrimaries(e0.workingColorSpace),x=B1.colorSpace===P2?null:e0.getPrimaries(B1.colorSpace),m=B1.colorSpace===P2||z===x?A.NONE:A.BROWSER_DEFAULT_WEBGL;A.pixelStorei(A.UNPACK_FLIP_Y_WEBGL,B1.flipY),A.pixelStorei(A.UNPACK_PREMULTIPLY_ALPHA_WEBGL,B1.premultiplyAlpha),A.pixelStorei(A.UNPACK_ALIGNMENT,B1.unpackAlignment),A.pixelStorei(A.UNPACK_COLORSPACE_CONVERSION_WEBGL,m);let l=V(B1.image,!1,C.maxTextureSize);l=Z1(B1,l);let a=U.convert(B1.format,B1.colorSpace),K1=U.convert(B1.type),F1=M(B1.internalFormat,a,K1,B1.colorSpace,B1.isVideoTexture);b(D1,B1);let R1,X1=B1.mipmaps,W1=B1.isVideoTexture!==!0,$1=G.__version===void 0||G1===!0,N1=w1.dataReady,_1=h(B1,l);if(B1.isDepthTexture){if(F1=T(B1.format===x9,B1.type),$1)if(W1)J.texStorage2D(A.TEXTURE_2D,1,F1,l.width,l.height);else J.texImage2D(A.TEXTURE_2D,0,F1,l.width,l.height,0,a,K1,null)}else if(B1.isDataTexture)if(X1.length>0){if(W1&&$1)J.texStorage2D(A.TEXTURE_2D,_1,F1,X1[0].width,X1[0].height);for(let J1=0,z1=X1.length;J10){let M1=EG(R1.width,R1.height,B1.format,B1.type);for(let L1 of B1.layerUpdates){let V1=R1.data.subarray(L1*M1/R1.data.BYTES_PER_ELEMENT,(L1+1)*M1/R1.data.BYTES_PER_ELEMENT);J.compressedTexSubImage3D(A.TEXTURE_2D_ARRAY,J1,0,0,L1,R1.width,R1.height,1,a,V1)}B1.clearLayerUpdates()}else J.compressedTexSubImage3D(A.TEXTURE_2D_ARRAY,J1,0,0,0,R1.width,R1.height,l.depth,a,R1.data)}else J.compressedTexImage3D(A.TEXTURE_2D_ARRAY,J1,F1,R1.width,R1.height,l.depth,0,R1.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(W1){if(N1)J.texSubImage3D(A.TEXTURE_2D_ARRAY,J1,0,0,0,R1.width,R1.height,l.depth,a,K1,R1.data)}else J.texImage3D(A.TEXTURE_2D_ARRAY,J1,F1,R1.width,R1.height,l.depth,0,a,K1,R1.data)}else{if(W1&&$1)J.texStorage2D(A.TEXTURE_2D,_1,F1,X1[0].width,X1[0].height);for(let J1=0,z1=X1.length;J10){let J1=EG(l.width,l.height,B1.format,B1.type);for(let z1 of B1.layerUpdates){let M1=l.data.subarray(z1*J1/l.data.BYTES_PER_ELEMENT,(z1+1)*J1/l.data.BYTES_PER_ELEMENT);J.texSubImage3D(A.TEXTURE_2D_ARRAY,0,0,0,z1,l.width,l.height,1,a,K1,M1)}B1.clearLayerUpdates()}else J.texSubImage3D(A.TEXTURE_2D_ARRAY,0,0,0,0,l.width,l.height,l.depth,a,K1,l.data)}else J.texImage3D(A.TEXTURE_2D_ARRAY,0,F1,l.width,l.height,l.depth,0,a,K1,l.data);else if(B1.isData3DTexture)if(W1){if($1)J.texStorage3D(A.TEXTURE_3D,_1,F1,l.width,l.height,l.depth);if(N1)J.texSubImage3D(A.TEXTURE_3D,0,0,0,0,l.width,l.height,l.depth,a,K1,l.data)}else J.texImage3D(A.TEXTURE_3D,0,F1,l.width,l.height,l.depth,0,a,K1,l.data);else if(B1.isFramebufferTexture){if($1)if(W1)J.texStorage2D(A.TEXTURE_2D,_1,F1,l.width,l.height);else{let{width:J1,height:z1}=l;for(let M1=0;M1<_1;M1++)J.texImage2D(A.TEXTURE_2D,M1,F1,J1,z1,0,a,K1,null),J1>>=1,z1>>=1}}else if(X1.length>0){if(W1&&$1){let J1=j1(X1[0]);J.texStorage2D(A.TEXTURE_2D,_1,F1,J1.width,J1.height)}for(let J1=0,z1=X1.length;J10)_1++;let z1=j1(a[0]);J.texStorage2D(A.TEXTURE_CUBE_MAP,_1,X1,z1.width,z1.height)}for(let z1=0;z1<6;z1++)if(l){if(W1){if(N1)J.texSubImage2D(A.TEXTURE_CUBE_MAP_POSITIVE_X+z1,0,0,0,a[z1].width,a[z1].height,F1,R1,a[z1].data)}else J.texImage2D(A.TEXTURE_CUBE_MAP_POSITIVE_X+z1,0,X1,a[z1].width,a[z1].height,0,F1,R1,a[z1].data);for(let M1=0;M1>w1),K1=Math.max(1,B1.height>>w1);if(G1===A.TEXTURE_3D||G1===A.TEXTURE_2D_ARRAY)J.texImage3D(G1,w1,x,a,K1,B1.depth,0,G,z,null);else J.texImage2D(G1,w1,x,a,K1,0,G,z,null)}if(J.bindFramebuffer(A.FRAMEBUFFER,H1),C1(B1))Z.framebufferTexture2DMultisampleEXT(A.FRAMEBUFFER,D1,G1,l.__webglTexture,0,o(B1));else if(G1===A.TEXTURE_2D||G1>=A.TEXTURE_CUBE_MAP_POSITIVE_X&&G1<=A.TEXTURE_CUBE_MAP_NEGATIVE_Z)A.framebufferTexture2D(A.FRAMEBUFFER,D1,G1,l.__webglTexture,w1);J.bindFramebuffer(A.FRAMEBUFFER,null)}function Q1(H1,B1,k1){if(A.bindRenderbuffer(A.RENDERBUFFER,H1),B1.depthBuffer){let D1=B1.depthTexture,G1=D1&&D1.isDepthTexture?D1.type:null,w1=T(B1.stencilBuffer,G1),G=B1.stencilBuffer?A.DEPTH_STENCIL_ATTACHMENT:A.DEPTH_ATTACHMENT,z=o(B1);if(C1(B1))Z.renderbufferStorageMultisampleEXT(A.RENDERBUFFER,z,w1,B1.width,B1.height);else if(k1)A.renderbufferStorageMultisample(A.RENDERBUFFER,z,w1,B1.width,B1.height);else A.renderbufferStorage(A.RENDERBUFFER,w1,B1.width,B1.height);A.framebufferRenderbuffer(A.FRAMEBUFFER,G,A.RENDERBUFFER,H1)}else{let D1=B1.textures;for(let G1=0;G1{delete B1.__boundDepthTexture,delete B1.__depthDisposeCallback,D1.removeEventListener("dispose",G1)};D1.addEventListener("dispose",G1),B1.__depthDisposeCallback=G1}B1.__boundDepthTexture=D1}if(H1.depthTexture&&!B1.__autoAllocateDepthBuffer){if(k1)throw new Error("target.depthTexture not supported in Cube render targets");e(B1.__webglFramebuffer,H1)}else if(k1){B1.__webglDepthbuffer=[];for(let D1=0;D1<6;D1++)if(J.bindFramebuffer(A.FRAMEBUFFER,B1.__webglFramebuffer[D1]),B1.__webglDepthbuffer[D1]===void 0)B1.__webglDepthbuffer[D1]=A.createRenderbuffer(),Q1(B1.__webglDepthbuffer[D1],H1,!1);else{let G1=H1.stencilBuffer?A.DEPTH_STENCIL_ATTACHMENT:A.DEPTH_ATTACHMENT,w1=B1.__webglDepthbuffer[D1];A.bindRenderbuffer(A.RENDERBUFFER,w1),A.framebufferRenderbuffer(A.FRAMEBUFFER,G1,A.RENDERBUFFER,w1)}}else if(J.bindFramebuffer(A.FRAMEBUFFER,B1.__webglFramebuffer),B1.__webglDepthbuffer===void 0)B1.__webglDepthbuffer=A.createRenderbuffer(),Q1(B1.__webglDepthbuffer,H1,!1);else{let D1=H1.stencilBuffer?A.DEPTH_STENCIL_ATTACHMENT:A.DEPTH_ATTACHMENT,G1=B1.__webglDepthbuffer;A.bindRenderbuffer(A.RENDERBUFFER,G1),A.framebufferRenderbuffer(A.FRAMEBUFFER,D1,A.RENDERBUFFER,G1)}J.bindFramebuffer(A.FRAMEBUFFER,null)}function U1(H1,B1,k1){let D1=K.get(H1);if(B1!==void 0)A1(D1.__webglFramebuffer,H1,H1.texture,A.COLOR_ATTACHMENT0,A.TEXTURE_2D,0);if(k1!==void 0)t(H1)}function O1(H1){let B1=H1.texture,k1=K.get(H1),D1=K.get(B1);H1.addEventListener("dispose",g);let G1=H1.textures,w1=H1.isWebGLCubeRenderTarget===!0,G=G1.length>1;if(!G){if(D1.__webglTexture===void 0)D1.__webglTexture=A.createTexture();D1.__version=B1.version,Y.memory.textures++}if(w1){k1.__webglFramebuffer=[];for(let z=0;z<6;z++)if(B1.mipmaps&&B1.mipmaps.length>0){k1.__webglFramebuffer[z]=[];for(let x=0;x0){k1.__webglFramebuffer=[];for(let z=0;z0&&C1(H1)===!1){k1.__webglMultisampledFramebuffer=A.createFramebuffer(),k1.__webglColorRenderbuffer=[],J.bindFramebuffer(A.FRAMEBUFFER,k1.__webglMultisampledFramebuffer);for(let z=0;z0)for(let x=0;x0)for(let x=0;x0){if(C1(H1)===!1){let{textures:B1,width:k1,height:D1}=H1,G1=A.COLOR_BUFFER_BIT,w1=H1.stencilBuffer?A.DEPTH_STENCIL_ATTACHMENT:A.DEPTH_ATTACHMENT,G=K.get(H1),z=B1.length>1;if(z)for(let x=0;x0&&Q.has("WEBGL_multisampled_render_to_texture")===!0&&B1.__useRenderToTexture!==!1}function q1(H1){let B1=Y.render.frame;if(H.get(H1)!==B1)H.set(H1,B1),H1.update()}function Z1(H1,B1){let{colorSpace:k1,format:D1,type:G1}=H1;if(H1.isCompressedTexture===!0||H1.isVideoTexture===!0)return B1;if(k1!==GA&&k1!==P2)if(e0.getTransfer(k1)===L2){if(D1!==xA||G1!==dA)console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.")}else console.error("THREE.WebGLTextures: Unsupported texture color space:",k1);return B1}function j1(H1){if(typeof HTMLImageElement!=="undefined"&&H1 instanceof HTMLImageElement)E.width=H1.naturalWidth||H1.width,E.height=H1.naturalHeight||H1.height;else if(typeof VideoFrame!=="undefined"&&H1 instanceof VideoFrame)E.width=H1.displayWidth,E.height=H1.displayHeight;else E.width=H1.width,E.height=H1.height;return E}this.allocateTextureUnit=q,this.resetTextureUnits=B,this.setTexture2D=O,this.setTexture2DArray=w,this.setTexture3D=k,this.setTextureCube=S,this.rebindTextures=U1,this.setupRenderTarget=O1,this.updateRenderTargetMipmap=E1,this.updateMultisampleRenderTarget=c,this.setupDepthRenderbuffer=t,this.setupFrameBufferTexture=A1,this.useMultisampledRTT=C1}function Tb(A,Q){function J(K,C=P2){let U,Y=e0.getTransfer(C);if(K===dA)return A.UNSIGNED_BYTE;if(K===$H)return A.UNSIGNED_SHORT_4_4_4_4;if(K===HH)return A.UNSIGNED_SHORT_5_5_5_1;if(K===HF)return A.UNSIGNED_INT_5_9_9_9_REV;if(K===EF)return A.BYTE;if(K===$F)return A.SHORT;if(K===r5)return A.UNSIGNED_SHORT;if(K===EH)return A.INT;if(K===TQ)return A.UNSIGNED_INT;if(K===aA)return A.FLOAT;if(K===g0)return A.HALF_FLOAT;if(K===GF)return A.ALPHA;if(K===WF)return A.RGB;if(K===xA)return A.RGBA;if(K===kQ)return A.LUMINANCE;if(K===tU)return A.LUMINANCE_ALPHA;if(K===eU)return A.DEPTH_COMPONENT;if(K===x9)return A.DEPTH_STENCIL;if(K===E8)return A.RED;if(K===AZ)return A.RED_INTEGER;if(K===Y9)return A.RG;if(K===QZ)return A.RG_INTEGER;if(K===GH)return A.RGBA_INTEGER;if(K===AC||K===SQ||K===QC||K===B4)if(Y===L2)if(U=Q.get("WEBGL_compressed_texture_s3tc_srgb"),U!==null){if(K===AC)return U.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(K===SQ)return U.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(K===QC)return U.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(K===B4)return U.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(U=Q.get("WEBGL_compressed_texture_s3tc"),U!==null){if(K===AC)return U.COMPRESSED_RGB_S3TC_DXT1_EXT;if(K===SQ)return U.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(K===QC)return U.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(K===B4)return U.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(K===jQ||K===JZ||K===vQ||K===KZ)if(U=Q.get("WEBGL_compressed_texture_pvrtc"),U!==null){if(K===jQ)return U.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(K===JZ)return U.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(K===vQ)return U.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(K===KZ)return U.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(K===xQ||K===JC||K===KC)if(U=Q.get("WEBGL_compressed_texture_etc"),U!==null){if(K===xQ||K===JC)return Y===L2?U.COMPRESSED_SRGB8_ETC2:U.COMPRESSED_RGB8_ETC2;if(K===KC)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:U.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(K===yQ||K===WH||K===IH||K===qH||K===hQ||K===OH||K===NH||K===LH||K===FH||K===RH||K===zH||K===DH||K===VH||K===MH)if(U=Q.get("WEBGL_compressed_texture_astc"),U!==null){if(K===yQ)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:U.COMPRESSED_RGBA_ASTC_4x4_KHR;if(K===WH)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:U.COMPRESSED_RGBA_ASTC_5x4_KHR;if(K===IH)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:U.COMPRESSED_RGBA_ASTC_5x5_KHR;if(K===qH)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:U.COMPRESSED_RGBA_ASTC_6x5_KHR;if(K===hQ)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:U.COMPRESSED_RGBA_ASTC_6x6_KHR;if(K===OH)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:U.COMPRESSED_RGBA_ASTC_8x5_KHR;if(K===NH)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:U.COMPRESSED_RGBA_ASTC_8x6_KHR;if(K===LH)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:U.COMPRESSED_RGBA_ASTC_8x8_KHR;if(K===FH)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:U.COMPRESSED_RGBA_ASTC_10x5_KHR;if(K===RH)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:U.COMPRESSED_RGBA_ASTC_10x6_KHR;if(K===zH)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:U.COMPRESSED_RGBA_ASTC_10x8_KHR;if(K===DH)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:U.COMPRESSED_RGBA_ASTC_10x10_KHR;if(K===VH)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:U.COMPRESSED_RGBA_ASTC_12x10_KHR;if(K===MH)return Y===L2?U.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:U.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(K===gQ||K===CZ||K===bQ)if(U=Q.get("EXT_texture_compression_bptc"),U!==null){if(K===gQ)return Y===L2?U.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:U.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(K===CZ)return U.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(K===bQ)return U.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(K===IF||K===wH||K===PH||K===_H)if(U=Q.get("EXT_texture_compression_rgtc"),U!==null){if(K===gQ)return U.COMPRESSED_RED_RGTC1_EXT;if(K===wH)return U.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(K===PH)return U.COMPRESSED_RED_GREEN_RGTC2_EXT;if(K===_H)return U.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;if(K===C9)return A.UNSIGNED_INT_24_8;return A[K]!==void 0?A[K]:null}return{convert:J}}var DK1=` -void main() { - - gl_Position = vec4( position, 1.0 ); - -}`,VK1=` -uniform sampler2DArray depthColor; -uniform float depthWidth; -uniform float depthHeight; - -void main() { - - vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); - - if ( coord.x >= 1.0 ) { - - gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; - - } else { - - gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; - - } - -}`;class kb{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(A,Q,J){if(this.texture===null){let K=new J2,C=A.properties.get(K);if(C.__webglTexture=Q.texture,Q.depthNear!==J.depthNear||Q.depthFar!==J.depthFar)this.depthNear=Q.depthNear,this.depthFar=Q.depthFar;this.texture=K}}getMesh(A){if(this.texture!==null){if(this.mesh===null){let Q=A.cameras[0].viewport,J=new T0({vertexShader:DK1,fragmentShader:VK1,uniforms:{depthColor:{value:this.texture},depthWidth:{value:Q.z},depthHeight:{value:Q.w}}});this.mesh=new _0(new g8(20,20),J)}}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Sb extends y9{constructor(A,Q){super();let J=this,K=null,C=1,U=null,Y="local-floor",Z=1,X=null,E=null,H=null,$=null,I=null,N=null,F=new kb,V=Q.getContextAttributes(),D=null,L=null,R=[],M=[],T=new p1,h=null,y=new kA;y.viewport=new X0;let g=new kA;g.viewport=new X0;let f=[y,g],u=new JG,d=null,n=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(p){let s=R[p];if(s===void 0)s=new BC,R[p]=s;return s.getTargetRaySpace()},this.getControllerGrip=function(p){let s=R[p];if(s===void 0)s=new BC,R[p]=s;return s.getGripSpace()},this.getHand=function(p){let s=R[p];if(s===void 0)s=new BC,R[p]=s;return s.getHandSpace()};function B(p){let s=M.indexOf(p.inputSource);if(s===-1)return;let r=R[s];if(r!==void 0)r.update(p.inputSource,p.frame,X||U),r.dispatchEvent({type:p.type,data:p.inputSource})}function q(){K.removeEventListener("select",B),K.removeEventListener("selectstart",B),K.removeEventListener("selectend",B),K.removeEventListener("squeeze",B),K.removeEventListener("squeezestart",B),K.removeEventListener("squeezeend",B),K.removeEventListener("end",q),K.removeEventListener("inputsourceschange",P);for(let p=0;p=0)M[A1]=null,R[A1].disconnect(r)}for(let s=0;s=M.length){M.push(r),A1=e;break}else if(M[e]===null){M[e]=r,A1=e;break}if(A1===-1)break}let Q1=R[A1];if(Q1)Q1.connect(r)}}let O=new I1,w=new I1;function k(p,s,r){O.setFromMatrixPosition(s.matrixWorld),w.setFromMatrixPosition(r.matrixWorld);let A1=O.distanceTo(w),Q1=s.projectionMatrix.elements,e=r.projectionMatrix.elements,t=Q1[14]/(Q1[10]-1),U1=Q1[14]/(Q1[10]+1),O1=(Q1[9]+1)/Q1[5],E1=(Q1[9]-1)/Q1[5],Y1=(Q1[8]-1)/Q1[0],i=(e[8]+1)/e[0],c=t*Y1,o=t*i,C1=A1/(-Y1+i),q1=C1*-Y1;if(s.matrixWorld.decompose(p.position,p.quaternion,p.scale),p.translateX(q1),p.translateZ(C1),p.matrixWorld.compose(p.position,p.quaternion,p.scale),p.matrixWorldInverse.copy(p.matrixWorld).invert(),Q1[10]===-1)p.projectionMatrix.copy(s.projectionMatrix),p.projectionMatrixInverse.copy(s.projectionMatrixInverse);else{let Z1=t+C1,j1=U1+C1,H1=c-q1,B1=o+(A1-q1),k1=O1*U1/j1*Z1,D1=E1*U1/j1*Z1;p.projectionMatrix.makePerspective(H1,B1,k1,D1,Z1,j1),p.projectionMatrixInverse.copy(p.projectionMatrix).invert()}}function S(p,s){if(s===null)p.matrixWorld.copy(p.matrix);else p.matrixWorld.multiplyMatrices(s.matrixWorld,p.matrix);p.matrixWorldInverse.copy(p.matrixWorld).invert()}this.updateCamera=function(p){if(K===null)return;let{near:s,far:r}=p;if(F.texture!==null){if(F.depthNear>0)s=F.depthNear;if(F.depthFar>0)r=F.depthFar}if(u.near=g.near=y.near=s,u.far=g.far=y.far=r,d!==u.near||n!==u.far)K.updateRenderState({depthNear:u.near,depthFar:u.far}),d=u.near,n=u.far;y.layers.mask=p.layers.mask|2,g.layers.mask=p.layers.mask|4,u.layers.mask=y.layers.mask|g.layers.mask;let A1=p.parent,Q1=u.cameras;S(u,A1);for(let e=0;e0)D.alphaTest.value=L.alphaTest;let R=Q.get(L),M=R.envMap,T=R.envMapRotation;if(M){if(D.envMap.value=M,aQ.copy(T),aQ.x*=-1,aQ.y*=-1,aQ.z*=-1,M.isCubeTexture&&M.isRenderTargetTexture===!1)aQ.y*=-1,aQ.z*=-1;D.envMapRotation.value.setFromMatrix4(MK1.makeRotationFromEuler(aQ)),D.flipEnvMap.value=M.isCubeTexture&&M.isRenderTargetTexture===!1?-1:1,D.reflectivity.value=L.reflectivity,D.ior.value=L.ior,D.refractionRatio.value=L.refractionRatio}if(L.lightMap)D.lightMap.value=L.lightMap,D.lightMapIntensity.value=L.lightMapIntensity,J(L.lightMap,D.lightMapTransform);if(L.aoMap)D.aoMap.value=L.aoMap,D.aoMapIntensity.value=L.aoMapIntensity,J(L.aoMap,D.aoMapTransform)}function Y(D,L){if(D.diffuse.value.copy(L.color),D.opacity.value=L.opacity,L.map)D.map.value=L.map,J(L.map,D.mapTransform)}function Z(D,L){D.dashSize.value=L.dashSize,D.totalSize.value=L.dashSize+L.gapSize,D.scale.value=L.scale}function X(D,L,R,M){if(D.diffuse.value.copy(L.color),D.opacity.value=L.opacity,D.size.value=L.size*R,D.scale.value=M*0.5,L.map)D.map.value=L.map,J(L.map,D.uvTransform);if(L.alphaMap)D.alphaMap.value=L.alphaMap,J(L.alphaMap,D.alphaMapTransform);if(L.alphaTest>0)D.alphaTest.value=L.alphaTest}function E(D,L){if(D.diffuse.value.copy(L.color),D.opacity.value=L.opacity,D.rotation.value=L.rotation,L.map)D.map.value=L.map,J(L.map,D.mapTransform);if(L.alphaMap)D.alphaMap.value=L.alphaMap,J(L.alphaMap,D.alphaMapTransform);if(L.alphaTest>0)D.alphaTest.value=L.alphaTest}function H(D,L){D.specular.value.copy(L.specular),D.shininess.value=Math.max(L.shininess,0.0001)}function $(D,L){if(L.gradientMap)D.gradientMap.value=L.gradientMap}function I(D,L){if(D.metalness.value=L.metalness,L.metalnessMap)D.metalnessMap.value=L.metalnessMap,J(L.metalnessMap,D.metalnessMapTransform);if(D.roughness.value=L.roughness,L.roughnessMap)D.roughnessMap.value=L.roughnessMap,J(L.roughnessMap,D.roughnessMapTransform);if(L.envMap)D.envMapIntensity.value=L.envMapIntensity}function N(D,L,R){if(D.ior.value=L.ior,L.sheen>0){if(D.sheenColor.value.copy(L.sheenColor).multiplyScalar(L.sheen),D.sheenRoughness.value=L.sheenRoughness,L.sheenColorMap)D.sheenColorMap.value=L.sheenColorMap,J(L.sheenColorMap,D.sheenColorMapTransform);if(L.sheenRoughnessMap)D.sheenRoughnessMap.value=L.sheenRoughnessMap,J(L.sheenRoughnessMap,D.sheenRoughnessMapTransform)}if(L.clearcoat>0){if(D.clearcoat.value=L.clearcoat,D.clearcoatRoughness.value=L.clearcoatRoughness,L.clearcoatMap)D.clearcoatMap.value=L.clearcoatMap,J(L.clearcoatMap,D.clearcoatMapTransform);if(L.clearcoatRoughnessMap)D.clearcoatRoughnessMap.value=L.clearcoatRoughnessMap,J(L.clearcoatRoughnessMap,D.clearcoatRoughnessMapTransform);if(L.clearcoatNormalMap){if(D.clearcoatNormalMap.value=L.clearcoatNormalMap,J(L.clearcoatNormalMap,D.clearcoatNormalMapTransform),D.clearcoatNormalScale.value.copy(L.clearcoatNormalScale),L.side===w2)D.clearcoatNormalScale.value.negate()}}if(L.dispersion>0)D.dispersion.value=L.dispersion;if(L.iridescence>0){if(D.iridescence.value=L.iridescence,D.iridescenceIOR.value=L.iridescenceIOR,D.iridescenceThicknessMinimum.value=L.iridescenceThicknessRange[0],D.iridescenceThicknessMaximum.value=L.iridescenceThicknessRange[1],L.iridescenceMap)D.iridescenceMap.value=L.iridescenceMap,J(L.iridescenceMap,D.iridescenceMapTransform);if(L.iridescenceThicknessMap)D.iridescenceThicknessMap.value=L.iridescenceThicknessMap,J(L.iridescenceThicknessMap,D.iridescenceThicknessMapTransform)}if(L.transmission>0){if(D.transmission.value=L.transmission,D.transmissionSamplerMap.value=R.texture,D.transmissionSamplerSize.value.set(R.width,R.height),L.transmissionMap)D.transmissionMap.value=L.transmissionMap,J(L.transmissionMap,D.transmissionMapTransform);if(D.thickness.value=L.thickness,L.thicknessMap)D.thicknessMap.value=L.thicknessMap,J(L.thicknessMap,D.thicknessMapTransform);D.attenuationDistance.value=L.attenuationDistance,D.attenuationColor.value.copy(L.attenuationColor)}if(L.anisotropy>0){if(D.anisotropyVector.value.set(L.anisotropy*Math.cos(L.anisotropyRotation),L.anisotropy*Math.sin(L.anisotropyRotation)),L.anisotropyMap)D.anisotropyMap.value=L.anisotropyMap,J(L.anisotropyMap,D.anisotropyMapTransform)}if(D.specularIntensity.value=L.specularIntensity,D.specularColor.value.copy(L.specularColor),L.specularColorMap)D.specularColorMap.value=L.specularColorMap,J(L.specularColorMap,D.specularColorMapTransform);if(L.specularIntensityMap)D.specularIntensityMap.value=L.specularIntensityMap,J(L.specularIntensityMap,D.specularIntensityMapTransform)}function F(D,L){if(L.matcap)D.matcap.value=L.matcap}function V(D,L){let R=Q.get(L).light;D.referencePosition.value.setFromMatrixPosition(R.matrixWorld),D.nearDistance.value=R.shadow.camera.near,D.farDistance.value=R.shadow.camera.far}return{refreshFogUniforms:K,refreshMaterialUniforms:C}}function PK1(A,Q,J,K){let C={},U={},Y=[],Z=A.getParameter(A.MAX_UNIFORM_BUFFER_BINDINGS);function X(R,M){let T=M.program;K.uniformBlockBinding(R,T)}function E(R,M){let T=C[R.id];if(T===void 0)F(R),T=H(R),C[R.id]=T,R.addEventListener("dispose",D);let h=M.program;K.updateUBOMapping(R,h);let y=Q.render.frame;if(U[R.id]!==y)I(R),U[R.id]=y}function H(R){let M=$();R.__bindingPointIndex=M;let T=A.createBuffer(),h=R.__size,y=R.usage;return A.bindBuffer(A.UNIFORM_BUFFER,T),A.bufferData(A.UNIFORM_BUFFER,h,y),A.bindBuffer(A.UNIFORM_BUFFER,null),A.bindBufferBase(A.UNIFORM_BUFFER,M,T),T}function $(){for(let R=0;R0)T+=h-y;return R.__size=T,R.__cache={},this}function V(R){let M={boundary:0,storage:0};if(typeof R==="number"||typeof R==="boolean")M.boundary=4,M.storage=4;else if(R.isVector2)M.boundary=8,M.storage=8;else if(R.isVector3||R.isColor)M.boundary=16,M.storage=12;else if(R.isVector4)M.boundary=16,M.storage=16;else if(R.isMatrix3)M.boundary=48,M.storage=48;else if(R.isMatrix4)M.boundary=64,M.storage=64;else if(R.isTexture)console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.");else console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",R);return M}function D(R){let M=R.target;M.removeEventListener("dispose",D);let T=Y.indexOf(M.__bindingPointIndex);Y.splice(T,1),A.deleteBuffer(C[M.id]),delete C[M.id],delete U[M.id]}function L(){for(let R in C)A.deleteBuffer(C[R]);Y=[],C={},U={}}return{bind:X,update:E,dispose:L}}class q4{constructor(A={}){let{canvas:Q=TF(),context:J=null,depth:K=!0,stencil:C=!1,alpha:U=!1,antialias:Y=!1,premultipliedAlpha:Z=!0,preserveDrawingBuffer:X=!1,powerPreference:E="default",failIfMajorPerformanceCaveat:H=!1,reverseDepthBuffer:$=!1}=A;this.isWebGLRenderer=!0;let I;if(J!==null){if(typeof WebGLRenderingContext!=="undefined"&&J instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");I=J.getContextAttributes().alpha}else I=U;let N=new Uint32Array(4),F=new Int32Array(4),V=null,D=null,L=[],R=[];this.domElement=Q,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=CA,this.toneMapping=i5,this.toneMappingExposure=1;let M=this,T=!1,h=0,y=0,g=null,f=-1,u=null,d=new X0,n=new X0,B=null,q=new y1(0),P=0,O=Q.width,w=Q.height,k=1,S=null,_=null,W=new X0(0,0,O,w),j=new X0(0,0,O,w),b=!1,p=new Q3,s=!1,r=!1;this.transmissionResolutionScale=1;let A1=new Y0,Q1=new Y0,e=new I1,t=new X0,U1={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},O1=!1;function E1(){return g===null?k:1}let Y1=J;function i(T1,m1){return Q.getContext(T1,m1)}try{let T1={alpha:!0,depth:K,stencil:C,antialias:Y,premultipliedAlpha:Z,preserveDrawingBuffer:X,powerPreference:E,failIfMajorPerformanceCaveat:H};if("setAttribute"in Q)Q.setAttribute("data-engine",`three.js r${G5}`);if(Q.addEventListener("webglcontextlost",J1,!1),Q.addEventListener("webglcontextrestored",z1,!1),Q.addEventListener("webglcontextcreationerror",M1,!1),Y1===null){if(Y1=i("webgl2",T1),Y1===null)if(i("webgl2"))throw new Error("Error creating WebGL context with your selected attributes.");else throw new Error("Error creating WebGL context.")}}catch(T1){throw console.error("THREE.WebGLRenderer: "+T1.message),T1}let c,o,C1,q1,Z1,j1,H1,B1,k1,D1,G1,w1,G,z,x,m,l,a,K1,F1,R1,X1,W1,$1;function N1(){if(c=new nQ1(Y1),c.init(),X1=new Tb(Y1,c),o=new pQ1(Y1,c,A,X1),C1=new RK1(Y1,c),o.reverseDepthBuffer&&$)C1.buffers.depth.setReversed(!0);q1=new iQ1(Y1),Z1=new BK1,j1=new zK1(Y1,c,C1,Z1,o,X1,q1),H1=new mQ1(M),B1=new lQ1(M),k1=new J71(Y1),W1=new bQ1(Y1,k1),D1=new sQ1(Y1,k1,q1,W1),G1=new rQ1(Y1,D1,k1,q1),K1=new aQ1(Y1,o,j1),m=new uQ1(Z1),w1=new ZK1(M,H1,B1,c,o,W1,m),G=new wK1(M,Z1),z=new EK1,x=new qK1(c),a=new gQ1(M,H1,B1,C1,G1,I,Z),l=new LK1(M,G1,o),$1=new PK1(Y1,q1,o,C1),F1=new fQ1(Y1,c,q1),R1=new oQ1(Y1,c,q1),q1.programs=w1.programs,M.capabilities=o,M.extensions=c,M.properties=Z1,M.renderLists=z,M.shadowMap=l,M.state=C1,M.info=q1}N1();let _1=new Sb(M,Y1);this.xr=_1,this.getContext=function(){return Y1},this.getContextAttributes=function(){return Y1.getContextAttributes()},this.forceContextLoss=function(){let T1=c.get("WEBGL_lose_context");if(T1)T1.loseContext()},this.forceContextRestore=function(){let T1=c.get("WEBGL_lose_context");if(T1)T1.restoreContext()},this.getPixelRatio=function(){return k},this.setPixelRatio=function(T1){if(T1===void 0)return;k=T1,this.setSize(O,w,!1)},this.getSize=function(T1){return T1.set(O,w)},this.setSize=function(T1,m1,i1=!0){if(_1.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}if(O=T1,w=m1,Q.width=Math.floor(T1*k),Q.height=Math.floor(m1*k),i1===!0)Q.style.width=T1+"px",Q.style.height=m1+"px";this.setViewport(0,0,T1,m1)},this.getDrawingBufferSize=function(T1){return T1.set(O*k,w*k).floor()},this.setDrawingBufferSize=function(T1,m1,i1){O=T1,w=m1,k=i1,Q.width=Math.floor(T1*i1),Q.height=Math.floor(m1*i1),this.setViewport(0,0,T1,m1)},this.getCurrentViewport=function(T1){return T1.copy(d)},this.getViewport=function(T1){return T1.copy(W)},this.setViewport=function(T1,m1,i1,t1){if(T1.isVector4)W.set(T1.x,T1.y,T1.z,T1.w);else W.set(T1,m1,i1,t1);C1.viewport(d.copy(W).multiplyScalar(k).round())},this.getScissor=function(T1){return T1.copy(j)},this.setScissor=function(T1,m1,i1,t1){if(T1.isVector4)j.set(T1.x,T1.y,T1.z,T1.w);else j.set(T1,m1,i1,t1);C1.scissor(n.copy(j).multiplyScalar(k).round())},this.getScissorTest=function(){return b},this.setScissorTest=function(T1){C1.setScissorTest(b=T1)},this.setOpaqueSort=function(T1){S=T1},this.setTransparentSort=function(T1){_=T1},this.getClearColor=function(T1){return T1.copy(a.getClearColor())},this.setClearColor=function(){a.setClearColor.apply(a,arguments)},this.getClearAlpha=function(){return a.getClearAlpha()},this.setClearAlpha=function(){a.setClearAlpha.apply(a,arguments)},this.clear=function(T1=!0,m1=!0,i1=!0){let t1=0;if(T1){let d1=!1;if(g!==null){let H0=g.texture.format;d1=H0===GH||H0===QZ||H0===AZ}if(d1){let H0=g.texture.type,R0=H0===dA||H0===TQ||H0===r5||H0===C9||H0===$H||H0===HH,D0=a.getClearColor(),P0=a.getClearAlpha(),j0=D0.r,v0=D0.g,S0=D0.b;if(R0)N[0]=j0,N[1]=v0,N[2]=S0,N[3]=P0,Y1.clearBufferuiv(Y1.COLOR,0,N);else F[0]=j0,F[1]=v0,F[2]=S0,F[3]=P0,Y1.clearBufferiv(Y1.COLOR,0,F)}else t1|=Y1.COLOR_BUFFER_BIT}if(m1)t1|=Y1.DEPTH_BUFFER_BIT;if(i1)t1|=Y1.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295);Y1.clear(t1)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){Q.removeEventListener("webglcontextlost",J1,!1),Q.removeEventListener("webglcontextrestored",z1,!1),Q.removeEventListener("webglcontextcreationerror",M1,!1),a.dispose(),z.dispose(),x.dispose(),Z1.dispose(),H1.dispose(),B1.dispose(),G1.dispose(),W1.dispose(),$1.dispose(),w1.dispose(),_1.dispose(),_1.removeEventListener("sessionstart",f0),_1.removeEventListener("sessionend",e1),s1.stop()};function J1(T1){T1.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),T=!0}function z1(){console.log("THREE.WebGLRenderer: Context Restored."),T=!1;let T1=q1.autoReset,m1=l.enabled,i1=l.autoUpdate,t1=l.needsUpdate,d1=l.type;N1(),q1.autoReset=T1,l.enabled=m1,l.autoUpdate=i1,l.needsUpdate=t1,l.type=d1}function M1(T1){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",T1.statusMessage)}function L1(T1){let m1=T1.target;m1.removeEventListener("dispose",L1),V1(m1)}function V1(T1){S1(T1),Z1.remove(T1)}function S1(T1){let m1=Z1.get(T1).programs;if(m1!==void 0){if(m1.forEach(function(i1){w1.releaseProgram(i1)}),T1.isShaderMaterial)w1.releaseShaderCache(T1)}}this.renderBufferDirect=function(T1,m1,i1,t1,d1,H0){if(m1===null)m1=U1;let R0=d1.isMesh&&d1.matrixWorld.determinant()<0,D0=A0(T1,m1,i1,t1,d1);C1.setMaterial(t1,R0);let P0=i1.index,j0=1;if(t1.wireframe===!0){if(P0=D1.getWireframeAttribute(i1),P0===void 0)return;j0=2}let v0=i1.drawRange,S0=i1.attributes.position,n0=v0.start*j0,i0=(v0.start+v0.count)*j0;if(H0!==null)n0=Math.max(n0,H0.start*j0),i0=Math.min(i0,(H0.start+H0.count)*j0);if(P0!==null)n0=Math.max(n0,0),i0=Math.min(i0,P0.count);else if(S0!==void 0&&S0!==null)n0=Math.max(n0,0),i0=Math.min(i0,S0.count);let S2=i0-n0;if(S2<0||S2===1/0)return;W1.setup(d1,t1,D0,i1,P0);let z2,P1=F1;if(P0!==null)z2=k1.get(P0),P1=R1,P1.setIndex(z2);if(d1.isMesh)if(t1.wireframe===!0)C1.setLineWidth(t1.wireframeLinewidth*E1()),P1.setMode(Y1.LINES);else P1.setMode(Y1.TRIANGLES);else if(d1.isLine){let x1=t1.linewidth;if(x1===void 0)x1=1;if(C1.setLineWidth(x1*E1()),d1.isLineSegments)P1.setMode(Y1.LINES);else if(d1.isLineLoop)P1.setMode(Y1.LINE_LOOP);else P1.setMode(Y1.LINE_STRIP)}else if(d1.isPoints)P1.setMode(Y1.POINTS);else if(d1.isSprite)P1.setMode(Y1.TRIANGLES);if(d1.isBatchedMesh)if(d1._multiDrawInstances!==null)P1.renderMultiDrawInstances(d1._multiDrawStarts,d1._multiDrawCounts,d1._multiDrawCount,d1._multiDrawInstances);else if(!c.get("WEBGL_multi_draw")){let{_multiDrawStarts:x1,_multiDrawCounts:v1,_multiDrawCount:u1}=d1,o1=P0?k1.get(P0).bytesPerElement:1,n1=Z1.get(t1).currentProgram.getUniforms();for(let E0=0;E0{function H0(){if(t1.forEach(function(R0){if(Z1.get(R0).currentProgram.isReady())t1.delete(R0)}),t1.size===0){d1(T1);return}setTimeout(H0,10)}if(c.get("KHR_parallel_shader_compile")!==null)H0();else setTimeout(H0,10)})};let h1=null;function b1(T1){if(h1)h1(T1)}function f0(){s1.stop()}function e1(){s1.start()}let s1=new Lb;if(s1.setAnimationLoop(b1),typeof self!=="undefined")s1.setContext(self);this.setAnimationLoop=function(T1){h1=T1,_1.setAnimationLoop(T1),T1===null?s1.stop():s1.start()},_1.addEventListener("sessionstart",f0),_1.addEventListener("sessionend",e1),this.render=function(T1,m1){if(m1!==void 0&&m1.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(T===!0)return;if(T1.matrixWorldAutoUpdate===!0)T1.updateMatrixWorld();if(m1.parent===null&&m1.matrixWorldAutoUpdate===!0)m1.updateMatrixWorld();if(_1.enabled===!0&&_1.isPresenting===!0){if(_1.cameraAutoUpdate===!0)_1.updateCamera(m1);m1=_1.getCamera()}if(T1.isScene===!0)T1.onBeforeRender(M,T1,m1,g);if(D=x.get(T1,R.length),D.init(m1),R.push(D),Q1.multiplyMatrices(m1.projectionMatrix,m1.matrixWorldInverse),p.setFromProjectionMatrix(Q1),r=this.localClippingEnabled,s=m.init(this.clippingPlanes,r),V=z.get(T1,L.length),V.init(),L.push(V),_1.enabled===!0&&_1.isPresenting===!0){let H0=M.xr.getDepthSensingMesh();if(H0!==null)o0(H0,m1,-1/0,M.sortObjects)}if(o0(T1,m1,0,M.sortObjects),V.finish(),M.sortObjects===!0)V.sort(S,_);if(O1=_1.enabled===!1||_1.isPresenting===!1||_1.hasDepthSensing()===!1,O1)a.addToRenderList(V,T1);if(this.info.render.frame++,s===!0)m.beginShadows();let i1=D.state.shadowsArray;if(l.render(i1,T1,m1),s===!0)m.endShadows();if(this.info.autoReset===!0)this.info.reset();let{opaque:t1,transmissive:d1}=V;if(D.setupLights(),m1.isArrayCamera){let H0=m1.cameras;if(d1.length>0)for(let R0=0,D0=H0.length;R00)r1(t1,d1,T1,m1);if(O1)a.render(T1);a1(V,T1,m1)}if(g!==null&&y===0)j1.updateMultisampleRenderTarget(g),j1.updateRenderTargetMipmap(g);if(T1.isScene===!0)T1.onAfterRender(M,T1,m1);if(W1.resetDefaultState(),f=-1,u=null,R.pop(),R.length>0){if(D=R[R.length-1],s===!0)m.setGlobalState(M.clippingPlanes,D.state.camera)}else D=null;if(L.pop(),L.length>0)V=L[L.length-1];else V=null};function o0(T1,m1,i1,t1){if(T1.visible===!1)return;if(T1.layers.test(m1.layers)){if(T1.isGroup)i1=T1.renderOrder;else if(T1.isLOD){if(T1.autoUpdate===!0)T1.update(m1)}else if(T1.isLight){if(D.pushLight(T1),T1.castShadow)D.pushShadow(T1)}else if(T1.isSprite){if(!T1.frustumCulled||p.intersectsSprite(T1)){if(t1)t.setFromMatrixPosition(T1.matrixWorld).applyMatrix4(Q1);let R0=G1.update(T1),D0=T1.material;if(D0.visible)V.push(T1,R0,D0,i1,t.z,null)}}else if(T1.isMesh||T1.isLine||T1.isPoints){if(!T1.frustumCulled||p.intersectsObject(T1)){let R0=G1.update(T1),D0=T1.material;if(t1){if(T1.boundingSphere!==void 0){if(T1.boundingSphere===null)T1.computeBoundingSphere();t.copy(T1.boundingSphere.center)}else{if(R0.boundingSphere===null)R0.computeBoundingSphere();t.copy(R0.boundingSphere.center)}t.applyMatrix4(T1.matrixWorld).applyMatrix4(Q1)}if(Array.isArray(D0)){let P0=R0.groups;for(let j0=0,v0=P0.length;j00)FA(d1,m1,i1);if(H0.length>0)FA(H0,m1,i1);if(R0.length>0)FA(R0,m1,i1);C1.buffers.depth.setTest(!0),C1.buffers.depth.setMask(!0),C1.buffers.color.setMask(!0),C1.setPolygonOffset(!1)}function r1(T1,m1,i1,t1){if((i1.isScene===!0?i1.overrideMaterial:null)!==null)return;if(D.state.transmissionRenderTarget[t1.id]===void 0)D.state.transmissionRenderTarget[t1.id]=new s0(1,1,{generateMipmaps:!0,type:c.has("EXT_color_buffer_half_float")||c.has("EXT_color_buffer_float")?g0:dA,minFilter:o2,samples:4,stencilBuffer:C,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:e0.workingColorSpace});let H0=D.state.transmissionRenderTarget[t1.id],R0=t1.viewport||d;H0.setSize(R0.z*M.transmissionResolutionScale,R0.w*M.transmissionResolutionScale);let D0=M.getRenderTarget();if(M.setRenderTarget(H0),M.getClearColor(q),P=M.getClearAlpha(),P<1)M.setClearColor(16777215,0.5);if(M.clear(),O1)a.render(i1);let P0=M.toneMapping;M.toneMapping=i5;let j0=t1.viewport;if(t1.viewport!==void 0)t1.viewport=void 0;if(D.setupLightsView(t1),s===!0)m.setGlobalState(M.clippingPlanes,t1);if(FA(T1,i1,t1),j1.updateMultisampleRenderTarget(H0),j1.updateRenderTargetMipmap(H0),c.has("WEBGL_multisampled_render_to_texture")===!1){let v0=!1;for(let S0=0,n0=m1.length;S00),S0=!!i1.morphAttributes.position,n0=!!i1.morphAttributes.normal,i0=!!i1.morphAttributes.color,S2=i5;if(t1.toneMapped){if(g===null||g.isXRRenderTarget===!0)S2=M.toneMapping}let z2=i1.morphAttributes.position||i1.morphAttributes.normal||i1.morphAttributes.color,P1=z2!==void 0?z2.length:0,x1=Z1.get(t1),v1=D.state.lights;if(s===!0){if(r===!0||T1!==u){let x0=T1===u&&t1.id===f;m.setState(t1,T1,x0)}}let u1=!1;if(t1.version===x1.__version){if(x1.needsLights&&x1.lightsStateVersion!==v1.state.version)u1=!0;else if(x1.outputColorSpace!==D0)u1=!0;else if(d1.isBatchedMesh&&x1.batching===!1)u1=!0;else if(!d1.isBatchedMesh&&x1.batching===!0)u1=!0;else if(d1.isBatchedMesh&&x1.batchingColor===!0&&d1.colorTexture===null)u1=!0;else if(d1.isBatchedMesh&&x1.batchingColor===!1&&d1.colorTexture!==null)u1=!0;else if(d1.isInstancedMesh&&x1.instancing===!1)u1=!0;else if(!d1.isInstancedMesh&&x1.instancing===!0)u1=!0;else if(d1.isSkinnedMesh&&x1.skinning===!1)u1=!0;else if(!d1.isSkinnedMesh&&x1.skinning===!0)u1=!0;else if(d1.isInstancedMesh&&x1.instancingColor===!0&&d1.instanceColor===null)u1=!0;else if(d1.isInstancedMesh&&x1.instancingColor===!1&&d1.instanceColor!==null)u1=!0;else if(d1.isInstancedMesh&&x1.instancingMorph===!0&&d1.morphTexture===null)u1=!0;else if(d1.isInstancedMesh&&x1.instancingMorph===!1&&d1.morphTexture!==null)u1=!0;else if(x1.envMap!==P0)u1=!0;else if(t1.fog===!0&&x1.fog!==H0)u1=!0;else if(x1.numClippingPlanes!==void 0&&(x1.numClippingPlanes!==m.numPlanes||x1.numIntersection!==m.numIntersection))u1=!0;else if(x1.vertexAlphas!==j0)u1=!0;else if(x1.vertexTangents!==v0)u1=!0;else if(x1.morphTargets!==S0)u1=!0;else if(x1.morphNormals!==n0)u1=!0;else if(x1.morphColors!==i0)u1=!0;else if(x1.toneMapping!==S2)u1=!0;else if(x1.morphTargetsCount!==P1)u1=!0}else u1=!0,x1.__version=t1.version;let o1=x1.currentProgram;if(u1===!0)o1=J0(t1,m1,d1);let n1=!1,E0=!1,F0=!1,I0=o1.getUniforms(),z0=x1.uniforms;if(C1.useProgram(o1.program))n1=!0,E0=!0,F0=!0;if(t1.id!==f)f=t1.id,E0=!0;if(n1||u!==T1){if(C1.buffers.depth.getReversed())A1.copy(T1.projectionMatrix),jg(A1),vg(A1),I0.setValue(Y1,"projectionMatrix",A1);else I0.setValue(Y1,"projectionMatrix",T1.projectionMatrix);I0.setValue(Y1,"viewMatrix",T1.matrixWorldInverse);let ZA=I0.map.cameraPosition;if(ZA!==void 0)ZA.setValue(Y1,e.setFromMatrixPosition(T1.matrixWorld));if(o.logarithmicDepthBuffer)I0.setValue(Y1,"logDepthBufFC",2/(Math.log(T1.far+1)/Math.LN2));if(t1.isMeshPhongMaterial||t1.isMeshToonMaterial||t1.isMeshLambertMaterial||t1.isMeshBasicMaterial||t1.isMeshStandardMaterial||t1.isShaderMaterial)I0.setValue(Y1,"isOrthographic",T1.isOrthographicCamera===!0);if(u!==T1)u=T1,E0=!0,F0=!0}if(d1.isSkinnedMesh){I0.setOptional(Y1,d1,"bindMatrix"),I0.setOptional(Y1,d1,"bindMatrixInverse");let x0=d1.skeleton;if(x0){if(x0.boneTexture===null)x0.computeBoneTexture();I0.setValue(Y1,"boneTexture",x0.boneTexture,j1)}}if(d1.isBatchedMesh){if(I0.setOptional(Y1,d1,"batchingTexture"),I0.setValue(Y1,"batchingTexture",d1._matricesTexture,j1),I0.setOptional(Y1,d1,"batchingIdTexture"),I0.setValue(Y1,"batchingIdTexture",d1._indirectTexture,j1),I0.setOptional(Y1,d1,"batchingColorTexture"),d1._colorsTexture!==null)I0.setValue(Y1,"batchingColorTexture",d1._colorsTexture,j1)}let w0=i1.morphAttributes;if(w0.position!==void 0||w0.normal!==void 0||w0.color!==void 0)K1.update(d1,i1,o1);if(E0||x1.receiveShadow!==d1.receiveShadow)x1.receiveShadow=d1.receiveShadow,I0.setValue(Y1,"receiveShadow",d1.receiveShadow);if(t1.isMeshGouraudMaterial&&t1.envMap!==null)z0.envMap.value=P0,z0.flipEnvMap.value=P0.isCubeTexture&&P0.isRenderTargetTexture===!1?-1:1;if(t1.isMeshStandardMaterial&&t1.envMap===null&&m1.environment!==null)z0.envMapIntensity.value=m1.environmentIntensity;if(E0){if(I0.setValue(Y1,"toneMappingExposure",M.toneMappingExposure),x1.needsLights)hA(z0,F0);if(H0&&t1.fog===!0)G.refreshFogUniforms(z0,H0);G.refreshMaterialUniforms(z0,t1,k,w,D.state.transmissionRenderTarget[T1.id]),fZ.upload(Y1,qA(x1),z0,j1)}if(t1.isShaderMaterial&&t1.uniformsNeedUpdate===!0)fZ.upload(Y1,qA(x1),z0,j1),t1.uniformsNeedUpdate=!1;if(t1.isSpriteMaterial)I0.setValue(Y1,"center",d1.center);if(I0.setValue(Y1,"modelViewMatrix",d1.modelViewMatrix),I0.setValue(Y1,"normalMatrix",d1.normalMatrix),I0.setValue(Y1,"modelMatrix",d1.matrixWorld),t1.isShaderMaterial||t1.isRawShaderMaterial){let x0=t1.uniformsGroups;for(let ZA=0,eA=x0.length;ZA0&&j1.useMultisampledRTT(T1)===!1)d1=Z1.get(T1).__webglMultisampledFramebuffer;else if(Array.isArray(v0))d1=v0[i1];else d1=v0;d.copy(T1.viewport),n.copy(T1.scissor),B=T1.scissorTest}else d.copy(W).multiplyScalar(k).floor(),n.copy(j).multiplyScalar(k).floor(),B=b;if(i1!==0)d1=EA;if(C1.bindFramebuffer(Y1.FRAMEBUFFER,d1)&&t1)C1.drawBuffers(T1,d1);if(C1.viewport(d),C1.scissor(n),C1.setScissorTest(B),H0){let P0=Z1.get(T1.texture);Y1.framebufferTexture2D(Y1.FRAMEBUFFER,Y1.COLOR_ATTACHMENT0,Y1.TEXTURE_CUBE_MAP_POSITIVE_X+m1,P0.__webglTexture,i1)}else if(R0){let P0=Z1.get(T1.texture),j0=m1;Y1.framebufferTextureLayer(Y1.FRAMEBUFFER,Y1.COLOR_ATTACHMENT0,P0.__webglTexture,i1,j0)}else if(T1!==null&&i1!==0){let P0=Z1.get(T1.texture);Y1.framebufferTexture2D(Y1.FRAMEBUFFER,Y1.COLOR_ATTACHMENT0,Y1.TEXTURE_2D,P0.__webglTexture,i1)}f=-1},this.readRenderTargetPixels=function(T1,m1,i1,t1,d1,H0,R0){if(!(T1&&T1.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let D0=Z1.get(T1).__webglFramebuffer;if(T1.isWebGLCubeRenderTarget&&R0!==void 0)D0=D0[R0];if(D0){C1.bindFramebuffer(Y1.FRAMEBUFFER,D0);try{let P0=T1.texture,j0=P0.format,v0=P0.type;if(!o.textureFormatReadable(j0)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!o.textureTypeReadable(v0)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}if(m1>=0&&m1<=T1.width-t1&&(i1>=0&&i1<=T1.height-d1))Y1.readPixels(m1,i1,t1,d1,X1.convert(j0),X1.convert(v0),H0)}finally{let P0=g!==null?Z1.get(g).__webglFramebuffer:null;C1.bindFramebuffer(Y1.FRAMEBUFFER,P0)}}},this.readRenderTargetPixelsAsync=async function(T1,m1,i1,t1,d1,H0,R0){if(!(T1&&T1.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let D0=Z1.get(T1).__webglFramebuffer;if(T1.isWebGLCubeRenderTarget&&R0!==void 0)D0=D0[R0];if(D0){let P0=T1.texture,j0=P0.format,v0=P0.type;if(!o.textureFormatReadable(j0))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!o.textureTypeReadable(v0))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(m1>=0&&m1<=T1.width-t1&&(i1>=0&&i1<=T1.height-d1)){C1.bindFramebuffer(Y1.FRAMEBUFFER,D0);let S0=Y1.createBuffer();Y1.bindBuffer(Y1.PIXEL_PACK_BUFFER,S0),Y1.bufferData(Y1.PIXEL_PACK_BUFFER,H0.byteLength,Y1.STREAM_READ),Y1.readPixels(m1,i1,t1,d1,X1.convert(j0),X1.convert(v0),0);let n0=g!==null?Z1.get(g).__webglFramebuffer:null;C1.bindFramebuffer(Y1.FRAMEBUFFER,n0);let i0=Y1.fenceSync(Y1.SYNC_GPU_COMMANDS_COMPLETE,0);return Y1.flush(),await Sg(Y1,i0,4),Y1.bindBuffer(Y1.PIXEL_PACK_BUFFER,S0),Y1.getBufferSubData(Y1.PIXEL_PACK_BUFFER,0,H0),Y1.deleteBuffer(S0),Y1.deleteSync(i0),H0}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(T1,m1=null,i1=0){if(T1.isTexture!==!0)fQ("WebGLRenderer: copyFramebufferToTexture function signature has changed."),m1=arguments[0]||null,T1=arguments[1];let t1=Math.pow(2,-i1),d1=Math.floor(T1.image.width*t1),H0=Math.floor(T1.image.height*t1),R0=m1!==null?m1.x:0,D0=m1!==null?m1.y:0;j1.setTexture2D(T1,0),Y1.copyTexSubImage2D(Y1.TEXTURE_2D,i1,0,0,R0,D0,d1,H0),C1.unbindTexture()};let X2=Y1.createFramebuffer(),E2=Y1.createFramebuffer();if(this.copyTextureToTexture=function(T1,m1,i1=null,t1=null,d1=0,H0=null){if(T1.isTexture!==!0)fQ("WebGLRenderer: copyTextureToTexture function signature has changed."),t1=arguments[0]||null,T1=arguments[1],m1=arguments[2],H0=arguments[3]||0,i1=null;if(H0===null)if(d1!==0)fQ("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),H0=d1,d1=0;else H0=0;let R0,D0,P0,j0,v0,S0,n0,i0,S2,z2=T1.isCompressedTexture?T1.mipmaps[H0]:T1.image;if(i1!==null)R0=i1.max.x-i1.min.x,D0=i1.max.y-i1.min.y,P0=i1.isBox3?i1.max.z-i1.min.z:1,j0=i1.min.x,v0=i1.min.y,S0=i1.isBox3?i1.min.z:0;else{let w0=Math.pow(2,-d1);if(R0=Math.floor(z2.width*w0),D0=Math.floor(z2.height*w0),T1.isDataArrayTexture)P0=z2.depth;else if(T1.isData3DTexture)P0=Math.floor(z2.depth*w0);else P0=1;j0=0,v0=0,S0=0}if(t1!==null)n0=t1.x,i0=t1.y,S2=t1.z;else n0=0,i0=0,S2=0;let P1=X1.convert(m1.format),x1=X1.convert(m1.type),v1;if(m1.isData3DTexture)j1.setTexture3D(m1,0),v1=Y1.TEXTURE_3D;else if(m1.isDataArrayTexture||m1.isCompressedArrayTexture)j1.setTexture2DArray(m1,0),v1=Y1.TEXTURE_2D_ARRAY;else j1.setTexture2D(m1,0),v1=Y1.TEXTURE_2D;Y1.pixelStorei(Y1.UNPACK_FLIP_Y_WEBGL,m1.flipY),Y1.pixelStorei(Y1.UNPACK_PREMULTIPLY_ALPHA_WEBGL,m1.premultiplyAlpha),Y1.pixelStorei(Y1.UNPACK_ALIGNMENT,m1.unpackAlignment);let u1=Y1.getParameter(Y1.UNPACK_ROW_LENGTH),o1=Y1.getParameter(Y1.UNPACK_IMAGE_HEIGHT),n1=Y1.getParameter(Y1.UNPACK_SKIP_PIXELS),E0=Y1.getParameter(Y1.UNPACK_SKIP_ROWS),F0=Y1.getParameter(Y1.UNPACK_SKIP_IMAGES);Y1.pixelStorei(Y1.UNPACK_ROW_LENGTH,z2.width),Y1.pixelStorei(Y1.UNPACK_IMAGE_HEIGHT,z2.height),Y1.pixelStorei(Y1.UNPACK_SKIP_PIXELS,j0),Y1.pixelStorei(Y1.UNPACK_SKIP_ROWS,v0),Y1.pixelStorei(Y1.UNPACK_SKIP_IMAGES,S0);let I0=T1.isDataArrayTexture||T1.isData3DTexture,z0=m1.isDataArrayTexture||m1.isData3DTexture;if(T1.isDepthTexture){let w0=Z1.get(T1),x0=Z1.get(m1),ZA=Z1.get(w0.__renderTarget),eA=Z1.get(x0.__renderTarget);C1.bindFramebuffer(Y1.READ_FRAMEBUFFER,ZA.__webglFramebuffer),C1.bindFramebuffer(Y1.DRAW_FRAMEBUFFER,eA.__webglFramebuffer);for(let uA=0;uA=2.0 are supported."));return}let X=new Zf(C,{path:Q||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});X.fileLoader.setRequestHeader(this.requestHeader);for(let E=0;E=0&&Y[H]===void 0)console.warn('THREE.GLTFLoader: Unknown extension "'+H+'".')}}X.setExtensions(U),X.setPlugins(Y),X.parse(J,K)}parseAsync(A,Q){let J=this;return new Promise(function(K,C){J.parse(A,Q,K,C)})}}function _K1(){let A={};return{get:function(Q){return A[Q]},add:function(Q,J){A[Q]=J},remove:function(Q){delete A[Q]},removeAll:function(){A={}}}}var lA={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class hb{constructor(A){this.parser=A,this.name=lA.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let A=this.parser,Q=this.parser.json.nodes||[];for(let J=0,K=Q.length;J=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");else return null;return Q.loadTextureImage(A,C.source,U)}}class rb{constructor(A){this.parser=A,this.name=lA.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(A){let Q=this.name,J=this.parser,K=J.json,C=K.textures[A];if(!C.extensions||!C.extensions[Q])return null;let U=C.extensions[Q],Y=K.images[U.source],Z=J.textureLoader;if(Y.uri){let X=J.options.manager.getHandler(Y.uri);if(X!==null)Z=X}return this.detectSupport().then(function(X){if(X)return J.loadTextureImage(A,U.source,Z);if(K.extensionsRequired&&K.extensionsRequired.indexOf(Q)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return J.loadTexture(A)})}detectSupport(){if(!this.isSupported)this.isSupported=new Promise(function(A){let Q=new Image;Q.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",Q.onload=Q.onerror=function(){A(Q.height===1)}});return this.isSupported}}class tb{constructor(A){this.parser=A,this.name=lA.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(A){let Q=this.name,J=this.parser,K=J.json,C=K.textures[A];if(!C.extensions||!C.extensions[Q])return null;let U=C.extensions[Q],Y=K.images[U.source],Z=J.textureLoader;if(Y.uri){let X=J.options.manager.getHandler(Y.uri);if(X!==null)Z=X}return this.detectSupport().then(function(X){if(X)return J.loadTextureImage(A,U.source,Z);if(K.extensionsRequired&&K.extensionsRequired.indexOf(Q)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return J.loadTexture(A)})}detectSupport(){if(!this.isSupported)this.isSupported=new Promise(function(A){let Q=new Image;Q.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",Q.onload=Q.onerror=function(){A(Q.height===1)}});return this.isSupported}}class eb{constructor(A){this.name=lA.EXT_MESHOPT_COMPRESSION,this.parser=A}loadBufferView(A){let Q=this.parser.json,J=Q.bufferViews[A];if(J.extensions&&J.extensions[this.name]){let K=J.extensions[this.name],C=this.parser.getDependency("buffer",K.buffer),U=this.parser.options.meshoptDecoder;if(!U||!U.supported)if(Q.extensionsRequired&&Q.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");else return null;return C.then(function(Y){let Z=K.byteOffset||0,X=K.byteLength||0,E=K.count,H=K.byteStride,$=new Uint8Array(Y,Z,X);if(U.decodeGltfBufferAsync)return U.decodeGltfBufferAsync(E,H,$,K.mode,K.filter).then(function(I){return I.buffer});else return U.ready.then(function(){let I=new ArrayBuffer(E*H);return U.decodeGltfBuffer(new Uint8Array(I),E,H,$,K.mode,K.filter),I})})}else return null}}class Af{constructor(A){this.name=lA.EXT_MESH_GPU_INSTANCING,this.parser=A}createNodeMesh(A){let Q=this.parser.json,J=Q.nodes[A];if(!J.extensions||!J.extensions[this.name]||J.mesh===void 0)return null;let K=Q.meshes[J.mesh];for(let X of K.primitives)if(X.mode!==b9.TRIANGLES&&X.mode!==b9.TRIANGLE_STRIP&&X.mode!==b9.TRIANGLE_FAN&&X.mode!==void 0)return null;let U=J.extensions[this.name].attributes,Y=[],Z={};for(let X in U)Y.push(this.parser.getDependency("accessor",U[X]).then((E)=>{return Z[X]=E,Z[X]}));if(Y.length<1)return null;return Y.push(this.parser.createNodeMesh(A)),Promise.all(Y).then((X)=>{let E=X.pop(),H=E.isGroup?E.children:[E],$=X[0].count,I=[];for(let N of H){let F=new Y0,V=new I1,D=new t0,L=new I1(1,1,1),R=new A3(N.geometry,N.material,$);for(let M=0;M<$;M++){if(Z.TRANSLATION)V.fromBufferAttribute(Z.TRANSLATION,M);if(Z.ROTATION)D.fromBufferAttribute(Z.ROTATION,M);if(Z.SCALE)L.fromBufferAttribute(Z.SCALE,M);R.setMatrixAt(M,F.compose(V,D,L))}for(let M in Z)if(M==="_COLOR_0"){let T=Z[M];R.instanceColor=new K9(T.array,T.itemSize,T.normalized)}else if(M!=="TRANSLATION"&&M!=="ROTATION"&&M!=="SCALE")N.geometry.setAttribute(M,Z[M]);AA.prototype.copy.call(R,N),this.parser.assignFinalMaterial(R),I.push(R)}if(E.isGroup)return E.clear(),E.add(...I),E;return I[0]})}}var Qf="glTF",pZ=12,jb={JSON:1313821514,BIN:5130562};class Jf{constructor(A){this.name=lA.KHR_BINARY_GLTF,this.content=null,this.body=null;let Q=new DataView(A,0,pZ),J=/*@__PURE__*/new TextDecoder;if(this.header={magic:J.decode(new Uint8Array(A.slice(0,4))),version:Q.getUint32(4,!0),length:Q.getUint32(8,!0)},this.header.magic!==Qf)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");else if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");let K=this.header.length-pZ,C=new DataView(A,pZ),U=0;while(U0||A.search(/^data\:image\/jpeg/)===0)return"image/jpeg";if(A.search(/\.webp($|\?)/i)>0||A.search(/^data\:image\/webp/)===0)return"image/webp";if(A.search(/\.ktx2($|\?)/i)>0||A.search(/^data\:image\/ktx2/)===0)return"image/ktx2";return"image/png"}var hK1=new Y0;class Zf{constructor(A={},Q={}){this.json=A,this.extensions={},this.plugins={},this.options=Q,this.cache=new _K1,this.associations=/*@__PURE__*/new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let J=!1,K=-1,C=!1,U=-1;if(typeof navigator!=="undefined"){let Y=navigator.userAgent;J=/^((?!chrome|android).)*safari/i.test(Y)===!0;let Z=Y.match(/Version\/(\d+)/);K=J&&Z?parseInt(Z[1],10):-1,C=Y.indexOf("Firefox")>-1,U=C?Y.match(/Firefox\/([0-9]+)\./)[1]:-1}if(typeof createImageBitmap==="undefined"||J&&K<17||C&&U<98)this.textureLoader=new J8(this.options.manager);else this.textureLoader=new sQ(this.options.manager);if(this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new KA(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials")this.fileLoader.setWithCredentials(!0)}setExtensions(A){this.extensions=A}setPlugins(A){this.plugins=A}parse(A,Q){let J=this,K=this.json,C=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(U){return U._markDefs&&U._markDefs()}),Promise.all(this._invokeAll(function(U){return U.beforeRoot&&U.beforeRoot()})).then(function(){return Promise.all([J.getDependencies("scene"),J.getDependencies("animation"),J.getDependencies("camera")])}).then(function(U){let Y={scene:U[0][K.scene||0],scenes:U[0],animations:U[1],cameras:U[2],asset:K.asset,parser:J,userData:{}};return eQ(C,Y,K),K7(Y,K),Promise.all(J._invokeAll(function(Z){return Z.afterRoot&&Z.afterRoot(Y)})).then(function(){for(let Z of Y.scenes)Z.updateMatrixWorld();A(Y)})}).catch(Q)}_markDefs(){let A=this.json.nodes||[],Q=this.json.skins||[],J=this.json.meshes||[];for(let K=0,C=Q.length;K{let Z=this.associations.get(U);if(Z!=null)this.associations.set(Y,Z);for(let[X,E]of U.children.entries())C(E,Y.children[X])};return C(J,K),K.name+="_instance_"+A.uses[Q]++,K}_invokeOne(A){let Q=Object.values(this.plugins);Q.push(this);for(let J=0;J=2)V.setY(f,h[y*Z+1]);if(Z>=3)V.setZ(f,h[y*Z+2]);if(Z>=4)V.setW(f,h[y*Z+3]);if(Z>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}V.normalized=N}return V})}loadTexture(A){let Q=this.json,J=this.options,C=Q.textures[A].source,U=Q.images[C],Y=this.textureLoader;if(U.uri){let Z=J.manager.getHandler(U.uri);if(Z!==null)Y=Z}return this.loadTextureImage(A,C,Y)}loadTextureImage(A,Q,J){let K=this,C=this.json,U=C.textures[A],Y=C.images[Q],Z=(Y.uri||Y.bufferView)+":"+U.sampler;if(this.textureCache[Z])return this.textureCache[Z];let X=this.loadImageSource(Q,J).then(function(E){if(E.flipY=!1,E.name=U.name||Y.name||"",E.name===""&&typeof Y.uri==="string"&&Y.uri.startsWith("data:image/")===!1)E.name=Y.uri;let $=(C.samplers||{})[U.sampler]||{};return E.magFilter=vb[$.magFilter]||HA,E.minFilter=vb[$.minFilter]||o2,E.wrapS=xb[$.wrapS]||A2,E.wrapT=xb[$.wrapT]||A2,E.generateMipmaps=!E.isCompressedTexture&&E.minFilter!==YA&&E.minFilter!==HA,K.associations.set(E,{textures:A}),E}).catch(function(){return null});return this.textureCache[Z]=X,X}loadImageSource(A,Q){let J=this,K=this.json,C=this.options;if(this.sourceCache[A]!==void 0)return this.sourceCache[A].then((H)=>H.clone());let U=K.images[A],Y=self.URL||self.webkitURL,Z=U.uri||"",X=!1;if(U.bufferView!==void 0)Z=J.getDependency("bufferView",U.bufferView).then(function(H){X=!0;let $=new Blob([H],{type:U.mimeType});return Z=Y.createObjectURL($),Z});else if(U.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+A+" is missing URI and bufferView");let E=Promise.resolve(Z).then(function(H){return new Promise(function($,I){let N=$;if(Q.isImageBitmapLoader===!0)N=function(F){let V=new J2(F);V.needsUpdate=!0,$(V)};Q.load(A8.resolveURL(H,C.path),N,void 0,I)})}).then(function(H){if(X===!0)Y.revokeObjectURL(Z);return K7(H,U),H.userData.mimeType=U.mimeType||yK1(U.uri),H}).catch(function(H){throw console.error("THREE.GLTFLoader: Couldn't load texture",Z),H});return this.sourceCache[A]=E,E}assignTexture(A,Q,J,K){let C=this;return this.getDependency("texture",J.index).then(function(U){if(!U)return null;if(J.texCoord!==void 0&&J.texCoord>0)U=U.clone(),U.channel=J.texCoord;if(C.extensions[lA.KHR_TEXTURE_TRANSFORM]){let Y=J.extensions!==void 0?J.extensions[lA.KHR_TEXTURE_TRANSFORM]:void 0;if(Y){let Z=C.associations.get(U);U=C.extensions[lA.KHR_TEXTURE_TRANSFORM].extendTexture(U,Y),C.associations.set(U,Z)}}if(K!==void 0)U.colorSpace=K;return A[Q]=U,U})}assignFinalMaterial(A){let{geometry:Q,material:J}=A,K=Q.attributes.tangent===void 0,C=Q.attributes.color!==void 0,U=Q.attributes.normal===void 0;if(A.isPoints){let Y="PointsMaterial:"+J.uuid,Z=this.cache.get(Y);if(!Z)Z=new X6,_2.prototype.copy.call(Z,J),Z.color.copy(J.color),Z.map=J.map,Z.sizeAttenuation=!1,this.cache.add(Y,Z);J=Z}else if(A.isLine){let Y="LineBasicMaterial:"+J.uuid,Z=this.cache.get(Y);if(!Z)Z=new pA,_2.prototype.copy.call(Z,J),Z.color.copy(J.color),Z.map=J.map,this.cache.add(Y,Z);J=Z}if(K||C||U){let Y="ClonedMaterial:"+J.uuid+":";if(K)Y+="derivative-tangents:";if(C)Y+="vertex-colors:";if(U)Y+="flat-shading:";let Z=this.cache.get(Y);if(!Z){if(Z=J.clone(),C)Z.vertexColors=!0;if(U)Z.flatShading=!0;if(K){if(Z.normalScale)Z.normalScale.y*=-1;if(Z.clearcoatNormalScale)Z.clearcoatNormalScale.y*=-1}this.cache.add(Y,Z),this.associations.set(Z,this.associations.get(J))}J=Z}A.material=J}getMaterialType(){return p2}loadMaterial(A){let Q=this,J=this.json,K=this.extensions,C=J.materials[A],U,Y={},Z=C.extensions||{},X=[];if(Z[lA.KHR_MATERIALS_UNLIT]){let H=K[lA.KHR_MATERIALS_UNLIT];U=H.getMaterialType(),X.push(H.extendParams(Y,C,Q))}else{let H=C.pbrMetallicRoughness||{};if(Y.color=new y1(1,1,1),Y.opacity=1,Array.isArray(H.baseColorFactor)){let $=H.baseColorFactor;Y.color.setRGB($[0],$[1],$[2],GA),Y.opacity=$[3]}if(H.baseColorTexture!==void 0)X.push(Q.assignTexture(Y,"map",H.baseColorTexture,CA));if(Y.metalness=H.metallicFactor!==void 0?H.metallicFactor:1,Y.roughness=H.roughnessFactor!==void 0?H.roughnessFactor:1,H.metallicRoughnessTexture!==void 0)X.push(Q.assignTexture(Y,"metalnessMap",H.metallicRoughnessTexture)),X.push(Q.assignTexture(Y,"roughnessMap",H.metallicRoughnessTexture));U=this._invokeOne(function($){return $.getMaterialType&&$.getMaterialType(A)}),X.push(Promise.all(this._invokeAll(function($){return $.extendMaterialParams&&$.extendMaterialParams(A,Y)})))}if(C.doubleSided===!0)Y.side=VA;let E=C.alphaMode||LR.OPAQUE;if(E===LR.BLEND)Y.transparent=!0,Y.depthWrite=!1;else if(Y.transparent=!1,E===LR.MASK)Y.alphaTest=C.alphaCutoff!==void 0?C.alphaCutoff:0.5;if(C.normalTexture!==void 0&&U!==BA){if(X.push(Q.assignTexture(Y,"normalMap",C.normalTexture)),Y.normalScale=new p1(1,1),C.normalTexture.scale!==void 0){let H=C.normalTexture.scale;Y.normalScale.set(H,H)}}if(C.occlusionTexture!==void 0&&U!==BA){if(X.push(Q.assignTexture(Y,"aoMap",C.occlusionTexture)),C.occlusionTexture.strength!==void 0)Y.aoMapIntensity=C.occlusionTexture.strength}if(C.emissiveFactor!==void 0&&U!==BA){let H=C.emissiveFactor;Y.emissive=new y1().setRGB(H[0],H[1],H[2],GA)}if(C.emissiveTexture!==void 0&&U!==BA)X.push(Q.assignTexture(Y,"emissiveMap",C.emissiveTexture,CA));return Promise.all(X).then(function(){let H=new U(Y);if(C.name)H.name=C.name;if(K7(H,C),Q.associations.set(H,{materials:A}),C.extensions)eQ(K,H,C);return H})}createUniqueName(A){let Q=RA.sanitizeNodeName(A||"");if(Q in this.nodeNamesUsed)return Q+"_"+ ++this.nodeNamesUsed[Q];else return this.nodeNamesUsed[Q]=0,Q}loadGeometries(A){let Q=this,J=this.extensions,K=this.primitiveCache;function C(Y){return J[lA.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(Y,Q).then(function(Z){return yb(Z,Y,Q)})}let U=[];for(let Y=0,Z=A.length;Y0)vK1(D,C);if(D.name=Q.createUniqueName(C.name||"mesh_"+A),K7(D,C),V.extensions)eQ(K,D,V);Q.assignFinalMaterial(D),H.push(D)}for(let I=0,N=H.length;I1)E=new cA;else if(X.length===1)E=X[0];else E=new AA;if(E!==X[0])for(let H=0,$=X.length;H<$;H++)E.add(X[H]);if(C.name)E.userData.name=C.name,E.name=U;if(K7(E,C),C.extensions)eQ(J,E,C);if(C.matrix!==void 0){let H=new Y0;H.fromArray(C.matrix),E.applyMatrix4(H)}else{if(C.translation!==void 0)E.position.fromArray(C.translation);if(C.rotation!==void 0)E.quaternion.fromArray(C.rotation);if(C.scale!==void 0)E.scale.fromArray(C.scale)}if(!K.associations.has(E))K.associations.set(E,{});return K.associations.get(E).nodes=A,E}),this.nodeCache[A]}loadScene(A){let Q=this.extensions,J=this.json.scenes[A],K=this,C=new cA;if(J.name)C.name=K.createUniqueName(J.name);if(K7(C,J),J.extensions)eQ(Q,C,J);let U=J.nodes||[],Y=[];for(let Z=0,X=U.length;Z{let H=/*@__PURE__*/new Map;for(let[$,I]of K.associations)if($ instanceof _2||$ instanceof J2)H.set($,I);return E.traverse(($)=>{let I=K.associations.get($);if(I!=null)H.set($,I)}),H};return K.associations=X(C),C})}_createAnimationTracks(A,Q,J,K,C){let U=[],Y=A.name?A.name:A.uuid,Z=[];if(O4[C.path]===O4.weights)A.traverse(function($){if($.morphTargetInfluences)Z.push($.name?$.name:$.uuid)});else Z.push(Y);let X;switch(O4[C.path]){case O4.weights:X=Y6;break;case O4.rotation:X=s8;break;case O4.position:case O4.scale:X=h8;break;default:switch(J.itemSize){case 1:X=Y6;break;case 2:case 3:default:X=h8;break}break}let E=K.interpolation!==void 0?kK1[K.interpolation]:t5,H=this._getArrayFromAccessor(J);for(let $=0,I=Z.length;$=2.0 are supported."));return}let X=new hf(C,{path:Q||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});X.fileLoader.setRequestHeader(this.requestHeader);for(let E=0;E=0&&Y[H]===void 0)console.warn('THREE.GLTFLoader: Unknown extension "'+H+'".')}}X.setExtensions(U),X.setPlugins(Y),X.parse(J,K)}parseAsync(A,Q){let J=this;return new Promise(function(K,C){J.parse(A,Q,K,C)})}}function bK1(){let A={};return{get:function(Q){return A[Q]},add:function(Q,J){A[Q]=J},remove:function(Q){delete A[Q]},removeAll:function(){A={}}}}var nA={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class Hf{constructor(A){this.parser=A,this.name=nA.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let A=this.parser,Q=this.parser.json.nodes||[];for(let J=0,K=Q.length;J=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");else return null;return Q.loadTextureImage(A,C.source,U)}}class wf{constructor(A){this.parser=A,this.name=nA.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(A){let Q=this.name,J=this.parser,K=J.json,C=K.textures[A];if(!C.extensions||!C.extensions[Q])return null;let U=C.extensions[Q],Y=K.images[U.source],Z=J.textureLoader;if(Y.uri){let X=J.options.manager.getHandler(Y.uri);if(X!==null)Z=X}return this.detectSupport().then(function(X){if(X)return J.loadTextureImage(A,U.source,Z);if(K.extensionsRequired&&K.extensionsRequired.indexOf(Q)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return J.loadTexture(A)})}detectSupport(){if(!this.isSupported)this.isSupported=new Promise(function(A){let Q=new Image;Q.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",Q.onload=Q.onerror=function(){A(Q.height===1)}});return this.isSupported}}class Pf{constructor(A){this.parser=A,this.name=nA.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(A){let Q=this.name,J=this.parser,K=J.json,C=K.textures[A];if(!C.extensions||!C.extensions[Q])return null;let U=C.extensions[Q],Y=K.images[U.source],Z=J.textureLoader;if(Y.uri){let X=J.options.manager.getHandler(Y.uri);if(X!==null)Z=X}return this.detectSupport().then(function(X){if(X)return J.loadTextureImage(A,U.source,Z);if(K.extensionsRequired&&K.extensionsRequired.indexOf(Q)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return J.loadTexture(A)})}detectSupport(){if(!this.isSupported)this.isSupported=new Promise(function(A){let Q=new Image;Q.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",Q.onload=Q.onerror=function(){A(Q.height===1)}});return this.isSupported}}class _f{constructor(A){this.name=nA.EXT_MESHOPT_COMPRESSION,this.parser=A}loadBufferView(A){let Q=this.parser.json,J=Q.bufferViews[A];if(J.extensions&&J.extensions[this.name]){let K=J.extensions[this.name],C=this.parser.getDependency("buffer",K.buffer),U=this.parser.options.meshoptDecoder;if(!U||!U.supported)if(Q.extensionsRequired&&Q.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");else return null;return C.then(function(Y){let Z=K.byteOffset||0,X=K.byteLength||0,E=K.count,H=K.byteStride,$=new Uint8Array(Y,Z,X);if(U.decodeGltfBufferAsync)return U.decodeGltfBufferAsync(E,H,$,K.mode,K.filter).then(function(I){return I.buffer});else return U.ready.then(function(){let I=new ArrayBuffer(E*H);return U.decodeGltfBuffer(new Uint8Array(I),E,H,$,K.mode,K.filter),I})})}else return null}}class Tf{constructor(A){this.name=nA.EXT_MESH_GPU_INSTANCING,this.parser=A}createNodeMesh(A){let Q=this.parser.json,J=Q.nodes[A];if(!J.extensions||!J.extensions[this.name]||J.mesh===void 0)return null;let K=Q.meshes[J.mesh];for(let X of K.primitives)if(X.mode!==f9.TRIANGLES&&X.mode!==f9.TRIANGLE_STRIP&&X.mode!==f9.TRIANGLE_FAN&&X.mode!==void 0)return null;let U=J.extensions[this.name].attributes,Y=[],Z={};for(let X in U)Y.push(this.parser.getDependency("accessor",U[X]).then((E)=>{return Z[X]=E,Z[X]}));if(Y.length<1)return null;return Y.push(this.parser.createNodeMesh(A)),Promise.all(Y).then((X)=>{let E=X.pop(),H=E.isGroup?E.children:[E],$=X[0].count,I=[];for(let N of H){let F=new Y0,V=new I1,D=new t0,L=new I1(1,1,1),R=new A3(N.geometry,N.material,$);for(let M=0;M<$;M++){if(Z.TRANSLATION)V.fromBufferAttribute(Z.TRANSLATION,M);if(Z.ROTATION)D.fromBufferAttribute(Z.ROTATION,M);if(Z.SCALE)L.fromBufferAttribute(Z.SCALE,M);R.setMatrixAt(M,F.compose(V,D,L))}for(let M in Z)if(M==="_COLOR_0"){let T=Z[M];R.instanceColor=new K9(T.array,T.itemSize,T.normalized)}else if(M!=="TRANSLATION"&&M!=="ROTATION"&&M!=="SCALE")N.geometry.setAttribute(M,Z[M]);AA.prototype.copy.call(R,N),this.parser.assignFinalMaterial(R),I.push(R)}if(E.isGroup)return E.clear(),E.add(...I),E;return I[0]})}}var kf="glTF",uZ=12,Bf={JSON:1313821514,BIN:5130562};class Sf{constructor(A){this.name=nA.KHR_BINARY_GLTF,this.content=null,this.body=null;let Q=new DataView(A,0,uZ),J=/*@__PURE__*/new TextDecoder;if(this.header={magic:J.decode(new Uint8Array(A.slice(0,4))),version:Q.getUint32(4,!0),length:Q.getUint32(8,!0)},this.header.magic!==kf)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");else if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");let K=this.header.length-uZ,C=new DataView(A,uZ),U=0;while(U0||A.search(/^data\:image\/jpeg/)===0)return"image/jpeg";if(A.search(/\.webp($|\?)/i)>0||A.search(/^data\:image\/webp/)===0)return"image/webp";return"image/png"}var nK1=new Y0;class hf{constructor(A={},Q={}){this.json=A,this.extensions={},this.plugins={},this.options=Q,this.cache=new bK1,this.associations=/*@__PURE__*/new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let J=!1,K=-1,C=!1,U=-1;if(typeof navigator!=="undefined"){let Y=navigator.userAgent;J=/^((?!chrome|android).)*safari/i.test(Y)===!0;let Z=Y.match(/Version\/(\d+)/);K=J&&Z?parseInt(Z[1],10):-1,C=Y.indexOf("Firefox")>-1,U=C?Y.match(/Firefox\/([0-9]+)\./)[1]:-1}if(typeof createImageBitmap==="undefined"||J&&K<17||C&&U<98)this.textureLoader=new J8(this.options.manager);else this.textureLoader=new sQ(this.options.manager);if(this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new KA(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials")this.fileLoader.setWithCredentials(!0)}setExtensions(A){this.extensions=A}setPlugins(A){this.plugins=A}parse(A,Q){let J=this,K=this.json,C=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(U){return U._markDefs&&U._markDefs()}),Promise.all(this._invokeAll(function(U){return U.beforeRoot&&U.beforeRoot()})).then(function(){return Promise.all([J.getDependencies("scene"),J.getDependencies("animation"),J.getDependencies("camera")])}).then(function(U){let Y={scene:U[0][K.scene||0],scenes:U[0],animations:U[1],cameras:U[2],asset:K.asset,parser:J,userData:{}};return QJ(C,Y,K),C7(Y,K),Promise.all(J._invokeAll(function(Z){return Z.afterRoot&&Z.afterRoot(Y)})).then(function(){for(let Z of Y.scenes)Z.updateMatrixWorld();A(Y)})}).catch(Q)}_markDefs(){let A=this.json.nodes||[],Q=this.json.skins||[],J=this.json.meshes||[];for(let K=0,C=Q.length;K{let Z=this.associations.get(U);if(Z!=null)this.associations.set(Y,Z);for(let[X,E]of U.children.entries())C(E,Y.children[X])};return C(J,K),K.name+="_instance_"+A.uses[Q]++,K}_invokeOne(A){let Q=Object.values(this.plugins);Q.push(this);for(let J=0;J=2)V.setY(f,h[y*Z+1]);if(Z>=3)V.setZ(f,h[y*Z+2]);if(Z>=4)V.setW(f,h[y*Z+3]);if(Z>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}V.normalized=N}return V})}loadTexture(A){let Q=this.json,J=this.options,C=Q.textures[A].source,U=Q.images[C],Y=this.textureLoader;if(U.uri){let Z=J.manager.getHandler(U.uri);if(Z!==null)Y=Z}return this.loadTextureImage(A,C,Y)}loadTextureImage(A,Q,J){let K=this,C=this.json,U=C.textures[A],Y=C.images[Q],Z=(Y.uri||Y.bufferView)+":"+U.sampler;if(this.textureCache[Z])return this.textureCache[Z];let X=this.loadImageSource(Q,J).then(function(E){if(E.flipY=!1,E.name=U.name||Y.name||"",E.name===""&&typeof Y.uri==="string"&&Y.uri.startsWith("data:image/")===!1)E.name=Y.uri;let $=(C.samplers||{})[U.sampler]||{};return E.magFilter=Xf[$.magFilter]||HA,E.minFilter=Xf[$.minFilter]||o2,E.wrapS=Ef[$.wrapS]||A2,E.wrapT=Ef[$.wrapT]||A2,K.associations.set(E,{textures:A}),E}).catch(function(){return null});return this.textureCache[Z]=X,X}loadImageSource(A,Q){let J=this,K=this.json,C=this.options;if(this.sourceCache[A]!==void 0)return this.sourceCache[A].then((H)=>H.clone());let U=K.images[A],Y=self.URL||self.webkitURL,Z=U.uri||"",X=!1;if(U.bufferView!==void 0)Z=J.getDependency("bufferView",U.bufferView).then(function(H){X=!0;let $=new Blob([H],{type:U.mimeType});return Z=Y.createObjectURL($),Z});else if(U.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+A+" is missing URI and bufferView");let E=Promise.resolve(Z).then(function(H){return new Promise(function($,I){let N=$;if(Q.isImageBitmapLoader===!0)N=function(F){let V=new J2(F);V.needsUpdate=!0,$(V)};Q.load(A8.resolveURL(H,C.path),N,void 0,I)})}).then(function(H){if(X===!0)Y.revokeObjectURL(Z);return C7(H,U),H.userData.mimeType=U.mimeType||lK1(U.uri),H}).catch(function(H){throw console.error("THREE.GLTFLoader: Couldn't load texture",Z),H});return this.sourceCache[A]=E,E}assignTexture(A,Q,J,K){let C=this;return this.getDependency("texture",J.index).then(function(U){if(!U)return null;if(J.texCoord!==void 0&&J.texCoord>0)U=U.clone(),U.channel=J.texCoord;if(C.extensions[nA.KHR_TEXTURE_TRANSFORM]){let Y=J.extensions!==void 0?J.extensions[nA.KHR_TEXTURE_TRANSFORM]:void 0;if(Y){let Z=C.associations.get(U);U=C.extensions[nA.KHR_TEXTURE_TRANSFORM].extendTexture(U,Y),C.associations.set(U,Z)}}if(K!==void 0)U.colorSpace=K;return A[Q]=U,U})}assignFinalMaterial(A){let{geometry:Q,material:J}=A,K=Q.attributes.tangent===void 0,C=Q.attributes.color!==void 0,U=Q.attributes.normal===void 0;if(A.isPoints){let Y="PointsMaterial:"+J.uuid,Z=this.cache.get(Y);if(!Z)Z=new X6,_2.prototype.copy.call(Z,J),Z.color.copy(J.color),Z.map=J.map,Z.sizeAttenuation=!1,this.cache.add(Y,Z);J=Z}else if(A.isLine){let Y="LineBasicMaterial:"+J.uuid,Z=this.cache.get(Y);if(!Z)Z=new pA,_2.prototype.copy.call(Z,J),Z.color.copy(J.color),Z.map=J.map,this.cache.add(Y,Z);J=Z}if(K||C||U){let Y="ClonedMaterial:"+J.uuid+":";if(K)Y+="derivative-tangents:";if(C)Y+="vertex-colors:";if(U)Y+="flat-shading:";let Z=this.cache.get(Y);if(!Z){if(Z=J.clone(),C)Z.vertexColors=!0;if(U)Z.flatShading=!0;if(K){if(Z.normalScale)Z.normalScale.y*=-1;if(Z.clearcoatNormalScale)Z.clearcoatNormalScale.y*=-1}this.cache.add(Y,Z),this.associations.set(Z,this.associations.get(J))}J=Z}A.material=J}getMaterialType(){return p2}loadMaterial(A){let Q=this,J=this.json,K=this.extensions,C=J.materials[A],U,Y={},Z=C.extensions||{},X=[];if(Z[nA.KHR_MATERIALS_UNLIT]){let H=K[nA.KHR_MATERIALS_UNLIT];U=H.getMaterialType(),X.push(H.extendParams(Y,C,Q))}else{let H=C.pbrMetallicRoughness||{};if(Y.color=new y1(1,1,1),Y.opacity=1,Array.isArray(H.baseColorFactor)){let $=H.baseColorFactor;Y.color.setRGB($[0],$[1],$[2],GA),Y.opacity=$[3]}if(H.baseColorTexture!==void 0)X.push(Q.assignTexture(Y,"map",H.baseColorTexture,GA));if(Y.metalness=H.metallicFactor!==void 0?H.metallicFactor:1,Y.roughness=H.roughnessFactor!==void 0?H.roughnessFactor:1,H.metallicRoughnessTexture!==void 0)X.push(Q.assignTexture(Y,"metalnessMap",H.metallicRoughnessTexture)),X.push(Q.assignTexture(Y,"roughnessMap",H.metallicRoughnessTexture));U=this._invokeOne(function($){return $.getMaterialType&&$.getMaterialType(A)}),X.push(Promise.all(this._invokeAll(function($){return $.extendMaterialParams&&$.extendMaterialParams(A,Y)})))}if(C.doubleSided===!0)Y.side=VA;let E=C.alphaMode||MR.OPAQUE;if(E===MR.BLEND)Y.transparent=!0,Y.depthWrite=!1;else if(Y.transparent=!1,E===MR.MASK)Y.alphaTest=C.alphaCutoff!==void 0?C.alphaCutoff:0.5;if(C.normalTexture!==void 0&&U!==BA){if(X.push(Q.assignTexture(Y,"normalMap",C.normalTexture)),Y.normalScale=new p1(1,1),C.normalTexture.scale!==void 0){let H=C.normalTexture.scale;Y.normalScale.set(H,H)}}if(C.occlusionTexture!==void 0&&U!==BA){if(X.push(Q.assignTexture(Y,"aoMap",C.occlusionTexture)),C.occlusionTexture.strength!==void 0)Y.aoMapIntensity=C.occlusionTexture.strength}if(C.emissiveFactor!==void 0&&U!==BA){let H=C.emissiveFactor;Y.emissive=new y1().setRGB(H[0],H[1],H[2],GA)}if(C.emissiveTexture!==void 0&&U!==BA)X.push(Q.assignTexture(Y,"emissiveMap",C.emissiveTexture,CA));return Promise.all(X).then(function(){let H=new U(Y);if(C.name)H.name=C.name;if(C7(H,C),Q.associations.set(H,{materials:A}),C.extensions)QJ(K,H,C);return H})}createUniqueName(A){let Q=RA.sanitizeNodeName(A||"");if(Q in this.nodeNamesUsed)return Q+"_"+ ++this.nodeNamesUsed[Q];else return this.nodeNamesUsed[Q]=0,Q}loadGeometries(A){let Q=this,J=this.extensions,K=this.primitiveCache;function C(Y){return J[nA.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(Y,Q).then(function(Z){return $f(Z,Y,Q)})}let U=[];for(let Y=0,Z=A.length;Y0)cK1(D,C);if(D.name=Q.createUniqueName(C.name||"mesh_"+A),C7(D,C),V.extensions)QJ(K,D,V);Q.assignFinalMaterial(D),H.push(D)}for(let I=0,N=H.length;I1)E=new cA;else if(X.length===1)E=X[0];else E=new AA;if(E!==X[0])for(let H=0,$=X.length;H<$;H++)E.add(X[H]);if(C.name)E.userData.name=C.name,E.name=U;if(C7(E,C),C.extensions)QJ(J,E,C);if(C.matrix!==void 0){let H=new Y0;H.fromArray(C.matrix),E.applyMatrix4(H)}else{if(C.translation!==void 0)E.position.fromArray(C.translation);if(C.rotation!==void 0)E.quaternion.fromArray(C.rotation);if(C.scale!==void 0)E.scale.fromArray(C.scale)}if(!K.associations.has(E))K.associations.set(E,{});return K.associations.get(E).nodes=A,E}),this.nodeCache[A]}loadScene(A){let Q=this.extensions,J=this.json.scenes[A],K=this,C=new cA;if(J.name)C.name=K.createUniqueName(J.name);if(C7(C,J),J.extensions)QJ(Q,C,J);let U=J.nodes||[],Y=[];for(let Z=0,X=U.length;Z{let H=/*@__PURE__*/new Map;for(let[$,I]of K.associations)if($ instanceof _2||$ instanceof J2)H.set($,I);return E.traverse(($)=>{let I=K.associations.get($);if(I!=null)H.set($,I)}),H};return K.associations=X(C),C})}_createAnimationTracks(A,Q,J,K,C){let U=[],Y=A.name?A.name:A.uuid,Z=[];if(N4[C.path]===N4.weights)A.traverse(function($){if($.morphTargetInfluences)Z.push($.name?$.name:$.uuid)});else Z.push(Y);let X;switch(N4[C.path]){case N4.weights:X=Y6;break;case N4.rotation:X=s8;break;case N4.position:case N4.scale:X=h8;break;default:switch(J.itemSize){case 1:X=Y6;break;case 2:case 3:default:X=h8;break}break}let E=K.interpolation!==void 0?pK1[K.interpolation]:t5,H=this._getArrayFromAccessor(J);for(let $=0,I=Z.length;$0===N>H)N=H,J.value=(N-H)/U;return N}function ff(A,Q,J,K,C=1/0,U,Y){K=Math.max(0.0001,K);let Z=2/K,X=Z*U,E=1/(1+X+0.48*X*X+0.235*X*X*X),H=Q.x,$=Q.y,I=Q.z,N=A.x-H,F=A.y-$,V=A.z-I,D=H,L=$,R=I,M=C*K,T=M*M,h=N*N+F*F+V*V;if(h>T){let O=Math.sqrt(h);N=N/O*M,F=F/O*M,V=V/O*M}H=A.x-N,$=A.y-F,I=A.z-V;let y=(J.x+Z*N)*U,g=(J.y+Z*F)*U,f=(J.z+Z*V)*U;J.x=(J.x-Z*y)*E,J.y=(J.y-Z*g)*E,J.z=(J.z-Z*f)*E,Y.x=H+(N+y)*E,Y.y=$+(F+g)*E,Y.z=I+(V+f)*E;let u=D-A.x,d=L-A.y,n=R-A.z,B=Y.x-D,q=Y.y-L,P=Y.z-R;if(u*B+d*q+n*P>0)Y.x=D,Y.y=L,Y.z=R,J.x=(Y.x-D)/U,J.y=(Y.y-L)/U,J.z=(Y.z-R)/U;return Y}function SR(A,Q){Q.set(0,0),A.forEach((J)=>{Q.x+=J.clientX,Q.y+=J.clientY}),Q.x/=A.length,Q.y/=A.length}function jR(A,Q){if(L4(A))return console.warn(`${Q} is not supported in OrthographicCamera`),!0;return!1}class nf{constructor(){this._listeners={}}addEventListener(A,Q){let J=this._listeners;if(J[A]===void 0)J[A]=[];if(J[A].indexOf(Q)===-1)J[A].push(Q)}hasEventListener(A,Q){let J=this._listeners;return J[A]!==void 0&&J[A].indexOf(Q)!==-1}removeEventListener(A,Q){let K=this._listeners[A];if(K!==void 0){let C=K.indexOf(Q);if(C!==-1)K.splice(C,1)}}removeAllEventListeners(A){if(!A){this._listeners={};return}if(Array.isArray(this._listeners[A]))this._listeners[A].length=0}dispatchEvent(A){let J=this._listeners[A.type];if(J!==void 0){A.target=this;let K=J.slice(0);for(let C=0,U=K.length;C{},this._enabled=!0,this._state=G0.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=TC.NONE,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new NA.Vector3,this._focalOffsetVelocity=new NA.Vector3,this._zoomVelocity={value:0},this._truckInternal=(D,L,R)=>{let M,T;if(JJ(this._camera)){let h=yA.copy(this._camera.position).sub(this._target),y=this._camera.getEffectiveFOV()*mZ,g=h.length()*Math.tan(y*0.5);M=this.truckSpeed*D*g/this._elementRect.height,T=this.truckSpeed*L*g/this._elementRect.height}else if(L4(this._camera)){let h=this._camera;M=D*(h.right-h.left)/h.zoom/this._elementRect.width,T=L*(h.top-h.bottom)/h.zoom/this._elementRect.height}else return;if(this.verticalDragToForward)R?this.setFocalOffset(this._focalOffsetEnd.x+M,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(M,0,!0),this.forward(-T,!0);else R?this.setFocalOffset(this._focalOffsetEnd.x+M,this._focalOffsetEnd.y+T,this._focalOffsetEnd.z,!0):this.truck(M,T,!0)},this._rotateInternal=(D,L)=>{let R=kC*this.azimuthRotateSpeed*D/this._elementRect.height,M=kC*this.polarRotateSpeed*L/this._elementRect.height;this.rotate(R,M,!0)},this._dollyInternal=(D,L,R)=>{let M=Math.pow(0.95,-D*this.dollySpeed),T=this._sphericalEnd.radius,h=this._sphericalEnd.radius*M,y=V5(h,this.minDistance,this.maxDistance),g=y-h;if(this.infinityDolly&&this.dollyToCursor)this._dollyToNoClamp(h,!0);else if(this.infinityDolly&&!this.dollyToCursor)this.dollyInFixed(g,!0),this._dollyToNoClamp(y,!0);else this._dollyToNoClamp(y,!0);if(this.dollyToCursor)this._changedDolly+=(this.infinityDolly?h:y)-T,this._dollyControlCoord.set(L,R);this._lastDollyDirection=Math.sign(-D)},this._zoomInternal=(D,L,R)=>{let M=Math.pow(0.95,D*this.dollySpeed),T=this._zoom,h=this._zoom*M;if(this.zoomTo(h,!0),this.dollyToCursor)this._changedZoom+=h-T,this._dollyControlCoord.set(L,R)},typeof NA==="undefined")console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information.");this._camera=A,this._yAxisUpSpace=new NA.Quaternion().setFromUnitVectors(this._camera.up,NG),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=G0.NONE,this._target=new NA.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new NA.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new NA.Spherical().setFromVector3(yA.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new NA.Vector3,new NA.Vector3,new NA.Vector3,new NA.Vector3],this._updateNearPlaneCorners(),this._boundary=new NA.Box3(new NA.Vector3(-1/0,-1/0,-1/0),new NA.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new NA.Vector2,this.mouseButtons={left:G0.ROTATE,middle:G0.DOLLY,right:G0.TRUCK,wheel:JJ(this._camera)?G0.DOLLY:L4(this._camera)?G0.ZOOM:G0.NONE},this.touches={one:G0.TOUCH_ROTATE,two:JJ(this._camera)?G0.TOUCH_DOLLY_TRUCK:L4(this._camera)?G0.TOUCH_ZOOM_TRUCK:G0.NONE,three:G0.TOUCH_TRUCK};let J=new NA.Vector2,K=new NA.Vector2,C=new NA.Vector2,U=(D)=>{if(!this._enabled||!this._domElement)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){let M=this._domElement.getBoundingClientRect(),T=D.clientX/M.width,h=D.clientY/M.height;if(Tthis._interactiveArea.right||hthis._interactiveArea.bottom)return}let L=D.pointerType!=="mouse"?null:(D.buttons&i2.LEFT)===i2.LEFT?i2.LEFT:(D.buttons&i2.MIDDLE)===i2.MIDDLE?i2.MIDDLE:(D.buttons&i2.RIGHT)===i2.RIGHT?i2.RIGHT:null;if(L!==null){let M=this._findPointerByMouseButton(L);M&&this._disposePointer(M)}if((D.buttons&i2.LEFT)===i2.LEFT&&this._lockedPointer)return;let R={pointerId:D.pointerId,clientX:D.clientX,clientY:D.clientY,deltaX:0,deltaY:0,mouseButton:L};this._activePointers.push(R),this._domElement.ownerDocument.removeEventListener("pointermove",Y,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",Z),this._domElement.ownerDocument.addEventListener("pointermove",Y,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",Z),this._isDragging=!0,$(D)},Y=(D)=>{if(D.cancelable)D.preventDefault();let L=D.pointerId,R=this._lockedPointer||this._findPointerById(L);if(!R)return;if(R.clientX=D.clientX,R.clientY=D.clientY,R.deltaX=D.movementX,R.deltaY=D.movementY,this._state=0,D.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else{if(!this._isDragging&&this._lockedPointer||this._isDragging&&(D.buttons&i2.LEFT)===i2.LEFT)this._state=this._state|this.mouseButtons.left;if(this._isDragging&&(D.buttons&i2.MIDDLE)===i2.MIDDLE)this._state=this._state|this.mouseButtons.middle;if(this._isDragging&&(D.buttons&i2.RIGHT)===i2.RIGHT)this._state=this._state|this.mouseButtons.right}I()},Z=(D)=>{let L=this._findPointerById(D.pointerId);if(L&&L===this._lockedPointer)return;if(L&&this._disposePointer(L),D.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=G0.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=G0.NONE;N()},X=-1,E=(D)=>{if(!this._domElement)return;if(!this._enabled||this.mouseButtons.wheel===G0.NONE)return;if(this._interactiveArea.left!==0||this._interactiveArea.top!==0||this._interactiveArea.width!==1||this._interactiveArea.height!==1){let h=this._domElement.getBoundingClientRect(),y=D.clientX/h.width,g=D.clientY/h.height;if(ythis._interactiveArea.right||gthis._interactiveArea.bottom)return}if(D.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===G0.ROTATE||this.mouseButtons.wheel===G0.TRUCK){let h=performance.now();if(X-h<1000)this._getClientRect(this._elementRect);X=h}let L=iK1?-1:-3,R=D.deltaMode===1?D.deltaY/L:D.deltaY/(L*10),M=this.dollyToCursor?(D.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,T=this.dollyToCursor?(D.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case G0.ROTATE:{this._rotateInternal(D.deltaX,D.deltaY),this._isUserControllingRotate=!0;break}case G0.TRUCK:{this._truckInternal(D.deltaX,D.deltaY,!1),this._isUserControllingTruck=!0;break}case G0.OFFSET:{this._truckInternal(D.deltaX,D.deltaY,!0),this._isUserControllingOffset=!0;break}case G0.DOLLY:{this._dollyInternal(-R,M,T),this._isUserControllingDolly=!0;break}case G0.ZOOM:{this._zoomInternal(-R,M,T),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},H=(D)=>{if(!this._domElement||!this._enabled)return;if(this.mouseButtons.right===b8.ACTION.NONE){let L=D instanceof PointerEvent?D.pointerId:0,R=this._findPointerById(L);R&&this._disposePointer(R),this._domElement.ownerDocument.removeEventListener("pointermove",Y,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",Z);return}D.preventDefault()},$=(D)=>{if(!this._enabled)return;if(SR(this._activePointers,m6),this._getClientRect(this._elementRect),J.copy(m6),K.copy(m6),this._activePointers.length>=2){let R=m6.x-this._activePointers[1].clientX,M=m6.y-this._activePointers[1].clientY,T=Math.sqrt(R*R+M*M);C.set(0,T);let h=(this._activePointers[0].clientX+this._activePointers[1].clientX)*0.5,y=(this._activePointers[0].clientY+this._activePointers[1].clientY)*0.5;K.set(h,y)}if(this._state=0,!D){if(this._lockedPointer)this._state=this._state|this.mouseButtons.left}else if("pointerType"in D&&D.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else{if(!this._lockedPointer&&(D.buttons&i2.LEFT)===i2.LEFT)this._state=this._state|this.mouseButtons.left;if((D.buttons&i2.MIDDLE)===i2.MIDDLE)this._state=this._state|this.mouseButtons.middle;if((D.buttons&i2.RIGHT)===i2.RIGHT)this._state=this._state|this.mouseButtons.right}if((this._state&G0.ROTATE)===G0.ROTATE||(this._state&G0.TOUCH_ROTATE)===G0.TOUCH_ROTATE||(this._state&G0.TOUCH_DOLLY_ROTATE)===G0.TOUCH_DOLLY_ROTATE||(this._state&G0.TOUCH_ZOOM_ROTATE)===G0.TOUCH_ZOOM_ROTATE)this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0;if((this._state&G0.TRUCK)===G0.TRUCK||(this._state&G0.TOUCH_TRUCK)===G0.TOUCH_TRUCK||(this._state&G0.TOUCH_DOLLY_TRUCK)===G0.TOUCH_DOLLY_TRUCK||(this._state&G0.TOUCH_ZOOM_TRUCK)===G0.TOUCH_ZOOM_TRUCK)this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0);if((this._state&G0.DOLLY)===G0.DOLLY||(this._state&G0.TOUCH_DOLLY)===G0.TOUCH_DOLLY||(this._state&G0.TOUCH_DOLLY_TRUCK)===G0.TOUCH_DOLLY_TRUCK||(this._state&G0.TOUCH_DOLLY_OFFSET)===G0.TOUCH_DOLLY_OFFSET||(this._state&G0.TOUCH_DOLLY_ROTATE)===G0.TOUCH_DOLLY_ROTATE)this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0;if((this._state&G0.ZOOM)===G0.ZOOM||(this._state&G0.TOUCH_ZOOM)===G0.TOUCH_ZOOM||(this._state&G0.TOUCH_ZOOM_TRUCK)===G0.TOUCH_ZOOM_TRUCK||(this._state&G0.TOUCH_ZOOM_OFFSET)===G0.TOUCH_ZOOM_OFFSET||(this._state&G0.TOUCH_ZOOM_ROTATE)===G0.TOUCH_ZOOM_ROTATE)this._zoomEnd=this._zoom,this._zoomVelocity.value=0;if((this._state&G0.OFFSET)===G0.OFFSET||(this._state&G0.TOUCH_OFFSET)===G0.TOUCH_OFFSET||(this._state&G0.TOUCH_DOLLY_OFFSET)===G0.TOUCH_DOLLY_OFFSET||(this._state&G0.TOUCH_ZOOM_OFFSET)===G0.TOUCH_ZOOM_OFFSET)this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0);this.dispatchEvent({type:"controlstart"})},I=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,SR(this._activePointers,m6);let L=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,R=L?-L.deltaX:K.x-m6.x,M=L?-L.deltaY:K.y-m6.y;if(K.copy(m6),(this._state&G0.ROTATE)===G0.ROTATE||(this._state&G0.TOUCH_ROTATE)===G0.TOUCH_ROTATE||(this._state&G0.TOUCH_DOLLY_ROTATE)===G0.TOUCH_DOLLY_ROTATE||(this._state&G0.TOUCH_ZOOM_ROTATE)===G0.TOUCH_ZOOM_ROTATE)this._rotateInternal(R,M),this._isUserControllingRotate=!0;if((this._state&G0.DOLLY)===G0.DOLLY||(this._state&G0.ZOOM)===G0.ZOOM){let T=this.dollyToCursor?(J.x-this._elementRect.x)/this._elementRect.width*2-1:0,h=this.dollyToCursor?(J.y-this._elementRect.y)/this._elementRect.height*-2+1:0,y=this.dollyDragInverted?-1:1;if((this._state&G0.DOLLY)===G0.DOLLY)this._dollyInternal(y*M*OG,T,h),this._isUserControllingDolly=!0;else this._zoomInternal(y*M*OG,T,h),this._isUserControllingZoom=!0}if((this._state&G0.TOUCH_DOLLY)===G0.TOUCH_DOLLY||(this._state&G0.TOUCH_ZOOM)===G0.TOUCH_ZOOM||(this._state&G0.TOUCH_DOLLY_TRUCK)===G0.TOUCH_DOLLY_TRUCK||(this._state&G0.TOUCH_ZOOM_TRUCK)===G0.TOUCH_ZOOM_TRUCK||(this._state&G0.TOUCH_DOLLY_OFFSET)===G0.TOUCH_DOLLY_OFFSET||(this._state&G0.TOUCH_ZOOM_OFFSET)===G0.TOUCH_ZOOM_OFFSET||(this._state&G0.TOUCH_DOLLY_ROTATE)===G0.TOUCH_DOLLY_ROTATE||(this._state&G0.TOUCH_ZOOM_ROTATE)===G0.TOUCH_ZOOM_ROTATE){let T=m6.x-this._activePointers[1].clientX,h=m6.y-this._activePointers[1].clientY,y=Math.sqrt(T*T+h*h),g=C.y-y;C.set(0,y);let f=this.dollyToCursor?(K.x-this._elementRect.x)/this._elementRect.width*2-1:0,u=this.dollyToCursor?(K.y-this._elementRect.y)/this._elementRect.height*-2+1:0;if((this._state&G0.TOUCH_DOLLY)===G0.TOUCH_DOLLY||(this._state&G0.TOUCH_DOLLY_ROTATE)===G0.TOUCH_DOLLY_ROTATE||(this._state&G0.TOUCH_DOLLY_TRUCK)===G0.TOUCH_DOLLY_TRUCK||(this._state&G0.TOUCH_DOLLY_OFFSET)===G0.TOUCH_DOLLY_OFFSET)this._dollyInternal(g*OG,f,u),this._isUserControllingDolly=!0;else this._zoomInternal(g*OG,f,u),this._isUserControllingZoom=!0}if((this._state&G0.TRUCK)===G0.TRUCK||(this._state&G0.TOUCH_TRUCK)===G0.TOUCH_TRUCK||(this._state&G0.TOUCH_DOLLY_TRUCK)===G0.TOUCH_DOLLY_TRUCK||(this._state&G0.TOUCH_ZOOM_TRUCK)===G0.TOUCH_ZOOM_TRUCK)this._truckInternal(R,M,!1),this._isUserControllingTruck=!0;if((this._state&G0.OFFSET)===G0.OFFSET||(this._state&G0.TOUCH_OFFSET)===G0.TOUCH_OFFSET||(this._state&G0.TOUCH_DOLLY_OFFSET)===G0.TOUCH_DOLLY_OFFSET||(this._state&G0.TOUCH_ZOOM_OFFSET)===G0.TOUCH_ZOOM_OFFSET)this._truckInternal(R,M,!0),this._isUserControllingOffset=!0;this.dispatchEvent({type:"control"})},N=()=>{if(SR(this._activePointers,m6),K.copy(m6),this._dragNeedsUpdate=!1,this._activePointers.length===0||this._activePointers.length===1&&this._activePointers[0]===this._lockedPointer)this._isDragging=!1;if(this._activePointers.length===0&&this._domElement)this._domElement.ownerDocument.removeEventListener("pointermove",Y,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",Z),this.dispatchEvent({type:"controlend"})};this.lockPointer=()=>{if(!this._enabled||!this._domElement)return;this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",Y,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",Z),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",F),this._domElement.ownerDocument.addEventListener("pointerlockerror",V),this._domElement.ownerDocument.addEventListener("pointermove",Y,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",Z),$()},this.unlockPointer=()=>{var D,L,R;if(this._lockedPointer!==null)this._disposePointer(this._lockedPointer),this._lockedPointer=null;(D=this._domElement)===null||D===void 0||D.ownerDocument.exitPointerLock(),(L=this._domElement)===null||L===void 0||L.ownerDocument.removeEventListener("pointerlockchange",F),(R=this._domElement)===null||R===void 0||R.ownerDocument.removeEventListener("pointerlockerror",V),this.cancel()};let F=()=>{if(!(this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement))this.unlockPointer()},V=()=>{this.unlockPointer()};if(this._addAllEventListeners=(D)=>{this._domElement=D,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",U),this._domElement.addEventListener("pointercancel",Z),this._domElement.addEventListener("wheel",E,{passive:!1}),this._domElement.addEventListener("contextmenu",H)},this._removeAllEventListeners=()=>{if(!this._domElement)return;this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",U),this._domElement.removeEventListener("pointercancel",Z),this._domElement.removeEventListener("wheel",E,{passive:!1}),this._domElement.removeEventListener("contextmenu",H),this._domElement.ownerDocument.removeEventListener("pointermove",Y,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",Z),this._domElement.ownerDocument.removeEventListener("pointerlockchange",F),this._domElement.ownerDocument.removeEventListener("pointerlockerror",V)},this.cancel=()=>{if(this._state===G0.NONE)return;this._state=G0.NONE,this._activePointers.length=0,N()},Q)this.connect(Q);this.update(0)}get camera(){return this._camera}set camera(A){this._camera=A,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(A){if(this._enabled=A,!this._domElement)return;if(A)this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none";else this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(A){if(this._spherical.radius===A&&this._sphericalEnd.radius===A)return;this._spherical.radius=A,this._sphericalEnd.radius=A,this._needsUpdate=!0}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(A){if(this._spherical.theta===A&&this._sphericalEnd.theta===A)return;this._spherical.theta=A,this._sphericalEnd.theta=A,this._needsUpdate=!0}get polarAngle(){return this._spherical.phi}set polarAngle(A){if(this._spherical.phi===A&&this._sphericalEnd.phi===A)return;this._spherical.phi=A,this._sphericalEnd.phi=A,this._needsUpdate=!0}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(A){this._boundaryEnclosesCamera=A,this._needsUpdate=!0}set interactiveArea(A){this._interactiveArea.width=V5(A.width,0,1),this._interactiveArea.height=V5(A.height,0,1),this._interactiveArea.x=V5(A.x,0,1-this._interactiveArea.width),this._interactiveArea.y=V5(A.y,0,1-this._interactiveArea.height)}addEventListener(A,Q){super.addEventListener(A,Q)}removeEventListener(A,Q){super.removeEventListener(A,Q)}rotate(A,Q,J=!1){return this.rotateTo(this._sphericalEnd.theta+A,this._sphericalEnd.phi+Q,J)}rotateAzimuthTo(A,Q=!1){return this.rotateTo(A,this._sphericalEnd.phi,Q)}rotatePolarTo(A,Q=!1){return this.rotateTo(this._sphericalEnd.theta,A,Q)}rotateTo(A,Q,J=!1){this._isUserControllingRotate=!1;let K=V5(A,this.minAzimuthAngle,this.maxAzimuthAngle),C=V5(Q,this.minPolarAngle,this.maxPolarAngle);if(this._sphericalEnd.theta=K,this._sphericalEnd.phi=C,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,!J)this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi;let U=!J||F2(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&F2(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(U)}dolly(A,Q=!1){return this.dollyTo(this._sphericalEnd.radius-A,Q)}dollyTo(A,Q=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=TC.NONE,this._changedDolly=0,this._dollyToNoClamp(V5(A,this.minDistance,this.maxDistance),Q)}_dollyToNoClamp(A,Q=!1){let J=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){let U=this._collisionTest(),Y=F2(U,this._spherical.radius);if(!(J>A)&&Y)return Promise.resolve();this._sphericalEnd.radius=Math.min(A,U)}else this._sphericalEnd.radius=A;if(this._needsUpdate=!0,!Q)this._spherical.radius=this._sphericalEnd.radius;let C=!Q||F2(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(C)}dollyInFixed(A,Q=!1){if(this._targetEnd.add(this._getCameraDirection(lZ).multiplyScalar(A)),!Q)this._target.copy(this._targetEnd);let J=!Q||F2(this._target.x,this._targetEnd.x,this.restThreshold)&&F2(this._target.y,this._targetEnd.y,this.restThreshold)&&F2(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(J)}zoom(A,Q=!1){return this.zoomTo(this._zoomEnd+A,Q)}zoomTo(A,Q=!1){if(this._isUserControllingZoom=!1,this._zoomEnd=V5(A,this.minZoom,this.maxZoom),this._needsUpdate=!0,!Q)this._zoom=this._zoomEnd;let J=!Q||F2(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(J)}pan(A,Q,J=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(A,Q,J)}truck(A,Q,J=!1){this._camera.updateMatrix(),U3.setFromMatrixColumn(this._camera.matrix,0),Z3.setFromMatrixColumn(this._camera.matrix,1),U3.multiplyScalar(A),Z3.multiplyScalar(-Q);let K=yA.copy(U3).add(Z3),C=Z2.copy(this._targetEnd).add(K);return this.moveTo(C.x,C.y,C.z,J)}forward(A,Q=!1){yA.setFromMatrixColumn(this._camera.matrix,0),yA.crossVectors(this._camera.up,yA),yA.multiplyScalar(A);let J=Z2.copy(this._targetEnd).add(yA);return this.moveTo(J.x,J.y,J.z,Q)}elevate(A,Q=!1){return yA.copy(this._camera.up).multiplyScalar(A),this.moveTo(this._targetEnd.x+yA.x,this._targetEnd.y+yA.y,this._targetEnd.z+yA.z,Q)}moveTo(A,Q,J,K=!1){this._isUserControllingTruck=!1;let C=yA.set(A,Q,J).sub(this._targetEnd);if(this._encloseToBoundary(this._targetEnd,C,this.boundaryFriction),this._needsUpdate=!0,!K)this._target.copy(this._targetEnd);let U=!K||F2(this._target.x,this._targetEnd.x,this.restThreshold)&&F2(this._target.y,this._targetEnd.y,this.restThreshold)&&F2(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(U)}lookInDirectionOf(A,Q,J,K=!1){let Y=yA.set(A,Q,J).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(Y.x,Y.y,Y.z,K)}fitToBox(A,Q,{cover:J=!1,paddingLeft:K=0,paddingRight:C=0,paddingBottom:U=0,paddingTop:Y=0}={}){let Z=[],X=A.isBox3?jC.copy(A):jC.setFromObject(A);if(X.isEmpty())console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve();let E=bf(this._sphericalEnd.theta,gf),H=bf(this._sphericalEnd.phi,gf);Z.push(this.rotateTo(E,H,Q));let $=yA.setFromSpherical(this._sphericalEnd).normalize(),I=df.setFromUnitVectors($,xR),N=F2(Math.abs($.y),1);if(N)I.multiply(hR.setFromAxisAngle(NG,E));I.multiply(this._yAxisUpSpaceInverse);let F=cf.makeEmpty();if(Z2.copy(X.min).applyQuaternion(I),F.expandByPoint(Z2),Z2.copy(X.min).setX(X.max.x).applyQuaternion(I),F.expandByPoint(Z2),Z2.copy(X.min).setY(X.max.y).applyQuaternion(I),F.expandByPoint(Z2),Z2.copy(X.max).setZ(X.min.z).applyQuaternion(I),F.expandByPoint(Z2),Z2.copy(X.min).setZ(X.max.z).applyQuaternion(I),F.expandByPoint(Z2),Z2.copy(X.max).setY(X.min.y).applyQuaternion(I),F.expandByPoint(Z2),Z2.copy(X.max).setX(X.min.x).applyQuaternion(I),F.expandByPoint(Z2),Z2.copy(X.max).applyQuaternion(I),F.expandByPoint(Z2),F.min.x-=K,F.min.y-=U,F.max.x+=C,F.max.y+=Y,I.setFromUnitVectors(xR,$),N)I.premultiply(hR.invert());I.premultiply(this._yAxisUpSpace);let V=F.getSize(yA),D=F.getCenter(Z2).applyQuaternion(I);if(JJ(this._camera)){let L=this.getDistanceToFitBox(V.x,V.y,V.z,J);Z.push(this.moveTo(D.x,D.y,D.z,Q)),Z.push(this.dollyTo(L,Q)),Z.push(this.setFocalOffset(0,0,0,Q))}else if(L4(this._camera)){let L=this._camera,R=L.right-L.left,M=L.top-L.bottom,T=J?Math.max(R/V.x,M/V.y):Math.min(R/V.x,M/V.y);Z.push(this.moveTo(D.x,D.y,D.z,Q)),Z.push(this.zoomTo(T,Q)),Z.push(this.setFocalOffset(0,0,0,Q))}return Promise.all(Z)}fitToSphere(A,Q){let J=[],C="isObject3D"in A?b8.createBoundingSphere(A,yR):yR.copy(A);if(J.push(this.moveTo(C.center.x,C.center.y,C.center.z,Q)),JJ(this._camera)){let U=this.getDistanceToFitSphere(C.radius);J.push(this.dollyTo(U,Q))}else if(L4(this._camera)){let U=this._camera.right-this._camera.left,Y=this._camera.top-this._camera.bottom,Z=2*C.radius,X=Math.min(U/Z,Y/Z);J.push(this.zoomTo(X,Q))}return J.push(this.setFocalOffset(0,0,0,Q)),Promise.all(J)}setLookAt(A,Q,J,K,C,U,Y=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=TC.NONE,this._changedDolly=0;let Z=Z2.set(K,C,U),X=yA.set(A,Q,J);if(this._targetEnd.copy(Z),this._sphericalEnd.setFromVector3(X.sub(Z).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,!Y)this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd);let E=!Y||F2(this._target.x,this._targetEnd.x,this.restThreshold)&&F2(this._target.y,this._targetEnd.y,this.restThreshold)&&F2(this._target.z,this._targetEnd.z,this.restThreshold)&&F2(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&F2(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&F2(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(E)}lerpLookAt(A,Q,J,K,C,U,Y,Z,X,E,H,$,I,N=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=TC.NONE,this._changedDolly=0;let F=yA.set(K,C,U),V=Z2.set(A,Q,J);p9.setFromVector3(V.sub(F).applyQuaternion(this._yAxisUpSpace));let D=SC.set(E,H,$),L=Z2.set(Y,Z,X);nZ.setFromVector3(L.sub(D).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(F.lerp(D,I));let R=nZ.theta-p9.theta,M=nZ.phi-p9.phi,T=nZ.radius-p9.radius;if(this._sphericalEnd.set(p9.radius+T*I,p9.phi+M*I,p9.theta+R*I),this.normalizeRotations(),this._needsUpdate=!0,!N)this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd);let h=!N||F2(this._target.x,this._targetEnd.x,this.restThreshold)&&F2(this._target.y,this._targetEnd.y,this.restThreshold)&&F2(this._target.z,this._targetEnd.z,this.restThreshold)&&F2(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&F2(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&F2(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(h)}setPosition(A,Q,J,K=!1){return this.setLookAt(A,Q,J,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,K)}setTarget(A,Q,J,K=!1){let C=this.getPosition(yA),U=this.setLookAt(C.x,C.y,C.z,A,Q,J,K);return this._sphericalEnd.phi=V5(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),U}setFocalOffset(A,Q,J,K=!1){if(this._isUserControllingOffset=!1,this._focalOffsetEnd.set(A,Q,J),this._needsUpdate=!0,!K)this._focalOffset.copy(this._focalOffsetEnd);let C=!K||F2(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&F2(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&F2(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(C)}setOrbitPoint(A,Q,J){this._camera.updateMatrixWorld(),U3.setFromMatrixColumn(this._camera.matrixWorldInverse,0),Z3.setFromMatrixColumn(this._camera.matrixWorldInverse,1),KJ.setFromMatrixColumn(this._camera.matrixWorldInverse,2);let K=yA.set(A,Q,J),C=K.distanceTo(this._camera.position),U=K.sub(this._camera.position);U3.multiplyScalar(U.x),Z3.multiplyScalar(U.y),KJ.multiplyScalar(U.z),yA.copy(U3).add(Z3).add(KJ),yA.z=yA.z+C,this.dollyTo(C,!1),this.setFocalOffset(-yA.x,yA.y,-yA.z,!1),this.moveTo(A,Q,J,!1)}setBoundary(A){if(!A){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(A),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(A,Q,J,K){if(A===null){this._viewport=null;return}if(this._viewport=this._viewport||new NA.Vector4,typeof A==="number")this._viewport.set(A,Q,J,K);else this._viewport.copy(A)}getDistanceToFitBox(A,Q,J,K=!1){if(jR(this._camera,"getDistanceToFitBox"))return this._spherical.radius;let C=A/Q,U=this._camera.getEffectiveFOV()*mZ,Y=this._camera.aspect;return((K?C>Y:CQ.pointerId===A)}_findPointerByMouseButton(A){return this._activePointers.find((Q)=>Q.mouseButton===A)}_disposePointer(A){this._activePointers.splice(this._activePointers.indexOf(A),1)}_encloseToBoundary(A,Q,J){let K=Q.lengthSq();if(K===0)return A;let C=Z2.copy(Q).add(A),Y=this._boundary.clampPoint(C,SC).sub(C),Z=Y.lengthSq();if(Z===0)return A.add(Q);else if(Z===K)return A;else if(J===0)return A.add(Q).add(Y);else{let X=1+J*Z/Q.dot(Y);return A.add(Z2.copy(Q).multiplyScalar(X)).add(Y.multiplyScalar(1-J))}}_updateNearPlaneCorners(){if(JJ(this._camera)){let A=this._camera,Q=A.near,J=A.getEffectiveFOV()*mZ,K=Math.tan(J*0.5)*Q,C=K*A.aspect;this._nearPlaneCorners[0].set(-C,-K,0),this._nearPlaneCorners[1].set(C,-K,0),this._nearPlaneCorners[2].set(C,K,0),this._nearPlaneCorners[3].set(-C,K,0)}else if(L4(this._camera)){let A=this._camera,Q=1/A.zoom,J=A.left*Q,K=A.right*Q,C=A.top*Q,U=A.bottom*Q;this._nearPlaneCorners[0].set(J,C,0),this._nearPlaneCorners[1].set(K,C,0),this._nearPlaneCorners[2].set(K,U,0),this._nearPlaneCorners[3].set(J,U,0)}}_collisionTest(){let A=1/0;if(!(this.colliderMeshes.length>=1))return A;if(jR(this._camera,"_collisionTest"))return A;let J=this._getTargetDirection(lZ);gR.lookAt(pf,J,this._camera.up);for(let K=0;K<4;K++){let C=Z2.copy(this._nearPlaneCorners[K]);C.applyMatrix4(gR);let U=SC.addVectors(this._target,C);LG.set(U,J),LG.far=this._spherical.radius+1;let Y=LG.intersectObjects(this.colliderMeshes);if(Y.length!==0&&Y[0].distance{let J=()=>{this.removeEventListener("rest",J),Q()};this.addEventListener("rest",J)})}_addAllEventListeners(A){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(A){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(A){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(A,Q=new NA.Sphere){let J=Q,K=J.center;jC.makeEmpty(),A.traverseVisible((U)=>{if(!U.isMesh)return;jC.expandByObject(U)}),jC.getCenter(K);let C=0;return A.traverseVisible((U)=>{if(!U.isMesh)return;let Y=U,Z=Y.geometry.clone();Z.applyMatrix4(Y.matrixWorld);let E=Z.attributes.position;for(let H=0,$=E.count;H<$;H++)yA.fromBufferAttribute(E,H),C=Math.max(C,K.distanceToSquared(yA))}),J.radius=Math.sqrt(C),J}}var sf={specularMode:0},of={ambient:new X0(0.8,0.8,0.8,1),diffuse:new X0(0.8,0.8,0.8,1),specular:new X0(0.1,0.1,0.1,1),specularPower:0.01,specularMode:0},FG=[{ambient:new X0(0.85,0.75,0.75,1),diffuse:new X0(0.75,0.75,0.75,1),specular:new X0(0.3,0.3,0.3,1),specularPower:1.2,specularMode:0},{ambient:new X0(1,1,1,1),diffuse:new X0(0.7,0.7,0.7,1),specular:new X0(0,0,0,1),specularPower:40,specularMode:1},{ambient:new X0(0.9,0.85,0.85,1),diffuse:new X0(0.75,0.75,0.75,1),specular:new X0(0.22,0.22,0.22,1),specularPower:1.5,specularMode:0},{ambient:new X0(0.85,0.75,0.75,1),diffuse:new X0(0.75,0.75,0.75,1),specular:new X0(0.3,0.3,0.3,1),specularPower:1.2,specularMode:0},{ambient:new X0(1,1,1,1),diffuse:new X0(0.7,0.7,0.7,1),specular:new X0(0.35,0.35,0.35,1),specularPower:10,specularMode:1},{ambient:new X0(0.75,0.75,0.75,1),diffuse:new X0(0.72,0.72,0.72,1),specular:new X0(0.3,0.3,0.3,1),specularPower:1.5,specularMode:0},{ambient:new X0(1,1,1,1),diffuse:new X0(0.7,0.7,0.7,1),specular:new X0(0,0,0,1),specularPower:40,specularMode:1},{ambient:new X0(1,1,1,1),diffuse:new X0(0.7,0.7,0.7,1),specular:new X0(0,0,0,1),specularPower:40,specularMode:1},{ambient:new X0(1,1,1,1),diffuse:new X0(0.7,0.7,0.7,1),specular:new X0(0,0,0,1),specularPower:40,specularMode:1},{ambient:new X0(0.95622,0.95622,0.95622,1),diffuse:new X0(0.49673,0.49673,0.49673,1),specular:new X0(0.24099,0.24099,0.24099,1),specularPower:3,specularMode:0},{ambient:new X0(0.95622,0.95622,0.95622,1),diffuse:new X0(1.08497,1.08497,1.08497,1),specular:new X0(0.2409,0.2409,0.2409,1),specularPower:3,specularMode:0}],bR=new X0(0.73,0.73,0.73,1),fR=new X0(0.6,0.6,0.6,1),pR=new X0(0.7,0.7,0.7,1),af=new X0(0.5,0.5,0.5,1),rf=new X0(0.9,0.9,0.9,1),tf=new X0(1,1,1,1),uR=new I1(-0.4531539381,0.4226179123,0.7848858833),ef=new I1(-0.35,1,0.8),Ap=new I1(-0.5,0.366,0.785),Qp=new X0(0.3,0.3,0.3,1),Jp=2,mR=[0.25098,0.27451,0.30588],Kp=[0.43922,0.12549,0.06275];var Cp=[0.75294,0.62745,0.18824],Yp=[0.05126930067255049,0.061246141699984984,0.07618418934386001],Up=[0.1620327698875954,0.014443805936996105,0.0051820344376627735];var Zp=[0.5271132835871205,0.3515313874944194,0.02955820686563641];var RG="#902010";var zG="#c0a030",DG={0:[0.824,0.118,0.078],1:[1,0.431,0.098],2:[1,0.847,0.125],3:[0.471,0.824,0.125],4:[0,0.471,0.188],5:[0.039,0.282,0.706],6:[0.235,0.667,0.871],7:[0.961,0.353,0.49],8:[0.451,0.157,0.678],9:[0.282,0.22,0.094],10:[0.878,0.878,0.878],11:[0.094,0.094,0.078]};function VG(A,Q=0){let J=new f1("div").class("tab-list"),K=new f1("div").class("tab-content");function C(U,Y,Z=!0){if(Z!==!1)J.qsa(".tab").forEach((X)=>X?.classOff("active")),U.classOn("active"),K.clear();Y(K)}for(let U of A){let Y=f2(new f1("div").classOn("tab").html(U.icon).on("click",async()=>{C(Y,U.select,U.update)}).appendTo(J),"hover","select_tab");switch(Q){case 0:Y.classOn("tab-square");break;case 1:Y.classOn("tab-rectangle");break}if(typeof U.type!=="undefined")Y.classOn(U.type)}return C(f1.from(J.elm.children[0]),A[0].select),{list:J,content:K}}var N0={loading:'',error:'',eyes:'',eyebrows:'',details:` - - - -`,save:'',scale:'',nose:'',mouth:'',glasses:'',mole:'',head:'',hair:'',hat:'',favoriteColor:'',facialHair:'',gender:'',genderMale:'',genderFemale:'',genderMaleLg:'',genderFemaleLg:'',favorite:'',special:'',sparkle:'',positionMoveDown:'',positionMoveUp:'',positionPushIn:'',positionPushOut:'',positionRotateCW:'',positionRotateCCW:'',positionSizeDown:'',positionSizeUp:'',positionStretchIn:'',positionStretchOut:'',positionHairFlip:'',positionHairFlipped:'',scaleShort:'',scaleTall:'',scaleThin:'',scaleFat:'',face:'',face_makeup:'',face_wrinkles:'',face_paint:'',color:'',contact_discord:'',contact_email:'',contact_github:''};var Bp=j2(MO(),1);var MG=()=>I2("hover");function D2(A){let Q;if(A.mii)if(A.miiIsNotMii===void 0||A.miiIsNotMii===!1)Q=new mA(A.mii.encode());else Q=A.mii;else Q={};let J=new f1("div").class("feature-set-container"),K=[];for(let C in A.entries){let U=A.entries[C],Y=C;if(U.validationProperty)Y=U.validationProperty;K.push({icon:U.label,async select(Z){let X=new f1("div").class("feature-set-group").appendTo(Z);if(U.header){let E=new f1("div").class("feature-set-header");if(U.headerIsHtml!==void 0)E.append(U.header);else E.text(U.header);X.append(E)}if("items"in U)for(let E of U.items){let H=Bp.default(String(Math.random()*21412855)),$=!0;if(E.forceRender!==void 0){if(E.forceRender===!1)$=!1}let I=()=>A.onChange(Q,$,E.part||0),N;if(U.validationFunction!==void 0)N=await U.validationFunction();else N=Q[Y];switch(E.type){case 0:let F=Y;if(E.property)F=E.property;let V=new f1("div").class("feature-item").on("pointerenter",MG).on("click",async()=>{let n;if(U.validationFunction)n=await U.validationFunction(E.property,E.value);else n=Q[F];if(n===E.value)return;if(Q[C]=E.value,I(),E.sound)I2(E.sound);else if(E.color)I2("select_color");else if(E.icon)I2("select_part");X.qsa(".feature-item").forEach((B)=>B.classOff("active")),V.classOn("active")}).appendTo(X);if(E.icon)V.html(E.icon);if(E.color)V.classOn("is-color").style({"--color":E.color});if(N===E.value)V.classOn("active");break;case 3:let D=new f1("div").class("feature-slider").on("pointerenter",MG).appendTo(X);if(E.iconStart){let n=new f1("span").html(E.iconStart).on("click",()=>{if(L.val(Number(L.getValue())-1),Q[E.property]=Number(L.getValue()),E.soundStart)I2(E.soundStart);else I2("select");I()});D.append(n)}let L=new f1("input").attr({type:"range",min:E.min,max:E.max}).id(H).appendTo(D);if(E.iconEnd){let n=new f1("span").html(E.iconEnd).on("click",()=>{if(L.val(Number(L.getValue())+1),Q[E.property]=Number(L.getValue()),E.soundEnd)I2(E.soundEnd);else I2("select");I()});D.append(n)}L.val(Q[E.property]),L.on("input",()=>{I2("slider_tick"),Q[E.property]=Number(L.getValue()),I()});break;case 2:let R=new f1("div").class("col").style({width:"100%",gap:"0","align-items":"center"}).appendTo(X);if(E.label!==void 0)new f1("span").text(E.label).appendTo(R);let M=new f1("div").class("feature-slider").appendTo(R);if(E.iconStart){let n=new f1("span").html(E.iconStart).on("click",()=>{if(T.val(Number(T.getValue())+(E.inverse?1:-1)),Q[E.property]=E.inverse?E.max+E.min-Number(T.getValue()):Number(T.getValue()),E.soundStart)I2(E.soundStart);else I2("select");I()});if(E.inverse)M.prepend(n);else M.append(n)}let T=new f1("input").attr({type:"range",min:E.min,max:E.max}).id(H);if(E.inverse)M.prepend(T);else M.append(T);if(E.iconEnd){let n=new f1("span").html(E.iconEnd).on("click",()=>{if(T.val(Number(T.getValue())+(E.inverse?-1:1)),Q[E.property]=E.inverse?E.max+E.min-Number(T.getValue()):Number(T.getValue()),E.soundEnd)I2(E.soundEnd);else I2("select");I()});if(E.inverse)M.prepend(n);else M.append(n)}T.val(E.inverse?E.max-Q[E.property]+E.min:Q[E.property]),T.on("change",()=>{let n=E.inverse?E.max+E.min-Number(T.getValue()):Number(T.getValue()),B=Q[E.property];if(E.soundStart!==void 0&&E.soundEnd!==void 0)if(n{I2("slider_tick")});break;case 4:let h=new f1("div").class("feature-switch-group").appendTo(X),y=new f1("div").class("feature-switch").id(H).appendTo(h),g=new f1("button").class("feature-switch-left").html(E.iconOff).appendTo(y),f=new f1("button").class("feature-switch-right").html(E.iconOn).appendTo(y),u=(n)=>{let B=n;if(E.isNumber)B=Number(B);if(Q[E.property]=B,n===!1)if(E.soundOff)I2(E.soundOff);else I2("select");if(n===!0)if(E.soundOn)I2(E.soundOn);else I2("select");I()};if(g.on("click",()=>{u(!1),g.classOn("active"),f.classOff("active")}),f.on("click",()=>{u(!0),g.classOff("active"),f.classOn("active")}),g.on("pointerenter",MG),f.on("pointerenter",MG),Q[E.property]==!0)g.classOff("active"),f.classOn("active");else g.classOn("active"),f.classOff("active");break;case 5:E.html.appendTo(X).on("click",E.select);break}}window.LazyLoad.update()}})}if(Object.keys(A.entries).length===1)K[0].select(J);else{let C=VG(K,1);C.list.appendTo(J),C.content.appendTo(J)}return J}var Xp={33:0,47:1,40:2,37:3,32:4,107:5,48:6,51:7,55:8,70:9,44:10,66:11,52:12,50:13,38:14,49:15,43:16,31:17,56:18,68:19,62:20,115:21,76:22,119:23,64:24,81:25,116:26,121:27,22:28,58:29,60:30,87:31,125:32,117:33,73:34,75:35,42:36,89:37,57:38,54:39,80:40,34:41,23:42,86:43,88:44,118:45,39:46,36:47,45:48,67:49,59:50,65:51,41:52,30:53,12:54,16:55,10:56,82:57,128:58,129:59,14:60,95:61,105:62,100:63,6:64,20:65,93:66,102:67,27:68,4:69,17:70,110:71,123:72,8:73,106:74,72:75,3:76,21:77,0:78,98:79,63:80,90:81,11:82,120:83,5:84,74:85,108:86,94:87,124:88,25:89,99:90,69:91,35:92,13:93,122:94,113:95,53:96,24:97,85:98,83:99,71:100,131:101,96:102,101:103,29:104,7:105,15:106,112:107,79:108,1:109,109:110,127:111,91:112,26:113,61:114,103:115,2:116,77:117,18:118,92:119,84:120,9:121,19:122,130:123,97:124,104:125,46:126,78:127,28:128,114:129,126:130,111:131},d6=[91,80,0,81,95,60,72,74,90,93,2,61,33,44,70,4,31,73,94,83,5,6,86,3,1,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,32,34,35,36,37,38,39,40,41,42,43,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,62,63,64,65,66,67,68,69,71,75,76,77,78,79,82,84,85,87,88,89,92,96,97,98,99],cR={0:0,7:1,1:2,4:3,5:4,6:5,3:6,2:7,8:8,9:9};function i8(A,Q){let J=[];for(let K in Q){let C=Q[K];J[C]=A[parseInt(K)]}return J=J.filter((K)=>K!==void 0),J}var l6=()=>({type:5,html:new f1("div").class("separator"),select(){}});var Ep=()=>({type:5,html:new f1("div").class("separator-gap-thin"),select(){}});function $p(A){let Q=A.mii;A.container.append(D2({mii:A.mii,onChange:(J,K,C)=>{A.callback(J,K,C),Q=J},entries:{eyeType:{label:"Type",items:_A(60).map((J)=>({type:0,value:J,icon:A.icons.eyes[J],part:1}))},eyeColor:{label:N0.color,validationProperty:"trueEyeColor",validationFunction(){if(Q.trueEyeColor>5)return Q.extEyeColor+6;else return Q.trueEyeColor},items:[..._A(6).map((J)=>({type:0,value:J,color:uE[J],part:1,property:"fflEyeColor"})),l6(),...i8(_A(100).map((J)=>({type:0,value:J+6,color:n2[J],part:1,property:"extEyeColor"})),d6)]},eyePosition:{label:"Position",items:[{type:2,property:"eyeYPosition",iconStart:N0.positionMoveUp,iconEnd:N0.positionMoveDown,soundStart:"position_down",soundEnd:"position_up",min:0,max:18,part:1,inverse:!0},{type:2,property:"eyeSpacing",iconStart:N0.positionPushIn,iconEnd:N0.positionPushOut,soundStart:"move_together",soundEnd:"move_apart",min:0,max:12,part:1},{type:2,property:"eyeRotation",iconStart:N0.positionRotateCW,iconEnd:N0.positionRotateCCW,soundStart:"rotate_cw",soundEnd:"rotate_ccw",min:0,max:7,part:1,inverse:!0},{type:2,property:"eyeScale",iconStart:N0.positionSizeDown,iconEnd:N0.positionSizeUp,soundStart:"scale_down",soundEnd:"scale_up",min:0,max:7,part:1},{type:2,property:"eyeVerticalStretch",iconStart:N0.positionStretchIn,iconEnd:N0.positionStretchOut,soundStart:"vert_stretch_down",soundEnd:"vert_stretch_up",min:0,max:6,part:1}]}}}))}function Hp(A){A.container.append(D2({mii:A.mii,onChange:A.callback,entries:{faceType:{label:N0.face,items:_A(12).map((Q)=>({type:0,value:Q,icon:A.icons.face[Q],part:0}))},makeupType:{label:N0.face_makeup,items:_A(12).map((Q)=>({type:0,value:Q,icon:A.icons.makeup[Q],part:0}))},wrinklesType:{label:N0.face_wrinkles,items:_A(12).map((Q)=>({type:0,value:Q,icon:A.icons.wrinkles[Q],part:0}))},skinColor:{label:N0.color,items:[..._A(6).map((Q)=>({type:0,value:Q,color:iv[Q],part:0})),l6(),...i8(_A(10).map((Q)=>({type:0,value:Q,color:DN[Q],part:0})),cR).slice(0,5),Ep(),...i8(_A(10).map((Q)=>({type:0,value:Q,color:DN[Q],part:0})),cR).slice(5)]},extFacePaintColor:{label:N0.face_paint,header:"Face paint is a CUSTOM property, and will not transfer to any other data formats.",items:[{type:0,forceRender:!0,value:0,icon:` - - - - -`,part:0},...i8(_A(100).map((Q)=>({type:0,value:Q+1,color:n2[Q],part:0,property:"extFacePaintColor"})),d6)]}}}))}function dR(A,Q,J,K,C){let U=String(performance.now());function Y(X){if(C){if(C.dirty=!0,K){if(K(X)){if(Z.classOff("invalid"),C)C.errors.set(A,!1);J(X)}else if(Z.classOn("invalid"),C)C.errors.set(A,!0)}}}let Z=new f1("input").id(U).attr({type:"text",value:Q}).on("input",(X)=>{let E=X.target;Y(E.value)});if(K)K(Q);return new f1("div").class("input-group").appendMany(new f1("label").attr({for:U}).text(A),Z)}function Gp(A){let Q=new mA(A.mii.encode()),J=(K,C)=>{return Q[K]=C,A.callback(Q,!1,0),!0};A.container.append(new f1("div").style({padding:"1rem",display:"flex","flex-direction":"column",gap:"1rem"}).appendMany(dR("Name",A.mii.miiName,(K)=>J("miiName",K.trim()),(K)=>{let C=QA.from(K,"utf16le");if(C.toString("utf16le").trim()==="")return!1;if(C.length<=20&&C.length!==0)return!0;return!1},A.editor),dR("Creator",A.mii.creatorName,(K)=>J("creatorName",K.trim()),(K)=>{let C=QA.from(K,"utf16le");if(C.toString("utf16le").trim()==="")return!1;if(C.length<=20)return!0;return!1},A.editor)))}function Wp(A){A.container.append(D2({mii:A.mii,onChange:A.callback,entries:{noseType:{label:"Type",items:_A(18).map((Q)=>({type:0,value:Q,icon:A.icons.nose[Q],part:0}))},nosePosition:{label:"Position",items:[{type:2,property:"noseYPosition",iconStart:N0.positionMoveUp,iconEnd:N0.positionMoveDown,soundStart:"position_down",soundEnd:"position_up",min:0,max:18,part:0,inverse:!0},{type:2,property:"noseScale",iconStart:N0.positionSizeDown,iconEnd:N0.positionSizeUp,soundStart:"scale_down",soundEnd:"scale_up",min:0,max:8,part:0}]}}}))}var wG=(A)=>"#"+A.toString(16).padStart(6,"0");function Ip(A){A.container.append(D2({mii:A.mii,onChange:A.callback,entries:{favoriteColor:{label:"Favorite Color",items:_A(12).map((Q)=>({type:0,forceRender:!0,value:Q,color:wG(c5[Q]),part:0}))}}}))}function qp(A){let Q=A.mii;A.container.append(D2({mii:A.mii,onChange:(J,K,C)=>{A.callback(J,K,C),Q=J},entries:{mouthType:{label:"Type",items:_A(36).map((J)=>({type:0,value:J,icon:A.icons.mouth[J],part:1}))},mouthColor:{label:N0.color,validationProperty:"trueMouthColor",validationFunction(){if(Q.trueMouthColor>4)return Q.trueMouthColor+5;else return Q.trueMouthColor},items:[..._A(5).map((J)=>({type:0,value:J,color:av[J],part:1,property:"fflMouthColor"})),l6(),...i8(_A(100).map((J)=>({type:0,value:J+5,color:n2[J],part:1,property:"extMouthColor"})),d6)]},mouthPosition:{label:"Position",items:[{type:2,property:"mouthYPosition",iconStart:N0.positionMoveUp,iconEnd:N0.positionMoveDown,soundStart:"position_down",soundEnd:"position_up",min:0,max:18,part:1,inverse:!0},{type:2,property:"mouthScale",iconStart:N0.positionSizeDown,iconEnd:N0.positionSizeUp,soundStart:"scale_down",soundEnd:"scale_up",min:0,max:8,part:1},{type:2,property:"mouthHorizontalStretch",iconStart:N0.positionStretchIn,iconEnd:N0.positionStretchOut,soundStart:"vert_stretch_down",soundEnd:"vert_stretch_up",min:0,max:6,part:1}]}}}))}function Op(A){let Q=A.mii;A.container.append(D2({mii:A.mii,onChange:(J,K,C)=>{A.callback(J,K,C),Q=J},entries:{hairType:{label:"Type",items:i8(_A(132).map((J)=>({type:0,value:J,icon:A.icons.hair[J],part:0})),Xp)},hairColor:{label:N0.color,validationProperty:"trueHairColor",validationFunction(){if(Q.trueHairColor>7)return Q.trueHairColor+8;else return Q.trueHairColor},items:[..._A(8).map((J)=>({type:0,value:J,color:n2[J],part:0,property:"fflHairColor"})),l6(),...i8(_A(100).map((J)=>({type:0,value:J+8,color:n2[J],part:0,property:"extHairColor"})),d6)]},hairPosition:{label:"Position",items:[{type:4,iconOff:N0.positionHairFlip,iconOn:N0.positionHairFlipped,property:"flipHair",part:0}]}}}))}function Np(A){A.container.append(D2({mii:A.mii,onChange:A.callback,entries:{bodySize:{label:"Scale",items:[{type:3,property:"height",iconStart:N0.scaleShort,iconEnd:N0.scaleTall,min:0,max:127,forceRender:!1,part:1,soundStart:"vert_stretch_down",soundEnd:"vert_stretch_up"},{type:3,property:"build",iconStart:N0.scaleThin,iconEnd:N0.scaleFat,min:0,max:127,forceRender:!1,part:1,soundStart:"vert_stretch_down",soundEnd:"vert_stretch_up"}]}}}))}function Lp(A){let Q=A.mii;A.container.append(D2({mii:A.mii,onChange:(J,K,C)=>{A.callback(J,K,C),Q=J},entries:{mustacheType:{label:"Mustache",items:_A(6).map((J)=>({type:0,value:J,icon:A.icons.mustache[J],part:1}))},mustachePosition:{label:"Position",items:[{type:2,property:"mustacheYPosition",iconStart:N0.positionMoveUp,iconEnd:N0.positionMoveDown,soundStart:"position_down",soundEnd:"position_up",min:0,max:16,part:1,inverse:!0},{type:2,property:"mustacheScale",iconStart:N0.positionSizeDown,iconEnd:N0.positionSizeUp,soundStart:"scale_down",soundEnd:"scale_up",min:0,max:8,part:1}]},beardType:{label:"Goatee",items:_A(6).map((J)=>({type:0,value:J,icon:A.icons.goatee[J],part:0}))},facialHairColor:{label:N0.color,validationProperty:"trueFacialHairColor",validationFunction(){if(Q.trueFacialHairColor>7)return Q.trueFacialHairColor+8;else return Q.trueFacialHairColor},items:[..._A(8).map((J)=>({type:0,value:J,color:pE[J],part:0,property:"fflHairColor"})),l6(),...i8(_A(100).map((J)=>({type:0,value:J+8,color:n2[J],part:0,property:"extHairColor"})),d6)]}}}))}function Fp(A){A.container.append(D2({mii:A.mii,onChange:A.callback,entries:{eyePosition:{label:"Position",items:[{type:4,iconOff:"Disable",iconOn:"Enable",property:"moleEnabled",part:1},{type:2,property:"moleYPosition",iconStart:N0.positionMoveUp,iconEnd:N0.positionMoveDown,soundStart:"position_down",soundEnd:"position_up",min:0,max:30,part:1,inverse:!0},{type:2,property:"moleXPosition",iconStart:N0.positionPushIn,iconEnd:N0.positionPushOut,soundStart:"move_together",soundEnd:"move_apart",min:0,max:16,part:1},{type:2,property:"moleScale",iconStart:N0.positionSizeDown,iconEnd:N0.positionSizeUp,soundStart:"scale_down",soundEnd:"scale_up",min:0,max:7,part:1}]}}}))}function Rp(A){let Q=A.mii;A.container.append(D2({mii:A.mii,onChange:(J,K,C)=>{A.callback(J,K,C),Q=J},entries:{eyebrowType:{label:"Type",items:_A(24).map((J)=>({type:0,value:J,icon:A.icons.eyebrows[J],part:1}))},eyebrowColor:{label:N0.color,validationProperty:"trueEyebrowColor",validationFunction(){if(Q.trueEyebrowColor>7)return Q.trueEyebrowColor+8;else return Q.trueEyebrowColor},items:[..._A(8).map((J)=>({type:0,value:J,color:pE[J],part:1,property:"fflEyebrowColor"})),l6(),...i8(_A(100).map((J)=>({type:0,value:J+8,color:n2[J],part:1,property:"extEyebrowColor"})),d6)]},eyebrowPosition:{label:"Position",items:[{type:2,property:"eyebrowYPosition",iconStart:N0.positionMoveUp,iconEnd:N0.positionMoveDown,soundStart:"position_down",soundEnd:"position_up",min:3,max:18,part:1,inverse:!0},{type:2,property:"eyebrowSpacing",iconStart:N0.positionPushIn,iconEnd:N0.positionPushOut,soundStart:"move_together",soundEnd:"move_apart",min:0,max:12,part:1},{type:2,property:"eyebrowRotation",iconStart:N0.positionRotateCW,iconEnd:N0.positionRotateCCW,soundStart:"rotate_cw",soundEnd:"rotate_ccw",min:0,max:11,part:1,inverse:!0},{type:2,property:"eyebrowScale",iconStart:N0.positionSizeDown,iconEnd:N0.positionSizeUp,soundStart:"scale_down",soundEnd:"scale_up",min:0,max:8,part:1},{type:2,property:"eyebrowVerticalStretch",iconStart:N0.positionStretchIn,iconEnd:N0.positionStretchOut,soundStart:"vert_stretch_down",soundEnd:"vert_stretch_up",min:0,max:6,part:1}]}}}))}function zp(A){let Q=A.mii;A.container.append(D2({mii:A.mii,onChange:(J,K,C)=>{A.callback(J,K,C),Q=J},entries:{glassesType:{label:"Type",items:_A(20).map((J)=>({type:0,value:J,icon:A.icons.glasses[J],part:0}))},glassesColor:{label:N0.color,validationProperty:"trueGlassesColor",validationFunction(){if(Q.trueGlassesColor>5)return Q.trueGlassesColor+6;else return Q.trueGlassesColor},items:[..._A(6).map((J)=>({type:0,value:J,color:rv[J],part:0,property:"fflGlassesColor"})),l6(),...i8(_A(100).map((J)=>({type:0,value:J+6,color:n2[J],part:0,property:"extGlassColor"})),d6)]},glassesPosition:{label:"Position",items:[{type:2,property:"glassesYPosition",iconStart:N0.positionMoveUp,iconEnd:N0.positionMoveDown,soundStart:"position_down",soundEnd:"position_up",min:0,max:20,part:0,inverse:!0},{type:2,property:"glassesScale",iconStart:N0.positionSizeDown,iconEnd:N0.positionSizeUp,soundStart:"scale_down",soundEnd:"scale_up",min:0,max:7,part:0}]}}}))}function Dp(A){A.container.append(D2({mii:A.mii,onChange:A.callback,entries:{gender:{label:"Gender",items:[{type:4,iconOff:N0.genderMale,iconOn:N0.genderFemale,property:"gender",isNumber:!0,forceRender:!1,part:1,soundOff:"select_misc",soundOn:"select_misc"}]},favorite:{label:"Favorite",items:[{type:4,iconOff:"No",iconOn:"Yes",property:"favorite",isNumber:!1,forceRender:!1,part:1,soundOff:"select_color",soundOn:"select_color"}]},isSpecial:{label:"Type",items:[{type:4,iconOff:"Special",iconOn:"Normal",property:"normalMii",isNumber:!1,forceRender:!1,part:1,soundOff:"select_color",soundOn:"select_color"}]}}}))}function Vp(A){A.container.append(D2({mii:A.mii,onChange:A.callback,entries:{extHatType:{label:"Hat",header:"Hat type is a CUSTOM property, and will not transfer to any other data formats.",items:[{type:0,forceRender:!0,value:0,icon:` - - - - -`,part:0},..._A(10).slice(1).map((Q)=>({type:0,forceRender:!0,value:Q,icon:A.icons.hat[Q-1],part:0}))]},extHatColor:{label:"Hat Color",header:"Hat color is a CUSTOM property, and will not transfer to any other data formats.",items:[{type:0,forceRender:!0,value:0,icon:` - - - - -`,part:0},..._A(12).map((Q)=>({type:0,forceRender:!0,value:Q+1,color:wG(c5[Q]),part:0}))]}}}))}var oR=j2(u8(),1);var k2=j2(u8(),1);function PG(A,Q){switch(Q){case"wiiu":case"switch":case"miitomo":A.set("shaderType",Q);break;case"wiiu_ffliconwithbody":A.set("shaderType","ffliconwithbody");break;case"wiiu_toon":A.set("shaderType","wiiu");break;case"wiiu_blinn":case"none":A.set("shaderType","wiiu_blinn");break;case"lightDisabled":A.set("shaderType","wiiu"),A.set("lightEnable","0");break;default:console.warn(`unknown shader type: ${Q}`)}}var _G=async(A=!1)=>{let Q=await k2.default.getItem("settings_bgm");if(Q===!0)m8().unmute();else if(Q===!1)m8().mute();let J=await k2.default.getItem("settings_sfx");if(J===!0)t8().unmute();else if(J===!1)t8().mute();if(await k2.default.getItem("settings_wiiu"))await k2.default.removeItem("settings_wiiu"),await k2.default.setItem("settings_theme","wiiu");if(await k2.default.getItem("settings_theme")===null)await sZ("theme","default");if(document.documentElement.dataset.theme=String(await k2.default.getItem("settings_theme")),Y7.theme!==await k2.default.getItem("settings_theme")||A)setTimeout(async()=>{document.dispatchEvent(new CustomEvent("theme-change"))},33.33);if(Y7.shaderType!==await k2.default.getItem("settings_shaderType")){console.log("shaderType changed!!!");let U=await SA("shaderType");if(document.dispatchEvent(new CustomEvent("library-shader-update")),f1.qsa("img[data-src]")!==null)f1.qsa("img[data-src]").forEach((Y)=>{let Z=Y.elm,X=Z.src.trim()||Z.dataset.src,E=Z.src.trim()!==""?"src":"data-src";if(console.log(E),!X.includes("?"))return;let H=new URLSearchParams(X.split("?").pop());if(H.delete("shaderType"),H.delete("lightEnable"),PG(H,U),E==="src")Z.src=`${X.split("?")[0]}?${H.toString()}`;else if(E==="data-src")Z.dataset.src=`${X.split("?")[0]}?${H.toString()}`})}if(Y7.bodyModel!==await k2.default.getItem("settings_bodyModel")){console.log("bodyModel changed!!!");let U=await SA("bodyModel");if(document.dispatchEvent(new CustomEvent("library-body-update")),f1.qsa("img[data-src]")!==null)f1.qsa("img[data-src]").forEach((Y)=>{let Z=Y.elm,X=Z.src.trim()||Z.dataset.src,E=Z.src.trim()!==""?"src":"data-src";if(!X.includes("?"))return;let H=new URLSearchParams(X.split("?").pop());if(H.delete("bodyType"),H.set("bodyType",U),E==="src")Z.src=`${X.split("?")[0]}?${H.toString()}`;else if(E==="data-src")Z.dataset.src=`${X.split("?")[0]}?${H.toString()}`})}},Y7={},f8={bgm:{type:"checkbox",label:"Background Music",default:!0,description:"Toggle background music depending on the theme."},sfx:{type:"checkbox",label:"Sound Effects",default:!0,description:"Toggle sound effects for buttons and inputs."},cameraPan:{type:"checkbox",label:"Static camera in editor",default:!1,description:`The camera will be further away in the editor and cannot be moved. -This option is for if you want it to look like Mii Studio.`},autoCloseCustomRender:{type:"checkbox",label:"Auto-close custom render menu",default:!0,description:"The custom render menu will automatically close when pressing save."},autoCloseQrScan:{type:"checkbox",label:"Auto-close QR scan menu",default:!0,description:"The QR code scanner will disappear after a successful scan."},allowQrCamera:{type:"checkbox",label:"Allow using camera in QR scanner",default:!0,description:"When this is disabled, the camera won't be used and some errors may not appear."},editMode:{type:"multi",label:"Editing Mode",description:"Changes the default edit mode option.",default:"3d",choices:[{label:"2D",value:"2d"},{label:"3D (default)",value:"3d"}]},theme:{type:"multi",label:"Theme",default:"default",description:"When this is set to default, your device's color theme preferences will be used.",choices:[{label:"Default",value:"default"},{label:"Wii U",value:"wiiu"}]},shaderType:{type:"multi",label:"Shader Type",description:`Sorry that most of the shaders are not yet ready for use. -Using the Simple shader brings back the old simplistic Mii Creator lighting from the early days. -* Does not apply to 2D mode.`,default:"miitomo",choices:[{label:"No Lighting",value:"lightDisabled"},{label:"Simple",value:"none"},{label:"Toon",value:"wiiu_toon"},{label:"Wii U (Default)",value:"wiiu"},{label:"Wii U (Blinn)",value:"wiiu_blinn"},{label:"Wii U (Alt)",value:"wiiu_ffliconwithbody"},{label:"Switch (WIP)",value:"switch",disabled:!0},{label:"Miitomo",value:"miitomo"}]},simpleShaderLegacyColors:{type:"checkbox",label:"Use legacy colors for Simple shader",default:!1,condition:(A)=>A.shaderType==="none",description:"Bring back the old, brighter body and pants colors."},bodyModel:{type:"multi",label:"Body Model",description:`Pose selections are different depending on the body model you use. -* Does not apply to 2D mode.`,default:"wiiu",choices:[{label:"Wii U (default)",value:"wiiu"},{label:"Switch",value:"switch",disabled:!0},{label:"Miitomo",value:"miitomo"}]},bodyModelHands:{type:"checkbox",label:"Color hands to skin tone",default:!1,description:`The hands of the body will match the Mii's skin tone. -* Does not apply to 2D mode.`},customRenderGreenScreen:{type:"multi",label:"Use background in custom render",default:"off",description:"The custom render will have a solid color background.",choices:[{label:"Disabled",value:"off"},{label:"Green",value:"green"},{label:"Blue",value:"blue"},{label:"Black",value:"black"},{label:"White",value:"white"},{label:"Custom",value:"custom",isColor:!0}]},saveData:{type:"non-settings-multi",label:"Save Data",description:"Not implemented yet.",choices:[{label:"Import",async select(){if(await y0.prompt("WARNING",`This will overwrite ALL of your currently saved Miis and delete them forever! -Please back up your save data before using this option. - -Are you certain that you understand the risk?`,"body")===!1)return;let A=document.createElement("input");A.type="file",A.accept="application/json",document.body.appendChild(A),A.click(),requestAnimationFrame(()=>{document.body.removeChild(A)}),A.addEventListener("change",async(Q)=>{if(A.files===null)return;if(A.files[0]===void 0)return;console.log(A.files);let J=new FileReader;J.onload=function(K){let C=K.target.result;console.log(C)},J.onerror=function(K){console.error("File reading error:",K)},J.readAsText(A.files[0])})},disabled:!0},{label:"Export",async select(){let A={};for(let K of(await k2.default.keys()).filter((C)=>C.startsWith("mii")))console.log(K),A[K]=await k2.default.getItem(K);console.log(A);let Q=URL.createObjectURL(new Blob([JSON.stringify(A)],{type:"application/json"})),J=document.createElement("a");J.href=Q,J.target="_blank",J.download="mii-editor-save-data.json",document.body.appendChild(J),J.click(),requestAnimationFrame(()=>{J.remove()})},disabled:!0},{label:"Delete",type:"danger",async select(){},disabled:!0}]},updateNotices:{type:"non-settings-multi",label:"Update Notices",description:"View the last update notice if you missed it.",choices:[{label:"Review update notice",select(){nR()}}]}},Mp="settings_";for(let A in f8){let Q=Mp+A;Y7[A]=await k2.default.getItem(Q)}async function TG(){let Q=y0.modal("Settings","","body",{text:"Cancel"}).qs(".modal-body").clear();Q.elm.style.setProperty("align-items","flex-start","important"),Q.elm.style.setProperty("max-width","600px");async function J(){let C=[...K],U={};for(let Y in f8)U[Y]=await SA(Y);for(let[Y,Z]of C)if(f8[Y].condition)if(f8[Y].condition(U)===!0)Z.style.display="flex";else Z.style.display="none"}let K=/*@__PURE__*/new Map;for(let C in f8){let U=Mp+C;if(await k2.default.getItem(U)===null)await k2.default.setItem(U,f8[C].default);switch(Y7[C]=await k2.default.getItem(U),f8[C].type){case"checkbox":let Y=new f1("div").class("col").appendMany(new f1("div").class("flex-group").style({"justify-content":"flex-start"}).appendMany(f2(new f1("input").attr({id:U,type:"checkbox",checked:await k2.default.getItem(U)===!0?!0:void 0}).on("input",async($)=>{Y7[C]=await k2.default.getItem(U),await k2.default.setItem(U,$.target.checked),_G(),J()}),"hover","select_misc"),new f1("label").attr({for:U}).text(f8[C].label)),new f1("small").text(f8[C].description));K.set(C,Y.elm),Q.append(Y);break;case"multi":let Z=await k2.default.getItem(U),X=await Promise.all(f8[C].choices.map(async($)=>{let I=void 0,N=!1;if(typeof $.isColor!=="undefined"){I=new f1("span").style({width:"1.2em",height:"1.2em","border-radius":"6px"}),I.style({"background-color":"var(--hover)",border:"1px solid var(--stroke)"});let D=await k2.default.getItem(U);if(typeof D==="string"){if(D.startsWith("#"))I.style({"background-color":D}),N=!0}}let F=new f1("button").class($.value===Z||N?"selected-setting":void 0).attr({"data-setting":U}).text($.label).on("click",async(D)=>{Y7[C]=String(await k2.default.getItem(U));let L=!1;if(typeof $.isColor!=="undefined"){let M=new f1("input").attr({type:"color"}).style({position:"fixed",opacity:"0"}).appendTo("body");if(Y7[C].startsWith("#"))M.val(Y7[C]),L=!0;M.elm.click(),M.on("change",(T)=>{if(k2.default.setItem(U,M.getValue()),I)I.style({"background-color":M.getValue()});M.cleanup(),L=!0})}else await k2.default.setItem(U,$.value);_G(),J();let R=D.target;if(R.parentElement.querySelectorAll(`[data-setting="${U}"]`).forEach((M)=>{M.classList.remove("selected-setting")}),$.isColor!==void 0){if(L)R.classList.add("selected-setting");let M=String(await k2.default.getItem(U));if(I)I.style({"background-color":M})}else R.classList.add("selected-setting")});if(I!==void 0)I.prependTo(F);let V=f2(F,"hover","select_misc");if($.disabled)V.attr({disabled:!0});return V})),E=new f1("div").class("col").appendMany(new f1("label").text(f8[C].label),new f1("small").text(f8[C].description),new f1("div").class("flex-group").style({"justify-content":"flex-start"}).appendMany(...X));K.set(C,E.elm),Q.append(E);break;case"non-settings-multi":let H=new f1("div").class("col").appendMany(new f1("label").text(f8[C].label),new f1("small").text(f8[C].description),new f1("div").class("flex-group").style({"justify-content":"flex-start"}).appendMany(...f8[C].choices.map(($)=>{let I=f2(new f1("button").attr({disabled:$.disabled}).class($.type).text($.label).on("click",async(N)=>{$.select()}),"hover","select_misc");if($.disabled)I.attr({disabled:!0});return I})));K.set(C,H.elm),Q.append(H);break}}await J()}async function nR(){await sZ(`has-seen-${d0.version.string}`,!1),sR()}async function sR(){let A=`has-seen-${d0.version.string}`,Q=await SA(A),J=Q===!1||Q===null,K=window.self!==window.top,C=!window.firstVisit&&!K&&J;if(console.log(`notSeenLatest: ${J} -firstVisit: ${window.firstVisit} -should see update notice?: ${C}`),window.firstVisit&&!K)await sZ(A,!0);else if(C){let E=function(){if(X!==0)Y.qs("button").text(`OK (${X})`);else clearInterval(U),Z.disabled=!1,Z.innerText="OK",Z.addEventListener("click",()=>{sZ(`has-seen-${d0.version.string}`,!0)})},Y=y0.modal(`New Update: ${d0.version.string}`,"Yes new update","body",{text:"OK"}),Z=Y.qs("button").elm;Z.disabled=!0;let X=10;Y.qs(".modal-body span").cleanup(),Y.qs(".modal-body").prepend(new f1("div").style({"max-width":"720px"}).html(d0.version.changelog)),Y.qsa("a").forEach((H)=>{if(H===null)return;f2(H),H.attr({target:"_blank"})}),E();var U=setInterval(()=>{X--,E()},1000)}}var SA=async(A)=>{let Q=await oR.default.getItem("settings_"+A);if(Q===null)if(f8[A])return f8[A].default;else return null;else return Q},sZ=async(A,Q)=>{return await oR.default.setItem("settings_"+A,Q)};var iR,wp=()=>iR;class V8{mii;icons;ui;dirty;ready;renderingMode;onShutdown;errors;constructor(A,Q,J){window.editor=this,document.dispatchEvent(new CustomEvent("editor-launch")),this.showLoadIndicator(),this.dirty=!1,this.ready=!1,this.errors=/*@__PURE__*/new Map;let K="AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn";if(A===1)K="AwEAAAAAAAAAAAAAgN8ZmgAAAAAAAAAAAQBNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAMAQRoQxggNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFik";if(J)K=J;if(Q)this.onShutdown=Q;if(SA("editMode").then((C)=>{if(C==="2d")this.renderingMode=0;else if(C==="3d")if(d0.renderer.allow3DMode===!0)this.renderingMode=1;else this.renderingMode=0}),this.mii=new mA(QA.from(K,"base64")),iR=this.mii,this.mii.deviceOrigin===0)this.mii.deviceOrigin=4;if(this.mii.allowCopying===!1)this.mii.allowCopying=!0;this.#A()}#K;showLoadIndicator(){let A=()=>{if(this.ready){this.hideLoadIndicator();return}else if(this.ui){if(this.ui.mii){if(this.ui.mii.qs(".loader"))this.ui.mii.qs(".loader").classOn("active")}}I2("wait")};A(),this.#K=setInterval(A,1000)}hideLoadIndicator(){if(clearInterval(this.#K),this.ui.mii.qs(".loader"))this.ui.mii.qs(".loader").classOff("active")}async#A(){this.icons=await fetch("./dist/icons.json?t="+Date.now()).then((A)=>A.json()),this.ui={},this.#Z(),this.#U(),await this.#Q(),this.#X(),await this.render(),this.ready=!0}#Z(){this.ui.base=new f1("div").class("ui-base").appendTo("body")}#C(A){switch(A){case 0:return"2D";case 1:return"3D"}}async#Q(){this.ui.mii=new f1("div").class("mii-holder").appendTo(this.ui.base),this.ui.mii.append(new f1("div").html(N0.loading).class("loader","active"));let A=0;switch(this.renderingMode){case 0:this.#J(),A=1;break;case 1:this.#Y(),A=0;break}let Q=f2(new f1("button").class("render-mode-toggle").style({"z-index":"1"}).text(this.#C(A)).on("click",()=>{if(d0.renderer.allow3DMode===!1)return y0.alert("You can't use this feature","Sorry, but you can't use this feature because 3D mode is disabled at the moment.");switch(Q.text(this.#C(this.renderingMode)),this.renderingMode){case 0:this.renderingMode=1;break;case 1:this.renderingMode=0}this.render()}).appendTo(this.ui.mii))}#J(){new f1("img").attr({crossorigin:"anonymous"}).appendTo(this.ui.mii)}async#Y(){this.ui.scene=new U7(this.mii,this.ui.mii.elm,void 0,void 0,void 0,this),await this.ui.scene.init(),this.ui.mii.append(this.ui.scene.getRendererElement()),window.addEventListener("resize",()=>{this.ui.scene.resize()}),this.ui.scene.focusCamera(0),this.ui.scene.getRendererElement().classList.add("ready"),this.ui.mii.qs(".loader").classOff("active")}#U(){let A;if(this.mii.trueGlassesColor>5)A=n2[this.mii.trueGlassesColor];else A=tv[this.mii.trueGlassesColor].top;let Q;if(this.mii.trueEyeColor>6)Q=n2[this.mii.trueEyeColor-6];else Q=uE[this.mii.fflEyeColor];let J;if(this.mii.trueMouthColor>6)J={top:zN[this.mii.trueMouthColor-5],bottom:n2[this.mii.trueMouthColor-5]};else J={top:zN[this.mii.fflMouthColor+19],bottom:n2[this.mii.fflMouthColor+19]};this.ui.base.style({"--eye-color":Q,"--icon-lip-color-top":J.top,"--icon-lip-color-bottom":J.bottom,"--icon-hair-tie":"#"+c5[this.mii.favoriteColor].toString(16).padStart(6,"0"),"--icon-eyebrow-fill":n2[this.mii.eyebrowColor],"--icon-hair-fill":n2[this.mii.hairColor],"--icon-facial-hair-fill":n2[this.mii.facialHairColor],"--icon-hat-fill":r7[this.mii.favoriteColor].top,"--icon-hat-stroke":r7[this.mii.favoriteColor].bottom,"--icon-glasses-fill":A,"--icon-glasses-shade":A+"77"})}#X(){let A=(J,K)=>{return async(C)=>{if(this.ui.scene)this.ui.scene.focusCamera(K);if(await J({container:C,callback:(U,Y,Z)=>{if(this.mii=U,this.mii.normalMii===!1)this.mii.disableSharing=!0;else this.mii.disableSharing=!1;if(iR=U,this.render(Y,Z),this.ui.scene)this.ui.scene.sparkle();this.#U(),this.dirty=!0},icons:this.icons,mii:this.mii,editor:this}),this.ui.scene)this.ui.scene.resize()}},Q=VG([{icon:N0.head,select:A(Hp,0)},{icon:N0.hair,select:A(Op,0)},{icon:N0.hat,select:A(Vp,0)},{icon:N0.eyebrows,select:A(Rp,0)},{icon:N0.eyes,select:A($p,0)},{icon:N0.nose,select:A(Wp,0)},{icon:N0.mouth,select:A(qp,0)},{icon:N0.facialHair,select:A(Lp,0)},{icon:N0.mole,select:A(Fp,0)},{icon:N0.glasses,select:A(zp,0)},{icon:N0.scale,select:A(Np,1)},{icon:N0.favoriteColor,select:A(Ip,1)},{icon:N0.gender,select:A(Dp,1)},{icon:N0.details,select:A(Gp,1)},{icon:N0.save+"Save",type:"tab-save",select:()=>{if(this.dirty===!0)y0.modal("Save Mii","Would you like to save?","body",{text:"Save & Exit",callback:()=>{if(wp().normalMii===!1)wp().disableSharing=!0;this.shutdown()}},{text:"Exit without Saving",callback:()=>{this.shutdown(!1)}},{text:"Cancel"});else y0.modal("Quitting Editor","No changes were made. Are you sure you want to exit?","body",{text:"Save & Exit",callback:()=>{this.shutdown()}},{text:"Exit without Saving",callback:()=>{this.shutdown(!1)}},{text:"Cancel"})},update:!1}]);this.ui.tabList=Q.list,this.ui.tabContent=Q.content,this.ui.base.appendMany(Q.list,Q.content)}async render(A=!0,Q=0){if(d0.renderer.allow3DMode===!1)this.renderingMode=0;switch(this.renderingMode){case 0:if(this.ui.mii.qs("img")===null)this.#J();if(this.ui.mii.qs("canvas.scene"))this.ui.mii.qs("canvas.scene")?.style({display:"none"});this.ui.mii.qs("img")?.style({display:"block"});let J="gray";if(this.mii.normalMii===!1)J="gold";if(this.mii.favorite)J="red";this.ui.mii.qs("img")?.style({display:"block"}).attr({src:`${d0.renderer.renderFullBodyURL}&data=${encodeURIComponent(this.mii.encodeStudio().toString("hex"))}&${d0.renderer.hatTypeParam}=${this.mii.extHatType+d0.renderer.hatTypeAdd}&${d0.renderer.hatColorParam}=${this.mii.extHatColor+d0.renderer.hatColorAdd}&miic=${encodeURIComponent(this.mii.encode().toString("base64"))}&pantsColor=${J}`});break;case 1:if(this.ui.mii.qs("canvas.scene")===null)await this.#Y();if(this.ui.mii.qs("img"))this.ui.mii.qs("img")?.style({display:"none"});if(this.ui.mii.qs("canvas.scene")?.style({display:"block"}),this.ui.scene.mii=this.mii,A)this.ui.scene.updateMiiHead(Q);else this.ui.scene.updateBody(!0);break}}#B(){this.ui.mii.qs("button").classOn("disabled"),this.ui.tabList.classOn("disabled"),this.ui.tabContent.classOn("disabled")}async shutdown(A=!0){if(A){if(Array.from(this.errors.values()).find((Q)=>Q===!0)){let Q=[];for(let[J,K]of this.errors.entries())if(K===!0)Q.push(J);y0.alert("Error",`Will not save because there are problems with the following items: - -`+Q.map((J)=>`• ${J}`).join(` -`));return}if(this.renderingMode===1)await new Promise((Q,J)=>{this.#B(),this.ui.scene.playEndingAnimation(),setTimeout(()=>{Q(null)},1500)})}if(this.#K)clearInterval(this.#K);this.ui.base.classOn("closing"),setTimeout(()=>{if(this.ui.mii.qs("canvas.scene"))this.ui.scene.shutdown();if(this.ui.base.cleanup(),this.onShutdown)this.onShutdown(QA.from(this.mii.encode()).toString("base64"),A);document.dispatchEvent(new CustomEvent("editor-shutdown"))},500)}}class aR{scene;position;texture;duration;particleCount;timeElapsed;geometry;material;particles;constructor(A,Q,J,K=0.2,C=6){this.scene=A,this.position=Q,this.texture=J,this.duration=K,this.particleCount=C,this.timeElapsed=0,this.initParticles()}initParticles(){this.geometry=new V0;let A=[],Q=[],J=1;for(let K=0;K=this.duration)this.dispose();return!0}dispose(){return this.scene.remove(this.particles),this.particles.geometry.dispose(),this.particles.material.dispose(),!1}}var _p=[0,1,1,1,0,0,0,1,3,1];var wc=j2(u8(),1);var rR=`// https://jsfiddle.net/arian_/8gvynrdu/7/ -// position, texCoord (uv), normal are all provided by three.js - -// 頂点シェーダーに入力される attribute 変数 -//attribute vec4 position; //!< 入力: 位置情報 -//attribute vec2 uv; //!< 入力: テクスチャー座標 -//attribute vec3 normal; //!< 入力: 法線ベクトル - -// color is not actually the vertex color, as such -// it is a custom attribute _COLOR in the glTF - -attribute vec4 _color; //!< 入力: 頂点の色 -attribute vec3 tangent; //!< 入力: 異方位 - -// フラグメントシェーダーへの入力 -varying vec4 v_color; //!< 出力: 頂点の色 -varying vec4 v_position; //!< 出力: 位置情報 -varying vec3 v_normal; //!< 出力: 法線ベクトル -varying vec3 v_tangent; //!< 出力: 異方位 -varying vec2 v_texCoord; //!< 出力: テクスチャー座標 - -// normalMatrix, modelViewMatrix, and projectionMatrix are provided by three.js -// ユニフォーム -//uniform mat3 normalMatrix; //!< ユニフォーム: モデルの法線用行列 -//uniform mat4 modelViewMatrix; //!< ユニフォーム: プロジェクション行列 -//uniform mat4 projectionMatrix; //!< ユニフォーム: モデル行列 - -#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif -void main() -{ -//#ifdef FFL_COORDINATE_MODE_NORMAL - // 頂点座標を変換 - // begin_vertex.glsl.js - vec3 transformed = vec3( position ); -#ifdef USE_SKINNING - // skinbase_vertex.glsl.js - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); - // skinning_vertex.glsl.js - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif - gl_Position = projectionMatrix * modelViewMatrix * vec4(transformed, 1.0);// * vec4(position, 1.0); - v_position = modelViewMatrix * vec4(transformed, 1.0); - // 法線も変換 <-- line 67 - vec3 objectNormal = normal; - vec3 objectTangent = tangent.xyz; - - -#ifdef USE_SKINNING - // skinnormal_vertex.glsl.js - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - - objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; - objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; - -#endif - - //v_normal = mat3(inverse(u_mv)) * a_normal; - v_normal = normalize(normalMatrix * objectNormal); - -//#elif defined(FFL_COORDINATE_MODE_NONE) -// // 頂点座標を変換 -// gl_Position = vec4(a_position.x, a_position.y * -1.0, a_position.z, a_position.w); -// v_position = a_position; -// -// v_normal = a_normal; -//#endif - - // その他の情報も書き出す - v_texCoord = uv; - v_tangent = normalize(normalMatrix * objectTangent); - v_color = _color; -}`;var tR=`// https://jsfiddle.net/arian_/8gvynrdu/7/ -// -// 定数定義ファイル -// - -/// シェーダーモード -#define FFL_SHADER_MODE_UR 0 -#define FFL_SHADER_MODE_UB 1 - -/// 変調処理のマクロ -#define FFL_MODULATE_MODE_CONSTANT 0 -#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 -#define FFL_MODULATE_MODE_RGB_LAYERED 2 -#define FFL_MODULATE_MODE_ALPHA 3 -#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 -#define FFL_MODULATE_MODE_ALPHA_OPA 5 - -/// スペキュラのモード -#define FFL_SPECULAR_MODE_BLINN 0 -#define FFL_SPECULAR_MODE_ANISO 1 - -/// ライトのON/OFF -#define FFL_LIGHT_MODE_DISABLE 0 -#define FFL_LIGHT_MODE_ENABLE 1 - -/// フラグメントのディスカードモード -#define FFL_DISCARD_FRAGMENT_DISABLE 0 -#define FFL_DISCARD_FRAGMENT_ENABLE 1 - -/// 座標変換モード -#define FFL_COORDINATE_MODE_NONE 0 -#define FFL_COORDINATE_MODE_NORMAL 1 - -// -// 関数の定義ファイル -// - -/** - * @brief 異方性反射の反射率を計算します。 - * @param[in] light ライトの向き - * @param[in] tangent 接線 - * @param[in] eye 視線の向き - * @param[in] power 鋭さ - */ -mediump float calculateAnisotropicSpecular(mediump vec3 light, mediump vec3 tangent, mediump vec3 eye, mediump float power ) -{ - mediump float dotLT = dot(light, tangent); - mediump float dotVT = dot(eye, tangent); - mediump float dotLN = sqrt(1.0 - dotLT * dotLT); - mediump float dotVR = dotLN*sqrt(1.0 - dotVT * dotVT) - dotLT * dotVT; - - return pow(max(0.0, dotVR), power); -} - -/** - * @brief 異方性反射の反射率を計算します。 - * @param[in] light ライトの向き - * @param[in] normal 法線 - * @param[in] eye 視線の向き - * @param[in] power 鋭さ - */ -mediump float calculateBlinnSpecular(mediump vec3 light, mediump vec3 normal, mediump vec3 eye, mediump float power) -{ - return pow(max(dot(reflect(-light, normal), eye), 0.0), power); -} - -/** - * @brief 異方性反射、ブリン反射をブレンドします。 - * @param[in] blend ブレンド率 - * @param[in] blinn ブリンの値 - * @param[in] aniso 異方性の値 - */ -mediump float calculateSpecularBlend(mediump float blend, mediump float blinn, mediump float aniso) -{ - return mix(aniso, blinn, blend); -} - -/** - * @brief アンビエントを計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - */ -mediump vec3 calculateAmbientColor(mediump vec3 light, mediump vec3 material) -{ - return light * material; -} - -/** - * @brief 拡散を計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - * @param[in] ln ライトと法線の内積 - */ -mediump vec3 calculateDiffuseColor(mediump vec3 light, mediump vec3 material, mediump float ln) -{ - return light * material * ln; -} - -/** - * @brief 鏡面反射を計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - * @param[in] reflection 反射率 - * @param[in] strength 幅 - */ -mediump vec3 calculateSpecularColor(mediump vec3 light, mediump vec3 material, mediump float reflection, mediump float strength) -{ - return light * material * reflection * strength; -} - -/** - * @brief リムを計算します。 - * @param[in] color リム色 - * @param[in] normalZ 法線のZ方向 - * @param[in] width リム幅 - * @param[in] power リムの鋭さ - */ -mediump vec3 calculateRimColor(mediump vec3 color, mediump float normalZ, mediump float width, mediump float power) -{ - return color * pow(width * (1.0 - abs(normalZ)), power); -} - -/** - * @brief ライト方向と法線の内積を求める - * @note 特殊な実装になっています。 - */ -mediump float calculateDot(mediump vec3 light, mediump vec3 normal) -{ - return max(dot(light, normal), 0.1); -} - -// フラグメントシェーダーに入力される varying 変数 -varying mediump vec4 v_color; //!< 出力: 頂点の色 -varying mediump vec4 v_position; //!< 出力: 位置情報 -varying mediump vec3 v_normal; //!< 出力: 法線ベクトル -varying mediump vec3 v_tangent; //!< 出力: 異方位 -varying mediump vec2 v_texCoord; //!< 出力: テクスチャー座標 - -/// constカラー -uniform mediump vec4 u_const1; ///< constカラー1 -/* -uniform mediump vec4 u_const2; ///< constカラー2 -uniform mediump vec4 u_const3; ///< constカラー3 -*/ - -/// ライト設定 -uniform mediump vec4 u_light_ambient; ///< カメラ空間のライト方向 -uniform mediump vec4 u_light_diffuse; ///< 拡散光用ライト -uniform mediump vec3 u_light_dir; -uniform bool u_light_enable; -uniform mediump vec4 u_light_specular; ///< 鏡面反射用ライト強度 - -/// マテリアル設定 -uniform mediump vec4 u_material_ambient; ///< 環境光用マテリアル設定 -uniform mediump vec4 u_material_diffuse; ///< 拡散光用マテリアル設定 -uniform mediump vec4 u_material_specular; ///< 鏡面反射用マテリアル設定 -uniform int u_material_specular_mode; ///< スペキュラの反射モード(CharModelに依存する設定のためub_modulateにしている) -uniform mediump float u_material_specular_power; ///< スペキュラの鋭さ(0.0を指定すると頂点カラーの設定が利用される) - -/// 変調設定 -uniform int u_mode; ///< 描画モード - -/// リム設定 -uniform mediump vec4 u_rim_color; -uniform mediump float u_rim_power; - -// サンプラー -uniform sampler2D s_texture; - -// ------------------------------------------------------- -// メイン文 -void main() -{ - mediump vec4 color; - - mediump float specularPower = u_material_specular_power; - mediump float rimWidth = v_color.a; - -//#ifdef FFL_MODULATE_MODE_CONSTANT - if(u_mode == FFL_MODULATE_MODE_CONSTANT) - { - color = u_const1; - } -//#elif defined(FFL_MODULATE_MODE_TEXTURE_DIRECT) - else if(u_mode > FFL_MODULATE_MODE_CONSTANT)// == FFL_MODULATE_MODE_TEXTURE_DIRECT) - { - color = texture2D(s_texture, v_texCoord); - } - /* -//#elif defined(FFL_MODULATE_MODE_RGB_LAYERED) - else if(u_mode == FFL_MODULATE_MODE_RGB_LAYERED) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.r * u_const1.rgb + color.g * u_const2.rgb + color.b * u_const3.rgb, color.a); - } -//#elif defined(FFL_MODULATE_MODE_ALPHA) - else if(u_mode == FFL_MODULATE_MODE_ALPHA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(u_const1.rgb, color.r); - } -//#elif defined(FFL_MODULATE_MODE_LUMINANCE_ALPHA) - else if(u_mode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.g * u_const1.rgb, color.r); - } -//#elif defined(FFL_MODULATE_MODE_ALPHA_OPA) - else if(u_mode == FFL_MODULATE_MODE_ALPHA_OPA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.r * u_const1.rgb, 1.0); - } - */ -//#endif - - // avoids little outline around mask elements - if(color.a == 0.0f) - { - discard; - } - -//#ifdef FFL_LIGHT_MODE_ENABLE - if(u_light_enable) - { - /// 環境光の計算 - mediump vec3 ambient = calculateAmbientColor(u_light_ambient.xyz, u_material_ambient.xyz); - - /// 法線ベクトルの正規化 - mediump vec3 norm = normalize(v_normal); - - /// 視線ベクトル - mediump vec3 eye = normalize(-v_position.xyz); - - // ライトの向き - mediump float fDot = calculateDot(u_light_dir, norm); - - /// Diffuse計算 - mediump vec3 diffuse = calculateDiffuseColor(u_light_diffuse.xyz, u_material_diffuse.xyz, fDot); - - /// Specular計算 - mediump float specularBlinn = calculateBlinnSpecular(u_light_dir, norm, eye, u_material_specular_power); - - /// Specularの値を確保する変数を宣言 - mediump float reflection; - mediump float strength = v_color.g; - if(u_material_specular_mode == 0) - { - /// Blinnモデルの場合 - strength = 1.0; - reflection = specularBlinn; - } - else - { - /// Aisoモデルの場合 - mediump float specularAniso = calculateAnisotropicSpecular(u_light_dir, v_tangent, eye, u_material_specular_power); - reflection = calculateSpecularBlend(v_color.r, specularBlinn, specularAniso); - } - /// Specularの色を取得 - mediump vec3 specular = calculateSpecularColor(u_light_specular.xyz, u_material_specular.xyz, reflection, strength); - - // リムの色を計算 - mediump vec3 rimColor = calculateRimColor(u_rim_color.rgb, norm.z, v_color.a, u_rim_power); - - // カラーの計算 - color.rgb = (ambient + diffuse) * color.rgb + specular + rimColor; - } -//#endif - - gl_FragColor = color; -}`;var eR=` -#define VARYING_QUALIFIER out -#define VARYING_INSTANCE Out - -// VARYING_QUALIFIER vec2 texCoord; -varying vec2 v_texCoord; -// VARYING_QUALIFIER vec3 normal; -varying vec3 v_normal; -varying vec4 v_position; -// VARYING_QUALIFIER float specularMix; -// varying mediump float v_specularMix; - -/// ================================================================ -/// 頂点シェーダーの実装 -/// ================================================================ - -// order of TexCoord and Normal flipped -// to be compliant with rio models -// layout( location = 1 ) in vec2 i_TexCoord; -// layout( location = 2 ) in vec3 i_Normal; -// layout( location = 3 ) in vec4 i_Parameter; - -// layout( location = 1 ) in vec2 i_TexCoord; -// layout( location = 2 ) in vec3 i_Normal; -// layout( location = 3 ) in vec4 i_Parameter; - -/* -layout( location = 4 ) in vec4 i_Parameter; -layout( location = 5 ) in ivec4 i_Index; -layout(std140) uniform u_Skeleton -{ - vec4 mtxPalette[3 * 128]; -}; - -layout(std140) uniform u_Shape -{ - vec4 shapeMtx[3]; - int vtxSkinCount; -}; -*/ - -// TODO: you can use rio mShader.setUniformArray to bind this(?) -// https://github.com/aboood40091/RIO-Tests/blob/b9db5fb506c92d89c526d6c93efa0d44a7260510/07_Uniform-Variables-2/src/roottask.cpp#L193 -/* -layout(std140) uniform u_Matrix -{ - vec4 mv[3]; - vec4 proj[4]; -}; - - -// vec4[3] * vec4(vec3, 1) -#define TRANSFORM_POS(mtx, pos) vec3( dot(mtx[0].xyzw, pos.xyzw), dot(mtx[1].xyzw, pos.xyzw), dot(mtx[2].xyzw, pos.xyzw)) - -// vec3[3] * vec3 -#define TRANSFORM_VEC(mtx, vec) vec3( dot(mtx[0].xyz, vec.xyz), dot(mtx[1].xyz, vec.xyz), dot(mtx[2].xyz, vec.xyz)) - -// vec4[4] * vec4 -#define PROJECT(mtx, pos) vec4( dot(mtx[0].xyzw, pos.xyzw), dot(mtx[1].xyzw, pos.xyzw), dot(mtx[2].xyzw, pos.xyzw), dot(mtx[3].xyzw, pos.xyzw)) -*/ - -#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif - -void main() -{ -// begin_vertex.glsl.js -vec3 transformed = vec3( position ); -#ifdef USE_SKINNING - // skinbase_vertex.glsl.js - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); - // skinning_vertex.glsl.js - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif - gl_Position = projectionMatrix * modelViewMatrix * vec4(transformed, 1.0);// * vec4(position, 1.0); - v_position = modelViewMatrix * vec4(transformed, 1.0); - - v_normal = mat3(modelViewMatrix) * normal.xyz; - - v_texCoord = uv.xy; - //normal = TRANSFORM_VEC(mv,i_Normal); - // v_specularMix = i_Parameter.r; - -#if defined(USE_DEBUG) - gl_Position = position; -#endif - -} -/* - vec4 pos_w = vec4(0, 0, 0, 1); - vec3 nrm_w = vec3(0, 0, 0); - vec4 tmp = vec4(i_Position.xyz, 1.0f); - - if (vtxSkinCount == 0) - { - pos_w.x = dot(shapeMtx[0], tmp); - pos_w.y = dot(shapeMtx[1], tmp); - pos_w.z = dot(shapeMtx[2], tmp); - nrm_w.x = dot(shapeMtx[0].xyz, i_Normal); - nrm_w.y = dot(shapeMtx[1].xyz, i_Normal); - nrm_w.z = dot(shapeMtx[2].xyz, i_Normal); - } - else if (vtxSkinCount == 1) - { - int mtxIndex = i_Index.x * 3; - pos_w.x = dot(mtxPalette[mtxIndex + 0], tmp); - pos_w.y = dot(mtxPalette[mtxIndex + 1], tmp); - pos_w.z = dot(mtxPalette[mtxIndex + 2], tmp); - nrm_w.x = dot(mtxPalette[mtxIndex + 0].xyz, i_Normal); - nrm_w.y = dot(mtxPalette[mtxIndex + 1].xyz, i_Normal); - nrm_w.z = dot(mtxPalette[mtxIndex + 2].xyz, i_Normal); - } - - vec4 pos_v; - pos_v.x = dot(cameraMtx[0], pos_w); - pos_v.y = dot(cameraMtx[1], pos_w); - pos_v.z = dot(cameraMtx[2], pos_w); - pos_v.w = 1.0; - - gl_Position.x = dot(projMtx[0], pos_v); - gl_Position.y = dot(projMtx[1], pos_v); - gl_Position.z = dot(projMtx[2], pos_v); - gl_Position.w = dot(projMtx[3], pos_v); - - Out.normal.x = dot(cameraMtx[0].xyz, nrm_w); - Out.normal.y = dot(cameraMtx[1].xyz, nrm_w); - Out.normal.z = dot(cameraMtx[2].xyz, nrm_w); - Out.texCoord = i_TexCoord.xy; - Out.specularMix = i_Parameter.r; - -} -*/ -`;var Az=` -#define VARYING_QUALIFIER in -#define VARYING_INSTANCE In - -varying mediump vec2 v_texCoord; -varying mediump vec3 v_normal; -// varying mediump float v_specularMix; - -/// ================================================================ -/// ピクセルシェーダーの実装 -/// ================================================================ - -// layout( location = 0 ) out vec4 o_Color; - -// NOTE: NOT SURE HOW TO SET UNIFORM BLOCKS IN RIO -//layout( std140 ) uniform u_Modulate -//{ - uniform int modulateType; - uniform int gammaType; - uniform int drawType; - uniform int pad0; - uniform vec4 u_const1; - uniform vec4 u_const2; - uniform vec4 u_const3; - uniform vec4 lightDirInView; - uniform vec4 lightColor; - uniform vec4 u_SssColor; - uniform vec4 u_SpecularColor; - uniform vec4 u_RimColor; - - uniform float u_HalfLambertFactor; - uniform float u_SssSpecularFactor; - - uniform float u_SpecularFactorA; - uniform float u_SpecularFactorB; - uniform float u_SpecularShinness; - uniform float u_RimPower; - - uniform float u_RimWidth; - uniform bool lightEnable; -//}; - - -uniform sampler2D s_Tex; - -/// 変調モード -#define MODULATE_TYPE_CONSTANT ( 0 ) -#define MODULATE_TYPE_TEXTRUE ( 1 ) -#define MODULATE_TYPE_LAYERED ( 2 ) -#define MODULATE_TYPE_ALPHA ( 3 ) -#define MODULATE_TYPE_ALPHA_OPA ( 4 ) -#define MODULATE_TYPE_GLASS ( 5 ) -#define MODULATE_TYPE_ICONBODY ( 6 ) - -#define USE_DEGAMMA(type) (type != 0) - -#define DRAW_TYPE_NORMAL 0 -#define DRAW_TYPE_FACELINE 1 -#define DRAW_TYPE_HAIR 2 - -vec4 GetAlbedo() -{ - vec4 texel; - vec4 albedo; - - if(modulateType != MODULATE_TYPE_CONSTANT && - modulateType != MODULATE_TYPE_ICONBODY) - { - texel = texture(s_Tex,v_texCoord); - } - switch(modulateType) - { - case MODULATE_TYPE_CONSTANT: - albedo = vec4(u_const1.rgb,1.0f); - break; - case MODULATE_TYPE_TEXTRUE: - albedo = texel; - break; - case MODULATE_TYPE_LAYERED: - albedo = vec4(u_const1.rgb * texel.r - + u_const2.rgb * texel.g - + u_const3.rgb * texel.b - , texel.a); - break; - case MODULATE_TYPE_ALPHA: - albedo = vec4(u_const1.rgb,texel.r); - break; - case MODULATE_TYPE_ALPHA_OPA: - albedo = vec4(u_const1.rgb * texel.r ,1.0f); - break; - case MODULATE_TYPE_GLASS: - // NOTE: glass background color on switch is R but here it's G - albedo = vec4(u_const1.rgb * texel.g , pow(texel.r, u_const2.g)); - break; - case MODULATE_TYPE_ICONBODY: - albedo = vec4(u_const1.rgb, 1.0f); - break; - default: - albedo = vec4(0.0f); - break; - } - return albedo; -} - -vec3 ToLinear(vec3 rgb) -{ - return pow(rgb,vec3(2.2f)); -} - -vec3 ToSrgb(vec3 rgb) -{ - return pow(rgb,vec3(1.0f/2.2f)); -} - -vec3 GetRimColor(vec3 color,float normalZ,float width,float power) -{ - return color * pow(width * (1.0f - abs(normalZ)),power); -} - -void main() -{ - /// ModulateTypeを考慮してアルベドを取得 - vec4 albedo = GetAlbedo(); - // NOTE: faceline color A channel is 1 here but 0 on switch, needs to be modified - // NOTE: THE BELOW CODE ALSO TARGETS BEARD!!!! - /*if(drawType == DRAW_TYPE_FACELINE && - modulateType == MODULATE_TYPE_TEXTRUE && - albedo.a != 0.0f) - { - albedo.a = 0.0f; - }*/ - if(albedo.a == 0.0f && drawType != DRAW_TYPE_FACELINE) - { - discard; - } - if(!lightEnable) - { - /*o_Color*/gl_FragColor = albedo; - return; - } - - if(USE_DEGAMMA(gammaType)) - { - /// SRGB to Linear - albedo.rgb = ToLinear(albedo.rgb); - } - - vec3 preNormal = v_normal; - - /// ライティング向け計算 - vec3 normal = normalize(preNormal); ///< ビュー空間法線 - vec3 lightDir = normalize(lightDirInView.xyz); ///< ビュー空間ライト方向 - - /// diffuseの計算 - float diffuseFactor = max(0.0f,dot(v_normal, lightDir)); - - /// 拡散値計算 - float halfLambert = ((diffuseFactor) * u_HalfLambertFactor + (1.0f - u_HalfLambertFactor)); - - /// スペキュラ計算 - vec3 halfDir = normalize(lightDir + vec3(0.0f,0.0f,1.0f)); - float specAngle = max(dot(halfDir,v_normal),0.0f); - float specular = pow(specAngle,u_SpecularShinness); - - /// 髪型は、スペキュラの係数をParameterのr値でAB補間 - float specularFactor; - if(drawType != DRAW_TYPE_HAIR) - { - specularFactor = u_SpecularFactorA; - } - else - { - specularFactor = mix(u_SpecularFactorA,u_SpecularFactorB, 0.5f);//,v_specularMix); - } - - vec4 outputColor = vec4(vec3(0.0f),albedo.a); - - vec3 diffuseColor = lightColor.rgb * albedo.rgb * halfLambert; - vec3 specularColor = specular * specularFactor * lightColor.rgb * u_SpecularColor.rgb; - vec3 sssColor = u_SssColor.rgb * (1.0f - halfLambert); - float sssSpecularFactor = (1.0f - albedo.a * u_SssSpecularFactor); - //float sssSpecularFactor = 1.0f; - - /// FACELINEは、アルファ値を考慮して計算する - if(drawType == DRAW_TYPE_FACELINE) - { - outputColor = vec4(diffuseColor + (specularColor + sssColor) * sssSpecularFactor,1.0f); - } - else - { - outputColor = vec4(diffuseColor + (specularColor + sssColor),albedo.a); - } - - outputColor.rgb += GetRimColor(u_RimColor.rgb,clamp(v_normal.z,0.0f,1.0f),u_RimWidth,u_RimPower); - - if(USE_DEGAMMA(gammaType)) - { - /// Linear to SRGB - outputColor.rgb = ToSrgb(outputColor.rgb); - } - - /*o_Color*/gl_FragColor = outputColor; -} -`;var Qz=2147483647,Tp={halfLambertFactor:0,sssSpecularBlendFactor:1,sssColor:[0,0,0],specular:{color:[0,0,0],factorA:0,factorB:0,shinness:0.1},rimLight:{color:[0,0,0],power:1,width:0.5}},kp={halfLambertFactor:0.35,sssSpecularBlendFactor:1,sssColor:[0,0,0],specular:{color:[0.09804292,0.09804292,0.09804292],factorA:0.3,factorB:0,shinness:30},rimLight:{color:[0,0,0],power:1,width:0}},Jz=[{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0,0,0],specular:{color:[0.01960913,0.01960913,0.01960913],factorA:1,factorB:0.02,shinness:0.7},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0,0,0.1568674],specular:{color:[0.2352996,0.1568674,0],factorA:1,factorB:0.02,shinness:0.7},rimLight:{color:[0,0,0],power:1,width:0.5}}],Sp=[{halfLambertFactor:0.4,sssSpecularBlendFactor:1,sssColor:[0.6470634,0.1333377,0],specular:{color:[0.1764755,0.08235628,0.05882626],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0.2627507,0.1176511,0.08627796],power:2,width:0.3}},{halfLambertFactor:0.4,sssSpecularBlendFactor:1,sssColor:[0.6431419,0.03529608,0],specular:{color:[0.1372593,0.09412124,0.03921773],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0.2352996,0.1568674,0.06666958],power:2,width:0.3}},{halfLambertFactor:0.4,sssSpecularBlendFactor:1,sssColor:[0.2941234,0,0],specular:{color:[0.1215728,0.03921773,0.01176563],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0.2431428,0.07843459,0.0235309],power:2,width:0.3}},{halfLambertFactor:0.4,sssSpecularBlendFactor:1,sssColor:[0.6980433,0.03921773,0],specular:{color:[0.1137294,0.05490454,0.01960913],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0.2352996,0.1176511,0.03921773],power:2,width:0.3}},{halfLambertFactor:0.4,sssSpecularBlendFactor:1,sssColor:[0.2000051,0.01176563,0],specular:{color:[0.1254943,0.02745257,0.01176563],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0.250986,0.05490454,0.0235309],power:2,width:0.3}},{halfLambertFactor:0.4,sssSpecularBlendFactor:1,sssColor:[0.05882626,0.00392195,0],specular:{color:[0.03137433,0.00784381,0.00392195],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0.250986,0.06274787,0.03137433],power:2,width:0.3}},{halfLambertFactor:0.4,sssSpecularBlendFactor:1,sssColor:[0.6549063,0.1568674,0],specular:{color:[0.1764755,0.08235628,0.05882626],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0.2627507,0.1215728,0.08627796],power:2,width:0.3}},{halfLambertFactor:0.4,sssSpecularBlendFactor:1,sssColor:[0.5882402,0.1098079,0.03529608],specular:{color:[0.1372593,0.07843459,0.03921773],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0.2352996,0.1451026,0.08235628],power:2,width:0.3}},{halfLambertFactor:0.4,sssSpecularBlendFactor:1,sssColor:[0.07843459,0.00392195,0.00392195],specular:{color:[0.05882626,0.01960913,0.00392195],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0.2352996,0.04706119,0.01176563],power:2,width:0.3}},{halfLambertFactor:0.4,sssSpecularBlendFactor:1,sssColor:[0.01960913,0,0],specular:{color:[0.01960913,0.00784381,0.00392195],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0.2352996,0.07843459,0.03921773],power:2,width:0.3}}],jp=[{halfLambertFactor:0.3,sssSpecularBlendFactor:0,sssColor:[0.6470634,0.1333377,0],specular:{color:[0.1764755,0.08235628,0.05882626],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:0.55,width:0}},{halfLambertFactor:0.3,sssSpecularBlendFactor:0,sssColor:[0.6431419,0.03529608,0],specular:{color:[0.1372593,0.09412124,0.03921773],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:0.55,width:0}},{halfLambertFactor:0.3,sssSpecularBlendFactor:0,sssColor:[0.2941234,0,0],specular:{color:[0.1215728,0.03921773,0.01176563],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:0.55,width:0}},{halfLambertFactor:0.3,sssSpecularBlendFactor:0,sssColor:[0.6980433,0.03921773,0],specular:{color:[0.1137294,0.05490454,0.01960913],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:0.55,width:0}},{halfLambertFactor:0.3,sssSpecularBlendFactor:0,sssColor:[0.2000051,0.01176563,0],specular:{color:[0.1254943,0.02745257,0.01176563],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:0.55,width:0}},{halfLambertFactor:0.3,sssSpecularBlendFactor:0,sssColor:[0.05882626,0.00392195,0],specular:{color:[0.03137433,0.00784381,0.00392195],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:0.55,width:0}},{halfLambertFactor:0.3,sssSpecularBlendFactor:0,sssColor:[0.6549063,0.1568674,0],specular:{color:[0.1764755,0.08235628,0.05882626],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:0.55,width:0}},{halfLambertFactor:0.3,sssSpecularBlendFactor:0,sssColor:[0.5882402,0.1098079,0.03529608],specular:{color:[0.1372593,0.07843459,0.03921773],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:0.55,width:0}},{halfLambertFactor:0.3,sssSpecularBlendFactor:0,sssColor:[0.07843459,0.00392195,0.00392195],specular:{color:[0.05882626,0.01960913,0.00392195],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:0.55,width:0}},{halfLambertFactor:0.3,sssSpecularBlendFactor:0,sssColor:[0.01960913,0,0],specular:{color:[0.01960913,0.00784381,0.00392195],factorA:2.6,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:0.55,width:0}}],vp=[{halfLambertFactor:0.5,sssSpecularBlendFactor:0,sssColor:[0.1647106,0.01176563,0.00392195],specular:{color:[0.1647106,0.0235309,0.01568734],factorA:1,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.5,sssSpecularBlendFactor:0,sssColor:[0.2745156,0,0],specular:{color:[0.2000051,0.08627796,0.01960913],factorA:1,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0}},{halfLambertFactor:0.5,sssSpecularBlendFactor:0,sssColor:[0.2000051,0.08235628,0.00392195],specular:{color:[0.2000051,0.1686323,0.0235309],factorA:1,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0}},{halfLambertFactor:0.5,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.08235628,0.0235309],specular:{color:[0.09412124,0.1647106,0.0235309],factorA:1,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0}},{halfLambertFactor:0.5,sssSpecularBlendFactor:0,sssColor:[0,0.04706119,0.03529608],specular:{color:[0,0.09412124,0.03529608],factorA:1,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0}},{halfLambertFactor:0.5,sssSpecularBlendFactor:0,sssColor:[0,0.02745257,0.1411809],specular:{color:[0.00784381,0.05490454,0.1411809],factorA:1,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0}},{halfLambertFactor:0.5,sssSpecularBlendFactor:0,sssColor:[0.01176563,0.06666958,0.1725539],specular:{color:[0.04706119,0.1725539,0.2156916],factorA:1,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0}},{halfLambertFactor:0.5,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.03529608,0.09804292],specular:{color:[0.1921619,0.07059128,0.09804292],factorA:1,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0}},{halfLambertFactor:0.5,sssSpecularBlendFactor:0,sssColor:[0.01960913,0.01568734,0.1333377],specular:{color:[0.09019956,0.03137433,0.1333377],factorA:1,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0}},{halfLambertFactor:0.5,sssSpecularBlendFactor:0,sssColor:[0,0,0.01568734],specular:{color:[0.03137433,0.01176563,0.00392195],factorA:1,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0}},{halfLambertFactor:0.5,sssSpecularBlendFactor:0,sssColor:[0.04313947,0.08627796,0.1725539],specular:{color:[0.2196132,0.1725539,0.1725539],factorA:1,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0}},{halfLambertFactor:0.5,sssSpecularBlendFactor:0,sssColor:[0,0,0],specular:{color:[0.01960913,0.01960913,0.01960913],factorA:1,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0}}],xp=[{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0.3333392,0,0.00392195],specular:{color:[0.2470644,0,0.00784381],factorA:2,factorB:0,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0.5098094,0.2745156,0.03921773],specular:{color:[0.2156916,0.1451026,0.02745257],factorA:2,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0.3921627,0.1372593,0.03921773],specular:{color:[0.2352996,0.1176511,0.03921773],factorA:1.1,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0.1176511,0.3137313,0.03921773],specular:{color:[0.1098079,0.2470644,0.01960913],factorA:2,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0.03921773,0.1176511,0.05098281],specular:{color:[0.01960913,0.1176511,0.01960913],factorA:2,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0.01960913,0.05882626,0.1960836],specular:{color:[0.00392195,0.02745257,0.2627507],factorA:2,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0.07843459,0.2235348,0.345104],specular:{color:[0.06274787,0.1647106,0.2392212],factorA:2,factorB:0.8,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0.3137313,0.05882626,0.07843459],specular:{color:[0.2745156,0.05882626,0.07843459],factorA:2,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0.1176511,0.02745257,0.3411824],specular:{color:[0.08627796,0.01176563,0.1725539],factorA:2,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0.03921773,0.01960913,0.00784381],specular:{color:[0.03921773,0.01960913,0.00784381],factorA:2,factorB:0.02,shinness:2},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0.4862802,0.4862802,0.3921627],specular:{color:[0.1568674,0.1568674,0.1176511],factorA:2,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.6,sssSpecularBlendFactor:1,sssColor:[0,0,0],specular:{color:[0.00784381,0.00784381,0.00784381],factorA:2,factorB:0.02,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}}],yp=[{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.00784381,0.00392195,0.00392195],specular:{color:[0.01960913,0.01568734,0.01568734],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01176563,0.00392195,0],specular:{color:[0.1254943,0.04706119,0.00784381],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01568734,0.00392195,0],specular:{color:[0.1803971,0.03529608,0.00392195],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.00784381,0.00392195],specular:{color:[0.2431428,0.09019956,0.01176563],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.0235309,0.02745257],specular:{color:[0.1411809,0.1411809,0.1490242],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01176563,0.01176563,0],specular:{color:[0.1529458,0.09412124,0.00784381],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.01568734,0.00392195],specular:{color:[0.2666723,0.1372593,0.01176563],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03921773,0.03137433,0.01176563],specular:{color:[0.407849,0.250986,0.04313947],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0,0,0],specular:{color:[0.01176563,0.01176563,0.01176563],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01960913,0.01960913,0.01960913],specular:{color:[0.1254943,0.1333377,0.1333377],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01960913,0.01176563,0.00784381],specular:{color:[0.2000051,0.09412124,0.0235309],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01568734,0.01568734,0.00784381],specular:{color:[0.1882403,0.1451026,0.02745257],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01176563,0.01568734,0.03137433],specular:{color:[0.08235628,0.129416,0.3294176],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.00784381,0.01960913,0.01568734],specular:{color:[0.06274787,0.1725539,0.1725539],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01568734,0.00784381,0],specular:{color:[0.1882403,0.08627796,0.00784381],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03137433,0,0],specular:{color:[0.3294176,0.0235309,0.00392195],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.00392195,0.00784381,0.01960913],specular:{color:[0.03529608,0.07451299,0.2039268],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03137433,0.01568734,0],specular:{color:[0.3294176,0.1490242,0],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.01960913,0.01960913],specular:{color:[0.1411809,0.1333377,0.1215728],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03921773,0.01568734,0],specular:{color:[0.4235353,0.1254943,0.00392195],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0,0,0],specular:{color:[0.01960913,0.01960913,0.01960913],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.01176563,0.01176563],specular:{color:[0.4784371,0.1098079,0.03921773],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.02745257,0.01960913],specular:{color:[0.4705939,0.2392212,0.06666958],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.02745257,0.01568734,0.01176563],specular:{color:[0.2745156,0.1254943,0.03529608],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.00392195,0.00392195],specular:{color:[0.2588292,0.05882626,0.01960913],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.01960913,0.01960913],specular:{color:[0.4980448,0.1803971,0.05882626],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.03137433,0.03137433],specular:{color:[0.4980448,0.2392212,0.09412124],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.03529608,0.03529608],specular:{color:[0.4980448,0.298045,0.1058862],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01960913,0.00784381,0.00784381],specular:{color:[0.2235348,0.07059128,0.03137433],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.02745257,0.00392195,0.01176563],specular:{color:[0.298045,0.04706119,0.03529608],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.00392195,0.01176563],specular:{color:[0.2705939,0.03529608,0.03529608],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03529608,0.01176563,0.01176563],specular:{color:[0.352947,0.09412124,0.03529608],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03529608,0.00392195,0.01568734],specular:{color:[0.3882412,0.04706119,0.04706119],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03137433,0.01568734,0.0235309],specular:{color:[0.345104,0.129416,0.07451299],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03529608,0.01568734,0.01960913],specular:{color:[0.3882412,0.129416,0.06274787],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.01960913,0.02745257],specular:{color:[0.4902016,0.1803971,0.08627796],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.03137433,0.03921773],specular:{color:[0.4941232,0.2666723,0.1176511],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.03921773,0.03921773],specular:{color:[0.4980448,0.3137313,0.1254943],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.00784381,0.00392195,0.01176563],specular:{color:[0.09412124,0.04313947,0.03529608],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.00784381,0.00784381,0.01176563],specular:{color:[0.06274787,0.06274787,0.1176511],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01176563,0.00392195,0.01176563],specular:{color:[0.1490242,0.03529608,0.04313947],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01960913,0.01176563,0.03137433],specular:{color:[0.2156916,0.1019645,0.1019645],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.01568734,0.03529608],specular:{color:[0.2588292,0.1411809,0.1058862],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03529608,0.0235309,0.03921773],specular:{color:[0.3764764,0.2039268,0.1176511],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03137433,0.02745257,0.03921773],specular:{color:[0.1960836,0.2274563,0.3921627],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03529608,0.03137433,0.04313947],specular:{color:[0.231378,0.2666723,0.4509861],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04313947,0.03529608,0.04706119],specular:{color:[0.278437,0.298045,0.4902016],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03921773,0.03529608,0.04313947],specular:{color:[0.2470644,0.3058882,0.4627508],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.00392195,0.00392195,0.01176563],specular:{color:[0.02745257,0.04706119,0.1254943],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0,0.01176563,0.01960913],specular:{color:[0.01960913,0.09804292,0.2000051],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.00784381,0.0235309,0.03921773],specular:{color:[0.04706119,0.2039268,0.4156921],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01568734,0.03529608,0.04706119],specular:{color:[0.1019645,0.2823587,0.4745156],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.03529608,0.04313947],specular:{color:[0.1411809,0.3058882,0.4353],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.03137433,0.04706119],specular:{color:[0.1607891,0.2588292,0.4902016],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.03529608,0.04706119],specular:{color:[0.1529458,0.2941234,0.4902016],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03137433,0.04313947,0.04706119],specular:{color:[0.1882403,0.352947,0.4980448],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0,0.00784381,0.00784381],specular:{color:[0.01176563,0.07059128,0.1058862],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0,0.01176563,0.00784381],specular:{color:[0,0.09412124,0.1137294],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0,0.01176563,0.01568734],specular:{color:[0.01176563,0.1215728,0.1725539],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.00392195,0.01960913,0.01568734],specular:{color:[0.03921773,0.1568674,0.1921619],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.00784381,0.0235309,0.02745257],specular:{color:[0.05490454,0.1960836,0.2745156],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01176563,0.03137433,0.03137433],specular:{color:[0.09019956,0.2705939,0.345104],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.03529608,0.02745257],specular:{color:[0.1411809,0.3058882,0.3098098],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.03921773,0.03529608],specular:{color:[0.1490242,0.3294176,0.3764764],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.04313947,0.03529608],specular:{color:[0.1568674,0.3568686,0.3568686],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0,0.01176563,0.00784381],specular:{color:[0.01960913,0.1137294,0.02745257],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01176563,0.0235309,0],specular:{color:[0.129416,0.1882403,0],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0,0.01960913,0.01568734],specular:{color:[0.00392195,0.1803971,0.05490454],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.00784381,0.02745257,0.01960913],specular:{color:[0.1058862,0.2392212,0.06274787],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01176563,0.03137433,0.00392195],specular:{color:[0.1451026,0.2705939,0.01176563],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.02745257,0.03529608,0],specular:{color:[0.2862803,0.298045,0.00392195],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01568734,0.03529608,0.0235309],specular:{color:[0.1921619,0.3098098,0.07843459],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.02745257,0.04313947,0.01176563],specular:{color:[0.3098098,0.3490255,0.03529608],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.02745257,0.04313947,0.0235309],specular:{color:[0.2941234,0.345104,0.07059128],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03529608,0.04706119,0.03137433],specular:{color:[0.3647118,0.3764764,0.09804292],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.02745257,0.02745257,0.00784381],specular:{color:[0.298045,0.2274563,0.0235309],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03137433,0.02745257,0.01568734],specular:{color:[0.3254961,0.231378,0.05490454],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03921773,0.03529608,0.00784381],specular:{color:[0.4000058,0.298045,0.03137433],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03921773,0.03529608,0.0235309],specular:{color:[0.4000058,0.2902018,0.07843459],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03921773,0.03921773,0.0235309],specular:{color:[0.4235353,0.3176529,0.07451299],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03921773,0.03921773,0.01960913],specular:{color:[0.4156921,0.3372608,0.06274787],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03921773,0.04313947,0.0235309],specular:{color:[0.4156921,0.3607903,0.07451299],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03921773,0.04706119,0.02745257],specular:{color:[0.4235353,0.3921627,0.09019956],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.01176563,0],specular:{color:[0.2431428,0.1058862,0],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04313947,0.03529608,0.0235309],specular:{color:[0.4509861,0.2902018,0.07059128],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.04313947,0.01176563],specular:{color:[0.4980448,0.352947,0.04313947],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.04313947,0.0235309],specular:{color:[0.4902016,0.345104,0.07451299],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.04313947,0.02745257],specular:{color:[0.4823586,0.3647118,0.09019956],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.04706119,0.02745257],specular:{color:[0.4902016,0.3882412,0.09019956],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03137433,0.01176563,0.00392195],specular:{color:[0.3254961,0.1176511,0.01568734],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.02745257,0],specular:{color:[0.4980448,0.2352996,0.00392195],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03921773,0.02745257,0.01960913],specular:{color:[0.407849,0.2431428,0.05882626],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.03137433,0.01960913],specular:{color:[0.4980448,0.278437,0.05882626],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04706119,0.03529608,0.02745257],specular:{color:[0.4980448,0.3019665,0.08235628],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04313947,0.03921773,0.03137433],specular:{color:[0.4470646,0.3215744,0.1019645],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.01176563,0.01176563,0.01176563],specular:{color:[0.07843459,0.07843459,0.07843459],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.02745257,0.02745257,0.02745257],specular:{color:[0.1843188,0.1843188,0.1843188],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.03529608,0.03529608,0.03529608],specular:{color:[0.2235348,0.2235348,0.2235348],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.04313947,0.03921773,0.03921773],specular:{color:[0.2588292,0.250986,0.2431428],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.45,sssSpecularBlendFactor:1,sssColor:[0.0235309,0.0235309,0.0235309],specular:{color:[0.00392195,0.00392195,0.00392195],factorA:1,factorB:0.06,shinness:0.8},rimLight:{color:[0,0,0],power:1,width:0.5}}],hp=[{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.00784381,0.00392195,0.00392195],specular:{color:[0.01960913,0.01568734,0.01568734],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01176563,0.00392195,0],specular:{color:[0.1254943,0.04706119,0.00784381],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01568734,0.00392195,0],specular:{color:[0.1803971,0.03529608,0.00392195],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.00784381,0.00392195],specular:{color:[0.2431428,0.09019956,0.01176563],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.0235309,0.02745257],specular:{color:[0.1411809,0.1411809,0.1490242],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01176563,0.01176563,0],specular:{color:[0.1529458,0.09412124,0.00784381],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.01568734,0.00392195],specular:{color:[0.2666723,0.1372593,0.01176563],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03921773,0.03137433,0.01176563],specular:{color:[0.407849,0.250986,0.04313947],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0,0,0],specular:{color:[0.01176563,0.01176563,0.01176563],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01960913,0.01960913,0.01960913],specular:{color:[0.1254943,0.1333377,0.1333377],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01960913,0.01176563,0.00784381],specular:{color:[0.2000051,0.09412124,0.0235309],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01568734,0.01568734,0.00784381],specular:{color:[0.1882403,0.1451026,0.02745257],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01176563,0.01568734,0.03137433],specular:{color:[0.08235628,0.129416,0.3294176],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.00784381,0.01960913,0.01568734],specular:{color:[0.06274787,0.1725539,0.1725539],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01568734,0.00784381,0],specular:{color:[0.1882403,0.08627796,0.00784381],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03137433,0,0],specular:{color:[0.3294176,0.0235309,0.00392195],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.00392195,0.00784381,0.01960913],specular:{color:[0.03529608,0.07451299,0.2039268],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03137433,0.01568734,0],specular:{color:[0.3294176,0.1490242,0],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.01960913,0.01960913],specular:{color:[0.1411809,0.1333377,0.1215728],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03921773,0.01568734,0],specular:{color:[0.4235353,0.1254943,0.00392195],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0,0,0],specular:{color:[0.01960913,0.01960913,0.01960913],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.01176563,0.01176563],specular:{color:[0.4784371,0.1098079,0.03921773],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.02745257,0.01960913],specular:{color:[0.4705939,0.2392212,0.06666958],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.02745257,0.01568734,0.01176563],specular:{color:[0.2745156,0.1254943,0.03529608],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.00392195,0.00392195],specular:{color:[0.2588292,0.05882626,0.01960913],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.01960913,0.01960913],specular:{color:[0.4980448,0.1803971,0.05882626],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.03137433,0.03137433],specular:{color:[0.4980448,0.2392212,0.09412124],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.03529608,0.03529608],specular:{color:[0.4980448,0.298045,0.1058862],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01960913,0.00784381,0.00784381],specular:{color:[0.2235348,0.07059128,0.03137433],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.02745257,0.00392195,0.01176563],specular:{color:[0.298045,0.04706119,0.03529608],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.00392195,0.01176563],specular:{color:[0.2705939,0.03529608,0.03529608],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03529608,0.01176563,0.01176563],specular:{color:[0.352947,0.09412124,0.03529608],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03529608,0.00392195,0.01568734],specular:{color:[0.3882412,0.04706119,0.04706119],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03137433,0.01568734,0.0235309],specular:{color:[0.345104,0.129416,0.07451299],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03529608,0.01568734,0.01960913],specular:{color:[0.3882412,0.129416,0.06274787],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.01960913,0.02745257],specular:{color:[0.4902016,0.1803971,0.08627796],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.03137433,0.03921773],specular:{color:[0.4941232,0.2666723,0.1176511],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.03921773,0.03921773],specular:{color:[0.4980448,0.3137313,0.1254943],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.00784381,0.00392195,0.01176563],specular:{color:[0.09412124,0.04313947,0.03529608],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.00784381,0.00784381,0.01176563],specular:{color:[0.06274787,0.06274787,0.1176511],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01176563,0.00392195,0.01176563],specular:{color:[0.1490242,0.03529608,0.04313947],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01960913,0.01176563,0.03137433],specular:{color:[0.2156916,0.1019645,0.1019645],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.01568734,0.03529608],specular:{color:[0.2588292,0.1411809,0.1058862],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03529608,0.0235309,0.03921773],specular:{color:[0.3764764,0.2039268,0.1176511],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03137433,0.02745257,0.03921773],specular:{color:[0.1960836,0.2274563,0.3921627],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03529608,0.03137433,0.04313947],specular:{color:[0.231378,0.2666723,0.4509861],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04313947,0.03529608,0.04706119],specular:{color:[0.278437,0.298045,0.4902016],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03921773,0.03529608,0.04313947],specular:{color:[0.2470644,0.3058882,0.4627508],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.00392195,0.00392195,0.01176563],specular:{color:[0.02745257,0.04706119,0.1254943],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0,0.01176563,0.01960913],specular:{color:[0.01960913,0.09804292,0.2000051],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.00784381,0.0235309,0.03921773],specular:{color:[0.04706119,0.2039268,0.4156921],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01568734,0.03529608,0.04706119],specular:{color:[0.1019645,0.2823587,0.4745156],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.03529608,0.04313947],specular:{color:[0.1411809,0.3058882,0.4353],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.03137433,0.04706119],specular:{color:[0.1607891,0.2588292,0.4902016],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.03529608,0.04706119],specular:{color:[0.1529458,0.2941234,0.4902016],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03137433,0.04313947,0.04706119],specular:{color:[0.1882403,0.352947,0.4980448],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0,0.00784381,0.00784381],specular:{color:[0.01176563,0.07059128,0.1058862],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0,0.01176563,0.00784381],specular:{color:[0,0.09412124,0.1137294],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0,0.01176563,0.01568734],specular:{color:[0.01176563,0.1215728,0.1725539],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.00392195,0.01960913,0.01568734],specular:{color:[0.03921773,0.1568674,0.1921619],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.00784381,0.0235309,0.02745257],specular:{color:[0.05490454,0.1960836,0.2745156],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01176563,0.03137433,0.03137433],specular:{color:[0.09019956,0.2705939,0.345104],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.03529608,0.02745257],specular:{color:[0.1411809,0.3058882,0.3098098],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.03921773,0.03529608],specular:{color:[0.1490242,0.3294176,0.3764764],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.04313947,0.03529608],specular:{color:[0.1568674,0.3568686,0.3568686],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0,0.01176563,0.00784381],specular:{color:[0.01960913,0.1137294,0.02745257],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01176563,0.0235309,0],specular:{color:[0.129416,0.1882403,0],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0,0.01960913,0.01568734],specular:{color:[0.00392195,0.1803971,0.05490454],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.00784381,0.02745257,0.01960913],specular:{color:[0.1058862,0.2392212,0.06274787],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01176563,0.03137433,0.00392195],specular:{color:[0.1451026,0.2705939,0.01176563],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.02745257,0.03529608,0],specular:{color:[0.2862803,0.298045,0.00392195],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01568734,0.03529608,0.0235309],specular:{color:[0.1921619,0.3098098,0.07843459],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.02745257,0.04313947,0.01176563],specular:{color:[0.3098098,0.3490255,0.03529608],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.02745257,0.04313947,0.0235309],specular:{color:[0.2941234,0.345104,0.07059128],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03529608,0.04706119,0.03137433],specular:{color:[0.3647118,0.3764764,0.09804292],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.02745257,0.02745257,0.00784381],specular:{color:[0.298045,0.2274563,0.0235309],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03137433,0.02745257,0.01568734],specular:{color:[0.3254961,0.231378,0.05490454],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03921773,0.03529608,0.00784381],specular:{color:[0.4000058,0.298045,0.03137433],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03921773,0.03529608,0.0235309],specular:{color:[0.4000058,0.2902018,0.07843459],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03921773,0.03921773,0.0235309],specular:{color:[0.4235353,0.3176529,0.07451299],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03921773,0.03921773,0.01960913],specular:{color:[0.4156921,0.3372608,0.06274787],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03921773,0.04313947,0.0235309],specular:{color:[0.4156921,0.3607903,0.07451299],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03921773,0.04706119,0.02745257],specular:{color:[0.4235353,0.3921627,0.09019956],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.01176563,0],specular:{color:[0.2431428,0.1058862,0],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04313947,0.03529608,0.0235309],specular:{color:[0.4509861,0.2902018,0.07059128],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.04313947,0.01176563],specular:{color:[0.4980448,0.352947,0.04313947],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.04313947,0.0235309],specular:{color:[0.4902016,0.345104,0.07451299],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.04313947,0.02745257],specular:{color:[0.4823586,0.3647118,0.09019956],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.04706119,0.02745257],specular:{color:[0.4902016,0.3882412,0.09019956],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03137433,0.01176563,0.00392195],specular:{color:[0.3254961,0.1176511,0.01568734],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.02745257,0],specular:{color:[0.4980448,0.2352996,0.00392195],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03921773,0.02745257,0.01960913],specular:{color:[0.407849,0.2431428,0.05882626],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.03137433,0.01960913],specular:{color:[0.4980448,0.278437,0.05882626],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04706119,0.03529608,0.02745257],specular:{color:[0.4980448,0.3019665,0.08235628],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04313947,0.03921773,0.03137433],specular:{color:[0.4470646,0.3215744,0.1019645],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.01176563,0.01176563,0.01176563],specular:{color:[0.07843459,0.07843459,0.07843459],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.02745257,0.02745257,0.02745257],specular:{color:[0.1843188,0.1843188,0.1843188],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.03529608,0.03529608,0.03529608],specular:{color:[0.2235348,0.2235348,0.2235348],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.04313947,0.03921773,0.03921773],specular:{color:[0.2588292,0.250986,0.2431428],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}},{halfLambertFactor:0.2,sssSpecularBlendFactor:0,sssColor:[0.0235309,0.0235309,0.0235309],specular:{color:[0.00392195,0.00392195,0.00392195],factorA:1,factorB:0,shinness:1.3},rimLight:{color:[0,0,0],power:1,width:0.5}}];var rK1=` -// 頂点シェーダーに入力される attribute 変数 -//attribute vec4 position; //!< 入力: 位置情報 -//attribute vec2 uv; //!< 入力: テクスチャー座標 -//attribute vec3 normal; //!< 入力: 法線ベクトル -// All provided by three.js ^^ - -// vertex color is not actually the color of the shape, as such -// it is a custom attribute _COLOR in the glTF - -attribute vec4 _color; //!< 入力: 頂点の色 -attribute vec3 tangent; //!< 入力: 異方位 - -// フラグメントシェーダーへの入力 -varying vec4 v_color; //!< 出力: 頂点の色 -varying vec4 v_position; //!< 出力: 位置情報 -varying vec3 v_normal; //!< 出力: 法線ベクトル -varying vec3 v_tangent; //!< 出力: 異方位 -varying vec2 v_texCoord; //!< 出力: テクスチャー座標 - -// ユニフォーム -//uniform mat3 normalMatrix; //!< ユニフォーム: モデルの法線用行列 -//uniform mat4 modelViewMatrix; //!< ユニフォーム: プロジェクション行列 -//uniform mat4 projectionMatrix; //!< ユニフォーム: モデル行列 -// All provided by three.js ^^ - -// skinning_pars_vertex.glsl.js -#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif - -void main() -{ - - // begin_vertex.glsl.js - vec3 transformed = vec3( position ); -// skinbase_vertex.glsl.js -#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); - // skinning_vertex.glsl.js - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif - -//#ifdef FFL_COORDINATE_MODE_NORMAL - // 頂点座標を変換 - v_position = modelViewMatrix * vec4(transformed, 1.0); - gl_Position = projectionMatrix * v_position; - - vec3 objectNormal = normal; - vec3 objectTangent = tangent.xyz; -// skinnormal_vertex.glsl.js -#ifdef USE_SKINNING - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - - objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; - objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; - -#endif - - // 法線も変換 - //v_normal = mat3(inverse(u_mv)) * a_normal; - v_normal = normalize(normalMatrix * objectNormal); -//#elif defined(FFL_COORDINATE_MODE_NONE) -// // 頂点座標を変換 -// gl_Position = vec4(a_position.x, a_position.y * -1.0, a_position.z, a_position.w); -// v_position = a_position; -// -// v_normal = a_normal; -//#endif - - // その他の情報も書き出す - v_texCoord = uv; - // safe normalize - if (tangent != vec3(0.0, 0.0, 0.0)) - { - v_tangent = normalize(normalMatrix * objectTangent); - } - else - { - v_tangent = vec3(0.0, 0.0, 0.0); - } - - v_color = _color; -} -`,tK1=` -// -// sample.flg -// Fragment shader -// Copyright (c) 2014 Nintendo Co., Ltd. All rights reserved. -// -// - -#ifdef GL_ES -precision mediump float; -#else -# define lowp -# define mediump -# define highp -#endif - - -// -// 定数定義ファイル -// - -/// シェーダーモード -#define FFL_SHADER_MODE_UR 0 -#define FFL_SHADER_MODE_UB 1 - -/// 変調処理のマクロ -#define FFL_MODULATE_MODE_CONSTANT 0 -#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 -#define FFL_MODULATE_MODE_RGB_LAYERED 2 -#define FFL_MODULATE_MODE_ALPHA 3 -#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 -#define FFL_MODULATE_MODE_ALPHA_OPA 5 - -/// スペキュラのモード -#define FFL_SPECULAR_MODE_BLINN 0 -#define FFL_SPECULAR_MODE_ANISO 1 - -/// ライトのON/OFF -#define FFL_LIGHT_MODE_DISABLE 0 -#define FFL_LIGHT_MODE_ENABLE 1 - -/// フラグメントのディスカードモード -#define FFL_DISCARD_FRAGMENT_DISABLE 0 -#define FFL_DISCARD_FRAGMENT_ENABLE 1 - -/// 座標変換モード -#define FFL_COORDINATE_MODE_NONE 0 -#define FFL_COORDINATE_MODE_NORMAL 1 - -// -// 関数の定義ファイル -// - -/** - * @brief 異方性反射の反射率を計算します。 - * @param[in] light ライトの向き - * @param[in] tangent 接線 - * @param[in] eye 視線の向き - * @param[in] power 鋭さ - */ -mediump float calculateAnisotropicSpecular(mediump vec3 light, mediump vec3 tangent, mediump vec3 eye, mediump float power ) -{ - mediump float dotLT = dot(light, tangent); - mediump float dotVT = dot(eye, tangent); - mediump float dotLN = sqrt(1.0 - dotLT * dotLT); - mediump float dotVR = dotLN*sqrt(1.0 - dotVT * dotVT) - dotLT * dotVT; - - return pow(max(0.0, dotVR), power); -} - -/** - * @brief 異方性反射の反射率を計算します。 - * @param[in] light ライトの向き - * @param[in] normal 法線 - * @param[in] eye 視線の向き - * @param[in] power 鋭さ - */ -mediump float calculateBlinnSpecular(mediump vec3 light, mediump vec3 normal, mediump vec3 eye, mediump float power) -{ - return pow(max(dot(reflect(-light, normal), eye), 0.0), power); -} - -/** - * @brief 異方性反射、ブリン反射をブレンドします。 - * @param[in] blend ブレンド率 - * @param[in] blinn ブリンの値 - * @param[in] aniso 異方性の値 - */ -mediump float calculateSpecularBlend(mediump float blend, mediump float blinn, mediump float aniso) -{ - return mix(aniso, blinn, blend); -} - -/** - * @brief アンビエントを計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - */ -mediump vec3 calculateAmbientColor(mediump vec3 light, mediump vec3 material) -{ - return light * material; -} - -/** - * @brief 拡散を計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - * @param[in] ln ライトと法線の内積 - */ -mediump vec3 calculateDiffuseColor(mediump vec3 light, mediump vec3 material, mediump float ln) -{ - return light * material * ln; -} - -/** - * @brief 鏡面反射を計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - * @param[in] reflection 反射率 - * @param[in] strength 幅 - */ -mediump vec3 calculateSpecularColor(mediump vec3 light, mediump vec3 material, mediump float reflection, mediump float strength) -{ - return light * material * reflection * strength; -} - -/** - * @brief リムを計算します。 - * @param[in] color リム色 - * @param[in] normalZ 法線のZ方向 - * @param[in] width リム幅 - * @param[in] power リムの鋭さ - */ -mediump vec3 calculateRimColor(mediump vec3 color, mediump float normalZ, mediump float width, mediump float power) -{ - return color * pow(width * (1.0 - abs(normalZ)), power); -} - -/** - * @brief ライト方向と法線の内積を求める - * @note 特殊な実装になっています。 - */ -mediump float calculateDot(mediump vec3 light, mediump vec3 normal) -{ - return max(dot(light, normal), 0.1); -} - -// フラグメントシェーダーに入力される varying 変数 -varying mediump vec4 v_color; //!< 出力: 頂点の色 -varying highp vec4 v_position; //!< 出力: 位置情報 -varying highp vec3 v_normal; //!< 出力: 法線ベクトル -// NOTE: ^^ Those two need to be highp to avoid weird black dot issue on Android -varying mediump vec3 v_tangent; //!< 出力: 異方位 -varying mediump vec2 v_texCoord; //!< 出力: テクスチャー座標 - -/// constカラー -uniform mediump vec4 u_const1; ///< constカラー1 -uniform mediump vec4 u_const2; ///< constカラー2 -uniform mediump vec4 u_const3; ///< constカラー3 - -/// ライト設定 -uniform mediump vec3 u_light_ambient; ///< カメラ空間のライト方向 -uniform mediump vec3 u_light_diffuse; ///< 拡散光用ライト -uniform mediump vec3 u_light_dir; -uniform bool u_light_enable; -uniform mediump vec3 u_light_specular; ///< 鏡面反射用ライト強度 - -/// マテリアル設定 -uniform mediump vec3 u_material_ambient; ///< 環境光用マテリアル設定 -uniform mediump vec3 u_material_diffuse; ///< 拡散光用マテリアル設定 -uniform mediump vec3 u_material_specular; ///< 鏡面反射用マテリアル設定 -uniform int u_material_specular_mode; ///< スペキュラの反射モード(CharModelに依存する設定のためub_modulateにしている) -uniform mediump float u_material_specular_power; ///< スペキュラの鋭さ(0.0を指定すると頂点カラーの設定が利用される) - -/// 変調設定 -uniform int u_mode; ///< 描画モード - -/// リム設定 -uniform mediump vec3 u_rim_color; -uniform mediump float u_rim_power; - -// サンプラー -uniform sampler2D s_texture; - - -// ------------------------------------------------------- -// メイン文 -void main() -{ - mediump vec4 color; - - mediump float specularPower = u_material_specular_power; - mediump float rimWidth = v_color.a; - -//#ifdef FFL_MODULATE_MODE_CONSTANT - if(u_mode == FFL_MODULATE_MODE_CONSTANT) - { - color = u_const1; - } -//#elif defined(FFL_MODULATE_MODE_TEXTURE_DIRECT) - else if(u_mode == FFL_MODULATE_MODE_TEXTURE_DIRECT) - { - color = texture2D(s_texture, v_texCoord); - } -//#elif defined(FFL_MODULATE_MODE_RGB_LAYERED) - else if(u_mode == FFL_MODULATE_MODE_RGB_LAYERED) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.r * u_const1.rgb + color.g * u_const2.rgb + color.b * u_const3.rgb, color.a); - } -//#elif defined(FFL_MODULATE_MODE_ALPHA) - else if(u_mode == FFL_MODULATE_MODE_ALPHA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(u_const1.rgb, color.r); - } -//#elif defined(FFL_MODULATE_MODE_LUMINANCE_ALPHA) - else if(u_mode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.g * u_const1.rgb, color.r); - } -//#elif defined(FFL_MODULATE_MODE_ALPHA_OPA) - else if(u_mode == FFL_MODULATE_MODE_ALPHA_OPA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.r * u_const1.rgb, 1.0); - } -//#endif - - // avoids little outline around mask elements - if(u_mode != FFL_MODULATE_MODE_CONSTANT && color.a == 0.0) - { - discard; - } - -//#ifdef FFL_LIGHT_MODE_ENABLE - if(u_light_enable) - { - /// 環境光の計算 - mediump vec3 ambient = calculateAmbientColor(u_light_ambient.xyz, u_material_ambient.xyz); - - /// 法線ベクトルの正規化 - mediump vec3 norm = normalize(v_normal); - - /// 視線ベクトル - mediump vec3 eye = normalize(-v_position.xyz); - - // ライトの向き - mediump float fDot = calculateDot(u_light_dir, norm); - - /// Diffuse計算 - mediump vec3 diffuse = calculateDiffuseColor(u_light_diffuse.xyz, u_material_diffuse.xyz, fDot); - - /// Specular計算 - mediump float specularBlinn = calculateBlinnSpecular(u_light_dir, norm, eye, u_material_specular_power); - - /// Specularの値を確保する変数を宣言 - mediump float reflection; - mediump float strength = v_color.g; - if(u_material_specular_mode == 0) - { - /// Blinnモデルの場合 - strength = 1.0; - reflection = specularBlinn; - } - else - { - /// Aisoモデルの場合 - mediump float specularAniso = calculateAnisotropicSpecular(u_light_dir, v_tangent, eye, u_material_specular_power); - reflection = calculateSpecularBlend(v_color.r, specularBlinn, specularAniso); - } - /// Specularの色を取得 - mediump vec3 specular = calculateSpecularColor(u_light_specular.xyz, u_material_specular.xyz, reflection, strength); - - // リムの色を計算 - mediump vec3 rimColor = calculateRimColor(u_rim_color.rgb, norm.z, rimWidth, u_rim_power); - - // カラーの計算 - color.rgb = (ambient + diffuse) * color.rgb + specular + rimColor; - } -//#endif - - gl_FragColor = color; -} -`;class n6 extends T0{static defaultLightAmbient=new y1(0.73,0.73,0.73);static defaultLightDiffuse=new y1(0.6,0.6,0.6);static defaultLightSpecular=new y1(0.7,0.7,0.7);static defaultLightDir=new I1(-0.4531539381,0.4226179123,0.7848858833);static defaultRimColor=new y1(0.3,0.3,0.3);static defaultRimPower=2;static defaultLightDirection=this.defaultLightDir;static materialParams=[{ambient:new y1(0.85,0.75,0.75),diffuse:new y1(0.75,0.75,0.75),specular:new y1(0.3,0.3,0.3),specularPower:1.2,specularMode:0},{ambient:new y1(1,1,1),diffuse:new y1(0.7,0.7,0.7),specular:new y1(0,0,0),specularPower:40,specularMode:1},{ambient:new y1(0.9,0.85,0.85),diffuse:new y1(0.75,0.75,0.75),specular:new y1(0.22,0.22,0.22),specularPower:1.5,specularMode:0},{ambient:new y1(0.85,0.75,0.75),diffuse:new y1(0.75,0.75,0.75),specular:new y1(0.3,0.3,0.3),specularPower:1.2,specularMode:0},{ambient:new y1(1,1,1),diffuse:new y1(0.7,0.7,0.7),specular:new y1(0.35,0.35,0.35),specularPower:10,specularMode:1},{ambient:new y1(0.75,0.75,0.75),diffuse:new y1(0.72,0.72,0.72),specular:new y1(0.3,0.3,0.3),specularPower:1.5,specularMode:0},{ambient:new y1(1,1,1),diffuse:new y1(0.7,0.7,0.7),specular:new y1(0,0,0),specularPower:40,specularMode:1},{ambient:new y1(1,1,1),diffuse:new y1(0.7,0.7,0.7),specular:new y1(0,0,0),specularPower:40,specularMode:1},{ambient:new y1(1,1,1),diffuse:new y1(0.7,0.7,0.7),specular:new y1(0,0,0),specularPower:40,specularMode:1},{ambient:new y1(0.95622,0.95622,0.95622),diffuse:new y1(0.49673,0.49673,0.49673),specular:new y1(0.24099,0.24099,0.24099),specularPower:3,specularMode:0},{ambient:new y1(0.95622,0.95622,0.95622),diffuse:new y1(1.08497,1.08497,1.08497),specular:new y1(0.2409,0.2409,0.2409),specularPower:3,specularMode:0}];static getBlendOptionsFromModulateType(A){if(A>=0&&A<=5)return{blending:y2,blendSrcAlpha:Z6,blendDstAlpha:F8};else if(A>=6&&A<=8)return{blending:y2,blendSrc:Z6,blendDst:j9,blendDstAlpha:F8};else if(A>=9&&A<=13)return{blending:y2,blendSrc:wQ,blendSrcAlpha:Z6,blendDst:b6};else if(A>=14&&A<=17)return{blending:y2,blendSrc:Z6,blendDst:j9,blendSrcAlpha:F8,blendDstAlpha:F8};else return console.error("Unknown modulate type:",A),{}}modulateMode;modulateType;modulateColor;lightEnable;constructor(A={}){let Q=A.modulateMode??0,J=A.modulateType??0,K=A.lightEnable??!0,C=A.lightDirection??n6.defaultLightDir.clone(),U=A.map||null,Y=A.customMaterial||null,Z={};if(Array.isArray(A.modulateColor)&&A.modulateColor.length===3)Z={u_const1:{value:A.modulateColor[0]},u_const2:{value:A.modulateColor[1]},u_const3:{value:A.modulateColor[2]}};else Z={u_const1:{value:A.modulateColor||new X0(1,1,1,1)}};let X=n6.materialParams[J]||n6.materialParams[0];if(Y)X=Y;let E=Object.assign({},Z,{u_light_ambient:{value:A.lightAmbient||n6.defaultLightAmbient},u_light_diffuse:{value:A.lightDiffuse||n6.defaultLightDiffuse},u_light_specular:{value:A.lightSpecular||n6.defaultLightSpecular},u_light_dir:{value:C},u_light_enable:{value:K},u_material_ambient:{value:X.ambient},u_material_diffuse:{value:X.diffuse},u_material_specular:{value:X.specular},u_material_specular_mode:{value:X.specularMode},u_material_specular_power:{value:X.specularPower},u_mode:{value:Q},u_rim_color:{value:n6.defaultRimColor},u_rim_power:{value:n6.defaultRimPower},s_texture:{value:U}});super({vertexShader:A.vertexShader||rK1,fragmentShader:A.fragmentShader||tK1,uniforms:E,side:A.side||M2,...Q!==0?n6.getBlendOptionsFromModulateType(J):{}});this.modulateMode=Q,this.modulateType=J,this.modulateColor=A.modulateColor,this.lightEnable=K}get map(){return this.uniforms.s_texture.value}set map(A){this.uniforms.s_texture.value=A}get lightDirection(){return this.uniforms.u_light_dir.value}set lightDirection(A){this.uniforms.u_light_dir.value=A}}var eK1=` -#define AGX_FEATURE_ALBEDO_TEXTURE -/** - * @file LUT.vsh - * @brief LUT - * @since 2014/10/02 - * - * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. - */ - -// シェーダーの種類毎に設定されるマクロリスト -// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 -// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 -// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 -// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 -// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 -// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 -// AGX_FEATURE_SKIN_MASK 肌マスクが有効(u_const1) -// AGX_FEATURE_HAIR_MASK 髪マスクが有効(u_const2) -// AGX_FEATURE_ALPHA_TEST アルファテストが有効 -// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(u_const3) -// AGX_FEATURE_DISABLE_LIGHT ライトが無効 -// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 -// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 -// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 -// AGX_FEATURE_MII Miiを描画する -// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant -// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct -// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered -// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha -// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha -// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa -// -// AGX_BONE_MAX ボーンの最大数 - -#ifdef GL_ES -precision highp float; -#else -# define lowp -# define mediump -# define highp -#endif - -//#ifndef AGX_BONE_MAX -//# define AGX_BONE_MAX 15 -//#endif -#ifndef AGX_DIR_LIGHT_MAX -# define AGX_DIR_LIGHT_MAX 2 -#endif - -// ---------------------------------------- -// 頂点シェーダーに入力される attribute 変数 -//attribute highp vec3 position; //!< 入力:[ 1 : 1 ] 位置情報 -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) -//attribute mediump vec2 uv; //!< 入力:[ 1 : 5 ] テクスチャー座標 -#endif -//attribute mediump vec3 normal; //!< 入力:[ 1 : 2 ] 法線ベクトル -//attribute mediump vec4 aBoneIndex; //!< 入力:[ 1 : 3 ] ボーンのインデックス(最大4つ) -//attribute mediump vec4 aBoneWeight; //!< 入力:[ 1 : 4 ] ボーンの影響度(最大4つ) -#if defined(AGX_FEATURE_VERTEX_COLOR) -//attribute lowp vec4 _color; //!< 入力:[ 1 : 6 ] 頂点カラー -#endif -#if defined(AGX_FEATURE_BUMP_TEXTURE) -//attribute mediump vec3 tangent; //!< 入力:[ 1 : 7 ] 接線ベクトル -#endif - -// ^^ Commented attributes are provided by three.js. - -// ---------------------------------------- -// 頂点シェーダーに入力される uniform 変数 -//uniform highp mat4 modelViewMatrix; //!< 入力:[ 4 / 4 : 4 ] モデルの合成行列 -//uniform mat4 projectionMatrix; -//uniform highp mat4 viewMatrix; //!< 入力:[ 4 / 4 : 8 ] モデルのビュー行列 -//uniform mediump mat3 normalMatrix; //!< 入力:[ 3 / 3 : 11 ] モデルの法線用行列 -//uniform highp mat4 modelMatrix; //!< 入力:[ 4 / 4 : 15 ] モデルのワールド変換行列 -//uniform lowp int uBoneCount; //!< 入力:[ 1 / 1 : 16 ] ボーンの個数 -//uniform highp mat4 uBoneMatrices[AGX_BONE_MAX]; //!< 入力:[ 4 x 15 / 60 : 76 ] ボーンの行列配列 -//uniform mediump mat3 uBoneNormalMatrices[AGX_BONE_MAX]; //!< 入力:[ 3 x 15 / 45 : 121 ] ボーンの法線行列配列 -// ^^ Unused in favor of three.js skinning. -uniform lowp int uDirLightCount; //!< 入力:[ 1 / 1 : 122 ] 方向ライトの数 -uniform mediump vec4 uDirLightDirAndType0;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 -uniform mediump vec4 uDirLightDirAndType1;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 -uniform mediump vec3 uDirLightColor0; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー -uniform mediump vec3 uDirLightColor1; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー -uniform mediump vec3 uHSLightSkyColor; //!< 入力:[ 1 / 1 : 127 ] 半球ライトのスカイカラー -uniform mediump vec3 uHSLightGroundColor; //!< 入力:[ 1 / 1 : 128 ] 半球ライトのグラウンドカラー -//uniform mediump vec3 cameraPosition; //!< 入力:[ 1 / 1 : 129 ] カメラの位置 -// ^^ previously uEyePt -uniform mediump float uAlpha; //!< 入力:[ 1 / 1 : 130 ] アルファ値 - -// ^^ Commented uniforms are provided by three.js. - -// ---------------------------------------- -// フラグメントシェーダーに渡される varying 変数 -varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 -#if !defined(AGX_FEATURE_BUMP_TEXTURE) -varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 -#endif -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) -varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV -#endif -// camera -varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル -#if !defined(AGX_FEATURE_DISABLE_LIGHT) -// punctual light -varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 -varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル -// GI -varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー -// Lighting Result -varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 -#endif -// Reflect -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) -varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル -#endif - -// skinning_pars_vertex.glsl.js -#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif - -// ------------------------------------------------------------ -// 頂点シェーダーのエントリーポイント -// ------------------------------------------------------------ -void main() -{ - // ------------------------------------------------------------ - // 頂点変換用の処理 - // ------------------------------------------------------------ - highp vec4 position_; //!< 最終的な頂点 - mediump vec3 normal_; //!< 最終的な法線 - mediump vec3 tangent_; //!< 最終的な接線 - highp vec4 positionWorld; //!< ワールド空間上での頂点 - - - // begin_vertex.glsl.js - vec3 transformed = vec3( position ); -// skinbase_vertex.glsl.js -#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); - // skinning_vertex.glsl.js - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif - - // ---------------------------------------- - // ボーンが存在しない場合は位置と法線に手を加えない - position_ = vec4(transformed.xyz, 1.0); - - - - normal_ = normal; -#if defined(AGX_FEATURE_BUMP_TEXTURE) - tangent_ = tangent.xyz; -#endif - // skinnormal_vertex.glsl.js -#ifdef USE_SKINNING - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - - normal_ = vec4( skinMatrix * vec4( normal_, 0.0 ) ).xyz; -#if defined(AGX_FEATURE_BUMP_TEXTURE) - tangent_ = vec4( skinMatrix * vec4( tangent_, 0.0 ) ).xyz; -#endif // defined(AGX_FEATURE_BUMP_TEXTURE) -#endif // USE_SKINNING - - // ---------------------------------------- - // ワールド上での位置を求める - positionWorld = modelMatrix * position_; - // 最終結果を行う - position_ = projectionMatrix * modelViewMatrix * position_; - normal_ = normalize(normalMatrix * normal_); -#if defined(AGX_FEATURE_BUMP_TEXTURE) - tangent = normalize(normalMatrix * tangent_); -#endif - - // ---------------------------------------- - // 計算結果を保持させる - gl_Position = position_; -#if !defined(AGX_FEATURE_BUMP_TEXTURE) - vNormal = normal_; -#endif -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) - // テクスチャー座標を設定する - vTexcoord0 = uv; -#endif - // モデルの色を指定する -#if defined(AGX_FEATURE_VERTEX_COLOR) - lowp vec4 modelColor = aColor; - -#else - lowp vec4 modelColor = vec4(1.0, 1.0, 1.0, 1.0); -#endif - - // プリマルチプライドアルファ -#if defined(AGX_FEATURE_PREMULTIPLY_ALPHA) - modelColor *= uAlpha; -#else - modelColor.a *= uAlpha; -#endif - - - // ------------------------------------------------------------ - // ライト用の処理 - // ------------------------------------------------------------ - mediump vec3 eyeVecWorld; //!< ワールド状態での視線ベクトル - mediump vec3 eyeVec; //!< 最終的にフラグメントシェーダーに渡す視線ベクトル(バンプの有無によって、ワールド座標系になったり、タンジェント座標系になったりする) - - vec4 eye = modelViewMatrix * position_; - - // 視線ベクトルを取得する - //eyeVecWorld = normalize(cameraPosition - positionWorld.xyz); - eyeVecWorld = normalize(-(eye.xyz) - positionWorld.xyz);//normalize(cameraPosition - positionWorld.xyz); - eyeVec = eyeVecWorld; - - lowp vec3 diffuseColor = vec3(0.0); // バーテックスシェーダーで計算できるディフューズの色をここに格納する - -# if defined(AGX_FEATURE_BUMP_TEXTURE) - // Normal, Binormal, Tangent を取得する - mediump vec3 n = normal; - mediump vec3 t = tangent; - mediump vec3 b = cross(n, t); - // 接空間からローカルへ変換する行列を設定する(mat3(N, T, B)の逆行列) - mediump mat3 tangentMatrix = mat3(t.x, b.x, n.x, t.y, b.y, n.y, t.z, b.z, n.z); - // 視線ベクトルを接空間へ - vEyeVecWorldOrTangent.xyz = tangentMatrix * eyeVec; -#else - vEyeVecWorldOrTangent.xyz = eyeVec; -#endif - -#if !defined(AGX_FEATURE_DISABLE_LIGHT) - // punctual lightの設定 - if (uDirLightCount > 0) - { - mediump vec3 lightDir; - - // 方向ライト - if (uDirLightDirAndType0.w < 0.0) { lightDir = uDirLightDirAndType0.xyz; } - // 点光源ライト - else { lightDir = uDirLightDirAndType0.xyz - positionWorld.xyz; } - lightDir = normalize(lightDir); - -# if defined(AGX_FEATURE_BUMP_TEXTURE) - // ライトを接空間へ - vPunctualLightDirWorldOrTangent.xyz = tangentMatrix * lightDir; -# else - vPunctualLightDirWorldOrTangent.xyz = lightDir; -# endif - - // Halfベクトルを求める - vPunctualLightHalfVecWorldOrTangent.xyz = normalize(vPunctualLightDirWorldOrTangent.xyz + vEyeVecWorldOrTangent.xyz); - - // Diffuse計算 - diffuseColor += (uDirLightColor0.rgb * clamp(dot(lightDir, normal), 0.0, 1.0)); - } - if (uDirLightCount > 1) - { - mediump vec3 lightDir; - - // 方向ライト - if (uDirLightDirAndType1.w < 0.0) { lightDir = uDirLightDirAndType1.xyz; } - // 点光源ライト - else { lightDir = uDirLightDirAndType1.xyz - positionWorld.xyz; } - lightDir = normalize(lightDir); - - diffuseColor += max(dot(lightDir, normal), 0.0) * uDirLightColor1; - } - // ライトは1.0を超えないように - diffuseColor = min(diffuseColor, 1.0); -#endif - -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) - { - // キューブ環境マップ用の反射ベクトルを求める -// vReflectDir = reflect(normalize(positionWorld.xyz - cameraPosition), normal); - - // スフィア環境マップ用の反射ベクトルを求める -// vReflectDir = normalize((uViewMatrix * vec4(normal, 0.0)).xyz) * 0.5 + 0.5; - - // ビュー座標系での位置と法線を取得 - mediump vec3 viewNormal = normalize(mat3(uViewMatrix) * normal); - mediump vec4 viewPosition = uViewMatrix * positionWorld; - viewPosition = viewPosition / viewPosition.w; - // ビュー座標系での頂点ベクトルを取得 - viewPosition.z = 1.0 - viewPosition.z; - mediump vec3 viewPositionVec = normalize(viewPosition.xyz); - // ビュー座標系での反射ベクトルを求める - mediump vec3 viewReflect = viewPositionVec - 2.0 * dot(viewPositionVec, viewNormal) * viewNormal; - // 両面スフィア環境マップではないので、反射ベクトルを調整 - viewReflect = normalize(viewReflect - vec3(0.0, 0.0, 1.5)); - // 反射ベクトルをテクスチャー座標系へ - vReflectDir = viewReflect * 0.5 + 0.5; - - // 公式 -// mediump vec3 viewPositionVec = normalize(vec3(uViewMatrix * positionWorld)); -// mediump vec3 viewReflectVec = viewPositionVec - 2.0 * dot(viewPositionVec, normal) * normal; -// mediump float m = 2.0 * sqrt(viewReflectVec.x * viewReflectVec.x + -// viewReflectVec.y * viewReflectVec.y + -// (viewReflectVec.z + 1.0) * (viewReflectVec.z * 1.0)); -// vReflectDir = viewReflectVec / m + 0.5; - - // 別版 -// mediump vec3 posW = positionWorld.xyz; -// mediump vec3 dir = normalize(mat3(uViewMatrix) * normal); -// -// mediump float radius = 75.0; -// mediump vec3 posWDir = dot(dir, posW) * dir; -// mediump vec3 posWDirV = posW - posWDir; -// mediump float lengthDir = sqrt(radius * radius - dot(posWDirV, posWDirV)) - length(posWDir); -// vReflectDir = normalize(posW + dir * lengthDir) * 0.5 + 0.5; - } -#endif - -#if !defined(AGX_FEATURE_DISABLE_LIGHT) - // GIの計算 - { - mediump vec3 hemiColor; - mediump vec3 sky = uHSLightSkyColor; - mediump vec3 ground = uHSLightGroundColor; - - { - mediump float skyRatio = (normal.y + 1.0) * 0.5; - hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); - diffuseColor += hemiColor; - } - - { -// mediump vec3 reflectDir = -reflect(normal, eyeVecWorld); // おそらくコレで良いはず - mediump vec3 reflectDir = 2.0 * dot(eyeVecWorld, normal) * normal - eyeVecWorld; // 多少冗長でも、正しい計算で行なう - - mediump float skyRatio = (reflectDir.y + 1.0) * 0.5; - hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); - vGISpecularLightColor.rgb = hemiColor; - } - } -#endif - - // モデルの色を設定 - vModelColor = modelColor; -#if !defined(AGX_FEATURE_DISABLE_LIGHT) - vDiffuseColor.rgb = diffuseColor; -#endif -} -`,AC1=` -#define AGX_FEATURE_ALBEDO_TEXTURE -#define AGX_FEATURE_MII -/** - * @file LUT.fsh - * @brief LUT - * @since 2014/10/02 - * - * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. - */ - -// シェーダーの種類毎に設定されるマクロリスト -// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 -// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 -// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 -// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 -// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 -// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 -// AGX_FEATURE_SKIN_MASK 肌マスクが有効(u_const1) -// AGX_FEATURE_HAIR_MASK 髪マスクが有効(u_const2) -// AGX_FEATURE_ALPHA_TEST アルファテストが有効 -// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(u_const3) -// AGX_FEATURE_DISABLE_LIGHT ライトが無効 -// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 -// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 -// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 -// AGX_FEATURE_MII Miiを描画する -// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant -// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct -// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered -// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha -// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha -// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa - -#ifdef GL_ES -precision mediump float; -#else -# define lowp -# define mediump -# define highp -#endif - -/// 変調処理のマクロ -#define FFL_MODULATE_MODE_CONSTANT 0 -#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 -#define FFL_MODULATE_MODE_RGB_LAYERED 2 -#define FFL_MODULATE_MODE_ALPHA 3 -#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 -#define FFL_MODULATE_MODE_ALPHA_OPA 5 - -// ---------------------------------------- -// フラグメントシェーダーに入力される uniform 変数 -uniform int uMode; ///< 描画モード -uniform bool uAlphaTest; -uniform bool uLightEnable; -uniform mediump vec4 u_const1; //!< 入力:[ 1 : 1 ] カラー0 (OR 肌カラー) -uniform mediump vec4 u_const2; //!< 入力:[ 1 : 2 ] カラー1 (OR 髪カラー) -uniform mediump vec4 u_const3; //!< 入力:[ 1 : 3 ] カラー2 (OR フェードアウトカラー) -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -uniform mediump vec3 uLightColor; //!< 入力:[ 1 : 4 ] ライトの色 -//#endif - -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) -uniform sampler2D uAlbedoTexture; //!< 入力: テクスチャー -#endif -#if defined(AGX_FEATURE_BUMP_TEXTURE) -uniform sampler2D uNormalTexture; //!< 入力: ノーマルマップ -#endif -#if defined(AGX_FEATURE_MASK_TEXTURE) -uniform sampler2D uMaskTexture; //!< 入力:マスクテクスチャー -#endif -#if defined(AGX_FEATURE_ALPHA_TEXTURE) -uniform sampler2D uAlphaTexture; //!< 入力:アルファテクスチャー -#endif -uniform sampler2D uLUTSpecTexture; //!< 入力: スペキュラーLUT -uniform sampler2D uLUTFresTexture; //!< 入力: フレネルLUT -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) -uniform sampler2D uSphereMapTexture; //!< 入力: スフィア環境マップ -#endif - -// ---------------------------------------- -// フラグメントシェーダーに渡される varying 変数 -varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 -#if !defined(AGX_FEATURE_BUMP_TEXTURE) -varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 -#endif -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) -varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV -#endif -// camera -varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -// punctual light -varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 -varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル -// GI -varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー -// Lighting Result -varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 -//#endif -// Reflect -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) -varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル -#endif - -// ------------------------------------------------------------ -// フラグメントシェーダーのエントリーポイント -// ------------------------------------------------------------ -void main() -{ - - // ディフューズカラーを取得 - lowp vec4 albedoColor = vec4(1.0, 1.0, 1.0, 1.0); - - // ============================================================ - // Mii - // ============================================================ -#if defined(AGX_FEATURE_MII) - - //#if defined(AGX_FEATURE_MII_CONSTANT) - if(uMode == FFL_MODULATE_MODE_CONSTANT) - { - albedoColor = vec4(u_const1.rgb, 1.0); - } - //#elif defined(AGX_FEATURE_MII_TEXTURE_DIRECT) - else if(uMode == FFL_MODULATE_MODE_TEXTURE_DIRECT) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - } - //#elif defined(AGX_FEATURE_MII_RGB_LAYERED) - else if(uMode == FFL_MODULATE_MODE_RGB_LAYERED) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(albedoColor.r * u_const1.rgb + albedoColor.g * u_const2.rgb + albedoColor.b * u_const3.rgb, - albedoColor.a); - } - //#elif defined(AGX_FEATURE_MII_ALPHA) - else if(uMode == FFL_MODULATE_MODE_ALPHA) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(u_const1.rgb, albedoColor.r); - } - //#elif defined(AGX_FEATURE_MII_LUMINANCE_ALPHA) - else if(uMode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(albedoColor.g * u_const1.rgb, albedoColor.r); - } - //#elif defined(AGX_FEATURE_MII_ALPHA_OPA) - else if(uMode == FFL_MODULATE_MODE_ALPHA_OPA) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(albedoColor.r * u_const1.rgb, 1.0); - } -//#endif - - albedoColor = albedoColor * vModelColor; -#endif - - // ============================================================ - // Albedo Texture - // ============================================================ -#if !defined(AGX_FEATURE_MII) && defined(AGX_FEATURE_ALBEDO_TEXTURE) - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); -#endif -#if defined(AGX_FEATURE_ALPHA_TEXTURE) - albedoColor.a = texture2D(uAlphaTexture, vTexcoord0).r; -#endif - - // ============================================================ - // Color Mask - // ============================================================ - // ---------------------------------------- - // Deprecated -#if defined(AGX_FEATURE_ALPHA_COLOR_FILTER) - // 一部の場所にColor0を反映する - albedoColor.rgb = (albedoColor.rgb * albedoColor.a + u_const1.rgb * (1.0 - albedoColor.a)); - albedoColor.a = 1.0; -#elif defined(AGX_FEATURE_MASK_TEXTURE) - lowp vec3 maskTextureColor = texture2D(uMaskTexture, vTexcoord0).rgb; - -# if defined(AGX_FEATURE_SKIN_MASK) && defined(AGX_FEATURE_HAIR_MASK) - // 肌と髪両方マスクが存在する - lowp float maskColorValue = maskTextureColor.g + maskTextureColor.b; - lowp vec3 maskColor = maskTextureColor.g * u_const1.rgb + maskTextureColor.b * u_const2.rgb; - albedoColor.rgb = (albedoColor.rgb * (1.0 - maskColorValue) + maskColor); - -# elif defined(AGX_FEATURE_SKIN_MASK) - // 肌しかマスクが存在しない - albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.g) + maskTextureColor.g * u_const1.rgb); - -# elif defined(AGX_FEATURE_HAIR_MASK) - // 髪しかマスクが存在しない - albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.b) + maskTextureColor.b * u_const2.rgb); - -# endif -#endif - - // アルベドに頂点カラーを掛ける - albedoColor *= vModelColor; - - // ============================================================ - // Alpha test - // ============================================================ -//#if defined(AGX_FEATURE_ALPHA_TEST) - if (uAlphaTest && albedoColor.a < 0.5) { discard; } -//#endif - - // ============================================================ - // Bumpmap - // ============================================================ - // 頂点からの情報 - lowp vec3 normalWorldOrTangent; -#if defined(AGX_FEATURE_BUMP_TEXTURE) - // バンプマップから法線を取得する - mediump vec3 bumpNormal = texture2D(uNormalTexture, vTexcoord0).rgb; - - // 法線の正規化は処理が重いのでいったん正規化しない様に... -// normalWorldOrTangent = normalize(bumpNormal * 2.0 - 1.0); - normalWorldOrTangent = bumpNormal * 2.0 - 1.0; - -#else - // 法線を正規化して取得する - normalWorldOrTangent = normalize(vNormal); -#endif - - // ============================================================ - // Lighting - // ============================================================ - // 最終的なカラー情報 - lowp vec4 colorOut = vec4(0.0, 0.0, 0.0, albedoColor.a); // 最終的に出力される色 - lowp vec3 fresnel = vec3(0.0, 0.0, 0.0); // フレネル - lowp vec3 specular = vec3(0.0, 0.0, 0.0); // スペキュラー - -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -if (uLightEnable) { - - // BRDFの計算を行う(バンプマッピングの場合は接空間) - lowp vec3 N = normalWorldOrTangent; - lowp vec3 V = vEyeVecWorldOrTangent.xyz;//normalize(vEyeVecWorldOrTangent.xyz); - lowp vec3 I = vPunctualLightDirWorldOrTangent.xyz;//normalize(vPunctualLightDirWorldOrTangent.xyz); - lowp vec3 H = vPunctualLightHalfVecWorldOrTangent.xyz;//normalize(vPunctualLightHalfVecWorldOrTangent.xyz); - - - // ---------------------------------------- - // punctual light - // 平行光源や点光源などの厳密なライティング計算を行なうもの - { - lowp float fSpecular = dot(N, H); - - lowp float specularIntensity = texture2D(uLUTSpecTexture, vec2(fSpecular)).r; - specular = (specularIntensity * uLightColor.rgb); - } - - // ---------------------------------------- - // GI - // 半球ライトやIBL、SHのように法線方向に半球積分された結果でライティング計算を行なうもの - { - lowp float fFresnel = dot(N, V); - lowp float fresnelIntensity = texture2D(uLUTFresTexture, vec2(fFresnel)).r; - - fresnel = (fresnelIntensity * vGISpecularLightColor.rgb); - } -} -//#endif - -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) - // スフィア環境マップ - specular += texture2D(uSphereMapTexture, vReflectDir.xy).rgb; -#endif - - // ============================================================ - // Specular Mask - // ============================================================ -#if !defined(AGX_FEATURE_ALPHA_COLOR_FILTER) && defined(AGX_FEATURE_MASK_TEXTURE) - // スペキュラーマスク - specular = specular * maskTextureColor.r + fresnel; -#else - specular += fresnel; -#endif - - // ============================================================ - // Output - // ============================================================ -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -if (uLightEnable) - colorOut.rgb = vDiffuseColor.rgb * albedoColor.rgb + specular; -//#else -else - colorOut.rgb = albedoColor.rgb; -//#endif - - // フェードアウトを実装する -#if defined(AGX_FEATURE_FADE_OUT_COLOR) - colorOut.rgb = (colorOut.rgb * (1.0 - u_const3.a)) + (u_const3.rgb * u_const3.a); -#endif - - // 色を反映させる - gl_FragColor = colorOut; - - //#include - //#include -} -`;class CJ{keys;constructor(A){this.keys=A.sort((Q,J)=>Q.x-J.x)}interpolate(A,Q,J,K,C){let U=2*A*A*A-3*A*A+1,Y=A*A*A-2*A*A+A,Z=-2*A*A*A+3*A*A,X=A*A*A-A*A;return U*Q+Y*K+Z*J+X*C}clamp(A,Q,J){return Math.min(Math.max(A,Q),J)}generateLUT(A=512){let Q=new Uint8Array(A),J=0;for(let K=0;Kthis.keys[J+1].x)J++;let U=this.keys[J],Y=this.keys[J+1],Z=(C-U.x)/(Y.x-U.x);Z=isNaN(Z)?0:Z;let X=this.interpolate(Z,U.y,Y.y,U.dx*(Y.x-U.x),Y.dx*(Y.x-U.x));Q[K]=Math.round(this.clamp(X,0,1)*255)}return Q}}class UA extends T0{static LUTSpecularTextureType={NONE:0,DEFAULT_02:1,SKIN_01:2,MAX:3};static LUTFresnelTextureType={NONE:0,DEFAULT_02:1,SKIN_01:2,MAX:3};static lutDefinitions={specular:{[UA.LUTSpecularTextureType.NONE]:new CJ([{x:0,y:0,dx:0,dy:0},{x:1,y:0,dx:0,dy:0}]),[UA.LUTSpecularTextureType.DEFAULT_02]:new CJ([{x:0,y:0,dx:0,dy:0},{x:0.05,y:0,dx:0,dy:0},{x:0.8,y:0.038,dx:0.157894736842105,dy:0.157894736842105},{x:1,y:0.11,dx:0,dy:0}]),[UA.LUTSpecularTextureType.SKIN_01]:new CJ([{x:0,y:0.03,dx:-0.105263157894737,dy:-0.105263157894737},{x:1,y:0,dx:0,dy:0}])},fresnel:{[UA.LUTFresnelTextureType.NONE]:new CJ([{x:0,y:0,dx:0,dy:0},{x:1,y:0,dx:0,dy:0}]),[UA.LUTFresnelTextureType.DEFAULT_02]:new CJ([{x:0,y:0.3,dx:-0.105263157894734,dy:-0.105263157894734},{x:0.175,y:0.23,dx:-0.626315789473681,dy:-0.626315789473681},{x:0.6,y:0.05,dx:-0.210526315789474,dy:-0.210526315789474},{x:1,y:0,dx:-0.105263157894737,dy:-0.105263157894737}]),[UA.LUTFresnelTextureType.SKIN_01]:new CJ([{x:0.005,y:0.35,dx:-0.105263157894734,dy:-0.105263157894734},{x:0.173,y:0.319,dx:-0.205263157894734,dy:-0.205263157894734},{x:0.552,y:0.051,dx:-0.210526315789474,dy:-0.210526315789474},{x:1,y:0.001,dx:0,dy:0}])}};static modulateToLUTSpecular=[UA.LUTSpecularTextureType.SKIN_01,UA.LUTSpecularTextureType.DEFAULT_02,UA.LUTSpecularTextureType.SKIN_01,UA.LUTSpecularTextureType.SKIN_01,UA.LUTSpecularTextureType.DEFAULT_02,UA.LUTSpecularTextureType.DEFAULT_02,UA.LUTSpecularTextureType.DEFAULT_02,UA.LUTSpecularTextureType.NONE,UA.LUTSpecularTextureType.NONE,UA.LUTSpecularTextureType.DEFAULT_02,UA.LUTSpecularTextureType.DEFAULT_02];static modulateToLUTFresnel=[UA.LUTFresnelTextureType.SKIN_01,UA.LUTFresnelTextureType.DEFAULT_02,UA.LUTFresnelTextureType.SKIN_01,UA.LUTFresnelTextureType.SKIN_01,UA.LUTFresnelTextureType.DEFAULT_02,UA.LUTFresnelTextureType.DEFAULT_02,UA.LUTFresnelTextureType.DEFAULT_02,UA.LUTFresnelTextureType.NONE,UA.LUTFresnelTextureType.NONE,UA.LUTFresnelTextureType.DEFAULT_02,UA.LUTFresnelTextureType.DEFAULT_02];static _lutTextures=null;static getLUTTextures(A=512){if(!UA._lutTextures){let Q={specular:{},fresnel:{}},J=Number(G5)<137?kQ:E8;for(let[K,C]of Object.entries(UA.lutDefinitions.specular)){let U=C.generateLUT(A),Y=new fA(U,A,1,J,dA);Y.needsUpdate=!0,Q.specular[K]=Y}for(let[K,C]of Object.entries(UA.lutDefinitions.fresnel)){let U=C.generateLUT(A),Y=new fA(U,A,1,J,dA);Y.needsUpdate=!0,Q.fresnel[K]=Y}UA._lutTextures=Q}return UA._lutTextures}static defaultHSLightGroundColor=new y1(0.87843,0.72157,0.5898);static defaultHSLightSkyColor=new y1(0.87843,0.83451,0.80314);static defaultDirLightColor0=new y1(0.35137,0.32392,0.32392);static defaultDirLightColor1=new y1(0.10039,0.09255,0.09255);static defaultDirLightCount=2;static defaultDirLightDirAndType0=new X0(-0.2,0.5,0.8,-1);static defaultDirLightDirAndType1=new X0(0,-0.19612,0.98058,-1);static defaultLightColor=new y1(0.35137,0.32392,0.32392);static defaultLightDirection=this.defaultDirLightDirAndType0;static getBlendOptionsFromModulateType(A){if(A>=0&&A<=5)return{blending:y2,blendSrcAlpha:Z6,blendDstAlpha:F8};else if(A>=6&&A<=8)return{blending:y2,blendSrc:Z6,blendDst:j9,blendDstAlpha:F8};else if(A>=9&&A<=13)return{blending:y2,blendSrc:wQ,blendSrcAlpha:Z6,blendDst:b6};else if(A>=14&&A<=17)return{blending:y2,blendSrc:Z6,blendDst:j9,blendSrcAlpha:F8,blendDstAlpha:F8};else return console.error(`Unknown modulate type: ${A}.`),{}}modulateMode;modulateType;modulateColor;lightEnable;_side;constructor(A={}){let Q=A.modulateMode??0,J=A.modulateType??0,K=A.lightEnable??!0,C=A.map||null,U=J>=6&&J<=8?!0:A.alphaTest,Y=J===6?VA:A.side||M2,Z={};if(Array.isArray(A.modulateColor)&&A.modulateColor.length===3)Z={u_const1:{value:A.modulateColor[0]},u_const2:{value:A.modulateColor[1]},u_const3:{value:A.modulateColor[2]}};else Z={u_const1:{value:A.modulateColor||new X0(1,1,1,1)}};let X=UA.getLUTTextures(),E=UA.modulateToLUTSpecular[J]??UA.LUTSpecularTextureType.NONE,H=UA.modulateToLUTFresnel[J]??UA.LUTFresnelTextureType.NONE,$=X.specular[E],I=X.fresnel[H],N=Object.assign({},Z,{uBoneCount:{value:0},uAlpha:{value:1},uHSLightGroundColor:{value:A.hslightGroundColor||UA.defaultHSLightGroundColor},uHSLightSkyColor:{value:A.hslightSkyColor||UA.defaultHSLightSkyColor},uDirLightColor0:{value:A.dirLightColor0||UA.defaultDirLightColor0},uDirLightColor1:{value:A.dirLightColor1||UA.defaultDirLightColor1},uDirLightCount:{value:A.dirLightCount||UA.defaultDirLightCount},uDirLightDirAndType0:{value:A.dirLightDirAndType0||UA.defaultDirLightDirAndType0.clone()},uDirLightDirAndType1:{value:A.dirLightDirAndType1||UA.defaultDirLightDirAndType1.clone()},uLightEnable:{value:K},uLightColor:{value:A.lightColor||UA.defaultLightColor},uMode:{value:Q},uAlphaTest:{value:U},uAlbedoTexture:{value:C},uLUTSpecTexture:{value:$},uLUTFresTexture:{value:I}});super({vertexShader:A.vertexShader||eK1,fragmentShader:A.fragmentShader||AC1,uniforms:N,side:Y,...Q!==0?UA.getBlendOptionsFromModulateType(J):{}});this.modulateMode=Q,this.modulateType=J,this.modulateColor=A.modulateColor,this.lightEnable=K,this._side=A.side}get map(){return this.uniforms.uAlbedoTexture.value}set map(A){this.uniforms.uAlbedoTexture.value=A}get lightDirection(){return this.uniforms.uDirLightDirAndType0.value}set lightDirection(A){this.uniforms.uDirLightDirAndType0.value=A,this.uniforms.uDirLightDirAndType0.value.w=-1}}function gp(A,Q){A.traverse((J)=>{let K=J;if(K.isMesh)YJ(K,Q)})}async function YJ(A,Q){let J=await SA("shaderType"),K=A.material,C=A.geometry.userData;if(C.ignore!==void 0){if(C.ignore===1)return}let U=C.modulateType;if(C.modulateType===void 0)console.warn(`Mesh "${A.name}" is missing "modulateType" in userData.`);let Y=U>5?!1:!0,Z=U!==void 0?U&&U<9?FG[U]:FG[0]:FG[0],X=uR,E=bR,H=fR,$=pR;function I(){if(J==="wiiu_blinn")Z={...Z,...sf};else if(J==="wiiu_toon")Z={...Z,...of},X=ef;else if(J==="wiiu_ffliconwithbody")X=Ap,E=af,H=rf,$=tf}I();let N=C.modulateMode===void 0?0:C.modulateMode,F;if(!C.modulateColor)console.warn(`Mesh "${A.name}" is missing "modulateColor" in userData.`),F=new X0(1,0,0,1);else F=new X0(...C.modulateColor,1);if(e0.enabled=!1,J==="none"){if(e0.enabled=!0,U===6||U===7){let R=new BA({color:K.color,side:K.side,map:K.map,blending:y2,blendDstAlpha:F8,transparent:K.transparent,alphaTest:0,reflectivity:0});A.material=R}else if(U===9||U===10){let R=new rA({color:K.color,side:K.side,map:K.map,blending:y2,blendDstAlpha:F8,transparent:K.transparent,alphaTest:K.alphaTest,metalness:1,roughness:1});A.material=R}else{let R=new rA({color:K.color,side:K.side,map:K.map,blending:y2,blendDstAlpha:F8,transparent:K.transparent,alphaTest:K.alphaTest,metalness:1,roughness:1,reflectivity:1});A.material=R}return}let V={};if(K.map)V.USE_MAP="",K.map.colorSpace=GA,K.needsUpdate=!0;let D=K.side;if(C.cullMode!==void 0)switch(C.cullMode){case 0:D=VA;break;case 1:D=M2;break;case 2:D=w2;break}let L;if(J==="switch"){let R,M=0;switch(U){case 7:case 6:R=Tp;break;case 8:R=kp;break;case 3:case 0:R=Sp[Q.extFacelineColor];break;case 2:R=jp[Q.extFacelineColor];break;case 9:R=vp[Q.favoriteColor];break;case 10:R=Q.normalMii===!1?Jz[1]:Jz[0];break;case 5:R=xp[Q.favoriteColor];break;case 4:if(Q.hairColor==0)M=8;else M=Q.extHairColor&Qz;R=yp[M];break;case 1:if(Q.facialHairColor==0)M=8;else M=Q.extBeardColor&Qz;R=hp[M];break;default:return}let T={};if(U===5)U=4;else if(U===4)U=5;else if(U===8||U===6||U===7)N=1;else if(U===5)U=0,N=0;T.modulateType={value:N},T.lightEnable={value:!0},T.u_const1={value:F},T.u_SssColor={value:new X0(R.sssColor[0],R.sssColor[1],R.sssColor[2],1)},T.u_SpecularColor={value:new X0(R.specular.color[0],R.specular.color[1],R.specular.color[2],1)},T.u_RimColor={value:new X0(R.rimLight.color[0],R.rimLight.color[1],R.rimLight.color[2],1)},T.u_HalfLambertFactor={value:R.halfLambertFactor},T.u_SssSpecularFactor={value:R.sssSpecularBlendFactor},T.u_SpecularFactorA={value:R.specular.factorA},T.u_SpecularFactorB={value:R.specular.factorB},T.u_SpecularShinness={value:R.specular.shinness},T.u_RimPower={value:R.rimLight.power},T.u_RimWidth={value:R.rimLight.width};let h=new X0(-0.12279,0.70711,0.69636,1).negate(),y=new X0(1,1,1,1);T.gammaType={value:1},T.lightDirInView={value:h},T.lightColor={value:y};var g;((B)=>{B[B.DRAW_TYPE_NORMAL=0]="DRAW_TYPE_NORMAL";B[B.DRAW_TYPE_FACELINE=1]="DRAW_TYPE_FACELINE";B[B.DRAW_TYPE_HAIR=2]="DRAW_TYPE_HAIR"})(g||={});let f=0;switch(U){case 4:f=2;break;default:f=0;break}T.drawType={value:f},T.s_Tex={value:K.map},L=new T0({vertexShader:eR,fragmentShader:Az,uniforms:{...T},defines:V,side:D,blending:y2,blendDstAlpha:F8,transparent:K.transparent,alphaTest:K.alphaTest})}else if(J.startsWith("wiiu")||J==="lightDisabled")console.log("Modulate type:",U),L=new n6({modulateColor:F.toArray(),modulateMode:N,modulateType:U,map:K.map||void 0,side:D,lightEnable:J.startsWith("wiiu")?!0:!1});else if(J==="miitomo")L=new UA({modulateColor:F.toArray(),modulateMode:N,modulateType:U,map:K.map||void 0,side:D});else L=new T0({vertexShader:rR,fragmentShader:tR,uniforms:{u_const1:{value:F},u_light_ambient:{value:bR},u_light_diffuse:{value:fR},u_light_specular:{value:pR},u_light_dir:{value:uR},u_light_enable:{value:Y},u_material_ambient:{value:Z.ambient},u_material_diffuse:{value:Z.diffuse},u_material_specular:{value:Z.specular},u_material_specular_mode:{value:Z.specularMode},u_material_specular_power:{value:Z.specularPower},u_mode:{value:N},u_rim_color:{value:Qp},u_rim_power:{value:Jp},s_texture:{value:K.map}},defines:V,side:D,blending:y2,blendDstAlpha:F8,transparent:K.transparent,alphaTest:K.alphaTest});A.material=L}var g1=j2(bp(),1);var oz1=new t0,iz1=new I1,az1=new I1,rz1=new I1,tz1=new I1,ez1=new I1,AD1=new t0,QD1=new I1,JD1=new I1,KD1=new I1,CD1=new Y0;var BD1={IDLE:Symbol(),ROTATE:Symbol(),PAN:Symbol(),SCALE:Symbol(),FOV:Symbol(),FOCUS:Symbol(),ZROTATE:Symbol(),TOUCH_MULTI:Symbol(),ANIMATION_FOCUS:Symbol(),ANIMATION_ROTATE:Symbol()},XD1={NONE:Symbol(),ONE_FINGER:Symbol(),ONE_FINGER_SWITCHED:Symbol(),TWO_FINGER:Symbol(),MULT_FINGER:Symbol(),CURSOR:Symbol()};var ED1={camera:new Y0,gizmos:new Y0};var $D1=new $9,HD1=new I1,GD1=new Y0,WD1=new Y0,ID1=new I1;var ND1=new V2,LD1=new p1,FD1=new I1,RD1=new p1,zD1=new p1,DD1=new I1,VD1=new I1,MD1=new Y0,wD1=new I1,PD1=new I1;var kD1=new I1,SD1=new zC,jD1=new I1,vD1=new I1;var hD1=new t0;var fD1=new f6,pD1=new V2,uD1=Math.cos(70*K2.DEG2RAD),mD1=new I1,cD1=2*Math.PI;var aD1=new t2(0,0,0,"YXZ"),rD1=new I1;var tD1=Math.PI/2;var QV1=new p1,JV1=new p1,KV1=new I1,CV1=new I1,YV1=new I1,UV1=new t0,ZV1=new I1,BV1=new I1,XV1=new I1,EV1=new I1;var GV1=new $9,WV1=new I1,IV1=new I1,qV1=new t0,OV1={X:new I1(1,0,0),Y:new I1(0,1,0),Z:new I1(0,0,1)};var NV1=new t2,LV1=new I1(0,1,0),FV1=new I1(0,0,0),RV1=new Y0,zV1=new t0,DV1=new t0,VV1=new I1,MV1=new Y0,wV1=new I1(1,0,0),PV1=new I1(0,1,0),_V1=new I1(0,0,1),TV1=new I1,kV1=new I1,SV1=new I1;var Uz=new Y0;class vG{constructor(A){if(A=A||{},this.zNear=A.webGL===!0?-1:0,this.vertices={near:[new I1,new I1,new I1,new I1],far:[new I1,new I1,new I1,new I1]},A.projectionMatrix!==void 0)this.setFromProjectionMatrix(A.projectionMatrix,A.maxFar||1e4)}setFromProjectionMatrix(A,Q){let J=this.zNear,K=A.elements[11]===0;return Uz.copy(A).invert(),this.vertices.near[0].set(1,1,J),this.vertices.near[1].set(1,-1,J),this.vertices.near[2].set(-1,-1,J),this.vertices.near[3].set(-1,1,J),this.vertices.near.forEach(function(C){C.applyMatrix4(Uz)}),this.vertices.far[0].set(1,1,1),this.vertices.far[1].set(1,-1,1),this.vertices.far[2].set(-1,-1,1),this.vertices.far[3].set(-1,1,1),this.vertices.far.forEach(function(C){C.applyMatrix4(Uz);let U=Math.abs(C.z);if(K)C.z*=Math.min(Q/U,1);else C.multiplyScalar(Math.min(Q/U,1))}),this.vertices}split(A,Q){while(A.length>Q.length)Q.push(new vG);Q.length=A.length;for(let J=0;J 0.0 ) { - material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); - // Iridescence F0 approximation - material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); - } -#endif - -IncidentLight directLight; - -#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) - - PointLight pointLight; - #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLightShadow; - #endif - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - - pointLight = pointLights[ i ]; - - getPointLightInfo( pointLight, geometryPosition, directLight ); - - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) - pointLightShadow = pointLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #endif - - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - } - #pragma unroll_loop_end - -#endif - -#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) - - SpotLight spotLight; - vec4 spotColor; - vec3 spotLightCoord; - bool inSpotLightMap; - - #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLightShadow; - #endif - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - - spotLight = spotLights[ i ]; - - getSpotLightInfo( spotLight, geometryPosition, directLight ); - - // spot lights are ordered [shadows with maps, shadows without maps, maps without shadows, none] - #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX - #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS - #else - #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #endif - #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) - spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; - inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); - spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); - directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; - #endif - #undef SPOT_LIGHT_MAP_INDEX - - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - spotLightShadow = spotLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - - #endif - - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - } - #pragma unroll_loop_end - -#endif - -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES ) - - DirectionalLight directionalLight; - float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear); - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - - #if defined( USE_SHADOWMAP ) && defined( CSM_FADE ) - vec2 cascade; - float cascadeCenter; - float closestEdge; - float margin; - float csmx; - float csmy; - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, directLight ); - - #if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - // NOTE: Depth gets larger away from the camera. - // cascade.x is closer, cascade.y is further - cascade = CSM_cascades[ i ]; - cascadeCenter = ( cascade.x + cascade.y ) / 2.0; - closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y; - margin = 0.25 * pow( closestEdge, 2.0 ); - csmx = cascade.x - margin / 2.0; - csmy = cascade.y + margin / 2.0; - if( linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) { - - float dist = min( linearDepth - csmx, csmy - linearDepth ); - float ratio = clamp( dist / margin, 0.0, 1.0 ); - - vec3 prevColor = directLight.color; - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - - bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter; - directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 ); - - ReflectedLight prevLight = reflectedLight; - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter; - float blendRatio = shouldBlend ? ratio : 1.0; - - reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio ); - reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio ); - reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio ); - reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio ); - - } - #endif - - } - #pragma unroll_loop_end - #elif defined (USE_SHADOWMAP) - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, directLight ); - - #if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - - directionalLightShadow = directionalLightShadows[ i ]; - if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - - if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - #endif - - } - #pragma unroll_loop_end - - #elif ( NUM_DIR_LIGHT_SHADOWS > 0 ) - // note: no loop here - all CSM lights are in fact one light only - getDirectionalLightInfo( directionalLights[0], directLight ); - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - #endif - - #if ( NUM_DIR_LIGHTS > NUM_DIR_LIGHT_SHADOWS) - // compute the lights not casting shadows (if any) - - #pragma unroll_loop_start - for ( int i = NUM_DIR_LIGHT_SHADOWS; i < NUM_DIR_LIGHTS; i ++ ) { - - directionalLight = directionalLights[ i ]; - - getDirectionalLightInfo( directionalLight, directLight ); - - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - } - #pragma unroll_loop_end - - #endif - -#endif - - -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !defined( USE_CSM ) && !defined( CSM_CASCADES ) - - DirectionalLight directionalLight; - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - directionalLight = directionalLights[ i ]; - - getDirectionalLightInfo( directionalLight, directLight ); - - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif - - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - } - #pragma unroll_loop_end - -#endif - -#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) - - RectAreaLight rectAreaLight; - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { - - rectAreaLight = rectAreaLights[ i ]; - RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - } - #pragma unroll_loop_end - -#endif - -#if defined( RE_IndirectDiffuse ) - - vec3 iblIrradiance = vec3( 0.0 ); - - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); - - #if defined( USE_LIGHT_PROBES ) - - irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); - - #endif - - #if ( NUM_HEMI_LIGHTS > 0 ) - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); - - } - #pragma unroll_loop_end - - #endif - -#endif - -#if defined( RE_IndirectSpecular ) - - vec3 radiance = vec3( 0.0 ); - vec3 clearcoatRadiance = vec3( 0.0 ); - -#endif -`,lights_pars_begin:` -#if defined( USE_CSM ) && defined( CSM_CASCADES ) -uniform vec2 CSM_cascades[CSM_CASCADES]; -uniform float cameraNear; -uniform float shadowFar; -#endif - `+$A.lights_pars_begin};var pV1=new Y0,uV1=new vG({webGL:!0}),mV1=new I1,cV1=new DA;var dV1=new Y0,lV1=new Y0,nV1=new I1(0,1,0);class B2{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}var KC1=new o8(-1,1,1,-1,0,1);class fp extends V0{constructor(){super();this.setAttribute("position",new L0([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new L0([0,2,0,0,2,0],2))}}var CC1=new fp;class $2{constructor(A){this._mesh=new _0(CC1,A)}dispose(){this._mesh.geometry.dispose()}render(A){A.render(this._mesh,KC1)}get material(){return this._mesh.material}set material(A){this._mesh.material=A}}class m9{parse(A,Q={}){if(Q=Object.assign({decodeSpeed:5,encodeSpeed:5,encoderMethod:m9.MESH_EDGEBREAKER_ENCODING,quantization:[16,8,8,8,8],exportUvs:!0,exportNormals:!0,exportColor:!1},Q),DracoEncoderModule===void 0)throw new Error("THREE.DRACOExporter: required the draco_encoder to work.");let J=A.geometry,K=DracoEncoderModule(),C=new K.Encoder,U,Y;if(A.isMesh===!0){U=new K.MeshBuilder,Y=new K.Mesh;let I=J.getAttribute("position");U.AddFloatAttributeToMesh(Y,K.POSITION,I.count,I.itemSize,I.array);let N=J.getIndex();if(N!==null)U.AddFacesToMesh(Y,N.count/3,N.array);else{let F=new(I.count>65535?Uint32Array:Uint16Array)(I.count);for(let V=0;V -Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE -version 0.8.2 -*/var vC=Uint8Array,up=Uint16Array,YC1=Int32Array,UC1=new vC([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,0,0,0]),ZC1=new vC([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,0,0]),TM1=new vC([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),mp=function(A,Q){var J=new up(31);for(var K=0;K<31;++K)J[K]=Q+=1<>1|(H2&21845)<<1,Z7=(Z7&52428)>>2|(Z7&13107)<<2,Z7=(Z7&61680)>>4|(Z7&3855)<<4,EC1[H2]=((Z7&65280)>>8|(Z7&255)<<8)>>1;var Z7,H2;var yG=new vC(288);for(H2=0;H2<144;++H2)yG[H2]=8;var H2;for(H2=144;H2<256;++H2)yG[H2]=9;var H2;for(H2=256;H2<280;++H2)yG[H2]=7;var H2;for(H2=280;H2<288;++H2)yG[H2]=8;var H2,$C1=new vC(32);for(H2=0;H2<32;++H2)$C1[H2]=5;var H2;var HC1=/*@__PURE__*/new vC(0);var GC1=typeof TextDecoder!="undefined"&&/*@__PURE__*/new TextDecoder,WC1=0;try{GC1.decode(HC1,{stream:!0}),WC1=1}catch(A){}var lp={POSITION:["byte","byte normalized","unsigned byte","unsigned byte normalized","short","short normalized","unsigned short","unsigned short normalized"],NORMAL:["byte normalized","short normalized"],TANGENT:["byte normalized","short normalized"],TEXCOORD:["byte","byte normalized","unsigned byte","short","short normalized","unsigned short"]};class R4{constructor(){this.textureUtils=null,this.pluginCallbacks=[],this.register(function(A){return new ep(A)}),this.register(function(A){return new Au(A)}),this.register(function(A){return new Cu(A)}),this.register(function(A){return new Yu(A)}),this.register(function(A){return new Uu(A)}),this.register(function(A){return new Zu(A)}),this.register(function(A){return new Qu(A)}),this.register(function(A){return new Ju(A)}),this.register(function(A){return new Ku(A)}),this.register(function(A){return new Bu(A)}),this.register(function(A){return new Xu(A)}),this.register(function(A){return new Eu(A)}),this.register(function(A){return new $u(A)}),this.register(function(A){return new Hu(A)})}register(A){if(this.pluginCallbacks.indexOf(A)===-1)this.pluginCallbacks.push(A);return this}unregister(A){if(this.pluginCallbacks.indexOf(A)!==-1)this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(A),1);return this}setTextureUtils(A){return this.textureUtils=A,this}parse(A,Q,J,K){let C=new tp,U=[];for(let Y=0,Z=this.pluginCallbacks.length;Y4)Y=A.array[C*A.itemSize+U];else{if(U===0)Y=A.getX(C);else if(U===1)Y=A.getY(C);else if(U===2)Y=A.getZ(C);else if(U===3)Y=A.getW(C);if(A.normalized===!0)Y=K2.normalize(Y,A.array)}K.min[U]=Math.min(K.min[U],Y),K.max[U]=Math.max(K.max[U],Y)}return K}function rp(A){return Math.ceil(A/4)*4}function Bz(A,Q=0){let J=rp(A.byteLength);if(J!==A.byteLength){let K=new Uint8Array(J);if(K.set(new Uint8Array(A)),Q!==0)for(let C=A.byteLength;CA.toBlob(K,Q));let J;if(Q==="image/jpeg")J=0.92;else if(Q==="image/webp")J=0.8;return A.convertToBlob({type:Q,quality:J})}class tp{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=/*@__PURE__*/new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=/*@__PURE__*/new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter r"+G5}},this.cache={meshes:/*@__PURE__*/new Map,attributes:/*@__PURE__*/new Map,attributesNormalized:/*@__PURE__*/new Map,materials:/*@__PURE__*/new Map,textures:/*@__PURE__*/new Map,images:/*@__PURE__*/new Map},this.textureUtils=null}setPlugins(A){this.plugins=A}setTextureUtils(A){this.textureUtils=A}async writeAsync(A,Q,J={}){if(this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1},J),this.options.animations.length>0)this.options.trs=!0;await this.processInputAsync(A),await Promise.all(this.pending);let K=this,C=K.buffers,U=K.json;J=K.options;let{extensionsUsed:Y,extensionsRequired:Z}=K,X=new Blob(C,{type:"application/octet-stream"}),E=Object.keys(Y),H=Object.keys(Z);if(E.length>0)U.extensionsUsed=E;if(H.length>0)U.extensionsRequired=H;if(U.buffers&&U.buffers.length>0)U.buffers[0].byteLength=X.size;if(J.binary===!0){let $=new FileReader;$.readAsArrayBuffer(X),$.onloadend=function(){let I=Bz($.result),N=new DataView(new ArrayBuffer(op));N.setUint32(0,I.byteLength,!0),N.setUint32(4,LC1,!0);let F=Bz(FC1(JSON.stringify(U)),32),V=new DataView(new ArrayBuffer(op));V.setUint32(0,F.byteLength,!0),V.setUint32(4,NC1,!0);let D=new ArrayBuffer(sp),L=new DataView(D);L.setUint32(0,qC1,!0),L.setUint32(4,OC1,!0);let R=sp+V.byteLength+F.byteLength+N.byteLength+I.byteLength;L.setUint32(8,R,!0);let M=new Blob([D,V,F,N,I],{type:"application/octet-stream"}),T=new FileReader;T.readAsArrayBuffer(M),T.onloadend=function(){Q(T.result)}}}else if(U.buffers&&U.buffers.length>0){let $=new FileReader;$.readAsDataURL(X),$.onloadend=function(){let I=$.result;U.buffers[0].uri=I,Q(U)}}else Q(U)}serializeUserData(A,Q){if(Object.keys(A.userData).length===0)return;let J=this.options,K=this.extensionsUsed;try{let C=JSON.parse(JSON.stringify(A.userData));if(J.includeCustomExtensions&&C.gltfExtensions){if(Q.extensions===void 0)Q.extensions={};for(let U in C.gltfExtensions)Q.extensions[U]=C.gltfExtensions[U],K[U]=!0;delete C.gltfExtensions}if(Object.keys(C).length>0)Q.extras=C}catch(C){console.warn("THREE.GLTFExporter: userData of '"+A.name+"' won't be serialized because of JSON.stringify error - "+C.message)}}getUID(A,Q=!1){if(this.uids.has(A)===!1){let K=/*@__PURE__*/new Map;K.set(!0,this.uid++),K.set(!1,this.uid++),this.uids.set(A,K)}return this.uids.get(A).get(Q)}isNormalizedNormalAttribute(A){if(this.cache.attributesNormalized.has(A))return!1;let J=new I1;for(let K=0,C=A.count;K0.0005)return!1;return!0}createNormalizedNormalAttribute(A){let Q=this.cache;if(Q.attributesNormalized.has(A))return Q.attributesNormalized.get(A);let J=A.clone(),K=new I1;for(let C=0,U=J.count;C4)V=A.array[N*A.itemSize+F];else{if(F===0)V=A.getX(N);else if(F===1)V=A.getY(N);else if(F===2)V=A.getZ(N);else if(F===3)V=A.getW(N);if(A.normalized===!0)V=K2.normalize(V,A.array)}if(Q===sA.FLOAT)E.setFloat32(H,V,!0);else if(Q===sA.INT)E.setInt32(H,V,!0);else if(Q===sA.UNSIGNED_INT)E.setUint32(H,V,!0);else if(Q===sA.SHORT)E.setInt16(H,V,!0);else if(Q===sA.UNSIGNED_SHORT)E.setUint16(H,V,!0);else if(Q===sA.BYTE)E.setInt8(H,V);else if(Q===sA.UNSIGNED_BYTE)E.setUint8(H,V);H+=Y}if(H%Z!==0)H+=Z-H%Z}let $={buffer:this.processBuffer(E.buffer),byteOffset:this.byteOffset,byteLength:X};if(C!==void 0)$.target=C;if(C===sA.ARRAY_BUFFER)$.byteStride=Z;return this.byteOffset+=X,U.bufferViews.push($),{id:U.bufferViews.length-1,byteLength:0}}processBufferViewImage(A){let Q=this,J=Q.json;if(!J.bufferViews)J.bufferViews=[];return new Promise(function(K){let C=new FileReader;C.readAsArrayBuffer(A),C.onloadend=function(){let U=Bz(C.result),Y={buffer:Q.processBuffer(U),byteOffset:Q.byteOffset,byteLength:U.byteLength};Q.byteOffset+=U.byteLength,K(J.bufferViews.push(Y)-1)}})}processAccessor(A,Q,J,K){let C=this.json,U={1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"},Y;if(A.array.constructor===Float32Array)Y=sA.FLOAT;else if(A.array.constructor===Int32Array)Y=sA.INT;else if(A.array.constructor===Uint32Array)Y=sA.UNSIGNED_INT;else if(A.array.constructor===Int16Array)Y=sA.SHORT;else if(A.array.constructor===Uint16Array)Y=sA.UNSIGNED_SHORT;else if(A.array.constructor===Int8Array)Y=sA.BYTE;else if(A.array.constructor===Uint8Array)Y=sA.UNSIGNED_BYTE;else throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+A.array.constructor.name);if(J===void 0)J=0;if(K===void 0||K===1/0)K=A.count;if(K===0)return null;let Z=zC1(A,J,K),X;if(Q!==void 0)X=A===Q.index?sA.ELEMENT_ARRAY_BUFFER:sA.ARRAY_BUFFER;let E=this.processBufferView(A,Y,J,K,X),H={bufferView:E.id,byteOffset:E.byteOffset,componentType:Y,count:K,max:Z.max,min:Z.min,type:U[A.itemSize]};if(A.normalized===!0)H.normalized=!0;if(!C.accessors)C.accessors=[];return C.accessors.push(H)-1}processImage(A,Q,J,K="image/png"){if(A!==null){let C=this,U=C.cache,Y=C.json,Z=C.options,X=C.pending;if(!U.images.has(A))U.images.set(A,{});let E=U.images.get(A),H=K+":flipY/"+J.toString();if(E[H]!==void 0)return E[H];if(!Y.images)Y.images=[];let $={mimeType:K},I=ip();I.width=Math.min(A.width,Z.maxTextureSize),I.height=Math.min(A.height,Z.maxTextureSize);let N=I.getContext("2d",{willReadFrequently:!0});if(J===!0)N.translate(0,I.height),N.scale(1,-1);if(A.data!==void 0){if(Q!==xA)console.error("GLTFExporter: Only RGBAFormat is supported.",Q);if(A.width>Z.maxTextureSize||A.height>Z.maxTextureSize)console.warn("GLTFExporter: Image size is bigger than maxTextureSize",A);let V=new Uint8ClampedArray(A.height*A.width*4);for(let D=0;DC.processBufferViewImage(V)).then((V)=>{$.bufferView=V}));else if(I.toDataURL!==void 0)$.uri=I.toDataURL(K);else X.push(ap(I,K).then((V)=>new FileReader().readAsDataURL(V)).then((V)=>{$.uri=V}));let F=Y.images.push($)-1;return E[H]=F,F}else throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(A){let Q=this.json;if(!Q.samplers)Q.samplers=[];let J={magFilter:H9[A.magFilter],minFilter:H9[A.minFilter],wrapS:H9[A.wrapS],wrapT:H9[A.wrapT]};return Q.samplers.push(J)-1}async processTextureAsync(A){let J=this.options,K=this.cache,C=this.json;if(K.textures.has(A))return K.textures.get(A);if(!C.textures)C.textures=[];if(A instanceof Z9)A=await this.decompressTextureAsync(A,J.maxTextureSize);let U=A.userData.mimeType;if(U==="image/webp")U="image/png";let Y={sampler:this.processSampler(A),source:this.processImage(A.image,A.format,A.flipY,U)};if(A.name)Y.name=A.name;await this._invokeAllAsync(async function(X){X.writeTexture&&await X.writeTexture(A,Y)});let Z=C.textures.push(Y)-1;return K.textures.set(A,Z),Z}async processMaterialAsync(A){let Q=this.cache,J=this.json;if(Q.materials.has(A))return Q.materials.get(A);if(A.isShaderMaterial)return console.warn("GLTFExporter: THREE.ShaderMaterial not supported."),null;if(!J.materials)J.materials=[];let K={pbrMetallicRoughness:{}};if(A.isMeshStandardMaterial!==!0&&A.isMeshBasicMaterial!==!0)console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");let C=A.color.toArray().concat([A.opacity]);if(!oZ(C,[1,1,1,1]))K.pbrMetallicRoughness.baseColorFactor=C;if(A.isMeshStandardMaterial)K.pbrMetallicRoughness.metallicFactor=A.metalness,K.pbrMetallicRoughness.roughnessFactor=A.roughness;else K.pbrMetallicRoughness.metallicFactor=0,K.pbrMetallicRoughness.roughnessFactor=1;if(A.metalnessMap||A.roughnessMap){let Y=await this.buildMetalRoughTextureAsync(A.metalnessMap,A.roughnessMap),Z={index:await this.processTextureAsync(Y),texCoord:Y.channel};this.applyTextureTransform(Z,Y),K.pbrMetallicRoughness.metallicRoughnessTexture=Z}if(A.map){let Y={index:await this.processTextureAsync(A.map),texCoord:A.map.channel};this.applyTextureTransform(Y,A.map),K.pbrMetallicRoughness.baseColorTexture=Y}if(A.emissive){let Y=A.emissive;if(Math.max(Y.r,Y.g,Y.b)>0)K.emissiveFactor=A.emissive.toArray();if(A.emissiveMap){let X={index:await this.processTextureAsync(A.emissiveMap),texCoord:A.emissiveMap.channel};this.applyTextureTransform(X,A.emissiveMap),K.emissiveTexture=X}}if(A.normalMap){let Y={index:await this.processTextureAsync(A.normalMap),texCoord:A.normalMap.channel};if(A.normalScale&&A.normalScale.x!==1)Y.scale=A.normalScale.x;this.applyTextureTransform(Y,A.normalMap),K.normalTexture=Y}if(A.aoMap){let Y={index:await this.processTextureAsync(A.aoMap),texCoord:A.aoMap.channel};if(A.aoMapIntensity!==1)Y.strength=A.aoMapIntensity;this.applyTextureTransform(Y,A.aoMap),K.occlusionTexture=Y}if(A.transparent)K.alphaMode="BLEND";else if(A.alphaTest>0)K.alphaMode="MASK",K.alphaCutoff=A.alphaTest;if(A.side===VA)K.doubleSided=!0;if(A.name!=="")K.name=A.name;this.serializeUserData(A,K),await this._invokeAllAsync(async function(Y){Y.writeMaterialAsync&&await Y.writeMaterialAsync(A,K)});let U=J.materials.push(K)-1;return Q.materials.set(A,U),U}async processMeshAsync(A){let Q=this.cache,J=this.json,K=[A.geometry.uuid];if(Array.isArray(A.material))for(let M=0,T=A.material.length;M0){let M=[],T=[],h={};if(A.morphTargetDictionary!==void 0)for(let y in A.morphTargetDictionary)h[A.morphTargetDictionary[y]]=y;for(let y=0;y0)Z.extras={},Z.extras.targetNames=T}let F=Array.isArray(A.material);if(F&&U.groups.length===0)return null;let V=!1;if(F&&U.index===null){let M=[];for(let T=0,h=U.attributes.position.count;T0)h.targets=H;if(U.index!==null){let g=this.getUID(U.index);if(L[M].start!==void 0||L[M].count!==void 0)g+=":"+L[M].start+":"+L[M].count;if(Q.attributes.has(g))h.indices=Q.attributes.get(g);else h.indices=this.processAccessor(U.index,U,L[M].start,L[M].count),Q.attributes.set(g,h.indices);if(h.indices===null)delete h.indices}let y=await this.processMaterialAsync(D[L[M].materialIndex]);if(y!==null)h.material=y;E.push(h)}if(V===!0)U.setIndex(null);if(Z.primitives=E,!J.meshes)J.meshes=[];await this._invokeAllAsync(function(M){M.writeMesh&&M.writeMesh(A,Z)});let R=J.meshes.push(Z)-1;return Q.meshes.set(C,R),R}detectMeshQuantization(A,Q){if(this.extensionsUsed[Zz])return;let J=void 0;switch(Q.array.constructor){case Int8Array:J="byte";break;case Uint8Array:J="unsigned byte";break;case Int16Array:J="short";break;case Uint16Array:J="unsigned short";break;default:return}if(Q.normalized)J+=" normalized";let K=A.split("_",1)[0];if(lp[K]&&lp[K].includes(J))this.extensionsUsed[Zz]=!0,this.extensionsRequired[Zz]=!0}processCamera(A){let Q=this.json;if(!Q.cameras)Q.cameras=[];let J=A.isOrthographicCamera,K={type:J?"orthographic":"perspective"};if(J)K.orthographic={xmag:A.right*2,ymag:A.top*2,zfar:A.far<=0?0.001:A.far,znear:A.near<0?0:A.near};else K.perspective={aspectRatio:A.aspect,yfov:K2.degToRad(A.fov),zfar:A.far<=0?0.001:A.far,znear:A.near<0?0:A.near};if(A.name!=="")K.name=A.type;return Q.cameras.push(K)-1}processAnimation(A,Q){let J=this.json,K=this.nodeMap;if(!J.animations)J.animations=[];A=R4.Utils.mergeMorphTargetTracks(A.clone(),Q);let C=A.tracks,U=[],Y=[];for(let Z=0;Z0){let Y=[];for(let Z=0,X=A.children.length;Z0)C.children=Y}await this._invokeAllAsync(function(Y){Y.writeNode&&Y.writeNode(A,C)});let U=Q.nodes.push(C)-1;return K.set(A,U),U}async processSceneAsync(A){let Q=this.json,J=this.options;if(!Q.scenes)Q.scenes=[],Q.scene=0;let K={};if(A.name!=="")K.name=A.name;Q.scenes.push(K);let C=[];for(let U=0,Y=A.children.length;U0)K.nodes=C;this.serializeUserData(A,K)}async processObjectsAsync(A){let Q=new Q8;Q.name="AuxScene";for(let J=0;J0)await this.processObjectsAsync(J);for(let K=0;K0)U.range=A.distance}else if(A.isSpotLight){if(U.type="spot",A.distance>0)U.range=A.distance;U.spot={},U.spot.innerConeAngle=(1-A.penumbra)*A.angle,U.spot.outerConeAngle=A.angle}if(A.decay!==void 0&&A.decay!==2)console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2.");if(A.target&&(A.target.parent!==A||A.target.position.x!==0||A.target.position.y!==0||A.target.position.z!==-1))console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, make light.target a child of the light with position 0,0,-1.");if(!C[this.name])K.extensions=K.extensions||{},K.extensions[this.name]={lights:[]},C[this.name]=!0;let Y=K.extensions[this.name].lights;Y.push(U),Q.extensions=Q.extensions||{},Q.extensions[this.name]={light:Y.length-1}}}class Au{constructor(A){this.writer=A,this.name="KHR_materials_unlit"}async writeMaterialAsync(A,Q){if(!A.isMeshBasicMaterial)return;let K=this.writer.extensionsUsed;Q.extensions=Q.extensions||{},Q.extensions[this.name]={},K[this.name]=!0,Q.pbrMetallicRoughness.metallicFactor=0,Q.pbrMetallicRoughness.roughnessFactor=0.9}}class Qu{constructor(A){this.writer=A,this.name="KHR_materials_clearcoat"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.clearcoat===0)return;let J=this.writer,K=J.extensionsUsed,C={};if(C.clearcoatFactor=A.clearcoat,A.clearcoatMap){let U={index:await J.processTextureAsync(A.clearcoatMap),texCoord:A.clearcoatMap.channel};J.applyTextureTransform(U,A.clearcoatMap),C.clearcoatTexture=U}if(C.clearcoatRoughnessFactor=A.clearcoatRoughness,A.clearcoatRoughnessMap){let U={index:await J.processTextureAsync(A.clearcoatRoughnessMap),texCoord:A.clearcoatRoughnessMap.channel};J.applyTextureTransform(U,A.clearcoatRoughnessMap),C.clearcoatRoughnessTexture=U}if(A.clearcoatNormalMap){let U={index:await J.processTextureAsync(A.clearcoatNormalMap),texCoord:A.clearcoatNormalMap.channel};if(A.clearcoatNormalScale.x!==1)U.scale=A.clearcoatNormalScale.x;J.applyTextureTransform(U,A.clearcoatNormalMap),C.clearcoatNormalTexture=U}Q.extensions=Q.extensions||{},Q.extensions[this.name]=C,K[this.name]=!0}}class Ju{constructor(A){this.writer=A,this.name="KHR_materials_dispersion"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.dispersion===0)return;let K=this.writer.extensionsUsed,C={};C.dispersion=A.dispersion,Q.extensions=Q.extensions||{},Q.extensions[this.name]=C,K[this.name]=!0}}class Ku{constructor(A){this.writer=A,this.name="KHR_materials_iridescence"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.iridescence===0)return;let J=this.writer,K=J.extensionsUsed,C={};if(C.iridescenceFactor=A.iridescence,A.iridescenceMap){let U={index:await J.processTextureAsync(A.iridescenceMap),texCoord:A.iridescenceMap.channel};J.applyTextureTransform(U,A.iridescenceMap),C.iridescenceTexture=U}if(C.iridescenceIor=A.iridescenceIOR,C.iridescenceThicknessMinimum=A.iridescenceThicknessRange[0],C.iridescenceThicknessMaximum=A.iridescenceThicknessRange[1],A.iridescenceThicknessMap){let U={index:await J.processTextureAsync(A.iridescenceThicknessMap),texCoord:A.iridescenceThicknessMap.channel};J.applyTextureTransform(U,A.iridescenceThicknessMap),C.iridescenceThicknessTexture=U}Q.extensions=Q.extensions||{},Q.extensions[this.name]=C,K[this.name]=!0}}class Cu{constructor(A){this.writer=A,this.name="KHR_materials_transmission"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.transmission===0)return;let J=this.writer,K=J.extensionsUsed,C={};if(C.transmissionFactor=A.transmission,A.transmissionMap){let U={index:await J.processTextureAsync(A.transmissionMap),texCoord:A.transmissionMap.channel};J.applyTextureTransform(U,A.transmissionMap),C.transmissionTexture=U}Q.extensions=Q.extensions||{},Q.extensions[this.name]=C,K[this.name]=!0}}class Yu{constructor(A){this.writer=A,this.name="KHR_materials_volume"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.transmission===0)return;let J=this.writer,K=J.extensionsUsed,C={};if(C.thicknessFactor=A.thickness,A.thicknessMap){let U={index:await J.processTextureAsync(A.thicknessMap),texCoord:A.thicknessMap.channel};J.applyTextureTransform(U,A.thicknessMap),C.thicknessTexture=U}if(A.attenuationDistance!==1/0)C.attenuationDistance=A.attenuationDistance;C.attenuationColor=A.attenuationColor.toArray(),Q.extensions=Q.extensions||{},Q.extensions[this.name]=C,K[this.name]=!0}}class Uu{constructor(A){this.writer=A,this.name="KHR_materials_ior"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.ior===1.5)return;let K=this.writer.extensionsUsed,C={};C.ior=A.ior,Q.extensions=Q.extensions||{},Q.extensions[this.name]=C,K[this.name]=!0}}class Zu{constructor(A){this.writer=A,this.name="KHR_materials_specular"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.specularIntensity===1&&A.specularColor.equals(IC1)&&!A.specularIntensityMap&&!A.specularColorMap)return;let J=this.writer,K=J.extensionsUsed,C={};if(A.specularIntensityMap){let U={index:await J.processTextureAsync(A.specularIntensityMap),texCoord:A.specularIntensityMap.channel};J.applyTextureTransform(U,A.specularIntensityMap),C.specularTexture=U}if(A.specularColorMap){let U={index:await J.processTextureAsync(A.specularColorMap),texCoord:A.specularColorMap.channel};J.applyTextureTransform(U,A.specularColorMap),C.specularColorTexture=U}C.specularFactor=A.specularIntensity,C.specularColorFactor=A.specularColor.toArray(),Q.extensions=Q.extensions||{},Q.extensions[this.name]=C,K[this.name]=!0}}class Bu{constructor(A){this.writer=A,this.name="KHR_materials_sheen"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.sheen==0)return;let J=this.writer,K=J.extensionsUsed,C={};if(A.sheenRoughnessMap){let U={index:await J.processTextureAsync(A.sheenRoughnessMap),texCoord:A.sheenRoughnessMap.channel};J.applyTextureTransform(U,A.sheenRoughnessMap),C.sheenRoughnessTexture=U}if(A.sheenColorMap){let U={index:await J.processTextureAsync(A.sheenColorMap),texCoord:A.sheenColorMap.channel};J.applyTextureTransform(U,A.sheenColorMap),C.sheenColorTexture=U}C.sheenRoughnessFactor=A.sheenRoughness,C.sheenColorFactor=A.sheenColor.toArray(),Q.extensions=Q.extensions||{},Q.extensions[this.name]=C,K[this.name]=!0}}class Xu{constructor(A){this.writer=A,this.name="KHR_materials_anisotropy"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.anisotropy==0)return;let J=this.writer,K=J.extensionsUsed,C={};if(A.anisotropyMap){let U={index:await J.processTextureAsync(A.anisotropyMap)};J.applyTextureTransform(U,A.anisotropyMap),C.anisotropyTexture=U}C.anisotropyStrength=A.anisotropy,C.anisotropyRotation=A.anisotropyRotation,Q.extensions=Q.extensions||{},Q.extensions[this.name]=C,K[this.name]=!0}}class Eu{constructor(A){this.writer=A,this.name="KHR_materials_emissive_strength"}async writeMaterialAsync(A,Q){if(!A.isMeshStandardMaterial||A.emissiveIntensity===1)return;let K=this.writer.extensionsUsed,C={};C.emissiveStrength=A.emissiveIntensity,Q.extensions=Q.extensions||{},Q.extensions[this.name]=C,K[this.name]=!0}}class $u{constructor(A){this.writer=A,this.name="EXT_materials_bump"}async writeMaterialAsync(A,Q){if(!A.isMeshStandardMaterial||A.bumpScale===1&&!A.bumpMap)return;let J=this.writer,K=J.extensionsUsed,C={};if(A.bumpMap){let U={index:await J.processTextureAsync(A.bumpMap),texCoord:A.bumpMap.channel};J.applyTextureTransform(U,A.bumpMap),C.bumpTexture=U}C.bumpFactor=A.bumpScale,Q.extensions=Q.extensions||{},Q.extensions[this.name]=C,K[this.name]=!0}}class Hu{constructor(A){this.writer=A,this.name="EXT_mesh_gpu_instancing"}writeNode(A,Q){if(!A.isInstancedMesh)return;let J=this.writer,K=A,C=new Float32Array(K.count*3),U=new Float32Array(K.count*4),Y=new Float32Array(K.count*3),Z=new Y0,X=new I1,E=new t0,H=new I1;for(let I=0;IA.times[A.times.length-1]){if(Math.abs(A.times[A.times.length-1]-Q)<0.001)return A.times.length-1;C[C.length-1]=Q,C.set(A.times,0),U.set(A.values,0),U.set(Y.evaluate(Q),A.values.length),Z=C.length-1}else for(let X=0;XQ){C.set(A.times.slice(0,X+1),0),C[X+1]=Q,C.set(A.times.slice(X+1),X+2),U.set(A.values.slice(0,(X+1)*K),0),U.set(Y.evaluate(Q),(X+1)*K),U.set(A.values.slice((X+1)*K),(X+2)*K),Z=X+1;break}}return A.times=C,A.values=U,Z},mergeMorphTargetTracks:function(A,Q){let J=[],K={},C=A.tracks;for(let U=0;UU.set(K,C,Math.cos(K)*Math.sin(C)),Q=8,J=8){super();this.type="ParametricGeometry",this.parameters={func:A,slices:Q,stacks:J};let K=[],C=[],U=[],Y=[],Z=0.00001,X=new I1,E=new I1,H=new I1,$=new I1,I=new I1,N=Q+1;for(let F=0;F<=J;F++){let V=F/J;for(let D=0;D<=Q;D++){let L=D/Q;if(A(L,V,E),C.push(E.x,E.y,E.z),L-Z>=0)A(L-Z,V,H),$.subVectors(E,H);else A(L+Z,V,H),$.subVectors(H,E);if(V-Z>=0)A(L,V-Z,H),I.subVectors(E,H);else A(L,V+Z,H),I.subVectors(H,E);X.crossVectors($,I).normalize(),U.push(X.x,X.y,X.z),Y.push(L,V)}}for(let F=0;F - #include - #include - #include - #include - - uniform float linewidth; - uniform vec2 resolution; - - attribute vec3 instanceStart; - attribute vec3 instanceEnd; - - attribute vec3 instanceColorStart; - attribute vec3 instanceColorEnd; - - #ifdef WORLD_UNITS - - varying vec4 worldPos; - varying vec3 worldStart; - varying vec3 worldEnd; - - #ifdef USE_DASH - - varying vec2 vUv; - - #endif - - #else - - varying vec2 vUv; - - #endif - - #ifdef USE_DASH - - uniform float dashScale; - attribute float instanceDistanceStart; - attribute float instanceDistanceEnd; - varying float vLineDistance; - - #endif - - void trimSegment( const in vec4 start, inout vec4 end ) { - - // trim end segment so it terminates between the camera plane and the near plane - - // conservative estimate of the near plane - float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column - float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column - float nearEstimate = - 0.5 * b / a; - - float alpha = ( nearEstimate - start.z ) / ( end.z - start.z ); - - end.xyz = mix( start.xyz, end.xyz, alpha ); - - } - - void main() { - - #ifdef USE_COLOR - - vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd; - - #endif - - #ifdef USE_DASH - - vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd; - vUv = uv; - - #endif - - float aspect = resolution.x / resolution.y; - - // camera space - vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 ); - vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 ); - - #ifdef WORLD_UNITS - - worldStart = start.xyz; - worldEnd = end.xyz; - - #else - - vUv = uv; - - #endif - - // special case for perspective projection, and segments that terminate either in, or behind, the camera plane - // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space - // but we need to perform ndc-space calculations in the shader, so we must address this issue directly - // perhaps there is a more elegant solution -- WestLangley - - bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column - - if ( perspective ) { - - if ( start.z < 0.0 && end.z >= 0.0 ) { - - trimSegment( start, end ); - - } else if ( end.z < 0.0 && start.z >= 0.0 ) { - - trimSegment( end, start ); - - } - - } - - // clip space - vec4 clipStart = projectionMatrix * start; - vec4 clipEnd = projectionMatrix * end; - - // ndc space - vec3 ndcStart = clipStart.xyz / clipStart.w; - vec3 ndcEnd = clipEnd.xyz / clipEnd.w; - - // direction - vec2 dir = ndcEnd.xy - ndcStart.xy; - - // account for clip-space aspect ratio - dir.x *= aspect; - dir = normalize( dir ); - - #ifdef WORLD_UNITS - - vec3 worldDir = normalize( end.xyz - start.xyz ); - vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) ); - vec3 worldUp = normalize( cross( worldDir, tmpFwd ) ); - vec3 worldFwd = cross( worldDir, worldUp ); - worldPos = position.y < 0.5 ? start: end; - - // height offset - float hw = linewidth * 0.5; - worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp; - - // don't extend the line if we're rendering dashes because we - // won't be rendering the endcaps - #ifndef USE_DASH - - // cap extension - worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir; - - // add width to the box - worldPos.xyz += worldFwd * hw; - - // endcaps - if ( position.y > 1.0 || position.y < 0.0 ) { - - worldPos.xyz -= worldFwd * 2.0 * hw; - - } - - #endif - - // project the worldpos - vec4 clip = projectionMatrix * worldPos; - - // shift the depth of the projected points so the line - // segments overlap neatly - vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd; - clip.z = clipPose.z * clip.w; - - #else - - vec2 offset = vec2( dir.y, - dir.x ); - // undo aspect ratio adjustment - dir.x /= aspect; - offset.x /= aspect; - - // sign flip - if ( position.x < 0.0 ) offset *= - 1.0; - - // endcaps - if ( position.y < 0.0 ) { - - offset += - dir; - - } else if ( position.y > 1.0 ) { - - offset += dir; - - } - - // adjust for linewidth - offset *= linewidth; - - // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ... - offset /= resolution.y; - - // select end - vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd; - - // back to clip space - offset *= clip.w; - - clip.xy += offset; - - #endif - - gl_Position = clip; - - vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation - - #include - #include - #include - - } - `,fragmentShader:` - uniform vec3 diffuse; - uniform float opacity; - uniform float linewidth; - - #ifdef USE_DASH - - uniform float dashOffset; - uniform float dashSize; - uniform float gapSize; - - #endif - - varying float vLineDistance; - - #ifdef WORLD_UNITS - - varying vec4 worldPos; - varying vec3 worldStart; - varying vec3 worldEnd; - - #ifdef USE_DASH - - varying vec2 vUv; - - #endif - - #else - - varying vec2 vUv; - - #endif - - #include - #include - #include - #include - #include - - vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) { - - float mua; - float mub; - - vec3 p13 = p1 - p3; - vec3 p43 = p4 - p3; - - vec3 p21 = p2 - p1; - - float d1343 = dot( p13, p43 ); - float d4321 = dot( p43, p21 ); - float d1321 = dot( p13, p21 ); - float d4343 = dot( p43, p43 ); - float d2121 = dot( p21, p21 ); - - float denom = d2121 * d4343 - d4321 * d4321; - - float numer = d1343 * d4321 - d1321 * d4343; - - mua = numer / denom; - mua = clamp( mua, 0.0, 1.0 ); - mub = ( d1343 + d4321 * ( mua ) ) / d4343; - mub = clamp( mub, 0.0, 1.0 ); - - return vec2( mua, mub ); - - } - - void main() { - - #include - - #ifdef USE_DASH - - if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps - - if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX - - #endif - - float alpha = opacity; - - #ifdef WORLD_UNITS - - // Find the closest points on the view ray and the line segment - vec3 rayEnd = normalize( worldPos.xyz ) * 1e5; - vec3 lineDir = worldEnd - worldStart; - vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd ); - - vec3 p1 = worldStart + lineDir * params.x; - vec3 p2 = rayEnd * params.y; - vec3 delta = p1 - p2; - float len = length( delta ); - float norm = len / linewidth; - - #ifndef USE_DASH - - #ifdef USE_ALPHA_TO_COVERAGE - - float dnorm = fwidth( norm ); - alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm ); - - #else - - if ( norm > 0.5 ) { - - discard; - - } - - #endif - - #endif - - #else - - #ifdef USE_ALPHA_TO_COVERAGE - - // artifacts appear on some hardware if a derivative is taken within a conditional - float a = vUv.x; - float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; - float len2 = a * a + b * b; - float dlen = fwidth( len2 ); - - if ( abs( vUv.y ) > 1.0 ) { - - alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 ); - - } - - #else - - if ( abs( vUv.y ) > 1.0 ) { - - float a = vUv.x; - float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; - float len2 = a * a + b * b; - - if ( len2 > 1.0 ) discard; - - } - - #endif - - #endif - - vec4 diffuseColor = vec4( diffuse, alpha ); - - #include - #include - - gl_FragColor = vec4( diffuseColor.rgb, alpha ); - - #include - #include - #include - #include - - } - `};var aP1=new X0,rP1=new I1,tP1=new I1,eP1=new X0,A_1=new X0,Q_1=new X0,J_1=new I1,K_1=new Y0,C_1=new R5,Y_1=new I1,U_1=new DA,Z_1=new O2,B_1=new X0;var R_1=new I1,z_1=new I1,D_1=new X0;var e_1=new t2,AT1=new I1;class Oz{constructor(A=4){this.pool=A,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(A){if(!this.workers[A]){let Q=this.workerCreator();Q.addEventListener("message",this._onMessage.bind(this,A)),this.workers[A]=Q}}_getIdleWorker(){for(let A=0;A{let K=this._getIdleWorker();if(K!==-1)this._initWorker(K),this.workerStatus|=1<A.terminate()),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}var Nz,X7,Fz,Lz={env:{emscripten_notify_memory_growth:function(A){Fz=new Uint8Array(X7.exports.memory.buffer)}}};class Rz{init(){return Nz||(Nz=typeof fetch!="undefined"?fetch("data:application/wasm;base64,"+Ru).then((A)=>A.arrayBuffer()).then((A)=>WebAssembly.instantiate(A,Lz)).then(this._init):WebAssembly.instantiate(Buffer.from(Ru,"base64"),Lz).then(this._init),Nz)}_init(A){X7=A.instance,Lz.env.emscripten_notify_memory_growth(0)}decode(A,Q=0){if(!X7)throw new Error("ZSTDDecoder: Await .init() before decoding.");let J=A.byteLength,K=X7.exports.malloc(J);Fz.set(A,K),Q=Q||Number(X7.exports.ZSTD_findDecompressedSize(K,J));let C=X7.exports.malloc(Q),U=X7.exports.ZSTD_decompress(C,Q,K,J),Y=Fz.slice(C,C+U);return X7.exports.free(K),X7.exports.free(C),Y}}var Ru="AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDBgEACQkHBgICAAYGAgQUBwYGAwIGAAMCAQgBBwUGCgoEEQAEBAEIAwgDBQgDEA8IAAcABAUBcAECAgUEAQCAAgYJAX8BQaCgwAILB2AHBm1lbW9yeQIABm1hbGxvYwAoBGZyZWUAJgxaU1REX2lzRXJyb3IAaBlaU1REX2ZpbmREZWNvbXByZXNzZWRTaXplAFQPWlNURF9kZWNvbXByZXNzAEoGX3N0YXJ0ACQJBwEAQQELASQKussBaA8AIAAgACgCBCABajYCBAsZACAAKAIAIAAoAgRBH3F0QQAgAWtBH3F2CwgAIABBiH9LC34BBH9BAyEBIAAoAgQiA0EgTQRAIAAoAggiASAAKAIQTwRAIAAQDQ8LIAAoAgwiAiABRgRAQQFBAiADQSBJGw8LIAAgASABIAJrIANBA3YiBCABIARrIAJJIgEbIgJrIgQ2AgggACADIAJBA3RrNgIEIAAgBCgAADYCAAsgAQsUAQF/IAAgARACIQIgACABEAEgAgv3AQECfyACRQRAIABCADcCACAAQQA2AhAgAEIANwIIQbh/DwsgACABNgIMIAAgAUEEajYCECACQQRPBEAgACABIAJqIgFBfGoiAzYCCCAAIAMoAAA2AgAgAUF/ai0AACIBBEAgAEEIIAEQFGs2AgQgAg8LIABBADYCBEF/DwsgACABNgIIIAAgAS0AACIDNgIAIAJBfmoiBEEBTQRAIARBAWtFBEAgACABLQACQRB0IANyIgM2AgALIAAgAS0AAUEIdCADajYCAAsgASACakF/ai0AACIBRQRAIABBADYCBEFsDwsgAEEoIAEQFCACQQN0ams2AgQgAgsWACAAIAEpAAA3AAAgACABKQAINwAICy8BAX8gAUECdEGgHWooAgAgACgCAEEgIAEgACgCBGprQR9xdnEhAiAAIAEQASACCyEAIAFCz9bTvtLHq9lCfiAAfEIfiUKHla+vmLbem55/fgsdAQF/IAAoAgggACgCDEYEfyAAKAIEQSBGBUEACwuCBAEDfyACQYDAAE8EQCAAIAEgAhBnIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAsMACAAIAEpAAA3AAALQQECfyAAKAIIIgEgACgCEEkEQEEDDwsgACAAKAIEIgJBB3E2AgQgACABIAJBA3ZrIgE2AgggACABKAAANgIAQQALDAAgACABKAIANgAAC/cCAQJ/AkAgACABRg0AAkAgASACaiAASwRAIAAgAmoiBCABSw0BCyAAIAEgAhALDwsgACABc0EDcSEDAkACQCAAIAFJBEAgAwRAIAAhAwwDCyAAQQNxRQRAIAAhAwwCCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigCACACaiAAQQZ2IgFBAnRBsB5qKAIAaiAAQSBxIgBFaiABRSAAQQV2cWoFQbh/CwsdACAAKAKQ4gEQWiAAQQA2AqDiASAAQgA3A5DiAQu1AwEFfyMAQZACayIKJABBuH8hBgJAIAVFDQAgBCwAACIIQf8BcSEHAkAgCEF/TARAIAdBgn9qQQF2IgggBU8NAkFsIQYgB0GBf2oiBUGAAk8NAiAEQQFqIQdBACEGA0AgBiAFTwRAIAUhBiAIIQcMAwUgACAGaiAHIAZBAXZqIgQtAABBBHY6AAAgACAGQQFyaiAELQAAQQ9xOgAAIAZBAmohBgwBCwAACwALIAcgBU8NASAAIARBAWogByAKEFMiBhADDQELIAYhBEEAIQYgAUEAQTQQECEJQQAhBQNAIAQgBkcEQCAAIAZqIggtAAAiAUELSwRAQWwhBgwDBSAJIAFBAnRqIgEgASgCAEEBajYCACAGQQFqIQZBASAILQAAdEEBdSAFaiEFDAILAAsLQWwhBiAFRQ0AIAUQFEEBaiIBQQxLDQAgAyABNgIAQQFBASABdCAFayIDEBQiAXQgA0cNACAAIARqIAFBAWoiADoAACAJIABBAnRqIgAgACgCAEEBajYCACAJKAIEIgBBAkkgAEEBcXINACACIARBAWo2AgAgB0EBaiEGCyAKQZACaiQAIAYLxhEBDH8jAEHwAGsiBSQAQWwhCwJAIANBCkkNACACLwAAIQogAi8AAiEJIAIvAAQhByAFQQhqIAQQDgJAIAMgByAJIApqakEGaiIMSQ0AIAUtAAohCCAFQdgAaiACQQZqIgIgChAGIgsQAw0BIAVBQGsgAiAKaiICIAkQBiILEAMNASAFQShqIAIgCWoiAiAHEAYiCxADDQEgBUEQaiACIAdqIAMgDGsQBiILEAMNASAAIAFqIg9BfWohECAEQQRqIQZBASELIAAgAUEDakECdiIDaiIMIANqIgIgA2oiDiEDIAIhBCAMIQcDQCALIAMgEElxBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgCS0AAyELIAcgBiAFQUBrIAgQAkECdGoiCS8BADsAACAFQUBrIAktAAIQASAJLQADIQogBCAGIAVBKGogCBACQQJ0aiIJLwEAOwAAIAVBKGogCS0AAhABIAktAAMhCSADIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgDS0AAyENIAAgC2oiCyAGIAVB2ABqIAgQAkECdGoiAC8BADsAACAFQdgAaiAALQACEAEgAC0AAyEAIAcgCmoiCiAGIAVBQGsgCBACQQJ0aiIHLwEAOwAAIAVBQGsgBy0AAhABIActAAMhByAEIAlqIgkgBiAFQShqIAgQAkECdGoiBC8BADsAACAFQShqIAQtAAIQASAELQADIQQgAyANaiIDIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgACALaiEAIAcgCmohByAEIAlqIQQgAyANLQADaiEDIAVB2ABqEA0gBUFAaxANciAFQShqEA1yIAVBEGoQDXJFIQsMAQsLIAQgDksgByACS3INAEFsIQsgACAMSw0BIAxBfWohCQNAQQAgACAJSSAFQdgAahAEGwRAIAAgBiAFQdgAaiAIEAJBAnRqIgovAQA7AAAgBUHYAGogCi0AAhABIAAgCi0AA2oiACAGIAVB2ABqIAgQAkECdGoiCi8BADsAACAFQdgAaiAKLQACEAEgACAKLQADaiEADAEFIAxBfmohCgNAIAVB2ABqEAQgACAKS3JFBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgACAJLQADaiEADAELCwNAIAAgCk0EQCAAIAYgBUHYAGogCBACQQJ0aiIJLwEAOwAAIAVB2ABqIAktAAIQASAAIAktAANqIQAMAQsLAkAgACAMTw0AIAAgBiAFQdgAaiAIEAIiAEECdGoiDC0AADoAACAMLQADQQFGBEAgBUHYAGogDC0AAhABDAELIAUoAlxBH0sNACAFQdgAaiAGIABBAnRqLQACEAEgBSgCXEEhSQ0AIAVBIDYCXAsgAkF9aiEMA0BBACAHIAxJIAVBQGsQBBsEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiIAIAYgBUFAayAIEAJBAnRqIgcvAQA7AAAgBUFAayAHLQACEAEgACAHLQADaiEHDAEFIAJBfmohDANAIAVBQGsQBCAHIAxLckUEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwNAIAcgDE0EQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwJAIAcgAk8NACAHIAYgBUFAayAIEAIiAEECdGoiAi0AADoAACACLQADQQFGBEAgBUFAayACLQACEAEMAQsgBSgCREEfSw0AIAVBQGsgBiAAQQJ0ai0AAhABIAUoAkRBIUkNACAFQSA2AkQLIA5BfWohAgNAQQAgBCACSSAFQShqEAQbBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2oiACAGIAVBKGogCBACQQJ0aiIELwEAOwAAIAVBKGogBC0AAhABIAAgBC0AA2ohBAwBBSAOQX5qIQIDQCAFQShqEAQgBCACS3JFBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsDQCAEIAJNBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsCQCAEIA5PDQAgBCAGIAVBKGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBKGogAi0AAhABDAELIAUoAixBH0sNACAFQShqIAYgAEECdGotAAIQASAFKAIsQSFJDQAgBUEgNgIsCwNAQQAgAyAQSSAFQRBqEAQbBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2oiACAGIAVBEGogCBACQQJ0aiICLwEAOwAAIAVBEGogAi0AAhABIAAgAi0AA2ohAwwBBSAPQX5qIQIDQCAFQRBqEAQgAyACS3JFBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsDQCADIAJNBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsCQCADIA9PDQAgAyAGIAVBEGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBEGogAi0AAhABDAELIAUoAhRBH0sNACAFQRBqIAYgAEECdGotAAIQASAFKAIUQSFJDQAgBUEgNgIUCyABQWwgBUHYAGoQCiAFQUBrEApxIAVBKGoQCnEgBUEQahAKcRshCwwJCwAACwALAAALAAsAAAsACwAACwALQWwhCwsgBUHwAGokACALC7UEAQ5/IwBBEGsiBiQAIAZBBGogABAOQVQhBQJAIARB3AtJDQAgBi0ABCEHIANB8ARqQQBB7AAQECEIIAdBDEsNACADQdwJaiIJIAggBkEIaiAGQQxqIAEgAhAxIhAQA0UEQCAGKAIMIgQgB0sNASADQdwFaiEPIANBpAVqIREgAEEEaiESIANBqAVqIQEgBCEFA0AgBSICQX9qIQUgCCACQQJ0aigCAEUNAAsgAkEBaiEOQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgASALaiAKNgIAIAVBAWohBSAKIAxqIQoMAQsLIAEgCjYCAEEAIQUgBigCCCELA0AgBSALRkUEQCABIAUgCWotAAAiDEECdGoiDSANKAIAIg1BAWo2AgAgDyANQQF0aiINIAw6AAEgDSAFOgAAIAVBAWohBQwBCwtBACEBIANBADYCqAUgBEF/cyAHaiEJQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgAyALaiABNgIAIAwgBSAJanQgAWohASAFQQFqIQUMAQsLIAcgBEEBaiIBIAJrIgRrQQFqIQgDQEEBIQUgBCAIT0UEQANAIAUgDk9FBEAgBUECdCIJIAMgBEE0bGpqIAMgCWooAgAgBHY2AgAgBUEBaiEFDAELCyAEQQFqIQQMAQsLIBIgByAPIAogESADIAIgARBkIAZBAToABSAGIAc6AAYgACAGKAIENgIACyAQIQULIAZBEGokACAFC8ENAQt/IwBB8ABrIgUkAEFsIQkCQCADQQpJDQAgAi8AACEKIAIvAAIhDCACLwAEIQYgBUEIaiAEEA4CQCADIAYgCiAMampBBmoiDUkNACAFLQAKIQcgBUHYAGogAkEGaiICIAoQBiIJEAMNASAFQUBrIAIgCmoiAiAMEAYiCRADDQEgBUEoaiACIAxqIgIgBhAGIgkQAw0BIAVBEGogAiAGaiADIA1rEAYiCRADDQEgACABaiIOQX1qIQ8gBEEEaiEGQQEhCSAAIAFBA2pBAnYiAmoiCiACaiIMIAJqIg0hAyAMIQQgCiECA0AgCSADIA9JcQRAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAACAGIAVBQGsgBxACQQF0aiIILQAAIQsgBUFAayAILQABEAEgAiALOgAAIAYgBUEoaiAHEAJBAXRqIggtAAAhCyAFQShqIAgtAAEQASAEIAs6AAAgBiAFQRBqIAcQAkEBdGoiCC0AACELIAVBEGogCC0AARABIAMgCzoAACAGIAVB2ABqIAcQAkEBdGoiCC0AACELIAVB2ABqIAgtAAEQASAAIAs6AAEgBiAFQUBrIAcQAkEBdGoiCC0AACELIAVBQGsgCC0AARABIAIgCzoAASAGIAVBKGogBxACQQF0aiIILQAAIQsgBUEoaiAILQABEAEgBCALOgABIAYgBUEQaiAHEAJBAXRqIggtAAAhCyAFQRBqIAgtAAEQASADIAs6AAEgA0ECaiEDIARBAmohBCACQQJqIQIgAEECaiEAIAkgBUHYAGoQDUVxIAVBQGsQDUVxIAVBKGoQDUVxIAVBEGoQDUVxIQkMAQsLIAQgDUsgAiAMS3INAEFsIQkgACAKSw0BIApBfWohCQNAIAVB2ABqEAQgACAJT3JFBEAgBiAFQdgAaiAHEAJBAXRqIggtAAAhCyAFQdgAaiAILQABEAEgACALOgAAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAASAAQQJqIQAMAQsLA0AgBUHYAGoQBCAAIApPckUEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCwNAIAAgCkkEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCyAMQX1qIQADQCAFQUBrEAQgAiAAT3JFBEAgBiAFQUBrIAcQAkEBdGoiCi0AACEJIAVBQGsgCi0AARABIAIgCToAACAGIAVBQGsgBxACQQF0aiIKLQAAIQkgBUFAayAKLQABEAEgAiAJOgABIAJBAmohAgwBCwsDQCAFQUBrEAQgAiAMT3JFBEAgBiAFQUBrIAcQAkEBdGoiAC0AACEKIAVBQGsgAC0AARABIAIgCjoAACACQQFqIQIMAQsLA0AgAiAMSQRAIAYgBUFAayAHEAJBAXRqIgAtAAAhCiAFQUBrIAAtAAEQASACIAo6AAAgAkEBaiECDAELCyANQX1qIQADQCAFQShqEAQgBCAAT3JFBEAgBiAFQShqIAcQAkEBdGoiAi0AACEKIAVBKGogAi0AARABIAQgCjoAACAGIAVBKGogBxACQQF0aiICLQAAIQogBUEoaiACLQABEAEgBCAKOgABIARBAmohBAwBCwsDQCAFQShqEAQgBCANT3JFBEAgBiAFQShqIAcQAkEBdGoiAC0AACECIAVBKGogAC0AARABIAQgAjoAACAEQQFqIQQMAQsLA0AgBCANSQRAIAYgBUEoaiAHEAJBAXRqIgAtAAAhAiAFQShqIAAtAAEQASAEIAI6AAAgBEEBaiEEDAELCwNAIAVBEGoQBCADIA9PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIAYgBUEQaiAHEAJBAXRqIgAtAAAhAiAFQRBqIAAtAAEQASADIAI6AAEgA0ECaiEDDAELCwNAIAVBEGoQBCADIA5PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIANBAWohAwwBCwsDQCADIA5JBEAgBiAFQRBqIAcQAkEBdGoiAC0AACECIAVBEGogAC0AARABIAMgAjoAACADQQFqIQMMAQsLIAFBbCAFQdgAahAKIAVBQGsQCnEgBUEoahAKcSAFQRBqEApxGyEJDAELQWwhCQsgBUHwAGokACAJC8oCAQR/IwBBIGsiBSQAIAUgBBAOIAUtAAIhByAFQQhqIAIgAxAGIgIQA0UEQCAEQQRqIQIgACABaiIDQX1qIQQDQCAFQQhqEAQgACAET3JFBEAgAiAFQQhqIAcQAkEBdGoiBi0AACEIIAVBCGogBi0AARABIAAgCDoAACACIAVBCGogBxACQQF0aiIGLQAAIQggBUEIaiAGLQABEAEgACAIOgABIABBAmohAAwBCwsDQCAFQQhqEAQgACADT3JFBEAgAiAFQQhqIAcQAkEBdGoiBC0AACEGIAVBCGogBC0AARABIAAgBjoAACAAQQFqIQAMAQsLA0AgACADT0UEQCACIAVBCGogBxACQQF0aiIELQAAIQYgBUEIaiAELQABEAEgACAGOgAAIABBAWohAAwBCwsgAUFsIAVBCGoQChshAgsgBUEgaiQAIAILtgMBCX8jAEEQayIGJAAgBkEANgIMIAZBADYCCEFUIQQCQAJAIANBQGsiDCADIAZBCGogBkEMaiABIAIQMSICEAMNACAGQQRqIAAQDiAGKAIMIgcgBi0ABEEBaksNASAAQQRqIQogBkEAOgAFIAYgBzoABiAAIAYoAgQ2AgAgB0EBaiEJQQEhBANAIAQgCUkEQCADIARBAnRqIgEoAgAhACABIAU2AgAgACAEQX9qdCAFaiEFIARBAWohBAwBCwsgB0EBaiEHQQAhBSAGKAIIIQkDQCAFIAlGDQEgAyAFIAxqLQAAIgRBAnRqIgBBASAEdEEBdSILIAAoAgAiAWoiADYCACAHIARrIQhBACEEAkAgC0EDTQRAA0AgBCALRg0CIAogASAEakEBdGoiACAIOgABIAAgBToAACAEQQFqIQQMAAALAAsDQCABIABPDQEgCiABQQF0aiIEIAg6AAEgBCAFOgAAIAQgCDoAAyAEIAU6AAIgBCAIOgAFIAQgBToABCAEIAg6AAcgBCAFOgAGIAFBBGohAQwAAAsACyAFQQFqIQUMAAALAAsgAiEECyAGQRBqJAAgBAutAQECfwJAQYQgKAIAIABHIAAoAgBBAXYiAyABa0F4aiICQXhxQQhHcgR/IAIFIAMQJ0UNASACQQhqC0EQSQ0AIAAgACgCACICQQFxIAAgAWpBD2pBeHEiASAAa0EBdHI2AgAgASAANgIEIAEgASgCAEEBcSAAIAJBAXZqIAFrIgJBAXRyNgIAQYQgIAEgAkH/////B3FqQQRqQYQgKAIAIABGGyABNgIAIAEQJQsLygIBBX8CQAJAAkAgAEEIIABBCEsbZ0EfcyAAaUEBR2oiAUEESSAAIAF2cg0AIAFBAnRB/B5qKAIAIgJFDQADQCACQXhqIgMoAgBBAXZBeGoiBSAATwRAIAIgBUEIIAVBCEsbZ0Efc0ECdEGAH2oiASgCAEYEQCABIAIoAgQ2AgALDAMLIARBHksNASAEQQFqIQQgAigCBCICDQALC0EAIQMgAUEgTw0BA0AgAUECdEGAH2ooAgAiAkUEQCABQR5LIQIgAUEBaiEBIAJFDQEMAwsLIAIgAkF4aiIDKAIAQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgBGBEAgASACKAIENgIACwsgAigCACIBBEAgASACKAIENgIECyACKAIEIgEEQCABIAIoAgA2AgALIAMgAygCAEEBcjYCACADIAAQNwsgAwvhCwINfwV+IwBB8ABrIgckACAHIAAoAvDhASIINgJcIAEgAmohDSAIIAAoAoDiAWohDwJAAkAgBUUEQCABIQQMAQsgACgCxOABIRAgACgCwOABIREgACgCvOABIQ4gAEEBNgKM4QFBACEIA0AgCEEDRwRAIAcgCEECdCICaiAAIAJqQazQAWooAgA2AkQgCEEBaiEIDAELC0FsIQwgB0EYaiADIAQQBhADDQEgB0EsaiAHQRhqIAAoAgAQEyAHQTRqIAdBGGogACgCCBATIAdBPGogB0EYaiAAKAIEEBMgDUFgaiESIAEhBEEAIQwDQCAHKAIwIAcoAixBA3RqKQIAIhRCEIinQf8BcSEIIAcoAkAgBygCPEEDdGopAgAiFUIQiKdB/wFxIQsgBygCOCAHKAI0QQN0aikCACIWQiCIpyEJIBVCIIghFyAUQiCIpyECAkAgFkIQiKdB/wFxIgNBAk8EQAJAIAZFIANBGUlyRQRAIAkgB0EYaiADQSAgBygCHGsiCiAKIANLGyIKEAUgAyAKayIDdGohCSAHQRhqEAQaIANFDQEgB0EYaiADEAUgCWohCQwBCyAHQRhqIAMQBSAJaiEJIAdBGGoQBBoLIAcpAkQhGCAHIAk2AkQgByAYNwNIDAELAkAgA0UEQCACBEAgBygCRCEJDAMLIAcoAkghCQwBCwJAAkAgB0EYakEBEAUgCSACRWpqIgNBA0YEQCAHKAJEQX9qIgMgA0VqIQkMAQsgA0ECdCAHaigCRCIJIAlFaiEJIANBAUYNAQsgByAHKAJINgJMCwsgByAHKAJENgJIIAcgCTYCRAsgF6chAyALBEAgB0EYaiALEAUgA2ohAwsgCCALakEUTwRAIAdBGGoQBBoLIAgEQCAHQRhqIAgQBSACaiECCyAHQRhqEAQaIAcgB0EYaiAUQhiIp0H/AXEQCCAUp0H//wNxajYCLCAHIAdBGGogFUIYiKdB/wFxEAggFadB//8DcWo2AjwgB0EYahAEGiAHIAdBGGogFkIYiKdB/wFxEAggFqdB//8DcWo2AjQgByACNgJgIAcoAlwhCiAHIAk2AmggByADNgJkAkACQAJAIAQgAiADaiILaiASSw0AIAIgCmoiEyAPSw0AIA0gBGsgC0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ";var zu="display-p3",Du="display-p3-linear";var zz=/*@__PURE__*/new WeakMap,Dz=0,Vz;class M5 extends JA{constructor(A){super(A);if(this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new Oz,this.workerSourceURL="",this.workerConfig=null,typeof MSC_TRANSCODER!=="undefined")console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.')}setTranscoderPath(A){return this.transcoderPath=A,this}setWorkerLimit(A){return this.workerPool.setWorkerLimit(A),this}async detectSupportAsync(A){return this.workerConfig={astcSupported:await A.hasFeatureAsync("texture-compression-astc"),astcHDRSupported:!1,etc1Supported:await A.hasFeatureAsync("texture-compression-etc1"),etc2Supported:await A.hasFeatureAsync("texture-compression-etc2"),dxtSupported:await A.hasFeatureAsync("texture-compression-bc"),bptcSupported:await A.hasFeatureAsync("texture-compression-bptc"),pvrtcSupported:await A.hasFeatureAsync("texture-compression-pvrtc")},this}detectSupport(A){if(A.isWebGPURenderer===!0)this.workerConfig={astcSupported:A.hasFeature("texture-compression-astc"),astcHDRSupported:!1,etc1Supported:A.hasFeature("texture-compression-etc1"),etc2Supported:A.hasFeature("texture-compression-etc2"),dxtSupported:A.hasFeature("texture-compression-bc"),bptcSupported:A.hasFeature("texture-compression-bptc"),pvrtcSupported:A.hasFeature("texture-compression-pvrtc")};else this.workerConfig={astcSupported:A.extensions.has("WEBGL_compressed_texture_astc"),astcHDRSupported:A.extensions.has("WEBGL_compressed_texture_astc")&&A.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"),etc1Supported:A.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:A.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:A.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:A.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:A.extensions.has("WEBGL_compressed_texture_pvrtc")||A.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")};return this}init(){if(!this.transcoderPending){let A=new KA(this.manager);A.setPath(this.transcoderPath),A.setWithCredentials(this.withCredentials);let Q=A.loadAsync("basis_transcoder.js"),J=new KA(this.manager);J.setPath(this.transcoderPath),J.setResponseType("arraybuffer"),J.setWithCredentials(this.withCredentials);let K=J.loadAsync("basis_transcoder.wasm");if(this.transcoderPending=Promise.all([Q,K]).then(([C,U])=>{let Y=M5.BasisWorker.toString(),Z=["/* constants */","let _EngineFormat = "+JSON.stringify(M5.EngineFormat),"let _EngineType = "+JSON.stringify(M5.EngineType),"let _TranscoderFormat = "+JSON.stringify(M5.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(M5.BasisFormat),"/* basis_transcoder.js */",C,"/* worker */",Y.substring(Y.indexOf("{")+1,Y.lastIndexOf("}"))].join(` -`);this.workerSourceURL=URL.createObjectURL(new Blob([Z])),this.transcoderBinary=U,this.workerPool.setWorkerCreator(()=>{let X=new Worker(this.workerSourceURL),E=this.transcoderBinary.slice(0);return X.postMessage({type:"init",config:this.workerConfig,transcoderBinary:E},[E]),X})}),Dz>0)console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances.");Dz++}return this.transcoderPending}load(A,Q,J,K){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");let C=new KA(this.manager);C.setResponseType("arraybuffer"),C.setWithCredentials(this.withCredentials),C.load(A,(U)=>{this.parse(U,Q,K)},J,K)}parse(A,Q,J){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if(zz.has(A))return zz.get(A).promise.then(Q).catch(J);this._createTexture(A).then((K)=>Q?Q(K):null).catch(J)}_createTextureFrom(A,Q){let{type:J,error:K,data:{faces:C,width:U,height:Y,format:Z,type:X,dfdFlags:E}}=A;if(J==="error")return Promise.reject(K);let H;if(Q.faceCount===6)H=new HZ(C,Z,X);else{let $=C[0].mipmaps;H=Q.layerCount>1?new $Z($,U,Y,Q.layerCount,Z,X):new Z9($,U,Y,Z,X)}return H.minFilter=C[0].mipmaps.length===1?HA:o2,H.magFilter=HA,H.generateMipmaps=!1,H.needsUpdate=!0,H.colorSpace=Vu(Q),H.premultiplyAlpha=!!(E&Iu),H}async _createTexture(A,Q={}){let J=Nu(new Uint8Array(A)),K=J.vkFormat===gG&&J.dataFormatDescriptor[0].colorModel===167;if(!(J.vkFormat===Ou||K&&!this.workerConfig.astcHDRSupported))return wC1(J);let U=Q,Y=this.init().then(()=>{return this.workerPool.postMessage({type:"transcode",buffer:A,taskConfig:U},[A])}).then((Z)=>this._createTextureFrom(Z.data,J));return zz.set(A,{promise:Y}),Y}dispose(){if(this.workerPool.dispose(),this.workerSourceURL)URL.revokeObjectURL(this.workerSourceURL);return Dz--,this}}M5.BasisFormat={ETC1S:0,UASTC:1,UASTC_HDR:2};M5.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16,BC6H:22,RGB_HALF:24,RGBA_HALF:25};M5.EngineFormat={RGBAFormat:xA,RGBA_ASTC_4x4_Format:yQ,RGB_BPTC_UNSIGNED_Format:bQ,RGBA_BPTC_Format:gQ,RGBA_ETC2_EAC_Format:KC,RGBA_PVRTC_4BPPV1_Format:vQ,RGBA_S3TC_DXT5_Format:B4,RGB_ETC1_Format:xQ,RGB_ETC2_Format:JC,RGB_PVRTC_4BPPV1_Format:jQ,RGBA_S3TC_DXT1_Format:SQ};M5.EngineType={UnsignedByteType:dA,HalfFloatType:g0,FloatType:aA};M5.BasisWorker=function(){let A,Q,J,K=_EngineFormat,C=_EngineType,U=_TranscoderFormat,Y=_BasisFormat;self.addEventListener("message",function(F){let V=F.data;switch(V.type){case"init":A=V.config,Z(V.transcoderBinary);break;case"transcode":Q.then(()=>{try{let{faces:D,buffers:L,width:R,height:M,hasAlpha:T,format:h,type:y,dfdFlags:g}=X(V.buffer);self.postMessage({type:"transcode",id:V.id,data:{faces:D,width:R,height:M,hasAlpha:T,format:h,type:y,dfdFlags:g}},L)}catch(D){console.error(D),self.postMessage({type:"error",id:V.id,error:D.message})}});break}});function Z(F){Q=new Promise((V)=>{J={wasmBinary:F,onRuntimeInitialized:V},BASIS(J)}).then(()=>{if(J.initializeBasis(),J.KTX2File===void 0)console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.")})}function X(F){let V=new J.KTX2File(new Uint8Array(F));function D(){V.close(),V.delete()}if(!V.isValid())throw D(),new Error("THREE.KTX2Loader:\tInvalid or unsupported .ktx2 file");let L;if(V.isUASTC())L=Y.UASTC;else if(V.isETC1S())L=Y.ETC1S;else if(V.isHDR())L=Y.UASTC_HDR;else throw new Error("THREE.KTX2Loader: Unknown Basis encoding");let R=V.getWidth(),M=V.getHeight(),T=V.getLayers()||1,h=V.getLevels(),y=V.getFaces(),g=V.getHasAlpha(),f=V.getDFDFlags(),{transcoderFormat:u,engineFormat:d,engineType:n}=$(L,R,M,g);if(!R||!M||!h)throw D(),new Error("THREE.KTX2Loader:\tInvalid texture");if(!V.startTranscoding())throw D(),new Error("THREE.KTX2Loader: .startTranscoding failed");let B=[],q=[];for(let P=0;P1)S=b.origWidth,_=b.origHeight;else S=b.width,_=b.height;let p=new Uint8Array(V.getImageTranscodedSizeInBytes(w,j,0,u)),s=V.transcodeImage(p,w,j,P,u,0,-1,-1);if(n===C.HalfFloatType)p=new Uint16Array(p.buffer,p.byteOffset,p.byteLength/Uint16Array.BYTES_PER_ELEMENT);if(!s)throw D(),new Error("THREE.KTX2Loader: .transcodeImage failed.");k.push(p)}let W=N(k);O.push({data:W,width:S,height:_}),q.push(W.buffer)}B.push({mipmaps:O,width:R,height:M,format:d,type:n})}return D(),{faces:B,buffers:q,width:R,height:M,hasAlpha:g,dfdFlags:f,format:d,type:n}}let E=[{if:"astcSupported",basisFormat:[Y.UASTC],transcoderFormat:[U.ASTC_4x4,U.ASTC_4x4],engineFormat:[K.RGBA_ASTC_4x4_Format,K.RGBA_ASTC_4x4_Format],engineType:[C.UnsignedByteType],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[Y.ETC1S,Y.UASTC],transcoderFormat:[U.BC7_M5,U.BC7_M5],engineFormat:[K.RGBA_BPTC_Format,K.RGBA_BPTC_Format],engineType:[C.UnsignedByteType],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[Y.ETC1S,Y.UASTC],transcoderFormat:[U.BC1,U.BC3],engineFormat:[K.RGBA_S3TC_DXT1_Format,K.RGBA_S3TC_DXT5_Format],engineType:[C.UnsignedByteType],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[Y.ETC1S,Y.UASTC],transcoderFormat:[U.ETC1,U.ETC2],engineFormat:[K.RGB_ETC2_Format,K.RGBA_ETC2_EAC_Format],engineType:[C.UnsignedByteType],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[Y.ETC1S,Y.UASTC],transcoderFormat:[U.ETC1],engineFormat:[K.RGB_ETC1_Format],engineType:[C.UnsignedByteType],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[Y.ETC1S,Y.UASTC],transcoderFormat:[U.PVRTC1_4_RGB,U.PVRTC1_4_RGBA],engineFormat:[K.RGB_PVRTC_4BPPV1_Format,K.RGBA_PVRTC_4BPPV1_Format],engineType:[C.UnsignedByteType],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0},{if:"bptcSupported",basisFormat:[Y.UASTC_HDR],transcoderFormat:[U.BC6H],engineFormat:[K.RGB_BPTC_UNSIGNED_Format],engineType:[C.HalfFloatType],priorityHDR:1,needsPowerOfTwo:!1},{basisFormat:[Y.ETC1S,Y.UASTC],transcoderFormat:[U.RGBA32,U.RGBA32],engineFormat:[K.RGBAFormat,K.RGBAFormat],engineType:[C.UnsignedByteType,C.UnsignedByteType],priorityETC1S:100,priorityUASTC:100,needsPowerOfTwo:!1},{basisFormat:[Y.UASTC_HDR],transcoderFormat:[U.RGBA_HALF],engineFormat:[K.RGBAFormat],engineType:[C.HalfFloatType],priorityHDR:100,needsPowerOfTwo:!1}],H={[Y.ETC1S]:E.filter((F)=>F.basisFormat.includes(Y.ETC1S)).sort((F,V)=>F.priorityUASTC-V.priorityUASTC),[Y.UASTC]:E.filter((F)=>F.basisFormat.includes(Y.UASTC)).sort((F,V)=>F.priorityUASTC-V.priorityUASTC),[Y.UASTC_HDR]:E.filter((F)=>F.basisFormat.includes(Y.UASTC_HDR)).sort((F,V)=>F.priorityHDR-V.priorityHDR)};function $(F,V,D,L){let R=H[F];for(let M=0;M{let Y=new Rz;await Y.init(),U(Y)});J=await Vz}let K=[];for(let U=0;U>U),Z=Math.max(1,A.pixelHeight>>U),X=A.pixelDepth?Math.max(1,A.pixelDepth>>U):0,E=A.levels[U],H;if(A.supercompressionScheme===Wu)H=E.levelData;else if(A.supercompressionScheme===Xz)H=J.decode(E.levelData,E.uncompressedByteLength);else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");let $;if(wz[Q]===aA)$=new Float32Array(H.buffer,H.byteOffset,H.byteLength/Float32Array.BYTES_PER_ELEMENT);else if(wz[Q]===g0)$=new Uint16Array(H.buffer,H.byteOffset,H.byteLength/Uint16Array.BYTES_PER_ELEMENT);else $=H;K.push({data:$,width:Y,height:Z,depth:X})}let C;if(MC1.has(Mz[Q]))C=A.pixelDepth===0?new fA(K[0].data,A.pixelWidth,A.pixelHeight):new q5(K[0].data,A.pixelWidth,A.pixelHeight,A.pixelDepth);else{if(A.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");C=new Z9(K,A.pixelWidth,A.pixelHeight),C.minFilter=K.length===1?HA:o2,C.magFilter=HA}return C.mipmaps=K,C.type=wz[Q],C.format=Mz[Q],C.colorSpace=Vu(A),C.needsUpdate=!0,Promise.resolve(C)}function Vu(A){let Q=A.dataFormatDescriptor[0];if(Q.colorPrimaries===$z)return Q.transferFunction===hG?CA:GA;else if(Q.colorPrimaries===qu)return Q.transferFunction===hG?zu:Du;else if(Q.colorPrimaries===Ez)return P2;else return console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${Q.colorPrimaries}"`),P2}var ST1=new I1,jT1=new I1;var vT1=new f6;var wu={};z3(wu,{default:()=>R2});var R2={};if(typeof document!=="undefined"){function createTag(A){return document.createElement(A)}function extendPrototype(A,Q){var J,K=A.length,C;for(J=0;J1)J[1]=1;else if(J[1]<=0)J[1]=0;return HSVtoRGB(J[0],J[1],J[2])}function addBrightnessToRGB(A,Q){var J=RGBtoHSV(A[0]*255,A[1]*255,A[2]*255);if(J[2]+=Q,J[2]>1)J[2]=1;else if(J[2]<0)J[2]=0;return HSVtoRGB(J[0],J[1],J[2])}function addHueToRGB(A,Q){var J=RGBtoHSV(A[0]*255,A[1]*255,A[2]*255);if(J[0]+=Q/360,J[0]>1)J[0]-=1;else if(J[0]<0)J[0]+=1;return HSVtoRGB(J[0],J[1],J[2])}function createNS(A){return document.createElementNS("http://www.w3.org/2000/svg",A)}function BaseEvent(){}function getRenderer(A){return renderers[A]}function bezFunction(){var A=Math;function Q(I,N,F,V,D,L){var R=I*V+N*D+F*L-D*V-L*I-F*N;return R>-0.001&&R<0.001}function J(I,N,F,V,D,L,R,M,T){if(F===0&&L===0&&T===0)return Q(I,N,V,D,R,M);var h=A.sqrt(A.pow(V-I,2)+A.pow(D-N,2)+A.pow(L-F,2)),y=A.sqrt(A.pow(R-I,2)+A.pow(M-N,2)+A.pow(T-F,2)),g=A.sqrt(A.pow(R-V,2)+A.pow(M-D,2)+A.pow(T-L,2)),f;if(h>y)if(h>g)f=h-y-g;else f=g-y-h;else if(g>y)f=g-y-h;else f=y-h-g;return f>-0.0001&&f<0.0001}var K=function(){return function(I,N,F,V){var D=getDefaultCurveSegments(),L,R,M,T,h,y=0,g,f=[],u=[],d=bezierLengthPool.newElement();M=F.length;for(L=0;LR?-1:1,h=!0;while(h){if(V[L]<=R&&V[L+1]>R)M=(R-V[L])/(V[L+1]-V[L]),h=!1;else L+=T;if(L<0||L>=D-1){if(L===D-1)return F[L];h=!1}}return F[L]+(F[L+1]-F[L])*M}function E(I,N,F,V,D,L){var R=X(D,L),M=1-R,T=A.round((M*M*M*I[0]+(R*M*M+M*R*M+M*M*R)*F[0]+(R*R*M+M*R*R+R*M*R)*V[0]+R*R*R*N[0])*1000)/1000,h=A.round((M*M*M*I[1]+(R*M*M+M*R*M+M*M*R)*F[1]+(R*R*M+M*R*R+R*M*R)*V[1]+R*R*R*N[1])*1000)/1000;return[T,h]}var H=createTypedArray("float32",8);function $(I,N,F,V,D,L,R){if(D<0)D=0;else if(D>1)D=1;var M=X(D,R);L=L>1?1:L;var T=X(L,R),h,y=I.length,g=1-M,f=1-T,u=g*g*g,d=M*g*g*3,n=M*M*g*3,B=M*M*M,q=g*g*f,P=M*g*f+g*M*f+g*g*T,O=M*M*f+g*M*T+M*g*T,w=M*M*T,k=g*f*f,S=M*f*f+g*T*f+g*f*T,_=M*T*f+g*T*T+M*f*T,W=M*T*T,j=f*f*f,b=T*f*f+f*T*f+f*f*T,p=T*T*f+f*T*T+T*f*T,s=T*T*T;for(h=0;h1)setDefaultCurveSegments(A);if(getDefaultCurveSegments()>=50)roundValues(!1);else roundValues(!0)}function inBrowser(){return typeof navigator!=="undefined"}function installPlugin(A,Q){if(A==="expressions")setExpressionsPlugin(Q)}function getFactory(A){switch(A){case"propertyFactory":return PropertyFactory;case"shapePropertyFactory":return ShapePropertyFactory;case"matrix":return Matrix;default:return null}}function checkReady(){if(document.readyState==="complete")clearInterval(readyStateCheckInterval),searchAnimations()}function getQueryVariable(A){var Q=queryString.split("&");for(var J=0;J0)this.maskElement.setAttribute("id",I),this.element.maskedElement.setAttribute(R,"url("+getLocationHref()+"#"+I+")"),K.appendChild(this.maskElement);if(this.viewData.length)this.element.addRenderableComponent(this)}function SVGEffects(A){var Q,J="SourceGraphic",K=A.data.ef?A.data.ef.length:0,C=createElementID(),U=filtersFactory.createFilter(C,!0),Y=0;this.filters=[];var Z;for(Q=0;Q=E)d/=2,n/=2,B>>>=1;return(d+B)/n};return u.int32=function(){return f.g(4)|0},u.quick=function(){return f.g(4)/4294967296},u.double=u,D(R(f.S),A),(T.pass||h||function(d,n,B,q){if(q){if(q.S)F(q,f);d.state=function(){return F(f,{})}}if(B)return Q[Y]=d,n;else return d})(u,g,"global"in T?T.global:this==Q,T.state)}Q["seed"+Y]=I;function N(M){var T,h=M.length,y=this,g=0,f=y.i=y.j=0,u=y.S=[];if(!h)M=[h++];while(gD.length-1)N=D.length-1;M=D[D.length-1-N].t,R=L-M}else{if(!N)R=Math.max(0,L-this.elem.data.ip);else R=Math.abs(L-this.elem.comp.globalData.frameRate*N);M=L-R}var T,h,y;if(I==="pingpong"){var g=Math.floor((V-M)/R);if(g%2!==0)return this.getValueAtTime((R-(V-M)%R+M)/this.comp.globalData.frameRate,0)}else if(I==="offset"){var f=this.getValueAtTime(M/this.comp.globalData.frameRate,0),u=this.getValueAtTime(L/this.comp.globalData.frameRate,0),d=this.getValueAtTime(((V-M)%R+M)/this.comp.globalData.frameRate,0),n=Math.floor((V-M)/R);if(this.pv.length){y=new Array(f.length),h=y.length;for(T=0;T=L)return this.pv;var R,M;if(!F){if(!N||N>D.length-1)N=D.length-1;M=D[N].t,R=M-L}else{if(!N)R=Math.max(0,this.elem.data.op-L);else R=Math.abs(this.elem.comp.globalData.frameRate*N);M=L+R}var T,h,y;if(I==="pingpong"){var g=Math.floor((L-V)/R);if(g%2===0)return this.getValueAtTime(((L-V)%R+L)/this.comp.globalData.frameRate,0)}else if(I==="offset"){var f=this.getValueAtTime(L/this.comp.globalData.frameRate,0),u=this.getValueAtTime(M/this.comp.globalData.frameRate,0),d=this.getValueAtTime((R-(L-V)%R+L)/this.comp.globalData.frameRate,0),n=Math.floor((L-V)/R)+1;if(this.pv.length){y=new Array(f.length),h=y.length;for(T=0;T1?(D-V)/(N-1):1,R=0,M=0,T;if(this.pv.length)T=createTypedArray("float32",this.pv.length);else T=0;var h;while(RL){var y=R,g=F.c&&R===M-1?0:R+1,f=(L-T)/D[R].addedLength;h=bez.getPointInSegment(F.v[y],F.v[g],F.o[y],F.i[g],f,D[R]);break}else T+=D[R].addedLength;R+=1}if(!h)h=F.c?[F.v[0][0],F.v[0][1]]:[F.v[F._length-1][0],F.v[F._length-1][1]];return h},vectorOnPath:function(I,N,F){if(I==1)I=this.v.c;else if(I==0)I=0.999;var V=this.pointOnPath(I,N),D=this.pointOnPath(I+0.001,N),L=D[0]-V[0],R=D[1]-V[1],M=Math.sqrt(Math.pow(L,2)+Math.pow(R,2));if(M===0)return[0,0];var T=F==="tangent"?[L/M,R/M]:[-R/M,L/M];return T},tangentOnPath:function(I,N){return this.vectorOnPath(I,N,"tangent")},normalOnPath:function(I,N){return this.vectorOnPath(I,N,"normal")},setGroupProperty:expressionHelpers.setGroupProperty,getValueAtTime:expressionHelpers.getStaticValueAtTime},extendPrototype([H],X),extendPrototype([H],E),E.prototype.getValueAtTime=Z,E.prototype.initiateExpression=ExpressionManager.initiateExpression;var $=ShapePropertyFactory.getShapeProp;ShapePropertyFactory.getShapeProp=function(I,N,F,V,D){var L=$(I,N,F,V,D);if(L.propertyIndex=N.ix,L.lock=!1,F===3)expressionHelpers.searchExpressions(I,N.pt,L);else if(F===4)expressionHelpers.searchExpressions(I,N.ks,L);if(L.k)I.addDynamicProperty(L);return L}}function initialize$1(){addPropertyDecorator()}function addDecorator(){function A(){if(this.data.d.x)return this.calculateExpression=ExpressionManager.initiateExpression.bind(this)(this.elem,this.data.d,this),this.addEffect(this.getExpressionValue.bind(this)),!0;return null}TextProperty.prototype.getExpressionValue=function(Q,J){var K=this.calculateExpression(J);if(Q.t!==K){var C={};return this.copyData(C,Q),C.t=K.toString(),C.__complete=!1,C}return Q},TextProperty.prototype.searchProperty=function(){var Q=this.searchKeyframes(),J=this.searchExpressions();return this.kf=Q||J,this.kf},TextProperty.prototype.searchExpressions=A}function initialize(){addDecorator()}let svgNS="http://www.w3.org/2000/svg",locationHref="",_useWebWorker=!1,initialDefaultFrame=-999999,setWebWorker=(A)=>{_useWebWorker=!!A},getWebWorker=()=>_useWebWorker,setLocationHref=(A)=>{locationHref=A},getLocationHref=()=>locationHref,audioControllerFactory=function(){function A(Q){this.audios=[],this.audioFactory=Q,this._volume=1,this._isMuted=!1}return A.prototype={addAudio:function(Q){this.audios.push(Q)},pause:function(){var Q,J=this.audios.length;for(Q=0;Q{subframeEnabled=!!A},getSubframeEnabled=()=>subframeEnabled,setExpressionsPlugin=(A)=>{expressionsPlugin=A},getExpressionsPlugin=()=>expressionsPlugin,setDefaultCurveSegments=(A)=>{defaultCurveSegments=A},getDefaultCurveSegments=()=>defaultCurveSegments,setIdPrefix=(A)=>{idPrefix$1=A},getIdPrefix=()=>idPrefix$1,dataManager=function(){var A=1,Q=[],J,K,C={onmessage:function(){},postMessage:function(I){J({data:I})}},U={postMessage:function(I){C.onmessage({data:I})}};function Y(I){if(window.Worker&&window.Blob&&getWebWorker()){var N=new Blob(["var _workerSelf = self; self.onmessage = ",I.toString()],{type:"text/javascript"}),F=URL.createObjectURL(N);return new Worker(F)}return J=I,C}function Z(){if(!K)K=Y(function I(N){function F(){function D(O,w){var k,S,_=O.length,W,j,b,p;for(S=0;S<_;S+=1)if(k=O[S],"ks"in k&&!k.completed){if(k.completed=!0,k.tt)O[S-1].td=k.tt;if(k.hasMask){var s=k.masksProperties;j=s.length;for(W=0;W=0;w-=1)if(O[w].ty==="sh")if(O[w].ks.k.i)h(O[w].ks.k);else{_=O[w].ks.k.length;for(S=0;S<_;S+=1){if(O[w].ks.k[S].s)h(O[w].ks.k[S].s[0]);if(O[w].ks.k[S].e)h(O[w].ks.k[S].e[0])}}else if(O[w].ty==="gr")T(O[w].it)}function h(O){var w,k=O.i.length;for(w=0;wk[0])return!0;if(k[0]>O[0])return!1;if(O[1]>k[1])return!0;if(k[1]>O[1])return!1;if(O[2]>k[2])return!0;if(k[2]>O[2])return!1;return null}var g=function(){var O=[4,4,14];function w(S){var _=S.t.d;S.t.d={k:[{s:_,t:0}]}}function k(S){var _,W=S.length;for(_=0;_=0;_-=1)if(S[_].ty==="sh")if(S[_].ks.k.i)S[_].ks.k.c=S[_].closed;else{b=S[_].ks.k.length;for(j=0;j500)this._imageLoaded(),clearInterval(M);R+=1}.bind(this),50)}function U(L){var R=K(L,this.assetsPath,this.path),M=createNS("image");if(isSafari)this.testImageLoaded(M);else M.addEventListener("load",this._imageLoaded,!1);if(M.addEventListener("error",function(){T.img=A,this._imageLoaded()}.bind(this),!1),M.setAttributeNS("http://www.w3.org/1999/xlink","href",R),this._elementHelper.append)this._elementHelper.append(M);else this._elementHelper.appendChild(M);var T={img:M,assetData:L};return T}function Y(L){var R=K(L,this.assetsPath,this.path),M=createTag("img");M.crossOrigin="anonymous",M.addEventListener("load",this._imageLoaded,!1),M.addEventListener("error",function(){T.img=A,this._imageLoaded()}.bind(this),!1),M.src=R;var T={img:M,assetData:L};return T}function Z(L){var R={assetData:L},M=K(L,this.assetsPath,this.path);return dataManager.loadData(M,function(T){R.img=T,this._footageLoaded()}.bind(this),function(){R.img={},this._footageLoaded()}.bind(this)),R}function X(L,R){this.imagesLoadedCb=R;var M,T=L.length;for(M=0;M{renderers[A]=Q},AnimationItem=function(){this._cbs=[],this.name="",this.path="",this.isLoaded=!1,this.currentFrame=0,this.currentRawFrame=0,this.firstFrame=0,this.totalFrames=0,this.frameRate=0,this.frameMult=0,this.playSpeed=1,this.playDirection=1,this.playCount=0,this.animationData={},this.assets=[],this.isPaused=!0,this.autoplay=!1,this.loop=!0,this.renderer=null,this.animationID=createElementID(),this.assetsPath="",this.timeCompleted=0,this.segmentPos=0,this.isSubframeEnabled=getSubframeEnabled(),this.segments=[],this._idle=!0,this._completedLoop=!1,this.projectInterface=ProjectInterface(),this.imagePreloader=new ImagePreloader,this.audioController=audioControllerFactory(),this.markers=[],this.configAnimation=this.configAnimation.bind(this),this.onSetupError=this.onSetupError.bind(this),this.onSegmentComplete=this.onSegmentComplete.bind(this),this.drawnFrameEvent=new BMEnterFrameEvent("drawnFrame",0,0,0)};extendPrototype([BaseEvent],AnimationItem),AnimationItem.prototype.setParams=function(A){if(A.wrapper||A.container)this.wrapper=A.wrapper||A.container;var Q="svg";if(A.animType)Q=A.animType;else if(A.renderer)Q=A.renderer;let J=getRenderer(Q);if(this.renderer=new J(this,A.rendererSettings),this.imagePreloader.setCacheType(Q,this.renderer.globalData.defs),this.renderer.setProjectInterface(this.projectInterface),this.animType=Q,A.loop===""||A.loop===null||A.loop===void 0||A.loop===!0)this.loop=!0;else if(A.loop===!1)this.loop=!1;else this.loop=parseInt(A.loop,10);if(this.autoplay="autoplay"in A?A.autoplay:!0,this.name=A.name?A.name:"",this.autoloadSegments=Object.prototype.hasOwnProperty.call(A,"autoloadSegments")?A.autoloadSegments:!0,this.assetsPath=A.assetsPath,this.initialSegment=A.initialSegment,A.audioFactory)this.audioController.setAudioFactory(A.audioFactory);if(A.animationData)this.setupAnimation(A.animationData);else if(A.path){if(A.path.lastIndexOf("\\")!==-1)this.path=A.path.substr(0,A.path.lastIndexOf("\\")+1);else this.path=A.path.substr(0,A.path.lastIndexOf("/")+1);this.fileName=A.path.substr(A.path.lastIndexOf("/")+1),this.fileName=this.fileName.substr(0,this.fileName.lastIndexOf(".json")),dataManager.loadAnimation(A.path,this.configAnimation,this.onSetupError)}},AnimationItem.prototype.onSetupError=function(){this.trigger("data_failed")},AnimationItem.prototype.setupAnimation=function(A){dataManager.completeAnimation(A,this.configAnimation)},AnimationItem.prototype.setData=function(A,Q){if(Q){if(typeof Q!=="object")Q=JSON.parse(Q)}var J={wrapper:A,animationData:Q},K=A.attributes;J.path=K.getNamedItem("data-animation-path")?K.getNamedItem("data-animation-path").value:K.getNamedItem("data-bm-path")?K.getNamedItem("data-bm-path").value:K.getNamedItem("bm-path")?K.getNamedItem("bm-path").value:"",J.animType=K.getNamedItem("data-anim-type")?K.getNamedItem("data-anim-type").value:K.getNamedItem("data-bm-type")?K.getNamedItem("data-bm-type").value:K.getNamedItem("bm-type")?K.getNamedItem("bm-type").value:K.getNamedItem("data-bm-renderer")?K.getNamedItem("data-bm-renderer").value:K.getNamedItem("bm-renderer")?K.getNamedItem("bm-renderer").value:"canvas";var C=K.getNamedItem("data-anim-loop")?K.getNamedItem("data-anim-loop").value:K.getNamedItem("data-bm-loop")?K.getNamedItem("data-bm-loop").value:K.getNamedItem("bm-loop")?K.getNamedItem("bm-loop").value:"";if(C==="false")J.loop=!1;else if(C==="true")J.loop=!0;else if(C!=="")J.loop=parseInt(C,10);var U=K.getNamedItem("data-anim-autoplay")?K.getNamedItem("data-anim-autoplay").value:K.getNamedItem("data-bm-autoplay")?K.getNamedItem("data-bm-autoplay").value:K.getNamedItem("bm-autoplay")?K.getNamedItem("bm-autoplay").value:!0;J.autoplay=U!=="false",J.name=K.getNamedItem("data-name")?K.getNamedItem("data-name").value:K.getNamedItem("data-bm-name")?K.getNamedItem("data-bm-name").value:K.getNamedItem("bm-name")?K.getNamedItem("bm-name").value:"";var Y=K.getNamedItem("data-anim-prerender")?K.getNamedItem("data-anim-prerender").value:K.getNamedItem("data-bm-prerender")?K.getNamedItem("data-bm-prerender").value:K.getNamedItem("bm-prerender")?K.getNamedItem("bm-prerender").value:"";if(Y==="false")J.prerender=!1;this.setParams(J)},AnimationItem.prototype.includeLayers=function(A){if(A.op>this.animationData.op)this.animationData.op=A.op,this.totalFrames=Math.floor(A.op-this.animationData.ip);var Q=this.animationData.layers,J,K=Q.length,C=A.layers,U,Y=C.length;for(U=0;Uthis.timeCompleted)this.currentFrame=this.timeCompleted;this.trigger("enterFrame"),this.renderFrame(),this.trigger("drawnFrame")},AnimationItem.prototype.renderFrame=function(){if(this.isLoaded===!1||!this.renderer)return;try{this.renderer.renderFrame(this.currentFrame+this.firstFrame)}catch(A){this.triggerRenderFrameError(A)}},AnimationItem.prototype.play=function(A){if(A&&this.name!==A)return;if(this.isPaused===!0){if(this.isPaused=!1,this.trigger("_pause"),this.audioController.resume(),this._idle)this._idle=!1,this.trigger("_active")}},AnimationItem.prototype.pause=function(A){if(A&&this.name!==A)return;if(this.isPaused===!1)this.isPaused=!0,this.trigger("_play"),this._idle=!0,this.trigger("_idle"),this.audioController.pause()},AnimationItem.prototype.togglePause=function(A){if(A&&this.name!==A)return;if(this.isPaused===!0)this.play();else this.pause()},AnimationItem.prototype.stop=function(A){if(A&&this.name!==A)return;this.pause(),this.playCount=0,this._completedLoop=!1,this.setCurrentRawFrameValue(0)},AnimationItem.prototype.getMarkerData=function(A){var Q;for(var J=0;J=this.totalFrames-1&&this.frameModifier>0)if(!this.loop||this.playCount===this.loop){if(!this.checkSegments(Q>this.totalFrames?Q%this.totalFrames:0))J=!0,Q=this.totalFrames-1}else if(Q>=this.totalFrames){if(this.playCount+=1,!this.checkSegments(Q%this.totalFrames))this.setCurrentRawFrameValue(Q%this.totalFrames),this._completedLoop=!0,this.trigger("loopComplete")}else this.setCurrentRawFrameValue(Q);else if(Q<0){if(!this.checkSegments(Q%this.totalFrames))if(this.loop&&!(this.playCount--<=0&&this.loop!==!0))if(this.setCurrentRawFrameValue(this.totalFrames+Q%this.totalFrames),!this._completedLoop)this._completedLoop=!0;else this.trigger("loopComplete");else J=!0,Q=0}else this.setCurrentRawFrameValue(Q);if(J)this.setCurrentRawFrameValue(Q),this.pause(),this.trigger("complete")},AnimationItem.prototype.adjustSegment=function(A,Q){if(this.playCount=0,A[1]0)if(this.playSpeed<0)this.setSpeed(-this.playSpeed);else this.setDirection(-1);this.totalFrames=A[0]-A[1],this.timeCompleted=this.totalFrames,this.firstFrame=A[1],this.setCurrentRawFrameValue(this.totalFrames-0.001-Q)}else if(A[1]>A[0]){if(this.frameModifier<0)if(this.playSpeed<0)this.setSpeed(-this.playSpeed);else this.setDirection(1);this.totalFrames=A[1]-A[0],this.timeCompleted=this.totalFrames,this.firstFrame=A[0],this.setCurrentRawFrameValue(0.001+Q)}this.trigger("segmentStart")},AnimationItem.prototype.setSegment=function(A,Q){var J=-1;if(this.isPaused){if(this.currentRawFrame+this.firstFrameQ)J=Q-A}if(this.firstFrame=A,this.totalFrames=Q-A,this.timeCompleted=this.totalFrames,J!==-1)this.goToAndStop(J,!0)},AnimationItem.prototype.playSegments=function(A,Q){if(Q)this.segments.length=0;if(typeof A[0]==="object"){var J,K=A.length;for(J=0;J=0;k-=1)Q[k].animation.destroy(w)}function f(w,k,S){var _=[].concat([].slice.call(document.getElementsByClassName("lottie")),[].slice.call(document.getElementsByClassName("bodymovin"))),W,j=_.length;for(W=0;W0)T=f;else M=f;while(Math.abs(g)>U&&++u=C)return D(R,d,M,T);if(n===0)return d;return V(R,y,y+X,M,T)}},A}(),pooling=function(){function A(Q){return Q.concat(createSizedArray(Q.length))}return{double:A}}(),poolFactory=function(){return function(A,Q,J){var K=0,C=A,U=createSizedArray(C),Y={newElement:Z,release:X};function Z(){var E;if(K)K-=1,E=U[K];else E=Q();return E}function X(E){if(K===C)U=pooling.double(U),C*=2;if(J)J(E);U[K]=E,K+=1}return Y}}(),bezierLengthPool=function(){function A(){return{addedLength:0,percents:createTypedArray("float32",getDefaultCurveSegments()),lengths:createTypedArray("float32",getDefaultCurveSegments())}}return poolFactory(8,A)}(),segmentsLengthPool=function(){function A(){return{lengths:[],totalLength:0}}function Q(J){var K,C=J.lengths.length;for(K=0;K=u.t-R){if(f.h)f=u;T=0;break}if(u.t-R>D){T=h;break}if(h=k||D=k?W.points.length-1:0;B=W.points[j].point.length;for(n=0;n=s&&b=k)M[0]=_[0],M[1]=_[1],M[2]=_[2];else if(D<=S)M[0]=f.s[0],M[1]=f.s[1],M[2]=f.s[2];else{var U1=U(f.s),O1=U(_),E1=(D-S)/(k-S);C(M,K(U1,O1,E1))}else for(h=0;h=k)q=1;else if(D0.000001)B=Math.acos(q),P=Math.sin(B),O=Math.sin((1-R)*B)/P,w=Math.sin(R*B)/P;else O=1-R,w=R;return M[0]=O*T+w*f,M[1]=O*h+w*u,M[2]=O*y+w*d,M[3]=O*g+w*n,M}function C(D,L){var R=L[0],M=L[1],T=L[2],h=L[3],y=Math.atan2(2*M*h-2*R*T,1-2*M*M-2*T*T),g=Math.asin(2*R*M+2*T*h),f=Math.atan2(2*R*h-2*M*T,1-2*R*R-2*T*T);D[0]=y/degToRads,D[1]=g/degToRads,D[2]=f/degToRads}function U(D){var L=D[0]*degToRads,R=D[1]*degToRads,M=D[2]*degToRads,T=Math.cos(L/2),h=Math.cos(R/2),y=Math.cos(M/2),g=Math.sin(L/2),f=Math.sin(R/2),u=Math.sin(M/2),d=T*h*y-g*f*u,n=g*f*y+T*h*u,B=g*h*y+T*f*u,q=T*f*y-g*h*u;return[n,B,q,d]}function Y(){var D=this.comp.renderedFrame-this.offsetTime,L=this.keyframes[0].t-this.offsetTime,R=this.keyframes[this.keyframes.length-1].t-this.offsetTime;if(!(D===this._caching.lastFrame||this._caching.lastFrame!==A&&(this._caching.lastFrame>=R&&D>=R||this._caching.lastFrame=D)this._caching._lastKeyframeIndex=-1,this._caching.lastIndex=0;var M=this.interpolateValue(D,this._caching);this.pv=M}return this._caching.lastFrame=D,this.pv}function Z(D){var L;if(this.propType==="unidimensional"){if(L=D*this.mult,Q(this.v-L)>0.00001)this.v=L,this._mdf=!0}else{var R=0,M=this.v.length;while(R0.00001)this.v[R]=L,this._mdf=!0;R+=1}}}function X(){if(this.elem.globalData.frameId===this.frameId||!this.effectsSequence.length)return;if(this.lock){this.setVValue(this.pv);return}this.lock=!0,this._mdf=this._isFirstFrame;var D,L=this.effectsSequence.length,R=this.kf?this.pv:this.data.k;for(D=0;D=this._maxLength)this.doubleArrayLength();switch(J){case"v":U=this.v;break;case"i":U=this.i;break;case"o":U=this.o;break;default:U=[];break}if(!U[K]||U[K]&&!C)U[K]=pointPool.newElement();U[K][0]=A,U[K][1]=Q},ShapePath.prototype.setTripleAt=function(A,Q,J,K,C,U,Y,Z){this.setXYAt(A,Q,"v",Y,Z),this.setXYAt(J,K,"o",Y,Z),this.setXYAt(C,U,"i",Y,Z)},ShapePath.prototype.reverse=function(){var A=new ShapePath;A.setPathData(this.c,this._length);var Q=this.v,J=this.o,K=this.i,C=0;if(this.c)A.setTripleAt(Q[0][0],Q[0][1],K[0][0],K[0][1],J[0][0],J[0][1],0,!1),C=1;var U=this._length-1,Y=this._length,Z;for(Z=C;Z=P[P.length-1].t-this.offsetTime)h=P[P.length-1].s?P[P.length-1].s[0]:P[P.length-2].e[0],g=!0;else{var O=T,w=P.length-1,k=!0,S,_,W;while(k){if(S=P[O],_=P[O+1],_.t-this.offsetTime>L)break;if(O=_.t-this.offsetTime)B=1;else if(LM&&L>M)))this._caching.lastIndex=T0||k>-0.000001&&k<0)return K(k*S)/S;return k}function w(){var k=this.props,S=O(k[0]),_=O(k[1]),W=O(k[4]),j=O(k[5]),b=O(k[12]),p=O(k[13]);return"matrix("+S+","+_+","+W+","+j+","+b+","+p+")"}return function(){this.reset=C,this.rotate=U,this.rotateX=Y,this.rotateY=Z,this.rotateZ=X,this.skew=H,this.skewFromAxis=$,this.shear=E,this.scale=I,this.setTransform=N,this.translate=F,this.transform=V,this.applyToPoint=T,this.applyToX=h,this.applyToY=y,this.applyToZ=g,this.applyToPointArray=B,this.applyToTriplePoints=n,this.applyToPointStringified=q,this.toCSS=P,this.to2dCSS=w,this.clone=R,this.cloneFromProps=M,this.equals=L,this.inversePoints=d,this.inversePoint=u,this.getInverseMatrix=f,this._t=this.transform,this.isIdentity=D,this._identity=!0,this._identityCalculated=!1,this.props=createTypedArray("float32",16),this.reset()}}();if(standalone="__[STANDALONE]__",animationData="__[ANIMATIONDATA]__",renderer="",R2.play=animationManager.play,R2.pause=animationManager.pause,R2.setLocationHref=setLocation,R2.togglePause=animationManager.togglePause,R2.setSpeed=animationManager.setSpeed,R2.setDirection=animationManager.setDirection,R2.stop=animationManager.stop,R2.searchAnimations=searchAnimations,R2.registerAnimation=animationManager.registerAnimation,R2.loadAnimation=loadAnimation,R2.setSubframeRendering=setSubframeRendering,R2.resize=animationManager.resize,R2.goToAndStop=animationManager.goToAndStop,R2.destroy=animationManager.destroy,R2.setQuality=setQuality,R2.inBrowser=inBrowser,R2.installPlugin=installPlugin,R2.freeze=animationManager.freeze,R2.unfreeze=animationManager.unfreeze,R2.setVolume=animationManager.setVolume,R2.mute=animationManager.mute,R2.unmute=animationManager.unmute,R2.getRegisteredAnimations=animationManager.getRegisteredAnimations,R2.useWebWorker=setWebWorker,R2.setIDPrefix=setPrefix,R2.__getFactory=getFactory,R2.version="[[BM_VERSION]]",queryString="",standalone)Pz=document.getElementsByTagName("script"),Mu=Pz.length-1,_z=Pz[Mu]||{src:""},queryString=_z.src?_z.src.replace(/^[^\?]+\??/,""):"",renderer=getQueryVariable("renderer");readyStateCheckInterval=setInterval(checkReady,100);try{if(!(typeof wu==="object"&&typeof PC1!=="undefined")&&!(typeof define==="function"&&define.amd))window.bodymovin=R2}catch(A){}let ShapeModifiers=function(){var A={},Q={};A.registerModifier=J,A.getModifier=K;function J(C,U){if(!Q[C])Q[C]=U}function K(C,U,Y){return new Q[C](U,Y)}return A}();ShapeModifier.prototype.initModifierProperties=function(){},ShapeModifier.prototype.addShapeToModifier=function(){},ShapeModifier.prototype.addShape=function(A){if(!this.closed){A.sh.container.addDynamicProperty(A.sh);var Q={shape:A.sh,data:A,localShapeCollection:shapeCollectionPool.newShapeCollection()};if(this.shapes.push(Q),this.addShapeToModifier(Q),this._isAnimated)A.setAsAnimated()}},ShapeModifier.prototype.init=function(A,Q){if(this.shapes=[],this.elem=A,this.initDynamicPropertyContainer(A),this.initModifierProperties(A,Q),this.frameId=initialDefaultFrame,this.closed=!1,this.k=!1,this.dynamicProperties.length)this.k=!0;else this.getValue(!0)},ShapeModifier.prototype.processKeys=function(){if(this.elem.globalData.frameId===this.frameId)return;this.frameId=this.elem.globalData.frameId,this.iterateDynamicProperties()},extendPrototype([DynamicPropertyContainer],ShapeModifier),extendPrototype([ShapeModifier],TrimModifier),TrimModifier.prototype.initModifierProperties=function(A,Q){this.s=PropertyFactory.getProp(A,Q.s,0,0.01,this),this.e=PropertyFactory.getProp(A,Q.e,0,0.01,this),this.o=PropertyFactory.getProp(A,Q.o,0,0,this),this.sValue=0,this.eValue=0,this.getValue=this.processKeys,this.m=Q.m,this._isAnimated=!!this.s.effectsSequence.length||!!this.e.effectsSequence.length||!!this.o.effectsSequence.length},TrimModifier.prototype.addShapeToModifier=function(A){A.pathsData=[]},TrimModifier.prototype.calculateShapeEdges=function(A,Q,J,K,C){var U=[];if(Q<=1)U.push({s:A,e:Q});else if(A>=1)U.push({s:A-1,e:Q-1});else U.push({s:A,e:1}),U.push({s:0,e:Q-1});var Y=[],Z,X=U.length,E;for(Z=0;ZK+J)){var H,$;if(E.s*C<=K)H=0;else H=(E.s*C-K)/J;if(E.e*C>=K+J)$=1;else $=(E.e*C-K)/J;Y.push([H,$])}if(!Y.length)Y.push([0,0]);return Y},TrimModifier.prototype.releasePathsData=function(A){var Q,J=A.length;for(Q=0;Q1)Q=1+K;else if(this.s.v<0)Q=0+K;else Q=this.s.v+K;if(this.e.v>1)J=1+K;else if(this.e.v<0)J=0+K;else J=this.e.v+K;if(Q>J){var C=Q;Q=J,J=C}Q=Math.round(Q*1e4)*0.0001,J=Math.round(J*1e4)*0.0001,this.sValue=Q,this.eValue=J}else Q=this.sValue,J=this.eValue;var U,Y,Z=this.shapes.length,X,E,H,$,I,N=0;if(J===Q){for(Y=0;Y=0;Y-=1)if(V=this.shapes[Y],V.shape._mdf){if(D=V.localShapeCollection,D.releaseShapes(),this.m===2&&Z>1)T=this.calculateShapeEdges(Q,J,V.totalShapeLength,M,N),M+=V.totalShapeLength;else T=[[L,R]];E=T.length;for(X=0;X=1)F.push({s:V.totalShapeLength*(L-1),e:V.totalShapeLength*(R-1)});else F.push({s:V.totalShapeLength*L,e:V.totalShapeLength}),F.push({s:0,e:V.totalShapeLength*(R-1)});var h=this.addShapes(V,F[0]);if(F[0].s!==F[0].e){if(F.length>1){var y=V.shape.paths.shapes[V.shape.paths._length-1];if(y.c){var g=h.pop();this.addPaths(h,D),h=this.addShapes(V,F[1],g)}else this.addPaths(h,D),h=this.addShapes(V,F[1])}this.addPaths(h,D)}}V.shape.paths=D}}else if(this._mdf)for(Y=0;YQ.e){J.c=!1;break}else{if(Q.s<=E&&Q.e>=E+H.addedLength)this.addSegment(C[U].v[Z-1],C[U].o[Z-1],C[U].i[Z],C[U].v[Z],J,$,D),D=!1;else N=bez.getNewSegment(C[U].v[Z-1],C[U].v[Z],C[U].o[Z-1],C[U].i[Z],(Q.s-E)/H.addedLength,(Q.e-E)/H.addedLength,I[Z-1]),this.addSegmentFromArray(N,J,$,D),D=!1,J.c=!1;E+=H.addedLength,$+=1}if(C[U].c&&I.length){if(H=I[Z-1],E<=Q.e){var L=I[Z-1].addedLength;if(Q.s<=E&&Q.e>=E+L)this.addSegment(C[U].v[Z-1],C[U].o[Z-1],C[U].i[0],C[U].v[0],J,$,D),D=!1;else N=bez.getNewSegment(C[U].v[Z-1],C[U].v[0],C[U].o[Z-1],C[U].i[0],(Q.s-E)/L,(Q.e-E)/L,I[Z-1]),this.addSegmentFromArray(N,J,$,D),D=!1,J.c=!1}else J.c=!1;E+=H.addedLength,$+=1}if(J._length)J.setXYAt(J.v[V][0],J.v[V][1],"i",V),J.setXYAt(J.v[J._length-1][0],J.v[J._length-1][1],"o",J._length-1);if(E>Q.e)break;if(U=this.p.keyframes[this.p.keyframes.length-1].t)H=this.p.getValueAtTime(this.p.keyframes[this.p.keyframes.length-1].t/E,0),$=this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length-1].t-0.05)/E,0);else H=this.p.pv,$=this.p.getValueAtTime((this.p._caching.lastFrame+this.p.offsetTime-0.01)/E,this.p.offsetTime);else if(this.px&&this.px.keyframes&&this.py.keyframes&&this.px.getValueAtTime&&this.py.getValueAtTime){H=[],$=[];var I=this.px,N=this.py;if(I._caching.lastFrame+I.offsetTime<=I.keyframes[0].t)H[0]=I.getValueAtTime((I.keyframes[0].t+0.01)/E,0),H[1]=N.getValueAtTime((N.keyframes[0].t+0.01)/E,0),$[0]=I.getValueAtTime(I.keyframes[0].t/E,0),$[1]=N.getValueAtTime(N.keyframes[0].t/E,0);else if(I._caching.lastFrame+I.offsetTime>=I.keyframes[I.keyframes.length-1].t)H[0]=I.getValueAtTime(I.keyframes[I.keyframes.length-1].t/E,0),H[1]=N.getValueAtTime(N.keyframes[N.keyframes.length-1].t/E,0),$[0]=I.getValueAtTime((I.keyframes[I.keyframes.length-1].t-0.01)/E,0),$[1]=N.getValueAtTime((N.keyframes[N.keyframes.length-1].t-0.01)/E,0);else H=[I.pv,N.pv],$[0]=I.getValueAtTime((I._caching.lastFrame+I.offsetTime-0.01)/E,I.offsetTime),$[1]=N.getValueAtTime((N._caching.lastFrame+N.offsetTime-0.01)/E,N.offsetTime)}else $=A,H=$;this.v.rotate(-Math.atan2(H[1]-$[1],H[0]-$[0]))}if(this.data.p&&this.data.p.s)if(this.data.p.z)this.v.translate(this.px.v,this.py.v,-this.pz.v);else this.v.translate(this.px.v,this.py.v,0);else this.v.translate(this.p.v[0],this.p.v[1],-this.p.v[2])}this.frameId=this.elem.globalData.frameId}function K(){if(!this.a.k)this.pre.translate(-this.a.v[0],-this.a.v[1],this.a.v[2]),this.appliedTransformations=1;else return;if(!this.s.effectsSequence.length)this.pre.scale(this.s.v[0],this.s.v[1],this.s.v[2]),this.appliedTransformations=2;else return;if(this.sk)if(!this.sk.effectsSequence.length&&!this.sa.effectsSequence.length)this.pre.skewFromAxis(-this.sk.v,this.sa.v),this.appliedTransformations=3;else return;if(this.r){if(!this.r.effectsSequence.length)this.pre.rotate(-this.r.v),this.appliedTransformations=4}else if(!this.rz.effectsSequence.length&&!this.ry.effectsSequence.length&&!this.rx.effectsSequence.length&&!this.or.effectsSequence.length)this.pre.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]),this.appliedTransformations=4}function C(){}function U(X){this._addDynamicProperty(X),this.elem.addDynamicProperty(X),this._isDirty=!0}function Y(X,E,H){if(this.elem=X,this.frameId=-1,this.propType="transform",this.data=E,this.v=new Matrix,this.pre=new Matrix,this.appliedTransformations=0,this.initDynamicPropertyContainer(H||X),E.p&&E.p.s){if(this.px=PropertyFactory.getProp(X,E.p.x,0,0,this),this.py=PropertyFactory.getProp(X,E.p.y,0,0,this),E.p.z)this.pz=PropertyFactory.getProp(X,E.p.z,0,0,this)}else this.p=PropertyFactory.getProp(X,E.p||{k:[0,0,0]},1,0,this);if(E.rx){if(this.rx=PropertyFactory.getProp(X,E.rx,0,degToRads,this),this.ry=PropertyFactory.getProp(X,E.ry,0,degToRads,this),this.rz=PropertyFactory.getProp(X,E.rz,0,degToRads,this),E.or.k[0].ti){var $,I=E.or.k.length;for($=0;$0)J-=1,this._elements.unshift(Q[J]);if(this.dynamicProperties.length)this.k=!0;else this.getValue(!0)},RepeaterModifier.prototype.resetElements=function(A){var Q,J=A.length;for(Q=0;Q0?Math.floor(I):Math.ceil(I),V=this.pMatrix.props,D=this.rMatrix.props,L=this.sMatrix.props;this.pMatrix.reset(),this.rMatrix.reset(),this.sMatrix.reset(),this.tMatrix.reset(),this.matrix.reset();var R=0;if(I>0){while(RF)this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,1,!0),R-=1;if(N)this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,-N,!0),R-=N}K=this.data.m===1?0:this._currentCopies-1,C=this.data.m===1?1:-1,U=this._currentCopies;var M,T;while(U){if(Q=this.elemsData[K].it,J=Q[Q.length-1].transform.mProps.v.props,T=J.length,Q[Q.length-1].transform.mProps._mdf=!0,Q[Q.length-1].transform.op._mdf=!0,Q[Q.length-1].transform.op.v=this._currentCopies===1?this.so.v:this.so.v+(this.eo.v-this.so.v)*(K/(this._currentCopies-1)),R!==0){if(K!==0&&C===1||K!==this._currentCopies-1&&C===-1)this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,1,!1);this.matrix.transform(D[0],D[1],D[2],D[3],D[4],D[5],D[6],D[7],D[8],D[9],D[10],D[11],D[12],D[13],D[14],D[15]),this.matrix.transform(L[0],L[1],L[2],L[3],L[4],L[5],L[6],L[7],L[8],L[9],L[10],L[11],L[12],L[13],L[14],L[15]),this.matrix.transform(V[0],V[1],V[2],V[3],V[4],V[5],V[6],V[7],V[8],V[9],V[10],V[11],V[12],V[13],V[14],V[15]);for(M=0;M{w.helper=X(w),w.cache={}}),this.fonts=T.list;return}var y=T.list,g,f=y.length,u=f;for(g=0;g0)d=!1;if(d){var q=createTag("style");q.setAttribute("f-forigin",y[g].fOrigin),q.setAttribute("f-origin",y[g].origin),q.setAttribute("f-family",y[g].fFamily),q.type="text/css",q.innerText="@font-face {font-family: "+y[g].fFamily+"; font-style: normal; src: url('"+y[g].fPath+"');}",h.appendChild(q)}}else if(y[g].fOrigin==="g"||y[g].origin===1){n=document.querySelectorAll('link[f-forigin="g"], link[f-origin="1"]');for(B=0;BA){if(this.isInRange!==!0)this.globalData._mdf=!0,this._mdf=!0,this.isInRange=!0,this.show()}else if(this.isInRange!==!1)this.globalData._mdf=!0,this.isInRange=!1,this.hide()},renderRenderable:function(){var A,Q=this.renderableComponents.length;for(A=0;A0.1)this.audio.seek(this._currentTime/this.globalData.frameRate)}},AudioElement.prototype.show=function(){},AudioElement.prototype.hide=function(){this.audio.pause(),this._isPlaying=!1},AudioElement.prototype.pause=function(){this.audio.pause(),this._isPlaying=!1,this._canPlay=!1},AudioElement.prototype.resume=function(){this._canPlay=!0},AudioElement.prototype.setRate=function(A){this.audio.rate(A)},AudioElement.prototype.volume=function(A){this._volumeMultiplier=A,this._previousVolume=A*this._volume,this.audio.volume(this._previousVolume)},AudioElement.prototype.getBaseElement=function(){return null},AudioElement.prototype.destroy=function(){},AudioElement.prototype.sourceRectAtTime=function(){},AudioElement.prototype.initExpressions=function(){},BaseRenderer.prototype.checkLayers=function(A){var Q,J=this.layers.length,K;this.completeLayers=!0;for(Q=J-1;Q>=0;Q-=1){if(!this.elements[Q]){if(K=this.layers[Q],K.ip-K.st<=A-this.layers[Q].st&&K.op-K.st>A-this.layers[Q].st)this.buildItem(Q)}this.completeLayers=this.elements[Q]?this.completeLayers:!1}this.checkPendingElements()},BaseRenderer.prototype.createItem=function(A){switch(A.ty){case 2:return this.createImage(A);case 0:return this.createComp(A);case 1:return this.createSolid(A);case 3:return this.createNull(A);case 4:return this.createShape(A);case 5:return this.createText(A);case 6:return this.createAudio(A);case 13:return this.createCamera(A);case 15:return this.createFootage(A);default:return this.createNull(A)}},BaseRenderer.prototype.createCamera=function(){throw new Error("You're using a 3d camera. Try the html renderer.")},BaseRenderer.prototype.createAudio=function(A){return new AudioElement(A,this.globalData,this)},BaseRenderer.prototype.createFootage=function(A){return new FootageElement(A,this.globalData,this)},BaseRenderer.prototype.buildAllItems=function(){var A,Q=this.layers.length;for(A=0;A1)K+=" C"+Q.o[C-1][0]+","+Q.o[C-1][1]+" "+Q.i[0][0]+","+Q.i[0][1]+" "+Q.v[0][0]+","+Q.v[0][1];if(J.lastPath!==K){var Y="";if(J.elem){if(Q.c)Y=A.inv?this.solidPath+K:K;J.elem.setAttribute("d",Y)}J.lastPath=K}},MaskElement.prototype.destroy=function(){this.element=null,this.globalData=null,this.maskElement=null,this.data=null,this.masksProperties=null};let filtersFactory=function(){var A={};A.createFilter=Q,A.createAlphaToLuminanceFilter=J;function Q(K,C){var U=createNS("filter");if(U.setAttribute("id",K),C!==!0)U.setAttribute("filterUnits","objectBoundingBox"),U.setAttribute("x","0%"),U.setAttribute("y","0%"),U.setAttribute("width","100%"),U.setAttribute("height","100%");return U}function J(){var K=createNS("feColorMatrix");return K.setAttribute("type","matrix"),K.setAttribute("color-interpolation-filters","sRGB"),K.setAttribute("values","0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1"),K}return A}(),featureSupport=function(){var A={maskType:!0};if(/MSIE 10/i.test(navigator.userAgent)||/MSIE 9/i.test(navigator.userAgent)||/rv:11.0/i.test(navigator.userAgent)||/Edge\/\d./i.test(navigator.userAgent))A.maskType=!1;return A}();registeredEffects={},idPrefix="filter_result_",SVGEffects.prototype.renderFrame=function(A){var Q,J=this.filters.length;for(Q=0;Q=0;A-=1)if(J=this.shapeModifiers[A].processShapes(this._isFirstFrame),J)break},searchProcessedElement:function(A){var Q=this.processedElements,J=0,K=Q.length;while(J0.01)return!1;J+=1}return!0},GradientProperty.prototype.checkCollapsable=function(){if(this.o.length/2!==this.c.length/4)return!1;if(this.data.k.k[0].s){var A=0,Q=this.data.k.k.length;while(A0)L=I.transformers[d].mProps._mdf||L,u-=1,d-=1;if(L){u=h-I.styles[M].lvl,d=I.transformers.length-1;while(u>0)f=I.transformers[d].mProps.v.props,g.transform(f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7],f[8],f[9],f[10],f[11],f[12],f[13],f[14],f[15]),u-=1,d-=1}}else g=A;if(y=I.sh.paths,V=y._length,L){D="";for(F=0;F=1)q=0.99;else if(q<=-1)q=-0.99;var P=n*q,O=Math.cos(B+I.a.v)*P+D[0],w=Math.sin(B+I.a.v)*P+D[1];if(F.setAttribute("fx",O),F.setAttribute("fy",w),V&&!I.g._collapsable)I.of.setAttribute("fx",O),I.of.setAttribute("fy",w)}}}function H($,I,N){var{style:F,d:V}=I;if(V&&(V._mdf||N)&&V.dashStr)F.pElem.setAttribute("stroke-dasharray",V.dashStr),F.pElem.setAttribute("stroke-dashoffset",V.dashoffset[0]);if(I.c&&(I.c._mdf||N))F.pElem.setAttribute("stroke","rgb("+bmFloor(I.c.v[0])+","+bmFloor(I.c.v[1])+","+bmFloor(I.c.v[2])+")");if(I.o._mdf||N)F.pElem.setAttribute("stroke-opacity",I.o.v);if(I.w._mdf||N){if(F.pElem.setAttribute("stroke-width",I.w.v),F.msElem)F.msElem.setAttribute("stroke-width",I.w.v)}}return J}();extendPrototype([BaseElement,TransformElement,SVGBaseElement,IShapeElement,HierarchyElement,FrameElement,RenderableDOMElement],SVGShapeElement),SVGShapeElement.prototype.initSecondaryElement=function(){},SVGShapeElement.prototype.identityMatrix=new Matrix,SVGShapeElement.prototype.buildExpressionInterface=function(){},SVGShapeElement.prototype.createContent=function(){this.searchShapes(this.shapesData,this.itemsData,this.prevViewData,this.layerElement,0,[],!0),this.filterUniqueShapes()},SVGShapeElement.prototype.filterUniqueShapes=function(){var A,Q=this.shapes.length,J,K,C=this.stylesList.length,U,Y=[],Z=!1;for(K=0;K1&&Z)this.setShapesAsAnimated(Y)}},SVGShapeElement.prototype.setShapesAsAnimated=function(A){var Q,J=A.length;for(Q=0;Q=0;X-=1){if(D=this.searchProcessedElement(A[X]),!D)A[X]._render=Y;else Q[X]=J[D-1];if(A[X].ty==="fl"||A[X].ty==="st"||A[X].ty==="gf"||A[X].ty==="gs"||A[X].ty==="no"){if(!D)Q[X]=this.createStyleElement(A[X],C);else Q[X].style.closed=!1;if(A[X]._render){if(Q[X].style.pElem.parentNode!==K)K.appendChild(Q[X].style.pElem)}I.push(Q[X].style)}else if(A[X].ty==="gr"){if(!D)Q[X]=this.createGroupElement(A[X]);else{$=Q[X].it.length;for(H=0;H<$;H+=1)Q[X].prevViewData[H]=Q[X].it[H]}if(this.searchShapes(A[X].it,Q[X].it,Q[X].prevViewData,Q[X].gr,C+1,Z,Y),A[X]._render){if(Q[X].gr.parentNode!==K)K.appendChild(Q[X].gr)}}else if(A[X].ty==="tr"){if(!D)Q[X]=this.createTransformElement(A[X],K);F=Q[X].transform,Z.push(F)}else if(A[X].ty==="sh"||A[X].ty==="rc"||A[X].ty==="el"||A[X].ty==="sr"){if(!D)Q[X]=this.createShapeElement(A[X],Z,C);this.setElementStyles(Q[X])}else if(A[X].ty==="tm"||A[X].ty==="rd"||A[X].ty==="ms"||A[X].ty==="pb"){if(!D)V=ShapeModifiers.getModifier(A[X].ty),V.init(this,A[X]),Q[X]=V,this.shapeModifiers.push(V);else V=Q[X],V.closed=!1;N.push(V)}else if(A[X].ty==="rp"){if(!D)V=ShapeModifiers.getModifier(A[X].ty),Q[X]=V,V.init(this,A,X,Q),this.shapeModifiers.push(V),Y=!1;else V=Q[X],V.closed=!0;N.push(V)}this.addProcessedElement(A[X],X+1)}E=I.length;for(X=0;X1,this.kf)this.addEffect(this.getKeyframeValue.bind(this));return this.kf},TextProperty.prototype.addEffect=function(A){this.effectsSequence.push(A),this.elem.addDynamicProperty(this)},TextProperty.prototype.getValue=function(A){if((this.elem.globalData.frameId===this.frameId||!this.effectsSequence.length)&&!A)return;this.currentData.t=this.data.d.k[this.keysIndex].s.t;var Q=this.currentData,J=this.keysIndex;if(this.lock){this.setCurrentData(this.currentData);return}this.lock=!0,this._mdf=!1;var K,C=this.effectsSequence.length,U=A||this.data.d.k[this.keysIndex].s;for(K=0;KQ)break;J+=1}if(this.keysIndex!==J)this.keysIndex=J;return this.data.d.k[this.keysIndex].s},TextProperty.prototype.buildFinalText=function(A){var Q=[],J=0,K=A.length,C,U,Y=!1;while(J=55296&&C<=56319)if(U=A.charCodeAt(J+1),U>=56320&&U<=57343){if(Y||FontManager.isModifier(C,U))Q[Q.length-1]+=A.substr(J,2),Y=!1;else Q.push(A.substr(J,2));J+=1}else Q.push(A.charAt(J));else if(C>56319)if(U=A.charCodeAt(J+1),FontManager.isZeroWidthJoiner(C,U))Y=!0,Q[Q.length-1]+=A.substr(J,2),J+=1;else Q.push(A.charAt(J));else if(FontManager.isZeroWidthJoiner(C))Q[Q.length-1]+=A.charAt(J),Y=!0;else Q.push(A.charAt(J));J+=1}return Q},TextProperty.prototype.completeTextData=function(A){A.__complete=!0;var Q=this.elem.globalData.fontManager,J=this.data,K=[],C,U,Y,Z=0,X,E=J.m.g,H=0,$=0,I=0,N=[],F=0,V=0,D,L,R=Q.getFontByName(A.f),M,T=0,h=getFontProperties(R);A.fWeight=h.weight,A.fStyle=h.style,A.finalSize=A.s,A.finalText=this.buildFinalText(A.t),U=A.finalText.length,A.finalLineHeight=A.lh;var y=A.tr/1000*A.finalSize,g;if(A.sz){var f=!0,u=A.sz[0],d=A.sz[1],n,B;while(f){B=this.buildFinalText(A.t),n=0,F=0,U=B.length,y=A.tr/1000*A.finalSize;var q=-1;for(C=0;Cu&&B[C]!==" "){if(q===-1)U+=1;else C=q;n+=A.finalLineHeight||A.finalSize*1.2,B.splice(C,q===C?1:0,"\r"),q=-1,F=0}else F+=T,F+=y}if(n+=R.ascent*A.finalSize/100,this.canResize&&A.finalSize>this.minimumFontSize&&dV?F:V,F=-2*y,X="",Y=!0,I+=1;else X=O;if(Q.chars)M=Q.getCharData(O,R.fStyle,Q.getFontByName(A.f).fFamily),T=Y?0:M.w*A.finalSize/100;else T=Q.measureText(X,A.f,A.finalSize);if(O===" ")P+=T+y;else F+=T+y+P,P=0;if(K.push({l:T,an:T,add:H,n:Y,anIndexes:[],val:X,line:I,animatorJustifyOffset:0}),E==2){if(H+=T,X===""||X===" "||C===U-1){if(X===""||X===" ")H-=T;while($<=C)K[$].an=H,K[$].ind=Z,K[$].extra=T,$+=1;Z+=1,H=0}}else if(E==3){if(H+=T,X===""||C===U-1){if(X==="")H-=T;while($<=C)K[$].an=H,K[$].ind=Z,K[$].extra=T,$+=1;H=0,Z+=1}}else K[Z].ind=Z,K[Z].extra=0,Z+=1}if(A.l=K,V=F>V?F:V,N.push(F),A.sz)A.boxWidth=A.sz[0],A.justifyOffset=0;else switch(A.boxWidth=V,A.j){case 1:A.justifyOffset=-A.boxWidth;break;case 2:A.justifyOffset=-A.boxWidth/2;break;default:A.justifyOffset=0}A.lineWidths=N;var w=J.a,k,S;L=w.length;var _,W,j=[];for(D=0;D0)Y=this.ne.v/100;else Z=-this.ne.v/100;if(this.xe.v>0)X=1-this.xe.v/100;else E=1+this.xe.v/100;var H=BezierFactory.getBezierEasing(Y,Z,X,E).get,$=0,I=this.finalS,N=this.finalE,F=this.data.sh;if(F===2){if(N===I)$=U>=N?1:0;else $=A(0,Q(0.5/(N-I)+(U-I)/(N-I),1));$=H($)}else if(F===3){if(N===I)$=U>=N?0:1;else $=1-A(0,Q(0.5/(N-I)+(U-I)/(N-I),1));$=H($)}else if(F===4){if(N===I)$=0;else if($=A(0,Q(0.5/(N-I)+(U-I)/(N-I),1)),$<0.5)$*=2;else $=1-2*($-0.5);$=H($)}else if(F===5){if(N===I)$=0;else{var V=N-I;U=Q(A(0,U+0.5-I),N-I);var D=-V/2+U,L=V/2;$=Math.sqrt(1-D*D/(L*L))}$=H($)}else if(F===6){if(N===I)$=0;else U=Q(A(0,U+0.5-I),N-I),$=(1+Math.cos(Math.PI+Math.PI*2*U/(N-I)))/2;$=H($)}else{if(U>=J(I))if(U-I<0)$=A(0,Q(Q(N,1)-(I-U),1));else $=A(0,Q(N-U,1));$=H($)}if(this.sm.v!==100){var R=this.sm.v*0.01;if(R===0)R=0.00000001;var M=0.5-R*0.5;if($1)$=1}return $*this.a.v},getValue:function(U){if(this.iterateDynamicProperties(),this._mdf=U||this._mdf,this._currentTextLength=this.elem.textProperty.currentData.l.length||0,U&&this.data.r===2)this.e.v=this._currentTextLength;var Y=this.data.r===2?1:100/this.data.totalChars,Z=this.o.v/Y,X=this.s.v/Y+Z,E=this.e.v/Y+Z;if(X>E){var H=X;X=E,E=H}this.finalS=X,this.finalE=E}},extendPrototype([DynamicPropertyContainer],K);function C(U,Y,Z){return new K(U,Y,Z)}return{getTextSelectorProp:C}}();TextAnimatorProperty.prototype.searchProperties=function(){var A,Q=this._textData.a.length,J,K=PropertyFactory.getProp;for(A=0;A=F+w1||!h)u=(F+w1-D)/V.partialLength,s=T.point[0]+(V.point[0]-T.point[0])*u,r=T.point[1]+(V.point[1]-T.point[1])*u,U.translate(-J[0]*I[H].an*0.005,-(J[1]*P)*0.01),L=!1;else if(h){if(D+=V.partialLength,R+=1,R>=h.length)if(R=0,M+=1,!y[M])if(n.v.c)R=0,M=0,h=y[M].points;else D-=V.partialLength,h=null;else h=y[M].points;if(h)T=V,V=h[R],g=V.partialLength}p=I[H].an/2-I[H].add,U.translate(-p,0,0)}else p=I[H].an/2-I[H].add,U.translate(-p,0,0),U.translate(-J[0]*I[H].an*0.005,-J[1]*P*0.01,0);for(S=0;S<_;S+=1)if(w=K[S].a,w.t.propType){if(k=K[S].s,j=k.getMult(I[H].anIndexes[S],C.a[S].s.totalChars),X!==0||A.j!==0)if(this._hasMaskedPath)if(j.length)F+=w.t.v*j[0];else F+=w.t.v*j;else if(j.length)X+=w.t.v*j[0];else X+=w.t.v*j}if(A.strokeWidthAnim)E1=A.sw||0;if(A.strokeColorAnim)if(A.sc)O1=[A.sc[0],A.sc[1],A.sc[2]];else O1=[0,0,0];if(A.fillColorAnim&&A.fc)Y1=[A.fc[0],A.fc[1],A.fc[2]];for(S=0;S<_;S+=1)if(w=K[S].a,w.a.propType)if(k=K[S].s,j=k.getMult(I[H].anIndexes[S],C.a[S].s.totalChars),j.length)U.translate(-w.a.v[0]*j[0],-w.a.v[1]*j[1],w.a.v[2]*j[2]);else U.translate(-w.a.v[0]*j,-w.a.v[1]*j,w.a.v[2]*j);for(S=0;S<_;S+=1)if(w=K[S].a,w.s.propType)if(k=K[S].s,j=k.getMult(I[H].anIndexes[S],C.a[S].s.totalChars),j.length)U.scale(1+(w.s.v[0]-1)*j[0],1+(w.s.v[1]-1)*j[1],1);else U.scale(1+(w.s.v[0]-1)*j,1+(w.s.v[1]-1)*j,1);for(S=0;S<_;S+=1){if(w=K[S].a,k=K[S].s,j=k.getMult(I[H].anIndexes[S],C.a[S].s.totalChars),w.sk.propType)if(j.length)U.skewFromAxis(-w.sk.v*j[0],w.sa.v*j[1]);else U.skewFromAxis(-w.sk.v*j,w.sa.v*j);if(w.r.propType)if(j.length)U.rotateZ(-w.r.v*j[2]);else U.rotateZ(-w.r.v*j);if(w.ry.propType)if(j.length)U.rotateY(w.ry.v*j[1]);else U.rotateY(w.ry.v*j);if(w.rx.propType)if(j.length)U.rotateX(w.rx.v*j[0]);else U.rotateX(w.rx.v*j);if(w.o.propType)if(j.length)U1+=(w.o.v*j[0]-U1)*j[0];else U1+=(w.o.v*j-U1)*j;if(A.strokeWidthAnim&&w.sw.propType)if(j.length)E1+=w.sw.v*j[0];else E1+=w.sw.v*j;if(A.strokeColorAnim&&w.sc.propType)for(i=0;i<3;i+=1)if(j.length)O1[i]+=(w.sc.v[i]-O1[i])*j[0];else O1[i]+=(w.sc.v[i]-O1[i])*j;if(A.fillColorAnim&&A.fc){if(w.fc.propType)for(i=0;i<3;i+=1)if(j.length)Y1[i]+=(w.fc.v[i]-Y1[i])*j[0];else Y1[i]+=(w.fc.v[i]-Y1[i])*j;if(w.fh.propType)if(j.length)Y1=addHueToRGB(Y1,w.fh.v*j[0]);else Y1=addHueToRGB(Y1,w.fh.v*j);if(w.fs.propType)if(j.length)Y1=addSaturationToRGB(Y1,w.fs.v*j[0]);else Y1=addSaturationToRGB(Y1,w.fs.v*j);if(w.fb.propType)if(j.length)Y1=addBrightnessToRGB(Y1,w.fb.v*j[0]);else Y1=addBrightnessToRGB(Y1,w.fb.v*j)}}for(S=0;S<_;S+=1)if(w=K[S].a,w.p.propType)if(k=K[S].s,j=k.getMult(I[H].anIndexes[S],C.a[S].s.totalChars),this._hasMaskedPath)if(j.length)U.translate(0,w.p.v[1]*j[0],-w.p.v[2]*j[1]);else U.translate(0,w.p.v[1]*j,-w.p.v[2]*j);else if(j.length)U.translate(w.p.v[0]*j[0],w.p.v[1]*j[1],-w.p.v[2]*j[2]);else U.translate(w.p.v[0]*j,w.p.v[1]*j,-w.p.v[2]*j);if(A.strokeWidthAnim)c=E1<0?0:E1;if(A.strokeColorAnim)o="rgb("+Math.round(O1[0]*255)+","+Math.round(O1[1]*255)+","+Math.round(O1[2]*255)+")";if(A.fillColorAnim&&A.fc)C1="rgb("+Math.round(Y1[0]*255)+","+Math.round(Y1[1]*255)+","+Math.round(Y1[2]*255)+")";if(this._hasMaskedPath){if(U.translate(0,-A.ls),U.translate(0,J[1]*P*0.01+E,0),this._pathData.p.v){d=(V.point[1]-T.point[1])/(V.point[0]-T.point[0]);var G=Math.atan(d)*180/Math.PI;if(V.point[0]A?this.textSpans[A].span:createNS(Z?"g":"text"),M<=A){if(X.setAttribute("stroke-linecap","butt"),X.setAttribute("stroke-linejoin","round"),X.setAttribute("stroke-miterlimit","4"),this.textSpans[A].span=X,Z){var h=createNS("g");X.appendChild(h),this.textSpans[A].childSpan=h}this.textSpans[A].span=X,this.layerElement.appendChild(X)}X.style.display="inherit"}if(E.reset(),$){if(Y[A].n)I=-V,N+=J.yOffset,N+=F?1:0,F=!1;this.applyTextPropertiesToMatrix(J,E,Y[A].line,I,N),I+=Y[A].l||0,I+=V}if(Z){T=this.globalData.fontManager.getCharData(J.finalText[A],K.fStyle,this.globalData.fontManager.getFontByName(J.f).fFamily);var y;if(T.t===1)y=new SVGCompElement(T.data,this.globalData,this);else{var g=emptyShapeData;if(T.data&&T.data.shapes)g=this.buildShapeData(T.data,J.finalSize);y=new SVGShapeElement(g,this.globalData,this)}if(this.textSpans[A].glyph){var f=this.textSpans[A].glyph;this.textSpans[A].childSpan.removeChild(f.layerElement),f.destroy()}if(this.textSpans[A].glyph=y,y._debug=!0,y.prepareFrame(0),y.renderFrame(),this.textSpans[A].childSpan.appendChild(y.layerElement),T.t===1)this.textSpans[A].childSpan.setAttribute("transform","scale("+J.finalSize/100+","+J.finalSize/100+")")}else{if($)X.setAttribute("transform","translate("+E.props[12]+","+E.props[13]+")");X.textContent=Y[A].val,X.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve")}}if($&&X)X.setAttribute("d",H)}while(A=0;Q-=1)if(this.completeLayers||this.elements[Q])this.elements[Q].prepareFrame(A-this.layers[Q].st);if(this.globalData._mdf){for(Q=0;Q=0;J-=1)if(this.completeLayers||this.elements[J]){if(this.elements[J].prepareFrame(this.renderedFrame-this.layers[J].st),this.elements[J]._mdf)this._mdf=!0}},ICompElement.prototype.renderInnerContent=function(){var A,Q=this.layers.length;for(A=0;A=0;J-=1)U=A.transforms[J].transform.mProps.v.props,A.finalTransform.transform(U[0],U[1],U[2],U[3],U[4],U[5],U[6],U[7],U[8],U[9],U[10],U[11],U[12],U[13],U[14],U[15])}A._mdf=C},processSequences:function(A){var Q,J=this.sequenceList.length;for(Q=0;Q=0;U-=1){if($=this.searchProcessedElement(A[U]),!$)A[U]._shouldRender=K;else Q[U]=J[$-1];if(A[U].ty==="fl"||A[U].ty==="st"||A[U].ty==="gf"||A[U].ty==="gs"){if(!$)Q[U]=this.createStyleElement(A[U],F);else Q[U].style.closed=!1;E.push(Q[U].style)}else if(A[U].ty==="gr"){if(!$)Q[U]=this.createGroupElement(A[U]);else{X=Q[U].it.length;for(Z=0;Z=0;C-=1)if(Q[C].ty==="tr")Y=J[C].transform,this.renderShapeTransform(A,Y);else if(Q[C].ty==="sh"||Q[C].ty==="el"||Q[C].ty==="rc"||Q[C].ty==="sr")this.renderPath(Q[C],J[C]);else if(Q[C].ty==="fl")this.renderFill(Q[C],J[C],Y);else if(Q[C].ty==="st")this.renderStroke(Q[C],J[C],Y);else if(Q[C].ty==="gf"||Q[C].ty==="gs")this.renderGradientFill(Q[C],J[C],Y);else if(Q[C].ty==="gr")this.renderShape(Y,Q[C].it,J[C].it);else if(Q[C].ty==="tm");if(K)this.drawLayer()},CVShapeElement.prototype.renderStyledShape=function(A,Q){if(this._isFirstFrame||Q._mdf||A.transforms._mdf){var J=A.trNodes,K=Q.paths,C,U,Y,Z=K._length;J.length=0;var X=A.transforms.finalTransform;for(Y=0;Y=1)H=0.99;else if(H<=-1)H=-0.99;var $=X*H,I=Math.cos(E+Q.a.v)*$+Y[0],N=Math.sin(E+Q.a.v)*$+Y[1];C=U.createRadialGradient(I,N,0,Y[0],Y[1],X)}var F,V=A.g.p,D=Q.g.c,L=1;for(F=0;FU&&X==="xMidYMid slice"||CJ&&U==="meet"||KJ&&U==="slice"))this.transformCanvas.tx=(A-this.transformCanvas.w*(Q/this.transformCanvas.h))/2*this.renderConfig.dpr;else if(Z==="xMax"&&(KJ&&U==="slice"))this.transformCanvas.tx=(A-this.transformCanvas.w*(Q/this.transformCanvas.h))*this.renderConfig.dpr;else this.transformCanvas.tx=0;if(X==="YMid"&&(K>J&&U==="meet"||KJ&&U==="meet"||K=0;A-=1)if(this.elements[A])this.elements[A].destroy();this.elements.length=0,this.globalData.canvasContext=null,this.animationItem.container=null,this.destroyed=!0},CanvasRendererBase.prototype.renderFrame=function(A,Q){if(this.renderedFrame===A&&this.renderConfig.clearCanvas===!0&&!Q||this.destroyed||A===-1)return;this.renderedFrame=A,this.globalData.frameNum=A-this.animationItem._isFirstFrame,this.globalData.frameId+=1,this.globalData._mdf=!this.renderConfig.clearCanvas||Q,this.globalData.projectInterface.currentFrame=A;var J,K=this.layers.length;if(!this.completeLayers)this.checkLayers(A);for(J=0;J=0;J-=1)if(this.completeLayers||this.elements[J])this.elements[J].renderFrame();if(this.renderConfig.clearCanvas!==!0)this.restore()}},CanvasRendererBase.prototype.buildItem=function(A){var Q=this.elements;if(Q[A]||this.layers[A].ty===99)return;var J=this.createItem(this.layers[A],this,this.globalData);Q[A]=J,J.initExpressions()},CanvasRendererBase.prototype.checkPendingElements=function(){while(this.pendingElements.length){var A=this.pendingElements.pop();A.checkParenting()}},CanvasRendererBase.prototype.hide=function(){this.animationItem.container.style.display="none"},CanvasRendererBase.prototype.show=function(){this.animationItem.container.style.display="block"},extendPrototype([CanvasRendererBase,ICompElement,CVBaseElement],CVCompElement),CVCompElement.prototype.renderInnerContent=function(){var A=this.canvasContext;A.beginPath(),A.moveTo(0,0),A.lineTo(this.data.w,0),A.lineTo(this.data.w,this.data.h),A.lineTo(0,this.data.h),A.lineTo(0,0),A.clip();var Q,J=this.layers.length;for(Q=J-1;Q>=0;Q-=1)if(this.completeLayers||this.elements[Q])this.elements[Q].renderFrame()},CVCompElement.prototype.destroy=function(){var A,Q=this.layers.length;for(A=Q-1;A>=0;A-=1)if(this.elements[A])this.elements[A].destroy();this.layers=null,this.elements=null},CVCompElement.prototype.createComp=function(A){return new CVCompElement(A,this.globalData,this)},extendPrototype([CanvasRendererBase],CanvasRenderer),CanvasRenderer.prototype.createComp=function(A){return new CVCompElement(A,this.globalData,this)},registerRenderer("canvas",CanvasRenderer),ShapeModifiers.registerModifier("tm",TrimModifier),ShapeModifiers.registerModifier("pb",PuckerAndBloatModifier),ShapeModifiers.registerModifier("rp",RepeaterModifier),ShapeModifiers.registerModifier("rd",RoundCornersModifier);let Expressions=function(){var A={};A.initExpressions=Q;function Q(J){var K=0,C=[];function U(){K+=1}function Y(){if(K-=1,K===0)X()}function Z(E){if(C.indexOf(E)===-1)C.push(E)}function X(){var E,H=C.length;for(E=0;EJ){var K=J;J=Q,Q=K}return Math.min(Math.max(A,Q),J)}function radiansToDegrees(A){return A/degToRads}var radians_to_degrees=radiansToDegrees;function degreesToRadians(A){return A*degToRads}var degrees_to_radians=radiansToDegrees,helperLengthArray=[0,0,0,0,0,0];function length(A,Q){if(typeof A==="number"||A instanceof Number)return Q=Q||0,Math.abs(A-Q);if(!Q)Q=helperLengthArray;var J,K=Math.min(A.length,Q.length),C=0;for(J=0;J0.5?E/(2-C-U):E/(C+U),C){case Q:Y=(J-K)/E+(J1)J-=1;if(J<0.16666666666666666)return A+(Q-A)*6*J;if(J<0.5)return Q;if(J<0.6666666666666666)return A+(Q-A)*(0.6666666666666666-J)*6;return A}function hslToRgb(A){var Q=A[0],J=A[1],K=A[2],C,U,Y;if(J===0)C=K,Y=K,U=K;else{var Z=K<0.5?K*(1+J):K+J-K*J,X=2*K-Z;C=hue2rgb(X,Z,Q+0.3333333333333333),U=hue2rgb(X,Z,Q),Y=hue2rgb(X,Z,Q-0.3333333333333333)}return[C,U,Y,A[3]]}function linear(A,Q,J,K,C){if(K===void 0||C===void 0)K=Q,C=J,Q=0,J=1;if(J=J)return C;var Y=J===Q?0:(A-Q)/(J-Q);if(!K.length)return K+(C-K)*Y;var Z,X=K.length,E=createTypedArray("float32",X);for(Z=0;Z1){for(C=0;C1)Q=1;else if(Q<0)Q=0;var Y=A(Q);if($bm_isInstanceOfArray(C)){var Z,X=C.length,E=createTypedArray("float32",X);for(Z=0;Zdata.k[Q].t&&Adata.k[Q+1].t-A)K=Q+2,C=data.k[Q+1].t;else K=Q+1,C=data.k[Q].t;break}if(K===-1)K=Q+1,C=data.k[Q].t}var U={};return U.index=K,U.time=C/elem.comp.globalData.frameRate,U}function key(A){var Q,J,K;if(!data.k.length||typeof data.k[0]==="number")throw new Error("The property has no keyframe at index "+A);A-=1,Q={time:data.k[A].t/elem.comp.globalData.frameRate,value:[]};var C=Object.prototype.hasOwnProperty.call(data.k[A],"s")?data.k[A].s:data.k[A-1].e;K=C.length;for(J=0;JMath.pow(Q/255*0.9478672986+0.0521327014,2.4));var gA={};gA.toRGBA8=function(A){var{width:Q,height:J}=A;if(A.tabs.acTL==null)return[gA.toRGBA8.decodeImage(A.data,Q,J,A).buffer];var K=[];if(A.frames[0].data==null)A.frames[0].data=A.data;var C=Q*J*4,U=new Uint8Array(C),Y=new Uint8Array(C),Z=new Uint8Array(C);for(var X=0;X>3)]>>7-((N&7)<<0)&1,n=3*d;Z[M]=T[n],Z[M+1]=T[n+1],Z[M+2]=T[n+2],Z[M+3]=d>2)]>>6-((N&3)<<1)&3,n=3*d;Z[M]=T[n],Z[M+1]=T[n+1],Z[M+2]=T[n+2],Z[M+3]=d>1)]>>4-((N&1)<<2)&15,n=3*d;Z[M]=T[n],Z[M+1]=T[n+1],Z[M+2]=T[n+2],Z[M+3]=d>>3)]>>>7-(w&7)&1),k=q==D*255?0:255;X[O+w]=k<<24|q<<16|q<<8|q}else if(H==2)for(var w=0;w>>2)]>>>6-((w&3)<<1)&3),k=q==D*85?0:255;X[O+w]=k<<24|q<<16|q<<8|q}else if(H==4)for(var w=0;w>>1)]>>>4-((w&1)<<2)&15),k=q==D*17?0:255;X[O+w]=k<<24|q<<16|q<<8|q}else if(H==8)for(var w=0;w>>2<<5);while(C==0){if(C=D(Q,I,1),U=D(Q,I+1,2),I+=3,U==0){if((I&7)!=0)I+=8-(I&7);var f=(I>>>3)+4,u=Q[f-4]|Q[f-3]<<8;if(g)J=A.H.W(J,$+u);J.set(new K(Q.buffer,Q.byteOffset+f,u),$),I=f+u<<3,$+=u;continue}if(g)J=A.H.W(J,$+131072);if(U==1)N=y.J,F=y.h,E=511,H=31;if(U==2){Y=L(Q,I,5)+257,Z=L(Q,I+5,5)+1,X=L(Q,I+10,4)+4,I+=14;var d=1;for(var n=0;n<38;n+=2)y.Q[n]=0,y.Q[n+1]=0;for(var n=0;nd)d=B}I+=3*X,M(y.Q,d),T(y.Q,d,y.u),N=y.w,F=y.d,I=R(y.u,(1<>>4;if(w>>>8==0)J[$++]=w;else if(w==256)break;else{var k=$+w-254;if(w>264){var S=y.q[w-257];k=$+(S>>>3)+L(Q,I,S&7),I+=S&7}var _=F[h(Q,I)&H];I+=_&15;var W=_>>>4,j=y.c[W],b=(j>>>4)+D(Q,I,j&15);I+=j&15;while($>>4;if($<=15)Y[E]=$,E++;else{var I=0,N=0;if($==16)N=3+Z(C,U,2),U+=2,I=Y[E-1];else if($==17)N=3+Z(C,U,3),U+=3;else if($==18)N=11+Z(C,U,7),U+=7;var F=E+N;while(E>>1;while(YU)U=X;Y++}while(Y>1,E=Q[Z+1],H=X<<4|E,$=J-E,I=Q[Z]<<$,N=I+(1<<$);while(I!=N){var F=Y[I]>>>15-J;K[F]=H,I++}}},A.H.l=function(Q,J){var K=A.H.m.r,C=15-J;for(var U=0;U>>C}},A.H.M=function(Q,J,K){K=K<<(J&7);var C=J>>>3;Q[C]|=K,Q[C+1]|=K>>>8},A.H.I=function(Q,J,K){K=K<<(J&7);var C=J>>>3;Q[C]|=K,Q[C+1]|=K>>>8,Q[C+2]|=K>>>16},A.H.e=function(Q,J,K){return(Q[J>>>3]|Q[(J>>>3)+1]<<8)>>>(J&7)&(1<>>3]|Q[(J>>>3)+1]<<8|Q[(J>>>3)+2]<<16)>>>(J&7)&(1<>>3]|Q[(J>>>3)+1]<<8|Q[(J>>>3)+2]<<16)>>>(J&7)},A.H.i=function(Q,J){return(Q[J>>>3]|Q[(J>>>3)+1]<<8|Q[(J>>>3)+2]<<16|Q[(J>>>3)+3]<<24)>>>(J&7)},A.H.m=function(){var Q=Uint16Array,J=Uint32Array;return{K:new Q(16),j:new Q(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[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,999,999,999],T:[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,0,0,0],q:new Q(32),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,65535,65535],z:[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,0,0],c:new J(32),J:new Q(512),_:[],h:new Q(32),$:[],w:new Q(32768),C:[],v:[],d:new Q(32768),D:[],u:new Q(512),Q:[],r:new Q(32768),s:new J(286),Y:new J(30),a:new J(19),t:new J(15000),k:new Q(65536),g:new Q(32768)}}(),function(){var Q=A.H.m,J=32768;for(var K=0;K>>1|(C&1431655765)<<1,C=(C&3435973836)>>>2|(C&858993459)<<2,C=(C&4042322160)>>>4|(C&252645135)<<4,C=(C&4278255360)>>>8|(C&16711935)<<8,Q.r[K]=(C>>>16|C<<16)>>>17}function U(Y,Z,X){while(Z--!=0)Y.push(0,X)}for(var K=0;K<32;K++)Q.q[K]=Q.S[K]<<3|Q.T[K],Q.c[K]=Q.p[K]<<4|Q.z[K];U(Q._,144,8),U(Q._,112,9),U(Q._,24,7),U(Q._,8,8),A.H.n(Q._,9),A.H.A(Q._,9,Q.J),A.H.l(Q._,9),U(Q.$,32,5),A.H.n(Q.$,5),A.H.A(Q.$,5,Q.h),A.H.l(Q.$,5),U(Q.Q,19,0),U(Q.C,286,0),U(Q.D,30,0),U(Q.v,320,0)}(),A.H.N}();gA.decode._readInterlace=function(A,Q){var{width:J,height:K}=Q,C=gA.decode._getBPP(Q),U=C>>3,Y=Math.ceil(J*C/8),Z=new Uint8Array(K*Y),X=0,E=[0,0,4,0,2,0,1],H=[0,4,0,2,0,1,0],$=[8,8,8,4,4,2,2],I=[8,8,4,4,2,2,1],N=0;while(N<7){var F=$[N],V=I[N],D=0,L=0,R=E[N];while(R>3],g=g>>7-(u&7)&1,Z[y*Y+(f>>3)]|=g<<7-((f&7)<<0);if(C==2)g=A[u>>3],g=g>>6-(u&7)&3,Z[y*Y+(f>>2)]|=g<<6-((f&3)<<1);if(C==4)g=A[u>>3],g=g>>4-(u&7)&15,Z[y*Y+(f>>1)]|=g<<4-((f&1)<<2);if(C>=8){var d=y*Y+f*U;for(var n=0;n>3)+n]}u+=C,f+=V}h++,y+=F}if(D*L!=0)X+=L*(1+T);N=N+1}return Z};gA.decode._getBPP=function(A){var Q=[1,null,3,1,2,null,4][A.ctype];return Q*A.depth};gA.decode._filterZero=function(A,Q,J,K,C){var U=gA.decode._getBPP(Q),Y=Math.ceil(K*U/8),Z=gA.decode._paeth;U=Math.ceil(U/8);var X,E,H=A[J],$=0;if(H>1)A[J]=[0,0,1][H-2];if(H==3)for($=U;$>>1)&255;for(var I=0;I>>1);for(;$>>1)}else{for(;$>8&255,A[Q+1]=J&255},readUint:function(A,Q){return A[Q]*16777216+(A[Q+1]<<16|A[Q+2]<<8|A[Q+3])},writeUint:function(A,Q,J){A[Q]=J>>24&255,A[Q+1]=J>>16&255,A[Q+2]=J>>8&255,A[Q+3]=J&255},readASCII:function(A,Q,J){var K="";for(var C=0;C=0&&Z>=0)$=N*Q+F<<2,I=(Z+N)*C+Y+F<<2;else $=(-Z+N)*Q-Y+F<<2,I=N*C+F<<2;if(X==0)K[I]=A[$],K[I+1]=A[$+1],K[I+2]=A[$+2],K[I+3]=A[$+3];else if(X==1){var V=A[$+3]*0.00392156862745098,D=A[$]*V,L=A[$+1]*V,R=A[$+2]*V,M=K[I+3]*0.00392156862745098,T=K[I]*M,h=K[I+1]*M,y=K[I+2]*M,g=1-V,f=V+M*g,u=f==0?0:1/f;K[I+3]=255*f,K[I+0]=(D+T*g)*u,K[I+1]=(L+h*g)*u,K[I+2]=(R+y*g)*u}else if(X==2){var V=A[$+3],D=A[$],L=A[$+1],R=A[$+2],M=K[I+3],T=K[I],h=K[I+1],y=K[I+2];if(V==M&&D==T&&L==h&&R==y)K[I]=0,K[I+1]=0,K[I+2]=0,K[I+3]=0;else K[I]=D,K[I+1]=L,K[I+2]=R,K[I+3]=V}else if(X==3){var V=A[$+3],D=A[$],L=A[$+1],R=A[$+2],M=K[I+3],T=K[I],h=K[I+1],y=K[I+2];if(V==M&&D==T&&L==h&&R==y)continue;if(V<220&&M>20)return!1}}return!0};var C0={};(function(){var A=function U(){function Y(Z){this.message="JPEG error: "+Z}return Y.prototype=new Error,Y.prototype.name="JpegError",Y.constructor=Y,Y}(),Q=function U(){var Y=new Uint8Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),Z=4017,X=799,E=3406,H=2276,$=1567,I=3784,N=5793,F=2896;function V(y){if(y==null)y={};if(y.w==null)y.w=-1;this.V=y.n,this.N=y.w}function D(y,g){var f=0,u=[],d,n,B=16,q;while(B>0&&!y[B-1])B--;u.push({children:[],index:0});var P=u[0];for(d=0;d0)P=u.pop();P.index++,u.push(P);while(u.length<=d)u.push(q={children:[],index:0}),P.children[P.index]=q.children,P=q;f++}if(d+10)return W--,_>>W&1;if(_=y[g++],_===255){var m=y[g++];if(m){if(m===220&&O){g+=2;var l=K(y,g);if(g+=2,l>0&&l!==f.s)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",l)}else if(m===217){if(O){var a=s*8;if(a>0&&a>>7}function C1(m){var l=m;while(!0){switch(l=l[o()],typeof l){case"number":return l;case"object":continue}throw new A("invalid huffman sequence")}}function q1(m){var l=0;while(m>0)l=l<<1|o(),m--;return l}function Z1(m){if(m===1)return o()===1?1:-1;var l=q1(m);if(l>=1<>4;if(X1===0){if(W1<15)break;F1+=16;continue}F1+=W1;var $1=Y[F1];m.D[l+$1]=Z1(X1),F1++}}function H1(m,l){var a=C1(m.J),K1=a===0?0:Z1(a)<0){j--;return}var a=n,K1=B;while(a<=K1){var F1=C1(m.i),R1=F1&15,X1=F1>>4;if(R1===0){if(X1<15){j=q1(X1)+(1<>4,R1===0)if(F1<15)j=q1(F1)+(1<0){for(A1=0;A10?"unexpected":"excessive";g=E1.offset}if(E1.M>=65488&&E1.M<=65495)g+=2;else break}return g-S}function M(y,g,f){var{$:u,D:d}=y,n,B,q,P,O,w,k,S,_,W,j,b,p,s,r,A1,Q1;if(!u)throw new A("missing required Quantization Table.");for(var e=0;e<64;e+=8){if(_=d[g+e],W=d[g+e+1],j=d[g+e+2],b=d[g+e+3],p=d[g+e+4],s=d[g+e+5],r=d[g+e+6],A1=d[g+e+7],_*=u[e],(W|j|b|p|s|r|A1)===0){Q1=N*_+512>>10,f[e]=Q1,f[e+1]=Q1,f[e+2]=Q1,f[e+3]=Q1,f[e+4]=Q1,f[e+5]=Q1,f[e+6]=Q1,f[e+7]=Q1;continue}W*=u[e+1],j*=u[e+2],b*=u[e+3],p*=u[e+4],s*=u[e+5],r*=u[e+6],A1*=u[e+7],n=N*_+128>>8,B=N*p+128>>8,q=j,P=r,O=F*(W-A1)+128>>8,S=F*(W+A1)+128>>8,w=b<<4,k=s<<4,n=n+B+1>>1,B=n-B,Q1=q*I+P*$+128>>8,q=q*$-P*I+128>>8,P=Q1,O=O+k+1>>1,k=O-k,S=S+w+1>>1,w=S-w,n=n+P+1>>1,P=n-P,B=B+q+1>>1,q=B-q,Q1=O*H+S*E+2048>>12,O=O*E-S*H+2048>>12,S=Q1,Q1=w*X+k*Z+2048>>12,w=w*Z-k*X+2048>>12,k=Q1,f[e]=n+S,f[e+7]=n-S,f[e+1]=B+k,f[e+6]=B-k,f[e+2]=q+w,f[e+5]=q-w,f[e+3]=P+O,f[e+4]=P-O}for(var t=0;t<8;++t){if(_=f[t],W=f[t+8],j=f[t+16],b=f[t+24],p=f[t+32],s=f[t+40],r=f[t+48],A1=f[t+56],(W|j|b|p|s|r|A1)===0){if(Q1=N*_+8192>>14,Q1<-2040)Q1=0;else if(Q1>=2024)Q1=255;else Q1=Q1+2056>>4;d[g+t]=Q1,d[g+t+8]=Q1,d[g+t+16]=Q1,d[g+t+24]=Q1,d[g+t+32]=Q1,d[g+t+40]=Q1,d[g+t+48]=Q1,d[g+t+56]=Q1;continue}if(n=N*_+2048>>12,B=N*p+2048>>12,q=j,P=r,O=F*(W-A1)+2048>>12,S=F*(W+A1)+2048>>12,w=b,k=s,n=(n+B+1>>1)+4112,B=n-B,Q1=q*I+P*$+2048>>12,q=q*$-P*I+2048>>12,P=Q1,O=O+k+1>>1,k=O-k,S=S+w+1>>1,w=S-w,n=n+P+1>>1,P=n-P,B=B+q+1>>1,q=B-q,Q1=O*H+S*E+2048>>12,O=O*E-S*H+2048>>12,S=Q1,Q1=w*X+k*Z+2048>>12,w=w*Z-k*X+2048>>12,k=Q1,_=n+S,A1=n-S,W=B+k,r=B-k,j=q+w,s=q-w,b=P+O,p=P-O,_<16)_=0;else if(_>=4080)_=255;else _>>=4;if(W<16)W=0;else if(W>=4080)W=255;else W>>=4;if(j<16)j=0;else if(j>=4080)j=255;else j>>=4;if(b<16)b=0;else if(b>=4080)b=255;else b>>=4;if(p<16)p=0;else if(p>=4080)p=255;else p>>=4;if(s<16)s=0;else if(s>=4080)s=255;else s>>=4;if(r<16)r=0;else if(r>=4080)r=255;else r>>=4;if(A1<16)A1=0;else if(A1>=4080)A1=255;else A1>>=4;d[g+t]=_,d[g+t+8]=W,d[g+t+16]=j,d[g+t+24]=b,d[g+t+32]=p,d[g+t+40]=s,d[g+t+48]=r,d[g+t+56]=A1}}function T(y,g){var{P:f,c:u}=g,d=new Int16Array(64);for(var n=0;n=u)return null;var n=K(y,g);if(n>=65472&&n<=65534)return{u:null,M:n,offset:g};var B=K(y,d);while(!(B>=65472&&B<=65534)){if(++d>=u)return null;B=K(y,d)}return{u:n.toString(16),M:B,offset:d}}return V.prototype={parse(y,g){if(g==null)g={};var f=g.F,u=0,d=null,n=null,B,q,P=0;function O(){var X1=K(y,u);u+=2;var W1=u+X1-2,$1=h(y,W1,u);if($1&&$1.u)W1=$1.offset;var N1=y.subarray(u,W1);return u+=N1.length,N1}function w(X1){var W1=Math.ceil(X1.o/8/X1.X),$1=Math.ceil(X1.s/8/X1.B);for(var N1=0;N1>4===0)for(b=0;b<64;b++)A1=Y[b],t[A1]=y[u++];else if(e>>4===1)for(b=0;b<64;b++)A1=Y[b],t[A1]=K(y,u),u+=2;else throw new A("DQT - invalid table spec");k[e&15]=t}break;case 65472:case 65473:case 65474:if(B)throw new A("Only single frame JPEGs supported");u+=2,B={},B.G=W===65473,B.Z=W===65474,B.precision=y[u++];var U1=K(y,u),O1,E1=0,Y1=0;u+=2,B.s=f||U1,B.o=K(y,u),u+=2,B.W=[],B._={};var i=y[u++];for(j=0;j>4,o=y[u+1]&15;if(E1>4===0?_:S)[Z1&15]=D(j1,B1)}break;case 65501:u+=2,q=K(y,u),u+=2;break;case 65498:var k1=++P===1&&!f,D1;u+=2;var G1=y[u++],w1=[];for(j=0;j>4],D1.i=S[x&15],w1.push(D1)}var m=y[u++],l=y[u++],a=y[u++];try{var K1=R(y,u,B,w1,q,m,l,a>>4,a&15,k1);u+=K1}catch(X1){if(X1 instanceof DNLMarkerError)return this.parse(y,{F:X1.s});else if(X1 instanceof EOIMarkerError)break A;throw X1}break;case 65500:u+=4;break;case 65535:if(y[u]!==255)u--;break;default:var F1=h(y,u-2,u-3);if(F1&&F1.u){u=F1.offset;break}if(u>=y.length-1)break A;throw new A("JpegImage.parse - unknown marker: "+W.toString(16))}W=K(y,u),u+=2}this.width=B.o,this.height=B.s,this.g=d,this.b=n,this.W=[];for(j=0;j>8)+t[_+1];return r},get f(){if(this.b)return!!this.b.a;if(this.p===3){if(this.N===0)return!1;else if(this.W[0].index===82&&this.W[1].index===71&&this.W[2].index===66)return!1;return!0}if(this.N===1)return!0;return!1},z:function y(g){var f,u,d;for(var n=0,B=g.length;n4)throw new A("Unsupported color mode");var n=this.Y(g,f,d);if(this.p===1&&u){var B=n.length,q=new Uint8ClampedArray(B*3),P=0;for(var O=0;O>24}function K(U,Y){return U[Y]<<8|U[Y+1]}function C(U,Y){return(U[Y]<<24|U[Y+1]<<16|U[Y+2]<<8|U[Y+3])>>>0}C0.JpegDecoder=Q})();C0.encodeImage=function(A,Q,J,K){var C={t256:[Q],t257:[J],t258:[8,8,8,8],t259:[1],t262:[2],t273:[1000],t277:[4],t278:[J],t279:[Q*J*4],t282:[[72,1]],t283:[[72,1]],t284:[1],t286:[[0,1]],t287:[[0,1]],t296:[1],t305:["Photopea (UTIF.js)"],t338:[1]};if(K)for(var U in K)C[U]=K[U];var Y=new Uint8Array(C0.encode([C])),Z=new Uint8Array(A),X=new Uint8Array(1000+Q*J*4);for(var U=0;U3)Q.t258=Q.t258.slice(0,3);var Z=Q.t277?Q.t277[0]:1,X=Q.t258?Q.t258[0]:1,E=X*Z;if(U==1&&Q.t279!=null&&Q.t278&&Q.t262[0]==32803)E=Math.round(Q.t279[0]*8/(Q.width*Q.t278[0]));if(Q.t50885&&Q.t50885[0]==4)E=Q.t258[0]*3;var H=Math.ceil(Q.width*E/8)*8,$=Q.t273;if($==null||Q.t322)$=Q.t324;var I=Q.t279;if(U==1&&$.length==1)I=[Q.height*(H>>>3)];if(I==null||Q.t322)I=Q.t325;var N=new Uint8Array(Q.height*(H>>>3)),F=0;if(Q.t322!=null){var V=Q.t322[0],D=Q.t323[0],L=Math.floor((Q.width+V-1)/V),R=Math.floor((Q.height+D-1)/D),M=new Uint8Array(Math.ceil(V*D*E/8)|0);console.log("====",L,R);for(var T=0;T>>3,L=Math.ceil(F*V*E/8);if(F==16&&!A.isLE&&A.t33422==null)for(var R=0;R>>8&255}else if(V==3)for(var $=3;$>3^16368,(q[F]|q[F+1]<<8)>>(N&7)&~(-1<>2,L[1]=((w(1)&3)<<12|w(2)<<4|w(3)>>4)&16383,L[2]=w(3)>>2&3,L[3]=(w(3)&3)<<8|w(4),L[4]=w(5)<<2|w(6)>>6,L[5]=(w(6)&63)<<4|w(7)>>4,L[6]=w(7)>>2&3,L[7]=(w(7)&3)<<8|w(8),L[8]=w(9)<<2&1020|w(10)>>6,L[9]=(w(10)<<4|w(11)>>4)&1023,L[10]=w(11)>>2&3,L[11]=(w(11)&3)<<8|w(12),L[12]=(w(13)<<2&1020|w(14)>>6)&1023,L[13]=(w(14)<<4|w(15)>>4)&1023,N+=16,F=0}function S(){L[0]=w(0)<<4|w(1)>>4,L[1]=((w(1)&15)<<8|w(2))&4095,L[2]=w(3)>>6&3,L[3]=(w(3)&63)<<2|w(4)>>6,L[4]=(w(4)&63)<<2|w(5)>>6,L[5]=(w(5)&63)<<2|w(6)>>6,L[6]=w(6)>>4&3,L[7]=(w(6)&15)<<4|w(7)>>4,L[8]=(w(7)&15)<<4|w(8)>>4,L[9]=(w(8)&15)<<4|w(9)>>4,L[10]=w(9)>>2&3,L[11]=(w(9)&3)<<6|w(10)>>2,L[12]=(w(10)&3)<<6|w(11)>>2,L[13]=(w(11)&3)<<6|w(12)>>2,L[14]=w(12)&3,L[15]=w(13),L[16]=w(14),L[17]=w(15),N+=16,F=0}function _(){h[0]=0,h[1]=0,y[0]=0,y[1]=0}if(H==7)throw H;else if(H==6){var W=E==12,j=W?S:k,b=W?14:11,p=W?128:512,s=W?2048:8192,r=W?16383:65535,A1=W?4095:16383,Q1=Z/b,e=Q1*16,t=W?18:14;for(d=0;du)i+=y[g]-u;y[g]=i}else if(h[g]=i,i)y[g]=i;else i=y[g];P[f+n++]=i-15<=r?i-15&r:i+2147483633>>31&A1}}}}}else if(H==5){var c=E==12?10:9;for(d=0;d>4),P[f++]=((L[4]&15)<<8)+L[3],P[f++]=16*L[5]+(L[4]>>4),P[f++]=((L[7]&15)<<8)+L[6],P[f++]=16*L[8]+(L[7]>>4),P[f++]=((L[10]&15)<<8)+L[9],P[f++]=16*L[11]+(L[10]>>4),P[f++]=((L[13]&15)<<8)+L[12],P[f++]=16*L[14]+(L[13]>>4);else if(E==14)P[f++]=L[0]+((L[1]&63)<<8),P[f++]=(L[1]>>6)+4*L[2]+((L[3]&15)<<10),P[f++]=(L[3]>>4)+16*L[4]+((L[5]&3)<<12),P[f++]=((L[5]&252)>>2)+(L[6]<<6),P[f++]=L[7]+((L[8]&63)<<8),P[f++]=(L[8]>>6)+4*L[9]+((L[10]&15)<<10),P[f++]=(L[10]>>4)+16*L[11]+((L[12]&3)<<12),P[f++]=((L[12]&252)>>2)+(L[13]<<6),P[f++]=L[14]+((L[15]&63)<<8)}else if(H==4)for(d=0;d>3-O(2);if(y[g]){if(M=O(8),M!=0){if(h[g]-=128<11)h[g]=y[g]<<4|O(4);P[f++]=h[n&1]}else throw H};C0.decode._decodeVC5=function(){var A=[1,0,1,0,2,2,1,1,3,7,1,2,5,25,1,3,6,48,1,4,6,54,1,5,7,111,1,8,7,99,1,6,7,105,12,0,7,107,1,7,8,209,20,0,8,212,1,9,8,220,1,10,9,393,1,11,9,394,32,0,9,416,1,12,9,427,1,13,10,887,1,18,10,784,1,14,10,790,1,15,10,835,60,0,10,852,1,16,10,885,1,17,11,1571,1,19,11,1668,1,20,11,1669,100,0,11,1707,1,21,11,1772,1,22,12,3547,1,29,12,3164,1,24,12,3166,1,25,12,3140,1,23,12,3413,1,26,12,3537,1,27,12,3539,1,28,13,7093,1,35,13,6283,1,30,13,6331,1,31,13,6335,180,0,13,6824,1,32,13,7072,1,33,13,7077,320,0,13,7076,1,34,14,12565,1,36,14,12661,1,37,14,12669,1,38,14,13651,1,39,14,14184,1,40,15,28295,1,46,15,28371,1,47,15,25320,1,42,15,25336,1,43,15,25128,1,41,15,27300,1,44,15,28293,1,45,16,50259,1,48,16,50643,1,49,16,50675,1,50,16,56740,1,53,16,56584,1,51,16,56588,1,52,17,113483,1,61,17,113482,1,60,17,101285,1,55,17,101349,1,56,17,109205,1,57,17,109207,1,58,17,100516,1,54,17,113171,1,59,18,202568,1,62,18,202696,1,63,18,218408,1,64,18,218412,1,65,18,226340,1,66,18,226356,1,67,18,226358,1,68,19,402068,1,69,19,405138,1,70,19,405394,1,71,19,436818,1,72,19,436826,1,73,19,452714,1,75,19,452718,1,76,19,452682,1,74,20,804138,1,77,20,810279,1,78,20,810790,1,79,20,873638,1,80,20,873654,1,81,20,905366,1,82,20,905430,1,83,20,905438,1,84,21,1608278,1,85,21,1620557,1,86,21,1621582,1,87,21,1621583,1,88,21,1747310,1,89,21,1810734,1,90,21,1810735,1,91,21,1810863,1,92,21,1810879,1,93,22,3621725,1,99,22,3621757,1,100,22,3241112,1,94,22,3494556,1,95,22,3494557,1,96,22,3494622,1,97,22,3494623,1,98,23,6482227,1,102,23,6433117,1,101,23,6989117,1,103,23,6989119,1,105,23,6989118,1,104,23,7243449,1,106,23,7243512,1,107,24,13978233,1,111,24,12964453,1,109,24,12866232,1,108,24,14486897,1,113,24,13978232,1,110,24,14486896,1,112,24,14487026,1,114,24,14487027,1,115,25,25732598,1,225,25,25732597,1,189,25,25732596,1,188,25,25732595,1,203,25,25732594,1,202,25,25732593,1,197,25,25732592,1,207,25,25732591,1,169,25,25732590,1,223,25,25732589,1,159,25,25732522,1,235,25,25732579,1,152,25,25732575,1,192,25,25732489,1,179,25,25732573,1,201,25,25732472,1,172,25,25732576,1,149,25,25732488,1,178,25,25732566,1,120,25,25732571,1,219,25,25732577,1,150,25,25732487,1,127,25,25732506,1,211,25,25732548,1,125,25,25732588,1,158,25,25732486,1,247,25,25732467,1,238,25,25732508,1,163,25,25732552,1,228,25,25732603,1,183,25,25732513,1,217,25,25732587,1,168,25,25732520,1,122,25,25732484,1,128,25,25732562,1,249,25,25732505,1,187,25,25732504,1,186,25,25732483,1,136,25,25928905,1,181,25,25732560,1,255,25,25732500,1,230,25,25732482,1,135,25,25732555,1,233,25,25732568,1,222,25,25732583,1,145,25,25732481,1,134,25,25732586,1,167,25,25732521,1,248,25,25732518,1,209,25,25732480,1,243,25,25732512,1,216,25,25732509,1,164,25,25732547,1,140,25,25732479,1,157,25,25732544,1,239,25,25732574,1,191,25,25732564,1,251,25,25732478,1,156,25,25732546,1,139,25,25732498,1,242,25,25732557,1,133,25,25732477,1,162,25,25732515,1,213,25,25732584,1,165,25,25732514,1,212,25,25732476,1,227,25,25732494,1,198,25,25732531,1,236,25,25732530,1,234,25,25732529,1,117,25,25732528,1,215,25,25732527,1,124,25,25732526,1,123,25,25732525,1,254,25,25732524,1,253,25,25732523,1,148,25,25732570,1,218,25,25732580,1,146,25,25732581,1,147,25,25732569,1,224,25,25732533,1,143,25,25732540,1,184,25,25732541,1,185,25,25732585,1,166,25,25732556,1,132,25,25732485,1,129,25,25732563,1,250,25,25732578,1,151,25,25732501,1,119,25,25732502,1,193,25,25732536,1,176,25,25732496,1,245,25,25732553,1,229,25,25732516,1,206,25,25732582,1,144,25,25732517,1,208,25,25732558,1,137,25,25732543,1,241,25,25732466,1,237,25,25732507,1,190,25,25732542,1,240,25,25732551,1,131,25,25732554,1,232,25,25732565,1,252,25,25732475,1,171,25,25732493,1,205,25,25732492,1,204,25,25732491,1,118,25,25732490,1,214,25,25928904,1,180,25,25732549,1,126,25,25732602,1,182,25,25732539,1,175,25,25732545,1,141,25,25732559,1,138,25,25732537,1,177,25,25732534,1,153,25,25732503,1,194,25,25732606,1,160,25,25732567,1,121,25,25732538,1,174,25,25732497,1,246,25,25732550,1,130,25,25732572,1,200,25,25732474,1,170,25,25732511,1,221,25,25732601,1,196,25,25732532,1,142,25,25732519,1,210,25,25732495,1,199,25,25732605,1,155,25,25732535,1,154,25,25732499,1,244,25,25732510,1,220,25,25732600,1,195,25,25732607,1,161,25,25732604,1,231,25,25732473,1,173,25,25732599,1,226,26,51465122,1,116,26,51465123,0,1],Q,J,K,C=[3,3,3,3,2,2,2,1,1,1],U=24576,Y=16384,Z=8192,X=Y|Z;function E(R){var M=R[1],T=R[0][M>>>3]>>>7-(M&7)&1;return R[1]++,T}function H(R,M){if(Q==null){Q={};for(var T=0;T>>1}return R}function I(R,M){return R>>M}function N(R,M,T,h,y,g){M[T]=I(I(11*R[y]-4*R[y+g]+R[y+g+g]+4,3)+R[h],1),M[T+g]=I(I(5*R[y]+4*R[y+g]-R[y+g+g]+4,3)-R[h],1)}function F(R,M,T,h,y,g){var f=R[y-g]-R[y+g],u=R[y],d=R[h];M[T]=I(I(f+4,3)+u+d,1),M[T+g]=I(I(-f+4,3)+u-d,1)}function V(R,M,T,h,y,g){M[T]=I(I(5*R[y]+4*R[y-g]-R[y-g-g]+4,3)+R[h],1),M[T+g]=I(I(11*R[y]-4*R[y-g]+R[y-g-g]+4,3)-R[h],1)}function D(R){return R=R<0?0:R>4095?4095:R,R=K[R]>>>2,R}function L(R,M,T,h,y,g){h=new Uint16Array(h.buffer);var f=Date.now(),u=C0._binBE,d=M+T,n,B,q,P,O,w,k,S,_,W,j,b,p,s,r,A1,Q1,e;M+=4;var t=g[0]==1;while(M>>1)*(q>>>1));e=new Int16Array((B>>>1)*(q>>>1)),J=new Int16Array(1024);for(var c=0;c<1024;c++){var o=c-512,C1=Math.abs(o),n=Math.floor(768*C1*C1*C1/16581375)+C1;J[c]=Math.sign(o)*n}K=new Uint16Array(4096);var q1=65535;for(var c=0;c<4096;c++){var Z1=c,j1=q1*(Math.pow(113,Z1/4095)-1)/112;K[c]=Math.min(j1,q1)}}var H1=Q1[k],B1=$(B,1+C[P]),k1=$(q,1+C[P]);if(P==0)for(var D1=0;D1>>1)+G1]=R[w1]<<8|R[w1+1]}else{var G=[R,M*8],z=[],x=0,m=B1*k1,l=[0,0],a=0,O1=0;while(x0)z[x++]=O1,a--}var K1=(P-1)%3,F1=K1!=1?B1:0,R1=K1!=0?k1:0;for(var D1=0;D1>>1)+F1,W1=D1*B1;for(var G1=0;G1>>1,$1=B1*2,N1=k1*2;for(var D1=0;D1>14-V1*2&3;var S1=M1[L1];if(S1!=0)for(var D1=0;D1>>1)*(B>>>1)+(G1>>>1),s1=O0[w1],o0=h1[w1]-2048,a1=b1[w1]-2048,r1=f0[w1]-2048,FA=(o0<<1)+s1,K0=(a1<<1)+s1,J0=s1+r1,qA=s1-r1;if(t)h[e1]=D(J0),h[e1+1]=D(K0),h[e1+B]=D(FA),h[e1+B+1]=D(qA);else h[e1]=D(FA),h[e1+1]=D(J0),h[e1+B]=D(qA),h[e1+B+1]=D(K0)}}M+=i*4}else if(E1==16388)M+=i*4;else if(Y1==8192||Y1==8448||Y1==9216);else throw E1.toString(16)}}console.log(Date.now()-f)}return L}();C0.decode._decodeLogLuv32=function(A,Q,J,K,C,U){var Y=A.width,Z=Y*4,X=0,E=new Uint8Array(Z);while(X>>(N[k]>>>8);for(var F=0;F>>4,C[U+k+1]=T<<4|y>>>4,C[U+k+2]=y<<4|h>>>4}return}var g=new Uint16Array(16),f,u,d,n,B,q,P,O,w,k,S,_=new Uint8Array(Y+1);for(f=0;f>>11,q=15&d>>>22,P=15&d>>>26;for(O=0;O<4&&128<>3))>>>(w&7)&127)<2047)g[k]=2047;w+=7}for(k=0;k<16;k++,u+=2){var M=g[k]<<1;C0.decode._putsF(C,(f*Y+u)*X,M<<16-X)}u-=u&1?1:31}}};C0.decode._decodeNikon=function(A,Q,J,K,C,U,Y){var Z=[[0,0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,5,4,3,6,2,7,1,0,8,9,11,10,12],[0,0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,57,90,56,39,22,5,4,3,2,1,0,11,12,12],[0,0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,5,4,6,3,7,2,8,1,9,0,10,11,12],[0,0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0,5,6,4,7,8,3,9,2,1,0,10,11,12,13,14],[0,0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0,8,92,75,58,41,7,6,5,4,3,2,1,0,13,14],[0,0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0,7,6,8,5,9,4,10,3,11,12,2,0,1,13,14]],X=A.t256[0],E=A.t257[0],H=A.t258[0],$=0,I=0,N=C0.decode._make_decoder,F=C0.decode._getbithuff,V=Q[0].exifIFD.makerNote,D=V.t150?V.t150:V.t140,L=0,R=D[L++],M=D[L++];if(R==73||M==88)L+=2110;if(R==70)$=2;if(H==14)$+=3;var T=[[0,0],[0,0]],h=A.isLE?C0._binLE:C0._binBE;for(var d=0;d<2;d++)for(var y=0;y<2;y++)T[d][y]=h.readShort(D,L),L+=2;var g=1<1)f=Math.floor(g/(u-1));if(R==68&&M==32&&f>0)I=h.readShort(D,562);var d,n,B,q,P,O,w=0,k=[0,0],S=N(Z[$]),_=[K,0,0,0];for(w=n=0;n>>4,O=(F(J,_,q-P,0)<<1)+1<

>>1,(O&1<>>3;A[K]|=J>>>16,A[K+1]|=J>>>8,A[K+2]|=J};C0.decode._getbithuff=function(A,Q,J,K){var C=0,U=C0.decode._get_byte,Y,Z=Q[0],X=Q[1],E=Q[2],H=Q[3];if(J==0||E<0)return 0;while(!H&&E>>32-J,K)E-=K[Y+1]>>>8,Y=K[Y+1]&255;else E-=J;if(E<0)throw"e";return Q[0]=Z,Q[1]=X,Q[2]=E,Q[3]=H,Y};C0.decode._make_decoder=function(A){var Q,J,K,C,U,Y=[];for(Q=16;Q!=0&&!A[Q];Q--);var Z=17;Y[0]=Q;for(K=J=1;J<=Q;J++)for(C=0;C>>8;else for(var I=0;I>>8,C[U+(I<<1)+1]=D[I]&255;else if(V==14||V==12||V==10){var R=16-V;for(var I=0;I1;if(!V){if(Q[J]==255&&Q[J+1]==C)return{jpegOffset:J};if(M!=null){if(Q[J+T]==255&&Q[J+T+1]==C)$=J+T;else log("JPEGInterchangeFormat does not point to SOI");if(h==null)log("JPEGInterchangeFormatLength field is missing");else if(T>=I||T+y<=I)log("JPEGInterchangeFormatLength field value is invalid");if($!=null)return{jpegOffset:$}}}if(f!=null)u=f[0],d=f[1];if(M!=null){if(h!=null)if(y>=2&&T+y<=I){if(Q[J+T+y-2]==255&&Q[J+T+y-1]==C)N=new Uint8Array(y-2);else N=new Uint8Array(y);for(D=0;D offset to first strip or tile")}if(N==null){var q=0,P=[];P[q++]=255,P[q++]=C;var O=A.t519;if(O==null)throw new Error("JPEGQTables tag is missing");for(D=0;D>>8,P[q++]=k&255,P[q++]=D|R<<4;for(L=0;L<16;L++)P[q++]=Q[J+w[D]+L];for(L=0;L>>8&255,P[q++]=A.height&255,P[q++]=A.width>>>8&255,P[q++]=A.width&255,P[q++]=n,n==1)P[q++]=1,P[q++]=17,P[q++]=0;else for(D=0;D<3;D++)P[q++]=D+1,P[q++]=D!=0?17:(u&15)<<4|d&15,P[q++]=D;if(B!=null&&B[0]!=0)P[q++]=255,P[q++]=X,P[q++]=0,P[q++]=4,P[q++]=B[0]>>>8&255,P[q++]=B[0]&255;N=new Uint8Array(P)}var S=-1;D=0;while(D>>8&255,N[W++]=A.height&255,N[W++]=A.width>>>8&255,N[W++]=A.width&255,N[W++]=n,n==1)N[W++]=1,N[W++]=17,N[W++]=0;else for(D=0;D<3;D++)N[W++]=D+1,N[W++]=D!=0?17:(u&15)<<4|d&15,N[W++]=D}if(Q[I]==255&&Q[I+1]==H){var j=Q[I+2]<<8|Q[I+3];F=new Uint8Array(j+2),F[0]=Q[I],F[1]=Q[I+1],F[2]=Q[I+2],F[3]=Q[I+3];for(D=0;D>>8&255,E[$.sofPosition+6]=A.height&255,E[$.sofPosition+7]=A.width>>>8&255,E[$.sofPosition+8]=A.width&255,Q[J]!=255||Q[J+1]!=SOS)E.set($.sosMarker,H),H+=sosMarker.length;for(Y=0;Y=0&&X<128)for(var E=0;E=-127&&X<0){for(var E=0;E<-X+1;E++)Y[C]=U[Q],C++;Q++}}return C};C0.decode._decodeThunder=function(A,Q,J,K,C){var U=[0,1,0,-1],Y=[0,1,2,3,0,-3,-2,-1],Z=Q+J,X=C*2,E=0;while(Q>>6,I=H&63;if(Q++,$==3)E=I&15,K[X>>>1]|=E<<4*(1-X&1),X++;if($==0)for(var N=0;N>>1]|=E<<4*(1-X&1),X++;if($==2)for(var N=0;N<2;N++){var F=I>>>3*(1-N)&7;if(F!=4)E+=Y[F],K[X>>>1]|=E<<4*(1-X&1),X++}if($==1)for(var N=0;N<3;N++){var F=I>>>2*(2-N)&3;if(F!=2)E+=U[F],K[X>>>1]|=E<<4*(1-X&1),X++}}};C0.decode._dmap={"1":0,"011":1,"000011":2,"0000011":3,"010":-1,"000010":-2,"0000010":-3};C0.decode._lens=function(){var A=function(X,E,H,$){for(var I=0;I>>3>>3]>>>7-(X&7)&1;if(Y==2)f=A[X>>>3]>>>(X&7)&1;if(X++,H+=f,h=="H"){if(Z._lens[M][H]!=null){var u=Z._lens[M][H];if(H="",E+=u,u<64){if(Z._addNtimes($,E,M),F+=E,M=1-M,E=0,y--,y==0)h=""}}}else{if(H=="0001")H="",Z._addNtimes($,R-F,M),F=R;if(H=="001")H="",h="H",y=2;if(Z._dmap[H]!=null)V=L+Z._dmap[H],Z._addNtimes($,V-F,M),F=V,H="",M=1-M}if($.length==U&&h=="")Z._writeBits($,K,C*8+T*g),M=0,T++,F=0,I=Z._makeDiff($),$=[]}};C0.decode._findDiff=function(A,Q,J){for(var K=0;K=Q&&A[K+1]==J)return A[K]};C0.decode._makeDiff=function(A){var Q=[];if(A[0]==1)Q.push(0,1);for(var J=1;J>>3>>3]>>>7-(X&7)&1;if(Y==2)V=A[X>>>3]>>>(X&7)&1;if(X++,H+=V,E=Z._lens[I][H],E!=null){if(Z._addNtimes($,E,I),H="",E<64)I=1-I;if($.length==U){if(Z._writeBits($,K,C*8+N*F),$=[],N++,I=0,(X&7)!=0)X+=8-(X&7);if(E>=64)X+=8}}}};C0.decode._decodeG3=function(A,Q,J,K,C,U,Y,Z){var X=C0.decode,E=Q<<3,H=0,$="",I=[],N=[];for(var F=0;F>>3>>3]>>>7-(E&7)&1;if(Y==2)d=A[E>>>3]>>>(E&7)&1;if(E++,$+=d,f){if(X._lens[T][$]!=null){var n=X._lens[T][$];if($="",H+=n,n<64)X._addNtimes(I,H,T),T=1-T,H=0}}else if(y=="H"){if(X._lens[T][$]!=null){var n=X._lens[T][$];if($="",H+=n,n<64){if(X._addNtimes(I,H,T),V+=H,T=1-T,H=0,g--,g==0)y=""}}}else{if($=="0001")$="",X._addNtimes(I,M-V,T),V=M;if($=="001")$="",y="H",g=2;if(X._dmap[$]!=null)D=R+X._dmap[$],X._addNtimes(I,D-V,T),V=D,$="",T=1-T}if($.endsWith("000000000001")){if(h>=0)X._writeBits(I,K,C*8+h*u);if(Z){if(Y==1)f=(A[E>>>3]>>>7-(E&7)&1)==1;if(Y==2)f=(A[E>>>3]>>>(E&7)&1)==1;E++}$="",T=0,h++,V=0,N=X._makeDiff(I),I=[]}}if(I.length==U)X._writeBits(I,K,C*8+h*u)};C0.decode._addNtimes=function(A,Q,J){for(var K=0;K>>3]|=A[K]<<7-(J+K&7)};C0.decode._decodeLZW=C0.decode._decodeLZW=function(){var A,Q,J,K,C=0,U=0,Y=0,Z=0,X=function(){var D=A>>>3,L=Q[D]<<16|Q[D+1]<<8|Q[D+2],R=L>>>24-(A&7)-U&(1<>>----------------");for(var X=0;XQ.buffer.byteLength)$=Q.buffer.byteLength-F;N=new Uint8Array(Q.buffer,F,$)}if(H==2){var V=$<5?J-4:I,D=Q[V],L=Math.max(0,Math.min($-1,Q.length-V));if(D<128||L==0)N.push(A.readASCII(Q,V,L));else N=new Uint8Array(Q.buffer,V,L)}if(H==3)for(var R=0;R<$;R++)N.push(A.readUshort(Q,($<3?J-4:I)+2*R));if(H==4||H==13)for(var R=0;R<$;R++)N.push(A.readUint(Q,($<2?J-4:I)+4*R));if(H==5||H==10){var M=H==5?A.readUint:A.readInt;for(var R=0;R<$;R++)N.push([M(Q,I+R*8),M(Q,I+R*8+4)])}if(H==8)for(var R=0;R<$;R++)N.push(A.readShort(Q,($<3?J-4:I)+2*R));if(H==9)for(var R=0;R<$;R++)N.push(A.readInt(Q,($<2?J-4:I)+4*R));if(H==11)for(var R=0;R<$;R++)N.push(A.readFloat(Q,I+R*4));if(H==12)for(var R=0;R<$;R++)N.push(A.readDouble(Q,I+R*8));if($!=0&&N.length==0){if(log(E,"unknown TIFF tag type: ",H,"num:",$),X==0)return;continue}if(U.debug)log(" ".repeat(C),E,H,C0.tags[E],N);if(Z["t"+E]=N,E==330&&Z.t272&&Z.t272[0]=="DSLR-A100");else if(E==330||E==34665||E==34853||E==50740&&A.readUshort(Q,A.readUint(N,0))<300||E==61440){var T=E==50740?[A.readUint(N,0)]:N,h=[];for(var R=0;R4)A.writeUint(J,K,Z),D=Z;if($==1||$==7)for(var L=0;L4)V+=V&1,Z+=V;K+=4}return[K,Z]};C0.toRGBA8=function(A,Q){function J(H1){return H1<0.0031308?12.92*H1:1.055*Math.pow(H1,0.4166666666666667)-0.055}var{width:K,height:C}=A,U=K*C,Y=U*4,Z=A.data,X=new Uint8Array(U*4),E=A.t262?A.t262[0]:2,H=A.t258?Math.min(32,A.t258[0]):1;if(A.t262==null&&H==1)E=0;var $=A.t277?A.t277[0]:A.t258?A.t258.length:[1,1,3,1,1,4,3][E],I=A.t339?A.t339[0]:null;if(E==1&&H==32&&I!=3)throw"e";var N=Math.ceil($*H*K/8);if(E==0){Q=0.00390625;for(var F=0;F>3)]>>7-(L&7)&1;X[R]=X[R+1]=X[R+2]=(1-M)*255,X[R+3]=255}if(H==4)for(var L=0;L>1)]>>4-4*(L&1)&15;X[R]=X[R+1]=X[R+2]=(15-M)*17,X[R+3]=255}if(H==8)for(var L=0;L>3)]>>7-(L&7)&1;X[R]=X[R+1]=X[R+2]=M*255,X[R+3]=255}if(H==2)for(var L=0;L>2)]>>6-2*(L&3)&3;X[R]=X[R+1]=X[R+2]=M*85,X[R+3]=255}if(H==8)for(var L=0;L>>2)+L,M=h[T];X[R]=X[R+1]=X[R+2]=~~(0.5+255*M),X[R+3]=255}}}else if(E==2)if(H==8){if($==1)for(var L=0;L=4)for(var L=0;L1&&A.t338&&A.t338[0]!=0;for(var F=0;F>>3)]>>>7-(O&7)&1;else if(H==2)w=Z[k+(O>>>2)]>>>6-2*(O&3)&3;else if(H==4)w=Z[k+(O>>>1)]>>>4-4*(O&1)&15;else if(H==8)w=Z[k+O*$];else throw H;X[R]=B[w]>>8,X[R+1]=B[q+w]>>8,X[R+2]=B[q+q+w]>>8,X[R+3]=P?Z[k+O*$+1]:255}}else if(E==5){var S=$>4?1:0;for(var L=0;L>>1),b=Z[_+(Q1&1)],e=Z[_+2]-128,t=Z[_+3]-128,U1=b+((t>>2)+(t>>3)+(t>>5)),O1=b-((e>>2)+(e>>4)+(e>>5))-((t>>1)+(t>>3)+(t>>4)+(t>>5)),E1=b+(e+(e>>1)+(e>>2)+(e>>6));X[R]=Math.max(0,Math.min(255,U1)),X[R+1]=Math.max(0,Math.min(255,O1)),X[R+2]=Math.max(0,Math.min(255,E1)),X[R+3]=255}}}else if(E==32845)for(var F=0;FK)K=Z,C=Y}C0.decodeImage(A,C,Q);var X=C0.toRGBA8(C),E=C.width,H=C.height,$=document.createElement("canvas");$.width=E,$.height=H;var I=$.getContext("2d"),N=new ImageData(new Uint8ClampedArray(X.buffer),E,H);return I.putImageData(N,0,0),$.toDataURL()};C0._binBE={nextZero:function(A,Q){while(A[Q]!=0)Q++;return Q},readUshort:function(A,Q){return A[Q]<<8|A[Q+1]},readShort:function(A,Q){var J=C0._binBE.ui8;return J[0]=A[Q+1],J[1]=A[Q+0],C0._binBE.i16[0]},readInt:function(A,Q){var J=C0._binBE.ui8;return J[0]=A[Q+3],J[1]=A[Q+2],J[2]=A[Q+1],J[3]=A[Q+0],C0._binBE.i32[0]},readUint:function(A,Q){var J=C0._binBE.ui8;return J[0]=A[Q+3],J[1]=A[Q+2],J[2]=A[Q+1],J[3]=A[Q+0],C0._binBE.ui32[0]},readASCII:function(A,Q,J){var K="";for(var C=0;C>8&255,A[Q+1]=J&255},writeInt:function(A,Q,J){var K=C0._binBE.ui8;C0._binBE.i32[0]=J,A[Q+3]=K[0],A[Q+2]=K[1],A[Q+1]=K[2],A[Q+0]=K[3]},writeUint:function(A,Q,J){A[Q]=J>>24&255,A[Q+1]=J>>16&255,A[Q+2]=J>>8&255,A[Q+3]=J>>0&255},writeASCII:function(A,Q,J){for(var K=0;K>8&255},writeInt:function(A,Q,J){var K=C0._binBE.ui8;C0._binBE.i32[0]=J,A[Q+0]=K[0],A[Q+1]=K[1],A[Q+2]=K[2],A[Q+3]=K[3]},writeUint:function(A,Q,J){A[Q]=J>>>0&255,A[Q+1]=J>>>8&255,A[Q+2]=J>>>16&255,A[Q+3]=J>>>24&255},writeASCII:C0._binBE.writeASCII};C0._copyTile=function(A,Q,J,K,C,U,Y,Z){var X=Math.min(Q,C-Y),E=Math.min(J,U-Z);for(var H=0;H>>2<<5);while(C==0){if(C=D(Q,I,1),U=D(Q,I+1,2),I+=3,U==0){if((I&7)!=0)I+=8-(I&7);var f=(I>>>3)+4,u=Q[f-4]|Q[f-3]<<8;if(g)J=A.H.W(J,$+u);J.set(new K(Q.buffer,Q.byteOffset+f,u),$),I=f+u<<3,$+=u;continue}if(g)J=A.H.W(J,$+131072);if(U==1)N=y.J,F=y.h,E=511,H=31;if(U==2){Y=L(Q,I,5)+257,Z=L(Q,I+5,5)+1,X=L(Q,I+10,4)+4,I+=14;var d=I,n=1;for(var B=0;B<38;B+=2)y.Q[B]=0,y.Q[B+1]=0;for(var B=0;Bn)n=q}I+=3*X,M(y.Q,n),T(y.Q,n,y.u),N=y.w,F=y.d,I=R(y.u,(1<>>4;if(k>>>8==0)J[$++]=k;else if(k==256)break;else{var S=$+k-254;if(k>264){var _=y.q[k-257];S=$+(_>>>3)+L(Q,I,_&7),I+=_&7}var W=F[h(Q,I)&H];I+=W&15;var j=W>>>4,b=y.c[j],p=(b>>>4)+D(Q,I,b&15);I+=b&15;while($>>4;if($<=15)Y[E]=$,E++;else{var I=0,N=0;if($==16)N=3+Z(C,U,2),U+=2,I=Y[E-1];else if($==17)N=3+Z(C,U,3),U+=3;else if($==18)N=11+Z(C,U,7),U+=7;var F=E+N;while(E>>1;while(YU)U=X;Y++}while(Y>1,E=Q[Z+1],H=X<<4|E,$=J-E,I=Q[Z]<<$,N=I+(1<<$);while(I!=N){var F=Y[I]>>>15-J;K[F]=H,I++}}},A.H.l=function(Q,J){var K=A.H.m.r,C=15-J;for(var U=0;U>>C}},A.H.M=function(Q,J,K){K=K<<(J&7);var C=J>>>3;Q[C]|=K,Q[C+1]|=K>>>8},A.H.I=function(Q,J,K){K=K<<(J&7);var C=J>>>3;Q[C]|=K,Q[C+1]|=K>>>8,Q[C+2]|=K>>>16},A.H.e=function(Q,J,K){return(Q[J>>>3]|Q[(J>>>3)+1]<<8)>>>(J&7)&(1<>>3]|Q[(J>>>3)+1]<<8|Q[(J>>>3)+2]<<16)>>>(J&7)&(1<>>3]|Q[(J>>>3)+1]<<8|Q[(J>>>3)+2]<<16)>>>(J&7)},A.H.i=function(Q,J){return(Q[J>>>3]|Q[(J>>>3)+1]<<8|Q[(J>>>3)+2]<<16|Q[(J>>>3)+3]<<24)>>>(J&7)},A.H.m=function(){var Q=Uint16Array,J=Uint32Array;return{K:new Q(16),j:new Q(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[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,999,999,999],T:[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,0,0,0],q:new Q(32),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,65535,65535],z:[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,0,0],c:new J(32),J:new Q(512),_:[],h:new Q(32),$:[],w:new Q(32768),C:[],v:[],d:new Q(32768),D:[],u:new Q(512),Q:[],r:new Q(32768),s:new J(286),Y:new J(30),a:new J(19),t:new J(15000),k:new Q(65536),g:new Q(32768)}}(),function(){var Q=A.H.m,J=32768;for(var K=0;K>>1|(C&1431655765)<<1,C=(C&3435973836)>>>2|(C&858993459)<<2,C=(C&4042322160)>>>4|(C&252645135)<<4,C=(C&4278255360)>>>8|(C&16711935)<<8,Q.r[K]=(C>>>16|C<<16)>>>17}function U(Y,Z,X){while(Z--!=0)Y.push(0,X)}for(var K=0;K<32;K++)Q.q[K]=Q.S[K]<<3|Q.T[K],Q.c[K]=Q.p[K]<<4|Q.z[K];U(Q._,144,8),U(Q._,112,9),U(Q._,24,7),U(Q._,8,8),A.H.n(Q._,9),A.H.A(Q._,9,Q.J),A.H.l(Q._,9),U(Q.$,32,5),A.H.n(Q.$,5),A.H.A(Q.$,5,Q.h),A.H.l(Q.$,5),U(Q.Q,19,0),U(Q.C,286,0),U(Q.D,30,0),U(Q.v,320,0)}(),A.H.N}();C0.LosslessJpegDecode=function(){var A,Q;function J(){return A[Q++]}function K(){return A[Q++]<<8|A[Q++]}function C(D){var L=J(),R=[0,0,0,255],M=[],T=8;for(var h=0;h<16;h++)M[h]=J();for(var h=0;h<16;h++)for(var y=0;y>--u&1,n=R[n+B];f[h]=n}}function U(D,L,R,M){if(D[L+3]!=255)return 0;if(R==0)return L;for(var T=0;T<2;T++){if(D[L+T]==0)D[L+T]=D.length,D.push(0,0,M,255);var h=U(D,D[L+T],R-1,M+1);if(h!=0)return h}return 0}function Y(D){var{b:L,f:R}=D;while(L<25&&D.a>(L.b-=D)&65535>>16-D}function X(D,L){var R=D[0],M=0,T=255,h=0;if(L.b<16)Y(L);var y=L.f>>L.b-8&255;M=D[1][y],T=R[M+3],L.b-=R[M+2];while(T==255)h=L.f>>--L.b&1,M=R[M+h],T=R[M+3];return T}function E(D,L){if(D<32768>>16-L)D+=-(1<>4,O&15]}}else if(n==65476){var k=Q+B-2;while(Q>>4],h[_[0]]=_.slice(1)}R=J(),Q+=2;break}else if(n==65501)T=K();else Q+=B-2}var W=M>8?Uint16Array:Uint8Array,j=new W(u*d*f),b={b:0,f:0,c:R==8,a:Q,data:A,d:A.length,e:T};if(b.c)N(j,d*f,b,g[0],u);else{var p=[],s=0,r=0;for(var q=0;qs)s=Q1;if(e>r)r=e;p.push(Q1*e)}if(s!=1||r!=1){if(f!=3||p[1]!=1||p[2]!=1)throw"e";if(s!=2||r!=1&&r!=2)throw"e";var t=[],U1=0;for(var q=0;q>>1)*E1+(Q1>>>1))*U1,Z1=(e&1)*2+(Q1&1);j[C1]=o[q1+Z1],j[C1+1]=o[q1+4],j[C1+2]=o[q1+5]}else for(var Q1=0;Q1>>1))*U1,Z1=Q1&1;j[C1]=o[q1+Z1],j[C1+1]=o[q1+2],j[C1+2]=o[q1+3]}}else if($(j,d*f,b,g,f,u),T==0)V(j,R,d,u,0,f,f,M);else{var j1=Math.floor(T/d);for(var e=0;e>>1);else if(L==6)w=D[P]+(O-D[P-y]>>>1);else if(L==7)w=O+D[P]>>>1;else throw L;D[q]+=w}}}return F}();(function(){var A=0,Q=1,J=2,K=3,C=4,U=5,Y=6,Z=7,X=8,E=9,H=10,$=11,I=12,N=13,F=14,V=15,D=16,L=17,R=18;function M(S){var _=C0._binBE.readUshort,W={b:_(S,0),i:S[2],C:S[3],u:S[4],q:_(S,5),k:_(S,7),e:_(S,9),l:_(S,11),s:S[13],d:_(S,14)};if(W.b!=18771||W.i>1||W.q<6||W.q%6||W.e<768||W.e%24||W.l!=768||W.k=W.l||W.s>16||W.s!=W.k/W.l||W.s!=Math.ceil(W.e/W.l)||W.d!=W.q/6||W.u!=12&&W.u!=14&&W.u!=16||W.C!=16&&W.C!=0)throw"Invalid data";if(W.i==0)throw"Not implemented. We need this file!";return W.h=W.C==16,W.m=(W.h?W.l*2/3:W.l>>>1)|0,W.A=W.m+2,W.f=64,W.g=(1<>>6);for(var j=0;j<3;j++)for(var b=0;b<41;b++)_[j][b]=[W,1];return _}function u(S){for(var _=-1,W=0;!W;_++)if(W=S[S.j]>>>7-S.a&1,S.a++,S.a&=7,!S.a)S.j++;return _}function d(S,_){var W=0,j=8-S.a,b=S.j,p=S.a;if(_){if(_>=j)do W<<=j,_-=j,W|=S[S.j]&(1<=8);if(_)W<<=_,j-=_,W|=S[S.j]>>>j&(1<<_)-1;S.a=8-j}return W}function n(S,_){var W=0;if(_D1&&k1>>2,r){Y1[A1]=G1;return}O1=_.t*_.c[S.g+C1-c]+_.c[S.g+o-C1]}else G1=C1>o&&C1>q1||C1>>2:Z1+j1>>>1,O1=_.t*_.c[S.g+C1-o]+_.c[S.g+o-Z1];E1=H1(O1);var w1=u(W);if(w1>>1):U1>>>1,s[E1][0]+=H1(U1),s[E1][1]==S.f)s[E1][0]>>>=1,s[E1][1]>>>=1;if(s[E1][1]++,G1=O1<0?G1-U1:G1+U1,S.i){if(G1<0)G1+=_.w;else if(G1>S.g)G1-=_.w}Y1[A1]=G1>=0?Math.min(G1,S.g):0}function q(S,_,W){var j=S[0].length;for(var b=_;b<=W;b++)S[b][0]=S[b-1][1],S[b][j-1]=S[b-1][j-2]}function P(S){q(S,Z,I),q(S,J,C),q(S,V,L)}function O(S,_,W,j,b,p,s,r,A1,Q1,e,t,U1){var O1=0,E1=1,Y1=bC;while(E18)B(S,_,W,j,b,E1,r[A1]),B(S,_,W,j,p,E1,r[A1]),E1+=2}P(j)}function w(S,_,W,j,b,p){O(S,_,W,j,J,Z,b,p,0,0,1,0,8),O(S,_,W,j,X,V,b,p,1,0,1,0,8),O(S,_,W,j,K,E,b,p,2,1,0,3,0),O(S,_,W,j,H,D,b,p,0,0,0,3,2),O(S,_,W,j,C,$,b,p,1,0,0,3,2),O(S,_,W,j,I,L,b,p,2,1,0,3,0)}function k(S,_,W,j,b,p){var s=p.length,r=S.l;if(b+1==S.s)r=S.e-b*S.l;var A1=6*S.e*j+b*S.l;for(var Q1=0;Q1<6;Q1++){for(var e=0;e>>1);else if(t==2)U1=V+(Q1>>>1);else U1=Z+Q1;var O1=S.h?(e*2/3&2147483646|e%3&1)+(e%3>>>1):e>>>1;_[A1+e]=W[U1][O1+1]}A1+=S.e}}C0._decompressRAF=function(S,_){var W=M(S),j=T(S,W),b=g(W),p=new Int16Array(W.e*W.q);if(_==null)_=W.h?[[1,1,0,1,1,2],[1,1,2,1,1,0],[2,0,1,0,2,1],[1,1,2,1,1,0],[1,1,0,1,1,2],[0,2,1,2,0,1]]:[[0,1],[3,2]];var s=[[A,K],[Q,C],[U,$],[Y,I],[N,D],[F,L]],r=[];for(var A1=0;A1=C)return;var Y=K.charCodeAt(U),Z;if(Y>=55296&&Y<=56319&&C>U+1){if(Z=K.charCodeAt(U+1),Z>=56320&&Z<=57343)return(Y-55296)*1024+Z-56320+65536}return Y};if(A)A(String.prototype,"codePointAt",{value:Q,configurable:!0,writable:!0});else String.prototype.codePointAt=Q})();function dz(){this.table=new Uint16Array(16),this.trans=new Uint16Array(288)}var _C1=new dz,TC1=new dz,Xm=new Uint8Array(30),Em=new Uint16Array(30),kC1=new Uint8Array(30),SC1=new Uint16Array(30),ik1=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ak1=new dz,rk1=new Uint8Array(320);function $m(A,Q,J,K){var C,U;for(C=0;Cthis.x2)this.x2=A}if(typeof Q==="number"){if(isNaN(this.y1)||isNaN(this.y2))this.y1=Q,this.y2=Q;if(Qthis.y2)this.y2=Q}};_4.prototype.addX=function(A){this.addPoint(A,null)};_4.prototype.addY=function(A){this.addPoint(null,A)};_4.prototype.addBezier=function(A,Q,J,K,C,U,Y,Z){var X=[A,Q],E=[J,K],H=[C,U],$=[Y,Z];this.addPoint(A,Q),this.addPoint(Y,Z);for(var I=0;I<=1;I++){var N=6*X[I]-12*E[I]+6*H[I],F=-3*X[I]+9*E[I]-9*H[I]+3*$[I],V=3*E[I]-3*X[I];if(F===0){if(N===0)continue;var D=-V/N;if(0=0&&X>0)Z+=" ";Z+=Q(E)}return Z}var K="";for(var C=0;C=0&&A<=255,"Byte value should be between 0 and 255."),[A]};LA.BYTE=_5(1);h0.CHAR=function(A){return[A.charCodeAt(0)]};LA.CHAR=_5(1);h0.CHARARRAY=function(A){if(typeof A==="undefined")A="",console.warn("Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name.");var Q=[];for(var J=0;J>8&255,A&255]};LA.USHORT=_5(2);h0.SHORT=function(A){if(A>=_u)A=-(2*_u-A);return[A>>8&255,A&255]};LA.SHORT=_5(2);h0.UINT24=function(A){return[A>>16&255,A>>8&255,A&255]};LA.UINT24=_5(3);h0.ULONG=function(A){return[A>>24&255,A>>16&255,A>>8&255,A&255]};LA.ULONG=_5(4);h0.LONG=function(A){if(A>=Tu)A=-(2*Tu-A);return[A>>24&255,A>>16&255,A>>8&255,A&255]};LA.LONG=_5(4);h0.FIXED=h0.ULONG;LA.FIXED=LA.ULONG;h0.FWORD=h0.SHORT;LA.FWORD=LA.SHORT;h0.UFWORD=h0.USHORT;LA.UFWORD=LA.USHORT;h0.LONGDATETIME=function(A){return[0,0,0,0,A>>24&255,A>>16&255,A>>8&255,A&255]};LA.LONGDATETIME=_5(8);h0.TAG=function(A){return WA.argument(A.length===4,"Tag should be exactly 4 ASCII characters."),[A.charCodeAt(0),A.charCodeAt(1),A.charCodeAt(2),A.charCodeAt(3)]};LA.TAG=_5(4);h0.Card8=h0.BYTE;LA.Card8=LA.BYTE;h0.Card16=h0.USHORT;LA.Card16=LA.USHORT;h0.OffSize=h0.BYTE;LA.OffSize=LA.BYTE;h0.SID=h0.USHORT;LA.SID=LA.USHORT;h0.NUMBER=function(A){if(A>=-107&&A<=107)return[A+139];else if(A>=108&&A<=1131)return A=A-108,[(A>>8)+247,A&255];else if(A>=-1131&&A<=-108)return A=-A-108,[(A>>8)+251,A&255];else if(A>=-32768&&A<=32767)return h0.NUMBER16(A);else return h0.NUMBER32(A)};LA.NUMBER=function(A){return h0.NUMBER(A).length};h0.NUMBER16=function(A){return[28,A>>8&255,A&255]};LA.NUMBER16=_5(3);h0.NUMBER32=function(A){return[29,A>>24&255,A>>16&255,A>>8&255,A&255]};LA.NUMBER32=_5(5);h0.REAL=function(A){var Q=A.toString(),J=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(Q);if(J){var K=parseFloat("1e"+((J[2]?+J[2]:0)+J[1].length));Q=(Math.round(A*K)/K).toString()}var C="";for(var U=0,Y=Q.length;U>8&255,Q[Q.length]=K&255}return Q};LA.UTF16=function(A){return A.length*2};var gz={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø"+"¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ"+"јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø"+"ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ"+"άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ"+"ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ"+"ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};sC.MACSTRING=function(A,Q,J,K){var C=gz[K];if(C===void 0)return;var U="";for(var Y=0;Y=128){if(U=J[U],U===void 0)return}K[C]=U}return K};LA.MACSTRING=function(A,Q){var J=h0.MACSTRING(A,Q);if(J!==void 0)return J.length;else return 0};function bz(A){return A>=-128&&A<=127}function xC1(A,Q,J){var K=0,C=A.length;while(Q>8&255,X+256&255)}return U}h0.VARDELTAS=function(A){var Q=0,J=[];while(Q=-128&&K<=127)Q=yC1(A,Q,J);else Q=hC1(A,Q,J)}return J};h0.INDEX=function(A){var Q=1,J=[Q],K=[];for(var C=0;C>8,Q[$+1]=I&255,Q=Q.concat(K[H])}return Q};LA.TABLE=function(A){var Q=0,J=A.fields.length;for(var K=0;K0)return new Z0(this.data,this.offset+Q).parseStruct(A);return};Z0.prototype.parsePointer32=function(A){var Q=this.parseOffset32();if(Q>0)return new Z0(this.data,this.offset+Q).parseStruct(A);return};Z0.prototype.parseListOfLists=function(A){var Q=this.parseOffset16List(),J=Q.length,K=this.relativeOffset,C=new Array(J);for(var U=0;U>1,Q.skip("uShort",3),A.glyphIndexMap={};var Y=new jA.Parser(J,K+C+14),Z=new jA.Parser(J,K+C+16+U*2),X=new jA.Parser(J,K+C+16+U*4),E=new jA.Parser(J,K+C+16+U*6),H=K+C+16+U*8;for(var $=0;$=0;C-=1){var U=jA.getUShort(A,Q+4+C*8),Y=jA.getUShort(A,Q+4+C*8+2);if(U===3&&(Y===0||Y===1||Y===10)||U===0&&(Y===0||Y===1||Y===2||Y===3||Y===4)){K=jA.getULong(A,Q+4+C*8+4);break}}if(K===-1)throw new Error("No valid cmap sub-tables found.");var Z=new jA.Parser(A,Q+K);if(J.format=Z.parseUShort(),J.format===12)cC1(J,Z);else if(J.format===4)dC1(J,Z,A,Q,K);else throw new Error("Only format 4 and 12 cmap tables are supported (found format "+J.format+").");return J}function nC1(A,Q,J){A.segments.push({end:Q,start:Q,delta:-(Q-J),offset:0,glyphIndex:J})}function sC1(A){A.segments.push({end:65535,start:65535,delta:1,offset:0})}function oC1(A){var Q=!0,J;for(J=A.length-1;J>0;J-=1){var K=A.get(J);if(K.unicode>65535){console.log("Adding CMAP format 12 (needed!)"),Q=!1;break}}var C=[{name:"version",type:"USHORT",value:0},{name:"numTables",type:"USHORT",value:Q?1:2},{name:"platformID",type:"USHORT",value:3},{name:"encodingID",type:"USHORT",value:1},{name:"offset",type:"ULONG",value:Q?12:20}];if(!Q)C=C.concat([{name:"cmap12PlatformID",type:"USHORT",value:3},{name:"cmap12EncodingID",type:"USHORT",value:10},{name:"cmap12Offset",type:"ULONG",value:0}]);C=C.concat([{name:"format",type:"USHORT",value:4},{name:"cmap4Length",type:"USHORT",value:0},{name:"language",type:"USHORT",value:0},{name:"segCountX2",type:"USHORT",value:0},{name:"searchRange",type:"USHORT",value:0},{name:"entrySelector",type:"USHORT",value:0},{name:"rangeShift",type:"USHORT",value:0}]);var U=new c0.Table("cmap",C);U.segments=[];for(J=0;J>4,Y=C&15;if(U===J)break;if(Q+=K[U],Y===J)break;Q+=K[Y]}return parseFloat(Q)}function ZY1(A,Q){var J,K,C,U;if(Q===28)return J=A.parseByte(),K=A.parseByte(),J<<8|K;if(Q===29)return J=A.parseByte(),K=A.parseByte(),C=A.parseByte(),U=A.parseByte(),J<<24|K<<16|C<<8|U;if(Q===30)return UY1(A);if(Q>=32&&Q<=246)return Q-139;if(Q>=247&&Q<=250)return J=A.parseByte(),(Q-247)*256+J+108;if(Q>=251&&Q<=254)return J=A.parseByte(),-(Q-251)*256-J-108;throw new Error("Invalid b0 "+Q)}function BY1(A){var Q={};for(var J=0;J>1,X.length=0,H=!0}function g(f){var u,d,n,B,q,P,O,w,k,S,_,W,j=0;while(j1&&!H)T=X.shift()+L,H=!0;N+=X.pop(),h(I,N);break;case 5:while(X.length>0)I+=X.shift(),N+=X.shift(),Z.lineTo(I,N);break;case 6:while(X.length>0){if(I+=X.shift(),Z.lineTo(I,N),X.length===0)break;N+=X.shift(),Z.lineTo(I,N)}break;case 7:while(X.length>0){if(N+=X.shift(),Z.lineTo(I,N),X.length===0)break;I+=X.shift(),Z.lineTo(I,N)}break;case 8:while(X.length>0)K=I+X.shift(),C=N+X.shift(),U=K+X.shift(),Y=C+X.shift(),I=U+X.shift(),N=Y+X.shift(),Z.curveTo(K,C,U,Y,I,N);break;case 10:if(q=X.pop()+V,P=F[q],P)g(P);break;case 11:return;case 12:switch(b=f[j],j+=1,b){case 35:K=I+X.shift(),C=N+X.shift(),U=K+X.shift(),Y=C+X.shift(),O=U+X.shift(),w=Y+X.shift(),k=O+X.shift(),S=w+X.shift(),_=k+X.shift(),W=S+X.shift(),I=_+X.shift(),N=W+X.shift(),X.shift(),Z.curveTo(K,C,U,Y,O,w),Z.curveTo(k,S,_,W,I,N);break;case 34:K=I+X.shift(),C=N,U=K+X.shift(),Y=C+X.shift(),O=U+X.shift(),w=Y,k=O+X.shift(),S=Y,_=k+X.shift(),W=N,I=_+X.shift(),Z.curveTo(K,C,U,Y,O,w),Z.curveTo(k,S,_,W,I,N);break;case 36:K=I+X.shift(),C=N+X.shift(),U=K+X.shift(),Y=C+X.shift(),O=U+X.shift(),w=Y,k=O+X.shift(),S=Y,_=k+X.shift(),W=S+X.shift(),I=_+X.shift(),Z.curveTo(K,C,U,Y,O,w),Z.curveTo(k,S,_,W,I,N);break;case 37:if(K=I+X.shift(),C=N+X.shift(),U=K+X.shift(),Y=C+X.shift(),O=U+X.shift(),w=Y+X.shift(),k=O+X.shift(),S=w+X.shift(),_=k+X.shift(),W=S+X.shift(),Math.abs(_-I)>Math.abs(W-N))I=_+X.shift();else N=W+X.shift();Z.curveTo(K,C,U,Y,O,w),Z.curveTo(k,S,_,W,I,N);break;default:console.log("Glyph "+Q.index+": unknown operator 1200"+b),X.length=0}break;case 14:if(X.length>0&&!H)T=X.shift()+L,H=!0;if($)Z.closePath(),$=!1;break;case 18:y();break;case 19:case 20:y(),j+=E+7>>3;break;case 21:if(X.length>2&&!H)T=X.shift()+L,H=!0;N+=X.pop(),I+=X.pop(),h(I,N);break;case 22:if(X.length>1&&!H)T=X.shift()+L,H=!0;I+=X.pop(),h(I,N);break;case 23:y();break;case 24:while(X.length>2)K=I+X.shift(),C=N+X.shift(),U=K+X.shift(),Y=C+X.shift(),I=U+X.shift(),N=Y+X.shift(),Z.curveTo(K,C,U,Y,I,N);I+=X.shift(),N+=X.shift(),Z.lineTo(I,N);break;case 25:while(X.length>6)I+=X.shift(),N+=X.shift(),Z.lineTo(I,N);K=I+X.shift(),C=N+X.shift(),U=K+X.shift(),Y=C+X.shift(),I=U+X.shift(),N=Y+X.shift(),Z.curveTo(K,C,U,Y,I,N);break;case 26:if(X.length%2)I+=X.shift();while(X.length>0)K=I,C=N+X.shift(),U=K+X.shift(),Y=C+X.shift(),I=U,N=Y+X.shift(),Z.curveTo(K,C,U,Y,I,N);break;case 27:if(X.length%2)N+=X.shift();while(X.length>0)K=I+X.shift(),C=N,U=K+X.shift(),Y=C+X.shift(),I=U+X.shift(),N=Y,Z.curveTo(K,C,U,Y,I,N);break;case 28:u=f[j],d=f[j+1],X.push((u<<24|d<<16)>>16),j+=2;break;case 29:if(q=X.pop()+A.gsubrsBias,P=A.gsubrs[q],P)g(P);break;case 30:while(X.length>0){if(K=I,C=N+X.shift(),U=K+X.shift(),Y=C+X.shift(),I=U+X.shift(),N=Y+(X.length===1?X.shift():0),Z.curveTo(K,C,U,Y,I,N),X.length===0)break;K=I+X.shift(),C=N,U=K+X.shift(),Y=C+X.shift(),N=Y+X.shift(),I=U+(X.length===1?X.shift():0),Z.curveTo(K,C,U,Y,I,N)}break;case 31:while(X.length>0){if(K=I+X.shift(),C=N,U=K+X.shift(),Y=C+X.shift(),N=Y+X.shift(),I=U+(X.length===1?X.shift():0),Z.curveTo(K,C,U,Y,I,N),X.length===0)break;K=I,C=N+X.shift(),U=K+X.shift(),Y=C+X.shift(),I=U+X.shift(),N=Y+(X.length===1?X.shift():0),Z.curveTo(K,C,U,Y,I,N)}break;default:if(b<32)console.log("Glyph "+Q.index+": unknown operator "+b);else if(b<247)X.push(b-139);else if(b<251)u=f[j],j+=1,X.push((b-247)*256+u+108);else if(b<255)u=f[j],j+=1,X.push(-(b-251)*256-u-108);else u=f[j],d=f[j+1],n=f[j+2],B=f[j+3],j+=4,X.push((u<<24|d<<16|n<<8|B)/65536)}}}return g(J),Q.advanceWidth=T,Z}function GY1(A,Q,J,K){var C=[],U,Y=new jA.Parser(A,Q),Z=Y.parseCard8();if(Z===0)for(var X=0;X=K)throw new Error("CFF table CID Font FDSelect has bad FD index value "+U+" (FD count "+K+")");C.push(U)}else if(Z===3){var E=Y.parseCard16(),H=Y.parseCard16();if(H!==0)throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID "+H);var $;for(var I=0;I=K)throw new Error("CFF table CID Font FDSelect has bad FD index value "+U+" (FD count "+K+")");if($>J)throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID "+$);for(;H<$;H++)C.push(U);H=$}if($!==J)throw new Error("CFF Table CID Font FDSelect format 3 range has bad final GID "+$)}else throw new Error("CFF Table CID Font FDSelect table has unsupported format "+Z);return C}function WY1(A,Q,J,K){J.tables.cff={};var C=XY1(A,Q),U=V4(A,C.endOffset,jA.bytesToString),Y=V4(A,U.endOffset),Z=V4(A,Y.endOffset,jA.bytesToString),X=V4(A,Z.endOffset);J.gsubrs=X.objects,J.gsubrsBias=pz(J.gsubrs);var E=ju(A,Q,Y.objects,Z.objects);if(E.length!==1)throw new Error("CFF table has too many fonts in 'FontSet' - count of fonts NameIndex.length = "+E.length);var H=E[0];if(J.tables.cff.topDict=H,H._privateDict)J.defaultWidthX=H._privateDict.defaultWidthX,J.nominalWidthX=H._privateDict.nominalWidthX;if(H.ros[0]!==void 0&&H.ros[1]!==void 0)J.isCIDFont=!0;if(J.isCIDFont){var{fdArray:$,fdSelect:I}=H;if($===0||I===0)throw new Error("Font is marked as a CID font, but FDArray and/or FDSelect information is missing");$+=Q;var N=V4(A,$),F=ju(A,Q,N.objects,Z.objects);H._fdArray=F,I+=Q,H._fdSelect=GY1(A,I,J.numGlyphs,F.length)}var V=Q+H.private[1],D=Rm(A,V,H.private[0],Z.objects);if(J.defaultWidthX=D.defaultWidthX,J.nominalWidthX=D.nominalWidthX,D.subrs!==0){var L=V+D.subrs,R=V4(A,L);J.subrs=R.objects,J.subrsBias=pz(J.subrs)}else J.subrs=[],J.subrsBias=0;var M;if(K.lowMemory)M=CY1(A,Q+H.charStrings),J.nGlyphs=M.offsets.length;else M=V4(A,Q+H.charStrings),J.nGlyphs=M.objects.length;var T=$Y1(A,Q+H.charset,J.nGlyphs,Z.objects);if(H.encoding===0)J.cffEncoding=new aG(aC1,T);else if(H.encoding===1)J.cffEncoding=new aG(rC1,T);else J.cffEncoding=HY1(A,Q+H.encoding,T);if(J.encoding=J.encoding||J.cffEncoding,J.glyphs=new X3.GlyphSet(J),K.lowMemory)J._push=function(g){var f=YY1(g,M.offsets,A,Q+H.charStrings);J.glyphs.push(g,X3.cffGlyphLoader(J,g,vu,f))};else for(var h=0;h=0)J=K;if(K=Q.indexOf(A),K>=0)J=K+cG.length;else J=cG.length+Q.length,Q.push(A);return J}function IY1(){return new c0.Record("Header",[{name:"major",type:"Card8",value:1},{name:"minor",type:"Card8",value:0},{name:"hdrSize",type:"Card8",value:4},{name:"major",type:"Card8",value:1}])}function qY1(A){var Q=new c0.Record("Name INDEX",[{name:"names",type:"INDEX",value:[]}]);Q.names=[];for(var J=0;J=J.begin&&A=1)J.ulCodePageRange1=K.parseULong(),J.ulCodePageRange2=K.parseULong();if(J.version>=2)J.sxHeight=K.parseShort(),J.sCapHeight=K.parseShort(),J.usDefaultChar=K.parseUShort(),J.usBreakChar=K.parseUShort(),J.usMaxContent=K.parseUShort();return J}function tY1(A){return new c0.Table("OS/2",[{name:"version",type:"USHORT",value:3},{name:"xAvgCharWidth",type:"SHORT",value:0},{name:"usWeightClass",type:"USHORT",value:0},{name:"usWidthClass",type:"USHORT",value:0},{name:"fsType",type:"USHORT",value:0},{name:"ySubscriptXSize",type:"SHORT",value:650},{name:"ySubscriptYSize",type:"SHORT",value:699},{name:"ySubscriptXOffset",type:"SHORT",value:0},{name:"ySubscriptYOffset",type:"SHORT",value:140},{name:"ySuperscriptXSize",type:"SHORT",value:650},{name:"ySuperscriptYSize",type:"SHORT",value:699},{name:"ySuperscriptXOffset",type:"SHORT",value:0},{name:"ySuperscriptYOffset",type:"SHORT",value:479},{name:"yStrikeoutSize",type:"SHORT",value:49},{name:"yStrikeoutPosition",type:"SHORT",value:258},{name:"sFamilyClass",type:"SHORT",value:0},{name:"bFamilyType",type:"BYTE",value:0},{name:"bSerifStyle",type:"BYTE",value:0},{name:"bWeight",type:"BYTE",value:0},{name:"bProportion",type:"BYTE",value:0},{name:"bContrast",type:"BYTE",value:0},{name:"bStrokeVariation",type:"BYTE",value:0},{name:"bArmStyle",type:"BYTE",value:0},{name:"bLetterform",type:"BYTE",value:0},{name:"bMidline",type:"BYTE",value:0},{name:"bXHeight",type:"BYTE",value:0},{name:"ulUnicodeRange1",type:"ULONG",value:0},{name:"ulUnicodeRange2",type:"ULONG",value:0},{name:"ulUnicodeRange3",type:"ULONG",value:0},{name:"ulUnicodeRange4",type:"ULONG",value:0},{name:"achVendID",type:"CHARARRAY",value:"XXXX"},{name:"fsSelection",type:"USHORT",value:0},{name:"usFirstCharIndex",type:"USHORT",value:0},{name:"usLastCharIndex",type:"USHORT",value:0},{name:"sTypoAscender",type:"SHORT",value:0},{name:"sTypoDescender",type:"SHORT",value:0},{name:"sTypoLineGap",type:"SHORT",value:0},{name:"usWinAscent",type:"USHORT",value:0},{name:"usWinDescent",type:"USHORT",value:0},{name:"ulCodePageRange1",type:"ULONG",value:0},{name:"ulCodePageRange2",type:"ULONG",value:0},{name:"sxHeight",type:"SHORT",value:0},{name:"sCapHeight",type:"SHORT",value:0},{name:"usDefaultChar",type:"USHORT",value:0},{name:"usBreakChar",type:"USHORT",value:0},{name:"usMaxContext",type:"USHORT",value:0}],A)}var bu={parse:rY1,make:tY1,unicodeRanges:mz,getUnicodeRange:aY1};function eY1(A,Q){var J={},K=new jA.Parser(A,Q);switch(J.version=K.parseVersion(),J.italicAngle=K.parseFixed(),J.underlinePosition=K.parseShort(),J.underlineThickness=K.parseShort(),J.isFixedPitch=K.parseULong(),J.minMemType42=K.parseULong(),J.maxMemType42=K.parseULong(),J.minMemType1=K.parseULong(),J.maxMemType1=K.parseULong(),J.version){case 1:J.names=ZJ.slice();break;case 2:J.numberOfGlyphs=K.parseUShort(),J.glyphNameIndex=new Array(J.numberOfGlyphs);for(var C=0;C=ZJ.length){var Y=K.parseChar();J.names.push(K.parseString(Y))}break;case 2.5:J.numberOfGlyphs=K.parseUShort(),J.offset=new Array(J.numberOfGlyphs);for(var Z=0;Z$.value.tag)return 1;else return-1}),Q.fields=Q.fields.concat(K),Q.fields=Q.fields.concat(C),Q}function uu(A,Q,J){for(var K=0;K0){var U=A.glyphs.get(C);return U.getMetrics()}}return J}function WU1(A){var Q=0;for(var J=0;JD||X===void 0){if(D>0)X=D}if(E 123 are reserved for internal usage");if(V.name===".notdef")continue;var R=V.getMetrics();Q.push(R.xMin),J.push(R.yMin),K.push(R.xMax),C.push(R.yMax),Y.push(R.leftSideBearing),Z.push(R.rightSideBearing),U.push(V.advanceWidth)}var M={xMin:Math.min.apply(null,Q),yMin:Math.min.apply(null,J),xMax:Math.max.apply(null,K),yMax:Math.max.apply(null,C),advanceWidthMax:Math.max.apply(null,U),advanceWidthAvg:WU1(U),minLeftSideBearing:Math.min.apply(null,Y),maxLeftSideBearing:Math.max.apply(null,Y),minRightSideBearing:Math.min.apply(null,Z)};M.ascender=A.ascender,M.descender=A.descender;var T=PY1.make({flags:3,unitsPerEm:A.unitsPerEm,xMin:M.xMin,yMin:M.yMin,xMax:M.xMax,yMax:M.yMax,lowestRecPPEM:3,createdTimestamp:A.createdTimestamp}),h=kY1.make({ascender:M.ascender,descender:M.descender,advanceWidthMax:M.advanceWidthMax,minLeftSideBearing:M.minLeftSideBearing,minRightSideBearing:M.minRightSideBearing,xMaxExtent:M.maxLeftSideBearing+(M.xMax-M.xMin),numberOfHMetrics:A.glyphs.length}),y=uY1.make(A.glyphs.length),g=bu.make(Object.assign({xAvgCharWidth:Math.round(M.advanceWidthAvg),usFirstCharIndex:X,usLastCharIndex:E,ulUnicodeRange1:H,ulUnicodeRange2:$,ulUnicodeRange3:I,ulUnicodeRange4:N,sTypoAscender:M.ascender,sTypoDescender:M.descender,sTypoLineGap:0,usWinAscent:M.yMax,usWinDescent:Math.abs(M.yMin),ulCodePageRange1:1,sxHeight:uu(A,"xyvw",{yMax:Math.round(M.ascender/2)}).yMax,sCapHeight:uu(A,"HIKLEFJMNTZBDPRAGOQSUVWXY",M).yMax,usDefaultChar:A.hasChar(" ")?32:0,usBreakChar:A.hasChar(" ")?32:0},A.tables.os2)),f=yY1.make(A.glyphs),u=iC1.make(A.glyphs),d=A.getEnglishName("fontFamily"),n=A.getEnglishName("fontSubfamily"),B=d+" "+n,q=A.getEnglishName("postScriptName");if(!q)q=d.replace(/\s/g,"")+"-"+n;var P={};for(var O in A.names)P[O]=A.names[O];if(!P.uniqueID)P.uniqueID={en:A.getEnglishName("manufacturer")+":"+B};if(!P.postScriptName)P.postScriptName={en:q};if(!P.preferredFamily)P.preferredFamily=A.names.fontFamily;if(!P.preferredSubfamily)P.preferredSubfamily=A.names.fontSubfamily;var w=[],k=iY1.make(P,w),S=w.length>0?bY1.make(w):void 0,_=QU1.make(),W=VY1.make(A.glyphs,{version:A.getEnglishName("version"),fullName:B,familyName:d,weightName:n,postScriptName:q,unitsPerEm:A.unitsPerEm,fontBBox:[0,M.yMin,M.ascender,M.advanceWidthMax]}),j=A.metas&&Object.keys(A.metas).length>0?ZU1.make(A.metas):void 0,b=[T,h,y,g,k,u,_,W,f];if(S)b.push(S);if(A.tables.gsub)b.push(CU1.make(A.tables.gsub));if(A.tables.cpal)b.push(GU1.make(A.tables.cpal));if(A.tables.colr)b.push(EU1.make(A.tables.colr));if(j)b.push(j);var p=_m(b),s=p.encode(),r=sz(s),A1=p.fields,Q1=!1;for(var e=0;e>>1,U=A[C].tag;if(U===Q)return C;else if(U>>1,U=A[C];if(U===Q)return C;else if(U>>1;J=A[U];var Y=J.start;if(Y===Q)return J;else if(Y0){if(J=A[K-1],Q>J.end)return 0;return J}}function YB(A,Q){this.font=A,this.tableName=Q}YB.prototype={searchTag:kz,binSearch:mu,getTable:function(A){var Q=this.font.tables[this.tableName];if(!Q&&A)Q=this.font.tables[this.tableName]=this.createDefaultTable();return Q},getScriptNames:function(){var A=this.getTable();if(!A)return[];return A.scripts.map(function(Q){return Q.tag})},getDefaultScriptName:function(){var A=this.getTable();if(!A)return;var Q=!1;for(var J=0;J=0)return K[C].script;else if(Q){var U={tag:A,script:{defaultLangSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]},langSysRecords:[]}};return K.splice(-1-C,0,U),U.script}}},getLangSysTable:function(A,Q,J){var K=this.getScriptTable(A,J);if(K){if(!Q||Q==="dflt"||Q==="DFLT")return K.defaultLangSys;var C=kz(K.langSysRecords,Q);if(C>=0)return K.langSysRecords[C].langSys;else if(J){var U={tag:Q,langSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]}};return K.langSysRecords.splice(-1-C,0,U),U.langSys}}},getFeatureTable:function(A,Q,J,K){var C=this.getLangSysTable(A,Q,K);if(C){var U,Y=C.featureIndexes,Z=this.font.tables[this.tableName].features;for(var X=0;X=Z[E-1].tag,"Features must be added in alphabetical order."),U={tag:J,feature:{params:0,lookupListIndexes:[]}},Z.push(U),Y.push(E),U.feature}}},getLookupTables:function(A,Q,J,K,C){var U=this.getFeatureTable(A,Q,J,C),Y=[];if(U){var Z,X=U.lookupListIndexes,E=this.font.tables[this.tableName].lookups;for(var H=0;H=0?J:-1;case 2:var K=cu(A.ranges,Q);return K?K.index+Q-K.start:-1}},expandCoverage:function(A){if(A.format===1)return A.glyphs;else{var Q=[],J=A.ranges;for(var K=0;K1,'Multiple: "by" must be an array of two or more ids');var C=this.getLookupTables(J,K,A,2,!0)[0],U=oz(C,1,{substFormat:1,coverage:{format:1,glyphs:[]},sequences:[]});WA.assert(U.coverage.format===1,"Multiple: unable to modify coverage table format "+U.coverage.format);var Y=Q.sub,Z=this.binSearch(U.coverage.glyphs,Y);if(Z<0)Z=-1-Z,U.coverage.glyphs.splice(Z,0,Y),U.sequences.splice(Z,0,0);U.sequences[Z]=Q.by};G9.prototype.addAlternate=function(A,Q,J,K){var C=this.getLookupTables(J,K,A,3,!0)[0],U=oz(C,1,{substFormat:1,coverage:{format:1,glyphs:[]},alternateSets:[]});WA.assert(U.coverage.format===1,"Alternate: unable to modify coverage table format "+U.coverage.format);var Y=Q.sub,Z=this.binSearch(U.coverage.glyphs,Y);if(Z<0)Z=-1-Z,U.coverage.glyphs.splice(Z,0,Y),U.alternateSets.splice(Z,0,0);U.alternateSets[Z]=Q.by};G9.prototype.addLigature=function(A,Q,J,K){var C=this.getLookupTables(J,K,A,4,!0)[0],U=C.subtables[0];if(!U)U={substFormat:1,coverage:{format:1,glyphs:[]},ligatureSets:[]},C.subtables[0]=U;WA.assert(U.coverage.format===1,"Ligature: unable to modify coverage table format "+U.coverage.format);var Y=Q.sub[0],Z=Q.sub.slice(1),X={ligGlyph:Q.by,components:Z},E=this.binSearch(U.coverage.glyphs,Y);if(E>=0){var H=U.ligatureSets[E];for(var $=0;$0){if(U=A.parseByte(),(Q&C)===0)U=-U;U=J+U}else if((Q&C)>0)U=J;else U=J+A.parseShort();return U}function Tm(A,Q,J){var K=new jA.Parser(Q,J);A.numberOfContours=K.parseShort(),A._xMin=K.parseShort(),A._yMin=K.parseShort(),A._xMax=K.parseShort(),A._yMax=K.parseShort();var C,U;if(A.numberOfContours>0){var Y=A.endPointIndices=[];for(var Z=0;Z0){var $=K.parseByte();for(var I=0;I<$;I+=1)C.push(U),H+=1}if(WA.argument(C.length===E,"Bad flags."),Y.length>0){var N=[],F;if(E>0){for(var V=0;V=0,N.push(F);var D=0;for(var L=0;L0)if((C&2)>0)h.dx=K.parseShort(),h.dy=K.parseShort();else h.matchedPoints=[K.parseUShort(),K.parseUShort()];else if((C&2)>0)h.dx=K.parseChar(),h.dy=K.parseChar();else h.matchedPoints=[K.parseByte(),K.parseByte()];if((C&8)>0)h.xScale=h.yScale=K.parseF2Dot14();else if((C&64)>0)h.xScale=K.parseF2Dot14(),h.yScale=K.parseF2Dot14();else if((C&128)>0)h.xScale=K.parseF2Dot14(),h.scale01=K.parseF2Dot14(),h.scale10=K.parseF2Dot14(),h.yScale=K.parseF2Dot14();A.components.push(h),T=!!(C&32)}if(C&256){A.instructionLength=K.parseUShort(),A.instructions=[];for(var y=0;yQ.points.length-1||K.matchedPoints[1]>C.points.length-1)throw Error("Matched points out of range in "+Q.name);var Y=Q.points[K.matchedPoints[0]],Z=C.points[K.matchedPoints[1]],X={xScale:K.xScale,scale01:K.scale01,scale10:K.scale10,yScale:K.yScale,dx:0,dy:0};Z=Sz([Z],X)[0],X.dx=Y.x-Z.x,X.dy=Y.y-Z.y,U=Sz(C.points,X)}Q.points=Q.points.concat(U)}}return km(Q.points)}function LU1(A,Q,J,K){var C=new X3.GlyphSet(K);for(var U=0;U2)return;var J=this.font,K=this._prepState;if(!K||K.ppem!==Q){var C=this._fpgmState;if(!C){if(M4.prototype=_U1,C=this._fpgmState=new M4("fpgm",J.tables.fpgm),C.funcs=[],C.font=J,AS1.DEBUG)console.log("---EXEC FPGM---"),C.step=-1;try{XJ(C)}catch(E){console.log("Hinting error in FPGM:"+E),this._errorState=3;return}}M4.prototype=C,K=this._prepState=new M4("prep",J.tables.prep),K.ppem=Q;var U=J.tables.cvt;if(U){var Y=K.cvt=new Array(U.length),Z=Q/J.unitsPerEm;for(var X=0;X1)return;try{return vm(A,K)}catch(E){if(this._errorState<1)console.log("Hinting error:"+E),console.log("Note: further hinting errors are silenced");this._errorState=1;return}};vm=function(A,Q){var J=Q.ppem/Q.font.unitsPerEm,K=J,C=A.components,U,Y,Z;if(M4.prototype=Q,!C){if(Z=new M4("glyf",A.instructions),AS1.DEBUG)console.log("---EXEC GLYPH---"),Z.step=-1;cz(A,Z,J,K),Y=Z.gZone}else{var X=Q.font;Y=[],U=[];for(var E=0;E=176&&U<=183)K+=U-176+1;else if(U>=184&&U<=191)K+=(U-184+1)*2;else if(Q&&C===1&&U===27)break;while(C>0);A.ip=K}function lu(A,Q){if(AS1.DEBUG)console.log(Q.step,"SVTCA["+A.axis+"]");Q.fv=Q.pv=Q.dpv=A}function nu(A,Q){if(AS1.DEBUG)console.log(Q.step,"SPVTCA["+A.axis+"]");Q.pv=Q.dpv=A}function su(A,Q){if(AS1.DEBUG)console.log(Q.step,"SFVTCA["+A.axis+"]");Q.fv=A}function ou(A,Q){var J=Q.stack,K=J.pop(),C=J.pop(),U=Q.z2[K],Y=Q.z1[C];if(AS1.DEBUG)console.log("SPVTL["+A+"]",K,C);var Z,X;if(!A)Z=Y.x-U.x,X=Y.y-U.y;else Z=U.y-Y.y,X=Y.x-U.x;Q.pv=Q.dpv=BB(Z,X)}function iu(A,Q){var J=Q.stack,K=J.pop(),C=J.pop(),U=Q.z2[K],Y=Q.z1[C];if(AS1.DEBUG)console.log("SFVTL["+A+"]",K,C);var Z,X;if(!A)Z=Y.x-U.x,X=Y.y-U.y;else Z=U.y-Y.y,X=Y.x-U.x;Q.fv=BB(Z,X)}function TU1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"SPVFS[]",J,K);A.pv=A.dpv=BB(K,J)}function kU1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"SPVFS[]",J,K);A.fv=BB(K,J)}function SU1(A){var{stack:Q,pv:J}=A;if(AS1.DEBUG)console.log(A.step,"GPV[]");Q.push(J.x*16384),Q.push(J.y*16384)}function jU1(A){var{stack:Q,fv:J}=A;if(AS1.DEBUG)console.log(A.step,"GFV[]");Q.push(J.x*16384),Q.push(J.y*16384)}function vU1(A){if(A.fv=A.pv,AS1.DEBUG)console.log(A.step,"SFVTPV[]")}function xU1(A){var Q=A.stack,J=Q.pop(),K=Q.pop(),C=Q.pop(),U=Q.pop(),Y=Q.pop(),Z=A.z0,X=A.z1,E=Z[J],H=Z[K],$=X[C],I=X[U],N=A.z2[Y];if(AS1.DEBUG)console.log("ISECT[], ",J,K,C,U,Y);var{x:F,y:V}=E,D=H.x,L=H.y,R=$.x,M=$.y,T=I.x,h=I.y,y=(F-D)*(M-h)-(V-L)*(R-T),g=F*L-V*D,f=R*h-M*T;N.x=(g*(R-T)-f*(F-D))/y,N.y=(g*(M-h)-f*(V-L))/y}function yU1(A){if(A.rp0=A.stack.pop(),AS1.DEBUG)console.log(A.step,"SRP0[]",A.rp0)}function hU1(A){if(A.rp1=A.stack.pop(),AS1.DEBUG)console.log(A.step,"SRP1[]",A.rp1)}function gU1(A){if(A.rp2=A.stack.pop(),AS1.DEBUG)console.log(A.step,"SRP2[]",A.rp2)}function bU1(A){var Q=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"SZP0[]",Q);switch(A.zp0=Q,Q){case 0:if(!A.tZone)rG(A);A.z0=A.tZone;break;case 1:A.z0=A.gZone;break;default:throw new Error("Invalid zone pointer")}}function fU1(A){var Q=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"SZP1[]",Q);switch(A.zp1=Q,Q){case 0:if(!A.tZone)rG(A);A.z1=A.tZone;break;case 1:A.z1=A.gZone;break;default:throw new Error("Invalid zone pointer")}}function pU1(A){var Q=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"SZP2[]",Q);switch(A.zp2=Q,Q){case 0:if(!A.tZone)rG(A);A.z2=A.tZone;break;case 1:A.z2=A.gZone;break;default:throw new Error("Invalid zone pointer")}}function uU1(A){var Q=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"SZPS[]",Q);switch(A.zp0=A.zp1=A.zp2=Q,Q){case 0:if(!A.tZone)rG(A);A.z0=A.z1=A.z2=A.tZone;break;case 1:A.z0=A.z1=A.z2=A.gZone;break;default:throw new Error("Invalid zone pointer")}}function mU1(A){if(A.loop=A.stack.pop(),AS1.DEBUG)console.log(A.step,"SLOOP[]",A.loop)}function cU1(A){if(AS1.DEBUG)console.log(A.step,"RTG[]");A.round=ym}function dU1(A){if(AS1.DEBUG)console.log(A.step,"RTHG[]");A.round=MU1}function lU1(A){var Q=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"SMD[]",Q);A.minDis=Q/64}function nU1(A){if(AS1.DEBUG)console.log(A.step,"ELSE[]");gm(A,!1)}function sU1(A){var Q=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"JMPR[]",Q);A.ip+=Q-1}function oU1(A){var Q=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"SCVTCI[]",Q);A.cvCutIn=Q/64}function iU1(A){var Q=A.stack;if(AS1.DEBUG)console.log(A.step,"DUP[]");Q.push(Q[Q.length-1])}function jz(A){if(AS1.DEBUG)console.log(A.step,"POP[]");A.stack.pop()}function aU1(A){if(AS1.DEBUG)console.log(A.step,"CLEAR[]");A.stack.length=0}function rU1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"SWAP[]");Q.push(J),Q.push(K)}function tU1(A){var Q=A.stack;if(AS1.DEBUG)console.log(A.step,"DEPTH[]");Q.push(Q.length)}function eU1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"LOOPCALL[]",J,K);var{ip:C,prog:U}=A;A.prog=A.funcs[J];for(var Y=0;Y1?"loop "+(Q.loop-Z)+": ":"")+"SHP["+(A?"rp1":"rp2")+"]",E)}Q.loop=1}function eu(A,Q){var J=Q.stack,K=A?Q.rp1:Q.rp2,C=(A?Q.z0:Q.z1)[K],U=Q.fv,Y=Q.pv,Z=J.pop(),X=Q.z2[Q.contours[Z]],E=X;if(AS1.DEBUG)console.log(Q.step,"SHC["+A+"]",Z);var H=Y.distance(C,C,!1,!0);do{if(E!==C)U.setRelative(E,E,H,Y);E=E.nextPointOnContour}while(E!==X)}function Am(A,Q){var J=Q.stack,K=A?Q.rp1:Q.rp2,C=(A?Q.z0:Q.z1)[K],U=Q.fv,Y=Q.pv,Z=J.pop();if(AS1.DEBUG)console.log(Q.step,"SHZ["+A+"]",Z);var X;switch(Z){case 0:X=Q.tZone;break;case 1:X=Q.gZone;break;default:throw new Error("Invalid zone")}var E,H=Y.distance(C,C,!1,!0),$=X.length-2;for(var I=0;I<$;I++)E=X[I],U.setRelative(E,E,H,Y)}function CZ1(A){var{stack:Q,loop:J,fv:K}=A,C=Q.pop()/64,U=A.z2;while(J--){var Y=Q.pop(),Z=U[Y];if(AS1.DEBUG)console.log(A.step,(A.loop>1?"loop "+(A.loop-J)+": ":"")+"SHPIX[]",Y,C);K.setRelative(Z,Z,C),K.touch(Z)}A.loop=1}function YZ1(A){var{stack:Q,rp1:J,rp2:K,loop:C}=A,U=A.z0[J],Y=A.z1[K],Z=A.fv,X=A.dpv,E=A.z2;while(C--){var H=Q.pop(),$=E[H];if(AS1.DEBUG)console.log(A.step,(A.loop>1?"loop "+(A.loop-C)+": ":"")+"IP[]",H,J,"<->",K);Z.interpolate($,U,Y,X),Z.touch($)}A.loop=1}function Qm(A,Q){var J=Q.stack,K=J.pop()/64,C=J.pop(),U=Q.z1[C],Y=Q.z0[Q.rp0],Z=Q.fv,X=Q.pv;if(Z.setRelative(U,Y,K,X),Z.touch(U),AS1.DEBUG)console.log(Q.step,"MSIRP["+A+"]",K,C);if(Q.rp1=Q.rp0,Q.rp2=C,A)Q.rp0=C}function UZ1(A){var{stack:Q,rp0:J}=A,K=A.z0[J],C=A.loop,U=A.fv,Y=A.pv,Z=A.z1;while(C--){var X=Q.pop(),E=Z[X];if(AS1.DEBUG)console.log(A.step,(A.loop>1?"loop "+(A.loop-C)+": ":"")+"ALIGNRP[]",X);U.setRelative(E,K,0,Y),U.touch(E)}A.loop=1}function ZZ1(A){if(AS1.DEBUG)console.log(A.step,"RTDG[]");A.round=VU1}function Jm(A,Q){var J=Q.stack,K=J.pop(),C=J.pop(),U=Q.z0[C],Y=Q.fv,Z=Q.pv,X=Q.cvt[K];if(AS1.DEBUG)console.log(Q.step,"MIAP["+A+"]",K,"(",X,")",C);var E=Z.distance(U,CB);if(A){if(Math.abs(E-X)",Z);Q.stack.push(Math.round(Z*64))}function WZ1(A){if(AS1.DEBUG)console.log(A.step,"MPPEM[]");A.stack.push(A.ppem)}function IZ1(A){if(AS1.DEBUG)console.log(A.step,"FLIPON[]");A.autoFlip=!0}function qZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"LT[]",J,K);Q.push(KJ?1:0)}function LZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"GTEQ[]",J,K);Q.push(K>=J?1:0)}function FZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"EQ[]",J,K);Q.push(J===K?1:0)}function RZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"NEQ[]",J,K);Q.push(J!==K?1:0)}function zZ1(A){var Q=A.stack,J=Q.pop();if(AS1.DEBUG)console.log(A.step,"ODD[]",J);Q.push(Math.trunc(J)%2?1:0)}function DZ1(A){var Q=A.stack,J=Q.pop();if(AS1.DEBUG)console.log(A.step,"EVEN[]",J);Q.push(Math.trunc(J)%2?0:1)}function VZ1(A){var Q=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"IF[]",Q);if(!Q){if(gm(A,!0),AS1.DEBUG)console.log(A.step,"EIF[]")}}function MZ1(A){if(AS1.DEBUG)console.log(A.step,"EIF[]")}function wZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"AND[]",J,K);Q.push(J&&K?1:0)}function PZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"OR[]",J,K);Q.push(J||K?1:0)}function _Z1(A){var Q=A.stack,J=Q.pop();if(AS1.DEBUG)console.log(A.step,"NOT[]",J);Q.push(J?0:1)}function vz(A,Q){var J=Q.stack,K=J.pop(),C=Q.fv,U=Q.pv,Y=Q.ppem,Z=Q.deltaBase+(A-1)*16,X=Q.deltaShift,E=Q.z0;if(AS1.DEBUG)console.log(Q.step,"DELTAP["+A+"]",K,J);for(var H=0;H>4);if(N!==Y)continue;var F=(I&15)-8;if(F>=0)F++;if(AS1.DEBUG)console.log(Q.step,"DELTAPFIX",$,"by",F*X);var V=E[$];C.setRelative(V,V,F*X,U)}}function TZ1(A){var Q=A.stack,J=Q.pop();if(AS1.DEBUG)console.log(A.step,"SDB[]",J);A.deltaBase=J}function kZ1(A){var Q=A.stack,J=Q.pop();if(AS1.DEBUG)console.log(A.step,"SDS[]",J);A.deltaShift=Math.pow(0.5,J)}function SZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"ADD[]",J,K);Q.push(K+J)}function jZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"SUB[]",J,K);Q.push(K-J)}function vZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"DIV[]",J,K);Q.push(K*64/J)}function xZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"MUL[]",J,K);Q.push(K*J/64)}function yZ1(A){var Q=A.stack,J=Q.pop();if(AS1.DEBUG)console.log(A.step,"ABS[]",J);Q.push(Math.abs(J))}function hZ1(A){var Q=A.stack,J=Q.pop();if(AS1.DEBUG)console.log(A.step,"NEG[]",J);Q.push(-J)}function gZ1(A){var Q=A.stack,J=Q.pop();if(AS1.DEBUG)console.log(A.step,"FLOOR[]",J);Q.push(Math.floor(J/64)*64)}function bZ1(A){var Q=A.stack,J=Q.pop();if(AS1.DEBUG)console.log(A.step,"CEILING[]",J);Q.push(Math.ceil(J/64)*64)}function mG(A,Q){var J=Q.stack,K=J.pop();if(AS1.DEBUG)console.log(Q.step,"ROUND[]");J.push(Q.round(K/64)*64)}function fZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"WCVTF[]",J,K);A.cvt[K]=J*A.ppem/A.font.unitsPerEm}function xz(A,Q){var J=Q.stack,K=J.pop(),C=Q.ppem,U=Q.deltaBase+(A-1)*16,Y=Q.deltaShift;if(AS1.DEBUG)console.log(Q.step,"DELTAC["+A+"]",K,J);for(var Z=0;Z>4);if(H!==C)continue;var $=(E&15)-8;if($>=0)$++;var I=$*Y;if(AS1.DEBUG)console.log(Q.step,"DELTACFIX",X,"by",I);Q.cvt[X]+=I}}function pZ1(A){var Q=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"SROUND[]",Q);A.round=hm;var J;switch(Q&192){case 0:J=0.5;break;case 64:J=1;break;case 128:J=2;break;default:throw new Error("invalid SROUND value")}switch(A.srPeriod=J,Q&48){case 0:A.srPhase=0;break;case 16:A.srPhase=0.25*J;break;case 32:A.srPhase=0.5*J;break;case 48:A.srPhase=0.75*J;break;default:throw new Error("invalid SROUND value")}if(Q&=15,Q===0)A.srThreshold=0;else A.srThreshold=(Q/8-0.5)*J}function uZ1(A){var Q=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"S45ROUND[]",Q);A.round=hm;var J;switch(Q&192){case 0:J=Math.sqrt(2)/2;break;case 64:J=Math.sqrt(2);break;case 128:J=2*Math.sqrt(2);break;default:throw new Error("invalid S45ROUND value")}switch(A.srPeriod=J,Q&48){case 0:A.srPhase=0;break;case 16:A.srPhase=0.25*J;break;case 32:A.srPhase=0.5*J;break;case 48:A.srPhase=0.75*J;break;default:throw new Error("invalid S45ROUND value")}if(Q&=15,Q===0)A.srThreshold=0;else A.srThreshold=(Q/8-0.5)*J}function mZ1(A){if(AS1.DEBUG)console.log(A.step,"ROFF[]");A.round=DU1}function cZ1(A){if(AS1.DEBUG)console.log(A.step,"RUTG[]");A.round=wU1}function dZ1(A){if(AS1.DEBUG)console.log(A.step,"RDTG[]");A.round=PU1}function lZ1(A){var Q=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"SCANCTRL[]",Q)}function Ym(A,Q){var J=Q.stack,K=J.pop(),C=J.pop(),U=Q.z2[K],Y=Q.z1[C];if(AS1.DEBUG)console.log(Q.step,"SDPVTL["+A+"]",K,C);var Z,X;if(!A)Z=Y.x-U.x,X=Y.y-U.y;else Z=U.y-Y.y,X=Y.x-U.x;Q.dpv=BB(Z,X)}function nZ1(A){var Q=A.stack,J=Q.pop(),K=0;if(AS1.DEBUG)console.log(A.step,"GETINFO[]",J);if(J&1)K=35;if(J&32)K|=4096;Q.push(K)}function sZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop(),C=Q.pop();if(AS1.DEBUG)console.log(A.step,"ROLL[]");Q.push(K),Q.push(J),Q.push(C)}function oZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"MAX[]",J,K);Q.push(Math.max(K,J))}function iZ1(A){var Q=A.stack,J=Q.pop(),K=Q.pop();if(AS1.DEBUG)console.log(A.step,"MIN[]",J,K);Q.push(Math.min(K,J))}function aZ1(A){var Q=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"SCANTYPE[]",Q)}function rZ1(A){var Q=A.stack.pop(),J=A.stack.pop();if(AS1.DEBUG)console.log(A.step,"INSTCTRL[]",Q,J);switch(Q){case 1:A.inhibitGridFit=!!J;return;case 2:A.ignoreCvt=!!J;return;default:throw new Error("invalid INSTCTRL[] selector")}}function z4(A,Q){var{stack:J,prog:K,ip:C}=Q;if(AS1.DEBUG)console.log(Q.step,"PUSHB["+A+"]");for(var U=0;U=0?1:-1,D=Math.abs(D),A){if(R=U.cvt[Z],K&&Math.abs(D-R)":"_")+(K?"R":"_")+(C===0?"Gr":C===1?"Bl":C===2?"Wh":"")+"]",A?Z+"("+U.cvt[Z]+","+R+")":"",X,"(d =",V,"->",L*D,")");if(U.rp1=U.rp0,U.rp2=X,Q)U.rp0=X}jm=[lu.bind(void 0,E7),lu.bind(void 0,B3),nu.bind(void 0,E7),nu.bind(void 0,B3),su.bind(void 0,E7),su.bind(void 0,B3),ou.bind(void 0,0),ou.bind(void 0,1),iu.bind(void 0,0),iu.bind(void 0,1),TU1,kU1,SU1,jU1,vU1,xU1,yU1,hU1,gU1,bU1,fU1,pU1,uU1,mU1,cU1,dU1,lU1,nU1,sU1,oU1,void 0,void 0,iU1,jz,aU1,rU1,tU1,QZ1,JZ1,void 0,void 0,void 0,eU1,AZ1,KZ1,void 0,au.bind(void 0,0),au.bind(void 0,1),ru.bind(void 0,E7),ru.bind(void 0,B3),tu.bind(void 0,0),tu.bind(void 0,1),eu.bind(void 0,0),eu.bind(void 0,1),Am.bind(void 0,0),Am.bind(void 0,1),CZ1,YZ1,Qm.bind(void 0,0),Qm.bind(void 0,1),UZ1,ZZ1,Jm.bind(void 0,0),Jm.bind(void 0,1),BZ1,XZ1,EZ1,$Z1,HZ1,GZ1,Km.bind(void 0,0),Km.bind(void 0,1),void 0,Cm.bind(void 0,0),Cm.bind(void 0,1),WZ1,void 0,IZ1,void 0,void 0,qZ1,OZ1,NZ1,LZ1,FZ1,RZ1,zZ1,DZ1,VZ1,MZ1,wZ1,PZ1,_Z1,vz.bind(void 0,1),TZ1,kZ1,SZ1,jZ1,vZ1,xZ1,yZ1,hZ1,gZ1,bZ1,mG.bind(void 0,0),mG.bind(void 0,1),mG.bind(void 0,2),mG.bind(void 0,3),void 0,void 0,void 0,void 0,fZ1,vz.bind(void 0,2),vz.bind(void 0,3),xz.bind(void 0,1),xz.bind(void 0,2),xz.bind(void 0,3),pZ1,uZ1,void 0,void 0,mZ1,void 0,cZ1,dZ1,jz,jz,void 0,void 0,void 0,void 0,void 0,lZ1,Ym.bind(void 0,0),Ym.bind(void 0,1),nZ1,void 0,sZ1,oZ1,iZ1,aZ1,rZ1,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,z4.bind(void 0,1),z4.bind(void 0,2),z4.bind(void 0,3),z4.bind(void 0,4),z4.bind(void 0,5),z4.bind(void 0,6),z4.bind(void 0,7),z4.bind(void 0,8),D4.bind(void 0,1),D4.bind(void 0,2),D4.bind(void 0,3),D4.bind(void 0,4),D4.bind(void 0,5),D4.bind(void 0,6),D4.bind(void 0,7),D4.bind(void 0,8),l0.bind(void 0,0,0,0,0,0),l0.bind(void 0,0,0,0,0,1),l0.bind(void 0,0,0,0,0,2),l0.bind(void 0,0,0,0,0,3),l0.bind(void 0,0,0,0,1,0),l0.bind(void 0,0,0,0,1,1),l0.bind(void 0,0,0,0,1,2),l0.bind(void 0,0,0,0,1,3),l0.bind(void 0,0,0,1,0,0),l0.bind(void 0,0,0,1,0,1),l0.bind(void 0,0,0,1,0,2),l0.bind(void 0,0,0,1,0,3),l0.bind(void 0,0,0,1,1,0),l0.bind(void 0,0,0,1,1,1),l0.bind(void 0,0,0,1,1,2),l0.bind(void 0,0,0,1,1,3),l0.bind(void 0,0,1,0,0,0),l0.bind(void 0,0,1,0,0,1),l0.bind(void 0,0,1,0,0,2),l0.bind(void 0,0,1,0,0,3),l0.bind(void 0,0,1,0,1,0),l0.bind(void 0,0,1,0,1,1),l0.bind(void 0,0,1,0,1,2),l0.bind(void 0,0,1,0,1,3),l0.bind(void 0,0,1,1,0,0),l0.bind(void 0,0,1,1,0,1),l0.bind(void 0,0,1,1,0,2),l0.bind(void 0,0,1,1,0,3),l0.bind(void 0,0,1,1,1,0),l0.bind(void 0,0,1,1,1,1),l0.bind(void 0,0,1,1,1,2),l0.bind(void 0,0,1,1,1,3),l0.bind(void 0,1,0,0,0,0),l0.bind(void 0,1,0,0,0,1),l0.bind(void 0,1,0,0,0,2),l0.bind(void 0,1,0,0,0,3),l0.bind(void 0,1,0,0,1,0),l0.bind(void 0,1,0,0,1,1),l0.bind(void 0,1,0,0,1,2),l0.bind(void 0,1,0,0,1,3),l0.bind(void 0,1,0,1,0,0),l0.bind(void 0,1,0,1,0,1),l0.bind(void 0,1,0,1,0,2),l0.bind(void 0,1,0,1,0,3),l0.bind(void 0,1,0,1,1,0),l0.bind(void 0,1,0,1,1,1),l0.bind(void 0,1,0,1,1,2),l0.bind(void 0,1,0,1,1,3),l0.bind(void 0,1,1,0,0,0),l0.bind(void 0,1,1,0,0,1),l0.bind(void 0,1,1,0,0,2),l0.bind(void 0,1,1,0,0,3),l0.bind(void 0,1,1,0,1,0),l0.bind(void 0,1,1,0,1,1),l0.bind(void 0,1,1,0,1,2),l0.bind(void 0,1,1,0,1,3),l0.bind(void 0,1,1,1,0,0),l0.bind(void 0,1,1,1,0,1),l0.bind(void 0,1,1,1,0,2),l0.bind(void 0,1,1,1,0,3),l0.bind(void 0,1,1,1,1,0),l0.bind(void 0,1,1,1,1,1),l0.bind(void 0,1,1,1,1,2),l0.bind(void 0,1,1,1,1,3)];function iC(A){this.char=A,this.state={},this.activeState=null}function iz(A,Q,J){this.contextName=J,this.startIndex=A,this.endOffset=Q}function tZ1(A,Q,J){this.contextName=A,this.openRange=null,this.ranges=[],this.checkStart=Q,this.checkEnd=J}function P5(A,Q){this.context=A,this.index=Q,this.length=A.length,this.current=A[Q],this.backtrack=A.slice(0,Q),this.lookahead=A.slice(Q+1)}function tG(A){this.eventId=A,this.subscribers=[]}function eZ1(A){var Q=this,J=["start","end","next","newToken","contextStart","contextEnd","insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD","updateContextsRanges"];if(J.forEach(function(C){Object.defineProperty(Q.events,C,{value:new tG(C)})}),A)J.forEach(function(C){var U=A[C];if(typeof U==="function")Q.events[C].subscribe(U)});var K=["insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD"];K.forEach(function(C){Q.events[C].subscribe(Q.updateContextsRanges)})}function C8(A){this.tokens=[],this.registeredContexts={},this.contextCheckers=[],this.events={},this.registeredModifiers=[],eZ1.call(this,A)}iC.prototype.setState=function(A,Q){return this.state[A]=Q,this.activeState={key:A,value:this.state[A]},this.activeState};iC.prototype.getState=function(A){return this.state[A]||null};C8.prototype.inboundIndex=function(A){return A>=0&&A0&&A<=this.lookahead.length):return this.lookahead[A-1];default:return null}};C8.prototype.rangeToText=function(A){if(A instanceof iz)return this.getRangeTokens(A).map(function(Q){return Q.char}).join("")};C8.prototype.getText=function(){return this.tokens.map(function(A){return A.char}).join("")};C8.prototype.getContext=function(A){var Q=this.registeredContexts[A];return Q?Q:null};C8.prototype.on=function(A,Q){var J=this.events[A];if(J)return J.subscribe(Q);else return null};C8.prototype.dispatch=function(A,Q){var J=this,K=this.events[A];if(K instanceof tG)K.subscribers.forEach(function(C){C.apply(J,Q||[])})};C8.prototype.registerContextChecker=function(A,Q,J){if(this.getContext(A))return{FAIL:"context name '"+A+"' is already registered."};if(typeof Q!=="function")return{FAIL:"missing context start check."};if(typeof J!=="function")return{FAIL:"missing context end check."};var K=new tZ1(A,Q,J);return this.registeredContexts[A]=K,this.contextCheckers.push(K),K};C8.prototype.getRangeTokens=function(A){var Q=A.startIndex+A.endOffset;return[].concat(this.tokens.slice(A.startIndex,Q))};C8.prototype.getContextRanges=function(A){var Q=this.getContext(A);if(Q)return Q.ranges;else return{FAIL:"context checker '"+A+"' is not registered."}};C8.prototype.resetContextsRanges=function(){var A=this.registeredContexts;for(var Q in A)if(A.hasOwnProperty(Q)){var J=A[Q];J.ranges=[]}};C8.prototype.updateContextsRanges=function(){this.resetContextsRanges();var A=this.tokens.map(function(K){return K.char});for(var Q=0;Q=C.start&&A<=C.end){var U=A-C.start;return C.index+U}}break;default:return-1}return-1}function QB1(A,Q){var J=XB(A,Q.coverage);if(J===-1)return null;return A+Q.deltaGlyphId}function JB1(A,Q){var J=XB(A,Q.coverage);if(J===-1)return null;return Q.substitute[J]}function yz(A,Q){var J=[];for(var K=0;K=0;J--){var K=Q[J],C=bm(K),U=P4(K);if(!C&&!U)return!0;if(C)return!1}return!1}function OB1(A){if(bm(A.current))return!1;for(var Q=0;Q0)}J("fontFamily"),J("weightName"),J("manufacturer"),J("copyright"),J("version"),Q(this.unitsPerEm>0)};g2.prototype.toTables=function(){return qU1.fontToTable(this)};g2.prototype.toBuffer=function(){return console.warn("Font.toBuffer is deprecated. Use Font.toArrayBuffer instead."),this.toArrayBuffer()};g2.prototype.toArrayBuffer=function(){var A=this.toTables(),Q=A.encode(),J=new ArrayBuffer(Q.length),K=new Uint8Array(J);for(var C=0;C()=>(Q||(Q={exports:{}},A(Q.exports,Q)),Q.exports),fm=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.VERSION=void 0,A.VERSION="9.0.1"}),G2=vA((exports,module)=>{var __spreadArray=exports&&exports.__spreadArray||function(A,Q){for(var J=0,K=Q.length,C=A.length;J{(function(J,K){typeof define=="function"&&define.amd?define([],K):typeof Q=="object"&&Q.exports?Q.exports=K():J.regexpToAst=K()})(typeof self!="undefined"?self:A,function(){function J(){}J.prototype.saveState=function(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}},J.prototype.restoreState=function(D){this.idx=D.idx,this.input=D.input,this.groupIdx=D.groupIdx},J.prototype.pattern=function(D){this.idx=0,this.input=D,this.groupIdx=0,this.consumeChar("/");var L=this.disjunction();this.consumeChar("/");for(var R={type:"Flags",loc:{begin:this.idx,end:D.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};this.isRegExpFlag();)switch(this.popChar()){case"g":X(R,"global");break;case"i":X(R,"ignoreCase");break;case"m":X(R,"multiLine");break;case"u":X(R,"unicode");break;case"y":X(R,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:R,value:L,loc:this.loc(0)}},J.prototype.disjunction=function(){var D=[],L=this.idx;for(D.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),D.push(this.alternative());return{type:"Disjunction",value:D,loc:this.loc(L)}},J.prototype.alternative=function(){for(var D=[],L=this.idx;this.isTerm();)D.push(this.term());return{type:"Alternative",value:D,loc:this.loc(L)}},J.prototype.term=function(){return this.isAssertion()?this.assertion():this.atom()},J.prototype.assertion=function(){var D=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(D)};case"$":return{type:"EndAnchor",loc:this.loc(D)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(D)};case"B":return{type:"NonWordBoundary",loc:this.loc(D)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");var L;switch(this.popChar()){case"=":L="Lookahead";break;case"!":L="NegativeLookahead";break}E(L);var R=this.disjunction();return this.consumeChar(")"),{type:L,value:R,loc:this.loc(D)}}H()},J.prototype.quantifier=function(D){var L,R=this.idx;switch(this.popChar()){case"*":L={atLeast:0,atMost:1/0};break;case"+":L={atLeast:1,atMost:1/0};break;case"?":L={atLeast:0,atMost:1};break;case"{":var M=this.integerIncludingZero();switch(this.popChar()){case"}":L={atLeast:M,atMost:M};break;case",":var T;this.isDigit()?(T=this.integerIncludingZero(),L={atLeast:M,atMost:T}):L={atLeast:M,atMost:1/0},this.consumeChar("}");break}if(D===!0&&L===void 0)return;E(L);break}if(!(D===!0&&L===void 0))return E(L),this.peekChar(0)==="?"?(this.consumeChar("?"),L.greedy=!1):L.greedy=!0,L.type="Quantifier",L.loc=this.loc(R),L},J.prototype.atom=function(){var D,L=this.idx;switch(this.peekChar()){case".":D=this.dotAll();break;case"\\":D=this.atomEscape();break;case"[":D=this.characterClass();break;case"(":D=this.group();break}return D===void 0&&this.isPatternCharacter()&&(D=this.patternCharacter()),E(D),D.loc=this.loc(L),this.isQuantifier()&&(D.quantifier=this.quantifier()),D},J.prototype.dotAll=function(){return this.consumeChar("."),{type:"Set",complement:!0,value:[Y(` -`),Y("\r"),Y("\u2028"),Y("\u2029")]}},J.prototype.atomEscape=function(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}},J.prototype.decimalEscapeAtom=function(){var D=this.positiveInteger();return{type:"GroupBackReference",value:D}},J.prototype.characterClassEscape=function(){var D,L=!1;switch(this.popChar()){case"d":D=I;break;case"D":D=I,L=!0;break;case"s":D=F;break;case"S":D=F,L=!0;break;case"w":D=N;break;case"W":D=N,L=!0;break}return E(D),{type:"Set",value:D,complement:L}},J.prototype.controlEscapeAtom=function(){var D;switch(this.popChar()){case"f":D=Y("\f");break;case"n":D=Y(` -`);break;case"r":D=Y("\r");break;case"t":D=Y("\t");break;case"v":D=Y("\v");break}return E(D),{type:"Character",value:D}},J.prototype.controlLetterEscapeAtom=function(){this.consumeChar("c");var D=this.popChar();if(/[a-zA-Z]/.test(D)===!1)throw Error("Invalid ");var L=D.toUpperCase().charCodeAt(0)-64;return{type:"Character",value:L}},J.prototype.nulCharacterAtom=function(){return this.consumeChar("0"),{type:"Character",value:Y("\x00")}},J.prototype.hexEscapeSequenceAtom=function(){return this.consumeChar("x"),this.parseHexDigits(2)},J.prototype.regExpUnicodeEscapeSequenceAtom=function(){return this.consumeChar("u"),this.parseHexDigits(4)},J.prototype.identityEscapeAtom=function(){var D=this.popChar();return{type:"Character",value:Y(D)}},J.prototype.classPatternCharacterAtom=function(){switch(this.peekChar()){case` -`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:var D=this.popChar();return{type:"Character",value:Y(D)}}},J.prototype.characterClass=function(){var D=[],L=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),L=!0);this.isClassAtom();){var R=this.classAtom(),M=R.type==="Character";if(M&&this.isRangeDash()){this.consumeChar("-");var T=this.classAtom(),h=T.type==="Character";if(h){if(T.value=this.input.length)throw Error("Unexpected end of input");this.idx++},J.prototype.loc=function(D){return{begin:D,end:this.idx}};var K=/[0-9a-fA-F]/,C=/[0-9]/,U=/[1-9]/;function Y(D){return D.charCodeAt(0)}function Z(D,L){D.length!==void 0?D.forEach(function(R){L.push(R)}):L.push(D)}function X(D,L){if(D[L]===!0)throw"duplicate flag "+L;D[L]=!0}function E(D){if(D===void 0)throw Error("Internal Error - Should never get here!")}function H(){throw Error("Internal Error - Should never get here!")}var $,I=[];for($=Y("0");$<=Y("9");$++)I.push($);var N=[Y("_")].concat(I);for($=Y("a");$<=Y("z");$++)N.push($);for($=Y("A");$<=Y("Z");$++)N.push($);var F=[Y(" "),Y("\f"),Y(` -`),Y("\r"),Y("\t"),Y("\v"),Y("\t"),Y(" "),Y(" "),Y(" "),Y(" "),Y(" "),Y(" "),Y(" "),Y(" "),Y(" "),Y(" "),Y(" "),Y(" "),Y(" "),Y("\u2028"),Y("\u2029"),Y(" "),Y(" "),Y(" "),Y("\uFEFF")];function V(){}return V.prototype.visitChildren=function(D){for(var L in D){var R=D[L];D.hasOwnProperty(L)&&(R.type!==void 0?this.visit(R):Array.isArray(R)&&R.forEach(function(M){this.visit(M)},this))}},V.prototype.visit=function(D){switch(D.type){case"Pattern":this.visitPattern(D);break;case"Flags":this.visitFlags(D);break;case"Disjunction":this.visitDisjunction(D);break;case"Alternative":this.visitAlternative(D);break;case"StartAnchor":this.visitStartAnchor(D);break;case"EndAnchor":this.visitEndAnchor(D);break;case"WordBoundary":this.visitWordBoundary(D);break;case"NonWordBoundary":this.visitNonWordBoundary(D);break;case"Lookahead":this.visitLookahead(D);break;case"NegativeLookahead":this.visitNegativeLookahead(D);break;case"Character":this.visitCharacter(D);break;case"Set":this.visitSet(D);break;case"Group":this.visitGroup(D);break;case"GroupBackReference":this.visitGroupBackReference(D);break;case"Quantifier":this.visitQuantifier(D);break}this.visitChildren(D)},V.prototype.visitPattern=function(D){},V.prototype.visitFlags=function(D){},V.prototype.visitDisjunction=function(D){},V.prototype.visitAlternative=function(D){},V.prototype.visitStartAnchor=function(D){},V.prototype.visitEndAnchor=function(D){},V.prototype.visitWordBoundary=function(D){},V.prototype.visitNonWordBoundary=function(D){},V.prototype.visitLookahead=function(D){},V.prototype.visitNegativeLookahead=function(D){},V.prototype.visitCharacter=function(D){},V.prototype.visitSet=function(D){},V.prototype.visitGroup=function(D){},V.prototype.visitGroupBackReference=function(D){},V.prototype.visitQuantifier=function(D){},{RegExpParser:J,BaseRegExpVisitor:V,VERSION:"0.5.0"}})}),ez=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.clearRegExpParserCache=A.getRegExpAst=void 0;var Q=tz(),J={},K=new Q.RegExpParser;function C(Y){var Z=Y.toString();if(J.hasOwnProperty(Z))return J[Z];var X=K.pattern(Z);return J[Z]=X,X}A.getRegExpAst=C;function U(){J={}}A.clearRegExpParserCache=U}),TB1=vA((A)=>{var Q=A&&A.__extends||function(){var V=function(D,L){return V=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(R,M){R.__proto__=M}||function(R,M){for(var T in M)Object.prototype.hasOwnProperty.call(M,T)&&(R[T]=M[T])},V(D,L)};return function(D,L){if(typeof L!="function"&&L!==null)throw new TypeError("Class extends value "+String(L)+" is not a constructor or null");V(D,L);function R(){this.constructor=D}D.prototype=L===null?Object.create(L):(R.prototype=L.prototype,new R)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.canMatchCharCode=A.firstCharOptimizedIndices=A.getOptimizedStartCodesIndices=A.failedOptimizationPrefixMsg=void 0;var J=tz(),K=G2(),C=ez(),U=pm(),Y="Complement Sets are not supported for first char optimization";A.failedOptimizationPrefixMsg=`Unable to use "first char" lexer optimizations: -`;function Z(V,D){D===void 0&&(D=!1);try{var L=C.getRegExpAst(V),R=X(L.value,{},L.flags.ignoreCase);return R}catch(T){if(T.message===Y)D&&K.PRINT_WARNING(""+A.failedOptimizationPrefixMsg+("\tUnable to optimize: < "+V.toString()+` > -`)+` Complement Sets cannot be automatically optimized. - This will disable the lexer's first char optimizations. - See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{var M="";D&&(M=` - This will disable the lexer's first char optimizations. - See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),K.PRINT_ERROR(A.failedOptimizationPrefixMsg+` -`+("\tFailed parsing: < "+V.toString()+` > -`)+("\tUsing the regexp-to-ast library version: "+J.VERSION+` -`)+"\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues"+M)}}return[]}A.getOptimizedStartCodesIndices=Z;function X(V,D,L){switch(V.type){case"Disjunction":for(var R=0;R=U.minOptimizationVal)for(var n=u.from>=U.minOptimizationVal?u.from:U.minOptimizationVal,B=u.to,q=U.charCodeToOptimizedIndex(n),P=U.charCodeToOptimizedIndex(B),O=q;O<=P;O++)D[O]=O}}});break;case"Group":X(h.value,D,L);break;default:throw Error("Non Exhaustive Match")}var y=h.quantifier!==void 0&&h.quantifier.atLeast===0;if(h.type==="Group"&&I(h)===!1||h.type!=="Group"&&y===!1)break}break;default:throw Error("non exhaustive match!")}return K.values(D)}A.firstCharOptimizedIndices=X;function E(V,D,L){var R=U.charCodeToOptimizedIndex(V);D[R]=R,L===!0&&H(V,D)}function H(V,D){var L=String.fromCharCode(V),R=L.toUpperCase();if(R!==L){var M=U.charCodeToOptimizedIndex(R.charCodeAt(0));D[M]=M}else{var T=L.toLowerCase();if(T!==L){var M=U.charCodeToOptimizedIndex(T.charCodeAt(0));D[M]=M}}}function $(V,D){return K.find(V.value,function(L){if(typeof L=="number")return K.contains(D,L);var R=L;return K.find(D,function(M){return R.from<=M&&M<=R.to})!==void 0})}function I(V){return V.quantifier&&V.quantifier.atLeast===0?!0:V.value?K.isArray(V.value)?K.every(V.value,I):I(V.value):!1}var N=function(V){Q(D,V);function D(L){var R=V.call(this)||this;return R.targetCharCodes=L,R.found=!1,R}return D.prototype.visitChildren=function(L){if(this.found!==!0){switch(L.type){case"Lookahead":this.visitLookahead(L);return;case"NegativeLookahead":this.visitNegativeLookahead(L);return}V.prototype.visitChildren.call(this,L)}},D.prototype.visitCharacter=function(L){K.contains(this.targetCharCodes,L.value)&&(this.found=!0)},D.prototype.visitSet=function(L){L.complement?$(L,this.targetCharCodes)===void 0&&(this.found=!0):$(L,this.targetCharCodes)!==void 0&&(this.found=!0)},D}(J.BaseRegExpVisitor);function F(V,D){if(D instanceof RegExp){var L=C.getRegExpAst(D),R=new N(V);return R.visit(L),R.found}else return K.find(D,function(M){return K.contains(V,M.charCodeAt(0))})!==void 0}A.canMatchCharCode=F}),pm=vA((A)=>{var Q=A&&A.__extends||function(){var r=function(A1,Q1){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var U1 in t)Object.prototype.hasOwnProperty.call(t,U1)&&(e[U1]=t[U1])},r(A1,Q1)};return function(A1,Q1){if(typeof Q1!="function"&&Q1!==null)throw new TypeError("Class extends value "+String(Q1)+" is not a constructor or null");r(A1,Q1);function e(){this.constructor=A1}A1.prototype=Q1===null?Object.create(Q1):(e.prototype=Q1.prototype,new e)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.charCodeToOptimizedIndex=A.minOptimizationVal=A.buildLineBreakIssueMessage=A.LineTerminatorOptimizedTester=A.isShortPattern=A.isCustomPattern=A.cloneEmptyGroups=A.performWarningRuntimeChecks=A.performRuntimeChecks=A.addStickyFlag=A.addStartOfInput=A.findUnreachablePatterns=A.findModesThatDoNotExist=A.findInvalidGroupType=A.findDuplicatePatterns=A.findUnsupportedFlags=A.findStartOfInputAnchor=A.findEmptyMatchRegExps=A.findEndOfInputAnchor=A.findInvalidPatterns=A.findMissingPatterns=A.validatePatterns=A.analyzeTokenTypes=A.enableSticky=A.disableSticky=A.SUPPORT_STICKY=A.MODES=A.DEFAULT_MODE=void 0;var J=tz(),K=eG(),C=G2(),U=TB1(),Y=ez(),Z="PATTERN";A.DEFAULT_MODE="defaultMode",A.MODES="modes",A.SUPPORT_STICKY=typeof new RegExp("(?:)").sticky=="boolean";function X(){A.SUPPORT_STICKY=!1}A.disableSticky=X;function E(){A.SUPPORT_STICKY=!0}A.enableSticky=E;function H(r,A1){A1=C.defaults(A1,{useSticky:A.SUPPORT_STICKY,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` -`],tracer:function(k1,D1){return D1()}});var Q1=A1.tracer;Q1("initCharCodeToOptimizedIndexMap",function(){s()});var e;Q1("Reject Lexer.NA",function(){e=C.reject(r,function(k1){return k1[Z]===K.Lexer.NA})});var t=!1,U1;Q1("Transform Patterns",function(){t=!1,U1=C.map(e,function(k1){var D1=k1[Z];if(C.isRegExp(D1)){var G1=D1.source;return G1.length===1&&G1!=="^"&&G1!=="$"&&G1!=="."&&!D1.ignoreCase?G1:G1.length===2&&G1[0]==="\\"&&!C.contains(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],G1[1])?G1[1]:A1.useSticky?B(D1):n(D1)}else{if(C.isFunction(D1))return t=!0,{exec:D1};if(C.has(D1,"exec"))return t=!0,D1;if(typeof D1=="string"){if(D1.length===1)return D1;var w1=D1.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),G=new RegExp(w1);return A1.useSticky?B(G):n(G)}else throw Error("non exhaustive match")}})});var O1,E1,Y1,i,c;Q1("misc mapping",function(){O1=C.map(e,function(k1){return k1.tokenTypeIdx}),E1=C.map(e,function(k1){var D1=k1.GROUP;if(D1!==K.Lexer.SKIPPED){if(C.isString(D1))return D1;if(C.isUndefined(D1))return!1;throw Error("non exhaustive match")}}),Y1=C.map(e,function(k1){var D1=k1.LONGER_ALT;if(D1){var G1=C.indexOf(e,D1);return G1}}),i=C.map(e,function(k1){return k1.PUSH_MODE}),c=C.map(e,function(k1){return C.has(k1,"POP_MODE")})});var o;Q1("Line Terminator Handling",function(){var k1=W(A1.lineTerminatorCharacters);o=C.map(e,function(D1){return!1}),A1.positionTracking!=="onlyOffset"&&(o=C.map(e,function(D1){if(C.has(D1,"LINE_BREAKS"))return D1.LINE_BREAKS;if(S(D1,k1)===!1)return U.canMatchCharCode(k1,D1.PATTERN)}))});var C1,q1,Z1,j1;Q1("Misc Mapping #2",function(){C1=C.map(e,w),q1=C.map(U1,k),Z1=C.reduce(e,function(k1,D1){var G1=D1.GROUP;return C.isString(G1)&&G1!==K.Lexer.SKIPPED&&(k1[G1]=[]),k1},{}),j1=C.map(U1,function(k1,D1){return{pattern:U1[D1],longerAlt:Y1[D1],canLineTerminator:o[D1],isCustom:C1[D1],short:q1[D1],group:E1[D1],push:i[D1],pop:c[D1],tokenTypeIdx:O1[D1],tokenType:e[D1]}})});var H1=!0,B1=[];return A1.safeMode||Q1("First Char Optimization",function(){B1=C.reduce(e,function(k1,D1,G1){if(typeof D1.PATTERN=="string"){var w1=D1.PATTERN.charCodeAt(0),G=p(w1);j(k1,G,j1[G1])}else if(C.isArray(D1.START_CHARS_HINT)){var z;C.forEach(D1.START_CHARS_HINT,function(m){var l=typeof m=="string"?m.charCodeAt(0):m,a=p(l);z!==a&&(z=a,j(k1,a,j1[G1]))})}else if(C.isRegExp(D1.PATTERN))if(D1.PATTERN.unicode)H1=!1,A1.ensureOptimizations&&C.PRINT_ERROR(""+U.failedOptimizationPrefixMsg+("\tUnable to analyze < "+D1.PATTERN.toString()+` > pattern. -`)+` The regexp unicode flag is not currently supported by the regexp-to-ast library. - This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{var x=U.getOptimizedStartCodesIndices(D1.PATTERN,A1.ensureOptimizations);C.isEmpty(x)&&(H1=!1),C.forEach(x,function(m){j(k1,m,j1[G1])})}else A1.ensureOptimizations&&C.PRINT_ERROR(""+U.failedOptimizationPrefixMsg+("\tTokenType: <"+D1.name+`> is using a custom token pattern without providing parameter. -`)+` This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),H1=!1;return k1},[])}),Q1("ArrayPacking",function(){B1=C.packArray(B1)}),{emptyGroups:Z1,patternIdxToConfig:j1,charCodeToPatternIdxToConfig:B1,hasCustom:t,canBeOptimized:H1}}A.analyzeTokenTypes=H;function $(r,A1){var Q1=[],e=N(r);Q1=Q1.concat(e.errors);var t=F(e.valid),U1=t.valid;return Q1=Q1.concat(t.errors),Q1=Q1.concat(I(U1)),Q1=Q1.concat(y(U1)),Q1=Q1.concat(g(U1,A1)),Q1=Q1.concat(f(U1)),Q1}A.validatePatterns=$;function I(r){var A1=[],Q1=C.filter(r,function(e){return C.isRegExp(e[Z])});return A1=A1.concat(D(Q1)),A1=A1.concat(M(Q1)),A1=A1.concat(T(Q1)),A1=A1.concat(h(Q1)),A1=A1.concat(L(Q1)),A1}function N(r){var A1=C.filter(r,function(t){return!C.has(t,Z)}),Q1=C.map(A1,function(t){return{message:"Token Type: ->"+t.name+"<- missing static 'PATTERN' property",type:K.LexerDefinitionErrorType.MISSING_PATTERN,tokenTypes:[t]}}),e=C.difference(r,A1);return{errors:Q1,valid:e}}A.findMissingPatterns=N;function F(r){var A1=C.filter(r,function(t){var U1=t[Z];return!C.isRegExp(U1)&&!C.isFunction(U1)&&!C.has(U1,"exec")&&!C.isString(U1)}),Q1=C.map(A1,function(t){return{message:"Token Type: ->"+t.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:K.LexerDefinitionErrorType.INVALID_PATTERN,tokenTypes:[t]}}),e=C.difference(r,A1);return{errors:Q1,valid:e}}A.findInvalidPatterns=F;var V=/[^\\][\$]/;function D(r){var A1=function(t){Q(U1,t);function U1(){var O1=t!==null&&t.apply(this,arguments)||this;return O1.found=!1,O1}return U1.prototype.visitEndAnchor=function(O1){this.found=!0},U1}(J.BaseRegExpVisitor),Q1=C.filter(r,function(t){var U1=t[Z];try{var O1=Y.getRegExpAst(U1),E1=new A1;return E1.visit(O1),E1.found}catch(Y1){return V.test(U1.source)}}),e=C.map(Q1,function(t){return{message:`Unexpected RegExp Anchor Error: - Token Type: ->`+t.name+`<- static 'PATTERN' cannot contain end of input anchor '$' - See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:K.LexerDefinitionErrorType.EOI_ANCHOR_FOUND,tokenTypes:[t]}});return e}A.findEndOfInputAnchor=D;function L(r){var A1=C.filter(r,function(e){var t=e[Z];return t.test("")}),Q1=C.map(A1,function(e){return{message:"Token Type: ->"+e.name+"<- static 'PATTERN' must not match an empty string",type:K.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,tokenTypes:[e]}});return Q1}A.findEmptyMatchRegExps=L;var R=/[^\\[][\^]|^\^/;function M(r){var A1=function(t){Q(U1,t);function U1(){var O1=t!==null&&t.apply(this,arguments)||this;return O1.found=!1,O1}return U1.prototype.visitStartAnchor=function(O1){this.found=!0},U1}(J.BaseRegExpVisitor),Q1=C.filter(r,function(t){var U1=t[Z];try{var O1=Y.getRegExpAst(U1),E1=new A1;return E1.visit(O1),E1.found}catch(Y1){return R.test(U1.source)}}),e=C.map(Q1,function(t){return{message:`Unexpected RegExp Anchor Error: - Token Type: ->`+t.name+`<- static 'PATTERN' cannot contain start of input anchor '^' - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:K.LexerDefinitionErrorType.SOI_ANCHOR_FOUND,tokenTypes:[t]}});return e}A.findStartOfInputAnchor=M;function T(r){var A1=C.filter(r,function(e){var t=e[Z];return t instanceof RegExp&&(t.multiline||t.global)}),Q1=C.map(A1,function(e){return{message:"Token Type: ->"+e.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:K.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[e]}});return Q1}A.findUnsupportedFlags=T;function h(r){var A1=[],Q1=C.map(r,function(U1){return C.reduce(r,function(O1,E1){return U1.PATTERN.source===E1.PATTERN.source&&!C.contains(A1,E1)&&E1.PATTERN!==K.Lexer.NA&&(A1.push(E1),O1.push(E1)),O1},[])});Q1=C.compact(Q1);var e=C.filter(Q1,function(U1){return U1.length>1}),t=C.map(e,function(U1){var O1=C.map(U1,function(Y1){return Y1.name}),E1=C.first(U1).PATTERN;return{message:"The same RegExp pattern ->"+E1+"<-"+("has been used in all of the following Token Types: "+O1.join(", ")+" <-"),type:K.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,tokenTypes:U1}});return t}A.findDuplicatePatterns=h;function y(r){var A1=C.filter(r,function(e){if(!C.has(e,"GROUP"))return!1;var t=e.GROUP;return t!==K.Lexer.SKIPPED&&t!==K.Lexer.NA&&!C.isString(t)}),Q1=C.map(A1,function(e){return{message:"Token Type: ->"+e.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:K.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,tokenTypes:[e]}});return Q1}A.findInvalidGroupType=y;function g(r,A1){var Q1=C.filter(r,function(t){return t.PUSH_MODE!==void 0&&!C.contains(A1,t.PUSH_MODE)}),e=C.map(Q1,function(t){var U1="Token Type: ->"+t.name+"<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->"+t.PUSH_MODE+"<-which does not exist";return{message:U1,type:K.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[t]}});return e}A.findModesThatDoNotExist=g;function f(r){var A1=[],Q1=C.reduce(r,function(e,t,U1){var O1=t.PATTERN;return O1===K.Lexer.NA||(C.isString(O1)?e.push({str:O1,idx:U1,tokenType:t}):C.isRegExp(O1)&&d(O1)&&e.push({str:O1.source,idx:U1,tokenType:t})),e},[]);return C.forEach(r,function(e,t){C.forEach(Q1,function(U1){var{str:O1,idx:E1,tokenType:Y1}=U1;if(t"+e.name+"<-")+`in the lexer's definition. -See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;A1.push({message:i,type:K.LexerDefinitionErrorType.UNREACHABLE_PATTERN,tokenTypes:[e,Y1]})}})}),A1}A.findUnreachablePatterns=f;function u(r,A1){if(C.isRegExp(A1)){var Q1=A1.exec(r);return Q1!==null&&Q1.index===0}else{if(C.isFunction(A1))return A1(r,0,[],{});if(C.has(A1,"exec"))return A1.exec(r,0,[],{});if(typeof A1=="string")return A1===r;throw Error("non exhaustive match")}}function d(r){var A1=[".","\\","[","]","|","^","$","(",")","?","*","+","{"];return C.find(A1,function(Q1){return r.source.indexOf(Q1)!==-1})===void 0}function n(r){var A1=r.ignoreCase?"i":"";return new RegExp("^(?:"+r.source+")",A1)}A.addStartOfInput=n;function B(r){var A1=r.ignoreCase?"iy":"y";return new RegExp(""+r.source,A1)}A.addStickyFlag=B;function q(r,A1,Q1){var e=[];return C.has(r,A.DEFAULT_MODE)||e.push({message:"A MultiMode Lexer cannot be initialized without a <"+A.DEFAULT_MODE+`> property in its definition -`,type:K.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),C.has(r,A.MODES)||e.push({message:"A MultiMode Lexer cannot be initialized without a <"+A.MODES+`> property in its definition -`,type:K.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),C.has(r,A.MODES)&&C.has(r,A.DEFAULT_MODE)&&!C.has(r.modes,r.defaultMode)&&e.push({message:"A MultiMode Lexer cannot be initialized with a "+A.DEFAULT_MODE+": <"+r.defaultMode+`>which does not exist -`,type:K.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),C.has(r,A.MODES)&&C.forEach(r.modes,function(t,U1){C.forEach(t,function(O1,E1){C.isUndefined(O1)&&e.push({message:"A Lexer cannot be initialized using an undefined Token Type. Mode:"+("<"+U1+"> at index: <"+E1+`> -`),type:K.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED})})}),e}A.performRuntimeChecks=q;function P(r,A1,Q1){var e=[],t=!1,U1=C.compact(C.flatten(C.mapValues(r.modes,function(Y1){return Y1}))),O1=C.reject(U1,function(Y1){return Y1[Z]===K.Lexer.NA}),E1=W(Q1);return A1&&C.forEach(O1,function(Y1){var i=S(Y1,E1);if(i!==!1){var c=_(Y1,i),o={message:c,type:i.issue,tokenType:Y1};e.push(o)}else C.has(Y1,"LINE_BREAKS")?Y1.LINE_BREAKS===!0&&(t=!0):U.canMatchCharCode(E1,Y1.PATTERN)&&(t=!0)}),A1&&!t&&e.push({message:`Warning: No LINE_BREAKS Found. - This Lexer has been defined to track line and column information, - But none of the Token Types can be identified as matching a line terminator. - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS - for details.`,type:K.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS}),e}A.performWarningRuntimeChecks=P;function O(r){var A1={},Q1=C.keys(r);return C.forEach(Q1,function(e){var t=r[e];if(C.isArray(t))A1[e]=[];else throw Error("non exhaustive match")}),A1}A.cloneEmptyGroups=O;function w(r){var A1=r.PATTERN;if(C.isRegExp(A1))return!1;if(C.isFunction(A1))return!0;if(C.has(A1,"exec"))return!0;if(C.isString(A1))return!1;throw Error("non exhaustive match")}A.isCustomPattern=w;function k(r){return C.isString(r)&&r.length===1?r.charCodeAt(0):!1}A.isShortPattern=k,A.LineTerminatorOptimizedTester={test:function(r){for(var A1=r.length,Q1=this.lastIndex;Q1 Token Type -`)+("\t Root cause: "+A1.errMsg+`. -`)+"\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR";if(A1.issue===K.LexerDefinitionErrorType.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. -`+("\tThe problem is in the <"+r.name+`> Token Type -`)+"\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK";throw Error("non exhaustive match")}A.buildLineBreakIssueMessage=_;function W(r){var A1=C.map(r,function(Q1){return C.isString(Q1)&&Q1.length>0?Q1.charCodeAt(0):Q1});return A1}function j(r,A1,Q1){r[A1]===void 0?r[A1]=[Q1]:r[A1].push(Q1)}A.minOptimizationVal=256;var b=[];function p(r){return r255?255+~~(r/255):r}}}),EB=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.isTokenType=A.hasExtendingTokensTypesMapProperty=A.hasExtendingTokensTypesProperty=A.hasCategoriesProperty=A.hasShortKeyProperty=A.singleAssignCategoriesToksMap=A.assignCategoriesMapProp=A.assignCategoriesTokensProp=A.assignTokenDefaultProps=A.expandCategories=A.augmentTokenTypes=A.tokenIdxToClass=A.tokenShortNameIdx=A.tokenStructuredMatcherNoCategories=A.tokenStructuredMatcher=void 0;var Q=G2();function J(V,D){var L=V.tokenTypeIdx;return L===D.tokenTypeIdx?!0:D.isParent===!0&&D.categoryMatchesMap[L]===!0}A.tokenStructuredMatcher=J;function K(V,D){return V.tokenTypeIdx===D.tokenTypeIdx}A.tokenStructuredMatcherNoCategories=K,A.tokenShortNameIdx=1,A.tokenIdxToClass={};function C(V){var D=U(V);Y(D),X(D),Z(D),Q.forEach(D,function(L){L.isParent=L.categoryMatches.length>0})}A.augmentTokenTypes=C;function U(V){for(var D=Q.cloneArr(V),L=V,R=!0;R;){L=Q.compact(Q.flatten(Q.map(L,function(T){return T.CATEGORIES})));var M=Q.difference(L,D);D=D.concat(M),Q.isEmpty(M)?R=!1:L=M}return D}A.expandCategories=U;function Y(V){Q.forEach(V,function(D){H(D)||(A.tokenIdxToClass[A.tokenShortNameIdx]=D,D.tokenTypeIdx=A.tokenShortNameIdx++),$(D)&&!Q.isArray(D.CATEGORIES)&&(D.CATEGORIES=[D.CATEGORIES]),$(D)||(D.CATEGORIES=[]),I(D)||(D.categoryMatches=[]),N(D)||(D.categoryMatchesMap={})})}A.assignTokenDefaultProps=Y;function Z(V){Q.forEach(V,function(D){D.categoryMatches=[],Q.forEach(D.categoryMatchesMap,function(L,R){D.categoryMatches.push(A.tokenIdxToClass[R].tokenTypeIdx)})})}A.assignCategoriesTokensProp=Z;function X(V){Q.forEach(V,function(D){E([],D)})}A.assignCategoriesMapProp=X;function E(V,D){Q.forEach(V,function(L){D.categoryMatchesMap[L.tokenTypeIdx]=!0}),Q.forEach(D.CATEGORIES,function(L){var R=V.concat(D);Q.contains(R,L)||E(R,L)})}A.singleAssignCategoriesToksMap=E;function H(V){return Q.has(V,"tokenTypeIdx")}A.hasShortKeyProperty=H;function $(V){return Q.has(V,"CATEGORIES")}A.hasCategoriesProperty=$;function I(V){return Q.has(V,"categoryMatches")}A.hasExtendingTokensTypesProperty=I;function N(V){return Q.has(V,"categoryMatchesMap")}A.hasExtendingTokensTypesMapProperty=N;function F(V){return Q.has(V,"tokenTypeIdx")}A.isTokenType=F}),um=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.defaultLexerErrorProvider=void 0,A.defaultLexerErrorProvider={buildUnableToPopLexerModeMessage:function(Q){return"Unable to pop Lexer Mode after encountering Token ->"+Q.image+"<- The Mode Stack is empty"},buildUnexpectedCharactersMessage:function(Q,J,K,C,U){return"unexpected character: ->"+Q.charAt(J)+"<- at offset: "+J+","+(" skipped "+K+" characters.")}}}),eG=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.Lexer=A.LexerDefinitionErrorType=void 0;var Q=pm(),J=G2(),K=EB(),C=um(),U=ez(),Y;(function(E){E[E.MISSING_PATTERN=0]="MISSING_PATTERN",E[E.INVALID_PATTERN=1]="INVALID_PATTERN",E[E.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",E[E.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",E[E.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",E[E.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",E[E.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",E[E.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",E[E.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",E[E.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",E[E.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",E[E.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",E[E.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",E[E.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",E[E.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",E[E.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",E[E.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK"})(Y=A.LexerDefinitionErrorType||(A.LexerDefinitionErrorType={}));var Z={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` -`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:C.defaultLexerErrorProvider,traceInitPerf:!1,skipValidations:!1};Object.freeze(Z);var X=function(){function E(H,$){var I=this;if($===void 0&&($=Z),this.lexerDefinition=H,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.config=void 0,this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},typeof $=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. -a boolean 2nd argument is no longer supported`);this.config=J.merge(Z,$);var N=this.config.traceInitPerf;N===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof N=="number"&&(this.traceInitMaxIdent=N,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",function(){var F,V=!0;I.TRACE_INIT("Lexer Config handling",function(){if(I.config.lineTerminatorsPattern===Z.lineTerminatorsPattern)I.config.lineTerminatorsPattern=Q.LineTerminatorOptimizedTester;else if(I.config.lineTerminatorCharacters===Z.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if($.safeMode&&$.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');I.trackStartLines=/full|onlyStart/i.test(I.config.positionTracking),I.trackEndLines=/full/i.test(I.config.positionTracking),J.isArray(H)?(F={modes:{}},F.modes[Q.DEFAULT_MODE]=J.cloneArr(H),F[Q.DEFAULT_MODE]=Q.DEFAULT_MODE):(V=!1,F=J.cloneObj(H))}),I.config.skipValidations===!1&&(I.TRACE_INIT("performRuntimeChecks",function(){I.lexerDefinitionErrors=I.lexerDefinitionErrors.concat(Q.performRuntimeChecks(F,I.trackStartLines,I.config.lineTerminatorCharacters))}),I.TRACE_INIT("performWarningRuntimeChecks",function(){I.lexerDefinitionWarning=I.lexerDefinitionWarning.concat(Q.performWarningRuntimeChecks(F,I.trackStartLines,I.config.lineTerminatorCharacters))})),F.modes=F.modes?F.modes:{},J.forEach(F.modes,function(M,T){F.modes[T]=J.reject(M,function(h){return J.isUndefined(h)})});var D=J.keys(F.modes);if(J.forEach(F.modes,function(M,T){I.TRACE_INIT("Mode: <"+T+"> processing",function(){if(I.modes.push(T),I.config.skipValidations===!1&&I.TRACE_INIT("validatePatterns",function(){I.lexerDefinitionErrors=I.lexerDefinitionErrors.concat(Q.validatePatterns(M,D))}),J.isEmpty(I.lexerDefinitionErrors)){K.augmentTokenTypes(M);var h;I.TRACE_INIT("analyzeTokenTypes",function(){h=Q.analyzeTokenTypes(M,{lineTerminatorCharacters:I.config.lineTerminatorCharacters,positionTracking:$.positionTracking,ensureOptimizations:$.ensureOptimizations,safeMode:$.safeMode,tracer:I.TRACE_INIT.bind(I)})}),I.patternIdxToConfig[T]=h.patternIdxToConfig,I.charCodeToPatternIdxToConfig[T]=h.charCodeToPatternIdxToConfig,I.emptyGroups=J.merge(I.emptyGroups,h.emptyGroups),I.hasCustom=h.hasCustom||I.hasCustom,I.canModeBeOptimized[T]=h.canBeOptimized}})}),I.defaultMode=F.defaultMode,!J.isEmpty(I.lexerDefinitionErrors)&&!I.config.deferDefinitionErrorsHandling){var L=J.map(I.lexerDefinitionErrors,function(M){return M.message}),R=L.join(`----------------------- -`);throw new Error(`Errors detected in definition of Lexer: -`+R)}J.forEach(I.lexerDefinitionWarning,function(M){J.PRINT_WARNING(M.message)}),I.TRACE_INIT("Choosing sub-methods implementations",function(){if(Q.SUPPORT_STICKY?(I.chopInput=J.IDENTITY,I.match=I.matchWithTest):(I.updateLastIndex=J.NOOP,I.match=I.matchWithExec),V&&(I.handleModes=J.NOOP),I.trackStartLines===!1&&(I.computeNewColumn=J.IDENTITY),I.trackEndLines===!1&&(I.updateTokenEndLineColumnLocation=J.NOOP),/full/i.test(I.config.positionTracking))I.createTokenInstance=I.createFullToken;else if(/onlyStart/i.test(I.config.positionTracking))I.createTokenInstance=I.createStartOnlyToken;else if(/onlyOffset/i.test(I.config.positionTracking))I.createTokenInstance=I.createOffsetOnlyToken;else throw Error('Invalid config option: "'+I.config.positionTracking+'"');I.hasCustom?(I.addToken=I.addTokenUsingPush,I.handlePayload=I.handlePayloadWithCustom):(I.addToken=I.addTokenUsingMemberAccess,I.handlePayload=I.handlePayloadNoCustom)}),I.TRACE_INIT("Failed Optimization Warnings",function(){var M=J.reduce(I.canModeBeOptimized,function(T,h,y){return h===!1&&T.push(y),T},[]);if($.ensureOptimizations&&!J.isEmpty(M))throw Error("Lexer Modes: < "+M.join(", ")+` > cannot be optimized. - Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. - Or inspect the console log for details on how to resolve these issues.`)}),I.TRACE_INIT("clearRegExpParserCache",function(){U.clearRegExpParserCache()}),I.TRACE_INIT("toFastProperties",function(){J.toFastProperties(I)})})}return E.prototype.tokenize=function(H,$){if($===void 0&&($=this.defaultMode),!J.isEmpty(this.lexerDefinitionErrors)){var I=J.map(this.lexerDefinitionErrors,function(V){return V.message}),N=I.join(`----------------------- -`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: -`+N)}var F=this.tokenizeInternal(H,$);return F},E.prototype.tokenizeInternal=function(H,$){var I=this,N,F,V,D,L,R,M,T,h,y,g,f,u,d,n,B=H,q=B.length,P=0,O=0,w=this.hasCustom?0:Math.floor(H.length/10),k=new Array(w),S=[],_=this.trackStartLines?1:void 0,W=this.trackStartLines?1:void 0,j=Q.cloneEmptyGroups(this.emptyGroups),b=this.trackStartLines,p=this.config.lineTerminatorsPattern,s=0,r=[],A1=[],Q1=[],e=[];Object.freeze(e);var t=void 0;function U1(){return r}function O1(m){var l=Q.charCodeToOptimizedIndex(m),a=A1[l];return a===void 0?e:a}var E1=function(m){if(Q1.length===1&&m.tokenType.PUSH_MODE===void 0){var l=I.config.errorMessageProvider.buildUnableToPopLexerModeMessage(m);S.push({offset:m.startOffset,line:m.startLine!==void 0?m.startLine:void 0,column:m.startColumn!==void 0?m.startColumn:void 0,length:m.image.length,message:l})}else{Q1.pop();var a=J.last(Q1);r=I.patternIdxToConfig[a],A1=I.charCodeToPatternIdxToConfig[a],s=r.length;var K1=I.canModeBeOptimized[a]&&I.config.safeMode===!1;A1&&K1?t=O1:t=U1}};function Y1(m){Q1.push(m),A1=this.charCodeToPatternIdxToConfig[m],r=this.patternIdxToConfig[m],s=r.length,s=r.length;var l=this.canModeBeOptimized[m]&&this.config.safeMode===!1;A1&&l?t=O1:t=U1}Y1.call(this,$);for(var i;PL.length&&(L=V,R=M,i=j1)}break}}if(L!==null){if(T=L.length,h=i.group,h!==void 0&&(y=i.tokenTypeIdx,g=this.createTokenInstance(L,P,y,i.tokenType,_,W,T),this.handlePayload(g,R),h===!1?O=this.addToken(k,O,g):j[h].push(g)),H=this.chopInput(H,T),P=P+T,W=this.computeNewColumn(W,T),b===!0&&i.canLineTerminator===!0){var B1=0,k1=void 0,D1=void 0;p.lastIndex=0;do k1=p.test(L),k1===!0&&(D1=p.lastIndex-1,B1++);while(k1===!0);B1!==0&&(_=_+B1,W=T-D1,this.updateTokenEndLineColumnLocation(g,h,D1,B1,_,W,T))}this.handleModes(i,E1,Y1,g)}else{for(var G1=P,w1=_,G=W,z=!1;!z&&P <"+H+">");var N=J.timer($),F=N.time,V=N.value,D=F>10?console.warn:console.log;return this.traceInitIndent time: "+F+"ms"),this.traceInitIndent--,V}else return $()},E.SKIPPED="This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.",E.NA=/NOT_APPLICABLE/,E}();A.Lexer=X}),EJ=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.tokenMatcher=A.createTokenInstance=A.EOF=A.createToken=A.hasTokenLabel=A.tokenName=A.tokenLabel=void 0;var Q=G2(),J=eG(),K=EB();function C(T){return Y(T)?T.LABEL:T.name}A.tokenLabel=C;function U(T){return T.name}A.tokenName=U;function Y(T){return Q.isString(T.LABEL)&&T.LABEL!==""}A.hasTokenLabel=Y;var Z="parent",X="categories",E="label",H="group",$="push_mode",I="pop_mode",N="longer_alt",F="line_breaks",V="start_chars_hint";function D(T){return L(T)}A.createToken=D;function L(T){var h=T.pattern,y={};if(y.name=T.name,Q.isUndefined(h)||(y.PATTERN=h),Q.has(T,Z))throw`The parent property is no longer supported. -See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.`;return Q.has(T,X)&&(y.CATEGORIES=T[X]),K.augmentTokenTypes([y]),Q.has(T,E)&&(y.LABEL=T[E]),Q.has(T,H)&&(y.GROUP=T[H]),Q.has(T,I)&&(y.POP_MODE=T[I]),Q.has(T,$)&&(y.PUSH_MODE=T[$]),Q.has(T,N)&&(y.LONGER_ALT=T[N]),Q.has(T,F)&&(y.LINE_BREAKS=T[F]),Q.has(T,V)&&(y.START_CHARS_HINT=T[V]),y}A.EOF=D({name:"EOF",pattern:J.Lexer.NA}),K.augmentTokenTypes([A.EOF]);function R(T,h,y,g,f,u,d,n){return{image:h,startOffset:y,endOffset:g,startLine:f,endLine:u,startColumn:d,endColumn:n,tokenTypeIdx:T.tokenTypeIdx,tokenType:T}}A.createTokenInstance=R;function M(T,h){return K.tokenStructuredMatcher(T,h)}A.tokenMatcher=M}),I9=vA((A)=>{var Q=A&&A.__extends||function(){var L=function(R,M){return L=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(T,h){T.__proto__=h}||function(T,h){for(var y in h)Object.prototype.hasOwnProperty.call(h,y)&&(T[y]=h[y])},L(R,M)};return function(R,M){if(typeof M!="function"&&M!==null)throw new TypeError("Class extends value "+String(M)+" is not a constructor or null");L(R,M);function T(){this.constructor=R}R.prototype=M===null?Object.create(M):(T.prototype=M.prototype,new T)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.serializeProduction=A.serializeGrammar=A.Terminal=A.Alternation=A.RepetitionWithSeparator=A.Repetition=A.RepetitionMandatoryWithSeparator=A.RepetitionMandatory=A.Option=A.Alternative=A.Rule=A.NonTerminal=A.AbstractProduction=void 0;var J=G2(),K=EJ(),C=function(){function L(R){this._definition=R}return Object.defineProperty(L.prototype,"definition",{get:function(){return this._definition},set:function(R){this._definition=R},enumerable:!1,configurable:!0}),L.prototype.accept=function(R){R.visit(this),J.forEach(this.definition,function(M){M.accept(R)})},L}();A.AbstractProduction=C;var U=function(L){Q(R,L);function R(M){var T=L.call(this,[])||this;return T.idx=1,J.assign(T,J.pick(M,function(h){return h!==void 0})),T}return Object.defineProperty(R.prototype,"definition",{get:function(){return this.referencedRule!==void 0?this.referencedRule.definition:[]},set:function(M){},enumerable:!1,configurable:!0}),R.prototype.accept=function(M){M.visit(this)},R}(C);A.NonTerminal=U;var Y=function(L){Q(R,L);function R(M){var T=L.call(this,M.definition)||this;return T.orgText="",J.assign(T,J.pick(M,function(h){return h!==void 0})),T}return R}(C);A.Rule=Y;var Z=function(L){Q(R,L);function R(M){var T=L.call(this,M.definition)||this;return T.ignoreAmbiguities=!1,J.assign(T,J.pick(M,function(h){return h!==void 0})),T}return R}(C);A.Alternative=Z;var X=function(L){Q(R,L);function R(M){var T=L.call(this,M.definition)||this;return T.idx=1,J.assign(T,J.pick(M,function(h){return h!==void 0})),T}return R}(C);A.Option=X;var E=function(L){Q(R,L);function R(M){var T=L.call(this,M.definition)||this;return T.idx=1,J.assign(T,J.pick(M,function(h){return h!==void 0})),T}return R}(C);A.RepetitionMandatory=E;var H=function(L){Q(R,L);function R(M){var T=L.call(this,M.definition)||this;return T.idx=1,J.assign(T,J.pick(M,function(h){return h!==void 0})),T}return R}(C);A.RepetitionMandatoryWithSeparator=H;var $=function(L){Q(R,L);function R(M){var T=L.call(this,M.definition)||this;return T.idx=1,J.assign(T,J.pick(M,function(h){return h!==void 0})),T}return R}(C);A.Repetition=$;var I=function(L){Q(R,L);function R(M){var T=L.call(this,M.definition)||this;return T.idx=1,J.assign(T,J.pick(M,function(h){return h!==void 0})),T}return R}(C);A.RepetitionWithSeparator=I;var N=function(L){Q(R,L);function R(M){var T=L.call(this,M.definition)||this;return T.idx=1,T.ignoreAmbiguities=!1,T.hasPredicates=!1,J.assign(T,J.pick(M,function(h){return h!==void 0})),T}return Object.defineProperty(R.prototype,"definition",{get:function(){return this._definition},set:function(M){this._definition=M},enumerable:!1,configurable:!0}),R}(C);A.Alternation=N;var F=function(){function L(R){this.idx=1,J.assign(this,J.pick(R,function(M){return M!==void 0}))}return L.prototype.accept=function(R){R.visit(this)},L}();A.Terminal=F;function V(L){return J.map(L,D)}A.serializeGrammar=V;function D(L){function R(h){return J.map(h,D)}if(L instanceof U)return{type:"NonTerminal",name:L.nonTerminalName,idx:L.idx};if(L instanceof Z)return{type:"Alternative",definition:R(L.definition)};if(L instanceof X)return{type:"Option",idx:L.idx,definition:R(L.definition)};if(L instanceof E)return{type:"RepetitionMandatory",idx:L.idx,definition:R(L.definition)};if(L instanceof H)return{type:"RepetitionMandatoryWithSeparator",idx:L.idx,separator:D(new F({terminalType:L.separator})),definition:R(L.definition)};if(L instanceof I)return{type:"RepetitionWithSeparator",idx:L.idx,separator:D(new F({terminalType:L.separator})),definition:R(L.definition)};if(L instanceof $)return{type:"Repetition",idx:L.idx,definition:R(L.definition)};if(L instanceof N)return{type:"Alternation",idx:L.idx,definition:R(L.definition)};if(L instanceof F){var M={type:"Terminal",name:L.terminalType.name,label:K.tokenLabel(L.terminalType),idx:L.idx},T=L.terminalType.PATTERN;return L.terminalType.PATTERN&&(M.pattern=J.isRegExp(T)?T.source:T),M}else{if(L instanceof Y)return{type:"Rule",name:L.name,orgText:L.orgText,definition:R(L.definition)};throw Error("non exhaustive match")}}A.serializeProduction=D}),AD=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.RestWalker=void 0;var Q=G2(),J=I9(),K=function(){function U(){}return U.prototype.walk=function(Y,Z){var X=this;Z===void 0&&(Z=[]),Q.forEach(Y.definition,function(E,H){var $=Q.drop(Y.definition,H+1);if(E instanceof J.NonTerminal)X.walkProdRef(E,$,Z);else if(E instanceof J.Terminal)X.walkTerminal(E,$,Z);else if(E instanceof J.Alternative)X.walkFlat(E,$,Z);else if(E instanceof J.Option)X.walkOption(E,$,Z);else if(E instanceof J.RepetitionMandatory)X.walkAtLeastOne(E,$,Z);else if(E instanceof J.RepetitionMandatoryWithSeparator)X.walkAtLeastOneSep(E,$,Z);else if(E instanceof J.RepetitionWithSeparator)X.walkManySep(E,$,Z);else if(E instanceof J.Repetition)X.walkMany(E,$,Z);else if(E instanceof J.Alternation)X.walkOr(E,$,Z);else throw Error("non exhaustive match")})},U.prototype.walkTerminal=function(Y,Z,X){},U.prototype.walkProdRef=function(Y,Z,X){},U.prototype.walkFlat=function(Y,Z,X){var E=Z.concat(X);this.walk(Y,E)},U.prototype.walkOption=function(Y,Z,X){var E=Z.concat(X);this.walk(Y,E)},U.prototype.walkAtLeastOne=function(Y,Z,X){var E=[new J.Option({definition:Y.definition})].concat(Z,X);this.walk(Y,E)},U.prototype.walkAtLeastOneSep=function(Y,Z,X){var E=C(Y,Z,X);this.walk(Y,E)},U.prototype.walkMany=function(Y,Z,X){var E=[new J.Option({definition:Y.definition})].concat(Z,X);this.walk(Y,E)},U.prototype.walkManySep=function(Y,Z,X){var E=C(Y,Z,X);this.walk(Y,E)},U.prototype.walkOr=function(Y,Z,X){var E=this,H=Z.concat(X);Q.forEach(Y.definition,function($){var I=new J.Alternative({definition:[$]});E.walk(I,H)})},U}();A.RestWalker=K;function C(U,Y,Z){var X=[new J.Option({definition:[new J.Terminal({terminalType:U.separator})].concat(U.definition)})],E=X.concat(Y,Z);return E}}),$B=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.GAstVisitor=void 0;var Q=I9(),J=function(){function K(){}return K.prototype.visit=function(C){var U=C;switch(U.constructor){case Q.NonTerminal:return this.visitNonTerminal(U);case Q.Alternative:return this.visitAlternative(U);case Q.Option:return this.visitOption(U);case Q.RepetitionMandatory:return this.visitRepetitionMandatory(U);case Q.RepetitionMandatoryWithSeparator:return this.visitRepetitionMandatoryWithSeparator(U);case Q.RepetitionWithSeparator:return this.visitRepetitionWithSeparator(U);case Q.Repetition:return this.visitRepetition(U);case Q.Alternation:return this.visitAlternation(U);case Q.Terminal:return this.visitTerminal(U);case Q.Rule:return this.visitRule(U);default:throw Error("non exhaustive match")}},K.prototype.visitNonTerminal=function(C){},K.prototype.visitAlternative=function(C){},K.prototype.visitOption=function(C){},K.prototype.visitRepetition=function(C){},K.prototype.visitRepetitionMandatory=function(C){},K.prototype.visitRepetitionMandatoryWithSeparator=function(C){},K.prototype.visitRepetitionWithSeparator=function(C){},K.prototype.visitAlternation=function(C){},K.prototype.visitTerminal=function(C){},K.prototype.visitRule=function(C){},K}();A.GAstVisitor=J}),AW=vA((A)=>{var Q=A&&A.__extends||function(){var I=function(N,F){return I=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(V,D){V.__proto__=D}||function(V,D){for(var L in D)Object.prototype.hasOwnProperty.call(D,L)&&(V[L]=D[L])},I(N,F)};return function(N,F){if(typeof F!="function"&&F!==null)throw new TypeError("Class extends value "+String(F)+" is not a constructor or null");I(N,F);function V(){this.constructor=N}N.prototype=F===null?Object.create(F):(V.prototype=F.prototype,new V)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.collectMethods=A.DslMethodsCollectorVisitor=A.getProductionDslName=A.isBranchingProd=A.isOptionalProd=A.isSequenceProd=void 0;var J=G2(),K=I9(),C=$B();function U(I){return I instanceof K.Alternative||I instanceof K.Option||I instanceof K.Repetition||I instanceof K.RepetitionMandatory||I instanceof K.RepetitionMandatoryWithSeparator||I instanceof K.RepetitionWithSeparator||I instanceof K.Terminal||I instanceof K.Rule}A.isSequenceProd=U;function Y(I,N){N===void 0&&(N=[]);var F=I instanceof K.Option||I instanceof K.Repetition||I instanceof K.RepetitionWithSeparator;return F?!0:I instanceof K.Alternation?J.some(I.definition,function(V){return Y(V,N)}):I instanceof K.NonTerminal&&J.contains(N,I)?!1:I instanceof K.AbstractProduction?(I instanceof K.NonTerminal&&N.push(I),J.every(I.definition,function(V){return Y(V,N)})):!1}A.isOptionalProd=Y;function Z(I){return I instanceof K.Alternation}A.isBranchingProd=Z;function X(I){if(I instanceof K.NonTerminal)return"SUBRULE";if(I instanceof K.Option)return"OPTION";if(I instanceof K.Alternation)return"OR";if(I instanceof K.RepetitionMandatory)return"AT_LEAST_ONE";if(I instanceof K.RepetitionMandatoryWithSeparator)return"AT_LEAST_ONE_SEP";if(I instanceof K.RepetitionWithSeparator)return"MANY_SEP";if(I instanceof K.Repetition)return"MANY";if(I instanceof K.Terminal)return"CONSUME";throw Error("non exhaustive match")}A.getProductionDslName=X;var E=function(I){Q(N,I);function N(){var F=I!==null&&I.apply(this,arguments)||this;return F.separator="-",F.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]},F}return N.prototype.reset=function(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}},N.prototype.visitTerminal=function(F){var V=F.terminalType.name+this.separator+"Terminal";J.has(this.dslMethods,V)||(this.dslMethods[V]=[]),this.dslMethods[V].push(F)},N.prototype.visitNonTerminal=function(F){var V=F.nonTerminalName+this.separator+"Terminal";J.has(this.dslMethods,V)||(this.dslMethods[V]=[]),this.dslMethods[V].push(F)},N.prototype.visitOption=function(F){this.dslMethods.option.push(F)},N.prototype.visitRepetitionWithSeparator=function(F){this.dslMethods.repetitionWithSeparator.push(F)},N.prototype.visitRepetitionMandatory=function(F){this.dslMethods.repetitionMandatory.push(F)},N.prototype.visitRepetitionMandatoryWithSeparator=function(F){this.dslMethods.repetitionMandatoryWithSeparator.push(F)},N.prototype.visitRepetition=function(F){this.dslMethods.repetition.push(F)},N.prototype.visitAlternation=function(F){this.dslMethods.alternation.push(F)},N}(C.GAstVisitor);A.DslMethodsCollectorVisitor=E;var H=new E;function $(I){H.reset(),I.accept(H);var N=H.dslMethods;return H.reset(),N}A.collectMethods=$}),mm=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.firstForTerminal=A.firstForBranching=A.firstForSequence=A.first=void 0;var Q=G2(),J=I9(),K=AW();function C(X){if(X instanceof J.NonTerminal)return C(X.referencedRule);if(X instanceof J.Terminal)return Z(X);if(K.isSequenceProd(X))return U(X);if(K.isBranchingProd(X))return Y(X);throw Error("non exhaustive match")}A.first=C;function U(X){for(var E=[],H=X.definition,$=0,I=H.length>$,N,F=!0;I&&F;)N=H[$],F=K.isOptionalProd(N),E=E.concat(C(N)),$=$+1,I=H.length>$;return Q.uniq(E)}A.firstForSequence=U;function Y(X){var E=Q.map(X.definition,function(H){return C(H)});return Q.uniq(Q.flatten(E))}A.firstForBranching=Y;function Z(X){return[X.terminalType]}A.firstForTerminal=Z}),cm=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.IN=void 0,A.IN="_~IN~_"}),kB1=vA((A)=>{var Q=A&&A.__extends||function(){var $=function(I,N){return $=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(F,V){F.__proto__=V}||function(F,V){for(var D in V)Object.prototype.hasOwnProperty.call(V,D)&&(F[D]=V[D])},$(I,N)};return function(I,N){if(typeof N!="function"&&N!==null)throw new TypeError("Class extends value "+String(N)+" is not a constructor or null");$(I,N);function F(){this.constructor=I}I.prototype=N===null?Object.create(N):(F.prototype=N.prototype,new F)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.buildInProdFollowPrefix=A.buildBetweenProdsFollowPrefix=A.computeAllProdsFollows=A.ResyncFollowsWalker=void 0;var J=AD(),K=mm(),C=G2(),U=cm(),Y=I9(),Z=function($){Q(I,$);function I(N){var F=$.call(this)||this;return F.topProd=N,F.follows={},F}return I.prototype.startWalking=function(){return this.walk(this.topProd),this.follows},I.prototype.walkTerminal=function(N,F,V){},I.prototype.walkProdRef=function(N,F,V){var D=E(N.referencedRule,N.idx)+this.topProd.name,L=F.concat(V),R=new Y.Alternative({definition:L}),M=K.first(R);this.follows[D]=M},I}(J.RestWalker);A.ResyncFollowsWalker=Z;function X($){var I={};return C.forEach($,function(N){var F=new Z(N).startWalking();C.assign(I,F)}),I}A.computeAllProdsFollows=X;function E($,I){return $.name+I+U.IN}A.buildBetweenProdsFollowPrefix=E;function H($){var I=$.terminalType.name;return I+$.idx+U.IN}A.buildInProdFollowPrefix=H}),QW=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.defaultGrammarValidatorErrorProvider=A.defaultGrammarResolverErrorProvider=A.defaultParserErrorProvider=void 0;var Q=EJ(),J=G2(),K=G2(),C=I9(),U=AW();A.defaultParserErrorProvider={buildMismatchTokenMessage:function(Y){var{expected:Z,actual:X,previous:E,ruleName:H}=Y,$=Q.hasTokenLabel(Z),I=$?"--> "+Q.tokenLabel(Z)+" <--":"token of type --> "+Z.name+" <--",N="Expecting "+I+" but found --> '"+X.image+"' <--";return N},buildNotAllInputParsedMessage:function(Y){var{firstRedundant:Z,ruleName:X}=Y;return"Redundant input, expecting EOF but found: "+Z.image},buildNoViableAltMessage:function(Y){var{expectedPathsPerAlt:Z,actual:X,previous:E,customUserDescription:H,ruleName:$}=Y,I="Expecting: ",N=K.first(X).image,F=` -but found: '`+N+"'";if(H)return I+H+F;var V=K.reduce(Z,function(M,T){return M.concat(T)},[]),D=K.map(V,function(M){return"["+K.map(M,function(T){return Q.tokenLabel(T)}).join(", ")+"]"}),L=K.map(D,function(M,T){return" "+(T+1)+". "+M}),R=`one of these possible Token sequences: -`+L.join(` -`);return I+R+F},buildEarlyExitMessage:function(Y){var{expectedIterationPaths:Z,actual:X,customUserDescription:E,ruleName:H}=Y,$="Expecting: ",I=K.first(X).image,N=` -but found: '`+I+"'";if(E)return $+E+N;var F=K.map(Z,function(D){return"["+K.map(D,function(L){return Q.tokenLabel(L)}).join(",")+"]"}),V=`expecting at least one iteration which starts with one of these possible Token sequences:: - `+("<"+F.join(" ,")+">");return $+V+N}},Object.freeze(A.defaultParserErrorProvider),A.defaultGrammarResolverErrorProvider={buildRuleNotFoundError:function(Y,Z){var X="Invalid grammar, reference to a rule which is not defined: ->"+Z.nonTerminalName+`<- -inside top level rule: ->`+Y.name+"<-";return X}},A.defaultGrammarValidatorErrorProvider={buildDuplicateFoundError:function(Y,Z){function X(D){return D instanceof C.Terminal?D.terminalType.name:D instanceof C.NonTerminal?D.nonTerminalName:""}var E=Y.name,H=K.first(Z),$=H.idx,I=U.getProductionDslName(H),N=X(H),F=$>0,V="->"+I+(F?$:"")+"<- "+(N?"with argument: ->"+N+"<-":"")+` - appears more than once (`+Z.length+" times) in the top level rule: ->"+E+`<-. - For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES - `;return V=V.replace(/[ \t]+/g," "),V=V.replace(/\s\s+/g,` -`),V},buildNamespaceConflictError:function(Y){var Z=`Namespace conflict found in grammar. -`+("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <"+Y.name+`>. -`)+`To resolve this make sure each Terminal and Non-Terminal names are unique -This is easy to accomplish by using the convention that Terminal names start with an uppercase letter -and Non-Terminal names start with a lower case letter.`;return Z},buildAlternationPrefixAmbiguityError:function(Y){var Z=K.map(Y.prefixPath,function(H){return Q.tokenLabel(H)}).join(", "),X=Y.alternation.idx===0?"":Y.alternation.idx,E="Ambiguous alternatives: <"+Y.ambiguityIndices.join(" ,")+`> due to common lookahead prefix -`+("in inside <"+Y.topLevelRule.name+`> Rule, -`)+("<"+Z+`> may appears as a prefix path in all these alternatives. -`)+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX -For Further details.`;return E},buildAlternationAmbiguityError:function(Y){var Z=K.map(Y.prefixPath,function(H){return Q.tokenLabel(H)}).join(", "),X=Y.alternation.idx===0?"":Y.alternation.idx,E="Ambiguous Alternatives Detected: <"+Y.ambiguityIndices.join(" ,")+"> in "+(" inside <"+Y.topLevelRule.name+`> Rule, -`)+("<"+Z+`> may appears as a prefix path in all these alternatives. -`);return E=E+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES -For Further details.`,E},buildEmptyRepetitionError:function(Y){var Z=U.getProductionDslName(Y.repetition);Y.repetition.idx!==0&&(Z+=Y.repetition.idx);var X="The repetition <"+Z+"> within Rule <"+Y.topLevelRule.name+`> can never consume any tokens. -This could lead to an infinite loop.`;return X},buildTokenNameError:function(Y){return"deprecated"},buildEmptyAlternationError:function(Y){var Z="Ambiguous empty alternative: <"+(Y.emptyChoiceIdx+1)+">"+(" in inside <"+Y.topLevelRule.name+`> Rule. -`)+"Only the last alternative may be an empty alternative.";return Z},buildTooManyAlternativesError:function(Y){var Z=`An Alternation cannot have more than 256 alternatives: -`+(" inside <"+Y.topLevelRule.name+`> Rule. - has `+(Y.alternation.definition.length+1)+" alternatives.");return Z},buildLeftRecursionError:function(Y){var Z=Y.topLevelRule.name,X=J.map(Y.leftRecursionPath,function($){return $.name}),E=Z+" --> "+X.concat([Z]).join(" --> "),H=`Left Recursion found in grammar. -`+("rule: <"+Z+`> can be invoked from itself (directly or indirectly) -`)+(`without consuming any Tokens. The grammar path that causes this is: - `+E+` -`)+` To fix this refactor your grammar to remove the left recursion. -see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring.`;return H},buildInvalidRuleNameError:function(Y){return"deprecated"},buildDuplicateRuleNameError:function(Y){var Z;Y.topLevelRule instanceof C.Rule?Z=Y.topLevelRule.name:Z=Y.topLevelRule;var X="Duplicate definition, rule: ->"+Z+"<- is already defined in the grammar: ->"+Y.grammarName+"<-";return X}}}),SB1=vA((A)=>{var Q=A&&A.__extends||function(){var Z=function(X,E){return Z=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,$){H.__proto__=$}||function(H,$){for(var I in $)Object.prototype.hasOwnProperty.call($,I)&&(H[I]=$[I])},Z(X,E)};return function(X,E){if(typeof E!="function"&&E!==null)throw new TypeError("Class extends value "+String(E)+" is not a constructor or null");Z(X,E);function H(){this.constructor=X}X.prototype=E===null?Object.create(E):(H.prototype=E.prototype,new H)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.GastRefResolverVisitor=A.resolveGrammar=void 0;var J=d9(),K=G2(),C=$B();function U(Z,X){var E=new Y(Z,X);return E.resolveRefs(),E.errors}A.resolveGrammar=U;var Y=function(Z){Q(X,Z);function X(E,H){var $=Z.call(this)||this;return $.nameToTopRule=E,$.errMsgProvider=H,$.errors=[],$}return X.prototype.resolveRefs=function(){var E=this;K.forEach(K.values(this.nameToTopRule),function(H){E.currTopLevel=H,H.accept(E)})},X.prototype.visitNonTerminal=function(E){var H=this.nameToTopRule[E.nonTerminalName];if(H)E.referencedRule=H;else{var $=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,E);this.errors.push({message:$,type:J.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:E.nonTerminalName})}},X}(C.GAstVisitor);A.GastRefResolverVisitor=Y}),JW=vA((A)=>{var Q=A&&A.__extends||function(){var D=function(L,R){return D=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(M,T){M.__proto__=T}||function(M,T){for(var h in T)Object.prototype.hasOwnProperty.call(T,h)&&(M[h]=T[h])},D(L,R)};return function(L,R){if(typeof R!="function"&&R!==null)throw new TypeError("Class extends value "+String(R)+" is not a constructor or null");D(L,R);function M(){this.constructor=L}L.prototype=R===null?Object.create(R):(M.prototype=R.prototype,new M)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.nextPossibleTokensAfter=A.possiblePathsFrom=A.NextTerminalAfterAtLeastOneSepWalker=A.NextTerminalAfterAtLeastOneWalker=A.NextTerminalAfterManySepWalker=A.NextTerminalAfterManyWalker=A.AbstractNextTerminalAfterProductionWalker=A.NextAfterTokenWalker=A.AbstractNextPossibleTokensWalker=void 0;var J=AD(),K=G2(),C=mm(),U=I9(),Y=function(D){Q(L,D);function L(R,M){var T=D.call(this)||this;return T.topProd=R,T.path=M,T.possibleTokTypes=[],T.nextProductionName="",T.nextProductionOccurrence=0,T.found=!1,T.isAtEndOfPath=!1,T}return L.prototype.startWalking=function(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=K.cloneArr(this.path.ruleStack).reverse(),this.occurrenceStack=K.cloneArr(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes},L.prototype.walk=function(R,M){M===void 0&&(M=[]),this.found||D.prototype.walk.call(this,R,M)},L.prototype.walkProdRef=function(R,M,T){if(R.referencedRule.name===this.nextProductionName&&R.idx===this.nextProductionOccurrence){var h=M.concat(T);this.updateExpectedNext(),this.walk(R.referencedRule,h)}},L.prototype.updateExpectedNext=function(){K.isEmpty(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())},L}(J.RestWalker);A.AbstractNextPossibleTokensWalker=Y;var Z=function(D){Q(L,D);function L(R,M){var T=D.call(this,R,M)||this;return T.path=M,T.nextTerminalName="",T.nextTerminalOccurrence=0,T.nextTerminalName=T.path.lastTok.name,T.nextTerminalOccurrence=T.path.lastTokOccurrence,T}return L.prototype.walkTerminal=function(R,M,T){if(this.isAtEndOfPath&&R.terminalType.name===this.nextTerminalName&&R.idx===this.nextTerminalOccurrence&&!this.found){var h=M.concat(T),y=new U.Alternative({definition:h});this.possibleTokTypes=C.first(y),this.found=!0}},L}(Y);A.NextAfterTokenWalker=Z;var X=function(D){Q(L,D);function L(R,M){var T=D.call(this)||this;return T.topRule=R,T.occurrence=M,T.result={token:void 0,occurrence:void 0,isEndOfRule:void 0},T}return L.prototype.startWalking=function(){return this.walk(this.topRule),this.result},L}(J.RestWalker);A.AbstractNextTerminalAfterProductionWalker=X;var E=function(D){Q(L,D);function L(){return D!==null&&D.apply(this,arguments)||this}return L.prototype.walkMany=function(R,M,T){if(R.idx===this.occurrence){var h=K.first(M.concat(T));this.result.isEndOfRule=h===void 0,h instanceof U.Terminal&&(this.result.token=h.terminalType,this.result.occurrence=h.idx)}else D.prototype.walkMany.call(this,R,M,T)},L}(X);A.NextTerminalAfterManyWalker=E;var H=function(D){Q(L,D);function L(){return D!==null&&D.apply(this,arguments)||this}return L.prototype.walkManySep=function(R,M,T){if(R.idx===this.occurrence){var h=K.first(M.concat(T));this.result.isEndOfRule=h===void 0,h instanceof U.Terminal&&(this.result.token=h.terminalType,this.result.occurrence=h.idx)}else D.prototype.walkManySep.call(this,R,M,T)},L}(X);A.NextTerminalAfterManySepWalker=H;var $=function(D){Q(L,D);function L(){return D!==null&&D.apply(this,arguments)||this}return L.prototype.walkAtLeastOne=function(R,M,T){if(R.idx===this.occurrence){var h=K.first(M.concat(T));this.result.isEndOfRule=h===void 0,h instanceof U.Terminal&&(this.result.token=h.terminalType,this.result.occurrence=h.idx)}else D.prototype.walkAtLeastOne.call(this,R,M,T)},L}(X);A.NextTerminalAfterAtLeastOneWalker=$;var I=function(D){Q(L,D);function L(){return D!==null&&D.apply(this,arguments)||this}return L.prototype.walkAtLeastOneSep=function(R,M,T){if(R.idx===this.occurrence){var h=K.first(M.concat(T));this.result.isEndOfRule=h===void 0,h instanceof U.Terminal&&(this.result.token=h.terminalType,this.result.occurrence=h.idx)}else D.prototype.walkAtLeastOneSep.call(this,R,M,T)},L}(X);A.NextTerminalAfterAtLeastOneSepWalker=I;function N(D,L,R){R===void 0&&(R=[]),R=K.cloneArr(R);var M=[],T=0;function h(u){return u.concat(K.drop(D,T+1))}function y(u){var d=N(h(u),L,R);return M.concat(d)}for(;R.length=0;t--){var U1=k.definition[t],O1={idx:P,def:U1.definition.concat(K.drop(q)),ruleStack:O,occurrenceStack:w};n.push(O1),n.push(y)}else if(k instanceof U.Alternative)n.push({idx:P,def:k.definition.concat(K.drop(q)),ruleStack:O,occurrenceStack:w});else if(k instanceof U.Rule)n.push(V(k,P,O,w));else throw Error("non exhaustive match")}}return d}A.nextPossibleTokensAfter=F;function V(D,L,R,M){var T=K.cloneArr(R);T.push(D.name);var h=K.cloneArr(M);return h.push(1),{idx:L,def:D.definition,ruleStack:T,occurrenceStack:h}}}),KW=vA((A)=>{var Q=A&&A.__extends||function(){var u=function(d,n){return u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(B,q){B.__proto__=q}||function(B,q){for(var P in q)Object.prototype.hasOwnProperty.call(q,P)&&(B[P]=q[P])},u(d,n)};return function(d,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");u(d,n);function B(){this.constructor=d}d.prototype=n===null?Object.create(n):(B.prototype=n.prototype,new B)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.areTokenCategoriesNotUsed=A.isStrictPrefixOfPath=A.containsPath=A.getLookaheadPathsForOptionalProd=A.getLookaheadPathsForOr=A.lookAheadSequenceFromAlternatives=A.buildSingleAlternativeLookaheadFunction=A.buildAlternativesLookAheadFunc=A.buildLookaheadFuncForOptionalProd=A.buildLookaheadFuncForOr=A.getProdType=A.PROD_TYPE=void 0;var J=G2(),K=JW(),C=AD(),U=EB(),Y=I9(),Z=$B(),X;(function(u){u[u.OPTION=0]="OPTION",u[u.REPETITION=1]="REPETITION",u[u.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",u[u.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",u[u.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",u[u.ALTERNATION=5]="ALTERNATION"})(X=A.PROD_TYPE||(A.PROD_TYPE={}));function E(u){if(u instanceof Y.Option)return X.OPTION;if(u instanceof Y.Repetition)return X.REPETITION;if(u instanceof Y.RepetitionMandatory)return X.REPETITION_MANDATORY;if(u instanceof Y.RepetitionMandatoryWithSeparator)return X.REPETITION_MANDATORY_WITH_SEPARATOR;if(u instanceof Y.RepetitionWithSeparator)return X.REPETITION_WITH_SEPARATOR;if(u instanceof Y.Alternation)return X.ALTERNATION;throw Error("non exhaustive match")}A.getProdType=E;function H(u,d,n,B,q,P){var O=T(u,d,n),w=f(O)?U.tokenStructuredMatcherNoCategories:U.tokenStructuredMatcher;return P(O,B,w,q)}A.buildLookaheadFuncForOr=H;function $(u,d,n,B,q,P){var O=h(u,d,q,n),w=f(O)?U.tokenStructuredMatcherNoCategories:U.tokenStructuredMatcher;return P(O[0],w,B)}A.buildLookaheadFuncForOptionalProd=$;function I(u,d,n,B){var q=u.length,P=J.every(u,function(k){return J.every(k,function(S){return S.length===1})});if(d)return function(k){for(var S=J.map(k,function(e){return e.GATE}),_=0;_{var Q=A&&A.__extends||function(){var B=function(q,P){return B=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(O,w){O.__proto__=w}||function(O,w){for(var k in w)Object.prototype.hasOwnProperty.call(w,k)&&(O[k]=w[k])},B(q,P)};return function(q,P){if(typeof P!="function"&&P!==null)throw new TypeError("Class extends value "+String(P)+" is not a constructor or null");B(q,P);function O(){this.constructor=q}q.prototype=P===null?Object.create(P):(O.prototype=P.prototype,new O)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.checkPrefixAlternativesAmbiguities=A.validateSomeNonEmptyLookaheadPath=A.validateTooManyAlts=A.RepetionCollector=A.validateAmbiguousAlternationAlternatives=A.validateEmptyOrAlternative=A.getFirstNoneTerminal=A.validateNoLeftRecursion=A.validateRuleIsOverridden=A.validateRuleDoesNotAlreadyExist=A.OccurrenceValidationCollector=A.identifyProductionForDuplicates=A.validateGrammar=void 0;var J=G2(),K=G2(),C=d9(),U=AW(),Y=KW(),Z=JW(),X=I9(),E=$B();function H(B,q,P,O,w){var k=J.map(B,function(r){return $(r,O)}),S=J.map(B,function(r){return L(r,r,O)}),_=[],W=[],j=[];K.every(S,K.isEmpty)&&(_=K.map(B,function(r){return T(r,O)}),W=K.map(B,function(r){return h(r,q,O)}),j=f(B,q,O));var b=n(B,P,O),p=K.map(B,function(r){return g(r,O)}),s=K.map(B,function(r){return V(r,B,w,O)});return J.flatten(k.concat(j,S,_,W,b,p,s))}A.validateGrammar=H;function $(B,q){var P=new F;B.accept(P);var O=P.allProductions,w=J.groupBy(O,I),k=J.pick(w,function(_){return _.length>1}),S=J.map(J.values(k),function(_){var W=J.first(_),j=q.buildDuplicateFoundError(B,_),b=U.getProductionDslName(W),p={message:j,type:C.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,ruleName:B.name,dslName:b,occurrence:W.idx},s=N(W);return s&&(p.parameter=s),p});return S}function I(B){return U.getProductionDslName(B)+"_#_"+B.idx+"_#_"+N(B)}A.identifyProductionForDuplicates=I;function N(B){return B instanceof X.Terminal?B.terminalType.name:B instanceof X.NonTerminal?B.nonTerminalName:""}var F=function(B){Q(q,B);function q(){var P=B!==null&&B.apply(this,arguments)||this;return P.allProductions=[],P}return q.prototype.visitNonTerminal=function(P){this.allProductions.push(P)},q.prototype.visitOption=function(P){this.allProductions.push(P)},q.prototype.visitRepetitionWithSeparator=function(P){this.allProductions.push(P)},q.prototype.visitRepetitionMandatory=function(P){this.allProductions.push(P)},q.prototype.visitRepetitionMandatoryWithSeparator=function(P){this.allProductions.push(P)},q.prototype.visitRepetition=function(P){this.allProductions.push(P)},q.prototype.visitAlternation=function(P){this.allProductions.push(P)},q.prototype.visitTerminal=function(P){this.allProductions.push(P)},q}(E.GAstVisitor);A.OccurrenceValidationCollector=F;function V(B,q,P,O){var w=[],k=K.reduce(q,function(_,W){return W.name===B.name?_+1:_},0);if(k>1){var S=O.buildDuplicateRuleNameError({topLevelRule:B,grammarName:P});w.push({message:S,type:C.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:B.name})}return w}A.validateRuleDoesNotAlreadyExist=V;function D(B,q,P){var O=[],w;return J.contains(q,B)||(w="Invalid rule override, rule: ->"+B+"<- cannot be overridden in the grammar: ->"+P+"<-as it is not defined in any of the super grammars ",O.push({message:w,type:C.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,ruleName:B})),O}A.validateRuleIsOverridden=D;function L(B,q,P,O){O===void 0&&(O=[]);var w=[],k=R(q.definition);if(J.isEmpty(k))return[];var S=B.name,_=J.contains(k,B);_&&w.push({message:P.buildLeftRecursionError({topLevelRule:B,leftRecursionPath:O}),type:C.ParserDefinitionErrorType.LEFT_RECURSION,ruleName:S});var W=J.difference(k,O.concat([B])),j=J.map(W,function(b){var p=J.cloneArr(O);return p.push(b),L(B,b,P,p)});return w.concat(J.flatten(j))}A.validateNoLeftRecursion=L;function R(B){var q=[];if(J.isEmpty(B))return q;var P=J.first(B);if(P instanceof X.NonTerminal)q.push(P.referencedRule);else if(P instanceof X.Alternative||P instanceof X.Option||P instanceof X.RepetitionMandatory||P instanceof X.RepetitionMandatoryWithSeparator||P instanceof X.RepetitionWithSeparator||P instanceof X.Repetition)q=q.concat(R(P.definition));else if(P instanceof X.Alternation)q=J.flatten(J.map(P.definition,function(S){return R(S.definition)}));else if(!(P instanceof X.Terminal))throw Error("non exhaustive match");var O=U.isOptionalProd(P),w=B.length>1;if(O&&w){var k=J.drop(B);return q.concat(R(k))}else return q}A.getFirstNoneTerminal=R;var M=function(B){Q(q,B);function q(){var P=B!==null&&B.apply(this,arguments)||this;return P.alternations=[],P}return q.prototype.visitAlternation=function(P){this.alternations.push(P)},q}(E.GAstVisitor);function T(B,q){var P=new M;B.accept(P);var O=P.alternations,w=J.reduce(O,function(k,S){var _=J.dropRight(S.definition),W=J.map(_,function(j,b){var p=Z.nextPossibleTokensAfter([j],[],null,1);return J.isEmpty(p)?{message:q.buildEmptyAlternationError({topLevelRule:B,alternation:S,emptyChoiceIdx:b}),type:C.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,ruleName:B.name,occurrence:S.idx,alternative:b+1}:null});return k.concat(J.compact(W))},[]);return w}A.validateEmptyOrAlternative=T;function h(B,q,P){var O=new M;B.accept(O);var w=O.alternations;w=K.reject(w,function(S){return S.ignoreAmbiguities===!0});var k=J.reduce(w,function(S,_){var W=_.idx,j=_.maxLookahead||q,b=Y.getLookaheadPathsForOr(W,B,j,_),p=u(b,_,B,P),s=d(b,_,B,P);return S.concat(p,s)},[]);return k}A.validateAmbiguousAlternationAlternatives=h;var y=function(B){Q(q,B);function q(){var P=B!==null&&B.apply(this,arguments)||this;return P.allProductions=[],P}return q.prototype.visitRepetitionWithSeparator=function(P){this.allProductions.push(P)},q.prototype.visitRepetitionMandatory=function(P){this.allProductions.push(P)},q.prototype.visitRepetitionMandatoryWithSeparator=function(P){this.allProductions.push(P)},q.prototype.visitRepetition=function(P){this.allProductions.push(P)},q}(E.GAstVisitor);A.RepetionCollector=y;function g(B,q){var P=new M;B.accept(P);var O=P.alternations,w=J.reduce(O,function(k,S){return S.definition.length>255&&k.push({message:q.buildTooManyAlternativesError({topLevelRule:B,alternation:S}),type:C.ParserDefinitionErrorType.TOO_MANY_ALTS,ruleName:B.name,occurrence:S.idx}),k},[]);return w}A.validateTooManyAlts=g;function f(B,q,P){var O=[];return K.forEach(B,function(w){var k=new y;w.accept(k);var S=k.allProductions;K.forEach(S,function(_){var W=Y.getProdType(_),j=_.maxLookahead||q,b=_.idx,p=Y.getLookaheadPathsForOptionalProd(b,w,W,j),s=p[0];if(K.isEmpty(K.flatten(s))){var r=P.buildEmptyRepetitionError({topLevelRule:w,repetition:_});O.push({message:r,type:C.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,ruleName:w.name})}})}),O}A.validateSomeNonEmptyLookaheadPath=f;function u(B,q,P,O){var w=[],k=K.reduce(B,function(_,W,j){return q.definition[j].ignoreAmbiguities===!0||K.forEach(W,function(b){var p=[j];K.forEach(B,function(s,r){j!==r&&Y.containsPath(s,b)&&q.definition[r].ignoreAmbiguities!==!0&&p.push(r)}),p.length>1&&!Y.containsPath(w,b)&&(w.push(b),_.push({alts:p,path:b}))}),_},[]),S=J.map(k,function(_){var W=K.map(_.alts,function(b){return b+1}),j=O.buildAlternationAmbiguityError({topLevelRule:P,alternation:q,ambiguityIndices:W,prefixPath:_.path});return{message:j,type:C.ParserDefinitionErrorType.AMBIGUOUS_ALTS,ruleName:P.name,occurrence:q.idx,alternatives:[_.alts]}});return S}function d(B,q,P,O){var w=[],k=K.reduce(B,function(S,_,W){var j=K.map(_,function(b){return{idx:W,path:b}});return S.concat(j)},[]);return K.forEach(k,function(S){var _=q.definition[S.idx];if(_.ignoreAmbiguities!==!0){var{idx:W,path:j}=S,b=K.findAll(k,function(s){return q.definition[s.idx].ignoreAmbiguities!==!0&&s.idx{Object.defineProperty(A,"__esModule",{value:!0}),A.validateGrammar=A.resolveGrammar=void 0;var Q=G2(),J=SB1(),K=dm(),C=QW();function U(Z){Z=Q.defaults(Z,{errMsgProvider:C.defaultGrammarResolverErrorProvider});var X={};return Q.forEach(Z.rules,function(E){X[E.name]=E}),J.resolveGrammar(X,Z.errMsgProvider)}A.resolveGrammar=U;function Y(Z){return Z=Q.defaults(Z,{errMsgProvider:C.defaultGrammarValidatorErrorProvider}),K.validateGrammar(Z.rules,Z.maxLookahead,Z.tokenTypes,Z.errMsgProvider,Z.grammarName)}A.validateGrammar=Y}),HB=vA((A)=>{var Q=A&&A.__extends||function(){var F=function(V,D){return F=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(L,R){L.__proto__=R}||function(L,R){for(var M in R)Object.prototype.hasOwnProperty.call(R,M)&&(L[M]=R[M])},F(V,D)};return function(V,D){if(typeof D!="function"&&D!==null)throw new TypeError("Class extends value "+String(D)+" is not a constructor or null");F(V,D);function L(){this.constructor=V}V.prototype=D===null?Object.create(D):(L.prototype=D.prototype,new L)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.EarlyExitException=A.NotAllInputParsedException=A.NoViableAltException=A.MismatchedTokenException=A.isRecognitionException=void 0;var J=G2(),K="MismatchedTokenException",C="NoViableAltException",U="EarlyExitException",Y="NotAllInputParsedException",Z=[K,C,U,Y];Object.freeze(Z);function X(F){return J.contains(Z,F.name)}A.isRecognitionException=X;var E=function(F){Q(V,F);function V(D,L){var R=this.constructor,M=F.call(this,D)||this;return M.token=L,M.resyncedTokens=[],Object.setPrototypeOf(M,R.prototype),Error.captureStackTrace&&Error.captureStackTrace(M,M.constructor),M}return V}(Error),H=function(F){Q(V,F);function V(D,L,R){var M=F.call(this,D,L)||this;return M.previousToken=R,M.name=K,M}return V}(E);A.MismatchedTokenException=H;var $=function(F){Q(V,F);function V(D,L,R){var M=F.call(this,D,L)||this;return M.previousToken=R,M.name=C,M}return V}(E);A.NoViableAltException=$;var I=function(F){Q(V,F);function V(D,L){var R=F.call(this,D,L)||this;return R.name=Y,R}return V}(E);A.NotAllInputParsedException=I;var N=function(F){Q(V,F);function V(D,L,R){var M=F.call(this,D,L)||this;return M.previousToken=R,M.name=U,M}return V}(E);A.EarlyExitException=N}),lm=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.attemptInRepetitionRecovery=A.Recoverable=A.InRuleRecoveryException=A.IN_RULE_RECOVERY_EXCEPTION=A.EOF_FOLLOW_KEY=void 0;var Q=EJ(),J=G2(),K=HB(),C=cm(),U=d9();A.EOF_FOLLOW_KEY={},A.IN_RULE_RECOVERY_EXCEPTION="InRuleRecoveryException";function Y(E){this.name=A.IN_RULE_RECOVERY_EXCEPTION,this.message=E}A.InRuleRecoveryException=Y,Y.prototype=Error.prototype;var Z=function(){function E(){}return E.prototype.initRecoverable=function(H){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=J.has(H,"recoveryEnabled")?H.recoveryEnabled:U.DEFAULT_PARSER_CONFIG.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=X)},E.prototype.getTokenToInsert=function(H){var $=Q.createTokenInstance(H,"",NaN,NaN,NaN,NaN,NaN,NaN);return $.isInsertedInRecovery=!0,$},E.prototype.canTokenTypeBeInsertedInRecovery=function(H){return!0},E.prototype.tryInRepetitionRecovery=function(H,$,I,N){for(var F=this,V=this.findReSyncTokenType(),D=this.exportLexerState(),L=[],R=!1,M=this.LA(1),T=this.LA(1),h=function(){var y=F.LA(0),g=F.errorMessageProvider.buildMismatchTokenMessage({expected:N,actual:M,previous:y,ruleName:F.getCurrRuleFullName()}),f=new K.MismatchedTokenException(g,M,F.LA(0));f.resyncedTokens=J.dropRight(L),F.SAVE_ERROR(f)};!R;)if(this.tokenMatcher(T,N)){h();return}else if(I.call(this)){h(),H.apply(this,$);return}else this.tokenMatcher(T,V)?R=!0:(T=this.SKIP_TOKEN(),this.addToResyncTokens(T,L));this.importLexerState(D)},E.prototype.shouldInRepetitionRecoveryBeTried=function(H,$,I){return!(I===!1||H===void 0||$===void 0||this.tokenMatcher(this.LA(1),H)||this.isBackTracking()||this.canPerformInRuleRecovery(H,this.getFollowsForInRuleRecovery(H,$)))},E.prototype.getFollowsForInRuleRecovery=function(H,$){var I=this.getCurrentGrammarPath(H,$),N=this.getNextPossibleTokenTypes(I);return N},E.prototype.tryInRuleRecovery=function(H,$){if(this.canRecoverWithSingleTokenInsertion(H,$)){var I=this.getTokenToInsert(H);return I}if(this.canRecoverWithSingleTokenDeletion(H)){var N=this.SKIP_TOKEN();return this.consumeToken(),N}throw new Y("sad sad panda")},E.prototype.canPerformInRuleRecovery=function(H,$){return this.canRecoverWithSingleTokenInsertion(H,$)||this.canRecoverWithSingleTokenDeletion(H)},E.prototype.canRecoverWithSingleTokenInsertion=function(H,$){var I=this;if(!this.canTokenTypeBeInsertedInRecovery(H)||J.isEmpty($))return!1;var N=this.LA(1),F=J.find($,function(V){return I.tokenMatcher(N,V)})!==void 0;return F},E.prototype.canRecoverWithSingleTokenDeletion=function(H){var $=this.tokenMatcher(this.LA(2),H);return $},E.prototype.isInCurrentRuleReSyncSet=function(H){var $=this.getCurrFollowKey(),I=this.getFollowSetFromFollowKey($);return J.contains(I,H)},E.prototype.findReSyncTokenType=function(){for(var H=this.flattenFollowSet(),$=this.LA(1),I=2;;){var N=$.tokenType;if(J.contains(H,N))return N;$=this.LA(I),I++}},E.prototype.getCurrFollowKey=function(){if(this.RULE_STACK.length===1)return A.EOF_FOLLOW_KEY;var H=this.getLastExplicitRuleShortName(),$=this.getLastExplicitRuleOccurrenceIndex(),I=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(H),idxInCallingRule:$,inRule:this.shortRuleNameToFullName(I)}},E.prototype.buildFullFollowKeyStack=function(){var H=this,$=this.RULE_STACK,I=this.RULE_OCCURRENCE_STACK;return J.map($,function(N,F){return F===0?A.EOF_FOLLOW_KEY:{ruleName:H.shortRuleNameToFullName(N),idxInCallingRule:I[F],inRule:H.shortRuleNameToFullName($[F-1])}})},E.prototype.flattenFollowSet=function(){var H=this,$=J.map(this.buildFullFollowKeyStack(),function(I){return H.getFollowSetFromFollowKey(I)});return J.flatten($)},E.prototype.getFollowSetFromFollowKey=function(H){if(H===A.EOF_FOLLOW_KEY)return[Q.EOF];var $=H.ruleName+H.idxInCallingRule+C.IN+H.inRule;return this.resyncFollows[$]},E.prototype.addToResyncTokens=function(H,$){return this.tokenMatcher(H,Q.EOF)||$.push(H),$},E.prototype.reSyncTo=function(H){for(var $=[],I=this.LA(1);this.tokenMatcher(I,H)===!1;)I=this.SKIP_TOKEN(),this.addToResyncTokens(I,$);return J.dropRight($)},E.prototype.attemptInRepetitionRecovery=function(H,$,I,N,F,V,D){},E.prototype.getCurrentGrammarPath=function(H,$){var I=this.getHumanReadableRuleStack(),N=J.cloneArr(this.RULE_OCCURRENCE_STACK),F={ruleStack:I,occurrenceStack:N,lastTok:H,lastTokOccurrence:$};return F},E.prototype.getHumanReadableRuleStack=function(){var H=this;return J.map(this.RULE_STACK,function($){return H.shortRuleNameToFullName($)})},E}();A.Recoverable=Z;function X(E,H,$,I,N,F,V){var D=this.getKeyForAutomaticLookahead(I,N),L=this.firstAfterRepMap[D];if(L===void 0){var R=this.getCurrRuleFullName(),M=this.getGAstProductions()[R],T=new F(M,N);L=T.startWalking(),this.firstAfterRepMap[D]=L}var{token:h,occurrence:y,isEndOfRule:g}=L;this.RULE_STACK.length===1&&g&&h===void 0&&(h=Q.EOF,y=1),this.shouldInRepetitionRecoveryBeTried(h,y,V)&&this.tryInRepetitionRecovery(E,H,$,h)}A.attemptInRepetitionRecovery=X}),QD=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.getKeyForAutomaticLookahead=A.AT_LEAST_ONE_SEP_IDX=A.MANY_SEP_IDX=A.AT_LEAST_ONE_IDX=A.MANY_IDX=A.OPTION_IDX=A.OR_IDX=A.BITS_FOR_ALT_IDX=A.BITS_FOR_RULE_IDX=A.BITS_FOR_OCCURRENCE_IDX=A.BITS_FOR_METHOD_TYPE=void 0,A.BITS_FOR_METHOD_TYPE=4,A.BITS_FOR_OCCURRENCE_IDX=8,A.BITS_FOR_RULE_IDX=12,A.BITS_FOR_ALT_IDX=8,A.OR_IDX=1<{Object.defineProperty(A,"__esModule",{value:!0}),A.LooksAhead=void 0;var Q=KW(),J=G2(),K=d9(),C=QD(),U=AW(),Y=function(){function Z(){}return Z.prototype.initLooksAhead=function(X){this.dynamicTokensEnabled=J.has(X,"dynamicTokensEnabled")?X.dynamicTokensEnabled:K.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled,this.maxLookahead=J.has(X,"maxLookahead")?X.maxLookahead:K.DEFAULT_PARSER_CONFIG.maxLookahead,this.lookAheadFuncsCache=J.isES2015MapSupported()?/*@__PURE__*/new Map:[],J.isES2015MapSupported()?(this.getLaFuncFromCache=this.getLaFuncFromMap,this.setLaFuncCache=this.setLaFuncCacheUsingMap):(this.getLaFuncFromCache=this.getLaFuncFromObj,this.setLaFuncCache=this.setLaFuncUsingObj)},Z.prototype.preComputeLookaheadFunctions=function(X){var E=this;J.forEach(X,function(H){E.TRACE_INIT(H.name+" Rule Lookahead",function(){var $=U.collectMethods(H),I=$.alternation,N=$.repetition,F=$.option,V=$.repetitionMandatory,D=$.repetitionMandatoryWithSeparator,L=$.repetitionWithSeparator;J.forEach(I,function(R){var M=R.idx===0?"":R.idx;E.TRACE_INIT(""+U.getProductionDslName(R)+M,function(){var T=Q.buildLookaheadFuncForOr(R.idx,H,R.maxLookahead||E.maxLookahead,R.hasPredicates,E.dynamicTokensEnabled,E.lookAheadBuilderForAlternatives),h=C.getKeyForAutomaticLookahead(E.fullRuleNameToShort[H.name],C.OR_IDX,R.idx);E.setLaFuncCache(h,T)})}),J.forEach(N,function(R){E.computeLookaheadFunc(H,R.idx,C.MANY_IDX,Q.PROD_TYPE.REPETITION,R.maxLookahead,U.getProductionDslName(R))}),J.forEach(F,function(R){E.computeLookaheadFunc(H,R.idx,C.OPTION_IDX,Q.PROD_TYPE.OPTION,R.maxLookahead,U.getProductionDslName(R))}),J.forEach(V,function(R){E.computeLookaheadFunc(H,R.idx,C.AT_LEAST_ONE_IDX,Q.PROD_TYPE.REPETITION_MANDATORY,R.maxLookahead,U.getProductionDslName(R))}),J.forEach(D,function(R){E.computeLookaheadFunc(H,R.idx,C.AT_LEAST_ONE_SEP_IDX,Q.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,R.maxLookahead,U.getProductionDslName(R))}),J.forEach(L,function(R){E.computeLookaheadFunc(H,R.idx,C.MANY_SEP_IDX,Q.PROD_TYPE.REPETITION_WITH_SEPARATOR,R.maxLookahead,U.getProductionDslName(R))})})})},Z.prototype.computeLookaheadFunc=function(X,E,H,$,I,N){var F=this;this.TRACE_INIT(""+N+(E===0?"":E),function(){var V=Q.buildLookaheadFuncForOptionalProd(E,X,I||F.maxLookahead,F.dynamicTokensEnabled,$,F.lookAheadBuilderForOptional),D=C.getKeyForAutomaticLookahead(F.fullRuleNameToShort[X.name],H,E);F.setLaFuncCache(D,V)})},Z.prototype.lookAheadBuilderForOptional=function(X,E,H){return Q.buildSingleAlternativeLookaheadFunction(X,E,H)},Z.prototype.lookAheadBuilderForAlternatives=function(X,E,H,$){return Q.buildAlternativesLookAheadFunc(X,E,H,$)},Z.prototype.getKeyForAutomaticLookahead=function(X,E){var H=this.getLastExplicitRuleShortName();return C.getKeyForAutomaticLookahead(H,X,E)},Z.prototype.getLaFuncFromCache=function(X){},Z.prototype.getLaFuncFromMap=function(X){return this.lookAheadFuncsCache.get(X)},Z.prototype.getLaFuncFromObj=function(X){return this.lookAheadFuncsCache[X]},Z.prototype.setLaFuncCache=function(X,E){},Z.prototype.setLaFuncCacheUsingMap=function(X,E){this.lookAheadFuncsCache.set(X,E)},Z.prototype.setLaFuncUsingObj=function(X,E){this.lookAheadFuncsCache[X]=E},Z}();A.LooksAhead=Y}),xB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.addNoneTerminalToCst=A.addTerminalToCst=A.setNodeLocationFull=A.setNodeLocationOnlyOffset=void 0;function Q(U,Y){isNaN(U.startOffset)===!0?(U.startOffset=Y.startOffset,U.endOffset=Y.endOffset):U.endOffset{Object.defineProperty(A,"__esModule",{value:!0}),A.defineNameProp=A.functionName=A.classNameFromInstance=void 0;var Q=G2();function J(Y){return C(Y.constructor)}A.classNameFromInstance=J;var K="name";function C(Y){var Z=Y.name;return Z||"anonymous"}A.functionName=C;function U(Y,Z){var X=Object.getOwnPropertyDescriptor(Y,K);return Q.isUndefined(X)||X.configurable?(Object.defineProperty(Y,K,{enumerable:!1,configurable:!0,writable:!1,value:Z}),!0):!1}A.defineNameProp=U}),yB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.validateRedundantMethods=A.validateMissingCstMethods=A.validateVisitor=A.CstVisitorDefinitionError=A.createBaseVisitorConstructorWithDefaults=A.createBaseSemanticVisitorConstructor=A.defaultVisit=void 0;var Q=G2(),J=nm();function K($,I){for(var N=Q.keys($),F=N.length,V=0;V: - `+(""+D.join(` - -`).replace(/\n/g,` - `)))}}};return N.prototype=F,N.prototype.constructor=N,N._RULE_NAMES=I,N}A.createBaseSemanticVisitorConstructor=C;function U($,I,N){var F=function(){};J.defineNameProp(F,$+"BaseSemanticsWithDefaults");var V=Object.create(N.prototype);return Q.forEach(I,function(D){V[D]=K}),F.prototype=V,F.prototype.constructor=F,F}A.createBaseVisitorConstructorWithDefaults=U;var Y;(function($){$[$.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",$[$.MISSING_METHOD=1]="MISSING_METHOD"})(Y=A.CstVisitorDefinitionError||(A.CstVisitorDefinitionError={}));function Z($,I){var N=X($,I),F=H($,I);return N.concat(F)}A.validateVisitor=Z;function X($,I){var N=Q.map(I,function(F){if(!Q.isFunction($[F]))return{msg:"Missing visitor method: <"+F+"> on "+J.functionName($.constructor)+" CST Visitor.",type:Y.MISSING_METHOD,methodName:F}});return Q.compact(N)}A.validateMissingCstMethods=X;var E=["constructor","visit","validateVisitor"];function H($,I){var N=[];for(var F in $)Q.isFunction($[F])&&!Q.contains(E,F)&&!Q.contains(I,F)&&N.push({msg:"Redundant visitor method: <"+F+"> on "+J.functionName($.constructor)+` CST Visitor -There is no Grammar Rule corresponding to this method's name. -`,type:Y.REDUNDANT_METHOD,methodName:F});return N}A.validateRedundantMethods=H}),hB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.TreeBuilder=void 0;var Q=xB1(),J=G2(),K=yB1(),C=d9(),U=function(){function Y(){}return Y.prototype.initTreeBuilder=function(Z){if(this.CST_STACK=[],this.outputCst=Z.outputCst,this.nodeLocationTracking=J.has(Z,"nodeLocationTracking")?Z.nodeLocationTracking:C.DEFAULT_PARSER_CONFIG.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=J.NOOP,this.cstFinallyStateUpdate=J.NOOP,this.cstPostTerminal=J.NOOP,this.cstPostNonTerminal=J.NOOP,this.cstPostRule=J.NOOP;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Q.setNodeLocationFull,this.setNodeLocationFromNode=Q.setNodeLocationFull,this.cstPostRule=J.NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=J.NOOP,this.setNodeLocationFromNode=J.NOOP,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Q.setNodeLocationOnlyOffset,this.setNodeLocationFromNode=Q.setNodeLocationOnlyOffset,this.cstPostRule=J.NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=J.NOOP,this.setNodeLocationFromNode=J.NOOP,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=J.NOOP,this.setNodeLocationFromNode=J.NOOP,this.cstPostRule=J.NOOP,this.setInitialNodeLocation=J.NOOP;else throw Error('Invalid config option: "'+Z.nodeLocationTracking+'"')},Y.prototype.setInitialNodeLocationOnlyOffsetRecovery=function(Z){Z.location={startOffset:NaN,endOffset:NaN}},Y.prototype.setInitialNodeLocationOnlyOffsetRegular=function(Z){Z.location={startOffset:this.LA(1).startOffset,endOffset:NaN}},Y.prototype.setInitialNodeLocationFullRecovery=function(Z){Z.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}},Y.prototype.setInitialNodeLocationFullRegular=function(Z){var X=this.LA(1);Z.location={startOffset:X.startOffset,startLine:X.startLine,startColumn:X.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}},Y.prototype.cstInvocationStateUpdate=function(Z,X){var E={name:Z,children:{}};this.setInitialNodeLocation(E),this.CST_STACK.push(E)},Y.prototype.cstFinallyStateUpdate=function(){this.CST_STACK.pop()},Y.prototype.cstPostRuleFull=function(Z){var X=this.LA(0),E=Z.location;E.startOffset<=X.startOffset?(E.endOffset=X.endOffset,E.endLine=X.endLine,E.endColumn=X.endColumn):(E.startOffset=NaN,E.startLine=NaN,E.startColumn=NaN)},Y.prototype.cstPostRuleOnlyOffset=function(Z){var X=this.LA(0),E=Z.location;E.startOffset<=X.startOffset?E.endOffset=X.endOffset:E.startOffset=NaN},Y.prototype.cstPostTerminal=function(Z,X){var E=this.CST_STACK[this.CST_STACK.length-1];Q.addTerminalToCst(E,X,Z),this.setNodeLocationFromToken(E.location,X)},Y.prototype.cstPostNonTerminal=function(Z,X){var E=this.CST_STACK[this.CST_STACK.length-1];Q.addNoneTerminalToCst(E,X,Z),this.setNodeLocationFromNode(E.location,Z.location)},Y.prototype.getBaseCstVisitorConstructor=function(){if(J.isUndefined(this.baseCstVisitorConstructor)){var Z=K.createBaseSemanticVisitorConstructor(this.className,J.keys(this.gastProductionsCache));return this.baseCstVisitorConstructor=Z,Z}return this.baseCstVisitorConstructor},Y.prototype.getBaseCstVisitorConstructorWithDefaults=function(){if(J.isUndefined(this.baseCstVisitorWithDefaultsConstructor)){var Z=K.createBaseVisitorConstructorWithDefaults(this.className,J.keys(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=Z,Z}return this.baseCstVisitorWithDefaultsConstructor},Y.prototype.getLastExplicitRuleShortName=function(){var Z=this.RULE_STACK;return Z[Z.length-1]},Y.prototype.getPreviousExplicitRuleShortName=function(){var Z=this.RULE_STACK;return Z[Z.length-2]},Y.prototype.getLastExplicitRuleOccurrenceIndex=function(){var Z=this.RULE_OCCURRENCE_STACK;return Z[Z.length-1]},Y}();A.TreeBuilder=U}),gB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.LexerAdapter=void 0;var Q=d9(),J=function(){function K(){}return K.prototype.initLexerAdapter=function(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1},Object.defineProperty(K.prototype,"input",{get:function(){return this.tokVector},set:function(C){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=C,this.tokVectorLength=C.length},enumerable:!1,configurable:!0}),K.prototype.SKIP_TOKEN=function(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):Q.END_OF_FILE},K.prototype.LA=function(C){var U=this.currIdx+C;return U<0||this.tokVectorLength<=U?Q.END_OF_FILE:this.tokVector[U]},K.prototype.consumeToken=function(){this.currIdx++},K.prototype.exportLexerState=function(){return this.currIdx},K.prototype.importLexerState=function(C){this.currIdx=C},K.prototype.resetLexerState=function(){this.currIdx=-1},K.prototype.moveToTerminatedState=function(){this.currIdx=this.tokVector.length-1},K.prototype.getLexerPosition=function(){return this.exportLexerState()},K}();A.LexerAdapter=J}),bB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.RecognizerApi=void 0;var Q=G2(),J=HB(),K=d9(),C=QW(),U=dm(),Y=I9(),Z=function(){function X(){}return X.prototype.ACTION=function(E){return E.call(this)},X.prototype.consume=function(E,H,$){return this.consumeInternal(H,E,$)},X.prototype.subrule=function(E,H,$){return this.subruleInternal(H,E,$)},X.prototype.option=function(E,H){return this.optionInternal(H,E)},X.prototype.or=function(E,H){return this.orInternal(H,E)},X.prototype.many=function(E,H){return this.manyInternal(E,H)},X.prototype.atLeastOne=function(E,H){return this.atLeastOneInternal(E,H)},X.prototype.CONSUME=function(E,H){return this.consumeInternal(E,0,H)},X.prototype.CONSUME1=function(E,H){return this.consumeInternal(E,1,H)},X.prototype.CONSUME2=function(E,H){return this.consumeInternal(E,2,H)},X.prototype.CONSUME3=function(E,H){return this.consumeInternal(E,3,H)},X.prototype.CONSUME4=function(E,H){return this.consumeInternal(E,4,H)},X.prototype.CONSUME5=function(E,H){return this.consumeInternal(E,5,H)},X.prototype.CONSUME6=function(E,H){return this.consumeInternal(E,6,H)},X.prototype.CONSUME7=function(E,H){return this.consumeInternal(E,7,H)},X.prototype.CONSUME8=function(E,H){return this.consumeInternal(E,8,H)},X.prototype.CONSUME9=function(E,H){return this.consumeInternal(E,9,H)},X.prototype.SUBRULE=function(E,H){return this.subruleInternal(E,0,H)},X.prototype.SUBRULE1=function(E,H){return this.subruleInternal(E,1,H)},X.prototype.SUBRULE2=function(E,H){return this.subruleInternal(E,2,H)},X.prototype.SUBRULE3=function(E,H){return this.subruleInternal(E,3,H)},X.prototype.SUBRULE4=function(E,H){return this.subruleInternal(E,4,H)},X.prototype.SUBRULE5=function(E,H){return this.subruleInternal(E,5,H)},X.prototype.SUBRULE6=function(E,H){return this.subruleInternal(E,6,H)},X.prototype.SUBRULE7=function(E,H){return this.subruleInternal(E,7,H)},X.prototype.SUBRULE8=function(E,H){return this.subruleInternal(E,8,H)},X.prototype.SUBRULE9=function(E,H){return this.subruleInternal(E,9,H)},X.prototype.OPTION=function(E){return this.optionInternal(E,0)},X.prototype.OPTION1=function(E){return this.optionInternal(E,1)},X.prototype.OPTION2=function(E){return this.optionInternal(E,2)},X.prototype.OPTION3=function(E){return this.optionInternal(E,3)},X.prototype.OPTION4=function(E){return this.optionInternal(E,4)},X.prototype.OPTION5=function(E){return this.optionInternal(E,5)},X.prototype.OPTION6=function(E){return this.optionInternal(E,6)},X.prototype.OPTION7=function(E){return this.optionInternal(E,7)},X.prototype.OPTION8=function(E){return this.optionInternal(E,8)},X.prototype.OPTION9=function(E){return this.optionInternal(E,9)},X.prototype.OR=function(E){return this.orInternal(E,0)},X.prototype.OR1=function(E){return this.orInternal(E,1)},X.prototype.OR2=function(E){return this.orInternal(E,2)},X.prototype.OR3=function(E){return this.orInternal(E,3)},X.prototype.OR4=function(E){return this.orInternal(E,4)},X.prototype.OR5=function(E){return this.orInternal(E,5)},X.prototype.OR6=function(E){return this.orInternal(E,6)},X.prototype.OR7=function(E){return this.orInternal(E,7)},X.prototype.OR8=function(E){return this.orInternal(E,8)},X.prototype.OR9=function(E){return this.orInternal(E,9)},X.prototype.MANY=function(E){this.manyInternal(0,E)},X.prototype.MANY1=function(E){this.manyInternal(1,E)},X.prototype.MANY2=function(E){this.manyInternal(2,E)},X.prototype.MANY3=function(E){this.manyInternal(3,E)},X.prototype.MANY4=function(E){this.manyInternal(4,E)},X.prototype.MANY5=function(E){this.manyInternal(5,E)},X.prototype.MANY6=function(E){this.manyInternal(6,E)},X.prototype.MANY7=function(E){this.manyInternal(7,E)},X.prototype.MANY8=function(E){this.manyInternal(8,E)},X.prototype.MANY9=function(E){this.manyInternal(9,E)},X.prototype.MANY_SEP=function(E){this.manySepFirstInternal(0,E)},X.prototype.MANY_SEP1=function(E){this.manySepFirstInternal(1,E)},X.prototype.MANY_SEP2=function(E){this.manySepFirstInternal(2,E)},X.prototype.MANY_SEP3=function(E){this.manySepFirstInternal(3,E)},X.prototype.MANY_SEP4=function(E){this.manySepFirstInternal(4,E)},X.prototype.MANY_SEP5=function(E){this.manySepFirstInternal(5,E)},X.prototype.MANY_SEP6=function(E){this.manySepFirstInternal(6,E)},X.prototype.MANY_SEP7=function(E){this.manySepFirstInternal(7,E)},X.prototype.MANY_SEP8=function(E){this.manySepFirstInternal(8,E)},X.prototype.MANY_SEP9=function(E){this.manySepFirstInternal(9,E)},X.prototype.AT_LEAST_ONE=function(E){this.atLeastOneInternal(0,E)},X.prototype.AT_LEAST_ONE1=function(E){return this.atLeastOneInternal(1,E)},X.prototype.AT_LEAST_ONE2=function(E){this.atLeastOneInternal(2,E)},X.prototype.AT_LEAST_ONE3=function(E){this.atLeastOneInternal(3,E)},X.prototype.AT_LEAST_ONE4=function(E){this.atLeastOneInternal(4,E)},X.prototype.AT_LEAST_ONE5=function(E){this.atLeastOneInternal(5,E)},X.prototype.AT_LEAST_ONE6=function(E){this.atLeastOneInternal(6,E)},X.prototype.AT_LEAST_ONE7=function(E){this.atLeastOneInternal(7,E)},X.prototype.AT_LEAST_ONE8=function(E){this.atLeastOneInternal(8,E)},X.prototype.AT_LEAST_ONE9=function(E){this.atLeastOneInternal(9,E)},X.prototype.AT_LEAST_ONE_SEP=function(E){this.atLeastOneSepFirstInternal(0,E)},X.prototype.AT_LEAST_ONE_SEP1=function(E){this.atLeastOneSepFirstInternal(1,E)},X.prototype.AT_LEAST_ONE_SEP2=function(E){this.atLeastOneSepFirstInternal(2,E)},X.prototype.AT_LEAST_ONE_SEP3=function(E){this.atLeastOneSepFirstInternal(3,E)},X.prototype.AT_LEAST_ONE_SEP4=function(E){this.atLeastOneSepFirstInternal(4,E)},X.prototype.AT_LEAST_ONE_SEP5=function(E){this.atLeastOneSepFirstInternal(5,E)},X.prototype.AT_LEAST_ONE_SEP6=function(E){this.atLeastOneSepFirstInternal(6,E)},X.prototype.AT_LEAST_ONE_SEP7=function(E){this.atLeastOneSepFirstInternal(7,E)},X.prototype.AT_LEAST_ONE_SEP8=function(E){this.atLeastOneSepFirstInternal(8,E)},X.prototype.AT_LEAST_ONE_SEP9=function(E){this.atLeastOneSepFirstInternal(9,E)},X.prototype.RULE=function(E,H,$){if($===void 0&&($=K.DEFAULT_RULE_CONFIG),Q.contains(this.definedRulesNames,E)){var I=C.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({topLevelRule:E,grammarName:this.className}),N={message:I,type:K.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:E};this.definitionErrors.push(N)}this.definedRulesNames.push(E);var F=this.defineRule(E,H,$);return this[E]=F,F},X.prototype.OVERRIDE_RULE=function(E,H,$){$===void 0&&($=K.DEFAULT_RULE_CONFIG);var I=[];I=I.concat(U.validateRuleIsOverridden(E,this.definedRulesNames,this.className)),this.definitionErrors=this.definitionErrors.concat(I);var N=this.defineRule(E,H,$);return this[E]=N,N},X.prototype.BACKTRACK=function(E,H){return function(){this.isBackTrackingStack.push(1);var $=this.saveRecogState();try{return E.apply(this,H),!0}catch(I){if(J.isRecognitionException(I))return!1;throw I}finally{this.reloadRecogState($),this.isBackTrackingStack.pop()}}},X.prototype.getGAstProductions=function(){return this.gastProductionsCache},X.prototype.getSerializedGastProductions=function(){return Y.serializeGrammar(Q.values(this.gastProductionsCache))},X}();A.RecognizerApi=Z}),fB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.RecognizerEngine=void 0;var Q=G2(),J=QD(),K=HB(),C=KW(),U=JW(),Y=d9(),Z=lm(),X=EJ(),E=EB(),H=nm(),$=function(){function I(){}return I.prototype.initRecognizerEngine=function(N,F){if(this.className=H.classNameFromInstance(this),this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=E.tokenStructuredMatcherNoCategories,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},Q.has(F,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. - See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 - For Further details.`);if(Q.isArray(N)){if(Q.isEmpty(N))throw Error(`A Token Vocabulary cannot be empty. - Note that the first argument for the parser constructor - is no longer a Token vector (since v4.0).`);if(typeof N[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. - See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 - For Further details.`)}if(Q.isArray(N))this.tokensMap=Q.reduce(N,function(R,M){return R[M.name]=M,R},{});else if(Q.has(N,"modes")&&Q.every(Q.flatten(Q.values(N.modes)),E.isTokenType)){var V=Q.flatten(Q.values(N.modes)),D=Q.uniq(V);this.tokensMap=Q.reduce(D,function(R,M){return R[M.name]=M,R},{})}else if(Q.isObject(N))this.tokensMap=Q.cloneObj(N);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=X.EOF;var L=Q.every(Q.values(N),function(R){return Q.isEmpty(R.categoryMatches)});this.tokenMatcher=L?E.tokenStructuredMatcherNoCategories:E.tokenStructuredMatcher,E.augmentTokenTypes(Q.values(this.tokensMap))},I.prototype.defineRule=function(N,F,V){if(this.selfAnalysisDone)throw Error("Grammar rule <"+N+`> may not be defined after the 'performSelfAnalysis' method has been called' -Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);var D=Q.has(V,"resyncEnabled")?V.resyncEnabled:Y.DEFAULT_RULE_CONFIG.resyncEnabled,L=Q.has(V,"recoveryValueFunc")?V.recoveryValueFunc:Y.DEFAULT_RULE_CONFIG.recoveryValueFunc,R=this.ruleShortNameIdx<F},I.prototype.orInternal=function(N,F){var V=this.getKeyForAutomaticLookahead(J.OR_IDX,F),D=Q.isArray(N)?N:N.DEF,L=this.getLaFuncFromCache(V),R=L.call(this,D);if(R!==void 0){var M=D[R];return M.ALT.call(this)}this.raiseNoAltException(F,N.ERR_MSG)},I.prototype.ruleFinallyStateUpdate=function(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){var N=this.LA(1),F=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:N,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new K.NotAllInputParsedException(F,N))}},I.prototype.subruleInternal=function(N,F,V){var D;try{var L=V!==void 0?V.ARGS:void 0;return D=N.call(this,F,L),this.cstPostNonTerminal(D,V!==void 0&&V.LABEL!==void 0?V.LABEL:N.ruleName),D}catch(R){this.subruleInternalError(R,V,N.ruleName)}},I.prototype.subruleInternalError=function(N,F,V){throw K.isRecognitionException(N)&&N.partialCstResult!==void 0&&(this.cstPostNonTerminal(N.partialCstResult,F!==void 0&&F.LABEL!==void 0?F.LABEL:V),delete N.partialCstResult),N},I.prototype.consumeInternal=function(N,F,V){var D;try{var L=this.LA(1);this.tokenMatcher(L,N)===!0?(this.consumeToken(),D=L):this.consumeInternalError(N,L,V)}catch(R){D=this.consumeInternalRecovery(N,F,R)}return this.cstPostTerminal(V!==void 0&&V.LABEL!==void 0?V.LABEL:N.name,D),D},I.prototype.consumeInternalError=function(N,F,V){var D,L=this.LA(0);throw V!==void 0&&V.ERR_MSG?D=V.ERR_MSG:D=this.errorMessageProvider.buildMismatchTokenMessage({expected:N,actual:F,previous:L,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new K.MismatchedTokenException(D,F,L))},I.prototype.consumeInternalRecovery=function(N,F,V){if(this.recoveryEnabled&&V.name==="MismatchedTokenException"&&!this.isBackTracking()){var D=this.getFollowsForInRuleRecovery(N,F);try{return this.tryInRuleRecovery(N,D)}catch(L){throw L.name===Z.IN_RULE_RECOVERY_EXCEPTION?V:L}}else throw V},I.prototype.saveRecogState=function(){var N=this.errors,F=Q.cloneArr(this.RULE_STACK);return{errors:N,lexerState:this.exportLexerState(),RULE_STACK:F,CST_STACK:this.CST_STACK}},I.prototype.reloadRecogState=function(N){this.errors=N.errors,this.importLexerState(N.lexerState),this.RULE_STACK=N.RULE_STACK},I.prototype.ruleInvocationStateUpdate=function(N,F,V){this.RULE_OCCURRENCE_STACK.push(V),this.RULE_STACK.push(N),this.cstInvocationStateUpdate(F,N)},I.prototype.isBackTracking=function(){return this.isBackTrackingStack.length!==0},I.prototype.getCurrRuleFullName=function(){var N=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[N]},I.prototype.shortRuleNameToFullName=function(N){return this.shortRuleNameToFull[N]},I.prototype.isAtEndOfInput=function(){return this.tokenMatcher(this.LA(1),X.EOF)},I.prototype.reset=function(){this.resetLexerState(),this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]},I}();A.RecognizerEngine=$}),pB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.ErrorHandler=void 0;var Q=HB(),J=G2(),K=KW(),C=d9(),U=function(){function Y(){}return Y.prototype.initErrorHandler=function(Z){this._errors=[],this.errorMessageProvider=J.has(Z,"errorMessageProvider")?Z.errorMessageProvider:C.DEFAULT_PARSER_CONFIG.errorMessageProvider},Y.prototype.SAVE_ERROR=function(Z){if(Q.isRecognitionException(Z))return Z.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:J.cloneArr(this.RULE_OCCURRENCE_STACK)},this._errors.push(Z),Z;throw Error("Trying to save an Error which is not a RecognitionException")},Object.defineProperty(Y.prototype,"errors",{get:function(){return J.cloneArr(this._errors)},set:function(Z){this._errors=Z},enumerable:!1,configurable:!0}),Y.prototype.raiseEarlyExitException=function(Z,X,E){for(var H=this.getCurrRuleFullName(),$=this.getGAstProductions()[H],I=K.getLookaheadPathsForOptionalProd(Z,$,X,this.maxLookahead),N=I[0],F=[],V=1;V<=this.maxLookahead;V++)F.push(this.LA(V));var D=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:N,actual:F,previous:this.LA(0),customUserDescription:E,ruleName:H});throw this.SAVE_ERROR(new Q.EarlyExitException(D,this.LA(1),this.LA(0)))},Y.prototype.raiseNoAltException=function(Z,X){for(var E=this.getCurrRuleFullName(),H=this.getGAstProductions()[E],$=K.getLookaheadPathsForOr(Z,H,this.maxLookahead),I=[],N=1;N<=this.maxLookahead;N++)I.push(this.LA(N));var F=this.LA(0),V=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:$,actual:I,previous:F,customUserDescription:X,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new Q.NoViableAltException(V,this.LA(1),F))},Y}();A.ErrorHandler=U}),uB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.ContentAssist=void 0;var Q=JW(),J=G2(),K=function(){function C(){}return C.prototype.initContentAssist=function(){},C.prototype.computeContentAssist=function(U,Y){var Z=this.gastProductionsCache[U];if(J.isUndefined(Z))throw Error("Rule ->"+U+"<- does not exist in this grammar.");return Q.nextPossibleTokensAfter([Z],Y,this.tokenMatcher,this.maxLookahead)},C.prototype.getNextPossibleTokenTypes=function(U){var Y=J.first(U.ruleStack),Z=this.getGAstProductions(),X=Z[Y],E=new Q.NextAfterTokenWalker(X,U).startWalking();return E},C}();A.ContentAssist=K}),mB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.GastRecorder=void 0;var Q=G2(),J=I9(),K=eG(),C=EB(),U=EJ(),Y=d9(),Z=QD(),X={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(X);var E=!0,H=Math.pow(2,Z.BITS_FOR_OCCURRENCE_IDX)-1,$=U.createToken({name:"RECORDING_PHASE_TOKEN",pattern:K.Lexer.NA});C.augmentTokenTypes([$]);var I=U.createTokenInstance($,`This IToken indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(I);var N={name:`This CSTNode indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}},F=function(){function M(){}return M.prototype.initGastRecorder=function(T){this.recordingProdStack=[],this.RECORDING_PHASE=!1},M.prototype.enableRecording=function(){var T=this;this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",function(){for(var h=function(g){var f=g>0?g:"";T["CONSUME"+f]=function(u,d){return this.consumeInternalRecord(u,g,d)},T["SUBRULE"+f]=function(u,d){return this.subruleInternalRecord(u,g,d)},T["OPTION"+f]=function(u){return this.optionInternalRecord(u,g)},T["OR"+f]=function(u){return this.orInternalRecord(u,g)},T["MANY"+f]=function(u){this.manyInternalRecord(g,u)},T["MANY_SEP"+f]=function(u){this.manySepFirstInternalRecord(g,u)},T["AT_LEAST_ONE"+f]=function(u){this.atLeastOneInternalRecord(g,u)},T["AT_LEAST_ONE_SEP"+f]=function(u){this.atLeastOneSepFirstInternalRecord(g,u)}},y=0;y<10;y++)h(y);T.consume=function(g,f,u){return this.consumeInternalRecord(f,g,u)},T.subrule=function(g,f,u){return this.subruleInternalRecord(f,g,u)},T.option=function(g,f){return this.optionInternalRecord(f,g)},T.or=function(g,f){return this.orInternalRecord(f,g)},T.many=function(g,f){this.manyInternalRecord(g,f)},T.atLeastOne=function(g,f){this.atLeastOneInternalRecord(g,f)},T.ACTION=T.ACTION_RECORD,T.BACKTRACK=T.BACKTRACK_RECORD,T.LA=T.LA_RECORD})},M.prototype.disableRecording=function(){var T=this;this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",function(){for(var h=0;h<10;h++){var y=h>0?h:"";delete T["CONSUME"+y],delete T["SUBRULE"+y],delete T["OPTION"+y],delete T["OR"+y],delete T["MANY"+y],delete T["MANY_SEP"+y],delete T["AT_LEAST_ONE"+y],delete T["AT_LEAST_ONE_SEP"+y]}delete T.consume,delete T.subrule,delete T.option,delete T.or,delete T.many,delete T.atLeastOne,delete T.ACTION,delete T.BACKTRACK,delete T.LA})},M.prototype.ACTION_RECORD=function(T){},M.prototype.BACKTRACK_RECORD=function(T,h){return function(){return!0}},M.prototype.LA_RECORD=function(T){return Y.END_OF_FILE},M.prototype.topLevelRuleRecord=function(T,h){try{var y=new J.Rule({definition:[],name:T});return y.name=T,this.recordingProdStack.push(y),h.call(this),this.recordingProdStack.pop(),y}catch(g){if(g.KNOWN_RECORDER_ERROR!==!0)try{g.message=g.message+` - This error was thrown during the "grammar recording phase" For more info see: - https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch(f){throw g}throw g}},M.prototype.optionInternalRecord=function(T,h){return V.call(this,J.Option,T,h)},M.prototype.atLeastOneInternalRecord=function(T,h){V.call(this,J.RepetitionMandatory,h,T)},M.prototype.atLeastOneSepFirstInternalRecord=function(T,h){V.call(this,J.RepetitionMandatoryWithSeparator,h,T,E)},M.prototype.manyInternalRecord=function(T,h){V.call(this,J.Repetition,h,T)},M.prototype.manySepFirstInternalRecord=function(T,h){V.call(this,J.RepetitionWithSeparator,h,T,E)},M.prototype.orInternalRecord=function(T,h){return D.call(this,T,h)},M.prototype.subruleInternalRecord=function(T,h,y){if(R(h),!T||Q.has(T,"ruleName")===!1){var g=new Error(" argument is invalid"+(" expecting a Parser method reference but got: <"+JSON.stringify(T)+">")+(` - inside top level rule: <`+this.recordingProdStack[0].name+">"));throw g.KNOWN_RECORDER_ERROR=!0,g}var f=Q.peek(this.recordingProdStack),u=T.ruleName,d=new J.NonTerminal({idx:h,nonTerminalName:u,referencedRule:void 0});return f.definition.push(d),this.outputCst?N:X},M.prototype.consumeInternalRecord=function(T,h,y){if(R(h),!C.hasShortKeyProperty(T)){var g=new Error(" argument is invalid"+(" expecting a TokenType reference but got: <"+JSON.stringify(T)+">")+(` - inside top level rule: <`+this.recordingProdStack[0].name+">"));throw g.KNOWN_RECORDER_ERROR=!0,g}var f=Q.peek(this.recordingProdStack),u=new J.Terminal({idx:h,terminalType:T});return f.definition.push(u),I},M}();A.GastRecorder=F;function V(M,T,h,y){y===void 0&&(y=!1),R(h);var g=Q.peek(this.recordingProdStack),f=Q.isFunction(T)?T:T.DEF,u=new M({definition:[],idx:h});return y&&(u.separator=T.SEP),Q.has(T,"MAX_LOOKAHEAD")&&(u.maxLookahead=T.MAX_LOOKAHEAD),this.recordingProdStack.push(u),f.call(this),g.definition.push(u),this.recordingProdStack.pop(),X}function D(M,T){var h=this;R(T);var y=Q.peek(this.recordingProdStack),g=Q.isArray(M)===!1,f=g===!1?M:M.DEF,u=new J.Alternation({definition:[],idx:T,ignoreAmbiguities:g&&M.IGNORE_AMBIGUITIES===!0});Q.has(M,"MAX_LOOKAHEAD")&&(u.maxLookahead=M.MAX_LOOKAHEAD);var d=Q.some(f,function(n){return Q.isFunction(n.GATE)});return u.hasPredicates=d,y.definition.push(u),Q.forEach(f,function(n){var B=new J.Alternative({definition:[]});u.definition.push(B),Q.has(n,"IGNORE_AMBIGUITIES")?B.ignoreAmbiguities=n.IGNORE_AMBIGUITIES:Q.has(n,"GATE")&&(B.ignoreAmbiguities=!0),h.recordingProdStack.push(B),n.ALT.call(h),h.recordingProdStack.pop()}),X}function L(M){return M===0?"":""+M}function R(M){if(M<0||M>H){var T=new Error("Invalid DSL Method idx value: <"+M+`> - `+("Idx value must be a none negative value smaller than "+(H+1)));throw T.KNOWN_RECORDER_ERROR=!0,T}}}),cB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.PerformanceTracer=void 0;var Q=G2(),J=d9(),K=function(){function C(){}return C.prototype.initPerformanceTracer=function(U){if(Q.has(U,"traceInitPerf")){var Y=U.traceInitPerf,Z=typeof Y=="number";this.traceInitMaxIdent=Z?Y:1/0,this.traceInitPerf=Z?Y>0:Y}else this.traceInitMaxIdent=0,this.traceInitPerf=J.DEFAULT_PARSER_CONFIG.traceInitPerf;this.traceInitIndent=-1},C.prototype.TRACE_INIT=function(U,Y){if(this.traceInitPerf===!0){this.traceInitIndent++;var Z=new Array(this.traceInitIndent+1).join("\t");this.traceInitIndent <"+U+">");var X=Q.timer(Y),E=X.time,H=X.value,$=E>10?console.warn:console.log;return this.traceInitIndent time: "+E+"ms"),this.traceInitIndent--,H}else return Y()},C}();A.PerformanceTracer=K}),dB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.applyMixins=void 0;function Q(J,K){K.forEach(function(C){var U=C.prototype;Object.getOwnPropertyNames(U).forEach(function(Y){if(Y!=="constructor"){var Z=Object.getOwnPropertyDescriptor(U,Y);Z&&(Z.get||Z.set)?Object.defineProperty(J.prototype,Y,Z):J.prototype[Y]=C.prototype[Y]}})})}A.applyMixins=Q}),d9=vA((A)=>{var Q=A&&A.__extends||function(){var g=function(f,u){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,n){d.__proto__=n}||function(d,n){for(var B in n)Object.prototype.hasOwnProperty.call(n,B)&&(d[B]=n[B])},g(f,u)};return function(f,u){if(typeof u!="function"&&u!==null)throw new TypeError("Class extends value "+String(u)+" is not a constructor or null");g(f,u);function d(){this.constructor=f}f.prototype=u===null?Object.create(u):(d.prototype=u.prototype,new d)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.EmbeddedActionsParser=A.CstParser=A.Parser=A.EMPTY_ALT=A.ParserDefinitionErrorType=A.DEFAULT_RULE_CONFIG=A.DEFAULT_PARSER_CONFIG=A.END_OF_FILE=void 0;var J=G2(),K=kB1(),C=EJ(),U=QW(),Y=jB1(),Z=lm(),X=vB1(),E=hB1(),H=gB1(),$=bB1(),I=fB1(),N=pB1(),F=uB1(),V=mB1(),D=cB1(),L=dB1();A.END_OF_FILE=C.createTokenInstance(C.EOF,"",NaN,NaN,NaN,NaN,NaN,NaN),Object.freeze(A.END_OF_FILE),A.DEFAULT_PARSER_CONFIG=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:U.defaultParserErrorProvider,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),A.DEFAULT_RULE_CONFIG=Object.freeze({recoveryValueFunc:function(){},resyncEnabled:!0});var R;(function(g){g[g.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",g[g.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",g[g.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",g[g.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",g[g.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",g[g.LEFT_RECURSION=5]="LEFT_RECURSION",g[g.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",g[g.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",g[g.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",g[g.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",g[g.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",g[g.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",g[g.TOO_MANY_ALTS=12]="TOO_MANY_ALTS"})(R=A.ParserDefinitionErrorType||(A.ParserDefinitionErrorType={}));function M(g){return g===void 0&&(g=void 0),function(){return g}}A.EMPTY_ALT=M;var T=function(){function g(f,u){this.definitionErrors=[],this.selfAnalysisDone=!1;var d=this;if(d.initErrorHandler(u),d.initLexerAdapter(),d.initLooksAhead(u),d.initRecognizerEngine(f,u),d.initRecoverable(u),d.initTreeBuilder(u),d.initContentAssist(),d.initGastRecorder(u),d.initPerformanceTracer(u),J.has(u,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. - Please use the flag on the relevant DSL method instead. - See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES - For further details.`);this.skipValidations=J.has(u,"skipValidations")?u.skipValidations:A.DEFAULT_PARSER_CONFIG.skipValidations}return g.performSelfAnalysis=function(f){throw Error("The **static** `performSelfAnalysis` method has been deprecated.\t\nUse the **instance** method with the same name instead.")},g.prototype.performSelfAnalysis=function(){var f=this;this.TRACE_INIT("performSelfAnalysis",function(){var u;f.selfAnalysisDone=!0;var d=f.className;f.TRACE_INIT("toFastProps",function(){J.toFastProperties(f)}),f.TRACE_INIT("Grammar Recording",function(){try{f.enableRecording(),J.forEach(f.definedRulesNames,function(B){var q=f[B],P=q.originalGrammarAction,O=void 0;f.TRACE_INIT(B+" Rule",function(){O=f.topLevelRuleRecord(B,P)}),f.gastProductionsCache[B]=O})}finally{f.disableRecording()}});var n=[];if(f.TRACE_INIT("Grammar Resolving",function(){n=Y.resolveGrammar({rules:J.values(f.gastProductionsCache)}),f.definitionErrors=f.definitionErrors.concat(n)}),f.TRACE_INIT("Grammar Validations",function(){if(J.isEmpty(n)&&f.skipValidations===!1){var B=Y.validateGrammar({rules:J.values(f.gastProductionsCache),maxLookahead:f.maxLookahead,tokenTypes:J.values(f.tokensMap),errMsgProvider:U.defaultGrammarValidatorErrorProvider,grammarName:d});f.definitionErrors=f.definitionErrors.concat(B)}}),J.isEmpty(f.definitionErrors)&&(f.recoveryEnabled&&f.TRACE_INIT("computeAllProdsFollows",function(){var B=K.computeAllProdsFollows(J.values(f.gastProductionsCache));f.resyncFollows=B}),f.TRACE_INIT("ComputeLookaheadFunctions",function(){f.preComputeLookaheadFunctions(J.values(f.gastProductionsCache))})),!g.DEFER_DEFINITION_ERRORS_HANDLING&&!J.isEmpty(f.definitionErrors))throw u=J.map(f.definitionErrors,function(B){return B.message}),new Error(`Parser Definition Errors detected: - `+u.join(` -------------------------------- -`))})},g.DEFER_DEFINITION_ERRORS_HANDLING=!1,g}();A.Parser=T,L.applyMixins(T,[Z.Recoverable,X.LooksAhead,E.TreeBuilder,H.LexerAdapter,I.RecognizerEngine,$.RecognizerApi,N.ErrorHandler,F.ContentAssist,V.GastRecorder,D.PerformanceTracer]);var h=function(g){Q(f,g);function f(u,d){d===void 0&&(d=A.DEFAULT_PARSER_CONFIG);var n=this,B=J.cloneObj(d);return B.outputCst=!0,n=g.call(this,u,B)||this,n}return f}(T);A.CstParser=h;var y=function(g){Q(f,g);function f(u,d){d===void 0&&(d=A.DEFAULT_PARSER_CONFIG);var n=this,B=J.cloneObj(d);return B.outputCst=!1,n=g.call(this,u,B)||this,n}return f}(T);A.EmbeddedActionsParser=y}),lB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.createSyntaxDiagramsCode=void 0;var Q=fm();function J(K,C){var U=C===void 0?{}:C,Y=U.resourceBase,Z=Y===void 0?"https://unpkg.com/chevrotain@"+Q.VERSION+"/diagrams/":Y,X=U.css,E=X===void 0?"https://unpkg.com/chevrotain@"+Q.VERSION+"/diagrams/diagrams.css":X,H=` - - - - - -`,$=` - -`,I=` - - - - -`,N=` -

-`,F=` - -`,V=` - -`;return H+$+I+N+F+V}A.createSyntaxDiagramsCode=J}),nB1=vA((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.Parser=A.createSyntaxDiagramsCode=A.clearCache=A.GAstVisitor=A.serializeProduction=A.serializeGrammar=A.Terminal=A.Rule=A.RepetitionWithSeparator=A.RepetitionMandatoryWithSeparator=A.RepetitionMandatory=A.Repetition=A.Option=A.NonTerminal=A.Alternative=A.Alternation=A.defaultLexerErrorProvider=A.NoViableAltException=A.NotAllInputParsedException=A.MismatchedTokenException=A.isRecognitionException=A.EarlyExitException=A.defaultParserErrorProvider=A.tokenName=A.tokenMatcher=A.tokenLabel=A.EOF=A.createTokenInstance=A.createToken=A.LexerDefinitionErrorType=A.Lexer=A.EMPTY_ALT=A.ParserDefinitionErrorType=A.EmbeddedActionsParser=A.CstParser=A.VERSION=void 0;var Q=fm();Object.defineProperty(A,"VERSION",{enumerable:!0,get:function(){return Q.VERSION}});var J=d9();Object.defineProperty(A,"CstParser",{enumerable:!0,get:function(){return J.CstParser}}),Object.defineProperty(A,"EmbeddedActionsParser",{enumerable:!0,get:function(){return J.EmbeddedActionsParser}}),Object.defineProperty(A,"ParserDefinitionErrorType",{enumerable:!0,get:function(){return J.ParserDefinitionErrorType}}),Object.defineProperty(A,"EMPTY_ALT",{enumerable:!0,get:function(){return J.EMPTY_ALT}});var K=eG();Object.defineProperty(A,"Lexer",{enumerable:!0,get:function(){return K.Lexer}}),Object.defineProperty(A,"LexerDefinitionErrorType",{enumerable:!0,get:function(){return K.LexerDefinitionErrorType}});var C=EJ();Object.defineProperty(A,"createToken",{enumerable:!0,get:function(){return C.createToken}}),Object.defineProperty(A,"createTokenInstance",{enumerable:!0,get:function(){return C.createTokenInstance}}),Object.defineProperty(A,"EOF",{enumerable:!0,get:function(){return C.EOF}}),Object.defineProperty(A,"tokenLabel",{enumerable:!0,get:function(){return C.tokenLabel}}),Object.defineProperty(A,"tokenMatcher",{enumerable:!0,get:function(){return C.tokenMatcher}}),Object.defineProperty(A,"tokenName",{enumerable:!0,get:function(){return C.tokenName}});var U=QW();Object.defineProperty(A,"defaultParserErrorProvider",{enumerable:!0,get:function(){return U.defaultParserErrorProvider}});var Y=HB();Object.defineProperty(A,"EarlyExitException",{enumerable:!0,get:function(){return Y.EarlyExitException}}),Object.defineProperty(A,"isRecognitionException",{enumerable:!0,get:function(){return Y.isRecognitionException}}),Object.defineProperty(A,"MismatchedTokenException",{enumerable:!0,get:function(){return Y.MismatchedTokenException}}),Object.defineProperty(A,"NotAllInputParsedException",{enumerable:!0,get:function(){return Y.NotAllInputParsedException}}),Object.defineProperty(A,"NoViableAltException",{enumerable:!0,get:function(){return Y.NoViableAltException}});var Z=um();Object.defineProperty(A,"defaultLexerErrorProvider",{enumerable:!0,get:function(){return Z.defaultLexerErrorProvider}});var X=I9();Object.defineProperty(A,"Alternation",{enumerable:!0,get:function(){return X.Alternation}}),Object.defineProperty(A,"Alternative",{enumerable:!0,get:function(){return X.Alternative}}),Object.defineProperty(A,"NonTerminal",{enumerable:!0,get:function(){return X.NonTerminal}}),Object.defineProperty(A,"Option",{enumerable:!0,get:function(){return X.Option}}),Object.defineProperty(A,"Repetition",{enumerable:!0,get:function(){return X.Repetition}}),Object.defineProperty(A,"RepetitionMandatory",{enumerable:!0,get:function(){return X.RepetitionMandatory}}),Object.defineProperty(A,"RepetitionMandatoryWithSeparator",{enumerable:!0,get:function(){return X.RepetitionMandatoryWithSeparator}}),Object.defineProperty(A,"RepetitionWithSeparator",{enumerable:!0,get:function(){return X.RepetitionWithSeparator}}),Object.defineProperty(A,"Rule",{enumerable:!0,get:function(){return X.Rule}}),Object.defineProperty(A,"Terminal",{enumerable:!0,get:function(){return X.Terminal}});var E=I9();Object.defineProperty(A,"serializeGrammar",{enumerable:!0,get:function(){return E.serializeGrammar}}),Object.defineProperty(A,"serializeProduction",{enumerable:!0,get:function(){return E.serializeProduction}});var H=$B();Object.defineProperty(A,"GAstVisitor",{enumerable:!0,get:function(){return H.GAstVisitor}});function $(){console.warn(`The clearCache function was 'soft' removed from the Chevrotain API. - It performs no action other than printing this message. - Please avoid using it as it will be completely removed in the future`)}A.clearCache=$;var I=lB1();Object.defineProperty(A,"createSyntaxDiagramsCode",{enumerable:!0,get:function(){return I.createSyntaxDiagramsCode}});var N=function(){function F(){throw new Error(`The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead. -See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_7-0-0`)}return F}();A.Parser=N}),sm=nB1();var HS1=sm.CstParser;var LS1={name:"GouraudShader",uniforms:u0.merge([M0.common,M0.specularmap,M0.envmap,M0.aomap,M0.lightmap,M0.emissivemap,M0.fog,M0.lights,{emissive:{value:new y1(0)}}]),vertexShader:` - - #define GOURAUD - - varying vec3 vLightFront; - varying vec3 vIndirectFront; - - #ifdef DOUBLE_SIDED - varying vec3 vLightBack; - varying vec3 vIndirectBack; - #endif - - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - - void main() { - - #include - #include - #include - - #include - #include - #include - #include - #include - - #include - #include - #include - #include - #include - #include - - #include - #include - - // inlining legacy - - vec3 diffuse = vec3( 1.0 ); - - vec3 geometryPosition = mvPosition.xyz; - vec3 geometryNormal = normalize( transformedNormal ); - vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz ); - - vec3 backGeometryNormal = - geometryNormal; - - vLightFront = vec3( 0.0 ); - vIndirectFront = vec3( 0.0 ); - #ifdef DOUBLE_SIDED - vLightBack = vec3( 0.0 ); - vIndirectBack = vec3( 0.0 ); - #endif - - IncidentLight directLight; - float dotNL; - vec3 directLightColor_Diffuse; - - vIndirectFront += getAmbientLightIrradiance( ambientLightColor ); - - #if defined( USE_LIGHT_PROBES ) - - vIndirectFront += getLightProbeIrradiance( lightProbe, geometryNormal ); - - #endif - - #ifdef DOUBLE_SIDED - - vIndirectBack += getAmbientLightIrradiance( ambientLightColor ); - - #if defined( USE_LIGHT_PROBES ) - - vIndirectBack += getLightProbeIrradiance( lightProbe, backGeometryNormal ); - - #endif - - #endif - - #if NUM_POINT_LIGHTS > 0 - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - - getPointLightInfo( pointLights[ i ], geometryPosition, directLight ); - - dotNL = dot( geometryNormal, directLight.direction ); - directLightColor_Diffuse = directLight.color; - - vLightFront += saturate( dotNL ) * directLightColor_Diffuse; - - #ifdef DOUBLE_SIDED - - vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; - - #endif - - } - #pragma unroll_loop_end - - #endif - - #if NUM_SPOT_LIGHTS > 0 - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - - getSpotLightInfo( spotLights[ i ], geometryPosition, directLight ); - - dotNL = dot( geometryNormal, directLight.direction ); - directLightColor_Diffuse = directLight.color; - - vLightFront += saturate( dotNL ) * directLightColor_Diffuse; - - #ifdef DOUBLE_SIDED - - vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; - - #endif - } - #pragma unroll_loop_end - - #endif - - #if NUM_DIR_LIGHTS > 0 - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - getDirectionalLightInfo( directionalLights[ i ], directLight ); - - dotNL = dot( geometryNormal, directLight.direction ); - directLightColor_Diffuse = directLight.color; - - vLightFront += saturate( dotNL ) * directLightColor_Diffuse; - - #ifdef DOUBLE_SIDED - - vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; - - #endif - - } - #pragma unroll_loop_end - - #endif - - #if NUM_HEMI_LIGHTS > 0 - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - - vIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); - - #ifdef DOUBLE_SIDED - - vIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometryNormal ); - - #endif - - } - #pragma unroll_loop_end - - #endif - - #include - #include - - }`,fragmentShader:` - - #define GOURAUD - - uniform vec3 diffuse; - uniform vec3 emissive; - uniform float opacity; - - varying vec3 vLightFront; - varying vec3 vIndirectFront; - - #ifdef DOUBLE_SIDED - varying vec3 vLightBack; - varying vec3 vIndirectBack; - #endif - - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - - void main() { - - #include - - vec4 diffuseColor = vec4( diffuse, opacity ); - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - - #include - #include - #include - #include - #include - #include - #include - - // accumulation - - #ifdef DOUBLE_SIDED - - reflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack; - - #else - - reflectedLight.indirectDiffuse += vIndirectFront; - - #endif - - #ifdef USE_LIGHTMAP - - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; - reflectedLight.indirectDiffuse += lightMapIrradiance; - - #endif - - reflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb ); - - #ifdef DOUBLE_SIDED - - reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack; - - #else - - reflectedLight.directDiffuse = vLightFront; - - #endif - - reflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask(); - - // modulation - - #include - - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - - #include - - #include - #include - #include - #include - #include - #include - - }`};class CW{constructor(A=new I1(0,0,0),Q=new I1(0,1,0),J=1){this.start=A,this.end=Q,this.radius=J}clone(){return new CW(this.start.clone(),this.end.clone(),this.radius)}set(A,Q,J){this.start.copy(A),this.end.copy(Q),this.radius=J}copy(A){this.start.copy(A.start),this.end.copy(A.end),this.radius=A.radius}getCenter(A){return A.copy(this.end).add(this.start).multiplyScalar(0.5)}translate(A){this.start.add(A),this.end.add(A)}checkAABBAxis(A,Q,J,K,C,U,Y,Z,X){return(C-AJ+K)return!1;for(let C=0;C<3;C++)if(J=Q2.e[0]*wA[0][C]+Q2.e[1]*wA[1][C]+Q2.e[2]*wA[2][C],K=W2.e[C],Math.abs(u2[0]*a2[0][C]+u2[1]*a2[1][C]+u2[2]*a2[2][C])>J+K)return!1;if(J=Q2.e[1]*wA[2][0]+Q2.e[2]*wA[1][0],K=W2.e[1]*wA[0][2]+W2.e[2]*wA[0][1],Math.abs(u2[2]*a2[1][0]-u2[1]*a2[2][0])>J+K)return!1;if(J=Q2.e[1]*wA[2][1]+Q2.e[2]*wA[1][1],K=W2.e[0]*wA[0][2]+W2.e[2]*wA[0][0],Math.abs(u2[2]*a2[1][1]-u2[1]*a2[2][1])>J+K)return!1;if(J=Q2.e[1]*wA[2][2]+Q2.e[2]*wA[1][2],K=W2.e[0]*wA[0][1]+W2.e[1]*wA[0][0],Math.abs(u2[2]*a2[1][2]-u2[1]*a2[2][2])>J+K)return!1;if(J=Q2.e[0]*wA[2][0]+Q2.e[2]*wA[0][0],K=W2.e[1]*wA[1][2]+W2.e[2]*wA[1][1],Math.abs(u2[0]*a2[2][0]-u2[2]*a2[0][0])>J+K)return!1;if(J=Q2.e[0]*wA[2][1]+Q2.e[2]*wA[0][1],K=W2.e[0]*wA[1][2]+W2.e[2]*wA[1][0],Math.abs(u2[0]*a2[2][1]-u2[2]*a2[0][1])>J+K)return!1;if(J=Q2.e[0]*wA[2][2]+Q2.e[2]*wA[0][2],K=W2.e[0]*wA[1][1]+W2.e[1]*wA[1][0],Math.abs(u2[0]*a2[2][2]-u2[2]*a2[0][2])>J+K)return!1;if(J=Q2.e[0]*wA[1][0]+Q2.e[1]*wA[0][0],K=W2.e[1]*wA[2][2]+W2.e[2]*wA[2][1],Math.abs(u2[1]*a2[0][0]-u2[0]*a2[1][0])>J+K)return!1;if(J=Q2.e[0]*wA[1][1]+Q2.e[1]*wA[0][1],K=W2.e[0]*wA[2][2]+W2.e[2]*wA[2][0],Math.abs(u2[1]*a2[0][1]-u2[0]*a2[1][1])>J+K)return!1;if(J=Q2.e[0]*wA[1][2]+Q2.e[1]*wA[0][2],K=W2.e[0]*wA[2][1]+W2.e[1]*wA[2][0],Math.abs(u2[1]*a2[0][2]-u2[0]*a2[1][2])>J+K)return!1;return!0}intersectsPlane(A){this.rotation.extractBasis($J,HJ,GJ);let Q=this.halfSize.x*Math.abs(A.normal.dot($J))+this.halfSize.y*Math.abs(A.normal.dot(HJ))+this.halfSize.z*Math.abs(A.normal.dot(GJ)),J=A.normal.dot(this.center)-A.constant;return Math.abs(J)<=Q}intersectRay(A,Q){if(this.getSize(im),rm.setFromCenterAndSize(w8.set(0,0,0),im),YW.setFromMatrix3(this.rotation),YW.setPosition(this.center),tm.copy(YW).invert(),em.copy(A).applyMatrix4(tm),em.intersectBox(rm,Q))return Q.applyMatrix4(YW);else return null}intersectsRay(A){return this.intersectRay(A,w8)!==null}fromBox3(A){return A.getCenter(this.center),A.getSize(this.halfSize).multiplyScalar(0.5),this.rotation.identity(),this}equals(A){return A.center.equals(this.center)&&A.halfSize.equals(this.halfSize)&&A.rotation.equals(this.rotation)}applyMatrix4(A){let Q=A.elements,J=w8.set(Q[0],Q[1],Q[2]).length(),K=w8.set(Q[4],Q[5],Q[6]).length(),C=w8.set(Q[8],Q[9],Q[10]).length();if(A.determinant()<0)J=-J;k5.setFromMatrix4(A);let Y=1/J,Z=1/K,X=1/C;return k5.elements[0]*=Y,k5.elements[1]*=Y,k5.elements[2]*=Y,k5.elements[3]*=Z,k5.elements[4]*=Z,k5.elements[5]*=Z,k5.elements[6]*=X,k5.elements[7]*=X,k5.elements[8]*=X,this.rotation.multiply(k5),this.halfSize.x*=J,this.halfSize.y*=K,this.halfSize.z*=C,w8.setFromMatrixPosition(A),this.center.add(w8),this}}var sB1=new Ac;var cS1=new I1,dS1=new I1,lS1=new I1,nS1=new I1,sS1=new V2,oS1=new R5,iS1=new R5,aS1=new O2,rS1=new CW,tS1=new I1,eS1=new I1,Aj1=new I1;class GB{constructor(A=Math){this.grad3=[[1,1,0],[-1,1,0],[1,-1,0],[-1,-1,0],[1,0,1],[-1,0,1],[1,0,-1],[-1,0,-1],[0,1,1],[0,-1,1],[0,1,-1],[0,-1,-1]],this.grad4=[[0,1,1,1],[0,1,1,-1],[0,1,-1,1],[0,1,-1,-1],[0,-1,1,1],[0,-1,1,-1],[0,-1,-1,1],[0,-1,-1,-1],[1,0,1,1],[1,0,1,-1],[1,0,-1,1],[1,0,-1,-1],[-1,0,1,1],[-1,0,1,-1],[-1,0,-1,1],[-1,0,-1,-1],[1,1,0,1],[1,1,0,-1],[1,-1,0,1],[1,-1,0,-1],[-1,1,0,1],[-1,1,0,-1],[-1,-1,0,1],[-1,-1,0,-1],[1,1,1,0],[1,1,-1,0],[1,-1,1,0],[1,-1,-1,0],[-1,1,1,0],[-1,1,-1,0],[-1,-1,1,0],[-1,-1,-1,0]],this.p=[];for(let Q=0;Q<256;Q++)this.p[Q]=Math.floor(A.random()*256);this.perm=[];for(let Q=0;Q<512;Q++)this.perm[Q]=this.p[Q&255];this.simplex=[[0,1,2,3],[0,1,3,2],[0,0,0,0],[0,2,3,1],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,2,3,0],[0,2,1,3],[0,0,0,0],[0,3,1,2],[0,3,2,1],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,3,2,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,2,0,3],[0,0,0,0],[1,3,0,2],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,3,0,1],[2,3,1,0],[1,0,2,3],[1,0,3,2],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,0,3,1],[0,0,0,0],[2,1,3,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,0,1,3],[0,0,0,0],[0,0,0,0],[0,0,0,0],[3,0,1,2],[3,0,2,1],[0,0,0,0],[3,1,2,0],[2,1,0,3],[0,0,0,0],[0,0,0,0],[0,0,0,0],[3,1,0,2],[0,0,0,0],[3,2,0,1],[3,2,1,0]]}dot(A,Q,J){return A[0]*Q+A[1]*J}dot3(A,Q,J,K){return A[0]*Q+A[1]*J+A[2]*K}dot4(A,Q,J,K,C){return A[0]*Q+A[1]*J+A[2]*K+A[3]*C}noise(A,Q){let J,K,C,U=0.5*(Math.sqrt(3)-1),Y=(A+Q)*U,Z=Math.floor(A+Y),X=Math.floor(Q+Y),E=(3-Math.sqrt(3))/6,H=(Z+X)*E,$=Z-H,I=X-H,N=A-$,F=Q-I,V,D;if(N>F)V=1,D=0;else V=0,D=1;let L=N-V+E,R=F-D+E,M=N-1+2*E,T=F-1+2*E,h=Z&255,y=X&255,g=this.perm[h+this.perm[y]]%12,f=this.perm[h+V+this.perm[y+D]]%12,u=this.perm[h+1+this.perm[y+1]]%12,d=0.5-N*N-F*F;if(d<0)J=0;else d*=d,J=d*d*this.dot(this.grad3[g],N,F);let n=0.5-L*L-R*R;if(n<0)K=0;else n*=n,K=n*n*this.dot(this.grad3[f],L,R);let B=0.5-M*M-T*T;if(B<0)C=0;else B*=B,C=B*B*this.dot(this.grad3[u],M,T);return 70*(J+K+C)}noise3d(A,Q,J){let K,C,U,Y,Z=0.3333333333333333,X=(A+Q+J)*0.3333333333333333,E=Math.floor(A+X),H=Math.floor(Q+X),$=Math.floor(J+X),I=0.16666666666666666,N=(E+H+$)*0.16666666666666666,F=E-N,V=H-N,D=$-N,L=A-F,R=Q-V,M=J-D,T,h,y,g,f,u;if(L>=R)if(R>=M)T=1,h=0,y=0,g=1,f=1,u=0;else if(L>=M)T=1,h=0,y=0,g=1,f=0,u=1;else T=0,h=0,y=1,g=1,f=0,u=1;else if(Ru?32:0,q=f>d?16:0,P=u>d?8:0,O=f>n?4:0,w=u>n?2:0,k=d>n?1:0,S=B+q+P+O+w+k,_=U[S][0]>=3?1:0,W=U[S][1]>=3?1:0,j=U[S][2]>=3?1:0,b=U[S][3]>=3?1:0,p=U[S][0]>=2?1:0,s=U[S][1]>=2?1:0,r=U[S][2]>=2?1:0,A1=U[S][3]>=2?1:0,Q1=U[S][0]>=1?1:0,e=U[S][1]>=1?1:0,t=U[S][2]>=1?1:0,U1=U[S][3]>=1?1:0,O1=f-_+X,E1=u-W+X,Y1=d-j+X,i=n-b+X,c=f-p+2*X,o=u-s+2*X,C1=d-r+2*X,q1=n-A1+2*X,Z1=f-Q1+3*X,j1=u-e+3*X,H1=d-t+3*X,B1=n-U1+3*X,k1=f-1+4*X,D1=u-1+4*X,G1=d-1+4*X,w1=n-1+4*X,G=V&255,z=D&255,x=L&255,m=R&255,l=Y[G+Y[z+Y[x+Y[m]]]]%32,a=Y[G+_+Y[z+W+Y[x+j+Y[m+b]]]]%32,K1=Y[G+p+Y[z+s+Y[x+r+Y[m+A1]]]]%32,F1=Y[G+Q1+Y[z+e+Y[x+t+Y[m+U1]]]]%32,R1=Y[G+1+Y[z+1+Y[x+1+Y[m+1]]]]%32,X1=0.6-f*f-u*u-d*d-n*n;if(X1<0)E=0;else X1*=X1,E=X1*X1*this.dot4(C[l],f,u,d,n);let W1=0.6-O1*O1-E1*E1-Y1*Y1-i*i;if(W1<0)H=0;else W1*=W1,H=W1*W1*this.dot4(C[a],O1,E1,Y1,i);let $1=0.6-c*c-o*o-C1*C1-q1*q1;if($1<0)$=0;else $1*=$1,$=$1*$1*this.dot4(C[K1],c,o,C1,q1);let N1=0.6-Z1*Z1-j1*j1-H1*H1-B1*B1;if(N1<0)I=0;else N1*=N1,I=N1*N1*this.dot4(C[F1],Z1,j1,H1,B1);let _1=0.6-k1*k1-D1*D1-G1*G1-w1*w1;if(_1<0)N=0;else _1*=_1,N=_1*_1*this.dot4(C[R1],k1,D1,G1,w1);return 27*(E+H+$+I+N)}}var Uj1=new I1;var Hj1=new I1,Gj1=new t0,Wj1=new I1,Ij1=new I1,qj1=new t0,Oj1=new I1;var mj1=new Y0;var lj1=new I1,nj1=new I1,sj1=new I1;var aj1=new I1,rj1=new I1;class UW extends _0{constructor(){super(UW.Geometry,new BA({opacity:0,transparent:!0}));this.isLensflare=!0,this.type="Lensflare",this.frustumCulled=!1,this.renderOrder=1/0;let A=new I1,Q=new I1,J=new EC(16,16),K=new EC(16,16),C=dA,U=UW.Geometry,Y=new A7({uniforms:{scale:{value:null},screenPosition:{value:null}},vertexShader:` - - precision highp float; - - uniform vec3 screenPosition; - uniform vec2 scale; - - attribute vec3 position; - - void main() { - - gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); - - }`,fragmentShader:` - - precision highp float; - - void main() { - - gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 ); - - }`,depthTest:!0,depthWrite:!1,transparent:!1}),Z=new A7({uniforms:{map:{value:J},scale:{value:null},screenPosition:{value:null}},vertexShader:` - - precision highp float; - - uniform vec3 screenPosition; - uniform vec2 scale; - - attribute vec3 position; - attribute vec2 uv; - - varying vec2 vUV; - - void main() { - - vUV = uv; - - gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); - - }`,fragmentShader:` - - precision highp float; - - uniform sampler2D map; - - varying vec2 vUV; - - void main() { - - gl_FragColor = texture2D( map, vUV ); - - }`,depthTest:!1,depthWrite:!1,transparent:!1}),X=new _0(U,Y),E=[],H=JD.Shader,$=new A7({name:H.name,uniforms:{map:{value:null},occlusionMap:{value:K},color:{value:new y1(16777215)},scale:{value:new p1},screenPosition:{value:new I1}},vertexShader:H.vertexShader,fragmentShader:H.fragmentShader,blending:U6,transparent:!0,depthWrite:!1}),I=new _0(U,$);this.addElement=function(L){E.push(L)};let N=new p1,F=new p1,V=new oQ,D=new X0;this.onBeforeRender=function(L,R,M){L.getCurrentViewport(D);let T=L.getRenderTarget(),h=T!==null?T.texture.type:dA;if(C!==h)J.dispose(),K.dispose(),J.type=K.type=h,C=h;let y=D.w/D.z,g=D.z/2,f=D.w/2,u=16/D.w;if(N.set(u*y,u),V.min.set(D.x,D.y),V.max.set(D.x+(D.z-16),D.y+(D.w-16)),Q.setFromMatrixPosition(this.matrixWorld),Q.applyMatrix4(M.matrixWorldInverse),Q.z>0)return;if(A.copy(Q).applyMatrix4(M.projectionMatrix),F.x=D.x+A.x*g+g-8,F.y=D.y+A.y*f+f-8,V.containsPoint(F)){L.copyFramebufferToTexture(J,F);let d=Y.uniforms;d.scale.value=N,d.screenPosition.value=A,L.renderBufferDirect(M,null,U,Y,X,null),L.copyFramebufferToTexture(K,F),d=Z.uniforms,d.scale.value=N,d.screenPosition.value=A,L.renderBufferDirect(M,null,U,Z,X,null);let n=-A.x*2,B=-A.y*2;for(let q=0,P=E.length;q0)return;D.reflect(H).negate(),D.add($),N.extractRotation(u.matrixWorld),F.set(0,0,-1),F.applyMatrix4(N),F.add(I),L.subVectors($,F),L.reflect(H).negate(),L.add($),T.position.copy(D),T.up.set(0,1,0),T.up.applyMatrix4(N),T.up.reflect(H),T.lookAt(L),T.far=u.far,T.updateMatrixWorld(),T.projectionMatrix.copy(u.projectionMatrix),M.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1),M.multiply(T.projectionMatrix),M.multiply(T.matrixWorldInverse),M.multiply(J.matrixWorld),E.setFromNormalAndCoplanarPoint(H,$),E.applyMatrix4(T.matrixWorldInverse),V.set(E.normal.x,E.normal.y,E.normal.z,E.constant);let d=T.projectionMatrix;R.x=(Math.sign(V.x)+d.elements[8])/d.elements[0],R.y=(Math.sign(V.y)+d.elements[9])/d.elements[5],R.z=-1,R.w=(1+d.elements[10])/d.elements[14],V.multiplyScalar(2/V.dot(R)),d.elements[2]=V.x,d.elements[6]=V.y,d.elements[10]=V.z+1-Y,d.elements[14]=V.w,J.visible=!1;let n=g.getRenderTarget(),B=g.xr.enabled,q=g.shadowMap.autoUpdate;if(g.xr.enabled=!1,g.shadowMap.autoUpdate=!1,g.setRenderTarget(h),g.state.buffers.depth.setMask(!0),g.autoClear===!1)g.clear();g.render(f,T),g.xr.enabled=B,g.shadowMap.autoUpdate=q,g.setRenderTarget(n);let P=u.viewport;if(P!==void 0)g.state.viewport(P);J.visible=!0},this.getRenderTarget=function(){return h},this.dispose=function(){h.dispose(),J.material.dispose()}}}aC.ReflectorShader={name:"ReflectorShader",uniforms:{color:{value:null},tDiffuse:{value:null},textureMatrix:{value:null}},vertexShader:` - uniform mat4 textureMatrix; - varying vec4 vUv; - - #include - #include - - void main() { - - vUv = textureMatrix * vec4( position, 1.0 ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - #include - - }`,fragmentShader:` - uniform vec3 color; - uniform sampler2D tDiffuse; - varying vec4 vUv; - - #include - - float blendOverlay( float base, float blend ) { - - return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); - - } - - vec3 blendOverlay( vec3 base, vec3 blend ) { - - return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); - - } - - void main() { - - #include - - vec4 base = texture2DProj( tDiffuse, vUv ); - gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); - - #include - #include - - }`};class T4 extends _0{constructor(A,Q={}){super(A);this.isReflectorForSSRPass=!0,this.type="ReflectorForSSRPass";let J=this,K=Q.color!==void 0?new y1(Q.color):new y1(8355711),C=Q.textureWidth||512,U=Q.textureHeight||512,Y=Q.clipBias||0,Z=Q.shader||T4.ReflectorShader,X=Q.useDepthTexture===!0,E=new I1(0,1,0),H=new I1,$=new I1;J.needsUpdate=!1,J.maxDistance=T4.ReflectorShader.uniforms.maxDistance.value,J.opacity=T4.ReflectorShader.uniforms.opacity.value,J.color=K,J.resolution=Q.resolution||new p1(window.innerWidth,window.innerHeight),J._distanceAttenuation=T4.ReflectorShader.defines.DISTANCE_ATTENUATION,Object.defineProperty(J,"distanceAttenuation",{get(){return J._distanceAttenuation},set(n){if(J._distanceAttenuation===n)return;J._distanceAttenuation=n,J.material.defines.DISTANCE_ATTENUATION=n,J.material.needsUpdate=!0}}),J._fresnel=T4.ReflectorShader.defines.FRESNEL,Object.defineProperty(J,"fresnel",{get(){return J._fresnel},set(n){if(J._fresnel===n)return;J._fresnel=n,J.material.defines.FRESNEL=n,J.material.needsUpdate=!0}});let I=new I1,N=new I1,F=new I1,V=new Y0,D=new I1(0,0,-1),L=new I1,R=new I1,M=new Y0,T=new kA,h;if(X)h=new E6,h.type=r5,h.minFilter=YA,h.magFilter=YA;let g=new s0(C,U,{depthTexture:X?h:null,type:g0}),f=new T0({name:Z.name!==void 0?Z.name:"unspecified",transparent:X,defines:Object.assign({},T4.ReflectorShader.defines,{useDepthTexture:X}),uniforms:u0.clone(Z.uniforms),fragmentShader:Z.fragmentShader,vertexShader:Z.vertexShader});if(f.uniforms.tDiffuse.value=g.texture,f.uniforms.color.value=J.color,f.uniforms.textureMatrix.value=M,X)f.uniforms.tDepth.value=g.depthTexture;this.material=f;let d=[new V2(new I1(0,1,0),Y)];this.doRender=function(n,B,q){if(f.uniforms.maxDistance.value=J.maxDistance,f.uniforms.color.value=J.color,f.uniforms.opacity.value=J.opacity,H.copy(q.position).normalize(),$.copy(H).reflect(E),f.uniforms.fresnelCoe.value=(H.dot($)+1)/2,N.setFromMatrixPosition(J.matrixWorld),F.setFromMatrixPosition(q.matrixWorld),V.extractRotation(J.matrixWorld),I.set(0,0,1),I.applyMatrix4(V),L.subVectors(N,F),L.dot(I)>0)return;L.reflect(I).negate(),L.add(N),V.extractRotation(q.matrixWorld),D.set(0,0,-1),D.applyMatrix4(V),D.add(F),R.subVectors(N,D),R.reflect(I).negate(),R.add(N),T.position.copy(L),T.up.set(0,1,0),T.up.applyMatrix4(V),T.up.reflect(I),T.lookAt(R),T.far=q.far,T.updateMatrixWorld(),T.projectionMatrix.copy(q.projectionMatrix),f.uniforms.virtualCameraNear.value=q.near,f.uniforms.virtualCameraFar.value=q.far,f.uniforms.virtualCameraMatrixWorld.value=T.matrixWorld,f.uniforms.virtualCameraProjectionMatrix.value=q.projectionMatrix,f.uniforms.virtualCameraProjectionMatrixInverse.value=q.projectionMatrixInverse,f.uniforms.resolution.value=J.resolution,M.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1),M.multiply(T.projectionMatrix),M.multiply(T.matrixWorldInverse),M.multiply(J.matrixWorld);let P=n.getRenderTarget(),O=n.xr.enabled,w=n.shadowMap.autoUpdate,k=n.clippingPlanes;if(n.xr.enabled=!1,n.shadowMap.autoUpdate=!1,n.clippingPlanes=d,n.setRenderTarget(g),n.state.buffers.depth.setMask(!0),n.autoClear===!1)n.clear();n.render(B,T),n.xr.enabled=O,n.shadowMap.autoUpdate=w,n.clippingPlanes=k,n.setRenderTarget(P);let S=q.viewport;if(S!==void 0)n.state.viewport(S)},this.getRenderTarget=function(){return g}}}T4.ReflectorShader={name:"ReflectorShader",defines:{DISTANCE_ATTENUATION:!0,FRESNEL:!0},uniforms:{color:{value:null},tDiffuse:{value:null},tDepth:{value:null},textureMatrix:{value:new Y0},maxDistance:{value:180},opacity:{value:0.5},fresnelCoe:{value:null},virtualCameraNear:{value:null},virtualCameraFar:{value:null},virtualCameraProjectionMatrix:{value:new Y0},virtualCameraMatrixWorld:{value:new Y0},virtualCameraProjectionMatrixInverse:{value:new Y0},resolution:{value:new p1}},vertexShader:` - uniform mat4 textureMatrix; - varying vec4 vUv; - - void main() { - - vUv = textureMatrix * vec4( position, 1.0 ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - uniform vec3 color; - uniform sampler2D tDiffuse; - uniform sampler2D tDepth; - uniform float maxDistance; - uniform float opacity; - uniform float fresnelCoe; - uniform float virtualCameraNear; - uniform float virtualCameraFar; - uniform mat4 virtualCameraProjectionMatrix; - uniform mat4 virtualCameraProjectionMatrixInverse; - uniform mat4 virtualCameraMatrixWorld; - uniform vec2 resolution; - varying vec4 vUv; - #include - float blendOverlay( float base, float blend ) { - return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); - } - vec3 blendOverlay( vec3 base, vec3 blend ) { - return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); - } - float getDepth( const in vec2 uv ) { - return texture2D( tDepth, uv ).x; - } - float getViewZ( const in float depth ) { - return perspectiveDepthToViewZ( depth, virtualCameraNear, virtualCameraFar ); - } - vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { - vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc - clipPosition *= clipW; //clip - return ( virtualCameraProjectionMatrixInverse * clipPosition ).xyz;//view - } - void main() { - vec4 base = texture2DProj( tDiffuse, vUv ); - #ifdef useDepthTexture - vec2 uv=(gl_FragCoord.xy-.5)/resolution.xy; - uv.x=1.-uv.x; - float depth = texture2DProj( tDepth, vUv ).r; - float viewZ = getViewZ( depth ); - float clipW = virtualCameraProjectionMatrix[2][3] * viewZ+virtualCameraProjectionMatrix[3][3]; - vec3 viewPosition=getViewPosition( uv, depth, clipW ); - vec3 worldPosition=(virtualCameraMatrixWorld*vec4(viewPosition,1)).xyz; - if(worldPosition.y>maxDistance) discard; - float op=opacity; - #ifdef DISTANCE_ATTENUATION - float ratio=1.-(worldPosition.y/maxDistance); - float attenuation=ratio*ratio; - op=opacity*attenuation; - #endif - #ifdef FRESNEL - op*=fresnelCoe; - #endif - gl_FragColor = vec4( blendOverlay( base.rgb, color ), op ); - #else - gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); - #endif - } - `};class rC extends _0{constructor(A,Q={}){super(A);this.isRefractor=!0,this.type="Refractor",this.camera=new kA;let J=this,K=Q.color!==void 0?new y1(Q.color):new y1(8355711),C=Q.textureWidth||512,U=Q.textureHeight||512,Y=Q.clipBias||0,Z=Q.shader||rC.RefractorShader,X=Q.multisample!==void 0?Q.multisample:4,E=this.camera;E.matrixAutoUpdate=!1,E.userData.refractor=!0;let H=new V2,$=new Y0,I=new s0(C,U,{samples:X,type:g0});this.material=new T0({name:Z.name!==void 0?Z.name:"unspecified",uniforms:u0.clone(Z.uniforms),vertexShader:Z.vertexShader,fragmentShader:Z.fragmentShader,transparent:!0}),this.material.uniforms.color.value=K,this.material.uniforms.tDiffuse.value=I.texture,this.material.uniforms.textureMatrix.value=$;let N=function(){let R=new I1,M=new I1,T=new Y0,h=new I1,y=new I1;return function g(f){return R.setFromMatrixPosition(J.matrixWorld),M.setFromMatrixPosition(f.matrixWorld),h.subVectors(R,M),T.extractRotation(J.matrixWorld),y.set(0,0,1),y.applyMatrix4(T),h.dot(y)<0}}(),F=function(){let R=new I1,M=new I1,T=new t0,h=new I1;return function y(){J.matrixWorld.decompose(M,T,h),R.set(0,0,1).applyQuaternion(T).normalize(),R.negate(),H.setFromNormalAndCoplanarPoint(R,M)}}(),V=function(){let R=new V2,M=new X0,T=new X0;return function h(y){E.matrixWorld.copy(y.matrixWorld),E.matrixWorldInverse.copy(E.matrixWorld).invert(),E.projectionMatrix.copy(y.projectionMatrix),E.far=y.far,R.copy(H),R.applyMatrix4(E.matrixWorldInverse),M.set(R.normal.x,R.normal.y,R.normal.z,R.constant);let g=E.projectionMatrix;T.x=(Math.sign(M.x)+g.elements[8])/g.elements[0],T.y=(Math.sign(M.y)+g.elements[9])/g.elements[5],T.z=-1,T.w=(1+g.elements[10])/g.elements[14],M.multiplyScalar(2/M.dot(T)),g.elements[2]=M.x,g.elements[6]=M.y,g.elements[10]=M.z+1-Y,g.elements[14]=M.w}}();function D(R){$.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1),$.multiply(R.projectionMatrix),$.multiply(R.matrixWorldInverse),$.multiply(J.matrixWorld)}function L(R,M,T){J.visible=!1;let h=R.getRenderTarget(),y=R.xr.enabled,g=R.shadowMap.autoUpdate;if(R.xr.enabled=!1,R.shadowMap.autoUpdate=!1,R.setRenderTarget(I),R.autoClear===!1)R.clear();R.render(M,E),R.xr.enabled=y,R.shadowMap.autoUpdate=g,R.setRenderTarget(h);let f=T.viewport;if(f!==void 0)R.state.viewport(f);J.visible=!0}this.onBeforeRender=function(R,M,T){if(T.userData.refractor===!0)return;if(!N(T)===!0)return;F(),D(T),V(T),L(R,M,T)},this.getRenderTarget=function(){return I},this.dispose=function(){I.dispose(),J.material.dispose()}}}rC.RefractorShader={name:"RefractorShader",uniforms:{color:{value:null},tDiffuse:{value:null},textureMatrix:{value:null}},vertexShader:` - - uniform mat4 textureMatrix; - - varying vec4 vUv; - - void main() { - - vUv = textureMatrix * vec4( position, 1.0 ); - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform vec3 color; - uniform sampler2D tDiffuse; - - varying vec4 vUv; - - float blendOverlay( float base, float blend ) { - - return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); - - } - - vec3 blendOverlay( vec3 base, vec3 blend ) { - - return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); - - } - - void main() { - - vec4 base = texture2DProj( tDiffuse, vUv ); - gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); - - #include - #include - - }`};var qv1=new Y0;class KD extends _0{constructor(){let A=KD.SkyShader,Q=new T0({name:A.name,uniforms:u0.clone(A.uniforms),vertexShader:A.vertexShader,fragmentShader:A.fragmentShader,side:w2,depthWrite:!1});super(new R8(1,1,1),Q);this.isSky=!0}}KD.SkyShader={name:"SkyShader",uniforms:{turbidity:{value:2},rayleigh:{value:1},mieCoefficient:{value:0.005},mieDirectionalG:{value:0.8},sunPosition:{value:new I1},up:{value:new I1(0,1,0)}},vertexShader:` - uniform vec3 sunPosition; - uniform float rayleigh; - uniform float turbidity; - uniform float mieCoefficient; - uniform vec3 up; - - varying vec3 vWorldPosition; - varying vec3 vSunDirection; - varying float vSunfade; - varying vec3 vBetaR; - varying vec3 vBetaM; - varying float vSunE; - - // constants for atmospheric scattering - const float e = 2.71828182845904523536028747135266249775724709369995957; - const float pi = 3.141592653589793238462643383279502884197169; - - // wavelength of used primaries, according to preetham - const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 ); - // this pre-calculation replaces older TotalRayleigh(vec3 lambda) function: - // (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn)) - const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 ); - - // mie stuff - // K coefficient for the primaries - const float v = 4.0; - const vec3 K = vec3( 0.686, 0.678, 0.666 ); - // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K - const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 ); - - // earth shadow hack - // cutoffAngle = pi / 1.95; - const float cutoffAngle = 1.6110731556870734; - const float steepness = 1.5; - const float EE = 1000.0; - - float sunIntensity( float zenithAngleCos ) { - zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 ); - return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) ); - } - - vec3 totalMie( float T ) { - float c = ( 0.2 * T ) * 10E-18; - return 0.434 * c * MieConst; - } - - void main() { - - vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); - vWorldPosition = worldPosition.xyz; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - gl_Position.z = gl_Position.w; // set z to camera.far - - vSunDirection = normalize( sunPosition ); - - vSunE = sunIntensity( dot( vSunDirection, up ) ); - - vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 ); - - float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) ); - - // extinction (absorption + out scattering) - // rayleigh coefficients - vBetaR = totalRayleigh * rayleighCoefficient; - - // mie coefficients - vBetaM = totalMie( turbidity ) * mieCoefficient; - - }`,fragmentShader:` - varying vec3 vWorldPosition; - varying vec3 vSunDirection; - varying float vSunfade; - varying vec3 vBetaR; - varying vec3 vBetaM; - varying float vSunE; - - uniform float mieDirectionalG; - uniform vec3 up; - - // constants for atmospheric scattering - const float pi = 3.141592653589793238462643383279502884197169; - - const float n = 1.0003; // refractive index of air - const float N = 2.545E25; // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius) - - // optical length at zenith for molecules - const float rayleighZenithLength = 8.4E3; - const float mieZenithLength = 1.25E3; - // 66 arc seconds -> degrees, and the cosine of that - const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324; - - // 3.0 / ( 16.0 * pi ) - const float THREE_OVER_SIXTEENPI = 0.05968310365946075; - // 1.0 / ( 4.0 * pi ) - const float ONE_OVER_FOURPI = 0.07957747154594767; - - float rayleighPhase( float cosTheta ) { - return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) ); - } - - float hgPhase( float cosTheta, float g ) { - float g2 = pow( g, 2.0 ); - float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 ); - return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse ); - } - - void main() { - - vec3 direction = normalize( vWorldPosition - cameraPosition ); - - // optical length - // cutoff angle at 90 to avoid singularity in next formula. - float zenithAngle = acos( max( 0.0, dot( up, direction ) ) ); - float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) ); - float sR = rayleighZenithLength * inverse; - float sM = mieZenithLength * inverse; - - // combined extinction factor - vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) ); - - // in scattering - float cosTheta = dot( direction, vSunDirection ); - - float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 ); - vec3 betaRTheta = vBetaR * rPhase; - - float mPhase = hgPhase( cosTheta, mieDirectionalG ); - vec3 betaMTheta = vBetaM * mPhase; - - vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) ); - Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) ); - - // nightsky - float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2] - float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2] - vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 ); - vec3 L0 = vec3( 0.1 ) * Fex; - - // composition + solar disc - float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta ); - L0 += ( vSunE * 19000.0 * Fex ) * sundisk; - - vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 ); - - vec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) ); - - gl_FragColor = vec4( retColor, 1.0 ); - - #include - #include - - }`};class ZW extends _0{constructor(A,Q={}){super(A);this.isWater=!0,this.type="Water";let J=this,K=Q.color!==void 0?new y1(Q.color):new y1(16777215),C=Q.textureWidth!==void 0?Q.textureWidth:512,U=Q.textureHeight!==void 0?Q.textureHeight:512,Y=Q.clipBias!==void 0?Q.clipBias:0,Z=Q.flowDirection!==void 0?Q.flowDirection:new p1(1,0),X=Q.flowSpeed!==void 0?Q.flowSpeed:0.03,E=Q.reflectivity!==void 0?Q.reflectivity:0.02,H=Q.scale!==void 0?Q.scale:1,$=Q.shader!==void 0?Q.shader:ZW.WaterShader,I=new J8,N=Q.flowMap||void 0,F=Q.normalMap0||I.load("textures/water/Water_1_M_Normal.jpg"),V=Q.normalMap1||I.load("textures/water/Water_2_M_Normal.jpg"),D=0.15,L=D*0.5,R=new Y0,M=new Y3;if(aC===void 0){console.error("THREE.Water: Required component Reflector not found.");return}if(rC===void 0){console.error("THREE.Water: Required component Refractor not found.");return}let T=new aC(A,{textureWidth:C,textureHeight:U,clipBias:Y}),h=new rC(A,{textureWidth:C,textureHeight:U,clipBias:Y});if(T.matrixAutoUpdate=!1,h.matrixAutoUpdate=!1,this.material=new T0({name:$.name,uniforms:u0.merge([M0.fog,$.uniforms]),vertexShader:$.vertexShader,fragmentShader:$.fragmentShader,transparent:!0,fog:!0}),N!==void 0)this.material.defines.USE_FLOWMAP="",this.material.uniforms.tFlowMap={type:"t",value:N};else this.material.uniforms.flowDirection={type:"v2",value:Z};F.wrapS=F.wrapT=A2,V.wrapS=V.wrapT=A2,this.material.uniforms.tReflectionMap.value=T.getRenderTarget().texture,this.material.uniforms.tRefractionMap.value=h.getRenderTarget().texture,this.material.uniforms.tNormalMap0.value=F,this.material.uniforms.tNormalMap1.value=V,this.material.uniforms.color.value=K,this.material.uniforms.reflectivity.value=E,this.material.uniforms.textureMatrix.value=R,this.material.uniforms.config.value.x=0,this.material.uniforms.config.value.y=L,this.material.uniforms.config.value.z=L,this.material.uniforms.config.value.w=H;function y(f){R.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1),R.multiply(f.projectionMatrix),R.multiply(f.matrixWorldInverse),R.multiply(J.matrixWorld)}function g(){let f=M.getDelta(),u=J.material.uniforms.config;if(u.value.x+=X*f,u.value.y=u.value.x+L,u.value.x>=D)u.value.x=0,u.value.y=L;else if(u.value.y>=D)u.value.y=u.value.y-D}this.onBeforeRender=function(f,u,d){y(d),g(),J.visible=!1,T.matrixWorld.copy(J.matrixWorld),h.matrixWorld.copy(J.matrixWorld),T.onBeforeRender(f,u,d),h.onBeforeRender(f,u,d),J.visible=!0}}}ZW.WaterShader={name:"WaterShader",uniforms:{color:{type:"c",value:null},reflectivity:{type:"f",value:0},tReflectionMap:{type:"t",value:null},tRefractionMap:{type:"t",value:null},tNormalMap0:{type:"t",value:null},tNormalMap1:{type:"t",value:null},textureMatrix:{type:"m4",value:null},config:{type:"v4",value:new X0}},vertexShader:` - - #include - #include - #include - - uniform mat4 textureMatrix; - - varying vec4 vCoord; - varying vec2 vUv; - varying vec3 vToEye; - - void main() { - - vUv = uv; - vCoord = textureMatrix * vec4( position, 1.0 ); - - vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); - vToEye = cameraPosition - worldPosition.xyz; - - vec4 mvPosition = viewMatrix * worldPosition; // used in fog_vertex - gl_Position = projectionMatrix * mvPosition; - - #include - #include - - }`,fragmentShader:` - - #include - #include - #include - - uniform sampler2D tReflectionMap; - uniform sampler2D tRefractionMap; - uniform sampler2D tNormalMap0; - uniform sampler2D tNormalMap1; - - #ifdef USE_FLOWMAP - uniform sampler2D tFlowMap; - #else - uniform vec2 flowDirection; - #endif - - uniform vec3 color; - uniform float reflectivity; - uniform vec4 config; - - varying vec4 vCoord; - varying vec2 vUv; - varying vec3 vToEye; - - void main() { - - #include - - float flowMapOffset0 = config.x; - float flowMapOffset1 = config.y; - float halfCycle = config.z; - float scale = config.w; - - vec3 toEye = normalize( vToEye ); - - // determine flow direction - vec2 flow; - #ifdef USE_FLOWMAP - flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0; - #else - flow = flowDirection; - #endif - flow.x *= - 1.0; - - // sample normal maps (distort uvs with flowdata) - vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 ); - vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 ); - - // linear interpolate to get the final normal color - float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle; - vec4 normalColor = mix( normalColor0, normalColor1, flowLerp ); - - // calculate normal vector - vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) ); - - // calculate the fresnel term to blend reflection and refraction maps - float theta = max( dot( toEye, normal ), 0.0 ); - float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 ); - - // calculate final uv coords - vec3 coord = vCoord.xyz / vCoord.w; - vec2 uv = coord.xy + coord.z * normal.xz * 0.05; - - vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) ); - vec4 refractColor = texture2D( tRefractionMap, uv ); - - // multiply water color with the mix of both textures - gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance ); - - #include - #include - #include - - }`};var _v1=new I1(1,1,1),Tv1=new I1;var m2={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform float opacity; - - uniform sampler2D tDiffuse; - - varying vec2 vUv; - - void main() { - - vec4 texel = texture2D( tDiffuse, vUv ); - gl_FragColor = opacity * texel; - - - }`};var CD={name:"ConvolutionShader",defines:{KERNEL_SIZE_FLOAT:"25.0",KERNEL_SIZE_INT:"25"},uniforms:{tDiffuse:{value:null},uImageIncrement:{value:new p1(0.001953125,0)},cKernel:{value:[]}},vertexShader:` - - uniform vec2 uImageIncrement; - - varying vec2 vUv; - - void main() { - - vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform float cKernel[ KERNEL_SIZE_INT ]; - - uniform sampler2D tDiffuse; - uniform vec2 uImageIncrement; - - varying vec2 vUv; - - void main() { - - vec2 imageCoord = vUv; - vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 ); - - for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) { - - sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ]; - imageCoord += uImageIncrement; - - } - - gl_FragColor = sum; - - }`,buildKernel:function(A){let J=2*Math.ceil(A*3)+1;if(J>25)J=25;let K=(J-1)*0.5,C=new Array(J),U=0;for(let Y=0;Y - #include - - #ifndef FRAGMENT_OUTPUT - #define FRAGMENT_OUTPUT vec4(vec3(ao), 1.) - #endif - - vec3 getViewPosition(const in vec2 screenPosition, const in float depth) { - vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); - vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; - return viewSpacePosition.xyz / viewSpacePosition.w; - } - - float getDepth(const vec2 uv) { - return textureLod(tDepth, uv.xy, 0.0).DEPTH_SWIZZLING; - } - - float fetchDepth(const ivec2 uv) { - return texelFetch(tDepth, uv.xy, 0).DEPTH_SWIZZLING; - } - - float getViewZ(const in float depth) { - #if PERSPECTIVE_CAMERA == 1 - return perspectiveDepthToViewZ(depth, cameraNear, cameraFar); - #else - return orthographicDepthToViewZ(depth, cameraNear, cameraFar); - #endif - } - - vec3 computeNormalFromDepth(const vec2 uv) { - vec2 size = vec2(textureSize(tDepth, 0)); - ivec2 p = ivec2(uv * size); - float c0 = fetchDepth(p); - float l2 = fetchDepth(p - ivec2(2, 0)); - float l1 = fetchDepth(p - ivec2(1, 0)); - float r1 = fetchDepth(p + ivec2(1, 0)); - float r2 = fetchDepth(p + ivec2(2, 0)); - float b2 = fetchDepth(p - ivec2(0, 2)); - float b1 = fetchDepth(p - ivec2(0, 1)); - float t1 = fetchDepth(p + ivec2(0, 1)); - float t2 = fetchDepth(p + ivec2(0, 2)); - float dl = abs((2.0 * l1 - l2) - c0); - float dr = abs((2.0 * r1 - r2) - c0); - float db = abs((2.0 * b1 - b2) - c0); - float dt = abs((2.0 * t1 - t2) - c0); - vec3 ce = getViewPosition(uv, c0).xyz; - vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; - vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; - return normalize(cross(dpdx, dpdy)); - } - - vec3 getViewNormal(const vec2 uv) { - #if NORMAL_VECTOR_TYPE == 2 - return normalize(textureLod(tNormal, uv, 0.).rgb); - #elif NORMAL_VECTOR_TYPE == 1 - return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); - #else - return computeNormalFromDepth(uv); - #endif - } - - vec3 getSceneUvAndDepth(vec3 sampleViewPos) { - vec4 sampleClipPos = cameraProjectionMatrix * vec4(sampleViewPos, 1.); - vec2 sampleUv = sampleClipPos.xy / sampleClipPos.w * 0.5 + 0.5; - float sampleSceneDepth = getDepth(sampleUv); - return vec3(sampleUv, sampleSceneDepth); - } - - void main() { - float depth = getDepth(vUv.xy); - if (depth >= 1.0) { - discard; - return; - } - vec3 viewPos = getViewPosition(vUv, depth); - vec3 viewNormal = getViewNormal(vUv); - - float radiusToUse = radius; - float distanceFalloffToUse = thickness; - #if SCREEN_SPACE_RADIUS == 1 - float radiusScale = getViewPosition(vec2(0.5 + float(SCREEN_SPACE_RADIUS_SCALE) / resolution.x, 0.0), depth).x; - radiusToUse *= radiusScale; - distanceFalloffToUse *= radiusScale; - #endif - - #if SCENE_CLIP_BOX == 1 - vec3 worldPos = (cameraWorldMatrix * vec4(viewPos, 1.0)).xyz; - float boxDistance = length(max(vec3(0.0), max(sceneBoxMin - worldPos, worldPos - sceneBoxMax))); - if (boxDistance > radiusToUse) { - discard; - return; - } - #endif - - vec2 noiseResolution = vec2(textureSize(tNoise, 0)); - vec2 noiseUv = vUv * resolution / noiseResolution; - vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); - vec3 randomVec = noiseTexel.xyz * 2.0 - 1.0; - vec3 tangent = normalize(vec3(randomVec.xy, 0.)); - vec3 bitangent = vec3(-tangent.y, tangent.x, 0.); - mat3 kernelMatrix = mat3(tangent, bitangent, vec3(0., 0., 1.)); - - const int DIRECTIONS = SAMPLES < 30 ? 3 : 5; - const int STEPS = (SAMPLES + DIRECTIONS - 1) / DIRECTIONS; - float ao = 0.0; - for (int i = 0; i < DIRECTIONS; ++i) { - - float angle = float(i) / float(DIRECTIONS) * PI; - vec4 sampleDir = vec4(cos(angle), sin(angle), 0., 0.5 + 0.5 * noiseTexel.w); - sampleDir.xyz = normalize(kernelMatrix * sampleDir.xyz); - - vec3 viewDir = normalize(-viewPos.xyz); - vec3 sliceBitangent = normalize(cross(sampleDir.xyz, viewDir)); - vec3 sliceTangent = cross(sliceBitangent, viewDir); - vec3 normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent)); - - vec3 tangentToNormalInSlice = cross(normalInSlice, sliceBitangent); - vec2 cosHorizons = vec2(dot(viewDir, tangentToNormalInSlice), dot(viewDir, -tangentToNormalInSlice)); - - for (int j = 0; j < STEPS; ++j) { - vec3 sampleViewOffset = sampleDir.xyz * radiusToUse * sampleDir.w * pow(float(j + 1) / float(STEPS), distanceExponent); - - vec3 sampleSceneUvDepth = getSceneUvAndDepth(viewPos + sampleViewOffset); - vec3 sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); - vec3 viewDelta = sampleSceneViewPos - viewPos; - if (abs(viewDelta.z) < thickness) { - float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); - cosHorizons.x += max(0., (sampleCosHorizon - cosHorizons.x) * mix(1., 2. / float(j + 2), distanceFallOff)); - } - - sampleSceneUvDepth = getSceneUvAndDepth(viewPos - sampleViewOffset); - sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); - viewDelta = sampleSceneViewPos - viewPos; - if (abs(viewDelta.z) < thickness) { - float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); - cosHorizons.y += max(0., (sampleCosHorizon - cosHorizons.y) * mix(1., 2. / float(j + 2), distanceFallOff)); - } - } - - vec2 sinHorizons = sqrt(1. - cosHorizons * cosHorizons); - float nx = dot(normalInSlice, sliceTangent); - float ny = dot(normalInSlice, viewDir); - float nxb = 1. / 2. * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y); - float nyb = 1. / 2. * (2. - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y); - float occlusion = nx * nxb + ny * nyb; - ao += occlusion; - } - - ao = clamp(ao / float(DIRECTIONS), 0., 1.); - #if SCENE_CLIP_BOX == 1 - ao = mix(ao, 1., smoothstep(0., radiusToUse, boxDistance)); - #endif - ao = pow(ao, scale); - - gl_FragColor = FRAGMENT_OUTPUT; - }`},IB={name:"GTAODepthShader",defines:{PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null}},vertexShader:` - varying vec2 vUv; - - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:` - uniform sampler2D tDepth; - uniform float cameraNear; - uniform float cameraFar; - varying vec2 vUv; - - #include - - float getLinearDepth( const in vec2 screenPosition ) { - #if PERSPECTIVE_CAMERA == 1 - float fragCoordZ = texture2D( tDepth, screenPosition ).x; - float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); - return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); - #else - return texture2D( tDepth, screenPosition ).x; - #endif - } - - void main() { - float depth = getLinearDepth( vUv ); - gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); - - }`},XW={name:"GTAOBlendShader",uniforms:{tDiffuse:{value:null},intensity:{value:1}},vertexShader:` - varying vec2 vUv; - - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:` - uniform float intensity; - uniform sampler2D tDiffuse; - varying vec2 vUv; - - void main() { - vec4 texel = texture2D( tDiffuse, vUv ); - gl_FragColor = vec4(mix(vec3(1.), texel.rgb, intensity), texel.a); - }`};function Qc(A=5){let Q=Math.floor(A)%2===0?Math.floor(A)+1:Math.floor(A),J=eB1(Q),K=J.length,C=new Uint8Array(K*4);for(let Y=0;Y - #include - - #ifndef SAMPLE_LUMINANCE - #define SAMPLE_LUMINANCE dot(vec3(0.2125, 0.7154, 0.0721), a) - #endif - - #ifndef FRAGMENT_OUTPUT - #define FRAGMENT_OUTPUT vec4(denoised, 1.) - #endif - - float getLuminance(const in vec3 a) { - return SAMPLE_LUMINANCE; - } - - const vec3 poissonDisk[SAMPLES] = SAMPLE_VECTORS; - - vec3 getViewPosition(const in vec2 screenPosition, const in float depth) { - vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); - vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; - return viewSpacePosition.xyz / viewSpacePosition.w; - } - - float getDepth(const vec2 uv) { - #if DEPTH_VALUE_SOURCE == 1 - return textureLod(tDepth, uv.xy, 0.0).a; - #else - return textureLod(tDepth, uv.xy, 0.0).r; - #endif - } - - float fetchDepth(const ivec2 uv) { - #if DEPTH_VALUE_SOURCE == 1 - return texelFetch(tDepth, uv.xy, 0).a; - #else - return texelFetch(tDepth, uv.xy, 0).r; - #endif - } - - vec3 computeNormalFromDepth(const vec2 uv) { - vec2 size = vec2(textureSize(tDepth, 0)); - ivec2 p = ivec2(uv * size); - float c0 = fetchDepth(p); - float l2 = fetchDepth(p - ivec2(2, 0)); - float l1 = fetchDepth(p - ivec2(1, 0)); - float r1 = fetchDepth(p + ivec2(1, 0)); - float r2 = fetchDepth(p + ivec2(2, 0)); - float b2 = fetchDepth(p - ivec2(0, 2)); - float b1 = fetchDepth(p - ivec2(0, 1)); - float t1 = fetchDepth(p + ivec2(0, 1)); - float t2 = fetchDepth(p + ivec2(0, 2)); - float dl = abs((2.0 * l1 - l2) - c0); - float dr = abs((2.0 * r1 - r2) - c0); - float db = abs((2.0 * b1 - b2) - c0); - float dt = abs((2.0 * t1 - t2) - c0); - vec3 ce = getViewPosition(uv, c0).xyz; - vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz - : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; - vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz - : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; - return normalize(cross(dpdx, dpdy)); - } - - vec3 getViewNormal(const vec2 uv) { - #if NORMAL_VECTOR_TYPE == 2 - return normalize(textureLod(tNormal, uv, 0.).rgb); - #elif NORMAL_VECTOR_TYPE == 1 - return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); - #else - return computeNormalFromDepth(uv); - #endif - } - - void denoiseSample(in vec3 center, in vec3 viewNormal, in vec3 viewPos, in vec2 sampleUv, inout vec3 denoised, inout float totalWeight) { - vec4 sampleTexel = textureLod(tDiffuse, sampleUv, 0.0); - float sampleDepth = getDepth(sampleUv); - vec3 sampleNormal = getViewNormal(sampleUv); - vec3 neighborColor = sampleTexel.rgb; - vec3 viewPosSample = getViewPosition(sampleUv, sampleDepth); - - float normalDiff = dot(viewNormal, sampleNormal); - float normalSimilarity = pow(max(normalDiff, 0.), normalPhi); - float lumaDiff = abs(getLuminance(neighborColor) - getLuminance(center)); - float lumaSimilarity = max(1.0 - lumaDiff / lumaPhi, 0.0); - float depthDiff = abs(dot(viewPos - viewPosSample, viewNormal)); - float depthSimilarity = max(1. - depthDiff / depthPhi, 0.); - float w = lumaSimilarity * depthSimilarity * normalSimilarity; - - denoised += w * neighborColor; - totalWeight += w; - } - - void main() { - float depth = getDepth(vUv.xy); - vec3 viewNormal = getViewNormal(vUv); - if (depth == 1. || dot(viewNormal, viewNormal) == 0.) { - discard; - return; - } - vec4 texel = textureLod(tDiffuse, vUv, 0.0); - vec3 center = texel.rgb; - vec3 viewPos = getViewPosition(vUv, depth); - - vec2 noiseResolution = vec2(textureSize(tNoise, 0)); - vec2 noiseUv = vUv * resolution / noiseResolution; - vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); - vec2 noiseVec = vec2(sin(noiseTexel[index % 4] * 2. * PI), cos(noiseTexel[index % 4] * 2. * PI)); - mat2 rotationMatrix = mat2(noiseVec.x, -noiseVec.y, noiseVec.x, noiseVec.y); - - float totalWeight = 1.0; - vec3 denoised = texel.rgb; - for (int i = 0; i < SAMPLES; i++) { - vec3 sampleDir = poissonDisk[i]; - vec2 offset = rotationMatrix * (sampleDir.xy * (1. + sampleDir.z * (radius - 1.)) / resolution); - vec2 sampleUv = vUv + offset; - denoiseSample(center, viewNormal, viewPos, sampleUv, denoised, totalWeight); - } - - if (totalWeight > 0.) { - denoised /= totalWeight; - } - gl_FragColor = FRAGMENT_OUTPUT; - }`};function YD(A,Q,J){let K=AX1(A,Q,J),C="vec3[SAMPLES](";for(let U=0;U cos_t ) ? rad - sin_t * rad : rad - cos_t * rad ) ); - - } - - return rad - dist; - - } - - struct Cell { - - // grid sample positions - vec2 normal; - vec2 p1; - vec2 p2; - vec2 p3; - vec2 p4; - float samp2; - float samp1; - float samp3; - float samp4; - - }; - - vec4 getSample( vec2 point ) { - - // multi-sampled point - vec4 tex = texture2D( tDiffuse, vec2( point.x / width, point.y / height ) ); - float base = rand( vec2( floor( point.x ), floor( point.y ) ) ) * PI2; - float step = PI2 / float( samples ); - float dist = radius * 0.66; - - for ( int i = 0; i < samples; ++i ) { - - float r = base + step * float( i ); - vec2 coord = point + vec2( cos( r ) * dist, sin( r ) * dist ); - tex += texture2D( tDiffuse, vec2( coord.x / width, coord.y / height ) ); - - } - - tex /= float( samples ) + 1.0; - return tex; - - } - - float getDotColour( Cell c, vec2 p, int channel, float angle, float aa ) { - - // get colour for given point - float dist_c_1, dist_c_2, dist_c_3, dist_c_4, res; - - if ( channel == 0 ) { - - c.samp1 = getSample( c.p1 ).r; - c.samp2 = getSample( c.p2 ).r; - c.samp3 = getSample( c.p3 ).r; - c.samp4 = getSample( c.p4 ).r; - - } else if (channel == 1) { - - c.samp1 = getSample( c.p1 ).g; - c.samp2 = getSample( c.p2 ).g; - c.samp3 = getSample( c.p3 ).g; - c.samp4 = getSample( c.p4 ).g; - - } else { - - c.samp1 = getSample( c.p1 ).b; - c.samp3 = getSample( c.p3 ).b; - c.samp2 = getSample( c.p2 ).b; - c.samp4 = getSample( c.p4 ).b; - - } - - dist_c_1 = distanceToDotRadius( c.samp1, c.p1, c.normal, p, angle, radius ); - dist_c_2 = distanceToDotRadius( c.samp2, c.p2, c.normal, p, angle, radius ); - dist_c_3 = distanceToDotRadius( c.samp3, c.p3, c.normal, p, angle, radius ); - dist_c_4 = distanceToDotRadius( c.samp4, c.p4, c.normal, p, angle, radius ); - res = ( dist_c_1 > 0.0 ) ? clamp( dist_c_1 / aa, 0.0, 1.0 ) : 0.0; - res += ( dist_c_2 > 0.0 ) ? clamp( dist_c_2 / aa, 0.0, 1.0 ) : 0.0; - res += ( dist_c_3 > 0.0 ) ? clamp( dist_c_3 / aa, 0.0, 1.0 ) : 0.0; - res += ( dist_c_4 > 0.0 ) ? clamp( dist_c_4 / aa, 0.0, 1.0 ) : 0.0; - res = clamp( res, 0.0, 1.0 ); - - return res; - - } - - Cell getReferenceCell( vec2 p, vec2 origin, float grid_angle, float step ) { - - // get containing cell - Cell c; - - // calc grid - vec2 n = vec2( cos( grid_angle ), sin( grid_angle ) ); - float threshold = step * 0.5; - float dot_normal = n.x * ( p.x - origin.x ) + n.y * ( p.y - origin.y ); - float dot_line = -n.y * ( p.x - origin.x ) + n.x * ( p.y - origin.y ); - vec2 offset = vec2( n.x * dot_normal, n.y * dot_normal ); - float offset_normal = mod( hypot( offset.x, offset.y ), step ); - float normal_dir = ( dot_normal < 0.0 ) ? 1.0 : -1.0; - float normal_scale = ( ( offset_normal < threshold ) ? -offset_normal : step - offset_normal ) * normal_dir; - float offset_line = mod( hypot( ( p.x - offset.x ) - origin.x, ( p.y - offset.y ) - origin.y ), step ); - float line_dir = ( dot_line < 0.0 ) ? 1.0 : -1.0; - float line_scale = ( ( offset_line < threshold ) ? -offset_line : step - offset_line ) * line_dir; - - // get closest corner - c.normal = n; - c.p1.x = p.x - n.x * normal_scale + n.y * line_scale; - c.p1.y = p.y - n.y * normal_scale - n.x * line_scale; - - // scatter - if ( scatter != 0.0 ) { - - float off_mag = scatter * threshold * 0.5; - float off_angle = rand( vec2( floor( c.p1.x ), floor( c.p1.y ) ) ) * PI2; - c.p1.x += cos( off_angle ) * off_mag; - c.p1.y += sin( off_angle ) * off_mag; - - } - - // find corners - float normal_step = normal_dir * ( ( offset_normal < threshold ) ? step : -step ); - float line_step = line_dir * ( ( offset_line < threshold ) ? step : -step ); - c.p2.x = c.p1.x - n.x * normal_step; - c.p2.y = c.p1.y - n.y * normal_step; - c.p3.x = c.p1.x + n.y * line_step; - c.p3.y = c.p1.y - n.x * line_step; - c.p4.x = c.p1.x - n.x * normal_step + n.y * line_step; - c.p4.y = c.p1.y - n.y * normal_step - n.x * line_step; - - return c; - - } - - float blendColour( float a, float b, float t ) { - - // blend colours - if ( blendingMode == BLENDING_LINEAR ) { - return blend( a, b, 1.0 - t ); - } else if ( blendingMode == BLENDING_ADD ) { - return blend( a, min( 1.0, a + b ), t ); - } else if ( blendingMode == BLENDING_MULTIPLY ) { - return blend( a, max( 0.0, a * b ), t ); - } else if ( blendingMode == BLENDING_LIGHTER ) { - return blend( a, max( a, b ), t ); - } else if ( blendingMode == BLENDING_DARKER ) { - return blend( a, min( a, b ), t ); - } else { - return blend( a, b, 1.0 - t ); - } - - } - - void main() { - - if ( ! disable ) { - - // setup - vec2 p = vec2( vUV.x * width, vUV.y * height ); - vec2 origin = vec2( 0, 0 ); - float aa = ( radius < 2.5 ) ? radius * 0.5 : 1.25; - - // get channel samples - Cell cell_r = getReferenceCell( p, origin, rotateR, radius ); - Cell cell_g = getReferenceCell( p, origin, rotateG, radius ); - Cell cell_b = getReferenceCell( p, origin, rotateB, radius ); - float r = getDotColour( cell_r, p, 0, rotateR, aa ); - float g = getDotColour( cell_g, p, 1, rotateG, aa ); - float b = getDotColour( cell_b, p, 2, rotateB, aa ); - - // blend with original - vec4 colour = texture2D( tDiffuse, vUV ); - r = blendColour( r, colour.r, blending ); - g = blendColour( g, colour.g, blending ); - b = blendColour( b, colour.b, blending ); - - if ( greyscale ) { - r = g = b = (r + b + g) / 3.0; - } - - gl_FragColor = vec4( r, g, b, 1.0 ); - - } else { - - gl_FragColor = texture2D( tDiffuse, vUV ); - - } - - }`};class WJ extends B2{constructor(A,Q,J,K){super();this.renderScene=Q,this.renderCamera=J,this.selectedObjects=K!==void 0?K:[],this.visibleEdgeColor=new y1(1,1,1),this.hiddenEdgeColor=new y1(0.1,0.04,0.02),this.edgeGlow=0,this.usePatternTexture=!1,this.edgeThickness=1,this.edgeStrength=3,this.downSampleRatio=2,this.pulsePeriod=0,this._visibilityCache=/*@__PURE__*/new Map,this._selectionCache=/*@__PURE__*/new Set,this.resolution=A!==void 0?new p1(A.x,A.y):new p1(256,256);let C=Math.round(this.resolution.x/this.downSampleRatio),U=Math.round(this.resolution.y/this.downSampleRatio);this.renderTargetMaskBuffer=new s0(this.resolution.x,this.resolution.y),this.renderTargetMaskBuffer.texture.name="OutlinePass.mask",this.renderTargetMaskBuffer.texture.generateMipmaps=!1,this.depthMaterial=new G4,this.depthMaterial.side=VA,this.depthMaterial.depthPacking=CC,this.depthMaterial.blending=XA,this.prepareMaskMaterial=this.getPrepareMaskMaterial(),this.prepareMaskMaterial.side=VA,this.prepareMaskMaterial.fragmentShader=E(this.prepareMaskMaterial.fragmentShader,this.renderCamera),this.renderTargetDepthBuffer=new s0(this.resolution.x,this.resolution.y,{type:g0}),this.renderTargetDepthBuffer.texture.name="OutlinePass.depth",this.renderTargetDepthBuffer.texture.generateMipmaps=!1,this.renderTargetMaskDownSampleBuffer=new s0(C,U,{type:g0}),this.renderTargetMaskDownSampleBuffer.texture.name="OutlinePass.depthDownSample",this.renderTargetMaskDownSampleBuffer.texture.generateMipmaps=!1,this.renderTargetBlurBuffer1=new s0(C,U,{type:g0}),this.renderTargetBlurBuffer1.texture.name="OutlinePass.blur1",this.renderTargetBlurBuffer1.texture.generateMipmaps=!1,this.renderTargetBlurBuffer2=new s0(Math.round(C/2),Math.round(U/2),{type:g0}),this.renderTargetBlurBuffer2.texture.name="OutlinePass.blur2",this.renderTargetBlurBuffer2.texture.generateMipmaps=!1,this.edgeDetectionMaterial=this.getEdgeDetectionMaterial(),this.renderTargetEdgeBuffer1=new s0(C,U,{type:g0}),this.renderTargetEdgeBuffer1.texture.name="OutlinePass.edge1",this.renderTargetEdgeBuffer1.texture.generateMipmaps=!1,this.renderTargetEdgeBuffer2=new s0(Math.round(C/2),Math.round(U/2),{type:g0}),this.renderTargetEdgeBuffer2.texture.name="OutlinePass.edge2",this.renderTargetEdgeBuffer2.texture.generateMipmaps=!1;let Y=4,Z=4;this.separableBlurMaterial1=this.getSeparableBlurMaterial(Y),this.separableBlurMaterial1.uniforms.texSize.value.set(C,U),this.separableBlurMaterial1.uniforms.kernelRadius.value=1,this.separableBlurMaterial2=this.getSeparableBlurMaterial(Z),this.separableBlurMaterial2.uniforms.texSize.value.set(Math.round(C/2),Math.round(U/2)),this.separableBlurMaterial2.uniforms.kernelRadius.value=Z,this.overlayMaterial=this.getOverlayMaterial();let X=m2;this.copyUniforms=u0.clone(X.uniforms),this.materialCopy=new T0({uniforms:this.copyUniforms,vertexShader:X.vertexShader,fragmentShader:X.fragmentShader,blending:XA,depthTest:!1,depthWrite:!1}),this.enabled=!0,this.needsSwap=!1,this._oldClearColor=new y1,this.oldClearAlpha=1,this.fsQuad=new $2(null),this.tempPulseColor1=new y1,this.tempPulseColor2=new y1,this.textureMatrix=new Y0;function E(H,$){let I=$.isPerspectiveCamera?"perspective":"orthographic";return H.replace(/DEPTH_TO_VIEW_Z/g,I+"DepthToViewZ")}}dispose(){this.renderTargetMaskBuffer.dispose(),this.renderTargetDepthBuffer.dispose(),this.renderTargetMaskDownSampleBuffer.dispose(),this.renderTargetBlurBuffer1.dispose(),this.renderTargetBlurBuffer2.dispose(),this.renderTargetEdgeBuffer1.dispose(),this.renderTargetEdgeBuffer2.dispose(),this.depthMaterial.dispose(),this.prepareMaskMaterial.dispose(),this.edgeDetectionMaterial.dispose(),this.separableBlurMaterial1.dispose(),this.separableBlurMaterial2.dispose(),this.overlayMaterial.dispose(),this.materialCopy.dispose(),this.fsQuad.dispose()}setSize(A,Q){this.renderTargetMaskBuffer.setSize(A,Q),this.renderTargetDepthBuffer.setSize(A,Q);let J=Math.round(A/this.downSampleRatio),K=Math.round(Q/this.downSampleRatio);this.renderTargetMaskDownSampleBuffer.setSize(J,K),this.renderTargetBlurBuffer1.setSize(J,K),this.renderTargetEdgeBuffer1.setSize(J,K),this.separableBlurMaterial1.uniforms.texSize.value.set(J,K),J=Math.round(J/2),K=Math.round(K/2),this.renderTargetBlurBuffer2.setSize(J,K),this.renderTargetEdgeBuffer2.setSize(J,K),this.separableBlurMaterial2.uniforms.texSize.value.set(J,K)}updateSelectionCache(){let A=this._selectionCache;function Q(J){if(J.isMesh)A.add(J)}A.clear();for(let J=0;J0){A.getClearColor(this._oldClearColor),this.oldClearAlpha=A.getClearAlpha();let U=A.autoClear;if(A.autoClear=!1,C)A.state.buffers.stencil.setTest(!1);A.setClearColor(16777215,1),this.updateSelectionCache(),this.changeVisibilityOfSelectedObjects(!1);let Y=this.renderScene.background;if(this.renderScene.background=null,this.renderScene.overrideMaterial=this.depthMaterial,A.setRenderTarget(this.renderTargetDepthBuffer),A.clear(),A.render(this.renderScene,this.renderCamera),this.changeVisibilityOfSelectedObjects(!0),this._visibilityCache.clear(),this.updateTextureMatrix(),this.changeVisibilityOfNonSelectedObjects(!1),this.renderScene.overrideMaterial=this.prepareMaskMaterial,this.prepareMaskMaterial.uniforms.cameraNearFar.value.set(this.renderCamera.near,this.renderCamera.far),this.prepareMaskMaterial.uniforms.depthTexture.value=this.renderTargetDepthBuffer.texture,this.prepareMaskMaterial.uniforms.textureMatrix.value=this.textureMatrix,A.setRenderTarget(this.renderTargetMaskBuffer),A.clear(),A.render(this.renderScene,this.renderCamera),this.renderScene.overrideMaterial=null,this.changeVisibilityOfNonSelectedObjects(!0),this._visibilityCache.clear(),this._selectionCache.clear(),this.renderScene.background=Y,this.fsQuad.material=this.materialCopy,this.copyUniforms.tDiffuse.value=this.renderTargetMaskBuffer.texture,A.setRenderTarget(this.renderTargetMaskDownSampleBuffer),A.clear(),this.fsQuad.render(A),this.tempPulseColor1.copy(this.visibleEdgeColor),this.tempPulseColor2.copy(this.hiddenEdgeColor),this.pulsePeriod>0){let Z=0.625+Math.cos(performance.now()*0.01/this.pulsePeriod)*0.75/2;this.tempPulseColor1.multiplyScalar(Z),this.tempPulseColor2.multiplyScalar(Z)}if(this.fsQuad.material=this.edgeDetectionMaterial,this.edgeDetectionMaterial.uniforms.maskTexture.value=this.renderTargetMaskDownSampleBuffer.texture,this.edgeDetectionMaterial.uniforms.texSize.value.set(this.renderTargetMaskDownSampleBuffer.width,this.renderTargetMaskDownSampleBuffer.height),this.edgeDetectionMaterial.uniforms.visibleEdgeColor.value=this.tempPulseColor1,this.edgeDetectionMaterial.uniforms.hiddenEdgeColor.value=this.tempPulseColor2,A.setRenderTarget(this.renderTargetEdgeBuffer1),A.clear(),this.fsQuad.render(A),this.fsQuad.material=this.separableBlurMaterial1,this.separableBlurMaterial1.uniforms.colorTexture.value=this.renderTargetEdgeBuffer1.texture,this.separableBlurMaterial1.uniforms.direction.value=WJ.BlurDirectionX,this.separableBlurMaterial1.uniforms.kernelRadius.value=this.edgeThickness,A.setRenderTarget(this.renderTargetBlurBuffer1),A.clear(),this.fsQuad.render(A),this.separableBlurMaterial1.uniforms.colorTexture.value=this.renderTargetBlurBuffer1.texture,this.separableBlurMaterial1.uniforms.direction.value=WJ.BlurDirectionY,A.setRenderTarget(this.renderTargetEdgeBuffer1),A.clear(),this.fsQuad.render(A),this.fsQuad.material=this.separableBlurMaterial2,this.separableBlurMaterial2.uniforms.colorTexture.value=this.renderTargetEdgeBuffer1.texture,this.separableBlurMaterial2.uniforms.direction.value=WJ.BlurDirectionX,A.setRenderTarget(this.renderTargetBlurBuffer2),A.clear(),this.fsQuad.render(A),this.separableBlurMaterial2.uniforms.colorTexture.value=this.renderTargetBlurBuffer2.texture,this.separableBlurMaterial2.uniforms.direction.value=WJ.BlurDirectionY,A.setRenderTarget(this.renderTargetEdgeBuffer2),A.clear(),this.fsQuad.render(A),this.fsQuad.material=this.overlayMaterial,this.overlayMaterial.uniforms.maskTexture.value=this.renderTargetMaskBuffer.texture,this.overlayMaterial.uniforms.edgeTexture1.value=this.renderTargetEdgeBuffer1.texture,this.overlayMaterial.uniforms.edgeTexture2.value=this.renderTargetEdgeBuffer2.texture,this.overlayMaterial.uniforms.patternTexture.value=this.patternTexture,this.overlayMaterial.uniforms.edgeStrength.value=this.edgeStrength,this.overlayMaterial.uniforms.edgeGlow.value=this.edgeGlow,this.overlayMaterial.uniforms.usePatternTexture.value=this.usePatternTexture,C)A.state.buffers.stencil.setTest(!0);A.setRenderTarget(J),this.fsQuad.render(A),A.setClearColor(this._oldClearColor,this.oldClearAlpha),A.autoClear=U}if(this.renderToScreen)this.fsQuad.material=this.materialCopy,this.copyUniforms.tDiffuse.value=J.texture,A.setRenderTarget(null),this.fsQuad.render(A)}getPrepareMaskMaterial(){return new T0({uniforms:{depthTexture:{value:null},cameraNearFar:{value:new p1(0.5,0.5)},textureMatrix:{value:null}},vertexShader:`#include - #include - - varying vec4 projTexCoord; - varying vec4 vPosition; - uniform mat4 textureMatrix; - - void main() { - - #include - #include - #include - #include - #include - - vPosition = mvPosition; - - vec4 worldPosition = vec4( transformed, 1.0 ); - - #ifdef USE_INSTANCING - - worldPosition = instanceMatrix * worldPosition; - - #endif - - worldPosition = modelMatrix * worldPosition; - - projTexCoord = textureMatrix * worldPosition; - - }`,fragmentShader:`#include - varying vec4 vPosition; - varying vec4 projTexCoord; - uniform sampler2D depthTexture; - uniform vec2 cameraNearFar; - - void main() { - - float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord )); - float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y ); - float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0; - gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0); - - }`})}getEdgeDetectionMaterial(){return new T0({uniforms:{maskTexture:{value:null},texSize:{value:new p1(0.5,0.5)},visibleEdgeColor:{value:new I1(1,1,1)},hiddenEdgeColor:{value:new I1(1,1,1)}},vertexShader:`varying vec2 vUv; - - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:`varying vec2 vUv; - - uniform sampler2D maskTexture; - uniform vec2 texSize; - uniform vec3 visibleEdgeColor; - uniform vec3 hiddenEdgeColor; - - void main() { - vec2 invSize = 1.0 / texSize; - vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize); - vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy); - vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy); - vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw); - vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw); - float diff1 = (c1.r - c2.r)*0.5; - float diff2 = (c3.r - c4.r)*0.5; - float d = length( vec2(diff1, diff2) ); - float a1 = min(c1.g, c2.g); - float a2 = min(c3.g, c4.g); - float visibilityFactor = min(a1, a2); - vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor; - gl_FragColor = vec4(edgeColor, 1.0) * vec4(d); - }`})}getSeparableBlurMaterial(A){return new T0({defines:{MAX_RADIUS:A},uniforms:{colorTexture:{value:null},texSize:{value:new p1(0.5,0.5)},direction:{value:new p1(0.5,0.5)},kernelRadius:{value:1}},vertexShader:`varying vec2 vUv; - - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:`#include - varying vec2 vUv; - uniform sampler2D colorTexture; - uniform vec2 texSize; - uniform vec2 direction; - uniform float kernelRadius; - - float gaussianPdf(in float x, in float sigma) { - return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma; - } - - void main() { - vec2 invSize = 1.0 / texSize; - float sigma = kernelRadius/2.0; - float weightSum = gaussianPdf(0.0, sigma); - vec4 diffuseSum = texture2D( colorTexture, vUv) * weightSum; - vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS); - vec2 uvOffset = delta; - for( int i = 1; i <= MAX_RADIUS; i ++ ) { - float x = kernelRadius * float(i) / float(MAX_RADIUS); - float w = gaussianPdf(x, sigma); - vec4 sample1 = texture2D( colorTexture, vUv + uvOffset); - vec4 sample2 = texture2D( colorTexture, vUv - uvOffset); - diffuseSum += ((sample1 + sample2) * w); - weightSum += (2.0 * w); - uvOffset += delta; - } - gl_FragColor = diffuseSum/weightSum; - }`})}getOverlayMaterial(){return new T0({uniforms:{maskTexture:{value:null},edgeTexture1:{value:null},edgeTexture2:{value:null},patternTexture:{value:null},edgeStrength:{value:1},edgeGlow:{value:1},usePatternTexture:{value:0}},vertexShader:`varying vec2 vUv; - - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:`varying vec2 vUv; - - uniform sampler2D maskTexture; - uniform sampler2D edgeTexture1; - uniform sampler2D edgeTexture2; - uniform sampler2D patternTexture; - uniform float edgeStrength; - uniform float edgeGlow; - uniform bool usePatternTexture; - - void main() { - vec4 edgeValue1 = texture2D(edgeTexture1, vUv); - vec4 edgeValue2 = texture2D(edgeTexture2, vUv); - vec4 maskColor = texture2D(maskTexture, vUv); - vec4 patternColor = texture2D(patternTexture, 6.0 * vUv); - float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5; - vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow; - vec4 finalColor = edgeStrength * maskColor.r * edgeValue; - if(usePatternTexture) - finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r); - gl_FragColor = finalColor; - }`,blending:U6,depthTest:!1,depthWrite:!1,transparent:!0})}}WJ.BlurDirectionX=new p1(1,0);WJ.BlurDirectionY=new p1(0,1);var OB={name:"SAOShader",defines:{NUM_SAMPLES:7,NUM_RINGS:4,DIFFUSE_TEXTURE:0,PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},tDiffuse:{value:null},tNormal:{value:null},size:{value:new p1(512,512)},cameraNear:{value:1},cameraFar:{value:100},cameraProjectionMatrix:{value:new Y0},cameraInverseProjectionMatrix:{value:new Y0},scale:{value:1},intensity:{value:0.1},bias:{value:0.5},minResolution:{value:0},kernelRadius:{value:100},randomSeed:{value:0}},vertexShader:` - - varying vec2 vUv; - - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:` - #include - - varying vec2 vUv; - - #if DIFFUSE_TEXTURE == 1 - uniform sampler2D tDiffuse; - #endif - - uniform highp sampler2D tDepth; - uniform highp sampler2D tNormal; - - uniform float cameraNear; - uniform float cameraFar; - uniform mat4 cameraProjectionMatrix; - uniform mat4 cameraInverseProjectionMatrix; - - uniform float scale; - uniform float intensity; - uniform float bias; - uniform float kernelRadius; - uniform float minResolution; - uniform vec2 size; - uniform float randomSeed; - - // RGBA depth - - #include - - vec4 getDefaultColor( const in vec2 screenPosition ) { - #if DIFFUSE_TEXTURE == 1 - return texture2D( tDiffuse, vUv ); - #else - return vec4( 1.0 ); - #endif - } - - float getDepth( const in vec2 screenPosition ) { - return texture2D( tDepth, screenPosition ).x; - } - - float getViewZ( const in float depth ) { - #if PERSPECTIVE_CAMERA == 1 - return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); - #else - return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); - #endif - } - - vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) { - float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3]; - vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 ); - clipPosition *= clipW; // unprojection. - - return ( cameraInverseProjectionMatrix * clipPosition ).xyz; - } - - vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPosition ) { - return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); - } - - float scaleDividedByCameraFar; - float minResolutionMultipliedByCameraFar; - - float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) { - vec3 viewDelta = sampleViewPosition - centerViewPosition; - float viewDistance = length( viewDelta ); - float scaledScreenDistance = scaleDividedByCameraFar * viewDistance; - - return max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - bias) / (1.0 + pow2( scaledScreenDistance ) ); - } - - // moving costly divides into consts - const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES ); - const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES ); - - float getAmbientOcclusion( const in vec3 centerViewPosition ) { - // precompute some variables require in getOcclusion. - scaleDividedByCameraFar = scale / cameraFar; - minResolutionMultipliedByCameraFar = minResolution * cameraFar; - vec3 centerViewNormal = getViewNormal( centerViewPosition, vUv ); - - // jsfiddle that shows sample pattern: https://jsfiddle.net/a16ff1p7/ - float angle = rand( vUv + randomSeed ) * PI2; - vec2 radius = vec2( kernelRadius * INV_NUM_SAMPLES ) / size; - vec2 radiusStep = radius; - - float occlusionSum = 0.0; - float weightSum = 0.0; - - for( int i = 0; i < NUM_SAMPLES; i ++ ) { - vec2 sampleUv = vUv + vec2( cos( angle ), sin( angle ) ) * radius; - radius += radiusStep; - angle += ANGLE_STEP; - - float sampleDepth = getDepth( sampleUv ); - if( sampleDepth >= ( 1.0 - EPSILON ) ) { - continue; - } - - float sampleViewZ = getViewZ( sampleDepth ); - vec3 sampleViewPosition = getViewPosition( sampleUv, sampleDepth, sampleViewZ ); - occlusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition ); - weightSum += 1.0; - } - - if( weightSum == 0.0 ) discard; - - return occlusionSum * ( intensity / weightSum ); - } - - void main() { - float centerDepth = getDepth( vUv ); - if( centerDepth >= ( 1.0 - EPSILON ) ) { - discard; - } - - float centerViewZ = getViewZ( centerDepth ); - vec3 viewPosition = getViewPosition( vUv, centerDepth, centerViewZ ); - - float ambientOcclusion = getAmbientOcclusion( viewPosition ); - - gl_FragColor = getDefaultColor( vUv ); - gl_FragColor.xyz *= 1.0 - ambientOcclusion; - }`};var W7={name:"DepthLimitedBlurShader",defines:{KERNEL_RADIUS:4,DEPTH_PACKING:1,PERSPECTIVE_CAMERA:1},uniforms:{tDiffuse:{value:null},size:{value:new p1(512,512)},sampleUvOffsets:{value:[new p1(0,0)]},sampleWeights:{value:[1]},tDepth:{value:null},cameraNear:{value:10},cameraFar:{value:1000},depthCutoff:{value:10}},vertexShader:` - - #include - - uniform vec2 size; - - varying vec2 vUv; - varying vec2 vInvSize; - - void main() { - vUv = uv; - vInvSize = 1.0 / size; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:` - - #include - #include - - uniform sampler2D tDiffuse; - uniform sampler2D tDepth; - - uniform float cameraNear; - uniform float cameraFar; - uniform float depthCutoff; - - uniform vec2 sampleUvOffsets[ KERNEL_RADIUS + 1 ]; - uniform float sampleWeights[ KERNEL_RADIUS + 1 ]; - - varying vec2 vUv; - varying vec2 vInvSize; - - float getDepth( const in vec2 screenPosition ) { - #if DEPTH_PACKING == 1 - return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) ); - #else - return texture2D( tDepth, screenPosition ).x; - #endif - } - - float getViewZ( const in float depth ) { - #if PERSPECTIVE_CAMERA == 1 - return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); - #else - return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); - #endif - } - - void main() { - float depth = getDepth( vUv ); - if( depth >= ( 1.0 - EPSILON ) ) { - discard; - } - - float centerViewZ = -getViewZ( depth ); - bool rBreak = false, lBreak = false; - - float weightSum = sampleWeights[0]; - vec4 diffuseSum = texture2D( tDiffuse, vUv ) * weightSum; - - for( int i = 1; i <= KERNEL_RADIUS; i ++ ) { - - float sampleWeight = sampleWeights[i]; - vec2 sampleUvOffset = sampleUvOffsets[i] * vInvSize; - - vec2 sampleUv = vUv + sampleUvOffset; - float viewZ = -getViewZ( getDepth( sampleUv ) ); - - if( abs( viewZ - centerViewZ ) > depthCutoff ) rBreak = true; - - if( ! rBreak ) { - diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight; - weightSum += sampleWeight; - } - - sampleUv = vUv - sampleUvOffset; - viewZ = -getViewZ( getDepth( sampleUv ) ); - - if( abs( viewZ - centerViewZ ) > depthCutoff ) lBreak = true; - - if( ! lBreak ) { - diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight; - weightSum += sampleWeight; - } - - } - - gl_FragColor = diffuseSum / weightSum; - }`},NB={createSampleWeights:function(A,Q){let J=[];for(let K=0;K<=A;K++)J.push(JX1(K,Q));return J},createSampleOffsets:function(A,Q){let J=[];for(let K=0;K<=A;K++)J.push(Q.clone().multiplyScalar(K));return J},configure:function(A,Q,J,K){A.defines.KERNEL_RADIUS=Q,A.uniforms.sampleUvOffsets.value=NB.createSampleOffsets(Q,K),A.uniforms.sampleWeights.value=NB.createSampleWeights(Q,J),A.needsUpdate=!0}};function JX1(A,Q){return Math.exp(-(A*A)/(2*(Q*Q)))/(Math.sqrt(2*Math.PI)*Q)}class EW extends B2{constructor(A,Q,J=new p1(256,256)){super();this.scene=A,this.camera=Q,this.clear=!0,this.needsSwap=!1,this.originalClearColor=new y1,this._oldClearColor=new y1,this.oldClearAlpha=1,this.params={output:0,saoBias:0.5,saoIntensity:0.18,saoScale:1,saoKernelRadius:100,saoMinResolution:0,saoBlur:!0,saoBlurRadius:8,saoBlurStdDev:4,saoBlurDepthCutoff:0.01},this.resolution=new p1(J.x,J.y),this.saoRenderTarget=new s0(this.resolution.x,this.resolution.y,{type:g0}),this.blurIntermediateRenderTarget=this.saoRenderTarget.clone();let K=new E6;K.format=x9,K.type=C9,this.normalRenderTarget=new s0(this.resolution.x,this.resolution.y,{minFilter:YA,magFilter:YA,type:g0,depthTexture:K}),this.normalMaterial=new B9,this.normalMaterial.blending=XA,this.saoMaterial=new T0({defines:Object.assign({},OB.defines),fragmentShader:OB.fragmentShader,vertexShader:OB.vertexShader,uniforms:u0.clone(OB.uniforms)}),this.saoMaterial.defines.PERSPECTIVE_CAMERA=this.camera.isPerspectiveCamera?1:0,this.saoMaterial.uniforms.tDepth.value=K,this.saoMaterial.uniforms.tNormal.value=this.normalRenderTarget.texture,this.saoMaterial.uniforms.size.value.set(this.resolution.x,this.resolution.y),this.saoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.saoMaterial.uniforms.cameraProjectionMatrix.value=this.camera.projectionMatrix,this.saoMaterial.blending=XA,this.vBlurMaterial=new T0({uniforms:u0.clone(W7.uniforms),defines:Object.assign({},W7.defines),vertexShader:W7.vertexShader,fragmentShader:W7.fragmentShader}),this.vBlurMaterial.defines.DEPTH_PACKING=0,this.vBlurMaterial.defines.PERSPECTIVE_CAMERA=this.camera.isPerspectiveCamera?1:0,this.vBlurMaterial.uniforms.tDiffuse.value=this.saoRenderTarget.texture,this.vBlurMaterial.uniforms.tDepth.value=K,this.vBlurMaterial.uniforms.size.value.set(this.resolution.x,this.resolution.y),this.vBlurMaterial.blending=XA,this.hBlurMaterial=new T0({uniforms:u0.clone(W7.uniforms),defines:Object.assign({},W7.defines),vertexShader:W7.vertexShader,fragmentShader:W7.fragmentShader}),this.hBlurMaterial.defines.DEPTH_PACKING=0,this.hBlurMaterial.defines.PERSPECTIVE_CAMERA=this.camera.isPerspectiveCamera?1:0,this.hBlurMaterial.uniforms.tDiffuse.value=this.blurIntermediateRenderTarget.texture,this.hBlurMaterial.uniforms.tDepth.value=K,this.hBlurMaterial.uniforms.size.value.set(this.resolution.x,this.resolution.y),this.hBlurMaterial.blending=XA,this.materialCopy=new T0({uniforms:u0.clone(m2.uniforms),vertexShader:m2.vertexShader,fragmentShader:m2.fragmentShader,blending:XA}),this.materialCopy.transparent=!0,this.materialCopy.depthTest=!1,this.materialCopy.depthWrite=!1,this.materialCopy.blending=y2,this.materialCopy.blendSrc=o5,this.materialCopy.blendDst=g6,this.materialCopy.blendEquation=X8,this.materialCopy.blendSrcAlpha=b6,this.materialCopy.blendDstAlpha=g6,this.materialCopy.blendEquationAlpha=X8,this.fsQuad=new $2(null)}render(A,Q,J){if(this.renderToScreen)this.materialCopy.blending=XA,this.materialCopy.uniforms.tDiffuse.value=J.texture,this.materialCopy.needsUpdate=!0,this.renderPass(A,this.materialCopy,null);A.getClearColor(this._oldClearColor),this.oldClearAlpha=A.getClearAlpha();let K=A.autoClear;A.autoClear=!1,this.saoMaterial.uniforms.bias.value=this.params.saoBias,this.saoMaterial.uniforms.intensity.value=this.params.saoIntensity,this.saoMaterial.uniforms.scale.value=this.params.saoScale,this.saoMaterial.uniforms.kernelRadius.value=this.params.saoKernelRadius,this.saoMaterial.uniforms.minResolution.value=this.params.saoMinResolution,this.saoMaterial.uniforms.cameraNear.value=this.camera.near,this.saoMaterial.uniforms.cameraFar.value=this.camera.far;let C=this.params.saoBlurDepthCutoff*(this.camera.far-this.camera.near);if(this.vBlurMaterial.uniforms.depthCutoff.value=C,this.hBlurMaterial.uniforms.depthCutoff.value=C,this.vBlurMaterial.uniforms.cameraNear.value=this.camera.near,this.vBlurMaterial.uniforms.cameraFar.value=this.camera.far,this.hBlurMaterial.uniforms.cameraNear.value=this.camera.near,this.hBlurMaterial.uniforms.cameraFar.value=this.camera.far,this.params.saoBlurRadius=Math.floor(this.params.saoBlurRadius),this.prevStdDev!==this.params.saoBlurStdDev||this.prevNumSamples!==this.params.saoBlurRadius)NB.configure(this.vBlurMaterial,this.params.saoBlurRadius,this.params.saoBlurStdDev,new p1(0,1)),NB.configure(this.hBlurMaterial,this.params.saoBlurRadius,this.params.saoBlurStdDev,new p1(1,0)),this.prevStdDev=this.params.saoBlurStdDev,this.prevNumSamples=this.params.saoBlurRadius;if(this.renderOverride(A,this.normalMaterial,this.normalRenderTarget,7829503,1),this.renderPass(A,this.saoMaterial,this.saoRenderTarget,16777215,1),this.params.saoBlur)this.renderPass(A,this.vBlurMaterial,this.blurIntermediateRenderTarget,16777215,1),this.renderPass(A,this.hBlurMaterial,this.saoRenderTarget,16777215,1);let U=this.materialCopy;if(this.params.output===EW.OUTPUT.Normal)this.materialCopy.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.materialCopy.needsUpdate=!0;else this.materialCopy.uniforms.tDiffuse.value=this.saoRenderTarget.texture,this.materialCopy.needsUpdate=!0;if(this.params.output===EW.OUTPUT.Default)U.blending=y2;else U.blending=XA;this.renderPass(A,U,this.renderToScreen?null:J),A.setClearColor(this._oldClearColor,this.oldClearAlpha),A.autoClear=K}renderPass(A,Q,J,K,C){A.getClearColor(this.originalClearColor);let U=A.getClearAlpha(),Y=A.autoClear;if(A.setRenderTarget(J),A.autoClear=!1,K!==void 0&&K!==null)A.setClearColor(K),A.setClearAlpha(C||0),A.clear();this.fsQuad.material=Q,this.fsQuad.render(A),A.autoClear=Y,A.setClearColor(this.originalClearColor),A.setClearAlpha(U)}renderOverride(A,Q,J,K,C){A.getClearColor(this.originalClearColor);let U=A.getClearAlpha(),Y=A.autoClear;if(A.setRenderTarget(J),A.autoClear=!1,K=Q.clearColor||K,C=Q.clearAlpha||C,K!==void 0&&K!==null)A.setClearColor(K),A.setClearAlpha(C||0),A.clear();this.scene.overrideMaterial=Q,A.render(this.scene,this.camera),this.scene.overrideMaterial=null,A.autoClear=Y,A.setClearColor(this.originalClearColor),A.setClearAlpha(U)}setSize(A,Q){this.saoRenderTarget.setSize(A,Q),this.blurIntermediateRenderTarget.setSize(A,Q),this.normalRenderTarget.setSize(A,Q),this.saoMaterial.uniforms.size.value.set(A,Q),this.saoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.saoMaterial.uniforms.cameraProjectionMatrix.value=this.camera.projectionMatrix,this.saoMaterial.needsUpdate=!0,this.vBlurMaterial.uniforms.size.value.set(A,Q),this.vBlurMaterial.needsUpdate=!0,this.hBlurMaterial.uniforms.size.value.set(A,Q),this.hBlurMaterial.needsUpdate=!0}dispose(){this.saoRenderTarget.dispose(),this.blurIntermediateRenderTarget.dispose(),this.normalRenderTarget.dispose(),this.normalMaterial.dispose(),this.saoMaterial.dispose(),this.vBlurMaterial.dispose(),this.hBlurMaterial.dispose(),this.materialCopy.dispose(),this.fsQuad.dispose()}}EW.OUTPUT={Default:0,SAO:1,Normal:2};var KX1={name:"SMAAEdgesShader",defines:{SMAA_THRESHOLD:"0.1"},uniforms:{tDiffuse:{value:null},resolution:{value:new p1(0.0009765625,0.001953125)}},vertexShader:` - - uniform vec2 resolution; - - varying vec2 vUv; - varying vec4 vOffset[ 3 ]; - - void SMAAEdgeDetectionVS( vec2 texcoord ) { - vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component - vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component - vOffset[ 2 ] = texcoord.xyxy + resolution.xyxy * vec4( -2.0, 0.0, 0.0, 2.0 ); // WebGL port note: Changed sign in W component - } - - void main() { - - vUv = uv; - - SMAAEdgeDetectionVS( vUv ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform sampler2D tDiffuse; - - varying vec2 vUv; - varying vec4 vOffset[ 3 ]; - - vec4 SMAAColorEdgeDetectionPS( vec2 texcoord, vec4 offset[3], sampler2D colorTex ) { - vec2 threshold = vec2( SMAA_THRESHOLD, SMAA_THRESHOLD ); - - // Calculate color deltas: - vec4 delta; - vec3 C = texture2D( colorTex, texcoord ).rgb; - - vec3 Cleft = texture2D( colorTex, offset[0].xy ).rgb; - vec3 t = abs( C - Cleft ); - delta.x = max( max( t.r, t.g ), t.b ); - - vec3 Ctop = texture2D( colorTex, offset[0].zw ).rgb; - t = abs( C - Ctop ); - delta.y = max( max( t.r, t.g ), t.b ); - - // We do the usual threshold: - vec2 edges = step( threshold, delta.xy ); - - // Then discard if there is no edge: - if ( dot( edges, vec2( 1.0, 1.0 ) ) == 0.0 ) - discard; - - // Calculate right and bottom deltas: - vec3 Cright = texture2D( colorTex, offset[1].xy ).rgb; - t = abs( C - Cright ); - delta.z = max( max( t.r, t.g ), t.b ); - - vec3 Cbottom = texture2D( colorTex, offset[1].zw ).rgb; - t = abs( C - Cbottom ); - delta.w = max( max( t.r, t.g ), t.b ); - - // Calculate the maximum delta in the direct neighborhood: - float maxDelta = max( max( max( delta.x, delta.y ), delta.z ), delta.w ); - - // Calculate left-left and top-top deltas: - vec3 Cleftleft = texture2D( colorTex, offset[2].xy ).rgb; - t = abs( C - Cleftleft ); - delta.z = max( max( t.r, t.g ), t.b ); - - vec3 Ctoptop = texture2D( colorTex, offset[2].zw ).rgb; - t = abs( C - Ctoptop ); - delta.w = max( max( t.r, t.g ), t.b ); - - // Calculate the final maximum delta: - maxDelta = max( max( maxDelta, delta.z ), delta.w ); - - // Local contrast adaptation in action: - edges.xy *= step( 0.5 * maxDelta, delta.xy ); - - return vec4( edges, 0.0, 0.0 ); - } - - void main() { - - gl_FragColor = SMAAColorEdgeDetectionPS( vUv, vOffset, tDiffuse ); - - }`},CX1={name:"SMAAWeightsShader",defines:{SMAA_MAX_SEARCH_STEPS:"8",SMAA_AREATEX_MAX_DISTANCE:"16",SMAA_AREATEX_PIXEL_SIZE:"( 1.0 / vec2( 160.0, 560.0 ) )",SMAA_AREATEX_SUBTEX_SIZE:"( 1.0 / 7.0 )"},uniforms:{tDiffuse:{value:null},tArea:{value:null},tSearch:{value:null},resolution:{value:new p1(0.0009765625,0.001953125)}},vertexShader:` - - uniform vec2 resolution; - - varying vec2 vUv; - varying vec4 vOffset[ 3 ]; - varying vec2 vPixcoord; - - void SMAABlendingWeightCalculationVS( vec2 texcoord ) { - vPixcoord = texcoord / resolution; - - // We will use these offsets for the searches later on (see @PSEUDO_GATHER4): - vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.25, 0.125, 1.25, 0.125 ); // WebGL port note: Changed sign in Y and W components - vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.125, 0.25, -0.125, -1.25 ); // WebGL port note: Changed sign in Y and W components - - // And these for the searches, they indicate the ends of the loops: - vOffset[ 2 ] = vec4( vOffset[ 0 ].xz, vOffset[ 1 ].yw ) + vec4( -2.0, 2.0, -2.0, 2.0 ) * resolution.xxyy * float( SMAA_MAX_SEARCH_STEPS ); - - } - - void main() { - - vUv = uv; - - SMAABlendingWeightCalculationVS( vUv ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - #define SMAASampleLevelZeroOffset( tex, coord, offset ) texture2D( tex, coord + float( offset ) * resolution, 0.0 ) - - uniform sampler2D tDiffuse; - uniform sampler2D tArea; - uniform sampler2D tSearch; - uniform vec2 resolution; - - varying vec2 vUv; - varying vec4 vOffset[3]; - varying vec2 vPixcoord; - - #if __VERSION__ == 100 - vec2 round( vec2 x ) { - return sign( x ) * floor( abs( x ) + 0.5 ); - } - #endif - - float SMAASearchLength( sampler2D searchTex, vec2 e, float bias, float scale ) { - // Not required if searchTex accesses are set to point: - // float2 SEARCH_TEX_PIXEL_SIZE = 1.0 / float2(66.0, 33.0); - // e = float2(bias, 0.0) + 0.5 * SEARCH_TEX_PIXEL_SIZE + - // e * float2(scale, 1.0) * float2(64.0, 32.0) * SEARCH_TEX_PIXEL_SIZE; - e.r = bias + e.r * scale; - return 255.0 * texture2D( searchTex, e, 0.0 ).r; - } - - float SMAASearchXLeft( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { - /** - * @PSEUDO_GATHER4 - * This texcoord has been offset by (-0.25, -0.125) in the vertex shader to - * sample between edge, thus fetching four edges in a row. - * Sampling with different offsets in each direction allows to disambiguate - * which edges are active from the four fetched ones. - */ - vec2 e = vec2( 0.0, 1.0 ); - - for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for - e = texture2D( edgesTex, texcoord, 0.0 ).rg; - texcoord -= vec2( 2.0, 0.0 ) * resolution; - if ( ! ( texcoord.x > end && e.g > 0.8281 && e.r == 0.0 ) ) break; - } - - // We correct the previous (-0.25, -0.125) offset we applied: - texcoord.x += 0.25 * resolution.x; - - // The searches are bias by 1, so adjust the coords accordingly: - texcoord.x += resolution.x; - - // Disambiguate the length added by the last step: - texcoord.x += 2.0 * resolution.x; // Undo last step - texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5); - - return texcoord.x; - } - - float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { - vec2 e = vec2( 0.0, 1.0 ); - - for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for - e = texture2D( edgesTex, texcoord, 0.0 ).rg; - texcoord += vec2( 2.0, 0.0 ) * resolution; - if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break; - } - - texcoord.x -= 0.25 * resolution.x; - texcoord.x -= resolution.x; - texcoord.x -= 2.0 * resolution.x; - texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 ); - - return texcoord.x; - } - - float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { - vec2 e = vec2( 1.0, 0.0 ); - - for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for - e = texture2D( edgesTex, texcoord, 0.0 ).rg; - texcoord += vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign - if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break; - } - - texcoord.y -= 0.25 * resolution.y; // WebGL port note: Changed sign - texcoord.y -= resolution.y; // WebGL port note: Changed sign - texcoord.y -= 2.0 * resolution.y; // WebGL port note: Changed sign - texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 ); // WebGL port note: Changed sign - - return texcoord.y; - } - - float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { - vec2 e = vec2( 1.0, 0.0 ); - - for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for - e = texture2D( edgesTex, texcoord, 0.0 ).rg; - texcoord -= vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign - if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break; - } - - texcoord.y += 0.25 * resolution.y; // WebGL port note: Changed sign - texcoord.y += resolution.y; // WebGL port note: Changed sign - texcoord.y += 2.0 * resolution.y; // WebGL port note: Changed sign - texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 ); // WebGL port note: Changed sign - - return texcoord.y; - } - - vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) { - // Rounding prevents precision errors of bilinear filtering: - vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist; - - // We do a scale and bias for mapping to texel space: - texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE ); - - // Move to proper place, according to the subpixel offset: - texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset; - - return texture2D( areaTex, texcoord, 0.0 ).rg; - } - - vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) { - vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 ); - - vec2 e = texture2D( edgesTex, texcoord ).rg; - - if ( e.g > 0.0 ) { // Edge at north - vec2 d; - - // Find the distance to the left: - vec2 coords; - coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x ); - coords.y = offset[ 1 ].y; // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET) - d.x = coords.x; - - // Now fetch the left crossing edges, two at a time using bilinear - // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to - // discern what value each edge has: - float e1 = texture2D( edgesTex, coords, 0.0 ).r; - - // Find the distance to the right: - coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y ); - d.y = coords.x; - - // We want the distances to be in pixel units (doing this here allow to - // better interleave arithmetic and memory accesses): - d = d / resolution.x - pixcoord.x; - - // SMAAArea below needs a sqrt, as the areas texture is compressed - // quadratically: - vec2 sqrt_d = sqrt( abs( d ) ); - - // Fetch the right crossing edges: - coords.y -= 1.0 * resolution.y; // WebGL port note: Added - float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r; - - // Ok, we know how this pattern looks like, now it is time for getting - // the actual area: - weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) ); - } - - if ( e.r > 0.0 ) { // Edge at west - vec2 d; - - // Find the distance to the top: - vec2 coords; - - coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z ); - coords.x = offset[ 0 ].x; // offset[1].x = texcoord.x - 0.25 * resolution.x; - d.x = coords.y; - - // Fetch the top crossing edges: - float e1 = texture2D( edgesTex, coords, 0.0 ).g; - - // Find the distance to the bottom: - coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w ); - d.y = coords.y; - - // We want the distances to be in pixel units: - d = d / resolution.y - pixcoord.y; - - // SMAAArea below needs a sqrt, as the areas texture is compressed - // quadratically: - vec2 sqrt_d = sqrt( abs( d ) ); - - // Fetch the bottom crossing edges: - coords.y -= 1.0 * resolution.y; // WebGL port note: Added - float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g; - - // Get the area for this direction: - weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) ); - } - - return weights; - } - - void main() { - - gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) ); - - }`},YX1={name:"SMAABlendShader",uniforms:{tDiffuse:{value:null},tColor:{value:null},resolution:{value:new p1(0.0009765625,0.001953125)}},vertexShader:` - - uniform vec2 resolution; - - varying vec2 vUv; - varying vec4 vOffset[ 2 ]; - - void SMAANeighborhoodBlendingVS( vec2 texcoord ) { - vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component - vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component - } - - void main() { - - vUv = uv; - - SMAANeighborhoodBlendingVS( vUv ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform sampler2D tDiffuse; - uniform sampler2D tColor; - uniform vec2 resolution; - - varying vec2 vUv; - varying vec4 vOffset[ 2 ]; - - vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) { - // Fetch the blending weights for current pixel: - vec4 a; - a.xz = texture2D( blendTex, texcoord ).xz; - a.y = texture2D( blendTex, offset[ 1 ].zw ).g; - a.w = texture2D( blendTex, offset[ 1 ].xy ).a; - - // Is there any blending weight with a value greater than 0.0? - if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) { - return texture2D( colorTex, texcoord, 0.0 ); - } else { - // Up to 4 lines can be crossing a pixel (one through each edge). We - // favor blending by choosing the line with the maximum weight for each - // direction: - vec2 offset; - offset.x = a.a > a.b ? a.a : -a.b; // left vs. right - offset.y = a.g > a.r ? -a.g : a.r; // top vs. bottom // WebGL port note: Changed signs - - // Then we go in the direction that has the maximum weight: - if ( abs( offset.x ) > abs( offset.y )) { // horizontal vs. vertical - offset.y = 0.0; - } else { - offset.x = 0.0; - } - - // Fetch the opposite color and lerp by hand: - vec4 C = texture2D( colorTex, texcoord, 0.0 ); - texcoord += sign( offset ) * resolution; - vec4 Cop = texture2D( colorTex, texcoord, 0.0 ); - float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y ); - - // WebGL port note: Added gamma correction - C.xyz = pow(C.xyz, vec3(2.2)); - Cop.xyz = pow(Cop.xyz, vec3(2.2)); - vec4 mixed = mix(C, Cop, s); - mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2)); - - return mixed; - } - } - - void main() { - - gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse ); - - }`};var LB={name:"SSAOShader",defines:{PERSPECTIVE_CAMERA:1,KERNEL_SIZE:32},uniforms:{tNormal:{value:null},tDepth:{value:null},tNoise:{value:null},kernel:{value:null},cameraNear:{value:null},cameraFar:{value:null},resolution:{value:new p1},cameraProjectionMatrix:{value:new Y0},cameraInverseProjectionMatrix:{value:new Y0},kernelRadius:{value:8},minDistance:{value:0.005},maxDistance:{value:0.05}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - uniform highp sampler2D tNormal; - uniform highp sampler2D tDepth; - uniform sampler2D tNoise; - - uniform vec3 kernel[ KERNEL_SIZE ]; - - uniform vec2 resolution; - - uniform float cameraNear; - uniform float cameraFar; - uniform mat4 cameraProjectionMatrix; - uniform mat4 cameraInverseProjectionMatrix; - - uniform float kernelRadius; - uniform float minDistance; // avoid artifacts caused by neighbour fragments with minimal depth difference - uniform float maxDistance; // avoid the influence of fragments which are too far away - - varying vec2 vUv; - - #include - - float getDepth( const in vec2 screenPosition ) { - - return texture2D( tDepth, screenPosition ).x; - - } - - float getLinearDepth( const in vec2 screenPosition ) { - - #if PERSPECTIVE_CAMERA == 1 - - float fragCoordZ = texture2D( tDepth, screenPosition ).x; - float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); - return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); - - #else - - return texture2D( tDepth, screenPosition ).x; - - #endif - - } - - float getViewZ( const in float depth ) { - - #if PERSPECTIVE_CAMERA == 1 - - return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); - - #else - - return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); - - #endif - - } - - vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) { - - float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3]; - - vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 ); - - clipPosition *= clipW; // unprojection. - - return ( cameraInverseProjectionMatrix * clipPosition ).xyz; - - } - - vec3 getViewNormal( const in vec2 screenPosition ) { - - return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); - - } - - void main() { - - float depth = getDepth( vUv ); - - if ( depth == 1.0 ) { - - gl_FragColor = vec4( 1.0 ); // don't influence background - - } else { - - float viewZ = getViewZ( depth ); - - vec3 viewPosition = getViewPosition( vUv, depth, viewZ ); - vec3 viewNormal = getViewNormal( vUv ); - - vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 ); - vec3 random = vec3( texture2D( tNoise, vUv * noiseScale ).r ); - - // compute matrix used to reorient a kernel vector - - vec3 tangent = normalize( random - viewNormal * dot( random, viewNormal ) ); - vec3 bitangent = cross( viewNormal, tangent ); - mat3 kernelMatrix = mat3( tangent, bitangent, viewNormal ); - - float occlusion = 0.0; - - for ( int i = 0; i < KERNEL_SIZE; i ++ ) { - - vec3 sampleVector = kernelMatrix * kernel[ i ]; // reorient sample vector in view space - vec3 samplePoint = viewPosition + ( sampleVector * kernelRadius ); // calculate sample point - - vec4 samplePointNDC = cameraProjectionMatrix * vec4( samplePoint, 1.0 ); // project point and calculate NDC - samplePointNDC /= samplePointNDC.w; - - vec2 samplePointUv = samplePointNDC.xy * 0.5 + 0.5; // compute uv coordinates - - float realDepth = getLinearDepth( samplePointUv ); // get linear depth from depth texture - float sampleDepth = viewZToOrthographicDepth( samplePoint.z, cameraNear, cameraFar ); // compute linear depth of the sample view Z value - float delta = sampleDepth - realDepth; - - if ( delta > minDistance && delta < maxDistance ) { // if fragment is before sample point, increase occlusion - - occlusion += 1.0; - - } - - } - - occlusion = clamp( occlusion / float( KERNEL_SIZE ), 0.0, 1.0 ); - - gl_FragColor = vec4( vec3( 1.0 - occlusion ), 1.0 ); - - } - - }`},FB={name:"SSAODepthShader",defines:{PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null}},vertexShader:`varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:`uniform sampler2D tDepth; - - uniform float cameraNear; - uniform float cameraFar; - - varying vec2 vUv; - - #include - - float getLinearDepth( const in vec2 screenPosition ) { - - #if PERSPECTIVE_CAMERA == 1 - - float fragCoordZ = texture2D( tDepth, screenPosition ).x; - float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); - return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); - - #else - - return texture2D( tDepth, screenPosition ).x; - - #endif - - } - - void main() { - - float depth = getLinearDepth( vUv ); - gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); - - }`},RB={name:"SSAOBlurShader",uniforms:{tDiffuse:{value:null},resolution:{value:new p1}},vertexShader:`varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:`uniform sampler2D tDiffuse; - - uniform vec2 resolution; - - varying vec2 vUv; - - void main() { - - vec2 texelSize = ( 1.0 / resolution ); - float result = 0.0; - - for ( int i = - 2; i <= 2; i ++ ) { - - for ( int j = - 2; j <= 2; j ++ ) { - - vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize; - result += texture2D( tDiffuse, vUv + offset ).r; - - } - - } - - gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 ); - - }`};class IJ extends B2{constructor(A,Q,J,K,C=32){super();this.width=J!==void 0?J:512,this.height=K!==void 0?K:512,this.clear=!0,this.needsSwap=!1,this.camera=Q,this.scene=A,this.kernelRadius=8,this.kernel=[],this.noiseTexture=null,this.output=0,this.minDistance=0.005,this.maxDistance=0.1,this._visibilityCache=/*@__PURE__*/new Map,this.generateSampleKernel(C),this.generateRandomKernelRotations();let U=new E6;U.format=x9,U.type=C9,this.normalRenderTarget=new s0(this.width,this.height,{minFilter:YA,magFilter:YA,type:g0,depthTexture:U}),this.ssaoRenderTarget=new s0(this.width,this.height,{type:g0}),this.blurRenderTarget=this.ssaoRenderTarget.clone(),this.ssaoMaterial=new T0({defines:Object.assign({},LB.defines),uniforms:u0.clone(LB.uniforms),vertexShader:LB.vertexShader,fragmentShader:LB.fragmentShader,blending:XA}),this.ssaoMaterial.defines.KERNEL_SIZE=C,this.ssaoMaterial.uniforms.tNormal.value=this.normalRenderTarget.texture,this.ssaoMaterial.uniforms.tDepth.value=this.normalRenderTarget.depthTexture,this.ssaoMaterial.uniforms.tNoise.value=this.noiseTexture,this.ssaoMaterial.uniforms.kernel.value=this.kernel,this.ssaoMaterial.uniforms.cameraNear.value=this.camera.near,this.ssaoMaterial.uniforms.cameraFar.value=this.camera.far,this.ssaoMaterial.uniforms.resolution.value.set(this.width,this.height),this.ssaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssaoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.normalMaterial=new B9,this.normalMaterial.blending=XA,this.blurMaterial=new T0({defines:Object.assign({},RB.defines),uniforms:u0.clone(RB.uniforms),vertexShader:RB.vertexShader,fragmentShader:RB.fragmentShader}),this.blurMaterial.uniforms.tDiffuse.value=this.ssaoRenderTarget.texture,this.blurMaterial.uniforms.resolution.value.set(this.width,this.height),this.depthRenderMaterial=new T0({defines:Object.assign({},FB.defines),uniforms:u0.clone(FB.uniforms),vertexShader:FB.vertexShader,fragmentShader:FB.fragmentShader,blending:XA}),this.depthRenderMaterial.uniforms.tDepth.value=this.normalRenderTarget.depthTexture,this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this.copyMaterial=new T0({uniforms:u0.clone(m2.uniforms),vertexShader:m2.vertexShader,fragmentShader:m2.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blendSrc:o5,blendDst:g6,blendEquation:X8,blendSrcAlpha:b6,blendDstAlpha:g6,blendEquationAlpha:X8}),this.fsQuad=new $2(null),this.originalClearColor=new y1}dispose(){this.normalRenderTarget.dispose(),this.ssaoRenderTarget.dispose(),this.blurRenderTarget.dispose(),this.normalMaterial.dispose(),this.blurMaterial.dispose(),this.copyMaterial.dispose(),this.depthRenderMaterial.dispose(),this.fsQuad.dispose()}render(A,Q,J){switch(this.overrideVisibility(),this.renderOverride(A,this.normalMaterial,this.normalRenderTarget,7829503,1),this.restoreVisibility(),this.ssaoMaterial.uniforms.kernelRadius.value=this.kernelRadius,this.ssaoMaterial.uniforms.minDistance.value=this.minDistance,this.ssaoMaterial.uniforms.maxDistance.value=this.maxDistance,this.renderPass(A,this.ssaoMaterial,this.ssaoRenderTarget),this.renderPass(A,this.blurMaterial,this.blurRenderTarget),this.output){case IJ.OUTPUT.SSAO:this.copyMaterial.uniforms.tDiffuse.value=this.ssaoRenderTarget.texture,this.copyMaterial.blending=XA,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:J);break;case IJ.OUTPUT.Blur:this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget.texture,this.copyMaterial.blending=XA,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:J);break;case IJ.OUTPUT.Depth:this.renderPass(A,this.depthRenderMaterial,this.renderToScreen?null:J);break;case IJ.OUTPUT.Normal:this.copyMaterial.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.copyMaterial.blending=XA,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:J);break;case IJ.OUTPUT.Default:this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget.texture,this.copyMaterial.blending=y2,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:J);break;default:console.warn("THREE.SSAOPass: Unknown output type.")}}renderPass(A,Q,J,K,C){A.getClearColor(this.originalClearColor);let U=A.getClearAlpha(),Y=A.autoClear;if(A.setRenderTarget(J),A.autoClear=!1,K!==void 0&&K!==null)A.setClearColor(K),A.setClearAlpha(C||0),A.clear();this.fsQuad.material=Q,this.fsQuad.render(A),A.autoClear=Y,A.setClearColor(this.originalClearColor),A.setClearAlpha(U)}renderOverride(A,Q,J,K,C){A.getClearColor(this.originalClearColor);let U=A.getClearAlpha(),Y=A.autoClear;if(A.setRenderTarget(J),A.autoClear=!1,K=Q.clearColor||K,C=Q.clearAlpha||C,K!==void 0&&K!==null)A.setClearColor(K),A.setClearAlpha(C||0),A.clear();this.scene.overrideMaterial=Q,A.render(this.scene,this.camera),this.scene.overrideMaterial=null,A.autoClear=Y,A.setClearColor(this.originalClearColor),A.setClearAlpha(U)}setSize(A,Q){this.width=A,this.height=Q,this.ssaoRenderTarget.setSize(A,Q),this.normalRenderTarget.setSize(A,Q),this.blurRenderTarget.setSize(A,Q),this.ssaoMaterial.uniforms.resolution.value.set(A,Q),this.ssaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssaoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.blurMaterial.uniforms.resolution.value.set(A,Q)}generateSampleKernel(A){let Q=this.kernel;for(let J=0;J - float pointToLineDistance(vec3 x0, vec3 x1, vec3 x2) { - //x0: point, x1: linePointA, x2: linePointB - //https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html - return length(cross(x0-x1,x0-x2))/length(x2-x1); - } - float pointPlaneDistance(vec3 point,vec3 planePoint,vec3 planeNormal){ - // https://mathworld.wolfram.com/Point-PlaneDistance.html - //// https://en.wikipedia.org/wiki/Plane_(geometry) - //// http://paulbourke.net/geometry/pointlineplane/ - float a=planeNormal.x,b=planeNormal.y,c=planeNormal.z; - float x0=point.x,y0=point.y,z0=point.z; - float x=planePoint.x,y=planePoint.y,z=planePoint.z; - float d=-(a*x+b*y+c*z); - float distance=(a*x0+b*y0+c*z0+d)/sqrt(a*a+b*b+c*c); - return distance; - } - float getDepth( const in vec2 uv ) { - return texture2D( tDepth, uv ).x; - } - float getViewZ( const in float depth ) { - #ifdef PERSPECTIVE_CAMERA - return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); - #else - return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); - #endif - } - vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { - vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc - clipPosition *= clipW; //clip - return ( cameraInverseProjectionMatrix * clipPosition ).xyz;//view - } - vec3 getViewNormal( const in vec2 uv ) { - return unpackRGBToNormal( texture2D( tNormal, uv ).xyz ); - } - vec2 viewPositionToXY(vec3 viewPosition){ - vec2 xy; - vec4 clip=cameraProjectionMatrix*vec4(viewPosition,1); - xy=clip.xy;//clip - float clipW=clip.w; - xy/=clipW;//NDC - xy=(xy+1.)/2.;//uv - xy*=resolution;//screen - return xy; - } - void main(){ - #ifdef SELECTIVE - float metalness=texture2D(tMetalness,vUv).r; - if(metalness==0.) return; - #endif - - float depth = getDepth( vUv ); - float viewZ = getViewZ( depth ); - if(-viewZ>=cameraFar) return; - - float clipW = cameraProjectionMatrix[2][3] * viewZ+cameraProjectionMatrix[3][3]; - vec3 viewPosition=getViewPosition( vUv, depth, clipW ); - - vec2 d0=gl_FragCoord.xy; - vec2 d1; - - vec3 viewNormal=getViewNormal( vUv ); - - #ifdef PERSPECTIVE_CAMERA - vec3 viewIncidentDir=normalize(viewPosition); - vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal); - #else - vec3 viewIncidentDir=vec3(0,0,-1); - vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal); - #endif - - float maxReflectRayLen=maxDistance/dot(-viewIncidentDir,viewNormal); - // dot(a,b)==length(a)*length(b)*cos(theta) // https://www.mathsisfun.com/algebra/vectors-dot-product.html - // if(a.isNormalized&&b.isNormalized) dot(a,b)==cos(theta) - // maxDistance/maxReflectRayLen=cos(theta) - // maxDistance/maxReflectRayLen==dot(a,b) - // maxReflectRayLen==maxDistance/dot(a,b) - - vec3 d1viewPosition=viewPosition+viewReflectDir*maxReflectRayLen; - #ifdef PERSPECTIVE_CAMERA - if(d1viewPosition.z>-cameraNear){ - //https://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx - float t=(-cameraNear-viewPosition.z)/viewReflectDir.z; - d1viewPosition=viewPosition+viewReflectDir*t; - } - #endif - d1=viewPositionToXY(d1viewPosition); - - float totalLen=length(d1-d0); - float xLen=d1.x-d0.x; - float yLen=d1.y-d0.y; - float totalStep=max(abs(xLen),abs(yLen)); - float xSpan=xLen/totalStep; - float ySpan=yLen/totalStep; - for(float i=0.;i=totalStep) break; - vec2 xy=vec2(d0.x+i*xSpan,d0.y+i*ySpan); - if(xy.x<0.||xy.x>resolution.x||xy.y<0.||xy.y>resolution.y) break; - float s=length(xy-d0)/totalLen; - vec2 uv=xy/resolution; - - float d = getDepth(uv); - float vZ = getViewZ( d ); - if(-vZ>=cameraFar) continue; - float cW = cameraProjectionMatrix[2][3] * vZ+cameraProjectionMatrix[3][3]; - vec3 vP=getViewPosition( uv, d, cW ); - - #ifdef PERSPECTIVE_CAMERA - // https://comp.nus.edu.sg/~lowkl/publications/lowk_persp_interp_techrep.pdf - float recipVPZ=1./viewPosition.z; - float viewReflectRayZ=1./(recipVPZ+s*(1./d1viewPosition.z-recipVPZ)); - #else - float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z); - #endif - - // if(viewReflectRayZ>vZ) continue; // will cause "npm run make-screenshot webgl_postprocessing_ssr" high probability hang. - // https://github.com/mrdoob/three.js/pull/21539#issuecomment-821061164 - if(viewReflectRayZ<=vZ){ - - bool hit; - #ifdef INFINITE_THICK - hit=true; - #else - float away=pointToLineDistance(vP,viewPosition,d1viewPosition); - - float minThickness; - vec2 xyNeighbor=xy; - xyNeighbor.x+=1.; - vec2 uvNeighbor=xyNeighbor/resolution; - vec3 vPNeighbor=getViewPosition(uvNeighbor,d,cW); - minThickness=vPNeighbor.x-vP.x; - minThickness*=3.; - float tk=max(minThickness,thickness); - - hit=away<=tk; - #endif - - if(hit){ - vec3 vN=getViewNormal( uv ); - if(dot(viewReflectDir,vN)>=0.) continue; - float distance=pointPlaneDistance(vP,viewPosition,viewNormal); - if(distance>maxDistance) break; - float op=opacity; - #ifdef DISTANCE_ATTENUATION - float ratio=1.-(distance/maxDistance); - float attenuation=ratio*ratio; - op=opacity*attenuation; - #endif - #ifdef FRESNEL - float fresnelCoe=(dot(viewIncidentDir,viewReflectDir)+1.)/2.; - op*=fresnelCoe; - #endif - vec4 reflectColor=texture2D(tDiffuse,uv); - gl_FragColor.xyz=reflectColor.xyz; - gl_FragColor.a=op; - break; - } - } - } - } - `},zB={name:"SSRDepthShader",defines:{PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - } - - `,fragmentShader:` - - uniform sampler2D tDepth; - - uniform float cameraNear; - uniform float cameraFar; - - varying vec2 vUv; - - #include - - float getLinearDepth( const in vec2 uv ) { - - #if PERSPECTIVE_CAMERA == 1 - - float fragCoordZ = texture2D( tDepth, uv ).x; - float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); - return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); - - #else - - return texture2D( tDepth, uv ).x; - - #endif - - } - - void main() { - - float depth = getLinearDepth( vUv ); - float d = 1.0 - depth; - // d=(d-.999)*1000.; - gl_FragColor = vec4( vec3( d ), 1.0 ); - - } - - `},I7={name:"SSRBlurShader",uniforms:{tDiffuse:{value:null},resolution:{value:new p1},opacity:{value:0.5}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - } - - `,fragmentShader:` - - uniform sampler2D tDiffuse; - uniform vec2 resolution; - varying vec2 vUv; - void main() { - //reverse engineering from PhotoShop blur filter, then change coefficient - - vec2 texelSize = ( 1.0 / resolution ); - - vec4 c=texture2D(tDiffuse,vUv); - - vec2 offset; - - offset=(vec2(-1,0))*texelSize; - vec4 cl=texture2D(tDiffuse,vUv+offset); - - offset=(vec2(1,0))*texelSize; - vec4 cr=texture2D(tDiffuse,vUv+offset); - - offset=(vec2(0,-1))*texelSize; - vec4 cb=texture2D(tDiffuse,vUv+offset); - - offset=(vec2(0,1))*texelSize; - vec4 ct=texture2D(tDiffuse,vUv+offset); - - // float coeCenter=.5; - // float coeSide=.125; - float coeCenter=.2; - float coeSide=.2; - float a=c.a*coeCenter+cl.a*coeSide+cr.a*coeSide+cb.a*coeSide+ct.a*coeSide; - vec3 rgb=(c.rgb*c.a*coeCenter+cl.rgb*cl.a*coeSide+cr.rgb*cr.a*coeSide+cb.rgb*cb.a*coeSide+ct.rgb*ct.a*coeSide)/a; - gl_FragColor=vec4(rgb,a); - - } - `};class k4 extends B2{constructor({renderer:A,scene:Q,camera:J,width:K,height:C,selects:U,bouncing:Y=!1,groundReflector:Z}){super();this.width=K!==void 0?K:512,this.height=C!==void 0?C:512,this.clear=!0,this.renderer=A,this.scene=Q,this.camera=J,this.groundReflector=Z,this.opacity=S5.uniforms.opacity.value,this.output=0,this.maxDistance=S5.uniforms.maxDistance.value,this.thickness=S5.uniforms.thickness.value,this.tempColor=new y1,this._selects=U,this.selective=Array.isArray(this._selects),Object.defineProperty(this,"selects",{get(){return this._selects},set(E){if(this._selects===E)return;if(this._selects=E,Array.isArray(E))this.selective=!0,this.ssrMaterial.defines.SELECTIVE=!0,this.ssrMaterial.needsUpdate=!0;else this.selective=!1,this.ssrMaterial.defines.SELECTIVE=!1,this.ssrMaterial.needsUpdate=!0}}),this._bouncing=Y,Object.defineProperty(this,"bouncing",{get(){return this._bouncing},set(E){if(this._bouncing===E)return;if(this._bouncing=E,E)this.ssrMaterial.uniforms.tDiffuse.value=this.prevRenderTarget.texture;else this.ssrMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture}}),this.blur=!0,this._distanceAttenuation=S5.defines.DISTANCE_ATTENUATION,Object.defineProperty(this,"distanceAttenuation",{get(){return this._distanceAttenuation},set(E){if(this._distanceAttenuation===E)return;this._distanceAttenuation=E,this.ssrMaterial.defines.DISTANCE_ATTENUATION=E,this.ssrMaterial.needsUpdate=!0}}),this._fresnel=S5.defines.FRESNEL,Object.defineProperty(this,"fresnel",{get(){return this._fresnel},set(E){if(this._fresnel===E)return;this._fresnel=E,this.ssrMaterial.defines.FRESNEL=E,this.ssrMaterial.needsUpdate=!0}}),this._infiniteThick=S5.defines.INFINITE_THICK,Object.defineProperty(this,"infiniteThick",{get(){return this._infiniteThick},set(E){if(this._infiniteThick===E)return;this._infiniteThick=E,this.ssrMaterial.defines.INFINITE_THICK=E,this.ssrMaterial.needsUpdate=!0}});let X=new E6;X.type=r5,X.minFilter=YA,X.magFilter=YA,this.beautyRenderTarget=new s0(this.width,this.height,{minFilter:YA,magFilter:YA,type:g0,depthTexture:X,depthBuffer:!0}),this.prevRenderTarget=new s0(this.width,this.height,{minFilter:YA,magFilter:YA}),this.normalRenderTarget=new s0(this.width,this.height,{minFilter:YA,magFilter:YA,type:g0}),this.metalnessRenderTarget=new s0(this.width,this.height,{minFilter:YA,magFilter:YA,type:g0}),this.ssrRenderTarget=new s0(this.width,this.height,{minFilter:YA,magFilter:YA}),this.blurRenderTarget=this.ssrRenderTarget.clone(),this.blurRenderTarget2=this.ssrRenderTarget.clone(),this.ssrMaterial=new T0({defines:Object.assign({},S5.defines,{MAX_STEP:Math.sqrt(this.width*this.width+this.height*this.height)}),uniforms:u0.clone(S5.uniforms),vertexShader:S5.vertexShader,fragmentShader:S5.fragmentShader,blending:XA}),this.ssrMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.ssrMaterial.uniforms.tNormal.value=this.normalRenderTarget.texture,this.ssrMaterial.defines.SELECTIVE=this.selective,this.ssrMaterial.needsUpdate=!0,this.ssrMaterial.uniforms.tMetalness.value=this.metalnessRenderTarget.texture,this.ssrMaterial.uniforms.tDepth.value=this.beautyRenderTarget.depthTexture,this.ssrMaterial.uniforms.cameraNear.value=this.camera.near,this.ssrMaterial.uniforms.cameraFar.value=this.camera.far,this.ssrMaterial.uniforms.thickness.value=this.thickness,this.ssrMaterial.uniforms.resolution.value.set(this.width,this.height),this.ssrMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssrMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.normalMaterial=new B9,this.normalMaterial.blending=XA,this.metalnessOnMaterial=new BA({color:"white"}),this.metalnessOffMaterial=new BA({color:"black"}),this.blurMaterial=new T0({defines:Object.assign({},I7.defines),uniforms:u0.clone(I7.uniforms),vertexShader:I7.vertexShader,fragmentShader:I7.fragmentShader}),this.blurMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture,this.blurMaterial.uniforms.resolution.value.set(this.width,this.height),this.blurMaterial2=new T0({defines:Object.assign({},I7.defines),uniforms:u0.clone(I7.uniforms),vertexShader:I7.vertexShader,fragmentShader:I7.fragmentShader}),this.blurMaterial2.uniforms.tDiffuse.value=this.blurRenderTarget.texture,this.blurMaterial2.uniforms.resolution.value.set(this.width,this.height),this.depthRenderMaterial=new T0({defines:Object.assign({},zB.defines),uniforms:u0.clone(zB.uniforms),vertexShader:zB.vertexShader,fragmentShader:zB.fragmentShader,blending:XA}),this.depthRenderMaterial.uniforms.tDepth.value=this.beautyRenderTarget.depthTexture,this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this.copyMaterial=new T0({uniforms:u0.clone(m2.uniforms),vertexShader:m2.vertexShader,fragmentShader:m2.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blendSrc:Z6,blendDst:j9,blendEquation:X8,blendSrcAlpha:Z6,blendDstAlpha:j9,blendEquationAlpha:X8}),this.fsQuad=new $2(null),this.originalClearColor=new y1}dispose(){this.beautyRenderTarget.dispose(),this.prevRenderTarget.dispose(),this.normalRenderTarget.dispose(),this.metalnessRenderTarget.dispose(),this.ssrRenderTarget.dispose(),this.blurRenderTarget.dispose(),this.blurRenderTarget2.dispose(),this.normalMaterial.dispose(),this.metalnessOnMaterial.dispose(),this.metalnessOffMaterial.dispose(),this.blurMaterial.dispose(),this.blurMaterial2.dispose(),this.copyMaterial.dispose(),this.depthRenderMaterial.dispose(),this.fsQuad.dispose()}render(A,Q){if(A.setRenderTarget(this.beautyRenderTarget),A.clear(),this.groundReflector)this.groundReflector.visible=!1,this.groundReflector.doRender(this.renderer,this.scene,this.camera),this.groundReflector.visible=!0;if(A.render(this.scene,this.camera),this.groundReflector)this.groundReflector.visible=!1;if(this.renderOverride(A,this.normalMaterial,this.normalRenderTarget,0,0),this.selective)this.renderMetalness(A,this.metalnessOnMaterial,this.metalnessRenderTarget,0,0);if(this.ssrMaterial.uniforms.opacity.value=this.opacity,this.ssrMaterial.uniforms.maxDistance.value=this.maxDistance,this.ssrMaterial.uniforms.thickness.value=this.thickness,this.renderPass(A,this.ssrMaterial,this.ssrRenderTarget),this.blur)this.renderPass(A,this.blurMaterial,this.blurRenderTarget),this.renderPass(A,this.blurMaterial2,this.blurRenderTarget2);switch(this.output){case k4.OUTPUT.Default:if(this.bouncing){if(this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.copyMaterial.blending=XA,this.renderPass(A,this.copyMaterial,this.prevRenderTarget),this.blur)this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget2.texture;else this.copyMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture;this.copyMaterial.blending=s5,this.renderPass(A,this.copyMaterial,this.prevRenderTarget),this.copyMaterial.uniforms.tDiffuse.value=this.prevRenderTarget.texture,this.copyMaterial.blending=XA,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q)}else{if(this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.copyMaterial.blending=XA,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q),this.blur)this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget2.texture;else this.copyMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture;this.copyMaterial.blending=s5,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q)}break;case k4.OUTPUT.SSR:if(this.blur)this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget2.texture;else this.copyMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture;if(this.copyMaterial.blending=XA,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q),this.bouncing){if(this.blur)this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget2.texture;else this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture;this.copyMaterial.blending=XA,this.renderPass(A,this.copyMaterial,this.prevRenderTarget),this.copyMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture,this.copyMaterial.blending=s5,this.renderPass(A,this.copyMaterial,this.prevRenderTarget)}break;case k4.OUTPUT.Beauty:this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.copyMaterial.blending=XA,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q);break;case k4.OUTPUT.Depth:this.renderPass(A,this.depthRenderMaterial,this.renderToScreen?null:Q);break;case k4.OUTPUT.Normal:this.copyMaterial.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.copyMaterial.blending=XA,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q);break;case k4.OUTPUT.Metalness:this.copyMaterial.uniforms.tDiffuse.value=this.metalnessRenderTarget.texture,this.copyMaterial.blending=XA,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q);break;default:console.warn("THREE.SSRPass: Unknown output type.")}}renderPass(A,Q,J,K,C){this.originalClearColor.copy(A.getClearColor(this.tempColor));let U=A.getClearAlpha(this.tempColor),Y=A.autoClear;if(A.setRenderTarget(J),A.autoClear=!1,K!==void 0&&K!==null)A.setClearColor(K),A.setClearAlpha(C||0),A.clear();this.fsQuad.material=Q,this.fsQuad.render(A),A.autoClear=Y,A.setClearColor(this.originalClearColor),A.setClearAlpha(U)}renderOverride(A,Q,J,K,C){this.originalClearColor.copy(A.getClearColor(this.tempColor));let U=A.getClearAlpha(this.tempColor),Y=A.autoClear;if(A.setRenderTarget(J),A.autoClear=!1,K=Q.clearColor||K,C=Q.clearAlpha||C,K!==void 0&&K!==null)A.setClearColor(K),A.setClearAlpha(C||0),A.clear();this.scene.overrideMaterial=Q,A.render(this.scene,this.camera),this.scene.overrideMaterial=null,A.autoClear=Y,A.setClearColor(this.originalClearColor),A.setClearAlpha(U)}renderMetalness(A,Q,J,K,C){this.originalClearColor.copy(A.getClearColor(this.tempColor));let U=A.getClearAlpha(this.tempColor),Y=A.autoClear,Z=this.scene.background,X=this.scene.fog;if(A.setRenderTarget(J),A.autoClear=!1,this.scene.background=null,this.scene.fog=null,K=Q.clearColor||K,C=Q.clearAlpha||C,K!==void 0&&K!==null)A.setClearColor(K),A.setClearAlpha(C||0),A.clear();this.scene.traverseVisible((E)=>{if(E._SSRPassBackupMaterial=E.material,this._selects.includes(E))E.material=this.metalnessOnMaterial;else E.material=this.metalnessOffMaterial}),A.render(this.scene,this.camera),this.scene.traverseVisible((E)=>{E.material=E._SSRPassBackupMaterial}),A.autoClear=Y,A.setClearColor(this.originalClearColor),A.setClearAlpha(U),this.scene.background=Z,this.scene.fog=X}setSize(A,Q){this.width=A,this.height=Q,this.ssrMaterial.defines.MAX_STEP=Math.sqrt(A*A+Q*Q),this.ssrMaterial.needsUpdate=!0,this.beautyRenderTarget.setSize(A,Q),this.prevRenderTarget.setSize(A,Q),this.ssrRenderTarget.setSize(A,Q),this.normalRenderTarget.setSize(A,Q),this.metalnessRenderTarget.setSize(A,Q),this.blurRenderTarget.setSize(A,Q),this.blurRenderTarget2.setSize(A,Q),this.ssrMaterial.uniforms.resolution.value.set(A,Q),this.ssrMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssrMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.blurMaterial.uniforms.resolution.value.set(A,Q),this.blurMaterial2.uniforms.resolution.value.set(A,Q)}}k4.OUTPUT={Default:0,SSR:1,Beauty:3,Depth:4,Normal:5,Metalness:7};var Jc={name:"LuminosityHighPassShader",shaderID:"luminosityHighPass",uniforms:{tDiffuse:{value:null},luminosityThreshold:{value:1},smoothWidth:{value:1},defaultColor:{value:new y1(0)},defaultOpacity:{value:0}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform sampler2D tDiffuse; - uniform vec3 defaultColor; - uniform float defaultOpacity; - uniform float luminosityThreshold; - uniform float smoothWidth; - - varying vec2 vUv; - - void main() { - - vec4 texel = texture2D( tDiffuse, vUv ); - - float v = luminance( texel.xyz ); - - vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity ); - - float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v ); - - gl_FragColor = mix( outputColor, texel, alpha ); - - }`};class DB extends B2{constructor(A,Q,J,K){super();this.strength=Q!==void 0?Q:1,this.radius=J,this.threshold=K,this.resolution=A!==void 0?new p1(A.x,A.y):new p1(256,256),this.clearColor=new y1(0,0,0),this.renderTargetsHorizontal=[],this.renderTargetsVertical=[],this.nMips=5;let C=Math.round(this.resolution.x/2),U=Math.round(this.resolution.y/2);this.renderTargetBright=new s0(C,U,{type:g0}),this.renderTargetBright.texture.name="UnrealBloomPass.bright",this.renderTargetBright.texture.generateMipmaps=!1;for(let H=0;H - varying vec2 vUv; - uniform sampler2D colorTexture; - uniform vec2 invSize; - uniform vec2 direction; - uniform float gaussianCoefficients[KERNEL_RADIUS]; - - void main() { - float weightSum = gaussianCoefficients[0]; - vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum; - for( int i = 1; i < KERNEL_RADIUS; i ++ ) { - float x = float(i); - float w = gaussianCoefficients[i]; - vec2 uvOffset = direction * invSize * x; - vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb; - vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb; - diffuseSum += (sample1 + sample2) * w; - weightSum += 2.0 * w; - } - gl_FragColor = vec4(diffuseSum/weightSum, 1.0); - }`})}getCompositeMaterial(A){return new T0({defines:{NUM_MIPS:A},uniforms:{blurTexture1:{value:null},blurTexture2:{value:null},blurTexture3:{value:null},blurTexture4:{value:null},blurTexture5:{value:null},bloomStrength:{value:1},bloomFactors:{value:null},bloomTintColors:{value:null},bloomRadius:{value:0}},vertexShader:`varying vec2 vUv; - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:`varying vec2 vUv; - uniform sampler2D blurTexture1; - uniform sampler2D blurTexture2; - uniform sampler2D blurTexture3; - uniform sampler2D blurTexture4; - uniform sampler2D blurTexture5; - uniform float bloomStrength; - uniform float bloomRadius; - uniform float bloomFactors[NUM_MIPS]; - uniform vec3 bloomTintColors[NUM_MIPS]; - - float lerpBloomFactor(const in float factor) { - float mirrorFactor = 1.2 - factor; - return mix(factor, mirrorFactor, bloomRadius); - } - - void main() { - gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + - lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + - lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + - lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + - lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) ); - }`})}}DB.BlurDirectionX=new p1(1,0);DB.BlurDirectionY=new p1(0,1);var Wh1=new I1,Ih1=new Y0,qh1=new Y0,Oh1=new I1,Nh1=new I1;var Rh1=new I1,zh1=new t0,Dh1=new I1;var Vh1=new Y0,Mh1=new Y0;var UX1={name:"BokehShader",uniforms:{textureWidth:{value:1},textureHeight:{value:1},focalDepth:{value:1},focalLength:{value:24},fstop:{value:0.9},tColor:{value:null},tDepth:{value:null},maxblur:{value:1},showFocus:{value:0},manualdof:{value:0},vignetting:{value:0},depthblur:{value:0},threshold:{value:0.5},gain:{value:2},bias:{value:0.5},fringe:{value:0.7},znear:{value:0.1},zfar:{value:100},noise:{value:1},dithering:{value:0.0001},pentagon:{value:0},shaderFocus:{value:1},focusCoords:{value:new p1}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - #include - - varying vec2 vUv; - - uniform sampler2D tColor; - uniform sampler2D tDepth; - uniform float textureWidth; - uniform float textureHeight; - - uniform float focalDepth; //focal distance value in meters, but you may use autofocus option below - uniform float focalLength; //focal length in mm - uniform float fstop; //f-stop value - uniform bool showFocus; //show debug focus point and focal range (red = focal point, green = focal range) - - /* - make sure that these two values are the same for your camera, otherwise distances will be wrong. - */ - - uniform float znear; // camera clipping start - uniform float zfar; // camera clipping end - - //------------------------------------------ - //user variables - - const int samples = SAMPLES; //samples on the first ring - const int rings = RINGS; //ring count - - const int maxringsamples = rings * samples; - - uniform bool manualdof; // manual dof calculation - float ndofstart = 1.0; // near dof blur start - float ndofdist = 2.0; // near dof blur falloff distance - float fdofstart = 1.0; // far dof blur start - float fdofdist = 3.0; // far dof blur falloff distance - - float CoC = 0.03; //circle of confusion size in mm (35mm film = 0.03mm) - - uniform bool vignetting; // use optical lens vignetting - - float vignout = 1.3; // vignetting outer border - float vignin = 0.0; // vignetting inner border - float vignfade = 22.0; // f-stops till vignette fades - - uniform bool shaderFocus; - // disable if you use external focalDepth value - - uniform vec2 focusCoords; - // autofocus point on screen (0.0,0.0 - left lower corner, 1.0,1.0 - upper right) - // if center of screen use vec2(0.5, 0.5); - - uniform float maxblur; - //clamp value of max blur (0.0 = no blur, 1.0 default) - - uniform float threshold; // highlight threshold; - uniform float gain; // highlight gain; - - uniform float bias; // bokeh edge bias - uniform float fringe; // bokeh chromatic aberration / fringing - - uniform bool noise; //use noise instead of pattern for sample dithering - - uniform float dithering; - - uniform bool depthblur; // blur the depth buffer - float dbsize = 1.25; // depth blur size - - /* - next part is experimental - not looking good with small sample and ring count - looks okay starting from samples = 4, rings = 4 - */ - - uniform bool pentagon; //use pentagon as bokeh shape? - float feather = 0.4; //pentagon shape feather - - //------------------------------------------ - - float penta(vec2 coords) { - //pentagonal shape - float scale = float(rings) - 1.3; - vec4 HS0 = vec4( 1.0, 0.0, 0.0, 1.0); - vec4 HS1 = vec4( 0.309016994, 0.951056516, 0.0, 1.0); - vec4 HS2 = vec4(-0.809016994, 0.587785252, 0.0, 1.0); - vec4 HS3 = vec4(-0.809016994,-0.587785252, 0.0, 1.0); - vec4 HS4 = vec4( 0.309016994,-0.951056516, 0.0, 1.0); - vec4 HS5 = vec4( 0.0 ,0.0 , 1.0, 1.0); - - vec4 one = vec4( 1.0 ); - - vec4 P = vec4((coords),vec2(scale, scale)); - - vec4 dist = vec4(0.0); - float inorout = -4.0; - - dist.x = dot( P, HS0 ); - dist.y = dot( P, HS1 ); - dist.z = dot( P, HS2 ); - dist.w = dot( P, HS3 ); - - dist = smoothstep( -feather, feather, dist ); - - inorout += dot( dist, one ); - - dist.x = dot( P, HS4 ); - dist.y = HS5.w - abs( P.z ); - - dist = smoothstep( -feather, feather, dist ); - inorout += dist.x; - - return clamp( inorout, 0.0, 1.0 ); - } - - float bdepth(vec2 coords) { - // Depth buffer blur - float d = 0.0; - float kernel[9]; - vec2 offset[9]; - - vec2 wh = vec2(1.0/textureWidth,1.0/textureHeight) * dbsize; - - offset[0] = vec2(-wh.x,-wh.y); - offset[1] = vec2( 0.0, -wh.y); - offset[2] = vec2( wh.x -wh.y); - - offset[3] = vec2(-wh.x, 0.0); - offset[4] = vec2( 0.0, 0.0); - offset[5] = vec2( wh.x, 0.0); - - offset[6] = vec2(-wh.x, wh.y); - offset[7] = vec2( 0.0, wh.y); - offset[8] = vec2( wh.x, wh.y); - - kernel[0] = 1.0/16.0; kernel[1] = 2.0/16.0; kernel[2] = 1.0/16.0; - kernel[3] = 2.0/16.0; kernel[4] = 4.0/16.0; kernel[5] = 2.0/16.0; - kernel[6] = 1.0/16.0; kernel[7] = 2.0/16.0; kernel[8] = 1.0/16.0; - - - for( int i=0; i<9; i++ ) { - float tmp = texture2D(tDepth, coords + offset[i]).r; - d += tmp * kernel[i]; - } - - return d; - } - - - vec3 color(vec2 coords,float blur) { - //processing the sample - - vec3 col = vec3(0.0); - vec2 texel = vec2(1.0/textureWidth,1.0/textureHeight); - - col.r = texture2D(tColor,coords + vec2(0.0,1.0)*texel*fringe*blur).r; - col.g = texture2D(tColor,coords + vec2(-0.866,-0.5)*texel*fringe*blur).g; - col.b = texture2D(tColor,coords + vec2(0.866,-0.5)*texel*fringe*blur).b; - - vec3 lumcoeff = vec3(0.299,0.587,0.114); - float lum = dot(col.rgb, lumcoeff); - float thresh = max((lum-threshold)*gain, 0.0); - return col+mix(vec3(0.0),col,thresh*blur); - } - - vec3 debugFocus(vec3 col, float blur, float depth) { - float edge = 0.002*depth; //distance based edge smoothing - float m = clamp(smoothstep(0.0,edge,blur),0.0,1.0); - float e = clamp(smoothstep(1.0-edge,1.0,blur),0.0,1.0); - - col = mix(col,vec3(1.0,0.5,0.0),(1.0-m)*0.6); - col = mix(col,vec3(0.0,0.5,1.0),((1.0-e)-(1.0-m))*0.2); - - return col; - } - - float linearize(float depth) { - return -zfar * znear / (depth * (zfar - znear) - zfar); - } - - float vignette() { - float dist = distance(vUv.xy, vec2(0.5,0.5)); - dist = smoothstep(vignout+(fstop/vignfade), vignin+(fstop/vignfade), dist); - return clamp(dist,0.0,1.0); - } - - float gather(float i, float j, int ringsamples, inout vec3 col, float w, float h, float blur) { - float rings2 = float(rings); - float step = PI*2.0 / float(ringsamples); - float pw = cos(j*step)*i; - float ph = sin(j*step)*i; - float p = 1.0; - if (pentagon) { - p = penta(vec2(pw,ph)); - } - col += color(vUv.xy + vec2(pw*w,ph*h), blur) * mix(1.0, i/rings2, bias) * p; - return 1.0 * mix(1.0, i /rings2, bias) * p; - } - - void main() { - //scene depth calculation - - float depth = linearize(texture2D(tDepth,vUv.xy).x); - - // Blur depth? - if ( depthblur ) { - depth = linearize(bdepth(vUv.xy)); - } - - //focal plane calculation - - float fDepth = focalDepth; - - if (shaderFocus) { - - fDepth = linearize(texture2D(tDepth,focusCoords).x); - - } - - // dof blur factor calculation - - float blur = 0.0; - - if (manualdof) { - float a = depth-fDepth; // Focal plane - float b = (a-fdofstart)/fdofdist; // Far DoF - float c = (-a-ndofstart)/ndofdist; // Near Dof - blur = (a>0.0) ? b : c; - } else { - float f = focalLength; // focal length in mm - float d = fDepth*1000.0; // focal plane in mm - float o = depth*1000.0; // depth in mm - - float a = (o*f)/(o-f); - float b = (d*f)/(d-f); - float c = (d-f)/(d*fstop*CoC); - - blur = abs(a-b)*c; - } - - blur = clamp(blur,0.0,1.0); - - // calculation of pattern for dithering - - vec2 noise = vec2(rand(vUv.xy), rand( vUv.xy + vec2( 0.4, 0.6 ) ) )*dithering*blur; - - // getting blur x and y step factor - - float w = (1.0/textureWidth)*blur*maxblur+noise.x; - float h = (1.0/textureHeight)*blur*maxblur+noise.y; - - // calculation of final color - - vec3 col = vec3(0.0); - - if(blur < 0.05) { - //some optimization thingy - col = texture2D(tColor, vUv.xy).rgb; - } else { - col = texture2D(tColor, vUv.xy).rgb; - float s = 1.0; - int ringsamples; - - for (int i = 1; i <= rings; i++) { - /*unboxstart*/ - ringsamples = i * samples; - - for (int j = 0 ; j < maxringsamples ; j++) { - if (j >= ringsamples) break; - s += gather(float(i), float(j), ringsamples, col, w, h, blur); - } - /*unboxend*/ - } - - col /= s; //divide by sample count - } - - if (showFocus) { - col = debugFocus(col, blur, depth); - } - - if (vignetting) { - col *= vignette(); - } - - gl_FragColor.rgb = col; - gl_FragColor.a = 1.0; - - #include - #include - }`};var dh1={name:"ColorCorrectionShader",uniforms:{tDiffuse:{value:null},powRGB:{value:new I1(2,2,2)},mulRGB:{value:new I1(1,1,1)},addRGB:{value:new I1(0,0,0)}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform sampler2D tDiffuse; - uniform vec3 powRGB; - uniform vec3 mulRGB; - uniform vec3 addRGB; - - varying vec2 vUv; - - void main() { - - gl_FragColor = texture2D( tDiffuse, vUv ); - gl_FragColor.rgb = mulRGB * pow( ( gl_FragColor.rgb + addRGB ), powRGB ); - - }`};var sh1={name:"ColorifyShader",uniforms:{tDiffuse:{value:null},color:{value:new y1(16777215)}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform vec3 color; - uniform sampler2D tDiffuse; - - varying vec2 vUv; - - void main() { - - vec4 texel = texture2D( tDiffuse, vUv ); - - float v = luminance( texel.xyz ); - - gl_FragColor = vec4( v * color, texel.w ); - - }`};var th1={name:"FXAAShader",uniforms:{tDiffuse:{value:null},resolution:{value:new p1(0.0009765625,0.001953125)}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - // FXAA algorithm from NVIDIA, C# implementation by Jasper Flick, GLSL port by Dave Hoskins - // http://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf - // https://catlikecoding.com/unity/tutorials/advanced-rendering/fxaa/ - - uniform sampler2D tDiffuse; - uniform vec2 resolution; - varying vec2 vUv; - - #define EDGE_STEP_COUNT 6 - #define EDGE_GUESS 8.0 - #define EDGE_STEPS 1.0, 1.5, 2.0, 2.0, 2.0, 4.0 - const float edgeSteps[EDGE_STEP_COUNT] = float[EDGE_STEP_COUNT]( EDGE_STEPS ); - - float _ContrastThreshold = 0.0312; - float _RelativeThreshold = 0.063; - float _SubpixelBlending = 1.0; - - vec4 Sample( sampler2D tex2D, vec2 uv ) { - - return texture( tex2D, uv ); - - } - - float SampleLuminance( sampler2D tex2D, vec2 uv ) { - - return dot( Sample( tex2D, uv ).rgb, vec3( 0.3, 0.59, 0.11 ) ); - - } - - float SampleLuminance( sampler2D tex2D, vec2 texSize, vec2 uv, float uOffset, float vOffset ) { - - uv += texSize * vec2(uOffset, vOffset); - return SampleLuminance(tex2D, uv); - - } - - struct LuminanceData { - - float m, n, e, s, w; - float ne, nw, se, sw; - float highest, lowest, contrast; - - }; - - LuminanceData SampleLuminanceNeighborhood( sampler2D tex2D, vec2 texSize, vec2 uv ) { - - LuminanceData l; - l.m = SampleLuminance( tex2D, uv ); - l.n = SampleLuminance( tex2D, texSize, uv, 0.0, 1.0 ); - l.e = SampleLuminance( tex2D, texSize, uv, 1.0, 0.0 ); - l.s = SampleLuminance( tex2D, texSize, uv, 0.0, -1.0 ); - l.w = SampleLuminance( tex2D, texSize, uv, -1.0, 0.0 ); - - l.ne = SampleLuminance( tex2D, texSize, uv, 1.0, 1.0 ); - l.nw = SampleLuminance( tex2D, texSize, uv, -1.0, 1.0 ); - l.se = SampleLuminance( tex2D, texSize, uv, 1.0, -1.0 ); - l.sw = SampleLuminance( tex2D, texSize, uv, -1.0, -1.0 ); - - l.highest = max( max( max( max( l.n, l.e ), l.s ), l.w ), l.m ); - l.lowest = min( min( min( min( l.n, l.e ), l.s ), l.w ), l.m ); - l.contrast = l.highest - l.lowest; - return l; - - } - - bool ShouldSkipPixel( LuminanceData l ) { - - float threshold = max( _ContrastThreshold, _RelativeThreshold * l.highest ); - return l.contrast < threshold; - - } - - float DeterminePixelBlendFactor( LuminanceData l ) { - - float f = 2.0 * ( l.n + l.e + l.s + l.w ); - f += l.ne + l.nw + l.se + l.sw; - f *= 1.0 / 12.0; - f = abs( f - l.m ); - f = clamp( f / l.contrast, 0.0, 1.0 ); - - float blendFactor = smoothstep( 0.0, 1.0, f ); - return blendFactor * blendFactor * _SubpixelBlending; - - } - - struct EdgeData { - - bool isHorizontal; - float pixelStep; - float oppositeLuminance, gradient; - - }; - - EdgeData DetermineEdge( vec2 texSize, LuminanceData l ) { - - EdgeData e; - float horizontal = - abs( l.n + l.s - 2.0 * l.m ) * 2.0 + - abs( l.ne + l.se - 2.0 * l.e ) + - abs( l.nw + l.sw - 2.0 * l.w ); - float vertical = - abs( l.e + l.w - 2.0 * l.m ) * 2.0 + - abs( l.ne + l.nw - 2.0 * l.n ) + - abs( l.se + l.sw - 2.0 * l.s ); - e.isHorizontal = horizontal >= vertical; - - float pLuminance = e.isHorizontal ? l.n : l.e; - float nLuminance = e.isHorizontal ? l.s : l.w; - float pGradient = abs( pLuminance - l.m ); - float nGradient = abs( nLuminance - l.m ); - - e.pixelStep = e.isHorizontal ? texSize.y : texSize.x; - - if (pGradient < nGradient) { - - e.pixelStep = -e.pixelStep; - e.oppositeLuminance = nLuminance; - e.gradient = nGradient; - - } else { - - e.oppositeLuminance = pLuminance; - e.gradient = pGradient; - - } - - return e; - - } - - float DetermineEdgeBlendFactor( sampler2D tex2D, vec2 texSize, LuminanceData l, EdgeData e, vec2 uv ) { - - vec2 uvEdge = uv; - vec2 edgeStep; - if (e.isHorizontal) { - - uvEdge.y += e.pixelStep * 0.5; - edgeStep = vec2( texSize.x, 0.0 ); - - } else { - - uvEdge.x += e.pixelStep * 0.5; - edgeStep = vec2( 0.0, texSize.y ); - - } - - float edgeLuminance = ( l.m + e.oppositeLuminance ) * 0.5; - float gradientThreshold = e.gradient * 0.25; - - vec2 puv = uvEdge + edgeStep * edgeSteps[0]; - float pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; - bool pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; - - for ( int i = 1; i < EDGE_STEP_COUNT && !pAtEnd; i++ ) { - - puv += edgeStep * edgeSteps[i]; - pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; - pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; - - } - - if ( !pAtEnd ) { - - puv += edgeStep * EDGE_GUESS; - - } - - vec2 nuv = uvEdge - edgeStep * edgeSteps[0]; - float nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; - bool nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; - - for ( int i = 1; i < EDGE_STEP_COUNT && !nAtEnd; i++ ) { - - nuv -= edgeStep * edgeSteps[i]; - nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; - nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; - - } - - if ( !nAtEnd ) { - - nuv -= edgeStep * EDGE_GUESS; - - } - - float pDistance, nDistance; - if ( e.isHorizontal ) { - - pDistance = puv.x - uv.x; - nDistance = uv.x - nuv.x; - - } else { - - pDistance = puv.y - uv.y; - nDistance = uv.y - nuv.y; - - } - - float shortestDistance; - bool deltaSign; - if ( pDistance <= nDistance ) { - - shortestDistance = pDistance; - deltaSign = pLuminanceDelta >= 0.0; - - } else { - - shortestDistance = nDistance; - deltaSign = nLuminanceDelta >= 0.0; - - } - - if ( deltaSign == ( l.m - edgeLuminance >= 0.0 ) ) { - - return 0.0; - - } - - return 0.5 - shortestDistance / ( pDistance + nDistance ); - - } - - vec4 ApplyFXAA( sampler2D tex2D, vec2 texSize, vec2 uv ) { - - LuminanceData luminance = SampleLuminanceNeighborhood( tex2D, texSize, uv ); - if ( ShouldSkipPixel( luminance ) ) { - - return Sample( tex2D, uv ); - - } - - float pixelBlend = DeterminePixelBlendFactor( luminance ); - EdgeData edge = DetermineEdge( texSize, luminance ); - float edgeBlend = DetermineEdgeBlendFactor( tex2D, texSize, luminance, edge, uv ); - float finalBlend = max( pixelBlend, edgeBlend ); - - if (edge.isHorizontal) { - - uv.y += edge.pixelStep * finalBlend; - - } else { - - uv.x += edge.pixelStep * finalBlend; - - } - - return Sample( tex2D, uv ); - - } - - void main() { - - gl_FragColor = ApplyFXAA( tDiffuse, resolution.xy, vUv ); - - }`};var Jg1={name:"FreiChenShader",uniforms:{tDiffuse:{value:null},aspect:{value:new p1(512,512)}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform sampler2D tDiffuse; - varying vec2 vUv; - - uniform vec2 aspect; - - vec2 texel = vec2( 1.0 / aspect.x, 1.0 / aspect.y ); - - - mat3 G[9]; - - // hard coded matrix values!!!! as suggested in https://github.com/neilmendoza/ofxPostProcessing/blob/master/src/EdgePass.cpp#L45 - - const mat3 g0 = mat3( 0.3535533845424652, 0, -0.3535533845424652, 0.5, 0, -0.5, 0.3535533845424652, 0, -0.3535533845424652 ); - const mat3 g1 = mat3( 0.3535533845424652, 0.5, 0.3535533845424652, 0, 0, 0, -0.3535533845424652, -0.5, -0.3535533845424652 ); - const mat3 g2 = mat3( 0, 0.3535533845424652, -0.5, -0.3535533845424652, 0, 0.3535533845424652, 0.5, -0.3535533845424652, 0 ); - const mat3 g3 = mat3( 0.5, -0.3535533845424652, 0, -0.3535533845424652, 0, 0.3535533845424652, 0, 0.3535533845424652, -0.5 ); - const mat3 g4 = mat3( 0, -0.5, 0, 0.5, 0, 0.5, 0, -0.5, 0 ); - const mat3 g5 = mat3( -0.5, 0, 0.5, 0, 0, 0, 0.5, 0, -0.5 ); - const mat3 g6 = mat3( 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.6666666865348816, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204 ); - const mat3 g7 = mat3( -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, 0.6666666865348816, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408 ); - const mat3 g8 = mat3( 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408 ); - - void main(void) - { - - G[0] = g0, - G[1] = g1, - G[2] = g2, - G[3] = g3, - G[4] = g4, - G[5] = g5, - G[6] = g6, - G[7] = g7, - G[8] = g8; - - mat3 I; - float cnv[9]; - vec3 sample; - - /* fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */ - for (float i=0.0; i<3.0; i++) { - for (float j=0.0; j<3.0; j++) { - sample = texture2D(tDiffuse, vUv + texel * vec2(i-1.0,j-1.0) ).rgb; - I[int(i)][int(j)] = length(sample); - } - } - - /* calculate the convolution values for all the masks */ - for (int i=0; i<9; i++) { - float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]); - cnv[i] = dp3 * dp3; - } - - float M = (cnv[0] + cnv[1]) + (cnv[2] + cnv[3]); - float S = (cnv[4] + cnv[5]) + (cnv[6] + cnv[7]) + (cnv[8] + M); - - gl_FragColor = vec4(vec3(sqrt(M/S)), 1.0); - }`};var Ug1={name:"GodRaysGenerateShader",uniforms:{tInput:{value:null},fStepSize:{value:1},vSunPositionScreenSpace:{value:new I1}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - #define TAPS_PER_PASS 6.0 - - varying vec2 vUv; - - uniform sampler2D tInput; - - uniform vec3 vSunPositionScreenSpace; - uniform float fStepSize; // filter step size - - void main() { - - // delta from current pixel to "sun" position - - vec2 delta = vSunPositionScreenSpace.xy - vUv; - float dist = length( delta ); - - // Step vector (uv space) - - vec2 stepv = fStepSize * delta / dist; - - // Number of iterations between pixel and sun - - float iters = dist/fStepSize; - - vec2 uv = vUv.xy; - float col = 0.0; - - // This breaks ANGLE in Chrome 22 - // - see http://code.google.com/p/chromium/issues/detail?id=153105 - - /* - // Unrolling didn't do much on my hardware (ATI Mobility Radeon 3450), - // so i've just left the loop - - "for ( float i = 0.0; i < TAPS_PER_PASS; i += 1.0 ) {", - - // Accumulate samples, making sure we don't walk past the light source. - - // The check for uv.y < 1 would not be necessary with "border" UV wrap - // mode, with a black border color. I don't think this is currently - // exposed by three.js. As a result there might be artifacts when the - // sun is to the left, right or bottom of screen as these cases are - // not specifically handled. - - " col += ( i <= iters && uv.y < 1.0 ? texture2D( tInput, uv ).r : 0.0 );", - " uv += stepv;", - - "}", - */ - - // Unrolling loop manually makes it work in ANGLE - - float f = min( 1.0, max( vSunPositionScreenSpace.z / 1000.0, 0.0 ) ); // used to fade out godrays - - if ( 0.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; - uv += stepv; - - if ( 1.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; - uv += stepv; - - if ( 2.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; - uv += stepv; - - if ( 3.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; - uv += stepv; - - if ( 4.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; - uv += stepv; - - if ( 5.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; - uv += stepv; - - // Should technically be dividing by 'iters but 'TAPS_PER_PASS' smooths out - // objectionable artifacts, in particular near the sun position. The side - // effect is that the result is darker than it should be around the sun, as - // TAPS_PER_PASS is greater than the number of samples actually accumulated. - // When the result is inverted (in the shader 'godrays_combine this produces - // a slight bright spot at the position of the sun, even when it is occluded. - - gl_FragColor = vec4( col/TAPS_PER_PASS ); - gl_FragColor.a = 1.0; - - }`};var Zg1={name:"GodRaysFakeSunShader",uniforms:{vSunPositionScreenSpace:{value:new I1},fAspect:{value:1},sunColor:{value:new y1(16772608)},bgColor:{value:new y1(0)}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - varying vec2 vUv; - - uniform vec3 vSunPositionScreenSpace; - uniform float fAspect; - - uniform vec3 sunColor; - uniform vec3 bgColor; - - void main() { - - vec2 diff = vUv - vSunPositionScreenSpace.xy; - - // Correct for aspect ratio - - diff.x *= fAspect; - - float prop = clamp( length( diff ) / 0.5, 0.0, 1.0 ); - prop = 0.35 * pow( 1.0 - prop, 3.0 ); - - gl_FragColor.xyz = ( vSunPositionScreenSpace.z > 0.0 ) ? mix( sunColor, bgColor, 1.0 - prop ) : bgColor; - gl_FragColor.w = 1.0; - - }`};var qg1={name:"NormalMapShader",uniforms:{heightMap:{value:null},resolution:{value:new p1(512,512)},scale:{value:new p1(1,1)},height:{value:0.05}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform float height; - uniform vec2 resolution; - uniform sampler2D heightMap; - - varying vec2 vUv; - - void main() { - - float val = texture2D( heightMap, vUv ).x; - - float valU = texture2D( heightMap, vUv + vec2( 1.0 / resolution.x, 0.0 ) ).x; - float valV = texture2D( heightMap, vUv + vec2( 0.0, 1.0 / resolution.y ) ).x; - - gl_FragColor = vec4( ( 0.5 * normalize( vec3( val - valU, val - valV, height ) ) + 0.5 ), 1.0 ); - - }`};var Rg1={name:"SobelOperatorShader",uniforms:{tDiffuse:{value:null},resolution:{value:new p1}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform sampler2D tDiffuse; - uniform vec2 resolution; - varying vec2 vUv; - - void main() { - - vec2 texel = vec2( 1.0 / resolution.x, 1.0 / resolution.y ); - - // kernel definition (in glsl matrices are filled in column-major order) - - const mat3 Gx = mat3( -1, -2, -1, 0, 0, 0, 1, 2, 1 ); // x direction kernel - const mat3 Gy = mat3( -1, 0, 1, -2, 0, 2, -1, 0, 1 ); // y direction kernel - - // fetch the 3x3 neighbourhood of a fragment - - // first column - - float tx0y0 = texture2D( tDiffuse, vUv + texel * vec2( -1, -1 ) ).r; - float tx0y1 = texture2D( tDiffuse, vUv + texel * vec2( -1, 0 ) ).r; - float tx0y2 = texture2D( tDiffuse, vUv + texel * vec2( -1, 1 ) ).r; - - // second column - - float tx1y0 = texture2D( tDiffuse, vUv + texel * vec2( 0, -1 ) ).r; - float tx1y1 = texture2D( tDiffuse, vUv + texel * vec2( 0, 0 ) ).r; - float tx1y2 = texture2D( tDiffuse, vUv + texel * vec2( 0, 1 ) ).r; - - // third column - - float tx2y0 = texture2D( tDiffuse, vUv + texel * vec2( 1, -1 ) ).r; - float tx2y1 = texture2D( tDiffuse, vUv + texel * vec2( 1, 0 ) ).r; - float tx2y2 = texture2D( tDiffuse, vUv + texel * vec2( 1, 1 ) ).r; - - // gradient value in x direction - - float valueGx = Gx[0][0] * tx0y0 + Gx[1][0] * tx1y0 + Gx[2][0] * tx2y0 + - Gx[0][1] * tx0y1 + Gx[1][1] * tx1y1 + Gx[2][1] * tx2y1 + - Gx[0][2] * tx0y2 + Gx[1][2] * tx1y2 + Gx[2][2] * tx2y2; - - // gradient value in y direction - - float valueGy = Gy[0][0] * tx0y0 + Gy[1][0] * tx1y0 + Gy[2][0] * tx2y0 + - Gy[0][1] * tx0y1 + Gy[1][1] * tx1y1 + Gy[2][1] * tx2y1 + - Gy[0][2] * tx0y2 + Gy[1][2] * tx1y2 + Gy[2][2] * tx2y2; - - // magnitude of the total gradient - - float G = sqrt( ( valueGx * valueGx ) + ( valueGy * valueGy ) ); - - gl_FragColor = vec4( vec3( G ), 1 ); - - }`};function ZX1(A,Q,J){return A.split(Q).join(J)}var BX1=$A.meshphong_frag.slice(0,$A.meshphong_frag.indexOf("void main() {")),XX1=$A.meshphong_frag.slice($A.meshphong_frag.indexOf("void main() {")),Vg1={name:"SubsurfaceScatteringShader",uniforms:u0.merge([$6.phong.uniforms,{thicknessMap:{value:null},thicknessColor:{value:new y1(16777215)},thicknessDistortion:{value:0.1},thicknessAmbient:{value:0},thicknessAttenuation:{value:0.1},thicknessPower:{value:2},thicknessScale:{value:10}}]),vertexShader:["#define USE_UV",$A.meshphong_vert].join(` -`),fragmentShader:["#define USE_UV","#define SUBSURFACE",BX1,"uniform sampler2D thicknessMap;","uniform float thicknessPower;","uniform float thicknessScale;","uniform float thicknessDistortion;","uniform float thicknessAmbient;","uniform float thicknessAttenuation;","uniform vec3 thicknessColor;","void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, inout ReflectedLight reflectedLight) {","\tvec3 thickness = thicknessColor * texture2D(thicknessMap, uv).r;","\tvec3 scatteringHalf = normalize(directLight.direction + (geometryNormal * thicknessDistortion));","\tfloat scatteringDot = pow(saturate(dot(geometryViewDir, -scatteringHalf)), thicknessPower) * thicknessScale;","\tvec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;","\treflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;","}",XX1.replace("#include ",ZX1($A.lights_fragment_begin,"RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );",["RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );","#if defined( SUBSURFACE ) && defined( USE_UV )"," RE_Direct_Scattering(directLight, vUv, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, reflectedLight);","#endif"].join(` -`)))].join(` -`)};var _g1={uniforms:{uDirLightPos:{value:new I1},uDirLightColor:{value:new y1(15658734)},uAmbientLightColor:{value:new y1(328965)},uBaseColor:{value:new y1(16777215)}},vertexShader:` - - varying vec3 vNormal; - varying vec3 vRefract; - - void main() { - - vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); - vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); - vec3 worldNormal = normalize ( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal ); - - vNormal = normalize( normalMatrix * normal ); - - vec3 I = worldPosition.xyz - cameraPosition; - vRefract = refract( normalize( I ), worldNormal, 1.02 ); - - gl_Position = projectionMatrix * mvPosition; - - }`,fragmentShader:` - - uniform vec3 uBaseColor; - - uniform vec3 uDirLightPos; - uniform vec3 uDirLightColor; - - uniform vec3 uAmbientLightColor; - - varying vec3 vNormal; - - varying vec3 vRefract; - - void main() { - - float directionalLightWeighting = max( dot( normalize( vNormal ), uDirLightPos ), 0.0); - vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; - - float intensity = smoothstep( - 0.5, 1.0, pow( length(lightWeighting), 20.0 ) ); - intensity += length(lightWeighting) * 0.2; - - float cameraWeighting = dot( normalize( vNormal ), vRefract ); - intensity += pow( 1.0 - length( cameraWeighting ), 6.0 ); - intensity = intensity * 0.2 + 0.3; - - if ( intensity < 0.50 ) { - - gl_FragColor = vec4( 2.0 * intensity * uBaseColor, 1.0 ); - - } else { - - gl_FragColor = vec4( 1.0 - 2.0 * ( 1.0 - intensity ) * ( 1.0 - uBaseColor ), 1.0 ); - - } - - #include - - }`},Tg1={uniforms:{uDirLightPos:{value:new I1},uDirLightColor:{value:new y1(15658734)},uAmbientLightColor:{value:new y1(328965)},uBaseColor:{value:new y1(15658734)},uLineColor1:{value:new y1(8421504)},uLineColor2:{value:new y1(0)},uLineColor3:{value:new y1(0)},uLineColor4:{value:new y1(0)}},vertexShader:` - - varying vec3 vNormal; - - void main() { - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - vNormal = normalize( normalMatrix * normal ); - - }`,fragmentShader:` - - uniform vec3 uBaseColor; - uniform vec3 uLineColor1; - uniform vec3 uLineColor2; - uniform vec3 uLineColor3; - uniform vec3 uLineColor4; - - uniform vec3 uDirLightPos; - uniform vec3 uDirLightColor; - - uniform vec3 uAmbientLightColor; - - varying vec3 vNormal; - - void main() { - - float camera = max( dot( normalize( vNormal ), vec3( 0.0, 0.0, 1.0 ) ), 0.4); - float light = max( dot( normalize( vNormal ), uDirLightPos ), 0.0); - - gl_FragColor = vec4( uBaseColor, 1.0 ); - - if ( length(uAmbientLightColor + uDirLightColor * light) < 1.00 ) { - - gl_FragColor *= vec4( uLineColor1, 1.0 ); - - } - - if ( length(uAmbientLightColor + uDirLightColor * camera) < 0.50 ) { - - gl_FragColor *= vec4( uLineColor2, 1.0 ); - - } - - #include - - }`},kg1={uniforms:{uDirLightPos:{value:new I1},uDirLightColor:{value:new y1(15658734)},uAmbientLightColor:{value:new y1(328965)},uBaseColor:{value:new y1(16777215)},uLineColor1:{value:new y1(0)},uLineColor2:{value:new y1(0)},uLineColor3:{value:new y1(0)},uLineColor4:{value:new y1(0)}},vertexShader:` - - varying vec3 vNormal; - - void main() { - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - vNormal = normalize( normalMatrix * normal ); - - }`,fragmentShader:` - - uniform vec3 uBaseColor; - uniform vec3 uLineColor1; - uniform vec3 uLineColor2; - uniform vec3 uLineColor3; - uniform vec3 uLineColor4; - - uniform vec3 uDirLightPos; - uniform vec3 uDirLightColor; - - uniform vec3 uAmbientLightColor; - - varying vec3 vNormal; - - void main() { - - float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0); - vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; - - gl_FragColor = vec4( uBaseColor, 1.0 ); - - if ( length(lightWeighting) < 1.00 ) { - - if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) { - - gl_FragColor = vec4( uLineColor1, 1.0 ); - - } - - } - - if ( length(lightWeighting) < 0.75 ) { - - if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) { - - gl_FragColor = vec4( uLineColor2, 1.0 ); - - } - - } - - if ( length(lightWeighting) < 0.50 ) { - - if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) { - - gl_FragColor = vec4( uLineColor3, 1.0 ); - - } - - } - - if ( length(lightWeighting) < 0.3465 ) { - - if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) { - - gl_FragColor = vec4( uLineColor4, 1.0 ); - - } - - } - - #include - - }`},Sg1={uniforms:{uDirLightPos:{value:new I1},uDirLightColor:{value:new y1(15658734)},uAmbientLightColor:{value:new y1(328965)},uBaseColor:{value:new y1(16777215)},uLineColor1:{value:new y1(0)}},vertexShader:` - - varying vec3 vNormal; - - void main() { - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - vNormal = normalize( normalMatrix * normal ); - - }`,fragmentShader:` - - uniform vec3 uBaseColor; - uniform vec3 uLineColor1; - uniform vec3 uLineColor2; - uniform vec3 uLineColor3; - uniform vec3 uLineColor4; - - uniform vec3 uDirLightPos; - uniform vec3 uDirLightColor; - - uniform vec3 uAmbientLightColor; - - varying vec3 vNormal; - - void main() { - - float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0); - vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; - - gl_FragColor = vec4( uBaseColor, 1.0 ); - - if ( length(lightWeighting) < 1.00 ) { - - if ( ( mod(gl_FragCoord.x, 4.001) + mod(gl_FragCoord.y, 4.0) ) > 6.00 ) { - - gl_FragColor = vec4( uLineColor1, 1.0 ); - - } - - } - - if ( length(lightWeighting) < 0.50 ) { - - if ( ( mod(gl_FragCoord.x + 2.0, 4.001) + mod(gl_FragCoord.y + 2.0, 4.0) ) > 6.00 ) { - - gl_FragColor = vec4( uLineColor1, 1.0 ); - - } - - } - - #include - - }`};var xg1={name:"TriangleBlurShader",uniforms:{texture:{value:null},delta:{value:new p1(1,1)}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - #include - - #define ITERATIONS 10.0 - - uniform sampler2D texture; - uniform vec2 delta; - - varying vec2 vUv; - - void main() { - - vec4 color = vec4( 0.0 ); - - float total = 0.0; - - // randomize the lookup values to hide the fixed number of samples - - float offset = rand( vUv ); - - for ( float t = -ITERATIONS; t <= ITERATIONS; t ++ ) { - - float percent = ( t + offset - 0.5 ) / ITERATIONS; - float weight = 1.0 - abs( percent ); - - color += texture2D( texture, vUv + delta * percent ) * weight; - total += weight; - - } - - gl_FragColor = color / total; - - }`};var bg1={name:"VelocityShader",uniforms:u0.merge([M0.common,M0.displacementmap,{modelMatrixPrev:{value:new Y0},currentProjectionViewMatrix:{value:new Y0},previousProjectionViewMatrix:{value:new Y0}}]),vertexShader:` -#define NORMAL - -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - - varying vec3 vViewPosition; - -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -uniform mat4 previousProjectionViewMatrix; -uniform mat4 currentProjectionViewMatrix; - -uniform mat4 modelMatrixPrev; - -varying vec4 clipPositionCurrent; -varying vec4 clipPositionPrevious; - -void main() { - - - #include - - #include - #include - #include - #include - #include - #include - - #include - #include - #include - #include - #include - -#ifdef USE_SKINNING - - vec4 mvPosition = modelViewMatrix * skinned; - clipPositionCurrent = currentProjectionViewMatrix * modelMatrix * skinned; - clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * skinned; - -#else - - vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 ); - clipPositionCurrent = currentProjectionViewMatrix * modelMatrix * vec4( transformed, 1.0 ); - clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * vec4( transformed, 1.0 ); - -#endif - - gl_Position = projectionMatrix * mvPosition; - - #include - #include -} -`,fragmentShader:` -#define NORMAL - -uniform float opacity; - -#include -#include -#include -#include -#include -#include -#include - -varying vec4 clipPositionCurrent; -varying vec4 clipPositionPrevious; - -void main() { - - vec4 diffuseColor = vec4( 1.0 ); - diffuseColor.a = opacity; - - #include - #include - #include - - vec2 ndcPositionCurrent = clipPositionCurrent.xy/clipPositionCurrent.w; - vec2 ndcPositionPrevious = clipPositionPrevious.xy/clipPositionPrevious.w; - vec2 vel = ( ndcPositionCurrent - ndcPositionPrevious ) * 0.5; - vel = vel * 0.5 + 0.5; - vec2 v1 = packDepthToRG(vel.x); - vec2 v2 = packDepthToRG(vel.y); - gl_FragColor = vec4(v1.x, v1.y, v2.x, v2.y); - - #include - -} - -`};var dg1={uniforms:{u_size:{value:new I1(1,1,1)},u_renderstyle:{value:0},u_renderthreshold:{value:0.5},u_clim:{value:new p1(1,1)},u_data:{value:null},u_cmdata:{value:null}},vertexShader:` - - varying vec4 v_nearpos; - varying vec4 v_farpos; - varying vec3 v_position; - - void main() { - // Prepare transforms to map to "camera view". See also: - // https://threejs.org/docs/#api/renderers/webgl/WebGLProgram - mat4 viewtransformf = modelViewMatrix; - mat4 viewtransformi = inverse(modelViewMatrix); - - // Project local vertex coordinate to camera position. Then do a step - // backward (in cam coords) to the near clipping plane, and project back. Do - // the same for the far clipping plane. This gives us all the information we - // need to calculate the ray and truncate it to the viewing cone. - vec4 position4 = vec4(position, 1.0); - vec4 pos_in_cam = viewtransformf * position4; - - // Intersection of ray and near clipping plane (z = -1 in clip coords) - pos_in_cam.z = -pos_in_cam.w; - v_nearpos = viewtransformi * pos_in_cam; - - // Intersection of ray and far clipping plane (z = +1 in clip coords) - pos_in_cam.z = pos_in_cam.w; - v_farpos = viewtransformi * pos_in_cam; - - // Set varyings and output pos - v_position = position; - gl_Position = projectionMatrix * viewMatrix * modelMatrix * position4; - }`,fragmentShader:` - - precision highp float; - precision mediump sampler3D; - - uniform vec3 u_size; - uniform int u_renderstyle; - uniform float u_renderthreshold; - uniform vec2 u_clim; - - uniform sampler3D u_data; - uniform sampler2D u_cmdata; - - varying vec3 v_position; - varying vec4 v_nearpos; - varying vec4 v_farpos; - - // The maximum distance through our rendering volume is sqrt(3). - const int MAX_STEPS = 887; // 887 for 512^3, 1774 for 1024^3 - const int REFINEMENT_STEPS = 4; - const float relative_step_size = 1.0; - const vec4 ambient_color = vec4(0.2, 0.4, 0.2, 1.0); - const vec4 diffuse_color = vec4(0.8, 0.2, 0.2, 1.0); - const vec4 specular_color = vec4(1.0, 1.0, 1.0, 1.0); - const float shininess = 40.0; - - void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray); - void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray); - - float sample1(vec3 texcoords); - vec4 apply_colormap(float val); - vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray); - - - void main() { - // Normalize clipping plane info - vec3 farpos = v_farpos.xyz / v_farpos.w; - vec3 nearpos = v_nearpos.xyz / v_nearpos.w; - - // Calculate unit vector pointing in the view direction through this fragment. - vec3 view_ray = normalize(nearpos.xyz - farpos.xyz); - - // Compute the (negative) distance to the front surface or near clipping plane. - // v_position is the back face of the cuboid, so the initial distance calculated in the dot - // product below is the distance from near clip plane to the back of the cuboid - float distance = dot(nearpos - v_position, view_ray); - distance = max(distance, min((-0.5 - v_position.x) / view_ray.x, - (u_size.x - 0.5 - v_position.x) / view_ray.x)); - distance = max(distance, min((-0.5 - v_position.y) / view_ray.y, - (u_size.y - 0.5 - v_position.y) / view_ray.y)); - distance = max(distance, min((-0.5 - v_position.z) / view_ray.z, - (u_size.z - 0.5 - v_position.z) / view_ray.z)); - - // Now we have the starting position on the front surface - vec3 front = v_position + view_ray * distance; - - // Decide how many steps to take - int nsteps = int(-distance / relative_step_size + 0.5); - if ( nsteps < 1 ) - discard; - - // Get starting location and step vector in texture coordinates - vec3 step = ((v_position - front) / u_size) / float(nsteps); - vec3 start_loc = front / u_size; - - // For testing: show the number of steps. This helps to establish - // whether the rays are correctly oriented - //'gl_FragColor = vec4(0.0, float(nsteps) / 1.0 / u_size.x, 1.0, 1.0); - //'return; - - if (u_renderstyle == 0) - cast_mip(start_loc, step, nsteps, view_ray); - else if (u_renderstyle == 1) - cast_iso(start_loc, step, nsteps, view_ray); - - if (gl_FragColor.a < 0.05) - discard; - } - - - float sample1(vec3 texcoords) { - /* Sample float value from a 3D texture. Assumes intensity data. */ - return texture(u_data, texcoords.xyz).r; - } - - - vec4 apply_colormap(float val) { - val = (val - u_clim[0]) / (u_clim[1] - u_clim[0]); - return texture2D(u_cmdata, vec2(val, 0.5)); - } - - - void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) { - - float max_val = -1e6; - int max_i = 100; - vec3 loc = start_loc; - - // Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with - // non-constant expression. So we use a hard-coded max, and an additional condition - // inside the loop. - for (int iter=0; iter= nsteps) - break; - // Sample from the 3D texture - float val = sample1(loc); - // Apply MIP operation - if (val > max_val) { - max_val = val; - max_i = iter; - } - // Advance location deeper into the volume - loc += step; - } - - // Refine location, gives crispier images - vec3 iloc = start_loc + step * (float(max_i) - 0.5); - vec3 istep = step / float(REFINEMENT_STEPS); - for (int i=0; i= nsteps) - break; - - // Sample from the 3D texture - float val = sample1(loc); - - if (val > low_threshold) { - // Take the last interval in smaller steps - vec3 iloc = loc - 0.5 * step; - vec3 istep = step / float(REFINEMENT_STEPS); - for (int i=0; i u_renderthreshold) { - gl_FragColor = add_lighting(val, iloc, dstep, view_ray); - return; - } - iloc += istep; - } - } - - // Advance location deeper into the volume - loc += step; - } - } - - - vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray) - { - // Calculate color by incorporating lighting - - // View direction - vec3 V = normalize(view_ray); - - // calculate normal vector from gradient - vec3 N; - float val1, val2; - val1 = sample1(loc + vec3(-step[0], 0.0, 0.0)); - val2 = sample1(loc + vec3(+step[0], 0.0, 0.0)); - N[0] = val1 - val2; - val = max(max(val1, val2), val); - val1 = sample1(loc + vec3(0.0, -step[1], 0.0)); - val2 = sample1(loc + vec3(0.0, +step[1], 0.0)); - N[1] = val1 - val2; - val = max(max(val1, val2), val); - val1 = sample1(loc + vec3(0.0, 0.0, -step[2])); - val2 = sample1(loc + vec3(0.0, 0.0, +step[2])); - N[2] = val1 - val2; - val = max(max(val1, val2), val); - - float gm = length(N); // gradient magnitude - N = normalize(N); - - // Flip normal so it points towards viewer - float Nselect = float(dot(N, V) > 0.0); - N = (2.0 * Nselect - 1.0) * N; // == Nselect * N - (1.0-Nselect)*N; - - // Init colors - vec4 ambient_color = vec4(0.0, 0.0, 0.0, 0.0); - vec4 diffuse_color = vec4(0.0, 0.0, 0.0, 0.0); - vec4 specular_color = vec4(0.0, 0.0, 0.0, 0.0); - - // note: could allow multiple lights - for (int i=0; i<1; i++) - { - // Get light direction (make sure to prevent zero devision) - vec3 L = normalize(view_ray); //lightDirs[i]; - float lightEnabled = float( length(L) > 0.0 ); - L = normalize(L + (1.0 - lightEnabled)); - - // Calculate lighting properties - float lambertTerm = clamp(dot(N, L), 0.0, 1.0); - vec3 H = normalize(L+V); // Halfway vector - float specularTerm = pow(max(dot(H, N), 0.0), shininess); - - // Calculate mask - float mask1 = lightEnabled; - - // Calculate colors - ambient_color += mask1 * ambient_color; // * gl_LightSource[i].ambient; - diffuse_color += mask1 * lambertTerm; - specular_color += mask1 * specularTerm * specular_color; - } - - // Calculate final color by componing different components - vec4 final_color; - vec4 color = apply_colormap(val); - final_color = color * (ambient_color + diffuse_color) + specular_color; - final_color.a = color.a; - return final_color; - }`};var IX1=new Array(4),qX1=new ArrayBuffer(5120),Kc=0;for(let A=0;A<5;A++)IX1[A]=new Uint32Array(qX1,Kc,256),Kc+=1024;class VB{static createButton(A,Q={}){let J=document.createElement("button");function K(){let X=null;async function E(I){I.addEventListener("end",H),await A.xr.setSession(I),J.textContent="EXIT VR",X=I}function H(){X.removeEventListener("end",H),J.textContent="ENTER VR",X=null}J.style.display="",J.style.cursor="pointer",J.style.left="calc(50% - 50px)",J.style.width="100px",J.textContent="ENTER VR";let $={...Q,optionalFeatures:["local-floor","bounded-floor","layers",...Q.optionalFeatures||[]]};if(J.onmouseenter=function(){J.style.opacity="1.0"},J.onmouseleave=function(){J.style.opacity="0.5"},J.onclick=function(){if(X===null)navigator.xr.requestSession("immersive-vr",$).then(E);else if(X.end(),navigator.xr.offerSession!==void 0)navigator.xr.offerSession("immersive-vr",$).then(E).catch((I)=>{console.warn(I)})},navigator.xr.offerSession!==void 0)navigator.xr.offerSession("immersive-vr",$).then(E).catch((I)=>{console.warn(I)})}function C(){J.style.display="",J.style.cursor="auto",J.style.left="calc(50% - 75px)",J.style.width="150px",J.onmouseenter=null,J.onmouseleave=null,J.onclick=null}function U(){C(),J.textContent="VR NOT SUPPORTED"}function Y(X){C(),console.warn("Exception when trying to call xr.isSessionSupported",X),J.textContent="VR NOT ALLOWED"}function Z(X){X.style.position="absolute",X.style.bottom="20px",X.style.padding="12px 6px",X.style.border="1px solid #fff",X.style.borderRadius="4px",X.style.background="rgba(0,0,0,0.1)",X.style.color="#fff",X.style.font="normal 13px sans-serif",X.style.textAlign="center",X.style.opacity="0.5",X.style.outline="none",X.style.zIndex="999"}if("xr"in navigator)return J.id="VRButton",J.style.display="none",Z(J),navigator.xr.isSessionSupported("immersive-vr").then(function(X){if(X?K():U(),X&&VB.xrSessionIsGranted)J.click()}).catch(Y),J;else{let X=document.createElement("a");if(window.isSecureContext===!1)X.href=document.location.href.replace(/^http:/,"https:"),X.innerHTML="WEBXR NEEDS HTTPS";else X.href="https://immersiveweb.dev/",X.innerHTML="WEBXR NOT AVAILABLE";return X.style.left="calc(50% - 90px)",X.style.width="180px",X.style.textDecoration="none",Z(X),X}}static registerSessionGrantedListener(){if(typeof navigator!=="undefined"&&"xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{VB.xrSessionIsGranted=!0})}}}VB.xrSessionIsGranted=!1;VB.registerSessionGrantedListener();var Cc={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:0.05,AxisTouchThreshold:0.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};var Mb1={xAxis:0,yAxis:0,button:0,state:Cc.ComponentState.DEFAULT};var hb1=new Y0,gb1=new I1;var s6;if(typeof window==="undefined")s6=self;else s6=window;s6.FFLShaderMaterial=n6;s6.LUTShaderMaterial=UA;var TB={WiiU:{m:null,f:null},Switch:{m:null,f:null},Miitomo:{m:null,f:null}},LX1=new AJ;//! NOTE: THIS ASSUMES THE ROOT IS THE PUBLIC FOLDER -function Yc(A,Q){return`/assets/models/miiBody${A}_${Q}.glb`}async function Uc(A){let Q=await LX1.loadAsync(A);var J=new F5(Q.scene);let K=Q.scene,C=Q.animations[0];J.clipAction(C,K).stop();let Y=Q.animations.find((X)=>X.name==="Wait"),Z=J.clipAction(Y,K);return Z.play(),Z.timeScale=0,J.update(),K}async function Gc(){TB.Miitomo.m=await Uc(Yc("M","miitomo")),TB.Miitomo.f=await Uc(Yc("F","miitomo"))}s6.bodyModels=TB;function Zc(A,Q="GeneratedType",J=0){if(J>5)return"";let K=" ".repeat(J),C=`${K}/** -${K} * @typedef {Object} ${Q} -`;Object.keys(A).forEach((U)=>{if(U.startsWith("_"))return;let Y=A[U],Z=typeof Y,X;if(Y===null)X="null";else if(Array.isArray(Y)){let E=Y.length>0?typeof Y[0]:"any";if(typeof Y[0]==="object"&&Y[0]!==null)E=Zc(Y[0],`${Q}_${U}_Item`,J+1);X=`Array<${E}>`}else if(Z==="object")X=Zc(Y,`${Q}_${U}`,J+1)||"Object";else X=Z;C+=`${K} * @property {${X}} ${U} -`}),C+=`${K} */ -`,console.log(C)}function yc1(typeName){if(typeof typeName!=="string")throw new Error;eval(` - const empty = new Uint8Array(${typeName}.size); - generateJSDoc(${typeName}.unpack(empty), typeName); - `)}if(g1.default===void 0){let A=s6._}var wB={OPA_BEARD:0,OPA_FACELINE:1,OPA_HAIR_NORMAL:2,OPA_FOREHEAD_NORMAL:3,XLU_MASK:4,XLU_NOSELINE:5,OPA_NOSE:6,OPA_HAT_NORMAL:7,XLU_GLASS:8,OPA_HAIR_CAP:9,OPA_FOREHEAD_CAP:10,OPA_HAT_CAP:11,MAX:12},qJ={POSITION:0,TEXCOORD:1,NORMAL:2,TANGENT:3,COLOR:4,MAX:5},$W={NONE:0,BACK:1,FRONT:2,MAX:3},FX1={CONSTANT:0,TEXTURE_DIRECT:1,RGB_LAYERED:2,ALPHA:3,LUMINANCE_ALPHA:4,ALPHA_OPA:5},QY={SHAPE_FACELINE:0,SHAPE_BEARD:1,SHAPE_NOSE:2,SHAPE_FOREHEAD:3,SHAPE_HAIR:4,SHAPE_CAP:5,SHAPE_MASK:6,SHAPE_NOSELINE:7,SHAPE_GLASS:8,MUSTACHE:9,MOUTH:10,EYEBROW:11,EYE:12,MOLE:13,FACE_MAKE:14,FACE_LINE:15,FACE_BEARD:16,FILL:17,SHAPE_MAX:9},kB={MIDDLE:0,HIGH:1,MAX:2},SB={NORMAL:0,MAX:70},qW={NORMAL:1,HAT:2,FACE_ONLY:4,FLATTEN_NOSE:8,NEW_EXPRESSIONS:16,NEW_MASK_ONLY:32},RX1=g1.default.struct([g1.default.uint32le("size"),g1.default.uint32le("stride"),g1.default.uintptr("ptr")]),zX1=g1.default.struct([g1.default.struct("attributeBuffers",[RX1],5)]),DX1=g1.default.struct([g1.default.uint32le("primitiveType"),g1.default.uint32le("indexCount"),g1.default.uint32le("_8"),g1.default.uintptr("pIndexBuffer")]),BD=g1.default.struct([g1.default.float32le("r"),g1.default.float32le("g"),g1.default.float32le("b"),g1.default.float32le("a")]),E3=g1.default.struct([g1.default.float32le("x"),g1.default.float32le("y"),g1.default.float32le("z")]),VX1=g1.default.struct([g1.default.uint32le("mode"),g1.default.uint32le("type"),g1.default.uintptr("pColorR"),g1.default.uintptr("pColorG"),g1.default.uintptr("pColorB"),g1.default.uintptr("pTexture2D")]),$3=g1.default.struct([g1.default.struct("attributeBufferParam",[zX1]),g1.default.struct("modulateParam",[VX1]),g1.default.uint32le("cullMode"),g1.default.struct("primitiveParam",[DX1])]),Wc=g1.default.struct([g1.default.uint8("data",10)]),l9=g1.default.struct([g1.default.int32le("miiVersion"),g1.default.struct("faceline",[g1.default.int32le("type"),g1.default.int32le("color"),g1.default.int32le("texture"),g1.default.int32le("make")]),g1.default.struct("hair",[g1.default.int32le("type"),g1.default.int32le("color"),g1.default.int32le("flip")]),g1.default.struct("eye",[g1.default.int32le("type"),g1.default.int32le("color"),g1.default.int32le("scale"),g1.default.int32le("aspect"),g1.default.int32le("rotate"),g1.default.int32le("x"),g1.default.int32le("y")]),g1.default.struct("eyebrow",[g1.default.int32le("type"),g1.default.int32le("color"),g1.default.int32le("scale"),g1.default.int32le("aspect"),g1.default.int32le("rotate"),g1.default.int32le("x"),g1.default.int32le("y")]),g1.default.struct("nose",[g1.default.int32le("type"),g1.default.int32le("scale"),g1.default.int32le("y")]),g1.default.struct("mouth",[g1.default.int32le("type"),g1.default.int32le("color"),g1.default.int32le("scale"),g1.default.int32le("aspect"),g1.default.int32le("y")]),g1.default.struct("beard",[g1.default.int32le("mustache"),g1.default.int32le("type"),g1.default.int32le("color"),g1.default.int32le("scale"),g1.default.int32le("y")]),g1.default.struct("glass",[g1.default.int32le("type"),g1.default.int32le("color"),g1.default.int32le("scale"),g1.default.int32le("y")]),g1.default.struct("mole",[g1.default.int32le("type"),g1.default.int32le("scale"),g1.default.int32le("x"),g1.default.int32le("y")]),g1.default.struct("body",[g1.default.int32le("height"),g1.default.int32le("build")]),g1.default.struct("personal",[g1.default.char16le("name",22),g1.default.char16le("creator",22),g1.default.int32le("gender"),g1.default.int32le("birthMonth"),g1.default.int32le("birthDay"),g1.default.int32le("favoriteColor"),g1.default.uint8("favorite"),g1.default.uint8("copyable"),g1.default.uint8("ngWord"),g1.default.uint8("localonly"),g1.default.int32le("regionMove"),g1.default.int32le("fontRegion"),g1.default.int32le("roomIndex"),g1.default.int32le("positionInRoom"),g1.default.int32le("birthPlatform")]),g1.default.struct("createID",[Wc]),g1.default.uint16le("padding_0"),g1.default.int32le("authorType"),g1.default.uint8("authorID",8)]),WW=96,XD=-2147483648,eC=(A)=>A|XD,AY=(A)=>A&~XD===0?A:A&~XD,UD=g1.default.struct([g1.default.char16le("name",22),g1.default.char16le("creator",22),g1.default.struct("createID",[Wc]),g1.default.byte("_padding0",2),g1.default.struct("skinColor",[BD]),g1.default.uint32le("flags"),g1.default.uint8("facelineType"),g1.default.uint8("hairType"),g1.default.byte("_padding1",2)]),MX1=g1.default.struct([g1.default.uintptr("pTexture2DRenderBufferColorTargetDepthTarget",4)]),wX1=g1.default.struct([g1.default.uintptr("pTextureFaceLine"),g1.default.struct("drawParamFaceLine",[$3]),g1.default.uintptr("pTextureFaceMake"),g1.default.struct("drawParamFaceMake",[$3]),g1.default.uintptr("pTextureFaceBeard"),g1.default.struct("drawParamFaceBeard",[$3]),g1.default.uintptr("pRenderTextureCompressorParam",2)]),Bc=g1.default.struct([g1.default.struct("drawParamRawMaskPartsEye",[$3],2),g1.default.struct("drawParamRawMaskPartsEyebrow",[$3],2),g1.default.struct("drawParamRawMaskPartsMouth",[$3]),g1.default.struct("drawParamRawMaskPartsMustache",[$3],2),g1.default.struct("drawParamRawMaskPartsMole",[$3]),g1.default.struct("drawParamRawMaskPartsFill",[$3])]),Ic=g1.default.struct([g1.default.uint8("partsTextures",340),g1.default.uintptr("pRawMaskDrawParam",SB.MAX),g1.default.byte("_remaining",284)]),MB=g1.default.struct([g1.default.struct("maskTextures",[Ic]),g1.default.struct("facelineTexture",[wX1])]),PX1=g1.default.struct([g1.default.uintptr("pRenderTextures",SB.MAX)]),_X1=1073741823,OJ=g1.default.struct([g1.default.uint32le("resolution"),g1.default.uint32le("allExpressionFlag",3),g1.default.uint32le("modelFlag"),g1.default.uint32le("resourceType")]);OJ.default={resolution:512,allExpressionFlag:new Uint32Array([1,0,0]),modelFlag:qW.NORMAL,resourceType:kB.HIGH};var HD=OJ.default,TX1=g1.default.struct([g1.default.struct("min",[E3]),g1.default.struct("max",[E3])]),kX1=g1.default.struct([g1.default.struct("hatTranslate",[E3]),g1.default.struct("headFrontRotate",[E3]),g1.default.struct("headFrontTranslate",[E3]),g1.default.struct("headSideRotate",[E3]),g1.default.struct("headSideTranslate",[E3]),g1.default.struct("headTopRotate",[E3]),g1.default.struct("headTopTranslate",[E3])]),IW=g1.default.struct([g1.default.struct("charInfo",[l9]),g1.default.struct("charModelDesc",[OJ]),g1.default.uint32le("expression"),g1.default.uintptr("pTextureTempObject"),g1.default.struct("drawParam",[$3],wB.MAX),g1.default.uintptr("pShapeData",wB.MAX),g1.default.struct("facelineRenderTexture",[MX1]),g1.default.uintptr("pCapGlassNoselineTextures",3),g1.default.struct("maskTextures",[PX1]),g1.default.struct("beardHairFaceCenterPos",[E3],3),g1.default.struct("partsTransform",[kX1]),g1.default.uint32le("modelType"),g1.default.struct("boundingBox",[TX1],3)]),qc={OFFICIAL:0,DEFAULT:1,MIDDLE_DB:2,STORE_DATA_OFFICIAL:3,STORE_DATA:4,BUFFER:5,DIRECT_POINTER:6},Xc=g1.default.struct([g1.default.uint32le("dataSource"),g1.default.uintptr("pBuffer"),g1.default.uint16le("index")]),hc1={MALE:0,FEMALE:1,ALL:2},gc1={CHILD:0,ADULT:1,ELDER:2,ALL:3},bc1={BLACK:0,WHITE:1,ASIAN:2,ALL:3},Ec=g1.default.struct([g1.default.uintptr("pData",kB.MAX),g1.default.uint32le("size",kB.MAX)]),ZD={R8_UNORM:0,R8_G8_UNORM:1,R8_G8_B8_A8_UNORM:2,MAX:3},$c=g1.default.struct([g1.default.uint16le("width"),g1.default.uint16le("height"),g1.default.uint8("mipCount"),g1.default.uint8("format"),g1.default.uint8("isGX2Tiled"),g1.default.byte("_padding",1),g1.default.uint32le("imageSize"),g1.default.uintptr("imagePtr"),g1.default.uint32le("mipSize"),g1.default.uintptr("mipPtr"),g1.default.uint32le("mipLevelOffset",13)]),Hc=g1.default.struct([g1.default.uintptr("pObj"),g1.default.uint8("useOriginalTileMode"),g1.default.byte("_padding",3),g1.default.uintptr("pCreateFunc"),g1.default.uintptr("pDeleteFunc")]);class Oc{constructor(A=s6.Module){this.module=A,this.textures=/*@__PURE__*/new Map,this.textureCallbackPtr=null,this._setupTextureCallbacks()}_setupTextureCallbacks(){let A=this.module;this.createCallback=A.addFunction(this._textureCreateFunc.bind(this),"vppp"),this.deleteCallback=A.addFunction(this._textureDeleteFunc.bind(this),"vpp");let Q={pObj:0,useOriginalTileMode:!1,_padding:[0,0,0],pCreateFunc:this.createCallback,pDeleteFunc:this.deleteCallback},J=Hc.pack(Q);this.textureCallbackPtr=A._malloc(Hc.size),A.HEAPU8.set(new Uint8Array(J),this.textureCallbackPtr),A._FFLSetTextureCallback(this.textureCallbackPtr)}_getTextureFormat(A){let Q=Number(G5)<137,J=Q?kQ:E8,K=Q?tU:Y9,U={[ZD.R8_UNORM]:J,[ZD.R8_G8_UNORM]:K,[ZD.R8_G8_B8_A8_UNORM]:xA}[A];if(U===void 0)throw new Error(`_textureCreateFunc: Unexpected FFLTextureFormat value: ${A}`);return U}_textureCreateFunc(A,Q,J){let K=this.module.HEAPU8.subarray(Q,Q+$c.size),C=$c.unpack(K),U=this._getTextureFormat(C.format),Y=this.module.HEAPU8.slice(C.imagePtr,C.imagePtr+C.imageSize),Z=new fA(Y,C.width,C.height,U,dA);if(Z.magFilter=HA,Z.minFilter=HA,Number(G5)>=138)Z.minFilter=o2,Z.generateMipmaps=!1,this._addMipmaps(Z,C);Z.needsUpdate=!0,this.set(Z.id,Z),this.module.HEAPU32[J/4]=Z.id}_addMipmaps(A,Q){if(Q.mipPtr===0||Q.mipCount<2)return;let J=[1,2,4][Q.format];if(!J)throw new Error(`_addMipmaps: Unexpected FFLTextureFormat value: ${Q.format}`);for(let K=1;K>K),Y=Math.max(1,Q.height>>K),Z=U*Y*J,X=Q.mipPtr+C,E=this.module.HEAPU8.slice(X,X+Z);A.mipmaps.push({data:E,width:U,height:Y})}}_textureDeleteFunc(A,Q){let J=this.module.HEAPU32[Q/4],K=this.textures.get(J)}get(A){let Q=this.textures.get(A);if(!Q)console.error("Unknown texture",A);return Q}set(A,Q){Q._dispose=Q.dispose.bind(Q),Q.dispose=()=>{this.delete(A)},this.textures.set(A,Q)}delete(A){let Q=this.textures.get(A);if(Q)Q._dispose(),Q.source=null,this.textures.delete(A)}}function GD(A,Q){let J;if(typeof Q!=="number")J=`Unexpected type for FFLResult from ${A}: ${typeof Q}`;else if(Q!==0)J=`${A} failed with FFLResult: ${Q}`;if(J)throw new Error(J)}async function SX1(A,Q){let J,K;try{if(A instanceof ArrayBuffer)A=new Uint8Array(A);if(A instanceof Uint8Array)console.warn("initializeFFL -> _loadDataIntoHeap: resource was passed as Uint8Array/ArrayBuffer. Please pass in a fetch Response instance for improved efficiency."),J=A.length,K=Q._malloc(J),console.debug(`loadDataIntoHeap: Loading from Uint8Array. Size: ${J}, pointer: ${K}`),Q.HEAPU8.set(A,K);else if(A instanceof Response){if(!A.body)throw new Error("Fetch response is not streamable.");let C=A.headers.get("Content-Length");if(!C)throw new Error("Fetch response missing Content-Length.");J=parseInt(C,10),K=Q._malloc(J),console.debug(`loadDataIntoHeap: Streaming ${J} bytes from fetch response. URL: ${A.url}, pointer: ${K}`);let U=A.body.getReader(),Y=K;while(!0){let{done:Z,value:X}=await U.read();if(Z)break;Q.HEAPU8.set(X,Y),Y+=X.length}}else throw new Error("loadDataIntoHeap: type is not Uint8Array or Response");return{pointer:K,size:J}}catch(C){if(K)Q._free(K);throw C}}var GW;async function jX1(A,Q=s6.Module){console.debug("initializeFFL: Entrypoint, waiting for module to be ready.");let J;return new Promise((K)=>{if(!Q.calledRun&&!Q.onRuntimeInitialized)Q.onRuntimeInitialized=()=>{console.debug("initializeFFL: Emscripten runtime initialized, resolving."),K()},console.debug(`initializeFFL: module.calledRun: ${Q.calledRun}, module.onRuntimeInitialized: ${Q.onRuntimeInitialized} / << assigned and waiting.`);else console.debug("initializeFFL: Assuming module is ready."),K()}).then(async()=>{if(A instanceof Promise)A=await A}).then(()=>{return SX1(A,Q)}).then(({pointer:K,size:C})=>{console.debug(`initializeFFL: Resource loaded into heap. Pointer: ${K}, Size: ${C}`);let U={pData:[0,0],size:[0,0]};U.pData[kB.HIGH]=K,U.size[kB.HIGH]=C,GW=U;let Y=Ec.pack(U);J=Q._malloc(Ec.size),Q.HEAPU8.set(Y,J);let Z=Q._FFLInitRes(0,J);GD("FFLInitRes",Z),Q._FFLInitResGPUStep(),Q._FFLSetNormalIsSnorm8_8_8_8(!0),Q._FFLSetTextureFlipY(!0)}).catch((K)=>{throw Q._free(),console.error("initializeFFL failed:",K),K}).finally(()=>{if(J)Q._free(J)})}async function Nc(A=null,Q=s6.Module){if(!A&&typeof document!=="undefined"){let K=document.querySelector("meta[itemprop=ffl-js-resource-fetch-path]");if(!K||!K.getAttribute("content"))throw new Error('initializeFFLWithResource: Element not found or does not have "content" attribute with path to FFL resource: meta[itemprop=ffl-js-resource-fetch-path]');A=K.getAttribute("content")}if(!A)throw new Error("initializeFFLWithResource: resourcePath must be a string");try{let K=await fetch(A);await jX1(K,Q),s6.FFLTextures=new Oc(Q),console.debug("initializeFFLWithResource: FFLiManager and TextureManager initialized, exiting")}catch(K){throw alert(`Error initializing FFL with resource: ${K}`),K}}function fc1(A){if(!GW){console.warn("exitFFL was called when FFL is not initialized.");return}console.debug("exitFFL called, _resourceDesc:",GW),A._FFLExit(),GW.pData.forEach((Q)=>{if(Q)A._free(_fflResourcePtr)})}class PB{constructor(A,Q=s6.Module,J=s6.FFLShaderMaterial){this._module=Q,this._materialClass=J,this._ptr=A,this.__ptr=A;let K=this._module.HEAPU8.subarray(A,A+IW.size);this._model=IW.unpack(K),this._facelineTarget=null,this._maskTargets=new Array(SB.MAX).fill(null),this.meshes=new cA,this._addCharModelMeshes(Q)}_addCharModelMeshes(A){for(let Q=0;Q{if(!A)return;A.dispose(),this._maskTargets[Q]=null})}dispose(){this._finalizeCharModel(),OD(this.meshes),this.meshes=null,this._disposeTextures()}getStoreData(){let A=this._getCharInfoUint8Array(),Q=this._module,J=Q._malloc(l9.size),K=Q._malloc(WW);Q.HEAPU8.set(A,J);let C=Q._FFLpGetStoreDataFromCharInfo(K,J),U=Q.HEAPU8.slice(K,K+WW);if(Q._free(J),Q._free(K),!C)throw new Error("getStoreData: call to FFLpGetStoreDataFromCharInfo returned false, CharInfo verification probably failed");return U}setExpression(A){this._model.expression=A;let Q=this._maskTargets[A];if(!Q||!Q.texture)throw new Error(`setExpression: this._maskTargets[${A}].texture is not a valid texture`);let J=this.meshes.getObjectById(this._maskID);if(!J)throw new Error("setExpression: this.meshes[FFLiShapeType.XLU_MASK] does not exist, cannot set expression on the mask");J.material.map=Q.texture,J.material.needsUpdate=!0}get expression(){return this._model.expression}set expression(A){throw new Error("nope you cannot do this, try setExpression instead")}get facelineColor(){if(!this._facelineColor)this._facelineColor=this._getFacelineColor();return this._facelineColor}get favoriteColor(){if(!this._favoriteColor)this._favoriteColor=this._getFavoriteColor();return this._favoriteColor}get partsTransform(){if(!this._partsTransform)this._partsTransform=this._getPartsTransform();return this._partsTransform}get boundingBox(){if(!this._boundingBox)this._boundingBox=this._getBoundingBox();return this._boundingBox}static BodyScaleMode={Apply:0,Limit:1};getBodyScale(A=PB.BodyScaleMode.Apply){let Q=this._model.charInfo.body.build,J=this._model.charInfo.body.height,K=new I1;switch(A){case PB.BodyScaleMode.Apply:{K.x=Q*(J*0.003671875+0.4)/128+J*0.001796875+0.4,K.y=J*0.006015625+0.5;break}case PB.BodyScaleMode.Limit:{let C=J/128;K.y=C*0.55+0.6,K.x=C*0.3+0.6,K.x=(C*0.6+0.8-K.x)*(Q/128)+K.x;break}default:throw new Error(`getBodyScale: Unexpected value for scaleMode: ${A}`)}return K.z=K.x,K}}var HW={GrayNormal:0,BluePresent:1,RedRegular:2,GoldSpecial:3},pc1={[HW.GrayNormal]:new y1(4212558),[HW.BluePresent]:new y1(2637946),[HW.RedRegular]:new y1(7348245),[HW.GoldSpecial]:new y1(12623920)};function vX1(A,Q){let J=Q._malloc(l9.size),K={dataSource:qc.DIRECT_POINTER,pBuffer:J,index:0};if(!(A instanceof Uint8Array))try{if(typeof A!=="object")throw new Error("_allocateModelSource: data passed in is not FFLiCharInfo object or Uint8Array");A=l9.pack(A)}catch(C){throw Q._free(J),C}switch(A.length){case WW:{let C=Q._malloc(WW);Q.HEAPU8.set(A,C);let U=Q._FFLpGetCharInfoFromStoreData(J,C);if(Q._free(C),!U)throw Q._free(J),new Error("_allocateModelSource: call to FFLpGetCharInfoFromStoreData returned false, CharInfo verification probably failed");break}case l9.size:Q.HEAPU8.set(A,J);break;case JY.size+1:A=dX1(A);case JY.size:{let C=JY.unpack(A),U=LD(C);A=l9.pack(U),Q.HEAPU8.set(A,J);break}default:throw Q._free(J),new Error(`_allocateModelSource: Unknown data length: ${A.length}`)}return K}function xX1(A,Q,J=!1){let K=0,C=!1;if(typeof A==="number")K=A,C=!1;else C=!0,K=Q._malloc(l9.size),Q.HEAPU8.set(A,K);let U=Q._FFLiVerifyCharInfoWithReason(K,J);if(C)Q._free(K);if(U!==0)throw new Error(`FFLiVerifyCharInfoWithReason failed with result: ${U}`)}function uc1(A,Q,J,K){let C=A._malloc(l9.size);A._FFLiGetRandomCharInfo(C,Q,J,K);let U=A.HEAPU8.slice(C,C+l9.size);return A._free(C),U}function yX1(A){function Q(K){if(K>=SB.MAX)throw new Error(`makeExpressionFlag: input out of range: got ${K}, max: ${SB.MAX}`)}let J=new Uint32Array([0,0,0]);if(typeof A==="number")A=[A];else if(!Array.isArray(A))throw new Error("makeExpressionFlag: expected array or single number");for(let K of A){Q(K);let C=Math.floor(K/32),U=K%32;J[C]|=1<{let $=parseInt(E);if(H.size===0&&$!==qJ.POSITION)return;switch($){case qJ.POSITION:{let I=H.ptr/4,N=Q.HEAPF32.subarray(I,I+C*4),F=new L6(N,4);U.setAttribute("position",new B8(F,3,0));break}case qJ.NORMAL:{let I=Q.HEAP8.subarray(H.ptr,H.ptr+H.size);U.setAttribute("normal",new ZC(I,H.stride,!0));break}case qJ.TANGENT:{let I=Q.HEAP8.subarray(H.ptr,H.ptr+H.size);U.setAttribute("tangent",new ZC(I,H.stride,!0));break}case qJ.TEXCOORD:{let I=H.ptr/4,N=Q.HEAPF32.subarray(I,I+C*2);U.setAttribute("uv",new L0(N,H.stride/4));break}case qJ.COLOR:{if(H.stride===0)break;let I=Q.HEAPU8.subarray(H.ptr,H.ptr+H.size);U.setAttribute("_color",new UZ(I,H.stride,!0));break}}}),U}function gX1(A,Q=s6.FFLTextures){if(!A.pTexture2D||A.type===QY.SHAPE_FACELINE||A.type===QY.SHAPE_MASK)return null;let J=A.pTexture2D,K=Q.get(J);if(!K)throw new Error(`_getTextureFromModulateParam: Texture not found for ${J}.`);if([QY.SHAPE_FACELINE,QY.SHAPE_CAP,QY.SHAPE_GLASS].includes(A.type))K.wrapS=l8,K.wrapT=l8,K.needsUpdate=!0;return K}function bX1(A,Q){let J=new X0(0,0,0,0);if(A.pColorR!==0){let C=A.pColorR/4,U=Q.HEAPF32.subarray(C,C+4);J=new X0(U[0],U[1],U[2],U[3])}if(A.pColorG!==0&&A.pColorB!==0)J=[_B(A.pColorR,Q),_B(A.pColorG,Q),_B(A.pColorB,Q)];let K=!(A.mode!==FX1.CONSTANT&&A.type>=QY.SHAPE_MAX);return{modulateMode:A.mode,modulateType:A.type,modulateColor:J,lightEnable:K}}function _B(A,Q){if(!A)return console.error("getVector4FromFFLColorPtr: Received null pointer"),new X0(0,0,0,0);let J=Q.HEAPF32.subarray(A/4,A/4+4);return new X0(J[0],J[1],J[2],J[3])}var WD=!1;function CY(A,Q){let J=A._module,K=A._getTextureTempObject();if(fX1(A,K,Q,J),pX1(A,K,Q,J),!WD)A._finalizeCharModel();A.setExpression(A.expression)}var ED=()=>null,$D=()=>null;function mc1(A){ED=async(Q,J)=>{let K=await ND(Q,J,!0);A(K),ED=()=>null}}function Rc(A){$D=async(Q,J)=>{let K=await ND(Q,J,!0);A(K),$D=()=>null}}function fX1(A,Q,J,K){let C=A._getFacelineTempObjectPtr();K._FFLiInvalidateTempObjectFacelineTexture(C);let U=[Q.facelineTexture.drawParamFaceLine,Q.facelineTexture.drawParamFaceBeard,Q.facelineTexture.drawParamFaceMake].filter((I)=>I&&I.modulateParam.pTexture2D!==0);if(U.length===0)return;let Y=A.facelineColor,{scene:Z}=zc(U,Y,A._materialClass,A._module,J),X=A._getResolution()/2,E=A._getResolution(),H={depthBuffer:!1,stencilBuffer:!1,wrapS:l8,wrapT:l8},$=qD(Z,ID(),J,X,E,H);if(ED($,J),mX1(A,$),!WD)K._FFLiDeleteTempObjectFacelineTexture(C,A._ptr,A._model.charModelDesc.resourceType);OD(Z)}function pX1(A,Q,J,K){let C=A._getMaskTempObjectPtr(),U=A._ptr+IW.fields.charModelDesc.offset+OJ.fields.allExpressionFlag.offset,Y=[];for(let Z=0;Z{OD(Z)}),!WD)K._FFLiDeleteTempObjectMaskTextures(C,U,A._model.charModelDesc.resourceType),K._FFLiDeleteTextureTempObject(A._ptr)}function uX1(A,Q,J,K){let C=[Q.drawParamRawMaskPartsMustache[0],Q.drawParamRawMaskPartsMustache[1],Q.drawParamRawMaskPartsMouth,Q.drawParamRawMaskPartsEyebrow[0],Q.drawParamRawMaskPartsEyebrow[1],Q.drawParamRawMaskPartsEye[0],Q.drawParamRawMaskPartsEye[1],Q.drawParamRawMaskPartsMole].filter((E)=>E&&E.primitiveParam.indexCount!==0);if(C.length===0)return console.error("No mask drawParams found"),null;let U={depthBuffer:!1,stencilBuffer:!1},{scene:Y}=zc(C,null,A._materialClass,K),Z=A._getResolution(),X=qD(Y,ID(),J,Z,Z,U);return $D(X,J),{target:X,scene:Y}}function mX1(A,Q){if(!Q||!Q.texture)throw new Error("setFaceline: passed in RenderTarget is invalid");A._facelineTarget=Q;let J=A.meshes.getObjectById(A._facelineID);if(!J)throw new Error("setFaceline: charModel.meshes[FFLiShapeType.OPA_FACELINE] does not exist");J.material.map=Q.texture,J.material.needsUpdate=!0}function zc(A,Q=null,J,K){let C=new Q8;C.background=Q||null;let U=[];return A.forEach((Y)=>{let Z=Fc(Y,J,K);if(Z)C.add(Z),U.push(Z)}),{scene:C,meshes:U}}function ID(A=!1){let Q=new o8(-1,1,A?-1:1,A?1:-1,0.1,10);return Q.position.z=1,Q}function qD(A,Q,J,K,C,U={}){let Y={minFilter:HA,magFilter:HA,...U},Z=new s0(K,C,Y),X=J.getRenderTarget();return J.setRenderTarget(Z),J.render(A,Q),J.setRenderTarget(X),Z}function OD(A,Q){if(A.traverse((J)=>{if(!J.isMesh)return;if(J.geometry)J.geometry.dispose();if(J.material){if(J.material.map)J.material.map.dispose();J.material.dispose()}}),Q&&Q instanceof Q8)Q.remove(A);A.children=[]}function ND(A,Q,J=!1){return new Promise((K)=>{let C=new Q8;C.background=null;let U=new BA({side:VA,map:A.texture,transparent:!0}),Y=new g8(2,2),Z=new _0(Y,U);C.add(Z);let X=ID(J),E=Q.getRenderTarget(),H=Q.outputColorSpace,$=new p1;Q.getSize($),Q.setRenderTarget(null),Q.outputColorSpace=e0?e0.workingColorSpace:null,Q.setSize(A.width,A.height,!1),Q.render(C,X);function I(){U.dispose(),Y.dispose(),C.remove(Z),Q.outputColorSpace=H,Q.setSize($.x,$.y,!1),Q.setRenderTarget(E)}if(typeof window==="undefined")Q.domElement.convertToBlob({type:"image/png"}).then((N)=>{K({type:"blob",result:N}),I()});else{let N=Q.domElement.toDataURL("image/png");K({type:"dataURL",result:N}),I()}})}function cc1(A,Q){if(!Q)console.warn(`appendImageFromDataUrl: you did not specify "container" so we will use document.body, don't be surprised if your image ends up in brazil`),Q=document.body;let J=new Image;J.src=A,Q.appendChild(J)}var q7={Face:0,MakeIcon:1,IconFovy45:2,AllBody:3};function cX1(A,Q=1,J=1){let K=Q/J;switch(A){case q7.Face:{let U=new kA(15,K,0.1,1000);return U.position.set(0,34.5,380),U.lookAt(0,34.3,0),U}case q7.MakeIcon:{let U=new kA(10,K,500,1000);return U.position.set(0,34.5,600),U.lookAt(0,34.5,0),U}case q7.IconFovy45:{let C=new kA(45,K,50,1000);return C.position.set(0,34,110),C.lookAt(0,34,0),C}case q7.AllBody:{let U=new kA(15,K,50,1500);return U.position.set(0,50,900),U.lookAt(0,105,0),U}default:throw new Error("getCameraForViewType: not implemented")}}function Dc(A,Q,J=q7.MakeIcon,K=256,C=256,U=!1){return new Promise((Y)=>{let Z=new Q8;Z.background=null;let X=A._getGender();if(U){let V,D,L,R;var E=A.getBodyScale();switch(X){case 0:{V=TB.Miitomo.m,D=V.getObjectByName("body_m"),L=V.getObjectByName("hands_m"),R=V.getObjectByName("legs_m");break}case 1:{V=TB.Miitomo.f,D=V.getObjectByName("body_f"),L=V.getObjectByName("hands_f"),R=V.getObjectByName("legs_f");break}}V.scale.set(1,E.y*10,1);var H=new DA().setFromObject(V);console.log("pos y:",H.max.y),V.position.set(0,-H.max.y,0),Z.add(V);var $=A._getFavoriteColor(!0);D.material=new UA({modulateType:9,modulateMode:0,modulateColor:new X0($.r,$.g,$.b,1)}),R.material=new UA({modulateType:10,modulateMode:0,modulateColor:new X0(0.3,0.3,0.3,1)})}Z.add(A.meshes.clone());let I=cX1(J),N=qD(Z,I,Q,K,C),F=ND(N,Q);N.dispose(),Y(F)})}var JY=g1.default.struct([g1.default.uint8("beardColor"),g1.default.uint8("beardType"),g1.default.uint8("build"),g1.default.uint8("eyeAspect"),g1.default.uint8("eyeColor"),g1.default.uint8("eyeRotate"),g1.default.uint8("eyeScale"),g1.default.uint8("eyeType"),g1.default.uint8("eyeX"),g1.default.uint8("eyeY"),g1.default.uint8("eyebrowAspect"),g1.default.uint8("eyebrowColor"),g1.default.uint8("eyebrowRotate"),g1.default.uint8("eyebrowScale"),g1.default.uint8("eyebrowType"),g1.default.uint8("eyebrowX"),g1.default.uint8("eyebrowY"),g1.default.uint8("facelineColor"),g1.default.uint8("facelineMake"),g1.default.uint8("facelineType"),g1.default.uint8("facelineWrinkle"),g1.default.uint8("favoriteColor"),g1.default.uint8("gender"),g1.default.uint8("glassColor"),g1.default.uint8("glassScale"),g1.default.uint8("glassType"),g1.default.uint8("glassY"),g1.default.uint8("hairColor"),g1.default.uint8("hairFlip"),g1.default.uint8("hairType"),g1.default.uint8("height"),g1.default.uint8("moleScale"),g1.default.uint8("moleType"),g1.default.uint8("moleX"),g1.default.uint8("moleY"),g1.default.uint8("mouthAspect"),g1.default.uint8("mouthColor"),g1.default.uint8("mouthScale"),g1.default.uint8("mouthType"),g1.default.uint8("mouthY"),g1.default.uint8("mustacheScale"),g1.default.uint8("mustacheType"),g1.default.uint8("mustacheY"),g1.default.uint8("noseScale"),g1.default.uint8("noseType"),g1.default.uint8("noseY")]);function LD(A){return{miiVersion:0,faceline:{type:A.facelineType,color:A.facelineColor,texture:A.facelineWrinkle,make:A.facelineMake},hair:{type:A.hairType,color:eC(A.hairColor),flip:A.hairFlip},eye:{type:A.eyeType,color:eC(A.eyeColor),scale:A.eyeScale,aspect:A.eyeAspect,rotate:A.eyeRotate,x:A.eyeX,y:A.eyeY},eyebrow:{type:A.eyebrowType,color:eC(A.eyebrowColor),scale:A.eyebrowScale,aspect:A.eyebrowAspect,rotate:A.eyebrowRotate,x:A.eyebrowX,y:A.eyebrowY},nose:{type:A.noseType,scale:A.noseScale,y:A.noseY},mouth:{type:A.mouthType,color:eC(A.mouthColor),scale:A.mouthScale,aspect:A.mouthAspect,y:A.mouthY},beard:{mustache:A.mustacheType,type:A.beardType,color:eC(A.beardColor),scale:A.mustacheScale,y:A.mustacheY},glass:{type:A.glassType,color:eC(A.glassColor),scale:A.glassScale,y:A.glassY},mole:{type:A.moleType,scale:A.moleScale,x:A.moleX,y:A.moleY},body:{height:A.height,build:A.build},personal:{name:"",creator:"",gender:A.gender,birthMonth:0,birthDay:0,favoriteColor:A.favoriteColor,favorite:0,copyable:0,ngWord:0,localonly:0,regionMove:0,fontRegion:0,roomIndex:0,positionInRoom:0,birthPlatform:3},createID:{data:new Array(10).fill(0)},padding_0:0,authorType:0,authorID:new Array(8).fill(0)}}function dX1(A){let Q=new Uint8Array(A),K=Q[0];for(let C=1;C<48;C++){let U=Q[C],Y=(U-7+256)%256;Q[C-1]=Y^K,K=U}return Q.slice(0,JY.size)}function dc1(A){return{beardColor:AY(A.beard.color),beardType:A.beard.type,build:A.body.build,eyeAspect:A.eye.aspect,eyeColor:AY(A.eye.color),eyeRotate:A.eye.rotate,eyeScale:A.eye.scale,eyeType:A.eye.type,eyeX:A.eye.x,eyeY:A.eye.y,eyebrowAspect:A.eyebrow.aspect,eyebrowColor:AY(A.eyebrow.color),eyebrowRotate:A.eyebrow.rotate,eyebrowScale:A.eyebrow.scale,eyebrowType:A.eyebrow.type,eyebrowX:A.eyebrow.x,eyebrowY:A.eyebrow.y,facelineColor:A.faceline.color,facelineMake:A.faceline.make,facelineType:A.faceline.type,facelineWrinkle:A.faceline.texture,favoriteColor:A.personal.favoriteColor,gender:A.personal.gender,glassColor:AY(A.glass.color),glassScale:A.glass.scale,glassType:A.glass.type,glassY:A.glass.y,hairColor:AY(A.hair.color),hairFlip:A.hair.flip,hairType:A.hair.type,height:A.body.height,moleScale:A.mole.scale,moleType:A.mole.type,moleX:A.mole.x,moleY:A.mole.y,mouthAspect:A.mouth.aspect,mouthColor:AY(A.mouth.color),mouthScale:A.mouth.scale,mouthType:A.mouth.type,mouthY:A.mouth.y,mustacheScale:A.beard.scale,mustacheType:A.beard.mustache,mustacheY:A.beard.y,noseScale:A.nose.scale,noseType:A.nose.type,noseY:A.nose.y}}var lX1=(A)=>A.replace(/\s+/g,""),nX1=(A)=>new Uint8Array(A.match(/.{1,2}/g).map((Q)=>parseInt(Q,16)));function sX1(A){let Q=A.replace(/-/g,"+").replace(/_/g,"/"),J=Q.padEnd(Q.length+(4-Q.length%4)%4,"=");return Uint8Array.from(atob(J),(K)=>K.charCodeAt(0))}var lc1=(A)=>btoa(String.fromCharCode.apply(null,A));function nc1(A){let Q,J=lX1(A);if(/^[0-9a-fA-F]+$/.test(J))Q=nX1(J);else Q=sX1(J);return Q}async function Vc(A,Q,J,K,C,U){let Y=A.encodeStudio(),Z=HD;Z.resolution=512,Z.allExpressionFlag=new Uint32Array([1,0,0]),Z.modelFlag=qW[J];let X;try{if(K){if(!C)throw new Error("Missing renderer when trying to update CharModel");X=K;let $=JY.unpack(Y),I=l9.pack(LD($));Lc(X,I,C,Z)}else X=KY(Y,Z,window.LUTShaderMaterial,jB(),!1);CY(X,Q.getRenderer())}catch($){throw X=null,alert(`Error creating/updating CharModel: ${$}`),console.error("Error creating/updating CharModel:",$),$}let E={extras:{partsTransform:{hatTranslate:[0,0,0]}}},H=new cA;return H.add(X.meshes),{animations:[],asset:E,cameras:[],parser:{},scene:H,scenes:[H],userData:{},CharModel:X}}async function Mc(A,Q){let J=A.encodeStudio(),K=HD;K.resolution=512,K.allExpressionFlag=new Uint32Array([1,0,0]);let C;var U="";try{C=KY(J,K,window.LUTShaderMaterial,jB(),!1),U=await new Promise((Y)=>{Rc((Z)=>{Y(Z.result)}),CY(C,Q.getRenderer())})}catch(Y){throw C=null,alert(`Error creating/updating CharModel: ${Y}`),console.error("Error creating/updating CharModel:",Y),Y}return{img:U,model:C}}var Pc=j2(zO(),1);class U7{#K;#A;#Z;#C;#Q;#J;#Y;#U;#X;mii;ready;headReady;mixer;animators;animations;setupType;#B;type;cameraPan;shaderOverride;bodyModel;handColor;shaderType;simpleShaderLegacyColors;hatModels;editor;constructor(A,Q,J=0,K,C=!1,U){if(this.animations=/*@__PURE__*/new Map,this.animators=/*@__PURE__*/new Map,this.anim=/*@__PURE__*/new Map,this.#Y=Q,this.#Q=new Q8,this.#K=new kA(45,Q.offsetWidth/Q.offsetHeight,0.1,1000),this.ready=!1,this.headReady=!1,K)this.#B=K;if(this.shaderOverride=C,this.editor=U,J===1)this.#J=new q4({antialias:!0,preserveDrawingBuffer:!0});else this.#J=new q4({antialias:!0});if(this.getRendererElement().classList.add("scene"),this.setupType=J,SA("bodyModel").then((X)=>{this.bodyModel=X}),SA("shaderType").then((X)=>{if(this.shaderType=X,SA("simpleShaderLegacyColors").then((E)=>{this.simpleShaderLegacyColors=E}),X==="lightDisabled"||X.startsWith("wiiu")||X==="switch")this.#C=new TR;else this.#C=new AJ;if(X==="none"){let H=new TZ().load(["./cube_map.png","./cube_map.png","./cube_map.png","./cube_map.png","./cube_map.png","./cube_map.png"]);this.#Q.environment=H,this.#Q.environmentIntensity=1.25;let $=new R6(15466239,Math.PI);$.position.set(1,0.1,1),this.#Q.add($);let I=new I4(6710886,Math.PI/16);this.#Q.add(I)}else if(X!=="lightDisabled")this.#Q.environmentIntensity=0;this.focusCamera(0,!0)}),this.#J.setSize(512,512),this.#J.setPixelRatio(window.devicePixelRatio),b8.install({THREE:D5}),this.#A=new b8(this.#K,this.#J.domElement),J===0)(async()=>{let E=await wc.default.getItem("settings_cameraPan");if(E!==!0)console.log("canPan is not false:",E),this.#A.mouseButtons.left=b8.ACTION.ROTATE,this.#A.mouseButtons.right=b8.ACTION.NONE,this.#A.mouseButtons.wheel=b8.ACTION.DOLLY,this.#A.touches.one=b8.ACTION.TOUCH_ROTATE,this.#A.touches.two=b8.ACTION.TOUCH_DOLLY,this.#A.touches.three=b8.ACTION.NONE,this.#A.minDistance=8,this.#A.maxDistance=35,this.#A.minAzimuthAngle=-Math.PI,this.#A.maxAzimuthAngle=Math.PI,this.cameraPan=!0;else this.#K.fov=15,this.#K.updateProjectionMatrix(),this.#A.mouseButtons.left=b8.ACTION.NONE,this.#A.mouseButtons.right=b8.ACTION.NONE,this.#A.mouseButtons.wheel=b8.ACTION.NONE,this.#A.touches.one=b8.ACTION.NONE,this.#A.touches.two=b8.ACTION.NONE,this.#A.touches.three=b8.ACTION.NONE,this.#A.minDistance=60,this.#A.maxDistance=140,this.#A.minAzimuthAngle=-Math.PI,this.#A.maxAzimuthAngle=Math.PI,this.#A.dollyTo(38),this.cameraPan=!1})();if(J===1)this.#A.dollyTo(40),this.#K.fov=30,this.#A.minDistance=8,this.#A.maxDistance=300;else setTimeout(()=>{this.focusCamera(0,!0)},200);this.animators.set("cameraControls",(X,E)=>{this.#A.update(E)}),this.#Z=new J8,this.mii=A,this.type=this.mii.gender===0?"m":"f";let Y=new Y3,Z=(X)=>{let E=Y.getDelta();this.#J.render(this.#Q,this.#K),this.animators.forEach((H)=>H(X,E))};this.#J.setClearAlpha(0),this.#J.setAnimationLoop(Z),this.#K.aspect=this.#Y.offsetWidth/this.#Y.offsetHeight,this.#K.updateProjectionMatrix(),setTimeout(()=>{this.resizeRendererToDisplaySize()},500)}async#E(A="./assets/models/hat_models_bundle.zip"){this.hatModels=[];let Q=await fetch(A).then((Y)=>Y.blob()),J=await Pc.default.loadAsync(Q),K=[],C=Object.keys(J.files);for(let Y of C)K.push(J.files[Y].async("blob"));let U=await Promise.all(K);for(let Y=0;Y{this.focusCamera(0,!0,!1)},500)}getRendererElement(){return this.#J.domElement}anim;currentAnim;initAnimation(A,Q){if(console.debug("playAnimation() called:",A,Q),this.mixer===void 0)this.mixer=new F5(this.#Q.getObjectByName("m"));this.animators.set(Q,(J,K)=>{try{this.mixer.update(K)}catch(C){console.warn(C)}})}swapAnimation(A,Q=!1){if(A===this.currentAnim)return;if(console.debug("swapAnimation() called:",A),Q!==!0)for(let[K,C]of this.anim)C.fadeOut(0.2);else for(let[K,C]of this.anim)C.fadeOut(0).reset().stop();this.currentAnim=A;let J=["m","f"];for(let K of J){if(this.anim.set(K,this.mixer.clipAction(this.animations.get(`${K}-${A}`),this.#Q.getObjectByName(K))),this.anim.get(K).reset().setEffectiveTimeScale(1).setEffectiveWeight(1),A==="Wait")setTimeout(()=>{this.anim.get(K).timeScale=0.5},33.33);if(A==="Finish")setTimeout(()=>{this.anim.get(K).timeScale=0.8},33.33);if(Q===!1)this.anim.get(K).fadeIn(0.2).play();else this.anim.get(K).play();this.anim.get(K).timeScale=1}}async#$(){console.log("addBody()");let A=async(K,C)=>{let U=await this.#C.loadAsync(K),Y=U.animations;this.mixer=new F5(U.scene.getObjectByName(C));for(let H of Y)this.animations.set(`${C}-${H.name}`,H);U.scene.name=`${C}-body-root`,this.#Q.add(U.scene),this.initAnimation(U.scene.getObjectByName(C),`animation-${C}`);let Z=U.scene.getObjectByName(`body_${C}`);if(Z.geometry.userData={cullMode:1,modulateColor:DG[this.mii.favoriteColor],modulateMode:0,modulateType:9},this.shaderOverride)Z.material=new p2({roughness:1,metalness:1,color:c5[this.mii.favoriteColor]});else YJ(Z,this.mii);let X=U.scene.getObjectByName(`hands_${C}`);if(X.geometry.userData={cullMode:1,modulateColor:DG[this.mii.favoriteColor],modulateMode:0,modulateType:9},this.shaderOverride)X.material=new p2({roughness:1,metalness:1,color:c5[this.mii.favoriteColor]});else if(d0.renderer.useRendererServer)YJ(X,this.mii);let E=U.scene.getObjectByName(`legs_${C}`);if(E.geometry.userData={cullMode:1,modulateColor:mR,modulateMode:0,modulateType:10},this.shaderOverride)E.material=new p2({metalness:1,roughness:1,color:new y1(this.getPantsColor()[0],this.getPantsColor()[1],this.getPantsColor()[2])});else YJ(E,this.mii);if(this.#Q.getObjectByName("m"))this.#Q.getObjectByName("m").visible=!1;if(this.#Q.getObjectByName("f"))this.#Q.getObjectByName("f").visible=!1;U.scene.rotation.set(0,0,0),console.log(`setupBody("${K}", "${C}")`)},Q=await SA("bodyModel"),J=[A(`./assets/models/miiBodyM_${Q}.glb`,"m"),A(`./assets/models/miiBodyF_${Q}.glb`,"f")];await Promise.all(J),console.log("READY")}getPantsColor(){let A=this.shaderType==="none"&&this.simpleShaderLegacyColors===!1?!0:!1;if(this.mii.normalMii===!1)return A?Zp:Cp;if(this.mii.favorite)return A?Up:Kp;return A?Yp:mR}async updateBody(A){if(!this.ready)return;this.type=this.mii.gender===0?"m":"f";let Q=this.#Q.getObjectByName("m-body-root"),J=this.#Q.getObjectByName("f-body-root");if(!Q)return;if(!J)return;let K=this.mii.build,C=this.mii.height,U={x:0,y:0,z:0};switch(d0.mii.scalingMode){case"scaleLimit":let $=C/128;U.y=$*0.55+0.6,U.x=$*0.3+0.6,U.x=($*0.6+0.8-U.x)*(K/128)+U.x;break;case"scaleLimitClampY":$=C/128,U.y=$*0.55+0.6,U.x=$*0.3+0.6,U.x=($*0.6+0.8-U.x)*(K/128)+U.x,U.y=Math.min(U.y,1);break;case"scaleApply":U.x=K*(C*0.003671875+0.4)/128+C*0.001796875+0.4,U.y=C*0.006015625+0.5;break}U.z=U.x,window.scaleFactors=U;let Y=($)=>{$.scale.set(U.x,U.y,U.z)},Z=await SA("shaderType"),X=await SA("bodyModel"),E=($)=>{let I=new t0,N=new I1;return()=>{let F=$.getObjectByName("head");if(F===void 0)F=$.getObjectByName("Head");if(!F)return;F.updateMatrixWorld(!0);let V=new I1;if(F.matrixWorld.decompose(V,I,N),this.#Q.getObjectByName("MiiHead")){if(this.#Q.getObjectByName("MiiHead").position.copy(V),this.#Q.getObjectByName("MiiHead").setRotationFromQuaternion(I),X==="miitomo")this.#Q.getObjectByName("MiiHead").rotation.z-=Math.PI/2}}},H=async($,I)=>{let N=this.shaderOverride===!1,F=await SA("bodyModelHands"),V=$.getObjectByName(I).getObjectByName("body_"+I);if(N)V.material.uniforms.u_const1.value=new X0(...DG[this.mii.favoriteColor]);let D=$.getObjectByName(I).getObjectByName("legs_"+I);if(N)D.material.uniforms.u_const1.value=new X0(...this.getPantsColor());if(Z==="none"||this.shaderOverride){if(this.simpleShaderLegacyColors===!1){let R=c5;V.material.color.set(R[this.mii.favoriteColor])}else{let R=OK;V.material.color.set(R[this.mii.favoriteColor][0],R[this.mii.favoriteColor][1],R[this.mii.favoriteColor][2])}D.material.color.set(this.getPantsColor()[0],this.getPantsColor()[1],this.getPantsColor()[2])}let L=$.getObjectByName(I).getObjectByName("hands_"+I);if(F===!0){let R=[1,0,0];if(this.mii.extFacePaintColor!==0)if(Z==="none")R=Ax[this.mii.extFacePaintColor-1];else R=ev[this.mii.extFacePaintColor-1];else if(Z==="none")R=Jx[this.mii.skinColor];else R=Qx[this.mii.skinColor];if(N)L.material.uniforms.u_const1.value=new X0(...R,1);else if(Z==="none"||this.shaderOverride)L.material.color.set(R[0],R[1],R[2]);this.handColor=R}else L.material=V.material};switch(this.mii.gender){case 0:Q.getObjectByName("m").visible=!0,J.getObjectByName("f").visible=!1,this.animators.set("head_bone",E(Q)),Y(Q),H(Q,"m");break;case 1:Q.getObjectByName("m").visible=!1,J.getObjectByName("f").visible=!0,this.animators.set("head_bone",E(J)),Y(J),H(J,"f");break}if(A)requestAnimationFrame(()=>{this.focusCamera(this.currentPosition,!0,!0,!1)})}debugGetScene(){return this.#Q}fadeIn(){if(this.setupType===0)this.getRendererElement().style.opacity="0",setTimeout(()=>{this.getRendererElement().style.opacity="1"},500);else this.getRendererElement().style.opacity="1"}async updateMiiHead(A=0){if(!this.ready)console.log("first time loading head");let Q=this.#Q.getObjectsByProperty("name","MiiHead");switch(A){case 0:if(Q.length>0)Q.forEach((J)=>{J.traverse((K)=>{let C=K;if(C.isMesh){C.geometry.dispose();let U=C.material;if(U.map)U.map.dispose();U.dispose()}})});try{let J=this.mii.favoriteColor,K=new mA(this.mii.encode());if(this.mii.extHatColor!==0)K.favoriteColor=this.mii.extHatColor-1;let C={};if(this.mii.extHatType!==0)switch(_p[this.mii.extHatType]){case 1:C.modelType="hat";break;case 2:C.modelType="face_only";break;case 3:K.hairType=30;break}C.verifyCharInfo="0";let U;if(d0.renderer.useRendererServer)U=await this.#C.loadAsync(K.studioUrl({ext:"glb",texResolution:"512",miiName:this.mii.miiName,creatorName:this.mii.creatorName,miic:encodeURIComponent(this.mii.encode().toString("base64")),...C}));else{if(this.#U){if(this.#U.dispose)this.#U.dispose()}let I="NORMAL";switch(C.modelType){case"hat":I="HAT";break;case"face_only":I="FACE_ONLY";break}U=await Vc(K,this,I)}if(window.GLB=U,this.mii.favoriteColor=J,U.scene.name="MiiHead",U.scene.scale.set(0.12,0.12,0.12),this.#Q.remove(...Q),this.#Q.getObjectsByProperty("name","MiiHead").forEach((I)=>{I.parent.remove(I)}),d0.renderer.useRendererServer)gp(U.scene,this.mii);else this.#U=U.CharModel;console.debug("Traversing shader now");let Y=this.#Q.getObjectByName(this.type),Z=Y.getObjectByName("head");if(Z===void 0)Z=Y.getObjectByName("Head");if(!Z)return;Z.updateMatrixWorld(!0);let X=new I1,E=new t0,H=new I1;if(Z.matrixWorld.decompose(X,E,H),U.scene)U.scene.position.copy(X),U.scene.setRotationFromQuaternion(E),console.debug("Positioning head to body");let $=this.bodyModel;if(this.#Q.add(U.scene),console.debug("Adding head to scene"),$==="miitomo")U.scene.rotation.z-=Math.PI/2;try{if(this.mii.extHatType!==0){let I=this.hatModels[this.mii.extHatType].scene.clone(!0);I.name="HatScene";let N=0;if(U.asset.extras.partsTransform.hatTranslate){let[V,D,L]=U.asset.extras.partsTransform.hatTranslate;console.log(U.asset.extras.partsTransform.hatTranslate);let R=new I1(V,D,L);I.position.add(R),window.hatModel=I}let F=await SA("shaderType");I.traverse((V)=>{if(V.name==="HatScene"||V.name==="HatRoot")return;if(V.isMesh){let D=V,L=D.material,R=OK;if(F==="none"){if(R=OK,this.simpleShaderLegacyColors===!0)R=OK}if(D.material=new BA({color:16777215,map:L.map}),D.material.needsUpdate=!0,D.geometry.userData={cullMode:0,modulateColor:OK[this.mii.extHatColor!==0?this.mii.extHatColor-1:this.mii.favoriteColor],modulateMode:5,modulateType:5},N++,d0.renderer.useRendererServer===!1)YJ(D,this.mii)}}),U.scene.add(I)}}catch(I){console.error("Hat type resulted in an error, but we're not going to let that stop the head from rendering!",I)}}catch(J){console.error(J)}break;case 1:if(Q.length>0)Q.forEach((J)=>{this.traverseAddFaceMaterial(J,`&data=${encodeURIComponent(this.mii.encodeStudio().toString("hex"))}&width=512`)});break}if(this.headReady===!1)this.fadeIn();this.headReady=!0,await this.updateBody()}particles;lastSparkleTime;sparkle(){if(!this.particles)this.particles=[];if(!this.lastSparkleTime)this.lastSparkleTime=0;if(performance.now()-this.lastSparkleTime<150)return;this.lastSparkleTime=performance.now(),this.#Z.load("./assets/images/star.png",(A)=>{let Q=new I1,J=new DA;this.#Q.getObjectByName("MiiHead").getWorldPosition(Q),J.setFromObject(this.#Q.getObjectByName("MiiHead"));let K=new aR(this.#Q,new I1(0,Q.y+J.min.y/2,2),A);this.particles.push(K),this.animators.set("particle_"+performance.now(),(C,U)=>K.update(U)),setTimeout(()=>{this.particles.forEach((C,U)=>{C.dispose()}),this.particles=[],Array.from(this.animators.keys()).filter((C)=>C.startsWith("particle_")).forEach((C)=>{this.animators.delete(C)})},1000)})}getHead(){return this.#Q.getObjectByName("MiiHead")}traverseAddFaceMaterial(A,Q){A.traverse((J)=>{let K=J;if(K.isMesh){if(K.geometry.userData){let C=K.geometry.userData;if(C.modulateMode){if(C.modulateType===6)(async()=>{let Y=K.material;var Z=d0.renderer.renderFaceURL+Q;if(d0.renderer.useRendererServer===!1){console.log("READY");let{img:E,model:H}=await Mc(this.mii,this);console.log("DONE"),Z=E,H.dispose(),console.log("Mask URL:",E)}let X=await this.#Z.loadAsync(Z);if(X){if(await SA("shaderType")==="none")X.colorSpace="srgb";X.flipY=!1,this.#J.initTexture(X),K.material=new p2({map:X,emissiveIntensity:1,transparent:!0,metalness:1,toneMapped:!0,alphaTest:0.5}),YJ(K,this.mii),Y.dispose()}})()}}}})}getCamera(){return this.#K}getControls(){return this.#A}getScene(){return this.#Q}getRenderer(){return this.#J}shutdown(){Array.from(this.animators.keys()).forEach((A)=>{this.animators.delete(A)})}}var _c=FK.find((A)=>A.className==="Gen2Wiiu3dsMiitomo"),oX1=async(A)=>{let Q,J,K=new Uint8Array(QA.from(A,"base64"));Q=new Uint8Array(Wx(K,_c,_c.className,!0)),J=Sy(Q),J=new Uint8Array([...J,...K.subarray(96)]);let C=kc.default.generatePNG(J,{margin:0}),U=new Image(431,431);return U.src=URL.createObjectURL(await(await fetch(C)).blob()),new Promise((Y)=>{U.onload=()=>{return Y(U)}})};var j5=async(A,Q,J=!0,K=!0)=>{return new Promise((C,U)=>{let Y=new mA(A.encode());if(J===!1)Y.trueEyeColor=Y.fflEyeColor,Y.trueEyebrowColor=Y.fflEyebrowColor,Y.trueFacialHairColor=Y.fflFacialHairColor,Y.trueGlassesColor=Y.fflGlassesColor,Y.trueGlassesType=Y.fflGlassesType,Y.trueHairColor=Y.fflHairColor,Y.trueMouthColor=Y.fflMouthColor,Y.trueSkinColor=Y.fflSkinColor,Y.extEyeColor=Y.fflEyeColor+8,Y.extHairColor=Y.fflHairColor,Y.extFacelineColor=Y.fflSkinColor,Y.extBeardColor=Y.fflFacialHairColor,Y.extEyebrowColor=Y.fflEyebrowColor,Y.extGlassColor=0,Y.extGlassType=Y.fflGlassesType,Y.extHatColor=0,Y.extHatType=0;let Z=new f1("div").style({width:"720px",height:"720px",opacity:"0"}).appendTo("body"),X=new U7(Y,Z.elm,1);X.init().then(async()=>{await X.updateBody(),await X.updateMiiHead(),X.anim.forEach((F)=>{F.timeScale=0}),X.swapAnimation("Pose.01");let E=X.getScene(),H=X.getCamera(),$=X.getControls(),I=new I1;switch(Q){case 0:setTimeout(()=>{X.focusCamera(0,!0,!1),$.dollyTo(50),H.fov=15,H.updateProjectionMatrix()},300);break;case 1:E.getObjectByName("body_m").visible=!1,E.getObjectByName("hands_m").visible=!1,E.getObjectByName("legs_m").visible=!1,E.getObjectByName("body_f").visible=!1,E.getObjectByName("hands_f").visible=!1,E.getObjectByName("legs_f").visible=!1,X.focusCamera(0,!0,!1),$.dollyTo(40),H.fov=15,H.updateProjectionMatrix();break;case 2:X.focusCamera(1,!0,!1),$.dollyTo(90,!1),H.fov=15,H.updateProjectionMatrix();break}Z.append(X.getRendererElement());let N=X.getRenderer();setTimeout(()=>{if(K)N.domElement.toBlob((F)=>{let V=new Image(N.domElement.width,N.domElement.height);V.src=URL.createObjectURL(F),console.log("Temporary render URL:",V.src),V.onload=()=>{C(V),X.shutdown(),Z.cleanup()}});else{let F=N.domElement.toDataURL("png",100),V=new Image(N.domElement.width,N.domElement.height);V.src=F,V.onload=()=>{C(V),X.shutdown(),Z.cleanup()}}},500)})})},iX1=async(A)=>{let Q="";if(A)Q="./assets/images/bg_qr_miic.png";else Q="./assets/images/bg_qr_wiiu.png";let J=await(await fetch(Q)).blob(),K=new Image(1280,720);return K.src=URL.createObjectURL(J),new Promise((C)=>{K.onload=()=>{return C(K)}})};function aX1(A){return new Promise((Q,J)=>{let K=new Image;K.crossOrigin="anonymous",K.src=A,K.onload=()=>{Q(K)},K.onerror=(C)=>{J(C)}})}var Sc=async(A,Q=!0)=>{let J=new mA(QA.from(A,"base64")),K=await aX1(`${d0.renderer.renderFullBodyAltURL}&data=${encodeURIComponent(J.encodeStudio().toString("hex"))}&${d0.renderer.hatTypeParam}=${J.extHatType+d0.renderer.hatTypeAdd}&${d0.renderer.hatColorParam}=${J.extHatColor+d0.renderer.hatColorAdd}`),C=await oX1(A),U=await iX1(Q),Y=document.createElement("canvas");Y.width=1280,Y.height=720;let Z=Y.getContext("2d");return Z.drawImage(U,0,0),Z.font='500 24px "NTLG", sans-serif',Z.textAlign="left",Z.textBaseline="top",Z.fillStyle="#cccccc",Z.fillText(`${location.origin}`,32,667),Z.font='500 24px "NTLG", sans-serif',Z.textAlign="right",Z.textBaseline="top",Z.fillStyle="#cccccc",Z.fillText(`Made with Mii Creator ${d0.version.string}`,1248,667),Z.drawImage(K,54,-54,714,953),Z.fillStyle="#ffffff",Z.beginPath(),Z.roundRect(769,79,463,463,[16,16,0,0]),Z.fill(),Z.drawImage(C,797,107,408,408),Z.fillStyle="#707070",Z.beginPath(),Z.roundRect(769,542,463,99,[0,0,16,16]),Z.fill(),Z.fillStyle="#ffffff",Z.textAlign="center",Z.textBaseline="middle",Z.font='500 38px "NTLG", sans-serif',Z.fillText(J.miiName,1005,591),Y.toDataURL("png",100)};function YY(A,Q,J,K,C,U,Y=""){new f1("div").class("flex-group").style({gap:"0","justify-content":"flex-start","text-align":"left"}).appendMany(new f1("img").attr({width:96,draggable:"false",src:d0.renderer.renderHeadshotURLNoParams+`?data=${encodeURIComponent(U)}&type=variableiconbody&verifyCharInfo=0&shaderType=switch&width=96&source=credits&characterYRotate=8&bodyType=switch&`+Y}).style({width:"96px",height:"96px"}),new f1("div").class("col").style({gap:"12px",flex:"1"}).appendMany(new f1("small").appendMany(new f1("span").text(Q).style({display:"inline",width:"max-content"}),f2(new f1("a").text(`(@${J})`).attr({target:"_blank",href:K}))).style({display:"flex",gap:"8px"}),new f1("div").html(C))).appendTo(A)}function OW(A,Q,J,K,C){let U;if(J!=="")U=new f1("a").attr({href:J,target:"_blank"}).html(K);else U=new f1("div").html(K);new f1("div").class("flex-group").style({gap:"0","justify-content":"flex-start","text-align":"left"}).appendMany(new f1("div").html(C).style({width:"96px",height:"96px"}),new f1("div").class("col").style({gap:"12px",flex:"1"}).appendMany(new f1("small").appendMany(new f1("span").text(Q).style({display:"inline",width:"max-content"})).style({display:"flex",gap:"8px"}),U)).appendTo(A)}function S4(A,Q){let J=document.createElement("a");J.href=A,J.download=Q,document.body.appendChild(J),J.click(),setTimeout(()=>{J.remove()},1000)}var vB=document.createElement("a");function rX1(A,Q){if(vB.href)URL.revokeObjectURL(vB.href);vB.href=URL.createObjectURL(A),vB.download=Q||"data.json",vB.dispatchEvent(new MouseEvent("click"))}function NJ(A,Q){rX1(new Blob([A],{type:"application/octet-stream"}),Q)}var xB=j2(u8(),1),FD=await xB.default.getItem("language"),jc=FD||"en_US",vc={};async function xc(A,Q){if(Q)window.firstVisit=FD===null;if(Q&&FD===null)await xB.default.setItem("language",A);try{let J=(await import(`./lang/${A}.js`)).default;if(Q)xB.default.setItem("language",A);else await xB.default.setItem("language",A);vc=J}catch(J){console.log("Failed to load strings!")}}await xc(jc,!0);var NW={async setLanguage(A){xc(A,!1)},getLanguage(){return jc},getString(A,Q={}){let J=A.split("."),K=vc;for(let C=0;CNW.getString(A,Q);window.langManager=NW;window.getString=RD;var VD=j2(u8(),1);var yc=j2(u8(),1);async function LJ(A,Q,J="Mii Import"){var K=y0.modal(J,"","body",{text:"Cancel"},{text:"Don't Save"},{text:"Save",async callback(C){let U=await q9();await yc.default.setItem(U,A.encode().toString("base64")),G6()(),$8(U)}});K.qs(".modal-content").styleJs({maxWidth:"100%",maxHeight:"100%"}),K.qs(".modal-body span").cleanup(),K.qs(".modal-body").style({"align-items":"center",gap:"1.5rem"}).prependMany(new f1("span").text("Do you want to save this Mii?"),new f1("small").text(Q),new f1("span").style({"font-size":"20px"}).text(`${A.miiName} has arrived!`),new f1("img").attr({src:H3(A,"qr_code","all_body_sugar",260)}).style({width:"260px",height:"260px","object-fit":"contain"}))}function LW(A){if(A<=0.0031308)return A*12.92;else return 1.055*Math.pow(A,0.4166666666666667)-0.055}async function FW(A){let Q=await SA("shaderType"),J=await SA("bodyModelHands");return new Promise((K)=>{let C=/*@__PURE__*/new Map,U=0,Y=0;A.getScene().traverse((Z)=>{if(Z.isMesh!==!0)return;if(Z.material)Y++}),A.getScene().traverse((Z)=>{if(Z.isMesh!==!0)return;let X=Z;C.set(U,X.material),console.log(X.name,X.geometry.userData);let E=null,H=X.geometry.userData;if(Q.startsWith("wiiu")||Q==="lightDisabled"){if(console.log(X.name,X.material.type),X.material.type!=="ShaderMaterial")return;if(E=X.material.uniforms.s_texture.value,E!==null){let D=document.createElement("canvas"),L=D.getContext("2d");D.width=E.image.width,D.height=E.image.height;let R=E.image,M=!1;if(typeof E.image.data!=="undefined")R=new ImageData(E.image.data,E.image.width,E.image.height),M=!0;if(M)L.putImageData(R,0,0);else L.drawImage(R,0,0);let T=L.getImageData(0,0,D.width,D.height),h=T.data;for(let g=0;g{let u=L.focusCamera(1,!0,!1,!0),d=new I1;$.getTarget(d),d.x=u.x,$.moveTo(d.x,d.y,d.z)}),new f1("button").text("Center vertically").on("click",()=>{let u=L.focusCamera(1,!0,!1,!0),d=new I1;$.getTarget(d),d.y=u.y,$.moveTo(d.x,d.y,d.z)}),new f1("button").text("Reset").on("click",()=>{let u=L.focusCamera(1,!0,!1,!0);L.getControls().moveTo(u.x,u.y,u.z)})),new f1("label").text("Rotate"),new f1("div").class("flex-group").appendMany(new f1("button").text("Up").on("click",()=>{L.getControls().rotateTo($.azimuthAngle,$.polarAngle-I)}),new f1("button").text("Down").on("click",()=>{L.getControls().rotateTo($.azimuthAngle,$.polarAngle+I)}),new f1("button").text("Left").on("click",()=>{L.getControls().rotateTo($.azimuthAngle-I,$.polarAngle)}),new f1("button").text("Right").on("click",()=>{L.getControls().rotateTo($.azimuthAngle+I,$.polarAngle)}),new f1("button").text("Reset").on("click",()=>{$.rotateTo(0,Math.PI/2)}))),select(){}}]},pose:{label:"Pose",header:new f1("div").appendMany(new f1("span").html('Change the Body Model option in Settings to get many different options of poses!

Do you like the Mii that does the poses? His name is "dummy". '),new f1("a").text("Click here").on("click",(u)=>{L.shutdown(),K.cleanup(),Q.qs("button")?.elm.click();let d=new mA(QA.from("A0EAwAAAAAAAAAAAgP9wmS/5Fhz6rQAAAABkAHUAbQBtAHkAAAAAAAAAAAAAAEBAEgAeARJoYxoHA2YWIRQTZgwAAAEAUkhQTQBpAGkAQwByAGUAYQB0AG8AcgAAAK6gAAAICAAAAAAAAGQA","base64"));LJ(d,"Mii Creator (Special Mii)")}),new f1("span").html(" to obtain him in your library :)")),headerIsHtml:!0,items:_A(H).map((u)=>({type:0,value:u,icon:u===0?"None":``,part:0}))},expression:{label:"Expression",items:hc.map((u)=>({type:0,value:String(u.id),icon:``,part:0}))},animation:{label:"Animation",header:"This usually only applies to Miitomo body model which has animations for its poses.",items:[{type:3,property:"animSpeed",part:1,iconStart:"0x",iconEnd:"2x",min:0,max:200}]}};D2({mii:Y,miiIsNotMii:!0,entries:N,onChange(u,d,n){Y=u,T(),M=Object.assign({},Y)}}).style({height:"auto"}).appendTo(U);let F=!0;if(E==="wiiu")F=!1;let V=f2(new f1("button").text(F?"Pause Animation":"Pause Animation").on("click",()=>{if(F===!0)F=!1;else F=!0;L.anim.forEach((u)=>{if(F===!0)u.paused=!1,V.text("Pause Animation");else u.paused=!0,V.text("Play Animation")})}).appendTo(U));new f1("button").text("Download PNG").on("click",g).appendTo(U),new f1("button").text("Download 3D model").on("click",f).appendTo(U);function D(){let{width:u,height:d}=C.elm.getBoundingClientRect();if(u<1024)u=1024;if(d<1024)d=1024;L.resize(u,d),L.getRendererElement().style.height="100%",L.getRendererElement().style.width="unset"}window.addEventListener("resize",()=>{D()});let L=new U7(A,C.elm,1,(u)=>{});$=L.getControls(),window.scene=L;let R=await SA("customRenderGreenScreen");if(R!=="off"){let u=R;switch(R){case"green":u="#00ff00";break;case"blue":u="#0000ff";break;case"white":u="#ffffff";break;case"black":u="#000000";break}L.getScene().background=new y1(u)}let M={fov:30,pose:0,expression:0,renderWidth:720,renderHeight:720,cameraPosition:1,animSpeed:1};function T(){switch(L.getCamera().fov=Y.fov,L.getCamera().updateProjectionMatrix(),Y.cameraPosition){case 0:L.focusCamera(0);break;case 1:L.focusCamera(1);break}if(M.expression!==Y.expression)L.traverseAddFaceMaterial(L.getHead(),`&data=${encodeURIComponent(Z)}&expression=${Y.expression}&width=896&verifyCharInfo=0`);let u=hc.find((n)=>n.id===Y.expression);if(u)if(typeof u.modifier!=="undefined")switch(u.modifier){case 0:L.getHead().traverse((n)=>{if(n.isMesh!==!0)return;let B=n,q=B.geometry.userData.modulateType;if(q===2||q===7)B.visible=!1;else B.visible=!0});break;case 1:L.getHead().traverse((n)=>{if(n.isMesh!==!0)return;let B=n,q=B.geometry.userData.modulateType;if(q===6||q===2||q===7)B.visible=!1;else B.visible=!0});break}else L.getHead().traverse((n)=>{if(n.isMesh!==!0)return;let B=n;B.visible=!0});let d="Pose."+String(Y.pose).padStart(2,"0");if(L.animations.get(`${L.type}-${d}`)){if(L.swapAnimation(d),F===!1)L.anim.forEach((n)=>n.paused=!0)}else if(L.swapAnimation("Wait"),F===!1)L.anim.forEach((n)=>n.paused=!0);L.anim.forEach((n)=>{n.timeScale=Y.animSpeed/100}),L.anim.get(L.type).timeScale*=0.5}window.scene=L,L.init().then(async()=>{if(await L.updateMiiHead(),F===!1)L.anim.forEach((u)=>{if(F===!0)u.paused=!1,V.text("Pause Animation");else u.paused=!0,V.text("Play Animation")});L.focusCamera(1,!0,!1),C.append(L.getRendererElement())});let h=await SA("autoCloseCustomRender"),y=L.getRendererElement();function g(){y.toBlob((u)=>{let d=new Image(y.width,y.height);d.src=URL.createObjectURL(u),d.onload=()=>{if(S4(d.src,`${A.miiName}_all_body_${(/*@__PURE__*/new Date()).toJSON()}.png`),h)L.shutdown(),K.cleanup(),Q.qs("button")?.elm.click()}})}async function f(){if(await SA("shaderType")==="none"){if(await y0.prompt("Notice",`3D model export looks best when using the Wii U shader, which you aren't using. -This may result in incorrect color output. Do you still want to continue?`,"body")===!1)return}let d=await FW(L),n=0;new R4().parse(L.getScene(),(q)=>{if(console.log("gltf",q),q instanceof ArrayBuffer)NJ(q,`${A.miiName}_all_body_${(/*@__PURE__*/new Date()).toJSON()}.glb`);if(h)L.shutdown(),K.cleanup(),Q.qs("button")?.elm.click();else n=0,L.getScene().traverse((P)=>{if(P.isMesh!==!0)return;let O=P;O.material=d.get(n),n++})},(q)=>{console.error("Oops, something went wrong:",q)},{binary:!0})}}var gc=async(A,Q)=>{y0.modal(`Render options: ${Q.miiName}`,"Choose a way to render this Mii","body",{text:"Focus on head",async callback(){let J=await j5(Q,0);S4(J.src,`${Q.miiName}_render_headshot_${Date.now()}.png`)}},{text:"Focus on full body",async callback(){let J=await j5(Q,2);S4(J.src,`${Q.miiName}_render_body_${Date.now()}.png`)}},{text:"Head only",async callback(){let J=await j5(Q,1);S4(J.src,`${Q.miiName}_render_head_only_${Date.now()}.png`)}},{text:"Cancel"})};var bc=(A,Q)=>{y0.modal("Render Mii","What would you like to do?","body",{text:"Download 3D head model",async callback(){let J=new f1("div").style({opacity:"0"}),K=new U7(Q,J.elm,1,(C)=>{},!0);K.init().then(async()=>{if(await K.updateMiiHead(),K.getScene().getObjectByName("m").visible=!1,K.getScene().getObjectByName("f").visible=!1,await SA("shaderType")==="none"){if(await y0.prompt("Notice",`3D model export looks best when using the Wii U shader, which you aren't using. -This may result in incorrect color output. Do you still want to continue?`,"body")===!1)return}FW(K),await new Promise((Y)=>{setTimeout(()=>{Y(null)},250)}),new R4().parse(K.getScene(),(Y)=>{if(console.log("gltf",Y),Y instanceof ArrayBuffer)NJ(Y,Q.miiName+"_head.glb");K.shutdown()},(Y)=>{console.error("Oops, something went wrong:",Y)},{binary:!0})})}},{text:"Render presets",async callback(){gc(A,Q)}},{text:"Make your own render",async callback(){RW(Q)}},{text:"Cancel"})};var zD=j2(u8(),1);var DD=async(A,Q)=>{y0.modal("Export Mii","How would you like to save the Mii?","body",{text:"Cancel"},{text:"Save MiiCreator data",async callback(){let J=new Blob([Q.encode()]),K=URL.createObjectURL(J),C=document.createElement("a");C.href=K,C.target="_blank",C.download=Q.miiName+".miic",document.body.appendChild(C),C.click(),requestAnimationFrame(()=>{C.remove()}),setTimeout(()=>{URL.revokeObjectURL(K)},2000)}},{text:"Download other file types...",callback(J){y0.modal("Other download types","Choose a file type to download","body",{text:"Cancel",callback(K){DD(A,Q)}},{text:"Download FFSD file",async callback(){if(!await pc(Q))return;let K=new Blob([Q.encodeFFSD()]),C=URL.createObjectURL(K),U=document.createElement("a");U.href=C,U.target="_blank",U.download=Q.miiName+".ffsd",document.body.appendChild(U),U.click(),requestAnimationFrame(()=>{U.remove()}),setTimeout(()=>{URL.revokeObjectURL(C)},2000)}},{text:"Download CharInfo (Switch) file",async callback(){let K=new Blob([Q.encodeCharInfoSwitch()]),C=URL.createObjectURL(K),U=document.createElement("a");U.href=C,U.target="_blank",U.download=Q.miiName+".charinfo",document.body.appendChild(U),U.click(),requestAnimationFrame(()=>{U.remove()}),setTimeout(()=>{URL.revokeObjectURL(C)},2000)}})}},{text:"Save Mii as QR Code",async callback(){if(!await fc(Q))return;let J=await SA("shaderType");await zD.default.setItem("settings_shaderType","wiiu");let K=await Sc(A.mii,Q.hasExtendedColors());await zD.default.setItem("settings_shaderType",J),S4(K,`${Q.miiName}_QR.png`)}},{text:"Show other raw data formats",async callback(){let J=y0.modal("Miscellaneous Output Formats","Click inside a code block to select it.","body",...x3);J.qs(".modal-content").style({"max-height":"100vh","max-width":"600px"}),J.qs(".modal-body").prependMany(new f1("div").appendMany(new f1("span").class("h4").text("CharInfo (Switch) data (Hex)"),new f1("pre").class("pre-wrap","mb-0").text(Q.encodeCharInfoSwitch().toString("hex"))),new f1("div").appendMany(new f1("span").class("h4").text("MiiC (Base64)"),new f1("pre").class("pre-wrap","mb-0").text(Q.encode().toString("base64"))),new f1("div").appendMany(new f1("span").class("h4").text("FFSD (Base64)"),new f1("pre").class("pre-wrap","mb-0").text(Q.encodeFFSD().toString("base64"))),new f1("div").appendMany(new f1("span").class("h4").text("FFSD (Hex)"),new f1("pre").class("pre-wrap","mb-0").text(Q.encodeFFSD().toString("hex"))),new f1("div").appendMany(new f1("span").class("h4").text("Mii Studio data"),new f1("pre").class("pre-wrap","mb-0").text(Q.encodeStudio().toString("hex"))))}})};var uc=(A,Q,J)=>{return async()=>{y0.modal(Q.miiName,"What would you like to do?","body",{text:"Edit",async callback(){if(J)y0.modal("Nope","You can't edit Special Miis obtained through Mii Creator.","body",{text:"Cancel"},{text:"OK"});else await G6()(),new V8(0,async(C,U)=>{if(U===!0)await VD.default.setItem(A.id,C);$8()},A.mii)}},{text:"Delete",async callback(){let C,U,Y,Z,X,E;C=await(await fetch(await H3(Q)+"&expression=10")).blob(),U=await(await fetch(await H3(Q)+"&expression=30")).blob(),Y=await(await fetch(await H3(Q)+"&expression=1")).blob(),Z=URL.createObjectURL(C),X=URL.createObjectURL(U),E=URL.createObjectURL(Y);function H(){URL.revokeObjectURL(Z),URL.revokeObjectURL(X),URL.revokeObjectURL(E)}function $(){N(),D.classOn("rotateAndCry")}function I(){V.qs(".modal-body").qsa("*").forEach((L)=>L.attr({disabled:!0,tabindex:"-1"}))}function N(){I()}function F(){V.class("closing"),I(),setTimeout(()=>{V.cleanup()},350)}let V=y0.modal("Warning",`Are you sure you want to delete ${Q.miiName}?`,"body");V.qs(".modal-body .flex-group").appendMany(new f1("button").class("danger").text("Yes").on("click",()=>{$(),D.attr({src:X}),setTimeout(async()=>{F(),H(),await VD.default.removeItem(A.id),await G6()(),$8()},1000)}),new f1("button").text("No").on("click",()=>{F(),H()})),V.qs(".modal-body").classOn("flex-group");let D=new f1("img").attr({src:Z}).style({width:"180px",margin:"-18px auto 0 auto"});V.qs(".modal-body").prepend(D),V.qsa("button").forEach((L)=>{let R=L?.elm.classList.contains("danger");L.on("pointerenter",()=>{if(R)D.attr({src:X});else D.attr({src:E})}),L.on("pointerleave",()=>{D.attr({src:Z})})})}},{text:"Export/Download Data",async callback(){DD(A,Q)}},{text:"Render",async callback(){bc(A,Q)}},{text:"Cancel"}).qs(".modal-body")?.prepend(new f1("img").attr({src:await H3(Q,"preview","all_body_sugar",240)}).style({"object-fit":"contain",width:"180px",height:"240px",margin:"-18px auto 0 auto"}))}};var Id=j2(u8(),1);var mc=j2(u8(),1);var cc=()=>{function A(C){return()=>{G6()(),new V8(C,async(U,Y)=>{if(Y===!0)await mc.default.setItem(await q9(),U);$8()})}}var Q=y0.modal("Create New","Select the Mii's gender","body",{text:"Male",callback:A(0)},{text:"Female",callback:A(1)},{text:"Cancel",callback:()=>n9()});let J=Q.qs(".modal-body button:nth-child(1)"),K=Q.qs(".modal-body button:nth-child(2)");if(J)J.classOn("gender-select-btn"),J.prepend(new f1("span").html(N0.genderMaleLg));if(K)K.classOn("gender-select-btn"),K.prepend(new f1("span").html(N0.genderFemaleLg))};var UY=j2(lc(),1);var JE1="59FC817E6446EA6190347B20E9BDCE52",KE1="30819F300D06092A864886F70D010101",CE1=Q6.codec.hex.toBits(JE1),YE1=window.crypto,nc=YE1.subtle;function j4(A){if(A==="Camera not found.")A+=` -Check your browser settings and make sure it isn't disabled. -If you don't have a camera, you can disable the option in Mii Creator settings.`;var Q=y0.modal("QR Scanner Error",A,"body",{text:"Cancel"},{text:"OK"});Q.qs(".modal-content").styleJs({minWidth:"360px"})}function UE1(A){let Q=new Uint8Array(A.length/2);for(let J=0;J>>0}}XE1();function EE1(A){if(A.length<112)throw new Error("Mii QR codes should be 112 or more bytes long, yours is "+A.length);let Q=A.slice(0,8),J=A.slice(8),K=new Q6.cipher.aes(CE1),C=Q6.codec.bytes.toBits(Array.from(J)),U=Q6.codec.bytes.toBits([...Q,0,0,0,0]),Y=128,Z=Q6.bitArray.clamp(C,Q6.bitArray.bitLength(C)-Y),E=(Q6.mode.ccm._ctrMode||Q6.mode.ccm.C)(K,Z,U,[],Y,3),H=Q6.codec.bytes.fromBits(E.data),$=new Uint8Array(H).slice(0,88);return new Uint8Array([...$.slice(0,12),...Q,...$.slice(12)])}async function $E1(A,Q){let J=await nc.importKey("raw",UE1(KE1),{name:"AES-CTR"},!1,["decrypt"]),K=await nc.decrypt({name:"AES-CTR",counter:Q,length:128},J,A.buffer);return new Uint8Array(K)}var O7;async function sc(A){if(console.log("startScanner()"),O7=new UY.default(document.getElementById("qr-video"),(J)=>PD(J),{onDecodeError:(J)=>{if(J==="No QR code found")return;console.log("QR scan error:",J)},highlightScanRegion:!0,highlightCodeOutline:!0}),await SA("allowQrCamera"))O7.start().then(()=>{let J=document.getElementsByClassName("device-camera");Array.from(J).forEach((K)=>{K.remove()}),UY.default.listCameras(!0).then((K)=>K.forEach((C)=>{let U=document.createElement("option");U.value=C.id,U.text=C.label,U.className="device-camera",A.appendChild(U)})).catch((K)=>{j4(K),console.error(K)})}).catch((J)=>{j4(J),console.error(J)});else O7.start().catch((J)=>{if(J!=="Camera not found.")j4(J)})}async function oc(A,Q,J,K){console.log("initQrCam()");let C=await SA("allowQrCamera"),U=()=>{A.style.display="none",Q.style.display="none",J.style.display="none"};if(C)UY.default.hasCamera().then((Y)=>{if(Y===!1)U()}).catch((Y)=>{j4(Y),console.error(Y)});else U();A.addEventListener("change",(Y)=>{O7.setCamera(Y.target.value)}),Q.addEventListener("click",()=>{try{O7=new UY.default(document.getElementById("qr-video"),(Y)=>PD(Y)),O7.start().catch((Y)=>{j4(Y),console.error(Y)})}catch(Y){j4(Y),console.error(Y)}}),J.addEventListener("click",()=>{if(O7)O7.stop()}),K.addEventListener("change",(Y)=>{let Z=Y.target.files[0];if(Z)UY.default.scanImage(Z,{returnDetailedScanResult:!0}).then((X)=>PD(X))})}var zW;function ic(A){zW=A}function PD(A){if(!A||!A.bytes)return;if(A.noQrCode)return;O7.stop();let Q=new Uint8Array(A.bytes);console.log(QA.from(Q).toString("hex"));let J=EE1(Q.slice(0,112)),K=QA.from(J);if(console.log("Decrypted QR Store Data:",K.toString("base64")),Q.length>112){console.log("Has extra data");let C=Q.slice(112,128),U=Q.slice(128,-4);$E1(U,C).then((Y)=>{if(console.log("Scanned Extra Data:",QA.from(Y).toString("hex")),Y.length===240)zW(QA.concat([K]),1)}).catch((Y)=>{console.error("Something went wrong decrypting the QR extra data",Y),console.log("Attempting to load QR extra data anyways:");let Z=QA.from(Q.slice(112));if(console.log(Z.toString("base64")),Z.length===10||Z.length===12)console.log("This is probably miic data"),zW(QA.concat([K,Z]),2)})}else console.log("No extra data"),zW(K,0)}var ac=async()=>{let A=!0,Q=y0.modal("Scan QR Code","","body",{text:"Cancel",callback:()=>{if(Q.qs("#stop-camera").elm.click(),A)n9()}}),J=Q.qs(".modal-body");if(Q.qs(".modal-body").qsa("*").forEach((C)=>C.cleanup()),Q.qs(".modal-content")?.styleJs({maxHeight:"100%",maxWidth:"600px"}),J.appendMany(new f1("div").classOn("col").appendMany(new f1("span").attr({for:"cam-list"}).text("Select camera:"),new f1("select").id("cam-list").appendMany(new f1("option").attr({value:"environment",selected:"yes"}).text("Back Camera (default)"),new f1("option").attr({value:"user"}).text("User/Front Facing Camera"),new f1("option").attr({value:"device-camera",disabled:!0}).text("(Open the camera for more options)")),new f1("div").class("flex-group").appendMany(new f1("button").id("start-camera").text("Start camera"),new f1("button").id("stop-camera").text("Stop camera")),new f1("video").id("qr-video").styleJs({maxWidth:"100%"}),new f1("span").id("file-upload").text("Or upload an image:"),new f1("input").attr({type:"file",id:"file-input",accept:"image/*"}))),sc(J.qs("#cam-list").elm),oc(J.qs("#cam-list").elm,J.qs("#start-camera").elm,J.qs("#stop-camera").elm,J.qs("#file-input").elm),await SA("allowQrCamera")===!1)J.qsa('span[for="cam-list"], #cam-list, .flex-group, video').forEach((C)=>C.style({display:"none"})),J.qs("video").style({position:"fixed"}),J.qs("span#file-upload").text(`Camera is disabled in settings. - -Upload an image:`);async function K(C,U){if(await SA("autoCloseQrScan"))A=!1,Q.qs(".modal-header button")?.elm.click();LJ(C,U,"Mii QR Scanned")}ic((C,U)=>{try{var Y;switch(U){case 0:Y=new mA(C),K(Y,"3DS/Wii U QR Code"),Y=new mA(C),K(Y,"3DS/Wii U QR Code");break;case 1:y0.alert("Notice",new f1("span").html(`Tomodachi Life QR codes aren't supported yet. Use Mii Renderer (REAL) to scan it.`));break;case 2:Y=new mA(C),K(Y,"Mii Creator QR Code");break}}catch(Z){j4(`An error occurred when reading the data. -Please check the console for more information.`),console.error(Z)}})};var _D=j2(u8(),1);var yB,O9={show(){if(yB===void 0)yB=new f1("div").class("loader","active").html(N0.loading).appendTo("body");else yB.classOn("active")},hide(){if(yB)yB.classOff("active")}};var rc=async()=>{let A=await y0.input("Nintendo Network ID","Enter NNID of user..","Username","body",!1);if(A===!1)return n9();O9.show();let J=await(await fetch(d0.apis.nnidFetchURL(encodeURIComponent(A)))).json();if(O9.hide(),J.error!==void 0){await y0.alert("Error",`Couldn't get Mii: ${J.error}`);return}G6()(),new V8(0,async(K,C)=>{if(C===!0)await _D.default.setItem(await q9(),K);$8()},J.data)},tc=async()=>{let A=await y0.input("Pretendo Network ID","Enter PNID of user..","Username","body",!1);if(A===!1)return n9();O9.show();let Q=await fetch(d0.apis.pnidFetchURL(encodeURIComponent(A)));if(O9.hide(),!Q.ok){await y0.alert("Error",`Couldn't get Mii: ${await Q.text()}`);return}G6()(),new V8(0,async(J,K)=>{if(K===!0)await _D.default.setItem(await q9(),J);$8()},(await Q.json()).data)};var $d=j2(u8(),1);function DW(A){return 32-[3,4,4,4,3,4,4,4,3,4,4,4,4,3,3,4,4,4,3,3,4,3,4,3,3,4,3,4,4,3,4,4,4,3,3,3,4,4,3,3,3,4,4,3,3,3,3,3,3,3,3,3,4,4,4,4,3,4,4,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4][A]}var ec=[[[[10,[0,0,1,1,2,3,4,5,9,9]],[10,[0,0,1,1,2,3,4,5,9,9]],[10,[0,0,1,1,2,3,4,5,9,9]]],[[12,[0,0,1,2,2,3,4,5,6,7,10,11]],[13,[0,1,2,2,3,4,5,6,6,7,7,10,11]],[12,[0,0,1,2,2,3,4,5,6,7,10,11]]],[[12,[0,0,1,2,2,3,4,5,6,7,10,11]],[13,[0,1,2,2,3,4,5,6,6,7,7,10,11]],[12,[0,0,1,2,2,3,4,5,6,7,10,11]]]],[[[10,[0,0,1,1,2,3,4,5,9,9]],[10,[0,0,1,1,2,3,4,5,9,9]],[10,[0,0,1,1,2,3,4,5,9,9]]],[[12,[0,0,0,1,1,1,2,3,4,5,8,10]],[12,[0,0,0,1,1,1,2,3,4,5,8,10]],[12,[0,0,0,1,1,1,2,3,4,5,8,10]]],[[12,[0,0,0,1,1,1,2,3,4,5,8,10]],[12,[0,0,0,1,1,1,2,3,4,5,8,10]],[12,[0,0,0,1,1,1,2,3,4,5,8,10]]]]],Ad=[[[[30,[13,23,30,31,32,33,34,35,36,37,38,40,43,44,45,47,48,49,50,51,52,54,56,57,64,66,75,76,86,89]],[31,[13,23,30,31,32,33,34,35,36,37,38,40,43,44,45,47,48,49,50,51,52,54,56,57,64,66,73,75,81,86,87]],[31,[13,23,30,31,32,33,34,35,36,37,38,40,43,44,45,47,48,49,50,51,52,54,56,57,64,66,73,75,81,86,87]]],[[38,[13,23,30,31,32,33,34,36,37,38,40,42,43,44,45,47,48,49,50,51,52,53,54,55,56,58,59,60,64,65,66,67,68,70,75,76,86,89]],[39,[13,23,30,31,32,33,34,36,37,38,39,40,43,44,45,47,48,49,50,51,52,53,54,55,56,58,59,60,64,65,66,67,68,70,73,75,81,86,87]],[39,[13,23,30,31,32,33,34,36,37,38,39,40,43,44,45,47,48,49,50,51,52,53,54,55,56,58,59,60,64,65,66,67,68,70,73,75,81,86,87]]],[[18,[13,23,30,36,37,41,45,47,51,53,54,55,58,59,65,67,86,88]],[19,[13,23,30,36,37,39,41,45,47,51,53,54,55,58,59,65,67,86,88]],[19,[13,23,30,36,37,39,41,45,47,51,53,54,55,58,59,65,67,86,88]]]],[[[39,[0,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,24,25,26,28,46,50,61,62,63,64,69,76,77,79,80,83,85]],[42,[0,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,24,25,26,28,46,50,61,62,63,64,69,72,74,77,78,82,83,84,85,87]],[42,[0,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,24,25,26,28,46,50,61,62,63,64,69,72,74,77,78,82,83,84,85,87]]],[[44,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,24,25,26,27,29,42,50,58,60,62,63,64,69,71,76,79,80,81,82,83,86]],[44,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,24,25,26,27,29,50,58,60,62,63,64,69,71,72,74,79,81,82,83,84,85]],[44,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,24,25,26,27,29,50,58,60,62,63,64,69,71,72,74,79,81,82,83,84,85]]],[[24,[0,1,2,3,4,5,6,10,11,12,13,14,16,17,18,20,21,24,25,58,62,69,76,83]],[27,[0,1,2,3,4,5,6,10,11,12,13,14,16,17,18,20,21,24,25,58,62,69,74,76,81,83,85]],[27,[0,1,2,3,4,5,6,10,11,12,13,14,16,17,18,20,21,24,25,58,62,69,74,76,81,83,85]]]]],Qd=[[[[26,[2,3,5,7,8,9,11,12,13,15,16,18,27,29,32,34,36,38,39,41,43,47,49,51,53,57]],[26,[2,3,5,7,8,9,11,12,13,15,16,18,27,29,32,34,36,38,39,41,43,47,49,51,53,57]],[27,[2,3,5,7,8,9,11,12,13,15,16,18,26,27,29,32,34,36,38,39,41,43,47,48,49,53,57]]],[[35,[2,3,5,6,7,8,9,11,12,13,15,16,17,18,21,22,27,29,31,32,34,36,37,38,39,41,43,44,47,49,51,53,55,56,57]],[35,[2,3,5,6,7,8,9,11,12,13,15,16,17,18,21,22,27,29,31,32,34,36,37,38,39,41,43,44,47,49,51,53,55,56,57]],[35,[2,3,5,6,7,8,9,11,12,13,15,16,18,21,22,26,27,29,31,32,34,36,37,38,39,41,43,44,47,48,49,50,53,56,57]]],[[30,[2,3,5,7,8,9,11,12,13,14,15,16,17,18,21,22,31,32,34,36,37,39,41,44,49,51,53,55,56,57]],[30,[2,3,5,7,8,9,11,12,13,14,15,16,17,18,21,22,31,32,34,36,37,39,41,44,49,51,53,55,56,57]],[30,[2,3,5,7,8,9,11,12,13,14,15,16,18,21,22,26,31,32,34,36,37,39,41,44,48,49,50,51,53,57]]]],[[[39,[0,1,2,4,5,7,8,9,10,11,12,13,15,16,18,19,23,24,25,27,28,29,32,33,34,35,38,39,40,41,42,45,46,47,48,53,54,57,59]],[39,[0,1,2,4,5,7,8,9,10,11,12,13,15,16,18,19,23,24,25,27,28,29,32,33,34,35,38,39,40,41,42,45,46,47,48,53,54,57,59]],[40,[0,1,2,4,5,7,8,9,10,11,12,13,15,16,18,19,23,24,25,26,27,28,29,32,33,34,35,38,39,40,41,42,45,46,47,48,53,54,57,59]]],[[46,[0,1,2,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,23,24,25,27,28,29,30,32,33,34,35,37,38,39,40,41,42,45,46,47,48,53,54,57,58,59]],[46,[0,1,2,4,5,6,7,8,9,10,11,12,13,15,16,17,18,19,20,21,23,24,25,27,28,29,30,32,33,34,35,37,38,39,40,41,42,45,46,47,48,53,54,57,58,59]],[46,[0,1,2,4,5,6,7,8,9,10,11,12,13,15,16,18,19,20,21,23,24,25,26,27,28,29,30,32,33,34,35,37,38,39,40,41,42,45,46,47,48,53,54,57,58,59]]],[[34,[0,1,2,4,5,7,8,9,10,11,12,13,15,16,18,19,23,24,25,27,28,29,32,33,34,35,38,39,40,41,42,45,46,47]],[34,[0,1,2,4,5,7,8,9,10,11,12,13,15,16,18,19,23,24,25,27,28,29,32,33,34,35,38,39,40,41,42,45,46,47]],[35,[0,1,2,4,5,7,8,9,10,11,12,13,15,16,18,19,23,24,25,26,27,28,29,32,33,34,35,38,39,40,41,42,45,46,47]]]]],Jd=[[[[18,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,17,18,20]],[18,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,17,18,20]],[18,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,17,18,20]]],[[23,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]],[23,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]],[23,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]]],[[21,[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,20,21,22]],[21,[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,20,21,22]],[21,[0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,20,21,22]]]],[[[9,[0,1,3,7,8,9,10,11,13]],[9,[0,1,3,7,8,9,10,11,13]],[9,[0,1,3,7,8,9,10,11,13]]],[[11,[0,1,3,7,8,9,10,11,13,15,19]],[11,[0,1,3,7,8,9,10,11,13,15,19]],[11,[0,1,3,7,8,9,10,11,13,15,19]]],[[9,[0,3,7,8,9,10,11,13,15]],[9,[0,3,7,8,9,10,11,13,15]],[9,[0,3,7,8,9,10,11,13,15]]]]],Kd=[[[[11,[0,1,2,3,4,5,7,8,10,13,14]],[11,[0,1,2,3,4,5,7,8,10,13,14]],[11,[0,1,2,3,4,5,7,8,10,13,14]]],[[18,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]],[18,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]],[15,[0,1,2,3,4,5,6,7,8,10,11,12,13,14,16]]],[[18,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]],[18,[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]],[15,[0,1,2,3,4,5,6,7,8,10,11,12,13,14,16]]]],[[[8,[0,1,3,4,8,10,13,14]],[8,[0,1,3,4,8,10,13,14]],[8,[0,1,3,4,8,10,13,14]]],[[12,[0,1,3,4,6,8,9,10,11,13,14,15]],[11,[0,1,3,4,6,8,9,10,11,13,15]],[10,[0,1,3,4,6,8,10,11,13,14]]],[[12,[0,1,3,4,6,8,9,10,11,13,14,15]],[11,[0,1,3,4,6,8,9,10,11,13,15]],[10,[0,1,3,4,6,8,10,11,13,14]]]]],Cd=[[[[25,[0,2,3,6,7,8,9,10,12,14,15,17,18,19,21,22,23,25,26,28,30,32,33,34,35]],[27,[0,2,3,6,7,8,9,10,11,12,13,14,15,17,18,19,21,22,23,25,26,28,30,32,33,34,35]],[28,[0,2,3,6,7,8,9,10,11,12,13,14,15,17,18,19,21,22,23,25,26,28,30,31,32,33,34,35]]],[[24,[0,2,3,6,7,8,9,10,12,14,15,16,17,18,19,20,21,22,23,30,31,33,34,35]],[26,[0,2,3,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,30,31,33,34,35]],[26,[0,2,3,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,30,31,33,34,35]]],[[24,[0,2,3,6,7,8,9,10,12,14,15,16,17,18,19,20,21,22,23,30,31,33,34,35]],[26,[0,2,3,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,30,31,33,34,35]],[26,[0,2,3,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,30,31,33,34,35]]]],[[[25,[0,1,2,3,4,5,6,7,8,9,12,14,15,17,18,19,21,22,23,25,26,30,33,34,35]],[26,[0,1,2,3,4,5,6,7,8,9,12,13,14,15,17,18,19,21,22,23,25,26,30,33,34,35]],[26,[0,1,2,3,4,5,6,7,8,9,12,13,14,15,17,18,19,21,22,23,25,26,30,33,34,35]]],[[25,[0,1,2,3,4,5,6,7,8,9,12,14,15,17,18,19,21,22,23,24,26,27,29,33,35]],[26,[0,1,2,3,4,5,6,7,8,9,12,13,14,15,17,18,19,21,22,23,24,26,27,29,33,35]],[25,[0,1,2,3,4,5,6,7,8,9,12,13,14,15,17,18,19,21,22,23,24,25,29,33,35]]],[[24,[0,1,2,3,4,5,6,7,8,9,12,14,15,16,17,18,19,21,22,23,25,26,29,33]],[25,[0,1,2,3,4,5,6,7,8,9,12,13,14,15,16,17,18,19,21,22,23,25,26,29,33]],[25,[0,1,2,3,4,5,6,7,8,9,12,13,14,15,16,17,18,19,21,22,23,25,26,29,33]]]]],Yd=[[[[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,8]]],[[20,[0,0,0,0,0,0,0,0,0,1,1,2,3,4,5,6,7,8,8,9]],[20,[0,0,0,0,0,0,0,0,0,1,1,2,3,4,5,6,7,8,8,9]],[20,[0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9]]],[[20,[9,9,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11]],[20,[9,9,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11]],[20,[9,9,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11]]]],[[[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8]]],[[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,4,4,8,8]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,4,4,8,8]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,4,4]]],[[20,[9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,11,11,11,11,11]],[20,[9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,11,11,11,11,11]],[20,[9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,11,11,11,11,11]]]]],Ud=[[[[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,9,9,9]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,9]]],[[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,9,9]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,9,9]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,9,9]]],[[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,9,9]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,9,9]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,9,9]]]],[[[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2]],[20,[0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,9,9]],[20,[0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,9,9]]],[[20,[0,0,0,0,0,0,0,0,1,1,2,3,3,4,5,5,6,7,8,9]],[20,[0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9]],[20,[0,0,0,0,0,0,1,1,2,2,3,3,4,4,5,6,7,8,9,9]]],[[20,[0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9]],[20,[0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9]],[20,[0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9]]]]],Zd=[[[10,[2,2,4,4,4,4,5,5,5,5]],[10,[0,0,0,0,1,1,2,3,3,3]],[10,[0,0,1,1,1,1,1,1,1,2]]],[[10,[2,2,4,4,4,4,5,5,5,5]],[10,[0,0,0,0,0,0,0,0,1,3]],[10,[0,0,0,0,0,0,0,0,1,1]]]],Bd=[[[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],[20,[0,0,0,0,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4]]],[[20,[2,3,3,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7,7]],[20,[2,3,3,3,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7]],[20,[2,3,3,4,4,4,4,4,4,5,6,6,6,6,7,7,7,7,7,7]]],[[20,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]],[20,[0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,3,3,3,3,3]],[20,[4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4]]]],Xd=[[10,[0,0,0,0,0,0,0,0,0,1]],[10,[0,1,1,2,3,3,4,4,4,5]],[10,[0,0,0,0,0,0,0,0,0,1]]];function VW(A){return 32-[6,6,5,7,6,7,6,7,4,7,6,8,5,5,6,6,7,7,6,6,5,6,7,5,6,6,6,6][A]}var Ed=5;function HE1(A,Q,J){let K=A,C=Q,U=J;if(A==2)K=Math.floor(Math.random()*2)==0?0:1;if(Q==3){let Y=Math.floor(Math.random()*10);C=Y<4?0:Y<8?1:2}if(J==3){let Y=Math.floor(Math.random()*10);U=Y<4?2:Y<8?1:0}return[K,C,U]}function GE1(A){let Q=Math.floor(Math.random()*100),J=0;while(Q>=WE1[A][J])J++;return J}function v5(A){return A[1][Math.floor(Math.random()*A[0])]}var WE1=[[90,94,96,100,0,0,0,0,0],[83,86,90,93,94,96,98,100,0],[78,83,0,93,0,0,98,100,0]];function hB(A,Q){let[J,K,C]=[2,3,3],[U,Y,Z]=HE1(J,K,C);if(Q.age!==void 0)Y=Q.age;if(Q.gender!==void 0)U=Q.gender;if(Q.race!==void 0)Z=Q.race;console.log("Gender,age,race",U,Y,Z),A.deviceOrigin=3;let X=0;if(U==1||Y==0)X=Math.floor(Math.random()*3);if(A.faceType=v5(ec[U][Y][Z]),A.skinColor=v5(Zd[U][Z]),A.wrinklesType=v5(Yd[U][Y][Z]),A.makeupType=v5(Ud[U][Y][Z]),A.hairType=v5(Ad[U][Y][Z]),A.hairColor=v5(Bd[Z][Y]),Q.hairColor!==void 0)A.hairColor=Q.hairColor;if(A.flipHair=Boolean(Math.ceil(Math.random()*2)),A.eyeType=v5(Qd[U][Y][Z]),A.eyeColor=v5(Xd[Z]),Q.eyeColor!==void 0)A.eyeColor=Q.eyeColor;A.eyeScale=4,A.eyeVerticalStretch=3;let E;if(U==0)A.eyeRotation=4,E=DW(2);else A.eyeRotation=3,E=DW(4);let H=DW(A.eyeType);A.eyeSpacing=2,A.eyeYPosition=X+12,A.eyeRotation+=E-H,A.eyebrowType=v5(Jd[U][Y][Z]),A.eyebrowColor=A.hairColor,A.eyebrowScale=4,A.eyebrowVerticalStretch=3,A.eyebrowRotation=6,A.eyebrowSpacing=2;let $;if(Z==2)A.eyebrowYPosition=X+9,$=VW(6);else A.eyebrowYPosition=X+10,$=VW(0);let I=VW(A.eyebrowType);A.eyebrowRotation+=$-I,A.noseType=v5(Kd[U][Y][Z]),A.noseScale=U==0?4:3,A.noseYPosition=X+9,A.mouthType=v5(Cd[U][Y][Z]),A.mouthColor=U==0?0:Math.floor(Math.random()*Ed),A.mouthScale=4,A.mouthHorizontalStretch=3,A.mouthYPosition=X+13;let N,F,V;if(U==0&&(Y==1||Y==2)&&Math.floor(Math.random()*10)<2){N=0;let D=!1;switch(Math.floor(Math.random()*3)){case 0:D=!0;break;case 2:D=!0;case 1:N=Math.floor(Math.random()*5)+1;break}F=D?Math.floor(Math.random()*5)+1:0,V=10}else N=0,F=0,V=X+10;if(A.mustacheType=N,A.beardType=F,A.facialHairColor=A.hairColor,A.mustacheScale=4,A.mustacheYPosition=V,A.glassesType=GE1(Y),A.glassesColor=0,A.glassesScale=4,A.glassesYPosition=X+10,A.moleEnabled=Boolean(0),A.moleScale=4,A.moleXPosition=2,A.moleYPosition=20,A.height=64,A.build=64,A.miiName="no name",A.gender=U,A.birthMonth=0,A.birthDay=0,A.favoriteColor=Math.floor(Math.random()*12),Q.favoriteColor!==void 0)A.favoriteColor=Q.favoriteColor;A.favorite=!1,A.allowCopying=!0,A.profanityFlag=!1,A.regionLock=0,A.characterSet=0,A.pageIndex=0,A.slotIndex=0,A.deviceOrigin=4}window.mii=mA;window.FFLiDatabaseRandom_Get=hB;var Hd=async()=>{var A=y0.modal("Choose a look-alike","","body",{text:"Cancel",callback(Z){n9()}},{text:"Confirm"});A.classOn("random-mii-grid");let Q=A.qs(".modal-body");Q.qsa("span,.flex-group *").forEach((Z)=>Z.style({display:"none"}));let J=new f1("div").class("random-mii-container").appendTo(Q),K=Q.qs(".flex-group");Q.prepend(new f1("span").style({width:"100%",padding:"14px 18px",background:"var(--hover)",color:"var(--text)",border:"1px solid var(--stroke)","border-radius":"6px","flex-shrink":"0"}).text("All of the options here are what Nintendo originally programmed in. Please let me know if you want more options added.")),new f1("button").class("primary").text("Reroll").on("click",()=>Y()).appendTo(K);let C={};function U(Z,X){return console.log(X),new f1("select").appendMany(...X).on("input",(E)=>{if(C[Z]=parseInt(E.target.value),C[Z]===-1)delete C[Z];console.log(C)})}K.prependMany(U("race",[new Option("Skin tone","-1",!0,!0),new Option("(Random)","-1"),new Option("Black","0"),new Option("White","1"),new Option("Asian","2")]),U("gender",[new Option("Gender","-1",!0,!0),new Option("(Random)","-1"),new Option("Male","0"),new Option("Female","1")]),U("hairColor",[new Option("Hair color","-1",!0,!0),new Option("(Random)","-1"),new Option("Black","0"),new Option("Brown","1"),new Option("Red","2"),new Option("Light brown","3"),new Option("Gray","4"),new Option("Green","5"),new Option("Dirty blonde","6"),new Option("Blonde","7")]),U("favoriteColor",[new Option("Favorite color","-1",!0,!0),new Option("(Random)","-1"),new Option("Red","0"),new Option("Orange","1"),new Option("Yellow","2"),new Option("Lime","3"),new Option("Green","4"),new Option("Blue","5"),new Option("Cyan","6"),new Option("Pink","7"),new Option("Purple","8"),new Option("Brown","9"),new Option("White","10"),new Option("Black","11")]),U("eyeColor",[new Option("Eye color","-1",!0,!0),new Option("(Random)","-1"),new Option("Black","0"),new Option("Gray","1"),new Option("Brown","2"),new Option("Hazel","3"),new Option("Blue","4"),new Option("Green","5")]),U("age",[new Option("Age","-1",!0,!0),new Option("(Random)","-1"),new Option("Child","0"),new Option("Adult","1"),new Option("Elder","2")]));function Y(){J.clear();for(let Z=0;Z<21;Z++){let X=new mA(QA.from("AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn","base64"));hB(X,C);let E=new f1("button").append(new f1("img").attr({src:""})).appendTo(J);H3(X,"lookalike").then(($)=>{TD(),E.qs("img")?.attr({src:$})});let H=X.encode().toString("base64");E.on("click",()=>{A.qs(".flex-group button")?.elm.click(),G6()(),new V8(0,async($,I)=>{if(I===!0)await $d.default.setItem(await q9(),$);$8()},H)})}}Y()};var Gd=j2(u8(),1);var Wd=async()=>{O9.show();let A=await fetch(d0.apis.nnidRandomURL).then((Q)=>Q.json());O9.hide(),G6()(),new V8(0,async(Q,J)=>{if(J===!0)await Gd.default.setItem(await q9(),Q);$8()},A.data)};var n9=()=>{y0.modal("New Mii","How would you like to create the Mii?","body",{text:"From Scratch",type:"primary",callback:()=>{cc()}},{text:"QR Code",callback:()=>{ac()}},{text:"FFSD/MiiCreator data",callback:()=>{let Q,J=y0.modal("Import FFSD/MiiCreator data","","body",{text:"Cancel",callback:()=>{n9()}},{text:"Confirm",callback(){$8(Q)}});J.qsa(".modal-body .flex-group,.modal-body span").forEach((K)=>K.style({display:"none"})),J.qs(".modal-body").appendMany(new f1("span").text("Select a FFSD or .miic file to import"),new f1("input").attr({type:"file",accept:".ffsd,.cfsd,.miic"}).style({margin:"auto"}).on("change",(K)=>{let C=K.target;console.log("Files",C.files);let U=new FileReader;U.readAsArrayBuffer(C.files[0]),U.onload=async()=>{try{let Y=QA.from(U.result),X=new mA(Y).encode().toString("base64");Q=await q9(),await Id.default.setItem(Q,X),G6()(),J.qs(".modal-body button").elm.click()}catch(Y){y0.alert("Error",`Invalid Mii data: ${Y}`),C.value=""}}}))}},{text:"Enter NNID/PNID",callback:()=>{y0.modal("Enter NNID/PNID","Select a service to look up","body",{text:"Cancel"},{text:"Enter Nintendo Network ID",callback(Q){rc()}},{text:"Enter Pretendo Network ID",callback(Q){tc()}})}},{text:"Choose a look-alike",callback:()=>{Hd()}},{text:"Random NNID",callback:()=>{Wd()}},{text:"Cancel"}).qs(".modal-body").styleJs({maxWidth:"600px"})};var IE1=async()=>(await gB.default.keys()).filter((A)=>A.startsWith("mii-")).length,q9=async()=>`mii-${Date.now()}-${await IE1()}`,TD=()=>{setTimeout(()=>{if(NK(2)!==0)return;I2(`load${NK(4)+1}`)},NK(200))},kD;var qE1=document.createElement("canvas");document.body.appendChild(qE1);kD=new q4({alpha:!0,preserveDrawingBuffer:!0});var H3=async(A,Q="unknown",J="variableiconbody",K=180,C=0)=>{if(d0.renderer.useRendererServer===!1){let Z="undefined",X,E=A.encodeStudio();if(qd())return console.log("Asking worker thread for an icon plz!"),await Od(E,J);try{X=KY(E,void 0,window.LUTShaderMaterial,jB(),!1),CY(X,kD);let H=q7.MakeIcon;switch(J){case"face":case"variableiconbody":H=q7.MakeIcon;break;case"all_body_sugar":H=q7.MakeIcon;break}Z=await Dc(X,kD,H,512,512)}catch(H){console.error(`Library: Could not make icon for ${A.miiName}: ${H}`)}finally{return X.dispose(),Z}}let U=d0.renderer.renderHeadshotURLNoParams,Y=new URLSearchParams;if(Y.set("data",A.encodeStudio().toString("hex")),PG(Y,jD),Y.set("bodyType",vD),Y.set("type",J),Y.set("width",K.toString()),Y.set("verifyCharInfo","0"),Y.set("miic",encodeURIComponent(A.encode().toString("base64"))),Y.set("version",d0.version.string),Y.set("source",Q?"library":"lookalike"),Y.set("index",C.toString()),Y.set("pantsColor",A.normalMii===!1?"gold":A.favorite===!0?"red":"gray"),A.extHatType!==0)Y.set(d0.renderer.hatTypeParam,String(A.extHatType+d0.renderer.hatTypeAdd));if(A.extHatColor!==0)Y.set(d0.renderer.hatColorParam,String(A.extHatColor+d0.renderer.hatColorAdd));return`${U}?${Y.toString()}`},jD="wiiu";document.addEventListener("library-shader-update",async()=>{jD=await SA("shaderType")});var vD="wiiu";document.addEventListener("library-body-update",async()=>{vD=await SA("bodyModel")});var SD=()=>{console.log("Shutdown was called but was not set yet!")},G6=()=>SD;async function $8(A){jD=await SA("shaderType"),vD=await SA("bodyModel");function Q(){return new Promise((X)=>{J.class("fadeOut"),setTimeout(()=>{J.cleanup(),X()},500)})}SD=Q;let J=new f1("div").class("mii-library").appendTo("body"),K=new f1("div").class("library-sidebar").appendTo(J);K.append(new f1("h1").text(RD("generic.app_title")));let C=new f1("div").class("library-list").appendTo(J),U=await Promise.all((await gB.default.keys()).filter((X)=>X.startsWith("mii-")).sort((X,E)=>Number(X.split("-")[1])-Number(E.split("-")[1])).map(async(X)=>({id:X,mii:await gB.default.getItem(X)})));if(U.length===0)C.append(new f1("div").style({position:"absolute",top:"2rem",left:"2rem"}).text("You have no Miis yet. Create one to get started!"));let Y=0,Z=0;for(let X of U){let E=new f1("div").class("library-list-mii");f2(E);try{let H=new mA(QA.from(X.mii,"base64"));H.unknown1=0,H.unknown2=0;let $=!1;if(H.consoleMAC[0]===47&&H.consoleMAC[1]===249&&H.consoleMAC[2]===22&&H.consoleMAC[3]===28&&H.consoleMAC[4]===250&&H.consoleMAC[5]===173)E.classOn("highlight").style({"--selection-color":"#ffbf00"}),$=!0;E.style({"--color":r7[H.favoriteColor].top});let I="";if(H.extHatType!==0)I+=`&${d0.renderer.hatTypeParam}=${encodeURIComponent(H.extHatType+d0.renderer.hatTypeAdd)}&${d0.renderer.hatColorParam}=${encodeURIComponent(H.extHatColor+d0.renderer.hatColorAdd)}`;let N=new f1("img").class("lazy").attr({});if(H3(H,"library","variableiconbody",180,Z).then((L)=>{N.attr({src:L})}),H.normalMii===!1||H.favorite===!0||$){let L=new f1("i").style({position:"absolute",top:"-22px",right:"-18px"}).appendTo(E);if(H.favorite===!0)L.html(N0.favorite).style({color:RG});if(H.normalMii===!1||$)L.html(N0.special).style({color:zG})}let F=new f1("span").text(H.miiName),V=uc(X,H,$);E.on("click",async()=>{if(D===!0){y0.modal("Oops","This Mii hasn't loaded correctly. Do you still want to try and manage it?","body",{text:"Cancel"},{callback(L){V()},text:"Yes"},{text:"No"});return}V()});let D=!1;N.on("error",()=>{if(D===!0)return;N.attr({src:"data:image/svg+xml,"+encodeURIComponent(N0.error)}),D=!0}),N.on("load",()=>{TD()}),E.appendMany(N,F).appendTo(C),requestAnimationFrame(()=>{if(A!==void 0){if(A===X.id){E.classOn("highlight"),setTimeout(()=>{if($===!1)E.classOff("highlight")},2000);let L=E.elm;L.closest(".library-list").scroll({top:L.getBoundingClientRect().top+L.getBoundingClientRect().height,behavior:"smooth"})}}}),Z++}catch(H){console.log("Oops",H),Y++;let $=new f1("img").attr({src:"data:image/svg+xml,"+encodeURIComponent(N0.error)}),I=new f1("span").text("?");E.appendMany($,I).appendTo(C),E.on("click",async()=>{y0.modal("Oops","This Mii might be corrupted. Choose an option below.","body",{text:"Cancel"},{text:"Download a copy",callback(N){console.log(X),NJ(QA.from(X.mii,"base64").buffer,X.id+".miic")}},{text:"Download a copy (Base64 encoded)",callback(N){console.log(X),NJ(QA.from(X.mii).buffer,X.id+".miic.txt")}},{text:"Delete",callback(N){y0.modal("Warning","Are you sure you want to delete this Mii?","body",{async callback(F){await gB.default.removeItem(X.id),await SD(),$8()},text:"Yes",type:"danger"},{text:"No"})}})})}}if(Y>0)y0.modal("Error",`It appears that ${Y} of your Miis have failed to load. Their data may be corrupted. - -If you'd like to try and recover the Mii data, you can select the Miis with errors and choose to either save a copy or delete them.`,"body",...x3);window.LazyLoad.update(),K.appendMany(new f1("div").class("sidebar-buttons").appendMany(f2(new f1("button").text("Create Mii").on("click",async()=>{n9()})),f2(new f1("button").text("Settings").on("click",async()=>{TG()}))),new f1("div").class("sidebar-credits").appendMany(new f1("div").class("flex-group").style({width:"100%"}).appendMany(f2(new f1("button").text("Credits").on("click",async()=>{var X=y0.modal("Credits","","body",{text:"Cancel"},{text:"OK"});X.qs(".modal-body span").cleanup(),X.qs(".modal-content").style({"max-width":"100%","max-height":"100%"});let E=X.qs(".modal-body");X.qs(".modal-content").style({position:"relative"});let H=new f1("div").class("col").prependTo(E);new f1("span").text("Check out the people behind Mii Creator!").style({"font-size":"20px","flex-shrink":"0","margin-bottom":"-16px"}).prependTo(E),new f1("a").text("secret?").style({"font-size":"10px",opacity:"0.3",cursor:"pointer",position:"absolute",bottom:"10px",right:"10px"}).on("click",($)=>{X.qs("button")?.elm.click();let I=new mA(QA.from("A8EAwELycUHCpfBSXhcDbS/5Fhz6rQAAWS1KAGEAcwBtAGkAbgBlAAAAAAAAABw3ExB7ASFuQxwNZMcYAAgegg0AMEGzW4JtcwBvAHMAaQBnAG8AbgBhAGwAAAAAAMwDAAAAAAAAAAAAAAAA","base64"));LJ(I,"Mii Creator (Special Mii)")}).appendTo(E),YY(H,"Austin☆²¹ / Kat21","datkat21","https://github.com/datkat21","Author of Mii Creator","00070e555d5863674e53666975777c767c7d848b9299989f9ea1a8a9b5bc89e1e9efececf6ecf6ece8f3faf7fbfdfe"),YY(H,"Arian","ariankordi","https://github.com/ariankordi",'Creator of Mii Renderer (REAL) and was a big help with debugging many issues',"080037030d020531020c030105040a0209000001000a011004010b0100662f04000214031603140d04000a020109"),YY(H,"obj","objecty","https://x.com/objecty_twitt","Composed the music for the site","00070e3b3f3c4649555e5c6675777a7a7f7e818890979ea5b4b7bebbbac188bdc6ced4ccd6cccfe3f5f8fffcff0513"),YY(H,"Timothy","Timimimi","https://github.com/Timiimiimii","Modeled many of the custom hats and helped with debugging","00070e3c4554575c616c6872818b909da0b1b7bec3cad0d78f93a1b1c0c78ce8f0f8fdf2f8f3f7ebebf6fdfcfffffb"),YY(H,"David J.","dwyazzo90","https://x.com/dwyazzo90","Helped with design and created the Wii U theme","0800450308040402020c0308060406020a0001000006000804000a0800326702010314031304190d04000a040109")}).style({flex:"1"})),f2(new f1("button").text("Help/Contact").on("click",async()=>{var X=y0.modal("Contact","","body",{text:"Cancel"},{text:"OK"});X.qs(".modal-body span").cleanup(),X.qs(".modal-content").style({"max-width":"100%","max-height":"100%"});let E=X.qs(".modal-body");X.qs(".modal-content").style({position:"relative"});let H=new f1("div").class("col").style({gap:"0"}).prependTo(E);new f1("span").text("Here's where you can contact the author, Kat21").style({"font-size":"20px","flex-shrink":"0","margin-bottom":"-16px"}).prependTo(E),new f1("a").text("secret?").style({"font-size":"10px",opacity:"0.3",cursor:"pointer",position:"absolute",bottom:"10px",left:"10px"}).on("click",($)=>{X.qs("button")?.elm.click();let I=new mA(QA.from("AwEAwAAAAAAAAAAAAP91dC/5Fhz6rQAAAChiAG8AbwBlAHkAAAAAAAAAAAAAABRvEwBJBBJvQxgNVGUUABoTqAoAACmwUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE8TAGMyCAAANgACC2QA","base64"));LJ(I,"Mii Creator (Special Mii)")}).appendTo(E),OW(H,"E-mail (Preferred)","mailto:datkat21.yt@gmail.com","datkat21.yt@gmail.com",N0.contact_email),OW(H,"Discord","","kat21",N0.contact_discord),OW(H,"File an issue on GitHub","https://github.com/datkat21/mii-creator","datkat21/mii-creator",N0.contact_github)}).style({flex:"1"}))),new f1("strong").text("This site is not affiliated with Nintendo."),new f1("small").text(`${d0.version.string} (${d0.version.name})`).style({cursor:"pointer"}).on("click",()=>{nR()})))}var fc=async(A)=>{if(A.hasExtendedColors()===!0){if(await y0.prompt("Warning","This Mii is using extended Switch colors, but those colors will never show up if you scan this QR Code anywhere outside of this app. Is this OK?","body",!1)===!1)return!1}return!0},pc=async(A)=>{if(A.hasExtendedColors()===!0){if(await y0.prompt("Warning",`This Mii is using extended Switch colors and/or MiiCreator features, but those features will be lost when converting to FFSD. -Use "Save MiiCreator data" or "Save CharInfo (Switch) data" if you want to keep the data. -Is this OK?`,"body",!1)===!1)return!1}return!0};var N7=j2(u8(),1);var OE1=async()=>(await N7.default.keys()).filter((A)=>A.startsWith("mii-")).length,bB=async()=>`mii-${await OE1()}-${Date.now()}`,Nd=(A)=>`${d0.renderer.renderHeadshotURLNoParams}?data=${A.encodeStudio().toString("hex")}&shaderType=wiiu&type=face&width=180&verifyCharInfo=0`;function L7(A){return new Promise(async(Q,J)=>{function K(){return new Promise((Z)=>{C.class("fadeOut"),setTimeout(()=>{C.cleanup(),Z()},500)})}let C=new f1("div").class("mii-library").appendTo("body"),U=new f1("div").class("library-list").appendTo(C),Y=await Promise.all((await N7.default.keys()).filter((Z)=>Z.startsWith("mii-")).sort((Z,X)=>Number(Z.split("-")[1])-Number(X.split("-")[1])).map(async(Z)=>({id:Z,mii:await N7.default.getItem(Z)})));if(Y.length===0)U.appendMany(new f1("div").style({position:"absolute",top:"2rem",left:"2rem"}).text("You have no Miis yet. Create one to get started!"),f2(new f1("button").style({position:"absolute",top:"4rem",left:"2rem"}).text("Create New").on("click",async()=>{await K(),MW()})));for(let Z of Y){let X=new f1("div").class("library-list-mii");f2(X);let E=new mA(QA.from(Z.mii,"base64"));try{E.unknown1=0,E.unknown2=0;let H=new f1("img").class("lazy").attr({"data-src":Nd(E)});if(E.normalMii===!1||E.favorite===!0){let F=new f1("i").style({position:"absolute",top:"0",right:"0"}).appendTo(X);if(E.normalMii===!1)F.html(N0.special).style({color:zG});if(E.favorite===!0)F.html(N0.favorite).style({color:RG})}if(E.extHatType!==0)new f1("i").style({position:"absolute",top:"0",left:"0"}).appendTo(X).html(N0.hat).style({color:E.extHatColor!==0?r7[E.extHatColor-1].top:r7[E.favoriteColor].top});let $=new f1("span").text(E.miiName),I=()=>{y0.modal("Mii Options","What would you like to do?","body",{text:"Select",async callback(){await K(),Q(E)}},{text:"Cancel"}).qs(".modal-body")?.prepend(new f1("img").attr({src:Nd(E)}).style({width:"180px",margin:"-18px auto 0 auto"}))};X.on("click",async()=>{if(N===!0){if(await y0.prompt("Oops","This Mii hasn't loaded correctly. Do you still want to try and manage it?")===!1)return}I()});let N=!1;H.on("error",()=>{if(N===!0)return;H.attr({src:"data:image/svg+xml,"+encodeURIComponent(N0.error)}),N=!0}),X.appendMany(H,$).appendTo(U),requestAnimationFrame(()=>{if(A!==void 0){if(A===Z.id){X.classOn("highlight"),setTimeout(()=>{X.classOff("highlight")},2000);let F=X.elm;F.closest(".library-list").scroll({top:F.getBoundingClientRect().top+F.getBoundingClientRect().height,behavior:"smooth"})}}})}catch(H){console.log("Oops",H)}}window.LazyLoad.update()})}var MW=()=>{y0.modal("Create New","How would you like to create the Mii?","body",{text:"From Scratch",callback:NE1},{text:"Enter PNID",callback:LE1},{text:"Random Mii",callback:RE1},{text:"Random NNID",callback:FE1},{text:"Import FFSD/MiiCreator data",callback:()=>{let A,Q=y0.modal("Import FFSD/MiiCreator data","","body",{text:"Cancel",callback:MW},{text:"Confirm",callback(){L7(A)}});Q.qsa(".modal-body .flex-group,.modal-body span").forEach((J)=>J.style({display:"none"})),Q.qs(".modal-body").appendMany(new f1("span").text("Select a FFSD or .miic file to import"),new f1("input").attr({type:"file",accept:".ffsd,.cfsd,.miic"}).style({margin:"auto"}).on("change",(J)=>{let K=J.target;console.log("Files",K.files);let C=new FileReader;C.readAsArrayBuffer(K.files[0]),C.onload=async()=>{try{let U=QA.from(C.result),Z=new mA(U).encode().toString("base64");A=await bB(),await N7.default.setItem(A,Z),Q.qs(".modal-body button").elm.click()}catch(U){y0.alert("Error",`Invalid Mii data: ${U}`),K.value=""}}}))}},{text:"Cancel",callback:()=>L7()})},NE1=()=>{function A(Q){return()=>{new V8(Q,async(J,K)=>{if(K===!0)await N7.default.setItem(await bB(),J);L7()})}}y0.modal("Create New","Select the Mii's gender","body",{text:"Male",callback:A(0)},{text:"Female",callback:A(1)},{text:"Cancel",callback:()=>MW()})},LE1=async()=>{let A=await y0.input("Create New","Enter PNID of user..","Username","body",!1);if(A===!1)return MW();O9.show();let Q=await fetch(d0.apis.pnidFetchURL(encodeURIComponent(A)));if(O9.hide(),!Q.ok)return await y0.alert("Error",`Couldn't get Mii: ${await Q.text()}`),L7();new V8(0,async(J,K)=>{if(K===!0)await N7.default.setItem(await bB(),J);L7()},(await Q.json()).data)},FE1=async()=>{O9.show();let A=await fetch(d0.apis.nnidRandomURL).then((Q)=>Q.json());O9.hide(),new V8(0,async(Q,J)=>{if(J===!0)await N7.default.setItem(await bB(),Q);L7()},A.data)},RE1=async()=>{let A=new mA(QA.from("AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn","base64"));hB(A,{}),new V8(0,async(Q,J)=>{if(J===!0)await N7.default.setItem(await bB(),Q);L7()},A.encode().toString("base64"))};var el=j2(tl(),1);window.KaitaiStream=el.default;console.log("LOADED STRUCTS");var a9=window;(function(A,Q){A.Gen1Wii=Q(A.KaitaiStream)})(typeof a9!=="undefined"?a9:null,function(A){var Q=function(){function J(K,C,U){this._io=K,this._parent=C,this._root=U||this,this._read()}return J.prototype._read=function(){this.invalid=this._io.readBitsIntBe(1)!=0,this.gender=this._io.readBitsIntBe(1)!=0,this.birthMonth=this._io.readBitsIntBe(4),this.birthDay=this._io.readBitsIntBe(5),this.favoriteColor=this._io.readBitsIntBe(4),this.favorite=this._io.readBitsIntBe(1)!=0,this._io.alignToByte(),this.miiName=A.bytesToStr(this._io.readBytes(20),"utf-16be"),this.bodyHeight=this._io.readU1(),this.bodyWeight=this._io.readU1(),this.avatarId=[];for(var K=0;K<4;K++)this.avatarId.push(this._io.readU1());this.clientId=[];for(var K=0;K<4;K++)this.clientId.push(this._io.readU1());this.faceType=this._io.readBitsIntBe(3),this.faceColor=this._io.readBitsIntBe(3),this.facialFeature=this._io.readBitsIntBe(4),this.unknown=this._io.readBitsIntBe(3),this.mingle=this._io.readBitsIntBe(1)!=0,this.unknown2=this._io.readBitsIntBe(1)!=0,this.downloaded=this._io.readBitsIntBe(1)!=0,this.hairType=this._io.readBitsIntBe(7),this.hairColor=this._io.readBitsIntBe(3),this.hairFlip=this._io.readBitsIntBe(1)!=0,this.unknown3=this._io.readBitsIntBe(5),this.eyebrowType=this._io.readBitsIntBe(5),this.unknown4=this._io.readBitsIntBe(1)!=0,this.eyebrowRotation=this._io.readBitsIntBe(4),this.unknown5=this._io.readBitsIntBe(6),this.eyebrowColor=this._io.readBitsIntBe(3),this.eyebrowSize=this._io.readBitsIntBe(4),this.eyebrowVertical=this._io.readBitsIntBe(5),this.eyebrowHorizontal=this._io.readBitsIntBe(4),this.eyeType=this._io.readBitsIntBe(6),this.unknown6=this._io.readBitsIntBe(2),this.eyeRotation=this._io.readBitsIntBe(3),this.eyeVertical=this._io.readBitsIntBe(5),this.eyeColor=this._io.readBitsIntBe(3),this.unknown7=this._io.readBitsIntBe(1)!=0,this.eyeSize=this._io.readBitsIntBe(3),this.eyeHorizontal=this._io.readBitsIntBe(4),this.unknown8=this._io.readBitsIntBe(5),this.noseType=this._io.readBitsIntBe(4),this.noseSize=this._io.readBitsIntBe(4),this.noseVertical=this._io.readBitsIntBe(5),this.unknown9=this._io.readBitsIntBe(3),this.mouthType=this._io.readBitsIntBe(5),this.mouthColor=this._io.readBitsIntBe(2),this.mouthSize=this._io.readBitsIntBe(4),this.mouthVertical=this._io.readBitsIntBe(5),this.glassesType=this._io.readBitsIntBe(4),this.glassesColor=this._io.readBitsIntBe(3),this.unknown10=this._io.readBitsIntBe(1)!=0,this.glassesSize=this._io.readBitsIntBe(3),this.glassesVertical=this._io.readBitsIntBe(5),this.facialHairMustache=this._io.readBitsIntBe(2),this.facialHairBeard=this._io.readBitsIntBe(2),this.facialHairColor=this._io.readBitsIntBe(3),this.facialHairSize=this._io.readBitsIntBe(4),this.facialHairVertical=this._io.readBitsIntBe(5),this.moleEnable=this._io.readBitsIntBe(1)!=0,this.moleSize=this._io.readBitsIntBe(4),this.moleVertical=this._io.readBitsIntBe(5),this.moleHorizontal=this._io.readBitsIntBe(5),this.unknown11=this._io.readBitsIntBe(1)!=0,this._io.alignToByte(),this.creatorName=A.bytesToStr(this._io.readBytes(20),"utf-16be")},J}();return Q});(function(A,Q){A.Gen2Wiiu3dsMiitomo=Q(A.KaitaiStream)})(typeof a9!=="undefined"?a9:null,function(A){var Q=function(){function J(K,C,U){this._io=K,this._parent=C,this._root=U||this,this._read()}return J.prototype._read=function(){this.unknown1=this._io.readU1(),this.characterSet=this._io.readBitsIntBe(2),this.regionLock=this._io.readBitsIntBe(2),this.profanityFlag=this._io.readBitsIntBe(1)!=0,this.copying=this._io.readBitsIntBe(1)!=0,this.unknown2=this._io.readBitsIntBe(2),this.miiPositionSlotIndex=this._io.readBitsIntBe(4),this.miiPositionPageIndex=this._io.readBitsIntBe(4),this.version=this._io.readBitsIntBe(4),this.unknown3=this._io.readBitsIntBe(4),this._io.alignToByte(),this.systemId=[];for(var K=0;K<8;K++)this.systemId.push(this._io.readU1());this.avatarId=[];for(var K=0;K<4;K++)this.avatarId.push(this._io.readU1());this.clientId=[];for(var K=0;K<6;K++)this.clientId.push(this._io.readU1());this.padding=this._io.readU2le(),this.data1=this._io.readU2le(),this.miiName=A.bytesToStr(this._io.readBytes(20),"utf-16le"),this.bodyHeight=this._io.readU1(),this.bodyWeight=this._io.readU1(),this.faceColor=this._io.readBitsIntBe(3),this.faceType=this._io.readBitsIntBe(4),this.mingle=this._io.readBitsIntBe(1)!=0,this.faceMakeup=this._io.readBitsIntBe(4),this.faceWrinkles=this._io.readBitsIntBe(4),this._io.alignToByte(),this.hairType=this._io.readU1(),this.unknown5=this._io.readBitsIntBe(4),this.hairFlip=this._io.readBitsIntBe(1)!=0,this.hairColor=this._io.readBitsIntBe(3),this._io.alignToByte(),this.eye=this._io.readU4le(),this.eyebrow=this._io.readU4le(),this.nose=this._io.readU2le(),this.mouth=this._io.readU2le(),this.mouth2=this._io.readU2le(),this.beard=this._io.readU2le(),this.glasses=this._io.readU2le(),this.mole=this._io.readU2le(),this.creatorName=A.bytesToStr(this._io.readBytes(20),"utf-16le"),this.padding2=this._io.readU2le(),this.checksum=this._io.readU2le()},Object.defineProperty(J.prototype,"glassesColor",{get:function(){if(this._m_glassesColor!==void 0)return this._m_glassesColor;return this._m_glassesColor=this.glasses>>>4&7,this._m_glassesColor}}),Object.defineProperty(J.prototype,"eyebrowHorizontal",{get:function(){if(this._m_eyebrowHorizontal!==void 0)return this._m_eyebrowHorizontal;return this._m_eyebrowHorizontal=this.eyebrow>>>21&15,this._m_eyebrowHorizontal}}),Object.defineProperty(J.prototype,"eyeVertical",{get:function(){if(this._m_eyeVertical!==void 0)return this._m_eyeVertical;return this._m_eyeVertical=this.eye>>>25&31,this._m_eyeVertical}}),Object.defineProperty(J.prototype,"facialHairBeard",{get:function(){if(this._m_facialHairBeard!==void 0)return this._m_facialHairBeard;return this._m_facialHairBeard=this.beard&7,this._m_facialHairBeard}}),Object.defineProperty(J.prototype,"mouthSize",{get:function(){if(this._m_mouthSize!==void 0)return this._m_mouthSize;return this._m_mouthSize=this.mouth>>>9&15,this._m_mouthSize}}),Object.defineProperty(J.prototype,"eyebrowStretch",{get:function(){if(this._m_eyebrowStretch!==void 0)return this._m_eyebrowStretch;return this._m_eyebrowStretch=this.eyebrow>>>12&7,this._m_eyebrowStretch}}),Object.defineProperty(J.prototype,"noseVertical",{get:function(){if(this._m_noseVertical!==void 0)return this._m_noseVertical;return this._m_noseVertical=this.nose>>>9&31,this._m_noseVertical}}),Object.defineProperty(J.prototype,"eyeColor",{get:function(){if(this._m_eyeColor!==void 0)return this._m_eyeColor;return this._m_eyeColor=this.eye>>>6&7,this._m_eyeColor}}),Object.defineProperty(J.prototype,"birthMonth",{get:function(){if(this._m_birthMonth!==void 0)return this._m_birthMonth;return this._m_birthMonth=this.data1>>>1&15,this._m_birthMonth}}),Object.defineProperty(J.prototype,"mouthColor",{get:function(){if(this._m_mouthColor!==void 0)return this._m_mouthColor;return this._m_mouthColor=this.mouth>>>6&7,this._m_mouthColor}}),Object.defineProperty(J.prototype,"moleHorizontal",{get:function(){if(this._m_moleHorizontal!==void 0)return this._m_moleHorizontal;return this._m_moleHorizontal=this.mole>>>5&31,this._m_moleHorizontal}}),Object.defineProperty(J.prototype,"facialHairMustache",{get:function(){if(this._m_facialHairMustache!==void 0)return this._m_facialHairMustache;return this._m_facialHairMustache=this.mouth2>>>5&7,this._m_facialHairMustache}}),Object.defineProperty(J.prototype,"eyebrowRotation",{get:function(){if(this._m_eyebrowRotation!==void 0)return this._m_eyebrowRotation;return this._m_eyebrowRotation=this.eyebrow>>>16&15,this._m_eyebrowRotation}}),Object.defineProperty(J.prototype,"moleVertical",{get:function(){if(this._m_moleVertical!==void 0)return this._m_moleVertical;return this._m_moleVertical=this.mole>>>10&31,this._m_moleVertical}}),Object.defineProperty(J.prototype,"glassesType",{get:function(){if(this._m_glassesType!==void 0)return this._m_glassesType;return this._m_glassesType=this.glasses&15,this._m_glassesType}}),Object.defineProperty(J.prototype,"eyebrowSize",{get:function(){if(this._m_eyebrowSize!==void 0)return this._m_eyebrowSize;return this._m_eyebrowSize=this.eyebrow>>>8&15,this._m_eyebrowSize}}),Object.defineProperty(J.prototype,"moleSize",{get:function(){if(this._m_moleSize!==void 0)return this._m_moleSize;return this._m_moleSize=this.mole>>>1&15,this._m_moleSize}}),Object.defineProperty(J.prototype,"noseSize",{get:function(){if(this._m_noseSize!==void 0)return this._m_noseSize;return this._m_noseSize=this.nose>>>5&15,this._m_noseSize}}),Object.defineProperty(J.prototype,"facialHairVertical",{get:function(){if(this._m_facialHairVertical!==void 0)return this._m_facialHairVertical;return this._m_facialHairVertical=this.beard>>>10&31,this._m_facialHairVertical}}),Object.defineProperty(J.prototype,"eyeStretch",{get:function(){if(this._m_eyeStretch!==void 0)return this._m_eyeStretch;return this._m_eyeStretch=this.eye>>>13&7,this._m_eyeStretch}}),Object.defineProperty(J.prototype,"eyeSize",{get:function(){if(this._m_eyeSize!==void 0)return this._m_eyeSize;return this._m_eyeSize=this.eye>>>9&7,this._m_eyeSize}}),Object.defineProperty(J.prototype,"eyeType",{get:function(){if(this._m_eyeType!==void 0)return this._m_eyeType;return this._m_eyeType=this.eye&63,this._m_eyeType}}),Object.defineProperty(J.prototype,"eyeHorizontal",{get:function(){if(this._m_eyeHorizontal!==void 0)return this._m_eyeHorizontal;return this._m_eyeHorizontal=this.eye>>>21&15,this._m_eyeHorizontal}}),Object.defineProperty(J.prototype,"eyebrowType",{get:function(){if(this._m_eyebrowType!==void 0)return this._m_eyebrowType;return this._m_eyebrowType=this.eyebrow&31,this._m_eyebrowType}}),Object.defineProperty(J.prototype,"mouthVertical",{get:function(){if(this._m_mouthVertical!==void 0)return this._m_mouthVertical;return this._m_mouthVertical=this.mouth2&31,this._m_mouthVertical}}),Object.defineProperty(J.prototype,"eyebrowColor",{get:function(){if(this._m_eyebrowColor!==void 0)return this._m_eyebrowColor;return this._m_eyebrowColor=this.eyebrow>>>5&7,this._m_eyebrowColor}}),Object.defineProperty(J.prototype,"noseType",{get:function(){if(this._m_noseType!==void 0)return this._m_noseType;return this._m_noseType=this.nose&31,this._m_noseType}}),Object.defineProperty(J.prototype,"facialHairColor",{get:function(){if(this._m_facialHairColor!==void 0)return this._m_facialHairColor;return this._m_facialHairColor=this.beard>>>3&7,this._m_facialHairColor}}),Object.defineProperty(J.prototype,"eyebrowVertical",{get:function(){if(this._m_eyebrowVertical!==void 0)return this._m_eyebrowVertical;return this._m_eyebrowVertical=this.eyebrow>>>25&31,this._m_eyebrowVertical}}),Object.defineProperty(J.prototype,"glassesSize",{get:function(){if(this._m_glassesSize!==void 0)return this._m_glassesSize;return this._m_glassesSize=this.glasses>>>7&15,this._m_glassesSize}}),Object.defineProperty(J.prototype,"eyeRotation",{get:function(){if(this._m_eyeRotation!==void 0)return this._m_eyeRotation;return this._m_eyeRotation=this.eye>>>16&31,this._m_eyeRotation}}),Object.defineProperty(J.prototype,"gender",{get:function(){if(this._m_gender!==void 0)return this._m_gender;return this._m_gender=this.data1&1,this._m_gender}}),Object.defineProperty(J.prototype,"birthDay",{get:function(){if(this._m_birthDay!==void 0)return this._m_birthDay;return this._m_birthDay=this.data1>>>5&31,this._m_birthDay}}),Object.defineProperty(J.prototype,"mouthStretch",{get:function(){if(this._m_mouthStretch!==void 0)return this._m_mouthStretch;return this._m_mouthStretch=this.mouth>>>13&7,this._m_mouthStretch}}),Object.defineProperty(J.prototype,"moleEnable",{get:function(){if(this._m_moleEnable!==void 0)return this._m_moleEnable;return this._m_moleEnable=this.mole>>>0&1,this._m_moleEnable}}),Object.defineProperty(J.prototype,"favorite",{get:function(){if(this._m_favorite!==void 0)return this._m_favorite;return this._m_favorite=this.data1>>>14&1,this._m_favorite}}),Object.defineProperty(J.prototype,"glassesVertical",{get:function(){if(this._m_glassesVertical!==void 0)return this._m_glassesVertical;return this._m_glassesVertical=this.glasses>>>11&31,this._m_glassesVertical}}),Object.defineProperty(J.prototype,"favoriteColor",{get:function(){if(this._m_favoriteColor!==void 0)return this._m_favoriteColor;return this._m_favoriteColor=this.data1>>>10&15,this._m_favoriteColor}}),Object.defineProperty(J.prototype,"mouthType",{get:function(){if(this._m_mouthType!==void 0)return this._m_mouthType;return this._m_mouthType=this.mouth&63,this._m_mouthType}}),Object.defineProperty(J.prototype,"facialHairSize",{get:function(){if(this._m_facialHairSize!==void 0)return this._m_facialHairSize;return this._m_facialHairSize=this.beard>>>6&15,this._m_facialHairSize}}),J}();return Q});(function(A,Q){A.TomodachiLifeQrCode=Q(A.KaitaiStream)})(typeof a9!=="undefined"?a9:null,function(A){var Q=function(){function J(K,C,U){this._io=K,this._parent=C,this._root=U||this,this._read()}return J.prototype._read=function(){this.firstName=A.bytesToStr(this._io.readBytes(32),"UTF-16LE"),this.lastName=A.bytesToStr(this._io.readBytes(32),"UTF-16LE"),this.unknown=[];for(var K=0;K<3;K++)this.unknown.push(this._io.readU1());this.hairDyeEnable=this._io.readBitsIntBe(1)!=0,this.unknownb1=this._io.readBitsIntBe(1)!=0,this.hairDye=this._io.readBitsIntBe(5),this.unknownb2=this._io.readBitsIntBe(1)!=0,this._io.alignToByte(),this.unknown2=[];for(var K=0;K<12;K++)this.unknown2.push(this._io.readU1());this.catchphrase=A.bytesToStr(this._io.readBytes(32),"UTF-16LE"),this.unknown3=[];for(var K=0;K<58;K++)this.unknown3.push(this._io.readU1());this.voicePitch=this._io.readU1(),this.voiceSpeed=this._io.readU1(),this.voiceQuality=this._io.readU1(),this.voiceTone=this._io.readU1(),this.voiceAccent=this._io.readU1(),this.voiceInotation=this._io.readU1(),this.characterMovement=this._io.readU1(),this.characterSpeech=this._io.readU1(),this.characterExpressiveness=this._io.readU1(),this.characterAttitude=this._io.readU1(),this.characterOverall=this._io.readU1(),this.unknown4=[];for(var K=0;K<35;K++)this.unknown4.push(this._io.readU1());this.islandName=A.bytesToStr(this._io.readBytes(20),"UTF-16LE")},J}();return Q});(function(A,Q){A.Gen3Studio=Q(A.KaitaiStream)})(typeof a9!=="undefined"?a9:null,function(A){var Q=function(){function J(K,C,U){this._io=K,this._parent=C,this._root=U||this,this._read()}return J.prototype._read=function(){this.facialHairColor=this._io.readU1(),this.beardGoatee=this._io.readU1(),this.bodyWeight=this._io.readU1(),this.eyeStretch=this._io.readU1(),this.eyeColor=this._io.readU1(),this.eyeRotation=this._io.readU1(),this.eyeSize=this._io.readU1(),this.eyeType=this._io.readU1(),this.eyeHorizontal=this._io.readU1(),this.eyeVertical=this._io.readU1(),this.eyebrowStretch=this._io.readU1(),this.eyebrowColor=this._io.readU1(),this.eyebrowRotation=this._io.readU1(),this.eyebrowSize=this._io.readU1(),this.eyebrowType=this._io.readU1(),this.eyebrowHorizontal=this._io.readU1(),this.eyebrowVertical=this._io.readU1(),this.faceColor=this._io.readU1(),this.faceMakeup=this._io.readU1(),this.faceType=this._io.readU1(),this.faceWrinkles=this._io.readU1(),this.favoriteColor=this._io.readU1(),this.gender=this._io.readU1(),this.glassesColor=this._io.readU1(),this.glassesSize=this._io.readU1(),this.glassesType=this._io.readU1(),this.glassesVertical=this._io.readU1(),this.hairColor=this._io.readU1(),this.hairFlip=this._io.readU1(),this.hairType=this._io.readU1(),this.bodyHeight=this._io.readU1(),this.moleSize=this._io.readU1(),this.moleEnable=this._io.readU1(),this.moleHorizontal=this._io.readU1(),this.moleVertical=this._io.readU1(),this.mouthStretch=this._io.readU1(),this.mouthColor=this._io.readU1(),this.mouthSize=this._io.readU1(),this.mouthType=this._io.readU1(),this.mouthVertical=this._io.readU1(),this.beardSize=this._io.readU1(),this.beardMustache=this._io.readU1(),this.beardVertical=this._io.readU1(),this.noseSize=this._io.readU1(),this.noseType=this._io.readU1(),this.noseVertical=this._io.readU1()},J}();return Q});(function(A,Q){A.Gen3Switch=Q(A.KaitaiStream)})(typeof a9!=="undefined"?a9:null,function(A){var Q=function(){function J(K,C,U){this._io=K,this._parent=C,this._root=U||this,this._read()}return J.prototype._read=function(){this.hairType=this._io.readU1(),this.moleEnable=this._io.readBitsIntBe(1)!=0,this.bodyHeight=this._io.readBitsIntBe(7),this.hairFlip=this._io.readBitsIntBe(1)!=0,this.bodyWeight=this._io.readBitsIntBe(7),this.isSpecial=this._io.readBitsIntBe(1)!=0,this.hairColor=this._io.readBitsIntBe(7),this.gender=this._io.readBitsIntBe(1)!=0,this.eyeColor=this._io.readBitsIntBe(7),this._io.alignToByte(),this.eyebrowColor=this._io.readU1(),this.mouthColor=this._io.readU1(),this.facialHairColor=this._io.readU1(),this.glassesColor=this._io.readU1(),this.regionLock=this._io.readBitsIntBe(2),this.eyeType=this._io.readBitsIntBe(6),this.fontRegion=this._io.readBitsIntBe(2),this.mouthType=this._io.readBitsIntBe(6),this.glassesSize=this._io.readBitsIntBe(3),this.eyeVertical=this._io.readBitsIntBe(5),this.facialHairMustache=this._io.readBitsIntBe(3),this.eyebrowType=this._io.readBitsIntBe(5),this.facialHairBeard=this._io.readBitsIntBe(3),this.noseType=this._io.readBitsIntBe(5),this.mouthStretch=this._io.readBitsIntBe(3),this.noseVertical=this._io.readBitsIntBe(5),this.eyebrowStretch=this._io.readBitsIntBe(3),this.mouthVertical=this._io.readBitsIntBe(5),this.eyeRotation=this._io.readBitsIntBe(3),this.facialHairVertical=this._io.readBitsIntBe(5),this.eyeStretch=this._io.readBitsIntBe(3),this.glassesVertical=this._io.readBitsIntBe(5),this.eyeSize=this._io.readBitsIntBe(3),this.moleHorizontal=this._io.readBitsIntBe(5),this._io.alignToByte(),this.moleVertical=this._io.readU1(),this.glassesType=this._io.readU1(),this.faceType=this._io.readBitsIntBe(4),this.favoriteColor=this._io.readBitsIntBe(4),this.faceWrinkles=this._io.readBitsIntBe(4),this.faceColor=this._io.readBitsIntBe(4),this.eyeHorizontal=this._io.readBitsIntBe(4),this.faceMakeup=this._io.readBitsIntBe(4),this.eyebrowRotation=this._io.readBitsIntBe(4),this.eyebrowSize=this._io.readBitsIntBe(4),this.eyebrowVertical=this._io.readBitsIntBe(4),this.eyebrowHorizontal=this._io.readBitsIntBe(4),this.mouthSize=this._io.readBitsIntBe(4),this.noseSize=this._io.readBitsIntBe(4),this.moleSize=this._io.readBitsIntBe(4),this.facialHairSize=this._io.readBitsIntBe(4),this._io.alignToByte(),this.miiName=A.bytesToStr(this._io.readBytes(20),"utf-16le"),this.unknown=[];for(var K=0;K<16;K++)this.unknown.push(this._io.readU1());this.miiId=[];for(var K=0;K<4;K++)this.miiId.push(this._io.readU1())},J}();return Q});(function(A,Q){A.Gen3Switchgame=Q(A.KaitaiStream)})(typeof a9!=="undefined"?a9:null,function(A){var Q=function(){function J(K,C,U){this._io=K,this._parent=C,this._root=U||this,this._read()}return J.prototype._read=function(){this.unknownData=[];for(var K=0;K<16;K++)this.unknownData.push(this._io.readU1());this.miiName=A.bytesToStr(this._io.readBytes(20),"utf-16le"),this.unknownBuffer=[];for(var K=0;K<3;K++)this.unknownBuffer.push(this._io.readU1());this.favoriteColor=this._io.readU1(),this.gender=this._io.readU1(),this.bodyHeight=this._io.readU1(),this.bodyWeight=this._io.readU1(),this.unknownBuffer2=[];for(var K=0;K<2;K++)this.unknownBuffer2.push(this._io.readU1());this.faceType=this._io.readU1(),this.faceColor=this._io.readU1(),this.faceWrinkles=this._io.readU1(),this.faceMakeup=this._io.readU1(),this.hairType=this._io.readU1(),this.hairColor=this._io.readU1(),this.hairFlip=this._io.readU1(),this.eyeType=this._io.readU1(),this.eyeColor=this._io.readU1(),this.eyeSize=this._io.readU1(),this.eyeStretch=this._io.readU1(),this.eyeRotation=this._io.readU1(),this.eyeHorizontal=this._io.readU1(),this.eyeVertical=this._io.readU1(),this.eyebrowType=this._io.readU1(),this.eyebrowColor=this._io.readU1(),this.eyebrowSize=this._io.readU1(),this.eyebrowStretch=this._io.readU1(),this.eyebrowRotation=this._io.readU1(),this.eyebrowHorizontal=this._io.readU1(),this.eyebrowVertical=this._io.readU1(),this.noseType=this._io.readU1(),this.noseSize=this._io.readU1(),this.noseVertical=this._io.readU1(),this.mouthType=this._io.readU1(),this.mouthColor=this._io.readU1(),this.mouthSize=this._io.readU1(),this.mouthStretch=this._io.readU1(),this.mouthVertical=this._io.readU1(),this.facialHairColor=this._io.readU1(),this.facialHairBeard=this._io.readU1(),this.facialHairMustache=this._io.readU1(),this.facialHairSize=this._io.readU1(),this.facialHairVertical=this._io.readU1(),this.glassesType=this._io.readU1(),this.glassesColor=this._io.readU1(),this.glassesSize=this._io.readU1(),this.glassesVertical=this._io.readU1(),this.moleEnable=this._io.readU1(),this.moleSize=this._io.readU1(),this.moleHorizontal=this._io.readU1(),this.moleVertical=this._io.readU1(),this.unknownBuffer3=[];for(var K=0;K<1;K++)this.unknownBuffer3.push(this._io.readU1())},J}();return Q});async function Qn(){let A=m8();if(t8(),_G(!0),sR(),navigator.userAgent.includes("Firefox")&&sessionStorage.getItem("seen-firefox-notice")===null)sessionStorage.setItem("seen-firefox-notice","yes"),y0.modal("Notice","You're using Mii Creator under Firefox. The Firefox browser may have slowdowns.","body",...x3);let Q="main";document.addEventListener("editor-launch",()=>{Q="edit",setTimeout(()=>{J()},100)}),document.addEventListener("editor-shutdown",()=>{Q="main",setTimeout(()=>{J()},100)});function J(){if(A.editGainNode===void 0)return;if(Q==="main")A.mainGainNode.gain.linearRampToValueAtTime(-0.6,m8().audioContext.currentTime+0.5),A.editGainNode.gain.linearRampToValueAtTime(-1,m8().audioContext.currentTime+0.5);if(Q==="edit")A.mainGainNode.gain.linearRampToValueAtTime(-1,m8().audioContext.currentTime+0.5),A.editGainNode.gain.linearRampToValueAtTime(-0.6,m8().audioContext.currentTime+0.5)}if(A.initMusic(),location.search!==""){let K=new URLSearchParams(location.search);if(K.has("data"))new V8(0,async(C,U)=>{if(window.parent!==window.self){let Y=new mA(QA.from(C,"base64")),Z=null,X=null,E=null;if(U===!0){if(K.has("renderTypes")){let H=K.get("renderTypes").split(",");if(H.includes("headshot"))Z=(await j5(Y,0,!0,!1)).src;if(H.includes("headOnly"))X=(await j5(Y,1,!0,!1)).src;if(H.includes("fullBody"))E=(await j5(Y,2,!0,!1)).src}}A.mainGainNode.gain.linearRampToValueAtTime(-1,A.audioContext.currentTime+0.5),window.parent.postMessage({type:"miic-data-finalize",properSave:U,data:C,name:Y.miiName,creator:Y.creatorName,headshot:Z,headOnly:X,fullBody:E},K.get("origin"))}else $8()},K.get("data"));else if(K.has("select")){let C=await L7();console.log("selection:",C);let U=null,Y=null,Z=null;if(K.has("renderTypes")){let X=K.get("renderTypes").split(",");if(X.includes("headshot"))U=(await j5(C,0,!0,!1)).src;if(X.includes("headOnly"))Y=(await j5(C,1,!0,!1)).src;if(X.includes("fullBody"))Z=(await j5(C,2,!0,!1)).src}window.parent.postMessage({type:"miic-select",data:C.encode(),name:C.miiName,creator:C.creatorName,headshot:U,headOnly:Y,fullBody:Z},location.origin)}else if(K.has("custom-render-preview")){let C=new mA(QA.from(K.get("custom-render-preview"),"base64"));RW(C)}else if(K.has("settings"))TG();else $8()}else $8();t8().setVolume(0.28),A.setVolume(0.28),window.addEventListener("blur",()=>{if(A.mainGainNode){if(A.mainGainNode.gain.linearRampToValueAtTime(-1,m8().audioContext.currentTime+0.5),A.editGainNode)A.editGainNode.gain.linearRampToValueAtTime(-1,m8().audioContext.currentTime+0.5)}else m8().setVolume(0);t8().setVolume(0)}),window.addEventListener("focus",()=>{if(A.mainGainNode){if(Q==="main")A.mainGainNode.gain.setValueAtTime(-1,A.audioContext.currentTime),A.mainGainNode.gain.linearRampToValueAtTime(-0.6,m8().audioContext.currentTime+0.5);else if(Q==="edit")if(A.editGainNode)A.editGainNode.gain.setValueAtTime(-1,A.audioContext.currentTime),A.editGainNode.gain.linearRampToValueAtTime(-0.6,m8().audioContext.currentTime+0.5);else A.mainGainNode.gain.setValueAtTime(-1,A.audioContext.currentTime),A.mainGainNode.gain.linearRampToValueAtTime(-0.6,m8().audioContext.currentTime+0.5)}else m8().setVolume(0);t8().setVolume(t8().previousVolume)}),window.MusicManager=m8(),window.soundManager=t8(),document.addEventListener("keydown",(K)=>{if(document.activeElement===document.body){if(K.ctrlKey||K.altKey||K.metaKey)return;if(K.code==="KeyS")y0.modal("sound test","choose a sound","body",...Object.keys(t8().soundBufs).map((C)=>({text:C,callback(){t8().playSound(C),window.lastPlayedSound=C}}))).qs(".modal-content").style({"max-width":"unset","max-height":"unset"});if(K.code==="KeyD")window.localforage=An.default,window.Mii=mA;if(K.code==="KeyV"){let C=Number(prompt("Enter volume level from 0-1 (default is 0.35)"));if(C<0)return;if(C>1)return;t8().setVolume(C),A.setVolume(C)}}})}var Ko=j2(Jn(),1);var tA=typeof __SENTRY_DEBUG__==="undefined"||__SENTRY_DEBUG__;var I3="8.53.0";var OA=globalThis;function v4(A,Q,J){let K=J||OA,C=K.__SENTRY__=K.__SENTRY__||{},U=C[I3]=C[I3]||{};return U[A]||(U[A]=Q())}var r9=typeof __SENTRY_DEBUG__==="undefined"||__SENTRY_DEBUG__;var IH1="Sentry Logger ",cB=["debug","info","warn","error","log","assert","trace"],HY={};function i6(A){if(!("console"in OA))return A();let Q=OA.console,J={},K=Object.keys(HY);K.forEach((C)=>{let U=HY[C];J[C]=Q[C],Q[C]=U});try{return A()}finally{K.forEach((C)=>{Q[C]=J[C]})}}function qH1(){let A=!1,Q={enable:()=>{A=!0},disable:()=>{A=!1},isEnabled:()=>A};if(r9)cB.forEach((J)=>{Q[J]=(...K)=>{if(A)i6(()=>{OA.console[J](`${IH1}[${J}]:`,...K)})}});else cB.forEach((J)=>{Q[J]=()=>{return}});return Q}var m0=v4("logger",qH1);var M7="?",Kn=/\(error: (.*)\)/,Cn=/captureMessage|captureException/;function tW(...A){let Q=A.sort((J,K)=>J[0]-K[0]).map((J)=>J[1]);return(J,K=0,C=0)=>{let U=[],Y=J.split(` -`);for(let Z=K;Z1024)continue;let E=Kn.test(X)?X.replace(Kn,"$1"):X;if(E.match(/\S*Error: /))continue;for(let H of Q){let $=H(E);if($){U.push($);break}}if(U.length>=50+C)break}return Yn(U.slice(C))}}function yV(A){if(Array.isArray(A))return tW(...A);return A}function Yn(A){if(!A.length)return[];let Q=Array.from(A);if(/sentryWrapped/.test(rW(Q).function||""))Q.pop();if(Q.reverse(),Cn.test(rW(Q).function||"")){if(Q.pop(),Cn.test(rW(Q).function||""))Q.pop()}return Q.slice(0,50).map((J)=>({...J,filename:J.filename||rW(Q).filename,function:J.function||"?"}))}function rW(A){return A[A.length-1]||{}}var xV="";function t9(A){try{if(!A||typeof A!=="function")return xV;return A.name||xV}catch(Q){return xV}}function eW(A){let Q=A.exception;if(Q){let J=[];try{return Q.values.forEach((K)=>{if(K.stacktrace.frames)J.push(...K.stacktrace.frames)}),J}catch(K){return}}return}var AI={},Un={};function V6(A,Q){AI[A]=AI[A]||[],AI[A].push(Q)}function M6(A,Q){if(!Un[A]){Un[A]=!0;try{Q()}catch(J){r9&&m0.error(`Error while instrumenting ${A}`,J)}}}function _8(A,Q){let J=A&&AI[A];if(!J)return;for(let K of J)try{K(Q)}catch(C){r9&&m0.error(`Error while triggering instrumentation handler. -Type: ${A} -Name: ${t9(K)} -Error:`,C)}}var hV=null;function gV(A){V6("error",A),M6("error",OH1)}function OH1(){hV=OA.onerror,OA.onerror=function(A,Q,J,K,C){if(_8("error",{column:K,error:C,line:J,msg:A,url:Q}),hV)return hV.apply(this,arguments);return!1},OA.onerror.__SENTRY_INSTRUMENTED__=!0}var bV=null;function fV(A){V6("unhandledrejection",A),M6("unhandledrejection",NH1)}function NH1(){bV=OA.onunhandledrejection,OA.onunhandledrejection=function(A){if(_8("unhandledrejection",A),bV)return bV.apply(this,arguments);return!0},OA.onunhandledrejection.__SENTRY_INSTRUMENTED__=!0}function PJ(){return dB(OA),OA}function dB(A){let Q=A.__SENTRY__=A.__SENTRY__||{};return Q.version=Q.version||I3,Q[I3]=Q[I3]||{}}var Zn=Object.prototype.toString;function _J(A){switch(Zn.call(A)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return q3(A,Error)}}function GY(A,Q){return Zn.call(A)===`[object ${Q}]`}function QI(A){return GY(A,"ErrorEvent")}function JI(A){return GY(A,"DOMError")}function pV(A){return GY(A,"DOMException")}function w6(A){return GY(A,"String")}function WY(A){return typeof A==="object"&&A!==null&&"__sentry_template_string__"in A&&"__sentry_template_values__"in A}function TJ(A){return A===null||WY(A)||typeof A!=="object"&&typeof A!=="function"}function x5(A){return GY(A,"Object")}function kJ(A){return typeof Event!=="undefined"&&q3(A,Event)}function uV(A){return typeof Element!=="undefined"&&q3(A,Element)}function mV(A){return GY(A,"RegExp")}function w7(A){return Boolean(A&&A.then&&typeof A.then==="function")}function cV(A){return x5(A)&&"nativeEvent"in A&&"preventDefault"in A&&"stopPropagation"in A}function q3(A,Q){try{return A instanceof Q}catch(J){return!1}}function lB(A){return!!(typeof A==="object"&&A!==null&&(A.__isVue||A._isVue))}var dV=OA,LH1=80;function nB(A,Q={}){if(!A)return"";try{let J=A,K=5,C=[],U=0,Y=0,Z=" > ",X=Z.length,E,H=Array.isArray(Q)?Q:Q.keyAttrs,$=!Array.isArray(Q)&&Q.maxStringLength||LH1;while(J&&U++1&&Y+C.length*X+E.length>=$)break;C.push(E),Y+=E.length,J=J.parentNode}return C.reverse().join(Z)}catch(J){return""}}function FH1(A,Q){let J=A,K=[];if(!J||!J.tagName)return"";if(dV.HTMLElement){if(J instanceof HTMLElement&&J.dataset){if(J.dataset.sentryComponent)return J.dataset.sentryComponent;if(J.dataset.sentryElement)return J.dataset.sentryElement}}K.push(J.tagName.toLowerCase());let C=Q&&Q.length?Q.filter((Y)=>J.getAttribute(Y)).map((Y)=>[Y,J.getAttribute(Y)]):null;if(C&&C.length)C.forEach((Y)=>{K.push(`[${Y[0]}="${Y[1]}"]`)});else{if(J.id)K.push(`#${J.id}`);let Y=J.className;if(Y&&w6(Y)){let Z=Y.split(/\s+/);for(let X of Z)K.push(`.${X}`)}}let U=["aria-label","type","name","title","alt"];for(let Y of U){let Z=J.getAttribute(Y);if(Z)K.push(`[${Y}="${Z}"]`)}return K.join("")}function lV(){try{return dV.document.location.href}catch(A){return""}}function nV(A){if(!dV.HTMLElement)return null;let Q=A,J=5;for(let K=0;KBn(A,K,J))}function T8(A,Q,J){if(!(Q in A))return;let K=A[Q],C=J(K);if(typeof C==="function")CI(C,K);try{A[Q]=C}catch(U){r9&&m0.log(`Failed to replace method "${Q}" in object`,A)}}function P6(A,Q,J){try{Object.defineProperty(A,Q,{value:J,writable:!0,configurable:!0})}catch(K){r9&&m0.log(`Failed to add non-enumerable property "${Q}" to object`,A)}}function CI(A,Q){try{let J=Q.prototype||{};A.prototype=Q.prototype=J,P6(A,"__sentry_original__",Q)}catch(J){}}function SJ(A){return A.__sentry_original__}function YI(A){if(_J(A))return{message:A.message,name:A.name,stack:A.stack,...En(A)};else if(kJ(A)){let Q={type:A.type,target:Xn(A.target),currentTarget:Xn(A.currentTarget),...En(A)};if(typeof CustomEvent!=="undefined"&&q3(A,CustomEvent))Q.detail=A.detail;return Q}else return A}function Xn(A){try{return uV(A)?nB(A):Object.prototype.toString.call(A)}catch(Q){return""}}function En(A){if(typeof A==="object"&&A!==null){let Q={};for(let J in A)if(Object.prototype.hasOwnProperty.call(A,J))Q[J]=A[J];return Q}else return{}}function oV(A,Q=40){let J=Object.keys(YI(A));J.sort();let K=J[0];if(!K)return"[object has no keys]";if(K.length>=Q)return O3(K,Q);for(let C=J.length;C>0;C--){let U=J.slice(0,C).join(", ");if(U.length>Q)continue;if(C===J.length)return U;return O3(U,Q)}return""}function I8(A){return sV(A,/*@__PURE__*/new Map)}function sV(A,Q){if(RH1(A)){let J=Q.get(A);if(J!==void 0)return J;let K={};Q.set(A,K);for(let C of Object.getOwnPropertyNames(A))if(typeof A[C]!=="undefined")K[C]=sV(A[C],Q);return K}if(Array.isArray(A)){let J=Q.get(A);if(J!==void 0)return J;let K=[];return Q.set(A,K),A.forEach((C)=>{K.push(sV(C,Q))}),K}return A}function RH1(A){if(!x5(A))return!1;try{let Q=Object.getPrototypeOf(A).constructor.name;return!Q||Q==="Object"}catch(Q){return!0}}var $n=1000;function N3(){return Date.now()/$n}function zH1(){let{performance:A}=OA;if(!A||!A.now)return N3;let Q=Date.now()-A.now(),J=A.timeOrigin==null?Q:A.timeOrigin;return()=>{return(J+A.now())/$n}}var a6=zH1(),sB,DH1=(()=>{let{performance:A}=OA;if(!A||!A.now){sB="none";return}let Q=3600000,J=A.now(),K=Date.now(),C=A.timeOrigin?Math.abs(A.timeOrigin+J-K):Q,U=CMath.random()*16;try{if(Q&&Q.randomUUID)return Q.randomUUID().replace(/-/g,"");if(Q&&Q.getRandomValues)J=()=>{let K=new Uint8Array(1);return Q.getRandomValues(K),K[0]}}catch(K){}return([1e7]+1000+4000+8000+100000000000).replace(/[018]/g,(K)=>(K^(J()&15)>>K/4).toString(16))}function Hn(A){return A.exception&&A.exception.values?A.exception.values[0]:void 0}function y5(A){let{message:Q,event_id:J}=A;if(Q)return Q;let K=Hn(A);if(K){if(K.type&&K.value)return`${K.type}: ${K.value}`;return K.type||K.value||J||""}return J||""}function qY(A,Q,J){let K=A.exception=A.exception||{},C=K.values=K.values||[],U=C[0]=C[0]||{};if(!U.value)U.value=Q||"";if(!U.type)U.type=J||"Error"}function L3(A,Q){let J=Hn(A);if(!J)return;let K={type:"generic",handled:!0},C=J.mechanism;if(J.mechanism={...K,...C,...Q},Q&&"data"in Q){let U={...C&&C.data,...Q.data};J.mechanism.data=U}}function UI(A){if(VH1(A))return!0;try{P6(A,"__sentry_captured__",!0)}catch(Q){}return!1}function VH1(A){try{return A.__sentry_captured__}catch(Q){}}var P7;(function(A){A[A.PENDING=0]="PENDING";let J=1;A[A.RESOLVED=J]="RESOLVED";let K=2;A[A.REJECTED=K]="REJECTED"})(P7||(P7={}));function e9(A){return new W6((Q)=>{Q(A)})}function x4(A){return new W6((Q,J)=>{J(A)})}class W6{constructor(A){W6.prototype.__init.call(this),W6.prototype.__init2.call(this),W6.prototype.__init3.call(this),W6.prototype.__init4.call(this),this._state=P7.PENDING,this._handlers=[];try{A(this._resolve,this._reject)}catch(Q){this._reject(Q)}}then(A,Q){return new W6((J,K)=>{this._handlers.push([!1,(C)=>{if(!A)J(C);else try{J(A(C))}catch(U){K(U)}},(C)=>{if(!Q)K(C);else try{J(Q(C))}catch(U){K(U)}}]),this._executeHandlers()})}catch(A){return this.then((Q)=>Q,A)}finally(A){return new W6((Q,J)=>{let K,C;return this.then((U)=>{if(C=!1,K=U,A)A()},(U)=>{if(C=!0,K=U,A)A()}).then(()=>{if(C){J(K);return}Q(K)})})}__init(){this._resolve=(A)=>{this._setResult(P7.RESOLVED,A)}}__init2(){this._reject=(A)=>{this._setResult(P7.REJECTED,A)}}__init3(){this._setResult=(A,Q)=>{if(this._state!==P7.PENDING)return;if(w7(Q)){Q.then(this._resolve,this._reject);return}this._state=A,this._value=Q,this._executeHandlers()}}__init4(){this._executeHandlers=()=>{if(this._state===P7.PENDING)return;let A=this._handlers.slice();this._handlers=[],A.forEach((Q)=>{if(Q[0])return;if(this._state===P7.RESOLVED)Q[1](this._value);if(this._state===P7.REJECTED)Q[2](this._value);Q[0]=!0})}}}function Gn(A){let Q=a6(),J={sid:k8(),init:!0,timestamp:Q,started:Q,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>MH1(J)};if(A)_7(J,A);return J}function _7(A,Q={}){if(Q.user){if(!A.ipAddress&&Q.user.ip_address)A.ipAddress=Q.user.ip_address;if(!A.did&&!Q.did)A.did=Q.user.id||Q.user.email||Q.user.username}if(A.timestamp=Q.timestamp||a6(),Q.abnormal_mechanism)A.abnormal_mechanism=Q.abnormal_mechanism;if(Q.ignoreDuration)A.ignoreDuration=Q.ignoreDuration;if(Q.sid)A.sid=Q.sid.length===32?Q.sid:k8();if(Q.init!==void 0)A.init=Q.init;if(!A.did&&Q.did)A.did=`${Q.did}`;if(typeof Q.started==="number")A.started=Q.started;if(A.ignoreDuration)A.duration=void 0;else if(typeof Q.duration==="number")A.duration=Q.duration;else{let J=A.timestamp-A.started;A.duration=J>=0?J:0}if(Q.release)A.release=Q.release;if(Q.environment)A.environment=Q.environment;if(!A.ipAddress&&Q.ipAddress)A.ipAddress=Q.ipAddress;if(!A.userAgent&&Q.userAgent)A.userAgent=Q.userAgent;if(typeof Q.errors==="number")A.errors=Q.errors;if(Q.status)A.status=Q.status}function Wn(A,Q){let J={};if(Q)J={status:Q};else if(A.status==="ok")J={status:"exited"};_7(A,J)}function MH1(A){return I8({sid:`${A.sid}`,init:A.init,started:new Date(A.started*1000).toISOString(),timestamp:new Date(A.timestamp*1000).toISOString(),status:A.status,errors:A.errors,did:typeof A.did==="number"||typeof A.did==="string"?`${A.did}`:void 0,duration:A.duration,abnormal_mechanism:A.abnormal_mechanism,attrs:{release:A.release,environment:A.environment,ip_address:A.ipAddress,user_agent:A.userAgent}})}function iV(){return k8()}function oB(){return k8().substring(16)}function OY(A,Q,J=2){if(!Q||typeof Q!=="object"||J<=0)return Q;if(A&&Q&&Object.keys(Q).length===0)return A;let K={...A};for(let C in Q)if(Object.prototype.hasOwnProperty.call(Q,C))K[C]=OY(K[C],Q[C],J-1);return K}var aV="_sentrySpan";function rV(A,Q){if(Q)P6(A,aV,Q);else delete A[aV]}function tV(A){return A[aV]}var wH1=100;class eV{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:iV(),spanId:oB()}}clone(){let A=new eV;if(A._breadcrumbs=[...this._breadcrumbs],A._tags={...this._tags},A._extra={...this._extra},A._contexts={...this._contexts},this._contexts.flags)A._contexts.flags={values:[...this._contexts.flags.values]};return A._user=this._user,A._level=this._level,A._session=this._session,A._transactionName=this._transactionName,A._fingerprint=this._fingerprint,A._eventProcessors=[...this._eventProcessors],A._requestSession=this._requestSession,A._attachments=[...this._attachments],A._sdkProcessingMetadata={...this._sdkProcessingMetadata},A._propagationContext={...this._propagationContext},A._client=this._client,A._lastEventId=this._lastEventId,rV(A,tV(this)),A}setClient(A){this._client=A}setLastEventId(A){this._lastEventId=A}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(A){this._scopeListeners.push(A)}addEventProcessor(A){return this._eventProcessors.push(A),this}setUser(A){if(this._user=A||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session)_7(this._session,{user:A});return this._notifyScopeListeners(),this}getUser(){return this._user}getRequestSession(){return this._requestSession}setRequestSession(A){return this._requestSession=A,this}setTags(A){return this._tags={...this._tags,...A},this._notifyScopeListeners(),this}setTag(A,Q){return this._tags={...this._tags,[A]:Q},this._notifyScopeListeners(),this}setExtras(A){return this._extra={...this._extra,...A},this._notifyScopeListeners(),this}setExtra(A,Q){return this._extra={...this._extra,[A]:Q},this._notifyScopeListeners(),this}setFingerprint(A){return this._fingerprint=A,this._notifyScopeListeners(),this}setLevel(A){return this._level=A,this._notifyScopeListeners(),this}setTransactionName(A){return this._transactionName=A,this._notifyScopeListeners(),this}setContext(A,Q){if(Q===null)delete this._contexts[A];else this._contexts[A]=Q;return this._notifyScopeListeners(),this}setSession(A){if(!A)delete this._session;else this._session=A;return this._notifyScopeListeners(),this}getSession(){return this._session}update(A){if(!A)return this;let Q=typeof A==="function"?A(this):A,[J,K]=Q instanceof A5?[Q.getScopeData(),Q.getRequestSession()]:x5(Q)?[A,A.requestSession]:[],{tags:C,extra:U,user:Y,contexts:Z,level:X,fingerprint:E=[],propagationContext:H}=J||{};if(this._tags={...this._tags,...C},this._extra={...this._extra,...U},this._contexts={...this._contexts,...Z},Y&&Object.keys(Y).length)this._user=Y;if(X)this._level=X;if(E.length)this._fingerprint=E;if(H)this._propagationContext=H;if(K)this._requestSession=K;return this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._session=void 0,rV(this,void 0),this._attachments=[],this.setPropagationContext({traceId:iV()}),this._notifyScopeListeners(),this}addBreadcrumb(A,Q){let J=typeof Q==="number"?Q:wH1;if(J<=0)return this;let K={timestamp:N3(),...A};if(this._breadcrumbs.push(K),this._breadcrumbs.length>J){if(this._breadcrumbs=this._breadcrumbs.slice(-J),this._client)this._client.recordDroppedEvent("buffer_overflow","log_item")}return this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(A){return this._attachments.push(A),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:tV(this)}}setSDKProcessingMetadata(A){return this._sdkProcessingMetadata=OY(this._sdkProcessingMetadata,A,2),this}setPropagationContext(A){return this._propagationContext={spanId:oB(),...A},this}getPropagationContext(){return this._propagationContext}captureException(A,Q){let J=Q&&Q.event_id?Q.event_id:k8();if(!this._client)return m0.warn("No client configured on scope - will not capture exception!"),J;let K=new Error("Sentry syntheticException");return this._client.captureException(A,{originalException:A,syntheticException:K,...Q,event_id:J},this),J}captureMessage(A,Q,J){let K=J&&J.event_id?J.event_id:k8();if(!this._client)return m0.warn("No client configured on scope - will not capture message!"),K;let C=new Error(A);return this._client.captureMessage(A,Q,{originalException:A,syntheticException:C,...J,event_id:K},this),K}captureEvent(A,Q){let J=Q&&Q.event_id?Q.event_id:k8();if(!this._client)return m0.warn("No client configured on scope - will not capture event!"),J;return this._client.captureEvent(A,{...Q,event_id:J},this),J}_notifyScopeListeners(){if(!this._notifyingListeners)this._notifyingListeners=!0,this._scopeListeners.forEach((A)=>{A(this)}),this._notifyingListeners=!1}}var A5=eV;function In(){return v4("defaultCurrentScope",()=>new A5)}function qn(){return v4("defaultIsolationScope",()=>new A5)}class Nn{constructor(A,Q){let J;if(!A)J=new A5;else J=A;let K;if(!Q)K=new A5;else K=Q;this._stack=[{scope:J}],this._isolationScope=K}withScope(A){let Q=this._pushScope(),J;try{J=A(Q)}catch(K){throw this._popScope(),K}if(w7(J))return J.then((K)=>{return this._popScope(),K},(K)=>{throw this._popScope(),K});return this._popScope(),J}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){let A=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:A}),A}_popScope(){if(this._stack.length<=1)return!1;return!!this._stack.pop()}}function NY(){let A=PJ(),Q=dB(A);return Q.stack=Q.stack||new Nn(In(),qn())}function PH1(A){return NY().withScope(A)}function _H1(A,Q){let J=NY();return J.withScope(()=>{return J.getStackTop().scope=A,Q(A)})}function On(A){return NY().withScope(()=>{return A(NY().getIsolationScope())})}function Ln(){return{withIsolationScope:On,withScope:PH1,withSetScope:_H1,withSetIsolationScope:(A,Q)=>{return On(Q)},getCurrentScope:()=>NY().getScope(),getIsolationScope:()=>NY().getIsolationScope()}}function ZI(A){let Q=dB(A);if(Q.acs)return Q.acs;return Ln()}function r6(){let A=PJ();return ZI(A).getCurrentScope()}function T7(){let A=PJ();return ZI(A).getIsolationScope()}function AM(){return v4("globalScope",()=>new A5)}function QM(...A){let Q=PJ(),J=ZI(Q);if(A.length===2){let[K,C]=A;if(!K)return J.withScope(C);return J.withSetScope(K,C)}return J.withScope(A[0])}function b2(){return r6().getClient()}function JM(A){let Q=A.getPropagationContext(),{traceId:J,spanId:K,parentSpanId:C}=Q;return I8({trace_id:J,span_id:K,parent_span_id:C})}var TH1="_sentryMetrics";function Fn(A){let Q=A[TH1];if(!Q)return;let J={};for(let[,[K,C]]of Q)(J[K]||(J[K]=[])).push(I8(C));return J}var KM="sentry.source",Rn="sentry.sample_rate",zn="sentry.op",Dn="sentry.origin";var Vn=0,Mn=1;var kH1="sentry-",SH1=/^sentry-/;function Pn(A){let Q=jH1(A);if(!Q)return;let J=Object.entries(Q).reduce((K,[C,U])=>{if(C.match(SH1)){let Y=C.slice(kH1.length);K[Y]=U}return K},{});if(Object.keys(J).length>0)return J;else return}function jH1(A){if(!A||!w6(A)&&!Array.isArray(A))return;if(Array.isArray(A))return A.reduce((Q,J)=>{let K=wn(J);return Object.entries(K).forEach(([C,U])=>{Q[C]=U}),Q},{});return wn(A)}function wn(A){return A.split(",").map((Q)=>Q.split("=").map((J)=>decodeURIComponent(J.trim()))).reduce((Q,[J,K])=>{if(J&&K)Q[J]=K;return Q},{})}var vH1=1,_n=!1;function Sn(A){let{spanId:Q,traceId:J,isRemote:K}=A.spanContext(),C=K?Q:iB(A).parent_span_id,U=K?oB():Q;return I8({parent_span_id:C,span_id:U,trace_id:J})}function Tn(A){if(typeof A==="number")return kn(A);if(Array.isArray(A))return A[0]+A[1]/1e9;if(A instanceof Date)return kn(A.getTime());return a6()}function kn(A){return A>9999999999?A/1000:A}function iB(A){if(yH1(A))return A.getSpanJSON();try{let{spanId:Q,traceId:J}=A.spanContext();if(xH1(A)){let{attributes:K,startTime:C,name:U,endTime:Y,parentSpanId:Z,status:X}=A;return I8({span_id:Q,trace_id:J,data:K,description:U,parent_span_id:Z,start_timestamp:Tn(C),timestamp:Tn(Y)||void 0,status:hH1(X),op:K[zn],origin:K[Dn],_metrics_summary:Fn(A)})}return{span_id:Q,trace_id:J}}catch(Q){return{}}}function xH1(A){let Q=A;return!!Q.attributes&&!!Q.startTime&&!!Q.name&&!!Q.endTime&&!!Q.status}function yH1(A){return typeof A.getSpanJSON==="function"}function jn(A){let{traceFlags:Q}=A.spanContext();return Q===vH1}function hH1(A){if(!A||A.code===Vn)return;if(A.code===Mn)return"ok";return A.message||"unknown_error"}var gH1="_sentryRootSpan";function BI(A){return A[gH1]||A}function vn(){if(!_n)i6(()=>{console.warn("[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly.")}),_n=!0}function xn(A){if(typeof __SENTRY_TRACING__==="boolean"&&!__SENTRY_TRACING__)return!1;let Q=b2(),J=A||Q&&Q.getOptions();return!!J&&(J.enableTracing||("tracesSampleRate"in J)||("tracesSampler"in J))}var LY="production";var bH1="_frozenDsc";function yn(A,Q){let J=Q.getOptions(),{publicKey:K}=Q.getDsn()||{},C=I8({environment:J.environment||LY,release:J.release,public_key:K,trace_id:A});return Q.emit("createDsc",C),C}function hn(A,Q){let J=Q.getPropagationContext();return J.dsc||yn(J.traceId,A)}function gn(A){let Q=b2();if(!Q)return{};let J=BI(A),K=J[bH1];if(K)return K;let C=J.spanContext().traceState,U=C&&C.get("sentry.dsc"),Y=U&&Pn(U);if(Y)return Y;let Z=yn(A.spanContext().traceId,Q),X=iB(J),E=X.data||{},H=E[Rn];if(H!=null)Z.sample_rate=`${H}`;let $=E[KM],I=X.description;if($!=="url"&&I)Z.transaction=I;if(xn())Z.sampled=String(jn(J));return Q.emit("createDsc",Z,J),Z}function bn(A){if(typeof A==="boolean")return Number(A);let Q=typeof A==="string"?parseFloat(A):A;if(typeof Q!=="number"||isNaN(Q)||Q<0||Q>1){tA&&m0.warn(`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(A)} of type ${JSON.stringify(typeof A)}.`);return}return Q}var fH1=/^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;function pH1(A){return A==="http"||A==="https"}function k7(A,Q=!1){let{host:J,path:K,pass:C,port:U,projectId:Y,protocol:Z,publicKey:X}=A;return`${Z}://${X}${Q&&C?`:${C}`:""}@${J}${U?`:${U}`:""}/${K?`${K}/`:K}${Y}`}function fn(A){let Q=fH1.exec(A);if(!Q){i6(()=>{console.error(`Invalid Sentry Dsn: ${A}`)});return}let[J,K,C="",U="",Y="",Z=""]=Q.slice(1),X="",E=Z,H=E.split("/");if(H.length>1)X=H.slice(0,-1).join("/"),E=H.pop();if(E){let $=E.match(/^\d+/);if($)E=$[0]}return pn({host:U,pass:C,path:X,projectId:E,port:Y,protocol:J,publicKey:K})}function pn(A){return{protocol:A.protocol,publicKey:A.publicKey||"",pass:A.pass||"",host:A.host,port:A.port||"",path:A.path||"",projectId:A.projectId}}function uH1(A){if(!r9)return!0;let{port:Q,projectId:J,protocol:K}=A;if(["protocol","publicKey","host","projectId"].find((Y)=>{if(!A[Y])return m0.error(`Invalid Sentry Dsn: ${Y} missing`),!0;return!1}))return!1;if(!J.match(/^\d+$/))return m0.error(`Invalid Sentry Dsn: Invalid projectId ${J}`),!1;if(!pH1(K))return m0.error(`Invalid Sentry Dsn: Invalid protocol ${K}`),!1;if(Q&&isNaN(parseInt(Q,10)))return m0.error(`Invalid Sentry Dsn: Invalid port ${Q}`),!1;return!0}function CM(A){let Q=typeof A==="string"?fn(A):pn(A);if(!Q||!uH1(Q))return;return Q}function un(){let A=typeof WeakSet==="function",Q=A?/*@__PURE__*/new WeakSet:[];function J(C){if(A){if(Q.has(C))return!0;return Q.add(C),!1}for(let U=0;UJ)return XI(A,Q-1,J);return K}function YM(A,Q,J=1/0,K=1/0,C=un()){let[U,Y]=C;if(Q==null||["boolean","string"].includes(typeof Q)||typeof Q==="number"&&Number.isFinite(Q))return Q;let Z=mH1(A,Q);if(!Z.startsWith("[object "))return Z;if(Q.__sentry_skip_normalization__)return Q;let X=typeof Q.__sentry_override_normalization_depth__==="number"?Q.__sentry_override_normalization_depth__:J;if(X===0)return Z.replace("object ","");if(U(Q))return"[Circular ~]";let E=Q;if(E&&typeof E.toJSON==="function")try{let N=E.toJSON();return YM("",N,X-1,K,C)}catch(N){}let H=Array.isArray(Q)?[]:{},$=0,I=YI(Q);for(let N in I){if(!Object.prototype.hasOwnProperty.call(I,N))continue;if($>=K){H[N]="[MaxProperties ~]";break}let F=I[N];H[N]=YM(N,F,X-1,K,C),$++}return Y(Q),H}function mH1(A,Q){try{if(A==="domain"&&Q&&typeof Q==="object"&&Q._events)return"[Domain]";if(A==="domainEmitter")return"[DomainEmitter]";if(typeof global!=="undefined"&&Q===global)return"[Global]";if(typeof window!=="undefined"&&Q===window)return"[Window]";if(typeof document!=="undefined"&&Q===document)return"[Document]";if(lB(Q))return"[VueViewModel]";if(cV(Q))return"[SyntheticEvent]";if(typeof Q==="number"&&!Number.isFinite(Q))return`[${Q}]`;if(typeof Q==="function")return`[Function: ${t9(Q)}]`;if(typeof Q==="symbol")return`[${String(Q)}]`;if(typeof Q==="bigint")return`[BigInt: ${String(Q)}]`;let J=cH1(Q);if(/^HTML(\w*)Element$/.test(J))return`[HTMLElement: ${J}]`;return`[object ${J}]`}catch(J){return`**non-serializable** (${J})`}}function cH1(A){let Q=Object.getPrototypeOf(A);return Q?Q.constructor.name:"null prototype"}function dH1(A){return~-encodeURI(A).split(/%..|./).length}function lH1(A){return dH1(JSON.stringify(A))}function F3(A,Q=[]){return[A,Q]}function ZM(A,Q){let[J,K]=A;return[J,[...K,Q]]}function EI(A,Q){let J=A[1];for(let K of J){let C=K[0].type;if(Q(K,C))return!0}return!1}function UM(A){return OA.__SENTRY__&&OA.__SENTRY__.encodePolyfill?OA.__SENTRY__.encodePolyfill(A):(/*@__PURE__*/new TextEncoder()).encode(A)}function BM(A){let[Q,J]=A,K=JSON.stringify(Q);function C(U){if(typeof K==="string")K=typeof U==="string"?K+U:[UM(K),U];else K.push(typeof U==="string"?UM(U):U)}for(let U of J){let[Y,Z]=U;if(C(` -${JSON.stringify(Y)} -`),typeof Z==="string"||Z instanceof Uint8Array)C(Z);else{let X;try{X=JSON.stringify(Z)}catch(E){X=JSON.stringify(Q5(Z))}C(X)}}return typeof K==="string"?K:nH1(K)}function nH1(A){let Q=A.reduce((C,U)=>C+U.length,0),J=new Uint8Array(Q),K=0;for(let C of A)J.set(C,K),K+=C.length;return J}function XM(A){let Q=typeof A.data==="string"?UM(A.data):A.data;return[I8({type:"attachment",length:Q.length,filename:A.filename,content_type:A.contentType,attachment_type:A.attachmentType}),Q]}var sH1={session:"session",sessions:"session",attachment:"attachment",transaction:"transaction",event:"error",client_report:"internal",user_report:"default",profile:"profile",profile_chunk:"profile",replay_event:"replay",replay_recording:"replay",check_in:"monitor",feedback:"feedback",span:"span",statsd:"metric_bucket",raw_security:"security"};function $I(A){return sH1[A]}function HI(A){if(!A||!A.sdk)return;let{name:Q,version:J}=A.sdk;return{name:Q,version:J}}function EM(A,Q,J,K){let C=A.sdkProcessingMetadata&&A.sdkProcessingMetadata.dynamicSamplingContext;return{event_id:A.event_id,sent_at:(/*@__PURE__*/new Date()).toISOString(),...Q&&{sdk:Q},...!!J&&K&&{dsn:k7(K)},...C&&{trace:I8({...C})}}}function iH1(A,Q){if(!Q)return A;return A.sdk=A.sdk||{},A.sdk.name=A.sdk.name||Q.name,A.sdk.version=A.sdk.version||Q.version,A.sdk.integrations=[...A.sdk.integrations||[],...Q.integrations||[]],A.sdk.packages=[...A.sdk.packages||[],...Q.packages||[]],A}function mn(A,Q,J,K){let C=HI(J),U={sent_at:(/*@__PURE__*/new Date()).toISOString(),...C&&{sdk:C},...!!K&&Q&&{dsn:k7(Q)}},Y="aggregates"in A?[{type:"sessions"},A]:[{type:"session"},A.toJSON()];return F3(U,[Y])}function cn(A,Q,J,K){let C=HI(J),U=A.type&&A.type!=="replay_event"?A.type:"event";iH1(A,J&&J.sdk);let Y=EM(A,C,K,Q);return delete A.sdkProcessingMetadata,F3(Y,[[{type:U},A]])}function GI(A,Q,J,K=0){return new W6((C,U)=>{let Y=A[K];if(Q===null||typeof Y!=="function")C(Q);else{let Z=Y({...Q},J);if(tA&&Y.id&&Z===null&&m0.log(`Event processor "${Y.id}" dropped event`),w7(Z))Z.then((X)=>GI(A,X,J,K+1).then(C)).then(null,U);else GI(A,Z,J,K+1).then(C).then(null,U)}})}var WI,dn,II;function ln(A){let Q=OA._sentryDebugIds;if(!Q)return{};let J=Object.keys(Q);if(II&&J.length===dn)return II;return dn=J.length,II=J.reduce((K,C)=>{if(!WI)WI={};let U=WI[C];if(U)K[U[0]]=U[1];else{let Y=A(C);for(let Z=Y.length-1;Z>=0;Z--){let X=Y[Z],E=X&&X.filename,H=Q[C];if(E&&H){K[E]=H,WI[C]=[E,H];break}}}return K},{}),II}function nn(A,Q){let{fingerprint:J,span:K,breadcrumbs:C,sdkProcessingMetadata:U}=Q;if(aH1(A,Q),K)eH1(A,K);AG1(A,J),rH1(A,C),tH1(A,U)}function $M(A,Q){let{extra:J,tags:K,user:C,contexts:U,level:Y,sdkProcessingMetadata:Z,breadcrumbs:X,fingerprint:E,eventProcessors:H,attachments:$,propagationContext:I,transactionName:N,span:F}=Q;if(qI(A,"extra",J),qI(A,"tags",K),qI(A,"user",C),qI(A,"contexts",U),A.sdkProcessingMetadata=OY(A.sdkProcessingMetadata,Z,2),Y)A.level=Y;if(N)A.transactionName=N;if(F)A.span=F;if(X.length)A.breadcrumbs=[...A.breadcrumbs,...X];if(E.length)A.fingerprint=[...A.fingerprint,...E];if(H.length)A.eventProcessors=[...A.eventProcessors,...H];if($.length)A.attachments=[...A.attachments,...$];A.propagationContext={...A.propagationContext,...I}}function qI(A,Q,J){A[Q]=OY(A[Q],J,1)}function aH1(A,Q){let{extra:J,tags:K,user:C,contexts:U,level:Y,transactionName:Z}=Q,X=I8(J);if(X&&Object.keys(X).length)A.extra={...X,...A.extra};let E=I8(K);if(E&&Object.keys(E).length)A.tags={...E,...A.tags};let H=I8(C);if(H&&Object.keys(H).length)A.user={...H,...A.user};let $=I8(U);if($&&Object.keys($).length)A.contexts={...$,...A.contexts};if(Y)A.level=Y;if(Z&&A.type!=="transaction")A.transaction=Z}function rH1(A,Q){let J=[...A.breadcrumbs||[],...Q];A.breadcrumbs=J.length?J:void 0}function tH1(A,Q){A.sdkProcessingMetadata={...A.sdkProcessingMetadata,...Q}}function eH1(A,Q){A.contexts={trace:Sn(Q),...A.contexts},A.sdkProcessingMetadata={dynamicSamplingContext:gn(Q),...A.sdkProcessingMetadata};let J=BI(Q),K=iB(J).description;if(K&&!A.transaction&&A.type==="transaction")A.transaction=K}function AG1(A,Q){if(A.fingerprint=A.fingerprint?Array.isArray(A.fingerprint)?A.fingerprint:[A.fingerprint]:[],Q)A.fingerprint=A.fingerprint.concat(Q);if(A.fingerprint&&!A.fingerprint.length)delete A.fingerprint}function sn(A,Q,J,K,C,U){let{normalizeDepth:Y=3,normalizeMaxBreadth:Z=1000}=A,X={...Q,event_id:Q.event_id||J.event_id||k8(),timestamp:Q.timestamp||N3()},E=J.integrations||A.integrations.map((D)=>D.name);if(QG1(X,A),CG1(X,E),C)C.emit("applyFrameMetadata",Q);if(Q.type===void 0)JG1(X,A.stackParser);let H=UG1(K,J.captureContext);if(J.mechanism)L3(X,J.mechanism);let $=C?C.getEventProcessors():[],I=AM().getScopeData();if(U){let D=U.getScopeData();$M(I,D)}if(H){let D=H.getScopeData();$M(I,D)}let N=[...J.attachments||[],...I.attachments];if(N.length)J.attachments=N;nn(X,I);let F=[...$,...I.eventProcessors];return GI(F,X,J).then((D)=>{if(D)KG1(D);if(typeof Y==="number"&&Y>0)return YG1(D,Y,Z);return D})}function QG1(A,Q){let{environment:J,release:K,dist:C,maxValueLength:U=250}=Q;if(A.environment=A.environment||J||LY,!A.release&&K)A.release=K;if(!A.dist&&C)A.dist=C;if(A.message)A.message=O3(A.message,U);let Y=A.exception&&A.exception.values&&A.exception.values[0];if(Y&&Y.value)Y.value=O3(Y.value,U);let Z=A.request;if(Z&&Z.url)Z.url=O3(Z.url,U)}function JG1(A,Q){let J=ln(Q);try{A.exception.values.forEach((K)=>{K.stacktrace.frames.forEach((C)=>{if(J&&C.filename)C.debug_id=J[C.filename]})})}catch(K){}}function KG1(A){let Q={};try{A.exception.values.forEach((K)=>{K.stacktrace.frames.forEach((C)=>{if(C.debug_id){if(C.abs_path)Q[C.abs_path]=C.debug_id;else if(C.filename)Q[C.filename]=C.debug_id;delete C.debug_id}})})}catch(K){}if(Object.keys(Q).length===0)return;A.debug_meta=A.debug_meta||{},A.debug_meta.images=A.debug_meta.images||[];let J=A.debug_meta.images;Object.entries(Q).forEach(([K,C])=>{J.push({type:"sourcemap",code_file:K,debug_id:C})})}function CG1(A,Q){if(Q.length>0)A.sdk=A.sdk||{},A.sdk.integrations=[...A.sdk.integrations||[],...Q]}function YG1(A,Q,J){if(!A)return null;let K={...A,...A.breadcrumbs&&{breadcrumbs:A.breadcrumbs.map((C)=>({...C,...C.data&&{data:Q5(C.data,Q,J)}}))},...A.user&&{user:Q5(A.user,Q,J)},...A.contexts&&{contexts:Q5(A.contexts,Q,J)},...A.extra&&{extra:Q5(A.extra,Q,J)}};if(A.contexts&&A.contexts.trace&&K.contexts){if(K.contexts.trace=A.contexts.trace,A.contexts.trace.data)K.contexts.trace.data=Q5(A.contexts.trace.data,Q,J)}if(A.spans)K.spans=A.spans.map((C)=>{return{...C,...C.data&&{data:Q5(C.data,Q,J)}}});if(A.contexts&&A.contexts.flags&&K.contexts)K.contexts.flags=Q5(A.contexts.flags,3,J);return K}function UG1(A,Q){if(!Q)return A;let J=A?A.clone():new A5;return J.update(Q),J}function on(A){if(!A)return;if(ZG1(A))return{captureContext:A};if(XG1(A))return{captureContext:A};return A}function ZG1(A){return A instanceof A5||typeof A==="function"}var BG1=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"];function XG1(A){return Object.keys(A).some((Q)=>BG1.includes(Q))}function HM(A,Q){return r6().captureException(A,on(Q))}function OI(A,Q){return r6().captureEvent(A,Q)}function NI(A){let Q=b2(),J=T7(),K=r6(),{release:C,environment:U=LY}=Q&&Q.getOptions()||{},{userAgent:Y}=OA.navigator||{},Z=Gn({release:C,environment:U,user:K.getUser()||J.getUser(),...Y&&{userAgent:Y},...A}),X=J.getSession();if(X&&X.status==="ok")_7(X,{status:"exited"});return GM(),J.setSession(Z),K.setSession(Z),Z}function GM(){let A=T7(),Q=r6(),J=Q.getSession()||A.getSession();if(J)Wn(J);an(),A.setSession(),Q.setSession()}function an(){let A=T7(),Q=r6(),J=b2(),K=Q.getSession()||A.getSession();if(K&&J)J.captureSession(K)}function LI(A=!1){if(A){GM();return}an()}var $G1="7";function HG1(A){let Q=A.protocol?`${A.protocol}:`:"",J=A.port?`:${A.port}`:"";return`${Q}//${A.host}${J}${A.path?`/${A.path}`:""}/api/`}function GG1(A){return`${HG1(A)}${A.projectId}/envelope/`}function WG1(A,Q){let J={sentry_version:$G1};if(A.publicKey)J.sentry_key=A.publicKey;if(Q)J.sentry_client=`${Q.name}/${Q.version}`;return new URLSearchParams(J).toString()}function rn(A,Q,J){return Q?Q:`${GG1(A)}?${WG1(A,J)}`}var tn=[];function IG1(A){let Q={};return A.forEach((J)=>{let{name:K}=J,C=Q[K];if(C&&!C.isDefaultInstance&&J.isDefaultInstance)return;Q[K]=J}),Object.values(Q)}function WM(A){let Q=A.defaultIntegrations||[],J=A.integrations;Q.forEach((Y)=>{Y.isDefaultInstance=!0});let K;if(Array.isArray(J))K=[...Q,...J];else if(typeof J==="function"){let Y=J(Q);K=Array.isArray(Y)?Y:[Y]}else K=Q;let C=IG1(K),U=C.findIndex((Y)=>Y.name==="Debug");if(U>-1){let[Y]=C.splice(U,1);C.push(Y)}return C}function en(A,Q){let J={};return Q.forEach((K)=>{if(K)qM(A,K,J)}),J}function IM(A,Q){for(let J of Q)if(J&&J.afterAllSetup)J.afterAllSetup(A)}function qM(A,Q,J){if(J[Q.name]){tA&&m0.log(`Integration skipped because it was already installed: ${Q.name}`);return}if(J[Q.name]=Q,tn.indexOf(Q.name)===-1&&typeof Q.setupOnce==="function")Q.setupOnce(),tn.push(Q.name);if(Q.setup&&typeof Q.setup==="function")Q.setup(A);if(typeof Q.preprocessEvent==="function"){let K=Q.preprocessEvent.bind(Q);A.on("preprocessEvent",(C,U)=>K(C,U,A))}if(typeof Q.processEvent==="function"){let K=Q.processEvent.bind(Q),C=Object.assign((U,Y)=>K(U,Y,A),{id:Q.name});A.addEventProcessor(C)}tA&&m0.log(`Integration installed: ${Q.name}`)}function S8(A){return A}function As(A,Q,J){let K=[{type:"client_report"},{timestamp:J||N3(),discarded_events:A}];return F3(Q?{dsn:Q}:{},[K])}class _6 extends Error{constructor(A,Q="warn"){super(A);this.message=A,this.logLevel=Q}}var Qs="Not capturing exception because it's already been captured.";class FI{constructor(A){if(this._options=A,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],A.dsn)this._dsn=CM(A.dsn);else tA&&m0.warn("No DSN provided, client will not send events.");if(this._dsn){let K=rn(this._dsn,A.tunnel,A._metadata?A._metadata.sdk:void 0);this._transport=A.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...A.transportOptions,url:K})}let J=["enableTracing","tracesSampleRate","tracesSampler"].find((K)=>(K in A)&&A[K]==null);if(J)i6(()=>{console.warn(`[Sentry] Deprecation warning: \`${J}\` is set to undefined, which leads to tracing being enabled. In v9, a value of \`undefined\` will result in tracing being disabled.`)})}captureException(A,Q,J){let K=k8();if(UI(A))return tA&&m0.log(Qs),K;let C={event_id:K,...Q};return this._process(this.eventFromException(A,C).then((U)=>this._captureEvent(U,C,J))),C.event_id}captureMessage(A,Q,J,K){let C={event_id:k8(),...J},U=WY(A)?A:String(A),Y=TJ(A)?this.eventFromMessage(U,Q,C):this.eventFromException(A,C);return this._process(Y.then((Z)=>this._captureEvent(Z,C,K))),C.event_id}captureEvent(A,Q,J){let K=k8();if(Q&&Q.originalException&&UI(Q.originalException))return tA&&m0.log(Qs),K;let C={event_id:K,...Q},Y=(A.sdkProcessingMetadata||{}).capturedSpanScope;return this._process(this._captureEvent(A,C,Y||J)),C.event_id}captureSession(A){if(typeof A.release!=="string")tA&&m0.warn("Discarded session because of missing or non-string release");else this.sendSession(A),_7(A,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}flush(A){let Q=this._transport;if(Q)return this.emit("flush"),this._isClientDoneProcessing(A).then((J)=>{return Q.flush(A).then((K)=>J&&K)});else return e9(!0)}close(A){return this.flush(A).then((Q)=>{return this.getOptions().enabled=!1,this.emit("close"),Q})}getEventProcessors(){return this._eventProcessors}addEventProcessor(A){this._eventProcessors.push(A)}init(){if(this._isEnabled()||this._options.integrations.some(({name:A})=>A.startsWith("Spotlight")))this._setupIntegrations()}getIntegrationByName(A){return this._integrations[A]}addIntegration(A){let Q=this._integrations[A.name];if(qM(this,A,this._integrations),!Q)IM(this,[A])}sendEvent(A,Q={}){this.emit("beforeSendEvent",A,Q);let J=cn(A,this._dsn,this._options._metadata,this._options.tunnel);for(let C of Q.attachments||[])J=ZM(J,XM(C));let K=this.sendEnvelope(J);if(K)K.then((C)=>this.emit("afterSendEvent",A,C),null)}sendSession(A){let Q=mn(A,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(Q)}recordDroppedEvent(A,Q,J){if(this._options.sendClientReports){let K=typeof J==="number"?J:1,C=`${A}:${Q}`;tA&&m0.log(`Recording outcome: "${C}"${K>1?` (${K} times)`:""}`),this._outcomes[C]=(this._outcomes[C]||0)+K}}on(A,Q){let J=this._hooks[A]=this._hooks[A]||[];return J.push(Q),()=>{let K=J.indexOf(Q);if(K>-1)J.splice(K,1)}}emit(A,...Q){let J=this._hooks[A];if(J)J.forEach((K)=>K(...Q))}sendEnvelope(A){if(this.emit("beforeEnvelope",A),this._isEnabled()&&this._transport)return this._transport.send(A).then(null,(Q)=>{return tA&&m0.error("Error while sending envelope:",Q),Q});return tA&&m0.error("Transport disabled"),e9({})}_setupIntegrations(){let{integrations:A}=this._options;this._integrations=en(this,A),IM(this,A)}_updateSessionFromEvent(A,Q){let J=Q.level==="fatal",K=!1,C=Q.exception&&Q.exception.values;if(C){K=!0;for(let Z of C){let X=Z.mechanism;if(X&&X.handled===!1){J=!0;break}}}let U=A.status==="ok";if(U&&A.errors===0||U&&J)_7(A,{...J&&{status:"crashed"},errors:A.errors||Number(K||J)}),this.captureSession(A)}_isClientDoneProcessing(A){return new W6((Q)=>{let J=0,K=1,C=setInterval(()=>{if(this._numProcessing==0)clearInterval(C),Q(!0);else if(J+=K,A&&J>=A)clearInterval(C),Q(!1)},K)})}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(A,Q,J=r6(),K=T7()){let C=this.getOptions(),U=Object.keys(this._integrations);if(!Q.integrations&&U.length>0)Q.integrations=U;if(this.emit("preprocessEvent",A,Q),!A.type)K.setLastEventId(A.event_id||Q.event_id);return sn(C,A,Q,J,this,K).then((Y)=>{if(Y===null)return Y;Y.contexts={trace:JM(J),...Y.contexts};let Z=hn(this,J);return Y.sdkProcessingMetadata={dynamicSamplingContext:Z,...Y.sdkProcessingMetadata},Y})}_captureEvent(A,Q={},J){return this._processEvent(A,Q,J).then((K)=>{return K.event_id},(K)=>{if(tA)if(K instanceof _6&&K.logLevel==="log")m0.log(K.message);else m0.warn(K);return})}_processEvent(A,Q,J){let K=this.getOptions(),{sampleRate:C}=K,U=Ks(A),Y=Js(A),Z=A.type||"error",X=`before send for type \`${Z}\``,E=typeof C==="undefined"?void 0:bn(C);if(Y&&typeof E==="number"&&Math.random()>E)return this.recordDroppedEvent("sample_rate","error",A),x4(new _6(`Discarding event because it's not included in the random sample (sampling rate = ${C})`,"log"));let H=Z==="replay_event"?"replay":Z,I=(A.sdkProcessingMetadata||{}).capturedSpanIsolationScope;return this._prepareEvent(A,Q,J,I).then((N)=>{if(N===null)throw this.recordDroppedEvent("event_processor",H,A),new _6("An event processor returned `null`, will not send event.","log");if(Q.data&&Q.data.__sentry__===!0)return N;let V=OG1(this,K,N,Q);return qG1(V,X)}).then((N)=>{if(N===null){if(this.recordDroppedEvent("before_send",H,A),U){let L=1+(A.spans||[]).length;this.recordDroppedEvent("before_send","span",L)}throw new _6(`${X} returned \`null\`, will not send event.`,"log")}let F=J&&J.getSession();if(!U&&F)this._updateSessionFromEvent(F,N);if(U){let D=N.sdkProcessingMetadata&&N.sdkProcessingMetadata.spanCountBeforeProcessing||0,L=N.spans?N.spans.length:0,R=D-L;if(R>0)this.recordDroppedEvent("before_send","span",R)}let V=N.transaction_info;if(U&&V&&N.transaction!==A.transaction)N.transaction_info={...V,source:"custom"};return this.sendEvent(N,Q),N}).then(null,(N)=>{if(N instanceof _6)throw N;throw this.captureException(N,{data:{__sentry__:!0},originalException:N}),new _6(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event. -Reason: ${N}`)})}_process(A){this._numProcessing++,A.then((Q)=>{return this._numProcessing--,Q},(Q)=>{return this._numProcessing--,Q})}_clearOutcomes(){let A=this._outcomes;return this._outcomes={},Object.entries(A).map(([Q,J])=>{let[K,C]=Q.split(":");return{reason:K,category:C,quantity:J}})}_flushOutcomes(){tA&&m0.log("Flushing outcomes...");let A=this._clearOutcomes();if(A.length===0){tA&&m0.log("No outcomes to send");return}if(!this._dsn){tA&&m0.log("No dsn provided, will not send outcomes");return}tA&&m0.log("Sending outcomes:",A);let Q=As(A,this._options.tunnel&&k7(this._dsn));this.sendEnvelope(Q)}}function qG1(A,Q){let J=`${Q} must return \`null\` or a valid event.`;if(w7(A))return A.then((K)=>{if(!x5(K)&&K!==null)throw new _6(J);return K},(K)=>{throw new _6(`${Q} rejected with ${K}`)});else if(!x5(A)&&A!==null)throw new _6(J);return A}function OG1(A,Q,J,K){let{beforeSend:C,beforeSendTransaction:U,beforeSendSpan:Y}=Q;if(Js(J)&&C)return C(J,K);if(Ks(J)){if(J.spans&&Y){let Z=[];for(let X of J.spans){let E=Y(X);if(E)Z.push(E);else vn(),A.recordDroppedEvent("before_send","span")}J.spans=Z}if(U){if(J.spans){let Z=J.spans.length;J.sdkProcessingMetadata={...J.sdkProcessingMetadata,spanCountBeforeProcessing:Z}}return U(J,K)}}return J}function Js(A){return A.type===void 0}function Ks(A){return A.type==="transaction"}function OM(A,Q){if(Q.debug===!0)if(tA)m0.enable();else i6(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});r6().update(Q.initialScope);let K=new A(Q);return Cs(K),K.init(),K}function Cs(A){r6().setClient(A)}function Ys(A){let Q=[];function J(){return A===void 0||Q.lengthK(Z)).then(null,()=>K(Z).then(null,()=>{})),Z}function U(Y){return new W6((Z,X)=>{let E=Q.length;if(!E)return Z(!0);let H=setTimeout(()=>{if(Y&&Y>0)Z(!1)},Y);Q.forEach(($)=>{e9($).then(()=>{if(!--E)clearTimeout(H),Z(!0)},X)})})}return{$:Q,add:C,drain:U}}function NG1(A,Q=Date.now()){let J=parseInt(`${A}`,10);if(!isNaN(J))return J*1000;let K=Date.parse(`${A}`);if(!isNaN(K))return K-Q;return 60000}function LG1(A,Q){return A[Q]||A.all||0}function Us(A,Q,J=Date.now()){return LG1(A,Q)>J}function Zs(A,{statusCode:Q,headers:J},K=Date.now()){let C={...A},U=J&&J["x-sentry-rate-limits"],Y=J&&J["retry-after"];if(U)for(let Z of U.trim().split(",")){let[X,E,,,H]=Z.split(":",5),$=parseInt(X,10),I=(!isNaN($)?$:60)*1000;if(!E)C.all=K+I;else for(let N of E.split(";"))if(N==="metric_bucket"){if(!H||H.split(";").includes("custom"))C[N]=K+I}else C[N]=K+I}else if(Y)C.all=K+NG1(Y,K);else if(Q===429)C.all=K+60000;return C}var FG1=64;function NM(A,Q,J=Ys(A.bufferSize||FG1)){let K={},C=(Y)=>J.drain(Y);function U(Y){let Z=[];if(EI(Y,($,I)=>{let N=$I(I);if(Us(K,N)){let F=Bs($,I);A.recordDroppedEvent("ratelimit_backoff",N,F)}else Z.push($)}),Z.length===0)return e9({});let X=F3(Y[0],Z),E=($)=>{EI(X,(I,N)=>{let F=Bs(I,N);A.recordDroppedEvent($,$I(N),F)})},H=()=>Q({body:BM(X)}).then(($)=>{if($.statusCode!==void 0&&($.statusCode<200||$.statusCode>=300))tA&&m0.warn(`Sentry responded with status code ${$.statusCode} to sent event.`);return K=Zs(K,$),$},($)=>{throw E("network_error"),$});return J.add(H).then(($)=>$,($)=>{if($ instanceof _6)return tA&&m0.error("Skipped sending event because buffer is full."),E("queue_overflow"),e9({});else throw $})}return{send:U,flush:C}}function Bs(A,Q){if(Q!=="event"&&Q!=="transaction")return;return Array.isArray(A)?A[1]:void 0}function LM(A,Q,J=[Q],K="npm"){let C=A._metadata||{};if(!C.sdk)C.sdk={name:`sentry.javascript.${Q}`,packages:J.map((U)=>({name:`${K}:@sentry/${U}`,version:I3})),version:I3};A._metadata=C}var RG1=100;function S7(A,Q){let J=b2(),K=T7();if(!J)return;let{beforeBreadcrumb:C=null,maxBreadcrumbs:U=RG1}=J.getOptions();if(U<=0)return;let Z={timestamp:N3(),...A},X=C?i6(()=>C(Z,Q)):Z;if(X===null)return;if(J.emit)J.emit("beforeAddBreadcrumb",X,Q);K.addBreadcrumb(X,U)}var Xs,zG1="FunctionToString",Es=/*@__PURE__*/new WeakMap,DG1=()=>{return{name:zG1,setupOnce(){Xs=Function.prototype.toString;try{Function.prototype.toString=function(...A){let Q=SJ(this),J=Es.has(b2())&&Q!==void 0?Q:this;return Xs.apply(J,A)}}catch(A){}},setup(A){Es.set(A,!0)}}},FM=S8(DG1);var VG1=[/^Script error\.?$/,/^Javascript error: Script error\.? on line 0$/,/^ResizeObserver loop completed with undelivered notifications.$/,/^Cannot redefine property: googletag$/,"undefined is not an object (evaluating 'a.L')",`can't redefine non-configurable property "solana"`,"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)","Can't find variable: _AutofillCallbackHandler",/^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/],MG1="InboundFilters",wG1=(A={})=>{return{name:MG1,processEvent(Q,J,K){let C=K.getOptions(),U=PG1(A,C);return _G1(Q,U)?null:Q}}},RM=S8(wG1);function PG1(A={},Q={}){return{allowUrls:[...A.allowUrls||[],...Q.allowUrls||[]],denyUrls:[...A.denyUrls||[],...Q.denyUrls||[]],ignoreErrors:[...A.ignoreErrors||[],...Q.ignoreErrors||[],...A.disableErrorDefaults?[]:VG1],ignoreTransactions:[...A.ignoreTransactions||[],...Q.ignoreTransactions||[]],ignoreInternal:A.ignoreInternal!==void 0?A.ignoreInternal:!0}}function _G1(A,Q){if(Q.ignoreInternal&&xG1(A))return tA&&m0.warn(`Event dropped due to being internal Sentry Error. -Event: ${y5(A)}`),!0;if(TG1(A,Q.ignoreErrors))return tA&&m0.warn(`Event dropped due to being matched by \`ignoreErrors\` option. -Event: ${y5(A)}`),!0;if(hG1(A))return tA&&m0.warn(`Event dropped due to not having an error message, error type or stacktrace. -Event: ${y5(A)}`),!0;if(kG1(A,Q.ignoreTransactions))return tA&&m0.warn(`Event dropped due to being matched by \`ignoreTransactions\` option. -Event: ${y5(A)}`),!0;if(SG1(A,Q.denyUrls))return tA&&m0.warn(`Event dropped due to being matched by \`denyUrls\` option. -Event: ${y5(A)}. -Url: ${RI(A)}`),!0;if(!jG1(A,Q.allowUrls))return tA&&m0.warn(`Event dropped due to not being matched by \`allowUrls\` option. -Event: ${y5(A)}. -Url: ${RI(A)}`),!0;return!1}function TG1(A,Q){if(A.type||!Q||!Q.length)return!1;return vG1(A).some((J)=>IY(J,Q))}function kG1(A,Q){if(A.type!=="transaction"||!Q||!Q.length)return!1;let J=A.transaction;return J?IY(J,Q):!1}function SG1(A,Q){if(!Q||!Q.length)return!1;let J=RI(A);return!J?!1:IY(J,Q)}function jG1(A,Q){if(!Q||!Q.length)return!0;let J=RI(A);return!J?!0:IY(J,Q)}function vG1(A){let Q=[];if(A.message)Q.push(A.message);let J;try{J=A.exception.values[A.exception.values.length-1]}catch(K){}if(J){if(J.value){if(Q.push(J.value),J.type)Q.push(`${J.type}: ${J.value}`)}}return Q}function xG1(A){try{return A.exception.values[0].type==="SentryError"}catch(Q){}return!1}function yG1(A=[]){for(let Q=A.length-1;Q>=0;Q--){let J=A[Q];if(J&&J.filename!==""&&J.filename!=="[native code]")return J.filename||null}return null}function RI(A){try{let Q;try{Q=A.exception.values[0].stacktrace.frames}catch(J){}return Q?yG1(Q):null}catch(Q){return tA&&m0.error(`Cannot extract url for event ${y5(A)}`),null}}function hG1(A){if(A.type)return!1;if(!A.exception||!A.exception.values||A.exception.values.length===0)return!1;return!A.message&&!A.exception.values.some((Q)=>Q.stacktrace||Q.type&&Q.type!=="Error"||Q.value)}function DM(A,Q,J=250,K,C,U,Y){if(!U.exception||!U.exception.values||!Y||!q3(Y.originalException,Error))return;let Z=U.exception.values.length>0?U.exception.values[U.exception.values.length-1]:void 0;if(Z)U.exception.values=gG1(zM(A,Q,C,Y.originalException,K,U.exception.values,Z,0),J)}function zM(A,Q,J,K,C,U,Y,Z){if(U.length>=J+1)return U;let X=[...U];if(q3(K[C],Error)){$s(Y,Z);let E=A(Q,K[C]),H=X.length;Hs(E,C,H,Z),X=zM(A,Q,J,K[C],C,[E,...X],E,H)}if(Array.isArray(K.errors))K.errors.forEach((E,H)=>{if(q3(E,Error)){$s(Y,Z);let $=A(Q,E),I=X.length;Hs($,`errors[${H}]`,I,Z),X=zM(A,Q,J,E,C,[$,...X],$,I)}});return X}function $s(A,Q){A.mechanism=A.mechanism||{type:"generic",handled:!0},A.mechanism={...A.mechanism,...A.type==="AggregateError"&&{is_exception_group:!0},exception_id:Q}}function Hs(A,Q,J,K){A.mechanism=A.mechanism||{type:"generic",handled:!0},A.mechanism={...A.mechanism,type:"chained",source:Q,exception_id:J,parent_id:K}}function gG1(A,Q){return A.map((J)=>{if(J.value)J.value=O3(J.value,Q);return J})}function aB(A){if(!A)return{};let Q=A.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!Q)return{};let J=Q[6]||"",K=Q[8]||"";return{host:Q[4],path:Q[5],protocol:Q[2],search:J,hash:K,relative:Q[5]+J+K}}function VM(A){V6("console",A),M6("console",bG1)}function bG1(){if(!("console"in OA))return;cB.forEach(function(A){if(!(A in OA.console))return;T8(OA.console,A,function(Q){return HY[A]=Q,function(...J){_8("console",{args:J,level:A});let C=HY[A];C&&C.apply(OA.console,J)}})})}function MM(A){return A==="warn"?"warning":["fatal","error","warning","log","info","debug"].includes(A)?A:"log"}var fG1="Dedupe",pG1=()=>{let A;return{name:fG1,processEvent(Q){if(Q.type)return Q;try{if(uG1(Q,A))return tA&&m0.warn("Event dropped due to being a duplicate of previously captured event."),null}catch(J){}return A=Q}}},wM=S8(pG1);function uG1(A,Q){if(!Q)return!1;if(mG1(A,Q))return!0;if(cG1(A,Q))return!0;return!1}function mG1(A,Q){let J=A.message,K=Q.message;if(!J&&!K)return!1;if(J&&!K||!J&&K)return!1;if(J!==K)return!1;if(!Is(A,Q))return!1;if(!Ws(A,Q))return!1;return!0}function cG1(A,Q){let J=Gs(Q),K=Gs(A);if(!J||!K)return!1;if(J.type!==K.type||J.value!==K.value)return!1;if(!Is(A,Q))return!1;if(!Ws(A,Q))return!1;return!0}function Ws(A,Q){let J=eW(A),K=eW(Q);if(!J&&!K)return!0;if(J&&!K||!J&&K)return!1;if(J=J,K=K,K.length!==J.length)return!1;for(let C=0;C=400&&A<500)return"warning";else if(A>=500)return"error";else return}var PM=OA;function DI(){if(!("fetch"in PM))return!1;try{return new Request("http://www.example.com"),!0}catch(A){return!1}}function rB(A){return A&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(A.toString())}function _M(){if(typeof EdgeRuntime==="string")return!0;if(!DI())return!1;if(rB(PM.fetch))return!0;let A=!1,Q=PM.document;if(Q&&typeof Q.createElement==="function")try{let J=Q.createElement("iframe");if(J.hidden=!0,Q.head.appendChild(J),J.contentWindow&&J.contentWindow.fetch)A=rB(J.contentWindow.fetch);Q.head.removeChild(J)}catch(J){r9&&m0.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ",J)}return A}function kM(A,Q){V6("fetch",A),M6("fetch",()=>dG1(void 0,Q))}function dG1(A,Q=!1){if(Q&&!_M())return;T8(OA,"fetch",function(J){return function(...K){let C=new Error,{method:U,url:Y}=lG1(K),Z={args:K,fetchData:{method:U,url:Y},startTimestamp:a6()*1000,virtualError:C};if(!A)_8("fetch",{...Z});return J.apply(OA,K).then(async(X)=>{if(A)A(X);else _8("fetch",{...Z,endTimestamp:a6()*1000,response:X});return X},(X)=>{if(_8("fetch",{...Z,endTimestamp:a6()*1000,error:X}),_J(X)&&X.stack===void 0)X.stack=C.stack,P6(X,"framesToPop",1);throw X})}})}function TM(A,Q){return!!A&&typeof A==="object"&&!!A[Q]}function qs(A){if(typeof A==="string")return A;if(!A)return"";if(TM(A,"url"))return A.url;if(A.toString)return A.toString();return""}function lG1(A){if(A.length===0)return{method:"GET",url:""};if(A.length===2){let[J,K]=A;return{url:qs(J),method:TM(K,"method")?String(K.method).toUpperCase():"GET"}}let Q=A[0];return{url:qs(Q),method:TM(Q,"method")?String(Q.method).toUpperCase():"GET"}}function SM(){return"npm"}var VI=OA;function jM(){let A=VI.chrome,Q=A&&A.app&&A.app.runtime,J="history"in VI&&!!VI.history.pushState&&!!VI.history.replaceState;return!Q&&J}var C2=OA,vM=0;function xM(){return vM>0}function sG1(){vM++,setTimeout(()=>{vM--})}function jJ(A,Q={}){function J(C){return typeof C==="function"}if(!J(A))return A;try{let C=A.__sentry_wrapped__;if(C)if(typeof C==="function")return C;else return A;if(SJ(A))return A}catch(C){return A}let K=function(...C){try{let U=C.map((Y)=>jJ(Y,Q));return A.apply(this,U)}catch(U){throw sG1(),QM((Y)=>{Y.addEventProcessor((Z)=>{if(Q.mechanism)qY(Z,void 0,void 0),L3(Z,Q.mechanism);return Z.extra={...Z.extra,arguments:C},Z}),HM(U)}),U}};try{for(let C in A)if(Object.prototype.hasOwnProperty.call(A,C))K[C]=A[C]}catch(C){}CI(K,A),P6(A,"__sentry_wrapped__",K);try{if(Object.getOwnPropertyDescriptor(K,"name").configurable)Object.defineProperty(K,"name",{get(){return A.name}})}catch(C){}return K}var R3=typeof __SENTRY_DEBUG__==="undefined"||__SENTRY_DEBUG__;function MI(A,Q){let J=gM(A,Q),K={type:tG1(Q),value:eG1(Q)};if(J.length)K.stacktrace={frames:J};if(K.type===void 0&&K.value==="")K.value="Unrecoverable error caught";return K}function oG1(A,Q,J,K){let C=b2(),U=C&&C.getOptions().normalizeDepth,Y=JW1(Q),Z={__serialized__:XI(Q,U)};if(Y)return{exception:{values:[MI(A,Y)]},extra:Z};let X={exception:{values:[{type:kJ(Q)?Q.constructor.name:K?"UnhandledRejection":"Error",value:AW1(Q,{isUnhandledRejection:K})}]},extra:Z};if(J){let E=gM(A,J);if(E.length)X.exception.values[0].stacktrace={frames:E}}return X}function yM(A,Q){return{exception:{values:[MI(A,Q)]}}}function gM(A,Q){let J=Q.stacktrace||Q.stack||"",K=aG1(Q),C=rG1(Q);try{return A(J,K,C)}catch(U){}return[]}var iG1=/Minified React error #\d+;/i;function aG1(A){if(A&&iG1.test(A.message))return 1;return 0}function rG1(A){if(typeof A.framesToPop==="number")return A.framesToPop;return 0}function Os(A){if(typeof WebAssembly!=="undefined"&&typeof WebAssembly.Exception!=="undefined")return A instanceof WebAssembly.Exception;else return!1}function tG1(A){let Q=A&&A.name;if(!Q&&Os(A))return A.message&&Array.isArray(A.message)&&A.message.length==2?A.message[0]:"WebAssembly.Exception";return Q}function eG1(A){let Q=A&&A.message;if(!Q)return"No error message";if(Q.error&&typeof Q.error.message==="string")return Q.error.message;if(Os(A)&&Array.isArray(A.message)&&A.message.length==2)return A.message[1];return Q}function Ns(A,Q,J,K){let C=J&&J.syntheticException||void 0,U=wI(A,Q,C,K);if(L3(U),U.level="error",J&&J.event_id)U.event_id=J.event_id;return e9(U)}function Ls(A,Q,J="info",K,C){let U=K&&K.syntheticException||void 0,Y=hM(A,Q,U,C);if(Y.level=J,K&&K.event_id)Y.event_id=K.event_id;return e9(Y)}function wI(A,Q,J,K,C){let U;if(QI(Q)&&Q.error)return yM(A,Q.error);if(JI(Q)||pV(Q)){let Y=Q;if("stack"in Q)U=yM(A,Q);else{let Z=Y.name||(JI(Y)?"DOMError":"DOMException"),X=Y.message?`${Z}: ${Y.message}`:Z;U=hM(A,X,J,K),qY(U,X)}if("code"in Y)U.tags={...U.tags,"DOMException.code":`${Y.code}`};return U}if(_J(Q))return yM(A,Q);if(x5(Q)||kJ(Q))return U=oG1(A,Q,J,C),L3(U,{synthetic:!0}),U;return U=hM(A,Q,J,K),qY(U,`${Q}`,void 0),L3(U,{synthetic:!0}),U}function hM(A,Q,J,K){let C={};if(K&&J){let U=gM(A,J);if(U.length)C.exception={values:[{value:Q,stacktrace:{frames:U}}]};L3(C,{synthetic:!0})}if(WY(Q)){let{__sentry_template_string__:U,__sentry_template_values__:Y}=Q;return C.logentry={message:U,params:Y},C}return C.message=Q,C}function AW1(A,{isUnhandledRejection:Q}){let J=oV(A),K=Q?"promise rejection":"exception";if(QI(A))return`Event \`ErrorEvent\` captured as ${K} with message \`${A.message}\``;if(kJ(A))return`Event \`${QW1(A)}\` (type=${A.type}) captured as ${K}`;return`Object captured as ${K} with keys: ${J}`}function QW1(A){try{let Q=Object.getPrototypeOf(A);return Q?Q.constructor.name:void 0}catch(Q){}}function JW1(A){for(let Q in A)if(Object.prototype.hasOwnProperty.call(A,Q)){let J=A[Q];if(J instanceof Error)return J}return}function Fs(A,{metadata:Q,tunnel:J,dsn:K}){let C={event_id:A.event_id,sent_at:(/*@__PURE__*/new Date()).toISOString(),...Q&&Q.sdk&&{sdk:{name:Q.sdk.name,version:Q.sdk.version}},...!!J&&!!K&&{dsn:k7(K)}},U=KW1(A);return F3(C,[U])}function KW1(A){return[{type:"user_report"},A]}class bM extends FI{constructor(A){let Q={parentSpanIsAlwaysRootSpan:!0,...A},J=C2.SENTRY_SDK_SOURCE||SM();LM(Q,"browser",["browser"],J);super(Q);if(Q.sendClientReports&&C2.document)C2.document.addEventListener("visibilitychange",()=>{if(C2.document.visibilityState==="hidden")this._flushOutcomes()})}eventFromException(A,Q){return Ns(this._options.stackParser,A,Q,this._options.attachStacktrace)}eventFromMessage(A,Q="info",J){return Ls(this._options.stackParser,A,Q,J,this._options.attachStacktrace)}captureUserFeedback(A){if(!this._isEnabled()){R3&&m0.warn("SDK not enabled, will not capture user feedback.");return}let Q=Fs(A,{metadata:this.getSdkMetadata(),dsn:this.getDsn(),tunnel:this.getOptions().tunnel});this.sendEnvelope(Q)}_prepareEvent(A,Q,J){return A.platform=A.platform||"javascript",super._prepareEvent(A,Q,J)}}var Rs=typeof __SENTRY_DEBUG__==="undefined"||__SENTRY_DEBUG__;var j8=OA;var CW1=1000,zs,fM,pM;function uM(A){V6("dom",A),M6("dom",YW1)}function YW1(){if(!j8.document)return;let A=_8.bind(null,"dom"),Q=Ds(A,!0);j8.document.addEventListener("click",Q,!1),j8.document.addEventListener("keypress",Q,!1),["EventTarget","Node"].forEach((J)=>{let C=j8[J],U=C&&C.prototype;if(!U||!U.hasOwnProperty||!U.hasOwnProperty("addEventListener"))return;T8(U,"addEventListener",function(Y){return function(Z,X,E){if(Z==="click"||Z=="keypress")try{let H=this.__sentry_instrumentation_handlers__=this.__sentry_instrumentation_handlers__||{},$=H[Z]=H[Z]||{refCount:0};if(!$.handler){let I=Ds(A);$.handler=I,Y.call(this,Z,I,E)}$.refCount++}catch(H){}return Y.call(this,Z,X,E)}}),T8(U,"removeEventListener",function(Y){return function(Z,X,E){if(Z==="click"||Z=="keypress")try{let H=this.__sentry_instrumentation_handlers__||{},$=H[Z];if($){if($.refCount--,$.refCount<=0)Y.call(this,Z,$.handler,E),$.handler=void 0,delete H[Z];if(Object.keys(H).length===0)delete this.__sentry_instrumentation_handlers__}}catch(H){}return Y.call(this,Z,X,E)}})})}function UW1(A){if(A.type!==fM)return!1;try{if(!A.target||A.target._sentryId!==pM)return!1}catch(Q){}return!0}function ZW1(A,Q){if(A!=="keypress")return!1;if(!Q||!Q.tagName)return!0;if(Q.tagName==="INPUT"||Q.tagName==="TEXTAREA"||Q.isContentEditable)return!1;return!0}function Ds(A,Q=!1){return(J)=>{if(!J||J._sentryCaptured)return;let K=BW1(J);if(ZW1(J.type,K))return;if(P6(J,"_sentryCaptured",!0),K&&!K._sentryId)P6(K,"_sentryId",k8());let C=J.type==="keypress"?"input":J.type;if(!UW1(J))A({event:J,name:C,global:Q}),fM=J.type,pM=K?K._sentryId:void 0;clearTimeout(zs),zs=j8.setTimeout(()=>{pM=void 0,fM=void 0},CW1)}}function BW1(A){try{return A.target}catch(Q){return null}}var PI;function tB(A){V6("history",A),M6("history",XW1)}function XW1(){if(!jM())return;let A=j8.onpopstate;j8.onpopstate=function(...J){let K=j8.location.href,C=PI;if(PI=K,_8("history",{from:C,to:K}),A)try{return A.apply(this,J)}catch(Y){}};function Q(J){return function(...K){let C=K.length>2?K[2]:void 0;if(C){let U=PI,Y=String(C);PI=Y,_8("history",{from:U,to:Y})}return J.apply(this,K)}}T8(j8.history,"pushState",Q),T8(j8.history,"replaceState",Q)}var _I={};function mM(A){let Q=_I[A];if(Q)return Q;let J=j8[A];if(rB(J))return _I[A]=J.bind(j8);let K=j8.document;if(K&&typeof K.createElement==="function")try{let C=K.createElement("iframe");C.hidden=!0,K.head.appendChild(C);let U=C.contentWindow;if(U&&U[A])J=U[A];K.head.removeChild(C)}catch(C){Rs&&m0.warn(`Could not create sandbox iframe for ${A} check, bailing to window.${A}: `,C)}if(!J)return J;return _I[A]=J.bind(j8)}function TI(A){_I[A]=void 0}var vJ="__sentry_xhr_v3__";function cM(A){V6("xhr",A),M6("xhr",EW1)}function EW1(){if(!j8.XMLHttpRequest)return;let A=XMLHttpRequest.prototype;A.open=new Proxy(A.open,{apply(Q,J,K){let C=new Error,U=a6()*1000,Y=w6(K[0])?K[0].toUpperCase():void 0,Z=$W1(K[1]);if(!Y||!Z)return Q.apply(J,K);if(J[vJ]={method:Y,url:Z,request_headers:{}},Y==="POST"&&Z.match(/sentry_key/))J.__sentry_own_request__=!0;let X=()=>{let E=J[vJ];if(!E)return;if(J.readyState===4){try{E.status_code=J.status}catch($){}let H={endTimestamp:a6()*1000,startTimestamp:U,xhr:J,virtualError:C};_8("xhr",H)}};if("onreadystatechange"in J&&typeof J.onreadystatechange==="function")J.onreadystatechange=new Proxy(J.onreadystatechange,{apply(E,H,$){return X(),E.apply(H,$)}});else J.addEventListener("readystatechange",X);return J.setRequestHeader=new Proxy(J.setRequestHeader,{apply(E,H,$){let[I,N]=$,F=H[vJ];if(F&&w6(I)&&w6(N))F.request_headers[I.toLowerCase()]=N;return E.apply(H,$)}}),Q.apply(J,K)}}),A.send=new Proxy(A.send,{apply(Q,J,K){let C=J[vJ];if(!C)return Q.apply(J,K);if(K[0]!==void 0)C.body=K[0];let U={startTimestamp:a6()*1000,xhr:J};return _8("xhr",U),Q.apply(J,K)}})}function $W1(A){if(w6(A))return A;try{return A.toString()}catch(Q){}return}function Vs(A,Q=mM("fetch")){let J=0,K=0;function C(U){let Y=U.body.length;J+=Y,K++;let Z={body:U.body,method:"POST",referrerPolicy:"origin",headers:A.headers,keepalive:J<=60000&&K<15,...A.fetchOptions};if(!Q)return TI("fetch"),x4("No fetch implementation available");try{return Q(A.url,Z).then((X)=>{return J-=Y,K--,{statusCode:X.status,headers:{"x-sentry-rate-limits":X.headers.get("X-Sentry-Rate-Limits"),"retry-after":X.headers.get("Retry-After")}}})}catch(X){return TI("fetch"),J-=Y,K--,x4(X)}}return NM(A,C)}var HW1=30;var GW1=50;function dM(A,Q,J,K){let C={filename:A,function:Q===""?M7:Q,in_app:!0};if(J!==void 0)C.lineno=J;if(K!==void 0)C.colno=K;return C}var WW1=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,IW1=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,qW1=/\((\S*)(?::(\d+))(?::(\d+))\)/,OW1=(A)=>{let Q=WW1.exec(A);if(Q){let[,K,C,U]=Q;return dM(K,M7,+C,+U)}let J=IW1.exec(A);if(J){if(J[2]&&J[2].indexOf("eval")===0){let Y=qW1.exec(J[2]);if(Y)J[2]=Y[1],J[3]=Y[2],J[4]=Y[3]}let[C,U]=ws(J[1]||M7,J[2]);return dM(U,C,J[3]?+J[3]:void 0,J[4]?+J[4]:void 0)}return},NW1=[HW1,OW1],LW1=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,FW1=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,RW1=(A)=>{let Q=LW1.exec(A);if(Q){if(Q[3]&&Q[3].indexOf(" > eval")>-1){let U=FW1.exec(Q[3]);if(U)Q[1]=Q[1]||"eval",Q[3]=U[1],Q[4]=U[2],Q[5]=""}let K=Q[3],C=Q[1]||M7;return[C,K]=ws(C,K),dM(K,C,Q[4]?+Q[4]:void 0,Q[5]?+Q[5]:void 0)}return},zW1=[GW1,RW1];var DW1=[NW1,zW1],Ms=tW(...DW1),ws=(A,Q)=>{let J=A.indexOf("safari-extension")!==-1,K=A.indexOf("safari-web-extension")!==-1;return J||K?[A.indexOf("@")!==-1?A.split("@")[0]:M7,J?`safari-extension:${Q}`:`safari-web-extension:${Q}`]:[A,Q]};var kI=1024,VW1="Breadcrumbs",MW1=(A={})=>{let Q={console:!0,dom:!0,fetch:!0,history:!0,sentry:!0,xhr:!0,...A};return{name:VW1,setup(J){if(Q.console)VM(_W1(J));if(Q.dom)uM(PW1(J,Q.dom));if(Q.xhr)cM(TW1(J));if(Q.fetch)kM(kW1(J));if(Q.history)tB(SW1(J));if(Q.sentry)J.on("beforeSendEvent",wW1(J))}}},Ps=S8(MW1);function wW1(A){return function Q(J){if(b2()!==A)return;S7({category:`sentry.${J.type==="transaction"?"transaction":"event"}`,event_id:J.event_id,level:J.level,message:y5(J)},{event:J})}}function PW1(A,Q){return function J(K){if(b2()!==A)return;let C,U,Y=typeof Q==="object"?Q.serializeAttribute:void 0,Z=typeof Q==="object"&&typeof Q.maxStringLength==="number"?Q.maxStringLength:void 0;if(Z&&Z>kI)R3&&m0.warn(`\`dom.maxStringLength\` cannot exceed ${kI}, but a value of ${Z} was configured. Sentry will use ${kI} instead.`),Z=kI;if(typeof Y==="string")Y=[Y];try{let E=K.event,H=jW1(E)?E.target:E;C=nB(H,{keyAttrs:Y,maxStringLength:Z}),U=nV(H)}catch(E){C=""}if(C.length===0)return;let X={category:`ui.${K.name}`,message:C};if(U)X.data={"ui.component_name":U};S7(X,{event:K.event,name:K.name,global:K.global})}}function _W1(A){return function Q(J){if(b2()!==A)return;let K={category:"console",data:{arguments:J.args,logger:"console"},level:MM(J.level),message:KI(J.args," ")};if(J.level==="assert")if(J.args[0]===!1)K.message=`Assertion failed: ${KI(J.args.slice(1)," ")||"console.assert"}`,K.data.arguments=J.args.slice(1);else return;S7(K,{input:J.args,level:J.level})}}function TW1(A){return function Q(J){if(b2()!==A)return;let{startTimestamp:K,endTimestamp:C}=J,U=J.xhr[vJ];if(!K||!C||!U)return;let{method:Y,url:Z,status_code:X,body:E}=U,H={method:Y,url:Z,status_code:X},$={xhr:J.xhr,input:E,startTimestamp:K,endTimestamp:C},I=zI(X);S7({category:"xhr",data:H,type:"http",level:I},$)}}function kW1(A){return function Q(J){if(b2()!==A)return;let{startTimestamp:K,endTimestamp:C}=J;if(!C)return;if(J.fetchData.url.match(/sentry_key/)&&J.fetchData.method==="POST")return;if(J.error){let U=J.fetchData,Y={data:J.error,input:J.args,startTimestamp:K,endTimestamp:C};S7({category:"fetch",data:U,level:"error",type:"http"},Y)}else{let U=J.response,Y={...J.fetchData,status_code:U&&U.status},Z={input:J.args,response:U,startTimestamp:K,endTimestamp:C},X=zI(Y.status_code);S7({category:"fetch",data:Y,type:"http",level:X},Z)}}}function SW1(A){return function Q(J){if(b2()!==A)return;let{from:K,to:C}=J,U=aB(C2.location.href),Y=K?aB(K):void 0,Z=aB(C);if(!Y||!Y.path)Y=U;if(U.protocol===Z.protocol&&U.host===Z.host)C=Z.relative;if(U.protocol===Y.protocol&&U.host===Y.host)K=Y.relative;S7({category:"navigation",data:{from:K,to:C}})}}function jW1(A){return!!A&&!!A.target}var vW1=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","BroadcastChannel","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","SharedWorker","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"],xW1="BrowserApiErrors",yW1=(A={})=>{let Q={XMLHttpRequest:!0,eventTarget:!0,requestAnimationFrame:!0,setInterval:!0,setTimeout:!0,...A};return{name:xW1,setupOnce(){if(Q.setTimeout)T8(C2,"setTimeout",_s);if(Q.setInterval)T8(C2,"setInterval",_s);if(Q.requestAnimationFrame)T8(C2,"requestAnimationFrame",hW1);if(Q.XMLHttpRequest&&"XMLHttpRequest"in C2)T8(XMLHttpRequest.prototype,"send",gW1);let J=Q.eventTarget;if(J)(Array.isArray(J)?J:vW1).forEach(bW1)}}},Ts=S8(yW1);function _s(A){return function(...Q){let J=Q[0];return Q[0]=jJ(J,{mechanism:{data:{function:t9(A)},handled:!1,type:"instrument"}}),A.apply(this,Q)}}function hW1(A){return function(Q){return A.apply(this,[jJ(Q,{mechanism:{data:{function:"requestAnimationFrame",handler:t9(A)},handled:!1,type:"instrument"}})])}}function gW1(A){return function(...Q){let J=this;return["onload","onerror","onprogress","onreadystatechange"].forEach((C)=>{if(C in J&&typeof J[C]==="function")T8(J,C,function(U){let Y={mechanism:{data:{function:C,handler:t9(U)},handled:!1,type:"instrument"}},Z=SJ(U);if(Z)Y.mechanism.data.handler=t9(Z);return jJ(U,Y)})}),A.apply(this,Q)}}function bW1(A){let J=C2[A],K=J&&J.prototype;if(!K||!K.hasOwnProperty||!K.hasOwnProperty("addEventListener"))return;T8(K,"addEventListener",function(C){return function(U,Y,Z){try{if(fW1(Y))Y.handleEvent=jJ(Y.handleEvent,{mechanism:{data:{function:"handleEvent",handler:t9(Y),target:A},handled:!1,type:"instrument"}})}catch(X){}return C.apply(this,[U,jJ(Y,{mechanism:{data:{function:"addEventListener",handler:t9(Y),target:A},handled:!1,type:"instrument"}}),Z])}}),T8(K,"removeEventListener",function(C){return function(U,Y,Z){try{let X=Y.__sentry_wrapped__;if(X)C.call(this,U,X,Z)}catch(X){}return C.call(this,U,Y,Z)}})}function fW1(A){return typeof A.handleEvent==="function"}var ks=S8(()=>{return{name:"BrowserSession",setupOnce(){if(typeof C2.document==="undefined"){R3&&m0.warn("Using the `browserSessionIntegration` in non-browser environments is not supported.");return}NI({ignoreDuration:!0}),LI(),tB(({from:A,to:Q})=>{if(A!==void 0&&A!==Q)NI({ignoreDuration:!0}),LI()})}}});var pW1="GlobalHandlers",uW1=(A={})=>{let Q={onerror:!0,onunhandledrejection:!0,...A};return{name:pW1,setupOnce(){Error.stackTraceLimit=50},setup(J){if(Q.onerror)mW1(J),Ss("onerror");if(Q.onunhandledrejection)cW1(J),Ss("onunhandledrejection")}}},js=S8(uW1);function mW1(A){gV((Q)=>{let{stackParser:J,attachStacktrace:K}=vs();if(b2()!==A||xM())return;let{msg:C,url:U,line:Y,column:Z,error:X}=Q,E=nW1(wI(J,X||C,void 0,K,!1),U,Y,Z);E.level="error",OI(E,{originalException:X,mechanism:{handled:!1,type:"onerror"}})})}function cW1(A){fV((Q)=>{let{stackParser:J,attachStacktrace:K}=vs();if(b2()!==A||xM())return;let C=dW1(Q),U=TJ(C)?lW1(C):wI(J,C,void 0,K,!0);U.level="error",OI(U,{originalException:C,mechanism:{handled:!1,type:"onunhandledrejection"}})})}function dW1(A){if(TJ(A))return A;try{if("reason"in A)return A.reason;if("detail"in A&&"reason"in A.detail)return A.detail.reason}catch(Q){}return A}function lW1(A){return{exception:{values:[{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(A)}`}]}}}function nW1(A,Q,J,K){let C=A.exception=A.exception||{},U=C.values=C.values||[],Y=U[0]=U[0]||{},Z=Y.stacktrace=Y.stacktrace||{},X=Z.frames=Z.frames||[],E=K,H=J,$=w6(Q)&&Q.length>0?Q:lV();if(X.length===0)X.push({colno:E,filename:$,function:M7,in_app:!0,lineno:H});return A}function Ss(A){R3&&m0.log(`Global Handler attached: ${A}`)}function vs(){let A=b2();return A&&A.getOptions()||{stackParser:()=>[],attachStacktrace:!1}}var xs=S8(()=>{return{name:"HttpContext",preprocessEvent(A){if(!C2.navigator&&!C2.location&&!C2.document)return;let Q=A.request&&A.request.url||C2.location&&C2.location.href,{referrer:J}=C2.document||{},{userAgent:K}=C2.navigator||{},C={...A.request&&A.request.headers,...J&&{Referer:J},...K&&{"User-Agent":K}},U={...A.request,...Q&&{url:Q},headers:C};A.request=U}}});var sW1="cause",oW1=5,iW1="LinkedErrors",aW1=(A={})=>{let Q=A.limit||oW1,J=A.key||sW1;return{name:iW1,preprocessEvent(K,C,U){let Y=U.getOptions();DM(MI,Y.stackParser,Y.maxValueLength,J,Q,K,C)}}},ys=S8(aW1);function hs(A){let Q=[RM(),FM(),Ts(),Ps(),js(),ys(),wM(),xs()];if(A.autoSessionTracking!==!1)Q.push(ks());return Q}function rW1(A={}){let Q={defaultIntegrations:hs(A),release:typeof __SENTRY_RELEASE__==="string"?__SENTRY_RELEASE__:C2.SENTRY_RELEASE&&C2.SENTRY_RELEASE.id?C2.SENTRY_RELEASE.id:void 0,autoSessionTracking:!0,sendClientReports:!0};if(A.defaultIntegrations==null)delete A.defaultIntegrations;return{...Q,...A}}function tW1(){let A=typeof C2.window!=="undefined"&&C2;if(!A)return!1;let Q=A.chrome?"chrome":"browser",J=A[Q],K=J&&J.runtime&&J.runtime.id,C=C2.location&&C2.location.href||"",U=["chrome-extension:","moz-extension:","ms-browser-extension:","safari-web-extension:"],Y=!!K&&C2===C2.top&&U.some((X)=>C.startsWith(`${X}//`)),Z=typeof A.nw!=="undefined";return!!K&&!Y&&!Z}function lM(A={}){let Q=rW1(A);if(!Q.skipBrowserExtensionCheck&&tW1()){i6(()=>{console.error("[Sentry] You cannot run Sentry this way in a browser extension, check: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/")});return}if(R3){if(!DI())m0.warn("No Fetch API detected. The Sentry SDK requires a Fetch API compatible environment to send events. Please add a Fetch API polyfill.")}let J={...Q,stackParser:yV(Q.stackParser||Ms),integrations:WM(Q),transport:Q.transport||Vs};return OM(bM,J)}window.buffer=QA;window.LazyLoad=new Ko.default;if(d0.apis.useSentry)lM({dsn:d0.apis.sentryURL,tracesSampleRate:0.01});document.documentElement.dataset.theme="default";var xI,v7,jB=()=>xI,o00=()=>v7,qd=()=>v7!==void 0,Od=(A,Q)=>{if(v7===void 0)throw new Error("FFL worker told to make icon, but it wasn't initialized");return new Promise((J,K)=>{Co({type:"MakeIcon",data:A,view:Q}).then((C)=>J(C)).catch((C)=>K(C))})},Co;if(d0.renderer.useRendererServer===!1){if(Jo=y0.modal("Notice","Mii Creator is loading assets, please wait..."),xI=(await Promise.resolve().then(() => (Qo(),Ao))).default.Module,console.log(xI),console.log("We've got FFL!"),await Gc(),await Nc(d0.renderer.fflResourcePath,xI),window.Worker)if(window.OffscreenCanvas){let Q=document.createElement("canvas").transferControlToOffscreen();v7=new Worker("./dist/worker.js",{type:"module"}),Co=(J)=>{return new Promise((K,C)=>{let U=Math.random().toString(36).substring(7);function Y(Z){let{id:X,result:E,error:H}=Z.data;if(X===U)v7.removeEventListener("message",Y),H?C(H):K(E)}v7.addEventListener("message",Y),v7.postMessage({id:U,...J})})},v7.postMessage({type:"Init",resourcePath:d0.renderer.fflResourcePath,offscreenCanvas:Q},[Q]),await new Promise((J)=>{v7.onmessage=(K)=>{if(K.data.ready)J()}})}else y0.modal("Notice","Your browser doesn't support OffscreenCanvas, so Mii Creator may experience lag.","body",...x3);else y0.modal("Notice","Your browser doesn't support Web Workers, so Mii Creator may experience lag.","body",...x3);console.log("Ready!"),Bk(Jo)}var Jo;NW.getString("languages.en_US");Qn();export{Od as getFFLWorkerMakeIcon,qd as getFFLWorkerExists,o00 as getFFLWorker,jB as getFFL}; +var __create = Object.create; +var __getProtoOf = Object.getPrototypeOf; +var __defProp = Object.defineProperty; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __toESM = (mod2, isNodeMode, target) => { + target = mod2 != null ? __create(__getProtoOf(mod2)) : {}; + const to = isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target; + for (let key2 of __getOwnPropNames(mod2)) + if (!__hasOwnProp.call(to, key2)) + __defProp(to, key2, { + get: () => mod2[key2], + enumerable: true + }); + return to; +}; +var __moduleCache = /* @__PURE__ */ new WeakMap; +var __toCommonJS = (from) => { + var entry = __moduleCache.get(from), desc; + if (entry) + return entry; + entry = __defProp({}, "__esModule", { value: true }); + if (from && typeof from === "object" || typeof from === "function") + __getOwnPropNames(from).map((key2) => !__hasOwnProp.call(entry, key2) && __defProp(entry, key2, { + get: () => from[key2], + enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable + })); + __moduleCache.set(from, entry); + return entry; +}; +var __commonJS = (cb, mod2) => () => (mod2 || cb((mod2 = { exports: {} }).exports, mod2), mod2.exports); +var __export = (target, all) => { + for (var name2 in all) + __defProp(target, name2, { + get: all[name2], + enumerable: true, + configurable: true, + set: (newValue) => all[name2] = () => newValue + }); +}; +var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res); +var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] +}) : x)(function(x) { + if (typeof require !== "undefined") + return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); +}); + +// node_modules/localforage/dist/localforage.js +var require_localforage = __commonJS((exports2, module2) => { + /*! + localForage -- Offline Storage, Improved + Version 1.10.0 + https://localforage.github.io/localForage + (c) 2013-2017 Mozilla, Apache License 2.0 + */ + (function(f) { + if (typeof exports2 === "object" && typeof module2 !== "undefined") { + module2.exports = f(); + } else if (typeof define === "function" && define.amd) { + define([], f); + } else { + var g; + if (typeof window !== "undefined") { + g = window; + } else if (typeof global !== "undefined") { + g = global; + } else if (typeof self !== "undefined") { + g = self; + } else { + g = this; + } + g.localforage = f(); + } + })(function() { + var define2, module3, exports3; + return function e(t, n, r) { + function s(o2, u) { + if (!n[o2]) { + if (!t[o2]) { + var a = __require; + if (!u && a) + return a(o2, true); + if (i) + return i(o2, true); + var f = new Error("Cannot find module '" + o2 + "'"); + throw f.code = "MODULE_NOT_FOUND", f; + } + var l = n[o2] = { exports: {} }; + t[o2][0].call(l.exports, function(e) { + var n2 = t[o2][1][e]; + return s(n2 ? n2 : e); + }, l, l.exports, e, t, n, r); + } + return n[o2].exports; + } + var i = __require; + for (var o = 0;o < r.length; o++) + s(r[o]); + return s; + }({ 1: [function(_dereq_, module4, exports4) { + (function(global2) { + var Mutation = global2.MutationObserver || global2.WebKitMutationObserver; + var scheduleDrain; + { + if (Mutation) { + var called = 0; + var observer = new Mutation(nextTick); + var element = global2.document.createTextNode(""); + observer.observe(element, { + characterData: true + }); + scheduleDrain = function() { + element.data = called = ++called % 2; + }; + } else if (!global2.setImmediate && typeof global2.MessageChannel !== "undefined") { + var channel = new global2.MessageChannel; + channel.port1.onmessage = nextTick; + scheduleDrain = function() { + channel.port2.postMessage(0); + }; + } else if ("document" in global2 && "onreadystatechange" in global2.document.createElement("script")) { + scheduleDrain = function() { + var scriptEl = global2.document.createElement("script"); + scriptEl.onreadystatechange = function() { + nextTick(); + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + global2.document.documentElement.appendChild(scriptEl); + }; + } else { + scheduleDrain = function() { + setTimeout(nextTick, 0); + }; + } + } + var draining; + var queue = []; + function nextTick() { + draining = true; + var i, oldQueue; + var len = queue.length; + while (len) { + oldQueue = queue; + queue = []; + i = -1; + while (++i < len) { + oldQueue[i](); + } + len = queue.length; + } + draining = false; + } + module4.exports = immediate; + function immediate(task) { + if (queue.push(task) === 1 && !draining) { + scheduleDrain(); + } + } + }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); + }, {}], 2: [function(_dereq_, module4, exports4) { + var immediate = _dereq_(1); + function INTERNAL() { + } + var handlers = {}; + var REJECTED = ["REJECTED"]; + var FULFILLED = ["FULFILLED"]; + var PENDING = ["PENDING"]; + module4.exports = Promise2; + function Promise2(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("resolver must be a function"); + } + this.state = PENDING; + this.queue = []; + this.outcome = undefined; + if (resolver !== INTERNAL) { + safelyResolveThenable(this, resolver); + } + } + Promise2.prototype["catch"] = function(onRejected) { + return this.then(null, onRejected); + }; + Promise2.prototype.then = function(onFulfilled, onRejected) { + if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) { + return this; + } + var promise = new this.constructor(INTERNAL); + if (this.state !== PENDING) { + var resolver = this.state === FULFILLED ? onFulfilled : onRejected; + unwrap(promise, resolver, this.outcome); + } else { + this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); + } + return promise; + }; + function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === "function") { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === "function") { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } + } + QueueItem.prototype.callFulfilled = function(value2) { + handlers.resolve(this.promise, value2); + }; + QueueItem.prototype.otherCallFulfilled = function(value2) { + unwrap(this.promise, this.onFulfilled, value2); + }; + QueueItem.prototype.callRejected = function(value2) { + handlers.reject(this.promise, value2); + }; + QueueItem.prototype.otherCallRejected = function(value2) { + unwrap(this.promise, this.onRejected, value2); + }; + function unwrap(promise, func, value2) { + immediate(function() { + var returnValue; + try { + returnValue = func(value2); + } catch (e) { + return handlers.reject(promise, e); + } + if (returnValue === promise) { + handlers.reject(promise, new TypeError("Cannot resolve promise with itself")); + } else { + handlers.resolve(promise, returnValue); + } + }); + } + handlers.resolve = function(self2, value2) { + var result = tryCatch(getThen, value2); + if (result.status === "error") { + return handlers.reject(self2, result.value); + } + var thenable = result.value; + if (thenable) { + safelyResolveThenable(self2, thenable); + } else { + self2.state = FULFILLED; + self2.outcome = value2; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callFulfilled(value2); + } + } + return self2; + }; + handlers.reject = function(self2, error) { + self2.state = REJECTED; + self2.outcome = error; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callRejected(error); + } + return self2; + }; + function getThen(obj) { + var then = obj && obj.then; + if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") { + return function appyThen() { + then.apply(obj, arguments); + }; + } + } + function safelyResolveThenable(self2, thenable) { + var called = false; + function onError(value2) { + if (called) { + return; + } + called = true; + handlers.reject(self2, value2); + } + function onSuccess(value2) { + if (called) { + return; + } + called = true; + handlers.resolve(self2, value2); + } + function tryToUnwrap() { + thenable(onSuccess, onError); + } + var result = tryCatch(tryToUnwrap); + if (result.status === "error") { + onError(result.value); + } + } + function tryCatch(func, value2) { + var out = {}; + try { + out.value = func(value2); + out.status = "success"; + } catch (e) { + out.status = "error"; + out.value = e; + } + return out; + } + Promise2.resolve = resolve; + function resolve(value2) { + if (value2 instanceof this) { + return value2; + } + return handlers.resolve(new this(INTERNAL), value2); + } + Promise2.reject = reject2; + function reject2(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); + } + Promise2.all = all; + function all(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var values2 = new Array(len); + var resolved = 0; + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + allResolver(iterable[i], i); + } + return promise; + function allResolver(value2, i2) { + self2.resolve(value2).then(resolveFromAll, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values2[i2] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values2); + } + } + } + } + Promise2.race = race; + function race(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + resolver(iterable[i]); + } + return promise; + function resolver(value2) { + self2.resolve(value2).then(function(response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } + } + }, { "1": 1 }], 3: [function(_dereq_, module4, exports4) { + (function(global2) { + if (typeof global2.Promise !== "function") { + global2.Promise = _dereq_(2); + } + }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); + }, { "2": 2 }], 4: [function(_dereq_, module4, exports4) { + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) { + return typeof obj; + } : function(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function getIDB() { + try { + if (typeof indexedDB !== "undefined") { + return indexedDB; + } + if (typeof webkitIndexedDB !== "undefined") { + return webkitIndexedDB; + } + if (typeof mozIndexedDB !== "undefined") { + return mozIndexedDB; + } + if (typeof OIndexedDB !== "undefined") { + return OIndexedDB; + } + if (typeof msIndexedDB !== "undefined") { + return msIndexedDB; + } + } catch (e) { + return; + } + } + var idb = getIDB(); + function isIndexedDBValid() { + try { + if (!idb || !idb.open) { + return false; + } + var isSafari2 = typeof openDatabase !== "undefined" && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform); + var hasFetch = typeof fetch === "function" && fetch.toString().indexOf("[native code") !== -1; + return (!isSafari2 || hasFetch) && typeof indexedDB !== "undefined" && typeof IDBKeyRange !== "undefined"; + } catch (e) { + return false; + } + } + function createBlob(parts, properties) { + parts = parts || []; + properties = properties || {}; + try { + return new Blob(parts, properties); + } catch (e) { + if (e.name !== "TypeError") { + throw e; + } + var Builder = typeof BlobBuilder !== "undefined" ? BlobBuilder : typeof MSBlobBuilder !== "undefined" ? MSBlobBuilder : typeof MozBlobBuilder !== "undefined" ? MozBlobBuilder : WebKitBlobBuilder; + var builder = new Builder; + for (var i = 0;i < parts.length; i += 1) { + builder.append(parts[i]); + } + return builder.getBlob(properties.type); + } + } + if (typeof Promise === "undefined") { + _dereq_(3); + } + var Promise$1 = Promise; + function executeCallback(promise, callback) { + if (callback) { + promise.then(function(result) { + callback(null, result); + }, function(error) { + callback(error); + }); + } + } + function executeTwoCallbacks(promise, callback, errorCallback) { + if (typeof callback === "function") { + promise.then(callback); + } + if (typeof errorCallback === "function") { + promise["catch"](errorCallback); + } + } + function normalizeKey(key3) { + if (typeof key3 !== "string") { + console.warn(key3 + " used as a key, but it is not a string."); + key3 = String(key3); + } + return key3; + } + function getCallback() { + if (arguments.length && typeof arguments[arguments.length - 1] === "function") { + return arguments[arguments.length - 1]; + } + } + var DETECT_BLOB_SUPPORT_STORE = "local-forage-detect-blob-support"; + var supportsBlobs = undefined; + var dbContexts = {}; + var toString2 = Object.prototype.toString; + var READ_ONLY = "readonly"; + var READ_WRITE = "readwrite"; + function _binStringToArrayBuffer(bin) { + var length3 = bin.length; + var buf = new ArrayBuffer(length3); + var arr = new Uint8Array(buf); + for (var i = 0;i < length3; i++) { + arr[i] = bin.charCodeAt(i); + } + return buf; + } + function _checkBlobSupportWithoutCaching(idb2) { + return new Promise$1(function(resolve) { + var txn = idb2.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE); + var blob = createBlob([""]); + txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, "key"); + txn.onabort = function(e) { + e.preventDefault(); + e.stopPropagation(); + resolve(false); + }; + txn.oncomplete = function() { + var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); + var matchedEdge = navigator.userAgent.match(/Edge\//); + resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43); + }; + })["catch"](function() { + return false; + }); + } + function _checkBlobSupport(idb2) { + if (typeof supportsBlobs === "boolean") { + return Promise$1.resolve(supportsBlobs); + } + return _checkBlobSupportWithoutCaching(idb2).then(function(value2) { + supportsBlobs = value2; + return supportsBlobs; + }); + } + function _deferReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + var deferredOperation = {}; + deferredOperation.promise = new Promise$1(function(resolve, reject2) { + deferredOperation.resolve = resolve; + deferredOperation.reject = reject2; + }); + dbContext.deferredOperations.push(deferredOperation); + if (!dbContext.dbReady) { + dbContext.dbReady = deferredOperation.promise; + } else { + dbContext.dbReady = dbContext.dbReady.then(function() { + return deferredOperation.promise; + }); + } + } + function _advanceReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + var deferredOperation = dbContext.deferredOperations.pop(); + if (deferredOperation) { + deferredOperation.resolve(); + return deferredOperation.promise; + } + } + function _rejectReadiness(dbInfo, err) { + var dbContext = dbContexts[dbInfo.name]; + var deferredOperation = dbContext.deferredOperations.pop(); + if (deferredOperation) { + deferredOperation.reject(err); + return deferredOperation.promise; + } + } + function _getConnection(dbInfo, upgradeNeeded) { + return new Promise$1(function(resolve, reject2) { + dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext(); + if (dbInfo.db) { + if (upgradeNeeded) { + _deferReadiness(dbInfo); + dbInfo.db.close(); + } else { + return resolve(dbInfo.db); + } + } + var dbArgs = [dbInfo.name]; + if (upgradeNeeded) { + dbArgs.push(dbInfo.version); + } + var openreq = idb.open.apply(idb, dbArgs); + if (upgradeNeeded) { + openreq.onupgradeneeded = function(e) { + var db = openreq.result; + try { + db.createObjectStore(dbInfo.storeName); + if (e.oldVersion <= 1) { + db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); + } + } catch (ex) { + if (ex.name === "ConstraintError") { + console.warn('The database "' + dbInfo.name + '"' + " has been upgraded from version " + e.oldVersion + " to version " + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); + } else { + throw ex; + } + } + }; + } + openreq.onerror = function(e) { + e.preventDefault(); + reject2(openreq.error); + }; + openreq.onsuccess = function() { + var db = openreq.result; + db.onversionchange = function(e) { + e.target.close(); + }; + resolve(db); + _advanceReadiness(dbInfo); + }; + }); + } + function _getOriginalConnection(dbInfo) { + return _getConnection(dbInfo, false); + } + function _getUpgradedConnection(dbInfo) { + return _getConnection(dbInfo, true); + } + function _isUpgradeNeeded(dbInfo, defaultVersion) { + if (!dbInfo.db) { + return true; + } + var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); + var isDowngrade = dbInfo.version < dbInfo.db.version; + var isUpgrade = dbInfo.version > dbInfo.db.version; + if (isDowngrade) { + if (dbInfo.version !== defaultVersion) { + console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + " to version " + dbInfo.version + "."); + } + dbInfo.version = dbInfo.db.version; + } + if (isUpgrade || isNewStore) { + if (isNewStore) { + var incVersion = dbInfo.db.version + 1; + if (incVersion > dbInfo.version) { + dbInfo.version = incVersion; + } + } + return true; + } + return false; + } + function _encodeBlob(blob) { + return new Promise$1(function(resolve, reject2) { + var reader = new FileReader; + reader.onerror = reject2; + reader.onloadend = function(e) { + var base64 = btoa(e.target.result || ""); + resolve({ + __local_forage_encoded_blob: true, + data: base64, + type: blob.type + }); + }; + reader.readAsBinaryString(blob); + }); + } + function _decodeBlob(encodedBlob) { + var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); + return createBlob([arrayBuff], { type: encodedBlob.type }); + } + function _isEncodedBlob(value2) { + return value2 && value2.__local_forage_encoded_blob; + } + function _fullyReady(callback) { + var self2 = this; + var promise = self2._initReady().then(function() { + var dbContext = dbContexts[self2._dbInfo.name]; + if (dbContext && dbContext.dbReady) { + return dbContext.dbReady; + } + }); + executeTwoCallbacks(promise, callback, callback); + return promise; + } + function _tryReconnect(dbInfo) { + _deferReadiness(dbInfo); + var dbContext = dbContexts[dbInfo.name]; + var forages = dbContext.forages; + for (var i = 0;i < forages.length; i++) { + var forage = forages[i]; + if (forage._dbInfo.db) { + forage._dbInfo.db.close(); + forage._dbInfo.db = null; + } + } + dbInfo.db = null; + return _getOriginalConnection(dbInfo).then(function(db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo)) { + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function(db) { + dbInfo.db = dbContext.db = db; + for (var i2 = 0;i2 < forages.length; i2++) { + forages[i2]._dbInfo.db = db; + } + })["catch"](function(err) { + _rejectReadiness(dbInfo, err); + throw err; + }); + } + function createTransaction(dbInfo, mode, callback, retries) { + if (retries === undefined) { + retries = 1; + } + try { + var tx = dbInfo.db.transaction(dbInfo.storeName, mode); + callback(null, tx); + } catch (err) { + if (retries > 0 && (!dbInfo.db || err.name === "InvalidStateError" || err.name === "NotFoundError")) { + return Promise$1.resolve().then(function() { + if (!dbInfo.db || err.name === "NotFoundError" && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) { + if (dbInfo.db) { + dbInfo.version = dbInfo.db.version + 1; + } + return _getUpgradedConnection(dbInfo); + } + }).then(function() { + return _tryReconnect(dbInfo).then(function() { + createTransaction(dbInfo, mode, callback, retries - 1); + }); + })["catch"](callback); + } + callback(err); + } + } + function createDbContext() { + return { + forages: [], + db: null, + dbReady: null, + deferredOperations: [] + }; + } + function _initStorage(options) { + var self2 = this; + var dbInfo = { + db: null + }; + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + var dbContext = dbContexts[dbInfo.name]; + if (!dbContext) { + dbContext = createDbContext(); + dbContexts[dbInfo.name] = dbContext; + } + dbContext.forages.push(self2); + if (!self2._initReady) { + self2._initReady = self2.ready; + self2.ready = _fullyReady; + } + var initPromises = []; + function ignoreErrors() { + return Promise$1.resolve(); + } + for (var j = 0;j < dbContext.forages.length; j++) { + var forage = dbContext.forages[j]; + if (forage !== self2) { + initPromises.push(forage._initReady()["catch"](ignoreErrors)); + } + } + var forages = dbContext.forages.slice(0); + return Promise$1.all(initPromises).then(function() { + dbInfo.db = dbContext.db; + return _getOriginalConnection(dbInfo); + }).then(function(db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo, self2._defaultConfig.version)) { + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function(db) { + dbInfo.db = dbContext.db = db; + self2._dbInfo = dbInfo; + for (var k = 0;k < forages.length; k++) { + var forage2 = forages[k]; + if (forage2 !== self2) { + forage2._dbInfo.db = dbInfo.db; + forage2._dbInfo.version = dbInfo.version; + } + } + }); + } + function getItem(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.get(key3); + req.onsuccess = function() { + var value2 = req.result; + if (value2 === undefined) { + value2 = null; + } + if (_isEncodedBlob(value2)) { + value2 = _decodeBlob(value2); + } + resolve(value2); + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function iterate(iterator, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.openCursor(); + var iterationNumber = 1; + req.onsuccess = function() { + var cursor = req.result; + if (cursor) { + var value2 = cursor.value; + if (_isEncodedBlob(value2)) { + value2 = _decodeBlob(value2); + } + var result = iterator(value2, cursor.key, iterationNumber++); + if (result !== undefined) { + resolve(result); + } else { + cursor["continue"](); + } + } else { + resolve(); + } + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function setItem(key3, value2, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + var dbInfo; + self2.ready().then(function() { + dbInfo = self2._dbInfo; + if (toString2.call(value2) === "[object Blob]") { + return _checkBlobSupport(dbInfo.db).then(function(blobSupport) { + if (blobSupport) { + return value2; + } + return _encodeBlob(value2); + }); + } + return value2; + }).then(function(value3) { + createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + if (value3 === null) { + value3 = undefined; + } + var req = store.put(value3, key3); + transaction.oncomplete = function() { + if (value3 === undefined) { + value3 = null; + } + resolve(value3); + }; + transaction.onabort = transaction.onerror = function() { + var err2 = req.error ? req.error : req.transaction.error; + reject2(err2); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function removeItem(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store["delete"](key3); + transaction.oncomplete = function() { + resolve(); + }; + transaction.onerror = function() { + reject2(req.error); + }; + transaction.onabort = function() { + var err2 = req.error ? req.error : req.transaction.error; + reject2(err2); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function clear(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.clear(); + transaction.oncomplete = function() { + resolve(); + }; + transaction.onabort = transaction.onerror = function() { + var err2 = req.error ? req.error : req.transaction.error; + reject2(err2); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function length2(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.count(); + req.onsuccess = function() { + resolve(req.result); + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function key2(n, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + if (n < 0) { + resolve(null); + return; + } + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var advanced = false; + var req = store.openKeyCursor(); + req.onsuccess = function() { + var cursor = req.result; + if (!cursor) { + resolve(null); + return; + } + if (n === 0) { + resolve(cursor.key); + } else { + if (!advanced) { + advanced = true; + cursor.advance(n); + } else { + resolve(cursor.key); + } + } + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function keys2(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.openKeyCursor(); + var keys3 = []; + req.onsuccess = function() { + var cursor = req.result; + if (!cursor) { + resolve(keys3); + return; + } + keys3.push(cursor.key); + cursor["continue"](); + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function dropInstance(options, callback) { + callback = getCallback.apply(this, arguments); + var currentConfig = this.config(); + options = typeof options !== "function" && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + var self2 = this; + var promise; + if (!options.name) { + promise = Promise$1.reject("Invalid arguments"); + } else { + var isCurrentDb = options.name === currentConfig.name && self2._dbInfo.db; + var dbPromise = isCurrentDb ? Promise$1.resolve(self2._dbInfo.db) : _getOriginalConnection(options).then(function(db) { + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + dbContext.db = db; + for (var i = 0;i < forages.length; i++) { + forages[i]._dbInfo.db = db; + } + return db; + }); + if (!options.storeName) { + promise = dbPromise.then(function(db) { + _deferReadiness(options); + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + db.close(); + for (var i = 0;i < forages.length; i++) { + var forage = forages[i]; + forage._dbInfo.db = null; + } + var dropDBPromise = new Promise$1(function(resolve, reject2) { + var req = idb.deleteDatabase(options.name); + req.onerror = function() { + var db2 = req.result; + if (db2) { + db2.close(); + } + reject2(req.error); + }; + req.onblocked = function() { + console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed'); + }; + req.onsuccess = function() { + var db2 = req.result; + if (db2) { + db2.close(); + } + resolve(db2); + }; + }); + return dropDBPromise.then(function(db2) { + dbContext.db = db2; + for (var i2 = 0;i2 < forages.length; i2++) { + var _forage = forages[i2]; + _advanceReadiness(_forage._dbInfo); + } + })["catch"](function(err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() { + }); + throw err; + }); + }); + } else { + promise = dbPromise.then(function(db) { + if (!db.objectStoreNames.contains(options.storeName)) { + return; + } + var newVersion = db.version + 1; + _deferReadiness(options); + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + db.close(); + for (var i = 0;i < forages.length; i++) { + var forage = forages[i]; + forage._dbInfo.db = null; + forage._dbInfo.version = newVersion; + } + var dropObjectPromise = new Promise$1(function(resolve, reject2) { + var req = idb.open(options.name, newVersion); + req.onerror = function(err) { + var db2 = req.result; + db2.close(); + reject2(err); + }; + req.onupgradeneeded = function() { + var db2 = req.result; + db2.deleteObjectStore(options.storeName); + }; + req.onsuccess = function() { + var db2 = req.result; + db2.close(); + resolve(db2); + }; + }); + return dropObjectPromise.then(function(db2) { + dbContext.db = db2; + for (var j = 0;j < forages.length; j++) { + var _forage2 = forages[j]; + _forage2._dbInfo.db = db2; + _advanceReadiness(_forage2._dbInfo); + } + })["catch"](function(err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() { + }); + throw err; + }); + }); + } + } + executeCallback(promise, callback); + return promise; + } + var asyncStorage = { + _driver: "asyncStorage", + _initStorage, + _support: isIndexedDBValid(), + iterate, + getItem, + setItem, + removeItem, + clear, + length: length2, + key: key2, + keys: keys2, + dropInstance + }; + function isWebSQLValid() { + return typeof openDatabase === "function"; + } + var BASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var BLOB_TYPE_PREFIX = "~~local_forage_type~"; + var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; + var SERIALIZED_MARKER = "__lfsc__:"; + var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; + var TYPE_ARRAYBUFFER = "arbf"; + var TYPE_BLOB = "blob"; + var TYPE_INT8ARRAY = "si08"; + var TYPE_UINT8ARRAY = "ui08"; + var TYPE_UINT8CLAMPEDARRAY = "uic8"; + var TYPE_INT16ARRAY = "si16"; + var TYPE_INT32ARRAY = "si32"; + var TYPE_UINT16ARRAY = "ur16"; + var TYPE_UINT32ARRAY = "ui32"; + var TYPE_FLOAT32ARRAY = "fl32"; + var TYPE_FLOAT64ARRAY = "fl64"; + var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; + var toString$1 = Object.prototype.toString; + function stringToBuffer(serializedString) { + var bufferLength = serializedString.length * 0.75; + var len = serializedString.length; + var i; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + if (serializedString[serializedString.length - 1] === "=") { + bufferLength--; + if (serializedString[serializedString.length - 2] === "=") { + bufferLength--; + } + } + var buffer = new ArrayBuffer(bufferLength); + var bytes = new Uint8Array(buffer); + for (i = 0;i < len; i += 4) { + encoded1 = BASE_CHARS.indexOf(serializedString[i]); + encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); + encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); + encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + return buffer; + } + function bufferToString(buffer) { + var bytes = new Uint8Array(buffer); + var base64String = ""; + var i; + for (i = 0;i < bytes.length; i += 3) { + base64String += BASE_CHARS[bytes[i] >> 2]; + base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; + base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; + base64String += BASE_CHARS[bytes[i + 2] & 63]; + } + if (bytes.length % 3 === 2) { + base64String = base64String.substring(0, base64String.length - 1) + "="; + } else if (bytes.length % 3 === 1) { + base64String = base64String.substring(0, base64String.length - 2) + "=="; + } + return base64String; + } + function serialize(value2, callback) { + var valueType = ""; + if (value2) { + valueType = toString$1.call(value2); + } + if (value2 && (valueType === "[object ArrayBuffer]" || value2.buffer && toString$1.call(value2.buffer) === "[object ArrayBuffer]")) { + var buffer; + var marker = SERIALIZED_MARKER; + if (value2 instanceof ArrayBuffer) { + buffer = value2; + marker += TYPE_ARRAYBUFFER; + } else { + buffer = value2.buffer; + if (valueType === "[object Int8Array]") { + marker += TYPE_INT8ARRAY; + } else if (valueType === "[object Uint8Array]") { + marker += TYPE_UINT8ARRAY; + } else if (valueType === "[object Uint8ClampedArray]") { + marker += TYPE_UINT8CLAMPEDARRAY; + } else if (valueType === "[object Int16Array]") { + marker += TYPE_INT16ARRAY; + } else if (valueType === "[object Uint16Array]") { + marker += TYPE_UINT16ARRAY; + } else if (valueType === "[object Int32Array]") { + marker += TYPE_INT32ARRAY; + } else if (valueType === "[object Uint32Array]") { + marker += TYPE_UINT32ARRAY; + } else if (valueType === "[object Float32Array]") { + marker += TYPE_FLOAT32ARRAY; + } else if (valueType === "[object Float64Array]") { + marker += TYPE_FLOAT64ARRAY; + } else { + callback(new Error("Failed to get type for BinaryArray")); + } + } + callback(marker + bufferToString(buffer)); + } else if (valueType === "[object Blob]") { + var fileReader = new FileReader; + fileReader.onload = function() { + var str = BLOB_TYPE_PREFIX + value2.type + "~" + bufferToString(this.result); + callback(SERIALIZED_MARKER + TYPE_BLOB + str); + }; + fileReader.readAsArrayBuffer(value2); + } else { + try { + callback(JSON.stringify(value2)); + } catch (e) { + console.error("Couldn't convert value into a JSON string: ", value2); + callback(null, e); + } + } + } + function deserialize(value2) { + if (value2.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { + return JSON.parse(value2); + } + var serializedString = value2.substring(TYPE_SERIALIZED_MARKER_LENGTH); + var type = value2.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); + var blobType; + if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { + var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); + blobType = matcher[1]; + serializedString = serializedString.substring(matcher[0].length); + } + var buffer = stringToBuffer(serializedString); + switch (type) { + case TYPE_ARRAYBUFFER: + return buffer; + case TYPE_BLOB: + return createBlob([buffer], { type: blobType }); + case TYPE_INT8ARRAY: + return new Int8Array(buffer); + case TYPE_UINT8ARRAY: + return new Uint8Array(buffer); + case TYPE_UINT8CLAMPEDARRAY: + return new Uint8ClampedArray(buffer); + case TYPE_INT16ARRAY: + return new Int16Array(buffer); + case TYPE_UINT16ARRAY: + return new Uint16Array(buffer); + case TYPE_INT32ARRAY: + return new Int32Array(buffer); + case TYPE_UINT32ARRAY: + return new Uint32Array(buffer); + case TYPE_FLOAT32ARRAY: + return new Float32Array(buffer); + case TYPE_FLOAT64ARRAY: + return new Float64Array(buffer); + default: + throw new Error("Unkown type: " + type); + } + } + var localforageSerializer = { + serialize, + deserialize, + stringToBuffer, + bufferToString + }; + function createDbTable(t, dbInfo, callback, errorCallback) { + t.executeSql("CREATE TABLE IF NOT EXISTS " + dbInfo.storeName + " " + "(id INTEGER PRIMARY KEY, key unique, value)", [], callback, errorCallback); + } + function _initStorage$1(options) { + var self2 = this; + var dbInfo = { + db: null + }; + if (options) { + for (var i in options) { + dbInfo[i] = typeof options[i] !== "string" ? options[i].toString() : options[i]; + } + } + var dbInfoPromise = new Promise$1(function(resolve, reject2) { + try { + dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); + } catch (e) { + return reject2(e); + } + dbInfo.db.transaction(function(t) { + createDbTable(t, dbInfo, function() { + self2._dbInfo = dbInfo; + resolve(); + }, function(t2, error) { + reject2(error); + }); + }, reject2); + }); + dbInfo.serializer = localforageSerializer; + return dbInfoPromise; + } + function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) { + t.executeSql(sqlStatement, args, callback, function(t2, error) { + if (error.code === error.SYNTAX_ERR) { + t2.executeSql("SELECT name FROM sqlite_master " + "WHERE type='table' AND name = ?", [dbInfo.storeName], function(t3, results) { + if (!results.rows.length) { + createDbTable(t3, dbInfo, function() { + t3.executeSql(sqlStatement, args, callback, errorCallback); + }, errorCallback); + } else { + errorCallback(t3, error); + } + }, errorCallback); + } else { + errorCallback(t2, error); + } + }, errorCallback); + } + function getItem$1(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT * FROM " + dbInfo.storeName + " WHERE key = ? LIMIT 1", [key3], function(t2, results) { + var result = results.rows.length ? results.rows.item(0).value : null; + if (result) { + result = dbInfo.serializer.deserialize(result); + } + resolve(result); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function iterate$1(iterator, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT * FROM " + dbInfo.storeName, [], function(t2, results) { + var rows = results.rows; + var length3 = rows.length; + for (var i = 0;i < length3; i++) { + var item = rows.item(i); + var result = item.value; + if (result) { + result = dbInfo.serializer.deserialize(result); + } + result = iterator(result, item.key, i + 1); + if (result !== undefined) { + resolve(result); + return; + } + } + resolve(); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function _setItem(key3, value2, callback, retriesLeft) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + if (value2 === undefined) { + value2 = null; + } + var originalValue = value2; + var dbInfo = self2._dbInfo; + dbInfo.serializer.serialize(value2, function(value3, error) { + if (error) { + reject2(error); + } else { + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "INSERT OR REPLACE INTO " + dbInfo.storeName + " " + "(key, value) VALUES (?, ?)", [key3, value3], function() { + resolve(originalValue); + }, function(t2, error2) { + reject2(error2); + }); + }, function(sqlError) { + if (sqlError.code === sqlError.QUOTA_ERR) { + if (retriesLeft > 0) { + resolve(_setItem.apply(self2, [key3, originalValue, callback, retriesLeft - 1])); + return; + } + reject2(sqlError); + } + }); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function setItem$1(key3, value2, callback) { + return _setItem.apply(this, [key3, value2, callback, 1]); + } + function removeItem$1(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "DELETE FROM " + dbInfo.storeName + " WHERE key = ?", [key3], function() { + resolve(); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function clear$1(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "DELETE FROM " + dbInfo.storeName, [], function() { + resolve(); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function length$1(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT COUNT(key) as c FROM " + dbInfo.storeName, [], function(t2, results) { + var result = results.rows.item(0).c; + resolve(result); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function key$1(n, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT key FROM " + dbInfo.storeName + " WHERE id = ? LIMIT 1", [n + 1], function(t2, results) { + var result = results.rows.length ? results.rows.item(0).key : null; + resolve(result); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function keys$1(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT key FROM " + dbInfo.storeName, [], function(t2, results) { + var keys3 = []; + for (var i = 0;i < results.rows.length; i++) { + keys3.push(results.rows.item(i).key); + } + resolve(keys3); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function getAllStoreNames(db) { + return new Promise$1(function(resolve, reject2) { + db.transaction(function(t) { + t.executeSql("SELECT name FROM sqlite_master " + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function(t2, results) { + var storeNames = []; + for (var i = 0;i < results.rows.length; i++) { + storeNames.push(results.rows.item(i).name); + } + resolve({ + db, + storeNames + }); + }, function(t2, error) { + reject2(error); + }); + }, function(sqlError) { + reject2(sqlError); + }); + }); + } + function dropInstance$1(options, callback) { + callback = getCallback.apply(this, arguments); + var currentConfig = this.config(); + options = typeof options !== "function" && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + var self2 = this; + var promise; + if (!options.name) { + promise = Promise$1.reject("Invalid arguments"); + } else { + promise = new Promise$1(function(resolve) { + var db; + if (options.name === currentConfig.name) { + db = self2._dbInfo.db; + } else { + db = openDatabase(options.name, "", "", 0); + } + if (!options.storeName) { + resolve(getAllStoreNames(db)); + } else { + resolve({ + db, + storeNames: [options.storeName] + }); + } + }).then(function(operationInfo) { + return new Promise$1(function(resolve, reject2) { + operationInfo.db.transaction(function(t) { + function dropTable(storeName) { + return new Promise$1(function(resolve2, reject3) { + t.executeSql("DROP TABLE IF EXISTS " + storeName, [], function() { + resolve2(); + }, function(t2, error) { + reject3(error); + }); + }); + } + var operations = []; + for (var i = 0, len = operationInfo.storeNames.length;i < len; i++) { + operations.push(dropTable(operationInfo.storeNames[i])); + } + Promise$1.all(operations).then(function() { + resolve(); + })["catch"](function(e) { + reject2(e); + }); + }, function(sqlError) { + reject2(sqlError); + }); + }); + }); + } + executeCallback(promise, callback); + return promise; + } + var webSQLStorage = { + _driver: "webSQLStorage", + _initStorage: _initStorage$1, + _support: isWebSQLValid(), + iterate: iterate$1, + getItem: getItem$1, + setItem: setItem$1, + removeItem: removeItem$1, + clear: clear$1, + length: length$1, + key: key$1, + keys: keys$1, + dropInstance: dropInstance$1 + }; + function isLocalStorageValid() { + try { + return typeof localStorage !== "undefined" && "setItem" in localStorage && !!localStorage.setItem; + } catch (e) { + return false; + } + } + function _getKeyPrefix(options, defaultConfig) { + var keyPrefix = options.name + "/"; + if (options.storeName !== defaultConfig.storeName) { + keyPrefix += options.storeName + "/"; + } + return keyPrefix; + } + function checkIfLocalStorageThrows() { + var localStorageTestKey = "_localforage_support_test"; + try { + localStorage.setItem(localStorageTestKey, true); + localStorage.removeItem(localStorageTestKey); + return false; + } catch (e) { + return true; + } + } + function _isLocalStorageUsable() { + return !checkIfLocalStorageThrows() || localStorage.length > 0; + } + function _initStorage$2(options) { + var self2 = this; + var dbInfo = {}; + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + dbInfo.keyPrefix = _getKeyPrefix(options, self2._defaultConfig); + if (!_isLocalStorageUsable()) { + return Promise$1.reject(); + } + self2._dbInfo = dbInfo; + dbInfo.serializer = localforageSerializer; + return Promise$1.resolve(); + } + function clear$2(callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var keyPrefix = self2._dbInfo.keyPrefix; + for (var i = localStorage.length - 1;i >= 0; i--) { + var key3 = localStorage.key(i); + if (key3.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key3); + } + } + }); + executeCallback(promise, callback); + return promise; + } + function getItem$2(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var result = localStorage.getItem(dbInfo.keyPrefix + key3); + if (result) { + result = dbInfo.serializer.deserialize(result); + } + return result; + }); + executeCallback(promise, callback); + return promise; + } + function iterate$2(iterator, callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var keyPrefix = dbInfo.keyPrefix; + var keyPrefixLength = keyPrefix.length; + var length3 = localStorage.length; + var iterationNumber = 1; + for (var i = 0;i < length3; i++) { + var key3 = localStorage.key(i); + if (key3.indexOf(keyPrefix) !== 0) { + continue; + } + var value2 = localStorage.getItem(key3); + if (value2) { + value2 = dbInfo.serializer.deserialize(value2); + } + value2 = iterator(value2, key3.substring(keyPrefixLength), iterationNumber++); + if (value2 !== undefined) { + return value2; + } + } + }); + executeCallback(promise, callback); + return promise; + } + function key$2(n, callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var result; + try { + result = localStorage.key(n); + } catch (error) { + result = null; + } + if (result) { + result = result.substring(dbInfo.keyPrefix.length); + } + return result; + }); + executeCallback(promise, callback); + return promise; + } + function keys$2(callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var length3 = localStorage.length; + var keys3 = []; + for (var i = 0;i < length3; i++) { + var itemKey = localStorage.key(i); + if (itemKey.indexOf(dbInfo.keyPrefix) === 0) { + keys3.push(itemKey.substring(dbInfo.keyPrefix.length)); + } + } + return keys3; + }); + executeCallback(promise, callback); + return promise; + } + function length$2(callback) { + var self2 = this; + var promise = self2.keys().then(function(keys3) { + return keys3.length; + }); + executeCallback(promise, callback); + return promise; + } + function removeItem$2(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + localStorage.removeItem(dbInfo.keyPrefix + key3); + }); + executeCallback(promise, callback); + return promise; + } + function setItem$2(key3, value2, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = self2.ready().then(function() { + if (value2 === undefined) { + value2 = null; + } + var originalValue = value2; + return new Promise$1(function(resolve, reject2) { + var dbInfo = self2._dbInfo; + dbInfo.serializer.serialize(value2, function(value3, error) { + if (error) { + reject2(error); + } else { + try { + localStorage.setItem(dbInfo.keyPrefix + key3, value3); + resolve(originalValue); + } catch (e) { + if (e.name === "QuotaExceededError" || e.name === "NS_ERROR_DOM_QUOTA_REACHED") { + reject2(e); + } + reject2(e); + } + } + }); + }); + }); + executeCallback(promise, callback); + return promise; + } + function dropInstance$2(options, callback) { + callback = getCallback.apply(this, arguments); + options = typeof options !== "function" && options || {}; + if (!options.name) { + var currentConfig = this.config(); + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + var self2 = this; + var promise; + if (!options.name) { + promise = Promise$1.reject("Invalid arguments"); + } else { + promise = new Promise$1(function(resolve) { + if (!options.storeName) { + resolve(options.name + "/"); + } else { + resolve(_getKeyPrefix(options, self2._defaultConfig)); + } + }).then(function(keyPrefix) { + for (var i = localStorage.length - 1;i >= 0; i--) { + var key3 = localStorage.key(i); + if (key3.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key3); + } + } + }); + } + executeCallback(promise, callback); + return promise; + } + var localStorageWrapper = { + _driver: "localStorageWrapper", + _initStorage: _initStorage$2, + _support: isLocalStorageValid(), + iterate: iterate$2, + getItem: getItem$2, + setItem: setItem$2, + removeItem: removeItem$2, + clear: clear$2, + length: length$2, + key: key$2, + keys: keys$2, + dropInstance: dropInstance$2 + }; + var sameValue = function sameValue(x, y) { + return x === y || typeof x === "number" && typeof y === "number" && isNaN(x) && isNaN(y); + }; + var includes = function includes(array, searchElement) { + var len = array.length; + var i = 0; + while (i < len) { + if (sameValue(array[i], searchElement)) { + return true; + } + i++; + } + return false; + }; + var isArray2 = Array.isArray || function(arg) { + return Object.prototype.toString.call(arg) === "[object Array]"; + }; + var DefinedDrivers = {}; + var DriverSupport = {}; + var DefaultDrivers = { + INDEXEDDB: asyncStorage, + WEBSQL: webSQLStorage, + LOCALSTORAGE: localStorageWrapper + }; + var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver]; + var OptionalDriverMethods = ["dropInstance"]; + var LibraryMethods = ["clear", "getItem", "iterate", "key", "keys", "length", "removeItem", "setItem"].concat(OptionalDriverMethods); + var DefaultConfig = { + description: "", + driver: DefaultDriverOrder.slice(), + name: "localforage", + size: 4980736, + storeName: "keyvaluepairs", + version: 1 + }; + function callWhenReady(localForageInstance, libraryMethod) { + localForageInstance[libraryMethod] = function() { + var _args = arguments; + return localForageInstance.ready().then(function() { + return localForageInstance[libraryMethod].apply(localForageInstance, _args); + }); + }; + } + function extend() { + for (var i = 1;i < arguments.length; i++) { + var arg = arguments[i]; + if (arg) { + for (var _key in arg) { + if (arg.hasOwnProperty(_key)) { + if (isArray2(arg[_key])) { + arguments[0][_key] = arg[_key].slice(); + } else { + arguments[0][_key] = arg[_key]; + } + } + } + } + } + return arguments[0]; + } + var LocalForage = function() { + function LocalForage2(options) { + _classCallCheck(this, LocalForage2); + for (var driverTypeKey in DefaultDrivers) { + if (DefaultDrivers.hasOwnProperty(driverTypeKey)) { + var driver = DefaultDrivers[driverTypeKey]; + var driverName = driver._driver; + this[driverTypeKey] = driverName; + if (!DefinedDrivers[driverName]) { + this.defineDriver(driver); + } + } + } + this._defaultConfig = extend({}, DefaultConfig); + this._config = extend({}, this._defaultConfig, options); + this._driverSet = null; + this._initDriver = null; + this._ready = false; + this._dbInfo = null; + this._wrapLibraryMethodsWithReady(); + this.setDriver(this._config.driver)["catch"](function() { + }); + } + LocalForage2.prototype.config = function config(options) { + if ((typeof options === "undefined" ? "undefined" : _typeof(options)) === "object") { + if (this._ready) { + return new Error("Can't call config() after localforage " + "has been used."); + } + for (var i in options) { + if (i === "storeName") { + options[i] = options[i].replace(/\W/g, "_"); + } + if (i === "version" && typeof options[i] !== "number") { + return new Error("Database version must be a number."); + } + this._config[i] = options[i]; + } + if ("driver" in options && options.driver) { + return this.setDriver(this._config.driver); + } + return true; + } else if (typeof options === "string") { + return this._config[options]; + } else { + return this._config; + } + }; + LocalForage2.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { + var promise = new Promise$1(function(resolve, reject2) { + try { + var driverName = driverObject._driver; + var complianceError = new Error("Custom driver not compliant; see " + "https://mozilla.github.io/localForage/#definedriver"); + if (!driverObject._driver) { + reject2(complianceError); + return; + } + var driverMethods = LibraryMethods.concat("_initStorage"); + for (var i = 0, len = driverMethods.length;i < len; i++) { + var driverMethodName = driverMethods[i]; + var isRequired = !includes(OptionalDriverMethods, driverMethodName); + if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== "function") { + reject2(complianceError); + return; + } + } + var configureMissingMethods = function configureMissingMethods() { + var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) { + return function() { + var error = new Error("Method " + methodName + " is not implemented by the current driver"); + var promise2 = Promise$1.reject(error); + executeCallback(promise2, arguments[arguments.length - 1]); + return promise2; + }; + }; + for (var _i = 0, _len = OptionalDriverMethods.length;_i < _len; _i++) { + var optionalDriverMethod = OptionalDriverMethods[_i]; + if (!driverObject[optionalDriverMethod]) { + driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod); + } + } + }; + configureMissingMethods(); + var setDriverSupport = function setDriverSupport(support) { + if (DefinedDrivers[driverName]) { + console.info("Redefining LocalForage driver: " + driverName); + } + DefinedDrivers[driverName] = driverObject; + DriverSupport[driverName] = support; + resolve(); + }; + if ("_support" in driverObject) { + if (driverObject._support && typeof driverObject._support === "function") { + driverObject._support().then(setDriverSupport, reject2); + } else { + setDriverSupport(!!driverObject._support); + } + } else { + setDriverSupport(true); + } + } catch (e) { + reject2(e); + } + }); + executeTwoCallbacks(promise, callback, errorCallback); + return promise; + }; + LocalForage2.prototype.driver = function driver() { + return this._driver || null; + }; + LocalForage2.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { + var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error("Driver not found.")); + executeTwoCallbacks(getDriverPromise, callback, errorCallback); + return getDriverPromise; + }; + LocalForage2.prototype.getSerializer = function getSerializer(callback) { + var serializerPromise = Promise$1.resolve(localforageSerializer); + executeTwoCallbacks(serializerPromise, callback); + return serializerPromise; + }; + LocalForage2.prototype.ready = function ready(callback) { + var self2 = this; + var promise = self2._driverSet.then(function() { + if (self2._ready === null) { + self2._ready = self2._initDriver(); + } + return self2._ready; + }); + executeTwoCallbacks(promise, callback, callback); + return promise; + }; + LocalForage2.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { + var self2 = this; + if (!isArray2(drivers)) { + drivers = [drivers]; + } + var supportedDrivers = this._getSupportedDrivers(drivers); + function setDriverToConfig() { + self2._config.driver = self2.driver(); + } + function extendSelfWithDriver(driver) { + self2._extend(driver); + setDriverToConfig(); + self2._ready = self2._initStorage(self2._config); + return self2._ready; + } + function initDriver(supportedDrivers2) { + return function() { + var currentDriverIndex = 0; + function driverPromiseLoop() { + while (currentDriverIndex < supportedDrivers2.length) { + var driverName = supportedDrivers2[currentDriverIndex]; + currentDriverIndex++; + self2._dbInfo = null; + self2._ready = null; + return self2.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop); + } + setDriverToConfig(); + var error = new Error("No available storage method found."); + self2._driverSet = Promise$1.reject(error); + return self2._driverSet; + } + return driverPromiseLoop(); + }; + } + var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function() { + return Promise$1.resolve(); + }) : Promise$1.resolve(); + this._driverSet = oldDriverSetDone.then(function() { + var driverName = supportedDrivers[0]; + self2._dbInfo = null; + self2._ready = null; + return self2.getDriver(driverName).then(function(driver) { + self2._driver = driver._driver; + setDriverToConfig(); + self2._wrapLibraryMethodsWithReady(); + self2._initDriver = initDriver(supportedDrivers); + }); + })["catch"](function() { + setDriverToConfig(); + var error = new Error("No available storage method found."); + self2._driverSet = Promise$1.reject(error); + return self2._driverSet; + }); + executeTwoCallbacks(this._driverSet, callback, errorCallback); + return this._driverSet; + }; + LocalForage2.prototype.supports = function supports(driverName) { + return !!DriverSupport[driverName]; + }; + LocalForage2.prototype._extend = function _extend(libraryMethodsAndProperties) { + extend(this, libraryMethodsAndProperties); + }; + LocalForage2.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { + var supportedDrivers = []; + for (var i = 0, len = drivers.length;i < len; i++) { + var driverName = drivers[i]; + if (this.supports(driverName)) { + supportedDrivers.push(driverName); + } + } + return supportedDrivers; + }; + LocalForage2.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { + for (var i = 0, len = LibraryMethods.length;i < len; i++) { + callWhenReady(this, LibraryMethods[i]); + } + }; + LocalForage2.prototype.createInstance = function createInstance(options) { + return new LocalForage2(options); + }; + return LocalForage2; + }(); + var localforage_js = new LocalForage; + module4.exports = localforage_js; + }, { "3": 3 }] }, {}, [4])(4); + }); +}); + +// node:stream +var exports_stream = {}; +__export(exports_stream, { + default: () => Uc +}); +var al, tt, cl, dl, hl, pl, yl = (e, t) => () => (e && (t = e(e = 0)), t), E = (e, t) => () => (t || e((t = { exports: {} }).exports, t), t.exports), Qr = (e, t) => { + for (var r in t) + tt(e, r, { get: t[r], enumerable: true }); +}, et = (e, t, r, n) => { + if (t && typeof t == "object" || typeof t == "function") + for (let i of dl(t)) + !pl.call(e, i) && i !== r && tt(e, i, { get: () => t[i], enumerable: !(n = cl(t, i)) || n.enumerable }); + return e; +}, ue = (e, t, r) => (et(e, t, "default"), r && et(r, t, "default")), rt = (e, t, r) => (r = e != null ? al(hl(e)) : {}, et(t || !e || !e.__esModule ? tt(r, "default", { value: e, enumerable: true }) : r, e)), pe = (e) => et(tt({}, "__esModule", { value: true }), e), tn, rn, te, I, V, ut, C, He, ir, k, Gu, se, ae, ce, di, Se, Et, xt, At, Pi, Tt, Wi, Gi, Er, Ke, Cr, Mo, J, qr, $r, Ut, Jo, Kr, fl, Jr, Ze, Uc; +var init_stream = __esm(() => { + al = Object.create; + tt = Object.defineProperty; + cl = Object.getOwnPropertyDescriptor; + dl = Object.getOwnPropertyNames; + hl = Object.getPrototypeOf; + pl = Object.prototype.hasOwnProperty; + tn = E((nt) => { + nt.byteLength = bl; + nt.toByteArray = _l; + nt.fromByteArray = ml; + var G = [], P = [], wl = typeof Uint8Array < "u" ? Uint8Array : Array, Wt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (ye = 0, Zr = Wt.length;ye < Zr; ++ye) + G[ye] = Wt[ye], P[Wt.charCodeAt(ye)] = ye; + var ye, Zr; + P[45] = 62; + P[95] = 63; + function en(e) { + var t = e.length; + if (t % 4 > 0) + throw new Error("Invalid string. Length must be a multiple of 4"); + var r = e.indexOf("="); + r === -1 && (r = t); + var n = r === t ? 0 : 4 - r % 4; + return [r, n]; + } + function bl(e) { + var t = en(e), r = t[0], n = t[1]; + return (r + n) * 3 / 4 - n; + } + function gl(e, t, r) { + return (t + r) * 3 / 4 - r; + } + function _l(e) { + var t, r = en(e), n = r[0], i = r[1], o = new wl(gl(e, n, i)), l = 0, u = i > 0 ? n - 4 : n, f; + for (f = 0;f < u; f += 4) + t = P[e.charCodeAt(f)] << 18 | P[e.charCodeAt(f + 1)] << 12 | P[e.charCodeAt(f + 2)] << 6 | P[e.charCodeAt(f + 3)], o[l++] = t >> 16 & 255, o[l++] = t >> 8 & 255, o[l++] = t & 255; + return i === 2 && (t = P[e.charCodeAt(f)] << 2 | P[e.charCodeAt(f + 1)] >> 4, o[l++] = t & 255), i === 1 && (t = P[e.charCodeAt(f)] << 10 | P[e.charCodeAt(f + 1)] << 4 | P[e.charCodeAt(f + 2)] >> 2, o[l++] = t >> 8 & 255, o[l++] = t & 255), o; + } + function El(e) { + return G[e >> 18 & 63] + G[e >> 12 & 63] + G[e >> 6 & 63] + G[e & 63]; + } + function Sl(e, t, r) { + for (var n, i = [], o = t;o < r; o += 3) + n = (e[o] << 16 & 16711680) + (e[o + 1] << 8 & 65280) + (e[o + 2] & 255), i.push(El(n)); + return i.join(""); + } + function ml(e) { + for (var t, r = e.length, n = r % 3, i = [], o = 16383, l = 0, u = r - n;l < u; l += o) + i.push(Sl(e, l, l + o > u ? u : l + o)); + return n === 1 ? (t = e[r - 1], i.push(G[t >> 2] + G[t << 4 & 63] + "==")) : n === 2 && (t = (e[r - 2] << 8) + e[r - 1], i.push(G[t >> 10] + G[t >> 4 & 63] + G[t << 2 & 63] + "=")), i.join(""); + } + }); + rn = E(($t) => { + $t.read = function(e, t, r, n, i) { + var o, l, u = i * 8 - n - 1, f = (1 << u) - 1, s = f >> 1, d = -7, c = r ? i - 1 : 0, y = r ? -1 : 1, h = e[t + c]; + for (c += y, o = h & (1 << -d) - 1, h >>= -d, d += u;d > 0; o = o * 256 + e[t + c], c += y, d -= 8) + ; + for (l = o & (1 << -d) - 1, o >>= -d, d += n;d > 0; l = l * 256 + e[t + c], c += y, d -= 8) + ; + if (o === 0) + o = 1 - s; + else { + if (o === f) + return l ? NaN : (h ? -1 : 1) * (1 / 0); + l = l + Math.pow(2, n), o = o - s; + } + return (h ? -1 : 1) * l * Math.pow(2, o - n); + }; + $t.write = function(e, t, r, n, i, o) { + var l, u, f, s = o * 8 - i - 1, d = (1 << s) - 1, c = d >> 1, y = i === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, h = n ? 0 : o - 1, p = n ? 1 : -1, B = t < 0 || t === 0 && 1 / t < 0 ? 1 : 0; + for (t = Math.abs(t), isNaN(t) || t === 1 / 0 ? (u = isNaN(t) ? 1 : 0, l = d) : (l = Math.floor(Math.log(t) / Math.LN2), t * (f = Math.pow(2, -l)) < 1 && (l--, f *= 2), l + c >= 1 ? t += y / f : t += y * Math.pow(2, 1 - c), t * f >= 2 && (l++, f /= 2), l + c >= d ? (u = 0, l = d) : l + c >= 1 ? (u = (t * f - 1) * Math.pow(2, i), l = l + c) : (u = t * Math.pow(2, c - 1) * Math.pow(2, i), l = 0));i >= 8; e[r + h] = u & 255, h += p, u /= 256, i -= 8) + ; + for (l = l << i | u, s += i;s > 0; e[r + h] = l & 255, h += p, l /= 256, s -= 8) + ; + e[r + h - p] |= B * 128; + }; + }); + te = E((Fe) => { + var jt = tn(), Le = rn(), nn = typeof Symbol == "function" && typeof Symbol.for == "function" ? Symbol.for("nodejs.util.inspect.custom") : null; + Fe.Buffer = a; + Fe.SlowBuffer = Bl; + Fe.INSPECT_MAX_BYTES = 50; + var it = 2147483647; + Fe.kMaxLength = it; + a.TYPED_ARRAY_SUPPORT = xl(); + !a.TYPED_ARRAY_SUPPORT && typeof console < "u" && typeof console.error == "function" && console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."); + function xl() { + try { + let e = new Uint8Array(1), t = { foo: function() { + return 42; + } }; + return Object.setPrototypeOf(t, Uint8Array.prototype), Object.setPrototypeOf(e, t), e.foo() === 42; + } catch { + return false; + } + } + Object.defineProperty(a.prototype, "parent", { enumerable: true, get: function() { + if (!!a.isBuffer(this)) + return this.buffer; + } }); + Object.defineProperty(a.prototype, "offset", { enumerable: true, get: function() { + if (!!a.isBuffer(this)) + return this.byteOffset; + } }); + function ee(e) { + if (e > it) + throw new RangeError('The value "' + e + '" is invalid for option "size"'); + let t = new Uint8Array(e); + return Object.setPrototypeOf(t, a.prototype), t; + } + function a(e, t, r) { + if (typeof e == "number") { + if (typeof t == "string") + throw new TypeError('The "string" argument must be of type string. Received type number'); + return Yt(e); + } + return fn(e, t, r); + } + a.poolSize = 8192; + function fn(e, t, r) { + if (typeof e == "string") + return Al(e, t); + if (ArrayBuffer.isView(e)) + return Il(e); + if (e == null) + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e); + if (H(e, ArrayBuffer) || e && H(e.buffer, ArrayBuffer) || typeof SharedArrayBuffer < "u" && (H(e, SharedArrayBuffer) || e && H(e.buffer, SharedArrayBuffer))) + return Ht(e, t, r); + if (typeof e == "number") + throw new TypeError('The "value" argument must not be of type number. Received type number'); + let n = e.valueOf && e.valueOf(); + if (n != null && n !== e) + return a.from(n, t, r); + let i = Tl(e); + if (i) + return i; + if (typeof Symbol < "u" && Symbol.toPrimitive != null && typeof e[Symbol.toPrimitive] == "function") + return a.from(e[Symbol.toPrimitive]("string"), t, r); + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e); + } + a.from = function(e, t, r) { + return fn(e, t, r); + }; + Object.setPrototypeOf(a.prototype, Uint8Array.prototype); + Object.setPrototypeOf(a, Uint8Array); + function sn(e) { + if (typeof e != "number") + throw new TypeError('"size" argument must be of type number'); + if (e < 0) + throw new RangeError('The value "' + e + '" is invalid for option "size"'); + } + function Rl(e, t, r) { + return sn(e), e <= 0 ? ee(e) : t !== undefined ? typeof r == "string" ? ee(e).fill(t, r) : ee(e).fill(t) : ee(e); + } + a.alloc = function(e, t, r) { + return Rl(e, t, r); + }; + function Yt(e) { + return sn(e), ee(e < 0 ? 0 : Kt(e) | 0); + } + a.allocUnsafe = function(e) { + return Yt(e); + }; + a.allocUnsafeSlow = function(e) { + return Yt(e); + }; + function Al(e, t) { + if ((typeof t != "string" || t === "") && (t = "utf8"), !a.isEncoding(t)) + throw new TypeError("Unknown encoding: " + t); + let r = an(e, t) | 0, n = ee(r), i = n.write(e, t); + return i !== r && (n = n.slice(0, i)), n; + } + function Gt(e) { + let t = e.length < 0 ? 0 : Kt(e.length) | 0, r = ee(t); + for (let n = 0;n < t; n += 1) + r[n] = e[n] & 255; + return r; + } + function Il(e) { + if (H(e, Uint8Array)) { + let t = new Uint8Array(e); + return Ht(t.buffer, t.byteOffset, t.byteLength); + } + return Gt(e); + } + function Ht(e, t, r) { + if (t < 0 || e.byteLength < t) + throw new RangeError('"offset" is outside of buffer bounds'); + if (e.byteLength < t + (r || 0)) + throw new RangeError('"length" is outside of buffer bounds'); + let n; + return t === undefined && r === undefined ? n = new Uint8Array(e) : r === undefined ? n = new Uint8Array(e, t) : n = new Uint8Array(e, t, r), Object.setPrototypeOf(n, a.prototype), n; + } + function Tl(e) { + if (a.isBuffer(e)) { + let t = Kt(e.length) | 0, r = ee(t); + return r.length === 0 || e.copy(r, 0, 0, t), r; + } + if (e.length !== undefined) + return typeof e.length != "number" || Xt(e.length) ? ee(0) : Gt(e); + if (e.type === "Buffer" && Array.isArray(e.data)) + return Gt(e.data); + } + function Kt(e) { + if (e >= it) + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + it.toString(16) + " bytes"); + return e | 0; + } + function Bl(e) { + return +e != e && (e = 0), a.alloc(+e); + } + a.isBuffer = function(t) { + return t != null && t._isBuffer === true && t !== a.prototype; + }; + a.compare = function(t, r) { + if (H(t, Uint8Array) && (t = a.from(t, t.offset, t.byteLength)), H(r, Uint8Array) && (r = a.from(r, r.offset, r.byteLength)), !a.isBuffer(t) || !a.isBuffer(r)) + throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'); + if (t === r) + return 0; + let n = t.length, i = r.length; + for (let o = 0, l = Math.min(n, i);o < l; ++o) + if (t[o] !== r[o]) { + n = t[o], i = r[o]; + break; + } + return n < i ? -1 : i < n ? 1 : 0; + }; + a.isEncoding = function(t) { + switch (String(t).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } + }; + a.concat = function(t, r) { + if (!Array.isArray(t)) + throw new TypeError('"list" argument must be an Array of Buffers'); + if (t.length === 0) + return a.alloc(0); + let n; + if (r === undefined) + for (r = 0, n = 0;n < t.length; ++n) + r += t[n].length; + let i = a.allocUnsafe(r), o = 0; + for (n = 0;n < t.length; ++n) { + let l = t[n]; + if (H(l, Uint8Array)) + o + l.length > i.length ? (a.isBuffer(l) || (l = a.from(l)), l.copy(i, o)) : Uint8Array.prototype.set.call(i, l, o); + else if (a.isBuffer(l)) + l.copy(i, o); + else + throw new TypeError('"list" argument must be an Array of Buffers'); + o += l.length; + } + return i; + }; + function an(e, t) { + if (a.isBuffer(e)) + return e.length; + if (ArrayBuffer.isView(e) || H(e, ArrayBuffer)) + return e.byteLength; + if (typeof e != "string") + throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof e); + let r = e.length, n = arguments.length > 2 && arguments[2] === true; + if (!n && r === 0) + return 0; + let i = false; + for (;; ) + switch (t) { + case "ascii": + case "latin1": + case "binary": + return r; + case "utf8": + case "utf-8": + return Vt(e).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return r * 2; + case "hex": + return r >>> 1; + case "base64": + return _n(e).length; + default: + if (i) + return n ? -1 : Vt(e).length; + t = ("" + t).toLowerCase(), i = true; + } + } + a.byteLength = an; + function Ll(e, t, r) { + let n = false; + if ((t === undefined || t < 0) && (t = 0), t > this.length || ((r === undefined || r > this.length) && (r = this.length), r <= 0) || (r >>>= 0, t >>>= 0, r <= t)) + return ""; + for (e || (e = "utf8");; ) + switch (e) { + case "hex": + return vl(this, t, r); + case "utf8": + case "utf-8": + return dn(this, t, r); + case "ascii": + return kl(this, t, r); + case "latin1": + case "binary": + return Ul(this, t, r); + case "base64": + return Dl(this, t, r); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ql(this, t, r); + default: + if (n) + throw new TypeError("Unknown encoding: " + e); + e = (e + "").toLowerCase(), n = true; + } + } + a.prototype._isBuffer = true; + function we(e, t, r) { + let n = e[t]; + e[t] = e[r], e[r] = n; + } + a.prototype.swap16 = function() { + let t = this.length; + if (t % 2 !== 0) + throw new RangeError("Buffer size must be a multiple of 16-bits"); + for (let r = 0;r < t; r += 2) + we(this, r, r + 1); + return this; + }; + a.prototype.swap32 = function() { + let t = this.length; + if (t % 4 !== 0) + throw new RangeError("Buffer size must be a multiple of 32-bits"); + for (let r = 0;r < t; r += 4) + we(this, r, r + 3), we(this, r + 1, r + 2); + return this; + }; + a.prototype.swap64 = function() { + let t = this.length; + if (t % 8 !== 0) + throw new RangeError("Buffer size must be a multiple of 64-bits"); + for (let r = 0;r < t; r += 8) + we(this, r, r + 7), we(this, r + 1, r + 6), we(this, r + 2, r + 5), we(this, r + 3, r + 4); + return this; + }; + a.prototype.toString = function() { + let t = this.length; + return t === 0 ? "" : arguments.length === 0 ? dn(this, 0, t) : Ll.apply(this, arguments); + }; + a.prototype.toLocaleString = a.prototype.toString; + a.prototype.equals = function(t) { + if (!a.isBuffer(t)) + throw new TypeError("Argument must be a Buffer"); + return this === t ? true : a.compare(this, t) === 0; + }; + a.prototype.inspect = function() { + let t = "", r = Fe.INSPECT_MAX_BYTES; + return t = this.toString("hex", 0, r).replace(/(.{2})/g, "$1 ").trim(), this.length > r && (t += " ... "), ""; + }; + nn && (a.prototype[nn] = a.prototype.inspect); + a.prototype.compare = function(t, r, n, i, o) { + if (H(t, Uint8Array) && (t = a.from(t, t.offset, t.byteLength)), !a.isBuffer(t)) + throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof t); + if (r === undefined && (r = 0), n === undefined && (n = t ? t.length : 0), i === undefined && (i = 0), o === undefined && (o = this.length), r < 0 || n > t.length || i < 0 || o > this.length) + throw new RangeError("out of range index"); + if (i >= o && r >= n) + return 0; + if (i >= o) + return -1; + if (r >= n) + return 1; + if (r >>>= 0, n >>>= 0, i >>>= 0, o >>>= 0, this === t) + return 0; + let l = o - i, u = n - r, f = Math.min(l, u), s = this.slice(i, o), d = t.slice(r, n); + for (let c = 0;c < f; ++c) + if (s[c] !== d[c]) { + l = s[c], u = d[c]; + break; + } + return l < u ? -1 : u < l ? 1 : 0; + }; + function cn(e, t, r, n, i) { + if (e.length === 0) + return -1; + if (typeof r == "string" ? (n = r, r = 0) : r > 2147483647 ? r = 2147483647 : r < -2147483648 && (r = -2147483648), r = +r, Xt(r) && (r = i ? 0 : e.length - 1), r < 0 && (r = e.length + r), r >= e.length) { + if (i) + return -1; + r = e.length - 1; + } else if (r < 0) + if (i) + r = 0; + else + return -1; + if (typeof t == "string" && (t = a.from(t, n)), a.isBuffer(t)) + return t.length === 0 ? -1 : on(e, t, r, n, i); + if (typeof t == "number") + return t = t & 255, typeof Uint8Array.prototype.indexOf == "function" ? i ? Uint8Array.prototype.indexOf.call(e, t, r) : Uint8Array.prototype.lastIndexOf.call(e, t, r) : on(e, [t], r, n, i); + throw new TypeError("val must be string, number or Buffer"); + } + function on(e, t, r, n, i) { + let o = 1, l = e.length, u = t.length; + if (n !== undefined && (n = String(n).toLowerCase(), n === "ucs2" || n === "ucs-2" || n === "utf16le" || n === "utf-16le")) { + if (e.length < 2 || t.length < 2) + return -1; + o = 2, l /= 2, u /= 2, r /= 2; + } + function f(d, c) { + return o === 1 ? d[c] : d.readUInt16BE(c * o); + } + let s; + if (i) { + let d = -1; + for (s = r;s < l; s++) + if (f(e, s) === f(t, d === -1 ? 0 : s - d)) { + if (d === -1 && (d = s), s - d + 1 === u) + return d * o; + } else + d !== -1 && (s -= s - d), d = -1; + } else + for (r + u > l && (r = l - u), s = r;s >= 0; s--) { + let d = true; + for (let c = 0;c < u; c++) + if (f(e, s + c) !== f(t, c)) { + d = false; + break; + } + if (d) + return s; + } + return -1; + } + a.prototype.includes = function(t, r, n) { + return this.indexOf(t, r, n) !== -1; + }; + a.prototype.indexOf = function(t, r, n) { + return cn(this, t, r, n, true); + }; + a.prototype.lastIndexOf = function(t, r, n) { + return cn(this, t, r, n, false); + }; + function Nl(e, t, r, n) { + r = Number(r) || 0; + let i = e.length - r; + n ? (n = Number(n), n > i && (n = i)) : n = i; + let o = t.length; + n > o / 2 && (n = o / 2); + let l; + for (l = 0;l < n; ++l) { + let u = parseInt(t.substr(l * 2, 2), 16); + if (Xt(u)) + return l; + e[r + l] = u; + } + return l; + } + function Fl(e, t, r, n) { + return ot(Vt(t, e.length - r), e, r, n); + } + function Ml(e, t, r, n) { + return ot(Gl(t), e, r, n); + } + function Cl(e, t, r, n) { + return ot(_n(t), e, r, n); + } + function Ol(e, t, r, n) { + return ot(Hl(t, e.length - r), e, r, n); + } + a.prototype.write = function(t, r, n, i) { + if (r === undefined) + i = "utf8", n = this.length, r = 0; + else if (n === undefined && typeof r == "string") + i = r, n = this.length, r = 0; + else if (isFinite(r)) + r = r >>> 0, isFinite(n) ? (n = n >>> 0, i === undefined && (i = "utf8")) : (i = n, n = undefined); + else + throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported"); + let o = this.length - r; + if ((n === undefined || n > o) && (n = o), t.length > 0 && (n < 0 || r < 0) || r > this.length) + throw new RangeError("Attempt to write outside buffer bounds"); + i || (i = "utf8"); + let l = false; + for (;; ) + switch (i) { + case "hex": + return Nl(this, t, r, n); + case "utf8": + case "utf-8": + return Fl(this, t, r, n); + case "ascii": + case "latin1": + case "binary": + return Ml(this, t, r, n); + case "base64": + return Cl(this, t, r, n); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return Ol(this, t, r, n); + default: + if (l) + throw new TypeError("Unknown encoding: " + i); + i = ("" + i).toLowerCase(), l = true; + } + }; + a.prototype.toJSON = function() { + return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) }; + }; + function Dl(e, t, r) { + return t === 0 && r === e.length ? jt.fromByteArray(e) : jt.fromByteArray(e.slice(t, r)); + } + function dn(e, t, r) { + r = Math.min(e.length, r); + let n = [], i = t; + for (;i < r; ) { + let o = e[i], l = null, u = o > 239 ? 4 : o > 223 ? 3 : o > 191 ? 2 : 1; + if (i + u <= r) { + let f, s, d, c; + switch (u) { + case 1: + o < 128 && (l = o); + break; + case 2: + f = e[i + 1], (f & 192) === 128 && (c = (o & 31) << 6 | f & 63, c > 127 && (l = c)); + break; + case 3: + f = e[i + 1], s = e[i + 2], (f & 192) === 128 && (s & 192) === 128 && (c = (o & 15) << 12 | (f & 63) << 6 | s & 63, c > 2047 && (c < 55296 || c > 57343) && (l = c)); + break; + case 4: + f = e[i + 1], s = e[i + 2], d = e[i + 3], (f & 192) === 128 && (s & 192) === 128 && (d & 192) === 128 && (c = (o & 15) << 18 | (f & 63) << 12 | (s & 63) << 6 | d & 63, c > 65535 && c < 1114112 && (l = c)); + } + } + l === null ? (l = 65533, u = 1) : l > 65535 && (l -= 65536, n.push(l >>> 10 & 1023 | 55296), l = 56320 | l & 1023), n.push(l), i += u; + } + return Pl(n); + } + var ln = 4096; + function Pl(e) { + let t = e.length; + if (t <= ln) + return String.fromCharCode.apply(String, e); + let r = "", n = 0; + for (;n < t; ) + r += String.fromCharCode.apply(String, e.slice(n, n += ln)); + return r; + } + function kl(e, t, r) { + let n = ""; + r = Math.min(e.length, r); + for (let i = t;i < r; ++i) + n += String.fromCharCode(e[i] & 127); + return n; + } + function Ul(e, t, r) { + let n = ""; + r = Math.min(e.length, r); + for (let i = t;i < r; ++i) + n += String.fromCharCode(e[i]); + return n; + } + function vl(e, t, r) { + let n = e.length; + (!t || t < 0) && (t = 0), (!r || r < 0 || r > n) && (r = n); + let i = ""; + for (let o = t;o < r; ++o) + i += Vl[e[o]]; + return i; + } + function ql(e, t, r) { + let n = e.slice(t, r), i = ""; + for (let o = 0;o < n.length - 1; o += 2) + i += String.fromCharCode(n[o] + n[o + 1] * 256); + return i; + } + a.prototype.slice = function(t, r) { + let n = this.length; + t = ~~t, r = r === undefined ? n : ~~r, t < 0 ? (t += n, t < 0 && (t = 0)) : t > n && (t = n), r < 0 ? (r += n, r < 0 && (r = 0)) : r > n && (r = n), r < t && (r = t); + let i = this.subarray(t, r); + return Object.setPrototypeOf(i, a.prototype), i; + }; + function F(e, t, r) { + if (e % 1 !== 0 || e < 0) + throw new RangeError("offset is not uint"); + if (e + t > r) + throw new RangeError("Trying to access beyond buffer length"); + } + a.prototype.readUintLE = a.prototype.readUIntLE = function(t, r, n) { + t = t >>> 0, r = r >>> 0, n || F(t, r, this.length); + let i = this[t], o = 1, l = 0; + for (;++l < r && (o *= 256); ) + i += this[t + l] * o; + return i; + }; + a.prototype.readUintBE = a.prototype.readUIntBE = function(t, r, n) { + t = t >>> 0, r = r >>> 0, n || F(t, r, this.length); + let i = this[t + --r], o = 1; + for (;r > 0 && (o *= 256); ) + i += this[t + --r] * o; + return i; + }; + a.prototype.readUint8 = a.prototype.readUInt8 = function(t, r) { + return t = t >>> 0, r || F(t, 1, this.length), this[t]; + }; + a.prototype.readUint16LE = a.prototype.readUInt16LE = function(t, r) { + return t = t >>> 0, r || F(t, 2, this.length), this[t] | this[t + 1] << 8; + }; + a.prototype.readUint16BE = a.prototype.readUInt16BE = function(t, r) { + return t = t >>> 0, r || F(t, 2, this.length), this[t] << 8 | this[t + 1]; + }; + a.prototype.readUint32LE = a.prototype.readUInt32LE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), (this[t] | this[t + 1] << 8 | this[t + 2] << 16) + this[t + 3] * 16777216; + }; + a.prototype.readUint32BE = a.prototype.readUInt32BE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), this[t] * 16777216 + (this[t + 1] << 16 | this[t + 2] << 8 | this[t + 3]); + }; + a.prototype.readBigUInt64LE = fe(function(t) { + t = t >>> 0, Ne(t, "offset"); + let r = this[t], n = this[t + 7]; + (r === undefined || n === undefined) && Ge(t, this.length - 8); + let i = r + this[++t] * 2 ** 8 + this[++t] * 2 ** 16 + this[++t] * 2 ** 24, o = this[++t] + this[++t] * 2 ** 8 + this[++t] * 2 ** 16 + n * 2 ** 24; + return BigInt(i) + (BigInt(o) << BigInt(32)); + }); + a.prototype.readBigUInt64BE = fe(function(t) { + t = t >>> 0, Ne(t, "offset"); + let r = this[t], n = this[t + 7]; + (r === undefined || n === undefined) && Ge(t, this.length - 8); + let i = r * 2 ** 24 + this[++t] * 2 ** 16 + this[++t] * 2 ** 8 + this[++t], o = this[++t] * 2 ** 24 + this[++t] * 2 ** 16 + this[++t] * 2 ** 8 + n; + return (BigInt(i) << BigInt(32)) + BigInt(o); + }); + a.prototype.readIntLE = function(t, r, n) { + t = t >>> 0, r = r >>> 0, n || F(t, r, this.length); + let i = this[t], o = 1, l = 0; + for (;++l < r && (o *= 256); ) + i += this[t + l] * o; + return o *= 128, i >= o && (i -= Math.pow(2, 8 * r)), i; + }; + a.prototype.readIntBE = function(t, r, n) { + t = t >>> 0, r = r >>> 0, n || F(t, r, this.length); + let i = r, o = 1, l = this[t + --i]; + for (;i > 0 && (o *= 256); ) + l += this[t + --i] * o; + return o *= 128, l >= o && (l -= Math.pow(2, 8 * r)), l; + }; + a.prototype.readInt8 = function(t, r) { + return t = t >>> 0, r || F(t, 1, this.length), this[t] & 128 ? (255 - this[t] + 1) * -1 : this[t]; + }; + a.prototype.readInt16LE = function(t, r) { + t = t >>> 0, r || F(t, 2, this.length); + let n = this[t] | this[t + 1] << 8; + return n & 32768 ? n | 4294901760 : n; + }; + a.prototype.readInt16BE = function(t, r) { + t = t >>> 0, r || F(t, 2, this.length); + let n = this[t + 1] | this[t] << 8; + return n & 32768 ? n | 4294901760 : n; + }; + a.prototype.readInt32LE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), this[t] | this[t + 1] << 8 | this[t + 2] << 16 | this[t + 3] << 24; + }; + a.prototype.readInt32BE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), this[t] << 24 | this[t + 1] << 16 | this[t + 2] << 8 | this[t + 3]; + }; + a.prototype.readBigInt64LE = fe(function(t) { + t = t >>> 0, Ne(t, "offset"); + let r = this[t], n = this[t + 7]; + (r === undefined || n === undefined) && Ge(t, this.length - 8); + let i = this[t + 4] + this[t + 5] * 2 ** 8 + this[t + 6] * 2 ** 16 + (n << 24); + return (BigInt(i) << BigInt(32)) + BigInt(r + this[++t] * 2 ** 8 + this[++t] * 2 ** 16 + this[++t] * 2 ** 24); + }); + a.prototype.readBigInt64BE = fe(function(t) { + t = t >>> 0, Ne(t, "offset"); + let r = this[t], n = this[t + 7]; + (r === undefined || n === undefined) && Ge(t, this.length - 8); + let i = (r << 24) + this[++t] * 2 ** 16 + this[++t] * 2 ** 8 + this[++t]; + return (BigInt(i) << BigInt(32)) + BigInt(this[++t] * 2 ** 24 + this[++t] * 2 ** 16 + this[++t] * 2 ** 8 + n); + }); + a.prototype.readFloatLE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), Le.read(this, t, true, 23, 4); + }; + a.prototype.readFloatBE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), Le.read(this, t, false, 23, 4); + }; + a.prototype.readDoubleLE = function(t, r) { + return t = t >>> 0, r || F(t, 8, this.length), Le.read(this, t, true, 52, 8); + }; + a.prototype.readDoubleBE = function(t, r) { + return t = t >>> 0, r || F(t, 8, this.length), Le.read(this, t, false, 52, 8); + }; + function O(e, t, r, n, i, o) { + if (!a.isBuffer(e)) + throw new TypeError('"buffer" argument must be a Buffer instance'); + if (t > i || t < o) + throw new RangeError('"value" argument is out of bounds'); + if (r + n > e.length) + throw new RangeError("Index out of range"); + } + a.prototype.writeUintLE = a.prototype.writeUIntLE = function(t, r, n, i) { + if (t = +t, r = r >>> 0, n = n >>> 0, !i) { + let u = Math.pow(2, 8 * n) - 1; + O(this, t, r, n, u, 0); + } + let o = 1, l = 0; + for (this[r] = t & 255;++l < n && (o *= 256); ) + this[r + l] = t / o & 255; + return r + n; + }; + a.prototype.writeUintBE = a.prototype.writeUIntBE = function(t, r, n, i) { + if (t = +t, r = r >>> 0, n = n >>> 0, !i) { + let u = Math.pow(2, 8 * n) - 1; + O(this, t, r, n, u, 0); + } + let o = n - 1, l = 1; + for (this[r + o] = t & 255;--o >= 0 && (l *= 256); ) + this[r + o] = t / l & 255; + return r + n; + }; + a.prototype.writeUint8 = a.prototype.writeUInt8 = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 1, 255, 0), this[r] = t & 255, r + 1; + }; + a.prototype.writeUint16LE = a.prototype.writeUInt16LE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 2, 65535, 0), this[r] = t & 255, this[r + 1] = t >>> 8, r + 2; + }; + a.prototype.writeUint16BE = a.prototype.writeUInt16BE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 2, 65535, 0), this[r] = t >>> 8, this[r + 1] = t & 255, r + 2; + }; + a.prototype.writeUint32LE = a.prototype.writeUInt32LE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 4, 4294967295, 0), this[r + 3] = t >>> 24, this[r + 2] = t >>> 16, this[r + 1] = t >>> 8, this[r] = t & 255, r + 4; + }; + a.prototype.writeUint32BE = a.prototype.writeUInt32BE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 4, 4294967295, 0), this[r] = t >>> 24, this[r + 1] = t >>> 16, this[r + 2] = t >>> 8, this[r + 3] = t & 255, r + 4; + }; + function hn(e, t, r, n, i) { + gn(t, n, i, e, r, 7); + let o = Number(t & BigInt(4294967295)); + e[r++] = o, o = o >> 8, e[r++] = o, o = o >> 8, e[r++] = o, o = o >> 8, e[r++] = o; + let l = Number(t >> BigInt(32) & BigInt(4294967295)); + return e[r++] = l, l = l >> 8, e[r++] = l, l = l >> 8, e[r++] = l, l = l >> 8, e[r++] = l, r; + } + function pn(e, t, r, n, i) { + gn(t, n, i, e, r, 7); + let o = Number(t & BigInt(4294967295)); + e[r + 7] = o, o = o >> 8, e[r + 6] = o, o = o >> 8, e[r + 5] = o, o = o >> 8, e[r + 4] = o; + let l = Number(t >> BigInt(32) & BigInt(4294967295)); + return e[r + 3] = l, l = l >> 8, e[r + 2] = l, l = l >> 8, e[r + 1] = l, l = l >> 8, e[r] = l, r + 8; + } + a.prototype.writeBigUInt64LE = fe(function(t, r = 0) { + return hn(this, t, r, BigInt(0), BigInt("0xffffffffffffffff")); + }); + a.prototype.writeBigUInt64BE = fe(function(t, r = 0) { + return pn(this, t, r, BigInt(0), BigInt("0xffffffffffffffff")); + }); + a.prototype.writeIntLE = function(t, r, n, i) { + if (t = +t, r = r >>> 0, !i) { + let f = Math.pow(2, 8 * n - 1); + O(this, t, r, n, f - 1, -f); + } + let o = 0, l = 1, u = 0; + for (this[r] = t & 255;++o < n && (l *= 256); ) + t < 0 && u === 0 && this[r + o - 1] !== 0 && (u = 1), this[r + o] = (t / l >> 0) - u & 255; + return r + n; + }; + a.prototype.writeIntBE = function(t, r, n, i) { + if (t = +t, r = r >>> 0, !i) { + let f = Math.pow(2, 8 * n - 1); + O(this, t, r, n, f - 1, -f); + } + let o = n - 1, l = 1, u = 0; + for (this[r + o] = t & 255;--o >= 0 && (l *= 256); ) + t < 0 && u === 0 && this[r + o + 1] !== 0 && (u = 1), this[r + o] = (t / l >> 0) - u & 255; + return r + n; + }; + a.prototype.writeInt8 = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 1, 127, -128), t < 0 && (t = 255 + t + 1), this[r] = t & 255, r + 1; + }; + a.prototype.writeInt16LE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 2, 32767, -32768), this[r] = t & 255, this[r + 1] = t >>> 8, r + 2; + }; + a.prototype.writeInt16BE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 2, 32767, -32768), this[r] = t >>> 8, this[r + 1] = t & 255, r + 2; + }; + a.prototype.writeInt32LE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 4, 2147483647, -2147483648), this[r] = t & 255, this[r + 1] = t >>> 8, this[r + 2] = t >>> 16, this[r + 3] = t >>> 24, r + 4; + }; + a.prototype.writeInt32BE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 4, 2147483647, -2147483648), t < 0 && (t = 4294967295 + t + 1), this[r] = t >>> 24, this[r + 1] = t >>> 16, this[r + 2] = t >>> 8, this[r + 3] = t & 255, r + 4; + }; + a.prototype.writeBigInt64LE = fe(function(t, r = 0) { + return hn(this, t, r, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + a.prototype.writeBigInt64BE = fe(function(t, r = 0) { + return pn(this, t, r, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + function yn(e, t, r, n, i, o) { + if (r + n > e.length) + throw new RangeError("Index out of range"); + if (r < 0) + throw new RangeError("Index out of range"); + } + function wn(e, t, r, n, i) { + return t = +t, r = r >>> 0, i || yn(e, t, r, 4, 340282346638528860000000000000000000000, -340282346638528860000000000000000000000), Le.write(e, t, r, n, 23, 4), r + 4; + } + a.prototype.writeFloatLE = function(t, r, n) { + return wn(this, t, r, true, n); + }; + a.prototype.writeFloatBE = function(t, r, n) { + return wn(this, t, r, false, n); + }; + function bn(e, t, r, n, i) { + return t = +t, r = r >>> 0, i || yn(e, t, r, 8, 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, -179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000), Le.write(e, t, r, n, 52, 8), r + 8; + } + a.prototype.writeDoubleLE = function(t, r, n) { + return bn(this, t, r, true, n); + }; + a.prototype.writeDoubleBE = function(t, r, n) { + return bn(this, t, r, false, n); + }; + a.prototype.copy = function(t, r, n, i) { + if (!a.isBuffer(t)) + throw new TypeError("argument should be a Buffer"); + if (n || (n = 0), !i && i !== 0 && (i = this.length), r >= t.length && (r = t.length), r || (r = 0), i > 0 && i < n && (i = n), i === n || t.length === 0 || this.length === 0) + return 0; + if (r < 0) + throw new RangeError("targetStart out of bounds"); + if (n < 0 || n >= this.length) + throw new RangeError("Index out of range"); + if (i < 0) + throw new RangeError("sourceEnd out of bounds"); + i > this.length && (i = this.length), t.length - r < i - n && (i = t.length - r + n); + let o = i - n; + return this === t && typeof Uint8Array.prototype.copyWithin == "function" ? this.copyWithin(r, n, i) : Uint8Array.prototype.set.call(t, this.subarray(n, i), r), o; + }; + a.prototype.fill = function(t, r, n, i) { + if (typeof t == "string") { + if (typeof r == "string" ? (i = r, r = 0, n = this.length) : typeof n == "string" && (i = n, n = this.length), i !== undefined && typeof i != "string") + throw new TypeError("encoding must be a string"); + if (typeof i == "string" && !a.isEncoding(i)) + throw new TypeError("Unknown encoding: " + i); + if (t.length === 1) { + let l = t.charCodeAt(0); + (i === "utf8" && l < 128 || i === "latin1") && (t = l); + } + } else + typeof t == "number" ? t = t & 255 : typeof t == "boolean" && (t = Number(t)); + if (r < 0 || this.length < r || this.length < n) + throw new RangeError("Out of range index"); + if (n <= r) + return this; + r = r >>> 0, n = n === undefined ? this.length : n >>> 0, t || (t = 0); + let o; + if (typeof t == "number") + for (o = r;o < n; ++o) + this[o] = t; + else { + let l = a.isBuffer(t) ? t : a.from(t, i), u = l.length; + if (u === 0) + throw new TypeError('The value "' + t + '" is invalid for argument "value"'); + for (o = 0;o < n - r; ++o) + this[o + r] = l[o % u]; + } + return this; + }; + var Be = {}; + function zt(e, t, r) { + Be[e] = class extends r { + constructor() { + super(), Object.defineProperty(this, "message", { value: t.apply(this, arguments), writable: true, configurable: true }), this.name = `${this.name} [${e}]`, this.stack, delete this.name; + } + get code() { + return e; + } + set code(i) { + Object.defineProperty(this, "code", { configurable: true, enumerable: true, value: i, writable: true }); + } + toString() { + return `${this.name} [${e}]: ${this.message}`; + } + }; + } + zt("ERR_BUFFER_OUT_OF_BOUNDS", function(e) { + return e ? `${e} is outside of buffer bounds` : "Attempt to access memory outside buffer bounds"; + }, RangeError); + zt("ERR_INVALID_ARG_TYPE", function(e, t) { + return `The "${e}" argument must be of type number. Received type ${typeof t}`; + }, TypeError); + zt("ERR_OUT_OF_RANGE", function(e, t, r) { + let n = `The value of "${e}" is out of range.`, i = r; + return Number.isInteger(r) && Math.abs(r) > 2 ** 32 ? i = un(String(r)) : typeof r == "bigint" && (i = String(r), (r > BigInt(2) ** BigInt(32) || r < -(BigInt(2) ** BigInt(32))) && (i = un(i)), i += "n"), n += ` It must be ${t}. Received ${i}`, n; + }, RangeError); + function un(e) { + let t = "", r = e.length, n = e[0] === "-" ? 1 : 0; + for (;r >= n + 4; r -= 3) + t = `_${e.slice(r - 3, r)}${t}`; + return `${e.slice(0, r)}${t}`; + } + function Wl(e, t, r) { + Ne(t, "offset"), (e[t] === undefined || e[t + r] === undefined) && Ge(t, e.length - (r + 1)); + } + function gn(e, t, r, n, i, o) { + if (e > r || e < t) { + let l = typeof t == "bigint" ? "n" : "", u; + throw o > 3 ? t === 0 || t === BigInt(0) ? u = `>= 0${l} and < 2${l} ** ${(o + 1) * 8}${l}` : u = `>= -(2${l} ** ${(o + 1) * 8 - 1}${l}) and < 2 ** ${(o + 1) * 8 - 1}${l}` : u = `>= ${t}${l} and <= ${r}${l}`, new Be.ERR_OUT_OF_RANGE("value", u, e); + } + Wl(n, i, o); + } + function Ne(e, t) { + if (typeof e != "number") + throw new Be.ERR_INVALID_ARG_TYPE(t, "number", e); + } + function Ge(e, t, r) { + throw Math.floor(e) !== e ? (Ne(e, r), new Be.ERR_OUT_OF_RANGE(r || "offset", "an integer", e)) : t < 0 ? new Be.ERR_BUFFER_OUT_OF_BOUNDS : new Be.ERR_OUT_OF_RANGE(r || "offset", `>= ${r ? 1 : 0} and <= ${t}`, e); + } + var $l = /[^+/0-9A-Za-z-_]/g; + function jl(e) { + if (e = e.split("=")[0], e = e.trim().replace($l, ""), e.length < 2) + return ""; + for (;e.length % 4 !== 0; ) + e = e + "="; + return e; + } + function Vt(e, t) { + t = t || 1 / 0; + let r, n = e.length, i = null, o = []; + for (let l = 0;l < n; ++l) { + if (r = e.charCodeAt(l), r > 55295 && r < 57344) { + if (!i) { + if (r > 56319) { + (t -= 3) > -1 && o.push(239, 191, 189); + continue; + } else if (l + 1 === n) { + (t -= 3) > -1 && o.push(239, 191, 189); + continue; + } + i = r; + continue; + } + if (r < 56320) { + (t -= 3) > -1 && o.push(239, 191, 189), i = r; + continue; + } + r = (i - 55296 << 10 | r - 56320) + 65536; + } else + i && (t -= 3) > -1 && o.push(239, 191, 189); + if (i = null, r < 128) { + if ((t -= 1) < 0) + break; + o.push(r); + } else if (r < 2048) { + if ((t -= 2) < 0) + break; + o.push(r >> 6 | 192, r & 63 | 128); + } else if (r < 65536) { + if ((t -= 3) < 0) + break; + o.push(r >> 12 | 224, r >> 6 & 63 | 128, r & 63 | 128); + } else if (r < 1114112) { + if ((t -= 4) < 0) + break; + o.push(r >> 18 | 240, r >> 12 & 63 | 128, r >> 6 & 63 | 128, r & 63 | 128); + } else + throw new Error("Invalid code point"); + } + return o; + } + function Gl(e) { + let t = []; + for (let r = 0;r < e.length; ++r) + t.push(e.charCodeAt(r) & 255); + return t; + } + function Hl(e, t) { + let r, n, i, o = []; + for (let l = 0;l < e.length && !((t -= 2) < 0); ++l) + r = e.charCodeAt(l), n = r >> 8, i = r % 256, o.push(i), o.push(n); + return o; + } + function _n(e) { + return jt.toByteArray(jl(e)); + } + function ot(e, t, r, n) { + let i; + for (i = 0;i < n && !(i + r >= t.length || i >= e.length); ++i) + t[i + r] = e[i]; + return i; + } + function H(e, t) { + return e instanceof t || e != null && e.constructor != null && e.constructor.name != null && e.constructor.name === t.name; + } + function Xt(e) { + return e !== e; + } + var Vl = function() { + let e = "0123456789abcdef", t = new Array(256); + for (let r = 0;r < 16; ++r) { + let n = r * 16; + for (let i = 0;i < 16; ++i) + t[n + i] = e[r] + e[i]; + } + return t; + }(); + function fe(e) { + return typeof BigInt > "u" ? Yl : e; + } + function Yl() { + throw new Error("BigInt not supported"); + } + }); + I = E((Gc, En) => { + En.exports = { ArrayIsArray(e) { + return Array.isArray(e); + }, ArrayPrototypeIncludes(e, t) { + return e.includes(t); + }, ArrayPrototypeIndexOf(e, t) { + return e.indexOf(t); + }, ArrayPrototypeJoin(e, t) { + return e.join(t); + }, ArrayPrototypeMap(e, t) { + return e.map(t); + }, ArrayPrototypePop(e, t) { + return e.pop(t); + }, ArrayPrototypePush(e, t) { + return e.push(t); + }, ArrayPrototypeSlice(e, t, r) { + return e.slice(t, r); + }, Error, FunctionPrototypeCall(e, t, ...r) { + return e.call(t, ...r); + }, FunctionPrototypeSymbolHasInstance(e, t) { + return Function.prototype[Symbol.hasInstance].call(e, t); + }, MathFloor: Math.floor, Number, NumberIsInteger: Number.isInteger, NumberIsNaN: Number.isNaN, NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, NumberParseInt: Number.parseInt, ObjectDefineProperties(e, t) { + return Object.defineProperties(e, t); + }, ObjectDefineProperty(e, t, r) { + return Object.defineProperty(e, t, r); + }, ObjectGetOwnPropertyDescriptor(e, t) { + return Object.getOwnPropertyDescriptor(e, t); + }, ObjectKeys(e) { + return Object.keys(e); + }, ObjectSetPrototypeOf(e, t) { + return Object.setPrototypeOf(e, t); + }, Promise, PromisePrototypeCatch(e, t) { + return e.catch(t); + }, PromisePrototypeThen(e, t, r) { + return e.then(t, r); + }, PromiseReject(e) { + return Promise.reject(e); + }, ReflectApply: Reflect.apply, RegExpPrototypeTest(e, t) { + return e.test(t); + }, SafeSet: Set, String, StringPrototypeSlice(e, t, r) { + return e.slice(t, r); + }, StringPrototypeToLowerCase(e) { + return e.toLowerCase(); + }, StringPrototypeToUpperCase(e) { + return e.toUpperCase(); + }, StringPrototypeTrim(e) { + return e.trim(); + }, Symbol, SymbolAsyncIterator: Symbol.asyncIterator, SymbolHasInstance: Symbol.hasInstance, SymbolIterator: Symbol.iterator, TypedArrayPrototypeSet(e, t, r) { + return e.set(t, r); + }, Uint8Array }; + }); + V = E((Hc, Qt) => { + var Kl = te(), zl = Object.getPrototypeOf(async function() { + }).constructor, Sn = globalThis.Blob || Kl.Blob, Xl = typeof Sn < "u" ? function(t) { + return t instanceof Sn; + } : function(t) { + return false; + }, Jt = class extends Error { + constructor(t) { + if (!Array.isArray(t)) + throw new TypeError(`Expected input to be an Array, got ${typeof t}`); + let r = ""; + for (let n = 0;n < t.length; n++) + r += ` ${t[n].stack} +`; + super(r), this.name = "AggregateError", this.errors = t; + } + }; + Qt.exports = { AggregateError: Jt, kEmptyObject: Object.freeze({}), once(e) { + let t = false; + return function(...r) { + t || (t = true, e.apply(this, r)); + }; + }, createDeferredPromise: function() { + let e, t; + return { promise: new Promise((n, i) => { + e = n, t = i; + }), resolve: e, reject: t }; + }, promisify(e) { + return new Promise((t, r) => { + e((n, ...i) => n ? r(n) : t(...i)); + }); + }, debuglog() { + return function() { + }; + }, format(e, ...t) { + return e.replace(/%([sdifj])/g, function(...[r, n]) { + let i = t.shift(); + return n === "f" ? i.toFixed(6) : n === "j" ? JSON.stringify(i) : n === "s" && typeof i == "object" ? `${i.constructor !== Object ? i.constructor.name : ""} {}`.trim() : i.toString(); + }); + }, inspect(e) { + switch (typeof e) { + case "string": + if (e.includes("'")) + if (e.includes('"')) { + if (!e.includes("`") && !e.includes("${")) + return `\`${e}\``; + } else + return `"${e}"`; + return `'${e}'`; + case "number": + return isNaN(e) ? "NaN" : Object.is(e, -0) ? String(e) : e; + case "bigint": + return `${String(e)}n`; + case "boolean": + case "undefined": + return String(e); + case "object": + return "{}"; + } + }, types: { isAsyncFunction(e) { + return e instanceof zl; + }, isArrayBufferView(e) { + return ArrayBuffer.isView(e); + } }, isBlob: Xl }; + Qt.exports.promisify.custom = Symbol.for("nodejs.util.promisify.custom"); + }); + ut = E((Vc, lt) => { + var { AbortController: mn, AbortSignal: Jl } = typeof self < "u" ? self : typeof window < "u" ? window : undefined; + lt.exports = mn; + lt.exports.AbortSignal = Jl; + lt.exports.default = mn; + }); + C = E((Yc, An) => { + var { format: Ql, inspect: ft, AggregateError: Zl } = V(), eu = globalThis.AggregateError || Zl, tu = Symbol("kIsNodeError"), ru = ["string", "function", "number", "object", "Function", "Object", "boolean", "bigint", "symbol"], nu = /^([A-Z][a-z0-9]*)+$/, iu = "__node_internal_", st = {}; + function be(e, t) { + if (!e) + throw new st.ERR_INTERNAL_ASSERTION(t); + } + function xn(e) { + let t = "", r = e.length, n = e[0] === "-" ? 1 : 0; + for (;r >= n + 4; r -= 3) + t = `_${e.slice(r - 3, r)}${t}`; + return `${e.slice(0, r)}${t}`; + } + function ou(e, t, r) { + if (typeof t == "function") + return be(t.length <= r.length, `Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`), t(...r); + let n = (t.match(/%[dfijoOs]/g) || []).length; + return be(n === r.length, `Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${n}).`), r.length === 0 ? t : Ql(t, ...r); + } + function M(e, t, r) { + r || (r = Error); + + class n extends r { + constructor(...o) { + super(ou(e, t, o)); + } + toString() { + return `${this.name} [${e}]: ${this.message}`; + } + } + Object.defineProperties(n.prototype, { name: { value: r.name, writable: true, enumerable: false, configurable: true }, toString: { value() { + return `${this.name} [${e}]: ${this.message}`; + }, writable: true, enumerable: false, configurable: true } }), n.prototype.code = e, n.prototype[tu] = true, st[e] = n; + } + function Rn(e) { + let t = iu + e.name; + return Object.defineProperty(e, "name", { value: t }), e; + } + function lu(e, t) { + if (e && t && e !== t) { + if (Array.isArray(t.errors)) + return t.errors.push(e), t; + let r = new eu([t, e], t.message); + return r.code = t.code, r; + } + return e || t; + } + var Zt = class extends Error { + constructor(t = "The operation was aborted", r = undefined) { + if (r !== undefined && typeof r != "object") + throw new st.ERR_INVALID_ARG_TYPE("options", "Object", r); + super(t, r), this.code = "ABORT_ERR", this.name = "AbortError"; + } + }; + M("ERR_ASSERTION", "%s", Error); + M("ERR_INVALID_ARG_TYPE", (e, t, r) => { + be(typeof e == "string", "'name' must be a string"), Array.isArray(t) || (t = [t]); + let n = "The "; + e.endsWith(" argument") ? n += `${e} ` : n += `"${e}" ${e.includes(".") ? "property" : "argument"} `, n += "must be "; + let i = [], o = [], l = []; + for (let f of t) + be(typeof f == "string", "All expected entries have to be of type string"), ru.includes(f) ? i.push(f.toLowerCase()) : nu.test(f) ? o.push(f) : (be(f !== "object", 'The value "object" should be written as "Object"'), l.push(f)); + if (o.length > 0) { + let f = i.indexOf("object"); + f !== -1 && (i.splice(i, f, 1), o.push("Object")); + } + if (i.length > 0) { + switch (i.length) { + case 1: + n += `of type ${i[0]}`; + break; + case 2: + n += `one of type ${i[0]} or ${i[1]}`; + break; + default: { + let f = i.pop(); + n += `one of type ${i.join(", ")}, or ${f}`; + } + } + (o.length > 0 || l.length > 0) && (n += " or "); + } + if (o.length > 0) { + switch (o.length) { + case 1: + n += `an instance of ${o[0]}`; + break; + case 2: + n += `an instance of ${o[0]} or ${o[1]}`; + break; + default: { + let f = o.pop(); + n += `an instance of ${o.join(", ")}, or ${f}`; + } + } + l.length > 0 && (n += " or "); + } + switch (l.length) { + case 0: + break; + case 1: + l[0].toLowerCase() !== l[0] && (n += "an "), n += `${l[0]}`; + break; + case 2: + n += `one of ${l[0]} or ${l[1]}`; + break; + default: { + let f = l.pop(); + n += `one of ${l.join(", ")}, or ${f}`; + } + } + if (r == null) + n += `. Received ${r}`; + else if (typeof r == "function" && r.name) + n += `. Received function ${r.name}`; + else if (typeof r == "object") { + var u; + (u = r.constructor) !== null && u !== undefined && u.name ? n += `. Received an instance of ${r.constructor.name}` : n += `. Received ${ft(r, { depth: -1 })}`; + } else { + let f = ft(r, { colors: false }); + f.length > 25 && (f = `${f.slice(0, 25)}...`), n += `. Received type ${typeof r} (${f})`; + } + return n; + }, TypeError); + M("ERR_INVALID_ARG_VALUE", (e, t, r = "is invalid") => { + let n = ft(t); + return n.length > 128 && (n = n.slice(0, 128) + "..."), `The ${e.includes(".") ? "property" : "argument"} '${e}' ${r}. Received ${n}`; + }, TypeError); + M("ERR_INVALID_RETURN_VALUE", (e, t, r) => { + var n; + let i = r != null && (n = r.constructor) !== null && n !== undefined && n.name ? `instance of ${r.constructor.name}` : `type ${typeof r}`; + return `Expected ${e} to be returned from the "${t}" function but got ${i}.`; + }, TypeError); + M("ERR_MISSING_ARGS", (...e) => { + be(e.length > 0, "At least one arg needs to be specified"); + let t, r = e.length; + switch (e = (Array.isArray(e) ? e : [e]).map((n) => `"${n}"`).join(" or "), r) { + case 1: + t += `The ${e[0]} argument`; + break; + case 2: + t += `The ${e[0]} and ${e[1]} arguments`; + break; + default: + { + let n = e.pop(); + t += `The ${e.join(", ")}, and ${n} arguments`; + } + break; + } + return `${t} must be specified`; + }, TypeError); + M("ERR_OUT_OF_RANGE", (e, t, r) => { + be(t, 'Missing "range" argument'); + let n; + return Number.isInteger(r) && Math.abs(r) > 2 ** 32 ? n = xn(String(r)) : typeof r == "bigint" ? (n = String(r), (r > 2n ** 32n || r < -(2n ** 32n)) && (n = xn(n)), n += "n") : n = ft(r), `The value of "${e}" is out of range. It must be ${t}. Received ${n}`; + }, RangeError); + M("ERR_MULTIPLE_CALLBACK", "Callback called multiple times", Error); + M("ERR_METHOD_NOT_IMPLEMENTED", "The %s method is not implemented", Error); + M("ERR_STREAM_ALREADY_FINISHED", "Cannot call %s after a stream was finished", Error); + M("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable", Error); + M("ERR_STREAM_DESTROYED", "Cannot call %s after a stream was destroyed", Error); + M("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + M("ERR_STREAM_PREMATURE_CLOSE", "Premature close", Error); + M("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF", Error); + M("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event", Error); + M("ERR_STREAM_WRITE_AFTER_END", "write after end", Error); + M("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s", TypeError); + An.exports = { AbortError: Zt, aggregateTwoErrors: Rn(lu), hideStackFrames: Rn, codes: st }; + }); + He = E((Kc, Cn) => { + var { ArrayIsArray: Bn, ArrayPrototypeIncludes: Ln, ArrayPrototypeJoin: Nn, ArrayPrototypeMap: uu, NumberIsInteger: tr, NumberIsNaN: fu, NumberMAX_SAFE_INTEGER: su, NumberMIN_SAFE_INTEGER: au, NumberParseInt: cu, ObjectPrototypeHasOwnProperty: du, RegExpPrototypeExec: hu, String: pu, StringPrototypeToUpperCase: yu, StringPrototypeTrim: wu } = I(), { hideStackFrames: W, codes: { ERR_SOCKET_BAD_PORT: bu, ERR_INVALID_ARG_TYPE: D, ERR_INVALID_ARG_VALUE: at, ERR_OUT_OF_RANGE: ge, ERR_UNKNOWN_SIGNAL: In } } = C(), { normalizeEncoding: gu } = V(), { isAsyncFunction: _u, isArrayBufferView: Eu } = V().types, Tn = {}; + function Su(e) { + return e === (e | 0); + } + function mu(e) { + return e === e >>> 0; + } + var xu = /^[0-7]+$/, Ru = "must be a 32-bit unsigned integer or an octal string"; + function Au(e, t, r) { + if (typeof e > "u" && (e = r), typeof e == "string") { + if (hu(xu, e) === null) + throw new at(t, e, Ru); + e = cu(e, 8); + } + return Fn(e, t), e; + } + var Iu = W((e, t, r = au, n = su) => { + if (typeof e != "number") + throw new D(t, "number", e); + if (!tr(e)) + throw new ge(t, "an integer", e); + if (e < r || e > n) + throw new ge(t, `>= ${r} && <= ${n}`, e); + }), Tu = W((e, t, r = -2147483648, n = 2147483647) => { + if (typeof e != "number") + throw new D(t, "number", e); + if (!tr(e)) + throw new ge(t, "an integer", e); + if (e < r || e > n) + throw new ge(t, `>= ${r} && <= ${n}`, e); + }), Fn = W((e, t, r = false) => { + if (typeof e != "number") + throw new D(t, "number", e); + if (!tr(e)) + throw new ge(t, "an integer", e); + let n = r ? 1 : 0, i = 4294967295; + if (e < n || e > i) + throw new ge(t, `>= ${n} && <= ${i}`, e); + }); + function Mn(e, t) { + if (typeof e != "string") + throw new D(t, "string", e); + } + function Bu(e, t, r = undefined, n) { + if (typeof e != "number") + throw new D(t, "number", e); + if (r != null && e < r || n != null && e > n || (r != null || n != null) && fu(e)) + throw new ge(t, `${r != null ? `>= ${r}` : ""}${r != null && n != null ? " && " : ""}${n != null ? `<= ${n}` : ""}`, e); + } + var Lu = W((e, t, r) => { + if (!Ln(r, e)) { + let n = Nn(uu(r, (o) => typeof o == "string" ? `'${o}'` : pu(o)), ", "), i = "must be one of: " + n; + throw new at(t, e, i); + } + }); + function Nu(e, t) { + if (typeof e != "boolean") + throw new D(t, "boolean", e); + } + function er(e, t, r) { + return e == null || !du(e, t) ? r : e[t]; + } + var Fu = W((e, t, r = null) => { + let n = er(r, "allowArray", false), i = er(r, "allowFunction", false); + if (!er(r, "nullable", false) && e === null || !n && Bn(e) || typeof e != "object" && (!i || typeof e != "function")) + throw new D(t, "Object", e); + }), Mu = W((e, t, r = 0) => { + if (!Bn(e)) + throw new D(t, "Array", e); + if (e.length < r) { + let n = `must be longer than ${r}`; + throw new at(t, e, n); + } + }); + function Cu(e, t = "signal") { + if (Mn(e, t), Tn[e] === undefined) + throw Tn[yu(e)] !== undefined ? new In(e + " (signals must use all capital letters)") : new In(e); + } + var Ou = W((e, t = "buffer") => { + if (!Eu(e)) + throw new D(t, ["Buffer", "TypedArray", "DataView"], e); + }); + function Du(e, t) { + let r = gu(t), n = e.length; + if (r === "hex" && n % 2 !== 0) + throw new at("encoding", t, `is invalid for data of length ${n}`); + } + function Pu(e, t = "Port", r = true) { + if (typeof e != "number" && typeof e != "string" || typeof e == "string" && wu(e).length === 0 || +e !== +e >>> 0 || e > 65535 || e === 0 && !r) + throw new bu(t, e, r); + return e | 0; + } + var ku = W((e, t) => { + if (e !== undefined && (e === null || typeof e != "object" || !("aborted" in e))) + throw new D(t, "AbortSignal", e); + }), Uu = W((e, t) => { + if (typeof e != "function") + throw new D(t, "Function", e); + }), vu = W((e, t) => { + if (typeof e != "function" || _u(e)) + throw new D(t, "Function", e); + }), qu = W((e, t) => { + if (e !== undefined) + throw new D(t, "undefined", e); + }); + function Wu(e, t, r) { + if (!Ln(r, e)) + throw new D(t, `('${Nn(r, "|")}')`, e); + } + Cn.exports = { isInt32: Su, isUint32: mu, parseFileMode: Au, validateArray: Mu, validateBoolean: Nu, validateBuffer: Ou, validateEncoding: Du, validateFunction: Uu, validateInt32: Tu, validateInteger: Iu, validateNumber: Bu, validateObject: Fu, validateOneOf: Lu, validatePlainFunction: vu, validatePort: Pu, validateSignalName: Cu, validateString: Mn, validateUint32: Fn, validateUndefined: qu, validateUnion: Wu, validateAbortSignal: ku }; + }); + ir = E((zc, kn) => { + var x = kn.exports = {}, Y, K; + function rr() { + throw new Error("setTimeout has not been defined"); + } + function nr() { + throw new Error("clearTimeout has not been defined"); + } + (function() { + try { + typeof setTimeout == "function" ? Y = setTimeout : Y = rr; + } catch { + Y = rr; + } + try { + typeof clearTimeout == "function" ? K = clearTimeout : K = nr; + } catch { + K = nr; + } + })(); + function On(e) { + if (Y === setTimeout) + return setTimeout(e, 0); + if ((Y === rr || !Y) && setTimeout) + return Y = setTimeout, setTimeout(e, 0); + try { + return Y(e, 0); + } catch { + try { + return Y.call(null, e, 0); + } catch { + return Y.call(this, e, 0); + } + } + } + function $u(e) { + if (K === clearTimeout) + return clearTimeout(e); + if ((K === nr || !K) && clearTimeout) + return K = clearTimeout, clearTimeout(e); + try { + return K(e); + } catch { + try { + return K.call(null, e); + } catch { + return K.call(this, e); + } + } + } + var re = [], Me = false, _e, ct = -1; + function ju() { + !Me || !_e || (Me = false, _e.length ? re = _e.concat(re) : ct = -1, re.length && Dn()); + } + function Dn() { + if (!Me) { + var e = On(ju); + Me = true; + for (var t = re.length;t; ) { + for (_e = re, re = [];++ct < t; ) + _e && _e[ct].run(); + ct = -1, t = re.length; + } + _e = null, Me = false, $u(e); + } + } + x.nextTick = function(e) { + var t = new Array(arguments.length - 1); + if (arguments.length > 1) + for (var r = 1;r < arguments.length; r++) + t[r - 1] = arguments[r]; + re.push(new Pn(e, t)), re.length === 1 && !Me && On(Dn); + }; + function Pn(e, t) { + this.fun = e, this.array = t; + } + Pn.prototype.run = function() { + this.fun.apply(null, this.array); + }; + x.title = "browser"; + x.browser = true; + x.env = {}; + x.argv = []; + x.version = ""; + x.versions = {}; + function ne() { + } + x.on = ne; + x.addListener = ne; + x.once = ne; + x.off = ne; + x.removeListener = ne; + x.removeAllListeners = ne; + x.emit = ne; + x.prependListener = ne; + x.prependOnceListener = ne; + x.listeners = function(e) { + return []; + }; + x.binding = function(e) { + throw new Error("process.binding is not supported"); + }; + x.cwd = function() { + return "/"; + }; + x.chdir = function(e) { + throw new Error("process.chdir is not supported"); + }; + x.umask = function() { + return 0; + }; + }); + k = {}; + Qr(k, { default: () => Gu }); + se = yl(() => { + ue(k, rt(ir())); + Gu = rt(ir()); + }); + ae = E((Jc, zn) => { + var { Symbol: dt, SymbolAsyncIterator: Un, SymbolIterator: vn } = I(), qn = dt("kDestroyed"), Wn = dt("kIsErrored"), or = dt("kIsReadable"), $n = dt("kIsDisturbed"); + function ht(e, t = false) { + var r; + return !!(e && typeof e.pipe == "function" && typeof e.on == "function" && (!t || typeof e.pause == "function" && typeof e.resume == "function") && (!e._writableState || ((r = e._readableState) === null || r === undefined ? undefined : r.readable) !== false) && (!e._writableState || e._readableState)); + } + function pt(e) { + var t; + return !!(e && typeof e.write == "function" && typeof e.on == "function" && (!e._readableState || ((t = e._writableState) === null || t === undefined ? undefined : t.writable) !== false)); + } + function Hu(e) { + return !!(e && typeof e.pipe == "function" && e._readableState && typeof e.on == "function" && typeof e.write == "function"); + } + function Ee(e) { + return e && (e._readableState || e._writableState || typeof e.write == "function" && typeof e.on == "function" || typeof e.pipe == "function" && typeof e.on == "function"); + } + function Vu(e, t) { + return e == null ? false : t === true ? typeof e[Un] == "function" : t === false ? typeof e[vn] == "function" : typeof e[Un] == "function" || typeof e[vn] == "function"; + } + function yt(e) { + if (!Ee(e)) + return null; + let { _writableState: t, _readableState: r } = e, n = t || r; + return !!(e.destroyed || e[qn] || n != null && n.destroyed); + } + function jn(e) { + if (!pt(e)) + return null; + if (e.writableEnded === true) + return true; + let t = e._writableState; + return t != null && t.errored ? false : typeof t?.ended != "boolean" ? null : t.ended; + } + function Yu(e, t) { + if (!pt(e)) + return null; + if (e.writableFinished === true) + return true; + let r = e._writableState; + return r != null && r.errored ? false : typeof r?.finished != "boolean" ? null : !!(r.finished || t === false && r.ended === true && r.length === 0); + } + function Ku(e) { + if (!ht(e)) + return null; + if (e.readableEnded === true) + return true; + let t = e._readableState; + return !t || t.errored ? false : typeof t?.ended != "boolean" ? null : t.ended; + } + function Gn(e, t) { + if (!ht(e)) + return null; + let r = e._readableState; + return r != null && r.errored ? false : typeof r?.endEmitted != "boolean" ? null : !!(r.endEmitted || t === false && r.ended === true && r.length === 0); + } + function Hn(e) { + return e && e[or] != null ? e[or] : typeof e?.readable != "boolean" ? null : yt(e) ? false : ht(e) && e.readable && !Gn(e); + } + function Vn(e) { + return typeof e?.writable != "boolean" ? null : yt(e) ? false : pt(e) && e.writable && !jn(e); + } + function zu(e, t) { + return Ee(e) ? yt(e) ? true : !(t?.readable !== false && Hn(e) || t?.writable !== false && Vn(e)) : null; + } + function Xu(e) { + var t, r; + return Ee(e) ? e.writableErrored ? e.writableErrored : (t = (r = e._writableState) === null || r === undefined ? undefined : r.errored) !== null && t !== undefined ? t : null : null; + } + function Ju(e) { + var t, r; + return Ee(e) ? e.readableErrored ? e.readableErrored : (t = (r = e._readableState) === null || r === undefined ? undefined : r.errored) !== null && t !== undefined ? t : null : null; + } + function Qu(e) { + if (!Ee(e)) + return null; + if (typeof e.closed == "boolean") + return e.closed; + let { _writableState: t, _readableState: r } = e; + return typeof t?.closed == "boolean" || typeof r?.closed == "boolean" ? t?.closed || r?.closed : typeof e._closed == "boolean" && Yn(e) ? e._closed : null; + } + function Yn(e) { + return typeof e._closed == "boolean" && typeof e._defaultKeepAlive == "boolean" && typeof e._removedConnection == "boolean" && typeof e._removedContLen == "boolean"; + } + function Kn(e) { + return typeof e._sent100 == "boolean" && Yn(e); + } + function Zu(e) { + var t; + return typeof e._consuming == "boolean" && typeof e._dumped == "boolean" && ((t = e.req) === null || t === undefined ? undefined : t.upgradeOrConnect) === undefined; + } + function ef(e) { + if (!Ee(e)) + return null; + let { _writableState: t, _readableState: r } = e, n = t || r; + return !n && Kn(e) || !!(n && n.autoDestroy && n.emitClose && n.closed === false); + } + function tf(e) { + var t; + return !!(e && ((t = e[$n]) !== null && t !== undefined ? t : e.readableDidRead || e.readableAborted)); + } + function rf(e) { + var t, r, n, i, o, l, u, f, s, d; + return !!(e && ((t = (r = (n = (i = (o = (l = e[Wn]) !== null && l !== undefined ? l : e.readableErrored) !== null && o !== undefined ? o : e.writableErrored) !== null && i !== undefined ? i : (u = e._readableState) === null || u === undefined ? undefined : u.errorEmitted) !== null && n !== undefined ? n : (f = e._writableState) === null || f === undefined ? undefined : f.errorEmitted) !== null && r !== undefined ? r : (s = e._readableState) === null || s === undefined ? undefined : s.errored) !== null && t !== undefined ? t : (d = e._writableState) === null || d === undefined ? undefined : d.errored)); + } + zn.exports = { kDestroyed: qn, isDisturbed: tf, kIsDisturbed: $n, isErrored: rf, kIsErrored: Wn, isReadable: Hn, kIsReadable: or, isClosed: Qu, isDestroyed: yt, isDuplexNodeStream: Hu, isFinished: zu, isIterable: Vu, isReadableNodeStream: ht, isReadableEnded: Ku, isReadableFinished: Gn, isReadableErrored: Ju, isNodeStream: Ee, isWritable: Vn, isWritableNodeStream: pt, isWritableEnded: jn, isWritableFinished: Yu, isWritableErrored: Xu, isServerRequest: Zu, isServerResponse: Kn, willEmitClose: ef }; + }); + ce = E((Qc, ur) => { + var Ce = (se(), pe(k)), { AbortError: nf, codes: of } = C(), { ERR_INVALID_ARG_TYPE: lf, ERR_STREAM_PREMATURE_CLOSE: Xn } = of, { kEmptyObject: Jn, once: Qn } = V(), { validateAbortSignal: uf, validateFunction: ff, validateObject: sf } = He(), { Promise: af } = I(), { isClosed: cf, isReadable: Zn, isReadableNodeStream: lr, isReadableFinished: ei, isReadableErrored: df, isWritable: ti, isWritableNodeStream: ri, isWritableFinished: ni, isWritableErrored: hf, isNodeStream: pf, willEmitClose: yf } = ae(); + function wf(e) { + return e.setHeader && typeof e.abort == "function"; + } + var bf = () => { + }; + function ii(e, t, r) { + var n, i; + arguments.length === 2 ? (r = t, t = Jn) : t == null ? t = Jn : sf(t, "options"), ff(r, "callback"), uf(t.signal, "options.signal"), r = Qn(r); + let o = (n = t.readable) !== null && n !== undefined ? n : lr(e), l = (i = t.writable) !== null && i !== undefined ? i : ri(e); + if (!pf(e)) + throw new lf("stream", "Stream", e); + let { _writableState: u, _readableState: f } = e, s = () => { + e.writable || y(); + }, d = yf(e) && lr(e) === o && ri(e) === l, c = ni(e, false), y = () => { + c = true, e.destroyed && (d = false), !(d && (!e.readable || o)) && (!o || h) && r.call(e); + }, h = ei(e, false), p = () => { + h = true, e.destroyed && (d = false), !(d && (!e.writable || l)) && (!l || c) && r.call(e); + }, B = (N) => { + r.call(e, N); + }, v = cf(e), w = () => { + v = true; + let N = hf(e) || df(e); + if (N && typeof N != "boolean") + return r.call(e, N); + if (o && !h && lr(e, true) && !ei(e, false)) + return r.call(e, new Xn); + if (l && !c && !ni(e, false)) + return r.call(e, new Xn); + r.call(e); + }, b = () => { + e.req.on("finish", y); + }; + wf(e) ? (e.on("complete", y), d || e.on("abort", w), e.req ? b() : e.on("request", b)) : l && !u && (e.on("end", s), e.on("close", s)), !d && typeof e.aborted == "boolean" && e.on("aborted", w), e.on("end", p), e.on("finish", y), t.error !== false && e.on("error", B), e.on("close", w), v ? Ce.nextTick(w) : u != null && u.errorEmitted || f != null && f.errorEmitted ? d || Ce.nextTick(w) : (!o && (!d || Zn(e)) && (c || ti(e) === false) || !l && (!d || ti(e)) && (h || Zn(e) === false) || f && e.req && e.aborted) && Ce.nextTick(w); + let L = () => { + r = bf, e.removeListener("aborted", w), e.removeListener("complete", y), e.removeListener("abort", w), e.removeListener("request", b), e.req && e.req.removeListener("finish", y), e.removeListener("end", s), e.removeListener("close", s), e.removeListener("finish", y), e.removeListener("end", p), e.removeListener("error", B), e.removeListener("close", w); + }; + if (t.signal && !v) { + let N = () => { + let Q = r; + L(), Q.call(e, new nf(undefined, { cause: t.signal.reason })); + }; + if (t.signal.aborted) + Ce.nextTick(N); + else { + let Q = r; + r = Qn((...Ie) => { + t.signal.removeEventListener("abort", N), Q.apply(e, Ie); + }), t.signal.addEventListener("abort", N); + } + } + return L; + } + function gf(e, t) { + return new af((r, n) => { + ii(e, t, (i) => { + i ? n(i) : r(); + }); + }); + } + ur.exports = ii; + ur.exports.finished = gf; + }); + di = E((Zc, ar) => { + var fi = globalThis.AbortController || ut().AbortController, { codes: { ERR_INVALID_ARG_TYPE: Ve, ERR_MISSING_ARGS: _f, ERR_OUT_OF_RANGE: Ef }, AbortError: z } = C(), { validateAbortSignal: Oe, validateInteger: Sf, validateObject: De } = He(), mf = I().Symbol("kWeak"), { finished: xf } = ce(), { ArrayPrototypePush: Rf, MathFloor: Af, Number: If, NumberIsNaN: Tf, Promise: oi, PromiseReject: li, PromisePrototypeThen: Bf, Symbol: si } = I(), wt = si("kEmpty"), ui = si("kEof"); + function bt(e, t) { + if (typeof e != "function") + throw new Ve("fn", ["Function", "AsyncFunction"], e); + t != null && De(t, "options"), t?.signal != null && Oe(t.signal, "options.signal"); + let r = 1; + return t?.concurrency != null && (r = Af(t.concurrency)), Sf(r, "concurrency", 1), async function* () { + var i, o; + let l = new fi, u = this, f = [], s = l.signal, d = { signal: s }, c = () => l.abort(); + t != null && (i = t.signal) !== null && i !== undefined && i.aborted && c(), t == null || (o = t.signal) === null || o === undefined || o.addEventListener("abort", c); + let y, h, p = false; + function B() { + p = true; + } + async function v() { + try { + for await (let L of u) { + var w; + if (p) + return; + if (s.aborted) + throw new z; + try { + L = e(L, d); + } catch (N) { + L = li(N); + } + L !== wt && (typeof ((w = L) === null || w === undefined ? undefined : w.catch) == "function" && L.catch(B), f.push(L), y && (y(), y = null), !p && f.length && f.length >= r && await new oi((N) => { + h = N; + })); + } + f.push(ui); + } catch (L) { + let N = li(L); + Bf(N, undefined, B), f.push(N); + } finally { + var b; + p = true, y && (y(), y = null), t == null || (b = t.signal) === null || b === undefined || b.removeEventListener("abort", c); + } + } + v(); + try { + for (;; ) { + for (;f.length > 0; ) { + let w = await f[0]; + if (w === ui) + return; + if (s.aborted) + throw new z; + w !== wt && (yield w), f.shift(), h && (h(), h = null); + } + await new oi((w) => { + y = w; + }); + } + } finally { + l.abort(), p = true, h && (h(), h = null); + } + }.call(this); + } + function Lf(e = undefined) { + return e != null && De(e, "options"), e?.signal != null && Oe(e.signal, "options.signal"), async function* () { + let r = 0; + for await (let i of this) { + var n; + if (e != null && (n = e.signal) !== null && n !== undefined && n.aborted) + throw new z({ cause: e.signal.reason }); + yield [r++, i]; + } + }.call(this); + } + async function ai(e, t = undefined) { + for await (let r of sr.call(this, e, t)) + return true; + return false; + } + async function Nf(e, t = undefined) { + if (typeof e != "function") + throw new Ve("fn", ["Function", "AsyncFunction"], e); + return !await ai.call(this, async (...r) => !await e(...r), t); + } + async function Ff(e, t) { + for await (let r of sr.call(this, e, t)) + return r; + } + async function Mf(e, t) { + if (typeof e != "function") + throw new Ve("fn", ["Function", "AsyncFunction"], e); + async function r(n, i) { + return await e(n, i), wt; + } + for await (let n of bt.call(this, r, t)) + ; + } + function sr(e, t) { + if (typeof e != "function") + throw new Ve("fn", ["Function", "AsyncFunction"], e); + async function r(n, i) { + return await e(n, i) ? n : wt; + } + return bt.call(this, r, t); + } + var fr = class extends _f { + constructor() { + super("reduce"), this.message = "Reduce of an empty stream requires an initial value"; + } + }; + async function Cf(e, t, r) { + var n; + if (typeof e != "function") + throw new Ve("reducer", ["Function", "AsyncFunction"], e); + r != null && De(r, "options"), r?.signal != null && Oe(r.signal, "options.signal"); + let i = arguments.length > 1; + if (r != null && (n = r.signal) !== null && n !== undefined && n.aborted) { + let s = new z(undefined, { cause: r.signal.reason }); + throw this.once("error", () => { + }), await xf(this.destroy(s)), s; + } + let o = new fi, l = o.signal; + if (r != null && r.signal) { + let s = { once: true, [mf]: this }; + r.signal.addEventListener("abort", () => o.abort(), s); + } + let u = false; + try { + for await (let s of this) { + var f; + if (u = true, r != null && (f = r.signal) !== null && f !== undefined && f.aborted) + throw new z; + i ? t = await e(t, s, { signal: l }) : (t = s, i = true); + } + if (!u && !i) + throw new fr; + } finally { + o.abort(); + } + return t; + } + async function Of(e) { + e != null && De(e, "options"), e?.signal != null && Oe(e.signal, "options.signal"); + let t = []; + for await (let n of this) { + var r; + if (e != null && (r = e.signal) !== null && r !== undefined && r.aborted) + throw new z(undefined, { cause: e.signal.reason }); + Rf(t, n); + } + return t; + } + function Df(e, t) { + let r = bt.call(this, e, t); + return async function* () { + for await (let i of r) + yield* i; + }.call(this); + } + function ci(e) { + if (e = If(e), Tf(e)) + return 0; + if (e < 0) + throw new Ef("number", ">= 0", e); + return e; + } + function Pf(e, t = undefined) { + return t != null && De(t, "options"), t?.signal != null && Oe(t.signal, "options.signal"), e = ci(e), async function* () { + var n; + if (t != null && (n = t.signal) !== null && n !== undefined && n.aborted) + throw new z; + for await (let o of this) { + var i; + if (t != null && (i = t.signal) !== null && i !== undefined && i.aborted) + throw new z; + e-- <= 0 && (yield o); + } + }.call(this); + } + function kf(e, t = undefined) { + return t != null && De(t, "options"), t?.signal != null && Oe(t.signal, "options.signal"), e = ci(e), async function* () { + var n; + if (t != null && (n = t.signal) !== null && n !== undefined && n.aborted) + throw new z; + for await (let o of this) { + var i; + if (t != null && (i = t.signal) !== null && i !== undefined && i.aborted) + throw new z; + if (e-- > 0) + yield o; + else + return; + } + }.call(this); + } + ar.exports.streamReturningOperators = { asIndexedPairs: Lf, drop: Pf, filter: sr, flatMap: Df, map: bt, take: kf }; + ar.exports.promiseReturningOperators = { every: Nf, forEach: Mf, reduce: Cf, toArray: Of, some: ai, find: Ff }; + }); + Se = E((ed, Ei) => { + var de = (se(), pe(k)), { aggregateTwoErrors: Uf, codes: { ERR_MULTIPLE_CALLBACK: vf }, AbortError: qf } = C(), { Symbol: yi } = I(), { kDestroyed: Wf, isDestroyed: $f, isFinished: jf, isServerRequest: Gf } = ae(), wi = yi("kDestroy"), cr = yi("kConstruct"); + function bi(e, t, r) { + e && (e.stack, t && !t.errored && (t.errored = e), r && !r.errored && (r.errored = e)); + } + function Hf(e, t) { + let r = this._readableState, n = this._writableState, i = n || r; + return n && n.destroyed || r && r.destroyed ? (typeof t == "function" && t(), this) : (bi(e, n, r), n && (n.destroyed = true), r && (r.destroyed = true), i.constructed ? hi(this, e, t) : this.once(wi, function(o) { + hi(this, Uf(o, e), t); + }), this); + } + function hi(e, t, r) { + let n = false; + function i(o) { + if (n) + return; + n = true; + let { _readableState: l, _writableState: u } = e; + bi(o, u, l), u && (u.closed = true), l && (l.closed = true), typeof r == "function" && r(o), o ? de.nextTick(Vf, e, o) : de.nextTick(gi, e); + } + try { + e._destroy(t || null, i); + } catch (o) { + i(o); + } + } + function Vf(e, t) { + dr(e, t), gi(e); + } + function gi(e) { + let { _readableState: t, _writableState: r } = e; + r && (r.closeEmitted = true), t && (t.closeEmitted = true), (r && r.emitClose || t && t.emitClose) && e.emit("close"); + } + function dr(e, t) { + let { _readableState: r, _writableState: n } = e; + n && n.errorEmitted || r && r.errorEmitted || (n && (n.errorEmitted = true), r && (r.errorEmitted = true), e.emit("error", t)); + } + function Yf() { + let e = this._readableState, t = this._writableState; + e && (e.constructed = true, e.closed = false, e.closeEmitted = false, e.destroyed = false, e.errored = null, e.errorEmitted = false, e.reading = false, e.ended = e.readable === false, e.endEmitted = e.readable === false), t && (t.constructed = true, t.destroyed = false, t.closed = false, t.closeEmitted = false, t.errored = null, t.errorEmitted = false, t.finalCalled = false, t.prefinished = false, t.ended = t.writable === false, t.ending = t.writable === false, t.finished = t.writable === false); + } + function hr(e, t, r) { + let { _readableState: n, _writableState: i } = e; + if (i && i.destroyed || n && n.destroyed) + return this; + n && n.autoDestroy || i && i.autoDestroy ? e.destroy(t) : t && (t.stack, i && !i.errored && (i.errored = t), n && !n.errored && (n.errored = t), r ? de.nextTick(dr, e, t) : dr(e, t)); + } + function Kf(e, t) { + if (typeof e._construct != "function") + return; + let { _readableState: r, _writableState: n } = e; + r && (r.constructed = false), n && (n.constructed = false), e.once(cr, t), !(e.listenerCount(cr) > 1) && de.nextTick(zf, e); + } + function zf(e) { + let t = false; + function r(n) { + if (t) { + hr(e, n ?? new vf); + return; + } + t = true; + let { _readableState: i, _writableState: o } = e, l = o || i; + i && (i.constructed = true), o && (o.constructed = true), l.destroyed ? e.emit(wi, n) : n ? hr(e, n, true) : de.nextTick(Xf, e); + } + try { + e._construct(r); + } catch (n) { + r(n); + } + } + function Xf(e) { + e.emit(cr); + } + function pi(e) { + return e && e.setHeader && typeof e.abort == "function"; + } + function _i(e) { + e.emit("close"); + } + function Jf(e, t) { + e.emit("error", t), de.nextTick(_i, e); + } + function Qf(e, t) { + !e || $f(e) || (!t && !jf(e) && (t = new qf), Gf(e) ? (e.socket = null, e.destroy(t)) : pi(e) ? e.abort() : pi(e.req) ? e.req.abort() : typeof e.destroy == "function" ? e.destroy(t) : typeof e.close == "function" ? e.close() : t ? de.nextTick(Jf, e, t) : de.nextTick(_i, e), e.destroyed || (e[Wf] = true)); + } + Ei.exports = { construct: Kf, destroyer: Qf, destroy: Hf, undestroy: Yf, errorOrDestroy: hr }; + }); + Et = E((td, pr) => { + var Pe = typeof Reflect == "object" ? Reflect : null, Si = Pe && typeof Pe.apply == "function" ? Pe.apply : function(t, r, n) { + return Function.prototype.apply.call(t, r, n); + }, gt; + Pe && typeof Pe.ownKeys == "function" ? gt = Pe.ownKeys : Object.getOwnPropertySymbols ? gt = function(t) { + return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t)); + } : gt = function(t) { + return Object.getOwnPropertyNames(t); + }; + function Zf(e) { + console && console.warn && console.warn(e); + } + var xi = Number.isNaN || function(t) { + return t !== t; + }; + function S() { + S.init.call(this); + } + pr.exports = S; + pr.exports.once = ns; + S.EventEmitter = S; + S.prototype._events = undefined; + S.prototype._eventsCount = 0; + S.prototype._maxListeners = undefined; + var mi = 10; + function _t(e) { + if (typeof e != "function") + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof e); + } + Object.defineProperty(S, "defaultMaxListeners", { enumerable: true, get: function() { + return mi; + }, set: function(e) { + if (typeof e != "number" || e < 0 || xi(e)) + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + e + "."); + mi = e; + } }); + S.init = function() { + (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) && (this._events = Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || undefined; + }; + S.prototype.setMaxListeners = function(t) { + if (typeof t != "number" || t < 0 || xi(t)) + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + t + "."); + return this._maxListeners = t, this; + }; + function Ri(e) { + return e._maxListeners === undefined ? S.defaultMaxListeners : e._maxListeners; + } + S.prototype.getMaxListeners = function() { + return Ri(this); + }; + S.prototype.emit = function(t) { + for (var r = [], n = 1;n < arguments.length; n++) + r.push(arguments[n]); + var i = t === "error", o = this._events; + if (o !== undefined) + i = i && o.error === undefined; + else if (!i) + return false; + if (i) { + var l; + if (r.length > 0 && (l = r[0]), l instanceof Error) + throw l; + var u = new Error("Unhandled error." + (l ? " (" + l.message + ")" : "")); + throw u.context = l, u; + } + var f = o[t]; + if (f === undefined) + return false; + if (typeof f == "function") + Si(f, this, r); + else + for (var s = f.length, d = Li(f, s), n = 0;n < s; ++n) + Si(d[n], this, r); + return true; + }; + function Ai(e, t, r, n) { + var i, o, l; + if (_t(r), o = e._events, o === undefined ? (o = e._events = Object.create(null), e._eventsCount = 0) : (o.newListener !== undefined && (e.emit("newListener", t, r.listener ? r.listener : r), o = e._events), l = o[t]), l === undefined) + l = o[t] = r, ++e._eventsCount; + else if (typeof l == "function" ? l = o[t] = n ? [r, l] : [l, r] : n ? l.unshift(r) : l.push(r), i = Ri(e), i > 0 && l.length > i && !l.warned) { + l.warned = true; + var u = new Error("Possible EventEmitter memory leak detected. " + l.length + " " + String(t) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + u.name = "MaxListenersExceededWarning", u.emitter = e, u.type = t, u.count = l.length, Zf(u); + } + return e; + } + S.prototype.addListener = function(t, r) { + return Ai(this, t, r, false); + }; + S.prototype.on = S.prototype.addListener; + S.prototype.prependListener = function(t, r) { + return Ai(this, t, r, true); + }; + function es() { + if (!this.fired) + return this.target.removeListener(this.type, this.wrapFn), this.fired = true, arguments.length === 0 ? this.listener.call(this.target) : this.listener.apply(this.target, arguments); + } + function Ii(e, t, r) { + var n = { fired: false, wrapFn: undefined, target: e, type: t, listener: r }, i = es.bind(n); + return i.listener = r, n.wrapFn = i, i; + } + S.prototype.once = function(t, r) { + return _t(r), this.on(t, Ii(this, t, r)), this; + }; + S.prototype.prependOnceListener = function(t, r) { + return _t(r), this.prependListener(t, Ii(this, t, r)), this; + }; + S.prototype.removeListener = function(t, r) { + var n, i, o, l, u; + if (_t(r), i = this._events, i === undefined) + return this; + if (n = i[t], n === undefined) + return this; + if (n === r || n.listener === r) + --this._eventsCount === 0 ? this._events = Object.create(null) : (delete i[t], i.removeListener && this.emit("removeListener", t, n.listener || r)); + else if (typeof n != "function") { + for (o = -1, l = n.length - 1;l >= 0; l--) + if (n[l] === r || n[l].listener === r) { + u = n[l].listener, o = l; + break; + } + if (o < 0) + return this; + o === 0 ? n.shift() : ts(n, o), n.length === 1 && (i[t] = n[0]), i.removeListener !== undefined && this.emit("removeListener", t, u || r); + } + return this; + }; + S.prototype.off = S.prototype.removeListener; + S.prototype.removeAllListeners = function(t) { + var r, n, i; + if (n = this._events, n === undefined) + return this; + if (n.removeListener === undefined) + return arguments.length === 0 ? (this._events = Object.create(null), this._eventsCount = 0) : n[t] !== undefined && (--this._eventsCount === 0 ? this._events = Object.create(null) : delete n[t]), this; + if (arguments.length === 0) { + var o = Object.keys(n), l; + for (i = 0;i < o.length; ++i) + l = o[i], l !== "removeListener" && this.removeAllListeners(l); + return this.removeAllListeners("removeListener"), this._events = Object.create(null), this._eventsCount = 0, this; + } + if (r = n[t], typeof r == "function") + this.removeListener(t, r); + else if (r !== undefined) + for (i = r.length - 1;i >= 0; i--) + this.removeListener(t, r[i]); + return this; + }; + function Ti(e, t, r) { + var n = e._events; + if (n === undefined) + return []; + var i = n[t]; + return i === undefined ? [] : typeof i == "function" ? r ? [i.listener || i] : [i] : r ? rs(i) : Li(i, i.length); + } + S.prototype.listeners = function(t) { + return Ti(this, t, true); + }; + S.prototype.rawListeners = function(t) { + return Ti(this, t, false); + }; + S.listenerCount = function(e, t) { + return typeof e.listenerCount == "function" ? e.listenerCount(t) : Bi.call(e, t); + }; + S.prototype.listenerCount = Bi; + function Bi(e) { + var t = this._events; + if (t !== undefined) { + var r = t[e]; + if (typeof r == "function") + return 1; + if (r !== undefined) + return r.length; + } + return 0; + } + S.prototype.eventNames = function() { + return this._eventsCount > 0 ? gt(this._events) : []; + }; + function Li(e, t) { + for (var r = new Array(t), n = 0;n < t; ++n) + r[n] = e[n]; + return r; + } + function ts(e, t) { + for (;t + 1 < e.length; t++) + e[t] = e[t + 1]; + e.pop(); + } + function rs(e) { + for (var t = new Array(e.length), r = 0;r < t.length; ++r) + t[r] = e[r].listener || e[r]; + return t; + } + function ns(e, t) { + return new Promise(function(r, n) { + function i(l) { + e.removeListener(t, o), n(l); + } + function o() { + typeof e.removeListener == "function" && e.removeListener("error", i), r([].slice.call(arguments)); + } + Ni(e, t, o, { once: true }), t !== "error" && is(e, i, { once: true }); + }); + } + function is(e, t, r) { + typeof e.on == "function" && Ni(e, "error", t, r); + } + function Ni(e, t, r, n) { + if (typeof e.on == "function") + n.once ? e.once(t, r) : e.on(t, r); + else if (typeof e.addEventListener == "function") + e.addEventListener(t, function i(o) { + n.once && e.removeEventListener(t, i), r(o); + }); + else + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof e); + } + }); + xt = E((rd, Mi) => { + var { ArrayIsArray: os, ObjectSetPrototypeOf: Fi } = I(), { EventEmitter: St } = Et(); + function mt(e) { + St.call(this, e); + } + Fi(mt.prototype, St.prototype); + Fi(mt, St); + mt.prototype.pipe = function(e, t) { + let r = this; + function n(d) { + e.writable && e.write(d) === false && r.pause && r.pause(); + } + r.on("data", n); + function i() { + r.readable && r.resume && r.resume(); + } + e.on("drain", i), !e._isStdio && (!t || t.end !== false) && (r.on("end", l), r.on("close", u)); + let o = false; + function l() { + o || (o = true, e.end()); + } + function u() { + o || (o = true, typeof e.destroy == "function" && e.destroy()); + } + function f(d) { + s(), St.listenerCount(this, "error") === 0 && this.emit("error", d); + } + yr(r, "error", f), yr(e, "error", f); + function s() { + r.removeListener("data", n), e.removeListener("drain", i), r.removeListener("end", l), r.removeListener("close", u), r.removeListener("error", f), e.removeListener("error", f), r.removeListener("end", s), r.removeListener("close", s), e.removeListener("close", s); + } + return r.on("end", s), r.on("close", s), e.on("close", s), e.emit("pipe", r), e; + }; + function yr(e, t, r) { + if (typeof e.prependListener == "function") + return e.prependListener(t, r); + !e._events || !e._events[t] ? e.on(t, r) : os(e._events[t]) ? e._events[t].unshift(r) : e._events[t] = [r, e._events[t]]; + } + Mi.exports = { Stream: mt, prependListener: yr }; + }); + At = E((nd, Rt) => { + var { AbortError: ls, codes: us } = C(), fs = ce(), { ERR_INVALID_ARG_TYPE: Ci } = us, ss = (e, t) => { + if (typeof e != "object" || !("aborted" in e)) + throw new Ci(t, "AbortSignal", e); + }; + function as(e) { + return !!(e && typeof e.pipe == "function"); + } + Rt.exports.addAbortSignal = function(t, r) { + if (ss(t, "signal"), !as(r)) + throw new Ci("stream", "stream.Stream", r); + return Rt.exports.addAbortSignalNoValidate(t, r); + }; + Rt.exports.addAbortSignalNoValidate = function(e, t) { + if (typeof e != "object" || !("aborted" in e)) + return t; + let r = () => { + t.destroy(new ls(undefined, { cause: e.reason })); + }; + return e.aborted ? r() : (e.addEventListener("abort", r), fs(t, () => e.removeEventListener("abort", r))), t; + }; + }); + Pi = E((od, Di) => { + var { StringPrototypeSlice: Oi, SymbolIterator: cs, TypedArrayPrototypeSet: It, Uint8Array: ds } = I(), { Buffer: wr } = te(), { inspect: hs } = V(); + Di.exports = class { + constructor() { + this.head = null, this.tail = null, this.length = 0; + } + push(t) { + let r = { data: t, next: null }; + this.length > 0 ? this.tail.next = r : this.head = r, this.tail = r, ++this.length; + } + unshift(t) { + let r = { data: t, next: this.head }; + this.length === 0 && (this.tail = r), this.head = r, ++this.length; + } + shift() { + if (this.length === 0) + return; + let t = this.head.data; + return this.length === 1 ? this.head = this.tail = null : this.head = this.head.next, --this.length, t; + } + clear() { + this.head = this.tail = null, this.length = 0; + } + join(t) { + if (this.length === 0) + return ""; + let r = this.head, n = "" + r.data; + for (;(r = r.next) !== null; ) + n += t + r.data; + return n; + } + concat(t) { + if (this.length === 0) + return wr.alloc(0); + let r = wr.allocUnsafe(t >>> 0), n = this.head, i = 0; + for (;n; ) + It(r, n.data, i), i += n.data.length, n = n.next; + return r; + } + consume(t, r) { + let n = this.head.data; + if (t < n.length) { + let i = n.slice(0, t); + return this.head.data = n.slice(t), i; + } + return t === n.length ? this.shift() : r ? this._getString(t) : this._getBuffer(t); + } + first() { + return this.head.data; + } + *[cs]() { + for (let t = this.head;t; t = t.next) + yield t.data; + } + _getString(t) { + let r = "", n = this.head, i = 0; + do { + let o = n.data; + if (t > o.length) + r += o, t -= o.length; + else { + t === o.length ? (r += o, ++i, n.next ? this.head = n.next : this.head = this.tail = null) : (r += Oi(o, 0, t), this.head = n, n.data = Oi(o, t)); + break; + } + ++i; + } while ((n = n.next) !== null); + return this.length -= i, r; + } + _getBuffer(t) { + let r = wr.allocUnsafe(t), n = t, i = this.head, o = 0; + do { + let l = i.data; + if (t > l.length) + It(r, l, n - t), t -= l.length; + else { + t === l.length ? (It(r, l, n - t), ++o, i.next ? this.head = i.next : this.head = this.tail = null) : (It(r, new ds(l.buffer, l.byteOffset, t), n - t), this.head = i, i.data = l.slice(t)); + break; + } + ++o; + } while ((i = i.next) !== null); + return this.length -= o, r; + } + [Symbol.for("nodejs.util.inspect.custom")](t, r) { + return hs(this, { ...r, depth: 0, customInspect: false }); + } + }; + }); + Tt = E((ld, Ui) => { + var { MathFloor: ps, NumberIsInteger: ys } = I(), { ERR_INVALID_ARG_VALUE: ws } = C().codes; + function bs(e, t, r) { + return e.highWaterMark != null ? e.highWaterMark : t ? e[r] : null; + } + function ki(e) { + return e ? 16 : 16 * 1024; + } + function gs(e, t, r, n) { + let i = bs(t, n, r); + if (i != null) { + if (!ys(i) || i < 0) { + let o = n ? `options.${r}` : "options.highWaterMark"; + throw new ws(o, i); + } + return ps(i); + } + return ki(e.objectMode); + } + Ui.exports = { getHighWaterMark: gs, getDefaultHighWaterMark: ki }; + }); + Wi = E((br, qi) => { + var Bt = te(), X = Bt.Buffer; + function vi(e, t) { + for (var r in e) + t[r] = e[r]; + } + X.from && X.alloc && X.allocUnsafe && X.allocUnsafeSlow ? qi.exports = Bt : (vi(Bt, br), br.Buffer = me); + function me(e, t, r) { + return X(e, t, r); + } + me.prototype = Object.create(X.prototype); + vi(X, me); + me.from = function(e, t, r) { + if (typeof e == "number") + throw new TypeError("Argument must not be a number"); + return X(e, t, r); + }; + me.alloc = function(e, t, r) { + if (typeof e != "number") + throw new TypeError("Argument must be a number"); + var n = X(e); + return t !== undefined ? typeof r == "string" ? n.fill(t, r) : n.fill(t) : n.fill(0), n; + }; + me.allocUnsafe = function(e) { + if (typeof e != "number") + throw new TypeError("Argument must be a number"); + return X(e); + }; + me.allocUnsafeSlow = function(e) { + if (typeof e != "number") + throw new TypeError("Argument must be a number"); + return Bt.SlowBuffer(e); + }; + }); + Gi = E((ji) => { + var _r = Wi().Buffer, $i = _r.isEncoding || function(e) { + switch (e = "" + e, e && e.toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + case "raw": + return true; + default: + return false; + } + }; + function _s(e) { + if (!e) + return "utf8"; + for (var t;; ) + switch (e) { + case "utf8": + case "utf-8": + return "utf8"; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return "utf16le"; + case "latin1": + case "binary": + return "latin1"; + case "base64": + case "ascii": + case "hex": + return e; + default: + if (t) + return; + e = ("" + e).toLowerCase(), t = true; + } + } + function Es(e) { + var t = _s(e); + if (typeof t != "string" && (_r.isEncoding === $i || !$i(e))) + throw new Error("Unknown encoding: " + e); + return t || e; + } + ji.StringDecoder = Ye; + function Ye(e) { + this.encoding = Es(e); + var t; + switch (this.encoding) { + case "utf16le": + this.text = Is, this.end = Ts, t = 4; + break; + case "utf8": + this.fillLast = xs, t = 4; + break; + case "base64": + this.text = Bs, this.end = Ls, t = 3; + break; + default: + this.write = Ns, this.end = Fs; + return; + } + this.lastNeed = 0, this.lastTotal = 0, this.lastChar = _r.allocUnsafe(t); + } + Ye.prototype.write = function(e) { + if (e.length === 0) + return ""; + var t, r; + if (this.lastNeed) { + if (t = this.fillLast(e), t === undefined) + return ""; + r = this.lastNeed, this.lastNeed = 0; + } else + r = 0; + return r < e.length ? t ? t + this.text(e, r) : this.text(e, r) : t || ""; + }; + Ye.prototype.end = As; + Ye.prototype.text = Rs; + Ye.prototype.fillLast = function(e) { + if (this.lastNeed <= e.length) + return e.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal); + e.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, e.length), this.lastNeed -= e.length; + }; + function gr(e) { + return e <= 127 ? 0 : e >> 5 === 6 ? 2 : e >> 4 === 14 ? 3 : e >> 3 === 30 ? 4 : e >> 6 === 2 ? -1 : -2; + } + function Ss(e, t, r) { + var n = t.length - 1; + if (n < r) + return 0; + var i = gr(t[n]); + return i >= 0 ? (i > 0 && (e.lastNeed = i - 1), i) : --n < r || i === -2 ? 0 : (i = gr(t[n]), i >= 0 ? (i > 0 && (e.lastNeed = i - 2), i) : --n < r || i === -2 ? 0 : (i = gr(t[n]), i >= 0 ? (i > 0 && (i === 2 ? i = 0 : e.lastNeed = i - 3), i) : 0)); + } + function ms(e, t, r) { + if ((t[0] & 192) !== 128) + return e.lastNeed = 0, "�"; + if (e.lastNeed > 1 && t.length > 1) { + if ((t[1] & 192) !== 128) + return e.lastNeed = 1, "�"; + if (e.lastNeed > 2 && t.length > 2 && (t[2] & 192) !== 128) + return e.lastNeed = 2, "�"; + } + } + function xs(e) { + var t = this.lastTotal - this.lastNeed, r = ms(this, e, t); + if (r !== undefined) + return r; + if (this.lastNeed <= e.length) + return e.copy(this.lastChar, t, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal); + e.copy(this.lastChar, t, 0, e.length), this.lastNeed -= e.length; + } + function Rs(e, t) { + var r = Ss(this, e, t); + if (!this.lastNeed) + return e.toString("utf8", t); + this.lastTotal = r; + var n = e.length - (r - this.lastNeed); + return e.copy(this.lastChar, 0, n), e.toString("utf8", t, n); + } + function As(e) { + var t = e && e.length ? this.write(e) : ""; + return this.lastNeed ? t + "�" : t; + } + function Is(e, t) { + if ((e.length - t) % 2 === 0) { + var r = e.toString("utf16le", t); + if (r) { + var n = r.charCodeAt(r.length - 1); + if (n >= 55296 && n <= 56319) + return this.lastNeed = 2, this.lastTotal = 4, this.lastChar[0] = e[e.length - 2], this.lastChar[1] = e[e.length - 1], r.slice(0, -1); + } + return r; + } + return this.lastNeed = 1, this.lastTotal = 2, this.lastChar[0] = e[e.length - 1], e.toString("utf16le", t, e.length - 1); + } + function Ts(e) { + var t = e && e.length ? this.write(e) : ""; + if (this.lastNeed) { + var r = this.lastTotal - this.lastNeed; + return t + this.lastChar.toString("utf16le", 0, r); + } + return t; + } + function Bs(e, t) { + var r = (e.length - t) % 3; + return r === 0 ? e.toString("base64", t) : (this.lastNeed = 3 - r, this.lastTotal = 3, r === 1 ? this.lastChar[0] = e[e.length - 1] : (this.lastChar[0] = e[e.length - 2], this.lastChar[1] = e[e.length - 1]), e.toString("base64", t, e.length - r)); + } + function Ls(e) { + var t = e && e.length ? this.write(e) : ""; + return this.lastNeed ? t + this.lastChar.toString("base64", 0, 3 - this.lastNeed) : t; + } + function Ns(e) { + return e.toString(this.encoding); + } + function Fs(e) { + return e && e.length ? this.write(e) : ""; + } + }); + Er = E((fd, Ki) => { + var Hi = (se(), pe(k)), { PromisePrototypeThen: Ms, SymbolAsyncIterator: Vi, SymbolIterator: Yi } = I(), { Buffer: Cs } = te(), { ERR_INVALID_ARG_TYPE: Os, ERR_STREAM_NULL_VALUES: Ds } = C().codes; + function Ps(e, t, r) { + let n; + if (typeof t == "string" || t instanceof Cs) + return new e({ objectMode: true, ...r, read() { + this.push(t), this.push(null); + } }); + let i; + if (t && t[Vi]) + i = true, n = t[Vi](); + else if (t && t[Yi]) + i = false, n = t[Yi](); + else + throw new Os("iterable", ["Iterable"], t); + let o = new e({ objectMode: true, highWaterMark: 1, ...r }), l = false; + o._read = function() { + l || (l = true, f()); + }, o._destroy = function(s, d) { + Ms(u(s), () => Hi.nextTick(d, s), (c) => Hi.nextTick(d, c || s)); + }; + async function u(s) { + let d = s != null, c = typeof n.throw == "function"; + if (d && c) { + let { value: y, done: h } = await n.throw(s); + if (await y, h) + return; + } + if (typeof n.return == "function") { + let { value: y } = await n.return(); + await y; + } + } + async function f() { + for (;; ) { + try { + let { value: s, done: d } = i ? await n.next() : n.next(); + if (d) + o.push(null); + else { + let c = s && typeof s.then == "function" ? await s : s; + if (c === null) + throw l = false, new Ds; + if (o.push(c)) + continue; + l = false; + } + } catch (s) { + o.destroy(s); + } + break; + } + } + return o; + } + Ki.exports = Ps; + }); + Ke = E((sd, uo) => { + var $ = (se(), pe(k)), { ArrayPrototypeIndexOf: ks, NumberIsInteger: Us, NumberIsNaN: vs, NumberParseInt: qs, ObjectDefineProperties: Ji, ObjectKeys: Ws, ObjectSetPrototypeOf: Qi, Promise: $s, SafeSet: js, SymbolAsyncIterator: Gs, Symbol: Hs } = I(); + uo.exports = g; + g.ReadableState = Ir; + var { EventEmitter: Vs } = Et(), { Stream: he, prependListener: Ys } = xt(), { Buffer: Sr } = te(), { addAbortSignal: Ks } = At(), zs = ce(), _ = V().debuglog("stream", (e) => { + _ = e; + }), Xs = Pi(), Ue = Se(), { getHighWaterMark: Js, getDefaultHighWaterMark: Qs } = Tt(), { aggregateTwoErrors: zi, codes: { ERR_INVALID_ARG_TYPE: Zs, ERR_METHOD_NOT_IMPLEMENTED: ea, ERR_OUT_OF_RANGE: ta, ERR_STREAM_PUSH_AFTER_EOF: ra, ERR_STREAM_UNSHIFT_AFTER_END_EVENT: na } } = C(), { validateObject: ia } = He(), xe = Hs("kPaused"), { StringDecoder: Zi } = Gi(), oa = Er(); + Qi(g.prototype, he.prototype); + Qi(g, he); + var mr = () => { + }, { errorOrDestroy: ke } = Ue; + function Ir(e, t, r) { + typeof r != "boolean" && (r = t instanceof J()), this.objectMode = !!(e && e.objectMode), r && (this.objectMode = this.objectMode || !!(e && e.readableObjectMode)), this.highWaterMark = e ? Js(this, e, "readableHighWaterMark", r) : Qs(false), this.buffer = new Xs, this.length = 0, this.pipes = [], this.flowing = null, this.ended = false, this.endEmitted = false, this.reading = false, this.constructed = true, this.sync = true, this.needReadable = false, this.emittedReadable = false, this.readableListening = false, this.resumeScheduled = false, this[xe] = null, this.errorEmitted = false, this.emitClose = !e || e.emitClose !== false, this.autoDestroy = !e || e.autoDestroy !== false, this.destroyed = false, this.errored = null, this.closed = false, this.closeEmitted = false, this.defaultEncoding = e && e.defaultEncoding || "utf8", this.awaitDrainWriters = null, this.multiAwaitDrain = false, this.readingMore = false, this.dataEmitted = false, this.decoder = null, this.encoding = null, e && e.encoding && (this.decoder = new Zi(e.encoding), this.encoding = e.encoding); + } + function g(e) { + if (!(this instanceof g)) + return new g(e); + let t = this instanceof J(); + this._readableState = new Ir(e, this, t), e && (typeof e.read == "function" && (this._read = e.read), typeof e.destroy == "function" && (this._destroy = e.destroy), typeof e.construct == "function" && (this._construct = e.construct), e.signal && !t && Ks(e.signal, this)), he.call(this, e), Ue.construct(this, () => { + this._readableState.needReadable && Lt(this, this._readableState); + }); + } + g.prototype.destroy = Ue.destroy; + g.prototype._undestroy = Ue.undestroy; + g.prototype._destroy = function(e, t) { + t(e); + }; + g.prototype[Vs.captureRejectionSymbol] = function(e) { + this.destroy(e); + }; + g.prototype.push = function(e, t) { + return eo(this, e, t, false); + }; + g.prototype.unshift = function(e, t) { + return eo(this, e, t, true); + }; + function eo(e, t, r, n) { + _("readableAddChunk", t); + let i = e._readableState, o; + if (i.objectMode || (typeof t == "string" ? (r = r || i.defaultEncoding, i.encoding !== r && (n && i.encoding ? t = Sr.from(t, r).toString(i.encoding) : (t = Sr.from(t, r), r = ""))) : t instanceof Sr ? r = "" : he._isUint8Array(t) ? (t = he._uint8ArrayToBuffer(t), r = "") : t != null && (o = new Zs("chunk", ["string", "Buffer", "Uint8Array"], t))), o) + ke(e, o); + else if (t === null) + i.reading = false, fa(e, i); + else if (i.objectMode || t && t.length > 0) + if (n) + if (i.endEmitted) + ke(e, new na); + else { + if (i.destroyed || i.errored) + return false; + xr(e, i, t, true); + } + else if (i.ended) + ke(e, new ra); + else { + if (i.destroyed || i.errored) + return false; + i.reading = false, i.decoder && !r ? (t = i.decoder.write(t), i.objectMode || t.length !== 0 ? xr(e, i, t, false) : Lt(e, i)) : xr(e, i, t, false); + } + else + n || (i.reading = false, Lt(e, i)); + return !i.ended && (i.length < i.highWaterMark || i.length === 0); + } + function xr(e, t, r, n) { + t.flowing && t.length === 0 && !t.sync && e.listenerCount("data") > 0 ? (t.multiAwaitDrain ? t.awaitDrainWriters.clear() : t.awaitDrainWriters = null, t.dataEmitted = true, e.emit("data", r)) : (t.length += t.objectMode ? 1 : r.length, n ? t.buffer.unshift(r) : t.buffer.push(r), t.needReadable && Nt(e)), Lt(e, t); + } + g.prototype.isPaused = function() { + let e = this._readableState; + return e[xe] === true || e.flowing === false; + }; + g.prototype.setEncoding = function(e) { + let t = new Zi(e); + this._readableState.decoder = t, this._readableState.encoding = this._readableState.decoder.encoding; + let r = this._readableState.buffer, n = ""; + for (let i of r) + n += t.write(i); + return r.clear(), n !== "" && r.push(n), this._readableState.length = n.length, this; + }; + var la = 1073741824; + function ua(e) { + if (e > la) + throw new ta("size", "<= 1GiB", e); + return e--, e |= e >>> 1, e |= e >>> 2, e |= e >>> 4, e |= e >>> 8, e |= e >>> 16, e++, e; + } + function Xi(e, t) { + return e <= 0 || t.length === 0 && t.ended ? 0 : t.objectMode ? 1 : vs(e) ? t.flowing && t.length ? t.buffer.first().length : t.length : e <= t.length ? e : t.ended ? t.length : 0; + } + g.prototype.read = function(e) { + _("read", e), e === undefined ? e = NaN : Us(e) || (e = qs(e, 10)); + let t = this._readableState, r = e; + if (e > t.highWaterMark && (t.highWaterMark = ua(e)), e !== 0 && (t.emittedReadable = false), e === 0 && t.needReadable && ((t.highWaterMark !== 0 ? t.length >= t.highWaterMark : t.length > 0) || t.ended)) + return _("read: emitReadable", t.length, t.ended), t.length === 0 && t.ended ? Rr(this) : Nt(this), null; + if (e = Xi(e, t), e === 0 && t.ended) + return t.length === 0 && Rr(this), null; + let n = t.needReadable; + if (_("need readable", n), (t.length === 0 || t.length - e < t.highWaterMark) && (n = true, _("length less than watermark", n)), t.ended || t.reading || t.destroyed || t.errored || !t.constructed) + n = false, _("reading, ended or constructing", n); + else if (n) { + _("do read"), t.reading = true, t.sync = true, t.length === 0 && (t.needReadable = true); + try { + this._read(t.highWaterMark); + } catch (o) { + ke(this, o); + } + t.sync = false, t.reading || (e = Xi(r, t)); + } + let i; + return e > 0 ? i = oo(e, t) : i = null, i === null ? (t.needReadable = t.length <= t.highWaterMark, e = 0) : (t.length -= e, t.multiAwaitDrain ? t.awaitDrainWriters.clear() : t.awaitDrainWriters = null), t.length === 0 && (t.ended || (t.needReadable = true), r !== e && t.ended && Rr(this)), i !== null && !t.errorEmitted && !t.closeEmitted && (t.dataEmitted = true, this.emit("data", i)), i; + }; + function fa(e, t) { + if (_("onEofChunk"), !t.ended) { + if (t.decoder) { + let r = t.decoder.end(); + r && r.length && (t.buffer.push(r), t.length += t.objectMode ? 1 : r.length); + } + t.ended = true, t.sync ? Nt(e) : (t.needReadable = false, t.emittedReadable = true, to(e)); + } + } + function Nt(e) { + let t = e._readableState; + _("emitReadable", t.needReadable, t.emittedReadable), t.needReadable = false, t.emittedReadable || (_("emitReadable", t.flowing), t.emittedReadable = true, $.nextTick(to, e)); + } + function to(e) { + let t = e._readableState; + _("emitReadable_", t.destroyed, t.length, t.ended), !t.destroyed && !t.errored && (t.length || t.ended) && (e.emit("readable"), t.emittedReadable = false), t.needReadable = !t.flowing && !t.ended && t.length <= t.highWaterMark, no(e); + } + function Lt(e, t) { + !t.readingMore && t.constructed && (t.readingMore = true, $.nextTick(sa, e, t)); + } + function sa(e, t) { + for (;!t.reading && !t.ended && (t.length < t.highWaterMark || t.flowing && t.length === 0); ) { + let r = t.length; + if (_("maybeReadMore read 0"), e.read(0), r === t.length) + break; + } + t.readingMore = false; + } + g.prototype._read = function(e) { + throw new ea("_read()"); + }; + g.prototype.pipe = function(e, t) { + let r = this, n = this._readableState; + n.pipes.length === 1 && (n.multiAwaitDrain || (n.multiAwaitDrain = true, n.awaitDrainWriters = new js(n.awaitDrainWriters ? [n.awaitDrainWriters] : []))), n.pipes.push(e), _("pipe count=%d opts=%j", n.pipes.length, t); + let o = (!t || t.end !== false) && e !== $.stdout && e !== $.stderr ? u : v; + n.endEmitted ? $.nextTick(o) : r.once("end", o), e.on("unpipe", l); + function l(w, b) { + _("onunpipe"), w === r && b && b.hasUnpiped === false && (b.hasUnpiped = true, d()); + } + function u() { + _("onend"), e.end(); + } + let f, s = false; + function d() { + _("cleanup"), e.removeListener("close", p), e.removeListener("finish", B), f && e.removeListener("drain", f), e.removeListener("error", h), e.removeListener("unpipe", l), r.removeListener("end", u), r.removeListener("end", v), r.removeListener("data", y), s = true, f && n.awaitDrainWriters && (!e._writableState || e._writableState.needDrain) && f(); + } + function c() { + s || (n.pipes.length === 1 && n.pipes[0] === e ? (_("false write response, pause", 0), n.awaitDrainWriters = e, n.multiAwaitDrain = false) : n.pipes.length > 1 && n.pipes.includes(e) && (_("false write response, pause", n.awaitDrainWriters.size), n.awaitDrainWriters.add(e)), r.pause()), f || (f = aa(r, e), e.on("drain", f)); + } + r.on("data", y); + function y(w) { + _("ondata"); + let b = e.write(w); + _("dest.write", b), b === false && c(); + } + function h(w) { + if (_("onerror", w), v(), e.removeListener("error", h), e.listenerCount("error") === 0) { + let b = e._writableState || e._readableState; + b && !b.errorEmitted ? ke(e, w) : e.emit("error", w); + } + } + Ys(e, "error", h); + function p() { + e.removeListener("finish", B), v(); + } + e.once("close", p); + function B() { + _("onfinish"), e.removeListener("close", p), v(); + } + e.once("finish", B); + function v() { + _("unpipe"), r.unpipe(e); + } + return e.emit("pipe", r), e.writableNeedDrain === true ? n.flowing && c() : n.flowing || (_("pipe resume"), r.resume()), e; + }; + function aa(e, t) { + return function() { + let n = e._readableState; + n.awaitDrainWriters === t ? (_("pipeOnDrain", 1), n.awaitDrainWriters = null) : n.multiAwaitDrain && (_("pipeOnDrain", n.awaitDrainWriters.size), n.awaitDrainWriters.delete(t)), (!n.awaitDrainWriters || n.awaitDrainWriters.size === 0) && e.listenerCount("data") && e.resume(); + }; + } + g.prototype.unpipe = function(e) { + let t = this._readableState, r = { hasUnpiped: false }; + if (t.pipes.length === 0) + return this; + if (!e) { + let i = t.pipes; + t.pipes = [], this.pause(); + for (let o = 0;o < i.length; o++) + i[o].emit("unpipe", this, { hasUnpiped: false }); + return this; + } + let n = ks(t.pipes, e); + return n === -1 ? this : (t.pipes.splice(n, 1), t.pipes.length === 0 && this.pause(), e.emit("unpipe", this, r), this); + }; + g.prototype.on = function(e, t) { + let r = he.prototype.on.call(this, e, t), n = this._readableState; + return e === "data" ? (n.readableListening = this.listenerCount("readable") > 0, n.flowing !== false && this.resume()) : e === "readable" && !n.endEmitted && !n.readableListening && (n.readableListening = n.needReadable = true, n.flowing = false, n.emittedReadable = false, _("on readable", n.length, n.reading), n.length ? Nt(this) : n.reading || $.nextTick(ca, this)), r; + }; + g.prototype.addListener = g.prototype.on; + g.prototype.removeListener = function(e, t) { + let r = he.prototype.removeListener.call(this, e, t); + return e === "readable" && $.nextTick(ro, this), r; + }; + g.prototype.off = g.prototype.removeListener; + g.prototype.removeAllListeners = function(e) { + let t = he.prototype.removeAllListeners.apply(this, arguments); + return (e === "readable" || e === undefined) && $.nextTick(ro, this), t; + }; + function ro(e) { + let t = e._readableState; + t.readableListening = e.listenerCount("readable") > 0, t.resumeScheduled && t[xe] === false ? t.flowing = true : e.listenerCount("data") > 0 ? e.resume() : t.readableListening || (t.flowing = null); + } + function ca(e) { + _("readable nexttick read 0"), e.read(0); + } + g.prototype.resume = function() { + let e = this._readableState; + return e.flowing || (_("resume"), e.flowing = !e.readableListening, da(this, e)), e[xe] = false, this; + }; + function da(e, t) { + t.resumeScheduled || (t.resumeScheduled = true, $.nextTick(ha, e, t)); + } + function ha(e, t) { + _("resume", t.reading), t.reading || e.read(0), t.resumeScheduled = false, e.emit("resume"), no(e), t.flowing && !t.reading && e.read(0); + } + g.prototype.pause = function() { + return _("call pause flowing=%j", this._readableState.flowing), this._readableState.flowing !== false && (_("pause"), this._readableState.flowing = false, this.emit("pause")), this._readableState[xe] = true, this; + }; + function no(e) { + let t = e._readableState; + for (_("flow", t.flowing);t.flowing && e.read() !== null; ) + ; + } + g.prototype.wrap = function(e) { + let t = false; + e.on("data", (n) => { + !this.push(n) && e.pause && (t = true, e.pause()); + }), e.on("end", () => { + this.push(null); + }), e.on("error", (n) => { + ke(this, n); + }), e.on("close", () => { + this.destroy(); + }), e.on("destroy", () => { + this.destroy(); + }), this._read = () => { + t && e.resume && (t = false, e.resume()); + }; + let r = Ws(e); + for (let n = 1;n < r.length; n++) { + let i = r[n]; + this[i] === undefined && typeof e[i] == "function" && (this[i] = e[i].bind(e)); + } + return this; + }; + g.prototype[Gs] = function() { + return io(this); + }; + g.prototype.iterator = function(e) { + return e !== undefined && ia(e, "options"), io(this, e); + }; + function io(e, t) { + typeof e.read != "function" && (e = g.wrap(e, { objectMode: true })); + let r = pa(e, t); + return r.stream = e, r; + } + async function* pa(e, t) { + let r = mr; + function n(l) { + this === e ? (r(), r = mr) : r = l; + } + e.on("readable", n); + let i, o = zs(e, { writable: false }, (l) => { + i = l ? zi(i, l) : null, r(), r = mr; + }); + try { + for (;; ) { + let l = e.destroyed ? null : e.read(); + if (l !== null) + yield l; + else { + if (i) + throw i; + if (i === null) + return; + await new $s(n); + } + } + } catch (l) { + throw i = zi(i, l), i; + } finally { + (i || t?.destroyOnReturn !== false) && (i === undefined || e._readableState.autoDestroy) ? Ue.destroyer(e, null) : (e.off("readable", n), o()); + } + } + Ji(g.prototype, { readable: { __proto__: null, get() { + let e = this._readableState; + return !!e && e.readable !== false && !e.destroyed && !e.errorEmitted && !e.endEmitted; + }, set(e) { + this._readableState && (this._readableState.readable = !!e); + } }, readableDidRead: { __proto__: null, enumerable: false, get: function() { + return this._readableState.dataEmitted; + } }, readableAborted: { __proto__: null, enumerable: false, get: function() { + return !!(this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted); + } }, readableHighWaterMark: { __proto__: null, enumerable: false, get: function() { + return this._readableState.highWaterMark; + } }, readableBuffer: { __proto__: null, enumerable: false, get: function() { + return this._readableState && this._readableState.buffer; + } }, readableFlowing: { __proto__: null, enumerable: false, get: function() { + return this._readableState.flowing; + }, set: function(e) { + this._readableState && (this._readableState.flowing = e); + } }, readableLength: { __proto__: null, enumerable: false, get() { + return this._readableState.length; + } }, readableObjectMode: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.objectMode : false; + } }, readableEncoding: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.encoding : null; + } }, errored: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.errored : null; + } }, closed: { __proto__: null, get() { + return this._readableState ? this._readableState.closed : false; + } }, destroyed: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.destroyed : false; + }, set(e) { + !this._readableState || (this._readableState.destroyed = e); + } }, readableEnded: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.endEmitted : false; + } } }); + Ji(Ir.prototype, { pipesCount: { __proto__: null, get() { + return this.pipes.length; + } }, paused: { __proto__: null, get() { + return this[xe] !== false; + }, set(e) { + this[xe] = !!e; + } } }); + g._fromList = oo; + function oo(e, t) { + if (t.length === 0) + return null; + let r; + return t.objectMode ? r = t.buffer.shift() : !e || e >= t.length ? (t.decoder ? r = t.buffer.join("") : t.buffer.length === 1 ? r = t.buffer.first() : r = t.buffer.concat(t.length), t.buffer.clear()) : r = t.buffer.consume(e, t.decoder), r; + } + function Rr(e) { + let t = e._readableState; + _("endReadable", t.endEmitted), t.endEmitted || (t.ended = true, $.nextTick(ya, t, e)); + } + function ya(e, t) { + if (_("endReadableNT", e.endEmitted, e.length), !e.errored && !e.closeEmitted && !e.endEmitted && e.length === 0) { + if (e.endEmitted = true, t.emit("end"), t.writable && t.allowHalfOpen === false) + $.nextTick(wa, t); + else if (e.autoDestroy) { + let r = t._writableState; + (!r || r.autoDestroy && (r.finished || r.writable === false)) && t.destroy(); + } + } + } + function wa(e) { + e.writable && !e.writableEnded && !e.destroyed && e.end(); + } + g.from = function(e, t) { + return oa(g, e, t); + }; + var Ar; + function lo() { + return Ar === undefined && (Ar = {}), Ar; + } + g.fromWeb = function(e, t) { + return lo().newStreamReadableFromReadableStream(e, t); + }; + g.toWeb = function(e, t) { + return lo().newReadableStreamFromStreamReadable(e, t); + }; + g.wrap = function(e, t) { + var r, n; + return new g({ objectMode: (r = (n = e.readableObjectMode) !== null && n !== undefined ? n : e.objectMode) !== null && r !== undefined ? r : true, ...t, destroy(i, o) { + Ue.destroyer(e, i), o(i); + } }).wrap(e); + }; + }); + Cr = E((ad, Eo) => { + var Re = (se(), pe(k)), { ArrayPrototypeSlice: ao, Error: ba, FunctionPrototypeSymbolHasInstance: co, ObjectDefineProperty: ho, ObjectDefineProperties: ga, ObjectSetPrototypeOf: po, StringPrototypeToLowerCase: _a, Symbol: Ea, SymbolHasInstance: Sa } = I(); + Eo.exports = m; + m.WritableState = Je; + var { EventEmitter: ma } = Et(), ze = xt().Stream, { Buffer: Ft } = te(), Ot = Se(), { addAbortSignal: xa } = At(), { getHighWaterMark: Ra, getDefaultHighWaterMark: Aa } = Tt(), { ERR_INVALID_ARG_TYPE: Ia, ERR_METHOD_NOT_IMPLEMENTED: Ta, ERR_MULTIPLE_CALLBACK: yo, ERR_STREAM_CANNOT_PIPE: Ba, ERR_STREAM_DESTROYED: Xe, ERR_STREAM_ALREADY_FINISHED: La, ERR_STREAM_NULL_VALUES: Na, ERR_STREAM_WRITE_AFTER_END: Fa, ERR_UNKNOWN_ENCODING: wo } = C().codes, { errorOrDestroy: ve } = Ot; + po(m.prototype, ze.prototype); + po(m, ze); + function Lr() { + } + var qe = Ea("kOnFinished"); + function Je(e, t, r) { + typeof r != "boolean" && (r = t instanceof J()), this.objectMode = !!(e && e.objectMode), r && (this.objectMode = this.objectMode || !!(e && e.writableObjectMode)), this.highWaterMark = e ? Ra(this, e, "writableHighWaterMark", r) : Aa(false), this.finalCalled = false, this.needDrain = false, this.ending = false, this.ended = false, this.finished = false, this.destroyed = false; + let n = !!(e && e.decodeStrings === false); + this.decodeStrings = !n, this.defaultEncoding = e && e.defaultEncoding || "utf8", this.length = 0, this.writing = false, this.corked = 0, this.sync = true, this.bufferProcessing = false, this.onwrite = Ca.bind(undefined, t), this.writecb = null, this.writelen = 0, this.afterWriteTickInfo = null, Ct(this), this.pendingcb = 0, this.constructed = true, this.prefinished = false, this.errorEmitted = false, this.emitClose = !e || e.emitClose !== false, this.autoDestroy = !e || e.autoDestroy !== false, this.errored = null, this.closed = false, this.closeEmitted = false, this[qe] = []; + } + function Ct(e) { + e.buffered = [], e.bufferedIndex = 0, e.allBuffers = true, e.allNoop = true; + } + Je.prototype.getBuffer = function() { + return ao(this.buffered, this.bufferedIndex); + }; + ho(Je.prototype, "bufferedRequestCount", { __proto__: null, get() { + return this.buffered.length - this.bufferedIndex; + } }); + function m(e) { + let t = this instanceof J(); + if (!t && !co(m, this)) + return new m(e); + this._writableState = new Je(e, this, t), e && (typeof e.write == "function" && (this._write = e.write), typeof e.writev == "function" && (this._writev = e.writev), typeof e.destroy == "function" && (this._destroy = e.destroy), typeof e.final == "function" && (this._final = e.final), typeof e.construct == "function" && (this._construct = e.construct), e.signal && xa(e.signal, this)), ze.call(this, e), Ot.construct(this, () => { + let r = this._writableState; + r.writing || Fr(this, r), Mr(this, r); + }); + } + ho(m, Sa, { __proto__: null, value: function(e) { + return co(this, e) ? true : this !== m ? false : e && e._writableState instanceof Je; + } }); + m.prototype.pipe = function() { + ve(this, new Ba); + }; + function bo(e, t, r, n) { + let i = e._writableState; + if (typeof r == "function") + n = r, r = i.defaultEncoding; + else { + if (!r) + r = i.defaultEncoding; + else if (r !== "buffer" && !Ft.isEncoding(r)) + throw new wo(r); + typeof n != "function" && (n = Lr); + } + if (t === null) + throw new Na; + if (!i.objectMode) + if (typeof t == "string") + i.decodeStrings !== false && (t = Ft.from(t, r), r = "buffer"); + else if (t instanceof Ft) + r = "buffer"; + else if (ze._isUint8Array(t)) + t = ze._uint8ArrayToBuffer(t), r = "buffer"; + else + throw new Ia("chunk", ["string", "Buffer", "Uint8Array"], t); + let o; + return i.ending ? o = new Fa : i.destroyed && (o = new Xe("write")), o ? (Re.nextTick(n, o), ve(e, o, true), o) : (i.pendingcb++, Ma(e, i, t, r, n)); + } + m.prototype.write = function(e, t, r) { + return bo(this, e, t, r) === true; + }; + m.prototype.cork = function() { + this._writableState.corked++; + }; + m.prototype.uncork = function() { + let e = this._writableState; + e.corked && (e.corked--, e.writing || Fr(this, e)); + }; + m.prototype.setDefaultEncoding = function(t) { + if (typeof t == "string" && (t = _a(t)), !Ft.isEncoding(t)) + throw new wo(t); + return this._writableState.defaultEncoding = t, this; + }; + function Ma(e, t, r, n, i) { + let o = t.objectMode ? 1 : r.length; + t.length += o; + let l = t.length < t.highWaterMark; + return l || (t.needDrain = true), t.writing || t.corked || t.errored || !t.constructed ? (t.buffered.push({ chunk: r, encoding: n, callback: i }), t.allBuffers && n !== "buffer" && (t.allBuffers = false), t.allNoop && i !== Lr && (t.allNoop = false)) : (t.writelen = o, t.writecb = i, t.writing = true, t.sync = true, e._write(r, n, t.onwrite), t.sync = false), l && !t.errored && !t.destroyed; + } + function fo(e, t, r, n, i, o, l) { + t.writelen = n, t.writecb = l, t.writing = true, t.sync = true, t.destroyed ? t.onwrite(new Xe("write")) : r ? e._writev(i, t.onwrite) : e._write(i, o, t.onwrite), t.sync = false; + } + function so(e, t, r, n) { + --t.pendingcb, n(r), Nr(t), ve(e, r); + } + function Ca(e, t) { + let r = e._writableState, n = r.sync, i = r.writecb; + if (typeof i != "function") { + ve(e, new yo); + return; + } + r.writing = false, r.writecb = null, r.length -= r.writelen, r.writelen = 0, t ? (t.stack, r.errored || (r.errored = t), e._readableState && !e._readableState.errored && (e._readableState.errored = t), n ? Re.nextTick(so, e, r, t, i) : so(e, r, t, i)) : (r.buffered.length > r.bufferedIndex && Fr(e, r), n ? r.afterWriteTickInfo !== null && r.afterWriteTickInfo.cb === i ? r.afterWriteTickInfo.count++ : (r.afterWriteTickInfo = { count: 1, cb: i, stream: e, state: r }, Re.nextTick(Oa, r.afterWriteTickInfo)) : go(e, r, 1, i)); + } + function Oa({ stream: e, state: t, count: r, cb: n }) { + return t.afterWriteTickInfo = null, go(e, t, r, n); + } + function go(e, t, r, n) { + for (!t.ending && !e.destroyed && t.length === 0 && t.needDrain && (t.needDrain = false, e.emit("drain"));r-- > 0; ) + t.pendingcb--, n(); + t.destroyed && Nr(t), Mr(e, t); + } + function Nr(e) { + if (e.writing) + return; + for (let i = e.bufferedIndex;i < e.buffered.length; ++i) { + var t; + let { chunk: o, callback: l } = e.buffered[i], u = e.objectMode ? 1 : o.length; + e.length -= u, l((t = e.errored) !== null && t !== undefined ? t : new Xe("write")); + } + let r = e[qe].splice(0); + for (let i = 0;i < r.length; i++) { + var n; + r[i]((n = e.errored) !== null && n !== undefined ? n : new Xe("end")); + } + Ct(e); + } + function Fr(e, t) { + if (t.corked || t.bufferProcessing || t.destroyed || !t.constructed) + return; + let { buffered: r, bufferedIndex: n, objectMode: i } = t, o = r.length - n; + if (!o) + return; + let l = n; + if (t.bufferProcessing = true, o > 1 && e._writev) { + t.pendingcb -= o - 1; + let u = t.allNoop ? Lr : (s) => { + for (let d = l;d < r.length; ++d) + r[d].callback(s); + }, f = t.allNoop && l === 0 ? r : ao(r, l); + f.allBuffers = t.allBuffers, fo(e, t, true, t.length, f, "", u), Ct(t); + } else { + do { + let { chunk: u, encoding: f, callback: s } = r[l]; + r[l++] = null; + let d = i ? 1 : u.length; + fo(e, t, false, d, u, f, s); + } while (l < r.length && !t.writing); + l === r.length ? Ct(t) : l > 256 ? (r.splice(0, l), t.bufferedIndex = 0) : t.bufferedIndex = l; + } + t.bufferProcessing = false; + } + m.prototype._write = function(e, t, r) { + if (this._writev) + this._writev([{ chunk: e, encoding: t }], r); + else + throw new Ta("_write()"); + }; + m.prototype._writev = null; + m.prototype.end = function(e, t, r) { + let n = this._writableState; + typeof e == "function" ? (r = e, e = null, t = null) : typeof t == "function" && (r = t, t = null); + let i; + if (e != null) { + let o = bo(this, e, t); + o instanceof ba && (i = o); + } + return n.corked && (n.corked = 1, this.uncork()), i || (!n.errored && !n.ending ? (n.ending = true, Mr(this, n, true), n.ended = true) : n.finished ? i = new La("end") : n.destroyed && (i = new Xe("end"))), typeof r == "function" && (i || n.finished ? Re.nextTick(r, i) : n[qe].push(r)), this; + }; + function Mt(e) { + return e.ending && !e.destroyed && e.constructed && e.length === 0 && !e.errored && e.buffered.length === 0 && !e.finished && !e.writing && !e.errorEmitted && !e.closeEmitted; + } + function Da(e, t) { + let r = false; + function n(i) { + if (r) { + ve(e, i ?? yo()); + return; + } + if (r = true, t.pendingcb--, i) { + let o = t[qe].splice(0); + for (let l = 0;l < o.length; l++) + o[l](i); + ve(e, i, t.sync); + } else + Mt(t) && (t.prefinished = true, e.emit("prefinish"), t.pendingcb++, Re.nextTick(Br, e, t)); + } + t.sync = true, t.pendingcb++; + try { + e._final(n); + } catch (i) { + n(i); + } + t.sync = false; + } + function Pa(e, t) { + !t.prefinished && !t.finalCalled && (typeof e._final == "function" && !t.destroyed ? (t.finalCalled = true, Da(e, t)) : (t.prefinished = true, e.emit("prefinish"))); + } + function Mr(e, t, r) { + Mt(t) && (Pa(e, t), t.pendingcb === 0 && (r ? (t.pendingcb++, Re.nextTick((n, i) => { + Mt(i) ? Br(n, i) : i.pendingcb--; + }, e, t)) : Mt(t) && (t.pendingcb++, Br(e, t)))); + } + function Br(e, t) { + t.pendingcb--, t.finished = true; + let r = t[qe].splice(0); + for (let n = 0;n < r.length; n++) + r[n](); + if (e.emit("finish"), t.autoDestroy) { + let n = e._readableState; + (!n || n.autoDestroy && (n.endEmitted || n.readable === false)) && e.destroy(); + } + } + ga(m.prototype, { closed: { __proto__: null, get() { + return this._writableState ? this._writableState.closed : false; + } }, destroyed: { __proto__: null, get() { + return this._writableState ? this._writableState.destroyed : false; + }, set(e) { + this._writableState && (this._writableState.destroyed = e); + } }, writable: { __proto__: null, get() { + let e = this._writableState; + return !!e && e.writable !== false && !e.destroyed && !e.errored && !e.ending && !e.ended; + }, set(e) { + this._writableState && (this._writableState.writable = !!e); + } }, writableFinished: { __proto__: null, get() { + return this._writableState ? this._writableState.finished : false; + } }, writableObjectMode: { __proto__: null, get() { + return this._writableState ? this._writableState.objectMode : false; + } }, writableBuffer: { __proto__: null, get() { + return this._writableState && this._writableState.getBuffer(); + } }, writableEnded: { __proto__: null, get() { + return this._writableState ? this._writableState.ending : false; + } }, writableNeedDrain: { __proto__: null, get() { + let e = this._writableState; + return e ? !e.destroyed && !e.ending && e.needDrain : false; + } }, writableHighWaterMark: { __proto__: null, get() { + return this._writableState && this._writableState.highWaterMark; + } }, writableCorked: { __proto__: null, get() { + return this._writableState ? this._writableState.corked : 0; + } }, writableLength: { __proto__: null, get() { + return this._writableState && this._writableState.length; + } }, errored: { __proto__: null, enumerable: false, get() { + return this._writableState ? this._writableState.errored : null; + } }, writableAborted: { __proto__: null, enumerable: false, get: function() { + return !!(this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished); + } } }); + var ka = Ot.destroy; + m.prototype.destroy = function(e, t) { + let r = this._writableState; + return !r.destroyed && (r.bufferedIndex < r.buffered.length || r[qe].length) && Re.nextTick(Nr, r), ka.call(this, e, t), this; + }; + m.prototype._undestroy = Ot.undestroy; + m.prototype._destroy = function(e, t) { + t(e); + }; + m.prototype[ma.captureRejectionSymbol] = function(e) { + this.destroy(e); + }; + var Tr; + function _o() { + return Tr === undefined && (Tr = {}), Tr; + } + m.fromWeb = function(e, t) { + return _o().newStreamWritableFromWritableStream(e, t); + }; + m.toWeb = function(e) { + return _o().newWritableStreamFromStreamWritable(e); + }; + }); + Mo = E((cd, Fo) => { + var Or = (se(), pe(k)), Ua = te(), { isReadable: va, isWritable: qa, isIterable: So, isNodeStream: Wa, isReadableNodeStream: mo, isWritableNodeStream: xo, isDuplexNodeStream: $a } = ae(), Ro = ce(), { AbortError: No, codes: { ERR_INVALID_ARG_TYPE: ja, ERR_INVALID_RETURN_VALUE: Ao } } = C(), { destroyer: We } = Se(), Ga = J(), Ha = Ke(), { createDeferredPromise: Io } = V(), To = Er(), Bo = globalThis.Blob || Ua.Blob, Va = typeof Bo < "u" ? function(t) { + return t instanceof Bo; + } : function(t) { + return false; + }, Ya = globalThis.AbortController || ut().AbortController, { FunctionPrototypeCall: Lo } = I(), Ae = class extends Ga { + constructor(t) { + super(t), t?.readable === false && (this._readableState.readable = false, this._readableState.ended = true, this._readableState.endEmitted = true), t?.writable === false && (this._writableState.writable = false, this._writableState.ending = true, this._writableState.ended = true, this._writableState.finished = true); + } + }; + Fo.exports = function e(t, r) { + if ($a(t)) + return t; + if (mo(t)) + return Dt({ readable: t }); + if (xo(t)) + return Dt({ writable: t }); + if (Wa(t)) + return Dt({ writable: false, readable: false }); + if (typeof t == "function") { + let { value: i, write: o, final: l, destroy: u } = Ka(t); + if (So(i)) + return To(Ae, i, { objectMode: true, write: o, final: l, destroy: u }); + let f = i?.then; + if (typeof f == "function") { + let s, d = Lo(f, i, (c) => { + if (c != null) + throw new Ao("nully", "body", c); + }, (c) => { + We(s, c); + }); + return s = new Ae({ objectMode: true, readable: false, write: o, final(c) { + l(async () => { + try { + await d, Or.nextTick(c, null); + } catch (y) { + Or.nextTick(c, y); + } + }); + }, destroy: u }); + } + throw new Ao("Iterable, AsyncIterable or AsyncFunction", r, i); + } + if (Va(t)) + return e(t.arrayBuffer()); + if (So(t)) + return To(Ae, t, { objectMode: true, writable: false }); + if (typeof t?.writable == "object" || typeof t?.readable == "object") { + let i = t != null && t.readable ? mo(t?.readable) ? t?.readable : e(t.readable) : undefined, o = t != null && t.writable ? xo(t?.writable) ? t?.writable : e(t.writable) : undefined; + return Dt({ readable: i, writable: o }); + } + let n = t?.then; + if (typeof n == "function") { + let i; + return Lo(n, t, (o) => { + o != null && i.push(o), i.push(null); + }, (o) => { + We(i, o); + }), i = new Ae({ objectMode: true, writable: false, read() { + } }); + } + throw new ja(r, ["Blob", "ReadableStream", "WritableStream", "Stream", "Iterable", "AsyncIterable", "Function", "{ readable, writable } pair", "Promise"], t); + }; + function Ka(e) { + let { promise: t, resolve: r } = Io(), n = new Ya, i = n.signal; + return { value: e(async function* () { + for (;; ) { + let l = t; + t = null; + let { chunk: u, done: f, cb: s } = await l; + if (Or.nextTick(s), f) + return; + if (i.aborted) + throw new No(undefined, { cause: i.reason }); + ({ promise: t, resolve: r } = Io()), yield u; + } + }(), { signal: i }), write(l, u, f) { + let s = r; + r = null, s({ chunk: l, done: false, cb: f }); + }, final(l) { + let u = r; + r = null, u({ done: true, cb: l }); + }, destroy(l, u) { + n.abort(), u(l); + } }; + } + function Dt(e) { + let t = e.readable && typeof e.readable.read != "function" ? Ha.wrap(e.readable) : e.readable, r = e.writable, n = !!va(t), i = !!qa(r), o, l, u, f, s; + function d(c) { + let y = f; + f = null, y ? y(c) : c ? s.destroy(c) : !n && !i && s.destroy(); + } + return s = new Ae({ readableObjectMode: !!(t != null && t.readableObjectMode), writableObjectMode: !!(r != null && r.writableObjectMode), readable: n, writable: i }), i && (Ro(r, (c) => { + i = false, c && We(t, c), d(c); + }), s._write = function(c, y, h) { + r.write(c, y) ? h() : o = h; + }, s._final = function(c) { + r.end(), l = c; + }, r.on("drain", function() { + if (o) { + let c = o; + o = null, c(); + } + }), r.on("finish", function() { + if (l) { + let c = l; + l = null, c(); + } + })), n && (Ro(t, (c) => { + n = false, c && We(t, c), d(c); + }), t.on("readable", function() { + if (u) { + let c = u; + u = null, c(); + } + }), t.on("end", function() { + s.push(null); + }), s._read = function() { + for (;; ) { + let c = t.read(); + if (c === null) { + u = s._read; + return; + } + if (!s.push(c)) + return; + } + }), s._destroy = function(c, y) { + !c && f !== null && (c = new No), u = null, o = null, l = null, f === null ? y(c) : (f = y, We(r, c), We(t, c)); + }, s; + } + }); + J = E((dd, Do) => { + var { ObjectDefineProperties: za, ObjectGetOwnPropertyDescriptor: ie, ObjectKeys: Xa, ObjectSetPrototypeOf: Co } = I(); + Do.exports = j; + var kr = Ke(), U = Cr(); + Co(j.prototype, kr.prototype); + Co(j, kr); + { + let e = Xa(U.prototype); + for (let t = 0;t < e.length; t++) { + let r = e[t]; + j.prototype[r] || (j.prototype[r] = U.prototype[r]); + } + } + function j(e) { + if (!(this instanceof j)) + return new j(e); + kr.call(this, e), U.call(this, e), e ? (this.allowHalfOpen = e.allowHalfOpen !== false, e.readable === false && (this._readableState.readable = false, this._readableState.ended = true, this._readableState.endEmitted = true), e.writable === false && (this._writableState.writable = false, this._writableState.ending = true, this._writableState.ended = true, this._writableState.finished = true)) : this.allowHalfOpen = true; + } + za(j.prototype, { writable: { __proto__: null, ...ie(U.prototype, "writable") }, writableHighWaterMark: { __proto__: null, ...ie(U.prototype, "writableHighWaterMark") }, writableObjectMode: { __proto__: null, ...ie(U.prototype, "writableObjectMode") }, writableBuffer: { __proto__: null, ...ie(U.prototype, "writableBuffer") }, writableLength: { __proto__: null, ...ie(U.prototype, "writableLength") }, writableFinished: { __proto__: null, ...ie(U.prototype, "writableFinished") }, writableCorked: { __proto__: null, ...ie(U.prototype, "writableCorked") }, writableEnded: { __proto__: null, ...ie(U.prototype, "writableEnded") }, writableNeedDrain: { __proto__: null, ...ie(U.prototype, "writableNeedDrain") }, destroyed: { __proto__: null, get() { + return this._readableState === undefined || this._writableState === undefined ? false : this._readableState.destroyed && this._writableState.destroyed; + }, set(e) { + this._readableState && this._writableState && (this._readableState.destroyed = e, this._writableState.destroyed = e); + } } }); + var Dr; + function Oo() { + return Dr === undefined && (Dr = {}), Dr; + } + j.fromWeb = function(e, t) { + return Oo().newStreamDuplexFromReadableWritablePair(e, t); + }; + j.toWeb = function(e) { + return Oo().newReadableWritablePairFromDuplex(e); + }; + var Pr; + j.from = function(e) { + return Pr || (Pr = Mo()), Pr(e, "body"); + }; + }); + qr = E((hd, ko) => { + var { ObjectSetPrototypeOf: Po, Symbol: Ja } = I(); + ko.exports = oe; + var { ERR_METHOD_NOT_IMPLEMENTED: Qa } = C().codes, vr = J(), { getHighWaterMark: Za } = Tt(); + Po(oe.prototype, vr.prototype); + Po(oe, vr); + var Qe = Ja("kCallback"); + function oe(e) { + if (!(this instanceof oe)) + return new oe(e); + let t = e ? Za(this, e, "readableHighWaterMark", true) : null; + t === 0 && (e = { ...e, highWaterMark: null, readableHighWaterMark: t, writableHighWaterMark: e.writableHighWaterMark || 0 }), vr.call(this, e), this._readableState.sync = false, this[Qe] = null, e && (typeof e.transform == "function" && (this._transform = e.transform), typeof e.flush == "function" && (this._flush = e.flush)), this.on("prefinish", ec); + } + function Ur(e) { + typeof this._flush == "function" && !this.destroyed ? this._flush((t, r) => { + if (t) { + e ? e(t) : this.destroy(t); + return; + } + r != null && this.push(r), this.push(null), e && e(); + }) : (this.push(null), e && e()); + } + function ec() { + this._final !== Ur && Ur.call(this); + } + oe.prototype._final = Ur; + oe.prototype._transform = function(e, t, r) { + throw new Qa("_transform()"); + }; + oe.prototype._write = function(e, t, r) { + let n = this._readableState, i = this._writableState, o = n.length; + this._transform(e, t, (l, u) => { + if (l) { + r(l); + return; + } + u != null && this.push(u), i.ended || o === n.length || n.length < n.highWaterMark ? r() : this[Qe] = r; + }); + }; + oe.prototype._read = function() { + if (this[Qe]) { + let e = this[Qe]; + this[Qe] = null, e(); + } + }; + }); + $r = E((pd, vo) => { + var { ObjectSetPrototypeOf: Uo } = I(); + vo.exports = $e; + var Wr = qr(); + Uo($e.prototype, Wr.prototype); + Uo($e, Wr); + function $e(e) { + if (!(this instanceof $e)) + return new $e(e); + Wr.call(this, e); + } + $e.prototype._transform = function(e, t, r) { + r(null, e); + }; + }); + Ut = E((yd, Vo) => { + var Pt = (se(), pe(k)), { ArrayIsArray: tc, Promise: rc, SymbolAsyncIterator: nc } = I(), kt = ce(), { once: ic } = V(), oc = Se(), qo = J(), { aggregateTwoErrors: lc, codes: { ERR_INVALID_ARG_TYPE: Go, ERR_INVALID_RETURN_VALUE: jr, ERR_MISSING_ARGS: uc, ERR_STREAM_DESTROYED: fc, ERR_STREAM_PREMATURE_CLOSE: sc }, AbortError: ac } = C(), { validateFunction: cc, validateAbortSignal: dc } = He(), { isIterable: je, isReadable: Gr, isReadableNodeStream: Yr, isNodeStream: Wo } = ae(), hc = globalThis.AbortController || ut().AbortController, Hr, Vr; + function $o(e, t, r) { + let n = false; + e.on("close", () => { + n = true; + }); + let i = kt(e, { readable: t, writable: r }, (o) => { + n = !o; + }); + return { destroy: (o) => { + n || (n = true, oc.destroyer(e, o || new fc("pipe"))); + }, cleanup: i }; + } + function pc(e) { + return cc(e[e.length - 1], "streams[stream.length - 1]"), e.pop(); + } + function yc(e) { + if (je(e)) + return e; + if (Yr(e)) + return wc(e); + throw new Go("val", ["Readable", "Iterable", "AsyncIterable"], e); + } + async function* wc(e) { + Vr || (Vr = Ke()), yield* Vr.prototype[nc].call(e); + } + async function jo(e, t, r, { end: n }) { + let i, o = null, l = (s) => { + if (s && (i = s), o) { + let d = o; + o = null, d(); + } + }, u = () => new rc((s, d) => { + i ? d(i) : o = () => { + i ? d(i) : s(); + }; + }); + t.on("drain", l); + let f = kt(t, { readable: false }, l); + try { + t.writableNeedDrain && await u(); + for await (let s of e) + t.write(s) || await u(); + n && t.end(), await u(), r(); + } catch (s) { + r(i !== s ? lc(i, s) : s); + } finally { + f(), t.off("drain", l); + } + } + function bc(...e) { + return Ho(e, ic(pc(e))); + } + function Ho(e, t, r) { + if (e.length === 1 && tc(e[0]) && (e = e[0]), e.length < 2) + throw new uc("streams"); + let n = new hc, i = n.signal, o = r?.signal, l = []; + dc(o, "options.signal"); + function u() { + h(new ac); + } + o?.addEventListener("abort", u); + let f, s, d = [], c = 0; + function y(w) { + h(w, --c === 0); + } + function h(w, b) { + if (w && (!f || f.code === "ERR_STREAM_PREMATURE_CLOSE") && (f = w), !(!f && !b)) { + for (;d.length; ) + d.shift()(f); + o?.removeEventListener("abort", u), n.abort(), b && (f || l.forEach((L) => L()), Pt.nextTick(t, f, s)); + } + } + let p; + for (let w = 0;w < e.length; w++) { + let b = e[w], L = w < e.length - 1, N = w > 0, Q = L || r?.end !== false, Ie = w === e.length - 1; + if (Wo(b)) { + let q = function(Z) { + Z && Z.name !== "AbortError" && Z.code !== "ERR_STREAM_PREMATURE_CLOSE" && y(Z); + }; + var v = q; + if (Q) { + let { destroy: Z, cleanup: qt } = $o(b, L, N); + d.push(Z), Gr(b) && Ie && l.push(qt); + } + b.on("error", q), Gr(b) && Ie && l.push(() => { + b.removeListener("error", q); + }); + } + if (w === 0) + if (typeof b == "function") { + if (p = b({ signal: i }), !je(p)) + throw new jr("Iterable, AsyncIterable or Stream", "source", p); + } else + je(b) || Yr(b) ? p = b : p = qo.from(b); + else if (typeof b == "function") + if (p = yc(p), p = b(p, { signal: i }), L) { + if (!je(p, true)) + throw new jr("AsyncIterable", `transform[${w - 1}]`, p); + } else { + var B; + Hr || (Hr = $r()); + let q = new Hr({ objectMode: true }), Z = (B = p) === null || B === undefined ? undefined : B.then; + if (typeof Z == "function") + c++, Z.call(p, (Te) => { + s = Te, Te != null && q.write(Te), Q && q.end(), Pt.nextTick(y); + }, (Te) => { + q.destroy(Te), Pt.nextTick(y, Te); + }); + else if (je(p, true)) + c++, jo(p, q, y, { end: Q }); + else + throw new jr("AsyncIterable or Promise", "destination", p); + p = q; + let { destroy: qt, cleanup: sl } = $o(p, false, true); + d.push(qt), Ie && l.push(sl); + } + else if (Wo(b)) { + if (Yr(p)) { + c += 2; + let q = gc(p, b, y, { end: Q }); + Gr(b) && Ie && l.push(q); + } else if (je(p)) + c++, jo(p, b, y, { end: Q }); + else + throw new Go("val", ["Readable", "Iterable", "AsyncIterable"], p); + p = b; + } else + p = qo.from(b); + } + return (i != null && i.aborted || o != null && o.aborted) && Pt.nextTick(u), p; + } + function gc(e, t, r, { end: n }) { + let i = false; + return t.on("close", () => { + i || r(new sc); + }), e.pipe(t, { end: n }), n ? e.once("end", () => { + i = true, t.end(); + }) : r(), kt(e, { readable: true, writable: false }, (o) => { + let l = e._readableState; + o && o.code === "ERR_STREAM_PREMATURE_CLOSE" && l && l.ended && !l.errored && !l.errorEmitted ? e.once("end", r).once("error", r) : r(o); + }), kt(t, { readable: false, writable: true }, r); + } + Vo.exports = { pipelineImpl: Ho, pipeline: bc }; + }); + Jo = E((wd, Xo) => { + var { pipeline: _c } = Ut(), vt = J(), { destroyer: Ec } = Se(), { isNodeStream: Sc, isReadable: Yo, isWritable: Ko } = ae(), { AbortError: mc, codes: { ERR_INVALID_ARG_VALUE: zo, ERR_MISSING_ARGS: xc } } = C(); + Xo.exports = function(...t) { + if (t.length === 0) + throw new xc("streams"); + if (t.length === 1) + return vt.from(t[0]); + let r = [...t]; + if (typeof t[0] == "function" && (t[0] = vt.from(t[0])), typeof t[t.length - 1] == "function") { + let h = t.length - 1; + t[h] = vt.from(t[h]); + } + for (let h = 0;h < t.length; ++h) + if (!!Sc(t[h])) { + if (h < t.length - 1 && !Yo(t[h])) + throw new zo(`streams[${h}]`, r[h], "must be readable"); + if (h > 0 && !Ko(t[h])) + throw new zo(`streams[${h}]`, r[h], "must be writable"); + } + let n, i, o, l, u; + function f(h) { + let p = l; + l = null, p ? p(h) : h ? u.destroy(h) : !y && !c && u.destroy(); + } + let s = t[0], d = _c(t, f), c = !!Ko(s), y = !!Yo(d); + return u = new vt({ writableObjectMode: !!(s != null && s.writableObjectMode), readableObjectMode: !!(d != null && d.writableObjectMode), writable: c, readable: y }), c && (u._write = function(h, p, B) { + s.write(h, p) ? B() : n = B; + }, u._final = function(h) { + s.end(), i = h; + }, s.on("drain", function() { + if (n) { + let h = n; + n = null, h(); + } + }), d.on("finish", function() { + if (i) { + let h = i; + i = null, h(); + } + })), y && (d.on("readable", function() { + if (o) { + let h = o; + o = null, h(); + } + }), d.on("end", function() { + u.push(null); + }), u._read = function() { + for (;; ) { + let h = d.read(); + if (h === null) { + o = u._read; + return; + } + if (!u.push(h)) + return; + } + }), u._destroy = function(h, p) { + !h && l !== null && (h = new mc), o = null, n = null, i = null, l === null ? p(h) : (l = p, Ec(d, h)); + }, u; + }; + }); + Kr = E((bd, Qo) => { + var { ArrayPrototypePop: Rc, Promise: Ac } = I(), { isIterable: Ic, isNodeStream: Tc } = ae(), { pipelineImpl: Bc } = Ut(), { finished: Lc } = ce(); + function Nc(...e) { + return new Ac((t, r) => { + let n, i, o = e[e.length - 1]; + if (o && typeof o == "object" && !Tc(o) && !Ic(o)) { + let l = Rc(e); + n = l.signal, i = l.end; + } + Bc(e, (l, u) => { + l ? r(l) : t(u); + }, { signal: n, end: i }); + }); + } + Qo.exports = { finished: Lc, pipeline: Nc }; + }); + fl = E((gd, ul) => { + var { Buffer: Fc } = te(), { ObjectDefineProperty: le, ObjectKeys: tl, ReflectApply: rl } = I(), { promisify: { custom: nl } } = V(), { streamReturningOperators: Zo, promiseReturningOperators: el } = di(), { codes: { ERR_ILLEGAL_CONSTRUCTOR: il } } = C(), Mc = Jo(), { pipeline: ol } = Ut(), { destroyer: Cc } = Se(), ll = ce(), zr = Kr(), Xr = ae(), R = ul.exports = xt().Stream; + R.isDisturbed = Xr.isDisturbed; + R.isErrored = Xr.isErrored; + R.isReadable = Xr.isReadable; + R.Readable = Ke(); + for (let e of tl(Zo)) { + let r = function(...n) { + if (new.target) + throw il(); + return R.Readable.from(rl(t, this, n)); + }; + Dc = r; + let t = Zo[e]; + le(r, "name", { __proto__: null, value: t.name }), le(r, "length", { __proto__: null, value: t.length }), le(R.Readable.prototype, e, { __proto__: null, value: r, enumerable: false, configurable: true, writable: true }); + } + var Dc; + for (let e of tl(el)) { + let r = function(...i) { + if (new.target) + throw il(); + return rl(t, this, i); + }; + Dc = r; + let t = el[e]; + le(r, "name", { __proto__: null, value: t.name }), le(r, "length", { __proto__: null, value: t.length }), le(R.Readable.prototype, e, { __proto__: null, value: r, enumerable: false, configurable: true, writable: true }); + } + var Dc; + R.Writable = Cr(); + R.Duplex = J(); + R.Transform = qr(); + R.PassThrough = $r(); + R.pipeline = ol; + var { addAbortSignal: Oc } = At(); + R.addAbortSignal = Oc; + R.finished = ll; + R.destroy = Cc; + R.compose = Mc; + le(R, "promises", { __proto__: null, configurable: true, enumerable: true, get() { + return zr; + } }); + le(ol, nl, { __proto__: null, enumerable: true, get() { + return zr.pipeline; + } }); + le(ll, nl, { __proto__: null, enumerable: true, get() { + return zr.finished; + } }); + R.Stream = R; + R._isUint8Array = function(t) { + return t instanceof Uint8Array; + }; + R._uint8ArrayToBuffer = function(t) { + return Fc.from(t.buffer, t.byteOffset, t.byteLength); + }; + }); + Jr = E((_d, A) => { + var T = fl(), Pc = Kr(), kc = T.Readable.destroy; + A.exports = T.Readable; + A.exports._uint8ArrayToBuffer = T._uint8ArrayToBuffer; + A.exports._isUint8Array = T._isUint8Array; + A.exports.isDisturbed = T.isDisturbed; + A.exports.isErrored = T.isErrored; + A.exports.isReadable = T.isReadable; + A.exports.Readable = T.Readable; + A.exports.Writable = T.Writable; + A.exports.Duplex = T.Duplex; + A.exports.Transform = T.Transform; + A.exports.PassThrough = T.PassThrough; + A.exports.addAbortSignal = T.addAbortSignal; + A.exports.finished = T.finished; + A.exports.destroy = T.destroy; + A.exports.destroy = kc; + A.exports.pipeline = T.pipeline; + A.exports.compose = T.compose; + Object.defineProperty(T, "promises", { configurable: true, enumerable: true, get() { + return Pc; + } }); + A.exports.Stream = T.Stream; + A.exports.default = A.exports; + }); + Ze = {}; + Qr(Ze, { default: () => Uc }); + ue(Ze, rt(Jr())); + Uc = rt(Jr()); + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + /*! safe-buffer. MIT License. Feross Aboukhadijeh */ +}); + +// node_modules/jszip/lib/support.js +var require_support = __commonJS((exports2) => { + exports2.base64 = true; + exports2.array = true; + exports2.string = true; + exports2.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"; + exports2.nodebuffer = typeof Buffer !== "undefined"; + exports2.uint8array = typeof Uint8Array !== "undefined"; + if (typeof ArrayBuffer === "undefined") { + exports2.blob = false; + } else { + buffer = new ArrayBuffer(0); + try { + exports2.blob = new Blob([buffer], { + type: "application/zip" + }).size === 0; + } catch (e) { + try { + Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; + builder = new Builder; + builder.append(buffer); + exports2.blob = builder.getBlob("application/zip").size === 0; + } catch (e2) { + exports2.blob = false; + } + } + } + var buffer; + var Builder; + var builder; + try { + exports2.nodestream = !!(init_stream(), __toCommonJS(exports_stream)).Readable; + } catch (e) { + exports2.nodestream = false; + } +}); + +// node_modules/jszip/lib/base64.js +var require_base64 = __commonJS((exports2) => { + var utils = require_utils(); + var support = require_support(); + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + exports2.encode = function(input) { + var output = []; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0, len = input.length, remainingBytes = len; + var isArray2 = utils.getTypeOf(input) !== "string"; + while (i < input.length) { + remainingBytes = len - i; + if (!isArray2) { + chr1 = input.charCodeAt(i++); + chr2 = i < len ? input.charCodeAt(i++) : 0; + chr3 = i < len ? input.charCodeAt(i++) : 0; + } else { + chr1 = input[i++]; + chr2 = i < len ? input[i++] : 0; + chr3 = i < len ? input[i++] : 0; + } + enc1 = chr1 >> 2; + enc2 = (chr1 & 3) << 4 | chr2 >> 4; + enc3 = remainingBytes > 1 ? (chr2 & 15) << 2 | chr3 >> 6 : 64; + enc4 = remainingBytes > 2 ? chr3 & 63 : 64; + output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4)); + } + return output.join(""); + }; + exports2.decode = function(input) { + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0, resultIndex = 0; + var dataUrlPrefix = "data:"; + if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) { + throw new Error("Invalid base64 input, it looks like a data url."); + } + input = input.replace(/[^A-Za-z0-9+/=]/g, ""); + var totalLength = input.length * 3 / 4; + if (input.charAt(input.length - 1) === _keyStr.charAt(64)) { + totalLength--; + } + if (input.charAt(input.length - 2) === _keyStr.charAt(64)) { + totalLength--; + } + if (totalLength % 1 !== 0) { + throw new Error("Invalid base64 input, bad content length."); + } + var output; + if (support.uint8array) { + output = new Uint8Array(totalLength | 0); + } else { + output = new Array(totalLength | 0); + } + while (i < input.length) { + enc1 = _keyStr.indexOf(input.charAt(i++)); + enc2 = _keyStr.indexOf(input.charAt(i++)); + enc3 = _keyStr.indexOf(input.charAt(i++)); + enc4 = _keyStr.indexOf(input.charAt(i++)); + chr1 = enc1 << 2 | enc2 >> 4; + chr2 = (enc2 & 15) << 4 | enc3 >> 2; + chr3 = (enc3 & 3) << 6 | enc4; + output[resultIndex++] = chr1; + if (enc3 !== 64) { + output[resultIndex++] = chr2; + } + if (enc4 !== 64) { + output[resultIndex++] = chr3; + } + } + return output; + }; +}); + +// node_modules/jszip/lib/nodejsUtils.js +var require_nodejsUtils = __commonJS((exports2, module2) => { + module2.exports = { + isNode: typeof Buffer !== "undefined", + newBufferFrom: function(data2, encoding) { + if (Buffer.from && Buffer.from !== Uint8Array.from) { + return Buffer.from(data2, encoding); + } else { + if (typeof data2 === "number") { + throw new Error('The "data" argument must not be a number'); + } + return new Buffer(data2, encoding); + } + }, + allocBuffer: function(size) { + if (Buffer.alloc) { + return Buffer.alloc(size); + } else { + var buf = new Buffer(size); + buf.fill(0); + return buf; + } + }, + isBuffer: function(b) { + return Buffer.isBuffer(b); + }, + isStream: function(obj) { + return obj && typeof obj.on === "function" && typeof obj.pause === "function" && typeof obj.resume === "function"; + } + }; +}); + +// node_modules/immediate/lib/browser.js +var require_browser = __commonJS((exports2, module2) => { + var Mutation = global.MutationObserver || global.WebKitMutationObserver; + var scheduleDrain; + { + if (Mutation) { + called = 0; + observer = new Mutation(nextTick); + element = global.document.createTextNode(""); + observer.observe(element, { + characterData: true + }); + scheduleDrain = function() { + element.data = called = ++called % 2; + }; + } else if (!global.setImmediate && typeof global.MessageChannel !== "undefined") { + channel = new global.MessageChannel; + channel.port1.onmessage = nextTick; + scheduleDrain = function() { + channel.port2.postMessage(0); + }; + } else if ("document" in global && "onreadystatechange" in global.document.createElement("script")) { + scheduleDrain = function() { + var scriptEl = global.document.createElement("script"); + scriptEl.onreadystatechange = function() { + nextTick(); + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + global.document.documentElement.appendChild(scriptEl); + }; + } else { + scheduleDrain = function() { + setTimeout(nextTick, 0); + }; + } + } + var called; + var observer; + var element; + var channel; + var draining; + var queue = []; + function nextTick() { + draining = true; + var i, oldQueue; + var len = queue.length; + while (len) { + oldQueue = queue; + queue = []; + i = -1; + while (++i < len) { + oldQueue[i](); + } + len = queue.length; + } + draining = false; + } + module2.exports = immediate; + function immediate(task) { + if (queue.push(task) === 1 && !draining) { + scheduleDrain(); + } + } +}); + +// node_modules/lie/lib/browser.js +var require_browser2 = __commonJS((exports2, module2) => { + var immediate = require_browser(); + function INTERNAL() { + } + var handlers = {}; + var REJECTED = ["REJECTED"]; + var FULFILLED = ["FULFILLED"]; + var PENDING = ["PENDING"]; + module2.exports = Promise2; + function Promise2(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("resolver must be a function"); + } + this.state = PENDING; + this.queue = []; + this.outcome = undefined; + if (resolver !== INTERNAL) { + safelyResolveThenable(this, resolver); + } + } + Promise2.prototype["finally"] = function(callback) { + if (typeof callback !== "function") { + return this; + } + var p = this.constructor; + return this.then(resolve2, reject3); + function resolve2(value2) { + function yes() { + return value2; + } + return p.resolve(callback()).then(yes); + } + function reject3(reason) { + function no() { + throw reason; + } + return p.resolve(callback()).then(no); + } + }; + Promise2.prototype["catch"] = function(onRejected) { + return this.then(null, onRejected); + }; + Promise2.prototype.then = function(onFulfilled, onRejected) { + if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) { + return this; + } + var promise = new this.constructor(INTERNAL); + if (this.state !== PENDING) { + var resolver = this.state === FULFILLED ? onFulfilled : onRejected; + unwrap(promise, resolver, this.outcome); + } else { + this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); + } + return promise; + }; + function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === "function") { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === "function") { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } + } + QueueItem.prototype.callFulfilled = function(value2) { + handlers.resolve(this.promise, value2); + }; + QueueItem.prototype.otherCallFulfilled = function(value2) { + unwrap(this.promise, this.onFulfilled, value2); + }; + QueueItem.prototype.callRejected = function(value2) { + handlers.reject(this.promise, value2); + }; + QueueItem.prototype.otherCallRejected = function(value2) { + unwrap(this.promise, this.onRejected, value2); + }; + function unwrap(promise, func, value2) { + immediate(function() { + var returnValue; + try { + returnValue = func(value2); + } catch (e) { + return handlers.reject(promise, e); + } + if (returnValue === promise) { + handlers.reject(promise, new TypeError("Cannot resolve promise with itself")); + } else { + handlers.resolve(promise, returnValue); + } + }); + } + handlers.resolve = function(self2, value2) { + var result = tryCatch(getThen, value2); + if (result.status === "error") { + return handlers.reject(self2, result.value); + } + var thenable = result.value; + if (thenable) { + safelyResolveThenable(self2, thenable); + } else { + self2.state = FULFILLED; + self2.outcome = value2; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callFulfilled(value2); + } + } + return self2; + }; + handlers.reject = function(self2, error) { + self2.state = REJECTED; + self2.outcome = error; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callRejected(error); + } + return self2; + }; + function getThen(obj) { + var then = obj && obj.then; + if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") { + return function appyThen() { + then.apply(obj, arguments); + }; + } + } + function safelyResolveThenable(self2, thenable) { + var called = false; + function onError(value2) { + if (called) { + return; + } + called = true; + handlers.reject(self2, value2); + } + function onSuccess(value2) { + if (called) { + return; + } + called = true; + handlers.resolve(self2, value2); + } + function tryToUnwrap() { + thenable(onSuccess, onError); + } + var result = tryCatch(tryToUnwrap); + if (result.status === "error") { + onError(result.value); + } + } + function tryCatch(func, value2) { + var out = {}; + try { + out.value = func(value2); + out.status = "success"; + } catch (e) { + out.status = "error"; + out.value = e; + } + return out; + } + Promise2.resolve = resolve; + function resolve(value2) { + if (value2 instanceof this) { + return value2; + } + return handlers.resolve(new this(INTERNAL), value2); + } + Promise2.reject = reject2; + function reject2(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); + } + Promise2.all = all; + function all(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var values2 = new Array(len); + var resolved = 0; + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + allResolver(iterable[i], i); + } + return promise; + function allResolver(value2, i2) { + self2.resolve(value2).then(resolveFromAll, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values2[i2] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values2); + } + } + } + } + Promise2.race = race; + function race(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + resolver(iterable[i]); + } + return promise; + function resolver(value2) { + self2.resolve(value2).then(function(response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } + } +}); + +// node_modules/jszip/lib/external.js +var require_external = __commonJS((exports2, module2) => { + var ES6Promise = null; + if (typeof Promise !== "undefined") { + ES6Promise = Promise; + } else { + ES6Promise = require_browser2(); + } + module2.exports = { + Promise: ES6Promise + }; +}); + +// node_modules/setimmediate/setImmediate.js +var require_setImmediate = __commonJS((exports2) => { + (function(global2, undefined2) { + if (global2.setImmediate) { + return; + } + var nextHandle = 1; + var tasksByHandle = {}; + var currentlyRunningATask = false; + var doc = global2.document; + var registerImmediate; + function setImmediate2(callback) { + if (typeof callback !== "function") { + callback = new Function("" + callback); + } + var args = new Array(arguments.length - 1); + for (var i = 0;i < args.length; i++) { + args[i] = arguments[i + 1]; + } + var task = { callback, args }; + tasksByHandle[nextHandle] = task; + registerImmediate(nextHandle); + return nextHandle++; + } + function clearImmediate(handle) { + delete tasksByHandle[handle]; + } + function run(task) { + var callback = task.callback; + var args = task.args; + switch (args.length) { + case 0: + callback(); + break; + case 1: + callback(args[0]); + break; + case 2: + callback(args[0], args[1]); + break; + case 3: + callback(args[0], args[1], args[2]); + break; + default: + callback.apply(undefined2, args); + break; + } + } + function runIfPresent(handle) { + if (currentlyRunningATask) { + setTimeout(runIfPresent, 0, handle); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunningATask = true; + try { + run(task); + } finally { + clearImmediate(handle); + currentlyRunningATask = false; + } + } + } + } + function installNextTickImplementation() { + registerImmediate = function(handle) { + process.nextTick(function() { + runIfPresent(handle); + }); + }; + } + function canUsePostMessage() { + if (global2.postMessage && !global2.importScripts) { + var postMessageIsAsynchronous = true; + var oldOnMessage = global2.onmessage; + global2.onmessage = function() { + postMessageIsAsynchronous = false; + }; + global2.postMessage("", "*"); + global2.onmessage = oldOnMessage; + return postMessageIsAsynchronous; + } + } + function installPostMessageImplementation() { + var messagePrefix = "setImmediate$" + Math.random() + "$"; + var onGlobalMessage = function(event) { + if (event.source === global2 && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { + runIfPresent(+event.data.slice(messagePrefix.length)); + } + }; + if (global2.addEventListener) { + global2.addEventListener("message", onGlobalMessage, false); + } else { + global2.attachEvent("onmessage", onGlobalMessage); + } + registerImmediate = function(handle) { + global2.postMessage(messagePrefix + handle, "*"); + }; + } + function installMessageChannelImplementation() { + var channel = new MessageChannel; + channel.port1.onmessage = function(event) { + var handle = event.data; + runIfPresent(handle); + }; + registerImmediate = function(handle) { + channel.port2.postMessage(handle); + }; + } + function installReadyStateChangeImplementation() { + var html = doc.documentElement; + registerImmediate = function(handle) { + var script = doc.createElement("script"); + script.onreadystatechange = function() { + runIfPresent(handle); + script.onreadystatechange = null; + html.removeChild(script); + script = null; + }; + html.appendChild(script); + }; + } + function installSetTimeoutImplementation() { + registerImmediate = function(handle) { + setTimeout(runIfPresent, 0, handle); + }; + } + var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global2); + attachTo = attachTo && attachTo.setTimeout ? attachTo : global2; + if ({}.toString.call(global2.process) === "[object process]") { + installNextTickImplementation(); + } else if (canUsePostMessage()) { + installPostMessageImplementation(); + } else if (global2.MessageChannel) { + installMessageChannelImplementation(); + } else if (doc && "onreadystatechange" in doc.createElement("script")) { + installReadyStateChangeImplementation(); + } else { + installSetTimeoutImplementation(); + } + attachTo.setImmediate = setImmediate2; + attachTo.clearImmediate = clearImmediate; + })(typeof self === "undefined" ? typeof global === "undefined" ? exports2 : global : self); +}); + +// node_modules/jszip/lib/utils.js +var require_utils = __commonJS((exports2) => { + var support = require_support(); + var base64 = require_base64(); + var nodejsUtils = require_nodejsUtils(); + var external = require_external(); + require_setImmediate(); + function string2binary(str) { + var result = null; + if (support.uint8array) { + result = new Uint8Array(str.length); + } else { + result = new Array(str.length); + } + return stringToArrayLike(str, result); + } + exports2.newBlob = function(part, type) { + exports2.checkSupport("blob"); + try { + return new Blob([part], { + type + }); + } catch (e) { + try { + var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; + var builder = new Builder; + builder.append(part); + return builder.getBlob(type); + } catch (e2) { + throw new Error("Bug : can't construct the Blob."); + } + } + }; + function identity(input) { + return input; + } + function stringToArrayLike(str, array) { + for (var i = 0;i < str.length; ++i) { + array[i] = str.charCodeAt(i) & 255; + } + return array; + } + var arrayToStringHelper = { + stringifyByChunk: function(array, type, chunk) { + var result = [], k2 = 0, len = array.length; + if (len <= chunk) { + return String.fromCharCode.apply(null, array); + } + while (k2 < len) { + if (type === "array" || type === "nodebuffer") { + result.push(String.fromCharCode.apply(null, array.slice(k2, Math.min(k2 + chunk, len)))); + } else { + result.push(String.fromCharCode.apply(null, array.subarray(k2, Math.min(k2 + chunk, len)))); + } + k2 += chunk; + } + return result.join(""); + }, + stringifyByChar: function(array) { + var resultStr = ""; + for (var i = 0;i < array.length; i++) { + resultStr += String.fromCharCode(array[i]); + } + return resultStr; + }, + applyCanBeUsed: { + uint8array: function() { + try { + return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1; + } catch (e) { + return false; + } + }(), + nodebuffer: function() { + try { + return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1; + } catch (e) { + return false; + } + }() + } + }; + function arrayLikeToString(array) { + var chunk = 65536, type = exports2.getTypeOf(array), canUseApply = true; + if (type === "uint8array") { + canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array; + } else if (type === "nodebuffer") { + canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer; + } + if (canUseApply) { + while (chunk > 1) { + try { + return arrayToStringHelper.stringifyByChunk(array, type, chunk); + } catch (e) { + chunk = Math.floor(chunk / 2); + } + } + } + return arrayToStringHelper.stringifyByChar(array); + } + exports2.applyFromCharCode = arrayLikeToString; + function arrayLikeToArrayLike(arrayFrom, arrayTo) { + for (var i = 0;i < arrayFrom.length; i++) { + arrayTo[i] = arrayFrom[i]; + } + return arrayTo; + } + var transform2 = {}; + transform2["string"] = { + string: identity, + array: function(input) { + return stringToArrayLike(input, new Array(input.length)); + }, + arraybuffer: function(input) { + return transform2["string"]["uint8array"](input).buffer; + }, + uint8array: function(input) { + return stringToArrayLike(input, new Uint8Array(input.length)); + }, + nodebuffer: function(input) { + return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length)); + } + }; + transform2["array"] = { + string: arrayLikeToString, + array: identity, + arraybuffer: function(input) { + return new Uint8Array(input).buffer; + }, + uint8array: function(input) { + return new Uint8Array(input); + }, + nodebuffer: function(input) { + return nodejsUtils.newBufferFrom(input); + } + }; + transform2["arraybuffer"] = { + string: function(input) { + return arrayLikeToString(new Uint8Array(input)); + }, + array: function(input) { + return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); + }, + arraybuffer: identity, + uint8array: function(input) { + return new Uint8Array(input); + }, + nodebuffer: function(input) { + return nodejsUtils.newBufferFrom(new Uint8Array(input)); + } + }; + transform2["uint8array"] = { + string: arrayLikeToString, + array: function(input) { + return arrayLikeToArrayLike(input, new Array(input.length)); + }, + arraybuffer: function(input) { + return input.buffer; + }, + uint8array: identity, + nodebuffer: function(input) { + return nodejsUtils.newBufferFrom(input); + } + }; + transform2["nodebuffer"] = { + string: arrayLikeToString, + array: function(input) { + return arrayLikeToArrayLike(input, new Array(input.length)); + }, + arraybuffer: function(input) { + return transform2["nodebuffer"]["uint8array"](input).buffer; + }, + uint8array: function(input) { + return arrayLikeToArrayLike(input, new Uint8Array(input.length)); + }, + nodebuffer: identity + }; + exports2.transformTo = function(outputType, input) { + if (!input) { + input = ""; + } + if (!outputType) { + return input; + } + exports2.checkSupport(outputType); + var inputType = exports2.getTypeOf(input); + var result = transform2[inputType][outputType](input); + return result; + }; + exports2.resolve = function(path) { + var parts = path.split("/"); + var result = []; + for (var index2 = 0;index2 < parts.length; index2++) { + var part = parts[index2]; + if (part === "." || part === "" && index2 !== 0 && index2 !== parts.length - 1) { + continue; + } else if (part === "..") { + result.pop(); + } else { + result.push(part); + } + } + return result.join("/"); + }; + exports2.getTypeOf = function(input) { + if (typeof input === "string") { + return "string"; + } + if (Object.prototype.toString.call(input) === "[object Array]") { + return "array"; + } + if (support.nodebuffer && nodejsUtils.isBuffer(input)) { + return "nodebuffer"; + } + if (support.uint8array && input instanceof Uint8Array) { + return "uint8array"; + } + if (support.arraybuffer && input instanceof ArrayBuffer) { + return "arraybuffer"; + } + }; + exports2.checkSupport = function(type) { + var supported = support[type.toLowerCase()]; + if (!supported) { + throw new Error(type + " is not supported by this platform"); + } + }; + exports2.MAX_VALUE_16BITS = 65535; + exports2.MAX_VALUE_32BITS = -1; + exports2.pretty = function(str) { + var res = "", code, i; + for (i = 0;i < (str || "").length; i++) { + code = str.charCodeAt(i); + res += "\\x" + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); + } + return res; + }; + exports2.delay = function(callback, args, self2) { + setImmediate(function() { + callback.apply(self2 || null, args || []); + }); + }; + exports2.inherits = function(ctor, superCtor) { + var Obj = function() { + }; + Obj.prototype = superCtor.prototype; + ctor.prototype = new Obj; + }; + exports2.extend = function() { + var result = {}, i, attr; + for (i = 0;i < arguments.length; i++) { + for (attr in arguments[i]) { + if (Object.prototype.hasOwnProperty.call(arguments[i], attr) && typeof result[attr] === "undefined") { + result[attr] = arguments[i][attr]; + } + } + } + return result; + }; + exports2.prepareContent = function(name2, inputData, isBinary, isOptimizedBinaryString, isBase64) { + var promise = external.Promise.resolve(inputData).then(function(data2) { + var isBlob = support.blob && (data2 instanceof Blob || ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(data2)) !== -1); + if (isBlob && typeof FileReader !== "undefined") { + return new external.Promise(function(resolve, reject2) { + var reader = new FileReader; + reader.onload = function(e) { + resolve(e.target.result); + }; + reader.onerror = function(e) { + reject2(e.target.error); + }; + reader.readAsArrayBuffer(data2); + }); + } else { + return data2; + } + }); + return promise.then(function(data2) { + var dataType = exports2.getTypeOf(data2); + if (!dataType) { + return external.Promise.reject(new Error("Can't read the data of '" + name2 + "'. Is it " + "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")); + } + if (dataType === "arraybuffer") { + data2 = exports2.transformTo("uint8array", data2); + } else if (dataType === "string") { + if (isBase64) { + data2 = base64.decode(data2); + } else if (isBinary) { + if (isOptimizedBinaryString !== true) { + data2 = string2binary(data2); + } + } + } + return data2; + }); + }; +}); + +// node_modules/jszip/lib/stream/GenericWorker.js +var require_GenericWorker = __commonJS((exports2, module2) => { + function GenericWorker(name2) { + this.name = name2 || "default"; + this.streamInfo = {}; + this.generatedError = null; + this.extraStreamInfo = {}; + this.isPaused = true; + this.isFinished = false; + this.isLocked = false; + this._listeners = { + data: [], + end: [], + error: [] + }; + this.previous = null; + } + GenericWorker.prototype = { + push: function(chunk) { + this.emit("data", chunk); + }, + end: function() { + if (this.isFinished) { + return false; + } + this.flush(); + try { + this.emit("end"); + this.cleanUp(); + this.isFinished = true; + } catch (e) { + this.emit("error", e); + } + return true; + }, + error: function(e) { + if (this.isFinished) { + return false; + } + if (this.isPaused) { + this.generatedError = e; + } else { + this.isFinished = true; + this.emit("error", e); + if (this.previous) { + this.previous.error(e); + } + this.cleanUp(); + } + return true; + }, + on: function(name2, listener) { + this._listeners[name2].push(listener); + return this; + }, + cleanUp: function() { + this.streamInfo = this.generatedError = this.extraStreamInfo = null; + this._listeners = []; + }, + emit: function(name2, arg) { + if (this._listeners[name2]) { + for (var i = 0;i < this._listeners[name2].length; i++) { + this._listeners[name2][i].call(this, arg); + } + } + }, + pipe: function(next) { + return next.registerPrevious(this); + }, + registerPrevious: function(previous) { + if (this.isLocked) { + throw new Error("The stream '" + this + "' has already been used."); + } + this.streamInfo = previous.streamInfo; + this.mergeStreamInfo(); + this.previous = previous; + var self2 = this; + previous.on("data", function(chunk) { + self2.processChunk(chunk); + }); + previous.on("end", function() { + self2.end(); + }); + previous.on("error", function(e) { + self2.error(e); + }); + return this; + }, + pause: function() { + if (this.isPaused || this.isFinished) { + return false; + } + this.isPaused = true; + if (this.previous) { + this.previous.pause(); + } + return true; + }, + resume: function() { + if (!this.isPaused || this.isFinished) { + return false; + } + this.isPaused = false; + var withError = false; + if (this.generatedError) { + this.error(this.generatedError); + withError = true; + } + if (this.previous) { + this.previous.resume(); + } + return !withError; + }, + flush: function() { + }, + processChunk: function(chunk) { + this.push(chunk); + }, + withStreamInfo: function(key2, value2) { + this.extraStreamInfo[key2] = value2; + this.mergeStreamInfo(); + return this; + }, + mergeStreamInfo: function() { + for (var key2 in this.extraStreamInfo) { + if (!Object.prototype.hasOwnProperty.call(this.extraStreamInfo, key2)) { + continue; + } + this.streamInfo[key2] = this.extraStreamInfo[key2]; + } + }, + lock: function() { + if (this.isLocked) { + throw new Error("The stream '" + this + "' has already been used."); + } + this.isLocked = true; + if (this.previous) { + this.previous.lock(); + } + }, + toString: function() { + var me = "Worker " + this.name; + if (this.previous) { + return this.previous + " -> " + me; + } else { + return me; + } + } + }; + module2.exports = GenericWorker; +}); + +// node_modules/jszip/lib/utf8.js +var require_utf8 = __commonJS((exports2) => { + var utils = require_utils(); + var support = require_support(); + var nodejsUtils = require_nodejsUtils(); + var GenericWorker = require_GenericWorker(); + var _utf8len = new Array(256); + for (i = 0;i < 256; i++) { + _utf8len[i] = i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1; + } + var i; + _utf8len[254] = _utf8len[254] = 1; + var string2buf = function(str) { + var buf, c, c2, m_pos, i2, str_len = str.length, buf_len = 0; + for (m_pos = 0;m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4; + } + if (support.uint8array) { + buf = new Uint8Array(buf_len); + } else { + buf = new Array(buf_len); + } + for (i2 = 0, m_pos = 0;i2 < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + if (c < 128) { + buf[i2++] = c; + } else if (c < 2048) { + buf[i2++] = 192 | c >>> 6; + buf[i2++] = 128 | c & 63; + } else if (c < 65536) { + buf[i2++] = 224 | c >>> 12; + buf[i2++] = 128 | c >>> 6 & 63; + buf[i2++] = 128 | c & 63; + } else { + buf[i2++] = 240 | c >>> 18; + buf[i2++] = 128 | c >>> 12 & 63; + buf[i2++] = 128 | c >>> 6 & 63; + buf[i2++] = 128 | c & 63; + } + } + return buf; + }; + var utf8border = function(buf, max) { + var pos; + max = max || buf.length; + if (max > buf.length) { + max = buf.length; + } + pos = max - 1; + while (pos >= 0 && (buf[pos] & 192) === 128) { + pos--; + } + if (pos < 0) { + return max; + } + if (pos === 0) { + return max; + } + return pos + _utf8len[buf[pos]] > max ? pos : max; + }; + var buf2string = function(buf) { + var i2, out, c, c_len; + var len = buf.length; + var utf16buf = new Array(len * 2); + for (out = 0, i2 = 0;i2 < len; ) { + c = buf[i2++]; + if (c < 128) { + utf16buf[out++] = c; + continue; + } + c_len = _utf8len[c]; + if (c_len > 4) { + utf16buf[out++] = 65533; + i2 += c_len - 1; + continue; + } + c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7; + while (c_len > 1 && i2 < len) { + c = c << 6 | buf[i2++] & 63; + c_len--; + } + if (c_len > 1) { + utf16buf[out++] = 65533; + continue; + } + if (c < 65536) { + utf16buf[out++] = c; + } else { + c -= 65536; + utf16buf[out++] = 55296 | c >> 10 & 1023; + utf16buf[out++] = 56320 | c & 1023; + } + } + if (utf16buf.length !== out) { + if (utf16buf.subarray) { + utf16buf = utf16buf.subarray(0, out); + } else { + utf16buf.length = out; + } + } + return utils.applyFromCharCode(utf16buf); + }; + exports2.utf8encode = function utf8encode(str) { + if (support.nodebuffer) { + return nodejsUtils.newBufferFrom(str, "utf-8"); + } + return string2buf(str); + }; + exports2.utf8decode = function utf8decode(buf) { + if (support.nodebuffer) { + return utils.transformTo("nodebuffer", buf).toString("utf-8"); + } + buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf); + return buf2string(buf); + }; + function Utf8DecodeWorker() { + GenericWorker.call(this, "utf-8 decode"); + this.leftOver = null; + } + utils.inherits(Utf8DecodeWorker, GenericWorker); + Utf8DecodeWorker.prototype.processChunk = function(chunk) { + var data2 = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data); + if (this.leftOver && this.leftOver.length) { + if (support.uint8array) { + var previousData = data2; + data2 = new Uint8Array(previousData.length + this.leftOver.length); + data2.set(this.leftOver, 0); + data2.set(previousData, this.leftOver.length); + } else { + data2 = this.leftOver.concat(data2); + } + this.leftOver = null; + } + var nextBoundary = utf8border(data2); + var usableData = data2; + if (nextBoundary !== data2.length) { + if (support.uint8array) { + usableData = data2.subarray(0, nextBoundary); + this.leftOver = data2.subarray(nextBoundary, data2.length); + } else { + usableData = data2.slice(0, nextBoundary); + this.leftOver = data2.slice(nextBoundary, data2.length); + } + } + this.push({ + data: exports2.utf8decode(usableData), + meta: chunk.meta + }); + }; + Utf8DecodeWorker.prototype.flush = function() { + if (this.leftOver && this.leftOver.length) { + this.push({ + data: exports2.utf8decode(this.leftOver), + meta: {} + }); + this.leftOver = null; + } + }; + exports2.Utf8DecodeWorker = Utf8DecodeWorker; + function Utf8EncodeWorker() { + GenericWorker.call(this, "utf-8 encode"); + } + utils.inherits(Utf8EncodeWorker, GenericWorker); + Utf8EncodeWorker.prototype.processChunk = function(chunk) { + this.push({ + data: exports2.utf8encode(chunk.data), + meta: chunk.meta + }); + }; + exports2.Utf8EncodeWorker = Utf8EncodeWorker; +}); + +// node_modules/jszip/lib/stream/ConvertWorker.js +var require_ConvertWorker = __commonJS((exports2, module2) => { + var GenericWorker = require_GenericWorker(); + var utils = require_utils(); + function ConvertWorker(destType) { + GenericWorker.call(this, "ConvertWorker to " + destType); + this.destType = destType; + } + utils.inherits(ConvertWorker, GenericWorker); + ConvertWorker.prototype.processChunk = function(chunk) { + this.push({ + data: utils.transformTo(this.destType, chunk.data), + meta: chunk.meta + }); + }; + module2.exports = ConvertWorker; +}); + +// node_modules/jszip/lib/nodejs/NodejsStreamOutputAdapter.js +var require_NodejsStreamOutputAdapter = __commonJS((exports2, module2) => { + var Readable = (init_stream(), __toCommonJS(exports_stream)).Readable; + var utils = require_utils(); + utils.inherits(NodejsStreamOutputAdapter, Readable); + function NodejsStreamOutputAdapter(helper, options, updateCb) { + Readable.call(this, options); + this._helper = helper; + var self2 = this; + helper.on("data", function(data2, meta) { + if (!self2.push(data2)) { + self2._helper.pause(); + } + if (updateCb) { + updateCb(meta); + } + }).on("error", function(e) { + self2.emit("error", e); + }).on("end", function() { + self2.push(null); + }); + } + NodejsStreamOutputAdapter.prototype._read = function() { + this._helper.resume(); + }; + module2.exports = NodejsStreamOutputAdapter; +}); + +// node_modules/jszip/lib/stream/StreamHelper.js +var require_StreamHelper = __commonJS((exports2, module2) => { + var utils = require_utils(); + var ConvertWorker = require_ConvertWorker(); + var GenericWorker = require_GenericWorker(); + var base64 = require_base64(); + var support = require_support(); + var external = require_external(); + var NodejsStreamOutputAdapter = null; + if (support.nodestream) { + try { + NodejsStreamOutputAdapter = require_NodejsStreamOutputAdapter(); + } catch (e) { + } + } + function transformZipOutput(type, content2, mimeType) { + switch (type) { + case "blob": + return utils.newBlob(utils.transformTo("arraybuffer", content2), mimeType); + case "base64": + return base64.encode(content2); + default: + return utils.transformTo(type, content2); + } + } + function concat(type, dataArray) { + var i, index2 = 0, res = null, totalLength = 0; + for (i = 0;i < dataArray.length; i++) { + totalLength += dataArray[i].length; + } + switch (type) { + case "string": + return dataArray.join(""); + case "array": + return Array.prototype.concat.apply([], dataArray); + case "uint8array": + res = new Uint8Array(totalLength); + for (i = 0;i < dataArray.length; i++) { + res.set(dataArray[i], index2); + index2 += dataArray[i].length; + } + return res; + case "nodebuffer": + return Buffer.concat(dataArray); + default: + throw new Error("concat : unsupported type '" + type + "'"); + } + } + function accumulate(helper, updateCallback) { + return new external.Promise(function(resolve, reject2) { + var dataArray = []; + var { _internalType: chunkType, _outputType: resultType, _mimeType: mimeType } = helper; + helper.on("data", function(data2, meta) { + dataArray.push(data2); + if (updateCallback) { + updateCallback(meta); + } + }).on("error", function(err) { + dataArray = []; + reject2(err); + }).on("end", function() { + try { + var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType); + resolve(result); + } catch (e) { + reject2(e); + } + dataArray = []; + }).resume(); + }); + } + function StreamHelper(worker, outputType, mimeType) { + var internalType = outputType; + switch (outputType) { + case "blob": + case "arraybuffer": + internalType = "uint8array"; + break; + case "base64": + internalType = "string"; + break; + } + try { + this._internalType = internalType; + this._outputType = outputType; + this._mimeType = mimeType; + utils.checkSupport(internalType); + this._worker = worker.pipe(new ConvertWorker(internalType)); + worker.lock(); + } catch (e) { + this._worker = new GenericWorker("error"); + this._worker.error(e); + } + } + StreamHelper.prototype = { + accumulate: function(updateCb) { + return accumulate(this, updateCb); + }, + on: function(evt, fn) { + var self2 = this; + if (evt === "data") { + this._worker.on(evt, function(chunk) { + fn.call(self2, chunk.data, chunk.meta); + }); + } else { + this._worker.on(evt, function() { + utils.delay(fn, arguments, self2); + }); + } + return this; + }, + resume: function() { + utils.delay(this._worker.resume, [], this._worker); + return this; + }, + pause: function() { + this._worker.pause(); + return this; + }, + toNodejsStream: function(updateCb) { + utils.checkSupport("nodestream"); + if (this._outputType !== "nodebuffer") { + throw new Error(this._outputType + " is not supported by this method"); + } + return new NodejsStreamOutputAdapter(this, { + objectMode: this._outputType !== "nodebuffer" + }, updateCb); + } + }; + module2.exports = StreamHelper; +}); + +// node_modules/jszip/lib/defaults.js +var require_defaults = __commonJS((exports2) => { + exports2.base64 = false; + exports2.binary = false; + exports2.dir = false; + exports2.createFolders = true; + exports2.date = null; + exports2.compression = null; + exports2.compressionOptions = null; + exports2.comment = null; + exports2.unixPermissions = null; + exports2.dosPermissions = null; +}); + +// node_modules/jszip/lib/stream/DataWorker.js +var require_DataWorker = __commonJS((exports2, module2) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var DEFAULT_BLOCK_SIZE = 16 * 1024; + function DataWorker(dataP) { + GenericWorker.call(this, "DataWorker"); + var self2 = this; + this.dataIsReady = false; + this.index = 0; + this.max = 0; + this.data = null; + this.type = ""; + this._tickScheduled = false; + dataP.then(function(data2) { + self2.dataIsReady = true; + self2.data = data2; + self2.max = data2 && data2.length || 0; + self2.type = utils.getTypeOf(data2); + if (!self2.isPaused) { + self2._tickAndRepeat(); + } + }, function(e) { + self2.error(e); + }); + } + utils.inherits(DataWorker, GenericWorker); + DataWorker.prototype.cleanUp = function() { + GenericWorker.prototype.cleanUp.call(this); + this.data = null; + }; + DataWorker.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) { + return false; + } + if (!this._tickScheduled && this.dataIsReady) { + this._tickScheduled = true; + utils.delay(this._tickAndRepeat, [], this); + } + return true; + }; + DataWorker.prototype._tickAndRepeat = function() { + this._tickScheduled = false; + if (this.isPaused || this.isFinished) { + return; + } + this._tick(); + if (!this.isFinished) { + utils.delay(this._tickAndRepeat, [], this); + this._tickScheduled = true; + } + }; + DataWorker.prototype._tick = function() { + if (this.isPaused || this.isFinished) { + return false; + } + var size = DEFAULT_BLOCK_SIZE; + var data2 = null, nextIndex = Math.min(this.max, this.index + size); + if (this.index >= this.max) { + return this.end(); + } else { + switch (this.type) { + case "string": + data2 = this.data.substring(this.index, nextIndex); + break; + case "uint8array": + data2 = this.data.subarray(this.index, nextIndex); + break; + case "array": + case "nodebuffer": + data2 = this.data.slice(this.index, nextIndex); + break; + } + this.index = nextIndex; + return this.push({ + data: data2, + meta: { + percent: this.max ? this.index / this.max * 100 : 0 + } + }); + } + }; + module2.exports = DataWorker; +}); + +// node_modules/jszip/lib/crc32.js +var require_crc32 = __commonJS((exports2, module2) => { + var utils = require_utils(); + function makeTable() { + var c, table = []; + for (var n = 0;n < 256; n++) { + c = n; + for (var k2 = 0;k2 < 8; k2++) { + c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; + } + table[n] = c; + } + return table; + } + var crcTable = makeTable(); + function crc32(crc, buf, len, pos) { + var t = crcTable, end = pos + len; + crc = crc ^ -1; + for (var i = pos;i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255]; + } + return crc ^ -1; + } + function crc32str(crc, str, len, pos) { + var t = crcTable, end = pos + len; + crc = crc ^ -1; + for (var i = pos;i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ str.charCodeAt(i)) & 255]; + } + return crc ^ -1; + } + module2.exports = function crc32wrapper(input, crc) { + if (typeof input === "undefined" || !input.length) { + return 0; + } + var isArray2 = utils.getTypeOf(input) !== "string"; + if (isArray2) { + return crc32(crc | 0, input, input.length, 0); + } else { + return crc32str(crc | 0, input, input.length, 0); + } + }; +}); + +// node_modules/jszip/lib/stream/Crc32Probe.js +var require_Crc32Probe = __commonJS((exports2, module2) => { + var GenericWorker = require_GenericWorker(); + var crc32 = require_crc32(); + var utils = require_utils(); + function Crc32Probe() { + GenericWorker.call(this, "Crc32Probe"); + this.withStreamInfo("crc32", 0); + } + utils.inherits(Crc32Probe, GenericWorker); + Crc32Probe.prototype.processChunk = function(chunk) { + this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0); + this.push(chunk); + }; + module2.exports = Crc32Probe; +}); + +// node_modules/jszip/lib/stream/DataLengthProbe.js +var require_DataLengthProbe = __commonJS((exports2, module2) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + function DataLengthProbe(propName) { + GenericWorker.call(this, "DataLengthProbe for " + propName); + this.propName = propName; + this.withStreamInfo(propName, 0); + } + utils.inherits(DataLengthProbe, GenericWorker); + DataLengthProbe.prototype.processChunk = function(chunk) { + if (chunk) { + var length2 = this.streamInfo[this.propName] || 0; + this.streamInfo[this.propName] = length2 + chunk.data.length; + } + GenericWorker.prototype.processChunk.call(this, chunk); + }; + module2.exports = DataLengthProbe; +}); + +// node_modules/jszip/lib/compressedObject.js +var require_compressedObject = __commonJS((exports2, module2) => { + var external = require_external(); + var DataWorker = require_DataWorker(); + var Crc32Probe = require_Crc32Probe(); + var DataLengthProbe = require_DataLengthProbe(); + function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data2) { + this.compressedSize = compressedSize; + this.uncompressedSize = uncompressedSize; + this.crc32 = crc32; + this.compression = compression; + this.compressedContent = data2; + } + CompressedObject.prototype = { + getContentWorker: function() { + var worker = new DataWorker(external.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new DataLengthProbe("data_length")); + var that = this; + worker.on("end", function() { + if (this.streamInfo["data_length"] !== that.uncompressedSize) { + throw new Error("Bug : uncompressed data size mismatch"); + } + }); + return worker; + }, + getCompressedWorker: function() { + return new DataWorker(external.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression); + } + }; + CompressedObject.createWorkerFrom = function(uncompressedWorker, compression, compressionOptions) { + return uncompressedWorker.pipe(new Crc32Probe).pipe(new DataLengthProbe("uncompressedSize")).pipe(compression.compressWorker(compressionOptions)).pipe(new DataLengthProbe("compressedSize")).withStreamInfo("compression", compression); + }; + module2.exports = CompressedObject; +}); + +// node_modules/jszip/lib/zipObject.js +var require_zipObject = __commonJS((exports2, module2) => { + var StreamHelper = require_StreamHelper(); + var DataWorker = require_DataWorker(); + var utf8 = require_utf8(); + var CompressedObject = require_compressedObject(); + var GenericWorker = require_GenericWorker(); + var ZipObject = function(name2, data2, options) { + this.name = name2; + this.dir = options.dir; + this.date = options.date; + this.comment = options.comment; + this.unixPermissions = options.unixPermissions; + this.dosPermissions = options.dosPermissions; + this._data = data2; + this._dataBinary = options.binary; + this.options = { + compression: options.compression, + compressionOptions: options.compressionOptions + }; + }; + ZipObject.prototype = { + internalStream: function(type) { + var result = null, outputType = "string"; + try { + if (!type) { + throw new Error("No output type specified."); + } + outputType = type.toLowerCase(); + var askUnicodeString = outputType === "string" || outputType === "text"; + if (outputType === "binarystring" || outputType === "text") { + outputType = "string"; + } + result = this._decompressWorker(); + var isUnicodeString = !this._dataBinary; + if (isUnicodeString && !askUnicodeString) { + result = result.pipe(new utf8.Utf8EncodeWorker); + } + if (!isUnicodeString && askUnicodeString) { + result = result.pipe(new utf8.Utf8DecodeWorker); + } + } catch (e) { + result = new GenericWorker("error"); + result.error(e); + } + return new StreamHelper(result, outputType, ""); + }, + async: function(type, onUpdate) { + return this.internalStream(type).accumulate(onUpdate); + }, + nodeStream: function(type, onUpdate) { + return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate); + }, + _compressWorker: function(compression, compressionOptions) { + if (this._data instanceof CompressedObject && this._data.compression.magic === compression.magic) { + return this._data.getCompressedWorker(); + } else { + var result = this._decompressWorker(); + if (!this._dataBinary) { + result = result.pipe(new utf8.Utf8EncodeWorker); + } + return CompressedObject.createWorkerFrom(result, compression, compressionOptions); + } + }, + _decompressWorker: function() { + if (this._data instanceof CompressedObject) { + return this._data.getContentWorker(); + } else if (this._data instanceof GenericWorker) { + return this._data; + } else { + return new DataWorker(this._data); + } + } + }; + var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"]; + var removedFn = function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }; + for (i = 0;i < removedMethods.length; i++) { + ZipObject.prototype[removedMethods[i]] = removedFn; + } + var i; + module2.exports = ZipObject; +}); + +// node_modules/pako/lib/utils/common.js +var require_common = __commonJS((exports2) => { + var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined"; + function _has(obj, key2) { + return Object.prototype.hasOwnProperty.call(obj, key2); + } + exports2.assign = function(obj) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { + continue; + } + if (typeof source !== "object") { + throw new TypeError(source + "must be non-object"); + } + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + return obj; + }; + exports2.shrinkBuf = function(buf, size) { + if (buf.length === size) { + return buf; + } + if (buf.subarray) { + return buf.subarray(0, size); + } + buf.length = size; + return buf; + }; + var fnTyped = { + arraySet: function(dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + for (var i = 0;i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + flattenChunks: function(chunks) { + var i, l, len, pos, chunk, result; + len = 0; + for (i = 0, l = chunks.length;i < l; i++) { + len += chunks[i].length; + } + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length;i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + return result; + } + }; + var fnUntyped = { + arraySet: function(dest, src, src_offs, len, dest_offs) { + for (var i = 0;i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + flattenChunks: function(chunks) { + return [].concat.apply([], chunks); + } + }; + exports2.setTyped = function(on) { + if (on) { + exports2.Buf8 = Uint8Array; + exports2.Buf16 = Uint16Array; + exports2.Buf32 = Int32Array; + exports2.assign(exports2, fnTyped); + } else { + exports2.Buf8 = Array; + exports2.Buf16 = Array; + exports2.Buf32 = Array; + exports2.assign(exports2, fnUntyped); + } + }; + exports2.setTyped(TYPED_OK); +}); + +// node_modules/pako/lib/zlib/trees.js +var require_trees = __commonJS((exports2) => { + var utils = require_common(); + var Z_FIXED = 4; + var Z_BINARY = 0; + var Z_TEXT = 1; + var Z_UNKNOWN = 2; + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + var STORED_BLOCK = 0; + var STATIC_TREES = 1; + var DYN_TREES = 2; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var Buf_size = 16; + var MAX_BL_BITS = 7; + var END_BLOCK = 256; + var REP_3_6 = 16; + var REPZ_3_10 = 17; + var REPZ_11_138 = 18; + var 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]; + var 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]; + var extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]; + var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + var DIST_CODE_LEN = 512; + var static_ltree = new Array((L_CODES + 2) * 2); + zero(static_ltree); + var static_dtree = new Array(D_CODES * 2); + zero(static_dtree); + var _dist_code = new Array(DIST_CODE_LEN); + zero(_dist_code); + var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); + zero(_length_code); + var base_length = new Array(LENGTH_CODES); + zero(base_length); + var base_dist = new Array(D_CODES); + zero(base_dist); + function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + this.static_tree = static_tree; + this.extra_bits = extra_bits; + this.extra_base = extra_base; + this.elems = elems; + this.max_length = max_length; + this.has_stree = static_tree && static_tree.length; + } + var static_l_desc; + var static_d_desc; + var static_bl_desc; + function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; + this.max_code = 0; + this.stat_desc = stat_desc; + } + function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; + } + function put_short(s, w) { + s.pending_buf[s.pending++] = w & 255; + s.pending_buf[s.pending++] = w >>> 8 & 255; + } + function send_bits(s, value2, length2) { + if (s.bi_valid > Buf_size - length2) { + s.bi_buf |= value2 << s.bi_valid & 65535; + put_short(s, s.bi_buf); + s.bi_buf = value2 >> Buf_size - s.bi_valid; + s.bi_valid += length2 - Buf_size; + } else { + s.bi_buf |= value2 << s.bi_valid & 65535; + s.bi_valid += length2; + } + } + function send_code(s, c, tree) { + send_bits(s, tree[c * 2], tree[c * 2 + 1]); + } + function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; + } + function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 255; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } + } + function gen_bitlen(s, desc) { + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; + var n, m; + var bits; + var xbits; + var f; + var overflow = 0; + for (bits = 0;bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + tree[s.heap[s.heap_max] * 2 + 1] = 0; + for (h = s.heap_max + 1;h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1] = bits; + if (n > max_code) { + continue; + } + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1] + xbits); + } + } + if (overflow === 0) { + return; + } + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { + bits--; + } + s.bl_count[bits]--; + s.bl_count[bits + 1] += 2; + s.bl_count[max_length]--; + overflow -= 2; + } while (overflow > 0); + for (bits = max_length;bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { + continue; + } + if (tree[m * 2 + 1] !== bits) { + s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2]; + tree[m * 2 + 1] = bits; + } + n--; + } + } + } + function gen_codes(tree, max_code, bl_count) { + var next_code = new Array(MAX_BITS + 1); + var code = 0; + var bits; + var n; + for (bits = 1;bits <= MAX_BITS; bits++) { + next_code[bits] = code = code + bl_count[bits - 1] << 1; + } + for (n = 0;n <= max_code; n++) { + var len = tree[n * 2 + 1]; + if (len === 0) { + continue; + } + tree[n * 2] = bi_reverse(next_code[len]++, len); + } + } + function tr_static_init() { + var n; + var bits; + var length2; + var code; + var dist; + var bl_count = new Array(MAX_BITS + 1); + length2 = 0; + for (code = 0;code < LENGTH_CODES - 1; code++) { + base_length[code] = length2; + for (n = 0;n < 1 << extra_lbits[code]; n++) { + _length_code[length2++] = code; + } + } + _length_code[length2 - 1] = code; + dist = 0; + for (code = 0;code < 16; code++) { + base_dist[code] = dist; + for (n = 0;n < 1 << extra_dbits[code]; n++) { + _dist_code[dist++] = code; + } + } + dist >>= 7; + for (;code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0;n < 1 << extra_dbits[code] - 7; n++) { + _dist_code[256 + dist++] = code; + } + } + for (bits = 0;bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1] = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1] = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + gen_codes(static_ltree, L_CODES + 1, bl_count); + for (n = 0;n < D_CODES; n++) { + static_dtree[n * 2 + 1] = 5; + static_dtree[n * 2] = bi_reverse(n, 5); + } + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + } + function init_block(s) { + var n; + for (n = 0;n < L_CODES; n++) { + s.dyn_ltree[n * 2] = 0; + } + for (n = 0;n < D_CODES; n++) { + s.dyn_dtree[n * 2] = 0; + } + for (n = 0;n < BL_CODES; n++) { + s.bl_tree[n * 2] = 0; + } + s.dyn_ltree[END_BLOCK * 2] = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; + } + function bi_windup(s) { + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; + } + function copy_block(s, buf, len, header) { + bi_windup(s); + if (header) { + put_short(s, len); + put_short(s, ~len); + } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; + } + function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return tree[_n2] < tree[_m2] || tree[_n2] === tree[_m2] && depth[n] <= depth[m]; + } + function pqdownheap(s, tree, k2) { + var v = s.heap[k2]; + var j = k2 << 1; + while (j <= s.heap_len) { + if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + if (smaller(tree, v, s.heap[j], s.depth)) { + break; + } + s.heap[k2] = s.heap[j]; + k2 = j; + j <<= 1; + } + s.heap[k2] = v; + } + function compress_block(s, ltree, dtree) { + var dist; + var lc; + var lx = 0; + var code; + var extra; + if (s.last_lit !== 0) { + do { + dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1]; + lc = s.pending_buf[s.l_buf + lx]; + lx++; + if (dist === 0) { + send_code(s, lc, ltree); + } else { + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); + } + dist--; + code = d_code(dist); + send_code(s, code, dtree); + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); + } + } + } while (lx < s.last_lit); + } + send_code(s, END_BLOCK, ltree); + } + function build_tree(s, desc) { + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; + var max_code = -1; + var node; + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + for (n = 0;n < elems; n++) { + if (tree[n * 2] !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + } else { + tree[n * 2 + 1] = 0; + } + } + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; + tree[node * 2] = 1; + s.depth[node] = 0; + s.opt_len--; + if (has_stree) { + s.static_len -= stree[node * 2 + 1]; + } + } + desc.max_code = max_code; + for (n = s.heap_len >> 1;n >= 1; n--) { + pqdownheap(s, tree, n); + } + node = elems; + do { + n = s.heap[1]; + s.heap[1] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1); + m = s.heap[1]; + s.heap[--s.heap_max] = n; + s.heap[--s.heap_max] = m; + tree[node * 2] = tree[n * 2] + tree[m * 2]; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1] = tree[m * 2 + 1] = node; + s.heap[1] = node++; + pqdownheap(s, tree, 1); + } while (s.heap_len >= 2); + s.heap[--s.heap_max] = s.heap[1]; + gen_bitlen(s, desc); + gen_codes(tree, max_code, s.bl_count); + } + function scan_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[0 * 2 + 1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1] = 65535; + for (n = 0;n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) { + continue; + } else if (count < min_count) { + s.bl_tree[curlen * 2] += count; + } else if (curlen !== 0) { + if (curlen !== prevlen) { + s.bl_tree[curlen * 2]++; + } + s.bl_tree[REP_3_6 * 2]++; + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]++; + } else { + s.bl_tree[REPZ_11_138 * 2]++; + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function send_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[0 * 2 + 1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + for (n = 0;n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) { + continue; + } else if (count < min_count) { + do { + send_code(s, curlen, s.bl_tree); + } while (--count !== 0); + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function build_bl_tree(s) { + var max_blindex; + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + build_tree(s, s.bl_desc); + for (max_blindex = BL_CODES - 1;max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1] !== 0) { + break; + } + } + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + return max_blindex; + } + function send_all_trees(s, lcodes, dcodes, blcodes) { + var rank; + send_bits(s, lcodes - 257, 5); + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); + for (rank = 0;rank < blcodes; rank++) { + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1], 3); + } + send_tree(s, s.dyn_ltree, lcodes - 1); + send_tree(s, s.dyn_dtree, dcodes - 1); + } + function detect_data_type(s) { + var black_mask = 4093624447; + var n; + for (n = 0;n <= 31; n++, black_mask >>>= 1) { + if (black_mask & 1 && s.dyn_ltree[n * 2] !== 0) { + return Z_BINARY; + } + } + if (s.dyn_ltree[9 * 2] !== 0 || s.dyn_ltree[10 * 2] !== 0 || s.dyn_ltree[13 * 2] !== 0) { + return Z_TEXT; + } + for (n = 32;n < LITERALS; n++) { + if (s.dyn_ltree[n * 2] !== 0) { + return Z_TEXT; + } + } + return Z_BINARY; + } + var static_init_done = false; + function _tr_init(s) { + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + s.bi_buf = 0; + s.bi_valid = 0; + init_block(s); + } + function _tr_stored_block(s, buf, stored_len, last2) { + send_bits(s, (STORED_BLOCK << 1) + (last2 ? 1 : 0), 3); + copy_block(s, buf, stored_len, true); + } + function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); + } + function _tr_flush_block(s, buf, stored_len, last2) { + var opt_lenb, static_lenb; + var max_blindex = 0; + if (s.level > 0) { + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + build_tree(s, s.l_desc); + build_tree(s, s.d_desc); + max_blindex = build_bl_tree(s); + opt_lenb = s.opt_len + 3 + 7 >>> 3; + static_lenb = s.static_len + 3 + 7 >>> 3; + if (static_lenb <= opt_lenb) { + opt_lenb = static_lenb; + } + } else { + opt_lenb = static_lenb = stored_len + 5; + } + if (stored_len + 4 <= opt_lenb && buf !== -1) { + _tr_stored_block(s, buf, stored_len, last2); + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + send_bits(s, (STATIC_TREES << 1) + (last2 ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + } else { + send_bits(s, (DYN_TREES << 1) + (last2 ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + init_block(s); + if (last2) { + bi_windup(s); + } + } + function _tr_tally(s, dist, lc) { + s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 255; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 255; + s.pending_buf[s.l_buf + s.last_lit] = lc & 255; + s.last_lit++; + if (dist === 0) { + s.dyn_ltree[lc * 2]++; + } else { + s.matches++; + dist--; + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]++; + s.dyn_dtree[d_code(dist) * 2]++; + } + return s.last_lit === s.lit_bufsize - 1; + } + exports2._tr_init = _tr_init; + exports2._tr_stored_block = _tr_stored_block; + exports2._tr_flush_block = _tr_flush_block; + exports2._tr_tally = _tr_tally; + exports2._tr_align = _tr_align; +}); + +// node_modules/pako/lib/zlib/adler32.js +var require_adler32 = __commonJS((exports2, module2) => { + function adler32(adler, buf, len, pos) { + var s1 = adler & 65535 | 0, s2 = adler >>> 16 & 65535 | 0, n = 0; + while (len !== 0) { + n = len > 2000 ? 2000 : len; + len -= n; + do { + s1 = s1 + buf[pos++] | 0; + s2 = s2 + s1 | 0; + } while (--n); + s1 %= 65521; + s2 %= 65521; + } + return s1 | s2 << 16 | 0; + } + module2.exports = adler32; +}); + +// node_modules/pako/lib/zlib/crc32.js +var require_crc322 = __commonJS((exports2, module2) => { + function makeTable() { + var c, table = []; + for (var n = 0;n < 256; n++) { + c = n; + for (var k2 = 0;k2 < 8; k2++) { + c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; + } + table[n] = c; + } + return table; + } + var crcTable = makeTable(); + function crc32(crc, buf, len, pos) { + var t = crcTable, end = pos + len; + crc ^= -1; + for (var i = pos;i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255]; + } + return crc ^ -1; + } + module2.exports = crc32; +}); + +// node_modules/pako/lib/zlib/messages.js +var require_messages = __commonJS((exports2, module2) => { + module2.exports = { + 2: "need dictionary", + 1: "stream end", + 0: "", + "-1": "file error", + "-2": "stream error", + "-3": "data error", + "-4": "insufficient memory", + "-5": "buffer error", + "-6": "incompatible version" + }; +}); + +// node_modules/pako/lib/zlib/deflate.js +var require_deflate = __commonJS((exports2) => { + var utils = require_common(); + var trees = require_trees(); + var adler32 = require_adler32(); + var crc32 = require_crc322(); + var msg = require_messages(); + var Z_NO_FLUSH = 0; + var Z_PARTIAL_FLUSH = 1; + var Z_FULL_FLUSH = 3; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_BUF_ERROR = -5; + var Z_DEFAULT_COMPRESSION = -1; + var Z_FILTERED = 1; + var Z_HUFFMAN_ONLY = 2; + var Z_RLE = 3; + var Z_FIXED = 4; + var Z_DEFAULT_STRATEGY = 0; + var Z_UNKNOWN = 2; + var Z_DEFLATED = 8; + var MAX_MEM_LEVEL = 9; + var MAX_WBITS = 15; + var DEF_MEM_LEVEL = 8; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1; + var PRESET_DICT = 32; + var INIT_STATE = 42; + var EXTRA_STATE = 69; + var NAME_STATE = 73; + var COMMENT_STATE = 91; + var HCRC_STATE = 103; + var BUSY_STATE = 113; + var FINISH_STATE = 666; + var BS_NEED_MORE = 1; + var BS_BLOCK_DONE = 2; + var BS_FINISH_STARTED = 3; + var BS_FINISH_DONE = 4; + var OS_CODE = 3; + function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; + } + function rank(f) { + return (f << 1) - (f > 4 ? 9 : 0); + } + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + function flush_pending(strm) { + var s = strm.state; + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { + return; + } + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } + } + function flush_block_only(s, last2) { + trees._tr_flush_block(s, s.block_start >= 0 ? s.block_start : -1, s.strstart - s.block_start, last2); + s.block_start = s.strstart; + flush_pending(s.strm); + } + function put_byte(s, b) { + s.pending_buf[s.pending++] = b; + } + function putShortMSB(s, b) { + s.pending_buf[s.pending++] = b >>> 8 & 255; + s.pending_buf[s.pending++] = b & 255; + } + function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + if (len > size) { + len = size; + } + if (len === 0) { + return 0; + } + strm.avail_in -= len; + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + strm.next_in += len; + strm.total_in += len; + return len; + } + function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; + var scan = s.strstart; + var match; + var len; + var best_len = s.prev_length; + var nice_match = s.nice_match; + var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0; + var _win = s.window; + var wmask = s.w_mask; + var prev = s.prev; + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + if (nice_match > s.lookahead) { + nice_match = s.lookahead; + } + do { + match = cur_match; + if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { + continue; + } + scan += 2; + match++; + do { + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; + } + function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + do { + more = s.window_size - s.lookahead - s.strstart; + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + s.block_start -= _w_size; + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + 1]) & s.hash_mask; + while (s.insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + } + function deflate_stored(s, flush) { + var max_block_size = 65535; + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + for (;; ) { + if (s.lookahead <= 1) { + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + s.strstart += s.lookahead; + s.lookahead = 0; + var max_start = s.block_start + max_block_size; + if (s.strstart === 0 || s.strstart >= max_start) { + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + if (s.strstart - s.block_start >= s.w_size - MIN_LOOKAHEAD) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.strstart > s.block_start) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_NEED_MORE; + } + function deflate_fast(s, flush) { + var hash_head; + var bflush; + for (;; ) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + if (hash_head !== 0 && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + } + if (s.match_length >= MIN_MATCH) { + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + if (s.match_length <= s.max_lazy_match && s.lookahead >= MIN_MATCH) { + s.match_length--; + do { + s.strstart++; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } while (--s.match_length !== 0); + s.strstart++; + } else { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + 1]) & s.hash_mask; + } + } else { + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_slow(s, flush) { + var hash_head; + var bflush; + var max_insert; + for (;; ) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + if (hash_head !== 0 && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + if (s.match_length <= 5 && (s.strategy === Z_FILTERED || s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096)) { + s.match_length = MIN_MATCH - 1; + } + } + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } else if (s.match_available) { + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + if (bflush) { + flush_block_only(s, false); + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + if (s.match_available) { + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_rle(s, flush) { + var bflush; + var prev; + var scan, strend; + var _win = s.window; + for (;; ) { + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + } + if (s.match_length >= MIN_MATCH) { + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_huff(s, flush) { + var bflush; + for (;; ) { + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; + } + } + s.match_length = 0; + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; + } + var configuration_table; + configuration_table = [ + new Config(0, 0, 0, 0, deflate_stored), + new Config(4, 4, 8, 4, deflate_fast), + new Config(4, 5, 16, 8, deflate_fast), + new Config(4, 6, 32, 32, deflate_fast), + new Config(4, 4, 16, 16, deflate_slow), + new Config(8, 16, 32, 32, deflate_slow), + new Config(8, 16, 128, 128, deflate_slow), + new Config(8, 32, 128, 256, deflate_slow), + new Config(32, 128, 258, 1024, deflate_slow), + new Config(32, 258, 258, 4096, deflate_slow) + ]; + function lm_init(s) { + s.window_size = 2 * s.w_size; + zero(s.head); + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; + } + function DeflateState() { + this.strm = null; + this.status = 0; + this.pending_buf = null; + this.pending_buf_size = 0; + this.pending_out = 0; + this.pending = 0; + this.wrap = 0; + this.gzhead = null; + this.gzindex = 0; + this.method = Z_DEFLATED; + this.last_flush = -1; + this.w_size = 0; + this.w_bits = 0; + this.w_mask = 0; + this.window = null; + this.window_size = 0; + this.prev = null; + this.head = null; + this.ins_h = 0; + this.hash_size = 0; + this.hash_bits = 0; + this.hash_mask = 0; + this.hash_shift = 0; + this.block_start = 0; + this.match_length = 0; + this.prev_match = 0; + this.match_available = 0; + this.strstart = 0; + this.match_start = 0; + this.lookahead = 0; + this.prev_length = 0; + this.max_chain_length = 0; + this.max_lazy_match = 0; + this.level = 0; + this.strategy = 0; + this.good_match = 0; + this.nice_match = 0; + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + this.l_desc = null; + this.d_desc = null; + this.bl_desc = null; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + this.heap = new utils.Buf16(2 * L_CODES + 1); + zero(this.heap); + this.heap_len = 0; + this.heap_max = 0; + this.depth = new utils.Buf16(2 * L_CODES + 1); + zero(this.depth); + this.l_buf = 0; + this.lit_bufsize = 0; + this.last_lit = 0; + this.d_buf = 0; + this.opt_len = 0; + this.static_len = 0; + this.matches = 0; + this.insert = 0; + this.bi_buf = 0; + this.bi_valid = 0; + } + function deflateResetKeep(strm) { + var s; + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + s = strm.state; + s.pending = 0; + s.pending_out = 0; + if (s.wrap < 0) { + s.wrap = -s.wrap; + } + s.status = s.wrap ? INIT_STATE : BUSY_STATE; + strm.adler = s.wrap === 2 ? 0 : 1; + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; + } + function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; + } + function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + if (strm.state.wrap !== 2) { + return Z_STREAM_ERROR; + } + strm.state.gzhead = head; + return Z_OK; + } + function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { + return Z_STREAM_ERROR; + } + var wrap = 1; + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else if (windowBits > 15) { + wrap = 2; + windowBits -= 16; + } + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + if (windowBits === 8) { + windowBits = 9; + } + var s = new DeflateState; + strm.state = s; + s.strm = strm; + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + s.lit_bufsize = 1 << memLevel + 6; + s.pending_buf_size = s.lit_bufsize * 4; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + s.d_buf = 1 * s.lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + s.level = level; + s.strategy = strategy; + s.method = method; + return deflateReset(strm); + } + function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); + } + function deflate(strm, flush) { + var old_flush, s; + var beg, val2; + if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + s = strm.state; + if (!strm.output || !strm.input && strm.avail_in !== 0 || s.status === FINISH_STATE && flush !== Z_FINISH) { + return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + s.strm = strm; + old_flush = s.last_flush; + s.last_flush = flush; + if (s.status === INIT_STATE) { + if (s.wrap === 2) { + strm.adler = 0; + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } else { + put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16)); + put_byte(s, s.gzhead.time & 255); + put_byte(s, s.gzhead.time >> 8 & 255); + put_byte(s, s.gzhead.time >> 16 & 255); + put_byte(s, s.gzhead.time >> 24 & 255); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, s.gzhead.os & 255); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 255); + put_byte(s, s.gzhead.extra.length >> 8 & 255); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } else { + var header = Z_DEFLATED + (s.w_bits - 8 << 4) << 8; + var level_flags = -1; + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= level_flags << 6; + if (s.strstart !== 0) { + header |= PRESET_DICT; + } + header += 31 - header % 31; + s.status = BUSY_STATE; + putShortMSB(s, header); + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + strm.adler = 1; + } + } + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra) { + beg = s.pending; + while (s.gzindex < (s.gzhead.extra.length & 65535)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 255); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val2 = 1; + break; + } + } + if (s.gzindex < s.gzhead.name.length) { + val2 = s.gzhead.name.charCodeAt(s.gzindex++) & 255; + } else { + val2 = 0; + } + put_byte(s, val2); + } while (val2 !== 0); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val2 === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val2 = 1; + break; + } + } + if (s.gzindex < s.gzhead.comment.length) { + val2 = s.gzhead.comment.charCodeAt(s.gzindex++) & 255; + } else { + val2 = 0; + } + put_byte(s, val2); + } while (val2 !== 0); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val2 === 0) { + s.status = HCRC_STATE; + } + } else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + strm.adler = 0; + s.status = BUSY_STATE; + } + } else { + s.status = BUSY_STATE; + } + } + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + if (strm.avail_in !== 0 || s.lookahead !== 0 || flush !== Z_NO_FLUSH && s.status !== FINISH_STATE) { + var bstate = s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush); + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + } + return Z_OK; + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } else if (flush !== Z_BLOCK) { + trees._tr_stored_block(s, 0, 0, false); + if (flush === Z_FULL_FLUSH) { + zero(s.head); + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } + } + if (flush !== Z_FINISH) { + return Z_OK; + } + if (s.wrap <= 0) { + return Z_STREAM_END; + } + if (s.wrap === 2) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + put_byte(s, strm.adler >> 16 & 255); + put_byte(s, strm.adler >> 24 & 255); + put_byte(s, strm.total_in & 255); + put_byte(s, strm.total_in >> 8 & 255); + put_byte(s, strm.total_in >> 16 & 255); + put_byte(s, strm.total_in >> 24 & 255); + } else { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + flush_pending(strm); + if (s.wrap > 0) { + s.wrap = -s.wrap; + } + return s.pending !== 0 ? Z_OK : Z_STREAM_END; + } + function deflateEnd(strm) { + var status; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + status = strm.state.status; + if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE) { + return err(strm, Z_STREAM_ERROR); + } + strm.state = null; + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; + } + function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + s = strm.state; + wrap = s.wrap; + if (wrap === 2 || wrap === 1 && s.status !== INIT_STATE || s.lookahead) { + return Z_STREAM_ERROR; + } + if (wrap === 1) { + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + s.wrap = 0; + if (dictLength >= s.w_size) { + if (wrap === 0) { + zero(s.head); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; + } + exports2.deflateInit = deflateInit; + exports2.deflateInit2 = deflateInit2; + exports2.deflateReset = deflateReset; + exports2.deflateResetKeep = deflateResetKeep; + exports2.deflateSetHeader = deflateSetHeader; + exports2.deflate = deflate; + exports2.deflateEnd = deflateEnd; + exports2.deflateSetDictionary = deflateSetDictionary; + exports2.deflateInfo = "pako deflate (from Nodeca project)"; +}); + +// node_modules/pako/lib/utils/strings.js +var require_strings = __commonJS((exports2) => { + var utils = require_common(); + var STR_APPLY_OK = true; + var STR_APPLY_UIA_OK = true; + try { + String.fromCharCode.apply(null, [0]); + } catch (__) { + STR_APPLY_OK = false; + } + try { + String.fromCharCode.apply(null, new Uint8Array(1)); + } catch (__) { + STR_APPLY_UIA_OK = false; + } + var _utf8len = new utils.Buf8(256); + for (q = 0;q < 256; q++) { + _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1; + } + var q; + _utf8len[254] = _utf8len[254] = 1; + exports2.string2buf = function(str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + for (m_pos = 0;m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4; + } + buf = new utils.Buf8(buf_len); + for (i = 0, m_pos = 0;i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + if (c < 128) { + buf[i++] = c; + } else if (c < 2048) { + buf[i++] = 192 | c >>> 6; + buf[i++] = 128 | c & 63; + } else if (c < 65536) { + buf[i++] = 224 | c >>> 12; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } else { + buf[i++] = 240 | c >>> 18; + buf[i++] = 128 | c >>> 12 & 63; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } + } + return buf; + }; + function buf2binstring(buf, len) { + if (len < 65534) { + if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + var result = ""; + for (var i = 0;i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; + } + exports2.buf2binstring = function(buf) { + return buf2binstring(buf, buf.length); + }; + exports2.binstring2buf = function(str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length;i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; + }; + exports2.buf2string = function(buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + var utf16buf = new Array(len * 2); + for (out = 0, i = 0;i < len; ) { + c = buf[i++]; + if (c < 128) { + utf16buf[out++] = c; + continue; + } + c_len = _utf8len[c]; + if (c_len > 4) { + utf16buf[out++] = 65533; + i += c_len - 1; + continue; + } + c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7; + while (c_len > 1 && i < len) { + c = c << 6 | buf[i++] & 63; + c_len--; + } + if (c_len > 1) { + utf16buf[out++] = 65533; + continue; + } + if (c < 65536) { + utf16buf[out++] = c; + } else { + c -= 65536; + utf16buf[out++] = 55296 | c >> 10 & 1023; + utf16buf[out++] = 56320 | c & 1023; + } + } + return buf2binstring(utf16buf, out); + }; + exports2.utf8border = function(buf, max) { + var pos; + max = max || buf.length; + if (max > buf.length) { + max = buf.length; + } + pos = max - 1; + while (pos >= 0 && (buf[pos] & 192) === 128) { + pos--; + } + if (pos < 0) { + return max; + } + if (pos === 0) { + return max; + } + return pos + _utf8len[buf[pos]] > max ? pos : max; + }; +}); + +// node_modules/pako/lib/zlib/zstream.js +var require_zstream = __commonJS((exports2, module2) => { + function ZStream() { + this.input = null; + this.next_in = 0; + this.avail_in = 0; + this.total_in = 0; + this.output = null; + this.next_out = 0; + this.avail_out = 0; + this.total_out = 0; + this.msg = ""; + this.state = null; + this.data_type = 2; + this.adler = 0; + } + module2.exports = ZStream; +}); + +// node_modules/pako/lib/deflate.js +var require_deflate2 = __commonJS((exports2) => { + var zlib_deflate = require_deflate(); + var utils = require_common(); + var strings = require_strings(); + var msg = require_messages(); + var ZStream = require_zstream(); + var toString2 = Object.prototype.toString; + var Z_NO_FLUSH = 0; + var Z_FINISH = 4; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_SYNC_FLUSH = 2; + var Z_DEFAULT_COMPRESSION = -1; + var Z_DEFAULT_STRATEGY = 0; + var Z_DEFLATED = 8; + function Deflate(options) { + if (!(this instanceof Deflate)) + return new Deflate(options); + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: "" + }, options || {}); + var opt = this.options; + if (opt.raw && opt.windowBits > 0) { + opt.windowBits = -opt.windowBits; + } else if (opt.gzip && opt.windowBits > 0 && opt.windowBits < 16) { + opt.windowBits += 16; + } + this.err = 0; + this.msg = ""; + this.ended = false; + this.chunks = []; + this.strm = new ZStream; + this.strm.avail_out = 0; + var status = zlib_deflate.deflateInit2(this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy); + if (status !== Z_OK) { + throw new Error(msg[status]); + } + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } + if (opt.dictionary) { + var dict; + if (typeof opt.dictionary === "string") { + dict = strings.string2buf(opt.dictionary); + } else if (toString2.call(opt.dictionary) === "[object ArrayBuffer]") { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + if (status !== Z_OK) { + throw new Error(msg[status]); + } + this._dict_set = true; + } + } + Deflate.prototype.push = function(data2, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + if (this.ended) { + return false; + } + _mode = mode === ~~mode ? mode : mode === true ? Z_FINISH : Z_NO_FLUSH; + if (typeof data2 === "string") { + strm.input = strings.string2buf(data2); + } else if (toString2.call(data2) === "[object ArrayBuffer]") { + strm.input = new Uint8Array(data2); + } else { + strm.input = data2; + } + strm.next_in = 0; + strm.avail_in = strm.input.length; + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH)) { + if (this.options.to === "string") { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + return true; + }; + Deflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); + }; + Deflate.prototype.onEnd = function(status) { + if (status === Z_OK) { + if (this.options.to === "string") { + this.result = this.chunks.join(""); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; + function deflate(input, options) { + var deflator = new Deflate(options); + deflator.push(input, true); + if (deflator.err) { + throw deflator.msg || msg[deflator.err]; + } + return deflator.result; + } + function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); + } + function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); + } + exports2.Deflate = Deflate; + exports2.deflate = deflate; + exports2.deflateRaw = deflateRaw; + exports2.gzip = gzip; +}); + +// node_modules/pako/lib/zlib/inffast.js +var require_inffast = __commonJS((exports2, module2) => { + var BAD = 30; + var TYPE = 12; + module2.exports = function inflate_fast(strm, start) { + var state; + var _in; + var last2; + var _out; + var beg; + var end; + var dmax; + var wsize; + var whave; + var wnext; + var s_window; + var hold; + var bits; + var lcode; + var dcode; + var lmask; + var dmask; + var here; + var op; + var len; + var dist; + var from; + var from_source; + var input, output; + state = strm.state; + _in = strm.next_in; + input = strm.input; + last2 = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); + dmax = state.dmax; + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + for (;; ) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op === 0) { + output[_out++] = here & 65535; + } else if (op & 16) { + len = here & 65535; + op &= 15; + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & (1 << op) - 1; + hold >>>= op; + bits -= op; + } + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + for (;; ) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op & 16) { + dist = here & 65535; + op &= 15; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & (1 << op) - 1; + if (dist > dmax) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break top; + } + hold >>>= op; + bits -= op; + op = _out - beg; + if (dist > op) { + op = dist - op; + if (op > whave) { + if (state.sane) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break top; + } + } + from = 0; + from_source = s_window; + if (wnext === 0) { + from += wsize - op; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } else if (wnext < op) { + from += wsize + wnext - op; + op -= wnext; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } + } else { + from += wnext - op; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } else { + from = _out - dist; + do { + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } else if ((op & 64) === 0) { + here = dcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dodist; + } else { + strm.msg = "invalid distance code"; + state.mode = BAD; + break top; + } + break; + } + } else if ((op & 64) === 0) { + here = lcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dolen; + } else if (op & 32) { + state.mode = TYPE; + break top; + } else { + strm.msg = "invalid literal/length code"; + state.mode = BAD; + break top; + } + break; + } + } while (_in < last2 && _out < end); + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = _in < last2 ? 5 + (last2 - _in) : 5 - (_in - last2); + strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); + state.hold = hold; + state.bits = bits; + return; + }; +}); + +// node_modules/pako/lib/zlib/inftrees.js +var require_inftrees = __commonJS((exports2, module2) => { + var utils = require_common(); + var MAXBITS = 15; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var lbase = [ + 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 + ]; + var lext = [ + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 17, + 17, + 17, + 17, + 18, + 18, + 18, + 18, + 19, + 19, + 19, + 19, + 20, + 20, + 20, + 20, + 21, + 21, + 21, + 21, + 16, + 72, + 78 + ]; + var dbase = [ + 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, + 0, + 0 + ]; + var dext = [ + 16, + 16, + 16, + 16, + 17, + 17, + 18, + 18, + 19, + 19, + 20, + 20, + 21, + 21, + 22, + 22, + 23, + 23, + 24, + 24, + 25, + 25, + 26, + 26, + 27, + 27, + 28, + 28, + 29, + 29, + 64, + 64 + ]; + module2.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { + var bits = opts.bits; + var len = 0; + var sym = 0; + var min = 0, max = 0; + var root = 0; + var curr = 0; + var drop2 = 0; + var left = 0; + var used = 0; + var huff = 0; + var incr; + var fill; + var low; + var mask2; + var next; + var base = null; + var base_index = 0; + var end; + var count = new utils.Buf16(MAXBITS + 1); + var offs = new utils.Buf16(MAXBITS + 1); + var extra = null; + var extra_index = 0; + var here_bits, here_op, here_val; + for (len = 0;len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0;sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + root = bits; + for (max = MAXBITS;max >= 1; max--) { + if (count[max] !== 0) { + break; + } + } + if (root > max) { + root = max; + } + if (max === 0) { + table[table_index++] = 1 << 24 | 64 << 16 | 0; + table[table_index++] = 1 << 24 | 64 << 16 | 0; + opts.bits = 1; + return 0; + } + for (min = 1;min < max; min++) { + if (count[min] !== 0) { + break; + } + } + if (root < min) { + root = min; + } + left = 1; + for (len = 1;len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; + } + offs[1] = 0; + for (len = 1;len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + for (sym = 0;sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + if (type === CODES) { + base = extra = work; + end = 19; + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + } else { + base = dbase; + extra = dext; + end = -1; + } + huff = 0; + sym = 0; + len = min; + next = table_index; + curr = root; + drop2 = 0; + low = -1; + used = 1 << root; + mask2 = used - 1; + if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) { + return 1; + } + for (;; ) { + here_bits = len - drop2; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } else { + here_op = 32 + 64; + here_val = 0; + } + incr = 1 << len - drop2; + fill = 1 << curr; + min = fill; + do { + fill -= incr; + table[next + (huff >> drop2) + fill] = here_bits << 24 | here_op << 16 | here_val | 0; + } while (fill !== 0); + incr = 1 << len - 1; + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + sym++; + if (--count[len] === 0) { + if (len === max) { + break; + } + len = lens[lens_index + work[sym]]; + } + if (len > root && (huff & mask2) !== low) { + if (drop2 === 0) { + drop2 = root; + } + next += min; + curr = len - drop2; + left = 1 << curr; + while (curr + drop2 < max) { + left -= count[curr + drop2]; + if (left <= 0) { + break; + } + curr++; + left <<= 1; + } + used += 1 << curr; + if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) { + return 1; + } + low = huff & mask2; + table[low] = root << 24 | curr << 16 | next - table_index | 0; + } + } + if (huff !== 0) { + table[next + huff] = len - drop2 << 24 | 64 << 16 | 0; + } + opts.bits = root; + return 0; + }; +}); + +// node_modules/pako/lib/zlib/inflate.js +var require_inflate = __commonJS((exports2) => { + var utils = require_common(); + var adler32 = require_adler32(); + var crc32 = require_crc322(); + var inflate_fast = require_inffast(); + var inflate_table = require_inftrees(); + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_TREES = 6; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_NEED_DICT = 2; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_MEM_ERROR = -4; + var Z_BUF_ERROR = -5; + var Z_DEFLATED = 8; + var HEAD = 1; + var FLAGS = 2; + var TIME = 3; + var OS = 4; + var EXLEN = 5; + var EXTRA = 6; + var NAME = 7; + var COMMENT = 8; + var HCRC = 9; + var DICTID = 10; + var DICT = 11; + var TYPE = 12; + var TYPEDO = 13; + var STORED = 14; + var COPY_ = 15; + var COPY = 16; + var TABLE = 17; + var LENLENS = 18; + var CODELENS = 19; + var LEN_ = 20; + var LEN = 21; + var LENEXT = 22; + var DIST = 23; + var DISTEXT = 24; + var MATCH = 25; + var LIT = 26; + var CHECK = 27; + var LENGTH = 28; + var DONE = 29; + var BAD = 30; + var MEM = 31; + var SYNC = 32; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var MAX_WBITS = 15; + var DEF_WBITS = MAX_WBITS; + function zswap32(q) { + return (q >>> 24 & 255) + (q >>> 8 & 65280) + ((q & 65280) << 8) + ((q & 255) << 24); + } + function InflateState() { + this.mode = 0; + this.last = false; + this.wrap = 0; + this.havedict = false; + this.flags = 0; + this.dmax = 0; + this.check = 0; + this.total = 0; + this.head = null; + this.wbits = 0; + this.wsize = 0; + this.whave = 0; + this.wnext = 0; + this.window = null; + this.hold = 0; + this.bits = 0; + this.length = 0; + this.offset = 0; + this.extra = 0; + this.lencode = null; + this.distcode = null; + this.lenbits = 0; + this.distbits = 0; + this.ncode = 0; + this.nlen = 0; + this.ndist = 0; + this.have = 0; + this.next = null; + this.lens = new utils.Buf16(320); + this.work = new utils.Buf16(288); + this.lendyn = null; + this.distdyn = null; + this.sane = 0; + this.back = 0; + this.was = 0; + } + function inflateResetKeep(strm) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ""; + if (state.wrap) { + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null; + state.hold = 0; + state.bits = 0; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + state.sane = 1; + state.back = -1; + return Z_OK; + } + function inflateReset(strm) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + } + function inflateReset2(strm, windowBits) { + var wrap; + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); + } + function inflateInit2(strm, windowBits) { + var ret; + var state; + if (!strm) { + return Z_STREAM_ERROR; + } + state = new InflateState; + strm.state = state; + state.window = null; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null; + } + return ret; + } + function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); + } + var virgin = true; + var lenfix; + var distfix; + function fixedtables(state) { + if (virgin) { + var sym; + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + sym = 0; + while (sym < 144) { + state.lens[sym++] = 8; + } + while (sym < 256) { + state.lens[sym++] = 9; + } + while (sym < 280) { + state.lens[sym++] = 7; + } + while (sym < 288) { + state.lens[sym++] = 8; + } + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + sym = 0; + while (sym < 32) { + state.lens[sym++] = 5; + } + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + virgin = false; + } + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; + } + function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + state.window = new utils.Buf8(state.wsize); + } + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } else { + state.wnext += dist; + if (state.wnext === state.wsize) { + state.wnext = 0; + } + if (state.whave < state.wsize) { + state.whave += dist; + } + } + } + return 0; + } + function inflate(strm, flush) { + var state; + var input, output; + var next; + var put; + var have, left; + var hold; + var bits; + var _in, _out; + var copy; + var from; + var from_source; + var here = 0; + var here_bits, here_op, here_val; + var last_bits, last_op, last_val; + var len; + var ret; + var hbuf = new utils.Buf8(4); + var opts; + var n; + var order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (state.mode === TYPE) { + state.mode = TYPEDO; + } + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + _in = have; + _out = left; + ret = Z_OK; + inf_leave: + for (;; ) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.wrap & 2 && hold === 35615) { + state.check = 0; + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + hold = 0; + bits = 0; + state.mode = FLAGS; + break; + } + state.flags = 0; + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || (((hold & 255) << 8) + (hold >> 8)) % 31) { + strm.msg = "incorrect header check"; + state.mode = BAD; + break; + } + if ((hold & 15) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state.mode = BAD; + break; + } + hold >>>= 4; + bits -= 4; + len = (hold & 15) + 8; + if (state.wbits === 0) { + state.wbits = len; + } else if (len > state.wbits) { + strm.msg = "invalid window size"; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + strm.adler = state.check = 1; + state.mode = hold & 512 ? DICTID : TYPE; + hold = 0; + bits = 0; + break; + case FLAGS: + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.flags = hold; + if ((state.flags & 255) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state.mode = BAD; + break; + } + if (state.flags & 57344) { + strm.msg = "unknown header flags set"; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = hold >> 8 & 1; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state.mode = TIME; + case TIME: + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.head) { + state.head.time = hold; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + hbuf[2] = hold >>> 16 & 255; + hbuf[3] = hold >>> 24 & 255; + state.check = crc32(state.check, hbuf, 4, 0); + } + hold = 0; + bits = 0; + state.mode = OS; + case OS: + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.head) { + state.head.xflags = hold & 255; + state.head.os = hold >> 8; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state.mode = EXLEN; + case EXLEN: + if (state.flags & 1024) { + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + } else if (state.head) { + state.head.extra = null; + } + state.mode = EXTRA; + case EXTRA: + if (state.flags & 1024) { + copy = state.length; + if (copy > have) { + copy = have; + } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet(state.head.extra, input, next, copy, len); + } + if (state.flags & 512) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { + break inf_leave; + } + } + state.length = 0; + state.mode = NAME; + case NAME: + if (state.flags & 2048) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + len = input[next + copy++]; + if (state.head && len && state.length < 65536) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 512) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + case COMMENT: + if (state.flags & 4096) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + len = input[next + copy++]; + if (state.head && len && state.length < 65536) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 512) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + case HCRC: + if (state.flags & 512) { + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state.check & 65535)) { + strm.msg = "header crc mismatch"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + if (state.head) { + state.head.hcrc = state.flags >> 9 & 1; + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + strm.adler = state.check = zswap32(hold); + hold = 0; + bits = 0; + state.mode = DICT; + case DICT: + if (state.havedict === 0) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + return Z_NEED_DICT; + } + strm.adler = state.check = 1; + state.mode = TYPE; + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { + break inf_leave; + } + case TYPEDO: + if (state.last) { + hold >>>= bits & 7; + bits -= bits & 7; + state.mode = CHECK; + break; + } + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.last = hold & 1; + hold >>>= 1; + bits -= 1; + switch (hold & 3) { + case 0: + state.mode = STORED; + break; + case 1: + fixedtables(state); + state.mode = LEN_; + if (flush === Z_TREES) { + hold >>>= 2; + bits -= 2; + break inf_leave; + } + break; + case 2: + state.mode = TABLE; + break; + case 3: + strm.msg = "invalid block type"; + state.mode = BAD; + } + hold >>>= 2; + bits -= 2; + break; + case STORED: + hold >>>= bits & 7; + bits -= bits & 7; + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((hold & 65535) !== (hold >>> 16 ^ 65535)) { + strm.msg = "invalid stored block lengths"; + state.mode = BAD; + break; + } + state.length = hold & 65535; + hold = 0; + bits = 0; + state.mode = COPY_; + if (flush === Z_TREES) { + break inf_leave; + } + case COPY_: + state.mode = COPY; + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { + copy = have; + } + if (copy > left) { + copy = left; + } + if (copy === 0) { + break inf_leave; + } + utils.arraySet(output, input, next, copy, put); + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + state.mode = TYPE; + break; + case TABLE: + while (bits < 14) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.nlen = (hold & 31) + 257; + hold >>>= 5; + bits -= 5; + state.ndist = (hold & 31) + 1; + hold >>>= 5; + bits -= 5; + state.ncode = (hold & 15) + 4; + hold >>>= 4; + bits -= 4; + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = "too many length or distance symbols"; + state.mode = BAD; + break; + } + state.have = 0; + state.mode = LENLENS; + case LENLENS: + while (state.have < state.ncode) { + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.lens[order[state.have++]] = hold & 7; + hold >>>= 3; + bits -= 3; + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + state.lencode = state.lendyn; + state.lenbits = 7; + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid code lengths set"; + state.mode = BAD; + break; + } + state.have = 0; + state.mode = CODELENS; + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;; ) { + here = state.lencode[hold & (1 << state.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_val < 16) { + hold >>>= here_bits; + bits -= here_bits; + state.lens[state.have++] = here_val; + } else { + if (here_val === 16) { + n = here_bits + 2; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + if (state.have === 0) { + strm.msg = "invalid bit length repeat"; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 3); + hold >>>= 2; + bits -= 2; + } else if (here_val === 17) { + n = here_bits + 3; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy = 3 + (hold & 7); + hold >>>= 3; + bits -= 3; + } else { + n = here_bits + 7; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy = 11 + (hold & 127); + hold >>>= 7; + bits -= 7; + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = "invalid bit length repeat"; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + if (state.mode === BAD) { + break; + } + if (state.lens[256] === 0) { + strm.msg = "invalid code -- missing end-of-block"; + state.mode = BAD; + break; + } + state.lenbits = 9; + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid literal/lengths set"; + state.mode = BAD; + break; + } + state.distbits = 6; + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + state.distbits = opts.bits; + if (ret) { + strm.msg = "invalid distances set"; + state.mode = BAD; + break; + } + state.mode = LEN_; + if (flush === Z_TREES) { + break inf_leave; + } + case LEN_: + state.mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + inflate_fast(strm, _out); + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;; ) { + here = state.lencode[hold & (1 << state.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_op && (here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;; ) { + here = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + state.mode = LIT; + break; + } + if (here_op & 32) { + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = "invalid literal/length code"; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + case LENEXT: + if (state.extra) { + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.length += hold & (1 << state.extra) - 1; + hold >>>= state.extra; + bits -= state.extra; + state.back += state.extra; + } + state.was = state.length; + state.mode = DIST; + case DIST: + for (;; ) { + here = state.distcode[hold & (1 << state.distbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;; ) { + here = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state.back += here_bits; + if (here_op & 64) { + strm.msg = "invalid distance code"; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = here_op & 15; + state.mode = DISTEXT; + case DISTEXT: + if (state.extra) { + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.offset += hold & (1 << state.extra) - 1; + hold >>>= state.extra; + bits -= state.extra; + state.back += state.extra; + } + if (state.offset > state.dmax) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break; + } + state.mode = MATCH; + case MATCH: + if (left === 0) { + break inf_leave; + } + copy = _out - left; + if (state.offset > copy) { + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break; + } + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } else { + from = state.wnext - copy; + } + if (copy > state.length) { + copy = state.length; + } + from_source = state.window; + } else { + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { + copy = left; + } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { + state.mode = LEN; + } + break; + case LIT: + if (left === 0) { + break inf_leave; + } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold |= input[next++] << bits; + bits += 8; + } + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out); + } + _out = left; + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = "incorrect data check"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state.mode = LENGTH; + case LENGTH: + if (state.wrap && state.flags) { + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state.total & 4294967295)) { + strm.msg = "incorrect length check"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state.mode = DONE; + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + } + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + if (state.wsize || _out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH)) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if ((_in === 0 && _out === 0 || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; + } + function inflateEnd(strm) { + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; + } + function inflateGetHeader(strm, head) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if ((state.wrap & 2) === 0) { + return Z_STREAM_ERROR; + } + state.head = head; + head.done = false; + return Z_OK; + } + function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var state; + var dictid; + var ret; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + if (state.mode === DICT) { + dictid = 1; + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + return Z_OK; + } + exports2.inflateReset = inflateReset; + exports2.inflateReset2 = inflateReset2; + exports2.inflateResetKeep = inflateResetKeep; + exports2.inflateInit = inflateInit; + exports2.inflateInit2 = inflateInit2; + exports2.inflate = inflate; + exports2.inflateEnd = inflateEnd; + exports2.inflateGetHeader = inflateGetHeader; + exports2.inflateSetDictionary = inflateSetDictionary; + exports2.inflateInfo = "pako inflate (from Nodeca project)"; +}); + +// node_modules/pako/lib/zlib/constants.js +var require_constants = __commonJS((exports2, module2) => { + module2.exports = { + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + Z_BUF_ERROR: -5, + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + Z_BINARY: 0, + Z_TEXT: 1, + Z_UNKNOWN: 2, + Z_DEFLATED: 8 + }; +}); + +// node_modules/pako/lib/zlib/gzheader.js +var require_gzheader = __commonJS((exports2, module2) => { + function GZheader() { + this.text = 0; + this.time = 0; + this.xflags = 0; + this.os = 0; + this.extra = null; + this.extra_len = 0; + this.name = ""; + this.comment = ""; + this.hcrc = 0; + this.done = false; + } + module2.exports = GZheader; +}); + +// node_modules/pako/lib/inflate.js +var require_inflate2 = __commonJS((exports2) => { + var zlib_inflate = require_inflate(); + var utils = require_common(); + var strings = require_strings(); + var c = require_constants(); + var msg = require_messages(); + var ZStream = require_zstream(); + var GZheader = require_gzheader(); + var toString2 = Object.prototype.toString; + function Inflate(options) { + if (!(this instanceof Inflate)) + return new Inflate(options); + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: "" + }, options || {}); + var opt = this.options; + if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { + opt.windowBits = -15; + } + } + if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) { + opt.windowBits += 32; + } + if (opt.windowBits > 15 && opt.windowBits < 48) { + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + this.err = 0; + this.msg = ""; + this.ended = false; + this.chunks = []; + this.strm = new ZStream; + this.strm.avail_out = 0; + var status = zlib_inflate.inflateInit2(this.strm, opt.windowBits); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + this.header = new GZheader; + zlib_inflate.inflateGetHeader(this.strm, this.header); + if (opt.dictionary) { + if (typeof opt.dictionary === "string") { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString2.call(opt.dictionary) === "[object ArrayBuffer]") { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { + status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + } + } + } + Inflate.prototype.push = function(data2, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + var allowBufError = false; + if (this.ended) { + return false; + } + _mode = mode === ~~mode ? mode : mode === true ? c.Z_FINISH : c.Z_NO_FLUSH; + if (typeof data2 === "string") { + strm.input = strings.binstring2buf(data2); + } else if (toString2.call(data2) === "[object ArrayBuffer]") { + strm.input = new Uint8Array(data2); + } else { + strm.input = data2; + } + strm.next_in = 0; + strm.avail_in = strm.input.length; + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); + if (status === c.Z_NEED_DICT && dictionary) { + status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); + } + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH)) { + if (this.options.to === "string") { + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { + utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); + } + this.onData(utf8str); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + return true; + }; + Inflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); + }; + Inflate.prototype.onEnd = function(status) { + if (status === c.Z_OK) { + if (this.options.to === "string") { + this.result = this.chunks.join(""); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; + function inflate(input, options) { + var inflator = new Inflate(options); + inflator.push(input, true); + if (inflator.err) { + throw inflator.msg || msg[inflator.err]; + } + return inflator.result; + } + function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); + } + exports2.Inflate = Inflate; + exports2.inflate = inflate; + exports2.inflateRaw = inflateRaw; + exports2.ungzip = inflate; +}); + +// node_modules/pako/index.js +var require_pako = __commonJS((exports2, module2) => { + var assign2 = require_common().assign; + var deflate = require_deflate2(); + var inflate = require_inflate2(); + var constants = require_constants(); + var pako = {}; + assign2(pako, deflate, inflate, constants); + module2.exports = pako; +}); + +// node_modules/jszip/lib/flate.js +var require_flate = __commonJS((exports2) => { + var USE_TYPEDARRAY = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Uint32Array !== "undefined"; + var pako = require_pako(); + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array"; + exports2.magic = "\b\x00"; + function FlateWorker(action, options) { + GenericWorker.call(this, "FlateWorker/" + action); + this._pako = null; + this._pakoAction = action; + this._pakoOptions = options; + this.meta = {}; + } + utils.inherits(FlateWorker, GenericWorker); + FlateWorker.prototype.processChunk = function(chunk) { + this.meta = chunk.meta; + if (this._pako === null) { + this._createPako(); + } + this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false); + }; + FlateWorker.prototype.flush = function() { + GenericWorker.prototype.flush.call(this); + if (this._pako === null) { + this._createPako(); + } + this._pako.push([], true); + }; + FlateWorker.prototype.cleanUp = function() { + GenericWorker.prototype.cleanUp.call(this); + this._pako = null; + }; + FlateWorker.prototype._createPako = function() { + this._pako = new pako[this._pakoAction]({ + raw: true, + level: this._pakoOptions.level || -1 + }); + var self2 = this; + this._pako.onData = function(data2) { + self2.push({ + data: data2, + meta: self2.meta + }); + }; + }; + exports2.compressWorker = function(compressionOptions) { + return new FlateWorker("Deflate", compressionOptions); + }; + exports2.uncompressWorker = function() { + return new FlateWorker("Inflate", {}); + }; +}); + +// node_modules/jszip/lib/compressions.js +var require_compressions = __commonJS((exports2) => { + var GenericWorker = require_GenericWorker(); + exports2.STORE = { + magic: "\x00\x00", + compressWorker: function() { + return new GenericWorker("STORE compression"); + }, + uncompressWorker: function() { + return new GenericWorker("STORE decompression"); + } + }; + exports2.DEFLATE = require_flate(); +}); + +// node_modules/jszip/lib/signature.js +var require_signature = __commonJS((exports2) => { + exports2.LOCAL_FILE_HEADER = "PK\x03\x04"; + exports2.CENTRAL_FILE_HEADER = "PK\x01\x02"; + exports2.CENTRAL_DIRECTORY_END = "PK\x05\x06"; + exports2.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07"; + exports2.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06"; + exports2.DATA_DESCRIPTOR = "PK\x07\b"; +}); + +// node_modules/jszip/lib/generate/ZipFileWorker.js +var require_ZipFileWorker = __commonJS((exports2, module2) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var utf8 = require_utf8(); + var crc32 = require_crc32(); + var signature = require_signature(); + var decToHex = function(dec, bytes) { + var hex = "", i; + for (i = 0;i < bytes; i++) { + hex += String.fromCharCode(dec & 255); + dec = dec >>> 8; + } + return hex; + }; + var generateUnixExternalFileAttr = function(unixPermissions, isDir) { + var result = unixPermissions; + if (!unixPermissions) { + result = isDir ? 16893 : 33204; + } + return (result & 65535) << 16; + }; + var generateDosExternalFileAttr = function(dosPermissions) { + return (dosPermissions || 0) & 63; + }; + var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) { + var file = streamInfo["file"], compression = streamInfo["compression"], useCustomEncoding = encodeFileName !== utf8.utf8encode, encodedFileName = utils.transformTo("string", encodeFileName(file.name)), utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), comment = file.comment, encodedComment = utils.transformTo("string", encodeFileName(comment)), utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, useUTF8ForComment = utfEncodedComment.length !== comment.length, dosTime, dosDate, extraFields = "", unicodePathExtraField = "", unicodeCommentExtraField = "", dir = file.dir, date = file.date; + var dataInfo = { + crc32: 0, + compressedSize: 0, + uncompressedSize: 0 + }; + if (!streamedContent || streamingEnded) { + dataInfo.crc32 = streamInfo["crc32"]; + dataInfo.compressedSize = streamInfo["compressedSize"]; + dataInfo.uncompressedSize = streamInfo["uncompressedSize"]; + } + var bitflag = 0; + if (streamedContent) { + bitflag |= 8; + } + if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) { + bitflag |= 2048; + } + var extFileAttr = 0; + var versionMadeBy = 0; + if (dir) { + extFileAttr |= 16; + } + if (platform === "UNIX") { + versionMadeBy = 798; + extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir); + } else { + versionMadeBy = 20; + extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir); + } + dosTime = date.getUTCHours(); + dosTime = dosTime << 6; + dosTime = dosTime | date.getUTCMinutes(); + dosTime = dosTime << 5; + dosTime = dosTime | date.getUTCSeconds() / 2; + dosDate = date.getUTCFullYear() - 1980; + dosDate = dosDate << 4; + dosDate = dosDate | date.getUTCMonth() + 1; + dosDate = dosDate << 5; + dosDate = dosDate | date.getUTCDate(); + if (useUTF8ForFileName) { + unicodePathExtraField = decToHex(1, 1) + decToHex(crc32(encodedFileName), 4) + utfEncodedFileName; + extraFields += "up" + decToHex(unicodePathExtraField.length, 2) + unicodePathExtraField; + } + if (useUTF8ForComment) { + unicodeCommentExtraField = decToHex(1, 1) + decToHex(crc32(encodedComment), 4) + utfEncodedComment; + extraFields += "uc" + decToHex(unicodeCommentExtraField.length, 2) + unicodeCommentExtraField; + } + var header = ""; + header += ` +\x00`; + header += decToHex(bitflag, 2); + header += compression.magic; + header += decToHex(dosTime, 2); + header += decToHex(dosDate, 2); + header += decToHex(dataInfo.crc32, 4); + header += decToHex(dataInfo.compressedSize, 4); + header += decToHex(dataInfo.uncompressedSize, 4); + header += decToHex(encodedFileName.length, 2); + header += decToHex(extraFields.length, 2); + var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields; + var dirRecord = signature.CENTRAL_FILE_HEADER + decToHex(versionMadeBy, 2) + header + decToHex(encodedComment.length, 2) + "\x00\x00" + "\x00\x00" + decToHex(extFileAttr, 4) + decToHex(offset, 4) + encodedFileName + extraFields + encodedComment; + return { + fileRecord, + dirRecord + }; + }; + var generateCentralDirectoryEnd = function(entriesCount, centralDirLength, localDirLength, comment, encodeFileName) { + var dirEnd = ""; + var encodedComment = utils.transformTo("string", encodeFileName(comment)); + dirEnd = signature.CENTRAL_DIRECTORY_END + "\x00\x00" + "\x00\x00" + decToHex(entriesCount, 2) + decToHex(entriesCount, 2) + decToHex(centralDirLength, 4) + decToHex(localDirLength, 4) + decToHex(encodedComment.length, 2) + encodedComment; + return dirEnd; + }; + var generateDataDescriptors = function(streamInfo) { + var descriptor = ""; + descriptor = signature.DATA_DESCRIPTOR + decToHex(streamInfo["crc32"], 4) + decToHex(streamInfo["compressedSize"], 4) + decToHex(streamInfo["uncompressedSize"], 4); + return descriptor; + }; + function ZipFileWorker(streamFiles, comment, platform, encodeFileName) { + GenericWorker.call(this, "ZipFileWorker"); + this.bytesWritten = 0; + this.zipComment = comment; + this.zipPlatform = platform; + this.encodeFileName = encodeFileName; + this.streamFiles = streamFiles; + this.accumulate = false; + this.contentBuffer = []; + this.dirRecords = []; + this.currentSourceOffset = 0; + this.entriesCount = 0; + this.currentFile = null; + this._sources = []; + } + utils.inherits(ZipFileWorker, GenericWorker); + ZipFileWorker.prototype.push = function(chunk) { + var currentFilePercent = chunk.meta.percent || 0; + var entriesCount = this.entriesCount; + var remainingFiles = this._sources.length; + if (this.accumulate) { + this.contentBuffer.push(chunk); + } else { + this.bytesWritten += chunk.data.length; + GenericWorker.prototype.push.call(this, { + data: chunk.data, + meta: { + currentFile: this.currentFile, + percent: entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100 + } + }); + } + }; + ZipFileWorker.prototype.openedSource = function(streamInfo) { + this.currentSourceOffset = this.bytesWritten; + this.currentFile = streamInfo["file"].name; + var streamedContent = this.streamFiles && !streamInfo["file"].dir; + if (streamedContent) { + var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.push({ + data: record.fileRecord, + meta: { percent: 0 } + }); + } else { + this.accumulate = true; + } + }; + ZipFileWorker.prototype.closedSource = function(streamInfo) { + this.accumulate = false; + var streamedContent = this.streamFiles && !streamInfo["file"].dir; + var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.dirRecords.push(record.dirRecord); + if (streamedContent) { + this.push({ + data: generateDataDescriptors(streamInfo), + meta: { percent: 100 } + }); + } else { + this.push({ + data: record.fileRecord, + meta: { percent: 0 } + }); + while (this.contentBuffer.length) { + this.push(this.contentBuffer.shift()); + } + } + this.currentFile = null; + }; + ZipFileWorker.prototype.flush = function() { + var localDirLength = this.bytesWritten; + for (var i = 0;i < this.dirRecords.length; i++) { + this.push({ + data: this.dirRecords[i], + meta: { percent: 100 } + }); + } + var centralDirLength = this.bytesWritten - localDirLength; + var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName); + this.push({ + data: dirEnd, + meta: { percent: 100 } + }); + }; + ZipFileWorker.prototype.prepareNextSource = function() { + this.previous = this._sources.shift(); + this.openedSource(this.previous.streamInfo); + if (this.isPaused) { + this.previous.pause(); + } else { + this.previous.resume(); + } + }; + ZipFileWorker.prototype.registerPrevious = function(previous) { + this._sources.push(previous); + var self2 = this; + previous.on("data", function(chunk) { + self2.processChunk(chunk); + }); + previous.on("end", function() { + self2.closedSource(self2.previous.streamInfo); + if (self2._sources.length) { + self2.prepareNextSource(); + } else { + self2.end(); + } + }); + previous.on("error", function(e) { + self2.error(e); + }); + return this; + }; + ZipFileWorker.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) { + return false; + } + if (!this.previous && this._sources.length) { + this.prepareNextSource(); + return true; + } + if (!this.previous && !this._sources.length && !this.generatedError) { + this.end(); + return true; + } + }; + ZipFileWorker.prototype.error = function(e) { + var sources = this._sources; + if (!GenericWorker.prototype.error.call(this, e)) { + return false; + } + for (var i = 0;i < sources.length; i++) { + try { + sources[i].error(e); + } catch (e2) { + } + } + return true; + }; + ZipFileWorker.prototype.lock = function() { + GenericWorker.prototype.lock.call(this); + var sources = this._sources; + for (var i = 0;i < sources.length; i++) { + sources[i].lock(); + } + }; + module2.exports = ZipFileWorker; +}); + +// node_modules/jszip/lib/generate/index.js +var require_generate = __commonJS((exports2) => { + var compressions = require_compressions(); + var ZipFileWorker = require_ZipFileWorker(); + var getCompression = function(fileCompression, zipCompression) { + var compressionName = fileCompression || zipCompression; + var compression = compressions[compressionName]; + if (!compression) { + throw new Error(compressionName + " is not a valid compression method !"); + } + return compression; + }; + exports2.generateWorker = function(zip, options, comment) { + var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName); + var entriesCount = 0; + try { + zip.forEach(function(relativePath, file) { + entriesCount++; + var compression = getCompression(file.options.compression, options.compression); + var compressionOptions = file.options.compressionOptions || options.compressionOptions || {}; + var { dir, date } = file; + file._compressWorker(compression, compressionOptions).withStreamInfo("file", { + name: relativePath, + dir, + date, + comment: file.comment || "", + unixPermissions: file.unixPermissions, + dosPermissions: file.dosPermissions + }).pipe(zipFileWorker); + }); + zipFileWorker.entriesCount = entriesCount; + } catch (e) { + zipFileWorker.error(e); + } + return zipFileWorker; + }; +}); + +// node_modules/jszip/lib/nodejs/NodejsStreamInputAdapter.js +var require_NodejsStreamInputAdapter = __commonJS((exports2, module2) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + function NodejsStreamInputAdapter(filename, stream) { + GenericWorker.call(this, "Nodejs stream input adapter for " + filename); + this._upstreamEnded = false; + this._bindStream(stream); + } + utils.inherits(NodejsStreamInputAdapter, GenericWorker); + NodejsStreamInputAdapter.prototype._bindStream = function(stream) { + var self2 = this; + this._stream = stream; + stream.pause(); + stream.on("data", function(chunk) { + self2.push({ + data: chunk, + meta: { + percent: 0 + } + }); + }).on("error", function(e) { + if (self2.isPaused) { + this.generatedError = e; + } else { + self2.error(e); + } + }).on("end", function() { + if (self2.isPaused) { + self2._upstreamEnded = true; + } else { + self2.end(); + } + }); + }; + NodejsStreamInputAdapter.prototype.pause = function() { + if (!GenericWorker.prototype.pause.call(this)) { + return false; + } + this._stream.pause(); + return true; + }; + NodejsStreamInputAdapter.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) { + return false; + } + if (this._upstreamEnded) { + this.end(); + } else { + this._stream.resume(); + } + return true; + }; + module2.exports = NodejsStreamInputAdapter; +}); + +// node_modules/jszip/lib/object.js +var require_object = __commonJS((exports2, module2) => { + var utf8 = require_utf8(); + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var StreamHelper = require_StreamHelper(); + var defaults2 = require_defaults(); + var CompressedObject = require_compressedObject(); + var ZipObject = require_zipObject(); + var generate = require_generate(); + var nodejsUtils = require_nodejsUtils(); + var NodejsStreamInputAdapter = require_NodejsStreamInputAdapter(); + var fileAdd = function(name2, data2, originalOptions) { + var dataType = utils.getTypeOf(data2), parent2; + var o = utils.extend(originalOptions || {}, defaults2); + o.date = o.date || new Date; + if (o.compression !== null) { + o.compression = o.compression.toUpperCase(); + } + if (typeof o.unixPermissions === "string") { + o.unixPermissions = parseInt(o.unixPermissions, 8); + } + if (o.unixPermissions && o.unixPermissions & 16384) { + o.dir = true; + } + if (o.dosPermissions && o.dosPermissions & 16) { + o.dir = true; + } + if (o.dir) { + name2 = forceTrailingSlash(name2); + } + if (o.createFolders && (parent2 = parentFolder(name2))) { + folderAdd.call(this, parent2, true); + } + var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false; + if (!originalOptions || typeof originalOptions.binary === "undefined") { + o.binary = !isUnicodeString; + } + var isCompressedEmpty = data2 instanceof CompressedObject && data2.uncompressedSize === 0; + if (isCompressedEmpty || o.dir || !data2 || data2.length === 0) { + o.base64 = false; + o.binary = true; + data2 = ""; + o.compression = "STORE"; + dataType = "string"; + } + var zipObjectContent = null; + if (data2 instanceof CompressedObject || data2 instanceof GenericWorker) { + zipObjectContent = data2; + } else if (nodejsUtils.isNode && nodejsUtils.isStream(data2)) { + zipObjectContent = new NodejsStreamInputAdapter(name2, data2); + } else { + zipObjectContent = utils.prepareContent(name2, data2, o.binary, o.optimizedBinaryString, o.base64); + } + var object = new ZipObject(name2, zipObjectContent, o); + this.files[name2] = object; + }; + var parentFolder = function(path) { + if (path.slice(-1) === "/") { + path = path.substring(0, path.length - 1); + } + var lastSlash = path.lastIndexOf("/"); + return lastSlash > 0 ? path.substring(0, lastSlash) : ""; + }; + var forceTrailingSlash = function(path) { + if (path.slice(-1) !== "/") { + path += "/"; + } + return path; + }; + var folderAdd = function(name2, createFolders) { + createFolders = typeof createFolders !== "undefined" ? createFolders : defaults2.createFolders; + name2 = forceTrailingSlash(name2); + if (!this.files[name2]) { + fileAdd.call(this, name2, null, { + dir: true, + createFolders + }); + } + return this.files[name2]; + }; + function isRegExp2(object) { + return Object.prototype.toString.call(object) === "[object RegExp]"; + } + var out = { + load: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, + forEach: function(cb) { + var filename, relativePath, file; + for (filename in this.files) { + file = this.files[filename]; + relativePath = filename.slice(this.root.length, filename.length); + if (relativePath && filename.slice(0, this.root.length) === this.root) { + cb(relativePath, file); + } + } + }, + filter: function(search) { + var result = []; + this.forEach(function(relativePath, entry) { + if (search(relativePath, entry)) { + result.push(entry); + } + }); + return result; + }, + file: function(name2, data2, o) { + if (arguments.length === 1) { + if (isRegExp2(name2)) { + var regexp = name2; + return this.filter(function(relativePath, file) { + return !file.dir && regexp.test(relativePath); + }); + } else { + var obj = this.files[this.root + name2]; + if (obj && !obj.dir) { + return obj; + } else { + return null; + } + } + } else { + name2 = this.root + name2; + fileAdd.call(this, name2, data2, o); + } + return this; + }, + folder: function(arg) { + if (!arg) { + return this; + } + if (isRegExp2(arg)) { + return this.filter(function(relativePath, file) { + return file.dir && arg.test(relativePath); + }); + } + var name2 = this.root + arg; + var newFolder = folderAdd.call(this, name2); + var ret = this.clone(); + ret.root = newFolder.name; + return ret; + }, + remove: function(name2) { + name2 = this.root + name2; + var file = this.files[name2]; + if (!file) { + if (name2.slice(-1) !== "/") { + name2 += "/"; + } + file = this.files[name2]; + } + if (file && !file.dir) { + delete this.files[name2]; + } else { + var kids = this.filter(function(relativePath, file2) { + return file2.name.slice(0, name2.length) === name2; + }); + for (var i = 0;i < kids.length; i++) { + delete this.files[kids[i].name]; + } + } + return this; + }, + generate: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, + generateInternalStream: function(options) { + var worker, opts = {}; + try { + opts = utils.extend(options || {}, { + streamFiles: false, + compression: "STORE", + compressionOptions: null, + type: "", + platform: "DOS", + comment: null, + mimeType: "application/zip", + encodeFileName: utf8.utf8encode + }); + opts.type = opts.type.toLowerCase(); + opts.compression = opts.compression.toUpperCase(); + if (opts.type === "binarystring") { + opts.type = "string"; + } + if (!opts.type) { + throw new Error("No output type specified."); + } + utils.checkSupport(opts.type); + if (opts.platform === "darwin" || opts.platform === "freebsd" || opts.platform === "linux" || opts.platform === "sunos") { + opts.platform = "UNIX"; + } + if (opts.platform === "win32") { + opts.platform = "DOS"; + } + var comment = opts.comment || this.comment || ""; + worker = generate.generateWorker(this, opts, comment); + } catch (e) { + worker = new GenericWorker("error"); + worker.error(e); + } + return new StreamHelper(worker, opts.type || "string", opts.mimeType); + }, + generateAsync: function(options, onUpdate) { + return this.generateInternalStream(options).accumulate(onUpdate); + }, + generateNodeStream: function(options, onUpdate) { + options = options || {}; + if (!options.type) { + options.type = "nodebuffer"; + } + return this.generateInternalStream(options).toNodejsStream(onUpdate); + } + }; + module2.exports = out; +}); + +// node_modules/jszip/lib/reader/DataReader.js +var require_DataReader = __commonJS((exports2, module2) => { + var utils = require_utils(); + function DataReader(data2) { + this.data = data2; + this.length = data2.length; + this.index = 0; + this.zero = 0; + } + DataReader.prototype = { + checkOffset: function(offset) { + this.checkIndex(this.index + offset); + }, + checkIndex: function(newIndex) { + if (this.length < this.zero + newIndex || newIndex < 0) { + throw new Error("End of data reached (data length = " + this.length + ", asked index = " + newIndex + "). Corrupted zip ?"); + } + }, + setIndex: function(newIndex) { + this.checkIndex(newIndex); + this.index = newIndex; + }, + skip: function(n) { + this.setIndex(this.index + n); + }, + byteAt: function() { + }, + readInt: function(size) { + var result = 0, i; + this.checkOffset(size); + for (i = this.index + size - 1;i >= this.index; i--) { + result = (result << 8) + this.byteAt(i); + } + this.index += size; + return result; + }, + readString: function(size) { + return utils.transformTo("string", this.readData(size)); + }, + readData: function() { + }, + lastIndexOfSignature: function() { + }, + readAndCheckSignature: function() { + }, + readDate: function() { + var dostime = this.readInt(4); + return new Date(Date.UTC((dostime >> 25 & 127) + 1980, (dostime >> 21 & 15) - 1, dostime >> 16 & 31, dostime >> 11 & 31, dostime >> 5 & 63, (dostime & 31) << 1)); + } + }; + module2.exports = DataReader; +}); + +// node_modules/jszip/lib/reader/ArrayReader.js +var require_ArrayReader = __commonJS((exports2, module2) => { + var DataReader = require_DataReader(); + var utils = require_utils(); + function ArrayReader(data2) { + DataReader.call(this, data2); + for (var i = 0;i < this.data.length; i++) { + data2[i] = data2[i] & 255; + } + } + utils.inherits(ArrayReader, DataReader); + ArrayReader.prototype.byteAt = function(i) { + return this.data[this.zero + i]; + }; + ArrayReader.prototype.lastIndexOfSignature = function(sig) { + var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3); + for (var i = this.length - 4;i >= 0; --i) { + if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) { + return i - this.zero; + } + } + return -1; + }; + ArrayReader.prototype.readAndCheckSignature = function(sig) { + var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3), data2 = this.readData(4); + return sig0 === data2[0] && sig1 === data2[1] && sig2 === data2[2] && sig3 === data2[3]; + }; + ArrayReader.prototype.readData = function(size) { + this.checkOffset(size); + if (size === 0) { + return []; + } + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module2.exports = ArrayReader; +}); + +// node_modules/jszip/lib/reader/StringReader.js +var require_StringReader = __commonJS((exports2, module2) => { + var DataReader = require_DataReader(); + var utils = require_utils(); + function StringReader(data2) { + DataReader.call(this, data2); + } + utils.inherits(StringReader, DataReader); + StringReader.prototype.byteAt = function(i) { + return this.data.charCodeAt(this.zero + i); + }; + StringReader.prototype.lastIndexOfSignature = function(sig) { + return this.data.lastIndexOf(sig) - this.zero; + }; + StringReader.prototype.readAndCheckSignature = function(sig) { + var data2 = this.readData(4); + return sig === data2; + }; + StringReader.prototype.readData = function(size) { + this.checkOffset(size); + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module2.exports = StringReader; +}); + +// node_modules/jszip/lib/reader/Uint8ArrayReader.js +var require_Uint8ArrayReader = __commonJS((exports2, module2) => { + var ArrayReader = require_ArrayReader(); + var utils = require_utils(); + function Uint8ArrayReader(data2) { + ArrayReader.call(this, data2); + } + utils.inherits(Uint8ArrayReader, ArrayReader); + Uint8ArrayReader.prototype.readData = function(size) { + this.checkOffset(size); + if (size === 0) { + return new Uint8Array(0); + } + var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module2.exports = Uint8ArrayReader; +}); + +// node_modules/jszip/lib/reader/NodeBufferReader.js +var require_NodeBufferReader = __commonJS((exports2, module2) => { + var Uint8ArrayReader = require_Uint8ArrayReader(); + var utils = require_utils(); + function NodeBufferReader(data2) { + Uint8ArrayReader.call(this, data2); + } + utils.inherits(NodeBufferReader, Uint8ArrayReader); + NodeBufferReader.prototype.readData = function(size) { + this.checkOffset(size); + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module2.exports = NodeBufferReader; +}); + +// node_modules/jszip/lib/reader/readerFor.js +var require_readerFor = __commonJS((exports2, module2) => { + var utils = require_utils(); + var support = require_support(); + var ArrayReader = require_ArrayReader(); + var StringReader = require_StringReader(); + var NodeBufferReader = require_NodeBufferReader(); + var Uint8ArrayReader = require_Uint8ArrayReader(); + module2.exports = function(data2) { + var type = utils.getTypeOf(data2); + utils.checkSupport(type); + if (type === "string" && !support.uint8array) { + return new StringReader(data2); + } + if (type === "nodebuffer") { + return new NodeBufferReader(data2); + } + if (support.uint8array) { + return new Uint8ArrayReader(utils.transformTo("uint8array", data2)); + } + return new ArrayReader(utils.transformTo("array", data2)); + }; +}); + +// node_modules/jszip/lib/zipEntry.js +var require_zipEntry = __commonJS((exports2, module2) => { + var readerFor = require_readerFor(); + var utils = require_utils(); + var CompressedObject = require_compressedObject(); + var crc32fn = require_crc32(); + var utf8 = require_utf8(); + var compressions = require_compressions(); + var support = require_support(); + var MADE_BY_DOS = 0; + var MADE_BY_UNIX = 3; + var findCompression = function(compressionMethod) { + for (var method in compressions) { + if (!Object.prototype.hasOwnProperty.call(compressions, method)) { + continue; + } + if (compressions[method].magic === compressionMethod) { + return compressions[method]; + } + } + return null; + }; + function ZipEntry(options, loadOptions) { + this.options = options; + this.loadOptions = loadOptions; + } + ZipEntry.prototype = { + isEncrypted: function() { + return (this.bitFlag & 1) === 1; + }, + useUTF8: function() { + return (this.bitFlag & 2048) === 2048; + }, + readLocalPart: function(reader) { + var compression, localExtraFieldsLength; + reader.skip(22); + this.fileNameLength = reader.readInt(2); + localExtraFieldsLength = reader.readInt(2); + this.fileName = reader.readData(this.fileNameLength); + reader.skip(localExtraFieldsLength); + if (this.compressedSize === -1 || this.uncompressedSize === -1) { + throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)"); + } + compression = findCompression(this.compressionMethod); + if (compression === null) { + throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")"); + } + this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize)); + }, + readCentralPart: function(reader) { + this.versionMadeBy = reader.readInt(2); + reader.skip(2); + this.bitFlag = reader.readInt(2); + this.compressionMethod = reader.readString(2); + this.date = reader.readDate(); + this.crc32 = reader.readInt(4); + this.compressedSize = reader.readInt(4); + this.uncompressedSize = reader.readInt(4); + var fileNameLength = reader.readInt(2); + this.extraFieldsLength = reader.readInt(2); + this.fileCommentLength = reader.readInt(2); + this.diskNumberStart = reader.readInt(2); + this.internalFileAttributes = reader.readInt(2); + this.externalFileAttributes = reader.readInt(4); + this.localHeaderOffset = reader.readInt(4); + if (this.isEncrypted()) { + throw new Error("Encrypted zip are not supported"); + } + reader.skip(fileNameLength); + this.readExtraFields(reader); + this.parseZIP64ExtraField(reader); + this.fileComment = reader.readData(this.fileCommentLength); + }, + processAttributes: function() { + this.unixPermissions = null; + this.dosPermissions = null; + var madeBy = this.versionMadeBy >> 8; + this.dir = this.externalFileAttributes & 16 ? true : false; + if (madeBy === MADE_BY_DOS) { + this.dosPermissions = this.externalFileAttributes & 63; + } + if (madeBy === MADE_BY_UNIX) { + this.unixPermissions = this.externalFileAttributes >> 16 & 65535; + } + if (!this.dir && this.fileNameStr.slice(-1) === "/") { + this.dir = true; + } + }, + parseZIP64ExtraField: function() { + if (!this.extraFields[1]) { + return; + } + var extraReader = readerFor(this.extraFields[1].value); + if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { + this.uncompressedSize = extraReader.readInt(8); + } + if (this.compressedSize === utils.MAX_VALUE_32BITS) { + this.compressedSize = extraReader.readInt(8); + } + if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { + this.localHeaderOffset = extraReader.readInt(8); + } + if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { + this.diskNumberStart = extraReader.readInt(4); + } + }, + readExtraFields: function(reader) { + var end = reader.index + this.extraFieldsLength, extraFieldId, extraFieldLength, extraFieldValue; + if (!this.extraFields) { + this.extraFields = {}; + } + while (reader.index + 4 < end) { + extraFieldId = reader.readInt(2); + extraFieldLength = reader.readInt(2); + extraFieldValue = reader.readData(extraFieldLength); + this.extraFields[extraFieldId] = { + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue + }; + } + reader.setIndex(end); + }, + handleUTF8: function() { + var decodeParamType = support.uint8array ? "uint8array" : "array"; + if (this.useUTF8()) { + this.fileNameStr = utf8.utf8decode(this.fileName); + this.fileCommentStr = utf8.utf8decode(this.fileComment); + } else { + var upath = this.findExtraFieldUnicodePath(); + if (upath !== null) { + this.fileNameStr = upath; + } else { + var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName); + this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray); + } + var ucomment = this.findExtraFieldUnicodeComment(); + if (ucomment !== null) { + this.fileCommentStr = ucomment; + } else { + var commentByteArray = utils.transformTo(decodeParamType, this.fileComment); + this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray); + } + } + }, + findExtraFieldUnicodePath: function() { + var upathField = this.extraFields[28789]; + if (upathField) { + var extraReader = readerFor(upathField.value); + if (extraReader.readInt(1) !== 1) { + return null; + } + if (crc32fn(this.fileName) !== extraReader.readInt(4)) { + return null; + } + return utf8.utf8decode(extraReader.readData(upathField.length - 5)); + } + return null; + }, + findExtraFieldUnicodeComment: function() { + var ucommentField = this.extraFields[25461]; + if (ucommentField) { + var extraReader = readerFor(ucommentField.value); + if (extraReader.readInt(1) !== 1) { + return null; + } + if (crc32fn(this.fileComment) !== extraReader.readInt(4)) { + return null; + } + return utf8.utf8decode(extraReader.readData(ucommentField.length - 5)); + } + return null; + } + }; + module2.exports = ZipEntry; +}); + +// node_modules/jszip/lib/zipEntries.js +var require_zipEntries = __commonJS((exports2, module2) => { + var readerFor = require_readerFor(); + var utils = require_utils(); + var sig = require_signature(); + var ZipEntry = require_zipEntry(); + var support = require_support(); + function ZipEntries(loadOptions) { + this.files = []; + this.loadOptions = loadOptions; + } + ZipEntries.prototype = { + checkSignature: function(expectedSignature) { + if (!this.reader.readAndCheckSignature(expectedSignature)) { + this.reader.index -= 4; + var signature = this.reader.readString(4); + throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); + } + }, + isSignature: function(askedIndex, expectedSignature) { + var currentIndex = this.reader.index; + this.reader.setIndex(askedIndex); + var signature = this.reader.readString(4); + var result = signature === expectedSignature; + this.reader.setIndex(currentIndex); + return result; + }, + readBlockEndOfCentral: function() { + this.diskNumber = this.reader.readInt(2); + this.diskWithCentralDirStart = this.reader.readInt(2); + this.centralDirRecordsOnThisDisk = this.reader.readInt(2); + this.centralDirRecords = this.reader.readInt(2); + this.centralDirSize = this.reader.readInt(4); + this.centralDirOffset = this.reader.readInt(4); + this.zipCommentLength = this.reader.readInt(2); + var zipComment = this.reader.readData(this.zipCommentLength); + var decodeParamType = support.uint8array ? "uint8array" : "array"; + var decodeContent = utils.transformTo(decodeParamType, zipComment); + this.zipComment = this.loadOptions.decodeFileName(decodeContent); + }, + readBlockZip64EndOfCentral: function() { + this.zip64EndOfCentralSize = this.reader.readInt(8); + this.reader.skip(4); + this.diskNumber = this.reader.readInt(4); + this.diskWithCentralDirStart = this.reader.readInt(4); + this.centralDirRecordsOnThisDisk = this.reader.readInt(8); + this.centralDirRecords = this.reader.readInt(8); + this.centralDirSize = this.reader.readInt(8); + this.centralDirOffset = this.reader.readInt(8); + this.zip64ExtensibleData = {}; + var extraDataSize = this.zip64EndOfCentralSize - 44, index2 = 0, extraFieldId, extraFieldLength, extraFieldValue; + while (index2 < extraDataSize) { + extraFieldId = this.reader.readInt(2); + extraFieldLength = this.reader.readInt(4); + extraFieldValue = this.reader.readData(extraFieldLength); + this.zip64ExtensibleData[extraFieldId] = { + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue + }; + } + }, + readBlockZip64EndOfCentralLocator: function() { + this.diskWithZip64CentralDirStart = this.reader.readInt(4); + this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); + this.disksCount = this.reader.readInt(4); + if (this.disksCount > 1) { + throw new Error("Multi-volumes zip are not supported"); + } + }, + readLocalFiles: function() { + var i, file; + for (i = 0;i < this.files.length; i++) { + file = this.files[i]; + this.reader.setIndex(file.localHeaderOffset); + this.checkSignature(sig.LOCAL_FILE_HEADER); + file.readLocalPart(this.reader); + file.handleUTF8(); + file.processAttributes(); + } + }, + readCentralDir: function() { + var file; + this.reader.setIndex(this.centralDirOffset); + while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) { + file = new ZipEntry({ + zip64: this.zip64 + }, this.loadOptions); + file.readCentralPart(this.reader); + this.files.push(file); + } + if (this.centralDirRecords !== this.files.length) { + if (this.centralDirRecords !== 0 && this.files.length === 0) { + throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); + } else { + } + } + }, + readEndOfCentral: function() { + var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); + if (offset < 0) { + var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER); + if (isGarbage) { + throw new Error("Can't find end of central directory : is this a zip file ? " + "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"); + } else { + throw new Error("Corrupted zip: can't find end of central directory"); + } + } + this.reader.setIndex(offset); + var endOfCentralDirOffset = offset; + this.checkSignature(sig.CENTRAL_DIRECTORY_END); + this.readBlockEndOfCentral(); + if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { + this.zip64 = true; + offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); + if (offset < 0) { + throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); + } + this.reader.setIndex(offset); + this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); + this.readBlockZip64EndOfCentralLocator(); + if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) { + this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + if (this.relativeOffsetEndOfZip64CentralDir < 0) { + throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); + } + } + this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); + this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + this.readBlockZip64EndOfCentral(); + } + var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize; + if (this.zip64) { + expectedEndOfCentralDirOffset += 20; + expectedEndOfCentralDirOffset += 12 + this.zip64EndOfCentralSize; + } + var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset; + if (extraBytes > 0) { + if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) { + } else { + this.reader.zero = extraBytes; + } + } else if (extraBytes < 0) { + throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes."); + } + }, + prepareReader: function(data2) { + this.reader = readerFor(data2); + }, + load: function(data2) { + this.prepareReader(data2); + this.readEndOfCentral(); + this.readCentralDir(); + this.readLocalFiles(); + } + }; + module2.exports = ZipEntries; +}); + +// node_modules/jszip/lib/load.js +var require_load = __commonJS((exports2, module2) => { + var utils = require_utils(); + var external = require_external(); + var utf8 = require_utf8(); + var ZipEntries = require_zipEntries(); + var Crc32Probe = require_Crc32Probe(); + var nodejsUtils = require_nodejsUtils(); + function checkEntryCRC32(zipEntry) { + return new external.Promise(function(resolve, reject2) { + var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe); + worker.on("error", function(e) { + reject2(e); + }).on("end", function() { + if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) { + reject2(new Error("Corrupted zip : CRC32 mismatch")); + } else { + resolve(); + } + }).resume(); + }); + } + module2.exports = function(data2, options) { + var zip = this; + options = utils.extend(options || {}, { + base64: false, + checkCRC32: false, + optimizedBinaryString: false, + createFolders: false, + decodeFileName: utf8.utf8decode + }); + if (nodejsUtils.isNode && nodejsUtils.isStream(data2)) { + return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")); + } + return utils.prepareContent("the loaded zip file", data2, true, options.optimizedBinaryString, options.base64).then(function(data3) { + var zipEntries = new ZipEntries(options); + zipEntries.load(data3); + return zipEntries; + }).then(function checkCRC32(zipEntries) { + var promises = [external.Promise.resolve(zipEntries)]; + var files = zipEntries.files; + if (options.checkCRC32) { + for (var i = 0;i < files.length; i++) { + promises.push(checkEntryCRC32(files[i])); + } + } + return external.Promise.all(promises); + }).then(function addFiles(results) { + var zipEntries = results.shift(); + var files = zipEntries.files; + for (var i = 0;i < files.length; i++) { + var input = files[i]; + var unsafeName = input.fileNameStr; + var safeName = utils.resolve(input.fileNameStr); + zip.file(safeName, input.decompressed, { + binary: true, + optimizedBinaryString: true, + date: input.date, + dir: input.dir, + comment: input.fileCommentStr.length ? input.fileCommentStr : null, + unixPermissions: input.unixPermissions, + dosPermissions: input.dosPermissions, + createFolders: options.createFolders + }); + if (!input.dir) { + zip.file(safeName).unsafeOriginalName = unsafeName; + } + } + if (zipEntries.zipComment.length) { + zip.comment = zipEntries.zipComment; + } + return zip; + }); + }; +}); + +// node_modules/jszip/lib/index.js +var require_lib = __commonJS((exports2, module2) => { + function JSZip() { + if (!(this instanceof JSZip)) { + return new JSZip; + } + if (arguments.length) { + throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide."); + } + this.files = Object.create(null); + this.comment = null; + this.root = ""; + this.clone = function() { + var newObj = new JSZip; + for (var i in this) { + if (typeof this[i] !== "function") { + newObj[i] = this[i]; + } + } + return newObj; + }; + } + JSZip.prototype = require_object(); + JSZip.prototype.loadAsync = require_load(); + JSZip.support = require_support(); + JSZip.defaults = require_defaults(); + JSZip.version = "3.10.1"; + JSZip.loadAsync = function(content2, options) { + return new JSZip().loadAsync(content2, options); + }; + JSZip.external = require_external(); + module2.exports = JSZip; +}); + +// src/external/ffl.js/struct-fu.js +var require_struct_fu = __commonJS((exports2, module2) => { + /*! + * struct-fu library: https://github.com/natevw/struct-fu + * forked by ariankordi: https://github.com/ariankordi/struct-fu + * @author Nathan Vander Wilt + * @license Apache-2.0 + * @license BSD-2-Clause + */ + (function(root, factory) { + if (typeof define === "function" && define.amd) { + define([], factory); + } else if (typeof module2 === "object" && module2.exports) { + module2.exports = factory(globalThis.TextEncoder, globalThis.TextDecoder); + } else { + root._ = factory(root.TextEncoder, root.TextDecoder); + } + })(typeof self !== "undefined" ? self : exports2, function(_TextEncoder, _TextDecoder) { + var _ = {}; + if (!("bind" in Function.prototype)) { + Function.prototype.bind = function(owner) { + var that = this; + if (arguments.length <= 1) { + return function() { + return that.apply(owner, arguments); + }; + } + var args = Array.prototype.slice.call(arguments, 1); + return function() { + return that.apply(owner, arguments.length === 0 ? args : args.concat(Array.prototype.slice.call(arguments))); + }; + }; + } + function newBuffer(size) { + return new Uint8Array(new ArrayBuffer(size)); + } + function extend(obj) { + var args = Array.prototype.slice.call(arguments, 1); + args.forEach(function(ext) { + Object.keys(ext).forEach(function(key2) { + obj[key2] = ext[key2]; + }); + }); + return obj; + } + function addField(ctr, f) { + if ("width" in f && typeof f.width === "number") { + ctr.bits = (ctr.bits || 0) + f.width; + while ((ctr.bits || 0) > 7) { + ctr.bytes += 1; + ctr.bits -= 8; + } + } else if (!ctr.bits) { + ctr.bytes += f.size || 0; + } else { + throw Error("Improperly aligned bitfield before field: " + (f.name || "")); + } + return ctr; + } + function arrayizeField(f, count) { + var field = typeof count === "number" ? extend({ + name: f.name, + field: f, + unpack: function(buf, off) { + off || (off = { bytes: 0, bits: 0 }); + var arr = new Array(count); + for (var idx = 0, len = arr.length;idx < len; idx += 1) { + arr[idx] = f.unpack(buf, off); + } + return arr; + }, + pack: function(arr, buf, off) { + arr || (arr = new Array(count)); + buf || (buf = newBuffer(this.size)); + off || (off = { bytes: 0, bits: 0 }); + for (var idx = 0, len = Math.min(arr.length, count);idx < len; idx += 1) { + f.pack(arr[idx], buf, off); + } + while (idx++ < count) + addField(off, f); + return buf; + } + }, f.width !== undefined ? { width: f.width * count } : { size: f.size * count }) : f; + return field; + } + _.struct = function(name2, fields, count) { + var structName; + var fieldDefs; + if (typeof name2 !== "string") { + count = fields; + fieldDefs = name2; + } else { + structName = name2; + fieldDefs = fields; + } + var _size = { bytes: 0, bits: 0 }; + var _padsById = Object.create(null); + function reduceFunc(obj, f) { + if ("_padTo" in f) { + var padField = f; + if (!padField._id) { + padField._id = "id" + Math.random().toFixed(20).slice(2); + } + var neededPadBytes = padField._padTo - _size.bytes; + if (_size.bits) { + var bitsNeeded = 8 * neededPadBytes - _size.bits; + if (bitsNeeded < 0) { + throw Error("Invalid .padTo(" + padField._padTo + ") field, struct is already " + _size.bytes + " byte(s) and " + _size.bits + " bits!"); + } + _padsById[padField._id] = { width: bitsNeeded }; + f.width = bitsNeeded; + } else { + if (neededPadBytes < 0) { + throw Error("Invalid .padTo(" + padField._padTo + ") field, struct is already " + _size.bytes + " bytes!"); + } + _padsById[padField._id] = { size: neededPadBytes }; + f.size = neededPadBytes; + } + } + if (f._hoistFields) { + var hoistFields = f._hoistFields; + Object.keys(hoistFields).forEach(function(subName) { + var _f = Object.create(hoistFields[subName]); + if ("width" in _f && typeof _f.width === "number") { + _f.offset = { bytes: _f.offset.bytes + _size.bytes, bits: _f.offset.bits }; + } else { + _f.offset = _f.offset + _size.bytes; + } + obj[subName] = _f; + }); + } else if (f.name) { + var localCopy = Object.create(f); + if ("width" in localCopy && typeof localCopy.width === "number") { + localCopy.offset = { bytes: _size.bytes, bits: _size.bits }; + } else { + localCopy.offset = _size.bytes; + } + obj[f.name] = localCopy; + } + addField(_size, f); + return obj; + } + var fieldsObj = fieldDefs.reduce(reduceFunc, {}); + if (_size.bits) { + throw Error("Improperly aligned bitfield at end of struct: " + (structName || "")); + } + var structField = { + unpack: function(buf, off) { + off = off || { bytes: 0, bits: 0 }; + var obj = {}; + fieldDefs.forEach(function(f) { + if ("_padTo" in f && f._id !== undefined) { + addField(off, _padsById[f._id]); + return; + } + var value2 = f.unpack(buf, off); + if (f.name) { + obj[f.name] = value2; + } else if (typeof value2 === "object") { + extend(obj, value2); + } + }); + return obj; + }, + pack: function(obj, buf, off) { + obj = obj || {}; + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0, bits: 0 }; + fieldDefs.forEach(function(f) { + if ("_padTo" in f && f._id !== undefined) { + addField(off, _padsById[f._id]); + return; + } + var value2 = f.name ? obj[f.name] : obj; + f.pack(value2, buf, off); + }); + return buf; + }, + _hoistFields: structName ? null : fieldsObj, + fields: fieldsObj, + size: _size.bytes, + name: structName + }; + return arrayizeField(structField, count); + }; + function truncatedReadUInt32(buffer, offset, littleEndian) { + var bytes = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : buffer; + var availableBytes = bytes.length - offset; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + if (availableBytes >= 4) { + return view.getUint32(offset, littleEndian); + } else if (availableBytes === 3) { + var first2 = view.getUint16(offset, littleEndian); + var second = view.getUint8(offset + 2); + return littleEndian ? (second << 16) + first2 >>> 0 : (first2 << 8) + second << 8 >>> 0; + } else if (availableBytes === 2) { + return view.getUint16(offset, littleEndian) << (littleEndian ? 0 : 16) >>> 0; + } else if (availableBytes === 1) { + return view.getUint8(offset) << (littleEndian ? 0 : 24) >>> 0; + } + return 0; + } + function truncatedWriteUInt32(buffer, offset, data2, littleEndian) { + var bytes = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : buffer; + var availableBytes = bytes.length - offset; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + if (availableBytes >= 4) { + view.setUint32(offset, data2, littleEndian); + } else if (availableBytes === 3) { + if (littleEndian) { + view.setUint8(offset, data2 & 255); + view.setUint16(offset + 1, data2 >>> 8, littleEndian); + } else { + view.setUint16(offset, data2 >>> 16, littleEndian); + view.setUint8(offset + 2, data2 >>> 8 & 255); + } + } else if (availableBytes === 2) { + view.setUint16(offset, littleEndian ? data2 & 65535 : data2 >>> 16, littleEndian); + } else if (availableBytes === 1) { + view.setUint8(offset, littleEndian ? data2 & 255 : data2 >>> 24); + } + } + _.padTo = function(off) { + var field = { + _padTo: off, + size: 0, + unpack: function() { + return null; + }, + pack: function() { + return newBuffer(0); + } + }; + return field; + }; + var FULL = 4294967295; + function bitfield(name2, width2, count) { + if (width2 === undefined) { + width2 = 1; + } + if (width2 > 24) { + throw Error("Bitfields support a maximum width of 24 bits."); + } + var mask2 = FULL >>> 32 - width2; + var littleEndian = this.littleEndian; + if (littleEndian) { + mask2 >>>= 0; + } + var impl = this; + return arrayizeField({ + unpack: function(buf, off) { + off = off || { bytes: 0, bits: 0 }; + var over; + var end; + var word; + if (littleEndian) { + end = off.bits || 0; + word = truncatedReadUInt32(buf, off.bytes, true) >>> 0; + over = word >>> end; + } else { + end = (off.bits || 0) + width2; + word = truncatedReadUInt32(buf, off.bytes, false) || 0; + over = word >>> 32 - end; + } + addField(off, this); + return impl.b2v.call(this, over & mask2); + }, + pack: function(val2, buf, off) { + val2 = impl.v2b.call(this, val2 || 0); + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0, bits: 0 }; + var word; + var zero; + var over; + if (littleEndian) { + word = truncatedReadUInt32(buf, off.bytes, true) >>> 0; + var shift = off.bits || 0; + zero = mask2 << shift >>> 0; + word &= ~zero; + over = (val2 & mask2) << shift; + word = (word | over) >>> 0; + truncatedWriteUInt32(buf, off.bytes, word, true); + } else { + var end = (off.bits || 0) + width2; + word = truncatedReadUInt32(buf, off.bytes, false) || 0; + zero = mask2 << 32 - end; + over = (val2 & mask2) << 32 - end; + word &= ~zero; + word = (word | over) >>> 0; + truncatedWriteUInt32(buf, off.bytes, word, false); + } + addField(off, this); + return new Uint8Array(buf); + }, + width: width2, + size: 0, + name: name2 + }, count); + } + _.bool = function(name2, count) { + return bitfield.call({ + b2v: function(b) { + return Boolean(b); + }, + v2b: function(v) { + return v ? FULL : 0; + } + }, name2, 1, count); + }; + _.ubit = bitfield.bind({ + b2v: function(b) { + return b; + }, + v2b: function(v) { + return Number(v); + } + }); + _.ubitLE = bitfield.bind({ + b2v: function(b) { + return b; + }, + v2b: function(v) { + return Number(v); + }, + littleEndian: true + }); + _.sbit = bitfield.bind({ + b2v: function(b) { + var m = 1 << (this.width || 1) - 1; + var s = b & m; + return s ? -(b &= ~m) : b; + }, + v2b: function(v) { + v = Number(v); + var m = 1 << (this.width || 1) - 1; + var s = v < 0; + return s ? -v | m : v; + } + }); + function bytefield(name2, size, count) { + var fieldName; + var fieldSize = 1; + if (typeof name2 === "string") { + fieldName = name2; + if (typeof size === "number") { + fieldSize = size; + } + } else { + fieldSize = name2; + count = size; + } + var impl = this; + return arrayizeField({ + name: fieldName, + size: fieldSize, + unpack: function(buf, off) { + off = off || { bytes: 0, bits: 0 }; + var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; + var val2 = bytes.subarray(off.bytes, off.bytes + this.size); + addField(off, this); + return impl.b2v.call(this, val2); + }, + pack: function(val2, buf, off) { + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0, bits: 0 }; + var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; + var blk = bytes.subarray(off.bytes, off.bytes + this.size); + impl.vTb.call(this, val2, blk); + addField(off, this); + return buf; + }, + b2v: function(b) { + return b; + }, + vTb: function(v, b) { + if (!v) + return 0; + var src = new Uint8Array(v); + b.set(src.subarray(0, b.length)); + return b.length; + } + }, count); + } + function swapBytesPairs(fromBuffer, toBuffer) { + toBuffer = toBuffer || fromBuffer; + var l = fromBuffer.length; + for (var i = 1;i < l; i += 2) { + var a = fromBuffer[i - 1]; + toBuffer[i - 1] = fromBuffer[i]; + toBuffer[i] = a; + } + return toBuffer; + } + _.byte = bytefield.bind({ + b2v: function(b) { + return new Uint8Array(b); + }, + vTb: function(v, b) { + if (!v) + return 0; + b.set(new Uint8Array(v)); + return v.byteLength; + } + }); + _.char = bytefield.bind({ + b2v: function(b) { + var decoder; + if (typeof _TextDecoder !== "undefined" && _TextDecoder) { + decoder = new _TextDecoder("utf-8"); + } else { + decoder = { + decode: function(buf) { + var bytes = new Uint8Array(buf); + var str = ""; + for (var i = 0;i < bytes.length; i++) { + str += String.fromCharCode(bytes[i]); + } + return str; + } + }; + } + var v = decoder.decode(b); + var z = v.indexOf("\x00"); + return ~z ? v.slice(0, z) : v; + }, + vTb: function(v, b) { + v || (v = ""); + var encoder; + if (typeof _TextEncoder !== "undefined" && _TextEncoder) { + encoder = new _TextEncoder; + } else { + encoder = { + encode: function(str) { + var arr = new Uint8Array(str.length); + for (var i2 = 0;i2 < str.length; i2++) { + arr[i2] = str.charCodeAt(i2) & 255; + } + return arr; + } + }; + } + var encoded = encoder.encode(v); + for (var i = 0;i < encoded.length && i < b.length; i++) { + b[i] = encoded[i]; + } + return encoded.length; + } + }); + _.char16le = bytefield.bind({ + b2v: function(b) { + var decoder; + if (typeof _TextDecoder !== "undefined" && _TextDecoder) { + decoder = new _TextDecoder("utf-16le"); + } else { + decoder = { + decode: function(buf) { + var bytes = new Uint8Array(buf); + var str = ""; + for (var i = 0;i < bytes.length; i += 2) { + var charCode = bytes[i] | bytes[i + 1] << 8; + str += String.fromCharCode(charCode); + } + return str; + } + }; + } + var v = decoder.decode(b); + var z = v.indexOf("\x00"); + return ~z ? v.slice(0, z) : v; + }, + vTb: function(v, b) { + v || (v = ""); + var bytesWritten = 0; + for (var i = 0;i < v.length && bytesWritten + 1 < b.length; i++) { + var charCode = v.charCodeAt(i); + b[bytesWritten++] = charCode & 255; + b[bytesWritten++] = charCode >> 8 & 255; + } + return bytesWritten; + } + }); + _.char16be = bytefield.bind({ + b2v: function(b) { + var temp = new Uint8Array(b); + swapBytesPairs(temp); + var decoder; + if (typeof _TextDecoder !== "undefined" && _TextDecoder) { + decoder = new _TextDecoder("utf-16le"); + } else { + decoder = { + decode: function(buf) { + var bytes = new Uint8Array(buf); + var str = ""; + for (var i = 0;i < bytes.length; i += 2) { + var charCode = bytes[i] | bytes[i + 1] << 8; + str += String.fromCharCode(charCode); + } + return str; + } + }; + } + var v = decoder.decode(temp.buffer); + var z = v.indexOf("\x00"); + return ~z ? v.slice(0, z) : v; + }, + vTb: function(v, b) { + v || (v = ""); + var temp = new Uint8Array(b.length); + var bytesWritten = 0; + for (var i = 0;i < v.length && bytesWritten + 1 < temp.length; i++) { + var charCode = v.charCodeAt(i); + temp[bytesWritten++] = charCode & 255; + temp[bytesWritten++] = charCode >> 8 & 255; + } + swapBytesPairs(temp, b); + return bytesWritten; + } + }); + function dataViewField(getFn, setFn, size, littleEndian) { + var func = function(name2, count) { + var fieldName; + if (typeof name2 === "string") { + fieldName = name2; + } else { + count = name2; + } + return arrayizeField({ + name: fieldName, + size, + unpack: function(buf, off) { + off = off || { bytes: 0 }; + var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + var val2 = getFn.call(view, off.bytes, littleEndian); + addField(off, this); + return val2; + }, + pack: function(val2, buf, off) { + if (val2 === undefined || val2 === null) { + val2 = 0; + } + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0 }; + var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + setFn.call(view, off.bytes, val2, littleEndian); + addField(off, this); + return new Uint8Array(buf); + } + }, count); + }; + return func; + } + var DV = DataView.prototype; + _.uint8 = dataViewField(DV.getUint8, DV.setUint8, 1, false); + _.uint16 = dataViewField(DV.getUint16, DV.setUint16, 2, false); + _.uint32 = dataViewField(DV.getUint32, DV.setUint32, 4, false); + _.uint16le = dataViewField(DV.getUint16, DV.setUint16, 2, true); + _.uint32le = dataViewField(DV.getUint32, DV.setUint32, 4, true); + _.int8 = dataViewField(DV.getInt8, DV.setInt8, 1, false); + _.int16 = dataViewField(DV.getInt16, DV.setInt16, 2, false); + _.int32 = dataViewField(DV.getInt32, DV.setInt32, 4, false); + _.int16le = dataViewField(DV.getInt16, DV.setInt16, 2, true); + _.int32le = dataViewField(DV.getInt32, DV.setInt32, 4, true); + _.float32 = dataViewField(DV.getFloat32, DV.setFloat32, 4, false); + _.float64 = dataViewField(DV.getFloat64, DV.setFloat64, 8, false); + _.float32le = dataViewField(DV.getFloat32, DV.setFloat32, 4, true); + _.float64le = dataViewField(DV.getFloat64, DV.setFloat64, 8, true); + _.derive = function(orig, pack, unpack) { + var func = function(name2, count) { + var fieldName = null; + if (typeof name2 === "string") { + fieldName = name2; + } else { + count = name2; + } + var derived = extend({ + unpack: function(buf, off) { + var rawVal = orig.unpack(buf, off); + return unpack(rawVal); + }, + pack: function(val2, buf, off) { + var packed = pack(val2); + return orig.pack(packed, buf, off); + }, + name: fieldName + }, "width" in orig ? { width: orig.width } : { size: orig.size }); + return arrayizeField(derived, count); + }; + return func; + }; + return _; + }); +}); + +// src/external/mii-frontend/qrjs.min.js +var require_qrjs_min = __commonJS((exports2, module2) => { + (function(r, t, e) { + typeof define == "function" && define.amd ? define([], e) : typeof module2 == "object" && module2.exports ? module2.exports = e() : r.QRCode = e(); + })(exports2, 0, function() { + for (var r = [null, [[10, 7, 17, 13], [1, 1, 1, 1], []], [[16, 10, 28, 22], [1, 1, 1, 1], [4, 16]], [[26, 15, 22, 18], [1, 1, 2, 2], [4, 20]], [[18, 20, 16, 26], [2, 1, 4, 2], [4, 24]], [[24, 26, 22, 18], [2, 1, 4, 4], [4, 28]], [[16, 18, 28, 24], [4, 2, 4, 4], [4, 32]], [[18, 20, 26, 18], [4, 2, 5, 6], [4, 20, 36]], [[22, 24, 26, 22], [4, 2, 6, 6], [4, 22, 40]], [[22, 30, 24, 20], [5, 2, 8, 8], [4, 24, 44]], [[26, 18, 28, 24], [5, 4, 8, 8], [4, 26, 48]], [[30, 20, 24, 28], [5, 4, 11, 8], [4, 28, 52]], [[22, 24, 28, 26], [8, 4, 11, 10], [4, 30, 56]], [[22, 26, 22, 24], [9, 4, 16, 12], [4, 32, 60]], [[24, 30, 24, 20], [9, 4, 16, 16], [4, 24, 44, 64]], [[24, 22, 24, 30], [10, 6, 18, 12], [4, 24, 46, 68]], [[28, 24, 30, 24], [10, 6, 16, 17], [4, 24, 48, 72]], [[28, 28, 28, 28], [11, 6, 19, 16], [4, 28, 52, 76]], [[26, 30, 28, 28], [13, 6, 21, 18], [4, 28, 54, 80]], [[26, 28, 26, 26], [14, 7, 25, 21], [4, 28, 56, 84]], [[26, 28, 28, 30], [16, 8, 25, 20], [4, 32, 60, 88]], [[26, 28, 30, 28], [17, 8, 25, 23], [4, 26, 48, 70, 92]], [[28, 28, 24, 30], [17, 9, 34, 23], [4, 24, 48, 72, 96]], [[28, 30, 30, 30], [18, 9, 30, 25], [4, 28, 52, 76, 100]], [[28, 30, 30, 30], [20, 10, 32, 27], [4, 26, 52, 78, 104]], [[28, 26, 30, 30], [21, 12, 35, 29], [4, 30, 56, 82, 108]], [[28, 28, 30, 28], [23, 12, 37, 34], [4, 28, 56, 84, 112]], [[28, 30, 30, 30], [25, 12, 40, 34], [4, 32, 60, 88, 116]], [[28, 30, 30, 30], [26, 13, 42, 35], [4, 24, 48, 72, 96, 120]], [[28, 30, 30, 30], [28, 14, 45, 38], [4, 28, 52, 76, 100, 124]], [[28, 30, 30, 30], [29, 15, 48, 40], [4, 24, 50, 76, 102, 128]], [[28, 30, 30, 30], [31, 16, 51, 43], [4, 28, 54, 80, 106, 132]], [[28, 30, 30, 30], [33, 17, 54, 45], [4, 32, 58, 84, 110, 136]], [[28, 30, 30, 30], [35, 18, 57, 48], [4, 28, 56, 84, 112, 140]], [[28, 30, 30, 30], [37, 19, 60, 51], [4, 32, 60, 88, 116, 144]], [[28, 30, 30, 30], [38, 19, 63, 53], [4, 28, 52, 76, 100, 124, 148]], [[28, 30, 30, 30], [40, 20, 66, 56], [4, 22, 48, 74, 100, 126, 152]], [[28, 30, 30, 30], [43, 21, 70, 59], [4, 26, 52, 78, 104, 130, 156]], [[28, 30, 30, 30], [45, 22, 74, 62], [4, 30, 56, 82, 108, 134, 160]], [[28, 30, 30, 30], [47, 24, 77, 65], [4, 24, 52, 80, 108, 136, 164]], [[28, 30, 30, 30], [49, 25, 81, 68], [4, 28, 56, 84, 112, 140, 168]]], t = /^\d*$/, e = /^[A-Za-z0-9 $%*+\-./:]*$/, n = /^[A-Z0-9 $%*+\-./:]*$/, a = [], o = [-1], u = 0, f = 1;u < 255; ++u) + a.push(f), o[f] = u, f = 2 * f ^ (f >= 128 ? 285 : 0); + var i = [[]]; + for (u = 0;u < 30; ++u) { + for (var s = i[u], h = [], l = 0;l <= u; ++l) { + var c = l < u ? a[s[l]] : 0, v = a[(u + (s[l - 1] || 0)) % 255]; + h.push(o[c ^ v]); + } + i.push(h); + } + var g = {}; + for (u = 0;u < 45; ++u) + g["0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:".charAt(u)] = u; + var p = [function(r2, t2) { + return (r2 + t2) % 2 == 0; + }, function(r2, t2) { + return r2 % 2 == 0; + }, function(r2, t2) { + return t2 % 3 == 0; + }, function(r2, t2) { + return (r2 + t2) % 3 == 0; + }, function(r2, t2) { + return ((r2 / 2 | 0) + (t2 / 3 | 0)) % 2 == 0; + }, function(r2, t2) { + return r2 * t2 % 2 + r2 * t2 % 3 == 0; + }, function(r2, t2) { + return (r2 * t2 % 2 + r2 * t2 % 3) % 2 == 0; + }, function(r2, t2) { + return ((r2 + t2) % 2 + r2 * t2 % 3) % 2 == 0; + }], d = function(r2) { + return r2 > 6; + }, m = function(t2, e2) { + var n2 = -8 & function(t3) { + var e3 = r[t3], n3 = 16 * t3 * t3 + 128 * t3 + 64; + return d(t3) && (n3 -= 36), e3[2].length && (n3 -= 25 * e3[2].length * e3[2].length - 10 * e3[2].length - 55), n3; + }(t2), a2 = r[t2]; + return n2 -= 8 * a2[0][e2] * a2[1][e2]; + }, w = function(r2, t2) { + switch (t2) { + case 1: + return r2 < 10 ? 10 : r2 < 27 ? 12 : 14; + case 2: + return r2 < 10 ? 9 : r2 < 27 ? 11 : 13; + case 4: + return r2 < 10 ? 8 : 16; + case 8: + return r2 < 10 ? 8 : r2 < 27 ? 10 : 12; + } + }, b = function(r2, t2, e2) { + var n2 = m(r2, e2) - 4 - w(r2, t2); + switch (t2) { + case 1: + return 3 * (n2 / 10 | 0) + (n2 % 10 < 4 ? 0 : n2 % 10 < 7 ? 1 : 2); + case 2: + return 2 * (n2 / 11 | 0) + (n2 % 11 < 6 ? 0 : 1); + case 4: + return n2 / 8 | 0; + case 8: + return n2 / 13 | 0; + } + }, x = function(r2, t2) { + for (var e2 = r2.slice(0), n2 = r2.length, u2 = t2.length, f2 = 0;f2 < u2; ++f2) + e2.push(0); + for (f2 = 0;f2 < n2; ) { + var i2 = o[e2[f2++]]; + if (i2 >= 0) + for (var s2 = 0;s2 < u2; ++s2) + e2[f2 + s2] ^= a[(i2 + t2[s2]) % 255]; + } + return e2.slice(n2); + }, y = function(r2, t2, e2, n2) { + for (var a2 = r2 << n2, o2 = t2 - 1;o2 >= 0; --o2) + a2 >> n2 + o2 & 1 && (a2 ^= e2 << o2); + return r2 << n2 | a2; + }, A = function(r2, t2, e2) { + for (var n2 = p[e2], a2 = r2.length, o2 = 0;o2 < a2; ++o2) + for (var u2 = 0;u2 < a2; ++u2) + t2[o2][u2] || (r2[o2][u2] ^= n2(o2, u2)); + return r2; + }, M = function(r2, t2, e2, n2) { + for (var a2 = r2.length, o2 = 21522 ^ y(e2 << 3 | n2, 5, 1335, 10), u2 = 0;u2 < 15; ++u2) { + var f2 = [a2 - 1, a2 - 2, a2 - 3, a2 - 4, a2 - 5, a2 - 6, a2 - 7, a2 - 8, 7, 5, 4, 3, 2, 1, 0][u2]; + r2[[0, 1, 2, 3, 4, 5, 7, 8, a2 - 7, a2 - 6, a2 - 5, a2 - 4, a2 - 3, a2 - 2, a2 - 1][u2]][8] = r2[8][f2] = o2 >> u2 & 1; + } + return r2; + }, C2 = function(r2) { + for (var t2 = function(r3) { + for (var t3 = 0, e3 = 0;e3 < r3.length; ++e3) + r3[e3] >= 5 && (t3 += r3[e3] - 5 + 3); + for (e3 = 5;e3 < r3.length; e3 += 2) { + var n3 = r3[e3]; + r3[e3 - 1] == n3 && r3[e3 - 2] == 3 * n3 && r3[e3 - 3] == n3 && r3[e3 - 4] == n3 && (r3[e3 - 5] >= 4 * n3 || r3[e3 + 1] >= 4 * n3) && (t3 += 40); + } + return t3; + }, e2 = r2.length, n2 = 0, a2 = 0, o2 = 0;o2 < e2; ++o2) { + var u2, f2 = r2[o2]; + u2 = [0]; + for (var i2 = 0;i2 < e2; ) { + for (s2 = 0;i2 < e2 && f2[i2]; ++s2) + ++i2; + for (u2.push(s2), s2 = 0;i2 < e2 && !f2[i2]; ++s2) + ++i2; + u2.push(s2); + } + n2 += t2(u2), u2 = [0]; + for (i2 = 0;i2 < e2; ) { + var s2; + for (s2 = 0;i2 < e2 && r2[i2][o2]; ++s2) + ++i2; + for (u2.push(s2), s2 = 0;i2 < e2 && !r2[i2][o2]; ++s2) + ++i2; + u2.push(s2); + } + n2 += t2(u2); + var h2 = r2[o2 + 1] || []; + a2 += f2[0]; + for (i2 = 1;i2 < e2; ++i2) { + var l2 = f2[i2]; + a2 += l2, f2[i2 - 1] == l2 && h2[i2] === l2 && h2[i2 - 1] === l2 && (n2 += 3); + } + } + return n2 += 10 * (Math.abs(a2 / e2 / e2 - 0.5) / 0.05 | 0); + }, L = function(t2, e2, n2, a2, o2) { + var u2 = r[e2], f2 = function(r2, t3, e3, n3) { + var a3 = [], o3 = 0, u3 = 8, f3 = e3.length, i2 = function(r3, t4) { + if (t4 >= u3) { + for (a3.push(o3 | r3 >> (t4 -= u3));t4 >= 8; ) + a3.push(r3 >> (t4 -= 8) & 255); + o3 = 0, u3 = 8; + } + t4 > 0 && (o3 |= (r3 & (1 << t4) - 1) << (u3 -= t4)); + }, s3 = w(r2, t3); + switch (i2(t3, 4), i2(f3, s3), t3) { + case 1: + for (var h3 = 2;h3 < f3; h3 += 3) + i2(parseInt(e3.substring(h3 - 2, h3 + 1), 10), 10); + i2(parseInt(e3.substring(h3 - 2), 10), [0, 4, 7][f3 % 3]); + break; + case 2: + for (h3 = 1;h3 < f3; h3 += 2) + i2(45 * g[e3.charAt(h3 - 1)] + g[e3.charAt(h3)], 11); + f3 % 2 == 1 && i2(g[e3.charAt(h3 - 1)], 6); + break; + case 4: + for (h3 = 0;h3 < f3; ++h3) + i2(e3[h3], 8); + } + for (i2(0, 4), u3 < 8 && a3.push(o3);a3.length + 1 < n3; ) + a3.push(236, 17); + return a3.length < n3 && a3.push(236), a3; + }(e2, n2, t2, m(e2, a2) >> 3); + f2 = function(r2, t3, e3) { + for (var n3 = [], a3 = r2.length / t3 | 0, o3 = 0, u3 = t3 - r2.length % t3, f3 = 0;f3 < u3; ++f3) + n3.push(o3), o3 += a3; + for (f3 = u3;f3 < t3; ++f3) + n3.push(o3), o3 += a3 + 1; + n3.push(o3); + var i2 = []; + for (f3 = 0;f3 < t3; ++f3) + i2.push(x(r2.slice(n3[f3], n3[f3 + 1]), e3)); + var s3 = [], h3 = r2.length / t3 | 0; + for (f3 = 0;f3 < h3; ++f3) + for (var l3 = 0;l3 < t3; ++l3) + s3.push(r2[n3[l3] + f3]); + for (l3 = u3;l3 < t3; ++l3) + s3.push(r2[n3[l3 + 1] - 1]); + for (f3 = 0;f3 < e3.length; ++f3) + for (l3 = 0;l3 < t3; ++l3) + s3.push(i2[l3][f3]); + return s3; + }(f2, u2[1][a2], i[u2[0][a2]]); + var s2 = function(t3) { + for (var e3 = r[t3], n3 = function(r2) { + return 4 * r2 + 17; + }(t3), a3 = [], o3 = [], u3 = 0;u3 < n3; ++u3) + a3.push([]), o3.push([]); + var f3 = function(r2, t4, e4, n4, u4) { + for (var f4 = 0;f4 < e4; ++f4) + for (var i3 = 0;i3 < n4; ++i3) + a3[r2 + f4][t4 + i3] = u4[f4] >> i3 & 1, o3[r2 + f4][t4 + i3] = 1; + }; + for (f3(0, 0, 9, 9, [127, 65, 93, 93, 93, 65, 383, 0, 64]), f3(n3 - 8, 0, 8, 9, [256, 127, 65, 93, 93, 93, 65, 127]), f3(0, n3 - 8, 9, 8, [254, 130, 186, 186, 186, 130, 254, 0, 0]), u3 = 9;u3 < n3 - 8; ++u3) + a3[6][u3] = a3[u3][6] = 1 & ~u3, o3[6][u3] = o3[u3][6] = 1; + var i2 = e3[2], s3 = i2.length; + for (u3 = 0;u3 < s3; ++u3) + for (var h3 = u3 == 0 ? s3 - 1 : s3, l3 = u3 == 0 || u3 == s3 - 1 ? 1 : 0;l3 < h3; ++l3) + f3(i2[u3], i2[l3], 5, 5, [31, 17, 21, 17, 31]); + if (d(t3)) { + var c3 = y(t3, 6, 7973, 12), v3 = 0; + for (u3 = 0;u3 < 6; ++u3) + for (l3 = 0;l3 < 3; ++l3) + a3[u3][n3 - 11 + l3] = a3[n3 - 11 + l3][u3] = c3 >> v3++ & 1, o3[u3][n3 - 11 + l3] = o3[n3 - 11 + l3][u3] = 1; + } + return { matrix: a3, reserved: o3 }; + }(e2), h2 = s2.matrix, l2 = s2.reserved; + if (function(r2, t3, e3) { + for (var n3 = r2.length, a3 = 0, o3 = -1, u3 = n3 - 1;u3 >= 0; u3 -= 2) { + u3 == 6 && --u3; + for (var f3 = o3 < 0 ? n3 - 1 : 0, i2 = 0;i2 < n3; ++i2) { + for (var s3 = u3;s3 > u3 - 2; --s3) + t3[f3][s3] || (r2[f3][s3] = e3[a3 >> 3] >> (7 & ~a3) & 1, ++a3); + f3 += o3; + } + o3 = -o3; + } + }(h2, l2, f2), o2 < 0) { + A(h2, l2, 0), M(h2, 0, a2, 0); + var c2 = 0, v2 = C2(h2); + for (A(h2, l2, 0), o2 = 1;o2 < 8; ++o2) { + A(h2, l2, o2), M(h2, 0, a2, o2); + var p2 = C2(h2); + v2 > p2 && (v2 = p2, c2 = o2), A(h2, l2, o2); + } + o2 = c2; + } + return A(h2, l2, o2), M(h2, 0, a2, o2), h2; + }, k2 = { generate: function(r2, a2) { + var o2 = { numeric: 1, alphanumeric: 2, octet: 4 }, u2 = { L: 1, M: 0, Q: 3, H: 2 }, f2 = (a2 = a2 || {}).version || -1, i2 = u2[(a2.ecclevel || "L").toUpperCase()], s2 = a2.mode ? o2[a2.mode.toLowerCase()] : -1, h2 = "mask" in a2 ? a2.mask : -1; + if (s2 < 0) + s2 = typeof r2 == "string" ? r2.match(t) ? 1 : r2.match(n) ? 2 : 4 : 4; + else if (s2 != 1 && s2 != 2 && s2 != 4) + throw "invalid or unsupported mode"; + if (r2 = function(r3, n2) { + switch (r3) { + case 1: + return n2.match(t) ? n2 : null; + case 2: + return n2.match(e) ? n2.toUpperCase() : null; + case 4: + if (typeof n2 == "string") { + for (var a3 = [], o3 = 0;o3 < n2.length; ++o3) { + var u3 = n2.charCodeAt(o3); + u3 < 128 ? a3.push(u3) : u3 < 2048 ? a3.push(192 | u3 >> 6, 128 | 63 & u3) : u3 < 65536 ? a3.push(224 | u3 >> 12, 128 | u3 >> 6 & 63, 128 | 63 & u3) : a3.push(240 | u3 >> 18, 128 | u3 >> 12 & 63, 128 | u3 >> 6 & 63, 128 | 63 & u3); + } + return a3; + } + return n2; + } + }(s2, r2), r2 === null) + throw "invalid data format"; + if (i2 < 0 || i2 > 3) + throw "invalid ECC level"; + if (f2 < 0) { + for (f2 = 1;f2 <= 40 && !(r2.length <= b(f2, s2, i2)); ++f2) + ; + if (f2 > 40) + throw "too large data"; + } else if (f2 < 1 || f2 > 40) + throw "invalid version"; + if (h2 != -1 && (h2 < 0 || h2 > 8)) + throw "invalid mask"; + return L(r2, f2, s2, i2, h2); + }, generateHTML: function(r2, t2) { + t2 = t2 || {}; + for (var e2 = k2.generate(r2, t2), n2 = Math.max(t2.modulesize || 5, 0.5), a2 = t2.unit || "px", o2 = t2.ratio || 1, u2 = Math.max(t2.margin !== null ? t2.margin : 4, 0), f2 = document.createElement("div"), i2 = e2.length, s2 = [''], h2 = 0;h2 < i2; ++h2) { + s2.push(""); + for (var l2 = 0;l2 < i2; ++l2) { + const r3 = a2 !== "px" ? "width:" + n2 * o2 + a2 + "; height:" + n2 * o2 + a2 : "width:" + n2 + "px;height:" + n2 + "px"; + s2.push(''); + } + s2.push(""); + } + return f2.className = "qrcode", f2.innerHTML = s2.join("") + "
", f2; + }, generateSVG: function(r2, t2) { + t2 = t2 || {}; + var e2 = k2.generate(r2, t2), n2 = e2.length, a2 = Math.max(t2.modulesize || 5, 0.5), o2 = Math.max(t2.margin !== null ? t2.margin : 4, 0), u2 = a2 * (n2 + 2 * o2), f2 = ' class= "fg" width="' + a2 + '" height="' + a2 + '"/>', i2 = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + i2.setAttribute("viewBox", "0 0 " + u2 + " " + u2), i2.setAttribute("style", "shape-rendering:crispEdges"), t2.modulesize && (i2.setAttribute("width", u2), i2.setAttribute("height", u2)); + for (var s2 = ["", ''], h2 = o2 * a2, l2 = 0;l2 < n2; ++l2) { + for (var c2 = o2 * a2, v2 = 0;v2 < n2; ++v2) + e2[l2][v2] && s2.push(' cw, + timingSafeEqual: () => x0, + scryptSync: () => Id, + scrypt: () => Td, + randomUUID: () => lw, + getRandomValues: () => uw, + getCurves: () => dw, + default: () => Wq, + DEFAULT_ENCODING: () => Ga +}); +function dw() { + return Hq; +} +var pw, Xa, vw, bw, mw, gw, R0 = (t, e) => () => (t && (e = t(t = 0)), e), T = (t, e) => () => (e || t((e = { exports: {} }).exports, e), e.exports), Ja = (t, e) => { + for (var r in e) + Xa(t, r, { get: e[r], enumerable: true }); +}, Ya = (t, e, r, o) => { + if (e && typeof e == "object" || typeof e == "function") + for (let f of bw(e)) + !gw.call(t, f) && f !== r && Xa(t, f, { get: () => e[f], enumerable: !(o = vw(e, f)) || o.enumerable }); + return t; +}, ot = (t, e, r) => (Ya(t, e, "default"), r && Ya(r, e, "default")), rn2 = (t, e, r) => (r = t != null ? pw(mw(t)) : {}, Ya(e || !t || !t.__esModule ? Xa(r, "default", { value: t, enumerable: true }) : r, t)), ur = (t) => Ya(Xa({}, "__esModule", { value: true }), t), Nd, Dd, Ut2, Te, on, Ie, ki, W0, $f, pc, Z0, sn, V0, G0, J0, hn, co, Jf, po, Qf, vo, Pc, Oc, th, ph, Qc, np, ap, bh, Ao, Bo, pn, _p, Ep, gh, qp, yh, Op, ko, Tt2, Gr, No, Jt, pa, Rh, pr, Y_, Oi, Fi, Ui, k1, yn, Vo, Go, Z1, Xo, Fh, ba, Jh, Dv, Qr2, fu, ou, os, eb, cu, lb, bu, vf, S7, db, yi, bf, wb, mu, wu, Mu, Eb, _u, xu, Eu, Au, Ub, Iu, Tu, ar, vs, ku, Yb, Qb, em, im, nm, yf, om, um, dm, pm, bm, Pu, Ou, Fu, ws, Aa, Em, Wu, ju, Ba, Dm, Fm, Es, Hm, Vm, ji, Yu, Ym, Xm, As, tl, ol, rg, ag, hg, hl2, pg, dl2, kn, cl2, bl, Ln, Ds, Lg, Dg, yl2, Il, Yg, t2, i2, Ws, Ks, s2, ri, Nl, or, Oa, b2, y2, _22, Pl, Cr2, Tf, Cl, N2, Fl, F2, Wl, Z2, V2, Q2, ty, e0, ny, t0, uy, dy, vy, yy, xy, Ey, Iy, o0, td, h0, u0, Kf, d0, c0, nd, Hy, od, hd, Jy, dd, r3, n3, o3, cd, d3, p3, v3, m3, Ha, bd, _32, A3, k3, N3, P3, _d, xd, w0, Ed, j3, Y3, X3, ow, qd, Xt, zq, Ga = "buffer", uw = (t) => crypto.getRandomValues(t), lw = () => crypto.randomUUID(), Hq, x0, Id, Td, cw, Wq; +var init_crypto = __esm(() => { + pw = Object.create; + Xa = Object.defineProperty; + vw = Object.getOwnPropertyDescriptor; + bw = Object.getOwnPropertyNames; + mw = Object.getPrototypeOf; + gw = Object.prototype.hasOwnProperty; + Nd = T((Qa) => { + Qa.byteLength = ww; + Qa.toByteArray = _w; + Qa.fromByteArray = Ew; + var jr = [], lr = [], yw = typeof Uint8Array < "u" ? Uint8Array : Array, B0 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (nn = 0, kd = B0.length;nn < kd; ++nn) + jr[nn] = B0[nn], lr[B0.charCodeAt(nn)] = nn; + var nn, kd; + lr[45] = 62; + lr[95] = 63; + function Ld(t) { + var e = t.length; + if (e % 4 > 0) + throw new Error("Invalid string. Length must be a multiple of 4"); + var r = t.indexOf("="); + r === -1 && (r = e); + var o = r === e ? 0 : 4 - r % 4; + return [r, o]; + } + function ww(t) { + var e = Ld(t), r = e[0], o = e[1]; + return (r + o) * 3 / 4 - o; + } + function Mw(t, e, r) { + return (e + r) * 3 / 4 - r; + } + function _w(t) { + var e, r = Ld(t), o = r[0], f = r[1], p = new yw(Mw(t, o, f)), m = 0, y = f > 0 ? o - 4 : o, M; + for (M = 0;M < y; M += 4) + e = lr[t.charCodeAt(M)] << 18 | lr[t.charCodeAt(M + 1)] << 12 | lr[t.charCodeAt(M + 2)] << 6 | lr[t.charCodeAt(M + 3)], p[m++] = e >> 16 & 255, p[m++] = e >> 8 & 255, p[m++] = e & 255; + return f === 2 && (e = lr[t.charCodeAt(M)] << 2 | lr[t.charCodeAt(M + 1)] >> 4, p[m++] = e & 255), f === 1 && (e = lr[t.charCodeAt(M)] << 10 | lr[t.charCodeAt(M + 1)] << 4 | lr[t.charCodeAt(M + 2)] >> 2, p[m++] = e >> 8 & 255, p[m++] = e & 255), p; + } + function xw(t) { + return jr[t >> 18 & 63] + jr[t >> 12 & 63] + jr[t >> 6 & 63] + jr[t & 63]; + } + function Sw(t, e, r) { + for (var o, f = [], p = e;p < r; p += 3) + o = (t[p] << 16 & 16711680) + (t[p + 1] << 8 & 65280) + (t[p + 2] & 255), f.push(xw(o)); + return f.join(""); + } + function Ew(t) { + for (var e, r = t.length, o = r % 3, f = [], p = 16383, m = 0, y = r - o;m < y; m += p) + f.push(Sw(t, m, m + p > y ? y : m + p)); + return o === 1 ? (e = t[r - 1], f.push(jr[e >> 2] + jr[e << 4 & 63] + "==")) : o === 2 && (e = (t[r - 2] << 8) + t[r - 1], f.push(jr[e >> 10] + jr[e >> 4 & 63] + jr[e << 2 & 63] + "=")), f.join(""); + } + }); + Dd = T((q0) => { + q0.read = function(t, e, r, o, f) { + var p, m, y = f * 8 - o - 1, M = (1 << y) - 1, x = M >> 1, S = -7, E2 = r ? f - 1 : 0, B = r ? -1 : 1, q = t[e + E2]; + for (E2 += B, p = q & (1 << -S) - 1, q >>= -S, S += y;S > 0; p = p * 256 + t[e + E2], E2 += B, S -= 8) + ; + for (m = p & (1 << -S) - 1, p >>= -S, S += o;S > 0; m = m * 256 + t[e + E2], E2 += B, S -= 8) + ; + if (p === 0) + p = 1 - x; + else { + if (p === M) + return m ? NaN : (q ? -1 : 1) * (1 / 0); + m = m + Math.pow(2, o), p = p - x; + } + return (q ? -1 : 1) * m * Math.pow(2, p - o); + }; + q0.write = function(t, e, r, o, f, p) { + var m, y, M, x = p * 8 - f - 1, S = (1 << x) - 1, E2 = S >> 1, B = f === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, q = o ? 0 : p - 1, L = o ? 1 : -1, ge = e < 0 || e === 0 && 1 / e < 0 ? 1 : 0; + for (e = Math.abs(e), isNaN(e) || e === 1 / 0 ? (y = isNaN(e) ? 1 : 0, m = S) : (m = Math.floor(Math.log(e) / Math.LN2), e * (M = Math.pow(2, -m)) < 1 && (m--, M *= 2), m + E2 >= 1 ? e += B / M : e += B * Math.pow(2, 1 - E2), e * M >= 2 && (m++, M /= 2), m + E2 >= S ? (y = 0, m = S) : m + E2 >= 1 ? (y = (e * M - 1) * Math.pow(2, f), m = m + E2) : (y = e * Math.pow(2, E2 - 1) * Math.pow(2, f), m = 0));f >= 8; t[r + q] = y & 255, q += L, y /= 256, f -= 8) + ; + for (m = m << f | y, x += f;x > 0; t[r + q] = m & 255, q += L, m /= 256, x -= 8) + ; + t[r + q - L] |= ge * 128; + }; + }); + Ut2 = T((Xn) => { + var I0 = Nd(), Gn = Dd(), Pd = typeof Symbol == "function" && typeof Symbol.for == "function" ? Symbol.for("nodejs.util.inspect.custom") : null; + Xn.Buffer = me; + Xn.SlowBuffer = Tw; + Xn.INSPECT_MAX_BYTES = 50; + var eo = 2147483647; + Xn.kMaxLength = eo; + me.TYPED_ARRAY_SUPPORT = Aw(); + !me.TYPED_ARRAY_SUPPORT && typeof console < "u" && typeof console.error == "function" && console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."); + function Aw() { + try { + let t = new Uint8Array(1), e = { foo: function() { + return 42; + } }; + return Object.setPrototypeOf(e, Uint8Array.prototype), Object.setPrototypeOf(t, e), t.foo() === 42; + } catch { + return false; + } + } + Object.defineProperty(me.prototype, "parent", { enumerable: true, get: function() { + if (!!me.isBuffer(this)) + return this.buffer; + } }); + Object.defineProperty(me.prototype, "offset", { enumerable: true, get: function() { + if (!!me.isBuffer(this)) + return this.byteOffset; + } }); + function li(t) { + if (t > eo) + throw new RangeError('The value "' + t + '" is invalid for option "size"'); + let e = new Uint8Array(t); + return Object.setPrototypeOf(e, me.prototype), e; + } + function me(t, e, r) { + if (typeof t == "number") { + if (typeof e == "string") + throw new TypeError('The "string" argument must be of type string. Received type number'); + return N0(t); + } + return Ud(t, e, r); + } + me.poolSize = 8192; + function Ud(t, e, r) { + if (typeof t == "string") + return Bw(t, e); + if (ArrayBuffer.isView(t)) + return qw(t); + if (t == null) + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof t); + if (Zr(t, ArrayBuffer) || t && Zr(t.buffer, ArrayBuffer) || typeof SharedArrayBuffer < "u" && (Zr(t, SharedArrayBuffer) || t && Zr(t.buffer, SharedArrayBuffer))) + return k0(t, e, r); + if (typeof t == "number") + throw new TypeError('The "value" argument must not be of type number. Received type number'); + let o = t.valueOf && t.valueOf(); + if (o != null && o !== t) + return me.from(o, e, r); + let f = Iw(t); + if (f) + return f; + if (typeof Symbol < "u" && Symbol.toPrimitive != null && typeof t[Symbol.toPrimitive] == "function") + return me.from(t[Symbol.toPrimitive]("string"), e, r); + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof t); + } + me.from = function(t, e, r) { + return Ud(t, e, r); + }; + Object.setPrototypeOf(me.prototype, Uint8Array.prototype); + Object.setPrototypeOf(me, Uint8Array); + function zd(t) { + if (typeof t != "number") + throw new TypeError('"size" argument must be of type number'); + if (t < 0) + throw new RangeError('The value "' + t + '" is invalid for option "size"'); + } + function Rw(t, e, r) { + return zd(t), t <= 0 ? li(t) : e !== undefined ? typeof r == "string" ? li(t).fill(e, r) : li(t).fill(e) : li(t); + } + me.alloc = function(t, e, r) { + return Rw(t, e, r); + }; + function N0(t) { + return zd(t), li(t < 0 ? 0 : D0(t) | 0); + } + me.allocUnsafe = function(t) { + return N0(t); + }; + me.allocUnsafeSlow = function(t) { + return N0(t); + }; + function Bw(t, e) { + if ((typeof e != "string" || e === "") && (e = "utf8"), !me.isEncoding(e)) + throw new TypeError("Unknown encoding: " + e); + let r = Hd(t, e) | 0, o = li(r), f = o.write(t, e); + return f !== r && (o = o.slice(0, f)), o; + } + function T0(t) { + let e = t.length < 0 ? 0 : D0(t.length) | 0, r = li(e); + for (let o = 0;o < e; o += 1) + r[o] = t[o] & 255; + return r; + } + function qw(t) { + if (Zr(t, Uint8Array)) { + let e = new Uint8Array(t); + return k0(e.buffer, e.byteOffset, e.byteLength); + } + return T0(t); + } + function k0(t, e, r) { + if (e < 0 || t.byteLength < e) + throw new RangeError('"offset" is outside of buffer bounds'); + if (t.byteLength < e + (r || 0)) + throw new RangeError('"length" is outside of buffer bounds'); + let o; + return e === undefined && r === undefined ? o = new Uint8Array(t) : r === undefined ? o = new Uint8Array(t, e) : o = new Uint8Array(t, e, r), Object.setPrototypeOf(o, me.prototype), o; + } + function Iw(t) { + if (me.isBuffer(t)) { + let e = D0(t.length) | 0, r = li(e); + return r.length === 0 || t.copy(r, 0, 0, e), r; + } + if (t.length !== undefined) + return typeof t.length != "number" || C0(t.length) ? li(0) : T0(t); + if (t.type === "Buffer" && Array.isArray(t.data)) + return T0(t.data); + } + function D0(t) { + if (t >= eo) + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + eo.toString(16) + " bytes"); + return t | 0; + } + function Tw(t) { + return +t != t && (t = 0), me.alloc(+t); + } + me.isBuffer = function(e) { + return e != null && e._isBuffer === true && e !== me.prototype; + }; + me.compare = function(e, r) { + if (Zr(e, Uint8Array) && (e = me.from(e, e.offset, e.byteLength)), Zr(r, Uint8Array) && (r = me.from(r, r.offset, r.byteLength)), !me.isBuffer(e) || !me.isBuffer(r)) + throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'); + if (e === r) + return 0; + let o = e.length, f = r.length; + for (let p = 0, m = Math.min(o, f);p < m; ++p) + if (e[p] !== r[p]) { + o = e[p], f = r[p]; + break; + } + return o < f ? -1 : f < o ? 1 : 0; + }; + me.isEncoding = function(e) { + switch (String(e).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } + }; + me.concat = function(e, r) { + if (!Array.isArray(e)) + throw new TypeError('"list" argument must be an Array of Buffers'); + if (e.length === 0) + return me.alloc(0); + let o; + if (r === undefined) + for (r = 0, o = 0;o < e.length; ++o) + r += e[o].length; + let f = me.allocUnsafe(r), p = 0; + for (o = 0;o < e.length; ++o) { + let m = e[o]; + if (Zr(m, Uint8Array)) + p + m.length > f.length ? (me.isBuffer(m) || (m = me.from(m)), m.copy(f, p)) : Uint8Array.prototype.set.call(f, m, p); + else if (me.isBuffer(m)) + m.copy(f, p); + else + throw new TypeError('"list" argument must be an Array of Buffers'); + p += m.length; + } + return f; + }; + function Hd(t, e) { + if (me.isBuffer(t)) + return t.length; + if (ArrayBuffer.isView(t) || Zr(t, ArrayBuffer)) + return t.byteLength; + if (typeof t != "string") + throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof t); + let r = t.length, o = arguments.length > 2 && arguments[2] === true; + if (!o && r === 0) + return 0; + let f = false; + for (;; ) + switch (e) { + case "ascii": + case "latin1": + case "binary": + return r; + case "utf8": + case "utf-8": + return L0(t).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return r * 2; + case "hex": + return r >>> 1; + case "base64": + return Xd(t).length; + default: + if (f) + return o ? -1 : L0(t).length; + e = ("" + e).toLowerCase(), f = true; + } + } + me.byteLength = Hd; + function kw(t, e, r) { + let o = false; + if ((e === undefined || e < 0) && (e = 0), e > this.length || ((r === undefined || r > this.length) && (r = this.length), r <= 0) || (r >>>= 0, e >>>= 0, r <= e)) + return ""; + for (t || (t = "utf8");; ) + switch (t) { + case "hex": + return Hw(this, e, r); + case "utf8": + case "utf-8": + return Kd(this, e, r); + case "ascii": + return Uw(this, e, r); + case "latin1": + case "binary": + return zw(this, e, r); + case "base64": + return Ow(this, e, r); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return Ww(this, e, r); + default: + if (o) + throw new TypeError("Unknown encoding: " + t); + t = (t + "").toLowerCase(), o = true; + } + } + me.prototype._isBuffer = true; + function fn(t, e, r) { + let o = t[e]; + t[e] = t[r], t[r] = o; + } + me.prototype.swap16 = function() { + let e = this.length; + if (e % 2 !== 0) + throw new RangeError("Buffer size must be a multiple of 16-bits"); + for (let r = 0;r < e; r += 2) + fn(this, r, r + 1); + return this; + }; + me.prototype.swap32 = function() { + let e = this.length; + if (e % 4 !== 0) + throw new RangeError("Buffer size must be a multiple of 32-bits"); + for (let r = 0;r < e; r += 4) + fn(this, r, r + 3), fn(this, r + 1, r + 2); + return this; + }; + me.prototype.swap64 = function() { + let e = this.length; + if (e % 8 !== 0) + throw new RangeError("Buffer size must be a multiple of 64-bits"); + for (let r = 0;r < e; r += 8) + fn(this, r, r + 7), fn(this, r + 1, r + 6), fn(this, r + 2, r + 5), fn(this, r + 3, r + 4); + return this; + }; + me.prototype.toString = function() { + let e = this.length; + return e === 0 ? "" : arguments.length === 0 ? Kd(this, 0, e) : kw.apply(this, arguments); + }; + me.prototype.toLocaleString = me.prototype.toString; + me.prototype.equals = function(e) { + if (!me.isBuffer(e)) + throw new TypeError("Argument must be a Buffer"); + return this === e ? true : me.compare(this, e) === 0; + }; + me.prototype.inspect = function() { + let e = "", r = Xn.INSPECT_MAX_BYTES; + return e = this.toString("hex", 0, r).replace(/(.{2})/g, "$1 ").trim(), this.length > r && (e += " ... "), ""; + }; + Pd && (me.prototype[Pd] = me.prototype.inspect); + me.prototype.compare = function(e, r, o, f, p) { + if (Zr(e, Uint8Array) && (e = me.from(e, e.offset, e.byteLength)), !me.isBuffer(e)) + throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof e); + if (r === undefined && (r = 0), o === undefined && (o = e ? e.length : 0), f === undefined && (f = 0), p === undefined && (p = this.length), r < 0 || o > e.length || f < 0 || p > this.length) + throw new RangeError("out of range index"); + if (f >= p && r >= o) + return 0; + if (f >= p) + return -1; + if (r >= o) + return 1; + if (r >>>= 0, o >>>= 0, f >>>= 0, p >>>= 0, this === e) + return 0; + let m = p - f, y = o - r, M = Math.min(m, y), x = this.slice(f, p), S = e.slice(r, o); + for (let E2 = 0;E2 < M; ++E2) + if (x[E2] !== S[E2]) { + m = x[E2], y = S[E2]; + break; + } + return m < y ? -1 : y < m ? 1 : 0; + }; + function Wd(t, e, r, o, f) { + if (t.length === 0) + return -1; + if (typeof r == "string" ? (o = r, r = 0) : r > 2147483647 ? r = 2147483647 : r < -2147483648 && (r = -2147483648), r = +r, C0(r) && (r = f ? 0 : t.length - 1), r < 0 && (r = t.length + r), r >= t.length) { + if (f) + return -1; + r = t.length - 1; + } else if (r < 0) + if (f) + r = 0; + else + return -1; + if (typeof e == "string" && (e = me.from(e, o)), me.isBuffer(e)) + return e.length === 0 ? -1 : Cd(t, e, r, o, f); + if (typeof e == "number") + return e = e & 255, typeof Uint8Array.prototype.indexOf == "function" ? f ? Uint8Array.prototype.indexOf.call(t, e, r) : Uint8Array.prototype.lastIndexOf.call(t, e, r) : Cd(t, [e], r, o, f); + throw new TypeError("val must be string, number or Buffer"); + } + function Cd(t, e, r, o, f) { + let p = 1, m = t.length, y = e.length; + if (o !== undefined && (o = String(o).toLowerCase(), o === "ucs2" || o === "ucs-2" || o === "utf16le" || o === "utf-16le")) { + if (t.length < 2 || e.length < 2) + return -1; + p = 2, m /= 2, y /= 2, r /= 2; + } + function M(S, E2) { + return p === 1 ? S[E2] : S.readUInt16BE(E2 * p); + } + let x; + if (f) { + let S = -1; + for (x = r;x < m; x++) + if (M(t, x) === M(e, S === -1 ? 0 : x - S)) { + if (S === -1 && (S = x), x - S + 1 === y) + return S * p; + } else + S !== -1 && (x -= x - S), S = -1; + } else + for (r + y > m && (r = m - y), x = r;x >= 0; x--) { + let S = true; + for (let E2 = 0;E2 < y; E2++) + if (M(t, x + E2) !== M(e, E2)) { + S = false; + break; + } + if (S) + return x; + } + return -1; + } + me.prototype.includes = function(e, r, o) { + return this.indexOf(e, r, o) !== -1; + }; + me.prototype.indexOf = function(e, r, o) { + return Wd(this, e, r, o, true); + }; + me.prototype.lastIndexOf = function(e, r, o) { + return Wd(this, e, r, o, false); + }; + function Lw(t, e, r, o) { + r = Number(r) || 0; + let f = t.length - r; + o ? (o = Number(o), o > f && (o = f)) : o = f; + let p = e.length; + o > p / 2 && (o = p / 2); + let m; + for (m = 0;m < o; ++m) { + let y = parseInt(e.substr(m * 2, 2), 16); + if (C0(y)) + return m; + t[r + m] = y; + } + return m; + } + function Nw(t, e, r, o) { + return to(L0(e, t.length - r), t, r, o); + } + function Dw(t, e, r, o) { + return to(Vw(e), t, r, o); + } + function Pw(t, e, r, o) { + return to(Xd(e), t, r, o); + } + function Cw(t, e, r, o) { + return to($w(e, t.length - r), t, r, o); + } + me.prototype.write = function(e, r, o, f) { + if (r === undefined) + f = "utf8", o = this.length, r = 0; + else if (o === undefined && typeof r == "string") + f = r, o = this.length, r = 0; + else if (isFinite(r)) + r = r >>> 0, isFinite(o) ? (o = o >>> 0, f === undefined && (f = "utf8")) : (f = o, o = undefined); + else + throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported"); + let p = this.length - r; + if ((o === undefined || o > p) && (o = p), e.length > 0 && (o < 0 || r < 0) || r > this.length) + throw new RangeError("Attempt to write outside buffer bounds"); + f || (f = "utf8"); + let m = false; + for (;; ) + switch (f) { + case "hex": + return Lw(this, e, r, o); + case "utf8": + case "utf-8": + return Nw(this, e, r, o); + case "ascii": + case "latin1": + case "binary": + return Dw(this, e, r, o); + case "base64": + return Pw(this, e, r, o); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return Cw(this, e, r, o); + default: + if (m) + throw new TypeError("Unknown encoding: " + f); + f = ("" + f).toLowerCase(), m = true; + } + }; + me.prototype.toJSON = function() { + return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) }; + }; + function Ow(t, e, r) { + return e === 0 && r === t.length ? I0.fromByteArray(t) : I0.fromByteArray(t.slice(e, r)); + } + function Kd(t, e, r) { + r = Math.min(t.length, r); + let o = [], f = e; + for (;f < r; ) { + let p = t[f], m = null, y = p > 239 ? 4 : p > 223 ? 3 : p > 191 ? 2 : 1; + if (f + y <= r) { + let M, x, S, E2; + switch (y) { + case 1: + p < 128 && (m = p); + break; + case 2: + M = t[f + 1], (M & 192) === 128 && (E2 = (p & 31) << 6 | M & 63, E2 > 127 && (m = E2)); + break; + case 3: + M = t[f + 1], x = t[f + 2], (M & 192) === 128 && (x & 192) === 128 && (E2 = (p & 15) << 12 | (M & 63) << 6 | x & 63, E2 > 2047 && (E2 < 55296 || E2 > 57343) && (m = E2)); + break; + case 4: + M = t[f + 1], x = t[f + 2], S = t[f + 3], (M & 192) === 128 && (x & 192) === 128 && (S & 192) === 128 && (E2 = (p & 15) << 18 | (M & 63) << 12 | (x & 63) << 6 | S & 63, E2 > 65535 && E2 < 1114112 && (m = E2)); + } + } + m === null ? (m = 65533, y = 1) : m > 65535 && (m -= 65536, o.push(m >>> 10 & 1023 | 55296), m = 56320 | m & 1023), o.push(m), f += y; + } + return Fw(o); + } + var Od = 4096; + function Fw(t) { + let e = t.length; + if (e <= Od) + return String.fromCharCode.apply(String, t); + let r = "", o = 0; + for (;o < e; ) + r += String.fromCharCode.apply(String, t.slice(o, o += Od)); + return r; + } + function Uw(t, e, r) { + let o = ""; + r = Math.min(t.length, r); + for (let f = e;f < r; ++f) + o += String.fromCharCode(t[f] & 127); + return o; + } + function zw(t, e, r) { + let o = ""; + r = Math.min(t.length, r); + for (let f = e;f < r; ++f) + o += String.fromCharCode(t[f]); + return o; + } + function Hw(t, e, r) { + let o = t.length; + (!e || e < 0) && (e = 0), (!r || r < 0 || r > o) && (r = o); + let f = ""; + for (let p = e;p < r; ++p) + f += Gw[t[p]]; + return f; + } + function Ww(t, e, r) { + let o = t.slice(e, r), f = ""; + for (let p = 0;p < o.length - 1; p += 2) + f += String.fromCharCode(o[p] + o[p + 1] * 256); + return f; + } + me.prototype.slice = function(e, r) { + let o = this.length; + e = ~~e, r = r === undefined ? o : ~~r, e < 0 ? (e += o, e < 0 && (e = 0)) : e > o && (e = o), r < 0 ? (r += o, r < 0 && (r = 0)) : r > o && (r = o), r < e && (r = e); + let f = this.subarray(e, r); + return Object.setPrototypeOf(f, me.prototype), f; + }; + function Dt(t, e, r) { + if (t % 1 !== 0 || t < 0) + throw new RangeError("offset is not uint"); + if (t + e > r) + throw new RangeError("Trying to access beyond buffer length"); + } + me.prototype.readUintLE = me.prototype.readUIntLE = function(e, r, o) { + e = e >>> 0, r = r >>> 0, o || Dt(e, r, this.length); + let f = this[e], p = 1, m = 0; + for (;++m < r && (p *= 256); ) + f += this[e + m] * p; + return f; + }; + me.prototype.readUintBE = me.prototype.readUIntBE = function(e, r, o) { + e = e >>> 0, r = r >>> 0, o || Dt(e, r, this.length); + let f = this[e + --r], p = 1; + for (;r > 0 && (p *= 256); ) + f += this[e + --r] * p; + return f; + }; + me.prototype.readUint8 = me.prototype.readUInt8 = function(e, r) { + return e = e >>> 0, r || Dt(e, 1, this.length), this[e]; + }; + me.prototype.readUint16LE = me.prototype.readUInt16LE = function(e, r) { + return e = e >>> 0, r || Dt(e, 2, this.length), this[e] | this[e + 1] << 8; + }; + me.prototype.readUint16BE = me.prototype.readUInt16BE = function(e, r) { + return e = e >>> 0, r || Dt(e, 2, this.length), this[e] << 8 | this[e + 1]; + }; + me.prototype.readUint32LE = me.prototype.readUInt32LE = function(e, r) { + return e = e >>> 0, r || Dt(e, 4, this.length), (this[e] | this[e + 1] << 8 | this[e + 2] << 16) + this[e + 3] * 16777216; + }; + me.prototype.readUint32BE = me.prototype.readUInt32BE = function(e, r) { + return e = e >>> 0, r || Dt(e, 4, this.length), this[e] * 16777216 + (this[e + 1] << 16 | this[e + 2] << 8 | this[e + 3]); + }; + me.prototype.readBigUInt64LE = Ti(function(e) { + e = e >>> 0, Yn(e, "offset"); + let r = this[e], o = this[e + 7]; + (r === undefined || o === undefined) && Vf(e, this.length - 8); + let f = r + this[++e] * 2 ** 8 + this[++e] * 2 ** 16 + this[++e] * 2 ** 24, p = this[++e] + this[++e] * 2 ** 8 + this[++e] * 2 ** 16 + o * 2 ** 24; + return BigInt(f) + (BigInt(p) << BigInt(32)); + }); + me.prototype.readBigUInt64BE = Ti(function(e) { + e = e >>> 0, Yn(e, "offset"); + let r = this[e], o = this[e + 7]; + (r === undefined || o === undefined) && Vf(e, this.length - 8); + let f = r * 2 ** 24 + this[++e] * 2 ** 16 + this[++e] * 2 ** 8 + this[++e], p = this[++e] * 2 ** 24 + this[++e] * 2 ** 16 + this[++e] * 2 ** 8 + o; + return (BigInt(f) << BigInt(32)) + BigInt(p); + }); + me.prototype.readIntLE = function(e, r, o) { + e = e >>> 0, r = r >>> 0, o || Dt(e, r, this.length); + let f = this[e], p = 1, m = 0; + for (;++m < r && (p *= 256); ) + f += this[e + m] * p; + return p *= 128, f >= p && (f -= Math.pow(2, 8 * r)), f; + }; + me.prototype.readIntBE = function(e, r, o) { + e = e >>> 0, r = r >>> 0, o || Dt(e, r, this.length); + let f = r, p = 1, m = this[e + --f]; + for (;f > 0 && (p *= 256); ) + m += this[e + --f] * p; + return p *= 128, m >= p && (m -= Math.pow(2, 8 * r)), m; + }; + me.prototype.readInt8 = function(e, r) { + return e = e >>> 0, r || Dt(e, 1, this.length), this[e] & 128 ? (255 - this[e] + 1) * -1 : this[e]; + }; + me.prototype.readInt16LE = function(e, r) { + e = e >>> 0, r || Dt(e, 2, this.length); + let o = this[e] | this[e + 1] << 8; + return o & 32768 ? o | 4294901760 : o; + }; + me.prototype.readInt16BE = function(e, r) { + e = e >>> 0, r || Dt(e, 2, this.length); + let o = this[e + 1] | this[e] << 8; + return o & 32768 ? o | 4294901760 : o; + }; + me.prototype.readInt32LE = function(e, r) { + return e = e >>> 0, r || Dt(e, 4, this.length), this[e] | this[e + 1] << 8 | this[e + 2] << 16 | this[e + 3] << 24; + }; + me.prototype.readInt32BE = function(e, r) { + return e = e >>> 0, r || Dt(e, 4, this.length), this[e] << 24 | this[e + 1] << 16 | this[e + 2] << 8 | this[e + 3]; + }; + me.prototype.readBigInt64LE = Ti(function(e) { + e = e >>> 0, Yn(e, "offset"); + let r = this[e], o = this[e + 7]; + (r === undefined || o === undefined) && Vf(e, this.length - 8); + let f = this[e + 4] + this[e + 5] * 2 ** 8 + this[e + 6] * 2 ** 16 + (o << 24); + return (BigInt(f) << BigInt(32)) + BigInt(r + this[++e] * 2 ** 8 + this[++e] * 2 ** 16 + this[++e] * 2 ** 24); + }); + me.prototype.readBigInt64BE = Ti(function(e) { + e = e >>> 0, Yn(e, "offset"); + let r = this[e], o = this[e + 7]; + (r === undefined || o === undefined) && Vf(e, this.length - 8); + let f = (r << 24) + this[++e] * 2 ** 16 + this[++e] * 2 ** 8 + this[++e]; + return (BigInt(f) << BigInt(32)) + BigInt(this[++e] * 2 ** 24 + this[++e] * 2 ** 16 + this[++e] * 2 ** 8 + o); + }); + me.prototype.readFloatLE = function(e, r) { + return e = e >>> 0, r || Dt(e, 4, this.length), Gn.read(this, e, true, 23, 4); + }; + me.prototype.readFloatBE = function(e, r) { + return e = e >>> 0, r || Dt(e, 4, this.length), Gn.read(this, e, false, 23, 4); + }; + me.prototype.readDoubleLE = function(e, r) { + return e = e >>> 0, r || Dt(e, 8, this.length), Gn.read(this, e, true, 52, 8); + }; + me.prototype.readDoubleBE = function(e, r) { + return e = e >>> 0, r || Dt(e, 8, this.length), Gn.read(this, e, false, 52, 8); + }; + function er(t, e, r, o, f, p) { + if (!me.isBuffer(t)) + throw new TypeError('"buffer" argument must be a Buffer instance'); + if (e > f || e < p) + throw new RangeError('"value" argument is out of bounds'); + if (r + o > t.length) + throw new RangeError("Index out of range"); + } + me.prototype.writeUintLE = me.prototype.writeUIntLE = function(e, r, o, f) { + if (e = +e, r = r >>> 0, o = o >>> 0, !f) { + let y = Math.pow(2, 8 * o) - 1; + er(this, e, r, o, y, 0); + } + let p = 1, m = 0; + for (this[r] = e & 255;++m < o && (p *= 256); ) + this[r + m] = e / p & 255; + return r + o; + }; + me.prototype.writeUintBE = me.prototype.writeUIntBE = function(e, r, o, f) { + if (e = +e, r = r >>> 0, o = o >>> 0, !f) { + let y = Math.pow(2, 8 * o) - 1; + er(this, e, r, o, y, 0); + } + let p = o - 1, m = 1; + for (this[r + p] = e & 255;--p >= 0 && (m *= 256); ) + this[r + p] = e / m & 255; + return r + o; + }; + me.prototype.writeUint8 = me.prototype.writeUInt8 = function(e, r, o) { + return e = +e, r = r >>> 0, o || er(this, e, r, 1, 255, 0), this[r] = e & 255, r + 1; + }; + me.prototype.writeUint16LE = me.prototype.writeUInt16LE = function(e, r, o) { + return e = +e, r = r >>> 0, o || er(this, e, r, 2, 65535, 0), this[r] = e & 255, this[r + 1] = e >>> 8, r + 2; + }; + me.prototype.writeUint16BE = me.prototype.writeUInt16BE = function(e, r, o) { + return e = +e, r = r >>> 0, o || er(this, e, r, 2, 65535, 0), this[r] = e >>> 8, this[r + 1] = e & 255, r + 2; + }; + me.prototype.writeUint32LE = me.prototype.writeUInt32LE = function(e, r, o) { + return e = +e, r = r >>> 0, o || er(this, e, r, 4, 4294967295, 0), this[r + 3] = e >>> 24, this[r + 2] = e >>> 16, this[r + 1] = e >>> 8, this[r] = e & 255, r + 4; + }; + me.prototype.writeUint32BE = me.prototype.writeUInt32BE = function(e, r, o) { + return e = +e, r = r >>> 0, o || er(this, e, r, 4, 4294967295, 0), this[r] = e >>> 24, this[r + 1] = e >>> 16, this[r + 2] = e >>> 8, this[r + 3] = e & 255, r + 4; + }; + function jd(t, e, r, o, f) { + Yd(e, o, f, t, r, 7); + let p = Number(e & BigInt(4294967295)); + t[r++] = p, p = p >> 8, t[r++] = p, p = p >> 8, t[r++] = p, p = p >> 8, t[r++] = p; + let m = Number(e >> BigInt(32) & BigInt(4294967295)); + return t[r++] = m, m = m >> 8, t[r++] = m, m = m >> 8, t[r++] = m, m = m >> 8, t[r++] = m, r; + } + function Zd(t, e, r, o, f) { + Yd(e, o, f, t, r, 7); + let p = Number(e & BigInt(4294967295)); + t[r + 7] = p, p = p >> 8, t[r + 6] = p, p = p >> 8, t[r + 5] = p, p = p >> 8, t[r + 4] = p; + let m = Number(e >> BigInt(32) & BigInt(4294967295)); + return t[r + 3] = m, m = m >> 8, t[r + 2] = m, m = m >> 8, t[r + 1] = m, m = m >> 8, t[r] = m, r + 8; + } + me.prototype.writeBigUInt64LE = Ti(function(e, r = 0) { + return jd(this, e, r, BigInt(0), BigInt("0xffffffffffffffff")); + }); + me.prototype.writeBigUInt64BE = Ti(function(e, r = 0) { + return Zd(this, e, r, BigInt(0), BigInt("0xffffffffffffffff")); + }); + me.prototype.writeIntLE = function(e, r, o, f) { + if (e = +e, r = r >>> 0, !f) { + let M = Math.pow(2, 8 * o - 1); + er(this, e, r, o, M - 1, -M); + } + let p = 0, m = 1, y = 0; + for (this[r] = e & 255;++p < o && (m *= 256); ) + e < 0 && y === 0 && this[r + p - 1] !== 0 && (y = 1), this[r + p] = (e / m >> 0) - y & 255; + return r + o; + }; + me.prototype.writeIntBE = function(e, r, o, f) { + if (e = +e, r = r >>> 0, !f) { + let M = Math.pow(2, 8 * o - 1); + er(this, e, r, o, M - 1, -M); + } + let p = o - 1, m = 1, y = 0; + for (this[r + p] = e & 255;--p >= 0 && (m *= 256); ) + e < 0 && y === 0 && this[r + p + 1] !== 0 && (y = 1), this[r + p] = (e / m >> 0) - y & 255; + return r + o; + }; + me.prototype.writeInt8 = function(e, r, o) { + return e = +e, r = r >>> 0, o || er(this, e, r, 1, 127, -128), e < 0 && (e = 255 + e + 1), this[r] = e & 255, r + 1; + }; + me.prototype.writeInt16LE = function(e, r, o) { + return e = +e, r = r >>> 0, o || er(this, e, r, 2, 32767, -32768), this[r] = e & 255, this[r + 1] = e >>> 8, r + 2; + }; + me.prototype.writeInt16BE = function(e, r, o) { + return e = +e, r = r >>> 0, o || er(this, e, r, 2, 32767, -32768), this[r] = e >>> 8, this[r + 1] = e & 255, r + 2; + }; + me.prototype.writeInt32LE = function(e, r, o) { + return e = +e, r = r >>> 0, o || er(this, e, r, 4, 2147483647, -2147483648), this[r] = e & 255, this[r + 1] = e >>> 8, this[r + 2] = e >>> 16, this[r + 3] = e >>> 24, r + 4; + }; + me.prototype.writeInt32BE = function(e, r, o) { + return e = +e, r = r >>> 0, o || er(this, e, r, 4, 2147483647, -2147483648), e < 0 && (e = 4294967295 + e + 1), this[r] = e >>> 24, this[r + 1] = e >>> 16, this[r + 2] = e >>> 8, this[r + 3] = e & 255, r + 4; + }; + me.prototype.writeBigInt64LE = Ti(function(e, r = 0) { + return jd(this, e, r, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + me.prototype.writeBigInt64BE = Ti(function(e, r = 0) { + return Zd(this, e, r, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + function Vd(t, e, r, o, f, p) { + if (r + o > t.length) + throw new RangeError("Index out of range"); + if (r < 0) + throw new RangeError("Index out of range"); + } + function $d(t, e, r, o, f) { + return e = +e, r = r >>> 0, f || Vd(t, e, r, 4, 340282346638528860000000000000000000000, -340282346638528860000000000000000000000), Gn.write(t, e, r, o, 23, 4), r + 4; + } + me.prototype.writeFloatLE = function(e, r, o) { + return $d(this, e, r, true, o); + }; + me.prototype.writeFloatBE = function(e, r, o) { + return $d(this, e, r, false, o); + }; + function Gd(t, e, r, o, f) { + return e = +e, r = r >>> 0, f || Vd(t, e, r, 8, 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, -179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000), Gn.write(t, e, r, o, 52, 8), r + 8; + } + me.prototype.writeDoubleLE = function(e, r, o) { + return Gd(this, e, r, true, o); + }; + me.prototype.writeDoubleBE = function(e, r, o) { + return Gd(this, e, r, false, o); + }; + me.prototype.copy = function(e, r, o, f) { + if (!me.isBuffer(e)) + throw new TypeError("argument should be a Buffer"); + if (o || (o = 0), !f && f !== 0 && (f = this.length), r >= e.length && (r = e.length), r || (r = 0), f > 0 && f < o && (f = o), f === o || e.length === 0 || this.length === 0) + return 0; + if (r < 0) + throw new RangeError("targetStart out of bounds"); + if (o < 0 || o >= this.length) + throw new RangeError("Index out of range"); + if (f < 0) + throw new RangeError("sourceEnd out of bounds"); + f > this.length && (f = this.length), e.length - r < f - o && (f = e.length - r + o); + let p = f - o; + return this === e && typeof Uint8Array.prototype.copyWithin == "function" ? this.copyWithin(r, o, f) : Uint8Array.prototype.set.call(e, this.subarray(o, f), r), p; + }; + me.prototype.fill = function(e, r, o, f) { + if (typeof e == "string") { + if (typeof r == "string" ? (f = r, r = 0, o = this.length) : typeof o == "string" && (f = o, o = this.length), f !== undefined && typeof f != "string") + throw new TypeError("encoding must be a string"); + if (typeof f == "string" && !me.isEncoding(f)) + throw new TypeError("Unknown encoding: " + f); + if (e.length === 1) { + let m = e.charCodeAt(0); + (f === "utf8" && m < 128 || f === "latin1") && (e = m); + } + } else + typeof e == "number" ? e = e & 255 : typeof e == "boolean" && (e = Number(e)); + if (r < 0 || this.length < r || this.length < o) + throw new RangeError("Out of range index"); + if (o <= r) + return this; + r = r >>> 0, o = o === undefined ? this.length : o >>> 0, e || (e = 0); + let p; + if (typeof e == "number") + for (p = r;p < o; ++p) + this[p] = e; + else { + let m = me.isBuffer(e) ? e : me.from(e, f), y = m.length; + if (y === 0) + throw new TypeError('The value "' + e + '" is invalid for argument "value"'); + for (p = 0;p < o - r; ++p) + this[p + r] = m[p % y]; + } + return this; + }; + var $n = {}; + function P0(t, e, r) { + $n[t] = class extends r { + constructor() { + super(), Object.defineProperty(this, "message", { value: e.apply(this, arguments), writable: true, configurable: true }), this.name = `${this.name} [${t}]`, this.stack, delete this.name; + } + get code() { + return t; + } + set code(f) { + Object.defineProperty(this, "code", { configurable: true, enumerable: true, value: f, writable: true }); + } + toString() { + return `${this.name} [${t}]: ${this.message}`; + } + }; + } + P0("ERR_BUFFER_OUT_OF_BOUNDS", function(t) { + return t ? `${t} is outside of buffer bounds` : "Attempt to access memory outside buffer bounds"; + }, RangeError); + P0("ERR_INVALID_ARG_TYPE", function(t, e) { + return `The "${t}" argument must be of type number. Received type ${typeof e}`; + }, TypeError); + P0("ERR_OUT_OF_RANGE", function(t, e, r) { + let o = `The value of "${t}" is out of range.`, f = r; + return Number.isInteger(r) && Math.abs(r) > 2 ** 32 ? f = Fd(String(r)) : typeof r == "bigint" && (f = String(r), (r > BigInt(2) ** BigInt(32) || r < -(BigInt(2) ** BigInt(32))) && (f = Fd(f)), f += "n"), o += ` It must be ${e}. Received ${f}`, o; + }, RangeError); + function Fd(t) { + let e = "", r = t.length, o = t[0] === "-" ? 1 : 0; + for (;r >= o + 4; r -= 3) + e = `_${t.slice(r - 3, r)}${e}`; + return `${t.slice(0, r)}${e}`; + } + function Kw(t, e, r) { + Yn(e, "offset"), (t[e] === undefined || t[e + r] === undefined) && Vf(e, t.length - (r + 1)); + } + function Yd(t, e, r, o, f, p) { + if (t > r || t < e) { + let m = typeof e == "bigint" ? "n" : "", y; + throw p > 3 ? e === 0 || e === BigInt(0) ? y = `>= 0${m} and < 2${m} ** ${(p + 1) * 8}${m}` : y = `>= -(2${m} ** ${(p + 1) * 8 - 1}${m}) and < 2 ** ${(p + 1) * 8 - 1}${m}` : y = `>= ${e}${m} and <= ${r}${m}`, new $n.ERR_OUT_OF_RANGE("value", y, t); + } + Kw(o, f, p); + } + function Yn(t, e) { + if (typeof t != "number") + throw new $n.ERR_INVALID_ARG_TYPE(e, "number", t); + } + function Vf(t, e, r) { + throw Math.floor(t) !== t ? (Yn(t, r), new $n.ERR_OUT_OF_RANGE(r || "offset", "an integer", t)) : e < 0 ? new $n.ERR_BUFFER_OUT_OF_BOUNDS : new $n.ERR_OUT_OF_RANGE(r || "offset", `>= ${r ? 1 : 0} and <= ${e}`, t); + } + var jw = /[^+/0-9A-Za-z-_]/g; + function Zw(t) { + if (t = t.split("=")[0], t = t.trim().replace(jw, ""), t.length < 2) + return ""; + for (;t.length % 4 !== 0; ) + t = t + "="; + return t; + } + function L0(t, e) { + e = e || 1 / 0; + let r, o = t.length, f = null, p = []; + for (let m = 0;m < o; ++m) { + if (r = t.charCodeAt(m), r > 55295 && r < 57344) { + if (!f) { + if (r > 56319) { + (e -= 3) > -1 && p.push(239, 191, 189); + continue; + } else if (m + 1 === o) { + (e -= 3) > -1 && p.push(239, 191, 189); + continue; + } + f = r; + continue; + } + if (r < 56320) { + (e -= 3) > -1 && p.push(239, 191, 189), f = r; + continue; + } + r = (f - 55296 << 10 | r - 56320) + 65536; + } else + f && (e -= 3) > -1 && p.push(239, 191, 189); + if (f = null, r < 128) { + if ((e -= 1) < 0) + break; + p.push(r); + } else if (r < 2048) { + if ((e -= 2) < 0) + break; + p.push(r >> 6 | 192, r & 63 | 128); + } else if (r < 65536) { + if ((e -= 3) < 0) + break; + p.push(r >> 12 | 224, r >> 6 & 63 | 128, r & 63 | 128); + } else if (r < 1114112) { + if ((e -= 4) < 0) + break; + p.push(r >> 18 | 240, r >> 12 & 63 | 128, r >> 6 & 63 | 128, r & 63 | 128); + } else + throw new Error("Invalid code point"); + } + return p; + } + function Vw(t) { + let e = []; + for (let r = 0;r < t.length; ++r) + e.push(t.charCodeAt(r) & 255); + return e; + } + function $w(t, e) { + let r, o, f, p = []; + for (let m = 0;m < t.length && !((e -= 2) < 0); ++m) + r = t.charCodeAt(m), o = r >> 8, f = r % 256, p.push(f), p.push(o); + return p; + } + function Xd(t) { + return I0.toByteArray(Zw(t)); + } + function to(t, e, r, o) { + let f; + for (f = 0;f < o && !(f + r >= e.length || f >= t.length); ++f) + e[f + r] = t[f]; + return f; + } + function Zr(t, e) { + return t instanceof e || t != null && t.constructor != null && t.constructor.name != null && t.constructor.name === e.name; + } + function C0(t) { + return t !== t; + } + var Gw = function() { + let t = "0123456789abcdef", e = new Array(256); + for (let r = 0;r < 16; ++r) { + let o = r * 16; + for (let f = 0;f < 16; ++f) + e[o + f] = t[r] + t[f]; + } + return e; + }(); + function Ti(t) { + return typeof BigInt > "u" ? Yw : t; + } + function Yw() { + throw new Error("BigInt not supported"); + } + }); + Te = T((O0, Qd) => { + var ro = Ut2(), Vr = ro.Buffer; + function Jd(t, e) { + for (var r in t) + e[r] = t[r]; + } + Vr.from && Vr.alloc && Vr.allocUnsafe && Vr.allocUnsafeSlow ? Qd.exports = ro : (Jd(ro, O0), O0.Buffer = an); + function an(t, e, r) { + return Vr(t, e, r); + } + an.prototype = Object.create(Vr.prototype); + Jd(Vr, an); + an.from = function(t, e, r) { + if (typeof t == "number") + throw new TypeError("Argument must not be a number"); + return Vr(t, e, r); + }; + an.alloc = function(t, e, r) { + if (typeof t != "number") + throw new TypeError("Argument must be a number"); + var o = Vr(t); + return e !== undefined ? typeof r == "string" ? o.fill(e, r) : o.fill(e) : o.fill(0), o; + }; + an.allocUnsafe = function(t) { + if (typeof t != "number") + throw new TypeError("Argument must be a number"); + return Vr(t); + }; + an.allocUnsafeSlow = function(t) { + if (typeof t != "number") + throw new TypeError("Argument must be a number"); + return ro.SlowBuffer(t); + }; + }); + on = T((Gq, U0) => { + var F0 = 65536, Xw = 4294967295; + function Jw() { + throw new Error(`Secure random number generation is not supported by this browser. +Use Chrome, Firefox or Internet Explorer 11`); + } + var Qw = Te().Buffer, io = global.crypto || global.msCrypto; + io && io.getRandomValues ? U0.exports = e6 : U0.exports = Jw; + function e6(t, e) { + if (t > Xw) + throw new RangeError("requested too many random bytes"); + var r = Qw.allocUnsafe(t); + if (t > 0) + if (t > F0) + for (var o = 0;o < t; o += F0) + io.getRandomValues(r.slice(o, o + F0)); + else + io.getRandomValues(r); + return typeof e == "function" ? process.nextTick(function() { + e(null, r); + }) : r; + } + }); + Ie = T((Yq, z0) => { + typeof Object.create == "function" ? z0.exports = function(e, r) { + r && (e.super_ = r, e.prototype = Object.create(r.prototype, { constructor: { value: e, enumerable: false, writable: true, configurable: true } })); + } : z0.exports = function(e, r) { + if (r) { + e.super_ = r; + var o = function() { + }; + o.prototype = r.prototype, e.prototype = new o, e.prototype.constructor = e; + } + }; + }); + ki = T((Xq, H0) => { + var Jn = typeof Reflect == "object" ? Reflect : null, ec = Jn && typeof Jn.apply == "function" ? Jn.apply : function(e, r, o) { + return Function.prototype.apply.call(e, r, o); + }, no; + Jn && typeof Jn.ownKeys == "function" ? no = Jn.ownKeys : Object.getOwnPropertySymbols ? no = function(e) { + return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e)); + } : no = function(e) { + return Object.getOwnPropertyNames(e); + }; + function t6(t) { + console && console.warn && console.warn(t); + } + var rc = Number.isNaN || function(e) { + return e !== e; + }; + function Fe() { + Fe.init.call(this); + } + H0.exports = Fe; + H0.exports.once = f6; + Fe.EventEmitter = Fe; + Fe.prototype._events = undefined; + Fe.prototype._eventsCount = 0; + Fe.prototype._maxListeners = undefined; + var tc = 10; + function fo(t) { + if (typeof t != "function") + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof t); + } + Object.defineProperty(Fe, "defaultMaxListeners", { enumerable: true, get: function() { + return tc; + }, set: function(t) { + if (typeof t != "number" || t < 0 || rc(t)) + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + t + "."); + tc = t; + } }); + Fe.init = function() { + (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) && (this._events = Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || undefined; + }; + Fe.prototype.setMaxListeners = function(e) { + if (typeof e != "number" || e < 0 || rc(e)) + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + e + "."); + return this._maxListeners = e, this; + }; + function ic(t) { + return t._maxListeners === undefined ? Fe.defaultMaxListeners : t._maxListeners; + } + Fe.prototype.getMaxListeners = function() { + return ic(this); + }; + Fe.prototype.emit = function(e) { + for (var r = [], o = 1;o < arguments.length; o++) + r.push(arguments[o]); + var f = e === "error", p = this._events; + if (p !== undefined) + f = f && p.error === undefined; + else if (!f) + return false; + if (f) { + var m; + if (r.length > 0 && (m = r[0]), m instanceof Error) + throw m; + var y = new Error("Unhandled error." + (m ? " (" + m.message + ")" : "")); + throw y.context = m, y; + } + var M = p[e]; + if (M === undefined) + return false; + if (typeof M == "function") + ec(M, this, r); + else + for (var x = M.length, S = sc(M, x), o = 0;o < x; ++o) + ec(S[o], this, r); + return true; + }; + function nc(t, e, r, o) { + var f, p, m; + if (fo(r), p = t._events, p === undefined ? (p = t._events = Object.create(null), t._eventsCount = 0) : (p.newListener !== undefined && (t.emit("newListener", e, r.listener ? r.listener : r), p = t._events), m = p[e]), m === undefined) + m = p[e] = r, ++t._eventsCount; + else if (typeof m == "function" ? m = p[e] = o ? [r, m] : [m, r] : o ? m.unshift(r) : m.push(r), f = ic(t), f > 0 && m.length > f && !m.warned) { + m.warned = true; + var y = new Error("Possible EventEmitter memory leak detected. " + m.length + " " + String(e) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + y.name = "MaxListenersExceededWarning", y.emitter = t, y.type = e, y.count = m.length, t6(y); + } + return t; + } + Fe.prototype.addListener = function(e, r) { + return nc(this, e, r, false); + }; + Fe.prototype.on = Fe.prototype.addListener; + Fe.prototype.prependListener = function(e, r) { + return nc(this, e, r, true); + }; + function r6() { + if (!this.fired) + return this.target.removeListener(this.type, this.wrapFn), this.fired = true, arguments.length === 0 ? this.listener.call(this.target) : this.listener.apply(this.target, arguments); + } + function fc(t, e, r) { + var o = { fired: false, wrapFn: undefined, target: t, type: e, listener: r }, f = r6.bind(o); + return f.listener = r, o.wrapFn = f, f; + } + Fe.prototype.once = function(e, r) { + return fo(r), this.on(e, fc(this, e, r)), this; + }; + Fe.prototype.prependOnceListener = function(e, r) { + return fo(r), this.prependListener(e, fc(this, e, r)), this; + }; + Fe.prototype.removeListener = function(e, r) { + var o, f, p, m, y; + if (fo(r), f = this._events, f === undefined) + return this; + if (o = f[e], o === undefined) + return this; + if (o === r || o.listener === r) + --this._eventsCount === 0 ? this._events = Object.create(null) : (delete f[e], f.removeListener && this.emit("removeListener", e, o.listener || r)); + else if (typeof o != "function") { + for (p = -1, m = o.length - 1;m >= 0; m--) + if (o[m] === r || o[m].listener === r) { + y = o[m].listener, p = m; + break; + } + if (p < 0) + return this; + p === 0 ? o.shift() : i6(o, p), o.length === 1 && (f[e] = o[0]), f.removeListener !== undefined && this.emit("removeListener", e, y || r); + } + return this; + }; + Fe.prototype.off = Fe.prototype.removeListener; + Fe.prototype.removeAllListeners = function(e) { + var r, o, f; + if (o = this._events, o === undefined) + return this; + if (o.removeListener === undefined) + return arguments.length === 0 ? (this._events = Object.create(null), this._eventsCount = 0) : o[e] !== undefined && (--this._eventsCount === 0 ? this._events = Object.create(null) : delete o[e]), this; + if (arguments.length === 0) { + var p = Object.keys(o), m; + for (f = 0;f < p.length; ++f) + m = p[f], m !== "removeListener" && this.removeAllListeners(m); + return this.removeAllListeners("removeListener"), this._events = Object.create(null), this._eventsCount = 0, this; + } + if (r = o[e], typeof r == "function") + this.removeListener(e, r); + else if (r !== undefined) + for (f = r.length - 1;f >= 0; f--) + this.removeListener(e, r[f]); + return this; + }; + function ac(t, e, r) { + var o = t._events; + if (o === undefined) + return []; + var f = o[e]; + return f === undefined ? [] : typeof f == "function" ? r ? [f.listener || f] : [f] : r ? n6(f) : sc(f, f.length); + } + Fe.prototype.listeners = function(e) { + return ac(this, e, true); + }; + Fe.prototype.rawListeners = function(e) { + return ac(this, e, false); + }; + Fe.listenerCount = function(t, e) { + return typeof t.listenerCount == "function" ? t.listenerCount(e) : oc.call(t, e); + }; + Fe.prototype.listenerCount = oc; + function oc(t) { + var e = this._events; + if (e !== undefined) { + var r = e[t]; + if (typeof r == "function") + return 1; + if (r !== undefined) + return r.length; + } + return 0; + } + Fe.prototype.eventNames = function() { + return this._eventsCount > 0 ? no(this._events) : []; + }; + function sc(t, e) { + for (var r = new Array(e), o = 0;o < e; ++o) + r[o] = t[o]; + return r; + } + function i6(t, e) { + for (;e + 1 < t.length; e++) + t[e] = t[e + 1]; + t.pop(); + } + function n6(t) { + for (var e = new Array(t.length), r = 0;r < e.length; ++r) + e[r] = t[r].listener || t[r]; + return e; + } + function f6(t, e) { + return new Promise(function(r, o) { + function f(m) { + t.removeListener(e, p), o(m); + } + function p() { + typeof t.removeListener == "function" && t.removeListener("error", f), r([].slice.call(arguments)); + } + hc(t, e, p, { once: true }), e !== "error" && a6(t, f, { once: true }); + }); + } + function a6(t, e, r) { + typeof t.on == "function" && hc(t, "error", e, r); + } + function hc(t, e, r, o) { + if (typeof t.on == "function") + o.once ? t.once(e, r) : t.on(e, r); + else if (typeof t.addEventListener == "function") + t.addEventListener(e, function f(p) { + o.once && t.removeEventListener(e, f), r(p); + }); + else + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof t); + } + }); + W0 = T((Jq, uc) => { + uc.exports = ki().EventEmitter; + }); + $f = T(() => { + }); + pc = T((tI, cc) => { + function lc(t, e) { + var r = Object.keys(t); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(t); + e && (o = o.filter(function(f) { + return Object.getOwnPropertyDescriptor(t, f).enumerable; + })), r.push.apply(r, o); + } + return r; + } + function o6(t) { + for (var e = 1;e < arguments.length; e++) { + var r = arguments[e] != null ? arguments[e] : {}; + e % 2 ? lc(Object(r), true).forEach(function(o) { + s6(t, o, r[o]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(t, Object.getOwnPropertyDescriptors(r)) : lc(Object(r)).forEach(function(o) { + Object.defineProperty(t, o, Object.getOwnPropertyDescriptor(r, o)); + }); + } + return t; + } + function s6(t, e, r) { + return e in t ? Object.defineProperty(t, e, { value: r, enumerable: true, configurable: true, writable: true }) : t[e] = r, t; + } + function h6(t, e) { + if (!(t instanceof e)) + throw new TypeError("Cannot call a class as a function"); + } + function dc(t, e) { + for (var r = 0;r < e.length; r++) { + var o = e[r]; + o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(t, o.key, o); + } + } + function u6(t, e, r) { + return e && dc(t.prototype, e), r && dc(t, r), t; + } + var l6 = Ut2(), ao = l6.Buffer, d6 = $f(), K0 = d6.inspect, c6 = K0 && K0.custom || "inspect"; + function p6(t, e, r) { + ao.prototype.copy.call(t, e, r); + } + cc.exports = function() { + function t() { + h6(this, t), this.head = null, this.tail = null, this.length = 0; + } + return u6(t, [{ key: "push", value: function(r) { + var o = { data: r, next: null }; + this.length > 0 ? this.tail.next = o : this.head = o, this.tail = o, ++this.length; + } }, { key: "unshift", value: function(r) { + var o = { data: r, next: this.head }; + this.length === 0 && (this.tail = o), this.head = o, ++this.length; + } }, { key: "shift", value: function() { + if (this.length !== 0) { + var r = this.head.data; + return this.length === 1 ? this.head = this.tail = null : this.head = this.head.next, --this.length, r; + } + } }, { key: "clear", value: function() { + this.head = this.tail = null, this.length = 0; + } }, { key: "join", value: function(r) { + if (this.length === 0) + return ""; + for (var o = this.head, f = "" + o.data;o = o.next; ) + f += r + o.data; + return f; + } }, { key: "concat", value: function(r) { + if (this.length === 0) + return ao.alloc(0); + for (var o = ao.allocUnsafe(r >>> 0), f = this.head, p = 0;f; ) + p6(f.data, o, p), p += f.data.length, f = f.next; + return o; + } }, { key: "consume", value: function(r, o) { + var f; + return r < this.head.data.length ? (f = this.head.data.slice(0, r), this.head.data = this.head.data.slice(r)) : r === this.head.data.length ? f = this.shift() : f = o ? this._getString(r) : this._getBuffer(r), f; + } }, { key: "first", value: function() { + return this.head.data; + } }, { key: "_getString", value: function(r) { + var o = this.head, f = 1, p = o.data; + for (r -= p.length;o = o.next; ) { + var m = o.data, y = r > m.length ? m.length : r; + if (y === m.length ? p += m : p += m.slice(0, r), r -= y, r === 0) { + y === m.length ? (++f, o.next ? this.head = o.next : this.head = this.tail = null) : (this.head = o, o.data = m.slice(y)); + break; + } + ++f; + } + return this.length -= f, p; + } }, { key: "_getBuffer", value: function(r) { + var o = ao.allocUnsafe(r), f = this.head, p = 1; + for (f.data.copy(o), r -= f.data.length;f = f.next; ) { + var m = f.data, y = r > m.length ? m.length : r; + if (m.copy(o, o.length - r, 0, y), r -= y, r === 0) { + y === m.length ? (++p, f.next ? this.head = f.next : this.head = this.tail = null) : (this.head = f, f.data = m.slice(y)); + break; + } + ++p; + } + return this.length -= p, o; + } }, { key: c6, value: function(r, o) { + return K0(this, o6({}, o, { depth: 0, customInspect: false })); + } }]), t; + }(); + }); + Z0 = T((rI, bc) => { + function v6(t, e) { + var r = this, o = this._readableState && this._readableState.destroyed, f = this._writableState && this._writableState.destroyed; + return o || f ? (e ? e(t) : t && (this._writableState ? this._writableState.errorEmitted || (this._writableState.errorEmitted = true, process.nextTick(j0, this, t)) : process.nextTick(j0, this, t)), this) : (this._readableState && (this._readableState.destroyed = true), this._writableState && (this._writableState.destroyed = true), this._destroy(t || null, function(p) { + !e && p ? r._writableState ? r._writableState.errorEmitted ? process.nextTick(oo, r) : (r._writableState.errorEmitted = true, process.nextTick(vc, r, p)) : process.nextTick(vc, r, p) : e ? (process.nextTick(oo, r), e(p)) : process.nextTick(oo, r); + }), this); + } + function vc(t, e) { + j0(t, e), oo(t); + } + function oo(t) { + t._writableState && !t._writableState.emitClose || t._readableState && !t._readableState.emitClose || t.emit("close"); + } + function b6() { + this._readableState && (this._readableState.destroyed = false, this._readableState.reading = false, this._readableState.ended = false, this._readableState.endEmitted = false), this._writableState && (this._writableState.destroyed = false, this._writableState.ended = false, this._writableState.ending = false, this._writableState.finalCalled = false, this._writableState.prefinished = false, this._writableState.finished = false, this._writableState.errorEmitted = false); + } + function j0(t, e) { + t.emit("error", e); + } + function m6(t, e) { + var { _readableState: r, _writableState: o } = t; + r && r.autoDestroy || o && o.autoDestroy ? t.destroy(e) : t.emit("error", e); + } + bc.exports = { destroy: v6, undestroy: b6, errorOrDestroy: m6 }; + }); + sn = T((iI, yc) => { + function g6(t, e) { + t.prototype = Object.create(e.prototype), t.prototype.constructor = t, t.__proto__ = e; + } + var gc = {}; + function dr(t, e, r) { + r || (r = Error); + function o(p, m, y) { + return typeof e == "string" ? e : e(p, m, y); + } + var f = function(p) { + g6(m, p); + function m(y, M, x) { + return p.call(this, o(y, M, x)) || this; + } + return m; + }(r); + f.prototype.name = r.name, f.prototype.code = t, gc[t] = f; + } + function mc(t, e) { + if (Array.isArray(t)) { + var r = t.length; + return t = t.map(function(o) { + return String(o); + }), r > 2 ? "one of ".concat(e, " ").concat(t.slice(0, r - 1).join(", "), ", or ") + t[r - 1] : r === 2 ? "one of ".concat(e, " ").concat(t[0], " or ").concat(t[1]) : "of ".concat(e, " ").concat(t[0]); + } else + return "of ".concat(e, " ").concat(String(t)); + } + function y6(t, e, r) { + return t.substr(!r || r < 0 ? 0 : +r, e.length) === e; + } + function w6(t, e, r) { + return (r === undefined || r > t.length) && (r = t.length), t.substring(r - e.length, r) === e; + } + function M6(t, e, r) { + return typeof r != "number" && (r = 0), r + e.length > t.length ? false : t.indexOf(e, r) !== -1; + } + dr("ERR_INVALID_OPT_VALUE", function(t, e) { + return 'The value "' + e + '" is invalid for option "' + t + '"'; + }, TypeError); + dr("ERR_INVALID_ARG_TYPE", function(t, e, r) { + var o; + typeof e == "string" && y6(e, "not ") ? (o = "must not be", e = e.replace(/^not /, "")) : o = "must be"; + var f; + if (w6(t, " argument")) + f = "The ".concat(t, " ").concat(o, " ").concat(mc(e, "type")); + else { + var p = M6(t, ".") ? "property" : "argument"; + f = 'The "'.concat(t, '" ').concat(p, " ").concat(o, " ").concat(mc(e, "type")); + } + return f += ". Received type ".concat(typeof r), f; + }, TypeError); + dr("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); + dr("ERR_METHOD_NOT_IMPLEMENTED", function(t) { + return "The " + t + " method is not implemented"; + }); + dr("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); + dr("ERR_STREAM_DESTROYED", function(t) { + return "Cannot call " + t + " after a stream was destroyed"; + }); + dr("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); + dr("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); + dr("ERR_STREAM_WRITE_AFTER_END", "write after end"); + dr("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + dr("ERR_UNKNOWN_ENCODING", function(t) { + return "Unknown encoding: " + t; + }, TypeError); + dr("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); + yc.exports.codes = gc; + }); + V0 = T((nI, wc) => { + var _62 = sn().codes.ERR_INVALID_OPT_VALUE; + function x6(t, e, r) { + return t.highWaterMark != null ? t.highWaterMark : e ? t[r] : null; + } + function S6(t, e, r, o) { + var f = x6(e, o, r); + if (f != null) { + if (!(isFinite(f) && Math.floor(f) === f) || f < 0) { + var p = o ? r : "highWaterMark"; + throw new _62(p, f); + } + return Math.floor(f); + } + return t.objectMode ? 16 : 16 * 1024; + } + wc.exports = { getHighWaterMark: S6 }; + }); + G0 = T((fI, Mc) => { + Mc.exports = E6; + function E6(t, e) { + if ($0("noDeprecation")) + return t; + var r = false; + function o() { + if (!r) { + if ($0("throwDeprecation")) + throw new Error(e); + $0("traceDeprecation") ? console.trace(e) : console.warn(e), r = true; + } + return t.apply(this, arguments); + } + return o; + } + function $0(t) { + try { + if (!global.localStorage) + return false; + } catch { + return false; + } + var e = global.localStorage[t]; + return e == null ? false : String(e).toLowerCase() === "true"; + } + }); + J0 = T((aI, Rc) => { + Rc.exports = ht; + function xc(t) { + var e = this; + this.next = null, this.entry = null, this.finish = function() { + J6(e, t); + }; + } + var Qn; + ht.WritableState = Yf; + var A6 = { deprecate: G0() }, Sc = W0(), ho = Ut2().Buffer, R6 = global.Uint8Array || function() { + }; + function B6(t) { + return ho.from(t); + } + function q6(t) { + return ho.isBuffer(t) || t instanceof R6; + } + var X0 = Z0(), I6 = V0(), T6 = I6.getHighWaterMark, Li = sn().codes, k6 = Li.ERR_INVALID_ARG_TYPE, L6 = Li.ERR_METHOD_NOT_IMPLEMENTED, N6 = Li.ERR_MULTIPLE_CALLBACK, D6 = Li.ERR_STREAM_CANNOT_PIPE, P6 = Li.ERR_STREAM_DESTROYED, C6 = Li.ERR_STREAM_NULL_VALUES, O6 = Li.ERR_STREAM_WRITE_AFTER_END, F6 = Li.ERR_UNKNOWN_ENCODING, ef = X0.errorOrDestroy; + Ie()(ht, Sc); + function U6() { + } + function Yf(t, e, r) { + Qn = Qn || hn(), t = t || {}, typeof r != "boolean" && (r = e instanceof Qn), this.objectMode = !!t.objectMode, r && (this.objectMode = this.objectMode || !!t.writableObjectMode), this.highWaterMark = T6(this, t, "writableHighWaterMark", r), this.finalCalled = false, this.needDrain = false, this.ending = false, this.ended = false, this.finished = false, this.destroyed = false; + var o = t.decodeStrings === false; + this.decodeStrings = !o, this.defaultEncoding = t.defaultEncoding || "utf8", this.length = 0, this.writing = false, this.corked = 0, this.sync = true, this.bufferProcessing = false, this.onwrite = function(f) { + V6(e, f); + }, this.writecb = null, this.writelen = 0, this.bufferedRequest = null, this.lastBufferedRequest = null, this.pendingcb = 0, this.prefinished = false, this.errorEmitted = false, this.emitClose = t.emitClose !== false, this.autoDestroy = !!t.autoDestroy, this.bufferedRequestCount = 0, this.corkedRequestsFree = new xc(this); + } + Yf.prototype.getBuffer = function() { + for (var e = this.bufferedRequest, r = [];e; ) + r.push(e), e = e.next; + return r; + }; + (function() { + try { + Object.defineProperty(Yf.prototype, "buffer", { get: A6.deprecate(function() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") }); + } catch { + } + })(); + var so; + typeof Symbol == "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] == "function" ? (so = Function.prototype[Symbol.hasInstance], Object.defineProperty(ht, Symbol.hasInstance, { value: function(e) { + return so.call(this, e) ? true : this !== ht ? false : e && e._writableState instanceof Yf; + } })) : so = function(e) { + return e instanceof this; + }; + function ht(t) { + Qn = Qn || hn(); + var e = this instanceof Qn; + if (!e && !so.call(ht, this)) + return new ht(t); + this._writableState = new Yf(t, this, e), this.writable = true, t && (typeof t.write == "function" && (this._write = t.write), typeof t.writev == "function" && (this._writev = t.writev), typeof t.destroy == "function" && (this._destroy = t.destroy), typeof t.final == "function" && (this._final = t.final)), Sc.call(this); + } + ht.prototype.pipe = function() { + ef(this, new D6); + }; + function z6(t, e) { + var r = new O6; + ef(t, r), process.nextTick(e, r); + } + function H6(t, e, r, o) { + var f; + return r === null ? f = new C6 : typeof r != "string" && !e.objectMode && (f = new k6("chunk", ["string", "Buffer"], r)), f ? (ef(t, f), process.nextTick(o, f), false) : true; + } + ht.prototype.write = function(t, e, r) { + var o = this._writableState, f = false, p = !o.objectMode && q6(t); + return p && !ho.isBuffer(t) && (t = B6(t)), typeof e == "function" && (r = e, e = null), p ? e = "buffer" : e || (e = o.defaultEncoding), typeof r != "function" && (r = U6), o.ending ? z6(this, r) : (p || H6(this, o, t, r)) && (o.pendingcb++, f = K6(this, o, p, t, e, r)), f; + }; + ht.prototype.cork = function() { + this._writableState.corked++; + }; + ht.prototype.uncork = function() { + var t = this._writableState; + t.corked && (t.corked--, !t.writing && !t.corked && !t.bufferProcessing && t.bufferedRequest && Ec(this, t)); + }; + ht.prototype.setDefaultEncoding = function(e) { + if (typeof e == "string" && (e = e.toLowerCase()), !(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((e + "").toLowerCase()) > -1)) + throw new F6(e); + return this._writableState.defaultEncoding = e, this; + }; + Object.defineProperty(ht.prototype, "writableBuffer", { enumerable: false, get: function() { + return this._writableState && this._writableState.getBuffer(); + } }); + function W6(t, e, r) { + return !t.objectMode && t.decodeStrings !== false && typeof e == "string" && (e = ho.from(e, r)), e; + } + Object.defineProperty(ht.prototype, "writableHighWaterMark", { enumerable: false, get: function() { + return this._writableState.highWaterMark; + } }); + function K6(t, e, r, o, f, p) { + if (!r) { + var m = W6(e, o, f); + o !== m && (r = true, f = "buffer", o = m); + } + var y = e.objectMode ? 1 : o.length; + e.length += y; + var M = e.length < e.highWaterMark; + if (M || (e.needDrain = true), e.writing || e.corked) { + var x = e.lastBufferedRequest; + e.lastBufferedRequest = { chunk: o, encoding: f, isBuf: r, callback: p, next: null }, x ? x.next = e.lastBufferedRequest : e.bufferedRequest = e.lastBufferedRequest, e.bufferedRequestCount += 1; + } else + Y0(t, e, false, y, o, f, p); + return M; + } + function Y0(t, e, r, o, f, p, m) { + e.writelen = o, e.writecb = m, e.writing = true, e.sync = true, e.destroyed ? e.onwrite(new P6("write")) : r ? t._writev(f, e.onwrite) : t._write(f, p, e.onwrite), e.sync = false; + } + function j6(t, e, r, o, f) { + --e.pendingcb, r ? (process.nextTick(f, o), process.nextTick(Gf, t, e), t._writableState.errorEmitted = true, ef(t, o)) : (f(o), t._writableState.errorEmitted = true, ef(t, o), Gf(t, e)); + } + function Z6(t) { + t.writing = false, t.writecb = null, t.length -= t.writelen, t.writelen = 0; + } + function V6(t, e) { + var r = t._writableState, o = r.sync, f = r.writecb; + if (typeof f != "function") + throw new N6; + if (Z6(r), e) + j6(t, r, o, e, f); + else { + var p = Ac(r) || t.destroyed; + !p && !r.corked && !r.bufferProcessing && r.bufferedRequest && Ec(t, r), o ? process.nextTick(_c, t, r, p, f) : _c(t, r, p, f); + } + } + function _c(t, e, r, o) { + r || $6(t, e), e.pendingcb--, o(), Gf(t, e); + } + function $6(t, e) { + e.length === 0 && e.needDrain && (e.needDrain = false, t.emit("drain")); + } + function Ec(t, e) { + e.bufferProcessing = true; + var r = e.bufferedRequest; + if (t._writev && r && r.next) { + var o = e.bufferedRequestCount, f = new Array(o), p = e.corkedRequestsFree; + p.entry = r; + for (var m = 0, y = true;r; ) + f[m] = r, r.isBuf || (y = false), r = r.next, m += 1; + f.allBuffers = y, Y0(t, e, true, e.length, f, "", p.finish), e.pendingcb++, e.lastBufferedRequest = null, p.next ? (e.corkedRequestsFree = p.next, p.next = null) : e.corkedRequestsFree = new xc(e), e.bufferedRequestCount = 0; + } else { + for (;r; ) { + var { chunk: M, encoding: x, callback: S } = r, E2 = e.objectMode ? 1 : M.length; + if (Y0(t, e, false, E2, M, x, S), r = r.next, e.bufferedRequestCount--, e.writing) + break; + } + r === null && (e.lastBufferedRequest = null); + } + e.bufferedRequest = r, e.bufferProcessing = false; + } + ht.prototype._write = function(t, e, r) { + r(new L6("_write()")); + }; + ht.prototype._writev = null; + ht.prototype.end = function(t, e, r) { + var o = this._writableState; + return typeof t == "function" ? (r = t, t = null, e = null) : typeof e == "function" && (r = e, e = null), t != null && this.write(t, e), o.corked && (o.corked = 1, this.uncork()), o.ending || X6(this, o, r), this; + }; + Object.defineProperty(ht.prototype, "writableLength", { enumerable: false, get: function() { + return this._writableState.length; + } }); + function Ac(t) { + return t.ending && t.length === 0 && t.bufferedRequest === null && !t.finished && !t.writing; + } + function G6(t, e) { + t._final(function(r) { + e.pendingcb--, r && ef(t, r), e.prefinished = true, t.emit("prefinish"), Gf(t, e); + }); + } + function Y6(t, e) { + !e.prefinished && !e.finalCalled && (typeof t._final == "function" && !e.destroyed ? (e.pendingcb++, e.finalCalled = true, process.nextTick(G6, t, e)) : (e.prefinished = true, t.emit("prefinish"))); + } + function Gf(t, e) { + var r = Ac(e); + if (r && (Y6(t, e), e.pendingcb === 0 && (e.finished = true, t.emit("finish"), e.autoDestroy))) { + var o = t._readableState; + (!o || o.autoDestroy && o.endEmitted) && t.destroy(); + } + return r; + } + function X6(t, e, r) { + e.ending = true, Gf(t, e), r && (e.finished ? process.nextTick(r) : t.once("finish", r)), e.ended = true, t.writable = false; + } + function J6(t, e, r) { + var o = t.entry; + for (t.entry = null;o; ) { + var f = o.callback; + e.pendingcb--, f(r), o = o.next; + } + e.corkedRequestsFree.next = t; + } + Object.defineProperty(ht.prototype, "destroyed", { enumerable: false, get: function() { + return this._writableState === undefined ? false : this._writableState.destroyed; + }, set: function(e) { + !this._writableState || (this._writableState.destroyed = e); + } }); + ht.prototype.destroy = X0.destroy; + ht.prototype._undestroy = X0.undestroy; + ht.prototype._destroy = function(t, e) { + e(t); + }; + }); + hn = T((oI, qc) => { + var Q6 = Object.keys || function(t) { + var e = []; + for (var r in t) + e.push(r); + return e; + }; + qc.exports = $r2; + var Bc = th(), eh = J0(); + Ie()($r2, Bc); + for (Q0 = Q6(eh.prototype), uo = 0;uo < Q0.length; uo++) + lo = Q0[uo], $r2.prototype[lo] || ($r2.prototype[lo] = eh.prototype[lo]); + var Q0, lo, uo; + function $r2(t) { + if (!(this instanceof $r2)) + return new $r2(t); + Bc.call(this, t), eh.call(this, t), this.allowHalfOpen = true, t && (t.readable === false && (this.readable = false), t.writable === false && (this.writable = false), t.allowHalfOpen === false && (this.allowHalfOpen = false, this.once("end", eM))); + } + Object.defineProperty($r2.prototype, "writableHighWaterMark", { enumerable: false, get: function() { + return this._writableState.highWaterMark; + } }); + Object.defineProperty($r2.prototype, "writableBuffer", { enumerable: false, get: function() { + return this._writableState && this._writableState.getBuffer(); + } }); + Object.defineProperty($r2.prototype, "writableLength", { enumerable: false, get: function() { + return this._writableState.length; + } }); + function eM() { + this._writableState.ended || process.nextTick(tM, this); + } + function tM(t) { + t.end(); + } + Object.defineProperty($r2.prototype, "destroyed", { enumerable: false, get: function() { + return this._readableState === undefined || this._writableState === undefined ? false : this._readableState.destroyed && this._writableState.destroyed; + }, set: function(e) { + this._readableState === undefined || this._writableState === undefined || (this._readableState.destroyed = e, this._writableState.destroyed = e); + } }); + }); + co = T((Tc) => { + var ih = Te().Buffer, Ic = ih.isEncoding || function(t) { + switch (t = "" + t, t && t.toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + case "raw": + return true; + default: + return false; + } + }; + function rM(t) { + if (!t) + return "utf8"; + for (var e;; ) + switch (t) { + case "utf8": + case "utf-8": + return "utf8"; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return "utf16le"; + case "latin1": + case "binary": + return "latin1"; + case "base64": + case "ascii": + case "hex": + return t; + default: + if (e) + return; + t = ("" + t).toLowerCase(), e = true; + } + } + function iM(t) { + var e = rM(t); + if (typeof e != "string" && (ih.isEncoding === Ic || !Ic(t))) + throw new Error("Unknown encoding: " + t); + return e || t; + } + Tc.StringDecoder = Xf; + function Xf(t) { + this.encoding = iM(t); + var e; + switch (this.encoding) { + case "utf16le": + this.text = hM, this.end = uM, e = 4; + break; + case "utf8": + this.fillLast = aM, e = 4; + break; + case "base64": + this.text = lM, this.end = dM, e = 3; + break; + default: + this.write = cM, this.end = pM; + return; + } + this.lastNeed = 0, this.lastTotal = 0, this.lastChar = ih.allocUnsafe(e); + } + Xf.prototype.write = function(t) { + if (t.length === 0) + return ""; + var e, r; + if (this.lastNeed) { + if (e = this.fillLast(t), e === undefined) + return ""; + r = this.lastNeed, this.lastNeed = 0; + } else + r = 0; + return r < t.length ? e ? e + this.text(t, r) : this.text(t, r) : e || ""; + }; + Xf.prototype.end = sM; + Xf.prototype.text = oM; + Xf.prototype.fillLast = function(t) { + if (this.lastNeed <= t.length) + return t.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal); + t.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, t.length), this.lastNeed -= t.length; + }; + function rh(t) { + return t <= 127 ? 0 : t >> 5 === 6 ? 2 : t >> 4 === 14 ? 3 : t >> 3 === 30 ? 4 : t >> 6 === 2 ? -1 : -2; + } + function nM(t, e, r) { + var o = e.length - 1; + if (o < r) + return 0; + var f = rh(e[o]); + return f >= 0 ? (f > 0 && (t.lastNeed = f - 1), f) : --o < r || f === -2 ? 0 : (f = rh(e[o]), f >= 0 ? (f > 0 && (t.lastNeed = f - 2), f) : --o < r || f === -2 ? 0 : (f = rh(e[o]), f >= 0 ? (f > 0 && (f === 2 ? f = 0 : t.lastNeed = f - 3), f) : 0)); + } + function fM(t, e, r) { + if ((e[0] & 192) !== 128) + return t.lastNeed = 0, "�"; + if (t.lastNeed > 1 && e.length > 1) { + if ((e[1] & 192) !== 128) + return t.lastNeed = 1, "�"; + if (t.lastNeed > 2 && e.length > 2 && (e[2] & 192) !== 128) + return t.lastNeed = 2, "�"; + } + } + function aM(t) { + var e = this.lastTotal - this.lastNeed, r = fM(this, t, e); + if (r !== undefined) + return r; + if (this.lastNeed <= t.length) + return t.copy(this.lastChar, e, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal); + t.copy(this.lastChar, e, 0, t.length), this.lastNeed -= t.length; + } + function oM(t, e) { + var r = nM(this, t, e); + if (!this.lastNeed) + return t.toString("utf8", e); + this.lastTotal = r; + var o = t.length - (r - this.lastNeed); + return t.copy(this.lastChar, 0, o), t.toString("utf8", e, o); + } + function sM(t) { + var e = t && t.length ? this.write(t) : ""; + return this.lastNeed ? e + "�" : e; + } + function hM(t, e) { + if ((t.length - e) % 2 === 0) { + var r = t.toString("utf16le", e); + if (r) { + var o = r.charCodeAt(r.length - 1); + if (o >= 55296 && o <= 56319) + return this.lastNeed = 2, this.lastTotal = 4, this.lastChar[0] = t[t.length - 2], this.lastChar[1] = t[t.length - 1], r.slice(0, -1); + } + return r; + } + return this.lastNeed = 1, this.lastTotal = 2, this.lastChar[0] = t[t.length - 1], t.toString("utf16le", e, t.length - 1); + } + function uM(t) { + var e = t && t.length ? this.write(t) : ""; + if (this.lastNeed) { + var r = this.lastTotal - this.lastNeed; + return e + this.lastChar.toString("utf16le", 0, r); + } + return e; + } + function lM(t, e) { + var r = (t.length - e) % 3; + return r === 0 ? t.toString("base64", e) : (this.lastNeed = 3 - r, this.lastTotal = 3, r === 1 ? this.lastChar[0] = t[t.length - 1] : (this.lastChar[0] = t[t.length - 2], this.lastChar[1] = t[t.length - 1]), t.toString("base64", e, t.length - r)); + } + function dM(t) { + var e = t && t.length ? this.write(t) : ""; + return this.lastNeed ? e + this.lastChar.toString("base64", 0, 3 - this.lastNeed) : e; + } + function cM(t) { + return t.toString(this.encoding); + } + function pM(t) { + return t && t.length ? this.write(t) : ""; + } + }); + Jf = {}; + Ja(Jf, { StringDecoder: () => po.StringDecoder, default: () => po.StringDecoder }); + Qf = R0(() => { + po = rn2(co()); + }); + vo = T((hI, Nc) => { + var kc = sn().codes.ERR_STREAM_PREMATURE_CLOSE; + function vM(t) { + var e = false; + return function() { + if (!e) { + e = true; + for (var r = arguments.length, o = new Array(r), f = 0;f < r; f++) + o[f] = arguments[f]; + t.apply(this, o); + } + }; + } + function bM() { + } + function mM(t) { + return t.setHeader && typeof t.abort == "function"; + } + function Lc(t, e, r) { + if (typeof e == "function") + return Lc(t, null, e); + e || (e = {}), r = vM(r || bM); + var o = e.readable || e.readable !== false && t.readable, f = e.writable || e.writable !== false && t.writable, p = function() { + t.writable || y(); + }, m = t._writableState && t._writableState.finished, y = function() { + f = false, m = true, o || r.call(t); + }, M = t._readableState && t._readableState.endEmitted, x = function() { + o = false, M = true, f || r.call(t); + }, S = function(L) { + r.call(t, L); + }, E2 = function() { + var L; + if (o && !M) + return (!t._readableState || !t._readableState.ended) && (L = new kc), r.call(t, L); + if (f && !m) + return (!t._writableState || !t._writableState.ended) && (L = new kc), r.call(t, L); + }, B = function() { + t.req.on("finish", y); + }; + return mM(t) ? (t.on("complete", y), t.on("abort", E2), t.req ? B() : t.on("request", B)) : f && !t._writableState && (t.on("end", p), t.on("close", p)), t.on("end", x), t.on("finish", y), e.error !== false && t.on("error", S), t.on("close", E2), function() { + t.removeListener("complete", y), t.removeListener("abort", E2), t.removeListener("request", B), t.req && t.req.removeListener("finish", y), t.removeListener("end", p), t.removeListener("close", p), t.removeListener("finish", y), t.removeListener("end", x), t.removeListener("error", S), t.removeListener("close", E2); + }; + } + Nc.exports = Lc; + }); + Pc = T((uI, Dc) => { + var bo; + function Ni(t, e, r) { + return e in t ? Object.defineProperty(t, e, { value: r, enumerable: true, configurable: true, writable: true }) : t[e] = r, t; + } + var gM = vo(), Di = Symbol("lastResolve"), un = Symbol("lastReject"), ea = Symbol("error"), mo = Symbol("ended"), ln = Symbol("lastPromise"), nh = Symbol("handlePromise"), dn = Symbol("stream"); + function Pi2(t, e) { + return { value: t, done: e }; + } + function yM(t) { + var e = t[Di]; + if (e !== null) { + var r = t[dn].read(); + r !== null && (t[ln] = null, t[Di] = null, t[un] = null, e(Pi2(r, false))); + } + } + function wM(t) { + process.nextTick(yM, t); + } + function MM(t, e) { + return function(r, o) { + t.then(function() { + if (e[mo]) { + r(Pi2(undefined, true)); + return; + } + e[nh](r, o); + }, o); + }; + } + var _M = Object.getPrototypeOf(function() { + }), xM = Object.setPrototypeOf((bo = { get stream() { + return this[dn]; + }, next: function() { + var e = this, r = this[ea]; + if (r !== null) + return Promise.reject(r); + if (this[mo]) + return Promise.resolve(Pi2(undefined, true)); + if (this[dn].destroyed) + return new Promise(function(m, y) { + process.nextTick(function() { + e[ea] ? y(e[ea]) : m(Pi2(undefined, true)); + }); + }); + var o = this[ln], f; + if (o) + f = new Promise(MM(o, this)); + else { + var p = this[dn].read(); + if (p !== null) + return Promise.resolve(Pi2(p, false)); + f = new Promise(this[nh]); + } + return this[ln] = f, f; + } }, Ni(bo, Symbol.asyncIterator, function() { + return this; + }), Ni(bo, "return", function() { + var e = this; + return new Promise(function(r, o) { + e[dn].destroy(null, function(f) { + if (f) { + o(f); + return; + } + r(Pi2(undefined, true)); + }); + }); + }), bo), _M), SM = function(e) { + var r, o = Object.create(xM, (r = {}, Ni(r, dn, { value: e, writable: true }), Ni(r, Di, { value: null, writable: true }), Ni(r, un, { value: null, writable: true }), Ni(r, ea, { value: null, writable: true }), Ni(r, mo, { value: e._readableState.endEmitted, writable: true }), Ni(r, nh, { value: function(p, m) { + var y = o[dn].read(); + y ? (o[ln] = null, o[Di] = null, o[un] = null, p(Pi2(y, false))) : (o[Di] = p, o[un] = m); + }, writable: true }), r)); + return o[ln] = null, gM(e, function(f) { + if (f && f.code !== "ERR_STREAM_PREMATURE_CLOSE") { + var p = o[un]; + p !== null && (o[ln] = null, o[Di] = null, o[un] = null, p(f)), o[ea] = f; + return; + } + var m = o[Di]; + m !== null && (o[ln] = null, o[Di] = null, o[un] = null, m(Pi2(undefined, true))), o[mo] = true; + }), e.on("readable", wM.bind(null, o)), o; + }; + Dc.exports = SM; + }); + Oc = T((lI, Cc) => { + Cc.exports = function() { + throw new Error("Readable.from is not available in the browser"); + }; + }); + th = T((cI, $c) => { + $c.exports = Ce; + var tf; + Ce.ReadableState = Hc; + var dI = ki().EventEmitter, zc = function(e, r) { + return e.listeners(r).length; + }, ra = W0(), go = Ut2().Buffer, EM = global.Uint8Array || function() { + }; + function AM(t) { + return go.from(t); + } + function RM(t) { + return go.isBuffer(t) || t instanceof EM; + } + var fh = $f(), Ne; + fh && fh.debuglog ? Ne = fh.debuglog("stream") : Ne = function() { + }; + var BM = pc(), dh = Z0(), qM = V0(), IM = qM.getHighWaterMark, yo = sn().codes, TM = yo.ERR_INVALID_ARG_TYPE, kM = yo.ERR_STREAM_PUSH_AFTER_EOF, LM = yo.ERR_METHOD_NOT_IMPLEMENTED, NM = yo.ERR_STREAM_UNSHIFT_AFTER_END_EVENT, rf, ah, oh; + Ie()(Ce, ra); + var ta = dh.errorOrDestroy, sh = ["error", "close", "destroy", "pause", "resume"]; + function DM(t, e, r) { + if (typeof t.prependListener == "function") + return t.prependListener(e, r); + !t._events || !t._events[e] ? t.on(e, r) : Array.isArray(t._events[e]) ? t._events[e].unshift(r) : t._events[e] = [r, t._events[e]]; + } + function Hc(t, e, r) { + tf = tf || hn(), t = t || {}, typeof r != "boolean" && (r = e instanceof tf), this.objectMode = !!t.objectMode, r && (this.objectMode = this.objectMode || !!t.readableObjectMode), this.highWaterMark = IM(this, t, "readableHighWaterMark", r), this.buffer = new BM, this.length = 0, this.pipes = null, this.pipesCount = 0, this.flowing = null, this.ended = false, this.endEmitted = false, this.reading = false, this.sync = true, this.needReadable = false, this.emittedReadable = false, this.readableListening = false, this.resumeScheduled = false, this.paused = true, this.emitClose = t.emitClose !== false, this.autoDestroy = !!t.autoDestroy, this.destroyed = false, this.defaultEncoding = t.defaultEncoding || "utf8", this.awaitDrain = 0, this.readingMore = false, this.decoder = null, this.encoding = null, t.encoding && (rf || (rf = (Qf(), ur(Jf)).StringDecoder), this.decoder = new rf(t.encoding), this.encoding = t.encoding); + } + function Ce(t) { + if (tf = tf || hn(), !(this instanceof Ce)) + return new Ce(t); + var e = this instanceof tf; + this._readableState = new Hc(t, this, e), this.readable = true, t && (typeof t.read == "function" && (this._read = t.read), typeof t.destroy == "function" && (this._destroy = t.destroy)), ra.call(this); + } + Object.defineProperty(Ce.prototype, "destroyed", { enumerable: false, get: function() { + return this._readableState === undefined ? false : this._readableState.destroyed; + }, set: function(e) { + !this._readableState || (this._readableState.destroyed = e); + } }); + Ce.prototype.destroy = dh.destroy; + Ce.prototype._undestroy = dh.undestroy; + Ce.prototype._destroy = function(t, e) { + e(t); + }; + Ce.prototype.push = function(t, e) { + var r = this._readableState, o; + return r.objectMode ? o = true : typeof t == "string" && (e = e || r.defaultEncoding, e !== r.encoding && (t = go.from(t, e), e = ""), o = true), Wc(this, t, e, false, o); + }; + Ce.prototype.unshift = function(t) { + return Wc(this, t, null, true, false); + }; + function Wc(t, e, r, o, f) { + Ne("readableAddChunk", e); + var p = t._readableState; + if (e === null) + p.reading = false, OM(t, p); + else { + var m; + if (f || (m = PM(p, e)), m) + ta(t, m); + else if (p.objectMode || e && e.length > 0) + if (typeof e != "string" && !p.objectMode && Object.getPrototypeOf(e) !== go.prototype && (e = AM(e)), o) + p.endEmitted ? ta(t, new NM) : hh(t, p, e, true); + else if (p.ended) + ta(t, new kM); + else { + if (p.destroyed) + return false; + p.reading = false, p.decoder && !r ? (e = p.decoder.write(e), p.objectMode || e.length !== 0 ? hh(t, p, e, false) : lh(t, p)) : hh(t, p, e, false); + } + else + o || (p.reading = false, lh(t, p)); + } + return !p.ended && (p.length < p.highWaterMark || p.length === 0); + } + function hh(t, e, r, o) { + e.flowing && e.length === 0 && !e.sync ? (e.awaitDrain = 0, t.emit("data", r)) : (e.length += e.objectMode ? 1 : r.length, o ? e.buffer.unshift(r) : e.buffer.push(r), e.needReadable && wo(t)), lh(t, e); + } + function PM(t, e) { + var r; + return !RM(e) && typeof e != "string" && e !== undefined && !t.objectMode && (r = new TM("chunk", ["string", "Buffer", "Uint8Array"], e)), r; + } + Ce.prototype.isPaused = function() { + return this._readableState.flowing === false; + }; + Ce.prototype.setEncoding = function(t) { + rf || (rf = (Qf(), ur(Jf)).StringDecoder); + var e = new rf(t); + this._readableState.decoder = e, this._readableState.encoding = this._readableState.decoder.encoding; + for (var r = this._readableState.buffer.head, o = "";r !== null; ) + o += e.write(r.data), r = r.next; + return this._readableState.buffer.clear(), o !== "" && this._readableState.buffer.push(o), this._readableState.length = o.length, this; + }; + var Fc = 1073741824; + function CM(t) { + return t >= Fc ? t = Fc : (t--, t |= t >>> 1, t |= t >>> 2, t |= t >>> 4, t |= t >>> 8, t |= t >>> 16, t++), t; + } + function Uc2(t, e) { + return t <= 0 || e.length === 0 && e.ended ? 0 : e.objectMode ? 1 : t !== t ? e.flowing && e.length ? e.buffer.head.data.length : e.length : (t > e.highWaterMark && (e.highWaterMark = CM(t)), t <= e.length ? t : e.ended ? e.length : (e.needReadable = true, 0)); + } + Ce.prototype.read = function(t) { + Ne("read", t), t = parseInt(t, 10); + var e = this._readableState, r = t; + if (t !== 0 && (e.emittedReadable = false), t === 0 && e.needReadable && ((e.highWaterMark !== 0 ? e.length >= e.highWaterMark : e.length > 0) || e.ended)) + return Ne("read: emitReadable", e.length, e.ended), e.length === 0 && e.ended ? uh(this) : wo(this), null; + if (t = Uc2(t, e), t === 0 && e.ended) + return e.length === 0 && uh(this), null; + var o = e.needReadable; + Ne("need readable", o), (e.length === 0 || e.length - t < e.highWaterMark) && (o = true, Ne("length less than watermark", o)), e.ended || e.reading ? (o = false, Ne("reading or ended", o)) : o && (Ne("do read"), e.reading = true, e.sync = true, e.length === 0 && (e.needReadable = true), this._read(e.highWaterMark), e.sync = false, e.reading || (t = Uc2(r, e))); + var f; + return t > 0 ? f = Zc(t, e) : f = null, f === null ? (e.needReadable = e.length <= e.highWaterMark, t = 0) : (e.length -= t, e.awaitDrain = 0), e.length === 0 && (e.ended || (e.needReadable = true), r !== t && e.ended && uh(this)), f !== null && this.emit("data", f), f; + }; + function OM(t, e) { + if (Ne("onEofChunk"), !e.ended) { + if (e.decoder) { + var r = e.decoder.end(); + r && r.length && (e.buffer.push(r), e.length += e.objectMode ? 1 : r.length); + } + e.ended = true, e.sync ? wo(t) : (e.needReadable = false, e.emittedReadable || (e.emittedReadable = true, Kc(t))); + } + } + function wo(t) { + var e = t._readableState; + Ne("emitReadable", e.needReadable, e.emittedReadable), e.needReadable = false, e.emittedReadable || (Ne("emitReadable", e.flowing), e.emittedReadable = true, process.nextTick(Kc, t)); + } + function Kc(t) { + var e = t._readableState; + Ne("emitReadable_", e.destroyed, e.length, e.ended), !e.destroyed && (e.length || e.ended) && (t.emit("readable"), e.emittedReadable = false), e.needReadable = !e.flowing && !e.ended && e.length <= e.highWaterMark, ch(t); + } + function lh(t, e) { + e.readingMore || (e.readingMore = true, process.nextTick(FM, t, e)); + } + function FM(t, e) { + for (;!e.reading && !e.ended && (e.length < e.highWaterMark || e.flowing && e.length === 0); ) { + var r = e.length; + if (Ne("maybeReadMore read 0"), t.read(0), r === e.length) + break; + } + e.readingMore = false; + } + Ce.prototype._read = function(t) { + ta(this, new LM("_read()")); + }; + Ce.prototype.pipe = function(t, e) { + var r = this, o = this._readableState; + switch (o.pipesCount) { + case 0: + o.pipes = t; + break; + case 1: + o.pipes = [o.pipes, t]; + break; + default: + o.pipes.push(t); + break; + } + o.pipesCount += 1, Ne("pipe count=%d opts=%j", o.pipesCount, e); + var f = (!e || e.end !== false) && t !== process.stdout && t !== process.stderr, p = f ? y : ge; + o.endEmitted ? process.nextTick(p) : r.once("end", p), t.on("unpipe", m); + function m(_e, N) { + Ne("onunpipe"), _e === r && N && N.hasUnpiped === false && (N.hasUnpiped = true, S()); + } + function y() { + Ne("onend"), t.end(); + } + var M = UM(r); + t.on("drain", M); + var x = false; + function S() { + Ne("cleanup"), t.removeListener("close", q), t.removeListener("finish", L), t.removeListener("drain", M), t.removeListener("error", B), t.removeListener("unpipe", m), r.removeListener("end", y), r.removeListener("end", ge), r.removeListener("data", E2), x = true, o.awaitDrain && (!t._writableState || t._writableState.needDrain) && M(); + } + r.on("data", E2); + function E2(_e) { + Ne("ondata"); + var N = t.write(_e); + Ne("dest.write", N), N === false && ((o.pipesCount === 1 && o.pipes === t || o.pipesCount > 1 && Vc(o.pipes, t) !== -1) && !x && (Ne("false write response, pause", o.awaitDrain), o.awaitDrain++), r.pause()); + } + function B(_e) { + Ne("onerror", _e), ge(), t.removeListener("error", B), zc(t, "error") === 0 && ta(t, _e); + } + DM(t, "error", B); + function q() { + t.removeListener("finish", L), ge(); + } + t.once("close", q); + function L() { + Ne("onfinish"), t.removeListener("close", q), ge(); + } + t.once("finish", L); + function ge() { + Ne("unpipe"), r.unpipe(t); + } + return t.emit("pipe", r), o.flowing || (Ne("pipe resume"), r.resume()), t; + }; + function UM(t) { + return function() { + var r = t._readableState; + Ne("pipeOnDrain", r.awaitDrain), r.awaitDrain && r.awaitDrain--, r.awaitDrain === 0 && zc(t, "data") && (r.flowing = true, ch(t)); + }; + } + Ce.prototype.unpipe = function(t) { + var e = this._readableState, r = { hasUnpiped: false }; + if (e.pipesCount === 0) + return this; + if (e.pipesCount === 1) + return t && t !== e.pipes ? this : (t || (t = e.pipes), e.pipes = null, e.pipesCount = 0, e.flowing = false, t && t.emit("unpipe", this, r), this); + if (!t) { + var { pipes: o, pipesCount: f } = e; + e.pipes = null, e.pipesCount = 0, e.flowing = false; + for (var p = 0;p < f; p++) + o[p].emit("unpipe", this, { hasUnpiped: false }); + return this; + } + var m = Vc(e.pipes, t); + return m === -1 ? this : (e.pipes.splice(m, 1), e.pipesCount -= 1, e.pipesCount === 1 && (e.pipes = e.pipes[0]), t.emit("unpipe", this, r), this); + }; + Ce.prototype.on = function(t, e) { + var r = ra.prototype.on.call(this, t, e), o = this._readableState; + return t === "data" ? (o.readableListening = this.listenerCount("readable") > 0, o.flowing !== false && this.resume()) : t === "readable" && !o.endEmitted && !o.readableListening && (o.readableListening = o.needReadable = true, o.flowing = false, o.emittedReadable = false, Ne("on readable", o.length, o.reading), o.length ? wo(this) : o.reading || process.nextTick(zM, this)), r; + }; + Ce.prototype.addListener = Ce.prototype.on; + Ce.prototype.removeListener = function(t, e) { + var r = ra.prototype.removeListener.call(this, t, e); + return t === "readable" && process.nextTick(jc, this), r; + }; + Ce.prototype.removeAllListeners = function(t) { + var e = ra.prototype.removeAllListeners.apply(this, arguments); + return (t === "readable" || t === undefined) && process.nextTick(jc, this), e; + }; + function jc(t) { + var e = t._readableState; + e.readableListening = t.listenerCount("readable") > 0, e.resumeScheduled && !e.paused ? e.flowing = true : t.listenerCount("data") > 0 && t.resume(); + } + function zM(t) { + Ne("readable nexttick read 0"), t.read(0); + } + Ce.prototype.resume = function() { + var t = this._readableState; + return t.flowing || (Ne("resume"), t.flowing = !t.readableListening, HM(this, t)), t.paused = false, this; + }; + function HM(t, e) { + e.resumeScheduled || (e.resumeScheduled = true, process.nextTick(WM, t, e)); + } + function WM(t, e) { + Ne("resume", e.reading), e.reading || t.read(0), e.resumeScheduled = false, t.emit("resume"), ch(t), e.flowing && !e.reading && t.read(0); + } + Ce.prototype.pause = function() { + return Ne("call pause flowing=%j", this._readableState.flowing), this._readableState.flowing !== false && (Ne("pause"), this._readableState.flowing = false, this.emit("pause")), this._readableState.paused = true, this; + }; + function ch(t) { + var e = t._readableState; + for (Ne("flow", e.flowing);e.flowing && t.read() !== null; ) + ; + } + Ce.prototype.wrap = function(t) { + var e = this, r = this._readableState, o = false; + t.on("end", function() { + if (Ne("wrapped end"), r.decoder && !r.ended) { + var m = r.decoder.end(); + m && m.length && e.push(m); + } + e.push(null); + }), t.on("data", function(m) { + if (Ne("wrapped data"), r.decoder && (m = r.decoder.write(m)), !(r.objectMode && m == null) && !(!r.objectMode && (!m || !m.length))) { + var y = e.push(m); + y || (o = true, t.pause()); + } + }); + for (var f in t) + this[f] === undefined && typeof t[f] == "function" && (this[f] = function(y) { + return function() { + return t[y].apply(t, arguments); + }; + }(f)); + for (var p = 0;p < sh.length; p++) + t.on(sh[p], this.emit.bind(this, sh[p])); + return this._read = function(m) { + Ne("wrapped _read", m), o && (o = false, t.resume()); + }, this; + }; + typeof Symbol == "function" && (Ce.prototype[Symbol.asyncIterator] = function() { + return ah === undefined && (ah = Pc()), ah(this); + }); + Object.defineProperty(Ce.prototype, "readableHighWaterMark", { enumerable: false, get: function() { + return this._readableState.highWaterMark; + } }); + Object.defineProperty(Ce.prototype, "readableBuffer", { enumerable: false, get: function() { + return this._readableState && this._readableState.buffer; + } }); + Object.defineProperty(Ce.prototype, "readableFlowing", { enumerable: false, get: function() { + return this._readableState.flowing; + }, set: function(e) { + this._readableState && (this._readableState.flowing = e); + } }); + Ce._fromList = Zc; + Object.defineProperty(Ce.prototype, "readableLength", { enumerable: false, get: function() { + return this._readableState.length; + } }); + function Zc(t, e) { + if (e.length === 0) + return null; + var r; + return e.objectMode ? r = e.buffer.shift() : !t || t >= e.length ? (e.decoder ? r = e.buffer.join("") : e.buffer.length === 1 ? r = e.buffer.first() : r = e.buffer.concat(e.length), e.buffer.clear()) : r = e.buffer.consume(t, e.decoder), r; + } + function uh(t) { + var e = t._readableState; + Ne("endReadable", e.endEmitted), e.endEmitted || (e.ended = true, process.nextTick(KM, e, t)); + } + function KM(t, e) { + if (Ne("endReadableNT", t.endEmitted, t.length), !t.endEmitted && t.length === 0 && (t.endEmitted = true, e.readable = false, e.emit("end"), t.autoDestroy)) { + var r = e._writableState; + (!r || r.autoDestroy && r.finished) && e.destroy(); + } + } + typeof Symbol == "function" && (Ce.from = function(t, e) { + return oh === undefined && (oh = Oc()), oh(Ce, t, e); + }); + function Vc(t, e) { + for (var r = 0, o = t.length;r < o; r++) + if (t[r] === e) + return r; + return -1; + } + }); + ph = T((pI, Yc) => { + Yc.exports = di2; + var Mo2 = sn().codes, jM = Mo2.ERR_METHOD_NOT_IMPLEMENTED, ZM = Mo2.ERR_MULTIPLE_CALLBACK, VM = Mo2.ERR_TRANSFORM_ALREADY_TRANSFORMING, $M = Mo2.ERR_TRANSFORM_WITH_LENGTH_0, _o = hn(); + Ie()(di2, _o); + function GM(t, e) { + var r = this._transformState; + r.transforming = false; + var o = r.writecb; + if (o === null) + return this.emit("error", new ZM); + r.writechunk = null, r.writecb = null, e != null && this.push(e), o(t); + var f = this._readableState; + f.reading = false, (f.needReadable || f.length < f.highWaterMark) && this._read(f.highWaterMark); + } + function di2(t) { + if (!(this instanceof di2)) + return new di2(t); + _o.call(this, t), this._transformState = { afterTransform: GM.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }, this._readableState.needReadable = true, this._readableState.sync = false, t && (typeof t.transform == "function" && (this._transform = t.transform), typeof t.flush == "function" && (this._flush = t.flush)), this.on("prefinish", YM); + } + function YM() { + var t = this; + typeof this._flush == "function" && !this._readableState.destroyed ? this._flush(function(e, r) { + Gc(t, e, r); + }) : Gc(this, null, null); + } + di2.prototype.push = function(t, e) { + return this._transformState.needTransform = false, _o.prototype.push.call(this, t, e); + }; + di2.prototype._transform = function(t, e, r) { + r(new jM("_transform()")); + }; + di2.prototype._write = function(t, e, r) { + var o = this._transformState; + if (o.writecb = r, o.writechunk = t, o.writeencoding = e, !o.transforming) { + var f = this._readableState; + (o.needTransform || f.needReadable || f.length < f.highWaterMark) && this._read(f.highWaterMark); + } + }; + di2.prototype._read = function(t) { + var e = this._transformState; + e.writechunk !== null && !e.transforming ? (e.transforming = true, this._transform(e.writechunk, e.writeencoding, e.afterTransform)) : e.needTransform = true; + }; + di2.prototype._destroy = function(t, e) { + _o.prototype._destroy.call(this, t, function(r) { + e(r); + }); + }; + function Gc(t, e, r) { + if (e) + return t.emit("error", e); + if (r != null && t.push(r), t._writableState.length) + throw new $M; + if (t._transformState.transforming) + throw new VM; + return t.push(null); + } + }); + Qc = T((vI, Jc) => { + Jc.exports = ia; + var Xc = ph(); + Ie()(ia, Xc); + function ia(t) { + if (!(this instanceof ia)) + return new ia(t); + Xc.call(this, t); + } + ia.prototype._transform = function(t, e, r) { + r(null, t); + }; + }); + np = T((bI, ip) => { + var vh; + function XM(t) { + var e = false; + return function() { + e || (e = true, t.apply(undefined, arguments)); + }; + } + var rp = sn().codes, JM = rp.ERR_MISSING_ARGS, QM = rp.ERR_STREAM_DESTROYED; + function ep(t) { + if (t) + throw t; + } + function e4(t) { + return t.setHeader && typeof t.abort == "function"; + } + function t4(t, e, r, o) { + o = XM(o); + var f = false; + t.on("close", function() { + f = true; + }), vh === undefined && (vh = vo()), vh(t, { readable: e, writable: r }, function(m) { + if (m) + return o(m); + f = true, o(); + }); + var p = false; + return function(m) { + if (!f && !p) { + if (p = true, e4(t)) + return t.abort(); + if (typeof t.destroy == "function") + return t.destroy(); + o(m || new QM("pipe")); + } + }; + } + function tp(t) { + t(); + } + function r4(t, e) { + return t.pipe(e); + } + function i4(t) { + return !t.length || typeof t[t.length - 1] != "function" ? ep : t.pop(); + } + function n4() { + for (var t = arguments.length, e = new Array(t), r = 0;r < t; r++) + e[r] = arguments[r]; + var o = i4(e); + if (Array.isArray(e[0]) && (e = e[0]), e.length < 2) + throw new JM("streams"); + var f, p = e.map(function(m, y) { + var M = y < e.length - 1, x = y > 0; + return t4(m, M, x, function(S) { + f || (f = S), S && p.forEach(tp), !M && (p.forEach(tp), o(f)); + }); + }); + return e.reduce(r4); + } + ip.exports = n4; + }); + ap = T((cr, fp) => { + cr = fp.exports = th(); + cr.Stream = cr; + cr.Readable = cr; + cr.Writable = J0(); + cr.Duplex = hn(); + cr.Transform = ph(); + cr.PassThrough = Qc(); + cr.finished = vo(); + cr.pipeline = np(); + }); + bh = T((mI, sp) => { + var xo = Te().Buffer, op = ap().Transform, f4 = Ie(); + function a4(t, e) { + if (!xo.isBuffer(t) && typeof t != "string") + throw new TypeError(e + " must be a string or a buffer"); + } + function Ci(t) { + op.call(this), this._block = xo.allocUnsafe(t), this._blockSize = t, this._blockOffset = 0, this._length = [0, 0, 0, 0], this._finalized = false; + } + f4(Ci, op); + Ci.prototype._transform = function(t, e, r) { + var o = null; + try { + this.update(t, e); + } catch (f) { + o = f; + } + r(o); + }; + Ci.prototype._flush = function(t) { + var e = null; + try { + this.push(this.digest()); + } catch (r) { + e = r; + } + t(e); + }; + Ci.prototype.update = function(t, e) { + if (a4(t, "Data"), this._finalized) + throw new Error("Digest already called"); + xo.isBuffer(t) || (t = xo.from(t, e)); + for (var r = this._block, o = 0;this._blockOffset + t.length - o >= this._blockSize; ) { + for (var f = this._blockOffset;f < this._blockSize; ) + r[f++] = t[o++]; + this._update(), this._blockOffset = 0; + } + for (;o < t.length; ) + r[this._blockOffset++] = t[o++]; + for (var p = 0, m = t.length * 8;m > 0; ++p) + this._length[p] += m, m = this._length[p] / 4294967296 | 0, m > 0 && (this._length[p] -= 4294967296 * m); + return this; + }; + Ci.prototype._update = function() { + throw new Error("_update is not implemented"); + }; + Ci.prototype.digest = function(t) { + if (this._finalized) + throw new Error("Digest already called"); + this._finalized = true; + var e = this._digest(); + t !== undefined && (e = e.toString(t)), this._block.fill(0), this._blockOffset = 0; + for (var r = 0;r < 4; ++r) + this._length[r] = 0; + return e; + }; + Ci.prototype._digest = function() { + throw new Error("_digest is not implemented"); + }; + sp.exports = Ci; + }); + Ao = T((gI, up) => { + var o4 = Ie(), hp = bh(), s4 = Te().Buffer, h4 = new Array(16); + function So() { + hp.call(this, 64), this._a = 1732584193, this._b = 4023233417, this._c = 2562383102, this._d = 271733878; + } + o4(So, hp); + So.prototype._update = function() { + for (var t = h4, e = 0;e < 16; ++e) + t[e] = this._block.readInt32LE(e * 4); + var r = this._a, o = this._b, f = this._c, p = this._d; + r = jt(r, o, f, p, t[0], 3614090360, 7), p = jt(p, r, o, f, t[1], 3905402710, 12), f = jt(f, p, r, o, t[2], 606105819, 17), o = jt(o, f, p, r, t[3], 3250441966, 22), r = jt(r, o, f, p, t[4], 4118548399, 7), p = jt(p, r, o, f, t[5], 1200080426, 12), f = jt(f, p, r, o, t[6], 2821735955, 17), o = jt(o, f, p, r, t[7], 4249261313, 22), r = jt(r, o, f, p, t[8], 1770035416, 7), p = jt(p, r, o, f, t[9], 2336552879, 12), f = jt(f, p, r, o, t[10], 4294925233, 17), o = jt(o, f, p, r, t[11], 2304563134, 22), r = jt(r, o, f, p, t[12], 1804603682, 7), p = jt(p, r, o, f, t[13], 4254626195, 12), f = jt(f, p, r, o, t[14], 2792965006, 17), o = jt(o, f, p, r, t[15], 1236535329, 22), r = Zt(r, o, f, p, t[1], 4129170786, 5), p = Zt(p, r, o, f, t[6], 3225465664, 9), f = Zt(f, p, r, o, t[11], 643717713, 14), o = Zt(o, f, p, r, t[0], 3921069994, 20), r = Zt(r, o, f, p, t[5], 3593408605, 5), p = Zt(p, r, o, f, t[10], 38016083, 9), f = Zt(f, p, r, o, t[15], 3634488961, 14), o = Zt(o, f, p, r, t[4], 3889429448, 20), r = Zt(r, o, f, p, t[9], 568446438, 5), p = Zt(p, r, o, f, t[14], 3275163606, 9), f = Zt(f, p, r, o, t[3], 4107603335, 14), o = Zt(o, f, p, r, t[8], 1163531501, 20), r = Zt(r, o, f, p, t[13], 2850285829, 5), p = Zt(p, r, o, f, t[2], 4243563512, 9), f = Zt(f, p, r, o, t[7], 1735328473, 14), o = Zt(o, f, p, r, t[12], 2368359562, 20), r = Vt(r, o, f, p, t[5], 4294588738, 4), p = Vt(p, r, o, f, t[8], 2272392833, 11), f = Vt(f, p, r, o, t[11], 1839030562, 16), o = Vt(o, f, p, r, t[14], 4259657740, 23), r = Vt(r, o, f, p, t[1], 2763975236, 4), p = Vt(p, r, o, f, t[4], 1272893353, 11), f = Vt(f, p, r, o, t[7], 4139469664, 16), o = Vt(o, f, p, r, t[10], 3200236656, 23), r = Vt(r, o, f, p, t[13], 681279174, 4), p = Vt(p, r, o, f, t[0], 3936430074, 11), f = Vt(f, p, r, o, t[3], 3572445317, 16), o = Vt(o, f, p, r, t[6], 76029189, 23), r = Vt(r, o, f, p, t[9], 3654602809, 4), p = Vt(p, r, o, f, t[12], 3873151461, 11), f = Vt(f, p, r, o, t[15], 530742520, 16), o = Vt(o, f, p, r, t[2], 3299628645, 23), r = $t(r, o, f, p, t[0], 4096336452, 6), p = $t(p, r, o, f, t[7], 1126891415, 10), f = $t(f, p, r, o, t[14], 2878612391, 15), o = $t(o, f, p, r, t[5], 4237533241, 21), r = $t(r, o, f, p, t[12], 1700485571, 6), p = $t(p, r, o, f, t[3], 2399980690, 10), f = $t(f, p, r, o, t[10], 4293915773, 15), o = $t(o, f, p, r, t[1], 2240044497, 21), r = $t(r, o, f, p, t[8], 1873313359, 6), p = $t(p, r, o, f, t[15], 4264355552, 10), f = $t(f, p, r, o, t[6], 2734768916, 15), o = $t(o, f, p, r, t[13], 1309151649, 21), r = $t(r, o, f, p, t[4], 4149444226, 6), p = $t(p, r, o, f, t[11], 3174756917, 10), f = $t(f, p, r, o, t[2], 718787259, 15), o = $t(o, f, p, r, t[9], 3951481745, 21), this._a = this._a + r | 0, this._b = this._b + o | 0, this._c = this._c + f | 0, this._d = this._d + p | 0; + }; + So.prototype._digest = function() { + this._block[this._blockOffset++] = 128, this._blockOffset > 56 && (this._block.fill(0, this._blockOffset, 64), this._update(), this._blockOffset = 0), this._block.fill(0, this._blockOffset, 56), this._block.writeUInt32LE(this._length[0], 56), this._block.writeUInt32LE(this._length[1], 60), this._update(); + var t = s4.allocUnsafe(16); + return t.writeInt32LE(this._a, 0), t.writeInt32LE(this._b, 4), t.writeInt32LE(this._c, 8), t.writeInt32LE(this._d, 12), t; + }; + function Eo(t, e) { + return t << e | t >>> 32 - e; + } + function jt(t, e, r, o, f, p, m) { + return Eo(t + (e & r | ~e & o) + f + p | 0, m) + e | 0; + } + function Zt(t, e, r, o, f, p, m) { + return Eo(t + (e & o | r & ~o) + f + p | 0, m) + e | 0; + } + function Vt(t, e, r, o, f, p, m) { + return Eo(t + (e ^ r ^ o) + f + p | 0, m) + e | 0; + } + function $t(t, e, r, o, f, p, m) { + return Eo(t + (r ^ (e | ~o)) + f + p | 0, m) + e | 0; + } + up.exports = So; + }); + Bo = T((yI, mp) => { + var mh = Ut2().Buffer, u4 = Ie(), bp = bh(), l4 = new Array(16), na = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13], fa = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11], aa = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6], oa = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11], sa = [0, 1518500249, 1859775393, 2400959708, 2840853838], ha = [1352829926, 1548603684, 1836072691, 2053994217, 0]; + function Ro() { + bp.call(this, 64), this._a = 1732584193, this._b = 4023233417, this._c = 2562383102, this._d = 271733878, this._e = 3285377520; + } + u4(Ro, bp); + Ro.prototype._update = function() { + for (var t = l4, e = 0;e < 16; ++e) + t[e] = this._block.readInt32LE(e * 4); + for (var r = this._a | 0, o = this._b | 0, f = this._c | 0, p = this._d | 0, m = this._e | 0, y = this._a | 0, M = this._b | 0, x = this._c | 0, S = this._d | 0, E2 = this._e | 0, B = 0;B < 80; B += 1) { + var q, L; + B < 16 ? (q = lp(r, o, f, p, m, t[na[B]], sa[0], aa[B]), L = vp(y, M, x, S, E2, t[fa[B]], ha[0], oa[B])) : B < 32 ? (q = dp(r, o, f, p, m, t[na[B]], sa[1], aa[B]), L = pp(y, M, x, S, E2, t[fa[B]], ha[1], oa[B])) : B < 48 ? (q = cp(r, o, f, p, m, t[na[B]], sa[2], aa[B]), L = cp(y, M, x, S, E2, t[fa[B]], ha[2], oa[B])) : B < 64 ? (q = pp(r, o, f, p, m, t[na[B]], sa[3], aa[B]), L = dp(y, M, x, S, E2, t[fa[B]], ha[3], oa[B])) : (q = vp(r, o, f, p, m, t[na[B]], sa[4], aa[B]), L = lp(y, M, x, S, E2, t[fa[B]], ha[4], oa[B])), r = m, m = p, p = cn(f, 10), f = o, o = q, y = E2, E2 = S, S = cn(x, 10), x = M, M = L; + } + var ge = this._b + f + S | 0; + this._b = this._c + p + E2 | 0, this._c = this._d + m + y | 0, this._d = this._e + r + M | 0, this._e = this._a + o + x | 0, this._a = ge; + }; + Ro.prototype._digest = function() { + this._block[this._blockOffset++] = 128, this._blockOffset > 56 && (this._block.fill(0, this._blockOffset, 64), this._update(), this._blockOffset = 0), this._block.fill(0, this._blockOffset, 56), this._block.writeUInt32LE(this._length[0], 56), this._block.writeUInt32LE(this._length[1], 60), this._update(); + var t = mh.alloc ? mh.alloc(20) : new mh(20); + return t.writeInt32LE(this._a, 0), t.writeInt32LE(this._b, 4), t.writeInt32LE(this._c, 8), t.writeInt32LE(this._d, 12), t.writeInt32LE(this._e, 16), t; + }; + function cn(t, e) { + return t << e | t >>> 32 - e; + } + function lp(t, e, r, o, f, p, m, y) { + return cn(t + (e ^ r ^ o) + p + m | 0, y) + f | 0; + } + function dp(t, e, r, o, f, p, m, y) { + return cn(t + (e & r | ~e & o) + p + m | 0, y) + f | 0; + } + function cp(t, e, r, o, f, p, m, y) { + return cn(t + ((e | ~r) ^ o) + p + m | 0, y) + f | 0; + } + function pp(t, e, r, o, f, p, m, y) { + return cn(t + (e & o | r & ~o) + p + m | 0, y) + f | 0; + } + function vp(t, e, r, o, f, p, m, y) { + return cn(t + (e ^ (r | ~o)) + p + m | 0, y) + f | 0; + } + mp.exports = Ro; + }); + pn = T((wI, yp) => { + var gp = Te().Buffer; + function qo(t, e) { + this._block = gp.alloc(t), this._finalSize = e, this._blockSize = t, this._len = 0; + } + qo.prototype.update = function(t, e) { + typeof t == "string" && (e = e || "utf8", t = gp.from(t, e)); + for (var r = this._block, o = this._blockSize, f = t.length, p = this._len, m = 0;m < f; ) { + for (var y = p % o, M = Math.min(f - m, o - y), x = 0;x < M; x++) + r[y + x] = t[m + x]; + p += M, m += M, p % o === 0 && this._update(r); + } + return this._len += f, this; + }; + qo.prototype.digest = function(t) { + var e = this._len % this._blockSize; + this._block[e] = 128, this._block.fill(0, e + 1), e >= this._finalSize && (this._update(this._block), this._block.fill(0)); + var r = this._len * 8; + if (r <= 4294967295) + this._block.writeUInt32BE(r, this._blockSize - 4); + else { + var o = (r & 4294967295) >>> 0, f = (r - o) / 4294967296; + this._block.writeUInt32BE(f, this._blockSize - 8), this._block.writeUInt32BE(o, this._blockSize - 4); + } + this._update(this._block); + var p = this._hash(); + return t ? p.toString(t) : p; + }; + qo.prototype._update = function() { + throw new Error("_update must be implemented by subclass"); + }; + yp.exports = qo; + }); + _p = T((MI, Mp) => { + var d4 = Ie(), wp = pn(), c4 = Te().Buffer, p4 = [1518500249, 1859775393, -1894007588, -899497514], v4 = new Array(80); + function ua() { + this.init(), this._w = v4, wp.call(this, 64, 56); + } + d4(ua, wp); + ua.prototype.init = function() { + return this._a = 1732584193, this._b = 4023233417, this._c = 2562383102, this._d = 271733878, this._e = 3285377520, this; + }; + function b4(t) { + return t << 5 | t >>> 27; + } + function m4(t) { + return t << 30 | t >>> 2; + } + function g4(t, e, r, o) { + return t === 0 ? e & r | ~e & o : t === 2 ? e & r | e & o | r & o : e ^ r ^ o; + } + ua.prototype._update = function(t) { + for (var e = this._w, r = this._a | 0, o = this._b | 0, f = this._c | 0, p = this._d | 0, m = this._e | 0, y = 0;y < 16; ++y) + e[y] = t.readInt32BE(y * 4); + for (;y < 80; ++y) + e[y] = e[y - 3] ^ e[y - 8] ^ e[y - 14] ^ e[y - 16]; + for (var M = 0;M < 80; ++M) { + var x = ~~(M / 20), S = b4(r) + g4(x, o, f, p) + m + e[M] + p4[x] | 0; + m = p, p = f, f = m4(o), o = r, r = S; + } + this._a = r + this._a | 0, this._b = o + this._b | 0, this._c = f + this._c | 0, this._d = p + this._d | 0, this._e = m + this._e | 0; + }; + ua.prototype._hash = function() { + var t = c4.allocUnsafe(20); + return t.writeInt32BE(this._a | 0, 0), t.writeInt32BE(this._b | 0, 4), t.writeInt32BE(this._c | 0, 8), t.writeInt32BE(this._d | 0, 12), t.writeInt32BE(this._e | 0, 16), t; + }; + Mp.exports = ua; + }); + Ep = T((_I, Sp) => { + var y4 = Ie(), xp = pn(), w4 = Te().Buffer, M4 = [1518500249, 1859775393, -1894007588, -899497514], _42 = new Array(80); + function la() { + this.init(), this._w = _42, xp.call(this, 64, 56); + } + y4(la, xp); + la.prototype.init = function() { + return this._a = 1732584193, this._b = 4023233417, this._c = 2562383102, this._d = 271733878, this._e = 3285377520, this; + }; + function x4(t) { + return t << 1 | t >>> 31; + } + function S4(t) { + return t << 5 | t >>> 27; + } + function E4(t) { + return t << 30 | t >>> 2; + } + function A4(t, e, r, o) { + return t === 0 ? e & r | ~e & o : t === 2 ? e & r | e & o | r & o : e ^ r ^ o; + } + la.prototype._update = function(t) { + for (var e = this._w, r = this._a | 0, o = this._b | 0, f = this._c | 0, p = this._d | 0, m = this._e | 0, y = 0;y < 16; ++y) + e[y] = t.readInt32BE(y * 4); + for (;y < 80; ++y) + e[y] = x4(e[y - 3] ^ e[y - 8] ^ e[y - 14] ^ e[y - 16]); + for (var M = 0;M < 80; ++M) { + var x = ~~(M / 20), S = S4(r) + A4(x, o, f, p) + m + e[M] + M4[x] | 0; + m = p, p = f, f = E4(o), o = r, r = S; + } + this._a = r + this._a | 0, this._b = o + this._b | 0, this._c = f + this._c | 0, this._d = p + this._d | 0, this._e = m + this._e | 0; + }; + la.prototype._hash = function() { + var t = w4.allocUnsafe(20); + return t.writeInt32BE(this._a | 0, 0), t.writeInt32BE(this._b | 0, 4), t.writeInt32BE(this._c | 0, 8), t.writeInt32BE(this._d | 0, 12), t.writeInt32BE(this._e | 0, 16), t; + }; + Sp.exports = la; + }); + gh = T((xI, Rp) => { + var R4 = Ie(), Ap = pn(), B4 = Te().Buffer, q4 = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298], I4 = new Array(64); + function da() { + this.init(), this._w = I4, Ap.call(this, 64, 56); + } + R4(da, Ap); + da.prototype.init = function() { + return this._a = 1779033703, this._b = 3144134277, this._c = 1013904242, this._d = 2773480762, this._e = 1359893119, this._f = 2600822924, this._g = 528734635, this._h = 1541459225, this; + }; + function T4(t, e, r) { + return r ^ t & (e ^ r); + } + function k4(t, e, r) { + return t & e | r & (t | e); + } + function L4(t) { + return (t >>> 2 | t << 30) ^ (t >>> 13 | t << 19) ^ (t >>> 22 | t << 10); + } + function N4(t) { + return (t >>> 6 | t << 26) ^ (t >>> 11 | t << 21) ^ (t >>> 25 | t << 7); + } + function D4(t) { + return (t >>> 7 | t << 25) ^ (t >>> 18 | t << 14) ^ t >>> 3; + } + function P4(t) { + return (t >>> 17 | t << 15) ^ (t >>> 19 | t << 13) ^ t >>> 10; + } + da.prototype._update = function(t) { + for (var e = this._w, r = this._a | 0, o = this._b | 0, f = this._c | 0, p = this._d | 0, m = this._e | 0, y = this._f | 0, M = this._g | 0, x = this._h | 0, S = 0;S < 16; ++S) + e[S] = t.readInt32BE(S * 4); + for (;S < 64; ++S) + e[S] = P4(e[S - 2]) + e[S - 7] + D4(e[S - 15]) + e[S - 16] | 0; + for (var E2 = 0;E2 < 64; ++E2) { + var B = x + N4(m) + T4(m, y, M) + q4[E2] + e[E2] | 0, q = L4(r) + k4(r, o, f) | 0; + x = M, M = y, y = m, m = p + B | 0, p = f, f = o, o = r, r = B + q | 0; + } + this._a = r + this._a | 0, this._b = o + this._b | 0, this._c = f + this._c | 0, this._d = p + this._d | 0, this._e = m + this._e | 0, this._f = y + this._f | 0, this._g = M + this._g | 0, this._h = x + this._h | 0; + }; + da.prototype._hash = function() { + var t = B4.allocUnsafe(32); + return t.writeInt32BE(this._a, 0), t.writeInt32BE(this._b, 4), t.writeInt32BE(this._c, 8), t.writeInt32BE(this._d, 12), t.writeInt32BE(this._e, 16), t.writeInt32BE(this._f, 20), t.writeInt32BE(this._g, 24), t.writeInt32BE(this._h, 28), t; + }; + Rp.exports = da; + }); + qp = T((SI, Bp) => { + var C4 = Ie(), O4 = gh(), F4 = pn(), U4 = Te().Buffer, z4 = new Array(64); + function Io() { + this.init(), this._w = z4, F4.call(this, 64, 56); + } + C4(Io, O4); + Io.prototype.init = function() { + return this._a = 3238371032, this._b = 914150663, this._c = 812702999, this._d = 4144912697, this._e = 4290775857, this._f = 1750603025, this._g = 1694076839, this._h = 3204075428, this; + }; + Io.prototype._hash = function() { + var t = U4.allocUnsafe(28); + return t.writeInt32BE(this._a, 0), t.writeInt32BE(this._b, 4), t.writeInt32BE(this._c, 8), t.writeInt32BE(this._d, 12), t.writeInt32BE(this._e, 16), t.writeInt32BE(this._f, 20), t.writeInt32BE(this._g, 24), t; + }; + Bp.exports = Io; + }); + yh = T((EI, Pp) => { + var H4 = Ie(), Dp = pn(), W4 = Te().Buffer, Ip = [1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591], K4 = new Array(160); + function ca() { + this.init(), this._w = K4, Dp.call(this, 128, 112); + } + H4(ca, Dp); + ca.prototype.init = function() { + return this._ah = 1779033703, this._bh = 3144134277, this._ch = 1013904242, this._dh = 2773480762, this._eh = 1359893119, this._fh = 2600822924, this._gh = 528734635, this._hh = 1541459225, this._al = 4089235720, this._bl = 2227873595, this._cl = 4271175723, this._dl = 1595750129, this._el = 2917565137, this._fl = 725511199, this._gl = 4215389547, this._hl = 327033209, this; + }; + function Tp(t, e, r) { + return r ^ t & (e ^ r); + } + function kp(t, e, r) { + return t & e | r & (t | e); + } + function Lp(t, e) { + return (t >>> 28 | e << 4) ^ (e >>> 2 | t << 30) ^ (e >>> 7 | t << 25); + } + function Np(t, e) { + return (t >>> 14 | e << 18) ^ (t >>> 18 | e << 14) ^ (e >>> 9 | t << 23); + } + function j4(t, e) { + return (t >>> 1 | e << 31) ^ (t >>> 8 | e << 24) ^ t >>> 7; + } + function Z4(t, e) { + return (t >>> 1 | e << 31) ^ (t >>> 8 | e << 24) ^ (t >>> 7 | e << 25); + } + function V4(t, e) { + return (t >>> 19 | e << 13) ^ (e >>> 29 | t << 3) ^ t >>> 6; + } + function $4(t, e) { + return (t >>> 19 | e << 13) ^ (e >>> 29 | t << 3) ^ (t >>> 6 | e << 26); + } + function Pt(t, e) { + return t >>> 0 < e >>> 0 ? 1 : 0; + } + ca.prototype._update = function(t) { + for (var e = this._w, r = this._ah | 0, o = this._bh | 0, f = this._ch | 0, p = this._dh | 0, m = this._eh | 0, y = this._fh | 0, M = this._gh | 0, x = this._hh | 0, S = this._al | 0, E2 = this._bl | 0, B = this._cl | 0, q = this._dl | 0, L = this._el | 0, ge = this._fl | 0, _e = this._gl | 0, N = this._hl | 0, we = 0;we < 32; we += 2) + e[we] = t.readInt32BE(we * 4), e[we + 1] = t.readInt32BE(we * 4 + 4); + for (;we < 160; we += 2) { + var ye = e[we - 30], xe = e[we - 15 * 2 + 1], Re = j4(ye, xe), Ee = Z4(xe, ye); + ye = e[we - 2 * 2], xe = e[we - 2 * 2 + 1]; + var Ae = V4(ye, xe), P = $4(xe, ye), Se2 = e[we - 7 * 2], v = e[we - 7 * 2 + 1], i = e[we - 16 * 2], a = e[we - 16 * 2 + 1], h = Ee + v | 0, s = Re + Se2 + Pt(h, Ee) | 0; + h = h + P | 0, s = s + Ae + Pt(h, P) | 0, h = h + a | 0, s = s + i + Pt(h, a) | 0, e[we] = s, e[we + 1] = h; + } + for (var u = 0;u < 160; u += 2) { + s = e[u], h = e[u + 1]; + var c = kp(r, o, f), b = kp(S, E2, B), l = Lp(r, S), n = Lp(S, r), d = Np(m, L), w = Np(L, m), g = Ip[u], _9 = Ip[u + 1], A = Tp(m, y, M), R = Tp(L, ge, _e), I2 = N + w | 0, Me = x + d + Pt(I2, N) | 0; + I2 = I2 + R | 0, Me = Me + A + Pt(I2, R) | 0, I2 = I2 + _9 | 0, Me = Me + g + Pt(I2, _9) | 0, I2 = I2 + h | 0, Me = Me + s + Pt(I2, h) | 0; + var k2 = n + b | 0, D = l + c + Pt(k2, n) | 0; + x = M, N = _e, M = y, _e = ge, y = m, ge = L, L = q + I2 | 0, m = p + Me + Pt(L, q) | 0, p = f, q = B, f = o, B = E2, o = r, E2 = S, S = I2 + k2 | 0, r = Me + D + Pt(S, I2) | 0; + } + this._al = this._al + S | 0, this._bl = this._bl + E2 | 0, this._cl = this._cl + B | 0, this._dl = this._dl + q | 0, this._el = this._el + L | 0, this._fl = this._fl + ge | 0, this._gl = this._gl + _e | 0, this._hl = this._hl + N | 0, this._ah = this._ah + r + Pt(this._al, S) | 0, this._bh = this._bh + o + Pt(this._bl, E2) | 0, this._ch = this._ch + f + Pt(this._cl, B) | 0, this._dh = this._dh + p + Pt(this._dl, q) | 0, this._eh = this._eh + m + Pt(this._el, L) | 0, this._fh = this._fh + y + Pt(this._fl, ge) | 0, this._gh = this._gh + M + Pt(this._gl, _e) | 0, this._hh = this._hh + x + Pt(this._hl, N) | 0; + }; + ca.prototype._hash = function() { + var t = W4.allocUnsafe(64); + function e(r, o, f) { + t.writeInt32BE(r, f), t.writeInt32BE(o, f + 4); + } + return e(this._ah, this._al, 0), e(this._bh, this._bl, 8), e(this._ch, this._cl, 16), e(this._dh, this._dl, 24), e(this._eh, this._el, 32), e(this._fh, this._fl, 40), e(this._gh, this._gl, 48), e(this._hh, this._hl, 56), t; + }; + Pp.exports = ca; + }); + Op = T((AI, Cp) => { + var G4 = Ie(), Y4 = yh(), X4 = pn(), J4 = Te().Buffer, Q4 = new Array(160); + function To() { + this.init(), this._w = Q4, X4.call(this, 128, 112); + } + G4(To, Y4); + To.prototype.init = function() { + return this._ah = 3418070365, this._bh = 1654270250, this._ch = 2438529370, this._dh = 355462360, this._eh = 1731405415, this._fh = 2394180231, this._gh = 3675008525, this._hh = 1203062813, this._al = 3238371032, this._bl = 914150663, this._cl = 812702999, this._dl = 4144912697, this._el = 4290775857, this._fl = 1750603025, this._gl = 1694076839, this._hl = 3204075428, this; + }; + To.prototype._hash = function() { + var t = J4.allocUnsafe(48); + function e(r, o, f) { + t.writeInt32BE(r, f), t.writeInt32BE(o, f + 4); + } + return e(this._ah, this._al, 0), e(this._bh, this._bl, 8), e(this._ch, this._cl, 16), e(this._dh, this._dl, 24), e(this._eh, this._el, 32), e(this._fh, this._fl, 40), t; + }; + Cp.exports = To; + }); + ko = T((ci, Fp) => { + var ci = Fp.exports = function(e) { + e = e.toLowerCase(); + var r = ci[e]; + if (!r) + throw new Error(e + " is not supported (we accept pull requests)"); + return new r; + }; + ci.sha = _p(); + ci.sha1 = Ep(); + ci.sha224 = qp(); + ci.sha256 = gh(); + ci.sha384 = Op(); + ci.sha512 = yh(); + }); + Tt2 = T((RI, Up) => { + Up.exports = { ArrayIsArray(t) { + return Array.isArray(t); + }, ArrayPrototypeIncludes(t, e) { + return t.includes(e); + }, ArrayPrototypeIndexOf(t, e) { + return t.indexOf(e); + }, ArrayPrototypeJoin(t, e) { + return t.join(e); + }, ArrayPrototypeMap(t, e) { + return t.map(e); + }, ArrayPrototypePop(t, e) { + return t.pop(e); + }, ArrayPrototypePush(t, e) { + return t.push(e); + }, ArrayPrototypeSlice(t, e, r) { + return t.slice(e, r); + }, Error, FunctionPrototypeCall(t, e, ...r) { + return t.call(e, ...r); + }, FunctionPrototypeSymbolHasInstance(t, e) { + return Function.prototype[Symbol.hasInstance].call(t, e); + }, MathFloor: Math.floor, Number, NumberIsInteger: Number.isInteger, NumberIsNaN: Number.isNaN, NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, NumberParseInt: Number.parseInt, ObjectDefineProperties(t, e) { + return Object.defineProperties(t, e); + }, ObjectDefineProperty(t, e, r) { + return Object.defineProperty(t, e, r); + }, ObjectGetOwnPropertyDescriptor(t, e) { + return Object.getOwnPropertyDescriptor(t, e); + }, ObjectKeys(t) { + return Object.keys(t); + }, ObjectSetPrototypeOf(t, e) { + return Object.setPrototypeOf(t, e); + }, Promise, PromisePrototypeCatch(t, e) { + return t.catch(e); + }, PromisePrototypeThen(t, e, r) { + return t.then(e, r); + }, PromiseReject(t) { + return Promise.reject(t); + }, ReflectApply: Reflect.apply, RegExpPrototypeTest(t, e) { + return t.test(e); + }, SafeSet: Set, String, StringPrototypeSlice(t, e, r) { + return t.slice(e, r); + }, StringPrototypeToLowerCase(t) { + return t.toLowerCase(); + }, StringPrototypeToUpperCase(t) { + return t.toUpperCase(); + }, StringPrototypeTrim(t) { + return t.trim(); + }, Symbol, SymbolAsyncIterator: Symbol.asyncIterator, SymbolHasInstance: Symbol.hasInstance, SymbolIterator: Symbol.iterator, TypedArrayPrototypeSet(t, e, r) { + return t.set(e, r); + }, Uint8Array }; + }); + Gr = T((BI, Mh) => { + var e_ = Ut2(), t_ = Object.getPrototypeOf(async function() { + }).constructor, zp = globalThis.Blob || e_.Blob, r_ = typeof zp < "u" ? function(e) { + return e instanceof zp; + } : function(e) { + return false; + }, wh = class extends Error { + constructor(e) { + if (!Array.isArray(e)) + throw new TypeError(`Expected input to be an Array, got ${typeof e}`); + let r = ""; + for (let o = 0;o < e.length; o++) + r += ` ${e[o].stack} +`; + super(r), this.name = "AggregateError", this.errors = e; + } + }; + Mh.exports = { AggregateError: wh, kEmptyObject: Object.freeze({}), once(t) { + let e = false; + return function(...r) { + e || (e = true, t.apply(this, r)); + }; + }, createDeferredPromise: function() { + let t, e; + return { promise: new Promise((o, f) => { + t = o, e = f; + }), resolve: t, reject: e }; + }, promisify(t) { + return new Promise((e, r) => { + t((o, ...f) => o ? r(o) : e(...f)); + }); + }, debuglog() { + return function() { + }; + }, format(t, ...e) { + return t.replace(/%([sdifj])/g, function(...[r, o]) { + let f = e.shift(); + return o === "f" ? f.toFixed(6) : o === "j" ? JSON.stringify(f) : o === "s" && typeof f == "object" ? `${f.constructor !== Object ? f.constructor.name : ""} {}`.trim() : f.toString(); + }); + }, inspect(t) { + switch (typeof t) { + case "string": + if (t.includes("'")) + if (t.includes('"')) { + if (!t.includes("`") && !t.includes("${")) + return `\`${t}\``; + } else + return `"${t}"`; + return `'${t}'`; + case "number": + return isNaN(t) ? "NaN" : Object.is(t, -0) ? String(t) : t; + case "bigint": + return `${String(t)}n`; + case "boolean": + case "undefined": + return String(t); + case "object": + return "{}"; + } + }, types: { isAsyncFunction(t) { + return t instanceof t_; + }, isArrayBufferView(t) { + return ArrayBuffer.isView(t); + } }, isBlob: r_ }; + Mh.exports.promisify.custom = Symbol.for("nodejs.util.promisify.custom"); + }); + No = T((qI, Lo) => { + var { AbortController: Hp, AbortSignal: i_ } = typeof self < "u" ? self : typeof window < "u" ? window : undefined; + Lo.exports = Hp; + Lo.exports.AbortSignal = i_; + Lo.exports.default = Hp; + }); + Jt = T((II, jp) => { + var { format: n_, inspect: Do, AggregateError: f_ } = Gr(), a_ = globalThis.AggregateError || f_, o_ = Symbol("kIsNodeError"), s_ = ["string", "function", "number", "object", "Function", "Object", "boolean", "bigint", "symbol"], h_ = /^([A-Z][a-z0-9]*)+$/, u_ = "__node_internal_", Po = {}; + function vn(t, e) { + if (!t) + throw new Po.ERR_INTERNAL_ASSERTION(e); + } + function Wp(t) { + let e = "", r = t.length, o = t[0] === "-" ? 1 : 0; + for (;r >= o + 4; r -= 3) + e = `_${t.slice(r - 3, r)}${e}`; + return `${t.slice(0, r)}${e}`; + } + function l_(t, e, r) { + if (typeof e == "function") + return vn(e.length <= r.length, `Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${e.length}).`), e(...r); + let o = (e.match(/%[dfijoOs]/g) || []).length; + return vn(o === r.length, `Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${o}).`), r.length === 0 ? e : n_(e, ...r); + } + function zt(t, e, r) { + r || (r = Error); + + class o extends r { + constructor(...p) { + super(l_(t, e, p)); + } + toString() { + return `${this.name} [${t}]: ${this.message}`; + } + } + Object.defineProperties(o.prototype, { name: { value: r.name, writable: true, enumerable: false, configurable: true }, toString: { value() { + return `${this.name} [${t}]: ${this.message}`; + }, writable: true, enumerable: false, configurable: true } }), o.prototype.code = t, o.prototype[o_] = true, Po[t] = o; + } + function Kp(t) { + let e = u_ + t.name; + return Object.defineProperty(t, "name", { value: e }), t; + } + function d_(t, e) { + if (t && e && t !== e) { + if (Array.isArray(e.errors)) + return e.errors.push(t), e; + let r = new a_([e, t], e.message); + return r.code = e.code, r; + } + return t || e; + } + var _h = class extends Error { + constructor(e = "The operation was aborted", r = undefined) { + if (r !== undefined && typeof r != "object") + throw new Po.ERR_INVALID_ARG_TYPE("options", "Object", r); + super(e, r), this.code = "ABORT_ERR", this.name = "AbortError"; + } + }; + zt("ERR_ASSERTION", "%s", Error); + zt("ERR_INVALID_ARG_TYPE", (t, e, r) => { + vn(typeof t == "string", "'name' must be a string"), Array.isArray(e) || (e = [e]); + let o = "The "; + t.endsWith(" argument") ? o += `${t} ` : o += `"${t}" ${t.includes(".") ? "property" : "argument"} `, o += "must be "; + let f = [], p = [], m = []; + for (let M of e) + vn(typeof M == "string", "All expected entries have to be of type string"), s_.includes(M) ? f.push(M.toLowerCase()) : h_.test(M) ? p.push(M) : (vn(M !== "object", 'The value "object" should be written as "Object"'), m.push(M)); + if (p.length > 0) { + let M = f.indexOf("object"); + M !== -1 && (f.splice(f, M, 1), p.push("Object")); + } + if (f.length > 0) { + switch (f.length) { + case 1: + o += `of type ${f[0]}`; + break; + case 2: + o += `one of type ${f[0]} or ${f[1]}`; + break; + default: { + let M = f.pop(); + o += `one of type ${f.join(", ")}, or ${M}`; + } + } + (p.length > 0 || m.length > 0) && (o += " or "); + } + if (p.length > 0) { + switch (p.length) { + case 1: + o += `an instance of ${p[0]}`; + break; + case 2: + o += `an instance of ${p[0]} or ${p[1]}`; + break; + default: { + let M = p.pop(); + o += `an instance of ${p.join(", ")}, or ${M}`; + } + } + m.length > 0 && (o += " or "); + } + switch (m.length) { + case 0: + break; + case 1: + m[0].toLowerCase() !== m[0] && (o += "an "), o += `${m[0]}`; + break; + case 2: + o += `one of ${m[0]} or ${m[1]}`; + break; + default: { + let M = m.pop(); + o += `one of ${m.join(", ")}, or ${M}`; + } + } + if (r == null) + o += `. Received ${r}`; + else if (typeof r == "function" && r.name) + o += `. Received function ${r.name}`; + else if (typeof r == "object") { + var y; + (y = r.constructor) !== null && y !== undefined && y.name ? o += `. Received an instance of ${r.constructor.name}` : o += `. Received ${Do(r, { depth: -1 })}`; + } else { + let M = Do(r, { colors: false }); + M.length > 25 && (M = `${M.slice(0, 25)}...`), o += `. Received type ${typeof r} (${M})`; + } + return o; + }, TypeError); + zt("ERR_INVALID_ARG_VALUE", (t, e, r = "is invalid") => { + let o = Do(e); + return o.length > 128 && (o = o.slice(0, 128) + "..."), `The ${t.includes(".") ? "property" : "argument"} '${t}' ${r}. Received ${o}`; + }, TypeError); + zt("ERR_INVALID_RETURN_VALUE", (t, e, r) => { + var o; + let f = r != null && (o = r.constructor) !== null && o !== undefined && o.name ? `instance of ${r.constructor.name}` : `type ${typeof r}`; + return `Expected ${t} to be returned from the "${e}" function but got ${f}.`; + }, TypeError); + zt("ERR_MISSING_ARGS", (...t) => { + vn(t.length > 0, "At least one arg needs to be specified"); + let e, r = t.length; + switch (t = (Array.isArray(t) ? t : [t]).map((o) => `"${o}"`).join(" or "), r) { + case 1: + e += `The ${t[0]} argument`; + break; + case 2: + e += `The ${t[0]} and ${t[1]} arguments`; + break; + default: + { + let o = t.pop(); + e += `The ${t.join(", ")}, and ${o} arguments`; + } + break; + } + return `${e} must be specified`; + }, TypeError); + zt("ERR_OUT_OF_RANGE", (t, e, r) => { + vn(e, 'Missing "range" argument'); + let o; + return Number.isInteger(r) && Math.abs(r) > 2 ** 32 ? o = Wp(String(r)) : typeof r == "bigint" ? (o = String(r), (r > 2n ** 32n || r < -(2n ** 32n)) && (o = Wp(o)), o += "n") : o = Do(r), `The value of "${t}" is out of range. It must be ${e}. Received ${o}`; + }, RangeError); + zt("ERR_MULTIPLE_CALLBACK", "Callback called multiple times", Error); + zt("ERR_METHOD_NOT_IMPLEMENTED", "The %s method is not implemented", Error); + zt("ERR_STREAM_ALREADY_FINISHED", "Cannot call %s after a stream was finished", Error); + zt("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable", Error); + zt("ERR_STREAM_DESTROYED", "Cannot call %s after a stream was destroyed", Error); + zt("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + zt("ERR_STREAM_PREMATURE_CLOSE", "Premature close", Error); + zt("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF", Error); + zt("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event", Error); + zt("ERR_STREAM_WRITE_AFTER_END", "write after end", Error); + zt("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s", TypeError); + jp.exports = { AbortError: _h, aggregateTwoErrors: Kp(d_), hideStackFrames: Kp, codes: Po }; + }); + pa = T((TI, Qp) => { + var { ArrayIsArray: $p, ArrayPrototypeIncludes: Gp, ArrayPrototypeJoin: Yp, ArrayPrototypeMap: c_, NumberIsInteger: Sh, NumberIsNaN: p_, NumberMAX_SAFE_INTEGER: v_, NumberMIN_SAFE_INTEGER: b_, NumberParseInt: m_, ObjectPrototypeHasOwnProperty: g_, RegExpPrototypeExec: y_, String: w_, StringPrototypeToUpperCase: M_, StringPrototypeTrim: __2 } = Tt2(), { hideStackFrames: Ir, codes: { ERR_SOCKET_BAD_PORT: x_, ERR_INVALID_ARG_TYPE: tr, ERR_INVALID_ARG_VALUE: Co, ERR_OUT_OF_RANGE: bn, ERR_UNKNOWN_SIGNAL: Zp } } = Jt(), { normalizeEncoding: S_ } = Gr(), { isAsyncFunction: E_, isArrayBufferView: A_ } = Gr().types, Vp = {}; + function R_(t) { + return t === (t | 0); + } + function B_(t) { + return t === t >>> 0; + } + var q_ = /^[0-7]+$/, I_ = "must be a 32-bit unsigned integer or an octal string"; + function T_(t, e, r) { + if (typeof t > "u" && (t = r), typeof t == "string") { + if (y_(q_, t) === null) + throw new Co(e, t, I_); + t = m_(t, 8); + } + return Xp(t, e), t; + } + var k_ = Ir((t, e, r = b_, o = v_) => { + if (typeof t != "number") + throw new tr(e, "number", t); + if (!Sh(t)) + throw new bn(e, "an integer", t); + if (t < r || t > o) + throw new bn(e, `>= ${r} && <= ${o}`, t); + }), L_ = Ir((t, e, r = -2147483648, o = 2147483647) => { + if (typeof t != "number") + throw new tr(e, "number", t); + if (!Sh(t)) + throw new bn(e, "an integer", t); + if (t < r || t > o) + throw new bn(e, `>= ${r} && <= ${o}`, t); + }), Xp = Ir((t, e, r = false) => { + if (typeof t != "number") + throw new tr(e, "number", t); + if (!Sh(t)) + throw new bn(e, "an integer", t); + let o = r ? 1 : 0, f = 4294967295; + if (t < o || t > f) + throw new bn(e, `>= ${o} && <= ${f}`, t); + }); + function Jp(t, e) { + if (typeof t != "string") + throw new tr(e, "string", t); + } + function N_(t, e, r = undefined, o) { + if (typeof t != "number") + throw new tr(e, "number", t); + if (r != null && t < r || o != null && t > o || (r != null || o != null) && p_(t)) + throw new bn(e, `${r != null ? `>= ${r}` : ""}${r != null && o != null ? " && " : ""}${o != null ? `<= ${o}` : ""}`, t); + } + var D_ = Ir((t, e, r) => { + if (!Gp(r, t)) { + let o = Yp(c_(r, (p) => typeof p == "string" ? `'${p}'` : w_(p)), ", "), f = "must be one of: " + o; + throw new Co(e, t, f); + } + }); + function P_(t, e) { + if (typeof t != "boolean") + throw new tr(e, "boolean", t); + } + function xh(t, e, r) { + return t == null || !g_(t, e) ? r : t[e]; + } + var C_ = Ir((t, e, r = null) => { + let o = xh(r, "allowArray", false), f = xh(r, "allowFunction", false); + if (!xh(r, "nullable", false) && t === null || !o && $p(t) || typeof t != "object" && (!f || typeof t != "function")) + throw new tr(e, "Object", t); + }), O_ = Ir((t, e, r = 0) => { + if (!$p(t)) + throw new tr(e, "Array", t); + if (t.length < r) { + let o = `must be longer than ${r}`; + throw new Co(e, t, o); + } + }); + function F_(t, e = "signal") { + if (Jp(t, e), Vp[t] === undefined) + throw Vp[M_(t)] !== undefined ? new Zp(t + " (signals must use all capital letters)") : new Zp(t); + } + var U_ = Ir((t, e = "buffer") => { + if (!A_(t)) + throw new tr(e, ["Buffer", "TypedArray", "DataView"], t); + }); + function z_(t, e) { + let r = S_(e), o = t.length; + if (r === "hex" && o % 2 !== 0) + throw new Co("encoding", e, `is invalid for data of length ${o}`); + } + function H_(t, e = "Port", r = true) { + if (typeof t != "number" && typeof t != "string" || typeof t == "string" && __2(t).length === 0 || +t !== +t >>> 0 || t > 65535 || t === 0 && !r) + throw new x_(e, t, r); + return t | 0; + } + var W_ = Ir((t, e) => { + if (t !== undefined && (t === null || typeof t != "object" || !("aborted" in t))) + throw new tr(e, "AbortSignal", t); + }), K_ = Ir((t, e) => { + if (typeof t != "function") + throw new tr(e, "Function", t); + }), j_ = Ir((t, e) => { + if (typeof t != "function" || E_(t)) + throw new tr(e, "Function", t); + }), Z_ = Ir((t, e) => { + if (t !== undefined) + throw new tr(e, "undefined", t); + }); + function V_(t, e, r) { + if (!Gp(r, t)) + throw new tr(e, `('${Yp(r, "|")}')`, t); + } + Qp.exports = { isInt32: R_, isUint32: B_, parseFileMode: T_, validateArray: O_, validateBoolean: P_, validateBuffer: U_, validateEncoding: z_, validateFunction: K_, validateInt32: L_, validateInteger: k_, validateNumber: N_, validateObject: C_, validateOneOf: D_, validatePlainFunction: j_, validatePort: H_, validateSignalName: F_, validateString: Jp, validateUint32: Xp, validateUndefined: Z_, validateUnion: V_, validateAbortSignal: W_ }; + }); + Rh = T((kI, i1) => { + var dt = i1.exports = {}, Yr, Xr; + function Eh() { + throw new Error("setTimeout has not been defined"); + } + function Ah() { + throw new Error("clearTimeout has not been defined"); + } + (function() { + try { + typeof setTimeout == "function" ? Yr = setTimeout : Yr = Eh; + } catch { + Yr = Eh; + } + try { + typeof clearTimeout == "function" ? Xr = clearTimeout : Xr = Ah; + } catch { + Xr = Ah; + } + })(); + function e1(t) { + if (Yr === setTimeout) + return setTimeout(t, 0); + if ((Yr === Eh || !Yr) && setTimeout) + return Yr = setTimeout, setTimeout(t, 0); + try { + return Yr(t, 0); + } catch { + try { + return Yr.call(null, t, 0); + } catch { + return Yr.call(this, t, 0); + } + } + } + function $_(t) { + if (Xr === clearTimeout) + return clearTimeout(t); + if ((Xr === Ah || !Xr) && clearTimeout) + return Xr = clearTimeout, clearTimeout(t); + try { + return Xr(t); + } catch { + try { + return Xr.call(null, t); + } catch { + return Xr.call(this, t); + } + } + } + var pi = [], nf = false, mn, Oo = -1; + function G_() { + !nf || !mn || (nf = false, mn.length ? pi = mn.concat(pi) : Oo = -1, pi.length && t1()); + } + function t1() { + if (!nf) { + var t = e1(G_); + nf = true; + for (var e = pi.length;e; ) { + for (mn = pi, pi = [];++Oo < e; ) + mn && mn[Oo].run(); + Oo = -1, e = pi.length; + } + mn = null, nf = false, $_(t); + } + } + dt.nextTick = function(t) { + var e = new Array(arguments.length - 1); + if (arguments.length > 1) + for (var r = 1;r < arguments.length; r++) + e[r - 1] = arguments[r]; + pi.push(new r1(t, e)), pi.length === 1 && !nf && e1(t1); + }; + function r1(t, e) { + this.fun = t, this.array = e; + } + r1.prototype.run = function() { + this.fun.apply(null, this.array); + }; + dt.title = "browser"; + dt.browser = true; + dt.env = {}; + dt.argv = []; + dt.version = ""; + dt.versions = {}; + function vi() { + } + dt.on = vi; + dt.addListener = vi; + dt.once = vi; + dt.off = vi; + dt.removeListener = vi; + dt.removeAllListeners = vi; + dt.emit = vi; + dt.prependListener = vi; + dt.prependOnceListener = vi; + dt.listeners = function(t) { + return []; + }; + dt.binding = function(t) { + throw new Error("process.binding is not supported"); + }; + dt.cwd = function() { + return "/"; + }; + dt.chdir = function(t) { + throw new Error("process.chdir is not supported"); + }; + dt.umask = function() { + return 0; + }; + }); + pr = {}; + Ja(pr, { default: () => Y_ }); + Oi = R0(() => { + ot(pr, rn2(Rh())); + Y_ = rn2(Rh()); + }); + Fi = T((NI, v1) => { + var { Symbol: Fo, SymbolAsyncIterator: n1, SymbolIterator: f1 } = Tt2(), a1 = Fo("kDestroyed"), o1 = Fo("kIsErrored"), Bh = Fo("kIsReadable"), s1 = Fo("kIsDisturbed"); + function Uo(t, e = false) { + var r; + return !!(t && typeof t.pipe == "function" && typeof t.on == "function" && (!e || typeof t.pause == "function" && typeof t.resume == "function") && (!t._writableState || ((r = t._readableState) === null || r === undefined ? undefined : r.readable) !== false) && (!t._writableState || t._readableState)); + } + function zo(t) { + var e; + return !!(t && typeof t.write == "function" && typeof t.on == "function" && (!t._readableState || ((e = t._writableState) === null || e === undefined ? undefined : e.writable) !== false)); + } + function X_(t) { + return !!(t && typeof t.pipe == "function" && t._readableState && typeof t.on == "function" && typeof t.write == "function"); + } + function gn(t) { + return t && (t._readableState || t._writableState || typeof t.write == "function" && typeof t.on == "function" || typeof t.pipe == "function" && typeof t.on == "function"); + } + function J_(t, e) { + return t == null ? false : e === true ? typeof t[n1] == "function" : e === false ? typeof t[f1] == "function" : typeof t[n1] == "function" || typeof t[f1] == "function"; + } + function Ho(t) { + if (!gn(t)) + return null; + let { _writableState: e, _readableState: r } = t, o = e || r; + return !!(t.destroyed || t[a1] || o != null && o.destroyed); + } + function h1(t) { + if (!zo(t)) + return null; + if (t.writableEnded === true) + return true; + let e = t._writableState; + return e != null && e.errored ? false : typeof e?.ended != "boolean" ? null : e.ended; + } + function Q_(t, e) { + if (!zo(t)) + return null; + if (t.writableFinished === true) + return true; + let r = t._writableState; + return r != null && r.errored ? false : typeof r?.finished != "boolean" ? null : !!(r.finished || e === false && r.ended === true && r.length === 0); + } + function e8(t) { + if (!Uo(t)) + return null; + if (t.readableEnded === true) + return true; + let e = t._readableState; + return !e || e.errored ? false : typeof e?.ended != "boolean" ? null : e.ended; + } + function u1(t, e) { + if (!Uo(t)) + return null; + let r = t._readableState; + return r != null && r.errored ? false : typeof r?.endEmitted != "boolean" ? null : !!(r.endEmitted || e === false && r.ended === true && r.length === 0); + } + function l1(t) { + return t && t[Bh] != null ? t[Bh] : typeof t?.readable != "boolean" ? null : Ho(t) ? false : Uo(t) && t.readable && !u1(t); + } + function d1(t) { + return typeof t?.writable != "boolean" ? null : Ho(t) ? false : zo(t) && t.writable && !h1(t); + } + function t8(t, e) { + return gn(t) ? Ho(t) ? true : !(e?.readable !== false && l1(t) || e?.writable !== false && d1(t)) : null; + } + function r8(t) { + var e, r; + return gn(t) ? t.writableErrored ? t.writableErrored : (e = (r = t._writableState) === null || r === undefined ? undefined : r.errored) !== null && e !== undefined ? e : null : null; + } + function i8(t) { + var e, r; + return gn(t) ? t.readableErrored ? t.readableErrored : (e = (r = t._readableState) === null || r === undefined ? undefined : r.errored) !== null && e !== undefined ? e : null : null; + } + function n8(t) { + if (!gn(t)) + return null; + if (typeof t.closed == "boolean") + return t.closed; + let { _writableState: e, _readableState: r } = t; + return typeof e?.closed == "boolean" || typeof r?.closed == "boolean" ? e?.closed || r?.closed : typeof t._closed == "boolean" && c1(t) ? t._closed : null; + } + function c1(t) { + return typeof t._closed == "boolean" && typeof t._defaultKeepAlive == "boolean" && typeof t._removedConnection == "boolean" && typeof t._removedContLen == "boolean"; + } + function p1(t) { + return typeof t._sent100 == "boolean" && c1(t); + } + function f8(t) { + var e; + return typeof t._consuming == "boolean" && typeof t._dumped == "boolean" && ((e = t.req) === null || e === undefined ? undefined : e.upgradeOrConnect) === undefined; + } + function a8(t) { + if (!gn(t)) + return null; + let { _writableState: e, _readableState: r } = t, o = e || r; + return !o && p1(t) || !!(o && o.autoDestroy && o.emitClose && o.closed === false); + } + function o8(t) { + var e; + return !!(t && ((e = t[s1]) !== null && e !== undefined ? e : t.readableDidRead || t.readableAborted)); + } + function s8(t) { + var e, r, o, f, p, m, y, M, x, S; + return !!(t && ((e = (r = (o = (f = (p = (m = t[o1]) !== null && m !== undefined ? m : t.readableErrored) !== null && p !== undefined ? p : t.writableErrored) !== null && f !== undefined ? f : (y = t._readableState) === null || y === undefined ? undefined : y.errorEmitted) !== null && o !== undefined ? o : (M = t._writableState) === null || M === undefined ? undefined : M.errorEmitted) !== null && r !== undefined ? r : (x = t._readableState) === null || x === undefined ? undefined : x.errored) !== null && e !== undefined ? e : (S = t._writableState) === null || S === undefined ? undefined : S.errored)); + } + v1.exports = { kDestroyed: a1, isDisturbed: o8, kIsDisturbed: s1, isErrored: s8, kIsErrored: o1, isReadable: l1, kIsReadable: Bh, isClosed: n8, isDestroyed: Ho, isDuplexNodeStream: X_, isFinished: t8, isIterable: J_, isReadableNodeStream: Uo, isReadableEnded: e8, isReadableFinished: u1, isReadableErrored: i8, isNodeStream: gn, isWritable: d1, isWritableNodeStream: zo, isWritableEnded: h1, isWritableFinished: Q_, isWritableErrored: r8, isServerRequest: f8, isServerResponse: p1, willEmitClose: a8 }; + }); + Ui = T((DI, Ih) => { + var ff = (Oi(), ur(pr)), { AbortError: h8, codes: u8 } = Jt(), { ERR_INVALID_ARG_TYPE: l8, ERR_STREAM_PREMATURE_CLOSE: b1 } = u8, { kEmptyObject: m1, once: g1 } = Gr(), { validateAbortSignal: d8, validateFunction: c8, validateObject: p8 } = pa(), { Promise: v8 } = Tt2(), { isClosed: b8, isReadable: y1, isReadableNodeStream: qh, isReadableFinished: w1, isReadableErrored: m8, isWritable: M1, isWritableNodeStream: _1, isWritableFinished: x1, isWritableErrored: g8, isNodeStream: y8, willEmitClose: w8 } = Fi(); + function M8(t) { + return t.setHeader && typeof t.abort == "function"; + } + var _82 = () => { + }; + function S1(t, e, r) { + var o, f; + arguments.length === 2 ? (r = e, e = m1) : e == null ? e = m1 : p8(e, "options"), c8(r, "callback"), d8(e.signal, "options.signal"), r = g1(r); + let p = (o = e.readable) !== null && o !== undefined ? o : qh(t), m = (f = e.writable) !== null && f !== undefined ? f : _1(t); + if (!y8(t)) + throw new l8("stream", "Stream", t); + let { _writableState: y, _readableState: M } = t, x = () => { + t.writable || B(); + }, S = w8(t) && qh(t) === p && _1(t) === m, E2 = x1(t, false), B = () => { + E2 = true, t.destroyed && (S = false), !(S && (!t.readable || p)) && (!p || q) && r.call(t); + }, q = w1(t, false), L = () => { + q = true, t.destroyed && (S = false), !(S && (!t.writable || m)) && (!m || E2) && r.call(t); + }, ge = (xe) => { + r.call(t, xe); + }, _e = b8(t), N = () => { + _e = true; + let xe = g8(t) || m8(t); + if (xe && typeof xe != "boolean") + return r.call(t, xe); + if (p && !q && qh(t, true) && !w1(t, false)) + return r.call(t, new b1); + if (m && !E2 && !x1(t, false)) + return r.call(t, new b1); + r.call(t); + }, we = () => { + t.req.on("finish", B); + }; + M8(t) ? (t.on("complete", B), S || t.on("abort", N), t.req ? we() : t.on("request", we)) : m && !y && (t.on("end", x), t.on("close", x)), !S && typeof t.aborted == "boolean" && t.on("aborted", N), t.on("end", L), t.on("finish", B), e.error !== false && t.on("error", ge), t.on("close", N), _e ? ff.nextTick(N) : y != null && y.errorEmitted || M != null && M.errorEmitted ? S || ff.nextTick(N) : (!p && (!S || y1(t)) && (E2 || M1(t) === false) || !m && (!S || M1(t)) && (q || y1(t) === false) || M && t.req && t.aborted) && ff.nextTick(N); + let ye = () => { + r = _82, t.removeListener("aborted", N), t.removeListener("complete", B), t.removeListener("abort", N), t.removeListener("request", we), t.req && t.req.removeListener("finish", B), t.removeListener("end", x), t.removeListener("close", x), t.removeListener("finish", B), t.removeListener("end", L), t.removeListener("error", ge), t.removeListener("close", N); + }; + if (e.signal && !_e) { + let xe = () => { + let Re = r; + ye(), Re.call(t, new h8(undefined, { cause: e.signal.reason })); + }; + if (e.signal.aborted) + ff.nextTick(xe); + else { + let Re = r; + r = g1((...Ee) => { + e.signal.removeEventListener("abort", xe), Re.apply(t, Ee); + }), e.signal.addEventListener("abort", xe); + } + } + return ye; + } + function x8(t, e) { + return new v8((r, o) => { + S1(t, e, (f) => { + f ? o(f) : r(); + }); + }); + } + Ih.exports = S1; + Ih.exports.finished = x8; + }); + k1 = T((PI, Lh) => { + var B1 = globalThis.AbortController || No().AbortController, { codes: { ERR_INVALID_ARG_TYPE: va, ERR_MISSING_ARGS: S8, ERR_OUT_OF_RANGE: E8 }, AbortError: Jr2 } = Jt(), { validateAbortSignal: af, validateInteger: A8, validateObject: of } = pa(), R8 = Tt2().Symbol("kWeak"), { finished: B8 } = Ui(), { ArrayPrototypePush: q8, MathFloor: I8, Number: T8, NumberIsNaN: k8, Promise: E1, PromiseReject: A1, PromisePrototypeThen: L8, Symbol: q1 } = Tt2(), Wo = q1("kEmpty"), R1 = q1("kEof"); + function Ko(t, e) { + if (typeof t != "function") + throw new va("fn", ["Function", "AsyncFunction"], t); + e != null && of(e, "options"), e?.signal != null && af(e.signal, "options.signal"); + let r = 1; + return e?.concurrency != null && (r = I8(e.concurrency)), A8(r, "concurrency", 1), async function* () { + var f, p; + let m = new B1, y = this, M = [], x = m.signal, S = { signal: x }, E2 = () => m.abort(); + e != null && (f = e.signal) !== null && f !== undefined && f.aborted && E2(), e == null || (p = e.signal) === null || p === undefined || p.addEventListener("abort", E2); + let B, q, L = false; + function ge() { + L = true; + } + async function _e() { + try { + for await (let ye of y) { + var N; + if (L) + return; + if (x.aborted) + throw new Jr2; + try { + ye = t(ye, S); + } catch (xe) { + ye = A1(xe); + } + ye !== Wo && (typeof ((N = ye) === null || N === undefined ? undefined : N.catch) == "function" && ye.catch(ge), M.push(ye), B && (B(), B = null), !L && M.length && M.length >= r && await new E1((xe) => { + q = xe; + })); + } + M.push(R1); + } catch (ye) { + let xe = A1(ye); + L8(xe, undefined, ge), M.push(xe); + } finally { + var we; + L = true, B && (B(), B = null), e == null || (we = e.signal) === null || we === undefined || we.removeEventListener("abort", E2); + } + } + _e(); + try { + for (;; ) { + for (;M.length > 0; ) { + let N = await M[0]; + if (N === R1) + return; + if (x.aborted) + throw new Jr2; + N !== Wo && (yield N), M.shift(), q && (q(), q = null); + } + await new E1((N) => { + B = N; + }); + } + } finally { + m.abort(), L = true, q && (q(), q = null); + } + }.call(this); + } + function N8(t = undefined) { + return t != null && of(t, "options"), t?.signal != null && af(t.signal, "options.signal"), async function* () { + let r = 0; + for await (let f of this) { + var o; + if (t != null && (o = t.signal) !== null && o !== undefined && o.aborted) + throw new Jr2({ cause: t.signal.reason }); + yield [r++, f]; + } + }.call(this); + } + async function I1(t, e = undefined) { + for await (let r of kh.call(this, t, e)) + return true; + return false; + } + async function D8(t, e = undefined) { + if (typeof t != "function") + throw new va("fn", ["Function", "AsyncFunction"], t); + return !await I1.call(this, async (...r) => !await t(...r), e); + } + async function P8(t, e) { + for await (let r of kh.call(this, t, e)) + return r; + } + async function C8(t, e) { + if (typeof t != "function") + throw new va("fn", ["Function", "AsyncFunction"], t); + async function r(o, f) { + return await t(o, f), Wo; + } + for await (let o of Ko.call(this, r, e)) + ; + } + function kh(t, e) { + if (typeof t != "function") + throw new va("fn", ["Function", "AsyncFunction"], t); + async function r(o, f) { + return await t(o, f) ? o : Wo; + } + return Ko.call(this, r, e); + } + var Th = class extends S8 { + constructor() { + super("reduce"), this.message = "Reduce of an empty stream requires an initial value"; + } + }; + async function O8(t, e, r) { + var o; + if (typeof t != "function") + throw new va("reducer", ["Function", "AsyncFunction"], t); + r != null && of(r, "options"), r?.signal != null && af(r.signal, "options.signal"); + let f = arguments.length > 1; + if (r != null && (o = r.signal) !== null && o !== undefined && o.aborted) { + let x = new Jr2(undefined, { cause: r.signal.reason }); + throw this.once("error", () => { + }), await B8(this.destroy(x)), x; + } + let p = new B1, m = p.signal; + if (r != null && r.signal) { + let x = { once: true, [R8]: this }; + r.signal.addEventListener("abort", () => p.abort(), x); + } + let y = false; + try { + for await (let x of this) { + var M; + if (y = true, r != null && (M = r.signal) !== null && M !== undefined && M.aborted) + throw new Jr2; + f ? e = await t(e, x, { signal: m }) : (e = x, f = true); + } + if (!y && !f) + throw new Th; + } finally { + p.abort(); + } + return e; + } + async function F8(t) { + t != null && of(t, "options"), t?.signal != null && af(t.signal, "options.signal"); + let e = []; + for await (let o of this) { + var r; + if (t != null && (r = t.signal) !== null && r !== undefined && r.aborted) + throw new Jr2(undefined, { cause: t.signal.reason }); + q8(e, o); + } + return e; + } + function U8(t, e) { + let r = Ko.call(this, t, e); + return async function* () { + for await (let f of r) + yield* f; + }.call(this); + } + function T1(t) { + if (t = T8(t), k8(t)) + return 0; + if (t < 0) + throw new E8("number", ">= 0", t); + return t; + } + function z8(t, e = undefined) { + return e != null && of(e, "options"), e?.signal != null && af(e.signal, "options.signal"), t = T1(t), async function* () { + var o; + if (e != null && (o = e.signal) !== null && o !== undefined && o.aborted) + throw new Jr2; + for await (let p of this) { + var f; + if (e != null && (f = e.signal) !== null && f !== undefined && f.aborted) + throw new Jr2; + t-- <= 0 && (yield p); + } + }.call(this); + } + function H8(t, e = undefined) { + return e != null && of(e, "options"), e?.signal != null && af(e.signal, "options.signal"), t = T1(t), async function* () { + var o; + if (e != null && (o = e.signal) !== null && o !== undefined && o.aborted) + throw new Jr2; + for await (let p of this) { + var f; + if (e != null && (f = e.signal) !== null && f !== undefined && f.aborted) + throw new Jr2; + if (t-- > 0) + yield p; + else + return; + } + }.call(this); + } + Lh.exports.streamReturningOperators = { asIndexedPairs: N8, drop: z8, filter: kh, flatMap: U8, map: Ko, take: H8 }; + Lh.exports.promiseReturningOperators = { every: D8, forEach: C8, reduce: O8, toArray: F8, some: I1, find: P8 }; + }); + yn = T((CI, U1) => { + var zi = (Oi(), ur(pr)), { aggregateTwoErrors: W8, codes: { ERR_MULTIPLE_CALLBACK: K8 }, AbortError: j8 } = Jt(), { Symbol: D1 } = Tt2(), { kDestroyed: Z8, isDestroyed: V8, isFinished: $8, isServerRequest: G8 } = Fi(), P1 = D1("kDestroy"), Nh = D1("kConstruct"); + function C1(t, e, r) { + t && (t.stack, e && !e.errored && (e.errored = t), r && !r.errored && (r.errored = t)); + } + function Y8(t, e) { + let r = this._readableState, o = this._writableState, f = o || r; + return o && o.destroyed || r && r.destroyed ? (typeof e == "function" && e(), this) : (C1(t, o, r), o && (o.destroyed = true), r && (r.destroyed = true), f.constructed ? L1(this, t, e) : this.once(P1, function(p) { + L1(this, W8(p, t), e); + }), this); + } + function L1(t, e, r) { + let o = false; + function f(p) { + if (o) + return; + o = true; + let { _readableState: m, _writableState: y } = t; + C1(p, y, m), y && (y.closed = true), m && (m.closed = true), typeof r == "function" && r(p), p ? zi.nextTick(X8, t, p) : zi.nextTick(O1, t); + } + try { + t._destroy(e || null, f); + } catch (p) { + f(p); + } + } + function X8(t, e) { + Dh(t, e), O1(t); + } + function O1(t) { + let { _readableState: e, _writableState: r } = t; + r && (r.closeEmitted = true), e && (e.closeEmitted = true), (r && r.emitClose || e && e.emitClose) && t.emit("close"); + } + function Dh(t, e) { + let { _readableState: r, _writableState: o } = t; + o && o.errorEmitted || r && r.errorEmitted || (o && (o.errorEmitted = true), r && (r.errorEmitted = true), t.emit("error", e)); + } + function J8() { + let t = this._readableState, e = this._writableState; + t && (t.constructed = true, t.closed = false, t.closeEmitted = false, t.destroyed = false, t.errored = null, t.errorEmitted = false, t.reading = false, t.ended = t.readable === false, t.endEmitted = t.readable === false), e && (e.constructed = true, e.destroyed = false, e.closed = false, e.closeEmitted = false, e.errored = null, e.errorEmitted = false, e.finalCalled = false, e.prefinished = false, e.ended = e.writable === false, e.ending = e.writable === false, e.finished = e.writable === false); + } + function Ph(t, e, r) { + let { _readableState: o, _writableState: f } = t; + if (f && f.destroyed || o && o.destroyed) + return this; + o && o.autoDestroy || f && f.autoDestroy ? t.destroy(e) : e && (e.stack, f && !f.errored && (f.errored = e), o && !o.errored && (o.errored = e), r ? zi.nextTick(Dh, t, e) : Dh(t, e)); + } + function Q8(t, e) { + if (typeof t._construct != "function") + return; + let { _readableState: r, _writableState: o } = t; + r && (r.constructed = false), o && (o.constructed = false), t.once(Nh, e), !(t.listenerCount(Nh) > 1) && zi.nextTick(e5, t); + } + function e5(t) { + let e = false; + function r(o) { + if (e) { + Ph(t, o ?? new K8); + return; + } + e = true; + let { _readableState: f, _writableState: p } = t, m = p || f; + f && (f.constructed = true), p && (p.constructed = true), m.destroyed ? t.emit(P1, o) : o ? Ph(t, o, true) : zi.nextTick(t5, t); + } + try { + t._construct(r); + } catch (o) { + r(o); + } + } + function t5(t) { + t.emit(Nh); + } + function N1(t) { + return t && t.setHeader && typeof t.abort == "function"; + } + function F1(t) { + t.emit("close"); + } + function r5(t, e) { + t.emit("error", e), zi.nextTick(F1, t); + } + function i5(t, e) { + !t || V8(t) || (!e && !$8(t) && (e = new j8), G8(t) ? (t.socket = null, t.destroy(e)) : N1(t) ? t.abort() : N1(t.req) ? t.req.abort() : typeof t.destroy == "function" ? t.destroy(e) : typeof t.close == "function" ? t.close() : e ? zi.nextTick(r5, t, e) : zi.nextTick(F1, t), t.destroyed || (t[Z8] = true)); + } + U1.exports = { construct: Q8, destroyer: i5, destroy: Y8, undestroy: J8, errorOrDestroy: Ph }; + }); + Vo = T((OI, H1) => { + var { ArrayIsArray: n5, ObjectSetPrototypeOf: z1 } = Tt2(), { EventEmitter: jo } = ki(); + function Zo(t) { + jo.call(this, t); + } + z1(Zo.prototype, jo.prototype); + z1(Zo, jo); + Zo.prototype.pipe = function(t, e) { + let r = this; + function o(S) { + t.writable && t.write(S) === false && r.pause && r.pause(); + } + r.on("data", o); + function f() { + r.readable && r.resume && r.resume(); + } + t.on("drain", f), !t._isStdio && (!e || e.end !== false) && (r.on("end", m), r.on("close", y)); + let p = false; + function m() { + p || (p = true, t.end()); + } + function y() { + p || (p = true, typeof t.destroy == "function" && t.destroy()); + } + function M(S) { + x(), jo.listenerCount(this, "error") === 0 && this.emit("error", S); + } + Ch(r, "error", M), Ch(t, "error", M); + function x() { + r.removeListener("data", o), t.removeListener("drain", f), r.removeListener("end", m), r.removeListener("close", y), r.removeListener("error", M), t.removeListener("error", M), r.removeListener("end", x), r.removeListener("close", x), t.removeListener("close", x); + } + return r.on("end", x), r.on("close", x), t.on("close", x), t.emit("pipe", r), t; + }; + function Ch(t, e, r) { + if (typeof t.prependListener == "function") + return t.prependListener(e, r); + !t._events || !t._events[e] ? t.on(e, r) : n5(t._events[e]) ? t._events[e].unshift(r) : t._events[e] = [r, t._events[e]]; + } + H1.exports = { Stream: Zo, prependListener: Ch }; + }); + Go = T((FI, $o) => { + var { AbortError: f5, codes: a5 } = Jt(), o5 = Ui(), { ERR_INVALID_ARG_TYPE: W1 } = a5, s5 = (t, e) => { + if (typeof t != "object" || !("aborted" in t)) + throw new W1(e, "AbortSignal", t); + }; + function h5(t) { + return !!(t && typeof t.pipe == "function"); + } + $o.exports.addAbortSignal = function(e, r) { + if (s5(e, "signal"), !h5(r)) + throw new W1("stream", "stream.Stream", r); + return $o.exports.addAbortSignalNoValidate(e, r); + }; + $o.exports.addAbortSignalNoValidate = function(t, e) { + if (typeof t != "object" || !("aborted" in t)) + return e; + let r = () => { + e.destroy(new f5(undefined, { cause: t.reason })); + }; + return t.aborted ? r() : (t.addEventListener("abort", r), o5(e, () => t.removeEventListener("abort", r))), e; + }; + }); + Z1 = T((zI, j1) => { + var { StringPrototypeSlice: K1, SymbolIterator: u5, TypedArrayPrototypeSet: Yo, Uint8Array: l5 } = Tt2(), { Buffer: Oh } = Ut2(), { inspect: d5 } = Gr(); + j1.exports = class { + constructor() { + this.head = null, this.tail = null, this.length = 0; + } + push(e) { + let r = { data: e, next: null }; + this.length > 0 ? this.tail.next = r : this.head = r, this.tail = r, ++this.length; + } + unshift(e) { + let r = { data: e, next: this.head }; + this.length === 0 && (this.tail = r), this.head = r, ++this.length; + } + shift() { + if (this.length === 0) + return; + let e = this.head.data; + return this.length === 1 ? this.head = this.tail = null : this.head = this.head.next, --this.length, e; + } + clear() { + this.head = this.tail = null, this.length = 0; + } + join(e) { + if (this.length === 0) + return ""; + let r = this.head, o = "" + r.data; + for (;(r = r.next) !== null; ) + o += e + r.data; + return o; + } + concat(e) { + if (this.length === 0) + return Oh.alloc(0); + let r = Oh.allocUnsafe(e >>> 0), o = this.head, f = 0; + for (;o; ) + Yo(r, o.data, f), f += o.data.length, o = o.next; + return r; + } + consume(e, r) { + let o = this.head.data; + if (e < o.length) { + let f = o.slice(0, e); + return this.head.data = o.slice(e), f; + } + return e === o.length ? this.shift() : r ? this._getString(e) : this._getBuffer(e); + } + first() { + return this.head.data; + } + *[u5]() { + for (let e = this.head;e; e = e.next) + yield e.data; + } + _getString(e) { + let r = "", o = this.head, f = 0; + do { + let p = o.data; + if (e > p.length) + r += p, e -= p.length; + else { + e === p.length ? (r += p, ++f, o.next ? this.head = o.next : this.head = this.tail = null) : (r += K1(p, 0, e), this.head = o, o.data = K1(p, e)); + break; + } + ++f; + } while ((o = o.next) !== null); + return this.length -= f, r; + } + _getBuffer(e) { + let r = Oh.allocUnsafe(e), o = e, f = this.head, p = 0; + do { + let m = f.data; + if (e > m.length) + Yo(r, m, o - e), e -= m.length; + else { + e === m.length ? (Yo(r, m, o - e), ++p, f.next ? this.head = f.next : this.head = this.tail = null) : (Yo(r, new l5(m.buffer, m.byteOffset, e), o - e), this.head = f, f.data = m.slice(e)); + break; + } + ++p; + } while ((f = f.next) !== null); + return this.length -= p, r; + } + [Symbol.for("nodejs.util.inspect.custom")](e, r) { + return d5(this, { ...r, depth: 0, customInspect: false }); + } + }; + }); + Xo = T((HI, $1) => { + var { MathFloor: c5, NumberIsInteger: p5 } = Tt2(), { ERR_INVALID_ARG_VALUE: v5 } = Jt().codes; + function b5(t, e, r) { + return t.highWaterMark != null ? t.highWaterMark : e ? t[r] : null; + } + function V1(t) { + return t ? 16 : 16 * 1024; + } + function m5(t, e, r, o) { + let f = b5(e, o, r); + if (f != null) { + if (!p5(f) || f < 0) { + let p = o ? `options.${r}` : "options.highWaterMark"; + throw new v5(p, f); + } + return c5(f); + } + return V1(t.objectMode); + } + $1.exports = { getHighWaterMark: m5, getDefaultHighWaterMark: V1 }; + }); + Fh = T((WI, J1) => { + var G1 = (Oi(), ur(pr)), { PromisePrototypeThen: g5, SymbolAsyncIterator: Y1, SymbolIterator: X1 } = Tt2(), { Buffer: y5 } = Ut2(), { ERR_INVALID_ARG_TYPE: w5, ERR_STREAM_NULL_VALUES: M5 } = Jt().codes; + function _52(t, e, r) { + let o; + if (typeof e == "string" || e instanceof y5) + return new t({ objectMode: true, ...r, read() { + this.push(e), this.push(null); + } }); + let f; + if (e && e[Y1]) + f = true, o = e[Y1](); + else if (e && e[X1]) + f = false, o = e[X1](); + else + throw new w5("iterable", ["Iterable"], e); + let p = new t({ objectMode: true, highWaterMark: 1, ...r }), m = false; + p._read = function() { + m || (m = true, M()); + }, p._destroy = function(x, S) { + g5(y(x), () => G1.nextTick(S, x), (E2) => G1.nextTick(S, E2 || x)); + }; + async function y(x) { + let S = x != null, E2 = typeof o.throw == "function"; + if (S && E2) { + let { value: B, done: q } = await o.throw(x); + if (await B, q) + return; + } + if (typeof o.return == "function") { + let { value: B } = await o.return(); + await B; + } + } + async function M() { + for (;; ) { + try { + let { value: x, done: S } = f ? await o.next() : o.next(); + if (S) + p.push(null); + else { + let E2 = x && typeof x.then == "function" ? await x : x; + if (E2 === null) + throw m = false, new M5; + if (p.push(E2)) + continue; + m = false; + } + } catch (x) { + p.destroy(x); + } + break; + } + } + return p; + } + J1.exports = _52; + }); + ba = T((KI, lv) => { + var Tr = (Oi(), ur(pr)), { ArrayPrototypeIndexOf: x5, NumberIsInteger: S5, NumberIsNaN: E5, NumberParseInt: A5, ObjectDefineProperties: tv, ObjectKeys: R5, ObjectSetPrototypeOf: rv, Promise: B5, SafeSet: q5, SymbolAsyncIterator: I5, Symbol: T5 } = Tt2(); + lv.exports = Le; + Le.ReadableState = jh; + var { EventEmitter: k5 } = ki(), { Stream: Hi, prependListener: L5 } = Vo(), { Buffer: Uh } = Ut2(), { addAbortSignal: N5 } = Go(), D5 = Ui(), Pe = Gr().debuglog("stream", (t) => { + Pe = t; + }), P5 = Z1(), hf = yn(), { getHighWaterMark: C5, getDefaultHighWaterMark: O5 } = Xo(), { aggregateTwoErrors: Q1, codes: { ERR_INVALID_ARG_TYPE: F5, ERR_METHOD_NOT_IMPLEMENTED: U5, ERR_OUT_OF_RANGE: z5, ERR_STREAM_PUSH_AFTER_EOF: H5, ERR_STREAM_UNSHIFT_AFTER_END_EVENT: W5 } } = Jt(), { validateObject: K5 } = pa(), wn = T5("kPaused"), { StringDecoder: iv } = co(), j5 = Fh(); + rv(Le.prototype, Hi.prototype); + rv(Le, Hi); + var zh = () => { + }, { errorOrDestroy: sf } = hf; + function jh(t, e, r) { + typeof r != "boolean" && (r = e instanceof Qr2()), this.objectMode = !!(t && t.objectMode), r && (this.objectMode = this.objectMode || !!(t && t.readableObjectMode)), this.highWaterMark = t ? C5(this, t, "readableHighWaterMark", r) : O5(false), this.buffer = new P5, this.length = 0, this.pipes = [], this.flowing = null, this.ended = false, this.endEmitted = false, this.reading = false, this.constructed = true, this.sync = true, this.needReadable = false, this.emittedReadable = false, this.readableListening = false, this.resumeScheduled = false, this[wn] = null, this.errorEmitted = false, this.emitClose = !t || t.emitClose !== false, this.autoDestroy = !t || t.autoDestroy !== false, this.destroyed = false, this.errored = null, this.closed = false, this.closeEmitted = false, this.defaultEncoding = t && t.defaultEncoding || "utf8", this.awaitDrainWriters = null, this.multiAwaitDrain = false, this.readingMore = false, this.dataEmitted = false, this.decoder = null, this.encoding = null, t && t.encoding && (this.decoder = new iv(t.encoding), this.encoding = t.encoding); + } + function Le(t) { + if (!(this instanceof Le)) + return new Le(t); + let e = this instanceof Qr2(); + this._readableState = new jh(t, this, e), t && (typeof t.read == "function" && (this._read = t.read), typeof t.destroy == "function" && (this._destroy = t.destroy), typeof t.construct == "function" && (this._construct = t.construct), t.signal && !e && N5(t.signal, this)), Hi.call(this, t), hf.construct(this, () => { + this._readableState.needReadable && Jo2(this, this._readableState); + }); + } + Le.prototype.destroy = hf.destroy; + Le.prototype._undestroy = hf.undestroy; + Le.prototype._destroy = function(t, e) { + e(t); + }; + Le.prototype[k5.captureRejectionSymbol] = function(t) { + this.destroy(t); + }; + Le.prototype.push = function(t, e) { + return nv(this, t, e, false); + }; + Le.prototype.unshift = function(t, e) { + return nv(this, t, e, true); + }; + function nv(t, e, r, o) { + Pe("readableAddChunk", e); + let f = t._readableState, p; + if (f.objectMode || (typeof e == "string" ? (r = r || f.defaultEncoding, f.encoding !== r && (o && f.encoding ? e = Uh.from(e, r).toString(f.encoding) : (e = Uh.from(e, r), r = ""))) : e instanceof Uh ? r = "" : Hi._isUint8Array(e) ? (e = Hi._uint8ArrayToBuffer(e), r = "") : e != null && (p = new F5("chunk", ["string", "Buffer", "Uint8Array"], e))), p) + sf(t, p); + else if (e === null) + f.reading = false, $5(t, f); + else if (f.objectMode || e && e.length > 0) + if (o) + if (f.endEmitted) + sf(t, new W5); + else { + if (f.destroyed || f.errored) + return false; + Hh(t, f, e, true); + } + else if (f.ended) + sf(t, new H5); + else { + if (f.destroyed || f.errored) + return false; + f.reading = false, f.decoder && !r ? (e = f.decoder.write(e), f.objectMode || e.length !== 0 ? Hh(t, f, e, false) : Jo2(t, f)) : Hh(t, f, e, false); + } + else + o || (f.reading = false, Jo2(t, f)); + return !f.ended && (f.length < f.highWaterMark || f.length === 0); + } + function Hh(t, e, r, o) { + e.flowing && e.length === 0 && !e.sync && t.listenerCount("data") > 0 ? (e.multiAwaitDrain ? e.awaitDrainWriters.clear() : e.awaitDrainWriters = null, e.dataEmitted = true, t.emit("data", r)) : (e.length += e.objectMode ? 1 : r.length, o ? e.buffer.unshift(r) : e.buffer.push(r), e.needReadable && Qo(t)), Jo2(t, e); + } + Le.prototype.isPaused = function() { + let t = this._readableState; + return t[wn] === true || t.flowing === false; + }; + Le.prototype.setEncoding = function(t) { + let e = new iv(t); + this._readableState.decoder = e, this._readableState.encoding = this._readableState.decoder.encoding; + let r = this._readableState.buffer, o = ""; + for (let f of r) + o += e.write(f); + return r.clear(), o !== "" && r.push(o), this._readableState.length = o.length, this; + }; + var Z5 = 1073741824; + function V5(t) { + if (t > Z5) + throw new z5("size", "<= 1GiB", t); + return t--, t |= t >>> 1, t |= t >>> 2, t |= t >>> 4, t |= t >>> 8, t |= t >>> 16, t++, t; + } + function ev(t, e) { + return t <= 0 || e.length === 0 && e.ended ? 0 : e.objectMode ? 1 : E5(t) ? e.flowing && e.length ? e.buffer.first().length : e.length : t <= e.length ? t : e.ended ? e.length : 0; + } + Le.prototype.read = function(t) { + Pe("read", t), t === undefined ? t = NaN : S5(t) || (t = A5(t, 10)); + let e = this._readableState, r = t; + if (t > e.highWaterMark && (e.highWaterMark = V5(t)), t !== 0 && (e.emittedReadable = false), t === 0 && e.needReadable && ((e.highWaterMark !== 0 ? e.length >= e.highWaterMark : e.length > 0) || e.ended)) + return Pe("read: emitReadable", e.length, e.ended), e.length === 0 && e.ended ? Wh(this) : Qo(this), null; + if (t = ev(t, e), t === 0 && e.ended) + return e.length === 0 && Wh(this), null; + let o = e.needReadable; + if (Pe("need readable", o), (e.length === 0 || e.length - t < e.highWaterMark) && (o = true, Pe("length less than watermark", o)), e.ended || e.reading || e.destroyed || e.errored || !e.constructed) + o = false, Pe("reading, ended or constructing", o); + else if (o) { + Pe("do read"), e.reading = true, e.sync = true, e.length === 0 && (e.needReadable = true); + try { + this._read(e.highWaterMark); + } catch (p) { + sf(this, p); + } + e.sync = false, e.reading || (t = ev(r, e)); + } + let f; + return t > 0 ? f = hv(t, e) : f = null, f === null ? (e.needReadable = e.length <= e.highWaterMark, t = 0) : (e.length -= t, e.multiAwaitDrain ? e.awaitDrainWriters.clear() : e.awaitDrainWriters = null), e.length === 0 && (e.ended || (e.needReadable = true), r !== t && e.ended && Wh(this)), f !== null && !e.errorEmitted && !e.closeEmitted && (e.dataEmitted = true, this.emit("data", f)), f; + }; + function $5(t, e) { + if (Pe("onEofChunk"), !e.ended) { + if (e.decoder) { + let r = e.decoder.end(); + r && r.length && (e.buffer.push(r), e.length += e.objectMode ? 1 : r.length); + } + e.ended = true, e.sync ? Qo(t) : (e.needReadable = false, e.emittedReadable = true, fv(t)); + } + } + function Qo(t) { + let e = t._readableState; + Pe("emitReadable", e.needReadable, e.emittedReadable), e.needReadable = false, e.emittedReadable || (Pe("emitReadable", e.flowing), e.emittedReadable = true, Tr.nextTick(fv, t)); + } + function fv(t) { + let e = t._readableState; + Pe("emitReadable_", e.destroyed, e.length, e.ended), !e.destroyed && !e.errored && (e.length || e.ended) && (t.emit("readable"), e.emittedReadable = false), e.needReadable = !e.flowing && !e.ended && e.length <= e.highWaterMark, ov(t); + } + function Jo2(t, e) { + !e.readingMore && e.constructed && (e.readingMore = true, Tr.nextTick(G5, t, e)); + } + function G5(t, e) { + for (;!e.reading && !e.ended && (e.length < e.highWaterMark || e.flowing && e.length === 0); ) { + let r = e.length; + if (Pe("maybeReadMore read 0"), t.read(0), r === e.length) + break; + } + e.readingMore = false; + } + Le.prototype._read = function(t) { + throw new U5("_read()"); + }; + Le.prototype.pipe = function(t, e) { + let r = this, o = this._readableState; + o.pipes.length === 1 && (o.multiAwaitDrain || (o.multiAwaitDrain = true, o.awaitDrainWriters = new q5(o.awaitDrainWriters ? [o.awaitDrainWriters] : []))), o.pipes.push(t), Pe("pipe count=%d opts=%j", o.pipes.length, e); + let p = (!e || e.end !== false) && t !== Tr.stdout && t !== Tr.stderr ? y : _e; + o.endEmitted ? Tr.nextTick(p) : r.once("end", p), t.on("unpipe", m); + function m(N, we) { + Pe("onunpipe"), N === r && we && we.hasUnpiped === false && (we.hasUnpiped = true, S()); + } + function y() { + Pe("onend"), t.end(); + } + let M, x = false; + function S() { + Pe("cleanup"), t.removeListener("close", L), t.removeListener("finish", ge), M && t.removeListener("drain", M), t.removeListener("error", q), t.removeListener("unpipe", m), r.removeListener("end", y), r.removeListener("end", _e), r.removeListener("data", B), x = true, M && o.awaitDrainWriters && (!t._writableState || t._writableState.needDrain) && M(); + } + function E2() { + x || (o.pipes.length === 1 && o.pipes[0] === t ? (Pe("false write response, pause", 0), o.awaitDrainWriters = t, o.multiAwaitDrain = false) : o.pipes.length > 1 && o.pipes.includes(t) && (Pe("false write response, pause", o.awaitDrainWriters.size), o.awaitDrainWriters.add(t)), r.pause()), M || (M = Y5(r, t), t.on("drain", M)); + } + r.on("data", B); + function B(N) { + Pe("ondata"); + let we = t.write(N); + Pe("dest.write", we), we === false && E2(); + } + function q(N) { + if (Pe("onerror", N), _e(), t.removeListener("error", q), t.listenerCount("error") === 0) { + let we = t._writableState || t._readableState; + we && !we.errorEmitted ? sf(t, N) : t.emit("error", N); + } + } + L5(t, "error", q); + function L() { + t.removeListener("finish", ge), _e(); + } + t.once("close", L); + function ge() { + Pe("onfinish"), t.removeListener("close", L), _e(); + } + t.once("finish", ge); + function _e() { + Pe("unpipe"), r.unpipe(t); + } + return t.emit("pipe", r), t.writableNeedDrain === true ? o.flowing && E2() : o.flowing || (Pe("pipe resume"), r.resume()), t; + }; + function Y5(t, e) { + return function() { + let o = t._readableState; + o.awaitDrainWriters === e ? (Pe("pipeOnDrain", 1), o.awaitDrainWriters = null) : o.multiAwaitDrain && (Pe("pipeOnDrain", o.awaitDrainWriters.size), o.awaitDrainWriters.delete(e)), (!o.awaitDrainWriters || o.awaitDrainWriters.size === 0) && t.listenerCount("data") && t.resume(); + }; + } + Le.prototype.unpipe = function(t) { + let e = this._readableState, r = { hasUnpiped: false }; + if (e.pipes.length === 0) + return this; + if (!t) { + let f = e.pipes; + e.pipes = [], this.pause(); + for (let p = 0;p < f.length; p++) + f[p].emit("unpipe", this, { hasUnpiped: false }); + return this; + } + let o = x5(e.pipes, t); + return o === -1 ? this : (e.pipes.splice(o, 1), e.pipes.length === 0 && this.pause(), t.emit("unpipe", this, r), this); + }; + Le.prototype.on = function(t, e) { + let r = Hi.prototype.on.call(this, t, e), o = this._readableState; + return t === "data" ? (o.readableListening = this.listenerCount("readable") > 0, o.flowing !== false && this.resume()) : t === "readable" && !o.endEmitted && !o.readableListening && (o.readableListening = o.needReadable = true, o.flowing = false, o.emittedReadable = false, Pe("on readable", o.length, o.reading), o.length ? Qo(this) : o.reading || Tr.nextTick(X5, this)), r; + }; + Le.prototype.addListener = Le.prototype.on; + Le.prototype.removeListener = function(t, e) { + let r = Hi.prototype.removeListener.call(this, t, e); + return t === "readable" && Tr.nextTick(av, this), r; + }; + Le.prototype.off = Le.prototype.removeListener; + Le.prototype.removeAllListeners = function(t) { + let e = Hi.prototype.removeAllListeners.apply(this, arguments); + return (t === "readable" || t === undefined) && Tr.nextTick(av, this), e; + }; + function av(t) { + let e = t._readableState; + e.readableListening = t.listenerCount("readable") > 0, e.resumeScheduled && e[wn] === false ? e.flowing = true : t.listenerCount("data") > 0 ? t.resume() : e.readableListening || (e.flowing = null); + } + function X5(t) { + Pe("readable nexttick read 0"), t.read(0); + } + Le.prototype.resume = function() { + let t = this._readableState; + return t.flowing || (Pe("resume"), t.flowing = !t.readableListening, J5(this, t)), t[wn] = false, this; + }; + function J5(t, e) { + e.resumeScheduled || (e.resumeScheduled = true, Tr.nextTick(Q5, t, e)); + } + function Q5(t, e) { + Pe("resume", e.reading), e.reading || t.read(0), e.resumeScheduled = false, t.emit("resume"), ov(t), e.flowing && !e.reading && t.read(0); + } + Le.prototype.pause = function() { + return Pe("call pause flowing=%j", this._readableState.flowing), this._readableState.flowing !== false && (Pe("pause"), this._readableState.flowing = false, this.emit("pause")), this._readableState[wn] = true, this; + }; + function ov(t) { + let e = t._readableState; + for (Pe("flow", e.flowing);e.flowing && t.read() !== null; ) + ; + } + Le.prototype.wrap = function(t) { + let e = false; + t.on("data", (o) => { + !this.push(o) && t.pause && (e = true, t.pause()); + }), t.on("end", () => { + this.push(null); + }), t.on("error", (o) => { + sf(this, o); + }), t.on("close", () => { + this.destroy(); + }), t.on("destroy", () => { + this.destroy(); + }), this._read = () => { + e && t.resume && (e = false, t.resume()); + }; + let r = R5(t); + for (let o = 1;o < r.length; o++) { + let f = r[o]; + this[f] === undefined && typeof t[f] == "function" && (this[f] = t[f].bind(t)); + } + return this; + }; + Le.prototype[I5] = function() { + return sv(this); + }; + Le.prototype.iterator = function(t) { + return t !== undefined && K5(t, "options"), sv(this, t); + }; + function sv(t, e) { + typeof t.read != "function" && (t = Le.wrap(t, { objectMode: true })); + let r = ex(t, e); + return r.stream = t, r; + } + async function* ex(t, e) { + let r = zh; + function o(m) { + this === t ? (r(), r = zh) : r = m; + } + t.on("readable", o); + let f, p = D5(t, { writable: false }, (m) => { + f = m ? Q1(f, m) : null, r(), r = zh; + }); + try { + for (;; ) { + let m = t.destroyed ? null : t.read(); + if (m !== null) + yield m; + else { + if (f) + throw f; + if (f === null) + return; + await new B5(o); + } + } + } catch (m) { + throw f = Q1(f, m), f; + } finally { + (f || e?.destroyOnReturn !== false) && (f === undefined || t._readableState.autoDestroy) ? hf.destroyer(t, null) : (t.off("readable", o), p()); + } + } + tv(Le.prototype, { readable: { __proto__: null, get() { + let t = this._readableState; + return !!t && t.readable !== false && !t.destroyed && !t.errorEmitted && !t.endEmitted; + }, set(t) { + this._readableState && (this._readableState.readable = !!t); + } }, readableDidRead: { __proto__: null, enumerable: false, get: function() { + return this._readableState.dataEmitted; + } }, readableAborted: { __proto__: null, enumerable: false, get: function() { + return !!(this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted); + } }, readableHighWaterMark: { __proto__: null, enumerable: false, get: function() { + return this._readableState.highWaterMark; + } }, readableBuffer: { __proto__: null, enumerable: false, get: function() { + return this._readableState && this._readableState.buffer; + } }, readableFlowing: { __proto__: null, enumerable: false, get: function() { + return this._readableState.flowing; + }, set: function(t) { + this._readableState && (this._readableState.flowing = t); + } }, readableLength: { __proto__: null, enumerable: false, get() { + return this._readableState.length; + } }, readableObjectMode: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.objectMode : false; + } }, readableEncoding: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.encoding : null; + } }, errored: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.errored : null; + } }, closed: { __proto__: null, get() { + return this._readableState ? this._readableState.closed : false; + } }, destroyed: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.destroyed : false; + }, set(t) { + !this._readableState || (this._readableState.destroyed = t); + } }, readableEnded: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.endEmitted : false; + } } }); + tv(jh.prototype, { pipesCount: { __proto__: null, get() { + return this.pipes.length; + } }, paused: { __proto__: null, get() { + return this[wn] !== false; + }, set(t) { + this[wn] = !!t; + } } }); + Le._fromList = hv; + function hv(t, e) { + if (e.length === 0) + return null; + let r; + return e.objectMode ? r = e.buffer.shift() : !t || t >= e.length ? (e.decoder ? r = e.buffer.join("") : e.buffer.length === 1 ? r = e.buffer.first() : r = e.buffer.concat(e.length), e.buffer.clear()) : r = e.buffer.consume(t, e.decoder), r; + } + function Wh(t) { + let e = t._readableState; + Pe("endReadable", e.endEmitted), e.endEmitted || (e.ended = true, Tr.nextTick(tx, e, t)); + } + function tx(t, e) { + if (Pe("endReadableNT", t.endEmitted, t.length), !t.errored && !t.closeEmitted && !t.endEmitted && t.length === 0) { + if (t.endEmitted = true, e.emit("end"), e.writable && e.allowHalfOpen === false) + Tr.nextTick(rx, e); + else if (t.autoDestroy) { + let r = e._writableState; + (!r || r.autoDestroy && (r.finished || r.writable === false)) && e.destroy(); + } + } + } + function rx(t) { + t.writable && !t.writableEnded && !t.destroyed && t.end(); + } + Le.from = function(t, e) { + return j5(Le, t, e); + }; + var Kh; + function uv() { + return Kh === undefined && (Kh = {}), Kh; + } + Le.fromWeb = function(t, e) { + return uv().newStreamReadableFromReadableStream(t, e); + }; + Le.toWeb = function(t, e) { + return uv().newReadableStreamFromStreamReadable(t, e); + }; + Le.wrap = function(t, e) { + var r, o; + return new Le({ objectMode: (r = (o = t.readableObjectMode) !== null && o !== undefined ? o : t.objectMode) !== null && r !== undefined ? r : true, ...e, destroy(f, p) { + hf.destroyer(t, f), p(f); + } }).wrap(t); + }; + }); + Jh = T((jI, xv) => { + var Mn = (Oi(), ur(pr)), { ArrayPrototypeSlice: pv, Error: ix, FunctionPrototypeSymbolHasInstance: vv, ObjectDefineProperty: bv, ObjectDefineProperties: nx, ObjectSetPrototypeOf: mv, StringPrototypeToLowerCase: fx, Symbol: ax, SymbolHasInstance: ox } = Tt2(); + xv.exports = st; + st.WritableState = ya; + var { EventEmitter: sx } = ki(), ma = Vo().Stream, { Buffer: es } = Ut2(), is = yn(), { addAbortSignal: hx } = Go(), { getHighWaterMark: ux, getDefaultHighWaterMark: lx } = Xo(), { ERR_INVALID_ARG_TYPE: dx, ERR_METHOD_NOT_IMPLEMENTED: cx, ERR_MULTIPLE_CALLBACK: gv, ERR_STREAM_CANNOT_PIPE: px2, ERR_STREAM_DESTROYED: ga, ERR_STREAM_ALREADY_FINISHED: vx, ERR_STREAM_NULL_VALUES: bx, ERR_STREAM_WRITE_AFTER_END: mx, ERR_UNKNOWN_ENCODING: yv } = Jt().codes, { errorOrDestroy: uf } = is; + mv(st.prototype, ma.prototype); + mv(st, ma); + function $h() { + } + var lf = ax("kOnFinished"); + function ya(t, e, r) { + typeof r != "boolean" && (r = e instanceof Qr2()), this.objectMode = !!(t && t.objectMode), r && (this.objectMode = this.objectMode || !!(t && t.writableObjectMode)), this.highWaterMark = t ? ux(this, t, "writableHighWaterMark", r) : lx(false), this.finalCalled = false, this.needDrain = false, this.ending = false, this.ended = false, this.finished = false, this.destroyed = false; + let o = !!(t && t.decodeStrings === false); + this.decodeStrings = !o, this.defaultEncoding = t && t.defaultEncoding || "utf8", this.length = 0, this.writing = false, this.corked = 0, this.sync = true, this.bufferProcessing = false, this.onwrite = yx.bind(undefined, e), this.writecb = null, this.writelen = 0, this.afterWriteTickInfo = null, rs(this), this.pendingcb = 0, this.constructed = true, this.prefinished = false, this.errorEmitted = false, this.emitClose = !t || t.emitClose !== false, this.autoDestroy = !t || t.autoDestroy !== false, this.errored = null, this.closed = false, this.closeEmitted = false, this[lf] = []; + } + function rs(t) { + t.buffered = [], t.bufferedIndex = 0, t.allBuffers = true, t.allNoop = true; + } + ya.prototype.getBuffer = function() { + return pv(this.buffered, this.bufferedIndex); + }; + bv(ya.prototype, "bufferedRequestCount", { __proto__: null, get() { + return this.buffered.length - this.bufferedIndex; + } }); + function st(t) { + let e = this instanceof Qr2(); + if (!e && !vv(st, this)) + return new st(t); + this._writableState = new ya(t, this, e), t && (typeof t.write == "function" && (this._write = t.write), typeof t.writev == "function" && (this._writev = t.writev), typeof t.destroy == "function" && (this._destroy = t.destroy), typeof t.final == "function" && (this._final = t.final), typeof t.construct == "function" && (this._construct = t.construct), t.signal && hx(t.signal, this)), ma.call(this, t), is.construct(this, () => { + let r = this._writableState; + r.writing || Yh(this, r), Xh(this, r); + }); + } + bv(st, ox, { __proto__: null, value: function(t) { + return vv(this, t) ? true : this !== st ? false : t && t._writableState instanceof ya; + } }); + st.prototype.pipe = function() { + uf(this, new px2); + }; + function wv(t, e, r, o) { + let f = t._writableState; + if (typeof r == "function") + o = r, r = f.defaultEncoding; + else { + if (!r) + r = f.defaultEncoding; + else if (r !== "buffer" && !es.isEncoding(r)) + throw new yv(r); + typeof o != "function" && (o = $h); + } + if (e === null) + throw new bx; + if (!f.objectMode) + if (typeof e == "string") + f.decodeStrings !== false && (e = es.from(e, r), r = "buffer"); + else if (e instanceof es) + r = "buffer"; + else if (ma._isUint8Array(e)) + e = ma._uint8ArrayToBuffer(e), r = "buffer"; + else + throw new dx("chunk", ["string", "Buffer", "Uint8Array"], e); + let p; + return f.ending ? p = new mx : f.destroyed && (p = new ga("write")), p ? (Mn.nextTick(o, p), uf(t, p, true), p) : (f.pendingcb++, gx(t, f, e, r, o)); + } + st.prototype.write = function(t, e, r) { + return wv(this, t, e, r) === true; + }; + st.prototype.cork = function() { + this._writableState.corked++; + }; + st.prototype.uncork = function() { + let t = this._writableState; + t.corked && (t.corked--, t.writing || Yh(this, t)); + }; + st.prototype.setDefaultEncoding = function(e) { + if (typeof e == "string" && (e = fx(e)), !es.isEncoding(e)) + throw new yv(e); + return this._writableState.defaultEncoding = e, this; + }; + function gx(t, e, r, o, f) { + let p = e.objectMode ? 1 : r.length; + e.length += p; + let m = e.length < e.highWaterMark; + return m || (e.needDrain = true), e.writing || e.corked || e.errored || !e.constructed ? (e.buffered.push({ chunk: r, encoding: o, callback: f }), e.allBuffers && o !== "buffer" && (e.allBuffers = false), e.allNoop && f !== $h && (e.allNoop = false)) : (e.writelen = p, e.writecb = f, e.writing = true, e.sync = true, t._write(r, o, e.onwrite), e.sync = false), m && !e.errored && !e.destroyed; + } + function dv(t, e, r, o, f, p, m) { + e.writelen = o, e.writecb = m, e.writing = true, e.sync = true, e.destroyed ? e.onwrite(new ga("write")) : r ? t._writev(f, e.onwrite) : t._write(f, p, e.onwrite), e.sync = false; + } + function cv(t, e, r, o) { + --e.pendingcb, o(r), Gh(e), uf(t, r); + } + function yx(t, e) { + let r = t._writableState, o = r.sync, f = r.writecb; + if (typeof f != "function") { + uf(t, new gv); + return; + } + r.writing = false, r.writecb = null, r.length -= r.writelen, r.writelen = 0, e ? (e.stack, r.errored || (r.errored = e), t._readableState && !t._readableState.errored && (t._readableState.errored = e), o ? Mn.nextTick(cv, t, r, e, f) : cv(t, r, e, f)) : (r.buffered.length > r.bufferedIndex && Yh(t, r), o ? r.afterWriteTickInfo !== null && r.afterWriteTickInfo.cb === f ? r.afterWriteTickInfo.count++ : (r.afterWriteTickInfo = { count: 1, cb: f, stream: t, state: r }, Mn.nextTick(wx, r.afterWriteTickInfo)) : Mv(t, r, 1, f)); + } + function wx({ stream: t, state: e, count: r, cb: o }) { + return e.afterWriteTickInfo = null, Mv(t, e, r, o); + } + function Mv(t, e, r, o) { + for (!e.ending && !t.destroyed && e.length === 0 && e.needDrain && (e.needDrain = false, t.emit("drain"));r-- > 0; ) + e.pendingcb--, o(); + e.destroyed && Gh(e), Xh(t, e); + } + function Gh(t) { + if (t.writing) + return; + for (let f = t.bufferedIndex;f < t.buffered.length; ++f) { + var e; + let { chunk: p, callback: m } = t.buffered[f], y = t.objectMode ? 1 : p.length; + t.length -= y, m((e = t.errored) !== null && e !== undefined ? e : new ga("write")); + } + let r = t[lf].splice(0); + for (let f = 0;f < r.length; f++) { + var o; + r[f]((o = t.errored) !== null && o !== undefined ? o : new ga("end")); + } + rs(t); + } + function Yh(t, e) { + if (e.corked || e.bufferProcessing || e.destroyed || !e.constructed) + return; + let { buffered: r, bufferedIndex: o, objectMode: f } = e, p = r.length - o; + if (!p) + return; + let m = o; + if (e.bufferProcessing = true, p > 1 && t._writev) { + e.pendingcb -= p - 1; + let y = e.allNoop ? $h : (x) => { + for (let S = m;S < r.length; ++S) + r[S].callback(x); + }, M = e.allNoop && m === 0 ? r : pv(r, m); + M.allBuffers = e.allBuffers, dv(t, e, true, e.length, M, "", y), rs(e); + } else { + do { + let { chunk: y, encoding: M, callback: x } = r[m]; + r[m++] = null; + let S = f ? 1 : y.length; + dv(t, e, false, S, y, M, x); + } while (m < r.length && !e.writing); + m === r.length ? rs(e) : m > 256 ? (r.splice(0, m), e.bufferedIndex = 0) : e.bufferedIndex = m; + } + e.bufferProcessing = false; + } + st.prototype._write = function(t, e, r) { + if (this._writev) + this._writev([{ chunk: t, encoding: e }], r); + else + throw new cx("_write()"); + }; + st.prototype._writev = null; + st.prototype.end = function(t, e, r) { + let o = this._writableState; + typeof t == "function" ? (r = t, t = null, e = null) : typeof e == "function" && (r = e, e = null); + let f; + if (t != null) { + let p = wv(this, t, e); + p instanceof ix && (f = p); + } + return o.corked && (o.corked = 1, this.uncork()), f || (!o.errored && !o.ending ? (o.ending = true, Xh(this, o, true), o.ended = true) : o.finished ? f = new vx("end") : o.destroyed && (f = new ga("end"))), typeof r == "function" && (f || o.finished ? Mn.nextTick(r, f) : o[lf].push(r)), this; + }; + function ts(t) { + return t.ending && !t.destroyed && t.constructed && t.length === 0 && !t.errored && t.buffered.length === 0 && !t.finished && !t.writing && !t.errorEmitted && !t.closeEmitted; + } + function Mx(t, e) { + let r = false; + function o(f) { + if (r) { + uf(t, f ?? gv()); + return; + } + if (r = true, e.pendingcb--, f) { + let p = e[lf].splice(0); + for (let m = 0;m < p.length; m++) + p[m](f); + uf(t, f, e.sync); + } else + ts(e) && (e.prefinished = true, t.emit("prefinish"), e.pendingcb++, Mn.nextTick(Vh, t, e)); + } + e.sync = true, e.pendingcb++; + try { + t._final(o); + } catch (f) { + o(f); + } + e.sync = false; + } + function _x2(t, e) { + !e.prefinished && !e.finalCalled && (typeof t._final == "function" && !e.destroyed ? (e.finalCalled = true, Mx(t, e)) : (e.prefinished = true, t.emit("prefinish"))); + } + function Xh(t, e, r) { + ts(e) && (_x2(t, e), e.pendingcb === 0 && (r ? (e.pendingcb++, Mn.nextTick((o, f) => { + ts(f) ? Vh(o, f) : f.pendingcb--; + }, t, e)) : ts(e) && (e.pendingcb++, Vh(t, e)))); + } + function Vh(t, e) { + e.pendingcb--, e.finished = true; + let r = e[lf].splice(0); + for (let o = 0;o < r.length; o++) + r[o](); + if (t.emit("finish"), e.autoDestroy) { + let o = t._readableState; + (!o || o.autoDestroy && (o.endEmitted || o.readable === false)) && t.destroy(); + } + } + nx(st.prototype, { closed: { __proto__: null, get() { + return this._writableState ? this._writableState.closed : false; + } }, destroyed: { __proto__: null, get() { + return this._writableState ? this._writableState.destroyed : false; + }, set(t) { + this._writableState && (this._writableState.destroyed = t); + } }, writable: { __proto__: null, get() { + let t = this._writableState; + return !!t && t.writable !== false && !t.destroyed && !t.errored && !t.ending && !t.ended; + }, set(t) { + this._writableState && (this._writableState.writable = !!t); + } }, writableFinished: { __proto__: null, get() { + return this._writableState ? this._writableState.finished : false; + } }, writableObjectMode: { __proto__: null, get() { + return this._writableState ? this._writableState.objectMode : false; + } }, writableBuffer: { __proto__: null, get() { + return this._writableState && this._writableState.getBuffer(); + } }, writableEnded: { __proto__: null, get() { + return this._writableState ? this._writableState.ending : false; + } }, writableNeedDrain: { __proto__: null, get() { + let t = this._writableState; + return t ? !t.destroyed && !t.ending && t.needDrain : false; + } }, writableHighWaterMark: { __proto__: null, get() { + return this._writableState && this._writableState.highWaterMark; + } }, writableCorked: { __proto__: null, get() { + return this._writableState ? this._writableState.corked : 0; + } }, writableLength: { __proto__: null, get() { + return this._writableState && this._writableState.length; + } }, errored: { __proto__: null, enumerable: false, get() { + return this._writableState ? this._writableState.errored : null; + } }, writableAborted: { __proto__: null, enumerable: false, get: function() { + return !!(this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished); + } } }); + var xx = is.destroy; + st.prototype.destroy = function(t, e) { + let r = this._writableState; + return !r.destroyed && (r.bufferedIndex < r.buffered.length || r[lf].length) && Mn.nextTick(Gh, r), xx.call(this, t, e), this; + }; + st.prototype._undestroy = is.undestroy; + st.prototype._destroy = function(t, e) { + e(t); + }; + st.prototype[sx.captureRejectionSymbol] = function(t) { + this.destroy(t); + }; + var Zh; + function _v() { + return Zh === undefined && (Zh = {}), Zh; + } + st.fromWeb = function(t, e) { + return _v().newStreamWritableFromWritableStream(t, e); + }; + st.toWeb = function(t) { + return _v().newWritableStreamFromStreamWritable(t); + }; + }); + Dv = T((ZI, Nv) => { + var Qh = (Oi(), ur(pr)), Sx = Ut2(), { isReadable: Ex, isWritable: Ax, isIterable: Sv, isNodeStream: Rx, isReadableNodeStream: Ev, isWritableNodeStream: Av, isDuplexNodeStream: Bx } = Fi(), Rv = Ui(), { AbortError: Lv, codes: { ERR_INVALID_ARG_TYPE: qx, ERR_INVALID_RETURN_VALUE: Bv } } = Jt(), { destroyer: df } = yn(), Ix = Qr2(), Tx = ba(), { createDeferredPromise: qv } = Gr(), Iv = Fh(), Tv = globalThis.Blob || Sx.Blob, kx = typeof Tv < "u" ? function(e) { + return e instanceof Tv; + } : function(e) { + return false; + }, Lx = globalThis.AbortController || No().AbortController, { FunctionPrototypeCall: kv } = Tt2(), _n = class extends Ix { + constructor(e) { + super(e), e?.readable === false && (this._readableState.readable = false, this._readableState.ended = true, this._readableState.endEmitted = true), e?.writable === false && (this._writableState.writable = false, this._writableState.ending = true, this._writableState.ended = true, this._writableState.finished = true); + } + }; + Nv.exports = function t(e, r) { + if (Bx(e)) + return e; + if (Ev(e)) + return ns({ readable: e }); + if (Av(e)) + return ns({ writable: e }); + if (Rx(e)) + return ns({ writable: false, readable: false }); + if (typeof e == "function") { + let { value: f, write: p, final: m, destroy: y } = Nx(e); + if (Sv(f)) + return Iv(_n, f, { objectMode: true, write: p, final: m, destroy: y }); + let M = f?.then; + if (typeof M == "function") { + let x, S = kv(M, f, (E2) => { + if (E2 != null) + throw new Bv("nully", "body", E2); + }, (E2) => { + df(x, E2); + }); + return x = new _n({ objectMode: true, readable: false, write: p, final(E2) { + m(async () => { + try { + await S, Qh.nextTick(E2, null); + } catch (B) { + Qh.nextTick(E2, B); + } + }); + }, destroy: y }); + } + throw new Bv("Iterable, AsyncIterable or AsyncFunction", r, f); + } + if (kx(e)) + return t(e.arrayBuffer()); + if (Sv(e)) + return Iv(_n, e, { objectMode: true, writable: false }); + if (typeof e?.writable == "object" || typeof e?.readable == "object") { + let f = e != null && e.readable ? Ev(e?.readable) ? e?.readable : t(e.readable) : undefined, p = e != null && e.writable ? Av(e?.writable) ? e?.writable : t(e.writable) : undefined; + return ns({ readable: f, writable: p }); + } + let o = e?.then; + if (typeof o == "function") { + let f; + return kv(o, e, (p) => { + p != null && f.push(p), f.push(null); + }, (p) => { + df(f, p); + }), f = new _n({ objectMode: true, writable: false, read() { + } }); + } + throw new qx(r, ["Blob", "ReadableStream", "WritableStream", "Stream", "Iterable", "AsyncIterable", "Function", "{ readable, writable } pair", "Promise"], e); + }; + function Nx(t) { + let { promise: e, resolve: r } = qv(), o = new Lx, f = o.signal; + return { value: t(async function* () { + for (;; ) { + let m = e; + e = null; + let { chunk: y, done: M, cb: x } = await m; + if (Qh.nextTick(x), M) + return; + if (f.aborted) + throw new Lv(undefined, { cause: f.reason }); + ({ promise: e, resolve: r } = qv()), yield y; + } + }(), { signal: f }), write(m, y, M) { + let x = r; + r = null, x({ chunk: m, done: false, cb: M }); + }, final(m) { + let y = r; + r = null, y({ done: true, cb: m }); + }, destroy(m, y) { + o.abort(), y(m); + } }; + } + function ns(t) { + let e = t.readable && typeof t.readable.read != "function" ? Tx.wrap(t.readable) : t.readable, r = t.writable, o = !!Ex(e), f = !!Ax(r), p, m, y, M, x; + function S(E2) { + let B = M; + M = null, B ? B(E2) : E2 ? x.destroy(E2) : !o && !f && x.destroy(); + } + return x = new _n({ readableObjectMode: !!(e != null && e.readableObjectMode), writableObjectMode: !!(r != null && r.writableObjectMode), readable: o, writable: f }), f && (Rv(r, (E2) => { + f = false, E2 && df(e, E2), S(E2); + }), x._write = function(E2, B, q) { + r.write(E2, B) ? q() : p = q; + }, x._final = function(E2) { + r.end(), m = E2; + }, r.on("drain", function() { + if (p) { + let E2 = p; + p = null, E2(); + } + }), r.on("finish", function() { + if (m) { + let E2 = m; + m = null, E2(); + } + })), o && (Rv(e, (E2) => { + o = false, E2 && df(e, E2), S(E2); + }), e.on("readable", function() { + if (y) { + let E2 = y; + y = null, E2(); + } + }), e.on("end", function() { + x.push(null); + }), x._read = function() { + for (;; ) { + let E2 = e.read(); + if (E2 === null) { + y = x._read; + return; + } + if (!x.push(E2)) + return; + } + }), x._destroy = function(E2, B) { + !E2 && M !== null && (E2 = new Lv), y = null, p = null, m = null, M === null ? B(E2) : (M = B, df(r, E2), df(e, E2)); + }, x; + } + }); + Qr2 = T((VI, Ov) => { + var { ObjectDefineProperties: Dx, ObjectGetOwnPropertyDescriptor: bi, ObjectKeys: Px, ObjectSetPrototypeOf: Pv } = Tt2(); + Ov.exports = kr; + var ru = ba(), vr = Jh(); + Pv(kr.prototype, ru.prototype); + Pv(kr, ru); + { + let t = Px(vr.prototype); + for (let e = 0;e < t.length; e++) { + let r = t[e]; + kr.prototype[r] || (kr.prototype[r] = vr.prototype[r]); + } + } + function kr(t) { + if (!(this instanceof kr)) + return new kr(t); + ru.call(this, t), vr.call(this, t), t ? (this.allowHalfOpen = t.allowHalfOpen !== false, t.readable === false && (this._readableState.readable = false, this._readableState.ended = true, this._readableState.endEmitted = true), t.writable === false && (this._writableState.writable = false, this._writableState.ending = true, this._writableState.ended = true, this._writableState.finished = true)) : this.allowHalfOpen = true; + } + Dx(kr.prototype, { writable: { __proto__: null, ...bi(vr.prototype, "writable") }, writableHighWaterMark: { __proto__: null, ...bi(vr.prototype, "writableHighWaterMark") }, writableObjectMode: { __proto__: null, ...bi(vr.prototype, "writableObjectMode") }, writableBuffer: { __proto__: null, ...bi(vr.prototype, "writableBuffer") }, writableLength: { __proto__: null, ...bi(vr.prototype, "writableLength") }, writableFinished: { __proto__: null, ...bi(vr.prototype, "writableFinished") }, writableCorked: { __proto__: null, ...bi(vr.prototype, "writableCorked") }, writableEnded: { __proto__: null, ...bi(vr.prototype, "writableEnded") }, writableNeedDrain: { __proto__: null, ...bi(vr.prototype, "writableNeedDrain") }, destroyed: { __proto__: null, get() { + return this._readableState === undefined || this._writableState === undefined ? false : this._readableState.destroyed && this._writableState.destroyed; + }, set(t) { + this._readableState && this._writableState && (this._readableState.destroyed = t, this._writableState.destroyed = t); + } } }); + var eu; + function Cv() { + return eu === undefined && (eu = {}), eu; + } + kr.fromWeb = function(t, e) { + return Cv().newStreamDuplexFromReadableWritablePair(t, e); + }; + kr.toWeb = function(t) { + return Cv().newReadableWritablePairFromDuplex(t); + }; + var tu; + kr.from = function(t) { + return tu || (tu = Dv()), tu(t, "body"); + }; + }); + fu = T(($I, Uv) => { + var { ObjectSetPrototypeOf: Fv, Symbol: Cx } = Tt2(); + Uv.exports = mi; + var { ERR_METHOD_NOT_IMPLEMENTED: Ox } = Jt().codes, nu = Qr2(), { getHighWaterMark: Fx } = Xo(); + Fv(mi.prototype, nu.prototype); + Fv(mi, nu); + var wa = Cx("kCallback"); + function mi(t) { + if (!(this instanceof mi)) + return new mi(t); + let e = t ? Fx(this, t, "readableHighWaterMark", true) : null; + e === 0 && (t = { ...t, highWaterMark: null, readableHighWaterMark: e, writableHighWaterMark: t.writableHighWaterMark || 0 }), nu.call(this, t), this._readableState.sync = false, this[wa] = null, t && (typeof t.transform == "function" && (this._transform = t.transform), typeof t.flush == "function" && (this._flush = t.flush)), this.on("prefinish", Ux); + } + function iu(t) { + typeof this._flush == "function" && !this.destroyed ? this._flush((e, r) => { + if (e) { + t ? t(e) : this.destroy(e); + return; + } + r != null && this.push(r), this.push(null), t && t(); + }) : (this.push(null), t && t()); + } + function Ux() { + this._final !== iu && iu.call(this); + } + mi.prototype._final = iu; + mi.prototype._transform = function(t, e, r) { + throw new Ox("_transform()"); + }; + mi.prototype._write = function(t, e, r) { + let o = this._readableState, f = this._writableState, p = o.length; + this._transform(t, e, (m, y) => { + if (m) { + r(m); + return; + } + y != null && this.push(y), f.ended || p === o.length || o.length < o.highWaterMark ? r() : this[wa] = r; + }); + }; + mi.prototype._read = function() { + if (this[wa]) { + let t = this[wa]; + this[wa] = null, t(); + } + }; + }); + ou = T((GI, Hv) => { + var { ObjectSetPrototypeOf: zv } = Tt2(); + Hv.exports = cf; + var au = fu(); + zv(cf.prototype, au.prototype); + zv(cf, au); + function cf(t) { + if (!(this instanceof cf)) + return new cf(t); + au.call(this, t); + } + cf.prototype._transform = function(t, e, r) { + r(null, t); + }; + }); + os = T((YI, Gv) => { + var fs = (Oi(), ur(pr)), { ArrayIsArray: zx, Promise: Hx, SymbolAsyncIterator: Wx } = Tt2(), as = Ui(), { once: Kx } = Gr(), jx = yn(), Wv = Qr2(), { aggregateTwoErrors: Zx, codes: { ERR_INVALID_ARG_TYPE: Vv, ERR_INVALID_RETURN_VALUE: su, ERR_MISSING_ARGS: Vx, ERR_STREAM_DESTROYED: $x, ERR_STREAM_PREMATURE_CLOSE: Gx }, AbortError: Yx } = Jt(), { validateFunction: Xx, validateAbortSignal: Jx } = pa(), { isIterable: pf, isReadable: hu, isReadableNodeStream: du, isNodeStream: Kv } = Fi(), Qx = globalThis.AbortController || No().AbortController, uu, lu; + function jv(t, e, r) { + let o = false; + t.on("close", () => { + o = true; + }); + let f = as(t, { readable: e, writable: r }, (p) => { + o = !p; + }); + return { destroy: (p) => { + o || (o = true, jx.destroyer(t, p || new $x("pipe"))); + }, cleanup: f }; + } + function e7(t) { + return Xx(t[t.length - 1], "streams[stream.length - 1]"), t.pop(); + } + function t7(t) { + if (pf(t)) + return t; + if (du(t)) + return r7(t); + throw new Vv("val", ["Readable", "Iterable", "AsyncIterable"], t); + } + async function* r7(t) { + lu || (lu = ba()), yield* lu.prototype[Wx].call(t); + } + async function Zv(t, e, r, { end: o }) { + let f, p = null, m = (x) => { + if (x && (f = x), p) { + let S = p; + p = null, S(); + } + }, y = () => new Hx((x, S) => { + f ? S(f) : p = () => { + f ? S(f) : x(); + }; + }); + e.on("drain", m); + let M = as(e, { readable: false }, m); + try { + e.writableNeedDrain && await y(); + for await (let x of t) + e.write(x) || await y(); + o && e.end(), await y(), r(); + } catch (x) { + r(f !== x ? Zx(f, x) : x); + } finally { + M(), e.off("drain", m); + } + } + function i7(...t) { + return $v(t, Kx(e7(t))); + } + function $v(t, e, r) { + if (t.length === 1 && zx(t[0]) && (t = t[0]), t.length < 2) + throw new Vx("streams"); + let o = new Qx, f = o.signal, p = r?.signal, m = []; + Jx(p, "options.signal"); + function y() { + q(new Yx); + } + p?.addEventListener("abort", y); + let M, x, S = [], E2 = 0; + function B(N) { + q(N, --E2 === 0); + } + function q(N, we) { + if (N && (!M || M.code === "ERR_STREAM_PREMATURE_CLOSE") && (M = N), !(!M && !we)) { + for (;S.length; ) + S.shift()(M); + p?.removeEventListener("abort", y), o.abort(), we && (M || m.forEach((ye) => ye()), fs.nextTick(e, M, x)); + } + } + let L; + for (let N = 0;N < t.length; N++) { + let we = t[N], ye = N < t.length - 1, xe = N > 0, Re = ye || r?.end !== false, Ee = N === t.length - 1; + if (Kv(we)) { + let Ae = function(P) { + P && P.name !== "AbortError" && P.code !== "ERR_STREAM_PREMATURE_CLOSE" && B(P); + }; + var _e = Ae; + if (Re) { + let { destroy: P, cleanup: Se2 } = jv(we, ye, xe); + S.push(P), hu(we) && Ee && m.push(Se2); + } + we.on("error", Ae), hu(we) && Ee && m.push(() => { + we.removeListener("error", Ae); + }); + } + if (N === 0) + if (typeof we == "function") { + if (L = we({ signal: f }), !pf(L)) + throw new su("Iterable, AsyncIterable or Stream", "source", L); + } else + pf(we) || du(we) ? L = we : L = Wv.from(we); + else if (typeof we == "function") + if (L = t7(L), L = we(L, { signal: f }), ye) { + if (!pf(L, true)) + throw new su("AsyncIterable", `transform[${N - 1}]`, L); + } else { + var ge; + uu || (uu = ou()); + let Ae = new uu({ objectMode: true }), P = (ge = L) === null || ge === undefined ? undefined : ge.then; + if (typeof P == "function") + E2++, P.call(L, (i) => { + x = i, i != null && Ae.write(i), Re && Ae.end(), fs.nextTick(B); + }, (i) => { + Ae.destroy(i), fs.nextTick(B, i); + }); + else if (pf(L, true)) + E2++, Zv(L, Ae, B, { end: Re }); + else + throw new su("AsyncIterable or Promise", "destination", L); + L = Ae; + let { destroy: Se2, cleanup: v } = jv(L, false, true); + S.push(Se2), Ee && m.push(v); + } + else if (Kv(we)) { + if (du(L)) { + E2 += 2; + let Ae = n7(L, we, B, { end: Re }); + hu(we) && Ee && m.push(Ae); + } else if (pf(L)) + E2++, Zv(L, we, B, { end: Re }); + else + throw new Vv("val", ["Readable", "Iterable", "AsyncIterable"], L); + L = we; + } else + L = Wv.from(we); + } + return (f != null && f.aborted || p != null && p.aborted) && fs.nextTick(y), L; + } + function n7(t, e, r, { end: o }) { + let f = false; + return e.on("close", () => { + f || r(new Gx); + }), t.pipe(e, { end: o }), o ? t.once("end", () => { + f = true, e.end(); + }) : r(), as(t, { readable: true, writable: false }, (p) => { + let m = t._readableState; + p && p.code === "ERR_STREAM_PREMATURE_CLOSE" && m && m.ended && !m.errored && !m.errorEmitted ? t.once("end", r).once("error", r) : r(p); + }), as(e, { readable: false, writable: true }, r); + } + Gv.exports = { pipelineImpl: $v, pipeline: i7 }; + }); + eb = T((XI, Qv) => { + var { pipeline: f7 } = os(), ss = Qr2(), { destroyer: a7 } = yn(), { isNodeStream: o7, isReadable: Yv, isWritable: Xv } = Fi(), { AbortError: s7, codes: { ERR_INVALID_ARG_VALUE: Jv, ERR_MISSING_ARGS: h7 } } = Jt(); + Qv.exports = function(...e) { + if (e.length === 0) + throw new h7("streams"); + if (e.length === 1) + return ss.from(e[0]); + let r = [...e]; + if (typeof e[0] == "function" && (e[0] = ss.from(e[0])), typeof e[e.length - 1] == "function") { + let q = e.length - 1; + e[q] = ss.from(e[q]); + } + for (let q = 0;q < e.length; ++q) + if (!!o7(e[q])) { + if (q < e.length - 1 && !Yv(e[q])) + throw new Jv(`streams[${q}]`, r[q], "must be readable"); + if (q > 0 && !Xv(e[q])) + throw new Jv(`streams[${q}]`, r[q], "must be writable"); + } + let o, f, p, m, y; + function M(q) { + let L = m; + m = null, L ? L(q) : q ? y.destroy(q) : !B && !E2 && y.destroy(); + } + let x = e[0], S = f7(e, M), E2 = !!Xv(x), B = !!Yv(S); + return y = new ss({ writableObjectMode: !!(x != null && x.writableObjectMode), readableObjectMode: !!(S != null && S.writableObjectMode), writable: E2, readable: B }), E2 && (y._write = function(q, L, ge) { + x.write(q, L) ? ge() : o = ge; + }, y._final = function(q) { + x.end(), f = q; + }, x.on("drain", function() { + if (o) { + let q = o; + o = null, q(); + } + }), S.on("finish", function() { + if (f) { + let q = f; + f = null, q(); + } + })), B && (S.on("readable", function() { + if (p) { + let q = p; + p = null, q(); + } + }), S.on("end", function() { + y.push(null); + }), y._read = function() { + for (;; ) { + let q = S.read(); + if (q === null) { + p = y._read; + return; + } + if (!y.push(q)) + return; + } + }), y._destroy = function(q, L) { + !q && m !== null && (q = new s7), p = null, o = null, f = null, m === null ? L(q) : (m = L, a7(S, q)); + }, y; + }; + }); + cu = T((JI, tb) => { + var { ArrayPrototypePop: u7, Promise: l7 } = Tt2(), { isIterable: d7, isNodeStream: c7 } = Fi(), { pipelineImpl: p7 } = os(), { finished: v7 } = Ui(); + function b7(...t) { + return new l7((e, r) => { + let o, f, p = t[t.length - 1]; + if (p && typeof p == "object" && !c7(p) && !d7(p)) { + let m = u7(t); + o = m.signal, f = m.end; + } + p7(t, (m, y) => { + m ? r(m) : e(y); + }, { signal: o, end: f }); + }); + } + tb.exports = { finished: v7, pipeline: b7 }; + }); + lb = T((QI, ub) => { + var { Buffer: m7 } = Ut2(), { ObjectDefineProperty: gi, ObjectKeys: nb, ReflectApply: fb } = Tt2(), { promisify: { custom: ab } } = Gr(), { streamReturningOperators: rb, promiseReturningOperators: ib } = k1(), { codes: { ERR_ILLEGAL_CONSTRUCTOR: ob2 } } = Jt(), g7 = eb(), { pipeline: sb } = os(), { destroyer: y7 } = yn(), hb = Ui(), pu = cu(), vu = Fi(), ct = ub.exports = Vo().Stream; + ct.isDisturbed = vu.isDisturbed; + ct.isErrored = vu.isErrored; + ct.isReadable = vu.isReadable; + ct.Readable = ba(); + for (let t of nb(rb)) { + let r = function(...o) { + if (new.target) + throw ob2(); + return ct.Readable.from(fb(e, this, o)); + }; + M7 = r; + let e = rb[t]; + gi(r, "name", { __proto__: null, value: e.name }), gi(r, "length", { __proto__: null, value: e.length }), gi(ct.Readable.prototype, t, { __proto__: null, value: r, enumerable: false, configurable: true, writable: true }); + } + var M7; + for (let t of nb(ib)) { + let r = function(...f) { + if (new.target) + throw ob2(); + return fb(e, this, f); + }; + M7 = r; + let e = ib[t]; + gi(r, "name", { __proto__: null, value: e.name }), gi(r, "length", { __proto__: null, value: e.length }), gi(ct.Readable.prototype, t, { __proto__: null, value: r, enumerable: false, configurable: true, writable: true }); + } + var M7; + ct.Writable = Jh(); + ct.Duplex = Qr2(); + ct.Transform = fu(); + ct.PassThrough = ou(); + ct.pipeline = sb; + var { addAbortSignal: w7 } = Go(); + ct.addAbortSignal = w7; + ct.finished = hb; + ct.destroy = y7; + ct.compose = g7; + gi(ct, "promises", { __proto__: null, configurable: true, enumerable: true, get() { + return pu; + } }); + gi(sb, ab, { __proto__: null, enumerable: true, get() { + return pu.pipeline; + } }); + gi(hb, ab, { __proto__: null, enumerable: true, get() { + return pu.finished; + } }); + ct.Stream = ct; + ct._isUint8Array = function(e) { + return e instanceof Uint8Array; + }; + ct._uint8ArrayToBuffer = function(e) { + return m7.from(e.buffer, e.byteOffset, e.byteLength); + }; + }); + bu = T((eT, pt) => { + var Lt = lb(), _72 = cu(), x7 = Lt.Readable.destroy; + pt.exports = Lt.Readable; + pt.exports._uint8ArrayToBuffer = Lt._uint8ArrayToBuffer; + pt.exports._isUint8Array = Lt._isUint8Array; + pt.exports.isDisturbed = Lt.isDisturbed; + pt.exports.isErrored = Lt.isErrored; + pt.exports.isReadable = Lt.isReadable; + pt.exports.Readable = Lt.Readable; + pt.exports.Writable = Lt.Writable; + pt.exports.Duplex = Lt.Duplex; + pt.exports.Transform = Lt.Transform; + pt.exports.PassThrough = Lt.PassThrough; + pt.exports.addAbortSignal = Lt.addAbortSignal; + pt.exports.finished = Lt.finished; + pt.exports.destroy = Lt.destroy; + pt.exports.destroy = x7; + pt.exports.pipeline = Lt.pipeline; + pt.exports.compose = Lt.compose; + Object.defineProperty(Lt, "promises", { configurable: true, enumerable: true, get() { + return _72; + } }); + pt.exports.Stream = Lt.Stream; + pt.exports.default = pt.exports; + }); + vf = {}; + Ja(vf, { default: () => S7 }); + db = R0(() => { + ot(vf, rn2(bu())); + S7 = rn2(bu()); + }); + yi = T((rT, vb) => { + var cb = Te().Buffer, pb = (db(), ur(vf)).Transform, E7 = co().StringDecoder, A7 = Ie(); + function Lr(t) { + pb.call(this), this.hashMode = typeof t == "string", this.hashMode ? this[t] = this._finalOrDigest : this.final = this._finalOrDigest, this._final && (this.__final = this._final, this._final = null), this._decoder = null, this._encoding = null; + } + A7(Lr, pb); + Lr.prototype.update = function(t, e, r) { + typeof t == "string" && (t = cb.from(t, e)); + var o = this._update(t); + return this.hashMode ? this : (r && (o = this._toString(o, r)), o); + }; + Lr.prototype.setAutoPadding = function() { + }; + Lr.prototype.getAuthTag = function() { + throw new Error("trying to get auth tag in unsupported state"); + }; + Lr.prototype.setAuthTag = function() { + throw new Error("trying to set auth tag in unsupported state"); + }; + Lr.prototype.setAAD = function() { + throw new Error("trying to set aad in unsupported state"); + }; + Lr.prototype._transform = function(t, e, r) { + var o; + try { + this.hashMode ? this._update(t) : this.push(this._update(t)); + } catch (f) { + o = f; + } finally { + r(o); + } + }; + Lr.prototype._flush = function(t) { + var e; + try { + this.push(this.__final()); + } catch (r) { + e = r; + } + t(e); + }; + Lr.prototype._finalOrDigest = function(t) { + var e = this.__final() || cb.alloc(0); + return t && (e = this._toString(e, t, true)), e; + }; + Lr.prototype._toString = function(t, e, r) { + if (this._decoder || (this._decoder = new E7(e), this._encoding = e), this._encoding !== e) + throw new Error("can't switch encodings"); + var o = this._decoder.write(t); + return r && (o += this._decoder.end()), o; + }; + vb.exports = Lr; + }); + bf = T((iT, mb) => { + var R7 = Ie(), B7 = Ao(), q7 = Bo(), I7 = ko(), bb = yi(); + function hs(t) { + bb.call(this, "digest"), this._hash = t; + } + R7(hs, bb); + hs.prototype._update = function(t) { + this._hash.update(t); + }; + hs.prototype._final = function() { + return this._hash.digest(); + }; + mb.exports = function(e) { + return e = e.toLowerCase(), e === "md5" ? new B7 : e === "rmd160" || e === "ripemd160" ? new q7 : new hs(I7(e)); + }; + }); + wb = T((nT, yb) => { + var T7 = Ie(), xn = Te().Buffer, gb = yi(), k7 = xn.alloc(128), mf = 64; + function us(t, e) { + gb.call(this, "digest"), typeof e == "string" && (e = xn.from(e)), this._alg = t, this._key = e, e.length > mf ? e = t(e) : e.length < mf && (e = xn.concat([e, k7], mf)); + for (var r = this._ipad = xn.allocUnsafe(mf), o = this._opad = xn.allocUnsafe(mf), f = 0;f < mf; f++) + r[f] = e[f] ^ 54, o[f] = e[f] ^ 92; + this._hash = [r]; + } + T7(us, gb); + us.prototype._update = function(t) { + this._hash.push(t); + }; + us.prototype._final = function() { + var t = this._alg(xn.concat(this._hash)); + return this._alg(xn.concat([this._opad, t])); + }; + yb.exports = us; + }); + mu = T((fT, Mb) => { + var L7 = Ao(); + Mb.exports = function(t) { + return new L7().update(t).digest(); + }; + }); + wu = T((aT, xb) => { + var N7 = Ie(), D7 = wb(), _b = yi(), Ma = Te().Buffer, P7 = mu(), gu = Bo(), yu = ko(), C7 = Ma.alloc(128); + function _a(t, e) { + _b.call(this, "digest"), typeof e == "string" && (e = Ma.from(e)); + var r = t === "sha512" || t === "sha384" ? 128 : 64; + if (this._alg = t, this._key = e, e.length > r) { + var o = t === "rmd160" ? new gu : yu(t); + e = o.update(e).digest(); + } else + e.length < r && (e = Ma.concat([e, C7], r)); + for (var f = this._ipad = Ma.allocUnsafe(r), p = this._opad = Ma.allocUnsafe(r), m = 0;m < r; m++) + f[m] = e[m] ^ 54, p[m] = e[m] ^ 92; + this._hash = t === "rmd160" ? new gu : yu(t), this._hash.update(f); + } + N7(_a, _b); + _a.prototype._update = function(t) { + this._hash.update(t); + }; + _a.prototype._final = function() { + var t = this._hash.digest(), e = this._alg === "rmd160" ? new gu : yu(this._alg); + return e.update(this._opad).update(t).digest(); + }; + xb.exports = function(e, r) { + return e = e.toLowerCase(), e === "rmd160" || e === "ripemd160" ? new _a("rmd160", r) : e === "md5" ? new D7(P7, r) : new _a(e, r); + }; + }); + Mu = T((oT, O7) => { + O7.exports = { sha224WithRSAEncryption: { sign: "rsa", hash: "sha224", id: "302d300d06096086480165030402040500041c" }, "RSA-SHA224": { sign: "ecdsa/rsa", hash: "sha224", id: "302d300d06096086480165030402040500041c" }, sha256WithRSAEncryption: { sign: "rsa", hash: "sha256", id: "3031300d060960864801650304020105000420" }, "RSA-SHA256": { sign: "ecdsa/rsa", hash: "sha256", id: "3031300d060960864801650304020105000420" }, sha384WithRSAEncryption: { sign: "rsa", hash: "sha384", id: "3041300d060960864801650304020205000430" }, "RSA-SHA384": { sign: "ecdsa/rsa", hash: "sha384", id: "3041300d060960864801650304020205000430" }, sha512WithRSAEncryption: { sign: "rsa", hash: "sha512", id: "3051300d060960864801650304020305000440" }, "RSA-SHA512": { sign: "ecdsa/rsa", hash: "sha512", id: "3051300d060960864801650304020305000440" }, "RSA-SHA1": { sign: "rsa", hash: "sha1", id: "3021300906052b0e03021a05000414" }, "ecdsa-with-SHA1": { sign: "ecdsa", hash: "sha1", id: "" }, sha256: { sign: "ecdsa", hash: "sha256", id: "" }, sha224: { sign: "ecdsa", hash: "sha224", id: "" }, sha384: { sign: "ecdsa", hash: "sha384", id: "" }, sha512: { sign: "ecdsa", hash: "sha512", id: "" }, "DSA-SHA": { sign: "dsa", hash: "sha1", id: "" }, "DSA-SHA1": { sign: "dsa", hash: "sha1", id: "" }, DSA: { sign: "dsa", hash: "sha1", id: "" }, "DSA-WITH-SHA224": { sign: "dsa", hash: "sha224", id: "" }, "DSA-SHA224": { sign: "dsa", hash: "sha224", id: "" }, "DSA-WITH-SHA256": { sign: "dsa", hash: "sha256", id: "" }, "DSA-SHA256": { sign: "dsa", hash: "sha256", id: "" }, "DSA-WITH-SHA384": { sign: "dsa", hash: "sha384", id: "" }, "DSA-SHA384": { sign: "dsa", hash: "sha384", id: "" }, "DSA-WITH-SHA512": { sign: "dsa", hash: "sha512", id: "" }, "DSA-SHA512": { sign: "dsa", hash: "sha512", id: "" }, "DSA-RIPEMD160": { sign: "dsa", hash: "rmd160", id: "" }, ripemd160WithRSA: { sign: "rsa", hash: "rmd160", id: "3021300906052b2403020105000414" }, "RSA-RIPEMD160": { sign: "rsa", hash: "rmd160", id: "3021300906052b2403020105000414" }, md5WithRSAEncryption: { sign: "rsa", hash: "md5", id: "3020300c06082a864886f70d020505000410" }, "RSA-MD5": { sign: "rsa", hash: "md5", id: "3020300c06082a864886f70d020505000410" } }; + }); + Eb = T((sT, Sb) => { + Sb.exports = Mu(); + }); + _u = T((hT, Ab) => { + var F7 = Math.pow(2, 30) - 1; + Ab.exports = function(t, e) { + if (typeof t != "number") + throw new TypeError("Iterations not a number"); + if (t < 0) + throw new TypeError("Bad iterations"); + if (typeof e != "number") + throw new TypeError("Key length not a number"); + if (e < 0 || e > F7 || e !== e) + throw new TypeError("Bad key length"); + }; + }); + xu = T((uT, Bb) => { + var ls; + global.process && global.process.browser ? ls = "utf-8" : global.process && global.process.version ? (Rb = parseInt(process.version.split(".")[0].slice(1), 10), ls = Rb >= 6 ? "utf-8" : "binary") : ls = "utf-8"; + var Rb; + Bb.exports = ls; + }); + Eu = T((lT, qb) => { + var Su = Te().Buffer; + qb.exports = function(t, e, r) { + if (Su.isBuffer(t)) + return t; + if (typeof t == "string") + return Su.from(t, e); + if (ArrayBuffer.isView(t)) + return Su.from(t.buffer); + throw new TypeError(r + " must be a string, a Buffer, a typed array or a DataView"); + }; + }); + Au = T((dT, Lb) => { + var U7 = mu(), z7 = Bo(), H7 = ko(), Sn = Te().Buffer, W7 = _u(), Ib = xu(), Tb = Eu(), K7 = Sn.alloc(128), ds = { md5: 16, sha1: 20, sha224: 28, sha256: 32, sha384: 48, sha512: 64, rmd160: 20, ripemd160: 20 }; + function kb(t, e, r) { + var o = j7(t), f = t === "sha512" || t === "sha384" ? 128 : 64; + e.length > f ? e = o(e) : e.length < f && (e = Sn.concat([e, K7], f)); + for (var p = Sn.allocUnsafe(f + ds[t]), m = Sn.allocUnsafe(f + ds[t]), y = 0;y < f; y++) + p[y] = e[y] ^ 54, m[y] = e[y] ^ 92; + var M = Sn.allocUnsafe(f + r + 4); + p.copy(M, 0, 0, f), this.ipad1 = M, this.ipad2 = p, this.opad = m, this.alg = t, this.blocksize = f, this.hash = o, this.size = ds[t]; + } + kb.prototype.run = function(t, e) { + t.copy(e, this.blocksize); + var r = this.hash(e); + return r.copy(this.opad, this.blocksize), this.hash(this.opad); + }; + function j7(t) { + function e(o) { + return H7(t).update(o).digest(); + } + function r(o) { + return new z7().update(o).digest(); + } + return t === "rmd160" || t === "ripemd160" ? r : t === "md5" ? U7 : e; + } + function Z7(t, e, r, o, f) { + W7(r, o), t = Tb(t, Ib, "Password"), e = Tb(e, Ib, "Salt"), f = f || "sha1"; + var p = new kb(f, t, e.length), m = Sn.allocUnsafe(o), y = Sn.allocUnsafe(e.length + 4); + e.copy(y, 0, 0, e.length); + for (var M = 0, x = ds[f], S = Math.ceil(o / x), E2 = 1;E2 <= S; E2++) { + y.writeUInt32BE(E2, e.length); + for (var B = p.run(y, p.ipad1), q = B, L = 1;L < r; L++) { + q = p.run(q, p.ipad2); + for (var ge = 0;ge < x; ge++) + B[ge] ^= q[ge]; + } + B.copy(m, M), M += x; + } + return m; + } + Lb.exports = Z7; + }); + Ub = T((cT, Fb) => { + var Cb = Te().Buffer, V7 = _u(), Nb = xu(), Db = Au(), Pb = Eu(), cs, xa = global.crypto && global.crypto.subtle, $7 = { sha: "SHA-1", "sha-1": "SHA-1", sha1: "SHA-1", sha256: "SHA-256", "sha-256": "SHA-256", sha384: "SHA-384", "sha-384": "SHA-384", "sha-512": "SHA-512", sha512: "SHA-512" }, Ru = []; + function G7(t) { + if (global.process && !global.process.browser || !xa || !xa.importKey || !xa.deriveBits) + return Promise.resolve(false); + if (Ru[t] !== undefined) + return Ru[t]; + cs = cs || Cb.alloc(8); + var e = Ob(cs, cs, 10, 128, t).then(function() { + return true; + }).catch(function() { + return false; + }); + return Ru[t] = e, e; + } + var En; + function Bu() { + return En || (global.process && global.process.nextTick ? En = global.process.nextTick : global.queueMicrotask ? En = global.queueMicrotask : global.setImmediate ? En = global.setImmediate : En = global.setTimeout, En); + } + function Ob(t, e, r, o, f) { + return xa.importKey("raw", t, { name: "PBKDF2" }, false, ["deriveBits"]).then(function(p) { + return xa.deriveBits({ name: "PBKDF2", salt: e, iterations: r, hash: { name: f } }, p, o << 3); + }).then(function(p) { + return Cb.from(p); + }); + } + function Y7(t, e) { + t.then(function(r) { + Bu()(function() { + e(null, r); + }); + }, function(r) { + Bu()(function() { + e(r); + }); + }); + } + Fb.exports = function(t, e, r, o, f, p) { + typeof f == "function" && (p = f, f = undefined), f = f || "sha1"; + var m = $7[f.toLowerCase()]; + if (!m || typeof global.Promise != "function") { + Bu()(function() { + var y; + try { + y = Db(t, e, r, o, f); + } catch (M) { + return p(M); + } + p(null, y); + }); + return; + } + if (V7(r, o), t = Pb(t, Nb, "Password"), e = Pb(e, Nb, "Salt"), typeof p != "function") + throw new Error("No callback provided to pbkdf2"); + Y7(G7(m).then(function(y) { + return y ? Ob(t, e, r, o, m) : Db(t, e, r, o, f); + }), p); + }; + }); + Iu = T((qu) => { + qu.pbkdf2 = Ub(); + qu.pbkdf2Sync = Au(); + }); + Tu = T((br) => { + br.readUInt32BE = function(e, r) { + var o = e[0 + r] << 24 | e[1 + r] << 16 | e[2 + r] << 8 | e[3 + r]; + return o >>> 0; + }; + br.writeUInt32BE = function(e, r, o) { + e[0 + o] = r >>> 24, e[1 + o] = r >>> 16 & 255, e[2 + o] = r >>> 8 & 255, e[3 + o] = r & 255; + }; + br.ip = function(e, r, o, f) { + for (var p = 0, m = 0, y = 6;y >= 0; y -= 2) { + for (var M = 0;M <= 24; M += 8) + p <<= 1, p |= r >>> M + y & 1; + for (var M = 0;M <= 24; M += 8) + p <<= 1, p |= e >>> M + y & 1; + } + for (var y = 6;y >= 0; y -= 2) { + for (var M = 1;M <= 25; M += 8) + m <<= 1, m |= r >>> M + y & 1; + for (var M = 1;M <= 25; M += 8) + m <<= 1, m |= e >>> M + y & 1; + } + o[f + 0] = p >>> 0, o[f + 1] = m >>> 0; + }; + br.rip = function(e, r, o, f) { + for (var p = 0, m = 0, y = 0;y < 4; y++) + for (var M = 24;M >= 0; M -= 8) + p <<= 1, p |= r >>> M + y & 1, p <<= 1, p |= e >>> M + y & 1; + for (var y = 4;y < 8; y++) + for (var M = 24;M >= 0; M -= 8) + m <<= 1, m |= r >>> M + y & 1, m <<= 1, m |= e >>> M + y & 1; + o[f + 0] = p >>> 0, o[f + 1] = m >>> 0; + }; + br.pc1 = function(e, r, o, f) { + for (var p = 0, m = 0, y = 7;y >= 5; y--) { + for (var M = 0;M <= 24; M += 8) + p <<= 1, p |= r >> M + y & 1; + for (var M = 0;M <= 24; M += 8) + p <<= 1, p |= e >> M + y & 1; + } + for (var M = 0;M <= 24; M += 8) + p <<= 1, p |= r >> M + y & 1; + for (var y = 1;y <= 3; y++) { + for (var M = 0;M <= 24; M += 8) + m <<= 1, m |= r >> M + y & 1; + for (var M = 0;M <= 24; M += 8) + m <<= 1, m |= e >> M + y & 1; + } + for (var M = 0;M <= 24; M += 8) + m <<= 1, m |= e >> M + y & 1; + o[f + 0] = p >>> 0, o[f + 1] = m >>> 0; + }; + br.r28shl = function(e, r) { + return e << r & 268435455 | e >>> 28 - r; + }; + var ps = [14, 11, 17, 4, 27, 23, 25, 0, 13, 22, 7, 18, 5, 9, 16, 24, 2, 20, 12, 21, 1, 8, 15, 26, 15, 4, 25, 19, 9, 1, 26, 16, 5, 11, 23, 8, 12, 7, 17, 0, 22, 3, 10, 14, 6, 20, 27, 24]; + br.pc2 = function(e, r, o, f) { + for (var p = 0, m = 0, y = ps.length >>> 1, M = 0;M < y; M++) + p <<= 1, p |= e >>> ps[M] & 1; + for (var M = y;M < ps.length; M++) + m <<= 1, m |= r >>> ps[M] & 1; + o[f + 0] = p >>> 0, o[f + 1] = m >>> 0; + }; + br.expand = function(e, r, o) { + var f = 0, p = 0; + f = (e & 1) << 5 | e >>> 27; + for (var m = 23;m >= 15; m -= 4) + f <<= 6, f |= e >>> m & 63; + for (var m = 11;m >= 3; m -= 4) + p |= e >>> m & 63, p <<= 6; + p |= (e & 31) << 1 | e >>> 31, r[o + 0] = f >>> 0, r[o + 1] = p >>> 0; + }; + var zb = [14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11]; + br.substitute = function(e, r) { + for (var o = 0, f = 0;f < 4; f++) { + var p = e >>> 18 - f * 6 & 63, m = zb[f * 64 + p]; + o <<= 4, o |= m; + } + for (var f = 0;f < 4; f++) { + var p = r >>> 18 - f * 6 & 63, m = zb[4 * 64 + f * 64 + p]; + o <<= 4, o |= m; + } + return o >>> 0; + }; + var Hb = [16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22, 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7]; + br.permute = function(e) { + for (var r = 0, o = 0;o < Hb.length; o++) + r <<= 1, r |= e >>> Hb[o] & 1; + return r >>> 0; + }; + br.padSplit = function(e, r, o) { + for (var f = e.toString(2);f.length < r; ) + f = "0" + f; + for (var p = [], m = 0;m < r; m += o) + p.push(f.slice(m, m + o)); + return p.join(" "); + }; + }); + ar = T((bT, Kb) => { + Kb.exports = Wb; + function Wb(t, e) { + if (!t) + throw new Error(e || "Assertion failed"); + } + Wb.equal = function(e, r, o) { + if (e != r) + throw new Error(o || "Assertion failed: " + e + " != " + r); + }; + }); + vs = T((mT, jb) => { + var X7 = ar(); + function mr(t) { + this.options = t, this.type = this.options.type, this.blockSize = 8, this._init(), this.buffer = new Array(this.blockSize), this.bufferOff = 0; + } + jb.exports = mr; + mr.prototype._init = function() { + }; + mr.prototype.update = function(e) { + return e.length === 0 ? [] : this.type === "decrypt" ? this._updateDecrypt(e) : this._updateEncrypt(e); + }; + mr.prototype._buffer = function(e, r) { + for (var o = Math.min(this.buffer.length - this.bufferOff, e.length - r), f = 0;f < o; f++) + this.buffer[this.bufferOff + f] = e[r + f]; + return this.bufferOff += o, o; + }; + mr.prototype._flushBuffer = function(e, r) { + return this._update(this.buffer, 0, e, r), this.bufferOff = 0, this.blockSize; + }; + mr.prototype._updateEncrypt = function(e) { + var r = 0, o = 0, f = (this.bufferOff + e.length) / this.blockSize | 0, p = new Array(f * this.blockSize); + this.bufferOff !== 0 && (r += this._buffer(e, r), this.bufferOff === this.buffer.length && (o += this._flushBuffer(p, o))); + for (var m = e.length - (e.length - r) % this.blockSize;r < m; r += this.blockSize) + this._update(e, r, p, o), o += this.blockSize; + for (;r < e.length; r++, this.bufferOff++) + this.buffer[this.bufferOff] = e[r]; + return p; + }; + mr.prototype._updateDecrypt = function(e) { + for (var r = 0, o = 0, f = Math.ceil((this.bufferOff + e.length) / this.blockSize) - 1, p = new Array(f * this.blockSize);f > 0; f--) + r += this._buffer(e, r), o += this._flushBuffer(p, o); + return r += this._buffer(e, r), p; + }; + mr.prototype.final = function(e) { + var r; + e && (r = this.update(e)); + var o; + return this.type === "encrypt" ? o = this._finalEncrypt() : o = this._finalDecrypt(), r ? r.concat(o) : o; + }; + mr.prototype._pad = function(e, r) { + if (r === 0) + return false; + for (;r < e.length; ) + e[r++] = 0; + return true; + }; + mr.prototype._finalEncrypt = function() { + if (!this._pad(this.buffer, this.bufferOff)) + return []; + var e = new Array(this.blockSize); + return this._update(this.buffer, 0, e, 0), e; + }; + mr.prototype._unpad = function(e) { + return e; + }; + mr.prototype._finalDecrypt = function() { + X7.equal(this.bufferOff, this.blockSize, "Not enough data to decrypt"); + var e = new Array(this.blockSize); + return this._flushBuffer(e, 0), this._unpad(e); + }; + }); + ku = T((gT, $b) => { + var Zb = ar(), J7 = Ie(), Nt = Tu(), Vb = vs(); + function Q7() { + this.tmp = new Array(2), this.keys = null; + } + function ei(t) { + Vb.call(this, t); + var e = new Q7; + this._desState = e, this.deriveKeys(e, t.key); + } + J7(ei, Vb); + $b.exports = ei; + ei.create = function(e) { + return new ei(e); + }; + var e9 = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]; + ei.prototype.deriveKeys = function(e, r) { + e.keys = new Array(16 * 2), Zb.equal(r.length, this.blockSize, "Invalid key length"); + var o = Nt.readUInt32BE(r, 0), f = Nt.readUInt32BE(r, 4); + Nt.pc1(o, f, e.tmp, 0), o = e.tmp[0], f = e.tmp[1]; + for (var p = 0;p < e.keys.length; p += 2) { + var m = e9[p >>> 1]; + o = Nt.r28shl(o, m), f = Nt.r28shl(f, m), Nt.pc2(o, f, e.keys, p); + } + }; + ei.prototype._update = function(e, r, o, f) { + var p = this._desState, m = Nt.readUInt32BE(e, r), y = Nt.readUInt32BE(e, r + 4); + Nt.ip(m, y, p.tmp, 0), m = p.tmp[0], y = p.tmp[1], this.type === "encrypt" ? this._encrypt(p, m, y, p.tmp, 0) : this._decrypt(p, m, y, p.tmp, 0), m = p.tmp[0], y = p.tmp[1], Nt.writeUInt32BE(o, m, f), Nt.writeUInt32BE(o, y, f + 4); + }; + ei.prototype._pad = function(e, r) { + for (var o = e.length - r, f = r;f < e.length; f++) + e[f] = o; + return true; + }; + ei.prototype._unpad = function(e) { + for (var r = e[e.length - 1], o = e.length - r;o < e.length; o++) + Zb.equal(e[o], r); + return e.slice(0, e.length - r); + }; + ei.prototype._encrypt = function(e, r, o, f, p) { + for (var m = r, y = o, M = 0;M < e.keys.length; M += 2) { + var x = e.keys[M], S = e.keys[M + 1]; + Nt.expand(y, e.tmp, 0), x ^= e.tmp[0], S ^= e.tmp[1]; + var E2 = Nt.substitute(x, S), B = Nt.permute(E2), q = y; + y = (m ^ B) >>> 0, m = q; + } + Nt.rip(y, m, f, p); + }; + ei.prototype._decrypt = function(e, r, o, f, p) { + for (var m = o, y = r, M = e.keys.length - 2;M >= 0; M -= 2) { + var x = e.keys[M], S = e.keys[M + 1]; + Nt.expand(m, e.tmp, 0), x ^= e.tmp[0], S ^= e.tmp[1]; + var E2 = Nt.substitute(x, S), B = Nt.permute(E2), q = m; + m = (y ^ B) >>> 0, y = q; + } + Nt.rip(m, y, f, p); + }; + }); + Yb = T((Gb) => { + var t9 = ar(), r9 = Ie(), bs = {}; + function i9(t) { + t9.equal(t.length, 8, "Invalid IV length"), this.iv = new Array(8); + for (var e = 0;e < this.iv.length; e++) + this.iv[e] = t[e]; + } + function n9(t) { + function e(p) { + t.call(this, p), this._cbcInit(); + } + r9(e, t); + for (var r = Object.keys(bs), o = 0;o < r.length; o++) { + var f = r[o]; + e.prototype[f] = bs[f]; + } + return e.create = function(m) { + return new e(m); + }, e; + } + Gb.instantiate = n9; + bs._cbcInit = function() { + var e = new i9(this.options.iv); + this._cbcState = e; + }; + bs._update = function(e, r, o, f) { + var p = this._cbcState, m = this.constructor.super_.prototype, y = p.iv; + if (this.type === "encrypt") { + for (var M = 0;M < this.blockSize; M++) + y[M] ^= e[r + M]; + m._update.call(this, y, 0, o, f); + for (var M = 0;M < this.blockSize; M++) + y[M] = o[f + M]; + } else { + m._update.call(this, e, r, o, f); + for (var M = 0;M < this.blockSize; M++) + o[f + M] ^= y[M]; + for (var M = 0;M < this.blockSize; M++) + y[M] = e[r + M]; + } + }; + }); + Qb = T((wT, Jb) => { + var f9 = ar(), a9 = Ie(), Xb = vs(), Wi2 = ku(); + function o9(t, e) { + f9.equal(e.length, 24, "Invalid key length"); + var r = e.slice(0, 8), o = e.slice(8, 16), f = e.slice(16, 24); + t === "encrypt" ? this.ciphers = [Wi2.create({ type: "encrypt", key: r }), Wi2.create({ type: "decrypt", key: o }), Wi2.create({ type: "encrypt", key: f })] : this.ciphers = [Wi2.create({ type: "decrypt", key: f }), Wi2.create({ type: "encrypt", key: o }), Wi2.create({ type: "decrypt", key: r })]; + } + function An(t) { + Xb.call(this, t); + var e = new o9(this.type, this.options.key); + this._edeState = e; + } + a9(An, Xb); + Jb.exports = An; + An.create = function(e) { + return new An(e); + }; + An.prototype._update = function(e, r, o, f) { + var p = this._edeState; + p.ciphers[0]._update(e, r, o, f), p.ciphers[1]._update(o, f, o, f), p.ciphers[2]._update(o, f, o, f); + }; + An.prototype._pad = Wi2.prototype._pad; + An.prototype._unpad = Wi2.prototype._unpad; + }); + em = T((gf) => { + gf.utils = Tu(); + gf.Cipher = vs(); + gf.DES = ku(); + gf.CBC = Yb(); + gf.EDE = Qb(); + }); + im = T((_T, rm) => { + var tm = yi(), wi = em(), s9 = Ie(), Rn = Te().Buffer, Sa = { "des-ede3-cbc": wi.CBC.instantiate(wi.EDE), "des-ede3": wi.EDE, "des-ede-cbc": wi.CBC.instantiate(wi.EDE), "des-ede": wi.EDE, "des-cbc": wi.CBC.instantiate(wi.DES), "des-ecb": wi.DES }; + Sa.des = Sa["des-cbc"]; + Sa.des3 = Sa["des-ede3-cbc"]; + rm.exports = ms; + s9(ms, tm); + function ms(t) { + tm.call(this); + var e = t.mode.toLowerCase(), r = Sa[e], o; + t.decrypt ? o = "decrypt" : o = "encrypt"; + var f = t.key; + Rn.isBuffer(f) || (f = Rn.from(f)), (e === "des-ede" || e === "des-ede-cbc") && (f = Rn.concat([f, f.slice(0, 8)])); + var p = t.iv; + Rn.isBuffer(p) || (p = Rn.from(p)), this._des = r.create({ key: f, iv: p, type: o }); + } + ms.prototype._update = function(t) { + return Rn.from(this._des.update(t)); + }; + ms.prototype._final = function() { + return Rn.from(this._des.final()); + }; + }); + nm = T((Lu) => { + Lu.encrypt = function(t, e) { + return t._cipher.encryptBlock(e); + }; + Lu.decrypt = function(t, e) { + return t._cipher.decryptBlock(e); + }; + }); + yf = T((ST, fm) => { + fm.exports = function(e, r) { + for (var o = Math.min(e.length, r.length), f = new Buffer(o), p = 0;p < o; ++p) + f[p] = e[p] ^ r[p]; + return f; + }; + }); + om = T((Nu) => { + var am = yf(); + Nu.encrypt = function(t, e) { + var r = am(e, t._prev); + return t._prev = t._cipher.encryptBlock(r), t._prev; + }; + Nu.decrypt = function(t, e) { + var r = t._prev; + t._prev = e; + var o = t._cipher.decryptBlock(e); + return am(o, r); + }; + }); + um = T((hm) => { + var Ea = Te().Buffer, h9 = yf(); + function sm2(t, e, r) { + var o = e.length, f = h9(e, t._cache); + return t._cache = t._cache.slice(o), t._prev = Ea.concat([t._prev, r ? e : f]), f; + } + hm.encrypt = function(t, e, r) { + for (var o = Ea.allocUnsafe(0), f;e.length; ) + if (t._cache.length === 0 && (t._cache = t._cipher.encryptBlock(t._prev), t._prev = Ea.allocUnsafe(0)), t._cache.length <= e.length) + f = t._cache.length, o = Ea.concat([o, sm2(t, e.slice(0, f), r)]), e = e.slice(f); + else { + o = Ea.concat([o, sm2(t, e, r)]); + break; + } + return o; + }; + }); + dm = T((lm) => { + var Du = Te().Buffer; + function u9(t, e, r) { + var o = t._cipher.encryptBlock(t._prev), f = o[0] ^ e; + return t._prev = Du.concat([t._prev.slice(1), Du.from([r ? e : f])]), f; + } + lm.encrypt = function(t, e, r) { + for (var o = e.length, f = Du.allocUnsafe(o), p = -1;++p < o; ) + f[p] = u9(t, e[p], r); + return f; + }; + }); + pm = T((cm) => { + var gs = Te().Buffer; + function l9(t, e, r) { + for (var o, f = -1, p = 8, m = 0, y, M;++f < p; ) + o = t._cipher.encryptBlock(t._prev), y = e & 1 << 7 - f ? 128 : 0, M = o[0] ^ y, m += (M & 128) >> f % 8, t._prev = d9(t._prev, r ? y : M); + return m; + } + function d9(t, e) { + var r = t.length, o = -1, f = gs.allocUnsafe(t.length); + for (t = gs.concat([t, gs.from([e])]);++o < r; ) + f[o] = t[o] << 1 | t[o + 1] >> 7; + return f; + } + cm.encrypt = function(t, e, r) { + for (var o = e.length, f = gs.allocUnsafe(o), p = -1;++p < o; ) + f[p] = l9(t, e[p], r); + return f; + }; + }); + bm = T((vm) => { + var c9 = yf(); + function p9(t) { + return t._prev = t._cipher.encryptBlock(t._prev), t._prev; + } + vm.encrypt = function(t, e) { + for (;t._cache.length < e.length; ) + t._cache = Buffer.concat([t._cache, p9(t)]); + var r = t._cache.slice(0, e.length); + return t._cache = t._cache.slice(e.length), c9(e, r); + }; + }); + Pu = T((IT, mm2) => { + function v9(t) { + for (var e = t.length, r;e--; ) + if (r = t.readUInt8(e), r === 255) + t.writeUInt8(0, e); + else { + r++, t.writeUInt8(r, e); + break; + } + } + mm2.exports = v9; + }); + Ou = T((ym) => { + var b9 = yf(), gm = Te().Buffer, m9 = Pu(); + function g9(t) { + var e = t._cipher.encryptBlockRaw(t._prev); + return m9(t._prev), e; + } + var Cu = 16; + ym.encrypt = function(t, e) { + var r = Math.ceil(e.length / Cu), o = t._cache.length; + t._cache = gm.concat([t._cache, gm.allocUnsafe(r * Cu)]); + for (var f = 0;f < r; f++) { + var p = g9(t), m = o + f * Cu; + t._cache.writeUInt32BE(p[0], m + 0), t._cache.writeUInt32BE(p[1], m + 4), t._cache.writeUInt32BE(p[2], m + 8), t._cache.writeUInt32BE(p[3], m + 12); + } + var y = t._cache.slice(0, e.length); + return t._cache = t._cache.slice(e.length), b9(e, y); + }; + }); + Fu = T((kT, y9) => { + y9.exports = { "aes-128-ecb": { cipher: "AES", key: 128, iv: 0, mode: "ECB", type: "block" }, "aes-192-ecb": { cipher: "AES", key: 192, iv: 0, mode: "ECB", type: "block" }, "aes-256-ecb": { cipher: "AES", key: 256, iv: 0, mode: "ECB", type: "block" }, "aes-128-cbc": { cipher: "AES", key: 128, iv: 16, mode: "CBC", type: "block" }, "aes-192-cbc": { cipher: "AES", key: 192, iv: 16, mode: "CBC", type: "block" }, "aes-256-cbc": { cipher: "AES", key: 256, iv: 16, mode: "CBC", type: "block" }, aes128: { cipher: "AES", key: 128, iv: 16, mode: "CBC", type: "block" }, aes192: { cipher: "AES", key: 192, iv: 16, mode: "CBC", type: "block" }, aes256: { cipher: "AES", key: 256, iv: 16, mode: "CBC", type: "block" }, "aes-128-cfb": { cipher: "AES", key: 128, iv: 16, mode: "CFB", type: "stream" }, "aes-192-cfb": { cipher: "AES", key: 192, iv: 16, mode: "CFB", type: "stream" }, "aes-256-cfb": { cipher: "AES", key: 256, iv: 16, mode: "CFB", type: "stream" }, "aes-128-cfb8": { cipher: "AES", key: 128, iv: 16, mode: "CFB8", type: "stream" }, "aes-192-cfb8": { cipher: "AES", key: 192, iv: 16, mode: "CFB8", type: "stream" }, "aes-256-cfb8": { cipher: "AES", key: 256, iv: 16, mode: "CFB8", type: "stream" }, "aes-128-cfb1": { cipher: "AES", key: 128, iv: 16, mode: "CFB1", type: "stream" }, "aes-192-cfb1": { cipher: "AES", key: 192, iv: 16, mode: "CFB1", type: "stream" }, "aes-256-cfb1": { cipher: "AES", key: 256, iv: 16, mode: "CFB1", type: "stream" }, "aes-128-ofb": { cipher: "AES", key: 128, iv: 16, mode: "OFB", type: "stream" }, "aes-192-ofb": { cipher: "AES", key: 192, iv: 16, mode: "OFB", type: "stream" }, "aes-256-ofb": { cipher: "AES", key: 256, iv: 16, mode: "OFB", type: "stream" }, "aes-128-ctr": { cipher: "AES", key: 128, iv: 16, mode: "CTR", type: "stream" }, "aes-192-ctr": { cipher: "AES", key: 192, iv: 16, mode: "CTR", type: "stream" }, "aes-256-ctr": { cipher: "AES", key: 256, iv: 16, mode: "CTR", type: "stream" }, "aes-128-gcm": { cipher: "AES", key: 128, iv: 12, mode: "GCM", type: "auth" }, "aes-192-gcm": { cipher: "AES", key: 192, iv: 12, mode: "GCM", type: "auth" }, "aes-256-gcm": { cipher: "AES", key: 256, iv: 12, mode: "GCM", type: "auth" } }; + }); + ws = T((LT, wm) => { + var w9 = { ECB: nm(), CBC: om(), CFB: um(), CFB8: dm(), CFB1: pm(), OFB: bm(), CTR: Ou(), GCM: Ou() }, ys = Fu(); + for (Uu in ys) + ys[Uu].module = w9[ys[Uu].mode]; + var Uu; + wm.exports = ys; + }); + Aa = T((NT, _m) => { + var Ms = Te().Buffer; + function Hu(t) { + Ms.isBuffer(t) || (t = Ms.from(t)); + for (var e = t.length / 4 | 0, r = new Array(e), o = 0;o < e; o++) + r[o] = t.readUInt32BE(o * 4); + return r; + } + function zu(t) { + for (var e = 0;e < t.length; t++) + t[e] = 0; + } + function Mm(t, e, r, o, f) { + for (var p = r[0], m = r[1], y = r[2], M = r[3], x = t[0] ^ e[0], S = t[1] ^ e[1], E2 = t[2] ^ e[2], B = t[3] ^ e[3], q, L, ge, _e, N = 4, we = 1;we < f; we++) + q = p[x >>> 24] ^ m[S >>> 16 & 255] ^ y[E2 >>> 8 & 255] ^ M[B & 255] ^ e[N++], L = p[S >>> 24] ^ m[E2 >>> 16 & 255] ^ y[B >>> 8 & 255] ^ M[x & 255] ^ e[N++], ge = p[E2 >>> 24] ^ m[B >>> 16 & 255] ^ y[x >>> 8 & 255] ^ M[S & 255] ^ e[N++], _e = p[B >>> 24] ^ m[x >>> 16 & 255] ^ y[S >>> 8 & 255] ^ M[E2 & 255] ^ e[N++], x = q, S = L, E2 = ge, B = _e; + return q = (o[x >>> 24] << 24 | o[S >>> 16 & 255] << 16 | o[E2 >>> 8 & 255] << 8 | o[B & 255]) ^ e[N++], L = (o[S >>> 24] << 24 | o[E2 >>> 16 & 255] << 16 | o[B >>> 8 & 255] << 8 | o[x & 255]) ^ e[N++], ge = (o[E2 >>> 24] << 24 | o[B >>> 16 & 255] << 16 | o[x >>> 8 & 255] << 8 | o[S & 255]) ^ e[N++], _e = (o[B >>> 24] << 24 | o[x >>> 16 & 255] << 16 | o[S >>> 8 & 255] << 8 | o[E2 & 255]) ^ e[N++], q = q >>> 0, L = L >>> 0, ge = ge >>> 0, _e = _e >>> 0, [q, L, ge, _e]; + } + var M9 = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54], kt = function() { + for (var t = new Array(256), e = 0;e < 256; e++) + e < 128 ? t[e] = e << 1 : t[e] = e << 1 ^ 283; + for (var r = [], o = [], f = [[], [], [], []], p = [[], [], [], []], m = 0, y = 0, M = 0;M < 256; ++M) { + var x = y ^ y << 1 ^ y << 2 ^ y << 3 ^ y << 4; + x = x >>> 8 ^ x & 255 ^ 99, r[m] = x, o[x] = m; + var S = t[m], E2 = t[S], B = t[E2], q = t[x] * 257 ^ x * 16843008; + f[0][m] = q << 24 | q >>> 8, f[1][m] = q << 16 | q >>> 16, f[2][m] = q << 8 | q >>> 24, f[3][m] = q, q = B * 16843009 ^ E2 * 65537 ^ S * 257 ^ m * 16843008, p[0][x] = q << 24 | q >>> 8, p[1][x] = q << 16 | q >>> 16, p[2][x] = q << 8 | q >>> 24, p[3][x] = q, m === 0 ? m = y = 1 : (m = S ^ t[t[t[B ^ S]]], y ^= t[t[y]]); + } + return { SBOX: r, INV_SBOX: o, SUB_MIX: f, INV_SUB_MIX: p }; + }(); + function gr(t) { + this._key = Hu(t), this._reset(); + } + gr.blockSize = 4 * 4; + gr.keySize = 256 / 8; + gr.prototype.blockSize = gr.blockSize; + gr.prototype.keySize = gr.keySize; + gr.prototype._reset = function() { + for (var t = this._key, e = t.length, r = e + 6, o = (r + 1) * 4, f = [], p = 0;p < e; p++) + f[p] = t[p]; + for (p = e;p < o; p++) { + var m = f[p - 1]; + p % e === 0 ? (m = m << 8 | m >>> 24, m = kt.SBOX[m >>> 24] << 24 | kt.SBOX[m >>> 16 & 255] << 16 | kt.SBOX[m >>> 8 & 255] << 8 | kt.SBOX[m & 255], m ^= M9[p / e | 0] << 24) : e > 6 && p % e === 4 && (m = kt.SBOX[m >>> 24] << 24 | kt.SBOX[m >>> 16 & 255] << 16 | kt.SBOX[m >>> 8 & 255] << 8 | kt.SBOX[m & 255]), f[p] = f[p - e] ^ m; + } + for (var y = [], M = 0;M < o; M++) { + var x = o - M, S = f[x - (M % 4 ? 0 : 4)]; + M < 4 || x <= 4 ? y[M] = S : y[M] = kt.INV_SUB_MIX[0][kt.SBOX[S >>> 24]] ^ kt.INV_SUB_MIX[1][kt.SBOX[S >>> 16 & 255]] ^ kt.INV_SUB_MIX[2][kt.SBOX[S >>> 8 & 255]] ^ kt.INV_SUB_MIX[3][kt.SBOX[S & 255]]; + } + this._nRounds = r, this._keySchedule = f, this._invKeySchedule = y; + }; + gr.prototype.encryptBlockRaw = function(t) { + return t = Hu(t), Mm(t, this._keySchedule, kt.SUB_MIX, kt.SBOX, this._nRounds); + }; + gr.prototype.encryptBlock = function(t) { + var e = this.encryptBlockRaw(t), r = Ms.allocUnsafe(16); + return r.writeUInt32BE(e[0], 0), r.writeUInt32BE(e[1], 4), r.writeUInt32BE(e[2], 8), r.writeUInt32BE(e[3], 12), r; + }; + gr.prototype.decryptBlock = function(t) { + t = Hu(t); + var e = t[1]; + t[1] = t[3], t[3] = e; + var r = Mm(t, this._invKeySchedule, kt.INV_SUB_MIX, kt.INV_SBOX, this._nRounds), o = Ms.allocUnsafe(16); + return o.writeUInt32BE(r[0], 0), o.writeUInt32BE(r[3], 4), o.writeUInt32BE(r[2], 8), o.writeUInt32BE(r[1], 12), o; + }; + gr.prototype.scrub = function() { + zu(this._keySchedule), zu(this._invKeySchedule), zu(this._key); + }; + _m.exports.AES = gr; + }); + Em = T((DT, Sm) => { + var wf = Te().Buffer, _9 = wf.alloc(16, 0); + function x9(t) { + return [t.readUInt32BE(0), t.readUInt32BE(4), t.readUInt32BE(8), t.readUInt32BE(12)]; + } + function xm(t) { + var e = wf.allocUnsafe(16); + return e.writeUInt32BE(t[0] >>> 0, 0), e.writeUInt32BE(t[1] >>> 0, 4), e.writeUInt32BE(t[2] >>> 0, 8), e.writeUInt32BE(t[3] >>> 0, 12), e; + } + function Ra(t) { + this.h = t, this.state = wf.alloc(16, 0), this.cache = wf.allocUnsafe(0); + } + Ra.prototype.ghash = function(t) { + for (var e = -1;++e < t.length; ) + this.state[e] ^= t[e]; + this._multiply(); + }; + Ra.prototype._multiply = function() { + for (var t = x9(this.h), e = [0, 0, 0, 0], r, o, f, p = -1;++p < 128; ) { + for (o = (this.state[~~(p / 8)] & 1 << 7 - p % 8) !== 0, o && (e[0] ^= t[0], e[1] ^= t[1], e[2] ^= t[2], e[3] ^= t[3]), f = (t[3] & 1) !== 0, r = 3;r > 0; r--) + t[r] = t[r] >>> 1 | (t[r - 1] & 1) << 31; + t[0] = t[0] >>> 1, f && (t[0] = t[0] ^ 225 << 24); + } + this.state = xm(e); + }; + Ra.prototype.update = function(t) { + this.cache = wf.concat([this.cache, t]); + for (var e;this.cache.length >= 16; ) + e = this.cache.slice(0, 16), this.cache = this.cache.slice(16), this.ghash(e); + }; + Ra.prototype.final = function(t, e) { + return this.cache.length && this.ghash(wf.concat([this.cache, _9], 16)), this.ghash(xm([0, t, 0, e])), this.state; + }; + Sm.exports = Ra; + }); + Wu = T((PT, Bm) => { + var S9 = Aa(), rr = Te().Buffer, Am = yi(), E9 = Ie(), Rm = Em(), A9 = yf(), R9 = Pu(); + function B9(t, e) { + var r = 0; + t.length !== e.length && r++; + for (var o = Math.min(t.length, e.length), f = 0;f < o; ++f) + r += t[f] ^ e[f]; + return r; + } + function q9(t, e, r) { + if (e.length === 12) + return t._finID = rr.concat([e, rr.from([0, 0, 0, 1])]), rr.concat([e, rr.from([0, 0, 0, 2])]); + var o = new Rm(r), f = e.length, p = f % 16; + o.update(e), p && (p = 16 - p, o.update(rr.alloc(p, 0))), o.update(rr.alloc(8, 0)); + var m = f * 8, y = rr.alloc(8); + y.writeUIntBE(m, 0, 8), o.update(y), t._finID = o.state; + var M = rr.from(t._finID); + return R9(M), M; + } + function Bn(t, e, r, o) { + Am.call(this); + var f = rr.alloc(4, 0); + this._cipher = new S9.AES(e); + var p = this._cipher.encryptBlock(f); + this._ghash = new Rm(p), r = q9(this, r, p), this._prev = rr.from(r), this._cache = rr.allocUnsafe(0), this._secCache = rr.allocUnsafe(0), this._decrypt = o, this._alen = 0, this._len = 0, this._mode = t, this._authTag = null, this._called = false; + } + E9(Bn, Am); + Bn.prototype._update = function(t) { + if (!this._called && this._alen) { + var e = 16 - this._alen % 16; + e < 16 && (e = rr.alloc(e, 0), this._ghash.update(e)); + } + this._called = true; + var r = this._mode.encrypt(this, t); + return this._decrypt ? this._ghash.update(t) : this._ghash.update(r), this._len += t.length, r; + }; + Bn.prototype._final = function() { + if (this._decrypt && !this._authTag) + throw new Error("Unsupported state or unable to authenticate data"); + var t = A9(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)); + if (this._decrypt && B9(t, this._authTag)) + throw new Error("Unsupported state or unable to authenticate data"); + this._authTag = t, this._cipher.scrub(); + }; + Bn.prototype.getAuthTag = function() { + if (this._decrypt || !rr.isBuffer(this._authTag)) + throw new Error("Attempting to get auth tag in unsupported state"); + return this._authTag; + }; + Bn.prototype.setAuthTag = function(e) { + if (!this._decrypt) + throw new Error("Attempting to set auth tag in unsupported state"); + this._authTag = e; + }; + Bn.prototype.setAAD = function(e) { + if (this._called) + throw new Error("Attempting to set AAD in unsupported state"); + this._ghash.update(e), this._alen += e.length; + }; + Bm.exports = Bn; + }); + ju = T((CT, Im) => { + var I9 = Aa(), Ku = Te().Buffer, qm = yi(), T9 = Ie(); + function _s(t, e, r, o) { + qm.call(this), this._cipher = new I9.AES(e), this._prev = Ku.from(r), this._cache = Ku.allocUnsafe(0), this._secCache = Ku.allocUnsafe(0), this._decrypt = o, this._mode = t; + } + T9(_s, qm); + _s.prototype._update = function(t) { + return this._mode.encrypt(this, t, this._decrypt); + }; + _s.prototype._final = function() { + this._cipher.scrub(); + }; + Im.exports = _s; + }); + Ba = T((OT, Tm) => { + var qn = Te().Buffer, k9 = Ao(); + function L9(t, e, r, o) { + if (qn.isBuffer(t) || (t = qn.from(t, "binary")), e && (qn.isBuffer(e) || (e = qn.from(e, "binary")), e.length !== 8)) + throw new RangeError("salt should be Buffer with 8 byte length"); + for (var f = r / 8, p = qn.alloc(f), m = qn.alloc(o || 0), y = qn.alloc(0);f > 0 || o > 0; ) { + var M = new k9; + M.update(y), M.update(t), e && M.update(e), y = M.digest(); + var x = 0; + if (f > 0) { + var S = p.length - f; + x = Math.min(f, y.length), y.copy(p, S, 0, x), f -= x; + } + if (x < y.length && o > 0) { + var E2 = m.length - o, B = Math.min(o, y.length - x); + y.copy(m, E2, x, x + B), o -= B; + } + } + return y.fill(0), { key: p, iv: m }; + } + Tm.exports = L9; + }); + Dm = T((Zu) => { + var km = ws(), N9 = Wu(), Mi = Te().Buffer, D9 = ju(), Lm = yi(), P9 = Aa(), C9 = Ba(), O9 = Ie(); + function qa(t, e, r) { + Lm.call(this), this._cache = new xs, this._cipher = new P9.AES(e), this._prev = Mi.from(r), this._mode = t, this._autopadding = true; + } + O9(qa, Lm); + qa.prototype._update = function(t) { + this._cache.add(t); + for (var e, r, o = [];e = this._cache.get(); ) + r = this._mode.encrypt(this, e), o.push(r); + return Mi.concat(o); + }; + var F9 = Mi.alloc(16, 16); + qa.prototype._final = function() { + var t = this._cache.flush(); + if (this._autopadding) + return t = this._mode.encrypt(this, t), this._cipher.scrub(), t; + if (!t.equals(F9)) + throw this._cipher.scrub(), new Error("data not multiple of block length"); + }; + qa.prototype.setAutoPadding = function(t) { + return this._autopadding = !!t, this; + }; + function xs() { + this.cache = Mi.allocUnsafe(0); + } + xs.prototype.add = function(t) { + this.cache = Mi.concat([this.cache, t]); + }; + xs.prototype.get = function() { + if (this.cache.length > 15) { + var t = this.cache.slice(0, 16); + return this.cache = this.cache.slice(16), t; + } + return null; + }; + xs.prototype.flush = function() { + for (var t = 16 - this.cache.length, e = Mi.allocUnsafe(t), r = -1;++r < t; ) + e.writeUInt8(t, r); + return Mi.concat([this.cache, e]); + }; + function Nm(t, e, r) { + var o = km[t.toLowerCase()]; + if (!o) + throw new TypeError("invalid suite type"); + if (typeof e == "string" && (e = Mi.from(e)), e.length !== o.key / 8) + throw new TypeError("invalid key length " + e.length); + if (typeof r == "string" && (r = Mi.from(r)), o.mode !== "GCM" && r.length !== o.iv) + throw new TypeError("invalid iv length " + r.length); + return o.type === "stream" ? new D9(o.module, e, r) : o.type === "auth" ? new N9(o.module, e, r) : new qa(o.module, e, r); + } + function U9(t, e) { + var r = km[t.toLowerCase()]; + if (!r) + throw new TypeError("invalid suite type"); + var o = C9(e, false, r.key, r.iv); + return Nm(t, o.key, o.iv); + } + Zu.createCipheriv = Nm; + Zu.createCipher = U9; + }); + Fm = T((Vu) => { + var z9 = Wu(), Mf = Te().Buffer, Pm = ws(), H9 = ju(), Cm = yi(), W9 = Aa(), K9 = Ba(), j9 = Ie(); + function Ia(t, e, r) { + Cm.call(this), this._cache = new Ss, this._last = undefined, this._cipher = new W9.AES(e), this._prev = Mf.from(r), this._mode = t, this._autopadding = true; + } + j9(Ia, Cm); + Ia.prototype._update = function(t) { + this._cache.add(t); + for (var e, r, o = [];e = this._cache.get(this._autopadding); ) + r = this._mode.decrypt(this, e), o.push(r); + return Mf.concat(o); + }; + Ia.prototype._final = function() { + var t = this._cache.flush(); + if (this._autopadding) + return Z9(this._mode.decrypt(this, t)); + if (t) + throw new Error("data not multiple of block length"); + }; + Ia.prototype.setAutoPadding = function(t) { + return this._autopadding = !!t, this; + }; + function Ss() { + this.cache = Mf.allocUnsafe(0); + } + Ss.prototype.add = function(t) { + this.cache = Mf.concat([this.cache, t]); + }; + Ss.prototype.get = function(t) { + var e; + if (t) { + if (this.cache.length > 16) + return e = this.cache.slice(0, 16), this.cache = this.cache.slice(16), e; + } else if (this.cache.length >= 16) + return e = this.cache.slice(0, 16), this.cache = this.cache.slice(16), e; + return null; + }; + Ss.prototype.flush = function() { + if (this.cache.length) + return this.cache; + }; + function Z9(t) { + var e = t[15]; + if (e < 1 || e > 16) + throw new Error("unable to decrypt data"); + for (var r = -1;++r < e; ) + if (t[r + (16 - e)] !== e) + throw new Error("unable to decrypt data"); + if (e !== 16) + return t.slice(0, 16 - e); + } + function Om(t, e, r) { + var o = Pm[t.toLowerCase()]; + if (!o) + throw new TypeError("invalid suite type"); + if (typeof r == "string" && (r = Mf.from(r)), o.mode !== "GCM" && r.length !== o.iv) + throw new TypeError("invalid iv length " + r.length); + if (typeof e == "string" && (e = Mf.from(e)), e.length !== o.key / 8) + throw new TypeError("invalid key length " + e.length); + return o.type === "stream" ? new H9(o.module, e, r, true) : o.type === "auth" ? new z9(o.module, e, r, true) : new Ia(o.module, e, r); + } + function V9(t, e) { + var r = Pm[t.toLowerCase()]; + if (!r) + throw new TypeError("invalid suite type"); + var o = K9(e, false, r.key, r.iv); + return Om(t, o.key, o.iv); + } + Vu.createDecipher = V9; + Vu.createDecipheriv = Om; + }); + Es = T((Nr) => { + var Um = Dm(), zm = Fm(), $9 = Fu(); + function G9() { + return Object.keys($9); + } + Nr.createCipher = Nr.Cipher = Um.createCipher; + Nr.createCipheriv = Nr.Cipheriv = Um.createCipheriv; + Nr.createDecipher = Nr.Decipher = zm.createDecipher; + Nr.createDecipheriv = Nr.Decipheriv = zm.createDecipheriv; + Nr.listCiphers = Nr.getCiphers = G9; + }); + Hm = T((_i) => { + _i["des-ecb"] = { key: 8, iv: 0 }; + _i["des-cbc"] = _i.des = { key: 8, iv: 8 }; + _i["des-ede3-cbc"] = _i.des3 = { key: 24, iv: 8 }; + _i["des-ede3"] = { key: 24, iv: 0 }; + _i["des-ede-cbc"] = { key: 16, iv: 8 }; + _i["des-ede"] = { key: 16, iv: 0 }; + }); + Vm = T((Dr) => { + var Wm = im(), $u = Es(), Ki = ws(), xi = Hm(), Km = Ba(); + function Y9(t, e) { + t = t.toLowerCase(); + var r, o; + if (Ki[t]) + r = Ki[t].key, o = Ki[t].iv; + else if (xi[t]) + r = xi[t].key * 8, o = xi[t].iv; + else + throw new TypeError("invalid suite type"); + var f = Km(e, false, r, o); + return jm(t, f.key, f.iv); + } + function X9(t, e) { + t = t.toLowerCase(); + var r, o; + if (Ki[t]) + r = Ki[t].key, o = Ki[t].iv; + else if (xi[t]) + r = xi[t].key * 8, o = xi[t].iv; + else + throw new TypeError("invalid suite type"); + var f = Km(e, false, r, o); + return Zm(t, f.key, f.iv); + } + function jm(t, e, r) { + if (t = t.toLowerCase(), Ki[t]) + return $u.createCipheriv(t, e, r); + if (xi[t]) + return new Wm({ key: e, iv: r, mode: t }); + throw new TypeError("invalid suite type"); + } + function Zm(t, e, r) { + if (t = t.toLowerCase(), Ki[t]) + return $u.createDecipheriv(t, e, r); + if (xi[t]) + return new Wm({ key: e, iv: r, mode: t, decrypt: true }); + throw new TypeError("invalid suite type"); + } + function J9() { + return Object.keys(xi).concat($u.getCiphers()); + } + Dr.createCipher = Dr.Cipher = Y9; + Dr.createCipheriv = Dr.Cipheriv = jm; + Dr.createDecipher = Dr.Decipher = X9; + Dr.createDecipheriv = Dr.Decipheriv = Zm; + Dr.listCiphers = Dr.getCiphers = J9; + }); + ji = T(() => { + }); + Yu = T(($m, Gu2) => { + (function(t, e) { + function r(v, i) { + if (!v) + throw new Error(i || "Assertion failed"); + } + function o(v, i) { + v.super_ = i; + var a = function() { + }; + a.prototype = i.prototype, v.prototype = new a, v.prototype.constructor = v; + } + function f(v, i, a) { + if (f.isBN(v)) + return v; + this.negative = 0, this.words = null, this.length = 0, this.red = null, v !== null && ((i === "le" || i === "be") && (a = i, i = 10), this._init(v || 0, i || 10, a || "be")); + } + typeof t == "object" ? t.exports = f : e.BN = f, f.BN = f, f.wordSize = 26; + var p; + try { + typeof window < "u" && typeof window.Buffer < "u" ? p = window.Buffer : p = ji().Buffer; + } catch { + } + f.isBN = function(i) { + return i instanceof f ? true : i !== null && typeof i == "object" && i.constructor.wordSize === f.wordSize && Array.isArray(i.words); + }, f.max = function(i, a) { + return i.cmp(a) > 0 ? i : a; + }, f.min = function(i, a) { + return i.cmp(a) < 0 ? i : a; + }, f.prototype._init = function(i, a, h) { + if (typeof i == "number") + return this._initNumber(i, a, h); + if (typeof i == "object") + return this._initArray(i, a, h); + a === "hex" && (a = 16), r(a === (a | 0) && a >= 2 && a <= 36), i = i.toString().replace(/\s+/g, ""); + var s = 0; + i[0] === "-" && (s++, this.negative = 1), s < i.length && (a === 16 ? this._parseHex(i, s, h) : (this._parseBase(i, a, s), h === "le" && this._initArray(this.toArray(), a, h))); + }, f.prototype._initNumber = function(i, a, h) { + i < 0 && (this.negative = 1, i = -i), i < 67108864 ? (this.words = [i & 67108863], this.length = 1) : i < 4503599627370496 ? (this.words = [i & 67108863, i / 67108864 & 67108863], this.length = 2) : (r(i < 9007199254740992), this.words = [i & 67108863, i / 67108864 & 67108863, 1], this.length = 3), h === "le" && this._initArray(this.toArray(), a, h); + }, f.prototype._initArray = function(i, a, h) { + if (r(typeof i.length == "number"), i.length <= 0) + return this.words = [0], this.length = 1, this; + this.length = Math.ceil(i.length / 3), this.words = new Array(this.length); + for (var s = 0;s < this.length; s++) + this.words[s] = 0; + var u, c, b = 0; + if (h === "be") + for (s = i.length - 1, u = 0;s >= 0; s -= 3) + c = i[s] | i[s - 1] << 8 | i[s - 2] << 16, this.words[u] |= c << b & 67108863, this.words[u + 1] = c >>> 26 - b & 67108863, b += 24, b >= 26 && (b -= 26, u++); + else if (h === "le") + for (s = 0, u = 0;s < i.length; s += 3) + c = i[s] | i[s + 1] << 8 | i[s + 2] << 16, this.words[u] |= c << b & 67108863, this.words[u + 1] = c >>> 26 - b & 67108863, b += 24, b >= 26 && (b -= 26, u++); + return this.strip(); + }; + function m(v, i) { + var a = v.charCodeAt(i); + return a >= 65 && a <= 70 ? a - 55 : a >= 97 && a <= 102 ? a - 87 : a - 48 & 15; + } + function y(v, i, a) { + var h = m(v, a); + return a - 1 >= i && (h |= m(v, a - 1) << 4), h; + } + f.prototype._parseHex = function(i, a, h) { + this.length = Math.ceil((i.length - a) / 6), this.words = new Array(this.length); + for (var s = 0;s < this.length; s++) + this.words[s] = 0; + var u = 0, c = 0, b; + if (h === "be") + for (s = i.length - 1;s >= a; s -= 2) + b = y(i, a, s) << u, this.words[c] |= b & 67108863, u >= 18 ? (u -= 18, c += 1, this.words[c] |= b >>> 26) : u += 8; + else { + var l = i.length - a; + for (s = l % 2 === 0 ? a + 1 : a;s < i.length; s += 2) + b = y(i, a, s) << u, this.words[c] |= b & 67108863, u >= 18 ? (u -= 18, c += 1, this.words[c] |= b >>> 26) : u += 8; + } + this.strip(); + }; + function M(v, i, a, h) { + for (var s = 0, u = Math.min(v.length, a), c = i;c < u; c++) { + var b = v.charCodeAt(c) - 48; + s *= h, b >= 49 ? s += b - 49 + 10 : b >= 17 ? s += b - 17 + 10 : s += b; + } + return s; + } + f.prototype._parseBase = function(i, a, h) { + this.words = [0], this.length = 1; + for (var s = 0, u = 1;u <= 67108863; u *= a) + s++; + s--, u = u / a | 0; + for (var c = i.length - h, b = c % s, l = Math.min(c, c - b) + h, n = 0, d = h;d < l; d += s) + n = M(i, d, d + s, a), this.imuln(u), this.words[0] + n < 67108864 ? this.words[0] += n : this._iaddn(n); + if (b !== 0) { + var w = 1; + for (n = M(i, d, i.length, a), d = 0;d < b; d++) + w *= a; + this.imuln(w), this.words[0] + n < 67108864 ? this.words[0] += n : this._iaddn(n); + } + this.strip(); + }, f.prototype.copy = function(i) { + i.words = new Array(this.length); + for (var a = 0;a < this.length; a++) + i.words[a] = this.words[a]; + i.length = this.length, i.negative = this.negative, i.red = this.red; + }, f.prototype.clone = function() { + var i = new f(null); + return this.copy(i), i; + }, f.prototype._expand = function(i) { + for (;this.length < i; ) + this.words[this.length++] = 0; + return this; + }, f.prototype.strip = function() { + for (;this.length > 1 && this.words[this.length - 1] === 0; ) + this.length--; + return this._normSign(); + }, f.prototype._normSign = function() { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }, f.prototype.inspect = function() { + return (this.red ? ""; + }; + var x = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], S = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], E2 = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; + f.prototype.toString = function(i, a) { + i = i || 10, a = a | 0 || 1; + var h; + if (i === 16 || i === "hex") { + h = ""; + for (var s = 0, u = 0, c = 0;c < this.length; c++) { + var b = this.words[c], l = ((b << s | u) & 16777215).toString(16); + u = b >>> 24 - s & 16777215, u !== 0 || c !== this.length - 1 ? h = x[6 - l.length] + l + h : h = l + h, s += 2, s >= 26 && (s -= 26, c--); + } + for (u !== 0 && (h = u.toString(16) + h);h.length % a !== 0; ) + h = "0" + h; + return this.negative !== 0 && (h = "-" + h), h; + } + if (i === (i | 0) && i >= 2 && i <= 36) { + var n = S[i], d = E2[i]; + h = ""; + var w = this.clone(); + for (w.negative = 0;!w.isZero(); ) { + var g = w.modn(d).toString(i); + w = w.idivn(d), w.isZero() ? h = g + h : h = x[n - g.length] + g + h; + } + for (this.isZero() && (h = "0" + h);h.length % a !== 0; ) + h = "0" + h; + return this.negative !== 0 && (h = "-" + h), h; + } + r(false, "Base should be between 2 and 36"); + }, f.prototype.toNumber = function() { + var i = this.words[0]; + return this.length === 2 ? i += this.words[1] * 67108864 : this.length === 3 && this.words[2] === 1 ? i += 4503599627370496 + this.words[1] * 67108864 : this.length > 2 && r(false, "Number can only safely store up to 53 bits"), this.negative !== 0 ? -i : i; + }, f.prototype.toJSON = function() { + return this.toString(16); + }, f.prototype.toBuffer = function(i, a) { + return r(typeof p < "u"), this.toArrayLike(p, i, a); + }, f.prototype.toArray = function(i, a) { + return this.toArrayLike(Array, i, a); + }, f.prototype.toArrayLike = function(i, a, h) { + var s = this.byteLength(), u = h || Math.max(1, s); + r(s <= u, "byte array longer than desired length"), r(u > 0, "Requested array length <= 0"), this.strip(); + var c = a === "le", b = new i(u), l, n, d = this.clone(); + if (c) { + for (n = 0;!d.isZero(); n++) + l = d.andln(255), d.iushrn(8), b[n] = l; + for (;n < u; n++) + b[n] = 0; + } else { + for (n = 0;n < u - s; n++) + b[n] = 0; + for (n = 0;!d.isZero(); n++) + l = d.andln(255), d.iushrn(8), b[u - n - 1] = l; + } + return b; + }, Math.clz32 ? f.prototype._countBits = function(i) { + return 32 - Math.clz32(i); + } : f.prototype._countBits = function(i) { + var a = i, h = 0; + return a >= 4096 && (h += 13, a >>>= 13), a >= 64 && (h += 7, a >>>= 7), a >= 8 && (h += 4, a >>>= 4), a >= 2 && (h += 2, a >>>= 2), h + a; + }, f.prototype._zeroBits = function(i) { + if (i === 0) + return 26; + var a = i, h = 0; + return (a & 8191) === 0 && (h += 13, a >>>= 13), (a & 127) === 0 && (h += 7, a >>>= 7), (a & 15) === 0 && (h += 4, a >>>= 4), (a & 3) === 0 && (h += 2, a >>>= 2), (a & 1) === 0 && h++, h; + }, f.prototype.bitLength = function() { + var i = this.words[this.length - 1], a = this._countBits(i); + return (this.length - 1) * 26 + a; + }; + function B(v) { + for (var i = new Array(v.bitLength()), a = 0;a < i.length; a++) { + var h = a / 26 | 0, s = a % 26; + i[a] = (v.words[h] & 1 << s) >>> s; + } + return i; + } + f.prototype.zeroBits = function() { + if (this.isZero()) + return 0; + for (var i = 0, a = 0;a < this.length; a++) { + var h = this._zeroBits(this.words[a]); + if (i += h, h !== 26) + break; + } + return i; + }, f.prototype.byteLength = function() { + return Math.ceil(this.bitLength() / 8); + }, f.prototype.toTwos = function(i) { + return this.negative !== 0 ? this.abs().inotn(i).iaddn(1) : this.clone(); + }, f.prototype.fromTwos = function(i) { + return this.testn(i - 1) ? this.notn(i).iaddn(1).ineg() : this.clone(); + }, f.prototype.isNeg = function() { + return this.negative !== 0; + }, f.prototype.neg = function() { + return this.clone().ineg(); + }, f.prototype.ineg = function() { + return this.isZero() || (this.negative ^= 1), this; + }, f.prototype.iuor = function(i) { + for (;this.length < i.length; ) + this.words[this.length++] = 0; + for (var a = 0;a < i.length; a++) + this.words[a] = this.words[a] | i.words[a]; + return this.strip(); + }, f.prototype.ior = function(i) { + return r((this.negative | i.negative) === 0), this.iuor(i); + }, f.prototype.or = function(i) { + return this.length > i.length ? this.clone().ior(i) : i.clone().ior(this); + }, f.prototype.uor = function(i) { + return this.length > i.length ? this.clone().iuor(i) : i.clone().iuor(this); + }, f.prototype.iuand = function(i) { + var a; + this.length > i.length ? a = i : a = this; + for (var h = 0;h < a.length; h++) + this.words[h] = this.words[h] & i.words[h]; + return this.length = a.length, this.strip(); + }, f.prototype.iand = function(i) { + return r((this.negative | i.negative) === 0), this.iuand(i); + }, f.prototype.and = function(i) { + return this.length > i.length ? this.clone().iand(i) : i.clone().iand(this); + }, f.prototype.uand = function(i) { + return this.length > i.length ? this.clone().iuand(i) : i.clone().iuand(this); + }, f.prototype.iuxor = function(i) { + var a, h; + this.length > i.length ? (a = this, h = i) : (a = i, h = this); + for (var s = 0;s < h.length; s++) + this.words[s] = a.words[s] ^ h.words[s]; + if (this !== a) + for (;s < a.length; s++) + this.words[s] = a.words[s]; + return this.length = a.length, this.strip(); + }, f.prototype.ixor = function(i) { + return r((this.negative | i.negative) === 0), this.iuxor(i); + }, f.prototype.xor = function(i) { + return this.length > i.length ? this.clone().ixor(i) : i.clone().ixor(this); + }, f.prototype.uxor = function(i) { + return this.length > i.length ? this.clone().iuxor(i) : i.clone().iuxor(this); + }, f.prototype.inotn = function(i) { + r(typeof i == "number" && i >= 0); + var a = Math.ceil(i / 26) | 0, h = i % 26; + this._expand(a), h > 0 && a--; + for (var s = 0;s < a; s++) + this.words[s] = ~this.words[s] & 67108863; + return h > 0 && (this.words[s] = ~this.words[s] & 67108863 >> 26 - h), this.strip(); + }, f.prototype.notn = function(i) { + return this.clone().inotn(i); + }, f.prototype.setn = function(i, a) { + r(typeof i == "number" && i >= 0); + var h = i / 26 | 0, s = i % 26; + return this._expand(h + 1), a ? this.words[h] = this.words[h] | 1 << s : this.words[h] = this.words[h] & ~(1 << s), this.strip(); + }, f.prototype.iadd = function(i) { + var a; + if (this.negative !== 0 && i.negative === 0) + return this.negative = 0, a = this.isub(i), this.negative ^= 1, this._normSign(); + if (this.negative === 0 && i.negative !== 0) + return i.negative = 0, a = this.isub(i), i.negative = 1, a._normSign(); + var h, s; + this.length > i.length ? (h = this, s = i) : (h = i, s = this); + for (var u = 0, c = 0;c < s.length; c++) + a = (h.words[c] | 0) + (s.words[c] | 0) + u, this.words[c] = a & 67108863, u = a >>> 26; + for (;u !== 0 && c < h.length; c++) + a = (h.words[c] | 0) + u, this.words[c] = a & 67108863, u = a >>> 26; + if (this.length = h.length, u !== 0) + this.words[this.length] = u, this.length++; + else if (h !== this) + for (;c < h.length; c++) + this.words[c] = h.words[c]; + return this; + }, f.prototype.add = function(i) { + var a; + return i.negative !== 0 && this.negative === 0 ? (i.negative = 0, a = this.sub(i), i.negative ^= 1, a) : i.negative === 0 && this.negative !== 0 ? (this.negative = 0, a = i.sub(this), this.negative = 1, a) : this.length > i.length ? this.clone().iadd(i) : i.clone().iadd(this); + }, f.prototype.isub = function(i) { + if (i.negative !== 0) { + i.negative = 0; + var a = this.iadd(i); + return i.negative = 1, a._normSign(); + } else if (this.negative !== 0) + return this.negative = 0, this.iadd(i), this.negative = 1, this._normSign(); + var h = this.cmp(i); + if (h === 0) + return this.negative = 0, this.length = 1, this.words[0] = 0, this; + var s, u; + h > 0 ? (s = this, u = i) : (s = i, u = this); + for (var c = 0, b = 0;b < u.length; b++) + a = (s.words[b] | 0) - (u.words[b] | 0) + c, c = a >> 26, this.words[b] = a & 67108863; + for (;c !== 0 && b < s.length; b++) + a = (s.words[b] | 0) + c, c = a >> 26, this.words[b] = a & 67108863; + if (c === 0 && b < s.length && s !== this) + for (;b < s.length; b++) + this.words[b] = s.words[b]; + return this.length = Math.max(this.length, b), s !== this && (this.negative = 1), this.strip(); + }, f.prototype.sub = function(i) { + return this.clone().isub(i); + }; + function q(v, i, a) { + a.negative = i.negative ^ v.negative; + var h = v.length + i.length | 0; + a.length = h, h = h - 1 | 0; + var s = v.words[0] | 0, u = i.words[0] | 0, c = s * u, b = c & 67108863, l = c / 67108864 | 0; + a.words[0] = b; + for (var n = 1;n < h; n++) { + for (var d = l >>> 26, w = l & 67108863, g = Math.min(n, i.length - 1), _9 = Math.max(0, n - v.length + 1);_9 <= g; _9++) { + var A = n - _9 | 0; + s = v.words[A] | 0, u = i.words[_9] | 0, c = s * u + w, d += c / 67108864 | 0, w = c & 67108863; + } + a.words[n] = w | 0, l = d | 0; + } + return l !== 0 ? a.words[n] = l | 0 : a.length--, a.strip(); + } + var L = function(i, a, h) { + var s = i.words, u = a.words, c = h.words, b = 0, l, n, d, w = s[0] | 0, g = w & 8191, _9 = w >>> 13, A = s[1] | 0, R = A & 8191, I2 = A >>> 13, Me = s[2] | 0, k2 = Me & 8191, D = Me >>> 13, nt = s[3] | 0, C2 = nt & 8191, O = nt >>> 13, vt = s[4] | 0, F = vt & 8191, U = vt >>> 13, bt = s[5] | 0, z = bt & 8191, H = bt >>> 13, mt = s[6] | 0, W = mt & 8191, K = mt >>> 13, gt = s[7] | 0, j = gt & 8191, Z = gt >>> 13, yt = s[8] | 0, V2 = yt & 8191, $ = yt >>> 13, wt = s[9] | 0, G = wt & 8191, Y = wt >>> 13, Mt = u[0] | 0, X = Mt & 8191, J2 = Mt >>> 13, _t = u[1] | 0, Q = _t & 8191, ee = _t >>> 13, xt2 = u[2] | 0, te2 = xt2 & 8191, re = xt2 >>> 13, St = u[3] | 0, ie = St & 8191, ne = St >>> 13, Et2 = u[4] | 0, fe = Et2 & 8191, ae2 = Et2 >>> 13, At2 = u[5] | 0, oe = At2 & 8191, se2 = At2 >>> 13, Rt = u[6] | 0, he = Rt & 8191, ue2 = Rt >>> 13, Bt = u[7] | 0, le = Bt & 8191, de = Bt >>> 13, qt = u[8] | 0, ce2 = qt & 8191, pe2 = qt >>> 13, It = u[9] | 0, ve = It & 8191, be = It >>> 13; + h.negative = i.negative ^ a.negative, h.length = 19, l = Math.imul(g, X), n = Math.imul(g, J2), n = n + Math.imul(_9, X) | 0, d = Math.imul(_9, J2); + var ft = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (ft >>> 26) | 0, ft &= 67108863, l = Math.imul(R, X), n = Math.imul(R, J2), n = n + Math.imul(I2, X) | 0, d = Math.imul(I2, J2), l = l + Math.imul(g, Q) | 0, n = n + Math.imul(g, ee) | 0, n = n + Math.imul(_9, Q) | 0, d = d + Math.imul(_9, ee) | 0; + var Be = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Be >>> 26) | 0, Be &= 67108863, l = Math.imul(k2, X), n = Math.imul(k2, J2), n = n + Math.imul(D, X) | 0, d = Math.imul(D, J2), l = l + Math.imul(R, Q) | 0, n = n + Math.imul(R, ee) | 0, n = n + Math.imul(I2, Q) | 0, d = d + Math.imul(I2, ee) | 0, l = l + Math.imul(g, te2) | 0, n = n + Math.imul(g, re) | 0, n = n + Math.imul(_9, te2) | 0, d = d + Math.imul(_9, re) | 0; + var qe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (qe >>> 26) | 0, qe &= 67108863, l = Math.imul(C2, X), n = Math.imul(C2, J2), n = n + Math.imul(O, X) | 0, d = Math.imul(O, J2), l = l + Math.imul(k2, Q) | 0, n = n + Math.imul(k2, ee) | 0, n = n + Math.imul(D, Q) | 0, d = d + Math.imul(D, ee) | 0, l = l + Math.imul(R, te2) | 0, n = n + Math.imul(R, re) | 0, n = n + Math.imul(I2, te2) | 0, d = d + Math.imul(I2, re) | 0, l = l + Math.imul(g, ie) | 0, n = n + Math.imul(g, ne) | 0, n = n + Math.imul(_9, ie) | 0, d = d + Math.imul(_9, ne) | 0; + var ze = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (ze >>> 26) | 0, ze &= 67108863, l = Math.imul(F, X), n = Math.imul(F, J2), n = n + Math.imul(U, X) | 0, d = Math.imul(U, J2), l = l + Math.imul(C2, Q) | 0, n = n + Math.imul(C2, ee) | 0, n = n + Math.imul(O, Q) | 0, d = d + Math.imul(O, ee) | 0, l = l + Math.imul(k2, te2) | 0, n = n + Math.imul(k2, re) | 0, n = n + Math.imul(D, te2) | 0, d = d + Math.imul(D, re) | 0, l = l + Math.imul(R, ie) | 0, n = n + Math.imul(R, ne) | 0, n = n + Math.imul(I2, ie) | 0, d = d + Math.imul(I2, ne) | 0, l = l + Math.imul(g, fe) | 0, n = n + Math.imul(g, ae2) | 0, n = n + Math.imul(_9, fe) | 0, d = d + Math.imul(_9, ae2) | 0; + var He2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (He2 >>> 26) | 0, He2 &= 67108863, l = Math.imul(z, X), n = Math.imul(z, J2), n = n + Math.imul(H, X) | 0, d = Math.imul(H, J2), l = l + Math.imul(F, Q) | 0, n = n + Math.imul(F, ee) | 0, n = n + Math.imul(U, Q) | 0, d = d + Math.imul(U, ee) | 0, l = l + Math.imul(C2, te2) | 0, n = n + Math.imul(C2, re) | 0, n = n + Math.imul(O, te2) | 0, d = d + Math.imul(O, re) | 0, l = l + Math.imul(k2, ie) | 0, n = n + Math.imul(k2, ne) | 0, n = n + Math.imul(D, ie) | 0, d = d + Math.imul(D, ne) | 0, l = l + Math.imul(R, fe) | 0, n = n + Math.imul(R, ae2) | 0, n = n + Math.imul(I2, fe) | 0, d = d + Math.imul(I2, ae2) | 0, l = l + Math.imul(g, oe) | 0, n = n + Math.imul(g, se2) | 0, n = n + Math.imul(_9, oe) | 0, d = d + Math.imul(_9, se2) | 0; + var We = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (We >>> 26) | 0, We &= 67108863, l = Math.imul(W, X), n = Math.imul(W, J2), n = n + Math.imul(K, X) | 0, d = Math.imul(K, J2), l = l + Math.imul(z, Q) | 0, n = n + Math.imul(z, ee) | 0, n = n + Math.imul(H, Q) | 0, d = d + Math.imul(H, ee) | 0, l = l + Math.imul(F, te2) | 0, n = n + Math.imul(F, re) | 0, n = n + Math.imul(U, te2) | 0, d = d + Math.imul(U, re) | 0, l = l + Math.imul(C2, ie) | 0, n = n + Math.imul(C2, ne) | 0, n = n + Math.imul(O, ie) | 0, d = d + Math.imul(O, ne) | 0, l = l + Math.imul(k2, fe) | 0, n = n + Math.imul(k2, ae2) | 0, n = n + Math.imul(D, fe) | 0, d = d + Math.imul(D, ae2) | 0, l = l + Math.imul(R, oe) | 0, n = n + Math.imul(R, se2) | 0, n = n + Math.imul(I2, oe) | 0, d = d + Math.imul(I2, se2) | 0, l = l + Math.imul(g, he) | 0, n = n + Math.imul(g, ue2) | 0, n = n + Math.imul(_9, he) | 0, d = d + Math.imul(_9, ue2) | 0; + var Ke2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ke2 >>> 26) | 0, Ke2 &= 67108863, l = Math.imul(j, X), n = Math.imul(j, J2), n = n + Math.imul(Z, X) | 0, d = Math.imul(Z, J2), l = l + Math.imul(W, Q) | 0, n = n + Math.imul(W, ee) | 0, n = n + Math.imul(K, Q) | 0, d = d + Math.imul(K, ee) | 0, l = l + Math.imul(z, te2) | 0, n = n + Math.imul(z, re) | 0, n = n + Math.imul(H, te2) | 0, d = d + Math.imul(H, re) | 0, l = l + Math.imul(F, ie) | 0, n = n + Math.imul(F, ne) | 0, n = n + Math.imul(U, ie) | 0, d = d + Math.imul(U, ne) | 0, l = l + Math.imul(C2, fe) | 0, n = n + Math.imul(C2, ae2) | 0, n = n + Math.imul(O, fe) | 0, d = d + Math.imul(O, ae2) | 0, l = l + Math.imul(k2, oe) | 0, n = n + Math.imul(k2, se2) | 0, n = n + Math.imul(D, oe) | 0, d = d + Math.imul(D, se2) | 0, l = l + Math.imul(R, he) | 0, n = n + Math.imul(R, ue2) | 0, n = n + Math.imul(I2, he) | 0, d = d + Math.imul(I2, ue2) | 0, l = l + Math.imul(g, le) | 0, n = n + Math.imul(g, de) | 0, n = n + Math.imul(_9, le) | 0, d = d + Math.imul(_9, de) | 0; + var je = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (je >>> 26) | 0, je &= 67108863, l = Math.imul(V2, X), n = Math.imul(V2, J2), n = n + Math.imul($, X) | 0, d = Math.imul($, J2), l = l + Math.imul(j, Q) | 0, n = n + Math.imul(j, ee) | 0, n = n + Math.imul(Z, Q) | 0, d = d + Math.imul(Z, ee) | 0, l = l + Math.imul(W, te2) | 0, n = n + Math.imul(W, re) | 0, n = n + Math.imul(K, te2) | 0, d = d + Math.imul(K, re) | 0, l = l + Math.imul(z, ie) | 0, n = n + Math.imul(z, ne) | 0, n = n + Math.imul(H, ie) | 0, d = d + Math.imul(H, ne) | 0, l = l + Math.imul(F, fe) | 0, n = n + Math.imul(F, ae2) | 0, n = n + Math.imul(U, fe) | 0, d = d + Math.imul(U, ae2) | 0, l = l + Math.imul(C2, oe) | 0, n = n + Math.imul(C2, se2) | 0, n = n + Math.imul(O, oe) | 0, d = d + Math.imul(O, se2) | 0, l = l + Math.imul(k2, he) | 0, n = n + Math.imul(k2, ue2) | 0, n = n + Math.imul(D, he) | 0, d = d + Math.imul(D, ue2) | 0, l = l + Math.imul(R, le) | 0, n = n + Math.imul(R, de) | 0, n = n + Math.imul(I2, le) | 0, d = d + Math.imul(I2, de) | 0, l = l + Math.imul(g, ce2) | 0, n = n + Math.imul(g, pe2) | 0, n = n + Math.imul(_9, ce2) | 0, d = d + Math.imul(_9, pe2) | 0; + var Ze2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ze2 >>> 26) | 0, Ze2 &= 67108863, l = Math.imul(G, X), n = Math.imul(G, J2), n = n + Math.imul(Y, X) | 0, d = Math.imul(Y, J2), l = l + Math.imul(V2, Q) | 0, n = n + Math.imul(V2, ee) | 0, n = n + Math.imul($, Q) | 0, d = d + Math.imul($, ee) | 0, l = l + Math.imul(j, te2) | 0, n = n + Math.imul(j, re) | 0, n = n + Math.imul(Z, te2) | 0, d = d + Math.imul(Z, re) | 0, l = l + Math.imul(W, ie) | 0, n = n + Math.imul(W, ne) | 0, n = n + Math.imul(K, ie) | 0, d = d + Math.imul(K, ne) | 0, l = l + Math.imul(z, fe) | 0, n = n + Math.imul(z, ae2) | 0, n = n + Math.imul(H, fe) | 0, d = d + Math.imul(H, ae2) | 0, l = l + Math.imul(F, oe) | 0, n = n + Math.imul(F, se2) | 0, n = n + Math.imul(U, oe) | 0, d = d + Math.imul(U, se2) | 0, l = l + Math.imul(C2, he) | 0, n = n + Math.imul(C2, ue2) | 0, n = n + Math.imul(O, he) | 0, d = d + Math.imul(O, ue2) | 0, l = l + Math.imul(k2, le) | 0, n = n + Math.imul(k2, de) | 0, n = n + Math.imul(D, le) | 0, d = d + Math.imul(D, de) | 0, l = l + Math.imul(R, ce2) | 0, n = n + Math.imul(R, pe2) | 0, n = n + Math.imul(I2, ce2) | 0, d = d + Math.imul(I2, pe2) | 0, l = l + Math.imul(g, ve) | 0, n = n + Math.imul(g, be) | 0, n = n + Math.imul(_9, ve) | 0, d = d + Math.imul(_9, be) | 0; + var Ve = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ve >>> 26) | 0, Ve &= 67108863, l = Math.imul(G, Q), n = Math.imul(G, ee), n = n + Math.imul(Y, Q) | 0, d = Math.imul(Y, ee), l = l + Math.imul(V2, te2) | 0, n = n + Math.imul(V2, re) | 0, n = n + Math.imul($, te2) | 0, d = d + Math.imul($, re) | 0, l = l + Math.imul(j, ie) | 0, n = n + Math.imul(j, ne) | 0, n = n + Math.imul(Z, ie) | 0, d = d + Math.imul(Z, ne) | 0, l = l + Math.imul(W, fe) | 0, n = n + Math.imul(W, ae2) | 0, n = n + Math.imul(K, fe) | 0, d = d + Math.imul(K, ae2) | 0, l = l + Math.imul(z, oe) | 0, n = n + Math.imul(z, se2) | 0, n = n + Math.imul(H, oe) | 0, d = d + Math.imul(H, se2) | 0, l = l + Math.imul(F, he) | 0, n = n + Math.imul(F, ue2) | 0, n = n + Math.imul(U, he) | 0, d = d + Math.imul(U, ue2) | 0, l = l + Math.imul(C2, le) | 0, n = n + Math.imul(C2, de) | 0, n = n + Math.imul(O, le) | 0, d = d + Math.imul(O, de) | 0, l = l + Math.imul(k2, ce2) | 0, n = n + Math.imul(k2, pe2) | 0, n = n + Math.imul(D, ce2) | 0, d = d + Math.imul(D, pe2) | 0, l = l + Math.imul(R, ve) | 0, n = n + Math.imul(R, be) | 0, n = n + Math.imul(I2, ve) | 0, d = d + Math.imul(I2, be) | 0; + var $e = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + ($e >>> 26) | 0, $e &= 67108863, l = Math.imul(G, te2), n = Math.imul(G, re), n = n + Math.imul(Y, te2) | 0, d = Math.imul(Y, re), l = l + Math.imul(V2, ie) | 0, n = n + Math.imul(V2, ne) | 0, n = n + Math.imul($, ie) | 0, d = d + Math.imul($, ne) | 0, l = l + Math.imul(j, fe) | 0, n = n + Math.imul(j, ae2) | 0, n = n + Math.imul(Z, fe) | 0, d = d + Math.imul(Z, ae2) | 0, l = l + Math.imul(W, oe) | 0, n = n + Math.imul(W, se2) | 0, n = n + Math.imul(K, oe) | 0, d = d + Math.imul(K, se2) | 0, l = l + Math.imul(z, he) | 0, n = n + Math.imul(z, ue2) | 0, n = n + Math.imul(H, he) | 0, d = d + Math.imul(H, ue2) | 0, l = l + Math.imul(F, le) | 0, n = n + Math.imul(F, de) | 0, n = n + Math.imul(U, le) | 0, d = d + Math.imul(U, de) | 0, l = l + Math.imul(C2, ce2) | 0, n = n + Math.imul(C2, pe2) | 0, n = n + Math.imul(O, ce2) | 0, d = d + Math.imul(O, pe2) | 0, l = l + Math.imul(k2, ve) | 0, n = n + Math.imul(k2, be) | 0, n = n + Math.imul(D, ve) | 0, d = d + Math.imul(D, be) | 0; + var Ge = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ge >>> 26) | 0, Ge &= 67108863, l = Math.imul(G, ie), n = Math.imul(G, ne), n = n + Math.imul(Y, ie) | 0, d = Math.imul(Y, ne), l = l + Math.imul(V2, fe) | 0, n = n + Math.imul(V2, ae2) | 0, n = n + Math.imul($, fe) | 0, d = d + Math.imul($, ae2) | 0, l = l + Math.imul(j, oe) | 0, n = n + Math.imul(j, se2) | 0, n = n + Math.imul(Z, oe) | 0, d = d + Math.imul(Z, se2) | 0, l = l + Math.imul(W, he) | 0, n = n + Math.imul(W, ue2) | 0, n = n + Math.imul(K, he) | 0, d = d + Math.imul(K, ue2) | 0, l = l + Math.imul(z, le) | 0, n = n + Math.imul(z, de) | 0, n = n + Math.imul(H, le) | 0, d = d + Math.imul(H, de) | 0, l = l + Math.imul(F, ce2) | 0, n = n + Math.imul(F, pe2) | 0, n = n + Math.imul(U, ce2) | 0, d = d + Math.imul(U, pe2) | 0, l = l + Math.imul(C2, ve) | 0, n = n + Math.imul(C2, be) | 0, n = n + Math.imul(O, ve) | 0, d = d + Math.imul(O, be) | 0; + var Ye = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ye >>> 26) | 0, Ye &= 67108863, l = Math.imul(G, fe), n = Math.imul(G, ae2), n = n + Math.imul(Y, fe) | 0, d = Math.imul(Y, ae2), l = l + Math.imul(V2, oe) | 0, n = n + Math.imul(V2, se2) | 0, n = n + Math.imul($, oe) | 0, d = d + Math.imul($, se2) | 0, l = l + Math.imul(j, he) | 0, n = n + Math.imul(j, ue2) | 0, n = n + Math.imul(Z, he) | 0, d = d + Math.imul(Z, ue2) | 0, l = l + Math.imul(W, le) | 0, n = n + Math.imul(W, de) | 0, n = n + Math.imul(K, le) | 0, d = d + Math.imul(K, de) | 0, l = l + Math.imul(z, ce2) | 0, n = n + Math.imul(z, pe2) | 0, n = n + Math.imul(H, ce2) | 0, d = d + Math.imul(H, pe2) | 0, l = l + Math.imul(F, ve) | 0, n = n + Math.imul(F, be) | 0, n = n + Math.imul(U, ve) | 0, d = d + Math.imul(U, be) | 0; + var Xe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Xe >>> 26) | 0, Xe &= 67108863, l = Math.imul(G, oe), n = Math.imul(G, se2), n = n + Math.imul(Y, oe) | 0, d = Math.imul(Y, se2), l = l + Math.imul(V2, he) | 0, n = n + Math.imul(V2, ue2) | 0, n = n + Math.imul($, he) | 0, d = d + Math.imul($, ue2) | 0, l = l + Math.imul(j, le) | 0, n = n + Math.imul(j, de) | 0, n = n + Math.imul(Z, le) | 0, d = d + Math.imul(Z, de) | 0, l = l + Math.imul(W, ce2) | 0, n = n + Math.imul(W, pe2) | 0, n = n + Math.imul(K, ce2) | 0, d = d + Math.imul(K, pe2) | 0, l = l + Math.imul(z, ve) | 0, n = n + Math.imul(z, be) | 0, n = n + Math.imul(H, ve) | 0, d = d + Math.imul(H, be) | 0; + var Je = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Je >>> 26) | 0, Je &= 67108863, l = Math.imul(G, he), n = Math.imul(G, ue2), n = n + Math.imul(Y, he) | 0, d = Math.imul(Y, ue2), l = l + Math.imul(V2, le) | 0, n = n + Math.imul(V2, de) | 0, n = n + Math.imul($, le) | 0, d = d + Math.imul($, de) | 0, l = l + Math.imul(j, ce2) | 0, n = n + Math.imul(j, pe2) | 0, n = n + Math.imul(Z, ce2) | 0, d = d + Math.imul(Z, pe2) | 0, l = l + Math.imul(W, ve) | 0, n = n + Math.imul(W, be) | 0, n = n + Math.imul(K, ve) | 0, d = d + Math.imul(K, be) | 0; + var Qe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Qe >>> 26) | 0, Qe &= 67108863, l = Math.imul(G, le), n = Math.imul(G, de), n = n + Math.imul(Y, le) | 0, d = Math.imul(Y, de), l = l + Math.imul(V2, ce2) | 0, n = n + Math.imul(V2, pe2) | 0, n = n + Math.imul($, ce2) | 0, d = d + Math.imul($, pe2) | 0, l = l + Math.imul(j, ve) | 0, n = n + Math.imul(j, be) | 0, n = n + Math.imul(Z, ve) | 0, d = d + Math.imul(Z, be) | 0; + var et2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (et2 >>> 26) | 0, et2 &= 67108863, l = Math.imul(G, ce2), n = Math.imul(G, pe2), n = n + Math.imul(Y, ce2) | 0, d = Math.imul(Y, pe2), l = l + Math.imul(V2, ve) | 0, n = n + Math.imul(V2, be) | 0, n = n + Math.imul($, ve) | 0, d = d + Math.imul($, be) | 0; + var tt2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (tt2 >>> 26) | 0, tt2 &= 67108863, l = Math.imul(G, ve), n = Math.imul(G, be), n = n + Math.imul(Y, ve) | 0, d = Math.imul(Y, be); + var rt2 = (b + l | 0) + ((n & 8191) << 13) | 0; + return b = (d + (n >>> 13) | 0) + (rt2 >>> 26) | 0, rt2 &= 67108863, c[0] = ft, c[1] = Be, c[2] = qe, c[3] = ze, c[4] = He2, c[5] = We, c[6] = Ke2, c[7] = je, c[8] = Ze2, c[9] = Ve, c[10] = $e, c[11] = Ge, c[12] = Ye, c[13] = Xe, c[14] = Je, c[15] = Qe, c[16] = et2, c[17] = tt2, c[18] = rt2, b !== 0 && (c[19] = b, h.length++), h; + }; + Math.imul || (L = q); + function ge(v, i, a) { + a.negative = i.negative ^ v.negative, a.length = v.length + i.length; + for (var h = 0, s = 0, u = 0;u < a.length - 1; u++) { + var c = s; + s = 0; + for (var b = h & 67108863, l = Math.min(u, i.length - 1), n = Math.max(0, u - v.length + 1);n <= l; n++) { + var d = u - n, w = v.words[d] | 0, g = i.words[n] | 0, _9 = w * g, A = _9 & 67108863; + c = c + (_9 / 67108864 | 0) | 0, A = A + b | 0, b = A & 67108863, c = c + (A >>> 26) | 0, s += c >>> 26, c &= 67108863; + } + a.words[u] = b, h = c, c = s; + } + return h !== 0 ? a.words[u] = h : a.length--, a.strip(); + } + function _e(v, i, a) { + var h = new N; + return h.mulp(v, i, a); + } + f.prototype.mulTo = function(i, a) { + var h, s = this.length + i.length; + return this.length === 10 && i.length === 10 ? h = L(this, i, a) : s < 63 ? h = q(this, i, a) : s < 1024 ? h = ge(this, i, a) : h = _e(this, i, a), h; + }; + function N(v, i) { + this.x = v, this.y = i; + } + N.prototype.makeRBT = function(i) { + for (var a = new Array(i), h = f.prototype._countBits(i) - 1, s = 0;s < i; s++) + a[s] = this.revBin(s, h, i); + return a; + }, N.prototype.revBin = function(i, a, h) { + if (i === 0 || i === h - 1) + return i; + for (var s = 0, u = 0;u < a; u++) + s |= (i & 1) << a - u - 1, i >>= 1; + return s; + }, N.prototype.permute = function(i, a, h, s, u, c) { + for (var b = 0;b < c; b++) + s[b] = a[i[b]], u[b] = h[i[b]]; + }, N.prototype.transform = function(i, a, h, s, u, c) { + this.permute(c, i, a, h, s, u); + for (var b = 1;b < u; b <<= 1) + for (var l = b << 1, n = Math.cos(2 * Math.PI / l), d = Math.sin(2 * Math.PI / l), w = 0;w < u; w += l) + for (var g = n, _9 = d, A = 0;A < b; A++) { + var R = h[w + A], I2 = s[w + A], Me = h[w + A + b], k2 = s[w + A + b], D = g * Me - _9 * k2; + k2 = g * k2 + _9 * Me, Me = D, h[w + A] = R + Me, s[w + A] = I2 + k2, h[w + A + b] = R - Me, s[w + A + b] = I2 - k2, A !== l && (D = n * g - d * _9, _9 = n * _9 + d * g, g = D); + } + }, N.prototype.guessLen13b = function(i, a) { + var h = Math.max(a, i) | 1, s = h & 1, u = 0; + for (h = h / 2 | 0;h; h = h >>> 1) + u++; + return 1 << u + 1 + s; + }, N.prototype.conjugate = function(i, a, h) { + if (!(h <= 1)) + for (var s = 0;s < h / 2; s++) { + var u = i[s]; + i[s] = i[h - s - 1], i[h - s - 1] = u, u = a[s], a[s] = -a[h - s - 1], a[h - s - 1] = -u; + } + }, N.prototype.normalize13b = function(i, a) { + for (var h = 0, s = 0;s < a / 2; s++) { + var u = Math.round(i[2 * s + 1] / a) * 8192 + Math.round(i[2 * s] / a) + h; + i[s] = u & 67108863, u < 67108864 ? h = 0 : h = u / 67108864 | 0; + } + return i; + }, N.prototype.convert13b = function(i, a, h, s) { + for (var u = 0, c = 0;c < a; c++) + u = u + (i[c] | 0), h[2 * c] = u & 8191, u = u >>> 13, h[2 * c + 1] = u & 8191, u = u >>> 13; + for (c = 2 * a;c < s; ++c) + h[c] = 0; + r(u === 0), r((u & -8192) === 0); + }, N.prototype.stub = function(i) { + for (var a = new Array(i), h = 0;h < i; h++) + a[h] = 0; + return a; + }, N.prototype.mulp = function(i, a, h) { + var s = 2 * this.guessLen13b(i.length, a.length), u = this.makeRBT(s), c = this.stub(s), b = new Array(s), l = new Array(s), n = new Array(s), d = new Array(s), w = new Array(s), g = new Array(s), _9 = h.words; + _9.length = s, this.convert13b(i.words, i.length, b, s), this.convert13b(a.words, a.length, d, s), this.transform(b, c, l, n, s, u), this.transform(d, c, w, g, s, u); + for (var A = 0;A < s; A++) { + var R = l[A] * w[A] - n[A] * g[A]; + n[A] = l[A] * g[A] + n[A] * w[A], l[A] = R; + } + return this.conjugate(l, n, s), this.transform(l, n, _9, c, s, u), this.conjugate(_9, c, s), this.normalize13b(_9, s), h.negative = i.negative ^ a.negative, h.length = i.length + a.length, h.strip(); + }, f.prototype.mul = function(i) { + var a = new f(null); + return a.words = new Array(this.length + i.length), this.mulTo(i, a); + }, f.prototype.mulf = function(i) { + var a = new f(null); + return a.words = new Array(this.length + i.length), _e(this, i, a); + }, f.prototype.imul = function(i) { + return this.clone().mulTo(i, this); + }, f.prototype.imuln = function(i) { + r(typeof i == "number"), r(i < 67108864); + for (var a = 0, h = 0;h < this.length; h++) { + var s = (this.words[h] | 0) * i, u = (s & 67108863) + (a & 67108863); + a >>= 26, a += s / 67108864 | 0, a += u >>> 26, this.words[h] = u & 67108863; + } + return a !== 0 && (this.words[h] = a, this.length++), this; + }, f.prototype.muln = function(i) { + return this.clone().imuln(i); + }, f.prototype.sqr = function() { + return this.mul(this); + }, f.prototype.isqr = function() { + return this.imul(this.clone()); + }, f.prototype.pow = function(i) { + var a = B(i); + if (a.length === 0) + return new f(1); + for (var h = this, s = 0;s < a.length && a[s] === 0; s++, h = h.sqr()) + ; + if (++s < a.length) + for (var u = h.sqr();s < a.length; s++, u = u.sqr()) + a[s] !== 0 && (h = h.mul(u)); + return h; + }, f.prototype.iushln = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26, s = 67108863 >>> 26 - a << 26 - a, u; + if (a !== 0) { + var c = 0; + for (u = 0;u < this.length; u++) { + var b = this.words[u] & s, l = (this.words[u] | 0) - b << a; + this.words[u] = l | c, c = b >>> 26 - a; + } + c && (this.words[u] = c, this.length++); + } + if (h !== 0) { + for (u = this.length - 1;u >= 0; u--) + this.words[u + h] = this.words[u]; + for (u = 0;u < h; u++) + this.words[u] = 0; + this.length += h; + } + return this.strip(); + }, f.prototype.ishln = function(i) { + return r(this.negative === 0), this.iushln(i); + }, f.prototype.iushrn = function(i, a, h) { + r(typeof i == "number" && i >= 0); + var s; + a ? s = (a - a % 26) / 26 : s = 0; + var u = i % 26, c = Math.min((i - u) / 26, this.length), b = 67108863 ^ 67108863 >>> u << u, l = h; + if (s -= c, s = Math.max(0, s), l) { + for (var n = 0;n < c; n++) + l.words[n] = this.words[n]; + l.length = c; + } + if (c !== 0) + if (this.length > c) + for (this.length -= c, n = 0;n < this.length; n++) + this.words[n] = this.words[n + c]; + else + this.words[0] = 0, this.length = 1; + var d = 0; + for (n = this.length - 1;n >= 0 && (d !== 0 || n >= s); n--) { + var w = this.words[n] | 0; + this.words[n] = d << 26 - u | w >>> u, d = w & b; + } + return l && d !== 0 && (l.words[l.length++] = d), this.length === 0 && (this.words[0] = 0, this.length = 1), this.strip(); + }, f.prototype.ishrn = function(i, a, h) { + return r(this.negative === 0), this.iushrn(i, a, h); + }, f.prototype.shln = function(i) { + return this.clone().ishln(i); + }, f.prototype.ushln = function(i) { + return this.clone().iushln(i); + }, f.prototype.shrn = function(i) { + return this.clone().ishrn(i); + }, f.prototype.ushrn = function(i) { + return this.clone().iushrn(i); + }, f.prototype.testn = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26, s = 1 << a; + if (this.length <= h) + return false; + var u = this.words[h]; + return !!(u & s); + }, f.prototype.imaskn = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26; + if (r(this.negative === 0, "imaskn works only with positive numbers"), this.length <= h) + return this; + if (a !== 0 && h++, this.length = Math.min(h, this.length), a !== 0) { + var s = 67108863 ^ 67108863 >>> a << a; + this.words[this.length - 1] &= s; + } + return this.strip(); + }, f.prototype.maskn = function(i) { + return this.clone().imaskn(i); + }, f.prototype.iaddn = function(i) { + return r(typeof i == "number"), r(i < 67108864), i < 0 ? this.isubn(-i) : this.negative !== 0 ? this.length === 1 && (this.words[0] | 0) < i ? (this.words[0] = i - (this.words[0] | 0), this.negative = 0, this) : (this.negative = 0, this.isubn(i), this.negative = 1, this) : this._iaddn(i); + }, f.prototype._iaddn = function(i) { + this.words[0] += i; + for (var a = 0;a < this.length && this.words[a] >= 67108864; a++) + this.words[a] -= 67108864, a === this.length - 1 ? this.words[a + 1] = 1 : this.words[a + 1]++; + return this.length = Math.max(this.length, a + 1), this; + }, f.prototype.isubn = function(i) { + if (r(typeof i == "number"), r(i < 67108864), i < 0) + return this.iaddn(-i); + if (this.negative !== 0) + return this.negative = 0, this.iaddn(i), this.negative = 1, this; + if (this.words[0] -= i, this.length === 1 && this.words[0] < 0) + this.words[0] = -this.words[0], this.negative = 1; + else + for (var a = 0;a < this.length && this.words[a] < 0; a++) + this.words[a] += 67108864, this.words[a + 1] -= 1; + return this.strip(); + }, f.prototype.addn = function(i) { + return this.clone().iaddn(i); + }, f.prototype.subn = function(i) { + return this.clone().isubn(i); + }, f.prototype.iabs = function() { + return this.negative = 0, this; + }, f.prototype.abs = function() { + return this.clone().iabs(); + }, f.prototype._ishlnsubmul = function(i, a, h) { + var s = i.length + h, u; + this._expand(s); + var c, b = 0; + for (u = 0;u < i.length; u++) { + c = (this.words[u + h] | 0) + b; + var l = (i.words[u] | 0) * a; + c -= l & 67108863, b = (c >> 26) - (l / 67108864 | 0), this.words[u + h] = c & 67108863; + } + for (;u < this.length - h; u++) + c = (this.words[u + h] | 0) + b, b = c >> 26, this.words[u + h] = c & 67108863; + if (b === 0) + return this.strip(); + for (r(b === -1), b = 0, u = 0;u < this.length; u++) + c = -(this.words[u] | 0) + b, b = c >> 26, this.words[u] = c & 67108863; + return this.negative = 1, this.strip(); + }, f.prototype._wordDiv = function(i, a) { + var h = this.length - i.length, s = this.clone(), u = i, c = u.words[u.length - 1] | 0, b = this._countBits(c); + h = 26 - b, h !== 0 && (u = u.ushln(h), s.iushln(h), c = u.words[u.length - 1] | 0); + var l = s.length - u.length, n; + if (a !== "mod") { + n = new f(null), n.length = l + 1, n.words = new Array(n.length); + for (var d = 0;d < n.length; d++) + n.words[d] = 0; + } + var w = s.clone()._ishlnsubmul(u, 1, l); + w.negative === 0 && (s = w, n && (n.words[l] = 1)); + for (var g = l - 1;g >= 0; g--) { + var _9 = (s.words[u.length + g] | 0) * 67108864 + (s.words[u.length + g - 1] | 0); + for (_9 = Math.min(_9 / c | 0, 67108863), s._ishlnsubmul(u, _9, g);s.negative !== 0; ) + _9--, s.negative = 0, s._ishlnsubmul(u, 1, g), s.isZero() || (s.negative ^= 1); + n && (n.words[g] = _9); + } + return n && n.strip(), s.strip(), a !== "div" && h !== 0 && s.iushrn(h), { div: n || null, mod: s }; + }, f.prototype.divmod = function(i, a, h) { + if (r(!i.isZero()), this.isZero()) + return { div: new f(0), mod: new f(0) }; + var s, u, c; + return this.negative !== 0 && i.negative === 0 ? (c = this.neg().divmod(i, a), a !== "mod" && (s = c.div.neg()), a !== "div" && (u = c.mod.neg(), h && u.negative !== 0 && u.iadd(i)), { div: s, mod: u }) : this.negative === 0 && i.negative !== 0 ? (c = this.divmod(i.neg(), a), a !== "mod" && (s = c.div.neg()), { div: s, mod: c.mod }) : (this.negative & i.negative) !== 0 ? (c = this.neg().divmod(i.neg(), a), a !== "div" && (u = c.mod.neg(), h && u.negative !== 0 && u.isub(i)), { div: c.div, mod: u }) : i.length > this.length || this.cmp(i) < 0 ? { div: new f(0), mod: this } : i.length === 1 ? a === "div" ? { div: this.divn(i.words[0]), mod: null } : a === "mod" ? { div: null, mod: new f(this.modn(i.words[0])) } : { div: this.divn(i.words[0]), mod: new f(this.modn(i.words[0])) } : this._wordDiv(i, a); + }, f.prototype.div = function(i) { + return this.divmod(i, "div", false).div; + }, f.prototype.mod = function(i) { + return this.divmod(i, "mod", false).mod; + }, f.prototype.umod = function(i) { + return this.divmod(i, "mod", true).mod; + }, f.prototype.divRound = function(i) { + var a = this.divmod(i); + if (a.mod.isZero()) + return a.div; + var h = a.div.negative !== 0 ? a.mod.isub(i) : a.mod, s = i.ushrn(1), u = i.andln(1), c = h.cmp(s); + return c < 0 || u === 1 && c === 0 ? a.div : a.div.negative !== 0 ? a.div.isubn(1) : a.div.iaddn(1); + }, f.prototype.modn = function(i) { + r(i <= 67108863); + for (var a = (1 << 26) % i, h = 0, s = this.length - 1;s >= 0; s--) + h = (a * h + (this.words[s] | 0)) % i; + return h; + }, f.prototype.idivn = function(i) { + r(i <= 67108863); + for (var a = 0, h = this.length - 1;h >= 0; h--) { + var s = (this.words[h] | 0) + a * 67108864; + this.words[h] = s / i | 0, a = s % i; + } + return this.strip(); + }, f.prototype.divn = function(i) { + return this.clone().idivn(i); + }, f.prototype.egcd = function(i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, h = i.clone(); + a.negative !== 0 ? a = a.umod(i) : a = a.clone(); + for (var s = new f(1), u = new f(0), c = new f(0), b = new f(1), l = 0;a.isEven() && h.isEven(); ) + a.iushrn(1), h.iushrn(1), ++l; + for (var n = h.clone(), d = a.clone();!a.isZero(); ) { + for (var w = 0, g = 1;(a.words[0] & g) === 0 && w < 26; ++w, g <<= 1) + ; + if (w > 0) + for (a.iushrn(w);w-- > 0; ) + (s.isOdd() || u.isOdd()) && (s.iadd(n), u.isub(d)), s.iushrn(1), u.iushrn(1); + for (var _9 = 0, A = 1;(h.words[0] & A) === 0 && _9 < 26; ++_9, A <<= 1) + ; + if (_9 > 0) + for (h.iushrn(_9);_9-- > 0; ) + (c.isOdd() || b.isOdd()) && (c.iadd(n), b.isub(d)), c.iushrn(1), b.iushrn(1); + a.cmp(h) >= 0 ? (a.isub(h), s.isub(c), u.isub(b)) : (h.isub(a), c.isub(s), b.isub(u)); + } + return { a: c, b, gcd: h.iushln(l) }; + }, f.prototype._invmp = function(i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, h = i.clone(); + a.negative !== 0 ? a = a.umod(i) : a = a.clone(); + for (var s = new f(1), u = new f(0), c = h.clone();a.cmpn(1) > 0 && h.cmpn(1) > 0; ) { + for (var b = 0, l = 1;(a.words[0] & l) === 0 && b < 26; ++b, l <<= 1) + ; + if (b > 0) + for (a.iushrn(b);b-- > 0; ) + s.isOdd() && s.iadd(c), s.iushrn(1); + for (var n = 0, d = 1;(h.words[0] & d) === 0 && n < 26; ++n, d <<= 1) + ; + if (n > 0) + for (h.iushrn(n);n-- > 0; ) + u.isOdd() && u.iadd(c), u.iushrn(1); + a.cmp(h) >= 0 ? (a.isub(h), s.isub(u)) : (h.isub(a), u.isub(s)); + } + var w; + return a.cmpn(1) === 0 ? w = s : w = u, w.cmpn(0) < 0 && w.iadd(i), w; + }, f.prototype.gcd = function(i) { + if (this.isZero()) + return i.abs(); + if (i.isZero()) + return this.abs(); + var a = this.clone(), h = i.clone(); + a.negative = 0, h.negative = 0; + for (var s = 0;a.isEven() && h.isEven(); s++) + a.iushrn(1), h.iushrn(1); + do { + for (;a.isEven(); ) + a.iushrn(1); + for (;h.isEven(); ) + h.iushrn(1); + var u = a.cmp(h); + if (u < 0) { + var c = a; + a = h, h = c; + } else if (u === 0 || h.cmpn(1) === 0) + break; + a.isub(h); + } while (true); + return h.iushln(s); + }, f.prototype.invm = function(i) { + return this.egcd(i).a.umod(i); + }, f.prototype.isEven = function() { + return (this.words[0] & 1) === 0; + }, f.prototype.isOdd = function() { + return (this.words[0] & 1) === 1; + }, f.prototype.andln = function(i) { + return this.words[0] & i; + }, f.prototype.bincn = function(i) { + r(typeof i == "number"); + var a = i % 26, h = (i - a) / 26, s = 1 << a; + if (this.length <= h) + return this._expand(h + 1), this.words[h] |= s, this; + for (var u = s, c = h;u !== 0 && c < this.length; c++) { + var b = this.words[c] | 0; + b += u, u = b >>> 26, b &= 67108863, this.words[c] = b; + } + return u !== 0 && (this.words[c] = u, this.length++), this; + }, f.prototype.isZero = function() { + return this.length === 1 && this.words[0] === 0; + }, f.prototype.cmpn = function(i) { + var a = i < 0; + if (this.negative !== 0 && !a) + return -1; + if (this.negative === 0 && a) + return 1; + this.strip(); + var h; + if (this.length > 1) + h = 1; + else { + a && (i = -i), r(i <= 67108863, "Number is too big"); + var s = this.words[0] | 0; + h = s === i ? 0 : s < i ? -1 : 1; + } + return this.negative !== 0 ? -h | 0 : h; + }, f.prototype.cmp = function(i) { + if (this.negative !== 0 && i.negative === 0) + return -1; + if (this.negative === 0 && i.negative !== 0) + return 1; + var a = this.ucmp(i); + return this.negative !== 0 ? -a | 0 : a; + }, f.prototype.ucmp = function(i) { + if (this.length > i.length) + return 1; + if (this.length < i.length) + return -1; + for (var a = 0, h = this.length - 1;h >= 0; h--) { + var s = this.words[h] | 0, u = i.words[h] | 0; + if (s !== u) { + s < u ? a = -1 : s > u && (a = 1); + break; + } + } + return a; + }, f.prototype.gtn = function(i) { + return this.cmpn(i) === 1; + }, f.prototype.gt = function(i) { + return this.cmp(i) === 1; + }, f.prototype.gten = function(i) { + return this.cmpn(i) >= 0; + }, f.prototype.gte = function(i) { + return this.cmp(i) >= 0; + }, f.prototype.ltn = function(i) { + return this.cmpn(i) === -1; + }, f.prototype.lt = function(i) { + return this.cmp(i) === -1; + }, f.prototype.lten = function(i) { + return this.cmpn(i) <= 0; + }, f.prototype.lte = function(i) { + return this.cmp(i) <= 0; + }, f.prototype.eqn = function(i) { + return this.cmpn(i) === 0; + }, f.prototype.eq = function(i) { + return this.cmp(i) === 0; + }, f.red = function(i) { + return new P(i); + }, f.prototype.toRed = function(i) { + return r(!this.red, "Already a number in reduction context"), r(this.negative === 0, "red works only with positives"), i.convertTo(this)._forceRed(i); + }, f.prototype.fromRed = function() { + return r(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); + }, f.prototype._forceRed = function(i) { + return this.red = i, this; + }, f.prototype.forceRed = function(i) { + return r(!this.red, "Already a number in reduction context"), this._forceRed(i); + }, f.prototype.redAdd = function(i) { + return r(this.red, "redAdd works only with red numbers"), this.red.add(this, i); + }, f.prototype.redIAdd = function(i) { + return r(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, i); + }, f.prototype.redSub = function(i) { + return r(this.red, "redSub works only with red numbers"), this.red.sub(this, i); + }, f.prototype.redISub = function(i) { + return r(this.red, "redISub works only with red numbers"), this.red.isub(this, i); + }, f.prototype.redShl = function(i) { + return r(this.red, "redShl works only with red numbers"), this.red.shl(this, i); + }, f.prototype.redMul = function(i) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, i), this.red.mul(this, i); + }, f.prototype.redIMul = function(i) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, i), this.red.imul(this, i); + }, f.prototype.redSqr = function() { + return r(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); + }, f.prototype.redISqr = function() { + return r(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); + }, f.prototype.redSqrt = function() { + return r(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); + }, f.prototype.redInvm = function() { + return r(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); + }, f.prototype.redNeg = function() { + return r(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); + }, f.prototype.redPow = function(i) { + return r(this.red && !i.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, i); + }; + var we = { k256: null, p224: null, p192: null, p25519: null }; + function ye(v, i) { + this.name = v, this.p = new f(i, 16), this.n = this.p.bitLength(), this.k = new f(1).iushln(this.n).isub(this.p), this.tmp = this._tmp(); + } + ye.prototype._tmp = function() { + var i = new f(null); + return i.words = new Array(Math.ceil(this.n / 13)), i; + }, ye.prototype.ireduce = function(i) { + var a = i, h; + do + this.split(a, this.tmp), a = this.imulK(a), a = a.iadd(this.tmp), h = a.bitLength(); + while (h > this.n); + var s = h < this.n ? -1 : a.ucmp(this.p); + return s === 0 ? (a.words[0] = 0, a.length = 1) : s > 0 ? a.isub(this.p) : a.strip !== undefined ? a.strip() : a._strip(), a; + }, ye.prototype.split = function(i, a) { + i.iushrn(this.n, 0, a); + }, ye.prototype.imulK = function(i) { + return i.imul(this.k); + }; + function xe() { + ye.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); + } + o(xe, ye), xe.prototype.split = function(i, a) { + for (var h = 4194303, s = Math.min(i.length, 9), u = 0;u < s; u++) + a.words[u] = i.words[u]; + if (a.length = s, i.length <= 9) { + i.words[0] = 0, i.length = 1; + return; + } + var c = i.words[9]; + for (a.words[a.length++] = c & h, u = 10;u < i.length; u++) { + var b = i.words[u] | 0; + i.words[u - 10] = (b & h) << 4 | c >>> 22, c = b; + } + c >>>= 22, i.words[u - 10] = c, c === 0 && i.length > 10 ? i.length -= 10 : i.length -= 9; + }, xe.prototype.imulK = function(i) { + i.words[i.length] = 0, i.words[i.length + 1] = 0, i.length += 2; + for (var a = 0, h = 0;h < i.length; h++) { + var s = i.words[h] | 0; + a += s * 977, i.words[h] = a & 67108863, a = s * 64 + (a / 67108864 | 0); + } + return i.words[i.length - 1] === 0 && (i.length--, i.words[i.length - 1] === 0 && i.length--), i; + }; + function Re() { + ye.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); + } + o(Re, ye); + function Ee() { + ye.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); + } + o(Ee, ye); + function Ae() { + ye.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); + } + o(Ae, ye), Ae.prototype.imulK = function(i) { + for (var a = 0, h = 0;h < i.length; h++) { + var s = (i.words[h] | 0) * 19 + a, u = s & 67108863; + s >>>= 26, i.words[h] = u, a = s; + } + return a !== 0 && (i.words[i.length++] = a), i; + }, f._prime = function(i) { + if (we[i]) + return we[i]; + var a; + if (i === "k256") + a = new xe; + else if (i === "p224") + a = new Re; + else if (i === "p192") + a = new Ee; + else if (i === "p25519") + a = new Ae; + else + throw new Error("Unknown prime " + i); + return we[i] = a, a; + }; + function P(v) { + if (typeof v == "string") { + var i = f._prime(v); + this.m = i.p, this.prime = i; + } else + r(v.gtn(1), "modulus must be greater than 1"), this.m = v, this.prime = null; + } + P.prototype._verify1 = function(i) { + r(i.negative === 0, "red works only with positives"), r(i.red, "red works only with red numbers"); + }, P.prototype._verify2 = function(i, a) { + r((i.negative | a.negative) === 0, "red works only with positives"), r(i.red && i.red === a.red, "red works only with red numbers"); + }, P.prototype.imod = function(i) { + return this.prime ? this.prime.ireduce(i)._forceRed(this) : i.umod(this.m)._forceRed(this); + }, P.prototype.neg = function(i) { + return i.isZero() ? i.clone() : this.m.sub(i)._forceRed(this); + }, P.prototype.add = function(i, a) { + this._verify2(i, a); + var h = i.add(a); + return h.cmp(this.m) >= 0 && h.isub(this.m), h._forceRed(this); + }, P.prototype.iadd = function(i, a) { + this._verify2(i, a); + var h = i.iadd(a); + return h.cmp(this.m) >= 0 && h.isub(this.m), h; + }, P.prototype.sub = function(i, a) { + this._verify2(i, a); + var h = i.sub(a); + return h.cmpn(0) < 0 && h.iadd(this.m), h._forceRed(this); + }, P.prototype.isub = function(i, a) { + this._verify2(i, a); + var h = i.isub(a); + return h.cmpn(0) < 0 && h.iadd(this.m), h; + }, P.prototype.shl = function(i, a) { + return this._verify1(i), this.imod(i.ushln(a)); + }, P.prototype.imul = function(i, a) { + return this._verify2(i, a), this.imod(i.imul(a)); + }, P.prototype.mul = function(i, a) { + return this._verify2(i, a), this.imod(i.mul(a)); + }, P.prototype.isqr = function(i) { + return this.imul(i, i.clone()); + }, P.prototype.sqr = function(i) { + return this.mul(i, i); + }, P.prototype.sqrt = function(i) { + if (i.isZero()) + return i.clone(); + var a = this.m.andln(3); + if (r(a % 2 === 1), a === 3) { + var h = this.m.add(new f(1)).iushrn(2); + return this.pow(i, h); + } + for (var s = this.m.subn(1), u = 0;!s.isZero() && s.andln(1) === 0; ) + u++, s.iushrn(1); + r(!s.isZero()); + var c = new f(1).toRed(this), b = c.redNeg(), l = this.m.subn(1).iushrn(1), n = this.m.bitLength(); + for (n = new f(2 * n * n).toRed(this);this.pow(n, l).cmp(b) !== 0; ) + n.redIAdd(b); + for (var d = this.pow(n, s), w = this.pow(i, s.addn(1).iushrn(1)), g = this.pow(i, s), _9 = u;g.cmp(c) !== 0; ) { + for (var A = g, R = 0;A.cmp(c) !== 0; R++) + A = A.redSqr(); + r(R < _9); + var I2 = this.pow(d, new f(1).iushln(_9 - R - 1)); + w = w.redMul(I2), d = I2.redSqr(), g = g.redMul(d), _9 = R; + } + return w; + }, P.prototype.invm = function(i) { + var a = i._invmp(this.m); + return a.negative !== 0 ? (a.negative = 0, this.imod(a).redNeg()) : this.imod(a); + }, P.prototype.pow = function(i, a) { + if (a.isZero()) + return new f(1).toRed(this); + if (a.cmpn(1) === 0) + return i.clone(); + var h = 4, s = new Array(1 << h); + s[0] = new f(1).toRed(this), s[1] = i; + for (var u = 2;u < s.length; u++) + s[u] = this.mul(s[u - 1], i); + var c = s[0], b = 0, l = 0, n = a.bitLength() % 26; + for (n === 0 && (n = 26), u = a.length - 1;u >= 0; u--) { + for (var d = a.words[u], w = n - 1;w >= 0; w--) { + var g = d >> w & 1; + if (c !== s[0] && (c = this.sqr(c)), g === 0 && b === 0) { + l = 0; + continue; + } + b <<= 1, b |= g, l++, !(l !== h && (u !== 0 || w !== 0)) && (c = this.mul(c, s[b]), l = 0, b = 0); + } + n = 26; + } + return c; + }, P.prototype.convertTo = function(i) { + var a = i.umod(this.m); + return a === i ? a.clone() : a; + }, P.prototype.convertFrom = function(i) { + var a = i.clone(); + return a.red = null, a; + }, f.mont = function(i) { + return new Se2(i); + }; + function Se2(v) { + P.call(this, v), this.shift = this.m.bitLength(), this.shift % 26 !== 0 && (this.shift += 26 - this.shift % 26), this.r = new f(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv); + } + o(Se2, P), Se2.prototype.convertTo = function(i) { + return this.imod(i.ushln(this.shift)); + }, Se2.prototype.convertFrom = function(i) { + var a = this.imod(i.mul(this.rinv)); + return a.red = null, a; + }, Se2.prototype.imul = function(i, a) { + if (i.isZero() || a.isZero()) + return i.words[0] = 0, i.length = 1, i; + var h = i.imul(a), s = h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = h.isub(s).iushrn(this.shift), c = u; + return u.cmp(this.m) >= 0 ? c = u.isub(this.m) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }, Se2.prototype.mul = function(i, a) { + if (i.isZero() || a.isZero()) + return new f(0)._forceRed(this); + var h = i.mul(a), s = h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = h.isub(s).iushrn(this.shift), c = u; + return u.cmp(this.m) >= 0 ? c = u.isub(this.m) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }, Se2.prototype.invm = function(i) { + var a = this.imod(i._invmp(this.m).mul(this.r2)); + return a._forceRed(this); + }; + })(typeof Gu2 > "u" || Gu2, $m); + }); + Ym = T((Gm, Xu) => { + (function(t, e) { + function r(v, i) { + if (!v) + throw new Error(i || "Assertion failed"); + } + function o(v, i) { + v.super_ = i; + var a = function() { + }; + a.prototype = i.prototype, v.prototype = new a, v.prototype.constructor = v; + } + function f(v, i, a) { + if (f.isBN(v)) + return v; + this.negative = 0, this.words = null, this.length = 0, this.red = null, v !== null && ((i === "le" || i === "be") && (a = i, i = 10), this._init(v || 0, i || 10, a || "be")); + } + typeof t == "object" ? t.exports = f : e.BN = f, f.BN = f, f.wordSize = 26; + var p; + try { + typeof window < "u" && typeof window.Buffer < "u" ? p = window.Buffer : p = ji().Buffer; + } catch { + } + f.isBN = function(i) { + return i instanceof f ? true : i !== null && typeof i == "object" && i.constructor.wordSize === f.wordSize && Array.isArray(i.words); + }, f.max = function(i, a) { + return i.cmp(a) > 0 ? i : a; + }, f.min = function(i, a) { + return i.cmp(a) < 0 ? i : a; + }, f.prototype._init = function(i, a, h) { + if (typeof i == "number") + return this._initNumber(i, a, h); + if (typeof i == "object") + return this._initArray(i, a, h); + a === "hex" && (a = 16), r(a === (a | 0) && a >= 2 && a <= 36), i = i.toString().replace(/\s+/g, ""); + var s = 0; + i[0] === "-" && (s++, this.negative = 1), s < i.length && (a === 16 ? this._parseHex(i, s, h) : (this._parseBase(i, a, s), h === "le" && this._initArray(this.toArray(), a, h))); + }, f.prototype._initNumber = function(i, a, h) { + i < 0 && (this.negative = 1, i = -i), i < 67108864 ? (this.words = [i & 67108863], this.length = 1) : i < 4503599627370496 ? (this.words = [i & 67108863, i / 67108864 & 67108863], this.length = 2) : (r(i < 9007199254740992), this.words = [i & 67108863, i / 67108864 & 67108863, 1], this.length = 3), h === "le" && this._initArray(this.toArray(), a, h); + }, f.prototype._initArray = function(i, a, h) { + if (r(typeof i.length == "number"), i.length <= 0) + return this.words = [0], this.length = 1, this; + this.length = Math.ceil(i.length / 3), this.words = new Array(this.length); + for (var s = 0;s < this.length; s++) + this.words[s] = 0; + var u, c, b = 0; + if (h === "be") + for (s = i.length - 1, u = 0;s >= 0; s -= 3) + c = i[s] | i[s - 1] << 8 | i[s - 2] << 16, this.words[u] |= c << b & 67108863, this.words[u + 1] = c >>> 26 - b & 67108863, b += 24, b >= 26 && (b -= 26, u++); + else if (h === "le") + for (s = 0, u = 0;s < i.length; s += 3) + c = i[s] | i[s + 1] << 8 | i[s + 2] << 16, this.words[u] |= c << b & 67108863, this.words[u + 1] = c >>> 26 - b & 67108863, b += 24, b >= 26 && (b -= 26, u++); + return this.strip(); + }; + function m(v, i) { + var a = v.charCodeAt(i); + return a >= 65 && a <= 70 ? a - 55 : a >= 97 && a <= 102 ? a - 87 : a - 48 & 15; + } + function y(v, i, a) { + var h = m(v, a); + return a - 1 >= i && (h |= m(v, a - 1) << 4), h; + } + f.prototype._parseHex = function(i, a, h) { + this.length = Math.ceil((i.length - a) / 6), this.words = new Array(this.length); + for (var s = 0;s < this.length; s++) + this.words[s] = 0; + var u = 0, c = 0, b; + if (h === "be") + for (s = i.length - 1;s >= a; s -= 2) + b = y(i, a, s) << u, this.words[c] |= b & 67108863, u >= 18 ? (u -= 18, c += 1, this.words[c] |= b >>> 26) : u += 8; + else { + var l = i.length - a; + for (s = l % 2 === 0 ? a + 1 : a;s < i.length; s += 2) + b = y(i, a, s) << u, this.words[c] |= b & 67108863, u >= 18 ? (u -= 18, c += 1, this.words[c] |= b >>> 26) : u += 8; + } + this.strip(); + }; + function M(v, i, a, h) { + for (var s = 0, u = Math.min(v.length, a), c = i;c < u; c++) { + var b = v.charCodeAt(c) - 48; + s *= h, b >= 49 ? s += b - 49 + 10 : b >= 17 ? s += b - 17 + 10 : s += b; + } + return s; + } + f.prototype._parseBase = function(i, a, h) { + this.words = [0], this.length = 1; + for (var s = 0, u = 1;u <= 67108863; u *= a) + s++; + s--, u = u / a | 0; + for (var c = i.length - h, b = c % s, l = Math.min(c, c - b) + h, n = 0, d = h;d < l; d += s) + n = M(i, d, d + s, a), this.imuln(u), this.words[0] + n < 67108864 ? this.words[0] += n : this._iaddn(n); + if (b !== 0) { + var w = 1; + for (n = M(i, d, i.length, a), d = 0;d < b; d++) + w *= a; + this.imuln(w), this.words[0] + n < 67108864 ? this.words[0] += n : this._iaddn(n); + } + this.strip(); + }, f.prototype.copy = function(i) { + i.words = new Array(this.length); + for (var a = 0;a < this.length; a++) + i.words[a] = this.words[a]; + i.length = this.length, i.negative = this.negative, i.red = this.red; + }, f.prototype.clone = function() { + var i = new f(null); + return this.copy(i), i; + }, f.prototype._expand = function(i) { + for (;this.length < i; ) + this.words[this.length++] = 0; + return this; + }, f.prototype.strip = function() { + for (;this.length > 1 && this.words[this.length - 1] === 0; ) + this.length--; + return this._normSign(); + }, f.prototype._normSign = function() { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }, f.prototype.inspect = function() { + return (this.red ? ""; + }; + var x = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], S = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], E2 = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; + f.prototype.toString = function(i, a) { + i = i || 10, a = a | 0 || 1; + var h; + if (i === 16 || i === "hex") { + h = ""; + for (var s = 0, u = 0, c = 0;c < this.length; c++) { + var b = this.words[c], l = ((b << s | u) & 16777215).toString(16); + u = b >>> 24 - s & 16777215, u !== 0 || c !== this.length - 1 ? h = x[6 - l.length] + l + h : h = l + h, s += 2, s >= 26 && (s -= 26, c--); + } + for (u !== 0 && (h = u.toString(16) + h);h.length % a !== 0; ) + h = "0" + h; + return this.negative !== 0 && (h = "-" + h), h; + } + if (i === (i | 0) && i >= 2 && i <= 36) { + var n = S[i], d = E2[i]; + h = ""; + var w = this.clone(); + for (w.negative = 0;!w.isZero(); ) { + var g = w.modn(d).toString(i); + w = w.idivn(d), w.isZero() ? h = g + h : h = x[n - g.length] + g + h; + } + for (this.isZero() && (h = "0" + h);h.length % a !== 0; ) + h = "0" + h; + return this.negative !== 0 && (h = "-" + h), h; + } + r(false, "Base should be between 2 and 36"); + }, f.prototype.toNumber = function() { + var i = this.words[0]; + return this.length === 2 ? i += this.words[1] * 67108864 : this.length === 3 && this.words[2] === 1 ? i += 4503599627370496 + this.words[1] * 67108864 : this.length > 2 && r(false, "Number can only safely store up to 53 bits"), this.negative !== 0 ? -i : i; + }, f.prototype.toJSON = function() { + return this.toString(16); + }, f.prototype.toBuffer = function(i, a) { + return r(typeof p < "u"), this.toArrayLike(p, i, a); + }, f.prototype.toArray = function(i, a) { + return this.toArrayLike(Array, i, a); + }, f.prototype.toArrayLike = function(i, a, h) { + var s = this.byteLength(), u = h || Math.max(1, s); + r(s <= u, "byte array longer than desired length"), r(u > 0, "Requested array length <= 0"), this.strip(); + var c = a === "le", b = new i(u), l, n, d = this.clone(); + if (c) { + for (n = 0;!d.isZero(); n++) + l = d.andln(255), d.iushrn(8), b[n] = l; + for (;n < u; n++) + b[n] = 0; + } else { + for (n = 0;n < u - s; n++) + b[n] = 0; + for (n = 0;!d.isZero(); n++) + l = d.andln(255), d.iushrn(8), b[u - n - 1] = l; + } + return b; + }, Math.clz32 ? f.prototype._countBits = function(i) { + return 32 - Math.clz32(i); + } : f.prototype._countBits = function(i) { + var a = i, h = 0; + return a >= 4096 && (h += 13, a >>>= 13), a >= 64 && (h += 7, a >>>= 7), a >= 8 && (h += 4, a >>>= 4), a >= 2 && (h += 2, a >>>= 2), h + a; + }, f.prototype._zeroBits = function(i) { + if (i === 0) + return 26; + var a = i, h = 0; + return (a & 8191) === 0 && (h += 13, a >>>= 13), (a & 127) === 0 && (h += 7, a >>>= 7), (a & 15) === 0 && (h += 4, a >>>= 4), (a & 3) === 0 && (h += 2, a >>>= 2), (a & 1) === 0 && h++, h; + }, f.prototype.bitLength = function() { + var i = this.words[this.length - 1], a = this._countBits(i); + return (this.length - 1) * 26 + a; + }; + function B(v) { + for (var i = new Array(v.bitLength()), a = 0;a < i.length; a++) { + var h = a / 26 | 0, s = a % 26; + i[a] = (v.words[h] & 1 << s) >>> s; + } + return i; + } + f.prototype.zeroBits = function() { + if (this.isZero()) + return 0; + for (var i = 0, a = 0;a < this.length; a++) { + var h = this._zeroBits(this.words[a]); + if (i += h, h !== 26) + break; + } + return i; + }, f.prototype.byteLength = function() { + return Math.ceil(this.bitLength() / 8); + }, f.prototype.toTwos = function(i) { + return this.negative !== 0 ? this.abs().inotn(i).iaddn(1) : this.clone(); + }, f.prototype.fromTwos = function(i) { + return this.testn(i - 1) ? this.notn(i).iaddn(1).ineg() : this.clone(); + }, f.prototype.isNeg = function() { + return this.negative !== 0; + }, f.prototype.neg = function() { + return this.clone().ineg(); + }, f.prototype.ineg = function() { + return this.isZero() || (this.negative ^= 1), this; + }, f.prototype.iuor = function(i) { + for (;this.length < i.length; ) + this.words[this.length++] = 0; + for (var a = 0;a < i.length; a++) + this.words[a] = this.words[a] | i.words[a]; + return this.strip(); + }, f.prototype.ior = function(i) { + return r((this.negative | i.negative) === 0), this.iuor(i); + }, f.prototype.or = function(i) { + return this.length > i.length ? this.clone().ior(i) : i.clone().ior(this); + }, f.prototype.uor = function(i) { + return this.length > i.length ? this.clone().iuor(i) : i.clone().iuor(this); + }, f.prototype.iuand = function(i) { + var a; + this.length > i.length ? a = i : a = this; + for (var h = 0;h < a.length; h++) + this.words[h] = this.words[h] & i.words[h]; + return this.length = a.length, this.strip(); + }, f.prototype.iand = function(i) { + return r((this.negative | i.negative) === 0), this.iuand(i); + }, f.prototype.and = function(i) { + return this.length > i.length ? this.clone().iand(i) : i.clone().iand(this); + }, f.prototype.uand = function(i) { + return this.length > i.length ? this.clone().iuand(i) : i.clone().iuand(this); + }, f.prototype.iuxor = function(i) { + var a, h; + this.length > i.length ? (a = this, h = i) : (a = i, h = this); + for (var s = 0;s < h.length; s++) + this.words[s] = a.words[s] ^ h.words[s]; + if (this !== a) + for (;s < a.length; s++) + this.words[s] = a.words[s]; + return this.length = a.length, this.strip(); + }, f.prototype.ixor = function(i) { + return r((this.negative | i.negative) === 0), this.iuxor(i); + }, f.prototype.xor = function(i) { + return this.length > i.length ? this.clone().ixor(i) : i.clone().ixor(this); + }, f.prototype.uxor = function(i) { + return this.length > i.length ? this.clone().iuxor(i) : i.clone().iuxor(this); + }, f.prototype.inotn = function(i) { + r(typeof i == "number" && i >= 0); + var a = Math.ceil(i / 26) | 0, h = i % 26; + this._expand(a), h > 0 && a--; + for (var s = 0;s < a; s++) + this.words[s] = ~this.words[s] & 67108863; + return h > 0 && (this.words[s] = ~this.words[s] & 67108863 >> 26 - h), this.strip(); + }, f.prototype.notn = function(i) { + return this.clone().inotn(i); + }, f.prototype.setn = function(i, a) { + r(typeof i == "number" && i >= 0); + var h = i / 26 | 0, s = i % 26; + return this._expand(h + 1), a ? this.words[h] = this.words[h] | 1 << s : this.words[h] = this.words[h] & ~(1 << s), this.strip(); + }, f.prototype.iadd = function(i) { + var a; + if (this.negative !== 0 && i.negative === 0) + return this.negative = 0, a = this.isub(i), this.negative ^= 1, this._normSign(); + if (this.negative === 0 && i.negative !== 0) + return i.negative = 0, a = this.isub(i), i.negative = 1, a._normSign(); + var h, s; + this.length > i.length ? (h = this, s = i) : (h = i, s = this); + for (var u = 0, c = 0;c < s.length; c++) + a = (h.words[c] | 0) + (s.words[c] | 0) + u, this.words[c] = a & 67108863, u = a >>> 26; + for (;u !== 0 && c < h.length; c++) + a = (h.words[c] | 0) + u, this.words[c] = a & 67108863, u = a >>> 26; + if (this.length = h.length, u !== 0) + this.words[this.length] = u, this.length++; + else if (h !== this) + for (;c < h.length; c++) + this.words[c] = h.words[c]; + return this; + }, f.prototype.add = function(i) { + var a; + return i.negative !== 0 && this.negative === 0 ? (i.negative = 0, a = this.sub(i), i.negative ^= 1, a) : i.negative === 0 && this.negative !== 0 ? (this.negative = 0, a = i.sub(this), this.negative = 1, a) : this.length > i.length ? this.clone().iadd(i) : i.clone().iadd(this); + }, f.prototype.isub = function(i) { + if (i.negative !== 0) { + i.negative = 0; + var a = this.iadd(i); + return i.negative = 1, a._normSign(); + } else if (this.negative !== 0) + return this.negative = 0, this.iadd(i), this.negative = 1, this._normSign(); + var h = this.cmp(i); + if (h === 0) + return this.negative = 0, this.length = 1, this.words[0] = 0, this; + var s, u; + h > 0 ? (s = this, u = i) : (s = i, u = this); + for (var c = 0, b = 0;b < u.length; b++) + a = (s.words[b] | 0) - (u.words[b] | 0) + c, c = a >> 26, this.words[b] = a & 67108863; + for (;c !== 0 && b < s.length; b++) + a = (s.words[b] | 0) + c, c = a >> 26, this.words[b] = a & 67108863; + if (c === 0 && b < s.length && s !== this) + for (;b < s.length; b++) + this.words[b] = s.words[b]; + return this.length = Math.max(this.length, b), s !== this && (this.negative = 1), this.strip(); + }, f.prototype.sub = function(i) { + return this.clone().isub(i); + }; + function q(v, i, a) { + a.negative = i.negative ^ v.negative; + var h = v.length + i.length | 0; + a.length = h, h = h - 1 | 0; + var s = v.words[0] | 0, u = i.words[0] | 0, c = s * u, b = c & 67108863, l = c / 67108864 | 0; + a.words[0] = b; + for (var n = 1;n < h; n++) { + for (var d = l >>> 26, w = l & 67108863, g = Math.min(n, i.length - 1), _9 = Math.max(0, n - v.length + 1);_9 <= g; _9++) { + var A = n - _9 | 0; + s = v.words[A] | 0, u = i.words[_9] | 0, c = s * u + w, d += c / 67108864 | 0, w = c & 67108863; + } + a.words[n] = w | 0, l = d | 0; + } + return l !== 0 ? a.words[n] = l | 0 : a.length--, a.strip(); + } + var L = function(i, a, h) { + var s = i.words, u = a.words, c = h.words, b = 0, l, n, d, w = s[0] | 0, g = w & 8191, _9 = w >>> 13, A = s[1] | 0, R = A & 8191, I2 = A >>> 13, Me = s[2] | 0, k2 = Me & 8191, D = Me >>> 13, nt = s[3] | 0, C2 = nt & 8191, O = nt >>> 13, vt = s[4] | 0, F = vt & 8191, U = vt >>> 13, bt = s[5] | 0, z = bt & 8191, H = bt >>> 13, mt = s[6] | 0, W = mt & 8191, K = mt >>> 13, gt = s[7] | 0, j = gt & 8191, Z = gt >>> 13, yt = s[8] | 0, V2 = yt & 8191, $ = yt >>> 13, wt = s[9] | 0, G = wt & 8191, Y = wt >>> 13, Mt = u[0] | 0, X = Mt & 8191, J2 = Mt >>> 13, _t = u[1] | 0, Q = _t & 8191, ee = _t >>> 13, xt2 = u[2] | 0, te2 = xt2 & 8191, re = xt2 >>> 13, St = u[3] | 0, ie = St & 8191, ne = St >>> 13, Et2 = u[4] | 0, fe = Et2 & 8191, ae2 = Et2 >>> 13, At2 = u[5] | 0, oe = At2 & 8191, se2 = At2 >>> 13, Rt = u[6] | 0, he = Rt & 8191, ue2 = Rt >>> 13, Bt = u[7] | 0, le = Bt & 8191, de = Bt >>> 13, qt = u[8] | 0, ce2 = qt & 8191, pe2 = qt >>> 13, It = u[9] | 0, ve = It & 8191, be = It >>> 13; + h.negative = i.negative ^ a.negative, h.length = 19, l = Math.imul(g, X), n = Math.imul(g, J2), n = n + Math.imul(_9, X) | 0, d = Math.imul(_9, J2); + var ft = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (ft >>> 26) | 0, ft &= 67108863, l = Math.imul(R, X), n = Math.imul(R, J2), n = n + Math.imul(I2, X) | 0, d = Math.imul(I2, J2), l = l + Math.imul(g, Q) | 0, n = n + Math.imul(g, ee) | 0, n = n + Math.imul(_9, Q) | 0, d = d + Math.imul(_9, ee) | 0; + var Be = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Be >>> 26) | 0, Be &= 67108863, l = Math.imul(k2, X), n = Math.imul(k2, J2), n = n + Math.imul(D, X) | 0, d = Math.imul(D, J2), l = l + Math.imul(R, Q) | 0, n = n + Math.imul(R, ee) | 0, n = n + Math.imul(I2, Q) | 0, d = d + Math.imul(I2, ee) | 0, l = l + Math.imul(g, te2) | 0, n = n + Math.imul(g, re) | 0, n = n + Math.imul(_9, te2) | 0, d = d + Math.imul(_9, re) | 0; + var qe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (qe >>> 26) | 0, qe &= 67108863, l = Math.imul(C2, X), n = Math.imul(C2, J2), n = n + Math.imul(O, X) | 0, d = Math.imul(O, J2), l = l + Math.imul(k2, Q) | 0, n = n + Math.imul(k2, ee) | 0, n = n + Math.imul(D, Q) | 0, d = d + Math.imul(D, ee) | 0, l = l + Math.imul(R, te2) | 0, n = n + Math.imul(R, re) | 0, n = n + Math.imul(I2, te2) | 0, d = d + Math.imul(I2, re) | 0, l = l + Math.imul(g, ie) | 0, n = n + Math.imul(g, ne) | 0, n = n + Math.imul(_9, ie) | 0, d = d + Math.imul(_9, ne) | 0; + var ze = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (ze >>> 26) | 0, ze &= 67108863, l = Math.imul(F, X), n = Math.imul(F, J2), n = n + Math.imul(U, X) | 0, d = Math.imul(U, J2), l = l + Math.imul(C2, Q) | 0, n = n + Math.imul(C2, ee) | 0, n = n + Math.imul(O, Q) | 0, d = d + Math.imul(O, ee) | 0, l = l + Math.imul(k2, te2) | 0, n = n + Math.imul(k2, re) | 0, n = n + Math.imul(D, te2) | 0, d = d + Math.imul(D, re) | 0, l = l + Math.imul(R, ie) | 0, n = n + Math.imul(R, ne) | 0, n = n + Math.imul(I2, ie) | 0, d = d + Math.imul(I2, ne) | 0, l = l + Math.imul(g, fe) | 0, n = n + Math.imul(g, ae2) | 0, n = n + Math.imul(_9, fe) | 0, d = d + Math.imul(_9, ae2) | 0; + var He2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (He2 >>> 26) | 0, He2 &= 67108863, l = Math.imul(z, X), n = Math.imul(z, J2), n = n + Math.imul(H, X) | 0, d = Math.imul(H, J2), l = l + Math.imul(F, Q) | 0, n = n + Math.imul(F, ee) | 0, n = n + Math.imul(U, Q) | 0, d = d + Math.imul(U, ee) | 0, l = l + Math.imul(C2, te2) | 0, n = n + Math.imul(C2, re) | 0, n = n + Math.imul(O, te2) | 0, d = d + Math.imul(O, re) | 0, l = l + Math.imul(k2, ie) | 0, n = n + Math.imul(k2, ne) | 0, n = n + Math.imul(D, ie) | 0, d = d + Math.imul(D, ne) | 0, l = l + Math.imul(R, fe) | 0, n = n + Math.imul(R, ae2) | 0, n = n + Math.imul(I2, fe) | 0, d = d + Math.imul(I2, ae2) | 0, l = l + Math.imul(g, oe) | 0, n = n + Math.imul(g, se2) | 0, n = n + Math.imul(_9, oe) | 0, d = d + Math.imul(_9, se2) | 0; + var We = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (We >>> 26) | 0, We &= 67108863, l = Math.imul(W, X), n = Math.imul(W, J2), n = n + Math.imul(K, X) | 0, d = Math.imul(K, J2), l = l + Math.imul(z, Q) | 0, n = n + Math.imul(z, ee) | 0, n = n + Math.imul(H, Q) | 0, d = d + Math.imul(H, ee) | 0, l = l + Math.imul(F, te2) | 0, n = n + Math.imul(F, re) | 0, n = n + Math.imul(U, te2) | 0, d = d + Math.imul(U, re) | 0, l = l + Math.imul(C2, ie) | 0, n = n + Math.imul(C2, ne) | 0, n = n + Math.imul(O, ie) | 0, d = d + Math.imul(O, ne) | 0, l = l + Math.imul(k2, fe) | 0, n = n + Math.imul(k2, ae2) | 0, n = n + Math.imul(D, fe) | 0, d = d + Math.imul(D, ae2) | 0, l = l + Math.imul(R, oe) | 0, n = n + Math.imul(R, se2) | 0, n = n + Math.imul(I2, oe) | 0, d = d + Math.imul(I2, se2) | 0, l = l + Math.imul(g, he) | 0, n = n + Math.imul(g, ue2) | 0, n = n + Math.imul(_9, he) | 0, d = d + Math.imul(_9, ue2) | 0; + var Ke2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ke2 >>> 26) | 0, Ke2 &= 67108863, l = Math.imul(j, X), n = Math.imul(j, J2), n = n + Math.imul(Z, X) | 0, d = Math.imul(Z, J2), l = l + Math.imul(W, Q) | 0, n = n + Math.imul(W, ee) | 0, n = n + Math.imul(K, Q) | 0, d = d + Math.imul(K, ee) | 0, l = l + Math.imul(z, te2) | 0, n = n + Math.imul(z, re) | 0, n = n + Math.imul(H, te2) | 0, d = d + Math.imul(H, re) | 0, l = l + Math.imul(F, ie) | 0, n = n + Math.imul(F, ne) | 0, n = n + Math.imul(U, ie) | 0, d = d + Math.imul(U, ne) | 0, l = l + Math.imul(C2, fe) | 0, n = n + Math.imul(C2, ae2) | 0, n = n + Math.imul(O, fe) | 0, d = d + Math.imul(O, ae2) | 0, l = l + Math.imul(k2, oe) | 0, n = n + Math.imul(k2, se2) | 0, n = n + Math.imul(D, oe) | 0, d = d + Math.imul(D, se2) | 0, l = l + Math.imul(R, he) | 0, n = n + Math.imul(R, ue2) | 0, n = n + Math.imul(I2, he) | 0, d = d + Math.imul(I2, ue2) | 0, l = l + Math.imul(g, le) | 0, n = n + Math.imul(g, de) | 0, n = n + Math.imul(_9, le) | 0, d = d + Math.imul(_9, de) | 0; + var je = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (je >>> 26) | 0, je &= 67108863, l = Math.imul(V2, X), n = Math.imul(V2, J2), n = n + Math.imul($, X) | 0, d = Math.imul($, J2), l = l + Math.imul(j, Q) | 0, n = n + Math.imul(j, ee) | 0, n = n + Math.imul(Z, Q) | 0, d = d + Math.imul(Z, ee) | 0, l = l + Math.imul(W, te2) | 0, n = n + Math.imul(W, re) | 0, n = n + Math.imul(K, te2) | 0, d = d + Math.imul(K, re) | 0, l = l + Math.imul(z, ie) | 0, n = n + Math.imul(z, ne) | 0, n = n + Math.imul(H, ie) | 0, d = d + Math.imul(H, ne) | 0, l = l + Math.imul(F, fe) | 0, n = n + Math.imul(F, ae2) | 0, n = n + Math.imul(U, fe) | 0, d = d + Math.imul(U, ae2) | 0, l = l + Math.imul(C2, oe) | 0, n = n + Math.imul(C2, se2) | 0, n = n + Math.imul(O, oe) | 0, d = d + Math.imul(O, se2) | 0, l = l + Math.imul(k2, he) | 0, n = n + Math.imul(k2, ue2) | 0, n = n + Math.imul(D, he) | 0, d = d + Math.imul(D, ue2) | 0, l = l + Math.imul(R, le) | 0, n = n + Math.imul(R, de) | 0, n = n + Math.imul(I2, le) | 0, d = d + Math.imul(I2, de) | 0, l = l + Math.imul(g, ce2) | 0, n = n + Math.imul(g, pe2) | 0, n = n + Math.imul(_9, ce2) | 0, d = d + Math.imul(_9, pe2) | 0; + var Ze2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ze2 >>> 26) | 0, Ze2 &= 67108863, l = Math.imul(G, X), n = Math.imul(G, J2), n = n + Math.imul(Y, X) | 0, d = Math.imul(Y, J2), l = l + Math.imul(V2, Q) | 0, n = n + Math.imul(V2, ee) | 0, n = n + Math.imul($, Q) | 0, d = d + Math.imul($, ee) | 0, l = l + Math.imul(j, te2) | 0, n = n + Math.imul(j, re) | 0, n = n + Math.imul(Z, te2) | 0, d = d + Math.imul(Z, re) | 0, l = l + Math.imul(W, ie) | 0, n = n + Math.imul(W, ne) | 0, n = n + Math.imul(K, ie) | 0, d = d + Math.imul(K, ne) | 0, l = l + Math.imul(z, fe) | 0, n = n + Math.imul(z, ae2) | 0, n = n + Math.imul(H, fe) | 0, d = d + Math.imul(H, ae2) | 0, l = l + Math.imul(F, oe) | 0, n = n + Math.imul(F, se2) | 0, n = n + Math.imul(U, oe) | 0, d = d + Math.imul(U, se2) | 0, l = l + Math.imul(C2, he) | 0, n = n + Math.imul(C2, ue2) | 0, n = n + Math.imul(O, he) | 0, d = d + Math.imul(O, ue2) | 0, l = l + Math.imul(k2, le) | 0, n = n + Math.imul(k2, de) | 0, n = n + Math.imul(D, le) | 0, d = d + Math.imul(D, de) | 0, l = l + Math.imul(R, ce2) | 0, n = n + Math.imul(R, pe2) | 0, n = n + Math.imul(I2, ce2) | 0, d = d + Math.imul(I2, pe2) | 0, l = l + Math.imul(g, ve) | 0, n = n + Math.imul(g, be) | 0, n = n + Math.imul(_9, ve) | 0, d = d + Math.imul(_9, be) | 0; + var Ve = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ve >>> 26) | 0, Ve &= 67108863, l = Math.imul(G, Q), n = Math.imul(G, ee), n = n + Math.imul(Y, Q) | 0, d = Math.imul(Y, ee), l = l + Math.imul(V2, te2) | 0, n = n + Math.imul(V2, re) | 0, n = n + Math.imul($, te2) | 0, d = d + Math.imul($, re) | 0, l = l + Math.imul(j, ie) | 0, n = n + Math.imul(j, ne) | 0, n = n + Math.imul(Z, ie) | 0, d = d + Math.imul(Z, ne) | 0, l = l + Math.imul(W, fe) | 0, n = n + Math.imul(W, ae2) | 0, n = n + Math.imul(K, fe) | 0, d = d + Math.imul(K, ae2) | 0, l = l + Math.imul(z, oe) | 0, n = n + Math.imul(z, se2) | 0, n = n + Math.imul(H, oe) | 0, d = d + Math.imul(H, se2) | 0, l = l + Math.imul(F, he) | 0, n = n + Math.imul(F, ue2) | 0, n = n + Math.imul(U, he) | 0, d = d + Math.imul(U, ue2) | 0, l = l + Math.imul(C2, le) | 0, n = n + Math.imul(C2, de) | 0, n = n + Math.imul(O, le) | 0, d = d + Math.imul(O, de) | 0, l = l + Math.imul(k2, ce2) | 0, n = n + Math.imul(k2, pe2) | 0, n = n + Math.imul(D, ce2) | 0, d = d + Math.imul(D, pe2) | 0, l = l + Math.imul(R, ve) | 0, n = n + Math.imul(R, be) | 0, n = n + Math.imul(I2, ve) | 0, d = d + Math.imul(I2, be) | 0; + var $e = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + ($e >>> 26) | 0, $e &= 67108863, l = Math.imul(G, te2), n = Math.imul(G, re), n = n + Math.imul(Y, te2) | 0, d = Math.imul(Y, re), l = l + Math.imul(V2, ie) | 0, n = n + Math.imul(V2, ne) | 0, n = n + Math.imul($, ie) | 0, d = d + Math.imul($, ne) | 0, l = l + Math.imul(j, fe) | 0, n = n + Math.imul(j, ae2) | 0, n = n + Math.imul(Z, fe) | 0, d = d + Math.imul(Z, ae2) | 0, l = l + Math.imul(W, oe) | 0, n = n + Math.imul(W, se2) | 0, n = n + Math.imul(K, oe) | 0, d = d + Math.imul(K, se2) | 0, l = l + Math.imul(z, he) | 0, n = n + Math.imul(z, ue2) | 0, n = n + Math.imul(H, he) | 0, d = d + Math.imul(H, ue2) | 0, l = l + Math.imul(F, le) | 0, n = n + Math.imul(F, de) | 0, n = n + Math.imul(U, le) | 0, d = d + Math.imul(U, de) | 0, l = l + Math.imul(C2, ce2) | 0, n = n + Math.imul(C2, pe2) | 0, n = n + Math.imul(O, ce2) | 0, d = d + Math.imul(O, pe2) | 0, l = l + Math.imul(k2, ve) | 0, n = n + Math.imul(k2, be) | 0, n = n + Math.imul(D, ve) | 0, d = d + Math.imul(D, be) | 0; + var Ge = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ge >>> 26) | 0, Ge &= 67108863, l = Math.imul(G, ie), n = Math.imul(G, ne), n = n + Math.imul(Y, ie) | 0, d = Math.imul(Y, ne), l = l + Math.imul(V2, fe) | 0, n = n + Math.imul(V2, ae2) | 0, n = n + Math.imul($, fe) | 0, d = d + Math.imul($, ae2) | 0, l = l + Math.imul(j, oe) | 0, n = n + Math.imul(j, se2) | 0, n = n + Math.imul(Z, oe) | 0, d = d + Math.imul(Z, se2) | 0, l = l + Math.imul(W, he) | 0, n = n + Math.imul(W, ue2) | 0, n = n + Math.imul(K, he) | 0, d = d + Math.imul(K, ue2) | 0, l = l + Math.imul(z, le) | 0, n = n + Math.imul(z, de) | 0, n = n + Math.imul(H, le) | 0, d = d + Math.imul(H, de) | 0, l = l + Math.imul(F, ce2) | 0, n = n + Math.imul(F, pe2) | 0, n = n + Math.imul(U, ce2) | 0, d = d + Math.imul(U, pe2) | 0, l = l + Math.imul(C2, ve) | 0, n = n + Math.imul(C2, be) | 0, n = n + Math.imul(O, ve) | 0, d = d + Math.imul(O, be) | 0; + var Ye = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ye >>> 26) | 0, Ye &= 67108863, l = Math.imul(G, fe), n = Math.imul(G, ae2), n = n + Math.imul(Y, fe) | 0, d = Math.imul(Y, ae2), l = l + Math.imul(V2, oe) | 0, n = n + Math.imul(V2, se2) | 0, n = n + Math.imul($, oe) | 0, d = d + Math.imul($, se2) | 0, l = l + Math.imul(j, he) | 0, n = n + Math.imul(j, ue2) | 0, n = n + Math.imul(Z, he) | 0, d = d + Math.imul(Z, ue2) | 0, l = l + Math.imul(W, le) | 0, n = n + Math.imul(W, de) | 0, n = n + Math.imul(K, le) | 0, d = d + Math.imul(K, de) | 0, l = l + Math.imul(z, ce2) | 0, n = n + Math.imul(z, pe2) | 0, n = n + Math.imul(H, ce2) | 0, d = d + Math.imul(H, pe2) | 0, l = l + Math.imul(F, ve) | 0, n = n + Math.imul(F, be) | 0, n = n + Math.imul(U, ve) | 0, d = d + Math.imul(U, be) | 0; + var Xe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Xe >>> 26) | 0, Xe &= 67108863, l = Math.imul(G, oe), n = Math.imul(G, se2), n = n + Math.imul(Y, oe) | 0, d = Math.imul(Y, se2), l = l + Math.imul(V2, he) | 0, n = n + Math.imul(V2, ue2) | 0, n = n + Math.imul($, he) | 0, d = d + Math.imul($, ue2) | 0, l = l + Math.imul(j, le) | 0, n = n + Math.imul(j, de) | 0, n = n + Math.imul(Z, le) | 0, d = d + Math.imul(Z, de) | 0, l = l + Math.imul(W, ce2) | 0, n = n + Math.imul(W, pe2) | 0, n = n + Math.imul(K, ce2) | 0, d = d + Math.imul(K, pe2) | 0, l = l + Math.imul(z, ve) | 0, n = n + Math.imul(z, be) | 0, n = n + Math.imul(H, ve) | 0, d = d + Math.imul(H, be) | 0; + var Je = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Je >>> 26) | 0, Je &= 67108863, l = Math.imul(G, he), n = Math.imul(G, ue2), n = n + Math.imul(Y, he) | 0, d = Math.imul(Y, ue2), l = l + Math.imul(V2, le) | 0, n = n + Math.imul(V2, de) | 0, n = n + Math.imul($, le) | 0, d = d + Math.imul($, de) | 0, l = l + Math.imul(j, ce2) | 0, n = n + Math.imul(j, pe2) | 0, n = n + Math.imul(Z, ce2) | 0, d = d + Math.imul(Z, pe2) | 0, l = l + Math.imul(W, ve) | 0, n = n + Math.imul(W, be) | 0, n = n + Math.imul(K, ve) | 0, d = d + Math.imul(K, be) | 0; + var Qe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Qe >>> 26) | 0, Qe &= 67108863, l = Math.imul(G, le), n = Math.imul(G, de), n = n + Math.imul(Y, le) | 0, d = Math.imul(Y, de), l = l + Math.imul(V2, ce2) | 0, n = n + Math.imul(V2, pe2) | 0, n = n + Math.imul($, ce2) | 0, d = d + Math.imul($, pe2) | 0, l = l + Math.imul(j, ve) | 0, n = n + Math.imul(j, be) | 0, n = n + Math.imul(Z, ve) | 0, d = d + Math.imul(Z, be) | 0; + var et2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (et2 >>> 26) | 0, et2 &= 67108863, l = Math.imul(G, ce2), n = Math.imul(G, pe2), n = n + Math.imul(Y, ce2) | 0, d = Math.imul(Y, pe2), l = l + Math.imul(V2, ve) | 0, n = n + Math.imul(V2, be) | 0, n = n + Math.imul($, ve) | 0, d = d + Math.imul($, be) | 0; + var tt2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (tt2 >>> 26) | 0, tt2 &= 67108863, l = Math.imul(G, ve), n = Math.imul(G, be), n = n + Math.imul(Y, ve) | 0, d = Math.imul(Y, be); + var rt2 = (b + l | 0) + ((n & 8191) << 13) | 0; + return b = (d + (n >>> 13) | 0) + (rt2 >>> 26) | 0, rt2 &= 67108863, c[0] = ft, c[1] = Be, c[2] = qe, c[3] = ze, c[4] = He2, c[5] = We, c[6] = Ke2, c[7] = je, c[8] = Ze2, c[9] = Ve, c[10] = $e, c[11] = Ge, c[12] = Ye, c[13] = Xe, c[14] = Je, c[15] = Qe, c[16] = et2, c[17] = tt2, c[18] = rt2, b !== 0 && (c[19] = b, h.length++), h; + }; + Math.imul || (L = q); + function ge(v, i, a) { + a.negative = i.negative ^ v.negative, a.length = v.length + i.length; + for (var h = 0, s = 0, u = 0;u < a.length - 1; u++) { + var c = s; + s = 0; + for (var b = h & 67108863, l = Math.min(u, i.length - 1), n = Math.max(0, u - v.length + 1);n <= l; n++) { + var d = u - n, w = v.words[d] | 0, g = i.words[n] | 0, _9 = w * g, A = _9 & 67108863; + c = c + (_9 / 67108864 | 0) | 0, A = A + b | 0, b = A & 67108863, c = c + (A >>> 26) | 0, s += c >>> 26, c &= 67108863; + } + a.words[u] = b, h = c, c = s; + } + return h !== 0 ? a.words[u] = h : a.length--, a.strip(); + } + function _e(v, i, a) { + var h = new N; + return h.mulp(v, i, a); + } + f.prototype.mulTo = function(i, a) { + var h, s = this.length + i.length; + return this.length === 10 && i.length === 10 ? h = L(this, i, a) : s < 63 ? h = q(this, i, a) : s < 1024 ? h = ge(this, i, a) : h = _e(this, i, a), h; + }; + function N(v, i) { + this.x = v, this.y = i; + } + N.prototype.makeRBT = function(i) { + for (var a = new Array(i), h = f.prototype._countBits(i) - 1, s = 0;s < i; s++) + a[s] = this.revBin(s, h, i); + return a; + }, N.prototype.revBin = function(i, a, h) { + if (i === 0 || i === h - 1) + return i; + for (var s = 0, u = 0;u < a; u++) + s |= (i & 1) << a - u - 1, i >>= 1; + return s; + }, N.prototype.permute = function(i, a, h, s, u, c) { + for (var b = 0;b < c; b++) + s[b] = a[i[b]], u[b] = h[i[b]]; + }, N.prototype.transform = function(i, a, h, s, u, c) { + this.permute(c, i, a, h, s, u); + for (var b = 1;b < u; b <<= 1) + for (var l = b << 1, n = Math.cos(2 * Math.PI / l), d = Math.sin(2 * Math.PI / l), w = 0;w < u; w += l) + for (var g = n, _9 = d, A = 0;A < b; A++) { + var R = h[w + A], I2 = s[w + A], Me = h[w + A + b], k2 = s[w + A + b], D = g * Me - _9 * k2; + k2 = g * k2 + _9 * Me, Me = D, h[w + A] = R + Me, s[w + A] = I2 + k2, h[w + A + b] = R - Me, s[w + A + b] = I2 - k2, A !== l && (D = n * g - d * _9, _9 = n * _9 + d * g, g = D); + } + }, N.prototype.guessLen13b = function(i, a) { + var h = Math.max(a, i) | 1, s = h & 1, u = 0; + for (h = h / 2 | 0;h; h = h >>> 1) + u++; + return 1 << u + 1 + s; + }, N.prototype.conjugate = function(i, a, h) { + if (!(h <= 1)) + for (var s = 0;s < h / 2; s++) { + var u = i[s]; + i[s] = i[h - s - 1], i[h - s - 1] = u, u = a[s], a[s] = -a[h - s - 1], a[h - s - 1] = -u; + } + }, N.prototype.normalize13b = function(i, a) { + for (var h = 0, s = 0;s < a / 2; s++) { + var u = Math.round(i[2 * s + 1] / a) * 8192 + Math.round(i[2 * s] / a) + h; + i[s] = u & 67108863, u < 67108864 ? h = 0 : h = u / 67108864 | 0; + } + return i; + }, N.prototype.convert13b = function(i, a, h, s) { + for (var u = 0, c = 0;c < a; c++) + u = u + (i[c] | 0), h[2 * c] = u & 8191, u = u >>> 13, h[2 * c + 1] = u & 8191, u = u >>> 13; + for (c = 2 * a;c < s; ++c) + h[c] = 0; + r(u === 0), r((u & -8192) === 0); + }, N.prototype.stub = function(i) { + for (var a = new Array(i), h = 0;h < i; h++) + a[h] = 0; + return a; + }, N.prototype.mulp = function(i, a, h) { + var s = 2 * this.guessLen13b(i.length, a.length), u = this.makeRBT(s), c = this.stub(s), b = new Array(s), l = new Array(s), n = new Array(s), d = new Array(s), w = new Array(s), g = new Array(s), _9 = h.words; + _9.length = s, this.convert13b(i.words, i.length, b, s), this.convert13b(a.words, a.length, d, s), this.transform(b, c, l, n, s, u), this.transform(d, c, w, g, s, u); + for (var A = 0;A < s; A++) { + var R = l[A] * w[A] - n[A] * g[A]; + n[A] = l[A] * g[A] + n[A] * w[A], l[A] = R; + } + return this.conjugate(l, n, s), this.transform(l, n, _9, c, s, u), this.conjugate(_9, c, s), this.normalize13b(_9, s), h.negative = i.negative ^ a.negative, h.length = i.length + a.length, h.strip(); + }, f.prototype.mul = function(i) { + var a = new f(null); + return a.words = new Array(this.length + i.length), this.mulTo(i, a); + }, f.prototype.mulf = function(i) { + var a = new f(null); + return a.words = new Array(this.length + i.length), _e(this, i, a); + }, f.prototype.imul = function(i) { + return this.clone().mulTo(i, this); + }, f.prototype.imuln = function(i) { + r(typeof i == "number"), r(i < 67108864); + for (var a = 0, h = 0;h < this.length; h++) { + var s = (this.words[h] | 0) * i, u = (s & 67108863) + (a & 67108863); + a >>= 26, a += s / 67108864 | 0, a += u >>> 26, this.words[h] = u & 67108863; + } + return a !== 0 && (this.words[h] = a, this.length++), this; + }, f.prototype.muln = function(i) { + return this.clone().imuln(i); + }, f.prototype.sqr = function() { + return this.mul(this); + }, f.prototype.isqr = function() { + return this.imul(this.clone()); + }, f.prototype.pow = function(i) { + var a = B(i); + if (a.length === 0) + return new f(1); + for (var h = this, s = 0;s < a.length && a[s] === 0; s++, h = h.sqr()) + ; + if (++s < a.length) + for (var u = h.sqr();s < a.length; s++, u = u.sqr()) + a[s] !== 0 && (h = h.mul(u)); + return h; + }, f.prototype.iushln = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26, s = 67108863 >>> 26 - a << 26 - a, u; + if (a !== 0) { + var c = 0; + for (u = 0;u < this.length; u++) { + var b = this.words[u] & s, l = (this.words[u] | 0) - b << a; + this.words[u] = l | c, c = b >>> 26 - a; + } + c && (this.words[u] = c, this.length++); + } + if (h !== 0) { + for (u = this.length - 1;u >= 0; u--) + this.words[u + h] = this.words[u]; + for (u = 0;u < h; u++) + this.words[u] = 0; + this.length += h; + } + return this.strip(); + }, f.prototype.ishln = function(i) { + return r(this.negative === 0), this.iushln(i); + }, f.prototype.iushrn = function(i, a, h) { + r(typeof i == "number" && i >= 0); + var s; + a ? s = (a - a % 26) / 26 : s = 0; + var u = i % 26, c = Math.min((i - u) / 26, this.length), b = 67108863 ^ 67108863 >>> u << u, l = h; + if (s -= c, s = Math.max(0, s), l) { + for (var n = 0;n < c; n++) + l.words[n] = this.words[n]; + l.length = c; + } + if (c !== 0) + if (this.length > c) + for (this.length -= c, n = 0;n < this.length; n++) + this.words[n] = this.words[n + c]; + else + this.words[0] = 0, this.length = 1; + var d = 0; + for (n = this.length - 1;n >= 0 && (d !== 0 || n >= s); n--) { + var w = this.words[n] | 0; + this.words[n] = d << 26 - u | w >>> u, d = w & b; + } + return l && d !== 0 && (l.words[l.length++] = d), this.length === 0 && (this.words[0] = 0, this.length = 1), this.strip(); + }, f.prototype.ishrn = function(i, a, h) { + return r(this.negative === 0), this.iushrn(i, a, h); + }, f.prototype.shln = function(i) { + return this.clone().ishln(i); + }, f.prototype.ushln = function(i) { + return this.clone().iushln(i); + }, f.prototype.shrn = function(i) { + return this.clone().ishrn(i); + }, f.prototype.ushrn = function(i) { + return this.clone().iushrn(i); + }, f.prototype.testn = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26, s = 1 << a; + if (this.length <= h) + return false; + var u = this.words[h]; + return !!(u & s); + }, f.prototype.imaskn = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26; + if (r(this.negative === 0, "imaskn works only with positive numbers"), this.length <= h) + return this; + if (a !== 0 && h++, this.length = Math.min(h, this.length), a !== 0) { + var s = 67108863 ^ 67108863 >>> a << a; + this.words[this.length - 1] &= s; + } + return this.strip(); + }, f.prototype.maskn = function(i) { + return this.clone().imaskn(i); + }, f.prototype.iaddn = function(i) { + return r(typeof i == "number"), r(i < 67108864), i < 0 ? this.isubn(-i) : this.negative !== 0 ? this.length === 1 && (this.words[0] | 0) < i ? (this.words[0] = i - (this.words[0] | 0), this.negative = 0, this) : (this.negative = 0, this.isubn(i), this.negative = 1, this) : this._iaddn(i); + }, f.prototype._iaddn = function(i) { + this.words[0] += i; + for (var a = 0;a < this.length && this.words[a] >= 67108864; a++) + this.words[a] -= 67108864, a === this.length - 1 ? this.words[a + 1] = 1 : this.words[a + 1]++; + return this.length = Math.max(this.length, a + 1), this; + }, f.prototype.isubn = function(i) { + if (r(typeof i == "number"), r(i < 67108864), i < 0) + return this.iaddn(-i); + if (this.negative !== 0) + return this.negative = 0, this.iaddn(i), this.negative = 1, this; + if (this.words[0] -= i, this.length === 1 && this.words[0] < 0) + this.words[0] = -this.words[0], this.negative = 1; + else + for (var a = 0;a < this.length && this.words[a] < 0; a++) + this.words[a] += 67108864, this.words[a + 1] -= 1; + return this.strip(); + }, f.prototype.addn = function(i) { + return this.clone().iaddn(i); + }, f.prototype.subn = function(i) { + return this.clone().isubn(i); + }, f.prototype.iabs = function() { + return this.negative = 0, this; + }, f.prototype.abs = function() { + return this.clone().iabs(); + }, f.prototype._ishlnsubmul = function(i, a, h) { + var s = i.length + h, u; + this._expand(s); + var c, b = 0; + for (u = 0;u < i.length; u++) { + c = (this.words[u + h] | 0) + b; + var l = (i.words[u] | 0) * a; + c -= l & 67108863, b = (c >> 26) - (l / 67108864 | 0), this.words[u + h] = c & 67108863; + } + for (;u < this.length - h; u++) + c = (this.words[u + h] | 0) + b, b = c >> 26, this.words[u + h] = c & 67108863; + if (b === 0) + return this.strip(); + for (r(b === -1), b = 0, u = 0;u < this.length; u++) + c = -(this.words[u] | 0) + b, b = c >> 26, this.words[u] = c & 67108863; + return this.negative = 1, this.strip(); + }, f.prototype._wordDiv = function(i, a) { + var h = this.length - i.length, s = this.clone(), u = i, c = u.words[u.length - 1] | 0, b = this._countBits(c); + h = 26 - b, h !== 0 && (u = u.ushln(h), s.iushln(h), c = u.words[u.length - 1] | 0); + var l = s.length - u.length, n; + if (a !== "mod") { + n = new f(null), n.length = l + 1, n.words = new Array(n.length); + for (var d = 0;d < n.length; d++) + n.words[d] = 0; + } + var w = s.clone()._ishlnsubmul(u, 1, l); + w.negative === 0 && (s = w, n && (n.words[l] = 1)); + for (var g = l - 1;g >= 0; g--) { + var _9 = (s.words[u.length + g] | 0) * 67108864 + (s.words[u.length + g - 1] | 0); + for (_9 = Math.min(_9 / c | 0, 67108863), s._ishlnsubmul(u, _9, g);s.negative !== 0; ) + _9--, s.negative = 0, s._ishlnsubmul(u, 1, g), s.isZero() || (s.negative ^= 1); + n && (n.words[g] = _9); + } + return n && n.strip(), s.strip(), a !== "div" && h !== 0 && s.iushrn(h), { div: n || null, mod: s }; + }, f.prototype.divmod = function(i, a, h) { + if (r(!i.isZero()), this.isZero()) + return { div: new f(0), mod: new f(0) }; + var s, u, c; + return this.negative !== 0 && i.negative === 0 ? (c = this.neg().divmod(i, a), a !== "mod" && (s = c.div.neg()), a !== "div" && (u = c.mod.neg(), h && u.negative !== 0 && u.iadd(i)), { div: s, mod: u }) : this.negative === 0 && i.negative !== 0 ? (c = this.divmod(i.neg(), a), a !== "mod" && (s = c.div.neg()), { div: s, mod: c.mod }) : (this.negative & i.negative) !== 0 ? (c = this.neg().divmod(i.neg(), a), a !== "div" && (u = c.mod.neg(), h && u.negative !== 0 && u.isub(i)), { div: c.div, mod: u }) : i.length > this.length || this.cmp(i) < 0 ? { div: new f(0), mod: this } : i.length === 1 ? a === "div" ? { div: this.divn(i.words[0]), mod: null } : a === "mod" ? { div: null, mod: new f(this.modn(i.words[0])) } : { div: this.divn(i.words[0]), mod: new f(this.modn(i.words[0])) } : this._wordDiv(i, a); + }, f.prototype.div = function(i) { + return this.divmod(i, "div", false).div; + }, f.prototype.mod = function(i) { + return this.divmod(i, "mod", false).mod; + }, f.prototype.umod = function(i) { + return this.divmod(i, "mod", true).mod; + }, f.prototype.divRound = function(i) { + var a = this.divmod(i); + if (a.mod.isZero()) + return a.div; + var h = a.div.negative !== 0 ? a.mod.isub(i) : a.mod, s = i.ushrn(1), u = i.andln(1), c = h.cmp(s); + return c < 0 || u === 1 && c === 0 ? a.div : a.div.negative !== 0 ? a.div.isubn(1) : a.div.iaddn(1); + }, f.prototype.modn = function(i) { + r(i <= 67108863); + for (var a = (1 << 26) % i, h = 0, s = this.length - 1;s >= 0; s--) + h = (a * h + (this.words[s] | 0)) % i; + return h; + }, f.prototype.idivn = function(i) { + r(i <= 67108863); + for (var a = 0, h = this.length - 1;h >= 0; h--) { + var s = (this.words[h] | 0) + a * 67108864; + this.words[h] = s / i | 0, a = s % i; + } + return this.strip(); + }, f.prototype.divn = function(i) { + return this.clone().idivn(i); + }, f.prototype.egcd = function(i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, h = i.clone(); + a.negative !== 0 ? a = a.umod(i) : a = a.clone(); + for (var s = new f(1), u = new f(0), c = new f(0), b = new f(1), l = 0;a.isEven() && h.isEven(); ) + a.iushrn(1), h.iushrn(1), ++l; + for (var n = h.clone(), d = a.clone();!a.isZero(); ) { + for (var w = 0, g = 1;(a.words[0] & g) === 0 && w < 26; ++w, g <<= 1) + ; + if (w > 0) + for (a.iushrn(w);w-- > 0; ) + (s.isOdd() || u.isOdd()) && (s.iadd(n), u.isub(d)), s.iushrn(1), u.iushrn(1); + for (var _9 = 0, A = 1;(h.words[0] & A) === 0 && _9 < 26; ++_9, A <<= 1) + ; + if (_9 > 0) + for (h.iushrn(_9);_9-- > 0; ) + (c.isOdd() || b.isOdd()) && (c.iadd(n), b.isub(d)), c.iushrn(1), b.iushrn(1); + a.cmp(h) >= 0 ? (a.isub(h), s.isub(c), u.isub(b)) : (h.isub(a), c.isub(s), b.isub(u)); + } + return { a: c, b, gcd: h.iushln(l) }; + }, f.prototype._invmp = function(i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, h = i.clone(); + a.negative !== 0 ? a = a.umod(i) : a = a.clone(); + for (var s = new f(1), u = new f(0), c = h.clone();a.cmpn(1) > 0 && h.cmpn(1) > 0; ) { + for (var b = 0, l = 1;(a.words[0] & l) === 0 && b < 26; ++b, l <<= 1) + ; + if (b > 0) + for (a.iushrn(b);b-- > 0; ) + s.isOdd() && s.iadd(c), s.iushrn(1); + for (var n = 0, d = 1;(h.words[0] & d) === 0 && n < 26; ++n, d <<= 1) + ; + if (n > 0) + for (h.iushrn(n);n-- > 0; ) + u.isOdd() && u.iadd(c), u.iushrn(1); + a.cmp(h) >= 0 ? (a.isub(h), s.isub(u)) : (h.isub(a), u.isub(s)); + } + var w; + return a.cmpn(1) === 0 ? w = s : w = u, w.cmpn(0) < 0 && w.iadd(i), w; + }, f.prototype.gcd = function(i) { + if (this.isZero()) + return i.abs(); + if (i.isZero()) + return this.abs(); + var a = this.clone(), h = i.clone(); + a.negative = 0, h.negative = 0; + for (var s = 0;a.isEven() && h.isEven(); s++) + a.iushrn(1), h.iushrn(1); + do { + for (;a.isEven(); ) + a.iushrn(1); + for (;h.isEven(); ) + h.iushrn(1); + var u = a.cmp(h); + if (u < 0) { + var c = a; + a = h, h = c; + } else if (u === 0 || h.cmpn(1) === 0) + break; + a.isub(h); + } while (true); + return h.iushln(s); + }, f.prototype.invm = function(i) { + return this.egcd(i).a.umod(i); + }, f.prototype.isEven = function() { + return (this.words[0] & 1) === 0; + }, f.prototype.isOdd = function() { + return (this.words[0] & 1) === 1; + }, f.prototype.andln = function(i) { + return this.words[0] & i; + }, f.prototype.bincn = function(i) { + r(typeof i == "number"); + var a = i % 26, h = (i - a) / 26, s = 1 << a; + if (this.length <= h) + return this._expand(h + 1), this.words[h] |= s, this; + for (var u = s, c = h;u !== 0 && c < this.length; c++) { + var b = this.words[c] | 0; + b += u, u = b >>> 26, b &= 67108863, this.words[c] = b; + } + return u !== 0 && (this.words[c] = u, this.length++), this; + }, f.prototype.isZero = function() { + return this.length === 1 && this.words[0] === 0; + }, f.prototype.cmpn = function(i) { + var a = i < 0; + if (this.negative !== 0 && !a) + return -1; + if (this.negative === 0 && a) + return 1; + this.strip(); + var h; + if (this.length > 1) + h = 1; + else { + a && (i = -i), r(i <= 67108863, "Number is too big"); + var s = this.words[0] | 0; + h = s === i ? 0 : s < i ? -1 : 1; + } + return this.negative !== 0 ? -h | 0 : h; + }, f.prototype.cmp = function(i) { + if (this.negative !== 0 && i.negative === 0) + return -1; + if (this.negative === 0 && i.negative !== 0) + return 1; + var a = this.ucmp(i); + return this.negative !== 0 ? -a | 0 : a; + }, f.prototype.ucmp = function(i) { + if (this.length > i.length) + return 1; + if (this.length < i.length) + return -1; + for (var a = 0, h = this.length - 1;h >= 0; h--) { + var s = this.words[h] | 0, u = i.words[h] | 0; + if (s !== u) { + s < u ? a = -1 : s > u && (a = 1); + break; + } + } + return a; + }, f.prototype.gtn = function(i) { + return this.cmpn(i) === 1; + }, f.prototype.gt = function(i) { + return this.cmp(i) === 1; + }, f.prototype.gten = function(i) { + return this.cmpn(i) >= 0; + }, f.prototype.gte = function(i) { + return this.cmp(i) >= 0; + }, f.prototype.ltn = function(i) { + return this.cmpn(i) === -1; + }, f.prototype.lt = function(i) { + return this.cmp(i) === -1; + }, f.prototype.lten = function(i) { + return this.cmpn(i) <= 0; + }, f.prototype.lte = function(i) { + return this.cmp(i) <= 0; + }, f.prototype.eqn = function(i) { + return this.cmpn(i) === 0; + }, f.prototype.eq = function(i) { + return this.cmp(i) === 0; + }, f.red = function(i) { + return new P(i); + }, f.prototype.toRed = function(i) { + return r(!this.red, "Already a number in reduction context"), r(this.negative === 0, "red works only with positives"), i.convertTo(this)._forceRed(i); + }, f.prototype.fromRed = function() { + return r(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); + }, f.prototype._forceRed = function(i) { + return this.red = i, this; + }, f.prototype.forceRed = function(i) { + return r(!this.red, "Already a number in reduction context"), this._forceRed(i); + }, f.prototype.redAdd = function(i) { + return r(this.red, "redAdd works only with red numbers"), this.red.add(this, i); + }, f.prototype.redIAdd = function(i) { + return r(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, i); + }, f.prototype.redSub = function(i) { + return r(this.red, "redSub works only with red numbers"), this.red.sub(this, i); + }, f.prototype.redISub = function(i) { + return r(this.red, "redISub works only with red numbers"), this.red.isub(this, i); + }, f.prototype.redShl = function(i) { + return r(this.red, "redShl works only with red numbers"), this.red.shl(this, i); + }, f.prototype.redMul = function(i) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, i), this.red.mul(this, i); + }, f.prototype.redIMul = function(i) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, i), this.red.imul(this, i); + }, f.prototype.redSqr = function() { + return r(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); + }, f.prototype.redISqr = function() { + return r(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); + }, f.prototype.redSqrt = function() { + return r(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); + }, f.prototype.redInvm = function() { + return r(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); + }, f.prototype.redNeg = function() { + return r(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); + }, f.prototype.redPow = function(i) { + return r(this.red && !i.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, i); + }; + var we = { k256: null, p224: null, p192: null, p25519: null }; + function ye(v, i) { + this.name = v, this.p = new f(i, 16), this.n = this.p.bitLength(), this.k = new f(1).iushln(this.n).isub(this.p), this.tmp = this._tmp(); + } + ye.prototype._tmp = function() { + var i = new f(null); + return i.words = new Array(Math.ceil(this.n / 13)), i; + }, ye.prototype.ireduce = function(i) { + var a = i, h; + do + this.split(a, this.tmp), a = this.imulK(a), a = a.iadd(this.tmp), h = a.bitLength(); + while (h > this.n); + var s = h < this.n ? -1 : a.ucmp(this.p); + return s === 0 ? (a.words[0] = 0, a.length = 1) : s > 0 ? a.isub(this.p) : a.strip !== undefined ? a.strip() : a._strip(), a; + }, ye.prototype.split = function(i, a) { + i.iushrn(this.n, 0, a); + }, ye.prototype.imulK = function(i) { + return i.imul(this.k); + }; + function xe() { + ye.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); + } + o(xe, ye), xe.prototype.split = function(i, a) { + for (var h = 4194303, s = Math.min(i.length, 9), u = 0;u < s; u++) + a.words[u] = i.words[u]; + if (a.length = s, i.length <= 9) { + i.words[0] = 0, i.length = 1; + return; + } + var c = i.words[9]; + for (a.words[a.length++] = c & h, u = 10;u < i.length; u++) { + var b = i.words[u] | 0; + i.words[u - 10] = (b & h) << 4 | c >>> 22, c = b; + } + c >>>= 22, i.words[u - 10] = c, c === 0 && i.length > 10 ? i.length -= 10 : i.length -= 9; + }, xe.prototype.imulK = function(i) { + i.words[i.length] = 0, i.words[i.length + 1] = 0, i.length += 2; + for (var a = 0, h = 0;h < i.length; h++) { + var s = i.words[h] | 0; + a += s * 977, i.words[h] = a & 67108863, a = s * 64 + (a / 67108864 | 0); + } + return i.words[i.length - 1] === 0 && (i.length--, i.words[i.length - 1] === 0 && i.length--), i; + }; + function Re() { + ye.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); + } + o(Re, ye); + function Ee() { + ye.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); + } + o(Ee, ye); + function Ae() { + ye.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); + } + o(Ae, ye), Ae.prototype.imulK = function(i) { + for (var a = 0, h = 0;h < i.length; h++) { + var s = (i.words[h] | 0) * 19 + a, u = s & 67108863; + s >>>= 26, i.words[h] = u, a = s; + } + return a !== 0 && (i.words[i.length++] = a), i; + }, f._prime = function(i) { + if (we[i]) + return we[i]; + var a; + if (i === "k256") + a = new xe; + else if (i === "p224") + a = new Re; + else if (i === "p192") + a = new Ee; + else if (i === "p25519") + a = new Ae; + else + throw new Error("Unknown prime " + i); + return we[i] = a, a; + }; + function P(v) { + if (typeof v == "string") { + var i = f._prime(v); + this.m = i.p, this.prime = i; + } else + r(v.gtn(1), "modulus must be greater than 1"), this.m = v, this.prime = null; + } + P.prototype._verify1 = function(i) { + r(i.negative === 0, "red works only with positives"), r(i.red, "red works only with red numbers"); + }, P.prototype._verify2 = function(i, a) { + r((i.negative | a.negative) === 0, "red works only with positives"), r(i.red && i.red === a.red, "red works only with red numbers"); + }, P.prototype.imod = function(i) { + return this.prime ? this.prime.ireduce(i)._forceRed(this) : i.umod(this.m)._forceRed(this); + }, P.prototype.neg = function(i) { + return i.isZero() ? i.clone() : this.m.sub(i)._forceRed(this); + }, P.prototype.add = function(i, a) { + this._verify2(i, a); + var h = i.add(a); + return h.cmp(this.m) >= 0 && h.isub(this.m), h._forceRed(this); + }, P.prototype.iadd = function(i, a) { + this._verify2(i, a); + var h = i.iadd(a); + return h.cmp(this.m) >= 0 && h.isub(this.m), h; + }, P.prototype.sub = function(i, a) { + this._verify2(i, a); + var h = i.sub(a); + return h.cmpn(0) < 0 && h.iadd(this.m), h._forceRed(this); + }, P.prototype.isub = function(i, a) { + this._verify2(i, a); + var h = i.isub(a); + return h.cmpn(0) < 0 && h.iadd(this.m), h; + }, P.prototype.shl = function(i, a) { + return this._verify1(i), this.imod(i.ushln(a)); + }, P.prototype.imul = function(i, a) { + return this._verify2(i, a), this.imod(i.imul(a)); + }, P.prototype.mul = function(i, a) { + return this._verify2(i, a), this.imod(i.mul(a)); + }, P.prototype.isqr = function(i) { + return this.imul(i, i.clone()); + }, P.prototype.sqr = function(i) { + return this.mul(i, i); + }, P.prototype.sqrt = function(i) { + if (i.isZero()) + return i.clone(); + var a = this.m.andln(3); + if (r(a % 2 === 1), a === 3) { + var h = this.m.add(new f(1)).iushrn(2); + return this.pow(i, h); + } + for (var s = this.m.subn(1), u = 0;!s.isZero() && s.andln(1) === 0; ) + u++, s.iushrn(1); + r(!s.isZero()); + var c = new f(1).toRed(this), b = c.redNeg(), l = this.m.subn(1).iushrn(1), n = this.m.bitLength(); + for (n = new f(2 * n * n).toRed(this);this.pow(n, l).cmp(b) !== 0; ) + n.redIAdd(b); + for (var d = this.pow(n, s), w = this.pow(i, s.addn(1).iushrn(1)), g = this.pow(i, s), _9 = u;g.cmp(c) !== 0; ) { + for (var A = g, R = 0;A.cmp(c) !== 0; R++) + A = A.redSqr(); + r(R < _9); + var I2 = this.pow(d, new f(1).iushln(_9 - R - 1)); + w = w.redMul(I2), d = I2.redSqr(), g = g.redMul(d), _9 = R; + } + return w; + }, P.prototype.invm = function(i) { + var a = i._invmp(this.m); + return a.negative !== 0 ? (a.negative = 0, this.imod(a).redNeg()) : this.imod(a); + }, P.prototype.pow = function(i, a) { + if (a.isZero()) + return new f(1).toRed(this); + if (a.cmpn(1) === 0) + return i.clone(); + var h = 4, s = new Array(1 << h); + s[0] = new f(1).toRed(this), s[1] = i; + for (var u = 2;u < s.length; u++) + s[u] = this.mul(s[u - 1], i); + var c = s[0], b = 0, l = 0, n = a.bitLength() % 26; + for (n === 0 && (n = 26), u = a.length - 1;u >= 0; u--) { + for (var d = a.words[u], w = n - 1;w >= 0; w--) { + var g = d >> w & 1; + if (c !== s[0] && (c = this.sqr(c)), g === 0 && b === 0) { + l = 0; + continue; + } + b <<= 1, b |= g, l++, !(l !== h && (u !== 0 || w !== 0)) && (c = this.mul(c, s[b]), l = 0, b = 0); + } + n = 26; + } + return c; + }, P.prototype.convertTo = function(i) { + var a = i.umod(this.m); + return a === i ? a.clone() : a; + }, P.prototype.convertFrom = function(i) { + var a = i.clone(); + return a.red = null, a; + }, f.mont = function(i) { + return new Se2(i); + }; + function Se2(v) { + P.call(this, v), this.shift = this.m.bitLength(), this.shift % 26 !== 0 && (this.shift += 26 - this.shift % 26), this.r = new f(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv); + } + o(Se2, P), Se2.prototype.convertTo = function(i) { + return this.imod(i.ushln(this.shift)); + }, Se2.prototype.convertFrom = function(i) { + var a = this.imod(i.mul(this.rinv)); + return a.red = null, a; + }, Se2.prototype.imul = function(i, a) { + if (i.isZero() || a.isZero()) + return i.words[0] = 0, i.length = 1, i; + var h = i.imul(a), s = h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = h.isub(s).iushrn(this.shift), c = u; + return u.cmp(this.m) >= 0 ? c = u.isub(this.m) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }, Se2.prototype.mul = function(i, a) { + if (i.isZero() || a.isZero()) + return new f(0)._forceRed(this); + var h = i.mul(a), s = h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = h.isub(s).iushrn(this.shift), c = u; + return u.cmp(this.m) >= 0 ? c = u.isub(this.m) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }, Se2.prototype.invm = function(i) { + var a = this.imod(i._invmp(this.m).mul(this.r2)); + return a._forceRed(this); + }; + })(typeof Xu > "u" || Xu, Gm); + }); + Xm = T(() => { + }); + As = T(($T, el) => { + var Ju; + el.exports = function(e) { + return Ju || (Ju = new Zi(null)), Ju.generate(e); + }; + function Zi(t) { + this.rand = t; + } + el.exports.Rand = Zi; + Zi.prototype.generate = function(e) { + return this._rand(e); + }; + Zi.prototype._rand = function(e) { + if (this.rand.getBytes) + return this.rand.getBytes(e); + for (var r = new Uint8Array(e), o = 0;o < r.length; o++) + r[o] = this.rand.getByte(); + return r; + }; + if (typeof self == "object") + self.crypto && self.crypto.getRandomValues ? Zi.prototype._rand = function(e) { + var r = new Uint8Array(e); + return self.crypto.getRandomValues(r), r; + } : self.msCrypto && self.msCrypto.getRandomValues ? Zi.prototype._rand = function(e) { + var r = new Uint8Array(e); + return self.msCrypto.getRandomValues(r), r; + } : typeof window == "object" && (Zi.prototype._rand = function() { + throw new Error("Not implemented yet"); + }); + else + try { + if (Qu = Xm(), typeof Qu.randomBytes != "function") + throw new Error("Not supported"); + Zi.prototype._rand = function(e) { + return Qu.randomBytes(e); + }; + } catch { + } + var Qu; + }); + tl = T((GT, Jm) => { + var In = Ym(), Q9 = As(); + function Tn(t) { + this.rand = t || new Q9.Rand; + } + Jm.exports = Tn; + Tn.create = function(e) { + return new Tn(e); + }; + Tn.prototype._randbelow = function(e) { + var r = e.bitLength(), o = Math.ceil(r / 8); + do + var f = new In(this.rand.generate(o)); + while (f.cmp(e) >= 0); + return f; + }; + Tn.prototype._randrange = function(e, r) { + var o = r.sub(e); + return e.add(this._randbelow(o)); + }; + Tn.prototype.test = function(e, r, o) { + var f = e.bitLength(), p = In.mont(e), m = new In(1).toRed(p); + r || (r = Math.max(1, f / 48 | 0)); + for (var y = e.subn(1), M = 0;!y.testn(M); M++) + ; + for (var x = e.shrn(M), S = y.toRed(p), E2 = true;r > 0; r--) { + var B = this._randrange(new In(2), y); + o && o(B); + var q = B.toRed(p).redPow(x); + if (!(q.cmp(m) === 0 || q.cmp(S) === 0)) { + for (var L = 1;L < M; L++) { + if (q = q.redSqr(), q.cmp(m) === 0) + return false; + if (q.cmp(S) === 0) + break; + } + if (L === M) + return false; + } + } + return E2; + }; + Tn.prototype.getDivisor = function(e, r) { + var o = e.bitLength(), f = In.mont(e), p = new In(1).toRed(f); + r || (r = Math.max(1, o / 48 | 0)); + for (var m = e.subn(1), y = 0;!m.testn(y); y++) + ; + for (var M = e.shrn(y), x = m.toRed(f);r > 0; r--) { + var S = this._randrange(new In(2), m), E2 = e.gcd(S); + if (E2.cmpn(1) !== 0) + return E2; + var B = S.toRed(f).redPow(M); + if (!(B.cmp(p) === 0 || B.cmp(x) === 0)) { + for (var q = 1;q < y; q++) { + if (B = B.redSqr(), B.cmp(p) === 0) + return B.fromRed().subn(1).gcd(e); + if (B.cmp(x) === 0) + break; + } + if (q === y) + return B = B.redSqr(), B.fromRed().subn(1).gcd(e); + } + } + return false; + }; + }); + ol = T((ek, tg) => { + var eS = on(); + tg.exports = al2; + al2.simpleSieve = nl; + al2.fermatTest = fl2; + var Ht = Yu(), tS = new Ht(24), rS = tl(), Qm = new rS, iS = new Ht(1), il = new Ht(2), nS = new Ht(5), YT = new Ht(16), XT = new Ht(8), fS = new Ht(10), aS = new Ht(3), JT = new Ht(7), oS = new Ht(11), eg = new Ht(4), QT = new Ht(12), rl = null; + function sS() { + if (rl !== null) + return rl; + var t = 1048576, e = []; + e[0] = 2; + for (var r = 1, o = 3;o < t; o += 2) { + for (var f = Math.ceil(Math.sqrt(o)), p = 0;p < r && e[p] <= f && o % e[p] !== 0; p++) + ; + r !== p && e[p] <= f || (e[r++] = o); + } + return rl = e, e; + } + function nl(t) { + for (var e = sS(), r = 0;r < e.length; r++) + if (t.modn(e[r]) === 0) + return t.cmpn(e[r]) === 0; + return true; + } + function fl2(t) { + var e = Ht.mont(t); + return il.toRed(e).redPow(t.subn(1)).fromRed().cmpn(1) === 0; + } + function al2(t, e) { + if (t < 16) + return e === 2 || e === 5 ? new Ht([140, 123]) : new Ht([140, 39]); + e = new Ht(e); + for (var r, o;; ) { + for (r = new Ht(eS(Math.ceil(t / 8)));r.bitLength() > t; ) + r.ishrn(1); + if (r.isEven() && r.iadd(iS), r.testn(1) || r.iadd(il), e.cmp(il)) { + if (!e.cmp(nS)) + for (;r.mod(fS).cmp(aS); ) + r.iadd(eg); + } else + for (;r.mod(tS).cmp(oS); ) + r.iadd(eg); + if (o = r.shrn(1), nl(o) && nl(r) && fl2(o) && fl2(r) && Qm.test(o) && Qm.test(r)) + return r; + } + } + }); + rg = T((tk, hS) => { + hS.exports = { modp1: { gen: "02", prime: "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff" }, modp2: { gen: "02", prime: "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff" }, modp5: { gen: "02", prime: "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff" }, modp14: { gen: "02", prime: "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff" }, modp15: { gen: "02", prime: "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff" }, modp16: { gen: "02", prime: "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff" }, modp17: { gen: "02", prime: "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff" }, modp18: { gen: "02", prime: "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" } }; + }); + ag = T((rk, fg) => { + var yr = Yu(), uS = tl(), ig = new uS, lS = new yr(24), dS = new yr(11), cS = new yr(10), pS = new yr(3), vS = new yr(7), ng = ol(), bS = on(); + fg.exports = Si; + function mS(t, e) { + return e = e || "utf8", Buffer.isBuffer(t) || (t = new Buffer(t, e)), this._pub = new yr(t), this; + } + function gS(t, e) { + return e = e || "utf8", Buffer.isBuffer(t) || (t = new Buffer(t, e)), this._priv = new yr(t), this; + } + var Rs = {}; + function yS(t, e) { + var r = e.toString("hex"), o = [r, t.toString(16)].join("_"); + if (o in Rs) + return Rs[o]; + var f = 0; + if (t.isEven() || !ng.simpleSieve || !ng.fermatTest(t) || !ig.test(t)) + return f += 1, r === "02" || r === "05" ? f += 8 : f += 4, Rs[o] = f, f; + ig.test(t.shrn(1)) || (f += 2); + var p; + switch (r) { + case "02": + t.mod(lS).cmp(dS) && (f += 8); + break; + case "05": + p = t.mod(cS), p.cmp(pS) && p.cmp(vS) && (f += 8); + break; + default: + f += 4; + } + return Rs[o] = f, f; + } + function Si(t, e, r) { + this.setGenerator(e), this.__prime = new yr(t), this._prime = yr.mont(this.__prime), this._primeLen = t.length, this._pub = undefined, this._priv = undefined, this._primeCode = undefined, r ? (this.setPublicKey = mS, this.setPrivateKey = gS) : this._primeCode = 8; + } + Object.defineProperty(Si.prototype, "verifyError", { enumerable: true, get: function() { + return typeof this._primeCode != "number" && (this._primeCode = yS(this.__prime, this.__gen)), this._primeCode; + } }); + Si.prototype.generateKeys = function() { + return this._priv || (this._priv = new yr(bS(this._primeLen))), this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(), this.getPublicKey(); + }; + Si.prototype.computeSecret = function(t) { + t = new yr(t), t = t.toRed(this._prime); + var e = t.redPow(this._priv).fromRed(), r = new Buffer(e.toArray()), o = this.getPrime(); + if (r.length < o.length) { + var f = new Buffer(o.length - r.length); + f.fill(0), r = Buffer.concat([f, r]); + } + return r; + }; + Si.prototype.getPublicKey = function(e) { + return Bs(this._pub, e); + }; + Si.prototype.getPrivateKey = function(e) { + return Bs(this._priv, e); + }; + Si.prototype.getPrime = function(t) { + return Bs(this.__prime, t); + }; + Si.prototype.getGenerator = function(t) { + return Bs(this._gen, t); + }; + Si.prototype.setGenerator = function(t, e) { + return e = e || "utf8", Buffer.isBuffer(t) || (t = new Buffer(t, e)), this.__gen = t, this._gen = new yr(t), this; + }; + function Bs(t, e) { + var r = new Buffer(t.toArray()); + return e ? r.toString(e) : r; + } + }); + hg = T((_f) => { + var wS = ol(), og = rg(), sl = ag(); + function MS(t) { + var e = new Buffer(og[t].prime, "hex"), r = new Buffer(og[t].gen, "hex"); + return new sl(e, r); + } + var _S = { binary: true, hex: true, base64: true }; + function sg(t, e, r, o) { + return Buffer.isBuffer(e) || _S[e] === undefined ? sg(t, "binary", e, r) : (e = e || "binary", o = o || "binary", r = r || new Buffer([2]), Buffer.isBuffer(r) || (r = new Buffer(r, o)), typeof t == "number" ? new sl(wS(t, r), r, true) : (Buffer.isBuffer(t) || (t = new Buffer(t, e)), new sl(t, r, true))); + } + _f.DiffieHellmanGroup = _f.createDiffieHellmanGroup = _f.getDiffieHellman = MS; + _f.createDiffieHellman = _f.DiffieHellman = sg; + }); + hl2 = T((nk, ug) => { + ug.exports = ki().EventEmitter; + }); + pg = T((fk, cg) => { + function lg(t, e) { + var r = Object.keys(t); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(t); + e && (o = o.filter(function(f) { + return Object.getOwnPropertyDescriptor(t, f).enumerable; + })), r.push.apply(r, o); + } + return r; + } + function xS(t) { + for (var e = 1;e < arguments.length; e++) { + var r = arguments[e] != null ? arguments[e] : {}; + e % 2 ? lg(Object(r), true).forEach(function(o) { + SS(t, o, r[o]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(t, Object.getOwnPropertyDescriptors(r)) : lg(Object(r)).forEach(function(o) { + Object.defineProperty(t, o, Object.getOwnPropertyDescriptor(r, o)); + }); + } + return t; + } + function SS(t, e, r) { + return e in t ? Object.defineProperty(t, e, { value: r, enumerable: true, configurable: true, writable: true }) : t[e] = r, t; + } + function ES(t, e) { + if (!(t instanceof e)) + throw new TypeError("Cannot call a class as a function"); + } + function dg(t, e) { + for (var r = 0;r < e.length; r++) { + var o = e[r]; + o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(t, o.key, o); + } + } + function AS(t, e, r) { + return e && dg(t.prototype, e), r && dg(t, r), t; + } + var RS = Ut2(), qs = RS.Buffer, BS = $f(), ul = BS.inspect, qS = ul && ul.custom || "inspect"; + function IS(t, e, r) { + qs.prototype.copy.call(t, e, r); + } + cg.exports = function() { + function t() { + ES(this, t), this.head = null, this.tail = null, this.length = 0; + } + return AS(t, [{ key: "push", value: function(r) { + var o = { data: r, next: null }; + this.length > 0 ? this.tail.next = o : this.head = o, this.tail = o, ++this.length; + } }, { key: "unshift", value: function(r) { + var o = { data: r, next: this.head }; + this.length === 0 && (this.tail = o), this.head = o, ++this.length; + } }, { key: "shift", value: function() { + if (this.length !== 0) { + var r = this.head.data; + return this.length === 1 ? this.head = this.tail = null : this.head = this.head.next, --this.length, r; + } + } }, { key: "clear", value: function() { + this.head = this.tail = null, this.length = 0; + } }, { key: "join", value: function(r) { + if (this.length === 0) + return ""; + for (var o = this.head, f = "" + o.data;o = o.next; ) + f += r + o.data; + return f; + } }, { key: "concat", value: function(r) { + if (this.length === 0) + return qs.alloc(0); + for (var o = qs.allocUnsafe(r >>> 0), f = this.head, p = 0;f; ) + IS(f.data, o, p), p += f.data.length, f = f.next; + return o; + } }, { key: "consume", value: function(r, o) { + var f; + return r < this.head.data.length ? (f = this.head.data.slice(0, r), this.head.data = this.head.data.slice(r)) : r === this.head.data.length ? f = this.shift() : f = o ? this._getString(r) : this._getBuffer(r), f; + } }, { key: "first", value: function() { + return this.head.data; + } }, { key: "_getString", value: function(r) { + var o = this.head, f = 1, p = o.data; + for (r -= p.length;o = o.next; ) { + var m = o.data, y = r > m.length ? m.length : r; + if (y === m.length ? p += m : p += m.slice(0, r), r -= y, r === 0) { + y === m.length ? (++f, o.next ? this.head = o.next : this.head = this.tail = null) : (this.head = o, o.data = m.slice(y)); + break; + } + ++f; + } + return this.length -= f, p; + } }, { key: "_getBuffer", value: function(r) { + var o = qs.allocUnsafe(r), f = this.head, p = 1; + for (f.data.copy(o), r -= f.data.length;f = f.next; ) { + var m = f.data, y = r > m.length ? m.length : r; + if (m.copy(o, o.length - r, 0, y), r -= y, r === 0) { + y === m.length ? (++p, f.next ? this.head = f.next : this.head = this.tail = null) : (this.head = f, f.data = m.slice(y)); + break; + } + ++p; + } + return this.length -= p, o; + } }, { key: qS, value: function(r, o) { + return ul(this, xS({}, o, { depth: 0, customInspect: false })); + } }]), t; + }(); + }); + dl2 = T((ak, bg) => { + function TS(t, e) { + var r = this, o = this._readableState && this._readableState.destroyed, f = this._writableState && this._writableState.destroyed; + return o || f ? (e ? e(t) : t && (this._writableState ? this._writableState.errorEmitted || (this._writableState.errorEmitted = true, process.nextTick(ll, this, t)) : process.nextTick(ll, this, t)), this) : (this._readableState && (this._readableState.destroyed = true), this._writableState && (this._writableState.destroyed = true), this._destroy(t || null, function(p) { + !e && p ? r._writableState ? r._writableState.errorEmitted ? process.nextTick(Is, r) : (r._writableState.errorEmitted = true, process.nextTick(vg, r, p)) : process.nextTick(vg, r, p) : e ? (process.nextTick(Is, r), e(p)) : process.nextTick(Is, r); + }), this); + } + function vg(t, e) { + ll(t, e), Is(t); + } + function Is(t) { + t._writableState && !t._writableState.emitClose || t._readableState && !t._readableState.emitClose || t.emit("close"); + } + function kS() { + this._readableState && (this._readableState.destroyed = false, this._readableState.reading = false, this._readableState.ended = false, this._readableState.endEmitted = false), this._writableState && (this._writableState.destroyed = false, this._writableState.ended = false, this._writableState.ending = false, this._writableState.finalCalled = false, this._writableState.prefinished = false, this._writableState.finished = false, this._writableState.errorEmitted = false); + } + function ll(t, e) { + t.emit("error", e); + } + function LS(t, e) { + var { _readableState: r, _writableState: o } = t; + r && r.autoDestroy || o && o.autoDestroy ? t.destroy(e) : t.emit("error", e); + } + bg.exports = { destroy: TS, undestroy: kS, errorOrDestroy: LS }; + }); + kn = T((ok, yg) => { + function NS(t, e) { + t.prototype = Object.create(e.prototype), t.prototype.constructor = t, t.__proto__ = e; + } + var gg = {}; + function wr(t, e, r) { + r || (r = Error); + function o(p, m, y) { + return typeof e == "string" ? e : e(p, m, y); + } + var f = function(p) { + NS(m, p); + function m(y, M, x) { + return p.call(this, o(y, M, x)) || this; + } + return m; + }(r); + f.prototype.name = r.name, f.prototype.code = t, gg[t] = f; + } + function mg(t, e) { + if (Array.isArray(t)) { + var r = t.length; + return t = t.map(function(o) { + return String(o); + }), r > 2 ? "one of ".concat(e, " ").concat(t.slice(0, r - 1).join(", "), ", or ") + t[r - 1] : r === 2 ? "one of ".concat(e, " ").concat(t[0], " or ").concat(t[1]) : "of ".concat(e, " ").concat(t[0]); + } else + return "of ".concat(e, " ").concat(String(t)); + } + function DS(t, e, r) { + return t.substr(!r || r < 0 ? 0 : +r, e.length) === e; + } + function PS(t, e, r) { + return (r === undefined || r > t.length) && (r = t.length), t.substring(r - e.length, r) === e; + } + function CS(t, e, r) { + return typeof r != "number" && (r = 0), r + e.length > t.length ? false : t.indexOf(e, r) !== -1; + } + wr("ERR_INVALID_OPT_VALUE", function(t, e) { + return 'The value "' + e + '" is invalid for option "' + t + '"'; + }, TypeError); + wr("ERR_INVALID_ARG_TYPE", function(t, e, r) { + var o; + typeof e == "string" && DS(e, "not ") ? (o = "must not be", e = e.replace(/^not /, "")) : o = "must be"; + var f; + if (PS(t, " argument")) + f = "The ".concat(t, " ").concat(o, " ").concat(mg(e, "type")); + else { + var p = CS(t, ".") ? "property" : "argument"; + f = 'The "'.concat(t, '" ').concat(p, " ").concat(o, " ").concat(mg(e, "type")); + } + return f += ". Received type ".concat(typeof r), f; + }, TypeError); + wr("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"); + wr("ERR_METHOD_NOT_IMPLEMENTED", function(t) { + return "The " + t + " method is not implemented"; + }); + wr("ERR_STREAM_PREMATURE_CLOSE", "Premature close"); + wr("ERR_STREAM_DESTROYED", function(t) { + return "Cannot call " + t + " after a stream was destroyed"; + }); + wr("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"); + wr("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"); + wr("ERR_STREAM_WRITE_AFTER_END", "write after end"); + wr("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + wr("ERR_UNKNOWN_ENCODING", function(t) { + return "Unknown encoding: " + t; + }, TypeError); + wr("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"); + yg.exports.codes = gg; + }); + cl2 = T((sk, wg) => { + var OS = kn().codes.ERR_INVALID_OPT_VALUE; + function FS(t, e, r) { + return t.highWaterMark != null ? t.highWaterMark : e ? t[r] : null; + } + function US(t, e, r, o) { + var f = FS(e, o, r); + if (f != null) { + if (!(isFinite(f) && Math.floor(f) === f) || f < 0) { + var p = o ? r : "highWaterMark"; + throw new OS(p, f); + } + return Math.floor(f); + } + return t.objectMode ? 16 : 16 * 1024; + } + wg.exports = { getHighWaterMark: US }; + }); + bl = T((hk, Ag) => { + Ag.exports = ut2; + function _g(t) { + var e = this; + this.next = null, this.entry = null, this.finish = function() { + cE(e, t); + }; + } + var xf; + ut2.WritableState = ka; + var zS = { deprecate: G0() }, xg = hl2(), ks = Ut2().Buffer, HS = global.Uint8Array || function() { + }; + function WS(t) { + return ks.from(t); + } + function KS(t) { + return ks.isBuffer(t) || t instanceof HS; + } + var vl = dl2(), jS = cl2(), ZS = jS.getHighWaterMark, Vi = kn().codes, VS = Vi.ERR_INVALID_ARG_TYPE, $S = Vi.ERR_METHOD_NOT_IMPLEMENTED, GS = Vi.ERR_MULTIPLE_CALLBACK, YS = Vi.ERR_STREAM_CANNOT_PIPE, XS = Vi.ERR_STREAM_DESTROYED, JS = Vi.ERR_STREAM_NULL_VALUES, QS = Vi.ERR_STREAM_WRITE_AFTER_END, eE = Vi.ERR_UNKNOWN_ENCODING, Sf = vl.errorOrDestroy; + Ie()(ut2, xg); + function tE() { + } + function ka(t, e, r) { + xf = xf || Ln(), t = t || {}, typeof r != "boolean" && (r = e instanceof xf), this.objectMode = !!t.objectMode, r && (this.objectMode = this.objectMode || !!t.writableObjectMode), this.highWaterMark = ZS(this, t, "writableHighWaterMark", r), this.finalCalled = false, this.needDrain = false, this.ending = false, this.ended = false, this.finished = false, this.destroyed = false; + var o = t.decodeStrings === false; + this.decodeStrings = !o, this.defaultEncoding = t.defaultEncoding || "utf8", this.length = 0, this.writing = false, this.corked = 0, this.sync = true, this.bufferProcessing = false, this.onwrite = function(f) { + sE(e, f); + }, this.writecb = null, this.writelen = 0, this.bufferedRequest = null, this.lastBufferedRequest = null, this.pendingcb = 0, this.prefinished = false, this.errorEmitted = false, this.emitClose = t.emitClose !== false, this.autoDestroy = !!t.autoDestroy, this.bufferedRequestCount = 0, this.corkedRequestsFree = new _g(this); + } + ka.prototype.getBuffer = function() { + for (var e = this.bufferedRequest, r = [];e; ) + r.push(e), e = e.next; + return r; + }; + (function() { + try { + Object.defineProperty(ka.prototype, "buffer", { get: zS.deprecate(function() { + return this.getBuffer(); + }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") }); + } catch { + } + })(); + var Ts; + typeof Symbol == "function" && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] == "function" ? (Ts = Function.prototype[Symbol.hasInstance], Object.defineProperty(ut2, Symbol.hasInstance, { value: function(e) { + return Ts.call(this, e) ? true : this !== ut2 ? false : e && e._writableState instanceof ka; + } })) : Ts = function(e) { + return e instanceof this; + }; + function ut2(t) { + xf = xf || Ln(); + var e = this instanceof xf; + if (!e && !Ts.call(ut2, this)) + return new ut2(t); + this._writableState = new ka(t, this, e), this.writable = true, t && (typeof t.write == "function" && (this._write = t.write), typeof t.writev == "function" && (this._writev = t.writev), typeof t.destroy == "function" && (this._destroy = t.destroy), typeof t.final == "function" && (this._final = t.final)), xg.call(this); + } + ut2.prototype.pipe = function() { + Sf(this, new YS); + }; + function rE(t, e) { + var r = new QS; + Sf(t, r), process.nextTick(e, r); + } + function iE(t, e, r, o) { + var f; + return r === null ? f = new JS : typeof r != "string" && !e.objectMode && (f = new VS("chunk", ["string", "Buffer"], r)), f ? (Sf(t, f), process.nextTick(o, f), false) : true; + } + ut2.prototype.write = function(t, e, r) { + var o = this._writableState, f = false, p = !o.objectMode && KS(t); + return p && !ks.isBuffer(t) && (t = WS(t)), typeof e == "function" && (r = e, e = null), p ? e = "buffer" : e || (e = o.defaultEncoding), typeof r != "function" && (r = tE), o.ending ? rE(this, r) : (p || iE(this, o, t, r)) && (o.pendingcb++, f = fE(this, o, p, t, e, r)), f; + }; + ut2.prototype.cork = function() { + this._writableState.corked++; + }; + ut2.prototype.uncork = function() { + var t = this._writableState; + t.corked && (t.corked--, !t.writing && !t.corked && !t.bufferProcessing && t.bufferedRequest && Sg(this, t)); + }; + ut2.prototype.setDefaultEncoding = function(e) { + if (typeof e == "string" && (e = e.toLowerCase()), !(["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((e + "").toLowerCase()) > -1)) + throw new eE(e); + return this._writableState.defaultEncoding = e, this; + }; + Object.defineProperty(ut2.prototype, "writableBuffer", { enumerable: false, get: function() { + return this._writableState && this._writableState.getBuffer(); + } }); + function nE(t, e, r) { + return !t.objectMode && t.decodeStrings !== false && typeof e == "string" && (e = ks.from(e, r)), e; + } + Object.defineProperty(ut2.prototype, "writableHighWaterMark", { enumerable: false, get: function() { + return this._writableState.highWaterMark; + } }); + function fE(t, e, r, o, f, p) { + if (!r) { + var m = nE(e, o, f); + o !== m && (r = true, f = "buffer", o = m); + } + var y = e.objectMode ? 1 : o.length; + e.length += y; + var M = e.length < e.highWaterMark; + if (M || (e.needDrain = true), e.writing || e.corked) { + var x = e.lastBufferedRequest; + e.lastBufferedRequest = { chunk: o, encoding: f, isBuf: r, callback: p, next: null }, x ? x.next = e.lastBufferedRequest : e.bufferedRequest = e.lastBufferedRequest, e.bufferedRequestCount += 1; + } else + pl2(t, e, false, y, o, f, p); + return M; + } + function pl2(t, e, r, o, f, p, m) { + e.writelen = o, e.writecb = m, e.writing = true, e.sync = true, e.destroyed ? e.onwrite(new XS("write")) : r ? t._writev(f, e.onwrite) : t._write(f, p, e.onwrite), e.sync = false; + } + function aE(t, e, r, o, f) { + --e.pendingcb, r ? (process.nextTick(f, o), process.nextTick(Ta, t, e), t._writableState.errorEmitted = true, Sf(t, o)) : (f(o), t._writableState.errorEmitted = true, Sf(t, o), Ta(t, e)); + } + function oE(t) { + t.writing = false, t.writecb = null, t.length -= t.writelen, t.writelen = 0; + } + function sE(t, e) { + var r = t._writableState, o = r.sync, f = r.writecb; + if (typeof f != "function") + throw new GS; + if (oE(r), e) + aE(t, r, o, e, f); + else { + var p = Eg(r) || t.destroyed; + !p && !r.corked && !r.bufferProcessing && r.bufferedRequest && Sg(t, r), o ? process.nextTick(Mg, t, r, p, f) : Mg(t, r, p, f); + } + } + function Mg(t, e, r, o) { + r || hE(t, e), e.pendingcb--, o(), Ta(t, e); + } + function hE(t, e) { + e.length === 0 && e.needDrain && (e.needDrain = false, t.emit("drain")); + } + function Sg(t, e) { + e.bufferProcessing = true; + var r = e.bufferedRequest; + if (t._writev && r && r.next) { + var o = e.bufferedRequestCount, f = new Array(o), p = e.corkedRequestsFree; + p.entry = r; + for (var m = 0, y = true;r; ) + f[m] = r, r.isBuf || (y = false), r = r.next, m += 1; + f.allBuffers = y, pl2(t, e, true, e.length, f, "", p.finish), e.pendingcb++, e.lastBufferedRequest = null, p.next ? (e.corkedRequestsFree = p.next, p.next = null) : e.corkedRequestsFree = new _g(e), e.bufferedRequestCount = 0; + } else { + for (;r; ) { + var { chunk: M, encoding: x, callback: S } = r, E2 = e.objectMode ? 1 : M.length; + if (pl2(t, e, false, E2, M, x, S), r = r.next, e.bufferedRequestCount--, e.writing) + break; + } + r === null && (e.lastBufferedRequest = null); + } + e.bufferedRequest = r, e.bufferProcessing = false; + } + ut2.prototype._write = function(t, e, r) { + r(new $S("_write()")); + }; + ut2.prototype._writev = null; + ut2.prototype.end = function(t, e, r) { + var o = this._writableState; + return typeof t == "function" ? (r = t, t = null, e = null) : typeof e == "function" && (r = e, e = null), t != null && this.write(t, e), o.corked && (o.corked = 1, this.uncork()), o.ending || dE(this, o, r), this; + }; + Object.defineProperty(ut2.prototype, "writableLength", { enumerable: false, get: function() { + return this._writableState.length; + } }); + function Eg(t) { + return t.ending && t.length === 0 && t.bufferedRequest === null && !t.finished && !t.writing; + } + function uE(t, e) { + t._final(function(r) { + e.pendingcb--, r && Sf(t, r), e.prefinished = true, t.emit("prefinish"), Ta(t, e); + }); + } + function lE(t, e) { + !e.prefinished && !e.finalCalled && (typeof t._final == "function" && !e.destroyed ? (e.pendingcb++, e.finalCalled = true, process.nextTick(uE, t, e)) : (e.prefinished = true, t.emit("prefinish"))); + } + function Ta(t, e) { + var r = Eg(e); + if (r && (lE(t, e), e.pendingcb === 0 && (e.finished = true, t.emit("finish"), e.autoDestroy))) { + var o = t._readableState; + (!o || o.autoDestroy && o.endEmitted) && t.destroy(); + } + return r; + } + function dE(t, e, r) { + e.ending = true, Ta(t, e), r && (e.finished ? process.nextTick(r) : t.once("finish", r)), e.ended = true, t.writable = false; + } + function cE(t, e, r) { + var o = t.entry; + for (t.entry = null;o; ) { + var f = o.callback; + e.pendingcb--, f(r), o = o.next; + } + e.corkedRequestsFree.next = t; + } + Object.defineProperty(ut2.prototype, "destroyed", { enumerable: false, get: function() { + return this._writableState === undefined ? false : this._writableState.destroyed; + }, set: function(e) { + !this._writableState || (this._writableState.destroyed = e); + } }); + ut2.prototype.destroy = vl.destroy; + ut2.prototype._undestroy = vl.undestroy; + ut2.prototype._destroy = function(t, e) { + e(t); + }; + }); + Ln = T((uk, Bg) => { + var pE = Object.keys || function(t) { + var e = []; + for (var r in t) + e.push(r); + return e; + }; + Bg.exports = ti; + var Rg = yl2(), gl = bl(); + Ie()(ti, Rg); + for (ml = pE(gl.prototype), Ls = 0;Ls < ml.length; Ls++) + Ns = ml[Ls], ti.prototype[Ns] || (ti.prototype[Ns] = gl.prototype[Ns]); + var ml, Ns, Ls; + function ti(t) { + if (!(this instanceof ti)) + return new ti(t); + Rg.call(this, t), gl.call(this, t), this.allowHalfOpen = true, t && (t.readable === false && (this.readable = false), t.writable === false && (this.writable = false), t.allowHalfOpen === false && (this.allowHalfOpen = false, this.once("end", vE))); + } + Object.defineProperty(ti.prototype, "writableHighWaterMark", { enumerable: false, get: function() { + return this._writableState.highWaterMark; + } }); + Object.defineProperty(ti.prototype, "writableBuffer", { enumerable: false, get: function() { + return this._writableState && this._writableState.getBuffer(); + } }); + Object.defineProperty(ti.prototype, "writableLength", { enumerable: false, get: function() { + return this._writableState.length; + } }); + function vE() { + this._writableState.ended || process.nextTick(bE, this); + } + function bE(t) { + t.end(); + } + Object.defineProperty(ti.prototype, "destroyed", { enumerable: false, get: function() { + return this._readableState === undefined || this._writableState === undefined ? false : this._readableState.destroyed && this._writableState.destroyed; + }, set: function(e) { + this._readableState === undefined || this._writableState === undefined || (this._readableState.destroyed = e, this._writableState.destroyed = e); + } }); + }); + Ds = T((lk, Tg) => { + var qg = kn().codes.ERR_STREAM_PREMATURE_CLOSE; + function mE(t) { + var e = false; + return function() { + if (!e) { + e = true; + for (var r = arguments.length, o = new Array(r), f = 0;f < r; f++) + o[f] = arguments[f]; + t.apply(this, o); + } + }; + } + function gE() { + } + function yE(t) { + return t.setHeader && typeof t.abort == "function"; + } + function Ig(t, e, r) { + if (typeof e == "function") + return Ig(t, null, e); + e || (e = {}), r = mE(r || gE); + var o = e.readable || e.readable !== false && t.readable, f = e.writable || e.writable !== false && t.writable, p = function() { + t.writable || y(); + }, m = t._writableState && t._writableState.finished, y = function() { + f = false, m = true, o || r.call(t); + }, M = t._readableState && t._readableState.endEmitted, x = function() { + o = false, M = true, f || r.call(t); + }, S = function(L) { + r.call(t, L); + }, E2 = function() { + var L; + if (o && !M) + return (!t._readableState || !t._readableState.ended) && (L = new qg), r.call(t, L); + if (f && !m) + return (!t._writableState || !t._writableState.ended) && (L = new qg), r.call(t, L); + }, B = function() { + t.req.on("finish", y); + }; + return yE(t) ? (t.on("complete", y), t.on("abort", E2), t.req ? B() : t.on("request", B)) : f && !t._writableState && (t.on("end", p), t.on("close", p)), t.on("end", x), t.on("finish", y), e.error !== false && t.on("error", S), t.on("close", E2), function() { + t.removeListener("complete", y), t.removeListener("abort", E2), t.removeListener("request", B), t.req && t.req.removeListener("finish", y), t.removeListener("end", p), t.removeListener("close", p), t.removeListener("finish", y), t.removeListener("end", x), t.removeListener("error", S), t.removeListener("close", E2); + }; + } + Tg.exports = Ig; + }); + Lg = T((dk, kg) => { + var Ps; + function $i(t, e, r) { + return e in t ? Object.defineProperty(t, e, { value: r, enumerable: true, configurable: true, writable: true }) : t[e] = r, t; + } + var wE = Ds(), Gi2 = Symbol("lastResolve"), Nn = Symbol("lastReject"), La = Symbol("error"), Cs = Symbol("ended"), Dn = Symbol("lastPromise"), wl = Symbol("handlePromise"), Pn = Symbol("stream"); + function Yi(t, e) { + return { value: t, done: e }; + } + function ME(t) { + var e = t[Gi2]; + if (e !== null) { + var r = t[Pn].read(); + r !== null && (t[Dn] = null, t[Gi2] = null, t[Nn] = null, e(Yi(r, false))); + } + } + function _E(t) { + process.nextTick(ME, t); + } + function xE(t, e) { + return function(r, o) { + t.then(function() { + if (e[Cs]) { + r(Yi(undefined, true)); + return; + } + e[wl](r, o); + }, o); + }; + } + var SE = Object.getPrototypeOf(function() { + }), EE = Object.setPrototypeOf((Ps = { get stream() { + return this[Pn]; + }, next: function() { + var e = this, r = this[La]; + if (r !== null) + return Promise.reject(r); + if (this[Cs]) + return Promise.resolve(Yi(undefined, true)); + if (this[Pn].destroyed) + return new Promise(function(m, y) { + process.nextTick(function() { + e[La] ? y(e[La]) : m(Yi(undefined, true)); + }); + }); + var o = this[Dn], f; + if (o) + f = new Promise(xE(o, this)); + else { + var p = this[Pn].read(); + if (p !== null) + return Promise.resolve(Yi(p, false)); + f = new Promise(this[wl]); + } + return this[Dn] = f, f; + } }, $i(Ps, Symbol.asyncIterator, function() { + return this; + }), $i(Ps, "return", function() { + var e = this; + return new Promise(function(r, o) { + e[Pn].destroy(null, function(f) { + if (f) { + o(f); + return; + } + r(Yi(undefined, true)); + }); + }); + }), Ps), SE), AE = function(e) { + var r, o = Object.create(EE, (r = {}, $i(r, Pn, { value: e, writable: true }), $i(r, Gi2, { value: null, writable: true }), $i(r, Nn, { value: null, writable: true }), $i(r, La, { value: null, writable: true }), $i(r, Cs, { value: e._readableState.endEmitted, writable: true }), $i(r, wl, { value: function(p, m) { + var y = o[Pn].read(); + y ? (o[Dn] = null, o[Gi2] = null, o[Nn] = null, p(Yi(y, false))) : (o[Gi2] = p, o[Nn] = m); + }, writable: true }), r)); + return o[Dn] = null, wE(e, function(f) { + if (f && f.code !== "ERR_STREAM_PREMATURE_CLOSE") { + var p = o[Nn]; + p !== null && (o[Dn] = null, o[Gi2] = null, o[Nn] = null, p(f)), o[La] = f; + return; + } + var m = o[Gi2]; + m !== null && (o[Dn] = null, o[Gi2] = null, o[Nn] = null, m(Yi(undefined, true))), o[Cs] = true; + }), e.on("readable", _E.bind(null, o)), o; + }; + kg.exports = AE; + }); + Dg = T((ck, Ng) => { + Ng.exports = function() { + throw new Error("Readable.from is not available in the browser"); + }; + }); + yl2 = T((vk, jg) => { + jg.exports = Oe; + var Ef; + Oe.ReadableState = Fg; + var pk = ki().EventEmitter, Og = function(e, r) { + return e.listeners(r).length; + }, Da = hl2(), Os = Ut2().Buffer, RE = global.Uint8Array || function() { + }; + function BE(t) { + return Os.from(t); + } + function qE(t) { + return Os.isBuffer(t) || t instanceof RE; + } + var Ml = $f(), De; + Ml && Ml.debuglog ? De = Ml.debuglog("stream") : De = function() { + }; + var IE = pg(), Bl = dl2(), TE = cl2(), kE = TE.getHighWaterMark, Fs = kn().codes, LE = Fs.ERR_INVALID_ARG_TYPE, NE = Fs.ERR_STREAM_PUSH_AFTER_EOF, DE = Fs.ERR_METHOD_NOT_IMPLEMENTED, PE = Fs.ERR_STREAM_UNSHIFT_AFTER_END_EVENT, Af, _l, xl; + Ie()(Oe, Da); + var Na = Bl.errorOrDestroy, Sl = ["error", "close", "destroy", "pause", "resume"]; + function CE(t, e, r) { + if (typeof t.prependListener == "function") + return t.prependListener(e, r); + !t._events || !t._events[e] ? t.on(e, r) : Array.isArray(t._events[e]) ? t._events[e].unshift(r) : t._events[e] = [r, t._events[e]]; + } + function Fg(t, e, r) { + Ef = Ef || Ln(), t = t || {}, typeof r != "boolean" && (r = e instanceof Ef), this.objectMode = !!t.objectMode, r && (this.objectMode = this.objectMode || !!t.readableObjectMode), this.highWaterMark = kE(this, t, "readableHighWaterMark", r), this.buffer = new IE, this.length = 0, this.pipes = null, this.pipesCount = 0, this.flowing = null, this.ended = false, this.endEmitted = false, this.reading = false, this.sync = true, this.needReadable = false, this.emittedReadable = false, this.readableListening = false, this.resumeScheduled = false, this.paused = true, this.emitClose = t.emitClose !== false, this.autoDestroy = !!t.autoDestroy, this.destroyed = false, this.defaultEncoding = t.defaultEncoding || "utf8", this.awaitDrain = 0, this.readingMore = false, this.decoder = null, this.encoding = null, t.encoding && (Af || (Af = (Qf(), ur(Jf)).StringDecoder), this.decoder = new Af(t.encoding), this.encoding = t.encoding); + } + function Oe(t) { + if (Ef = Ef || Ln(), !(this instanceof Oe)) + return new Oe(t); + var e = this instanceof Ef; + this._readableState = new Fg(t, this, e), this.readable = true, t && (typeof t.read == "function" && (this._read = t.read), typeof t.destroy == "function" && (this._destroy = t.destroy)), Da.call(this); + } + Object.defineProperty(Oe.prototype, "destroyed", { enumerable: false, get: function() { + return this._readableState === undefined ? false : this._readableState.destroyed; + }, set: function(e) { + !this._readableState || (this._readableState.destroyed = e); + } }); + Oe.prototype.destroy = Bl.destroy; + Oe.prototype._undestroy = Bl.undestroy; + Oe.prototype._destroy = function(t, e) { + e(t); + }; + Oe.prototype.push = function(t, e) { + var r = this._readableState, o; + return r.objectMode ? o = true : typeof t == "string" && (e = e || r.defaultEncoding, e !== r.encoding && (t = Os.from(t, e), e = ""), o = true), Ug(this, t, e, false, o); + }; + Oe.prototype.unshift = function(t) { + return Ug(this, t, null, true, false); + }; + function Ug(t, e, r, o, f) { + De("readableAddChunk", e); + var p = t._readableState; + if (e === null) + p.reading = false, UE(t, p); + else { + var m; + if (f || (m = OE(p, e)), m) + Na(t, m); + else if (p.objectMode || e && e.length > 0) + if (typeof e != "string" && !p.objectMode && Object.getPrototypeOf(e) !== Os.prototype && (e = BE(e)), o) + p.endEmitted ? Na(t, new PE) : El(t, p, e, true); + else if (p.ended) + Na(t, new NE); + else { + if (p.destroyed) + return false; + p.reading = false, p.decoder && !r ? (e = p.decoder.write(e), p.objectMode || e.length !== 0 ? El(t, p, e, false) : Rl(t, p)) : El(t, p, e, false); + } + else + o || (p.reading = false, Rl(t, p)); + } + return !p.ended && (p.length < p.highWaterMark || p.length === 0); + } + function El(t, e, r, o) { + e.flowing && e.length === 0 && !e.sync ? (e.awaitDrain = 0, t.emit("data", r)) : (e.length += e.objectMode ? 1 : r.length, o ? e.buffer.unshift(r) : e.buffer.push(r), e.needReadable && Us(t)), Rl(t, e); + } + function OE(t, e) { + var r; + return !qE(e) && typeof e != "string" && e !== undefined && !t.objectMode && (r = new LE("chunk", ["string", "Buffer", "Uint8Array"], e)), r; + } + Oe.prototype.isPaused = function() { + return this._readableState.flowing === false; + }; + Oe.prototype.setEncoding = function(t) { + Af || (Af = (Qf(), ur(Jf)).StringDecoder); + var e = new Af(t); + this._readableState.decoder = e, this._readableState.encoding = this._readableState.decoder.encoding; + for (var r = this._readableState.buffer.head, o = "";r !== null; ) + o += e.write(r.data), r = r.next; + return this._readableState.buffer.clear(), o !== "" && this._readableState.buffer.push(o), this._readableState.length = o.length, this; + }; + var Pg = 1073741824; + function FE(t) { + return t >= Pg ? t = Pg : (t--, t |= t >>> 1, t |= t >>> 2, t |= t >>> 4, t |= t >>> 8, t |= t >>> 16, t++), t; + } + function Cg(t, e) { + return t <= 0 || e.length === 0 && e.ended ? 0 : e.objectMode ? 1 : t !== t ? e.flowing && e.length ? e.buffer.head.data.length : e.length : (t > e.highWaterMark && (e.highWaterMark = FE(t)), t <= e.length ? t : e.ended ? e.length : (e.needReadable = true, 0)); + } + Oe.prototype.read = function(t) { + De("read", t), t = parseInt(t, 10); + var e = this._readableState, r = t; + if (t !== 0 && (e.emittedReadable = false), t === 0 && e.needReadable && ((e.highWaterMark !== 0 ? e.length >= e.highWaterMark : e.length > 0) || e.ended)) + return De("read: emitReadable", e.length, e.ended), e.length === 0 && e.ended ? Al(this) : Us(this), null; + if (t = Cg(t, e), t === 0 && e.ended) + return e.length === 0 && Al(this), null; + var o = e.needReadable; + De("need readable", o), (e.length === 0 || e.length - t < e.highWaterMark) && (o = true, De("length less than watermark", o)), e.ended || e.reading ? (o = false, De("reading or ended", o)) : o && (De("do read"), e.reading = true, e.sync = true, e.length === 0 && (e.needReadable = true), this._read(e.highWaterMark), e.sync = false, e.reading || (t = Cg(r, e))); + var f; + return t > 0 ? f = Wg(t, e) : f = null, f === null ? (e.needReadable = e.length <= e.highWaterMark, t = 0) : (e.length -= t, e.awaitDrain = 0), e.length === 0 && (e.ended || (e.needReadable = true), r !== t && e.ended && Al(this)), f !== null && this.emit("data", f), f; + }; + function UE(t, e) { + if (De("onEofChunk"), !e.ended) { + if (e.decoder) { + var r = e.decoder.end(); + r && r.length && (e.buffer.push(r), e.length += e.objectMode ? 1 : r.length); + } + e.ended = true, e.sync ? Us(t) : (e.needReadable = false, e.emittedReadable || (e.emittedReadable = true, zg(t))); + } + } + function Us(t) { + var e = t._readableState; + De("emitReadable", e.needReadable, e.emittedReadable), e.needReadable = false, e.emittedReadable || (De("emitReadable", e.flowing), e.emittedReadable = true, process.nextTick(zg, t)); + } + function zg(t) { + var e = t._readableState; + De("emitReadable_", e.destroyed, e.length, e.ended), !e.destroyed && (e.length || e.ended) && (t.emit("readable"), e.emittedReadable = false), e.needReadable = !e.flowing && !e.ended && e.length <= e.highWaterMark, ql(t); + } + function Rl(t, e) { + e.readingMore || (e.readingMore = true, process.nextTick(zE, t, e)); + } + function zE(t, e) { + for (;!e.reading && !e.ended && (e.length < e.highWaterMark || e.flowing && e.length === 0); ) { + var r = e.length; + if (De("maybeReadMore read 0"), t.read(0), r === e.length) + break; + } + e.readingMore = false; + } + Oe.prototype._read = function(t) { + Na(this, new DE("_read()")); + }; + Oe.prototype.pipe = function(t, e) { + var r = this, o = this._readableState; + switch (o.pipesCount) { + case 0: + o.pipes = t; + break; + case 1: + o.pipes = [o.pipes, t]; + break; + default: + o.pipes.push(t); + break; + } + o.pipesCount += 1, De("pipe count=%d opts=%j", o.pipesCount, e); + var f = (!e || e.end !== false) && t !== process.stdout && t !== process.stderr, p = f ? y : ge; + o.endEmitted ? process.nextTick(p) : r.once("end", p), t.on("unpipe", m); + function m(_e, N) { + De("onunpipe"), _e === r && N && N.hasUnpiped === false && (N.hasUnpiped = true, S()); + } + function y() { + De("onend"), t.end(); + } + var M = HE(r); + t.on("drain", M); + var x = false; + function S() { + De("cleanup"), t.removeListener("close", q), t.removeListener("finish", L), t.removeListener("drain", M), t.removeListener("error", B), t.removeListener("unpipe", m), r.removeListener("end", y), r.removeListener("end", ge), r.removeListener("data", E2), x = true, o.awaitDrain && (!t._writableState || t._writableState.needDrain) && M(); + } + r.on("data", E2); + function E2(_e) { + De("ondata"); + var N = t.write(_e); + De("dest.write", N), N === false && ((o.pipesCount === 1 && o.pipes === t || o.pipesCount > 1 && Kg(o.pipes, t) !== -1) && !x && (De("false write response, pause", o.awaitDrain), o.awaitDrain++), r.pause()); + } + function B(_e) { + De("onerror", _e), ge(), t.removeListener("error", B), Og(t, "error") === 0 && Na(t, _e); + } + CE(t, "error", B); + function q() { + t.removeListener("finish", L), ge(); + } + t.once("close", q); + function L() { + De("onfinish"), t.removeListener("close", q), ge(); + } + t.once("finish", L); + function ge() { + De("unpipe"), r.unpipe(t); + } + return t.emit("pipe", r), o.flowing || (De("pipe resume"), r.resume()), t; + }; + function HE(t) { + return function() { + var r = t._readableState; + De("pipeOnDrain", r.awaitDrain), r.awaitDrain && r.awaitDrain--, r.awaitDrain === 0 && Og(t, "data") && (r.flowing = true, ql(t)); + }; + } + Oe.prototype.unpipe = function(t) { + var e = this._readableState, r = { hasUnpiped: false }; + if (e.pipesCount === 0) + return this; + if (e.pipesCount === 1) + return t && t !== e.pipes ? this : (t || (t = e.pipes), e.pipes = null, e.pipesCount = 0, e.flowing = false, t && t.emit("unpipe", this, r), this); + if (!t) { + var { pipes: o, pipesCount: f } = e; + e.pipes = null, e.pipesCount = 0, e.flowing = false; + for (var p = 0;p < f; p++) + o[p].emit("unpipe", this, { hasUnpiped: false }); + return this; + } + var m = Kg(e.pipes, t); + return m === -1 ? this : (e.pipes.splice(m, 1), e.pipesCount -= 1, e.pipesCount === 1 && (e.pipes = e.pipes[0]), t.emit("unpipe", this, r), this); + }; + Oe.prototype.on = function(t, e) { + var r = Da.prototype.on.call(this, t, e), o = this._readableState; + return t === "data" ? (o.readableListening = this.listenerCount("readable") > 0, o.flowing !== false && this.resume()) : t === "readable" && !o.endEmitted && !o.readableListening && (o.readableListening = o.needReadable = true, o.flowing = false, o.emittedReadable = false, De("on readable", o.length, o.reading), o.length ? Us(this) : o.reading || process.nextTick(WE, this)), r; + }; + Oe.prototype.addListener = Oe.prototype.on; + Oe.prototype.removeListener = function(t, e) { + var r = Da.prototype.removeListener.call(this, t, e); + return t === "readable" && process.nextTick(Hg, this), r; + }; + Oe.prototype.removeAllListeners = function(t) { + var e = Da.prototype.removeAllListeners.apply(this, arguments); + return (t === "readable" || t === undefined) && process.nextTick(Hg, this), e; + }; + function Hg(t) { + var e = t._readableState; + e.readableListening = t.listenerCount("readable") > 0, e.resumeScheduled && !e.paused ? e.flowing = true : t.listenerCount("data") > 0 && t.resume(); + } + function WE(t) { + De("readable nexttick read 0"), t.read(0); + } + Oe.prototype.resume = function() { + var t = this._readableState; + return t.flowing || (De("resume"), t.flowing = !t.readableListening, KE(this, t)), t.paused = false, this; + }; + function KE(t, e) { + e.resumeScheduled || (e.resumeScheduled = true, process.nextTick(jE, t, e)); + } + function jE(t, e) { + De("resume", e.reading), e.reading || t.read(0), e.resumeScheduled = false, t.emit("resume"), ql(t), e.flowing && !e.reading && t.read(0); + } + Oe.prototype.pause = function() { + return De("call pause flowing=%j", this._readableState.flowing), this._readableState.flowing !== false && (De("pause"), this._readableState.flowing = false, this.emit("pause")), this._readableState.paused = true, this; + }; + function ql(t) { + var e = t._readableState; + for (De("flow", e.flowing);e.flowing && t.read() !== null; ) + ; + } + Oe.prototype.wrap = function(t) { + var e = this, r = this._readableState, o = false; + t.on("end", function() { + if (De("wrapped end"), r.decoder && !r.ended) { + var m = r.decoder.end(); + m && m.length && e.push(m); + } + e.push(null); + }), t.on("data", function(m) { + if (De("wrapped data"), r.decoder && (m = r.decoder.write(m)), !(r.objectMode && m == null) && !(!r.objectMode && (!m || !m.length))) { + var y = e.push(m); + y || (o = true, t.pause()); + } + }); + for (var f in t) + this[f] === undefined && typeof t[f] == "function" && (this[f] = function(y) { + return function() { + return t[y].apply(t, arguments); + }; + }(f)); + for (var p = 0;p < Sl.length; p++) + t.on(Sl[p], this.emit.bind(this, Sl[p])); + return this._read = function(m) { + De("wrapped _read", m), o && (o = false, t.resume()); + }, this; + }; + typeof Symbol == "function" && (Oe.prototype[Symbol.asyncIterator] = function() { + return _l === undefined && (_l = Lg()), _l(this); + }); + Object.defineProperty(Oe.prototype, "readableHighWaterMark", { enumerable: false, get: function() { + return this._readableState.highWaterMark; + } }); + Object.defineProperty(Oe.prototype, "readableBuffer", { enumerable: false, get: function() { + return this._readableState && this._readableState.buffer; + } }); + Object.defineProperty(Oe.prototype, "readableFlowing", { enumerable: false, get: function() { + return this._readableState.flowing; + }, set: function(e) { + this._readableState && (this._readableState.flowing = e); + } }); + Oe._fromList = Wg; + Object.defineProperty(Oe.prototype, "readableLength", { enumerable: false, get: function() { + return this._readableState.length; + } }); + function Wg(t, e) { + if (e.length === 0) + return null; + var r; + return e.objectMode ? r = e.buffer.shift() : !t || t >= e.length ? (e.decoder ? r = e.buffer.join("") : e.buffer.length === 1 ? r = e.buffer.first() : r = e.buffer.concat(e.length), e.buffer.clear()) : r = e.buffer.consume(t, e.decoder), r; + } + function Al(t) { + var e = t._readableState; + De("endReadable", e.endEmitted), e.endEmitted || (e.ended = true, process.nextTick(ZE, e, t)); + } + function ZE(t, e) { + if (De("endReadableNT", t.endEmitted, t.length), !t.endEmitted && t.length === 0 && (t.endEmitted = true, e.readable = false, e.emit("end"), t.autoDestroy)) { + var r = e._writableState; + (!r || r.autoDestroy && r.finished) && e.destroy(); + } + } + typeof Symbol == "function" && (Oe.from = function(t, e) { + return xl === undefined && (xl = Dg()), xl(Oe, t, e); + }); + function Kg(t, e) { + for (var r = 0, o = t.length;r < o; r++) + if (t[r] === e) + return r; + return -1; + } + }); + Il = T((bk, Vg) => { + Vg.exports = Ei; + var zs = kn().codes, VE = zs.ERR_METHOD_NOT_IMPLEMENTED, $E = zs.ERR_MULTIPLE_CALLBACK, GE = zs.ERR_TRANSFORM_ALREADY_TRANSFORMING, YE = zs.ERR_TRANSFORM_WITH_LENGTH_0, Hs = Ln(); + Ie()(Ei, Hs); + function XE(t, e) { + var r = this._transformState; + r.transforming = false; + var o = r.writecb; + if (o === null) + return this.emit("error", new $E); + r.writechunk = null, r.writecb = null, e != null && this.push(e), o(t); + var f = this._readableState; + f.reading = false, (f.needReadable || f.length < f.highWaterMark) && this._read(f.highWaterMark); + } + function Ei(t) { + if (!(this instanceof Ei)) + return new Ei(t); + Hs.call(this, t), this._transformState = { afterTransform: XE.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }, this._readableState.needReadable = true, this._readableState.sync = false, t && (typeof t.transform == "function" && (this._transform = t.transform), typeof t.flush == "function" && (this._flush = t.flush)), this.on("prefinish", JE); + } + function JE() { + var t = this; + typeof this._flush == "function" && !this._readableState.destroyed ? this._flush(function(e, r) { + Zg(t, e, r); + }) : Zg(this, null, null); + } + Ei.prototype.push = function(t, e) { + return this._transformState.needTransform = false, Hs.prototype.push.call(this, t, e); + }; + Ei.prototype._transform = function(t, e, r) { + r(new VE("_transform()")); + }; + Ei.prototype._write = function(t, e, r) { + var o = this._transformState; + if (o.writecb = r, o.writechunk = t, o.writeencoding = e, !o.transforming) { + var f = this._readableState; + (o.needTransform || f.needReadable || f.length < f.highWaterMark) && this._read(f.highWaterMark); + } + }; + Ei.prototype._read = function(t) { + var e = this._transformState; + e.writechunk !== null && !e.transforming ? (e.transforming = true, this._transform(e.writechunk, e.writeencoding, e.afterTransform)) : e.needTransform = true; + }; + Ei.prototype._destroy = function(t, e) { + Hs.prototype._destroy.call(this, t, function(r) { + e(r); + }); + }; + function Zg(t, e, r) { + if (e) + return t.emit("error", e); + if (r != null && t.push(r), t._writableState.length) + throw new YE; + if (t._transformState.transforming) + throw new GE; + return t.push(null); + } + }); + Yg = T((mk, Gg) => { + Gg.exports = Pa; + var $g = Il(); + Ie()(Pa, $g); + function Pa(t) { + if (!(this instanceof Pa)) + return new Pa(t); + $g.call(this, t); + } + Pa.prototype._transform = function(t, e, r) { + r(null, t); + }; + }); + t2 = T((gk, e2) => { + var Tl; + function QE(t) { + var e = false; + return function() { + e || (e = true, t.apply(undefined, arguments)); + }; + } + var Qg = kn().codes, eA = Qg.ERR_MISSING_ARGS, tA = Qg.ERR_STREAM_DESTROYED; + function Xg(t) { + if (t) + throw t; + } + function rA(t) { + return t.setHeader && typeof t.abort == "function"; + } + function iA(t, e, r, o) { + o = QE(o); + var f = false; + t.on("close", function() { + f = true; + }), Tl === undefined && (Tl = Ds()), Tl(t, { readable: e, writable: r }, function(m) { + if (m) + return o(m); + f = true, o(); + }); + var p = false; + return function(m) { + if (!f && !p) { + if (p = true, rA(t)) + return t.abort(); + if (typeof t.destroy == "function") + return t.destroy(); + o(m || new tA("pipe")); + } + }; + } + function Jg(t) { + t(); + } + function nA(t, e) { + return t.pipe(e); + } + function fA(t) { + return !t.length || typeof t[t.length - 1] != "function" ? Xg : t.pop(); + } + function aA() { + for (var t = arguments.length, e = new Array(t), r = 0;r < t; r++) + e[r] = arguments[r]; + var o = fA(e); + if (Array.isArray(e[0]) && (e = e[0]), e.length < 2) + throw new eA("streams"); + var f, p = e.map(function(m, y) { + var M = y < e.length - 1, x = y > 0; + return iA(m, M, x, function(S) { + f || (f = S), S && p.forEach(Jg), !M && (p.forEach(Jg), o(f)); + }); + }); + return e.reduce(nA); + } + e2.exports = aA; + }); + i2 = T((Mr, r2) => { + Mr = r2.exports = yl2(); + Mr.Stream = Mr; + Mr.Readable = Mr; + Mr.Writable = bl(); + Mr.Duplex = Ln(); + Mr.Transform = Il(); + Mr.PassThrough = Yg(); + Mr.finished = Ds(); + Mr.pipeline = t2(); + }); + Ws = T((n2, kl) => { + (function(t, e) { + function r(h, s) { + if (!h) + throw new Error(s || "Assertion failed"); + } + function o(h, s) { + h.super_ = s; + var u = function() { + }; + u.prototype = s.prototype, h.prototype = new u, h.prototype.constructor = h; + } + function f(h, s, u) { + if (f.isBN(h)) + return h; + this.negative = 0, this.words = null, this.length = 0, this.red = null, h !== null && ((s === "le" || s === "be") && (u = s, s = 10), this._init(h || 0, s || 10, u || "be")); + } + typeof t == "object" ? t.exports = f : e.BN = f, f.BN = f, f.wordSize = 26; + var p; + try { + typeof window < "u" && typeof window.Buffer < "u" ? p = window.Buffer : p = ji().Buffer; + } catch { + } + f.isBN = function(s) { + return s instanceof f ? true : s !== null && typeof s == "object" && s.constructor.wordSize === f.wordSize && Array.isArray(s.words); + }, f.max = function(s, u) { + return s.cmp(u) > 0 ? s : u; + }, f.min = function(s, u) { + return s.cmp(u) < 0 ? s : u; + }, f.prototype._init = function(s, u, c) { + if (typeof s == "number") + return this._initNumber(s, u, c); + if (typeof s == "object") + return this._initArray(s, u, c); + u === "hex" && (u = 16), r(u === (u | 0) && u >= 2 && u <= 36), s = s.toString().replace(/\s+/g, ""); + var b = 0; + s[0] === "-" && (b++, this.negative = 1), b < s.length && (u === 16 ? this._parseHex(s, b, c) : (this._parseBase(s, u, b), c === "le" && this._initArray(this.toArray(), u, c))); + }, f.prototype._initNumber = function(s, u, c) { + s < 0 && (this.negative = 1, s = -s), s < 67108864 ? (this.words = [s & 67108863], this.length = 1) : s < 4503599627370496 ? (this.words = [s & 67108863, s / 67108864 & 67108863], this.length = 2) : (r(s < 9007199254740992), this.words = [s & 67108863, s / 67108864 & 67108863, 1], this.length = 3), c === "le" && this._initArray(this.toArray(), u, c); + }, f.prototype._initArray = function(s, u, c) { + if (r(typeof s.length == "number"), s.length <= 0) + return this.words = [0], this.length = 1, this; + this.length = Math.ceil(s.length / 3), this.words = new Array(this.length); + for (var b = 0;b < this.length; b++) + this.words[b] = 0; + var l, n, d = 0; + if (c === "be") + for (b = s.length - 1, l = 0;b >= 0; b -= 3) + n = s[b] | s[b - 1] << 8 | s[b - 2] << 16, this.words[l] |= n << d & 67108863, this.words[l + 1] = n >>> 26 - d & 67108863, d += 24, d >= 26 && (d -= 26, l++); + else if (c === "le") + for (b = 0, l = 0;b < s.length; b += 3) + n = s[b] | s[b + 1] << 8 | s[b + 2] << 16, this.words[l] |= n << d & 67108863, this.words[l + 1] = n >>> 26 - d & 67108863, d += 24, d >= 26 && (d -= 26, l++); + return this._strip(); + }; + function m(h, s) { + var u = h.charCodeAt(s); + if (u >= 48 && u <= 57) + return u - 48; + if (u >= 65 && u <= 70) + return u - 55; + if (u >= 97 && u <= 102) + return u - 87; + r(false, "Invalid character in " + h); + } + function y(h, s, u) { + var c = m(h, u); + return u - 1 >= s && (c |= m(h, u - 1) << 4), c; + } + f.prototype._parseHex = function(s, u, c) { + this.length = Math.ceil((s.length - u) / 6), this.words = new Array(this.length); + for (var b = 0;b < this.length; b++) + this.words[b] = 0; + var l = 0, n = 0, d; + if (c === "be") + for (b = s.length - 1;b >= u; b -= 2) + d = y(s, u, b) << l, this.words[n] |= d & 67108863, l >= 18 ? (l -= 18, n += 1, this.words[n] |= d >>> 26) : l += 8; + else { + var w = s.length - u; + for (b = w % 2 === 0 ? u + 1 : u;b < s.length; b += 2) + d = y(s, u, b) << l, this.words[n] |= d & 67108863, l >= 18 ? (l -= 18, n += 1, this.words[n] |= d >>> 26) : l += 8; + } + this._strip(); + }; + function M(h, s, u, c) { + for (var b = 0, l = 0, n = Math.min(h.length, u), d = s;d < n; d++) { + var w = h.charCodeAt(d) - 48; + b *= c, w >= 49 ? l = w - 49 + 10 : w >= 17 ? l = w - 17 + 10 : l = w, r(w >= 0 && l < c, "Invalid character"), b += l; + } + return b; + } + f.prototype._parseBase = function(s, u, c) { + this.words = [0], this.length = 1; + for (var b = 0, l = 1;l <= 67108863; l *= u) + b++; + b--, l = l / u | 0; + for (var n = s.length - c, d = n % b, w = Math.min(n, n - d) + c, g = 0, _9 = c;_9 < w; _9 += b) + g = M(s, _9, _9 + b, u), this.imuln(l), this.words[0] + g < 67108864 ? this.words[0] += g : this._iaddn(g); + if (d !== 0) { + var A = 1; + for (g = M(s, _9, s.length, u), _9 = 0;_9 < d; _9++) + A *= u; + this.imuln(A), this.words[0] + g < 67108864 ? this.words[0] += g : this._iaddn(g); + } + this._strip(); + }, f.prototype.copy = function(s) { + s.words = new Array(this.length); + for (var u = 0;u < this.length; u++) + s.words[u] = this.words[u]; + s.length = this.length, s.negative = this.negative, s.red = this.red; + }; + function x(h, s) { + h.words = s.words, h.length = s.length, h.negative = s.negative, h.red = s.red; + } + if (f.prototype._move = function(s) { + x(s, this); + }, f.prototype.clone = function() { + var s = new f(null); + return this.copy(s), s; + }, f.prototype._expand = function(s) { + for (;this.length < s; ) + this.words[this.length++] = 0; + return this; + }, f.prototype._strip = function() { + for (;this.length > 1 && this.words[this.length - 1] === 0; ) + this.length--; + return this._normSign(); + }, f.prototype._normSign = function() { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }, typeof Symbol < "u" && typeof Symbol.for == "function") + try { + f.prototype[Symbol.for("nodejs.util.inspect.custom")] = S; + } catch { + f.prototype.inspect = S; + } + else + f.prototype.inspect = S; + function S() { + return (this.red ? ""; + } + var E2 = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], B = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], q = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; + f.prototype.toString = function(s, u) { + s = s || 10, u = u | 0 || 1; + var c; + if (s === 16 || s === "hex") { + c = ""; + for (var b = 0, l = 0, n = 0;n < this.length; n++) { + var d = this.words[n], w = ((d << b | l) & 16777215).toString(16); + l = d >>> 24 - b & 16777215, b += 2, b >= 26 && (b -= 26, n--), l !== 0 || n !== this.length - 1 ? c = E2[6 - w.length] + w + c : c = w + c; + } + for (l !== 0 && (c = l.toString(16) + c);c.length % u !== 0; ) + c = "0" + c; + return this.negative !== 0 && (c = "-" + c), c; + } + if (s === (s | 0) && s >= 2 && s <= 36) { + var g = B[s], _9 = q[s]; + c = ""; + var A = this.clone(); + for (A.negative = 0;!A.isZero(); ) { + var R = A.modrn(_9).toString(s); + A = A.idivn(_9), A.isZero() ? c = R + c : c = E2[g - R.length] + R + c; + } + for (this.isZero() && (c = "0" + c);c.length % u !== 0; ) + c = "0" + c; + return this.negative !== 0 && (c = "-" + c), c; + } + r(false, "Base should be between 2 and 36"); + }, f.prototype.toNumber = function() { + var s = this.words[0]; + return this.length === 2 ? s += this.words[1] * 67108864 : this.length === 3 && this.words[2] === 1 ? s += 4503599627370496 + this.words[1] * 67108864 : this.length > 2 && r(false, "Number can only safely store up to 53 bits"), this.negative !== 0 ? -s : s; + }, f.prototype.toJSON = function() { + return this.toString(16, 2); + }, p && (f.prototype.toBuffer = function(s, u) { + return this.toArrayLike(p, s, u); + }), f.prototype.toArray = function(s, u) { + return this.toArrayLike(Array, s, u); + }; + var L = function(s, u) { + return s.allocUnsafe ? s.allocUnsafe(u) : new s(u); + }; + f.prototype.toArrayLike = function(s, u, c) { + this._strip(); + var b = this.byteLength(), l = c || Math.max(1, b); + r(b <= l, "byte array longer than desired length"), r(l > 0, "Requested array length <= 0"); + var n = L(s, l), d = u === "le" ? "LE" : "BE"; + return this["_toArrayLike" + d](n, b), n; + }, f.prototype._toArrayLikeLE = function(s, u) { + for (var c = 0, b = 0, l = 0, n = 0;l < this.length; l++) { + var d = this.words[l] << n | b; + s[c++] = d & 255, c < s.length && (s[c++] = d >> 8 & 255), c < s.length && (s[c++] = d >> 16 & 255), n === 6 ? (c < s.length && (s[c++] = d >> 24 & 255), b = 0, n = 0) : (b = d >>> 24, n += 2); + } + if (c < s.length) + for (s[c++] = b;c < s.length; ) + s[c++] = 0; + }, f.prototype._toArrayLikeBE = function(s, u) { + for (var c = s.length - 1, b = 0, l = 0, n = 0;l < this.length; l++) { + var d = this.words[l] << n | b; + s[c--] = d & 255, c >= 0 && (s[c--] = d >> 8 & 255), c >= 0 && (s[c--] = d >> 16 & 255), n === 6 ? (c >= 0 && (s[c--] = d >> 24 & 255), b = 0, n = 0) : (b = d >>> 24, n += 2); + } + if (c >= 0) + for (s[c--] = b;c >= 0; ) + s[c--] = 0; + }, Math.clz32 ? f.prototype._countBits = function(s) { + return 32 - Math.clz32(s); + } : f.prototype._countBits = function(s) { + var u = s, c = 0; + return u >= 4096 && (c += 13, u >>>= 13), u >= 64 && (c += 7, u >>>= 7), u >= 8 && (c += 4, u >>>= 4), u >= 2 && (c += 2, u >>>= 2), c + u; + }, f.prototype._zeroBits = function(s) { + if (s === 0) + return 26; + var u = s, c = 0; + return (u & 8191) === 0 && (c += 13, u >>>= 13), (u & 127) === 0 && (c += 7, u >>>= 7), (u & 15) === 0 && (c += 4, u >>>= 4), (u & 3) === 0 && (c += 2, u >>>= 2), (u & 1) === 0 && c++, c; + }, f.prototype.bitLength = function() { + var s = this.words[this.length - 1], u = this._countBits(s); + return (this.length - 1) * 26 + u; + }; + function ge(h) { + for (var s = new Array(h.bitLength()), u = 0;u < s.length; u++) { + var c = u / 26 | 0, b = u % 26; + s[u] = h.words[c] >>> b & 1; + } + return s; + } + f.prototype.zeroBits = function() { + if (this.isZero()) + return 0; + for (var s = 0, u = 0;u < this.length; u++) { + var c = this._zeroBits(this.words[u]); + if (s += c, c !== 26) + break; + } + return s; + }, f.prototype.byteLength = function() { + return Math.ceil(this.bitLength() / 8); + }, f.prototype.toTwos = function(s) { + return this.negative !== 0 ? this.abs().inotn(s).iaddn(1) : this.clone(); + }, f.prototype.fromTwos = function(s) { + return this.testn(s - 1) ? this.notn(s).iaddn(1).ineg() : this.clone(); + }, f.prototype.isNeg = function() { + return this.negative !== 0; + }, f.prototype.neg = function() { + return this.clone().ineg(); + }, f.prototype.ineg = function() { + return this.isZero() || (this.negative ^= 1), this; + }, f.prototype.iuor = function(s) { + for (;this.length < s.length; ) + this.words[this.length++] = 0; + for (var u = 0;u < s.length; u++) + this.words[u] = this.words[u] | s.words[u]; + return this._strip(); + }, f.prototype.ior = function(s) { + return r((this.negative | s.negative) === 0), this.iuor(s); + }, f.prototype.or = function(s) { + return this.length > s.length ? this.clone().ior(s) : s.clone().ior(this); + }, f.prototype.uor = function(s) { + return this.length > s.length ? this.clone().iuor(s) : s.clone().iuor(this); + }, f.prototype.iuand = function(s) { + var u; + this.length > s.length ? u = s : u = this; + for (var c = 0;c < u.length; c++) + this.words[c] = this.words[c] & s.words[c]; + return this.length = u.length, this._strip(); + }, f.prototype.iand = function(s) { + return r((this.negative | s.negative) === 0), this.iuand(s); + }, f.prototype.and = function(s) { + return this.length > s.length ? this.clone().iand(s) : s.clone().iand(this); + }, f.prototype.uand = function(s) { + return this.length > s.length ? this.clone().iuand(s) : s.clone().iuand(this); + }, f.prototype.iuxor = function(s) { + var u, c; + this.length > s.length ? (u = this, c = s) : (u = s, c = this); + for (var b = 0;b < c.length; b++) + this.words[b] = u.words[b] ^ c.words[b]; + if (this !== u) + for (;b < u.length; b++) + this.words[b] = u.words[b]; + return this.length = u.length, this._strip(); + }, f.prototype.ixor = function(s) { + return r((this.negative | s.negative) === 0), this.iuxor(s); + }, f.prototype.xor = function(s) { + return this.length > s.length ? this.clone().ixor(s) : s.clone().ixor(this); + }, f.prototype.uxor = function(s) { + return this.length > s.length ? this.clone().iuxor(s) : s.clone().iuxor(this); + }, f.prototype.inotn = function(s) { + r(typeof s == "number" && s >= 0); + var u = Math.ceil(s / 26) | 0, c = s % 26; + this._expand(u), c > 0 && u--; + for (var b = 0;b < u; b++) + this.words[b] = ~this.words[b] & 67108863; + return c > 0 && (this.words[b] = ~this.words[b] & 67108863 >> 26 - c), this._strip(); + }, f.prototype.notn = function(s) { + return this.clone().inotn(s); + }, f.prototype.setn = function(s, u) { + r(typeof s == "number" && s >= 0); + var c = s / 26 | 0, b = s % 26; + return this._expand(c + 1), u ? this.words[c] = this.words[c] | 1 << b : this.words[c] = this.words[c] & ~(1 << b), this._strip(); + }, f.prototype.iadd = function(s) { + var u; + if (this.negative !== 0 && s.negative === 0) + return this.negative = 0, u = this.isub(s), this.negative ^= 1, this._normSign(); + if (this.negative === 0 && s.negative !== 0) + return s.negative = 0, u = this.isub(s), s.negative = 1, u._normSign(); + var c, b; + this.length > s.length ? (c = this, b = s) : (c = s, b = this); + for (var l = 0, n = 0;n < b.length; n++) + u = (c.words[n] | 0) + (b.words[n] | 0) + l, this.words[n] = u & 67108863, l = u >>> 26; + for (;l !== 0 && n < c.length; n++) + u = (c.words[n] | 0) + l, this.words[n] = u & 67108863, l = u >>> 26; + if (this.length = c.length, l !== 0) + this.words[this.length] = l, this.length++; + else if (c !== this) + for (;n < c.length; n++) + this.words[n] = c.words[n]; + return this; + }, f.prototype.add = function(s) { + var u; + return s.negative !== 0 && this.negative === 0 ? (s.negative = 0, u = this.sub(s), s.negative ^= 1, u) : s.negative === 0 && this.negative !== 0 ? (this.negative = 0, u = s.sub(this), this.negative = 1, u) : this.length > s.length ? this.clone().iadd(s) : s.clone().iadd(this); + }, f.prototype.isub = function(s) { + if (s.negative !== 0) { + s.negative = 0; + var u = this.iadd(s); + return s.negative = 1, u._normSign(); + } else if (this.negative !== 0) + return this.negative = 0, this.iadd(s), this.negative = 1, this._normSign(); + var c = this.cmp(s); + if (c === 0) + return this.negative = 0, this.length = 1, this.words[0] = 0, this; + var b, l; + c > 0 ? (b = this, l = s) : (b = s, l = this); + for (var n = 0, d = 0;d < l.length; d++) + u = (b.words[d] | 0) - (l.words[d] | 0) + n, n = u >> 26, this.words[d] = u & 67108863; + for (;n !== 0 && d < b.length; d++) + u = (b.words[d] | 0) + n, n = u >> 26, this.words[d] = u & 67108863; + if (n === 0 && d < b.length && b !== this) + for (;d < b.length; d++) + this.words[d] = b.words[d]; + return this.length = Math.max(this.length, d), b !== this && (this.negative = 1), this._strip(); + }, f.prototype.sub = function(s) { + return this.clone().isub(s); + }; + function _e(h, s, u) { + u.negative = s.negative ^ h.negative; + var c = h.length + s.length | 0; + u.length = c, c = c - 1 | 0; + var b = h.words[0] | 0, l = s.words[0] | 0, n = b * l, d = n & 67108863, w = n / 67108864 | 0; + u.words[0] = d; + for (var g = 1;g < c; g++) { + for (var _9 = w >>> 26, A = w & 67108863, R = Math.min(g, s.length - 1), I2 = Math.max(0, g - h.length + 1);I2 <= R; I2++) { + var Me = g - I2 | 0; + b = h.words[Me] | 0, l = s.words[I2] | 0, n = b * l + A, _9 += n / 67108864 | 0, A = n & 67108863; + } + u.words[g] = A | 0, w = _9 | 0; + } + return w !== 0 ? u.words[g] = w | 0 : u.length--, u._strip(); + } + var N = function(s, u, c) { + var b = s.words, l = u.words, n = c.words, d = 0, w, g, _9, A = b[0] | 0, R = A & 8191, I2 = A >>> 13, Me = b[1] | 0, k2 = Me & 8191, D = Me >>> 13, nt = b[2] | 0, C2 = nt & 8191, O = nt >>> 13, vt = b[3] | 0, F = vt & 8191, U = vt >>> 13, bt = b[4] | 0, z = bt & 8191, H = bt >>> 13, mt = b[5] | 0, W = mt & 8191, K = mt >>> 13, gt = b[6] | 0, j = gt & 8191, Z = gt >>> 13, yt = b[7] | 0, V2 = yt & 8191, $ = yt >>> 13, wt = b[8] | 0, G = wt & 8191, Y = wt >>> 13, Mt = b[9] | 0, X = Mt & 8191, J2 = Mt >>> 13, _t = l[0] | 0, Q = _t & 8191, ee = _t >>> 13, xt2 = l[1] | 0, te2 = xt2 & 8191, re = xt2 >>> 13, St = l[2] | 0, ie = St & 8191, ne = St >>> 13, Et2 = l[3] | 0, fe = Et2 & 8191, ae2 = Et2 >>> 13, At2 = l[4] | 0, oe = At2 & 8191, se2 = At2 >>> 13, Rt = l[5] | 0, he = Rt & 8191, ue2 = Rt >>> 13, Bt = l[6] | 0, le = Bt & 8191, de = Bt >>> 13, qt = l[7] | 0, ce2 = qt & 8191, pe2 = qt >>> 13, It = l[8] | 0, ve = It & 8191, be = It >>> 13, ft = l[9] | 0, Be = ft & 8191, qe = ft >>> 13; + c.negative = s.negative ^ u.negative, c.length = 19, w = Math.imul(R, Q), g = Math.imul(R, ee), g = g + Math.imul(I2, Q) | 0, _9 = Math.imul(I2, ee); + var ze = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (ze >>> 26) | 0, ze &= 67108863, w = Math.imul(k2, Q), g = Math.imul(k2, ee), g = g + Math.imul(D, Q) | 0, _9 = Math.imul(D, ee), w = w + Math.imul(R, te2) | 0, g = g + Math.imul(R, re) | 0, g = g + Math.imul(I2, te2) | 0, _9 = _9 + Math.imul(I2, re) | 0; + var He2 = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (He2 >>> 26) | 0, He2 &= 67108863, w = Math.imul(C2, Q), g = Math.imul(C2, ee), g = g + Math.imul(O, Q) | 0, _9 = Math.imul(O, ee), w = w + Math.imul(k2, te2) | 0, g = g + Math.imul(k2, re) | 0, g = g + Math.imul(D, te2) | 0, _9 = _9 + Math.imul(D, re) | 0, w = w + Math.imul(R, ie) | 0, g = g + Math.imul(R, ne) | 0, g = g + Math.imul(I2, ie) | 0, _9 = _9 + Math.imul(I2, ne) | 0; + var We = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (We >>> 26) | 0, We &= 67108863, w = Math.imul(F, Q), g = Math.imul(F, ee), g = g + Math.imul(U, Q) | 0, _9 = Math.imul(U, ee), w = w + Math.imul(C2, te2) | 0, g = g + Math.imul(C2, re) | 0, g = g + Math.imul(O, te2) | 0, _9 = _9 + Math.imul(O, re) | 0, w = w + Math.imul(k2, ie) | 0, g = g + Math.imul(k2, ne) | 0, g = g + Math.imul(D, ie) | 0, _9 = _9 + Math.imul(D, ne) | 0, w = w + Math.imul(R, fe) | 0, g = g + Math.imul(R, ae2) | 0, g = g + Math.imul(I2, fe) | 0, _9 = _9 + Math.imul(I2, ae2) | 0; + var Ke2 = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (Ke2 >>> 26) | 0, Ke2 &= 67108863, w = Math.imul(z, Q), g = Math.imul(z, ee), g = g + Math.imul(H, Q) | 0, _9 = Math.imul(H, ee), w = w + Math.imul(F, te2) | 0, g = g + Math.imul(F, re) | 0, g = g + Math.imul(U, te2) | 0, _9 = _9 + Math.imul(U, re) | 0, w = w + Math.imul(C2, ie) | 0, g = g + Math.imul(C2, ne) | 0, g = g + Math.imul(O, ie) | 0, _9 = _9 + Math.imul(O, ne) | 0, w = w + Math.imul(k2, fe) | 0, g = g + Math.imul(k2, ae2) | 0, g = g + Math.imul(D, fe) | 0, _9 = _9 + Math.imul(D, ae2) | 0, w = w + Math.imul(R, oe) | 0, g = g + Math.imul(R, se2) | 0, g = g + Math.imul(I2, oe) | 0, _9 = _9 + Math.imul(I2, se2) | 0; + var je = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (je >>> 26) | 0, je &= 67108863, w = Math.imul(W, Q), g = Math.imul(W, ee), g = g + Math.imul(K, Q) | 0, _9 = Math.imul(K, ee), w = w + Math.imul(z, te2) | 0, g = g + Math.imul(z, re) | 0, g = g + Math.imul(H, te2) | 0, _9 = _9 + Math.imul(H, re) | 0, w = w + Math.imul(F, ie) | 0, g = g + Math.imul(F, ne) | 0, g = g + Math.imul(U, ie) | 0, _9 = _9 + Math.imul(U, ne) | 0, w = w + Math.imul(C2, fe) | 0, g = g + Math.imul(C2, ae2) | 0, g = g + Math.imul(O, fe) | 0, _9 = _9 + Math.imul(O, ae2) | 0, w = w + Math.imul(k2, oe) | 0, g = g + Math.imul(k2, se2) | 0, g = g + Math.imul(D, oe) | 0, _9 = _9 + Math.imul(D, se2) | 0, w = w + Math.imul(R, he) | 0, g = g + Math.imul(R, ue2) | 0, g = g + Math.imul(I2, he) | 0, _9 = _9 + Math.imul(I2, ue2) | 0; + var Ze2 = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (Ze2 >>> 26) | 0, Ze2 &= 67108863, w = Math.imul(j, Q), g = Math.imul(j, ee), g = g + Math.imul(Z, Q) | 0, _9 = Math.imul(Z, ee), w = w + Math.imul(W, te2) | 0, g = g + Math.imul(W, re) | 0, g = g + Math.imul(K, te2) | 0, _9 = _9 + Math.imul(K, re) | 0, w = w + Math.imul(z, ie) | 0, g = g + Math.imul(z, ne) | 0, g = g + Math.imul(H, ie) | 0, _9 = _9 + Math.imul(H, ne) | 0, w = w + Math.imul(F, fe) | 0, g = g + Math.imul(F, ae2) | 0, g = g + Math.imul(U, fe) | 0, _9 = _9 + Math.imul(U, ae2) | 0, w = w + Math.imul(C2, oe) | 0, g = g + Math.imul(C2, se2) | 0, g = g + Math.imul(O, oe) | 0, _9 = _9 + Math.imul(O, se2) | 0, w = w + Math.imul(k2, he) | 0, g = g + Math.imul(k2, ue2) | 0, g = g + Math.imul(D, he) | 0, _9 = _9 + Math.imul(D, ue2) | 0, w = w + Math.imul(R, le) | 0, g = g + Math.imul(R, de) | 0, g = g + Math.imul(I2, le) | 0, _9 = _9 + Math.imul(I2, de) | 0; + var Ve = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (Ve >>> 26) | 0, Ve &= 67108863, w = Math.imul(V2, Q), g = Math.imul(V2, ee), g = g + Math.imul($, Q) | 0, _9 = Math.imul($, ee), w = w + Math.imul(j, te2) | 0, g = g + Math.imul(j, re) | 0, g = g + Math.imul(Z, te2) | 0, _9 = _9 + Math.imul(Z, re) | 0, w = w + Math.imul(W, ie) | 0, g = g + Math.imul(W, ne) | 0, g = g + Math.imul(K, ie) | 0, _9 = _9 + Math.imul(K, ne) | 0, w = w + Math.imul(z, fe) | 0, g = g + Math.imul(z, ae2) | 0, g = g + Math.imul(H, fe) | 0, _9 = _9 + Math.imul(H, ae2) | 0, w = w + Math.imul(F, oe) | 0, g = g + Math.imul(F, se2) | 0, g = g + Math.imul(U, oe) | 0, _9 = _9 + Math.imul(U, se2) | 0, w = w + Math.imul(C2, he) | 0, g = g + Math.imul(C2, ue2) | 0, g = g + Math.imul(O, he) | 0, _9 = _9 + Math.imul(O, ue2) | 0, w = w + Math.imul(k2, le) | 0, g = g + Math.imul(k2, de) | 0, g = g + Math.imul(D, le) | 0, _9 = _9 + Math.imul(D, de) | 0, w = w + Math.imul(R, ce2) | 0, g = g + Math.imul(R, pe2) | 0, g = g + Math.imul(I2, ce2) | 0, _9 = _9 + Math.imul(I2, pe2) | 0; + var $e = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + ($e >>> 26) | 0, $e &= 67108863, w = Math.imul(G, Q), g = Math.imul(G, ee), g = g + Math.imul(Y, Q) | 0, _9 = Math.imul(Y, ee), w = w + Math.imul(V2, te2) | 0, g = g + Math.imul(V2, re) | 0, g = g + Math.imul($, te2) | 0, _9 = _9 + Math.imul($, re) | 0, w = w + Math.imul(j, ie) | 0, g = g + Math.imul(j, ne) | 0, g = g + Math.imul(Z, ie) | 0, _9 = _9 + Math.imul(Z, ne) | 0, w = w + Math.imul(W, fe) | 0, g = g + Math.imul(W, ae2) | 0, g = g + Math.imul(K, fe) | 0, _9 = _9 + Math.imul(K, ae2) | 0, w = w + Math.imul(z, oe) | 0, g = g + Math.imul(z, se2) | 0, g = g + Math.imul(H, oe) | 0, _9 = _9 + Math.imul(H, se2) | 0, w = w + Math.imul(F, he) | 0, g = g + Math.imul(F, ue2) | 0, g = g + Math.imul(U, he) | 0, _9 = _9 + Math.imul(U, ue2) | 0, w = w + Math.imul(C2, le) | 0, g = g + Math.imul(C2, de) | 0, g = g + Math.imul(O, le) | 0, _9 = _9 + Math.imul(O, de) | 0, w = w + Math.imul(k2, ce2) | 0, g = g + Math.imul(k2, pe2) | 0, g = g + Math.imul(D, ce2) | 0, _9 = _9 + Math.imul(D, pe2) | 0, w = w + Math.imul(R, ve) | 0, g = g + Math.imul(R, be) | 0, g = g + Math.imul(I2, ve) | 0, _9 = _9 + Math.imul(I2, be) | 0; + var Ge = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (Ge >>> 26) | 0, Ge &= 67108863, w = Math.imul(X, Q), g = Math.imul(X, ee), g = g + Math.imul(J2, Q) | 0, _9 = Math.imul(J2, ee), w = w + Math.imul(G, te2) | 0, g = g + Math.imul(G, re) | 0, g = g + Math.imul(Y, te2) | 0, _9 = _9 + Math.imul(Y, re) | 0, w = w + Math.imul(V2, ie) | 0, g = g + Math.imul(V2, ne) | 0, g = g + Math.imul($, ie) | 0, _9 = _9 + Math.imul($, ne) | 0, w = w + Math.imul(j, fe) | 0, g = g + Math.imul(j, ae2) | 0, g = g + Math.imul(Z, fe) | 0, _9 = _9 + Math.imul(Z, ae2) | 0, w = w + Math.imul(W, oe) | 0, g = g + Math.imul(W, se2) | 0, g = g + Math.imul(K, oe) | 0, _9 = _9 + Math.imul(K, se2) | 0, w = w + Math.imul(z, he) | 0, g = g + Math.imul(z, ue2) | 0, g = g + Math.imul(H, he) | 0, _9 = _9 + Math.imul(H, ue2) | 0, w = w + Math.imul(F, le) | 0, g = g + Math.imul(F, de) | 0, g = g + Math.imul(U, le) | 0, _9 = _9 + Math.imul(U, de) | 0, w = w + Math.imul(C2, ce2) | 0, g = g + Math.imul(C2, pe2) | 0, g = g + Math.imul(O, ce2) | 0, _9 = _9 + Math.imul(O, pe2) | 0, w = w + Math.imul(k2, ve) | 0, g = g + Math.imul(k2, be) | 0, g = g + Math.imul(D, ve) | 0, _9 = _9 + Math.imul(D, be) | 0, w = w + Math.imul(R, Be) | 0, g = g + Math.imul(R, qe) | 0, g = g + Math.imul(I2, Be) | 0, _9 = _9 + Math.imul(I2, qe) | 0; + var Ye = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (Ye >>> 26) | 0, Ye &= 67108863, w = Math.imul(X, te2), g = Math.imul(X, re), g = g + Math.imul(J2, te2) | 0, _9 = Math.imul(J2, re), w = w + Math.imul(G, ie) | 0, g = g + Math.imul(G, ne) | 0, g = g + Math.imul(Y, ie) | 0, _9 = _9 + Math.imul(Y, ne) | 0, w = w + Math.imul(V2, fe) | 0, g = g + Math.imul(V2, ae2) | 0, g = g + Math.imul($, fe) | 0, _9 = _9 + Math.imul($, ae2) | 0, w = w + Math.imul(j, oe) | 0, g = g + Math.imul(j, se2) | 0, g = g + Math.imul(Z, oe) | 0, _9 = _9 + Math.imul(Z, se2) | 0, w = w + Math.imul(W, he) | 0, g = g + Math.imul(W, ue2) | 0, g = g + Math.imul(K, he) | 0, _9 = _9 + Math.imul(K, ue2) | 0, w = w + Math.imul(z, le) | 0, g = g + Math.imul(z, de) | 0, g = g + Math.imul(H, le) | 0, _9 = _9 + Math.imul(H, de) | 0, w = w + Math.imul(F, ce2) | 0, g = g + Math.imul(F, pe2) | 0, g = g + Math.imul(U, ce2) | 0, _9 = _9 + Math.imul(U, pe2) | 0, w = w + Math.imul(C2, ve) | 0, g = g + Math.imul(C2, be) | 0, g = g + Math.imul(O, ve) | 0, _9 = _9 + Math.imul(O, be) | 0, w = w + Math.imul(k2, Be) | 0, g = g + Math.imul(k2, qe) | 0, g = g + Math.imul(D, Be) | 0, _9 = _9 + Math.imul(D, qe) | 0; + var Xe = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (Xe >>> 26) | 0, Xe &= 67108863, w = Math.imul(X, ie), g = Math.imul(X, ne), g = g + Math.imul(J2, ie) | 0, _9 = Math.imul(J2, ne), w = w + Math.imul(G, fe) | 0, g = g + Math.imul(G, ae2) | 0, g = g + Math.imul(Y, fe) | 0, _9 = _9 + Math.imul(Y, ae2) | 0, w = w + Math.imul(V2, oe) | 0, g = g + Math.imul(V2, se2) | 0, g = g + Math.imul($, oe) | 0, _9 = _9 + Math.imul($, se2) | 0, w = w + Math.imul(j, he) | 0, g = g + Math.imul(j, ue2) | 0, g = g + Math.imul(Z, he) | 0, _9 = _9 + Math.imul(Z, ue2) | 0, w = w + Math.imul(W, le) | 0, g = g + Math.imul(W, de) | 0, g = g + Math.imul(K, le) | 0, _9 = _9 + Math.imul(K, de) | 0, w = w + Math.imul(z, ce2) | 0, g = g + Math.imul(z, pe2) | 0, g = g + Math.imul(H, ce2) | 0, _9 = _9 + Math.imul(H, pe2) | 0, w = w + Math.imul(F, ve) | 0, g = g + Math.imul(F, be) | 0, g = g + Math.imul(U, ve) | 0, _9 = _9 + Math.imul(U, be) | 0, w = w + Math.imul(C2, Be) | 0, g = g + Math.imul(C2, qe) | 0, g = g + Math.imul(O, Be) | 0, _9 = _9 + Math.imul(O, qe) | 0; + var Je = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (Je >>> 26) | 0, Je &= 67108863, w = Math.imul(X, fe), g = Math.imul(X, ae2), g = g + Math.imul(J2, fe) | 0, _9 = Math.imul(J2, ae2), w = w + Math.imul(G, oe) | 0, g = g + Math.imul(G, se2) | 0, g = g + Math.imul(Y, oe) | 0, _9 = _9 + Math.imul(Y, se2) | 0, w = w + Math.imul(V2, he) | 0, g = g + Math.imul(V2, ue2) | 0, g = g + Math.imul($, he) | 0, _9 = _9 + Math.imul($, ue2) | 0, w = w + Math.imul(j, le) | 0, g = g + Math.imul(j, de) | 0, g = g + Math.imul(Z, le) | 0, _9 = _9 + Math.imul(Z, de) | 0, w = w + Math.imul(W, ce2) | 0, g = g + Math.imul(W, pe2) | 0, g = g + Math.imul(K, ce2) | 0, _9 = _9 + Math.imul(K, pe2) | 0, w = w + Math.imul(z, ve) | 0, g = g + Math.imul(z, be) | 0, g = g + Math.imul(H, ve) | 0, _9 = _9 + Math.imul(H, be) | 0, w = w + Math.imul(F, Be) | 0, g = g + Math.imul(F, qe) | 0, g = g + Math.imul(U, Be) | 0, _9 = _9 + Math.imul(U, qe) | 0; + var Qe = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (Qe >>> 26) | 0, Qe &= 67108863, w = Math.imul(X, oe), g = Math.imul(X, se2), g = g + Math.imul(J2, oe) | 0, _9 = Math.imul(J2, se2), w = w + Math.imul(G, he) | 0, g = g + Math.imul(G, ue2) | 0, g = g + Math.imul(Y, he) | 0, _9 = _9 + Math.imul(Y, ue2) | 0, w = w + Math.imul(V2, le) | 0, g = g + Math.imul(V2, de) | 0, g = g + Math.imul($, le) | 0, _9 = _9 + Math.imul($, de) | 0, w = w + Math.imul(j, ce2) | 0, g = g + Math.imul(j, pe2) | 0, g = g + Math.imul(Z, ce2) | 0, _9 = _9 + Math.imul(Z, pe2) | 0, w = w + Math.imul(W, ve) | 0, g = g + Math.imul(W, be) | 0, g = g + Math.imul(K, ve) | 0, _9 = _9 + Math.imul(K, be) | 0, w = w + Math.imul(z, Be) | 0, g = g + Math.imul(z, qe) | 0, g = g + Math.imul(H, Be) | 0, _9 = _9 + Math.imul(H, qe) | 0; + var et2 = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (et2 >>> 26) | 0, et2 &= 67108863, w = Math.imul(X, he), g = Math.imul(X, ue2), g = g + Math.imul(J2, he) | 0, _9 = Math.imul(J2, ue2), w = w + Math.imul(G, le) | 0, g = g + Math.imul(G, de) | 0, g = g + Math.imul(Y, le) | 0, _9 = _9 + Math.imul(Y, de) | 0, w = w + Math.imul(V2, ce2) | 0, g = g + Math.imul(V2, pe2) | 0, g = g + Math.imul($, ce2) | 0, _9 = _9 + Math.imul($, pe2) | 0, w = w + Math.imul(j, ve) | 0, g = g + Math.imul(j, be) | 0, g = g + Math.imul(Z, ve) | 0, _9 = _9 + Math.imul(Z, be) | 0, w = w + Math.imul(W, Be) | 0, g = g + Math.imul(W, qe) | 0, g = g + Math.imul(K, Be) | 0, _9 = _9 + Math.imul(K, qe) | 0; + var tt2 = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (tt2 >>> 26) | 0, tt2 &= 67108863, w = Math.imul(X, le), g = Math.imul(X, de), g = g + Math.imul(J2, le) | 0, _9 = Math.imul(J2, de), w = w + Math.imul(G, ce2) | 0, g = g + Math.imul(G, pe2) | 0, g = g + Math.imul(Y, ce2) | 0, _9 = _9 + Math.imul(Y, pe2) | 0, w = w + Math.imul(V2, ve) | 0, g = g + Math.imul(V2, be) | 0, g = g + Math.imul($, ve) | 0, _9 = _9 + Math.imul($, be) | 0, w = w + Math.imul(j, Be) | 0, g = g + Math.imul(j, qe) | 0, g = g + Math.imul(Z, Be) | 0, _9 = _9 + Math.imul(Z, qe) | 0; + var rt2 = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (rt2 >>> 26) | 0, rt2 &= 67108863, w = Math.imul(X, ce2), g = Math.imul(X, pe2), g = g + Math.imul(J2, ce2) | 0, _9 = Math.imul(J2, pe2), w = w + Math.imul(G, ve) | 0, g = g + Math.imul(G, be) | 0, g = g + Math.imul(Y, ve) | 0, _9 = _9 + Math.imul(Y, be) | 0, w = w + Math.imul(V2, Be) | 0, g = g + Math.imul(V2, qe) | 0, g = g + Math.imul($, Be) | 0, _9 = _9 + Math.imul($, qe) | 0; + var S0 = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (S0 >>> 26) | 0, S0 &= 67108863, w = Math.imul(X, ve), g = Math.imul(X, be), g = g + Math.imul(J2, ve) | 0, _9 = Math.imul(J2, be), w = w + Math.imul(G, Be) | 0, g = g + Math.imul(G, qe) | 0, g = g + Math.imul(Y, Be) | 0, _9 = _9 + Math.imul(Y, qe) | 0; + var E0 = (d + w | 0) + ((g & 8191) << 13) | 0; + d = (_9 + (g >>> 13) | 0) + (E0 >>> 26) | 0, E0 &= 67108863, w = Math.imul(X, Be), g = Math.imul(X, qe), g = g + Math.imul(J2, Be) | 0, _9 = Math.imul(J2, qe); + var A0 = (d + w | 0) + ((g & 8191) << 13) | 0; + return d = (_9 + (g >>> 13) | 0) + (A0 >>> 26) | 0, A0 &= 67108863, n[0] = ze, n[1] = He2, n[2] = We, n[3] = Ke2, n[4] = je, n[5] = Ze2, n[6] = Ve, n[7] = $e, n[8] = Ge, n[9] = Ye, n[10] = Xe, n[11] = Je, n[12] = Qe, n[13] = et2, n[14] = tt2, n[15] = rt2, n[16] = S0, n[17] = E0, n[18] = A0, d !== 0 && (n[19] = d, c.length++), c; + }; + Math.imul || (N = _e); + function we(h, s, u) { + u.negative = s.negative ^ h.negative, u.length = h.length + s.length; + for (var c = 0, b = 0, l = 0;l < u.length - 1; l++) { + var n = b; + b = 0; + for (var d = c & 67108863, w = Math.min(l, s.length - 1), g = Math.max(0, l - h.length + 1);g <= w; g++) { + var _9 = l - g, A = h.words[_9] | 0, R = s.words[g] | 0, I2 = A * R, Me = I2 & 67108863; + n = n + (I2 / 67108864 | 0) | 0, Me = Me + d | 0, d = Me & 67108863, n = n + (Me >>> 26) | 0, b += n >>> 26, n &= 67108863; + } + u.words[l] = d, c = n, n = b; + } + return c !== 0 ? u.words[l] = c : u.length--, u._strip(); + } + function ye(h, s, u) { + return we(h, s, u); + } + f.prototype.mulTo = function(s, u) { + var c, b = this.length + s.length; + return this.length === 10 && s.length === 10 ? c = N(this, s, u) : b < 63 ? c = _e(this, s, u) : b < 1024 ? c = we(this, s, u) : c = ye(this, s, u), c; + }; + function xe(h, s) { + this.x = h, this.y = s; + } + xe.prototype.makeRBT = function(s) { + for (var u = new Array(s), c = f.prototype._countBits(s) - 1, b = 0;b < s; b++) + u[b] = this.revBin(b, c, s); + return u; + }, xe.prototype.revBin = function(s, u, c) { + if (s === 0 || s === c - 1) + return s; + for (var b = 0, l = 0;l < u; l++) + b |= (s & 1) << u - l - 1, s >>= 1; + return b; + }, xe.prototype.permute = function(s, u, c, b, l, n) { + for (var d = 0;d < n; d++) + b[d] = u[s[d]], l[d] = c[s[d]]; + }, xe.prototype.transform = function(s, u, c, b, l, n) { + this.permute(n, s, u, c, b, l); + for (var d = 1;d < l; d <<= 1) + for (var w = d << 1, g = Math.cos(2 * Math.PI / w), _9 = Math.sin(2 * Math.PI / w), A = 0;A < l; A += w) + for (var R = g, I2 = _9, Me = 0;Me < d; Me++) { + var k2 = c[A + Me], D = b[A + Me], nt = c[A + Me + d], C2 = b[A + Me + d], O = R * nt - I2 * C2; + C2 = R * C2 + I2 * nt, nt = O, c[A + Me] = k2 + nt, b[A + Me] = D + C2, c[A + Me + d] = k2 - nt, b[A + Me + d] = D - C2, Me !== w && (O = g * R - _9 * I2, I2 = g * I2 + _9 * R, R = O); + } + }, xe.prototype.guessLen13b = function(s, u) { + var c = Math.max(u, s) | 1, b = c & 1, l = 0; + for (c = c / 2 | 0;c; c = c >>> 1) + l++; + return 1 << l + 1 + b; + }, xe.prototype.conjugate = function(s, u, c) { + if (!(c <= 1)) + for (var b = 0;b < c / 2; b++) { + var l = s[b]; + s[b] = s[c - b - 1], s[c - b - 1] = l, l = u[b], u[b] = -u[c - b - 1], u[c - b - 1] = -l; + } + }, xe.prototype.normalize13b = function(s, u) { + for (var c = 0, b = 0;b < u / 2; b++) { + var l = Math.round(s[2 * b + 1] / u) * 8192 + Math.round(s[2 * b] / u) + c; + s[b] = l & 67108863, l < 67108864 ? c = 0 : c = l / 67108864 | 0; + } + return s; + }, xe.prototype.convert13b = function(s, u, c, b) { + for (var l = 0, n = 0;n < u; n++) + l = l + (s[n] | 0), c[2 * n] = l & 8191, l = l >>> 13, c[2 * n + 1] = l & 8191, l = l >>> 13; + for (n = 2 * u;n < b; ++n) + c[n] = 0; + r(l === 0), r((l & -8192) === 0); + }, xe.prototype.stub = function(s) { + for (var u = new Array(s), c = 0;c < s; c++) + u[c] = 0; + return u; + }, xe.prototype.mulp = function(s, u, c) { + var b = 2 * this.guessLen13b(s.length, u.length), l = this.makeRBT(b), n = this.stub(b), d = new Array(b), w = new Array(b), g = new Array(b), _9 = new Array(b), A = new Array(b), R = new Array(b), I2 = c.words; + I2.length = b, this.convert13b(s.words, s.length, d, b), this.convert13b(u.words, u.length, _9, b), this.transform(d, n, w, g, b, l), this.transform(_9, n, A, R, b, l); + for (var Me = 0;Me < b; Me++) { + var k2 = w[Me] * A[Me] - g[Me] * R[Me]; + g[Me] = w[Me] * R[Me] + g[Me] * A[Me], w[Me] = k2; + } + return this.conjugate(w, g, b), this.transform(w, g, I2, n, b, l), this.conjugate(I2, n, b), this.normalize13b(I2, b), c.negative = s.negative ^ u.negative, c.length = s.length + u.length, c._strip(); + }, f.prototype.mul = function(s) { + var u = new f(null); + return u.words = new Array(this.length + s.length), this.mulTo(s, u); + }, f.prototype.mulf = function(s) { + var u = new f(null); + return u.words = new Array(this.length + s.length), ye(this, s, u); + }, f.prototype.imul = function(s) { + return this.clone().mulTo(s, this); + }, f.prototype.imuln = function(s) { + var u = s < 0; + u && (s = -s), r(typeof s == "number"), r(s < 67108864); + for (var c = 0, b = 0;b < this.length; b++) { + var l = (this.words[b] | 0) * s, n = (l & 67108863) + (c & 67108863); + c >>= 26, c += l / 67108864 | 0, c += n >>> 26, this.words[b] = n & 67108863; + } + return c !== 0 && (this.words[b] = c, this.length++), u ? this.ineg() : this; + }, f.prototype.muln = function(s) { + return this.clone().imuln(s); + }, f.prototype.sqr = function() { + return this.mul(this); + }, f.prototype.isqr = function() { + return this.imul(this.clone()); + }, f.prototype.pow = function(s) { + var u = ge(s); + if (u.length === 0) + return new f(1); + for (var c = this, b = 0;b < u.length && u[b] === 0; b++, c = c.sqr()) + ; + if (++b < u.length) + for (var l = c.sqr();b < u.length; b++, l = l.sqr()) + u[b] !== 0 && (c = c.mul(l)); + return c; + }, f.prototype.iushln = function(s) { + r(typeof s == "number" && s >= 0); + var u = s % 26, c = (s - u) / 26, b = 67108863 >>> 26 - u << 26 - u, l; + if (u !== 0) { + var n = 0; + for (l = 0;l < this.length; l++) { + var d = this.words[l] & b, w = (this.words[l] | 0) - d << u; + this.words[l] = w | n, n = d >>> 26 - u; + } + n && (this.words[l] = n, this.length++); + } + if (c !== 0) { + for (l = this.length - 1;l >= 0; l--) + this.words[l + c] = this.words[l]; + for (l = 0;l < c; l++) + this.words[l] = 0; + this.length += c; + } + return this._strip(); + }, f.prototype.ishln = function(s) { + return r(this.negative === 0), this.iushln(s); + }, f.prototype.iushrn = function(s, u, c) { + r(typeof s == "number" && s >= 0); + var b; + u ? b = (u - u % 26) / 26 : b = 0; + var l = s % 26, n = Math.min((s - l) / 26, this.length), d = 67108863 ^ 67108863 >>> l << l, w = c; + if (b -= n, b = Math.max(0, b), w) { + for (var g = 0;g < n; g++) + w.words[g] = this.words[g]; + w.length = n; + } + if (n !== 0) + if (this.length > n) + for (this.length -= n, g = 0;g < this.length; g++) + this.words[g] = this.words[g + n]; + else + this.words[0] = 0, this.length = 1; + var _9 = 0; + for (g = this.length - 1;g >= 0 && (_9 !== 0 || g >= b); g--) { + var A = this.words[g] | 0; + this.words[g] = _9 << 26 - l | A >>> l, _9 = A & d; + } + return w && _9 !== 0 && (w.words[w.length++] = _9), this.length === 0 && (this.words[0] = 0, this.length = 1), this._strip(); + }, f.prototype.ishrn = function(s, u, c) { + return r(this.negative === 0), this.iushrn(s, u, c); + }, f.prototype.shln = function(s) { + return this.clone().ishln(s); + }, f.prototype.ushln = function(s) { + return this.clone().iushln(s); + }, f.prototype.shrn = function(s) { + return this.clone().ishrn(s); + }, f.prototype.ushrn = function(s) { + return this.clone().iushrn(s); + }, f.prototype.testn = function(s) { + r(typeof s == "number" && s >= 0); + var u = s % 26, c = (s - u) / 26, b = 1 << u; + if (this.length <= c) + return false; + var l = this.words[c]; + return !!(l & b); + }, f.prototype.imaskn = function(s) { + r(typeof s == "number" && s >= 0); + var u = s % 26, c = (s - u) / 26; + if (r(this.negative === 0, "imaskn works only with positive numbers"), this.length <= c) + return this; + if (u !== 0 && c++, this.length = Math.min(c, this.length), u !== 0) { + var b = 67108863 ^ 67108863 >>> u << u; + this.words[this.length - 1] &= b; + } + return this._strip(); + }, f.prototype.maskn = function(s) { + return this.clone().imaskn(s); + }, f.prototype.iaddn = function(s) { + return r(typeof s == "number"), r(s < 67108864), s < 0 ? this.isubn(-s) : this.negative !== 0 ? this.length === 1 && (this.words[0] | 0) <= s ? (this.words[0] = s - (this.words[0] | 0), this.negative = 0, this) : (this.negative = 0, this.isubn(s), this.negative = 1, this) : this._iaddn(s); + }, f.prototype._iaddn = function(s) { + this.words[0] += s; + for (var u = 0;u < this.length && this.words[u] >= 67108864; u++) + this.words[u] -= 67108864, u === this.length - 1 ? this.words[u + 1] = 1 : this.words[u + 1]++; + return this.length = Math.max(this.length, u + 1), this; + }, f.prototype.isubn = function(s) { + if (r(typeof s == "number"), r(s < 67108864), s < 0) + return this.iaddn(-s); + if (this.negative !== 0) + return this.negative = 0, this.iaddn(s), this.negative = 1, this; + if (this.words[0] -= s, this.length === 1 && this.words[0] < 0) + this.words[0] = -this.words[0], this.negative = 1; + else + for (var u = 0;u < this.length && this.words[u] < 0; u++) + this.words[u] += 67108864, this.words[u + 1] -= 1; + return this._strip(); + }, f.prototype.addn = function(s) { + return this.clone().iaddn(s); + }, f.prototype.subn = function(s) { + return this.clone().isubn(s); + }, f.prototype.iabs = function() { + return this.negative = 0, this; + }, f.prototype.abs = function() { + return this.clone().iabs(); + }, f.prototype._ishlnsubmul = function(s, u, c) { + var b = s.length + c, l; + this._expand(b); + var n, d = 0; + for (l = 0;l < s.length; l++) { + n = (this.words[l + c] | 0) + d; + var w = (s.words[l] | 0) * u; + n -= w & 67108863, d = (n >> 26) - (w / 67108864 | 0), this.words[l + c] = n & 67108863; + } + for (;l < this.length - c; l++) + n = (this.words[l + c] | 0) + d, d = n >> 26, this.words[l + c] = n & 67108863; + if (d === 0) + return this._strip(); + for (r(d === -1), d = 0, l = 0;l < this.length; l++) + n = -(this.words[l] | 0) + d, d = n >> 26, this.words[l] = n & 67108863; + return this.negative = 1, this._strip(); + }, f.prototype._wordDiv = function(s, u) { + var c = this.length - s.length, b = this.clone(), l = s, n = l.words[l.length - 1] | 0, d = this._countBits(n); + c = 26 - d, c !== 0 && (l = l.ushln(c), b.iushln(c), n = l.words[l.length - 1] | 0); + var w = b.length - l.length, g; + if (u !== "mod") { + g = new f(null), g.length = w + 1, g.words = new Array(g.length); + for (var _9 = 0;_9 < g.length; _9++) + g.words[_9] = 0; + } + var A = b.clone()._ishlnsubmul(l, 1, w); + A.negative === 0 && (b = A, g && (g.words[w] = 1)); + for (var R = w - 1;R >= 0; R--) { + var I2 = (b.words[l.length + R] | 0) * 67108864 + (b.words[l.length + R - 1] | 0); + for (I2 = Math.min(I2 / n | 0, 67108863), b._ishlnsubmul(l, I2, R);b.negative !== 0; ) + I2--, b.negative = 0, b._ishlnsubmul(l, 1, R), b.isZero() || (b.negative ^= 1); + g && (g.words[R] = I2); + } + return g && g._strip(), b._strip(), u !== "div" && c !== 0 && b.iushrn(c), { div: g || null, mod: b }; + }, f.prototype.divmod = function(s, u, c) { + if (r(!s.isZero()), this.isZero()) + return { div: new f(0), mod: new f(0) }; + var b, l, n; + return this.negative !== 0 && s.negative === 0 ? (n = this.neg().divmod(s, u), u !== "mod" && (b = n.div.neg()), u !== "div" && (l = n.mod.neg(), c && l.negative !== 0 && l.iadd(s)), { div: b, mod: l }) : this.negative === 0 && s.negative !== 0 ? (n = this.divmod(s.neg(), u), u !== "mod" && (b = n.div.neg()), { div: b, mod: n.mod }) : (this.negative & s.negative) !== 0 ? (n = this.neg().divmod(s.neg(), u), u !== "div" && (l = n.mod.neg(), c && l.negative !== 0 && l.isub(s)), { div: n.div, mod: l }) : s.length > this.length || this.cmp(s) < 0 ? { div: new f(0), mod: this } : s.length === 1 ? u === "div" ? { div: this.divn(s.words[0]), mod: null } : u === "mod" ? { div: null, mod: new f(this.modrn(s.words[0])) } : { div: this.divn(s.words[0]), mod: new f(this.modrn(s.words[0])) } : this._wordDiv(s, u); + }, f.prototype.div = function(s) { + return this.divmod(s, "div", false).div; + }, f.prototype.mod = function(s) { + return this.divmod(s, "mod", false).mod; + }, f.prototype.umod = function(s) { + return this.divmod(s, "mod", true).mod; + }, f.prototype.divRound = function(s) { + var u = this.divmod(s); + if (u.mod.isZero()) + return u.div; + var c = u.div.negative !== 0 ? u.mod.isub(s) : u.mod, b = s.ushrn(1), l = s.andln(1), n = c.cmp(b); + return n < 0 || l === 1 && n === 0 ? u.div : u.div.negative !== 0 ? u.div.isubn(1) : u.div.iaddn(1); + }, f.prototype.modrn = function(s) { + var u = s < 0; + u && (s = -s), r(s <= 67108863); + for (var c = (1 << 26) % s, b = 0, l = this.length - 1;l >= 0; l--) + b = (c * b + (this.words[l] | 0)) % s; + return u ? -b : b; + }, f.prototype.modn = function(s) { + return this.modrn(s); + }, f.prototype.idivn = function(s) { + var u = s < 0; + u && (s = -s), r(s <= 67108863); + for (var c = 0, b = this.length - 1;b >= 0; b--) { + var l = (this.words[b] | 0) + c * 67108864; + this.words[b] = l / s | 0, c = l % s; + } + return this._strip(), u ? this.ineg() : this; + }, f.prototype.divn = function(s) { + return this.clone().idivn(s); + }, f.prototype.egcd = function(s) { + r(s.negative === 0), r(!s.isZero()); + var u = this, c = s.clone(); + u.negative !== 0 ? u = u.umod(s) : u = u.clone(); + for (var b = new f(1), l = new f(0), n = new f(0), d = new f(1), w = 0;u.isEven() && c.isEven(); ) + u.iushrn(1), c.iushrn(1), ++w; + for (var g = c.clone(), _9 = u.clone();!u.isZero(); ) { + for (var A = 0, R = 1;(u.words[0] & R) === 0 && A < 26; ++A, R <<= 1) + ; + if (A > 0) + for (u.iushrn(A);A-- > 0; ) + (b.isOdd() || l.isOdd()) && (b.iadd(g), l.isub(_9)), b.iushrn(1), l.iushrn(1); + for (var I2 = 0, Me = 1;(c.words[0] & Me) === 0 && I2 < 26; ++I2, Me <<= 1) + ; + if (I2 > 0) + for (c.iushrn(I2);I2-- > 0; ) + (n.isOdd() || d.isOdd()) && (n.iadd(g), d.isub(_9)), n.iushrn(1), d.iushrn(1); + u.cmp(c) >= 0 ? (u.isub(c), b.isub(n), l.isub(d)) : (c.isub(u), n.isub(b), d.isub(l)); + } + return { a: n, b: d, gcd: c.iushln(w) }; + }, f.prototype._invmp = function(s) { + r(s.negative === 0), r(!s.isZero()); + var u = this, c = s.clone(); + u.negative !== 0 ? u = u.umod(s) : u = u.clone(); + for (var b = new f(1), l = new f(0), n = c.clone();u.cmpn(1) > 0 && c.cmpn(1) > 0; ) { + for (var d = 0, w = 1;(u.words[0] & w) === 0 && d < 26; ++d, w <<= 1) + ; + if (d > 0) + for (u.iushrn(d);d-- > 0; ) + b.isOdd() && b.iadd(n), b.iushrn(1); + for (var g = 0, _9 = 1;(c.words[0] & _9) === 0 && g < 26; ++g, _9 <<= 1) + ; + if (g > 0) + for (c.iushrn(g);g-- > 0; ) + l.isOdd() && l.iadd(n), l.iushrn(1); + u.cmp(c) >= 0 ? (u.isub(c), b.isub(l)) : (c.isub(u), l.isub(b)); + } + var A; + return u.cmpn(1) === 0 ? A = b : A = l, A.cmpn(0) < 0 && A.iadd(s), A; + }, f.prototype.gcd = function(s) { + if (this.isZero()) + return s.abs(); + if (s.isZero()) + return this.abs(); + var u = this.clone(), c = s.clone(); + u.negative = 0, c.negative = 0; + for (var b = 0;u.isEven() && c.isEven(); b++) + u.iushrn(1), c.iushrn(1); + do { + for (;u.isEven(); ) + u.iushrn(1); + for (;c.isEven(); ) + c.iushrn(1); + var l = u.cmp(c); + if (l < 0) { + var n = u; + u = c, c = n; + } else if (l === 0 || c.cmpn(1) === 0) + break; + u.isub(c); + } while (true); + return c.iushln(b); + }, f.prototype.invm = function(s) { + return this.egcd(s).a.umod(s); + }, f.prototype.isEven = function() { + return (this.words[0] & 1) === 0; + }, f.prototype.isOdd = function() { + return (this.words[0] & 1) === 1; + }, f.prototype.andln = function(s) { + return this.words[0] & s; + }, f.prototype.bincn = function(s) { + r(typeof s == "number"); + var u = s % 26, c = (s - u) / 26, b = 1 << u; + if (this.length <= c) + return this._expand(c + 1), this.words[c] |= b, this; + for (var l = b, n = c;l !== 0 && n < this.length; n++) { + var d = this.words[n] | 0; + d += l, l = d >>> 26, d &= 67108863, this.words[n] = d; + } + return l !== 0 && (this.words[n] = l, this.length++), this; + }, f.prototype.isZero = function() { + return this.length === 1 && this.words[0] === 0; + }, f.prototype.cmpn = function(s) { + var u = s < 0; + if (this.negative !== 0 && !u) + return -1; + if (this.negative === 0 && u) + return 1; + this._strip(); + var c; + if (this.length > 1) + c = 1; + else { + u && (s = -s), r(s <= 67108863, "Number is too big"); + var b = this.words[0] | 0; + c = b === s ? 0 : b < s ? -1 : 1; + } + return this.negative !== 0 ? -c | 0 : c; + }, f.prototype.cmp = function(s) { + if (this.negative !== 0 && s.negative === 0) + return -1; + if (this.negative === 0 && s.negative !== 0) + return 1; + var u = this.ucmp(s); + return this.negative !== 0 ? -u | 0 : u; + }, f.prototype.ucmp = function(s) { + if (this.length > s.length) + return 1; + if (this.length < s.length) + return -1; + for (var u = 0, c = this.length - 1;c >= 0; c--) { + var b = this.words[c] | 0, l = s.words[c] | 0; + if (b !== l) { + b < l ? u = -1 : b > l && (u = 1); + break; + } + } + return u; + }, f.prototype.gtn = function(s) { + return this.cmpn(s) === 1; + }, f.prototype.gt = function(s) { + return this.cmp(s) === 1; + }, f.prototype.gten = function(s) { + return this.cmpn(s) >= 0; + }, f.prototype.gte = function(s) { + return this.cmp(s) >= 0; + }, f.prototype.ltn = function(s) { + return this.cmpn(s) === -1; + }, f.prototype.lt = function(s) { + return this.cmp(s) === -1; + }, f.prototype.lten = function(s) { + return this.cmpn(s) <= 0; + }, f.prototype.lte = function(s) { + return this.cmp(s) <= 0; + }, f.prototype.eqn = function(s) { + return this.cmpn(s) === 0; + }, f.prototype.eq = function(s) { + return this.cmp(s) === 0; + }, f.red = function(s) { + return new i(s); + }, f.prototype.toRed = function(s) { + return r(!this.red, "Already a number in reduction context"), r(this.negative === 0, "red works only with positives"), s.convertTo(this)._forceRed(s); + }, f.prototype.fromRed = function() { + return r(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); + }, f.prototype._forceRed = function(s) { + return this.red = s, this; + }, f.prototype.forceRed = function(s) { + return r(!this.red, "Already a number in reduction context"), this._forceRed(s); + }, f.prototype.redAdd = function(s) { + return r(this.red, "redAdd works only with red numbers"), this.red.add(this, s); + }, f.prototype.redIAdd = function(s) { + return r(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, s); + }, f.prototype.redSub = function(s) { + return r(this.red, "redSub works only with red numbers"), this.red.sub(this, s); + }, f.prototype.redISub = function(s) { + return r(this.red, "redISub works only with red numbers"), this.red.isub(this, s); + }, f.prototype.redShl = function(s) { + return r(this.red, "redShl works only with red numbers"), this.red.shl(this, s); + }, f.prototype.redMul = function(s) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, s), this.red.mul(this, s); + }, f.prototype.redIMul = function(s) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, s), this.red.imul(this, s); + }, f.prototype.redSqr = function() { + return r(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); + }, f.prototype.redISqr = function() { + return r(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); + }, f.prototype.redSqrt = function() { + return r(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); + }, f.prototype.redInvm = function() { + return r(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); + }, f.prototype.redNeg = function() { + return r(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); + }, f.prototype.redPow = function(s) { + return r(this.red && !s.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, s); + }; + var Re = { k256: null, p224: null, p192: null, p25519: null }; + function Ee(h, s) { + this.name = h, this.p = new f(s, 16), this.n = this.p.bitLength(), this.k = new f(1).iushln(this.n).isub(this.p), this.tmp = this._tmp(); + } + Ee.prototype._tmp = function() { + var s = new f(null); + return s.words = new Array(Math.ceil(this.n / 13)), s; + }, Ee.prototype.ireduce = function(s) { + var u = s, c; + do + this.split(u, this.tmp), u = this.imulK(u), u = u.iadd(this.tmp), c = u.bitLength(); + while (c > this.n); + var b = c < this.n ? -1 : u.ucmp(this.p); + return b === 0 ? (u.words[0] = 0, u.length = 1) : b > 0 ? u.isub(this.p) : u.strip !== undefined ? u.strip() : u._strip(), u; + }, Ee.prototype.split = function(s, u) { + s.iushrn(this.n, 0, u); + }, Ee.prototype.imulK = function(s) { + return s.imul(this.k); + }; + function Ae() { + Ee.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); + } + o(Ae, Ee), Ae.prototype.split = function(s, u) { + for (var c = 4194303, b = Math.min(s.length, 9), l = 0;l < b; l++) + u.words[l] = s.words[l]; + if (u.length = b, s.length <= 9) { + s.words[0] = 0, s.length = 1; + return; + } + var n = s.words[9]; + for (u.words[u.length++] = n & c, l = 10;l < s.length; l++) { + var d = s.words[l] | 0; + s.words[l - 10] = (d & c) << 4 | n >>> 22, n = d; + } + n >>>= 22, s.words[l - 10] = n, n === 0 && s.length > 10 ? s.length -= 10 : s.length -= 9; + }, Ae.prototype.imulK = function(s) { + s.words[s.length] = 0, s.words[s.length + 1] = 0, s.length += 2; + for (var u = 0, c = 0;c < s.length; c++) { + var b = s.words[c] | 0; + u += b * 977, s.words[c] = u & 67108863, u = b * 64 + (u / 67108864 | 0); + } + return s.words[s.length - 1] === 0 && (s.length--, s.words[s.length - 1] === 0 && s.length--), s; + }; + function P() { + Ee.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); + } + o(P, Ee); + function Se2() { + Ee.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); + } + o(Se2, Ee); + function v() { + Ee.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); + } + o(v, Ee), v.prototype.imulK = function(s) { + for (var u = 0, c = 0;c < s.length; c++) { + var b = (s.words[c] | 0) * 19 + u, l = b & 67108863; + b >>>= 26, s.words[c] = l, u = b; + } + return u !== 0 && (s.words[s.length++] = u), s; + }, f._prime = function(s) { + if (Re[s]) + return Re[s]; + var u; + if (s === "k256") + u = new Ae; + else if (s === "p224") + u = new P; + else if (s === "p192") + u = new Se2; + else if (s === "p25519") + u = new v; + else + throw new Error("Unknown prime " + s); + return Re[s] = u, u; + }; + function i(h) { + if (typeof h == "string") { + var s = f._prime(h); + this.m = s.p, this.prime = s; + } else + r(h.gtn(1), "modulus must be greater than 1"), this.m = h, this.prime = null; + } + i.prototype._verify1 = function(s) { + r(s.negative === 0, "red works only with positives"), r(s.red, "red works only with red numbers"); + }, i.prototype._verify2 = function(s, u) { + r((s.negative | u.negative) === 0, "red works only with positives"), r(s.red && s.red === u.red, "red works only with red numbers"); + }, i.prototype.imod = function(s) { + return this.prime ? this.prime.ireduce(s)._forceRed(this) : (x(s, s.umod(this.m)._forceRed(this)), s); + }, i.prototype.neg = function(s) { + return s.isZero() ? s.clone() : this.m.sub(s)._forceRed(this); + }, i.prototype.add = function(s, u) { + this._verify2(s, u); + var c = s.add(u); + return c.cmp(this.m) >= 0 && c.isub(this.m), c._forceRed(this); + }, i.prototype.iadd = function(s, u) { + this._verify2(s, u); + var c = s.iadd(u); + return c.cmp(this.m) >= 0 && c.isub(this.m), c; + }, i.prototype.sub = function(s, u) { + this._verify2(s, u); + var c = s.sub(u); + return c.cmpn(0) < 0 && c.iadd(this.m), c._forceRed(this); + }, i.prototype.isub = function(s, u) { + this._verify2(s, u); + var c = s.isub(u); + return c.cmpn(0) < 0 && c.iadd(this.m), c; + }, i.prototype.shl = function(s, u) { + return this._verify1(s), this.imod(s.ushln(u)); + }, i.prototype.imul = function(s, u) { + return this._verify2(s, u), this.imod(s.imul(u)); + }, i.prototype.mul = function(s, u) { + return this._verify2(s, u), this.imod(s.mul(u)); + }, i.prototype.isqr = function(s) { + return this.imul(s, s.clone()); + }, i.prototype.sqr = function(s) { + return this.mul(s, s); + }, i.prototype.sqrt = function(s) { + if (s.isZero()) + return s.clone(); + var u = this.m.andln(3); + if (r(u % 2 === 1), u === 3) { + var c = this.m.add(new f(1)).iushrn(2); + return this.pow(s, c); + } + for (var b = this.m.subn(1), l = 0;!b.isZero() && b.andln(1) === 0; ) + l++, b.iushrn(1); + r(!b.isZero()); + var n = new f(1).toRed(this), d = n.redNeg(), w = this.m.subn(1).iushrn(1), g = this.m.bitLength(); + for (g = new f(2 * g * g).toRed(this);this.pow(g, w).cmp(d) !== 0; ) + g.redIAdd(d); + for (var _9 = this.pow(g, b), A = this.pow(s, b.addn(1).iushrn(1)), R = this.pow(s, b), I2 = l;R.cmp(n) !== 0; ) { + for (var Me = R, k2 = 0;Me.cmp(n) !== 0; k2++) + Me = Me.redSqr(); + r(k2 < I2); + var D = this.pow(_9, new f(1).iushln(I2 - k2 - 1)); + A = A.redMul(D), _9 = D.redSqr(), R = R.redMul(_9), I2 = k2; + } + return A; + }, i.prototype.invm = function(s) { + var u = s._invmp(this.m); + return u.negative !== 0 ? (u.negative = 0, this.imod(u).redNeg()) : this.imod(u); + }, i.prototype.pow = function(s, u) { + if (u.isZero()) + return new f(1).toRed(this); + if (u.cmpn(1) === 0) + return s.clone(); + var c = 4, b = new Array(1 << c); + b[0] = new f(1).toRed(this), b[1] = s; + for (var l = 2;l < b.length; l++) + b[l] = this.mul(b[l - 1], s); + var n = b[0], d = 0, w = 0, g = u.bitLength() % 26; + for (g === 0 && (g = 26), l = u.length - 1;l >= 0; l--) { + for (var _9 = u.words[l], A = g - 1;A >= 0; A--) { + var R = _9 >> A & 1; + if (n !== b[0] && (n = this.sqr(n)), R === 0 && d === 0) { + w = 0; + continue; + } + d <<= 1, d |= R, w++, !(w !== c && (l !== 0 || A !== 0)) && (n = this.mul(n, b[d]), w = 0, d = 0); + } + g = 26; + } + return n; + }, i.prototype.convertTo = function(s) { + var u = s.umod(this.m); + return u === s ? u.clone() : u; + }, i.prototype.convertFrom = function(s) { + var u = s.clone(); + return u.red = null, u; + }, f.mont = function(s) { + return new a(s); + }; + function a(h) { + i.call(this, h), this.shift = this.m.bitLength(), this.shift % 26 !== 0 && (this.shift += 26 - this.shift % 26), this.r = new f(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv); + } + o(a, i), a.prototype.convertTo = function(s) { + return this.imod(s.ushln(this.shift)); + }, a.prototype.convertFrom = function(s) { + var u = this.imod(s.mul(this.rinv)); + return u.red = null, u; + }, a.prototype.imul = function(s, u) { + if (s.isZero() || u.isZero()) + return s.words[0] = 0, s.length = 1, s; + var c = s.imul(u), b = c.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), l = c.isub(b).iushrn(this.shift), n = l; + return l.cmp(this.m) >= 0 ? n = l.isub(this.m) : l.cmpn(0) < 0 && (n = l.iadd(this.m)), n._forceRed(this); + }, a.prototype.mul = function(s, u) { + if (s.isZero() || u.isZero()) + return new f(0)._forceRed(this); + var c = s.mul(u), b = c.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), l = c.isub(b).iushrn(this.shift), n = l; + return l.cmp(this.m) >= 0 ? n = l.isub(this.m) : l.cmpn(0) < 0 && (n = l.iadd(this.m)), n._forceRed(this); + }, a.prototype.invm = function(s) { + var u = this.imod(s._invmp(this.m).mul(this.r2)); + return u._forceRed(this); + }; + })(typeof kl > "u" || kl, n2); + }); + Ks = T((yk, o2) => { + var Rf = Ws(), oA = on(); + function sA(t) { + var e = f2(t), r = e.toRed(Rf.mont(t.modulus)).redPow(new Rf(t.publicExponent)).fromRed(); + return { blinder: r, unblinder: e.invm(t.modulus) }; + } + function f2(t) { + var e = t.modulus.byteLength(), r; + do + r = new Rf(oA(e)); + while (r.cmp(t.modulus) >= 0 || !r.umod(t.prime1) || !r.umod(t.prime2)); + return r; + } + function a2(t, e) { + var r = sA(e), o = e.modulus.byteLength(), f = new Rf(t).mul(r.blinder).umod(e.modulus), p = f.toRed(Rf.mont(e.prime1)), m = f.toRed(Rf.mont(e.prime2)), y = e.coefficient, M = e.prime1, x = e.prime2, S = p.redPow(e.exponent1).fromRed(), E2 = m.redPow(e.exponent2).fromRed(), B = S.isub(E2).imul(y).umod(M).imul(x); + return E2.iadd(B).imul(r.unblinder).umod(e.modulus).toArrayLike(Buffer, "be", o); + } + a2.getr = f2; + o2.exports = a2; + }); + s2 = T((wk, hA) => { + hA.exports = { name: "elliptic", version: "6.5.4", description: "EC cryptography", main: "lib/elliptic.js", files: ["lib"], scripts: { lint: "eslint lib test", "lint:fix": "npm run lint -- --fix", unit: "istanbul test _mocha --reporter=spec test/index.js", test: "npm run lint && npm run unit", version: "grunt dist && git add dist/" }, repository: { type: "git", url: "git@github.com:indutny/elliptic" }, keywords: ["EC", "Elliptic", "curve", "Cryptography"], author: "Fedor Indutny ", license: "MIT", bugs: { url: "https://github.com/indutny/elliptic/issues" }, homepage: "https://github.com/indutny/elliptic", devDependencies: { brfs: "^2.0.2", coveralls: "^3.1.0", eslint: "^7.6.0", grunt: "^1.2.1", "grunt-browserify": "^5.3.0", "grunt-cli": "^1.3.2", "grunt-contrib-connect": "^3.0.0", "grunt-contrib-copy": "^1.0.0", "grunt-contrib-uglify": "^5.0.0", "grunt-mocha-istanbul": "^5.0.2", "grunt-saucelabs": "^9.0.1", istanbul: "^0.4.5", mocha: "^8.0.1" }, dependencies: { "bn.js": "^4.11.9", brorand: "^1.1.0", "hash.js": "^1.0.0", "hmac-drbg": "^1.0.1", inherits: "^2.0.4", "minimalistic-assert": "^1.0.1", "minimalistic-crypto-utils": "^1.0.1" } }; + }); + ri = T((h2, Ll) => { + (function(t, e) { + function r(v, i) { + if (!v) + throw new Error(i || "Assertion failed"); + } + function o(v, i) { + v.super_ = i; + var a = function() { + }; + a.prototype = i.prototype, v.prototype = new a, v.prototype.constructor = v; + } + function f(v, i, a) { + if (f.isBN(v)) + return v; + this.negative = 0, this.words = null, this.length = 0, this.red = null, v !== null && ((i === "le" || i === "be") && (a = i, i = 10), this._init(v || 0, i || 10, a || "be")); + } + typeof t == "object" ? t.exports = f : e.BN = f, f.BN = f, f.wordSize = 26; + var p; + try { + typeof window < "u" && typeof window.Buffer < "u" ? p = window.Buffer : p = ji().Buffer; + } catch { + } + f.isBN = function(i) { + return i instanceof f ? true : i !== null && typeof i == "object" && i.constructor.wordSize === f.wordSize && Array.isArray(i.words); + }, f.max = function(i, a) { + return i.cmp(a) > 0 ? i : a; + }, f.min = function(i, a) { + return i.cmp(a) < 0 ? i : a; + }, f.prototype._init = function(i, a, h) { + if (typeof i == "number") + return this._initNumber(i, a, h); + if (typeof i == "object") + return this._initArray(i, a, h); + a === "hex" && (a = 16), r(a === (a | 0) && a >= 2 && a <= 36), i = i.toString().replace(/\s+/g, ""); + var s = 0; + i[0] === "-" && (s++, this.negative = 1), s < i.length && (a === 16 ? this._parseHex(i, s, h) : (this._parseBase(i, a, s), h === "le" && this._initArray(this.toArray(), a, h))); + }, f.prototype._initNumber = function(i, a, h) { + i < 0 && (this.negative = 1, i = -i), i < 67108864 ? (this.words = [i & 67108863], this.length = 1) : i < 4503599627370496 ? (this.words = [i & 67108863, i / 67108864 & 67108863], this.length = 2) : (r(i < 9007199254740992), this.words = [i & 67108863, i / 67108864 & 67108863, 1], this.length = 3), h === "le" && this._initArray(this.toArray(), a, h); + }, f.prototype._initArray = function(i, a, h) { + if (r(typeof i.length == "number"), i.length <= 0) + return this.words = [0], this.length = 1, this; + this.length = Math.ceil(i.length / 3), this.words = new Array(this.length); + for (var s = 0;s < this.length; s++) + this.words[s] = 0; + var u, c, b = 0; + if (h === "be") + for (s = i.length - 1, u = 0;s >= 0; s -= 3) + c = i[s] | i[s - 1] << 8 | i[s - 2] << 16, this.words[u] |= c << b & 67108863, this.words[u + 1] = c >>> 26 - b & 67108863, b += 24, b >= 26 && (b -= 26, u++); + else if (h === "le") + for (s = 0, u = 0;s < i.length; s += 3) + c = i[s] | i[s + 1] << 8 | i[s + 2] << 16, this.words[u] |= c << b & 67108863, this.words[u + 1] = c >>> 26 - b & 67108863, b += 24, b >= 26 && (b -= 26, u++); + return this.strip(); + }; + function m(v, i) { + var a = v.charCodeAt(i); + return a >= 65 && a <= 70 ? a - 55 : a >= 97 && a <= 102 ? a - 87 : a - 48 & 15; + } + function y(v, i, a) { + var h = m(v, a); + return a - 1 >= i && (h |= m(v, a - 1) << 4), h; + } + f.prototype._parseHex = function(i, a, h) { + this.length = Math.ceil((i.length - a) / 6), this.words = new Array(this.length); + for (var s = 0;s < this.length; s++) + this.words[s] = 0; + var u = 0, c = 0, b; + if (h === "be") + for (s = i.length - 1;s >= a; s -= 2) + b = y(i, a, s) << u, this.words[c] |= b & 67108863, u >= 18 ? (u -= 18, c += 1, this.words[c] |= b >>> 26) : u += 8; + else { + var l = i.length - a; + for (s = l % 2 === 0 ? a + 1 : a;s < i.length; s += 2) + b = y(i, a, s) << u, this.words[c] |= b & 67108863, u >= 18 ? (u -= 18, c += 1, this.words[c] |= b >>> 26) : u += 8; + } + this.strip(); + }; + function M(v, i, a, h) { + for (var s = 0, u = Math.min(v.length, a), c = i;c < u; c++) { + var b = v.charCodeAt(c) - 48; + s *= h, b >= 49 ? s += b - 49 + 10 : b >= 17 ? s += b - 17 + 10 : s += b; + } + return s; + } + f.prototype._parseBase = function(i, a, h) { + this.words = [0], this.length = 1; + for (var s = 0, u = 1;u <= 67108863; u *= a) + s++; + s--, u = u / a | 0; + for (var c = i.length - h, b = c % s, l = Math.min(c, c - b) + h, n = 0, d = h;d < l; d += s) + n = M(i, d, d + s, a), this.imuln(u), this.words[0] + n < 67108864 ? this.words[0] += n : this._iaddn(n); + if (b !== 0) { + var w = 1; + for (n = M(i, d, i.length, a), d = 0;d < b; d++) + w *= a; + this.imuln(w), this.words[0] + n < 67108864 ? this.words[0] += n : this._iaddn(n); + } + this.strip(); + }, f.prototype.copy = function(i) { + i.words = new Array(this.length); + for (var a = 0;a < this.length; a++) + i.words[a] = this.words[a]; + i.length = this.length, i.negative = this.negative, i.red = this.red; + }, f.prototype.clone = function() { + var i = new f(null); + return this.copy(i), i; + }, f.prototype._expand = function(i) { + for (;this.length < i; ) + this.words[this.length++] = 0; + return this; + }, f.prototype.strip = function() { + for (;this.length > 1 && this.words[this.length - 1] === 0; ) + this.length--; + return this._normSign(); + }, f.prototype._normSign = function() { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }, f.prototype.inspect = function() { + return (this.red ? ""; + }; + var x = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], S = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], E2 = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; + f.prototype.toString = function(i, a) { + i = i || 10, a = a | 0 || 1; + var h; + if (i === 16 || i === "hex") { + h = ""; + for (var s = 0, u = 0, c = 0;c < this.length; c++) { + var b = this.words[c], l = ((b << s | u) & 16777215).toString(16); + u = b >>> 24 - s & 16777215, u !== 0 || c !== this.length - 1 ? h = x[6 - l.length] + l + h : h = l + h, s += 2, s >= 26 && (s -= 26, c--); + } + for (u !== 0 && (h = u.toString(16) + h);h.length % a !== 0; ) + h = "0" + h; + return this.negative !== 0 && (h = "-" + h), h; + } + if (i === (i | 0) && i >= 2 && i <= 36) { + var n = S[i], d = E2[i]; + h = ""; + var w = this.clone(); + for (w.negative = 0;!w.isZero(); ) { + var g = w.modn(d).toString(i); + w = w.idivn(d), w.isZero() ? h = g + h : h = x[n - g.length] + g + h; + } + for (this.isZero() && (h = "0" + h);h.length % a !== 0; ) + h = "0" + h; + return this.negative !== 0 && (h = "-" + h), h; + } + r(false, "Base should be between 2 and 36"); + }, f.prototype.toNumber = function() { + var i = this.words[0]; + return this.length === 2 ? i += this.words[1] * 67108864 : this.length === 3 && this.words[2] === 1 ? i += 4503599627370496 + this.words[1] * 67108864 : this.length > 2 && r(false, "Number can only safely store up to 53 bits"), this.negative !== 0 ? -i : i; + }, f.prototype.toJSON = function() { + return this.toString(16); + }, f.prototype.toBuffer = function(i, a) { + return r(typeof p < "u"), this.toArrayLike(p, i, a); + }, f.prototype.toArray = function(i, a) { + return this.toArrayLike(Array, i, a); + }, f.prototype.toArrayLike = function(i, a, h) { + var s = this.byteLength(), u = h || Math.max(1, s); + r(s <= u, "byte array longer than desired length"), r(u > 0, "Requested array length <= 0"), this.strip(); + var c = a === "le", b = new i(u), l, n, d = this.clone(); + if (c) { + for (n = 0;!d.isZero(); n++) + l = d.andln(255), d.iushrn(8), b[n] = l; + for (;n < u; n++) + b[n] = 0; + } else { + for (n = 0;n < u - s; n++) + b[n] = 0; + for (n = 0;!d.isZero(); n++) + l = d.andln(255), d.iushrn(8), b[u - n - 1] = l; + } + return b; + }, Math.clz32 ? f.prototype._countBits = function(i) { + return 32 - Math.clz32(i); + } : f.prototype._countBits = function(i) { + var a = i, h = 0; + return a >= 4096 && (h += 13, a >>>= 13), a >= 64 && (h += 7, a >>>= 7), a >= 8 && (h += 4, a >>>= 4), a >= 2 && (h += 2, a >>>= 2), h + a; + }, f.prototype._zeroBits = function(i) { + if (i === 0) + return 26; + var a = i, h = 0; + return (a & 8191) === 0 && (h += 13, a >>>= 13), (a & 127) === 0 && (h += 7, a >>>= 7), (a & 15) === 0 && (h += 4, a >>>= 4), (a & 3) === 0 && (h += 2, a >>>= 2), (a & 1) === 0 && h++, h; + }, f.prototype.bitLength = function() { + var i = this.words[this.length - 1], a = this._countBits(i); + return (this.length - 1) * 26 + a; + }; + function B(v) { + for (var i = new Array(v.bitLength()), a = 0;a < i.length; a++) { + var h = a / 26 | 0, s = a % 26; + i[a] = (v.words[h] & 1 << s) >>> s; + } + return i; + } + f.prototype.zeroBits = function() { + if (this.isZero()) + return 0; + for (var i = 0, a = 0;a < this.length; a++) { + var h = this._zeroBits(this.words[a]); + if (i += h, h !== 26) + break; + } + return i; + }, f.prototype.byteLength = function() { + return Math.ceil(this.bitLength() / 8); + }, f.prototype.toTwos = function(i) { + return this.negative !== 0 ? this.abs().inotn(i).iaddn(1) : this.clone(); + }, f.prototype.fromTwos = function(i) { + return this.testn(i - 1) ? this.notn(i).iaddn(1).ineg() : this.clone(); + }, f.prototype.isNeg = function() { + return this.negative !== 0; + }, f.prototype.neg = function() { + return this.clone().ineg(); + }, f.prototype.ineg = function() { + return this.isZero() || (this.negative ^= 1), this; + }, f.prototype.iuor = function(i) { + for (;this.length < i.length; ) + this.words[this.length++] = 0; + for (var a = 0;a < i.length; a++) + this.words[a] = this.words[a] | i.words[a]; + return this.strip(); + }, f.prototype.ior = function(i) { + return r((this.negative | i.negative) === 0), this.iuor(i); + }, f.prototype.or = function(i) { + return this.length > i.length ? this.clone().ior(i) : i.clone().ior(this); + }, f.prototype.uor = function(i) { + return this.length > i.length ? this.clone().iuor(i) : i.clone().iuor(this); + }, f.prototype.iuand = function(i) { + var a; + this.length > i.length ? a = i : a = this; + for (var h = 0;h < a.length; h++) + this.words[h] = this.words[h] & i.words[h]; + return this.length = a.length, this.strip(); + }, f.prototype.iand = function(i) { + return r((this.negative | i.negative) === 0), this.iuand(i); + }, f.prototype.and = function(i) { + return this.length > i.length ? this.clone().iand(i) : i.clone().iand(this); + }, f.prototype.uand = function(i) { + return this.length > i.length ? this.clone().iuand(i) : i.clone().iuand(this); + }, f.prototype.iuxor = function(i) { + var a, h; + this.length > i.length ? (a = this, h = i) : (a = i, h = this); + for (var s = 0;s < h.length; s++) + this.words[s] = a.words[s] ^ h.words[s]; + if (this !== a) + for (;s < a.length; s++) + this.words[s] = a.words[s]; + return this.length = a.length, this.strip(); + }, f.prototype.ixor = function(i) { + return r((this.negative | i.negative) === 0), this.iuxor(i); + }, f.prototype.xor = function(i) { + return this.length > i.length ? this.clone().ixor(i) : i.clone().ixor(this); + }, f.prototype.uxor = function(i) { + return this.length > i.length ? this.clone().iuxor(i) : i.clone().iuxor(this); + }, f.prototype.inotn = function(i) { + r(typeof i == "number" && i >= 0); + var a = Math.ceil(i / 26) | 0, h = i % 26; + this._expand(a), h > 0 && a--; + for (var s = 0;s < a; s++) + this.words[s] = ~this.words[s] & 67108863; + return h > 0 && (this.words[s] = ~this.words[s] & 67108863 >> 26 - h), this.strip(); + }, f.prototype.notn = function(i) { + return this.clone().inotn(i); + }, f.prototype.setn = function(i, a) { + r(typeof i == "number" && i >= 0); + var h = i / 26 | 0, s = i % 26; + return this._expand(h + 1), a ? this.words[h] = this.words[h] | 1 << s : this.words[h] = this.words[h] & ~(1 << s), this.strip(); + }, f.prototype.iadd = function(i) { + var a; + if (this.negative !== 0 && i.negative === 0) + return this.negative = 0, a = this.isub(i), this.negative ^= 1, this._normSign(); + if (this.negative === 0 && i.negative !== 0) + return i.negative = 0, a = this.isub(i), i.negative = 1, a._normSign(); + var h, s; + this.length > i.length ? (h = this, s = i) : (h = i, s = this); + for (var u = 0, c = 0;c < s.length; c++) + a = (h.words[c] | 0) + (s.words[c] | 0) + u, this.words[c] = a & 67108863, u = a >>> 26; + for (;u !== 0 && c < h.length; c++) + a = (h.words[c] | 0) + u, this.words[c] = a & 67108863, u = a >>> 26; + if (this.length = h.length, u !== 0) + this.words[this.length] = u, this.length++; + else if (h !== this) + for (;c < h.length; c++) + this.words[c] = h.words[c]; + return this; + }, f.prototype.add = function(i) { + var a; + return i.negative !== 0 && this.negative === 0 ? (i.negative = 0, a = this.sub(i), i.negative ^= 1, a) : i.negative === 0 && this.negative !== 0 ? (this.negative = 0, a = i.sub(this), this.negative = 1, a) : this.length > i.length ? this.clone().iadd(i) : i.clone().iadd(this); + }, f.prototype.isub = function(i) { + if (i.negative !== 0) { + i.negative = 0; + var a = this.iadd(i); + return i.negative = 1, a._normSign(); + } else if (this.negative !== 0) + return this.negative = 0, this.iadd(i), this.negative = 1, this._normSign(); + var h = this.cmp(i); + if (h === 0) + return this.negative = 0, this.length = 1, this.words[0] = 0, this; + var s, u; + h > 0 ? (s = this, u = i) : (s = i, u = this); + for (var c = 0, b = 0;b < u.length; b++) + a = (s.words[b] | 0) - (u.words[b] | 0) + c, c = a >> 26, this.words[b] = a & 67108863; + for (;c !== 0 && b < s.length; b++) + a = (s.words[b] | 0) + c, c = a >> 26, this.words[b] = a & 67108863; + if (c === 0 && b < s.length && s !== this) + for (;b < s.length; b++) + this.words[b] = s.words[b]; + return this.length = Math.max(this.length, b), s !== this && (this.negative = 1), this.strip(); + }, f.prototype.sub = function(i) { + return this.clone().isub(i); + }; + function q(v, i, a) { + a.negative = i.negative ^ v.negative; + var h = v.length + i.length | 0; + a.length = h, h = h - 1 | 0; + var s = v.words[0] | 0, u = i.words[0] | 0, c = s * u, b = c & 67108863, l = c / 67108864 | 0; + a.words[0] = b; + for (var n = 1;n < h; n++) { + for (var d = l >>> 26, w = l & 67108863, g = Math.min(n, i.length - 1), _9 = Math.max(0, n - v.length + 1);_9 <= g; _9++) { + var A = n - _9 | 0; + s = v.words[A] | 0, u = i.words[_9] | 0, c = s * u + w, d += c / 67108864 | 0, w = c & 67108863; + } + a.words[n] = w | 0, l = d | 0; + } + return l !== 0 ? a.words[n] = l | 0 : a.length--, a.strip(); + } + var L = function(i, a, h) { + var s = i.words, u = a.words, c = h.words, b = 0, l, n, d, w = s[0] | 0, g = w & 8191, _9 = w >>> 13, A = s[1] | 0, R = A & 8191, I2 = A >>> 13, Me = s[2] | 0, k2 = Me & 8191, D = Me >>> 13, nt = s[3] | 0, C2 = nt & 8191, O = nt >>> 13, vt = s[4] | 0, F = vt & 8191, U = vt >>> 13, bt = s[5] | 0, z = bt & 8191, H = bt >>> 13, mt = s[6] | 0, W = mt & 8191, K = mt >>> 13, gt = s[7] | 0, j = gt & 8191, Z = gt >>> 13, yt = s[8] | 0, V2 = yt & 8191, $ = yt >>> 13, wt = s[9] | 0, G = wt & 8191, Y = wt >>> 13, Mt = u[0] | 0, X = Mt & 8191, J2 = Mt >>> 13, _t = u[1] | 0, Q = _t & 8191, ee = _t >>> 13, xt2 = u[2] | 0, te2 = xt2 & 8191, re = xt2 >>> 13, St = u[3] | 0, ie = St & 8191, ne = St >>> 13, Et2 = u[4] | 0, fe = Et2 & 8191, ae2 = Et2 >>> 13, At2 = u[5] | 0, oe = At2 & 8191, se2 = At2 >>> 13, Rt = u[6] | 0, he = Rt & 8191, ue2 = Rt >>> 13, Bt = u[7] | 0, le = Bt & 8191, de = Bt >>> 13, qt = u[8] | 0, ce2 = qt & 8191, pe2 = qt >>> 13, It = u[9] | 0, ve = It & 8191, be = It >>> 13; + h.negative = i.negative ^ a.negative, h.length = 19, l = Math.imul(g, X), n = Math.imul(g, J2), n = n + Math.imul(_9, X) | 0, d = Math.imul(_9, J2); + var ft = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (ft >>> 26) | 0, ft &= 67108863, l = Math.imul(R, X), n = Math.imul(R, J2), n = n + Math.imul(I2, X) | 0, d = Math.imul(I2, J2), l = l + Math.imul(g, Q) | 0, n = n + Math.imul(g, ee) | 0, n = n + Math.imul(_9, Q) | 0, d = d + Math.imul(_9, ee) | 0; + var Be = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Be >>> 26) | 0, Be &= 67108863, l = Math.imul(k2, X), n = Math.imul(k2, J2), n = n + Math.imul(D, X) | 0, d = Math.imul(D, J2), l = l + Math.imul(R, Q) | 0, n = n + Math.imul(R, ee) | 0, n = n + Math.imul(I2, Q) | 0, d = d + Math.imul(I2, ee) | 0, l = l + Math.imul(g, te2) | 0, n = n + Math.imul(g, re) | 0, n = n + Math.imul(_9, te2) | 0, d = d + Math.imul(_9, re) | 0; + var qe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (qe >>> 26) | 0, qe &= 67108863, l = Math.imul(C2, X), n = Math.imul(C2, J2), n = n + Math.imul(O, X) | 0, d = Math.imul(O, J2), l = l + Math.imul(k2, Q) | 0, n = n + Math.imul(k2, ee) | 0, n = n + Math.imul(D, Q) | 0, d = d + Math.imul(D, ee) | 0, l = l + Math.imul(R, te2) | 0, n = n + Math.imul(R, re) | 0, n = n + Math.imul(I2, te2) | 0, d = d + Math.imul(I2, re) | 0, l = l + Math.imul(g, ie) | 0, n = n + Math.imul(g, ne) | 0, n = n + Math.imul(_9, ie) | 0, d = d + Math.imul(_9, ne) | 0; + var ze = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (ze >>> 26) | 0, ze &= 67108863, l = Math.imul(F, X), n = Math.imul(F, J2), n = n + Math.imul(U, X) | 0, d = Math.imul(U, J2), l = l + Math.imul(C2, Q) | 0, n = n + Math.imul(C2, ee) | 0, n = n + Math.imul(O, Q) | 0, d = d + Math.imul(O, ee) | 0, l = l + Math.imul(k2, te2) | 0, n = n + Math.imul(k2, re) | 0, n = n + Math.imul(D, te2) | 0, d = d + Math.imul(D, re) | 0, l = l + Math.imul(R, ie) | 0, n = n + Math.imul(R, ne) | 0, n = n + Math.imul(I2, ie) | 0, d = d + Math.imul(I2, ne) | 0, l = l + Math.imul(g, fe) | 0, n = n + Math.imul(g, ae2) | 0, n = n + Math.imul(_9, fe) | 0, d = d + Math.imul(_9, ae2) | 0; + var He2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (He2 >>> 26) | 0, He2 &= 67108863, l = Math.imul(z, X), n = Math.imul(z, J2), n = n + Math.imul(H, X) | 0, d = Math.imul(H, J2), l = l + Math.imul(F, Q) | 0, n = n + Math.imul(F, ee) | 0, n = n + Math.imul(U, Q) | 0, d = d + Math.imul(U, ee) | 0, l = l + Math.imul(C2, te2) | 0, n = n + Math.imul(C2, re) | 0, n = n + Math.imul(O, te2) | 0, d = d + Math.imul(O, re) | 0, l = l + Math.imul(k2, ie) | 0, n = n + Math.imul(k2, ne) | 0, n = n + Math.imul(D, ie) | 0, d = d + Math.imul(D, ne) | 0, l = l + Math.imul(R, fe) | 0, n = n + Math.imul(R, ae2) | 0, n = n + Math.imul(I2, fe) | 0, d = d + Math.imul(I2, ae2) | 0, l = l + Math.imul(g, oe) | 0, n = n + Math.imul(g, se2) | 0, n = n + Math.imul(_9, oe) | 0, d = d + Math.imul(_9, se2) | 0; + var We = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (We >>> 26) | 0, We &= 67108863, l = Math.imul(W, X), n = Math.imul(W, J2), n = n + Math.imul(K, X) | 0, d = Math.imul(K, J2), l = l + Math.imul(z, Q) | 0, n = n + Math.imul(z, ee) | 0, n = n + Math.imul(H, Q) | 0, d = d + Math.imul(H, ee) | 0, l = l + Math.imul(F, te2) | 0, n = n + Math.imul(F, re) | 0, n = n + Math.imul(U, te2) | 0, d = d + Math.imul(U, re) | 0, l = l + Math.imul(C2, ie) | 0, n = n + Math.imul(C2, ne) | 0, n = n + Math.imul(O, ie) | 0, d = d + Math.imul(O, ne) | 0, l = l + Math.imul(k2, fe) | 0, n = n + Math.imul(k2, ae2) | 0, n = n + Math.imul(D, fe) | 0, d = d + Math.imul(D, ae2) | 0, l = l + Math.imul(R, oe) | 0, n = n + Math.imul(R, se2) | 0, n = n + Math.imul(I2, oe) | 0, d = d + Math.imul(I2, se2) | 0, l = l + Math.imul(g, he) | 0, n = n + Math.imul(g, ue2) | 0, n = n + Math.imul(_9, he) | 0, d = d + Math.imul(_9, ue2) | 0; + var Ke2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ke2 >>> 26) | 0, Ke2 &= 67108863, l = Math.imul(j, X), n = Math.imul(j, J2), n = n + Math.imul(Z, X) | 0, d = Math.imul(Z, J2), l = l + Math.imul(W, Q) | 0, n = n + Math.imul(W, ee) | 0, n = n + Math.imul(K, Q) | 0, d = d + Math.imul(K, ee) | 0, l = l + Math.imul(z, te2) | 0, n = n + Math.imul(z, re) | 0, n = n + Math.imul(H, te2) | 0, d = d + Math.imul(H, re) | 0, l = l + Math.imul(F, ie) | 0, n = n + Math.imul(F, ne) | 0, n = n + Math.imul(U, ie) | 0, d = d + Math.imul(U, ne) | 0, l = l + Math.imul(C2, fe) | 0, n = n + Math.imul(C2, ae2) | 0, n = n + Math.imul(O, fe) | 0, d = d + Math.imul(O, ae2) | 0, l = l + Math.imul(k2, oe) | 0, n = n + Math.imul(k2, se2) | 0, n = n + Math.imul(D, oe) | 0, d = d + Math.imul(D, se2) | 0, l = l + Math.imul(R, he) | 0, n = n + Math.imul(R, ue2) | 0, n = n + Math.imul(I2, he) | 0, d = d + Math.imul(I2, ue2) | 0, l = l + Math.imul(g, le) | 0, n = n + Math.imul(g, de) | 0, n = n + Math.imul(_9, le) | 0, d = d + Math.imul(_9, de) | 0; + var je = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (je >>> 26) | 0, je &= 67108863, l = Math.imul(V2, X), n = Math.imul(V2, J2), n = n + Math.imul($, X) | 0, d = Math.imul($, J2), l = l + Math.imul(j, Q) | 0, n = n + Math.imul(j, ee) | 0, n = n + Math.imul(Z, Q) | 0, d = d + Math.imul(Z, ee) | 0, l = l + Math.imul(W, te2) | 0, n = n + Math.imul(W, re) | 0, n = n + Math.imul(K, te2) | 0, d = d + Math.imul(K, re) | 0, l = l + Math.imul(z, ie) | 0, n = n + Math.imul(z, ne) | 0, n = n + Math.imul(H, ie) | 0, d = d + Math.imul(H, ne) | 0, l = l + Math.imul(F, fe) | 0, n = n + Math.imul(F, ae2) | 0, n = n + Math.imul(U, fe) | 0, d = d + Math.imul(U, ae2) | 0, l = l + Math.imul(C2, oe) | 0, n = n + Math.imul(C2, se2) | 0, n = n + Math.imul(O, oe) | 0, d = d + Math.imul(O, se2) | 0, l = l + Math.imul(k2, he) | 0, n = n + Math.imul(k2, ue2) | 0, n = n + Math.imul(D, he) | 0, d = d + Math.imul(D, ue2) | 0, l = l + Math.imul(R, le) | 0, n = n + Math.imul(R, de) | 0, n = n + Math.imul(I2, le) | 0, d = d + Math.imul(I2, de) | 0, l = l + Math.imul(g, ce2) | 0, n = n + Math.imul(g, pe2) | 0, n = n + Math.imul(_9, ce2) | 0, d = d + Math.imul(_9, pe2) | 0; + var Ze2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ze2 >>> 26) | 0, Ze2 &= 67108863, l = Math.imul(G, X), n = Math.imul(G, J2), n = n + Math.imul(Y, X) | 0, d = Math.imul(Y, J2), l = l + Math.imul(V2, Q) | 0, n = n + Math.imul(V2, ee) | 0, n = n + Math.imul($, Q) | 0, d = d + Math.imul($, ee) | 0, l = l + Math.imul(j, te2) | 0, n = n + Math.imul(j, re) | 0, n = n + Math.imul(Z, te2) | 0, d = d + Math.imul(Z, re) | 0, l = l + Math.imul(W, ie) | 0, n = n + Math.imul(W, ne) | 0, n = n + Math.imul(K, ie) | 0, d = d + Math.imul(K, ne) | 0, l = l + Math.imul(z, fe) | 0, n = n + Math.imul(z, ae2) | 0, n = n + Math.imul(H, fe) | 0, d = d + Math.imul(H, ae2) | 0, l = l + Math.imul(F, oe) | 0, n = n + Math.imul(F, se2) | 0, n = n + Math.imul(U, oe) | 0, d = d + Math.imul(U, se2) | 0, l = l + Math.imul(C2, he) | 0, n = n + Math.imul(C2, ue2) | 0, n = n + Math.imul(O, he) | 0, d = d + Math.imul(O, ue2) | 0, l = l + Math.imul(k2, le) | 0, n = n + Math.imul(k2, de) | 0, n = n + Math.imul(D, le) | 0, d = d + Math.imul(D, de) | 0, l = l + Math.imul(R, ce2) | 0, n = n + Math.imul(R, pe2) | 0, n = n + Math.imul(I2, ce2) | 0, d = d + Math.imul(I2, pe2) | 0, l = l + Math.imul(g, ve) | 0, n = n + Math.imul(g, be) | 0, n = n + Math.imul(_9, ve) | 0, d = d + Math.imul(_9, be) | 0; + var Ve = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ve >>> 26) | 0, Ve &= 67108863, l = Math.imul(G, Q), n = Math.imul(G, ee), n = n + Math.imul(Y, Q) | 0, d = Math.imul(Y, ee), l = l + Math.imul(V2, te2) | 0, n = n + Math.imul(V2, re) | 0, n = n + Math.imul($, te2) | 0, d = d + Math.imul($, re) | 0, l = l + Math.imul(j, ie) | 0, n = n + Math.imul(j, ne) | 0, n = n + Math.imul(Z, ie) | 0, d = d + Math.imul(Z, ne) | 0, l = l + Math.imul(W, fe) | 0, n = n + Math.imul(W, ae2) | 0, n = n + Math.imul(K, fe) | 0, d = d + Math.imul(K, ae2) | 0, l = l + Math.imul(z, oe) | 0, n = n + Math.imul(z, se2) | 0, n = n + Math.imul(H, oe) | 0, d = d + Math.imul(H, se2) | 0, l = l + Math.imul(F, he) | 0, n = n + Math.imul(F, ue2) | 0, n = n + Math.imul(U, he) | 0, d = d + Math.imul(U, ue2) | 0, l = l + Math.imul(C2, le) | 0, n = n + Math.imul(C2, de) | 0, n = n + Math.imul(O, le) | 0, d = d + Math.imul(O, de) | 0, l = l + Math.imul(k2, ce2) | 0, n = n + Math.imul(k2, pe2) | 0, n = n + Math.imul(D, ce2) | 0, d = d + Math.imul(D, pe2) | 0, l = l + Math.imul(R, ve) | 0, n = n + Math.imul(R, be) | 0, n = n + Math.imul(I2, ve) | 0, d = d + Math.imul(I2, be) | 0; + var $e = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + ($e >>> 26) | 0, $e &= 67108863, l = Math.imul(G, te2), n = Math.imul(G, re), n = n + Math.imul(Y, te2) | 0, d = Math.imul(Y, re), l = l + Math.imul(V2, ie) | 0, n = n + Math.imul(V2, ne) | 0, n = n + Math.imul($, ie) | 0, d = d + Math.imul($, ne) | 0, l = l + Math.imul(j, fe) | 0, n = n + Math.imul(j, ae2) | 0, n = n + Math.imul(Z, fe) | 0, d = d + Math.imul(Z, ae2) | 0, l = l + Math.imul(W, oe) | 0, n = n + Math.imul(W, se2) | 0, n = n + Math.imul(K, oe) | 0, d = d + Math.imul(K, se2) | 0, l = l + Math.imul(z, he) | 0, n = n + Math.imul(z, ue2) | 0, n = n + Math.imul(H, he) | 0, d = d + Math.imul(H, ue2) | 0, l = l + Math.imul(F, le) | 0, n = n + Math.imul(F, de) | 0, n = n + Math.imul(U, le) | 0, d = d + Math.imul(U, de) | 0, l = l + Math.imul(C2, ce2) | 0, n = n + Math.imul(C2, pe2) | 0, n = n + Math.imul(O, ce2) | 0, d = d + Math.imul(O, pe2) | 0, l = l + Math.imul(k2, ve) | 0, n = n + Math.imul(k2, be) | 0, n = n + Math.imul(D, ve) | 0, d = d + Math.imul(D, be) | 0; + var Ge = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ge >>> 26) | 0, Ge &= 67108863, l = Math.imul(G, ie), n = Math.imul(G, ne), n = n + Math.imul(Y, ie) | 0, d = Math.imul(Y, ne), l = l + Math.imul(V2, fe) | 0, n = n + Math.imul(V2, ae2) | 0, n = n + Math.imul($, fe) | 0, d = d + Math.imul($, ae2) | 0, l = l + Math.imul(j, oe) | 0, n = n + Math.imul(j, se2) | 0, n = n + Math.imul(Z, oe) | 0, d = d + Math.imul(Z, se2) | 0, l = l + Math.imul(W, he) | 0, n = n + Math.imul(W, ue2) | 0, n = n + Math.imul(K, he) | 0, d = d + Math.imul(K, ue2) | 0, l = l + Math.imul(z, le) | 0, n = n + Math.imul(z, de) | 0, n = n + Math.imul(H, le) | 0, d = d + Math.imul(H, de) | 0, l = l + Math.imul(F, ce2) | 0, n = n + Math.imul(F, pe2) | 0, n = n + Math.imul(U, ce2) | 0, d = d + Math.imul(U, pe2) | 0, l = l + Math.imul(C2, ve) | 0, n = n + Math.imul(C2, be) | 0, n = n + Math.imul(O, ve) | 0, d = d + Math.imul(O, be) | 0; + var Ye = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ye >>> 26) | 0, Ye &= 67108863, l = Math.imul(G, fe), n = Math.imul(G, ae2), n = n + Math.imul(Y, fe) | 0, d = Math.imul(Y, ae2), l = l + Math.imul(V2, oe) | 0, n = n + Math.imul(V2, se2) | 0, n = n + Math.imul($, oe) | 0, d = d + Math.imul($, se2) | 0, l = l + Math.imul(j, he) | 0, n = n + Math.imul(j, ue2) | 0, n = n + Math.imul(Z, he) | 0, d = d + Math.imul(Z, ue2) | 0, l = l + Math.imul(W, le) | 0, n = n + Math.imul(W, de) | 0, n = n + Math.imul(K, le) | 0, d = d + Math.imul(K, de) | 0, l = l + Math.imul(z, ce2) | 0, n = n + Math.imul(z, pe2) | 0, n = n + Math.imul(H, ce2) | 0, d = d + Math.imul(H, pe2) | 0, l = l + Math.imul(F, ve) | 0, n = n + Math.imul(F, be) | 0, n = n + Math.imul(U, ve) | 0, d = d + Math.imul(U, be) | 0; + var Xe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Xe >>> 26) | 0, Xe &= 67108863, l = Math.imul(G, oe), n = Math.imul(G, se2), n = n + Math.imul(Y, oe) | 0, d = Math.imul(Y, se2), l = l + Math.imul(V2, he) | 0, n = n + Math.imul(V2, ue2) | 0, n = n + Math.imul($, he) | 0, d = d + Math.imul($, ue2) | 0, l = l + Math.imul(j, le) | 0, n = n + Math.imul(j, de) | 0, n = n + Math.imul(Z, le) | 0, d = d + Math.imul(Z, de) | 0, l = l + Math.imul(W, ce2) | 0, n = n + Math.imul(W, pe2) | 0, n = n + Math.imul(K, ce2) | 0, d = d + Math.imul(K, pe2) | 0, l = l + Math.imul(z, ve) | 0, n = n + Math.imul(z, be) | 0, n = n + Math.imul(H, ve) | 0, d = d + Math.imul(H, be) | 0; + var Je = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Je >>> 26) | 0, Je &= 67108863, l = Math.imul(G, he), n = Math.imul(G, ue2), n = n + Math.imul(Y, he) | 0, d = Math.imul(Y, ue2), l = l + Math.imul(V2, le) | 0, n = n + Math.imul(V2, de) | 0, n = n + Math.imul($, le) | 0, d = d + Math.imul($, de) | 0, l = l + Math.imul(j, ce2) | 0, n = n + Math.imul(j, pe2) | 0, n = n + Math.imul(Z, ce2) | 0, d = d + Math.imul(Z, pe2) | 0, l = l + Math.imul(W, ve) | 0, n = n + Math.imul(W, be) | 0, n = n + Math.imul(K, ve) | 0, d = d + Math.imul(K, be) | 0; + var Qe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Qe >>> 26) | 0, Qe &= 67108863, l = Math.imul(G, le), n = Math.imul(G, de), n = n + Math.imul(Y, le) | 0, d = Math.imul(Y, de), l = l + Math.imul(V2, ce2) | 0, n = n + Math.imul(V2, pe2) | 0, n = n + Math.imul($, ce2) | 0, d = d + Math.imul($, pe2) | 0, l = l + Math.imul(j, ve) | 0, n = n + Math.imul(j, be) | 0, n = n + Math.imul(Z, ve) | 0, d = d + Math.imul(Z, be) | 0; + var et2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (et2 >>> 26) | 0, et2 &= 67108863, l = Math.imul(G, ce2), n = Math.imul(G, pe2), n = n + Math.imul(Y, ce2) | 0, d = Math.imul(Y, pe2), l = l + Math.imul(V2, ve) | 0, n = n + Math.imul(V2, be) | 0, n = n + Math.imul($, ve) | 0, d = d + Math.imul($, be) | 0; + var tt2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (tt2 >>> 26) | 0, tt2 &= 67108863, l = Math.imul(G, ve), n = Math.imul(G, be), n = n + Math.imul(Y, ve) | 0, d = Math.imul(Y, be); + var rt2 = (b + l | 0) + ((n & 8191) << 13) | 0; + return b = (d + (n >>> 13) | 0) + (rt2 >>> 26) | 0, rt2 &= 67108863, c[0] = ft, c[1] = Be, c[2] = qe, c[3] = ze, c[4] = He2, c[5] = We, c[6] = Ke2, c[7] = je, c[8] = Ze2, c[9] = Ve, c[10] = $e, c[11] = Ge, c[12] = Ye, c[13] = Xe, c[14] = Je, c[15] = Qe, c[16] = et2, c[17] = tt2, c[18] = rt2, b !== 0 && (c[19] = b, h.length++), h; + }; + Math.imul || (L = q); + function ge(v, i, a) { + a.negative = i.negative ^ v.negative, a.length = v.length + i.length; + for (var h = 0, s = 0, u = 0;u < a.length - 1; u++) { + var c = s; + s = 0; + for (var b = h & 67108863, l = Math.min(u, i.length - 1), n = Math.max(0, u - v.length + 1);n <= l; n++) { + var d = u - n, w = v.words[d] | 0, g = i.words[n] | 0, _9 = w * g, A = _9 & 67108863; + c = c + (_9 / 67108864 | 0) | 0, A = A + b | 0, b = A & 67108863, c = c + (A >>> 26) | 0, s += c >>> 26, c &= 67108863; + } + a.words[u] = b, h = c, c = s; + } + return h !== 0 ? a.words[u] = h : a.length--, a.strip(); + } + function _e(v, i, a) { + var h = new N; + return h.mulp(v, i, a); + } + f.prototype.mulTo = function(i, a) { + var h, s = this.length + i.length; + return this.length === 10 && i.length === 10 ? h = L(this, i, a) : s < 63 ? h = q(this, i, a) : s < 1024 ? h = ge(this, i, a) : h = _e(this, i, a), h; + }; + function N(v, i) { + this.x = v, this.y = i; + } + N.prototype.makeRBT = function(i) { + for (var a = new Array(i), h = f.prototype._countBits(i) - 1, s = 0;s < i; s++) + a[s] = this.revBin(s, h, i); + return a; + }, N.prototype.revBin = function(i, a, h) { + if (i === 0 || i === h - 1) + return i; + for (var s = 0, u = 0;u < a; u++) + s |= (i & 1) << a - u - 1, i >>= 1; + return s; + }, N.prototype.permute = function(i, a, h, s, u, c) { + for (var b = 0;b < c; b++) + s[b] = a[i[b]], u[b] = h[i[b]]; + }, N.prototype.transform = function(i, a, h, s, u, c) { + this.permute(c, i, a, h, s, u); + for (var b = 1;b < u; b <<= 1) + for (var l = b << 1, n = Math.cos(2 * Math.PI / l), d = Math.sin(2 * Math.PI / l), w = 0;w < u; w += l) + for (var g = n, _9 = d, A = 0;A < b; A++) { + var R = h[w + A], I2 = s[w + A], Me = h[w + A + b], k2 = s[w + A + b], D = g * Me - _9 * k2; + k2 = g * k2 + _9 * Me, Me = D, h[w + A] = R + Me, s[w + A] = I2 + k2, h[w + A + b] = R - Me, s[w + A + b] = I2 - k2, A !== l && (D = n * g - d * _9, _9 = n * _9 + d * g, g = D); + } + }, N.prototype.guessLen13b = function(i, a) { + var h = Math.max(a, i) | 1, s = h & 1, u = 0; + for (h = h / 2 | 0;h; h = h >>> 1) + u++; + return 1 << u + 1 + s; + }, N.prototype.conjugate = function(i, a, h) { + if (!(h <= 1)) + for (var s = 0;s < h / 2; s++) { + var u = i[s]; + i[s] = i[h - s - 1], i[h - s - 1] = u, u = a[s], a[s] = -a[h - s - 1], a[h - s - 1] = -u; + } + }, N.prototype.normalize13b = function(i, a) { + for (var h = 0, s = 0;s < a / 2; s++) { + var u = Math.round(i[2 * s + 1] / a) * 8192 + Math.round(i[2 * s] / a) + h; + i[s] = u & 67108863, u < 67108864 ? h = 0 : h = u / 67108864 | 0; + } + return i; + }, N.prototype.convert13b = function(i, a, h, s) { + for (var u = 0, c = 0;c < a; c++) + u = u + (i[c] | 0), h[2 * c] = u & 8191, u = u >>> 13, h[2 * c + 1] = u & 8191, u = u >>> 13; + for (c = 2 * a;c < s; ++c) + h[c] = 0; + r(u === 0), r((u & -8192) === 0); + }, N.prototype.stub = function(i) { + for (var a = new Array(i), h = 0;h < i; h++) + a[h] = 0; + return a; + }, N.prototype.mulp = function(i, a, h) { + var s = 2 * this.guessLen13b(i.length, a.length), u = this.makeRBT(s), c = this.stub(s), b = new Array(s), l = new Array(s), n = new Array(s), d = new Array(s), w = new Array(s), g = new Array(s), _9 = h.words; + _9.length = s, this.convert13b(i.words, i.length, b, s), this.convert13b(a.words, a.length, d, s), this.transform(b, c, l, n, s, u), this.transform(d, c, w, g, s, u); + for (var A = 0;A < s; A++) { + var R = l[A] * w[A] - n[A] * g[A]; + n[A] = l[A] * g[A] + n[A] * w[A], l[A] = R; + } + return this.conjugate(l, n, s), this.transform(l, n, _9, c, s, u), this.conjugate(_9, c, s), this.normalize13b(_9, s), h.negative = i.negative ^ a.negative, h.length = i.length + a.length, h.strip(); + }, f.prototype.mul = function(i) { + var a = new f(null); + return a.words = new Array(this.length + i.length), this.mulTo(i, a); + }, f.prototype.mulf = function(i) { + var a = new f(null); + return a.words = new Array(this.length + i.length), _e(this, i, a); + }, f.prototype.imul = function(i) { + return this.clone().mulTo(i, this); + }, f.prototype.imuln = function(i) { + r(typeof i == "number"), r(i < 67108864); + for (var a = 0, h = 0;h < this.length; h++) { + var s = (this.words[h] | 0) * i, u = (s & 67108863) + (a & 67108863); + a >>= 26, a += s / 67108864 | 0, a += u >>> 26, this.words[h] = u & 67108863; + } + return a !== 0 && (this.words[h] = a, this.length++), this; + }, f.prototype.muln = function(i) { + return this.clone().imuln(i); + }, f.prototype.sqr = function() { + return this.mul(this); + }, f.prototype.isqr = function() { + return this.imul(this.clone()); + }, f.prototype.pow = function(i) { + var a = B(i); + if (a.length === 0) + return new f(1); + for (var h = this, s = 0;s < a.length && a[s] === 0; s++, h = h.sqr()) + ; + if (++s < a.length) + for (var u = h.sqr();s < a.length; s++, u = u.sqr()) + a[s] !== 0 && (h = h.mul(u)); + return h; + }, f.prototype.iushln = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26, s = 67108863 >>> 26 - a << 26 - a, u; + if (a !== 0) { + var c = 0; + for (u = 0;u < this.length; u++) { + var b = this.words[u] & s, l = (this.words[u] | 0) - b << a; + this.words[u] = l | c, c = b >>> 26 - a; + } + c && (this.words[u] = c, this.length++); + } + if (h !== 0) { + for (u = this.length - 1;u >= 0; u--) + this.words[u + h] = this.words[u]; + for (u = 0;u < h; u++) + this.words[u] = 0; + this.length += h; + } + return this.strip(); + }, f.prototype.ishln = function(i) { + return r(this.negative === 0), this.iushln(i); + }, f.prototype.iushrn = function(i, a, h) { + r(typeof i == "number" && i >= 0); + var s; + a ? s = (a - a % 26) / 26 : s = 0; + var u = i % 26, c = Math.min((i - u) / 26, this.length), b = 67108863 ^ 67108863 >>> u << u, l = h; + if (s -= c, s = Math.max(0, s), l) { + for (var n = 0;n < c; n++) + l.words[n] = this.words[n]; + l.length = c; + } + if (c !== 0) + if (this.length > c) + for (this.length -= c, n = 0;n < this.length; n++) + this.words[n] = this.words[n + c]; + else + this.words[0] = 0, this.length = 1; + var d = 0; + for (n = this.length - 1;n >= 0 && (d !== 0 || n >= s); n--) { + var w = this.words[n] | 0; + this.words[n] = d << 26 - u | w >>> u, d = w & b; + } + return l && d !== 0 && (l.words[l.length++] = d), this.length === 0 && (this.words[0] = 0, this.length = 1), this.strip(); + }, f.prototype.ishrn = function(i, a, h) { + return r(this.negative === 0), this.iushrn(i, a, h); + }, f.prototype.shln = function(i) { + return this.clone().ishln(i); + }, f.prototype.ushln = function(i) { + return this.clone().iushln(i); + }, f.prototype.shrn = function(i) { + return this.clone().ishrn(i); + }, f.prototype.ushrn = function(i) { + return this.clone().iushrn(i); + }, f.prototype.testn = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26, s = 1 << a; + if (this.length <= h) + return false; + var u = this.words[h]; + return !!(u & s); + }, f.prototype.imaskn = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26; + if (r(this.negative === 0, "imaskn works only with positive numbers"), this.length <= h) + return this; + if (a !== 0 && h++, this.length = Math.min(h, this.length), a !== 0) { + var s = 67108863 ^ 67108863 >>> a << a; + this.words[this.length - 1] &= s; + } + return this.strip(); + }, f.prototype.maskn = function(i) { + return this.clone().imaskn(i); + }, f.prototype.iaddn = function(i) { + return r(typeof i == "number"), r(i < 67108864), i < 0 ? this.isubn(-i) : this.negative !== 0 ? this.length === 1 && (this.words[0] | 0) < i ? (this.words[0] = i - (this.words[0] | 0), this.negative = 0, this) : (this.negative = 0, this.isubn(i), this.negative = 1, this) : this._iaddn(i); + }, f.prototype._iaddn = function(i) { + this.words[0] += i; + for (var a = 0;a < this.length && this.words[a] >= 67108864; a++) + this.words[a] -= 67108864, a === this.length - 1 ? this.words[a + 1] = 1 : this.words[a + 1]++; + return this.length = Math.max(this.length, a + 1), this; + }, f.prototype.isubn = function(i) { + if (r(typeof i == "number"), r(i < 67108864), i < 0) + return this.iaddn(-i); + if (this.negative !== 0) + return this.negative = 0, this.iaddn(i), this.negative = 1, this; + if (this.words[0] -= i, this.length === 1 && this.words[0] < 0) + this.words[0] = -this.words[0], this.negative = 1; + else + for (var a = 0;a < this.length && this.words[a] < 0; a++) + this.words[a] += 67108864, this.words[a + 1] -= 1; + return this.strip(); + }, f.prototype.addn = function(i) { + return this.clone().iaddn(i); + }, f.prototype.subn = function(i) { + return this.clone().isubn(i); + }, f.prototype.iabs = function() { + return this.negative = 0, this; + }, f.prototype.abs = function() { + return this.clone().iabs(); + }, f.prototype._ishlnsubmul = function(i, a, h) { + var s = i.length + h, u; + this._expand(s); + var c, b = 0; + for (u = 0;u < i.length; u++) { + c = (this.words[u + h] | 0) + b; + var l = (i.words[u] | 0) * a; + c -= l & 67108863, b = (c >> 26) - (l / 67108864 | 0), this.words[u + h] = c & 67108863; + } + for (;u < this.length - h; u++) + c = (this.words[u + h] | 0) + b, b = c >> 26, this.words[u + h] = c & 67108863; + if (b === 0) + return this.strip(); + for (r(b === -1), b = 0, u = 0;u < this.length; u++) + c = -(this.words[u] | 0) + b, b = c >> 26, this.words[u] = c & 67108863; + return this.negative = 1, this.strip(); + }, f.prototype._wordDiv = function(i, a) { + var h = this.length - i.length, s = this.clone(), u = i, c = u.words[u.length - 1] | 0, b = this._countBits(c); + h = 26 - b, h !== 0 && (u = u.ushln(h), s.iushln(h), c = u.words[u.length - 1] | 0); + var l = s.length - u.length, n; + if (a !== "mod") { + n = new f(null), n.length = l + 1, n.words = new Array(n.length); + for (var d = 0;d < n.length; d++) + n.words[d] = 0; + } + var w = s.clone()._ishlnsubmul(u, 1, l); + w.negative === 0 && (s = w, n && (n.words[l] = 1)); + for (var g = l - 1;g >= 0; g--) { + var _9 = (s.words[u.length + g] | 0) * 67108864 + (s.words[u.length + g - 1] | 0); + for (_9 = Math.min(_9 / c | 0, 67108863), s._ishlnsubmul(u, _9, g);s.negative !== 0; ) + _9--, s.negative = 0, s._ishlnsubmul(u, 1, g), s.isZero() || (s.negative ^= 1); + n && (n.words[g] = _9); + } + return n && n.strip(), s.strip(), a !== "div" && h !== 0 && s.iushrn(h), { div: n || null, mod: s }; + }, f.prototype.divmod = function(i, a, h) { + if (r(!i.isZero()), this.isZero()) + return { div: new f(0), mod: new f(0) }; + var s, u, c; + return this.negative !== 0 && i.negative === 0 ? (c = this.neg().divmod(i, a), a !== "mod" && (s = c.div.neg()), a !== "div" && (u = c.mod.neg(), h && u.negative !== 0 && u.iadd(i)), { div: s, mod: u }) : this.negative === 0 && i.negative !== 0 ? (c = this.divmod(i.neg(), a), a !== "mod" && (s = c.div.neg()), { div: s, mod: c.mod }) : (this.negative & i.negative) !== 0 ? (c = this.neg().divmod(i.neg(), a), a !== "div" && (u = c.mod.neg(), h && u.negative !== 0 && u.isub(i)), { div: c.div, mod: u }) : i.length > this.length || this.cmp(i) < 0 ? { div: new f(0), mod: this } : i.length === 1 ? a === "div" ? { div: this.divn(i.words[0]), mod: null } : a === "mod" ? { div: null, mod: new f(this.modn(i.words[0])) } : { div: this.divn(i.words[0]), mod: new f(this.modn(i.words[0])) } : this._wordDiv(i, a); + }, f.prototype.div = function(i) { + return this.divmod(i, "div", false).div; + }, f.prototype.mod = function(i) { + return this.divmod(i, "mod", false).mod; + }, f.prototype.umod = function(i) { + return this.divmod(i, "mod", true).mod; + }, f.prototype.divRound = function(i) { + var a = this.divmod(i); + if (a.mod.isZero()) + return a.div; + var h = a.div.negative !== 0 ? a.mod.isub(i) : a.mod, s = i.ushrn(1), u = i.andln(1), c = h.cmp(s); + return c < 0 || u === 1 && c === 0 ? a.div : a.div.negative !== 0 ? a.div.isubn(1) : a.div.iaddn(1); + }, f.prototype.modn = function(i) { + r(i <= 67108863); + for (var a = (1 << 26) % i, h = 0, s = this.length - 1;s >= 0; s--) + h = (a * h + (this.words[s] | 0)) % i; + return h; + }, f.prototype.idivn = function(i) { + r(i <= 67108863); + for (var a = 0, h = this.length - 1;h >= 0; h--) { + var s = (this.words[h] | 0) + a * 67108864; + this.words[h] = s / i | 0, a = s % i; + } + return this.strip(); + }, f.prototype.divn = function(i) { + return this.clone().idivn(i); + }, f.prototype.egcd = function(i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, h = i.clone(); + a.negative !== 0 ? a = a.umod(i) : a = a.clone(); + for (var s = new f(1), u = new f(0), c = new f(0), b = new f(1), l = 0;a.isEven() && h.isEven(); ) + a.iushrn(1), h.iushrn(1), ++l; + for (var n = h.clone(), d = a.clone();!a.isZero(); ) { + for (var w = 0, g = 1;(a.words[0] & g) === 0 && w < 26; ++w, g <<= 1) + ; + if (w > 0) + for (a.iushrn(w);w-- > 0; ) + (s.isOdd() || u.isOdd()) && (s.iadd(n), u.isub(d)), s.iushrn(1), u.iushrn(1); + for (var _9 = 0, A = 1;(h.words[0] & A) === 0 && _9 < 26; ++_9, A <<= 1) + ; + if (_9 > 0) + for (h.iushrn(_9);_9-- > 0; ) + (c.isOdd() || b.isOdd()) && (c.iadd(n), b.isub(d)), c.iushrn(1), b.iushrn(1); + a.cmp(h) >= 0 ? (a.isub(h), s.isub(c), u.isub(b)) : (h.isub(a), c.isub(s), b.isub(u)); + } + return { a: c, b, gcd: h.iushln(l) }; + }, f.prototype._invmp = function(i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, h = i.clone(); + a.negative !== 0 ? a = a.umod(i) : a = a.clone(); + for (var s = new f(1), u = new f(0), c = h.clone();a.cmpn(1) > 0 && h.cmpn(1) > 0; ) { + for (var b = 0, l = 1;(a.words[0] & l) === 0 && b < 26; ++b, l <<= 1) + ; + if (b > 0) + for (a.iushrn(b);b-- > 0; ) + s.isOdd() && s.iadd(c), s.iushrn(1); + for (var n = 0, d = 1;(h.words[0] & d) === 0 && n < 26; ++n, d <<= 1) + ; + if (n > 0) + for (h.iushrn(n);n-- > 0; ) + u.isOdd() && u.iadd(c), u.iushrn(1); + a.cmp(h) >= 0 ? (a.isub(h), s.isub(u)) : (h.isub(a), u.isub(s)); + } + var w; + return a.cmpn(1) === 0 ? w = s : w = u, w.cmpn(0) < 0 && w.iadd(i), w; + }, f.prototype.gcd = function(i) { + if (this.isZero()) + return i.abs(); + if (i.isZero()) + return this.abs(); + var a = this.clone(), h = i.clone(); + a.negative = 0, h.negative = 0; + for (var s = 0;a.isEven() && h.isEven(); s++) + a.iushrn(1), h.iushrn(1); + do { + for (;a.isEven(); ) + a.iushrn(1); + for (;h.isEven(); ) + h.iushrn(1); + var u = a.cmp(h); + if (u < 0) { + var c = a; + a = h, h = c; + } else if (u === 0 || h.cmpn(1) === 0) + break; + a.isub(h); + } while (true); + return h.iushln(s); + }, f.prototype.invm = function(i) { + return this.egcd(i).a.umod(i); + }, f.prototype.isEven = function() { + return (this.words[0] & 1) === 0; + }, f.prototype.isOdd = function() { + return (this.words[0] & 1) === 1; + }, f.prototype.andln = function(i) { + return this.words[0] & i; + }, f.prototype.bincn = function(i) { + r(typeof i == "number"); + var a = i % 26, h = (i - a) / 26, s = 1 << a; + if (this.length <= h) + return this._expand(h + 1), this.words[h] |= s, this; + for (var u = s, c = h;u !== 0 && c < this.length; c++) { + var b = this.words[c] | 0; + b += u, u = b >>> 26, b &= 67108863, this.words[c] = b; + } + return u !== 0 && (this.words[c] = u, this.length++), this; + }, f.prototype.isZero = function() { + return this.length === 1 && this.words[0] === 0; + }, f.prototype.cmpn = function(i) { + var a = i < 0; + if (this.negative !== 0 && !a) + return -1; + if (this.negative === 0 && a) + return 1; + this.strip(); + var h; + if (this.length > 1) + h = 1; + else { + a && (i = -i), r(i <= 67108863, "Number is too big"); + var s = this.words[0] | 0; + h = s === i ? 0 : s < i ? -1 : 1; + } + return this.negative !== 0 ? -h | 0 : h; + }, f.prototype.cmp = function(i) { + if (this.negative !== 0 && i.negative === 0) + return -1; + if (this.negative === 0 && i.negative !== 0) + return 1; + var a = this.ucmp(i); + return this.negative !== 0 ? -a | 0 : a; + }, f.prototype.ucmp = function(i) { + if (this.length > i.length) + return 1; + if (this.length < i.length) + return -1; + for (var a = 0, h = this.length - 1;h >= 0; h--) { + var s = this.words[h] | 0, u = i.words[h] | 0; + if (s !== u) { + s < u ? a = -1 : s > u && (a = 1); + break; + } + } + return a; + }, f.prototype.gtn = function(i) { + return this.cmpn(i) === 1; + }, f.prototype.gt = function(i) { + return this.cmp(i) === 1; + }, f.prototype.gten = function(i) { + return this.cmpn(i) >= 0; + }, f.prototype.gte = function(i) { + return this.cmp(i) >= 0; + }, f.prototype.ltn = function(i) { + return this.cmpn(i) === -1; + }, f.prototype.lt = function(i) { + return this.cmp(i) === -1; + }, f.prototype.lten = function(i) { + return this.cmpn(i) <= 0; + }, f.prototype.lte = function(i) { + return this.cmp(i) <= 0; + }, f.prototype.eqn = function(i) { + return this.cmpn(i) === 0; + }, f.prototype.eq = function(i) { + return this.cmp(i) === 0; + }, f.red = function(i) { + return new P(i); + }, f.prototype.toRed = function(i) { + return r(!this.red, "Already a number in reduction context"), r(this.negative === 0, "red works only with positives"), i.convertTo(this)._forceRed(i); + }, f.prototype.fromRed = function() { + return r(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); + }, f.prototype._forceRed = function(i) { + return this.red = i, this; + }, f.prototype.forceRed = function(i) { + return r(!this.red, "Already a number in reduction context"), this._forceRed(i); + }, f.prototype.redAdd = function(i) { + return r(this.red, "redAdd works only with red numbers"), this.red.add(this, i); + }, f.prototype.redIAdd = function(i) { + return r(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, i); + }, f.prototype.redSub = function(i) { + return r(this.red, "redSub works only with red numbers"), this.red.sub(this, i); + }, f.prototype.redISub = function(i) { + return r(this.red, "redISub works only with red numbers"), this.red.isub(this, i); + }, f.prototype.redShl = function(i) { + return r(this.red, "redShl works only with red numbers"), this.red.shl(this, i); + }, f.prototype.redMul = function(i) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, i), this.red.mul(this, i); + }, f.prototype.redIMul = function(i) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, i), this.red.imul(this, i); + }, f.prototype.redSqr = function() { + return r(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); + }, f.prototype.redISqr = function() { + return r(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); + }, f.prototype.redSqrt = function() { + return r(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); + }, f.prototype.redInvm = function() { + return r(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); + }, f.prototype.redNeg = function() { + return r(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); + }, f.prototype.redPow = function(i) { + return r(this.red && !i.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, i); + }; + var we = { k256: null, p224: null, p192: null, p25519: null }; + function ye(v, i) { + this.name = v, this.p = new f(i, 16), this.n = this.p.bitLength(), this.k = new f(1).iushln(this.n).isub(this.p), this.tmp = this._tmp(); + } + ye.prototype._tmp = function() { + var i = new f(null); + return i.words = new Array(Math.ceil(this.n / 13)), i; + }, ye.prototype.ireduce = function(i) { + var a = i, h; + do + this.split(a, this.tmp), a = this.imulK(a), a = a.iadd(this.tmp), h = a.bitLength(); + while (h > this.n); + var s = h < this.n ? -1 : a.ucmp(this.p); + return s === 0 ? (a.words[0] = 0, a.length = 1) : s > 0 ? a.isub(this.p) : a.strip !== undefined ? a.strip() : a._strip(), a; + }, ye.prototype.split = function(i, a) { + i.iushrn(this.n, 0, a); + }, ye.prototype.imulK = function(i) { + return i.imul(this.k); + }; + function xe() { + ye.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); + } + o(xe, ye), xe.prototype.split = function(i, a) { + for (var h = 4194303, s = Math.min(i.length, 9), u = 0;u < s; u++) + a.words[u] = i.words[u]; + if (a.length = s, i.length <= 9) { + i.words[0] = 0, i.length = 1; + return; + } + var c = i.words[9]; + for (a.words[a.length++] = c & h, u = 10;u < i.length; u++) { + var b = i.words[u] | 0; + i.words[u - 10] = (b & h) << 4 | c >>> 22, c = b; + } + c >>>= 22, i.words[u - 10] = c, c === 0 && i.length > 10 ? i.length -= 10 : i.length -= 9; + }, xe.prototype.imulK = function(i) { + i.words[i.length] = 0, i.words[i.length + 1] = 0, i.length += 2; + for (var a = 0, h = 0;h < i.length; h++) { + var s = i.words[h] | 0; + a += s * 977, i.words[h] = a & 67108863, a = s * 64 + (a / 67108864 | 0); + } + return i.words[i.length - 1] === 0 && (i.length--, i.words[i.length - 1] === 0 && i.length--), i; + }; + function Re() { + ye.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); + } + o(Re, ye); + function Ee() { + ye.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); + } + o(Ee, ye); + function Ae() { + ye.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); + } + o(Ae, ye), Ae.prototype.imulK = function(i) { + for (var a = 0, h = 0;h < i.length; h++) { + var s = (i.words[h] | 0) * 19 + a, u = s & 67108863; + s >>>= 26, i.words[h] = u, a = s; + } + return a !== 0 && (i.words[i.length++] = a), i; + }, f._prime = function(i) { + if (we[i]) + return we[i]; + var a; + if (i === "k256") + a = new xe; + else if (i === "p224") + a = new Re; + else if (i === "p192") + a = new Ee; + else if (i === "p25519") + a = new Ae; + else + throw new Error("Unknown prime " + i); + return we[i] = a, a; + }; + function P(v) { + if (typeof v == "string") { + var i = f._prime(v); + this.m = i.p, this.prime = i; + } else + r(v.gtn(1), "modulus must be greater than 1"), this.m = v, this.prime = null; + } + P.prototype._verify1 = function(i) { + r(i.negative === 0, "red works only with positives"), r(i.red, "red works only with red numbers"); + }, P.prototype._verify2 = function(i, a) { + r((i.negative | a.negative) === 0, "red works only with positives"), r(i.red && i.red === a.red, "red works only with red numbers"); + }, P.prototype.imod = function(i) { + return this.prime ? this.prime.ireduce(i)._forceRed(this) : i.umod(this.m)._forceRed(this); + }, P.prototype.neg = function(i) { + return i.isZero() ? i.clone() : this.m.sub(i)._forceRed(this); + }, P.prototype.add = function(i, a) { + this._verify2(i, a); + var h = i.add(a); + return h.cmp(this.m) >= 0 && h.isub(this.m), h._forceRed(this); + }, P.prototype.iadd = function(i, a) { + this._verify2(i, a); + var h = i.iadd(a); + return h.cmp(this.m) >= 0 && h.isub(this.m), h; + }, P.prototype.sub = function(i, a) { + this._verify2(i, a); + var h = i.sub(a); + return h.cmpn(0) < 0 && h.iadd(this.m), h._forceRed(this); + }, P.prototype.isub = function(i, a) { + this._verify2(i, a); + var h = i.isub(a); + return h.cmpn(0) < 0 && h.iadd(this.m), h; + }, P.prototype.shl = function(i, a) { + return this._verify1(i), this.imod(i.ushln(a)); + }, P.prototype.imul = function(i, a) { + return this._verify2(i, a), this.imod(i.imul(a)); + }, P.prototype.mul = function(i, a) { + return this._verify2(i, a), this.imod(i.mul(a)); + }, P.prototype.isqr = function(i) { + return this.imul(i, i.clone()); + }, P.prototype.sqr = function(i) { + return this.mul(i, i); + }, P.prototype.sqrt = function(i) { + if (i.isZero()) + return i.clone(); + var a = this.m.andln(3); + if (r(a % 2 === 1), a === 3) { + var h = this.m.add(new f(1)).iushrn(2); + return this.pow(i, h); + } + for (var s = this.m.subn(1), u = 0;!s.isZero() && s.andln(1) === 0; ) + u++, s.iushrn(1); + r(!s.isZero()); + var c = new f(1).toRed(this), b = c.redNeg(), l = this.m.subn(1).iushrn(1), n = this.m.bitLength(); + for (n = new f(2 * n * n).toRed(this);this.pow(n, l).cmp(b) !== 0; ) + n.redIAdd(b); + for (var d = this.pow(n, s), w = this.pow(i, s.addn(1).iushrn(1)), g = this.pow(i, s), _9 = u;g.cmp(c) !== 0; ) { + for (var A = g, R = 0;A.cmp(c) !== 0; R++) + A = A.redSqr(); + r(R < _9); + var I2 = this.pow(d, new f(1).iushln(_9 - R - 1)); + w = w.redMul(I2), d = I2.redSqr(), g = g.redMul(d), _9 = R; + } + return w; + }, P.prototype.invm = function(i) { + var a = i._invmp(this.m); + return a.negative !== 0 ? (a.negative = 0, this.imod(a).redNeg()) : this.imod(a); + }, P.prototype.pow = function(i, a) { + if (a.isZero()) + return new f(1).toRed(this); + if (a.cmpn(1) === 0) + return i.clone(); + var h = 4, s = new Array(1 << h); + s[0] = new f(1).toRed(this), s[1] = i; + for (var u = 2;u < s.length; u++) + s[u] = this.mul(s[u - 1], i); + var c = s[0], b = 0, l = 0, n = a.bitLength() % 26; + for (n === 0 && (n = 26), u = a.length - 1;u >= 0; u--) { + for (var d = a.words[u], w = n - 1;w >= 0; w--) { + var g = d >> w & 1; + if (c !== s[0] && (c = this.sqr(c)), g === 0 && b === 0) { + l = 0; + continue; + } + b <<= 1, b |= g, l++, !(l !== h && (u !== 0 || w !== 0)) && (c = this.mul(c, s[b]), l = 0, b = 0); + } + n = 26; + } + return c; + }, P.prototype.convertTo = function(i) { + var a = i.umod(this.m); + return a === i ? a.clone() : a; + }, P.prototype.convertFrom = function(i) { + var a = i.clone(); + return a.red = null, a; + }, f.mont = function(i) { + return new Se2(i); + }; + function Se2(v) { + P.call(this, v), this.shift = this.m.bitLength(), this.shift % 26 !== 0 && (this.shift += 26 - this.shift % 26), this.r = new f(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv); + } + o(Se2, P), Se2.prototype.convertTo = function(i) { + return this.imod(i.ushln(this.shift)); + }, Se2.prototype.convertFrom = function(i) { + var a = this.imod(i.mul(this.rinv)); + return a.red = null, a; + }, Se2.prototype.imul = function(i, a) { + if (i.isZero() || a.isZero()) + return i.words[0] = 0, i.length = 1, i; + var h = i.imul(a), s = h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = h.isub(s).iushrn(this.shift), c = u; + return u.cmp(this.m) >= 0 ? c = u.isub(this.m) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }, Se2.prototype.mul = function(i, a) { + if (i.isZero() || a.isZero()) + return new f(0)._forceRed(this); + var h = i.mul(a), s = h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = h.isub(s).iushrn(this.shift), c = u; + return u.cmp(this.m) >= 0 ? c = u.isub(this.m) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }, Se2.prototype.invm = function(i) { + var a = this.imod(i._invmp(this.m).mul(this.r2)); + return a._forceRed(this); + }; + })(typeof Ll > "u" || Ll, h2); + }); + Nl = T((d2) => { + var js = d2; + function uA(t, e) { + if (Array.isArray(t)) + return t.slice(); + if (!t) + return []; + var r = []; + if (typeof t != "string") { + for (var o = 0;o < t.length; o++) + r[o] = t[o] | 0; + return r; + } + if (e === "hex") { + t = t.replace(/[^a-z0-9]+/ig, ""), t.length % 2 !== 0 && (t = "0" + t); + for (var o = 0;o < t.length; o += 2) + r.push(parseInt(t[o] + t[o + 1], 16)); + } else + for (var o = 0;o < t.length; o++) { + var f = t.charCodeAt(o), p = f >> 8, m = f & 255; + p ? r.push(p, m) : r.push(m); + } + return r; + } + js.toArray = uA; + function u2(t) { + return t.length === 1 ? "0" + t : t; + } + js.zero2 = u2; + function l2(t) { + for (var e = "", r = 0;r < t.length; r++) + e += u2(t[r].toString(16)); + return e; + } + js.toHex = l2; + js.encode = function(e, r) { + return r === "hex" ? l2(e) : e; + }; + }); + or = T((c2) => { + var Pr = c2, lA = ri(), dA = ar(), Zs = Nl(); + Pr.assert = dA; + Pr.toArray = Zs.toArray; + Pr.zero2 = Zs.zero2; + Pr.toHex = Zs.toHex; + Pr.encode = Zs.encode; + function cA(t, e, r) { + var o = new Array(Math.max(t.bitLength(), r) + 1); + o.fill(0); + for (var f = 1 << e + 1, p = t.clone(), m = 0;m < o.length; m++) { + var y, M = p.andln(f - 1); + p.isOdd() ? (M > (f >> 1) - 1 ? y = (f >> 1) - M : y = M, p.isubn(y)) : y = 0, o[m] = y, p.iushrn(1); + } + return o; + } + Pr.getNAF = cA; + function pA(t, e) { + var r = [[], []]; + t = t.clone(), e = e.clone(); + for (var o = 0, f = 0, p;t.cmpn(-o) > 0 || e.cmpn(-f) > 0; ) { + var m = t.andln(3) + o & 3, y = e.andln(3) + f & 3; + m === 3 && (m = -1), y === 3 && (y = -1); + var M; + (m & 1) === 0 ? M = 0 : (p = t.andln(7) + o & 7, (p === 3 || p === 5) && y === 2 ? M = -m : M = m), r[0].push(M); + var x; + (y & 1) === 0 ? x = 0 : (p = e.andln(7) + f & 7, (p === 3 || p === 5) && m === 2 ? x = -y : x = y), r[1].push(x), 2 * o === M + 1 && (o = 1 - o), 2 * f === x + 1 && (f = 1 - f), t.iushrn(1), e.iushrn(1); + } + return r; + } + Pr.getJSF = pA; + function vA(t, e, r) { + var o = "_" + e; + t.prototype[e] = function() { + return this[o] !== undefined ? this[o] : this[o] = r.call(this); + }; + } + Pr.cachedProperty = vA; + function bA(t) { + return typeof t == "string" ? Pr.toArray(t, "hex") : t; + } + Pr.parseBytes = bA; + function mA(t) { + return new lA(t, "hex", "le"); + } + Pr.intFromLE = mA; + }); + Oa = T((xk, p2) => { + var Cn = ri(), Ca = or(), Vs = Ca.getNAF, gA = Ca.getJSF, $s = Ca.assert; + function Xi(t, e) { + this.type = t, this.p = new Cn(e.p, 16), this.red = e.prime ? Cn.red(e.prime) : Cn.mont(this.p), this.zero = new Cn(0).toRed(this.red), this.one = new Cn(1).toRed(this.red), this.two = new Cn(2).toRed(this.red), this.n = e.n && new Cn(e.n, 16), this.g = e.g && this.pointFromJSON(e.g, e.gRed), this._wnafT1 = new Array(4), this._wnafT2 = new Array(4), this._wnafT3 = new Array(4), this._wnafT4 = new Array(4), this._bitLength = this.n ? this.n.bitLength() : 0; + var r = this.n && this.p.div(this.n); + !r || r.cmpn(100) > 0 ? this.redN = null : (this._maxwellTrick = true, this.redN = this.n.toRed(this.red)); + } + p2.exports = Xi; + Xi.prototype.point = function() { + throw new Error("Not implemented"); + }; + Xi.prototype.validate = function() { + throw new Error("Not implemented"); + }; + Xi.prototype._fixedNafMul = function(e, r) { + $s(e.precomputed); + var o = e._getDoubles(), f = Vs(r, 1, this._bitLength), p = (1 << o.step + 1) - (o.step % 2 === 0 ? 2 : 1); + p /= 3; + var m = [], y, M; + for (y = 0;y < f.length; y += o.step) { + M = 0; + for (var x = y + o.step - 1;x >= y; x--) + M = (M << 1) + f[x]; + m.push(M); + } + for (var S = this.jpoint(null, null, null), E2 = this.jpoint(null, null, null), B = p;B > 0; B--) { + for (y = 0;y < m.length; y++) + M = m[y], M === B ? E2 = E2.mixedAdd(o.points[y]) : M === -B && (E2 = E2.mixedAdd(o.points[y].neg())); + S = S.add(E2); + } + return S.toP(); + }; + Xi.prototype._wnafMul = function(e, r) { + var o = 4, f = e._getNAFPoints(o); + o = f.wnd; + for (var p = f.points, m = Vs(r, o, this._bitLength), y = this.jpoint(null, null, null), M = m.length - 1;M >= 0; M--) { + for (var x = 0;M >= 0 && m[M] === 0; M--) + x++; + if (M >= 0 && x++, y = y.dblp(x), M < 0) + break; + var S = m[M]; + $s(S !== 0), e.type === "affine" ? S > 0 ? y = y.mixedAdd(p[S - 1 >> 1]) : y = y.mixedAdd(p[-S - 1 >> 1].neg()) : S > 0 ? y = y.add(p[S - 1 >> 1]) : y = y.add(p[-S - 1 >> 1].neg()); + } + return e.type === "affine" ? y.toP() : y; + }; + Xi.prototype._wnafMulAdd = function(e, r, o, f, p) { + var m = this._wnafT1, y = this._wnafT2, M = this._wnafT3, x = 0, S, E2, B; + for (S = 0;S < f; S++) { + B = r[S]; + var q = B._getNAFPoints(e); + m[S] = q.wnd, y[S] = q.points; + } + for (S = f - 1;S >= 1; S -= 2) { + var L = S - 1, ge = S; + if (m[L] !== 1 || m[ge] !== 1) { + M[L] = Vs(o[L], m[L], this._bitLength), M[ge] = Vs(o[ge], m[ge], this._bitLength), x = Math.max(M[L].length, x), x = Math.max(M[ge].length, x); + continue; + } + var _e = [r[L], null, null, r[ge]]; + r[L].y.cmp(r[ge].y) === 0 ? (_e[1] = r[L].add(r[ge]), _e[2] = r[L].toJ().mixedAdd(r[ge].neg())) : r[L].y.cmp(r[ge].y.redNeg()) === 0 ? (_e[1] = r[L].toJ().mixedAdd(r[ge]), _e[2] = r[L].add(r[ge].neg())) : (_e[1] = r[L].toJ().mixedAdd(r[ge]), _e[2] = r[L].toJ().mixedAdd(r[ge].neg())); + var N = [-3, -1, -5, -7, 0, 7, 5, 1, 3], we = gA(o[L], o[ge]); + for (x = Math.max(we[0].length, x), M[L] = new Array(x), M[ge] = new Array(x), E2 = 0;E2 < x; E2++) { + var ye = we[0][E2] | 0, xe = we[1][E2] | 0; + M[L][E2] = N[(ye + 1) * 3 + (xe + 1)], M[ge][E2] = 0, y[L] = _e; + } + } + var Re = this.jpoint(null, null, null), Ee = this._wnafT4; + for (S = x;S >= 0; S--) { + for (var Ae = 0;S >= 0; ) { + var P = true; + for (E2 = 0;E2 < f; E2++) + Ee[E2] = M[E2][S] | 0, Ee[E2] !== 0 && (P = false); + if (!P) + break; + Ae++, S--; + } + if (S >= 0 && Ae++, Re = Re.dblp(Ae), S < 0) + break; + for (E2 = 0;E2 < f; E2++) { + var Se2 = Ee[E2]; + Se2 !== 0 && (Se2 > 0 ? B = y[E2][Se2 - 1 >> 1] : Se2 < 0 && (B = y[E2][-Se2 - 1 >> 1].neg()), B.type === "affine" ? Re = Re.mixedAdd(B) : Re = Re.add(B)); + } + } + for (S = 0;S < f; S++) + y[S] = null; + return p ? Re : Re.toP(); + }; + function _r(t, e) { + this.curve = t, this.type = e, this.precomputed = null; + } + Xi.BasePoint = _r; + _r.prototype.eq = function() { + throw new Error("Not implemented"); + }; + _r.prototype.validate = function() { + return this.curve.validate(this); + }; + Xi.prototype.decodePoint = function(e, r) { + e = Ca.toArray(e, r); + var o = this.p.byteLength(); + if ((e[0] === 4 || e[0] === 6 || e[0] === 7) && e.length - 1 === 2 * o) { + e[0] === 6 ? $s(e[e.length - 1] % 2 === 0) : e[0] === 7 && $s(e[e.length - 1] % 2 === 1); + var f = this.point(e.slice(1, 1 + o), e.slice(1 + o, 1 + 2 * o)); + return f; + } else if ((e[0] === 2 || e[0] === 3) && e.length - 1 === o) + return this.pointFromX(e.slice(1, 1 + o), e[0] === 3); + throw new Error("Unknown point format"); + }; + _r.prototype.encodeCompressed = function(e) { + return this.encode(e, true); + }; + _r.prototype._encode = function(e) { + var r = this.curve.p.byteLength(), o = this.getX().toArray("be", r); + return e ? [this.getY().isEven() ? 2 : 3].concat(o) : [4].concat(o, this.getY().toArray("be", r)); + }; + _r.prototype.encode = function(e, r) { + return Ca.encode(this._encode(r), e); + }; + _r.prototype.precompute = function(e) { + if (this.precomputed) + return this; + var r = { doubles: null, naf: null, beta: null }; + return r.naf = this._getNAFPoints(8), r.doubles = this._getDoubles(4, e), r.beta = this._getBeta(), this.precomputed = r, this; + }; + _r.prototype._hasDoubles = function(e) { + if (!this.precomputed) + return false; + var r = this.precomputed.doubles; + return r ? r.points.length >= Math.ceil((e.bitLength() + 1) / r.step) : false; + }; + _r.prototype._getDoubles = function(e, r) { + if (this.precomputed && this.precomputed.doubles) + return this.precomputed.doubles; + for (var o = [this], f = this, p = 0;p < r; p += e) { + for (var m = 0;m < e; m++) + f = f.dbl(); + o.push(f); + } + return { step: e, points: o }; + }; + _r.prototype._getNAFPoints = function(e) { + if (this.precomputed && this.precomputed.naf) + return this.precomputed.naf; + for (var r = [this], o = (1 << e) - 1, f = o === 1 ? null : this.dbl(), p = 1;p < o; p++) + r[p] = r[p - 1].add(f); + return { wnd: e, points: r }; + }; + _r.prototype._getBeta = function() { + return null; + }; + _r.prototype.dblp = function(e) { + for (var r = this, o = 0;o < e; o++) + r = r.dbl(); + return r; + }; + }); + b2 = T((Sk, v2) => { + var yA = or(), lt = ri(), Dl = Ie(), Bf = Oa(), wA = yA.assert; + function xr(t) { + Bf.call(this, "short", t), this.a = new lt(t.a, 16).toRed(this.red), this.b = new lt(t.b, 16).toRed(this.red), this.tinv = this.two.redInvm(), this.zeroA = this.a.fromRed().cmpn(0) === 0, this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0, this.endo = this._getEndomorphism(t), this._endoWnafT1 = new Array(4), this._endoWnafT2 = new Array(4); + } + Dl(xr, Bf); + v2.exports = xr; + xr.prototype._getEndomorphism = function(e) { + if (!(!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)) { + var r, o; + if (e.beta) + r = new lt(e.beta, 16).toRed(this.red); + else { + var f = this._getEndoRoots(this.p); + r = f[0].cmp(f[1]) < 0 ? f[0] : f[1], r = r.toRed(this.red); + } + if (e.lambda) + o = new lt(e.lambda, 16); + else { + var p = this._getEndoRoots(this.n); + this.g.mul(p[0]).x.cmp(this.g.x.redMul(r)) === 0 ? o = p[0] : (o = p[1], wA(this.g.mul(o).x.cmp(this.g.x.redMul(r)) === 0)); + } + var m; + return e.basis ? m = e.basis.map(function(y) { + return { a: new lt(y.a, 16), b: new lt(y.b, 16) }; + }) : m = this._getEndoBasis(o), { beta: r, lambda: o, basis: m }; + } + }; + xr.prototype._getEndoRoots = function(e) { + var r = e === this.p ? this.red : lt.mont(e), o = new lt(2).toRed(r).redInvm(), f = o.redNeg(), p = new lt(3).toRed(r).redNeg().redSqrt().redMul(o), m = f.redAdd(p).fromRed(), y = f.redSub(p).fromRed(); + return [m, y]; + }; + xr.prototype._getEndoBasis = function(e) { + for (var r = this.n.ushrn(Math.floor(this.n.bitLength() / 2)), o = e, f = this.n.clone(), p = new lt(1), m = new lt(0), y = new lt(0), M = new lt(1), x, S, E2, B, q, L, ge, _e = 0, N, we;o.cmpn(0) !== 0; ) { + var ye = f.div(o); + N = f.sub(ye.mul(o)), we = y.sub(ye.mul(p)); + var xe = M.sub(ye.mul(m)); + if (!E2 && N.cmp(r) < 0) + x = ge.neg(), S = p, E2 = N.neg(), B = we; + else if (E2 && ++_e === 2) + break; + ge = N, f = o, o = N, y = p, p = we, M = m, m = xe; + } + q = N.neg(), L = we; + var Re = E2.sqr().add(B.sqr()), Ee = q.sqr().add(L.sqr()); + return Ee.cmp(Re) >= 0 && (q = x, L = S), E2.negative && (E2 = E2.neg(), B = B.neg()), q.negative && (q = q.neg(), L = L.neg()), [{ a: E2, b: B }, { a: q, b: L }]; + }; + xr.prototype._endoSplit = function(e) { + var r = this.endo.basis, o = r[0], f = r[1], p = f.b.mul(e).divRound(this.n), m = o.b.neg().mul(e).divRound(this.n), y = p.mul(o.a), M = m.mul(f.a), x = p.mul(o.b), S = m.mul(f.b), E2 = e.sub(y).sub(M), B = x.add(S).neg(); + return { k1: E2, k2: B }; + }; + xr.prototype.pointFromX = function(e, r) { + e = new lt(e, 16), e.red || (e = e.toRed(this.red)); + var o = e.redSqr().redMul(e).redIAdd(e.redMul(this.a)).redIAdd(this.b), f = o.redSqrt(); + if (f.redSqr().redSub(o).cmp(this.zero) !== 0) + throw new Error("invalid point"); + var p = f.fromRed().isOdd(); + return (r && !p || !r && p) && (f = f.redNeg()), this.point(e, f); + }; + xr.prototype.validate = function(e) { + if (e.inf) + return true; + var { x: r, y: o } = e, f = this.a.redMul(r), p = r.redSqr().redMul(r).redIAdd(f).redIAdd(this.b); + return o.redSqr().redISub(p).cmpn(0) === 0; + }; + xr.prototype._endoWnafMulAdd = function(e, r, o) { + for (var f = this._endoWnafT1, p = this._endoWnafT2, m = 0;m < e.length; m++) { + var y = this._endoSplit(r[m]), M = e[m], x = M._getBeta(); + y.k1.negative && (y.k1.ineg(), M = M.neg(true)), y.k2.negative && (y.k2.ineg(), x = x.neg(true)), f[m * 2] = M, f[m * 2 + 1] = x, p[m * 2] = y.k1, p[m * 2 + 1] = y.k2; + } + for (var S = this._wnafMulAdd(1, f, p, m * 2, o), E2 = 0;E2 < m * 2; E2++) + f[E2] = null, p[E2] = null; + return S; + }; + function Ct(t, e, r, o) { + Bf.BasePoint.call(this, t, "affine"), e === null && r === null ? (this.x = null, this.y = null, this.inf = true) : (this.x = new lt(e, 16), this.y = new lt(r, 16), o && (this.x.forceRed(this.curve.red), this.y.forceRed(this.curve.red)), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.y.red || (this.y = this.y.toRed(this.curve.red)), this.inf = false); + } + Dl(Ct, Bf.BasePoint); + xr.prototype.point = function(e, r, o) { + return new Ct(this, e, r, o); + }; + xr.prototype.pointFromJSON = function(e, r) { + return Ct.fromJSON(this, e, r); + }; + Ct.prototype._getBeta = function() { + if (!!this.curve.endo) { + var e = this.precomputed; + if (e && e.beta) + return e.beta; + var r = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (e) { + var o = this.curve, f = function(p) { + return o.point(p.x.redMul(o.endo.beta), p.y); + }; + e.beta = r, r.precomputed = { beta: null, naf: e.naf && { wnd: e.naf.wnd, points: e.naf.points.map(f) }, doubles: e.doubles && { step: e.doubles.step, points: e.doubles.points.map(f) } }; + } + return r; + } + }; + Ct.prototype.toJSON = function() { + return this.precomputed ? [this.x, this.y, this.precomputed && { doubles: this.precomputed.doubles && { step: this.precomputed.doubles.step, points: this.precomputed.doubles.points.slice(1) }, naf: this.precomputed.naf && { wnd: this.precomputed.naf.wnd, points: this.precomputed.naf.points.slice(1) } }] : [this.x, this.y]; + }; + Ct.fromJSON = function(e, r, o) { + typeof r == "string" && (r = JSON.parse(r)); + var f = e.point(r[0], r[1], o); + if (!r[2]) + return f; + function p(y) { + return e.point(y[0], y[1], o); + } + var m = r[2]; + return f.precomputed = { beta: null, doubles: m.doubles && { step: m.doubles.step, points: [f].concat(m.doubles.points.map(p)) }, naf: m.naf && { wnd: m.naf.wnd, points: [f].concat(m.naf.points.map(p)) } }, f; + }; + Ct.prototype.inspect = function() { + return this.isInfinity() ? "" : ""; + }; + Ct.prototype.isInfinity = function() { + return this.inf; + }; + Ct.prototype.add = function(e) { + if (this.inf) + return e; + if (e.inf) + return this; + if (this.eq(e)) + return this.dbl(); + if (this.neg().eq(e)) + return this.curve.point(null, null); + if (this.x.cmp(e.x) === 0) + return this.curve.point(null, null); + var r = this.y.redSub(e.y); + r.cmpn(0) !== 0 && (r = r.redMul(this.x.redSub(e.x).redInvm())); + var o = r.redSqr().redISub(this.x).redISub(e.x), f = r.redMul(this.x.redSub(o)).redISub(this.y); + return this.curve.point(o, f); + }; + Ct.prototype.dbl = function() { + if (this.inf) + return this; + var e = this.y.redAdd(this.y); + if (e.cmpn(0) === 0) + return this.curve.point(null, null); + var r = this.curve.a, o = this.x.redSqr(), f = e.redInvm(), p = o.redAdd(o).redIAdd(o).redIAdd(r).redMul(f), m = p.redSqr().redISub(this.x.redAdd(this.x)), y = p.redMul(this.x.redSub(m)).redISub(this.y); + return this.curve.point(m, y); + }; + Ct.prototype.getX = function() { + return this.x.fromRed(); + }; + Ct.prototype.getY = function() { + return this.y.fromRed(); + }; + Ct.prototype.mul = function(e) { + return e = new lt(e, 16), this.isInfinity() ? this : this._hasDoubles(e) ? this.curve._fixedNafMul(this, e) : this.curve.endo ? this.curve._endoWnafMulAdd([this], [e]) : this.curve._wnafMul(this, e); + }; + Ct.prototype.mulAdd = function(e, r, o) { + var f = [this, r], p = [e, o]; + return this.curve.endo ? this.curve._endoWnafMulAdd(f, p) : this.curve._wnafMulAdd(1, f, p, 2); + }; + Ct.prototype.jmulAdd = function(e, r, o) { + var f = [this, r], p = [e, o]; + return this.curve.endo ? this.curve._endoWnafMulAdd(f, p, true) : this.curve._wnafMulAdd(1, f, p, 2, true); + }; + Ct.prototype.eq = function(e) { + return this === e || this.inf === e.inf && (this.inf || this.x.cmp(e.x) === 0 && this.y.cmp(e.y) === 0); + }; + Ct.prototype.neg = function(e) { + if (this.inf) + return this; + var r = this.curve.point(this.x, this.y.redNeg()); + if (e && this.precomputed) { + var o = this.precomputed, f = function(p) { + return p.neg(); + }; + r.precomputed = { naf: o.naf && { wnd: o.naf.wnd, points: o.naf.points.map(f) }, doubles: o.doubles && { step: o.doubles.step, points: o.doubles.points.map(f) } }; + } + return r; + }; + Ct.prototype.toJ = function() { + if (this.inf) + return this.curve.jpoint(null, null, null); + var e = this.curve.jpoint(this.x, this.y, this.curve.one); + return e; + }; + function Wt(t, e, r, o) { + Bf.BasePoint.call(this, t, "jacobian"), e === null && r === null && o === null ? (this.x = this.curve.one, this.y = this.curve.one, this.z = new lt(0)) : (this.x = new lt(e, 16), this.y = new lt(r, 16), this.z = new lt(o, 16)), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.y.red || (this.y = this.y.toRed(this.curve.red)), this.z.red || (this.z = this.z.toRed(this.curve.red)), this.zOne = this.z === this.curve.one; + } + Dl(Wt, Bf.BasePoint); + xr.prototype.jpoint = function(e, r, o) { + return new Wt(this, e, r, o); + }; + Wt.prototype.toP = function() { + if (this.isInfinity()) + return this.curve.point(null, null); + var e = this.z.redInvm(), r = e.redSqr(), o = this.x.redMul(r), f = this.y.redMul(r).redMul(e); + return this.curve.point(o, f); + }; + Wt.prototype.neg = function() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); + }; + Wt.prototype.add = function(e) { + if (this.isInfinity()) + return e; + if (e.isInfinity()) + return this; + var r = e.z.redSqr(), o = this.z.redSqr(), f = this.x.redMul(r), p = e.x.redMul(o), m = this.y.redMul(r.redMul(e.z)), y = e.y.redMul(o.redMul(this.z)), M = f.redSub(p), x = m.redSub(y); + if (M.cmpn(0) === 0) + return x.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); + var S = M.redSqr(), E2 = S.redMul(M), B = f.redMul(S), q = x.redSqr().redIAdd(E2).redISub(B).redISub(B), L = x.redMul(B.redISub(q)).redISub(m.redMul(E2)), ge = this.z.redMul(e.z).redMul(M); + return this.curve.jpoint(q, L, ge); + }; + Wt.prototype.mixedAdd = function(e) { + if (this.isInfinity()) + return e.toJ(); + if (e.isInfinity()) + return this; + var r = this.z.redSqr(), o = this.x, f = e.x.redMul(r), p = this.y, m = e.y.redMul(r).redMul(this.z), y = o.redSub(f), M = p.redSub(m); + if (y.cmpn(0) === 0) + return M.cmpn(0) !== 0 ? this.curve.jpoint(null, null, null) : this.dbl(); + var x = y.redSqr(), S = x.redMul(y), E2 = o.redMul(x), B = M.redSqr().redIAdd(S).redISub(E2).redISub(E2), q = M.redMul(E2.redISub(B)).redISub(p.redMul(S)), L = this.z.redMul(y); + return this.curve.jpoint(B, q, L); + }; + Wt.prototype.dblp = function(e) { + if (e === 0) + return this; + if (this.isInfinity()) + return this; + if (!e) + return this.dbl(); + var r; + if (this.curve.zeroA || this.curve.threeA) { + var o = this; + for (r = 0;r < e; r++) + o = o.dbl(); + return o; + } + var f = this.curve.a, p = this.curve.tinv, m = this.x, y = this.y, M = this.z, x = M.redSqr().redSqr(), S = y.redAdd(y); + for (r = 0;r < e; r++) { + var E2 = m.redSqr(), B = S.redSqr(), q = B.redSqr(), L = E2.redAdd(E2).redIAdd(E2).redIAdd(f.redMul(x)), ge = m.redMul(B), _e = L.redSqr().redISub(ge.redAdd(ge)), N = ge.redISub(_e), we = L.redMul(N); + we = we.redIAdd(we).redISub(q); + var ye = S.redMul(M); + r + 1 < e && (x = x.redMul(q)), m = _e, M = ye, S = we; + } + return this.curve.jpoint(m, S.redMul(p), M); + }; + Wt.prototype.dbl = function() { + return this.isInfinity() ? this : this.curve.zeroA ? this._zeroDbl() : this.curve.threeA ? this._threeDbl() : this._dbl(); + }; + Wt.prototype._zeroDbl = function() { + var e, r, o; + if (this.zOne) { + var f = this.x.redSqr(), p = this.y.redSqr(), m = p.redSqr(), y = this.x.redAdd(p).redSqr().redISub(f).redISub(m); + y = y.redIAdd(y); + var M = f.redAdd(f).redIAdd(f), x = M.redSqr().redISub(y).redISub(y), S = m.redIAdd(m); + S = S.redIAdd(S), S = S.redIAdd(S), e = x, r = M.redMul(y.redISub(x)).redISub(S), o = this.y.redAdd(this.y); + } else { + var E2 = this.x.redSqr(), B = this.y.redSqr(), q = B.redSqr(), L = this.x.redAdd(B).redSqr().redISub(E2).redISub(q); + L = L.redIAdd(L); + var ge = E2.redAdd(E2).redIAdd(E2), _e = ge.redSqr(), N = q.redIAdd(q); + N = N.redIAdd(N), N = N.redIAdd(N), e = _e.redISub(L).redISub(L), r = ge.redMul(L.redISub(e)).redISub(N), o = this.y.redMul(this.z), o = o.redIAdd(o); + } + return this.curve.jpoint(e, r, o); + }; + Wt.prototype._threeDbl = function() { + var e, r, o; + if (this.zOne) { + var f = this.x.redSqr(), p = this.y.redSqr(), m = p.redSqr(), y = this.x.redAdd(p).redSqr().redISub(f).redISub(m); + y = y.redIAdd(y); + var M = f.redAdd(f).redIAdd(f).redIAdd(this.curve.a), x = M.redSqr().redISub(y).redISub(y); + e = x; + var S = m.redIAdd(m); + S = S.redIAdd(S), S = S.redIAdd(S), r = M.redMul(y.redISub(x)).redISub(S), o = this.y.redAdd(this.y); + } else { + var E2 = this.z.redSqr(), B = this.y.redSqr(), q = this.x.redMul(B), L = this.x.redSub(E2).redMul(this.x.redAdd(E2)); + L = L.redAdd(L).redIAdd(L); + var ge = q.redIAdd(q); + ge = ge.redIAdd(ge); + var _e = ge.redAdd(ge); + e = L.redSqr().redISub(_e), o = this.y.redAdd(this.z).redSqr().redISub(B).redISub(E2); + var N = B.redSqr(); + N = N.redIAdd(N), N = N.redIAdd(N), N = N.redIAdd(N), r = L.redMul(ge.redISub(e)).redISub(N); + } + return this.curve.jpoint(e, r, o); + }; + Wt.prototype._dbl = function() { + var e = this.curve.a, r = this.x, o = this.y, f = this.z, p = f.redSqr().redSqr(), m = r.redSqr(), y = o.redSqr(), M = m.redAdd(m).redIAdd(m).redIAdd(e.redMul(p)), x = r.redAdd(r); + x = x.redIAdd(x); + var S = x.redMul(y), E2 = M.redSqr().redISub(S.redAdd(S)), B = S.redISub(E2), q = y.redSqr(); + q = q.redIAdd(q), q = q.redIAdd(q), q = q.redIAdd(q); + var L = M.redMul(B).redISub(q), ge = o.redAdd(o).redMul(f); + return this.curve.jpoint(E2, L, ge); + }; + Wt.prototype.trpl = function() { + if (!this.curve.zeroA) + return this.dbl().add(this); + var e = this.x.redSqr(), r = this.y.redSqr(), o = this.z.redSqr(), f = r.redSqr(), p = e.redAdd(e).redIAdd(e), m = p.redSqr(), y = this.x.redAdd(r).redSqr().redISub(e).redISub(f); + y = y.redIAdd(y), y = y.redAdd(y).redIAdd(y), y = y.redISub(m); + var M = y.redSqr(), x = f.redIAdd(f); + x = x.redIAdd(x), x = x.redIAdd(x), x = x.redIAdd(x); + var S = p.redIAdd(y).redSqr().redISub(m).redISub(M).redISub(x), E2 = r.redMul(S); + E2 = E2.redIAdd(E2), E2 = E2.redIAdd(E2); + var B = this.x.redMul(M).redISub(E2); + B = B.redIAdd(B), B = B.redIAdd(B); + var q = this.y.redMul(S.redMul(x.redISub(S)).redISub(y.redMul(M))); + q = q.redIAdd(q), q = q.redIAdd(q), q = q.redIAdd(q); + var L = this.z.redAdd(y).redSqr().redISub(o).redISub(M); + return this.curve.jpoint(B, q, L); + }; + Wt.prototype.mul = function(e, r) { + return e = new lt(e, r), this.curve._wnafMul(this, e); + }; + Wt.prototype.eq = function(e) { + if (e.type === "affine") + return this.eq(e.toJ()); + if (this === e) + return true; + var r = this.z.redSqr(), o = e.z.redSqr(); + if (this.x.redMul(o).redISub(e.x.redMul(r)).cmpn(0) !== 0) + return false; + var f = r.redMul(this.z), p = o.redMul(e.z); + return this.y.redMul(p).redISub(e.y.redMul(f)).cmpn(0) === 0; + }; + Wt.prototype.eqXToP = function(e) { + var r = this.z.redSqr(), o = e.toRed(this.curve.red).redMul(r); + if (this.x.cmp(o) === 0) + return true; + for (var f = e.clone(), p = this.curve.redN.redMul(r);; ) { + if (f.iadd(this.curve.n), f.cmp(this.curve.p) >= 0) + return false; + if (o.redIAdd(p), this.x.cmp(o) === 0) + return true; + } + }; + Wt.prototype.inspect = function() { + return this.isInfinity() ? "" : ""; + }; + Wt.prototype.isInfinity = function() { + return this.z.cmpn(0) === 0; + }; + }); + y2 = T((Ek, g2) => { + var qf = ri(), m2 = Ie(), Gs = Oa(), MA = or(); + function If(t) { + Gs.call(this, "mont", t), this.a = new qf(t.a, 16).toRed(this.red), this.b = new qf(t.b, 16).toRed(this.red), this.i4 = new qf(4).toRed(this.red).redInvm(), this.two = new qf(2).toRed(this.red), this.a24 = this.i4.redMul(this.a.redAdd(this.two)); + } + m2(If, Gs); + g2.exports = If; + If.prototype.validate = function(e) { + var r = e.normalize().x, o = r.redSqr(), f = o.redMul(r).redAdd(o.redMul(this.a)).redAdd(r), p = f.redSqrt(); + return p.redSqr().cmp(f) === 0; + }; + function Ot(t, e, r) { + Gs.BasePoint.call(this, t, "projective"), e === null && r === null ? (this.x = this.curve.one, this.z = this.curve.zero) : (this.x = new qf(e, 16), this.z = new qf(r, 16), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.z.red || (this.z = this.z.toRed(this.curve.red))); + } + m2(Ot, Gs.BasePoint); + If.prototype.decodePoint = function(e, r) { + return this.point(MA.toArray(e, r), 1); + }; + If.prototype.point = function(e, r) { + return new Ot(this, e, r); + }; + If.prototype.pointFromJSON = function(e) { + return Ot.fromJSON(this, e); + }; + Ot.prototype.precompute = function() { + }; + Ot.prototype._encode = function() { + return this.getX().toArray("be", this.curve.p.byteLength()); + }; + Ot.fromJSON = function(e, r) { + return new Ot(e, r[0], r[1] || e.one); + }; + Ot.prototype.inspect = function() { + return this.isInfinity() ? "" : ""; + }; + Ot.prototype.isInfinity = function() { + return this.z.cmpn(0) === 0; + }; + Ot.prototype.dbl = function() { + var e = this.x.redAdd(this.z), r = e.redSqr(), o = this.x.redSub(this.z), f = o.redSqr(), p = r.redSub(f), m = r.redMul(f), y = p.redMul(f.redAdd(this.curve.a24.redMul(p))); + return this.curve.point(m, y); + }; + Ot.prototype.add = function() { + throw new Error("Not supported on Montgomery curve"); + }; + Ot.prototype.diffAdd = function(e, r) { + var o = this.x.redAdd(this.z), f = this.x.redSub(this.z), p = e.x.redAdd(e.z), m = e.x.redSub(e.z), y = m.redMul(o), M = p.redMul(f), x = r.z.redMul(y.redAdd(M).redSqr()), S = r.x.redMul(y.redISub(M).redSqr()); + return this.curve.point(x, S); + }; + Ot.prototype.mul = function(e) { + for (var r = e.clone(), o = this, f = this.curve.point(null, null), p = this, m = [];r.cmpn(0) !== 0; r.iushrn(1)) + m.push(r.andln(1)); + for (var y = m.length - 1;y >= 0; y--) + m[y] === 0 ? (o = o.diffAdd(f, p), f = f.dbl()) : (f = o.diffAdd(f, p), o = o.dbl()); + return f; + }; + Ot.prototype.mulAdd = function() { + throw new Error("Not supported on Montgomery curve"); + }; + Ot.prototype.jumlAdd = function() { + throw new Error("Not supported on Montgomery curve"); + }; + Ot.prototype.eq = function(e) { + return this.getX().cmp(e.getX()) === 0; + }; + Ot.prototype.normalize = function() { + return this.x = this.x.redMul(this.z.redInvm()), this.z = this.curve.one, this; + }; + Ot.prototype.getX = function() { + return this.normalize(), this.x.fromRed(); + }; + }); + _22 = T((Ak, M2) => { + var _A = or(), Ai = ri(), w2 = Ie(), Ys = Oa(), xA = _A.assert; + function ii(t) { + this.twisted = (t.a | 0) !== 1, this.mOneA = this.twisted && (t.a | 0) === -1, this.extended = this.mOneA, Ys.call(this, "edwards", t), this.a = new Ai(t.a, 16).umod(this.red.m), this.a = this.a.toRed(this.red), this.c = new Ai(t.c, 16).toRed(this.red), this.c2 = this.c.redSqr(), this.d = new Ai(t.d, 16).toRed(this.red), this.dd = this.d.redAdd(this.d), xA(!this.twisted || this.c.fromRed().cmpn(1) === 0), this.oneC = (t.c | 0) === 1; + } + w2(ii, Ys); + M2.exports = ii; + ii.prototype._mulA = function(e) { + return this.mOneA ? e.redNeg() : this.a.redMul(e); + }; + ii.prototype._mulC = function(e) { + return this.oneC ? e : this.c.redMul(e); + }; + ii.prototype.jpoint = function(e, r, o, f) { + return this.point(e, r, o, f); + }; + ii.prototype.pointFromX = function(e, r) { + e = new Ai(e, 16), e.red || (e = e.toRed(this.red)); + var o = e.redSqr(), f = this.c2.redSub(this.a.redMul(o)), p = this.one.redSub(this.c2.redMul(this.d).redMul(o)), m = f.redMul(p.redInvm()), y = m.redSqrt(); + if (y.redSqr().redSub(m).cmp(this.zero) !== 0) + throw new Error("invalid point"); + var M = y.fromRed().isOdd(); + return (r && !M || !r && M) && (y = y.redNeg()), this.point(e, y); + }; + ii.prototype.pointFromY = function(e, r) { + e = new Ai(e, 16), e.red || (e = e.toRed(this.red)); + var o = e.redSqr(), f = o.redSub(this.c2), p = o.redMul(this.d).redMul(this.c2).redSub(this.a), m = f.redMul(p.redInvm()); + if (m.cmp(this.zero) === 0) { + if (r) + throw new Error("invalid point"); + return this.point(this.zero, e); + } + var y = m.redSqrt(); + if (y.redSqr().redSub(m).cmp(this.zero) !== 0) + throw new Error("invalid point"); + return y.fromRed().isOdd() !== r && (y = y.redNeg()), this.point(y, e); + }; + ii.prototype.validate = function(e) { + if (e.isInfinity()) + return true; + e.normalize(); + var r = e.x.redSqr(), o = e.y.redSqr(), f = r.redMul(this.a).redAdd(o), p = this.c2.redMul(this.one.redAdd(this.d.redMul(r).redMul(o))); + return f.cmp(p) === 0; + }; + function at(t, e, r, o, f) { + Ys.BasePoint.call(this, t, "projective"), e === null && r === null && o === null ? (this.x = this.curve.zero, this.y = this.curve.one, this.z = this.curve.one, this.t = this.curve.zero, this.zOne = true) : (this.x = new Ai(e, 16), this.y = new Ai(r, 16), this.z = o ? new Ai(o, 16) : this.curve.one, this.t = f && new Ai(f, 16), this.x.red || (this.x = this.x.toRed(this.curve.red)), this.y.red || (this.y = this.y.toRed(this.curve.red)), this.z.red || (this.z = this.z.toRed(this.curve.red)), this.t && !this.t.red && (this.t = this.t.toRed(this.curve.red)), this.zOne = this.z === this.curve.one, this.curve.extended && !this.t && (this.t = this.x.redMul(this.y), this.zOne || (this.t = this.t.redMul(this.z.redInvm())))); + } + w2(at, Ys.BasePoint); + ii.prototype.pointFromJSON = function(e) { + return at.fromJSON(this, e); + }; + ii.prototype.point = function(e, r, o, f) { + return new at(this, e, r, o, f); + }; + at.fromJSON = function(e, r) { + return new at(e, r[0], r[1], r[2]); + }; + at.prototype.inspect = function() { + return this.isInfinity() ? "" : ""; + }; + at.prototype.isInfinity = function() { + return this.x.cmpn(0) === 0 && (this.y.cmp(this.z) === 0 || this.zOne && this.y.cmp(this.curve.c) === 0); + }; + at.prototype._extDbl = function() { + var e = this.x.redSqr(), r = this.y.redSqr(), o = this.z.redSqr(); + o = o.redIAdd(o); + var f = this.curve._mulA(e), p = this.x.redAdd(this.y).redSqr().redISub(e).redISub(r), m = f.redAdd(r), y = m.redSub(o), M = f.redSub(r), x = p.redMul(y), S = m.redMul(M), E2 = p.redMul(M), B = y.redMul(m); + return this.curve.point(x, S, B, E2); + }; + at.prototype._projDbl = function() { + var e = this.x.redAdd(this.y).redSqr(), r = this.x.redSqr(), o = this.y.redSqr(), f, p, m, y, M, x; + if (this.curve.twisted) { + y = this.curve._mulA(r); + var S = y.redAdd(o); + this.zOne ? (f = e.redSub(r).redSub(o).redMul(S.redSub(this.curve.two)), p = S.redMul(y.redSub(o)), m = S.redSqr().redSub(S).redSub(S)) : (M = this.z.redSqr(), x = S.redSub(M).redISub(M), f = e.redSub(r).redISub(o).redMul(x), p = S.redMul(y.redSub(o)), m = S.redMul(x)); + } else + y = r.redAdd(o), M = this.curve._mulC(this.z).redSqr(), x = y.redSub(M).redSub(M), f = this.curve._mulC(e.redISub(y)).redMul(x), p = this.curve._mulC(y).redMul(r.redISub(o)), m = y.redMul(x); + return this.curve.point(f, p, m); + }; + at.prototype.dbl = function() { + return this.isInfinity() ? this : this.curve.extended ? this._extDbl() : this._projDbl(); + }; + at.prototype._extAdd = function(e) { + var r = this.y.redSub(this.x).redMul(e.y.redSub(e.x)), o = this.y.redAdd(this.x).redMul(e.y.redAdd(e.x)), f = this.t.redMul(this.curve.dd).redMul(e.t), p = this.z.redMul(e.z.redAdd(e.z)), m = o.redSub(r), y = p.redSub(f), M = p.redAdd(f), x = o.redAdd(r), S = m.redMul(y), E2 = M.redMul(x), B = m.redMul(x), q = y.redMul(M); + return this.curve.point(S, E2, q, B); + }; + at.prototype._projAdd = function(e) { + var r = this.z.redMul(e.z), o = r.redSqr(), f = this.x.redMul(e.x), p = this.y.redMul(e.y), m = this.curve.d.redMul(f).redMul(p), y = o.redSub(m), M = o.redAdd(m), x = this.x.redAdd(this.y).redMul(e.x.redAdd(e.y)).redISub(f).redISub(p), S = r.redMul(y).redMul(x), E2, B; + return this.curve.twisted ? (E2 = r.redMul(M).redMul(p.redSub(this.curve._mulA(f))), B = y.redMul(M)) : (E2 = r.redMul(M).redMul(p.redSub(f)), B = this.curve._mulC(y).redMul(M)), this.curve.point(S, E2, B); + }; + at.prototype.add = function(e) { + return this.isInfinity() ? e : e.isInfinity() ? this : this.curve.extended ? this._extAdd(e) : this._projAdd(e); + }; + at.prototype.mul = function(e) { + return this._hasDoubles(e) ? this.curve._fixedNafMul(this, e) : this.curve._wnafMul(this, e); + }; + at.prototype.mulAdd = function(e, r, o) { + return this.curve._wnafMulAdd(1, [this, r], [e, o], 2, false); + }; + at.prototype.jmulAdd = function(e, r, o) { + return this.curve._wnafMulAdd(1, [this, r], [e, o], 2, true); + }; + at.prototype.normalize = function() { + if (this.zOne) + return this; + var e = this.z.redInvm(); + return this.x = this.x.redMul(e), this.y = this.y.redMul(e), this.t && (this.t = this.t.redMul(e)), this.z = this.curve.one, this.zOne = true, this; + }; + at.prototype.neg = function() { + return this.curve.point(this.x.redNeg(), this.y, this.z, this.t && this.t.redNeg()); + }; + at.prototype.getX = function() { + return this.normalize(), this.x.fromRed(); + }; + at.prototype.getY = function() { + return this.normalize(), this.y.fromRed(); + }; + at.prototype.eq = function(e) { + return this === e || this.getX().cmp(e.getX()) === 0 && this.getY().cmp(e.getY()) === 0; + }; + at.prototype.eqXToP = function(e) { + var r = e.toRed(this.curve.red).redMul(this.z); + if (this.x.cmp(r) === 0) + return true; + for (var o = e.clone(), f = this.curve.redN.redMul(this.z);; ) { + if (o.iadd(this.curve.n), o.cmp(this.curve.p) >= 0) + return false; + if (r.redIAdd(f), this.x.cmp(r) === 0) + return true; + } + }; + at.prototype.toP = at.prototype.normalize; + at.prototype.mixedAdd = at.prototype.add; + }); + Pl = T((x2) => { + var Xs = x2; + Xs.base = Oa(); + Xs.short = b2(); + Xs.mont = y2(); + Xs.edwards = _22(); + }); + Cr2 = T((it) => { + var SA = ar(), EA = Ie(); + it.inherits = EA; + function AA(t, e) { + return (t.charCodeAt(e) & 64512) !== 55296 || e < 0 || e + 1 >= t.length ? false : (t.charCodeAt(e + 1) & 64512) === 56320; + } + function RA(t, e) { + if (Array.isArray(t)) + return t.slice(); + if (!t) + return []; + var r = []; + if (typeof t == "string") + if (e) { + if (e === "hex") + for (t = t.replace(/[^a-z0-9]+/ig, ""), t.length % 2 !== 0 && (t = "0" + t), f = 0;f < t.length; f += 2) + r.push(parseInt(t[f] + t[f + 1], 16)); + } else + for (var o = 0, f = 0;f < t.length; f++) { + var p = t.charCodeAt(f); + p < 128 ? r[o++] = p : p < 2048 ? (r[o++] = p >> 6 | 192, r[o++] = p & 63 | 128) : AA(t, f) ? (p = 65536 + ((p & 1023) << 10) + (t.charCodeAt(++f) & 1023), r[o++] = p >> 18 | 240, r[o++] = p >> 12 & 63 | 128, r[o++] = p >> 6 & 63 | 128, r[o++] = p & 63 | 128) : (r[o++] = p >> 12 | 224, r[o++] = p >> 6 & 63 | 128, r[o++] = p & 63 | 128); + } + else + for (f = 0;f < t.length; f++) + r[f] = t[f] | 0; + return r; + } + it.toArray = RA; + function BA(t) { + for (var e = "", r = 0;r < t.length; r++) + e += E2(t[r].toString(16)); + return e; + } + it.toHex = BA; + function S2(t) { + var e = t >>> 24 | t >>> 8 & 65280 | t << 8 & 16711680 | (t & 255) << 24; + return e >>> 0; + } + it.htonl = S2; + function qA(t, e) { + for (var r = "", o = 0;o < t.length; o++) { + var f = t[o]; + e === "little" && (f = S2(f)), r += A2(f.toString(16)); + } + return r; + } + it.toHex32 = qA; + function E2(t) { + return t.length === 1 ? "0" + t : t; + } + it.zero2 = E2; + function A2(t) { + return t.length === 7 ? "0" + t : t.length === 6 ? "00" + t : t.length === 5 ? "000" + t : t.length === 4 ? "0000" + t : t.length === 3 ? "00000" + t : t.length === 2 ? "000000" + t : t.length === 1 ? "0000000" + t : t; + } + it.zero8 = A2; + function IA(t, e, r, o) { + var f = r - e; + SA(f % 4 === 0); + for (var p = new Array(f / 4), m = 0, y = e;m < p.length; m++, y += 4) { + var M; + o === "big" ? M = t[y] << 24 | t[y + 1] << 16 | t[y + 2] << 8 | t[y + 3] : M = t[y + 3] << 24 | t[y + 2] << 16 | t[y + 1] << 8 | t[y], p[m] = M >>> 0; + } + return p; + } + it.join32 = IA; + function TA(t, e) { + for (var r = new Array(t.length * 4), o = 0, f = 0;o < t.length; o++, f += 4) { + var p = t[o]; + e === "big" ? (r[f] = p >>> 24, r[f + 1] = p >>> 16 & 255, r[f + 2] = p >>> 8 & 255, r[f + 3] = p & 255) : (r[f + 3] = p >>> 24, r[f + 2] = p >>> 16 & 255, r[f + 1] = p >>> 8 & 255, r[f] = p & 255); + } + return r; + } + it.split32 = TA; + function kA(t, e) { + return t >>> e | t << 32 - e; + } + it.rotr32 = kA; + function LA(t, e) { + return t << e | t >>> 32 - e; + } + it.rotl32 = LA; + function NA(t, e) { + return t + e >>> 0; + } + it.sum32 = NA; + function DA(t, e, r) { + return t + e + r >>> 0; + } + it.sum32_3 = DA; + function PA(t, e, r, o) { + return t + e + r + o >>> 0; + } + it.sum32_4 = PA; + function CA(t, e, r, o, f) { + return t + e + r + o + f >>> 0; + } + it.sum32_5 = CA; + function OA(t, e, r, o) { + var f = t[e], p = t[e + 1], m = o + p >>> 0, y = (m < o ? 1 : 0) + r + f; + t[e] = y >>> 0, t[e + 1] = m; + } + it.sum64 = OA; + function FA(t, e, r, o) { + var f = e + o >>> 0, p = (f < e ? 1 : 0) + t + r; + return p >>> 0; + } + it.sum64_hi = FA; + function UA(t, e, r, o) { + var f = e + o; + return f >>> 0; + } + it.sum64_lo = UA; + function zA(t, e, r, o, f, p, m, y) { + var M = 0, x = e; + x = x + o >>> 0, M += x < e ? 1 : 0, x = x + p >>> 0, M += x < p ? 1 : 0, x = x + y >>> 0, M += x < y ? 1 : 0; + var S = t + r + f + m + M; + return S >>> 0; + } + it.sum64_4_hi = zA; + function HA(t, e, r, o, f, p, m, y) { + var M = e + o + p + y; + return M >>> 0; + } + it.sum64_4_lo = HA; + function WA(t, e, r, o, f, p, m, y, M, x) { + var S = 0, E3 = e; + E3 = E3 + o >>> 0, S += E3 < e ? 1 : 0, E3 = E3 + p >>> 0, S += E3 < p ? 1 : 0, E3 = E3 + y >>> 0, S += E3 < y ? 1 : 0, E3 = E3 + x >>> 0, S += E3 < x ? 1 : 0; + var B = t + r + f + m + M + S; + return B >>> 0; + } + it.sum64_5_hi = WA; + function KA(t, e, r, o, f, p, m, y, M, x) { + var S = e + o + p + y + x; + return S >>> 0; + } + it.sum64_5_lo = KA; + function jA(t, e, r) { + var o = e << 32 - r | t >>> r; + return o >>> 0; + } + it.rotr64_hi = jA; + function ZA(t, e, r) { + var o = t << 32 - r | e >>> r; + return o >>> 0; + } + it.rotr64_lo = ZA; + function VA(t, e, r) { + return t >>> r; + } + it.shr64_hi = VA; + function $A(t, e, r) { + var o = t << 32 - r | e >>> r; + return o >>> 0; + } + it.shr64_lo = $A; + }); + Tf = T((B2) => { + var R2 = Cr2(), GA = ar(); + function Js() { + this.pending = null, this.pendingTotal = 0, this.blockSize = this.constructor.blockSize, this.outSize = this.constructor.outSize, this.hmacStrength = this.constructor.hmacStrength, this.padLength = this.constructor.padLength / 8, this.endian = "big", this._delta8 = this.blockSize / 8, this._delta32 = this.blockSize / 32; + } + B2.BlockHash = Js; + Js.prototype.update = function(e, r) { + if (e = R2.toArray(e, r), this.pending ? this.pending = this.pending.concat(e) : this.pending = e, this.pendingTotal += e.length, this.pending.length >= this._delta8) { + e = this.pending; + var o = e.length % this._delta8; + this.pending = e.slice(e.length - o, e.length), this.pending.length === 0 && (this.pending = null), e = R2.join32(e, 0, e.length - o, this.endian); + for (var f = 0;f < e.length; f += this._delta32) + this._update(e, f, f + this._delta32); + } + return this; + }; + Js.prototype.digest = function(e) { + return this.update(this._pad()), GA(this.pending === null), this._digest(e); + }; + Js.prototype._pad = function() { + var e = this.pendingTotal, r = this._delta8, o = r - (e + this.padLength) % r, f = new Array(o + this.padLength); + f[0] = 128; + for (var p = 1;p < o; p++) + f[p] = 0; + if (e <<= 3, this.endian === "big") { + for (var m = 8;m < this.padLength; m++) + f[p++] = 0; + f[p++] = 0, f[p++] = 0, f[p++] = 0, f[p++] = 0, f[p++] = e >>> 24 & 255, f[p++] = e >>> 16 & 255, f[p++] = e >>> 8 & 255, f[p++] = e & 255; + } else + for (f[p++] = e & 255, f[p++] = e >>> 8 & 255, f[p++] = e >>> 16 & 255, f[p++] = e >>> 24 & 255, f[p++] = 0, f[p++] = 0, f[p++] = 0, f[p++] = 0, m = 8;m < this.padLength; m++) + f[p++] = 0; + return f; + }; + }); + Cl = T((Ri) => { + var YA = Cr2(), ni = YA.rotr32; + function XA(t, e, r, o) { + if (t === 0) + return q2(e, r, o); + if (t === 1 || t === 3) + return T2(e, r, o); + if (t === 2) + return I2(e, r, o); + } + Ri.ft_1 = XA; + function q2(t, e, r) { + return t & e ^ ~t & r; + } + Ri.ch32 = q2; + function I2(t, e, r) { + return t & e ^ t & r ^ e & r; + } + Ri.maj32 = I2; + function T2(t, e, r) { + return t ^ e ^ r; + } + Ri.p32 = T2; + function JA(t) { + return ni(t, 2) ^ ni(t, 13) ^ ni(t, 22); + } + Ri.s0_256 = JA; + function QA(t) { + return ni(t, 6) ^ ni(t, 11) ^ ni(t, 25); + } + Ri.s1_256 = QA; + function eR(t) { + return ni(t, 7) ^ ni(t, 18) ^ t >>> 3; + } + Ri.g0_256 = eR; + function tR(t) { + return ni(t, 17) ^ ni(t, 19) ^ t >>> 10; + } + Ri.g1_256 = tR; + }); + N2 = T((Tk, L2) => { + var kf = Cr2(), rR = Tf(), iR = Cl(), Ol = kf.rotl32, Fa = kf.sum32, nR = kf.sum32_5, fR = iR.ft_1, k2 = rR.BlockHash, aR = [1518500249, 1859775393, 2400959708, 3395469782]; + function fi() { + if (!(this instanceof fi)) + return new fi; + k2.call(this), this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.W = new Array(80); + } + kf.inherits(fi, k2); + L2.exports = fi; + fi.blockSize = 512; + fi.outSize = 160; + fi.hmacStrength = 80; + fi.padLength = 64; + fi.prototype._update = function(e, r) { + for (var o = this.W, f = 0;f < 16; f++) + o[f] = e[r + f]; + for (;f < o.length; f++) + o[f] = Ol(o[f - 3] ^ o[f - 8] ^ o[f - 14] ^ o[f - 16], 1); + var p = this.h[0], m = this.h[1], y = this.h[2], M = this.h[3], x = this.h[4]; + for (f = 0;f < o.length; f++) { + var S = ~~(f / 20), E2 = nR(Ol(p, 5), fR(S, m, y, M), x, o[f], aR[S]); + x = M, M = y, y = Ol(m, 30), m = p, p = E2; + } + this.h[0] = Fa(this.h[0], p), this.h[1] = Fa(this.h[1], m), this.h[2] = Fa(this.h[2], y), this.h[3] = Fa(this.h[3], M), this.h[4] = Fa(this.h[4], x); + }; + fi.prototype._digest = function(e) { + return e === "hex" ? kf.toHex32(this.h, "big") : kf.split32(this.h, "big"); + }; + }); + Fl = T((kk, P2) => { + var Lf = Cr2(), oR = Tf(), Nf = Cl(), sR = ar(), Or = Lf.sum32, hR = Lf.sum32_4, uR = Lf.sum32_5, lR = Nf.ch32, dR = Nf.maj32, cR = Nf.s0_256, pR = Nf.s1_256, vR = Nf.g0_256, bR = Nf.g1_256, D2 = oR.BlockHash, mR = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298]; + function ai() { + if (!(this instanceof ai)) + return new ai; + D2.call(this), this.h = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225], this.k = mR, this.W = new Array(64); + } + Lf.inherits(ai, D2); + P2.exports = ai; + ai.blockSize = 512; + ai.outSize = 256; + ai.hmacStrength = 192; + ai.padLength = 64; + ai.prototype._update = function(e, r) { + for (var o = this.W, f = 0;f < 16; f++) + o[f] = e[r + f]; + for (;f < o.length; f++) + o[f] = hR(bR(o[f - 2]), o[f - 7], vR(o[f - 15]), o[f - 16]); + var p = this.h[0], m = this.h[1], y = this.h[2], M = this.h[3], x = this.h[4], S = this.h[5], E2 = this.h[6], B = this.h[7]; + for (sR(this.k.length === o.length), f = 0;f < o.length; f++) { + var q = uR(B, pR(x), lR(x, S, E2), this.k[f], o[f]), L = Or(cR(p), dR(p, m, y)); + B = E2, E2 = S, S = x, x = Or(M, q), M = y, y = m, m = p, p = Or(q, L); + } + this.h[0] = Or(this.h[0], p), this.h[1] = Or(this.h[1], m), this.h[2] = Or(this.h[2], y), this.h[3] = Or(this.h[3], M), this.h[4] = Or(this.h[4], x), this.h[5] = Or(this.h[5], S), this.h[6] = Or(this.h[6], E2), this.h[7] = Or(this.h[7], B); + }; + ai.prototype._digest = function(e) { + return e === "hex" ? Lf.toHex32(this.h, "big") : Lf.split32(this.h, "big"); + }; + }); + F2 = T((Lk, O2) => { + var Ul = Cr2(), C2 = Fl(); + function Bi() { + if (!(this instanceof Bi)) + return new Bi; + C2.call(this), this.h = [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428]; + } + Ul.inherits(Bi, C2); + O2.exports = Bi; + Bi.blockSize = 512; + Bi.outSize = 224; + Bi.hmacStrength = 192; + Bi.padLength = 64; + Bi.prototype._digest = function(e) { + return e === "hex" ? Ul.toHex32(this.h.slice(0, 7), "big") : Ul.split32(this.h.slice(0, 7), "big"); + }; + }); + Wl = T((Nk, W2) => { + var ir2 = Cr2(), gR = Tf(), yR = ar(), oi = ir2.rotr64_hi, si = ir2.rotr64_lo, U2 = ir2.shr64_hi, z2 = ir2.shr64_lo, Ji = ir2.sum64, zl = ir2.sum64_hi, Hl = ir2.sum64_lo, wR = ir2.sum64_4_hi, MR = ir2.sum64_4_lo, _R = ir2.sum64_5_hi, xR = ir2.sum64_5_lo, H2 = gR.BlockHash, SR = [1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591]; + function Fr() { + if (!(this instanceof Fr)) + return new Fr; + H2.call(this), this.h = [1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209], this.k = SR, this.W = new Array(160); + } + ir2.inherits(Fr, H2); + W2.exports = Fr; + Fr.blockSize = 1024; + Fr.outSize = 512; + Fr.hmacStrength = 192; + Fr.padLength = 128; + Fr.prototype._prepareBlock = function(e, r) { + for (var o = this.W, f = 0;f < 32; f++) + o[f] = e[r + f]; + for (;f < o.length; f += 2) { + var p = DR(o[f - 4], o[f - 3]), m = PR(o[f - 4], o[f - 3]), y = o[f - 14], M = o[f - 13], x = LR(o[f - 30], o[f - 29]), S = NR(o[f - 30], o[f - 29]), E2 = o[f - 32], B = o[f - 31]; + o[f] = wR(p, m, y, M, x, S, E2, B), o[f + 1] = MR(p, m, y, M, x, S, E2, B); + } + }; + Fr.prototype._update = function(e, r) { + this._prepareBlock(e, r); + var o = this.W, f = this.h[0], p = this.h[1], m = this.h[2], y = this.h[3], M = this.h[4], x = this.h[5], S = this.h[6], E2 = this.h[7], B = this.h[8], q = this.h[9], L = this.h[10], ge = this.h[11], _e = this.h[12], N = this.h[13], we = this.h[14], ye = this.h[15]; + yR(this.k.length === o.length); + for (var xe = 0;xe < o.length; xe += 2) { + var Re = we, Ee = ye, Ae = TR(B, q), P = kR(B, q), Se2 = ER(B, q, L, ge, _e, N), v = AR(B, q, L, ge, _e, N), i = this.k[xe], a = this.k[xe + 1], h = o[xe], s = o[xe + 1], u = _R(Re, Ee, Ae, P, Se2, v, i, a, h, s), c = xR(Re, Ee, Ae, P, Se2, v, i, a, h, s); + Re = qR(f, p), Ee = IR(f, p), Ae = RR(f, p, m, y, M, x), P = BR(f, p, m, y, M, x); + var b = zl(Re, Ee, Ae, P), l = Hl(Re, Ee, Ae, P); + we = _e, ye = N, _e = L, N = ge, L = B, ge = q, B = zl(S, E2, u, c), q = Hl(E2, E2, u, c), S = M, E2 = x, M = m, x = y, m = f, y = p, f = zl(u, c, b, l), p = Hl(u, c, b, l); + } + Ji(this.h, 0, f, p), Ji(this.h, 2, m, y), Ji(this.h, 4, M, x), Ji(this.h, 6, S, E2), Ji(this.h, 8, B, q), Ji(this.h, 10, L, ge), Ji(this.h, 12, _e, N), Ji(this.h, 14, we, ye); + }; + Fr.prototype._digest = function(e) { + return e === "hex" ? ir2.toHex32(this.h, "big") : ir2.split32(this.h, "big"); + }; + function ER(t, e, r, o, f) { + var p = t & r ^ ~t & f; + return p < 0 && (p += 4294967296), p; + } + function AR(t, e, r, o, f, p) { + var m = e & o ^ ~e & p; + return m < 0 && (m += 4294967296), m; + } + function RR(t, e, r, o, f) { + var p = t & r ^ t & f ^ r & f; + return p < 0 && (p += 4294967296), p; + } + function BR(t, e, r, o, f, p) { + var m = e & o ^ e & p ^ o & p; + return m < 0 && (m += 4294967296), m; + } + function qR(t, e) { + var r = oi(t, e, 28), o = oi(e, t, 2), f = oi(e, t, 7), p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function IR(t, e) { + var r = si(t, e, 28), o = si(e, t, 2), f = si(e, t, 7), p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function TR(t, e) { + var r = oi(t, e, 14), o = oi(t, e, 18), f = oi(e, t, 9), p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function kR(t, e) { + var r = si(t, e, 14), o = si(t, e, 18), f = si(e, t, 9), p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function LR(t, e) { + var r = oi(t, e, 1), o = oi(t, e, 8), f = U2(t, e, 7), p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function NR(t, e) { + var r = si(t, e, 1), o = si(t, e, 8), f = z2(t, e, 7), p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function DR(t, e) { + var r = oi(t, e, 19), o = oi(e, t, 29), f = U2(t, e, 6), p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + function PR(t, e) { + var r = si(t, e, 19), o = si(e, t, 29), f = z2(t, e, 6), p = r ^ o ^ f; + return p < 0 && (p += 4294967296), p; + } + }); + Z2 = T((Dk, j2) => { + var Kl = Cr2(), K2 = Wl(); + function qi() { + if (!(this instanceof qi)) + return new qi; + K2.call(this), this.h = [3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428]; + } + Kl.inherits(qi, K2); + j2.exports = qi; + qi.blockSize = 1024; + qi.outSize = 384; + qi.hmacStrength = 192; + qi.padLength = 128; + qi.prototype._digest = function(e) { + return e === "hex" ? Kl.toHex32(this.h.slice(0, 12), "big") : Kl.split32(this.h.slice(0, 12), "big"); + }; + }); + V2 = T((Df) => { + Df.sha1 = N2(); + Df.sha224 = F2(); + Df.sha256 = Fl(); + Df.sha384 = Z2(); + Df.sha512 = Wl(); + }); + Q2 = T((J2) => { + var On = Cr2(), CR = Tf(), Qs = On.rotl32, $2 = On.sum32, Ua = On.sum32_3, G2 = On.sum32_4, X2 = CR.BlockHash; + function hi() { + if (!(this instanceof hi)) + return new hi; + X2.call(this), this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520], this.endian = "little"; + } + On.inherits(hi, X2); + J2.ripemd160 = hi; + hi.blockSize = 512; + hi.outSize = 160; + hi.hmacStrength = 192; + hi.padLength = 64; + hi.prototype._update = function(e, r) { + for (var o = this.h[0], f = this.h[1], p = this.h[2], m = this.h[3], y = this.h[4], M = o, x = f, S = p, E2 = m, B = y, q = 0;q < 80; q++) { + var L = $2(Qs(G2(o, Y2(q, f, p, m), e[UR[q] + r], OR(q)), HR[q]), y); + o = y, y = m, m = Qs(p, 10), p = f, f = L, L = $2(Qs(G2(M, Y2(79 - q, x, S, E2), e[zR[q] + r], FR(q)), WR[q]), B), M = B, B = E2, E2 = Qs(S, 10), S = x, x = L; + } + L = Ua(this.h[1], p, E2), this.h[1] = Ua(this.h[2], m, B), this.h[2] = Ua(this.h[3], y, M), this.h[3] = Ua(this.h[4], o, x), this.h[4] = Ua(this.h[0], f, S), this.h[0] = L; + }; + hi.prototype._digest = function(e) { + return e === "hex" ? On.toHex32(this.h, "little") : On.split32(this.h, "little"); + }; + function Y2(t, e, r, o) { + return t <= 15 ? e ^ r ^ o : t <= 31 ? e & r | ~e & o : t <= 47 ? (e | ~r) ^ o : t <= 63 ? e & o | r & ~o : e ^ (r | ~o); + } + function OR(t) { + return t <= 15 ? 0 : t <= 31 ? 1518500249 : t <= 47 ? 1859775393 : t <= 63 ? 2400959708 : 2840853838; + } + function FR(t) { + return t <= 15 ? 1352829926 : t <= 31 ? 1548603684 : t <= 47 ? 1836072691 : t <= 63 ? 2053994217 : 0; + } + var UR = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13], zR = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11], HR = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6], WR = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]; + }); + ty = T((Ok, ey) => { + var KR = Cr2(), jR = ar(); + function Pf(t, e, r) { + if (!(this instanceof Pf)) + return new Pf(t, e, r); + this.Hash = t, this.blockSize = t.blockSize / 8, this.outSize = t.outSize / 8, this.inner = null, this.outer = null, this._init(KR.toArray(e, r)); + } + ey.exports = Pf; + Pf.prototype._init = function(e) { + e.length > this.blockSize && (e = new this.Hash().update(e).digest()), jR(e.length <= this.blockSize); + for (var r = e.length;r < this.blockSize; r++) + e.push(0); + for (r = 0;r < e.length; r++) + e[r] ^= 54; + for (this.inner = new this.Hash().update(e), r = 0;r < e.length; r++) + e[r] ^= 106; + this.outer = new this.Hash().update(e); + }; + Pf.prototype.update = function(e, r) { + return this.inner.update(e, r), this; + }; + Pf.prototype.digest = function(e) { + return this.outer.update(this.inner.digest()), this.outer.digest(e); + }; + }); + e0 = T((ry) => { + var Kt = ry; + Kt.utils = Cr2(); + Kt.common = Tf(); + Kt.sha = V2(); + Kt.ripemd = Q2(); + Kt.hmac = ty(); + Kt.sha1 = Kt.sha.sha1; + Kt.sha256 = Kt.sha.sha256; + Kt.sha224 = Kt.sha.sha224; + Kt.sha384 = Kt.sha.sha384; + Kt.sha512 = Kt.sha.sha512; + Kt.ripemd160 = Kt.ripemd.ripemd160; + }); + ny = T((Uk, iy) => { + iy.exports = { doubles: { step: 4, points: [["e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a", "f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821"], ["8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508", "11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf"], ["175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739", "d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695"], ["363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640", "4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9"], ["8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c", "4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36"], ["723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda", "96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f"], ["eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa", "5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999"], ["100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0", "cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09"], ["e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d", "9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d"], ["feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d", "e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088"], ["da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1", "9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d"], ["53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0", "5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8"], ["8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047", "10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a"], ["385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862", "283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453"], ["6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7", "7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160"], ["3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd", "56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0"], ["85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83", "7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6"], ["948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a", "53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589"], ["6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8", "bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17"], ["e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d", "4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda"], ["e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725", "7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd"], ["213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754", "4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2"], ["4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c", "17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6"], ["fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6", "6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f"], ["76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39", "c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01"], ["c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891", "893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3"], ["d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b", "febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f"], ["b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03", "2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7"], ["e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d", "eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78"], ["a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070", "7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1"], ["90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4", "e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150"], ["8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da", "662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82"], ["e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11", "1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc"], ["8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e", "efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b"], ["e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41", "2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51"], ["b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef", "67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45"], ["d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8", "db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120"], ["324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d", "648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84"], ["4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96", "35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d"], ["9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd", "ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d"], ["6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5", "9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8"], ["a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266", "40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8"], ["7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71", "34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac"], ["928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac", "c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f"], ["85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751", "1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962"], ["ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e", "493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907"], ["827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241", "c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec"], ["eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3", "be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d"], ["e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f", "4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414"], ["1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19", "aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd"], ["146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be", "b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0"], ["fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9", "6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811"], ["da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2", "8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1"], ["a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13", "7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c"], ["174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c", "ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73"], ["959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba", "2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd"], ["d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151", "e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405"], ["64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073", "d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589"], ["8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458", "38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e"], ["13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b", "69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27"], ["bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366", "d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1"], ["8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa", "40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482"], ["8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0", "620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945"], ["dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787", "7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573"], ["f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e", "ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82"]] }, naf: { wnd: 7, points: [["f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", "388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672"], ["2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4", "d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6"], ["5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc", "6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da"], ["acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe", "cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37"], ["774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb", "d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b"], ["f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8", "ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81"], ["d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e", "581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58"], ["defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34", "4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77"], ["2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c", "85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a"], ["352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5", "321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c"], ["2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f", "2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67"], ["9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714", "73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402"], ["daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729", "a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55"], ["c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db", "2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482"], ["6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4", "e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82"], ["1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5", "b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396"], ["605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479", "2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49"], ["62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d", "80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf"], ["80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f", "1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a"], ["7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb", "d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7"], ["d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9", "eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933"], ["49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963", "758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a"], ["77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74", "958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6"], ["f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530", "e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37"], ["463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b", "5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e"], ["f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247", "cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6"], ["caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1", "cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476"], ["2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120", "4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40"], ["7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435", "91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61"], ["754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18", "673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683"], ["e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8", "59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5"], ["186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb", "3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b"], ["df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f", "55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417"], ["5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143", "efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868"], ["290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba", "e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a"], ["af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45", "f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6"], ["766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a", "744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996"], ["59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e", "c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e"], ["f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8", "e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d"], ["7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c", "30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2"], ["948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519", "e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e"], ["7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab", "100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437"], ["3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca", "ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311"], ["d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf", "8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4"], ["1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610", "68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575"], ["733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4", "f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d"], ["15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c", "d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d"], ["a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940", "edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629"], ["e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980", "a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06"], ["311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3", "66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374"], ["34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf", "9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee"], ["f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63", "4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1"], ["d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448", "fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b"], ["32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf", "5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661"], ["7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5", "8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6"], ["ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6", "8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e"], ["16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5", "5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d"], ["eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99", "f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc"], ["78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51", "f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4"], ["494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5", "42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c"], ["a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5", "204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"], ["c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997", "4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913"], ["841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881", "73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154"], ["5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5", "39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865"], ["36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66", "d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc"], ["336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726", "ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224"], ["8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede", "6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e"], ["1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94", "60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6"], ["85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31", "3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511"], ["29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51", "b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b"], ["a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252", "ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2"], ["4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5", "cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c"], ["d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b", "6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3"], ["ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4", "322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d"], ["af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f", "6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700"], ["e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889", "2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4"], ["591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246", "b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196"], ["11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984", "998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4"], ["3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a", "b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257"], ["cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030", "bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13"], ["c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197", "6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096"], ["c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593", "c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38"], ["a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef", "21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f"], ["347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38", "60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448"], ["da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a", "49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a"], ["c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111", "5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4"], ["4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502", "7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437"], ["3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea", "be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7"], ["cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26", "8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d"], ["b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986", "39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a"], ["d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e", "62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54"], ["48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4", "25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77"], ["dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda", "ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517"], ["6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859", "cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10"], ["e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f", "f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125"], ["eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c", "6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e"], ["13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942", "fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1"], ["ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a", "1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2"], ["b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80", "5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423"], ["ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d", "438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8"], ["8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1", "cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758"], ["52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63", "c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375"], ["e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352", "6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d"], ["7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193", "ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec"], ["5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00", "9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0"], ["32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58", "ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c"], ["e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7", "d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4"], ["8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8", "c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f"], ["4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e", "67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649"], ["3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d", "cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826"], ["674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b", "299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5"], ["d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f", "f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87"], ["30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6", "462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b"], ["be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297", "62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc"], ["93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a", "7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c"], ["b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c", "ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f"], ["d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52", "4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a"], ["d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb", "bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46"], ["463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065", "bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f"], ["7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917", "603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03"], ["74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9", "cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08"], ["30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3", "553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8"], ["9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57", "712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373"], ["176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66", "ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3"], ["75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8", "9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8"], ["809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721", "9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1"], ["1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180", "4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9"]] } }; + }); + t0 = T((oy) => { + var Zl = oy, Qi = e0(), jl = Pl(), ZR = or(), fy = ZR.assert; + function ay(t) { + t.type === "short" ? this.curve = new jl.short(t) : t.type === "edwards" ? this.curve = new jl.edwards(t) : this.curve = new jl.mont(t), this.g = this.curve.g, this.n = this.curve.n, this.hash = t.hash, fy(this.g.validate(), "Invalid curve"), fy(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O"); + } + Zl.PresetCurve = ay; + function en(t, e) { + Object.defineProperty(Zl, t, { configurable: true, enumerable: true, get: function() { + var r = new ay(e); + return Object.defineProperty(Zl, t, { configurable: true, enumerable: true, value: r }), r; + } }); + } + en("p192", { type: "short", prime: "p192", p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", hash: Qi.sha256, gRed: false, g: ["188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811"] }); + en("p224", { type: "short", prime: "p224", p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", hash: Qi.sha256, gRed: false, g: ["b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34"] }); + en("p256", { type: "short", prime: null, p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", hash: Qi.sha256, gRed: false, g: ["6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5"] }); + en("p384", { type: "short", prime: null, p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", hash: Qi.sha384, gRed: false, g: ["aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f"] }); + en("p521", { type: "short", prime: null, p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", hash: Qi.sha512, gRed: false, g: ["000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650"] }); + en("curve25519", { type: "mont", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "76d06", b: "1", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: Qi.sha256, gRed: false, g: ["9"] }); + en("ed25519", { type: "edwards", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "-1", c: "1", d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: Qi.sha256, gRed: false, g: ["216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", "6666666666666666666666666666666666666666666666666666666666666658"] }); + var Vl; + try { + Vl = ny(); + } catch { + Vl = undefined; + } + en("secp256k1", { type: "short", prime: "k256", p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", a: "0", b: "7", n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", h: "1", hash: Qi.sha256, beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", basis: [{ a: "3086d221a7d46bcde86c90e49284eb15", b: "-e4437ed6010e88286f547fa90abfe4c3" }, { a: "114ca50f7a8e2f3f657c1108d9d44cfd8", b: "3086d221a7d46bcde86c90e49284eb15" }], gRed: false, g: ["79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", Vl] }); + }); + uy = T((Hk, hy) => { + var VR = e0(), Fn = Nl(), sy = ar(); + function tn2(t) { + if (!(this instanceof tn2)) + return new tn2(t); + this.hash = t.hash, this.predResist = !!t.predResist, this.outLen = this.hash.outSize, this.minEntropy = t.minEntropy || this.hash.hmacStrength, this._reseed = null, this.reseedInterval = null, this.K = null, this.V = null; + var e = Fn.toArray(t.entropy, t.entropyEnc || "hex"), r = Fn.toArray(t.nonce, t.nonceEnc || "hex"), o = Fn.toArray(t.pers, t.persEnc || "hex"); + sy(e.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), this._init(e, r, o); + } + hy.exports = tn2; + tn2.prototype._init = function(e, r, o) { + var f = e.concat(r).concat(o); + this.K = new Array(this.outLen / 8), this.V = new Array(this.outLen / 8); + for (var p = 0;p < this.V.length; p++) + this.K[p] = 0, this.V[p] = 1; + this._update(f), this._reseed = 1, this.reseedInterval = 281474976710656; + }; + tn2.prototype._hmac = function() { + return new VR.hmac(this.hash, this.K); + }; + tn2.prototype._update = function(e) { + var r = this._hmac().update(this.V).update([0]); + e && (r = r.update(e)), this.K = r.digest(), this.V = this._hmac().update(this.V).digest(), e && (this.K = this._hmac().update(this.V).update([1]).update(e).digest(), this.V = this._hmac().update(this.V).digest()); + }; + tn2.prototype.reseed = function(e, r, o, f) { + typeof r != "string" && (f = o, o = r, r = null), e = Fn.toArray(e, r), o = Fn.toArray(o, f), sy(e.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"), this._update(e.concat(o || [])), this._reseed = 1; + }; + tn2.prototype.generate = function(e, r, o, f) { + if (this._reseed > this.reseedInterval) + throw new Error("Reseed is required"); + typeof r != "string" && (f = o, o = r, r = null), o && (o = Fn.toArray(o, f || "hex"), this._update(o)); + for (var p = [];p.length < e; ) + this.V = this._hmac().update(this.V).digest(), p = p.concat(this.V); + var m = p.slice(0, e); + return this._update(o), this._reseed++, Fn.encode(m, r); + }; + }); + dy = T((Wk, ly) => { + var $R = ri(), GR = or(), $l = GR.assert; + function Gt(t, e) { + this.ec = t, this.priv = null, this.pub = null, e.priv && this._importPrivate(e.priv, e.privEnc), e.pub && this._importPublic(e.pub, e.pubEnc); + } + ly.exports = Gt; + Gt.fromPublic = function(e, r, o) { + return r instanceof Gt ? r : new Gt(e, { pub: r, pubEnc: o }); + }; + Gt.fromPrivate = function(e, r, o) { + return r instanceof Gt ? r : new Gt(e, { priv: r, privEnc: o }); + }; + Gt.prototype.validate = function() { + var e = this.getPublic(); + return e.isInfinity() ? { result: false, reason: "Invalid public key" } : e.validate() ? e.mul(this.ec.curve.n).isInfinity() ? { result: true, reason: null } : { result: false, reason: "Public key * N != O" } : { result: false, reason: "Public key is not a point" }; + }; + Gt.prototype.getPublic = function(e, r) { + return typeof e == "string" && (r = e, e = null), this.pub || (this.pub = this.ec.g.mul(this.priv)), r ? this.pub.encode(r, e) : this.pub; + }; + Gt.prototype.getPrivate = function(e) { + return e === "hex" ? this.priv.toString(16, 2) : this.priv; + }; + Gt.prototype._importPrivate = function(e, r) { + this.priv = new $R(e, r || 16), this.priv = this.priv.umod(this.ec.curve.n); + }; + Gt.prototype._importPublic = function(e, r) { + if (e.x || e.y) { + this.ec.curve.type === "mont" ? $l(e.x, "Need x coordinate") : (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") && $l(e.x && e.y, "Need both x and y coordinate"), this.pub = this.ec.curve.point(e.x, e.y); + return; + } + this.pub = this.ec.curve.decodePoint(e, r); + }; + Gt.prototype.derive = function(e) { + return e.validate() || $l(e.validate(), "public point not validated"), e.mul(this.priv).getX(); + }; + Gt.prototype.sign = function(e, r, o) { + return this.ec.sign(e, this, r, o); + }; + Gt.prototype.verify = function(e, r) { + return this.ec.verify(e, r, this); + }; + Gt.prototype.inspect = function() { + return ""; + }; + }); + vy = T((Kk, py2) => { + var r0 = ri(), Xl = or(), YR = Xl.assert; + function i0(t, e) { + if (t instanceof i0) + return t; + this._importDER(t, e) || (YR(t.r && t.s, "Signature without r or s"), this.r = new r0(t.r, 16), this.s = new r0(t.s, 16), t.recoveryParam === undefined ? this.recoveryParam = null : this.recoveryParam = t.recoveryParam); + } + py2.exports = i0; + function XR() { + this.place = 0; + } + function Gl(t, e) { + var r = t[e.place++]; + if (!(r & 128)) + return r; + var o = r & 15; + if (o === 0 || o > 4) + return false; + for (var f = 0, p = 0, m = e.place;p < o; p++, m++) + f <<= 8, f |= t[m], f >>>= 0; + return f <= 127 ? false : (e.place = m, f); + } + function cy(t) { + for (var e = 0, r = t.length - 1;!t[e] && !(t[e + 1] & 128) && e < r; ) + e++; + return e === 0 ? t : t.slice(e); + } + i0.prototype._importDER = function(e, r) { + e = Xl.toArray(e, r); + var o = new XR; + if (e[o.place++] !== 48) + return false; + var f = Gl(e, o); + if (f === false || f + o.place !== e.length || e[o.place++] !== 2) + return false; + var p = Gl(e, o); + if (p === false) + return false; + var m = e.slice(o.place, p + o.place); + if (o.place += p, e[o.place++] !== 2) + return false; + var y = Gl(e, o); + if (y === false || e.length !== y + o.place) + return false; + var M = e.slice(o.place, y + o.place); + if (m[0] === 0) + if (m[1] & 128) + m = m.slice(1); + else + return false; + if (M[0] === 0) + if (M[1] & 128) + M = M.slice(1); + else + return false; + return this.r = new r0(m), this.s = new r0(M), this.recoveryParam = null, true; + }; + function Yl(t, e) { + if (e < 128) { + t.push(e); + return; + } + var r = 1 + (Math.log(e) / Math.LN2 >>> 3); + for (t.push(r | 128);--r; ) + t.push(e >>> (r << 3) & 255); + t.push(e); + } + i0.prototype.toDER = function(e) { + var r = this.r.toArray(), o = this.s.toArray(); + for (r[0] & 128 && (r = [0].concat(r)), o[0] & 128 && (o = [0].concat(o)), r = cy(r), o = cy(o);!o[0] && !(o[1] & 128); ) + o = o.slice(1); + var f = [2]; + Yl(f, r.length), f = f.concat(r), f.push(2), Yl(f, o.length); + var p = f.concat(o), m = [48]; + return Yl(m, p.length), m = m.concat(p), Xl.encode(m, e); + }; + }); + yy = T((jk, gy) => { + var Un = ri(), by = uy(), JR = or(), Jl = t0(), QR = As(), my = JR.assert, Ql = dy(), n0 = vy(); + function Sr(t) { + if (!(this instanceof Sr)) + return new Sr(t); + typeof t == "string" && (my(Object.prototype.hasOwnProperty.call(Jl, t), "Unknown curve " + t), t = Jl[t]), t instanceof Jl.PresetCurve && (t = { curve: t }), this.curve = t.curve.curve, this.n = this.curve.n, this.nh = this.n.ushrn(1), this.g = this.curve.g, this.g = t.curve.g, this.g.precompute(t.curve.n.bitLength() + 1), this.hash = t.hash || t.curve.hash; + } + gy.exports = Sr; + Sr.prototype.keyPair = function(e) { + return new Ql(this, e); + }; + Sr.prototype.keyFromPrivate = function(e, r) { + return Ql.fromPrivate(this, e, r); + }; + Sr.prototype.keyFromPublic = function(e, r) { + return Ql.fromPublic(this, e, r); + }; + Sr.prototype.genKeyPair = function(e) { + e || (e = {}); + for (var r = new by({ hash: this.hash, pers: e.pers, persEnc: e.persEnc || "utf8", entropy: e.entropy || QR(this.hash.hmacStrength), entropyEnc: e.entropy && e.entropyEnc || "utf8", nonce: this.n.toArray() }), o = this.n.byteLength(), f = this.n.sub(new Un(2));; ) { + var p = new Un(r.generate(o)); + if (!(p.cmp(f) > 0)) + return p.iaddn(1), this.keyFromPrivate(p); + } + }; + Sr.prototype._truncateToN = function(e, r) { + var o = e.byteLength() * 8 - this.n.bitLength(); + return o > 0 && (e = e.ushrn(o)), !r && e.cmp(this.n) >= 0 ? e.sub(this.n) : e; + }; + Sr.prototype.sign = function(e, r, o, f) { + typeof o == "object" && (f = o, o = null), f || (f = {}), r = this.keyFromPrivate(r, o), e = this._truncateToN(new Un(e, 16)); + for (var p = this.n.byteLength(), m = r.getPrivate().toArray("be", p), y = e.toArray("be", p), M = new by({ hash: this.hash, entropy: m, nonce: y, pers: f.pers, persEnc: f.persEnc || "utf8" }), x = this.n.sub(new Un(1)), S = 0;; S++) { + var E2 = f.k ? f.k(S) : new Un(M.generate(this.n.byteLength())); + if (E2 = this._truncateToN(E2, true), !(E2.cmpn(1) <= 0 || E2.cmp(x) >= 0)) { + var B = this.g.mul(E2); + if (!B.isInfinity()) { + var q = B.getX(), L = q.umod(this.n); + if (L.cmpn(0) !== 0) { + var ge = E2.invm(this.n).mul(L.mul(r.getPrivate()).iadd(e)); + if (ge = ge.umod(this.n), ge.cmpn(0) !== 0) { + var _e = (B.getY().isOdd() ? 1 : 0) | (q.cmp(L) !== 0 ? 2 : 0); + return f.canonical && ge.cmp(this.nh) > 0 && (ge = this.n.sub(ge), _e ^= 1), new n0({ r: L, s: ge, recoveryParam: _e }); + } + } + } + } + } + }; + Sr.prototype.verify = function(e, r, o, f) { + e = this._truncateToN(new Un(e, 16)), o = this.keyFromPublic(o, f), r = new n0(r, "hex"); + var { r: p, s: m } = r; + if (p.cmpn(1) < 0 || p.cmp(this.n) >= 0 || m.cmpn(1) < 0 || m.cmp(this.n) >= 0) + return false; + var y = m.invm(this.n), M = y.mul(e).umod(this.n), x = y.mul(p).umod(this.n), S; + return this.curve._maxwellTrick ? (S = this.g.jmulAdd(M, o.getPublic(), x), S.isInfinity() ? false : S.eqXToP(p)) : (S = this.g.mulAdd(M, o.getPublic(), x), S.isInfinity() ? false : S.getX().umod(this.n).cmp(p) === 0); + }; + Sr.prototype.recoverPubKey = function(t, e, r, o) { + my((3 & r) === r, "The recovery param is more than two bits"), e = new n0(e, o); + var f = this.n, p = new Un(t), m = e.r, y = e.s, M = r & 1, x = r >> 1; + if (m.cmp(this.curve.p.umod(this.curve.n)) >= 0 && x) + throw new Error("Unable to find sencond key candinate"); + x ? m = this.curve.pointFromX(m.add(this.curve.n), M) : m = this.curve.pointFromX(m, M); + var S = e.r.invm(f), E2 = f.sub(p).mul(S).umod(f), B = y.mul(S).umod(f); + return this.g.mulAdd(E2, m, B); + }; + Sr.prototype.getKeyRecoveryParam = function(t, e, r, o) { + if (e = new n0(e, o), e.recoveryParam !== null) + return e.recoveryParam; + for (var f = 0;f < 4; f++) { + var p; + try { + p = this.recoverPubKey(t, e, f); + } catch { + continue; + } + if (p.eq(r)) + return f; + } + throw new Error("Unable to find valid recovery factor"); + }; + }); + xy = T((Zk, _y2) => { + var za = or(), My = za.assert, wy = za.parseBytes, Cf = za.cachedProperty; + function Ft(t, e) { + this.eddsa = t, this._secret = wy(e.secret), t.isPoint(e.pub) ? this._pub = e.pub : this._pubBytes = wy(e.pub); + } + Ft.fromPublic = function(e, r) { + return r instanceof Ft ? r : new Ft(e, { pub: r }); + }; + Ft.fromSecret = function(e, r) { + return r instanceof Ft ? r : new Ft(e, { secret: r }); + }; + Ft.prototype.secret = function() { + return this._secret; + }; + Cf(Ft, "pubBytes", function() { + return this.eddsa.encodePoint(this.pub()); + }); + Cf(Ft, "pub", function() { + return this._pubBytes ? this.eddsa.decodePoint(this._pubBytes) : this.eddsa.g.mul(this.priv()); + }); + Cf(Ft, "privBytes", function() { + var e = this.eddsa, r = this.hash(), o = e.encodingLength - 1, f = r.slice(0, e.encodingLength); + return f[0] &= 248, f[o] &= 127, f[o] |= 64, f; + }); + Cf(Ft, "priv", function() { + return this.eddsa.decodeInt(this.privBytes()); + }); + Cf(Ft, "hash", function() { + return this.eddsa.hash().update(this.secret()).digest(); + }); + Cf(Ft, "messagePrefix", function() { + return this.hash().slice(this.eddsa.encodingLength); + }); + Ft.prototype.sign = function(e) { + return My(this._secret, "KeyPair can only verify"), this.eddsa.sign(e, this); + }; + Ft.prototype.verify = function(e, r) { + return this.eddsa.verify(e, r, this); + }; + Ft.prototype.getSecret = function(e) { + return My(this._secret, "KeyPair is public only"), za.encode(this.secret(), e); + }; + Ft.prototype.getPublic = function(e) { + return za.encode(this.pubBytes(), e); + }; + _y2.exports = Ft; + }); + Ey = T((Vk, Sy) => { + var eB = ri(), f0 = or(), tB = f0.assert, a0 = f0.cachedProperty, rB = f0.parseBytes; + function zn(t, e) { + this.eddsa = t, typeof e != "object" && (e = rB(e)), Array.isArray(e) && (e = { R: e.slice(0, t.encodingLength), S: e.slice(t.encodingLength) }), tB(e.R && e.S, "Signature without R or S"), t.isPoint(e.R) && (this._R = e.R), e.S instanceof eB && (this._S = e.S), this._Rencoded = Array.isArray(e.R) ? e.R : e.Rencoded, this._Sencoded = Array.isArray(e.S) ? e.S : e.Sencoded; + } + a0(zn, "S", function() { + return this.eddsa.decodeInt(this.Sencoded()); + }); + a0(zn, "R", function() { + return this.eddsa.decodePoint(this.Rencoded()); + }); + a0(zn, "Rencoded", function() { + return this.eddsa.encodePoint(this.R()); + }); + a0(zn, "Sencoded", function() { + return this.eddsa.encodeInt(this.S()); + }); + zn.prototype.toBytes = function() { + return this.Rencoded().concat(this.Sencoded()); + }; + zn.prototype.toHex = function() { + return f0.encode(this.toBytes(), "hex").toUpperCase(); + }; + Sy.exports = zn; + }); + Iy = T(($k, qy) => { + var iB = e0(), nB = t0(), Of = or(), fB = Of.assert, Ry = Of.parseBytes, By = xy(), Ay = Ey(); + function nr(t) { + if (fB(t === "ed25519", "only tested with ed25519 so far"), !(this instanceof nr)) + return new nr(t); + t = nB[t].curve, this.curve = t, this.g = t.g, this.g.precompute(t.n.bitLength() + 1), this.pointClass = t.point().constructor, this.encodingLength = Math.ceil(t.n.bitLength() / 8), this.hash = iB.sha512; + } + qy.exports = nr; + nr.prototype.sign = function(e, r) { + e = Ry(e); + var o = this.keyFromSecret(r), f = this.hashInt(o.messagePrefix(), e), p = this.g.mul(f), m = this.encodePoint(p), y = this.hashInt(m, o.pubBytes(), e).mul(o.priv()), M = f.add(y).umod(this.curve.n); + return this.makeSignature({ R: p, S: M, Rencoded: m }); + }; + nr.prototype.verify = function(e, r, o) { + e = Ry(e), r = this.makeSignature(r); + var f = this.keyFromPublic(o), p = this.hashInt(r.Rencoded(), f.pubBytes(), e), m = this.g.mul(r.S()), y = r.R().add(f.pub().mul(p)); + return y.eq(m); + }; + nr.prototype.hashInt = function() { + for (var e = this.hash(), r = 0;r < arguments.length; r++) + e.update(arguments[r]); + return Of.intFromLE(e.digest()).umod(this.curve.n); + }; + nr.prototype.keyFromPublic = function(e) { + return By.fromPublic(this, e); + }; + nr.prototype.keyFromSecret = function(e) { + return By.fromSecret(this, e); + }; + nr.prototype.makeSignature = function(e) { + return e instanceof Ay ? e : new Ay(this, e); + }; + nr.prototype.encodePoint = function(e) { + var r = e.getY().toArray("le", this.encodingLength); + return r[this.encodingLength - 1] |= e.getX().isOdd() ? 128 : 0, r; + }; + nr.prototype.decodePoint = function(e) { + e = Of.parseBytes(e); + var r = e.length - 1, o = e.slice(0, r).concat(e[r] & -129), f = (e[r] & 128) !== 0, p = Of.intFromLE(o); + return this.curve.pointFromY(p, f); + }; + nr.prototype.encodeInt = function(e) { + return e.toArray("le", this.encodingLength); + }; + nr.prototype.decodeInt = function(e) { + return Of.intFromLE(e); + }; + nr.prototype.isPoint = function(e) { + return e instanceof this.pointClass; + }; + }); + o0 = T((Ty) => { + var Hn = Ty; + Hn.version = s2().version; + Hn.utils = or(); + Hn.rand = As(); + Hn.curve = Pl(); + Hn.curves = t0(); + Hn.ec = yy(); + Hn.eddsa = Iy(); + }); + td = T((ky, ed) => { + (function(t, e) { + function r(v, i) { + if (!v) + throw new Error(i || "Assertion failed"); + } + function o(v, i) { + v.super_ = i; + var a = function() { + }; + a.prototype = i.prototype, v.prototype = new a, v.prototype.constructor = v; + } + function f(v, i, a) { + if (f.isBN(v)) + return v; + this.negative = 0, this.words = null, this.length = 0, this.red = null, v !== null && ((i === "le" || i === "be") && (a = i, i = 10), this._init(v || 0, i || 10, a || "be")); + } + typeof t == "object" ? t.exports = f : e.BN = f, f.BN = f, f.wordSize = 26; + var p; + try { + typeof window < "u" && typeof window.Buffer < "u" ? p = window.Buffer : p = ji().Buffer; + } catch { + } + f.isBN = function(i) { + return i instanceof f ? true : i !== null && typeof i == "object" && i.constructor.wordSize === f.wordSize && Array.isArray(i.words); + }, f.max = function(i, a) { + return i.cmp(a) > 0 ? i : a; + }, f.min = function(i, a) { + return i.cmp(a) < 0 ? i : a; + }, f.prototype._init = function(i, a, h) { + if (typeof i == "number") + return this._initNumber(i, a, h); + if (typeof i == "object") + return this._initArray(i, a, h); + a === "hex" && (a = 16), r(a === (a | 0) && a >= 2 && a <= 36), i = i.toString().replace(/\s+/g, ""); + var s = 0; + i[0] === "-" && (s++, this.negative = 1), s < i.length && (a === 16 ? this._parseHex(i, s, h) : (this._parseBase(i, a, s), h === "le" && this._initArray(this.toArray(), a, h))); + }, f.prototype._initNumber = function(i, a, h) { + i < 0 && (this.negative = 1, i = -i), i < 67108864 ? (this.words = [i & 67108863], this.length = 1) : i < 4503599627370496 ? (this.words = [i & 67108863, i / 67108864 & 67108863], this.length = 2) : (r(i < 9007199254740992), this.words = [i & 67108863, i / 67108864 & 67108863, 1], this.length = 3), h === "le" && this._initArray(this.toArray(), a, h); + }, f.prototype._initArray = function(i, a, h) { + if (r(typeof i.length == "number"), i.length <= 0) + return this.words = [0], this.length = 1, this; + this.length = Math.ceil(i.length / 3), this.words = new Array(this.length); + for (var s = 0;s < this.length; s++) + this.words[s] = 0; + var u, c, b = 0; + if (h === "be") + for (s = i.length - 1, u = 0;s >= 0; s -= 3) + c = i[s] | i[s - 1] << 8 | i[s - 2] << 16, this.words[u] |= c << b & 67108863, this.words[u + 1] = c >>> 26 - b & 67108863, b += 24, b >= 26 && (b -= 26, u++); + else if (h === "le") + for (s = 0, u = 0;s < i.length; s += 3) + c = i[s] | i[s + 1] << 8 | i[s + 2] << 16, this.words[u] |= c << b & 67108863, this.words[u + 1] = c >>> 26 - b & 67108863, b += 24, b >= 26 && (b -= 26, u++); + return this.strip(); + }; + function m(v, i) { + var a = v.charCodeAt(i); + return a >= 65 && a <= 70 ? a - 55 : a >= 97 && a <= 102 ? a - 87 : a - 48 & 15; + } + function y(v, i, a) { + var h = m(v, a); + return a - 1 >= i && (h |= m(v, a - 1) << 4), h; + } + f.prototype._parseHex = function(i, a, h) { + this.length = Math.ceil((i.length - a) / 6), this.words = new Array(this.length); + for (var s = 0;s < this.length; s++) + this.words[s] = 0; + var u = 0, c = 0, b; + if (h === "be") + for (s = i.length - 1;s >= a; s -= 2) + b = y(i, a, s) << u, this.words[c] |= b & 67108863, u >= 18 ? (u -= 18, c += 1, this.words[c] |= b >>> 26) : u += 8; + else { + var l = i.length - a; + for (s = l % 2 === 0 ? a + 1 : a;s < i.length; s += 2) + b = y(i, a, s) << u, this.words[c] |= b & 67108863, u >= 18 ? (u -= 18, c += 1, this.words[c] |= b >>> 26) : u += 8; + } + this.strip(); + }; + function M(v, i, a, h) { + for (var s = 0, u = Math.min(v.length, a), c = i;c < u; c++) { + var b = v.charCodeAt(c) - 48; + s *= h, b >= 49 ? s += b - 49 + 10 : b >= 17 ? s += b - 17 + 10 : s += b; + } + return s; + } + f.prototype._parseBase = function(i, a, h) { + this.words = [0], this.length = 1; + for (var s = 0, u = 1;u <= 67108863; u *= a) + s++; + s--, u = u / a | 0; + for (var c = i.length - h, b = c % s, l = Math.min(c, c - b) + h, n = 0, d = h;d < l; d += s) + n = M(i, d, d + s, a), this.imuln(u), this.words[0] + n < 67108864 ? this.words[0] += n : this._iaddn(n); + if (b !== 0) { + var w = 1; + for (n = M(i, d, i.length, a), d = 0;d < b; d++) + w *= a; + this.imuln(w), this.words[0] + n < 67108864 ? this.words[0] += n : this._iaddn(n); + } + this.strip(); + }, f.prototype.copy = function(i) { + i.words = new Array(this.length); + for (var a = 0;a < this.length; a++) + i.words[a] = this.words[a]; + i.length = this.length, i.negative = this.negative, i.red = this.red; + }, f.prototype.clone = function() { + var i = new f(null); + return this.copy(i), i; + }, f.prototype._expand = function(i) { + for (;this.length < i; ) + this.words[this.length++] = 0; + return this; + }, f.prototype.strip = function() { + for (;this.length > 1 && this.words[this.length - 1] === 0; ) + this.length--; + return this._normSign(); + }, f.prototype._normSign = function() { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }, f.prototype.inspect = function() { + return (this.red ? ""; + }; + var x = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], S = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], E2 = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; + f.prototype.toString = function(i, a) { + i = i || 10, a = a | 0 || 1; + var h; + if (i === 16 || i === "hex") { + h = ""; + for (var s = 0, u = 0, c = 0;c < this.length; c++) { + var b = this.words[c], l = ((b << s | u) & 16777215).toString(16); + u = b >>> 24 - s & 16777215, u !== 0 || c !== this.length - 1 ? h = x[6 - l.length] + l + h : h = l + h, s += 2, s >= 26 && (s -= 26, c--); + } + for (u !== 0 && (h = u.toString(16) + h);h.length % a !== 0; ) + h = "0" + h; + return this.negative !== 0 && (h = "-" + h), h; + } + if (i === (i | 0) && i >= 2 && i <= 36) { + var n = S[i], d = E2[i]; + h = ""; + var w = this.clone(); + for (w.negative = 0;!w.isZero(); ) { + var g = w.modn(d).toString(i); + w = w.idivn(d), w.isZero() ? h = g + h : h = x[n - g.length] + g + h; + } + for (this.isZero() && (h = "0" + h);h.length % a !== 0; ) + h = "0" + h; + return this.negative !== 0 && (h = "-" + h), h; + } + r(false, "Base should be between 2 and 36"); + }, f.prototype.toNumber = function() { + var i = this.words[0]; + return this.length === 2 ? i += this.words[1] * 67108864 : this.length === 3 && this.words[2] === 1 ? i += 4503599627370496 + this.words[1] * 67108864 : this.length > 2 && r(false, "Number can only safely store up to 53 bits"), this.negative !== 0 ? -i : i; + }, f.prototype.toJSON = function() { + return this.toString(16); + }, f.prototype.toBuffer = function(i, a) { + return r(typeof p < "u"), this.toArrayLike(p, i, a); + }, f.prototype.toArray = function(i, a) { + return this.toArrayLike(Array, i, a); + }, f.prototype.toArrayLike = function(i, a, h) { + var s = this.byteLength(), u = h || Math.max(1, s); + r(s <= u, "byte array longer than desired length"), r(u > 0, "Requested array length <= 0"), this.strip(); + var c = a === "le", b = new i(u), l, n, d = this.clone(); + if (c) { + for (n = 0;!d.isZero(); n++) + l = d.andln(255), d.iushrn(8), b[n] = l; + for (;n < u; n++) + b[n] = 0; + } else { + for (n = 0;n < u - s; n++) + b[n] = 0; + for (n = 0;!d.isZero(); n++) + l = d.andln(255), d.iushrn(8), b[u - n - 1] = l; + } + return b; + }, Math.clz32 ? f.prototype._countBits = function(i) { + return 32 - Math.clz32(i); + } : f.prototype._countBits = function(i) { + var a = i, h = 0; + return a >= 4096 && (h += 13, a >>>= 13), a >= 64 && (h += 7, a >>>= 7), a >= 8 && (h += 4, a >>>= 4), a >= 2 && (h += 2, a >>>= 2), h + a; + }, f.prototype._zeroBits = function(i) { + if (i === 0) + return 26; + var a = i, h = 0; + return (a & 8191) === 0 && (h += 13, a >>>= 13), (a & 127) === 0 && (h += 7, a >>>= 7), (a & 15) === 0 && (h += 4, a >>>= 4), (a & 3) === 0 && (h += 2, a >>>= 2), (a & 1) === 0 && h++, h; + }, f.prototype.bitLength = function() { + var i = this.words[this.length - 1], a = this._countBits(i); + return (this.length - 1) * 26 + a; + }; + function B(v) { + for (var i = new Array(v.bitLength()), a = 0;a < i.length; a++) { + var h = a / 26 | 0, s = a % 26; + i[a] = (v.words[h] & 1 << s) >>> s; + } + return i; + } + f.prototype.zeroBits = function() { + if (this.isZero()) + return 0; + for (var i = 0, a = 0;a < this.length; a++) { + var h = this._zeroBits(this.words[a]); + if (i += h, h !== 26) + break; + } + return i; + }, f.prototype.byteLength = function() { + return Math.ceil(this.bitLength() / 8); + }, f.prototype.toTwos = function(i) { + return this.negative !== 0 ? this.abs().inotn(i).iaddn(1) : this.clone(); + }, f.prototype.fromTwos = function(i) { + return this.testn(i - 1) ? this.notn(i).iaddn(1).ineg() : this.clone(); + }, f.prototype.isNeg = function() { + return this.negative !== 0; + }, f.prototype.neg = function() { + return this.clone().ineg(); + }, f.prototype.ineg = function() { + return this.isZero() || (this.negative ^= 1), this; + }, f.prototype.iuor = function(i) { + for (;this.length < i.length; ) + this.words[this.length++] = 0; + for (var a = 0;a < i.length; a++) + this.words[a] = this.words[a] | i.words[a]; + return this.strip(); + }, f.prototype.ior = function(i) { + return r((this.negative | i.negative) === 0), this.iuor(i); + }, f.prototype.or = function(i) { + return this.length > i.length ? this.clone().ior(i) : i.clone().ior(this); + }, f.prototype.uor = function(i) { + return this.length > i.length ? this.clone().iuor(i) : i.clone().iuor(this); + }, f.prototype.iuand = function(i) { + var a; + this.length > i.length ? a = i : a = this; + for (var h = 0;h < a.length; h++) + this.words[h] = this.words[h] & i.words[h]; + return this.length = a.length, this.strip(); + }, f.prototype.iand = function(i) { + return r((this.negative | i.negative) === 0), this.iuand(i); + }, f.prototype.and = function(i) { + return this.length > i.length ? this.clone().iand(i) : i.clone().iand(this); + }, f.prototype.uand = function(i) { + return this.length > i.length ? this.clone().iuand(i) : i.clone().iuand(this); + }, f.prototype.iuxor = function(i) { + var a, h; + this.length > i.length ? (a = this, h = i) : (a = i, h = this); + for (var s = 0;s < h.length; s++) + this.words[s] = a.words[s] ^ h.words[s]; + if (this !== a) + for (;s < a.length; s++) + this.words[s] = a.words[s]; + return this.length = a.length, this.strip(); + }, f.prototype.ixor = function(i) { + return r((this.negative | i.negative) === 0), this.iuxor(i); + }, f.prototype.xor = function(i) { + return this.length > i.length ? this.clone().ixor(i) : i.clone().ixor(this); + }, f.prototype.uxor = function(i) { + return this.length > i.length ? this.clone().iuxor(i) : i.clone().iuxor(this); + }, f.prototype.inotn = function(i) { + r(typeof i == "number" && i >= 0); + var a = Math.ceil(i / 26) | 0, h = i % 26; + this._expand(a), h > 0 && a--; + for (var s = 0;s < a; s++) + this.words[s] = ~this.words[s] & 67108863; + return h > 0 && (this.words[s] = ~this.words[s] & 67108863 >> 26 - h), this.strip(); + }, f.prototype.notn = function(i) { + return this.clone().inotn(i); + }, f.prototype.setn = function(i, a) { + r(typeof i == "number" && i >= 0); + var h = i / 26 | 0, s = i % 26; + return this._expand(h + 1), a ? this.words[h] = this.words[h] | 1 << s : this.words[h] = this.words[h] & ~(1 << s), this.strip(); + }, f.prototype.iadd = function(i) { + var a; + if (this.negative !== 0 && i.negative === 0) + return this.negative = 0, a = this.isub(i), this.negative ^= 1, this._normSign(); + if (this.negative === 0 && i.negative !== 0) + return i.negative = 0, a = this.isub(i), i.negative = 1, a._normSign(); + var h, s; + this.length > i.length ? (h = this, s = i) : (h = i, s = this); + for (var u = 0, c = 0;c < s.length; c++) + a = (h.words[c] | 0) + (s.words[c] | 0) + u, this.words[c] = a & 67108863, u = a >>> 26; + for (;u !== 0 && c < h.length; c++) + a = (h.words[c] | 0) + u, this.words[c] = a & 67108863, u = a >>> 26; + if (this.length = h.length, u !== 0) + this.words[this.length] = u, this.length++; + else if (h !== this) + for (;c < h.length; c++) + this.words[c] = h.words[c]; + return this; + }, f.prototype.add = function(i) { + var a; + return i.negative !== 0 && this.negative === 0 ? (i.negative = 0, a = this.sub(i), i.negative ^= 1, a) : i.negative === 0 && this.negative !== 0 ? (this.negative = 0, a = i.sub(this), this.negative = 1, a) : this.length > i.length ? this.clone().iadd(i) : i.clone().iadd(this); + }, f.prototype.isub = function(i) { + if (i.negative !== 0) { + i.negative = 0; + var a = this.iadd(i); + return i.negative = 1, a._normSign(); + } else if (this.negative !== 0) + return this.negative = 0, this.iadd(i), this.negative = 1, this._normSign(); + var h = this.cmp(i); + if (h === 0) + return this.negative = 0, this.length = 1, this.words[0] = 0, this; + var s, u; + h > 0 ? (s = this, u = i) : (s = i, u = this); + for (var c = 0, b = 0;b < u.length; b++) + a = (s.words[b] | 0) - (u.words[b] | 0) + c, c = a >> 26, this.words[b] = a & 67108863; + for (;c !== 0 && b < s.length; b++) + a = (s.words[b] | 0) + c, c = a >> 26, this.words[b] = a & 67108863; + if (c === 0 && b < s.length && s !== this) + for (;b < s.length; b++) + this.words[b] = s.words[b]; + return this.length = Math.max(this.length, b), s !== this && (this.negative = 1), this.strip(); + }, f.prototype.sub = function(i) { + return this.clone().isub(i); + }; + function q(v, i, a) { + a.negative = i.negative ^ v.negative; + var h = v.length + i.length | 0; + a.length = h, h = h - 1 | 0; + var s = v.words[0] | 0, u = i.words[0] | 0, c = s * u, b = c & 67108863, l = c / 67108864 | 0; + a.words[0] = b; + for (var n = 1;n < h; n++) { + for (var d = l >>> 26, w = l & 67108863, g = Math.min(n, i.length - 1), _9 = Math.max(0, n - v.length + 1);_9 <= g; _9++) { + var A = n - _9 | 0; + s = v.words[A] | 0, u = i.words[_9] | 0, c = s * u + w, d += c / 67108864 | 0, w = c & 67108863; + } + a.words[n] = w | 0, l = d | 0; + } + return l !== 0 ? a.words[n] = l | 0 : a.length--, a.strip(); + } + var L = function(i, a, h) { + var s = i.words, u = a.words, c = h.words, b = 0, l, n, d, w = s[0] | 0, g = w & 8191, _9 = w >>> 13, A = s[1] | 0, R = A & 8191, I2 = A >>> 13, Me = s[2] | 0, k2 = Me & 8191, D = Me >>> 13, nt = s[3] | 0, C2 = nt & 8191, O = nt >>> 13, vt = s[4] | 0, F = vt & 8191, U = vt >>> 13, bt = s[5] | 0, z = bt & 8191, H = bt >>> 13, mt = s[6] | 0, W = mt & 8191, K = mt >>> 13, gt = s[7] | 0, j = gt & 8191, Z = gt >>> 13, yt = s[8] | 0, V3 = yt & 8191, $ = yt >>> 13, wt = s[9] | 0, G = wt & 8191, Y = wt >>> 13, Mt = u[0] | 0, X = Mt & 8191, J2 = Mt >>> 13, _t = u[1] | 0, Q = _t & 8191, ee = _t >>> 13, xt2 = u[2] | 0, te2 = xt2 & 8191, re = xt2 >>> 13, St = u[3] | 0, ie = St & 8191, ne = St >>> 13, Et2 = u[4] | 0, fe = Et2 & 8191, ae2 = Et2 >>> 13, At2 = u[5] | 0, oe = At2 & 8191, se2 = At2 >>> 13, Rt = u[6] | 0, he = Rt & 8191, ue2 = Rt >>> 13, Bt = u[7] | 0, le = Bt & 8191, de = Bt >>> 13, qt = u[8] | 0, ce2 = qt & 8191, pe2 = qt >>> 13, It = u[9] | 0, ve = It & 8191, be = It >>> 13; + h.negative = i.negative ^ a.negative, h.length = 19, l = Math.imul(g, X), n = Math.imul(g, J2), n = n + Math.imul(_9, X) | 0, d = Math.imul(_9, J2); + var ft = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (ft >>> 26) | 0, ft &= 67108863, l = Math.imul(R, X), n = Math.imul(R, J2), n = n + Math.imul(I2, X) | 0, d = Math.imul(I2, J2), l = l + Math.imul(g, Q) | 0, n = n + Math.imul(g, ee) | 0, n = n + Math.imul(_9, Q) | 0, d = d + Math.imul(_9, ee) | 0; + var Be = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Be >>> 26) | 0, Be &= 67108863, l = Math.imul(k2, X), n = Math.imul(k2, J2), n = n + Math.imul(D, X) | 0, d = Math.imul(D, J2), l = l + Math.imul(R, Q) | 0, n = n + Math.imul(R, ee) | 0, n = n + Math.imul(I2, Q) | 0, d = d + Math.imul(I2, ee) | 0, l = l + Math.imul(g, te2) | 0, n = n + Math.imul(g, re) | 0, n = n + Math.imul(_9, te2) | 0, d = d + Math.imul(_9, re) | 0; + var qe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (qe >>> 26) | 0, qe &= 67108863, l = Math.imul(C2, X), n = Math.imul(C2, J2), n = n + Math.imul(O, X) | 0, d = Math.imul(O, J2), l = l + Math.imul(k2, Q) | 0, n = n + Math.imul(k2, ee) | 0, n = n + Math.imul(D, Q) | 0, d = d + Math.imul(D, ee) | 0, l = l + Math.imul(R, te2) | 0, n = n + Math.imul(R, re) | 0, n = n + Math.imul(I2, te2) | 0, d = d + Math.imul(I2, re) | 0, l = l + Math.imul(g, ie) | 0, n = n + Math.imul(g, ne) | 0, n = n + Math.imul(_9, ie) | 0, d = d + Math.imul(_9, ne) | 0; + var ze = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (ze >>> 26) | 0, ze &= 67108863, l = Math.imul(F, X), n = Math.imul(F, J2), n = n + Math.imul(U, X) | 0, d = Math.imul(U, J2), l = l + Math.imul(C2, Q) | 0, n = n + Math.imul(C2, ee) | 0, n = n + Math.imul(O, Q) | 0, d = d + Math.imul(O, ee) | 0, l = l + Math.imul(k2, te2) | 0, n = n + Math.imul(k2, re) | 0, n = n + Math.imul(D, te2) | 0, d = d + Math.imul(D, re) | 0, l = l + Math.imul(R, ie) | 0, n = n + Math.imul(R, ne) | 0, n = n + Math.imul(I2, ie) | 0, d = d + Math.imul(I2, ne) | 0, l = l + Math.imul(g, fe) | 0, n = n + Math.imul(g, ae2) | 0, n = n + Math.imul(_9, fe) | 0, d = d + Math.imul(_9, ae2) | 0; + var He2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (He2 >>> 26) | 0, He2 &= 67108863, l = Math.imul(z, X), n = Math.imul(z, J2), n = n + Math.imul(H, X) | 0, d = Math.imul(H, J2), l = l + Math.imul(F, Q) | 0, n = n + Math.imul(F, ee) | 0, n = n + Math.imul(U, Q) | 0, d = d + Math.imul(U, ee) | 0, l = l + Math.imul(C2, te2) | 0, n = n + Math.imul(C2, re) | 0, n = n + Math.imul(O, te2) | 0, d = d + Math.imul(O, re) | 0, l = l + Math.imul(k2, ie) | 0, n = n + Math.imul(k2, ne) | 0, n = n + Math.imul(D, ie) | 0, d = d + Math.imul(D, ne) | 0, l = l + Math.imul(R, fe) | 0, n = n + Math.imul(R, ae2) | 0, n = n + Math.imul(I2, fe) | 0, d = d + Math.imul(I2, ae2) | 0, l = l + Math.imul(g, oe) | 0, n = n + Math.imul(g, se2) | 0, n = n + Math.imul(_9, oe) | 0, d = d + Math.imul(_9, se2) | 0; + var We = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (We >>> 26) | 0, We &= 67108863, l = Math.imul(W, X), n = Math.imul(W, J2), n = n + Math.imul(K, X) | 0, d = Math.imul(K, J2), l = l + Math.imul(z, Q) | 0, n = n + Math.imul(z, ee) | 0, n = n + Math.imul(H, Q) | 0, d = d + Math.imul(H, ee) | 0, l = l + Math.imul(F, te2) | 0, n = n + Math.imul(F, re) | 0, n = n + Math.imul(U, te2) | 0, d = d + Math.imul(U, re) | 0, l = l + Math.imul(C2, ie) | 0, n = n + Math.imul(C2, ne) | 0, n = n + Math.imul(O, ie) | 0, d = d + Math.imul(O, ne) | 0, l = l + Math.imul(k2, fe) | 0, n = n + Math.imul(k2, ae2) | 0, n = n + Math.imul(D, fe) | 0, d = d + Math.imul(D, ae2) | 0, l = l + Math.imul(R, oe) | 0, n = n + Math.imul(R, se2) | 0, n = n + Math.imul(I2, oe) | 0, d = d + Math.imul(I2, se2) | 0, l = l + Math.imul(g, he) | 0, n = n + Math.imul(g, ue2) | 0, n = n + Math.imul(_9, he) | 0, d = d + Math.imul(_9, ue2) | 0; + var Ke2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ke2 >>> 26) | 0, Ke2 &= 67108863, l = Math.imul(j, X), n = Math.imul(j, J2), n = n + Math.imul(Z, X) | 0, d = Math.imul(Z, J2), l = l + Math.imul(W, Q) | 0, n = n + Math.imul(W, ee) | 0, n = n + Math.imul(K, Q) | 0, d = d + Math.imul(K, ee) | 0, l = l + Math.imul(z, te2) | 0, n = n + Math.imul(z, re) | 0, n = n + Math.imul(H, te2) | 0, d = d + Math.imul(H, re) | 0, l = l + Math.imul(F, ie) | 0, n = n + Math.imul(F, ne) | 0, n = n + Math.imul(U, ie) | 0, d = d + Math.imul(U, ne) | 0, l = l + Math.imul(C2, fe) | 0, n = n + Math.imul(C2, ae2) | 0, n = n + Math.imul(O, fe) | 0, d = d + Math.imul(O, ae2) | 0, l = l + Math.imul(k2, oe) | 0, n = n + Math.imul(k2, se2) | 0, n = n + Math.imul(D, oe) | 0, d = d + Math.imul(D, se2) | 0, l = l + Math.imul(R, he) | 0, n = n + Math.imul(R, ue2) | 0, n = n + Math.imul(I2, he) | 0, d = d + Math.imul(I2, ue2) | 0, l = l + Math.imul(g, le) | 0, n = n + Math.imul(g, de) | 0, n = n + Math.imul(_9, le) | 0, d = d + Math.imul(_9, de) | 0; + var je = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (je >>> 26) | 0, je &= 67108863, l = Math.imul(V3, X), n = Math.imul(V3, J2), n = n + Math.imul($, X) | 0, d = Math.imul($, J2), l = l + Math.imul(j, Q) | 0, n = n + Math.imul(j, ee) | 0, n = n + Math.imul(Z, Q) | 0, d = d + Math.imul(Z, ee) | 0, l = l + Math.imul(W, te2) | 0, n = n + Math.imul(W, re) | 0, n = n + Math.imul(K, te2) | 0, d = d + Math.imul(K, re) | 0, l = l + Math.imul(z, ie) | 0, n = n + Math.imul(z, ne) | 0, n = n + Math.imul(H, ie) | 0, d = d + Math.imul(H, ne) | 0, l = l + Math.imul(F, fe) | 0, n = n + Math.imul(F, ae2) | 0, n = n + Math.imul(U, fe) | 0, d = d + Math.imul(U, ae2) | 0, l = l + Math.imul(C2, oe) | 0, n = n + Math.imul(C2, se2) | 0, n = n + Math.imul(O, oe) | 0, d = d + Math.imul(O, se2) | 0, l = l + Math.imul(k2, he) | 0, n = n + Math.imul(k2, ue2) | 0, n = n + Math.imul(D, he) | 0, d = d + Math.imul(D, ue2) | 0, l = l + Math.imul(R, le) | 0, n = n + Math.imul(R, de) | 0, n = n + Math.imul(I2, le) | 0, d = d + Math.imul(I2, de) | 0, l = l + Math.imul(g, ce2) | 0, n = n + Math.imul(g, pe2) | 0, n = n + Math.imul(_9, ce2) | 0, d = d + Math.imul(_9, pe2) | 0; + var Ze2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ze2 >>> 26) | 0, Ze2 &= 67108863, l = Math.imul(G, X), n = Math.imul(G, J2), n = n + Math.imul(Y, X) | 0, d = Math.imul(Y, J2), l = l + Math.imul(V3, Q) | 0, n = n + Math.imul(V3, ee) | 0, n = n + Math.imul($, Q) | 0, d = d + Math.imul($, ee) | 0, l = l + Math.imul(j, te2) | 0, n = n + Math.imul(j, re) | 0, n = n + Math.imul(Z, te2) | 0, d = d + Math.imul(Z, re) | 0, l = l + Math.imul(W, ie) | 0, n = n + Math.imul(W, ne) | 0, n = n + Math.imul(K, ie) | 0, d = d + Math.imul(K, ne) | 0, l = l + Math.imul(z, fe) | 0, n = n + Math.imul(z, ae2) | 0, n = n + Math.imul(H, fe) | 0, d = d + Math.imul(H, ae2) | 0, l = l + Math.imul(F, oe) | 0, n = n + Math.imul(F, se2) | 0, n = n + Math.imul(U, oe) | 0, d = d + Math.imul(U, se2) | 0, l = l + Math.imul(C2, he) | 0, n = n + Math.imul(C2, ue2) | 0, n = n + Math.imul(O, he) | 0, d = d + Math.imul(O, ue2) | 0, l = l + Math.imul(k2, le) | 0, n = n + Math.imul(k2, de) | 0, n = n + Math.imul(D, le) | 0, d = d + Math.imul(D, de) | 0, l = l + Math.imul(R, ce2) | 0, n = n + Math.imul(R, pe2) | 0, n = n + Math.imul(I2, ce2) | 0, d = d + Math.imul(I2, pe2) | 0, l = l + Math.imul(g, ve) | 0, n = n + Math.imul(g, be) | 0, n = n + Math.imul(_9, ve) | 0, d = d + Math.imul(_9, be) | 0; + var Ve = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ve >>> 26) | 0, Ve &= 67108863, l = Math.imul(G, Q), n = Math.imul(G, ee), n = n + Math.imul(Y, Q) | 0, d = Math.imul(Y, ee), l = l + Math.imul(V3, te2) | 0, n = n + Math.imul(V3, re) | 0, n = n + Math.imul($, te2) | 0, d = d + Math.imul($, re) | 0, l = l + Math.imul(j, ie) | 0, n = n + Math.imul(j, ne) | 0, n = n + Math.imul(Z, ie) | 0, d = d + Math.imul(Z, ne) | 0, l = l + Math.imul(W, fe) | 0, n = n + Math.imul(W, ae2) | 0, n = n + Math.imul(K, fe) | 0, d = d + Math.imul(K, ae2) | 0, l = l + Math.imul(z, oe) | 0, n = n + Math.imul(z, se2) | 0, n = n + Math.imul(H, oe) | 0, d = d + Math.imul(H, se2) | 0, l = l + Math.imul(F, he) | 0, n = n + Math.imul(F, ue2) | 0, n = n + Math.imul(U, he) | 0, d = d + Math.imul(U, ue2) | 0, l = l + Math.imul(C2, le) | 0, n = n + Math.imul(C2, de) | 0, n = n + Math.imul(O, le) | 0, d = d + Math.imul(O, de) | 0, l = l + Math.imul(k2, ce2) | 0, n = n + Math.imul(k2, pe2) | 0, n = n + Math.imul(D, ce2) | 0, d = d + Math.imul(D, pe2) | 0, l = l + Math.imul(R, ve) | 0, n = n + Math.imul(R, be) | 0, n = n + Math.imul(I2, ve) | 0, d = d + Math.imul(I2, be) | 0; + var $e = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + ($e >>> 26) | 0, $e &= 67108863, l = Math.imul(G, te2), n = Math.imul(G, re), n = n + Math.imul(Y, te2) | 0, d = Math.imul(Y, re), l = l + Math.imul(V3, ie) | 0, n = n + Math.imul(V3, ne) | 0, n = n + Math.imul($, ie) | 0, d = d + Math.imul($, ne) | 0, l = l + Math.imul(j, fe) | 0, n = n + Math.imul(j, ae2) | 0, n = n + Math.imul(Z, fe) | 0, d = d + Math.imul(Z, ae2) | 0, l = l + Math.imul(W, oe) | 0, n = n + Math.imul(W, se2) | 0, n = n + Math.imul(K, oe) | 0, d = d + Math.imul(K, se2) | 0, l = l + Math.imul(z, he) | 0, n = n + Math.imul(z, ue2) | 0, n = n + Math.imul(H, he) | 0, d = d + Math.imul(H, ue2) | 0, l = l + Math.imul(F, le) | 0, n = n + Math.imul(F, de) | 0, n = n + Math.imul(U, le) | 0, d = d + Math.imul(U, de) | 0, l = l + Math.imul(C2, ce2) | 0, n = n + Math.imul(C2, pe2) | 0, n = n + Math.imul(O, ce2) | 0, d = d + Math.imul(O, pe2) | 0, l = l + Math.imul(k2, ve) | 0, n = n + Math.imul(k2, be) | 0, n = n + Math.imul(D, ve) | 0, d = d + Math.imul(D, be) | 0; + var Ge = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ge >>> 26) | 0, Ge &= 67108863, l = Math.imul(G, ie), n = Math.imul(G, ne), n = n + Math.imul(Y, ie) | 0, d = Math.imul(Y, ne), l = l + Math.imul(V3, fe) | 0, n = n + Math.imul(V3, ae2) | 0, n = n + Math.imul($, fe) | 0, d = d + Math.imul($, ae2) | 0, l = l + Math.imul(j, oe) | 0, n = n + Math.imul(j, se2) | 0, n = n + Math.imul(Z, oe) | 0, d = d + Math.imul(Z, se2) | 0, l = l + Math.imul(W, he) | 0, n = n + Math.imul(W, ue2) | 0, n = n + Math.imul(K, he) | 0, d = d + Math.imul(K, ue2) | 0, l = l + Math.imul(z, le) | 0, n = n + Math.imul(z, de) | 0, n = n + Math.imul(H, le) | 0, d = d + Math.imul(H, de) | 0, l = l + Math.imul(F, ce2) | 0, n = n + Math.imul(F, pe2) | 0, n = n + Math.imul(U, ce2) | 0, d = d + Math.imul(U, pe2) | 0, l = l + Math.imul(C2, ve) | 0, n = n + Math.imul(C2, be) | 0, n = n + Math.imul(O, ve) | 0, d = d + Math.imul(O, be) | 0; + var Ye = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ye >>> 26) | 0, Ye &= 67108863, l = Math.imul(G, fe), n = Math.imul(G, ae2), n = n + Math.imul(Y, fe) | 0, d = Math.imul(Y, ae2), l = l + Math.imul(V3, oe) | 0, n = n + Math.imul(V3, se2) | 0, n = n + Math.imul($, oe) | 0, d = d + Math.imul($, se2) | 0, l = l + Math.imul(j, he) | 0, n = n + Math.imul(j, ue2) | 0, n = n + Math.imul(Z, he) | 0, d = d + Math.imul(Z, ue2) | 0, l = l + Math.imul(W, le) | 0, n = n + Math.imul(W, de) | 0, n = n + Math.imul(K, le) | 0, d = d + Math.imul(K, de) | 0, l = l + Math.imul(z, ce2) | 0, n = n + Math.imul(z, pe2) | 0, n = n + Math.imul(H, ce2) | 0, d = d + Math.imul(H, pe2) | 0, l = l + Math.imul(F, ve) | 0, n = n + Math.imul(F, be) | 0, n = n + Math.imul(U, ve) | 0, d = d + Math.imul(U, be) | 0; + var Xe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Xe >>> 26) | 0, Xe &= 67108863, l = Math.imul(G, oe), n = Math.imul(G, se2), n = n + Math.imul(Y, oe) | 0, d = Math.imul(Y, se2), l = l + Math.imul(V3, he) | 0, n = n + Math.imul(V3, ue2) | 0, n = n + Math.imul($, he) | 0, d = d + Math.imul($, ue2) | 0, l = l + Math.imul(j, le) | 0, n = n + Math.imul(j, de) | 0, n = n + Math.imul(Z, le) | 0, d = d + Math.imul(Z, de) | 0, l = l + Math.imul(W, ce2) | 0, n = n + Math.imul(W, pe2) | 0, n = n + Math.imul(K, ce2) | 0, d = d + Math.imul(K, pe2) | 0, l = l + Math.imul(z, ve) | 0, n = n + Math.imul(z, be) | 0, n = n + Math.imul(H, ve) | 0, d = d + Math.imul(H, be) | 0; + var Je = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Je >>> 26) | 0, Je &= 67108863, l = Math.imul(G, he), n = Math.imul(G, ue2), n = n + Math.imul(Y, he) | 0, d = Math.imul(Y, ue2), l = l + Math.imul(V3, le) | 0, n = n + Math.imul(V3, de) | 0, n = n + Math.imul($, le) | 0, d = d + Math.imul($, de) | 0, l = l + Math.imul(j, ce2) | 0, n = n + Math.imul(j, pe2) | 0, n = n + Math.imul(Z, ce2) | 0, d = d + Math.imul(Z, pe2) | 0, l = l + Math.imul(W, ve) | 0, n = n + Math.imul(W, be) | 0, n = n + Math.imul(K, ve) | 0, d = d + Math.imul(K, be) | 0; + var Qe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Qe >>> 26) | 0, Qe &= 67108863, l = Math.imul(G, le), n = Math.imul(G, de), n = n + Math.imul(Y, le) | 0, d = Math.imul(Y, de), l = l + Math.imul(V3, ce2) | 0, n = n + Math.imul(V3, pe2) | 0, n = n + Math.imul($, ce2) | 0, d = d + Math.imul($, pe2) | 0, l = l + Math.imul(j, ve) | 0, n = n + Math.imul(j, be) | 0, n = n + Math.imul(Z, ve) | 0, d = d + Math.imul(Z, be) | 0; + var et2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (et2 >>> 26) | 0, et2 &= 67108863, l = Math.imul(G, ce2), n = Math.imul(G, pe2), n = n + Math.imul(Y, ce2) | 0, d = Math.imul(Y, pe2), l = l + Math.imul(V3, ve) | 0, n = n + Math.imul(V3, be) | 0, n = n + Math.imul($, ve) | 0, d = d + Math.imul($, be) | 0; + var tt2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (tt2 >>> 26) | 0, tt2 &= 67108863, l = Math.imul(G, ve), n = Math.imul(G, be), n = n + Math.imul(Y, ve) | 0, d = Math.imul(Y, be); + var rt2 = (b + l | 0) + ((n & 8191) << 13) | 0; + return b = (d + (n >>> 13) | 0) + (rt2 >>> 26) | 0, rt2 &= 67108863, c[0] = ft, c[1] = Be, c[2] = qe, c[3] = ze, c[4] = He2, c[5] = We, c[6] = Ke2, c[7] = je, c[8] = Ze2, c[9] = Ve, c[10] = $e, c[11] = Ge, c[12] = Ye, c[13] = Xe, c[14] = Je, c[15] = Qe, c[16] = et2, c[17] = tt2, c[18] = rt2, b !== 0 && (c[19] = b, h.length++), h; + }; + Math.imul || (L = q); + function ge(v, i, a) { + a.negative = i.negative ^ v.negative, a.length = v.length + i.length; + for (var h = 0, s = 0, u = 0;u < a.length - 1; u++) { + var c = s; + s = 0; + for (var b = h & 67108863, l = Math.min(u, i.length - 1), n = Math.max(0, u - v.length + 1);n <= l; n++) { + var d = u - n, w = v.words[d] | 0, g = i.words[n] | 0, _9 = w * g, A = _9 & 67108863; + c = c + (_9 / 67108864 | 0) | 0, A = A + b | 0, b = A & 67108863, c = c + (A >>> 26) | 0, s += c >>> 26, c &= 67108863; + } + a.words[u] = b, h = c, c = s; + } + return h !== 0 ? a.words[u] = h : a.length--, a.strip(); + } + function _e(v, i, a) { + var h = new N; + return h.mulp(v, i, a); + } + f.prototype.mulTo = function(i, a) { + var h, s = this.length + i.length; + return this.length === 10 && i.length === 10 ? h = L(this, i, a) : s < 63 ? h = q(this, i, a) : s < 1024 ? h = ge(this, i, a) : h = _e(this, i, a), h; + }; + function N(v, i) { + this.x = v, this.y = i; + } + N.prototype.makeRBT = function(i) { + for (var a = new Array(i), h = f.prototype._countBits(i) - 1, s = 0;s < i; s++) + a[s] = this.revBin(s, h, i); + return a; + }, N.prototype.revBin = function(i, a, h) { + if (i === 0 || i === h - 1) + return i; + for (var s = 0, u = 0;u < a; u++) + s |= (i & 1) << a - u - 1, i >>= 1; + return s; + }, N.prototype.permute = function(i, a, h, s, u, c) { + for (var b = 0;b < c; b++) + s[b] = a[i[b]], u[b] = h[i[b]]; + }, N.prototype.transform = function(i, a, h, s, u, c) { + this.permute(c, i, a, h, s, u); + for (var b = 1;b < u; b <<= 1) + for (var l = b << 1, n = Math.cos(2 * Math.PI / l), d = Math.sin(2 * Math.PI / l), w = 0;w < u; w += l) + for (var g = n, _9 = d, A = 0;A < b; A++) { + var R = h[w + A], I2 = s[w + A], Me = h[w + A + b], k2 = s[w + A + b], D = g * Me - _9 * k2; + k2 = g * k2 + _9 * Me, Me = D, h[w + A] = R + Me, s[w + A] = I2 + k2, h[w + A + b] = R - Me, s[w + A + b] = I2 - k2, A !== l && (D = n * g - d * _9, _9 = n * _9 + d * g, g = D); + } + }, N.prototype.guessLen13b = function(i, a) { + var h = Math.max(a, i) | 1, s = h & 1, u = 0; + for (h = h / 2 | 0;h; h = h >>> 1) + u++; + return 1 << u + 1 + s; + }, N.prototype.conjugate = function(i, a, h) { + if (!(h <= 1)) + for (var s = 0;s < h / 2; s++) { + var u = i[s]; + i[s] = i[h - s - 1], i[h - s - 1] = u, u = a[s], a[s] = -a[h - s - 1], a[h - s - 1] = -u; + } + }, N.prototype.normalize13b = function(i, a) { + for (var h = 0, s = 0;s < a / 2; s++) { + var u = Math.round(i[2 * s + 1] / a) * 8192 + Math.round(i[2 * s] / a) + h; + i[s] = u & 67108863, u < 67108864 ? h = 0 : h = u / 67108864 | 0; + } + return i; + }, N.prototype.convert13b = function(i, a, h, s) { + for (var u = 0, c = 0;c < a; c++) + u = u + (i[c] | 0), h[2 * c] = u & 8191, u = u >>> 13, h[2 * c + 1] = u & 8191, u = u >>> 13; + for (c = 2 * a;c < s; ++c) + h[c] = 0; + r(u === 0), r((u & -8192) === 0); + }, N.prototype.stub = function(i) { + for (var a = new Array(i), h = 0;h < i; h++) + a[h] = 0; + return a; + }, N.prototype.mulp = function(i, a, h) { + var s = 2 * this.guessLen13b(i.length, a.length), u = this.makeRBT(s), c = this.stub(s), b = new Array(s), l = new Array(s), n = new Array(s), d = new Array(s), w = new Array(s), g = new Array(s), _9 = h.words; + _9.length = s, this.convert13b(i.words, i.length, b, s), this.convert13b(a.words, a.length, d, s), this.transform(b, c, l, n, s, u), this.transform(d, c, w, g, s, u); + for (var A = 0;A < s; A++) { + var R = l[A] * w[A] - n[A] * g[A]; + n[A] = l[A] * g[A] + n[A] * w[A], l[A] = R; + } + return this.conjugate(l, n, s), this.transform(l, n, _9, c, s, u), this.conjugate(_9, c, s), this.normalize13b(_9, s), h.negative = i.negative ^ a.negative, h.length = i.length + a.length, h.strip(); + }, f.prototype.mul = function(i) { + var a = new f(null); + return a.words = new Array(this.length + i.length), this.mulTo(i, a); + }, f.prototype.mulf = function(i) { + var a = new f(null); + return a.words = new Array(this.length + i.length), _e(this, i, a); + }, f.prototype.imul = function(i) { + return this.clone().mulTo(i, this); + }, f.prototype.imuln = function(i) { + r(typeof i == "number"), r(i < 67108864); + for (var a = 0, h = 0;h < this.length; h++) { + var s = (this.words[h] | 0) * i, u = (s & 67108863) + (a & 67108863); + a >>= 26, a += s / 67108864 | 0, a += u >>> 26, this.words[h] = u & 67108863; + } + return a !== 0 && (this.words[h] = a, this.length++), this; + }, f.prototype.muln = function(i) { + return this.clone().imuln(i); + }, f.prototype.sqr = function() { + return this.mul(this); + }, f.prototype.isqr = function() { + return this.imul(this.clone()); + }, f.prototype.pow = function(i) { + var a = B(i); + if (a.length === 0) + return new f(1); + for (var h = this, s = 0;s < a.length && a[s] === 0; s++, h = h.sqr()) + ; + if (++s < a.length) + for (var u = h.sqr();s < a.length; s++, u = u.sqr()) + a[s] !== 0 && (h = h.mul(u)); + return h; + }, f.prototype.iushln = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26, s = 67108863 >>> 26 - a << 26 - a, u; + if (a !== 0) { + var c = 0; + for (u = 0;u < this.length; u++) { + var b = this.words[u] & s, l = (this.words[u] | 0) - b << a; + this.words[u] = l | c, c = b >>> 26 - a; + } + c && (this.words[u] = c, this.length++); + } + if (h !== 0) { + for (u = this.length - 1;u >= 0; u--) + this.words[u + h] = this.words[u]; + for (u = 0;u < h; u++) + this.words[u] = 0; + this.length += h; + } + return this.strip(); + }, f.prototype.ishln = function(i) { + return r(this.negative === 0), this.iushln(i); + }, f.prototype.iushrn = function(i, a, h) { + r(typeof i == "number" && i >= 0); + var s; + a ? s = (a - a % 26) / 26 : s = 0; + var u = i % 26, c = Math.min((i - u) / 26, this.length), b = 67108863 ^ 67108863 >>> u << u, l = h; + if (s -= c, s = Math.max(0, s), l) { + for (var n = 0;n < c; n++) + l.words[n] = this.words[n]; + l.length = c; + } + if (c !== 0) + if (this.length > c) + for (this.length -= c, n = 0;n < this.length; n++) + this.words[n] = this.words[n + c]; + else + this.words[0] = 0, this.length = 1; + var d = 0; + for (n = this.length - 1;n >= 0 && (d !== 0 || n >= s); n--) { + var w = this.words[n] | 0; + this.words[n] = d << 26 - u | w >>> u, d = w & b; + } + return l && d !== 0 && (l.words[l.length++] = d), this.length === 0 && (this.words[0] = 0, this.length = 1), this.strip(); + }, f.prototype.ishrn = function(i, a, h) { + return r(this.negative === 0), this.iushrn(i, a, h); + }, f.prototype.shln = function(i) { + return this.clone().ishln(i); + }, f.prototype.ushln = function(i) { + return this.clone().iushln(i); + }, f.prototype.shrn = function(i) { + return this.clone().ishrn(i); + }, f.prototype.ushrn = function(i) { + return this.clone().iushrn(i); + }, f.prototype.testn = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26, s = 1 << a; + if (this.length <= h) + return false; + var u = this.words[h]; + return !!(u & s); + }, f.prototype.imaskn = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26; + if (r(this.negative === 0, "imaskn works only with positive numbers"), this.length <= h) + return this; + if (a !== 0 && h++, this.length = Math.min(h, this.length), a !== 0) { + var s = 67108863 ^ 67108863 >>> a << a; + this.words[this.length - 1] &= s; + } + return this.strip(); + }, f.prototype.maskn = function(i) { + return this.clone().imaskn(i); + }, f.prototype.iaddn = function(i) { + return r(typeof i == "number"), r(i < 67108864), i < 0 ? this.isubn(-i) : this.negative !== 0 ? this.length === 1 && (this.words[0] | 0) < i ? (this.words[0] = i - (this.words[0] | 0), this.negative = 0, this) : (this.negative = 0, this.isubn(i), this.negative = 1, this) : this._iaddn(i); + }, f.prototype._iaddn = function(i) { + this.words[0] += i; + for (var a = 0;a < this.length && this.words[a] >= 67108864; a++) + this.words[a] -= 67108864, a === this.length - 1 ? this.words[a + 1] = 1 : this.words[a + 1]++; + return this.length = Math.max(this.length, a + 1), this; + }, f.prototype.isubn = function(i) { + if (r(typeof i == "number"), r(i < 67108864), i < 0) + return this.iaddn(-i); + if (this.negative !== 0) + return this.negative = 0, this.iaddn(i), this.negative = 1, this; + if (this.words[0] -= i, this.length === 1 && this.words[0] < 0) + this.words[0] = -this.words[0], this.negative = 1; + else + for (var a = 0;a < this.length && this.words[a] < 0; a++) + this.words[a] += 67108864, this.words[a + 1] -= 1; + return this.strip(); + }, f.prototype.addn = function(i) { + return this.clone().iaddn(i); + }, f.prototype.subn = function(i) { + return this.clone().isubn(i); + }, f.prototype.iabs = function() { + return this.negative = 0, this; + }, f.prototype.abs = function() { + return this.clone().iabs(); + }, f.prototype._ishlnsubmul = function(i, a, h) { + var s = i.length + h, u; + this._expand(s); + var c, b = 0; + for (u = 0;u < i.length; u++) { + c = (this.words[u + h] | 0) + b; + var l = (i.words[u] | 0) * a; + c -= l & 67108863, b = (c >> 26) - (l / 67108864 | 0), this.words[u + h] = c & 67108863; + } + for (;u < this.length - h; u++) + c = (this.words[u + h] | 0) + b, b = c >> 26, this.words[u + h] = c & 67108863; + if (b === 0) + return this.strip(); + for (r(b === -1), b = 0, u = 0;u < this.length; u++) + c = -(this.words[u] | 0) + b, b = c >> 26, this.words[u] = c & 67108863; + return this.negative = 1, this.strip(); + }, f.prototype._wordDiv = function(i, a) { + var h = this.length - i.length, s = this.clone(), u = i, c = u.words[u.length - 1] | 0, b = this._countBits(c); + h = 26 - b, h !== 0 && (u = u.ushln(h), s.iushln(h), c = u.words[u.length - 1] | 0); + var l = s.length - u.length, n; + if (a !== "mod") { + n = new f(null), n.length = l + 1, n.words = new Array(n.length); + for (var d = 0;d < n.length; d++) + n.words[d] = 0; + } + var w = s.clone()._ishlnsubmul(u, 1, l); + w.negative === 0 && (s = w, n && (n.words[l] = 1)); + for (var g = l - 1;g >= 0; g--) { + var _9 = (s.words[u.length + g] | 0) * 67108864 + (s.words[u.length + g - 1] | 0); + for (_9 = Math.min(_9 / c | 0, 67108863), s._ishlnsubmul(u, _9, g);s.negative !== 0; ) + _9--, s.negative = 0, s._ishlnsubmul(u, 1, g), s.isZero() || (s.negative ^= 1); + n && (n.words[g] = _9); + } + return n && n.strip(), s.strip(), a !== "div" && h !== 0 && s.iushrn(h), { div: n || null, mod: s }; + }, f.prototype.divmod = function(i, a, h) { + if (r(!i.isZero()), this.isZero()) + return { div: new f(0), mod: new f(0) }; + var s, u, c; + return this.negative !== 0 && i.negative === 0 ? (c = this.neg().divmod(i, a), a !== "mod" && (s = c.div.neg()), a !== "div" && (u = c.mod.neg(), h && u.negative !== 0 && u.iadd(i)), { div: s, mod: u }) : this.negative === 0 && i.negative !== 0 ? (c = this.divmod(i.neg(), a), a !== "mod" && (s = c.div.neg()), { div: s, mod: c.mod }) : (this.negative & i.negative) !== 0 ? (c = this.neg().divmod(i.neg(), a), a !== "div" && (u = c.mod.neg(), h && u.negative !== 0 && u.isub(i)), { div: c.div, mod: u }) : i.length > this.length || this.cmp(i) < 0 ? { div: new f(0), mod: this } : i.length === 1 ? a === "div" ? { div: this.divn(i.words[0]), mod: null } : a === "mod" ? { div: null, mod: new f(this.modn(i.words[0])) } : { div: this.divn(i.words[0]), mod: new f(this.modn(i.words[0])) } : this._wordDiv(i, a); + }, f.prototype.div = function(i) { + return this.divmod(i, "div", false).div; + }, f.prototype.mod = function(i) { + return this.divmod(i, "mod", false).mod; + }, f.prototype.umod = function(i) { + return this.divmod(i, "mod", true).mod; + }, f.prototype.divRound = function(i) { + var a = this.divmod(i); + if (a.mod.isZero()) + return a.div; + var h = a.div.negative !== 0 ? a.mod.isub(i) : a.mod, s = i.ushrn(1), u = i.andln(1), c = h.cmp(s); + return c < 0 || u === 1 && c === 0 ? a.div : a.div.negative !== 0 ? a.div.isubn(1) : a.div.iaddn(1); + }, f.prototype.modn = function(i) { + r(i <= 67108863); + for (var a = (1 << 26) % i, h = 0, s = this.length - 1;s >= 0; s--) + h = (a * h + (this.words[s] | 0)) % i; + return h; + }, f.prototype.idivn = function(i) { + r(i <= 67108863); + for (var a = 0, h = this.length - 1;h >= 0; h--) { + var s = (this.words[h] | 0) + a * 67108864; + this.words[h] = s / i | 0, a = s % i; + } + return this.strip(); + }, f.prototype.divn = function(i) { + return this.clone().idivn(i); + }, f.prototype.egcd = function(i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, h = i.clone(); + a.negative !== 0 ? a = a.umod(i) : a = a.clone(); + for (var s = new f(1), u = new f(0), c = new f(0), b = new f(1), l = 0;a.isEven() && h.isEven(); ) + a.iushrn(1), h.iushrn(1), ++l; + for (var n = h.clone(), d = a.clone();!a.isZero(); ) { + for (var w = 0, g = 1;(a.words[0] & g) === 0 && w < 26; ++w, g <<= 1) + ; + if (w > 0) + for (a.iushrn(w);w-- > 0; ) + (s.isOdd() || u.isOdd()) && (s.iadd(n), u.isub(d)), s.iushrn(1), u.iushrn(1); + for (var _9 = 0, A = 1;(h.words[0] & A) === 0 && _9 < 26; ++_9, A <<= 1) + ; + if (_9 > 0) + for (h.iushrn(_9);_9-- > 0; ) + (c.isOdd() || b.isOdd()) && (c.iadd(n), b.isub(d)), c.iushrn(1), b.iushrn(1); + a.cmp(h) >= 0 ? (a.isub(h), s.isub(c), u.isub(b)) : (h.isub(a), c.isub(s), b.isub(u)); + } + return { a: c, b, gcd: h.iushln(l) }; + }, f.prototype._invmp = function(i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, h = i.clone(); + a.negative !== 0 ? a = a.umod(i) : a = a.clone(); + for (var s = new f(1), u = new f(0), c = h.clone();a.cmpn(1) > 0 && h.cmpn(1) > 0; ) { + for (var b = 0, l = 1;(a.words[0] & l) === 0 && b < 26; ++b, l <<= 1) + ; + if (b > 0) + for (a.iushrn(b);b-- > 0; ) + s.isOdd() && s.iadd(c), s.iushrn(1); + for (var n = 0, d = 1;(h.words[0] & d) === 0 && n < 26; ++n, d <<= 1) + ; + if (n > 0) + for (h.iushrn(n);n-- > 0; ) + u.isOdd() && u.iadd(c), u.iushrn(1); + a.cmp(h) >= 0 ? (a.isub(h), s.isub(u)) : (h.isub(a), u.isub(s)); + } + var w; + return a.cmpn(1) === 0 ? w = s : w = u, w.cmpn(0) < 0 && w.iadd(i), w; + }, f.prototype.gcd = function(i) { + if (this.isZero()) + return i.abs(); + if (i.isZero()) + return this.abs(); + var a = this.clone(), h = i.clone(); + a.negative = 0, h.negative = 0; + for (var s = 0;a.isEven() && h.isEven(); s++) + a.iushrn(1), h.iushrn(1); + do { + for (;a.isEven(); ) + a.iushrn(1); + for (;h.isEven(); ) + h.iushrn(1); + var u = a.cmp(h); + if (u < 0) { + var c = a; + a = h, h = c; + } else if (u === 0 || h.cmpn(1) === 0) + break; + a.isub(h); + } while (true); + return h.iushln(s); + }, f.prototype.invm = function(i) { + return this.egcd(i).a.umod(i); + }, f.prototype.isEven = function() { + return (this.words[0] & 1) === 0; + }, f.prototype.isOdd = function() { + return (this.words[0] & 1) === 1; + }, f.prototype.andln = function(i) { + return this.words[0] & i; + }, f.prototype.bincn = function(i) { + r(typeof i == "number"); + var a = i % 26, h = (i - a) / 26, s = 1 << a; + if (this.length <= h) + return this._expand(h + 1), this.words[h] |= s, this; + for (var u = s, c = h;u !== 0 && c < this.length; c++) { + var b = this.words[c] | 0; + b += u, u = b >>> 26, b &= 67108863, this.words[c] = b; + } + return u !== 0 && (this.words[c] = u, this.length++), this; + }, f.prototype.isZero = function() { + return this.length === 1 && this.words[0] === 0; + }, f.prototype.cmpn = function(i) { + var a = i < 0; + if (this.negative !== 0 && !a) + return -1; + if (this.negative === 0 && a) + return 1; + this.strip(); + var h; + if (this.length > 1) + h = 1; + else { + a && (i = -i), r(i <= 67108863, "Number is too big"); + var s = this.words[0] | 0; + h = s === i ? 0 : s < i ? -1 : 1; + } + return this.negative !== 0 ? -h | 0 : h; + }, f.prototype.cmp = function(i) { + if (this.negative !== 0 && i.negative === 0) + return -1; + if (this.negative === 0 && i.negative !== 0) + return 1; + var a = this.ucmp(i); + return this.negative !== 0 ? -a | 0 : a; + }, f.prototype.ucmp = function(i) { + if (this.length > i.length) + return 1; + if (this.length < i.length) + return -1; + for (var a = 0, h = this.length - 1;h >= 0; h--) { + var s = this.words[h] | 0, u = i.words[h] | 0; + if (s !== u) { + s < u ? a = -1 : s > u && (a = 1); + break; + } + } + return a; + }, f.prototype.gtn = function(i) { + return this.cmpn(i) === 1; + }, f.prototype.gt = function(i) { + return this.cmp(i) === 1; + }, f.prototype.gten = function(i) { + return this.cmpn(i) >= 0; + }, f.prototype.gte = function(i) { + return this.cmp(i) >= 0; + }, f.prototype.ltn = function(i) { + return this.cmpn(i) === -1; + }, f.prototype.lt = function(i) { + return this.cmp(i) === -1; + }, f.prototype.lten = function(i) { + return this.cmpn(i) <= 0; + }, f.prototype.lte = function(i) { + return this.cmp(i) <= 0; + }, f.prototype.eqn = function(i) { + return this.cmpn(i) === 0; + }, f.prototype.eq = function(i) { + return this.cmp(i) === 0; + }, f.red = function(i) { + return new P(i); + }, f.prototype.toRed = function(i) { + return r(!this.red, "Already a number in reduction context"), r(this.negative === 0, "red works only with positives"), i.convertTo(this)._forceRed(i); + }, f.prototype.fromRed = function() { + return r(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); + }, f.prototype._forceRed = function(i) { + return this.red = i, this; + }, f.prototype.forceRed = function(i) { + return r(!this.red, "Already a number in reduction context"), this._forceRed(i); + }, f.prototype.redAdd = function(i) { + return r(this.red, "redAdd works only with red numbers"), this.red.add(this, i); + }, f.prototype.redIAdd = function(i) { + return r(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, i); + }, f.prototype.redSub = function(i) { + return r(this.red, "redSub works only with red numbers"), this.red.sub(this, i); + }, f.prototype.redISub = function(i) { + return r(this.red, "redISub works only with red numbers"), this.red.isub(this, i); + }, f.prototype.redShl = function(i) { + return r(this.red, "redShl works only with red numbers"), this.red.shl(this, i); + }, f.prototype.redMul = function(i) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, i), this.red.mul(this, i); + }, f.prototype.redIMul = function(i) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, i), this.red.imul(this, i); + }, f.prototype.redSqr = function() { + return r(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); + }, f.prototype.redISqr = function() { + return r(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); + }, f.prototype.redSqrt = function() { + return r(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); + }, f.prototype.redInvm = function() { + return r(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); + }, f.prototype.redNeg = function() { + return r(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); + }, f.prototype.redPow = function(i) { + return r(this.red && !i.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, i); + }; + var we = { k256: null, p224: null, p192: null, p25519: null }; + function ye(v, i) { + this.name = v, this.p = new f(i, 16), this.n = this.p.bitLength(), this.k = new f(1).iushln(this.n).isub(this.p), this.tmp = this._tmp(); + } + ye.prototype._tmp = function() { + var i = new f(null); + return i.words = new Array(Math.ceil(this.n / 13)), i; + }, ye.prototype.ireduce = function(i) { + var a = i, h; + do + this.split(a, this.tmp), a = this.imulK(a), a = a.iadd(this.tmp), h = a.bitLength(); + while (h > this.n); + var s = h < this.n ? -1 : a.ucmp(this.p); + return s === 0 ? (a.words[0] = 0, a.length = 1) : s > 0 ? a.isub(this.p) : a.strip !== undefined ? a.strip() : a._strip(), a; + }, ye.prototype.split = function(i, a) { + i.iushrn(this.n, 0, a); + }, ye.prototype.imulK = function(i) { + return i.imul(this.k); + }; + function xe() { + ye.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); + } + o(xe, ye), xe.prototype.split = function(i, a) { + for (var h = 4194303, s = Math.min(i.length, 9), u = 0;u < s; u++) + a.words[u] = i.words[u]; + if (a.length = s, i.length <= 9) { + i.words[0] = 0, i.length = 1; + return; + } + var c = i.words[9]; + for (a.words[a.length++] = c & h, u = 10;u < i.length; u++) { + var b = i.words[u] | 0; + i.words[u - 10] = (b & h) << 4 | c >>> 22, c = b; + } + c >>>= 22, i.words[u - 10] = c, c === 0 && i.length > 10 ? i.length -= 10 : i.length -= 9; + }, xe.prototype.imulK = function(i) { + i.words[i.length] = 0, i.words[i.length + 1] = 0, i.length += 2; + for (var a = 0, h = 0;h < i.length; h++) { + var s = i.words[h] | 0; + a += s * 977, i.words[h] = a & 67108863, a = s * 64 + (a / 67108864 | 0); + } + return i.words[i.length - 1] === 0 && (i.length--, i.words[i.length - 1] === 0 && i.length--), i; + }; + function Re() { + ye.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); + } + o(Re, ye); + function Ee() { + ye.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); + } + o(Ee, ye); + function Ae() { + ye.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); + } + o(Ae, ye), Ae.prototype.imulK = function(i) { + for (var a = 0, h = 0;h < i.length; h++) { + var s = (i.words[h] | 0) * 19 + a, u = s & 67108863; + s >>>= 26, i.words[h] = u, a = s; + } + return a !== 0 && (i.words[i.length++] = a), i; + }, f._prime = function(i) { + if (we[i]) + return we[i]; + var a; + if (i === "k256") + a = new xe; + else if (i === "p224") + a = new Re; + else if (i === "p192") + a = new Ee; + else if (i === "p25519") + a = new Ae; + else + throw new Error("Unknown prime " + i); + return we[i] = a, a; + }; + function P(v) { + if (typeof v == "string") { + var i = f._prime(v); + this.m = i.p, this.prime = i; + } else + r(v.gtn(1), "modulus must be greater than 1"), this.m = v, this.prime = null; + } + P.prototype._verify1 = function(i) { + r(i.negative === 0, "red works only with positives"), r(i.red, "red works only with red numbers"); + }, P.prototype._verify2 = function(i, a) { + r((i.negative | a.negative) === 0, "red works only with positives"), r(i.red && i.red === a.red, "red works only with red numbers"); + }, P.prototype.imod = function(i) { + return this.prime ? this.prime.ireduce(i)._forceRed(this) : i.umod(this.m)._forceRed(this); + }, P.prototype.neg = function(i) { + return i.isZero() ? i.clone() : this.m.sub(i)._forceRed(this); + }, P.prototype.add = function(i, a) { + this._verify2(i, a); + var h = i.add(a); + return h.cmp(this.m) >= 0 && h.isub(this.m), h._forceRed(this); + }, P.prototype.iadd = function(i, a) { + this._verify2(i, a); + var h = i.iadd(a); + return h.cmp(this.m) >= 0 && h.isub(this.m), h; + }, P.prototype.sub = function(i, a) { + this._verify2(i, a); + var h = i.sub(a); + return h.cmpn(0) < 0 && h.iadd(this.m), h._forceRed(this); + }, P.prototype.isub = function(i, a) { + this._verify2(i, a); + var h = i.isub(a); + return h.cmpn(0) < 0 && h.iadd(this.m), h; + }, P.prototype.shl = function(i, a) { + return this._verify1(i), this.imod(i.ushln(a)); + }, P.prototype.imul = function(i, a) { + return this._verify2(i, a), this.imod(i.imul(a)); + }, P.prototype.mul = function(i, a) { + return this._verify2(i, a), this.imod(i.mul(a)); + }, P.prototype.isqr = function(i) { + return this.imul(i, i.clone()); + }, P.prototype.sqr = function(i) { + return this.mul(i, i); + }, P.prototype.sqrt = function(i) { + if (i.isZero()) + return i.clone(); + var a = this.m.andln(3); + if (r(a % 2 === 1), a === 3) { + var h = this.m.add(new f(1)).iushrn(2); + return this.pow(i, h); + } + for (var s = this.m.subn(1), u = 0;!s.isZero() && s.andln(1) === 0; ) + u++, s.iushrn(1); + r(!s.isZero()); + var c = new f(1).toRed(this), b = c.redNeg(), l = this.m.subn(1).iushrn(1), n = this.m.bitLength(); + for (n = new f(2 * n * n).toRed(this);this.pow(n, l).cmp(b) !== 0; ) + n.redIAdd(b); + for (var d = this.pow(n, s), w = this.pow(i, s.addn(1).iushrn(1)), g = this.pow(i, s), _9 = u;g.cmp(c) !== 0; ) { + for (var A = g, R = 0;A.cmp(c) !== 0; R++) + A = A.redSqr(); + r(R < _9); + var I2 = this.pow(d, new f(1).iushln(_9 - R - 1)); + w = w.redMul(I2), d = I2.redSqr(), g = g.redMul(d), _9 = R; + } + return w; + }, P.prototype.invm = function(i) { + var a = i._invmp(this.m); + return a.negative !== 0 ? (a.negative = 0, this.imod(a).redNeg()) : this.imod(a); + }, P.prototype.pow = function(i, a) { + if (a.isZero()) + return new f(1).toRed(this); + if (a.cmpn(1) === 0) + return i.clone(); + var h = 4, s = new Array(1 << h); + s[0] = new f(1).toRed(this), s[1] = i; + for (var u = 2;u < s.length; u++) + s[u] = this.mul(s[u - 1], i); + var c = s[0], b = 0, l = 0, n = a.bitLength() % 26; + for (n === 0 && (n = 26), u = a.length - 1;u >= 0; u--) { + for (var d = a.words[u], w = n - 1;w >= 0; w--) { + var g = d >> w & 1; + if (c !== s[0] && (c = this.sqr(c)), g === 0 && b === 0) { + l = 0; + continue; + } + b <<= 1, b |= g, l++, !(l !== h && (u !== 0 || w !== 0)) && (c = this.mul(c, s[b]), l = 0, b = 0); + } + n = 26; + } + return c; + }, P.prototype.convertTo = function(i) { + var a = i.umod(this.m); + return a === i ? a.clone() : a; + }, P.prototype.convertFrom = function(i) { + var a = i.clone(); + return a.red = null, a; + }, f.mont = function(i) { + return new Se2(i); + }; + function Se2(v) { + P.call(this, v), this.shift = this.m.bitLength(), this.shift % 26 !== 0 && (this.shift += 26 - this.shift % 26), this.r = new f(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv); + } + o(Se2, P), Se2.prototype.convertTo = function(i) { + return this.imod(i.ushln(this.shift)); + }, Se2.prototype.convertFrom = function(i) { + var a = this.imod(i.mul(this.rinv)); + return a.red = null, a; + }, Se2.prototype.imul = function(i, a) { + if (i.isZero() || a.isZero()) + return i.words[0] = 0, i.length = 1, i; + var h = i.imul(a), s = h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = h.isub(s).iushrn(this.shift), c = u; + return u.cmp(this.m) >= 0 ? c = u.isub(this.m) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }, Se2.prototype.mul = function(i, a) { + if (i.isZero() || a.isZero()) + return new f(0)._forceRed(this); + var h = i.mul(a), s = h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = h.isub(s).iushrn(this.shift), c = u; + return u.cmp(this.m) >= 0 ? c = u.isub(this.m) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }, Se2.prototype.invm = function(i) { + var a = this.imod(i._invmp(this.m).mul(this.r2)); + return a._forceRed(this); + }; + })(typeof ed > "u" || ed, ky); + }); + h0 = T((Yk, Ly) => { + var s0 = Ut2(), Ff = s0.Buffer, Er2 = {}, Ar; + for (Ar in s0) + !s0.hasOwnProperty(Ar) || Ar === "SlowBuffer" || Ar === "Buffer" || (Er2[Ar] = s0[Ar]); + var Uf = Er2.Buffer = {}; + for (Ar in Ff) + !Ff.hasOwnProperty(Ar) || Ar === "allocUnsafe" || Ar === "allocUnsafeSlow" || (Uf[Ar] = Ff[Ar]); + Er2.Buffer.prototype = Ff.prototype; + (!Uf.from || Uf.from === Uint8Array.from) && (Uf.from = function(t, e, r) { + if (typeof t == "number") + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof t); + if (t && typeof t.length > "u") + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof t); + return Ff(t, e, r); + }); + Uf.alloc || (Uf.alloc = function(t, e, r) { + if (typeof t != "number") + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof t); + if (t < 0 || t >= 2 * (1 << 30)) + throw new RangeError('The value "' + t + '" is invalid for option "size"'); + var o = Ff(t); + return !e || e.length === 0 ? o.fill(0) : typeof r == "string" ? o.fill(e, r) : o.fill(e), o; + }); + if (!Er2.kStringMaxLength) + try { + Er2.kStringMaxLength = process.binding("buffer").kStringMaxLength; + } catch { + } + Er2.constants || (Er2.constants = { MAX_LENGTH: Er2.kMaxLength }, Er2.kStringMaxLength && (Er2.constants.MAX_STRING_LENGTH = Er2.kStringMaxLength)); + Ly.exports = Er2; + }); + u0 = T((Ny) => { + var aB = Ie(); + function Rr(t) { + this._reporterState = { obj: null, path: [], options: t || {}, errors: [] }; + } + Ny.Reporter = Rr; + Rr.prototype.isError = function(e) { + return e instanceof zf; + }; + Rr.prototype.save = function() { + let e = this._reporterState; + return { obj: e.obj, pathLen: e.path.length }; + }; + Rr.prototype.restore = function(e) { + let r = this._reporterState; + r.obj = e.obj, r.path = r.path.slice(0, e.pathLen); + }; + Rr.prototype.enterKey = function(e) { + return this._reporterState.path.push(e); + }; + Rr.prototype.exitKey = function(e) { + let r = this._reporterState; + r.path = r.path.slice(0, e - 1); + }; + Rr.prototype.leaveKey = function(e, r, o) { + let f = this._reporterState; + this.exitKey(e), f.obj !== null && (f.obj[r] = o); + }; + Rr.prototype.path = function() { + return this._reporterState.path.join("/"); + }; + Rr.prototype.enterObject = function() { + let e = this._reporterState, r = e.obj; + return e.obj = {}, r; + }; + Rr.prototype.leaveObject = function(e) { + let r = this._reporterState, o = r.obj; + return r.obj = e, o; + }; + Rr.prototype.error = function(e) { + let r, o = this._reporterState, f = e instanceof zf; + if (f ? r = e : r = new zf(o.path.map(function(p) { + return "[" + JSON.stringify(p) + "]"; + }).join(""), e.message || e, e.stack), !o.options.partial) + throw r; + return f || o.errors.push(r), r; + }; + Rr.prototype.wrapResult = function(e) { + let r = this._reporterState; + return r.options.partial ? { result: this.isError(e) ? null : e, errors: r.errors } : e; + }; + function zf(t, e) { + this.path = t, this.rethrow(e); + } + aB(zf, Error); + zf.prototype.rethrow = function(e) { + if (this.message = e + " at: " + (this.path || "(shallow)"), Error.captureStackTrace && Error.captureStackTrace(this, zf), !this.stack) + try { + throw new Error(this.message); + } catch (r) { + this.stack = r.stack; + } + return this; + }; + }); + Kf = T((rd) => { + var oB = Ie(), l0 = u0().Reporter, Hf = h0().Buffer; + function Br(t, e) { + if (l0.call(this, e), !Hf.isBuffer(t)) { + this.error("Input not Buffer"); + return; + } + this.base = t, this.offset = 0, this.length = t.length; + } + oB(Br, l0); + rd.DecoderBuffer = Br; + Br.isDecoderBuffer = function(e) { + return e instanceof Br ? true : typeof e == "object" && Hf.isBuffer(e.base) && e.constructor.name === "DecoderBuffer" && typeof e.offset == "number" && typeof e.length == "number" && typeof e.save == "function" && typeof e.restore == "function" && typeof e.isEmpty == "function" && typeof e.readUInt8 == "function" && typeof e.skip == "function" && typeof e.raw == "function"; + }; + Br.prototype.save = function() { + return { offset: this.offset, reporter: l0.prototype.save.call(this) }; + }; + Br.prototype.restore = function(e) { + let r = new Br(this.base); + return r.offset = e.offset, r.length = this.offset, this.offset = e.offset, l0.prototype.restore.call(this, e.reporter), r; + }; + Br.prototype.isEmpty = function() { + return this.offset === this.length; + }; + Br.prototype.readUInt8 = function(e) { + return this.offset + 1 <= this.length ? this.base.readUInt8(this.offset++, true) : this.error(e || "DecoderBuffer overrun"); + }; + Br.prototype.skip = function(e, r) { + if (!(this.offset + e <= this.length)) + return this.error(r || "DecoderBuffer overrun"); + let o = new Br(this.base); + return o._reporterState = this._reporterState, o.offset = this.offset, o.length = this.offset + e, this.offset += e, o; + }; + Br.prototype.raw = function(e) { + return this.base.slice(e ? e.offset : this.offset, this.length); + }; + function Wf(t, e) { + if (Array.isArray(t)) + this.length = 0, this.value = t.map(function(r) { + return Wf.isEncoderBuffer(r) || (r = new Wf(r, e)), this.length += r.length, r; + }, this); + else if (typeof t == "number") { + if (!(0 <= t && t <= 255)) + return e.error("non-byte EncoderBuffer value"); + this.value = t, this.length = 1; + } else if (typeof t == "string") + this.value = t, this.length = Hf.byteLength(t); + else if (Hf.isBuffer(t)) + this.value = t, this.length = t.length; + else + return e.error("Unsupported type: " + typeof t); + } + rd.EncoderBuffer = Wf; + Wf.isEncoderBuffer = function(e) { + return e instanceof Wf ? true : typeof e == "object" && e.constructor.name === "EncoderBuffer" && typeof e.length == "number" && typeof e.join == "function"; + }; + Wf.prototype.join = function(e, r) { + return e || (e = Hf.alloc(this.length)), r || (r = 0), this.length === 0 || (Array.isArray(this.value) ? this.value.forEach(function(o) { + o.join(e, r), r += o.length; + }) : (typeof this.value == "number" ? e[r] = this.value : typeof this.value == "string" ? e.write(this.value, r) : Hf.isBuffer(this.value) && this.value.copy(e, r), r += this.length)), e; + }; + }); + d0 = T((Qk, Py) => { + var sB = u0().Reporter, hB = Kf().EncoderBuffer, uB = Kf().DecoderBuffer, Qt = ar(), Dy = ["seq", "seqof", "set", "setof", "objid", "bool", "gentime", "utctime", "null_", "enum", "int", "objDesc", "bitstr", "bmpstr", "charstr", "genstr", "graphstr", "ia5str", "iso646str", "numstr", "octstr", "printstr", "t61str", "unistr", "utf8str", "videostr"], lB = ["key", "obj", "use", "optional", "explicit", "implicit", "def", "choice", "any", "contains"].concat(Dy), dB = ["_peekTag", "_decodeTag", "_use", "_decodeStr", "_decodeObjid", "_decodeTime", "_decodeNull", "_decodeInt", "_decodeBool", "_decodeList", "_encodeComposite", "_encodeStr", "_encodeObjid", "_encodeTime", "_encodeNull", "_encodeInt", "_encodeBool"]; + function Ue(t, e, r) { + let o = {}; + this._baseState = o, o.name = r, o.enc = t, o.parent = e || null, o.children = null, o.tag = null, o.args = null, o.reverseArgs = null, o.choice = null, o.optional = false, o.any = false, o.obj = false, o.use = null, o.useDecoder = null, o.key = null, o.default = null, o.explicit = null, o.implicit = null, o.contains = null, o.parent || (o.children = [], this._wrap()); + } + Py.exports = Ue; + var cB = ["enc", "parent", "children", "tag", "args", "reverseArgs", "choice", "optional", "any", "obj", "use", "alteredUse", "key", "default", "explicit", "implicit", "contains"]; + Ue.prototype.clone = function() { + let e = this._baseState, r = {}; + cB.forEach(function(f) { + r[f] = e[f]; + }); + let o = new this.constructor(r.parent); + return o._baseState = r, o; + }; + Ue.prototype._wrap = function() { + let e = this._baseState; + lB.forEach(function(r) { + this[r] = function() { + let f = new this.constructor(this); + return e.children.push(f), f[r].apply(f, arguments); + }; + }, this); + }; + Ue.prototype._init = function(e) { + let r = this._baseState; + Qt(r.parent === null), e.call(this), r.children = r.children.filter(function(o) { + return o._baseState.parent === this; + }, this), Qt.equal(r.children.length, 1, "Root node can have only one child"); + }; + Ue.prototype._useArgs = function(e) { + let r = this._baseState, o = e.filter(function(f) { + return f instanceof this.constructor; + }, this); + e = e.filter(function(f) { + return !(f instanceof this.constructor); + }, this), o.length !== 0 && (Qt(r.children === null), r.children = o, o.forEach(function(f) { + f._baseState.parent = this; + }, this)), e.length !== 0 && (Qt(r.args === null), r.args = e, r.reverseArgs = e.map(function(f) { + if (typeof f != "object" || f.constructor !== Object) + return f; + let p = {}; + return Object.keys(f).forEach(function(m) { + m == (m | 0) && (m |= 0); + let y = f[m]; + p[y] = m; + }), p; + })); + }; + dB.forEach(function(t) { + Ue.prototype[t] = function() { + let r = this._baseState; + throw new Error(t + " not implemented for encoding: " + r.enc); + }; + }); + Dy.forEach(function(t) { + Ue.prototype[t] = function() { + let r = this._baseState, o = Array.prototype.slice.call(arguments); + return Qt(r.tag === null), r.tag = t, this._useArgs(o), this; + }; + }); + Ue.prototype.use = function(e) { + Qt(e); + let r = this._baseState; + return Qt(r.use === null), r.use = e, this; + }; + Ue.prototype.optional = function() { + let e = this._baseState; + return e.optional = true, this; + }; + Ue.prototype.def = function(e) { + let r = this._baseState; + return Qt(r.default === null), r.default = e, r.optional = true, this; + }; + Ue.prototype.explicit = function(e) { + let r = this._baseState; + return Qt(r.explicit === null && r.implicit === null), r.explicit = e, this; + }; + Ue.prototype.implicit = function(e) { + let r = this._baseState; + return Qt(r.explicit === null && r.implicit === null), r.implicit = e, this; + }; + Ue.prototype.obj = function() { + let e = this._baseState, r = Array.prototype.slice.call(arguments); + return e.obj = true, r.length !== 0 && this._useArgs(r), this; + }; + Ue.prototype.key = function(e) { + let r = this._baseState; + return Qt(r.key === null), r.key = e, this; + }; + Ue.prototype.any = function() { + let e = this._baseState; + return e.any = true, this; + }; + Ue.prototype.choice = function(e) { + let r = this._baseState; + return Qt(r.choice === null), r.choice = e, this._useArgs(Object.keys(e).map(function(o) { + return e[o]; + })), this; + }; + Ue.prototype.contains = function(e) { + let r = this._baseState; + return Qt(r.use === null), r.contains = e, this; + }; + Ue.prototype._decode = function(e, r) { + let o = this._baseState; + if (o.parent === null) + return e.wrapResult(o.children[0]._decode(e, r)); + let f = o.default, p = true, m = null; + if (o.key !== null && (m = e.enterKey(o.key)), o.optional) { + let M = null; + if (o.explicit !== null ? M = o.explicit : o.implicit !== null ? M = o.implicit : o.tag !== null && (M = o.tag), M === null && !o.any) { + let x = e.save(); + try { + o.choice === null ? this._decodeGeneric(o.tag, e, r) : this._decodeChoice(e, r), p = true; + } catch { + p = false; + } + e.restore(x); + } else if (p = this._peekTag(e, M, o.any), e.isError(p)) + return p; + } + let y; + if (o.obj && p && (y = e.enterObject()), p) { + if (o.explicit !== null) { + let x = this._decodeTag(e, o.explicit); + if (e.isError(x)) + return x; + e = x; + } + let M = e.offset; + if (o.use === null && o.choice === null) { + let x; + o.any && (x = e.save()); + let S = this._decodeTag(e, o.implicit !== null ? o.implicit : o.tag, o.any); + if (e.isError(S)) + return S; + o.any ? f = e.raw(x) : e = S; + } + if (r && r.track && o.tag !== null && r.track(e.path(), M, e.length, "tagged"), r && r.track && o.tag !== null && r.track(e.path(), e.offset, e.length, "content"), o.any || (o.choice === null ? f = this._decodeGeneric(o.tag, e, r) : f = this._decodeChoice(e, r)), e.isError(f)) + return f; + if (!o.any && o.choice === null && o.children !== null && o.children.forEach(function(S) { + S._decode(e, r); + }), o.contains && (o.tag === "octstr" || o.tag === "bitstr")) { + let x = new uB(f); + f = this._getUse(o.contains, e._reporterState.obj)._decode(x, r); + } + } + return o.obj && p && (f = e.leaveObject(y)), o.key !== null && (f !== null || p === true) ? e.leaveKey(m, o.key, f) : m !== null && e.exitKey(m), f; + }; + Ue.prototype._decodeGeneric = function(e, r, o) { + let f = this._baseState; + return e === "seq" || e === "set" ? null : e === "seqof" || e === "setof" ? this._decodeList(r, e, f.args[0], o) : /str$/.test(e) ? this._decodeStr(r, e, o) : e === "objid" && f.args ? this._decodeObjid(r, f.args[0], f.args[1], o) : e === "objid" ? this._decodeObjid(r, null, null, o) : e === "gentime" || e === "utctime" ? this._decodeTime(r, e, o) : e === "null_" ? this._decodeNull(r, o) : e === "bool" ? this._decodeBool(r, o) : e === "objDesc" ? this._decodeStr(r, e, o) : e === "int" || e === "enum" ? this._decodeInt(r, f.args && f.args[0], o) : f.use !== null ? this._getUse(f.use, r._reporterState.obj)._decode(r, o) : r.error("unknown tag: " + e); + }; + Ue.prototype._getUse = function(e, r) { + let o = this._baseState; + return o.useDecoder = this._use(e, r), Qt(o.useDecoder._baseState.parent === null), o.useDecoder = o.useDecoder._baseState.children[0], o.implicit !== o.useDecoder._baseState.implicit && (o.useDecoder = o.useDecoder.clone(), o.useDecoder._baseState.implicit = o.implicit), o.useDecoder; + }; + Ue.prototype._decodeChoice = function(e, r) { + let o = this._baseState, f = null, p = false; + return Object.keys(o.choice).some(function(m) { + let y = e.save(), M = o.choice[m]; + try { + let x = M._decode(e, r); + if (e.isError(x)) + return false; + f = { type: m, value: x }, p = true; + } catch { + return e.restore(y), false; + } + return true; + }, this), p ? f : e.error("Choice not matched"); + }; + Ue.prototype._createEncoderBuffer = function(e) { + return new hB(e, this.reporter); + }; + Ue.prototype._encode = function(e, r, o) { + let f = this._baseState; + if (f.default !== null && f.default === e) + return; + let p = this._encodeValue(e, r, o); + if (p !== undefined && !this._skipDefault(p, r, o)) + return p; + }; + Ue.prototype._encodeValue = function(e, r, o) { + let f = this._baseState; + if (f.parent === null) + return f.children[0]._encode(e, r || new sB); + let p = null; + if (this.reporter = r, f.optional && e === undefined) + if (f.default !== null) + e = f.default; + else + return; + let m = null, y = false; + if (f.any) + p = this._createEncoderBuffer(e); + else if (f.choice) + p = this._encodeChoice(e, r); + else if (f.contains) + m = this._getUse(f.contains, o)._encode(e, r), y = true; + else if (f.children) + m = f.children.map(function(M) { + if (M._baseState.tag === "null_") + return M._encode(null, r, e); + if (M._baseState.key === null) + return r.error("Child should have a key"); + let x = r.enterKey(M._baseState.key); + if (typeof e != "object") + return r.error("Child expected, but input is not object"); + let S = M._encode(e[M._baseState.key], r, e); + return r.leaveKey(x), S; + }, this).filter(function(M) { + return M; + }), m = this._createEncoderBuffer(m); + else if (f.tag === "seqof" || f.tag === "setof") { + if (!(f.args && f.args.length === 1)) + return r.error("Too many args for : " + f.tag); + if (!Array.isArray(e)) + return r.error("seqof/setof, but data is not Array"); + let M = this.clone(); + M._baseState.implicit = null, m = this._createEncoderBuffer(e.map(function(x) { + let S = this._baseState; + return this._getUse(S.args[0], e)._encode(x, r); + }, M)); + } else + f.use !== null ? p = this._getUse(f.use, o)._encode(e, r) : (m = this._encodePrimitive(f.tag, e), y = true); + if (!f.any && f.choice === null) { + let M = f.implicit !== null ? f.implicit : f.tag, x = f.implicit === null ? "universal" : "context"; + M === null ? f.use === null && r.error("Tag could be omitted only for .use()") : f.use === null && (p = this._encodeComposite(M, y, x, m)); + } + return f.explicit !== null && (p = this._encodeComposite(f.explicit, false, "context", p)), p; + }; + Ue.prototype._encodeChoice = function(e, r) { + let o = this._baseState, f = o.choice[e.type]; + return f || Qt(false, e.type + " not found in " + JSON.stringify(Object.keys(o.choice))), f._encode(e.value, r); + }; + Ue.prototype._encodePrimitive = function(e, r) { + let o = this._baseState; + if (/str$/.test(e)) + return this._encodeStr(r, e); + if (e === "objid" && o.args) + return this._encodeObjid(r, o.reverseArgs[0], o.args[1]); + if (e === "objid") + return this._encodeObjid(r, null, null); + if (e === "gentime" || e === "utctime") + return this._encodeTime(r, e); + if (e === "null_") + return this._encodeNull(); + if (e === "int" || e === "enum") + return this._encodeInt(r, o.args && o.reverseArgs[0]); + if (e === "bool") + return this._encodeBool(r); + if (e === "objDesc") + return this._encodeStr(r, e); + throw new Error("Unsupported tag: " + e); + }; + Ue.prototype._isNumstr = function(e) { + return /^[0-9 ]*$/.test(e); + }; + Ue.prototype._isPrintstr = function(e) { + return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(e); + }; + }); + c0 = T((Wn) => { + function Cy(t) { + let e = {}; + return Object.keys(t).forEach(function(r) { + (r | 0) == r && (r = r | 0); + let o = t[r]; + e[o] = r; + }), e; + } + Wn.tagClass = { 0: "universal", 1: "application", 2: "context", 3: "private" }; + Wn.tagClassByName = Cy(Wn.tagClass); + Wn.tag = { 0: "end", 1: "bool", 2: "int", 3: "bitstr", 4: "octstr", 5: "null_", 6: "objid", 7: "objDesc", 8: "external", 9: "real", 10: "enum", 11: "embed", 12: "utf8str", 13: "relativeOid", 16: "seq", 17: "set", 18: "numstr", 19: "printstr", 20: "t61str", 21: "videostr", 22: "ia5str", 23: "utctime", 24: "gentime", 25: "graphstr", 26: "iso646str", 27: "genstr", 28: "unistr", 29: "charstr", 30: "bmpstr" }; + Wn.tagByName = Cy(Wn.tag); + }); + nd = T((tL, Uy) => { + var pB = Ie(), Ii = h0().Buffer, Oy = d0(), id = c0(); + function Fy(t) { + this.enc = "der", this.name = t.name, this.entity = t, this.tree = new Ur, this.tree._init(t.body); + } + Uy.exports = Fy; + Fy.prototype.encode = function(e, r) { + return this.tree._encode(e, r).join(); + }; + function Ur(t) { + Oy.call(this, "der", t); + } + pB(Ur, Oy); + Ur.prototype._encodeComposite = function(e, r, o, f) { + let p = vB(e, r, o, this.reporter); + if (f.length < 128) { + let M = Ii.alloc(2); + return M[0] = p, M[1] = f.length, this._createEncoderBuffer([M, f]); + } + let m = 1; + for (let M = f.length;M >= 256; M >>= 8) + m++; + let y = Ii.alloc(1 + 1 + m); + y[0] = p, y[1] = 128 | m; + for (let M = 1 + m, x = f.length;x > 0; M--, x >>= 8) + y[M] = x & 255; + return this._createEncoderBuffer([y, f]); + }; + Ur.prototype._encodeStr = function(e, r) { + if (r === "bitstr") + return this._createEncoderBuffer([e.unused | 0, e.data]); + if (r === "bmpstr") { + let o = Ii.alloc(e.length * 2); + for (let f = 0;f < e.length; f++) + o.writeUInt16BE(e.charCodeAt(f), f * 2); + return this._createEncoderBuffer(o); + } else + return r === "numstr" ? this._isNumstr(e) ? this._createEncoderBuffer(e) : this.reporter.error("Encoding of string type: numstr supports only digits and space") : r === "printstr" ? this._isPrintstr(e) ? this._createEncoderBuffer(e) : this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark") : /str$/.test(r) ? this._createEncoderBuffer(e) : r === "objDesc" ? this._createEncoderBuffer(e) : this.reporter.error("Encoding of string type: " + r + " unsupported"); + }; + Ur.prototype._encodeObjid = function(e, r, o) { + if (typeof e == "string") { + if (!r) + return this.reporter.error("string objid given, but no values map found"); + if (!r.hasOwnProperty(e)) + return this.reporter.error("objid not found in values map"); + e = r[e].split(/[\s.]+/g); + for (let y = 0;y < e.length; y++) + e[y] |= 0; + } else if (Array.isArray(e)) { + e = e.slice(); + for (let y = 0;y < e.length; y++) + e[y] |= 0; + } + if (!Array.isArray(e)) + return this.reporter.error("objid() should be either array or string, got: " + JSON.stringify(e)); + if (!o) { + if (e[1] >= 40) + return this.reporter.error("Second objid identifier OOB"); + e.splice(0, 2, e[0] * 40 + e[1]); + } + let f = 0; + for (let y = 0;y < e.length; y++) { + let M = e[y]; + for (f++;M >= 128; M >>= 7) + f++; + } + let p = Ii.alloc(f), m = p.length - 1; + for (let y = e.length - 1;y >= 0; y--) { + let M = e[y]; + for (p[m--] = M & 127;(M >>= 7) > 0; ) + p[m--] = 128 | M & 127; + } + return this._createEncoderBuffer(p); + }; + function qr2(t) { + return t < 10 ? "0" + t : t; + } + Ur.prototype._encodeTime = function(e, r) { + let o, f = new Date(e); + return r === "gentime" ? o = [qr2(f.getUTCFullYear()), qr2(f.getUTCMonth() + 1), qr2(f.getUTCDate()), qr2(f.getUTCHours()), qr2(f.getUTCMinutes()), qr2(f.getUTCSeconds()), "Z"].join("") : r === "utctime" ? o = [qr2(f.getUTCFullYear() % 100), qr2(f.getUTCMonth() + 1), qr2(f.getUTCDate()), qr2(f.getUTCHours()), qr2(f.getUTCMinutes()), qr2(f.getUTCSeconds()), "Z"].join("") : this.reporter.error("Encoding " + r + " time is not supported yet"), this._encodeStr(o, "octstr"); + }; + Ur.prototype._encodeNull = function() { + return this._createEncoderBuffer(""); + }; + Ur.prototype._encodeInt = function(e, r) { + if (typeof e == "string") { + if (!r) + return this.reporter.error("String int or enum given, but no values map"); + if (!r.hasOwnProperty(e)) + return this.reporter.error("Values map doesn't contain: " + JSON.stringify(e)); + e = r[e]; + } + if (typeof e != "number" && !Ii.isBuffer(e)) { + let p = e.toArray(); + !e.sign && p[0] & 128 && p.unshift(0), e = Ii.from(p); + } + if (Ii.isBuffer(e)) { + let p = e.length; + e.length === 0 && p++; + let m = Ii.alloc(p); + return e.copy(m), e.length === 0 && (m[0] = 0), this._createEncoderBuffer(m); + } + if (e < 128) + return this._createEncoderBuffer(e); + if (e < 256) + return this._createEncoderBuffer([0, e]); + let o = 1; + for (let p = e;p >= 256; p >>= 8) + o++; + let f = new Array(o); + for (let p = f.length - 1;p >= 0; p--) + f[p] = e & 255, e >>= 8; + return f[0] & 128 && f.unshift(0), this._createEncoderBuffer(Ii.from(f)); + }; + Ur.prototype._encodeBool = function(e) { + return this._createEncoderBuffer(e ? 255 : 0); + }; + Ur.prototype._use = function(e, r) { + return typeof e == "function" && (e = e(r)), e._getEncoder("der").tree; + }; + Ur.prototype._skipDefault = function(e, r, o) { + let f = this._baseState, p; + if (f.default === null) + return false; + let m = e.join(); + if (f.defaultBuffer === undefined && (f.defaultBuffer = this._encodeValue(f.default, r, o).join()), m.length !== f.defaultBuffer.length) + return false; + for (p = 0;p < m.length; p++) + if (m[p] !== f.defaultBuffer[p]) + return false; + return true; + }; + function vB(t, e, r, o) { + let f; + if (t === "seqof" ? t = "seq" : t === "setof" && (t = "set"), id.tagByName.hasOwnProperty(t)) + f = id.tagByName[t]; + else if (typeof t == "number" && (t | 0) === t) + f = t; + else + return o.error("Unknown tag: " + t); + return f >= 31 ? o.error("Multi-octet tag encoding unsupported") : (e || (f |= 32), f |= id.tagClassByName[r || "universal"] << 6, f); + } + }); + Hy = T((rL, zy) => { + var bB = Ie(), fd = nd(); + function ad(t) { + fd.call(this, t), this.enc = "pem"; + } + bB(ad, fd); + zy.exports = ad; + ad.prototype.encode = function(e, r) { + let f = fd.prototype.encode.call(this, e).toString("base64"), p = ["-----BEGIN " + r.label + "-----"]; + for (let m = 0;m < f.length; m += 64) + p.push(f.slice(m, m + 64)); + return p.push("-----END " + r.label + "-----"), p.join(` +`); + }; + }); + od = T((Ky) => { + var Wy = Ky; + Wy.der = nd(); + Wy.pem = Hy(); + }); + hd = T((nL, Yy) => { + var mB = Ie(), gB = td(), jy = Kf().DecoderBuffer, Vy = d0(), Zy = c0(); + function $y(t) { + this.enc = "der", this.name = t.name, this.entity = t, this.tree = new sr, this.tree._init(t.body); + } + Yy.exports = $y; + $y.prototype.decode = function(e, r) { + return jy.isDecoderBuffer(e) || (e = new jy(e, r)), this.tree._decode(e, r); + }; + function sr(t) { + Vy.call(this, "der", t); + } + mB(sr, Vy); + sr.prototype._peekTag = function(e, r, o) { + if (e.isEmpty()) + return false; + let f = e.save(), p = sd(e, 'Failed to peek tag: "' + r + '"'); + return e.isError(p) ? p : (e.restore(f), p.tag === r || p.tagStr === r || p.tagStr + "of" === r || o); + }; + sr.prototype._decodeTag = function(e, r, o) { + let f = sd(e, 'Failed to decode tag of "' + r + '"'); + if (e.isError(f)) + return f; + let p = Gy(e, f.primitive, 'Failed to get length of "' + r + '"'); + if (e.isError(p)) + return p; + if (!o && f.tag !== r && f.tagStr !== r && f.tagStr + "of" !== r) + return e.error('Failed to match tag: "' + r + '"'); + if (f.primitive || p !== null) + return e.skip(p, 'Failed to match body of: "' + r + '"'); + let m = e.save(), y = this._skipUntilEnd(e, 'Failed to skip indefinite length body: "' + this.tag + '"'); + return e.isError(y) ? y : (p = e.offset - m.offset, e.restore(m), e.skip(p, 'Failed to match body of: "' + r + '"')); + }; + sr.prototype._skipUntilEnd = function(e, r) { + for (;; ) { + let o = sd(e, r); + if (e.isError(o)) + return o; + let f = Gy(e, o.primitive, r); + if (e.isError(f)) + return f; + let p; + if (o.primitive || f !== null ? p = e.skip(f) : p = this._skipUntilEnd(e, r), e.isError(p)) + return p; + if (o.tagStr === "end") + break; + } + }; + sr.prototype._decodeList = function(e, r, o, f) { + let p = []; + for (;!e.isEmpty(); ) { + let m = this._peekTag(e, "end"); + if (e.isError(m)) + return m; + let y = o.decode(e, "der", f); + if (e.isError(y) && m) + break; + p.push(y); + } + return p; + }; + sr.prototype._decodeStr = function(e, r) { + if (r === "bitstr") { + let o = e.readUInt8(); + return e.isError(o) ? o : { unused: o, data: e.raw() }; + } else if (r === "bmpstr") { + let o = e.raw(); + if (o.length % 2 === 1) + return e.error("Decoding of string type: bmpstr length mismatch"); + let f = ""; + for (let p = 0;p < o.length / 2; p++) + f += String.fromCharCode(o.readUInt16BE(p * 2)); + return f; + } else if (r === "numstr") { + let o = e.raw().toString("ascii"); + return this._isNumstr(o) ? o : e.error("Decoding of string type: numstr unsupported characters"); + } else { + if (r === "octstr") + return e.raw(); + if (r === "objDesc") + return e.raw(); + if (r === "printstr") { + let o = e.raw().toString("ascii"); + return this._isPrintstr(o) ? o : e.error("Decoding of string type: printstr unsupported characters"); + } else + return /str$/.test(r) ? e.raw().toString() : e.error("Decoding of string type: " + r + " unsupported"); + } + }; + sr.prototype._decodeObjid = function(e, r, o) { + let f, p = [], m = 0, y = 0; + for (;!e.isEmpty(); ) + y = e.readUInt8(), m <<= 7, m |= y & 127, (y & 128) === 0 && (p.push(m), m = 0); + y & 128 && p.push(m); + let M = p[0] / 40 | 0, x = p[0] % 40; + if (o ? f = p : f = [M, x].concat(p.slice(1)), r) { + let S = r[f.join(" ")]; + S === undefined && (S = r[f.join(".")]), S !== undefined && (f = S); + } + return f; + }; + sr.prototype._decodeTime = function(e, r) { + let o = e.raw().toString(), f, p, m, y, M, x; + if (r === "gentime") + f = o.slice(0, 4) | 0, p = o.slice(4, 6) | 0, m = o.slice(6, 8) | 0, y = o.slice(8, 10) | 0, M = o.slice(10, 12) | 0, x = o.slice(12, 14) | 0; + else if (r === "utctime") + f = o.slice(0, 2) | 0, p = o.slice(2, 4) | 0, m = o.slice(4, 6) | 0, y = o.slice(6, 8) | 0, M = o.slice(8, 10) | 0, x = o.slice(10, 12) | 0, f < 70 ? f = 2000 + f : f = 1900 + f; + else + return e.error("Decoding " + r + " time is not supported yet"); + return Date.UTC(f, p - 1, m, y, M, x, 0); + }; + sr.prototype._decodeNull = function() { + return null; + }; + sr.prototype._decodeBool = function(e) { + let r = e.readUInt8(); + return e.isError(r) ? r : r !== 0; + }; + sr.prototype._decodeInt = function(e, r) { + let o = e.raw(), f = new gB(o); + return r && (f = r[f.toString(10)] || f), f; + }; + sr.prototype._use = function(e, r) { + return typeof e == "function" && (e = e(r)), e._getDecoder("der").tree; + }; + function sd(t, e) { + let r = t.readUInt8(e); + if (t.isError(r)) + return r; + let o = Zy.tagClass[r >> 6], f = (r & 32) === 0; + if ((r & 31) === 31) { + let m = r; + for (r = 0;(m & 128) === 128; ) { + if (m = t.readUInt8(e), t.isError(m)) + return m; + r <<= 7, r |= m & 127; + } + } else + r &= 31; + let p = Zy.tag[r]; + return { cls: o, primitive: f, tag: r, tagStr: p }; + } + function Gy(t, e, r) { + let o = t.readUInt8(r); + if (t.isError(o)) + return o; + if (!e && o === 128) + return null; + if ((o & 128) === 0) + return o; + let f = o & 127; + if (f > 4) + return t.error("length octect is too long"); + o = 0; + for (let p = 0;p < f; p++) { + o <<= 8; + let m = t.readUInt8(r); + if (t.isError(m)) + return m; + o |= m; + } + return o; + } + }); + Jy = T((fL, Xy) => { + var yB = Ie(), wB = h0().Buffer, ud = hd(); + function ld(t) { + ud.call(this, t), this.enc = "pem"; + } + yB(ld, ud); + Xy.exports = ld; + ld.prototype.decode = function(e, r) { + let o = e.toString().split(/[\r\n]+/g), f = r.label.toUpperCase(), p = /^-----(BEGIN|END) ([^-]+)-----$/, m = -1, y = -1; + for (let S = 0;S < o.length; S++) { + let E2 = o[S].match(p); + if (E2 !== null && E2[2] === f) + if (m === -1) { + if (E2[1] !== "BEGIN") + break; + m = S; + } else { + if (E2[1] !== "END") + break; + y = S; + break; + } + } + if (m === -1 || y === -1) + throw new Error("PEM section not found for: " + f); + let M = o.slice(m + 1, y).join(""); + M.replace(/[^a-z0-9+/=]+/gi, ""); + let x = wB.from(M, "base64"); + return ud.prototype.decode.call(this, x, r); + }; + }); + dd = T((e3) => { + var Qy = e3; + Qy.der = hd(); + Qy.pem = Jy(); + }); + r3 = T((t3) => { + var MB = od(), _B = dd(), xB = Ie(), SB = t3; + SB.define = function(e, r) { + return new jf(e, r); + }; + function jf(t, e) { + this.name = t, this.body = e, this.decoders = {}, this.encoders = {}; + } + jf.prototype._createNamed = function(e) { + let r = this.name; + function o(f) { + this._initNamed(f, r); + } + return xB(o, e), o.prototype._initNamed = function(p, m) { + e.call(this, p, m); + }, new o(this); + }; + jf.prototype._getDecoder = function(e) { + return e = e || "der", this.decoders.hasOwnProperty(e) || (this.decoders[e] = this._createNamed(_B[e])), this.decoders[e]; + }; + jf.prototype.decode = function(e, r, o) { + return this._getDecoder(r).decode(e, o); + }; + jf.prototype._getEncoder = function(e) { + return e = e || "der", this.encoders.hasOwnProperty(e) || (this.encoders[e] = this._createNamed(MB[e])), this.encoders[e]; + }; + jf.prototype.encode = function(e, r, o) { + return this._getEncoder(r).encode(e, o); + }; + }); + n3 = T((i3) => { + var p0 = i3; + p0.Reporter = u0().Reporter; + p0.DecoderBuffer = Kf().DecoderBuffer; + p0.EncoderBuffer = Kf().EncoderBuffer; + p0.Node = d0(); + }); + o3 = T((a3) => { + var f3 = a3; + f3._reverse = function(e) { + let r = {}; + return Object.keys(e).forEach(function(o) { + (o | 0) == o && (o = o | 0); + let f = e[o]; + r[f] = o; + }), r; + }; + f3.der = c0(); + }); + cd = T((s3) => { + var Zf = s3; + Zf.bignum = td(); + Zf.define = r3().define; + Zf.base = n3(); + Zf.constants = o3(); + Zf.decoders = dd(); + Zf.encoders = od(); + }); + d3 = T((lL, l3) => { + var zr = cd(), h3 = zr.define("Time", function() { + this.choice({ utcTime: this.utctime(), generalTime: this.gentime() }); + }), EB = zr.define("AttributeTypeValue", function() { + this.seq().obj(this.key("type").objid(), this.key("value").any()); + }), pd = zr.define("AlgorithmIdentifier", function() { + this.seq().obj(this.key("algorithm").objid(), this.key("parameters").optional(), this.key("curve").objid().optional()); + }), AB = zr.define("SubjectPublicKeyInfo", function() { + this.seq().obj(this.key("algorithm").use(pd), this.key("subjectPublicKey").bitstr()); + }), RB = zr.define("RelativeDistinguishedName", function() { + this.setof(EB); + }), BB = zr.define("RDNSequence", function() { + this.seqof(RB); + }), u3 = zr.define("Name", function() { + this.choice({ rdnSequence: this.use(BB) }); + }), qB = zr.define("Validity", function() { + this.seq().obj(this.key("notBefore").use(h3), this.key("notAfter").use(h3)); + }), IB = zr.define("Extension", function() { + this.seq().obj(this.key("extnID").objid(), this.key("critical").bool().def(false), this.key("extnValue").octstr()); + }), TB = zr.define("TBSCertificate", function() { + this.seq().obj(this.key("version").explicit(0).int().optional(), this.key("serialNumber").int(), this.key("signature").use(pd), this.key("issuer").use(u3), this.key("validity").use(qB), this.key("subject").use(u3), this.key("subjectPublicKeyInfo").use(AB), this.key("issuerUniqueID").implicit(1).bitstr().optional(), this.key("subjectUniqueID").implicit(2).bitstr().optional(), this.key("extensions").explicit(3).seqof(IB).optional()); + }), kB = zr.define("X509Certificate", function() { + this.seq().obj(this.key("tbsCertificate").use(TB), this.key("signatureAlgorithm").use(pd), this.key("signatureValue").bitstr()); + }); + l3.exports = kB; + }); + p3 = T((Wr) => { + var Hr = cd(); + Wr.certificate = d3(); + var LB = Hr.define("RSAPrivateKey", function() { + this.seq().obj(this.key("version").int(), this.key("modulus").int(), this.key("publicExponent").int(), this.key("privateExponent").int(), this.key("prime1").int(), this.key("prime2").int(), this.key("exponent1").int(), this.key("exponent2").int(), this.key("coefficient").int()); + }); + Wr.RSAPrivateKey = LB; + var NB = Hr.define("RSAPublicKey", function() { + this.seq().obj(this.key("modulus").int(), this.key("publicExponent").int()); + }); + Wr.RSAPublicKey = NB; + var DB = Hr.define("SubjectPublicKeyInfo", function() { + this.seq().obj(this.key("algorithm").use(c3), this.key("subjectPublicKey").bitstr()); + }); + Wr.PublicKey = DB; + var c3 = Hr.define("AlgorithmIdentifier", function() { + this.seq().obj(this.key("algorithm").objid(), this.key("none").null_().optional(), this.key("curve").objid().optional(), this.key("params").seq().obj(this.key("p").int(), this.key("q").int(), this.key("g").int()).optional()); + }), PB = Hr.define("PrivateKeyInfo", function() { + this.seq().obj(this.key("version").int(), this.key("algorithm").use(c3), this.key("subjectPrivateKey").octstr()); + }); + Wr.PrivateKey = PB; + var CB = Hr.define("EncryptedPrivateKeyInfo", function() { + this.seq().obj(this.key("algorithm").seq().obj(this.key("id").objid(), this.key("decrypt").seq().obj(this.key("kde").seq().obj(this.key("id").objid(), this.key("kdeparams").seq().obj(this.key("salt").octstr(), this.key("iters").int())), this.key("cipher").seq().obj(this.key("algo").objid(), this.key("iv").octstr()))), this.key("subjectPrivateKey").octstr()); + }); + Wr.EncryptedPrivateKey = CB; + var OB = Hr.define("DSAPrivateKey", function() { + this.seq().obj(this.key("version").int(), this.key("p").int(), this.key("q").int(), this.key("g").int(), this.key("pub_key").int(), this.key("priv_key").int()); + }); + Wr.DSAPrivateKey = OB; + Wr.DSAparam = Hr.define("DSAparam", function() { + this.int(); + }); + var FB = Hr.define("ECPrivateKey", function() { + this.seq().obj(this.key("version").int(), this.key("privateKey").octstr(), this.key("parameters").optional().explicit(0).use(UB), this.key("publicKey").optional().explicit(1).bitstr()); + }); + Wr.ECPrivateKey = FB; + var UB = Hr.define("ECParameters", function() { + this.choice({ namedCurve: this.objid() }); + }); + Wr.signature = Hr.define("signature", function() { + this.seq().obj(this.key("r").int(), this.key("s").int()); + }); + }); + v3 = T((cL, zB) => { + zB.exports = { "2.16.840.1.101.3.4.1.1": "aes-128-ecb", "2.16.840.1.101.3.4.1.2": "aes-128-cbc", "2.16.840.1.101.3.4.1.3": "aes-128-ofb", "2.16.840.1.101.3.4.1.4": "aes-128-cfb", "2.16.840.1.101.3.4.1.21": "aes-192-ecb", "2.16.840.1.101.3.4.1.22": "aes-192-cbc", "2.16.840.1.101.3.4.1.23": "aes-192-ofb", "2.16.840.1.101.3.4.1.24": "aes-192-cfb", "2.16.840.1.101.3.4.1.41": "aes-256-ecb", "2.16.840.1.101.3.4.1.42": "aes-256-cbc", "2.16.840.1.101.3.4.1.43": "aes-256-ofb", "2.16.840.1.101.3.4.1.44": "aes-256-cfb" }; + }); + m3 = T((pL, b3) => { + var HB = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m, WB = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m, KB = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m, jB = Ba(), ZB = Es(), v0 = Te().Buffer; + b3.exports = function(t, e) { + var r = t.toString(), o = r.match(HB), f; + if (o) { + var m = "aes" + o[1], y = v0.from(o[2], "hex"), M = v0.from(o[3].replace(/[\r\n]/g, ""), "base64"), x = jB(e, y.slice(0, 8), parseInt(o[1], 10)).key, S = [], E2 = ZB.createDecipheriv(m, x, y); + S.push(E2.update(M)), S.push(E2.final()), f = v0.concat(S); + } else { + var p = r.match(KB); + f = v0.from(p[2].replace(/[\r\n]/g, ""), "base64"); + } + var B = r.match(WB)[1]; + return { tag: B, data: f }; + }; + }); + Ha = T((vL, y3) => { + var fr = p3(), VB = v3(), $B = m3(), GB = Es(), YB = Iu(), vd = Te().Buffer; + y3.exports = g3; + function g3(t) { + var e; + typeof t == "object" && !vd.isBuffer(t) && (e = t.passphrase, t = t.key), typeof t == "string" && (t = vd.from(t)); + var r = $B(t, e), o = r.tag, f = r.data, p, m; + switch (o) { + case "CERTIFICATE": + m = fr.certificate.decode(f, "der").tbsCertificate.subjectPublicKeyInfo; + case "PUBLIC KEY": + switch (m || (m = fr.PublicKey.decode(f, "der")), p = m.algorithm.algorithm.join("."), p) { + case "1.2.840.113549.1.1.1": + return fr.RSAPublicKey.decode(m.subjectPublicKey.data, "der"); + case "1.2.840.10045.2.1": + return m.subjectPrivateKey = m.subjectPublicKey, { type: "ec", data: m }; + case "1.2.840.10040.4.1": + return m.algorithm.params.pub_key = fr.DSAparam.decode(m.subjectPublicKey.data, "der"), { type: "dsa", data: m.algorithm.params }; + default: + throw new Error("unknown key id " + p); + } + case "ENCRYPTED PRIVATE KEY": + f = fr.EncryptedPrivateKey.decode(f, "der"), f = XB(f, e); + case "PRIVATE KEY": + switch (m = fr.PrivateKey.decode(f, "der"), p = m.algorithm.algorithm.join("."), p) { + case "1.2.840.113549.1.1.1": + return fr.RSAPrivateKey.decode(m.subjectPrivateKey, "der"); + case "1.2.840.10045.2.1": + return { curve: m.algorithm.curve, privateKey: fr.ECPrivateKey.decode(m.subjectPrivateKey, "der").privateKey }; + case "1.2.840.10040.4.1": + return m.algorithm.params.priv_key = fr.DSAparam.decode(m.subjectPrivateKey, "der"), { type: "dsa", params: m.algorithm.params }; + default: + throw new Error("unknown key id " + p); + } + case "RSA PUBLIC KEY": + return fr.RSAPublicKey.decode(f, "der"); + case "RSA PRIVATE KEY": + return fr.RSAPrivateKey.decode(f, "der"); + case "DSA PRIVATE KEY": + return { type: "dsa", params: fr.DSAPrivateKey.decode(f, "der") }; + case "EC PRIVATE KEY": + return f = fr.ECPrivateKey.decode(f, "der"), { curve: f.parameters.value, privateKey: f.privateKey }; + default: + throw new Error("unknown key type " + o); + } + } + g3.signature = fr.signature; + function XB(t, e) { + var r = t.algorithm.decrypt.kde.kdeparams.salt, o = parseInt(t.algorithm.decrypt.kde.kdeparams.iters.toString(), 10), f = VB[t.algorithm.decrypt.cipher.algo.join(".")], p = t.algorithm.decrypt.cipher.iv, m = t.subjectPrivateKey, y = parseInt(f.split("-")[1], 10) / 8, M = YB.pbkdf2Sync(e, r, o, y, "sha1"), x = GB.createDecipheriv(f, M, p), S = []; + return S.push(x.update(m)), S.push(x.final()), vd.concat(S); + } + }); + bd = T((bL, JB) => { + JB.exports = { "1.3.132.0.10": "secp256k1", "1.3.132.0.33": "p224", "1.2.840.10045.3.1.1": "p192", "1.2.840.10045.3.1.7": "p256", "1.3.132.0.34": "p384", "1.3.132.0.35": "p521" }; + }); + _32 = T((mL, m0) => { + var Yt = Te().Buffer, Kn = wu(), QB = Ks(), eq = o0().ec, b0 = Ws(), tq = Ha(), rq = bd(); + function iq(t, e, r, o, f) { + var p = tq(e); + if (p.curve) { + if (o !== "ecdsa" && o !== "ecdsa/rsa") + throw new Error("wrong private key type"); + return nq(t, p); + } else if (p.type === "dsa") { + if (o !== "dsa") + throw new Error("wrong private key type"); + return fq(t, p, r); + } else if (o !== "rsa" && o !== "ecdsa/rsa") + throw new Error("wrong private key type"); + t = Yt.concat([f, t]); + for (var m = p.modulus.byteLength(), y = [0, 1];t.length + y.length + 1 < m; ) + y.push(255); + y.push(0); + for (var M = -1;++M < t.length; ) + y.push(t[M]); + var x = QB(y, p); + return x; + } + function nq(t, e) { + var r = rq[e.curve.join(".")]; + if (!r) + throw new Error("unknown curve " + e.curve.join(".")); + var o = new eq(r), f = o.keyFromPrivate(e.privateKey), p = f.sign(t); + return Yt.from(p.toDER()); + } + function fq(t, e, r) { + for (var o = e.params.priv_key, f = e.params.p, p = e.params.q, m = e.params.g, y = new b0(0), M, x = md(t, p).mod(p), S = false, E2 = w3(o, p, t, r);S === false; ) + M = M3(p, E2, r), y = sq(m, M, f, p), S = M.invm(p).imul(x.add(o.mul(y))).mod(p), S.cmpn(0) === 0 && (S = false, y = new b0(0)); + return aq(y, S); + } + function aq(t, e) { + t = t.toArray(), e = e.toArray(), t[0] & 128 && (t = [0].concat(t)), e[0] & 128 && (e = [0].concat(e)); + var r = t.length + e.length + 4, o = [48, r, 2, t.length]; + return o = o.concat(t, [2, e.length], e), Yt.from(o); + } + function w3(t, e, r, o) { + if (t = Yt.from(t.toArray()), t.length < e.byteLength()) { + var f = Yt.alloc(e.byteLength() - t.length); + t = Yt.concat([f, t]); + } + var p = r.length, m = oq(r, e), y = Yt.alloc(p); + y.fill(1); + var M = Yt.alloc(p); + return M = Kn(o, M).update(y).update(Yt.from([0])).update(t).update(m).digest(), y = Kn(o, M).update(y).digest(), M = Kn(o, M).update(y).update(Yt.from([1])).update(t).update(m).digest(), y = Kn(o, M).update(y).digest(), { k: M, v: y }; + } + function md(t, e) { + var r = new b0(t), o = (t.length << 3) - e.bitLength(); + return o > 0 && r.ishrn(o), r; + } + function oq(t, e) { + t = md(t, e), t = t.mod(e); + var r = Yt.from(t.toArray()); + if (r.length < e.byteLength()) { + var o = Yt.alloc(e.byteLength() - r.length); + r = Yt.concat([o, r]); + } + return r; + } + function M3(t, e, r) { + var o, f; + do { + for (o = Yt.alloc(0);o.length * 8 < t.bitLength(); ) + e.v = Kn(r, e.k).update(e.v).digest(), o = Yt.concat([o, e.v]); + f = md(o, t), e.k = Kn(r, e.k).update(e.v).update(Yt.from([0])).digest(), e.v = Kn(r, e.k).update(e.v).digest(); + } while (f.cmp(t) !== -1); + return f; + } + function sq(t, e, r, o) { + return t.toRed(b0.mont(r)).redPow(e).fromRed().mod(o); + } + m0.exports = iq; + m0.exports.getKey = w3; + m0.exports.makeKey = M3; + }); + A3 = T((gL, E3) => { + var gd = Te().Buffer, Wa = Ws(), hq = o0().ec, S3 = Ha(), uq = bd(); + function lq(t, e, r, o, f) { + var p = S3(r); + if (p.type === "ec") { + if (o !== "ecdsa" && o !== "ecdsa/rsa") + throw new Error("wrong public key type"); + return dq(t, e, p); + } else if (p.type === "dsa") { + if (o !== "dsa") + throw new Error("wrong public key type"); + return cq(t, e, p); + } else if (o !== "rsa" && o !== "ecdsa/rsa") + throw new Error("wrong public key type"); + e = gd.concat([f, e]); + for (var m = p.modulus.byteLength(), y = [1], M = 0;e.length + y.length + 2 < m; ) + y.push(255), M++; + y.push(0); + for (var x = -1;++x < e.length; ) + y.push(e[x]); + y = gd.from(y); + var S = Wa.mont(p.modulus); + t = new Wa(t).toRed(S), t = t.redPow(new Wa(p.publicExponent)), t = gd.from(t.fromRed().toArray()); + var E2 = M < 8 ? 1 : 0; + for (m = Math.min(t.length, y.length), t.length !== y.length && (E2 = 1), x = -1;++x < m; ) + E2 |= t[x] ^ y[x]; + return E2 === 0; + } + function dq(t, e, r) { + var o = uq[r.data.algorithm.curve.join(".")]; + if (!o) + throw new Error("unknown curve " + r.data.algorithm.curve.join(".")); + var f = new hq(o), p = r.data.subjectPrivateKey.data; + return f.verify(e, t, p); + } + function cq(t, e, r) { + var o = r.data.p, f = r.data.q, p = r.data.g, m = r.data.pub_key, y = S3.signature.decode(t, "der"), M = y.s, x = y.r; + x3(M, f), x3(x, f); + var S = Wa.mont(o), E2 = M.invm(f), B = p.toRed(S).redPow(new Wa(e).mul(E2).mod(f)).fromRed().mul(m.toRed(S).redPow(x.mul(E2).mod(f)).fromRed()).mod(o).mod(f); + return B.cmp(x) === 0; + } + function x3(t, e) { + if (t.cmpn(0) <= 0) + throw new Error("invalid sig"); + if (t.cmp(e) >= e) + throw new Error("invalid sig"); + } + E3.exports = lq; + }); + k3 = T((yL, T3) => { + var g0 = Te().Buffer, q3 = bf(), y0 = i2(), I3 = Ie(), pq = _32(), vq = A3(), jn = Mu(); + Object.keys(jn).forEach(function(t) { + jn[t].id = g0.from(jn[t].id, "hex"), jn[t.toLowerCase()] = jn[t]; + }); + function Ka(t) { + y0.Writable.call(this); + var e = jn[t]; + if (!e) + throw new Error("Unknown message digest"); + this._hashType = e.hash, this._hash = q3(e.hash), this._tag = e.id, this._signType = e.sign; + } + I3(Ka, y0.Writable); + Ka.prototype._write = function(e, r, o) { + this._hash.update(e), o(); + }; + Ka.prototype.update = function(e, r) { + return typeof e == "string" && (e = g0.from(e, r)), this._hash.update(e), this; + }; + Ka.prototype.sign = function(e, r) { + this.end(); + var o = this._hash.digest(), f = pq(o, e, this._hashType, this._signType, this._tag); + return r ? f.toString(r) : f; + }; + function ja(t) { + y0.Writable.call(this); + var e = jn[t]; + if (!e) + throw new Error("Unknown message digest"); + this._hash = q3(e.hash), this._tag = e.id, this._signType = e.sign; + } + I3(ja, y0.Writable); + ja.prototype._write = function(e, r, o) { + this._hash.update(e), o(); + }; + ja.prototype.update = function(e, r) { + return typeof e == "string" && (e = g0.from(e, r)), this._hash.update(e), this; + }; + ja.prototype.verify = function(e, r, o) { + typeof r == "string" && (r = g0.from(r, o)), this.end(); + var f = this._hash.digest(); + return vq(r, f, e, this._signType, this._tag); + }; + function R3(t) { + return new Ka(t); + } + function B3(t) { + return new ja(t); + } + T3.exports = { Sign: R3, Verify: B3, createSign: R3, createVerify: B3 }; + }); + N3 = T((L3, yd) => { + (function(t, e) { + function r(v, i) { + if (!v) + throw new Error(i || "Assertion failed"); + } + function o(v, i) { + v.super_ = i; + var a = function() { + }; + a.prototype = i.prototype, v.prototype = new a, v.prototype.constructor = v; + } + function f(v, i, a) { + if (f.isBN(v)) + return v; + this.negative = 0, this.words = null, this.length = 0, this.red = null, v !== null && ((i === "le" || i === "be") && (a = i, i = 10), this._init(v || 0, i || 10, a || "be")); + } + typeof t == "object" ? t.exports = f : e.BN = f, f.BN = f, f.wordSize = 26; + var p; + try { + typeof window < "u" && typeof window.Buffer < "u" ? p = window.Buffer : p = ji().Buffer; + } catch { + } + f.isBN = function(i) { + return i instanceof f ? true : i !== null && typeof i == "object" && i.constructor.wordSize === f.wordSize && Array.isArray(i.words); + }, f.max = function(i, a) { + return i.cmp(a) > 0 ? i : a; + }, f.min = function(i, a) { + return i.cmp(a) < 0 ? i : a; + }, f.prototype._init = function(i, a, h) { + if (typeof i == "number") + return this._initNumber(i, a, h); + if (typeof i == "object") + return this._initArray(i, a, h); + a === "hex" && (a = 16), r(a === (a | 0) && a >= 2 && a <= 36), i = i.toString().replace(/\s+/g, ""); + var s = 0; + i[0] === "-" && (s++, this.negative = 1), s < i.length && (a === 16 ? this._parseHex(i, s, h) : (this._parseBase(i, a, s), h === "le" && this._initArray(this.toArray(), a, h))); + }, f.prototype._initNumber = function(i, a, h) { + i < 0 && (this.negative = 1, i = -i), i < 67108864 ? (this.words = [i & 67108863], this.length = 1) : i < 4503599627370496 ? (this.words = [i & 67108863, i / 67108864 & 67108863], this.length = 2) : (r(i < 9007199254740992), this.words = [i & 67108863, i / 67108864 & 67108863, 1], this.length = 3), h === "le" && this._initArray(this.toArray(), a, h); + }, f.prototype._initArray = function(i, a, h) { + if (r(typeof i.length == "number"), i.length <= 0) + return this.words = [0], this.length = 1, this; + this.length = Math.ceil(i.length / 3), this.words = new Array(this.length); + for (var s = 0;s < this.length; s++) + this.words[s] = 0; + var u, c, b = 0; + if (h === "be") + for (s = i.length - 1, u = 0;s >= 0; s -= 3) + c = i[s] | i[s - 1] << 8 | i[s - 2] << 16, this.words[u] |= c << b & 67108863, this.words[u + 1] = c >>> 26 - b & 67108863, b += 24, b >= 26 && (b -= 26, u++); + else if (h === "le") + for (s = 0, u = 0;s < i.length; s += 3) + c = i[s] | i[s + 1] << 8 | i[s + 2] << 16, this.words[u] |= c << b & 67108863, this.words[u + 1] = c >>> 26 - b & 67108863, b += 24, b >= 26 && (b -= 26, u++); + return this.strip(); + }; + function m(v, i) { + var a = v.charCodeAt(i); + return a >= 65 && a <= 70 ? a - 55 : a >= 97 && a <= 102 ? a - 87 : a - 48 & 15; + } + function y(v, i, a) { + var h = m(v, a); + return a - 1 >= i && (h |= m(v, a - 1) << 4), h; + } + f.prototype._parseHex = function(i, a, h) { + this.length = Math.ceil((i.length - a) / 6), this.words = new Array(this.length); + for (var s = 0;s < this.length; s++) + this.words[s] = 0; + var u = 0, c = 0, b; + if (h === "be") + for (s = i.length - 1;s >= a; s -= 2) + b = y(i, a, s) << u, this.words[c] |= b & 67108863, u >= 18 ? (u -= 18, c += 1, this.words[c] |= b >>> 26) : u += 8; + else { + var l = i.length - a; + for (s = l % 2 === 0 ? a + 1 : a;s < i.length; s += 2) + b = y(i, a, s) << u, this.words[c] |= b & 67108863, u >= 18 ? (u -= 18, c += 1, this.words[c] |= b >>> 26) : u += 8; + } + this.strip(); + }; + function M(v, i, a, h) { + for (var s = 0, u = Math.min(v.length, a), c = i;c < u; c++) { + var b = v.charCodeAt(c) - 48; + s *= h, b >= 49 ? s += b - 49 + 10 : b >= 17 ? s += b - 17 + 10 : s += b; + } + return s; + } + f.prototype._parseBase = function(i, a, h) { + this.words = [0], this.length = 1; + for (var s = 0, u = 1;u <= 67108863; u *= a) + s++; + s--, u = u / a | 0; + for (var c = i.length - h, b = c % s, l = Math.min(c, c - b) + h, n = 0, d = h;d < l; d += s) + n = M(i, d, d + s, a), this.imuln(u), this.words[0] + n < 67108864 ? this.words[0] += n : this._iaddn(n); + if (b !== 0) { + var w = 1; + for (n = M(i, d, i.length, a), d = 0;d < b; d++) + w *= a; + this.imuln(w), this.words[0] + n < 67108864 ? this.words[0] += n : this._iaddn(n); + } + this.strip(); + }, f.prototype.copy = function(i) { + i.words = new Array(this.length); + for (var a = 0;a < this.length; a++) + i.words[a] = this.words[a]; + i.length = this.length, i.negative = this.negative, i.red = this.red; + }, f.prototype.clone = function() { + var i = new f(null); + return this.copy(i), i; + }, f.prototype._expand = function(i) { + for (;this.length < i; ) + this.words[this.length++] = 0; + return this; + }, f.prototype.strip = function() { + for (;this.length > 1 && this.words[this.length - 1] === 0; ) + this.length--; + return this._normSign(); + }, f.prototype._normSign = function() { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }, f.prototype.inspect = function() { + return (this.red ? ""; + }; + var x = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], S = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], E2 = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; + f.prototype.toString = function(i, a) { + i = i || 10, a = a | 0 || 1; + var h; + if (i === 16 || i === "hex") { + h = ""; + for (var s = 0, u = 0, c = 0;c < this.length; c++) { + var b = this.words[c], l = ((b << s | u) & 16777215).toString(16); + u = b >>> 24 - s & 16777215, u !== 0 || c !== this.length - 1 ? h = x[6 - l.length] + l + h : h = l + h, s += 2, s >= 26 && (s -= 26, c--); + } + for (u !== 0 && (h = u.toString(16) + h);h.length % a !== 0; ) + h = "0" + h; + return this.negative !== 0 && (h = "-" + h), h; + } + if (i === (i | 0) && i >= 2 && i <= 36) { + var n = S[i], d = E2[i]; + h = ""; + var w = this.clone(); + for (w.negative = 0;!w.isZero(); ) { + var g = w.modn(d).toString(i); + w = w.idivn(d), w.isZero() ? h = g + h : h = x[n - g.length] + g + h; + } + for (this.isZero() && (h = "0" + h);h.length % a !== 0; ) + h = "0" + h; + return this.negative !== 0 && (h = "-" + h), h; + } + r(false, "Base should be between 2 and 36"); + }, f.prototype.toNumber = function() { + var i = this.words[0]; + return this.length === 2 ? i += this.words[1] * 67108864 : this.length === 3 && this.words[2] === 1 ? i += 4503599627370496 + this.words[1] * 67108864 : this.length > 2 && r(false, "Number can only safely store up to 53 bits"), this.negative !== 0 ? -i : i; + }, f.prototype.toJSON = function() { + return this.toString(16); + }, f.prototype.toBuffer = function(i, a) { + return r(typeof p < "u"), this.toArrayLike(p, i, a); + }, f.prototype.toArray = function(i, a) { + return this.toArrayLike(Array, i, a); + }, f.prototype.toArrayLike = function(i, a, h) { + var s = this.byteLength(), u = h || Math.max(1, s); + r(s <= u, "byte array longer than desired length"), r(u > 0, "Requested array length <= 0"), this.strip(); + var c = a === "le", b = new i(u), l, n, d = this.clone(); + if (c) { + for (n = 0;!d.isZero(); n++) + l = d.andln(255), d.iushrn(8), b[n] = l; + for (;n < u; n++) + b[n] = 0; + } else { + for (n = 0;n < u - s; n++) + b[n] = 0; + for (n = 0;!d.isZero(); n++) + l = d.andln(255), d.iushrn(8), b[u - n - 1] = l; + } + return b; + }, Math.clz32 ? f.prototype._countBits = function(i) { + return 32 - Math.clz32(i); + } : f.prototype._countBits = function(i) { + var a = i, h = 0; + return a >= 4096 && (h += 13, a >>>= 13), a >= 64 && (h += 7, a >>>= 7), a >= 8 && (h += 4, a >>>= 4), a >= 2 && (h += 2, a >>>= 2), h + a; + }, f.prototype._zeroBits = function(i) { + if (i === 0) + return 26; + var a = i, h = 0; + return (a & 8191) === 0 && (h += 13, a >>>= 13), (a & 127) === 0 && (h += 7, a >>>= 7), (a & 15) === 0 && (h += 4, a >>>= 4), (a & 3) === 0 && (h += 2, a >>>= 2), (a & 1) === 0 && h++, h; + }, f.prototype.bitLength = function() { + var i = this.words[this.length - 1], a = this._countBits(i); + return (this.length - 1) * 26 + a; + }; + function B(v) { + for (var i = new Array(v.bitLength()), a = 0;a < i.length; a++) { + var h = a / 26 | 0, s = a % 26; + i[a] = (v.words[h] & 1 << s) >>> s; + } + return i; + } + f.prototype.zeroBits = function() { + if (this.isZero()) + return 0; + for (var i = 0, a = 0;a < this.length; a++) { + var h = this._zeroBits(this.words[a]); + if (i += h, h !== 26) + break; + } + return i; + }, f.prototype.byteLength = function() { + return Math.ceil(this.bitLength() / 8); + }, f.prototype.toTwos = function(i) { + return this.negative !== 0 ? this.abs().inotn(i).iaddn(1) : this.clone(); + }, f.prototype.fromTwos = function(i) { + return this.testn(i - 1) ? this.notn(i).iaddn(1).ineg() : this.clone(); + }, f.prototype.isNeg = function() { + return this.negative !== 0; + }, f.prototype.neg = function() { + return this.clone().ineg(); + }, f.prototype.ineg = function() { + return this.isZero() || (this.negative ^= 1), this; + }, f.prototype.iuor = function(i) { + for (;this.length < i.length; ) + this.words[this.length++] = 0; + for (var a = 0;a < i.length; a++) + this.words[a] = this.words[a] | i.words[a]; + return this.strip(); + }, f.prototype.ior = function(i) { + return r((this.negative | i.negative) === 0), this.iuor(i); + }, f.prototype.or = function(i) { + return this.length > i.length ? this.clone().ior(i) : i.clone().ior(this); + }, f.prototype.uor = function(i) { + return this.length > i.length ? this.clone().iuor(i) : i.clone().iuor(this); + }, f.prototype.iuand = function(i) { + var a; + this.length > i.length ? a = i : a = this; + for (var h = 0;h < a.length; h++) + this.words[h] = this.words[h] & i.words[h]; + return this.length = a.length, this.strip(); + }, f.prototype.iand = function(i) { + return r((this.negative | i.negative) === 0), this.iuand(i); + }, f.prototype.and = function(i) { + return this.length > i.length ? this.clone().iand(i) : i.clone().iand(this); + }, f.prototype.uand = function(i) { + return this.length > i.length ? this.clone().iuand(i) : i.clone().iuand(this); + }, f.prototype.iuxor = function(i) { + var a, h; + this.length > i.length ? (a = this, h = i) : (a = i, h = this); + for (var s = 0;s < h.length; s++) + this.words[s] = a.words[s] ^ h.words[s]; + if (this !== a) + for (;s < a.length; s++) + this.words[s] = a.words[s]; + return this.length = a.length, this.strip(); + }, f.prototype.ixor = function(i) { + return r((this.negative | i.negative) === 0), this.iuxor(i); + }, f.prototype.xor = function(i) { + return this.length > i.length ? this.clone().ixor(i) : i.clone().ixor(this); + }, f.prototype.uxor = function(i) { + return this.length > i.length ? this.clone().iuxor(i) : i.clone().iuxor(this); + }, f.prototype.inotn = function(i) { + r(typeof i == "number" && i >= 0); + var a = Math.ceil(i / 26) | 0, h = i % 26; + this._expand(a), h > 0 && a--; + for (var s = 0;s < a; s++) + this.words[s] = ~this.words[s] & 67108863; + return h > 0 && (this.words[s] = ~this.words[s] & 67108863 >> 26 - h), this.strip(); + }, f.prototype.notn = function(i) { + return this.clone().inotn(i); + }, f.prototype.setn = function(i, a) { + r(typeof i == "number" && i >= 0); + var h = i / 26 | 0, s = i % 26; + return this._expand(h + 1), a ? this.words[h] = this.words[h] | 1 << s : this.words[h] = this.words[h] & ~(1 << s), this.strip(); + }, f.prototype.iadd = function(i) { + var a; + if (this.negative !== 0 && i.negative === 0) + return this.negative = 0, a = this.isub(i), this.negative ^= 1, this._normSign(); + if (this.negative === 0 && i.negative !== 0) + return i.negative = 0, a = this.isub(i), i.negative = 1, a._normSign(); + var h, s; + this.length > i.length ? (h = this, s = i) : (h = i, s = this); + for (var u = 0, c = 0;c < s.length; c++) + a = (h.words[c] | 0) + (s.words[c] | 0) + u, this.words[c] = a & 67108863, u = a >>> 26; + for (;u !== 0 && c < h.length; c++) + a = (h.words[c] | 0) + u, this.words[c] = a & 67108863, u = a >>> 26; + if (this.length = h.length, u !== 0) + this.words[this.length] = u, this.length++; + else if (h !== this) + for (;c < h.length; c++) + this.words[c] = h.words[c]; + return this; + }, f.prototype.add = function(i) { + var a; + return i.negative !== 0 && this.negative === 0 ? (i.negative = 0, a = this.sub(i), i.negative ^= 1, a) : i.negative === 0 && this.negative !== 0 ? (this.negative = 0, a = i.sub(this), this.negative = 1, a) : this.length > i.length ? this.clone().iadd(i) : i.clone().iadd(this); + }, f.prototype.isub = function(i) { + if (i.negative !== 0) { + i.negative = 0; + var a = this.iadd(i); + return i.negative = 1, a._normSign(); + } else if (this.negative !== 0) + return this.negative = 0, this.iadd(i), this.negative = 1, this._normSign(); + var h = this.cmp(i); + if (h === 0) + return this.negative = 0, this.length = 1, this.words[0] = 0, this; + var s, u; + h > 0 ? (s = this, u = i) : (s = i, u = this); + for (var c = 0, b = 0;b < u.length; b++) + a = (s.words[b] | 0) - (u.words[b] | 0) + c, c = a >> 26, this.words[b] = a & 67108863; + for (;c !== 0 && b < s.length; b++) + a = (s.words[b] | 0) + c, c = a >> 26, this.words[b] = a & 67108863; + if (c === 0 && b < s.length && s !== this) + for (;b < s.length; b++) + this.words[b] = s.words[b]; + return this.length = Math.max(this.length, b), s !== this && (this.negative = 1), this.strip(); + }, f.prototype.sub = function(i) { + return this.clone().isub(i); + }; + function q(v, i, a) { + a.negative = i.negative ^ v.negative; + var h = v.length + i.length | 0; + a.length = h, h = h - 1 | 0; + var s = v.words[0] | 0, u = i.words[0] | 0, c = s * u, b = c & 67108863, l = c / 67108864 | 0; + a.words[0] = b; + for (var n = 1;n < h; n++) { + for (var d = l >>> 26, w = l & 67108863, g = Math.min(n, i.length - 1), _9 = Math.max(0, n - v.length + 1);_9 <= g; _9++) { + var A = n - _9 | 0; + s = v.words[A] | 0, u = i.words[_9] | 0, c = s * u + w, d += c / 67108864 | 0, w = c & 67108863; + } + a.words[n] = w | 0, l = d | 0; + } + return l !== 0 ? a.words[n] = l | 0 : a.length--, a.strip(); + } + var L = function(i, a, h) { + var s = i.words, u = a.words, c = h.words, b = 0, l, n, d, w = s[0] | 0, g = w & 8191, _9 = w >>> 13, A = s[1] | 0, R = A & 8191, I2 = A >>> 13, Me = s[2] | 0, k2 = Me & 8191, D = Me >>> 13, nt = s[3] | 0, C2 = nt & 8191, O = nt >>> 13, vt = s[4] | 0, F = vt & 8191, U = vt >>> 13, bt = s[5] | 0, z = bt & 8191, H = bt >>> 13, mt = s[6] | 0, W = mt & 8191, K = mt >>> 13, gt = s[7] | 0, j = gt & 8191, Z = gt >>> 13, yt = s[8] | 0, V3 = yt & 8191, $ = yt >>> 13, wt = s[9] | 0, G = wt & 8191, Y = wt >>> 13, Mt = u[0] | 0, X = Mt & 8191, J2 = Mt >>> 13, _t = u[1] | 0, Q = _t & 8191, ee = _t >>> 13, xt2 = u[2] | 0, te2 = xt2 & 8191, re = xt2 >>> 13, St = u[3] | 0, ie = St & 8191, ne = St >>> 13, Et2 = u[4] | 0, fe = Et2 & 8191, ae2 = Et2 >>> 13, At2 = u[5] | 0, oe = At2 & 8191, se2 = At2 >>> 13, Rt = u[6] | 0, he = Rt & 8191, ue2 = Rt >>> 13, Bt = u[7] | 0, le = Bt & 8191, de = Bt >>> 13, qt = u[8] | 0, ce2 = qt & 8191, pe2 = qt >>> 13, It = u[9] | 0, ve = It & 8191, be = It >>> 13; + h.negative = i.negative ^ a.negative, h.length = 19, l = Math.imul(g, X), n = Math.imul(g, J2), n = n + Math.imul(_9, X) | 0, d = Math.imul(_9, J2); + var ft = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (ft >>> 26) | 0, ft &= 67108863, l = Math.imul(R, X), n = Math.imul(R, J2), n = n + Math.imul(I2, X) | 0, d = Math.imul(I2, J2), l = l + Math.imul(g, Q) | 0, n = n + Math.imul(g, ee) | 0, n = n + Math.imul(_9, Q) | 0, d = d + Math.imul(_9, ee) | 0; + var Be = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Be >>> 26) | 0, Be &= 67108863, l = Math.imul(k2, X), n = Math.imul(k2, J2), n = n + Math.imul(D, X) | 0, d = Math.imul(D, J2), l = l + Math.imul(R, Q) | 0, n = n + Math.imul(R, ee) | 0, n = n + Math.imul(I2, Q) | 0, d = d + Math.imul(I2, ee) | 0, l = l + Math.imul(g, te2) | 0, n = n + Math.imul(g, re) | 0, n = n + Math.imul(_9, te2) | 0, d = d + Math.imul(_9, re) | 0; + var qe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (qe >>> 26) | 0, qe &= 67108863, l = Math.imul(C2, X), n = Math.imul(C2, J2), n = n + Math.imul(O, X) | 0, d = Math.imul(O, J2), l = l + Math.imul(k2, Q) | 0, n = n + Math.imul(k2, ee) | 0, n = n + Math.imul(D, Q) | 0, d = d + Math.imul(D, ee) | 0, l = l + Math.imul(R, te2) | 0, n = n + Math.imul(R, re) | 0, n = n + Math.imul(I2, te2) | 0, d = d + Math.imul(I2, re) | 0, l = l + Math.imul(g, ie) | 0, n = n + Math.imul(g, ne) | 0, n = n + Math.imul(_9, ie) | 0, d = d + Math.imul(_9, ne) | 0; + var ze = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (ze >>> 26) | 0, ze &= 67108863, l = Math.imul(F, X), n = Math.imul(F, J2), n = n + Math.imul(U, X) | 0, d = Math.imul(U, J2), l = l + Math.imul(C2, Q) | 0, n = n + Math.imul(C2, ee) | 0, n = n + Math.imul(O, Q) | 0, d = d + Math.imul(O, ee) | 0, l = l + Math.imul(k2, te2) | 0, n = n + Math.imul(k2, re) | 0, n = n + Math.imul(D, te2) | 0, d = d + Math.imul(D, re) | 0, l = l + Math.imul(R, ie) | 0, n = n + Math.imul(R, ne) | 0, n = n + Math.imul(I2, ie) | 0, d = d + Math.imul(I2, ne) | 0, l = l + Math.imul(g, fe) | 0, n = n + Math.imul(g, ae2) | 0, n = n + Math.imul(_9, fe) | 0, d = d + Math.imul(_9, ae2) | 0; + var He2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (He2 >>> 26) | 0, He2 &= 67108863, l = Math.imul(z, X), n = Math.imul(z, J2), n = n + Math.imul(H, X) | 0, d = Math.imul(H, J2), l = l + Math.imul(F, Q) | 0, n = n + Math.imul(F, ee) | 0, n = n + Math.imul(U, Q) | 0, d = d + Math.imul(U, ee) | 0, l = l + Math.imul(C2, te2) | 0, n = n + Math.imul(C2, re) | 0, n = n + Math.imul(O, te2) | 0, d = d + Math.imul(O, re) | 0, l = l + Math.imul(k2, ie) | 0, n = n + Math.imul(k2, ne) | 0, n = n + Math.imul(D, ie) | 0, d = d + Math.imul(D, ne) | 0, l = l + Math.imul(R, fe) | 0, n = n + Math.imul(R, ae2) | 0, n = n + Math.imul(I2, fe) | 0, d = d + Math.imul(I2, ae2) | 0, l = l + Math.imul(g, oe) | 0, n = n + Math.imul(g, se2) | 0, n = n + Math.imul(_9, oe) | 0, d = d + Math.imul(_9, se2) | 0; + var We = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (We >>> 26) | 0, We &= 67108863, l = Math.imul(W, X), n = Math.imul(W, J2), n = n + Math.imul(K, X) | 0, d = Math.imul(K, J2), l = l + Math.imul(z, Q) | 0, n = n + Math.imul(z, ee) | 0, n = n + Math.imul(H, Q) | 0, d = d + Math.imul(H, ee) | 0, l = l + Math.imul(F, te2) | 0, n = n + Math.imul(F, re) | 0, n = n + Math.imul(U, te2) | 0, d = d + Math.imul(U, re) | 0, l = l + Math.imul(C2, ie) | 0, n = n + Math.imul(C2, ne) | 0, n = n + Math.imul(O, ie) | 0, d = d + Math.imul(O, ne) | 0, l = l + Math.imul(k2, fe) | 0, n = n + Math.imul(k2, ae2) | 0, n = n + Math.imul(D, fe) | 0, d = d + Math.imul(D, ae2) | 0, l = l + Math.imul(R, oe) | 0, n = n + Math.imul(R, se2) | 0, n = n + Math.imul(I2, oe) | 0, d = d + Math.imul(I2, se2) | 0, l = l + Math.imul(g, he) | 0, n = n + Math.imul(g, ue2) | 0, n = n + Math.imul(_9, he) | 0, d = d + Math.imul(_9, ue2) | 0; + var Ke2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ke2 >>> 26) | 0, Ke2 &= 67108863, l = Math.imul(j, X), n = Math.imul(j, J2), n = n + Math.imul(Z, X) | 0, d = Math.imul(Z, J2), l = l + Math.imul(W, Q) | 0, n = n + Math.imul(W, ee) | 0, n = n + Math.imul(K, Q) | 0, d = d + Math.imul(K, ee) | 0, l = l + Math.imul(z, te2) | 0, n = n + Math.imul(z, re) | 0, n = n + Math.imul(H, te2) | 0, d = d + Math.imul(H, re) | 0, l = l + Math.imul(F, ie) | 0, n = n + Math.imul(F, ne) | 0, n = n + Math.imul(U, ie) | 0, d = d + Math.imul(U, ne) | 0, l = l + Math.imul(C2, fe) | 0, n = n + Math.imul(C2, ae2) | 0, n = n + Math.imul(O, fe) | 0, d = d + Math.imul(O, ae2) | 0, l = l + Math.imul(k2, oe) | 0, n = n + Math.imul(k2, se2) | 0, n = n + Math.imul(D, oe) | 0, d = d + Math.imul(D, se2) | 0, l = l + Math.imul(R, he) | 0, n = n + Math.imul(R, ue2) | 0, n = n + Math.imul(I2, he) | 0, d = d + Math.imul(I2, ue2) | 0, l = l + Math.imul(g, le) | 0, n = n + Math.imul(g, de) | 0, n = n + Math.imul(_9, le) | 0, d = d + Math.imul(_9, de) | 0; + var je = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (je >>> 26) | 0, je &= 67108863, l = Math.imul(V3, X), n = Math.imul(V3, J2), n = n + Math.imul($, X) | 0, d = Math.imul($, J2), l = l + Math.imul(j, Q) | 0, n = n + Math.imul(j, ee) | 0, n = n + Math.imul(Z, Q) | 0, d = d + Math.imul(Z, ee) | 0, l = l + Math.imul(W, te2) | 0, n = n + Math.imul(W, re) | 0, n = n + Math.imul(K, te2) | 0, d = d + Math.imul(K, re) | 0, l = l + Math.imul(z, ie) | 0, n = n + Math.imul(z, ne) | 0, n = n + Math.imul(H, ie) | 0, d = d + Math.imul(H, ne) | 0, l = l + Math.imul(F, fe) | 0, n = n + Math.imul(F, ae2) | 0, n = n + Math.imul(U, fe) | 0, d = d + Math.imul(U, ae2) | 0, l = l + Math.imul(C2, oe) | 0, n = n + Math.imul(C2, se2) | 0, n = n + Math.imul(O, oe) | 0, d = d + Math.imul(O, se2) | 0, l = l + Math.imul(k2, he) | 0, n = n + Math.imul(k2, ue2) | 0, n = n + Math.imul(D, he) | 0, d = d + Math.imul(D, ue2) | 0, l = l + Math.imul(R, le) | 0, n = n + Math.imul(R, de) | 0, n = n + Math.imul(I2, le) | 0, d = d + Math.imul(I2, de) | 0, l = l + Math.imul(g, ce2) | 0, n = n + Math.imul(g, pe2) | 0, n = n + Math.imul(_9, ce2) | 0, d = d + Math.imul(_9, pe2) | 0; + var Ze2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ze2 >>> 26) | 0, Ze2 &= 67108863, l = Math.imul(G, X), n = Math.imul(G, J2), n = n + Math.imul(Y, X) | 0, d = Math.imul(Y, J2), l = l + Math.imul(V3, Q) | 0, n = n + Math.imul(V3, ee) | 0, n = n + Math.imul($, Q) | 0, d = d + Math.imul($, ee) | 0, l = l + Math.imul(j, te2) | 0, n = n + Math.imul(j, re) | 0, n = n + Math.imul(Z, te2) | 0, d = d + Math.imul(Z, re) | 0, l = l + Math.imul(W, ie) | 0, n = n + Math.imul(W, ne) | 0, n = n + Math.imul(K, ie) | 0, d = d + Math.imul(K, ne) | 0, l = l + Math.imul(z, fe) | 0, n = n + Math.imul(z, ae2) | 0, n = n + Math.imul(H, fe) | 0, d = d + Math.imul(H, ae2) | 0, l = l + Math.imul(F, oe) | 0, n = n + Math.imul(F, se2) | 0, n = n + Math.imul(U, oe) | 0, d = d + Math.imul(U, se2) | 0, l = l + Math.imul(C2, he) | 0, n = n + Math.imul(C2, ue2) | 0, n = n + Math.imul(O, he) | 0, d = d + Math.imul(O, ue2) | 0, l = l + Math.imul(k2, le) | 0, n = n + Math.imul(k2, de) | 0, n = n + Math.imul(D, le) | 0, d = d + Math.imul(D, de) | 0, l = l + Math.imul(R, ce2) | 0, n = n + Math.imul(R, pe2) | 0, n = n + Math.imul(I2, ce2) | 0, d = d + Math.imul(I2, pe2) | 0, l = l + Math.imul(g, ve) | 0, n = n + Math.imul(g, be) | 0, n = n + Math.imul(_9, ve) | 0, d = d + Math.imul(_9, be) | 0; + var Ve = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ve >>> 26) | 0, Ve &= 67108863, l = Math.imul(G, Q), n = Math.imul(G, ee), n = n + Math.imul(Y, Q) | 0, d = Math.imul(Y, ee), l = l + Math.imul(V3, te2) | 0, n = n + Math.imul(V3, re) | 0, n = n + Math.imul($, te2) | 0, d = d + Math.imul($, re) | 0, l = l + Math.imul(j, ie) | 0, n = n + Math.imul(j, ne) | 0, n = n + Math.imul(Z, ie) | 0, d = d + Math.imul(Z, ne) | 0, l = l + Math.imul(W, fe) | 0, n = n + Math.imul(W, ae2) | 0, n = n + Math.imul(K, fe) | 0, d = d + Math.imul(K, ae2) | 0, l = l + Math.imul(z, oe) | 0, n = n + Math.imul(z, se2) | 0, n = n + Math.imul(H, oe) | 0, d = d + Math.imul(H, se2) | 0, l = l + Math.imul(F, he) | 0, n = n + Math.imul(F, ue2) | 0, n = n + Math.imul(U, he) | 0, d = d + Math.imul(U, ue2) | 0, l = l + Math.imul(C2, le) | 0, n = n + Math.imul(C2, de) | 0, n = n + Math.imul(O, le) | 0, d = d + Math.imul(O, de) | 0, l = l + Math.imul(k2, ce2) | 0, n = n + Math.imul(k2, pe2) | 0, n = n + Math.imul(D, ce2) | 0, d = d + Math.imul(D, pe2) | 0, l = l + Math.imul(R, ve) | 0, n = n + Math.imul(R, be) | 0, n = n + Math.imul(I2, ve) | 0, d = d + Math.imul(I2, be) | 0; + var $e = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + ($e >>> 26) | 0, $e &= 67108863, l = Math.imul(G, te2), n = Math.imul(G, re), n = n + Math.imul(Y, te2) | 0, d = Math.imul(Y, re), l = l + Math.imul(V3, ie) | 0, n = n + Math.imul(V3, ne) | 0, n = n + Math.imul($, ie) | 0, d = d + Math.imul($, ne) | 0, l = l + Math.imul(j, fe) | 0, n = n + Math.imul(j, ae2) | 0, n = n + Math.imul(Z, fe) | 0, d = d + Math.imul(Z, ae2) | 0, l = l + Math.imul(W, oe) | 0, n = n + Math.imul(W, se2) | 0, n = n + Math.imul(K, oe) | 0, d = d + Math.imul(K, se2) | 0, l = l + Math.imul(z, he) | 0, n = n + Math.imul(z, ue2) | 0, n = n + Math.imul(H, he) | 0, d = d + Math.imul(H, ue2) | 0, l = l + Math.imul(F, le) | 0, n = n + Math.imul(F, de) | 0, n = n + Math.imul(U, le) | 0, d = d + Math.imul(U, de) | 0, l = l + Math.imul(C2, ce2) | 0, n = n + Math.imul(C2, pe2) | 0, n = n + Math.imul(O, ce2) | 0, d = d + Math.imul(O, pe2) | 0, l = l + Math.imul(k2, ve) | 0, n = n + Math.imul(k2, be) | 0, n = n + Math.imul(D, ve) | 0, d = d + Math.imul(D, be) | 0; + var Ge = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ge >>> 26) | 0, Ge &= 67108863, l = Math.imul(G, ie), n = Math.imul(G, ne), n = n + Math.imul(Y, ie) | 0, d = Math.imul(Y, ne), l = l + Math.imul(V3, fe) | 0, n = n + Math.imul(V3, ae2) | 0, n = n + Math.imul($, fe) | 0, d = d + Math.imul($, ae2) | 0, l = l + Math.imul(j, oe) | 0, n = n + Math.imul(j, se2) | 0, n = n + Math.imul(Z, oe) | 0, d = d + Math.imul(Z, se2) | 0, l = l + Math.imul(W, he) | 0, n = n + Math.imul(W, ue2) | 0, n = n + Math.imul(K, he) | 0, d = d + Math.imul(K, ue2) | 0, l = l + Math.imul(z, le) | 0, n = n + Math.imul(z, de) | 0, n = n + Math.imul(H, le) | 0, d = d + Math.imul(H, de) | 0, l = l + Math.imul(F, ce2) | 0, n = n + Math.imul(F, pe2) | 0, n = n + Math.imul(U, ce2) | 0, d = d + Math.imul(U, pe2) | 0, l = l + Math.imul(C2, ve) | 0, n = n + Math.imul(C2, be) | 0, n = n + Math.imul(O, ve) | 0, d = d + Math.imul(O, be) | 0; + var Ye = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ye >>> 26) | 0, Ye &= 67108863, l = Math.imul(G, fe), n = Math.imul(G, ae2), n = n + Math.imul(Y, fe) | 0, d = Math.imul(Y, ae2), l = l + Math.imul(V3, oe) | 0, n = n + Math.imul(V3, se2) | 0, n = n + Math.imul($, oe) | 0, d = d + Math.imul($, se2) | 0, l = l + Math.imul(j, he) | 0, n = n + Math.imul(j, ue2) | 0, n = n + Math.imul(Z, he) | 0, d = d + Math.imul(Z, ue2) | 0, l = l + Math.imul(W, le) | 0, n = n + Math.imul(W, de) | 0, n = n + Math.imul(K, le) | 0, d = d + Math.imul(K, de) | 0, l = l + Math.imul(z, ce2) | 0, n = n + Math.imul(z, pe2) | 0, n = n + Math.imul(H, ce2) | 0, d = d + Math.imul(H, pe2) | 0, l = l + Math.imul(F, ve) | 0, n = n + Math.imul(F, be) | 0, n = n + Math.imul(U, ve) | 0, d = d + Math.imul(U, be) | 0; + var Xe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Xe >>> 26) | 0, Xe &= 67108863, l = Math.imul(G, oe), n = Math.imul(G, se2), n = n + Math.imul(Y, oe) | 0, d = Math.imul(Y, se2), l = l + Math.imul(V3, he) | 0, n = n + Math.imul(V3, ue2) | 0, n = n + Math.imul($, he) | 0, d = d + Math.imul($, ue2) | 0, l = l + Math.imul(j, le) | 0, n = n + Math.imul(j, de) | 0, n = n + Math.imul(Z, le) | 0, d = d + Math.imul(Z, de) | 0, l = l + Math.imul(W, ce2) | 0, n = n + Math.imul(W, pe2) | 0, n = n + Math.imul(K, ce2) | 0, d = d + Math.imul(K, pe2) | 0, l = l + Math.imul(z, ve) | 0, n = n + Math.imul(z, be) | 0, n = n + Math.imul(H, ve) | 0, d = d + Math.imul(H, be) | 0; + var Je = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Je >>> 26) | 0, Je &= 67108863, l = Math.imul(G, he), n = Math.imul(G, ue2), n = n + Math.imul(Y, he) | 0, d = Math.imul(Y, ue2), l = l + Math.imul(V3, le) | 0, n = n + Math.imul(V3, de) | 0, n = n + Math.imul($, le) | 0, d = d + Math.imul($, de) | 0, l = l + Math.imul(j, ce2) | 0, n = n + Math.imul(j, pe2) | 0, n = n + Math.imul(Z, ce2) | 0, d = d + Math.imul(Z, pe2) | 0, l = l + Math.imul(W, ve) | 0, n = n + Math.imul(W, be) | 0, n = n + Math.imul(K, ve) | 0, d = d + Math.imul(K, be) | 0; + var Qe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Qe >>> 26) | 0, Qe &= 67108863, l = Math.imul(G, le), n = Math.imul(G, de), n = n + Math.imul(Y, le) | 0, d = Math.imul(Y, de), l = l + Math.imul(V3, ce2) | 0, n = n + Math.imul(V3, pe2) | 0, n = n + Math.imul($, ce2) | 0, d = d + Math.imul($, pe2) | 0, l = l + Math.imul(j, ve) | 0, n = n + Math.imul(j, be) | 0, n = n + Math.imul(Z, ve) | 0, d = d + Math.imul(Z, be) | 0; + var et2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (et2 >>> 26) | 0, et2 &= 67108863, l = Math.imul(G, ce2), n = Math.imul(G, pe2), n = n + Math.imul(Y, ce2) | 0, d = Math.imul(Y, pe2), l = l + Math.imul(V3, ve) | 0, n = n + Math.imul(V3, be) | 0, n = n + Math.imul($, ve) | 0, d = d + Math.imul($, be) | 0; + var tt2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (tt2 >>> 26) | 0, tt2 &= 67108863, l = Math.imul(G, ve), n = Math.imul(G, be), n = n + Math.imul(Y, ve) | 0, d = Math.imul(Y, be); + var rt2 = (b + l | 0) + ((n & 8191) << 13) | 0; + return b = (d + (n >>> 13) | 0) + (rt2 >>> 26) | 0, rt2 &= 67108863, c[0] = ft, c[1] = Be, c[2] = qe, c[3] = ze, c[4] = He2, c[5] = We, c[6] = Ke2, c[7] = je, c[8] = Ze2, c[9] = Ve, c[10] = $e, c[11] = Ge, c[12] = Ye, c[13] = Xe, c[14] = Je, c[15] = Qe, c[16] = et2, c[17] = tt2, c[18] = rt2, b !== 0 && (c[19] = b, h.length++), h; + }; + Math.imul || (L = q); + function ge(v, i, a) { + a.negative = i.negative ^ v.negative, a.length = v.length + i.length; + for (var h = 0, s = 0, u = 0;u < a.length - 1; u++) { + var c = s; + s = 0; + for (var b = h & 67108863, l = Math.min(u, i.length - 1), n = Math.max(0, u - v.length + 1);n <= l; n++) { + var d = u - n, w = v.words[d] | 0, g = i.words[n] | 0, _9 = w * g, A = _9 & 67108863; + c = c + (_9 / 67108864 | 0) | 0, A = A + b | 0, b = A & 67108863, c = c + (A >>> 26) | 0, s += c >>> 26, c &= 67108863; + } + a.words[u] = b, h = c, c = s; + } + return h !== 0 ? a.words[u] = h : a.length--, a.strip(); + } + function _e(v, i, a) { + var h = new N; + return h.mulp(v, i, a); + } + f.prototype.mulTo = function(i, a) { + var h, s = this.length + i.length; + return this.length === 10 && i.length === 10 ? h = L(this, i, a) : s < 63 ? h = q(this, i, a) : s < 1024 ? h = ge(this, i, a) : h = _e(this, i, a), h; + }; + function N(v, i) { + this.x = v, this.y = i; + } + N.prototype.makeRBT = function(i) { + for (var a = new Array(i), h = f.prototype._countBits(i) - 1, s = 0;s < i; s++) + a[s] = this.revBin(s, h, i); + return a; + }, N.prototype.revBin = function(i, a, h) { + if (i === 0 || i === h - 1) + return i; + for (var s = 0, u = 0;u < a; u++) + s |= (i & 1) << a - u - 1, i >>= 1; + return s; + }, N.prototype.permute = function(i, a, h, s, u, c) { + for (var b = 0;b < c; b++) + s[b] = a[i[b]], u[b] = h[i[b]]; + }, N.prototype.transform = function(i, a, h, s, u, c) { + this.permute(c, i, a, h, s, u); + for (var b = 1;b < u; b <<= 1) + for (var l = b << 1, n = Math.cos(2 * Math.PI / l), d = Math.sin(2 * Math.PI / l), w = 0;w < u; w += l) + for (var g = n, _9 = d, A = 0;A < b; A++) { + var R = h[w + A], I2 = s[w + A], Me = h[w + A + b], k2 = s[w + A + b], D = g * Me - _9 * k2; + k2 = g * k2 + _9 * Me, Me = D, h[w + A] = R + Me, s[w + A] = I2 + k2, h[w + A + b] = R - Me, s[w + A + b] = I2 - k2, A !== l && (D = n * g - d * _9, _9 = n * _9 + d * g, g = D); + } + }, N.prototype.guessLen13b = function(i, a) { + var h = Math.max(a, i) | 1, s = h & 1, u = 0; + for (h = h / 2 | 0;h; h = h >>> 1) + u++; + return 1 << u + 1 + s; + }, N.prototype.conjugate = function(i, a, h) { + if (!(h <= 1)) + for (var s = 0;s < h / 2; s++) { + var u = i[s]; + i[s] = i[h - s - 1], i[h - s - 1] = u, u = a[s], a[s] = -a[h - s - 1], a[h - s - 1] = -u; + } + }, N.prototype.normalize13b = function(i, a) { + for (var h = 0, s = 0;s < a / 2; s++) { + var u = Math.round(i[2 * s + 1] / a) * 8192 + Math.round(i[2 * s] / a) + h; + i[s] = u & 67108863, u < 67108864 ? h = 0 : h = u / 67108864 | 0; + } + return i; + }, N.prototype.convert13b = function(i, a, h, s) { + for (var u = 0, c = 0;c < a; c++) + u = u + (i[c] | 0), h[2 * c] = u & 8191, u = u >>> 13, h[2 * c + 1] = u & 8191, u = u >>> 13; + for (c = 2 * a;c < s; ++c) + h[c] = 0; + r(u === 0), r((u & -8192) === 0); + }, N.prototype.stub = function(i) { + for (var a = new Array(i), h = 0;h < i; h++) + a[h] = 0; + return a; + }, N.prototype.mulp = function(i, a, h) { + var s = 2 * this.guessLen13b(i.length, a.length), u = this.makeRBT(s), c = this.stub(s), b = new Array(s), l = new Array(s), n = new Array(s), d = new Array(s), w = new Array(s), g = new Array(s), _9 = h.words; + _9.length = s, this.convert13b(i.words, i.length, b, s), this.convert13b(a.words, a.length, d, s), this.transform(b, c, l, n, s, u), this.transform(d, c, w, g, s, u); + for (var A = 0;A < s; A++) { + var R = l[A] * w[A] - n[A] * g[A]; + n[A] = l[A] * g[A] + n[A] * w[A], l[A] = R; + } + return this.conjugate(l, n, s), this.transform(l, n, _9, c, s, u), this.conjugate(_9, c, s), this.normalize13b(_9, s), h.negative = i.negative ^ a.negative, h.length = i.length + a.length, h.strip(); + }, f.prototype.mul = function(i) { + var a = new f(null); + return a.words = new Array(this.length + i.length), this.mulTo(i, a); + }, f.prototype.mulf = function(i) { + var a = new f(null); + return a.words = new Array(this.length + i.length), _e(this, i, a); + }, f.prototype.imul = function(i) { + return this.clone().mulTo(i, this); + }, f.prototype.imuln = function(i) { + r(typeof i == "number"), r(i < 67108864); + for (var a = 0, h = 0;h < this.length; h++) { + var s = (this.words[h] | 0) * i, u = (s & 67108863) + (a & 67108863); + a >>= 26, a += s / 67108864 | 0, a += u >>> 26, this.words[h] = u & 67108863; + } + return a !== 0 && (this.words[h] = a, this.length++), this; + }, f.prototype.muln = function(i) { + return this.clone().imuln(i); + }, f.prototype.sqr = function() { + return this.mul(this); + }, f.prototype.isqr = function() { + return this.imul(this.clone()); + }, f.prototype.pow = function(i) { + var a = B(i); + if (a.length === 0) + return new f(1); + for (var h = this, s = 0;s < a.length && a[s] === 0; s++, h = h.sqr()) + ; + if (++s < a.length) + for (var u = h.sqr();s < a.length; s++, u = u.sqr()) + a[s] !== 0 && (h = h.mul(u)); + return h; + }, f.prototype.iushln = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26, s = 67108863 >>> 26 - a << 26 - a, u; + if (a !== 0) { + var c = 0; + for (u = 0;u < this.length; u++) { + var b = this.words[u] & s, l = (this.words[u] | 0) - b << a; + this.words[u] = l | c, c = b >>> 26 - a; + } + c && (this.words[u] = c, this.length++); + } + if (h !== 0) { + for (u = this.length - 1;u >= 0; u--) + this.words[u + h] = this.words[u]; + for (u = 0;u < h; u++) + this.words[u] = 0; + this.length += h; + } + return this.strip(); + }, f.prototype.ishln = function(i) { + return r(this.negative === 0), this.iushln(i); + }, f.prototype.iushrn = function(i, a, h) { + r(typeof i == "number" && i >= 0); + var s; + a ? s = (a - a % 26) / 26 : s = 0; + var u = i % 26, c = Math.min((i - u) / 26, this.length), b = 67108863 ^ 67108863 >>> u << u, l = h; + if (s -= c, s = Math.max(0, s), l) { + for (var n = 0;n < c; n++) + l.words[n] = this.words[n]; + l.length = c; + } + if (c !== 0) + if (this.length > c) + for (this.length -= c, n = 0;n < this.length; n++) + this.words[n] = this.words[n + c]; + else + this.words[0] = 0, this.length = 1; + var d = 0; + for (n = this.length - 1;n >= 0 && (d !== 0 || n >= s); n--) { + var w = this.words[n] | 0; + this.words[n] = d << 26 - u | w >>> u, d = w & b; + } + return l && d !== 0 && (l.words[l.length++] = d), this.length === 0 && (this.words[0] = 0, this.length = 1), this.strip(); + }, f.prototype.ishrn = function(i, a, h) { + return r(this.negative === 0), this.iushrn(i, a, h); + }, f.prototype.shln = function(i) { + return this.clone().ishln(i); + }, f.prototype.ushln = function(i) { + return this.clone().iushln(i); + }, f.prototype.shrn = function(i) { + return this.clone().ishrn(i); + }, f.prototype.ushrn = function(i) { + return this.clone().iushrn(i); + }, f.prototype.testn = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26, s = 1 << a; + if (this.length <= h) + return false; + var u = this.words[h]; + return !!(u & s); + }, f.prototype.imaskn = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26; + if (r(this.negative === 0, "imaskn works only with positive numbers"), this.length <= h) + return this; + if (a !== 0 && h++, this.length = Math.min(h, this.length), a !== 0) { + var s = 67108863 ^ 67108863 >>> a << a; + this.words[this.length - 1] &= s; + } + return this.strip(); + }, f.prototype.maskn = function(i) { + return this.clone().imaskn(i); + }, f.prototype.iaddn = function(i) { + return r(typeof i == "number"), r(i < 67108864), i < 0 ? this.isubn(-i) : this.negative !== 0 ? this.length === 1 && (this.words[0] | 0) < i ? (this.words[0] = i - (this.words[0] | 0), this.negative = 0, this) : (this.negative = 0, this.isubn(i), this.negative = 1, this) : this._iaddn(i); + }, f.prototype._iaddn = function(i) { + this.words[0] += i; + for (var a = 0;a < this.length && this.words[a] >= 67108864; a++) + this.words[a] -= 67108864, a === this.length - 1 ? this.words[a + 1] = 1 : this.words[a + 1]++; + return this.length = Math.max(this.length, a + 1), this; + }, f.prototype.isubn = function(i) { + if (r(typeof i == "number"), r(i < 67108864), i < 0) + return this.iaddn(-i); + if (this.negative !== 0) + return this.negative = 0, this.iaddn(i), this.negative = 1, this; + if (this.words[0] -= i, this.length === 1 && this.words[0] < 0) + this.words[0] = -this.words[0], this.negative = 1; + else + for (var a = 0;a < this.length && this.words[a] < 0; a++) + this.words[a] += 67108864, this.words[a + 1] -= 1; + return this.strip(); + }, f.prototype.addn = function(i) { + return this.clone().iaddn(i); + }, f.prototype.subn = function(i) { + return this.clone().isubn(i); + }, f.prototype.iabs = function() { + return this.negative = 0, this; + }, f.prototype.abs = function() { + return this.clone().iabs(); + }, f.prototype._ishlnsubmul = function(i, a, h) { + var s = i.length + h, u; + this._expand(s); + var c, b = 0; + for (u = 0;u < i.length; u++) { + c = (this.words[u + h] | 0) + b; + var l = (i.words[u] | 0) * a; + c -= l & 67108863, b = (c >> 26) - (l / 67108864 | 0), this.words[u + h] = c & 67108863; + } + for (;u < this.length - h; u++) + c = (this.words[u + h] | 0) + b, b = c >> 26, this.words[u + h] = c & 67108863; + if (b === 0) + return this.strip(); + for (r(b === -1), b = 0, u = 0;u < this.length; u++) + c = -(this.words[u] | 0) + b, b = c >> 26, this.words[u] = c & 67108863; + return this.negative = 1, this.strip(); + }, f.prototype._wordDiv = function(i, a) { + var h = this.length - i.length, s = this.clone(), u = i, c = u.words[u.length - 1] | 0, b = this._countBits(c); + h = 26 - b, h !== 0 && (u = u.ushln(h), s.iushln(h), c = u.words[u.length - 1] | 0); + var l = s.length - u.length, n; + if (a !== "mod") { + n = new f(null), n.length = l + 1, n.words = new Array(n.length); + for (var d = 0;d < n.length; d++) + n.words[d] = 0; + } + var w = s.clone()._ishlnsubmul(u, 1, l); + w.negative === 0 && (s = w, n && (n.words[l] = 1)); + for (var g = l - 1;g >= 0; g--) { + var _9 = (s.words[u.length + g] | 0) * 67108864 + (s.words[u.length + g - 1] | 0); + for (_9 = Math.min(_9 / c | 0, 67108863), s._ishlnsubmul(u, _9, g);s.negative !== 0; ) + _9--, s.negative = 0, s._ishlnsubmul(u, 1, g), s.isZero() || (s.negative ^= 1); + n && (n.words[g] = _9); + } + return n && n.strip(), s.strip(), a !== "div" && h !== 0 && s.iushrn(h), { div: n || null, mod: s }; + }, f.prototype.divmod = function(i, a, h) { + if (r(!i.isZero()), this.isZero()) + return { div: new f(0), mod: new f(0) }; + var s, u, c; + return this.negative !== 0 && i.negative === 0 ? (c = this.neg().divmod(i, a), a !== "mod" && (s = c.div.neg()), a !== "div" && (u = c.mod.neg(), h && u.negative !== 0 && u.iadd(i)), { div: s, mod: u }) : this.negative === 0 && i.negative !== 0 ? (c = this.divmod(i.neg(), a), a !== "mod" && (s = c.div.neg()), { div: s, mod: c.mod }) : (this.negative & i.negative) !== 0 ? (c = this.neg().divmod(i.neg(), a), a !== "div" && (u = c.mod.neg(), h && u.negative !== 0 && u.isub(i)), { div: c.div, mod: u }) : i.length > this.length || this.cmp(i) < 0 ? { div: new f(0), mod: this } : i.length === 1 ? a === "div" ? { div: this.divn(i.words[0]), mod: null } : a === "mod" ? { div: null, mod: new f(this.modn(i.words[0])) } : { div: this.divn(i.words[0]), mod: new f(this.modn(i.words[0])) } : this._wordDiv(i, a); + }, f.prototype.div = function(i) { + return this.divmod(i, "div", false).div; + }, f.prototype.mod = function(i) { + return this.divmod(i, "mod", false).mod; + }, f.prototype.umod = function(i) { + return this.divmod(i, "mod", true).mod; + }, f.prototype.divRound = function(i) { + var a = this.divmod(i); + if (a.mod.isZero()) + return a.div; + var h = a.div.negative !== 0 ? a.mod.isub(i) : a.mod, s = i.ushrn(1), u = i.andln(1), c = h.cmp(s); + return c < 0 || u === 1 && c === 0 ? a.div : a.div.negative !== 0 ? a.div.isubn(1) : a.div.iaddn(1); + }, f.prototype.modn = function(i) { + r(i <= 67108863); + for (var a = (1 << 26) % i, h = 0, s = this.length - 1;s >= 0; s--) + h = (a * h + (this.words[s] | 0)) % i; + return h; + }, f.prototype.idivn = function(i) { + r(i <= 67108863); + for (var a = 0, h = this.length - 1;h >= 0; h--) { + var s = (this.words[h] | 0) + a * 67108864; + this.words[h] = s / i | 0, a = s % i; + } + return this.strip(); + }, f.prototype.divn = function(i) { + return this.clone().idivn(i); + }, f.prototype.egcd = function(i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, h = i.clone(); + a.negative !== 0 ? a = a.umod(i) : a = a.clone(); + for (var s = new f(1), u = new f(0), c = new f(0), b = new f(1), l = 0;a.isEven() && h.isEven(); ) + a.iushrn(1), h.iushrn(1), ++l; + for (var n = h.clone(), d = a.clone();!a.isZero(); ) { + for (var w = 0, g = 1;(a.words[0] & g) === 0 && w < 26; ++w, g <<= 1) + ; + if (w > 0) + for (a.iushrn(w);w-- > 0; ) + (s.isOdd() || u.isOdd()) && (s.iadd(n), u.isub(d)), s.iushrn(1), u.iushrn(1); + for (var _9 = 0, A = 1;(h.words[0] & A) === 0 && _9 < 26; ++_9, A <<= 1) + ; + if (_9 > 0) + for (h.iushrn(_9);_9-- > 0; ) + (c.isOdd() || b.isOdd()) && (c.iadd(n), b.isub(d)), c.iushrn(1), b.iushrn(1); + a.cmp(h) >= 0 ? (a.isub(h), s.isub(c), u.isub(b)) : (h.isub(a), c.isub(s), b.isub(u)); + } + return { a: c, b, gcd: h.iushln(l) }; + }, f.prototype._invmp = function(i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, h = i.clone(); + a.negative !== 0 ? a = a.umod(i) : a = a.clone(); + for (var s = new f(1), u = new f(0), c = h.clone();a.cmpn(1) > 0 && h.cmpn(1) > 0; ) { + for (var b = 0, l = 1;(a.words[0] & l) === 0 && b < 26; ++b, l <<= 1) + ; + if (b > 0) + for (a.iushrn(b);b-- > 0; ) + s.isOdd() && s.iadd(c), s.iushrn(1); + for (var n = 0, d = 1;(h.words[0] & d) === 0 && n < 26; ++n, d <<= 1) + ; + if (n > 0) + for (h.iushrn(n);n-- > 0; ) + u.isOdd() && u.iadd(c), u.iushrn(1); + a.cmp(h) >= 0 ? (a.isub(h), s.isub(u)) : (h.isub(a), u.isub(s)); + } + var w; + return a.cmpn(1) === 0 ? w = s : w = u, w.cmpn(0) < 0 && w.iadd(i), w; + }, f.prototype.gcd = function(i) { + if (this.isZero()) + return i.abs(); + if (i.isZero()) + return this.abs(); + var a = this.clone(), h = i.clone(); + a.negative = 0, h.negative = 0; + for (var s = 0;a.isEven() && h.isEven(); s++) + a.iushrn(1), h.iushrn(1); + do { + for (;a.isEven(); ) + a.iushrn(1); + for (;h.isEven(); ) + h.iushrn(1); + var u = a.cmp(h); + if (u < 0) { + var c = a; + a = h, h = c; + } else if (u === 0 || h.cmpn(1) === 0) + break; + a.isub(h); + } while (true); + return h.iushln(s); + }, f.prototype.invm = function(i) { + return this.egcd(i).a.umod(i); + }, f.prototype.isEven = function() { + return (this.words[0] & 1) === 0; + }, f.prototype.isOdd = function() { + return (this.words[0] & 1) === 1; + }, f.prototype.andln = function(i) { + return this.words[0] & i; + }, f.prototype.bincn = function(i) { + r(typeof i == "number"); + var a = i % 26, h = (i - a) / 26, s = 1 << a; + if (this.length <= h) + return this._expand(h + 1), this.words[h] |= s, this; + for (var u = s, c = h;u !== 0 && c < this.length; c++) { + var b = this.words[c] | 0; + b += u, u = b >>> 26, b &= 67108863, this.words[c] = b; + } + return u !== 0 && (this.words[c] = u, this.length++), this; + }, f.prototype.isZero = function() { + return this.length === 1 && this.words[0] === 0; + }, f.prototype.cmpn = function(i) { + var a = i < 0; + if (this.negative !== 0 && !a) + return -1; + if (this.negative === 0 && a) + return 1; + this.strip(); + var h; + if (this.length > 1) + h = 1; + else { + a && (i = -i), r(i <= 67108863, "Number is too big"); + var s = this.words[0] | 0; + h = s === i ? 0 : s < i ? -1 : 1; + } + return this.negative !== 0 ? -h | 0 : h; + }, f.prototype.cmp = function(i) { + if (this.negative !== 0 && i.negative === 0) + return -1; + if (this.negative === 0 && i.negative !== 0) + return 1; + var a = this.ucmp(i); + return this.negative !== 0 ? -a | 0 : a; + }, f.prototype.ucmp = function(i) { + if (this.length > i.length) + return 1; + if (this.length < i.length) + return -1; + for (var a = 0, h = this.length - 1;h >= 0; h--) { + var s = this.words[h] | 0, u = i.words[h] | 0; + if (s !== u) { + s < u ? a = -1 : s > u && (a = 1); + break; + } + } + return a; + }, f.prototype.gtn = function(i) { + return this.cmpn(i) === 1; + }, f.prototype.gt = function(i) { + return this.cmp(i) === 1; + }, f.prototype.gten = function(i) { + return this.cmpn(i) >= 0; + }, f.prototype.gte = function(i) { + return this.cmp(i) >= 0; + }, f.prototype.ltn = function(i) { + return this.cmpn(i) === -1; + }, f.prototype.lt = function(i) { + return this.cmp(i) === -1; + }, f.prototype.lten = function(i) { + return this.cmpn(i) <= 0; + }, f.prototype.lte = function(i) { + return this.cmp(i) <= 0; + }, f.prototype.eqn = function(i) { + return this.cmpn(i) === 0; + }, f.prototype.eq = function(i) { + return this.cmp(i) === 0; + }, f.red = function(i) { + return new P(i); + }, f.prototype.toRed = function(i) { + return r(!this.red, "Already a number in reduction context"), r(this.negative === 0, "red works only with positives"), i.convertTo(this)._forceRed(i); + }, f.prototype.fromRed = function() { + return r(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); + }, f.prototype._forceRed = function(i) { + return this.red = i, this; + }, f.prototype.forceRed = function(i) { + return r(!this.red, "Already a number in reduction context"), this._forceRed(i); + }, f.prototype.redAdd = function(i) { + return r(this.red, "redAdd works only with red numbers"), this.red.add(this, i); + }, f.prototype.redIAdd = function(i) { + return r(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, i); + }, f.prototype.redSub = function(i) { + return r(this.red, "redSub works only with red numbers"), this.red.sub(this, i); + }, f.prototype.redISub = function(i) { + return r(this.red, "redISub works only with red numbers"), this.red.isub(this, i); + }, f.prototype.redShl = function(i) { + return r(this.red, "redShl works only with red numbers"), this.red.shl(this, i); + }, f.prototype.redMul = function(i) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, i), this.red.mul(this, i); + }, f.prototype.redIMul = function(i) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, i), this.red.imul(this, i); + }, f.prototype.redSqr = function() { + return r(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); + }, f.prototype.redISqr = function() { + return r(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); + }, f.prototype.redSqrt = function() { + return r(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); + }, f.prototype.redInvm = function() { + return r(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); + }, f.prototype.redNeg = function() { + return r(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); + }, f.prototype.redPow = function(i) { + return r(this.red && !i.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, i); + }; + var we = { k256: null, p224: null, p192: null, p25519: null }; + function ye(v, i) { + this.name = v, this.p = new f(i, 16), this.n = this.p.bitLength(), this.k = new f(1).iushln(this.n).isub(this.p), this.tmp = this._tmp(); + } + ye.prototype._tmp = function() { + var i = new f(null); + return i.words = new Array(Math.ceil(this.n / 13)), i; + }, ye.prototype.ireduce = function(i) { + var a = i, h; + do + this.split(a, this.tmp), a = this.imulK(a), a = a.iadd(this.tmp), h = a.bitLength(); + while (h > this.n); + var s = h < this.n ? -1 : a.ucmp(this.p); + return s === 0 ? (a.words[0] = 0, a.length = 1) : s > 0 ? a.isub(this.p) : a.strip !== undefined ? a.strip() : a._strip(), a; + }, ye.prototype.split = function(i, a) { + i.iushrn(this.n, 0, a); + }, ye.prototype.imulK = function(i) { + return i.imul(this.k); + }; + function xe() { + ye.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); + } + o(xe, ye), xe.prototype.split = function(i, a) { + for (var h = 4194303, s = Math.min(i.length, 9), u = 0;u < s; u++) + a.words[u] = i.words[u]; + if (a.length = s, i.length <= 9) { + i.words[0] = 0, i.length = 1; + return; + } + var c = i.words[9]; + for (a.words[a.length++] = c & h, u = 10;u < i.length; u++) { + var b = i.words[u] | 0; + i.words[u - 10] = (b & h) << 4 | c >>> 22, c = b; + } + c >>>= 22, i.words[u - 10] = c, c === 0 && i.length > 10 ? i.length -= 10 : i.length -= 9; + }, xe.prototype.imulK = function(i) { + i.words[i.length] = 0, i.words[i.length + 1] = 0, i.length += 2; + for (var a = 0, h = 0;h < i.length; h++) { + var s = i.words[h] | 0; + a += s * 977, i.words[h] = a & 67108863, a = s * 64 + (a / 67108864 | 0); + } + return i.words[i.length - 1] === 0 && (i.length--, i.words[i.length - 1] === 0 && i.length--), i; + }; + function Re() { + ye.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); + } + o(Re, ye); + function Ee() { + ye.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); + } + o(Ee, ye); + function Ae() { + ye.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); + } + o(Ae, ye), Ae.prototype.imulK = function(i) { + for (var a = 0, h = 0;h < i.length; h++) { + var s = (i.words[h] | 0) * 19 + a, u = s & 67108863; + s >>>= 26, i.words[h] = u, a = s; + } + return a !== 0 && (i.words[i.length++] = a), i; + }, f._prime = function(i) { + if (we[i]) + return we[i]; + var a; + if (i === "k256") + a = new xe; + else if (i === "p224") + a = new Re; + else if (i === "p192") + a = new Ee; + else if (i === "p25519") + a = new Ae; + else + throw new Error("Unknown prime " + i); + return we[i] = a, a; + }; + function P(v) { + if (typeof v == "string") { + var i = f._prime(v); + this.m = i.p, this.prime = i; + } else + r(v.gtn(1), "modulus must be greater than 1"), this.m = v, this.prime = null; + } + P.prototype._verify1 = function(i) { + r(i.negative === 0, "red works only with positives"), r(i.red, "red works only with red numbers"); + }, P.prototype._verify2 = function(i, a) { + r((i.negative | a.negative) === 0, "red works only with positives"), r(i.red && i.red === a.red, "red works only with red numbers"); + }, P.prototype.imod = function(i) { + return this.prime ? this.prime.ireduce(i)._forceRed(this) : i.umod(this.m)._forceRed(this); + }, P.prototype.neg = function(i) { + return i.isZero() ? i.clone() : this.m.sub(i)._forceRed(this); + }, P.prototype.add = function(i, a) { + this._verify2(i, a); + var h = i.add(a); + return h.cmp(this.m) >= 0 && h.isub(this.m), h._forceRed(this); + }, P.prototype.iadd = function(i, a) { + this._verify2(i, a); + var h = i.iadd(a); + return h.cmp(this.m) >= 0 && h.isub(this.m), h; + }, P.prototype.sub = function(i, a) { + this._verify2(i, a); + var h = i.sub(a); + return h.cmpn(0) < 0 && h.iadd(this.m), h._forceRed(this); + }, P.prototype.isub = function(i, a) { + this._verify2(i, a); + var h = i.isub(a); + return h.cmpn(0) < 0 && h.iadd(this.m), h; + }, P.prototype.shl = function(i, a) { + return this._verify1(i), this.imod(i.ushln(a)); + }, P.prototype.imul = function(i, a) { + return this._verify2(i, a), this.imod(i.imul(a)); + }, P.prototype.mul = function(i, a) { + return this._verify2(i, a), this.imod(i.mul(a)); + }, P.prototype.isqr = function(i) { + return this.imul(i, i.clone()); + }, P.prototype.sqr = function(i) { + return this.mul(i, i); + }, P.prototype.sqrt = function(i) { + if (i.isZero()) + return i.clone(); + var a = this.m.andln(3); + if (r(a % 2 === 1), a === 3) { + var h = this.m.add(new f(1)).iushrn(2); + return this.pow(i, h); + } + for (var s = this.m.subn(1), u = 0;!s.isZero() && s.andln(1) === 0; ) + u++, s.iushrn(1); + r(!s.isZero()); + var c = new f(1).toRed(this), b = c.redNeg(), l = this.m.subn(1).iushrn(1), n = this.m.bitLength(); + for (n = new f(2 * n * n).toRed(this);this.pow(n, l).cmp(b) !== 0; ) + n.redIAdd(b); + for (var d = this.pow(n, s), w = this.pow(i, s.addn(1).iushrn(1)), g = this.pow(i, s), _9 = u;g.cmp(c) !== 0; ) { + for (var A = g, R = 0;A.cmp(c) !== 0; R++) + A = A.redSqr(); + r(R < _9); + var I2 = this.pow(d, new f(1).iushln(_9 - R - 1)); + w = w.redMul(I2), d = I2.redSqr(), g = g.redMul(d), _9 = R; + } + return w; + }, P.prototype.invm = function(i) { + var a = i._invmp(this.m); + return a.negative !== 0 ? (a.negative = 0, this.imod(a).redNeg()) : this.imod(a); + }, P.prototype.pow = function(i, a) { + if (a.isZero()) + return new f(1).toRed(this); + if (a.cmpn(1) === 0) + return i.clone(); + var h = 4, s = new Array(1 << h); + s[0] = new f(1).toRed(this), s[1] = i; + for (var u = 2;u < s.length; u++) + s[u] = this.mul(s[u - 1], i); + var c = s[0], b = 0, l = 0, n = a.bitLength() % 26; + for (n === 0 && (n = 26), u = a.length - 1;u >= 0; u--) { + for (var d = a.words[u], w = n - 1;w >= 0; w--) { + var g = d >> w & 1; + if (c !== s[0] && (c = this.sqr(c)), g === 0 && b === 0) { + l = 0; + continue; + } + b <<= 1, b |= g, l++, !(l !== h && (u !== 0 || w !== 0)) && (c = this.mul(c, s[b]), l = 0, b = 0); + } + n = 26; + } + return c; + }, P.prototype.convertTo = function(i) { + var a = i.umod(this.m); + return a === i ? a.clone() : a; + }, P.prototype.convertFrom = function(i) { + var a = i.clone(); + return a.red = null, a; + }, f.mont = function(i) { + return new Se2(i); + }; + function Se2(v) { + P.call(this, v), this.shift = this.m.bitLength(), this.shift % 26 !== 0 && (this.shift += 26 - this.shift % 26), this.r = new f(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv); + } + o(Se2, P), Se2.prototype.convertTo = function(i) { + return this.imod(i.ushln(this.shift)); + }, Se2.prototype.convertFrom = function(i) { + var a = this.imod(i.mul(this.rinv)); + return a.red = null, a; + }, Se2.prototype.imul = function(i, a) { + if (i.isZero() || a.isZero()) + return i.words[0] = 0, i.length = 1, i; + var h = i.imul(a), s = h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = h.isub(s).iushrn(this.shift), c = u; + return u.cmp(this.m) >= 0 ? c = u.isub(this.m) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }, Se2.prototype.mul = function(i, a) { + if (i.isZero() || a.isZero()) + return new f(0)._forceRed(this); + var h = i.mul(a), s = h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = h.isub(s).iushrn(this.shift), c = u; + return u.cmp(this.m) >= 0 ? c = u.isub(this.m) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }, Se2.prototype.invm = function(i) { + var a = this.imod(i._invmp(this.m).mul(this.r2)); + return a._forceRed(this); + }; + })(typeof yd > "u" || yd, L3); + }); + P3 = T((wL, D3) => { + var bq = o0(), mq = N3(); + D3.exports = function(e) { + return new Zn(e); + }; + var hr = { secp256k1: { name: "secp256k1", byteLength: 32 }, secp224r1: { name: "p224", byteLength: 28 }, prime256v1: { name: "p256", byteLength: 32 }, prime192v1: { name: "p192", byteLength: 24 }, ed25519: { name: "ed25519", byteLength: 32 }, secp384r1: { name: "p384", byteLength: 48 }, secp521r1: { name: "p521", byteLength: 66 } }; + hr.p224 = hr.secp224r1; + hr.p256 = hr.secp256r1 = hr.prime256v1; + hr.p192 = hr.secp192r1 = hr.prime192v1; + hr.p384 = hr.secp384r1; + hr.p521 = hr.secp521r1; + function Zn(t) { + this.curveType = hr[t], this.curveType || (this.curveType = { name: t }), this.curve = new bq.ec(this.curveType.name), this.keys = undefined; + } + Zn.prototype.generateKeys = function(t, e) { + return this.keys = this.curve.genKeyPair(), this.getPublicKey(t, e); + }; + Zn.prototype.computeSecret = function(t, e, r) { + e = e || "utf8", Buffer.isBuffer(t) || (t = new Buffer(t, e)); + var o = this.curve.keyFromPublic(t).getPublic(), f = o.mul(this.keys.getPrivate()).getX(); + return wd(f, r, this.curveType.byteLength); + }; + Zn.prototype.getPublicKey = function(t, e) { + var r = this.keys.getPublic(e === "compressed", true); + return e === "hybrid" && (r[r.length - 1] % 2 ? r[0] = 7 : r[0] = 6), wd(r, t); + }; + Zn.prototype.getPrivateKey = function(t) { + return wd(this.keys.getPrivate(), t); + }; + Zn.prototype.setPublicKey = function(t, e) { + return e = e || "utf8", Buffer.isBuffer(t) || (t = new Buffer(t, e)), this.keys._importPublic(t), this; + }; + Zn.prototype.setPrivateKey = function(t, e) { + e = e || "utf8", Buffer.isBuffer(t) || (t = new Buffer(t, e)); + var r = new mq(t); + return r = r.toString(16), this.keys = this.curve.genKeyPair(), this.keys._importPrivate(r), this; + }; + function wd(t, e, r) { + Array.isArray(t) || (t = t.toArray()); + var o = new Buffer(t); + if (r && o.length < r) { + var f = new Buffer(r - o.length); + f.fill(0), o = Buffer.concat([f, o]); + } + return e ? o.toString(e) : o; + } + }); + _d = T((ML, C3) => { + var gq = bf(), Md = Te().Buffer; + C3.exports = function(t, e) { + for (var r = Md.alloc(0), o = 0, f;r.length < e; ) + f = yq(o++), r = Md.concat([r, gq("sha1").update(t).update(f).digest()]); + return r.slice(0, e); + }; + function yq(t) { + var e = Md.allocUnsafe(4); + return e.writeUInt32BE(t, 0), e; + } + }); + xd = T((_L, O3) => { + O3.exports = function(e, r) { + for (var o = e.length, f = -1;++f < o; ) + e[f] ^= r[f]; + return e; + }; + }); + w0 = T((F3, Sd) => { + (function(t, e) { + function r(v, i) { + if (!v) + throw new Error(i || "Assertion failed"); + } + function o(v, i) { + v.super_ = i; + var a = function() { + }; + a.prototype = i.prototype, v.prototype = new a, v.prototype.constructor = v; + } + function f(v, i, a) { + if (f.isBN(v)) + return v; + this.negative = 0, this.words = null, this.length = 0, this.red = null, v !== null && ((i === "le" || i === "be") && (a = i, i = 10), this._init(v || 0, i || 10, a || "be")); + } + typeof t == "object" ? t.exports = f : e.BN = f, f.BN = f, f.wordSize = 26; + var p; + try { + typeof window < "u" && typeof window.Buffer < "u" ? p = window.Buffer : p = ji().Buffer; + } catch { + } + f.isBN = function(i) { + return i instanceof f ? true : i !== null && typeof i == "object" && i.constructor.wordSize === f.wordSize && Array.isArray(i.words); + }, f.max = function(i, a) { + return i.cmp(a) > 0 ? i : a; + }, f.min = function(i, a) { + return i.cmp(a) < 0 ? i : a; + }, f.prototype._init = function(i, a, h) { + if (typeof i == "number") + return this._initNumber(i, a, h); + if (typeof i == "object") + return this._initArray(i, a, h); + a === "hex" && (a = 16), r(a === (a | 0) && a >= 2 && a <= 36), i = i.toString().replace(/\s+/g, ""); + var s = 0; + i[0] === "-" && (s++, this.negative = 1), s < i.length && (a === 16 ? this._parseHex(i, s, h) : (this._parseBase(i, a, s), h === "le" && this._initArray(this.toArray(), a, h))); + }, f.prototype._initNumber = function(i, a, h) { + i < 0 && (this.negative = 1, i = -i), i < 67108864 ? (this.words = [i & 67108863], this.length = 1) : i < 4503599627370496 ? (this.words = [i & 67108863, i / 67108864 & 67108863], this.length = 2) : (r(i < 9007199254740992), this.words = [i & 67108863, i / 67108864 & 67108863, 1], this.length = 3), h === "le" && this._initArray(this.toArray(), a, h); + }, f.prototype._initArray = function(i, a, h) { + if (r(typeof i.length == "number"), i.length <= 0) + return this.words = [0], this.length = 1, this; + this.length = Math.ceil(i.length / 3), this.words = new Array(this.length); + for (var s = 0;s < this.length; s++) + this.words[s] = 0; + var u, c, b = 0; + if (h === "be") + for (s = i.length - 1, u = 0;s >= 0; s -= 3) + c = i[s] | i[s - 1] << 8 | i[s - 2] << 16, this.words[u] |= c << b & 67108863, this.words[u + 1] = c >>> 26 - b & 67108863, b += 24, b >= 26 && (b -= 26, u++); + else if (h === "le") + for (s = 0, u = 0;s < i.length; s += 3) + c = i[s] | i[s + 1] << 8 | i[s + 2] << 16, this.words[u] |= c << b & 67108863, this.words[u + 1] = c >>> 26 - b & 67108863, b += 24, b >= 26 && (b -= 26, u++); + return this.strip(); + }; + function m(v, i) { + var a = v.charCodeAt(i); + return a >= 65 && a <= 70 ? a - 55 : a >= 97 && a <= 102 ? a - 87 : a - 48 & 15; + } + function y(v, i, a) { + var h = m(v, a); + return a - 1 >= i && (h |= m(v, a - 1) << 4), h; + } + f.prototype._parseHex = function(i, a, h) { + this.length = Math.ceil((i.length - a) / 6), this.words = new Array(this.length); + for (var s = 0;s < this.length; s++) + this.words[s] = 0; + var u = 0, c = 0, b; + if (h === "be") + for (s = i.length - 1;s >= a; s -= 2) + b = y(i, a, s) << u, this.words[c] |= b & 67108863, u >= 18 ? (u -= 18, c += 1, this.words[c] |= b >>> 26) : u += 8; + else { + var l = i.length - a; + for (s = l % 2 === 0 ? a + 1 : a;s < i.length; s += 2) + b = y(i, a, s) << u, this.words[c] |= b & 67108863, u >= 18 ? (u -= 18, c += 1, this.words[c] |= b >>> 26) : u += 8; + } + this.strip(); + }; + function M(v, i, a, h) { + for (var s = 0, u = Math.min(v.length, a), c = i;c < u; c++) { + var b = v.charCodeAt(c) - 48; + s *= h, b >= 49 ? s += b - 49 + 10 : b >= 17 ? s += b - 17 + 10 : s += b; + } + return s; + } + f.prototype._parseBase = function(i, a, h) { + this.words = [0], this.length = 1; + for (var s = 0, u = 1;u <= 67108863; u *= a) + s++; + s--, u = u / a | 0; + for (var c = i.length - h, b = c % s, l = Math.min(c, c - b) + h, n = 0, d = h;d < l; d += s) + n = M(i, d, d + s, a), this.imuln(u), this.words[0] + n < 67108864 ? this.words[0] += n : this._iaddn(n); + if (b !== 0) { + var w = 1; + for (n = M(i, d, i.length, a), d = 0;d < b; d++) + w *= a; + this.imuln(w), this.words[0] + n < 67108864 ? this.words[0] += n : this._iaddn(n); + } + this.strip(); + }, f.prototype.copy = function(i) { + i.words = new Array(this.length); + for (var a = 0;a < this.length; a++) + i.words[a] = this.words[a]; + i.length = this.length, i.negative = this.negative, i.red = this.red; + }, f.prototype.clone = function() { + var i = new f(null); + return this.copy(i), i; + }, f.prototype._expand = function(i) { + for (;this.length < i; ) + this.words[this.length++] = 0; + return this; + }, f.prototype.strip = function() { + for (;this.length > 1 && this.words[this.length - 1] === 0; ) + this.length--; + return this._normSign(); + }, f.prototype._normSign = function() { + return this.length === 1 && this.words[0] === 0 && (this.negative = 0), this; + }, f.prototype.inspect = function() { + return (this.red ? ""; + }; + var x = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000"], S = [0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5], E2 = [0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176]; + f.prototype.toString = function(i, a) { + i = i || 10, a = a | 0 || 1; + var h; + if (i === 16 || i === "hex") { + h = ""; + for (var s = 0, u = 0, c = 0;c < this.length; c++) { + var b = this.words[c], l = ((b << s | u) & 16777215).toString(16); + u = b >>> 24 - s & 16777215, u !== 0 || c !== this.length - 1 ? h = x[6 - l.length] + l + h : h = l + h, s += 2, s >= 26 && (s -= 26, c--); + } + for (u !== 0 && (h = u.toString(16) + h);h.length % a !== 0; ) + h = "0" + h; + return this.negative !== 0 && (h = "-" + h), h; + } + if (i === (i | 0) && i >= 2 && i <= 36) { + var n = S[i], d = E2[i]; + h = ""; + var w = this.clone(); + for (w.negative = 0;!w.isZero(); ) { + var g = w.modn(d).toString(i); + w = w.idivn(d), w.isZero() ? h = g + h : h = x[n - g.length] + g + h; + } + for (this.isZero() && (h = "0" + h);h.length % a !== 0; ) + h = "0" + h; + return this.negative !== 0 && (h = "-" + h), h; + } + r(false, "Base should be between 2 and 36"); + }, f.prototype.toNumber = function() { + var i = this.words[0]; + return this.length === 2 ? i += this.words[1] * 67108864 : this.length === 3 && this.words[2] === 1 ? i += 4503599627370496 + this.words[1] * 67108864 : this.length > 2 && r(false, "Number can only safely store up to 53 bits"), this.negative !== 0 ? -i : i; + }, f.prototype.toJSON = function() { + return this.toString(16); + }, f.prototype.toBuffer = function(i, a) { + return r(typeof p < "u"), this.toArrayLike(p, i, a); + }, f.prototype.toArray = function(i, a) { + return this.toArrayLike(Array, i, a); + }, f.prototype.toArrayLike = function(i, a, h) { + var s = this.byteLength(), u = h || Math.max(1, s); + r(s <= u, "byte array longer than desired length"), r(u > 0, "Requested array length <= 0"), this.strip(); + var c = a === "le", b = new i(u), l, n, d = this.clone(); + if (c) { + for (n = 0;!d.isZero(); n++) + l = d.andln(255), d.iushrn(8), b[n] = l; + for (;n < u; n++) + b[n] = 0; + } else { + for (n = 0;n < u - s; n++) + b[n] = 0; + for (n = 0;!d.isZero(); n++) + l = d.andln(255), d.iushrn(8), b[u - n - 1] = l; + } + return b; + }, Math.clz32 ? f.prototype._countBits = function(i) { + return 32 - Math.clz32(i); + } : f.prototype._countBits = function(i) { + var a = i, h = 0; + return a >= 4096 && (h += 13, a >>>= 13), a >= 64 && (h += 7, a >>>= 7), a >= 8 && (h += 4, a >>>= 4), a >= 2 && (h += 2, a >>>= 2), h + a; + }, f.prototype._zeroBits = function(i) { + if (i === 0) + return 26; + var a = i, h = 0; + return (a & 8191) === 0 && (h += 13, a >>>= 13), (a & 127) === 0 && (h += 7, a >>>= 7), (a & 15) === 0 && (h += 4, a >>>= 4), (a & 3) === 0 && (h += 2, a >>>= 2), (a & 1) === 0 && h++, h; + }, f.prototype.bitLength = function() { + var i = this.words[this.length - 1], a = this._countBits(i); + return (this.length - 1) * 26 + a; + }; + function B(v) { + for (var i = new Array(v.bitLength()), a = 0;a < i.length; a++) { + var h = a / 26 | 0, s = a % 26; + i[a] = (v.words[h] & 1 << s) >>> s; + } + return i; + } + f.prototype.zeroBits = function() { + if (this.isZero()) + return 0; + for (var i = 0, a = 0;a < this.length; a++) { + var h = this._zeroBits(this.words[a]); + if (i += h, h !== 26) + break; + } + return i; + }, f.prototype.byteLength = function() { + return Math.ceil(this.bitLength() / 8); + }, f.prototype.toTwos = function(i) { + return this.negative !== 0 ? this.abs().inotn(i).iaddn(1) : this.clone(); + }, f.prototype.fromTwos = function(i) { + return this.testn(i - 1) ? this.notn(i).iaddn(1).ineg() : this.clone(); + }, f.prototype.isNeg = function() { + return this.negative !== 0; + }, f.prototype.neg = function() { + return this.clone().ineg(); + }, f.prototype.ineg = function() { + return this.isZero() || (this.negative ^= 1), this; + }, f.prototype.iuor = function(i) { + for (;this.length < i.length; ) + this.words[this.length++] = 0; + for (var a = 0;a < i.length; a++) + this.words[a] = this.words[a] | i.words[a]; + return this.strip(); + }, f.prototype.ior = function(i) { + return r((this.negative | i.negative) === 0), this.iuor(i); + }, f.prototype.or = function(i) { + return this.length > i.length ? this.clone().ior(i) : i.clone().ior(this); + }, f.prototype.uor = function(i) { + return this.length > i.length ? this.clone().iuor(i) : i.clone().iuor(this); + }, f.prototype.iuand = function(i) { + var a; + this.length > i.length ? a = i : a = this; + for (var h = 0;h < a.length; h++) + this.words[h] = this.words[h] & i.words[h]; + return this.length = a.length, this.strip(); + }, f.prototype.iand = function(i) { + return r((this.negative | i.negative) === 0), this.iuand(i); + }, f.prototype.and = function(i) { + return this.length > i.length ? this.clone().iand(i) : i.clone().iand(this); + }, f.prototype.uand = function(i) { + return this.length > i.length ? this.clone().iuand(i) : i.clone().iuand(this); + }, f.prototype.iuxor = function(i) { + var a, h; + this.length > i.length ? (a = this, h = i) : (a = i, h = this); + for (var s = 0;s < h.length; s++) + this.words[s] = a.words[s] ^ h.words[s]; + if (this !== a) + for (;s < a.length; s++) + this.words[s] = a.words[s]; + return this.length = a.length, this.strip(); + }, f.prototype.ixor = function(i) { + return r((this.negative | i.negative) === 0), this.iuxor(i); + }, f.prototype.xor = function(i) { + return this.length > i.length ? this.clone().ixor(i) : i.clone().ixor(this); + }, f.prototype.uxor = function(i) { + return this.length > i.length ? this.clone().iuxor(i) : i.clone().iuxor(this); + }, f.prototype.inotn = function(i) { + r(typeof i == "number" && i >= 0); + var a = Math.ceil(i / 26) | 0, h = i % 26; + this._expand(a), h > 0 && a--; + for (var s = 0;s < a; s++) + this.words[s] = ~this.words[s] & 67108863; + return h > 0 && (this.words[s] = ~this.words[s] & 67108863 >> 26 - h), this.strip(); + }, f.prototype.notn = function(i) { + return this.clone().inotn(i); + }, f.prototype.setn = function(i, a) { + r(typeof i == "number" && i >= 0); + var h = i / 26 | 0, s = i % 26; + return this._expand(h + 1), a ? this.words[h] = this.words[h] | 1 << s : this.words[h] = this.words[h] & ~(1 << s), this.strip(); + }, f.prototype.iadd = function(i) { + var a; + if (this.negative !== 0 && i.negative === 0) + return this.negative = 0, a = this.isub(i), this.negative ^= 1, this._normSign(); + if (this.negative === 0 && i.negative !== 0) + return i.negative = 0, a = this.isub(i), i.negative = 1, a._normSign(); + var h, s; + this.length > i.length ? (h = this, s = i) : (h = i, s = this); + for (var u = 0, c = 0;c < s.length; c++) + a = (h.words[c] | 0) + (s.words[c] | 0) + u, this.words[c] = a & 67108863, u = a >>> 26; + for (;u !== 0 && c < h.length; c++) + a = (h.words[c] | 0) + u, this.words[c] = a & 67108863, u = a >>> 26; + if (this.length = h.length, u !== 0) + this.words[this.length] = u, this.length++; + else if (h !== this) + for (;c < h.length; c++) + this.words[c] = h.words[c]; + return this; + }, f.prototype.add = function(i) { + var a; + return i.negative !== 0 && this.negative === 0 ? (i.negative = 0, a = this.sub(i), i.negative ^= 1, a) : i.negative === 0 && this.negative !== 0 ? (this.negative = 0, a = i.sub(this), this.negative = 1, a) : this.length > i.length ? this.clone().iadd(i) : i.clone().iadd(this); + }, f.prototype.isub = function(i) { + if (i.negative !== 0) { + i.negative = 0; + var a = this.iadd(i); + return i.negative = 1, a._normSign(); + } else if (this.negative !== 0) + return this.negative = 0, this.iadd(i), this.negative = 1, this._normSign(); + var h = this.cmp(i); + if (h === 0) + return this.negative = 0, this.length = 1, this.words[0] = 0, this; + var s, u; + h > 0 ? (s = this, u = i) : (s = i, u = this); + for (var c = 0, b = 0;b < u.length; b++) + a = (s.words[b] | 0) - (u.words[b] | 0) + c, c = a >> 26, this.words[b] = a & 67108863; + for (;c !== 0 && b < s.length; b++) + a = (s.words[b] | 0) + c, c = a >> 26, this.words[b] = a & 67108863; + if (c === 0 && b < s.length && s !== this) + for (;b < s.length; b++) + this.words[b] = s.words[b]; + return this.length = Math.max(this.length, b), s !== this && (this.negative = 1), this.strip(); + }, f.prototype.sub = function(i) { + return this.clone().isub(i); + }; + function q(v, i, a) { + a.negative = i.negative ^ v.negative; + var h = v.length + i.length | 0; + a.length = h, h = h - 1 | 0; + var s = v.words[0] | 0, u = i.words[0] | 0, c = s * u, b = c & 67108863, l = c / 67108864 | 0; + a.words[0] = b; + for (var n = 1;n < h; n++) { + for (var d = l >>> 26, w = l & 67108863, g = Math.min(n, i.length - 1), _9 = Math.max(0, n - v.length + 1);_9 <= g; _9++) { + var A = n - _9 | 0; + s = v.words[A] | 0, u = i.words[_9] | 0, c = s * u + w, d += c / 67108864 | 0, w = c & 67108863; + } + a.words[n] = w | 0, l = d | 0; + } + return l !== 0 ? a.words[n] = l | 0 : a.length--, a.strip(); + } + var L = function(i, a, h) { + var s = i.words, u = a.words, c = h.words, b = 0, l, n, d, w = s[0] | 0, g = w & 8191, _9 = w >>> 13, A = s[1] | 0, R = A & 8191, I2 = A >>> 13, Me = s[2] | 0, k2 = Me & 8191, D = Me >>> 13, nt = s[3] | 0, C2 = nt & 8191, O = nt >>> 13, vt = s[4] | 0, F = vt & 8191, U = vt >>> 13, bt = s[5] | 0, z = bt & 8191, H = bt >>> 13, mt = s[6] | 0, W = mt & 8191, K = mt >>> 13, gt = s[7] | 0, j = gt & 8191, Z = gt >>> 13, yt = s[8] | 0, V3 = yt & 8191, $ = yt >>> 13, wt = s[9] | 0, G = wt & 8191, Y = wt >>> 13, Mt = u[0] | 0, X = Mt & 8191, J2 = Mt >>> 13, _t = u[1] | 0, Q = _t & 8191, ee = _t >>> 13, xt2 = u[2] | 0, te2 = xt2 & 8191, re = xt2 >>> 13, St = u[3] | 0, ie = St & 8191, ne = St >>> 13, Et2 = u[4] | 0, fe = Et2 & 8191, ae2 = Et2 >>> 13, At2 = u[5] | 0, oe = At2 & 8191, se2 = At2 >>> 13, Rt = u[6] | 0, he = Rt & 8191, ue2 = Rt >>> 13, Bt = u[7] | 0, le = Bt & 8191, de = Bt >>> 13, qt = u[8] | 0, ce2 = qt & 8191, pe2 = qt >>> 13, It = u[9] | 0, ve = It & 8191, be = It >>> 13; + h.negative = i.negative ^ a.negative, h.length = 19, l = Math.imul(g, X), n = Math.imul(g, J2), n = n + Math.imul(_9, X) | 0, d = Math.imul(_9, J2); + var ft = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (ft >>> 26) | 0, ft &= 67108863, l = Math.imul(R, X), n = Math.imul(R, J2), n = n + Math.imul(I2, X) | 0, d = Math.imul(I2, J2), l = l + Math.imul(g, Q) | 0, n = n + Math.imul(g, ee) | 0, n = n + Math.imul(_9, Q) | 0, d = d + Math.imul(_9, ee) | 0; + var Be = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Be >>> 26) | 0, Be &= 67108863, l = Math.imul(k2, X), n = Math.imul(k2, J2), n = n + Math.imul(D, X) | 0, d = Math.imul(D, J2), l = l + Math.imul(R, Q) | 0, n = n + Math.imul(R, ee) | 0, n = n + Math.imul(I2, Q) | 0, d = d + Math.imul(I2, ee) | 0, l = l + Math.imul(g, te2) | 0, n = n + Math.imul(g, re) | 0, n = n + Math.imul(_9, te2) | 0, d = d + Math.imul(_9, re) | 0; + var qe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (qe >>> 26) | 0, qe &= 67108863, l = Math.imul(C2, X), n = Math.imul(C2, J2), n = n + Math.imul(O, X) | 0, d = Math.imul(O, J2), l = l + Math.imul(k2, Q) | 0, n = n + Math.imul(k2, ee) | 0, n = n + Math.imul(D, Q) | 0, d = d + Math.imul(D, ee) | 0, l = l + Math.imul(R, te2) | 0, n = n + Math.imul(R, re) | 0, n = n + Math.imul(I2, te2) | 0, d = d + Math.imul(I2, re) | 0, l = l + Math.imul(g, ie) | 0, n = n + Math.imul(g, ne) | 0, n = n + Math.imul(_9, ie) | 0, d = d + Math.imul(_9, ne) | 0; + var ze = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (ze >>> 26) | 0, ze &= 67108863, l = Math.imul(F, X), n = Math.imul(F, J2), n = n + Math.imul(U, X) | 0, d = Math.imul(U, J2), l = l + Math.imul(C2, Q) | 0, n = n + Math.imul(C2, ee) | 0, n = n + Math.imul(O, Q) | 0, d = d + Math.imul(O, ee) | 0, l = l + Math.imul(k2, te2) | 0, n = n + Math.imul(k2, re) | 0, n = n + Math.imul(D, te2) | 0, d = d + Math.imul(D, re) | 0, l = l + Math.imul(R, ie) | 0, n = n + Math.imul(R, ne) | 0, n = n + Math.imul(I2, ie) | 0, d = d + Math.imul(I2, ne) | 0, l = l + Math.imul(g, fe) | 0, n = n + Math.imul(g, ae2) | 0, n = n + Math.imul(_9, fe) | 0, d = d + Math.imul(_9, ae2) | 0; + var He2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (He2 >>> 26) | 0, He2 &= 67108863, l = Math.imul(z, X), n = Math.imul(z, J2), n = n + Math.imul(H, X) | 0, d = Math.imul(H, J2), l = l + Math.imul(F, Q) | 0, n = n + Math.imul(F, ee) | 0, n = n + Math.imul(U, Q) | 0, d = d + Math.imul(U, ee) | 0, l = l + Math.imul(C2, te2) | 0, n = n + Math.imul(C2, re) | 0, n = n + Math.imul(O, te2) | 0, d = d + Math.imul(O, re) | 0, l = l + Math.imul(k2, ie) | 0, n = n + Math.imul(k2, ne) | 0, n = n + Math.imul(D, ie) | 0, d = d + Math.imul(D, ne) | 0, l = l + Math.imul(R, fe) | 0, n = n + Math.imul(R, ae2) | 0, n = n + Math.imul(I2, fe) | 0, d = d + Math.imul(I2, ae2) | 0, l = l + Math.imul(g, oe) | 0, n = n + Math.imul(g, se2) | 0, n = n + Math.imul(_9, oe) | 0, d = d + Math.imul(_9, se2) | 0; + var We = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (We >>> 26) | 0, We &= 67108863, l = Math.imul(W, X), n = Math.imul(W, J2), n = n + Math.imul(K, X) | 0, d = Math.imul(K, J2), l = l + Math.imul(z, Q) | 0, n = n + Math.imul(z, ee) | 0, n = n + Math.imul(H, Q) | 0, d = d + Math.imul(H, ee) | 0, l = l + Math.imul(F, te2) | 0, n = n + Math.imul(F, re) | 0, n = n + Math.imul(U, te2) | 0, d = d + Math.imul(U, re) | 0, l = l + Math.imul(C2, ie) | 0, n = n + Math.imul(C2, ne) | 0, n = n + Math.imul(O, ie) | 0, d = d + Math.imul(O, ne) | 0, l = l + Math.imul(k2, fe) | 0, n = n + Math.imul(k2, ae2) | 0, n = n + Math.imul(D, fe) | 0, d = d + Math.imul(D, ae2) | 0, l = l + Math.imul(R, oe) | 0, n = n + Math.imul(R, se2) | 0, n = n + Math.imul(I2, oe) | 0, d = d + Math.imul(I2, se2) | 0, l = l + Math.imul(g, he) | 0, n = n + Math.imul(g, ue2) | 0, n = n + Math.imul(_9, he) | 0, d = d + Math.imul(_9, ue2) | 0; + var Ke2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ke2 >>> 26) | 0, Ke2 &= 67108863, l = Math.imul(j, X), n = Math.imul(j, J2), n = n + Math.imul(Z, X) | 0, d = Math.imul(Z, J2), l = l + Math.imul(W, Q) | 0, n = n + Math.imul(W, ee) | 0, n = n + Math.imul(K, Q) | 0, d = d + Math.imul(K, ee) | 0, l = l + Math.imul(z, te2) | 0, n = n + Math.imul(z, re) | 0, n = n + Math.imul(H, te2) | 0, d = d + Math.imul(H, re) | 0, l = l + Math.imul(F, ie) | 0, n = n + Math.imul(F, ne) | 0, n = n + Math.imul(U, ie) | 0, d = d + Math.imul(U, ne) | 0, l = l + Math.imul(C2, fe) | 0, n = n + Math.imul(C2, ae2) | 0, n = n + Math.imul(O, fe) | 0, d = d + Math.imul(O, ae2) | 0, l = l + Math.imul(k2, oe) | 0, n = n + Math.imul(k2, se2) | 0, n = n + Math.imul(D, oe) | 0, d = d + Math.imul(D, se2) | 0, l = l + Math.imul(R, he) | 0, n = n + Math.imul(R, ue2) | 0, n = n + Math.imul(I2, he) | 0, d = d + Math.imul(I2, ue2) | 0, l = l + Math.imul(g, le) | 0, n = n + Math.imul(g, de) | 0, n = n + Math.imul(_9, le) | 0, d = d + Math.imul(_9, de) | 0; + var je = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (je >>> 26) | 0, je &= 67108863, l = Math.imul(V3, X), n = Math.imul(V3, J2), n = n + Math.imul($, X) | 0, d = Math.imul($, J2), l = l + Math.imul(j, Q) | 0, n = n + Math.imul(j, ee) | 0, n = n + Math.imul(Z, Q) | 0, d = d + Math.imul(Z, ee) | 0, l = l + Math.imul(W, te2) | 0, n = n + Math.imul(W, re) | 0, n = n + Math.imul(K, te2) | 0, d = d + Math.imul(K, re) | 0, l = l + Math.imul(z, ie) | 0, n = n + Math.imul(z, ne) | 0, n = n + Math.imul(H, ie) | 0, d = d + Math.imul(H, ne) | 0, l = l + Math.imul(F, fe) | 0, n = n + Math.imul(F, ae2) | 0, n = n + Math.imul(U, fe) | 0, d = d + Math.imul(U, ae2) | 0, l = l + Math.imul(C2, oe) | 0, n = n + Math.imul(C2, se2) | 0, n = n + Math.imul(O, oe) | 0, d = d + Math.imul(O, se2) | 0, l = l + Math.imul(k2, he) | 0, n = n + Math.imul(k2, ue2) | 0, n = n + Math.imul(D, he) | 0, d = d + Math.imul(D, ue2) | 0, l = l + Math.imul(R, le) | 0, n = n + Math.imul(R, de) | 0, n = n + Math.imul(I2, le) | 0, d = d + Math.imul(I2, de) | 0, l = l + Math.imul(g, ce2) | 0, n = n + Math.imul(g, pe2) | 0, n = n + Math.imul(_9, ce2) | 0, d = d + Math.imul(_9, pe2) | 0; + var Ze2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ze2 >>> 26) | 0, Ze2 &= 67108863, l = Math.imul(G, X), n = Math.imul(G, J2), n = n + Math.imul(Y, X) | 0, d = Math.imul(Y, J2), l = l + Math.imul(V3, Q) | 0, n = n + Math.imul(V3, ee) | 0, n = n + Math.imul($, Q) | 0, d = d + Math.imul($, ee) | 0, l = l + Math.imul(j, te2) | 0, n = n + Math.imul(j, re) | 0, n = n + Math.imul(Z, te2) | 0, d = d + Math.imul(Z, re) | 0, l = l + Math.imul(W, ie) | 0, n = n + Math.imul(W, ne) | 0, n = n + Math.imul(K, ie) | 0, d = d + Math.imul(K, ne) | 0, l = l + Math.imul(z, fe) | 0, n = n + Math.imul(z, ae2) | 0, n = n + Math.imul(H, fe) | 0, d = d + Math.imul(H, ae2) | 0, l = l + Math.imul(F, oe) | 0, n = n + Math.imul(F, se2) | 0, n = n + Math.imul(U, oe) | 0, d = d + Math.imul(U, se2) | 0, l = l + Math.imul(C2, he) | 0, n = n + Math.imul(C2, ue2) | 0, n = n + Math.imul(O, he) | 0, d = d + Math.imul(O, ue2) | 0, l = l + Math.imul(k2, le) | 0, n = n + Math.imul(k2, de) | 0, n = n + Math.imul(D, le) | 0, d = d + Math.imul(D, de) | 0, l = l + Math.imul(R, ce2) | 0, n = n + Math.imul(R, pe2) | 0, n = n + Math.imul(I2, ce2) | 0, d = d + Math.imul(I2, pe2) | 0, l = l + Math.imul(g, ve) | 0, n = n + Math.imul(g, be) | 0, n = n + Math.imul(_9, ve) | 0, d = d + Math.imul(_9, be) | 0; + var Ve = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ve >>> 26) | 0, Ve &= 67108863, l = Math.imul(G, Q), n = Math.imul(G, ee), n = n + Math.imul(Y, Q) | 0, d = Math.imul(Y, ee), l = l + Math.imul(V3, te2) | 0, n = n + Math.imul(V3, re) | 0, n = n + Math.imul($, te2) | 0, d = d + Math.imul($, re) | 0, l = l + Math.imul(j, ie) | 0, n = n + Math.imul(j, ne) | 0, n = n + Math.imul(Z, ie) | 0, d = d + Math.imul(Z, ne) | 0, l = l + Math.imul(W, fe) | 0, n = n + Math.imul(W, ae2) | 0, n = n + Math.imul(K, fe) | 0, d = d + Math.imul(K, ae2) | 0, l = l + Math.imul(z, oe) | 0, n = n + Math.imul(z, se2) | 0, n = n + Math.imul(H, oe) | 0, d = d + Math.imul(H, se2) | 0, l = l + Math.imul(F, he) | 0, n = n + Math.imul(F, ue2) | 0, n = n + Math.imul(U, he) | 0, d = d + Math.imul(U, ue2) | 0, l = l + Math.imul(C2, le) | 0, n = n + Math.imul(C2, de) | 0, n = n + Math.imul(O, le) | 0, d = d + Math.imul(O, de) | 0, l = l + Math.imul(k2, ce2) | 0, n = n + Math.imul(k2, pe2) | 0, n = n + Math.imul(D, ce2) | 0, d = d + Math.imul(D, pe2) | 0, l = l + Math.imul(R, ve) | 0, n = n + Math.imul(R, be) | 0, n = n + Math.imul(I2, ve) | 0, d = d + Math.imul(I2, be) | 0; + var $e = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + ($e >>> 26) | 0, $e &= 67108863, l = Math.imul(G, te2), n = Math.imul(G, re), n = n + Math.imul(Y, te2) | 0, d = Math.imul(Y, re), l = l + Math.imul(V3, ie) | 0, n = n + Math.imul(V3, ne) | 0, n = n + Math.imul($, ie) | 0, d = d + Math.imul($, ne) | 0, l = l + Math.imul(j, fe) | 0, n = n + Math.imul(j, ae2) | 0, n = n + Math.imul(Z, fe) | 0, d = d + Math.imul(Z, ae2) | 0, l = l + Math.imul(W, oe) | 0, n = n + Math.imul(W, se2) | 0, n = n + Math.imul(K, oe) | 0, d = d + Math.imul(K, se2) | 0, l = l + Math.imul(z, he) | 0, n = n + Math.imul(z, ue2) | 0, n = n + Math.imul(H, he) | 0, d = d + Math.imul(H, ue2) | 0, l = l + Math.imul(F, le) | 0, n = n + Math.imul(F, de) | 0, n = n + Math.imul(U, le) | 0, d = d + Math.imul(U, de) | 0, l = l + Math.imul(C2, ce2) | 0, n = n + Math.imul(C2, pe2) | 0, n = n + Math.imul(O, ce2) | 0, d = d + Math.imul(O, pe2) | 0, l = l + Math.imul(k2, ve) | 0, n = n + Math.imul(k2, be) | 0, n = n + Math.imul(D, ve) | 0, d = d + Math.imul(D, be) | 0; + var Ge = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ge >>> 26) | 0, Ge &= 67108863, l = Math.imul(G, ie), n = Math.imul(G, ne), n = n + Math.imul(Y, ie) | 0, d = Math.imul(Y, ne), l = l + Math.imul(V3, fe) | 0, n = n + Math.imul(V3, ae2) | 0, n = n + Math.imul($, fe) | 0, d = d + Math.imul($, ae2) | 0, l = l + Math.imul(j, oe) | 0, n = n + Math.imul(j, se2) | 0, n = n + Math.imul(Z, oe) | 0, d = d + Math.imul(Z, se2) | 0, l = l + Math.imul(W, he) | 0, n = n + Math.imul(W, ue2) | 0, n = n + Math.imul(K, he) | 0, d = d + Math.imul(K, ue2) | 0, l = l + Math.imul(z, le) | 0, n = n + Math.imul(z, de) | 0, n = n + Math.imul(H, le) | 0, d = d + Math.imul(H, de) | 0, l = l + Math.imul(F, ce2) | 0, n = n + Math.imul(F, pe2) | 0, n = n + Math.imul(U, ce2) | 0, d = d + Math.imul(U, pe2) | 0, l = l + Math.imul(C2, ve) | 0, n = n + Math.imul(C2, be) | 0, n = n + Math.imul(O, ve) | 0, d = d + Math.imul(O, be) | 0; + var Ye = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Ye >>> 26) | 0, Ye &= 67108863, l = Math.imul(G, fe), n = Math.imul(G, ae2), n = n + Math.imul(Y, fe) | 0, d = Math.imul(Y, ae2), l = l + Math.imul(V3, oe) | 0, n = n + Math.imul(V3, se2) | 0, n = n + Math.imul($, oe) | 0, d = d + Math.imul($, se2) | 0, l = l + Math.imul(j, he) | 0, n = n + Math.imul(j, ue2) | 0, n = n + Math.imul(Z, he) | 0, d = d + Math.imul(Z, ue2) | 0, l = l + Math.imul(W, le) | 0, n = n + Math.imul(W, de) | 0, n = n + Math.imul(K, le) | 0, d = d + Math.imul(K, de) | 0, l = l + Math.imul(z, ce2) | 0, n = n + Math.imul(z, pe2) | 0, n = n + Math.imul(H, ce2) | 0, d = d + Math.imul(H, pe2) | 0, l = l + Math.imul(F, ve) | 0, n = n + Math.imul(F, be) | 0, n = n + Math.imul(U, ve) | 0, d = d + Math.imul(U, be) | 0; + var Xe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Xe >>> 26) | 0, Xe &= 67108863, l = Math.imul(G, oe), n = Math.imul(G, se2), n = n + Math.imul(Y, oe) | 0, d = Math.imul(Y, se2), l = l + Math.imul(V3, he) | 0, n = n + Math.imul(V3, ue2) | 0, n = n + Math.imul($, he) | 0, d = d + Math.imul($, ue2) | 0, l = l + Math.imul(j, le) | 0, n = n + Math.imul(j, de) | 0, n = n + Math.imul(Z, le) | 0, d = d + Math.imul(Z, de) | 0, l = l + Math.imul(W, ce2) | 0, n = n + Math.imul(W, pe2) | 0, n = n + Math.imul(K, ce2) | 0, d = d + Math.imul(K, pe2) | 0, l = l + Math.imul(z, ve) | 0, n = n + Math.imul(z, be) | 0, n = n + Math.imul(H, ve) | 0, d = d + Math.imul(H, be) | 0; + var Je = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Je >>> 26) | 0, Je &= 67108863, l = Math.imul(G, he), n = Math.imul(G, ue2), n = n + Math.imul(Y, he) | 0, d = Math.imul(Y, ue2), l = l + Math.imul(V3, le) | 0, n = n + Math.imul(V3, de) | 0, n = n + Math.imul($, le) | 0, d = d + Math.imul($, de) | 0, l = l + Math.imul(j, ce2) | 0, n = n + Math.imul(j, pe2) | 0, n = n + Math.imul(Z, ce2) | 0, d = d + Math.imul(Z, pe2) | 0, l = l + Math.imul(W, ve) | 0, n = n + Math.imul(W, be) | 0, n = n + Math.imul(K, ve) | 0, d = d + Math.imul(K, be) | 0; + var Qe = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (Qe >>> 26) | 0, Qe &= 67108863, l = Math.imul(G, le), n = Math.imul(G, de), n = n + Math.imul(Y, le) | 0, d = Math.imul(Y, de), l = l + Math.imul(V3, ce2) | 0, n = n + Math.imul(V3, pe2) | 0, n = n + Math.imul($, ce2) | 0, d = d + Math.imul($, pe2) | 0, l = l + Math.imul(j, ve) | 0, n = n + Math.imul(j, be) | 0, n = n + Math.imul(Z, ve) | 0, d = d + Math.imul(Z, be) | 0; + var et2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (et2 >>> 26) | 0, et2 &= 67108863, l = Math.imul(G, ce2), n = Math.imul(G, pe2), n = n + Math.imul(Y, ce2) | 0, d = Math.imul(Y, pe2), l = l + Math.imul(V3, ve) | 0, n = n + Math.imul(V3, be) | 0, n = n + Math.imul($, ve) | 0, d = d + Math.imul($, be) | 0; + var tt2 = (b + l | 0) + ((n & 8191) << 13) | 0; + b = (d + (n >>> 13) | 0) + (tt2 >>> 26) | 0, tt2 &= 67108863, l = Math.imul(G, ve), n = Math.imul(G, be), n = n + Math.imul(Y, ve) | 0, d = Math.imul(Y, be); + var rt2 = (b + l | 0) + ((n & 8191) << 13) | 0; + return b = (d + (n >>> 13) | 0) + (rt2 >>> 26) | 0, rt2 &= 67108863, c[0] = ft, c[1] = Be, c[2] = qe, c[3] = ze, c[4] = He2, c[5] = We, c[6] = Ke2, c[7] = je, c[8] = Ze2, c[9] = Ve, c[10] = $e, c[11] = Ge, c[12] = Ye, c[13] = Xe, c[14] = Je, c[15] = Qe, c[16] = et2, c[17] = tt2, c[18] = rt2, b !== 0 && (c[19] = b, h.length++), h; + }; + Math.imul || (L = q); + function ge(v, i, a) { + a.negative = i.negative ^ v.negative, a.length = v.length + i.length; + for (var h = 0, s = 0, u = 0;u < a.length - 1; u++) { + var c = s; + s = 0; + for (var b = h & 67108863, l = Math.min(u, i.length - 1), n = Math.max(0, u - v.length + 1);n <= l; n++) { + var d = u - n, w = v.words[d] | 0, g = i.words[n] | 0, _9 = w * g, A = _9 & 67108863; + c = c + (_9 / 67108864 | 0) | 0, A = A + b | 0, b = A & 67108863, c = c + (A >>> 26) | 0, s += c >>> 26, c &= 67108863; + } + a.words[u] = b, h = c, c = s; + } + return h !== 0 ? a.words[u] = h : a.length--, a.strip(); + } + function _e(v, i, a) { + var h = new N; + return h.mulp(v, i, a); + } + f.prototype.mulTo = function(i, a) { + var h, s = this.length + i.length; + return this.length === 10 && i.length === 10 ? h = L(this, i, a) : s < 63 ? h = q(this, i, a) : s < 1024 ? h = ge(this, i, a) : h = _e(this, i, a), h; + }; + function N(v, i) { + this.x = v, this.y = i; + } + N.prototype.makeRBT = function(i) { + for (var a = new Array(i), h = f.prototype._countBits(i) - 1, s = 0;s < i; s++) + a[s] = this.revBin(s, h, i); + return a; + }, N.prototype.revBin = function(i, a, h) { + if (i === 0 || i === h - 1) + return i; + for (var s = 0, u = 0;u < a; u++) + s |= (i & 1) << a - u - 1, i >>= 1; + return s; + }, N.prototype.permute = function(i, a, h, s, u, c) { + for (var b = 0;b < c; b++) + s[b] = a[i[b]], u[b] = h[i[b]]; + }, N.prototype.transform = function(i, a, h, s, u, c) { + this.permute(c, i, a, h, s, u); + for (var b = 1;b < u; b <<= 1) + for (var l = b << 1, n = Math.cos(2 * Math.PI / l), d = Math.sin(2 * Math.PI / l), w = 0;w < u; w += l) + for (var g = n, _9 = d, A = 0;A < b; A++) { + var R = h[w + A], I2 = s[w + A], Me = h[w + A + b], k2 = s[w + A + b], D = g * Me - _9 * k2; + k2 = g * k2 + _9 * Me, Me = D, h[w + A] = R + Me, s[w + A] = I2 + k2, h[w + A + b] = R - Me, s[w + A + b] = I2 - k2, A !== l && (D = n * g - d * _9, _9 = n * _9 + d * g, g = D); + } + }, N.prototype.guessLen13b = function(i, a) { + var h = Math.max(a, i) | 1, s = h & 1, u = 0; + for (h = h / 2 | 0;h; h = h >>> 1) + u++; + return 1 << u + 1 + s; + }, N.prototype.conjugate = function(i, a, h) { + if (!(h <= 1)) + for (var s = 0;s < h / 2; s++) { + var u = i[s]; + i[s] = i[h - s - 1], i[h - s - 1] = u, u = a[s], a[s] = -a[h - s - 1], a[h - s - 1] = -u; + } + }, N.prototype.normalize13b = function(i, a) { + for (var h = 0, s = 0;s < a / 2; s++) { + var u = Math.round(i[2 * s + 1] / a) * 8192 + Math.round(i[2 * s] / a) + h; + i[s] = u & 67108863, u < 67108864 ? h = 0 : h = u / 67108864 | 0; + } + return i; + }, N.prototype.convert13b = function(i, a, h, s) { + for (var u = 0, c = 0;c < a; c++) + u = u + (i[c] | 0), h[2 * c] = u & 8191, u = u >>> 13, h[2 * c + 1] = u & 8191, u = u >>> 13; + for (c = 2 * a;c < s; ++c) + h[c] = 0; + r(u === 0), r((u & -8192) === 0); + }, N.prototype.stub = function(i) { + for (var a = new Array(i), h = 0;h < i; h++) + a[h] = 0; + return a; + }, N.prototype.mulp = function(i, a, h) { + var s = 2 * this.guessLen13b(i.length, a.length), u = this.makeRBT(s), c = this.stub(s), b = new Array(s), l = new Array(s), n = new Array(s), d = new Array(s), w = new Array(s), g = new Array(s), _9 = h.words; + _9.length = s, this.convert13b(i.words, i.length, b, s), this.convert13b(a.words, a.length, d, s), this.transform(b, c, l, n, s, u), this.transform(d, c, w, g, s, u); + for (var A = 0;A < s; A++) { + var R = l[A] * w[A] - n[A] * g[A]; + n[A] = l[A] * g[A] + n[A] * w[A], l[A] = R; + } + return this.conjugate(l, n, s), this.transform(l, n, _9, c, s, u), this.conjugate(_9, c, s), this.normalize13b(_9, s), h.negative = i.negative ^ a.negative, h.length = i.length + a.length, h.strip(); + }, f.prototype.mul = function(i) { + var a = new f(null); + return a.words = new Array(this.length + i.length), this.mulTo(i, a); + }, f.prototype.mulf = function(i) { + var a = new f(null); + return a.words = new Array(this.length + i.length), _e(this, i, a); + }, f.prototype.imul = function(i) { + return this.clone().mulTo(i, this); + }, f.prototype.imuln = function(i) { + r(typeof i == "number"), r(i < 67108864); + for (var a = 0, h = 0;h < this.length; h++) { + var s = (this.words[h] | 0) * i, u = (s & 67108863) + (a & 67108863); + a >>= 26, a += s / 67108864 | 0, a += u >>> 26, this.words[h] = u & 67108863; + } + return a !== 0 && (this.words[h] = a, this.length++), this; + }, f.prototype.muln = function(i) { + return this.clone().imuln(i); + }, f.prototype.sqr = function() { + return this.mul(this); + }, f.prototype.isqr = function() { + return this.imul(this.clone()); + }, f.prototype.pow = function(i) { + var a = B(i); + if (a.length === 0) + return new f(1); + for (var h = this, s = 0;s < a.length && a[s] === 0; s++, h = h.sqr()) + ; + if (++s < a.length) + for (var u = h.sqr();s < a.length; s++, u = u.sqr()) + a[s] !== 0 && (h = h.mul(u)); + return h; + }, f.prototype.iushln = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26, s = 67108863 >>> 26 - a << 26 - a, u; + if (a !== 0) { + var c = 0; + for (u = 0;u < this.length; u++) { + var b = this.words[u] & s, l = (this.words[u] | 0) - b << a; + this.words[u] = l | c, c = b >>> 26 - a; + } + c && (this.words[u] = c, this.length++); + } + if (h !== 0) { + for (u = this.length - 1;u >= 0; u--) + this.words[u + h] = this.words[u]; + for (u = 0;u < h; u++) + this.words[u] = 0; + this.length += h; + } + return this.strip(); + }, f.prototype.ishln = function(i) { + return r(this.negative === 0), this.iushln(i); + }, f.prototype.iushrn = function(i, a, h) { + r(typeof i == "number" && i >= 0); + var s; + a ? s = (a - a % 26) / 26 : s = 0; + var u = i % 26, c = Math.min((i - u) / 26, this.length), b = 67108863 ^ 67108863 >>> u << u, l = h; + if (s -= c, s = Math.max(0, s), l) { + for (var n = 0;n < c; n++) + l.words[n] = this.words[n]; + l.length = c; + } + if (c !== 0) + if (this.length > c) + for (this.length -= c, n = 0;n < this.length; n++) + this.words[n] = this.words[n + c]; + else + this.words[0] = 0, this.length = 1; + var d = 0; + for (n = this.length - 1;n >= 0 && (d !== 0 || n >= s); n--) { + var w = this.words[n] | 0; + this.words[n] = d << 26 - u | w >>> u, d = w & b; + } + return l && d !== 0 && (l.words[l.length++] = d), this.length === 0 && (this.words[0] = 0, this.length = 1), this.strip(); + }, f.prototype.ishrn = function(i, a, h) { + return r(this.negative === 0), this.iushrn(i, a, h); + }, f.prototype.shln = function(i) { + return this.clone().ishln(i); + }, f.prototype.ushln = function(i) { + return this.clone().iushln(i); + }, f.prototype.shrn = function(i) { + return this.clone().ishrn(i); + }, f.prototype.ushrn = function(i) { + return this.clone().iushrn(i); + }, f.prototype.testn = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26, s = 1 << a; + if (this.length <= h) + return false; + var u = this.words[h]; + return !!(u & s); + }, f.prototype.imaskn = function(i) { + r(typeof i == "number" && i >= 0); + var a = i % 26, h = (i - a) / 26; + if (r(this.negative === 0, "imaskn works only with positive numbers"), this.length <= h) + return this; + if (a !== 0 && h++, this.length = Math.min(h, this.length), a !== 0) { + var s = 67108863 ^ 67108863 >>> a << a; + this.words[this.length - 1] &= s; + } + return this.strip(); + }, f.prototype.maskn = function(i) { + return this.clone().imaskn(i); + }, f.prototype.iaddn = function(i) { + return r(typeof i == "number"), r(i < 67108864), i < 0 ? this.isubn(-i) : this.negative !== 0 ? this.length === 1 && (this.words[0] | 0) < i ? (this.words[0] = i - (this.words[0] | 0), this.negative = 0, this) : (this.negative = 0, this.isubn(i), this.negative = 1, this) : this._iaddn(i); + }, f.prototype._iaddn = function(i) { + this.words[0] += i; + for (var a = 0;a < this.length && this.words[a] >= 67108864; a++) + this.words[a] -= 67108864, a === this.length - 1 ? this.words[a + 1] = 1 : this.words[a + 1]++; + return this.length = Math.max(this.length, a + 1), this; + }, f.prototype.isubn = function(i) { + if (r(typeof i == "number"), r(i < 67108864), i < 0) + return this.iaddn(-i); + if (this.negative !== 0) + return this.negative = 0, this.iaddn(i), this.negative = 1, this; + if (this.words[0] -= i, this.length === 1 && this.words[0] < 0) + this.words[0] = -this.words[0], this.negative = 1; + else + for (var a = 0;a < this.length && this.words[a] < 0; a++) + this.words[a] += 67108864, this.words[a + 1] -= 1; + return this.strip(); + }, f.prototype.addn = function(i) { + return this.clone().iaddn(i); + }, f.prototype.subn = function(i) { + return this.clone().isubn(i); + }, f.prototype.iabs = function() { + return this.negative = 0, this; + }, f.prototype.abs = function() { + return this.clone().iabs(); + }, f.prototype._ishlnsubmul = function(i, a, h) { + var s = i.length + h, u; + this._expand(s); + var c, b = 0; + for (u = 0;u < i.length; u++) { + c = (this.words[u + h] | 0) + b; + var l = (i.words[u] | 0) * a; + c -= l & 67108863, b = (c >> 26) - (l / 67108864 | 0), this.words[u + h] = c & 67108863; + } + for (;u < this.length - h; u++) + c = (this.words[u + h] | 0) + b, b = c >> 26, this.words[u + h] = c & 67108863; + if (b === 0) + return this.strip(); + for (r(b === -1), b = 0, u = 0;u < this.length; u++) + c = -(this.words[u] | 0) + b, b = c >> 26, this.words[u] = c & 67108863; + return this.negative = 1, this.strip(); + }, f.prototype._wordDiv = function(i, a) { + var h = this.length - i.length, s = this.clone(), u = i, c = u.words[u.length - 1] | 0, b = this._countBits(c); + h = 26 - b, h !== 0 && (u = u.ushln(h), s.iushln(h), c = u.words[u.length - 1] | 0); + var l = s.length - u.length, n; + if (a !== "mod") { + n = new f(null), n.length = l + 1, n.words = new Array(n.length); + for (var d = 0;d < n.length; d++) + n.words[d] = 0; + } + var w = s.clone()._ishlnsubmul(u, 1, l); + w.negative === 0 && (s = w, n && (n.words[l] = 1)); + for (var g = l - 1;g >= 0; g--) { + var _9 = (s.words[u.length + g] | 0) * 67108864 + (s.words[u.length + g - 1] | 0); + for (_9 = Math.min(_9 / c | 0, 67108863), s._ishlnsubmul(u, _9, g);s.negative !== 0; ) + _9--, s.negative = 0, s._ishlnsubmul(u, 1, g), s.isZero() || (s.negative ^= 1); + n && (n.words[g] = _9); + } + return n && n.strip(), s.strip(), a !== "div" && h !== 0 && s.iushrn(h), { div: n || null, mod: s }; + }, f.prototype.divmod = function(i, a, h) { + if (r(!i.isZero()), this.isZero()) + return { div: new f(0), mod: new f(0) }; + var s, u, c; + return this.negative !== 0 && i.negative === 0 ? (c = this.neg().divmod(i, a), a !== "mod" && (s = c.div.neg()), a !== "div" && (u = c.mod.neg(), h && u.negative !== 0 && u.iadd(i)), { div: s, mod: u }) : this.negative === 0 && i.negative !== 0 ? (c = this.divmod(i.neg(), a), a !== "mod" && (s = c.div.neg()), { div: s, mod: c.mod }) : (this.negative & i.negative) !== 0 ? (c = this.neg().divmod(i.neg(), a), a !== "div" && (u = c.mod.neg(), h && u.negative !== 0 && u.isub(i)), { div: c.div, mod: u }) : i.length > this.length || this.cmp(i) < 0 ? { div: new f(0), mod: this } : i.length === 1 ? a === "div" ? { div: this.divn(i.words[0]), mod: null } : a === "mod" ? { div: null, mod: new f(this.modn(i.words[0])) } : { div: this.divn(i.words[0]), mod: new f(this.modn(i.words[0])) } : this._wordDiv(i, a); + }, f.prototype.div = function(i) { + return this.divmod(i, "div", false).div; + }, f.prototype.mod = function(i) { + return this.divmod(i, "mod", false).mod; + }, f.prototype.umod = function(i) { + return this.divmod(i, "mod", true).mod; + }, f.prototype.divRound = function(i) { + var a = this.divmod(i); + if (a.mod.isZero()) + return a.div; + var h = a.div.negative !== 0 ? a.mod.isub(i) : a.mod, s = i.ushrn(1), u = i.andln(1), c = h.cmp(s); + return c < 0 || u === 1 && c === 0 ? a.div : a.div.negative !== 0 ? a.div.isubn(1) : a.div.iaddn(1); + }, f.prototype.modn = function(i) { + r(i <= 67108863); + for (var a = (1 << 26) % i, h = 0, s = this.length - 1;s >= 0; s--) + h = (a * h + (this.words[s] | 0)) % i; + return h; + }, f.prototype.idivn = function(i) { + r(i <= 67108863); + for (var a = 0, h = this.length - 1;h >= 0; h--) { + var s = (this.words[h] | 0) + a * 67108864; + this.words[h] = s / i | 0, a = s % i; + } + return this.strip(); + }, f.prototype.divn = function(i) { + return this.clone().idivn(i); + }, f.prototype.egcd = function(i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, h = i.clone(); + a.negative !== 0 ? a = a.umod(i) : a = a.clone(); + for (var s = new f(1), u = new f(0), c = new f(0), b = new f(1), l = 0;a.isEven() && h.isEven(); ) + a.iushrn(1), h.iushrn(1), ++l; + for (var n = h.clone(), d = a.clone();!a.isZero(); ) { + for (var w = 0, g = 1;(a.words[0] & g) === 0 && w < 26; ++w, g <<= 1) + ; + if (w > 0) + for (a.iushrn(w);w-- > 0; ) + (s.isOdd() || u.isOdd()) && (s.iadd(n), u.isub(d)), s.iushrn(1), u.iushrn(1); + for (var _9 = 0, A = 1;(h.words[0] & A) === 0 && _9 < 26; ++_9, A <<= 1) + ; + if (_9 > 0) + for (h.iushrn(_9);_9-- > 0; ) + (c.isOdd() || b.isOdd()) && (c.iadd(n), b.isub(d)), c.iushrn(1), b.iushrn(1); + a.cmp(h) >= 0 ? (a.isub(h), s.isub(c), u.isub(b)) : (h.isub(a), c.isub(s), b.isub(u)); + } + return { a: c, b, gcd: h.iushln(l) }; + }, f.prototype._invmp = function(i) { + r(i.negative === 0), r(!i.isZero()); + var a = this, h = i.clone(); + a.negative !== 0 ? a = a.umod(i) : a = a.clone(); + for (var s = new f(1), u = new f(0), c = h.clone();a.cmpn(1) > 0 && h.cmpn(1) > 0; ) { + for (var b = 0, l = 1;(a.words[0] & l) === 0 && b < 26; ++b, l <<= 1) + ; + if (b > 0) + for (a.iushrn(b);b-- > 0; ) + s.isOdd() && s.iadd(c), s.iushrn(1); + for (var n = 0, d = 1;(h.words[0] & d) === 0 && n < 26; ++n, d <<= 1) + ; + if (n > 0) + for (h.iushrn(n);n-- > 0; ) + u.isOdd() && u.iadd(c), u.iushrn(1); + a.cmp(h) >= 0 ? (a.isub(h), s.isub(u)) : (h.isub(a), u.isub(s)); + } + var w; + return a.cmpn(1) === 0 ? w = s : w = u, w.cmpn(0) < 0 && w.iadd(i), w; + }, f.prototype.gcd = function(i) { + if (this.isZero()) + return i.abs(); + if (i.isZero()) + return this.abs(); + var a = this.clone(), h = i.clone(); + a.negative = 0, h.negative = 0; + for (var s = 0;a.isEven() && h.isEven(); s++) + a.iushrn(1), h.iushrn(1); + do { + for (;a.isEven(); ) + a.iushrn(1); + for (;h.isEven(); ) + h.iushrn(1); + var u = a.cmp(h); + if (u < 0) { + var c = a; + a = h, h = c; + } else if (u === 0 || h.cmpn(1) === 0) + break; + a.isub(h); + } while (true); + return h.iushln(s); + }, f.prototype.invm = function(i) { + return this.egcd(i).a.umod(i); + }, f.prototype.isEven = function() { + return (this.words[0] & 1) === 0; + }, f.prototype.isOdd = function() { + return (this.words[0] & 1) === 1; + }, f.prototype.andln = function(i) { + return this.words[0] & i; + }, f.prototype.bincn = function(i) { + r(typeof i == "number"); + var a = i % 26, h = (i - a) / 26, s = 1 << a; + if (this.length <= h) + return this._expand(h + 1), this.words[h] |= s, this; + for (var u = s, c = h;u !== 0 && c < this.length; c++) { + var b = this.words[c] | 0; + b += u, u = b >>> 26, b &= 67108863, this.words[c] = b; + } + return u !== 0 && (this.words[c] = u, this.length++), this; + }, f.prototype.isZero = function() { + return this.length === 1 && this.words[0] === 0; + }, f.prototype.cmpn = function(i) { + var a = i < 0; + if (this.negative !== 0 && !a) + return -1; + if (this.negative === 0 && a) + return 1; + this.strip(); + var h; + if (this.length > 1) + h = 1; + else { + a && (i = -i), r(i <= 67108863, "Number is too big"); + var s = this.words[0] | 0; + h = s === i ? 0 : s < i ? -1 : 1; + } + return this.negative !== 0 ? -h | 0 : h; + }, f.prototype.cmp = function(i) { + if (this.negative !== 0 && i.negative === 0) + return -1; + if (this.negative === 0 && i.negative !== 0) + return 1; + var a = this.ucmp(i); + return this.negative !== 0 ? -a | 0 : a; + }, f.prototype.ucmp = function(i) { + if (this.length > i.length) + return 1; + if (this.length < i.length) + return -1; + for (var a = 0, h = this.length - 1;h >= 0; h--) { + var s = this.words[h] | 0, u = i.words[h] | 0; + if (s !== u) { + s < u ? a = -1 : s > u && (a = 1); + break; + } + } + return a; + }, f.prototype.gtn = function(i) { + return this.cmpn(i) === 1; + }, f.prototype.gt = function(i) { + return this.cmp(i) === 1; + }, f.prototype.gten = function(i) { + return this.cmpn(i) >= 0; + }, f.prototype.gte = function(i) { + return this.cmp(i) >= 0; + }, f.prototype.ltn = function(i) { + return this.cmpn(i) === -1; + }, f.prototype.lt = function(i) { + return this.cmp(i) === -1; + }, f.prototype.lten = function(i) { + return this.cmpn(i) <= 0; + }, f.prototype.lte = function(i) { + return this.cmp(i) <= 0; + }, f.prototype.eqn = function(i) { + return this.cmpn(i) === 0; + }, f.prototype.eq = function(i) { + return this.cmp(i) === 0; + }, f.red = function(i) { + return new P(i); + }, f.prototype.toRed = function(i) { + return r(!this.red, "Already a number in reduction context"), r(this.negative === 0, "red works only with positives"), i.convertTo(this)._forceRed(i); + }, f.prototype.fromRed = function() { + return r(this.red, "fromRed works only with numbers in reduction context"), this.red.convertFrom(this); + }, f.prototype._forceRed = function(i) { + return this.red = i, this; + }, f.prototype.forceRed = function(i) { + return r(!this.red, "Already a number in reduction context"), this._forceRed(i); + }, f.prototype.redAdd = function(i) { + return r(this.red, "redAdd works only with red numbers"), this.red.add(this, i); + }, f.prototype.redIAdd = function(i) { + return r(this.red, "redIAdd works only with red numbers"), this.red.iadd(this, i); + }, f.prototype.redSub = function(i) { + return r(this.red, "redSub works only with red numbers"), this.red.sub(this, i); + }, f.prototype.redISub = function(i) { + return r(this.red, "redISub works only with red numbers"), this.red.isub(this, i); + }, f.prototype.redShl = function(i) { + return r(this.red, "redShl works only with red numbers"), this.red.shl(this, i); + }, f.prototype.redMul = function(i) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, i), this.red.mul(this, i); + }, f.prototype.redIMul = function(i) { + return r(this.red, "redMul works only with red numbers"), this.red._verify2(this, i), this.red.imul(this, i); + }, f.prototype.redSqr = function() { + return r(this.red, "redSqr works only with red numbers"), this.red._verify1(this), this.red.sqr(this); + }, f.prototype.redISqr = function() { + return r(this.red, "redISqr works only with red numbers"), this.red._verify1(this), this.red.isqr(this); + }, f.prototype.redSqrt = function() { + return r(this.red, "redSqrt works only with red numbers"), this.red._verify1(this), this.red.sqrt(this); + }, f.prototype.redInvm = function() { + return r(this.red, "redInvm works only with red numbers"), this.red._verify1(this), this.red.invm(this); + }, f.prototype.redNeg = function() { + return r(this.red, "redNeg works only with red numbers"), this.red._verify1(this), this.red.neg(this); + }, f.prototype.redPow = function(i) { + return r(this.red && !i.red, "redPow(normalNum)"), this.red._verify1(this), this.red.pow(this, i); + }; + var we = { k256: null, p224: null, p192: null, p25519: null }; + function ye(v, i) { + this.name = v, this.p = new f(i, 16), this.n = this.p.bitLength(), this.k = new f(1).iushln(this.n).isub(this.p), this.tmp = this._tmp(); + } + ye.prototype._tmp = function() { + var i = new f(null); + return i.words = new Array(Math.ceil(this.n / 13)), i; + }, ye.prototype.ireduce = function(i) { + var a = i, h; + do + this.split(a, this.tmp), a = this.imulK(a), a = a.iadd(this.tmp), h = a.bitLength(); + while (h > this.n); + var s = h < this.n ? -1 : a.ucmp(this.p); + return s === 0 ? (a.words[0] = 0, a.length = 1) : s > 0 ? a.isub(this.p) : a.strip !== undefined ? a.strip() : a._strip(), a; + }, ye.prototype.split = function(i, a) { + i.iushrn(this.n, 0, a); + }, ye.prototype.imulK = function(i) { + return i.imul(this.k); + }; + function xe() { + ye.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); + } + o(xe, ye), xe.prototype.split = function(i, a) { + for (var h = 4194303, s = Math.min(i.length, 9), u = 0;u < s; u++) + a.words[u] = i.words[u]; + if (a.length = s, i.length <= 9) { + i.words[0] = 0, i.length = 1; + return; + } + var c = i.words[9]; + for (a.words[a.length++] = c & h, u = 10;u < i.length; u++) { + var b = i.words[u] | 0; + i.words[u - 10] = (b & h) << 4 | c >>> 22, c = b; + } + c >>>= 22, i.words[u - 10] = c, c === 0 && i.length > 10 ? i.length -= 10 : i.length -= 9; + }, xe.prototype.imulK = function(i) { + i.words[i.length] = 0, i.words[i.length + 1] = 0, i.length += 2; + for (var a = 0, h = 0;h < i.length; h++) { + var s = i.words[h] | 0; + a += s * 977, i.words[h] = a & 67108863, a = s * 64 + (a / 67108864 | 0); + } + return i.words[i.length - 1] === 0 && (i.length--, i.words[i.length - 1] === 0 && i.length--), i; + }; + function Re() { + ye.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); + } + o(Re, ye); + function Ee() { + ye.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); + } + o(Ee, ye); + function Ae() { + ye.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); + } + o(Ae, ye), Ae.prototype.imulK = function(i) { + for (var a = 0, h = 0;h < i.length; h++) { + var s = (i.words[h] | 0) * 19 + a, u = s & 67108863; + s >>>= 26, i.words[h] = u, a = s; + } + return a !== 0 && (i.words[i.length++] = a), i; + }, f._prime = function(i) { + if (we[i]) + return we[i]; + var a; + if (i === "k256") + a = new xe; + else if (i === "p224") + a = new Re; + else if (i === "p192") + a = new Ee; + else if (i === "p25519") + a = new Ae; + else + throw new Error("Unknown prime " + i); + return we[i] = a, a; + }; + function P(v) { + if (typeof v == "string") { + var i = f._prime(v); + this.m = i.p, this.prime = i; + } else + r(v.gtn(1), "modulus must be greater than 1"), this.m = v, this.prime = null; + } + P.prototype._verify1 = function(i) { + r(i.negative === 0, "red works only with positives"), r(i.red, "red works only with red numbers"); + }, P.prototype._verify2 = function(i, a) { + r((i.negative | a.negative) === 0, "red works only with positives"), r(i.red && i.red === a.red, "red works only with red numbers"); + }, P.prototype.imod = function(i) { + return this.prime ? this.prime.ireduce(i)._forceRed(this) : i.umod(this.m)._forceRed(this); + }, P.prototype.neg = function(i) { + return i.isZero() ? i.clone() : this.m.sub(i)._forceRed(this); + }, P.prototype.add = function(i, a) { + this._verify2(i, a); + var h = i.add(a); + return h.cmp(this.m) >= 0 && h.isub(this.m), h._forceRed(this); + }, P.prototype.iadd = function(i, a) { + this._verify2(i, a); + var h = i.iadd(a); + return h.cmp(this.m) >= 0 && h.isub(this.m), h; + }, P.prototype.sub = function(i, a) { + this._verify2(i, a); + var h = i.sub(a); + return h.cmpn(0) < 0 && h.iadd(this.m), h._forceRed(this); + }, P.prototype.isub = function(i, a) { + this._verify2(i, a); + var h = i.isub(a); + return h.cmpn(0) < 0 && h.iadd(this.m), h; + }, P.prototype.shl = function(i, a) { + return this._verify1(i), this.imod(i.ushln(a)); + }, P.prototype.imul = function(i, a) { + return this._verify2(i, a), this.imod(i.imul(a)); + }, P.prototype.mul = function(i, a) { + return this._verify2(i, a), this.imod(i.mul(a)); + }, P.prototype.isqr = function(i) { + return this.imul(i, i.clone()); + }, P.prototype.sqr = function(i) { + return this.mul(i, i); + }, P.prototype.sqrt = function(i) { + if (i.isZero()) + return i.clone(); + var a = this.m.andln(3); + if (r(a % 2 === 1), a === 3) { + var h = this.m.add(new f(1)).iushrn(2); + return this.pow(i, h); + } + for (var s = this.m.subn(1), u = 0;!s.isZero() && s.andln(1) === 0; ) + u++, s.iushrn(1); + r(!s.isZero()); + var c = new f(1).toRed(this), b = c.redNeg(), l = this.m.subn(1).iushrn(1), n = this.m.bitLength(); + for (n = new f(2 * n * n).toRed(this);this.pow(n, l).cmp(b) !== 0; ) + n.redIAdd(b); + for (var d = this.pow(n, s), w = this.pow(i, s.addn(1).iushrn(1)), g = this.pow(i, s), _9 = u;g.cmp(c) !== 0; ) { + for (var A = g, R = 0;A.cmp(c) !== 0; R++) + A = A.redSqr(); + r(R < _9); + var I2 = this.pow(d, new f(1).iushln(_9 - R - 1)); + w = w.redMul(I2), d = I2.redSqr(), g = g.redMul(d), _9 = R; + } + return w; + }, P.prototype.invm = function(i) { + var a = i._invmp(this.m); + return a.negative !== 0 ? (a.negative = 0, this.imod(a).redNeg()) : this.imod(a); + }, P.prototype.pow = function(i, a) { + if (a.isZero()) + return new f(1).toRed(this); + if (a.cmpn(1) === 0) + return i.clone(); + var h = 4, s = new Array(1 << h); + s[0] = new f(1).toRed(this), s[1] = i; + for (var u = 2;u < s.length; u++) + s[u] = this.mul(s[u - 1], i); + var c = s[0], b = 0, l = 0, n = a.bitLength() % 26; + for (n === 0 && (n = 26), u = a.length - 1;u >= 0; u--) { + for (var d = a.words[u], w = n - 1;w >= 0; w--) { + var g = d >> w & 1; + if (c !== s[0] && (c = this.sqr(c)), g === 0 && b === 0) { + l = 0; + continue; + } + b <<= 1, b |= g, l++, !(l !== h && (u !== 0 || w !== 0)) && (c = this.mul(c, s[b]), l = 0, b = 0); + } + n = 26; + } + return c; + }, P.prototype.convertTo = function(i) { + var a = i.umod(this.m); + return a === i ? a.clone() : a; + }, P.prototype.convertFrom = function(i) { + var a = i.clone(); + return a.red = null, a; + }, f.mont = function(i) { + return new Se2(i); + }; + function Se2(v) { + P.call(this, v), this.shift = this.m.bitLength(), this.shift % 26 !== 0 && (this.shift += 26 - this.shift % 26), this.r = new f(1).iushln(this.shift), this.r2 = this.imod(this.r.sqr()), this.rinv = this.r._invmp(this.m), this.minv = this.rinv.mul(this.r).isubn(1).div(this.m), this.minv = this.minv.umod(this.r), this.minv = this.r.sub(this.minv); + } + o(Se2, P), Se2.prototype.convertTo = function(i) { + return this.imod(i.ushln(this.shift)); + }, Se2.prototype.convertFrom = function(i) { + var a = this.imod(i.mul(this.rinv)); + return a.red = null, a; + }, Se2.prototype.imul = function(i, a) { + if (i.isZero() || a.isZero()) + return i.words[0] = 0, i.length = 1, i; + var h = i.imul(a), s = h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = h.isub(s).iushrn(this.shift), c = u; + return u.cmp(this.m) >= 0 ? c = u.isub(this.m) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }, Se2.prototype.mul = function(i, a) { + if (i.isZero() || a.isZero()) + return new f(0)._forceRed(this); + var h = i.mul(a), s = h.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m), u = h.isub(s).iushrn(this.shift), c = u; + return u.cmp(this.m) >= 0 ? c = u.isub(this.m) : u.cmpn(0) < 0 && (c = u.iadd(this.m)), c._forceRed(this); + }, Se2.prototype.invm = function(i) { + var a = this.imod(i._invmp(this.m).mul(this.r2)); + return a._forceRed(this); + }; + })(typeof Sd > "u" || Sd, F3); + }); + Ed = T((xL, z3) => { + var U3 = w0(), wq = Te().Buffer; + function Mq(t, e) { + return wq.from(t.toRed(U3.mont(e.modulus)).redPow(new U3(e.publicExponent)).fromRed().toArray()); + } + z3.exports = Mq; + }); + j3 = T((SL, K3) => { + var _q = Ha(), Ad = on(), xq = bf(), H3 = _d(), W3 = xd(), Rd = w0(), Sq = Ed(), Eq = Ks(), Kr2 = Te().Buffer; + K3.exports = function(e, r, o) { + var f; + e.padding ? f = e.padding : o ? f = 1 : f = 4; + var p = _q(e), m; + if (f === 4) + m = Aq(p, r); + else if (f === 1) + m = Rq(p, r, o); + else if (f === 3) { + if (m = new Rd(r), m.cmp(p.modulus) >= 0) + throw new Error("data too long for modulus"); + } else + throw new Error("unknown padding"); + return o ? Eq(m, p) : Sq(m, p); + }; + function Aq(t, e) { + var r = t.modulus.byteLength(), o = e.length, f = xq("sha1").update(Kr2.alloc(0)).digest(), p = f.length, m = 2 * p; + if (o > r - m - 2) + throw new Error("message too long"); + var y = Kr2.alloc(r - o - m - 2), M = r - p - 1, x = Ad(p), S = W3(Kr2.concat([f, y, Kr2.alloc(1, 1), e], M), H3(x, M)), E2 = W3(x, H3(S, p)); + return new Rd(Kr2.concat([Kr2.alloc(1), E2, S], r)); + } + function Rq(t, e, r) { + var o = e.length, f = t.modulus.byteLength(); + if (o > f - 11) + throw new Error("message too long"); + var p; + return r ? p = Kr2.alloc(f - o - 3, 255) : p = Bq(f - o - 3), new Rd(Kr2.concat([Kr2.from([0, r ? 1 : 2]), p, Kr2.alloc(1), e], f)); + } + function Bq(t) { + for (var e = Kr2.allocUnsafe(t), r = 0, o = Ad(t * 2), f = 0, p;r < t; ) + f === o.length && (o = Ad(t * 2), f = 0), p = o[f++], p && (e[r++] = p); + return e; + } + }); + Y3 = T((EL, G3) => { + var qq = Ha(), Z3 = _d(), V3 = xd(), $3 = w0(), Iq = Ks(), Tq = bf(), kq = Ed(), Za = Te().Buffer; + G3.exports = function(e, r, o) { + var f; + e.padding ? f = e.padding : o ? f = 1 : f = 4; + var p = qq(e), m = p.modulus.byteLength(); + if (r.length > m || new $3(r).cmp(p.modulus) >= 0) + throw new Error("decryption error"); + var y; + o ? y = kq(new $3(r), p) : y = Iq(r, p); + var M = Za.alloc(m - y.length); + if (y = Za.concat([M, y], m), f === 4) + return Lq(p, y); + if (f === 1) + return Nq(p, y, o); + if (f === 3) + return y; + throw new Error("unknown padding"); + }; + function Lq(t, e) { + var r = t.modulus.byteLength(), o = Tq("sha1").update(Za.alloc(0)).digest(), f = o.length; + if (e[0] !== 0) + throw new Error("decryption error"); + var p = e.slice(1, f + 1), m = e.slice(f + 1), y = V3(p, Z3(m, f)), M = V3(m, Z3(y, r - f - 1)); + if (Dq(o, M.slice(0, f))) + throw new Error("decryption error"); + for (var x = f;M[x] === 0; ) + x++; + if (M[x++] !== 1) + throw new Error("decryption error"); + return M.slice(x); + } + function Nq(t, e, r) { + for (var o = e.slice(0, 2), f = 2, p = 0;e[f++] !== 0; ) + if (f >= e.length) { + p++; + break; + } + var m = e.slice(2, f - 1); + if ((o.toString("hex") !== "0002" && !r || o.toString("hex") !== "0001" && r) && p++, m.length < 8 && p++, p) + throw new Error("decryption error"); + return e.slice(f); + } + function Dq(t, e) { + t = Za.from(t), e = Za.from(e); + var r = 0, o = t.length; + t.length !== e.length && (r++, o = Math.min(t.length, e.length)); + for (var f = -1;++f < o; ) + r += t[f] ^ e[f]; + return r; + } + }); + X3 = T((Vn) => { + Vn.publicEncrypt = j3(); + Vn.privateDecrypt = Y3(); + Vn.privateEncrypt = function(e, r) { + return Vn.publicEncrypt(e, r, true); + }; + Vn.publicDecrypt = function(e, r) { + return Vn.privateDecrypt(e, r, true); + }; + }); + ow = T((Va) => { + function J3() { + throw new Error(`secure random number generation not supported by this browser +use chrome, FireFox or Internet Explorer 11`); + } + var ew = Te(), Q3 = on(), tw = ew.Buffer, rw = ew.kMaxLength, Bd = global.crypto || global.msCrypto, iw = Math.pow(2, 32) - 1; + function nw(t, e) { + if (typeof t != "number" || t !== t) + throw new TypeError("offset must be a number"); + if (t > iw || t < 0) + throw new TypeError("offset must be a uint32"); + if (t > rw || t > e) + throw new RangeError("offset out of range"); + } + function fw(t, e, r) { + if (typeof t != "number" || t !== t) + throw new TypeError("size must be a number"); + if (t > iw || t < 0) + throw new TypeError("size must be a uint32"); + if (t + e > r || t > rw) + throw new RangeError("buffer too small"); + } + Bd && Bd.getRandomValues ? (Va.randomFill = Pq, Va.randomFillSync = Cq) : (Va.randomFill = J3, Va.randomFillSync = J3); + function Pq(t, e, r, o) { + if (!tw.isBuffer(t) && !(t instanceof global.Uint8Array)) + throw new TypeError('"buf" argument must be a Buffer or Uint8Array'); + if (typeof e == "function") + o = e, e = 0, r = t.length; + else if (typeof r == "function") + o = r, r = t.length - e; + else if (typeof o != "function") + throw new TypeError('"cb" argument must be a function'); + return nw(e, t.length), fw(r, e, t.length), aw(t, e, r, o); + } + function aw(t, e, r, o) { + if (true) { + var f = t.buffer, p = new Uint8Array(f, e, r); + if (Bd.getRandomValues(p), o) { + process.nextTick(function() { + o(null, t); + }); + return; + } + return t; + } + if (o) { + Q3(r, function(y, M) { + if (y) + return o(y); + M.copy(t, e), o(null, t); + }); + return; + } + var m = Q3(r); + return m.copy(t, e), t; + } + function Cq(t, e, r) { + if (typeof e > "u" && (e = 0), !tw.isBuffer(t) && !(t instanceof global.Uint8Array)) + throw new TypeError('"buf" argument must be a Buffer or Uint8Array'); + return nw(e, t.length), r === undefined && (r = t.length - e), fw(r, e, t.length), aw(t, e, r); + } + }); + qd = T((ke) => { + ke.randomBytes = ke.rng = ke.pseudoRandomBytes = ke.prng = on(); + ke.createHash = ke.Hash = bf(); + ke.createHmac = ke.Hmac = wu(); + var Oq = Eb(), Fq = Object.keys(Oq), Uq = ["sha1", "sha224", "sha256", "sha384", "sha512", "md5", "rmd160"].concat(Fq); + ke.getHashes = function() { + return Uq; + }; + var sw = Iu(); + ke.pbkdf2 = sw.pbkdf2; + ke.pbkdf2Sync = sw.pbkdf2Sync; + var ui = Vm(); + ke.Cipher = ui.Cipher; + ke.createCipher = ui.createCipher; + ke.Cipheriv = ui.Cipheriv; + ke.createCipheriv = ui.createCipheriv; + ke.Decipher = ui.Decipher; + ke.createDecipher = ui.createDecipher; + ke.Decipheriv = ui.Decipheriv; + ke.createDecipheriv = ui.createDecipheriv; + ke.getCiphers = ui.getCiphers; + ke.listCiphers = ui.listCiphers; + var $a = hg(); + ke.DiffieHellmanGroup = $a.DiffieHellmanGroup; + ke.createDiffieHellmanGroup = $a.createDiffieHellmanGroup; + ke.getDiffieHellman = $a.getDiffieHellman; + ke.createDiffieHellman = $a.createDiffieHellman; + ke.DiffieHellman = $a.DiffieHellman; + var M0 = k3(); + ke.createSign = M0.createSign; + ke.Sign = M0.Sign; + ke.createVerify = M0.createVerify; + ke.Verify = M0.Verify; + ke.createECDH = P3(); + var _0 = X3(); + ke.publicEncrypt = _0.publicEncrypt; + ke.privateEncrypt = _0.privateEncrypt; + ke.publicDecrypt = _0.publicDecrypt; + ke.privateDecrypt = _0.privateDecrypt; + var hw = ow(); + ke.randomFill = hw.randomFill; + ke.randomFillSync = hw.randomFillSync; + ke.createCredentials = function() { + throw new Error(["sorry, createCredentials is not implemented yet", "we accept pull requests", "https://github.com/crypto-browserify/crypto-browserify"].join(` +`)); + }; + ke.constants = { DH_CHECK_P_NOT_SAFE_PRIME: 2, DH_CHECK_P_NOT_PRIME: 1, DH_UNABLE_TO_CHECK_GENERATOR: 4, DH_NOT_SUITABLE_GENERATOR: 8, NPN_ENABLED: 1, ALPN_ENABLED: 1, RSA_PKCS1_PADDING: 1, RSA_SSLV23_PADDING: 2, RSA_NO_PADDING: 3, RSA_PKCS1_OAEP_PADDING: 4, RSA_X931_PADDING: 5, RSA_PKCS1_PSS_PADDING: 6, POINT_CONVERSION_COMPRESSED: 2, POINT_CONVERSION_UNCOMPRESSED: 4, POINT_CONVERSION_HYBRID: 6 }; + }); + Xt = {}; + Ja(Xt, { DEFAULT_ENCODING: () => Ga, default: () => Wq, getCurves: () => dw, getRandomValues: () => uw, randomUUID: () => lw, scrypt: () => Td, scryptSync: () => Id, timingSafeEqual: () => x0, webcrypto: () => cw }); + ot(Xt, rn2(qd())); + zq = rn2(qd()); + Hq = ["p192", "p224", "p256", "p384", "p521", "curve25519", "ed25519", "secp256k1", "secp224r1", "prime256v1", "prime192v1", "ed25519", "secp384r1", "secp521r1"]; + x0 = "timingSafeEqual" in crypto ? (t, e) => { + let { byteLength: r } = t, { byteLength: o } = e; + if (typeof r != "number" || typeof o != "number") + throw new TypeError("Input must be an array buffer view"); + if (r !== o) + throw new RangeError("Input buffers must have the same length"); + return crypto.timingSafeEqual(t, e); + } : undefined; + Id = "scryptSync" in crypto ? (t, e, r, o) => { + let f = crypto.scryptSync(t, e, r, o); + return Ga !== "buffer" ? new Buffer(f).toString(Ga) : new Buffer(f); + } : undefined; + Td = "scryptSync" in crypto ? function(t, e, r, o, f) { + if (typeof o == "function" && (f = o, o = undefined), typeof f != "function") { + var p = new TypeError("callback must be a function"); + throw p.code = "ERR_INVALID_CALLBACK", p; + } + try { + let m = crypto.scryptSync(t, e, r, o); + process.nextTick(f, null, Ga !== "buffer" ? new Buffer(m).toString(Ga) : new Buffer(m)); + } catch (m) { + throw m; + } + } : undefined; + x0 && (Object.defineProperty(x0, "name", { value: "::bunternal::" }), Object.defineProperty(Td, "name", { value: "::bunternal::" }), Object.defineProperty(Id, "name", { value: "::bunternal::" })); + cw = crypto; + Wq = { ...zq, getRandomValues: uw, randomUUID: lw, timingSafeEqual: x0, scryptSync: Id, scrypt: Td, webcrypto: cw, getCurves: dw }; + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + /*! safe-buffer. MIT License. Feross Aboukhadijeh */ +}); + +// node_modules/three/build/three.cjs +var require_three = __commonJS((exports2) => { + var REVISION2 = "173"; + var MOUSE2 = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; + var TOUCH2 = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; + var CullFaceNone2 = 0; + var CullFaceBack2 = 1; + var CullFaceFront2 = 2; + var CullFaceFrontBack2 = 3; + var BasicShadowMap2 = 0; + var PCFShadowMap2 = 1; + var PCFSoftShadowMap2 = 2; + var VSMShadowMap2 = 3; + var FrontSide2 = 0; + var BackSide2 = 1; + var DoubleSide2 = 2; + var NoBlending2 = 0; + var NormalBlending2 = 1; + var AdditiveBlending2 = 2; + var SubtractiveBlending2 = 3; + var MultiplyBlending2 = 4; + var CustomBlending2 = 5; + var AddEquation2 = 100; + var SubtractEquation2 = 101; + var ReverseSubtractEquation2 = 102; + var MinEquation2 = 103; + var MaxEquation2 = 104; + var ZeroFactor2 = 200; + var OneFactor2 = 201; + var SrcColorFactor2 = 202; + var OneMinusSrcColorFactor2 = 203; + var SrcAlphaFactor2 = 204; + var OneMinusSrcAlphaFactor2 = 205; + var DstAlphaFactor2 = 206; + var OneMinusDstAlphaFactor2 = 207; + var DstColorFactor2 = 208; + var OneMinusDstColorFactor2 = 209; + var SrcAlphaSaturateFactor2 = 210; + var ConstantColorFactor2 = 211; + var OneMinusConstantColorFactor2 = 212; + var ConstantAlphaFactor2 = 213; + var OneMinusConstantAlphaFactor2 = 214; + var NeverDepth2 = 0; + var AlwaysDepth2 = 1; + var LessDepth2 = 2; + var LessEqualDepth2 = 3; + var EqualDepth2 = 4; + var GreaterEqualDepth2 = 5; + var GreaterDepth2 = 6; + var NotEqualDepth2 = 7; + var MultiplyOperation2 = 0; + var MixOperation2 = 1; + var AddOperation2 = 2; + var NoToneMapping2 = 0; + var LinearToneMapping2 = 1; + var ReinhardToneMapping2 = 2; + var CineonToneMapping2 = 3; + var ACESFilmicToneMapping2 = 4; + var CustomToneMapping2 = 5; + var AgXToneMapping2 = 6; + var NeutralToneMapping2 = 7; + var AttachedBindMode2 = "attached"; + var DetachedBindMode2 = "detached"; + var UVMapping2 = 300; + var CubeReflectionMapping2 = 301; + var CubeRefractionMapping2 = 302; + var EquirectangularReflectionMapping2 = 303; + var EquirectangularRefractionMapping2 = 304; + var CubeUVReflectionMapping2 = 306; + var RepeatWrapping2 = 1000; + var ClampToEdgeWrapping2 = 1001; + var MirroredRepeatWrapping2 = 1002; + var NearestFilter2 = 1003; + var NearestMipmapNearestFilter2 = 1004; + var NearestMipMapNearestFilter2 = 1004; + var NearestMipmapLinearFilter2 = 1005; + var NearestMipMapLinearFilter2 = 1005; + var LinearFilter2 = 1006; + var LinearMipmapNearestFilter2 = 1007; + var LinearMipMapNearestFilter2 = 1007; + var LinearMipmapLinearFilter2 = 1008; + var LinearMipMapLinearFilter2 = 1008; + var UnsignedByteType2 = 1009; + var ByteType2 = 1010; + var ShortType2 = 1011; + var UnsignedShortType2 = 1012; + var IntType2 = 1013; + var UnsignedIntType2 = 1014; + var FloatType2 = 1015; + var HalfFloatType2 = 1016; + var UnsignedShort4444Type2 = 1017; + var UnsignedShort5551Type2 = 1018; + var UnsignedInt248Type2 = 1020; + var UnsignedInt5999Type2 = 35902; + var AlphaFormat2 = 1021; + var RGBFormat2 = 1022; + var RGBAFormat2 = 1023; + var LuminanceFormat2 = 1024; + var LuminanceAlphaFormat2 = 1025; + var DepthFormat2 = 1026; + var DepthStencilFormat2 = 1027; + var RedFormat2 = 1028; + var RedIntegerFormat2 = 1029; + var RGFormat2 = 1030; + var RGIntegerFormat2 = 1031; + var RGBIntegerFormat2 = 1032; + var RGBAIntegerFormat2 = 1033; + var RGB_S3TC_DXT1_Format2 = 33776; + var RGBA_S3TC_DXT1_Format2 = 33777; + var RGBA_S3TC_DXT3_Format2 = 33778; + var RGBA_S3TC_DXT5_Format2 = 33779; + var RGB_PVRTC_4BPPV1_Format2 = 35840; + var RGB_PVRTC_2BPPV1_Format2 = 35841; + var RGBA_PVRTC_4BPPV1_Format2 = 35842; + var RGBA_PVRTC_2BPPV1_Format2 = 35843; + var RGB_ETC1_Format2 = 36196; + var RGB_ETC2_Format2 = 37492; + var RGBA_ETC2_EAC_Format2 = 37496; + var RGBA_ASTC_4x4_Format2 = 37808; + var RGBA_ASTC_5x4_Format2 = 37809; + var RGBA_ASTC_5x5_Format2 = 37810; + var RGBA_ASTC_6x5_Format2 = 37811; + var RGBA_ASTC_6x6_Format2 = 37812; + var RGBA_ASTC_8x5_Format2 = 37813; + var RGBA_ASTC_8x6_Format2 = 37814; + var RGBA_ASTC_8x8_Format2 = 37815; + var RGBA_ASTC_10x5_Format2 = 37816; + var RGBA_ASTC_10x6_Format2 = 37817; + var RGBA_ASTC_10x8_Format2 = 37818; + var RGBA_ASTC_10x10_Format2 = 37819; + var RGBA_ASTC_12x10_Format2 = 37820; + var RGBA_ASTC_12x12_Format2 = 37821; + var RGBA_BPTC_Format2 = 36492; + var RGB_BPTC_SIGNED_Format2 = 36494; + var RGB_BPTC_UNSIGNED_Format2 = 36495; + var RED_RGTC1_Format2 = 36283; + var SIGNED_RED_RGTC1_Format2 = 36284; + var RED_GREEN_RGTC2_Format2 = 36285; + var SIGNED_RED_GREEN_RGTC2_Format2 = 36286; + var LoopOnce2 = 2200; + var LoopRepeat2 = 2201; + var LoopPingPong2 = 2202; + var InterpolateDiscrete2 = 2300; + var InterpolateLinear2 = 2301; + var InterpolateSmooth2 = 2302; + var ZeroCurvatureEnding2 = 2400; + var ZeroSlopeEnding2 = 2401; + var WrapAroundEnding2 = 2402; + var NormalAnimationBlendMode2 = 2500; + var AdditiveAnimationBlendMode2 = 2501; + var TrianglesDrawMode2 = 0; + var TriangleStripDrawMode2 = 1; + var TriangleFanDrawMode2 = 2; + var BasicDepthPacking2 = 3200; + var RGBADepthPacking2 = 3201; + var RGBDepthPacking2 = 3202; + var RGDepthPacking2 = 3203; + var TangentSpaceNormalMap2 = 0; + var ObjectSpaceNormalMap2 = 1; + var NoColorSpace2 = ""; + var SRGBColorSpace2 = "srgb"; + var LinearSRGBColorSpace2 = "srgb-linear"; + var LinearTransfer2 = "linear"; + var SRGBTransfer2 = "srgb"; + var ZeroStencilOp2 = 0; + var KeepStencilOp2 = 7680; + var ReplaceStencilOp2 = 7681; + var IncrementStencilOp2 = 7682; + var DecrementStencilOp2 = 7683; + var IncrementWrapStencilOp2 = 34055; + var DecrementWrapStencilOp2 = 34056; + var InvertStencilOp2 = 5386; + var NeverStencilFunc2 = 512; + var LessStencilFunc2 = 513; + var EqualStencilFunc2 = 514; + var LessEqualStencilFunc2 = 515; + var GreaterStencilFunc2 = 516; + var NotEqualStencilFunc2 = 517; + var GreaterEqualStencilFunc2 = 518; + var AlwaysStencilFunc2 = 519; + var NeverCompare2 = 512; + var LessCompare2 = 513; + var EqualCompare2 = 514; + var LessEqualCompare2 = 515; + var GreaterCompare2 = 516; + var NotEqualCompare2 = 517; + var GreaterEqualCompare2 = 518; + var AlwaysCompare2 = 519; + var StaticDrawUsage2 = 35044; + var DynamicDrawUsage2 = 35048; + var StreamDrawUsage2 = 35040; + var StaticReadUsage2 = 35045; + var DynamicReadUsage2 = 35049; + var StreamReadUsage2 = 35041; + var StaticCopyUsage2 = 35046; + var DynamicCopyUsage2 = 35050; + var StreamCopyUsage2 = 35042; + var GLSL12 = "100"; + var GLSL32 = "300 es"; + var WebGLCoordinateSystem2 = 2000; + var WebGPUCoordinateSystem2 = 2001; + var TimestampQuery2 = { + COMPUTE: "compute", + RENDER: "render" + }; + + class EventDispatcher2 { + addEventListener(type, listener) { + if (this._listeners === undefined) + this._listeners = {}; + const listeners = this._listeners; + if (listeners[type] === undefined) { + listeners[type] = []; + } + if (listeners[type].indexOf(listener) === -1) { + listeners[type].push(listener); + } + } + hasEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === undefined) + return false; + return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1; + } + removeEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === undefined) + return; + const listenerArray = listeners[type]; + if (listenerArray !== undefined) { + const index2 = listenerArray.indexOf(listener); + if (index2 !== -1) { + listenerArray.splice(index2, 1); + } + } + } + dispatchEvent(event) { + const listeners = this._listeners; + if (listeners === undefined) + return; + const listenerArray = listeners[event.type]; + if (listenerArray !== undefined) { + event.target = this; + const array = listenerArray.slice(0); + for (let i = 0, l2 = array.length;i < l2; i++) { + array[i].call(this, event); + } + event.target = null; + } + } + } + var _lut2 = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"]; + var _seed2 = 1234567; + var DEG2RAD2 = Math.PI / 180; + var RAD2DEG2 = 180 / Math.PI; + function generateUUID2() { + const d02 = Math.random() * 4294967295 | 0; + const d1 = Math.random() * 4294967295 | 0; + const d2 = Math.random() * 4294967295 | 0; + const d32 = Math.random() * 4294967295 | 0; + const uuid = _lut2[d02 & 255] + _lut2[d02 >> 8 & 255] + _lut2[d02 >> 16 & 255] + _lut2[d02 >> 24 & 255] + "-" + _lut2[d1 & 255] + _lut2[d1 >> 8 & 255] + "-" + _lut2[d1 >> 16 & 15 | 64] + _lut2[d1 >> 24 & 255] + "-" + _lut2[d2 & 63 | 128] + _lut2[d2 >> 8 & 255] + "-" + _lut2[d2 >> 16 & 255] + _lut2[d2 >> 24 & 255] + _lut2[d32 & 255] + _lut2[d32 >> 8 & 255] + _lut2[d32 >> 16 & 255] + _lut2[d32 >> 24 & 255]; + return uuid.toLowerCase(); + } + function clamp3(value2, min, max) { + return Math.max(min, Math.min(max, value2)); + } + function euclideanModulo2(n2, m) { + return (n2 % m + m) % m; + } + function mapLinear2(x2, a1, a2, b1, b22) { + return b1 + (x2 - a1) * (b22 - b1) / (a2 - a1); + } + function inverseLerp2(x2, y3, value2) { + if (x2 !== y3) { + return (value2 - x2) / (y3 - x2); + } else { + return 0; + } + } + function lerp2(x2, y3, t4) { + return (1 - t4) * x2 + t4 * y3; + } + function damp2(x2, y3, lambda, dt) { + return lerp2(x2, y3, 1 - Math.exp(-lambda * dt)); + } + function pingpong2(x2, length2 = 1) { + return length2 - Math.abs(euclideanModulo2(x2, length2 * 2) - length2); + } + function smoothstep2(x2, min, max) { + if (x2 <= min) + return 0; + if (x2 >= max) + return 1; + x2 = (x2 - min) / (max - min); + return x2 * x2 * (3 - 2 * x2); + } + function smootherstep2(x2, min, max) { + if (x2 <= min) + return 0; + if (x2 >= max) + return 1; + x2 = (x2 - min) / (max - min); + return x2 * x2 * x2 * (x2 * (x2 * 6 - 15) + 10); + } + function randInt2(low, high) { + return low + Math.floor(Math.random() * (high - low + 1)); + } + function randFloat2(low, high) { + return low + Math.random() * (high - low); + } + function randFloatSpread2(range) { + return range * (0.5 - Math.random()); + } + function seededRandom2(s) { + if (s !== undefined) + _seed2 = s; + let t4 = _seed2 += 1831565813; + t4 = Math.imul(t4 ^ t4 >>> 15, t4 | 1); + t4 ^= t4 + Math.imul(t4 ^ t4 >>> 7, t4 | 61); + return ((t4 ^ t4 >>> 14) >>> 0) / 4294967296; + } + function degToRad2(degrees) { + return degrees * DEG2RAD2; + } + function radToDeg2(radians) { + return radians * RAD2DEG2; + } + function isPowerOfTwo2(value2) { + return (value2 & value2 - 1) === 0 && value2 !== 0; + } + function ceilPowerOfTwo2(value2) { + return Math.pow(2, Math.ceil(Math.log(value2) / Math.LN2)); + } + function floorPowerOfTwo2(value2) { + return Math.pow(2, Math.floor(Math.log(value2) / Math.LN2)); + } + function setQuaternionFromProperEuler2(q2, a2, b3, c2, order) { + const cos = Math.cos; + const sin = Math.sin; + const c22 = cos(b3 / 2); + const s22 = sin(b3 / 2); + const c13 = cos((a2 + c2) / 2); + const s13 = sin((a2 + c2) / 2); + const c1_3 = cos((a2 - c2) / 2); + const s1_3 = sin((a2 - c2) / 2); + const c3_1 = cos((c2 - a2) / 2); + const s3_1 = sin((c2 - a2) / 2); + switch (order) { + case "XYX": + q2.set(c22 * s13, s22 * c1_3, s22 * s1_3, c22 * c13); + break; + case "YZY": + q2.set(s22 * s1_3, c22 * s13, s22 * c1_3, c22 * c13); + break; + case "ZXZ": + q2.set(s22 * c1_3, s22 * s1_3, c22 * s13, c22 * c13); + break; + case "XZX": + q2.set(c22 * s13, s22 * s3_1, s22 * c3_1, c22 * c13); + break; + case "YXY": + q2.set(s22 * c3_1, c22 * s13, s22 * s3_1, c22 * c13); + break; + case "ZYZ": + q2.set(s22 * s3_1, s22 * c3_1, c22 * s13, c22 * c13); + break; + default: + console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + order); + } + } + function denormalize2(value2, array) { + switch (array.constructor) { + case Float32Array: + return value2; + case Uint32Array: + return value2 / 4294967295; + case Uint16Array: + return value2 / 65535; + case Uint8Array: + return value2 / 255; + case Int32Array: + return Math.max(value2 / 2147483647, -1); + case Int16Array: + return Math.max(value2 / 32767, -1); + case Int8Array: + return Math.max(value2 / 127, -1); + default: + throw new Error("Invalid component type."); + } + } + function normalize3(value2, array) { + switch (array.constructor) { + case Float32Array: + return value2; + case Uint32Array: + return Math.round(value2 * 4294967295); + case Uint16Array: + return Math.round(value2 * 65535); + case Uint8Array: + return Math.round(value2 * 255); + case Int32Array: + return Math.round(value2 * 2147483647); + case Int16Array: + return Math.round(value2 * 32767); + case Int8Array: + return Math.round(value2 * 127); + default: + throw new Error("Invalid component type."); + } + } + var MathUtils2 = { + DEG2RAD: DEG2RAD2, + RAD2DEG: RAD2DEG2, + generateUUID: generateUUID2, + clamp: clamp3, + euclideanModulo: euclideanModulo2, + mapLinear: mapLinear2, + inverseLerp: inverseLerp2, + lerp: lerp2, + damp: damp2, + pingpong: pingpong2, + smoothstep: smoothstep2, + smootherstep: smootherstep2, + randInt: randInt2, + randFloat: randFloat2, + randFloatSpread: randFloatSpread2, + seededRandom: seededRandom2, + degToRad: degToRad2, + radToDeg: radToDeg2, + isPowerOfTwo: isPowerOfTwo2, + ceilPowerOfTwo: ceilPowerOfTwo2, + floorPowerOfTwo: floorPowerOfTwo2, + setQuaternionFromProperEuler: setQuaternionFromProperEuler2, + normalize: normalize3, + denormalize: denormalize2 + }; + + class Vector22 { + constructor(x2 = 0, y3 = 0) { + Vector22.prototype.isVector2 = true; + this.x = x2; + this.y = y3; + } + get width() { + return this.x; + } + set width(value2) { + this.x = value2; + } + get height() { + return this.y; + } + set height(value2) { + this.y = value2; + } + set(x2, y3) { + this.x = x2; + this.y = y3; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + return this; + } + setX(x2) { + this.x = x2; + return this; + } + setY(y3) { + this.y = y3; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y); + } + copy(v) { + this.x = v.x; + this.y = v.y; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + return this; + } + addVectors(a2, b3) { + this.x = a2.x + b3.x; + this.y = a2.y + b3.y; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + return this; + } + subVectors(a2, b3) { + this.x = a2.x - b3.x; + this.y = a2.y - b3.y; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + applyMatrix3(m) { + const x2 = this.x, y3 = this.y; + const e = m.elements; + this.x = e[0] * x2 + e[3] * y3 + e[6]; + this.y = e[1] * x2 + e[4] * y3 + e[7]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + return this; + } + clamp(min, max) { + this.x = clamp3(this.x, min.x, max.x); + this.y = clamp3(this.y, min.y, max.y); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp3(this.x, minVal, maxVal); + this.y = clamp3(this.y, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp3(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y; + } + cross(v) { + return this.x * v.y - this.y * v.x; + } + lengthSq() { + return this.x * this.x + this.y * this.y; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + angle() { + const angle = Math.atan2(-this.y, -this.x) + Math.PI; + return angle; + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) + return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp3(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy2 = this.y - v.y; + return dx * dx + dy2 * dy2; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + return this; + } + lerpVectors(v12, v2, alpha) { + this.x = v12.x + (v2.x - v12.x) * alpha; + this.y = v12.y + (v2.y - v12.y) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + return this; + } + rotateAround(center, angle) { + const c2 = Math.cos(angle), s = Math.sin(angle); + const x2 = this.x - center.x; + const y3 = this.y - center.y; + this.x = x2 * c2 - y3 * s + center.x; + this.y = x2 * s + y3 * c2 + center.y; + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + } + } + + class Matrix32 { + constructor(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + Matrix32.prototype.isMatrix3 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n13, n21, n22, n23, n31, n32, n33); + } + } + set(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + const te3 = this.elements; + te3[0] = n11; + te3[1] = n21; + te3[2] = n31; + te3[3] = n12; + te3[4] = n22; + te3[5] = n32; + te3[6] = n13; + te3[7] = n23; + te3[8] = n33; + return this; + } + identity() { + this.set(1, 0, 0, 0, 1, 0, 0, 0, 1); + return this; + } + copy(m) { + const te3 = this.elements; + const me = m.elements; + te3[0] = me[0]; + te3[1] = me[1]; + te3[2] = me[2]; + te3[3] = me[3]; + te3[4] = me[4]; + te3[5] = me[5]; + te3[6] = me[6]; + te3[7] = me[7]; + te3[8] = me[8]; + return this; + } + extractBasis(xAxis2, yAxis2, zAxis2) { + xAxis2.setFromMatrix3Column(this, 0); + yAxis2.setFromMatrix3Column(this, 1); + zAxis2.setFromMatrix3Column(this, 2); + return this; + } + setFromMatrix4(m) { + const me = m.elements; + this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]); + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a2, b3) { + const ae3 = a2.elements; + const be = b3.elements; + const te3 = this.elements; + const a11 = ae3[0], a12 = ae3[3], a13 = ae3[6]; + const a21 = ae3[1], a22 = ae3[4], a23 = ae3[7]; + const a31 = ae3[2], a32 = ae3[5], a33 = ae3[8]; + const b11 = be[0], b12 = be[3], b13 = be[6]; + const b21 = be[1], b22 = be[4], b23 = be[7]; + const b31 = be[2], b32 = be[5], b33 = be[8]; + te3[0] = a11 * b11 + a12 * b21 + a13 * b31; + te3[3] = a11 * b12 + a12 * b22 + a13 * b32; + te3[6] = a11 * b13 + a12 * b23 + a13 * b33; + te3[1] = a21 * b11 + a22 * b21 + a23 * b31; + te3[4] = a21 * b12 + a22 * b22 + a23 * b32; + te3[7] = a21 * b13 + a22 * b23 + a23 * b33; + te3[2] = a31 * b11 + a32 * b21 + a33 * b31; + te3[5] = a31 * b12 + a32 * b22 + a33 * b32; + te3[8] = a31 * b13 + a32 * b23 + a33 * b33; + return this; + } + multiplyScalar(s) { + const te3 = this.elements; + te3[0] *= s; + te3[3] *= s; + te3[6] *= s; + te3[1] *= s; + te3[4] *= s; + te3[7] *= s; + te3[2] *= s; + te3[5] *= s; + te3[8] *= s; + return this; + } + determinant() { + const te3 = this.elements; + const a2 = te3[0], b3 = te3[1], c2 = te3[2], d = te3[3], e = te3[4], f = te3[5], g3 = te3[6], h = te3[7], i = te3[8]; + return a2 * e * i - a2 * f * h - b3 * d * i + b3 * f * g3 + c2 * d * h - c2 * e * g3; + } + invert() { + const te3 = this.elements, n11 = te3[0], n21 = te3[1], n31 = te3[2], n12 = te3[3], n22 = te3[4], n32 = te3[5], n13 = te3[6], n23 = te3[7], n33 = te3[8], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13; + if (det === 0) + return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te3[0] = t11 * detInv; + te3[1] = (n31 * n23 - n33 * n21) * detInv; + te3[2] = (n32 * n21 - n31 * n22) * detInv; + te3[3] = t12 * detInv; + te3[4] = (n33 * n11 - n31 * n13) * detInv; + te3[5] = (n31 * n12 - n32 * n11) * detInv; + te3[6] = t13 * detInv; + te3[7] = (n21 * n13 - n23 * n11) * detInv; + te3[8] = (n22 * n11 - n21 * n12) * detInv; + return this; + } + transpose() { + let tmp3; + const m = this.elements; + tmp3 = m[1]; + m[1] = m[3]; + m[3] = tmp3; + tmp3 = m[2]; + m[2] = m[6]; + m[6] = tmp3; + tmp3 = m[5]; + m[5] = m[7]; + m[7] = tmp3; + return this; + } + getNormalMatrix(matrix4) { + return this.setFromMatrix4(matrix4).invert().transpose(); + } + transposeIntoArray(r) { + const m = this.elements; + r[0] = m[0]; + r[1] = m[3]; + r[2] = m[6]; + r[3] = m[1]; + r[4] = m[4]; + r[5] = m[7]; + r[6] = m[2]; + r[7] = m[5]; + r[8] = m[8]; + return this; + } + setUvTransform(tx, ty2, sx, sy, rotation2, cx, cy) { + const c2 = Math.cos(rotation2); + const s = Math.sin(rotation2); + this.set(sx * c2, sx * s, -sx * (c2 * cx + s * cy) + cx + tx, -sy * s, sy * c2, -sy * (-s * cx + c2 * cy) + cy + ty2, 0, 0, 1); + return this; + } + scale(sx, sy) { + this.premultiply(_m32.makeScale(sx, sy)); + return this; + } + rotate(theta) { + this.premultiply(_m32.makeRotation(-theta)); + return this; + } + translate(tx, ty2) { + this.premultiply(_m32.makeTranslation(tx, ty2)); + return this; + } + makeTranslation(x2, y3) { + if (x2.isVector2) { + this.set(1, 0, x2.x, 0, 1, x2.y, 0, 0, 1); + } else { + this.set(1, 0, x2, 0, 1, y3, 0, 0, 1); + } + return this; + } + makeRotation(theta) { + const c2 = Math.cos(theta); + const s = Math.sin(theta); + this.set(c2, -s, 0, s, c2, 0, 0, 0, 1); + return this; + } + makeScale(x2, y3) { + this.set(x2, 0, 0, 0, y3, 0, 0, 0, 1); + return this; + } + equals(matrix3) { + const te3 = this.elements; + const me = matrix3.elements; + for (let i = 0;i < 9; i++) { + if (te3[i] !== me[i]) + return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 9; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te3 = this.elements; + array[offset] = te3[0]; + array[offset + 1] = te3[1]; + array[offset + 2] = te3[2]; + array[offset + 3] = te3[3]; + array[offset + 4] = te3[4]; + array[offset + 5] = te3[5]; + array[offset + 6] = te3[6]; + array[offset + 7] = te3[7]; + array[offset + 8] = te3[8]; + return array; + } + clone() { + return new this.constructor().fromArray(this.elements); + } + } + var _m32 = /* @__PURE__ */ new Matrix32; + function arrayNeedsUint322(array) { + for (let i = array.length - 1;i >= 0; --i) { + if (array[i] >= 65535) + return true; + } + return false; + } + var TYPED_ARRAYS2 = { + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array + }; + function getTypedArray2(type, buffer) { + return new TYPED_ARRAYS2[type](buffer); + } + function createElementNS2(name2) { + return document.createElementNS("http://www.w3.org/1999/xhtml", name2); + } + function createCanvasElement2() { + const canvas = createElementNS2("canvas"); + canvas.style.display = "block"; + return canvas; + } + var _cache2 = {}; + function warnOnce2(message) { + if (message in _cache2) + return; + _cache2[message] = true; + console.warn(message); + } + function probeAsync2(gl, sync, interval) { + return new Promise(function(resolve, reject2) { + function probe() { + switch (gl.clientWaitSync(sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0)) { + case gl.WAIT_FAILED: + reject2(); + break; + case gl.TIMEOUT_EXPIRED: + setTimeout(probe, interval); + break; + default: + resolve(); + } + } + setTimeout(probe, interval); + }); + } + function toNormalizedProjectionMatrix2(projectionMatrix) { + const m = projectionMatrix.elements; + m[2] = 0.5 * m[2] + 0.5 * m[3]; + m[6] = 0.5 * m[6] + 0.5 * m[7]; + m[10] = 0.5 * m[10] + 0.5 * m[11]; + m[14] = 0.5 * m[14] + 0.5 * m[15]; + } + function toReversedProjectionMatrix2(projectionMatrix) { + const m = projectionMatrix.elements; + const isPerspectiveMatrix = m[11] === -1; + if (isPerspectiveMatrix) { + m[10] = -m[10] - 1; + m[14] = -m[14]; + } else { + m[10] = -m[10]; + m[14] = -m[14] + 1; + } + } + var LINEAR_REC709_TO_XYZ2 = /* @__PURE__ */ new Matrix32().set(0.4123908, 0.3575843, 0.1804808, 0.212639, 0.7151687, 0.0721923, 0.0193308, 0.1191948, 0.9505322); + var XYZ_TO_LINEAR_REC7092 = /* @__PURE__ */ new Matrix32().set(3.2409699, -1.5373832, -0.4986108, -0.9692436, 1.8759675, 0.0415551, 0.0556301, -0.203977, 1.0569715); + function createColorManagement2() { + const ColorManagement3 = { + enabled: true, + workingColorSpace: LinearSRGBColorSpace2, + spaces: {}, + convert: function(color, sourceColorSpace, targetColorSpace) { + if (this.enabled === false || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) { + return color; + } + if (this.spaces[sourceColorSpace].transfer === SRGBTransfer2) { + color.r = SRGBToLinear2(color.r); + color.g = SRGBToLinear2(color.g); + color.b = SRGBToLinear2(color.b); + } + if (this.spaces[sourceColorSpace].primaries !== this.spaces[targetColorSpace].primaries) { + color.applyMatrix3(this.spaces[sourceColorSpace].toXYZ); + color.applyMatrix3(this.spaces[targetColorSpace].fromXYZ); + } + if (this.spaces[targetColorSpace].transfer === SRGBTransfer2) { + color.r = LinearToSRGB2(color.r); + color.g = LinearToSRGB2(color.g); + color.b = LinearToSRGB2(color.b); + } + return color; + }, + fromWorkingColorSpace: function(color, targetColorSpace) { + return this.convert(color, this.workingColorSpace, targetColorSpace); + }, + toWorkingColorSpace: function(color, sourceColorSpace) { + return this.convert(color, sourceColorSpace, this.workingColorSpace); + }, + getPrimaries: function(colorSpace) { + return this.spaces[colorSpace].primaries; + }, + getTransfer: function(colorSpace) { + if (colorSpace === NoColorSpace2) + return LinearTransfer2; + return this.spaces[colorSpace].transfer; + }, + getLuminanceCoefficients: function(target, colorSpace = this.workingColorSpace) { + return target.fromArray(this.spaces[colorSpace].luminanceCoefficients); + }, + define: function(colorSpaces) { + Object.assign(this.spaces, colorSpaces); + }, + _getMatrix: function(targetMatrix, sourceColorSpace, targetColorSpace) { + return targetMatrix.copy(this.spaces[sourceColorSpace].toXYZ).multiply(this.spaces[targetColorSpace].fromXYZ); + }, + _getDrawingBufferColorSpace: function(colorSpace) { + return this.spaces[colorSpace].outputColorSpaceConfig.drawingBufferColorSpace; + }, + _getUnpackColorSpace: function(colorSpace = this.workingColorSpace) { + return this.spaces[colorSpace].workingColorSpaceConfig.unpackColorSpace; + } + }; + const REC709_PRIMARIES = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06]; + const REC709_LUMINANCE_COEFFICIENTS = [0.2126, 0.7152, 0.0722]; + const D65 = [0.3127, 0.329]; + ColorManagement3.define({ + [LinearSRGBColorSpace2]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: LinearTransfer2, + toXYZ: LINEAR_REC709_TO_XYZ2, + fromXYZ: XYZ_TO_LINEAR_REC7092, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace2 }, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace2 } + }, + [SRGBColorSpace2]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: SRGBTransfer2, + toXYZ: LINEAR_REC709_TO_XYZ2, + fromXYZ: XYZ_TO_LINEAR_REC7092, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace2 } + } + }); + return ColorManagement3; + } + var ColorManagement2 = /* @__PURE__ */ createColorManagement2(); + function SRGBToLinear2(c2) { + return c2 < 0.04045 ? c2 * 0.0773993808 : Math.pow(c2 * 0.9478672986 + 0.0521327014, 2.4); + } + function LinearToSRGB2(c2) { + return c2 < 0.0031308 ? c2 * 12.92 : 1.055 * Math.pow(c2, 0.41666) - 0.055; + } + var _canvas2; + + class ImageUtils2 { + static getDataURL(image) { + if (/^data:/i.test(image.src)) { + return image.src; + } + if (typeof HTMLCanvasElement === "undefined") { + return image.src; + } + let canvas; + if (image instanceof HTMLCanvasElement) { + canvas = image; + } else { + if (_canvas2 === undefined) + _canvas2 = createElementNS2("canvas"); + _canvas2.width = image.width; + _canvas2.height = image.height; + const context = _canvas2.getContext("2d"); + if (image instanceof ImageData) { + context.putImageData(image, 0, 0); + } else { + context.drawImage(image, 0, 0, image.width, image.height); + } + canvas = _canvas2; + } + return canvas.toDataURL("image/png"); + } + static sRGBToLinear(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + const canvas = createElementNS2("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, image.width, image.height); + const imageData = context.getImageData(0, 0, image.width, image.height); + const data2 = imageData.data; + for (let i = 0;i < data2.length; i++) { + data2[i] = SRGBToLinear2(data2[i] / 255) * 255; + } + context.putImageData(imageData, 0, 0); + return canvas; + } else if (image.data) { + const data2 = image.data.slice(0); + for (let i = 0;i < data2.length; i++) { + if (data2 instanceof Uint8Array || data2 instanceof Uint8ClampedArray) { + data2[i] = Math.floor(SRGBToLinear2(data2[i] / 255) * 255); + } else { + data2[i] = SRGBToLinear2(data2[i]); + } + } + return { + data: data2, + width: image.width, + height: image.height + }; + } else { + console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."); + return image; + } + } + } + var _sourceId2 = 0; + + class Source2 { + constructor(data2 = null) { + this.isSource = true; + Object.defineProperty(this, "id", { value: _sourceId2++ }); + this.uuid = generateUUID2(); + this.data = data2; + this.dataReady = true; + this.version = 0; + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + toJSON(meta2) { + const isRootObject = meta2 === undefined || typeof meta2 === "string"; + if (!isRootObject && meta2.images[this.uuid] !== undefined) { + return meta2.images[this.uuid]; + } + const output = { + uuid: this.uuid, + url: "" + }; + const data2 = this.data; + if (data2 !== null) { + let url; + if (Array.isArray(data2)) { + url = []; + for (let i = 0, l2 = data2.length;i < l2; i++) { + if (data2[i].isDataTexture) { + url.push(serializeImage2(data2[i].image)); + } else { + url.push(serializeImage2(data2[i])); + } + } + } else { + url = serializeImage2(data2); + } + output.url = url; + } + if (!isRootObject) { + meta2.images[this.uuid] = output; + } + return output; + } + } + function serializeImage2(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + return ImageUtils2.getDataURL(image); + } else { + if (image.data) { + return { + data: Array.from(image.data), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; + } else { + console.warn("THREE.Texture: Unable to serialize Texture."); + return {}; + } + } + } + var _textureId2 = 0; + + class Texture2 extends EventDispatcher2 { + constructor(image = Texture2.DEFAULT_IMAGE, mapping = Texture2.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping2, wrapT = ClampToEdgeWrapping2, magFilter = LinearFilter2, minFilter = LinearMipmapLinearFilter2, format = RGBAFormat2, type = UnsignedByteType2, anisotropy = Texture2.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace2) { + super(); + this.isTexture = true; + Object.defineProperty(this, "id", { value: _textureId2++ }); + this.uuid = generateUUID2(); + this.name = ""; + this.source = new Source2(image); + this.mipmaps = []; + this.mapping = mapping; + this.channel = 0; + this.wrapS = wrapS; + this.wrapT = wrapT; + this.magFilter = magFilter; + this.minFilter = minFilter; + this.anisotropy = anisotropy; + this.format = format; + this.internalFormat = null; + this.type = type; + this.offset = new Vector22(0, 0); + this.repeat = new Vector22(1, 1); + this.center = new Vector22(0, 0); + this.rotation = 0; + this.matrixAutoUpdate = true; + this.matrix = new Matrix32; + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; + this.colorSpace = colorSpace; + this.userData = {}; + this.version = 0; + this.onUpdate = null; + this.renderTarget = null; + this.isRenderTargetTexture = false; + this.pmremVersion = 0; + } + get image() { + return this.source.data; + } + set image(value2 = null) { + this.source.data = value2; + } + updateMatrix() { + this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.source = source.source; + this.mipmaps = source.mipmaps.slice(0); + this.mapping = source.mapping; + this.channel = source.channel; + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + this.anisotropy = source.anisotropy; + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + this.offset.copy(source.offset); + this.repeat.copy(source.repeat); + this.center.copy(source.center); + this.rotation = source.rotation; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy(source.matrix); + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.colorSpace = source.colorSpace; + this.renderTarget = source.renderTarget; + this.isRenderTargetTexture = source.isRenderTargetTexture; + this.userData = JSON.parse(JSON.stringify(source.userData)); + this.needsUpdate = true; + return this; + } + toJSON(meta2) { + const isRootObject = meta2 === undefined || typeof meta2 === "string"; + if (!isRootObject && meta2.textures[this.uuid] !== undefined) { + return meta2.textures[this.uuid]; + } + const output = { + metadata: { + version: 4.6, + type: "Texture", + generator: "Texture.toJSON" + }, + uuid: this.uuid, + name: this.name, + image: this.source.toJSON(meta2).uuid, + mapping: this.mapping, + channel: this.channel, + repeat: [this.repeat.x, this.repeat.y], + offset: [this.offset.x, this.offset.y], + center: [this.center.x, this.center.y], + rotation: this.rotation, + wrap: [this.wrapS, this.wrapT], + format: this.format, + internalFormat: this.internalFormat, + type: this.type, + colorSpace: this.colorSpace, + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + flipY: this.flipY, + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + }; + if (Object.keys(this.userData).length > 0) + output.userData = this.userData; + if (!isRootObject) { + meta2.textures[this.uuid] = output; + } + return output; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + transformUv(uv) { + if (this.mapping !== UVMapping2) + return uv; + uv.applyMatrix3(this.matrix); + if (uv.x < 0 || uv.x > 1) { + switch (this.wrapS) { + case RepeatWrapping2: + uv.x = uv.x - Math.floor(uv.x); + break; + case ClampToEdgeWrapping2: + uv.x = uv.x < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping2: + if (Math.abs(Math.floor(uv.x) % 2) === 1) { + uv.x = Math.ceil(uv.x) - uv.x; + } else { + uv.x = uv.x - Math.floor(uv.x); + } + break; + } + } + if (uv.y < 0 || uv.y > 1) { + switch (this.wrapT) { + case RepeatWrapping2: + uv.y = uv.y - Math.floor(uv.y); + break; + case ClampToEdgeWrapping2: + uv.y = uv.y < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping2: + if (Math.abs(Math.floor(uv.y) % 2) === 1) { + uv.y = Math.ceil(uv.y) - uv.y; + } else { + uv.y = uv.y - Math.floor(uv.y); + } + break; + } + } + if (this.flipY) { + uv.y = 1 - uv.y; + } + return uv; + } + set needsUpdate(value2) { + if (value2 === true) { + this.version++; + this.source.needsUpdate = true; + } + } + set needsPMREMUpdate(value2) { + if (value2 === true) { + this.pmremVersion++; + } + } + } + Texture2.DEFAULT_IMAGE = null; + Texture2.DEFAULT_MAPPING = UVMapping2; + Texture2.DEFAULT_ANISOTROPY = 1; + + class Vector42 { + constructor(x2 = 0, y3 = 0, z2 = 0, w = 1) { + Vector42.prototype.isVector4 = true; + this.x = x2; + this.y = y3; + this.z = z2; + this.w = w; + } + get width() { + return this.z; + } + set width(value2) { + this.z = value2; + } + get height() { + return this.w; + } + set height(value2) { + this.w = value2; + } + set(x2, y3, z2, w) { + this.x = x2; + this.y = y3; + this.z = z2; + this.w = w; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + return this; + } + setX(x2) { + this.x = x2; + return this; + } + setY(y3) { + this.y = y3; + return this; + } + setZ(z2) { + this.z = z2; + return this; + } + setW(w) { + this.w = w; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + case 2: + this.z = value2; + break; + case 3: + this.w = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + case 3: + return this.w; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z, this.w); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = v.w !== undefined ? v.w : 1; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + this.w += s; + return this; + } + addVectors(a2, b3) { + this.x = a2.x + b3.x; + this.y = a2.y + b3.y; + this.z = a2.z + b3.z; + this.w = a2.w + b3.w; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; + return this; + } + subVectors(a2, b3) { + this.x = a2.x - b3.x; + this.y = a2.y - b3.y; + this.z = a2.z - b3.z; + this.w = a2.w - b3.w; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + return this; + } + applyMatrix4(m) { + const x2 = this.x, y3 = this.y, z2 = this.z, w = this.w; + const e = m.elements; + this.x = e[0] * x2 + e[4] * y3 + e[8] * z2 + e[12] * w; + this.y = e[1] * x2 + e[5] * y3 + e[9] * z2 + e[13] * w; + this.z = e[2] * x2 + e[6] * y3 + e[10] * z2 + e[14] * w; + this.w = e[3] * x2 + e[7] * y3 + e[11] * z2 + e[15] * w; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + this.w /= v.w; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + setAxisAngleFromQuaternion(q2) { + this.w = 2 * Math.acos(q2.w); + const s = Math.sqrt(1 - q2.w * q2.w); + if (s < 0.0001) { + this.x = 1; + this.y = 0; + this.z = 0; + } else { + this.x = q2.x / s; + this.y = q2.y / s; + this.z = q2.z / s; + } + return this; + } + setAxisAngleFromRotationMatrix(m) { + let angle, x2, y3, z2; + const epsilon = 0.01, epsilon2 = 0.1, te3 = m.elements, m11 = te3[0], m12 = te3[4], m13 = te3[8], m21 = te3[1], m22 = te3[5], m23 = te3[9], m31 = te3[2], m32 = te3[6], m33 = te3[10]; + if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) { + if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) { + this.set(1, 0, 0, 0); + return this; + } + angle = Math.PI; + const xx = (m11 + 1) / 2; + const yy2 = (m22 + 1) / 2; + const zz = (m33 + 1) / 2; + const xy2 = (m12 + m21) / 4; + const xz = (m13 + m31) / 4; + const yz = (m23 + m32) / 4; + if (xx > yy2 && xx > zz) { + if (xx < epsilon) { + x2 = 0; + y3 = 0.707106781; + z2 = 0.707106781; + } else { + x2 = Math.sqrt(xx); + y3 = xy2 / x2; + z2 = xz / x2; + } + } else if (yy2 > zz) { + if (yy2 < epsilon) { + x2 = 0.707106781; + y3 = 0; + z2 = 0.707106781; + } else { + y3 = Math.sqrt(yy2); + x2 = xy2 / y3; + z2 = yz / y3; + } + } else { + if (zz < epsilon) { + x2 = 0.707106781; + y3 = 0.707106781; + z2 = 0; + } else { + z2 = Math.sqrt(zz); + x2 = xz / z2; + y3 = yz / z2; + } + } + this.set(x2, y3, z2, angle); + return this; + } + let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); + if (Math.abs(s) < 0.001) + s = 1; + this.x = (m32 - m23) / s; + this.y = (m13 - m31) / s; + this.z = (m21 - m12) / s; + this.w = Math.acos((m11 + m22 + m33 - 1) / 2); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + this.w = e[15]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + this.w = Math.min(this.w, v.w); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + this.w = Math.max(this.w, v.w); + return this; + } + clamp(min, max) { + this.x = clamp3(this.x, min.x, max.x); + this.y = clamp3(this.y, min.y, max.y); + this.z = clamp3(this.z, min.z, max.z); + this.w = clamp3(this.w, min.w, max.w); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp3(this.x, minVal, maxVal); + this.y = clamp3(this.y, minVal, maxVal); + this.z = clamp3(this.z, minVal, maxVal); + this.w = clamp3(this.w, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp3(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + this.w = Math.floor(this.w); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + this.w = Math.ceil(this.w); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + this.w = Math.round(this.w); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + this.w = Math.trunc(this.w); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + this.w += (v.w - this.w) * alpha; + return this; + } + lerpVectors(v12, v2, alpha) { + this.x = v12.x + (v2.x - v12.x) * alpha; + this.y = v12.y + (v2.y - v12.y) * alpha; + this.z = v12.z + (v2.z - v12.z) * alpha; + this.w = v12.w + (v2.w - v12.w) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + this.w = array[offset + 3]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + array[offset + 3] = this.w; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + this.z = attribute.getZ(index2); + this.w = attribute.getW(index2); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + yield this.w; + } + } + + class RenderTarget2 extends EventDispatcher2 { + constructor(width2 = 1, height2 = 1, options = {}) { + super(); + this.isRenderTarget = true; + this.width = width2; + this.height = height2; + this.depth = 1; + this.scissor = new Vector42(0, 0, width2, height2); + this.scissorTest = false; + this.viewport = new Vector42(0, 0, width2, height2); + const image = { width: width2, height: height2, depth: 1 }; + options = Object.assign({ + generateMipmaps: false, + internalFormat: null, + minFilter: LinearFilter2, + depthBuffer: true, + stencilBuffer: false, + resolveDepthBuffer: true, + resolveStencilBuffer: true, + depthTexture: null, + samples: 0, + count: 1 + }, options); + const texture = new Texture2(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + texture.flipY = false; + texture.generateMipmaps = options.generateMipmaps; + texture.internalFormat = options.internalFormat; + this.textures = []; + const count = options.count; + for (let i = 0;i < count; i++) { + this.textures[i] = texture.clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + } + this.depthBuffer = options.depthBuffer; + this.stencilBuffer = options.stencilBuffer; + this.resolveDepthBuffer = options.resolveDepthBuffer; + this.resolveStencilBuffer = options.resolveStencilBuffer; + this._depthTexture = null; + this.depthTexture = options.depthTexture; + this.samples = options.samples; + } + get texture() { + return this.textures[0]; + } + set texture(value2) { + this.textures[0] = value2; + } + set depthTexture(current) { + if (this._depthTexture !== null) + this._depthTexture.renderTarget = null; + if (current !== null) + current.renderTarget = this; + this._depthTexture = current; + } + get depthTexture() { + return this._depthTexture; + } + setSize(width2, height2, depth = 1) { + if (this.width !== width2 || this.height !== height2 || this.depth !== depth) { + this.width = width2; + this.height = height2; + this.depth = depth; + for (let i = 0, il = this.textures.length;i < il; i++) { + this.textures[i].image.width = width2; + this.textures[i].image.height = height2; + this.textures[i].image.depth = depth; + } + this.dispose(); + } + this.viewport.set(0, 0, width2, height2); + this.scissor.set(0, 0, width2, height2); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + this.scissor.copy(source.scissor); + this.scissorTest = source.scissorTest; + this.viewport.copy(source.viewport); + this.textures.length = 0; + for (let i = 0, il = source.textures.length;i < il; i++) { + this.textures[i] = source.textures[i].clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + } + const image = Object.assign({}, source.texture.image); + this.texture.source = new Source2(image); + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.resolveDepthBuffer = source.resolveDepthBuffer; + this.resolveStencilBuffer = source.resolveStencilBuffer; + if (source.depthTexture !== null) + this.depthTexture = source.depthTexture.clone(); + this.samples = source.samples; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + } + + class WebGLRenderTarget2 extends RenderTarget2 { + constructor(width2 = 1, height2 = 1, options = {}) { + super(width2, height2, options); + this.isWebGLRenderTarget = true; + } + } + + class DataArrayTexture2 extends Texture2 { + constructor(data2 = null, width2 = 1, height2 = 1, depth = 1) { + super(null); + this.isDataArrayTexture = true; + this.image = { data: data2, width: width2, height: height2, depth }; + this.magFilter = NearestFilter2; + this.minFilter = NearestFilter2; + this.wrapR = ClampToEdgeWrapping2; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + this.layerUpdates = new Set; + } + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + clearLayerUpdates() { + this.layerUpdates.clear(); + } + } + + class WebGLArrayRenderTarget2 extends WebGLRenderTarget2 { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isWebGLArrayRenderTarget = true; + this.depth = depth; + this.texture = new DataArrayTexture2(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } + } + + class Data3DTexture2 extends Texture2 { + constructor(data2 = null, width2 = 1, height2 = 1, depth = 1) { + super(null); + this.isData3DTexture = true; + this.image = { data: data2, width: width2, height: height2, depth }; + this.magFilter = NearestFilter2; + this.minFilter = NearestFilter2; + this.wrapR = ClampToEdgeWrapping2; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } + } + + class WebGL3DRenderTarget2 extends WebGLRenderTarget2 { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isWebGL3DRenderTarget = true; + this.depth = depth; + this.texture = new Data3DTexture2(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } + } + + class Quaternion2 { + constructor(x2 = 0, y3 = 0, z2 = 0, w = 1) { + this.isQuaternion = true; + this._x = x2; + this._y = y3; + this._z = z2; + this._w = w; + } + static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t4) { + let x02 = src0[srcOffset0 + 0], y0 = src0[srcOffset0 + 1], z0 = src0[srcOffset0 + 2], w02 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1 + 0], y1 = src1[srcOffset1 + 1], z1 = src1[srcOffset1 + 2], w1 = src1[srcOffset1 + 3]; + if (t4 === 0) { + dst[dstOffset + 0] = x02; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w02; + return; + } + if (t4 === 1) { + dst[dstOffset + 0] = x1; + dst[dstOffset + 1] = y1; + dst[dstOffset + 2] = z1; + dst[dstOffset + 3] = w1; + return; + } + if (w02 !== w1 || x02 !== x1 || y0 !== y1 || z0 !== z1) { + let s = 1 - t4; + const cos = x02 * x1 + y0 * y1 + z0 * z1 + w02 * w1, dir = cos >= 0 ? 1 : -1, sqrSin = 1 - cos * cos; + if (sqrSin > Number.EPSILON) { + const sin = Math.sqrt(sqrSin), len = Math.atan2(sin, cos * dir); + s = Math.sin(s * len) / sin; + t4 = Math.sin(t4 * len) / sin; + } + const tDir = t4 * dir; + x02 = x02 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w02 = w02 * s + w1 * tDir; + if (s === 1 - t4) { + const f = 1 / Math.sqrt(x02 * x02 + y0 * y0 + z0 * z0 + w02 * w02); + x02 *= f; + y0 *= f; + z0 *= f; + w02 *= f; + } + } + dst[dstOffset] = x02; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w02; + } + static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) { + const x02 = src0[srcOffset0]; + const y0 = src0[srcOffset0 + 1]; + const z0 = src0[srcOffset0 + 2]; + const w02 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1]; + const y1 = src1[srcOffset1 + 1]; + const z1 = src1[srcOffset1 + 2]; + const w1 = src1[srcOffset1 + 3]; + dst[dstOffset] = x02 * w1 + w02 * x1 + y0 * z1 - z0 * y1; + dst[dstOffset + 1] = y0 * w1 + w02 * y1 + z0 * x1 - x02 * z1; + dst[dstOffset + 2] = z0 * w1 + w02 * z1 + x02 * y1 - y0 * x1; + dst[dstOffset + 3] = w02 * w1 - x02 * x1 - y0 * y1 - z0 * z1; + return dst; + } + get x() { + return this._x; + } + set x(value2) { + this._x = value2; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value2) { + this._y = value2; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value2) { + this._z = value2; + this._onChangeCallback(); + } + get w() { + return this._w; + } + set w(value2) { + this._w = value2; + this._onChangeCallback(); + } + set(x2, y3, z2, w) { + this._x = x2; + this._y = y3; + this._z = z2; + this._w = w; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._w); + } + copy(quaternion) { + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + this._onChangeCallback(); + return this; + } + setFromEuler(euler, update = true) { + const { _x: x2, _y: y3, _z: z2, _order: order } = euler; + const cos = Math.cos; + const sin = Math.sin; + const c1 = cos(x2 / 2); + const c2 = cos(y3 / 2); + const c3 = cos(z2 / 2); + const s1 = sin(x2 / 2); + const s22 = sin(y3 / 2); + const s3 = sin(z2 / 2); + switch (order) { + case "XYZ": + this._x = s1 * c2 * c3 + c1 * s22 * s3; + this._y = c1 * s22 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s22 * c3; + this._w = c1 * c2 * c3 - s1 * s22 * s3; + break; + case "YXZ": + this._x = s1 * c2 * c3 + c1 * s22 * s3; + this._y = c1 * s22 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s22 * c3; + this._w = c1 * c2 * c3 + s1 * s22 * s3; + break; + case "ZXY": + this._x = s1 * c2 * c3 - c1 * s22 * s3; + this._y = c1 * s22 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s22 * c3; + this._w = c1 * c2 * c3 - s1 * s22 * s3; + break; + case "ZYX": + this._x = s1 * c2 * c3 - c1 * s22 * s3; + this._y = c1 * s22 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s22 * c3; + this._w = c1 * c2 * c3 + s1 * s22 * s3; + break; + case "YZX": + this._x = s1 * c2 * c3 + c1 * s22 * s3; + this._y = c1 * s22 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s22 * c3; + this._w = c1 * c2 * c3 - s1 * s22 * s3; + break; + case "XZY": + this._x = s1 * c2 * c3 - c1 * s22 * s3; + this._y = c1 * s22 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s22 * c3; + this._w = c1 * c2 * c3 + s1 * s22 * s3; + break; + default: + console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + order); + } + if (update === true) + this._onChangeCallback(); + return this; + } + setFromAxisAngle(axis, angle) { + const halfAngle = angle / 2, s = Math.sin(halfAngle); + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos(halfAngle); + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m) { + const te3 = m.elements, m11 = te3[0], m12 = te3[4], m13 = te3[8], m21 = te3[1], m22 = te3[5], m23 = te3[9], m31 = te3[2], m32 = te3[6], m33 = te3[10], trace = m11 + m22 + m33; + if (trace > 0) { + const s = 0.5 / Math.sqrt(trace + 1); + this._w = 0.25 / s; + this._x = (m32 - m23) * s; + this._y = (m13 - m31) * s; + this._z = (m21 - m12) * s; + } else if (m11 > m22 && m11 > m33) { + const s = 2 * Math.sqrt(1 + m11 - m22 - m33); + this._w = (m32 - m23) / s; + this._x = 0.25 * s; + this._y = (m12 + m21) / s; + this._z = (m13 + m31) / s; + } else if (m22 > m33) { + const s = 2 * Math.sqrt(1 + m22 - m11 - m33); + this._w = (m13 - m31) / s; + this._x = (m12 + m21) / s; + this._y = 0.25 * s; + this._z = (m23 + m32) / s; + } else { + const s = 2 * Math.sqrt(1 + m33 - m11 - m22); + this._w = (m21 - m12) / s; + this._x = (m13 + m31) / s; + this._y = (m23 + m32) / s; + this._z = 0.25 * s; + } + this._onChangeCallback(); + return this; + } + setFromUnitVectors(vFrom, vTo) { + let r = vFrom.dot(vTo) + 1; + if (r < Number.EPSILON) { + r = 0; + if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) { + this._x = -vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + } else { + this._x = 0; + this._y = -vFrom.z; + this._z = vFrom.y; + this._w = r; + } + } else { + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + } + return this.normalize(); + } + angleTo(q2) { + return 2 * Math.acos(Math.abs(clamp3(this.dot(q2), -1, 1))); + } + rotateTowards(q2, step) { + const angle = this.angleTo(q2); + if (angle === 0) + return this; + const t4 = Math.min(1, step / angle); + this.slerp(q2, t4); + return this; + } + identity() { + return this.set(0, 0, 0, 1); + } + invert() { + return this.conjugate(); + } + conjugate() { + this._x *= -1; + this._y *= -1; + this._z *= -1; + this._onChangeCallback(); + return this; + } + dot(v) { + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + } + lengthSq() { + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + } + length() { + return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); + } + normalize() { + let l2 = this.length(); + if (l2 === 0) { + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + } else { + l2 = 1 / l2; + this._x = this._x * l2; + this._y = this._y * l2; + this._z = this._z * l2; + this._w = this._w * l2; + } + this._onChangeCallback(); + return this; + } + multiply(q2) { + return this.multiplyQuaternions(this, q2); + } + premultiply(q2) { + return this.multiplyQuaternions(q2, this); + } + multiplyQuaternions(a2, b3) { + const { _x: qax, _y: qay, _z: qaz, _w: qaw } = a2; + const { _x: qbx, _y: qby, _z: qbz, _w: qbw } = b3; + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + this._onChangeCallback(); + return this; + } + slerp(qb, t4) { + if (t4 === 0) + return this; + if (t4 === 1) + return this.copy(qb); + const x2 = this._x, y3 = this._y, z2 = this._z, w = this._w; + let cosHalfTheta = w * qb._w + x2 * qb._x + y3 * qb._y + z2 * qb._z; + if (cosHalfTheta < 0) { + this._w = -qb._w; + this._x = -qb._x; + this._y = -qb._y; + this._z = -qb._z; + cosHalfTheta = -cosHalfTheta; + } else { + this.copy(qb); + } + if (cosHalfTheta >= 1) { + this._w = w; + this._x = x2; + this._y = y3; + this._z = z2; + return this; + } + const sqrSinHalfTheta = 1 - cosHalfTheta * cosHalfTheta; + if (sqrSinHalfTheta <= Number.EPSILON) { + const s = 1 - t4; + this._w = s * w + t4 * this._w; + this._x = s * x2 + t4 * this._x; + this._y = s * y3 + t4 * this._y; + this._z = s * z2 + t4 * this._z; + this.normalize(); + return this; + } + const sinHalfTheta = Math.sqrt(sqrSinHalfTheta); + const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta); + const ratioA = Math.sin((1 - t4) * halfTheta) / sinHalfTheta, ratioB = Math.sin(t4 * halfTheta) / sinHalfTheta; + this._w = w * ratioA + this._w * ratioB; + this._x = x2 * ratioA + this._x * ratioB; + this._y = y3 * ratioA + this._y * ratioB; + this._z = z2 * ratioA + this._z * ratioB; + this._onChangeCallback(); + return this; + } + slerpQuaternions(qa, qb, t4) { + return this.copy(qa).slerp(qb, t4); + } + random() { + const theta1 = 2 * Math.PI * Math.random(); + const theta2 = 2 * Math.PI * Math.random(); + const x02 = Math.random(); + const r1 = Math.sqrt(1 - x02); + const r2 = Math.sqrt(x02); + return this.set(r1 * Math.sin(theta1), r1 * Math.cos(theta1), r2 * Math.sin(theta2), r2 * Math.cos(theta2)); + } + equals(quaternion) { + return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w; + } + fromArray(array, offset = 0) { + this._x = array[offset]; + this._y = array[offset + 1]; + this._z = array[offset + 2]; + this._w = array[offset + 3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._w; + return array; + } + fromBufferAttribute(attribute, index2) { + this._x = attribute.getX(index2); + this._y = attribute.getY(index2); + this._z = attribute.getZ(index2); + this._w = attribute.getW(index2); + this._onChangeCallback(); + return this; + } + toJSON() { + return this.toArray(); + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._w; + } + } + + class Vector32 { + constructor(x2 = 0, y3 = 0, z2 = 0) { + Vector32.prototype.isVector3 = true; + this.x = x2; + this.y = y3; + this.z = z2; + } + set(x2, y3, z2) { + if (z2 === undefined) + z2 = this.z; + this.x = x2; + this.y = y3; + this.z = z2; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + return this; + } + setX(x2) { + this.x = x2; + return this; + } + setY(y3) { + this.y = y3; + return this; + } + setZ(z2) { + this.z = z2; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + case 2: + this.z = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + return this; + } + addVectors(a2, b3) { + this.x = a2.x + b3.x; + this.y = a2.y + b3.y; + this.z = a2.z + b3.z; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + return this; + } + subVectors(a2, b3) { + this.x = a2.x - b3.x; + this.y = a2.y - b3.y; + this.z = a2.z - b3.z; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + return this; + } + multiplyVectors(a2, b3) { + this.x = a2.x * b3.x; + this.y = a2.y * b3.y; + this.z = a2.z * b3.z; + return this; + } + applyEuler(euler) { + return this.applyQuaternion(_quaternion$42.setFromEuler(euler)); + } + applyAxisAngle(axis, angle) { + return this.applyQuaternion(_quaternion$42.setFromAxisAngle(axis, angle)); + } + applyMatrix3(m) { + const x2 = this.x, y3 = this.y, z2 = this.z; + const e = m.elements; + this.x = e[0] * x2 + e[3] * y3 + e[6] * z2; + this.y = e[1] * x2 + e[4] * y3 + e[7] * z2; + this.z = e[2] * x2 + e[5] * y3 + e[8] * z2; + return this; + } + applyNormalMatrix(m) { + return this.applyMatrix3(m).normalize(); + } + applyMatrix4(m) { + const x2 = this.x, y3 = this.y, z2 = this.z; + const e = m.elements; + const w = 1 / (e[3] * x2 + e[7] * y3 + e[11] * z2 + e[15]); + this.x = (e[0] * x2 + e[4] * y3 + e[8] * z2 + e[12]) * w; + this.y = (e[1] * x2 + e[5] * y3 + e[9] * z2 + e[13]) * w; + this.z = (e[2] * x2 + e[6] * y3 + e[10] * z2 + e[14]) * w; + return this; + } + applyQuaternion(q2) { + const vx = this.x, vy2 = this.y, vz = this.z; + const { x: qx, y: qy, z: qz, w: qw } = q2; + const tx = 2 * (qy * vz - qz * vy2); + const ty2 = 2 * (qz * vx - qx * vz); + const tz = 2 * (qx * vy2 - qy * vx); + this.x = vx + qw * tx + qy * tz - qz * ty2; + this.y = vy2 + qw * ty2 + qz * tx - qx * tz; + this.z = vz + qw * tz + qx * ty2 - qy * tx; + return this; + } + project(camera) { + return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix); + } + unproject(camera) { + return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld); + } + transformDirection(m) { + const x2 = this.x, y3 = this.y, z2 = this.z; + const e = m.elements; + this.x = e[0] * x2 + e[4] * y3 + e[8] * z2; + this.y = e[1] * x2 + e[5] * y3 + e[9] * z2; + this.z = e[2] * x2 + e[6] * y3 + e[10] * z2; + return this.normalize(); + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + return this; + } + clamp(min, max) { + this.x = clamp3(this.x, min.x, max.x); + this.y = clamp3(this.y, min.y, max.y); + this.z = clamp3(this.z, min.z, max.z); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp3(this.x, minVal, maxVal); + this.y = clamp3(this.y, minVal, maxVal); + this.z = clamp3(this.z, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp3(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + return this; + } + lerpVectors(v12, v2, alpha) { + this.x = v12.x + (v2.x - v12.x) * alpha; + this.y = v12.y + (v2.y - v12.y) * alpha; + this.z = v12.z + (v2.z - v12.z) * alpha; + return this; + } + cross(v) { + return this.crossVectors(this, v); + } + crossVectors(a2, b3) { + const { x: ax, y: ay, z: az } = a2; + const { x: bx, y: by, z: bz } = b3; + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + return this; + } + projectOnVector(v) { + const denominator = v.lengthSq(); + if (denominator === 0) + return this.set(0, 0, 0); + const scalar = v.dot(this) / denominator; + return this.copy(v).multiplyScalar(scalar); + } + projectOnPlane(planeNormal) { + _vector$c2.copy(this).projectOnVector(planeNormal); + return this.sub(_vector$c2); + } + reflect(normal) { + return this.sub(_vector$c2.copy(normal).multiplyScalar(2 * this.dot(normal))); + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) + return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp3(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy2 = this.y - v.y, dz = this.z - v.z; + return dx * dx + dy2 * dy2 + dz * dz; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z); + } + setFromSpherical(s) { + return this.setFromSphericalCoords(s.radius, s.phi, s.theta); + } + setFromSphericalCoords(radius, phi, theta) { + const sinPhiRadius = Math.sin(phi) * radius; + this.x = sinPhiRadius * Math.sin(theta); + this.y = Math.cos(phi) * radius; + this.z = sinPhiRadius * Math.cos(theta); + return this; + } + setFromCylindrical(c2) { + return this.setFromCylindricalCoords(c2.radius, c2.theta, c2.y); + } + setFromCylindricalCoords(radius, theta, y3) { + this.x = radius * Math.sin(theta); + this.y = y3; + this.z = radius * Math.cos(theta); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + return this; + } + setFromMatrixScale(m) { + const sx = this.setFromMatrixColumn(m, 0).length(); + const sy = this.setFromMatrixColumn(m, 1).length(); + const sz = this.setFromMatrixColumn(m, 2).length(); + this.x = sx; + this.y = sy; + this.z = sz; + return this; + } + setFromMatrixColumn(m, index2) { + return this.fromArray(m.elements, index2 * 4); + } + setFromMatrix3Column(m, index2) { + return this.fromArray(m.elements, index2 * 3); + } + setFromEuler(e) { + this.x = e._x; + this.y = e._y; + this.z = e._z; + return this; + } + setFromColor(c2) { + this.x = c2.r; + this.y = c2.g; + this.z = c2.b; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + this.z = attribute.getZ(index2); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + return this; + } + randomDirection() { + const theta = Math.random() * Math.PI * 2; + const u3 = Math.random() * 2 - 1; + const c2 = Math.sqrt(1 - u3 * u3); + this.x = c2 * Math.cos(theta); + this.y = u3; + this.z = c2 * Math.sin(theta); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + } + } + var _vector$c2 = /* @__PURE__ */ new Vector32; + var _quaternion$42 = /* @__PURE__ */ new Quaternion2; + + class Box32 { + constructor(min = new Vector32(Infinity, Infinity, Infinity), max = new Vector32(-Infinity, -Infinity, -Infinity)) { + this.isBox3 = true; + this.min = min; + this.max = max; + } + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + setFromArray(array) { + this.makeEmpty(); + for (let i = 0, il = array.length;i < il; i += 3) { + this.expandByPoint(_vector$b2.fromArray(array, i)); + } + return this; + } + setFromBufferAttribute(attribute) { + this.makeEmpty(); + for (let i = 0, il = attribute.count;i < il; i++) { + this.expandByPoint(_vector$b2.fromBufferAttribute(attribute, i)); + } + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length;i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size2) { + const halfSize = _vector$b2.copy(size2).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + setFromObject(object, precise = false) { + this.makeEmpty(); + return this.expandByObject(object, precise); + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = this.min.z = Infinity; + this.max.x = this.max.y = this.max.z = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + expandByObject(object, precise = false) { + object.updateWorldMatrix(false, false); + const geometry = object.geometry; + if (geometry !== undefined) { + const positionAttribute = geometry.getAttribute("position"); + if (precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true) { + for (let i = 0, l2 = positionAttribute.count;i < l2; i++) { + if (object.isMesh === true) { + object.getVertexPosition(i, _vector$b2); + } else { + _vector$b2.fromBufferAttribute(positionAttribute, i); + } + _vector$b2.applyMatrix4(object.matrixWorld); + this.expandByPoint(_vector$b2); + } + } else { + if (object.boundingBox !== undefined) { + if (object.boundingBox === null) { + object.computeBoundingBox(); + } + _box$42.copy(object.boundingBox); + } else { + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + _box$42.copy(geometry.boundingBox); + } + _box$42.applyMatrix4(object.matrixWorld); + this.union(_box$42); + } + } + const children = object.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + this.expandByObject(children[i], precise); + } + return this; + } + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y && point.z >= this.min.z && point.z <= this.max.z; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z; + } + getParameter(point, target) { + return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z)); + } + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y && box.max.z >= this.min.z && box.min.z <= this.max.z; + } + intersectsSphere(sphere) { + this.clampPoint(sphere.center, _vector$b2); + return _vector$b2.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; + } + intersectsPlane(plane) { + let min, max; + if (plane.normal.x > 0) { + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + } else { + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + } + if (plane.normal.y > 0) { + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + } else { + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + } + if (plane.normal.z > 0) { + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + } else { + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + } + return min <= -plane.constant && max >= -plane.constant; + } + intersectsTriangle(triangle) { + if (this.isEmpty()) { + return false; + } + this.getCenter(_center4); + _extents2.subVectors(this.max, _center4); + _v0$3.subVectors(triangle.a, _center4); + _v1$72.subVectors(triangle.b, _center4); + _v2$42.subVectors(triangle.c, _center4); + _f02.subVectors(_v1$72, _v0$3); + _f12.subVectors(_v2$42, _v1$72); + _f22.subVectors(_v0$3, _v2$42); + let axes = [ + 0, + -_f02.z, + _f02.y, + 0, + -_f12.z, + _f12.y, + 0, + -_f22.z, + _f22.y, + _f02.z, + 0, + -_f02.x, + _f12.z, + 0, + -_f12.x, + _f22.z, + 0, + -_f22.x, + -_f02.y, + _f02.x, + 0, + -_f12.y, + _f12.x, + 0, + -_f22.y, + _f22.x, + 0 + ]; + if (!satForAxes2(axes, _v0$3, _v1$72, _v2$42, _extents2)) { + return false; + } + axes = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + if (!satForAxes2(axes, _v0$3, _v1$72, _v2$42, _extents2)) { + return false; + } + _triangleNormal2.crossVectors(_f02, _f12); + axes = [_triangleNormal2.x, _triangleNormal2.y, _triangleNormal2.z]; + return satForAxes2(axes, _v0$3, _v1$72, _v2$42, _extents2); + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$b2).distanceTo(point); + } + getBoundingSphere(target) { + if (this.isEmpty()) { + target.makeEmpty(); + } else { + this.getCenter(target.center); + target.radius = this.getSize(_vector$b2).length() * 0.5; + } + return target; + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) + this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + applyMatrix4(matrix3) { + if (this.isEmpty()) + return this; + _points2[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix3); + _points2[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix3); + _points2[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix3); + _points2[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix3); + _points2[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix3); + _points2[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix3); + _points2[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix3); + _points2[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix3); + this.setFromPoints(_points2); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } + } + var _points2 = [ + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32 + ]; + var _vector$b2 = /* @__PURE__ */ new Vector32; + var _box$42 = /* @__PURE__ */ new Box32; + var _v0$3 = /* @__PURE__ */ new Vector32; + var _v1$72 = /* @__PURE__ */ new Vector32; + var _v2$42 = /* @__PURE__ */ new Vector32; + var _f02 = /* @__PURE__ */ new Vector32; + var _f12 = /* @__PURE__ */ new Vector32; + var _f22 = /* @__PURE__ */ new Vector32; + var _center4 = /* @__PURE__ */ new Vector32; + var _extents2 = /* @__PURE__ */ new Vector32; + var _triangleNormal2 = /* @__PURE__ */ new Vector32; + var _testAxis2 = /* @__PURE__ */ new Vector32; + function satForAxes2(axes, v0, v12, v2, extents) { + for (let i = 0, j2 = axes.length - 3;i <= j2; i += 3) { + _testAxis2.fromArray(axes, i); + const r = extents.x * Math.abs(_testAxis2.x) + extents.y * Math.abs(_testAxis2.y) + extents.z * Math.abs(_testAxis2.z); + const p0 = v0.dot(_testAxis2); + const p1 = v12.dot(_testAxis2); + const p2 = v2.dot(_testAxis2); + if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) { + return false; + } + } + return true; + } + var _box$32 = /* @__PURE__ */ new Box32; + var _v1$62 = /* @__PURE__ */ new Vector32; + var _v2$32 = /* @__PURE__ */ new Vector32; + + class Sphere2 { + constructor(center = new Vector32, radius = -1) { + this.isSphere = true; + this.center = center; + this.radius = radius; + } + set(center, radius) { + this.center.copy(center); + this.radius = radius; + return this; + } + setFromPoints(points, optionalCenter) { + const center = this.center; + if (optionalCenter !== undefined) { + center.copy(optionalCenter); + } else { + _box$32.setFromPoints(points).getCenter(center); + } + let maxRadiusSq = 0; + for (let i = 0, il = points.length;i < il; i++) { + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i])); + } + this.radius = Math.sqrt(maxRadiusSq); + return this; + } + copy(sphere) { + this.center.copy(sphere.center); + this.radius = sphere.radius; + return this; + } + isEmpty() { + return this.radius < 0; + } + makeEmpty() { + this.center.set(0, 0, 0); + this.radius = -1; + return this; + } + containsPoint(point) { + return point.distanceToSquared(this.center) <= this.radius * this.radius; + } + distanceToPoint(point) { + return point.distanceTo(this.center) - this.radius; + } + intersectsSphere(sphere) { + const radiusSum = this.radius + sphere.radius; + return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum; + } + intersectsBox(box) { + return box.intersectsSphere(this); + } + intersectsPlane(plane) { + return Math.abs(plane.distanceToPoint(this.center)) <= this.radius; + } + clampPoint(point, target) { + const deltaLengthSq = this.center.distanceToSquared(point); + target.copy(point); + if (deltaLengthSq > this.radius * this.radius) { + target.sub(this.center).normalize(); + target.multiplyScalar(this.radius).add(this.center); + } + return target; + } + getBoundingBox(target) { + if (this.isEmpty()) { + target.makeEmpty(); + return target; + } + target.set(this.center, this.center); + target.expandByScalar(this.radius); + return target; + } + applyMatrix4(matrix3) { + this.center.applyMatrix4(matrix3); + this.radius = this.radius * matrix3.getMaxScaleOnAxis(); + return this; + } + translate(offset) { + this.center.add(offset); + return this; + } + expandByPoint(point) { + if (this.isEmpty()) { + this.center.copy(point); + this.radius = 0; + return this; + } + _v1$62.subVectors(point, this.center); + const lengthSq = _v1$62.lengthSq(); + if (lengthSq > this.radius * this.radius) { + const length2 = Math.sqrt(lengthSq); + const delta = (length2 - this.radius) * 0.5; + this.center.addScaledVector(_v1$62, delta / length2); + this.radius += delta; + } + return this; + } + union(sphere) { + if (sphere.isEmpty()) { + return this; + } + if (this.isEmpty()) { + this.copy(sphere); + return this; + } + if (this.center.equals(sphere.center) === true) { + this.radius = Math.max(this.radius, sphere.radius); + } else { + _v2$32.subVectors(sphere.center, this.center).setLength(sphere.radius); + this.expandByPoint(_v1$62.copy(sphere.center).add(_v2$32)); + this.expandByPoint(_v1$62.copy(sphere.center).sub(_v2$32)); + } + return this; + } + equals(sphere) { + return sphere.center.equals(this.center) && sphere.radius === this.radius; + } + clone() { + return new this.constructor().copy(this); + } + } + var _vector$a2 = /* @__PURE__ */ new Vector32; + var _segCenter2 = /* @__PURE__ */ new Vector32; + var _segDir2 = /* @__PURE__ */ new Vector32; + var _diff3 = /* @__PURE__ */ new Vector32; + var _edge12 = /* @__PURE__ */ new Vector32; + var _edge22 = /* @__PURE__ */ new Vector32; + var _normal$12 = /* @__PURE__ */ new Vector32; + + class Ray2 { + constructor(origin = new Vector32, direction = new Vector32(0, 0, -1)) { + this.origin = origin; + this.direction = direction; + } + set(origin, direction) { + this.origin.copy(origin); + this.direction.copy(direction); + return this; + } + copy(ray) { + this.origin.copy(ray.origin); + this.direction.copy(ray.direction); + return this; + } + at(t4, target) { + return target.copy(this.origin).addScaledVector(this.direction, t4); + } + lookAt(v) { + this.direction.copy(v).sub(this.origin).normalize(); + return this; + } + recast(t4) { + this.origin.copy(this.at(t4, _vector$a2)); + return this; + } + closestPointToPoint(point, target) { + target.subVectors(point, this.origin); + const directionDistance = target.dot(this.direction); + if (directionDistance < 0) { + return target.copy(this.origin); + } + return target.copy(this.origin).addScaledVector(this.direction, directionDistance); + } + distanceToPoint(point) { + return Math.sqrt(this.distanceSqToPoint(point)); + } + distanceSqToPoint(point) { + const directionDistance = _vector$a2.subVectors(point, this.origin).dot(this.direction); + if (directionDistance < 0) { + return this.origin.distanceToSquared(point); + } + _vector$a2.copy(this.origin).addScaledVector(this.direction, directionDistance); + return _vector$a2.distanceToSquared(point); + } + distanceSqToSegment(v0, v12, optionalPointOnRay, optionalPointOnSegment) { + _segCenter2.copy(v0).add(v12).multiplyScalar(0.5); + _segDir2.copy(v12).sub(v0).normalize(); + _diff3.copy(this.origin).sub(_segCenter2); + const segExtent = v0.distanceTo(v12) * 0.5; + const a01 = -this.direction.dot(_segDir2); + const b0 = _diff3.dot(this.direction); + const b1 = -_diff3.dot(_segDir2); + const c2 = _diff3.lengthSq(); + const det = Math.abs(1 - a01 * a01); + let s0, s1, sqrDist, extDet; + if (det > 0) { + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + if (s0 >= 0) { + if (s1 >= -extDet) { + if (s1 <= extDet) { + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c2; + } else { + s1 = segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2; + } + } else { + s1 = -segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2; + } + } else { + if (s1 <= -extDet) { + s0 = Math.max(0, -(-a01 * segExtent + b0)); + s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2; + } else if (s1 <= extDet) { + s0 = 0; + s1 = Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = s1 * (s1 + 2 * b1) + c2; + } else { + s0 = Math.max(0, -(a01 * segExtent + b0)); + s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2; + } + } + } else { + s1 = a01 > 0 ? -segExtent : segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2; + } + if (optionalPointOnRay) { + optionalPointOnRay.copy(this.origin).addScaledVector(this.direction, s0); + } + if (optionalPointOnSegment) { + optionalPointOnSegment.copy(_segCenter2).addScaledVector(_segDir2, s1); + } + return sqrDist; + } + intersectSphere(sphere, target) { + _vector$a2.subVectors(sphere.center, this.origin); + const tca = _vector$a2.dot(this.direction); + const d2 = _vector$a2.dot(_vector$a2) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + if (d2 > radius2) + return null; + const thc = Math.sqrt(radius2 - d2); + const t02 = tca - thc; + const t1 = tca + thc; + if (t1 < 0) + return null; + if (t02 < 0) + return this.at(t1, target); + return this.at(t02, target); + } + intersectsSphere(sphere) { + return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius; + } + distanceToPlane(plane) { + const denominator = plane.normal.dot(this.direction); + if (denominator === 0) { + if (plane.distanceToPoint(this.origin) === 0) { + return 0; + } + return null; + } + const t4 = -(this.origin.dot(plane.normal) + plane.constant) / denominator; + return t4 >= 0 ? t4 : null; + } + intersectPlane(plane, target) { + const t4 = this.distanceToPlane(plane); + if (t4 === null) { + return null; + } + return this.at(t4, target); + } + intersectsPlane(plane) { + const distToPoint = plane.distanceToPoint(this.origin); + if (distToPoint === 0) { + return true; + } + const denominator = plane.normal.dot(this.direction); + if (denominator * distToPoint < 0) { + return true; + } + return false; + } + intersectBox(box, target) { + let tmin, tmax, tymin, tymax, tzmin, tzmax; + const invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z; + const origin = this.origin; + if (invdirx >= 0) { + tmin = (box.min.x - origin.x) * invdirx; + tmax = (box.max.x - origin.x) * invdirx; + } else { + tmin = (box.max.x - origin.x) * invdirx; + tmax = (box.min.x - origin.x) * invdirx; + } + if (invdiry >= 0) { + tymin = (box.min.y - origin.y) * invdiry; + tymax = (box.max.y - origin.y) * invdiry; + } else { + tymin = (box.max.y - origin.y) * invdiry; + tymax = (box.min.y - origin.y) * invdiry; + } + if (tmin > tymax || tymin > tmax) + return null; + if (tymin > tmin || isNaN(tmin)) + tmin = tymin; + if (tymax < tmax || isNaN(tmax)) + tmax = tymax; + if (invdirz >= 0) { + tzmin = (box.min.z - origin.z) * invdirz; + tzmax = (box.max.z - origin.z) * invdirz; + } else { + tzmin = (box.max.z - origin.z) * invdirz; + tzmax = (box.min.z - origin.z) * invdirz; + } + if (tmin > tzmax || tzmin > tmax) + return null; + if (tzmin > tmin || tmin !== tmin) + tmin = tzmin; + if (tzmax < tmax || tmax !== tmax) + tmax = tzmax; + if (tmax < 0) + return null; + return this.at(tmin >= 0 ? tmin : tmax, target); + } + intersectsBox(box) { + return this.intersectBox(box, _vector$a2) !== null; + } + intersectTriangle(a2, b3, c2, backfaceCulling, target) { + _edge12.subVectors(b3, a2); + _edge22.subVectors(c2, a2); + _normal$12.crossVectors(_edge12, _edge22); + let DdN = this.direction.dot(_normal$12); + let sign3; + if (DdN > 0) { + if (backfaceCulling) + return null; + sign3 = 1; + } else if (DdN < 0) { + sign3 = -1; + DdN = -DdN; + } else { + return null; + } + _diff3.subVectors(this.origin, a2); + const DdQxE2 = sign3 * this.direction.dot(_edge22.crossVectors(_diff3, _edge22)); + if (DdQxE2 < 0) { + return null; + } + const DdE1xQ = sign3 * this.direction.dot(_edge12.cross(_diff3)); + if (DdE1xQ < 0) { + return null; + } + if (DdQxE2 + DdE1xQ > DdN) { + return null; + } + const QdN = -sign3 * _diff3.dot(_normal$12); + if (QdN < 0) { + return null; + } + return this.at(QdN / DdN, target); + } + applyMatrix4(matrix4) { + this.origin.applyMatrix4(matrix4); + this.direction.transformDirection(matrix4); + return this; + } + equals(ray) { + return ray.origin.equals(this.origin) && ray.direction.equals(this.direction); + } + clone() { + return new this.constructor().copy(this); + } + } + + class Matrix42 { + constructor(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + Matrix42.prototype.isMatrix4 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44); + } + } + set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + const te3 = this.elements; + te3[0] = n11; + te3[4] = n12; + te3[8] = n13; + te3[12] = n14; + te3[1] = n21; + te3[5] = n22; + te3[9] = n23; + te3[13] = n24; + te3[2] = n31; + te3[6] = n32; + te3[10] = n33; + te3[14] = n34; + te3[3] = n41; + te3[7] = n42; + te3[11] = n43; + te3[15] = n44; + return this; + } + identity() { + this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return this; + } + clone() { + return new Matrix42().fromArray(this.elements); + } + copy(m) { + const te3 = this.elements; + const me = m.elements; + te3[0] = me[0]; + te3[1] = me[1]; + te3[2] = me[2]; + te3[3] = me[3]; + te3[4] = me[4]; + te3[5] = me[5]; + te3[6] = me[6]; + te3[7] = me[7]; + te3[8] = me[8]; + te3[9] = me[9]; + te3[10] = me[10]; + te3[11] = me[11]; + te3[12] = me[12]; + te3[13] = me[13]; + te3[14] = me[14]; + te3[15] = me[15]; + return this; + } + copyPosition(m) { + const te3 = this.elements, me = m.elements; + te3[12] = me[12]; + te3[13] = me[13]; + te3[14] = me[14]; + return this; + } + setFromMatrix3(m) { + const me = m.elements; + this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1); + return this; + } + extractBasis(xAxis2, yAxis2, zAxis2) { + xAxis2.setFromMatrixColumn(this, 0); + yAxis2.setFromMatrixColumn(this, 1); + zAxis2.setFromMatrixColumn(this, 2); + return this; + } + makeBasis(xAxis2, yAxis2, zAxis2) { + this.set(xAxis2.x, yAxis2.x, zAxis2.x, 0, xAxis2.y, yAxis2.y, zAxis2.y, 0, xAxis2.z, yAxis2.z, zAxis2.z, 0, 0, 0, 0, 1); + return this; + } + extractRotation(m) { + const te3 = this.elements; + const me = m.elements; + const scaleX = 1 / _v1$52.setFromMatrixColumn(m, 0).length(); + const scaleY = 1 / _v1$52.setFromMatrixColumn(m, 1).length(); + const scaleZ = 1 / _v1$52.setFromMatrixColumn(m, 2).length(); + te3[0] = me[0] * scaleX; + te3[1] = me[1] * scaleX; + te3[2] = me[2] * scaleX; + te3[3] = 0; + te3[4] = me[4] * scaleY; + te3[5] = me[5] * scaleY; + te3[6] = me[6] * scaleY; + te3[7] = 0; + te3[8] = me[8] * scaleZ; + te3[9] = me[9] * scaleZ; + te3[10] = me[10] * scaleZ; + te3[11] = 0; + te3[12] = 0; + te3[13] = 0; + te3[14] = 0; + te3[15] = 1; + return this; + } + makeRotationFromEuler(euler) { + const te3 = this.elements; + const { x: x2, y: y3, z: z2 } = euler; + const a2 = Math.cos(x2), b3 = Math.sin(x2); + const c2 = Math.cos(y3), d = Math.sin(y3); + const e = Math.cos(z2), f = Math.sin(z2); + if (euler.order === "XYZ") { + const ae3 = a2 * e, af = a2 * f, be = b3 * e, bf2 = b3 * f; + te3[0] = c2 * e; + te3[4] = -c2 * f; + te3[8] = d; + te3[1] = af + be * d; + te3[5] = ae3 - bf2 * d; + te3[9] = -b3 * c2; + te3[2] = bf2 - ae3 * d; + te3[6] = be + af * d; + te3[10] = a2 * c2; + } else if (euler.order === "YXZ") { + const ce3 = c2 * e, cf = c2 * f, de = d * e, df = d * f; + te3[0] = ce3 + df * b3; + te3[4] = de * b3 - cf; + te3[8] = a2 * d; + te3[1] = a2 * f; + te3[5] = a2 * e; + te3[9] = -b3; + te3[2] = cf * b3 - de; + te3[6] = df + ce3 * b3; + te3[10] = a2 * c2; + } else if (euler.order === "ZXY") { + const ce3 = c2 * e, cf = c2 * f, de = d * e, df = d * f; + te3[0] = ce3 - df * b3; + te3[4] = -a2 * f; + te3[8] = de + cf * b3; + te3[1] = cf + de * b3; + te3[5] = a2 * e; + te3[9] = df - ce3 * b3; + te3[2] = -a2 * d; + te3[6] = b3; + te3[10] = a2 * c2; + } else if (euler.order === "ZYX") { + const ae3 = a2 * e, af = a2 * f, be = b3 * e, bf2 = b3 * f; + te3[0] = c2 * e; + te3[4] = be * d - af; + te3[8] = ae3 * d + bf2; + te3[1] = c2 * f; + te3[5] = bf2 * d + ae3; + te3[9] = af * d - be; + te3[2] = -d; + te3[6] = b3 * c2; + te3[10] = a2 * c2; + } else if (euler.order === "YZX") { + const ac = a2 * c2, ad = a2 * d, bc = b3 * c2, bd2 = b3 * d; + te3[0] = c2 * e; + te3[4] = bd2 - ac * f; + te3[8] = bc * f + ad; + te3[1] = f; + te3[5] = a2 * e; + te3[9] = -b3 * e; + te3[2] = -d * e; + te3[6] = ad * f + bc; + te3[10] = ac - bd2 * f; + } else if (euler.order === "XZY") { + const ac = a2 * c2, ad = a2 * d, bc = b3 * c2, bd2 = b3 * d; + te3[0] = c2 * e; + te3[4] = -f; + te3[8] = d * e; + te3[1] = ac * f + bd2; + te3[5] = a2 * e; + te3[9] = ad * f - bc; + te3[2] = bc * f - ad; + te3[6] = b3 * e; + te3[10] = bd2 * f + ac; + } + te3[3] = 0; + te3[7] = 0; + te3[11] = 0; + te3[12] = 0; + te3[13] = 0; + te3[14] = 0; + te3[15] = 1; + return this; + } + makeRotationFromQuaternion(q2) { + return this.compose(_zero2, q2, _one2); + } + lookAt(eye, target, up) { + const te3 = this.elements; + _z2.subVectors(eye, target); + if (_z2.lengthSq() === 0) { + _z2.z = 1; + } + _z2.normalize(); + _x2.crossVectors(up, _z2); + if (_x2.lengthSq() === 0) { + if (Math.abs(up.z) === 1) { + _z2.x += 0.0001; + } else { + _z2.z += 0.0001; + } + _z2.normalize(); + _x2.crossVectors(up, _z2); + } + _x2.normalize(); + _y2.crossVectors(_z2, _x2); + te3[0] = _x2.x; + te3[4] = _y2.x; + te3[8] = _z2.x; + te3[1] = _x2.y; + te3[5] = _y2.y; + te3[9] = _z2.y; + te3[2] = _x2.z; + te3[6] = _y2.z; + te3[10] = _z2.z; + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a2, b3) { + const ae3 = a2.elements; + const be = b3.elements; + const te3 = this.elements; + const a11 = ae3[0], a12 = ae3[4], a13 = ae3[8], a14 = ae3[12]; + const a21 = ae3[1], a22 = ae3[5], a23 = ae3[9], a24 = ae3[13]; + const a31 = ae3[2], a32 = ae3[6], a33 = ae3[10], a34 = ae3[14]; + const a41 = ae3[3], a42 = ae3[7], a43 = ae3[11], a44 = ae3[15]; + const b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; + const b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; + const b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; + const b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; + te3[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te3[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te3[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te3[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + te3[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te3[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te3[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te3[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + te3[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te3[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te3[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te3[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + te3[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te3[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te3[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te3[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + return this; + } + multiplyScalar(s) { + const te3 = this.elements; + te3[0] *= s; + te3[4] *= s; + te3[8] *= s; + te3[12] *= s; + te3[1] *= s; + te3[5] *= s; + te3[9] *= s; + te3[13] *= s; + te3[2] *= s; + te3[6] *= s; + te3[10] *= s; + te3[14] *= s; + te3[3] *= s; + te3[7] *= s; + te3[11] *= s; + te3[15] *= s; + return this; + } + determinant() { + const te3 = this.elements; + const n11 = te3[0], n12 = te3[4], n13 = te3[8], n14 = te3[12]; + const n21 = te3[1], n22 = te3[5], n23 = te3[9], n24 = te3[13]; + const n31 = te3[2], n32 = te3[6], n33 = te3[10], n34 = te3[14]; + const n41 = te3[3], n42 = te3[7], n43 = te3[11], n44 = te3[15]; + return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31); + } + transpose() { + const te3 = this.elements; + let tmp3; + tmp3 = te3[1]; + te3[1] = te3[4]; + te3[4] = tmp3; + tmp3 = te3[2]; + te3[2] = te3[8]; + te3[8] = tmp3; + tmp3 = te3[6]; + te3[6] = te3[9]; + te3[9] = tmp3; + tmp3 = te3[3]; + te3[3] = te3[12]; + te3[12] = tmp3; + tmp3 = te3[7]; + te3[7] = te3[13]; + te3[13] = tmp3; + tmp3 = te3[11]; + te3[11] = te3[14]; + te3[14] = tmp3; + return this; + } + setPosition(x2, y3, z2) { + const te3 = this.elements; + if (x2.isVector3) { + te3[12] = x2.x; + te3[13] = x2.y; + te3[14] = x2.z; + } else { + te3[12] = x2; + te3[13] = y3; + te3[14] = z2; + } + return this; + } + invert() { + const te3 = this.elements, n11 = te3[0], n21 = te3[1], n31 = te3[2], n41 = te3[3], n12 = te3[4], n22 = te3[5], n32 = te3[6], n42 = te3[7], n13 = te3[8], n23 = te3[9], n33 = te3[10], n43 = te3[11], n14 = te3[12], n24 = te3[13], n34 = te3[14], n44 = te3[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + if (det === 0) + return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te3[0] = t11 * detInv; + te3[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; + te3[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; + te3[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; + te3[4] = t12 * detInv; + te3[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; + te3[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; + te3[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; + te3[8] = t13 * detInv; + te3[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; + te3[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; + te3[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; + te3[12] = t14 * detInv; + te3[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; + te3[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; + te3[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; + return this; + } + scale(v) { + const te3 = this.elements; + const { x: x2, y: y3, z: z2 } = v; + te3[0] *= x2; + te3[4] *= y3; + te3[8] *= z2; + te3[1] *= x2; + te3[5] *= y3; + te3[9] *= z2; + te3[2] *= x2; + te3[6] *= y3; + te3[10] *= z2; + te3[3] *= x2; + te3[7] *= y3; + te3[11] *= z2; + return this; + } + getMaxScaleOnAxis() { + const te3 = this.elements; + const scaleXSq = te3[0] * te3[0] + te3[1] * te3[1] + te3[2] * te3[2]; + const scaleYSq = te3[4] * te3[4] + te3[5] * te3[5] + te3[6] * te3[6]; + const scaleZSq = te3[8] * te3[8] + te3[9] * te3[9] + te3[10] * te3[10]; + return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); + } + makeTranslation(x2, y3, z2) { + if (x2.isVector3) { + this.set(1, 0, 0, x2.x, 0, 1, 0, x2.y, 0, 0, 1, x2.z, 0, 0, 0, 1); + } else { + this.set(1, 0, 0, x2, 0, 1, 0, y3, 0, 0, 1, z2, 0, 0, 0, 1); + } + return this; + } + makeRotationX(theta) { + const c2 = Math.cos(theta), s = Math.sin(theta); + this.set(1, 0, 0, 0, 0, c2, -s, 0, 0, s, c2, 0, 0, 0, 0, 1); + return this; + } + makeRotationY(theta) { + const c2 = Math.cos(theta), s = Math.sin(theta); + this.set(c2, 0, s, 0, 0, 1, 0, 0, -s, 0, c2, 0, 0, 0, 0, 1); + return this; + } + makeRotationZ(theta) { + const c2 = Math.cos(theta), s = Math.sin(theta); + this.set(c2, -s, 0, 0, s, c2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return this; + } + makeRotationAxis(axis, angle) { + const c2 = Math.cos(angle); + const s = Math.sin(angle); + const t4 = 1 - c2; + const { x: x2, y: y3, z: z2 } = axis; + const tx = t4 * x2, ty2 = t4 * y3; + this.set(tx * x2 + c2, tx * y3 - s * z2, tx * z2 + s * y3, 0, tx * y3 + s * z2, ty2 * y3 + c2, ty2 * z2 - s * x2, 0, tx * z2 - s * y3, ty2 * z2 + s * x2, t4 * z2 * z2 + c2, 0, 0, 0, 0, 1); + return this; + } + makeScale(x2, y3, z2) { + this.set(x2, 0, 0, 0, 0, y3, 0, 0, 0, 0, z2, 0, 0, 0, 0, 1); + return this; + } + makeShear(xy2, xz, yx, yz, zx, zy) { + this.set(1, yx, zx, 0, xy2, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1); + return this; + } + compose(position2, quaternion, scale2) { + const te3 = this.elements; + const { _x: x2, _y: y3, _z: z2, _w: w } = quaternion; + const x22 = x2 + x2, y22 = y3 + y3, z22 = z2 + z2; + const xx = x2 * x22, xy2 = x2 * y22, xz = x2 * z22; + const yy2 = y3 * y22, yz = y3 * z22, zz = z2 * z22; + const wx = w * x22, wy = w * y22, wz = w * z22; + const { x: sx, y: sy, z: sz } = scale2; + te3[0] = (1 - (yy2 + zz)) * sx; + te3[1] = (xy2 + wz) * sx; + te3[2] = (xz - wy) * sx; + te3[3] = 0; + te3[4] = (xy2 - wz) * sy; + te3[5] = (1 - (xx + zz)) * sy; + te3[6] = (yz + wx) * sy; + te3[7] = 0; + te3[8] = (xz + wy) * sz; + te3[9] = (yz - wx) * sz; + te3[10] = (1 - (xx + yy2)) * sz; + te3[11] = 0; + te3[12] = position2.x; + te3[13] = position2.y; + te3[14] = position2.z; + te3[15] = 1; + return this; + } + decompose(position2, quaternion, scale2) { + const te3 = this.elements; + let sx = _v1$52.set(te3[0], te3[1], te3[2]).length(); + const sy = _v1$52.set(te3[4], te3[5], te3[6]).length(); + const sz = _v1$52.set(te3[8], te3[9], te3[10]).length(); + const det = this.determinant(); + if (det < 0) + sx = -sx; + position2.x = te3[12]; + position2.y = te3[13]; + position2.z = te3[14]; + _m1$4.copy(this); + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + _m1$4.elements[0] *= invSX; + _m1$4.elements[1] *= invSX; + _m1$4.elements[2] *= invSX; + _m1$4.elements[4] *= invSY; + _m1$4.elements[5] *= invSY; + _m1$4.elements[6] *= invSY; + _m1$4.elements[8] *= invSZ; + _m1$4.elements[9] *= invSZ; + _m1$4.elements[10] *= invSZ; + quaternion.setFromRotationMatrix(_m1$4); + scale2.x = sx; + scale2.y = sy; + scale2.z = sz; + return this; + } + makePerspective(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem2) { + const te3 = this.elements; + const x2 = 2 * near / (right - left); + const y3 = 2 * near / (top - bottom); + const a2 = (right + left) / (right - left); + const b3 = (top + bottom) / (top - bottom); + let c2, d; + if (coordinateSystem === WebGLCoordinateSystem2) { + c2 = -(far + near) / (far - near); + d = -2 * far * near / (far - near); + } else if (coordinateSystem === WebGPUCoordinateSystem2) { + c2 = -far / (far - near); + d = -far * near / (far - near); + } else { + throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + coordinateSystem); + } + te3[0] = x2; + te3[4] = 0; + te3[8] = a2; + te3[12] = 0; + te3[1] = 0; + te3[5] = y3; + te3[9] = b3; + te3[13] = 0; + te3[2] = 0; + te3[6] = 0; + te3[10] = c2; + te3[14] = d; + te3[3] = 0; + te3[7] = 0; + te3[11] = -1; + te3[15] = 0; + return this; + } + makeOrthographic(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem2) { + const te3 = this.elements; + const w = 1 / (right - left); + const h = 1 / (top - bottom); + const p = 1 / (far - near); + const x2 = (right + left) * w; + const y3 = (top + bottom) * h; + let z2, zInv; + if (coordinateSystem === WebGLCoordinateSystem2) { + z2 = (far + near) * p; + zInv = -2 * p; + } else if (coordinateSystem === WebGPUCoordinateSystem2) { + z2 = near * p; + zInv = -1 * p; + } else { + throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + coordinateSystem); + } + te3[0] = 2 * w; + te3[4] = 0; + te3[8] = 0; + te3[12] = -x2; + te3[1] = 0; + te3[5] = 2 * h; + te3[9] = 0; + te3[13] = -y3; + te3[2] = 0; + te3[6] = 0; + te3[10] = zInv; + te3[14] = -z2; + te3[3] = 0; + te3[7] = 0; + te3[11] = 0; + te3[15] = 1; + return this; + } + equals(matrix3) { + const te3 = this.elements; + const me = matrix3.elements; + for (let i = 0;i < 16; i++) { + if (te3[i] !== me[i]) + return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 16; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te3 = this.elements; + array[offset] = te3[0]; + array[offset + 1] = te3[1]; + array[offset + 2] = te3[2]; + array[offset + 3] = te3[3]; + array[offset + 4] = te3[4]; + array[offset + 5] = te3[5]; + array[offset + 6] = te3[6]; + array[offset + 7] = te3[7]; + array[offset + 8] = te3[8]; + array[offset + 9] = te3[9]; + array[offset + 10] = te3[10]; + array[offset + 11] = te3[11]; + array[offset + 12] = te3[12]; + array[offset + 13] = te3[13]; + array[offset + 14] = te3[14]; + array[offset + 15] = te3[15]; + return array; + } + } + var _v1$52 = /* @__PURE__ */ new Vector32; + var _m1$4 = /* @__PURE__ */ new Matrix42; + var _zero2 = /* @__PURE__ */ new Vector32(0, 0, 0); + var _one2 = /* @__PURE__ */ new Vector32(1, 1, 1); + var _x2 = /* @__PURE__ */ new Vector32; + var _y2 = /* @__PURE__ */ new Vector32; + var _z2 = /* @__PURE__ */ new Vector32; + var _matrix$22 = /* @__PURE__ */ new Matrix42; + var _quaternion$32 = /* @__PURE__ */ new Quaternion2; + + class Euler2 { + constructor(x2 = 0, y3 = 0, z2 = 0, order = Euler2.DEFAULT_ORDER) { + this.isEuler = true; + this._x = x2; + this._y = y3; + this._z = z2; + this._order = order; + } + get x() { + return this._x; + } + set x(value2) { + this._x = value2; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value2) { + this._y = value2; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value2) { + this._z = value2; + this._onChangeCallback(); + } + get order() { + return this._order; + } + set order(value2) { + this._order = value2; + this._onChangeCallback(); + } + set(x2, y3, z2, order = this._order) { + this._x = x2; + this._y = y3; + this._z = z2; + this._order = order; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._order); + } + copy(euler) { + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m, order = this._order, update = true) { + const te3 = m.elements; + const m11 = te3[0], m12 = te3[4], m13 = te3[8]; + const m21 = te3[1], m22 = te3[5], m23 = te3[9]; + const m31 = te3[2], m32 = te3[6], m33 = te3[10]; + switch (order) { + case "XYZ": + this._y = Math.asin(clamp3(m13, -1, 1)); + if (Math.abs(m13) < 0.9999999) { + this._x = Math.atan2(-m23, m33); + this._z = Math.atan2(-m12, m11); + } else { + this._x = Math.atan2(m32, m22); + this._z = 0; + } + break; + case "YXZ": + this._x = Math.asin(-clamp3(m23, -1, 1)); + if (Math.abs(m23) < 0.9999999) { + this._y = Math.atan2(m13, m33); + this._z = Math.atan2(m21, m22); + } else { + this._y = Math.atan2(-m31, m11); + this._z = 0; + } + break; + case "ZXY": + this._x = Math.asin(clamp3(m32, -1, 1)); + if (Math.abs(m32) < 0.9999999) { + this._y = Math.atan2(-m31, m33); + this._z = Math.atan2(-m12, m22); + } else { + this._y = 0; + this._z = Math.atan2(m21, m11); + } + break; + case "ZYX": + this._y = Math.asin(-clamp3(m31, -1, 1)); + if (Math.abs(m31) < 0.9999999) { + this._x = Math.atan2(m32, m33); + this._z = Math.atan2(m21, m11); + } else { + this._x = 0; + this._z = Math.atan2(-m12, m22); + } + break; + case "YZX": + this._z = Math.asin(clamp3(m21, -1, 1)); + if (Math.abs(m21) < 0.9999999) { + this._x = Math.atan2(-m23, m22); + this._y = Math.atan2(-m31, m11); + } else { + this._x = 0; + this._y = Math.atan2(m13, m33); + } + break; + case "XZY": + this._z = Math.asin(-clamp3(m12, -1, 1)); + if (Math.abs(m12) < 0.9999999) { + this._x = Math.atan2(m32, m22); + this._y = Math.atan2(m13, m11); + } else { + this._x = Math.atan2(-m23, m33); + this._y = 0; + } + break; + default: + console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + order); + } + this._order = order; + if (update === true) + this._onChangeCallback(); + return this; + } + setFromQuaternion(q2, order, update) { + _matrix$22.makeRotationFromQuaternion(q2); + return this.setFromRotationMatrix(_matrix$22, order, update); + } + setFromVector3(v, order = this._order) { + return this.set(v.x, v.y, v.z, order); + } + reorder(newOrder) { + _quaternion$32.setFromEuler(this); + return this.setFromQuaternion(_quaternion$32, newOrder); + } + equals(euler) { + return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order; + } + fromArray(array) { + this._x = array[0]; + this._y = array[1]; + this._z = array[2]; + if (array[3] !== undefined) + this._order = array[3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._order; + return array; + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._order; + } + } + Euler2.DEFAULT_ORDER = "XYZ"; + + class Layers2 { + constructor() { + this.mask = 1 | 0; + } + set(channel) { + this.mask = (1 << channel | 0) >>> 0; + } + enable(channel) { + this.mask |= 1 << channel | 0; + } + enableAll() { + this.mask = 4294967295 | 0; + } + toggle(channel) { + this.mask ^= 1 << channel | 0; + } + disable(channel) { + this.mask &= ~(1 << channel | 0); + } + disableAll() { + this.mask = 0; + } + test(layers) { + return (this.mask & layers.mask) !== 0; + } + isEnabled(channel) { + return (this.mask & (1 << channel | 0)) !== 0; + } + } + var _object3DId2 = 0; + var _v1$42 = /* @__PURE__ */ new Vector32; + var _q12 = /* @__PURE__ */ new Quaternion2; + var _m1$3 = /* @__PURE__ */ new Matrix42; + var _target3 = /* @__PURE__ */ new Vector32; + var _position$32 = /* @__PURE__ */ new Vector32; + var _scale$22 = /* @__PURE__ */ new Vector32; + var _quaternion$22 = /* @__PURE__ */ new Quaternion2; + var _xAxis2 = /* @__PURE__ */ new Vector32(1, 0, 0); + var _yAxis2 = /* @__PURE__ */ new Vector32(0, 1, 0); + var _zAxis2 = /* @__PURE__ */ new Vector32(0, 0, 1); + var _addedEvent2 = { type: "added" }; + var _removedEvent2 = { type: "removed" }; + var _childaddedEvent2 = { type: "childadded", child: null }; + var _childremovedEvent2 = { type: "childremoved", child: null }; + + class Object3D2 extends EventDispatcher2 { + constructor() { + super(); + this.isObject3D = true; + Object.defineProperty(this, "id", { value: _object3DId2++ }); + this.uuid = generateUUID2(); + this.name = ""; + this.type = "Object3D"; + this.parent = null; + this.children = []; + this.up = Object3D2.DEFAULT_UP.clone(); + const position2 = new Vector32; + const rotation2 = new Euler2; + const quaternion = new Quaternion2; + const scale2 = new Vector32(1, 1, 1); + function onRotationChange() { + quaternion.setFromEuler(rotation2, false); + } + function onQuaternionChange() { + rotation2.setFromQuaternion(quaternion, undefined, false); + } + rotation2._onChange(onRotationChange); + quaternion._onChange(onQuaternionChange); + Object.defineProperties(this, { + position: { + configurable: true, + enumerable: true, + value: position2 + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation2 + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale2 + }, + modelViewMatrix: { + value: new Matrix42 + }, + normalMatrix: { + value: new Matrix32 + } + }); + this.matrix = new Matrix42; + this.matrixWorld = new Matrix42; + this.matrixAutoUpdate = Object3D2.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldAutoUpdate = Object3D2.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + this.layers = new Layers2; + this.visible = true; + this.castShadow = false; + this.receiveShadow = false; + this.frustumCulled = true; + this.renderOrder = 0; + this.animations = []; + this.userData = {}; + } + onBeforeShadow() { + } + onAfterShadow() { + } + onBeforeRender() { + } + onAfterRender() { + } + applyMatrix4(matrix3) { + if (this.matrixAutoUpdate) + this.updateMatrix(); + this.matrix.premultiply(matrix3); + this.matrix.decompose(this.position, this.quaternion, this.scale); + } + applyQuaternion(q2) { + this.quaternion.premultiply(q2); + return this; + } + setRotationFromAxisAngle(axis, angle) { + this.quaternion.setFromAxisAngle(axis, angle); + } + setRotationFromEuler(euler) { + this.quaternion.setFromEuler(euler, true); + } + setRotationFromMatrix(m) { + this.quaternion.setFromRotationMatrix(m); + } + setRotationFromQuaternion(q2) { + this.quaternion.copy(q2); + } + rotateOnAxis(axis, angle) { + _q12.setFromAxisAngle(axis, angle); + this.quaternion.multiply(_q12); + return this; + } + rotateOnWorldAxis(axis, angle) { + _q12.setFromAxisAngle(axis, angle); + this.quaternion.premultiply(_q12); + return this; + } + rotateX(angle) { + return this.rotateOnAxis(_xAxis2, angle); + } + rotateY(angle) { + return this.rotateOnAxis(_yAxis2, angle); + } + rotateZ(angle) { + return this.rotateOnAxis(_zAxis2, angle); + } + translateOnAxis(axis, distance) { + _v1$42.copy(axis).applyQuaternion(this.quaternion); + this.position.add(_v1$42.multiplyScalar(distance)); + return this; + } + translateX(distance) { + return this.translateOnAxis(_xAxis2, distance); + } + translateY(distance) { + return this.translateOnAxis(_yAxis2, distance); + } + translateZ(distance) { + return this.translateOnAxis(_zAxis2, distance); + } + localToWorld(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(this.matrixWorld); + } + worldToLocal(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(_m1$3.copy(this.matrixWorld).invert()); + } + lookAt(x2, y3, z2) { + if (x2.isVector3) { + _target3.copy(x2); + } else { + _target3.set(x2, y3, z2); + } + const parent2 = this.parent; + this.updateWorldMatrix(true, false); + _position$32.setFromMatrixPosition(this.matrixWorld); + if (this.isCamera || this.isLight) { + _m1$3.lookAt(_position$32, _target3, this.up); + } else { + _m1$3.lookAt(_target3, _position$32, this.up); + } + this.quaternion.setFromRotationMatrix(_m1$3); + if (parent2) { + _m1$3.extractRotation(parent2.matrixWorld); + _q12.setFromRotationMatrix(_m1$3); + this.quaternion.premultiply(_q12.invert()); + } + } + add(object) { + if (arguments.length > 1) { + for (let i = 0;i < arguments.length; i++) { + this.add(arguments[i]); + } + return this; + } + if (object === this) { + console.error("THREE.Object3D.add: object can't be added as a child of itself.", object); + return this; + } + if (object && object.isObject3D) { + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.dispatchEvent(_addedEvent2); + _childaddedEvent2.child = object; + this.dispatchEvent(_childaddedEvent2); + _childaddedEvent2.child = null; + } else { + console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object); + } + return this; + } + remove(object) { + if (arguments.length > 1) { + for (let i = 0;i < arguments.length; i++) { + this.remove(arguments[i]); + } + return this; + } + const index2 = this.children.indexOf(object); + if (index2 !== -1) { + object.parent = null; + this.children.splice(index2, 1); + object.dispatchEvent(_removedEvent2); + _childremovedEvent2.child = object; + this.dispatchEvent(_childremovedEvent2); + _childremovedEvent2.child = null; + } + return this; + } + removeFromParent() { + const parent2 = this.parent; + if (parent2 !== null) { + parent2.remove(this); + } + return this; + } + clear() { + return this.remove(...this.children); + } + attach(object) { + this.updateWorldMatrix(true, false); + _m1$3.copy(this.matrixWorld).invert(); + if (object.parent !== null) { + object.parent.updateWorldMatrix(true, false); + _m1$3.multiply(object.parent.matrixWorld); + } + object.applyMatrix4(_m1$3); + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.updateWorldMatrix(false, true); + object.dispatchEvent(_addedEvent2); + _childaddedEvent2.child = object; + this.dispatchEvent(_childaddedEvent2); + _childaddedEvent2.child = null; + return this; + } + getObjectById(id) { + return this.getObjectByProperty("id", id); + } + getObjectByName(name2) { + return this.getObjectByProperty("name", name2); + } + getObjectByProperty(name2, value2) { + if (this[name2] === value2) + return this; + for (let i = 0, l2 = this.children.length;i < l2; i++) { + const child = this.children[i]; + const object = child.getObjectByProperty(name2, value2); + if (object !== undefined) { + return object; + } + } + return; + } + getObjectsByProperty(name2, value2, result = []) { + if (this[name2] === value2) + result.push(this); + const children = this.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + children[i].getObjectsByProperty(name2, value2, result); + } + return result; + } + getWorldPosition(target) { + this.updateWorldMatrix(true, false); + return target.setFromMatrixPosition(this.matrixWorld); + } + getWorldQuaternion(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$32, target, _scale$22); + return target; + } + getWorldScale(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$32, _quaternion$22, target); + return target; + } + getWorldDirection(target) { + this.updateWorldMatrix(true, false); + const e = this.matrixWorld.elements; + return target.set(e[8], e[9], e[10]).normalize(); + } + raycast() { + } + traverse(callback) { + callback(this); + const children = this.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + children[i].traverse(callback); + } + } + traverseVisible(callback) { + if (this.visible === false) + return; + callback(this); + const children = this.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + children[i].traverseVisible(callback); + } + } + traverseAncestors(callback) { + const parent2 = this.parent; + if (parent2 !== null) { + callback(parent2); + parent2.traverseAncestors(callback); + } + } + updateMatrix() { + this.matrix.compose(this.position, this.quaternion, this.scale); + this.matrixWorldNeedsUpdate = true; + } + updateMatrixWorld(force) { + if (this.matrixAutoUpdate) + this.updateMatrix(); + if (this.matrixWorldNeedsUpdate || force) { + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + this.matrixWorldNeedsUpdate = false; + force = true; + } + const children = this.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + const child = children[i]; + child.updateMatrixWorld(force); + } + } + updateWorldMatrix(updateParents, updateChildren) { + const parent2 = this.parent; + if (updateParents === true && parent2 !== null) { + parent2.updateWorldMatrix(true, false); + } + if (this.matrixAutoUpdate) + this.updateMatrix(); + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + if (updateChildren === true) { + const children = this.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + const child = children[i]; + child.updateWorldMatrix(false, true); + } + } + } + toJSON(meta2) { + const isRootObject = meta2 === undefined || typeof meta2 === "string"; + const output = {}; + if (isRootObject) { + meta2 = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + output.metadata = { + version: 4.6, + type: "Object", + generator: "Object3D.toJSON" + }; + } + const object = {}; + object.uuid = this.uuid; + object.type = this.type; + if (this.name !== "") + object.name = this.name; + if (this.castShadow === true) + object.castShadow = true; + if (this.receiveShadow === true) + object.receiveShadow = true; + if (this.visible === false) + object.visible = false; + if (this.frustumCulled === false) + object.frustumCulled = false; + if (this.renderOrder !== 0) + object.renderOrder = this.renderOrder; + if (Object.keys(this.userData).length > 0) + object.userData = this.userData; + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + object.up = this.up.toArray(); + if (this.matrixAutoUpdate === false) + object.matrixAutoUpdate = false; + if (this.isInstancedMesh) { + object.type = "InstancedMesh"; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if (this.instanceColor !== null) + object.instanceColor = this.instanceColor.toJSON(); + } + if (this.isBatchedMesh) { + object.type = "BatchedMesh"; + object.perObjectFrustumCulled = this.perObjectFrustumCulled; + object.sortObjects = this.sortObjects; + object.drawRanges = this._drawRanges; + object.reservedRanges = this._reservedRanges; + object.visibility = this._visibility; + object.active = this._active; + object.bounds = this._bounds.map((bound) => ({ + boxInitialized: bound.boxInitialized, + boxMin: bound.box.min.toArray(), + boxMax: bound.box.max.toArray(), + sphereInitialized: bound.sphereInitialized, + sphereRadius: bound.sphere.radius, + sphereCenter: bound.sphere.center.toArray() + })); + object.maxInstanceCount = this._maxInstanceCount; + object.maxVertexCount = this._maxVertexCount; + object.maxIndexCount = this._maxIndexCount; + object.geometryInitialized = this._geometryInitialized; + object.geometryCount = this._geometryCount; + object.matricesTexture = this._matricesTexture.toJSON(meta2); + if (this._colorsTexture !== null) + object.colorsTexture = this._colorsTexture.toJSON(meta2); + if (this.boundingSphere !== null) { + object.boundingSphere = { + center: object.boundingSphere.center.toArray(), + radius: object.boundingSphere.radius + }; + } + if (this.boundingBox !== null) { + object.boundingBox = { + min: object.boundingBox.min.toArray(), + max: object.boundingBox.max.toArray() + }; + } + } + function serialize(library, element) { + if (library[element.uuid] === undefined) { + library[element.uuid] = element.toJSON(meta2); + } + return element.uuid; + } + if (this.isScene) { + if (this.background) { + if (this.background.isColor) { + object.background = this.background.toJSON(); + } else if (this.background.isTexture) { + object.background = this.background.toJSON(meta2).uuid; + } + } + if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) { + object.environment = this.environment.toJSON(meta2).uuid; + } + } else if (this.isMesh || this.isLine || this.isPoints) { + object.geometry = serialize(meta2.geometries, this.geometry); + const parameters = this.geometry.parameters; + if (parameters !== undefined && parameters.shapes !== undefined) { + const shapes = parameters.shapes; + if (Array.isArray(shapes)) { + for (let i = 0, l2 = shapes.length;i < l2; i++) { + const shape = shapes[i]; + serialize(meta2.shapes, shape); + } + } else { + serialize(meta2.shapes, shapes); + } + } + } + if (this.isSkinnedMesh) { + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + if (this.skeleton !== undefined) { + serialize(meta2.skeletons, this.skeleton); + object.skeleton = this.skeleton.uuid; + } + } + if (this.material !== undefined) { + if (Array.isArray(this.material)) { + const uuids = []; + for (let i = 0, l2 = this.material.length;i < l2; i++) { + uuids.push(serialize(meta2.materials, this.material[i])); + } + object.material = uuids; + } else { + object.material = serialize(meta2.materials, this.material); + } + } + if (this.children.length > 0) { + object.children = []; + for (let i = 0;i < this.children.length; i++) { + object.children.push(this.children[i].toJSON(meta2).object); + } + } + if (this.animations.length > 0) { + object.animations = []; + for (let i = 0;i < this.animations.length; i++) { + const animation = this.animations[i]; + object.animations.push(serialize(meta2.animations, animation)); + } + } + if (isRootObject) { + const geometries = extractFromCache(meta2.geometries); + const materials = extractFromCache(meta2.materials); + const textures = extractFromCache(meta2.textures); + const images = extractFromCache(meta2.images); + const shapes = extractFromCache(meta2.shapes); + const skeletons = extractFromCache(meta2.skeletons); + const animations = extractFromCache(meta2.animations); + const nodes = extractFromCache(meta2.nodes); + if (geometries.length > 0) + output.geometries = geometries; + if (materials.length > 0) + output.materials = materials; + if (textures.length > 0) + output.textures = textures; + if (images.length > 0) + output.images = images; + if (shapes.length > 0) + output.shapes = shapes; + if (skeletons.length > 0) + output.skeletons = skeletons; + if (animations.length > 0) + output.animations = animations; + if (nodes.length > 0) + output.nodes = nodes; + } + output.object = object; + return output; + function extractFromCache(cache) { + const values2 = []; + for (const key2 in cache) { + const data2 = cache[key2]; + delete data2.metadata; + values2.push(data2); + } + return values2; + } + } + clone(recursive) { + return new this.constructor().copy(this, recursive); + } + copy(source, recursive = true) { + this.name = source.name; + this.up.copy(source.up); + this.position.copy(source.position); + this.rotation.order = source.rotation.order; + this.quaternion.copy(source.quaternion); + this.scale.copy(source.scale); + this.matrix.copy(source.matrix); + this.matrixWorld.copy(source.matrixWorld); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + this.layers.mask = source.layers.mask; + this.visible = source.visible; + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + this.animations = source.animations.slice(); + this.userData = JSON.parse(JSON.stringify(source.userData)); + if (recursive === true) { + for (let i = 0;i < source.children.length; i++) { + const child = source.children[i]; + this.add(child.clone()); + } + } + return this; + } + } + Object3D2.DEFAULT_UP = /* @__PURE__ */ new Vector32(0, 1, 0); + Object3D2.DEFAULT_MATRIX_AUTO_UPDATE = true; + Object3D2.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; + var _v0$22 = /* @__PURE__ */ new Vector32; + var _v1$32 = /* @__PURE__ */ new Vector32; + var _v2$22 = /* @__PURE__ */ new Vector32; + var _v3$22 = /* @__PURE__ */ new Vector32; + var _vab2 = /* @__PURE__ */ new Vector32; + var _vac2 = /* @__PURE__ */ new Vector32; + var _vbc2 = /* @__PURE__ */ new Vector32; + var _vap2 = /* @__PURE__ */ new Vector32; + var _vbp2 = /* @__PURE__ */ new Vector32; + var _vcp2 = /* @__PURE__ */ new Vector32; + var _v402 = /* @__PURE__ */ new Vector42; + var _v412 = /* @__PURE__ */ new Vector42; + var _v422 = /* @__PURE__ */ new Vector42; + + class Triangle2 { + constructor(a2 = new Vector32, b3 = new Vector32, c2 = new Vector32) { + this.a = a2; + this.b = b3; + this.c = c2; + } + static getNormal(a2, b3, c2, target) { + target.subVectors(c2, b3); + _v0$22.subVectors(a2, b3); + target.cross(_v0$22); + const targetLengthSq = target.lengthSq(); + if (targetLengthSq > 0) { + return target.multiplyScalar(1 / Math.sqrt(targetLengthSq)); + } + return target.set(0, 0, 0); + } + static getBarycoord(point, a2, b3, c2, target) { + _v0$22.subVectors(c2, a2); + _v1$32.subVectors(b3, a2); + _v2$22.subVectors(point, a2); + const dot00 = _v0$22.dot(_v0$22); + const dot01 = _v0$22.dot(_v1$32); + const dot02 = _v0$22.dot(_v2$22); + const dot11 = _v1$32.dot(_v1$32); + const dot12 = _v1$32.dot(_v2$22); + const denom = dot00 * dot11 - dot01 * dot01; + if (denom === 0) { + target.set(0, 0, 0); + return null; + } + const invDenom = 1 / denom; + const u3 = (dot11 * dot02 - dot01 * dot12) * invDenom; + const v = (dot00 * dot12 - dot01 * dot02) * invDenom; + return target.set(1 - u3 - v, v, u3); + } + static containsPoint(point, a2, b3, c2) { + if (this.getBarycoord(point, a2, b3, c2, _v3$22) === null) { + return false; + } + return _v3$22.x >= 0 && _v3$22.y >= 0 && _v3$22.x + _v3$22.y <= 1; + } + static getInterpolation(point, p1, p2, p32, v12, v2, v32, target) { + if (this.getBarycoord(point, p1, p2, p32, _v3$22) === null) { + target.x = 0; + target.y = 0; + if ("z" in target) + target.z = 0; + if ("w" in target) + target.w = 0; + return null; + } + target.setScalar(0); + target.addScaledVector(v12, _v3$22.x); + target.addScaledVector(v2, _v3$22.y); + target.addScaledVector(v32, _v3$22.z); + return target; + } + static getInterpolatedAttribute(attr, i1, i22, i3, barycoord, target) { + _v402.setScalar(0); + _v412.setScalar(0); + _v422.setScalar(0); + _v402.fromBufferAttribute(attr, i1); + _v412.fromBufferAttribute(attr, i22); + _v422.fromBufferAttribute(attr, i3); + target.setScalar(0); + target.addScaledVector(_v402, barycoord.x); + target.addScaledVector(_v412, barycoord.y); + target.addScaledVector(_v422, barycoord.z); + return target; + } + static isFrontFacing(a2, b3, c2, direction) { + _v0$22.subVectors(c2, b3); + _v1$32.subVectors(a2, b3); + return _v0$22.cross(_v1$32).dot(direction) < 0 ? true : false; + } + set(a2, b3, c2) { + this.a.copy(a2); + this.b.copy(b3); + this.c.copy(c2); + return this; + } + setFromPointsAndIndices(points, i0, i1, i22) { + this.a.copy(points[i0]); + this.b.copy(points[i1]); + this.c.copy(points[i22]); + return this; + } + setFromAttributeAndIndices(attribute, i0, i1, i22) { + this.a.fromBufferAttribute(attribute, i0); + this.b.fromBufferAttribute(attribute, i1); + this.c.fromBufferAttribute(attribute, i22); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(triangle) { + this.a.copy(triangle.a); + this.b.copy(triangle.b); + this.c.copy(triangle.c); + return this; + } + getArea() { + _v0$22.subVectors(this.c, this.b); + _v1$32.subVectors(this.a, this.b); + return _v0$22.cross(_v1$32).length() * 0.5; + } + getMidpoint(target) { + return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); + } + getNormal(target) { + return Triangle2.getNormal(this.a, this.b, this.c, target); + } + getPlane(target) { + return target.setFromCoplanarPoints(this.a, this.b, this.c); + } + getBarycoord(point, target) { + return Triangle2.getBarycoord(point, this.a, this.b, this.c, target); + } + getInterpolation(point, v12, v2, v32, target) { + return Triangle2.getInterpolation(point, this.a, this.b, this.c, v12, v2, v32, target); + } + containsPoint(point) { + return Triangle2.containsPoint(point, this.a, this.b, this.c); + } + isFrontFacing(direction) { + return Triangle2.isFrontFacing(this.a, this.b, this.c, direction); + } + intersectsBox(box) { + return box.intersectsTriangle(this); + } + closestPointToPoint(p, target) { + const a2 = this.a, b3 = this.b, c2 = this.c; + let v, w; + _vab2.subVectors(b3, a2); + _vac2.subVectors(c2, a2); + _vap2.subVectors(p, a2); + const d1 = _vab2.dot(_vap2); + const d2 = _vac2.dot(_vap2); + if (d1 <= 0 && d2 <= 0) { + return target.copy(a2); + } + _vbp2.subVectors(p, b3); + const d32 = _vab2.dot(_vbp2); + const d4 = _vac2.dot(_vbp2); + if (d32 >= 0 && d4 <= d32) { + return target.copy(b3); + } + const vc = d1 * d4 - d32 * d2; + if (vc <= 0 && d1 >= 0 && d32 <= 0) { + v = d1 / (d1 - d32); + return target.copy(a2).addScaledVector(_vab2, v); + } + _vcp2.subVectors(p, c2); + const d5 = _vab2.dot(_vcp2); + const d6 = _vac2.dot(_vcp2); + if (d6 >= 0 && d5 <= d6) { + return target.copy(c2); + } + const vb = d5 * d2 - d1 * d6; + if (vb <= 0 && d2 >= 0 && d6 <= 0) { + w = d2 / (d2 - d6); + return target.copy(a2).addScaledVector(_vac2, w); + } + const va2 = d32 * d6 - d5 * d4; + if (va2 <= 0 && d4 - d32 >= 0 && d5 - d6 >= 0) { + _vbc2.subVectors(c2, b3); + w = (d4 - d32) / (d4 - d32 + (d5 - d6)); + return target.copy(b3).addScaledVector(_vbc2, w); + } + const denom = 1 / (va2 + vb + vc); + v = vb * denom; + w = vc * denom; + return target.copy(a2).addScaledVector(_vab2, v).addScaledVector(_vac2, w); + } + equals(triangle) { + return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c); + } + } + var _colorKeywords2 = { + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + rebeccapurple: 6697881, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 + }; + var _hslA2 = { h: 0, s: 0, l: 0 }; + var _hslB2 = { h: 0, s: 0, l: 0 }; + function hue2rgb3(p, q2, t4) { + if (t4 < 0) + t4 += 1; + if (t4 > 1) + t4 -= 1; + if (t4 < 1 / 6) + return p + (q2 - p) * 6 * t4; + if (t4 < 1 / 2) + return q2; + if (t4 < 2 / 3) + return p + (q2 - p) * 6 * (2 / 3 - t4); + return p; + } + + class Color2 { + constructor(r, g3, b3) { + this.isColor = true; + this.r = 1; + this.g = 1; + this.b = 1; + return this.set(r, g3, b3); + } + set(r, g3, b3) { + if (g3 === undefined && b3 === undefined) { + const value2 = r; + if (value2 && value2.isColor) { + this.copy(value2); + } else if (typeof value2 === "number") { + this.setHex(value2); + } else if (typeof value2 === "string") { + this.setStyle(value2); + } + } else { + this.setRGB(r, g3, b3); + } + return this; + } + setScalar(scalar) { + this.r = scalar; + this.g = scalar; + this.b = scalar; + return this; + } + setHex(hex, colorSpace = SRGBColorSpace2) { + hex = Math.floor(hex); + this.r = (hex >> 16 & 255) / 255; + this.g = (hex >> 8 & 255) / 255; + this.b = (hex & 255) / 255; + ColorManagement2.toWorkingColorSpace(this, colorSpace); + return this; + } + setRGB(r, g3, b3, colorSpace = ColorManagement2.workingColorSpace) { + this.r = r; + this.g = g3; + this.b = b3; + ColorManagement2.toWorkingColorSpace(this, colorSpace); + return this; + } + setHSL(h, s, l2, colorSpace = ColorManagement2.workingColorSpace) { + h = euclideanModulo2(h, 1); + s = clamp3(s, 0, 1); + l2 = clamp3(l2, 0, 1); + if (s === 0) { + this.r = this.g = this.b = l2; + } else { + const p = l2 <= 0.5 ? l2 * (1 + s) : l2 + s - l2 * s; + const q2 = 2 * l2 - p; + this.r = hue2rgb3(q2, p, h + 1 / 3); + this.g = hue2rgb3(q2, p, h); + this.b = hue2rgb3(q2, p, h - 1 / 3); + } + ColorManagement2.toWorkingColorSpace(this, colorSpace); + return this; + } + setStyle(style, colorSpace = SRGBColorSpace2) { + function handleAlpha(string) { + if (string === undefined) + return; + if (parseFloat(string) < 1) { + console.warn("THREE.Color: Alpha component of " + style + " will be ignored."); + } + } + let m; + if (m = /^(\w+)\(([^\)]*)\)/.exec(style)) { + let color; + const name2 = m[1]; + const components = m[2]; + switch (name2) { + case "rgb": + case "rgba": + if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB(Math.min(255, parseInt(color[1], 10)) / 255, Math.min(255, parseInt(color[2], 10)) / 255, Math.min(255, parseInt(color[3], 10)) / 255, colorSpace); + } + if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB(Math.min(100, parseInt(color[1], 10)) / 100, Math.min(100, parseInt(color[2], 10)) / 100, Math.min(100, parseInt(color[3], 10)) / 100, colorSpace); + } + break; + case "hsl": + case "hsla": + if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setHSL(parseFloat(color[1]) / 360, parseFloat(color[2]) / 100, parseFloat(color[3]) / 100, colorSpace); + } + break; + default: + console.warn("THREE.Color: Unknown color model " + style); + } + } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) { + const hex = m[1]; + const size2 = hex.length; + if (size2 === 3) { + return this.setRGB(parseInt(hex.charAt(0), 16) / 15, parseInt(hex.charAt(1), 16) / 15, parseInt(hex.charAt(2), 16) / 15, colorSpace); + } else if (size2 === 6) { + return this.setHex(parseInt(hex, 16), colorSpace); + } else { + console.warn("THREE.Color: Invalid hex color " + style); + } + } else if (style && style.length > 0) { + return this.setColorName(style, colorSpace); + } + return this; + } + setColorName(style, colorSpace = SRGBColorSpace2) { + const hex = _colorKeywords2[style.toLowerCase()]; + if (hex !== undefined) { + this.setHex(hex, colorSpace); + } else { + console.warn("THREE.Color: Unknown color " + style); + } + return this; + } + clone() { + return new this.constructor(this.r, this.g, this.b); + } + copy(color) { + this.r = color.r; + this.g = color.g; + this.b = color.b; + return this; + } + copySRGBToLinear(color) { + this.r = SRGBToLinear2(color.r); + this.g = SRGBToLinear2(color.g); + this.b = SRGBToLinear2(color.b); + return this; + } + copyLinearToSRGB(color) { + this.r = LinearToSRGB2(color.r); + this.g = LinearToSRGB2(color.g); + this.b = LinearToSRGB2(color.b); + return this; + } + convertSRGBToLinear() { + this.copySRGBToLinear(this); + return this; + } + convertLinearToSRGB() { + this.copyLinearToSRGB(this); + return this; + } + getHex(colorSpace = SRGBColorSpace2) { + ColorManagement2.fromWorkingColorSpace(_color4.copy(this), colorSpace); + return Math.round(clamp3(_color4.r * 255, 0, 255)) * 65536 + Math.round(clamp3(_color4.g * 255, 0, 255)) * 256 + Math.round(clamp3(_color4.b * 255, 0, 255)); + } + getHexString(colorSpace = SRGBColorSpace2) { + return ("000000" + this.getHex(colorSpace).toString(16)).slice(-6); + } + getHSL(target, colorSpace = ColorManagement2.workingColorSpace) { + ColorManagement2.fromWorkingColorSpace(_color4.copy(this), colorSpace); + const { r, g: g3, b: b3 } = _color4; + const max = Math.max(r, g3, b3); + const min = Math.min(r, g3, b3); + let hue, saturation; + const lightness = (min + max) / 2; + if (min === max) { + hue = 0; + saturation = 0; + } else { + const delta = max - min; + saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min); + switch (max) { + case r: + hue = (g3 - b3) / delta + (g3 < b3 ? 6 : 0); + break; + case g3: + hue = (b3 - r) / delta + 2; + break; + case b3: + hue = (r - g3) / delta + 4; + break; + } + hue /= 6; + } + target.h = hue; + target.s = saturation; + target.l = lightness; + return target; + } + getRGB(target, colorSpace = ColorManagement2.workingColorSpace) { + ColorManagement2.fromWorkingColorSpace(_color4.copy(this), colorSpace); + target.r = _color4.r; + target.g = _color4.g; + target.b = _color4.b; + return target; + } + getStyle(colorSpace = SRGBColorSpace2) { + ColorManagement2.fromWorkingColorSpace(_color4.copy(this), colorSpace); + const { r, g: g3, b: b3 } = _color4; + if (colorSpace !== SRGBColorSpace2) { + return `color(${colorSpace} ${r.toFixed(3)} ${g3.toFixed(3)} ${b3.toFixed(3)})`; + } + return `rgb(${Math.round(r * 255)},${Math.round(g3 * 255)},${Math.round(b3 * 255)})`; + } + offsetHSL(h, s, l2) { + this.getHSL(_hslA2); + return this.setHSL(_hslA2.h + h, _hslA2.s + s, _hslA2.l + l2); + } + add(color) { + this.r += color.r; + this.g += color.g; + this.b += color.b; + return this; + } + addColors(color1, color2) { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + return this; + } + addScalar(s) { + this.r += s; + this.g += s; + this.b += s; + return this; + } + sub(color) { + this.r = Math.max(0, this.r - color.r); + this.g = Math.max(0, this.g - color.g); + this.b = Math.max(0, this.b - color.b); + return this; + } + multiply(color) { + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + return this; + } + multiplyScalar(s) { + this.r *= s; + this.g *= s; + this.b *= s; + return this; + } + lerp(color, alpha) { + this.r += (color.r - this.r) * alpha; + this.g += (color.g - this.g) * alpha; + this.b += (color.b - this.b) * alpha; + return this; + } + lerpColors(color1, color2, alpha) { + this.r = color1.r + (color2.r - color1.r) * alpha; + this.g = color1.g + (color2.g - color1.g) * alpha; + this.b = color1.b + (color2.b - color1.b) * alpha; + return this; + } + lerpHSL(color, alpha) { + this.getHSL(_hslA2); + color.getHSL(_hslB2); + const h = lerp2(_hslA2.h, _hslB2.h, alpha); + const s = lerp2(_hslA2.s, _hslB2.s, alpha); + const l2 = lerp2(_hslA2.l, _hslB2.l, alpha); + this.setHSL(h, s, l2); + return this; + } + setFromVector3(v) { + this.r = v.x; + this.g = v.y; + this.b = v.z; + return this; + } + applyMatrix3(m) { + const r = this.r, g3 = this.g, b3 = this.b; + const e = m.elements; + this.r = e[0] * r + e[3] * g3 + e[6] * b3; + this.g = e[1] * r + e[4] * g3 + e[7] * b3; + this.b = e[2] * r + e[5] * g3 + e[8] * b3; + return this; + } + equals(c2) { + return c2.r === this.r && c2.g === this.g && c2.b === this.b; + } + fromArray(array, offset = 0) { + this.r = array[offset]; + this.g = array[offset + 1]; + this.b = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.r; + array[offset + 1] = this.g; + array[offset + 2] = this.b; + return array; + } + fromBufferAttribute(attribute, index2) { + this.r = attribute.getX(index2); + this.g = attribute.getY(index2); + this.b = attribute.getZ(index2); + return this; + } + toJSON() { + return this.getHex(); + } + *[Symbol.iterator]() { + yield this.r; + yield this.g; + yield this.b; + } + } + var _color4 = /* @__PURE__ */ new Color2; + Color2.NAMES = _colorKeywords2; + var _materialId2 = 0; + + class Material2 extends EventDispatcher2 { + constructor() { + super(); + this.isMaterial = true; + Object.defineProperty(this, "id", { value: _materialId2++ }); + this.uuid = generateUUID2(); + this.name = ""; + this.type = "Material"; + this.blending = NormalBlending2; + this.side = FrontSide2; + this.vertexColors = false; + this.opacity = 1; + this.transparent = false; + this.alphaHash = false; + this.blendSrc = SrcAlphaFactor2; + this.blendDst = OneMinusSrcAlphaFactor2; + this.blendEquation = AddEquation2; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; + this.blendColor = new Color2(0, 0, 0); + this.blendAlpha = 0; + this.depthFunc = LessEqualDepth2; + this.depthTest = true; + this.depthWrite = true; + this.stencilWriteMask = 255; + this.stencilFunc = AlwaysStencilFunc2; + this.stencilRef = 0; + this.stencilFuncMask = 255; + this.stencilFail = KeepStencilOp2; + this.stencilZFail = KeepStencilOp2; + this.stencilZPass = KeepStencilOp2; + this.stencilWrite = false; + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + this.shadowSide = null; + this.colorWrite = true; + this.precision = null; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + this.dithering = false; + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + this.forceSinglePass = false; + this.visible = true; + this.toneMapped = true; + this.userData = {}; + this.version = 0; + this._alphaTest = 0; + } + get alphaTest() { + return this._alphaTest; + } + set alphaTest(value2) { + if (this._alphaTest > 0 !== value2 > 0) { + this.version++; + } + this._alphaTest = value2; + } + onBeforeRender() { + } + onBeforeCompile() { + } + customProgramCacheKey() { + return this.onBeforeCompile.toString(); + } + setValues(values2) { + if (values2 === undefined) + return; + for (const key2 in values2) { + const newValue = values2[key2]; + if (newValue === undefined) { + console.warn(`THREE.Material: parameter '${key2}' has value of undefined.`); + continue; + } + const currentValue = this[key2]; + if (currentValue === undefined) { + console.warn(`THREE.Material: '${key2}' is not a property of THREE.${this.type}.`); + continue; + } + if (currentValue && currentValue.isColor) { + currentValue.set(newValue); + } else if (currentValue && currentValue.isVector3 && (newValue && newValue.isVector3)) { + currentValue.copy(newValue); + } else { + this[key2] = newValue; + } + } + } + toJSON(meta2) { + const isRootObject = meta2 === undefined || typeof meta2 === "string"; + if (isRootObject) { + meta2 = { + textures: {}, + images: {} + }; + } + const data2 = { + metadata: { + version: 4.6, + type: "Material", + generator: "Material.toJSON" + } + }; + data2.uuid = this.uuid; + data2.type = this.type; + if (this.name !== "") + data2.name = this.name; + if (this.color && this.color.isColor) + data2.color = this.color.getHex(); + if (this.roughness !== undefined) + data2.roughness = this.roughness; + if (this.metalness !== undefined) + data2.metalness = this.metalness; + if (this.sheen !== undefined) + data2.sheen = this.sheen; + if (this.sheenColor && this.sheenColor.isColor) + data2.sheenColor = this.sheenColor.getHex(); + if (this.sheenRoughness !== undefined) + data2.sheenRoughness = this.sheenRoughness; + if (this.emissive && this.emissive.isColor) + data2.emissive = this.emissive.getHex(); + if (this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1) + data2.emissiveIntensity = this.emissiveIntensity; + if (this.specular && this.specular.isColor) + data2.specular = this.specular.getHex(); + if (this.specularIntensity !== undefined) + data2.specularIntensity = this.specularIntensity; + if (this.specularColor && this.specularColor.isColor) + data2.specularColor = this.specularColor.getHex(); + if (this.shininess !== undefined) + data2.shininess = this.shininess; + if (this.clearcoat !== undefined) + data2.clearcoat = this.clearcoat; + if (this.clearcoatRoughness !== undefined) + data2.clearcoatRoughness = this.clearcoatRoughness; + if (this.clearcoatMap && this.clearcoatMap.isTexture) { + data2.clearcoatMap = this.clearcoatMap.toJSON(meta2).uuid; + } + if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) { + data2.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta2).uuid; + } + if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) { + data2.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta2).uuid; + data2.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + } + if (this.dispersion !== undefined) + data2.dispersion = this.dispersion; + if (this.iridescence !== undefined) + data2.iridescence = this.iridescence; + if (this.iridescenceIOR !== undefined) + data2.iridescenceIOR = this.iridescenceIOR; + if (this.iridescenceThicknessRange !== undefined) + data2.iridescenceThicknessRange = this.iridescenceThicknessRange; + if (this.iridescenceMap && this.iridescenceMap.isTexture) { + data2.iridescenceMap = this.iridescenceMap.toJSON(meta2).uuid; + } + if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) { + data2.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta2).uuid; + } + if (this.anisotropy !== undefined) + data2.anisotropy = this.anisotropy; + if (this.anisotropyRotation !== undefined) + data2.anisotropyRotation = this.anisotropyRotation; + if (this.anisotropyMap && this.anisotropyMap.isTexture) { + data2.anisotropyMap = this.anisotropyMap.toJSON(meta2).uuid; + } + if (this.map && this.map.isTexture) + data2.map = this.map.toJSON(meta2).uuid; + if (this.matcap && this.matcap.isTexture) + data2.matcap = this.matcap.toJSON(meta2).uuid; + if (this.alphaMap && this.alphaMap.isTexture) + data2.alphaMap = this.alphaMap.toJSON(meta2).uuid; + if (this.lightMap && this.lightMap.isTexture) { + data2.lightMap = this.lightMap.toJSON(meta2).uuid; + data2.lightMapIntensity = this.lightMapIntensity; + } + if (this.aoMap && this.aoMap.isTexture) { + data2.aoMap = this.aoMap.toJSON(meta2).uuid; + data2.aoMapIntensity = this.aoMapIntensity; + } + if (this.bumpMap && this.bumpMap.isTexture) { + data2.bumpMap = this.bumpMap.toJSON(meta2).uuid; + data2.bumpScale = this.bumpScale; + } + if (this.normalMap && this.normalMap.isTexture) { + data2.normalMap = this.normalMap.toJSON(meta2).uuid; + data2.normalMapType = this.normalMapType; + data2.normalScale = this.normalScale.toArray(); + } + if (this.displacementMap && this.displacementMap.isTexture) { + data2.displacementMap = this.displacementMap.toJSON(meta2).uuid; + data2.displacementScale = this.displacementScale; + data2.displacementBias = this.displacementBias; + } + if (this.roughnessMap && this.roughnessMap.isTexture) + data2.roughnessMap = this.roughnessMap.toJSON(meta2).uuid; + if (this.metalnessMap && this.metalnessMap.isTexture) + data2.metalnessMap = this.metalnessMap.toJSON(meta2).uuid; + if (this.emissiveMap && this.emissiveMap.isTexture) + data2.emissiveMap = this.emissiveMap.toJSON(meta2).uuid; + if (this.specularMap && this.specularMap.isTexture) + data2.specularMap = this.specularMap.toJSON(meta2).uuid; + if (this.specularIntensityMap && this.specularIntensityMap.isTexture) + data2.specularIntensityMap = this.specularIntensityMap.toJSON(meta2).uuid; + if (this.specularColorMap && this.specularColorMap.isTexture) + data2.specularColorMap = this.specularColorMap.toJSON(meta2).uuid; + if (this.envMap && this.envMap.isTexture) { + data2.envMap = this.envMap.toJSON(meta2).uuid; + if (this.combine !== undefined) + data2.combine = this.combine; + } + if (this.envMapRotation !== undefined) + data2.envMapRotation = this.envMapRotation.toArray(); + if (this.envMapIntensity !== undefined) + data2.envMapIntensity = this.envMapIntensity; + if (this.reflectivity !== undefined) + data2.reflectivity = this.reflectivity; + if (this.refractionRatio !== undefined) + data2.refractionRatio = this.refractionRatio; + if (this.gradientMap && this.gradientMap.isTexture) { + data2.gradientMap = this.gradientMap.toJSON(meta2).uuid; + } + if (this.transmission !== undefined) + data2.transmission = this.transmission; + if (this.transmissionMap && this.transmissionMap.isTexture) + data2.transmissionMap = this.transmissionMap.toJSON(meta2).uuid; + if (this.thickness !== undefined) + data2.thickness = this.thickness; + if (this.thicknessMap && this.thicknessMap.isTexture) + data2.thicknessMap = this.thicknessMap.toJSON(meta2).uuid; + if (this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity) + data2.attenuationDistance = this.attenuationDistance; + if (this.attenuationColor !== undefined) + data2.attenuationColor = this.attenuationColor.getHex(); + if (this.size !== undefined) + data2.size = this.size; + if (this.shadowSide !== null) + data2.shadowSide = this.shadowSide; + if (this.sizeAttenuation !== undefined) + data2.sizeAttenuation = this.sizeAttenuation; + if (this.blending !== NormalBlending2) + data2.blending = this.blending; + if (this.side !== FrontSide2) + data2.side = this.side; + if (this.vertexColors === true) + data2.vertexColors = true; + if (this.opacity < 1) + data2.opacity = this.opacity; + if (this.transparent === true) + data2.transparent = true; + if (this.blendSrc !== SrcAlphaFactor2) + data2.blendSrc = this.blendSrc; + if (this.blendDst !== OneMinusSrcAlphaFactor2) + data2.blendDst = this.blendDst; + if (this.blendEquation !== AddEquation2) + data2.blendEquation = this.blendEquation; + if (this.blendSrcAlpha !== null) + data2.blendSrcAlpha = this.blendSrcAlpha; + if (this.blendDstAlpha !== null) + data2.blendDstAlpha = this.blendDstAlpha; + if (this.blendEquationAlpha !== null) + data2.blendEquationAlpha = this.blendEquationAlpha; + if (this.blendColor && this.blendColor.isColor) + data2.blendColor = this.blendColor.getHex(); + if (this.blendAlpha !== 0) + data2.blendAlpha = this.blendAlpha; + if (this.depthFunc !== LessEqualDepth2) + data2.depthFunc = this.depthFunc; + if (this.depthTest === false) + data2.depthTest = this.depthTest; + if (this.depthWrite === false) + data2.depthWrite = this.depthWrite; + if (this.colorWrite === false) + data2.colorWrite = this.colorWrite; + if (this.stencilWriteMask !== 255) + data2.stencilWriteMask = this.stencilWriteMask; + if (this.stencilFunc !== AlwaysStencilFunc2) + data2.stencilFunc = this.stencilFunc; + if (this.stencilRef !== 0) + data2.stencilRef = this.stencilRef; + if (this.stencilFuncMask !== 255) + data2.stencilFuncMask = this.stencilFuncMask; + if (this.stencilFail !== KeepStencilOp2) + data2.stencilFail = this.stencilFail; + if (this.stencilZFail !== KeepStencilOp2) + data2.stencilZFail = this.stencilZFail; + if (this.stencilZPass !== KeepStencilOp2) + data2.stencilZPass = this.stencilZPass; + if (this.stencilWrite === true) + data2.stencilWrite = this.stencilWrite; + if (this.rotation !== undefined && this.rotation !== 0) + data2.rotation = this.rotation; + if (this.polygonOffset === true) + data2.polygonOffset = true; + if (this.polygonOffsetFactor !== 0) + data2.polygonOffsetFactor = this.polygonOffsetFactor; + if (this.polygonOffsetUnits !== 0) + data2.polygonOffsetUnits = this.polygonOffsetUnits; + if (this.linewidth !== undefined && this.linewidth !== 1) + data2.linewidth = this.linewidth; + if (this.dashSize !== undefined) + data2.dashSize = this.dashSize; + if (this.gapSize !== undefined) + data2.gapSize = this.gapSize; + if (this.scale !== undefined) + data2.scale = this.scale; + if (this.dithering === true) + data2.dithering = true; + if (this.alphaTest > 0) + data2.alphaTest = this.alphaTest; + if (this.alphaHash === true) + data2.alphaHash = true; + if (this.alphaToCoverage === true) + data2.alphaToCoverage = true; + if (this.premultipliedAlpha === true) + data2.premultipliedAlpha = true; + if (this.forceSinglePass === true) + data2.forceSinglePass = true; + if (this.wireframe === true) + data2.wireframe = true; + if (this.wireframeLinewidth > 1) + data2.wireframeLinewidth = this.wireframeLinewidth; + if (this.wireframeLinecap !== "round") + data2.wireframeLinecap = this.wireframeLinecap; + if (this.wireframeLinejoin !== "round") + data2.wireframeLinejoin = this.wireframeLinejoin; + if (this.flatShading === true) + data2.flatShading = true; + if (this.visible === false) + data2.visible = false; + if (this.toneMapped === false) + data2.toneMapped = false; + if (this.fog === false) + data2.fog = false; + if (Object.keys(this.userData).length > 0) + data2.userData = this.userData; + function extractFromCache(cache) { + const values2 = []; + for (const key2 in cache) { + const data3 = cache[key2]; + delete data3.metadata; + values2.push(data3); + } + return values2; + } + if (isRootObject) { + const textures = extractFromCache(meta2.textures); + const images = extractFromCache(meta2.images); + if (textures.length > 0) + data2.textures = textures; + if (images.length > 0) + data2.images = images; + } + return data2; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + this.opacity = source.opacity; + this.transparent = source.transparent; + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + this.blendColor.copy(source.blendColor); + this.blendAlpha = source.blendAlpha; + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + if (srcPlanes !== null) { + const n2 = srcPlanes.length; + dstPlanes = new Array(n2); + for (let i = 0;i !== n2; ++i) { + dstPlanes[i] = srcPlanes[i].clone(); + } + } + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + this.shadowSide = source.shadowSide; + this.colorWrite = source.colorWrite; + this.precision = source.precision; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + this.dithering = source.dithering; + this.alphaTest = source.alphaTest; + this.alphaHash = source.alphaHash; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + this.forceSinglePass = source.forceSinglePass; + this.visible = source.visible; + this.toneMapped = source.toneMapped; + this.userData = JSON.parse(JSON.stringify(source.userData)); + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + onBuild() { + console.warn("Material: onBuild() has been removed."); + } + } + + class MeshBasicMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshBasicMaterial = true; + this.type = "MeshBasicMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler2; + this.combine = MultiplyOperation2; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } + } + var _tables2 = /* @__PURE__ */ _generateTables2(); + function _generateTables2() { + const buffer = new ArrayBuffer(4); + const floatView = new Float32Array(buffer); + const uint32View = new Uint32Array(buffer); + const baseTable = new Uint32Array(512); + const shiftTable = new Uint32Array(512); + for (let i = 0;i < 256; ++i) { + const e = i - 127; + if (e < -27) { + baseTable[i] = 0; + baseTable[i | 256] = 32768; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else if (e < -14) { + baseTable[i] = 1024 >> -e - 14; + baseTable[i | 256] = 1024 >> -e - 14 | 32768; + shiftTable[i] = -e - 1; + shiftTable[i | 256] = -e - 1; + } else if (e <= 15) { + baseTable[i] = e + 15 << 10; + baseTable[i | 256] = e + 15 << 10 | 32768; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } else if (e < 128) { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } + } + const mantissaTable = new Uint32Array(2048); + const exponentTable = new Uint32Array(64); + const offsetTable = new Uint32Array(64); + for (let i = 1;i < 1024; ++i) { + let m = i << 13; + let e = 0; + while ((m & 8388608) === 0) { + m <<= 1; + e -= 8388608; + } + m &= ~8388608; + e += 947912704; + mantissaTable[i] = m | e; + } + for (let i = 1024;i < 2048; ++i) { + mantissaTable[i] = 939524096 + (i - 1024 << 13); + } + for (let i = 1;i < 31; ++i) { + exponentTable[i] = i << 23; + } + exponentTable[31] = 1199570944; + exponentTable[32] = 2147483648; + for (let i = 33;i < 63; ++i) { + exponentTable[i] = 2147483648 + (i - 32 << 23); + } + exponentTable[63] = 3347054592; + for (let i = 1;i < 64; ++i) { + if (i !== 32) { + offsetTable[i] = 1024; + } + } + return { + floatView, + uint32View, + baseTable, + shiftTable, + mantissaTable, + exponentTable, + offsetTable + }; + } + function toHalfFloat2(val2) { + if (Math.abs(val2) > 65504) + console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."); + val2 = clamp3(val2, -65504, 65504); + _tables2.floatView[0] = val2; + const f = _tables2.uint32View[0]; + const e = f >> 23 & 511; + return _tables2.baseTable[e] + ((f & 8388607) >> _tables2.shiftTable[e]); + } + function fromHalfFloat2(val2) { + const m = val2 >> 10; + _tables2.uint32View[0] = _tables2.mantissaTable[_tables2.offsetTable[m] + (val2 & 1023)] + _tables2.exponentTable[m]; + return _tables2.floatView[0]; + } + var DataUtils2 = { + toHalfFloat: toHalfFloat2, + fromHalfFloat: fromHalfFloat2 + }; + var _vector$92 = /* @__PURE__ */ new Vector32; + var _vector2$12 = /* @__PURE__ */ new Vector22; + var _id$3 = 0; + + class BufferAttribute2 { + constructor(array, itemSize, normalized = false) { + if (Array.isArray(array)) { + throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); + } + this.isBufferAttribute = true; + Object.defineProperty(this, "id", { value: _id$3++ }); + this.name = ""; + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized; + this.usage = StaticDrawUsage2; + this.updateRanges = []; + this.gpuType = FloatType2; + this.version = 0; + } + onUploadCallback() { + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setUsage(value2) { + this.usage = value2; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.name = source.name; + this.array = new source.array.constructor(source.array); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + this.usage = source.usage; + this.gpuType = source.gpuType; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.itemSize; + index2 *= attribute.itemSize; + for (let i = 0, l2 = this.itemSize;i < l2; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + copyArray(array) { + this.array.set(array); + return this; + } + applyMatrix3(m) { + if (this.itemSize === 2) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector2$12.fromBufferAttribute(this, i); + _vector2$12.applyMatrix3(m); + this.setXY(i, _vector2$12.x, _vector2$12.y); + } + } else if (this.itemSize === 3) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector$92.fromBufferAttribute(this, i); + _vector$92.applyMatrix3(m); + this.setXYZ(i, _vector$92.x, _vector$92.y, _vector$92.z); + } + } + return this; + } + applyMatrix4(m) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector$92.fromBufferAttribute(this, i); + _vector$92.applyMatrix4(m); + this.setXYZ(i, _vector$92.x, _vector$92.y, _vector$92.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector$92.fromBufferAttribute(this, i); + _vector$92.applyNormalMatrix(m); + this.setXYZ(i, _vector$92.x, _vector$92.y, _vector$92.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector$92.fromBufferAttribute(this, i); + _vector$92.transformDirection(m); + this.setXYZ(i, _vector$92.x, _vector$92.y, _vector$92.z); + } + return this; + } + set(value2, offset = 0) { + this.array.set(value2, offset); + return this; + } + getComponent(index2, component) { + let value2 = this.array[index2 * this.itemSize + component]; + if (this.normalized) + value2 = denormalize2(value2, this.array); + return value2; + } + setComponent(index2, component, value2) { + if (this.normalized) + value2 = normalize3(value2, this.array); + this.array[index2 * this.itemSize + component] = value2; + return this; + } + getX(index2) { + let x2 = this.array[index2 * this.itemSize]; + if (this.normalized) + x2 = denormalize2(x2, this.array); + return x2; + } + setX(index2, x2) { + if (this.normalized) + x2 = normalize3(x2, this.array); + this.array[index2 * this.itemSize] = x2; + return this; + } + getY(index2) { + let y3 = this.array[index2 * this.itemSize + 1]; + if (this.normalized) + y3 = denormalize2(y3, this.array); + return y3; + } + setY(index2, y3) { + if (this.normalized) + y3 = normalize3(y3, this.array); + this.array[index2 * this.itemSize + 1] = y3; + return this; + } + getZ(index2) { + let z2 = this.array[index2 * this.itemSize + 2]; + if (this.normalized) + z2 = denormalize2(z2, this.array); + return z2; + } + setZ(index2, z2) { + if (this.normalized) + z2 = normalize3(z2, this.array); + this.array[index2 * this.itemSize + 2] = z2; + return this; + } + getW(index2) { + let w = this.array[index2 * this.itemSize + 3]; + if (this.normalized) + w = denormalize2(w, this.array); + return w; + } + setW(index2, w) { + if (this.normalized) + w = normalize3(w, this.array); + this.array[index2 * this.itemSize + 3] = w; + return this; + } + setXY(index2, x2, y3) { + index2 *= this.itemSize; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y3 = normalize3(y3, this.array); + } + this.array[index2 + 0] = x2; + this.array[index2 + 1] = y3; + return this; + } + setXYZ(index2, x2, y3, z2) { + index2 *= this.itemSize; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y3 = normalize3(y3, this.array); + z2 = normalize3(z2, this.array); + } + this.array[index2 + 0] = x2; + this.array[index2 + 1] = y3; + this.array[index2 + 2] = z2; + return this; + } + setXYZW(index2, x2, y3, z2, w) { + index2 *= this.itemSize; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y3 = normalize3(y3, this.array); + z2 = normalize3(z2, this.array); + w = normalize3(w, this.array); + } + this.array[index2 + 0] = x2; + this.array[index2 + 1] = y3; + this.array[index2 + 2] = z2; + this.array[index2 + 3] = w; + return this; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + clone() { + return new this.constructor(this.array, this.itemSize).copy(this); + } + toJSON() { + const data2 = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from(this.array), + normalized: this.normalized + }; + if (this.name !== "") + data2.name = this.name; + if (this.usage !== StaticDrawUsage2) + data2.usage = this.usage; + return data2; + } + } + + class Int8BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Int8Array(array), itemSize, normalized); + } + } + + class Uint8BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint8Array(array), itemSize, normalized); + } + } + + class Uint8ClampedBufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint8ClampedArray(array), itemSize, normalized); + } + } + + class Int16BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Int16Array(array), itemSize, normalized); + } + } + + class Uint16BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + } + } + + class Int32BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Int32Array(array), itemSize, normalized); + } + } + + class Uint32BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint32Array(array), itemSize, normalized); + } + } + + class Float16BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + this.isFloat16BufferAttribute = true; + } + getX(index2) { + let x2 = fromHalfFloat2(this.array[index2 * this.itemSize]); + if (this.normalized) + x2 = denormalize2(x2, this.array); + return x2; + } + setX(index2, x2) { + if (this.normalized) + x2 = normalize3(x2, this.array); + this.array[index2 * this.itemSize] = toHalfFloat2(x2); + return this; + } + getY(index2) { + let y3 = fromHalfFloat2(this.array[index2 * this.itemSize + 1]); + if (this.normalized) + y3 = denormalize2(y3, this.array); + return y3; + } + setY(index2, y3) { + if (this.normalized) + y3 = normalize3(y3, this.array); + this.array[index2 * this.itemSize + 1] = toHalfFloat2(y3); + return this; + } + getZ(index2) { + let z2 = fromHalfFloat2(this.array[index2 * this.itemSize + 2]); + if (this.normalized) + z2 = denormalize2(z2, this.array); + return z2; + } + setZ(index2, z2) { + if (this.normalized) + z2 = normalize3(z2, this.array); + this.array[index2 * this.itemSize + 2] = toHalfFloat2(z2); + return this; + } + getW(index2) { + let w = fromHalfFloat2(this.array[index2 * this.itemSize + 3]); + if (this.normalized) + w = denormalize2(w, this.array); + return w; + } + setW(index2, w) { + if (this.normalized) + w = normalize3(w, this.array); + this.array[index2 * this.itemSize + 3] = toHalfFloat2(w); + return this; + } + setXY(index2, x2, y3) { + index2 *= this.itemSize; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y3 = normalize3(y3, this.array); + } + this.array[index2 + 0] = toHalfFloat2(x2); + this.array[index2 + 1] = toHalfFloat2(y3); + return this; + } + setXYZ(index2, x2, y3, z2) { + index2 *= this.itemSize; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y3 = normalize3(y3, this.array); + z2 = normalize3(z2, this.array); + } + this.array[index2 + 0] = toHalfFloat2(x2); + this.array[index2 + 1] = toHalfFloat2(y3); + this.array[index2 + 2] = toHalfFloat2(z2); + return this; + } + setXYZW(index2, x2, y3, z2, w) { + index2 *= this.itemSize; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y3 = normalize3(y3, this.array); + z2 = normalize3(z2, this.array); + w = normalize3(w, this.array); + } + this.array[index2 + 0] = toHalfFloat2(x2); + this.array[index2 + 1] = toHalfFloat2(y3); + this.array[index2 + 2] = toHalfFloat2(z2); + this.array[index2 + 3] = toHalfFloat2(w); + return this; + } + } + + class Float32BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Float32Array(array), itemSize, normalized); + } + } + var _id$22 = 0; + var _m1$22 = /* @__PURE__ */ new Matrix42; + var _obj2 = /* @__PURE__ */ new Object3D2; + var _offset4 = /* @__PURE__ */ new Vector32; + var _box$22 = /* @__PURE__ */ new Box32; + var _boxMorphTargets2 = /* @__PURE__ */ new Box32; + var _vector$82 = /* @__PURE__ */ new Vector32; + + class BufferGeometry2 extends EventDispatcher2 { + constructor() { + super(); + this.isBufferGeometry = true; + Object.defineProperty(this, "id", { value: _id$22++ }); + this.uuid = generateUUID2(); + this.name = ""; + this.type = "BufferGeometry"; + this.index = null; + this.indirect = null; + this.attributes = {}; + this.morphAttributes = {}; + this.morphTargetsRelative = false; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + this.drawRange = { start: 0, count: Infinity }; + this.userData = {}; + } + getIndex() { + return this.index; + } + setIndex(index2) { + if (Array.isArray(index2)) { + this.index = new ((arrayNeedsUint322(index2)) ? Uint32BufferAttribute2 : Uint16BufferAttribute2)(index2, 1); + } else { + this.index = index2; + } + return this; + } + setIndirect(indirect) { + this.indirect = indirect; + return this; + } + getIndirect() { + return this.indirect; + } + getAttribute(name2) { + return this.attributes[name2]; + } + setAttribute(name2, attribute) { + this.attributes[name2] = attribute; + return this; + } + deleteAttribute(name2) { + delete this.attributes[name2]; + return this; + } + hasAttribute(name2) { + return this.attributes[name2] !== undefined; + } + addGroup(start, count, materialIndex = 0) { + this.groups.push({ + start, + count, + materialIndex + }); + } + clearGroups() { + this.groups = []; + } + setDrawRange(start, count) { + this.drawRange.start = start; + this.drawRange.count = count; + } + applyMatrix4(matrix3) { + const position2 = this.attributes.position; + if (position2 !== undefined) { + position2.applyMatrix4(matrix3); + position2.needsUpdate = true; + } + const normal = this.attributes.normal; + if (normal !== undefined) { + const normalMatrix = new Matrix32().getNormalMatrix(matrix3); + normal.applyNormalMatrix(normalMatrix); + normal.needsUpdate = true; + } + const tangent = this.attributes.tangent; + if (tangent !== undefined) { + tangent.transformDirection(matrix3); + tangent.needsUpdate = true; + } + if (this.boundingBox !== null) { + this.computeBoundingBox(); + } + if (this.boundingSphere !== null) { + this.computeBoundingSphere(); + } + return this; + } + applyQuaternion(q2) { + _m1$22.makeRotationFromQuaternion(q2); + this.applyMatrix4(_m1$22); + return this; + } + rotateX(angle) { + _m1$22.makeRotationX(angle); + this.applyMatrix4(_m1$22); + return this; + } + rotateY(angle) { + _m1$22.makeRotationY(angle); + this.applyMatrix4(_m1$22); + return this; + } + rotateZ(angle) { + _m1$22.makeRotationZ(angle); + this.applyMatrix4(_m1$22); + return this; + } + translate(x2, y3, z2) { + _m1$22.makeTranslation(x2, y3, z2); + this.applyMatrix4(_m1$22); + return this; + } + scale(x2, y3, z2) { + _m1$22.makeScale(x2, y3, z2); + this.applyMatrix4(_m1$22); + return this; + } + lookAt(vector) { + _obj2.lookAt(vector); + _obj2.updateMatrix(); + this.applyMatrix4(_obj2.matrix); + return this; + } + center() { + this.computeBoundingBox(); + this.boundingBox.getCenter(_offset4).negate(); + this.translate(_offset4.x, _offset4.y, _offset4.z); + return this; + } + setFromPoints(points) { + const positionAttribute = this.getAttribute("position"); + if (positionAttribute === undefined) { + const position2 = []; + for (let i = 0, l2 = points.length;i < l2; i++) { + const point = points[i]; + position2.push(point.x, point.y, point.z || 0); + } + this.setAttribute("position", new Float32BufferAttribute2(position2, 3)); + } else { + const l2 = Math.min(points.length, positionAttribute.count); + for (let i = 0;i < l2; i++) { + const point = points[i]; + positionAttribute.setXYZ(i, point.x, point.y, point.z || 0); + } + if (points.length > positionAttribute.count) { + console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."); + } + positionAttribute.needsUpdate = true; + } + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box32; + } + const position2 = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position2 && position2.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this); + this.boundingBox.set(new Vector32(-Infinity, -Infinity, -Infinity), new Vector32(Infinity, Infinity, Infinity)); + return; + } + if (position2 !== undefined) { + this.boundingBox.setFromBufferAttribute(position2); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _box$22.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$82.addVectors(this.boundingBox.min, _box$22.min); + this.boundingBox.expandByPoint(_vector$82); + _vector$82.addVectors(this.boundingBox.max, _box$22.max); + this.boundingBox.expandByPoint(_vector$82); + } else { + this.boundingBox.expandByPoint(_box$22.min); + this.boundingBox.expandByPoint(_box$22.max); + } + } + } + } else { + this.boundingBox.makeEmpty(); + } + if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) { + console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere2; + } + const position2 = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position2 && position2.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this); + this.boundingSphere.set(new Vector32, Infinity); + return; + } + if (position2) { + const center = this.boundingSphere.center; + _box$22.setFromBufferAttribute(position2); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _boxMorphTargets2.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$82.addVectors(_box$22.min, _boxMorphTargets2.min); + _box$22.expandByPoint(_vector$82); + _vector$82.addVectors(_box$22.max, _boxMorphTargets2.max); + _box$22.expandByPoint(_vector$82); + } else { + _box$22.expandByPoint(_boxMorphTargets2.min); + _box$22.expandByPoint(_boxMorphTargets2.max); + } + } + } + _box$22.getCenter(center); + let maxRadiusSq = 0; + for (let i = 0, il = position2.count;i < il; i++) { + _vector$82.fromBufferAttribute(position2, i); + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$82)); + } + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + const morphTargetsRelative = this.morphTargetsRelative; + for (let j2 = 0, jl = morphAttribute.count;j2 < jl; j2++) { + _vector$82.fromBufferAttribute(morphAttribute, j2); + if (morphTargetsRelative) { + _offset4.fromBufferAttribute(position2, j2); + _vector$82.add(_offset4); + } + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$82)); + } + } + } + this.boundingSphere.radius = Math.sqrt(maxRadiusSq); + if (isNaN(this.boundingSphere.radius)) { + console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); + } + } + } + computeTangents() { + const index2 = this.index; + const attributes = this.attributes; + if (index2 === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) { + console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); + return; + } + const positionAttribute = attributes.position; + const normalAttribute = attributes.normal; + const uvAttribute = attributes.uv; + if (this.hasAttribute("tangent") === false) { + this.setAttribute("tangent", new BufferAttribute2(new Float32Array(4 * positionAttribute.count), 4)); + } + const tangentAttribute = this.getAttribute("tangent"); + const tan1 = [], tan2 = []; + for (let i = 0;i < positionAttribute.count; i++) { + tan1[i] = new Vector32; + tan2[i] = new Vector32; + } + const vA = new Vector32, vB = new Vector32, vC = new Vector32, uvA = new Vector22, uvB = new Vector22, uvC = new Vector22, sdir = new Vector32, tdir = new Vector32; + function handleTriangle(a2, b3, c2) { + vA.fromBufferAttribute(positionAttribute, a2); + vB.fromBufferAttribute(positionAttribute, b3); + vC.fromBufferAttribute(positionAttribute, c2); + uvA.fromBufferAttribute(uvAttribute, a2); + uvB.fromBufferAttribute(uvAttribute, b3); + uvC.fromBufferAttribute(uvAttribute, c2); + vB.sub(vA); + vC.sub(vA); + uvB.sub(uvA); + uvC.sub(uvA); + const r = 1 / (uvB.x * uvC.y - uvC.x * uvB.y); + if (!isFinite(r)) + return; + sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r); + tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r); + tan1[a2].add(sdir); + tan1[b3].add(sdir); + tan1[c2].add(sdir); + tan2[a2].add(tdir); + tan2[b3].add(tdir); + tan2[c2].add(tdir); + } + let groups = this.groups; + if (groups.length === 0) { + groups = [{ + start: 0, + count: index2.count + }]; + } + for (let i = 0, il = groups.length;i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j2 = start, jl = start + count;j2 < jl; j2 += 3) { + handleTriangle(index2.getX(j2 + 0), index2.getX(j2 + 1), index2.getX(j2 + 2)); + } + } + const tmp3 = new Vector32, tmp22 = new Vector32; + const n2 = new Vector32, n22 = new Vector32; + function handleVertex(v) { + n2.fromBufferAttribute(normalAttribute, v); + n22.copy(n2); + const t4 = tan1[v]; + tmp3.copy(t4); + tmp3.sub(n2.multiplyScalar(n2.dot(t4))).normalize(); + tmp22.crossVectors(n22, t4); + const test = tmp22.dot(tan2[v]); + const w = test < 0 ? -1 : 1; + tangentAttribute.setXYZW(v, tmp3.x, tmp3.y, tmp3.z, w); + } + for (let i = 0, il = groups.length;i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j2 = start, jl = start + count;j2 < jl; j2 += 3) { + handleVertex(index2.getX(j2 + 0)); + handleVertex(index2.getX(j2 + 1)); + handleVertex(index2.getX(j2 + 2)); + } + } + } + computeVertexNormals() { + const index2 = this.index; + const positionAttribute = this.getAttribute("position"); + if (positionAttribute !== undefined) { + let normalAttribute = this.getAttribute("normal"); + if (normalAttribute === undefined) { + normalAttribute = new BufferAttribute2(new Float32Array(positionAttribute.count * 3), 3); + this.setAttribute("normal", normalAttribute); + } else { + for (let i = 0, il = normalAttribute.count;i < il; i++) { + normalAttribute.setXYZ(i, 0, 0, 0); + } + } + const pA = new Vector32, pB = new Vector32, pC = new Vector32; + const nA = new Vector32, nB = new Vector32, nC = new Vector32; + const cb = new Vector32, ab = new Vector32; + if (index2) { + for (let i = 0, il = index2.count;i < il; i += 3) { + const vA = index2.getX(i + 0); + const vB = index2.getX(i + 1); + const vC = index2.getX(i + 2); + pA.fromBufferAttribute(positionAttribute, vA); + pB.fromBufferAttribute(positionAttribute, vB); + pC.fromBufferAttribute(positionAttribute, vC); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + nA.fromBufferAttribute(normalAttribute, vA); + nB.fromBufferAttribute(normalAttribute, vB); + nC.fromBufferAttribute(normalAttribute, vC); + nA.add(cb); + nB.add(cb); + nC.add(cb); + normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z); + normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z); + normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z); + } + } else { + for (let i = 0, il = positionAttribute.count;i < il; i += 3) { + pA.fromBufferAttribute(positionAttribute, i + 0); + pB.fromBufferAttribute(positionAttribute, i + 1); + pC.fromBufferAttribute(positionAttribute, i + 2); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z); + } + } + this.normalizeNormals(); + normalAttribute.needsUpdate = true; + } + } + normalizeNormals() { + const normals = this.attributes.normal; + for (let i = 0, il = normals.count;i < il; i++) { + _vector$82.fromBufferAttribute(normals, i); + _vector$82.normalize(); + normals.setXYZ(i, _vector$82.x, _vector$82.y, _vector$82.z); + } + } + toNonIndexed() { + function convertBufferAttribute(attribute, indices2) { + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + const array2 = new array.constructor(indices2.length * itemSize); + let index2 = 0, index22 = 0; + for (let i = 0, l2 = indices2.length;i < l2; i++) { + if (attribute.isInterleavedBufferAttribute) { + index2 = indices2[i] * attribute.data.stride + attribute.offset; + } else { + index2 = indices2[i] * itemSize; + } + for (let j2 = 0;j2 < itemSize; j2++) { + array2[index22++] = array[index2++]; + } + } + return new BufferAttribute2(array2, itemSize, normalized); + } + if (this.index === null) { + console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."); + return this; + } + const geometry2 = new BufferGeometry2; + const indices = this.index.array; + const attributes = this.attributes; + for (const name2 in attributes) { + const attribute = attributes[name2]; + const newAttribute = convertBufferAttribute(attribute, indices); + geometry2.setAttribute(name2, newAttribute); + } + const morphAttributes = this.morphAttributes; + for (const name2 in morphAttributes) { + const morphArray = []; + const morphAttribute = morphAttributes[name2]; + for (let i = 0, il = morphAttribute.length;i < il; i++) { + const attribute = morphAttribute[i]; + const newAttribute = convertBufferAttribute(attribute, indices); + morphArray.push(newAttribute); + } + geometry2.morphAttributes[name2] = morphArray; + } + geometry2.morphTargetsRelative = this.morphTargetsRelative; + const groups = this.groups; + for (let i = 0, l2 = groups.length;i < l2; i++) { + const group = groups[i]; + geometry2.addGroup(group.start, group.count, group.materialIndex); + } + return geometry2; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "BufferGeometry", + generator: "BufferGeometry.toJSON" + } + }; + data2.uuid = this.uuid; + data2.type = this.type; + if (this.name !== "") + data2.name = this.name; + if (Object.keys(this.userData).length > 0) + data2.userData = this.userData; + if (this.parameters !== undefined) { + const parameters = this.parameters; + for (const key2 in parameters) { + if (parameters[key2] !== undefined) + data2[key2] = parameters[key2]; + } + return data2; + } + data2.data = { attributes: {} }; + const index2 = this.index; + if (index2 !== null) { + data2.data.index = { + type: index2.array.constructor.name, + array: Array.prototype.slice.call(index2.array) + }; + } + const attributes = this.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + data2.data.attributes[key2] = attribute.toJSON(data2.data); + } + const morphAttributes = {}; + let hasMorphAttributes = false; + for (const key2 in this.morphAttributes) { + const attributeArray = this.morphAttributes[key2]; + const array = []; + for (let i = 0, il = attributeArray.length;i < il; i++) { + const attribute = attributeArray[i]; + array.push(attribute.toJSON(data2.data)); + } + if (array.length > 0) { + morphAttributes[key2] = array; + hasMorphAttributes = true; + } + } + if (hasMorphAttributes) { + data2.data.morphAttributes = morphAttributes; + data2.data.morphTargetsRelative = this.morphTargetsRelative; + } + const groups = this.groups; + if (groups.length > 0) { + data2.data.groups = JSON.parse(JSON.stringify(groups)); + } + const boundingSphere = this.boundingSphere; + if (boundingSphere !== null) { + data2.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; + } + return data2; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + const data2 = {}; + this.name = source.name; + const index2 = source.index; + if (index2 !== null) { + this.setIndex(index2.clone(data2)); + } + const attributes = source.attributes; + for (const name2 in attributes) { + const attribute = attributes[name2]; + this.setAttribute(name2, attribute.clone(data2)); + } + const morphAttributes = source.morphAttributes; + for (const name2 in morphAttributes) { + const array = []; + const morphAttribute = morphAttributes[name2]; + for (let i = 0, l2 = morphAttribute.length;i < l2; i++) { + array.push(morphAttribute[i].clone(data2)); + } + this.morphAttributes[name2] = array; + } + this.morphTargetsRelative = source.morphTargetsRelative; + const groups = source.groups; + for (let i = 0, l2 = groups.length;i < l2; i++) { + const group = groups[i]; + this.addGroup(group.start, group.count, group.materialIndex); + } + const boundingBox = source.boundingBox; + if (boundingBox !== null) { + this.boundingBox = boundingBox.clone(); + } + const boundingSphere = source.boundingSphere; + if (boundingSphere !== null) { + this.boundingSphere = boundingSphere.clone(); + } + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + this.userData = source.userData; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + } + var _inverseMatrix$32 = /* @__PURE__ */ new Matrix42; + var _ray$32 = /* @__PURE__ */ new Ray2; + var _sphere$62 = /* @__PURE__ */ new Sphere2; + var _sphereHitAt2 = /* @__PURE__ */ new Vector32; + var _vA$12 = /* @__PURE__ */ new Vector32; + var _vB$12 = /* @__PURE__ */ new Vector32; + var _vC$12 = /* @__PURE__ */ new Vector32; + var _tempA2 = /* @__PURE__ */ new Vector32; + var _morphA2 = /* @__PURE__ */ new Vector32; + var _intersectionPoint2 = /* @__PURE__ */ new Vector32; + var _intersectionPointWorld2 = /* @__PURE__ */ new Vector32; + + class Mesh2 extends Object3D2 { + constructor(geometry = new BufferGeometry2, material = new MeshBasicMaterial2) { + super(); + this.isMesh = true; + this.type = "Mesh"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.morphTargetInfluences !== undefined) { + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + } + if (source.morphTargetDictionary !== undefined) { + this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary); + } + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } + getVertexPosition(index2, target) { + const geometry = this.geometry; + const position2 = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + target.fromBufferAttribute(position2, index2); + const morphInfluences = this.morphTargetInfluences; + if (morphPosition && morphInfluences) { + _morphA2.set(0, 0, 0); + for (let i = 0, il = morphPosition.length;i < il; i++) { + const influence = morphInfluences[i]; + const morphAttribute = morphPosition[i]; + if (influence === 0) + continue; + _tempA2.fromBufferAttribute(morphAttribute, index2); + if (morphTargetsRelative) { + _morphA2.addScaledVector(_tempA2, influence); + } else { + _morphA2.addScaledVector(_tempA2.sub(target), influence); + } + } + target.add(_morphA2); + } + return target; + } + raycast(raycaster, intersects3) { + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === undefined) + return; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$62.copy(geometry.boundingSphere); + _sphere$62.applyMatrix4(matrixWorld); + _ray$32.copy(raycaster.ray).recast(raycaster.near); + if (_sphere$62.containsPoint(_ray$32.origin) === false) { + if (_ray$32.intersectSphere(_sphere$62, _sphereHitAt2) === null) + return; + if (_ray$32.origin.distanceToSquared(_sphereHitAt2) > (raycaster.far - raycaster.near) ** 2) + return; + } + _inverseMatrix$32.copy(matrixWorld).invert(); + _ray$32.copy(raycaster.ray).applyMatrix4(_inverseMatrix$32); + if (geometry.boundingBox !== null) { + if (_ray$32.intersectsBox(geometry.boundingBox) === false) + return; + } + this._computeIntersections(raycaster, intersects3, _ray$32); + } + _computeIntersections(raycaster, intersects3, rayLocalSpace) { + let intersection; + const geometry = this.geometry; + const material = this.material; + const index2 = geometry.index; + const position2 = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv1 = geometry.attributes.uv1; + const normal = geometry.attributes.normal; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + if (index2 !== null) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length;i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(index2.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j2 = start, jl = end;j2 < jl; j2 += 3) { + const a2 = index2.getX(j2); + const b3 = index2.getX(j2 + 1); + const c2 = index2.getX(j2 + 2); + intersection = checkGeometryIntersection2(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a2, b3, c2); + if (intersection) { + intersection.faceIndex = Math.floor(j2 / 3); + intersection.face.materialIndex = group.materialIndex; + intersects3.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i += 3) { + const a2 = index2.getX(i); + const b3 = index2.getX(i + 1); + const c2 = index2.getX(i + 2); + intersection = checkGeometryIntersection2(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a2, b3, c2); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects3.push(intersection); + } + } + } + } else if (position2 !== undefined) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length;i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(position2.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j2 = start, jl = end;j2 < jl; j2 += 3) { + const a2 = j2; + const b3 = j2 + 1; + const c2 = j2 + 2; + intersection = checkGeometryIntersection2(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a2, b3, c2); + if (intersection) { + intersection.faceIndex = Math.floor(j2 / 3); + intersection.face.materialIndex = group.materialIndex; + intersects3.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(position2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i += 3) { + const a2 = i; + const b3 = i + 1; + const c2 = i + 2; + intersection = checkGeometryIntersection2(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a2, b3, c2); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects3.push(intersection); + } + } + } + } + } + } + function checkIntersection$12(object, material, raycaster, ray, pA, pB, pC, point) { + let intersect3; + if (material.side === BackSide2) { + intersect3 = ray.intersectTriangle(pC, pB, pA, true, point); + } else { + intersect3 = ray.intersectTriangle(pA, pB, pC, material.side === FrontSide2, point); + } + if (intersect3 === null) + return null; + _intersectionPointWorld2.copy(point); + _intersectionPointWorld2.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld2); + if (distance < raycaster.near || distance > raycaster.far) + return null; + return { + distance, + point: _intersectionPointWorld2.clone(), + object + }; + } + function checkGeometryIntersection2(object, material, raycaster, ray, uv, uv1, normal, a2, b3, c2) { + object.getVertexPosition(a2, _vA$12); + object.getVertexPosition(b3, _vB$12); + object.getVertexPosition(c2, _vC$12); + const intersection = checkIntersection$12(object, material, raycaster, ray, _vA$12, _vB$12, _vC$12, _intersectionPoint2); + if (intersection) { + const barycoord = new Vector32; + Triangle2.getBarycoord(_intersectionPoint2, _vA$12, _vB$12, _vC$12, barycoord); + if (uv) { + intersection.uv = Triangle2.getInterpolatedAttribute(uv, a2, b3, c2, barycoord, new Vector22); + } + if (uv1) { + intersection.uv1 = Triangle2.getInterpolatedAttribute(uv1, a2, b3, c2, barycoord, new Vector22); + } + if (normal) { + intersection.normal = Triangle2.getInterpolatedAttribute(normal, a2, b3, c2, barycoord, new Vector32); + if (intersection.normal.dot(ray.direction) > 0) { + intersection.normal.multiplyScalar(-1); + } + } + const face = { + a: a2, + b: b3, + c: c2, + normal: new Vector32, + materialIndex: 0 + }; + Triangle2.getNormal(_vA$12, _vB$12, _vC$12, face.normal); + intersection.face = face; + intersection.barycoord = barycoord; + } + return intersection; + } + + class BoxGeometry2 extends BufferGeometry2 { + constructor(width2 = 1, height2 = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) { + super(); + this.type = "BoxGeometry"; + this.parameters = { + width: width2, + height: height2, + depth, + widthSegments, + heightSegments, + depthSegments + }; + const scope = this; + widthSegments = Math.floor(widthSegments); + heightSegments = Math.floor(heightSegments); + depthSegments = Math.floor(depthSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let numberOfVertices = 0; + let groupStart = 0; + buildPlane("z", "y", "x", -1, -1, depth, height2, width2, depthSegments, heightSegments, 0); + buildPlane("z", "y", "x", 1, -1, depth, height2, -width2, depthSegments, heightSegments, 1); + buildPlane("x", "z", "y", 1, 1, width2, depth, height2, widthSegments, depthSegments, 2); + buildPlane("x", "z", "y", 1, -1, width2, depth, -height2, widthSegments, depthSegments, 3); + buildPlane("x", "y", "z", 1, -1, width2, height2, depth, widthSegments, heightSegments, 4); + buildPlane("x", "y", "z", -1, -1, width2, height2, -depth, widthSegments, heightSegments, 5); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function buildPlane(u3, v, w, udir, vdir, width3, height3, depth2, gridX, gridY, materialIndex) { + const segmentWidth = width3 / gridX; + const segmentHeight = height3 / gridY; + const widthHalf = width3 / 2; + const heightHalf = height3 / 2; + const depthHalf = depth2 / 2; + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + let vertexCounter = 0; + let groupCount = 0; + const vector = new Vector32; + for (let iy = 0;iy < gridY1; iy++) { + const y3 = iy * segmentHeight - heightHalf; + for (let ix = 0;ix < gridX1; ix++) { + const x2 = ix * segmentWidth - widthHalf; + vector[u3] = x2 * udir; + vector[v] = y3 * vdir; + vector[w] = depthHalf; + vertices.push(vector.x, vector.y, vector.z); + vector[u3] = 0; + vector[v] = 0; + vector[w] = depth2 > 0 ? 1 : -1; + normals.push(vector.x, vector.y, vector.z); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + vertexCounter += 1; + } + } + for (let iy = 0;iy < gridY; iy++) { + for (let ix = 0;ix < gridX; ix++) { + const a2 = numberOfVertices + ix + gridX1 * iy; + const b3 = numberOfVertices + ix + gridX1 * (iy + 1); + const c2 = numberOfVertices + (ix + 1) + gridX1 * (iy + 1); + const d = numberOfVertices + (ix + 1) + gridX1 * iy; + indices.push(a2, b3, d); + indices.push(b3, c2, d); + groupCount += 6; + } + } + scope.addGroup(groupStart, groupCount, materialIndex); + groupStart += groupCount; + numberOfVertices += vertexCounter; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new BoxGeometry2(data2.width, data2.height, data2.depth, data2.widthSegments, data2.heightSegments, data2.depthSegments); + } + } + function cloneUniforms2(src) { + const dst = {}; + for (const u3 in src) { + dst[u3] = {}; + for (const p in src[u3]) { + const property2 = src[u3][p]; + if (property2 && (property2.isColor || property2.isMatrix3 || property2.isMatrix4 || property2.isVector2 || property2.isVector3 || property2.isVector4 || property2.isTexture || property2.isQuaternion)) { + if (property2.isRenderTargetTexture) { + console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."); + dst[u3][p] = null; + } else { + dst[u3][p] = property2.clone(); + } + } else if (Array.isArray(property2)) { + dst[u3][p] = property2.slice(); + } else { + dst[u3][p] = property2; + } + } + } + return dst; + } + function mergeUniforms2(uniforms) { + const merged = {}; + for (let u3 = 0;u3 < uniforms.length; u3++) { + const tmp3 = cloneUniforms2(uniforms[u3]); + for (const p in tmp3) { + merged[p] = tmp3[p]; + } + } + return merged; + } + function cloneUniformsGroups2(src) { + const dst = []; + for (let u3 = 0;u3 < src.length; u3++) { + dst.push(src[u3].clone()); + } + return dst; + } + function getUnlitUniformColorSpace2(renderer2) { + const currentRenderTarget = renderer2.getRenderTarget(); + if (currentRenderTarget === null) { + return renderer2.outputColorSpace; + } + if (currentRenderTarget.isXRRenderTarget === true) { + return currentRenderTarget.texture.colorSpace; + } + return ColorManagement2.workingColorSpace; + } + var UniformsUtils2 = { clone: cloneUniforms2, merge: mergeUniforms2 }; + var default_vertex2 = `void main() { + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); +}`; + var default_fragment2 = `void main() { + gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); +}`; + + class ShaderMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isShaderMaterial = true; + this.type = "ShaderMaterial"; + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + this.vertexShader = default_vertex2; + this.fragmentShader = default_fragment2; + this.linewidth = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.fog = false; + this.lights = false; + this.clipping = false; + this.forceSinglePass = true; + this.extensions = { + clipCullDistance: false, + multiDraw: false + }; + this.defaultAttributeValues = { + color: [1, 1, 1], + uv: [0, 0], + uv1: [0, 0] + }; + this.index0AttributeName = undefined; + this.uniformsNeedUpdate = false; + this.glslVersion = null; + if (parameters !== undefined) { + this.setValues(parameters); + } + } + copy(source) { + super.copy(source); + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + this.uniforms = cloneUniforms2(source.uniforms); + this.uniformsGroups = cloneUniformsGroups2(source.uniformsGroups); + this.defines = Object.assign({}, source.defines); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + this.extensions = Object.assign({}, source.extensions); + this.glslVersion = source.glslVersion; + return this; + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + data2.glslVersion = this.glslVersion; + data2.uniforms = {}; + for (const name2 in this.uniforms) { + const uniform = this.uniforms[name2]; + const value2 = uniform.value; + if (value2 && value2.isTexture) { + data2.uniforms[name2] = { + type: "t", + value: value2.toJSON(meta2).uuid + }; + } else if (value2 && value2.isColor) { + data2.uniforms[name2] = { + type: "c", + value: value2.getHex() + }; + } else if (value2 && value2.isVector2) { + data2.uniforms[name2] = { + type: "v2", + value: value2.toArray() + }; + } else if (value2 && value2.isVector3) { + data2.uniforms[name2] = { + type: "v3", + value: value2.toArray() + }; + } else if (value2 && value2.isVector4) { + data2.uniforms[name2] = { + type: "v4", + value: value2.toArray() + }; + } else if (value2 && value2.isMatrix3) { + data2.uniforms[name2] = { + type: "m3", + value: value2.toArray() + }; + } else if (value2 && value2.isMatrix4) { + data2.uniforms[name2] = { + type: "m4", + value: value2.toArray() + }; + } else { + data2.uniforms[name2] = { + value: value2 + }; + } + } + if (Object.keys(this.defines).length > 0) + data2.defines = this.defines; + data2.vertexShader = this.vertexShader; + data2.fragmentShader = this.fragmentShader; + data2.lights = this.lights; + data2.clipping = this.clipping; + const extensions = {}; + for (const key2 in this.extensions) { + if (this.extensions[key2] === true) + extensions[key2] = true; + } + if (Object.keys(extensions).length > 0) + data2.extensions = extensions; + return data2; + } + } + + class Camera2 extends Object3D2 { + constructor() { + super(); + this.isCamera = true; + this.type = "Camera"; + this.matrixWorldInverse = new Matrix42; + this.projectionMatrix = new Matrix42; + this.projectionMatrixInverse = new Matrix42; + this.coordinateSystem = WebGLCoordinateSystem2; + } + copy(source, recursive) { + super.copy(source, recursive); + this.matrixWorldInverse.copy(source.matrixWorldInverse); + this.projectionMatrix.copy(source.projectionMatrix); + this.projectionMatrixInverse.copy(source.projectionMatrixInverse); + this.coordinateSystem = source.coordinateSystem; + return this; + } + getWorldDirection(target) { + return super.getWorldDirection(target).negate(); + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + updateWorldMatrix(updateParents, updateChildren) { + super.updateWorldMatrix(updateParents, updateChildren); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + clone() { + return new this.constructor().copy(this); + } + } + var _v3$12 = /* @__PURE__ */ new Vector32; + var _minTarget2 = /* @__PURE__ */ new Vector22; + var _maxTarget2 = /* @__PURE__ */ new Vector22; + + class PerspectiveCamera2 extends Camera2 { + constructor(fov3 = 50, aspect3 = 1, near = 0.1, far = 2000) { + super(); + this.isPerspectiveCamera = true; + this.type = "PerspectiveCamera"; + this.fov = fov3; + this.zoom = 1; + this.near = near; + this.far = far; + this.focus = 10; + this.aspect = aspect3; + this.view = null; + this.filmGauge = 35; + this.filmOffset = 0; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.fov = source.fov; + this.zoom = source.zoom; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign({}, source.view); + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + return this; + } + setFocalLength(focalLength) { + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + this.fov = RAD2DEG2 * 2 * Math.atan(vExtentSlope); + this.updateProjectionMatrix(); + } + getFocalLength() { + const vExtentSlope = Math.tan(DEG2RAD2 * 0.5 * this.fov); + return 0.5 * this.getFilmHeight() / vExtentSlope; + } + getEffectiveFOV() { + return RAD2DEG2 * 2 * Math.atan(Math.tan(DEG2RAD2 * 0.5 * this.fov) / this.zoom); + } + getFilmWidth() { + return this.filmGauge * Math.min(this.aspect, 1); + } + getFilmHeight() { + return this.filmGauge / Math.max(this.aspect, 1); + } + getViewBounds(distance, minTarget, maxTarget) { + _v3$12.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse); + minTarget.set(_v3$12.x, _v3$12.y).multiplyScalar(-distance / _v3$12.z); + _v3$12.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse); + maxTarget.set(_v3$12.x, _v3$12.y).multiplyScalar(-distance / _v3$12.z); + } + getViewSize(distance, target) { + this.getViewBounds(distance, _minTarget2, _maxTarget2); + return target.subVectors(_maxTarget2, _minTarget2); + } + setViewOffset(fullWidth, fullHeight, x2, y3, width2, height2) { + this.aspect = fullWidth / fullHeight; + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x2; + this.view.offsetY = y3; + this.view.width = width2; + this.view.height = height2; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const near = this.near; + let top = near * Math.tan(DEG2RAD2 * 0.5 * this.fov) / this.zoom; + let height2 = 2 * top; + let width2 = this.aspect * height2; + let left = -0.5 * width2; + const view = this.view; + if (this.view !== null && this.view.enabled) { + const { fullWidth, fullHeight } = view; + left += view.offsetX * width2 / fullWidth; + top -= view.offsetY * height2 / fullHeight; + width2 *= view.width / fullWidth; + height2 *= view.height / fullHeight; + } + const skew = this.filmOffset; + if (skew !== 0) + left += near * skew / this.getFilmWidth(); + this.projectionMatrix.makePerspective(left, left + width2, top, top - height2, near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + data2.object.fov = this.fov; + data2.object.zoom = this.zoom; + data2.object.near = this.near; + data2.object.far = this.far; + data2.object.focus = this.focus; + data2.object.aspect = this.aspect; + if (this.view !== null) + data2.object.view = Object.assign({}, this.view); + data2.object.filmGauge = this.filmGauge; + data2.object.filmOffset = this.filmOffset; + return data2; + } + } + var fov2 = -90; + var aspect2 = 1; + + class CubeCamera2 extends Object3D2 { + constructor(near, far, renderTarget) { + super(); + this.type = "CubeCamera"; + this.renderTarget = renderTarget; + this.coordinateSystem = null; + this.activeMipmapLevel = 0; + const cameraPX = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraPX.layers = this.layers; + this.add(cameraPX); + const cameraNX = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraNX.layers = this.layers; + this.add(cameraNX); + const cameraPY = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraPY.layers = this.layers; + this.add(cameraPY); + const cameraNY = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraNY.layers = this.layers; + this.add(cameraNY); + const cameraPZ = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraPZ.layers = this.layers; + this.add(cameraPZ); + const cameraNZ = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraNZ.layers = this.layers; + this.add(cameraNZ); + } + updateCoordinateSystem() { + const coordinateSystem = this.coordinateSystem; + const cameras = this.children.concat(); + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = cameras; + for (const camera of cameras) + this.remove(camera); + if (coordinateSystem === WebGLCoordinateSystem2) { + cameraPX.up.set(0, 1, 0); + cameraPX.lookAt(1, 0, 0); + cameraNX.up.set(0, 1, 0); + cameraNX.lookAt(-1, 0, 0); + cameraPY.up.set(0, 0, -1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, 1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, 1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, 1, 0); + cameraNZ.lookAt(0, 0, -1); + } else if (coordinateSystem === WebGPUCoordinateSystem2) { + cameraPX.up.set(0, -1, 0); + cameraPX.lookAt(-1, 0, 0); + cameraNX.up.set(0, -1, 0); + cameraNX.lookAt(1, 0, 0); + cameraPY.up.set(0, 0, 1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, -1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, -1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, -1, 0); + cameraNZ.lookAt(0, 0, -1); + } else { + throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + coordinateSystem); + } + for (const camera of cameras) { + this.add(camera); + camera.updateMatrixWorld(); + } + } + update(renderer2, scene) { + if (this.parent === null) + this.updateMatrixWorld(); + const { renderTarget, activeMipmapLevel } = this; + if (this.coordinateSystem !== renderer2.coordinateSystem) { + this.coordinateSystem = renderer2.coordinateSystem; + this.updateCoordinateSystem(); + } + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children; + const currentRenderTarget = renderer2.getRenderTarget(); + const currentActiveCubeFace = renderer2.getActiveCubeFace(); + const currentActiveMipmapLevel = renderer2.getActiveMipmapLevel(); + const currentXrEnabled = renderer2.xr.enabled; + renderer2.xr.enabled = false; + const generateMipmaps = renderTarget.texture.generateMipmaps; + renderTarget.texture.generateMipmaps = false; + renderer2.setRenderTarget(renderTarget, 0, activeMipmapLevel); + renderer2.render(scene, cameraPX); + renderer2.setRenderTarget(renderTarget, 1, activeMipmapLevel); + renderer2.render(scene, cameraNX); + renderer2.setRenderTarget(renderTarget, 2, activeMipmapLevel); + renderer2.render(scene, cameraPY); + renderer2.setRenderTarget(renderTarget, 3, activeMipmapLevel); + renderer2.render(scene, cameraNY); + renderer2.setRenderTarget(renderTarget, 4, activeMipmapLevel); + renderer2.render(scene, cameraPZ); + renderTarget.texture.generateMipmaps = generateMipmaps; + renderer2.setRenderTarget(renderTarget, 5, activeMipmapLevel); + renderer2.render(scene, cameraNZ); + renderer2.setRenderTarget(currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel); + renderer2.xr.enabled = currentXrEnabled; + renderTarget.texture.needsPMREMUpdate = true; + } + } + + class CubeTexture2 extends Texture2 { + constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace) { + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping2; + super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCubeTexture = true; + this.flipY = false; + } + get images() { + return this.image; + } + set images(value2) { + this.image = value2; + } + } + + class WebGLCubeRenderTarget2 extends WebGLRenderTarget2 { + constructor(size2 = 1, options = {}) { + super(size2, size2, options); + this.isWebGLCubeRenderTarget = true; + const image = { width: size2, height: size2, depth: 1 }; + const images = [image, image, image, image, image, image]; + this.texture = new CubeTexture2(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + this.texture.isRenderTargetTexture = true; + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter2; + } + fromEquirectangularTexture(renderer2, texture) { + this.texture.type = texture.type; + this.texture.colorSpace = texture.colorSpace; + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + const shader = { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `, + fragmentShader: ` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + }; + const geometry = new BoxGeometry2(5, 5, 5); + const material = new ShaderMaterial2({ + name: "CubemapFromEquirect", + uniforms: cloneUniforms2(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide2, + blending: NoBlending2 + }); + material.uniforms.tEquirect.value = texture; + const mesh = new Mesh2(geometry, material); + const currentMinFilter = texture.minFilter; + if (texture.minFilter === LinearMipmapLinearFilter2) + texture.minFilter = LinearFilter2; + const camera = new CubeCamera2(1, 10, this); + camera.update(renderer2, mesh); + texture.minFilter = currentMinFilter; + mesh.geometry.dispose(); + mesh.material.dispose(); + return this; + } + clear(renderer2, color, depth, stencil) { + const currentRenderTarget = renderer2.getRenderTarget(); + for (let i = 0;i < 6; i++) { + renderer2.setRenderTarget(this, i); + renderer2.clear(color, depth, stencil); + } + renderer2.setRenderTarget(currentRenderTarget); + } + } + + class Group2 extends Object3D2 { + constructor() { + super(); + this.isGroup = true; + this.type = "Group"; + } + } + var _moveEvent2 = { type: "move" }; + + class WebXRController2 { + constructor() { + this._targetRay = null; + this._grip = null; + this._hand = null; + } + getHandSpace() { + if (this._hand === null) { + this._hand = new Group2; + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + } + return this._hand; + } + getTargetRaySpace() { + if (this._targetRay === null) { + this._targetRay = new Group2; + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector32; + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector32; + } + return this._targetRay; + } + getGripSpace() { + if (this._grip === null) { + this._grip = new Group2; + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector32; + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector32; + } + return this._grip; + } + dispatchEvent(event) { + if (this._targetRay !== null) { + this._targetRay.dispatchEvent(event); + } + if (this._grip !== null) { + this._grip.dispatchEvent(event); + } + if (this._hand !== null) { + this._hand.dispatchEvent(event); + } + return this; + } + connect(inputSource) { + if (inputSource && inputSource.hand) { + const hand = this._hand; + if (hand) { + for (const inputjoint of inputSource.hand.values()) { + this._getHandJoint(hand, inputjoint); + } + } + } + this.dispatchEvent({ type: "connected", data: inputSource }); + return this; + } + disconnect(inputSource) { + this.dispatchEvent({ type: "disconnected", data: inputSource }); + if (this._targetRay !== null) { + this._targetRay.visible = false; + } + if (this._grip !== null) { + this._grip.visible = false; + } + if (this._hand !== null) { + this._hand.visible = false; + } + return this; + } + update(inputSource, frame, referenceSpace) { + let inputPose = null; + let gripPose = null; + let handPose = null; + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + if (inputSource && frame.session.visibilityState !== "visible-blurred") { + if (hand && inputSource.hand) { + handPose = true; + for (const inputjoint of inputSource.hand.values()) { + const jointPose = frame.getJointPose(inputjoint, referenceSpace); + const joint = this._getHandJoint(hand, inputjoint); + if (jointPose !== null) { + joint.matrix.fromArray(jointPose.transform.matrix); + joint.matrix.decompose(joint.position, joint.rotation, joint.scale); + joint.matrixWorldNeedsUpdate = true; + joint.jointRadius = jointPose.radius; + } + joint.visible = jointPose !== null; + } + const indexTip = hand.joints["index-finger-tip"]; + const thumbTip = hand.joints["thumb-tip"]; + const distance = indexTip.position.distanceTo(thumbTip.position); + const distanceToPinch = 0.02; + const threshold = 0.005; + if (hand.inputState.pinching && distance > distanceToPinch + threshold) { + hand.inputState.pinching = false; + this.dispatchEvent({ + type: "pinchend", + handedness: inputSource.handedness, + target: this + }); + } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) { + hand.inputState.pinching = true; + this.dispatchEvent({ + type: "pinchstart", + handedness: inputSource.handedness, + target: this + }); + } + } else { + if (grip !== null && inputSource.gripSpace) { + gripPose = frame.getPose(inputSource.gripSpace, referenceSpace); + if (gripPose !== null) { + grip.matrix.fromArray(gripPose.transform.matrix); + grip.matrix.decompose(grip.position, grip.rotation, grip.scale); + grip.matrixWorldNeedsUpdate = true; + if (gripPose.linearVelocity) { + grip.hasLinearVelocity = true; + grip.linearVelocity.copy(gripPose.linearVelocity); + } else { + grip.hasLinearVelocity = false; + } + if (gripPose.angularVelocity) { + grip.hasAngularVelocity = true; + grip.angularVelocity.copy(gripPose.angularVelocity); + } else { + grip.hasAngularVelocity = false; + } + } + } + } + if (targetRay !== null) { + inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); + if (inputPose === null && gripPose !== null) { + inputPose = gripPose; + } + if (inputPose !== null) { + targetRay.matrix.fromArray(inputPose.transform.matrix); + targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale); + targetRay.matrixWorldNeedsUpdate = true; + if (inputPose.linearVelocity) { + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy(inputPose.linearVelocity); + } else { + targetRay.hasLinearVelocity = false; + } + if (inputPose.angularVelocity) { + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy(inputPose.angularVelocity); + } else { + targetRay.hasAngularVelocity = false; + } + this.dispatchEvent(_moveEvent2); + } + } + } + if (targetRay !== null) { + targetRay.visible = inputPose !== null; + } + if (grip !== null) { + grip.visible = gripPose !== null; + } + if (hand !== null) { + hand.visible = handPose !== null; + } + return this; + } + _getHandJoint(hand, inputjoint) { + if (hand.joints[inputjoint.jointName] === undefined) { + const joint = new Group2; + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[inputjoint.jointName] = joint; + hand.add(joint); + } + return hand.joints[inputjoint.jointName]; + } + } + + class FogExp22 { + constructor(color, density = 0.00025) { + this.isFogExp2 = true; + this.name = ""; + this.color = new Color2(color); + this.density = density; + } + clone() { + return new FogExp22(this.color, this.density); + } + toJSON() { + return { + type: "FogExp2", + name: this.name, + color: this.color.getHex(), + density: this.density + }; + } + } + + class Fog2 { + constructor(color, near = 1, far = 1000) { + this.isFog = true; + this.name = ""; + this.color = new Color2(color); + this.near = near; + this.far = far; + } + clone() { + return new Fog2(this.color, this.near, this.far); + } + toJSON() { + return { + type: "Fog", + name: this.name, + color: this.color.getHex(), + near: this.near, + far: this.far + }; + } + } + + class Scene2 extends Object3D2 { + constructor() { + super(); + this.isScene = true; + this.type = "Scene"; + this.background = null; + this.environment = null; + this.fog = null; + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + this.backgroundRotation = new Euler2; + this.environmentIntensity = 1; + this.environmentRotation = new Euler2; + this.overrideMaterial = null; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.background !== null) + this.background = source.background.clone(); + if (source.environment !== null) + this.environment = source.environment.clone(); + if (source.fog !== null) + this.fog = source.fog.clone(); + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + this.backgroundRotation.copy(source.backgroundRotation); + this.environmentIntensity = source.environmentIntensity; + this.environmentRotation.copy(source.environmentRotation); + if (source.overrideMaterial !== null) + this.overrideMaterial = source.overrideMaterial.clone(); + this.matrixAutoUpdate = source.matrixAutoUpdate; + return this; + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + if (this.fog !== null) + data2.object.fog = this.fog.toJSON(); + if (this.backgroundBlurriness > 0) + data2.object.backgroundBlurriness = this.backgroundBlurriness; + if (this.backgroundIntensity !== 1) + data2.object.backgroundIntensity = this.backgroundIntensity; + data2.object.backgroundRotation = this.backgroundRotation.toArray(); + if (this.environmentIntensity !== 1) + data2.object.environmentIntensity = this.environmentIntensity; + data2.object.environmentRotation = this.environmentRotation.toArray(); + return data2; + } + } + + class InterleavedBuffer2 { + constructor(array, stride) { + this.isInterleavedBuffer = true; + this.array = array; + this.stride = stride; + this.count = array !== undefined ? array.length / stride : 0; + this.usage = StaticDrawUsage2; + this.updateRanges = []; + this.version = 0; + this.uuid = generateUUID2(); + } + onUploadCallback() { + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setUsage(value2) { + this.usage = value2; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.array = new source.array.constructor(source.array); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.stride; + index2 *= attribute.stride; + for (let i = 0, l2 = this.stride;i < l2; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + set(value2, offset = 0) { + this.array.set(value2, offset); + return this; + } + clone(data2) { + if (data2.arrayBuffers === undefined) { + data2.arrayBuffers = {}; + } + if (this.array.buffer._uuid === undefined) { + this.array.buffer._uuid = generateUUID2(); + } + if (data2.arrayBuffers[this.array.buffer._uuid] === undefined) { + data2.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer; + } + const array = new this.array.constructor(data2.arrayBuffers[this.array.buffer._uuid]); + const ib = new this.constructor(array, this.stride); + ib.setUsage(this.usage); + return ib; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + toJSON(data2) { + if (data2.arrayBuffers === undefined) { + data2.arrayBuffers = {}; + } + if (this.array.buffer._uuid === undefined) { + this.array.buffer._uuid = generateUUID2(); + } + if (data2.arrayBuffers[this.array.buffer._uuid] === undefined) { + data2.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer)); + } + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; + } + } + var _vector$72 = /* @__PURE__ */ new Vector32; + + class InterleavedBufferAttribute2 { + constructor(interleavedBuffer, itemSize, offset, normalized = false) { + this.isInterleavedBufferAttribute = true; + this.name = ""; + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; + this.normalized = normalized; + } + get count() { + return this.data.count; + } + get array() { + return this.data.array; + } + set needsUpdate(value2) { + this.data.needsUpdate = value2; + } + applyMatrix4(m) { + for (let i = 0, l2 = this.data.count;i < l2; i++) { + _vector$72.fromBufferAttribute(this, i); + _vector$72.applyMatrix4(m); + this.setXYZ(i, _vector$72.x, _vector$72.y, _vector$72.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector$72.fromBufferAttribute(this, i); + _vector$72.applyNormalMatrix(m); + this.setXYZ(i, _vector$72.x, _vector$72.y, _vector$72.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector$72.fromBufferAttribute(this, i); + _vector$72.transformDirection(m); + this.setXYZ(i, _vector$72.x, _vector$72.y, _vector$72.z); + } + return this; + } + getComponent(index2, component) { + let value2 = this.array[index2 * this.data.stride + this.offset + component]; + if (this.normalized) + value2 = denormalize2(value2, this.array); + return value2; + } + setComponent(index2, component, value2) { + if (this.normalized) + value2 = normalize3(value2, this.array); + this.data.array[index2 * this.data.stride + this.offset + component] = value2; + return this; + } + setX(index2, x2) { + if (this.normalized) + x2 = normalize3(x2, this.array); + this.data.array[index2 * this.data.stride + this.offset] = x2; + return this; + } + setY(index2, y3) { + if (this.normalized) + y3 = normalize3(y3, this.array); + this.data.array[index2 * this.data.stride + this.offset + 1] = y3; + return this; + } + setZ(index2, z2) { + if (this.normalized) + z2 = normalize3(z2, this.array); + this.data.array[index2 * this.data.stride + this.offset + 2] = z2; + return this; + } + setW(index2, w) { + if (this.normalized) + w = normalize3(w, this.array); + this.data.array[index2 * this.data.stride + this.offset + 3] = w; + return this; + } + getX(index2) { + let x2 = this.data.array[index2 * this.data.stride + this.offset]; + if (this.normalized) + x2 = denormalize2(x2, this.array); + return x2; + } + getY(index2) { + let y3 = this.data.array[index2 * this.data.stride + this.offset + 1]; + if (this.normalized) + y3 = denormalize2(y3, this.array); + return y3; + } + getZ(index2) { + let z2 = this.data.array[index2 * this.data.stride + this.offset + 2]; + if (this.normalized) + z2 = denormalize2(z2, this.array); + return z2; + } + getW(index2) { + let w = this.data.array[index2 * this.data.stride + this.offset + 3]; + if (this.normalized) + w = denormalize2(w, this.array); + return w; + } + setXY(index2, x2, y3) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y3 = normalize3(y3, this.array); + } + this.data.array[index2 + 0] = x2; + this.data.array[index2 + 1] = y3; + return this; + } + setXYZ(index2, x2, y3, z2) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y3 = normalize3(y3, this.array); + z2 = normalize3(z2, this.array); + } + this.data.array[index2 + 0] = x2; + this.data.array[index2 + 1] = y3; + this.data.array[index2 + 2] = z2; + return this; + } + setXYZW(index2, x2, y3, z2, w) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y3 = normalize3(y3, this.array); + z2 = normalize3(z2, this.array); + w = normalize3(w, this.array); + } + this.data.array[index2 + 0] = x2; + this.data.array[index2 + 1] = y3; + this.data.array[index2 + 2] = z2; + this.data.array[index2 + 3] = w; + return this; + } + clone(data2) { + if (data2 === undefined) { + console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0;i < this.count; i++) { + const index2 = i * this.data.stride + this.offset; + for (let j2 = 0;j2 < this.itemSize; j2++) { + array.push(this.data.array[index2 + j2]); + } + } + return new BufferAttribute2(new this.array.constructor(array), this.itemSize, this.normalized); + } else { + if (data2.interleavedBuffers === undefined) { + data2.interleavedBuffers = {}; + } + if (data2.interleavedBuffers[this.data.uuid] === undefined) { + data2.interleavedBuffers[this.data.uuid] = this.data.clone(data2); + } + return new InterleavedBufferAttribute2(data2.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized); + } + } + toJSON(data2) { + if (data2 === undefined) { + console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0;i < this.count; i++) { + const index2 = i * this.data.stride + this.offset; + for (let j2 = 0;j2 < this.itemSize; j2++) { + array.push(this.data.array[index2 + j2]); + } + } + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array, + normalized: this.normalized + }; + } else { + if (data2.interleavedBuffers === undefined) { + data2.interleavedBuffers = {}; + } + if (data2.interleavedBuffers[this.data.uuid] === undefined) { + data2.interleavedBuffers[this.data.uuid] = this.data.toJSON(data2); + } + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + } + } + } + + class SpriteMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isSpriteMaterial = true; + this.type = "SpriteMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.alphaMap = null; + this.rotation = 0; + this.sizeAttenuation = true; + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.rotation = source.rotation; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } + } + var _geometry3; + var _intersectPoint2 = /* @__PURE__ */ new Vector32; + var _worldScale2 = /* @__PURE__ */ new Vector32; + var _mvPosition2 = /* @__PURE__ */ new Vector32; + var _alignedPosition2 = /* @__PURE__ */ new Vector22; + var _rotatedPosition2 = /* @__PURE__ */ new Vector22; + var _viewWorldMatrix2 = /* @__PURE__ */ new Matrix42; + var _vA3 = /* @__PURE__ */ new Vector32; + var _vB3 = /* @__PURE__ */ new Vector32; + var _vC3 = /* @__PURE__ */ new Vector32; + var _uvA2 = /* @__PURE__ */ new Vector22; + var _uvB2 = /* @__PURE__ */ new Vector22; + var _uvC2 = /* @__PURE__ */ new Vector22; + + class Sprite2 extends Object3D2 { + constructor(material = new SpriteMaterial2) { + super(); + this.isSprite = true; + this.type = "Sprite"; + if (_geometry3 === undefined) { + _geometry3 = new BufferGeometry2; + const float32Array = new Float32Array([ + -0.5, + -0.5, + 0, + 0, + 0, + 0.5, + -0.5, + 0, + 1, + 0, + 0.5, + 0.5, + 0, + 1, + 1, + -0.5, + 0.5, + 0, + 0, + 1 + ]); + const interleavedBuffer = new InterleavedBuffer2(float32Array, 5); + _geometry3.setIndex([0, 1, 2, 0, 2, 3]); + _geometry3.setAttribute("position", new InterleavedBufferAttribute2(interleavedBuffer, 3, 0, false)); + _geometry3.setAttribute("uv", new InterleavedBufferAttribute2(interleavedBuffer, 2, 3, false)); + } + this.geometry = _geometry3; + this.material = material; + this.center = new Vector22(0.5, 0.5); + } + raycast(raycaster, intersects3) { + if (raycaster.camera === null) { + console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'); + } + _worldScale2.setFromMatrixScale(this.matrixWorld); + _viewWorldMatrix2.copy(raycaster.camera.matrixWorld); + this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld); + _mvPosition2.setFromMatrixPosition(this.modelViewMatrix); + if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) { + _worldScale2.multiplyScalar(-_mvPosition2.z); + } + const rotation2 = this.material.rotation; + let sin, cos; + if (rotation2 !== 0) { + cos = Math.cos(rotation2); + sin = Math.sin(rotation2); + } + const center = this.center; + transformVertex2(_vA3.set(-0.5, -0.5, 0), _mvPosition2, center, _worldScale2, sin, cos); + transformVertex2(_vB3.set(0.5, -0.5, 0), _mvPosition2, center, _worldScale2, sin, cos); + transformVertex2(_vC3.set(0.5, 0.5, 0), _mvPosition2, center, _worldScale2, sin, cos); + _uvA2.set(0, 0); + _uvB2.set(1, 0); + _uvC2.set(1, 1); + let intersect3 = raycaster.ray.intersectTriangle(_vA3, _vB3, _vC3, false, _intersectPoint2); + if (intersect3 === null) { + transformVertex2(_vB3.set(-0.5, 0.5, 0), _mvPosition2, center, _worldScale2, sin, cos); + _uvB2.set(0, 1); + intersect3 = raycaster.ray.intersectTriangle(_vA3, _vC3, _vB3, false, _intersectPoint2); + if (intersect3 === null) { + return; + } + } + const distance = raycaster.ray.origin.distanceTo(_intersectPoint2); + if (distance < raycaster.near || distance > raycaster.far) + return; + intersects3.push({ + distance, + point: _intersectPoint2.clone(), + uv: Triangle2.getInterpolation(_intersectPoint2, _vA3, _vB3, _vC3, _uvA2, _uvB2, _uvC2, new Vector22), + face: null, + object: this + }); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.center !== undefined) + this.center.copy(source.center); + this.material = source.material; + return this; + } + } + function transformVertex2(vertexPosition, mvPosition, center, scale2, sin, cos) { + _alignedPosition2.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale2); + if (sin !== undefined) { + _rotatedPosition2.x = cos * _alignedPosition2.x - sin * _alignedPosition2.y; + _rotatedPosition2.y = sin * _alignedPosition2.x + cos * _alignedPosition2.y; + } else { + _rotatedPosition2.copy(_alignedPosition2); + } + vertexPosition.copy(mvPosition); + vertexPosition.x += _rotatedPosition2.x; + vertexPosition.y += _rotatedPosition2.y; + vertexPosition.applyMatrix4(_viewWorldMatrix2); + } + var _v1$22 = /* @__PURE__ */ new Vector32; + var _v2$12 = /* @__PURE__ */ new Vector32; + + class LOD2 extends Object3D2 { + constructor() { + super(); + this._currentLevel = 0; + this.type = "LOD"; + Object.defineProperties(this, { + levels: { + enumerable: true, + value: [] + }, + isLOD: { + value: true + } + }); + this.autoUpdate = true; + } + copy(source) { + super.copy(source, false); + const levels = source.levels; + for (let i = 0, l2 = levels.length;i < l2; i++) { + const level = levels[i]; + this.addLevel(level.object.clone(), level.distance, level.hysteresis); + } + this.autoUpdate = source.autoUpdate; + return this; + } + addLevel(object, distance = 0, hysteresis = 0) { + distance = Math.abs(distance); + const levels = this.levels; + let l2; + for (l2 = 0;l2 < levels.length; l2++) { + if (distance < levels[l2].distance) { + break; + } + } + levels.splice(l2, 0, { distance, hysteresis, object }); + this.add(object); + return this; + } + removeLevel(distance) { + const levels = this.levels; + for (let i = 0;i < levels.length; i++) { + if (levels[i].distance === distance) { + const removedElements = levels.splice(i, 1); + this.remove(removedElements[0].object); + return true; + } + } + return false; + } + getCurrentLevel() { + return this._currentLevel; + } + getObjectForDistance(distance) { + const levels = this.levels; + if (levels.length > 0) { + let i, l2; + for (i = 1, l2 = levels.length;i < l2; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance < levelDistance) { + break; + } + } + return levels[i - 1].object; + } + return null; + } + raycast(raycaster, intersects3) { + const levels = this.levels; + if (levels.length > 0) { + _v1$22.setFromMatrixPosition(this.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_v1$22); + this.getObjectForDistance(distance).raycast(raycaster, intersects3); + } + } + update(camera) { + const levels = this.levels; + if (levels.length > 1) { + _v1$22.setFromMatrixPosition(camera.matrixWorld); + _v2$12.setFromMatrixPosition(this.matrixWorld); + const distance = _v1$22.distanceTo(_v2$12) / camera.zoom; + levels[0].object.visible = true; + let i, l2; + for (i = 1, l2 = levels.length;i < l2; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance >= levelDistance) { + levels[i - 1].object.visible = false; + levels[i].object.visible = true; + } else { + break; + } + } + this._currentLevel = i - 1; + for (;i < l2; i++) { + levels[i].object.visible = false; + } + } + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + if (this.autoUpdate === false) + data2.object.autoUpdate = false; + data2.object.levels = []; + const levels = this.levels; + for (let i = 0, l2 = levels.length;i < l2; i++) { + const level = levels[i]; + data2.object.levels.push({ + object: level.object.uuid, + distance: level.distance, + hysteresis: level.hysteresis + }); + } + return data2; + } + } + var _basePosition2 = /* @__PURE__ */ new Vector32; + var _skinIndex2 = /* @__PURE__ */ new Vector42; + var _skinWeight2 = /* @__PURE__ */ new Vector42; + var _vector32 = /* @__PURE__ */ new Vector32; + var _matrix42 = /* @__PURE__ */ new Matrix42; + var _vertex2 = /* @__PURE__ */ new Vector32; + var _sphere$52 = /* @__PURE__ */ new Sphere2; + var _inverseMatrix$22 = /* @__PURE__ */ new Matrix42; + var _ray$22 = /* @__PURE__ */ new Ray2; + + class SkinnedMesh2 extends Mesh2 { + constructor(geometry, material) { + super(geometry, material); + this.isSkinnedMesh = true; + this.type = "SkinnedMesh"; + this.bindMode = AttachedBindMode2; + this.bindMatrix = new Matrix42; + this.bindMatrixInverse = new Matrix42; + this.boundingBox = null; + this.boundingSphere = null; + } + computeBoundingBox() { + const geometry = this.geometry; + if (this.boundingBox === null) { + this.boundingBox = new Box32; + } + this.boundingBox.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0;i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex2); + this.boundingBox.expandByPoint(_vertex2); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere2; + } + this.boundingSphere.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0;i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex2); + this.boundingSphere.expandByPoint(_vertex2); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.bindMode = source.bindMode; + this.bindMatrix.copy(source.bindMatrix); + this.bindMatrixInverse.copy(source.bindMatrixInverse); + this.skeleton = source.skeleton; + if (source.boundingBox !== null) + this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) + this.boundingSphere = source.boundingSphere.clone(); + return this; + } + raycast(raycaster, intersects3) { + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === undefined) + return; + if (this.boundingSphere === null) + this.computeBoundingSphere(); + _sphere$52.copy(this.boundingSphere); + _sphere$52.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$52) === false) + return; + _inverseMatrix$22.copy(matrixWorld).invert(); + _ray$22.copy(raycaster.ray).applyMatrix4(_inverseMatrix$22); + if (this.boundingBox !== null) { + if (_ray$22.intersectsBox(this.boundingBox) === false) + return; + } + this._computeIntersections(raycaster, intersects3, _ray$22); + } + getVertexPosition(index2, target) { + super.getVertexPosition(index2, target); + this.applyBoneTransform(index2, target); + return target; + } + bind(skeleton, bindMatrix) { + this.skeleton = skeleton; + if (bindMatrix === undefined) { + this.updateMatrixWorld(true); + this.skeleton.calculateInverses(); + bindMatrix = this.matrixWorld; + } + this.bindMatrix.copy(bindMatrix); + this.bindMatrixInverse.copy(bindMatrix).invert(); + } + pose() { + this.skeleton.pose(); + } + normalizeSkinWeights() { + const vector = new Vector42; + const skinWeight = this.geometry.attributes.skinWeight; + for (let i = 0, l2 = skinWeight.count;i < l2; i++) { + vector.fromBufferAttribute(skinWeight, i); + const scale2 = 1 / vector.manhattanLength(); + if (scale2 !== Infinity) { + vector.multiplyScalar(scale2); + } else { + vector.set(1, 0, 0, 0); + } + skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w); + } + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.bindMode === AttachedBindMode2) { + this.bindMatrixInverse.copy(this.matrixWorld).invert(); + } else if (this.bindMode === DetachedBindMode2) { + this.bindMatrixInverse.copy(this.bindMatrix).invert(); + } else { + console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode); + } + } + applyBoneTransform(index2, vector) { + const skeleton = this.skeleton; + const geometry = this.geometry; + _skinIndex2.fromBufferAttribute(geometry.attributes.skinIndex, index2); + _skinWeight2.fromBufferAttribute(geometry.attributes.skinWeight, index2); + _basePosition2.copy(vector).applyMatrix4(this.bindMatrix); + vector.set(0, 0, 0); + for (let i = 0;i < 4; i++) { + const weight = _skinWeight2.getComponent(i); + if (weight !== 0) { + const boneIndex = _skinIndex2.getComponent(i); + _matrix42.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]); + vector.addScaledVector(_vector32.copy(_basePosition2).applyMatrix4(_matrix42), weight); + } + } + return vector.applyMatrix4(this.bindMatrixInverse); + } + } + + class Bone2 extends Object3D2 { + constructor() { + super(); + this.isBone = true; + this.type = "Bone"; + } + } + + class DataTexture2 extends Texture2 { + constructor(data2 = null, width2 = 1, height2 = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter2, minFilter = NearestFilter2, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isDataTexture = true; + this.image = { data: data2, width: width2, height: height2 }; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } + } + var _offsetMatrix2 = /* @__PURE__ */ new Matrix42; + var _identityMatrix3 = /* @__PURE__ */ new Matrix42; + + class Skeleton2 { + constructor(bones = [], boneInverses = []) { + this.uuid = generateUUID2(); + this.bones = bones.slice(0); + this.boneInverses = boneInverses; + this.boneMatrices = null; + this.boneTexture = null; + this.init(); + } + init() { + const bones = this.bones; + const boneInverses = this.boneInverses; + this.boneMatrices = new Float32Array(bones.length * 16); + if (boneInverses.length === 0) { + this.calculateInverses(); + } else { + if (bones.length !== boneInverses.length) { + console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."); + this.boneInverses = []; + for (let i = 0, il = this.bones.length;i < il; i++) { + this.boneInverses.push(new Matrix42); + } + } + } + } + calculateInverses() { + this.boneInverses.length = 0; + for (let i = 0, il = this.bones.length;i < il; i++) { + const inverse2 = new Matrix42; + if (this.bones[i]) { + inverse2.copy(this.bones[i].matrixWorld).invert(); + } + this.boneInverses.push(inverse2); + } + } + pose() { + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone) { + bone.matrixWorld.copy(this.boneInverses[i]).invert(); + } + } + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone) { + if (bone.parent && bone.parent.isBone) { + bone.matrix.copy(bone.parent.matrixWorld).invert(); + bone.matrix.multiply(bone.matrixWorld); + } else { + bone.matrix.copy(bone.matrixWorld); + } + bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); + } + } + } + update() { + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; + for (let i = 0, il = bones.length;i < il; i++) { + const matrix3 = bones[i] ? bones[i].matrixWorld : _identityMatrix3; + _offsetMatrix2.multiplyMatrices(matrix3, boneInverses[i]); + _offsetMatrix2.toArray(boneMatrices, i * 16); + } + if (boneTexture !== null) { + boneTexture.needsUpdate = true; + } + } + clone() { + return new Skeleton2(this.bones, this.boneInverses); + } + computeBoneTexture() { + let size2 = Math.sqrt(this.bones.length * 4); + size2 = Math.ceil(size2 / 4) * 4; + size2 = Math.max(size2, 4); + const boneMatrices = new Float32Array(size2 * size2 * 4); + boneMatrices.set(this.boneMatrices); + const boneTexture = new DataTexture2(boneMatrices, size2, size2, RGBAFormat2, FloatType2); + boneTexture.needsUpdate = true; + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + return this; + } + getBoneByName(name2) { + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone.name === name2) { + return bone; + } + } + return; + } + dispose() { + if (this.boneTexture !== null) { + this.boneTexture.dispose(); + this.boneTexture = null; + } + } + fromJSON(json, bones) { + this.uuid = json.uuid; + for (let i = 0, l2 = json.bones.length;i < l2; i++) { + const uuid = json.bones[i]; + let bone = bones[uuid]; + if (bone === undefined) { + console.warn("THREE.Skeleton: No bone found with UUID:", uuid); + bone = new Bone2; + } + this.bones.push(bone); + this.boneInverses.push(new Matrix42().fromArray(json.boneInverses[i])); + } + this.init(); + return this; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "Skeleton", + generator: "Skeleton.toJSON" + }, + bones: [], + boneInverses: [] + }; + data2.uuid = this.uuid; + const bones = this.bones; + const boneInverses = this.boneInverses; + for (let i = 0, l2 = bones.length;i < l2; i++) { + const bone = bones[i]; + data2.bones.push(bone.uuid); + const boneInverse = boneInverses[i]; + data2.boneInverses.push(boneInverse.toArray()); + } + return data2; + } + } + + class InstancedBufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized, meshPerAttribute = 1) { + super(array, itemSize, normalized); + this.isInstancedBufferAttribute = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.meshPerAttribute = this.meshPerAttribute; + data2.isInstancedBufferAttribute = true; + return data2; + } + } + var _instanceLocalMatrix2 = /* @__PURE__ */ new Matrix42; + var _instanceWorldMatrix2 = /* @__PURE__ */ new Matrix42; + var _instanceIntersects2 = []; + var _box32 = /* @__PURE__ */ new Box32; + var _identity2 = /* @__PURE__ */ new Matrix42; + var _mesh$12 = /* @__PURE__ */ new Mesh2; + var _sphere$42 = /* @__PURE__ */ new Sphere2; + + class InstancedMesh2 extends Mesh2 { + constructor(geometry, material, count) { + super(geometry, material); + this.isInstancedMesh = true; + this.instanceMatrix = new InstancedBufferAttribute2(new Float32Array(count * 16), 16); + this.instanceColor = null; + this.morphTexture = null; + this.count = count; + this.boundingBox = null; + this.boundingSphere = null; + for (let i = 0;i < count; i++) { + this.setMatrixAt(i, _identity2); + } + } + computeBoundingBox() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingBox === null) { + this.boundingBox = new Box32; + } + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + this.boundingBox.makeEmpty(); + for (let i = 0;i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix2); + _box32.copy(geometry.boundingBox).applyMatrix4(_instanceLocalMatrix2); + this.boundingBox.union(_box32); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere2; + } + if (geometry.boundingSphere === null) { + geometry.computeBoundingSphere(); + } + this.boundingSphere.makeEmpty(); + for (let i = 0;i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix2); + _sphere$42.copy(geometry.boundingSphere).applyMatrix4(_instanceLocalMatrix2); + this.boundingSphere.union(_sphere$42); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.instanceMatrix.copy(source.instanceMatrix); + if (source.morphTexture !== null) + this.morphTexture = source.morphTexture.clone(); + if (source.instanceColor !== null) + this.instanceColor = source.instanceColor.clone(); + this.count = source.count; + if (source.boundingBox !== null) + this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) + this.boundingSphere = source.boundingSphere.clone(); + return this; + } + getColorAt(index2, color) { + color.fromArray(this.instanceColor.array, index2 * 3); + } + getMatrixAt(index2, matrix3) { + matrix3.fromArray(this.instanceMatrix.array, index2 * 16); + } + getMorphAt(index2, object) { + const objectInfluences = object.morphTargetInfluences; + const array = this.morphTexture.source.data.data; + const len = objectInfluences.length + 1; + const dataIndex = index2 * len + 1; + for (let i = 0;i < objectInfluences.length; i++) { + objectInfluences[i] = array[dataIndex + i]; + } + } + raycast(raycaster, intersects3) { + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + _mesh$12.geometry = this.geometry; + _mesh$12.material = this.material; + if (_mesh$12.material === undefined) + return; + if (this.boundingSphere === null) + this.computeBoundingSphere(); + _sphere$42.copy(this.boundingSphere); + _sphere$42.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$42) === false) + return; + for (let instanceId = 0;instanceId < raycastTimes; instanceId++) { + this.getMatrixAt(instanceId, _instanceLocalMatrix2); + _instanceWorldMatrix2.multiplyMatrices(matrixWorld, _instanceLocalMatrix2); + _mesh$12.matrixWorld = _instanceWorldMatrix2; + _mesh$12.raycast(raycaster, _instanceIntersects2); + for (let i = 0, l2 = _instanceIntersects2.length;i < l2; i++) { + const intersect3 = _instanceIntersects2[i]; + intersect3.instanceId = instanceId; + intersect3.object = this; + intersects3.push(intersect3); + } + _instanceIntersects2.length = 0; + } + } + setColorAt(index2, color) { + if (this.instanceColor === null) { + this.instanceColor = new InstancedBufferAttribute2(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3); + } + color.toArray(this.instanceColor.array, index2 * 3); + } + setMatrixAt(index2, matrix3) { + matrix3.toArray(this.instanceMatrix.array, index2 * 16); + } + setMorphAt(index2, object) { + const objectInfluences = object.morphTargetInfluences; + const len = objectInfluences.length + 1; + if (this.morphTexture === null) { + this.morphTexture = new DataTexture2(new Float32Array(len * this.count), len, this.count, RedFormat2, FloatType2); + } + const array = this.morphTexture.source.data.data; + let morphInfluencesSum = 0; + for (let i = 0;i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + const dataIndex = len * index2; + array[dataIndex] = morphBaseInfluence; + array.set(objectInfluences, dataIndex + 1); + } + updateMorphTargets() { + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + if (this.morphTexture !== null) { + this.morphTexture.dispose(); + this.morphTexture = null; + } + return this; + } + } + var _vector12 = /* @__PURE__ */ new Vector32; + var _vector22 = /* @__PURE__ */ new Vector32; + var _normalMatrix3 = /* @__PURE__ */ new Matrix32; + + class Plane2 { + constructor(normal = new Vector32(1, 0, 0), constant2 = 0) { + this.isPlane = true; + this.normal = normal; + this.constant = constant2; + } + set(normal, constant2) { + this.normal.copy(normal); + this.constant = constant2; + return this; + } + setComponents(x2, y3, z2, w) { + this.normal.set(x2, y3, z2); + this.constant = w; + return this; + } + setFromNormalAndCoplanarPoint(normal, point) { + this.normal.copy(normal); + this.constant = -point.dot(this.normal); + return this; + } + setFromCoplanarPoints(a2, b3, c2) { + const normal = _vector12.subVectors(c2, b3).cross(_vector22.subVectors(a2, b3)).normalize(); + this.setFromNormalAndCoplanarPoint(normal, a2); + return this; + } + copy(plane) { + this.normal.copy(plane.normal); + this.constant = plane.constant; + return this; + } + normalize() { + const inverseNormalLength = 1 / this.normal.length(); + this.normal.multiplyScalar(inverseNormalLength); + this.constant *= inverseNormalLength; + return this; + } + negate() { + this.constant *= -1; + this.normal.negate(); + return this; + } + distanceToPoint(point) { + return this.normal.dot(point) + this.constant; + } + distanceToSphere(sphere) { + return this.distanceToPoint(sphere.center) - sphere.radius; + } + projectPoint(point, target) { + return target.copy(point).addScaledVector(this.normal, -this.distanceToPoint(point)); + } + intersectLine(line2, target) { + const direction = line2.delta(_vector12); + const denominator = this.normal.dot(direction); + if (denominator === 0) { + if (this.distanceToPoint(line2.start) === 0) { + return target.copy(line2.start); + } + return null; + } + const t4 = -(line2.start.dot(this.normal) + this.constant) / denominator; + if (t4 < 0 || t4 > 1) { + return null; + } + return target.copy(line2.start).addScaledVector(direction, t4); + } + intersectsLine(line2) { + const startSign = this.distanceToPoint(line2.start); + const endSign = this.distanceToPoint(line2.end); + return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0; + } + intersectsBox(box) { + return box.intersectsPlane(this); + } + intersectsSphere(sphere) { + return sphere.intersectsPlane(this); + } + coplanarPoint(target) { + return target.copy(this.normal).multiplyScalar(-this.constant); + } + applyMatrix4(matrix3, optionalNormalMatrix) { + const normalMatrix = optionalNormalMatrix || _normalMatrix3.getNormalMatrix(matrix3); + const referencePoint = this.coplanarPoint(_vector12).applyMatrix4(matrix3); + const normal = this.normal.applyMatrix3(normalMatrix).normalize(); + this.constant = -referencePoint.dot(normal); + return this; + } + translate(offset) { + this.constant -= offset.dot(this.normal); + return this; + } + equals(plane) { + return plane.normal.equals(this.normal) && plane.constant === this.constant; + } + clone() { + return new this.constructor().copy(this); + } + } + var _sphere$32 = /* @__PURE__ */ new Sphere2; + var _vector$62 = /* @__PURE__ */ new Vector32; + + class Frustum2 { + constructor(p0 = new Plane2, p1 = new Plane2, p2 = new Plane2, p32 = new Plane2, p4 = new Plane2, p5 = new Plane2) { + this.planes = [p0, p1, p2, p32, p4, p5]; + } + set(p0, p1, p2, p32, p4, p5) { + const planes = this.planes; + planes[0].copy(p0); + planes[1].copy(p1); + planes[2].copy(p2); + planes[3].copy(p32); + planes[4].copy(p4); + planes[5].copy(p5); + return this; + } + copy(frustum) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + planes[i].copy(frustum.planes[i]); + } + return this; + } + setFromProjectionMatrix(m, coordinateSystem = WebGLCoordinateSystem2) { + const planes = this.planes; + const me = m.elements; + const me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3]; + const me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7]; + const me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11]; + const me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15]; + planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize(); + planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize(); + planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize(); + planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize(); + planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); + if (coordinateSystem === WebGLCoordinateSystem2) { + planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize(); + } else if (coordinateSystem === WebGPUCoordinateSystem2) { + planes[5].setComponents(me2, me6, me10, me14).normalize(); + } else { + throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + coordinateSystem); + } + return this; + } + intersectsObject(object) { + if (object.boundingSphere !== undefined) { + if (object.boundingSphere === null) + object.computeBoundingSphere(); + _sphere$32.copy(object.boundingSphere).applyMatrix4(object.matrixWorld); + } else { + const geometry = object.geometry; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$32.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld); + } + return this.intersectsSphere(_sphere$32); + } + intersectsSprite(sprite) { + _sphere$32.center.set(0, 0, 0); + _sphere$32.radius = 0.7071067811865476; + _sphere$32.applyMatrix4(sprite.matrixWorld); + return this.intersectsSphere(_sphere$32); + } + intersectsSphere(sphere) { + const planes = this.planes; + const center = sphere.center; + const negRadius = -sphere.radius; + for (let i = 0;i < 6; i++) { + const distance = planes[i].distanceToPoint(center); + if (distance < negRadius) { + return false; + } + } + return true; + } + intersectsBox(box) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + const plane = planes[i]; + _vector$62.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$62.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$62.z = plane.normal.z > 0 ? box.max.z : box.min.z; + if (plane.distanceToPoint(_vector$62) < 0) { + return false; + } + } + return true; + } + containsPoint(point) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + if (planes[i].distanceToPoint(point) < 0) { + return false; + } + } + return true; + } + clone() { + return new this.constructor().copy(this); + } + } + function ascIdSort2(a2, b3) { + return a2 - b3; + } + function sortOpaque2(a2, b3) { + return a2.z - b3.z; + } + function sortTransparent2(a2, b3) { + return b3.z - a2.z; + } + + class MultiDrawRenderList2 { + constructor() { + this.index = 0; + this.pool = []; + this.list = []; + } + push(start, count, z2, index2) { + const pool = this.pool; + const list = this.list; + if (this.index >= pool.length) { + pool.push({ + start: -1, + count: -1, + z: -1, + index: -1 + }); + } + const item = pool[this.index]; + list.push(item); + this.index++; + item.start = start; + item.count = count; + item.z = z2; + item.index = index2; + } + reset() { + this.list.length = 0; + this.index = 0; + } + } + var _matrix$12 = /* @__PURE__ */ new Matrix42; + var _whiteColor2 = /* @__PURE__ */ new Color2(1, 1, 1); + var _frustum3 = /* @__PURE__ */ new Frustum2; + var _box$12 = /* @__PURE__ */ new Box32; + var _sphere$22 = /* @__PURE__ */ new Sphere2; + var _vector$52 = /* @__PURE__ */ new Vector32; + var _forward2 = /* @__PURE__ */ new Vector32; + var _temp4 = /* @__PURE__ */ new Vector32; + var _renderList2 = /* @__PURE__ */ new MultiDrawRenderList2; + var _mesh2 = /* @__PURE__ */ new Mesh2; + var _batchIntersects2 = []; + function copyAttributeData2(src, target, targetOffset = 0) { + const itemSize = target.itemSize; + if (src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor) { + const vertexCount = src.count; + for (let i = 0;i < vertexCount; i++) { + for (let c2 = 0;c2 < itemSize; c2++) { + target.setComponent(i + targetOffset, c2, src.getComponent(i, c2)); + } + } + } else { + target.array.set(src.array, targetOffset * itemSize); + } + target.needsUpdate = true; + } + function copyArrayContents2(src, target) { + if (src.constructor !== target.constructor) { + const len = Math.min(src.length, target.length); + for (let i = 0;i < len; i++) { + target[i] = src[i]; + } + } else { + const len = Math.min(src.length, target.length); + target.set(new src.constructor(src.buffer, 0, len)); + } + } + + class BatchedMesh2 extends Mesh2 { + get maxInstanceCount() { + return this._maxInstanceCount; + } + get instanceCount() { + return this._instanceInfo.length - this._availableInstanceIds.length; + } + get unusedVertexCount() { + return this._maxVertexCount - this._nextVertexStart; + } + get unusedIndexCount() { + return this._maxIndexCount - this._nextIndexStart; + } + constructor(maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material) { + super(new BufferGeometry2, material); + this.isBatchedMesh = true; + this.perObjectFrustumCulled = true; + this.sortObjects = true; + this.boundingBox = null; + this.boundingSphere = null; + this.customSort = null; + this._instanceInfo = []; + this._geometryInfo = []; + this._availableInstanceIds = []; + this._availableGeometryIds = []; + this._nextIndexStart = 0; + this._nextVertexStart = 0; + this._geometryCount = 0; + this._visibilityChanged = true; + this._geometryInitialized = false; + this._maxInstanceCount = maxInstanceCount; + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + this._multiDrawCounts = new Int32Array(maxInstanceCount); + this._multiDrawStarts = new Int32Array(maxInstanceCount); + this._multiDrawCount = 0; + this._multiDrawInstances = null; + this._matricesTexture = null; + this._indirectTexture = null; + this._colorsTexture = null; + this._initMatricesTexture(); + this._initIndirectTexture(); + } + _initMatricesTexture() { + let size2 = Math.sqrt(this._maxInstanceCount * 4); + size2 = Math.ceil(size2 / 4) * 4; + size2 = Math.max(size2, 4); + const matricesArray = new Float32Array(size2 * size2 * 4); + const matricesTexture = new DataTexture2(matricesArray, size2, size2, RGBAFormat2, FloatType2); + this._matricesTexture = matricesTexture; + } + _initIndirectTexture() { + let size2 = Math.sqrt(this._maxInstanceCount); + size2 = Math.ceil(size2); + const indirectArray = new Uint32Array(size2 * size2); + const indirectTexture = new DataTexture2(indirectArray, size2, size2, RedIntegerFormat2, UnsignedIntType2); + this._indirectTexture = indirectTexture; + } + _initColorsTexture() { + let size2 = Math.sqrt(this._maxInstanceCount); + size2 = Math.ceil(size2); + const colorsArray = new Float32Array(size2 * size2 * 4).fill(1); + const colorsTexture = new DataTexture2(colorsArray, size2, size2, RGBAFormat2, FloatType2); + colorsTexture.colorSpace = ColorManagement2.workingColorSpace; + this._colorsTexture = colorsTexture; + } + _initializeGeometry(reference) { + const geometry = this.geometry; + const maxVertexCount = this._maxVertexCount; + const maxIndexCount = this._maxIndexCount; + if (this._geometryInitialized === false) { + for (const attributeName in reference.attributes) { + const srcAttribute = reference.getAttribute(attributeName); + const { array, itemSize, normalized } = srcAttribute; + const dstArray = new array.constructor(maxVertexCount * itemSize); + const dstAttribute = new BufferAttribute2(dstArray, itemSize, normalized); + geometry.setAttribute(attributeName, dstAttribute); + } + if (reference.getIndex() !== null) { + const indexArray = maxVertexCount > 65535 ? new Uint32Array(maxIndexCount) : new Uint16Array(maxIndexCount); + geometry.setIndex(new BufferAttribute2(indexArray, 1)); + } + this._geometryInitialized = true; + } + } + _validateGeometry(geometry) { + const batchGeometry = this.geometry; + if (Boolean(geometry.getIndex()) !== Boolean(batchGeometry.getIndex())) { + throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".'); + } + for (const attributeName in batchGeometry.attributes) { + if (!geometry.hasAttribute(attributeName)) { + throw new Error(`THREE.BatchedMesh: Added geometry missing "${attributeName}". All geometries must have consistent attributes.`); + } + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + if (srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized) { + throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value."); + } + } + } + validateInstanceId(instanceId) { + const instanceInfo = this._instanceInfo; + if (instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[instanceId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.`); + } + } + validateGeometryId(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.`); + } + } + setCustomSort(func) { + this.customSort = func; + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box32; + } + const boundingBox = this.boundingBox; + const instanceInfo = this._instanceInfo; + boundingBox.makeEmpty(); + for (let i = 0, l2 = instanceInfo.length;i < l2; i++) { + if (instanceInfo[i].active === false) + continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$12); + this.getBoundingBoxAt(geometryId, _box$12).applyMatrix4(_matrix$12); + boundingBox.union(_box$12); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere2; + } + const boundingSphere = this.boundingSphere; + const instanceInfo = this._instanceInfo; + boundingSphere.makeEmpty(); + for (let i = 0, l2 = instanceInfo.length;i < l2; i++) { + if (instanceInfo[i].active === false) + continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$12); + this.getBoundingSphereAt(geometryId, _sphere$22).applyMatrix4(_matrix$12); + boundingSphere.union(_sphere$22); + } + } + addInstance(geometryId) { + const atCapacity = this._instanceInfo.length >= this.maxInstanceCount; + if (atCapacity && this._availableInstanceIds.length === 0) { + throw new Error("THREE.BatchedMesh: Maximum item count reached."); + } + const instanceInfo = { + visible: true, + active: true, + geometryIndex: geometryId + }; + let drawId = null; + if (this._availableInstanceIds.length > 0) { + this._availableInstanceIds.sort(ascIdSort2); + drawId = this._availableInstanceIds.shift(); + this._instanceInfo[drawId] = instanceInfo; + } else { + drawId = this._instanceInfo.length; + this._instanceInfo.push(instanceInfo); + } + const matricesTexture = this._matricesTexture; + _matrix$12.identity().toArray(matricesTexture.image.data, drawId * 16); + matricesTexture.needsUpdate = true; + const colorsTexture = this._colorsTexture; + if (colorsTexture) { + _whiteColor2.toArray(colorsTexture.image.data, drawId * 4); + colorsTexture.needsUpdate = true; + } + this._visibilityChanged = true; + return drawId; + } + addGeometry(geometry, reservedVertexCount = -1, reservedIndexCount = -1) { + this._initializeGeometry(geometry); + this._validateGeometry(geometry); + const geometryInfo = { + vertexStart: -1, + vertexCount: -1, + reservedVertexCount: -1, + indexStart: -1, + indexCount: -1, + reservedIndexCount: -1, + start: -1, + count: -1, + boundingBox: null, + boundingSphere: null, + active: true + }; + const geometryInfoList = this._geometryInfo; + geometryInfo.vertexStart = this._nextVertexStart; + geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute("position").count : reservedVertexCount; + const index2 = geometry.getIndex(); + const hasIndex = index2 !== null; + if (hasIndex) { + geometryInfo.indexStart = this._nextIndexStart; + geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index2.count : reservedIndexCount; + } + if (geometryInfo.indexStart !== -1 && geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount || geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size."); + } + let geometryId; + if (this._availableGeometryIds.length > 0) { + this._availableGeometryIds.sort(ascIdSort2); + geometryId = this._availableGeometryIds.shift(); + geometryInfoList[geometryId] = geometryInfo; + } else { + geometryId = this._geometryCount; + this._geometryCount++; + geometryInfoList.push(geometryInfo); + } + this.setGeometryAt(geometryId, geometry); + this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + return geometryId; + } + setGeometryAt(geometryId, geometry) { + if (geometryId >= this._geometryCount) { + throw new Error("THREE.BatchedMesh: Maximum geometry count reached."); + } + this._validateGeometry(geometry); + const batchGeometry = this.geometry; + const hasIndex = batchGeometry.getIndex() !== null; + const dstIndex = batchGeometry.getIndex(); + const srcIndex = geometry.getIndex(); + const geometryInfo = this._geometryInfo[geometryId]; + if (hasIndex && srcIndex.count > geometryInfo.reservedIndexCount || geometry.attributes.position.count > geometryInfo.reservedVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry."); + } + const vertexStart = geometryInfo.vertexStart; + const reservedVertexCount = geometryInfo.reservedVertexCount; + geometryInfo.vertexCount = geometry.getAttribute("position").count; + for (const attributeName in batchGeometry.attributes) { + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + copyAttributeData2(srcAttribute, dstAttribute, vertexStart); + const itemSize = srcAttribute.itemSize; + for (let i = srcAttribute.count, l2 = reservedVertexCount;i < l2; i++) { + const index2 = vertexStart + i; + for (let c2 = 0;c2 < itemSize; c2++) { + dstAttribute.setComponent(index2, c2, 0); + } + } + dstAttribute.needsUpdate = true; + dstAttribute.addUpdateRange(vertexStart * itemSize, reservedVertexCount * itemSize); + } + if (hasIndex) { + const indexStart = geometryInfo.indexStart; + const reservedIndexCount = geometryInfo.reservedIndexCount; + geometryInfo.indexCount = geometry.getIndex().count; + for (let i = 0;i < srcIndex.count; i++) { + dstIndex.setX(indexStart + i, vertexStart + srcIndex.getX(i)); + } + for (let i = srcIndex.count, l2 = reservedIndexCount;i < l2; i++) { + dstIndex.setX(indexStart + i, vertexStart); + } + dstIndex.needsUpdate = true; + dstIndex.addUpdateRange(indexStart, geometryInfo.reservedIndexCount); + } + geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart; + geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount; + geometryInfo.boundingBox = null; + if (geometry.boundingBox !== null) { + geometryInfo.boundingBox = geometry.boundingBox.clone(); + } + geometryInfo.boundingSphere = null; + if (geometry.boundingSphere !== null) { + geometryInfo.boundingSphere = geometry.boundingSphere.clone(); + } + this._visibilityChanged = true; + return geometryId; + } + deleteGeometry(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + return this; + } + const instanceInfo = this._instanceInfo; + for (let i = 0, l2 = instanceInfo.length;i < l2; i++) { + if (instanceInfo[i].active && instanceInfo[i].geometryIndex === geometryId) { + this.deleteInstance(i); + } + } + geometryInfoList[geometryId].active = false; + this._availableGeometryIds.push(geometryId); + this._visibilityChanged = true; + return this; + } + deleteInstance(instanceId) { + this.validateInstanceId(instanceId); + this._instanceInfo[instanceId].active = false; + this._availableInstanceIds.push(instanceId); + this._visibilityChanged = true; + return this; + } + optimize() { + let nextVertexStart = 0; + let nextIndexStart = 0; + const geometryInfoList = this._geometryInfo; + const indices = geometryInfoList.map((e, i) => i).sort((a2, b3) => { + return geometryInfoList[a2].vertexStart - geometryInfoList[b3].vertexStart; + }); + const geometry = this.geometry; + for (let i = 0, l2 = geometryInfoList.length;i < l2; i++) { + const index2 = indices[i]; + const geometryInfo = geometryInfoList[index2]; + if (geometryInfo.active === false) { + continue; + } + if (geometry.index !== null) { + if (geometryInfo.indexStart !== nextIndexStart) { + const { indexStart, vertexStart, reservedIndexCount } = geometryInfo; + const index3 = geometry.index; + const array = index3.array; + const elementDelta = nextVertexStart - vertexStart; + for (let j2 = indexStart;j2 < indexStart + reservedIndexCount; j2++) { + array[j2] = array[j2] + elementDelta; + } + index3.array.copyWithin(nextIndexStart, indexStart, indexStart + reservedIndexCount); + index3.addUpdateRange(nextIndexStart, reservedIndexCount); + geometryInfo.indexStart = nextIndexStart; + } + nextIndexStart += geometryInfo.reservedIndexCount; + } + if (geometryInfo.vertexStart !== nextVertexStart) { + const { vertexStart, reservedVertexCount } = geometryInfo; + const attributes = geometry.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + const { array, itemSize } = attribute; + array.copyWithin(nextVertexStart * itemSize, vertexStart * itemSize, (vertexStart + reservedVertexCount) * itemSize); + attribute.addUpdateRange(nextVertexStart * itemSize, reservedVertexCount * itemSize); + } + geometryInfo.vertexStart = nextVertexStart; + } + nextVertexStart += geometryInfo.reservedVertexCount; + geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart; + this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + } + return this; + } + getBoundingBoxAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingBox === null) { + const box = new Box32; + const index2 = geometry.index; + const position2 = geometry.attributes.position; + for (let i = geometryInfo.start, l2 = geometryInfo.start + geometryInfo.count;i < l2; i++) { + let iv = i; + if (index2) { + iv = index2.getX(iv); + } + box.expandByPoint(_vector$52.fromBufferAttribute(position2, iv)); + } + geometryInfo.boundingBox = box; + } + target.copy(geometryInfo.boundingBox); + return target; + } + getBoundingSphereAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingSphere === null) { + const sphere = new Sphere2; + this.getBoundingBoxAt(geometryId, _box$12); + _box$12.getCenter(sphere.center); + const index2 = geometry.index; + const position2 = geometry.attributes.position; + let maxRadiusSq = 0; + for (let i = geometryInfo.start, l2 = geometryInfo.start + geometryInfo.count;i < l2; i++) { + let iv = i; + if (index2) { + iv = index2.getX(iv); + } + _vector$52.fromBufferAttribute(position2, iv); + maxRadiusSq = Math.max(maxRadiusSq, sphere.center.distanceToSquared(_vector$52)); + } + sphere.radius = Math.sqrt(maxRadiusSq); + geometryInfo.boundingSphere = sphere; + } + target.copy(geometryInfo.boundingSphere); + return target; + } + setMatrixAt(instanceId, matrix3) { + this.validateInstanceId(instanceId); + const matricesTexture = this._matricesTexture; + const matricesArray = this._matricesTexture.image.data; + matrix3.toArray(matricesArray, instanceId * 16); + matricesTexture.needsUpdate = true; + return this; + } + getMatrixAt(instanceId, matrix3) { + this.validateInstanceId(instanceId); + return matrix3.fromArray(this._matricesTexture.image.data, instanceId * 16); + } + setColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + if (this._colorsTexture === null) { + this._initColorsTexture(); + } + color.toArray(this._colorsTexture.image.data, instanceId * 4); + this._colorsTexture.needsUpdate = true; + return this; + } + getColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + return color.fromArray(this._colorsTexture.image.data, instanceId * 4); + } + setVisibleAt(instanceId, value2) { + this.validateInstanceId(instanceId); + if (this._instanceInfo[instanceId].visible === value2) { + return this; + } + this._instanceInfo[instanceId].visible = value2; + this._visibilityChanged = true; + return this; + } + getVisibleAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].visible; + } + setGeometryIdAt(instanceId, geometryId) { + this.validateInstanceId(instanceId); + this.validateGeometryId(geometryId); + this._instanceInfo[instanceId].geometryIndex = geometryId; + return this; + } + getGeometryIdAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].geometryIndex; + } + getGeometryRangeAt(geometryId, target = {}) { + this.validateGeometryId(geometryId); + const geometryInfo = this._geometryInfo[geometryId]; + target.vertexStart = geometryInfo.vertexStart; + target.vertexCount = geometryInfo.vertexCount; + target.reservedVertexCount = geometryInfo.reservedVertexCount; + target.indexStart = geometryInfo.indexStart; + target.indexCount = geometryInfo.indexCount; + target.reservedIndexCount = geometryInfo.reservedIndexCount; + target.start = geometryInfo.start; + target.count = geometryInfo.count; + return target; + } + setInstanceCount(maxInstanceCount) { + const availableInstanceIds = this._availableInstanceIds; + const instanceInfo = this._instanceInfo; + availableInstanceIds.sort(ascIdSort2); + while (availableInstanceIds[availableInstanceIds.length - 1] === instanceInfo.length) { + instanceInfo.pop(); + availableInstanceIds.pop(); + } + if (maxInstanceCount < instanceInfo.length) { + throw new Error(`BatchedMesh: Instance ids outside the range ${maxInstanceCount} are being used. Cannot shrink instance count.`); + } + const multiDrawCounts = new Int32Array(maxInstanceCount); + const multiDrawStarts = new Int32Array(maxInstanceCount); + copyArrayContents2(this._multiDrawCounts, multiDrawCounts); + copyArrayContents2(this._multiDrawStarts, multiDrawStarts); + this._multiDrawCounts = multiDrawCounts; + this._multiDrawStarts = multiDrawStarts; + this._maxInstanceCount = maxInstanceCount; + const indirectTexture = this._indirectTexture; + const matricesTexture = this._matricesTexture; + const colorsTexture = this._colorsTexture; + indirectTexture.dispose(); + this._initIndirectTexture(); + copyArrayContents2(indirectTexture.image.data, this._indirectTexture.image.data); + matricesTexture.dispose(); + this._initMatricesTexture(); + copyArrayContents2(matricesTexture.image.data, this._matricesTexture.image.data); + if (colorsTexture) { + colorsTexture.dispose(); + this._initColorsTexture(); + copyArrayContents2(colorsTexture.image.data, this._colorsTexture.image.data); + } + } + setGeometrySize(maxVertexCount, maxIndexCount) { + const validRanges = [...this._geometryInfo].filter((info) => info.active); + const requiredVertexLength = Math.max(...validRanges.map((range) => range.vertexStart + range.reservedVertexCount)); + if (requiredVertexLength > maxVertexCount) { + throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + if (this.geometry.index) { + const requiredIndexLength = Math.max(...validRanges.map((range) => range.indexStart + range.reservedIndexCount)); + if (requiredIndexLength > maxIndexCount) { + throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + } + const oldGeometry = this.geometry; + oldGeometry.dispose(); + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + if (this._geometryInitialized) { + this._geometryInitialized = false; + this.geometry = new BufferGeometry2; + this._initializeGeometry(oldGeometry); + } + const geometry = this.geometry; + if (oldGeometry.index) { + copyArrayContents2(oldGeometry.index.array, geometry.index.array); + } + for (const key2 in oldGeometry.attributes) { + copyArrayContents2(oldGeometry.attributes[key2].array, geometry.attributes[key2].array); + } + } + raycast(raycaster, intersects3) { + const instanceInfo = this._instanceInfo; + const geometryInfoList = this._geometryInfo; + const matrixWorld = this.matrixWorld; + const batchGeometry = this.geometry; + _mesh2.material = this.material; + _mesh2.geometry.index = batchGeometry.index; + _mesh2.geometry.attributes = batchGeometry.attributes; + if (_mesh2.geometry.boundingBox === null) { + _mesh2.geometry.boundingBox = new Box32; + } + if (_mesh2.geometry.boundingSphere === null) { + _mesh2.geometry.boundingSphere = new Sphere2; + } + for (let i = 0, l2 = instanceInfo.length;i < l2; i++) { + if (!instanceInfo[i].visible || !instanceInfo[i].active) { + continue; + } + const geometryId = instanceInfo[i].geometryIndex; + const geometryInfo = geometryInfoList[geometryId]; + _mesh2.geometry.setDrawRange(geometryInfo.start, geometryInfo.count); + this.getMatrixAt(i, _mesh2.matrixWorld).premultiply(matrixWorld); + this.getBoundingBoxAt(geometryId, _mesh2.geometry.boundingBox); + this.getBoundingSphereAt(geometryId, _mesh2.geometry.boundingSphere); + _mesh2.raycast(raycaster, _batchIntersects2); + for (let j2 = 0, l3 = _batchIntersects2.length;j2 < l3; j2++) { + const intersect3 = _batchIntersects2[j2]; + intersect3.object = this; + intersect3.batchId = i; + intersects3.push(intersect3); + } + _batchIntersects2.length = 0; + } + _mesh2.material = null; + _mesh2.geometry.index = null; + _mesh2.geometry.attributes = {}; + _mesh2.geometry.setDrawRange(0, Infinity); + } + copy(source) { + super.copy(source); + this.geometry = source.geometry.clone(); + this.perObjectFrustumCulled = source.perObjectFrustumCulled; + this.sortObjects = source.sortObjects; + this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null; + this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null; + this._geometryInfo = source._geometryInfo.map((info) => ({ + ...info, + boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null, + boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null + })); + this._instanceInfo = source._instanceInfo.map((info) => ({ ...info })); + this._maxInstanceCount = source._maxInstanceCount; + this._maxVertexCount = source._maxVertexCount; + this._maxIndexCount = source._maxIndexCount; + this._geometryInitialized = source._geometryInitialized; + this._geometryCount = source._geometryCount; + this._multiDrawCounts = source._multiDrawCounts.slice(); + this._multiDrawStarts = source._multiDrawStarts.slice(); + this._matricesTexture = source._matricesTexture.clone(); + this._matricesTexture.image.data = this._matricesTexture.image.data.slice(); + if (this._colorsTexture !== null) { + this._colorsTexture = source._colorsTexture.clone(); + this._colorsTexture.image.data = this._colorsTexture.image.data.slice(); + } + return this; + } + dispose() { + this.geometry.dispose(); + this._matricesTexture.dispose(); + this._matricesTexture = null; + this._indirectTexture.dispose(); + this._indirectTexture = null; + if (this._colorsTexture !== null) { + this._colorsTexture.dispose(); + this._colorsTexture = null; + } + return this; + } + onBeforeRender(renderer2, scene, camera, geometry, material) { + if (!this._visibilityChanged && !this.perObjectFrustumCulled && !this.sortObjects) { + return; + } + const index2 = geometry.getIndex(); + const bytesPerElement = index2 === null ? 1 : index2.array.BYTES_PER_ELEMENT; + const instanceInfo = this._instanceInfo; + const multiDrawStarts = this._multiDrawStarts; + const multiDrawCounts = this._multiDrawCounts; + const geometryInfoList = this._geometryInfo; + const perObjectFrustumCulled = this.perObjectFrustumCulled; + const indirectTexture = this._indirectTexture; + const indirectArray = indirectTexture.image.data; + if (perObjectFrustumCulled) { + _matrix$12.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).multiply(this.matrixWorld); + _frustum3.setFromProjectionMatrix(_matrix$12, renderer2.coordinateSystem); + } + let multiDrawCount = 0; + if (this.sortObjects) { + _matrix$12.copy(this.matrixWorld).invert(); + _vector$52.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(_matrix$12); + _forward2.set(0, 0, -1).transformDirection(camera.matrixWorld).transformDirection(_matrix$12); + for (let i = 0, l2 = instanceInfo.length;i < l2; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$12); + this.getBoundingSphereAt(geometryId, _sphere$22).applyMatrix4(_matrix$12); + let culled = false; + if (perObjectFrustumCulled) { + culled = !_frustum3.intersectsSphere(_sphere$22); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + const z2 = _temp4.subVectors(_sphere$22.center, _vector$52).dot(_forward2); + _renderList2.push(geometryInfo.start, geometryInfo.count, z2, i); + } + } + } + const list = _renderList2.list; + const customSort = this.customSort; + if (customSort === null) { + list.sort(material.transparent ? sortTransparent2 : sortOpaque2); + } else { + customSort.call(this, list, camera); + } + for (let i = 0, l2 = list.length;i < l2; i++) { + const item = list[i]; + multiDrawStarts[multiDrawCount] = item.start * bytesPerElement; + multiDrawCounts[multiDrawCount] = item.count; + indirectArray[multiDrawCount] = item.index; + multiDrawCount++; + } + _renderList2.reset(); + } else { + for (let i = 0, l2 = instanceInfo.length;i < l2; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + let culled = false; + if (perObjectFrustumCulled) { + this.getMatrixAt(i, _matrix$12); + this.getBoundingSphereAt(geometryId, _sphere$22).applyMatrix4(_matrix$12); + culled = !_frustum3.intersectsSphere(_sphere$22); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + multiDrawStarts[multiDrawCount] = geometryInfo.start * bytesPerElement; + multiDrawCounts[multiDrawCount] = geometryInfo.count; + indirectArray[multiDrawCount] = i; + multiDrawCount++; + } + } + } + } + indirectTexture.needsUpdate = true; + this._multiDrawCount = multiDrawCount; + this._visibilityChanged = false; + } + onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial) { + this.onBeforeRender(renderer2, null, shadowCamera, geometry, depthMaterial); + } + } + + class LineBasicMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isLineBasicMaterial = true; + this.type = "LineBasicMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.linewidth = 1; + this.linecap = "round"; + this.linejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + this.fog = source.fog; + return this; + } + } + var _vStart2 = /* @__PURE__ */ new Vector32; + var _vEnd2 = /* @__PURE__ */ new Vector32; + var _inverseMatrix$12 = /* @__PURE__ */ new Matrix42; + var _ray$12 = /* @__PURE__ */ new Ray2; + var _sphere$12 = /* @__PURE__ */ new Sphere2; + var _intersectPointOnRay2 = /* @__PURE__ */ new Vector32; + var _intersectPointOnSegment2 = /* @__PURE__ */ new Vector32; + + class Line4 extends Object3D2 { + constructor(geometry = new BufferGeometry2, material = new LineBasicMaterial2) { + super(); + this.isLine = true; + this.type = "Line"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = [0]; + for (let i = 1, l2 = positionAttribute.count;i < l2; i++) { + _vStart2.fromBufferAttribute(positionAttribute, i - 1); + _vEnd2.fromBufferAttribute(positionAttribute, i); + lineDistances[i] = lineDistances[i - 1]; + lineDistances[i] += _vStart2.distanceTo(_vEnd2); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute2(lineDistances, 1)); + } else { + console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + raycast(raycaster, intersects3) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$12.copy(geometry.boundingSphere); + _sphere$12.applyMatrix4(matrixWorld); + _sphere$12.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere$12) === false) + return; + _inverseMatrix$12.copy(matrixWorld).invert(); + _ray$12.copy(raycaster.ray).applyMatrix4(_inverseMatrix$12); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const step = this.isLineSegments ? 2 : 1; + const index2 = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index2 !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, l2 = end - 1;i < l2; i += step) { + const a2 = index2.getX(i); + const b3 = index2.getX(i + 1); + const intersect3 = checkIntersection2(this, raycaster, _ray$12, localThresholdSq, a2, b3, i); + if (intersect3) { + intersects3.push(intersect3); + } + } + if (this.isLineLoop) { + const a2 = index2.getX(end - 1); + const b3 = index2.getX(start); + const intersect3 = checkIntersection2(this, raycaster, _ray$12, localThresholdSq, a2, b3, end - 1); + if (intersect3) { + intersects3.push(intersect3); + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l2 = end - 1;i < l2; i += step) { + const intersect3 = checkIntersection2(this, raycaster, _ray$12, localThresholdSq, i, i + 1, i); + if (intersect3) { + intersects3.push(intersect3); + } + } + if (this.isLineLoop) { + const intersect3 = checkIntersection2(this, raycaster, _ray$12, localThresholdSq, end - 1, start, end - 1); + if (intersect3) { + intersects3.push(intersect3); + } + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } + } + function checkIntersection2(object, raycaster, ray, thresholdSq, a2, b3, i) { + const positionAttribute = object.geometry.attributes.position; + _vStart2.fromBufferAttribute(positionAttribute, a2); + _vEnd2.fromBufferAttribute(positionAttribute, b3); + const distSq = ray.distanceSqToSegment(_vStart2, _vEnd2, _intersectPointOnRay2, _intersectPointOnSegment2); + if (distSq > thresholdSq) + return; + _intersectPointOnRay2.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectPointOnRay2); + if (distance < raycaster.near || distance > raycaster.far) + return; + return { + distance, + point: _intersectPointOnSegment2.clone().applyMatrix4(object.matrixWorld), + index: i, + face: null, + faceIndex: null, + barycoord: null, + object + }; + } + var _start5 = /* @__PURE__ */ new Vector32; + var _end5 = /* @__PURE__ */ new Vector32; + + class LineSegments3 extends Line4 { + constructor(geometry, material) { + super(geometry, material); + this.isLineSegments = true; + this.type = "LineSegments"; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + for (let i = 0, l2 = positionAttribute.count;i < l2; i += 2) { + _start5.fromBufferAttribute(positionAttribute, i); + _end5.fromBufferAttribute(positionAttribute, i + 1); + lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1]; + lineDistances[i + 1] = lineDistances[i] + _start5.distanceTo(_end5); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute2(lineDistances, 1)); + } else { + console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + } + + class LineLoop2 extends Line4 { + constructor(geometry, material) { + super(geometry, material); + this.isLineLoop = true; + this.type = "LineLoop"; + } + } + + class PointsMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isPointsMaterial = true; + this.type = "PointsMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.alphaMap = null; + this.size = 1; + this.sizeAttenuation = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } + } + var _inverseMatrix3 = /* @__PURE__ */ new Matrix42; + var _ray4 = /* @__PURE__ */ new Ray2; + var _sphere4 = /* @__PURE__ */ new Sphere2; + var _position$22 = /* @__PURE__ */ new Vector32; + + class Points2 extends Object3D2 { + constructor(geometry = new BufferGeometry2, material = new PointsMaterial2) { + super(); + this.isPoints = true; + this.type = "Points"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + raycast(raycaster, intersects3) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere4.copy(geometry.boundingSphere); + _sphere4.applyMatrix4(matrixWorld); + _sphere4.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere4) === false) + return; + _inverseMatrix3.copy(matrixWorld).invert(); + _ray4.copy(raycaster.ray).applyMatrix4(_inverseMatrix3); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const index2 = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index2 !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i++) { + const a2 = index2.getX(i); + _position$22.fromBufferAttribute(positionAttribute, a2); + testPoint2(_position$22, a2, localThresholdSq, matrixWorld, raycaster, intersects3, this); + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l2 = end;i < l2; i++) { + _position$22.fromBufferAttribute(positionAttribute, i); + testPoint2(_position$22, i, localThresholdSq, matrixWorld, raycaster, intersects3, this); + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } + } + function testPoint2(point, index2, localThresholdSq, matrixWorld, raycaster, intersects3, object) { + const rayPointDistanceSq = _ray4.distanceSqToPoint(point); + if (rayPointDistanceSq < localThresholdSq) { + const intersectPoint = new Vector32; + _ray4.closestPointToPoint(point, intersectPoint); + intersectPoint.applyMatrix4(matrixWorld); + const distance = raycaster.ray.origin.distanceTo(intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) + return; + intersects3.push({ + distance, + distanceToRay: Math.sqrt(rayPointDistanceSq), + point: intersectPoint, + index: index2, + face: null, + faceIndex: null, + barycoord: null, + object + }); + } + } + + class VideoTexture2 extends Texture2 { + constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoTexture = true; + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter2; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter2; + this.generateMipmaps = false; + const scope = this; + function updateVideo() { + scope.needsUpdate = true; + video.requestVideoFrameCallback(updateVideo); + } + if ("requestVideoFrameCallback" in video) { + video.requestVideoFrameCallback(updateVideo); + } + } + clone() { + return new this.constructor(this.image).copy(this); + } + update() { + const video = this.image; + const hasVideoFrameCallback = "requestVideoFrameCallback" in video; + if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) { + this.needsUpdate = true; + } + } + } + + class VideoFrameTexture2 extends VideoTexture2 { + constructor(mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super({}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoFrameTexture = true; + } + update() { + } + clone() { + return new this.constructor().copy(this); + } + setFrame(frame) { + this.image = frame; + this.needsUpdate = true; + } + } + + class FramebufferTexture2 extends Texture2 { + constructor(width2, height2) { + super({ width: width2, height: height2 }); + this.isFramebufferTexture = true; + this.magFilter = NearestFilter2; + this.minFilter = NearestFilter2; + this.generateMipmaps = false; + this.needsUpdate = true; + } + } + + class CompressedTexture2 extends Texture2 { + constructor(mipmaps, width2, height2, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCompressedTexture = true; + this.image = { width: width2, height: height2 }; + this.mipmaps = mipmaps; + this.flipY = false; + this.generateMipmaps = false; + } + } + + class CompressedArrayTexture2 extends CompressedTexture2 { + constructor(mipmaps, width2, height2, depth, format, type) { + super(mipmaps, width2, height2, format, type); + this.isCompressedArrayTexture = true; + this.image.depth = depth; + this.wrapR = ClampToEdgeWrapping2; + this.layerUpdates = new Set; + } + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + clearLayerUpdates() { + this.layerUpdates.clear(); + } + } + + class CompressedCubeTexture2 extends CompressedTexture2 { + constructor(images, format, type) { + super(undefined, images[0].width, images[0].height, format, type, CubeReflectionMapping2); + this.isCompressedCubeTexture = true; + this.isCubeTexture = true; + this.image = images; + } + } + + class CanvasTexture2 extends Texture2 { + constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isCanvasTexture = true; + this.needsUpdate = true; + } + } + + class DepthTexture2 extends Texture2 { + constructor(width2, height2, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat2) { + if (format !== DepthFormat2 && format !== DepthStencilFormat2) { + throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); + } + if (type === undefined && format === DepthFormat2) + type = UnsignedIntType2; + if (type === undefined && format === DepthStencilFormat2) + type = UnsignedInt248Type2; + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isDepthTexture = true; + this.image = { width: width2, height: height2 }; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter2; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter2; + this.flipY = false; + this.generateMipmaps = false; + this.compareFunction = null; + } + copy(source) { + super.copy(source); + this.compareFunction = source.compareFunction; + return this; + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + if (this.compareFunction !== null) + data2.compareFunction = this.compareFunction; + return data2; + } + } + + class Curve2 { + constructor() { + this.type = "Curve"; + this.arcLengthDivisions = 200; + } + getPoint() { + console.warn("THREE.Curve: .getPoint() not implemented."); + return null; + } + getPointAt(u3, optionalTarget) { + const t4 = this.getUtoTmapping(u3); + return this.getPoint(t4, optionalTarget); + } + getPoints(divisions = 5) { + const points = []; + for (let d = 0;d <= divisions; d++) { + points.push(this.getPoint(d / divisions)); + } + return points; + } + getSpacedPoints(divisions = 5) { + const points = []; + for (let d = 0;d <= divisions; d++) { + points.push(this.getPointAt(d / divisions)); + } + return points; + } + getLength() { + const lengths2 = this.getLengths(); + return lengths2[lengths2.length - 1]; + } + getLengths(divisions = this.arcLengthDivisions) { + if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) { + return this.cacheArcLengths; + } + this.needsUpdate = false; + const cache = []; + let current, last2 = this.getPoint(0); + let sum2 = 0; + cache.push(0); + for (let p = 1;p <= divisions; p++) { + current = this.getPoint(p / divisions); + sum2 += current.distanceTo(last2); + cache.push(sum2); + last2 = current; + } + this.cacheArcLengths = cache; + return cache; + } + updateArcLengths() { + this.needsUpdate = true; + this.getLengths(); + } + getUtoTmapping(u3, distance) { + const arcLengths = this.getLengths(); + let i = 0; + const il = arcLengths.length; + let targetArcLength; + if (distance) { + targetArcLength = distance; + } else { + targetArcLength = u3 * arcLengths[il - 1]; + } + let low = 0, high = il - 1, comparison; + while (low <= high) { + i = Math.floor(low + (high - low) / 2); + comparison = arcLengths[i] - targetArcLength; + if (comparison < 0) { + low = i + 1; + } else if (comparison > 0) { + high = i - 1; + } else { + high = i; + break; + } + } + i = high; + if (arcLengths[i] === targetArcLength) { + return i / (il - 1); + } + const lengthBefore = arcLengths[i]; + const lengthAfter = arcLengths[i + 1]; + const segmentLength = lengthAfter - lengthBefore; + const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; + const t4 = (i + segmentFraction) / (il - 1); + return t4; + } + getTangent(t4, optionalTarget) { + const delta = 0.0001; + let t1 = t4 - delta; + let t22 = t4 + delta; + if (t1 < 0) + t1 = 0; + if (t22 > 1) + t22 = 1; + const pt1 = this.getPoint(t1); + const pt2 = this.getPoint(t22); + const tangent = optionalTarget || (pt1.isVector2 ? new Vector22 : new Vector32); + tangent.copy(pt2).sub(pt1).normalize(); + return tangent; + } + getTangentAt(u3, optionalTarget) { + const t4 = this.getUtoTmapping(u3); + return this.getTangent(t4, optionalTarget); + } + computeFrenetFrames(segments, closed) { + const normal = new Vector32; + const tangents = []; + const normals = []; + const binormals = []; + const vec = new Vector32; + const mat = new Matrix42; + for (let i = 0;i <= segments; i++) { + const u3 = i / segments; + tangents[i] = this.getTangentAt(u3, new Vector32); + } + normals[0] = new Vector32; + binormals[0] = new Vector32; + let min = Number.MAX_VALUE; + const tx = Math.abs(tangents[0].x); + const ty2 = Math.abs(tangents[0].y); + const tz = Math.abs(tangents[0].z); + if (tx <= min) { + min = tx; + normal.set(1, 0, 0); + } + if (ty2 <= min) { + min = ty2; + normal.set(0, 1, 0); + } + if (tz <= min) { + normal.set(0, 0, 1); + } + vec.crossVectors(tangents[0], normal).normalize(); + normals[0].crossVectors(tangents[0], vec); + binormals[0].crossVectors(tangents[0], normals[0]); + for (let i = 1;i <= segments; i++) { + normals[i] = normals[i - 1].clone(); + binormals[i] = binormals[i - 1].clone(); + vec.crossVectors(tangents[i - 1], tangents[i]); + if (vec.length() > Number.EPSILON) { + vec.normalize(); + const theta = Math.acos(clamp3(tangents[i - 1].dot(tangents[i]), -1, 1)); + normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta)); + } + binormals[i].crossVectors(tangents[i], normals[i]); + } + if (closed === true) { + let theta = Math.acos(clamp3(normals[0].dot(normals[segments]), -1, 1)); + theta /= segments; + if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) { + theta = -theta; + } + for (let i = 1;i <= segments; i++) { + normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i)); + binormals[i].crossVectors(tangents[i], normals[i]); + } + } + return { + tangents, + normals, + binormals + }; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.arcLengthDivisions = source.arcLengthDivisions; + return this; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "Curve", + generator: "Curve.toJSON" + } + }; + data2.arcLengthDivisions = this.arcLengthDivisions; + data2.type = this.type; + return data2; + } + fromJSON(json) { + this.arcLengthDivisions = json.arcLengthDivisions; + return this; + } + } + + class EllipseCurve2 extends Curve2 { + constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) { + super(); + this.isEllipseCurve = true; + this.type = "EllipseCurve"; + this.aX = aX; + this.aY = aY; + this.xRadius = xRadius; + this.yRadius = yRadius; + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; + this.aClockwise = aClockwise; + this.aRotation = aRotation; + } + getPoint(t4, optionalTarget = new Vector22) { + const point = optionalTarget; + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs(deltaAngle) < Number.EPSILON; + while (deltaAngle < 0) + deltaAngle += twoPi; + while (deltaAngle > twoPi) + deltaAngle -= twoPi; + if (deltaAngle < Number.EPSILON) { + if (samePoints) { + deltaAngle = 0; + } else { + deltaAngle = twoPi; + } + } + if (this.aClockwise === true && !samePoints) { + if (deltaAngle === twoPi) { + deltaAngle = -twoPi; + } else { + deltaAngle = deltaAngle - twoPi; + } + } + const angle = this.aStartAngle + t4 * deltaAngle; + let x2 = this.aX + this.xRadius * Math.cos(angle); + let y3 = this.aY + this.yRadius * Math.sin(angle); + if (this.aRotation !== 0) { + const cos = Math.cos(this.aRotation); + const sin = Math.sin(this.aRotation); + const tx = x2 - this.aX; + const ty2 = y3 - this.aY; + x2 = tx * cos - ty2 * sin + this.aX; + y3 = tx * sin + ty2 * cos + this.aY; + } + return point.set(x2, y3); + } + copy(source) { + super.copy(source); + this.aX = source.aX; + this.aY = source.aY; + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + this.aClockwise = source.aClockwise; + this.aRotation = source.aRotation; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.aX = this.aX; + data2.aY = this.aY; + data2.xRadius = this.xRadius; + data2.yRadius = this.yRadius; + data2.aStartAngle = this.aStartAngle; + data2.aEndAngle = this.aEndAngle; + data2.aClockwise = this.aClockwise; + data2.aRotation = this.aRotation; + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.aX = json.aX; + this.aY = json.aY; + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + this.aClockwise = json.aClockwise; + this.aRotation = json.aRotation; + return this; + } + } + + class ArcCurve2 extends EllipseCurve2 { + constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + this.isArcCurve = true; + this.type = "ArcCurve"; + } + } + function CubicPoly2() { + let c02 = 0, c1 = 0, c2 = 0, c3 = 0; + function init(x02, x1, t02, t1) { + c02 = x02; + c1 = t02; + c2 = -3 * x02 + 3 * x1 - 2 * t02 - t1; + c3 = 2 * x02 - 2 * x1 + t02 + t1; + } + return { + initCatmullRom: function(x02, x1, x2, x3, tension) { + init(x1, x2, tension * (x2 - x02), tension * (x3 - x1)); + }, + initNonuniformCatmullRom: function(x02, x1, x2, x3, dt0, dt1, dt2) { + let t1 = (x1 - x02) / dt0 - (x2 - x02) / (dt0 + dt1) + (x2 - x1) / dt1; + let t22 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; + t1 *= dt1; + t22 *= dt1; + init(x1, x2, t1, t22); + }, + calc: function(t4) { + const t22 = t4 * t4; + const t32 = t22 * t4; + return c02 + c1 * t4 + c2 * t22 + c3 * t32; + } + }; + } + var tmp2 = /* @__PURE__ */ new Vector32; + var px2 = /* @__PURE__ */ new CubicPoly2; + var py2 = /* @__PURE__ */ new CubicPoly2; + var pz2 = /* @__PURE__ */ new CubicPoly2; + + class CatmullRomCurve32 extends Curve2 { + constructor(points = [], closed = false, curveType = "centripetal", tension = 0.5) { + super(); + this.isCatmullRomCurve3 = true; + this.type = "CatmullRomCurve3"; + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + } + getPoint(t4, optionalTarget = new Vector32) { + const point = optionalTarget; + const points = this.points; + const l2 = points.length; + const p = (l2 - (this.closed ? 0 : 1)) * t4; + let intPoint = Math.floor(p); + let weight = p - intPoint; + if (this.closed) { + intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l2) + 1) * l2; + } else if (weight === 0 && intPoint === l2 - 1) { + intPoint = l2 - 2; + weight = 1; + } + let p0, p32; + if (this.closed || intPoint > 0) { + p0 = points[(intPoint - 1) % l2]; + } else { + tmp2.subVectors(points[0], points[1]).add(points[0]); + p0 = tmp2; + } + const p1 = points[intPoint % l2]; + const p2 = points[(intPoint + 1) % l2]; + if (this.closed || intPoint + 2 < l2) { + p32 = points[(intPoint + 2) % l2]; + } else { + tmp2.subVectors(points[l2 - 1], points[l2 - 2]).add(points[l2 - 1]); + p32 = tmp2; + } + if (this.curveType === "centripetal" || this.curveType === "chordal") { + const pow = this.curveType === "chordal" ? 0.5 : 0.25; + let dt0 = Math.pow(p0.distanceToSquared(p1), pow); + let dt1 = Math.pow(p1.distanceToSquared(p2), pow); + let dt2 = Math.pow(p2.distanceToSquared(p32), pow); + if (dt1 < 0.0001) + dt1 = 1; + if (dt0 < 0.0001) + dt0 = dt1; + if (dt2 < 0.0001) + dt2 = dt1; + px2.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p32.x, dt0, dt1, dt2); + py2.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p32.y, dt0, dt1, dt2); + pz2.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p32.z, dt0, dt1, dt2); + } else if (this.curveType === "catmullrom") { + px2.initCatmullRom(p0.x, p1.x, p2.x, p32.x, this.tension); + py2.initCatmullRom(p0.y, p1.y, p2.y, p32.y, this.tension); + pz2.initCatmullRom(p0.z, p1.z, p2.z, p32.z, this.tension); + } + point.set(px2.calc(weight), py2.calc(weight), pz2.calc(weight)); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l2 = source.points.length;i < l2; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.points = []; + for (let i = 0, l2 = this.points.length;i < l2; i++) { + const point = this.points[i]; + data2.points.push(point.toArray()); + } + data2.closed = this.closed; + data2.curveType = this.curveType; + data2.tension = this.tension; + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l2 = json.points.length;i < l2; i++) { + const point = json.points[i]; + this.points.push(new Vector32().fromArray(point)); + } + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + return this; + } + } + function CatmullRom2(t4, p0, p1, p2, p32) { + const v0 = (p2 - p0) * 0.5; + const v12 = (p32 - p1) * 0.5; + const t22 = t4 * t4; + const t32 = t4 * t22; + return (2 * p1 - 2 * p2 + v0 + v12) * t32 + (-3 * p1 + 3 * p2 - 2 * v0 - v12) * t22 + v0 * t4 + p1; + } + function QuadraticBezierP02(t4, p) { + const k4 = 1 - t4; + return k4 * k4 * p; + } + function QuadraticBezierP12(t4, p) { + return 2 * (1 - t4) * t4 * p; + } + function QuadraticBezierP22(t4, p) { + return t4 * t4 * p; + } + function QuadraticBezier2(t4, p0, p1, p2) { + return QuadraticBezierP02(t4, p0) + QuadraticBezierP12(t4, p1) + QuadraticBezierP22(t4, p2); + } + function CubicBezierP02(t4, p) { + const k4 = 1 - t4; + return k4 * k4 * k4 * p; + } + function CubicBezierP12(t4, p) { + const k4 = 1 - t4; + return 3 * k4 * k4 * t4 * p; + } + function CubicBezierP22(t4, p) { + return 3 * (1 - t4) * t4 * t4 * p; + } + function CubicBezierP32(t4, p) { + return t4 * t4 * t4 * p; + } + function CubicBezier2(t4, p0, p1, p2, p32) { + return CubicBezierP02(t4, p0) + CubicBezierP12(t4, p1) + CubicBezierP22(t4, p2) + CubicBezierP32(t4, p32); + } + + class CubicBezierCurve2 extends Curve2 { + constructor(v0 = new Vector22, v12 = new Vector22, v2 = new Vector22, v32 = new Vector22) { + super(); + this.isCubicBezierCurve = true; + this.type = "CubicBezierCurve"; + this.v0 = v0; + this.v1 = v12; + this.v2 = v2; + this.v3 = v32; + } + getPoint(t4, optionalTarget = new Vector22) { + const point = optionalTarget; + const v0 = this.v0, v12 = this.v1, v2 = this.v2, v32 = this.v3; + point.set(CubicBezier2(t4, v0.x, v12.x, v2.x, v32.x), CubicBezier2(t4, v0.y, v12.y, v2.y, v32.y)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + data2.v3 = this.v3.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } + } + + class CubicBezierCurve32 extends Curve2 { + constructor(v0 = new Vector32, v12 = new Vector32, v2 = new Vector32, v32 = new Vector32) { + super(); + this.isCubicBezierCurve3 = true; + this.type = "CubicBezierCurve3"; + this.v0 = v0; + this.v1 = v12; + this.v2 = v2; + this.v3 = v32; + } + getPoint(t4, optionalTarget = new Vector32) { + const point = optionalTarget; + const v0 = this.v0, v12 = this.v1, v2 = this.v2, v32 = this.v3; + point.set(CubicBezier2(t4, v0.x, v12.x, v2.x, v32.x), CubicBezier2(t4, v0.y, v12.y, v2.y, v32.y), CubicBezier2(t4, v0.z, v12.z, v2.z, v32.z)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + data2.v3 = this.v3.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } + } + + class LineCurve2 extends Curve2 { + constructor(v12 = new Vector22, v2 = new Vector22) { + super(); + this.isLineCurve = true; + this.type = "LineCurve"; + this.v1 = v12; + this.v2 = v2; + } + getPoint(t4, optionalTarget = new Vector22) { + const point = optionalTarget; + if (t4 === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t4).add(this.v1); + } + return point; + } + getPointAt(u3, optionalTarget) { + return this.getPoint(u3, optionalTarget); + } + getTangent(t4, optionalTarget = new Vector22) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u3, optionalTarget) { + return this.getTangent(u3, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + + class LineCurve32 extends Curve2 { + constructor(v12 = new Vector32, v2 = new Vector32) { + super(); + this.isLineCurve3 = true; + this.type = "LineCurve3"; + this.v1 = v12; + this.v2 = v2; + } + getPoint(t4, optionalTarget = new Vector32) { + const point = optionalTarget; + if (t4 === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t4).add(this.v1); + } + return point; + } + getPointAt(u3, optionalTarget) { + return this.getPoint(u3, optionalTarget); + } + getTangent(t4, optionalTarget = new Vector32) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u3, optionalTarget) { + return this.getTangent(u3, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + + class QuadraticBezierCurve2 extends Curve2 { + constructor(v0 = new Vector22, v12 = new Vector22, v2 = new Vector22) { + super(); + this.isQuadraticBezierCurve = true; + this.type = "QuadraticBezierCurve"; + this.v0 = v0; + this.v1 = v12; + this.v2 = v2; + } + getPoint(t4, optionalTarget = new Vector22) { + const point = optionalTarget; + const v0 = this.v0, v12 = this.v1, v2 = this.v2; + point.set(QuadraticBezier2(t4, v0.x, v12.x, v2.x), QuadraticBezier2(t4, v0.y, v12.y, v2.y)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + + class QuadraticBezierCurve32 extends Curve2 { + constructor(v0 = new Vector32, v12 = new Vector32, v2 = new Vector32) { + super(); + this.isQuadraticBezierCurve3 = true; + this.type = "QuadraticBezierCurve3"; + this.v0 = v0; + this.v1 = v12; + this.v2 = v2; + } + getPoint(t4, optionalTarget = new Vector32) { + const point = optionalTarget; + const v0 = this.v0, v12 = this.v1, v2 = this.v2; + point.set(QuadraticBezier2(t4, v0.x, v12.x, v2.x), QuadraticBezier2(t4, v0.y, v12.y, v2.y), QuadraticBezier2(t4, v0.z, v12.z, v2.z)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + + class SplineCurve2 extends Curve2 { + constructor(points = []) { + super(); + this.isSplineCurve = true; + this.type = "SplineCurve"; + this.points = points; + } + getPoint(t4, optionalTarget = new Vector22) { + const point = optionalTarget; + const points = this.points; + const p = (points.length - 1) * t4; + const intPoint = Math.floor(p); + const weight = p - intPoint; + const p0 = points[intPoint === 0 ? intPoint : intPoint - 1]; + const p1 = points[intPoint]; + const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1]; + const p32 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2]; + point.set(CatmullRom2(weight, p0.x, p1.x, p2.x, p32.x), CatmullRom2(weight, p0.y, p1.y, p2.y, p32.y)); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l2 = source.points.length;i < l2; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.points = []; + for (let i = 0, l2 = this.points.length;i < l2; i++) { + const point = this.points[i]; + data2.points.push(point.toArray()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l2 = json.points.length;i < l2; i++) { + const point = json.points[i]; + this.points.push(new Vector22().fromArray(point)); + } + return this; + } + } + var Curves2 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ArcCurve: ArcCurve2, + CatmullRomCurve3: CatmullRomCurve32, + CubicBezierCurve: CubicBezierCurve2, + CubicBezierCurve3: CubicBezierCurve32, + EllipseCurve: EllipseCurve2, + LineCurve: LineCurve2, + LineCurve3: LineCurve32, + QuadraticBezierCurve: QuadraticBezierCurve2, + QuadraticBezierCurve3: QuadraticBezierCurve32, + SplineCurve: SplineCurve2 + }); + + class CurvePath2 extends Curve2 { + constructor() { + super(); + this.type = "CurvePath"; + this.curves = []; + this.autoClose = false; + } + add(curve) { + this.curves.push(curve); + } + closePath() { + const startPoint = this.curves[0].getPoint(0); + const endPoint = this.curves[this.curves.length - 1].getPoint(1); + if (!startPoint.equals(endPoint)) { + const lineType = startPoint.isVector2 === true ? "LineCurve" : "LineCurve3"; + this.curves.push(new Curves2[lineType](endPoint, startPoint)); + } + return this; + } + getPoint(t4, optionalTarget) { + const d = t4 * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + while (i < curveLengths.length) { + if (curveLengths[i] >= d) { + const diff = curveLengths[i] - d; + const curve = this.curves[i]; + const segmentLength = curve.getLength(); + const u3 = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + return curve.getPointAt(u3, optionalTarget); + } + i++; + } + return null; + } + getLength() { + const lens = this.getCurveLengths(); + return lens[lens.length - 1]; + } + updateArcLengths() { + this.needsUpdate = true; + this.cacheLengths = null; + this.getCurveLengths(); + } + getCurveLengths() { + if (this.cacheLengths && this.cacheLengths.length === this.curves.length) { + return this.cacheLengths; + } + const lengths2 = []; + let sums = 0; + for (let i = 0, l2 = this.curves.length;i < l2; i++) { + sums += this.curves[i].getLength(); + lengths2.push(sums); + } + this.cacheLengths = lengths2; + return lengths2; + } + getSpacedPoints(divisions = 40) { + const points = []; + for (let i = 0;i <= divisions; i++) { + points.push(this.getPoint(i / divisions)); + } + if (this.autoClose) { + points.push(points[0]); + } + return points; + } + getPoints(divisions = 12) { + const points = []; + let last2; + for (let i = 0, curves = this.curves;i < curves.length; i++) { + const curve = curves[i]; + const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions; + const pts = curve.getPoints(resolution); + for (let j2 = 0;j2 < pts.length; j2++) { + const point = pts[j2]; + if (last2 && last2.equals(point)) + continue; + points.push(point); + last2 = point; + } + } + if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) { + points.push(points[0]); + } + return points; + } + copy(source) { + super.copy(source); + this.curves = []; + for (let i = 0, l2 = source.curves.length;i < l2; i++) { + const curve = source.curves[i]; + this.curves.push(curve.clone()); + } + this.autoClose = source.autoClose; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.autoClose = this.autoClose; + data2.curves = []; + for (let i = 0, l2 = this.curves.length;i < l2; i++) { + const curve = this.curves[i]; + data2.curves.push(curve.toJSON()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.autoClose = json.autoClose; + this.curves = []; + for (let i = 0, l2 = json.curves.length;i < l2; i++) { + const curve = json.curves[i]; + this.curves.push(new Curves2[curve.type]().fromJSON(curve)); + } + return this; + } + } + + class Path3 extends CurvePath2 { + constructor(points) { + super(); + this.type = "Path"; + this.currentPoint = new Vector22; + if (points) { + this.setFromPoints(points); + } + } + setFromPoints(points) { + this.moveTo(points[0].x, points[0].y); + for (let i = 1, l2 = points.length;i < l2; i++) { + this.lineTo(points[i].x, points[i].y); + } + return this; + } + moveTo(x2, y3) { + this.currentPoint.set(x2, y3); + return this; + } + lineTo(x2, y3) { + const curve = new LineCurve2(this.currentPoint.clone(), new Vector22(x2, y3)); + this.curves.push(curve); + this.currentPoint.set(x2, y3); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + const curve = new QuadraticBezierCurve2(this.currentPoint.clone(), new Vector22(aCPx, aCPy), new Vector22(aX, aY)); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + const curve = new CubicBezierCurve2(this.currentPoint.clone(), new Vector22(aCP1x, aCP1y), new Vector22(aCP2x, aCP2y), new Vector22(aX, aY)); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + splineThru(pts) { + const npts = [this.currentPoint.clone()].concat(pts); + const curve = new SplineCurve2(npts); + this.curves.push(curve); + this.currentPoint.copy(pts[pts.length - 1]); + return this; + } + arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + const x02 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absarc(aX + x02, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const x02 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absellipse(aX + x02, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + return this; + } + absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const curve = new EllipseCurve2(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + if (this.curves.length > 0) { + const firstPoint = curve.getPoint(0); + if (!firstPoint.equals(this.currentPoint)) { + this.lineTo(firstPoint.x, firstPoint.y); + } + } + this.curves.push(curve); + const lastPoint = curve.getPoint(1); + this.currentPoint.copy(lastPoint); + return this; + } + copy(source) { + super.copy(source); + this.currentPoint.copy(source.currentPoint); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.currentPoint = this.currentPoint.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.currentPoint.fromArray(json.currentPoint); + return this; + } + } + + class LatheGeometry2 extends BufferGeometry2 { + constructor(points = [new Vector22(0, -0.5), new Vector22(0.5, 0), new Vector22(0, 0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) { + super(); + this.type = "LatheGeometry"; + this.parameters = { + points, + segments, + phiStart, + phiLength + }; + segments = Math.floor(segments); + phiLength = clamp3(phiLength, 0, Math.PI * 2); + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; + const inverseSegments = 1 / segments; + const vertex3 = new Vector32; + const uv = new Vector22; + const normal = new Vector32; + const curNormal = new Vector32; + const prevNormal = new Vector32; + let dx = 0; + let dy2 = 0; + for (let j2 = 0;j2 <= points.length - 1; j2++) { + switch (j2) { + case 0: + dx = points[j2 + 1].x - points[j2].x; + dy2 = points[j2 + 1].y - points[j2].y; + normal.x = dy2 * 1; + normal.y = -dx; + normal.z = dy2 * 0; + prevNormal.copy(normal); + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + break; + case points.length - 1: + initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z); + break; + default: + dx = points[j2 + 1].x - points[j2].x; + dy2 = points[j2 + 1].y - points[j2].y; + normal.x = dy2 * 1; + normal.y = -dx; + normal.z = dy2 * 0; + curNormal.copy(normal); + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + prevNormal.copy(curNormal); + } + } + for (let i = 0;i <= segments; i++) { + const phi = phiStart + i * inverseSegments * phiLength; + const sin = Math.sin(phi); + const cos = Math.cos(phi); + for (let j2 = 0;j2 <= points.length - 1; j2++) { + vertex3.x = points[j2].x * sin; + vertex3.y = points[j2].y; + vertex3.z = points[j2].x * cos; + vertices.push(vertex3.x, vertex3.y, vertex3.z); + uv.x = i / segments; + uv.y = j2 / (points.length - 1); + uvs.push(uv.x, uv.y); + const x2 = initNormals[3 * j2 + 0] * sin; + const y3 = initNormals[3 * j2 + 1]; + const z2 = initNormals[3 * j2 + 0] * cos; + normals.push(x2, y3, z2); + } + } + for (let i = 0;i < segments; i++) { + for (let j2 = 0;j2 < points.length - 1; j2++) { + const base = j2 + i * points.length; + const a2 = base; + const b3 = base + points.length; + const c2 = base + points.length + 1; + const d = base + 1; + indices.push(a2, b3, d); + indices.push(c2, d, b3); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new LatheGeometry2(data2.points, data2.segments, data2.phiStart, data2.phiLength); + } + } + + class CapsuleGeometry2 extends LatheGeometry2 { + constructor(radius = 1, length2 = 1, capSegments = 4, radialSegments = 8) { + const path = new Path3; + path.absarc(0, -length2 / 2, radius, Math.PI * 1.5, 0); + path.absarc(0, length2 / 2, radius, 0, Math.PI * 0.5); + super(path.getPoints(capSegments), radialSegments); + this.type = "CapsuleGeometry"; + this.parameters = { + radius, + length: length2, + capSegments, + radialSegments + }; + } + static fromJSON(data2) { + return new CapsuleGeometry2(data2.radius, data2.length, data2.capSegments, data2.radialSegments); + } + } + + class CircleGeometry2 extends BufferGeometry2 { + constructor(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CircleGeometry"; + this.parameters = { + radius, + segments, + thetaStart, + thetaLength + }; + segments = Math.max(3, segments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex3 = new Vector32; + const uv = new Vector22; + vertices.push(0, 0, 0); + normals.push(0, 0, 1); + uvs.push(0.5, 0.5); + for (let s = 0, i = 3;s <= segments; s++, i += 3) { + const segment = thetaStart + s / segments * thetaLength; + vertex3.x = radius * Math.cos(segment); + vertex3.y = radius * Math.sin(segment); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normals.push(0, 0, 1); + uv.x = (vertices[i] / radius + 1) / 2; + uv.y = (vertices[i + 1] / radius + 1) / 2; + uvs.push(uv.x, uv.y); + } + for (let i = 1;i <= segments; i++) { + indices.push(i, i + 1, 0); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new CircleGeometry2(data2.radius, data2.segments, data2.thetaStart, data2.thetaLength); + } + } + + class CylinderGeometry2 extends BufferGeometry2 { + constructor(radiusTop = 1, radiusBottom = 1, height2 = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CylinderGeometry"; + this.parameters = { + radiusTop, + radiusBottom, + height: height2, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + const scope = this; + radialSegments = Math.floor(radialSegments); + heightSegments = Math.floor(heightSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let index2 = 0; + const indexArray = []; + const halfHeight = height2 / 2; + let groupStart = 0; + generateTorso(); + if (openEnded === false) { + if (radiusTop > 0) + generateCap(true); + if (radiusBottom > 0) + generateCap(false); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function generateTorso() { + const normal = new Vector32; + const vertex3 = new Vector32; + let groupCount = 0; + const slope = (radiusBottom - radiusTop) / height2; + for (let y3 = 0;y3 <= heightSegments; y3++) { + const indexRow = []; + const v = y3 / heightSegments; + const radius = v * (radiusBottom - radiusTop) + radiusTop; + for (let x2 = 0;x2 <= radialSegments; x2++) { + const u3 = x2 / radialSegments; + const theta = u3 * thetaLength + thetaStart; + const sinTheta = Math.sin(theta); + const cosTheta = Math.cos(theta); + vertex3.x = radius * sinTheta; + vertex3.y = -v * height2 + halfHeight; + vertex3.z = radius * cosTheta; + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normal.set(sinTheta, slope, cosTheta).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u3, 1 - v); + indexRow.push(index2++); + } + indexArray.push(indexRow); + } + for (let x2 = 0;x2 < radialSegments; x2++) { + for (let y3 = 0;y3 < heightSegments; y3++) { + const a2 = indexArray[y3][x2]; + const b3 = indexArray[y3 + 1][x2]; + const c2 = indexArray[y3 + 1][x2 + 1]; + const d = indexArray[y3][x2 + 1]; + if (radiusTop > 0 || y3 !== 0) { + indices.push(a2, b3, d); + groupCount += 3; + } + if (radiusBottom > 0 || y3 !== heightSegments - 1) { + indices.push(b3, c2, d); + groupCount += 3; + } + } + } + scope.addGroup(groupStart, groupCount, 0); + groupStart += groupCount; + } + function generateCap(top) { + const centerIndexStart = index2; + const uv = new Vector22; + const vertex3 = new Vector32; + let groupCount = 0; + const radius = top === true ? radiusTop : radiusBottom; + const sign3 = top === true ? 1 : -1; + for (let x2 = 1;x2 <= radialSegments; x2++) { + vertices.push(0, halfHeight * sign3, 0); + normals.push(0, sign3, 0); + uvs.push(0.5, 0.5); + index2++; + } + const centerIndexEnd = index2; + for (let x2 = 0;x2 <= radialSegments; x2++) { + const u3 = x2 / radialSegments; + const theta = u3 * thetaLength + thetaStart; + const cosTheta = Math.cos(theta); + const sinTheta = Math.sin(theta); + vertex3.x = radius * sinTheta; + vertex3.y = halfHeight * sign3; + vertex3.z = radius * cosTheta; + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normals.push(0, sign3, 0); + uv.x = cosTheta * 0.5 + 0.5; + uv.y = sinTheta * 0.5 * sign3 + 0.5; + uvs.push(uv.x, uv.y); + index2++; + } + for (let x2 = 0;x2 < radialSegments; x2++) { + const c2 = centerIndexStart + x2; + const i = centerIndexEnd + x2; + if (top === true) { + indices.push(i, i + 1, c2); + } else { + indices.push(i + 1, i, c2); + } + groupCount += 3; + } + scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); + groupStart += groupCount; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new CylinderGeometry2(data2.radiusTop, data2.radiusBottom, data2.height, data2.radialSegments, data2.heightSegments, data2.openEnded, data2.thetaStart, data2.thetaLength); + } + } + + class ConeGeometry2 extends CylinderGeometry2 { + constructor(radius = 1, height2 = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(0, radius, height2, radialSegments, heightSegments, openEnded, thetaStart, thetaLength); + this.type = "ConeGeometry"; + this.parameters = { + radius, + height: height2, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + } + static fromJSON(data2) { + return new ConeGeometry2(data2.radius, data2.height, data2.radialSegments, data2.heightSegments, data2.openEnded, data2.thetaStart, data2.thetaLength); + } + } + + class PolyhedronGeometry2 extends BufferGeometry2 { + constructor(vertices = [], indices = [], radius = 1, detail = 0) { + super(); + this.type = "PolyhedronGeometry"; + this.parameters = { + vertices, + indices, + radius, + detail + }; + const vertexBuffer = []; + const uvBuffer = []; + subdivide(detail); + applyRadius(radius); + generateUVs(); + this.setAttribute("position", new Float32BufferAttribute2(vertexBuffer, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(vertexBuffer.slice(), 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvBuffer, 2)); + if (detail === 0) { + this.computeVertexNormals(); + } else { + this.normalizeNormals(); + } + function subdivide(detail2) { + const a2 = new Vector32; + const b3 = new Vector32; + const c2 = new Vector32; + for (let i = 0;i < indices.length; i += 3) { + getVertexByIndex(indices[i + 0], a2); + getVertexByIndex(indices[i + 1], b3); + getVertexByIndex(indices[i + 2], c2); + subdivideFace(a2, b3, c2, detail2); + } + } + function subdivideFace(a2, b3, c2, detail2) { + const cols = detail2 + 1; + const v = []; + for (let i = 0;i <= cols; i++) { + v[i] = []; + const aj = a2.clone().lerp(c2, i / cols); + const bj = b3.clone().lerp(c2, i / cols); + const rows = cols - i; + for (let j2 = 0;j2 <= rows; j2++) { + if (j2 === 0 && i === cols) { + v[i][j2] = aj; + } else { + v[i][j2] = aj.clone().lerp(bj, j2 / rows); + } + } + } + for (let i = 0;i < cols; i++) { + for (let j2 = 0;j2 < 2 * (cols - i) - 1; j2++) { + const k4 = Math.floor(j2 / 2); + if (j2 % 2 === 0) { + pushVertex(v[i][k4 + 1]); + pushVertex(v[i + 1][k4]); + pushVertex(v[i][k4]); + } else { + pushVertex(v[i][k4 + 1]); + pushVertex(v[i + 1][k4 + 1]); + pushVertex(v[i + 1][k4]); + } + } + } + } + function applyRadius(radius2) { + const vertex3 = new Vector32; + for (let i = 0;i < vertexBuffer.length; i += 3) { + vertex3.x = vertexBuffer[i + 0]; + vertex3.y = vertexBuffer[i + 1]; + vertex3.z = vertexBuffer[i + 2]; + vertex3.normalize().multiplyScalar(radius2); + vertexBuffer[i + 0] = vertex3.x; + vertexBuffer[i + 1] = vertex3.y; + vertexBuffer[i + 2] = vertex3.z; + } + } + function generateUVs() { + const vertex3 = new Vector32; + for (let i = 0;i < vertexBuffer.length; i += 3) { + vertex3.x = vertexBuffer[i + 0]; + vertex3.y = vertexBuffer[i + 1]; + vertex3.z = vertexBuffer[i + 2]; + const u3 = azimuth(vertex3) / 2 / Math.PI + 0.5; + const v = inclination(vertex3) / Math.PI + 0.5; + uvBuffer.push(u3, 1 - v); + } + correctUVs(); + correctSeam(); + } + function correctSeam() { + for (let i = 0;i < uvBuffer.length; i += 6) { + const x02 = uvBuffer[i + 0]; + const x1 = uvBuffer[i + 2]; + const x2 = uvBuffer[i + 4]; + const max = Math.max(x02, x1, x2); + const min = Math.min(x02, x1, x2); + if (max > 0.9 && min < 0.1) { + if (x02 < 0.2) + uvBuffer[i + 0] += 1; + if (x1 < 0.2) + uvBuffer[i + 2] += 1; + if (x2 < 0.2) + uvBuffer[i + 4] += 1; + } + } + } + function pushVertex(vertex3) { + vertexBuffer.push(vertex3.x, vertex3.y, vertex3.z); + } + function getVertexByIndex(index2, vertex3) { + const stride = index2 * 3; + vertex3.x = vertices[stride + 0]; + vertex3.y = vertices[stride + 1]; + vertex3.z = vertices[stride + 2]; + } + function correctUVs() { + const a2 = new Vector32; + const b3 = new Vector32; + const c2 = new Vector32; + const centroid = new Vector32; + const uvA = new Vector22; + const uvB = new Vector22; + const uvC = new Vector22; + for (let i = 0, j2 = 0;i < vertexBuffer.length; i += 9, j2 += 6) { + a2.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]); + b3.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]); + c2.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]); + uvA.set(uvBuffer[j2 + 0], uvBuffer[j2 + 1]); + uvB.set(uvBuffer[j2 + 2], uvBuffer[j2 + 3]); + uvC.set(uvBuffer[j2 + 4], uvBuffer[j2 + 5]); + centroid.copy(a2).add(b3).add(c2).divideScalar(3); + const azi = azimuth(centroid); + correctUV(uvA, j2 + 0, a2, azi); + correctUV(uvB, j2 + 2, b3, azi); + correctUV(uvC, j2 + 4, c2, azi); + } + } + function correctUV(uv, stride, vector, azimuth2) { + if (azimuth2 < 0 && uv.x === 1) { + uvBuffer[stride] = uv.x - 1; + } + if (vector.x === 0 && vector.z === 0) { + uvBuffer[stride] = azimuth2 / 2 / Math.PI + 0.5; + } + } + function azimuth(vector) { + return Math.atan2(vector.z, -vector.x); + } + function inclination(vector) { + return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new PolyhedronGeometry2(data2.vertices, data2.indices, data2.radius, data2.details); + } + } + + class DodecahedronGeometry2 extends PolyhedronGeometry2 { + constructor(radius = 1, detail = 0) { + const t4 = (1 + Math.sqrt(5)) / 2; + const r = 1 / t4; + const vertices = [ + -1, + -1, + -1, + -1, + -1, + 1, + -1, + 1, + -1, + -1, + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + 1, + 1, + -1, + 1, + 1, + 1, + 0, + -r, + -t4, + 0, + -r, + t4, + 0, + r, + -t4, + 0, + r, + t4, + -r, + -t4, + 0, + -r, + t4, + 0, + r, + -t4, + 0, + r, + t4, + 0, + -t4, + 0, + -r, + t4, + 0, + -r, + -t4, + 0, + r, + t4, + 0, + r + ]; + const indices = [ + 3, + 11, + 7, + 3, + 7, + 15, + 3, + 15, + 13, + 7, + 19, + 17, + 7, + 17, + 6, + 7, + 6, + 15, + 17, + 4, + 8, + 17, + 8, + 10, + 17, + 10, + 6, + 8, + 0, + 16, + 8, + 16, + 2, + 8, + 2, + 10, + 0, + 12, + 1, + 0, + 1, + 18, + 0, + 18, + 16, + 6, + 10, + 2, + 6, + 2, + 13, + 6, + 13, + 15, + 2, + 16, + 18, + 2, + 18, + 3, + 2, + 3, + 13, + 18, + 1, + 9, + 18, + 9, + 11, + 18, + 11, + 3, + 4, + 14, + 12, + 4, + 12, + 0, + 4, + 0, + 8, + 11, + 9, + 5, + 11, + 5, + 19, + 11, + 19, + 7, + 19, + 5, + 14, + 19, + 14, + 4, + 19, + 4, + 17, + 1, + 12, + 14, + 1, + 14, + 5, + 1, + 5, + 9 + ]; + super(vertices, indices, radius, detail); + this.type = "DodecahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new DodecahedronGeometry2(data2.radius, data2.detail); + } + } + var _v0$12 = /* @__PURE__ */ new Vector32; + var _v1$12 = /* @__PURE__ */ new Vector32; + var _normal2 = /* @__PURE__ */ new Vector32; + var _triangle3 = /* @__PURE__ */ new Triangle2; + + class EdgesGeometry2 extends BufferGeometry2 { + constructor(geometry = null, thresholdAngle = 1) { + super(); + this.type = "EdgesGeometry"; + this.parameters = { + geometry, + thresholdAngle + }; + if (geometry !== null) { + const precisionPoints = 4; + const precision = Math.pow(10, precisionPoints); + const thresholdDot = Math.cos(DEG2RAD2 * thresholdAngle); + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute("position"); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + const indexArr = [0, 0, 0]; + const vertKeys = ["a", "b", "c"]; + const hashes = new Array(3); + const edgeData = {}; + const vertices = []; + for (let i = 0;i < indexCount; i += 3) { + if (indexAttr) { + indexArr[0] = indexAttr.getX(i); + indexArr[1] = indexAttr.getX(i + 1); + indexArr[2] = indexAttr.getX(i + 2); + } else { + indexArr[0] = i; + indexArr[1] = i + 1; + indexArr[2] = i + 2; + } + const { a: a2, b: b3, c: c2 } = _triangle3; + a2.fromBufferAttribute(positionAttr, indexArr[0]); + b3.fromBufferAttribute(positionAttr, indexArr[1]); + c2.fromBufferAttribute(positionAttr, indexArr[2]); + _triangle3.getNormal(_normal2); + hashes[0] = `${Math.round(a2.x * precision)},${Math.round(a2.y * precision)},${Math.round(a2.z * precision)}`; + hashes[1] = `${Math.round(b3.x * precision)},${Math.round(b3.y * precision)},${Math.round(b3.z * precision)}`; + hashes[2] = `${Math.round(c2.x * precision)},${Math.round(c2.y * precision)},${Math.round(c2.z * precision)}`; + if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) { + continue; + } + for (let j2 = 0;j2 < 3; j2++) { + const jNext = (j2 + 1) % 3; + const vecHash0 = hashes[j2]; + const vecHash1 = hashes[jNext]; + const v0 = _triangle3[vertKeys[j2]]; + const v12 = _triangle3[vertKeys[jNext]]; + const hash = `${vecHash0}_${vecHash1}`; + const reverseHash = `${vecHash1}_${vecHash0}`; + if (reverseHash in edgeData && edgeData[reverseHash]) { + if (_normal2.dot(edgeData[reverseHash].normal) <= thresholdDot) { + vertices.push(v0.x, v0.y, v0.z); + vertices.push(v12.x, v12.y, v12.z); + } + edgeData[reverseHash] = null; + } else if (!(hash in edgeData)) { + edgeData[hash] = { + index0: indexArr[j2], + index1: indexArr[jNext], + normal: _normal2.clone() + }; + } + } + } + for (const key2 in edgeData) { + if (edgeData[key2]) { + const { index0, index1 } = edgeData[key2]; + _v0$12.fromBufferAttribute(positionAttr, index0); + _v1$12.fromBufferAttribute(positionAttr, index1); + vertices.push(_v0$12.x, _v0$12.y, _v0$12.z); + vertices.push(_v1$12.x, _v1$12.y, _v1$12.z); + } + } + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + } + + class Shape2 extends Path3 { + constructor(points) { + super(points); + this.uuid = generateUUID2(); + this.type = "Shape"; + this.holes = []; + } + getPointsHoles(divisions) { + const holesPts = []; + for (let i = 0, l2 = this.holes.length;i < l2; i++) { + holesPts[i] = this.holes[i].getPoints(divisions); + } + return holesPts; + } + extractPoints(divisions) { + return { + shape: this.getPoints(divisions), + holes: this.getPointsHoles(divisions) + }; + } + copy(source) { + super.copy(source); + this.holes = []; + for (let i = 0, l2 = source.holes.length;i < l2; i++) { + const hole = source.holes[i]; + this.holes.push(hole.clone()); + } + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.uuid = this.uuid; + data2.holes = []; + for (let i = 0, l2 = this.holes.length;i < l2; i++) { + const hole = this.holes[i]; + data2.holes.push(hole.toJSON()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.uuid = json.uuid; + this.holes = []; + for (let i = 0, l2 = json.holes.length;i < l2; i++) { + const hole = json.holes[i]; + this.holes.push(new Path3().fromJSON(hole)); + } + return this; + } + } + var Earcut2 = { + triangulate: function(data2, holeIndices, dim = 2) { + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data2.length; + let outerNode = linkedList2(data2, 0, outerLen, dim, true); + const triangles = []; + if (!outerNode || outerNode.next === outerNode.prev) + return triangles; + let minX, minY, maxX, maxY, x2, y3, invSize; + if (hasHoles) + outerNode = eliminateHoles2(data2, holeIndices, outerNode, dim); + if (data2.length > 80 * dim) { + minX = maxX = data2[0]; + minY = maxY = data2[1]; + for (let i = dim;i < outerLen; i += dim) { + x2 = data2[i]; + y3 = data2[i + 1]; + if (x2 < minX) + minX = x2; + if (y3 < minY) + minY = y3; + if (x2 > maxX) + maxX = x2; + if (y3 > maxY) + maxY = y3; + } + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + earcutLinked2(outerNode, triangles, dim, minX, minY, invSize, 0); + return triangles; + } + }; + function linkedList2(data2, start, end, dim, clockwise) { + let i, last2; + if (clockwise === signedArea2(data2, start, end, dim) > 0) { + for (i = start;i < end; i += dim) + last2 = insertNode2(i, data2[i], data2[i + 1], last2); + } else { + for (i = end - dim;i >= start; i -= dim) + last2 = insertNode2(i, data2[i], data2[i + 1], last2); + } + if (last2 && equals3(last2, last2.next)) { + removeNode2(last2); + last2 = last2.next; + } + return last2; + } + function filterPoints2(start, end) { + if (!start) + return start; + if (!end) + end = start; + let p = start, again; + do { + again = false; + if (!p.steiner && (equals3(p, p.next) || area2(p.prev, p, p.next) === 0)) { + removeNode2(p); + p = end = p.prev; + if (p === p.next) + break; + again = true; + } else { + p = p.next; + } + } while (again || p !== end); + return end; + } + function earcutLinked2(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) + return; + if (!pass && invSize) + indexCurve2(ear, minX, minY, invSize); + let stop = ear, prev, next; + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + if (invSize ? isEarHashed2(ear, minX, minY, invSize) : isEar2(ear)) { + triangles.push(prev.i / dim | 0); + triangles.push(ear.i / dim | 0); + triangles.push(next.i / dim | 0); + removeNode2(ear); + ear = next.next; + stop = next.next; + continue; + } + ear = next; + if (ear === stop) { + if (!pass) { + earcutLinked2(filterPoints2(ear), triangles, dim, minX, minY, invSize, 1); + } else if (pass === 1) { + ear = cureLocalIntersections2(filterPoints2(ear), triangles, dim); + earcutLinked2(ear, triangles, dim, minX, minY, invSize, 2); + } else if (pass === 2) { + splitEarcut2(ear, triangles, dim, minX, minY, invSize); + } + break; + } + } + } + function isEar2(ear) { + const a2 = ear.prev, b3 = ear, c2 = ear.next; + if (area2(a2, b3, c2) >= 0) + return false; + const ax = a2.x, bx = b3.x, cx = c2.x, ay = a2.y, by = b3.y, cy = c2.y; + const x02 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + let p = c2.next; + while (p !== a2) { + if (p.x >= x02 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle2(ax, ay, bx, by, cx, cy, p.x, p.y) && area2(p.prev, p, p.next) >= 0) + return false; + p = p.next; + } + return true; + } + function isEarHashed2(ear, minX, minY, invSize) { + const a2 = ear.prev, b3 = ear, c2 = ear.next; + if (area2(a2, b3, c2) >= 0) + return false; + const ax = a2.x, bx = b3.x, cx = c2.x, ay = a2.y, by = b3.y, cy = c2.y; + const x02 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + const minZ = zOrder2(x02, y0, minX, minY, invSize), maxZ = zOrder2(x1, y1, minX, minY, invSize); + let { prevZ: p, nextZ: n2 } = ear; + while (p && p.z >= minZ && n2 && n2.z <= maxZ) { + if (p.x >= x02 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a2 && p !== c2 && pointInTriangle2(ax, ay, bx, by, cx, cy, p.x, p.y) && area2(p.prev, p, p.next) >= 0) + return false; + p = p.prevZ; + if (n2.x >= x02 && n2.x <= x1 && n2.y >= y0 && n2.y <= y1 && n2 !== a2 && n2 !== c2 && pointInTriangle2(ax, ay, bx, by, cx, cy, n2.x, n2.y) && area2(n2.prev, n2, n2.next) >= 0) + return false; + n2 = n2.nextZ; + } + while (p && p.z >= minZ) { + if (p.x >= x02 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a2 && p !== c2 && pointInTriangle2(ax, ay, bx, by, cx, cy, p.x, p.y) && area2(p.prev, p, p.next) >= 0) + return false; + p = p.prevZ; + } + while (n2 && n2.z <= maxZ) { + if (n2.x >= x02 && n2.x <= x1 && n2.y >= y0 && n2.y <= y1 && n2 !== a2 && n2 !== c2 && pointInTriangle2(ax, ay, bx, by, cx, cy, n2.x, n2.y) && area2(n2.prev, n2, n2.next) >= 0) + return false; + n2 = n2.nextZ; + } + return true; + } + function cureLocalIntersections2(start, triangles, dim) { + let p = start; + do { + const a2 = p.prev, b3 = p.next.next; + if (!equals3(a2, b3) && intersects2(a2, p, p.next, b3) && locallyInside2(a2, b3) && locallyInside2(b3, a2)) { + triangles.push(a2.i / dim | 0); + triangles.push(p.i / dim | 0); + triangles.push(b3.i / dim | 0); + removeNode2(p); + removeNode2(p.next); + p = start = b3; + } + p = p.next; + } while (p !== start); + return filterPoints2(p); + } + function splitEarcut2(start, triangles, dim, minX, minY, invSize) { + let a2 = start; + do { + let b3 = a2.next.next; + while (b3 !== a2.prev) { + if (a2.i !== b3.i && isValidDiagonal2(a2, b3)) { + let c2 = splitPolygon2(a2, b3); + a2 = filterPoints2(a2, a2.next); + c2 = filterPoints2(c2, c2.next); + earcutLinked2(a2, triangles, dim, minX, minY, invSize, 0); + earcutLinked2(c2, triangles, dim, minX, minY, invSize, 0); + return; + } + b3 = b3.next; + } + a2 = a2.next; + } while (a2 !== start); + } + function eliminateHoles2(data2, holeIndices, outerNode, dim) { + const queue = []; + let i, len, start, end, list; + for (i = 0, len = holeIndices.length;i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data2.length; + list = linkedList2(data2, start, end, dim, false); + if (list === list.next) + list.steiner = true; + queue.push(getLeftmost2(list)); + } + queue.sort(compareX2); + for (i = 0;i < queue.length; i++) { + outerNode = eliminateHole2(queue[i], outerNode); + } + return outerNode; + } + function compareX2(a2, b3) { + return a2.x - b3.x; + } + function eliminateHole2(hole, outerNode) { + const bridge = findHoleBridge2(hole, outerNode); + if (!bridge) { + return outerNode; + } + const bridgeReverse = splitPolygon2(bridge, hole); + filterPoints2(bridgeReverse, bridgeReverse.next); + return filterPoints2(bridge, bridge.next); + } + function findHoleBridge2(hole, outerNode) { + let p = outerNode, qx = -Infinity, m; + const { x: hx, y: hy } = hole; + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x2 = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x2 <= hx && x2 > qx) { + qx = x2; + m = p.x < p.next.x ? p : p.next; + if (x2 === hx) + return m; + } + } + p = p.next; + } while (p !== outerNode); + if (!m) + return null; + const stop = m, mx = m.x, my = m.y; + let tanMin = Infinity, tan; + p = m; + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle2(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + tan = Math.abs(hy - p.y) / (hx - p.x); + if (locallyInside2(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector2(m, p)))) { + m = p; + tanMin = tan; + } + } + p = p.next; + } while (p !== stop); + return m; + } + function sectorContainsSector2(m, p) { + return area2(m.prev, m, p.prev) < 0 && area2(p.next, m, m.next) < 0; + } + function indexCurve2(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) + p.z = zOrder2(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + p.prevZ.nextZ = null; + p.prevZ = null; + sortLinked2(p); + } + function sortLinked2(list) { + let i, p, q2, e, tail, numMerges, pSize, qSize, inSize = 1; + do { + p = list; + list = null; + tail = null; + numMerges = 0; + while (p) { + numMerges++; + q2 = p; + pSize = 0; + for (i = 0;i < inSize; i++) { + pSize++; + q2 = q2.nextZ; + if (!q2) + break; + } + qSize = inSize; + while (pSize > 0 || qSize > 0 && q2) { + if (pSize !== 0 && (qSize === 0 || !q2 || p.z <= q2.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q2; + q2 = q2.nextZ; + qSize--; + } + if (tail) + tail.nextZ = e; + else + list = e; + e.prevZ = tail; + tail = e; + } + p = q2; + } + tail.nextZ = null; + inSize *= 2; + } while (numMerges > 1); + return list; + } + function zOrder2(x2, y3, minX, minY, invSize) { + x2 = (x2 - minX) * invSize | 0; + y3 = (y3 - minY) * invSize | 0; + x2 = (x2 | x2 << 8) & 16711935; + x2 = (x2 | x2 << 4) & 252645135; + x2 = (x2 | x2 << 2) & 858993459; + x2 = (x2 | x2 << 1) & 1431655765; + y3 = (y3 | y3 << 8) & 16711935; + y3 = (y3 | y3 << 4) & 252645135; + y3 = (y3 | y3 << 2) & 858993459; + y3 = (y3 | y3 << 1) & 1431655765; + return x2 | y3 << 1; + } + function getLeftmost2(start) { + let p = start, leftmost = start; + do { + if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) + leftmost = p; + p = p.next; + } while (p !== start); + return leftmost; + } + function pointInTriangle2(ax, ay, bx, by, cx, cy, px3, py3) { + return (cx - px3) * (ay - py3) >= (ax - px3) * (cy - py3) && (ax - px3) * (by - py3) >= (bx - px3) * (ay - py3) && (bx - px3) * (cy - py3) >= (cx - px3) * (by - py3); + } + function isValidDiagonal2(a2, b3) { + return a2.next.i !== b3.i && a2.prev.i !== b3.i && !intersectsPolygon2(a2, b3) && (locallyInside2(a2, b3) && locallyInside2(b3, a2) && middleInside2(a2, b3) && (area2(a2.prev, a2, b3.prev) || area2(a2, b3.prev, b3)) || equals3(a2, b3) && area2(a2.prev, a2, a2.next) > 0 && area2(b3.prev, b3, b3.next) > 0); + } + function area2(p, q2, r) { + return (q2.y - p.y) * (r.x - q2.x) - (q2.x - p.x) * (r.y - q2.y); + } + function equals3(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; + } + function intersects2(p1, q1, p2, q2) { + const o1 = sign2(area2(p1, q1, p2)); + const o2 = sign2(area2(p1, q1, q2)); + const o32 = sign2(area2(p2, q2, p1)); + const o4 = sign2(area2(p2, q2, q1)); + if (o1 !== o2 && o32 !== o4) + return true; + if (o1 === 0 && onSegment2(p1, p2, q1)) + return true; + if (o2 === 0 && onSegment2(p1, q2, q1)) + return true; + if (o32 === 0 && onSegment2(p2, p1, q2)) + return true; + if (o4 === 0 && onSegment2(p2, q1, q2)) + return true; + return false; + } + function onSegment2(p, q2, r) { + return q2.x <= Math.max(p.x, r.x) && q2.x >= Math.min(p.x, r.x) && q2.y <= Math.max(p.y, r.y) && q2.y >= Math.min(p.y, r.y); + } + function sign2(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; + } + function intersectsPolygon2(a2, b3) { + let p = a2; + do { + if (p.i !== a2.i && p.next.i !== a2.i && p.i !== b3.i && p.next.i !== b3.i && intersects2(p, p.next, a2, b3)) + return true; + p = p.next; + } while (p !== a2); + return false; + } + function locallyInside2(a2, b3) { + return area2(a2.prev, a2, a2.next) < 0 ? area2(a2, b3, a2.next) >= 0 && area2(a2, a2.prev, b3) >= 0 : area2(a2, b3, a2.prev) < 0 || area2(a2, a2.next, b3) < 0; + } + function middleInside2(a2, b3) { + let p = a2, inside = false; + const px3 = (a2.x + b3.x) / 2, py3 = (a2.y + b3.y) / 2; + do { + if (p.y > py3 !== p.next.y > py3 && p.next.y !== p.y && px3 < (p.next.x - p.x) * (py3 - p.y) / (p.next.y - p.y) + p.x) + inside = !inside; + p = p.next; + } while (p !== a2); + return inside; + } + function splitPolygon2(a2, b3) { + const a22 = new Node3(a2.i, a2.x, a2.y), b22 = new Node3(b3.i, b3.x, b3.y), an = a2.next, bp = b3.prev; + a2.next = b3; + b3.prev = a2; + a22.next = an; + an.prev = a22; + b22.next = a22; + a22.prev = b22; + bp.next = b22; + b22.prev = bp; + return b22; + } + function insertNode2(i, x2, y3, last2) { + const p = new Node3(i, x2, y3); + if (!last2) { + p.prev = p; + p.next = p; + } else { + p.next = last2.next; + p.prev = last2; + last2.next.prev = p; + last2.next = p; + } + return p; + } + function removeNode2(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + if (p.prevZ) + p.prevZ.nextZ = p.nextZ; + if (p.nextZ) + p.nextZ.prevZ = p.prevZ; + } + function Node3(i, x2, y3) { + this.i = i; + this.x = x2; + this.y = y3; + this.prev = null; + this.next = null; + this.z = 0; + this.prevZ = null; + this.nextZ = null; + this.steiner = false; + } + function signedArea2(data2, start, end, dim) { + let sum2 = 0; + for (let i = start, j2 = end - dim;i < end; i += dim) { + sum2 += (data2[j2] - data2[i]) * (data2[i + 1] + data2[j2 + 1]); + j2 = i; + } + return sum2; + } + + class ShapeUtils2 { + static area(contour) { + const n2 = contour.length; + let a2 = 0; + for (let p = n2 - 1, q2 = 0;q2 < n2; p = q2++) { + a2 += contour[p].x * contour[q2].y - contour[q2].x * contour[p].y; + } + return a2 * 0.5; + } + static isClockWise(pts) { + return ShapeUtils2.area(pts) < 0; + } + static triangulateShape(contour, holes) { + const vertices = []; + const holeIndices = []; + const faces = []; + removeDupEndPts2(contour); + addContour2(vertices, contour); + let holeIndex = contour.length; + holes.forEach(removeDupEndPts2); + for (let i = 0;i < holes.length; i++) { + holeIndices.push(holeIndex); + holeIndex += holes[i].length; + addContour2(vertices, holes[i]); + } + const triangles = Earcut2.triangulate(vertices, holeIndices); + for (let i = 0;i < triangles.length; i += 3) { + faces.push(triangles.slice(i, i + 3)); + } + return faces; + } + } + function removeDupEndPts2(points) { + const l2 = points.length; + if (l2 > 2 && points[l2 - 1].equals(points[0])) { + points.pop(); + } + } + function addContour2(vertices, contour) { + for (let i = 0;i < contour.length; i++) { + vertices.push(contour[i].x); + vertices.push(contour[i].y); + } + } + + class ExtrudeGeometry2 extends BufferGeometry2 { + constructor(shapes = new Shape2([new Vector22(0.5, 0.5), new Vector22(-0.5, 0.5), new Vector22(-0.5, -0.5), new Vector22(0.5, -0.5)]), options = {}) { + super(); + this.type = "ExtrudeGeometry"; + this.parameters = { + shapes, + options + }; + shapes = Array.isArray(shapes) ? shapes : [shapes]; + const scope = this; + const verticesArray = []; + const uvArray = []; + for (let i = 0, l2 = shapes.length;i < l2; i++) { + const shape = shapes[i]; + addShape(shape); + } + this.setAttribute("position", new Float32BufferAttribute2(verticesArray, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvArray, 2)); + this.computeVertexNormals(); + function addShape(shape) { + const placeholder = []; + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + const extrudePath = options.extrudePath; + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator2; + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + if (extrudePath) { + extrudePts = extrudePath.getSpacedPoints(steps); + extrudeByPath = true; + bevelEnabled = false; + splineTube = extrudePath.computeFrenetFrames(steps, false); + binormal = new Vector32; + normal = new Vector32; + position2 = new Vector32; + } + if (!bevelEnabled) { + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + } + const shapePoints = shape.extractPoints(curveSegments); + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + const reverse = !ShapeUtils2.isClockWise(vertices); + if (reverse) { + vertices = vertices.reverse(); + for (let h = 0, hl3 = holes.length;h < hl3; h++) { + const ahole = holes[h]; + if (ShapeUtils2.isClockWise(ahole)) { + holes[h] = ahole.reverse(); + } + } + } + const faces = ShapeUtils2.triangulateShape(vertices, holes); + const contour = vertices; + for (let h = 0, hl3 = holes.length;h < hl3; h++) { + const ahole = holes[h]; + vertices = vertices.concat(ahole); + } + function scalePt2(pt, vec, size2) { + if (!vec) + console.error("THREE.ExtrudeGeometry: vec does not exist"); + return pt.clone().addScaledVector(vec, size2); + } + const vlen = vertices.length, flen = faces.length; + function getBevelVec(inPt, inPrev, inNext) { + let v_trans_x, v_trans_y, shrink_by; + const v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; + const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; + const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x; + if (Math.abs(collinear0) > Number.EPSILON) { + const v_prev_len = Math.sqrt(v_prev_lensq); + const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); + const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len; + const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len; + const ptNextShift_x = inNext.x - v_next_y / v_next_len; + const ptNextShift_y = inNext.y + v_next_x / v_next_len; + const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); + v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x; + v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; + const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y; + if (v_trans_lensq <= 2) { + return new Vector22(v_trans_x, v_trans_y); + } else { + shrink_by = Math.sqrt(v_trans_lensq / 2); + } + } else { + let direction_eq = false; + if (v_prev_x > Number.EPSILON) { + if (v_next_x > Number.EPSILON) { + direction_eq = true; + } + } else { + if (v_prev_x < -Number.EPSILON) { + if (v_next_x < -Number.EPSILON) { + direction_eq = true; + } + } else { + if (Math.sign(v_prev_y) === Math.sign(v_next_y)) { + direction_eq = true; + } + } + } + if (direction_eq) { + v_trans_x = -v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt(v_prev_lensq); + } else { + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt(v_prev_lensq / 2); + } + } + return new Vector22(v_trans_x / shrink_by, v_trans_y / shrink_by); + } + const contourMovements = []; + for (let i = 0, il = contour.length, j2 = il - 1, k4 = i + 1;i < il; i++, j2++, k4++) { + if (j2 === il) + j2 = 0; + if (k4 === il) + k4 = 0; + contourMovements[i] = getBevelVec(contour[i], contour[j2], contour[k4]); + } + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + for (let h = 0, hl3 = holes.length;h < hl3; h++) { + const ahole = holes[h]; + oneHoleMovements = []; + for (let i = 0, il = ahole.length, j2 = il - 1, k4 = i + 1;i < il; i++, j2++, k4++) { + if (j2 === il) + j2 = 0; + if (k4 === il) + k4 = 0; + oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j2], ahole[k4]); + } + holesMovements.push(oneHoleMovements); + verticesMovements = verticesMovements.concat(oneHoleMovements); + } + for (let b3 = 0;b3 < bevelSegments; b3++) { + const t4 = b3 / bevelSegments; + const z2 = bevelThickness * Math.cos(t4 * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t4 * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length;i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, -z2); + } + for (let h = 0, hl3 = holes.length;h < hl3; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length;i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + v(vert.x, vert.y, -z2); + } + } + } + const bs = bevelSize + bevelOffset; + for (let i = 0;i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, 0); + } else { + normal.copy(splineTube.normals[0]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y); + position2.copy(extrudePts[0]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + for (let s = 1;s <= steps; s++) { + for (let i = 0;i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, depth / steps * s); + } else { + normal.copy(splineTube.normals[s]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y); + position2.copy(extrudePts[s]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + } + for (let b3 = bevelSegments - 1;b3 >= 0; b3--) { + const t4 = b3 / bevelSegments; + const z2 = bevelThickness * Math.cos(t4 * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t4 * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length;i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, depth + z2); + } + for (let h = 0, hl3 = holes.length;h < hl3; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length;i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + if (!extrudeByPath) { + v(vert.x, vert.y, depth + z2); + } else { + v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z2); + } + } + } + } + buildLidFaces(); + buildSideFaces(); + function buildLidFaces() { + const start = verticesArray.length / 3; + if (bevelEnabled) { + let layer = 0; + let offset = vlen * layer; + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[2] + offset, face[1] + offset, face[0] + offset); + } + layer = steps + bevelSegments * 2; + offset = vlen * layer; + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[0] + offset, face[1] + offset, face[2] + offset); + } + } else { + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[2], face[1], face[0]); + } + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps); + } + } + scope.addGroup(start, verticesArray.length / 3 - start, 0); + } + function buildSideFaces() { + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls(contour, layeroffset); + layeroffset += contour.length; + for (let h = 0, hl3 = holes.length;h < hl3; h++) { + const ahole = holes[h]; + sidewalls(ahole, layeroffset); + layeroffset += ahole.length; + } + scope.addGroup(start, verticesArray.length / 3 - start, 1); + } + function sidewalls(contour2, layeroffset) { + let i = contour2.length; + while (--i >= 0) { + const j2 = i; + let k4 = i - 1; + if (k4 < 0) + k4 = contour2.length - 1; + for (let s = 0, sl = steps + bevelSegments * 2;s < sl; s++) { + const slen1 = vlen * s; + const slen2 = vlen * (s + 1); + const a2 = layeroffset + j2 + slen1, b3 = layeroffset + k4 + slen1, c2 = layeroffset + k4 + slen2, d = layeroffset + j2 + slen2; + f4(a2, b3, c2, d); + } + } + } + function v(x2, y3, z2) { + placeholder.push(x2); + placeholder.push(y3); + placeholder.push(z2); + } + function f3(a2, b3, c2) { + addVertex(a2); + addVertex(b3); + addVertex(c2); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[2]); + } + function f4(a2, b3, c2, d) { + addVertex(a2); + addVertex(b3); + addVertex(d); + addVertex(b3); + addVertex(c2); + addVertex(d); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[3]); + addUV(uvs[1]); + addUV(uvs[2]); + addUV(uvs[3]); + } + function addVertex(index2) { + verticesArray.push(placeholder[index2 * 3 + 0]); + verticesArray.push(placeholder[index2 * 3 + 1]); + verticesArray.push(placeholder[index2 * 3 + 2]); + } + function addUV(vector2) { + uvArray.push(vector2.x); + uvArray.push(vector2.y); + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + const shapes = this.parameters.shapes; + const options = this.parameters.options; + return toJSON$12(shapes, options, data2); + } + static fromJSON(data2, shapes) { + const geometryShapes = []; + for (let j2 = 0, jl = data2.shapes.length;j2 < jl; j2++) { + const shape = shapes[data2.shapes[j2]]; + geometryShapes.push(shape); + } + const extrudePath = data2.options.extrudePath; + if (extrudePath !== undefined) { + data2.options.extrudePath = new Curves2[extrudePath.type]().fromJSON(extrudePath); + } + return new ExtrudeGeometry2(geometryShapes, data2.options); + } + } + var WorldUVGenerator2 = { + generateTopUV: function(geometry, vertices, indexA, indexB, indexC) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + return [ + new Vector22(a_x, a_y), + new Vector22(b_x, b_y), + new Vector22(c_x, c_y) + ]; + }, + generateSideWallUV: function(geometry, vertices, indexA, indexB, indexC, indexD) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const a_z = vertices[indexA * 3 + 2]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const b_z = vertices[indexB * 3 + 2]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + const c_z = vertices[indexC * 3 + 2]; + const d_x = vertices[indexD * 3]; + const d_y = vertices[indexD * 3 + 1]; + const d_z = vertices[indexD * 3 + 2]; + if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) { + return [ + new Vector22(a_x, 1 - a_z), + new Vector22(b_x, 1 - b_z), + new Vector22(c_x, 1 - c_z), + new Vector22(d_x, 1 - d_z) + ]; + } else { + return [ + new Vector22(a_y, 1 - a_z), + new Vector22(b_y, 1 - b_z), + new Vector22(c_y, 1 - c_z), + new Vector22(d_y, 1 - d_z) + ]; + } + } + }; + function toJSON$12(shapes, options, data2) { + data2.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l2 = shapes.length;i < l2; i++) { + const shape = shapes[i]; + data2.shapes.push(shape.uuid); + } + } else { + data2.shapes.push(shapes.uuid); + } + data2.options = Object.assign({}, options); + if (options.extrudePath !== undefined) + data2.options.extrudePath = options.extrudePath.toJSON(); + return data2; + } + + class IcosahedronGeometry2 extends PolyhedronGeometry2 { + constructor(radius = 1, detail = 0) { + const t4 = (1 + Math.sqrt(5)) / 2; + const vertices = [ + -1, + t4, + 0, + 1, + t4, + 0, + -1, + -t4, + 0, + 1, + -t4, + 0, + 0, + -1, + t4, + 0, + 1, + t4, + 0, + -1, + -t4, + 0, + 1, + -t4, + t4, + 0, + -1, + t4, + 0, + 1, + -t4, + 0, + -1, + -t4, + 0, + 1 + ]; + const indices = [ + 0, + 11, + 5, + 0, + 5, + 1, + 0, + 1, + 7, + 0, + 7, + 10, + 0, + 10, + 11, + 1, + 5, + 9, + 5, + 11, + 4, + 11, + 10, + 2, + 10, + 7, + 6, + 7, + 1, + 8, + 3, + 9, + 4, + 3, + 4, + 2, + 3, + 2, + 6, + 3, + 6, + 8, + 3, + 8, + 9, + 4, + 9, + 5, + 2, + 4, + 11, + 6, + 2, + 10, + 8, + 6, + 7, + 9, + 8, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "IcosahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new IcosahedronGeometry2(data2.radius, data2.detail); + } + } + + class OctahedronGeometry2 extends PolyhedronGeometry2 { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1 + ]; + const indices = [ + 0, + 2, + 4, + 0, + 4, + 3, + 0, + 3, + 5, + 0, + 5, + 2, + 1, + 2, + 5, + 1, + 5, + 3, + 1, + 3, + 4, + 1, + 4, + 2 + ]; + super(vertices, indices, radius, detail); + this.type = "OctahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new OctahedronGeometry2(data2.radius, data2.detail); + } + } + + class PlaneGeometry3 extends BufferGeometry2 { + constructor(width2 = 1, height2 = 1, widthSegments = 1, heightSegments = 1) { + super(); + this.type = "PlaneGeometry"; + this.parameters = { + width: width2, + height: height2, + widthSegments, + heightSegments + }; + const width_half = width2 / 2; + const height_half = height2 / 2; + const gridX = Math.floor(widthSegments); + const gridY = Math.floor(heightSegments); + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + const segment_width = width2 / gridX; + const segment_height = height2 / gridY; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0;iy < gridY1; iy++) { + const y3 = iy * segment_height - height_half; + for (let ix = 0;ix < gridX1; ix++) { + const x2 = ix * segment_width - width_half; + vertices.push(x2, -y3, 0); + normals.push(0, 0, 1); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + } + } + for (let iy = 0;iy < gridY; iy++) { + for (let ix = 0;ix < gridX; ix++) { + const a2 = ix + gridX1 * iy; + const b3 = ix + gridX1 * (iy + 1); + const c2 = ix + 1 + gridX1 * (iy + 1); + const d = ix + 1 + gridX1 * iy; + indices.push(a2, b3, d); + indices.push(b3, c2, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new PlaneGeometry3(data2.width, data2.height, data2.widthSegments, data2.heightSegments); + } + } + + class RingGeometry2 extends BufferGeometry2 { + constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "RingGeometry"; + this.parameters = { + innerRadius, + outerRadius, + thetaSegments, + phiSegments, + thetaStart, + thetaLength + }; + thetaSegments = Math.max(3, thetaSegments); + phiSegments = Math.max(1, phiSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let radius = innerRadius; + const radiusStep = (outerRadius - innerRadius) / phiSegments; + const vertex3 = new Vector32; + const uv = new Vector22; + for (let j2 = 0;j2 <= phiSegments; j2++) { + for (let i = 0;i <= thetaSegments; i++) { + const segment = thetaStart + i / thetaSegments * thetaLength; + vertex3.x = radius * Math.cos(segment); + vertex3.y = radius * Math.sin(segment); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normals.push(0, 0, 1); + uv.x = (vertex3.x / outerRadius + 1) / 2; + uv.y = (vertex3.y / outerRadius + 1) / 2; + uvs.push(uv.x, uv.y); + } + radius += radiusStep; + } + for (let j2 = 0;j2 < phiSegments; j2++) { + const thetaSegmentLevel = j2 * (thetaSegments + 1); + for (let i = 0;i < thetaSegments; i++) { + const segment = i + thetaSegmentLevel; + const a2 = segment; + const b3 = segment + thetaSegments + 1; + const c2 = segment + thetaSegments + 2; + const d = segment + 1; + indices.push(a2, b3, d); + indices.push(b3, c2, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new RingGeometry2(data2.innerRadius, data2.outerRadius, data2.thetaSegments, data2.phiSegments, data2.thetaStart, data2.thetaLength); + } + } + + class ShapeGeometry2 extends BufferGeometry2 { + constructor(shapes = new Shape2([new Vector22(0, 0.5), new Vector22(-0.5, -0.5), new Vector22(0.5, -0.5)]), curveSegments = 12) { + super(); + this.type = "ShapeGeometry"; + this.parameters = { + shapes, + curveSegments + }; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let groupStart = 0; + let groupCount = 0; + if (Array.isArray(shapes) === false) { + addShape(shapes); + } else { + for (let i = 0;i < shapes.length; i++) { + addShape(shapes[i]); + this.addGroup(groupStart, groupCount, i); + groupStart += groupCount; + groupCount = 0; + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function addShape(shape) { + const indexOffset = vertices.length / 3; + const points = shape.extractPoints(curveSegments); + let shapeVertices = points.shape; + const shapeHoles = points.holes; + if (ShapeUtils2.isClockWise(shapeVertices) === false) { + shapeVertices = shapeVertices.reverse(); + } + for (let i = 0, l2 = shapeHoles.length;i < l2; i++) { + const shapeHole = shapeHoles[i]; + if (ShapeUtils2.isClockWise(shapeHole) === true) { + shapeHoles[i] = shapeHole.reverse(); + } + } + const faces = ShapeUtils2.triangulateShape(shapeVertices, shapeHoles); + for (let i = 0, l2 = shapeHoles.length;i < l2; i++) { + const shapeHole = shapeHoles[i]; + shapeVertices = shapeVertices.concat(shapeHole); + } + for (let i = 0, l2 = shapeVertices.length;i < l2; i++) { + const vertex3 = shapeVertices[i]; + vertices.push(vertex3.x, vertex3.y, 0); + normals.push(0, 0, 1); + uvs.push(vertex3.x, vertex3.y); + } + for (let i = 0, l2 = faces.length;i < l2; i++) { + const face = faces[i]; + const a2 = face[0] + indexOffset; + const b3 = face[1] + indexOffset; + const c2 = face[2] + indexOffset; + indices.push(a2, b3, c2); + groupCount += 3; + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + const shapes = this.parameters.shapes; + return toJSON2(shapes, data2); + } + static fromJSON(data2, shapes) { + const geometryShapes = []; + for (let j2 = 0, jl = data2.shapes.length;j2 < jl; j2++) { + const shape = shapes[data2.shapes[j2]]; + geometryShapes.push(shape); + } + return new ShapeGeometry2(geometryShapes, data2.curveSegments); + } + } + function toJSON2(shapes, data2) { + data2.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l2 = shapes.length;i < l2; i++) { + const shape = shapes[i]; + data2.shapes.push(shape.uuid); + } + } else { + data2.shapes.push(shapes.uuid); + } + return data2; + } + + class SphereGeometry3 extends BufferGeometry2 { + constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) { + super(); + this.type = "SphereGeometry"; + this.parameters = { + radius, + widthSegments, + heightSegments, + phiStart, + phiLength, + thetaStart, + thetaLength + }; + widthSegments = Math.max(3, Math.floor(widthSegments)); + heightSegments = Math.max(2, Math.floor(heightSegments)); + const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI); + let index2 = 0; + const grid = []; + const vertex3 = new Vector32; + const normal = new Vector32; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0;iy <= heightSegments; iy++) { + const verticesRow = []; + const v = iy / heightSegments; + let uOffset = 0; + if (iy === 0 && thetaStart === 0) { + uOffset = 0.5 / widthSegments; + } else if (iy === heightSegments && thetaEnd === Math.PI) { + uOffset = -0.5 / widthSegments; + } + for (let ix = 0;ix <= widthSegments; ix++) { + const u3 = ix / widthSegments; + vertex3.x = -radius * Math.cos(phiStart + u3 * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertex3.y = radius * Math.cos(thetaStart + v * thetaLength); + vertex3.z = radius * Math.sin(phiStart + u3 * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normal.copy(vertex3).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u3 + uOffset, 1 - v); + verticesRow.push(index2++); + } + grid.push(verticesRow); + } + for (let iy = 0;iy < heightSegments; iy++) { + for (let ix = 0;ix < widthSegments; ix++) { + const a2 = grid[iy][ix + 1]; + const b3 = grid[iy][ix]; + const c2 = grid[iy + 1][ix]; + const d = grid[iy + 1][ix + 1]; + if (iy !== 0 || thetaStart > 0) + indices.push(a2, b3, d); + if (iy !== heightSegments - 1 || thetaEnd < Math.PI) + indices.push(b3, c2, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new SphereGeometry3(data2.radius, data2.widthSegments, data2.heightSegments, data2.phiStart, data2.phiLength, data2.thetaStart, data2.thetaLength); + } + } + + class TetrahedronGeometry2 extends PolyhedronGeometry2 { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + -1, + 1, + -1, + -1 + ]; + const indices = [ + 2, + 1, + 0, + 0, + 3, + 2, + 1, + 3, + 0, + 2, + 3, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "TetrahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new TetrahedronGeometry2(data2.radius, data2.detail); + } + } + + class TorusGeometry2 extends BufferGeometry2 { + constructor(radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2) { + super(); + this.type = "TorusGeometry"; + this.parameters = { + radius, + tube, + radialSegments, + tubularSegments, + arc + }; + radialSegments = Math.floor(radialSegments); + tubularSegments = Math.floor(tubularSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const center = new Vector32; + const vertex3 = new Vector32; + const normal = new Vector32; + for (let j2 = 0;j2 <= radialSegments; j2++) { + for (let i = 0;i <= tubularSegments; i++) { + const u3 = i / tubularSegments * arc; + const v = j2 / radialSegments * Math.PI * 2; + vertex3.x = (radius + tube * Math.cos(v)) * Math.cos(u3); + vertex3.y = (radius + tube * Math.cos(v)) * Math.sin(u3); + vertex3.z = tube * Math.sin(v); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + center.x = radius * Math.cos(u3); + center.y = radius * Math.sin(u3); + normal.subVectors(vertex3, center).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j2 / radialSegments); + } + } + for (let j2 = 1;j2 <= radialSegments; j2++) { + for (let i = 1;i <= tubularSegments; i++) { + const a2 = (tubularSegments + 1) * j2 + i - 1; + const b3 = (tubularSegments + 1) * (j2 - 1) + i - 1; + const c2 = (tubularSegments + 1) * (j2 - 1) + i; + const d = (tubularSegments + 1) * j2 + i; + indices.push(a2, b3, d); + indices.push(b3, c2, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new TorusGeometry2(data2.radius, data2.tube, data2.radialSegments, data2.tubularSegments, data2.arc); + } + } + + class TorusKnotGeometry3 extends BufferGeometry2 { + constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q2 = 3) { + super(); + this.type = "TorusKnotGeometry"; + this.parameters = { + radius, + tube, + tubularSegments, + radialSegments, + p, + q: q2 + }; + tubularSegments = Math.floor(tubularSegments); + radialSegments = Math.floor(radialSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex3 = new Vector32; + const normal = new Vector32; + const P1 = new Vector32; + const P2 = new Vector32; + const B3 = new Vector32; + const T3 = new Vector32; + const N = new Vector32; + for (let i = 0;i <= tubularSegments; ++i) { + const u3 = i / tubularSegments * p * Math.PI * 2; + calculatePositionOnCurve(u3, p, q2, radius, P1); + calculatePositionOnCurve(u3 + 0.01, p, q2, radius, P2); + T3.subVectors(P2, P1); + N.addVectors(P2, P1); + B3.crossVectors(T3, N); + N.crossVectors(B3, T3); + B3.normalize(); + N.normalize(); + for (let j2 = 0;j2 <= radialSegments; ++j2) { + const v = j2 / radialSegments * Math.PI * 2; + const cx = -tube * Math.cos(v); + const cy = tube * Math.sin(v); + vertex3.x = P1.x + (cx * N.x + cy * B3.x); + vertex3.y = P1.y + (cx * N.y + cy * B3.y); + vertex3.z = P1.z + (cx * N.z + cy * B3.z); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normal.subVectors(vertex3, P1).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j2 / radialSegments); + } + } + for (let j2 = 1;j2 <= tubularSegments; j2++) { + for (let i = 1;i <= radialSegments; i++) { + const a2 = (radialSegments + 1) * (j2 - 1) + (i - 1); + const b3 = (radialSegments + 1) * j2 + (i - 1); + const c2 = (radialSegments + 1) * j2 + i; + const d = (radialSegments + 1) * (j2 - 1) + i; + indices.push(a2, b3, d); + indices.push(b3, c2, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function calculatePositionOnCurve(u3, p2, q3, radius2, position2) { + const cu2 = Math.cos(u3); + const su = Math.sin(u3); + const quOverP = q3 / p2 * u3; + const cs = Math.cos(quOverP); + position2.x = radius2 * (2 + cs) * 0.5 * cu2; + position2.y = radius2 * (2 + cs) * su * 0.5; + position2.z = radius2 * Math.sin(quOverP) * 0.5; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new TorusKnotGeometry3(data2.radius, data2.tube, data2.tubularSegments, data2.radialSegments, data2.p, data2.q); + } + } + + class TubeGeometry3 extends BufferGeometry2 { + constructor(path = new QuadraticBezierCurve32(new Vector32(-1, -1, 0), new Vector32(-1, 1, 0), new Vector32(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) { + super(); + this.type = "TubeGeometry"; + this.parameters = { + path, + tubularSegments, + radius, + radialSegments, + closed + }; + const frames2 = path.computeFrenetFrames(tubularSegments, closed); + this.tangents = frames2.tangents; + this.normals = frames2.normals; + this.binormals = frames2.binormals; + const vertex3 = new Vector32; + const normal = new Vector32; + const uv = new Vector22; + let P = new Vector32; + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; + generateBufferData(); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function generateBufferData() { + for (let i = 0;i < tubularSegments; i++) { + generateSegment(i); + } + generateSegment(closed === false ? tubularSegments : 0); + generateUVs(); + generateIndices(); + } + function generateSegment(i) { + P = path.getPointAt(i / tubularSegments, P); + const N = frames2.normals[i]; + const B3 = frames2.binormals[i]; + for (let j2 = 0;j2 <= radialSegments; j2++) { + const v = j2 / radialSegments * Math.PI * 2; + const sin = Math.sin(v); + const cos = -Math.cos(v); + normal.x = cos * N.x + sin * B3.x; + normal.y = cos * N.y + sin * B3.y; + normal.z = cos * N.z + sin * B3.z; + normal.normalize(); + normals.push(normal.x, normal.y, normal.z); + vertex3.x = P.x + radius * normal.x; + vertex3.y = P.y + radius * normal.y; + vertex3.z = P.z + radius * normal.z; + vertices.push(vertex3.x, vertex3.y, vertex3.z); + } + } + function generateIndices() { + for (let j2 = 1;j2 <= tubularSegments; j2++) { + for (let i = 1;i <= radialSegments; i++) { + const a2 = (radialSegments + 1) * (j2 - 1) + (i - 1); + const b3 = (radialSegments + 1) * j2 + (i - 1); + const c2 = (radialSegments + 1) * j2 + i; + const d = (radialSegments + 1) * (j2 - 1) + i; + indices.push(a2, b3, d); + indices.push(b3, c2, d); + } + } + } + function generateUVs() { + for (let i = 0;i <= tubularSegments; i++) { + for (let j2 = 0;j2 <= radialSegments; j2++) { + uv.x = i / tubularSegments; + uv.y = j2 / radialSegments; + uvs.push(uv.x, uv.y); + } + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.path = this.parameters.path.toJSON(); + return data2; + } + static fromJSON(data2) { + return new TubeGeometry3(new Curves2[data2.path.type]().fromJSON(data2.path), data2.tubularSegments, data2.radius, data2.radialSegments, data2.closed); + } + } + + class WireframeGeometry3 extends BufferGeometry2 { + constructor(geometry = null) { + super(); + this.type = "WireframeGeometry"; + this.parameters = { + geometry + }; + if (geometry !== null) { + const vertices = []; + const edges = new Set; + const start = new Vector32; + const end = new Vector32; + if (geometry.index !== null) { + const position2 = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; + if (groups.length === 0) { + groups = [{ start: 0, count: indices.count, materialIndex: 0 }]; + } + for (let o = 0, ol2 = groups.length;o < ol2; ++o) { + const group = groups[o]; + const groupStart = group.start; + const groupCount = group.count; + for (let i = groupStart, l2 = groupStart + groupCount;i < l2; i += 3) { + for (let j2 = 0;j2 < 3; j2++) { + const index1 = indices.getX(i + j2); + const index2 = indices.getX(i + (j2 + 1) % 3); + start.fromBufferAttribute(position2, index1); + end.fromBufferAttribute(position2, index2); + if (isUniqueEdge2(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + } else { + const position2 = geometry.attributes.position; + for (let i = 0, l2 = position2.count / 3;i < l2; i++) { + for (let j2 = 0;j2 < 3; j2++) { + const index1 = 3 * i + j2; + const index2 = 3 * i + (j2 + 1) % 3; + start.fromBufferAttribute(position2, index1); + end.fromBufferAttribute(position2, index2); + if (isUniqueEdge2(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + } + function isUniqueEdge2(start, end, edges) { + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; + if (edges.has(hash1) === true || edges.has(hash2) === true) { + return false; + } else { + edges.add(hash1); + edges.add(hash2); + return true; + } + } + var Geometries2 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + BoxGeometry: BoxGeometry2, + CapsuleGeometry: CapsuleGeometry2, + CircleGeometry: CircleGeometry2, + ConeGeometry: ConeGeometry2, + CylinderGeometry: CylinderGeometry2, + DodecahedronGeometry: DodecahedronGeometry2, + EdgesGeometry: EdgesGeometry2, + ExtrudeGeometry: ExtrudeGeometry2, + IcosahedronGeometry: IcosahedronGeometry2, + LatheGeometry: LatheGeometry2, + OctahedronGeometry: OctahedronGeometry2, + PlaneGeometry: PlaneGeometry3, + PolyhedronGeometry: PolyhedronGeometry2, + RingGeometry: RingGeometry2, + ShapeGeometry: ShapeGeometry2, + SphereGeometry: SphereGeometry3, + TetrahedronGeometry: TetrahedronGeometry2, + TorusGeometry: TorusGeometry2, + TorusKnotGeometry: TorusKnotGeometry3, + TubeGeometry: TubeGeometry3, + WireframeGeometry: WireframeGeometry3 + }); + + class ShadowMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isShadowMaterial = true; + this.type = "ShadowMaterial"; + this.color = new Color2(0); + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.fog = source.fog; + return this; + } + } + + class RawShaderMaterial2 extends ShaderMaterial2 { + constructor(parameters) { + super(parameters); + this.isRawShaderMaterial = true; + this.type = "RawShaderMaterial"; + } + } + + class MeshStandardMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshStandardMaterial = true; + this.type = "MeshStandardMaterial"; + this.defines = { STANDARD: "" }; + this.color = new Color2(16777215); + this.roughness = 1; + this.metalness = 0; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color2(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.roughnessMap = null; + this.metalnessMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler2; + this.envMapIntensity = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { STANDARD: "" }; + this.color.copy(source.color); + this.roughness = source.roughness; + this.metalness = source.metalness; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.roughnessMap = source.roughnessMap; + this.metalnessMap = source.metalnessMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.envMapIntensity = source.envMapIntensity; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + + class MeshPhysicalMaterial2 extends MeshStandardMaterial2 { + constructor(parameters) { + super(); + this.isMeshPhysicalMaterial = true; + this.defines = { + STANDARD: "", + PHYSICAL: "" + }; + this.type = "MeshPhysicalMaterial"; + this.anisotropyRotation = 0; + this.anisotropyMap = null; + this.clearcoatMap = null; + this.clearcoatRoughness = 0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector22(1, 1); + this.clearcoatNormalMap = null; + this.ior = 1.5; + Object.defineProperty(this, "reflectivity", { + get: function() { + return clamp3(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1); + }, + set: function(reflectivity) { + this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity); + } + }); + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [100, 400]; + this.iridescenceThicknessMap = null; + this.sheenColor = new Color2(0); + this.sheenColorMap = null; + this.sheenRoughness = 1; + this.sheenRoughnessMap = null; + this.transmissionMap = null; + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = Infinity; + this.attenuationColor = new Color2(1, 1, 1); + this.specularIntensity = 1; + this.specularIntensityMap = null; + this.specularColor = new Color2(1, 1, 1); + this.specularColorMap = null; + this._anisotropy = 0; + this._clearcoat = 0; + this._dispersion = 0; + this._iridescence = 0; + this._sheen = 0; + this._transmission = 0; + this.setValues(parameters); + } + get anisotropy() { + return this._anisotropy; + } + set anisotropy(value2) { + if (this._anisotropy > 0 !== value2 > 0) { + this.version++; + } + this._anisotropy = value2; + } + get clearcoat() { + return this._clearcoat; + } + set clearcoat(value2) { + if (this._clearcoat > 0 !== value2 > 0) { + this.version++; + } + this._clearcoat = value2; + } + get iridescence() { + return this._iridescence; + } + set iridescence(value2) { + if (this._iridescence > 0 !== value2 > 0) { + this.version++; + } + this._iridescence = value2; + } + get dispersion() { + return this._dispersion; + } + set dispersion(value2) { + if (this._dispersion > 0 !== value2 > 0) { + this.version++; + } + this._dispersion = value2; + } + get sheen() { + return this._sheen; + } + set sheen(value2) { + if (this._sheen > 0 !== value2 > 0) { + this.version++; + } + this._sheen = value2; + } + get transmission() { + return this._transmission; + } + set transmission(value2) { + if (this._transmission > 0 !== value2 > 0) { + this.version++; + } + this._transmission = value2; + } + copy(source) { + super.copy(source); + this.defines = { + STANDARD: "", + PHYSICAL: "" + }; + this.anisotropy = source.anisotropy; + this.anisotropyRotation = source.anisotropyRotation; + this.anisotropyMap = source.anisotropyMap; + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy(source.clearcoatNormalScale); + this.dispersion = source.dispersion; + this.ior = source.ior; + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [...source.iridescenceThicknessRange]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + this.sheen = source.sheen; + this.sheenColor.copy(source.sheenColor); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy(source.attenuationColor); + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy(source.specularColor); + this.specularColorMap = source.specularColorMap; + return this; + } + } + + class MeshPhongMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshPhongMaterial = true; + this.type = "MeshPhongMaterial"; + this.color = new Color2(16777215); + this.specular = new Color2(1118481); + this.shininess = 30; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color2(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler2; + this.combine = MultiplyOperation2; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.specular.copy(source.specular); + this.shininess = source.shininess; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + + class MeshToonMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshToonMaterial = true; + this.defines = { TOON: "" }; + this.type = "MeshToonMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.gradientMap = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color2(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.gradientMap = source.gradientMap; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } + } + + class MeshNormalMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshNormalMaterial = true; + this.type = "MeshNormalMaterial"; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.flatShading = false; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.flatShading = source.flatShading; + return this; + } + } + + class MeshLambertMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshLambertMaterial = true; + this.type = "MeshLambertMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color2(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler2; + this.combine = MultiplyOperation2; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + + class MeshDepthMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshDepthMaterial = true; + this.type = "MeshDepthMaterial"; + this.depthPacking = BasicDepthPacking2; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.depthPacking = source.depthPacking; + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + return this; + } + } + + class MeshDistanceMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshDistanceMaterial = true; + this.type = "MeshDistanceMaterial"; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + return this; + } + } + + class MeshMatcapMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshMatcapMaterial = true; + this.defines = { MATCAP: "" }; + this.type = "MeshMatcapMaterial"; + this.color = new Color2(16777215); + this.matcap = null; + this.map = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { MATCAP: "" }; + this.color.copy(source.color); + this.matcap = source.matcap; + this.map = source.map; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + + class LineDashedMaterial2 extends LineBasicMaterial2 { + constructor(parameters) { + super(); + this.isLineDashedMaterial = true; + this.type = "LineDashedMaterial"; + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + return this; + } + } + function convertArray2(array, type, forceClone) { + if (!array || !forceClone && array.constructor === type) + return array; + if (typeof type.BYTES_PER_ELEMENT === "number") { + return new type(array); + } + return Array.prototype.slice.call(array); + } + function isTypedArray2(object) { + return ArrayBuffer.isView(object) && !(object instanceof DataView); + } + function getKeyframeOrder2(times) { + function compareTime(i, j2) { + return times[i] - times[j2]; + } + const n2 = times.length; + const result = new Array(n2); + for (let i = 0;i !== n2; ++i) + result[i] = i; + result.sort(compareTime); + return result; + } + function sortedArray2(values2, stride, order) { + const nValues = values2.length; + const result = new values2.constructor(nValues); + for (let i = 0, dstOffset = 0;dstOffset !== nValues; ++i) { + const srcOffset = order[i] * stride; + for (let j2 = 0;j2 !== stride; ++j2) { + result[dstOffset++] = values2[srcOffset + j2]; + } + } + return result; + } + function flattenJSON2(jsonKeys, times, values2, valuePropertyName) { + let i = 1, key2 = jsonKeys[0]; + while (key2 !== undefined && key2[valuePropertyName] === undefined) { + key2 = jsonKeys[i++]; + } + if (key2 === undefined) + return; + let value2 = key2[valuePropertyName]; + if (value2 === undefined) + return; + if (Array.isArray(value2)) { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + values2.push.apply(values2, value2); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } else if (value2.toArray !== undefined) { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + value2.toArray(values2, values2.length); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } else { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + values2.push(value2); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } + } + function subclip2(sourceClip, name2, startFrame, endFrame, fps = 30) { + const clip = sourceClip.clone(); + clip.name = name2; + const tracks = []; + for (let i = 0;i < clip.tracks.length; ++i) { + const track = clip.tracks[i]; + const valueSize = track.getValueSize(); + const times = []; + const values2 = []; + for (let j2 = 0;j2 < track.times.length; ++j2) { + const frame = track.times[j2] * fps; + if (frame < startFrame || frame >= endFrame) + continue; + times.push(track.times[j2]); + for (let k4 = 0;k4 < valueSize; ++k4) { + values2.push(track.values[j2 * valueSize + k4]); + } + } + if (times.length === 0) + continue; + track.times = convertArray2(times, track.times.constructor); + track.values = convertArray2(values2, track.values.constructor); + tracks.push(track); + } + clip.tracks = tracks; + let minStartTime = Infinity; + for (let i = 0;i < clip.tracks.length; ++i) { + if (minStartTime > clip.tracks[i].times[0]) { + minStartTime = clip.tracks[i].times[0]; + } + } + for (let i = 0;i < clip.tracks.length; ++i) { + clip.tracks[i].shift(-1 * minStartTime); + } + clip.resetDuration(); + return clip; + } + function makeClipAdditive2(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) { + if (fps <= 0) + fps = 30; + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; + for (let i = 0;i < numTracks; ++i) { + const referenceTrack = referenceClip.tracks[i]; + const referenceTrackType = referenceTrack.ValueTypeName; + if (referenceTrackType === "bool" || referenceTrackType === "string") + continue; + const targetTrack = targetClip.tracks.find(function(track) { + return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType; + }); + if (targetTrack === undefined) + continue; + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); + if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + referenceOffset = referenceValueSize / 3; + } + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); + if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + targetOffset = targetValueSize / 3; + } + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; + if (referenceTime <= referenceTrack.times[0]) { + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else if (referenceTime >= referenceTrack.times[lastIndex]) { + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else { + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate(referenceTime); + referenceValue = interpolant.resultBuffer.slice(startIndex, endIndex); + } + if (referenceTrackType === "quaternion") { + const referenceQuat = new Quaternion2().fromArray(referenceValue).normalize().conjugate(); + referenceQuat.toArray(referenceValue); + } + const numTimes = targetTrack.times.length; + for (let j2 = 0;j2 < numTimes; ++j2) { + const valueStart = j2 * targetValueSize + targetOffset; + if (referenceTrackType === "quaternion") { + Quaternion2.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart); + } else { + const valueEnd = targetValueSize - targetOffset * 2; + for (let k4 = 0;k4 < valueEnd; ++k4) { + targetTrack.values[valueStart + k4] -= referenceValue[k4]; + } + } + } + } + targetClip.blendMode = AdditiveAnimationBlendMode2; + return targetClip; + } + var AnimationUtils2 = { + convertArray: convertArray2, + isTypedArray: isTypedArray2, + getKeyframeOrder: getKeyframeOrder2, + sortedArray: sortedArray2, + flattenJSON: flattenJSON2, + subclip: subclip2, + makeClipAdditive: makeClipAdditive2 + }; + + class Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; + this.settings = null; + this.DefaultSettings_ = {}; + } + evaluate(t4) { + const pp = this.parameterPositions; + let i1 = this._cachedIndex, t1 = pp[i1], t02 = pp[i1 - 1]; + validate_interval: { + seek: { + let right; + linear_scan: { + forward_scan: + if (!(t4 < t1)) { + for (let giveUpAt = i1 + 2;; ) { + if (t1 === undefined) { + if (t4 < t02) + break forward_scan; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + if (i1 === giveUpAt) + break; + t02 = t1; + t1 = pp[++i1]; + if (t4 < t1) { + break seek; + } + } + right = pp.length; + break linear_scan; + } + if (!(t4 >= t02)) { + const t1global = pp[1]; + if (t4 < t1global) { + i1 = 2; + t02 = t1global; + } + for (let giveUpAt = i1 - 2;; ) { + if (t02 === undefined) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (i1 === giveUpAt) + break; + t1 = t02; + t02 = pp[--i1 - 1]; + if (t4 >= t02) { + break seek; + } + } + right = i1; + i1 = 0; + break linear_scan; + } + break validate_interval; + } + while (i1 < right) { + const mid = i1 + right >>> 1; + if (t4 < pp[mid]) { + right = mid; + } else { + i1 = mid + 1; + } + } + t1 = pp[i1]; + t02 = pp[i1 - 1]; + if (t02 === undefined) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (t1 === undefined) { + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + } + this._cachedIndex = i1; + this.intervalChanged_(i1, t02, t1); + } + return this.interpolate_(i1, t02, t4, t1); + } + getSettings_() { + return this.settings || this.DefaultSettings_; + } + copySampleValue_(index2) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, offset = index2 * stride; + for (let i = 0;i !== stride; ++i) { + result[i] = values2[offset + i]; + } + return result; + } + interpolate_() { + throw new Error("call to abstract method"); + } + intervalChanged_() { + } + } + + class CubicInterpolant2 extends Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; + this.DefaultSettings_ = { + endingStart: ZeroCurvatureEnding2, + endingEnd: ZeroCurvatureEnding2 + }; + } + intervalChanged_(i1, t02, t1) { + const pp = this.parameterPositions; + let iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[iPrev], tNext = pp[iNext]; + if (tPrev === undefined) { + switch (this.getSettings_().endingStart) { + case ZeroSlopeEnding2: + iPrev = i1; + tPrev = 2 * t02 - t1; + break; + case WrapAroundEnding2: + iPrev = pp.length - 2; + tPrev = t02 + pp[iPrev] - pp[iPrev + 1]; + break; + default: + iPrev = i1; + tPrev = t1; + } + } + if (tNext === undefined) { + switch (this.getSettings_().endingEnd) { + case ZeroSlopeEnding2: + iNext = i1; + tNext = 2 * t1 - t02; + break; + case WrapAroundEnding2: + iNext = 1; + tNext = t1 + pp[1] - pp[0]; + break; + default: + iNext = i1 - 1; + tNext = t02; + } + } + const halfDt = (t1 - t02) * 0.5, stride = this.valueSize; + this._weightPrev = halfDt / (t02 - tPrev); + this._weightNext = halfDt / (tNext - t1); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + } + interpolate_(i1, t02, t4, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o02 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p = (t4 - t02) / (t1 - t02), pp = p * p, ppp = pp * p; + const sP = -wP * ppp + 2 * wP * pp - wP * p; + const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1; + const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; + for (let i = 0;i !== stride; ++i) { + result[i] = sP * values2[oP + i] + s0 * values2[o02 + i] + s1 * values2[o1 + i] + sN * values2[oN + i]; + } + return result; + } + } + + class LinearInterpolant2 extends Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t02, t4, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = (t4 - t02) / (t1 - t02), weight0 = 1 - weight1; + for (let i = 0;i !== stride; ++i) { + result[i] = values2[offset0 + i] * weight0 + values2[offset1 + i] * weight1; + } + return result; + } + } + + class DiscreteInterpolant2 extends Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1) { + return this.copySampleValue_(i1 - 1); + } + } + + class KeyframeTrack2 { + constructor(name2, times, values2, interpolation) { + if (name2 === undefined) + throw new Error("THREE.KeyframeTrack: track name is undefined"); + if (times === undefined || times.length === 0) + throw new Error("THREE.KeyframeTrack: no keyframes in track named " + name2); + this.name = name2; + this.times = convertArray2(times, this.TimeBufferType); + this.values = convertArray2(values2, this.ValueBufferType); + this.setInterpolation(interpolation || this.DefaultInterpolation); + } + static toJSON(track) { + const trackType = track.constructor; + let json; + if (trackType.toJSON !== this.toJSON) { + json = trackType.toJSON(track); + } else { + json = { + name: track.name, + times: convertArray2(track.times, Array), + values: convertArray2(track.values, Array) + }; + const interpolation = track.getInterpolation(); + if (interpolation !== track.DefaultInterpolation) { + json.interpolation = interpolation; + } + } + json.type = track.ValueTypeName; + return json; + } + InterpolantFactoryMethodDiscrete(result) { + return new DiscreteInterpolant2(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodLinear(result) { + return new LinearInterpolant2(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodSmooth(result) { + return new CubicInterpolant2(this.times, this.values, this.getValueSize(), result); + } + setInterpolation(interpolation) { + let factoryMethod; + switch (interpolation) { + case InterpolateDiscrete2: + factoryMethod = this.InterpolantFactoryMethodDiscrete; + break; + case InterpolateLinear2: + factoryMethod = this.InterpolantFactoryMethodLinear; + break; + case InterpolateSmooth2: + factoryMethod = this.InterpolantFactoryMethodSmooth; + break; + } + if (factoryMethod === undefined) { + const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; + if (this.createInterpolant === undefined) { + if (interpolation !== this.DefaultInterpolation) { + this.setInterpolation(this.DefaultInterpolation); + } else { + throw new Error(message); + } + } + console.warn("THREE.KeyframeTrack:", message); + return this; + } + this.createInterpolant = factoryMethod; + return this; + } + getInterpolation() { + switch (this.createInterpolant) { + case this.InterpolantFactoryMethodDiscrete: + return InterpolateDiscrete2; + case this.InterpolantFactoryMethodLinear: + return InterpolateLinear2; + case this.InterpolantFactoryMethodSmooth: + return InterpolateSmooth2; + } + } + getValueSize() { + return this.values.length / this.times.length; + } + shift(timeOffset) { + if (timeOffset !== 0) { + const times = this.times; + for (let i = 0, n2 = times.length;i !== n2; ++i) { + times[i] += timeOffset; + } + } + return this; + } + scale(timeScale) { + if (timeScale !== 1) { + const times = this.times; + for (let i = 0, n2 = times.length;i !== n2; ++i) { + times[i] *= timeScale; + } + } + return this; + } + trim(startTime, endTime) { + const times = this.times, nKeys = times.length; + let from = 0, to = nKeys - 1; + while (from !== nKeys && times[from] < startTime) { + ++from; + } + while (to !== -1 && times[to] > endTime) { + --to; + } + ++to; + if (from !== 0 || to !== nKeys) { + if (from >= to) { + to = Math.max(to, 1); + from = to - 1; + } + const stride = this.getValueSize(); + this.times = times.slice(from, to); + this.values = this.values.slice(from * stride, to * stride); + } + return this; + } + validate() { + let valid = true; + const valueSize = this.getValueSize(); + if (valueSize - Math.floor(valueSize) !== 0) { + console.error("THREE.KeyframeTrack: Invalid value size in track.", this); + valid = false; + } + const times = this.times, values2 = this.values, nKeys = times.length; + if (nKeys === 0) { + console.error("THREE.KeyframeTrack: Track is empty.", this); + valid = false; + } + let prevTime = null; + for (let i = 0;i !== nKeys; i++) { + const currTime = times[i]; + if (typeof currTime === "number" && isNaN(currTime)) { + console.error("THREE.KeyframeTrack: Time is not a valid number.", this, i, currTime); + valid = false; + break; + } + if (prevTime !== null && prevTime > currTime) { + console.error("THREE.KeyframeTrack: Out of order keys.", this, i, currTime, prevTime); + valid = false; + break; + } + prevTime = currTime; + } + if (values2 !== undefined) { + if (isTypedArray2(values2)) { + for (let i = 0, n2 = values2.length;i !== n2; ++i) { + const value2 = values2[i]; + if (isNaN(value2)) { + console.error("THREE.KeyframeTrack: Value is not a valid number.", this, i, value2); + valid = false; + break; + } + } + } + } + return valid; + } + optimize() { + const times = this.times.slice(), values2 = this.values.slice(), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth2, lastIndex = times.length - 1; + let writeIndex = 1; + for (let i = 1;i < lastIndex; ++i) { + let keep = false; + const time2 = times[i]; + const timeNext = times[i + 1]; + if (time2 !== timeNext && (i !== 1 || time2 !== times[0])) { + if (!smoothInterpolation) { + const offset = i * stride, offsetP = offset - stride, offsetN = offset + stride; + for (let j2 = 0;j2 !== stride; ++j2) { + const value2 = values2[offset + j2]; + if (value2 !== values2[offsetP + j2] || value2 !== values2[offsetN + j2]) { + keep = true; + break; + } + } + } else { + keep = true; + } + } + if (keep) { + if (i !== writeIndex) { + times[writeIndex] = times[i]; + const readOffset = i * stride, writeOffset = writeIndex * stride; + for (let j2 = 0;j2 !== stride; ++j2) { + values2[writeOffset + j2] = values2[readOffset + j2]; + } + } + ++writeIndex; + } + } + if (lastIndex > 0) { + times[writeIndex] = times[lastIndex]; + for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j2 = 0;j2 !== stride; ++j2) { + values2[writeOffset + j2] = values2[readOffset + j2]; + } + ++writeIndex; + } + if (writeIndex !== times.length) { + this.times = times.slice(0, writeIndex); + this.values = values2.slice(0, writeIndex * stride); + } else { + this.times = times; + this.values = values2; + } + return this; + } + clone() { + const times = this.times.slice(); + const values2 = this.values.slice(); + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack(this.name, times, values2); + track.createInterpolant = this.createInterpolant; + return track; + } + } + KeyframeTrack2.prototype.TimeBufferType = Float32Array; + KeyframeTrack2.prototype.ValueBufferType = Float32Array; + KeyframeTrack2.prototype.DefaultInterpolation = InterpolateLinear2; + + class BooleanKeyframeTrack2 extends KeyframeTrack2 { + constructor(name2, times, values2) { + super(name2, times, values2); + } + } + BooleanKeyframeTrack2.prototype.ValueTypeName = "bool"; + BooleanKeyframeTrack2.prototype.ValueBufferType = Array; + BooleanKeyframeTrack2.prototype.DefaultInterpolation = InterpolateDiscrete2; + BooleanKeyframeTrack2.prototype.InterpolantFactoryMethodLinear = undefined; + BooleanKeyframeTrack2.prototype.InterpolantFactoryMethodSmooth = undefined; + + class ColorKeyframeTrack2 extends KeyframeTrack2 { + } + ColorKeyframeTrack2.prototype.ValueTypeName = "color"; + + class NumberKeyframeTrack2 extends KeyframeTrack2 { + } + NumberKeyframeTrack2.prototype.ValueTypeName = "number"; + + class QuaternionLinearInterpolant2 extends Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t02, t4, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, alpha = (t4 - t02) / (t1 - t02); + let offset = i1 * stride; + for (let end = offset + stride;offset !== end; offset += 4) { + Quaternion2.slerpFlat(result, 0, values2, offset - stride, values2, offset, alpha); + } + return result; + } + } + + class QuaternionKeyframeTrack2 extends KeyframeTrack2 { + InterpolantFactoryMethodLinear(result) { + return new QuaternionLinearInterpolant2(this.times, this.values, this.getValueSize(), result); + } + } + QuaternionKeyframeTrack2.prototype.ValueTypeName = "quaternion"; + QuaternionKeyframeTrack2.prototype.InterpolantFactoryMethodSmooth = undefined; + + class StringKeyframeTrack2 extends KeyframeTrack2 { + constructor(name2, times, values2) { + super(name2, times, values2); + } + } + StringKeyframeTrack2.prototype.ValueTypeName = "string"; + StringKeyframeTrack2.prototype.ValueBufferType = Array; + StringKeyframeTrack2.prototype.DefaultInterpolation = InterpolateDiscrete2; + StringKeyframeTrack2.prototype.InterpolantFactoryMethodLinear = undefined; + StringKeyframeTrack2.prototype.InterpolantFactoryMethodSmooth = undefined; + + class VectorKeyframeTrack2 extends KeyframeTrack2 { + } + VectorKeyframeTrack2.prototype.ValueTypeName = "vector"; + + class AnimationClip2 { + constructor(name2 = "", duration = -1, tracks = [], blendMode = NormalAnimationBlendMode2) { + this.name = name2; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; + this.uuid = generateUUID2(); + if (this.duration < 0) { + this.resetDuration(); + } + } + static parse(json) { + const tracks = [], jsonTracks = json.tracks, frameTime = 1 / (json.fps || 1); + for (let i = 0, n2 = jsonTracks.length;i !== n2; ++i) { + tracks.push(parseKeyframeTrack2(jsonTracks[i]).scale(frameTime)); + } + const clip = new this(json.name, json.duration, tracks, json.blendMode); + clip.uuid = json.uuid; + return clip; + } + static toJSON(clip) { + const tracks = [], clipTracks = clip.tracks; + const json = { + name: clip.name, + duration: clip.duration, + tracks, + uuid: clip.uuid, + blendMode: clip.blendMode + }; + for (let i = 0, n2 = clipTracks.length;i !== n2; ++i) { + tracks.push(KeyframeTrack2.toJSON(clipTracks[i])); + } + return json; + } + static CreateFromMorphTargetSequence(name2, morphTargetSequence, fps, noLoop) { + const numMorphTargets = morphTargetSequence.length; + const tracks = []; + for (let i = 0;i < numMorphTargets; i++) { + let times = []; + let values2 = []; + times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets); + values2.push(0, 1, 0); + const order = getKeyframeOrder2(times); + times = sortedArray2(times, 1, order); + values2 = sortedArray2(values2, 1, order); + if (!noLoop && times[0] === 0) { + times.push(numMorphTargets); + values2.push(values2[0]); + } + tracks.push(new NumberKeyframeTrack2(".morphTargetInfluences[" + morphTargetSequence[i].name + "]", times, values2).scale(1 / fps)); + } + return new this(name2, -1, tracks); + } + static findByName(objectOrClipArray, name2) { + let clipArray = objectOrClipArray; + if (!Array.isArray(objectOrClipArray)) { + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; + } + for (let i = 0;i < clipArray.length; i++) { + if (clipArray[i].name === name2) { + return clipArray[i]; + } + } + return null; + } + static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) { + const animationToMorphTargets = {}; + const pattern = /^([\w-]*?)([\d]+)$/; + for (let i = 0, il = morphTargets.length;i < il; i++) { + const morphTarget = morphTargets[i]; + const parts = morphTarget.name.match(pattern); + if (parts && parts.length > 1) { + const name2 = parts[1]; + let animationMorphTargets = animationToMorphTargets[name2]; + if (!animationMorphTargets) { + animationToMorphTargets[name2] = animationMorphTargets = []; + } + animationMorphTargets.push(morphTarget); + } + } + const clips = []; + for (const name2 in animationToMorphTargets) { + clips.push(this.CreateFromMorphTargetSequence(name2, animationToMorphTargets[name2], fps, noLoop)); + } + return clips; + } + static parseAnimation(animation, bones) { + if (!animation) { + console.error("THREE.AnimationClip: No animation in JSONLoader data."); + return null; + } + const addNonemptyTrack = function(trackType, trackName, animationKeys, propertyName, destTracks) { + if (animationKeys.length !== 0) { + const times = []; + const values2 = []; + flattenJSON2(animationKeys, times, values2, propertyName); + if (times.length !== 0) { + destTracks.push(new trackType(trackName, times, values2)); + } + } + }; + const tracks = []; + const clipName = animation.name || "default"; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; + let duration = animation.length || -1; + const hierarchyTracks = animation.hierarchy || []; + for (let h = 0;h < hierarchyTracks.length; h++) { + const animationKeys = hierarchyTracks[h].keys; + if (!animationKeys || animationKeys.length === 0) + continue; + if (animationKeys[0].morphTargets) { + const morphTargetNames = {}; + let k4; + for (k4 = 0;k4 < animationKeys.length; k4++) { + if (animationKeys[k4].morphTargets) { + for (let m = 0;m < animationKeys[k4].morphTargets.length; m++) { + morphTargetNames[animationKeys[k4].morphTargets[m]] = -1; + } + } + } + for (const morphTargetName in morphTargetNames) { + const times = []; + const values2 = []; + for (let m = 0;m !== animationKeys[k4].morphTargets.length; ++m) { + const animationKey = animationKeys[k4]; + times.push(animationKey.time); + values2.push(animationKey.morphTarget === morphTargetName ? 1 : 0); + } + tracks.push(new NumberKeyframeTrack2(".morphTargetInfluence[" + morphTargetName + "]", times, values2)); + } + duration = morphTargetNames.length * fps; + } else { + const boneName = ".bones[" + bones[h].name + "]"; + addNonemptyTrack(VectorKeyframeTrack2, boneName + ".position", animationKeys, "pos", tracks); + addNonemptyTrack(QuaternionKeyframeTrack2, boneName + ".quaternion", animationKeys, "rot", tracks); + addNonemptyTrack(VectorKeyframeTrack2, boneName + ".scale", animationKeys, "scl", tracks); + } + } + if (tracks.length === 0) { + return null; + } + const clip = new this(clipName, duration, tracks, blendMode); + return clip; + } + resetDuration() { + const tracks = this.tracks; + let duration = 0; + for (let i = 0, n2 = tracks.length;i !== n2; ++i) { + const track = this.tracks[i]; + duration = Math.max(duration, track.times[track.times.length - 1]); + } + this.duration = duration; + return this; + } + trim() { + for (let i = 0;i < this.tracks.length; i++) { + this.tracks[i].trim(0, this.duration); + } + return this; + } + validate() { + let valid = true; + for (let i = 0;i < this.tracks.length; i++) { + valid = valid && this.tracks[i].validate(); + } + return valid; + } + optimize() { + for (let i = 0;i < this.tracks.length; i++) { + this.tracks[i].optimize(); + } + return this; + } + clone() { + const tracks = []; + for (let i = 0;i < this.tracks.length; i++) { + tracks.push(this.tracks[i].clone()); + } + return new this.constructor(this.name, this.duration, tracks, this.blendMode); + } + toJSON() { + return this.constructor.toJSON(this); + } + } + function getTrackTypeForValueTypeName2(typeName) { + switch (typeName.toLowerCase()) { + case "scalar": + case "double": + case "float": + case "number": + case "integer": + return NumberKeyframeTrack2; + case "vector": + case "vector2": + case "vector3": + case "vector4": + return VectorKeyframeTrack2; + case "color": + return ColorKeyframeTrack2; + case "quaternion": + return QuaternionKeyframeTrack2; + case "bool": + case "boolean": + return BooleanKeyframeTrack2; + case "string": + return StringKeyframeTrack2; + } + throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + typeName); + } + function parseKeyframeTrack2(json) { + if (json.type === undefined) { + throw new Error("THREE.KeyframeTrack: track type undefined, can not parse"); + } + const trackType = getTrackTypeForValueTypeName2(json.type); + if (json.times === undefined) { + const times = [], values2 = []; + flattenJSON2(json.keys, times, values2, "value"); + json.times = times; + json.values = values2; + } + if (trackType.parse !== undefined) { + return trackType.parse(json); + } else { + return new trackType(json.name, json.times, json.values, json.interpolation); + } + } + var Cache2 = { + enabled: false, + files: {}, + add: function(key2, file) { + if (this.enabled === false) + return; + this.files[key2] = file; + }, + get: function(key2) { + if (this.enabled === false) + return; + return this.files[key2]; + }, + remove: function(key2) { + delete this.files[key2]; + }, + clear: function() { + this.files = {}; + } + }; + + class LoadingManager2 { + constructor(onLoad, onProgress, onError) { + const scope = this; + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + this.itemStart = function(url) { + itemsTotal++; + if (isLoading === false) { + if (scope.onStart !== undefined) { + scope.onStart(url, itemsLoaded, itemsTotal); + } + } + isLoading = true; + }; + this.itemEnd = function(url) { + itemsLoaded++; + if (scope.onProgress !== undefined) { + scope.onProgress(url, itemsLoaded, itemsTotal); + } + if (itemsLoaded === itemsTotal) { + isLoading = false; + if (scope.onLoad !== undefined) { + scope.onLoad(); + } + } + }; + this.itemError = function(url) { + if (scope.onError !== undefined) { + scope.onError(url); + } + }; + this.resolveURL = function(url) { + if (urlModifier) { + return urlModifier(url); + } + return url; + }; + this.setURLModifier = function(transform2) { + urlModifier = transform2; + return this; + }; + this.addHandler = function(regex, loader) { + handlers.push(regex, loader); + return this; + }; + this.removeHandler = function(regex) { + const index2 = handlers.indexOf(regex); + if (index2 !== -1) { + handlers.splice(index2, 2); + } + return this; + }; + this.getHandler = function(file) { + for (let i = 0, l2 = handlers.length;i < l2; i += 2) { + const regex = handlers[i]; + const loader = handlers[i + 1]; + if (regex.global) + regex.lastIndex = 0; + if (regex.test(file)) { + return loader; + } + } + return null; + }; + } + } + var DefaultLoadingManager2 = /* @__PURE__ */ new LoadingManager2; + + class Loader2 { + constructor(manager) { + this.manager = manager !== undefined ? manager : DefaultLoadingManager2; + this.crossOrigin = "anonymous"; + this.withCredentials = false; + this.path = ""; + this.resourcePath = ""; + this.requestHeader = {}; + } + load() { + } + loadAsync(url, onProgress) { + const scope = this; + return new Promise(function(resolve, reject2) { + scope.load(url, resolve, onProgress, reject2); + }); + } + parse() { + } + setCrossOrigin(crossOrigin) { + this.crossOrigin = crossOrigin; + return this; + } + setWithCredentials(value2) { + this.withCredentials = value2; + return this; + } + setPath(path) { + this.path = path; + return this; + } + setResourcePath(resourcePath) { + this.resourcePath = resourcePath; + return this; + } + setRequestHeader(requestHeader) { + this.requestHeader = requestHeader; + return this; + } + } + Loader2.DEFAULT_MATERIAL_NAME = "__DEFAULT"; + var loading2 = {}; + + class HttpError2 extends Error { + constructor(message, response) { + super(message); + this.response = response; + } + } + + class FileLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (url === undefined) + url = ""; + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const cached = Cache2.get(url); + if (cached !== undefined) { + this.manager.itemStart(url); + setTimeout(() => { + if (onLoad) + onLoad(cached); + this.manager.itemEnd(url); + }, 0); + return cached; + } + if (loading2[url] !== undefined) { + loading2[url].push({ + onLoad, + onProgress, + onError + }); + return; + } + loading2[url] = []; + loading2[url].push({ + onLoad, + onProgress, + onError + }); + const req = new Request(url, { + headers: new Headers(this.requestHeader), + credentials: this.withCredentials ? "include" : "same-origin" + }); + const mimeType = this.mimeType; + const responseType = this.responseType; + fetch(req).then((response) => { + if (response.status === 200 || response.status === 0) { + if (response.status === 0) { + console.warn("THREE.FileLoader: HTTP Status 0 received."); + } + if (typeof ReadableStream === "undefined" || response.body === undefined || response.body.getReader === undefined) { + return response; + } + const callbacks = loading2[url]; + const reader = response.body.getReader(); + const contentLength = response.headers.get("X-File-Size") || response.headers.get("Content-Length"); + const total = contentLength ? parseInt(contentLength) : 0; + const lengthComputable = total !== 0; + let loaded = 0; + const stream = new ReadableStream({ + start(controller) { + readData(); + function readData() { + reader.read().then(({ done, value: value2 }) => { + if (done) { + controller.close(); + } else { + loaded += value2.byteLength; + const event = new ProgressEvent("progress", { lengthComputable, loaded, total }); + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onProgress) + callback.onProgress(event); + } + controller.enqueue(value2); + readData(); + } + }, (e) => { + controller.error(e); + }); + } + } + }); + return new Response(stream); + } else { + throw new HttpError2(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response); + } + }).then((response) => { + switch (responseType) { + case "arraybuffer": + return response.arrayBuffer(); + case "blob": + return response.blob(); + case "document": + return response.text().then((text2) => { + const parser = new DOMParser; + return parser.parseFromString(text2, mimeType); + }); + case "json": + return response.json(); + default: + if (mimeType === undefined) { + return response.text(); + } else { + const re = /charset="?([^;"\s]*)"?/i; + const exec2 = re.exec(mimeType); + const label = exec2 && exec2[1] ? exec2[1].toLowerCase() : undefined; + const decoder = new TextDecoder(label); + return response.arrayBuffer().then((ab) => decoder.decode(ab)); + } + } + }).then((data2) => { + Cache2.add(url, data2); + const callbacks = loading2[url]; + delete loading2[url]; + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onLoad) + callback.onLoad(data2); + } + }).catch((err) => { + const callbacks = loading2[url]; + if (callbacks === undefined) { + this.manager.itemError(url); + throw err; + } + delete loading2[url]; + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onError) + callback.onError(err); + } + this.manager.itemError(url); + }).finally(() => { + this.manager.itemEnd(url); + }); + this.manager.itemStart(url); + } + setResponseType(value2) { + this.responseType = value2; + return this; + } + setMimeType(value2) { + this.mimeType = value2; + return this; + } + } + + class AnimationLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader2(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const animations = []; + for (let i = 0;i < json.length; i++) { + const clip = AnimationClip2.parse(json[i]); + animations.push(clip); + } + return animations; + } + } + + class CompressedTextureLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const images = []; + const texture = new CompressedTexture2; + const loader = new FileLoader2(this.manager); + loader.setPath(this.path); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(scope.withCredentials); + let loaded = 0; + function loadTexture(i) { + loader.load(url[i], function(buffer) { + const texDatas = scope.parse(buffer, true); + images[i] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + loaded += 1; + if (loaded === 6) { + if (texDatas.mipmapCount === 1) + texture.minFilter = LinearFilter2; + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + } + }, onProgress, onError); + } + if (Array.isArray(url)) { + for (let i = 0, il = url.length;i < il; ++i) { + loadTexture(i); + } + } else { + loader.load(url, function(buffer) { + const texDatas = scope.parse(buffer, true); + if (texDatas.isCubemap) { + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + for (let f = 0;f < faces; f++) { + images[f] = { mipmaps: [] }; + for (let i = 0;i < texDatas.mipmapCount; i++) { + images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]); + images[f].format = texDatas.format; + images[f].width = texDatas.width; + images[f].height = texDatas.height; + } + } + texture.image = images; + } else { + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + } + if (texDatas.mipmapCount === 1) { + texture.minFilter = LinearFilter2; + } + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + }, onProgress, onError); + } + return texture; + } + } + + class ImageLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache2.get(url); + if (cached !== undefined) { + scope.manager.itemStart(url); + setTimeout(function() { + if (onLoad) + onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const image = createElementNS2("img"); + function onImageLoad() { + removeEventListeners(); + Cache2.add(url, this); + if (onLoad) + onLoad(this); + scope.manager.itemEnd(url); + } + function onImageError(event) { + removeEventListeners(); + if (onError) + onError(event); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + } + function removeEventListeners() { + image.removeEventListener("load", onImageLoad, false); + image.removeEventListener("error", onImageError, false); + } + image.addEventListener("load", onImageLoad, false); + image.addEventListener("error", onImageError, false); + if (url.slice(0, 5) !== "data:") { + if (this.crossOrigin !== undefined) + image.crossOrigin = this.crossOrigin; + } + scope.manager.itemStart(url); + image.src = url; + return image; + } + } + + class CubeTextureLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(urls, onLoad, onProgress, onError) { + const texture = new CubeTexture2; + texture.colorSpace = SRGBColorSpace2; + const loader = new ImageLoader2(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + let loaded = 0; + function loadTexture(i) { + loader.load(urls[i], function(image) { + texture.images[i] = image; + loaded++; + if (loaded === 6) { + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + } + }, undefined, onError); + } + for (let i = 0;i < urls.length; ++i) { + loadTexture(i); + } + return texture; + } + } + + class DataTextureLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const texture = new DataTexture2; + const loader = new FileLoader2(this.manager); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setPath(this.path); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(buffer) { + let texData; + try { + texData = scope.parse(buffer); + } catch (error) { + if (onError !== undefined) { + onError(error); + } else { + console.error(error); + return; + } + } + if (texData.image !== undefined) { + texture.image = texData.image; + } else if (texData.data !== undefined) { + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; + } + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping2; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping2; + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter2; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter2; + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + if (texData.colorSpace !== undefined) { + texture.colorSpace = texData.colorSpace; + } + if (texData.flipY !== undefined) { + texture.flipY = texData.flipY; + } + if (texData.format !== undefined) { + texture.format = texData.format; + } + if (texData.type !== undefined) { + texture.type = texData.type; + } + if (texData.mipmaps !== undefined) { + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter2; + } + if (texData.mipmapCount === 1) { + texture.minFilter = LinearFilter2; + } + if (texData.generateMipmaps !== undefined) { + texture.generateMipmaps = texData.generateMipmaps; + } + texture.needsUpdate = true; + if (onLoad) + onLoad(texture, texData); + }, onProgress, onError); + return texture; + } + } + + class TextureLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const texture = new Texture2; + const loader = new ImageLoader2(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + loader.load(url, function(image) { + texture.image = image; + texture.needsUpdate = true; + if (onLoad !== undefined) { + onLoad(texture); + } + }, onProgress, onError); + return texture; + } + } + + class Light2 extends Object3D2 { + constructor(color, intensity = 1) { + super(); + this.isLight = true; + this.type = "Light"; + this.color = new Color2(color); + this.intensity = intensity; + } + dispose() { + } + copy(source, recursive) { + super.copy(source, recursive); + this.color.copy(source.color); + this.intensity = source.intensity; + return this; + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + data2.object.color = this.color.getHex(); + data2.object.intensity = this.intensity; + if (this.groundColor !== undefined) + data2.object.groundColor = this.groundColor.getHex(); + if (this.distance !== undefined) + data2.object.distance = this.distance; + if (this.angle !== undefined) + data2.object.angle = this.angle; + if (this.decay !== undefined) + data2.object.decay = this.decay; + if (this.penumbra !== undefined) + data2.object.penumbra = this.penumbra; + if (this.shadow !== undefined) + data2.object.shadow = this.shadow.toJSON(); + if (this.target !== undefined) + data2.object.target = this.target.uuid; + return data2; + } + } + + class HemisphereLight2 extends Light2 { + constructor(skyColor, groundColor, intensity) { + super(skyColor, intensity); + this.isHemisphereLight = true; + this.type = "HemisphereLight"; + this.position.copy(Object3D2.DEFAULT_UP); + this.updateMatrix(); + this.groundColor = new Color2(groundColor); + } + copy(source, recursive) { + super.copy(source, recursive); + this.groundColor.copy(source.groundColor); + return this; + } + } + var _projScreenMatrix$12 = /* @__PURE__ */ new Matrix42; + var _lightPositionWorld$12 = /* @__PURE__ */ new Vector32; + var _lookTarget$12 = /* @__PURE__ */ new Vector32; + + class LightShadow2 { + constructor(camera) { + this.camera = camera; + this.intensity = 1; + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; + this.mapSize = new Vector22(512, 512); + this.map = null; + this.mapPass = null; + this.matrix = new Matrix42; + this.autoUpdate = true; + this.needsUpdate = false; + this._frustum = new Frustum2; + this._frameExtents = new Vector22(1, 1); + this._viewportCount = 1; + this._viewports = [ + new Vector42(0, 0, 1, 1) + ]; + } + getViewportCount() { + return this._viewportCount; + } + getFrustum() { + return this._frustum; + } + updateMatrices(light) { + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; + _lightPositionWorld$12.setFromMatrixPosition(light.matrixWorld); + shadowCamera.position.copy(_lightPositionWorld$12); + _lookTarget$12.setFromMatrixPosition(light.target.matrixWorld); + shadowCamera.lookAt(_lookTarget$12); + shadowCamera.updateMatrixWorld(); + _projScreenMatrix$12.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix$12); + shadowMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + shadowMatrix.multiply(_projScreenMatrix$12); + } + getViewport(viewportIndex) { + return this._viewports[viewportIndex]; + } + getFrameExtents() { + return this._frameExtents; + } + dispose() { + if (this.map) { + this.map.dispose(); + } + if (this.mapPass) { + this.mapPass.dispose(); + } + } + copy(source) { + this.camera = source.camera.clone(); + this.intensity = source.intensity; + this.bias = source.bias; + this.radius = source.radius; + this.mapSize.copy(source.mapSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + toJSON() { + const object = {}; + if (this.intensity !== 1) + object.intensity = this.intensity; + if (this.bias !== 0) + object.bias = this.bias; + if (this.normalBias !== 0) + object.normalBias = this.normalBias; + if (this.radius !== 1) + object.radius = this.radius; + if (this.mapSize.x !== 512 || this.mapSize.y !== 512) + object.mapSize = this.mapSize.toArray(); + object.camera = this.camera.toJSON(false).object; + delete object.camera.matrix; + return object; + } + } + + class SpotLightShadow2 extends LightShadow2 { + constructor() { + super(new PerspectiveCamera2(50, 1, 0.5, 500)); + this.isSpotLightShadow = true; + this.focus = 1; + } + updateMatrices(light) { + const camera = this.camera; + const fov3 = RAD2DEG2 * 2 * light.angle * this.focus; + const aspect3 = this.mapSize.width / this.mapSize.height; + const far = light.distance || camera.far; + if (fov3 !== camera.fov || aspect3 !== camera.aspect || far !== camera.far) { + camera.fov = fov3; + camera.aspect = aspect3; + camera.far = far; + camera.updateProjectionMatrix(); + } + super.updateMatrices(light); + } + copy(source) { + super.copy(source); + this.focus = source.focus; + return this; + } + } + + class SpotLight2 extends Light2 { + constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2) { + super(color, intensity); + this.isSpotLight = true; + this.type = "SpotLight"; + this.position.copy(Object3D2.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D2; + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; + this.map = null; + this.shadow = new SpotLightShadow2; + } + get power() { + return this.intensity * Math.PI; + } + set power(power) { + this.intensity = power / Math.PI; + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } + } + var _projScreenMatrix2 = /* @__PURE__ */ new Matrix42; + var _lightPositionWorld2 = /* @__PURE__ */ new Vector32; + var _lookTarget2 = /* @__PURE__ */ new Vector32; + + class PointLightShadow2 extends LightShadow2 { + constructor() { + super(new PerspectiveCamera2(90, 1, 0.5, 500)); + this.isPointLightShadow = true; + this._frameExtents = new Vector22(4, 2); + this._viewportCount = 6; + this._viewports = [ + new Vector42(2, 1, 1, 1), + new Vector42(0, 1, 1, 1), + new Vector42(3, 1, 1, 1), + new Vector42(1, 1, 1, 1), + new Vector42(3, 0, 1, 1), + new Vector42(1, 0, 1, 1) + ]; + this._cubeDirections = [ + new Vector32(1, 0, 0), + new Vector32(-1, 0, 0), + new Vector32(0, 0, 1), + new Vector32(0, 0, -1), + new Vector32(0, 1, 0), + new Vector32(0, -1, 0) + ]; + this._cubeUps = [ + new Vector32(0, 1, 0), + new Vector32(0, 1, 0), + new Vector32(0, 1, 0), + new Vector32(0, 1, 0), + new Vector32(0, 0, 1), + new Vector32(0, 0, -1) + ]; + } + updateMatrices(light, viewportIndex = 0) { + const camera = this.camera; + const shadowMatrix = this.matrix; + const far = light.distance || camera.far; + if (far !== camera.far) { + camera.far = far; + camera.updateProjectionMatrix(); + } + _lightPositionWorld2.setFromMatrixPosition(light.matrixWorld); + camera.position.copy(_lightPositionWorld2); + _lookTarget2.copy(camera.position); + _lookTarget2.add(this._cubeDirections[viewportIndex]); + camera.up.copy(this._cubeUps[viewportIndex]); + camera.lookAt(_lookTarget2); + camera.updateMatrixWorld(); + shadowMatrix.makeTranslation(-_lightPositionWorld2.x, -_lightPositionWorld2.y, -_lightPositionWorld2.z); + _projScreenMatrix2.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix2); + } + } + + class PointLight2 extends Light2 { + constructor(color, intensity, distance = 0, decay = 2) { + super(color, intensity); + this.isPointLight = true; + this.type = "PointLight"; + this.distance = distance; + this.decay = decay; + this.shadow = new PointLightShadow2; + } + get power() { + return this.intensity * 4 * Math.PI; + } + set power(power) { + this.intensity = power / (4 * Math.PI); + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.decay = source.decay; + this.shadow = source.shadow.clone(); + return this; + } + } + + class OrthographicCamera2 extends Camera2 { + constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) { + super(); + this.isOrthographicCamera = true; + this.type = "OrthographicCamera"; + this.zoom = 1; + this.view = null; + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + this.near = near; + this.far = far; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign({}, source.view); + return this; + } + setViewOffset(fullWidth, fullHeight, x2, y3, width2, height2) { + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x2; + this.view.offsetY = y3; + this.view.width = width2; + this.view.height = height2; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const dx = (this.right - this.left) / (2 * this.zoom); + const dy2 = (this.top - this.bottom) / (2 * this.zoom); + const cx = (this.right + this.left) / 2; + const cy = (this.top + this.bottom) / 2; + let left = cx - dx; + let right = cx + dx; + let top = cy + dy2; + let bottom = cy - dy2; + if (this.view !== null && this.view.enabled) { + const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom; + const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom; + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + } + this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + data2.object.zoom = this.zoom; + data2.object.left = this.left; + data2.object.right = this.right; + data2.object.top = this.top; + data2.object.bottom = this.bottom; + data2.object.near = this.near; + data2.object.far = this.far; + if (this.view !== null) + data2.object.view = Object.assign({}, this.view); + return data2; + } + } + + class DirectionalLightShadow2 extends LightShadow2 { + constructor() { + super(new OrthographicCamera2(-5, 5, 5, -5, 0.5, 500)); + this.isDirectionalLightShadow = true; + } + } + + class DirectionalLight2 extends Light2 { + constructor(color, intensity) { + super(color, intensity); + this.isDirectionalLight = true; + this.type = "DirectionalLight"; + this.position.copy(Object3D2.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D2; + this.shadow = new DirectionalLightShadow2; + } + dispose() { + this.shadow.dispose(); + } + copy(source) { + super.copy(source); + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } + } + + class AmbientLight2 extends Light2 { + constructor(color, intensity) { + super(color, intensity); + this.isAmbientLight = true; + this.type = "AmbientLight"; + } + } + + class RectAreaLight2 extends Light2 { + constructor(color, intensity, width2 = 10, height2 = 10) { + super(color, intensity); + this.isRectAreaLight = true; + this.type = "RectAreaLight"; + this.width = width2; + this.height = height2; + } + get power() { + return this.intensity * this.width * this.height * Math.PI; + } + set power(power) { + this.intensity = power / (this.width * this.height * Math.PI); + } + copy(source) { + super.copy(source); + this.width = source.width; + this.height = source.height; + return this; + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + data2.object.width = this.width; + data2.object.height = this.height; + return data2; + } + } + + class SphericalHarmonics32 { + constructor() { + this.isSphericalHarmonics3 = true; + this.coefficients = []; + for (let i = 0;i < 9; i++) { + this.coefficients.push(new Vector32); + } + } + set(coefficients) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].copy(coefficients[i]); + } + return this; + } + zero() { + for (let i = 0;i < 9; i++) { + this.coefficients[i].set(0, 0, 0); + } + return this; + } + getAt(normal, target) { + const { x: x2, y: y3, z: z2 } = normal; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.282095); + target.addScaledVector(coeff[1], 0.488603 * y3); + target.addScaledVector(coeff[2], 0.488603 * z2); + target.addScaledVector(coeff[3], 0.488603 * x2); + target.addScaledVector(coeff[4], 1.092548 * (x2 * y3)); + target.addScaledVector(coeff[5], 1.092548 * (y3 * z2)); + target.addScaledVector(coeff[6], 0.315392 * (3 * z2 * z2 - 1)); + target.addScaledVector(coeff[7], 1.092548 * (x2 * z2)); + target.addScaledVector(coeff[8], 0.546274 * (x2 * x2 - y3 * y3)); + return target; + } + getIrradianceAt(normal, target) { + const { x: x2, y: y3, z: z2 } = normal; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.886227); + target.addScaledVector(coeff[1], 2 * 0.511664 * y3); + target.addScaledVector(coeff[2], 2 * 0.511664 * z2); + target.addScaledVector(coeff[3], 2 * 0.511664 * x2); + target.addScaledVector(coeff[4], 2 * 0.429043 * x2 * y3); + target.addScaledVector(coeff[5], 2 * 0.429043 * y3 * z2); + target.addScaledVector(coeff[6], 0.743125 * z2 * z2 - 0.247708); + target.addScaledVector(coeff[7], 2 * 0.429043 * x2 * z2); + target.addScaledVector(coeff[8], 0.429043 * (x2 * x2 - y3 * y3)); + return target; + } + add(sh) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].add(sh.coefficients[i]); + } + return this; + } + addScaledSH(sh, s) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].addScaledVector(sh.coefficients[i], s); + } + return this; + } + scale(s) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].multiplyScalar(s); + } + return this; + } + lerp(sh, alpha) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].lerp(sh.coefficients[i], alpha); + } + return this; + } + equals(sh) { + for (let i = 0;i < 9; i++) { + if (!this.coefficients[i].equals(sh.coefficients[i])) { + return false; + } + } + return true; + } + copy(sh) { + return this.set(sh.coefficients); + } + clone() { + return new this.constructor().copy(this); + } + fromArray(array, offset = 0) { + const coefficients = this.coefficients; + for (let i = 0;i < 9; i++) { + coefficients[i].fromArray(array, offset + i * 3); + } + return this; + } + toArray(array = [], offset = 0) { + const coefficients = this.coefficients; + for (let i = 0;i < 9; i++) { + coefficients[i].toArray(array, offset + i * 3); + } + return array; + } + static getBasisAt(normal, shBasis) { + const { x: x2, y: y3, z: z2 } = normal; + shBasis[0] = 0.282095; + shBasis[1] = 0.488603 * y3; + shBasis[2] = 0.488603 * z2; + shBasis[3] = 0.488603 * x2; + shBasis[4] = 1.092548 * x2 * y3; + shBasis[5] = 1.092548 * y3 * z2; + shBasis[6] = 0.315392 * (3 * z2 * z2 - 1); + shBasis[7] = 1.092548 * x2 * z2; + shBasis[8] = 0.546274 * (x2 * x2 - y3 * y3); + } + } + + class LightProbe2 extends Light2 { + constructor(sh = new SphericalHarmonics32, intensity = 1) { + super(undefined, intensity); + this.isLightProbe = true; + this.sh = sh; + } + copy(source) { + super.copy(source); + this.sh.copy(source.sh); + return this; + } + fromJSON(json) { + this.intensity = json.intensity; + this.sh.fromArray(json.sh); + return this; + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + data2.object.sh = this.sh.toArray(); + return data2; + } + } + + class MaterialLoader2 extends Loader2 { + constructor(manager) { + super(manager); + this.textures = {}; + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader2(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const textures = this.textures; + function getTexture(name2) { + if (textures[name2] === undefined) { + console.warn("THREE.MaterialLoader: Undefined texture", name2); + } + return textures[name2]; + } + const material = this.createMaterialFromType(json.type); + if (json.uuid !== undefined) + material.uuid = json.uuid; + if (json.name !== undefined) + material.name = json.name; + if (json.color !== undefined && material.color !== undefined) + material.color.setHex(json.color); + if (json.roughness !== undefined) + material.roughness = json.roughness; + if (json.metalness !== undefined) + material.metalness = json.metalness; + if (json.sheen !== undefined) + material.sheen = json.sheen; + if (json.sheenColor !== undefined) + material.sheenColor = new Color2().setHex(json.sheenColor); + if (json.sheenRoughness !== undefined) + material.sheenRoughness = json.sheenRoughness; + if (json.emissive !== undefined && material.emissive !== undefined) + material.emissive.setHex(json.emissive); + if (json.specular !== undefined && material.specular !== undefined) + material.specular.setHex(json.specular); + if (json.specularIntensity !== undefined) + material.specularIntensity = json.specularIntensity; + if (json.specularColor !== undefined && material.specularColor !== undefined) + material.specularColor.setHex(json.specularColor); + if (json.shininess !== undefined) + material.shininess = json.shininess; + if (json.clearcoat !== undefined) + material.clearcoat = json.clearcoat; + if (json.clearcoatRoughness !== undefined) + material.clearcoatRoughness = json.clearcoatRoughness; + if (json.dispersion !== undefined) + material.dispersion = json.dispersion; + if (json.iridescence !== undefined) + material.iridescence = json.iridescence; + if (json.iridescenceIOR !== undefined) + material.iridescenceIOR = json.iridescenceIOR; + if (json.iridescenceThicknessRange !== undefined) + material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if (json.transmission !== undefined) + material.transmission = json.transmission; + if (json.thickness !== undefined) + material.thickness = json.thickness; + if (json.attenuationDistance !== undefined) + material.attenuationDistance = json.attenuationDistance; + if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) + material.attenuationColor.setHex(json.attenuationColor); + if (json.anisotropy !== undefined) + material.anisotropy = json.anisotropy; + if (json.anisotropyRotation !== undefined) + material.anisotropyRotation = json.anisotropyRotation; + if (json.fog !== undefined) + material.fog = json.fog; + if (json.flatShading !== undefined) + material.flatShading = json.flatShading; + if (json.blending !== undefined) + material.blending = json.blending; + if (json.combine !== undefined) + material.combine = json.combine; + if (json.side !== undefined) + material.side = json.side; + if (json.shadowSide !== undefined) + material.shadowSide = json.shadowSide; + if (json.opacity !== undefined) + material.opacity = json.opacity; + if (json.transparent !== undefined) + material.transparent = json.transparent; + if (json.alphaTest !== undefined) + material.alphaTest = json.alphaTest; + if (json.alphaHash !== undefined) + material.alphaHash = json.alphaHash; + if (json.depthFunc !== undefined) + material.depthFunc = json.depthFunc; + if (json.depthTest !== undefined) + material.depthTest = json.depthTest; + if (json.depthWrite !== undefined) + material.depthWrite = json.depthWrite; + if (json.colorWrite !== undefined) + material.colorWrite = json.colorWrite; + if (json.blendSrc !== undefined) + material.blendSrc = json.blendSrc; + if (json.blendDst !== undefined) + material.blendDst = json.blendDst; + if (json.blendEquation !== undefined) + material.blendEquation = json.blendEquation; + if (json.blendSrcAlpha !== undefined) + material.blendSrcAlpha = json.blendSrcAlpha; + if (json.blendDstAlpha !== undefined) + material.blendDstAlpha = json.blendDstAlpha; + if (json.blendEquationAlpha !== undefined) + material.blendEquationAlpha = json.blendEquationAlpha; + if (json.blendColor !== undefined && material.blendColor !== undefined) + material.blendColor.setHex(json.blendColor); + if (json.blendAlpha !== undefined) + material.blendAlpha = json.blendAlpha; + if (json.stencilWriteMask !== undefined) + material.stencilWriteMask = json.stencilWriteMask; + if (json.stencilFunc !== undefined) + material.stencilFunc = json.stencilFunc; + if (json.stencilRef !== undefined) + material.stencilRef = json.stencilRef; + if (json.stencilFuncMask !== undefined) + material.stencilFuncMask = json.stencilFuncMask; + if (json.stencilFail !== undefined) + material.stencilFail = json.stencilFail; + if (json.stencilZFail !== undefined) + material.stencilZFail = json.stencilZFail; + if (json.stencilZPass !== undefined) + material.stencilZPass = json.stencilZPass; + if (json.stencilWrite !== undefined) + material.stencilWrite = json.stencilWrite; + if (json.wireframe !== undefined) + material.wireframe = json.wireframe; + if (json.wireframeLinewidth !== undefined) + material.wireframeLinewidth = json.wireframeLinewidth; + if (json.wireframeLinecap !== undefined) + material.wireframeLinecap = json.wireframeLinecap; + if (json.wireframeLinejoin !== undefined) + material.wireframeLinejoin = json.wireframeLinejoin; + if (json.rotation !== undefined) + material.rotation = json.rotation; + if (json.linewidth !== undefined) + material.linewidth = json.linewidth; + if (json.dashSize !== undefined) + material.dashSize = json.dashSize; + if (json.gapSize !== undefined) + material.gapSize = json.gapSize; + if (json.scale !== undefined) + material.scale = json.scale; + if (json.polygonOffset !== undefined) + material.polygonOffset = json.polygonOffset; + if (json.polygonOffsetFactor !== undefined) + material.polygonOffsetFactor = json.polygonOffsetFactor; + if (json.polygonOffsetUnits !== undefined) + material.polygonOffsetUnits = json.polygonOffsetUnits; + if (json.dithering !== undefined) + material.dithering = json.dithering; + if (json.alphaToCoverage !== undefined) + material.alphaToCoverage = json.alphaToCoverage; + if (json.premultipliedAlpha !== undefined) + material.premultipliedAlpha = json.premultipliedAlpha; + if (json.forceSinglePass !== undefined) + material.forceSinglePass = json.forceSinglePass; + if (json.visible !== undefined) + material.visible = json.visible; + if (json.toneMapped !== undefined) + material.toneMapped = json.toneMapped; + if (json.userData !== undefined) + material.userData = json.userData; + if (json.vertexColors !== undefined) { + if (typeof json.vertexColors === "number") { + material.vertexColors = json.vertexColors > 0 ? true : false; + } else { + material.vertexColors = json.vertexColors; + } + } + if (json.uniforms !== undefined) { + for (const name2 in json.uniforms) { + const uniform = json.uniforms[name2]; + material.uniforms[name2] = {}; + switch (uniform.type) { + case "t": + material.uniforms[name2].value = getTexture(uniform.value); + break; + case "c": + material.uniforms[name2].value = new Color2().setHex(uniform.value); + break; + case "v2": + material.uniforms[name2].value = new Vector22().fromArray(uniform.value); + break; + case "v3": + material.uniforms[name2].value = new Vector32().fromArray(uniform.value); + break; + case "v4": + material.uniforms[name2].value = new Vector42().fromArray(uniform.value); + break; + case "m3": + material.uniforms[name2].value = new Matrix32().fromArray(uniform.value); + break; + case "m4": + material.uniforms[name2].value = new Matrix42().fromArray(uniform.value); + break; + default: + material.uniforms[name2].value = uniform.value; + } + } + } + if (json.defines !== undefined) + material.defines = json.defines; + if (json.vertexShader !== undefined) + material.vertexShader = json.vertexShader; + if (json.fragmentShader !== undefined) + material.fragmentShader = json.fragmentShader; + if (json.glslVersion !== undefined) + material.glslVersion = json.glslVersion; + if (json.extensions !== undefined) { + for (const key2 in json.extensions) { + material.extensions[key2] = json.extensions[key2]; + } + } + if (json.lights !== undefined) + material.lights = json.lights; + if (json.clipping !== undefined) + material.clipping = json.clipping; + if (json.size !== undefined) + material.size = json.size; + if (json.sizeAttenuation !== undefined) + material.sizeAttenuation = json.sizeAttenuation; + if (json.map !== undefined) + material.map = getTexture(json.map); + if (json.matcap !== undefined) + material.matcap = getTexture(json.matcap); + if (json.alphaMap !== undefined) + material.alphaMap = getTexture(json.alphaMap); + if (json.bumpMap !== undefined) + material.bumpMap = getTexture(json.bumpMap); + if (json.bumpScale !== undefined) + material.bumpScale = json.bumpScale; + if (json.normalMap !== undefined) + material.normalMap = getTexture(json.normalMap); + if (json.normalMapType !== undefined) + material.normalMapType = json.normalMapType; + if (json.normalScale !== undefined) { + let normalScale = json.normalScale; + if (Array.isArray(normalScale) === false) { + normalScale = [normalScale, normalScale]; + } + material.normalScale = new Vector22().fromArray(normalScale); + } + if (json.displacementMap !== undefined) + material.displacementMap = getTexture(json.displacementMap); + if (json.displacementScale !== undefined) + material.displacementScale = json.displacementScale; + if (json.displacementBias !== undefined) + material.displacementBias = json.displacementBias; + if (json.roughnessMap !== undefined) + material.roughnessMap = getTexture(json.roughnessMap); + if (json.metalnessMap !== undefined) + material.metalnessMap = getTexture(json.metalnessMap); + if (json.emissiveMap !== undefined) + material.emissiveMap = getTexture(json.emissiveMap); + if (json.emissiveIntensity !== undefined) + material.emissiveIntensity = json.emissiveIntensity; + if (json.specularMap !== undefined) + material.specularMap = getTexture(json.specularMap); + if (json.specularIntensityMap !== undefined) + material.specularIntensityMap = getTexture(json.specularIntensityMap); + if (json.specularColorMap !== undefined) + material.specularColorMap = getTexture(json.specularColorMap); + if (json.envMap !== undefined) + material.envMap = getTexture(json.envMap); + if (json.envMapRotation !== undefined) + material.envMapRotation.fromArray(json.envMapRotation); + if (json.envMapIntensity !== undefined) + material.envMapIntensity = json.envMapIntensity; + if (json.reflectivity !== undefined) + material.reflectivity = json.reflectivity; + if (json.refractionRatio !== undefined) + material.refractionRatio = json.refractionRatio; + if (json.lightMap !== undefined) + material.lightMap = getTexture(json.lightMap); + if (json.lightMapIntensity !== undefined) + material.lightMapIntensity = json.lightMapIntensity; + if (json.aoMap !== undefined) + material.aoMap = getTexture(json.aoMap); + if (json.aoMapIntensity !== undefined) + material.aoMapIntensity = json.aoMapIntensity; + if (json.gradientMap !== undefined) + material.gradientMap = getTexture(json.gradientMap); + if (json.clearcoatMap !== undefined) + material.clearcoatMap = getTexture(json.clearcoatMap); + if (json.clearcoatRoughnessMap !== undefined) + material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap); + if (json.clearcoatNormalMap !== undefined) + material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap); + if (json.clearcoatNormalScale !== undefined) + material.clearcoatNormalScale = new Vector22().fromArray(json.clearcoatNormalScale); + if (json.iridescenceMap !== undefined) + material.iridescenceMap = getTexture(json.iridescenceMap); + if (json.iridescenceThicknessMap !== undefined) + material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap); + if (json.transmissionMap !== undefined) + material.transmissionMap = getTexture(json.transmissionMap); + if (json.thicknessMap !== undefined) + material.thicknessMap = getTexture(json.thicknessMap); + if (json.anisotropyMap !== undefined) + material.anisotropyMap = getTexture(json.anisotropyMap); + if (json.sheenColorMap !== undefined) + material.sheenColorMap = getTexture(json.sheenColorMap); + if (json.sheenRoughnessMap !== undefined) + material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap); + return material; + } + setTextures(value2) { + this.textures = value2; + return this; + } + createMaterialFromType(type) { + return MaterialLoader2.createMaterialFromType(type); + } + static createMaterialFromType(type) { + const materialLib = { + ShadowMaterial: ShadowMaterial2, + SpriteMaterial: SpriteMaterial2, + RawShaderMaterial: RawShaderMaterial2, + ShaderMaterial: ShaderMaterial2, + PointsMaterial: PointsMaterial2, + MeshPhysicalMaterial: MeshPhysicalMaterial2, + MeshStandardMaterial: MeshStandardMaterial2, + MeshPhongMaterial: MeshPhongMaterial2, + MeshToonMaterial: MeshToonMaterial2, + MeshNormalMaterial: MeshNormalMaterial2, + MeshLambertMaterial: MeshLambertMaterial2, + MeshDepthMaterial: MeshDepthMaterial2, + MeshDistanceMaterial: MeshDistanceMaterial2, + MeshBasicMaterial: MeshBasicMaterial2, + MeshMatcapMaterial: MeshMatcapMaterial2, + LineDashedMaterial: LineDashedMaterial2, + LineBasicMaterial: LineBasicMaterial2, + Material: Material2 + }; + return new materialLib[type]; + } + } + + class LoaderUtils2 { + static decodeText(array) { + console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."); + if (typeof TextDecoder !== "undefined") { + return new TextDecoder().decode(array); + } + let s = ""; + for (let i = 0, il = array.length;i < il; i++) { + s += String.fromCharCode(array[i]); + } + try { + return decodeURIComponent(escape(s)); + } catch (e) { + return s; + } + } + static extractUrlBase(url) { + const index2 = url.lastIndexOf("/"); + if (index2 === -1) + return "./"; + return url.slice(0, index2 + 1); + } + static resolveURL(url, path) { + if (typeof url !== "string" || url === "") + return ""; + if (/^https?:\/\//i.test(path) && /^\//.test(url)) { + path = path.replace(/(^https?:\/\/[^\/]+).*/i, "$1"); + } + if (/^(https?:)?\/\//i.test(url)) + return url; + if (/^data:.*,.*$/i.test(url)) + return url; + if (/^blob:.*$/i.test(url)) + return url; + return path + url; + } + } + + class InstancedBufferGeometry2 extends BufferGeometry2 { + constructor() { + super(); + this.isInstancedBufferGeometry = true; + this.type = "InstancedBufferGeometry"; + this.instanceCount = Infinity; + } + copy(source) { + super.copy(source); + this.instanceCount = source.instanceCount; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.instanceCount = this.instanceCount; + data2.isInstancedBufferGeometry = true; + return data2; + } + } + + class BufferGeometryLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader2(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const interleavedBufferMap = {}; + const arrayBufferMap = {}; + function getInterleavedBuffer(json2, uuid) { + if (interleavedBufferMap[uuid] !== undefined) + return interleavedBufferMap[uuid]; + const interleavedBuffers = json2.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[uuid]; + const buffer = getArrayBuffer(json2, interleavedBuffer.buffer); + const array = getTypedArray2(interleavedBuffer.type, buffer); + const ib = new InterleavedBuffer2(array, interleavedBuffer.stride); + ib.uuid = interleavedBuffer.uuid; + interleavedBufferMap[uuid] = ib; + return ib; + } + function getArrayBuffer(json2, uuid) { + if (arrayBufferMap[uuid] !== undefined) + return arrayBufferMap[uuid]; + const arrayBuffers = json2.arrayBuffers; + const arrayBuffer = arrayBuffers[uuid]; + const ab = new Uint32Array(arrayBuffer).buffer; + arrayBufferMap[uuid] = ab; + return ab; + } + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry2 : new BufferGeometry2; + const index2 = json.data.index; + if (index2 !== undefined) { + const typedArray = getTypedArray2(index2.type, index2.array); + geometry.setIndex(new BufferAttribute2(typedArray, 1)); + } + const attributes = json.data.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute2(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray2(attribute.type, attribute.array); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute2 : BufferAttribute2; + bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== undefined) + bufferAttribute.name = attribute.name; + if (attribute.usage !== undefined) + bufferAttribute.setUsage(attribute.usage); + geometry.setAttribute(key2, bufferAttribute); + } + const morphAttributes = json.data.morphAttributes; + if (morphAttributes) { + for (const key2 in morphAttributes) { + const attributeArray = morphAttributes[key2]; + const array = []; + for (let i = 0, il = attributeArray.length;i < il; i++) { + const attribute = attributeArray[i]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute2(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray2(attribute.type, attribute.array); + bufferAttribute = new BufferAttribute2(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== undefined) + bufferAttribute.name = attribute.name; + array.push(bufferAttribute); + } + geometry.morphAttributes[key2] = array; + } + } + const morphTargetsRelative = json.data.morphTargetsRelative; + if (morphTargetsRelative) { + geometry.morphTargetsRelative = true; + } + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + if (groups !== undefined) { + for (let i = 0, n2 = groups.length;i !== n2; ++i) { + const group = groups[i]; + geometry.addGroup(group.start, group.count, group.materialIndex); + } + } + const boundingSphere = json.data.boundingSphere; + if (boundingSphere !== undefined) { + const center = new Vector32; + if (boundingSphere.center !== undefined) { + center.fromArray(boundingSphere.center); + } + geometry.boundingSphere = new Sphere2(center, boundingSphere.radius); + } + if (json.name) + geometry.name = json.name; + if (json.userData) + geometry.userData = json.userData; + return geometry; + } + } + + class ObjectLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const path = this.path === "" ? LoaderUtils2.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader2(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text2) { + let json = null; + try { + json = JSON.parse(text2); + } catch (error) { + if (onError !== undefined) + onError(error); + console.error("THREE:ObjectLoader: Can't parse " + url + ".", error.message); + return; + } + const metadata = json.metadata; + if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === "geometry") { + if (onError !== undefined) + onError(new Error("THREE.ObjectLoader: Can't load " + url)); + console.error("THREE.ObjectLoader: Can't load " + url); + return; + } + scope.parse(json, onLoad); + }, onProgress, onError); + } + async loadAsync(url, onProgress) { + const scope = this; + const path = this.path === "" ? LoaderUtils2.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader2(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + const text2 = await loader.loadAsync(url, onProgress); + const json = JSON.parse(text2); + const metadata = json.metadata; + if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === "geometry") { + throw new Error("THREE.ObjectLoader: Can't load " + url); + } + return await scope.parseAsync(json); + } + parse(json, onLoad) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = this.parseImages(json.images, function() { + if (onLoad !== undefined) + onLoad(object); + }); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + if (onLoad !== undefined) { + let hasImages = false; + for (const uuid in images) { + if (images[uuid].data instanceof HTMLImageElement) { + hasImages = true; + break; + } + } + if (hasImages === false) + onLoad(object); + } + return object; + } + async parseAsync(json) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = await this.parseImagesAsync(json.images); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + return object; + } + parseShapes(json) { + const shapes = {}; + if (json !== undefined) { + for (let i = 0, l2 = json.length;i < l2; i++) { + const shape = new Shape2().fromJSON(json[i]); + shapes[shape.uuid] = shape; + } + } + return shapes; + } + parseSkeletons(json, object) { + const skeletons = {}; + const bones = {}; + object.traverse(function(child) { + if (child.isBone) + bones[child.uuid] = child; + }); + if (json !== undefined) { + for (let i = 0, l2 = json.length;i < l2; i++) { + const skeleton = new Skeleton2().fromJSON(json[i], bones); + skeletons[skeleton.uuid] = skeleton; + } + } + return skeletons; + } + parseGeometries(json, shapes) { + const geometries = {}; + if (json !== undefined) { + const bufferGeometryLoader = new BufferGeometryLoader2; + for (let i = 0, l2 = json.length;i < l2; i++) { + let geometry; + const data2 = json[i]; + switch (data2.type) { + case "BufferGeometry": + case "InstancedBufferGeometry": + geometry = bufferGeometryLoader.parse(data2); + break; + default: + if (data2.type in Geometries2) { + geometry = Geometries2[data2.type].fromJSON(data2, shapes); + } else { + console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data2.type}"`); + } + } + geometry.uuid = data2.uuid; + if (data2.name !== undefined) + geometry.name = data2.name; + if (data2.userData !== undefined) + geometry.userData = data2.userData; + geometries[data2.uuid] = geometry; + } + } + return geometries; + } + parseMaterials(json, textures) { + const cache = {}; + const materials = {}; + if (json !== undefined) { + const loader = new MaterialLoader2; + loader.setTextures(textures); + for (let i = 0, l2 = json.length;i < l2; i++) { + const data2 = json[i]; + if (cache[data2.uuid] === undefined) { + cache[data2.uuid] = loader.parse(data2); + } + materials[data2.uuid] = cache[data2.uuid]; + } + } + return materials; + } + parseAnimations(json) { + const animations = {}; + if (json !== undefined) { + for (let i = 0;i < json.length; i++) { + const data2 = json[i]; + const clip = AnimationClip2.parse(data2); + animations[clip.uuid] = clip; + } + } + return animations; + } + parseImages(json, onLoad) { + const scope = this; + const images = {}; + let loader; + function loadImage(url) { + scope.manager.itemStart(url); + return loader.load(url, function() { + scope.manager.itemEnd(url); + }, undefined, function() { + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + } + function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return loadImage(path); + } else { + if (image.data) { + return { + data: getTypedArray2(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== undefined && json.length > 0) { + const manager = new LoadingManager2(onLoad); + loader = new ImageLoader2(manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length;i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j2 = 0, jl = url.length;j2 < jl; j2++) { + const currentUrl = url[j2]; + const deserializedImage = deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture2(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source2(imageArray); + } else { + const deserializedImage = deserializeImage(image.url); + images[image.uuid] = new Source2(deserializedImage); + } + } + } + return images; + } + async parseImagesAsync(json) { + const scope = this; + const images = {}; + let loader; + async function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return await loader.loadAsync(path); + } else { + if (image.data) { + return { + data: getTypedArray2(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== undefined && json.length > 0) { + loader = new ImageLoader2(this.manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length;i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j2 = 0, jl = url.length;j2 < jl; j2++) { + const currentUrl = url[j2]; + const deserializedImage = await deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture2(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source2(imageArray); + } else { + const deserializedImage = await deserializeImage(image.url); + images[image.uuid] = new Source2(deserializedImage); + } + } + } + return images; + } + parseTextures(json, images) { + function parseConstant(value2, type) { + if (typeof value2 === "number") + return value2; + console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.", value2); + return type[value2]; + } + const textures = {}; + if (json !== undefined) { + for (let i = 0, l2 = json.length;i < l2; i++) { + const data2 = json[i]; + if (data2.image === undefined) { + console.warn('THREE.ObjectLoader: No "image" specified for', data2.uuid); + } + if (images[data2.image] === undefined) { + console.warn("THREE.ObjectLoader: Undefined image", data2.image); + } + const source = images[data2.image]; + const image = source.data; + let texture; + if (Array.isArray(image)) { + texture = new CubeTexture2; + if (image.length === 6) + texture.needsUpdate = true; + } else { + if (image && image.data) { + texture = new DataTexture2; + } else { + texture = new Texture2; + } + if (image) + texture.needsUpdate = true; + } + texture.source = source; + texture.uuid = data2.uuid; + if (data2.name !== undefined) + texture.name = data2.name; + if (data2.mapping !== undefined) + texture.mapping = parseConstant(data2.mapping, TEXTURE_MAPPING2); + if (data2.channel !== undefined) + texture.channel = data2.channel; + if (data2.offset !== undefined) + texture.offset.fromArray(data2.offset); + if (data2.repeat !== undefined) + texture.repeat.fromArray(data2.repeat); + if (data2.center !== undefined) + texture.center.fromArray(data2.center); + if (data2.rotation !== undefined) + texture.rotation = data2.rotation; + if (data2.wrap !== undefined) { + texture.wrapS = parseConstant(data2.wrap[0], TEXTURE_WRAPPING2); + texture.wrapT = parseConstant(data2.wrap[1], TEXTURE_WRAPPING2); + } + if (data2.format !== undefined) + texture.format = data2.format; + if (data2.internalFormat !== undefined) + texture.internalFormat = data2.internalFormat; + if (data2.type !== undefined) + texture.type = data2.type; + if (data2.colorSpace !== undefined) + texture.colorSpace = data2.colorSpace; + if (data2.minFilter !== undefined) + texture.minFilter = parseConstant(data2.minFilter, TEXTURE_FILTER2); + if (data2.magFilter !== undefined) + texture.magFilter = parseConstant(data2.magFilter, TEXTURE_FILTER2); + if (data2.anisotropy !== undefined) + texture.anisotropy = data2.anisotropy; + if (data2.flipY !== undefined) + texture.flipY = data2.flipY; + if (data2.generateMipmaps !== undefined) + texture.generateMipmaps = data2.generateMipmaps; + if (data2.premultiplyAlpha !== undefined) + texture.premultiplyAlpha = data2.premultiplyAlpha; + if (data2.unpackAlignment !== undefined) + texture.unpackAlignment = data2.unpackAlignment; + if (data2.compareFunction !== undefined) + texture.compareFunction = data2.compareFunction; + if (data2.userData !== undefined) + texture.userData = data2.userData; + textures[data2.uuid] = texture; + } + } + return textures; + } + parseObject(data2, geometries, materials, textures, animations) { + let object; + function getGeometry(name2) { + if (geometries[name2] === undefined) { + console.warn("THREE.ObjectLoader: Undefined geometry", name2); + } + return geometries[name2]; + } + function getMaterial(name2) { + if (name2 === undefined) + return; + if (Array.isArray(name2)) { + const array = []; + for (let i = 0, l2 = name2.length;i < l2; i++) { + const uuid = name2[i]; + if (materials[uuid] === undefined) { + console.warn("THREE.ObjectLoader: Undefined material", uuid); + } + array.push(materials[uuid]); + } + return array; + } + if (materials[name2] === undefined) { + console.warn("THREE.ObjectLoader: Undefined material", name2); + } + return materials[name2]; + } + function getTexture(uuid) { + if (textures[uuid] === undefined) { + console.warn("THREE.ObjectLoader: Undefined texture", uuid); + } + return textures[uuid]; + } + let geometry, material; + switch (data2.type) { + case "Scene": + object = new Scene2; + if (data2.background !== undefined) { + if (Number.isInteger(data2.background)) { + object.background = new Color2(data2.background); + } else { + object.background = getTexture(data2.background); + } + } + if (data2.environment !== undefined) { + object.environment = getTexture(data2.environment); + } + if (data2.fog !== undefined) { + if (data2.fog.type === "Fog") { + object.fog = new Fog2(data2.fog.color, data2.fog.near, data2.fog.far); + } else if (data2.fog.type === "FogExp2") { + object.fog = new FogExp22(data2.fog.color, data2.fog.density); + } + if (data2.fog.name !== "") { + object.fog.name = data2.fog.name; + } + } + if (data2.backgroundBlurriness !== undefined) + object.backgroundBlurriness = data2.backgroundBlurriness; + if (data2.backgroundIntensity !== undefined) + object.backgroundIntensity = data2.backgroundIntensity; + if (data2.backgroundRotation !== undefined) + object.backgroundRotation.fromArray(data2.backgroundRotation); + if (data2.environmentIntensity !== undefined) + object.environmentIntensity = data2.environmentIntensity; + if (data2.environmentRotation !== undefined) + object.environmentRotation.fromArray(data2.environmentRotation); + break; + case "PerspectiveCamera": + object = new PerspectiveCamera2(data2.fov, data2.aspect, data2.near, data2.far); + if (data2.focus !== undefined) + object.focus = data2.focus; + if (data2.zoom !== undefined) + object.zoom = data2.zoom; + if (data2.filmGauge !== undefined) + object.filmGauge = data2.filmGauge; + if (data2.filmOffset !== undefined) + object.filmOffset = data2.filmOffset; + if (data2.view !== undefined) + object.view = Object.assign({}, data2.view); + break; + case "OrthographicCamera": + object = new OrthographicCamera2(data2.left, data2.right, data2.top, data2.bottom, data2.near, data2.far); + if (data2.zoom !== undefined) + object.zoom = data2.zoom; + if (data2.view !== undefined) + object.view = Object.assign({}, data2.view); + break; + case "AmbientLight": + object = new AmbientLight2(data2.color, data2.intensity); + break; + case "DirectionalLight": + object = new DirectionalLight2(data2.color, data2.intensity); + object.target = data2.target || ""; + break; + case "PointLight": + object = new PointLight2(data2.color, data2.intensity, data2.distance, data2.decay); + break; + case "RectAreaLight": + object = new RectAreaLight2(data2.color, data2.intensity, data2.width, data2.height); + break; + case "SpotLight": + object = new SpotLight2(data2.color, data2.intensity, data2.distance, data2.angle, data2.penumbra, data2.decay); + object.target = data2.target || ""; + break; + case "HemisphereLight": + object = new HemisphereLight2(data2.color, data2.groundColor, data2.intensity); + break; + case "LightProbe": + object = new LightProbe2().fromJSON(data2); + break; + case "SkinnedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new SkinnedMesh2(geometry, material); + if (data2.bindMode !== undefined) + object.bindMode = data2.bindMode; + if (data2.bindMatrix !== undefined) + object.bindMatrix.fromArray(data2.bindMatrix); + if (data2.skeleton !== undefined) + object.skeleton = data2.skeleton; + break; + case "Mesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new Mesh2(geometry, material); + break; + case "InstancedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + const count = data2.count; + const instanceMatrix = data2.instanceMatrix; + const instanceColor = data2.instanceColor; + object = new InstancedMesh2(geometry, material, count); + object.instanceMatrix = new InstancedBufferAttribute2(new Float32Array(instanceMatrix.array), 16); + if (instanceColor !== undefined) + object.instanceColor = new InstancedBufferAttribute2(new Float32Array(instanceColor.array), instanceColor.itemSize); + break; + case "BatchedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new BatchedMesh2(data2.maxInstanceCount, data2.maxVertexCount, data2.maxIndexCount, material); + object.geometry = geometry; + object.perObjectFrustumCulled = data2.perObjectFrustumCulled; + object.sortObjects = data2.sortObjects; + object._drawRanges = data2.drawRanges; + object._reservedRanges = data2.reservedRanges; + object._visibility = data2.visibility; + object._active = data2.active; + object._bounds = data2.bounds.map((bound) => { + const box = new Box32; + box.min.fromArray(bound.boxMin); + box.max.fromArray(bound.boxMax); + const sphere = new Sphere2; + sphere.radius = bound.sphereRadius; + sphere.center.fromArray(bound.sphereCenter); + return { + boxInitialized: bound.boxInitialized, + box, + sphereInitialized: bound.sphereInitialized, + sphere + }; + }); + object._maxInstanceCount = data2.maxInstanceCount; + object._maxVertexCount = data2.maxVertexCount; + object._maxIndexCount = data2.maxIndexCount; + object._geometryInitialized = data2.geometryInitialized; + object._geometryCount = data2.geometryCount; + object._matricesTexture = getTexture(data2.matricesTexture.uuid); + if (data2.colorsTexture !== undefined) + object._colorsTexture = getTexture(data2.colorsTexture.uuid); + break; + case "LOD": + object = new LOD2; + break; + case "Line": + object = new Line4(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "LineLoop": + object = new LineLoop2(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "LineSegments": + object = new LineSegments3(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "PointCloud": + case "Points": + object = new Points2(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "Sprite": + object = new Sprite2(getMaterial(data2.material)); + break; + case "Group": + object = new Group2; + break; + case "Bone": + object = new Bone2; + break; + default: + object = new Object3D2; + } + object.uuid = data2.uuid; + if (data2.name !== undefined) + object.name = data2.name; + if (data2.matrix !== undefined) { + object.matrix.fromArray(data2.matrix); + if (data2.matrixAutoUpdate !== undefined) + object.matrixAutoUpdate = data2.matrixAutoUpdate; + if (object.matrixAutoUpdate) + object.matrix.decompose(object.position, object.quaternion, object.scale); + } else { + if (data2.position !== undefined) + object.position.fromArray(data2.position); + if (data2.rotation !== undefined) + object.rotation.fromArray(data2.rotation); + if (data2.quaternion !== undefined) + object.quaternion.fromArray(data2.quaternion); + if (data2.scale !== undefined) + object.scale.fromArray(data2.scale); + } + if (data2.up !== undefined) + object.up.fromArray(data2.up); + if (data2.castShadow !== undefined) + object.castShadow = data2.castShadow; + if (data2.receiveShadow !== undefined) + object.receiveShadow = data2.receiveShadow; + if (data2.shadow) { + if (data2.shadow.intensity !== undefined) + object.shadow.intensity = data2.shadow.intensity; + if (data2.shadow.bias !== undefined) + object.shadow.bias = data2.shadow.bias; + if (data2.shadow.normalBias !== undefined) + object.shadow.normalBias = data2.shadow.normalBias; + if (data2.shadow.radius !== undefined) + object.shadow.radius = data2.shadow.radius; + if (data2.shadow.mapSize !== undefined) + object.shadow.mapSize.fromArray(data2.shadow.mapSize); + if (data2.shadow.camera !== undefined) + object.shadow.camera = this.parseObject(data2.shadow.camera); + } + if (data2.visible !== undefined) + object.visible = data2.visible; + if (data2.frustumCulled !== undefined) + object.frustumCulled = data2.frustumCulled; + if (data2.renderOrder !== undefined) + object.renderOrder = data2.renderOrder; + if (data2.userData !== undefined) + object.userData = data2.userData; + if (data2.layers !== undefined) + object.layers.mask = data2.layers; + if (data2.children !== undefined) { + const children = data2.children; + for (let i = 0;i < children.length; i++) { + object.add(this.parseObject(children[i], geometries, materials, textures, animations)); + } + } + if (data2.animations !== undefined) { + const objectAnimations = data2.animations; + for (let i = 0;i < objectAnimations.length; i++) { + const uuid = objectAnimations[i]; + object.animations.push(animations[uuid]); + } + } + if (data2.type === "LOD") { + if (data2.autoUpdate !== undefined) + object.autoUpdate = data2.autoUpdate; + const levels = data2.levels; + for (let l2 = 0;l2 < levels.length; l2++) { + const level = levels[l2]; + const child = object.getObjectByProperty("uuid", level.object); + if (child !== undefined) { + object.addLevel(child, level.distance, level.hysteresis); + } + } + } + return object; + } + bindSkeletons(object, skeletons) { + if (Object.keys(skeletons).length === 0) + return; + object.traverse(function(child) { + if (child.isSkinnedMesh === true && child.skeleton !== undefined) { + const skeleton = skeletons[child.skeleton]; + if (skeleton === undefined) { + console.warn("THREE.ObjectLoader: No skeleton found with UUID:", child.skeleton); + } else { + child.bind(skeleton, child.bindMatrix); + } + } + }); + } + bindLightTargets(object) { + object.traverse(function(child) { + if (child.isDirectionalLight || child.isSpotLight) { + const uuid = child.target; + const target = object.getObjectByProperty("uuid", uuid); + if (target !== undefined) { + child.target = target; + } else { + child.target = new Object3D2; + } + } + }); + } + } + var TEXTURE_MAPPING2 = { + UVMapping: UVMapping2, + CubeReflectionMapping: CubeReflectionMapping2, + CubeRefractionMapping: CubeRefractionMapping2, + EquirectangularReflectionMapping: EquirectangularReflectionMapping2, + EquirectangularRefractionMapping: EquirectangularRefractionMapping2, + CubeUVReflectionMapping: CubeUVReflectionMapping2 + }; + var TEXTURE_WRAPPING2 = { + RepeatWrapping: RepeatWrapping2, + ClampToEdgeWrapping: ClampToEdgeWrapping2, + MirroredRepeatWrapping: MirroredRepeatWrapping2 + }; + var TEXTURE_FILTER2 = { + NearestFilter: NearestFilter2, + NearestMipmapNearestFilter: NearestMipmapNearestFilter2, + NearestMipmapLinearFilter: NearestMipmapLinearFilter2, + LinearFilter: LinearFilter2, + LinearMipmapNearestFilter: LinearMipmapNearestFilter2, + LinearMipmapLinearFilter: LinearMipmapLinearFilter2 + }; + + class ImageBitmapLoader2 extends Loader2 { + constructor(manager) { + super(manager); + this.isImageBitmapLoader = true; + if (typeof createImageBitmap === "undefined") { + console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."); + } + if (typeof fetch === "undefined") { + console.warn("THREE.ImageBitmapLoader: fetch() not supported."); + } + this.options = { premultiplyAlpha: "none" }; + } + setOptions(options) { + this.options = options; + return this; + } + load(url, onLoad, onProgress, onError) { + if (url === undefined) + url = ""; + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache2.get(url); + if (cached !== undefined) { + scope.manager.itemStart(url); + if (cached.then) { + cached.then((imageBitmap) => { + if (onLoad) + onLoad(imageBitmap); + scope.manager.itemEnd(url); + }).catch((e) => { + if (onError) + onError(e); + }); + return; + } + setTimeout(function() { + if (onLoad) + onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const fetchOptions = {}; + fetchOptions.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include"; + fetchOptions.headers = this.requestHeader; + const promise = fetch(url, fetchOptions).then(function(res) { + return res.blob(); + }).then(function(blob) { + return createImageBitmap(blob, Object.assign(scope.options, { colorSpaceConversion: "none" })); + }).then(function(imageBitmap) { + Cache2.add(url, imageBitmap); + if (onLoad) + onLoad(imageBitmap); + scope.manager.itemEnd(url); + return imageBitmap; + }).catch(function(e) { + if (onError) + onError(e); + Cache2.remove(url); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + Cache2.add(url, promise); + scope.manager.itemStart(url); + } + } + var _context2; + + class AudioContext2 { + static getContext() { + if (_context2 === undefined) { + _context2 = new (window.AudioContext || window.webkitAudioContext); + } + return _context2; + } + static setContext(value2) { + _context2 = value2; + } + } + + class AudioLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader2(this.manager); + loader.setResponseType("arraybuffer"); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(buffer) { + try { + const bufferCopy = buffer.slice(0); + const context = AudioContext2.getContext(); + context.decodeAudioData(bufferCopy, function(audioBuffer) { + onLoad(audioBuffer); + }).catch(handleError); + } catch (e) { + handleError(e); + } + }, onProgress, onError); + function handleError(e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + } + } + var _eyeRight2 = /* @__PURE__ */ new Matrix42; + var _eyeLeft2 = /* @__PURE__ */ new Matrix42; + var _projectionMatrix2 = /* @__PURE__ */ new Matrix42; + + class StereoCamera2 { + constructor() { + this.type = "StereoCamera"; + this.aspect = 1; + this.eyeSep = 0.064; + this.cameraL = new PerspectiveCamera2; + this.cameraL.layers.enable(1); + this.cameraL.matrixAutoUpdate = false; + this.cameraR = new PerspectiveCamera2; + this.cameraR.layers.enable(2); + this.cameraR.matrixAutoUpdate = false; + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; + } + update(camera) { + const cache = this._cache; + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + if (needsUpdate) { + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; + _projectionMatrix2.copy(camera.projectionMatrix); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = cache.near * Math.tan(DEG2RAD2 * cache.fov * 0.5) / cache.zoom; + let xmin, xmax; + _eyeLeft2.elements[12] = -eyeSepHalf; + _eyeRight2.elements[12] = eyeSepHalf; + xmin = -ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; + _projectionMatrix2.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix2.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraL.projectionMatrix.copy(_projectionMatrix2); + xmin = -ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + _projectionMatrix2.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix2.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraR.projectionMatrix.copy(_projectionMatrix2); + } + this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft2); + this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight2); + } + } + + class ArrayCamera2 extends PerspectiveCamera2 { + constructor(array = []) { + super(); + this.isArrayCamera = true; + this.cameras = array; + this.index = 0; + } + } + + class Clock2 { + constructor(autoStart = true) { + this.autoStart = autoStart; + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; + this.running = false; + } + start() { + this.startTime = now2(); + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + } + stop() { + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + } + getElapsedTime() { + this.getDelta(); + return this.elapsedTime; + } + getDelta() { + let diff = 0; + if (this.autoStart && !this.running) { + this.start(); + return 0; + } + if (this.running) { + const newTime = now2(); + diff = (newTime - this.oldTime) / 1000; + this.oldTime = newTime; + this.elapsedTime += diff; + } + return diff; + } + } + function now2() { + return performance.now(); + } + var _position$12 = /* @__PURE__ */ new Vector32; + var _quaternion$12 = /* @__PURE__ */ new Quaternion2; + var _scale$12 = /* @__PURE__ */ new Vector32; + var _orientation$12 = /* @__PURE__ */ new Vector32; + + class AudioListener2 extends Object3D2 { + constructor() { + super(); + this.type = "AudioListener"; + this.context = AudioContext2.getContext(); + this.gain = this.context.createGain(); + this.gain.connect(this.context.destination); + this.filter = null; + this.timeDelta = 0; + this._clock = new Clock2; + } + getInput() { + return this.gain; + } + removeFilter() { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + this.gain.connect(this.context.destination); + this.filter = null; + } + return this; + } + getFilter() { + return this.filter; + } + setFilter(value2) { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + } else { + this.gain.disconnect(this.context.destination); + } + this.filter = value2; + this.gain.connect(this.filter); + this.filter.connect(this.context.destination); + return this; + } + getMasterVolume() { + return this.gain.gain.value; + } + setMasterVolume(value2) { + this.gain.gain.setTargetAtTime(value2, this.context.currentTime, 0.01); + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + const listener = this.context.listener; + const up = this.up; + this.timeDelta = this._clock.getDelta(); + this.matrixWorld.decompose(_position$12, _quaternion$12, _scale$12); + _orientation$12.set(0, 0, -1).applyQuaternion(_quaternion$12); + if (listener.positionX) { + const endTime = this.context.currentTime + this.timeDelta; + listener.positionX.linearRampToValueAtTime(_position$12.x, endTime); + listener.positionY.linearRampToValueAtTime(_position$12.y, endTime); + listener.positionZ.linearRampToValueAtTime(_position$12.z, endTime); + listener.forwardX.linearRampToValueAtTime(_orientation$12.x, endTime); + listener.forwardY.linearRampToValueAtTime(_orientation$12.y, endTime); + listener.forwardZ.linearRampToValueAtTime(_orientation$12.z, endTime); + listener.upX.linearRampToValueAtTime(up.x, endTime); + listener.upY.linearRampToValueAtTime(up.y, endTime); + listener.upZ.linearRampToValueAtTime(up.z, endTime); + } else { + listener.setPosition(_position$12.x, _position$12.y, _position$12.z); + listener.setOrientation(_orientation$12.x, _orientation$12.y, _orientation$12.z, up.x, up.y, up.z); + } + } + } + + class Audio2 extends Object3D2 { + constructor(listener) { + super(); + this.type = "Audio"; + this.listener = listener; + this.context = listener.context; + this.gain = this.context.createGain(); + this.gain.connect(listener.getInput()); + this.autoplay = false; + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = undefined; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = "empty"; + this._startedAt = 0; + this._progress = 0; + this._connected = false; + this.filters = []; + } + getOutput() { + return this.gain; + } + setNodeSource(audioNode) { + this.hasPlaybackControl = false; + this.sourceType = "audioNode"; + this.source = audioNode; + this.connect(); + return this; + } + setMediaElementSource(mediaElement) { + this.hasPlaybackControl = false; + this.sourceType = "mediaNode"; + this.source = this.context.createMediaElementSource(mediaElement); + this.connect(); + return this; + } + setMediaStreamSource(mediaStream) { + this.hasPlaybackControl = false; + this.sourceType = "mediaStreamNode"; + this.source = this.context.createMediaStreamSource(mediaStream); + this.connect(); + return this; + } + setBuffer(audioBuffer) { + this.buffer = audioBuffer; + this.sourceType = "buffer"; + if (this.autoplay) + this.play(); + return this; + } + play(delay = 0) { + if (this.isPlaying === true) { + console.warn("THREE.Audio: Audio is already playing."); + return; + } + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._startedAt = this.context.currentTime + delay; + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind(this); + source.start(this._startedAt, this._progress + this.offset, this.duration); + this.isPlaying = true; + this.source = source; + this.setDetune(this.detune); + this.setPlaybackRate(this.playbackRate); + return this.connect(); + } + pause() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + if (this.isPlaying === true) { + this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate; + if (this.loop === true) { + this._progress = this._progress % (this.duration || this.buffer.duration); + } + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; + } + return this; + } + stop(delay = 0) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._progress = 0; + if (this.source !== null) { + this.source.stop(this.context.currentTime + delay); + this.source.onended = null; + } + this.isPlaying = false; + return this; + } + connect() { + if (this.filters.length > 0) { + this.source.connect(this.filters[0]); + for (let i = 1, l2 = this.filters.length;i < l2; i++) { + this.filters[i - 1].connect(this.filters[i]); + } + this.filters[this.filters.length - 1].connect(this.getOutput()); + } else { + this.source.connect(this.getOutput()); + } + this._connected = true; + return this; + } + disconnect() { + if (this._connected === false) { + return; + } + if (this.filters.length > 0) { + this.source.disconnect(this.filters[0]); + for (let i = 1, l2 = this.filters.length;i < l2; i++) { + this.filters[i - 1].disconnect(this.filters[i]); + } + this.filters[this.filters.length - 1].disconnect(this.getOutput()); + } else { + this.source.disconnect(this.getOutput()); + } + this._connected = false; + return this; + } + getFilters() { + return this.filters; + } + setFilters(value2) { + if (!value2) + value2 = []; + if (this._connected === true) { + this.disconnect(); + this.filters = value2.slice(); + this.connect(); + } else { + this.filters = value2.slice(); + } + return this; + } + setDetune(value2) { + this.detune = value2; + if (this.isPlaying === true && this.source.detune !== undefined) { + this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01); + } + return this; + } + getDetune() { + return this.detune; + } + getFilter() { + return this.getFilters()[0]; + } + setFilter(filter2) { + return this.setFilters(filter2 ? [filter2] : []); + } + setPlaybackRate(value2) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.playbackRate = value2; + if (this.isPlaying === true) { + this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01); + } + return this; + } + getPlaybackRate() { + return this.playbackRate; + } + onEnded() { + this.isPlaying = false; + this._progress = 0; + } + getLoop() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return false; + } + return this.loop; + } + setLoop(value2) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.loop = value2; + if (this.isPlaying === true) { + this.source.loop = this.loop; + } + return this; + } + setLoopStart(value2) { + this.loopStart = value2; + return this; + } + setLoopEnd(value2) { + this.loopEnd = value2; + return this; + } + getVolume() { + return this.gain.gain.value; + } + setVolume(value2) { + this.gain.gain.setTargetAtTime(value2, this.context.currentTime, 0.01); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.sourceType !== "buffer") { + console.warn("THREE.Audio: Audio source type cannot be copied."); + return this; + } + this.autoplay = source.autoplay; + this.buffer = source.buffer; + this.detune = source.detune; + this.loop = source.loop; + this.loopStart = source.loopStart; + this.loopEnd = source.loopEnd; + this.offset = source.offset; + this.duration = source.duration; + this.playbackRate = source.playbackRate; + this.hasPlaybackControl = source.hasPlaybackControl; + this.sourceType = source.sourceType; + this.filters = source.filters.slice(); + return this; + } + clone(recursive) { + return new this.constructor(this.listener).copy(this, recursive); + } + } + var _position3 = /* @__PURE__ */ new Vector32; + var _quaternion5 = /* @__PURE__ */ new Quaternion2; + var _scale5 = /* @__PURE__ */ new Vector32; + var _orientation2 = /* @__PURE__ */ new Vector32; + + class PositionalAudio2 extends Audio2 { + constructor(listener) { + super(listener); + this.panner = this.context.createPanner(); + this.panner.panningModel = "HRTF"; + this.panner.connect(this.gain); + } + connect() { + super.connect(); + this.panner.connect(this.gain); + } + disconnect() { + super.disconnect(); + this.panner.disconnect(this.gain); + } + getOutput() { + return this.panner; + } + getRefDistance() { + return this.panner.refDistance; + } + setRefDistance(value2) { + this.panner.refDistance = value2; + return this; + } + getRolloffFactor() { + return this.panner.rolloffFactor; + } + setRolloffFactor(value2) { + this.panner.rolloffFactor = value2; + return this; + } + getDistanceModel() { + return this.panner.distanceModel; + } + setDistanceModel(value2) { + this.panner.distanceModel = value2; + return this; + } + getMaxDistance() { + return this.panner.maxDistance; + } + setMaxDistance(value2) { + this.panner.maxDistance = value2; + return this; + } + setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) { + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.hasPlaybackControl === true && this.isPlaying === false) + return; + this.matrixWorld.decompose(_position3, _quaternion5, _scale5); + _orientation2.set(0, 0, 1).applyQuaternion(_quaternion5); + const panner = this.panner; + if (panner.positionX) { + const endTime = this.context.currentTime + this.listener.timeDelta; + panner.positionX.linearRampToValueAtTime(_position3.x, endTime); + panner.positionY.linearRampToValueAtTime(_position3.y, endTime); + panner.positionZ.linearRampToValueAtTime(_position3.z, endTime); + panner.orientationX.linearRampToValueAtTime(_orientation2.x, endTime); + panner.orientationY.linearRampToValueAtTime(_orientation2.y, endTime); + panner.orientationZ.linearRampToValueAtTime(_orientation2.z, endTime); + } else { + panner.setPosition(_position3.x, _position3.y, _position3.z); + panner.setOrientation(_orientation2.x, _orientation2.y, _orientation2.z); + } + } + } + + class AudioAnalyser2 { + constructor(audio, fftSize = 2048) { + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; + this.data = new Uint8Array(this.analyser.frequencyBinCount); + audio.getOutput().connect(this.analyser); + } + getFrequencyData() { + this.analyser.getByteFrequencyData(this.data); + return this.data; + } + getAverageFrequency() { + let value2 = 0; + const data2 = this.getFrequencyData(); + for (let i = 0;i < data2.length; i++) { + value2 += data2[i]; + } + return value2 / data2.length; + } + } + + class PropertyMixer2 { + constructor(binding, typeName, valueSize) { + this.binding = binding; + this.valueSize = valueSize; + let mixFunction, mixFunctionAdditive, setIdentity; + switch (typeName) { + case "quaternion": + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; + this.buffer = new Float64Array(valueSize * 6); + this._workIndex = 5; + break; + case "string": + case "bool": + mixFunction = this._select; + mixFunctionAdditive = this._select; + setIdentity = this._setAdditiveIdentityOther; + this.buffer = new Array(valueSize * 5); + break; + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; + this.buffer = new Float64Array(valueSize * 5); + } + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + this.useCount = 0; + this.referenceCount = 0; + } + accumulate(accuIndex, weight) { + const buffer = this.buffer, stride = this.valueSize, offset = accuIndex * stride + stride; + let currentWeight = this.cumulativeWeight; + if (currentWeight === 0) { + for (let i = 0;i !== stride; ++i) { + buffer[offset + i] = buffer[i]; + } + currentWeight = weight; + } else { + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion(buffer, offset, 0, mix, stride); + } + this.cumulativeWeight = currentWeight; + } + accumulateAdditive(weight) { + const buffer = this.buffer, stride = this.valueSize, offset = stride * this._addIndex; + if (this.cumulativeWeightAdditive === 0) { + this._setIdentity(); + } + this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride); + this.cumulativeWeightAdditive += weight; + } + apply(accuIndex) { + const stride = this.valueSize, buffer = this.buffer, offset = accuIndex * stride + stride, weight = this.cumulativeWeight, weightAdditive = this.cumulativeWeightAdditive, binding = this.binding; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + if (weight < 1) { + const originalValueOffset = stride * this._origIndex; + this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride); + } + if (weightAdditive > 0) { + this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride); + } + for (let i = stride, e = stride + stride;i !== e; ++i) { + if (buffer[i] !== buffer[i + stride]) { + binding.setValue(buffer, offset); + break; + } + } + } + saveOriginalState() { + const binding = this.binding; + const buffer = this.buffer, stride = this.valueSize, originalValueOffset = stride * this._origIndex; + binding.getValue(buffer, originalValueOffset); + for (let i = stride, e = originalValueOffset;i !== e; ++i) { + buffer[i] = buffer[originalValueOffset + i % stride]; + } + this._setIdentity(); + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + } + restoreOriginalState() { + const originalValueOffset = this.valueSize * 3; + this.binding.setValue(this.buffer, originalValueOffset); + } + _setAdditiveIdentityNumeric() { + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; + for (let i = startIndex;i < endIndex; i++) { + this.buffer[i] = 0; + } + } + _setAdditiveIdentityQuaternion() { + this._setAdditiveIdentityNumeric(); + this.buffer[this._addIndex * this.valueSize + 3] = 1; + } + _setAdditiveIdentityOther() { + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; + for (let i = 0;i < this.valueSize; i++) { + this.buffer[targetIndex + i] = this.buffer[startIndex + i]; + } + } + _select(buffer, dstOffset, srcOffset, t4, stride) { + if (t4 >= 0.5) { + for (let i = 0;i !== stride; ++i) { + buffer[dstOffset + i] = buffer[srcOffset + i]; + } + } + } + _slerp(buffer, dstOffset, srcOffset, t4) { + Quaternion2.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t4); + } + _slerpAdditive(buffer, dstOffset, srcOffset, t4, stride) { + const workOffset = this._workIndex * stride; + Quaternion2.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); + Quaternion2.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t4); + } + _lerp(buffer, dstOffset, srcOffset, t4, stride) { + const s = 1 - t4; + for (let i = 0;i !== stride; ++i) { + const j2 = dstOffset + i; + buffer[j2] = buffer[j2] * s + buffer[srcOffset + i] * t4; + } + } + _lerpAdditive(buffer, dstOffset, srcOffset, t4, stride) { + for (let i = 0;i !== stride; ++i) { + const j2 = dstOffset + i; + buffer[j2] = buffer[j2] + buffer[srcOffset + i] * t4; + } + } + } + var _RESERVED_CHARS_RE2 = "\\[\\]\\.:\\/"; + var _reservedRe2 = new RegExp("[" + _RESERVED_CHARS_RE2 + "]", "g"); + var _wordChar2 = "[^" + _RESERVED_CHARS_RE2 + "]"; + var _wordCharOrDot2 = "[^" + _RESERVED_CHARS_RE2.replace("\\.", "") + "]"; + var _directoryRe2 = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", _wordChar2); + var _nodeRe2 = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", _wordCharOrDot2); + var _objectRe2 = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", _wordChar2); + var _propertyRe2 = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", _wordChar2); + var _trackRe2 = new RegExp("" + "^" + _directoryRe2 + _nodeRe2 + _objectRe2 + _propertyRe2 + "$"); + var _supportedObjectNames2 = ["material", "materials", "bones", "map"]; + + class Composite2 { + constructor(targetGroup, path, optionalParsedPath) { + const parsedPath = optionalParsedPath || PropertyBinding2.parseTrackName(path); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_(path, parsedPath); + } + getValue(array, offset) { + this.bind(); + const firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[firstValidIndex]; + if (binding !== undefined) + binding.getValue(array, offset); + } + setValue(array, offset) { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n2 = bindings.length;i !== n2; ++i) { + bindings[i].setValue(array, offset); + } + } + bind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n2 = bindings.length;i !== n2; ++i) { + bindings[i].bind(); + } + } + unbind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n2 = bindings.length;i !== n2; ++i) { + bindings[i].unbind(); + } + } + } + + class PropertyBinding2 { + constructor(rootNode, path, parsedPath) { + this.path = path; + this.parsedPath = parsedPath || PropertyBinding2.parseTrackName(path); + this.node = PropertyBinding2.findNode(rootNode, this.parsedPath.nodeName); + this.rootNode = rootNode; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + static create(root2, path, parsedPath) { + if (!(root2 && root2.isAnimationObjectGroup)) { + return new PropertyBinding2(root2, path, parsedPath); + } else { + return new PropertyBinding2.Composite(root2, path, parsedPath); + } + } + static sanitizeNodeName(name2) { + return name2.replace(/\s/g, "_").replace(_reservedRe2, ""); + } + static parseTrackName(trackName) { + const matches = _trackRe2.exec(trackName); + if (matches === null) { + throw new Error("PropertyBinding: Cannot parse trackName: " + trackName); + } + const results = { + nodeName: matches[2], + objectName: matches[3], + objectIndex: matches[4], + propertyName: matches[5], + propertyIndex: matches[6] + }; + const lastDot = results.nodeName && results.nodeName.lastIndexOf("."); + if (lastDot !== undefined && lastDot !== -1) { + const objectName = results.nodeName.substring(lastDot + 1); + if (_supportedObjectNames2.indexOf(objectName) !== -1) { + results.nodeName = results.nodeName.substring(0, lastDot); + results.objectName = objectName; + } + } + if (results.propertyName === null || results.propertyName.length === 0) { + throw new Error("PropertyBinding: can not parse propertyName from trackName: " + trackName); + } + return results; + } + static findNode(root2, nodeName) { + if (nodeName === undefined || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root2.name || nodeName === root2.uuid) { + return root2; + } + if (root2.skeleton) { + const bone = root2.skeleton.getBoneByName(nodeName); + if (bone !== undefined) { + return bone; + } + } + if (root2.children) { + const searchNodeSubtree = function(children) { + for (let i = 0;i < children.length; i++) { + const childNode = children[i]; + if (childNode.name === nodeName || childNode.uuid === nodeName) { + return childNode; + } + const result = searchNodeSubtree(childNode.children); + if (result) + return result; + } + return null; + }; + const subTreeNode = searchNodeSubtree(root2.children); + if (subTreeNode) { + return subTreeNode; + } + } + return null; + } + _getValue_unavailable() { + } + _setValue_unavailable() { + } + _getValue_direct(buffer, offset) { + buffer[offset] = this.targetObject[this.propertyName]; + } + _getValue_array(buffer, offset) { + const source = this.resolvedProperty; + for (let i = 0, n2 = source.length;i !== n2; ++i) { + buffer[offset++] = source[i]; + } + } + _getValue_arrayElement(buffer, offset) { + buffer[offset] = this.resolvedProperty[this.propertyIndex]; + } + _getValue_toArray(buffer, offset) { + this.resolvedProperty.toArray(buffer, offset); + } + _setValue_direct(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + } + _setValue_direct_setNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_array(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n2 = dest.length;i !== n2; ++i) { + dest[i] = buffer[offset++]; + } + } + _setValue_array_setNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n2 = dest.length;i !== n2; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.needsUpdate = true; + } + _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n2 = dest.length;i !== n2; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_arrayElement(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + } + _setValue_arrayElement_setNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_fromArray(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + } + _setValue_fromArray_setNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.needsUpdate = true; + } + _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.matrixWorldNeedsUpdate = true; + } + _getValue_unbound(targetArray, offset) { + this.bind(); + this.getValue(targetArray, offset); + } + _setValue_unbound(sourceArray, offset) { + this.bind(); + this.setValue(sourceArray, offset); + } + bind() { + let targetObject = this.node; + const parsedPath = this.parsedPath; + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + if (!targetObject) { + targetObject = PropertyBinding2.findNode(this.rootNode, parsedPath.nodeName); + this.node = targetObject; + } + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; + if (!targetObject) { + console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + "."); + return; + } + if (objectName) { + let objectIndex = parsedPath.objectIndex; + switch (objectName) { + case "materials": + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.materials) { + console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this); + return; + } + targetObject = targetObject.material.materials; + break; + case "bones": + if (!targetObject.skeleton) { + console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this); + return; + } + targetObject = targetObject.skeleton.bones; + for (let i = 0;i < targetObject.length; i++) { + if (targetObject[i].name === objectIndex) { + objectIndex = i; + break; + } + } + break; + case "map": + if ("map" in targetObject) { + targetObject = targetObject.map; + break; + } + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.map) { + console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this); + return; + } + targetObject = targetObject.material.map; + break; + default: + if (targetObject[objectName] === undefined) { + console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this); + return; + } + targetObject = targetObject[objectName]; + } + if (objectIndex !== undefined) { + if (targetObject[objectIndex] === undefined) { + console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, targetObject); + return; + } + targetObject = targetObject[objectIndex]; + } + } + const nodeProperty = targetObject[propertyName]; + if (nodeProperty === undefined) { + const nodeName = parsedPath.nodeName; + console.error("THREE.PropertyBinding: Trying to update property for track: " + nodeName + "." + propertyName + " but it wasn't found.", targetObject); + return; + } + let versioning = this.Versioning.None; + this.targetObject = targetObject; + if (targetObject.isMaterial === true) { + versioning = this.Versioning.NeedsUpdate; + } else if (targetObject.isObject3D === true) { + versioning = this.Versioning.MatrixWorldNeedsUpdate; + } + let bindingType = this.BindingType.Direct; + if (propertyIndex !== undefined) { + if (propertyName === "morphTargetInfluences") { + if (!targetObject.geometry) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this); + return; + } + if (!targetObject.geometry.morphAttributes) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this); + return; + } + if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) { + propertyIndex = targetObject.morphTargetDictionary[propertyIndex]; + } + } + bindingType = this.BindingType.ArrayElement; + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) { + bindingType = this.BindingType.HasFromToArray; + this.resolvedProperty = nodeProperty; + } else if (Array.isArray(nodeProperty)) { + bindingType = this.BindingType.EntireArray; + this.resolvedProperty = nodeProperty; + } else { + this.propertyName = propertyName; + } + this.getValue = this.GetterByBindingType[bindingType]; + this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning]; + } + unbind() { + this.node = null; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + } + PropertyBinding2.Composite = Composite2; + PropertyBinding2.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 + }; + PropertyBinding2.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 + }; + PropertyBinding2.prototype.GetterByBindingType = [ + PropertyBinding2.prototype._getValue_direct, + PropertyBinding2.prototype._getValue_array, + PropertyBinding2.prototype._getValue_arrayElement, + PropertyBinding2.prototype._getValue_toArray + ]; + PropertyBinding2.prototype.SetterByBindingTypeAndVersioning = [ + [ + PropertyBinding2.prototype._setValue_direct, + PropertyBinding2.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding2.prototype._setValue_direct_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding2.prototype._setValue_array, + PropertyBinding2.prototype._setValue_array_setNeedsUpdate, + PropertyBinding2.prototype._setValue_array_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding2.prototype._setValue_arrayElement, + PropertyBinding2.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding2.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding2.prototype._setValue_fromArray, + PropertyBinding2.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding2.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate + ] + ]; + + class AnimationObjectGroup2 { + constructor() { + this.isAnimationObjectGroup = true; + this.uuid = generateUUID2(); + this._objects = Array.prototype.slice.call(arguments); + this.nCachedObjects_ = 0; + const indices = {}; + this._indicesByUUID = indices; + for (let i = 0, n2 = arguments.length;i !== n2; ++i) { + indices[arguments[i].uuid] = i; + } + this._paths = []; + this._parsedPaths = []; + this._bindings = []; + this._bindingsIndicesByPath = {}; + const scope = this; + this.stats = { + objects: { + get total() { + return scope._objects.length; + }, + get inUse() { + return this.total - scope.nCachedObjects_; + } + }, + get bindingsPerObject() { + return scope._bindings.length; + } + }; + } + add() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, nBindings = bindings.length; + let knownObject = undefined, nObjects = objects.length, nCachedObjects = this.nCachedObjects_; + for (let i = 0, n2 = arguments.length;i !== n2; ++i) { + const object = arguments[i], uuid = object.uuid; + let index2 = indicesByUUID[uuid]; + if (index2 === undefined) { + index2 = nObjects++; + indicesByUUID[uuid] = index2; + objects.push(object); + for (let j2 = 0, m = nBindings;j2 !== m; ++j2) { + bindings[j2].push(new PropertyBinding2(object, paths[j2], parsedPaths[j2])); + } + } else if (index2 < nCachedObjects) { + knownObject = objects[index2]; + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex]; + indicesByUUID[lastCachedObject.uuid] = index2; + objects[index2] = lastCachedObject; + indicesByUUID[uuid] = firstActiveIndex; + objects[firstActiveIndex] = object; + for (let j2 = 0, m = nBindings;j2 !== m; ++j2) { + const bindingsForPath = bindings[j2], lastCached = bindingsForPath[firstActiveIndex]; + let binding = bindingsForPath[index2]; + bindingsForPath[index2] = lastCached; + if (binding === undefined) { + binding = new PropertyBinding2(object, paths[j2], parsedPaths[j2]); + } + bindingsForPath[firstActiveIndex] = binding; + } + } else if (objects[index2] !== knownObject) { + console.error("THREE.AnimationObjectGroup: Different objects with the same UUID " + "detected. Clean the caches or recreate your infrastructure when reloading scenes."); + } + } + this.nCachedObjects_ = nCachedObjects; + } + remove() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_; + for (let i = 0, n2 = arguments.length;i !== n2; ++i) { + const object = arguments[i], uuid = object.uuid, index2 = indicesByUUID[uuid]; + if (index2 !== undefined && index2 >= nCachedObjects) { + const lastCachedIndex = nCachedObjects++, firstActiveObject = objects[lastCachedIndex]; + indicesByUUID[firstActiveObject.uuid] = index2; + objects[index2] = firstActiveObject; + indicesByUUID[uuid] = lastCachedIndex; + objects[lastCachedIndex] = object; + for (let j2 = 0, m = nBindings;j2 !== m; ++j2) { + const bindingsForPath = bindings[j2], firstActive = bindingsForPath[lastCachedIndex], binding = bindingsForPath[index2]; + bindingsForPath[index2] = firstActive; + bindingsForPath[lastCachedIndex] = binding; + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + uncache() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_, nObjects = objects.length; + for (let i = 0, n2 = arguments.length;i !== n2; ++i) { + const object = arguments[i], uuid = object.uuid, index2 = indicesByUUID[uuid]; + if (index2 !== undefined) { + delete indicesByUUID[uuid]; + if (index2 < nCachedObjects) { + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex], lastIndex = --nObjects, lastObject = objects[lastIndex]; + indicesByUUID[lastCachedObject.uuid] = index2; + objects[index2] = lastCachedObject; + indicesByUUID[lastObject.uuid] = firstActiveIndex; + objects[firstActiveIndex] = lastObject; + objects.pop(); + for (let j2 = 0, m = nBindings;j2 !== m; ++j2) { + const bindingsForPath = bindings[j2], lastCached = bindingsForPath[firstActiveIndex], last2 = bindingsForPath[lastIndex]; + bindingsForPath[index2] = lastCached; + bindingsForPath[firstActiveIndex] = last2; + bindingsForPath.pop(); + } + } else { + const lastIndex = --nObjects, lastObject = objects[lastIndex]; + if (lastIndex > 0) { + indicesByUUID[lastObject.uuid] = index2; + } + objects[index2] = lastObject; + objects.pop(); + for (let j2 = 0, m = nBindings;j2 !== m; ++j2) { + const bindingsForPath = bindings[j2]; + bindingsForPath[index2] = bindingsForPath[lastIndex]; + bindingsForPath.pop(); + } + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + subscribe_(path, parsedPath) { + const indicesByPath = this._bindingsIndicesByPath; + let index2 = indicesByPath[path]; + const bindings = this._bindings; + if (index2 !== undefined) + return bindings[index2]; + const paths = this._paths, parsedPaths = this._parsedPaths, objects = this._objects, nObjects = objects.length, nCachedObjects = this.nCachedObjects_, bindingsForPath = new Array(nObjects); + index2 = bindings.length; + indicesByPath[path] = index2; + paths.push(path); + parsedPaths.push(parsedPath); + bindings.push(bindingsForPath); + for (let i = nCachedObjects, n2 = objects.length;i !== n2; ++i) { + const object = objects[i]; + bindingsForPath[i] = new PropertyBinding2(object, path, parsedPath); + } + return bindingsForPath; + } + unsubscribe_(path) { + const indicesByPath = this._bindingsIndicesByPath, index2 = indicesByPath[path]; + if (index2 !== undefined) { + const paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, lastBindingsIndex = bindings.length - 1, lastBindings = bindings[lastBindingsIndex], lastBindingsPath = path[lastBindingsIndex]; + indicesByPath[lastBindingsPath] = index2; + bindings[index2] = lastBindings; + bindings.pop(); + parsedPaths[index2] = parsedPaths[lastBindingsIndex]; + parsedPaths.pop(); + paths[index2] = paths[lastBindingsIndex]; + paths.pop(); + } + } + } + + class AnimationAction2 { + constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) { + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; + const tracks = clip.tracks, nTracks = tracks.length, interpolants = new Array(nTracks); + const interpolantSettings = { + endingStart: ZeroCurvatureEnding2, + endingEnd: ZeroCurvatureEnding2 + }; + for (let i = 0;i !== nTracks; ++i) { + const interpolant = tracks[i].createInterpolant(null); + interpolants[i] = interpolant; + interpolant.settings = interpolantSettings; + } + this._interpolantSettings = interpolantSettings; + this._interpolants = interpolants; + this._propertyBindings = new Array(nTracks); + this._cacheIndex = null; + this._byClipCacheIndex = null; + this._timeScaleInterpolant = null; + this._weightInterpolant = null; + this.loop = LoopRepeat2; + this._loopCount = -1; + this._startTime = null; + this.time = 0; + this.timeScale = 1; + this._effectiveTimeScale = 1; + this.weight = 1; + this._effectiveWeight = 1; + this.repetitions = Infinity; + this.paused = false; + this.enabled = true; + this.clampWhenFinished = false; + this.zeroSlopeAtStart = true; + this.zeroSlopeAtEnd = true; + } + play() { + this._mixer._activateAction(this); + return this; + } + stop() { + this._mixer._deactivateAction(this); + return this.reset(); + } + reset() { + this.paused = false; + this.enabled = true; + this.time = 0; + this._loopCount = -1; + this._startTime = null; + return this.stopFading().stopWarping(); + } + isRunning() { + return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this); + } + isScheduled() { + return this._mixer._isActiveAction(this); + } + startAt(time2) { + this._startTime = time2; + return this; + } + setLoop(mode, repetitions) { + this.loop = mode; + this.repetitions = repetitions; + return this; + } + setEffectiveWeight(weight) { + this.weight = weight; + this._effectiveWeight = this.enabled ? weight : 0; + return this.stopFading(); + } + getEffectiveWeight() { + return this._effectiveWeight; + } + fadeIn(duration) { + return this._scheduleFading(duration, 0, 1); + } + fadeOut(duration) { + return this._scheduleFading(duration, 1, 0); + } + crossFadeFrom(fadeOutAction, duration, warp) { + fadeOutAction.fadeOut(duration); + this.fadeIn(duration); + if (warp) { + const fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, startEndRatio = fadeOutDuration / fadeInDuration, endStartRatio = fadeInDuration / fadeOutDuration; + fadeOutAction.warp(1, startEndRatio, duration); + this.warp(endStartRatio, 1, duration); + } + return this; + } + crossFadeTo(fadeInAction, duration, warp) { + return fadeInAction.crossFadeFrom(this, duration, warp); + } + stopFading() { + const weightInterpolant = this._weightInterpolant; + if (weightInterpolant !== null) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant(weightInterpolant); + } + return this; + } + setEffectiveTimeScale(timeScale) { + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; + return this.stopWarping(); + } + getEffectiveTimeScale() { + return this._effectiveTimeScale; + } + setDuration(duration) { + this.timeScale = this._clip.duration / duration; + return this.stopWarping(); + } + syncWith(action) { + this.time = action.time; + this.timeScale = action.timeScale; + return this.stopWarping(); + } + halt(duration) { + return this.warp(this._effectiveTimeScale, 0, duration); + } + warp(startTimeScale, endTimeScale, duration) { + const mixer = this._mixer, now3 = mixer.time, timeScale = this.timeScale; + let interpolant = this._timeScaleInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; + } + const { parameterPositions: times, sampleValues: values2 } = interpolant; + times[0] = now3; + times[1] = now3 + duration; + values2[0] = startTimeScale / timeScale; + values2[1] = endTimeScale / timeScale; + return this; + } + stopWarping() { + const timeScaleInterpolant = this._timeScaleInterpolant; + if (timeScaleInterpolant !== null) { + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant(timeScaleInterpolant); + } + return this; + } + getMixer() { + return this._mixer; + } + getClip() { + return this._clip; + } + getRoot() { + return this._localRoot || this._mixer._root; + } + _update(time2, deltaTime, timeDirection, accuIndex) { + if (!this.enabled) { + this._updateWeight(time2); + return; + } + const startTime = this._startTime; + if (startTime !== null) { + const timeRunning = (time2 - startTime) * timeDirection; + if (timeRunning < 0 || timeDirection === 0) { + deltaTime = 0; + } else { + this._startTime = null; + deltaTime = timeDirection * timeRunning; + } + } + deltaTime *= this._updateTimeScale(time2); + const clipTime = this._updateTime(deltaTime); + const weight = this._updateWeight(time2); + if (weight > 0) { + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; + switch (this.blendMode) { + case AdditiveAnimationBlendMode2: + for (let j2 = 0, m = interpolants.length;j2 !== m; ++j2) { + interpolants[j2].evaluate(clipTime); + propertyMixers[j2].accumulateAdditive(weight); + } + break; + case NormalAnimationBlendMode2: + default: + for (let j2 = 0, m = interpolants.length;j2 !== m; ++j2) { + interpolants[j2].evaluate(clipTime); + propertyMixers[j2].accumulate(accuIndex, weight); + } + } + } + } + _updateWeight(time2) { + let weight = 0; + if (this.enabled) { + weight = this.weight; + const interpolant = this._weightInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time2)[0]; + weight *= interpolantValue; + if (time2 > interpolant.parameterPositions[1]) { + this.stopFading(); + if (interpolantValue === 0) { + this.enabled = false; + } + } + } + } + this._effectiveWeight = weight; + return weight; + } + _updateTimeScale(time2) { + let timeScale = 0; + if (!this.paused) { + timeScale = this.timeScale; + const interpolant = this._timeScaleInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time2)[0]; + timeScale *= interpolantValue; + if (time2 > interpolant.parameterPositions[1]) { + this.stopWarping(); + if (timeScale === 0) { + this.paused = true; + } else { + this.timeScale = timeScale; + } + } + } + } + this._effectiveTimeScale = timeScale; + return timeScale; + } + _updateTime(deltaTime) { + const duration = this._clip.duration; + const loop = this.loop; + let time2 = this.time + deltaTime; + let loopCount = this._loopCount; + const pingPong = loop === LoopPingPong2; + if (deltaTime === 0) { + if (loopCount === -1) + return time2; + return pingPong && (loopCount & 1) === 1 ? duration - time2 : time2; + } + if (loop === LoopOnce2) { + if (loopCount === -1) { + this._loopCount = 0; + this._setEndings(true, true, false); + } + handle_stop: { + if (time2 >= duration) { + time2 = duration; + } else if (time2 < 0) { + time2 = 0; + } else { + this.time = time2; + break handle_stop; + } + if (this.clampWhenFinished) + this.paused = true; + else + this.enabled = false; + this.time = time2; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime < 0 ? -1 : 1 + }); + } + } else { + if (loopCount === -1) { + if (deltaTime >= 0) { + loopCount = 0; + this._setEndings(true, this.repetitions === 0, pingPong); + } else { + this._setEndings(this.repetitions === 0, true, pingPong); + } + } + if (time2 >= duration || time2 < 0) { + const loopDelta = Math.floor(time2 / duration); + time2 -= duration * loopDelta; + loopCount += Math.abs(loopDelta); + const pending = this.repetitions - loopCount; + if (pending <= 0) { + if (this.clampWhenFinished) + this.paused = true; + else + this.enabled = false; + time2 = deltaTime > 0 ? duration : 0; + this.time = time2; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime > 0 ? 1 : -1 + }); + } else { + if (pending === 1) { + const atStart = deltaTime < 0; + this._setEndings(atStart, !atStart, pingPong); + } else { + this._setEndings(false, false, pingPong); + } + this._loopCount = loopCount; + this.time = time2; + this._mixer.dispatchEvent({ + type: "loop", + action: this, + loopDelta + }); + } + } else { + this.time = time2; + } + if (pingPong && (loopCount & 1) === 1) { + return duration - time2; + } + } + return time2; + } + _setEndings(atStart, atEnd, pingPong) { + const settings = this._interpolantSettings; + if (pingPong) { + settings.endingStart = ZeroSlopeEnding2; + settings.endingEnd = ZeroSlopeEnding2; + } else { + if (atStart) { + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding2 : ZeroCurvatureEnding2; + } else { + settings.endingStart = WrapAroundEnding2; + } + if (atEnd) { + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding2 : ZeroCurvatureEnding2; + } else { + settings.endingEnd = WrapAroundEnding2; + } + } + } + _scheduleFading(duration, weightNow, weightThen) { + const mixer = this._mixer, now3 = mixer.time; + let interpolant = this._weightInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; + } + const { parameterPositions: times, sampleValues: values2 } = interpolant; + times[0] = now3; + values2[0] = weightNow; + times[1] = now3 + duration; + values2[1] = weightThen; + return this; + } + } + var _controlInterpolantsResultBuffer2 = new Float32Array(1); + + class AnimationMixer2 extends EventDispatcher2 { + constructor(root2) { + super(); + this._root = root2; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1; + } + _bindAction(action, prototypeAction) { + const root2 = action._localRoot || this._root, tracks = action._clip.tracks, nTracks = tracks.length, bindings = action._propertyBindings, interpolants = action._interpolants, rootUuid = root2.uuid, bindingsByRoot = this._bindingsByRootAndName; + let bindingsByName = bindingsByRoot[rootUuid]; + if (bindingsByName === undefined) { + bindingsByName = {}; + bindingsByRoot[rootUuid] = bindingsByName; + } + for (let i = 0;i !== nTracks; ++i) { + const track = tracks[i], trackName = track.name; + let binding = bindingsByName[trackName]; + if (binding !== undefined) { + ++binding.referenceCount; + bindings[i] = binding; + } else { + binding = bindings[i]; + if (binding !== undefined) { + if (binding._cacheIndex === null) { + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + } + continue; + } + const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath; + binding = new PropertyMixer2(PropertyBinding2.create(root2, trackName, path), track.ValueTypeName, track.getValueSize()); + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + bindings[i] = binding; + } + interpolants[i].resultBuffer = binding.buffer; + } + } + _activateAction(action) { + if (!this._isActiveAction(action)) { + if (action._cacheIndex === null) { + const rootUuid = (action._localRoot || this._root).uuid, clipUuid = action._clip.uuid, actionsForClip = this._actionsByClip[clipUuid]; + this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]); + this._addInactiveAction(action, clipUuid, rootUuid); + } + const bindings = action._propertyBindings; + for (let i = 0, n2 = bindings.length;i !== n2; ++i) { + const binding = bindings[i]; + if (binding.useCount++ === 0) { + this._lendBinding(binding); + binding.saveOriginalState(); + } + } + this._lendAction(action); + } + } + _deactivateAction(action) { + if (this._isActiveAction(action)) { + const bindings = action._propertyBindings; + for (let i = 0, n2 = bindings.length;i !== n2; ++i) { + const binding = bindings[i]; + if (--binding.useCount === 0) { + binding.restoreOriginalState(); + this._takeBackBinding(binding); + } + } + this._takeBackAction(action); + } + } + _initMemoryManager() { + this._actions = []; + this._nActiveActions = 0; + this._actionsByClip = {}; + this._bindings = []; + this._nActiveBindings = 0; + this._bindingsByRootAndName = {}; + this._controlInterpolants = []; + this._nActiveControlInterpolants = 0; + const scope = this; + this.stats = { + actions: { + get total() { + return scope._actions.length; + }, + get inUse() { + return scope._nActiveActions; + } + }, + bindings: { + get total() { + return scope._bindings.length; + }, + get inUse() { + return scope._nActiveBindings; + } + }, + controlInterpolants: { + get total() { + return scope._controlInterpolants.length; + }, + get inUse() { + return scope._nActiveControlInterpolants; + } + } + }; + } + _isActiveAction(action) { + const index2 = action._cacheIndex; + return index2 !== null && index2 < this._nActiveActions; + } + _addInactiveAction(action, clipUuid, rootUuid) { + const actions = this._actions, actionsByClip = this._actionsByClip; + let actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip === undefined) { + actionsForClip = { + knownActions: [action], + actionByRoot: {} + }; + action._byClipCacheIndex = 0; + actionsByClip[clipUuid] = actionsForClip; + } else { + const knownActions = actionsForClip.knownActions; + action._byClipCacheIndex = knownActions.length; + knownActions.push(action); + } + action._cacheIndex = actions.length; + actions.push(action); + actionsForClip.actionByRoot[rootUuid] = action; + } + _removeInactiveAction(action) { + const actions = this._actions, lastInactiveAction = actions[actions.length - 1], cacheIndex = action._cacheIndex; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + action._cacheIndex = null; + const clipUuid = action._clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid], knownActionsForClip = actionsForClip.knownActions, lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1], byClipCacheIndex = action._byClipCacheIndex; + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[byClipCacheIndex] = lastKnownAction; + knownActionsForClip.pop(); + action._byClipCacheIndex = null; + const actionByRoot = actionsForClip.actionByRoot, rootUuid = (action._localRoot || this._root).uuid; + delete actionByRoot[rootUuid]; + if (knownActionsForClip.length === 0) { + delete actionsByClip[clipUuid]; + } + this._removeInactiveBindingsForAction(action); + } + _removeInactiveBindingsForAction(action) { + const bindings = action._propertyBindings; + for (let i = 0, n2 = bindings.length;i !== n2; ++i) { + const binding = bindings[i]; + if (--binding.referenceCount === 0) { + this._removeInactiveBinding(binding); + } + } + } + _lendAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, lastActiveIndex = this._nActiveActions++, firstInactiveAction = actions[lastActiveIndex]; + action._cacheIndex = lastActiveIndex; + actions[lastActiveIndex] = action; + firstInactiveAction._cacheIndex = prevIndex; + actions[prevIndex] = firstInactiveAction; + } + _takeBackAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, firstInactiveIndex = --this._nActiveActions, lastActiveAction = actions[firstInactiveIndex]; + action._cacheIndex = firstInactiveIndex; + actions[firstInactiveIndex] = action; + lastActiveAction._cacheIndex = prevIndex; + actions[prevIndex] = lastActiveAction; + } + _addInactiveBinding(binding, rootUuid, trackName) { + const bindingsByRoot = this._bindingsByRootAndName, bindings = this._bindings; + let bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName === undefined) { + bindingByName = {}; + bindingsByRoot[rootUuid] = bindingByName; + } + bindingByName[trackName] = binding; + binding._cacheIndex = bindings.length; + bindings.push(binding); + } + _removeInactiveBinding(binding) { + const bindings = this._bindings, propBinding = binding.binding, rootUuid = propBinding.rootNode.uuid, trackName = propBinding.path, bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid], lastInactiveBinding = bindings[bindings.length - 1], cacheIndex = binding._cacheIndex; + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[cacheIndex] = lastInactiveBinding; + bindings.pop(); + delete bindingByName[trackName]; + if (Object.keys(bindingByName).length === 0) { + delete bindingsByRoot[rootUuid]; + } + } + _lendBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, lastActiveIndex = this._nActiveBindings++, firstInactiveBinding = bindings[lastActiveIndex]; + binding._cacheIndex = lastActiveIndex; + bindings[lastActiveIndex] = binding; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = firstInactiveBinding; + } + _takeBackBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, firstInactiveIndex = --this._nActiveBindings, lastActiveBinding = bindings[firstInactiveIndex]; + binding._cacheIndex = firstInactiveIndex; + bindings[firstInactiveIndex] = binding; + lastActiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = lastActiveBinding; + } + _lendControlInterpolant() { + const interpolants = this._controlInterpolants, lastActiveIndex = this._nActiveControlInterpolants++; + let interpolant = interpolants[lastActiveIndex]; + if (interpolant === undefined) { + interpolant = new LinearInterpolant2(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer2); + interpolant.__cacheIndex = lastActiveIndex; + interpolants[lastActiveIndex] = interpolant; + } + return interpolant; + } + _takeBackControlInterpolant(interpolant) { + const interpolants = this._controlInterpolants, prevIndex = interpolant.__cacheIndex, firstInactiveIndex = --this._nActiveControlInterpolants, lastActiveInterpolant = interpolants[firstInactiveIndex]; + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[firstInactiveIndex] = interpolant; + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[prevIndex] = lastActiveInterpolant; + } + clipAction(clip, optionalRoot, blendMode) { + const root2 = optionalRoot || this._root, rootUuid = root2.uuid; + let clipObject = typeof clip === "string" ? AnimationClip2.findByName(root2, clip) : clip; + const clipUuid = clipObject !== null ? clipObject.uuid : clip; + const actionsForClip = this._actionsByClip[clipUuid]; + let prototypeAction = null; + if (blendMode === undefined) { + if (clipObject !== null) { + blendMode = clipObject.blendMode; + } else { + blendMode = NormalAnimationBlendMode2; + } + } + if (actionsForClip !== undefined) { + const existingAction = actionsForClip.actionByRoot[rootUuid]; + if (existingAction !== undefined && existingAction.blendMode === blendMode) { + return existingAction; + } + prototypeAction = actionsForClip.knownActions[0]; + if (clipObject === null) + clipObject = prototypeAction._clip; + } + if (clipObject === null) + return null; + const newAction = new AnimationAction2(this, clipObject, optionalRoot, blendMode); + this._bindAction(newAction, prototypeAction); + this._addInactiveAction(newAction, clipUuid, rootUuid); + return newAction; + } + existingAction(clip, optionalRoot) { + const root2 = optionalRoot || this._root, rootUuid = root2.uuid, clipObject = typeof clip === "string" ? AnimationClip2.findByName(root2, clip) : clip, clipUuid = clipObject ? clipObject.uuid : clip, actionsForClip = this._actionsByClip[clipUuid]; + if (actionsForClip !== undefined) { + return actionsForClip.actionByRoot[rootUuid] || null; + } + return null; + } + stopAllAction() { + const actions = this._actions, nActions = this._nActiveActions; + for (let i = nActions - 1;i >= 0; --i) { + actions[i].stop(); + } + return this; + } + update(deltaTime) { + deltaTime *= this.timeScale; + const actions = this._actions, nActions = this._nActiveActions, time2 = this.time += deltaTime, timeDirection = Math.sign(deltaTime), accuIndex = this._accuIndex ^= 1; + for (let i = 0;i !== nActions; ++i) { + const action = actions[i]; + action._update(time2, deltaTime, timeDirection, accuIndex); + } + const bindings = this._bindings, nBindings = this._nActiveBindings; + for (let i = 0;i !== nBindings; ++i) { + bindings[i].apply(accuIndex); + } + return this; + } + setTime(timeInSeconds) { + this.time = 0; + for (let i = 0;i < this._actions.length; i++) { + this._actions[i].time = 0; + } + return this.update(timeInSeconds); + } + getRoot() { + return this._root; + } + uncacheClip(clip) { + const actions = this._actions, clipUuid = clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip !== undefined) { + const actionsToRemove = actionsForClip.knownActions; + for (let i = 0, n2 = actionsToRemove.length;i !== n2; ++i) { + const action = actionsToRemove[i]; + this._deactivateAction(action); + const cacheIndex = action._cacheIndex, lastInactiveAction = actions[actions.length - 1]; + action._cacheIndex = null; + action._byClipCacheIndex = null; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + this._removeInactiveBindingsForAction(action); + } + delete actionsByClip[clipUuid]; + } + } + uncacheRoot(root2) { + const rootUuid = root2.uuid, actionsByClip = this._actionsByClip; + for (const clipUuid in actionsByClip) { + const actionByRoot = actionsByClip[clipUuid].actionByRoot, action = actionByRoot[rootUuid]; + if (action !== undefined) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + const bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName !== undefined) { + for (const trackName in bindingByName) { + const binding = bindingByName[trackName]; + binding.restoreOriginalState(); + this._removeInactiveBinding(binding); + } + } + } + uncacheAction(clip, optionalRoot) { + const action = this.existingAction(clip, optionalRoot); + if (action !== null) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + } + + class RenderTarget3D2 extends RenderTarget2 { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isRenderTarget3D = true; + this.depth = depth; + this.texture = new Data3DTexture2(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } + } + + class RenderTargetArray2 extends RenderTarget2 { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isRenderTargetArray = true; + this.depth = depth; + this.texture = new DataArrayTexture2(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } + } + + class Uniform2 { + constructor(value2) { + this.value = value2; + } + clone() { + return new Uniform2(this.value.clone === undefined ? this.value : this.value.clone()); + } + } + var _id$12 = 0; + + class UniformsGroup2 extends EventDispatcher2 { + constructor() { + super(); + this.isUniformsGroup = true; + Object.defineProperty(this, "id", { value: _id$12++ }); + this.name = ""; + this.usage = StaticDrawUsage2; + this.uniforms = []; + } + add(uniform) { + this.uniforms.push(uniform); + return this; + } + remove(uniform) { + const index2 = this.uniforms.indexOf(uniform); + if (index2 !== -1) + this.uniforms.splice(index2, 1); + return this; + } + setName(name2) { + this.name = name2; + return this; + } + setUsage(value2) { + this.usage = value2; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + return this; + } + copy(source) { + this.name = source.name; + this.usage = source.usage; + const uniformsSource = source.uniforms; + this.uniforms.length = 0; + for (let i = 0, l2 = uniformsSource.length;i < l2; i++) { + const uniforms = Array.isArray(uniformsSource[i]) ? uniformsSource[i] : [uniformsSource[i]]; + for (let j2 = 0;j2 < uniforms.length; j2++) { + this.uniforms.push(uniforms[j2].clone()); + } + } + return this; + } + clone() { + return new this.constructor().copy(this); + } + } + + class InstancedInterleavedBuffer2 extends InterleavedBuffer2 { + constructor(array, stride, meshPerAttribute = 1) { + super(array, stride); + this.isInstancedInterleavedBuffer = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + clone(data2) { + const ib = super.clone(data2); + ib.meshPerAttribute = this.meshPerAttribute; + return ib; + } + toJSON(data2) { + const json = super.toJSON(data2); + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; + return json; + } + } + + class GLBufferAttribute2 { + constructor(buffer, type, itemSize, elementSize, count) { + this.isGLBufferAttribute = true; + this.name = ""; + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; + this.version = 0; + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setBuffer(buffer) { + this.buffer = buffer; + return this; + } + setType(type, elementSize) { + this.type = type; + this.elementSize = elementSize; + return this; + } + setItemSize(itemSize) { + this.itemSize = itemSize; + return this; + } + setCount(count) { + this.count = count; + return this; + } + } + var _matrix6 = /* @__PURE__ */ new Matrix42; + + class Raycaster2 { + constructor(origin, direction, near = 0, far = Infinity) { + this.ray = new Ray2(origin, direction); + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers2; + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + } + set(origin, direction) { + this.ray.set(origin, direction); + } + setFromCamera(coords, camera) { + if (camera.isPerspectiveCamera) { + this.ray.origin.setFromMatrixPosition(camera.matrixWorld); + this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize(); + this.camera = camera; + } else if (camera.isOrthographicCamera) { + this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); + this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld); + this.camera = camera; + } else { + console.error("THREE.Raycaster: Unsupported camera type: " + camera.type); + } + } + setFromXRController(controller) { + _matrix6.identity().extractRotation(controller.matrixWorld); + this.ray.origin.setFromMatrixPosition(controller.matrixWorld); + this.ray.direction.set(0, 0, -1).applyMatrix4(_matrix6); + return this; + } + intersectObject(object, recursive = true, intersects3 = []) { + intersect2(object, this, intersects3, recursive); + intersects3.sort(ascSort2); + return intersects3; + } + intersectObjects(objects, recursive = true, intersects3 = []) { + for (let i = 0, l2 = objects.length;i < l2; i++) { + intersect2(objects[i], this, intersects3, recursive); + } + intersects3.sort(ascSort2); + return intersects3; + } + } + function ascSort2(a2, b3) { + return a2.distance - b3.distance; + } + function intersect2(object, raycaster, intersects3, recursive) { + let propagate = true; + if (object.layers.test(raycaster.layers)) { + const result = object.raycast(raycaster, intersects3); + if (result === false) + propagate = false; + } + if (propagate === true && recursive === true) { + const children = object.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + intersect2(children[i], raycaster, intersects3, true); + } + } + } + + class Spherical2 { + constructor(radius = 1, phi = 0, theta = 0) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + set(radius, phi, theta) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + copy(other) { + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + return this; + } + makeSafe() { + const EPS = 0.000001; + this.phi = clamp3(this.phi, EPS, Math.PI - EPS); + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x2, y3, z2) { + this.radius = Math.sqrt(x2 * x2 + y3 * y3 + z2 * z2); + if (this.radius === 0) { + this.theta = 0; + this.phi = 0; + } else { + this.theta = Math.atan2(x2, z2); + this.phi = Math.acos(clamp3(y3 / this.radius, -1, 1)); + } + return this; + } + clone() { + return new this.constructor().copy(this); + } + } + + class Cylindrical2 { + constructor(radius = 1, theta = 0, y3 = 0) { + this.radius = radius; + this.theta = theta; + this.y = y3; + return this; + } + set(radius, theta, y3) { + this.radius = radius; + this.theta = theta; + this.y = y3; + return this; + } + copy(other) { + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x2, y3, z2) { + this.radius = Math.sqrt(x2 * x2 + z2 * z2); + this.theta = Math.atan2(x2, z2); + this.y = y3; + return this; + } + clone() { + return new this.constructor().copy(this); + } + } + + class Matrix22 { + constructor(n11, n12, n21, n22) { + Matrix22.prototype.isMatrix2 = true; + this.elements = [ + 1, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n21, n22); + } + } + identity() { + this.set(1, 0, 0, 1); + return this; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 4; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + set(n11, n12, n21, n22) { + const te3 = this.elements; + te3[0] = n11; + te3[2] = n12; + te3[1] = n21; + te3[3] = n22; + return this; + } + } + var _vector$42 = /* @__PURE__ */ new Vector22; + + class Box22 { + constructor(min = new Vector22(Infinity, Infinity), max = new Vector22(-Infinity, -Infinity)) { + this.isBox2 = true; + this.min = min; + this.max = max; + } + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length;i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size2) { + const halfSize = _vector$42.copy(size2).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = Infinity; + this.max.x = this.max.y = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y; + } + getParameter(point, target) { + return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y)); + } + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y; + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$42).distanceTo(point); + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) + this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } + } + var _startP2 = /* @__PURE__ */ new Vector32; + var _startEnd2 = /* @__PURE__ */ new Vector32; + + class Line32 { + constructor(start = new Vector32, end = new Vector32) { + this.start = start; + this.end = end; + } + set(start, end) { + this.start.copy(start); + this.end.copy(end); + return this; + } + copy(line2) { + this.start.copy(line2.start); + this.end.copy(line2.end); + return this; + } + getCenter(target) { + return target.addVectors(this.start, this.end).multiplyScalar(0.5); + } + delta(target) { + return target.subVectors(this.end, this.start); + } + distanceSq() { + return this.start.distanceToSquared(this.end); + } + distance() { + return this.start.distanceTo(this.end); + } + at(t4, target) { + return this.delta(target).multiplyScalar(t4).add(this.start); + } + closestPointToPointParameter(point, clampToLine) { + _startP2.subVectors(point, this.start); + _startEnd2.subVectors(this.end, this.start); + const startEnd2 = _startEnd2.dot(_startEnd2); + const startEnd_startP = _startEnd2.dot(_startP2); + let t4 = startEnd_startP / startEnd2; + if (clampToLine) { + t4 = clamp3(t4, 0, 1); + } + return t4; + } + closestPointToPoint(point, clampToLine, target) { + const t4 = this.closestPointToPointParameter(point, clampToLine); + return this.delta(target).multiplyScalar(t4).add(this.start); + } + applyMatrix4(matrix3) { + this.start.applyMatrix4(matrix3); + this.end.applyMatrix4(matrix3); + return this; + } + equals(line2) { + return line2.start.equals(this.start) && line2.end.equals(this.end); + } + clone() { + return new this.constructor().copy(this); + } + } + var _vector$32 = /* @__PURE__ */ new Vector32; + + class SpotLightHelper2 extends Object3D2 { + constructor(light, color) { + super(); + this.light = light; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "SpotLightHelper"; + const geometry = new BufferGeometry2; + const positions = [ + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + -1, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + -1, + 1 + ]; + for (let i = 0, j2 = 1, l2 = 32;i < l2; i++, j2++) { + const p1 = i / l2 * Math.PI * 2; + const p2 = j2 / l2 * Math.PI * 2; + positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1); + } + geometry.setAttribute("position", new Float32BufferAttribute2(positions, 3)); + const material = new LineBasicMaterial2({ fog: false, toneMapped: false }); + this.cone = new LineSegments3(geometry, material); + this.add(this.cone); + this.update(); + } + dispose() { + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + if (this.parent) { + this.parent.updateWorldMatrix(true); + this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld); + } else { + this.matrix.copy(this.light.matrixWorld); + } + this.matrixWorld.copy(this.light.matrixWorld); + const coneLength = this.light.distance ? this.light.distance : 1000; + const coneWidth = coneLength * Math.tan(this.light.angle); + this.cone.scale.set(coneWidth, coneWidth, coneLength); + _vector$32.setFromMatrixPosition(this.light.target.matrixWorld); + this.cone.lookAt(_vector$32); + if (this.color !== undefined) { + this.cone.material.color.set(this.color); + } else { + this.cone.material.color.copy(this.light.color); + } + } + } + var _vector$22 = /* @__PURE__ */ new Vector32; + var _boneMatrix2 = /* @__PURE__ */ new Matrix42; + var _matrixWorldInv2 = /* @__PURE__ */ new Matrix42; + + class SkeletonHelper2 extends LineSegments3 { + constructor(object) { + const bones = getBoneList2(object); + const geometry = new BufferGeometry2; + const vertices = []; + const colors = []; + const color1 = new Color2(0, 0, 1); + const color2 = new Color2(0, 1, 0); + for (let i = 0;i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + vertices.push(0, 0, 0); + vertices.push(0, 0, 0); + colors.push(color1.r, color1.g, color1.b); + colors.push(color2.r, color2.g, color2.b); + } + } + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + const material = new LineBasicMaterial2({ vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true }); + super(geometry, material); + this.isSkeletonHelper = true; + this.type = "SkeletonHelper"; + this.root = object; + this.bones = bones; + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + } + updateMatrixWorld(force) { + const bones = this.bones; + const geometry = this.geometry; + const position2 = geometry.getAttribute("position"); + _matrixWorldInv2.copy(this.root.matrixWorld).invert(); + for (let i = 0, j2 = 0;i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + _boneMatrix2.multiplyMatrices(_matrixWorldInv2, bone.matrixWorld); + _vector$22.setFromMatrixPosition(_boneMatrix2); + position2.setXYZ(j2, _vector$22.x, _vector$22.y, _vector$22.z); + _boneMatrix2.multiplyMatrices(_matrixWorldInv2, bone.parent.matrixWorld); + _vector$22.setFromMatrixPosition(_boneMatrix2); + position2.setXYZ(j2 + 1, _vector$22.x, _vector$22.y, _vector$22.z); + j2 += 2; + } + } + geometry.getAttribute("position").needsUpdate = true; + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + function getBoneList2(object) { + const boneList = []; + if (object.isBone === true) { + boneList.push(object); + } + for (let i = 0;i < object.children.length; i++) { + boneList.push.apply(boneList, getBoneList2(object.children[i])); + } + return boneList; + } + + class PointLightHelper2 extends Mesh2 { + constructor(light, sphereSize, color) { + const geometry = new SphereGeometry3(sphereSize, 4, 2); + const material = new MeshBasicMaterial2({ wireframe: true, fog: false, toneMapped: false }); + super(geometry, material); + this.light = light; + this.color = color; + this.type = "PointLightHelper"; + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; + this.update(); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + if (this.color !== undefined) { + this.material.color.set(this.color); + } else { + this.material.color.copy(this.light.color); + } + } + } + var _vector$12 = /* @__PURE__ */ new Vector32; + var _color12 = /* @__PURE__ */ new Color2; + var _color22 = /* @__PURE__ */ new Color2; + + class HemisphereLightHelper2 extends Object3D2 { + constructor(light, size2, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "HemisphereLightHelper"; + const geometry = new OctahedronGeometry2(size2); + geometry.rotateY(Math.PI * 0.5); + this.material = new MeshBasicMaterial2({ wireframe: true, fog: false, toneMapped: false }); + if (this.color === undefined) + this.material.vertexColors = true; + const position2 = geometry.getAttribute("position"); + const colors = new Float32Array(position2.count * 3); + geometry.setAttribute("color", new BufferAttribute2(colors, 3)); + this.add(new Mesh2(geometry, this.material)); + this.update(); + } + dispose() { + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + update() { + const mesh = this.children[0]; + if (this.color !== undefined) { + this.material.color.set(this.color); + } else { + const colors = mesh.geometry.getAttribute("color"); + _color12.copy(this.light.color); + _color22.copy(this.light.groundColor); + for (let i = 0, l2 = colors.count;i < l2; i++) { + const color = i < l2 / 2 ? _color12 : _color22; + colors.setXYZ(i, color.r, color.g, color.b); + } + colors.needsUpdate = true; + } + this.light.updateWorldMatrix(true, false); + mesh.lookAt(_vector$12.setFromMatrixPosition(this.light.matrixWorld).negate()); + } + } + + class GridHelper2 extends LineSegments3 { + constructor(size2 = 10, divisions = 10, color1 = 4473924, color2 = 8947848) { + color1 = new Color2(color1); + color2 = new Color2(color2); + const center = divisions / 2; + const step = size2 / divisions; + const halfSize = size2 / 2; + const vertices = [], colors = []; + for (let i = 0, j2 = 0, k4 = -halfSize;i <= divisions; i++, k4 += step) { + vertices.push(-halfSize, 0, k4, halfSize, 0, k4); + vertices.push(k4, 0, -halfSize, k4, 0, halfSize); + const color = i === center ? color1 : color2; + color.toArray(colors, j2); + j2 += 3; + color.toArray(colors, j2); + j2 += 3; + color.toArray(colors, j2); + j2 += 3; + color.toArray(colors, j2); + j2 += 3; + } + const geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + const material = new LineBasicMaterial2({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "GridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + + class PolarGridHelper2 extends LineSegments3 { + constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 4473924, color2 = 8947848) { + color1 = new Color2(color1); + color2 = new Color2(color2); + const vertices = []; + const colors = []; + if (sectors > 1) { + for (let i = 0;i < sectors; i++) { + const v = i / sectors * (Math.PI * 2); + const x2 = Math.sin(v) * radius; + const z2 = Math.cos(v) * radius; + vertices.push(0, 0, 0); + vertices.push(x2, 0, z2); + const color = i & 1 ? color1 : color2; + colors.push(color.r, color.g, color.b); + colors.push(color.r, color.g, color.b); + } + } + for (let i = 0;i < rings; i++) { + const color = i & 1 ? color1 : color2; + const r = radius - radius / rings * i; + for (let j2 = 0;j2 < divisions; j2++) { + let v = j2 / divisions * (Math.PI * 2); + let x2 = Math.sin(v) * r; + let z2 = Math.cos(v) * r; + vertices.push(x2, 0, z2); + colors.push(color.r, color.g, color.b); + v = (j2 + 1) / divisions * (Math.PI * 2); + x2 = Math.sin(v) * r; + z2 = Math.cos(v) * r; + vertices.push(x2, 0, z2); + colors.push(color.r, color.g, color.b); + } + } + const geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + const material = new LineBasicMaterial2({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "PolarGridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + var _v18 = /* @__PURE__ */ new Vector32; + var _v27 = /* @__PURE__ */ new Vector32; + var _v33 = /* @__PURE__ */ new Vector32; + + class DirectionalLightHelper2 extends Object3D2 { + constructor(light, size2, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "DirectionalLightHelper"; + if (size2 === undefined) + size2 = 1; + let geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2([ + -size2, + size2, + 0, + size2, + size2, + 0, + size2, + -size2, + 0, + -size2, + -size2, + 0, + -size2, + size2, + 0 + ], 3)); + const material = new LineBasicMaterial2({ fog: false, toneMapped: false }); + this.lightPlane = new Line4(geometry, material); + this.add(this.lightPlane); + geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2([0, 0, 0, 0, 0, 1], 3)); + this.targetLine = new Line4(geometry, material); + this.add(this.targetLine); + this.update(); + } + dispose() { + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + _v18.setFromMatrixPosition(this.light.matrixWorld); + _v27.setFromMatrixPosition(this.light.target.matrixWorld); + _v33.subVectors(_v27, _v18); + this.lightPlane.lookAt(_v27); + if (this.color !== undefined) { + this.lightPlane.material.color.set(this.color); + this.targetLine.material.color.set(this.color); + } else { + this.lightPlane.material.color.copy(this.light.color); + this.targetLine.material.color.copy(this.light.color); + } + this.targetLine.lookAt(_v27); + this.targetLine.scale.z = _v33.length(); + } + } + var _vector5 = /* @__PURE__ */ new Vector32; + var _camera3 = /* @__PURE__ */ new Camera2; + + class CameraHelper2 extends LineSegments3 { + constructor(camera) { + const geometry = new BufferGeometry2; + const material = new LineBasicMaterial2({ color: 16777215, vertexColors: true, toneMapped: false }); + const vertices = []; + const colors = []; + const pointMap = {}; + addLine("n1", "n2"); + addLine("n2", "n4"); + addLine("n4", "n3"); + addLine("n3", "n1"); + addLine("f1", "f2"); + addLine("f2", "f4"); + addLine("f4", "f3"); + addLine("f3", "f1"); + addLine("n1", "f1"); + addLine("n2", "f2"); + addLine("n3", "f3"); + addLine("n4", "f4"); + addLine("p", "n1"); + addLine("p", "n2"); + addLine("p", "n3"); + addLine("p", "n4"); + addLine("u1", "u2"); + addLine("u2", "u3"); + addLine("u3", "u1"); + addLine("c", "t"); + addLine("p", "c"); + addLine("cn1", "cn2"); + addLine("cn3", "cn4"); + addLine("cf1", "cf2"); + addLine("cf3", "cf4"); + function addLine(a2, b3) { + addPoint(a2); + addPoint(b3); + } + function addPoint(id) { + vertices.push(0, 0, 0); + colors.push(0, 0, 0); + if (pointMap[id] === undefined) { + pointMap[id] = []; + } + pointMap[id].push(vertices.length / 3 - 1); + } + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + super(geometry, material); + this.type = "CameraHelper"; + this.camera = camera; + if (this.camera.updateProjectionMatrix) + this.camera.updateProjectionMatrix(); + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; + this.pointMap = pointMap; + this.update(); + const colorFrustum = new Color2(16755200); + const colorCone = new Color2(16711680); + const colorUp = new Color2(43775); + const colorTarget = new Color2(16777215); + const colorCross = new Color2(3355443); + this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross); + } + setColors(frustum, cone, up, target, cross) { + const geometry = this.geometry; + const colorAttribute = geometry.getAttribute("color"); + colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(24, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(26, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(28, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(30, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(32, up.r, up.g, up.b); + colorAttribute.setXYZ(33, up.r, up.g, up.b); + colorAttribute.setXYZ(34, up.r, up.g, up.b); + colorAttribute.setXYZ(35, up.r, up.g, up.b); + colorAttribute.setXYZ(36, up.r, up.g, up.b); + colorAttribute.setXYZ(37, up.r, up.g, up.b); + colorAttribute.setXYZ(38, target.r, target.g, target.b); + colorAttribute.setXYZ(39, target.r, target.g, target.b); + colorAttribute.setXYZ(40, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(42, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(44, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(46, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(48, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); + colorAttribute.needsUpdate = true; + } + update() { + const geometry = this.geometry; + const pointMap = this.pointMap; + const w = 1, h = 1; + _camera3.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); + const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem2 ? -1 : 0; + setPoint2("c", pointMap, geometry, _camera3, 0, 0, nearZ); + setPoint2("t", pointMap, geometry, _camera3, 0, 0, 1); + setPoint2("n1", pointMap, geometry, _camera3, -w, -h, nearZ); + setPoint2("n2", pointMap, geometry, _camera3, w, -h, nearZ); + setPoint2("n3", pointMap, geometry, _camera3, -w, h, nearZ); + setPoint2("n4", pointMap, geometry, _camera3, w, h, nearZ); + setPoint2("f1", pointMap, geometry, _camera3, -w, -h, 1); + setPoint2("f2", pointMap, geometry, _camera3, w, -h, 1); + setPoint2("f3", pointMap, geometry, _camera3, -w, h, 1); + setPoint2("f4", pointMap, geometry, _camera3, w, h, 1); + setPoint2("u1", pointMap, geometry, _camera3, w * 0.7, h * 1.1, nearZ); + setPoint2("u2", pointMap, geometry, _camera3, -w * 0.7, h * 1.1, nearZ); + setPoint2("u3", pointMap, geometry, _camera3, 0, h * 2, nearZ); + setPoint2("cf1", pointMap, geometry, _camera3, -w, 0, 1); + setPoint2("cf2", pointMap, geometry, _camera3, w, 0, 1); + setPoint2("cf3", pointMap, geometry, _camera3, 0, -h, 1); + setPoint2("cf4", pointMap, geometry, _camera3, 0, h, 1); + setPoint2("cn1", pointMap, geometry, _camera3, -w, 0, nearZ); + setPoint2("cn2", pointMap, geometry, _camera3, w, 0, nearZ); + setPoint2("cn3", pointMap, geometry, _camera3, 0, -h, nearZ); + setPoint2("cn4", pointMap, geometry, _camera3, 0, h, nearZ); + geometry.getAttribute("position").needsUpdate = true; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + function setPoint2(point, pointMap, geometry, camera, x2, y3, z2) { + _vector5.set(x2, y3, z2).unproject(camera); + const points = pointMap[point]; + if (points !== undefined) { + const position2 = geometry.getAttribute("position"); + for (let i = 0, l2 = points.length;i < l2; i++) { + position2.setXYZ(points[i], _vector5.x, _vector5.y, _vector5.z); + } + } + } + var _box5 = /* @__PURE__ */ new Box32; + + class BoxHelper2 extends LineSegments3 { + constructor(object, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = new Float32Array(8 * 3); + const geometry = new BufferGeometry2; + geometry.setIndex(new BufferAttribute2(indices, 1)); + geometry.setAttribute("position", new BufferAttribute2(positions, 3)); + super(geometry, new LineBasicMaterial2({ color, toneMapped: false })); + this.object = object; + this.type = "BoxHelper"; + this.matrixAutoUpdate = false; + this.update(); + } + update(object) { + if (object !== undefined) { + console.warn("THREE.BoxHelper: .update() has no longer arguments."); + } + if (this.object !== undefined) { + _box5.setFromObject(this.object); + } + if (_box5.isEmpty()) + return; + const min = _box5.min; + const max = _box5.max; + const position2 = this.geometry.attributes.position; + const array = position2.array; + array[0] = max.x; + array[1] = max.y; + array[2] = max.z; + array[3] = min.x; + array[4] = max.y; + array[5] = max.z; + array[6] = min.x; + array[7] = min.y; + array[8] = max.z; + array[9] = max.x; + array[10] = min.y; + array[11] = max.z; + array[12] = max.x; + array[13] = max.y; + array[14] = min.z; + array[15] = min.x; + array[16] = max.y; + array[17] = min.z; + array[18] = min.x; + array[19] = min.y; + array[20] = min.z; + array[21] = max.x; + array[22] = min.y; + array[23] = min.z; + position2.needsUpdate = true; + this.geometry.computeBoundingSphere(); + } + setFromObject(object) { + this.object = object; + this.update(); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + this.object = source.object; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + + class Box3Helper2 extends LineSegments3 { + constructor(box, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1]; + const geometry = new BufferGeometry2; + geometry.setIndex(new BufferAttribute2(indices, 1)); + geometry.setAttribute("position", new Float32BufferAttribute2(positions, 3)); + super(geometry, new LineBasicMaterial2({ color, toneMapped: false })); + this.box = box; + this.type = "Box3Helper"; + this.geometry.computeBoundingSphere(); + } + updateMatrixWorld(force) { + const box = this.box; + if (box.isEmpty()) + return; + box.getCenter(this.position); + box.getSize(this.scale); + this.scale.multiplyScalar(0.5); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + + class PlaneHelper2 extends Line4 { + constructor(plane, size2 = 1, hex = 16776960) { + const color = hex; + const positions = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0]; + const geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2(positions, 3)); + geometry.computeBoundingSphere(); + super(geometry, new LineBasicMaterial2({ color, toneMapped: false })); + this.type = "PlaneHelper"; + this.plane = plane; + this.size = size2; + const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0]; + const geometry2 = new BufferGeometry2; + geometry2.setAttribute("position", new Float32BufferAttribute2(positions2, 3)); + geometry2.computeBoundingSphere(); + this.add(new Mesh2(geometry2, new MeshBasicMaterial2({ color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false }))); + } + updateMatrixWorld(force) { + this.position.set(0, 0, 0); + this.scale.set(0.5 * this.size, 0.5 * this.size, 1); + this.lookAt(this.plane.normal); + this.translateZ(-this.plane.constant); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + } + var _axis4 = /* @__PURE__ */ new Vector32; + var _lineGeometry2; + var _coneGeometry2; + + class ArrowHelper2 extends Object3D2 { + constructor(dir = new Vector32(0, 0, 1), origin = new Vector32(0, 0, 0), length2 = 1, color = 16776960, headLength = length2 * 0.2, headWidth = headLength * 0.2) { + super(); + this.type = "ArrowHelper"; + if (_lineGeometry2 === undefined) { + _lineGeometry2 = new BufferGeometry2; + _lineGeometry2.setAttribute("position", new Float32BufferAttribute2([0, 0, 0, 0, 1, 0], 3)); + _coneGeometry2 = new CylinderGeometry2(0, 0.5, 1, 5, 1); + _coneGeometry2.translate(0, -0.5, 0); + } + this.position.copy(origin); + this.line = new Line4(_lineGeometry2, new LineBasicMaterial2({ color, toneMapped: false })); + this.line.matrixAutoUpdate = false; + this.add(this.line); + this.cone = new Mesh2(_coneGeometry2, new MeshBasicMaterial2({ color, toneMapped: false })); + this.cone.matrixAutoUpdate = false; + this.add(this.cone); + this.setDirection(dir); + this.setLength(length2, headLength, headWidth); + } + setDirection(dir) { + if (dir.y > 0.99999) { + this.quaternion.set(0, 0, 0, 1); + } else if (dir.y < -0.99999) { + this.quaternion.set(1, 0, 0, 0); + } else { + _axis4.set(dir.z, 0, -dir.x).normalize(); + const radians = Math.acos(dir.y); + this.quaternion.setFromAxisAngle(_axis4, radians); + } + } + setLength(length2, headLength = length2 * 0.2, headWidth = headLength * 0.2) { + this.line.scale.set(1, Math.max(0.0001, length2 - headLength), 1); + this.line.updateMatrix(); + this.cone.scale.set(headWidth, headLength, headWidth); + this.cone.position.y = length2; + this.cone.updateMatrix(); + } + setColor(color) { + this.line.material.color.set(color); + this.cone.material.color.set(color); + } + copy(source) { + super.copy(source, false); + this.line.copy(source.line); + this.cone.copy(source.cone); + return this; + } + dispose() { + this.line.geometry.dispose(); + this.line.material.dispose(); + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + } + + class AxesHelper2 extends LineSegments3 { + constructor(size2 = 1) { + const vertices = [ + 0, + 0, + 0, + size2, + 0, + 0, + 0, + 0, + 0, + 0, + size2, + 0, + 0, + 0, + 0, + 0, + 0, + size2 + ]; + const colors = [ + 1, + 0, + 0, + 1, + 0.6, + 0, + 0, + 1, + 0, + 0.6, + 1, + 0, + 0, + 0, + 1, + 0, + 0.6, + 1 + ]; + const geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + const material = new LineBasicMaterial2({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "AxesHelper"; + } + setColors(xAxisColor, yAxisColor, zAxisColor) { + const color = new Color2; + const array = this.geometry.attributes.color.array; + color.set(xAxisColor); + color.toArray(array, 0); + color.toArray(array, 3); + color.set(yAxisColor); + color.toArray(array, 6); + color.toArray(array, 9); + color.set(zAxisColor); + color.toArray(array, 12); + color.toArray(array, 15); + this.geometry.attributes.color.needsUpdate = true; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + + class ShapePath3 { + constructor() { + this.type = "ShapePath"; + this.color = new Color2; + this.subPaths = []; + this.currentPath = null; + } + moveTo(x2, y3) { + this.currentPath = new Path3; + this.subPaths.push(this.currentPath); + this.currentPath.moveTo(x2, y3); + return this; + } + lineTo(x2, y3) { + this.currentPath.lineTo(x2, y3); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY); + return this; + } + splineThru(pts) { + this.currentPath.splineThru(pts); + return this; + } + toShapes(isCCW) { + function toShapesNoHoles(inSubpaths) { + const shapes2 = []; + for (let i = 0, l2 = inSubpaths.length;i < l2; i++) { + const tmpPath2 = inSubpaths[i]; + const tmpShape2 = new Shape2; + tmpShape2.curves = tmpPath2.curves; + shapes2.push(tmpShape2); + } + return shapes2; + } + function isPointInsidePolygon(inPt, inPolygon) { + const polyLen = inPolygon.length; + let inside = false; + for (let p = polyLen - 1, q2 = 0;q2 < polyLen; p = q2++) { + let edgeLowPt = inPolygon[p]; + let edgeHighPt = inPolygon[q2]; + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; + if (Math.abs(edgeDy) > Number.EPSILON) { + if (edgeDy < 0) { + edgeLowPt = inPolygon[q2]; + edgeDx = -edgeDx; + edgeHighPt = inPolygon[p]; + edgeDy = -edgeDy; + } + if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) + continue; + if (inPt.y === edgeLowPt.y) { + if (inPt.x === edgeLowPt.x) + return true; + } else { + const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); + if (perpEdge === 0) + return true; + if (perpEdge < 0) + continue; + inside = !inside; + } + } else { + if (inPt.y !== edgeLowPt.y) + continue; + if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) + return true; + } + } + return inside; + } + const isClockWise = ShapeUtils2.isClockWise; + const subPaths = this.subPaths; + if (subPaths.length === 0) + return []; + let solid, tmpPath, tmpShape; + const shapes = []; + if (subPaths.length === 1) { + tmpPath = subPaths[0]; + tmpShape = new Shape2; + tmpShape.curves = tmpPath.curves; + shapes.push(tmpShape); + return shapes; + } + let holesFirst = !isClockWise(subPaths[0].getPoints()); + holesFirst = isCCW ? !holesFirst : holesFirst; + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; + newShapes[mainIdx] = undefined; + newShapeHoles[mainIdx] = []; + for (let i = 0, l2 = subPaths.length;i < l2; i++) { + tmpPath = subPaths[i]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise(tmpPoints); + solid = isCCW ? !solid : solid; + if (solid) { + if (!holesFirst && newShapes[mainIdx]) + mainIdx++; + newShapes[mainIdx] = { s: new Shape2, p: tmpPoints }; + newShapes[mainIdx].s.curves = tmpPath.curves; + if (holesFirst) + mainIdx++; + newShapeHoles[mainIdx] = []; + } else { + newShapeHoles[mainIdx].push({ h: tmpPath, p: tmpPoints[0] }); + } + } + if (!newShapes[0]) + return toShapesNoHoles(subPaths); + if (newShapes.length > 1) { + let ambiguous = false; + let toChange = 0; + for (let sIdx = 0, sLen = newShapes.length;sIdx < sLen; sIdx++) { + betterShapeHoles[sIdx] = []; + } + for (let sIdx = 0, sLen = newShapes.length;sIdx < sLen; sIdx++) { + const sho = newShapeHoles[sIdx]; + for (let hIdx = 0;hIdx < sho.length; hIdx++) { + const ho = sho[hIdx]; + let hole_unassigned = true; + for (let s2Idx = 0;s2Idx < newShapes.length; s2Idx++) { + if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) { + if (sIdx !== s2Idx) + toChange++; + if (hole_unassigned) { + hole_unassigned = false; + betterShapeHoles[s2Idx].push(ho); + } else { + ambiguous = true; + } + } + } + if (hole_unassigned) { + betterShapeHoles[sIdx].push(ho); + } + } + } + if (toChange > 0 && ambiguous === false) { + newShapeHoles = betterShapeHoles; + } + } + let tmpHoles; + for (let i = 0, il = newShapes.length;i < il; i++) { + tmpShape = newShapes[i].s; + shapes.push(tmpShape); + tmpHoles = newShapeHoles[i]; + for (let j2 = 0, jl = tmpHoles.length;j2 < jl; j2++) { + tmpShape.holes.push(tmpHoles[j2].h); + } + } + return shapes; + } + } + + class Controls2 extends EventDispatcher2 { + constructor(object, domElement = null) { + super(); + this.object = object; + this.domElement = domElement; + this.enabled = true; + this.state = -1; + this.keys = {}; + this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null }; + this.touches = { ONE: null, TWO: null }; + } + connect() { + } + disconnect() { + } + dispose() { + } + update() { + } + } + function contain2(texture, aspect3) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect3) { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect3; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } else { + texture.repeat.x = aspect3 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } + return texture; + } + function cover2(texture, aspect3) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect3) { + texture.repeat.x = aspect3 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } else { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect3; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } + return texture; + } + function fill2(texture) { + texture.repeat.x = 1; + texture.repeat.y = 1; + texture.offset.x = 0; + texture.offset.y = 0; + return texture; + } + function getByteLength2(width2, height2, format, type) { + const typeByteLength = getTextureTypeByteLength2(type); + switch (format) { + case AlphaFormat2: + return width2 * height2; + case LuminanceFormat2: + return width2 * height2; + case LuminanceAlphaFormat2: + return width2 * height2 * 2; + case RedFormat2: + return width2 * height2 / typeByteLength.components * typeByteLength.byteLength; + case RedIntegerFormat2: + return width2 * height2 / typeByteLength.components * typeByteLength.byteLength; + case RGFormat2: + return width2 * height2 * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGIntegerFormat2: + return width2 * height2 * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGBFormat2: + return width2 * height2 * 3 / typeByteLength.components * typeByteLength.byteLength; + case RGBAFormat2: + return width2 * height2 * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGBAIntegerFormat2: + return width2 * height2 * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGB_S3TC_DXT1_Format2: + case RGBA_S3TC_DXT1_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 8; + case RGBA_S3TC_DXT3_Format2: + case RGBA_S3TC_DXT5_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGB_PVRTC_2BPPV1_Format2: + case RGBA_PVRTC_2BPPV1_Format2: + return Math.max(width2, 16) * Math.max(height2, 8) / 4; + case RGB_PVRTC_4BPPV1_Format2: + case RGBA_PVRTC_4BPPV1_Format2: + return Math.max(width2, 8) * Math.max(height2, 8) / 2; + case RGB_ETC1_Format2: + case RGB_ETC2_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 8; + case RGBA_ETC2_EAC_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_4x4_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_5x4_Format2: + return Math.floor((width2 + 4) / 5) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_5x5_Format2: + return Math.floor((width2 + 4) / 5) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_6x5_Format2: + return Math.floor((width2 + 5) / 6) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_6x6_Format2: + return Math.floor((width2 + 5) / 6) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_8x5_Format2: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_8x6_Format2: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_8x8_Format2: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 7) / 8) * 16; + case RGBA_ASTC_10x5_Format2: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_10x6_Format2: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_10x8_Format2: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 7) / 8) * 16; + case RGBA_ASTC_10x10_Format2: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 9) / 10) * 16; + case RGBA_ASTC_12x10_Format2: + return Math.floor((width2 + 11) / 12) * Math.floor((height2 + 9) / 10) * 16; + case RGBA_ASTC_12x12_Format2: + return Math.floor((width2 + 11) / 12) * Math.floor((height2 + 11) / 12) * 16; + case RGBA_BPTC_Format2: + case RGB_BPTC_SIGNED_Format2: + case RGB_BPTC_UNSIGNED_Format2: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 16; + case RED_RGTC1_Format2: + case SIGNED_RED_RGTC1_Format2: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 8; + case RED_GREEN_RGTC2_Format2: + case SIGNED_RED_GREEN_RGTC2_Format2: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 16; + } + throw new Error(`Unable to determine texture byte length for ${format} format.`); + } + function getTextureTypeByteLength2(type) { + switch (type) { + case UnsignedByteType2: + case ByteType2: + return { byteLength: 1, components: 1 }; + case UnsignedShortType2: + case ShortType2: + case HalfFloatType2: + return { byteLength: 2, components: 1 }; + case UnsignedShort4444Type2: + case UnsignedShort5551Type2: + return { byteLength: 2, components: 4 }; + case UnsignedIntType2: + case IntType2: + case FloatType2: + return { byteLength: 4, components: 1 }; + case UnsignedInt5999Type2: + return { byteLength: 4, components: 3 }; + } + throw new Error(`Unknown texture type ${type}.`); + } + var TextureUtils2 = { + contain: contain2, + cover: cover2, + fill: fill2, + getByteLength: getByteLength2 + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { + revision: REVISION2 + } })); + } + if (typeof window !== "undefined") { + if (window.__THREE__) { + console.warn("WARNING: Multiple instances of Three.js being imported."); + } else { + window.__THREE__ = REVISION2; + } + } + function WebGLAnimation2() { + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + function onAnimationFrame(time2, frame) { + animationLoop(time2, frame); + requestId = context.requestAnimationFrame(onAnimationFrame); + } + return { + start: function() { + if (isAnimating === true) + return; + if (animationLoop === null) + return; + requestId = context.requestAnimationFrame(onAnimationFrame); + isAnimating = true; + }, + stop: function() { + context.cancelAnimationFrame(requestId); + isAnimating = false; + }, + setAnimationLoop: function(callback) { + animationLoop = callback; + }, + setContext: function(value2) { + context = value2; + } + }; + } + function WebGLAttributes2(gl) { + const buffers = new WeakMap; + function createBuffer(attribute, bufferType) { + const array = attribute.array; + const usage = attribute.usage; + const size2 = array.byteLength; + const buffer = gl.createBuffer(); + gl.bindBuffer(bufferType, buffer); + gl.bufferData(bufferType, array, usage); + attribute.onUploadCallback(); + let type; + if (array instanceof Float32Array) { + type = gl.FLOAT; + } else if (array instanceof Uint16Array) { + if (attribute.isFloat16BufferAttribute) { + type = gl.HALF_FLOAT; + } else { + type = gl.UNSIGNED_SHORT; + } + } else if (array instanceof Int16Array) { + type = gl.SHORT; + } else if (array instanceof Uint32Array) { + type = gl.UNSIGNED_INT; + } else if (array instanceof Int32Array) { + type = gl.INT; + } else if (array instanceof Int8Array) { + type = gl.BYTE; + } else if (array instanceof Uint8Array) { + type = gl.UNSIGNED_BYTE; + } else if (array instanceof Uint8ClampedArray) { + type = gl.UNSIGNED_BYTE; + } else { + throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + array); + } + return { + buffer, + type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version, + size: size2 + }; + } + function updateBuffer(buffer, attribute, bufferType) { + const array = attribute.array; + const updateRanges = attribute.updateRanges; + gl.bindBuffer(bufferType, buffer); + if (updateRanges.length === 0) { + gl.bufferSubData(bufferType, 0, array); + } else { + updateRanges.sort((a2, b3) => a2.start - b3.start); + let mergeIndex = 0; + for (let i = 1;i < updateRanges.length; i++) { + const previousRange = updateRanges[mergeIndex]; + const range = updateRanges[i]; + if (range.start <= previousRange.start + previousRange.count + 1) { + previousRange.count = Math.max(previousRange.count, range.start + range.count - previousRange.start); + } else { + ++mergeIndex; + updateRanges[mergeIndex] = range; + } + } + updateRanges.length = mergeIndex + 1; + for (let i = 0, l2 = updateRanges.length;i < l2; i++) { + const range = updateRanges[i]; + gl.bufferSubData(bufferType, range.start * array.BYTES_PER_ELEMENT, array, range.start, range.count); + } + attribute.clearUpdateRanges(); + } + attribute.onUploadCallback(); + } + function get(attribute) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + return buffers.get(attribute); + } + function remove(attribute) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + const data2 = buffers.get(attribute); + if (data2) { + gl.deleteBuffer(data2.buffer); + buffers.delete(attribute); + } + } + function update(attribute, bufferType) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + if (attribute.isGLBufferAttribute) { + const cached = buffers.get(attribute); + if (!cached || cached.version < attribute.version) { + buffers.set(attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + }); + } + return; + } + const data2 = buffers.get(attribute); + if (data2 === undefined) { + buffers.set(attribute, createBuffer(attribute, bufferType)); + } else if (data2.version < attribute.version) { + if (data2.size !== attribute.array.byteLength) { + throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported."); + } + updateBuffer(data2.buffer, attribute, bufferType); + data2.version = attribute.version; + } + } + return { + get, + remove, + update + }; + } + var alphahash_fragment2 = `#ifdef USE_ALPHAHASH + if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard; +#endif`; + var alphahash_pars_fragment2 = `#ifdef USE_ALPHAHASH + const float ALPHA_HASH_SCALE = 0.05; + float hash2D( vec2 value ) { + return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) ); + } + float hash3D( vec3 value ) { + return hash2D( vec2( hash2D( value.xy ), value.z ) ); + } + float getAlphaHashThreshold( vec3 position ) { + float maxDeriv = max( + length( dFdx( position.xyz ) ), + length( dFdy( position.xyz ) ) + ); + float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv ); + vec2 pixScales = vec2( + exp2( floor( log2( pixScale ) ) ), + exp2( ceil( log2( pixScale ) ) ) + ); + vec2 alpha = vec2( + hash3D( floor( pixScales.x * position.xyz ) ), + hash3D( floor( pixScales.y * position.xyz ) ) + ); + float lerpFactor = fract( log2( pixScale ) ); + float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y; + float a = min( lerpFactor, 1.0 - lerpFactor ); + vec3 cases = vec3( + x * x / ( 2.0 * a * ( 1.0 - a ) ), + ( x - 0.5 * a ) / ( 1.0 - a ), + 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) ) + ); + float threshold = ( x < ( 1.0 - a ) ) + ? ( ( x < a ) ? cases.x : cases.y ) + : cases.z; + return clamp( threshold , 1.0e-6, 1.0 ); + } +#endif`; + var alphamap_fragment2 = `#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g; +#endif`; + var alphamap_pars_fragment2 = `#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`; + var alphatest_fragment2 = `#ifdef USE_ALPHATEST + #ifdef ALPHA_TO_COVERAGE + diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a ); + if ( diffuseColor.a == 0.0 ) discard; + #else + if ( diffuseColor.a < alphaTest ) discard; + #endif +#endif`; + var alphatest_pars_fragment2 = `#ifdef USE_ALPHATEST + uniform float alphaTest; +#endif`; + var aomap_fragment2 = `#ifdef USE_AOMAP + float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0; + reflectedLight.indirectDiffuse *= ambientOcclusion; + #if defined( USE_CLEARCOAT ) + clearcoatSpecularIndirect *= ambientOcclusion; + #endif + #if defined( USE_SHEEN ) + sheenSpecularIndirect *= ambientOcclusion; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) + float dotNV = saturate( dot( geometryNormal, geometryViewDir ) ); + reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness ); + #endif +#endif`; + var aomap_pars_fragment2 = `#ifdef USE_AOMAP + uniform sampler2D aoMap; + uniform float aoMapIntensity; +#endif`; + var batching_pars_vertex2 = `#ifdef USE_BATCHING + #if ! defined( GL_ANGLE_multi_draw ) + #define gl_DrawID _gl_DrawID + uniform int _gl_DrawID; + #endif + uniform highp sampler2D batchingTexture; + uniform highp usampler2D batchingIdTexture; + mat4 getBatchingMatrix( const in float i ) { + int size = textureSize( batchingTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } + float getIndirectIndex( const in int i ) { + int size = textureSize( batchingIdTexture, 0 ).x; + int x = i % size; + int y = i / size; + return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r ); + } +#endif +#ifdef USE_BATCHING_COLOR + uniform sampler2D batchingColorTexture; + vec3 getBatchingColor( const in float i ) { + int size = textureSize( batchingColorTexture, 0 ).x; + int j = int( i ); + int x = j % size; + int y = j / size; + return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb; + } +#endif`; + var batching_vertex2 = `#ifdef USE_BATCHING + mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) ); +#endif`; + var begin_vertex2 = `vec3 transformed = vec3( position ); +#ifdef USE_ALPHAHASH + vPosition = vec3( position ); +#endif`; + var beginnormal_vertex2 = `vec3 objectNormal = vec3( normal ); +#ifdef USE_TANGENT + vec3 objectTangent = vec3( tangent.xyz ); +#endif`; + var bsdfs2 = `float G_BlinnPhong_Implicit( ) { + return 0.25; +} +float D_BlinnPhong( const in float shininess, const in float dotNH ) { + return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess ); +} +vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( specularColor, 1.0, dotVH ); + float G = G_BlinnPhong_Implicit( ); + float D = D_BlinnPhong( shininess, dotNH ); + return F * ( G * D ); +} // validated`; + var iridescence_fragment2 = `#ifdef USE_IRIDESCENCE + const mat3 XYZ_TO_REC709 = mat3( + 3.2404542, -0.9692660, 0.0556434, + -1.5371385, 1.8760108, -0.2040259, + -0.4985314, 0.0415560, 1.0572252 + ); + vec3 Fresnel0ToIor( vec3 fresnel0 ) { + vec3 sqrtF0 = sqrt( fresnel0 ); + return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 ); + } + vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) { + return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) ); + } + float IorToFresnel0( float transmittedIor, float incidentIor ) { + return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor )); + } + vec3 evalSensitivity( float OPD, vec3 shift ) { + float phase = 2.0 * PI * OPD * 1.0e-9; + vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 ); + vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 ); + vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 ); + vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var ); + xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) ); + xyz /= 1.0685e-7; + vec3 rgb = XYZ_TO_REC709 * xyz; + return rgb; + } + vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) { + vec3 I; + float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) ); + float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) ); + float cosTheta2Sq = 1.0 - sinTheta2Sq; + if ( cosTheta2Sq < 0.0 ) { + return vec3( 1.0 ); + } + float cosTheta2 = sqrt( cosTheta2Sq ); + float R0 = IorToFresnel0( iridescenceIOR, outsideIOR ); + float R12 = F_Schlick( R0, 1.0, cosTheta1 ); + float T121 = 1.0 - R12; + float phi12 = 0.0; + if ( iridescenceIOR < outsideIOR ) phi12 = PI; + float phi21 = PI - phi12; + vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR ); + vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 ); + vec3 phi23 = vec3( 0.0 ); + if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI; + if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI; + if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI; + float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2; + vec3 phi = vec3( phi21 ) + phi23; + vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 ); + vec3 r123 = sqrt( R123 ); + vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 ); + vec3 C0 = R12 + Rs; + I = C0; + vec3 Cm = Rs - T121; + for ( int m = 1; m <= 2; ++ m ) { + Cm *= r123; + vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi ); + I += Cm * Sm; + } + return max( I, vec3( 0.0 ) ); + } +#endif`; + var bumpmap_pars_fragment2 = `#ifdef USE_BUMPMAP + uniform sampler2D bumpMap; + uniform float bumpScale; + vec2 dHdxy_fwd() { + vec2 dSTdx = dFdx( vBumpMapUv ); + vec2 dSTdy = dFdy( vBumpMapUv ); + float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x; + float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll; + float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll; + return vec2( dBx, dBy ); + } + vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) { + vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) ); + vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) ); + vec3 vN = surf_norm; + vec3 R1 = cross( vSigmaY, vN ); + vec3 R2 = cross( vN, vSigmaX ); + float fDet = dot( vSigmaX, R1 ) * faceDirection; + vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 ); + return normalize( abs( fDet ) * surf_norm - vGrad ); + } +#endif`; + var clipping_planes_fragment2 = `#if NUM_CLIPPING_PLANES > 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`; + var clipping_planes_pars_fragment2 = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`; + var clipping_planes_pars_vertex2 = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`; + var clipping_planes_vertex2 = `#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`; + var color_fragment2 = `#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`; + var color_pars_fragment2 = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`; + var color_pars_vertex2 = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`; + var color_vertex2 = `#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`; + var common2 = `#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`; + var cube_uv_reflection_fragment2 = `#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`; + var defaultnormal_vertex2 = `vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`; + var displacementmap_pars_vertex2 = `#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`; + var displacementmap_vertex2 = `#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`; + var emissivemap_fragment2 = `#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`; + var emissivemap_pars_fragment2 = `#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`; + var colorspace_fragment2 = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; + var colorspace_pars_fragment2 = `vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`; + var envmap_fragment2 = `#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`; + var envmap_common_pars_fragment2 = `#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`; + var envmap_pars_fragment2 = `#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`; + var envmap_pars_vertex2 = `#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`; + var envmap_vertex2 = `#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`; + var fog_vertex2 = `#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`; + var fog_pars_vertex2 = `#ifdef USE_FOG + varying float vFogDepth; +#endif`; + var fog_fragment2 = `#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`; + var fog_pars_fragment2 = `#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`; + var gradientmap_pars_fragment2 = `#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`; + var lightmap_pars_fragment2 = `#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`; + var lights_lambert_fragment2 = `LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`; + var lights_lambert_pars_fragment2 = `varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`; + var lights_pars_begin2 = `uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`; + var envmap_physical_pars_fragment2 = `#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`; + var lights_toon_fragment2 = `ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`; + var lights_toon_pars_fragment2 = `varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`; + var lights_phong_fragment2 = `BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`; + var lights_phong_pars_fragment2 = `varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`; + var lights_physical_fragment2 = `PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`; + var lights_physical_pars_fragment2 = `struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`; + var lights_fragment_begin2 = ` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`; + var lights_fragment_maps2 = `#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`; + var lights_fragment_end2 = `#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`; + var logdepthbuf_fragment2 = `#if defined( USE_LOGDEPTHBUF ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`; + var logdepthbuf_pars_fragment2 = `#if defined( USE_LOGDEPTHBUF ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`; + var logdepthbuf_pars_vertex2 = `#ifdef USE_LOGDEPTHBUF + varying float vFragDepth; + varying float vIsPerspective; +#endif`; + var logdepthbuf_vertex2 = `#ifdef USE_LOGDEPTHBUF + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`; + var map_fragment2 = `#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`; + var map_pars_fragment2 = `#ifdef USE_MAP + uniform sampler2D map; +#endif`; + var map_particle_fragment2 = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`; + var map_particle_pars_fragment2 = `#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`; + var metalnessmap_fragment2 = `float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`; + var metalnessmap_pars_fragment2 = `#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`; + var morphinstance_vertex2 = `#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`; + var morphcolor_vertex2 = `#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`; + var morphnormal_vertex2 = `#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`; + var morphtarget_pars_vertex2 = `#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`; + var morphtarget_vertex2 = `#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`; + var normal_fragment_begin2 = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`; + var normal_fragment_maps2 = `#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`; + var normal_pars_fragment2 = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`; + var normal_pars_vertex2 = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`; + var normal_vertex2 = `#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`; + var normalmap_pars_fragment2 = `#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`; + var clearcoat_normal_fragment_begin2 = `#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`; + var clearcoat_normal_fragment_maps2 = `#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`; + var clearcoat_pars_fragment2 = `#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`; + var iridescence_pars_fragment2 = `#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`; + var opaque_fragment2 = `#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`; + var packing2 = `vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`; + var premultiplied_alpha_fragment2 = `#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`; + var project_vertex2 = `vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`; + var dithering_fragment2 = `#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`; + var dithering_pars_fragment2 = `#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`; + var roughnessmap_fragment2 = `float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`; + var roughnessmap_pars_fragment2 = `#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`; + var shadowmap_pars_fragment2 = `#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`; + var shadowmap_pars_vertex2 = `#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`; + var shadowmap_vertex2 = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`; + var shadowmask_pars_fragment2 = `float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`; + var skinbase_vertex2 = `#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`; + var skinning_pars_vertex2 = `#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`; + var skinning_vertex2 = `#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`; + var skinnormal_vertex2 = `#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`; + var specularmap_fragment2 = `float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`; + var specularmap_pars_fragment2 = `#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`; + var tonemapping_fragment2 = `#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`; + var tonemapping_pars_fragment2 = `#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`; + var transmission_fragment2 = `#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`; + var transmission_pars_fragment2 = `#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`; + var uv_pars_fragment2 = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`; + var uv_pars_vertex2 = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`; + var uv_vertex2 = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`; + var worldpos_vertex2 = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`; + var vertex$h2 = `varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`; + var fragment$h2 = `uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`; + var vertex$g2 = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`; + var fragment$g2 = `#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`; + var vertex$f2 = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`; + var fragment$f2 = `uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`; + var vertex$e2 = `#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`; + var fragment$e2 = `#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`; + var vertex$d2 = `#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`; + var fragment$d2 = `#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`; + var vertex$c2 = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`; + var fragment$c2 = `uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`; + var vertex$b2 = `uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; + var fragment$b2 = `uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`; + var vertex$a2 = `#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; + var fragment$a2 = `uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`; + var vertex$92 = `#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`; + var fragment$92 = `#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`; + var vertex$82 = `#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`; + var fragment$82 = `#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`; + var vertex$72 = `#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`; + var fragment$72 = `#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`; + var vertex$62 = `#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`; + var fragment$62 = `#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`; + var vertex$52 = `#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`; + var fragment$52 = `#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`; + var vertex$42 = `#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`; + var fragment$42 = `#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`; + var vertex$32 = `uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`; + var fragment$32 = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`; + var vertex$22 = `#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; + var fragment$22 = `uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`; + var vertex$12 = `uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`; + var fragment$12 = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`; + var ShaderChunk2 = { + alphahash_fragment: alphahash_fragment2, + alphahash_pars_fragment: alphahash_pars_fragment2, + alphamap_fragment: alphamap_fragment2, + alphamap_pars_fragment: alphamap_pars_fragment2, + alphatest_fragment: alphatest_fragment2, + alphatest_pars_fragment: alphatest_pars_fragment2, + aomap_fragment: aomap_fragment2, + aomap_pars_fragment: aomap_pars_fragment2, + batching_pars_vertex: batching_pars_vertex2, + batching_vertex: batching_vertex2, + begin_vertex: begin_vertex2, + beginnormal_vertex: beginnormal_vertex2, + bsdfs: bsdfs2, + iridescence_fragment: iridescence_fragment2, + bumpmap_pars_fragment: bumpmap_pars_fragment2, + clipping_planes_fragment: clipping_planes_fragment2, + clipping_planes_pars_fragment: clipping_planes_pars_fragment2, + clipping_planes_pars_vertex: clipping_planes_pars_vertex2, + clipping_planes_vertex: clipping_planes_vertex2, + color_fragment: color_fragment2, + color_pars_fragment: color_pars_fragment2, + color_pars_vertex: color_pars_vertex2, + color_vertex: color_vertex2, + common: common2, + cube_uv_reflection_fragment: cube_uv_reflection_fragment2, + defaultnormal_vertex: defaultnormal_vertex2, + displacementmap_pars_vertex: displacementmap_pars_vertex2, + displacementmap_vertex: displacementmap_vertex2, + emissivemap_fragment: emissivemap_fragment2, + emissivemap_pars_fragment: emissivemap_pars_fragment2, + colorspace_fragment: colorspace_fragment2, + colorspace_pars_fragment: colorspace_pars_fragment2, + envmap_fragment: envmap_fragment2, + envmap_common_pars_fragment: envmap_common_pars_fragment2, + envmap_pars_fragment: envmap_pars_fragment2, + envmap_pars_vertex: envmap_pars_vertex2, + envmap_physical_pars_fragment: envmap_physical_pars_fragment2, + envmap_vertex: envmap_vertex2, + fog_vertex: fog_vertex2, + fog_pars_vertex: fog_pars_vertex2, + fog_fragment: fog_fragment2, + fog_pars_fragment: fog_pars_fragment2, + gradientmap_pars_fragment: gradientmap_pars_fragment2, + lightmap_pars_fragment: lightmap_pars_fragment2, + lights_lambert_fragment: lights_lambert_fragment2, + lights_lambert_pars_fragment: lights_lambert_pars_fragment2, + lights_pars_begin: lights_pars_begin2, + lights_toon_fragment: lights_toon_fragment2, + lights_toon_pars_fragment: lights_toon_pars_fragment2, + lights_phong_fragment: lights_phong_fragment2, + lights_phong_pars_fragment: lights_phong_pars_fragment2, + lights_physical_fragment: lights_physical_fragment2, + lights_physical_pars_fragment: lights_physical_pars_fragment2, + lights_fragment_begin: lights_fragment_begin2, + lights_fragment_maps: lights_fragment_maps2, + lights_fragment_end: lights_fragment_end2, + logdepthbuf_fragment: logdepthbuf_fragment2, + logdepthbuf_pars_fragment: logdepthbuf_pars_fragment2, + logdepthbuf_pars_vertex: logdepthbuf_pars_vertex2, + logdepthbuf_vertex: logdepthbuf_vertex2, + map_fragment: map_fragment2, + map_pars_fragment: map_pars_fragment2, + map_particle_fragment: map_particle_fragment2, + map_particle_pars_fragment: map_particle_pars_fragment2, + metalnessmap_fragment: metalnessmap_fragment2, + metalnessmap_pars_fragment: metalnessmap_pars_fragment2, + morphinstance_vertex: morphinstance_vertex2, + morphcolor_vertex: morphcolor_vertex2, + morphnormal_vertex: morphnormal_vertex2, + morphtarget_pars_vertex: morphtarget_pars_vertex2, + morphtarget_vertex: morphtarget_vertex2, + normal_fragment_begin: normal_fragment_begin2, + normal_fragment_maps: normal_fragment_maps2, + normal_pars_fragment: normal_pars_fragment2, + normal_pars_vertex: normal_pars_vertex2, + normal_vertex: normal_vertex2, + normalmap_pars_fragment: normalmap_pars_fragment2, + clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin2, + clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps2, + clearcoat_pars_fragment: clearcoat_pars_fragment2, + iridescence_pars_fragment: iridescence_pars_fragment2, + opaque_fragment: opaque_fragment2, + packing: packing2, + premultiplied_alpha_fragment: premultiplied_alpha_fragment2, + project_vertex: project_vertex2, + dithering_fragment: dithering_fragment2, + dithering_pars_fragment: dithering_pars_fragment2, + roughnessmap_fragment: roughnessmap_fragment2, + roughnessmap_pars_fragment: roughnessmap_pars_fragment2, + shadowmap_pars_fragment: shadowmap_pars_fragment2, + shadowmap_pars_vertex: shadowmap_pars_vertex2, + shadowmap_vertex: shadowmap_vertex2, + shadowmask_pars_fragment: shadowmask_pars_fragment2, + skinbase_vertex: skinbase_vertex2, + skinning_pars_vertex: skinning_pars_vertex2, + skinning_vertex: skinning_vertex2, + skinnormal_vertex: skinnormal_vertex2, + specularmap_fragment: specularmap_fragment2, + specularmap_pars_fragment: specularmap_pars_fragment2, + tonemapping_fragment: tonemapping_fragment2, + tonemapping_pars_fragment: tonemapping_pars_fragment2, + transmission_fragment: transmission_fragment2, + transmission_pars_fragment: transmission_pars_fragment2, + uv_pars_fragment: uv_pars_fragment2, + uv_pars_vertex: uv_pars_vertex2, + uv_vertex: uv_vertex2, + worldpos_vertex: worldpos_vertex2, + background_vert: vertex$h2, + background_frag: fragment$h2, + backgroundCube_vert: vertex$g2, + backgroundCube_frag: fragment$g2, + cube_vert: vertex$f2, + cube_frag: fragment$f2, + depth_vert: vertex$e2, + depth_frag: fragment$e2, + distanceRGBA_vert: vertex$d2, + distanceRGBA_frag: fragment$d2, + equirect_vert: vertex$c2, + equirect_frag: fragment$c2, + linedashed_vert: vertex$b2, + linedashed_frag: fragment$b2, + meshbasic_vert: vertex$a2, + meshbasic_frag: fragment$a2, + meshlambert_vert: vertex$92, + meshlambert_frag: fragment$92, + meshmatcap_vert: vertex$82, + meshmatcap_frag: fragment$82, + meshnormal_vert: vertex$72, + meshnormal_frag: fragment$72, + meshphong_vert: vertex$62, + meshphong_frag: fragment$62, + meshphysical_vert: vertex$52, + meshphysical_frag: fragment$52, + meshtoon_vert: vertex$42, + meshtoon_frag: fragment$42, + points_vert: vertex$32, + points_frag: fragment$32, + shadow_vert: vertex$22, + shadow_frag: fragment$22, + sprite_vert: vertex$12, + sprite_frag: fragment$12 + }; + var UniformsLib2 = { + common: { + diffuse: { value: /* @__PURE__ */ new Color2(16777215) }, + opacity: { value: 1 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaTest: { value: 0 } + }, + specularmap: { + specularMap: { value: null }, + specularMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + envmap: { + envMap: { value: null }, + envMapRotation: { value: /* @__PURE__ */ new Matrix32 }, + flipEnvMap: { value: -1 }, + reflectivity: { value: 1 }, + ior: { value: 1.5 }, + refractionRatio: { value: 0.98 } + }, + aomap: { + aoMap: { value: null }, + aoMapIntensity: { value: 1 }, + aoMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + lightmap: { + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + bumpmap: { + bumpMap: { value: null }, + bumpMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + bumpScale: { value: 1 } + }, + normalmap: { + normalMap: { value: null }, + normalMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + normalScale: { value: /* @__PURE__ */ new Vector22(1, 1) } + }, + displacementmap: { + displacementMap: { value: null }, + displacementMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + }, + emissivemap: { + emissiveMap: { value: null }, + emissiveMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + metalnessmap: { + metalnessMap: { value: null }, + metalnessMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + roughnessmap: { + roughnessMap: { value: null }, + roughnessMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + gradientmap: { + gradientMap: { value: null } + }, + fog: { + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: /* @__PURE__ */ new Color2(16777215) } + }, + lights: { + ambientLightColor: { value: [] }, + lightProbe: { value: [] }, + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + directionalLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + spotLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + pointLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + ltc_1: { value: null }, + ltc_2: { value: null } + }, + points: { + diffuse: { value: /* @__PURE__ */ new Color2(16777215) }, + opacity: { value: 1 }, + size: { value: 1 }, + scale: { value: 1 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaTest: { value: 0 }, + uvTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + sprite: { + diffuse: { value: /* @__PURE__ */ new Color2(16777215) }, + opacity: { value: 1 }, + center: { value: /* @__PURE__ */ new Vector22(0.5, 0.5) }, + rotation: { value: 0 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaTest: { value: 0 } + } + }; + var ShaderLib2 = { + basic: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.specularmap, + UniformsLib2.envmap, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.fog + ]), + vertexShader: ShaderChunk2.meshbasic_vert, + fragmentShader: ShaderChunk2.meshbasic_frag + }, + lambert: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.specularmap, + UniformsLib2.envmap, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.emissivemap, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.fog, + UniformsLib2.lights, + { + emissive: { value: /* @__PURE__ */ new Color2(0) } + } + ]), + vertexShader: ShaderChunk2.meshlambert_vert, + fragmentShader: ShaderChunk2.meshlambert_frag + }, + phong: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.specularmap, + UniformsLib2.envmap, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.emissivemap, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.fog, + UniformsLib2.lights, + { + emissive: { value: /* @__PURE__ */ new Color2(0) }, + specular: { value: /* @__PURE__ */ new Color2(1118481) }, + shininess: { value: 30 } + } + ]), + vertexShader: ShaderChunk2.meshphong_vert, + fragmentShader: ShaderChunk2.meshphong_frag + }, + standard: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.envmap, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.emissivemap, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.roughnessmap, + UniformsLib2.metalnessmap, + UniformsLib2.fog, + UniformsLib2.lights, + { + emissive: { value: /* @__PURE__ */ new Color2(0) }, + roughness: { value: 1 }, + metalness: { value: 0 }, + envMapIntensity: { value: 1 } + } + ]), + vertexShader: ShaderChunk2.meshphysical_vert, + fragmentShader: ShaderChunk2.meshphysical_frag + }, + toon: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.emissivemap, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.gradientmap, + UniformsLib2.fog, + UniformsLib2.lights, + { + emissive: { value: /* @__PURE__ */ new Color2(0) } + } + ]), + vertexShader: ShaderChunk2.meshtoon_vert, + fragmentShader: ShaderChunk2.meshtoon_frag + }, + matcap: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.fog, + { + matcap: { value: null } + } + ]), + vertexShader: ShaderChunk2.meshmatcap_vert, + fragmentShader: ShaderChunk2.meshmatcap_frag + }, + points: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.points, + UniformsLib2.fog + ]), + vertexShader: ShaderChunk2.points_vert, + fragmentShader: ShaderChunk2.points_frag + }, + dashed: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ]), + vertexShader: ShaderChunk2.linedashed_vert, + fragmentShader: ShaderChunk2.linedashed_frag + }, + depth: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.displacementmap + ]), + vertexShader: ShaderChunk2.depth_vert, + fragmentShader: ShaderChunk2.depth_frag + }, + normal: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + { + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk2.meshnormal_vert, + fragmentShader: ShaderChunk2.meshnormal_frag + }, + sprite: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.sprite, + UniformsLib2.fog + ]), + vertexShader: ShaderChunk2.sprite_vert, + fragmentShader: ShaderChunk2.sprite_frag + }, + background: { + uniforms: { + uvTransform: { value: /* @__PURE__ */ new Matrix32 }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + vertexShader: ShaderChunk2.background_vert, + fragmentShader: ShaderChunk2.background_frag + }, + backgroundCube: { + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /* @__PURE__ */ new Matrix32 } + }, + vertexShader: ShaderChunk2.backgroundCube_vert, + fragmentShader: ShaderChunk2.backgroundCube_frag + }, + cube: { + uniforms: { + tCube: { value: null }, + tFlip: { value: -1 }, + opacity: { value: 1 } + }, + vertexShader: ShaderChunk2.cube_vert, + fragmentShader: ShaderChunk2.cube_frag + }, + equirect: { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ShaderChunk2.equirect_vert, + fragmentShader: ShaderChunk2.equirect_frag + }, + distanceRGBA: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.displacementmap, + { + referencePosition: { value: /* @__PURE__ */ new Vector32 }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ]), + vertexShader: ShaderChunk2.distanceRGBA_vert, + fragmentShader: ShaderChunk2.distanceRGBA_frag + }, + shadow: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.lights, + UniformsLib2.fog, + { + color: { value: /* @__PURE__ */ new Color2(0) }, + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk2.shadow_vert, + fragmentShader: ShaderChunk2.shadow_frag + } + }; + ShaderLib2.physical = { + uniforms: /* @__PURE__ */ mergeUniforms2([ + ShaderLib2.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + clearcoatNormalScale: { value: /* @__PURE__ */ new Vector22(1, 1) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + dispersion: { value: 0 }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + sheen: { value: 0 }, + sheenColor: { value: /* @__PURE__ */ new Color2(0) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + transmissionSamplerSize: { value: /* @__PURE__ */ new Vector22 }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /* @__PURE__ */ new Color2(0) }, + specularColor: { value: /* @__PURE__ */ new Color2(1, 1, 1) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + anisotropyVector: { value: /* @__PURE__ */ new Vector22 }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /* @__PURE__ */ new Matrix32 } + } + ]), + vertexShader: ShaderChunk2.meshphysical_vert, + fragmentShader: ShaderChunk2.meshphysical_frag + }; + var _rgb2 = { r: 0, b: 0, g: 0 }; + var _e1$12 = /* @__PURE__ */ new Euler2; + var _m1$13 = /* @__PURE__ */ new Matrix42; + function WebGLBackground2(renderer2, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) { + const clearColor = new Color2(0); + let clearAlpha = alpha === true ? 0 : 1; + let planeMesh; + let boxMesh; + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + function getBackground(scene) { + let background = scene.isScene === true ? scene.background : null; + if (background && background.isTexture) { + const usePMREM = scene.backgroundBlurriness > 0; + background = (usePMREM ? cubeuvmaps : cubemaps).get(background); + } + return background; + } + function render(scene) { + let forceClear = false; + const background = getBackground(scene); + if (background === null) { + setClear(clearColor, clearAlpha); + } else if (background && background.isColor) { + setClear(background, 1); + forceClear = true; + } + const environmentBlendMode = renderer2.xr.getEnvironmentBlendMode(); + if (environmentBlendMode === "additive") { + state.buffers.color.setClear(0, 0, 0, 1, premultipliedAlpha); + } else if (environmentBlendMode === "alpha-blend") { + state.buffers.color.setClear(0, 0, 0, 0, premultipliedAlpha); + } + if (renderer2.autoClear || forceClear) { + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + renderer2.clear(renderer2.autoClearColor, renderer2.autoClearDepth, renderer2.autoClearStencil); + } + } + function addToRenderList(renderList, scene) { + const background = getBackground(scene); + if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping2)) { + if (boxMesh === undefined) { + boxMesh = new Mesh2(new BoxGeometry2(1, 1, 1), new ShaderMaterial2({ + name: "BackgroundCubeMaterial", + uniforms: cloneUniforms2(ShaderLib2.backgroundCube.uniforms), + vertexShader: ShaderLib2.backgroundCube.vertexShader, + fragmentShader: ShaderLib2.backgroundCube.fragmentShader, + side: BackSide2, + depthTest: false, + depthWrite: false, + fog: false + })); + boxMesh.geometry.deleteAttribute("normal"); + boxMesh.geometry.deleteAttribute("uv"); + boxMesh.onBeforeRender = function(renderer3, scene2, camera) { + this.matrixWorld.copyPosition(camera.matrixWorld); + }; + Object.defineProperty(boxMesh.material, "envMap", { + get: function() { + return this.uniforms.envMap.value; + } + }); + objects.update(boxMesh); + } + _e1$12.copy(scene.backgroundRotation); + _e1$12.x *= -1; + _e1$12.y *= -1; + _e1$12.z *= -1; + if (background.isCubeTexture && background.isRenderTargetTexture === false) { + _e1$12.y *= -1; + _e1$12.z *= -1; + } + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4(_m1$13.makeRotationFromEuler(_e1$12)); + boxMesh.material.toneMapped = ColorManagement2.getTransfer(background.colorSpace) !== SRGBTransfer2; + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer2.toneMapping) { + boxMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer2.toneMapping; + } + boxMesh.layers.enableAll(); + renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null); + } else if (background && background.isTexture) { + if (planeMesh === undefined) { + planeMesh = new Mesh2(new PlaneGeometry3(2, 2), new ShaderMaterial2({ + name: "BackgroundMaterial", + uniforms: cloneUniforms2(ShaderLib2.background.uniforms), + vertexShader: ShaderLib2.background.vertexShader, + fragmentShader: ShaderLib2.background.fragmentShader, + side: FrontSide2, + depthTest: false, + depthWrite: false, + fog: false + })); + planeMesh.geometry.deleteAttribute("normal"); + Object.defineProperty(planeMesh.material, "map", { + get: function() { + return this.uniforms.t2D.value; + } + }); + objects.update(planeMesh); + } + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ColorManagement2.getTransfer(background.colorSpace) !== SRGBTransfer2; + if (background.matrixAutoUpdate === true) { + background.updateMatrix(); + } + planeMesh.material.uniforms.uvTransform.value.copy(background.matrix); + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer2.toneMapping) { + planeMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer2.toneMapping; + } + planeMesh.layers.enableAll(); + renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null); + } + } + function setClear(color, alpha2) { + color.getRGB(_rgb2, getUnlitUniformColorSpace2(renderer2)); + state.buffers.color.setClear(_rgb2.r, _rgb2.g, _rgb2.b, alpha2, premultipliedAlpha); + } + function dispose() { + if (boxMesh !== undefined) { + boxMesh.geometry.dispose(); + boxMesh.material.dispose(); + boxMesh = undefined; + } + if (planeMesh !== undefined) { + planeMesh.geometry.dispose(); + planeMesh.material.dispose(); + planeMesh = undefined; + } + } + return { + getClearColor: function() { + return clearColor; + }, + setClearColor: function(color, alpha2 = 1) { + clearColor.set(color); + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + getClearAlpha: function() { + return clearAlpha; + }, + setClearAlpha: function(alpha2) { + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + render, + addToRenderList, + dispose + }; + } + function WebGLBindingStates2(gl, attributes) { + const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const bindingStates = {}; + const defaultState2 = createBindingState(null); + let currentState = defaultState2; + let forceUpdate = false; + function setup(object, material, program, geometry, index2) { + let updateBuffers = false; + const state = getBindingState(geometry, program, material); + if (currentState !== state) { + currentState = state; + bindVertexArrayObject(currentState.object); + } + updateBuffers = needsUpdate(object, geometry, program, index2); + if (updateBuffers) + saveCache(object, geometry, program, index2); + if (index2 !== null) { + attributes.update(index2, gl.ELEMENT_ARRAY_BUFFER); + } + if (updateBuffers || forceUpdate) { + forceUpdate = false; + setupVertexAttributes(object, material, program, geometry); + if (index2 !== null) { + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index2).buffer); + } + } + } + function createVertexArrayObject() { + return gl.createVertexArray(); + } + function bindVertexArrayObject(vao) { + return gl.bindVertexArray(vao); + } + function deleteVertexArrayObject(vao) { + return gl.deleteVertexArray(vao); + } + function getBindingState(geometry, program, material) { + const wireframe = material.wireframe === true; + let programMap = bindingStates[geometry.id]; + if (programMap === undefined) { + programMap = {}; + bindingStates[geometry.id] = programMap; + } + let stateMap = programMap[program.id]; + if (stateMap === undefined) { + stateMap = {}; + programMap[program.id] = stateMap; + } + let state = stateMap[wireframe]; + if (state === undefined) { + state = createBindingState(createVertexArrayObject()); + stateMap[wireframe] = state; + } + return state; + } + function createBindingState(vao) { + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + for (let i = 0;i < maxVertexAttributes; i++) { + newAttributes[i] = 0; + enabledAttributes[i] = 0; + attributeDivisors[i] = 0; + } + return { + geometry: null, + program: null, + wireframe: false, + newAttributes, + enabledAttributes, + attributeDivisors, + object: vao, + attributes: {}, + index: null + }; + } + function needsUpdate(object, geometry, program, index2) { + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + const cachedAttribute = cachedAttributes[name2]; + let geometryAttribute = geometryAttributes[name2]; + if (geometryAttribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + geometryAttribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + geometryAttribute = object.instanceColor; + } + if (cachedAttribute === undefined) + return true; + if (cachedAttribute.attribute !== geometryAttribute) + return true; + if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) + return true; + attributesNum++; + } + } + if (currentState.attributesNum !== attributesNum) + return true; + if (currentState.index !== index2) + return true; + return false; + } + function saveCache(object, geometry, program, index2) { + const cache = {}; + const attributes2 = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + let attribute = attributes2[name2]; + if (attribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + attribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + attribute = object.instanceColor; + } + const data2 = {}; + data2.attribute = attribute; + if (attribute && attribute.data) { + data2.data = attribute.data; + } + cache[name2] = data2; + attributesNum++; + } + } + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + currentState.index = index2; + } + function initAttributes() { + const newAttributes = currentState.newAttributes; + for (let i = 0, il = newAttributes.length;i < il; i++) { + newAttributes[i] = 0; + } + } + function enableAttribute(attribute) { + enableAttributeAndDivisor(attribute, 0); + } + function enableAttributeAndDivisor(attribute, meshPerAttribute) { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + newAttributes[attribute] = 1; + if (enabledAttributes[attribute] === 0) { + gl.enableVertexAttribArray(attribute); + enabledAttributes[attribute] = 1; + } + if (attributeDivisors[attribute] !== meshPerAttribute) { + gl.vertexAttribDivisor(attribute, meshPerAttribute); + attributeDivisors[attribute] = meshPerAttribute; + } + } + function disableUnusedAttributes() { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + for (let i = 0, il = enabledAttributes.length;i < il; i++) { + if (enabledAttributes[i] !== newAttributes[i]) { + gl.disableVertexAttribArray(i); + enabledAttributes[i] = 0; + } + } + } + function vertexAttribPointer(index2, size2, type, normalized, stride, offset, integer) { + if (integer === true) { + gl.vertexAttribIPointer(index2, size2, type, stride, offset); + } else { + gl.vertexAttribPointer(index2, size2, type, normalized, stride, offset); + } + } + function setupVertexAttributes(object, material, program, geometry) { + initAttributes(); + const geometryAttributes = geometry.attributes; + const programAttributes = program.getAttributes(); + const materialDefaultAttributeValues = material.defaultAttributeValues; + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + let geometryAttribute = geometryAttributes[name2]; + if (geometryAttribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + geometryAttribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + geometryAttribute = object.instanceColor; + } + if (geometryAttribute !== undefined) { + const normalized = geometryAttribute.normalized; + const size2 = geometryAttribute.itemSize; + const attribute = attributes.get(geometryAttribute); + if (attribute === undefined) + continue; + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + const integer = type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType2; + if (geometryAttribute.isInterleavedBufferAttribute) { + const data2 = geometryAttribute.data; + const stride = data2.stride; + const offset = geometryAttribute.offset; + if (data2.isInstancedInterleavedBuffer) { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, data2.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { + geometry._maxInstanceCount = data2.meshPerAttribute * data2.count; + } + } else { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0;i < programAttribute.locationSize; i++) { + vertexAttribPointer(programAttribute.location + i, size2 / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size2 / programAttribute.locationSize * i) * bytesPerElement, integer); + } + } else { + if (geometryAttribute.isInstancedBufferAttribute) { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } + } else { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0;i < programAttribute.locationSize; i++) { + vertexAttribPointer(programAttribute.location + i, size2 / programAttribute.locationSize, type, normalized, size2 * bytesPerElement, size2 / programAttribute.locationSize * i * bytesPerElement, integer); + } + } + } else if (materialDefaultAttributeValues !== undefined) { + const value2 = materialDefaultAttributeValues[name2]; + if (value2 !== undefined) { + switch (value2.length) { + case 2: + gl.vertexAttrib2fv(programAttribute.location, value2); + break; + case 3: + gl.vertexAttrib3fv(programAttribute.location, value2); + break; + case 4: + gl.vertexAttrib4fv(programAttribute.location, value2); + break; + default: + gl.vertexAttrib1fv(programAttribute.location, value2); + } + } + } + } + } + disableUnusedAttributes(); + } + function dispose() { + reset(); + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometryId]; + } + } + function releaseStatesOfGeometry(geometry) { + if (bindingStates[geometry.id] === undefined) + return; + const programMap = bindingStates[geometry.id]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometry.id]; + } + function releaseStatesOfProgram(program) { + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + if (programMap[program.id] === undefined) + continue; + const stateMap = programMap[program.id]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[program.id]; + } + } + function reset() { + resetDefaultState(); + forceUpdate = true; + if (currentState === defaultState2) + return; + currentState = defaultState2; + bindVertexArrayObject(currentState.object); + } + function resetDefaultState() { + defaultState2.geometry = null; + defaultState2.program = null; + defaultState2.wireframe = false; + } + return { + setup, + reset, + resetDefaultState, + dispose, + releaseStatesOfGeometry, + releaseStatesOfProgram, + initAttributes, + enableAttribute, + disableUnusedAttributes + }; + } + function WebGLBufferRenderer2(gl, extensions, info) { + let mode; + function setMode(value2) { + mode = value2; + } + function render(start, count) { + gl.drawArrays(mode, start, count); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) + return; + gl.drawArraysInstanced(mode, start, count, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawArraysWEBGL(mode, starts, 0, counts, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0;i < starts.length; i++) { + renderInstances(starts[i], counts[i], primcount[i]); + } + } else { + extension.multiDrawArraysInstancedWEBGL(mode, starts, 0, counts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i] * primcount[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; + } + function WebGLCapabilities2(gl, extensions, parameters, utils) { + let maxAnisotropy; + function getMaxAnisotropy() { + if (maxAnisotropy !== undefined) + return maxAnisotropy; + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } else { + maxAnisotropy = 0; + } + return maxAnisotropy; + } + function textureFormatReadable(textureFormat) { + if (textureFormat !== RGBAFormat2 && utils.convert(textureFormat) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT)) { + return false; + } + return true; + } + function textureTypeReadable(textureType) { + const halfFloatSupportedByExt = textureType === HalfFloatType2 && (extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float")); + if (textureType !== UnsignedByteType2 && utils.convert(textureType) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE) && textureType !== FloatType2 && !halfFloatSupportedByExt) { + return false; + } + return true; + } + function getMaxPrecision(precision2) { + if (precision2 === "highp") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) { + return "highp"; + } + precision2 = "mediump"; + } + if (precision2 === "mediump") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) { + return "mediump"; + } + } + return "lowp"; + } + let precision = parameters.precision !== undefined ? parameters.precision : "highp"; + const maxPrecision = getMaxPrecision(precision); + if (maxPrecision !== precision) { + console.warn("THREE.WebGLRenderer:", precision, "not supported, using", maxPrecision, "instead."); + precision = maxPrecision; + } + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has("EXT_clip_control"); + const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); + const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); + const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); + const vertexTextures = maxVertexTextures > 0; + const maxSamples = gl.getParameter(gl.MAX_SAMPLES); + return { + isWebGL2: true, + getMaxAnisotropy, + getMaxPrecision, + textureFormatReadable, + textureTypeReadable, + precision, + logarithmicDepthBuffer, + reverseDepthBuffer, + maxTextures, + maxVertexTextures, + maxTextureSize, + maxCubemapSize, + maxAttributes, + maxVertexUniforms, + maxVaryings, + maxFragmentUniforms, + vertexTextures, + maxSamples + }; + } + function WebGLClipping2(properties) { + const scope = this; + let globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false; + const plane = new Plane2, viewNormalMatrix = new Matrix32, uniform = { value: null, needsUpdate: false }; + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + this.init = function(planes, enableLocalClipping) { + const enabled = planes.length !== 0 || enableLocalClipping || numGlobalPlanes !== 0 || localClippingEnabled; + localClippingEnabled = enableLocalClipping; + numGlobalPlanes = planes.length; + return enabled; + }; + this.beginShadows = function() { + renderingShadows = true; + projectPlanes(null); + }; + this.endShadows = function() { + renderingShadows = false; + }; + this.setGlobalState = function(planes, camera) { + globalState = projectPlanes(planes, camera, 0); + }; + this.setState = function(material, camera, useCache) { + const { clippingPlanes: planes, clipIntersection, clipShadows } = material; + const materialProperties = properties.get(material); + if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) { + if (renderingShadows) { + projectPlanes(null); + } else { + resetGlobalState(); + } + } else { + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4; + let dstArray = materialProperties.clippingState || null; + uniform.value = dstArray; + dstArray = projectPlanes(planes, camera, lGlobal, useCache); + for (let i = 0;i !== lGlobal; ++i) { + dstArray[i] = globalState[i]; + } + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + } + }; + function resetGlobalState() { + if (uniform.value !== globalState) { + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + } + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + } + function projectPlanes(planes, camera, dstOffset, skipTransform) { + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + if (nPlanes !== 0) { + dstArray = uniform.value; + if (skipTransform !== true || dstArray === null) { + const flatSize = dstOffset + nPlanes * 4, viewMatrix = camera.matrixWorldInverse; + viewNormalMatrix.getNormalMatrix(viewMatrix); + if (dstArray === null || dstArray.length < flatSize) { + dstArray = new Float32Array(flatSize); + } + for (let i = 0, i4 = dstOffset;i !== nPlanes; ++i, i4 += 4) { + plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix); + plane.normal.toArray(dstArray, i4); + dstArray[i4 + 3] = plane.constant; + } + } + uniform.value = dstArray; + uniform.needsUpdate = true; + } + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + return dstArray; + } + } + function WebGLCubeMaps2(renderer2) { + let cubemaps = new WeakMap; + function mapTextureMapping(texture, mapping) { + if (mapping === EquirectangularReflectionMapping2) { + texture.mapping = CubeReflectionMapping2; + } else if (mapping === EquirectangularRefractionMapping2) { + texture.mapping = CubeRefractionMapping2; + } + return texture; + } + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + if (mapping === EquirectangularReflectionMapping2 || mapping === EquirectangularRefractionMapping2) { + if (cubemaps.has(texture)) { + const cubemap = cubemaps.get(texture).texture; + return mapTextureMapping(cubemap, texture.mapping); + } else { + const image = texture.image; + if (image && image.height > 0) { + const renderTarget = new WebGLCubeRenderTarget2(image.height); + renderTarget.fromEquirectangularTexture(renderer2, texture); + cubemaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return mapTextureMapping(renderTarget.texture, texture.mapping); + } else { + return null; + } + } + } + } + return texture; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemap = cubemaps.get(texture); + if (cubemap !== undefined) { + cubemaps.delete(texture); + cubemap.dispose(); + } + } + function dispose() { + cubemaps = new WeakMap; + } + return { + get, + dispose + }; + } + var LOD_MIN2 = 4; + var EXTRA_LOD_SIGMA2 = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; + var MAX_SAMPLES2 = 20; + var _flatCamera2 = /* @__PURE__ */ new OrthographicCamera2; + var _clearColor2 = /* @__PURE__ */ new Color2; + var _oldTarget2 = null; + var _oldActiveCubeFace2 = 0; + var _oldActiveMipmapLevel2 = 0; + var _oldXrEnabled2 = false; + var PHI2 = (1 + Math.sqrt(5)) / 2; + var INV_PHI2 = 1 / PHI2; + var _axisDirections2 = [ + /* @__PURE__ */ new Vector32(-PHI2, INV_PHI2, 0), + /* @__PURE__ */ new Vector32(PHI2, INV_PHI2, 0), + /* @__PURE__ */ new Vector32(-INV_PHI2, 0, PHI2), + /* @__PURE__ */ new Vector32(INV_PHI2, 0, PHI2), + /* @__PURE__ */ new Vector32(0, PHI2, -INV_PHI2), + /* @__PURE__ */ new Vector32(0, PHI2, INV_PHI2), + /* @__PURE__ */ new Vector32(-1, 1, -1), + /* @__PURE__ */ new Vector32(1, 1, -1), + /* @__PURE__ */ new Vector32(-1, 1, 1), + /* @__PURE__ */ new Vector32(1, 1, 1) + ]; + + class PMREMGenerator2 { + constructor(renderer2) { + this._renderer = renderer2; + this._pingPongRenderTarget = null; + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + this._compileMaterial(this._blurMaterial); + } + fromScene(scene, sigma = 0, near = 0.1, far = 100) { + _oldTarget2 = this._renderer.getRenderTarget(); + _oldActiveCubeFace2 = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel2 = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled2 = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + this._setSize(256); + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget); + if (sigma > 0) { + this._blur(cubeUVRenderTarget, 0, 0, sigma); + } + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + fromEquirectangular(equirectangular, renderTarget = null) { + return this._fromTexture(equirectangular, renderTarget); + } + fromCubemap(cubemap, renderTarget = null) { + return this._fromTexture(cubemap, renderTarget); + } + compileCubemapShader() { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial2(); + this._compileMaterial(this._cubemapMaterial); + } + } + compileEquirectangularShader() { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial2(); + this._compileMaterial(this._equirectMaterial); + } + } + dispose() { + this._dispose(); + if (this._cubemapMaterial !== null) + this._cubemapMaterial.dispose(); + if (this._equirectMaterial !== null) + this._equirectMaterial.dispose(); + } + _setSize(cubeSize) { + this._lodMax = Math.floor(Math.log2(cubeSize)); + this._cubeSize = Math.pow(2, this._lodMax); + } + _dispose() { + if (this._blurMaterial !== null) + this._blurMaterial.dispose(); + if (this._pingPongRenderTarget !== null) + this._pingPongRenderTarget.dispose(); + for (let i = 0;i < this._lodPlanes.length; i++) { + this._lodPlanes[i].dispose(); + } + } + _cleanup(outputTarget) { + this._renderer.setRenderTarget(_oldTarget2, _oldActiveCubeFace2, _oldActiveMipmapLevel2); + this._renderer.xr.enabled = _oldXrEnabled2; + outputTarget.scissorTest = false; + _setViewport2(outputTarget, 0, 0, outputTarget.width, outputTarget.height); + } + _fromTexture(texture, renderTarget) { + if (texture.mapping === CubeReflectionMapping2 || texture.mapping === CubeRefractionMapping2) { + this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width); + } else { + this._setSize(texture.image.width / 4); + } + _oldTarget2 = this._renderer.getRenderTarget(); + _oldActiveCubeFace2 = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel2 = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled2 = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV(texture, cubeUVRenderTarget); + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + _allocateTargets() { + const width2 = 3 * Math.max(this._cubeSize, 16 * 7); + const height2 = 4 * this._cubeSize; + const params = { + magFilter: LinearFilter2, + minFilter: LinearFilter2, + generateMipmaps: false, + type: HalfFloatType2, + format: RGBAFormat2, + colorSpace: LinearSRGBColorSpace2, + depthBuffer: false + }; + const cubeUVRenderTarget = _createRenderTarget2(width2, height2, params); + if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width2 || this._pingPongRenderTarget.height !== height2) { + if (this._pingPongRenderTarget !== null) { + this._dispose(); + } + this._pingPongRenderTarget = _createRenderTarget2(width2, height2, params); + const { _lodMax } = this; + ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes2(_lodMax)); + this._blurMaterial = _getBlurShader2(_lodMax, width2, height2); + } + return cubeUVRenderTarget; + } + _compileMaterial(material) { + const tmpMesh = new Mesh2(this._lodPlanes[0], material); + this._renderer.compile(tmpMesh, _flatCamera2); + } + _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) { + const fov3 = 90; + const aspect3 = 1; + const cubeCamera = new PerspectiveCamera2(fov3, aspect3, near, far); + const upSign = [1, -1, 1, 1, 1, 1]; + const forwardSign = [1, 1, 1, -1, -1, -1]; + const renderer2 = this._renderer; + const originalAutoClear = renderer2.autoClear; + const toneMapping = renderer2.toneMapping; + renderer2.getClearColor(_clearColor2); + renderer2.toneMapping = NoToneMapping2; + renderer2.autoClear = false; + const backgroundMaterial = new MeshBasicMaterial2({ + name: "PMREM.Background", + side: BackSide2, + depthWrite: false, + depthTest: false + }); + const backgroundBox = new Mesh2(new BoxGeometry2, backgroundMaterial); + let useSolidColor = false; + const background = scene.background; + if (background) { + if (background.isColor) { + backgroundMaterial.color.copy(background); + scene.background = null; + useSolidColor = true; + } + } else { + backgroundMaterial.color.copy(_clearColor2); + useSolidColor = true; + } + for (let i = 0;i < 6; i++) { + const col = i % 3; + if (col === 0) { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(forwardSign[i], 0, 0); + } else if (col === 1) { + cubeCamera.up.set(0, 0, upSign[i]); + cubeCamera.lookAt(0, forwardSign[i], 0); + } else { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(0, 0, forwardSign[i]); + } + const size2 = this._cubeSize; + _setViewport2(cubeUVRenderTarget, col * size2, i > 2 ? size2 : 0, size2, size2); + renderer2.setRenderTarget(cubeUVRenderTarget); + if (useSolidColor) { + renderer2.render(backgroundBox, cubeCamera); + } + renderer2.render(scene, cubeCamera); + } + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + renderer2.toneMapping = toneMapping; + renderer2.autoClear = originalAutoClear; + scene.background = background; + } + _textureToCubeUV(texture, cubeUVRenderTarget) { + const renderer2 = this._renderer; + const isCubeTexture = texture.mapping === CubeReflectionMapping2 || texture.mapping === CubeRefractionMapping2; + if (isCubeTexture) { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial2(); + } + this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1; + } else { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial2(); + } + } + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh2(this._lodPlanes[0], material); + const uniforms = material.uniforms; + uniforms["envMap"].value = texture; + const size2 = this._cubeSize; + _setViewport2(cubeUVRenderTarget, 0, 0, 3 * size2, 2 * size2); + renderer2.setRenderTarget(cubeUVRenderTarget); + renderer2.render(mesh, _flatCamera2); + } + _applyPMREM(cubeUVRenderTarget) { + const renderer2 = this._renderer; + const autoClear = renderer2.autoClear; + renderer2.autoClear = false; + const n2 = this._lodPlanes.length; + for (let i = 1;i < n2; i++) { + const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]); + const poleAxis = _axisDirections2[(n2 - i - 1) % _axisDirections2.length]; + this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis); + } + renderer2.autoClear = autoClear; + } + _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) { + const pingPongRenderTarget = this._pingPongRenderTarget; + this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, "latitudinal", poleAxis); + this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, "longitudinal", poleAxis); + } + _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) { + const renderer2 = this._renderer; + const blurMaterial = this._blurMaterial; + if (direction !== "latitudinal" && direction !== "longitudinal") { + console.error("blur direction must be either latitudinal or longitudinal!"); + } + const STANDARD_DEVIATIONS = 3; + const blurMesh = new Mesh2(this._lodPlanes[lodOut], blurMaterial); + const blurUniforms = blurMaterial.uniforms; + const pixels = this._sizeLods[lodIn] - 1; + const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES2 - 1); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES2; + if (samples > MAX_SAMPLES2) { + console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES2}`); + } + const weights = []; + let sum2 = 0; + for (let i = 0;i < MAX_SAMPLES2; ++i) { + const x3 = i / sigmaPixels; + const weight = Math.exp(-x3 * x3 / 2); + weights.push(weight); + if (i === 0) { + sum2 += weight; + } else if (i < samples) { + sum2 += 2 * weight; + } + } + for (let i = 0;i < weights.length; i++) { + weights[i] = weights[i] / sum2; + } + blurUniforms["envMap"].value = targetIn.texture; + blurUniforms["samples"].value = samples; + blurUniforms["weights"].value = weights; + blurUniforms["latitudinal"].value = direction === "latitudinal"; + if (poleAxis) { + blurUniforms["poleAxis"].value = poleAxis; + } + const { _lodMax } = this; + blurUniforms["dTheta"].value = radiansPerPixel; + blurUniforms["mipInt"].value = _lodMax - lodIn; + const outputSize = this._sizeLods[lodOut]; + const x2 = 3 * outputSize * (lodOut > _lodMax - LOD_MIN2 ? lodOut - _lodMax + LOD_MIN2 : 0); + const y3 = 4 * (this._cubeSize - outputSize); + _setViewport2(targetOut, x2, y3, 3 * outputSize, 2 * outputSize); + renderer2.setRenderTarget(targetOut); + renderer2.render(blurMesh, _flatCamera2); + } + } + function _createPlanes2(lodMax) { + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + let lod = lodMax; + const totalLods = lodMax - LOD_MIN2 + 1 + EXTRA_LOD_SIGMA2.length; + for (let i = 0;i < totalLods; i++) { + const sizeLod = Math.pow(2, lod); + sizeLods.push(sizeLod); + let sigma = 1 / sizeLod; + if (i > lodMax - LOD_MIN2) { + sigma = EXTRA_LOD_SIGMA2[i - lodMax + LOD_MIN2 - 1]; + } else if (i === 0) { + sigma = 0; + } + sigmas.push(sigma); + const texelSize = 1 / (sizeLod - 2); + const min = -texelSize; + const max = 1 + texelSize; + const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max]; + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + const position2 = new Float32Array(positionSize * vertices * cubeFaces); + const uv = new Float32Array(uvSize * vertices * cubeFaces); + const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces); + for (let face = 0;face < cubeFaces; face++) { + const x2 = face % 3 * 2 / 3 - 1; + const y3 = face > 2 ? 0 : -1; + const coordinates = [ + x2, + y3, + 0, + x2 + 2 / 3, + y3, + 0, + x2 + 2 / 3, + y3 + 1, + 0, + x2, + y3, + 0, + x2 + 2 / 3, + y3 + 1, + 0, + x2, + y3 + 1, + 0 + ]; + position2.set(coordinates, positionSize * vertices * face); + uv.set(uv1, uvSize * vertices * face); + const fill3 = [face, face, face, face, face, face]; + faceIndex.set(fill3, faceIndexSize * vertices * face); + } + const planes = new BufferGeometry2; + planes.setAttribute("position", new BufferAttribute2(position2, positionSize)); + planes.setAttribute("uv", new BufferAttribute2(uv, uvSize)); + planes.setAttribute("faceIndex", new BufferAttribute2(faceIndex, faceIndexSize)); + lodPlanes.push(planes); + if (lod > LOD_MIN2) { + lod--; + } + } + return { lodPlanes, sizeLods, sigmas }; + } + function _createRenderTarget2(width2, height2, params) { + const cubeUVRenderTarget = new WebGLRenderTarget2(width2, height2, params); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping2; + cubeUVRenderTarget.texture.name = "PMREM.cubeUv"; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + } + function _setViewport2(target, x2, y3, width2, height2) { + target.viewport.set(x2, y3, width2, height2); + target.scissor.set(x2, y3, width2, height2); + } + function _getBlurShader2(lodMax, width2, height2) { + const weights = new Float32Array(MAX_SAMPLES2); + const poleAxis = new Vector32(0, 1, 0); + const shaderMaterial = new ShaderMaterial2({ + name: "SphericalGaussianBlur", + defines: { + n: MAX_SAMPLES2, + CUBEUV_TEXEL_WIDTH: 1 / width2, + CUBEUV_TEXEL_HEIGHT: 1 / height2, + CUBEUV_MAX_MIP: `${lodMax}.0` + }, + uniforms: { + envMap: { value: null }, + samples: { value: 1 }, + weights: { value: weights }, + latitudinal: { value: false }, + dTheta: { value: 0 }, + mipInt: { value: 0 }, + poleAxis: { value: poleAxis } + }, + vertexShader: _getCommonVertexShader2(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `, + blending: NoBlending2, + depthTest: false, + depthWrite: false + }); + return shaderMaterial; + } + function _getEquirectMaterial2() { + return new ShaderMaterial2({ + name: "EquirectangularToCubeUV", + uniforms: { + envMap: { value: null } + }, + vertexShader: _getCommonVertexShader2(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `, + blending: NoBlending2, + depthTest: false, + depthWrite: false + }); + } + function _getCubemapMaterial2() { + return new ShaderMaterial2({ + name: "CubemapToCubeUV", + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 } + }, + vertexShader: _getCommonVertexShader2(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `, + blending: NoBlending2, + depthTest: false, + depthWrite: false + }); + } + function _getCommonVertexShader2() { + return ` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `; + } + function WebGLCubeUVMaps2(renderer2) { + let cubeUVmaps = new WeakMap; + let pmremGenerator = null; + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + const isEquirectMap = mapping === EquirectangularReflectionMapping2 || mapping === EquirectangularRefractionMapping2; + const isCubeMap = mapping === CubeReflectionMapping2 || mapping === CubeRefractionMapping2; + if (isEquirectMap || isCubeMap) { + let renderTarget = cubeUVmaps.get(texture); + const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0; + if (texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion) { + if (pmremGenerator === null) + pmremGenerator = new PMREMGenerator2(renderer2); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + return renderTarget.texture; + } else { + if (renderTarget !== undefined) { + return renderTarget.texture; + } else { + const image = texture.image; + if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) { + if (pmremGenerator === null) + pmremGenerator = new PMREMGenerator2(renderer2); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return renderTarget.texture; + } else { + return null; + } + } + } + } + } + return texture; + } + function isCubeTextureComplete(image) { + let count = 0; + const length2 = 6; + for (let i = 0;i < length2; i++) { + if (image[i] !== undefined) + count++; + } + return count === length2; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemapUV = cubeUVmaps.get(texture); + if (cubemapUV !== undefined) { + cubeUVmaps.delete(texture); + cubemapUV.dispose(); + } + } + function dispose() { + cubeUVmaps = new WeakMap; + if (pmremGenerator !== null) { + pmremGenerator.dispose(); + pmremGenerator = null; + } + } + return { + get, + dispose + }; + } + function WebGLExtensions2(gl) { + const extensions = {}; + function getExtension(name2) { + if (extensions[name2] !== undefined) { + return extensions[name2]; + } + let extension; + switch (name2) { + case "WEBGL_depth_texture": + extension = gl.getExtension("WEBGL_depth_texture") || gl.getExtension("MOZ_WEBGL_depth_texture") || gl.getExtension("WEBKIT_WEBGL_depth_texture"); + break; + case "EXT_texture_filter_anisotropic": + extension = gl.getExtension("EXT_texture_filter_anisotropic") || gl.getExtension("MOZ_EXT_texture_filter_anisotropic") || gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic"); + break; + case "WEBGL_compressed_texture_s3tc": + extension = gl.getExtension("WEBGL_compressed_texture_s3tc") || gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"); + break; + case "WEBGL_compressed_texture_pvrtc": + extension = gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"); + break; + default: + extension = gl.getExtension(name2); + } + extensions[name2] = extension; + return extension; + } + return { + has: function(name2) { + return getExtension(name2) !== null; + }, + init: function() { + getExtension("EXT_color_buffer_float"); + getExtension("WEBGL_clip_cull_distance"); + getExtension("OES_texture_float_linear"); + getExtension("EXT_color_buffer_half_float"); + getExtension("WEBGL_multisampled_render_to_texture"); + getExtension("WEBGL_render_shared_exponent"); + }, + get: function(name2) { + const extension = getExtension(name2); + if (extension === null) { + warnOnce2("THREE.WebGLRenderer: " + name2 + " extension not supported."); + } + return extension; + } + }; + } + function WebGLGeometries2(gl, attributes, info, bindingStates) { + const geometries = {}; + const wireframeAttributes = new WeakMap; + function onGeometryDispose(event) { + const geometry = event.target; + if (geometry.index !== null) { + attributes.remove(geometry.index); + } + for (const name2 in geometry.attributes) { + attributes.remove(geometry.attributes[name2]); + } + geometry.removeEventListener("dispose", onGeometryDispose); + delete geometries[geometry.id]; + const attribute = wireframeAttributes.get(geometry); + if (attribute) { + attributes.remove(attribute); + wireframeAttributes.delete(geometry); + } + bindingStates.releaseStatesOfGeometry(geometry); + if (geometry.isInstancedBufferGeometry === true) { + delete geometry._maxInstanceCount; + } + info.memory.geometries--; + } + function get(object, geometry) { + if (geometries[geometry.id] === true) + return geometry; + geometry.addEventListener("dispose", onGeometryDispose); + geometries[geometry.id] = true; + info.memory.geometries++; + return geometry; + } + function update(geometry) { + const geometryAttributes = geometry.attributes; + for (const name2 in geometryAttributes) { + attributes.update(geometryAttributes[name2], gl.ARRAY_BUFFER); + } + } + function updateWireframeAttribute(geometry) { + const indices = []; + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + if (geometryIndex !== null) { + const array = geometryIndex.array; + version = geometryIndex.version; + for (let i = 0, l2 = array.length;i < l2; i += 3) { + const a2 = array[i + 0]; + const b3 = array[i + 1]; + const c2 = array[i + 2]; + indices.push(a2, b3, b3, c2, c2, a2); + } + } else if (geometryPosition !== undefined) { + const array = geometryPosition.array; + version = geometryPosition.version; + for (let i = 0, l2 = array.length / 3 - 1;i < l2; i += 3) { + const a2 = i + 0; + const b3 = i + 1; + const c2 = i + 2; + indices.push(a2, b3, b3, c2, c2, a2); + } + } else { + return; + } + const attribute = new ((arrayNeedsUint322(indices)) ? Uint32BufferAttribute2 : Uint16BufferAttribute2)(indices, 1); + attribute.version = version; + const previousAttribute = wireframeAttributes.get(geometry); + if (previousAttribute) + attributes.remove(previousAttribute); + wireframeAttributes.set(geometry, attribute); + } + function getWireframeAttribute(geometry) { + const currentAttribute = wireframeAttributes.get(geometry); + if (currentAttribute) { + const geometryIndex = geometry.index; + if (geometryIndex !== null) { + if (currentAttribute.version < geometryIndex.version) { + updateWireframeAttribute(geometry); + } + } + } else { + updateWireframeAttribute(geometry); + } + return wireframeAttributes.get(geometry); + } + return { + get, + update, + getWireframeAttribute + }; + } + function WebGLIndexedBufferRenderer2(gl, extensions, info) { + let mode; + function setMode(value2) { + mode = value2; + } + let type, bytesPerElement; + function setIndex(value2) { + type = value2.type; + bytesPerElement = value2.bytesPerElement; + } + function render(start, count) { + gl.drawElements(mode, count, type, start * bytesPerElement); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) + return; + gl.drawElementsInstanced(mode, count, type, start * bytesPerElement, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawElementsWEBGL(mode, counts, 0, type, starts, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0;i < starts.length; i++) { + renderInstances(starts[i] / bytesPerElement, counts[i], primcount[i]); + } + } else { + extension.multiDrawElementsInstancedWEBGL(mode, counts, 0, type, starts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i] * primcount[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; + } + function WebGLInfo2(gl) { + const memory = { + geometries: 0, + textures: 0 + }; + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + function update(count, mode, instanceCount) { + render.calls++; + switch (mode) { + case gl.TRIANGLES: + render.triangles += instanceCount * (count / 3); + break; + case gl.LINES: + render.lines += instanceCount * (count / 2); + break; + case gl.LINE_STRIP: + render.lines += instanceCount * (count - 1); + break; + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + case gl.POINTS: + render.points += instanceCount * count; + break; + default: + console.error("THREE.WebGLInfo: Unknown draw mode:", mode); + break; + } + } + function reset() { + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + } + return { + memory, + render, + programs: null, + autoReset: true, + reset, + update + }; + } + function WebGLMorphtargets2(gl, capabilities, textures) { + const morphTextures = new WeakMap; + const morph = new Vector42; + function update(object, geometry, program) { + const objectInfluences = object.morphTargetInfluences; + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + let entry = morphTextures.get(geometry); + if (entry === undefined || entry.count !== morphTargetsCount) { + let disposeTexture = function() { + texture.dispose(); + morphTextures.delete(geometry); + geometry.removeEventListener("dispose", disposeTexture); + }; + if (entry !== undefined) + entry.texture.dispose(); + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + let vertexDataCount = 0; + if (hasMorphPosition === true) + vertexDataCount = 1; + if (hasMorphNormals === true) + vertexDataCount = 2; + if (hasMorphColors === true) + vertexDataCount = 3; + let width2 = geometry.attributes.position.count * vertexDataCount; + let height2 = 1; + if (width2 > capabilities.maxTextureSize) { + height2 = Math.ceil(width2 / capabilities.maxTextureSize); + width2 = capabilities.maxTextureSize; + } + const buffer = new Float32Array(width2 * height2 * 4 * morphTargetsCount); + const texture = new DataArrayTexture2(buffer, width2, height2, morphTargetsCount); + texture.type = FloatType2; + texture.needsUpdate = true; + const vertexDataStride = vertexDataCount * 4; + for (let i = 0;i < morphTargetsCount; i++) { + const morphTarget = morphTargets[i]; + const morphNormal = morphNormals[i]; + const morphColor = morphColors[i]; + const offset = width2 * height2 * 4 * i; + for (let j2 = 0;j2 < morphTarget.count; j2++) { + const stride = j2 * vertexDataStride; + if (hasMorphPosition === true) { + morph.fromBufferAttribute(morphTarget, j2); + buffer[offset + stride + 0] = morph.x; + buffer[offset + stride + 1] = morph.y; + buffer[offset + stride + 2] = morph.z; + buffer[offset + stride + 3] = 0; + } + if (hasMorphNormals === true) { + morph.fromBufferAttribute(morphNormal, j2); + buffer[offset + stride + 4] = morph.x; + buffer[offset + stride + 5] = morph.y; + buffer[offset + stride + 6] = morph.z; + buffer[offset + stride + 7] = 0; + } + if (hasMorphColors === true) { + morph.fromBufferAttribute(morphColor, j2); + buffer[offset + stride + 8] = morph.x; + buffer[offset + stride + 9] = morph.y; + buffer[offset + stride + 10] = morph.z; + buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1; + } + } + } + entry = { + count: morphTargetsCount, + texture, + size: new Vector22(width2, height2) + }; + morphTextures.set(geometry, entry); + geometry.addEventListener("dispose", disposeTexture); + } + if (object.isInstancedMesh === true && object.morphTexture !== null) { + program.getUniforms().setValue(gl, "morphTexture", object.morphTexture, textures); + } else { + let morphInfluencesSum = 0; + for (let i = 0;i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence); + program.getUniforms().setValue(gl, "morphTargetInfluences", objectInfluences); + } + program.getUniforms().setValue(gl, "morphTargetsTexture", entry.texture, textures); + program.getUniforms().setValue(gl, "morphTargetsTextureSize", entry.size); + } + return { + update + }; + } + function WebGLObjects2(gl, geometries, attributes, info) { + let updateMap = new WeakMap; + function update(object) { + const frame = info.render.frame; + const geometry = object.geometry; + const buffergeometry = geometries.get(object, geometry); + if (updateMap.get(buffergeometry) !== frame) { + geometries.update(buffergeometry); + updateMap.set(buffergeometry, frame); + } + if (object.isInstancedMesh) { + if (object.hasEventListener("dispose", onInstancedMeshDispose) === false) { + object.addEventListener("dispose", onInstancedMeshDispose); + } + if (updateMap.get(object) !== frame) { + attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER); + if (object.instanceColor !== null) { + attributes.update(object.instanceColor, gl.ARRAY_BUFFER); + } + updateMap.set(object, frame); + } + } + if (object.isSkinnedMesh) { + const skeleton = object.skeleton; + if (updateMap.get(skeleton) !== frame) { + skeleton.update(); + updateMap.set(skeleton, frame); + } + } + return buffergeometry; + } + function dispose() { + updateMap = new WeakMap; + } + function onInstancedMeshDispose(event) { + const instancedMesh = event.target; + instancedMesh.removeEventListener("dispose", onInstancedMeshDispose); + attributes.remove(instancedMesh.instanceMatrix); + if (instancedMesh.instanceColor !== null) + attributes.remove(instancedMesh.instanceColor); + } + return { + update, + dispose + }; + } + var emptyTexture2 = /* @__PURE__ */ new Texture2; + var emptyShadowTexture2 = /* @__PURE__ */ new DepthTexture2(1, 1); + var emptyArrayTexture2 = /* @__PURE__ */ new DataArrayTexture2; + var empty3dTexture2 = /* @__PURE__ */ new Data3DTexture2; + var emptyCubeTexture2 = /* @__PURE__ */ new CubeTexture2; + var arrayCacheF322 = []; + var arrayCacheI322 = []; + var mat4array2 = new Float32Array(16); + var mat3array2 = new Float32Array(9); + var mat2array2 = new Float32Array(4); + function flatten3(array, nBlocks, blockSize) { + const firstElem = array[0]; + if (firstElem <= 0 || firstElem > 0) + return array; + const n2 = nBlocks * blockSize; + let r = arrayCacheF322[n2]; + if (r === undefined) { + r = new Float32Array(n2); + arrayCacheF322[n2] = r; + } + if (nBlocks !== 0) { + firstElem.toArray(r, 0); + for (let i = 1, offset = 0;i !== nBlocks; ++i) { + offset += blockSize; + array[i].toArray(r, offset); + } + } + return r; + } + function arraysEqual3(a2, b3) { + if (a2.length !== b3.length) + return false; + for (let i = 0, l2 = a2.length;i < l2; i++) { + if (a2[i] !== b3[i]) + return false; + } + return true; + } + function copyArray2(a2, b3) { + for (let i = 0, l2 = b3.length;i < l2; i++) { + a2[i] = b3[i]; + } + } + function allocTexUnits2(textures, n2) { + let r = arrayCacheI322[n2]; + if (r === undefined) { + r = new Int32Array(n2); + arrayCacheI322[n2] = r; + } + for (let i = 0;i !== n2; ++i) { + r[i] = textures.allocateTextureUnit(); + } + return r; + } + function setValueV1f2(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1f(this.addr, v); + cache[0] = v; + } + function setValueV2f2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2f(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform2fv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV3f2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3f(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else if (v.r !== undefined) { + if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) { + gl.uniform3f(this.addr, v.r, v.g, v.b); + cache[0] = v.r; + cache[1] = v.g; + cache[2] = v.b; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform3fv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV4f2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4f(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform4fv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueM22(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual3(cache, v)) + return; + gl.uniformMatrix2fv(this.addr, false, v); + copyArray2(cache, v); + } else { + if (arraysEqual3(cache, elements)) + return; + mat2array2.set(elements); + gl.uniformMatrix2fv(this.addr, false, mat2array2); + copyArray2(cache, elements); + } + } + function setValueM32(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual3(cache, v)) + return; + gl.uniformMatrix3fv(this.addr, false, v); + copyArray2(cache, v); + } else { + if (arraysEqual3(cache, elements)) + return; + mat3array2.set(elements); + gl.uniformMatrix3fv(this.addr, false, mat3array2); + copyArray2(cache, elements); + } + } + function setValueM42(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual3(cache, v)) + return; + gl.uniformMatrix4fv(this.addr, false, v); + copyArray2(cache, v); + } else { + if (arraysEqual3(cache, elements)) + return; + mat4array2.set(elements); + gl.uniformMatrix4fv(this.addr, false, mat4array2); + copyArray2(cache, elements); + } + } + function setValueV1i2(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1i(this.addr, v); + cache[0] = v; + } + function setValueV2i2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2i(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform2iv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV3i2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3i(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform3iv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV4i2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4i(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform4iv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV1ui2(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1ui(this.addr, v); + cache[0] = v; + } + function setValueV2ui2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2ui(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform2uiv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV3ui2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3ui(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform3uiv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV4ui2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4ui(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform4uiv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueT12(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + let emptyTexture2D; + if (this.type === gl.SAMPLER_2D_SHADOW) { + emptyShadowTexture2.compareFunction = LessEqualCompare2; + emptyTexture2D = emptyShadowTexture2; + } else { + emptyTexture2D = emptyTexture2; + } + textures.setTexture2D(v || emptyTexture2D, unit); + } + function setValueT3D12(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture3D(v || empty3dTexture2, unit); + } + function setValueT62(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTextureCube(v || emptyCubeTexture2, unit); + } + function setValueT2DArray12(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture2DArray(v || emptyArrayTexture2, unit); + } + function getSingularSetter2(type) { + switch (type) { + case 5126: + return setValueV1f2; + case 35664: + return setValueV2f2; + case 35665: + return setValueV3f2; + case 35666: + return setValueV4f2; + case 35674: + return setValueM22; + case 35675: + return setValueM32; + case 35676: + return setValueM42; + case 5124: + case 35670: + return setValueV1i2; + case 35667: + case 35671: + return setValueV2i2; + case 35668: + case 35672: + return setValueV3i2; + case 35669: + case 35673: + return setValueV4i2; + case 5125: + return setValueV1ui2; + case 36294: + return setValueV2ui2; + case 36295: + return setValueV3ui2; + case 36296: + return setValueV4ui2; + case 35678: + case 36198: + case 36298: + case 36306: + case 35682: + return setValueT12; + case 35679: + case 36299: + case 36307: + return setValueT3D12; + case 35680: + case 36300: + case 36308: + case 36293: + return setValueT62; + case 36289: + case 36303: + case 36311: + case 36292: + return setValueT2DArray12; + } + } + function setValueV1fArray2(gl, v) { + gl.uniform1fv(this.addr, v); + } + function setValueV2fArray2(gl, v) { + const data2 = flatten3(v, this.size, 2); + gl.uniform2fv(this.addr, data2); + } + function setValueV3fArray2(gl, v) { + const data2 = flatten3(v, this.size, 3); + gl.uniform3fv(this.addr, data2); + } + function setValueV4fArray2(gl, v) { + const data2 = flatten3(v, this.size, 4); + gl.uniform4fv(this.addr, data2); + } + function setValueM2Array2(gl, v) { + const data2 = flatten3(v, this.size, 4); + gl.uniformMatrix2fv(this.addr, false, data2); + } + function setValueM3Array2(gl, v) { + const data2 = flatten3(v, this.size, 9); + gl.uniformMatrix3fv(this.addr, false, data2); + } + function setValueM4Array2(gl, v) { + const data2 = flatten3(v, this.size, 16); + gl.uniformMatrix4fv(this.addr, false, data2); + } + function setValueV1iArray2(gl, v) { + gl.uniform1iv(this.addr, v); + } + function setValueV2iArray2(gl, v) { + gl.uniform2iv(this.addr, v); + } + function setValueV3iArray2(gl, v) { + gl.uniform3iv(this.addr, v); + } + function setValueV4iArray2(gl, v) { + gl.uniform4iv(this.addr, v); + } + function setValueV1uiArray2(gl, v) { + gl.uniform1uiv(this.addr, v); + } + function setValueV2uiArray2(gl, v) { + gl.uniform2uiv(this.addr, v); + } + function setValueV3uiArray2(gl, v) { + gl.uniform3uiv(this.addr, v); + } + function setValueV4uiArray2(gl, v) { + gl.uniform4uiv(this.addr, v); + } + function setValueT1Array2(gl, v, textures) { + const cache = this.cache; + const n2 = v.length; + const units = allocTexUnits2(textures, n2); + if (!arraysEqual3(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray2(cache, units); + } + for (let i = 0;i !== n2; ++i) { + textures.setTexture2D(v[i] || emptyTexture2, units[i]); + } + } + function setValueT3DArray2(gl, v, textures) { + const cache = this.cache; + const n2 = v.length; + const units = allocTexUnits2(textures, n2); + if (!arraysEqual3(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray2(cache, units); + } + for (let i = 0;i !== n2; ++i) { + textures.setTexture3D(v[i] || empty3dTexture2, units[i]); + } + } + function setValueT6Array2(gl, v, textures) { + const cache = this.cache; + const n2 = v.length; + const units = allocTexUnits2(textures, n2); + if (!arraysEqual3(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray2(cache, units); + } + for (let i = 0;i !== n2; ++i) { + textures.setTextureCube(v[i] || emptyCubeTexture2, units[i]); + } + } + function setValueT2DArrayArray2(gl, v, textures) { + const cache = this.cache; + const n2 = v.length; + const units = allocTexUnits2(textures, n2); + if (!arraysEqual3(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray2(cache, units); + } + for (let i = 0;i !== n2; ++i) { + textures.setTexture2DArray(v[i] || emptyArrayTexture2, units[i]); + } + } + function getPureArraySetter2(type) { + switch (type) { + case 5126: + return setValueV1fArray2; + case 35664: + return setValueV2fArray2; + case 35665: + return setValueV3fArray2; + case 35666: + return setValueV4fArray2; + case 35674: + return setValueM2Array2; + case 35675: + return setValueM3Array2; + case 35676: + return setValueM4Array2; + case 5124: + case 35670: + return setValueV1iArray2; + case 35667: + case 35671: + return setValueV2iArray2; + case 35668: + case 35672: + return setValueV3iArray2; + case 35669: + case 35673: + return setValueV4iArray2; + case 5125: + return setValueV1uiArray2; + case 36294: + return setValueV2uiArray2; + case 36295: + return setValueV3uiArray2; + case 36296: + return setValueV4uiArray2; + case 35678: + case 36198: + case 36298: + case 36306: + case 35682: + return setValueT1Array2; + case 35679: + case 36299: + case 36307: + return setValueT3DArray2; + case 35680: + case 36300: + case 36308: + case 36293: + return setValueT6Array2; + case 36289: + case 36303: + case 36311: + case 36292: + return setValueT2DArrayArray2; + } + } + + class SingleUniform2 { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.setValue = getSingularSetter2(activeInfo.type); + } + } + + class PureArrayUniform2 { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.size = activeInfo.size; + this.setValue = getPureArraySetter2(activeInfo.type); + } + } + + class StructuredUniform2 { + constructor(id) { + this.id = id; + this.seq = []; + this.map = {}; + } + setValue(gl, value2, textures) { + const seq = this.seq; + for (let i = 0, n2 = seq.length;i !== n2; ++i) { + const u3 = seq[i]; + u3.setValue(gl, value2[u3.id], textures); + } + } + } + var RePathPart2 = /(\w+)(\])?(\[|\.)?/g; + function addUniform2(container, uniformObject) { + container.seq.push(uniformObject); + container.map[uniformObject.id] = uniformObject; + } + function parseUniform2(activeInfo, addr, container) { + const path = activeInfo.name, pathLength = path.length; + RePathPart2.lastIndex = 0; + while (true) { + const match = RePathPart2.exec(path), matchEnd = RePathPart2.lastIndex; + let id = match[1]; + const idIsIndex = match[2] === "]", subscript = match[3]; + if (idIsIndex) + id = id | 0; + if (subscript === undefined || subscript === "[" && matchEnd + 2 === pathLength) { + addUniform2(container, subscript === undefined ? new SingleUniform2(id, activeInfo, addr) : new PureArrayUniform2(id, activeInfo, addr)); + break; + } else { + const map2 = container.map; + let next = map2[id]; + if (next === undefined) { + next = new StructuredUniform2(id); + addUniform2(container, next); + } + container = next; + } + } + } + + class WebGLUniforms2 { + constructor(gl, program) { + this.seq = []; + this.map = {}; + const n2 = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (let i = 0;i < n2; ++i) { + const info = gl.getActiveUniform(program, i), addr = gl.getUniformLocation(program, info.name); + parseUniform2(info, addr, this); + } + } + setValue(gl, name2, value2, textures) { + const u3 = this.map[name2]; + if (u3 !== undefined) + u3.setValue(gl, value2, textures); + } + setOptional(gl, object, name2) { + const v = object[name2]; + if (v !== undefined) + this.setValue(gl, name2, v); + } + static upload(gl, seq, values2, textures) { + for (let i = 0, n2 = seq.length;i !== n2; ++i) { + const u3 = seq[i], v = values2[u3.id]; + if (v.needsUpdate !== false) { + u3.setValue(gl, v.value, textures); + } + } + } + static seqWithValue(seq, values2) { + const r = []; + for (let i = 0, n2 = seq.length;i !== n2; ++i) { + const u3 = seq[i]; + if (u3.id in values2) + r.push(u3); + } + return r; + } + } + function WebGLShader2(gl, type, string) { + const shader = gl.createShader(type); + gl.shaderSource(shader, string); + gl.compileShader(shader); + return shader; + } + var COMPLETION_STATUS_KHR2 = 37297; + var programIdCount2 = 0; + function handleSource2(string, errorLine) { + const lines = string.split(` +`); + const lines2 = []; + const from = Math.max(errorLine - 6, 0); + const to = Math.min(errorLine + 6, lines.length); + for (let i = from;i < to; i++) { + const line2 = i + 1; + lines2.push(`${line2 === errorLine ? ">" : " "} ${line2}: ${lines[i]}`); + } + return lines2.join(` +`); + } + var _m02 = /* @__PURE__ */ new Matrix32; + function getEncodingComponents2(colorSpace) { + ColorManagement2._getMatrix(_m02, ColorManagement2.workingColorSpace, colorSpace); + const encodingMatrix = `mat3( ${_m02.elements.map((v) => v.toFixed(4))} )`; + switch (ColorManagement2.getTransfer(colorSpace)) { + case LinearTransfer2: + return [encodingMatrix, "LinearTransferOETF"]; + case SRGBTransfer2: + return [encodingMatrix, "sRGBTransferOETF"]; + default: + console.warn("THREE.WebGLProgram: Unsupported color space: ", colorSpace); + return [encodingMatrix, "LinearTransferOETF"]; + } + } + function getShaderErrors2(gl, shader, type) { + const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS); + const errors = gl.getShaderInfoLog(shader).trim(); + if (status && errors === "") + return ""; + const errorMatches = /ERROR: 0:(\d+)/.exec(errors); + if (errorMatches) { + const errorLine = parseInt(errorMatches[1]); + return type.toUpperCase() + ` + +` + errors + ` + +` + handleSource2(gl.getShaderSource(shader), errorLine); + } else { + return errors; + } + } + function getTexelEncodingFunction2(functionName, colorSpace) { + const components = getEncodingComponents2(colorSpace); + return [ + `vec4 ${functionName}( vec4 value ) {`, + ` return ${components[1]}( vec4( value.rgb * ${components[0]}, value.a ) );`, + "}" + ].join(` +`); + } + function getToneMappingFunction2(functionName, toneMapping) { + let toneMappingName; + switch (toneMapping) { + case LinearToneMapping2: + toneMappingName = "Linear"; + break; + case ReinhardToneMapping2: + toneMappingName = "Reinhard"; + break; + case CineonToneMapping2: + toneMappingName = "Cineon"; + break; + case ACESFilmicToneMapping2: + toneMappingName = "ACESFilmic"; + break; + case AgXToneMapping2: + toneMappingName = "AgX"; + break; + case NeutralToneMapping2: + toneMappingName = "Neutral"; + break; + case CustomToneMapping2: + toneMappingName = "Custom"; + break; + default: + console.warn("THREE.WebGLProgram: Unsupported toneMapping:", toneMapping); + toneMappingName = "Linear"; + } + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; + } + var _v03 = /* @__PURE__ */ new Vector32; + function getLuminanceFunction2() { + ColorManagement2.getLuminanceCoefficients(_v03); + const r = _v03.x.toFixed(4); + const g3 = _v03.y.toFixed(4); + const b3 = _v03.z.toFixed(4); + return [ + "float luminance( const in vec3 rgb ) {", + ` const vec3 weights = vec3( ${r}, ${g3}, ${b3} );`, + "\treturn dot( weights, rgb );", + "}" + ].join(` +`); + } + function generateVertexExtensions2(parameters) { + const chunks = [ + parameters.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "", + parameters.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : "" + ]; + return chunks.filter(filterEmptyLine2).join(` +`); + } + function generateDefines2(defines) { + const chunks = []; + for (const name2 in defines) { + const value2 = defines[name2]; + if (value2 === false) + continue; + chunks.push("#define " + name2 + " " + value2); + } + return chunks.join(` +`); + } + function fetchAttributeLocations2(gl, program) { + const attributes = {}; + const n2 = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (let i = 0;i < n2; i++) { + const info = gl.getActiveAttrib(program, i); + const name2 = info.name; + let locationSize = 1; + if (info.type === gl.FLOAT_MAT2) + locationSize = 2; + if (info.type === gl.FLOAT_MAT3) + locationSize = 3; + if (info.type === gl.FLOAT_MAT4) + locationSize = 4; + attributes[name2] = { + type: info.type, + location: gl.getAttribLocation(program, name2), + locationSize + }; + } + return attributes; + } + function filterEmptyLine2(string) { + return string !== ""; + } + function replaceLightNums2(string, parameters) { + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows); + } + function replaceClippingPlaneNums2(string, parameters) { + return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection); + } + var includePattern2 = /^[ \t]*#include +<([\w\d./]+)>/gm; + function resolveIncludes2(string) { + return string.replace(includePattern2, includeReplacer2); + } + var shaderChunkMap2 = new Map; + function includeReplacer2(match, include) { + let string = ShaderChunk2[include]; + if (string === undefined) { + const newInclude = shaderChunkMap2.get(include); + if (newInclude !== undefined) { + string = ShaderChunk2[newInclude]; + console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude); + } else { + throw new Error("Can not resolve #include <" + include + ">"); + } + } + return resolveIncludes2(string); + } + var unrollLoopPattern2 = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + function unrollLoops2(string) { + return string.replace(unrollLoopPattern2, loopReplacer2); + } + function loopReplacer2(match, start, end, snippet) { + let string = ""; + for (let i = parseInt(start);i < parseInt(end); i++) { + string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i + " ]").replace(/UNROLLED_LOOP_INDEX/g, i); + } + return string; + } + function generatePrecision2(parameters) { + let precisionstring = `precision ${parameters.precision} float; + precision ${parameters.precision} int; + precision ${parameters.precision} sampler2D; + precision ${parameters.precision} samplerCube; + precision ${parameters.precision} sampler3D; + precision ${parameters.precision} sampler2DArray; + precision ${parameters.precision} sampler2DShadow; + precision ${parameters.precision} samplerCubeShadow; + precision ${parameters.precision} sampler2DArrayShadow; + precision ${parameters.precision} isampler2D; + precision ${parameters.precision} isampler3D; + precision ${parameters.precision} isamplerCube; + precision ${parameters.precision} isampler2DArray; + precision ${parameters.precision} usampler2D; + precision ${parameters.precision} usampler3D; + precision ${parameters.precision} usamplerCube; + precision ${parameters.precision} usampler2DArray; + `; + if (parameters.precision === "highp") { + precisionstring += ` +#define HIGH_PRECISION`; + } else if (parameters.precision === "mediump") { + precisionstring += ` +#define MEDIUM_PRECISION`; + } else if (parameters.precision === "lowp") { + precisionstring += ` +#define LOW_PRECISION`; + } + return precisionstring; + } + function generateShadowMapTypeDefine2(parameters) { + let shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; + if (parameters.shadowMapType === PCFShadowMap2) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; + } else if (parameters.shadowMapType === PCFSoftShadowMap2) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; + } else if (parameters.shadowMapType === VSMShadowMap2) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_VSM"; + } + return shadowMapTypeDefine; + } + function generateEnvMapTypeDefine2(parameters) { + let envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeReflectionMapping2: + case CubeRefractionMapping2: + envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + break; + case CubeUVReflectionMapping2: + envMapTypeDefine = "ENVMAP_TYPE_CUBE_UV"; + break; + } + } + return envMapTypeDefine; + } + function generateEnvMapModeDefine2(parameters) { + let envMapModeDefine = "ENVMAP_MODE_REFLECTION"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeRefractionMapping2: + envMapModeDefine = "ENVMAP_MODE_REFRACTION"; + break; + } + } + return envMapModeDefine; + } + function generateEnvMapBlendingDefine2(parameters) { + let envMapBlendingDefine = "ENVMAP_BLENDING_NONE"; + if (parameters.envMap) { + switch (parameters.combine) { + case MultiplyOperation2: + envMapBlendingDefine = "ENVMAP_BLENDING_MULTIPLY"; + break; + case MixOperation2: + envMapBlendingDefine = "ENVMAP_BLENDING_MIX"; + break; + case AddOperation2: + envMapBlendingDefine = "ENVMAP_BLENDING_ADD"; + break; + } + } + return envMapBlendingDefine; + } + function generateCubeUVSize2(parameters) { + const imageHeight = parameters.envMapCubeUVHeight; + if (imageHeight === null) + return null; + const maxMip = Math.log2(imageHeight) - 2; + const texelHeight = 1 / imageHeight; + const texelWidth = 1 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16)); + return { texelWidth, texelHeight, maxMip }; + } + function WebGLProgram2(renderer2, cacheKey, parameters, bindingStates) { + const gl = renderer2.getContext(); + const defines = parameters.defines; + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + const shadowMapTypeDefine = generateShadowMapTypeDefine2(parameters); + const envMapTypeDefine = generateEnvMapTypeDefine2(parameters); + const envMapModeDefine = generateEnvMapModeDefine2(parameters); + const envMapBlendingDefine = generateEnvMapBlendingDefine2(parameters); + const envMapCubeUVSize = generateCubeUVSize2(parameters); + const customVertexExtensions = generateVertexExtensions2(parameters); + const customDefines = generateDefines2(defines); + const program = gl.createProgram(); + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? "#version " + parameters.glslVersion + ` +` : ""; + if (parameters.isRawShaderMaterial) { + prefixVertex = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine2).join(` +`); + if (prefixVertex.length > 0) { + prefixVertex += ` +`; + } + prefixFragment = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine2).join(` +`); + if (prefixFragment.length > 0) { + prefixFragment += ` +`; + } + } else { + prefixVertex = [ + generatePrecision2(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "", + parameters.batching ? "#define USE_BATCHING" : "", + parameters.batchingColor ? "#define USE_BATCHING_COLOR" : "", + parameters.instancing ? "#define USE_INSTANCING" : "", + parameters.instancingColor ? "#define USE_INSTANCING_COLOR" : "", + parameters.instancingMorph ? "#define USE_INSTANCING_MORPH" : "", + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.displacementMap ? "#define USE_DISPLACEMENTMAP" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.mapUv ? "#define MAP_UV " + parameters.mapUv : "", + parameters.alphaMapUv ? "#define ALPHAMAP_UV " + parameters.alphaMapUv : "", + parameters.lightMapUv ? "#define LIGHTMAP_UV " + parameters.lightMapUv : "", + parameters.aoMapUv ? "#define AOMAP_UV " + parameters.aoMapUv : "", + parameters.emissiveMapUv ? "#define EMISSIVEMAP_UV " + parameters.emissiveMapUv : "", + parameters.bumpMapUv ? "#define BUMPMAP_UV " + parameters.bumpMapUv : "", + parameters.normalMapUv ? "#define NORMALMAP_UV " + parameters.normalMapUv : "", + parameters.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + parameters.displacementMapUv : "", + parameters.metalnessMapUv ? "#define METALNESSMAP_UV " + parameters.metalnessMapUv : "", + parameters.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + parameters.roughnessMapUv : "", + parameters.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + parameters.anisotropyMapUv : "", + parameters.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + parameters.clearcoatMapUv : "", + parameters.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + parameters.clearcoatNormalMapUv : "", + parameters.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + parameters.clearcoatRoughnessMapUv : "", + parameters.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + parameters.iridescenceMapUv : "", + parameters.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + parameters.iridescenceThicknessMapUv : "", + parameters.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + parameters.sheenColorMapUv : "", + parameters.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + parameters.sheenRoughnessMapUv : "", + parameters.specularMapUv ? "#define SPECULARMAP_UV " + parameters.specularMapUv : "", + parameters.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + parameters.specularColorMapUv : "", + parameters.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + parameters.specularIntensityMapUv : "", + parameters.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + parameters.transmissionMapUv : "", + parameters.thicknessMapUv ? "#define THICKNESSMAP_UV " + parameters.thicknessMapUv : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.skinning ? "#define USE_SKINNING" : "", + parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", + parameters.morphNormals && parameters.flatShading === false ? "#define USE_MORPHNORMALS" : "", + parameters.morphColors ? "#define USE_MORPHCOLORS" : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + parameters.morphTextureStride : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + parameters.morphTargetsCount : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "", + "uniform mat4 modelMatrix;", + "uniform mat4 modelViewMatrix;", + "uniform mat4 projectionMatrix;", + "uniform mat4 viewMatrix;", + "uniform mat3 normalMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + "#ifdef USE_INSTANCING", + "\tattribute mat4 instanceMatrix;", + "#endif", + "#ifdef USE_INSTANCING_COLOR", + "\tattribute vec3 instanceColor;", + "#endif", + "#ifdef USE_INSTANCING_MORPH", + "\tuniform sampler2D morphTexture;", + "#endif", + "attribute vec3 position;", + "attribute vec3 normal;", + "attribute vec2 uv;", + "#ifdef USE_UV1", + "\tattribute vec2 uv1;", + "#endif", + "#ifdef USE_UV2", + "\tattribute vec2 uv2;", + "#endif", + "#ifdef USE_UV3", + "\tattribute vec2 uv3;", + "#endif", + "#ifdef USE_TANGENT", + "\tattribute vec4 tangent;", + "#endif", + "#if defined( USE_COLOR_ALPHA )", + "\tattribute vec4 color;", + "#elif defined( USE_COLOR )", + "\tattribute vec3 color;", + "#endif", + "#ifdef USE_SKINNING", + "\tattribute vec4 skinIndex;", + "\tattribute vec4 skinWeight;", + "#endif", + ` +` + ].filter(filterEmptyLine2).join(` +`); + prefixFragment = [ + generatePrecision2(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.matcap ? "#define USE_MATCAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapTypeDefine : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.envMap ? "#define " + envMapBlendingDefine : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_WIDTH " + envMapCubeUVSize.texelWidth : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_HEIGHT " + envMapCubeUVSize.texelHeight : "", + envMapCubeUVSize ? "#define CUBEUV_MAX_MIP " + envMapCubeUVSize.maxMip + ".0" : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoat ? "#define USE_CLEARCOAT" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.dispersion ? "#define USE_DISPERSION" : "", + parameters.iridescence ? "#define USE_IRIDESCENCE" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaTest ? "#define USE_ALPHATEST" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.sheen ? "#define USE_SHEEN" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.gradientMap ? "#define USE_GRADIENTMAP" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", + parameters.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "", + "uniform mat4 viewMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + parameters.toneMapping !== NoToneMapping2 ? "#define TONE_MAPPING" : "", + parameters.toneMapping !== NoToneMapping2 ? ShaderChunk2["tonemapping_pars_fragment"] : "", + parameters.toneMapping !== NoToneMapping2 ? getToneMappingFunction2("toneMapping", parameters.toneMapping) : "", + parameters.dithering ? "#define DITHERING" : "", + parameters.opaque ? "#define OPAQUE" : "", + ShaderChunk2["colorspace_pars_fragment"], + getTexelEncodingFunction2("linearToOutputTexel", parameters.outputColorSpace), + getLuminanceFunction2(), + parameters.useDepthPacking ? "#define DEPTH_PACKING " + parameters.depthPacking : "", + ` +` + ].filter(filterEmptyLine2).join(` +`); + } + vertexShader = resolveIncludes2(vertexShader); + vertexShader = replaceLightNums2(vertexShader, parameters); + vertexShader = replaceClippingPlaneNums2(vertexShader, parameters); + fragmentShader = resolveIncludes2(fragmentShader); + fragmentShader = replaceLightNums2(fragmentShader, parameters); + fragmentShader = replaceClippingPlaneNums2(fragmentShader, parameters); + vertexShader = unrollLoops2(vertexShader); + fragmentShader = unrollLoops2(fragmentShader); + if (parameters.isRawShaderMaterial !== true) { + versionString = `#version 300 es +`; + prefixVertex = [ + customVertexExtensions, + "#define attribute in", + "#define varying out", + "#define texture2D texture" + ].join(` +`) + ` +` + prefixVertex; + prefixFragment = [ + "#define varying in", + parameters.glslVersion === GLSL32 ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", + parameters.glslVersion === GLSL32 ? "" : "#define gl_FragColor pc_fragColor", + "#define gl_FragDepthEXT gl_FragDepth", + "#define texture2D texture", + "#define textureCube texture", + "#define texture2DProj textureProj", + "#define texture2DLodEXT textureLod", + "#define texture2DProjLodEXT textureProjLod", + "#define textureCubeLodEXT textureLod", + "#define texture2DGradEXT textureGrad", + "#define texture2DProjGradEXT textureProjGrad", + "#define textureCubeGradEXT textureGrad" + ].join(` +`) + ` +` + prefixFragment; + } + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + const glVertexShader = WebGLShader2(gl, gl.VERTEX_SHADER, vertexGlsl); + const glFragmentShader = WebGLShader2(gl, gl.FRAGMENT_SHADER, fragmentGlsl); + gl.attachShader(program, glVertexShader); + gl.attachShader(program, glFragmentShader); + if (parameters.index0AttributeName !== undefined) { + gl.bindAttribLocation(program, 0, parameters.index0AttributeName); + } else if (parameters.morphTargets === true) { + gl.bindAttribLocation(program, 0, "position"); + } + gl.linkProgram(program); + function onFirstUse(self2) { + if (renderer2.debug.checkShaderErrors) { + const programLog = gl.getProgramInfoLog(program).trim(); + const vertexLog = gl.getShaderInfoLog(glVertexShader).trim(); + const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim(); + let runnable = true; + let haveDiagnostics = true; + if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) { + runnable = false; + if (typeof renderer2.debug.onShaderError === "function") { + renderer2.debug.onShaderError(gl, program, glVertexShader, glFragmentShader); + } else { + const vertexErrors = getShaderErrors2(gl, glVertexShader, "vertex"); + const fragmentErrors = getShaderErrors2(gl, glFragmentShader, "fragment"); + console.error("THREE.WebGLProgram: Shader Error " + gl.getError() + " - " + "VALIDATE_STATUS " + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + ` + +` + "Material Name: " + self2.name + ` +` + "Material Type: " + self2.type + ` + +` + "Program Info Log: " + programLog + ` +` + vertexErrors + ` +` + fragmentErrors); + } + } else if (programLog !== "") { + console.warn("THREE.WebGLProgram: Program Info Log:", programLog); + } else if (vertexLog === "" || fragmentLog === "") { + haveDiagnostics = false; + } + if (haveDiagnostics) { + self2.diagnostics = { + runnable, + programLog, + vertexShader: { + log: vertexLog, + prefix: prefixVertex + }, + fragmentShader: { + log: fragmentLog, + prefix: prefixFragment + } + }; + } + } + gl.deleteShader(glVertexShader); + gl.deleteShader(glFragmentShader); + cachedUniforms = new WebGLUniforms2(gl, program); + cachedAttributes = fetchAttributeLocations2(gl, program); + } + let cachedUniforms; + this.getUniforms = function() { + if (cachedUniforms === undefined) { + onFirstUse(this); + } + return cachedUniforms; + }; + let cachedAttributes; + this.getAttributes = function() { + if (cachedAttributes === undefined) { + onFirstUse(this); + } + return cachedAttributes; + }; + let programReady = parameters.rendererExtensionParallelShaderCompile === false; + this.isReady = function() { + if (programReady === false) { + programReady = gl.getProgramParameter(program, COMPLETION_STATUS_KHR2); + } + return programReady; + }; + this.destroy = function() { + bindingStates.releaseStatesOfProgram(this); + gl.deleteProgram(program); + this.program = undefined; + }; + this.type = parameters.shaderType; + this.name = parameters.shaderName; + this.id = programIdCount2++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + return this; + } + var _id3 = 0; + + class WebGLShaderCache2 { + constructor() { + this.shaderCache = new Map; + this.materialCache = new Map; + } + update(material) { + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + const vertexShaderStage = this._getShaderStage(vertexShader); + const fragmentShaderStage = this._getShaderStage(fragmentShader); + const materialShaders = this._getShaderCacheForMaterial(material); + if (materialShaders.has(vertexShaderStage) === false) { + materialShaders.add(vertexShaderStage); + vertexShaderStage.usedTimes++; + } + if (materialShaders.has(fragmentShaderStage) === false) { + materialShaders.add(fragmentShaderStage); + fragmentShaderStage.usedTimes++; + } + return this; + } + remove(material) { + const materialShaders = this.materialCache.get(material); + for (const shaderStage of materialShaders) { + shaderStage.usedTimes--; + if (shaderStage.usedTimes === 0) + this.shaderCache.delete(shaderStage.code); + } + this.materialCache.delete(material); + return this; + } + getVertexShaderID(material) { + return this._getShaderStage(material.vertexShader).id; + } + getFragmentShaderID(material) { + return this._getShaderStage(material.fragmentShader).id; + } + dispose() { + this.shaderCache.clear(); + this.materialCache.clear(); + } + _getShaderCacheForMaterial(material) { + const cache = this.materialCache; + let set = cache.get(material); + if (set === undefined) { + set = new Set; + cache.set(material, set); + } + return set; + } + _getShaderStage(code) { + const cache = this.shaderCache; + let stage = cache.get(code); + if (stage === undefined) { + stage = new WebGLShaderStage2(code); + cache.set(code, stage); + } + return stage; + } + } + + class WebGLShaderStage2 { + constructor(code) { + this.id = _id3++; + this.code = code; + this.usedTimes = 0; + } + } + function WebGLPrograms2(renderer2, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) { + const _programLayers = new Layers2; + const _customShaders = new WebGLShaderCache2; + const _activeChannels = new Set; + const programs = []; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures; + let precision = capabilities.precision; + const shaderIDs = { + MeshDepthMaterial: "depth", + MeshDistanceMaterial: "distanceRGBA", + MeshNormalMaterial: "normal", + MeshBasicMaterial: "basic", + MeshLambertMaterial: "lambert", + MeshPhongMaterial: "phong", + MeshToonMaterial: "toon", + MeshStandardMaterial: "physical", + MeshPhysicalMaterial: "physical", + MeshMatcapMaterial: "matcap", + LineBasicMaterial: "basic", + LineDashedMaterial: "dashed", + PointsMaterial: "points", + ShadowMaterial: "shadow", + SpriteMaterial: "sprite" + }; + function getChannel(value2) { + _activeChannels.add(value2); + if (value2 === 0) + return "uv"; + return `uv${value2}`; + } + function getParameters(material, lights, shadows, scene, object) { + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping2 ? envMap.image.height : null; + const shaderID = shaderIDs[material.type]; + if (material.precision !== null) { + precision = capabilities.getMaxPrecision(material.precision); + if (precision !== material.precision) { + console.warn("THREE.WebGLProgram.getParameters:", material.precision, "not supported, using", precision, "instead."); + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + let morphTextureStride = 0; + if (geometry.morphAttributes.position !== undefined) + morphTextureStride = 1; + if (geometry.morphAttributes.normal !== undefined) + morphTextureStride = 2; + if (geometry.morphAttributes.color !== undefined) + morphTextureStride = 3; + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + if (shaderID) { + const shader = ShaderLib2[shaderID]; + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + } else { + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + _customShaders.update(material); + customVertexShaderID = _customShaders.getVertexShaderID(material); + customFragmentShaderID = _customShaders.getFragmentShaderID(material); + } + const currentRenderTarget = renderer2.getRenderTarget(); + const reverseDepthBuffer = renderer2.state.buffers.depth.getReversed(); + const IS_INSTANCEDMESH = object.isInstancedMesh === true; + const IS_BATCHEDMESH = object.isBatchedMesh === true; + const HAS_MAP = !!material.map; + const HAS_MATCAP = !!material.matcap; + const HAS_ENVMAP = !!envMap; + const HAS_AOMAP = !!material.aoMap; + const HAS_LIGHTMAP = !!material.lightMap; + const HAS_BUMPMAP = !!material.bumpMap; + const HAS_NORMALMAP = !!material.normalMap; + const HAS_DISPLACEMENTMAP = !!material.displacementMap; + const HAS_EMISSIVEMAP = !!material.emissiveMap; + const HAS_METALNESSMAP = !!material.metalnessMap; + const HAS_ROUGHNESSMAP = !!material.roughnessMap; + const HAS_ANISOTROPY = material.anisotropy > 0; + const HAS_CLEARCOAT = material.clearcoat > 0; + const HAS_DISPERSION = material.dispersion > 0; + const HAS_IRIDESCENCE = material.iridescence > 0; + const HAS_SHEEN = material.sheen > 0; + const HAS_TRANSMISSION = material.transmission > 0; + const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !!material.anisotropyMap; + const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !!material.clearcoatMap; + const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !!material.clearcoatNormalMap; + const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !!material.clearcoatRoughnessMap; + const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !!material.iridescenceMap; + const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !!material.iridescenceThicknessMap; + const HAS_SHEEN_COLORMAP = HAS_SHEEN && !!material.sheenColorMap; + const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !!material.sheenRoughnessMap; + const HAS_SPECULARMAP = !!material.specularMap; + const HAS_SPECULAR_COLORMAP = !!material.specularColorMap; + const HAS_SPECULAR_INTENSITYMAP = !!material.specularIntensityMap; + const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !!material.transmissionMap; + const HAS_THICKNESSMAP = HAS_TRANSMISSION && !!material.thicknessMap; + const HAS_GRADIENTMAP = !!material.gradientMap; + const HAS_ALPHAMAP = !!material.alphaMap; + const HAS_ALPHATEST = material.alphaTest > 0; + const HAS_ALPHAHASH = !!material.alphaHash; + const HAS_EXTENSIONS = !!material.extensions; + let toneMapping = NoToneMapping2; + if (material.toneMapped) { + if (currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true) { + toneMapping = renderer2.toneMapping; + } + } + const parameters = { + shaderID, + shaderType: material.type, + shaderName: material.name, + vertexShader, + fragmentShader, + defines: material.defines, + customVertexShaderID, + customFragmentShaderID, + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + precision, + batching: IS_BATCHEDMESH, + batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null, + instancing: IS_INSTANCEDMESH, + instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, + supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, + outputColorSpace: currentRenderTarget === null ? renderer2.outputColorSpace : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace2, + alphaToCoverage: !!material.alphaToCoverage, + map: HAS_MAP, + matcap: HAS_MATCAP, + envMap: HAS_ENVMAP, + envMapMode: HAS_ENVMAP && envMap.mapping, + envMapCubeUVHeight, + aoMap: HAS_AOMAP, + lightMap: HAS_LIGHTMAP, + bumpMap: HAS_BUMPMAP, + normalMap: HAS_NORMALMAP, + displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP, + emissiveMap: HAS_EMISSIVEMAP, + normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap2, + normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap2, + metalnessMap: HAS_METALNESSMAP, + roughnessMap: HAS_ROUGHNESSMAP, + anisotropy: HAS_ANISOTROPY, + anisotropyMap: HAS_ANISOTROPYMAP, + clearcoat: HAS_CLEARCOAT, + clearcoatMap: HAS_CLEARCOATMAP, + clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP, + clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP, + dispersion: HAS_DISPERSION, + iridescence: HAS_IRIDESCENCE, + iridescenceMap: HAS_IRIDESCENCEMAP, + iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP, + sheen: HAS_SHEEN, + sheenColorMap: HAS_SHEEN_COLORMAP, + sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP, + specularMap: HAS_SPECULARMAP, + specularColorMap: HAS_SPECULAR_COLORMAP, + specularIntensityMap: HAS_SPECULAR_INTENSITYMAP, + transmission: HAS_TRANSMISSION, + transmissionMap: HAS_TRANSMISSIONMAP, + thicknessMap: HAS_THICKNESSMAP, + gradientMap: HAS_GRADIENTMAP, + opaque: material.transparent === false && material.blending === NormalBlending2 && material.alphaToCoverage === false, + alphaMap: HAS_ALPHAMAP, + alphaTest: HAS_ALPHATEST, + alphaHash: HAS_ALPHAHASH, + combine: material.combine, + mapUv: HAS_MAP && getChannel(material.map.channel), + aoMapUv: HAS_AOMAP && getChannel(material.aoMap.channel), + lightMapUv: HAS_LIGHTMAP && getChannel(material.lightMap.channel), + bumpMapUv: HAS_BUMPMAP && getChannel(material.bumpMap.channel), + normalMapUv: HAS_NORMALMAP && getChannel(material.normalMap.channel), + displacementMapUv: HAS_DISPLACEMENTMAP && getChannel(material.displacementMap.channel), + emissiveMapUv: HAS_EMISSIVEMAP && getChannel(material.emissiveMap.channel), + metalnessMapUv: HAS_METALNESSMAP && getChannel(material.metalnessMap.channel), + roughnessMapUv: HAS_ROUGHNESSMAP && getChannel(material.roughnessMap.channel), + anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel(material.anisotropyMap.channel), + clearcoatMapUv: HAS_CLEARCOATMAP && getChannel(material.clearcoatMap.channel), + clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel(material.clearcoatNormalMap.channel), + clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel(material.clearcoatRoughnessMap.channel), + iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel(material.iridescenceMap.channel), + iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel(material.iridescenceThicknessMap.channel), + sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel(material.sheenColorMap.channel), + sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel(material.sheenRoughnessMap.channel), + specularMapUv: HAS_SPECULARMAP && getChannel(material.specularMap.channel), + specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel(material.specularColorMap.channel), + specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel(material.specularIntensityMap.channel), + transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel(material.transmissionMap.channel), + thicknessMapUv: HAS_THICKNESSMAP && getChannel(material.thicknessMap.channel), + alphaMapUv: HAS_ALPHAMAP && getChannel(material.alphaMap.channel), + vertexTangents: !!geometry.attributes.tangent && (HAS_NORMALMAP || HAS_ANISOTROPY), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4, + pointsUvs: object.isPoints === true && !!geometry.attributes.uv && (HAS_MAP || HAS_ALPHAMAP), + fog: !!fog, + useFog: material.fog === true, + fogExp2: !!fog && fog.isFogExp2, + flatShading: material.flatShading === true, + sizeAttenuation: material.sizeAttenuation === true, + logarithmicDepthBuffer, + reverseDepthBuffer, + skinning: object.isSkinnedMesh === true, + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount, + morphTextureStride, + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + numLightProbes: lights.numLightProbes, + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + dithering: material.dithering, + shadowMapEnabled: renderer2.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer2.shadowMap.type, + toneMapping, + decodeVideoTexture: HAS_MAP && material.map.isVideoTexture === true && ColorManagement2.getTransfer(material.map.colorSpace) === SRGBTransfer2, + decodeVideoTextureEmissive: HAS_EMISSIVEMAP && material.emissiveMap.isVideoTexture === true && ColorManagement2.getTransfer(material.emissiveMap.colorSpace) === SRGBTransfer2, + premultipliedAlpha: material.premultipliedAlpha, + doubleSided: material.side === DoubleSide2, + flipSided: material.side === BackSide2, + useDepthPacking: material.depthPacking >= 0, + depthPacking: material.depthPacking || 0, + index0AttributeName: material.index0AttributeName, + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has("WEBGL_clip_cull_distance"), + extensionMultiDraw: (HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH) && extensions.has("WEBGL_multi_draw"), + rendererExtensionParallelShaderCompile: extensions.has("KHR_parallel_shader_compile"), + customProgramCacheKey: material.customProgramCacheKey() + }; + parameters.vertexUv1s = _activeChannels.has(1); + parameters.vertexUv2s = _activeChannels.has(2); + parameters.vertexUv3s = _activeChannels.has(3); + _activeChannels.clear(); + return parameters; + } + function getProgramCacheKey(parameters) { + const array = []; + if (parameters.shaderID) { + array.push(parameters.shaderID); + } else { + array.push(parameters.customVertexShaderID); + array.push(parameters.customFragmentShaderID); + } + if (parameters.defines !== undefined) { + for (const name2 in parameters.defines) { + array.push(name2); + array.push(parameters.defines[name2]); + } + } + if (parameters.isRawShaderMaterial === false) { + getProgramCacheKeyParameters(array, parameters); + getProgramCacheKeyBooleans(array, parameters); + array.push(renderer2.outputColorSpace); + } + array.push(parameters.customProgramCacheKey); + return array.join(); + } + function getProgramCacheKeyParameters(array, parameters) { + array.push(parameters.precision); + array.push(parameters.outputColorSpace); + array.push(parameters.envMapMode); + array.push(parameters.envMapCubeUVHeight); + array.push(parameters.mapUv); + array.push(parameters.alphaMapUv); + array.push(parameters.lightMapUv); + array.push(parameters.aoMapUv); + array.push(parameters.bumpMapUv); + array.push(parameters.normalMapUv); + array.push(parameters.displacementMapUv); + array.push(parameters.emissiveMapUv); + array.push(parameters.metalnessMapUv); + array.push(parameters.roughnessMapUv); + array.push(parameters.anisotropyMapUv); + array.push(parameters.clearcoatMapUv); + array.push(parameters.clearcoatNormalMapUv); + array.push(parameters.clearcoatRoughnessMapUv); + array.push(parameters.iridescenceMapUv); + array.push(parameters.iridescenceThicknessMapUv); + array.push(parameters.sheenColorMapUv); + array.push(parameters.sheenRoughnessMapUv); + array.push(parameters.specularMapUv); + array.push(parameters.specularColorMapUv); + array.push(parameters.specularIntensityMapUv); + array.push(parameters.transmissionMapUv); + array.push(parameters.thicknessMapUv); + array.push(parameters.combine); + array.push(parameters.fogExp2); + array.push(parameters.sizeAttenuation); + array.push(parameters.morphTargetsCount); + array.push(parameters.morphAttributeCount); + array.push(parameters.numDirLights); + array.push(parameters.numPointLights); + array.push(parameters.numSpotLights); + array.push(parameters.numSpotLightMaps); + array.push(parameters.numHemiLights); + array.push(parameters.numRectAreaLights); + array.push(parameters.numDirLightShadows); + array.push(parameters.numPointLightShadows); + array.push(parameters.numSpotLightShadows); + array.push(parameters.numSpotLightShadowsWithMaps); + array.push(parameters.numLightProbes); + array.push(parameters.shadowMapType); + array.push(parameters.toneMapping); + array.push(parameters.numClippingPlanes); + array.push(parameters.numClipIntersection); + array.push(parameters.depthPacking); + } + function getProgramCacheKeyBooleans(array, parameters) { + _programLayers.disableAll(); + if (parameters.supportsVertexTextures) + _programLayers.enable(0); + if (parameters.instancing) + _programLayers.enable(1); + if (parameters.instancingColor) + _programLayers.enable(2); + if (parameters.instancingMorph) + _programLayers.enable(3); + if (parameters.matcap) + _programLayers.enable(4); + if (parameters.envMap) + _programLayers.enable(5); + if (parameters.normalMapObjectSpace) + _programLayers.enable(6); + if (parameters.normalMapTangentSpace) + _programLayers.enable(7); + if (parameters.clearcoat) + _programLayers.enable(8); + if (parameters.iridescence) + _programLayers.enable(9); + if (parameters.alphaTest) + _programLayers.enable(10); + if (parameters.vertexColors) + _programLayers.enable(11); + if (parameters.vertexAlphas) + _programLayers.enable(12); + if (parameters.vertexUv1s) + _programLayers.enable(13); + if (parameters.vertexUv2s) + _programLayers.enable(14); + if (parameters.vertexUv3s) + _programLayers.enable(15); + if (parameters.vertexTangents) + _programLayers.enable(16); + if (parameters.anisotropy) + _programLayers.enable(17); + if (parameters.alphaHash) + _programLayers.enable(18); + if (parameters.batching) + _programLayers.enable(19); + if (parameters.dispersion) + _programLayers.enable(20); + if (parameters.batchingColor) + _programLayers.enable(21); + array.push(_programLayers.mask); + _programLayers.disableAll(); + if (parameters.fog) + _programLayers.enable(0); + if (parameters.useFog) + _programLayers.enable(1); + if (parameters.flatShading) + _programLayers.enable(2); + if (parameters.logarithmicDepthBuffer) + _programLayers.enable(3); + if (parameters.reverseDepthBuffer) + _programLayers.enable(4); + if (parameters.skinning) + _programLayers.enable(5); + if (parameters.morphTargets) + _programLayers.enable(6); + if (parameters.morphNormals) + _programLayers.enable(7); + if (parameters.morphColors) + _programLayers.enable(8); + if (parameters.premultipliedAlpha) + _programLayers.enable(9); + if (parameters.shadowMapEnabled) + _programLayers.enable(10); + if (parameters.doubleSided) + _programLayers.enable(11); + if (parameters.flipSided) + _programLayers.enable(12); + if (parameters.useDepthPacking) + _programLayers.enable(13); + if (parameters.dithering) + _programLayers.enable(14); + if (parameters.transmission) + _programLayers.enable(15); + if (parameters.sheen) + _programLayers.enable(16); + if (parameters.opaque) + _programLayers.enable(17); + if (parameters.pointsUvs) + _programLayers.enable(18); + if (parameters.decodeVideoTexture) + _programLayers.enable(19); + if (parameters.decodeVideoTextureEmissive) + _programLayers.enable(20); + if (parameters.alphaToCoverage) + _programLayers.enable(21); + array.push(_programLayers.mask); + } + function getUniforms(material) { + const shaderID = shaderIDs[material.type]; + let uniforms; + if (shaderID) { + const shader = ShaderLib2[shaderID]; + uniforms = UniformsUtils2.clone(shader.uniforms); + } else { + uniforms = material.uniforms; + } + return uniforms; + } + function acquireProgram(parameters, cacheKey) { + let program; + for (let p = 0, pl2 = programs.length;p < pl2; p++) { + const preexistingProgram = programs[p]; + if (preexistingProgram.cacheKey === cacheKey) { + program = preexistingProgram; + ++program.usedTimes; + break; + } + } + if (program === undefined) { + program = new WebGLProgram2(renderer2, cacheKey, parameters, bindingStates); + programs.push(program); + } + return program; + } + function releaseProgram(program) { + if (--program.usedTimes === 0) { + const i = programs.indexOf(program); + programs[i] = programs[programs.length - 1]; + programs.pop(); + program.destroy(); + } + } + function releaseShaderCache(material) { + _customShaders.remove(material); + } + function dispose() { + _customShaders.dispose(); + } + return { + getParameters, + getProgramCacheKey, + getUniforms, + acquireProgram, + releaseProgram, + releaseShaderCache, + programs, + dispose + }; + } + function WebGLProperties2() { + let properties = new WeakMap; + function has2(object) { + return properties.has(object); + } + function get(object) { + let map2 = properties.get(object); + if (map2 === undefined) { + map2 = {}; + properties.set(object, map2); + } + return map2; + } + function remove(object) { + properties.delete(object); + } + function update(object, key2, value2) { + properties.get(object)[key2] = value2; + } + function dispose() { + properties = new WeakMap; + } + return { + has: has2, + get, + remove, + update, + dispose + }; + } + function painterSortStable2(a2, b3) { + if (a2.groupOrder !== b3.groupOrder) { + return a2.groupOrder - b3.groupOrder; + } else if (a2.renderOrder !== b3.renderOrder) { + return a2.renderOrder - b3.renderOrder; + } else if (a2.material.id !== b3.material.id) { + return a2.material.id - b3.material.id; + } else if (a2.z !== b3.z) { + return a2.z - b3.z; + } else { + return a2.id - b3.id; + } + } + function reversePainterSortStable2(a2, b3) { + if (a2.groupOrder !== b3.groupOrder) { + return a2.groupOrder - b3.groupOrder; + } else if (a2.renderOrder !== b3.renderOrder) { + return a2.renderOrder - b3.renderOrder; + } else if (a2.z !== b3.z) { + return b3.z - a2.z; + } else { + return a2.id - b3.id; + } + } + function WebGLRenderList2() { + const renderItems = []; + let renderItemsIndex = 0; + const opaque = []; + const transmissive = []; + const transparent = []; + function init() { + renderItemsIndex = 0; + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + } + function getNextRenderItem(object, geometry, material, groupOrder, z2, group) { + let renderItem = renderItems[renderItemsIndex]; + if (renderItem === undefined) { + renderItem = { + id: object.id, + object, + geometry, + material, + groupOrder, + renderOrder: object.renderOrder, + z: z2, + group + }; + renderItems[renderItemsIndex] = renderItem; + } else { + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z2; + renderItem.group = group; + } + renderItemsIndex++; + return renderItem; + } + function push(object, geometry, material, groupOrder, z2, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z2, group); + if (material.transmission > 0) { + transmissive.push(renderItem); + } else if (material.transparent === true) { + transparent.push(renderItem); + } else { + opaque.push(renderItem); + } + } + function unshift(object, geometry, material, groupOrder, z2, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z2, group); + if (material.transmission > 0) { + transmissive.unshift(renderItem); + } else if (material.transparent === true) { + transparent.unshift(renderItem); + } else { + opaque.unshift(renderItem); + } + } + function sort(customOpaqueSort, customTransparentSort) { + if (opaque.length > 1) + opaque.sort(customOpaqueSort || painterSortStable2); + if (transmissive.length > 1) + transmissive.sort(customTransparentSort || reversePainterSortStable2); + if (transparent.length > 1) + transparent.sort(customTransparentSort || reversePainterSortStable2); + } + function finish() { + for (let i = renderItemsIndex, il = renderItems.length;i < il; i++) { + const renderItem = renderItems[i]; + if (renderItem.id === null) + break; + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + } + } + return { + opaque, + transmissive, + transparent, + init, + push, + unshift, + finish, + sort + }; + } + function WebGLRenderLists2() { + let lists = new WeakMap; + function get(scene, renderCallDepth) { + const listArray = lists.get(scene); + let list; + if (listArray === undefined) { + list = new WebGLRenderList2; + lists.set(scene, [list]); + } else { + if (renderCallDepth >= listArray.length) { + list = new WebGLRenderList2; + listArray.push(list); + } else { + list = listArray[renderCallDepth]; + } + } + return list; + } + function dispose() { + lists = new WeakMap; + } + return { + get, + dispose + }; + } + function UniformsCache2() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== undefined) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + direction: new Vector32, + color: new Color2 + }; + break; + case "SpotLight": + uniforms = { + position: new Vector32, + direction: new Vector32, + color: new Color2, + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + case "PointLight": + uniforms = { + position: new Vector32, + color: new Color2, + distance: 0, + decay: 0 + }; + break; + case "HemisphereLight": + uniforms = { + direction: new Vector32, + skyColor: new Color2, + groundColor: new Color2 + }; + break; + case "RectAreaLight": + uniforms = { + color: new Color2, + position: new Vector32, + halfWidth: new Vector32, + halfHeight: new Vector32 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; + } + function ShadowUniformsCache2() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== undefined) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector22 + }; + break; + case "SpotLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector22 + }; + break; + case "PointLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector22, + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; + } + var nextVersion2 = 0; + function shadowCastingAndTexturingLightsFirst2(lightA, lightB) { + return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0); + } + function WebGLLights2(extensions) { + const cache = new UniformsCache2; + const shadowCache = ShadowUniformsCache2(); + const state = { + version: 0, + hash: { + directionalLength: -1, + pointLength: -1, + spotLength: -1, + rectAreaLength: -1, + hemiLength: -1, + numDirectionalShadows: -1, + numPointShadows: -1, + numSpotShadows: -1, + numSpotMaps: -1, + numLightProbes: -1 + }, + ambient: [0, 0, 0], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0, + numLightProbes: 0 + }; + for (let i = 0;i < 9; i++) + state.probe.push(new Vector32); + const vector3 = new Vector32; + const matrix4 = new Matrix42; + const matrix42 = new Matrix42; + function setup(lights) { + let r = 0, g3 = 0, b3 = 0; + for (let i = 0;i < 9; i++) + state.probe[i].set(0, 0, 0); + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + let numLightProbes = 0; + lights.sort(shadowCastingAndTexturingLightsFirst2); + for (let i = 0, l2 = lights.length;i < l2; i++) { + const light = lights[i]; + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null; + if (light.isAmbientLight) { + r += color.r * intensity; + g3 += color.g * intensity; + b3 += color.b * intensity; + } else if (light.isLightProbe) { + for (let j2 = 0;j2 < 9; j2++) { + state.probe[j2].addScaledVector(light.sh.coefficients[j2], intensity); + } + numLightProbes++; + } else if (light.isDirectionalLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.directionalShadow[directionalLength] = shadowUniforms; + state.directionalShadowMap[directionalLength] = shadowMap; + state.directionalShadowMatrix[directionalLength] = light.shadow.matrix; + numDirectionalShadows++; + } + state.directional[directionalLength] = uniforms; + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = cache.get(light); + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.distance = distance; + uniforms.coneCos = Math.cos(light.angle); + uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra)); + uniforms.decay = light.decay; + state.spot[spotLength] = uniforms; + const shadow = light.shadow; + if (light.map) { + state.spotLightMap[numSpotMaps] = light.map; + numSpotMaps++; + shadow.updateMatrices(light); + if (light.castShadow) + numSpotShadowsWithMaps++; + } + state.spotLightMatrix[spotLength] = shadow.matrix; + if (light.castShadow) { + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.spotShadow[spotLength] = shadowUniforms; + state.spotShadowMap[spotLength] = shadowMap; + numSpotShadows++; + } + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = cache.get(light); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + state.rectArea[rectAreaLength] = uniforms; + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + state.pointShadow[pointLength] = shadowUniforms; + state.pointShadowMap[pointLength] = shadowMap; + state.pointShadowMatrix[pointLength] = light.shadow.matrix; + numPointShadows++; + } + state.point[pointLength] = uniforms; + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = cache.get(light); + uniforms.skyColor.copy(light.color).multiplyScalar(intensity); + uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity); + state.hemi[hemiLength] = uniforms; + hemiLength++; + } + } + if (rectAreaLength > 0) { + if (extensions.has("OES_texture_float_linear") === true) { + state.rectAreaLTC1 = UniformsLib2.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib2.LTC_FLOAT_2; + } else { + state.rectAreaLTC1 = UniformsLib2.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib2.LTC_HALF_2; + } + } + state.ambient[0] = r; + state.ambient[1] = g3; + state.ambient[2] = b3; + const hash = state.hash; + if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps || hash.numLightProbes !== numLightProbes) { + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + state.numLightProbes = numLightProbes; + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + hash.numLightProbes = numLightProbes; + state.version = nextVersion2++; + } + } + function setupView(lights, camera) { + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + const viewMatrix = camera.matrixWorldInverse; + for (let i = 0, l2 = lights.length;i < l2; i++) { + const light = lights[i]; + if (light.isDirectionalLight) { + const uniforms = state.directional[directionalLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = state.spot[spotLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = state.rectArea[rectAreaLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + matrix42.identity(); + matrix4.copy(light.matrixWorld); + matrix4.premultiply(viewMatrix); + matrix42.extractRotation(matrix4); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + uniforms.halfWidth.applyMatrix4(matrix42); + uniforms.halfHeight.applyMatrix4(matrix42); + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = state.point[pointLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = state.hemi[hemiLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + uniforms.direction.transformDirection(viewMatrix); + hemiLength++; + } + } + } + return { + setup, + setupView, + state + }; + } + function WebGLRenderState2(extensions) { + const lights = new WebGLLights2(extensions); + const lightsArray = []; + const shadowsArray = []; + function init(camera) { + state.camera = camera; + lightsArray.length = 0; + shadowsArray.length = 0; + } + function pushLight(light) { + lightsArray.push(light); + } + function pushShadow(shadowLight) { + shadowsArray.push(shadowLight); + } + function setupLights() { + lights.setup(lightsArray); + } + function setupLightsView(camera) { + lights.setupView(lightsArray, camera); + } + const state = { + lightsArray, + shadowsArray, + camera: null, + lights, + transmissionRenderTarget: {} + }; + return { + init, + state, + setupLights, + setupLightsView, + pushLight, + pushShadow + }; + } + function WebGLRenderStates2(extensions) { + let renderStates = new WeakMap; + function get(scene, renderCallDepth = 0) { + const renderStateArray = renderStates.get(scene); + let renderState; + if (renderStateArray === undefined) { + renderState = new WebGLRenderState2(extensions); + renderStates.set(scene, [renderState]); + } else { + if (renderCallDepth >= renderStateArray.length) { + renderState = new WebGLRenderState2(extensions); + renderStateArray.push(renderState); + } else { + renderState = renderStateArray[renderCallDepth]; + } + } + return renderState; + } + function dispose() { + renderStates = new WeakMap; + } + return { + get, + dispose + }; + } + var vertex2 = `void main() { + gl_Position = vec4( position, 1.0 ); +}`; + var fragment2 = `uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`; + function WebGLShadowMap2(renderer2, objects, capabilities) { + let _frustum4 = new Frustum2; + const _shadowMapSize = new Vector22, _viewportSize = new Vector22, _viewport3 = new Vector42, _depthMaterial = new MeshDepthMaterial2({ depthPacking: RGBADepthPacking2 }), _distanceMaterial = new MeshDistanceMaterial2, _materialCache = {}, _maxTextureSize = capabilities.maxTextureSize; + const shadowSide = { [FrontSide2]: BackSide2, [BackSide2]: FrontSide2, [DoubleSide2]: DoubleSide2 }; + const shadowMaterialVertical = new ShaderMaterial2({ + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector22 }, + radius: { value: 4 } + }, + vertexShader: vertex2, + fragmentShader: fragment2 + }); + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + const fullScreenTri = new BufferGeometry2; + fullScreenTri.setAttribute("position", new BufferAttribute2(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3)); + const fullScreenMesh = new Mesh2(fullScreenTri, shadowMaterialVertical); + const scope = this; + this.enabled = false; + this.autoUpdate = true; + this.needsUpdate = false; + this.type = PCFShadowMap2; + let _previousType = this.type; + this.render = function(lights, scene, camera) { + if (scope.enabled === false) + return; + if (scope.autoUpdate === false && scope.needsUpdate === false) + return; + if (lights.length === 0) + return; + const currentRenderTarget = renderer2.getRenderTarget(); + const activeCubeFace = renderer2.getActiveCubeFace(); + const activeMipmapLevel = renderer2.getActiveMipmapLevel(); + const _state = renderer2.state; + _state.setBlending(NoBlending2); + _state.buffers.color.setClear(1, 1, 1, 1); + _state.buffers.depth.setTest(true); + _state.setScissorTest(false); + const toVSM = _previousType !== VSMShadowMap2 && this.type === VSMShadowMap2; + const fromVSM = _previousType === VSMShadowMap2 && this.type !== VSMShadowMap2; + for (let i = 0, il = lights.length;i < il; i++) { + const light = lights[i]; + const shadow = light.shadow; + if (shadow === undefined) { + console.warn("THREE.WebGLShadowMap:", light, "has no shadow."); + continue; + } + if (shadow.autoUpdate === false && shadow.needsUpdate === false) + continue; + _shadowMapSize.copy(shadow.mapSize); + const shadowFrameExtents = shadow.getFrameExtents(); + _shadowMapSize.multiply(shadowFrameExtents); + _viewportSize.copy(shadow.mapSize); + if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) { + if (_shadowMapSize.x > _maxTextureSize) { + _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + } + if (_shadowMapSize.y > _maxTextureSize) { + _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + } + } + if (shadow.map === null || toVSM === true || fromVSM === true) { + const pars = this.type !== VSMShadowMap2 ? { minFilter: NearestFilter2, magFilter: NearestFilter2 } : {}; + if (shadow.map !== null) { + shadow.map.dispose(); + } + shadow.map = new WebGLRenderTarget2(_shadowMapSize.x, _shadowMapSize.y, pars); + shadow.map.texture.name = light.name + ".shadowMap"; + shadow.camera.updateProjectionMatrix(); + } + renderer2.setRenderTarget(shadow.map); + renderer2.clear(); + const viewportCount = shadow.getViewportCount(); + for (let vp = 0;vp < viewportCount; vp++) { + const viewport = shadow.getViewport(vp); + _viewport3.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w); + _state.viewport(_viewport3); + shadow.updateMatrices(light, vp); + _frustum4 = shadow.getFrustum(); + renderObject(scene, camera, shadow.camera, light, this.type); + } + if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap2) { + VSMPass(shadow, camera); + } + shadow.needsUpdate = false; + } + _previousType = this.type; + scope.needsUpdate = false; + renderer2.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel); + }; + function VSMPass(shadow, camera) { + const geometry = objects.update(fullScreenMesh); + if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) { + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + } + if (shadow.mapPass === null) { + shadow.mapPass = new WebGLRenderTarget2(_shadowMapSize.x, _shadowMapSize.y); + } + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + renderer2.setRenderTarget(shadow.mapPass); + renderer2.clear(); + renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + renderer2.setRenderTarget(shadow.map); + renderer2.clear(); + renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null); + } + function getDepthMaterial(object, material, light, type) { + let result = null; + const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial; + if (customMaterial !== undefined) { + result = customMaterial; + } else { + result = light.isPointLight === true ? _distanceMaterial : _depthMaterial; + if (renderer2.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0 || material.map && material.alphaTest > 0) { + const keyA = result.uuid, keyB = material.uuid; + let materialsForVariant = _materialCache[keyA]; + if (materialsForVariant === undefined) { + materialsForVariant = {}; + _materialCache[keyA] = materialsForVariant; + } + let cachedMaterial = materialsForVariant[keyB]; + if (cachedMaterial === undefined) { + cachedMaterial = result.clone(); + materialsForVariant[keyB] = cachedMaterial; + material.addEventListener("dispose", onMaterialDispose); + } + result = cachedMaterial; + } + } + result.visible = material.visible; + result.wireframe = material.wireframe; + if (type === VSMShadowMap2) { + result.side = material.shadowSide !== null ? material.shadowSide : material.side; + } else { + result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side]; + } + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.map = material.map; + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + if (light.isPointLight === true && result.isMeshDistanceMaterial === true) { + const materialProperties = renderer2.properties.get(result); + materialProperties.light = light; + } + return result; + } + function renderObject(object, camera, shadowCamera, light, type) { + if (object.visible === false) + return; + const visible = object.layers.test(camera.layers); + if (visible && (object.isMesh || object.isLine || object.isPoints)) { + if ((object.castShadow || object.receiveShadow && type === VSMShadowMap2) && (!object.frustumCulled || _frustum4.intersectsObject(object))) { + object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld); + const geometry = objects.update(object); + const material = object.material; + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let k4 = 0, kl = groups.length;k4 < kl; k4++) { + const group = groups[k4]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + const depthMaterial = getDepthMaterial(object, groupMaterial, light, type); + object.onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group); + object.onAfterShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + } + } + } else if (material.visible) { + const depthMaterial = getDepthMaterial(object, material, light, type); + object.onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null); + object.onAfterShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + } + } + } + const children = object.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + renderObject(children[i], camera, shadowCamera, light, type); + } + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + for (const id in _materialCache) { + const cache = _materialCache[id]; + const uuid = event.target.uuid; + if (uuid in cache) { + const shadowMaterial = cache[uuid]; + shadowMaterial.dispose(); + delete cache[uuid]; + } + } + } + } + var reversedFuncs2 = { + [NeverDepth2]: AlwaysDepth2, + [LessDepth2]: GreaterDepth2, + [EqualDepth2]: NotEqualDepth2, + [LessEqualDepth2]: GreaterEqualDepth2, + [AlwaysDepth2]: NeverDepth2, + [GreaterDepth2]: LessDepth2, + [NotEqualDepth2]: EqualDepth2, + [GreaterEqualDepth2]: LessEqualDepth2 + }; + function WebGLState2(gl, extensions) { + function ColorBuffer() { + let locked = false; + const color = new Vector42; + let currentColorMask = null; + const currentColorClear = new Vector42(0, 0, 0, 0); + return { + setMask: function(colorMask) { + if (currentColorMask !== colorMask && !locked) { + gl.colorMask(colorMask, colorMask, colorMask, colorMask); + currentColorMask = colorMask; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(r, g3, b3, a2, premultipliedAlpha) { + if (premultipliedAlpha === true) { + r *= a2; + g3 *= a2; + b3 *= a2; + } + color.set(r, g3, b3, a2); + if (currentColorClear.equals(color) === false) { + gl.clearColor(r, g3, b3, a2); + currentColorClear.copy(color); + } + }, + reset: function() { + locked = false; + currentColorMask = null; + currentColorClear.set(-1, 0, 0, 0); + } + }; + } + function DepthBuffer() { + let locked = false; + let reversed = false; + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + return { + setReversed: function(value2) { + if (reversed !== value2) { + const ext = extensions.get("EXT_clip_control"); + if (reversed) { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT); + } else { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT); + } + const oldDepth = currentDepthClear; + currentDepthClear = null; + this.setClear(oldDepth); + } + reversed = value2; + }, + getReversed: function() { + return reversed; + }, + setTest: function(depthTest) { + if (depthTest) { + enable(gl.DEPTH_TEST); + } else { + disable(gl.DEPTH_TEST); + } + }, + setMask: function(depthMask) { + if (currentDepthMask !== depthMask && !locked) { + gl.depthMask(depthMask); + currentDepthMask = depthMask; + } + }, + setFunc: function(depthFunc) { + if (reversed) + depthFunc = reversedFuncs2[depthFunc]; + if (currentDepthFunc !== depthFunc) { + switch (depthFunc) { + case NeverDepth2: + gl.depthFunc(gl.NEVER); + break; + case AlwaysDepth2: + gl.depthFunc(gl.ALWAYS); + break; + case LessDepth2: + gl.depthFunc(gl.LESS); + break; + case LessEqualDepth2: + gl.depthFunc(gl.LEQUAL); + break; + case EqualDepth2: + gl.depthFunc(gl.EQUAL); + break; + case GreaterEqualDepth2: + gl.depthFunc(gl.GEQUAL); + break; + case GreaterDepth2: + gl.depthFunc(gl.GREATER); + break; + case NotEqualDepth2: + gl.depthFunc(gl.NOTEQUAL); + break; + default: + gl.depthFunc(gl.LEQUAL); + } + currentDepthFunc = depthFunc; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(depth) { + if (currentDepthClear !== depth) { + if (reversed) { + depth = 1 - depth; + } + gl.clearDepth(depth); + currentDepthClear = depth; + } + }, + reset: function() { + locked = false; + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + reversed = false; + } + }; + } + function StencilBuffer() { + let locked = false; + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + return { + setTest: function(stencilTest) { + if (!locked) { + if (stencilTest) { + enable(gl.STENCIL_TEST); + } else { + disable(gl.STENCIL_TEST); + } + } + }, + setMask: function(stencilMask) { + if (currentStencilMask !== stencilMask && !locked) { + gl.stencilMask(stencilMask); + currentStencilMask = stencilMask; + } + }, + setFunc: function(stencilFunc, stencilRef, stencilMask) { + if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) { + gl.stencilFunc(stencilFunc, stencilRef, stencilMask); + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + } + }, + setOp: function(stencilFail, stencilZFail, stencilZPass) { + if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) { + gl.stencilOp(stencilFail, stencilZFail, stencilZPass); + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(stencil) { + if (currentStencilClear !== stencil) { + gl.clearStencil(stencil); + currentStencilClear = stencil; + } + }, + reset: function() { + locked = false; + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + } + }; + } + const colorBuffer = new ColorBuffer; + const depthBuffer = new DepthBuffer; + const stencilBuffer = new StencilBuffer; + const uboBindings = new WeakMap; + const uboProgramMap = new WeakMap; + let enabledCapabilities = {}; + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap; + let defaultDrawbuffers = []; + let currentProgram = null; + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentBlendColor = new Color2(0, 0, 0); + let currentBlendAlpha = 0; + let currentPremultipledAlpha = false; + let currentFlipSided = null; + let currentCullFace = null; + let currentLineWidth = null; + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter(gl.VERSION); + if (glVersion.indexOf("WebGL") !== -1) { + version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 1; + } else if (glVersion.indexOf("OpenGL ES") !== -1) { + version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 2; + } + let currentTextureSlot = null; + let currentBoundTextures = {}; + const scissorParam = gl.getParameter(gl.SCISSOR_BOX); + const viewportParam = gl.getParameter(gl.VIEWPORT); + const currentScissor = new Vector42().fromArray(scissorParam); + const currentViewport = new Vector42().fromArray(viewportParam); + function createTexture(type, target, count, dimensions) { + const data2 = new Uint8Array(4); + const texture = gl.createTexture(); + gl.bindTexture(type, texture); + gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + for (let i = 0;i < count; i++) { + if (type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY) { + gl.texImage3D(target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data2); + } else { + gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data2); + } + } + return texture; + } + const emptyTextures = {}; + emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1); + emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); + emptyTextures[gl.TEXTURE_2D_ARRAY] = createTexture(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1); + emptyTextures[gl.TEXTURE_3D] = createTexture(gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1); + colorBuffer.setClear(0, 0, 0, 1); + depthBuffer.setClear(1); + stencilBuffer.setClear(0); + enable(gl.DEPTH_TEST); + depthBuffer.setFunc(LessEqualDepth2); + setFlipSided(false); + setCullFace(CullFaceBack2); + enable(gl.CULL_FACE); + setBlending(NoBlending2); + function enable(id) { + if (enabledCapabilities[id] !== true) { + gl.enable(id); + enabledCapabilities[id] = true; + } + } + function disable(id) { + if (enabledCapabilities[id] !== false) { + gl.disable(id); + enabledCapabilities[id] = false; + } + } + function bindFramebuffer(target, framebuffer) { + if (currentBoundFramebuffers[target] !== framebuffer) { + gl.bindFramebuffer(target, framebuffer); + currentBoundFramebuffers[target] = framebuffer; + if (target === gl.DRAW_FRAMEBUFFER) { + currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer; + } + if (target === gl.FRAMEBUFFER) { + currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer; + } + return true; + } + return false; + } + function drawBuffers(renderTarget, framebuffer) { + let drawBuffers2 = defaultDrawbuffers; + let needsUpdate = false; + if (renderTarget) { + drawBuffers2 = currentDrawbuffers.get(framebuffer); + if (drawBuffers2 === undefined) { + drawBuffers2 = []; + currentDrawbuffers.set(framebuffer, drawBuffers2); + } + const textures = renderTarget.textures; + if (drawBuffers2.length !== textures.length || drawBuffers2[0] !== gl.COLOR_ATTACHMENT0) { + for (let i = 0, il = textures.length;i < il; i++) { + drawBuffers2[i] = gl.COLOR_ATTACHMENT0 + i; + } + drawBuffers2.length = textures.length; + needsUpdate = true; + } + } else { + if (drawBuffers2[0] !== gl.BACK) { + drawBuffers2[0] = gl.BACK; + needsUpdate = true; + } + } + if (needsUpdate) { + gl.drawBuffers(drawBuffers2); + } + } + function useProgram(program) { + if (currentProgram !== program) { + gl.useProgram(program); + currentProgram = program; + return true; + } + return false; + } + const equationToGL = { + [AddEquation2]: gl.FUNC_ADD, + [SubtractEquation2]: gl.FUNC_SUBTRACT, + [ReverseSubtractEquation2]: gl.FUNC_REVERSE_SUBTRACT + }; + equationToGL[MinEquation2] = gl.MIN; + equationToGL[MaxEquation2] = gl.MAX; + const factorToGL = { + [ZeroFactor2]: gl.ZERO, + [OneFactor2]: gl.ONE, + [SrcColorFactor2]: gl.SRC_COLOR, + [SrcAlphaFactor2]: gl.SRC_ALPHA, + [SrcAlphaSaturateFactor2]: gl.SRC_ALPHA_SATURATE, + [DstColorFactor2]: gl.DST_COLOR, + [DstAlphaFactor2]: gl.DST_ALPHA, + [OneMinusSrcColorFactor2]: gl.ONE_MINUS_SRC_COLOR, + [OneMinusSrcAlphaFactor2]: gl.ONE_MINUS_SRC_ALPHA, + [OneMinusDstColorFactor2]: gl.ONE_MINUS_DST_COLOR, + [OneMinusDstAlphaFactor2]: gl.ONE_MINUS_DST_ALPHA, + [ConstantColorFactor2]: gl.CONSTANT_COLOR, + [OneMinusConstantColorFactor2]: gl.ONE_MINUS_CONSTANT_COLOR, + [ConstantAlphaFactor2]: gl.CONSTANT_ALPHA, + [OneMinusConstantAlphaFactor2]: gl.ONE_MINUS_CONSTANT_ALPHA + }; + function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha) { + if (blending === NoBlending2) { + if (currentBlendingEnabled === true) { + disable(gl.BLEND); + currentBlendingEnabled = false; + } + return; + } + if (currentBlendingEnabled === false) { + enable(gl.BLEND); + currentBlendingEnabled = true; + } + if (blending !== CustomBlending2) { + if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) { + if (currentBlendEquation !== AddEquation2 || currentBlendEquationAlpha !== AddEquation2) { + gl.blendEquation(gl.FUNC_ADD); + currentBlendEquation = AddEquation2; + currentBlendEquationAlpha = AddEquation2; + } + if (premultipliedAlpha) { + switch (blending) { + case NormalBlending2: + gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending2: + gl.blendFunc(gl.ONE, gl.ONE); + break; + case SubtractiveBlending2: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending2: + gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } else { + switch (blending) { + case NormalBlending2: + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending2: + gl.blendFunc(gl.SRC_ALPHA, gl.ONE); + break; + case SubtractiveBlending2: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending2: + gl.blendFunc(gl.ZERO, gl.SRC_COLOR); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor.set(0, 0, 0); + currentBlendAlpha = 0; + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + } + return; + } + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) { + gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]); + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + } + if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) { + gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]); + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + } + if (blendColor.equals(currentBlendColor) === false || blendAlpha !== currentBlendAlpha) { + gl.blendColor(blendColor.r, blendColor.g, blendColor.b, blendAlpha); + currentBlendColor.copy(blendColor); + currentBlendAlpha = blendAlpha; + } + currentBlending = blending; + currentPremultipledAlpha = false; + } + function setMaterial(material, frontFaceCW) { + material.side === DoubleSide2 ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE); + let flipSided = material.side === BackSide2; + if (frontFaceCW) + flipSided = !flipSided; + setFlipSided(flipSided); + material.blending === NormalBlending2 && material.transparent === false ? setBlending(NoBlending2) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha); + depthBuffer.setFunc(material.depthFunc); + depthBuffer.setTest(material.depthTest); + depthBuffer.setMask(material.depthWrite); + colorBuffer.setMask(material.colorWrite); + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest(stencilWrite); + if (stencilWrite) { + stencilBuffer.setMask(material.stencilWriteMask); + stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask); + stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass); + } + setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits); + material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + } + function setFlipSided(flipSided) { + if (currentFlipSided !== flipSided) { + if (flipSided) { + gl.frontFace(gl.CW); + } else { + gl.frontFace(gl.CCW); + } + currentFlipSided = flipSided; + } + } + function setCullFace(cullFace) { + if (cullFace !== CullFaceNone2) { + enable(gl.CULL_FACE); + if (cullFace !== currentCullFace) { + if (cullFace === CullFaceBack2) { + gl.cullFace(gl.BACK); + } else if (cullFace === CullFaceFront2) { + gl.cullFace(gl.FRONT); + } else { + gl.cullFace(gl.FRONT_AND_BACK); + } + } + } else { + disable(gl.CULL_FACE); + } + currentCullFace = cullFace; + } + function setLineWidth(width2) { + if (width2 !== currentLineWidth) { + if (lineWidthAvailable) + gl.lineWidth(width2); + currentLineWidth = width2; + } + } + function setPolygonOffset(polygonOffset, factor, units) { + if (polygonOffset) { + enable(gl.POLYGON_OFFSET_FILL); + if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) { + gl.polygonOffset(factor, units); + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + } + } else { + disable(gl.POLYGON_OFFSET_FILL); + } + } + function setScissorTest(scissorTest) { + if (scissorTest) { + enable(gl.SCISSOR_TEST); + } else { + disable(gl.SCISSOR_TEST); + } + } + function activeTexture(webglSlot) { + if (webglSlot === undefined) + webglSlot = gl.TEXTURE0 + maxTextures - 1; + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + } + function bindTexture(webglType, webglTexture, webglSlot) { + if (webglSlot === undefined) { + if (currentTextureSlot === null) { + webglSlot = gl.TEXTURE0 + maxTextures - 1; + } else { + webglSlot = currentTextureSlot; + } + } + let boundTexture = currentBoundTextures[webglSlot]; + if (boundTexture === undefined) { + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[webglSlot] = boundTexture; + } + if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) { + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]); + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + } + } + function unbindTexture() { + const boundTexture = currentBoundTextures[currentTextureSlot]; + if (boundTexture !== undefined && boundTexture.type !== undefined) { + gl.bindTexture(boundTexture.type, null); + boundTexture.type = undefined; + boundTexture.texture = undefined; + } + } + function compressedTexImage2D() { + try { + gl.compressedTexImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexImage3D() { + try { + gl.compressedTexImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage2D() { + try { + gl.texSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage3D() { + try { + gl.texSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage2D() { + try { + gl.compressedTexSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage3D() { + try { + gl.compressedTexSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage2D() { + try { + gl.texStorage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage3D() { + try { + gl.texStorage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage2D() { + try { + gl.texImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage3D() { + try { + gl.texImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function scissor(scissor2) { + if (currentScissor.equals(scissor2) === false) { + gl.scissor(scissor2.x, scissor2.y, scissor2.z, scissor2.w); + currentScissor.copy(scissor2); + } + } + function viewport(viewport2) { + if (currentViewport.equals(viewport2) === false) { + gl.viewport(viewport2.x, viewport2.y, viewport2.z, viewport2.w); + currentViewport.copy(viewport2); + } + } + function updateUBOMapping(uniformsGroup, program) { + let mapping = uboProgramMap.get(program); + if (mapping === undefined) { + mapping = new WeakMap; + uboProgramMap.set(program, mapping); + } + let blockIndex = mapping.get(uniformsGroup); + if (blockIndex === undefined) { + blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name); + mapping.set(uniformsGroup, blockIndex); + } + } + function uniformBlockBinding(uniformsGroup, program) { + const mapping = uboProgramMap.get(program); + const blockIndex = mapping.get(uniformsGroup); + if (uboBindings.get(program) !== blockIndex) { + gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex); + uboBindings.set(program, blockIndex); + } + } + function reset() { + gl.disable(gl.BLEND); + gl.disable(gl.CULL_FACE); + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.POLYGON_OFFSET_FILL); + gl.disable(gl.SCISSOR_TEST); + gl.disable(gl.STENCIL_TEST); + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ZERO); + gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO); + gl.blendColor(0, 0, 0, 0); + gl.colorMask(true, true, true, true); + gl.clearColor(0, 0, 0, 0); + gl.depthMask(true); + gl.depthFunc(gl.LESS); + depthBuffer.setReversed(false); + gl.clearDepth(1); + gl.stencilMask(4294967295); + gl.stencilFunc(gl.ALWAYS, 0, 4294967295); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + gl.clearStencil(0); + gl.cullFace(gl.BACK); + gl.frontFace(gl.CCW); + gl.polygonOffset(0, 0); + gl.activeTexture(gl.TEXTURE0); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); + gl.useProgram(null); + gl.lineWidth(1); + gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); + gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); + enabledCapabilities = {}; + currentTextureSlot = null; + currentBoundTextures = {}; + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap; + defaultDrawbuffers = []; + currentProgram = null; + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor = new Color2(0, 0, 0); + currentBlendAlpha = 0; + currentPremultipledAlpha = false; + currentFlipSided = null; + currentCullFace = null; + currentLineWidth = null; + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height); + currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height); + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + } + return { + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + enable, + disable, + bindFramebuffer, + drawBuffers, + useProgram, + setBlending, + setMaterial, + setFlipSided, + setCullFace, + setLineWidth, + setPolygonOffset, + setScissorTest, + activeTexture, + bindTexture, + unbindTexture, + compressedTexImage2D, + compressedTexImage3D, + texImage2D, + texImage3D, + updateUBOMapping, + uniformBlockBinding, + texStorage2D, + texStorage3D, + texSubImage2D, + texSubImage3D, + compressedTexSubImage2D, + compressedTexSubImage3D, + scissor, + viewport, + reset + }; + } + function WebGLTextures2(_gl, extensions, state, properties, capabilities, utils, info) { + const multisampledRTTExt = extensions.has("WEBGL_multisampled_render_to_texture") ? extensions.get("WEBGL_multisampled_render_to_texture") : null; + const supportsInvalidateFramebuffer = typeof navigator === "undefined" ? false : /OculusBrowser/g.test(navigator.userAgent); + const _imageDimensions = new Vector22; + const _videoTextures = new WeakMap; + let _canvas3; + const _sources = new WeakMap; + let useOffscreenCanvas = false; + try { + useOffscreenCanvas = typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null; + } catch (err) { + } + function createCanvas(width2, height2) { + return useOffscreenCanvas ? new OffscreenCanvas(width2, height2) : createElementNS2("canvas"); + } + function resizeImage(image, needsNewCanvas, maxSize) { + let scale2 = 1; + const dimensions = getDimensions(image); + if (dimensions.width > maxSize || dimensions.height > maxSize) { + scale2 = maxSize / Math.max(dimensions.width, dimensions.height); + } + if (scale2 < 1) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + const width2 = Math.floor(scale2 * dimensions.width); + const height2 = Math.floor(scale2 * dimensions.height); + if (_canvas3 === undefined) + _canvas3 = createCanvas(width2, height2); + const canvas = needsNewCanvas ? createCanvas(width2, height2) : _canvas3; + canvas.width = width2; + canvas.height = height2; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, width2, height2); + console.warn("THREE.WebGLRenderer: Texture has been resized from (" + dimensions.width + "x" + dimensions.height + ") to (" + width2 + "x" + height2 + ")."); + return canvas; + } else { + if ("data" in image) { + console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + dimensions.width + "x" + dimensions.height + ")."); + } + return image; + } + } + return image; + } + function textureNeedsGenerateMipmaps(texture) { + return texture.generateMipmaps; + } + function generateMipmap(target) { + _gl.generateMipmap(target); + } + function getTargetType(texture) { + if (texture.isWebGLCubeRenderTarget) + return _gl.TEXTURE_CUBE_MAP; + if (texture.isWebGL3DRenderTarget) + return _gl.TEXTURE_3D; + if (texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture) + return _gl.TEXTURE_2D_ARRAY; + return _gl.TEXTURE_2D; + } + function getInternalFormat(internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false) { + if (internalFormatName !== null) { + if (_gl[internalFormatName] !== undefined) + return _gl[internalFormatName]; + console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + internalFormatName + "'"); + } + let internalFormat = glFormat; + if (glFormat === _gl.RED) { + if (glType === _gl.FLOAT) + internalFormat = _gl.R32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.R16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.R8; + } + if (glFormat === _gl.RED_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.R8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.R16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.R32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.R8I; + if (glType === _gl.SHORT) + internalFormat = _gl.R16I; + if (glType === _gl.INT) + internalFormat = _gl.R32I; + } + if (glFormat === _gl.RG) { + if (glType === _gl.FLOAT) + internalFormat = _gl.RG32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.RG16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RG8; + } + if (glFormat === _gl.RG_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RG8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RG16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RG32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RG8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RG16I; + if (glType === _gl.INT) + internalFormat = _gl.RG32I; + } + if (glFormat === _gl.RGB_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RGB8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RGB16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RGB32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RGB8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RGB16I; + if (glType === _gl.INT) + internalFormat = _gl.RGB32I; + } + if (glFormat === _gl.RGBA_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RGBA8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RGBA16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RGBA32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RGBA8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RGBA16I; + if (glType === _gl.INT) + internalFormat = _gl.RGBA32I; + } + if (glFormat === _gl.RGB) { + if (glType === _gl.UNSIGNED_INT_5_9_9_9_REV) + internalFormat = _gl.RGB9_E5; + } + if (glFormat === _gl.RGBA) { + const transfer = forceLinearTransfer ? LinearTransfer2 : ColorManagement2.getTransfer(colorSpace); + if (glType === _gl.FLOAT) + internalFormat = _gl.RGBA32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.RGBA16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = transfer === SRGBTransfer2 ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) + internalFormat = _gl.RGBA4; + if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) + internalFormat = _gl.RGB5_A1; + } + if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) { + extensions.get("EXT_color_buffer_float"); + } + return internalFormat; + } + function getInternalDepthFormat(useStencil, depthType) { + let glInternalFormat; + if (useStencil) { + if (depthType === null || depthType === UnsignedIntType2 || depthType === UnsignedInt248Type2) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + } else if (depthType === FloatType2) { + glInternalFormat = _gl.DEPTH32F_STENCIL8; + } else if (depthType === UnsignedShortType2) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment."); + } + } else { + if (depthType === null || depthType === UnsignedIntType2 || depthType === UnsignedInt248Type2) { + glInternalFormat = _gl.DEPTH_COMPONENT24; + } else if (depthType === FloatType2) { + glInternalFormat = _gl.DEPTH_COMPONENT32F; + } else if (depthType === UnsignedShortType2) { + glInternalFormat = _gl.DEPTH_COMPONENT16; + } + } + return glInternalFormat; + } + function getMipLevels(texture, image) { + if (textureNeedsGenerateMipmaps(texture) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter2 && texture.minFilter !== LinearFilter2) { + return Math.log2(Math.max(image.width, image.height)) + 1; + } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) { + return texture.mipmaps.length; + } else if (texture.isCompressedTexture && Array.isArray(texture.image)) { + return image.mipmaps.length; + } else { + return 1; + } + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + deallocateTexture(texture); + if (texture.isVideoTexture) { + _videoTextures.delete(texture); + } + } + function onRenderTargetDispose(event) { + const renderTarget = event.target; + renderTarget.removeEventListener("dispose", onRenderTargetDispose); + deallocateRenderTarget(renderTarget); + } + function deallocateTexture(texture) { + const textureProperties = properties.get(texture); + if (textureProperties.__webglInit === undefined) + return; + const source = texture.source; + const webglTextures = _sources.get(source); + if (webglTextures) { + const webglTexture = webglTextures[textureProperties.__cacheKey]; + webglTexture.usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + if (Object.keys(webglTextures).length === 0) { + _sources.delete(source); + } + } + properties.remove(texture); + } + function deleteTexture(texture) { + const textureProperties = properties.get(texture); + _gl.deleteTexture(textureProperties.__webglTexture); + const source = texture.source; + const webglTextures = _sources.get(source); + delete webglTextures[textureProperties.__cacheKey]; + info.memory.textures--; + } + function deallocateRenderTarget(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTarget.depthTexture) { + renderTarget.depthTexture.dispose(); + properties.remove(renderTarget.depthTexture); + } + if (renderTarget.isWebGLCubeRenderTarget) { + for (let i = 0;i < 6; i++) { + if (Array.isArray(renderTargetProperties.__webglFramebuffer[i])) { + for (let level = 0;level < renderTargetProperties.__webglFramebuffer[i].length; level++) + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i][level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]); + } + if (renderTargetProperties.__webglDepthbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]); + } + } else { + if (Array.isArray(renderTargetProperties.__webglFramebuffer)) { + for (let level = 0;level < renderTargetProperties.__webglFramebuffer.length; level++) + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer); + } + if (renderTargetProperties.__webglDepthbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer); + if (renderTargetProperties.__webglMultisampledFramebuffer) + _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer); + if (renderTargetProperties.__webglColorRenderbuffer) { + for (let i = 0;i < renderTargetProperties.__webglColorRenderbuffer.length; i++) { + if (renderTargetProperties.__webglColorRenderbuffer[i]) + _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]); + } + } + if (renderTargetProperties.__webglDepthRenderbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer); + } + const textures = renderTarget.textures; + for (let i = 0, il = textures.length;i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture) { + _gl.deleteTexture(attachmentProperties.__webglTexture); + info.memory.textures--; + } + properties.remove(textures[i]); + } + properties.remove(renderTarget); + } + let textureUnits = 0; + function resetTextureUnits() { + textureUnits = 0; + } + function allocateTextureUnit() { + const textureUnit = textureUnits; + if (textureUnit >= capabilities.maxTextures) { + console.warn("THREE.WebGLTextures: Trying to use " + textureUnit + " texture units while this GPU supports only " + capabilities.maxTextures); + } + textureUnits += 1; + return textureUnit; + } + function getTextureCacheKey(texture) { + const array = []; + array.push(texture.wrapS); + array.push(texture.wrapT); + array.push(texture.wrapR || 0); + array.push(texture.magFilter); + array.push(texture.minFilter); + array.push(texture.anisotropy); + array.push(texture.internalFormat); + array.push(texture.format); + array.push(texture.type); + array.push(texture.generateMipmaps); + array.push(texture.premultiplyAlpha); + array.push(texture.flipY); + array.push(texture.unpackAlignment); + array.push(texture.colorSpace); + return array.join(); + } + function setTexture2D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isVideoTexture) + updateVideoTexture(texture); + if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { + const image = texture.image; + if (image === null) { + console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found."); + } else if (image.complete === false) { + console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete"); + } else { + uploadTexture(textureProperties, texture, slot); + return; + } + } + state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture2DArray(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture3D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTextureCube(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadCubeTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + const wrappingToGL = { + [RepeatWrapping2]: _gl.REPEAT, + [ClampToEdgeWrapping2]: _gl.CLAMP_TO_EDGE, + [MirroredRepeatWrapping2]: _gl.MIRRORED_REPEAT + }; + const filterToGL = { + [NearestFilter2]: _gl.NEAREST, + [NearestMipmapNearestFilter2]: _gl.NEAREST_MIPMAP_NEAREST, + [NearestMipmapLinearFilter2]: _gl.NEAREST_MIPMAP_LINEAR, + [LinearFilter2]: _gl.LINEAR, + [LinearMipmapNearestFilter2]: _gl.LINEAR_MIPMAP_NEAREST, + [LinearMipmapLinearFilter2]: _gl.LINEAR_MIPMAP_LINEAR + }; + const compareToGL = { + [NeverCompare2]: _gl.NEVER, + [AlwaysCompare2]: _gl.ALWAYS, + [LessCompare2]: _gl.LESS, + [LessEqualCompare2]: _gl.LEQUAL, + [EqualCompare2]: _gl.EQUAL, + [GreaterEqualCompare2]: _gl.GEQUAL, + [GreaterCompare2]: _gl.GREATER, + [NotEqualCompare2]: _gl.NOTEQUAL + }; + function setTextureParameters(textureType, texture) { + if (texture.type === FloatType2 && extensions.has("OES_texture_float_linear") === false && (texture.magFilter === LinearFilter2 || texture.magFilter === LinearMipmapNearestFilter2 || texture.magFilter === NearestMipmapLinearFilter2 || texture.magFilter === LinearMipmapLinearFilter2 || texture.minFilter === LinearFilter2 || texture.minFilter === LinearMipmapNearestFilter2 || texture.minFilter === NearestMipmapLinearFilter2 || texture.minFilter === LinearMipmapLinearFilter2)) { + console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."); + } + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]); + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]); + if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) { + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]); + } + _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]); + _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]); + if (texture.compareFunction) { + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE); + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[texture.compareFunction]); + } + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + if (texture.magFilter === NearestFilter2) + return; + if (texture.minFilter !== NearestMipmapLinearFilter2 && texture.minFilter !== LinearMipmapLinearFilter2) + return; + if (texture.type === FloatType2 && extensions.has("OES_texture_float_linear") === false) + return; + if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy())); + properties.get(texture).__currentAnisotropy = texture.anisotropy; + } + } + } + function initTexture(textureProperties, texture) { + let forceUpload = false; + if (textureProperties.__webglInit === undefined) { + textureProperties.__webglInit = true; + texture.addEventListener("dispose", onTextureDispose); + } + const source = texture.source; + let webglTextures = _sources.get(source); + if (webglTextures === undefined) { + webglTextures = {}; + _sources.set(source, webglTextures); + } + const textureCacheKey = getTextureCacheKey(texture); + if (textureCacheKey !== textureProperties.__cacheKey) { + if (webglTextures[textureCacheKey] === undefined) { + webglTextures[textureCacheKey] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + info.memory.textures++; + forceUpload = true; + } + webglTextures[textureCacheKey].usedTimes++; + const webglTexture = webglTextures[textureProperties.__cacheKey]; + if (webglTexture !== undefined) { + webglTextures[textureProperties.__cacheKey].usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + } + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[textureCacheKey].texture; + } + return forceUpload; + } + function uploadTexture(textureProperties, texture, slot) { + let textureType = _gl.TEXTURE_2D; + if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) + textureType = _gl.TEXTURE_2D_ARRAY; + if (texture.isData3DTexture) + textureType = _gl.TEXTURE_3D; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement2.getPrimaries(ColorManagement2.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace2 ? null : ColorManagement2.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace2 || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + let image = resizeImage(texture.image, false, capabilities.maxTextureSize); + image = verifyColorSpace(texture, image); + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + let glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture); + setTextureParameters(textureType, texture); + let mipmap; + const mipmaps = texture.mipmaps; + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; + const dataReady = source.dataReady; + const levels = getMipLevels(texture, image); + if (texture.isDepthTexture) { + glInternalFormat = getInternalDepthFormat(texture.format === DepthStencilFormat2, texture.type); + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height); + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null); + } + } + } else if (texture.isDataTexture) { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data); + } + } + } else if (texture.isCompressedTexture) { + if (texture.isCompressedArrayTexture) { + if (useTexStorage && allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat2) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength2(mipmap.width, mipmap.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = mipmap.data.subarray(layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT, (layerIndex + 1) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT); + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData); + } + texture.clearLayerUpdates(); + } else { + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data); + } + } + } else { + state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data); + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data); + } + } + } + } else { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat2) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else if (texture.isDataArrayTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength2(image.width, image.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = image.data.subarray(layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT, (layerIndex + 1) * layerByteLength / image.data.BYTES_PER_ELEMENT); + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData); + } + texture.clearLayerUpdates(); + } else { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isData3DTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } else { + state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isFramebufferTexture) { + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } else { + let { width: width2, height: height2 } = image; + for (let i = 0;i < levels; i++) { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width2, height2, 0, glFormat, glType, null); + width2 >>= 1; + height2 >>= 1; + } + } + } + } else { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + const dimensions = getDimensions(mipmaps[0]); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + const dimensions = getDimensions(image); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image); + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(textureType); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) + texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function uploadCubeTexture(textureProperties, texture, slot) { + if (texture.image.length !== 6) + return; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement2.getPrimaries(ColorManagement2.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace2 ? null : ColorManagement2.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace2 || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture; + const isDataTexture = texture.image[0] && texture.image[0].isDataTexture; + const cubeImage = []; + for (let i = 0;i < 6; i++) { + if (!isCompressed && !isDataTexture) { + cubeImage[i] = resizeImage(texture.image[i], true, capabilities.maxCubemapSize); + } else { + cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i]; + } + cubeImage[i] = verifyColorSpace(texture, cubeImage[i]); + } + const image = cubeImage[0], glFormat = utils.convert(texture.format, texture.colorSpace), glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; + const dataReady = source.dataReady; + let levels = getMipLevels(texture, image); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + let mipmaps; + if (isCompressed) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height); + } + for (let i = 0;i < 6; i++) { + mipmaps = cubeImage[i].mipmaps; + for (let j2 = 0;j2 < mipmaps.length; j2++) { + const mipmap = mipmaps[j2]; + if (texture.format !== RGBAFormat2) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else { + mipmaps = texture.mipmaps; + if (useTexStorage && allocateMemory) { + if (mipmaps.length > 0) + levels++; + const dimensions = getDimensions(cubeImage[0]); + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0;i < 6; i++) { + if (isDataTexture) { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data); + } + for (let j2 = 0;j2 < mipmaps.length; j2++) { + const mipmap = mipmaps[j2]; + const mipmapImage = mipmap.image[i].image; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2 + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2 + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data); + } + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]); + } + for (let j2 = 0;j2 < mipmaps.length; j2++) { + const mipmap = mipmaps[j2]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2 + 1, 0, 0, glFormat, glType, mipmap.image[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2 + 1, glInternalFormat, glFormat, glType, mipmap.image[i]); + } + } + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) + texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget, level) { + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + textureProperties.__renderTarget = renderTarget; + if (!renderTargetProperties.__hasExternalTextures) { + const width2 = Math.max(1, renderTarget.width >> level); + const height2 = Math.max(1, renderTarget.height >> level); + if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) { + state.texImage3D(textureTarget, level, glInternalFormat, width2, height2, renderTarget.depth, 0, glFormat, glType, null); + } else { + state.texImage2D(textureTarget, level, glInternalFormat, width2, height2, 0, glFormat, glType, null); + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples(renderTarget)); + } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) { + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null; + const glInternalFormat = getInternalDepthFormat(renderTarget.stencilBuffer, depthType); + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const samples = getRenderTargetSamples(renderTarget); + const isUseMultisampledRTT = useMultisampledRTT(renderTarget); + if (isUseMultisampledRTT) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (isMultisample) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } else { + const textures = renderTarget.textures; + for (let i = 0;i < textures.length; i++) { + const texture = textures[i]; + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const samples = getRenderTargetSamples(renderTarget); + if (isMultisample && useMultisampledRTT(renderTarget) === false) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + } + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + } + function setupDepthTexture(framebuffer, renderTarget) { + const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget; + if (isCube) + throw new Error("Depth Texture with cube render targets is not supported"); + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) { + throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); + } + const textureProperties = properties.get(renderTarget.depthTexture); + textureProperties.__renderTarget = renderTarget; + if (!textureProperties.__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) { + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + } + setTexture2D(renderTarget.depthTexture, 0); + const webglDepthTexture = textureProperties.__webglTexture; + const samples = getRenderTargetSamples(renderTarget); + if (renderTarget.depthTexture.format === DepthFormat2) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else if (renderTarget.depthTexture.format === DepthStencilFormat2) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else { + throw new Error("Unknown depthTexture format"); + } + } + function setupDepthRenderbuffer(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + if (renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__depthDisposeCallback) { + renderTargetProperties.__depthDisposeCallback(); + } + if (depthTexture) { + const disposeEvent = () => { + delete renderTargetProperties.__boundDepthTexture; + delete renderTargetProperties.__depthDisposeCallback; + depthTexture.removeEventListener("dispose", disposeEvent); + }; + depthTexture.addEventListener("dispose", disposeEvent); + renderTargetProperties.__depthDisposeCallback = disposeEvent; + } + renderTargetProperties.__boundDepthTexture = depthTexture; + } + if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) { + if (isCube) + throw new Error("target.depthTexture not supported in Cube render targets"); + setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget); + } else { + if (isCube) { + renderTargetProperties.__webglDepthbuffer = []; + for (let i = 0;i < 6; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]); + if (renderTargetProperties.__webglDepthbuffer[i] === undefined) { + renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer[i]; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } else { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + if (renderTargetProperties.__webglDepthbuffer === undefined) { + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function rebindTextures(renderTarget, colorTexture, depthTexture) { + const renderTargetProperties = properties.get(renderTarget); + if (colorTexture !== undefined) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0); + } + if (depthTexture !== undefined) { + setupDepthRenderbuffer(renderTarget); + } + } + function setupRenderTarget(renderTarget) { + const texture = renderTarget.texture; + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + renderTarget.addEventListener("dispose", onRenderTargetDispose); + const textures = renderTarget.textures; + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + const isMultipleRenderTargets = textures.length > 1; + if (!isMultipleRenderTargets) { + if (textureProperties.__webglTexture === undefined) { + textureProperties.__webglTexture = _gl.createTexture(); + } + textureProperties.__version = texture.version; + info.memory.textures++; + } + if (isCube) { + renderTargetProperties.__webglFramebuffer = []; + for (let i = 0;i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer[i] = []; + for (let level = 0;level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[i][level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer(); + } + } + } else { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer = []; + for (let level = 0;level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + } + if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length;i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture === undefined) { + attachmentProperties.__webglTexture = _gl.createTexture(); + info.memory.textures++; + } + } + } + if (renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + for (let i = 0;i < textures.length; i++) { + const texture2 = textures[i]; + renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer(); + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const glFormat = utils.convert(texture2.format, texture2.colorSpace); + const glType = utils.convert(texture2.type); + const glInternalFormat = getInternalFormat(texture2.internalFormat, glFormat, glType, texture2.colorSpace, renderTarget.isXRRenderTarget === true); + const samples = getRenderTargetSamples(renderTarget); + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + if (renderTarget.depthBuffer) { + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + } + if (isCube) { + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + for (let i = 0;i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0;level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i][level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0); + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + state.unbindTexture(); + } else if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length;i < il; i++) { + const attachment = textures[i]; + const attachmentProperties = properties.get(attachment); + state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_2D, attachment); + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0); + if (textureNeedsGenerateMipmaps(attachment)) { + generateMipmap(_gl.TEXTURE_2D); + } + } + state.unbindTexture(); + } else { + let glTextureType = _gl.TEXTURE_2D; + if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + } + state.bindTexture(glTextureType, textureProperties.__webglTexture); + setTextureParameters(glTextureType, texture); + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0;level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0); + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(glTextureType); + } + state.unbindTexture(); + } + if (renderTarget.depthBuffer) { + setupDepthRenderbuffer(renderTarget); + } + } + function updateRenderTargetMipmap(renderTarget) { + const textures = renderTarget.textures; + for (let i = 0, il = textures.length;i < il; i++) { + const texture = textures[i]; + if (textureNeedsGenerateMipmaps(texture)) { + const targetType = getTargetType(renderTarget); + const webglTexture = properties.get(texture).__webglTexture; + state.bindTexture(targetType, webglTexture); + generateMipmap(targetType); + state.unbindTexture(); + } + } + } + const invalidationArrayRead = []; + const invalidationArrayDraw = []; + function updateMultisampleRenderTarget(renderTarget) { + if (renderTarget.samples > 0) { + if (useMultisampledRTT(renderTarget) === false) { + const textures = renderTarget.textures; + const width2 = renderTarget.width; + const height2 = renderTarget.height; + let mask2 = _gl.COLOR_BUFFER_BIT; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get(renderTarget); + const isMultipleRenderTargets = textures.length > 1; + if (isMultipleRenderTargets) { + for (let i = 0;i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null); + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + for (let i = 0;i < textures.length; i++) { + if (renderTarget.resolveDepthBuffer) { + if (renderTarget.depthBuffer) + mask2 |= _gl.DEPTH_BUFFER_BIT; + if (renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer) + mask2 |= _gl.STENCIL_BUFFER_BIT; + } + if (isMultipleRenderTargets) { + _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0); + } + _gl.blitFramebuffer(0, 0, width2, height2, 0, 0, width2, height2, mask2, _gl.NEAREST); + if (supportsInvalidateFramebuffer === true) { + invalidationArrayRead.length = 0; + invalidationArrayDraw.length = 0; + invalidationArrayRead.push(_gl.COLOR_ATTACHMENT0 + i); + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false) { + invalidationArrayRead.push(depthStyle); + invalidationArrayDraw.push(depthStyle); + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, invalidationArrayDraw); + } + _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArrayRead); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + if (isMultipleRenderTargets) { + for (let i = 0;i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0); + } + } + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + } else { + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer) { + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]); + } + } + } + } + function getRenderTargetSamples(renderTarget) { + return Math.min(capabilities.maxSamples, renderTarget.samples); + } + function useMultisampledRTT(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + return renderTarget.samples > 0 && extensions.has("WEBGL_multisampled_render_to_texture") === true && renderTargetProperties.__useRenderToTexture !== false; + } + function updateVideoTexture(texture) { + const frame = info.render.frame; + if (_videoTextures.get(texture) !== frame) { + _videoTextures.set(texture, frame); + texture.update(); + } + } + function verifyColorSpace(texture, image) { + const colorSpace = texture.colorSpace; + const format = texture.format; + const type = texture.type; + if (texture.isCompressedTexture === true || texture.isVideoTexture === true) + return image; + if (colorSpace !== LinearSRGBColorSpace2 && colorSpace !== NoColorSpace2) { + if (ColorManagement2.getTransfer(colorSpace) === SRGBTransfer2) { + if (format !== RGBAFormat2 || type !== UnsignedByteType2) { + console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."); + } + } else { + console.error("THREE.WebGLTextures: Unsupported texture color space:", colorSpace); + } + } + return image; + } + function getDimensions(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement) { + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + } else if (typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + } else { + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + } + return _imageDimensions; + } + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; + } + function WebGLUtils2(gl, extensions) { + function convert(p, colorSpace = NoColorSpace2) { + let extension; + const transfer = ColorManagement2.getTransfer(colorSpace); + if (p === UnsignedByteType2) + return gl.UNSIGNED_BYTE; + if (p === UnsignedShort4444Type2) + return gl.UNSIGNED_SHORT_4_4_4_4; + if (p === UnsignedShort5551Type2) + return gl.UNSIGNED_SHORT_5_5_5_1; + if (p === UnsignedInt5999Type2) + return gl.UNSIGNED_INT_5_9_9_9_REV; + if (p === ByteType2) + return gl.BYTE; + if (p === ShortType2) + return gl.SHORT; + if (p === UnsignedShortType2) + return gl.UNSIGNED_SHORT; + if (p === IntType2) + return gl.INT; + if (p === UnsignedIntType2) + return gl.UNSIGNED_INT; + if (p === FloatType2) + return gl.FLOAT; + if (p === HalfFloatType2) + return gl.HALF_FLOAT; + if (p === AlphaFormat2) + return gl.ALPHA; + if (p === RGBFormat2) + return gl.RGB; + if (p === RGBAFormat2) + return gl.RGBA; + if (p === LuminanceFormat2) + return gl.LUMINANCE; + if (p === LuminanceAlphaFormat2) + return gl.LUMINANCE_ALPHA; + if (p === DepthFormat2) + return gl.DEPTH_COMPONENT; + if (p === DepthStencilFormat2) + return gl.DEPTH_STENCIL; + if (p === RedFormat2) + return gl.RED; + if (p === RedIntegerFormat2) + return gl.RED_INTEGER; + if (p === RGFormat2) + return gl.RG; + if (p === RGIntegerFormat2) + return gl.RG_INTEGER; + if (p === RGBAIntegerFormat2) + return gl.RGBA_INTEGER; + if (p === RGB_S3TC_DXT1_Format2 || p === RGBA_S3TC_DXT1_Format2 || p === RGBA_S3TC_DXT3_Format2 || p === RGBA_S3TC_DXT5_Format2) { + if (transfer === SRGBTransfer2) { + extension = extensions.get("WEBGL_compressed_texture_s3tc_srgb"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format2) + return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format2) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format2) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format2) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + } else { + return null; + } + } else { + extension = extensions.get("WEBGL_compressed_texture_s3tc"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format2) + return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format2) + return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format2) + return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format2) + return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + } else { + return null; + } + } + } + if (p === RGB_PVRTC_4BPPV1_Format2 || p === RGB_PVRTC_2BPPV1_Format2 || p === RGBA_PVRTC_4BPPV1_Format2 || p === RGBA_PVRTC_2BPPV1_Format2) { + extension = extensions.get("WEBGL_compressed_texture_pvrtc"); + if (extension !== null) { + if (p === RGB_PVRTC_4BPPV1_Format2) + return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if (p === RGB_PVRTC_2BPPV1_Format2) + return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if (p === RGBA_PVRTC_4BPPV1_Format2) + return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if (p === RGBA_PVRTC_2BPPV1_Format2) + return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + } else { + return null; + } + } + if (p === RGB_ETC1_Format2 || p === RGB_ETC2_Format2 || p === RGBA_ETC2_EAC_Format2) { + extension = extensions.get("WEBGL_compressed_texture_etc"); + if (extension !== null) { + if (p === RGB_ETC1_Format2 || p === RGB_ETC2_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if (p === RGBA_ETC2_EAC_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + } else { + return null; + } + } + if (p === RGBA_ASTC_4x4_Format2 || p === RGBA_ASTC_5x4_Format2 || p === RGBA_ASTC_5x5_Format2 || p === RGBA_ASTC_6x5_Format2 || p === RGBA_ASTC_6x6_Format2 || p === RGBA_ASTC_8x5_Format2 || p === RGBA_ASTC_8x6_Format2 || p === RGBA_ASTC_8x8_Format2 || p === RGBA_ASTC_10x5_Format2 || p === RGBA_ASTC_10x6_Format2 || p === RGBA_ASTC_10x8_Format2 || p === RGBA_ASTC_10x10_Format2 || p === RGBA_ASTC_12x10_Format2 || p === RGBA_ASTC_12x12_Format2) { + extension = extensions.get("WEBGL_compressed_texture_astc"); + if (extension !== null) { + if (p === RGBA_ASTC_4x4_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if (p === RGBA_ASTC_5x4_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if (p === RGBA_ASTC_5x5_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if (p === RGBA_ASTC_6x5_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if (p === RGBA_ASTC_6x6_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if (p === RGBA_ASTC_8x5_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if (p === RGBA_ASTC_8x6_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if (p === RGBA_ASTC_8x8_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if (p === RGBA_ASTC_10x5_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if (p === RGBA_ASTC_10x6_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if (p === RGBA_ASTC_10x8_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if (p === RGBA_ASTC_10x10_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if (p === RGBA_ASTC_12x10_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if (p === RGBA_ASTC_12x12_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + } else { + return null; + } + } + if (p === RGBA_BPTC_Format2 || p === RGB_BPTC_SIGNED_Format2 || p === RGB_BPTC_UNSIGNED_Format2) { + extension = extensions.get("EXT_texture_compression_bptc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + if (p === RGB_BPTC_SIGNED_Format2) + return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; + if (p === RGB_BPTC_UNSIGNED_Format2) + return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; + } else { + return null; + } + } + if (p === RED_RGTC1_Format2 || p === SIGNED_RED_RGTC1_Format2 || p === RED_GREEN_RGTC2_Format2 || p === SIGNED_RED_GREEN_RGTC2_Format2) { + extension = extensions.get("EXT_texture_compression_rgtc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format2) + return extension.COMPRESSED_RED_RGTC1_EXT; + if (p === SIGNED_RED_RGTC1_Format2) + return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if (p === RED_GREEN_RGTC2_Format2) + return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if (p === SIGNED_RED_GREEN_RGTC2_Format2) + return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + } else { + return null; + } + } + if (p === UnsignedInt248Type2) + return gl.UNSIGNED_INT_24_8; + return gl[p] !== undefined ? gl[p] : null; + } + return { convert }; + } + var _occlusion_vertex2 = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; + var _occlusion_fragment2 = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; + + class WebXRDepthSensing2 { + constructor() { + this.texture = null; + this.mesh = null; + this.depthNear = 0; + this.depthFar = 0; + } + init(renderer2, depthData, renderState) { + if (this.texture === null) { + const texture = new Texture2; + const texProps = renderer2.properties.get(texture); + texProps.__webglTexture = depthData.texture; + if (depthData.depthNear !== renderState.depthNear || depthData.depthFar !== renderState.depthFar) { + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + } + this.texture = texture; + } + } + getMesh(cameraXR) { + if (this.texture !== null) { + if (this.mesh === null) { + const viewport = cameraXR.cameras[0].viewport; + const material = new ShaderMaterial2({ + vertexShader: _occlusion_vertex2, + fragmentShader: _occlusion_fragment2, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + }); + this.mesh = new Mesh2(new PlaneGeometry3(20, 20), material); + } + } + return this.mesh; + } + reset() { + this.texture = null; + this.mesh = null; + } + getDepthTexture() { + return this.texture; + } + } + + class WebXRManager2 extends EventDispatcher2 { + constructor(renderer2, gl) { + super(); + const scope = this; + let session = null; + let framebufferScaleFactor = 1; + let referenceSpace = null; + let referenceSpaceType = "local-floor"; + let foveation = 1; + let customReferenceSpace = null; + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const depthSensing = new WebXRDepthSensing2; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + const controllers = []; + const controllerInputSources = []; + const currentSize = new Vector22; + let currentPixelRatio = null; + const cameraL = new PerspectiveCamera2; + cameraL.viewport = new Vector42; + const cameraR = new PerspectiveCamera2; + cameraR.viewport = new Vector42; + const cameras = [cameraL, cameraR]; + const cameraXR = new ArrayCamera2; + let _currentDepthNear = null; + let _currentDepthFar = null; + this.cameraAutoUpdate = true; + this.enabled = false; + this.isPresenting = false; + this.getController = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController2; + controllers[index2] = controller; + } + return controller.getTargetRaySpace(); + }; + this.getControllerGrip = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController2; + controllers[index2] = controller; + } + return controller.getGripSpace(); + }; + this.getHand = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController2; + controllers[index2] = controller; + } + return controller.getHandSpace(); + }; + function onSessionEvent(event) { + const controllerIndex = controllerInputSources.indexOf(event.inputSource); + if (controllerIndex === -1) { + return; + } + const controller = controllers[controllerIndex]; + if (controller !== undefined) { + controller.update(event.inputSource, event.frame, customReferenceSpace || referenceSpace); + controller.dispatchEvent({ type: event.type, data: event.inputSource }); + } + } + function onSessionEnd() { + session.removeEventListener("select", onSessionEvent); + session.removeEventListener("selectstart", onSessionEvent); + session.removeEventListener("selectend", onSessionEvent); + session.removeEventListener("squeeze", onSessionEvent); + session.removeEventListener("squeezestart", onSessionEvent); + session.removeEventListener("squeezeend", onSessionEvent); + session.removeEventListener("end", onSessionEnd); + session.removeEventListener("inputsourceschange", onInputSourcesChange); + for (let i = 0;i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + if (inputSource === null) + continue; + controllerInputSources[i] = null; + controllers[i].disconnect(inputSource); + } + _currentDepthNear = null; + _currentDepthFar = null; + depthSensing.reset(); + renderer2.setRenderTarget(initialRenderTarget); + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + animation.stop(); + scope.isPresenting = false; + renderer2.setPixelRatio(currentPixelRatio); + renderer2.setSize(currentSize.width, currentSize.height, false); + scope.dispatchEvent({ type: "sessionend" }); + } + this.setFramebufferScaleFactor = function(value2) { + framebufferScaleFactor = value2; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting."); + } + }; + this.setReferenceSpaceType = function(value2) { + referenceSpaceType = value2; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change reference space type while presenting."); + } + }; + this.getReferenceSpace = function() { + return customReferenceSpace || referenceSpace; + }; + this.setReferenceSpace = function(space) { + customReferenceSpace = space; + }; + this.getBaseLayer = function() { + return glProjLayer !== null ? glProjLayer : glBaseLayer; + }; + this.getBinding = function() { + return glBinding; + }; + this.getFrame = function() { + return xrFrame; + }; + this.getSession = function() { + return session; + }; + this.setSession = async function(value2) { + session = value2; + if (session !== null) { + initialRenderTarget = renderer2.getRenderTarget(); + session.addEventListener("select", onSessionEvent); + session.addEventListener("selectstart", onSessionEvent); + session.addEventListener("selectend", onSessionEvent); + session.addEventListener("squeeze", onSessionEvent); + session.addEventListener("squeezestart", onSessionEvent); + session.addEventListener("squeezeend", onSessionEvent); + session.addEventListener("end", onSessionEnd); + session.addEventListener("inputsourceschange", onInputSourcesChange); + if (attributes.xrCompatible !== true) { + await gl.makeXRCompatible(); + } + currentPixelRatio = renderer2.getPixelRatio(); + renderer2.getSize(currentSize); + const useLayers = typeof XRWebGLBinding !== "undefined" && "createProjectionLayer" in XRWebGLBinding.prototype; + if (!useLayers) { + const layerInit = { + antialias: attributes.antialias, + alpha: true, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor + }; + glBaseLayer = new XRWebGLLayer(session, gl, layerInit); + session.updateRenderState({ baseLayer: glBaseLayer }); + renderer2.setPixelRatio(1); + renderer2.setSize(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false); + newRenderTarget = new WebGLRenderTarget2(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, { + format: RGBAFormat2, + type: UnsignedByteType2, + colorSpace: renderer2.outputColorSpace, + stencilBuffer: attributes.stencil + }); + } else { + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + if (attributes.depth) { + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat2 : DepthFormat2; + depthType = attributes.stencil ? UnsignedInt248Type2 : UnsignedIntType2; + } + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + glBinding = new XRWebGLBinding(session, gl); + glProjLayer = glBinding.createProjectionLayer(projectionlayerInit); + session.updateRenderState({ layers: [glProjLayer] }); + renderer2.setPixelRatio(1); + renderer2.setSize(glProjLayer.textureWidth, glProjLayer.textureHeight, false); + newRenderTarget = new WebGLRenderTarget2(glProjLayer.textureWidth, glProjLayer.textureHeight, { + format: RGBAFormat2, + type: UnsignedByteType2, + depthTexture: new DepthTexture2(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat), + stencilBuffer: attributes.stencil, + colorSpace: renderer2.outputColorSpace, + samples: attributes.antialias ? 4 : 0, + resolveDepthBuffer: glProjLayer.ignoreDepthValues === false + }); + } + newRenderTarget.isXRRenderTarget = true; + this.setFoveation(foveation); + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace(referenceSpaceType); + animation.setContext(session); + animation.start(); + scope.isPresenting = true; + scope.dispatchEvent({ type: "sessionstart" }); + } + }; + this.getEnvironmentBlendMode = function() { + if (session !== null) { + return session.environmentBlendMode; + } + }; + this.getDepthTexture = function() { + return depthSensing.getDepthTexture(); + }; + function onInputSourcesChange(event) { + for (let i = 0;i < event.removed.length; i++) { + const inputSource = event.removed[i]; + const index2 = controllerInputSources.indexOf(inputSource); + if (index2 >= 0) { + controllerInputSources[index2] = null; + controllers[index2].disconnect(inputSource); + } + } + for (let i = 0;i < event.added.length; i++) { + const inputSource = event.added[i]; + let controllerIndex = controllerInputSources.indexOf(inputSource); + if (controllerIndex === -1) { + for (let i3 = 0;i3 < controllers.length; i3++) { + if (i3 >= controllerInputSources.length) { + controllerInputSources.push(inputSource); + controllerIndex = i3; + break; + } else if (controllerInputSources[i3] === null) { + controllerInputSources[i3] = inputSource; + controllerIndex = i3; + break; + } + } + if (controllerIndex === -1) + break; + } + const controller = controllers[controllerIndex]; + if (controller) { + controller.connect(inputSource); + } + } + } + const cameraLPos = new Vector32; + const cameraRPos = new Vector32; + function setProjectionFromUnion(camera, cameraL2, cameraR2) { + cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld); + cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld); + const ipd = cameraLPos.distanceTo(cameraRPos); + const projL = cameraL2.projectionMatrix.elements; + const projR = cameraR2.projectionMatrix.elements; + const near = projL[14] / (projL[10] - 1); + const far = projL[14] / (projL[10] + 1); + const topFov = (projL[9] + 1) / projL[5]; + const bottomFov = (projL[9] - 1) / projL[5]; + const leftFov = (projL[8] - 1) / projL[0]; + const rightFov = (projR[8] + 1) / projR[0]; + const left = near * leftFov; + const right = near * rightFov; + const zOffset = ipd / (-leftFov + rightFov); + const xOffset = zOffset * -leftFov; + cameraL2.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale); + camera.translateX(xOffset); + camera.translateZ(zOffset); + camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale); + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + if (projL[10] === -1) { + camera.projectionMatrix.copy(cameraL2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraL2.projectionMatrixInverse); + } else { + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + (ipd - xOffset); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + } + } + function updateCamera(camera, parent2) { + if (parent2 === null) { + camera.matrixWorld.copy(camera.matrix); + } else { + camera.matrixWorld.multiplyMatrices(parent2.matrixWorld, camera.matrix); + } + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + } + this.updateCamera = function(camera) { + if (session === null) + return; + let depthNear = camera.near; + let depthFar = camera.far; + if (depthSensing.texture !== null) { + if (depthSensing.depthNear > 0) + depthNear = depthSensing.depthNear; + if (depthSensing.depthFar > 0) + depthFar = depthSensing.depthFar; + } + cameraXR.near = cameraR.near = cameraL.near = depthNear; + cameraXR.far = cameraR.far = cameraL.far = depthFar; + if (_currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far) { + session.updateRenderState({ + depthNear: cameraXR.near, + depthFar: cameraXR.far + }); + _currentDepthNear = cameraXR.near; + _currentDepthFar = cameraXR.far; + } + cameraL.layers.mask = camera.layers.mask | 2; + cameraR.layers.mask = camera.layers.mask | 4; + cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask; + const parent2 = camera.parent; + const cameras2 = cameraXR.cameras; + updateCamera(cameraXR, parent2); + for (let i = 0;i < cameras2.length; i++) { + updateCamera(cameras2[i], parent2); + } + if (cameras2.length === 2) { + setProjectionFromUnion(cameraXR, cameraL, cameraR); + } else { + cameraXR.projectionMatrix.copy(cameraL.projectionMatrix); + } + updateUserCamera(camera, cameraXR, parent2); + }; + function updateUserCamera(camera, cameraXR2, parent2) { + if (parent2 === null) { + camera.matrix.copy(cameraXR2.matrixWorld); + } else { + camera.matrix.copy(parent2.matrixWorld); + camera.matrix.invert(); + camera.matrix.multiply(cameraXR2.matrixWorld); + } + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.updateMatrixWorld(true); + camera.projectionMatrix.copy(cameraXR2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraXR2.projectionMatrixInverse); + if (camera.isPerspectiveCamera) { + camera.fov = RAD2DEG2 * 2 * Math.atan(1 / camera.projectionMatrix.elements[5]); + camera.zoom = 1; + } + } + this.getCamera = function() { + return cameraXR; + }; + this.getFoveation = function() { + if (glProjLayer === null && glBaseLayer === null) { + return; + } + return foveation; + }; + this.setFoveation = function(value2) { + foveation = value2; + if (glProjLayer !== null) { + glProjLayer.fixedFoveation = value2; + } + if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) { + glBaseLayer.fixedFoveation = value2; + } + }; + this.hasDepthSensing = function() { + return depthSensing.texture !== null; + }; + this.getDepthSensingMesh = function() { + return depthSensing.getMesh(cameraXR); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time2, frame) { + pose = frame.getViewerPose(customReferenceSpace || referenceSpace); + xrFrame = frame; + if (pose !== null) { + const views = pose.views; + if (glBaseLayer !== null) { + renderer2.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer); + renderer2.setRenderTarget(newRenderTarget); + } + let cameraXRNeedsUpdate = false; + if (views.length !== cameraXR.cameras.length) { + cameraXR.cameras.length = 0; + cameraXRNeedsUpdate = true; + } + for (let i = 0;i < views.length; i++) { + const view = views[i]; + let viewport = null; + if (glBaseLayer !== null) { + viewport = glBaseLayer.getViewport(view); + } else { + const glSubImage = glBinding.getViewSubImage(glProjLayer, view); + viewport = glSubImage.viewport; + if (i === 0) { + renderer2.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture); + renderer2.setRenderTarget(newRenderTarget); + } + } + let camera = cameras[i]; + if (camera === undefined) { + camera = new PerspectiveCamera2; + camera.layers.enable(i); + camera.viewport = new Vector42; + cameras[i] = camera; + } + camera.matrix.fromArray(view.transform.matrix); + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.projectionMatrix.fromArray(view.projectionMatrix); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height); + if (i === 0) { + cameraXR.matrix.copy(camera.matrix); + cameraXR.matrix.decompose(cameraXR.position, cameraXR.quaternion, cameraXR.scale); + } + if (cameraXRNeedsUpdate === true) { + cameraXR.cameras.push(camera); + } + } + const enabledFeatures = session.enabledFeatures; + const gpuDepthSensingEnabled = enabledFeatures && enabledFeatures.includes("depth-sensing") && session.depthUsage == "gpu-optimized"; + if (gpuDepthSensingEnabled && glBinding) { + const depthData = glBinding.getDepthInformation(views[0]); + if (depthData && depthData.isValid && depthData.texture) { + depthSensing.init(renderer2, depthData, session.renderState); + } + } + } + for (let i = 0;i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + const controller = controllers[i]; + if (inputSource !== null && controller !== undefined) { + controller.update(inputSource, frame, customReferenceSpace || referenceSpace); + } + } + if (onAnimationFrameCallback) + onAnimationFrameCallback(time2, frame); + if (frame.detectedPlanes) { + scope.dispatchEvent({ type: "planesdetected", data: frame }); + } + xrFrame = null; + } + const animation = new WebGLAnimation2; + animation.setAnimationLoop(onAnimationFrame); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + }; + this.dispose = function() { + }; + } + } + var _e12 = /* @__PURE__ */ new Euler2; + var _m13 = /* @__PURE__ */ new Matrix42; + function WebGLMaterials2(renderer2, properties) { + function refreshTransformUniform(map2, uniform) { + if (map2.matrixAutoUpdate === true) { + map2.updateMatrix(); + } + uniform.value.copy(map2.matrix); + } + function refreshFogUniforms(uniforms, fog) { + fog.color.getRGB(uniforms.fogColor.value, getUnlitUniformColorSpace2(renderer2)); + if (fog.isFog) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + } else if (fog.isFogExp2) { + uniforms.fogDensity.value = fog.density; + } + } + function refreshMaterialUniforms(uniforms, material, pixelRatio, height2, transmissionRenderTarget) { + if (material.isMeshBasicMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshLambertMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshToonMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsToon(uniforms, material); + } else if (material.isMeshPhongMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsPhong(uniforms, material); + } else if (material.isMeshStandardMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsStandard(uniforms, material); + if (material.isMeshPhysicalMaterial) { + refreshUniformsPhysical(uniforms, material, transmissionRenderTarget); + } + } else if (material.isMeshMatcapMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsMatcap(uniforms, material); + } else if (material.isMeshDepthMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshDistanceMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsDistance(uniforms, material); + } else if (material.isMeshNormalMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isLineBasicMaterial) { + refreshUniformsLine(uniforms, material); + if (material.isLineDashedMaterial) { + refreshUniformsDash(uniforms, material); + } + } else if (material.isPointsMaterial) { + refreshUniformsPoints(uniforms, material, pixelRatio, height2); + } else if (material.isSpriteMaterial) { + refreshUniformsSprites(uniforms, material); + } else if (material.isShadowMaterial) { + uniforms.color.value.copy(material.color); + uniforms.opacity.value = material.opacity; + } else if (material.isShaderMaterial) { + material.uniformsNeedUpdate = false; + } + } + function refreshUniformsCommon(uniforms, material) { + uniforms.opacity.value = material.opacity; + if (material.color) { + uniforms.diffuse.value.copy(material.color); + } + if (material.emissive) { + uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity); + } + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.bumpMap) { + uniforms.bumpMap.value = material.bumpMap; + refreshTransformUniform(material.bumpMap, uniforms.bumpMapTransform); + uniforms.bumpScale.value = material.bumpScale; + if (material.side === BackSide2) { + uniforms.bumpScale.value *= -1; + } + } + if (material.normalMap) { + uniforms.normalMap.value = material.normalMap; + refreshTransformUniform(material.normalMap, uniforms.normalMapTransform); + uniforms.normalScale.value.copy(material.normalScale); + if (material.side === BackSide2) { + uniforms.normalScale.value.negate(); + } + } + if (material.displacementMap) { + uniforms.displacementMap.value = material.displacementMap; + refreshTransformUniform(material.displacementMap, uniforms.displacementMapTransform); + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + } + if (material.emissiveMap) { + uniforms.emissiveMap.value = material.emissiveMap; + refreshTransformUniform(material.emissiveMap, uniforms.emissiveMapTransform); + } + if (material.specularMap) { + uniforms.specularMap.value = material.specularMap; + refreshTransformUniform(material.specularMap, uniforms.specularMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + const materialProperties = properties.get(material); + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; + if (envMap) { + uniforms.envMap.value = envMap; + _e12.copy(envMapRotation); + _e12.x *= -1; + _e12.y *= -1; + _e12.z *= -1; + if (envMap.isCubeTexture && envMap.isRenderTargetTexture === false) { + _e12.y *= -1; + _e12.z *= -1; + } + uniforms.envMapRotation.value.setFromMatrix4(_m13.makeRotationFromEuler(_e12)); + uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + } + if (material.lightMap) { + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; + refreshTransformUniform(material.lightMap, uniforms.lightMapTransform); + } + if (material.aoMap) { + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + refreshTransformUniform(material.aoMap, uniforms.aoMapTransform); + } + } + function refreshUniformsLine(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + } + function refreshUniformsDash(uniforms, material) { + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + } + function refreshUniformsPoints(uniforms, material, pixelRatio, height2) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height2 * 0.5; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.uvTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsSprites(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsPhong(uniforms, material) { + uniforms.specular.value.copy(material.specular); + uniforms.shininess.value = Math.max(material.shininess, 0.0001); + } + function refreshUniformsToon(uniforms, material) { + if (material.gradientMap) { + uniforms.gradientMap.value = material.gradientMap; + } + } + function refreshUniformsStandard(uniforms, material) { + uniforms.metalness.value = material.metalness; + if (material.metalnessMap) { + uniforms.metalnessMap.value = material.metalnessMap; + refreshTransformUniform(material.metalnessMap, uniforms.metalnessMapTransform); + } + uniforms.roughness.value = material.roughness; + if (material.roughnessMap) { + uniforms.roughnessMap.value = material.roughnessMap; + refreshTransformUniform(material.roughnessMap, uniforms.roughnessMapTransform); + } + if (material.envMap) { + uniforms.envMapIntensity.value = material.envMapIntensity; + } + } + function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) { + uniforms.ior.value = material.ior; + if (material.sheen > 0) { + uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen); + uniforms.sheenRoughness.value = material.sheenRoughness; + if (material.sheenColorMap) { + uniforms.sheenColorMap.value = material.sheenColorMap; + refreshTransformUniform(material.sheenColorMap, uniforms.sheenColorMapTransform); + } + if (material.sheenRoughnessMap) { + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + refreshTransformUniform(material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform); + } + } + if (material.clearcoat > 0) { + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + if (material.clearcoatMap) { + uniforms.clearcoatMap.value = material.clearcoatMap; + refreshTransformUniform(material.clearcoatMap, uniforms.clearcoatMapTransform); + } + if (material.clearcoatRoughnessMap) { + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + refreshTransformUniform(material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform); + } + if (material.clearcoatNormalMap) { + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + refreshTransformUniform(material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform); + uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale); + if (material.side === BackSide2) { + uniforms.clearcoatNormalScale.value.negate(); + } + } + } + if (material.dispersion > 0) { + uniforms.dispersion.value = material.dispersion; + } + if (material.iridescence > 0) { + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1]; + if (material.iridescenceMap) { + uniforms.iridescenceMap.value = material.iridescenceMap; + refreshTransformUniform(material.iridescenceMap, uniforms.iridescenceMapTransform); + } + if (material.iridescenceThicknessMap) { + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + refreshTransformUniform(material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform); + } + } + if (material.transmission > 0) { + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height); + if (material.transmissionMap) { + uniforms.transmissionMap.value = material.transmissionMap; + refreshTransformUniform(material.transmissionMap, uniforms.transmissionMapTransform); + } + uniforms.thickness.value = material.thickness; + if (material.thicknessMap) { + uniforms.thicknessMap.value = material.thicknessMap; + refreshTransformUniform(material.thicknessMap, uniforms.thicknessMapTransform); + } + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy(material.attenuationColor); + } + if (material.anisotropy > 0) { + uniforms.anisotropyVector.value.set(material.anisotropy * Math.cos(material.anisotropyRotation), material.anisotropy * Math.sin(material.anisotropyRotation)); + if (material.anisotropyMap) { + uniforms.anisotropyMap.value = material.anisotropyMap; + refreshTransformUniform(material.anisotropyMap, uniforms.anisotropyMapTransform); + } + } + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy(material.specularColor); + if (material.specularColorMap) { + uniforms.specularColorMap.value = material.specularColorMap; + refreshTransformUniform(material.specularColorMap, uniforms.specularColorMapTransform); + } + if (material.specularIntensityMap) { + uniforms.specularIntensityMap.value = material.specularIntensityMap; + refreshTransformUniform(material.specularIntensityMap, uniforms.specularIntensityMapTransform); + } + } + function refreshUniformsMatcap(uniforms, material) { + if (material.matcap) { + uniforms.matcap.value = material.matcap; + } + } + function refreshUniformsDistance(uniforms, material) { + const light = properties.get(material).light; + uniforms.referencePosition.value.setFromMatrixPosition(light.matrixWorld); + uniforms.nearDistance.value = light.shadow.camera.near; + uniforms.farDistance.value = light.shadow.camera.far; + } + return { + refreshFogUniforms, + refreshMaterialUniforms + }; + } + function WebGLUniformsGroups2(gl, info, capabilities, state) { + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + const maxBindingPoints = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS); + function bind(uniformsGroup, program) { + const webglProgram = program.program; + state.uniformBlockBinding(uniformsGroup, webglProgram); + } + function update(uniformsGroup, program) { + let buffer = buffers[uniformsGroup.id]; + if (buffer === undefined) { + prepareUniformsGroup(uniformsGroup); + buffer = createBuffer(uniformsGroup); + buffers[uniformsGroup.id] = buffer; + uniformsGroup.addEventListener("dispose", onUniformsGroupsDispose); + } + const webglProgram = program.program; + state.updateUBOMapping(uniformsGroup, webglProgram); + const frame = info.render.frame; + if (updateList[uniformsGroup.id] !== frame) { + updateBufferData(uniformsGroup); + updateList[uniformsGroup.id] = frame; + } + } + function createBuffer(uniformsGroup) { + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + const buffer = gl.createBuffer(); + const size2 = uniformsGroup.__size; + const usage = uniformsGroup.usage; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + gl.bufferData(gl.UNIFORM_BUFFER, size2, usage); + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer); + return buffer; + } + function allocateBindingPointIndex() { + for (let i = 0;i < maxBindingPoints; i++) { + if (allocatedBindingPoints.indexOf(i) === -1) { + allocatedBindingPoints.push(i); + return i; + } + } + console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."); + return 0; + } + function updateBufferData(uniformsGroup) { + const buffer = buffers[uniformsGroup.id]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + for (let i = 0, il = uniforms.length;i < il; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j2 = 0, jl = uniformArray.length;j2 < jl; j2++) { + const uniform = uniformArray[j2]; + if (hasUniformChanged(uniform, i, j2, cache) === true) { + const offset = uniform.__offset; + const values2 = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + let arrayOffset = 0; + for (let k4 = 0;k4 < values2.length; k4++) { + const value2 = values2[k4]; + const info2 = getUniformSize(value2); + if (typeof value2 === "number" || typeof value2 === "boolean") { + uniform.__data[0] = value2; + gl.bufferSubData(gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data); + } else if (value2.isMatrix3) { + uniform.__data[0] = value2.elements[0]; + uniform.__data[1] = value2.elements[1]; + uniform.__data[2] = value2.elements[2]; + uniform.__data[3] = 0; + uniform.__data[4] = value2.elements[3]; + uniform.__data[5] = value2.elements[4]; + uniform.__data[6] = value2.elements[5]; + uniform.__data[7] = 0; + uniform.__data[8] = value2.elements[6]; + uniform.__data[9] = value2.elements[7]; + uniform.__data[10] = value2.elements[8]; + uniform.__data[11] = 0; + } else { + value2.toArray(uniform.__data, arrayOffset); + arrayOffset += info2.storage / Float32Array.BYTES_PER_ELEMENT; + } + } + gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data); + } + } + } + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + } + function hasUniformChanged(uniform, index2, indexArray, cache) { + const value2 = uniform.value; + const indexString = index2 + "_" + indexArray; + if (cache[indexString] === undefined) { + if (typeof value2 === "number" || typeof value2 === "boolean") { + cache[indexString] = value2; + } else { + cache[indexString] = value2.clone(); + } + return true; + } else { + const cachedObject = cache[indexString]; + if (typeof value2 === "number" || typeof value2 === "boolean") { + if (cachedObject !== value2) { + cache[indexString] = value2; + return true; + } + } else { + if (cachedObject.equals(value2) === false) { + cachedObject.copy(value2); + return true; + } + } + } + return false; + } + function prepareUniformsGroup(uniformsGroup) { + const uniforms = uniformsGroup.uniforms; + let offset = 0; + const chunkSize = 16; + for (let i = 0, l2 = uniforms.length;i < l2; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j2 = 0, jl = uniformArray.length;j2 < jl; j2++) { + const uniform = uniformArray[j2]; + const values2 = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + for (let k4 = 0, kl = values2.length;k4 < kl; k4++) { + const value2 = values2[k4]; + const info2 = getUniformSize(value2); + const chunkOffset2 = offset % chunkSize; + const chunkPadding = chunkOffset2 % info2.boundary; + const chunkStart = chunkOffset2 + chunkPadding; + offset += chunkPadding; + if (chunkStart !== 0 && chunkSize - chunkStart < info2.storage) { + offset += chunkSize - chunkStart; + } + uniform.__data = new Float32Array(info2.storage / Float32Array.BYTES_PER_ELEMENT); + uniform.__offset = offset; + offset += info2.storage; + } + } + } + const chunkOffset = offset % chunkSize; + if (chunkOffset > 0) + offset += chunkSize - chunkOffset; + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + return this; + } + function getUniformSize(value2) { + const info2 = { + boundary: 0, + storage: 0 + }; + if (typeof value2 === "number" || typeof value2 === "boolean") { + info2.boundary = 4; + info2.storage = 4; + } else if (value2.isVector2) { + info2.boundary = 8; + info2.storage = 8; + } else if (value2.isVector3 || value2.isColor) { + info2.boundary = 16; + info2.storage = 12; + } else if (value2.isVector4) { + info2.boundary = 16; + info2.storage = 16; + } else if (value2.isMatrix3) { + info2.boundary = 48; + info2.storage = 48; + } else if (value2.isMatrix4) { + info2.boundary = 64; + info2.storage = 64; + } else if (value2.isTexture) { + console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."); + } else { + console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", value2); + } + return info2; + } + function onUniformsGroupsDispose(event) { + const uniformsGroup = event.target; + uniformsGroup.removeEventListener("dispose", onUniformsGroupsDispose); + const index2 = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex); + allocatedBindingPoints.splice(index2, 1); + gl.deleteBuffer(buffers[uniformsGroup.id]); + delete buffers[uniformsGroup.id]; + delete updateList[uniformsGroup.id]; + } + function dispose() { + for (const id in buffers) { + gl.deleteBuffer(buffers[id]); + } + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + } + return { + bind, + update, + dispose + }; + } + + class WebGLRenderer2 { + constructor(parameters = {}) { + const { + canvas = createCanvasElement2(), + context = null, + depth = true, + stencil = false, + alpha = false, + antialias = false, + premultipliedAlpha = true, + preserveDrawingBuffer = false, + powerPreference = "default", + failIfMajorPerformanceCaveat = false, + reverseDepthBuffer = false + } = parameters; + this.isWebGLRenderer = true; + let _alpha; + if (context !== null) { + if (typeof WebGLRenderingContext !== "undefined" && context instanceof WebGLRenderingContext) { + throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163."); + } + _alpha = context.getContextAttributes().alpha; + } else { + _alpha = alpha; + } + const uintClearColor = new Uint32Array(4); + const intClearColor = new Int32Array(4); + let currentRenderList = null; + let currentRenderState = null; + const renderListStack = []; + const renderStateStack = []; + this.domElement = canvas; + this.debug = { + checkShaderErrors: true, + onShaderError: null + }; + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + this.sortObjects = true; + this.clippingPlanes = []; + this.localClippingEnabled = false; + this._outputColorSpace = SRGBColorSpace2; + this.toneMapping = NoToneMapping2; + this.toneMappingExposure = 1; + const _this = this; + let _isContextLost = false; + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = -1; + let _currentCamera = null; + const _currentViewport = new Vector42; + const _currentScissor = new Vector42; + let _currentScissorTest = null; + const _currentClearColor = new Color2(0); + let _currentClearAlpha = 0; + let _width = canvas.width; + let _height = canvas.height; + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + const _viewport3 = new Vector42(0, 0, _width, _height); + const _scissor = new Vector42(0, 0, _width, _height); + let _scissorTest = false; + const _frustum4 = new Frustum2; + let _clippingEnabled = false; + let _localClippingEnabled = false; + this.transmissionResolutionScale = 1; + const _currentProjectionMatrix = new Matrix42; + const _projScreenMatrix3 = new Matrix42; + const _vector33 = new Vector32; + const _vector42 = new Vector42; + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + let _renderBackground = false; + function getTargetPixelRatio() { + return _currentRenderTarget === null ? _pixelRatio : 1; + } + let _gl = context; + function getContext(contextName, contextAttributes) { + return canvas.getContext(contextName, contextAttributes); + } + try { + const contextAttributes = { + alpha: true, + depth, + stencil, + antialias, + premultipliedAlpha, + preserveDrawingBuffer, + powerPreference, + failIfMajorPerformanceCaveat + }; + if ("setAttribute" in canvas) + canvas.setAttribute("data-engine", `three.js r${REVISION2}`); + canvas.addEventListener("webglcontextlost", onContextLost, false); + canvas.addEventListener("webglcontextrestored", onContextRestore, false); + canvas.addEventListener("webglcontextcreationerror", onContextCreationError, false); + if (_gl === null) { + const contextName = "webgl2"; + _gl = getContext(contextName, contextAttributes); + if (_gl === null) { + if (getContext(contextName)) { + throw new Error("Error creating WebGL context with your selected attributes."); + } else { + throw new Error("Error creating WebGL context."); + } + } + } + } catch (error) { + console.error("THREE.WebGLRenderer: " + error.message); + throw error; + } + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + let utils, bindingStates, uniformsGroups; + function initGLContext() { + extensions = new WebGLExtensions2(_gl); + extensions.init(); + utils = new WebGLUtils2(_gl, extensions); + capabilities = new WebGLCapabilities2(_gl, extensions, parameters, utils); + state = new WebGLState2(_gl, extensions); + if (capabilities.reverseDepthBuffer && reverseDepthBuffer) { + state.buffers.depth.setReversed(true); + } + info = new WebGLInfo2(_gl); + properties = new WebGLProperties2; + textures = new WebGLTextures2(_gl, extensions, state, properties, capabilities, utils, info); + cubemaps = new WebGLCubeMaps2(_this); + cubeuvmaps = new WebGLCubeUVMaps2(_this); + attributes = new WebGLAttributes2(_gl); + bindingStates = new WebGLBindingStates2(_gl, attributes); + geometries = new WebGLGeometries2(_gl, attributes, info, bindingStates); + objects = new WebGLObjects2(_gl, geometries, attributes, info); + morphtargets = new WebGLMorphtargets2(_gl, capabilities, textures); + clipping = new WebGLClipping2(properties); + programCache = new WebGLPrograms2(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping); + materials = new WebGLMaterials2(_this, properties); + renderLists = new WebGLRenderLists2; + renderStates = new WebGLRenderStates2(extensions); + background = new WebGLBackground2(_this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha); + shadowMap = new WebGLShadowMap2(_this, objects, capabilities); + uniformsGroups = new WebGLUniformsGroups2(_gl, info, capabilities, state); + bufferRenderer = new WebGLBufferRenderer2(_gl, extensions, info); + indexedBufferRenderer = new WebGLIndexedBufferRenderer2(_gl, extensions, info); + info.programs = programCache.programs; + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; + } + initGLContext(); + const xr = new WebXRManager2(_this, _gl); + this.xr = xr; + this.getContext = function() { + return _gl; + }; + this.getContextAttributes = function() { + return _gl.getContextAttributes(); + }; + this.forceContextLoss = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) + extension.loseContext(); + }; + this.forceContextRestore = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) + extension.restoreContext(); + }; + this.getPixelRatio = function() { + return _pixelRatio; + }; + this.setPixelRatio = function(value2) { + if (value2 === undefined) + return; + _pixelRatio = value2; + this.setSize(_width, _height, false); + }; + this.getSize = function(target) { + return target.set(_width, _height); + }; + this.setSize = function(width2, height2, updateStyle = true) { + if (xr.isPresenting) { + console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."); + return; + } + _width = width2; + _height = height2; + canvas.width = Math.floor(width2 * _pixelRatio); + canvas.height = Math.floor(height2 * _pixelRatio); + if (updateStyle === true) { + canvas.style.width = width2 + "px"; + canvas.style.height = height2 + "px"; + } + this.setViewport(0, 0, width2, height2); + }; + this.getDrawingBufferSize = function(target) { + return target.set(_width * _pixelRatio, _height * _pixelRatio).floor(); + }; + this.setDrawingBufferSize = function(width2, height2, pixelRatio) { + _width = width2; + _height = height2; + _pixelRatio = pixelRatio; + canvas.width = Math.floor(width2 * pixelRatio); + canvas.height = Math.floor(height2 * pixelRatio); + this.setViewport(0, 0, width2, height2); + }; + this.getCurrentViewport = function(target) { + return target.copy(_currentViewport); + }; + this.getViewport = function(target) { + return target.copy(_viewport3); + }; + this.setViewport = function(x2, y3, width2, height2) { + if (x2.isVector4) { + _viewport3.set(x2.x, x2.y, x2.z, x2.w); + } else { + _viewport3.set(x2, y3, width2, height2); + } + state.viewport(_currentViewport.copy(_viewport3).multiplyScalar(_pixelRatio).round()); + }; + this.getScissor = function(target) { + return target.copy(_scissor); + }; + this.setScissor = function(x2, y3, width2, height2) { + if (x2.isVector4) { + _scissor.set(x2.x, x2.y, x2.z, x2.w); + } else { + _scissor.set(x2, y3, width2, height2); + } + state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).round()); + }; + this.getScissorTest = function() { + return _scissorTest; + }; + this.setScissorTest = function(boolean) { + state.setScissorTest(_scissorTest = boolean); + }; + this.setOpaqueSort = function(method) { + _opaqueSort = method; + }; + this.setTransparentSort = function(method) { + _transparentSort = method; + }; + this.getClearColor = function(target) { + return target.copy(background.getClearColor()); + }; + this.setClearColor = function() { + background.setClearColor.apply(background, arguments); + }; + this.getClearAlpha = function() { + return background.getClearAlpha(); + }; + this.setClearAlpha = function() { + background.setClearAlpha.apply(background, arguments); + }; + this.clear = function(color = true, depth2 = true, stencil2 = true) { + let bits = 0; + if (color) { + let isIntegerFormat = false; + if (_currentRenderTarget !== null) { + const targetFormat = _currentRenderTarget.texture.format; + isIntegerFormat = targetFormat === RGBAIntegerFormat2 || targetFormat === RGIntegerFormat2 || targetFormat === RedIntegerFormat2; + } + if (isIntegerFormat) { + const targetType = _currentRenderTarget.texture.type; + const isUnsignedType = targetType === UnsignedByteType2 || targetType === UnsignedIntType2 || targetType === UnsignedShortType2 || targetType === UnsignedInt248Type2 || targetType === UnsignedShort4444Type2 || targetType === UnsignedShort5551Type2; + const clearColor = background.getClearColor(); + const a2 = background.getClearAlpha(); + const r = clearColor.r; + const g3 = clearColor.g; + const b3 = clearColor.b; + if (isUnsignedType) { + uintClearColor[0] = r; + uintClearColor[1] = g3; + uintClearColor[2] = b3; + uintClearColor[3] = a2; + _gl.clearBufferuiv(_gl.COLOR, 0, uintClearColor); + } else { + intClearColor[0] = r; + intClearColor[1] = g3; + intClearColor[2] = b3; + intClearColor[3] = a2; + _gl.clearBufferiv(_gl.COLOR, 0, intClearColor); + } + } else { + bits |= _gl.COLOR_BUFFER_BIT; + } + } + if (depth2) { + bits |= _gl.DEPTH_BUFFER_BIT; + } + if (stencil2) { + bits |= _gl.STENCIL_BUFFER_BIT; + this.state.buffers.stencil.setMask(4294967295); + } + _gl.clear(bits); + }; + this.clearColor = function() { + this.clear(true, false, false); + }; + this.clearDepth = function() { + this.clear(false, true, false); + }; + this.clearStencil = function() { + this.clear(false, false, true); + }; + this.dispose = function() { + canvas.removeEventListener("webglcontextlost", onContextLost, false); + canvas.removeEventListener("webglcontextrestored", onContextRestore, false); + canvas.removeEventListener("webglcontextcreationerror", onContextCreationError, false); + background.dispose(); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + xr.dispose(); + xr.removeEventListener("sessionstart", onXRSessionStart); + xr.removeEventListener("sessionend", onXRSessionEnd); + animation.stop(); + }; + function onContextLost(event) { + event.preventDefault(); + console.log("THREE.WebGLRenderer: Context Lost."); + _isContextLost = true; + } + function onContextRestore() { + console.log("THREE.WebGLRenderer: Context Restored."); + _isContextLost = false; + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + initGLContext(); + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + } + function onContextCreationError(event) { + console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", event.statusMessage); + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + deallocateMaterial(material); + } + function deallocateMaterial(material) { + releaseMaterialProgramReferences(material); + properties.remove(material); + } + function releaseMaterialProgramReferences(material) { + const programs = properties.get(material).programs; + if (programs !== undefined) { + programs.forEach(function(program) { + programCache.releaseProgram(program); + }); + if (material.isShaderMaterial) { + programCache.releaseShaderCache(material); + } + } + } + this.renderBufferDirect = function(camera, scene, geometry, material, object, group) { + if (scene === null) + scene = _emptyScene; + const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0; + const program = setProgram(camera, scene, geometry, material, object); + state.setMaterial(material, frontFaceCW); + let index2 = geometry.index; + let rangeFactor = 1; + if (material.wireframe === true) { + index2 = geometries.getWireframeAttribute(geometry); + if (index2 === undefined) + return; + rangeFactor = 2; + } + const drawRange = geometry.drawRange; + const position2 = geometry.attributes.position; + let drawStart = drawRange.start * rangeFactor; + let drawEnd = (drawRange.start + drawRange.count) * rangeFactor; + if (group !== null) { + drawStart = Math.max(drawStart, group.start * rangeFactor); + drawEnd = Math.min(drawEnd, (group.start + group.count) * rangeFactor); + } + if (index2 !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, index2.count); + } else if (position2 !== undefined && position2 !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, position2.count); + } + const drawCount = drawEnd - drawStart; + if (drawCount < 0 || drawCount === Infinity) + return; + bindingStates.setup(object, material, program, geometry, index2); + let attribute; + let renderer2 = bufferRenderer; + if (index2 !== null) { + attribute = attributes.get(index2); + renderer2 = indexedBufferRenderer; + renderer2.setIndex(attribute); + } + if (object.isMesh) { + if (material.wireframe === true) { + state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio()); + renderer2.setMode(_gl.LINES); + } else { + renderer2.setMode(_gl.TRIANGLES); + } + } else if (object.isLine) { + let lineWidth = material.linewidth; + if (lineWidth === undefined) + lineWidth = 1; + state.setLineWidth(lineWidth * getTargetPixelRatio()); + if (object.isLineSegments) { + renderer2.setMode(_gl.LINES); + } else if (object.isLineLoop) { + renderer2.setMode(_gl.LINE_LOOP); + } else { + renderer2.setMode(_gl.LINE_STRIP); + } + } else if (object.isPoints) { + renderer2.setMode(_gl.POINTS); + } else if (object.isSprite) { + renderer2.setMode(_gl.TRIANGLES); + } + if (object.isBatchedMesh) { + if (object._multiDrawInstances !== null) { + renderer2.renderMultiDrawInstances(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances); + } else { + if (!extensions.get("WEBGL_multi_draw")) { + const starts = object._multiDrawStarts; + const counts = object._multiDrawCounts; + const drawCount2 = object._multiDrawCount; + const bytesPerElement = index2 ? attributes.get(index2).bytesPerElement : 1; + const uniforms = properties.get(material).currentProgram.getUniforms(); + for (let i = 0;i < drawCount2; i++) { + uniforms.setValue(_gl, "_gl_DrawID", i); + renderer2.render(starts[i] / bytesPerElement, counts[i]); + } + } else { + renderer2.renderMultiDraw(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount); + } + } + } else if (object.isInstancedMesh) { + renderer2.renderInstances(drawStart, drawCount, object.count); + } else if (geometry.isInstancedBufferGeometry) { + const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min(geometry.instanceCount, maxInstanceCount); + renderer2.renderInstances(drawStart, drawCount, instanceCount); + } else { + renderer2.render(drawStart, drawCount); + } + }; + function prepareMaterial(material, scene, object) { + if (material.transparent === true && material.side === DoubleSide2 && material.forceSinglePass === false) { + material.side = BackSide2; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = FrontSide2; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = DoubleSide2; + } else { + getProgram(material, scene, object); + } + } + this.compile = function(scene, camera, targetScene = null) { + if (targetScene === null) + targetScene = scene; + currentRenderState = renderStates.get(targetScene); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + targetScene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + if (scene !== targetScene) { + scene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + } + currentRenderState.setupLights(); + const materials2 = new Set; + scene.traverse(function(object) { + if (!(object.isMesh || object.isPoints || object.isLine || object.isSprite)) { + return; + } + const material = object.material; + if (material) { + if (Array.isArray(material)) { + for (let i = 0;i < material.length; i++) { + const material2 = material[i]; + prepareMaterial(material2, targetScene, object); + materials2.add(material2); + } + } else { + prepareMaterial(material, targetScene, object); + materials2.add(material); + } + } + }); + renderStateStack.pop(); + currentRenderState = null; + return materials2; + }; + this.compileAsync = function(scene, camera, targetScene = null) { + const materials2 = this.compile(scene, camera, targetScene); + return new Promise((resolve) => { + function checkMaterialsReady() { + materials2.forEach(function(material) { + const materialProperties = properties.get(material); + const program = materialProperties.currentProgram; + if (program.isReady()) { + materials2.delete(material); + } + }); + if (materials2.size === 0) { + resolve(scene); + return; + } + setTimeout(checkMaterialsReady, 10); + } + if (extensions.get("KHR_parallel_shader_compile") !== null) { + checkMaterialsReady(); + } else { + setTimeout(checkMaterialsReady, 10); + } + }); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time2) { + if (onAnimationFrameCallback) + onAnimationFrameCallback(time2); + } + function onXRSessionStart() { + animation.stop(); + } + function onXRSessionEnd() { + animation.start(); + } + const animation = new WebGLAnimation2; + animation.setAnimationLoop(onAnimationFrame); + if (typeof self !== "undefined") + animation.setContext(self); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + xr.setAnimationLoop(callback); + callback === null ? animation.stop() : animation.start(); + }; + xr.addEventListener("sessionstart", onXRSessionStart); + xr.addEventListener("sessionend", onXRSessionEnd); + this.render = function(scene, camera) { + if (camera !== undefined && camera.isCamera !== true) { + console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera."); + return; + } + if (_isContextLost === true) + return; + if (scene.matrixWorldAutoUpdate === true) + scene.updateMatrixWorld(); + if (camera.parent === null && camera.matrixWorldAutoUpdate === true) + camera.updateMatrixWorld(); + if (xr.enabled === true && xr.isPresenting === true) { + if (xr.cameraAutoUpdate === true) + xr.updateCamera(camera); + camera = xr.getCamera(); + } + if (scene.isScene === true) + scene.onBeforeRender(_this, scene, camera, _currentRenderTarget); + currentRenderState = renderStates.get(scene, renderStateStack.length); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + _projScreenMatrix3.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + _frustum4.setFromProjectionMatrix(_projScreenMatrix3); + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled); + currentRenderList = renderLists.get(scene, renderListStack.length); + currentRenderList.init(); + renderListStack.push(currentRenderList); + if (xr.enabled === true && xr.isPresenting === true) { + const depthSensingMesh = _this.xr.getDepthSensingMesh(); + if (depthSensingMesh !== null) { + projectObject(depthSensingMesh, camera, -Infinity, _this.sortObjects); + } + } + projectObject(scene, camera, 0, _this.sortObjects); + currentRenderList.finish(); + if (_this.sortObjects === true) { + currentRenderList.sort(_opaqueSort, _transparentSort); + } + _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false; + if (_renderBackground) { + background.addToRenderList(currentRenderList, scene); + } + this.info.render.frame++; + if (_clippingEnabled === true) + clipping.beginShadows(); + const shadowsArray = currentRenderState.state.shadowsArray; + shadowMap.render(shadowsArray, scene, camera); + if (_clippingEnabled === true) + clipping.endShadows(); + if (this.info.autoReset === true) + this.info.reset(); + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + currentRenderState.setupLights(); + if (camera.isArrayCamera) { + const cameras = camera.cameras; + if (transmissiveObjects.length > 0) { + for (let i = 0, l2 = cameras.length;i < l2; i++) { + const camera2 = cameras[i]; + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera2); + } + } + if (_renderBackground) + background.render(scene); + for (let i = 0, l2 = cameras.length;i < l2; i++) { + const camera2 = cameras[i]; + renderScene(currentRenderList, scene, camera2, camera2.viewport); + } + } else { + if (transmissiveObjects.length > 0) + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera); + if (_renderBackground) + background.render(scene); + renderScene(currentRenderList, scene, camera); + } + if (_currentRenderTarget !== null && _currentActiveMipmapLevel === 0) { + textures.updateMultisampleRenderTarget(_currentRenderTarget); + textures.updateRenderTargetMipmap(_currentRenderTarget); + } + if (scene.isScene === true) + scene.onAfterRender(_this, scene, camera); + bindingStates.resetDefaultState(); + _currentMaterialId = -1; + _currentCamera = null; + renderStateStack.pop(); + if (renderStateStack.length > 0) { + currentRenderState = renderStateStack[renderStateStack.length - 1]; + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, currentRenderState.state.camera); + } else { + currentRenderState = null; + } + renderListStack.pop(); + if (renderListStack.length > 0) { + currentRenderList = renderListStack[renderListStack.length - 1]; + } else { + currentRenderList = null; + } + }; + function projectObject(object, camera, groupOrder, sortObjects) { + if (object.visible === false) + return; + const visible = object.layers.test(camera.layers); + if (visible) { + if (object.isGroup) { + groupOrder = object.renderOrder; + } else if (object.isLOD) { + if (object.autoUpdate === true) + object.update(camera); + } else if (object.isLight) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } else if (object.isSprite) { + if (!object.frustumCulled || _frustum4.intersectsSprite(object)) { + if (sortObjects) { + _vector42.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix3); + } + const geometry = objects.update(object); + const material = object.material; + if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector42.z, null); + } + } + } else if (object.isMesh || object.isLine || object.isPoints) { + if (!object.frustumCulled || _frustum4.intersectsObject(object)) { + const geometry = objects.update(object); + const material = object.material; + if (sortObjects) { + if (object.boundingSphere !== undefined) { + if (object.boundingSphere === null) + object.computeBoundingSphere(); + _vector42.copy(object.boundingSphere.center); + } else { + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _vector42.copy(geometry.boundingSphere.center); + } + _vector42.applyMatrix4(object.matrixWorld).applyMatrix4(_projScreenMatrix3); + } + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let i = 0, l2 = groups.length;i < l2; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector42.z, group); + } + } + } else if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector42.z, null); + } + } + } + } + const children = object.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + projectObject(children[i], camera, groupOrder, sortObjects); + } + } + function renderScene(currentRenderList2, scene, camera, viewport) { + const opaqueObjects = currentRenderList2.opaque; + const transmissiveObjects = currentRenderList2.transmissive; + const transparentObjects = currentRenderList2.transparent; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, camera); + if (viewport) + state.viewport(_currentViewport.copy(viewport)); + if (opaqueObjects.length > 0) + renderObjects(opaqueObjects, scene, camera); + if (transmissiveObjects.length > 0) + renderObjects(transmissiveObjects, scene, camera); + if (transparentObjects.length > 0) + renderObjects(transparentObjects, scene, camera); + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + state.setPolygonOffset(false); + } + function renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + if (overrideMaterial !== null) { + return; + } + if (currentRenderState.state.transmissionRenderTarget[camera.id] === undefined) { + currentRenderState.state.transmissionRenderTarget[camera.id] = new WebGLRenderTarget2(1, 1, { + generateMipmaps: true, + type: extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float") ? HalfFloatType2 : UnsignedByteType2, + minFilter: LinearMipmapLinearFilter2, + samples: 4, + stencilBuffer: stencil, + resolveDepthBuffer: false, + resolveStencilBuffer: false, + colorSpace: ColorManagement2.workingColorSpace + }); + } + const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[camera.id]; + const activeViewport = camera.viewport || _currentViewport; + transmissionRenderTarget.setSize(activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale); + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget(transmissionRenderTarget); + _this.getClearColor(_currentClearColor); + _currentClearAlpha = _this.getClearAlpha(); + if (_currentClearAlpha < 1) + _this.setClearColor(16777215, 0.5); + _this.clear(); + if (_renderBackground) + background.render(scene); + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping2; + const currentCameraViewport = camera.viewport; + if (camera.viewport !== undefined) + camera.viewport = undefined; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, camera); + renderObjects(opaqueObjects, scene, camera); + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + if (extensions.has("WEBGL_multisampled_render_to_texture") === false) { + let renderTargetNeedsUpdate = false; + for (let i = 0, l2 = transmissiveObjects.length;i < l2; i++) { + const renderItem = transmissiveObjects[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = renderItem.material; + const group = renderItem.group; + if (material.side === DoubleSide2 && object.layers.test(camera.layers)) { + const currentSide = material.side; + material.side = BackSide2; + material.needsUpdate = true; + renderObject(object, scene, camera, geometry, material, group); + material.side = currentSide; + material.needsUpdate = true; + renderTargetNeedsUpdate = true; + } + } + if (renderTargetNeedsUpdate === true) { + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + } + } + _this.setRenderTarget(currentRenderTarget); + _this.setClearColor(_currentClearColor, _currentClearAlpha); + if (currentCameraViewport !== undefined) + camera.viewport = currentCameraViewport; + _this.toneMapping = currentToneMapping; + } + function renderObjects(renderList, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + for (let i = 0, l2 = renderList.length;i < l2; i++) { + const renderItem = renderList[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; + if (object.layers.test(camera.layers)) { + renderObject(object, scene, camera, geometry, material, group); + } + } + } + function renderObject(object, scene, camera, geometry, material, group) { + object.onBeforeRender(_this, scene, camera, geometry, material, group); + object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld); + object.normalMatrix.getNormalMatrix(object.modelViewMatrix); + material.onBeforeRender(_this, scene, camera, geometry, object, group); + if (material.transparent === true && material.side === DoubleSide2 && material.forceSinglePass === false) { + material.side = BackSide2; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = FrontSide2; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = DoubleSide2; + } else { + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + } + object.onAfterRender(_this, scene, camera, geometry, material, group); + } + function getProgram(material, scene, object) { + if (scene.isScene !== true) + scene = _emptyScene; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + const lightsStateVersion = lights.state.version; + const parameters2 = programCache.getParameters(material, lights.state, shadowsArray, scene, object); + const programCacheKey = programCache.getProgramCacheKey(parameters2); + let programs = materialProperties.programs; + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment); + materialProperties.envMapRotation = materialProperties.environment !== null && material.envMap === null ? scene.environmentRotation : material.envMapRotation; + if (programs === undefined) { + material.addEventListener("dispose", onMaterialDispose); + programs = new Map; + materialProperties.programs = programs; + } + let program = programs.get(programCacheKey); + if (program !== undefined) { + if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) { + updateCommonMaterialProperties(material, parameters2); + return program; + } + } else { + parameters2.uniforms = programCache.getUniforms(material); + material.onBeforeCompile(parameters2, _this); + program = programCache.acquireProgram(parameters2, programCacheKey); + programs.set(programCacheKey, program); + materialProperties.uniforms = parameters2.uniforms; + } + const uniforms = materialProperties.uniforms; + if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) { + uniforms.clippingPlanes = clipping.uniform; + } + updateCommonMaterialProperties(material, parameters2); + materialProperties.needsLights = materialNeedsLights(material); + materialProperties.lightsStateVersion = lightsStateVersion; + if (materialProperties.needsLights) { + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + } + materialProperties.currentProgram = program; + materialProperties.uniformsList = null; + return program; + } + function getUniformList(materialProperties) { + if (materialProperties.uniformsList === null) { + const progUniforms = materialProperties.currentProgram.getUniforms(); + materialProperties.uniformsList = WebGLUniforms2.seqWithValue(progUniforms.seq, materialProperties.uniforms); + } + return materialProperties.uniformsList; + } + function updateCommonMaterialProperties(material, parameters2) { + const materialProperties = properties.get(material); + materialProperties.outputColorSpace = parameters2.outputColorSpace; + materialProperties.batching = parameters2.batching; + materialProperties.batchingColor = parameters2.batchingColor; + materialProperties.instancing = parameters2.instancing; + materialProperties.instancingColor = parameters2.instancingColor; + materialProperties.instancingMorph = parameters2.instancingMorph; + materialProperties.skinning = parameters2.skinning; + materialProperties.morphTargets = parameters2.morphTargets; + materialProperties.morphNormals = parameters2.morphNormals; + materialProperties.morphColors = parameters2.morphColors; + materialProperties.morphTargetsCount = parameters2.morphTargetsCount; + materialProperties.numClippingPlanes = parameters2.numClippingPlanes; + materialProperties.numIntersection = parameters2.numClipIntersection; + materialProperties.vertexAlphas = parameters2.vertexAlphas; + materialProperties.vertexTangents = parameters2.vertexTangents; + materialProperties.toneMapping = parameters2.toneMapping; + } + function setProgram(camera, scene, geometry, material, object) { + if (scene.isScene !== true) + scene = _emptyScene; + textures.resetTextureUnits(); + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const colorSpace = _currentRenderTarget === null ? _this.outputColorSpace : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace2; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !!geometry.attributes.tangent && (!!material.normalMap || material.anisotropy > 0); + const morphTargets = !!geometry.morphAttributes.position; + const morphNormals = !!geometry.morphAttributes.normal; + const morphColors = !!geometry.morphAttributes.color; + let toneMapping = NoToneMapping2; + if (material.toneMapped) { + if (_currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true) { + toneMapping = _this.toneMapping; + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + if (_clippingEnabled === true) { + if (_localClippingEnabled === true || camera !== _currentCamera) { + const useCache = camera === _currentCamera && material.id === _currentMaterialId; + clipping.setState(material, camera, useCache); + } + } + let needsProgramChange = false; + if (material.version === materialProperties.__version) { + if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) { + needsProgramChange = true; + } else if (materialProperties.outputColorSpace !== colorSpace) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batching === false) { + needsProgramChange = true; + } else if (!object.isBatchedMesh && materialProperties.batching === true) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancing === false) { + needsProgramChange = true; + } else if (!object.isInstancedMesh && materialProperties.instancing === true) { + needsProgramChange = true; + } else if (object.isSkinnedMesh && materialProperties.skinning === false) { + needsProgramChange = true; + } else if (!object.isSkinnedMesh && materialProperties.skinning === true) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null) { + needsProgramChange = true; + } else if (materialProperties.envMap !== envMap) { + needsProgramChange = true; + } else if (material.fog === true && materialProperties.fog !== fog) { + needsProgramChange = true; + } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) { + needsProgramChange = true; + } else if (materialProperties.vertexAlphas !== vertexAlphas) { + needsProgramChange = true; + } else if (materialProperties.vertexTangents !== vertexTangents) { + needsProgramChange = true; + } else if (materialProperties.morphTargets !== morphTargets) { + needsProgramChange = true; + } else if (materialProperties.morphNormals !== morphNormals) { + needsProgramChange = true; + } else if (materialProperties.morphColors !== morphColors) { + needsProgramChange = true; + } else if (materialProperties.toneMapping !== toneMapping) { + needsProgramChange = true; + } else if (materialProperties.morphTargetsCount !== morphTargetsCount) { + needsProgramChange = true; + } + } else { + needsProgramChange = true; + materialProperties.__version = material.version; + } + let program = materialProperties.currentProgram; + if (needsProgramChange === true) { + program = getProgram(material, scene, object); + } + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + const p_uniforms = program.getUniforms(), m_uniforms = materialProperties.uniforms; + if (state.useProgram(program.program)) { + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + } + if (material.id !== _currentMaterialId) { + _currentMaterialId = material.id; + refreshMaterial = true; + } + if (refreshProgram || _currentCamera !== camera) { + const reverseDepthBuffer2 = state.buffers.depth.getReversed(); + if (reverseDepthBuffer2) { + _currentProjectionMatrix.copy(camera.projectionMatrix); + toNormalizedProjectionMatrix2(_currentProjectionMatrix); + toReversedProjectionMatrix2(_currentProjectionMatrix); + p_uniforms.setValue(_gl, "projectionMatrix", _currentProjectionMatrix); + } else { + p_uniforms.setValue(_gl, "projectionMatrix", camera.projectionMatrix); + } + p_uniforms.setValue(_gl, "viewMatrix", camera.matrixWorldInverse); + const uCamPos = p_uniforms.map.cameraPosition; + if (uCamPos !== undefined) { + uCamPos.setValue(_gl, _vector33.setFromMatrixPosition(camera.matrixWorld)); + } + if (capabilities.logarithmicDepthBuffer) { + p_uniforms.setValue(_gl, "logDepthBufFC", 2 / (Math.log(camera.far + 1) / Math.LN2)); + } + if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) { + p_uniforms.setValue(_gl, "isOrthographic", camera.isOrthographicCamera === true); + } + if (_currentCamera !== camera) { + _currentCamera = camera; + refreshMaterial = true; + refreshLights = true; + } + } + if (object.isSkinnedMesh) { + p_uniforms.setOptional(_gl, object, "bindMatrix"); + p_uniforms.setOptional(_gl, object, "bindMatrixInverse"); + const skeleton = object.skeleton; + if (skeleton) { + if (skeleton.boneTexture === null) + skeleton.computeBoneTexture(); + p_uniforms.setValue(_gl, "boneTexture", skeleton.boneTexture, textures); + } + } + if (object.isBatchedMesh) { + p_uniforms.setOptional(_gl, object, "batchingTexture"); + p_uniforms.setValue(_gl, "batchingTexture", object._matricesTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingIdTexture"); + p_uniforms.setValue(_gl, "batchingIdTexture", object._indirectTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingColorTexture"); + if (object._colorsTexture !== null) { + p_uniforms.setValue(_gl, "batchingColorTexture", object._colorsTexture, textures); + } + } + const morphAttributes = geometry.morphAttributes; + if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined) { + morphtargets.update(object, geometry, program); + } + if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) { + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue(_gl, "receiveShadow", object.receiveShadow); + } + if (material.isMeshGouraudMaterial && material.envMap !== null) { + m_uniforms.envMap.value = envMap; + m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + } + if (material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null) { + m_uniforms.envMapIntensity.value = scene.environmentIntensity; + } + if (refreshMaterial) { + p_uniforms.setValue(_gl, "toneMappingExposure", _this.toneMappingExposure); + if (materialProperties.needsLights) { + markUniformsLightsNeedsUpdate(m_uniforms, refreshLights); + } + if (fog && material.fog === true) { + materials.refreshFogUniforms(m_uniforms, fog); + } + materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[camera.id]); + WebGLUniforms2.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + } + if (material.isShaderMaterial && material.uniformsNeedUpdate === true) { + WebGLUniforms2.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + material.uniformsNeedUpdate = false; + } + if (material.isSpriteMaterial) { + p_uniforms.setValue(_gl, "center", object.center); + } + p_uniforms.setValue(_gl, "modelViewMatrix", object.modelViewMatrix); + p_uniforms.setValue(_gl, "normalMatrix", object.normalMatrix); + p_uniforms.setValue(_gl, "modelMatrix", object.matrixWorld); + if (material.isShaderMaterial || material.isRawShaderMaterial) { + const groups = material.uniformsGroups; + for (let i = 0, l2 = groups.length;i < l2; i++) { + const group = groups[i]; + uniformsGroups.update(group, program); + uniformsGroups.bind(group, program); + } + } + return program; + } + function markUniformsLightsNeedsUpdate(uniforms, value2) { + uniforms.ambientLightColor.needsUpdate = value2; + uniforms.lightProbe.needsUpdate = value2; + uniforms.directionalLights.needsUpdate = value2; + uniforms.directionalLightShadows.needsUpdate = value2; + uniforms.pointLights.needsUpdate = value2; + uniforms.pointLightShadows.needsUpdate = value2; + uniforms.spotLights.needsUpdate = value2; + uniforms.spotLightShadows.needsUpdate = value2; + uniforms.rectAreaLights.needsUpdate = value2; + uniforms.hemisphereLights.needsUpdate = value2; + } + function materialNeedsLights(material) { + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true; + } + this.getActiveCubeFace = function() { + return _currentActiveCubeFace; + }; + this.getActiveMipmapLevel = function() { + return _currentActiveMipmapLevel; + }; + this.getRenderTarget = function() { + return _currentRenderTarget; + }; + this.setRenderTargetTextures = function(renderTarget, colorTexture, depthTexture) { + properties.get(renderTarget.texture).__webglTexture = colorTexture; + properties.get(renderTarget.depthTexture).__webglTexture = depthTexture; + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__hasExternalTextures = true; + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; + if (!renderTargetProperties.__autoAllocateDepthBuffer) { + if (extensions.has("WEBGL_multisampled_render_to_texture") === true) { + console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"); + renderTargetProperties.__useRenderToTexture = false; + } + } + }; + this.setRenderTargetFramebuffer = function(renderTarget, defaultFramebuffer) { + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; + }; + const _scratchFrameBuffer = _gl.createFramebuffer(); + this.setRenderTarget = function(renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) { + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + if (renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTargetProperties.__useDefaultFramebuffer !== undefined) { + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + useDefaultFramebuffer = false; + } else if (renderTargetProperties.__webglFramebuffer === undefined) { + textures.setupRenderTarget(renderTarget); + } else if (renderTargetProperties.__hasExternalTextures) { + textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture); + } else if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__boundDepthTexture !== depthTexture) { + if (depthTexture !== null && properties.has(depthTexture) && (renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height)) { + throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size."); + } + textures.setupDepthRenderbuffer(renderTarget); + } + } + const texture = renderTarget.texture; + if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + isRenderTarget3D = true; + } + const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget) { + if (Array.isArray(__webglFramebuffer[activeCubeFace])) { + framebuffer = __webglFramebuffer[activeCubeFace][activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer[activeCubeFace]; + } + isCube = true; + } else if (renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) { + framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer; + } else { + if (Array.isArray(__webglFramebuffer)) { + framebuffer = __webglFramebuffer[activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer; + } + } + _currentViewport.copy(renderTarget.viewport); + _currentScissor.copy(renderTarget.scissor); + _currentScissorTest = renderTarget.scissorTest; + } else { + _currentViewport.copy(_viewport3).multiplyScalar(_pixelRatio).floor(); + _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(); + _currentScissorTest = _scissorTest; + } + if (activeMipmapLevel !== 0) { + framebuffer = _scratchFrameBuffer; + } + const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (framebufferBound && useDefaultFramebuffer) { + state.drawBuffers(renderTarget, framebuffer); + } + state.viewport(_currentViewport); + state.scissor(_currentScissor); + state.setScissorTest(_currentScissorTest); + if (isCube) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel); + } else if (isRenderTarget3D) { + const textureProperties = properties.get(renderTarget.texture); + const layer = activeCubeFace; + _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer); + } else if (renderTarget !== null && activeMipmapLevel !== 0) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel); + } + _currentMaterialId = -1; + }; + this.readRenderTargetPixels = function(renderTarget, x2, y3, width2, height2, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + return; + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + try { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); + return; + } + if (!capabilities.textureTypeReadable(textureType)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); + return; + } + if (x2 >= 0 && x2 <= renderTarget.width - width2 && (y3 >= 0 && y3 <= renderTarget.height - height2)) { + _gl.readPixels(x2, y3, width2, height2, utils.convert(textureFormat), utils.convert(textureType), buffer); + } + } finally { + const framebuffer2 = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer2); + } + } + }; + this.readRenderTargetPixelsAsync = async function(renderTarget, x2, y3, width2, height2, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format."); + } + if (!capabilities.textureTypeReadable(textureType)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type."); + } + if (x2 >= 0 && x2 <= renderTarget.width - width2 && (y3 >= 0 && y3 <= renderTarget.height - height2)) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + const glBuffer = _gl.createBuffer(); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.bufferData(_gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ); + _gl.readPixels(x2, y3, width2, height2, utils.convert(textureFormat), utils.convert(textureType), 0); + const currFramebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, currFramebuffer); + const sync = _gl.fenceSync(_gl.SYNC_GPU_COMMANDS_COMPLETE, 0); + _gl.flush(); + await probeAsync2(_gl, sync, 4); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.getBufferSubData(_gl.PIXEL_PACK_BUFFER, 0, buffer); + _gl.deleteBuffer(glBuffer); + _gl.deleteSync(sync); + return buffer; + } else { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range."); + } + } + }; + this.copyFramebufferToTexture = function(texture, position2 = null, level = 0) { + if (texture.isTexture !== true) { + warnOnce2("WebGLRenderer: copyFramebufferToTexture function signature has changed."); + position2 = arguments[0] || null; + texture = arguments[1]; + } + const levelScale = Math.pow(2, -level); + const width2 = Math.floor(texture.image.width * levelScale); + const height2 = Math.floor(texture.image.height * levelScale); + const x2 = position2 !== null ? position2.x : 0; + const y3 = position2 !== null ? position2.y : 0; + textures.setTexture2D(texture, 0); + _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, x2, y3, width2, height2); + state.unbindTexture(); + }; + const _srcFramebuffer = _gl.createFramebuffer(); + const _dstFramebuffer = _gl.createFramebuffer(); + this.copyTextureToTexture = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null) { + if (srcTexture.isTexture !== true) { + warnOnce2("WebGLRenderer: copyTextureToTexture function signature has changed."); + dstPosition = arguments[0] || null; + srcTexture = arguments[1]; + dstTexture = arguments[2]; + dstLevel = arguments[3] || 0; + srcRegion = null; + } + if (dstLevel === null) { + if (srcLevel !== 0) { + warnOnce2("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."); + dstLevel = srcLevel; + srcLevel = 0; + } else { + dstLevel = 0; + } + } + let width2, height2, depth2, minX, minY, minZ; + let dstX, dstY, dstZ; + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[dstLevel] : srcTexture.image; + if (srcRegion !== null) { + width2 = srcRegion.max.x - srcRegion.min.x; + height2 = srcRegion.max.y - srcRegion.min.y; + depth2 = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1; + minX = srcRegion.min.x; + minY = srcRegion.min.y; + minZ = srcRegion.isBox3 ? srcRegion.min.z : 0; + } else { + const levelScale = Math.pow(2, -srcLevel); + width2 = Math.floor(image.width * levelScale); + height2 = Math.floor(image.height * levelScale); + if (srcTexture.isDataArrayTexture) { + depth2 = image.depth; + } else if (srcTexture.isData3DTexture) { + depth2 = Math.floor(image.depth * levelScale); + } else { + depth2 = 1; + } + minX = 0; + minY = 0; + minZ = 0; + } + if (dstPosition !== null) { + dstX = dstPosition.x; + dstY = dstPosition.y; + dstZ = dstPosition.z; + } else { + dstX = 0; + dstY = 0; + dstZ = 0; + } + const glFormat = utils.convert(dstTexture.format); + const glType = utils.convert(dstTexture.type); + let glTarget; + if (dstTexture.isData3DTexture) { + textures.setTexture3D(dstTexture, 0); + glTarget = _gl.TEXTURE_3D; + } else if (dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture) { + textures.setTexture2DArray(dstTexture, 0); + glTarget = _gl.TEXTURE_2D_ARRAY; + } else { + textures.setTexture2D(dstTexture, 0); + glTarget = _gl.TEXTURE_2D; + } + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment); + const currentUnpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH); + const currentUnpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT); + const currentUnpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS); + const currentUnpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS); + const currentUnpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES); + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, minX); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, minY); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, minZ); + const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture; + const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture; + if (srcTexture.isDepthTexture) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + const srcRenderTargetProperties = properties.get(srcTextureProperties.__renderTarget); + const dstRenderTargetProperties = properties.get(dstTextureProperties.__renderTarget); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer); + for (let i = 0;i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(srcTexture).__webglTexture, srcLevel, minZ + i); + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(dstTexture).__webglTexture, dstLevel, dstZ + i); + } + _gl.blitFramebuffer(minX, minY, width2, height2, dstX, dstY, width2, height2, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST); + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else if (srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has(srcTexture)) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, _srcFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, _dstFramebuffer); + for (let i = 0;i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i); + } else { + _gl.framebufferTexture2D(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel); + } + if (isDst3D) { + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i); + } else { + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel); + } + if (srcLevel !== 0) { + _gl.blitFramebuffer(minX, minY, width2, height2, dstX, dstY, width2, height2, _gl.COLOR_BUFFER_BIT, _gl.NEAREST); + } else if (isDst3D) { + _gl.copyTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width2, height2); + } else { + _gl.copyTexSubImage2D(glTarget, dstLevel, dstX, dstY, minX, minY, width2, height2); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else { + if (isDst3D) { + if (srcTexture.isDataTexture || srcTexture.isData3DTexture) { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, glType, image.data); + } else if (dstTexture.isCompressedArrayTexture) { + _gl.compressedTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, image.data); + } else { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, glType, image); + } + } else { + if (srcTexture.isDataTexture) { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width2, height2, glFormat, glType, image.data); + } else if (srcTexture.isCompressedTexture) { + _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data); + } else { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width2, height2, glFormat, glType, image); + } + } + } + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, currentUnpackRowLen); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages); + if (dstLevel === 0 && dstTexture.generateMipmaps) { + _gl.generateMipmap(glTarget); + } + state.unbindTexture(); + }; + this.copyTextureToTexture3D = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0) { + if (srcTexture.isTexture !== true) { + warnOnce2("WebGLRenderer: copyTextureToTexture3D function signature has changed."); + srcRegion = arguments[0] || null; + dstPosition = arguments[1] || null; + srcTexture = arguments[2]; + dstTexture = arguments[3]; + level = arguments[4] || 0; + } + warnOnce2('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'); + return this.copyTextureToTexture(srcTexture, dstTexture, srcRegion, dstPosition, level); + }; + this.initRenderTarget = function(target) { + if (properties.get(target).__webglFramebuffer === undefined) { + textures.setupRenderTarget(target); + } + }; + this.initTexture = function(texture) { + if (texture.isCubeTexture) { + textures.setTextureCube(texture, 0); + } else if (texture.isData3DTexture) { + textures.setTexture3D(texture, 0); + } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + textures.setTexture2DArray(texture, 0); + } else { + textures.setTexture2D(texture, 0); + } + state.unbindTexture(); + }; + this.resetState = function() { + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + state.reset(); + bindingStates.reset(); + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + get coordinateSystem() { + return WebGLCoordinateSystem2; + } + get outputColorSpace() { + return this._outputColorSpace; + } + set outputColorSpace(colorSpace) { + this._outputColorSpace = colorSpace; + const gl = this.getContext(); + gl.drawingBufferColorspace = ColorManagement2._getDrawingBufferColorSpace(colorSpace); + gl.unpackColorSpace = ColorManagement2._getUnpackColorSpace(); + } + } + exports2.ACESFilmicToneMapping = ACESFilmicToneMapping2; + exports2.AddEquation = AddEquation2; + exports2.AddOperation = AddOperation2; + exports2.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode2; + exports2.AdditiveBlending = AdditiveBlending2; + exports2.AgXToneMapping = AgXToneMapping2; + exports2.AlphaFormat = AlphaFormat2; + exports2.AlwaysCompare = AlwaysCompare2; + exports2.AlwaysDepth = AlwaysDepth2; + exports2.AlwaysStencilFunc = AlwaysStencilFunc2; + exports2.AmbientLight = AmbientLight2; + exports2.AnimationAction = AnimationAction2; + exports2.AnimationClip = AnimationClip2; + exports2.AnimationLoader = AnimationLoader2; + exports2.AnimationMixer = AnimationMixer2; + exports2.AnimationObjectGroup = AnimationObjectGroup2; + exports2.AnimationUtils = AnimationUtils2; + exports2.ArcCurve = ArcCurve2; + exports2.ArrayCamera = ArrayCamera2; + exports2.ArrowHelper = ArrowHelper2; + exports2.AttachedBindMode = AttachedBindMode2; + exports2.Audio = Audio2; + exports2.AudioAnalyser = AudioAnalyser2; + exports2.AudioContext = AudioContext2; + exports2.AudioListener = AudioListener2; + exports2.AudioLoader = AudioLoader2; + exports2.AxesHelper = AxesHelper2; + exports2.BackSide = BackSide2; + exports2.BasicDepthPacking = BasicDepthPacking2; + exports2.BasicShadowMap = BasicShadowMap2; + exports2.BatchedMesh = BatchedMesh2; + exports2.Bone = Bone2; + exports2.BooleanKeyframeTrack = BooleanKeyframeTrack2; + exports2.Box2 = Box22; + exports2.Box3 = Box32; + exports2.Box3Helper = Box3Helper2; + exports2.BoxGeometry = BoxGeometry2; + exports2.BoxHelper = BoxHelper2; + exports2.BufferAttribute = BufferAttribute2; + exports2.BufferGeometry = BufferGeometry2; + exports2.BufferGeometryLoader = BufferGeometryLoader2; + exports2.ByteType = ByteType2; + exports2.Cache = Cache2; + exports2.Camera = Camera2; + exports2.CameraHelper = CameraHelper2; + exports2.CanvasTexture = CanvasTexture2; + exports2.CapsuleGeometry = CapsuleGeometry2; + exports2.CatmullRomCurve3 = CatmullRomCurve32; + exports2.CineonToneMapping = CineonToneMapping2; + exports2.CircleGeometry = CircleGeometry2; + exports2.ClampToEdgeWrapping = ClampToEdgeWrapping2; + exports2.Clock = Clock2; + exports2.Color = Color2; + exports2.ColorKeyframeTrack = ColorKeyframeTrack2; + exports2.ColorManagement = ColorManagement2; + exports2.CompressedArrayTexture = CompressedArrayTexture2; + exports2.CompressedCubeTexture = CompressedCubeTexture2; + exports2.CompressedTexture = CompressedTexture2; + exports2.CompressedTextureLoader = CompressedTextureLoader2; + exports2.ConeGeometry = ConeGeometry2; + exports2.ConstantAlphaFactor = ConstantAlphaFactor2; + exports2.ConstantColorFactor = ConstantColorFactor2; + exports2.Controls = Controls2; + exports2.CubeCamera = CubeCamera2; + exports2.CubeReflectionMapping = CubeReflectionMapping2; + exports2.CubeRefractionMapping = CubeRefractionMapping2; + exports2.CubeTexture = CubeTexture2; + exports2.CubeTextureLoader = CubeTextureLoader2; + exports2.CubeUVReflectionMapping = CubeUVReflectionMapping2; + exports2.CubicBezierCurve = CubicBezierCurve2; + exports2.CubicBezierCurve3 = CubicBezierCurve32; + exports2.CubicInterpolant = CubicInterpolant2; + exports2.CullFaceBack = CullFaceBack2; + exports2.CullFaceFront = CullFaceFront2; + exports2.CullFaceFrontBack = CullFaceFrontBack2; + exports2.CullFaceNone = CullFaceNone2; + exports2.Curve = Curve2; + exports2.CurvePath = CurvePath2; + exports2.CustomBlending = CustomBlending2; + exports2.CustomToneMapping = CustomToneMapping2; + exports2.CylinderGeometry = CylinderGeometry2; + exports2.Cylindrical = Cylindrical2; + exports2.Data3DTexture = Data3DTexture2; + exports2.DataArrayTexture = DataArrayTexture2; + exports2.DataTexture = DataTexture2; + exports2.DataTextureLoader = DataTextureLoader2; + exports2.DataUtils = DataUtils2; + exports2.DecrementStencilOp = DecrementStencilOp2; + exports2.DecrementWrapStencilOp = DecrementWrapStencilOp2; + exports2.DefaultLoadingManager = DefaultLoadingManager2; + exports2.DepthFormat = DepthFormat2; + exports2.DepthStencilFormat = DepthStencilFormat2; + exports2.DepthTexture = DepthTexture2; + exports2.DetachedBindMode = DetachedBindMode2; + exports2.DirectionalLight = DirectionalLight2; + exports2.DirectionalLightHelper = DirectionalLightHelper2; + exports2.DiscreteInterpolant = DiscreteInterpolant2; + exports2.DodecahedronGeometry = DodecahedronGeometry2; + exports2.DoubleSide = DoubleSide2; + exports2.DstAlphaFactor = DstAlphaFactor2; + exports2.DstColorFactor = DstColorFactor2; + exports2.DynamicCopyUsage = DynamicCopyUsage2; + exports2.DynamicDrawUsage = DynamicDrawUsage2; + exports2.DynamicReadUsage = DynamicReadUsage2; + exports2.EdgesGeometry = EdgesGeometry2; + exports2.EllipseCurve = EllipseCurve2; + exports2.EqualCompare = EqualCompare2; + exports2.EqualDepth = EqualDepth2; + exports2.EqualStencilFunc = EqualStencilFunc2; + exports2.EquirectangularReflectionMapping = EquirectangularReflectionMapping2; + exports2.EquirectangularRefractionMapping = EquirectangularRefractionMapping2; + exports2.Euler = Euler2; + exports2.EventDispatcher = EventDispatcher2; + exports2.ExtrudeGeometry = ExtrudeGeometry2; + exports2.FileLoader = FileLoader2; + exports2.Float16BufferAttribute = Float16BufferAttribute2; + exports2.Float32BufferAttribute = Float32BufferAttribute2; + exports2.FloatType = FloatType2; + exports2.Fog = Fog2; + exports2.FogExp2 = FogExp22; + exports2.FramebufferTexture = FramebufferTexture2; + exports2.FrontSide = FrontSide2; + exports2.Frustum = Frustum2; + exports2.GLBufferAttribute = GLBufferAttribute2; + exports2.GLSL1 = GLSL12; + exports2.GLSL3 = GLSL32; + exports2.GreaterCompare = GreaterCompare2; + exports2.GreaterDepth = GreaterDepth2; + exports2.GreaterEqualCompare = GreaterEqualCompare2; + exports2.GreaterEqualDepth = GreaterEqualDepth2; + exports2.GreaterEqualStencilFunc = GreaterEqualStencilFunc2; + exports2.GreaterStencilFunc = GreaterStencilFunc2; + exports2.GridHelper = GridHelper2; + exports2.Group = Group2; + exports2.HalfFloatType = HalfFloatType2; + exports2.HemisphereLight = HemisphereLight2; + exports2.HemisphereLightHelper = HemisphereLightHelper2; + exports2.IcosahedronGeometry = IcosahedronGeometry2; + exports2.ImageBitmapLoader = ImageBitmapLoader2; + exports2.ImageLoader = ImageLoader2; + exports2.ImageUtils = ImageUtils2; + exports2.IncrementStencilOp = IncrementStencilOp2; + exports2.IncrementWrapStencilOp = IncrementWrapStencilOp2; + exports2.InstancedBufferAttribute = InstancedBufferAttribute2; + exports2.InstancedBufferGeometry = InstancedBufferGeometry2; + exports2.InstancedInterleavedBuffer = InstancedInterleavedBuffer2; + exports2.InstancedMesh = InstancedMesh2; + exports2.Int16BufferAttribute = Int16BufferAttribute2; + exports2.Int32BufferAttribute = Int32BufferAttribute2; + exports2.Int8BufferAttribute = Int8BufferAttribute2; + exports2.IntType = IntType2; + exports2.InterleavedBuffer = InterleavedBuffer2; + exports2.InterleavedBufferAttribute = InterleavedBufferAttribute2; + exports2.Interpolant = Interpolant2; + exports2.InterpolateDiscrete = InterpolateDiscrete2; + exports2.InterpolateLinear = InterpolateLinear2; + exports2.InterpolateSmooth = InterpolateSmooth2; + exports2.InvertStencilOp = InvertStencilOp2; + exports2.KeepStencilOp = KeepStencilOp2; + exports2.KeyframeTrack = KeyframeTrack2; + exports2.LOD = LOD2; + exports2.LatheGeometry = LatheGeometry2; + exports2.Layers = Layers2; + exports2.LessCompare = LessCompare2; + exports2.LessDepth = LessDepth2; + exports2.LessEqualCompare = LessEqualCompare2; + exports2.LessEqualDepth = LessEqualDepth2; + exports2.LessEqualStencilFunc = LessEqualStencilFunc2; + exports2.LessStencilFunc = LessStencilFunc2; + exports2.Light = Light2; + exports2.LightProbe = LightProbe2; + exports2.Line = Line4; + exports2.Line3 = Line32; + exports2.LineBasicMaterial = LineBasicMaterial2; + exports2.LineCurve = LineCurve2; + exports2.LineCurve3 = LineCurve32; + exports2.LineDashedMaterial = LineDashedMaterial2; + exports2.LineLoop = LineLoop2; + exports2.LineSegments = LineSegments3; + exports2.LinearFilter = LinearFilter2; + exports2.LinearInterpolant = LinearInterpolant2; + exports2.LinearMipMapLinearFilter = LinearMipMapLinearFilter2; + exports2.LinearMipMapNearestFilter = LinearMipMapNearestFilter2; + exports2.LinearMipmapLinearFilter = LinearMipmapLinearFilter2; + exports2.LinearMipmapNearestFilter = LinearMipmapNearestFilter2; + exports2.LinearSRGBColorSpace = LinearSRGBColorSpace2; + exports2.LinearToneMapping = LinearToneMapping2; + exports2.LinearTransfer = LinearTransfer2; + exports2.Loader = Loader2; + exports2.LoaderUtils = LoaderUtils2; + exports2.LoadingManager = LoadingManager2; + exports2.LoopOnce = LoopOnce2; + exports2.LoopPingPong = LoopPingPong2; + exports2.LoopRepeat = LoopRepeat2; + exports2.LuminanceAlphaFormat = LuminanceAlphaFormat2; + exports2.LuminanceFormat = LuminanceFormat2; + exports2.MOUSE = MOUSE2; + exports2.Material = Material2; + exports2.MaterialLoader = MaterialLoader2; + exports2.MathUtils = MathUtils2; + exports2.Matrix2 = Matrix22; + exports2.Matrix3 = Matrix32; + exports2.Matrix4 = Matrix42; + exports2.MaxEquation = MaxEquation2; + exports2.Mesh = Mesh2; + exports2.MeshBasicMaterial = MeshBasicMaterial2; + exports2.MeshDepthMaterial = MeshDepthMaterial2; + exports2.MeshDistanceMaterial = MeshDistanceMaterial2; + exports2.MeshLambertMaterial = MeshLambertMaterial2; + exports2.MeshMatcapMaterial = MeshMatcapMaterial2; + exports2.MeshNormalMaterial = MeshNormalMaterial2; + exports2.MeshPhongMaterial = MeshPhongMaterial2; + exports2.MeshPhysicalMaterial = MeshPhysicalMaterial2; + exports2.MeshStandardMaterial = MeshStandardMaterial2; + exports2.MeshToonMaterial = MeshToonMaterial2; + exports2.MinEquation = MinEquation2; + exports2.MirroredRepeatWrapping = MirroredRepeatWrapping2; + exports2.MixOperation = MixOperation2; + exports2.MultiplyBlending = MultiplyBlending2; + exports2.MultiplyOperation = MultiplyOperation2; + exports2.NearestFilter = NearestFilter2; + exports2.NearestMipMapLinearFilter = NearestMipMapLinearFilter2; + exports2.NearestMipMapNearestFilter = NearestMipMapNearestFilter2; + exports2.NearestMipmapLinearFilter = NearestMipmapLinearFilter2; + exports2.NearestMipmapNearestFilter = NearestMipmapNearestFilter2; + exports2.NeutralToneMapping = NeutralToneMapping2; + exports2.NeverCompare = NeverCompare2; + exports2.NeverDepth = NeverDepth2; + exports2.NeverStencilFunc = NeverStencilFunc2; + exports2.NoBlending = NoBlending2; + exports2.NoColorSpace = NoColorSpace2; + exports2.NoToneMapping = NoToneMapping2; + exports2.NormalAnimationBlendMode = NormalAnimationBlendMode2; + exports2.NormalBlending = NormalBlending2; + exports2.NotEqualCompare = NotEqualCompare2; + exports2.NotEqualDepth = NotEqualDepth2; + exports2.NotEqualStencilFunc = NotEqualStencilFunc2; + exports2.NumberKeyframeTrack = NumberKeyframeTrack2; + exports2.Object3D = Object3D2; + exports2.ObjectLoader = ObjectLoader2; + exports2.ObjectSpaceNormalMap = ObjectSpaceNormalMap2; + exports2.OctahedronGeometry = OctahedronGeometry2; + exports2.OneFactor = OneFactor2; + exports2.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor2; + exports2.OneMinusConstantColorFactor = OneMinusConstantColorFactor2; + exports2.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor2; + exports2.OneMinusDstColorFactor = OneMinusDstColorFactor2; + exports2.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor2; + exports2.OneMinusSrcColorFactor = OneMinusSrcColorFactor2; + exports2.OrthographicCamera = OrthographicCamera2; + exports2.PCFShadowMap = PCFShadowMap2; + exports2.PCFSoftShadowMap = PCFSoftShadowMap2; + exports2.PMREMGenerator = PMREMGenerator2; + exports2.Path = Path3; + exports2.PerspectiveCamera = PerspectiveCamera2; + exports2.Plane = Plane2; + exports2.PlaneGeometry = PlaneGeometry3; + exports2.PlaneHelper = PlaneHelper2; + exports2.PointLight = PointLight2; + exports2.PointLightHelper = PointLightHelper2; + exports2.Points = Points2; + exports2.PointsMaterial = PointsMaterial2; + exports2.PolarGridHelper = PolarGridHelper2; + exports2.PolyhedronGeometry = PolyhedronGeometry2; + exports2.PositionalAudio = PositionalAudio2; + exports2.PropertyBinding = PropertyBinding2; + exports2.PropertyMixer = PropertyMixer2; + exports2.QuadraticBezierCurve = QuadraticBezierCurve2; + exports2.QuadraticBezierCurve3 = QuadraticBezierCurve32; + exports2.Quaternion = Quaternion2; + exports2.QuaternionKeyframeTrack = QuaternionKeyframeTrack2; + exports2.QuaternionLinearInterpolant = QuaternionLinearInterpolant2; + exports2.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format2; + exports2.RED_RGTC1_Format = RED_RGTC1_Format2; + exports2.REVISION = REVISION2; + exports2.RGBADepthPacking = RGBADepthPacking2; + exports2.RGBAFormat = RGBAFormat2; + exports2.RGBAIntegerFormat = RGBAIntegerFormat2; + exports2.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format2; + exports2.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format2; + exports2.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format2; + exports2.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format2; + exports2.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format2; + exports2.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format2; + exports2.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format2; + exports2.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format2; + exports2.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format2; + exports2.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format2; + exports2.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format2; + exports2.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format2; + exports2.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format2; + exports2.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format2; + exports2.RGBA_BPTC_Format = RGBA_BPTC_Format2; + exports2.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format2; + exports2.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format2; + exports2.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format2; + exports2.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format2; + exports2.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format2; + exports2.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format2; + exports2.RGBDepthPacking = RGBDepthPacking2; + exports2.RGBFormat = RGBFormat2; + exports2.RGBIntegerFormat = RGBIntegerFormat2; + exports2.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format2; + exports2.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format2; + exports2.RGB_ETC1_Format = RGB_ETC1_Format2; + exports2.RGB_ETC2_Format = RGB_ETC2_Format2; + exports2.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format2; + exports2.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format2; + exports2.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format2; + exports2.RGDepthPacking = RGDepthPacking2; + exports2.RGFormat = RGFormat2; + exports2.RGIntegerFormat = RGIntegerFormat2; + exports2.RawShaderMaterial = RawShaderMaterial2; + exports2.Ray = Ray2; + exports2.Raycaster = Raycaster2; + exports2.RectAreaLight = RectAreaLight2; + exports2.RedFormat = RedFormat2; + exports2.RedIntegerFormat = RedIntegerFormat2; + exports2.ReinhardToneMapping = ReinhardToneMapping2; + exports2.RenderTarget = RenderTarget2; + exports2.RenderTarget3D = RenderTarget3D2; + exports2.RenderTargetArray = RenderTargetArray2; + exports2.RepeatWrapping = RepeatWrapping2; + exports2.ReplaceStencilOp = ReplaceStencilOp2; + exports2.ReverseSubtractEquation = ReverseSubtractEquation2; + exports2.RingGeometry = RingGeometry2; + exports2.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format2; + exports2.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format2; + exports2.SRGBColorSpace = SRGBColorSpace2; + exports2.SRGBTransfer = SRGBTransfer2; + exports2.Scene = Scene2; + exports2.ShaderChunk = ShaderChunk2; + exports2.ShaderLib = ShaderLib2; + exports2.ShaderMaterial = ShaderMaterial2; + exports2.ShadowMaterial = ShadowMaterial2; + exports2.Shape = Shape2; + exports2.ShapeGeometry = ShapeGeometry2; + exports2.ShapePath = ShapePath3; + exports2.ShapeUtils = ShapeUtils2; + exports2.ShortType = ShortType2; + exports2.Skeleton = Skeleton2; + exports2.SkeletonHelper = SkeletonHelper2; + exports2.SkinnedMesh = SkinnedMesh2; + exports2.Source = Source2; + exports2.Sphere = Sphere2; + exports2.SphereGeometry = SphereGeometry3; + exports2.Spherical = Spherical2; + exports2.SphericalHarmonics3 = SphericalHarmonics32; + exports2.SplineCurve = SplineCurve2; + exports2.SpotLight = SpotLight2; + exports2.SpotLightHelper = SpotLightHelper2; + exports2.Sprite = Sprite2; + exports2.SpriteMaterial = SpriteMaterial2; + exports2.SrcAlphaFactor = SrcAlphaFactor2; + exports2.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor2; + exports2.SrcColorFactor = SrcColorFactor2; + exports2.StaticCopyUsage = StaticCopyUsage2; + exports2.StaticDrawUsage = StaticDrawUsage2; + exports2.StaticReadUsage = StaticReadUsage2; + exports2.StereoCamera = StereoCamera2; + exports2.StreamCopyUsage = StreamCopyUsage2; + exports2.StreamDrawUsage = StreamDrawUsage2; + exports2.StreamReadUsage = StreamReadUsage2; + exports2.StringKeyframeTrack = StringKeyframeTrack2; + exports2.SubtractEquation = SubtractEquation2; + exports2.SubtractiveBlending = SubtractiveBlending2; + exports2.TOUCH = TOUCH2; + exports2.TangentSpaceNormalMap = TangentSpaceNormalMap2; + exports2.TetrahedronGeometry = TetrahedronGeometry2; + exports2.Texture = Texture2; + exports2.TextureLoader = TextureLoader2; + exports2.TextureUtils = TextureUtils2; + exports2.TimestampQuery = TimestampQuery2; + exports2.TorusGeometry = TorusGeometry2; + exports2.TorusKnotGeometry = TorusKnotGeometry3; + exports2.Triangle = Triangle2; + exports2.TriangleFanDrawMode = TriangleFanDrawMode2; + exports2.TriangleStripDrawMode = TriangleStripDrawMode2; + exports2.TrianglesDrawMode = TrianglesDrawMode2; + exports2.TubeGeometry = TubeGeometry3; + exports2.UVMapping = UVMapping2; + exports2.Uint16BufferAttribute = Uint16BufferAttribute2; + exports2.Uint32BufferAttribute = Uint32BufferAttribute2; + exports2.Uint8BufferAttribute = Uint8BufferAttribute2; + exports2.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute2; + exports2.Uniform = Uniform2; + exports2.UniformsGroup = UniformsGroup2; + exports2.UniformsLib = UniformsLib2; + exports2.UniformsUtils = UniformsUtils2; + exports2.UnsignedByteType = UnsignedByteType2; + exports2.UnsignedInt248Type = UnsignedInt248Type2; + exports2.UnsignedInt5999Type = UnsignedInt5999Type2; + exports2.UnsignedIntType = UnsignedIntType2; + exports2.UnsignedShort4444Type = UnsignedShort4444Type2; + exports2.UnsignedShort5551Type = UnsignedShort5551Type2; + exports2.UnsignedShortType = UnsignedShortType2; + exports2.VSMShadowMap = VSMShadowMap2; + exports2.Vector2 = Vector22; + exports2.Vector3 = Vector32; + exports2.Vector4 = Vector42; + exports2.VectorKeyframeTrack = VectorKeyframeTrack2; + exports2.VideoFrameTexture = VideoFrameTexture2; + exports2.VideoTexture = VideoTexture2; + exports2.WebGL3DRenderTarget = WebGL3DRenderTarget2; + exports2.WebGLArrayRenderTarget = WebGLArrayRenderTarget2; + exports2.WebGLCoordinateSystem = WebGLCoordinateSystem2; + exports2.WebGLCubeRenderTarget = WebGLCubeRenderTarget2; + exports2.WebGLRenderTarget = WebGLRenderTarget2; + exports2.WebGLRenderer = WebGLRenderer2; + exports2.WebGLUtils = WebGLUtils2; + exports2.WebGPUCoordinateSystem = WebGPUCoordinateSystem2; + exports2.WebXRController = WebXRController2; + exports2.WireframeGeometry = WireframeGeometry3; + exports2.WrapAroundEnding = WrapAroundEnding2; + exports2.ZeroCurvatureEnding = ZeroCurvatureEnding2; + exports2.ZeroFactor = ZeroFactor2; + exports2.ZeroSlopeEnding = ZeroSlopeEnding2; + exports2.ZeroStencilOp = ZeroStencilOp2; + exports2.createCanvasElement = createCanvasElement2; +}); + +// src/external/ffl.js/FFLShaderMaterial.js +var require_FFLShaderMaterial = __commonJS((exports2, module2) => { + (function(root2, factory) { + if (typeof define === "function" && define.amd) { + define(["three"], factory); + } else if (typeof module2 === "object" && module2.exports) { + module2.exports = factory(require_three()); + } else { + root2.FFLShaderMaterial = factory(root2.THREE); + } + })(typeof self !== "undefined" ? self : exports2, function(THREE2) { + const _FFLShader_vert = ` +// 頂点シェーダーに入力される attribute 変数 +//attribute vec4 position; //!< 入力: 位置情報 +//attribute vec2 uv; //!< 入力: テクスチャー座標 +//attribute vec3 normal; //!< 入力: 法線ベクトル +// All provided by three.js ^^ + +// vertex color is not actually the color of the shape, as such +// it is a custom attribute _COLOR in the glTF + +attribute vec4 _color; //!< 入力: 頂点の色 +attribute vec3 tangent; //!< 入力: 異方位 + +// フラグメントシェーダーへの入力 +varying vec4 v_color; //!< 出力: 頂点の色 +varying vec4 v_position; //!< 出力: 位置情報 +varying vec3 v_normal; //!< 出力: 法線ベクトル +varying vec3 v_tangent; //!< 出力: 異方位 +varying vec2 v_texCoord; //!< 出力: テクスチャー座標 + +// ユニフォーム +//uniform mat3 normalMatrix; //!< ユニフォーム: モデルの法線用行列 +//uniform mat4 modelViewMatrix; //!< ユニフォーム: プロジェクション行列 +//uniform mat4 projectionMatrix; //!< ユニフォーム: モデル行列 +// All provided by three.js ^^ + +// skinning_pars_vertex.glsl.js +#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif + +void main() +{ + + // begin_vertex.glsl.js + vec3 transformed = vec3( position ); +// skinbase_vertex.glsl.js +#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); + // skinning_vertex.glsl.js + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif + +//#ifdef FFL_COORDINATE_MODE_NORMAL + // 頂点座標を変換 + v_position = modelViewMatrix * vec4(transformed, 1.0); + gl_Position = projectionMatrix * v_position; + + vec3 objectNormal = normal; + vec3 objectTangent = tangent.xyz; +// skinnormal_vertex.glsl.js +#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + +#endif + + // 法線も変換 + //v_normal = mat3(inverse(u_mv)) * a_normal; + v_normal = normalize(normalMatrix * objectNormal); +//#elif defined(FFL_COORDINATE_MODE_NONE) +// // 頂点座標を変換 +// gl_Position = vec4(a_position.x, a_position.y * -1.0, a_position.z, a_position.w); +// v_position = a_position; +// +// v_normal = a_normal; +//#endif + + // その他の情報も書き出す + v_texCoord = uv; + // safe normalize + if (tangent != vec3(0.0, 0.0, 0.0)) + { + v_tangent = normalize(normalMatrix * objectTangent); + } + else + { + v_tangent = vec3(0.0, 0.0, 0.0); + } + + v_color = _color; +} +`; + const _FFLShader_frag = ` +// +// sample.flg +// Fragment shader +// Copyright (c) 2014 Nintendo Co., Ltd. All rights reserved. +// +// + +#ifdef GL_ES +precision mediump float; +#else +# define lowp +# define mediump +# define highp +#endif + + +// +// 定数定義ファイル +// + +/// シェーダーモード +#define FFL_SHADER_MODE_UR 0 +#define FFL_SHADER_MODE_UB 1 + +/// 変調処理のマクロ +#define FFL_MODULATE_MODE_CONSTANT 0 +#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 +#define FFL_MODULATE_MODE_RGB_LAYERED 2 +#define FFL_MODULATE_MODE_ALPHA 3 +#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 +#define FFL_MODULATE_MODE_ALPHA_OPA 5 + +/// スペキュラのモード +#define FFL_SPECULAR_MODE_BLINN 0 +#define FFL_SPECULAR_MODE_ANISO 1 + +/// ライトのON/OFF +#define FFL_LIGHT_MODE_DISABLE 0 +#define FFL_LIGHT_MODE_ENABLE 1 + +/// フラグメントのディスカードモード +#define FFL_DISCARD_FRAGMENT_DISABLE 0 +#define FFL_DISCARD_FRAGMENT_ENABLE 1 + +/// 座標変換モード +#define FFL_COORDINATE_MODE_NONE 0 +#define FFL_COORDINATE_MODE_NORMAL 1 + +// +// 関数の定義ファイル +// + +/** + * @brief 異方性反射の反射率を計算します。 + * @param[in] light ライトの向き + * @param[in] tangent 接線 + * @param[in] eye 視線の向き + * @param[in] power 鋭さ + */ +mediump float calculateAnisotropicSpecular(mediump vec3 light, mediump vec3 tangent, mediump vec3 eye, mediump float power ) +{ + mediump float dotLT = dot(light, tangent); + mediump float dotVT = dot(eye, tangent); + mediump float dotLN = sqrt(1.0 - dotLT * dotLT); + mediump float dotVR = dotLN*sqrt(1.0 - dotVT * dotVT) - dotLT * dotVT; + + return pow(max(0.0, dotVR), power); +} + +/** + * @brief 異方性反射の反射率を計算します。 + * @param[in] light ライトの向き + * @param[in] normal 法線 + * @param[in] eye 視線の向き + * @param[in] power 鋭さ + */ +mediump float calculateBlinnSpecular(mediump vec3 light, mediump vec3 normal, mediump vec3 eye, mediump float power) +{ + return pow(max(dot(reflect(-light, normal), eye), 0.0), power); +} + +/** + * @brief 異方性反射、ブリン反射をブレンドします。 + * @param[in] blend ブレンド率 + * @param[in] blinn ブリンの値 + * @param[in] aniso 異方性の値 + */ +mediump float calculateSpecularBlend(mediump float blend, mediump float blinn, mediump float aniso) +{ + return mix(aniso, blinn, blend); +} + +/** + * @brief アンビエントを計算します。 + * @param[in] light ライト + * @param[in] material マテリアル + */ +mediump vec3 calculateAmbientColor(mediump vec3 light, mediump vec3 material) +{ + return light * material; +} + +/** + * @brief 拡散を計算します。 + * @param[in] light ライト + * @param[in] material マテリアル + * @param[in] ln ライトと法線の内積 + */ +mediump vec3 calculateDiffuseColor(mediump vec3 light, mediump vec3 material, mediump float ln) +{ + return light * material * ln; +} + +/** + * @brief 鏡面反射を計算します。 + * @param[in] light ライト + * @param[in] material マテリアル + * @param[in] reflection 反射率 + * @param[in] strength 幅 + */ +mediump vec3 calculateSpecularColor(mediump vec3 light, mediump vec3 material, mediump float reflection, mediump float strength) +{ + return light * material * reflection * strength; +} + +/** + * @brief リムを計算します。 + * @param[in] color リム色 + * @param[in] normalZ 法線のZ方向 + * @param[in] width リム幅 + * @param[in] power リムの鋭さ + */ +mediump vec3 calculateRimColor(mediump vec3 color, mediump float normalZ, mediump float width, mediump float power) +{ + return color * pow(width * (1.0 - abs(normalZ)), power); +} + +/** + * @brief ライト方向と法線の内積を求める + * @note 特殊な実装になっています。 + */ +mediump float calculateDot(mediump vec3 light, mediump vec3 normal) +{ + return max(dot(light, normal), 0.1); +} + +// フラグメントシェーダーに入力される varying 変数 +varying mediump vec4 v_color; //!< 出力: 頂点の色 +varying highp vec4 v_position; //!< 出力: 位置情報 +varying highp vec3 v_normal; //!< 出力: 法線ベクトル +// NOTE: ^^ Those two need to be highp to avoid weird black dot issue on Android +varying mediump vec3 v_tangent; //!< 出力: 異方位 +varying mediump vec2 v_texCoord; //!< 出力: テクスチャー座標 + +/// constカラー +uniform mediump vec4 u_const1; ///< constカラー1 +uniform mediump vec4 u_const2; ///< constカラー2 +uniform mediump vec4 u_const3; ///< constカラー3 + +/// ライト設定 +uniform mediump vec3 u_light_ambient; ///< カメラ空間のライト方向 +uniform mediump vec3 u_light_diffuse; ///< 拡散光用ライト +uniform mediump vec3 u_light_dir; +uniform bool u_light_enable; +uniform mediump vec3 u_light_specular; ///< 鏡面反射用ライト強度 + +/// マテリアル設定 +uniform mediump vec3 u_material_ambient; ///< 環境光用マテリアル設定 +uniform mediump vec3 u_material_diffuse; ///< 拡散光用マテリアル設定 +uniform mediump vec3 u_material_specular; ///< 鏡面反射用マテリアル設定 +uniform int u_material_specular_mode; ///< スペキュラの反射モード(CharModelに依存する設定のためub_modulateにしている) +uniform mediump float u_material_specular_power; ///< スペキュラの鋭さ(0.0を指定すると頂点カラーの設定が利用される) + +/// 変調設定 +uniform int u_mode; ///< 描画モード + +/// リム設定 +uniform mediump vec3 u_rim_color; +uniform mediump float u_rim_power; + +// サンプラー +uniform sampler2D s_texture; + + +// ------------------------------------------------------- +// メイン文 +void main() +{ + mediump vec4 color; + + mediump float specularPower = u_material_specular_power; + mediump float rimWidth = v_color.a; + +//#ifdef FFL_MODULATE_MODE_CONSTANT + if(u_mode == FFL_MODULATE_MODE_CONSTANT) + { + color = u_const1; + } + // modified to handle u_const1 alpha: +//#elif defined(FFL_MODULATE_MODE_TEXTURE_DIRECT) + else if(u_mode == FFL_MODULATE_MODE_TEXTURE_DIRECT) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.rgb, u_const1.a * texel.a); + } +//#elif defined(FFL_MODULATE_MODE_RGB_LAYERED) + else if(u_mode == FFL_MODULATE_MODE_RGB_LAYERED) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.r * u_const1.rgb + texel.g * u_const2.rgb + texel.b * u_const3.rgb, u_const1.a * texel.a); + } +//#elif defined(FFL_MODULATE_MODE_ALPHA) + else if(u_mode == FFL_MODULATE_MODE_ALPHA) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(u_const1.rgb, u_const1.a * texel.r); + } +//#elif defined(FFL_MODULATE_MODE_LUMINANCE_ALPHA) + else if(u_mode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.g * u_const1.rgb, u_const1.a * texel.r); + } +//#elif defined(FFL_MODULATE_MODE_ALPHA_OPA) + else if(u_mode == FFL_MODULATE_MODE_ALPHA_OPA) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.r * u_const1.rgb, u_const1.a); + } +//#endif + + // avoids little outline around mask elements + if(u_mode != FFL_MODULATE_MODE_CONSTANT && color.a == 0.0) + { + discard; + } + +//#ifdef FFL_LIGHT_MODE_ENABLE + if(u_light_enable) + { + /// 環境光の計算 + mediump vec3 ambient = calculateAmbientColor(u_light_ambient.xyz, u_material_ambient.xyz); + + /// 法線ベクトルの正規化 + mediump vec3 norm = normalize(v_normal); + + /// 視線ベクトル + mediump vec3 eye = normalize(-v_position.xyz); + + // ライトの向き + mediump float fDot = calculateDot(u_light_dir, norm); + + /// Diffuse計算 + mediump vec3 diffuse = calculateDiffuseColor(u_light_diffuse.xyz, u_material_diffuse.xyz, fDot); + + /// Specular計算 + mediump float specularBlinn = calculateBlinnSpecular(u_light_dir, norm, eye, u_material_specular_power); + + /// Specularの値を確保する変数を宣言 + mediump float reflection; + mediump float strength = v_color.g; + if(u_material_specular_mode == 0) + { + /// Blinnモデルの場合 + strength = 1.0; + reflection = specularBlinn; + } + else + { + /// Aisoモデルの場合 + mediump float specularAniso = calculateAnisotropicSpecular(u_light_dir, v_tangent, eye, u_material_specular_power); + reflection = calculateSpecularBlend(v_color.r, specularBlinn, specularAniso); + } + /// Specularの色を取得 + mediump vec3 specular = calculateSpecularColor(u_light_specular.xyz, u_material_specular.xyz, reflection, strength); + + // リムの色を計算 + mediump vec3 rimColor = calculateRimColor(u_rim_color.rgb, norm.z, rimWidth, u_rim_power); + + // カラーの計算 + color.rgb = (ambient + diffuse) * color.rgb + specular + rimColor; + } +//#endif + + gl_FragColor = color; +} +`; + + class FFLShaderMaterial extends THREE2.ShaderMaterial { + static defaultLightAmbient = new THREE2.Color(0.73, 0.73, 0.73); + static defaultLightDiffuse = new THREE2.Color(0.6, 0.6, 0.6); + static defaultLightSpecular = new THREE2.Color(0.7, 0.7, 0.7); + static defaultLightDir = new THREE2.Vector3(-0.4531539381, 0.4226179123, 0.7848858833); + static defaultRimColor = new THREE2.Color(0.3, 0.3, 0.3); + static defaultRimPower = 2; + static defaultLightDirection = this.defaultLightDir; + static materialParams = [ + { + ambient: new THREE2.Color(0.85, 0.75, 0.75), + diffuse: new THREE2.Color(0.75, 0.75, 0.75), + specular: new THREE2.Color(0.3, 0.3, 0.3), + specularPower: 1.2, + specularMode: 0 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0, 0, 0), + specularPower: 40, + specularMode: 1 + }, + { + ambient: new THREE2.Color(0.9, 0.85, 0.85), + diffuse: new THREE2.Color(0.75, 0.75, 0.75), + specular: new THREE2.Color(0.22, 0.22, 0.22), + specularPower: 1.5, + specularMode: 0 + }, + { + ambient: new THREE2.Color(0.85, 0.75, 0.75), + diffuse: new THREE2.Color(0.75, 0.75, 0.75), + specular: new THREE2.Color(0.3, 0.3, 0.3), + specularPower: 1.2, + specularMode: 0 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0.35, 0.35, 0.35), + specularPower: 10, + specularMode: 1 + }, + { + ambient: new THREE2.Color(0.75, 0.75, 0.75), + diffuse: new THREE2.Color(0.72, 0.72, 0.72), + specular: new THREE2.Color(0.3, 0.3, 0.3), + specularPower: 1.5, + specularMode: 0 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0, 0, 0), + specularPower: 40, + specularMode: 1 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0, 0, 0), + specularPower: 40, + specularMode: 1 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0, 0, 0), + specularPower: 40, + specularMode: 1 + }, + { + ambient: new THREE2.Color(0.95622, 0.95622, 0.95622), + diffuse: new THREE2.Color(0.49673, 0.49673, 0.49673), + specular: new THREE2.Color(0.24099, 0.24099, 0.24099), + specularPower: 3, + specularMode: 0 + }, + { + ambient: new THREE2.Color(0.95622, 0.95622, 0.95622), + diffuse: new THREE2.Color(1.08497, 1.08497, 1.08497), + specular: new THREE2.Color(0.2409, 0.2409, 0.2409), + specularPower: 3, + specularMode: 0 + } + ]; + constructor(options = {}) { + const uniforms = { + u_light_ambient: { + value: FFLShaderMaterial.defaultLightAmbient + }, + u_light_diffuse: { + value: FFLShaderMaterial.defaultLightDiffuse + }, + u_light_specular: { + value: FFLShaderMaterial.defaultLightSpecular + }, + u_light_dir: { value: FFLShaderMaterial.defaultLightDir.clone() }, + u_light_enable: { value: true }, + u_rim_color: { value: FFLShaderMaterial.defaultRimColor }, + u_rim_power: { value: FFLShaderMaterial.defaultRimPower } + }; + super({ + vertexShader: _FFLShader_vert, + fragmentShader: _FFLShader_frag, + uniforms + }); + this._modulateType = 0; + this.useSpecularModeBlinn = false; + this.setValues(options); + } + get color() { + if (!this.uniforms.u_const1) { + return null; + } else if (this._color3) { + return this._color3; + } + const color4 = this.uniforms.u_const1.value; + const color3 = new THREE2.Color(color4.x, color4.y, color4.z); + this._color3 = color3; + return color3; + } + set color(value2) { + function toColor4(color, opacity2 = 1) { + return new THREE2.Vector4(color.r, color.g, color.b, opacity2); + } + if (Array.isArray(value2)) { + this.uniforms.u_const1 = { value: toColor4(value2[0]) }; + this.uniforms.u_const2 = { value: toColor4(value2[1]) }; + this.uniforms.u_const3 = { value: toColor4(value2[2]) }; + return; + } + const color3 = value2 ? value2 : new THREE2.Color(1, 1, 1); + this._color3 = color3; + const opacity = this.opacity; + if (this._opacity) { + delete this._opacity; + } + this.uniforms.u_const1 = { value: toColor4(color3, opacity) }; + } + get opacity() { + if (!this.uniforms.u_const1) { + return this._opacity ? this._opacity : 1; + } + return this.uniforms.u_const1.value.w; + } + set opacity(value2) { + if (!this.uniforms || !this.uniforms.u_const1) { + this._opacity = 1; + return; + } + this.uniforms.u_const1.value.w = value2; + } + get modulateMode() { + return this.uniforms.u_mode ? this.uniforms.u_mode.value : null; + } + set modulateMode(value2) { + this.uniforms.u_mode = { value: value2 }; + } + get lightEnable() { + return this.uniforms.u_light_enable ? this.uniforms.u_light_enable.value : null; + } + set lightEnable(value2) { + this.uniforms.u_light_enable = { value: value2 }; + } + set useSpecularModeBlinn(value2) { + this._useSpecularModeBlinn = value2; + if (this._modulateType !== undefined) { + this.modulateType = this._modulateType; + } + } + get useSpecularModeBlinn() { + return this._useSpecularModeBlinn; + } + get modulateType() { + return this._modulateType; + } + set modulateType(value2) { + const matParam = FFLShaderMaterial.materialParams[value2]; + if (!matParam) { + return; + } + this._modulateType = value2; + this.uniforms.u_material_ambient = { value: matParam.ambient }; + this.uniforms.u_material_diffuse = { value: matParam.diffuse }; + this.uniforms.u_material_specular = { value: matParam.specular }; + this.uniforms.u_material_specular_mode = { + value: this._useSpecularModeBlinn ? 0 : matParam.specularMode + }; + this.uniforms.u_material_specular_power = { value: matParam.specularPower }; + } + get map() { + return this.uniforms.s_texture ? this.uniforms.s_texture.value : null; + } + set map(value2) { + this.uniforms.s_texture = { value: value2 }; + } + get lightDirection() { + return this.uniforms.u_light_dir.value; + } + set lightDirection(value2) { + this.uniforms.u_light_dir = { value: value2 }; + } + } + return FFLShaderMaterial; + }); +}); + +// src/external/ffl.js/LUTShaderMaterial.js +var require_LUTShaderMaterial = __commonJS((exports2, module2) => { + (function(root2, factory) { + if (typeof define === "function" && define.amd) { + define(["three"], factory); + } else if (typeof module2 === "object" && module2.exports) { + module2.exports = factory(require_three()); + } else { + root2.LUTShaderMaterial = factory(root2.THREE); + } + })(typeof self !== "undefined" ? self : exports2, function(THREE2) { + const _LUTShader_vert = ` +#define AGX_FEATURE_ALBEDO_TEXTURE +/** + * @file LUT.vsh + * @brief LUT + * @since 2014/10/02 + * + * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. + */ + +// シェーダーの種類毎に設定されるマクロリスト +// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 +// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 +// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 +// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 +// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 +// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 +// AGX_FEATURE_SKIN_MASK 肌マスクが有効(uColor0) +// AGX_FEATURE_HAIR_MASK 髪マスクが有効(uColor1) +// AGX_FEATURE_ALPHA_TEST アルファテストが有効 +// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(uColor2) +// AGX_FEATURE_DISABLE_LIGHT ライトが無効 +// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 +// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 +// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 +// AGX_FEATURE_MII Miiを描画する +// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant +// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct +// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered +// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha +// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha +// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa +// +// AGX_BONE_MAX ボーンの最大数 + +#ifdef GL_ES +precision highp float; +#else +# define lowp +# define mediump +# define highp +#endif + +//#ifndef AGX_BONE_MAX +//# define AGX_BONE_MAX 15 +//#endif +#ifndef AGX_DIR_LIGHT_MAX +# define AGX_DIR_LIGHT_MAX 2 +#endif + +// ---------------------------------------- +// 頂点シェーダーに入力される attribute 変数 +//attribute highp vec3 position; //!< 入力:[ 1 : 1 ] 位置情報 +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) +//attribute mediump vec2 uv; //!< 入力:[ 1 : 5 ] テクスチャー座標 +#endif +//attribute mediump vec3 normal; //!< 入力:[ 1 : 2 ] 法線ベクトル +//attribute mediump vec4 aBoneIndex; //!< 入力:[ 1 : 3 ] ボーンのインデックス(最大4つ) +//attribute mediump vec4 aBoneWeight; //!< 入力:[ 1 : 4 ] ボーンの影響度(最大4つ) +#if defined(AGX_FEATURE_VERTEX_COLOR) +//attribute lowp vec4 _color; //!< 入力:[ 1 : 6 ] 頂点カラー +#endif +#if defined(AGX_FEATURE_BUMP_TEXTURE) +//attribute mediump vec3 tangent; //!< 入力:[ 1 : 7 ] 接線ベクトル +#endif + +// ^^ Commented attributes are provided by three.js. + +// ---------------------------------------- +// 頂点シェーダーに入力される uniform 変数 +//uniform highp mat4 modelViewMatrix; //!< 入力:[ 4 / 4 : 4 ] モデルの合成行列 +//uniform mat4 projectionMatrix; +//uniform highp mat4 viewMatrix; //!< 入力:[ 4 / 4 : 8 ] モデルのビュー行列 +//uniform mediump mat3 normalMatrix; //!< 入力:[ 3 / 3 : 11 ] モデルの法線用行列 +//uniform highp mat4 modelMatrix; //!< 入力:[ 4 / 4 : 15 ] モデルのワールド変換行列 +//uniform lowp int uBoneCount; //!< 入力:[ 1 / 1 : 16 ] ボーンの個数 +//uniform highp mat4 uBoneMatrices[AGX_BONE_MAX]; //!< 入力:[ 4 x 15 / 60 : 76 ] ボーンの行列配列 +//uniform mediump mat3 uBoneNormalMatrices[AGX_BONE_MAX]; //!< 入力:[ 3 x 15 / 45 : 121 ] ボーンの法線行列配列 +// ^^ Unused in favor of three.js skinning. +uniform lowp int uDirLightCount; //!< 入力:[ 1 / 1 : 122 ] 方向ライトの数 +uniform mediump vec4 uDirLightDirAndType0;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 +uniform mediump vec4 uDirLightDirAndType1;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 +uniform mediump vec3 uDirLightColor0; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー +uniform mediump vec3 uDirLightColor1; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー +uniform mediump vec3 uHSLightSkyColor; //!< 入力:[ 1 / 1 : 127 ] 半球ライトのスカイカラー +uniform mediump vec3 uHSLightGroundColor; //!< 入力:[ 1 / 1 : 128 ] 半球ライトのグラウンドカラー +//uniform mediump vec3 cameraPosition; //!< 入力:[ 1 / 1 : 129 ] カメラの位置 +// ^^ previously uEyePt +uniform mediump float uAlpha; //!< 入力:[ 1 / 1 : 130 ] アルファ値 + +// ^^ Commented uniforms are provided by three.js. + +// ---------------------------------------- +// フラグメントシェーダーに渡される varying 変数 +varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 +#if !defined(AGX_FEATURE_BUMP_TEXTURE) +varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 +#endif +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) +varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV +#endif +// camera +varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル +#if !defined(AGX_FEATURE_DISABLE_LIGHT) +// punctual light +varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 +varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル +// GI +varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー +// Lighting Result +varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 +#endif +// Reflect +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) +varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル +#endif + +// skinning_pars_vertex.glsl.js +#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif + +// ------------------------------------------------------------ +// 頂点シェーダーのエントリーポイント +// ------------------------------------------------------------ +void main() +{ + // ------------------------------------------------------------ + // 頂点変換用の処理 + // ------------------------------------------------------------ + highp vec4 position_; //!< 最終的な頂点 + mediump vec3 normal_; //!< 最終的な法線 + mediump vec3 tangent_; //!< 最終的な接線 + highp vec4 positionWorld; //!< ワールド空間上での頂点 + + + // begin_vertex.glsl.js + vec3 transformed = vec3( position ); +// skinbase_vertex.glsl.js +#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); + // skinning_vertex.glsl.js + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif + + // ---------------------------------------- + // ボーンが存在しない場合は位置と法線に手を加えない + position_ = vec4(transformed.xyz, 1.0); + + + + normal_ = normal; +#if defined(AGX_FEATURE_BUMP_TEXTURE) + tangent_ = tangent.xyz; +#endif + // skinnormal_vertex.glsl.js +#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + + normal_ = vec4( skinMatrix * vec4( normal_, 0.0 ) ).xyz; +#if defined(AGX_FEATURE_BUMP_TEXTURE) + tangent_ = vec4( skinMatrix * vec4( tangent_, 0.0 ) ).xyz; +#endif // defined(AGX_FEATURE_BUMP_TEXTURE) +#endif // USE_SKINNING + + // ---------------------------------------- + // ワールド上での位置を求める + positionWorld = modelMatrix * position_; + // 最終結果を行う + position_ = projectionMatrix * modelViewMatrix * position_; + normal_ = normalize(normalMatrix * normal_); +#if defined(AGX_FEATURE_BUMP_TEXTURE) + tangent = normalize(normalMatrix * tangent_); +#endif + + // ---------------------------------------- + // 計算結果を保持させる + gl_Position = position_; +#if !defined(AGX_FEATURE_BUMP_TEXTURE) + vNormal = normal_; +#endif +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) + // テクスチャー座標を設定する + vTexcoord0 = uv; +#endif + // モデルの色を指定する +#if defined(AGX_FEATURE_VERTEX_COLOR) + lowp vec4 modelColor = aColor; + +#else + lowp vec4 modelColor = vec4(1.0, 1.0, 1.0, 1.0); +#endif + + // プリマルチプライドアルファ +#if defined(AGX_FEATURE_PREMULTIPLY_ALPHA) + modelColor *= uAlpha; +#else + modelColor.a *= uAlpha; +#endif + + + // ------------------------------------------------------------ + // ライト用の処理 + // ------------------------------------------------------------ + mediump vec3 eyeVecWorld; //!< ワールド状態での視線ベクトル + mediump vec3 eyeVec; //!< 最終的にフラグメントシェーダーに渡す視線ベクトル(バンプの有無によって、ワールド座標系になったり、タンジェント座標系になったりする) + + vec4 eye = modelViewMatrix * position_; + + // 視線ベクトルを取得する + //eyeVecWorld = normalize(cameraPosition - positionWorld.xyz); + eyeVecWorld = normalize(-(eye.xyz) - positionWorld.xyz);//normalize(cameraPosition - positionWorld.xyz); + eyeVec = eyeVecWorld; + + lowp vec3 diffuseColor = vec3(0.0); // バーテックスシェーダーで計算できるディフューズの色をここに格納する + +# if defined(AGX_FEATURE_BUMP_TEXTURE) + // Normal, Binormal, Tangent を取得する + mediump vec3 n = normal; + mediump vec3 t = tangent; + mediump vec3 b = cross(n, t); + // 接空間からローカルへ変換する行列を設定する(mat3(N, T, B)の逆行列) + mediump mat3 tangentMatrix = mat3(t.x, b.x, n.x, t.y, b.y, n.y, t.z, b.z, n.z); + // 視線ベクトルを接空間へ + vEyeVecWorldOrTangent.xyz = tangentMatrix * eyeVec; +#else + vEyeVecWorldOrTangent.xyz = eyeVec; +#endif + +#if !defined(AGX_FEATURE_DISABLE_LIGHT) + // punctual lightの設定 + if (uDirLightCount > 0) + { + mediump vec3 lightDir; + + // 方向ライト + if (uDirLightDirAndType0.w < 0.0) { lightDir = uDirLightDirAndType0.xyz; } + // 点光源ライト + else { lightDir = uDirLightDirAndType0.xyz - positionWorld.xyz; } + lightDir = normalize(lightDir); + +# if defined(AGX_FEATURE_BUMP_TEXTURE) + // ライトを接空間へ + vPunctualLightDirWorldOrTangent.xyz = tangentMatrix * lightDir; +# else + vPunctualLightDirWorldOrTangent.xyz = lightDir; +# endif + + // Halfベクトルを求める + vPunctualLightHalfVecWorldOrTangent.xyz = normalize(vPunctualLightDirWorldOrTangent.xyz + vEyeVecWorldOrTangent.xyz); + + // Diffuse計算 + diffuseColor += (uDirLightColor0.rgb * clamp(dot(lightDir, normal_), 0.0, 1.0)); + } + if (uDirLightCount > 1) + { + mediump vec3 lightDir; + + // 方向ライト + if (uDirLightDirAndType1.w < 0.0) { lightDir = uDirLightDirAndType1.xyz; } + // 点光源ライト + else { lightDir = uDirLightDirAndType1.xyz - positionWorld.xyz; } + lightDir = normalize(lightDir); + + diffuseColor += max(dot(lightDir, normal_), 0.0) * uDirLightColor1; + } + // ライトは1.0を超えないように + diffuseColor = min(diffuseColor, 1.0); +#endif + +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) + { + // キューブ環境マップ用の反射ベクトルを求める +// vReflectDir = reflect(normalize(positionWorld.xyz - cameraPosition), normal_); + + // スフィア環境マップ用の反射ベクトルを求める +// vReflectDir = normalize((uViewMatrix * vec4(normal_, 0.0)).xyz) * 0.5 + 0.5; + + // ビュー座標系での位置と法線を取得 + mediump vec3 viewNormal = normalize(mat3(uViewMatrix) * normal_); + mediump vec4 viewPosition = uViewMatrix * positionWorld; + viewPosition = viewPosition / viewPosition.w; + // ビュー座標系での頂点ベクトルを取得 + viewPosition.z = 1.0 - viewPosition.z; + mediump vec3 viewPositionVec = normalize(viewPosition.xyz); + // ビュー座標系での反射ベクトルを求める + mediump vec3 viewReflect = viewPositionVec - 2.0 * dot(viewPositionVec, viewNormal) * viewNormal; + // 両面スフィア環境マップではないので、反射ベクトルを調整 + viewReflect = normalize(viewReflect - vec3(0.0, 0.0, 1.5)); + // 反射ベクトルをテクスチャー座標系へ + vReflectDir = viewReflect * 0.5 + 0.5; + + // 公式 +// mediump vec3 viewPositionVec = normalize(vec3(uViewMatrix * positionWorld)); +// mediump vec3 viewReflectVec = viewPositionVec - 2.0 * dot(viewPositionVec, normal_) * normal; +// mediump float m = 2.0 * sqrt(viewReflectVec.x * viewReflectVec.x + +// viewReflectVec.y * viewReflectVec.y + +// (viewReflectVec.z + 1.0) * (viewReflectVec.z * 1.0)); +// vReflectDir = viewReflectVec / m + 0.5; + + // 別版 +// mediump vec3 posW = positionWorld.xyz; +// mediump vec3 dir = normalize(mat3(uViewMatrix) * normal); +// +// mediump float radius = 75.0; +// mediump vec3 posWDir = dot(dir, posW) * dir; +// mediump vec3 posWDirV = posW - posWDir; +// mediump float lengthDir = sqrt(radius * radius - dot(posWDirV, posWDirV)) - length(posWDir); +// vReflectDir = normalize(posW + dir * lengthDir) * 0.5 + 0.5; + } +#endif + +#if !defined(AGX_FEATURE_DISABLE_LIGHT) + // GIの計算 + { + mediump vec3 hemiColor; + mediump vec3 sky = uHSLightSkyColor; + mediump vec3 ground = uHSLightGroundColor; + + { + mediump float skyRatio = (normal_.y + 1.0) * 0.5; + hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); + diffuseColor += hemiColor; + } + + { +// mediump vec3 reflectDir = -reflect(normal_, eyeVecWorld); // おそらくコレで良いはず + mediump vec3 reflectDir = 2.0 * dot(eyeVecWorld, normal_) * normal_ - eyeVecWorld; // 多少冗長でも、正しい計算で行なう + + mediump float skyRatio = (reflectDir.y + 1.0) * 0.5; + hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); + vGISpecularLightColor.rgb = hemiColor; + } + } +#endif + + // モデルの色を設定 + vModelColor = modelColor; +#if !defined(AGX_FEATURE_DISABLE_LIGHT) + vDiffuseColor.rgb = diffuseColor; +#endif +} +`; + const _LUTShader_frag = ` +#define AGX_FEATURE_ALBEDO_TEXTURE +#define AGX_FEATURE_MII +/** + * @file LUT.fsh + * @brief LUT + * @since 2014/10/02 + * + * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. + */ + +// シェーダーの種類毎に設定されるマクロリスト +// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 +// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 +// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 +// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 +// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 +// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 +// AGX_FEATURE_SKIN_MASK 肌マスクが有効(uColor0) +// AGX_FEATURE_HAIR_MASK 髪マスクが有効(uColor1) +// AGX_FEATURE_ALPHA_TEST アルファテストが有効 +// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(uColor2) +// AGX_FEATURE_DISABLE_LIGHT ライトが無効 +// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 +// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 +// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 +// AGX_FEATURE_MII Miiを描画する +// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant +// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct +// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered +// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha +// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha +// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa + +#ifdef GL_ES +precision mediump float; +#else +# define lowp +# define mediump +# define highp +#endif + +/// 変調処理のマクロ +#define FFL_MODULATE_MODE_CONSTANT 0 +#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 +#define FFL_MODULATE_MODE_RGB_LAYERED 2 +#define FFL_MODULATE_MODE_ALPHA 3 +#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 +#define FFL_MODULATE_MODE_ALPHA_OPA 5 + +// ---------------------------------------- +// フラグメントシェーダーに入力される uniform 変数 +uniform int uMode; ///< 描画モード +uniform bool uAlphaTest; +uniform bool uLightEnable; +uniform mediump vec4 uColor0; //!< 入力:[ 1 : 1 ] カラー0 (OR 肌カラー) +uniform mediump vec4 uColor1; //!< 入力:[ 1 : 2 ] カラー1 (OR 髪カラー) +uniform mediump vec4 uColor2; //!< 入力:[ 1 : 3 ] カラー2 (OR フェードアウトカラー) +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +uniform mediump vec3 uLightColor; //!< 入力:[ 1 : 4 ] ライトの色 +//#endif + +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) +uniform sampler2D uAlbedoTexture; //!< 入力: テクスチャー +#endif +#if defined(AGX_FEATURE_BUMP_TEXTURE) +uniform sampler2D uNormalTexture; //!< 入力: ノーマルマップ +#endif +#if defined(AGX_FEATURE_MASK_TEXTURE) +uniform sampler2D uMaskTexture; //!< 入力:マスクテクスチャー +#endif +#if defined(AGX_FEATURE_ALPHA_TEXTURE) +uniform sampler2D uAlphaTexture; //!< 入力:アルファテクスチャー +#endif +uniform sampler2D uLUTSpecTexture; //!< 入力: スペキュラーLUT +uniform sampler2D uLUTFresTexture; //!< 入力: フレネルLUT +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) +uniform sampler2D uSphereMapTexture; //!< 入力: スフィア環境マップ +#endif + +// ---------------------------------------- +// フラグメントシェーダーに渡される varying 変数 +varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 +#if !defined(AGX_FEATURE_BUMP_TEXTURE) +varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 +#endif +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) +varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV +#endif +// camera +varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +// punctual light +varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 +varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル +// GI +varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー +// Lighting Result +varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 +//#endif +// Reflect +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) +varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル +#endif + +// ------------------------------------------------------------ +// フラグメントシェーダーのエントリーポイント +// ------------------------------------------------------------ +void main() +{ + + // ディフューズカラーを取得 + lowp vec4 albedoColor = vec4(1.0, 1.0, 1.0, 1.0); + + // ============================================================ + // Mii + // ============================================================ +#if defined(AGX_FEATURE_MII) + + //#if defined(AGX_FEATURE_MII_CONSTANT) + if(uMode == FFL_MODULATE_MODE_CONSTANT) + { + albedoColor = uColor0; + } + //#elif defined(AGX_FEATURE_MII_TEXTURE_DIRECT) + else if(uMode == FFL_MODULATE_MODE_TEXTURE_DIRECT) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + } + //#elif defined(AGX_FEATURE_MII_RGB_LAYERED) + else if(uMode == FFL_MODULATE_MODE_RGB_LAYERED) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(albedoColor.r * uColor0.rgb + albedoColor.g * uColor1.rgb + albedoColor.b * uColor2.rgb, + uColor0.a * albedoColor.a); + } + //#elif defined(AGX_FEATURE_MII_ALPHA) + else if(uMode == FFL_MODULATE_MODE_ALPHA) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(uColor0.rgb, uColor0.a * albedoColor.r); + } + //#elif defined(AGX_FEATURE_MII_LUMINANCE_ALPHA) + else if(uMode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(albedoColor.g * uColor0.rgb, uColor0.a * albedoColor.r); + } + //#elif defined(AGX_FEATURE_MII_ALPHA_OPA) + else if(uMode == FFL_MODULATE_MODE_ALPHA_OPA) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(albedoColor.r * uColor0.rgb, uColor0.a); + } +//#endif + + albedoColor = albedoColor * vModelColor; +#endif + + // ============================================================ + // Albedo Texture + // ============================================================ +#if !defined(AGX_FEATURE_MII) && defined(AGX_FEATURE_ALBEDO_TEXTURE) + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); +#endif +#if defined(AGX_FEATURE_ALPHA_TEXTURE) + albedoColor.a = texture2D(uAlphaTexture, vTexcoord0).r; +#endif + + // ============================================================ + // Color Mask + // ============================================================ + // ---------------------------------------- + // Deprecated +#if defined(AGX_FEATURE_ALPHA_COLOR_FILTER) + // 一部の場所にColor0を反映する + albedoColor.rgb = (albedoColor.rgb * albedoColor.a + uColor0.rgb * (1.0 - albedoColor.a)); + albedoColor.a = 1.0; +#elif defined(AGX_FEATURE_MASK_TEXTURE) + lowp vec3 maskTextureColor = texture2D(uMaskTexture, vTexcoord0).rgb; + +# if defined(AGX_FEATURE_SKIN_MASK) && defined(AGX_FEATURE_HAIR_MASK) + // 肌と髪両方マスクが存在する + lowp float maskColorValue = maskTextureColor.g + maskTextureColor.b; + lowp vec3 maskColor = maskTextureColor.g * uColor0.rgb + maskTextureColor.b * uColor1.rgb; + albedoColor.rgb = (albedoColor.rgb * (1.0 - maskColorValue) + maskColor); + +# elif defined(AGX_FEATURE_SKIN_MASK) + // 肌しかマスクが存在しない + albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.g) + maskTextureColor.g * uColor0.rgb); + +# elif defined(AGX_FEATURE_HAIR_MASK) + // 髪しかマスクが存在しない + albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.b) + maskTextureColor.b * uColor1.rgb); + +# endif +#endif + + // アルベドに頂点カラーを掛ける + albedoColor *= vModelColor; + + // ============================================================ + // Alpha test + // ============================================================ +//#if defined(AGX_FEATURE_ALPHA_TEST) + if (uAlphaTest && albedoColor.a < 0.5) { discard; } +//#endif + + // ============================================================ + // Bumpmap + // ============================================================ + // 頂点からの情報 + lowp vec3 normalWorldOrTangent; +#if defined(AGX_FEATURE_BUMP_TEXTURE) + // バンプマップから法線を取得する + mediump vec3 bumpNormal = texture2D(uNormalTexture, vTexcoord0).rgb; + + // 法線の正規化は処理が重いのでいったん正規化しない様に... +// normalWorldOrTangent = normalize(bumpNormal * 2.0 - 1.0); + normalWorldOrTangent = bumpNormal * 2.0 - 1.0; + +#else + // 法線を正規化して取得する + normalWorldOrTangent = normalize(vNormal); +#endif + + // ============================================================ + // Lighting + // ============================================================ + // 最終的なカラー情報 + lowp vec4 colorOut = vec4(0.0, 0.0, 0.0, albedoColor.a); // 最終的に出力される色 + lowp vec3 fresnel = vec3(0.0, 0.0, 0.0); // フレネル + lowp vec3 specular = vec3(0.0, 0.0, 0.0); // スペキュラー + +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +if (uLightEnable) { + + // BRDFの計算を行う(バンプマッピングの場合は接空間) + lowp vec3 N = normalWorldOrTangent; + lowp vec3 V = vEyeVecWorldOrTangent.xyz;//normalize(vEyeVecWorldOrTangent.xyz); + lowp vec3 I = vPunctualLightDirWorldOrTangent.xyz;//normalize(vPunctualLightDirWorldOrTangent.xyz); + lowp vec3 H = vPunctualLightHalfVecWorldOrTangent.xyz;//normalize(vPunctualLightHalfVecWorldOrTangent.xyz); + + + // ---------------------------------------- + // punctual light + // 平行光源や点光源などの厳密なライティング計算を行なうもの + { + lowp float fSpecular = dot(N, H); + + lowp float specularIntensity = texture2D(uLUTSpecTexture, vec2(fSpecular)).r; + specular = (specularIntensity * uLightColor.rgb); + } + + // ---------------------------------------- + // GI + // 半球ライトやIBL、SHのように法線方向に半球積分された結果でライティング計算を行なうもの + { + lowp float fFresnel = dot(N, V); + lowp float fresnelIntensity = texture2D(uLUTFresTexture, vec2(fFresnel)).r; + + fresnel = (fresnelIntensity * vGISpecularLightColor.rgb); + } +} +//#endif + +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) + // スフィア環境マップ + specular += texture2D(uSphereMapTexture, vReflectDir.xy).rgb; +#endif + + // ============================================================ + // Specular Mask + // ============================================================ +#if !defined(AGX_FEATURE_ALPHA_COLOR_FILTER) && defined(AGX_FEATURE_MASK_TEXTURE) + // スペキュラーマスク + specular = specular * maskTextureColor.r + fresnel; +#else + specular += fresnel; +#endif + + // ============================================================ + // Output + // ============================================================ +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +if (uLightEnable) + colorOut.rgb = vDiffuseColor.rgb * albedoColor.rgb + specular; +//#else +else + colorOut.rgb = albedoColor.rgb; +//#endif + + // フェードアウトを実装する +#if defined(AGX_FEATURE_FADE_OUT_COLOR) + colorOut.rgb = (colorOut.rgb * (1.0 - uColor2.a)) + (uColor2.rgb * uColor2.a); +#endif + + // 色を反映させる + gl_FragColor = colorOut; + + //#include + //#include +} +`; + + class HermitianCurve { + constructor(keys2) { + this.keys = keys2.sort((a2, b3) => a2.x - b3.x); + } + interpolate(t4, p0, p1, m0, m1) { + const h00 = 2 * t4 * t4 * t4 - 3 * t4 * t4 + 1; + const h10 = t4 * t4 * t4 - 2 * t4 * t4 + t4; + const h01 = -2 * t4 * t4 * t4 + 3 * t4 * t4; + const h11 = t4 * t4 * t4 - t4 * t4; + return h00 * p0 + h10 * m0 + h01 * p1 + h11 * m1; + } + clamp(value2, min, max) { + return Math.min(Math.max(value2, min), max); + } + generateLUT(lutSize = 512) { + const lut = new Uint8Array(lutSize); + let keyIdx = 0; + for (let i = 0;i < lutSize; i++) { + const pos = i / (lutSize - 1); + while (keyIdx < this.keys.length - 2 && pos > this.keys[keyIdx + 1].x) { + keyIdx++; + } + const p0 = this.keys[keyIdx]; + const p1 = this.keys[keyIdx + 1]; + let t4 = (pos - p0.x) / (p1.x - p0.x); + t4 = isNaN(t4) ? 0 : t4; + const y3 = this.interpolate(t4, p0.y, p1.y, p0.dx * (p1.x - p0.x), p1.dx * (p1.x - p0.x)); + lut[i] = Math.round(this.clamp(y3, 0, 1) * 255); + } + return lut; + } + } + + class LUTShaderMaterial extends THREE2.ShaderMaterial { + static LUTSpecularTextureType = { + NONE: 0, + DEFAULT_02: 1, + SKIN_01: 2, + MAX: 3 + }; + static LUTFresnelTextureType = { + NONE: 0, + DEFAULT_02: 1, + SKIN_01: 2, + MAX: 3 + }; + static lutDefinitions = { + specular: { + [LUTShaderMaterial.LUTSpecularTextureType.NONE]: new HermitianCurve([ + { x: 0, y: 0, dx: 0, dy: 0 }, + { x: 1, y: 0, dx: 0, dy: 0 } + ]), + [LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02]: new HermitianCurve([ + { x: 0, y: 0, dx: 0, dy: 0 }, + { x: 0.05, y: 0, dx: 0, dy: 0 }, + { + x: 0.8, + y: 0.038, + dx: 0.157894736842105, + dy: 0.157894736842105 + }, + { x: 1, y: 0.11, dx: 0, dy: 0 } + ]), + [LUTShaderMaterial.LUTSpecularTextureType.SKIN_01]: new HermitianCurve([ + { + x: 0, + y: 0.03, + dx: -0.105263157894737, + dy: -0.105263157894737 + }, + { x: 1, y: 0, dx: 0, dy: 0 } + ]) + }, + fresnel: { + [LUTShaderMaterial.LUTFresnelTextureType.NONE]: new HermitianCurve([ + { x: 0, y: 0, dx: 0, dy: 0 }, + { x: 1, y: 0, dx: 0, dy: 0 } + ]), + [LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02]: new HermitianCurve([ + { + x: 0, + y: 0.3, + dx: -0.105263157894734, + dy: -0.105263157894734 + }, + { + x: 0.175, + y: 0.23, + dx: -0.626315789473681, + dy: -0.626315789473681 + }, + { + x: 0.6, + y: 0.05, + dx: -0.210526315789474, + dy: -0.210526315789474 + }, + { + x: 1, + y: 0, + dx: -0.105263157894737, + dy: -0.105263157894737 + } + ]), + [LUTShaderMaterial.LUTFresnelTextureType.SKIN_01]: new HermitianCurve([ + { + x: 0.005, + y: 0.35, + dx: -0.105263157894734, + dy: -0.105263157894734 + }, + { + x: 0.173, + y: 0.319, + dx: -0.205263157894734, + dy: -0.205263157894734 + }, + { + x: 0.552, + y: 0.051, + dx: -0.210526315789474, + dy: -0.210526315789474 + }, + { x: 1, y: 0.001, dx: 0, dy: 0 } + ]) + } + }; + static modulateTypeToLUTSpecular = [ + LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, + LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.NONE, + LUTShaderMaterial.LUTSpecularTextureType.NONE, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02 + ]; + static modulateTypeToLUTFresnel = [ + LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, + LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.NONE, + LUTShaderMaterial.LUTFresnelTextureType.NONE, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02 + ]; + static _lutTextures = null; + static getLUTTextures(lutSize = 512) { + if (LUTShaderMaterial._lutTextures) { + return LUTShaderMaterial._lutTextures; + } + const textures = { specular: {}, fresnel: {} }; + const r8 = Number(THREE2.REVISION) <= 136 ? THREE2.LuminanceFormat : THREE2.RedFormat; + function generateLUTTextures(lutType, target) { + for (const key2 in lutType) { + const lutData = lutType[key2].generateLUT(lutSize); + target[Number(key2)] = Object.assign(new THREE2.DataTexture(lutData, lutSize, 1, r8, THREE2.UnsignedByteType), { + colorSpace: THREE2.LinearSRGBColorSpace, + needsUpdate: true + }); + } + } + generateLUTTextures(LUTShaderMaterial.lutDefinitions.specular, textures.specular); + generateLUTTextures(LUTShaderMaterial.lutDefinitions.fresnel, textures.fresnel); + LUTShaderMaterial._lutTextures = textures; + return textures; + } + static defaultHSLightGroundColor = new THREE2.Color(0.87843, 0.72157, 0.5898); + static defaultHSLightSkyColor = new THREE2.Color(0.87843, 0.83451, 0.80314); + static defaultDirLightColor0 = new THREE2.Color(0.35137, 0.32392, 0.32392); + static defaultDirLightColor1 = new THREE2.Color(0.10039, 0.09255, 0.09255); + static defaultDirLightCount = 2; + static defaultDirLightDirAndType0 = new THREE2.Vector4(-0.2, 0.5, 0.8, -1); + static defaultDirLightDirAndType1 = new THREE2.Vector4(0, -0.19612, 0.98058, -1); + static defaultLightColor = new THREE2.Color(0.35137, 0.32392, 0.32392); + static defaultLightDirection = this.defaultDirLightDirAndType0; + static multiplyColorIfNeeded(color, modulateType, modulateMode) { + if (modulateType === 1 || modulateType === 4 || modulateMode === 0 && modulateType === 9) { + const mul2 = 0.9019608; + color.r *= mul2; + color.g *= mul2; + color.b *= mul2; + } + return color; + } + constructor(options = {}) { + const uniforms = { + uBoneCount: { value: 0 }, + uAlpha: { value: 1 }, + uHSLightGroundColor: { + value: LUTShaderMaterial.defaultHSLightGroundColor + }, + uHSLightSkyColor: { + value: LUTShaderMaterial.defaultHSLightSkyColor + }, + uDirLightColor0: { + value: LUTShaderMaterial.defaultDirLightColor0 + }, + uDirLightColor1: { + value: LUTShaderMaterial.defaultDirLightColor1 + }, + uDirLightCount: { + value: LUTShaderMaterial.defaultDirLightCount + }, + uDirLightDirAndType0: { + value: LUTShaderMaterial.defaultDirLightDirAndType0.clone() + }, + uDirLightDirAndType1: { + value: LUTShaderMaterial.defaultDirLightDirAndType1.clone() + }, + uLightEnable: { value: true }, + uLightColor: { value: LUTShaderMaterial.defaultLightColor } + }; + super({ + vertexShader: _LUTShader_vert, + fragmentShader: _LUTShader_frag, + uniforms + }); + this._modulateType = 0; + this.setValues(options); + } + get color() { + if (!this.uniforms.uColor0) { + return null; + } else if (this._color3) { + return this._color3; + } + const color4 = this.uniforms.uColor0.value; + const color3 = new THREE2.Color(color4.x, color4.y, color4.z); + this._color3 = color3; + return color3; + } + set color(value2) { + function toColor4(color, opacity2 = 1) { + return new THREE2.Vector4(color.r, color.g, color.b, opacity2); + } + if (Array.isArray(value2)) { + this.uniforms.uColor0 = { value: toColor4(value2[0]) }; + this.uniforms.uColor1 = { value: toColor4(value2[1]) }; + this.uniforms.uColor2 = { value: toColor4(value2[2]) }; + return; + } + const color3 = value2 ? value2 : new THREE2.Color(1, 1, 1); + this._color3 = color3.clone(); + if (this.modulateType !== undefined && typeof this.modulateMode === "number") { + LUTShaderMaterial.multiplyColorIfNeeded(color3, this.modulateType, this.modulateMode); + } + const opacity = this.opacity; + if (this._opacity) { + delete this._opacity; + } + this.uniforms.uColor0 = { value: toColor4(color3, opacity) }; + } + get opacity() { + if (!this.uniforms.uColor0) { + return this._opacity ? this._opacity : 1; + } + return this.uniforms.uColor0.value.w; + } + set opacity(value2) { + if (!this.uniforms || !this.uniforms.uColor0) { + this._opacity = 1; + return; + } + this.uniforms.uColor0.value.w = value2; + } + get modulateMode() { + return this.uniforms.uMode ? this.uniforms.uMode.value : null; + } + set modulateMode(value2) { + this.uniforms.uMode = { value: value2 }; + } + get lightEnable() { + return this.uniforms.uLightEnable ? this.uniforms.uLightEnable.value : null; + } + set lightEnable(value2) { + this.uniforms.uLightEnable = { value: value2 }; + } + get modulateType() { + return this._modulateType; + } + set modulateType(value2) { + const lutTextures = LUTShaderMaterial.getLUTTextures(); + const specType = LUTShaderMaterial.modulateTypeToLUTSpecular[value2]; + const fresType = LUTShaderMaterial.modulateTypeToLUTFresnel[value2]; + if (specType === undefined || fresType === undefined) { + return; + } + this._modulateType = value2; + const lutSpecTexture = lutTextures.specular[specType]; + const lutFresTexture = lutTextures.fresnel[fresType]; + this.uniforms.uLUTSpecTexture = { value: lutSpecTexture }; + this.uniforms.uLUTFresTexture = { value: lutFresTexture }; + this.uniforms.uAlphaTest = { + value: value2 >= 6 && value2 <= 8 + }; + this._side = this.side; + this.side = value2 === 6 ? THREE2.DoubleSide : this.side; + } + get map() { + return this.uniforms.uAlbedoTexture ? this.uniforms.uAlbedoTexture.value : null; + } + set map(value2) { + this.uniforms.uAlbedoTexture = { value: value2 }; + } + get lightDirection() { + return this.uniforms.uDirLightDirAndType0.value; + } + set lightDirection(value2) { + this.uniforms.uDirLightDirAndType0 = { value: value2 }; + this.uniforms.uDirLightDirAndType0.value.w = -1; + } + } + return LUTShaderMaterial; + }); +}); + +// src/external/ffl.js/ffl-emscripten.js +var require_ffl_emscripten = __commonJS((exports2, module2) => { + var ModuleFFL = (() => { + var _scriptName = typeof document != "undefined" ? document.currentScript?.src : undefined; + return async function(moduleArg = {}) { + var moduleRtn; + var Module = moduleArg; + var readyPromiseResolve, readyPromiseReject; + var readyPromise = new Promise((resolve, reject2) => { + readyPromiseResolve = resolve; + readyPromiseReject = reject2; + }); + var ENVIRONMENT_IS_WEB = true; + var ENVIRONMENT_IS_WORKER = false; + var moduleOverrides = { ...Module }; + var scriptDirectory = ""; + function locateFile(path) { + if (Module["locateFile"]) { + return Module["locateFile"](path, scriptDirectory); + } + return scriptDirectory + path; + } + var readAsync, readBinary; + if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { + if (ENVIRONMENT_IS_WORKER) { + scriptDirectory = self.location.href; + } else if (typeof document != "undefined" && document.currentScript) { + scriptDirectory = document.currentScript.src; + } + if (_scriptName) { + scriptDirectory = _scriptName; + } + if (scriptDirectory.startsWith("blob:")) { + scriptDirectory = ""; + } else { + scriptDirectory = scriptDirectory.slice(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1); + } + { + readAsync = async (url) => { + var response = await fetch(url, { credentials: "same-origin" }); + if (response.ok) { + return response.arrayBuffer(); + } + throw new Error(response.status + " : " + response.url); + }; + } + } else { + } + var out = console.log.bind(console); + var err = console.error.bind(console); + Object.assign(Module, moduleOverrides); + moduleOverrides = null; + var wasmBinary; + var wasmMemory; + var ABORT = false; + var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAP64, HEAPU64, HEAPF64; + var runtimeInitialized = false; + function updateMemoryViews() { + var b3 = wasmMemory.buffer; + Module["HEAP8"] = HEAP8 = new Int8Array(b3); + HEAP16 = new Int16Array(b3); + Module["HEAPU8"] = HEAPU8 = new Uint8Array(b3); + Module["HEAPU16"] = HEAPU16 = new Uint16Array(b3); + Module["HEAP32"] = HEAP32 = new Int32Array(b3); + Module["HEAPU32"] = HEAPU32 = new Uint32Array(b3); + Module["HEAPF32"] = HEAPF32 = new Float32Array(b3); + HEAPF64 = new Float64Array(b3); + HEAP64 = new BigInt64Array(b3); + HEAPU64 = new BigUint64Array(b3); + } + function preRun() { + } + function initRuntime() { + runtimeInitialized = true; + wasmExports["e"](); + } + function postRun() { + } + var runDependencies = 0; + var dependenciesFulfilled = null; + function addRunDependency(id) { + runDependencies++; + } + function removeRunDependency(id) { + runDependencies--; + if (runDependencies == 0) { + if (dependenciesFulfilled) { + var callback = dependenciesFulfilled; + dependenciesFulfilled = null; + callback(); + } + } + } + function abort(what) { + what = "Aborted(" + what + ")"; + err(what); + ABORT = true; + what += ". Build with -sASSERTIONS for more info."; + var e = new WebAssembly.RuntimeError(what); + readyPromiseReject(e); + throw e; + } + var wasmBinaryFile; + function findWasmBinary() { + return locateFile("ffl-emscripten.wasm"); + } + function getBinarySync(file) { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary); + } + if (readBinary) { + return readBinary(file); + } + throw "both async and sync fetching of the wasm failed"; + } + async function getWasmBinary(binaryFile) { + if (!wasmBinary) { + try { + var response = await readAsync(binaryFile); + return new Uint8Array(response); + } catch { + } + } + return getBinarySync(binaryFile); + } + async function instantiateArrayBuffer(binaryFile, imports) { + try { + var binary = await getWasmBinary(binaryFile); + var instance = await WebAssembly.instantiate(binary, imports); + return instance; + } catch (reason) { + err(`failed to asynchronously prepare wasm: ${reason}`); + abort(reason); + } + } + async function instantiateAsync(binary, binaryFile, imports) { + if (!binary && typeof WebAssembly.instantiateStreaming == "function") { + try { + var response = fetch(binaryFile, { credentials: "same-origin" }); + var instantiationResult = await WebAssembly.instantiateStreaming(response, imports); + return instantiationResult; + } catch (reason) { + err(`wasm streaming compile failed: ${reason}`); + err("falling back to ArrayBuffer instantiation"); + } + } + return instantiateArrayBuffer(binaryFile, imports); + } + function getWasmImports() { + return { a: wasmImports }; + } + async function createWasm() { + function receiveInstance(instance, module3) { + wasmExports = instance.exports; + wasmMemory = wasmExports["d"]; + updateMemoryViews(); + wasmTable = wasmExports["O"]; + removeRunDependency("wasm-instantiate"); + return wasmExports; + } + addRunDependency("wasm-instantiate"); + function receiveInstantiationResult(result2) { + return receiveInstance(result2["instance"]); + } + var info = getWasmImports(); + wasmBinaryFile ??= findWasmBinary(); + try { + var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info); + var exports3 = receiveInstantiationResult(result); + return exports3; + } catch (e) { + readyPromiseReject(e); + return Promise.reject(e); + } + } + + class ExitStatus { + name = "ExitStatus"; + constructor(status) { + this.message = `Program terminated with exit(${status})`; + this.status = status; + } + } + function stackTrace() { + abort("missing function: $stackTrace"); + } + stackTrace.stub = true; + var __abort_js = () => abort(""); + var _emscripten_random = () => Math.random(); + var getHeapMax = () => 2147483648; + var alignMemory = (size2, alignment) => Math.ceil(size2 / alignment) * alignment; + var growMemory = (size2) => { + var b3 = wasmMemory.buffer; + var pages = (size2 - b3.byteLength + 65535) / 65536 | 0; + try { + wasmMemory.grow(pages); + updateMemoryViews(); + return 1; + } catch (e) { + } + }; + var _emscripten_resize_heap = (requestedSize) => { + var oldSize = HEAPU8.length; + requestedSize >>>= 0; + var maxHeapSize = getHeapMax(); + if (requestedSize > maxHeapSize) { + return false; + } + for (var cutDown = 1;cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); + overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); + var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536)); + var replacement = growMemory(newSize); + if (replacement) { + return true; + } + } + return false; + }; + var uleb128Encode = (n2, target) => { + if (n2 < 128) { + target.push(n2); + } else { + target.push(n2 % 128 | 128, n2 >> 7); + } + }; + var sigToWasmTypes = (sig) => { + var typeNames = { i: "i32", j: "i64", f: "f32", d: "f64", e: "externref", p: "i32" }; + var type = { parameters: [], results: sig[0] == "v" ? [] : [typeNames[sig[0]]] }; + for (var i = 1;i < sig.length; ++i) { + type.parameters.push(typeNames[sig[i]]); + } + return type; + }; + var generateFuncType = (sig, target) => { + var sigRet = sig.slice(0, 1); + var sigParam = sig.slice(1); + var typeCodes = { i: 127, p: 127, j: 126, f: 125, d: 124, e: 111 }; + target.push(96); + uleb128Encode(sigParam.length, target); + for (var paramType of sigParam) { + target.push(typeCodes[paramType]); + } + if (sigRet == "v") { + target.push(0); + } else { + target.push(1, typeCodes[sigRet]); + } + }; + var convertJsFunctionToWasm = (func, sig) => { + if (typeof WebAssembly.Function == "function") { + return new WebAssembly.Function(sigToWasmTypes(sig), func); + } + var typeSectionBody = [1]; + generateFuncType(sig, typeSectionBody); + var bytes = [0, 97, 115, 109, 1, 0, 0, 0, 1]; + uleb128Encode(typeSectionBody.length, bytes); + bytes.push(...typeSectionBody); + bytes.push(2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0); + var module3 = new WebAssembly.Module(new Uint8Array(bytes)); + var instance = new WebAssembly.Instance(module3, { e: { f: func } }); + var wrappedFunc = instance.exports["f"]; + return wrappedFunc; + }; + var wasmTableMirror = []; + var wasmTable; + var getWasmTableEntry = (funcPtr) => { + var func = wasmTableMirror[funcPtr]; + if (!func) { + wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr); + } + return func; + }; + var updateTableMap = (offset, count) => { + if (functionsInTableMap) { + for (var i = offset;i < offset + count; i++) { + var item = getWasmTableEntry(i); + if (item) { + functionsInTableMap.set(item, i); + } + } + } + }; + var functionsInTableMap; + var getFunctionAddress = (func) => { + if (!functionsInTableMap) { + functionsInTableMap = new WeakMap; + updateTableMap(0, wasmTable.length); + } + return functionsInTableMap.get(func) || 0; + }; + var freeTableIndexes = []; + var getEmptyTableSlot = () => { + if (freeTableIndexes.length) { + return freeTableIndexes.pop(); + } + try { + wasmTable.grow(1); + } catch (err2) { + if (!(err2 instanceof RangeError)) { + throw err2; + } + throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."; + } + return wasmTable.length - 1; + }; + var setWasmTableEntry = (idx, func) => { + wasmTable.set(idx, func); + wasmTableMirror[idx] = wasmTable.get(idx); + }; + var addFunction = (func, sig) => { + var rtn = getFunctionAddress(func); + if (rtn) { + return rtn; + } + var ret = getEmptyTableSlot(); + try { + setWasmTableEntry(ret, func); + } catch (err2) { + if (!(err2 instanceof TypeError)) { + throw err2; + } + var wrapped = convertJsFunctionToWasm(func, sig); + setWasmTableEntry(ret, wrapped); + } + functionsInTableMap.set(func, ret); + return ret; + }; + var removeFunction = (index2) => { + functionsInTableMap.delete(getWasmTableEntry(index2)); + setWasmTableEntry(index2, null); + freeTableIndexes.push(index2); + }; + var wasmImports = { a: __abort_js, c: _emscripten_random, b: _emscripten_resize_heap }; + var wasmExports = await createWasm(); + var ___wasm_call_ctors = wasmExports["e"]; + var _FFLInitCharModelCPUStepWithCallback = Module["_FFLInitCharModelCPUStepWithCallback"] = wasmExports["f"]; + var _FFLInitCharModelCPUStep = Module["_FFLInitCharModelCPUStep"] = wasmExports["g"]; + var _FFLDeleteCharModel = Module["_FFLDeleteCharModel"] = wasmExports["h"]; + var _FFLGetDrawParamOpaFaceline = Module["_FFLGetDrawParamOpaFaceline"] = wasmExports["i"]; + var _FFLGetDrawParamOpaBeard = Module["_FFLGetDrawParamOpaBeard"] = wasmExports["j"]; + var _FFLGetDrawParamOpaNose = Module["_FFLGetDrawParamOpaNose"] = wasmExports["k"]; + var _FFLGetDrawParamOpaForehead = Module["_FFLGetDrawParamOpaForehead"] = wasmExports["l"]; + var _FFLGetDrawParamOpaHair = Module["_FFLGetDrawParamOpaHair"] = wasmExports["m"]; + var _FFLGetDrawParamOpaCap = Module["_FFLGetDrawParamOpaCap"] = wasmExports["n"]; + var _FFLGetDrawParamXluMask = Module["_FFLGetDrawParamXluMask"] = wasmExports["o"]; + var _FFLGetDrawParamXluNoseLine = Module["_FFLGetDrawParamXluNoseLine"] = wasmExports["p"]; + var _FFLGetDrawParamXluGlass = Module["_FFLGetDrawParamXluGlass"] = wasmExports["q"]; + var _FFLSetExpression = Module["_FFLSetExpression"] = wasmExports["r"]; + var _FFLGetExpression = Module["_FFLGetExpression"] = wasmExports["s"]; + var _FFLSetViewModelType = Module["_FFLSetViewModelType"] = wasmExports["t"]; + var _FFLGetBoundingBox = Module["_FFLGetBoundingBox"] = wasmExports["u"]; + var _FFLIsAvailableExpression = Module["_FFLIsAvailableExpression"] = wasmExports["v"]; + var _FFLSetCoordinate = Module["_FFLSetCoordinate"] = wasmExports["w"]; + var _FFLSetScale = Module["_FFLSetScale"] = wasmExports["x"]; + var _FFLiGetRandomCharInfo = Module["_FFLiGetRandomCharInfo"] = wasmExports["y"]; + var _FFLpGetStoreDataFromCharInfo = Module["_FFLpGetStoreDataFromCharInfo"] = wasmExports["z"]; + var _FFLpGetCharInfoFromStoreData = Module["_FFLpGetCharInfoFromStoreData"] = wasmExports["A"]; + var _FFLpGetCharInfoFromMiiDataOfficialRFL = Module["_FFLpGetCharInfoFromMiiDataOfficialRFL"] = wasmExports["B"]; + var _FFLGetAdditionalInfo = Module["_FFLGetAdditionalInfo"] = wasmExports["C"]; + var _FFLInitRes = Module["_FFLInitRes"] = wasmExports["D"]; + var _FFLInitResGPUStep = Module["_FFLInitResGPUStep"] = wasmExports["E"]; + var _FFLExit = Module["_FFLExit"] = wasmExports["F"]; + var _FFLIsAvailable = Module["_FFLIsAvailable"] = wasmExports["G"]; + var _FFLGetFavoriteColor = Module["_FFLGetFavoriteColor"] = wasmExports["H"]; + var _FFLSetLinearGammaMode = Module["_FFLSetLinearGammaMode"] = wasmExports["I"]; + var _FFLGetFacelineColor = Module["_FFLGetFacelineColor"] = wasmExports["J"]; + var _FFLSetTextureFlipY = Module["_FFLSetTextureFlipY"] = wasmExports["K"]; + var _FFLSetNormalIsSnorm8_8_8_8 = Module["_FFLSetNormalIsSnorm8_8_8_8"] = wasmExports["L"]; + var _FFLSetFrontCullForFlipX = Module["_FFLSetFrontCullForFlipX"] = wasmExports["M"]; + var _FFLSetTextureCallback = Module["_FFLSetTextureCallback"] = wasmExports["N"]; + var _FFLiDeleteTempObjectMaskTextures = Module["_FFLiDeleteTempObjectMaskTextures"] = wasmExports["P"]; + var _FFLiDeleteTempObjectFacelineTexture = Module["_FFLiDeleteTempObjectFacelineTexture"] = wasmExports["Q"]; + var _FFLiDeleteTextureTempObject = Module["_FFLiDeleteTextureTempObject"] = wasmExports["R"]; + var _FFLiiGetEyeRotateOffset = Module["_FFLiiGetEyeRotateOffset"] = wasmExports["S"]; + var _FFLiiGetEyebrowRotateOffset = Module["_FFLiiGetEyebrowRotateOffset"] = wasmExports["T"]; + var _FFLiInvalidateTempObjectFacelineTexture = Module["_FFLiInvalidateTempObjectFacelineTexture"] = wasmExports["U"]; + var _FFLiInvalidatePartsTextures = Module["_FFLiInvalidatePartsTextures"] = wasmExports["V"]; + var _FFLiInvalidateRawMask = Module["_FFLiInvalidateRawMask"] = wasmExports["W"]; + var _GX2CalcSurfaceSizeAndAlignment = Module["_GX2CalcSurfaceSizeAndAlignment"] = wasmExports["X"]; + var _GX2CopySurface = Module["_GX2CopySurface"] = wasmExports["Y"]; + var _FFLiVerifyCharInfoWithReason = Module["_FFLiVerifyCharInfoWithReason"] = wasmExports["Z"]; + var _malloc = Module["_malloc"] = wasmExports["_"]; + var _free = Module["_free"] = wasmExports["$"]; + Module["addFunction"] = addFunction; + Module["removeFunction"] = removeFunction; + function run() { + if (runDependencies > 0) { + dependenciesFulfilled = run; + return; + } + preRun(); + if (runDependencies > 0) { + dependenciesFulfilled = run; + return; + } + function doRun() { + Module["calledRun"] = true; + if (ABORT) + return; + initRuntime(); + readyPromiseResolve(Module); + Module["onRuntimeInitialized"]?.(); + postRun(); + } + { + doRun(); + } + } + run(); + moduleRtn = readyPromise; + return moduleRtn; + }; + })(); + if (typeof exports2 === "object" && typeof module2 === "object") { + module2.exports = ModuleFFL; + module2.exports.default = ModuleFFL; + } else if (typeof define === "function" && define["amd"]) + define([], () => ModuleFFL); +}); + +// node_modules/crypt/crypt.js +var require_crypt = __commonJS((exports2, module2) => { + (function() { + var base64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", crypt = { + rotl: function(n2, b3) { + return n2 << b3 | n2 >>> 32 - b3; + }, + rotr: function(n2, b3) { + return n2 << 32 - b3 | n2 >>> b3; + }, + endian: function(n2) { + if (n2.constructor == Number) { + return crypt.rotl(n2, 8) & 16711935 | crypt.rotl(n2, 24) & 4278255360; + } + for (var i = 0;i < n2.length; i++) + n2[i] = crypt.endian(n2[i]); + return n2; + }, + randomBytes: function(n2) { + for (var bytes = [];n2 > 0; n2--) + bytes.push(Math.floor(Math.random() * 256)); + return bytes; + }, + bytesToWords: function(bytes) { + for (var words = [], i = 0, b3 = 0;i < bytes.length; i++, b3 += 8) + words[b3 >>> 5] |= bytes[i] << 24 - b3 % 32; + return words; + }, + wordsToBytes: function(words) { + for (var bytes = [], b3 = 0;b3 < words.length * 32; b3 += 8) + bytes.push(words[b3 >>> 5] >>> 24 - b3 % 32 & 255); + return bytes; + }, + bytesToHex: function(bytes) { + for (var hex = [], i = 0;i < bytes.length; i++) { + hex.push((bytes[i] >>> 4).toString(16)); + hex.push((bytes[i] & 15).toString(16)); + } + return hex.join(""); + }, + hexToBytes: function(hex) { + for (var bytes = [], c2 = 0;c2 < hex.length; c2 += 2) + bytes.push(parseInt(hex.substr(c2, 2), 16)); + return bytes; + }, + bytesToBase64: function(bytes) { + for (var base64 = [], i = 0;i < bytes.length; i += 3) { + var triplet = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2]; + for (var j2 = 0;j2 < 4; j2++) + if (i * 8 + j2 * 6 <= bytes.length * 8) + base64.push(base64map.charAt(triplet >>> 6 * (3 - j2) & 63)); + else + base64.push("="); + } + return base64.join(""); + }, + base64ToBytes: function(base64) { + base64 = base64.replace(/[^A-Z0-9+\/]/ig, ""); + for (var bytes = [], i = 0, imod4 = 0;i < base64.length; imod4 = ++i % 4) { + if (imod4 == 0) + continue; + bytes.push((base64map.indexOf(base64.charAt(i - 1)) & Math.pow(2, -2 * imod4 + 8) - 1) << imod4 * 2 | base64map.indexOf(base64.charAt(i)) >>> 6 - imod4 * 2); + } + return bytes; + } + }; + module2.exports = crypt; + })(); +}); + +// node_modules/charenc/charenc.js +var require_charenc = __commonJS((exports2, module2) => { + var charenc = { + utf8: { + stringToBytes: function(str) { + return charenc.bin.stringToBytes(unescape(encodeURIComponent(str))); + }, + bytesToString: function(bytes) { + return decodeURIComponent(escape(charenc.bin.bytesToString(bytes))); + } + }, + bin: { + stringToBytes: function(str) { + for (var bytes = [], i = 0;i < str.length; i++) + bytes.push(str.charCodeAt(i) & 255); + return bytes; + }, + bytesToString: function(bytes) { + for (var str = [], i = 0;i < bytes.length; i++) + str.push(String.fromCharCode(bytes[i])); + return str.join(""); + } + } + }; + module2.exports = charenc; +}); + +// node_modules/is-buffer/index.js +var require_is_buffer = __commonJS((exports2, module2) => { + /*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + module2.exports = function(obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer); + }; + function isBuffer(obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj); + } + function isSlowBuffer(obj) { + return typeof obj.readFloatLE === "function" && typeof obj.slice === "function" && isBuffer(obj.slice(0, 0)); + } +}); + +// node_modules/md5/md5.js +var require_md5 = __commonJS((exports2, module2) => { + (function() { + var crypt = require_crypt(), utf8 = require_charenc().utf8, isBuffer = require_is_buffer(), bin = require_charenc().bin, md5 = function(message, options) { + if (message.constructor == String) + if (options && options.encoding === "binary") + message = bin.stringToBytes(message); + else + message = utf8.stringToBytes(message); + else if (isBuffer(message)) + message = Array.prototype.slice.call(message, 0); + else if (!Array.isArray(message) && message.constructor !== Uint8Array) + message = message.toString(); + var m = crypt.bytesToWords(message), l2 = message.length * 8, a2 = 1732584193, b3 = -271733879, c2 = -1732584194, d = 271733878; + for (var i = 0;i < m.length; i++) { + m[i] = (m[i] << 8 | m[i] >>> 24) & 16711935 | (m[i] << 24 | m[i] >>> 8) & 4278255360; + } + m[l2 >>> 5] |= 128 << l2 % 32; + m[(l2 + 64 >>> 9 << 4) + 14] = l2; + var { _ff: FF, _gg: GG, _hh: HH, _ii: II } = md5; + for (var i = 0;i < m.length; i += 16) { + var aa = a2, bb = b3, cc = c2, dd2 = d; + a2 = FF(a2, b3, c2, d, m[i + 0], 7, -680876936); + d = FF(d, a2, b3, c2, m[i + 1], 12, -389564586); + c2 = FF(c2, d, a2, b3, m[i + 2], 17, 606105819); + b3 = FF(b3, c2, d, a2, m[i + 3], 22, -1044525330); + a2 = FF(a2, b3, c2, d, m[i + 4], 7, -176418897); + d = FF(d, a2, b3, c2, m[i + 5], 12, 1200080426); + c2 = FF(c2, d, a2, b3, m[i + 6], 17, -1473231341); + b3 = FF(b3, c2, d, a2, m[i + 7], 22, -45705983); + a2 = FF(a2, b3, c2, d, m[i + 8], 7, 1770035416); + d = FF(d, a2, b3, c2, m[i + 9], 12, -1958414417); + c2 = FF(c2, d, a2, b3, m[i + 10], 17, -42063); + b3 = FF(b3, c2, d, a2, m[i + 11], 22, -1990404162); + a2 = FF(a2, b3, c2, d, m[i + 12], 7, 1804603682); + d = FF(d, a2, b3, c2, m[i + 13], 12, -40341101); + c2 = FF(c2, d, a2, b3, m[i + 14], 17, -1502002290); + b3 = FF(b3, c2, d, a2, m[i + 15], 22, 1236535329); + a2 = GG(a2, b3, c2, d, m[i + 1], 5, -165796510); + d = GG(d, a2, b3, c2, m[i + 6], 9, -1069501632); + c2 = GG(c2, d, a2, b3, m[i + 11], 14, 643717713); + b3 = GG(b3, c2, d, a2, m[i + 0], 20, -373897302); + a2 = GG(a2, b3, c2, d, m[i + 5], 5, -701558691); + d = GG(d, a2, b3, c2, m[i + 10], 9, 38016083); + c2 = GG(c2, d, a2, b3, m[i + 15], 14, -660478335); + b3 = GG(b3, c2, d, a2, m[i + 4], 20, -405537848); + a2 = GG(a2, b3, c2, d, m[i + 9], 5, 568446438); + d = GG(d, a2, b3, c2, m[i + 14], 9, -1019803690); + c2 = GG(c2, d, a2, b3, m[i + 3], 14, -187363961); + b3 = GG(b3, c2, d, a2, m[i + 8], 20, 1163531501); + a2 = GG(a2, b3, c2, d, m[i + 13], 5, -1444681467); + d = GG(d, a2, b3, c2, m[i + 2], 9, -51403784); + c2 = GG(c2, d, a2, b3, m[i + 7], 14, 1735328473); + b3 = GG(b3, c2, d, a2, m[i + 12], 20, -1926607734); + a2 = HH(a2, b3, c2, d, m[i + 5], 4, -378558); + d = HH(d, a2, b3, c2, m[i + 8], 11, -2022574463); + c2 = HH(c2, d, a2, b3, m[i + 11], 16, 1839030562); + b3 = HH(b3, c2, d, a2, m[i + 14], 23, -35309556); + a2 = HH(a2, b3, c2, d, m[i + 1], 4, -1530992060); + d = HH(d, a2, b3, c2, m[i + 4], 11, 1272893353); + c2 = HH(c2, d, a2, b3, m[i + 7], 16, -155497632); + b3 = HH(b3, c2, d, a2, m[i + 10], 23, -1094730640); + a2 = HH(a2, b3, c2, d, m[i + 13], 4, 681279174); + d = HH(d, a2, b3, c2, m[i + 0], 11, -358537222); + c2 = HH(c2, d, a2, b3, m[i + 3], 16, -722521979); + b3 = HH(b3, c2, d, a2, m[i + 6], 23, 76029189); + a2 = HH(a2, b3, c2, d, m[i + 9], 4, -640364487); + d = HH(d, a2, b3, c2, m[i + 12], 11, -421815835); + c2 = HH(c2, d, a2, b3, m[i + 15], 16, 530742520); + b3 = HH(b3, c2, d, a2, m[i + 2], 23, -995338651); + a2 = II(a2, b3, c2, d, m[i + 0], 6, -198630844); + d = II(d, a2, b3, c2, m[i + 7], 10, 1126891415); + c2 = II(c2, d, a2, b3, m[i + 14], 15, -1416354905); + b3 = II(b3, c2, d, a2, m[i + 5], 21, -57434055); + a2 = II(a2, b3, c2, d, m[i + 12], 6, 1700485571); + d = II(d, a2, b3, c2, m[i + 3], 10, -1894986606); + c2 = II(c2, d, a2, b3, m[i + 10], 15, -1051523); + b3 = II(b3, c2, d, a2, m[i + 1], 21, -2054922799); + a2 = II(a2, b3, c2, d, m[i + 8], 6, 1873313359); + d = II(d, a2, b3, c2, m[i + 15], 10, -30611744); + c2 = II(c2, d, a2, b3, m[i + 6], 15, -1560198380); + b3 = II(b3, c2, d, a2, m[i + 13], 21, 1309151649); + a2 = II(a2, b3, c2, d, m[i + 4], 6, -145523070); + d = II(d, a2, b3, c2, m[i + 11], 10, -1120210379); + c2 = II(c2, d, a2, b3, m[i + 2], 15, 718787259); + b3 = II(b3, c2, d, a2, m[i + 9], 21, -343485551); + a2 = a2 + aa >>> 0; + b3 = b3 + bb >>> 0; + c2 = c2 + cc >>> 0; + d = d + dd2 >>> 0; + } + return crypt.endian([a2, b3, c2, d]); + }; + md5._ff = function(a2, b3, c2, d, x2, s, t4) { + var n2 = a2 + (b3 & c2 | ~b3 & d) + (x2 >>> 0) + t4; + return (n2 << s | n2 >>> 32 - s) + b3; + }; + md5._gg = function(a2, b3, c2, d, x2, s, t4) { + var n2 = a2 + (b3 & d | c2 & ~d) + (x2 >>> 0) + t4; + return (n2 << s | n2 >>> 32 - s) + b3; + }; + md5._hh = function(a2, b3, c2, d, x2, s, t4) { + var n2 = a2 + (b3 ^ c2 ^ d) + (x2 >>> 0) + t4; + return (n2 << s | n2 >>> 32 - s) + b3; + }; + md5._ii = function(a2, b3, c2, d, x2, s, t4) { + var n2 = a2 + (c2 ^ (b3 | ~d)) + (x2 >>> 0) + t4; + return (n2 << s | n2 >>> 32 - s) + b3; + }; + md5._blocksize = 16; + md5._digestsize = 16; + module2.exports = function(message, options) { + if (message === undefined || message === null) + throw new Error("Illegal argument " + message); + var digestbytes = crypt.wordsToBytes(md5(message, options)); + return options && options.asBytes ? digestbytes : options && options.asString ? bin.bytesToString(digestbytes) : crypt.bytesToHex(digestbytes); + }; + })(); +}); + +// src/external/mii-frontend/qr-scanner-worker.min.js +var exports_qr_scanner_worker_min = {}; +__export(exports_qr_scanner_worker_min, { + createWorker: () => createWorker +}); +var createWorker = () => new Worker(URL.createObjectURL(new Blob([`class x{constructor(a,b){this.width=b;this.height=a.length/b;this.data=a}static createEmpty(a,b){return new x(new Uint8ClampedArray(a*b),a)}get(a,b){return 0>a||a>=this.width||0>b||b>=this.height?!1:!!this.data[b*this.width+a]}set(a,b,c){this.data[b*this.width+a]=c?1:0}setRegion(a,b,c,d,e){for(let f=b;fa||32this.available())throw Error("Cannot read "+a.toString()+" bits");var b=0;if(0>8-c<>b;a-=c;this.bitOffset+=c;8===this.bitOffset&&(this.bitOffset=0,this.byteOffset++)}if(0>c<>c, +this.bitOffset+=a)}return b}available(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset}}var B,C=B||(B={});C.Numeric="numeric";C.Alphanumeric="alphanumeric";C.Byte="byte";C.Kanji="kanji";C.ECI="eci";C.StructuredAppend="structuredappend";var D,E=D||(D={});E[E.Terminator=0]="Terminator";E[E.Numeric=1]="Numeric";E[E.Alphanumeric=2]="Alphanumeric";E[E.Byte=4]="Byte";E[E.Kanji=8]="Kanji";E[E.ECI=7]="ECI";E[E.StructuredAppend=3]="StructuredAppend";let F="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:".split(""); +function ca(a,b){let c=[],d="";b=a.readBits([8,16,16][b]);for(let e=0;e\`%\${("0"+e.toString(16)).substr(-2)}\`).join(""))}catch(e){}return{bytes:c,text:d}} +function da(a,b){a=new ba(a);let c=9>=b?0:26>=b?1:2;for(b={text:"",bytes:[],chunks:[],version:b};4<=a.available();){var d=a.readBits(4);if(d===D.Terminator)return b;if(d===D.ECI)0===a.readBits(1)?b.chunks.push({type:B.ECI,assignmentNumber:a.readBits(7)}):0===a.readBits(1)?b.chunks.push({type:B.ECI,assignmentNumber:a.readBits(14)}):0===a.readBits(1)?b.chunks.push({type:B.ECI,assignmentNumber:a.readBits(21)}):b.chunks.push({type:B.ECI,assignmentNumber:-1});else if(d===D.Numeric){var e=a,f=[];d="";for(var g= +e.readBits([10,12,14][c]);3<=g;){var h=e.readBits(10);if(1E3<=h)throw Error("Invalid numeric value above 999");var k=Math.floor(h/100),m=Math.floor(h/10)%10;h%=10;f.push(48+k,48+m,48+h);d+=k.toString()+m.toString()+h.toString();g-=3}if(2===g){g=e.readBits(7);if(100<=g)throw Error("Invalid numeric value above 99");e=Math.floor(g/10);g%=10;f.push(48+e,48+g);d+=e.toString()+g.toString()}else if(1===g){e=e.readBits(4);if(10<=e)throw Error("Invalid numeric value above 9");f.push(48+e);d+=e.toString()}b.text+= +d;b.bytes.push(...f);b.chunks.push({type:B.Numeric,text:d})}else if(d===D.Alphanumeric){e=a;f=[];d="";for(g=e.readBits([9,11,13][c]);2<=g;)m=e.readBits(11),k=Math.floor(m/45),m%=45,f.push(F[k].charCodeAt(0),F[m].charCodeAt(0)),d+=F[k]+F[m],g-=2;1===g&&(e=e.readBits(6),f.push(F[e].charCodeAt(0)),d+=F[e]);b.text+=d;b.bytes.push(...f);b.chunks.push({type:B.Alphanumeric,text:d})}else if(d===D.Byte)d=ca(a,c),b.text+=d.text,b.bytes.push(...d.bytes),b.chunks.push({type:B.Byte,bytes:d.bytes,text:d.text}); +else if(d===D.Kanji){f=a;d=[];e=f.readBits([8,10,12][c]);for(g=0;gk?k+33088:k+49472,d.push(k>>8,k&255);f=(new TextDecoder("shift-jis")).decode(Uint8Array.from(d));b.text+=f;b.bytes.push(...d);b.chunks.push({type:B.Kanji,bytes:d,text:f})}else d===D.StructuredAppend&&b.chunks.push({type:B.StructuredAppend,currentSequence:a.readBits(4),totalSequence:a.readBits(4),parity:a.readBits(8)})}if(0===a.available()||0===a.readBits(a.available()))return b} +class G{constructor(a,b){if(0===b.length)throw Error("No coefficients.");this.field=a;let c=b.length;if(1a.length&&([b,a]=[a,b]);let c=new Uint8ClampedArray(a.length),d=a.length-b.length;for(var e=0;ea)throw Error("Invalid degree less than 0");if(0===b)return this.field.zero;let c=this.coefficients.length;a=new Uint8ClampedArray(c+a);for(let d=0;d{b^=d}),b;b=this.coefficients[0];for(let d=1;d=this.size&&(a=(a^this.primitive)&this.size-1);for(a=0;aa)throw Error("Invalid monomial degree less than 0");if(0===b)return this.zero;a=new Uint8ClampedArray(a+1);a[0]=b;return new G(this,a)}log(a){if(0===a)throw Error("Can't take log(0)");return this.logTable[a]}exp(a){return this.expTable[a]}} +function fa(a,b,c,d){b.degree()=d/2;){var g=b;let h=e;b=c;e=f;if(b.isZero())return null;c=g;f=a.zero;g=b.getCoefficient(b.degree());for(g=a.inverse(g);c.degree()>=b.degree()&&!c.isZero();){let k=c.degree()-b.degree(),m=a.multiply(c.getCoefficient(c.degree()),g);f=f.addOrSubtract(a.buildMonomial(k,m));c=c.addOrSubtract(b.multiplyByMonomial(k,m))}f=f.multiplyPoly(e).addOrSubtract(h);if(c.degree()>=b.degree())return null}d=f.getCoefficient(0); +if(0===d)return null;a=a.inverse(d);return[f.multiply(a),c.multiply(a)]} +function ha(a,b){let c=new Uint8ClampedArray(a.length);c.set(a);a=new ea(285,256,0);var d=new G(a,c),e=new Uint8ClampedArray(b),f=!1;for(var g=0;gf)return null;c[f]^=d[e]}return c} +let I=[{infoBits:null,versionNumber:1,alignmentPatternCenters:[],errorCorrectionLevels:[{ecCodewordsPerBlock:7,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:19}]},{ecCodewordsPerBlock:10,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:16}]},{ecCodewordsPerBlock:13,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:13}]},{ecCodewordsPerBlock:17,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:9}]}]},{infoBits:null,versionNumber:2,alignmentPatternCenters:[6,18],errorCorrectionLevels:[{ecCodewordsPerBlock:10,ecBlocks:[{numBlocks:1, +dataCodewordsPerBlock:34}]},{ecCodewordsPerBlock:16,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:28}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:22}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:16}]}]},{infoBits:null,versionNumber:3,alignmentPatternCenters:[6,22],errorCorrectionLevels:[{ecCodewordsPerBlock:15,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:55}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:44}]},{ecCodewordsPerBlock:18, +ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:17}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:13}]}]},{infoBits:null,versionNumber:4,alignmentPatternCenters:[6,26],errorCorrectionLevels:[{ecCodewordsPerBlock:20,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:80}]},{ecCodewordsPerBlock:18,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:32}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:24}]},{ecCodewordsPerBlock:16,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:9}]}]}, +{infoBits:null,versionNumber:5,alignmentPatternCenters:[6,30],errorCorrectionLevels:[{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:108}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:43}]},{ecCodewordsPerBlock:18,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:15},{numBlocks:2,dataCodewordsPerBlock:16}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:11},{numBlocks:2,dataCodewordsPerBlock:12}]}]},{infoBits:null,versionNumber:6,alignmentPatternCenters:[6, +34],errorCorrectionLevels:[{ecCodewordsPerBlock:18,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:68}]},{ecCodewordsPerBlock:16,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:27}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:19}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:15}]}]},{infoBits:31892,versionNumber:7,alignmentPatternCenters:[6,22,38],errorCorrectionLevels:[{ecCodewordsPerBlock:20,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:78}]},{ecCodewordsPerBlock:18, +ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:31}]},{ecCodewordsPerBlock:18,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:14},{numBlocks:4,dataCodewordsPerBlock:15}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:13},{numBlocks:1,dataCodewordsPerBlock:14}]}]},{infoBits:34236,versionNumber:8,alignmentPatternCenters:[6,24,42],errorCorrectionLevels:[{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:97}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:38}, +{numBlocks:2,dataCodewordsPerBlock:39}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:18},{numBlocks:2,dataCodewordsPerBlock:19}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:14},{numBlocks:2,dataCodewordsPerBlock:15}]}]},{infoBits:39577,versionNumber:9,alignmentPatternCenters:[6,26,46],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:116}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:36}, +{numBlocks:2,dataCodewordsPerBlock:37}]},{ecCodewordsPerBlock:20,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:16},{numBlocks:4,dataCodewordsPerBlock:17}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:12},{numBlocks:4,dataCodewordsPerBlock:13}]}]},{infoBits:42195,versionNumber:10,alignmentPatternCenters:[6,28,50],errorCorrectionLevels:[{ecCodewordsPerBlock:18,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:68},{numBlocks:2,dataCodewordsPerBlock:69}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:4, +dataCodewordsPerBlock:43},{numBlocks:1,dataCodewordsPerBlock:44}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:6,dataCodewordsPerBlock:19},{numBlocks:2,dataCodewordsPerBlock:20}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:6,dataCodewordsPerBlock:15},{numBlocks:2,dataCodewordsPerBlock:16}]}]},{infoBits:48118,versionNumber:11,alignmentPatternCenters:[6,30,54],errorCorrectionLevels:[{ecCodewordsPerBlock:20,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:81}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:1, +dataCodewordsPerBlock:50},{numBlocks:4,dataCodewordsPerBlock:51}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:22},{numBlocks:4,dataCodewordsPerBlock:23}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:12},{numBlocks:8,dataCodewordsPerBlock:13}]}]},{infoBits:51042,versionNumber:12,alignmentPatternCenters:[6,32,58],errorCorrectionLevels:[{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:92},{numBlocks:2,dataCodewordsPerBlock:93}]}, +{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:6,dataCodewordsPerBlock:36},{numBlocks:2,dataCodewordsPerBlock:37}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:20},{numBlocks:6,dataCodewordsPerBlock:21}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:7,dataCodewordsPerBlock:14},{numBlocks:4,dataCodewordsPerBlock:15}]}]},{infoBits:55367,versionNumber:13,alignmentPatternCenters:[6,34,62],errorCorrectionLevels:[{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:107}]}, +{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:8,dataCodewordsPerBlock:37},{numBlocks:1,dataCodewordsPerBlock:38}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:8,dataCodewordsPerBlock:20},{numBlocks:4,dataCodewordsPerBlock:21}]},{ecCodewordsPerBlock:22,ecBlocks:[{numBlocks:12,dataCodewordsPerBlock:11},{numBlocks:4,dataCodewordsPerBlock:12}]}]},{infoBits:58893,versionNumber:14,alignmentPatternCenters:[6,26,46,66],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:115}, +{numBlocks:1,dataCodewordsPerBlock:116}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:40},{numBlocks:5,dataCodewordsPerBlock:41}]},{ecCodewordsPerBlock:20,ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:16},{numBlocks:5,dataCodewordsPerBlock:17}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:12},{numBlocks:5,dataCodewordsPerBlock:13}]}]},{infoBits:63784,versionNumber:15,alignmentPatternCenters:[6,26,48,70],errorCorrectionLevels:[{ecCodewordsPerBlock:22, +ecBlocks:[{numBlocks:5,dataCodewordsPerBlock:87},{numBlocks:1,dataCodewordsPerBlock:88}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:5,dataCodewordsPerBlock:41},{numBlocks:5,dataCodewordsPerBlock:42}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:5,dataCodewordsPerBlock:24},{numBlocks:7,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:12},{numBlocks:7,dataCodewordsPerBlock:13}]}]},{infoBits:68472,versionNumber:16,alignmentPatternCenters:[6,26,50, +74],errorCorrectionLevels:[{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:5,dataCodewordsPerBlock:98},{numBlocks:1,dataCodewordsPerBlock:99}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:7,dataCodewordsPerBlock:45},{numBlocks:3,dataCodewordsPerBlock:46}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:15,dataCodewordsPerBlock:19},{numBlocks:2,dataCodewordsPerBlock:20}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:15},{numBlocks:13,dataCodewordsPerBlock:16}]}]},{infoBits:70749, +versionNumber:17,alignmentPatternCenters:[6,30,54,78],errorCorrectionLevels:[{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:107},{numBlocks:5,dataCodewordsPerBlock:108}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:10,dataCodewordsPerBlock:46},{numBlocks:1,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:22},{numBlocks:15,dataCodewordsPerBlock:23}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:14},{numBlocks:17, +dataCodewordsPerBlock:15}]}]},{infoBits:76311,versionNumber:18,alignmentPatternCenters:[6,30,56,82],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:5,dataCodewordsPerBlock:120},{numBlocks:1,dataCodewordsPerBlock:121}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:9,dataCodewordsPerBlock:43},{numBlocks:4,dataCodewordsPerBlock:44}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:22},{numBlocks:1,dataCodewordsPerBlock:23}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:2, +dataCodewordsPerBlock:14},{numBlocks:19,dataCodewordsPerBlock:15}]}]},{infoBits:79154,versionNumber:19,alignmentPatternCenters:[6,30,58,86],errorCorrectionLevels:[{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:113},{numBlocks:4,dataCodewordsPerBlock:114}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:44},{numBlocks:11,dataCodewordsPerBlock:45}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:21},{numBlocks:4,dataCodewordsPerBlock:22}]}, +{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:9,dataCodewordsPerBlock:13},{numBlocks:16,dataCodewordsPerBlock:14}]}]},{infoBits:84390,versionNumber:20,alignmentPatternCenters:[6,34,62,90],errorCorrectionLevels:[{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:107},{numBlocks:5,dataCodewordsPerBlock:108}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:41},{numBlocks:13,dataCodewordsPerBlock:42}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:15,dataCodewordsPerBlock:24}, +{numBlocks:5,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:15,dataCodewordsPerBlock:15},{numBlocks:10,dataCodewordsPerBlock:16}]}]},{infoBits:87683,versionNumber:21,alignmentPatternCenters:[6,28,50,72,94],errorCorrectionLevels:[{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:116},{numBlocks:4,dataCodewordsPerBlock:117}]},{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:42}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:22}, +{numBlocks:6,dataCodewordsPerBlock:23}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:19,dataCodewordsPerBlock:16},{numBlocks:6,dataCodewordsPerBlock:17}]}]},{infoBits:92361,versionNumber:22,alignmentPatternCenters:[6,26,50,74,98],errorCorrectionLevels:[{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:111},{numBlocks:7,dataCodewordsPerBlock:112}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:46}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:7,dataCodewordsPerBlock:24}, +{numBlocks:16,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:24,ecBlocks:[{numBlocks:34,dataCodewordsPerBlock:13}]}]},{infoBits:96236,versionNumber:23,alignmentPatternCenters:[6,30,54,74,102],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:121},{numBlocks:5,dataCodewordsPerBlock:122}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:47},{numBlocks:14,dataCodewordsPerBlock:48}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:24}, +{numBlocks:14,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:16,dataCodewordsPerBlock:15},{numBlocks:14,dataCodewordsPerBlock:16}]}]},{infoBits:102084,versionNumber:24,alignmentPatternCenters:[6,28,54,80,106],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:6,dataCodewordsPerBlock:117},{numBlocks:4,dataCodewordsPerBlock:118}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:6,dataCodewordsPerBlock:45},{numBlocks:14,dataCodewordsPerBlock:46}]},{ecCodewordsPerBlock:30, +ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:24},{numBlocks:16,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:30,dataCodewordsPerBlock:16},{numBlocks:2,dataCodewordsPerBlock:17}]}]},{infoBits:102881,versionNumber:25,alignmentPatternCenters:[6,32,58,84,110],errorCorrectionLevels:[{ecCodewordsPerBlock:26,ecBlocks:[{numBlocks:8,dataCodewordsPerBlock:106},{numBlocks:4,dataCodewordsPerBlock:107}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:8,dataCodewordsPerBlock:47},{numBlocks:13, +dataCodewordsPerBlock:48}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:7,dataCodewordsPerBlock:24},{numBlocks:22,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:22,dataCodewordsPerBlock:15},{numBlocks:13,dataCodewordsPerBlock:16}]}]},{infoBits:110507,versionNumber:26,alignmentPatternCenters:[6,30,58,86,114],errorCorrectionLevels:[{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:10,dataCodewordsPerBlock:114},{numBlocks:2,dataCodewordsPerBlock:115}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:19, +dataCodewordsPerBlock:46},{numBlocks:4,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:28,dataCodewordsPerBlock:22},{numBlocks:6,dataCodewordsPerBlock:23}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:33,dataCodewordsPerBlock:16},{numBlocks:4,dataCodewordsPerBlock:17}]}]},{infoBits:110734,versionNumber:27,alignmentPatternCenters:[6,34,62,90,118],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:8,dataCodewordsPerBlock:122},{numBlocks:4,dataCodewordsPerBlock:123}]}, +{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:22,dataCodewordsPerBlock:45},{numBlocks:3,dataCodewordsPerBlock:46}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:8,dataCodewordsPerBlock:23},{numBlocks:26,dataCodewordsPerBlock:24}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:12,dataCodewordsPerBlock:15},{numBlocks:28,dataCodewordsPerBlock:16}]}]},{infoBits:117786,versionNumber:28,alignmentPatternCenters:[6,26,50,74,98,122],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:117}, +{numBlocks:10,dataCodewordsPerBlock:118}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:3,dataCodewordsPerBlock:45},{numBlocks:23,dataCodewordsPerBlock:46}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:4,dataCodewordsPerBlock:24},{numBlocks:31,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:15},{numBlocks:31,dataCodewordsPerBlock:16}]}]},{infoBits:119615,versionNumber:29,alignmentPatternCenters:[6,30,54,78,102,126],errorCorrectionLevels:[{ecCodewordsPerBlock:30, +ecBlocks:[{numBlocks:7,dataCodewordsPerBlock:116},{numBlocks:7,dataCodewordsPerBlock:117}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:21,dataCodewordsPerBlock:45},{numBlocks:7,dataCodewordsPerBlock:46}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:1,dataCodewordsPerBlock:23},{numBlocks:37,dataCodewordsPerBlock:24}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:19,dataCodewordsPerBlock:15},{numBlocks:26,dataCodewordsPerBlock:16}]}]},{infoBits:126325,versionNumber:30,alignmentPatternCenters:[6, +26,52,78,104,130],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:5,dataCodewordsPerBlock:115},{numBlocks:10,dataCodewordsPerBlock:116}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:19,dataCodewordsPerBlock:47},{numBlocks:10,dataCodewordsPerBlock:48}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:15,dataCodewordsPerBlock:24},{numBlocks:25,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:23,dataCodewordsPerBlock:15},{numBlocks:25,dataCodewordsPerBlock:16}]}]}, +{infoBits:127568,versionNumber:31,alignmentPatternCenters:[6,30,56,82,108,134],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:13,dataCodewordsPerBlock:115},{numBlocks:3,dataCodewordsPerBlock:116}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:46},{numBlocks:29,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:42,dataCodewordsPerBlock:24},{numBlocks:1,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:23,dataCodewordsPerBlock:15}, +{numBlocks:28,dataCodewordsPerBlock:16}]}]},{infoBits:133589,versionNumber:32,alignmentPatternCenters:[6,34,60,86,112,138],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:115}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:10,dataCodewordsPerBlock:46},{numBlocks:23,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:10,dataCodewordsPerBlock:24},{numBlocks:35,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:19, +dataCodewordsPerBlock:15},{numBlocks:35,dataCodewordsPerBlock:16}]}]},{infoBits:136944,versionNumber:33,alignmentPatternCenters:[6,30,58,86,114,142],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:115},{numBlocks:1,dataCodewordsPerBlock:116}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:14,dataCodewordsPerBlock:46},{numBlocks:21,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:29,dataCodewordsPerBlock:24},{numBlocks:19,dataCodewordsPerBlock:25}]}, +{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:11,dataCodewordsPerBlock:15},{numBlocks:46,dataCodewordsPerBlock:16}]}]},{infoBits:141498,versionNumber:34,alignmentPatternCenters:[6,34,62,90,118,146],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:13,dataCodewordsPerBlock:115},{numBlocks:6,dataCodewordsPerBlock:116}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:14,dataCodewordsPerBlock:46},{numBlocks:23,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:44, +dataCodewordsPerBlock:24},{numBlocks:7,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:59,dataCodewordsPerBlock:16},{numBlocks:1,dataCodewordsPerBlock:17}]}]},{infoBits:145311,versionNumber:35,alignmentPatternCenters:[6,30,54,78,102,126,150],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:12,dataCodewordsPerBlock:121},{numBlocks:7,dataCodewordsPerBlock:122}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:12,dataCodewordsPerBlock:47},{numBlocks:26,dataCodewordsPerBlock:48}]}, +{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:39,dataCodewordsPerBlock:24},{numBlocks:14,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:22,dataCodewordsPerBlock:15},{numBlocks:41,dataCodewordsPerBlock:16}]}]},{infoBits:150283,versionNumber:36,alignmentPatternCenters:[6,24,50,76,102,128,154],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:6,dataCodewordsPerBlock:121},{numBlocks:14,dataCodewordsPerBlock:122}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:6, +dataCodewordsPerBlock:47},{numBlocks:34,dataCodewordsPerBlock:48}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:46,dataCodewordsPerBlock:24},{numBlocks:10,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:2,dataCodewordsPerBlock:15},{numBlocks:64,dataCodewordsPerBlock:16}]}]},{infoBits:152622,versionNumber:37,alignmentPatternCenters:[6,28,54,80,106,132,158],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:17,dataCodewordsPerBlock:122},{numBlocks:4,dataCodewordsPerBlock:123}]}, +{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:29,dataCodewordsPerBlock:46},{numBlocks:14,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:49,dataCodewordsPerBlock:24},{numBlocks:10,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:24,dataCodewordsPerBlock:15},{numBlocks:46,dataCodewordsPerBlock:16}]}]},{infoBits:158308,versionNumber:38,alignmentPatternCenters:[6,32,58,84,110,136,162],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:4, +dataCodewordsPerBlock:122},{numBlocks:18,dataCodewordsPerBlock:123}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:13,dataCodewordsPerBlock:46},{numBlocks:32,dataCodewordsPerBlock:47}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:48,dataCodewordsPerBlock:24},{numBlocks:14,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:42,dataCodewordsPerBlock:15},{numBlocks:32,dataCodewordsPerBlock:16}]}]},{infoBits:161089,versionNumber:39,alignmentPatternCenters:[6,26,54,82,110,138,166], +errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:20,dataCodewordsPerBlock:117},{numBlocks:4,dataCodewordsPerBlock:118}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:40,dataCodewordsPerBlock:47},{numBlocks:7,dataCodewordsPerBlock:48}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:43,dataCodewordsPerBlock:24},{numBlocks:22,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:10,dataCodewordsPerBlock:15},{numBlocks:67,dataCodewordsPerBlock:16}]}]},{infoBits:167017, +versionNumber:40,alignmentPatternCenters:[6,30,58,86,114,142,170],errorCorrectionLevels:[{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:19,dataCodewordsPerBlock:118},{numBlocks:6,dataCodewordsPerBlock:119}]},{ecCodewordsPerBlock:28,ecBlocks:[{numBlocks:18,dataCodewordsPerBlock:47},{numBlocks:31,dataCodewordsPerBlock:48}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:34,dataCodewordsPerBlock:24},{numBlocks:34,dataCodewordsPerBlock:25}]},{ecCodewordsPerBlock:30,ecBlocks:[{numBlocks:20,dataCodewordsPerBlock:15}, +{numBlocks:61,dataCodewordsPerBlock:16}]}]}];function J(a,b){a^=b;for(b=0;a;)b++,a&=a-1;return b}function K(a,b){return b<<1|a} +let ia=[{bits:21522,formatInfo:{errorCorrectionLevel:1,dataMask:0}},{bits:20773,formatInfo:{errorCorrectionLevel:1,dataMask:1}},{bits:24188,formatInfo:{errorCorrectionLevel:1,dataMask:2}},{bits:23371,formatInfo:{errorCorrectionLevel:1,dataMask:3}},{bits:17913,formatInfo:{errorCorrectionLevel:1,dataMask:4}},{bits:16590,formatInfo:{errorCorrectionLevel:1,dataMask:5}},{bits:20375,formatInfo:{errorCorrectionLevel:1,dataMask:6}},{bits:19104,formatInfo:{errorCorrectionLevel:1,dataMask:7}},{bits:30660,formatInfo:{errorCorrectionLevel:0, +dataMask:0}},{bits:29427,formatInfo:{errorCorrectionLevel:0,dataMask:1}},{bits:32170,formatInfo:{errorCorrectionLevel:0,dataMask:2}},{bits:30877,formatInfo:{errorCorrectionLevel:0,dataMask:3}},{bits:26159,formatInfo:{errorCorrectionLevel:0,dataMask:4}},{bits:25368,formatInfo:{errorCorrectionLevel:0,dataMask:5}},{bits:27713,formatInfo:{errorCorrectionLevel:0,dataMask:6}},{bits:26998,formatInfo:{errorCorrectionLevel:0,dataMask:7}},{bits:5769,formatInfo:{errorCorrectionLevel:3,dataMask:0}},{bits:5054, +formatInfo:{errorCorrectionLevel:3,dataMask:1}},{bits:7399,formatInfo:{errorCorrectionLevel:3,dataMask:2}},{bits:6608,formatInfo:{errorCorrectionLevel:3,dataMask:3}},{bits:1890,formatInfo:{errorCorrectionLevel:3,dataMask:4}},{bits:597,formatInfo:{errorCorrectionLevel:3,dataMask:5}},{bits:3340,formatInfo:{errorCorrectionLevel:3,dataMask:6}},{bits:2107,formatInfo:{errorCorrectionLevel:3,dataMask:7}},{bits:13663,formatInfo:{errorCorrectionLevel:2,dataMask:0}},{bits:12392,formatInfo:{errorCorrectionLevel:2, +dataMask:1}},{bits:16177,formatInfo:{errorCorrectionLevel:2,dataMask:2}},{bits:14854,formatInfo:{errorCorrectionLevel:2,dataMask:3}},{bits:9396,formatInfo:{errorCorrectionLevel:2,dataMask:4}},{bits:8579,formatInfo:{errorCorrectionLevel:2,dataMask:5}},{bits:11994,formatInfo:{errorCorrectionLevel:2,dataMask:6}},{bits:11245,formatInfo:{errorCorrectionLevel:2,dataMask:7}}],ja=[a=>0===(a.y+a.x)%2,a=>0===a.y%2,a=>0===a.x%3,a=>0===(a.y+a.x)%3,a=>0===(Math.floor(a.y/2)+Math.floor(a.x/3))%2,a=>0===a.x*a.y% +2+a.x*a.y%3,a=>0===(a.y*a.x%2+a.y*a.x%3)%2,a=>0===((a.y+a.x)%2+a.y*a.x%3)%2]; +function ka(a,b,c){c=ja[c.dataMask];let d=a.height;var e=17+4*b.versionNumber;let f=x.createEmpty(e,e);f.setRegion(0,0,9,9,!0);f.setRegion(e-8,0,8,9,!0);f.setRegion(0,e-8,9,8,!0);for(var g of b.alignmentPatternCenters)for(var h of b.alignmentPatternCenters)6===g&&6===h||6===g&&h===e-7||g===e-7&&6===h||f.setRegion(g-2,h-2,5,5,!0);f.setRegion(6,9,1,e-17,!0);f.setRegion(9,6,e-17,1,!0);6n;n++){let q=k-n;if(!f.get(q,l)){h++;let r=a.get(q,l);c({y:l,x:q})&&(r=!r);g=g<<1|r;8===h&&(b.push(g),g=h=0)}}}e=!e}return b} +function la(a){var b=a.height,c=Math.floor((b-17)/4);if(6>=c)return I[c-1];c=0;for(var d=5;0<=d;d--)for(var e=b-9;e>=b-11;e--)c=K(a.get(e,d),c);d=0;for(e=5;0<=e;e--)for(let g=b-9;g>=b-11;g--)d=K(a.get(e,g),d);a=Infinity;let f;for(let g of I){if(g.infoBits===c||g.infoBits===d)return g;b=J(c,g.infoBits);b=a)return f} +function ma(a){let b=0;for(var c=0;8>=c;c++)6!==c&&(b=K(a.get(c,8),b));for(c=7;0<=c;c--)6!==c&&(b=K(a.get(8,c),b));var d=a.height;c=0;for(var e=d-1;e>=d-7;e--)c=K(a.get(8,e),c);for(e=d-8;e=a?d:null} +function na(a,b,c){let d=b.errorCorrectionLevels[c],e=[],f=0;d.ecBlocks.forEach(h=>{for(let k=0;ke+f.numDataCodewords,0);c=new Uint8ClampedArray(c);a=0;for(let e of d){d=ha(e.codewords,e.codewords.length-e.numDataCodewords);if(!d)return null;for(let f=0;f{const p=g*r+m*u+q;return{x:(e*r+h*u+l)/p,y:(f*r+k*u+n)/p}};for(let r=0;rMath.sqrt(Math.pow(b.x-a.x,2)+Math.pow(b.y-a.y,2));function O(a){return a.reduce((b,c)=>b+c)} +function qa(a,b,c){let d=N(a,b),e=N(b,c),f=N(a,c),g,h,k;e>=d&&e>=f?[g,h,k]=[b,a,c]:f>=e&&f>=d?[g,h,k]=[a,b,c]:[g,h,k]=[a,c,b];0>(k.x-h.x)*(g.y-h.y)-(k.y-h.y)*(g.x-h.x)&&([g,k]=[k,g]);return{bottomLeft:g,topLeft:h,topRight:k}} +function ra(a,b,c,d){d=(O(P(a,c,d,5))/7+O(P(a,b,d,5))/7+O(P(c,a,d,5))/7+O(P(b,a,d,5))/7)/4;if(1>d)throw Error("Invalid module size");b=Math.round(N(a,b)/d);a=Math.round(N(a,c)/d);a=Math.floor((b+a)/2)+7;switch(a%4){case 0:a++;break;case 2:a--}return{dimension:a,moduleSize:d}} +function Q(a,b,c,d){let e=[{x:Math.floor(a.x),y:Math.floor(a.y)}];var f=Math.abs(b.y-a.y)>Math.abs(b.x-a.x);if(f){var g=Math.floor(a.y);var h=Math.floor(a.x);a=Math.floor(b.y);b=Math.floor(b.x)}else g=Math.floor(a.x),h=Math.floor(a.y),a=Math.floor(b.x),b=Math.floor(b.y);let k=Math.abs(a-g),m=Math.abs(b-h),l=Math.floor(-k/2),n=g{d+=Math.pow(a[f]-e*c,2)});return{averageSize:c,error:d}} +function S(a,b,c){try{let d=P(a,{x:-1,y:a.y},c,b.length),e=P(a,{x:a.x,y:-1},c,b.length),f=P(a,{x:Math.max(0,a.x-a.y)-1,y:Math.max(0,a.y-a.x)-1},c,b.length),g=P(a,{x:Math.min(c.width,a.x+a.y)+1,y:Math.min(c.height,a.y+a.x)+1},c,b.length),h=R(d,b),k=R(e,b),m=R(f,b),l=R(g,b),n=(h.averageSize+k.averageSize+m.averageSize+l.averageSize)/4;return Math.sqrt(h.error*h.error+k.error*k.error+m.error*m.error+l.error*l.error)+(Math.pow(h.averageSize-n,2)+Math.pow(k.averageSize-n,2)+Math.pow(m.averageSize-n,2)+ +Math.pow(l.averageSize-n,2))/n}catch(d){return Infinity}}function T(a,b){for(var c=Math.round(b.x);a.get(c,Math.round(b.y));)c--;for(var d=Math.round(b.x);a.get(d,Math.round(b.y));)d++;c=(c+d)/2;for(d=Math.round(b.y);a.get(Math.round(c),d);)d--;for(b=Math.round(b.y);a.get(Math.round(c),b);)b++;return{x:c,y:(d+b)/2}} +function sa(a){var b=[],c=[];let d=[];var e=[];for(let p=0;p<=a.height;p++){var f=0,g=!1;let t=[0,0,0,0,0];for(let v=-1;v<=a.width;v++){var h=a.get(v,p);if(h===g)f++;else{t=[t[1],t[2],t[3],t[4],f];f=1;g=h;var k=O(t)/7;k=Math.abs(t[0]-k)y>=w.bottom.startX&& +y<=w.bottom.endX||z>=w.bottom.startX&&y<=w.bottom.endX||y<=w.bottom.startX&&z>=w.bottom.endX&&1.5>t[2]/(w.bottom.endX-w.bottom.startX)&&.5y>=w.bottom.startX&&y<=w.bottom.endX||z>=w.bottom.startX&&y<=w.bottom.endX||y<=w.bottom.startX&&z>=w.bottom.endX&&1.5>t[2]/(w.bottom.endX-w.bottom.startX)&&.5v.bottom.y!==p&&2<=v.bottom.y-v.top.y));c=c.filter(v=>v.bottom.y===p);d.push(...e.filter(v=>v.bottom.y!==p));e=e.filter(v=>v.bottom.y===p)}b.push(...c.filter(p=>2<=p.bottom.y-p.top.y));d.push(...e);c=[];for(var l of b)2>l.bottom.y-l.top.y||(b=(l.top.startX+l.top.endX+l.bottom.startX+l.bottom.endX)/4,e=(l.top.y+l.bottom.y+1)/2,a.get(Math.round(b),Math.round(e))&&(f=[l.top.endX-l.top.startX,l.bottom.endX-l.bottom.startX,l.bottom.y-l.top.y+ +1],f=O(f)/f.length,g=S({x:Math.round(b),y:Math.round(e)},[1,1,3,1,1],a),c.push({score:g,x:b,y:e,size:f})));if(3>c.length)return null;c.sort((p,t)=>p.score-t.score);l=[];for(b=0;bp.score-t.score);l.push({points:[e,f[0],f[1]],score:e.score+f[0].score+f[1].score})}l.sort((p,t)=>p.score-t.score);let {topRight:q,topLeft:r,bottomLeft:u}=qa(...l[0].points); +l=U(a,d,q,r,u);n=[];l&&n.push({alignmentPattern:{x:l.alignmentPattern.x,y:l.alignmentPattern.y},bottomLeft:{x:u.x,y:u.y},dimension:l.dimension,topLeft:{x:r.x,y:r.y},topRight:{x:q.x,y:q.y}});l=T(a,q);b=T(a,r);c=T(a,u);(a=U(a,d,l,b,c))&&n.push({alignmentPattern:{x:a.alignmentPattern.x,y:a.alignmentPattern.y},bottomLeft:{x:c.x,y:c.y},topLeft:{x:b.x,y:b.y},topRight:{x:l.x,y:l.y},dimension:a.dimension});return 0===n.length?null:n} +function U(a,b,c,d,e){let f,g;try{({dimension:f,moduleSize:g}=ra(d,c,e,a))}catch(l){return null}var h=c.x-d.x+e.x,k=c.y-d.y+e.y;c=(N(d,e)+N(d,c))/2/g;e=1-3/c;let m={x:d.x+e*(h-d.x),y:d.y+e*(k-d.y)};b=b.map(l=>{const n=(l.top.startX+l.top.endX+l.bottom.startX+l.bottom.endX)/4;l=(l.top.y+l.bottom.y+1)/2;if(a.get(Math.floor(n),Math.floor(l))){var q=S({x:Math.floor(n),y:Math.floor(l)},[1,1,1],a)+N({x:n,y:l},m);return{x:n,y:l,score:q}}}).filter(l=>!!l).sort((l,n)=>l.score-n.score);return{alignmentPattern:15<= +c&&b.length?b[0]:m,dimension:f}} +function V(a){var b=sa(a);if(!b)return null;for(let e of b){b=pa(a,e);var c=b.matrix;if(null==c)c=null;else{var d=L(c);if(d)c=d;else{for(d=0;d{a[c]=b[c]})} +function X(a,b,c,d={}){let e=Object.create(null);W(e,ta);W(e,d);d="onlyInvert"===e.inversionAttempts||"invertFirst"===e.inversionAttempts;var f="attemptBoth"===e.inversionAttempts||d;var g=e.greyScaleWeights,h=e.canOverwriteImage,k=b*c;if(a.length!==4*k)throw Error("Malformed data passed to binarizer.");var m=0;if(h){var l=new Uint8ClampedArray(a.buffer,m,k);m+=k}l=new A(b,c,l);if(g.useIntegerApproximation)for(var n=0;n>8)}else for(n=0;nv;v++)for(let w=0;8>w;w++){let aa=l.get(8*r+w,8*q+v);p=Math.min(p,aa);t=Math.max(t,aa)}v=(p+t)/2;v=Math.min(255,1.11*v);24>=t-p&&(v=p/2,0a?2:a>c?c:a;h=n-3;h=2>b?2:b>h?h:b;k=0;for(m=-2;2>=m;m++)for(p=-2;2>=p;p++)k+=u.get(c+m,h+p);c=k/25;for(h=0;8>h;h++)for(k=0;8>k;k++)m=8*a+h,p=8*b+k,t=l.get(m,p),q.set(m,p,t<=c),f&&r.set(m,p,!(t<=c))}f=f?{binarized:q,inverted:r}:{binarized:q};let {binarized:z,inverted:y}=f;(f=V(d? +y:z))||"attemptBoth"!==e.inversionAttempts&&"invertFirst"!==e.inversionAttempts||(f=V(d?z:y));return f}X.default=X;let Y="dontInvert",Z={red:77,green:150,blue:29,useIntegerApproximation:!0}; +self.onmessage=a=>{let b=a.data.id,c=a.data.data;switch(a.data.type){case "decode":(a=X(c.data,c.width,c.height,{inversionAttempts:Y,greyScaleWeights:Z}))?self.postMessage({id:b,type:"qrResult",data:a.data,bytes:a.binaryData,cornerPoints:[a.location.topLeftCorner,a.location.topRightCorner,a.location.bottomRightCorner,a.location.bottomLeftCorner]}):self.postMessage({id:b,type:"qrResult",data:null});break;case "grayscaleWeights":Z.red=c.red;Z.green=c.green;Z.blue=c.blue;Z.useIntegerApproximation=c.useIntegerApproximation; +break;case "inversionMode":switch(c){case "original":Y="dontInvert";break;case "invert":Y="onlyInvert";break;case "both":Y="attemptBoth";break;default:throw Error("Invalid inversion mode");}break;case "close":self.close()}} +`]), { type: "application/javascript" })); + +// src/external/mii-frontend/qr-scanner.umd.min.js +var require_qr_scanner_umd_min = __commonJS((exports2, module2) => { + (function(e, a2) { + typeof exports2 === "object" && typeof module2 !== "undefined" ? module2.exports = a2() : typeof define === "function" && define.amd ? define(a2) : (e = typeof globalThis !== "undefined" ? globalThis : e || self, e.QrScanner = a2()); + })(exports2, function() { + + class e { + constructor(a2, b3, c2, d, f) { + this._legacyCanvasSize = e.DEFAULT_CANVAS_SIZE; + this._preferredCamera = "environment"; + this._maxScansPerSecond = 25; + this._lastScanTimestamp = -1; + this._destroyed = this._flashOn = this._paused = this._active = false; + this.$video = a2; + this.$canvas = document.createElement("canvas"); + c2 && typeof c2 === "object" ? this._onDecode = b3 : (c2 || d || f ? console.warn("You're using a deprecated version of the QrScanner constructor which will be removed in the future") : console.warn("Note that the type of the scan result passed to onDecode will change in the future. To already switch to the new api today, you can pass returnDetailedScanResult: true."), this._legacyOnDecode = b3); + b3 = typeof c2 === "object" ? c2 : {}; + this._onDecodeError = b3.onDecodeError || (typeof c2 === "function" ? c2 : this._onDecodeError); + this._calculateScanRegion = b3.calculateScanRegion || (typeof d === "function" ? d : this._calculateScanRegion); + this._preferredCamera = b3.preferredCamera || f || this._preferredCamera; + this._legacyCanvasSize = typeof c2 === "number" ? c2 : typeof d === "number" ? d : this._legacyCanvasSize; + this._maxScansPerSecond = b3.maxScansPerSecond || this._maxScansPerSecond; + this._onPlay = this._onPlay.bind(this); + this._onLoadedMetaData = this._onLoadedMetaData.bind(this); + this._onVisibilityChange = this._onVisibilityChange.bind(this); + this._updateOverlay = this._updateOverlay.bind(this); + a2.disablePictureInPicture = true; + a2.playsInline = true; + a2.muted = true; + let h = false; + a2.hidden && (a2.hidden = false, h = true); + document.body.contains(a2) || (document.body.appendChild(a2), h = true); + c2 = a2.parentElement; + if (b3.highlightScanRegion || b3.highlightCodeOutline) { + d = !!b3.overlay; + this.$overlay = b3.overlay || document.createElement("div"); + f = this.$overlay.style; + f.position = "absolute"; + f.display = "none"; + f.pointerEvents = "none"; + this.$overlay.classList.add("scan-region-highlight"); + if (!d && b3.highlightScanRegion) { + this.$overlay.innerHTML = ''; + try { + this.$overlay.firstElementChild.animate({ transform: ["scale(.98)", "scale(1.01)"] }, { duration: 400, iterations: Infinity, direction: "alternate", easing: "ease-in-out" }); + } catch (m) { + } + c2.insertBefore(this.$overlay, this.$video.nextSibling); + } + b3.highlightCodeOutline && (this.$overlay.insertAdjacentHTML("beforeend", ''), this.$codeOutlineHighlight = this.$overlay.lastElementChild); + } + this._scanRegion = this._calculateScanRegion(a2); + requestAnimationFrame(() => { + let m = window.getComputedStyle(a2); + m.display === "none" && (a2.style.setProperty("display", "block", "important"), h = true); + m.visibility !== "visible" && (a2.style.setProperty("visibility", "visible", "important"), h = true); + h && (console.warn("QrScanner has overwritten the video hiding style to avoid Safari stopping the playback."), a2.style.opacity = "0", a2.style.width = "0", a2.style.height = "0", this.$overlay && this.$overlay.parentElement && this.$overlay.parentElement.removeChild(this.$overlay), delete this.$overlay, delete this.$codeOutlineHighlight); + this.$overlay && this._updateOverlay(); + }); + a2.addEventListener("play", this._onPlay); + a2.addEventListener("loadedmetadata", this._onLoadedMetaData); + document.addEventListener("visibilitychange", this._onVisibilityChange); + window.addEventListener("resize", this._updateOverlay); + this._qrEnginePromise = e.createQrEngine(); + } + static set WORKER_PATH(a2) { + console.warn("Setting QrScanner.WORKER_PATH is not required and not supported anymore. Have a look at the README for new setup instructions."); + } + static async hasCamera() { + try { + return !!(await e.listCameras(false)).length; + } catch (a2) { + return false; + } + } + static async listCameras(a2 = false) { + if (!navigator.mediaDevices) + return []; + let b3 = async () => (await navigator.mediaDevices.enumerateDevices()).filter((d) => d.kind === "videoinput"), c2; + try { + a2 && (await b3()).every((d) => !d.label) && (c2 = await navigator.mediaDevices.getUserMedia({ audio: false, video: true })); + } catch (d) { + } + try { + return (await b3()).map((d, f) => ({ id: d.deviceId, label: d.label || (f === 0 ? "Default Camera" : `Camera ${f + 1}`) })); + } finally { + c2 && (console.warn("Call listCameras after successfully starting a QR scanner to avoid creating a temporary video stream"), e._stopVideoStream(c2)); + } + } + async hasFlash() { + let a2; + try { + if (this.$video.srcObject) { + if (!(this.$video.srcObject instanceof MediaStream)) + return false; + a2 = this.$video.srcObject; + } else + a2 = (await this._getCameraStream()).stream; + return "torch" in a2.getVideoTracks()[0].getSettings(); + } catch (b3) { + return false; + } finally { + a2 && a2 !== this.$video.srcObject && (console.warn("Call hasFlash after successfully starting the scanner to avoid creating a temporary video stream"), e._stopVideoStream(a2)); + } + } + isFlashOn() { + return this._flashOn; + } + async toggleFlash() { + this._flashOn ? await this.turnFlashOff() : await this.turnFlashOn(); + } + async turnFlashOn() { + if (!this._flashOn && !this._destroyed && (this._flashOn = true, this._active && !this._paused)) + try { + if (!await this.hasFlash()) + throw "No flash available"; + await this.$video.srcObject.getVideoTracks()[0].applyConstraints({ advanced: [{ torch: true }] }); + } catch (a2) { + throw this._flashOn = false, a2; + } + } + async turnFlashOff() { + this._flashOn && (this._flashOn = false, await this._restartVideoStream()); + } + destroy() { + this.$video.removeEventListener("loadedmetadata", this._onLoadedMetaData); + this.$video.removeEventListener("play", this._onPlay); + document.removeEventListener("visibilitychange", this._onVisibilityChange); + window.removeEventListener("resize", this._updateOverlay); + this._destroyed = true; + this._flashOn = false; + this.stop(); + e._postWorkerMessage(this._qrEnginePromise, "close"); + } + async start() { + if (this._destroyed) + throw Error("The QR scanner can not be started as it had been destroyed."); + if (!this._active || this._paused) { + if (window.location.protocol !== "https:" && console.warn("The camera stream is only accessible if the page is transferred via https."), this._active = true, !document.hidden) + if (this._paused = false, this.$video.srcObject) + await this.$video.play(); + else + try { + let { stream: a2, facingMode: b3 } = await this._getCameraStream(); + !this._active || this._paused ? e._stopVideoStream(a2) : (this._setVideoMirror(b3), this.$video.srcObject = a2, await this.$video.play(), this._flashOn && (this._flashOn = false, this.turnFlashOn().catch(() => { + }))); + } catch (a2) { + if (!this._paused) + throw this._active = false, a2; + } + } + } + stop() { + this.pause(); + this._active = false; + } + async pause(a2 = false) { + this._paused = true; + if (!this._active) + return true; + this.$video.pause(); + this.$overlay && (this.$overlay.style.display = "none"); + let b3 = () => { + this.$video.srcObject instanceof MediaStream && (e._stopVideoStream(this.$video.srcObject), this.$video.srcObject = null); + }; + if (a2) + return b3(), true; + await new Promise((c2) => setTimeout(c2, 300)); + if (!this._paused) + return false; + b3(); + return true; + } + async setCamera(a2) { + a2 !== this._preferredCamera && (this._preferredCamera = a2, await this._restartVideoStream()); + } + static async scanImage(a2, b3, c2, d, f = false, h = false) { + let m, n2 = false; + b3 && (("scanRegion" in b3) || ("qrEngine" in b3) || ("canvas" in b3) || ("disallowCanvasResizing" in b3) || ("alsoTryWithoutScanRegion" in b3) || ("returnDetailedScanResult" in b3)) ? (m = b3.scanRegion, c2 = b3.qrEngine, d = b3.canvas, f = b3.disallowCanvasResizing || false, h = b3.alsoTryWithoutScanRegion || false, n2 = true) : b3 || c2 || d || f || h ? console.warn("You're using a deprecated api for scanImage which will be removed in the future.") : console.warn("Note that the return type of scanImage will change in the future. To already switch to the new api today, you can pass returnDetailedScanResult: true."); + b3 = !!c2; + try { + let p, l2; + [c2, p] = await Promise.all([c2 || e.createQrEngine(), e._loadImage(a2)]); + [d, l2] = e._drawToCanvas(p, m, d, f); + let q2; + if (c2 instanceof Worker) { + let g3 = c2; + b3 || e._postWorkerMessageSync(g3, "inversionMode", "both"); + q2 = await new Promise((k4, v) => { + let w, u3, t4, y3 = -1; + u3 = (r) => { + r.data.id === y3 && (g3.removeEventListener("message", u3), g3.removeEventListener("error", t4), clearTimeout(w), r.data.data !== null ? k4({ data: r.data.data, cornerPoints: e._convertPoints(r.data.cornerPoints, m), bytes: r.data.bytes }) : v(e.NO_QR_CODE_FOUND)); + }; + t4 = (r) => { + g3.removeEventListener("message", u3); + g3.removeEventListener("error", t4); + clearTimeout(w); + v("Scanner error: " + (r ? r.message || r : "Unknown Error")); + }; + g3.addEventListener("message", u3); + g3.addEventListener("error", t4); + w = setTimeout(() => t4("timeout"), 1e4); + let x2 = l2.getImageData(0, 0, d.width, d.height); + y3 = e._postWorkerMessageSync(g3, "decode", x2, [x2.data.buffer]); + }); + } else + q2 = await Promise.race([new Promise((g3, k4) => window.setTimeout(() => k4("Scanner error: timeout"), 1e4)), (async () => { + try { + var [g3] = await c2.detect(d); + return { noQrCode: !g3, data: g3.rawValue, cornerPoints: e._convertPoints(g3.cornerPoints, m), bytes: g3.rawValue.split("").map((k4) => k4.charCodeAt(0)) }; + } catch (k4) { + g3 = k4.message || k4; + if (/not implemented|service unavailable/.test(g3)) + return e._disableBarcodeDetector = true, e.scanImage(a2, { scanRegion: m, canvas: d, disallowCanvasResizing: f, alsoTryWithoutScanRegion: h }); + throw `Scanner error: ${g3}`; + } + })()]); + return n2 ? q2 : q2.data; + } catch (p) { + if (!m || !h) + throw p; + let l2 = await e.scanImage(a2, { qrEngine: c2, canvas: d, disallowCanvasResizing: f }); + return n2 ? l2 : l2.data; + } finally { + b3 || e._postWorkerMessage(c2, "close"); + } + } + setGrayscaleWeights(a2, b3, c2, d = true) { + e._postWorkerMessage(this._qrEnginePromise, "grayscaleWeights", { red: a2, green: b3, blue: c2, useIntegerApproximation: d }); + } + setInversionMode(a2) { + e._postWorkerMessage(this._qrEnginePromise, "inversionMode", a2); + } + static async createQrEngine(a2) { + a2 && console.warn("Specifying a worker path is not required and not supported anymore."); + return !e._disableBarcodeDetector && "BarcodeDetector" in window && BarcodeDetector.getSupportedFormats && (await BarcodeDetector.getSupportedFormats()).includes("qr_code") ? new BarcodeDetector({ formats: ["qr_code"] }) : Promise.resolve().then(() => exports_qr_scanner_worker_min).then((b3) => b3.createWorker()); + } + _onPlay() { + this._scanRegion = this._calculateScanRegion(this.$video); + this._updateOverlay(); + this.$overlay && (this.$overlay.style.display = ""); + this._scanFrame(); + } + _onLoadedMetaData() { + this._scanRegion = this._calculateScanRegion(this.$video); + this._updateOverlay(); + } + _onVisibilityChange() { + document.hidden ? this.pause() : this._active && this.start(); + } + _calculateScanRegion(a2) { + let b3 = Math.round(0.6666666666666666 * Math.min(a2.videoWidth, a2.videoHeight)); + return { x: Math.round((a2.videoWidth - b3) / 2), y: Math.round((a2.videoHeight - b3) / 2), width: b3, height: b3, downScaledWidth: this._legacyCanvasSize, downScaledHeight: this._legacyCanvasSize }; + } + _updateOverlay() { + requestAnimationFrame(() => { + if (this.$overlay) { + var a2 = this.$video, b3 = a2.videoWidth, c2 = a2.videoHeight, d = a2.offsetWidth, f = a2.offsetHeight, h = a2.offsetLeft, m = a2.offsetTop, n2 = window.getComputedStyle(a2), p = n2.objectFit, l2 = b3 / c2, q2 = d / f; + switch (p) { + case "none": + var g3 = b3; + var k4 = c2; + break; + case "fill": + g3 = d; + k4 = f; + break; + default: + (p === "cover" ? l2 > q2 : l2 < q2) ? (k4 = f, g3 = k4 * l2) : (g3 = d, k4 = g3 / l2), p === "scale-down" && (g3 = Math.min(g3, b3), k4 = Math.min(k4, c2)); + } + var [ + v, + w + ] = n2.objectPosition.split(" ").map((t4, y3) => { + const x2 = parseFloat(t4); + return t4.endsWith("%") ? (y3 ? f - k4 : d - g3) * x2 / 100 : x2; + }); + n2 = this._scanRegion.width || b3; + q2 = this._scanRegion.height || c2; + p = this._scanRegion.x || 0; + var u3 = this._scanRegion.y || 0; + l2 = this.$overlay.style; + l2.width = `${n2 / b3 * g3}px`; + l2.height = `${q2 / c2 * k4}px`; + l2.top = `${m + w + u3 / c2 * k4}px`; + c2 = /scaleX\(-1\)/.test(a2.style.transform); + l2.left = `${h + (c2 ? d - v - g3 : v) + (c2 ? b3 - p - n2 : p) / b3 * g3}px`; + l2.transform = a2.style.transform; + } + }); + } + static _convertPoints(a2, b3) { + if (!b3) + return a2; + let c2 = b3.x || 0, d = b3.y || 0, f = b3.width && b3.downScaledWidth ? b3.width / b3.downScaledWidth : 1; + b3 = b3.height && b3.downScaledHeight ? b3.height / b3.downScaledHeight : 1; + for (let h of a2) + h.x = h.x * f + c2, h.y = h.y * b3 + d; + return a2; + } + _scanFrame() { + !this._active || this.$video.paused || this.$video.ended || ("requestVideoFrameCallback" in this.$video ? this.$video.requestVideoFrameCallback.bind(this.$video) : requestAnimationFrame)(async () => { + if (!(1 >= this.$video.readyState)) { + var a2 = Date.now() - this._lastScanTimestamp, b3 = 1000 / this._maxScansPerSecond; + a2 < b3 && await new Promise((d) => setTimeout(d, b3 - a2)); + this._lastScanTimestamp = Date.now(); + try { + var c2 = await e.scanImage(this.$video, { scanRegion: this._scanRegion, qrEngine: this._qrEnginePromise, canvas: this.$canvas }); + } catch (d) { + if (!this._active) + return; + this._onDecodeError(d); + } + !e._disableBarcodeDetector || await this._qrEnginePromise instanceof Worker || (this._qrEnginePromise = e.createQrEngine()); + c2 ? (this._onDecode ? this._onDecode(c2) : this._legacyOnDecode && this._legacyOnDecode(c2.data), this.$codeOutlineHighlight && (clearTimeout(this._codeOutlineHighlightRemovalTimeout), this._codeOutlineHighlightRemovalTimeout = undefined, this.$codeOutlineHighlight.setAttribute("viewBox", `${this._scanRegion.x || 0} ${this._scanRegion.y || 0} ${this._scanRegion.width || this.$video.videoWidth} ${this._scanRegion.height || this.$video.videoHeight}`), this.$codeOutlineHighlight.firstElementChild.setAttribute("points", c2.cornerPoints.map(({ x: d, y: f }) => `${d},${f}`).join(" ")), this.$codeOutlineHighlight.style.display = "")) : this.$codeOutlineHighlight && !this._codeOutlineHighlightRemovalTimeout && (this._codeOutlineHighlightRemovalTimeout = setTimeout(() => this.$codeOutlineHighlight.style.display = "none", 100)); + } + this._scanFrame(); + }); + } + _onDecodeError(a2) { + a2 !== e.NO_QR_CODE_FOUND && console.log(a2); + } + async _getCameraStream() { + if (!navigator.mediaDevices) + throw "Camera not found."; + let a2 = /^(environment|user)$/.test(this._preferredCamera) ? "facingMode" : "deviceId", b3 = [{ width: { min: 1024 } }, { width: { min: 768 } }, {}], c2 = b3.map((d) => Object.assign({}, d, { [a2]: { exact: this._preferredCamera } })); + for (let d of [...c2, ...b3]) + try { + let f = await navigator.mediaDevices.getUserMedia({ + video: d, + audio: false + }), h = this._getFacingMode(f) || (d.facingMode ? this._preferredCamera : this._preferredCamera === "environment" ? "user" : "environment"); + return { stream: f, facingMode: h }; + } catch (f) { + } + throw "Camera not found."; + } + async _restartVideoStream() { + let a2 = this._paused; + await this.pause(true) && !a2 && this._active && await this.start(); + } + static _stopVideoStream(a2) { + for (let b3 of a2.getTracks()) + b3.stop(), a2.removeTrack(b3); + } + _setVideoMirror(a2) { + this.$video.style.transform = "scaleX(" + (a2 === "user" ? -1 : 1) + ")"; + } + _getFacingMode(a2) { + return (a2 = a2.getVideoTracks()[0]) ? /rear|back|environment/i.test(a2.label) ? "environment" : /front|user|face/i.test(a2.label) ? "user" : null : null; + } + static _drawToCanvas(a2, b3, c2, d = false) { + c2 = c2 || document.createElement("canvas"); + let f = b3 && b3.x ? b3.x : 0, h = b3 && b3.y ? b3.y : 0, m = b3 && b3.width ? b3.width : a2.videoWidth || a2.width, n2 = b3 && b3.height ? b3.height : a2.videoHeight || a2.height; + d || (d = b3 && b3.downScaledWidth ? b3.downScaledWidth : m, b3 = b3 && b3.downScaledHeight ? b3.downScaledHeight : n2, c2.width !== d && (c2.width = d), c2.height !== b3 && (c2.height = b3)); + b3 = c2.getContext("2d", { alpha: false }); + b3.imageSmoothingEnabled = false; + b3.drawImage(a2, f, h, m, n2, 0, 0, c2.width, c2.height); + return [c2, b3]; + } + static async _loadImage(a2) { + if (a2 instanceof Image) + return await e._awaitImageLoad(a2), a2; + if (a2 instanceof HTMLVideoElement || a2 instanceof HTMLCanvasElement || a2 instanceof SVGImageElement || "OffscreenCanvas" in window && a2 instanceof OffscreenCanvas || "ImageBitmap" in window && a2 instanceof ImageBitmap) + return a2; + if (a2 instanceof File || a2 instanceof Blob || a2 instanceof URL || typeof a2 === "string") { + let b3 = new Image; + b3.src = a2 instanceof File || a2 instanceof Blob ? URL.createObjectURL(a2) : a2.toString(); + try { + return await e._awaitImageLoad(b3), b3; + } finally { + (a2 instanceof File || a2 instanceof Blob) && URL.revokeObjectURL(b3.src); + } + } else + throw "Unsupported image type."; + } + static async _awaitImageLoad(a2) { + a2.complete && a2.naturalWidth !== 0 || await new Promise((b3, c2) => { + let d = (f) => { + a2.removeEventListener("load", d); + a2.removeEventListener("error", d); + f instanceof ErrorEvent ? c2("Image load error") : b3(); + }; + a2.addEventListener("load", d); + a2.addEventListener("error", d); + }); + } + static async _postWorkerMessage(a2, b3, c2, d) { + return e._postWorkerMessageSync(await a2, b3, c2, d); + } + static _postWorkerMessageSync(a2, b3, c2, d) { + if (!(a2 instanceof Worker)) + return -1; + let f = e._workerMessageId++; + a2.postMessage({ id: f, type: b3, data: c2 }, d); + return f; + } + } + e.DEFAULT_CANVAS_SIZE = 400; + e.NO_QR_CODE_FOUND = "No QR code found"; + e._disableBarcodeDetector = false; + e._workerMessageId = 0; + return e; + }); +}); + +// node_modules/vanilla-lazyload/dist/lazyload.min.js +var require_lazyload_min = __commonJS((exports2, module2) => { + (function(e, t4) { + typeof exports2 == "object" && typeof module2 != "undefined" ? module2.exports = t4() : typeof define == "function" && define.amd ? define(t4) : (e = typeof globalThis != "undefined" ? globalThis : e || self).LazyLoad = t4(); + })(exports2, function() { + const e = typeof window != "undefined", t4 = e && !("onscroll" in window) || typeof navigator != "undefined" && /(gle|ing|ro)bot|crawl|spider/i.test(navigator.userAgent), a2 = e && window.devicePixelRatio > 1, n2 = { elements_selector: ".lazy", container: t4 || e ? document : null, threshold: 300, thresholds: null, data_src: "src", data_srcset: "srcset", data_sizes: "sizes", data_bg: "bg", data_bg_hidpi: "bg-hidpi", data_bg_multi: "bg-multi", data_bg_multi_hidpi: "bg-multi-hidpi", data_bg_set: "bg-set", data_poster: "poster", class_applied: "applied", class_loading: "loading", class_loaded: "loaded", class_error: "error", class_entered: "entered", class_exited: "exited", unobserve_completed: true, unobserve_entered: false, cancel_on_exit: true, callback_enter: null, callback_exit: null, callback_applied: null, callback_loading: null, callback_loaded: null, callback_error: null, callback_finish: null, callback_cancel: null, use_native: false, restore_on_error: false }, s = (e2) => Object.assign({}, n2, e2), l2 = function(e2, t6) { + let a3; + const n4 = "LazyLoad::Initialized", s3 = new e2(t6); + try { + a3 = new CustomEvent(n4, { detail: { instance: s3 } }); + } catch (e3) { + a3 = document.createEvent("CustomEvent"), a3.initCustomEvent(n4, false, false, { instance: s3 }); + } + window.dispatchEvent(a3); + }, o = "src", r = "srcset", i = "sizes", d = "poster", c2 = "llOriginalAttrs", _9 = "data", u3 = "loading", g3 = "loaded", b3 = "applied", h = "error", m = "native", p = "data-", f = "ll-status", v = (e2, t6) => e2.getAttribute(p + t6), E2 = (e2) => v(e2, f), I3 = (e2, t6) => ((e3, t7, a3) => { + const n4 = p + t7; + a3 !== null ? e3.setAttribute(n4, a3) : e3.removeAttribute(n4); + })(e2, f, t6), y3 = (e2) => I3(e2, null), k4 = (e2) => E2(e2) === null, A4 = (e2) => E2(e2) === m, L = [u3, g3, b3, h], w = (e2, t6, a3, n4) => { + e2 && typeof e2 == "function" && (n4 === undefined ? a3 === undefined ? e2(t6) : e2(t6, a3) : e2(t6, a3, n4)); + }, x2 = (t6, a3) => { + e && a3 !== "" && t6.classList.add(a3); + }, C5 = (t6, a3) => { + e && a3 !== "" && t6.classList.remove(a3); + }, O = (e2) => e2.llTempImage, M = (e2, t6) => { + if (!t6) + return; + const a3 = t6._observer; + a3 && a3.unobserve(e2); + }, z2 = (e2, t6) => { + e2 && (e2.loadingCount += t6); + }, N = (e2, t6) => { + e2 && (e2.toLoadCount = t6); + }, T3 = (e2) => { + let t6 = []; + for (let a3, n4 = 0;a3 = e2.children[n4]; n4 += 1) + a3.tagName === "SOURCE" && t6.push(a3); + return t6; + }, R4 = (e2, t6) => { + const a3 = e2.parentNode; + a3 && a3.tagName === "PICTURE" && T3(a3).forEach(t6); + }, G2 = (e2, t6) => { + T3(e2).forEach(t6); + }, D = [o], H = [o, d], V3 = [o, r, i], F = [_9], j2 = (e2) => !!e2[c2], B3 = (e2) => e2[c2], J2 = (e2) => delete e2[c2], S = (e2, t6) => { + if (j2(e2)) + return; + const a3 = {}; + t6.forEach((t7) => { + a3[t7] = e2.getAttribute(t7); + }), e2[c2] = a3; + }, P = (e2, t6) => { + if (!j2(e2)) + return; + const a3 = B3(e2); + t6.forEach((t7) => { + ((e3, t8, a4) => { + a4 ? e3.setAttribute(t8, a4) : e3.removeAttribute(t8); + })(e2, t7, a3[t7]); + }); + }, U = (e2, t6, a3) => { + x2(e2, t6.class_applied), I3(e2, b3), a3 && (t6.unobserve_completed && M(e2, t6), w(t6.callback_applied, e2, a3)); + }, $2 = (e2, t6, a3) => { + x2(e2, t6.class_loading), I3(e2, u3), a3 && (z2(a3, 1), w(t6.callback_loading, e2, a3)); + }, q2 = (e2, t6, a3) => { + a3 && e2.setAttribute(t6, a3); + }, K = (e2, t6) => { + q2(e2, i, v(e2, t6.data_sizes)), q2(e2, r, v(e2, t6.data_srcset)), q2(e2, o, v(e2, t6.data_src)); + }, Q3 = { IMG: (e2, t6) => { + R4(e2, (e3) => { + S(e3, V3), K(e3, t6); + }), S(e2, V3), K(e2, t6); + }, IFRAME: (e2, t6) => { + S(e2, D), q2(e2, o, v(e2, t6.data_src)); + }, VIDEO: (e2, t6) => { + G2(e2, (e3) => { + S(e3, D), q2(e3, o, v(e3, t6.data_src)); + }), S(e2, H), q2(e2, d, v(e2, t6.data_poster)), q2(e2, o, v(e2, t6.data_src)), e2.load(); + }, OBJECT: (e2, t6) => { + S(e2, F), q2(e2, _9, v(e2, t6.data_src)); + } }, W = ["IMG", "IFRAME", "VIDEO", "OBJECT"], X = (e2, t6) => { + !t6 || ((e3) => e3.loadingCount > 0)(t6) || ((e3) => e3.toLoadCount > 0)(t6) || w(e2.callback_finish, t6); + }, Y = (e2, t6, a3) => { + e2.addEventListener(t6, a3), e2.llEvLisnrs[t6] = a3; + }, Z3 = (e2, t6, a3) => { + e2.removeEventListener(t6, a3); + }, ee = (e2) => !!e2.llEvLisnrs, te3 = (e2) => { + if (!ee(e2)) + return; + const t6 = e2.llEvLisnrs; + for (let a3 in t6) { + const n4 = t6[a3]; + Z3(e2, a3, n4); + } + delete e2.llEvLisnrs; + }, ae3 = (e2, t6, a3) => { + ((e3) => { + delete e3.llTempImage; + })(e2), z2(a3, -1), ((e3) => { + e3 && (e3.toLoadCount -= 1); + })(a3), C5(e2, t6.class_loading), t6.unobserve_completed && M(e2, a3); + }, ne2 = (e2, t6, a3) => { + const n4 = O(e2) || e2; + ee(n4) || ((e3, t7, a4) => { + ee(e3) || (e3.llEvLisnrs = {}); + const n5 = e3.tagName === "VIDEO" ? "loadeddata" : "load"; + Y(e3, n5, t7), Y(e3, "error", a4); + })(n4, (s3) => { + ((e3, t7, a4, n5) => { + const s4 = A4(t7); + ae3(t7, a4, n5), x2(t7, a4.class_loaded), I3(t7, g3), w(a4.callback_loaded, t7, n5), s4 || X(a4, n5); + })(0, e2, t6, a3), te3(n4); + }, (s3) => { + ((e3, t7, a4, n5) => { + const s4 = A4(t7); + ae3(t7, a4, n5), x2(t7, a4.class_error), I3(t7, h), w(a4.callback_error, t7, n5), a4.restore_on_error && P(t7, V3), s4 || X(a4, n5); + })(0, e2, t6, a3), te3(n4); + }); + }, se2 = (e2, t6, n4) => { + ((e3) => W.indexOf(e3.tagName) > -1)(e2) ? ((e3, t7, a3) => { + ne2(e3, t7, a3), ((e4, t8, a4) => { + const n5 = Q3[e4.tagName]; + n5 && (n5(e4, t8), $2(e4, t8, a4)); + })(e3, t7, a3); + })(e2, t6, n4) : ((e3, t7, n5) => { + ((e4) => { + e4.llTempImage = document.createElement("IMG"); + })(e3), ne2(e3, t7, n5), ((e4) => { + j2(e4) || (e4[c2] = { backgroundImage: e4.style.backgroundImage }); + })(e3), ((e4, t8, n6) => { + const s3 = v(e4, t8.data_bg), l3 = v(e4, t8.data_bg_hidpi), r2 = a2 && l3 ? l3 : s3; + r2 && (e4.style.backgroundImage = `url("${r2}")`, O(e4).setAttribute(o, r2), $2(e4, t8, n6)); + })(e3, t7, n5), ((e4, t8, n6) => { + const s3 = v(e4, t8.data_bg_multi), l3 = v(e4, t8.data_bg_multi_hidpi), o2 = a2 && l3 ? l3 : s3; + o2 && (e4.style.backgroundImage = o2, U(e4, t8, n6)); + })(e3, t7, n5), ((e4, t8, a3) => { + const n6 = v(e4, t8.data_bg_set); + if (!n6) + return; + let s3 = n6.split("|").map((e5) => `image-set(${e5})`); + e4.style.backgroundImage = s3.join(), U(e4, t8, a3); + })(e3, t7, n5); + })(e2, t6, n4); + }, le = (e2) => { + e2.removeAttribute(o), e2.removeAttribute(r), e2.removeAttribute(i); + }, oe = (e2) => { + R4(e2, (e3) => { + P(e3, V3); + }), P(e2, V3); + }, re = { IMG: oe, IFRAME: (e2) => { + P(e2, D); + }, VIDEO: (e2) => { + G2(e2, (e3) => { + P(e3, D); + }), P(e2, H), e2.load(); + }, OBJECT: (e2) => { + P(e2, F); + } }, ie = (e2, t6) => { + ((e3) => { + const t7 = re[e3.tagName]; + t7 ? t7(e3) : ((e4) => { + if (!j2(e4)) + return; + const t8 = B3(e4); + e4.style.backgroundImage = t8.backgroundImage; + })(e3); + })(e2), ((e3, t7) => { + k4(e3) || A4(e3) || (C5(e3, t7.class_entered), C5(e3, t7.class_exited), C5(e3, t7.class_applied), C5(e3, t7.class_loading), C5(e3, t7.class_loaded), C5(e3, t7.class_error)); + })(e2, t6), y3(e2), J2(e2); + }, de = ["IMG", "IFRAME", "VIDEO"], ce3 = (e2) => e2.use_native && ("loading" in HTMLImageElement.prototype), _e = (e2, t6, a3) => { + e2.forEach((e3) => ((e4) => e4.isIntersecting || e4.intersectionRatio > 0)(e3) ? ((e4, t7, a4, n4) => { + const s3 = ((e5) => L.indexOf(E2(e5)) >= 0)(e4); + I3(e4, "entered"), x2(e4, a4.class_entered), C5(e4, a4.class_exited), ((e5, t8, a5) => { + t8.unobserve_entered && M(e5, a5); + })(e4, a4, n4), w(a4.callback_enter, e4, t7, n4), s3 || se2(e4, a4, n4); + })(e3.target, e3, t6, a3) : ((e4, t7, a4, n4) => { + k4(e4) || (x2(e4, a4.class_exited), ((e5, t8, a5, n5) => { + a5.cancel_on_exit && ((e6) => E2(e6) === u3)(e5) && e5.tagName === "IMG" && (te3(e5), ((e6) => { + R4(e6, (e7) => { + le(e7); + }), le(e6); + })(e5), oe(e5), C5(e5, a5.class_loading), z2(n5, -1), y3(e5), w(a5.callback_cancel, e5, t8, n5)); + })(e4, t7, a4, n4), w(a4.callback_exit, e4, t7, n4)); + })(e3.target, e3, t6, a3)); + }, ue3 = (e2) => Array.prototype.slice.call(e2), ge2 = (e2) => e2.container.querySelectorAll(e2.elements_selector), be = (e2) => ((e3) => E2(e3) === h)(e2), he = (e2, t6) => ((e3) => ue3(e3).filter(k4))(e2 || ge2(t6)), me = function(t6, a3) { + const n4 = s(t6); + this._settings = n4, this.loadingCount = 0, ((e2, t7) => { + ce3(e2) || (t7._observer = new IntersectionObserver((a4) => { + _e(a4, e2, t7); + }, ((e3) => ({ root: e3.container === document ? null : e3.container, rootMargin: e3.thresholds || e3.threshold + "px" }))(e2))); + })(n4, this), ((t7, a4) => { + e && (a4._onlineHandler = () => { + ((e2, t8) => { + var a5; + (a5 = ge2(e2), ue3(a5).filter(be)).forEach((t9) => { + C5(t9, e2.class_error), y3(t9); + }), t8.update(); + })(t7, a4); + }, window.addEventListener("online", a4._onlineHandler)); + })(n4, this), this.update(a3); + }; + return me.prototype = { update: function(e2) { + const a3 = this._settings, n4 = he(e2, a3); + var s3, l3; + N(this, n4.length), t4 ? this.loadAll(n4) : ce3(a3) ? ((e3, t6, a4) => { + e3.forEach((e4) => { + de.indexOf(e4.tagName) !== -1 && ((e5, t7, a5) => { + e5.setAttribute("loading", "lazy"), ne2(e5, t7, a5), ((e6, t8) => { + const a6 = Q3[e6.tagName]; + a6 && a6(e6, t8); + })(e5, t7), I3(e5, m); + })(e4, t6, a4); + }), N(a4, 0); + })(n4, a3, this) : (l3 = n4, ((e3) => { + e3.disconnect(); + })(s3 = this._observer), ((e3, t6) => { + t6.forEach((t7) => { + e3.observe(t7); + }); + })(s3, l3)); + }, destroy: function() { + this._observer && this._observer.disconnect(), e && window.removeEventListener("online", this._onlineHandler), ge2(this._settings).forEach((e2) => { + J2(e2); + }), delete this._observer, delete this._settings, delete this._onlineHandler, delete this.loadingCount, delete this.toLoadCount; + }, loadAll: function(e2) { + const t6 = this._settings; + he(e2, t6).forEach((e3) => { + M(e3, this), se2(e3, t6, this); + }); + }, restoreAll: function() { + const e2 = this._settings; + ge2(e2).forEach((t6) => { + ie(t6, e2); + }); + } }, me.load = (e2, t6) => { + const a3 = s(t6); + se2(e2, a3); + }, me.resetStatus = (e2) => { + y3(e2); + }, e && ((e2, t6) => { + if (t6) + if (t6.length) + for (let a3, n4 = 0;a3 = t6[n4]; n4 += 1) + l2(e2, a3); + else + l2(e2, t6); + })(me, window.lazyLoadOptions), me; + }); +}); + +// src/ui/setup.ts +var import_localforage14 = __toESM(require_localforage(), 1); + +// src/class/audio/MusicManager.ts +var import_localforage = __toESM(require_localforage(), 1); +var getMusicManager = () => mm; + +class MusicManager { + SongBufs; + audioContext; + gainNode; + muted; + previousVolume; + constructor() { + this.SongBufs = {}; + this.audioContext = new (window.AudioContext || window.webkitAudioContext); + this.gainNode = this.audioContext.createGain(); + this.gainNode.connect(this.audioContext.destination); + this.muted = false; + this.previousVolume = 0.28; + setTimeout(() => { + let theme = ""; + document.addEventListener("theme-change", () => { + let newTheme = document.documentElement.dataset.theme; + if (theme !== newTheme) { + this.initMusic(); + } + theme = newTheme; + }); + }, 2000); + this.sources = []; + } + mainSource; + editSource; + mainGainNode; + editGainNode; + theme; + async initMusic() { + this.sources.forEach((src) => src.stop()); + const theme = document.documentElement.dataset.theme !== undefined ? document.documentElement.dataset.theme : await import_localforage.default.getItem("settings_theme"); + if (this.theme === theme) + return; + this.theme = theme; + console.error("initMusic()", theme, document.documentElement.dataset.theme); + this.setVolume(0.28); + this.previousVolume = 0.28; + await this.loadSong("./assets/audio/miimakermusic.mp3", "mii_creator_music"); + this.initMusicReady(); + } + initMusicReady() { + setTimeout(async () => { + if (this.audioContext.state === "suspended") { + if (location.hostname === "localhost" || location.hostname === "127.0.0.1") { + this.playMusic(); + } + } + document.onclick = () => { + document.onclick = null; + this.playMusic(); + }; + }, 100); + } + started; + playMusic() { + if (this.mainSource) + this.mainSource.stop(); + if (this.editSource) + this.editSource.stop(); + this.playSong("mii_creator_music", 0, 100, true, true, (source, gainNode) => { + this.mainSource = source; + this.started = true; + this.mainGainNode = gainNode; + if (this.theme !== "wiiu") { + this.editSource = undefined; + this.editGainNode = undefined; + } + gainNode.gain.setValueAtTime(-1, this.audioContext.currentTime); + gainNode.gain.linearRampToValueAtTime(-0.6, this.audioContext.currentTime + 2); + }); + if (this.theme === "wiiu") + this.playSong("mii_editor_music", 0, 100, true, true, (source, gainNode) => { + this.editSource = source; + this.editGainNode = gainNode; + gainNode.gain.setValueAtTime(-1, this.audioContext.currentTime); + }); + } + async loadSong(url, name2) { + const response = await fetch(url); + const arrayBuffer = await response.arrayBuffer(); + const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer); + this.SongBufs[name2] = audioBuffer; + } + sources; + playSong(name2, loopStart = null, loopEnd = null, loops = true, autoPlay = true, callbackBeforeStart) { + try { + const SongBuffer = this.SongBufs[name2]; + if (!SongBuffer) { + console.error(`Song "${name2}" not found.`); + return null; + } + const source = this.audioContext.createBufferSource(); + source.buffer = SongBuffer; + source.connect(this.gainNode); + if (loops === true) + source.loop = true; + if (loopStart !== null) + source.loopStart = loopStart; + if (loopEnd !== null) + source.loopEnd = loopEnd; + this.sources.push(source); + const gainNode = this.audioContext.createGain(); + source.connect(gainNode); + gainNode.connect(this.gainNode); + if (callbackBeforeStart) { + callbackBeforeStart(source, gainNode); + } + if (autoPlay) { + source.start(); + } + return { source, gainNode }; + } catch (e) { + console.log("OOPS", e); + return null; + } + } + stopSong() { + this.audioContext.suspend(); + } + setVolume(volume) { + if (this.muted) + return; + this.gainNode.gain.value = volume; + } + mute() { + if (this.muted) + return; + this.previousVolume = this.gainNode.gain.value; + this.setVolume(0); + this.muted = true; + } + unmute() { + if (this.muted === false) + return; + this.muted = false; + this.setVolume(this.previousVolume); + } +} +var mm = new MusicManager; + +// src/class/audio/SoundManager.ts +var import_jszip = __toESM(require_lib(), 1); +var getSoundManager = () => sm; +var playSound = (sound) => getSoundManager().playSound(sound); + +class SoundManager { + soundBufs; + audioContext; + gainNode; + muted; + previousVolume; + constructor() { + this.soundBufs = {}; + this.audioContext = new (window.AudioContext || window.webkitAudioContext); + this.gainNode = this.audioContext.createGain(); + this.gainNode.connect(this.audioContext.destination); + this.muted = false; + this.previousVolume = 0.28; + this.queue = new Set; + const theme = document.documentElement.dataset.theme; + let currentTheme = theme; + document.addEventListener("theme-change", () => { + const theme2 = document.documentElement.dataset.theme; + if (theme2 !== currentTheme) { + loadBaseSounds("./assets/audio/miiMakerSwitch.zip"); + this.previousVolume = 0.28; + this.setVolume(0.28); + this.previousVolume = 0.28; + } + currentTheme = theme2; + }); + } + async loadSound(url, name2) { + const response = await fetch(url); + const arrayBuffer = await response.arrayBuffer(); + const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer); + this.soundBufs[name2] = audioBuffer; + } + async loadSoundBuffer(arrayBuffer, name2) { + const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer); + this.soundBufs[name2] = audioBuffer; + } + queue; + playSound(name2) { + const soundBuffer = this.soundBufs[name2]; + if (!soundBuffer) { + console.error(`Sound "${name2}" not found.`); + return; + } + if (this.queue.has(name2)) + return; + const source = this.audioContext.createBufferSource(); + source.buffer = soundBuffer; + source.connect(this.gainNode); + source.start(); + this.queue.add(name2); + setTimeout(() => { + this.queue.delete(name2); + }, 50); + } + setVolume(volume) { + if (this.muted) + return; + this.gainNode.gain.value = volume; + } + mute() { + if (this.muted) + return; + this.previousVolume = this.gainNode.gain.value; + this.setVolume(0); + this.muted = true; + } + unmute() { + if (this.muted === false) + return; + this.muted = false; + this.setVolume(this.previousVolume); + } +} +var sm = new SoundManager; +var loadBaseSounds = async (path = "./assets/audio/miiMakerSwitch.zip", smRef = sm) => { + const data2 = await fetch(path).then((j) => j.blob()); + const zip = await import_jszip.default.loadAsync(data2); + let promises = []; + const fileList = Object.keys(zip.files); + for (const file of fileList) { + promises.push(zip.files[file].async("arraybuffer")); + } + const resolves = await Promise.all(promises); + for (let i = 0;i < fileList.length; i++) { + const fileName = fileList[i].split("."); + fileName.pop(); + await smRef.loadSoundBuffer(resolves[i], fileName.join(".")); + } +}; + +// node_modules/@datkat21/html/dist/html.js +/*! +Html library by datkat21 on GitHub. Licensed under MIT +https://github.com/datkat21/html +!*/ + +class Html { + elm; + constructor(elm) { + if (elm instanceof HTMLElement) + this.elm = elm; + else + this.elm = document.createElement(elm || "div"); + } + text(val2) { + this.elm.innerText = val2; + return this; + } + html(val2) { + this.elm.innerHTML = val2; + return this; + } + cleanup() { + this.elm.remove(); + return this; + } + query(selector) { + return this.elm.querySelector(selector); + } + qs(query) { + if (this.elm.querySelector(query)) + return Html.from(this.elm.querySelector(query)); + else + return null; + } + qsa(query) { + if (this.elm.querySelector(query)) + return Array.from(this.elm.querySelectorAll(query)).map((e) => Html.from(e)); + else + return null; + } + id(val2) { + this.elm.id = val2; + return this; + } + class(...val2) { + for (let i = 0;i < val2.length; i++) + this.elm.classList.toggle(val2[i]); + return this; + } + classOn(...val2) { + for (let i = 0;i < val2.length; i++) + this.elm.classList.add(val2[i]); + return this; + } + classOff(...val2) { + for (let i = 0;i < val2.length; i++) + this.elm.classList.remove(val2[i]); + return this; + } + style(obj) { + for (const key2 of Object.keys(obj)) + this.elm.style.setProperty(key2, obj[key2]); + return this; + } + styleJs(obj) { + for (const key2 of Object.keys(obj)) + this.elm.style[key2] = obj[key2]; + return this; + } + on(ev, cb) { + this.elm.addEventListener(ev, cb); + return this; + } + un(ev, cb) { + this.elm.removeEventListener(ev, cb); + return this; + } + getElement(element) { + let p = element instanceof Html ? element.elm : element; + if (typeof element === "string") + p = document.querySelector(element); + if (p instanceof HTMLElement) + return p; + else + throw new Error("Invalid element type."); + } + appendTo(parent2) { + let p = this.getElement(parent2); + if (p instanceof HTMLElement) + p.appendChild(this.elm); + else + throw new Error("Invalid parent element, exausted 3 checks."); + return this; + } + prependTo(parent2) { + let p = this.getElement(parent2); + if (p instanceof HTMLElement) + p.prepend(this.elm); + return this; + } + append(elem2) { + let e = this.getElement(elem2); + if (e instanceof HTMLElement) + this.elm.appendChild(e); + else if (typeof elem2 === "string") { + const newElem = document.createElement(elem2); + this.elm.appendChild(newElem); + return new Html(newElem.tagName); + } + return this; + } + prepend(elem2) { + let e = this.getElement(elem2); + if (e instanceof HTMLElement) + this.elm.prepend(e); + else if (typeof elem2 === "string") { + const newElem = document.createElement(elem2); + this.elm.prepend(newElem); + return new Html(newElem.tagName); + } + return this; + } + appendMany(...elements) { + for (const elem2 of elements) + this.append(elem2); + return this; + } + prependMany(...elements) { + for (const elem2 of elements) + this.prepend(elem2); + return this; + } + clear() { + this.elm.innerHTML = ""; + return this; + } + attr(obj) { + for (let key2 in obj) + if (obj[key2] !== null && obj[key2] !== undefined) + this.elm.setAttribute(key2, obj[key2]); + else + this.elm.removeAttribute(key2); + return this; + } + val(str) { + this.elm.value = str; + return this; + } + getText() { + return this.elm.innerText; + } + getHtml() { + return this.elm.innerHTML; + } + getValue() { + return this.elm.value; + } + swapRef(elm) { + this.elm = elm; + return this; + } + static from(elm) { + const qs = () => Html.qs(elm); + if (typeof elm === "string") + return qs(); + return new Html(elm); + } + static qs(query) { + if (document.querySelector(query)) + return Html.from(document.querySelector(query)); + return null; + } + static qsa(query) { + if (document.querySelector(query)) + return Array.from(document.querySelectorAll(query)).map((e) => Html.from(e)); + return null; + } +} + +// src/util/AddButtonSounds.ts +function AddButtonSounds(button, hoverSound = "hover", pressSound = "select") { + button.on("pointerenter", () => { + playSound(hoverSound); + }); + button.on("click", () => { + playSound(pressSound); + }); + return button; +} + +// src/ui/components/Modal.ts +var buttonsOkCancel = [ + { callback() { + }, text: "Cancel" }, + { callback() { + }, text: "OK" } +]; +function closingCallback(modal) { + modal.qs(".modal-body").qsa("*").forEach((a) => a.attr({ disabled: true, tabindex: "-1" })); +} +function closeModal(modal) { + modal.class("closing"); + closingCallback(modal); + setTimeout(() => { + modal.cleanup(); + }, 350); +} +var Modal_default = { + modal: function(title, content2, parent2 = "body", ...buttons) { + if (content2 === undefined && title) { + content2 = "" + title; + title = "Alert"; + } + let modalContent = new Html("div").class("modal-content"); + let modalHeader = new Html("div").class("modal-header"); + let modalBody = new Html("div").class("modal-body"); + modalContent.appendMany(modalHeader, modalBody); + const x = new Html("div").class("modal").append(modalContent); + new Html("span").text(title).appendTo(modalHeader); + if (content2 instanceof Html === false) { + new Html("span").text(content2).appendTo(modalBody); + } else { + content2.appendTo(modalBody); + } + if (buttons.length > 0) + new Html("div").class("flex-group").appendTo(modalBody); + for (let i = 0;i < buttons.length; i++) { + let button = buttons[i]; + if (!button.text) + throw new Error("Invalid button configuration"); + if (button.text === "Cancel") { + let isClosing = false; + const closeButtonHandler = (e) => { + const t = e.target; + if (t == null) + return; + if (!t.classList.contains("close-button") && t.closest(".modal-content") !== null) + return; + if (isClosing) + return; + playSound("back"); + isClosing = true; + x.classOn("closing"); + setTimeout(() => { + x.cleanup(); + if (typeof button.callback === "function") + button.callback(e); + }, 350); + }; + AddButtonSounds(new Html("button").class("close-button").appendTo(modalHeader).on("click", closeButtonHandler), "hover", "back"); + x.on("click", (e) => { + closeButtonHandler(e); + }); + continue; + } + const b = AddButtonSounds(new Html("button").text(button.text).on("click", (e) => { + x.class("closing"); + closingCallback2(); + setTimeout(() => { + x.cleanup(); + if (typeof button.callback === "function") + button.callback(e); + }, 350); + })); + if (button.type && button.type === "primary") + b.class("primary"); + if (button.type && button.type === "danger") + b.class("danger"); + b.appendTo(modalContent.elm.querySelector(".flex-group")); + } + function closingCallback2() { + x.qsa("a,button,div").forEach((a) => a.attr({ disabled: true, tabindex: "-1" })); + } + x.appendTo(parent2); + let elementsArray; + requestAnimationFrame(() => { + const focusableElements = x.elm.querySelectorAll('a[href], button, textarea, input[type="text"], input[type="checkbox"], input[type="radio"], select'); + elementsArray = Array.prototype.slice.call(focusableElements); + elementsArray.forEach((el) => { + el.setAttribute("tabindex", "0"); + }); + if (elementsArray.length > 0) { + elementsArray[0].addEventListener("keydown", (e) => { + if (e.key === "Tab" && e.shiftKey) { + e.preventDefault(); + elementsArray[elementsArray.length - 1].focus(); + } + }); + elementsArray[elementsArray.length - 1].addEventListener("keydown", (e) => { + if (e.key === "Tab" && !e.shiftKey) { + e.preventDefault(); + elementsArray[0].focus(); + } + }); + } + }); + requestAnimationFrame(() => { + modalBody.elm.querySelector("input") && modalBody.elm.querySelector("input").focus(); + }); + return x; + }, + alert: function(title, content2, parent2 = "body", selectable = false) { + return new Promise((res, _rej) => { + let p = parent2; + if (selectable) { + new Html("div").class("modal-selectable").appendTo("body"); + p = ".modal-selectable"; + } + this.modal(title, content2, p, { + text: "OK", + callback: (_) => { + res(true); + Html.qs(".modal-selectable")?.cleanup(); + } + }, { + text: "Cancel", + callback: (_) => { + res(false); + Html.qs(".modal-selectable")?.cleanup(); + } + }); + }); + }, + prompt: function(title, content2, parent2 = "body", dangerous = false) { + return new Promise((res, _rej) => { + var m = this.modal(title, content2, parent2, { + text: "Yes", + type: dangerous ? "danger" : "primary", + callback: (_) => res(true) + }, { + text: "No", + callback: (_) => res(false) + }, { + text: "Cancel", + callback: (_) => res(false) + }); + m.qs(".modal-body").classOn("flex-group"); + }); + }, + input: function(title, description, placeholder, parent2 = "body", isPassword = false, value2 = "") { + return new Promise((res, _rej) => { + let wrapper = new Html("div").class("col"); + let modal = this.modal(title, wrapper, parent2, { + text: "OK", + type: "primary", + callback: (_) => { + res(input.elm.value); + } + }, { + text: "Cancel", + callback: (_) => res(false) + }); + new Html("span").text(description).appendTo(wrapper); + let input = new Html("input").attr({ + placeholder, + value: value2, + type: isPassword === true ? "password" : "text" + }).on("keyup", (e) => { + const ev = e; + if (ev.key === "Enter") { + modal.class("closing"); + setTimeout(() => { + modal.cleanup(); + res(input.elm.value); + }, 350); + } + }).appendTo(wrapper); + }); + } +}; + +// src/ui/pages/Library.ts +var import_localforage13 = __toESM(require_localforage(), 1); + +// node_modules/three/build/three.module.js +var exports_three_module = {}; +__export(exports_three_module, { + createCanvasElement: () => createCanvasElement, + ZeroStencilOp: () => ZeroStencilOp, + ZeroSlopeEnding: () => ZeroSlopeEnding, + ZeroFactor: () => ZeroFactor, + ZeroCurvatureEnding: () => ZeroCurvatureEnding, + WrapAroundEnding: () => WrapAroundEnding, + WireframeGeometry: () => WireframeGeometry, + WebXRController: () => WebXRController, + WebGPUCoordinateSystem: () => WebGPUCoordinateSystem, + WebGLUtils: () => WebGLUtils, + WebGLRenderer: () => WebGLRenderer, + WebGLRenderTarget: () => WebGLRenderTarget, + WebGLCubeRenderTarget: () => WebGLCubeRenderTarget, + WebGLCoordinateSystem: () => WebGLCoordinateSystem, + WebGLArrayRenderTarget: () => WebGLArrayRenderTarget, + WebGL3DRenderTarget: () => WebGL3DRenderTarget, + VideoTexture: () => VideoTexture, + VideoFrameTexture: () => VideoFrameTexture, + VectorKeyframeTrack: () => VectorKeyframeTrack, + Vector4: () => Vector4, + Vector3: () => Vector3, + Vector2: () => Vector2, + VSMShadowMap: () => VSMShadowMap, + UnsignedShortType: () => UnsignedShortType, + UnsignedShort5551Type: () => UnsignedShort5551Type, + UnsignedShort4444Type: () => UnsignedShort4444Type, + UnsignedIntType: () => UnsignedIntType, + UnsignedInt5999Type: () => UnsignedInt5999Type, + UnsignedInt248Type: () => UnsignedInt248Type, + UnsignedByteType: () => UnsignedByteType, + UniformsUtils: () => UniformsUtils, + UniformsLib: () => UniformsLib, + UniformsGroup: () => UniformsGroup, + Uniform: () => Uniform, + Uint8ClampedBufferAttribute: () => Uint8ClampedBufferAttribute, + Uint8BufferAttribute: () => Uint8BufferAttribute, + Uint32BufferAttribute: () => Uint32BufferAttribute, + Uint16BufferAttribute: () => Uint16BufferAttribute, + UVMapping: () => UVMapping, + TubeGeometry: () => TubeGeometry, + TrianglesDrawMode: () => TrianglesDrawMode, + TriangleStripDrawMode: () => TriangleStripDrawMode, + TriangleFanDrawMode: () => TriangleFanDrawMode, + Triangle: () => Triangle, + TorusKnotGeometry: () => TorusKnotGeometry, + TorusGeometry: () => TorusGeometry, + TimestampQuery: () => TimestampQuery, + TextureUtils: () => TextureUtils, + TextureLoader: () => TextureLoader, + Texture: () => Texture, + TetrahedronGeometry: () => TetrahedronGeometry, + TangentSpaceNormalMap: () => TangentSpaceNormalMap, + TOUCH: () => TOUCH, + SubtractiveBlending: () => SubtractiveBlending, + SubtractEquation: () => SubtractEquation, + StringKeyframeTrack: () => StringKeyframeTrack, + StreamReadUsage: () => StreamReadUsage, + StreamDrawUsage: () => StreamDrawUsage, + StreamCopyUsage: () => StreamCopyUsage, + StereoCamera: () => StereoCamera, + StaticReadUsage: () => StaticReadUsage, + StaticDrawUsage: () => StaticDrawUsage, + StaticCopyUsage: () => StaticCopyUsage, + SrcColorFactor: () => SrcColorFactor, + SrcAlphaSaturateFactor: () => SrcAlphaSaturateFactor, + SrcAlphaFactor: () => SrcAlphaFactor, + SpriteMaterial: () => SpriteMaterial, + Sprite: () => Sprite, + SpotLightHelper: () => SpotLightHelper, + SpotLight: () => SpotLight, + SplineCurve: () => SplineCurve, + SphericalHarmonics3: () => SphericalHarmonics3, + Spherical: () => Spherical, + SphereGeometry: () => SphereGeometry, + Sphere: () => Sphere, + Source: () => Source, + SkinnedMesh: () => SkinnedMesh, + SkeletonHelper: () => SkeletonHelper, + Skeleton: () => Skeleton, + ShortType: () => ShortType, + ShapeUtils: () => ShapeUtils, + ShapePath: () => ShapePath2, + ShapeGeometry: () => ShapeGeometry, + Shape: () => Shape, + ShadowMaterial: () => ShadowMaterial, + ShaderMaterial: () => ShaderMaterial, + ShaderLib: () => ShaderLib, + ShaderChunk: () => ShaderChunk, + Scene: () => Scene, + SRGBTransfer: () => SRGBTransfer, + SRGBColorSpace: () => SRGBColorSpace, + SIGNED_RED_RGTC1_Format: () => SIGNED_RED_RGTC1_Format, + SIGNED_RED_GREEN_RGTC2_Format: () => SIGNED_RED_GREEN_RGTC2_Format, + RingGeometry: () => RingGeometry, + ReverseSubtractEquation: () => ReverseSubtractEquation, + ReplaceStencilOp: () => ReplaceStencilOp, + RepeatWrapping: () => RepeatWrapping, + RenderTargetArray: () => RenderTargetArray, + RenderTarget3D: () => RenderTarget3D, + RenderTarget: () => RenderTarget, + ReinhardToneMapping: () => ReinhardToneMapping, + RedIntegerFormat: () => RedIntegerFormat, + RedFormat: () => RedFormat, + RectAreaLight: () => RectAreaLight, + Raycaster: () => Raycaster, + Ray: () => Ray, + RawShaderMaterial: () => RawShaderMaterial, + RGIntegerFormat: () => RGIntegerFormat, + RGFormat: () => RGFormat, + RGDepthPacking: () => RGDepthPacking, + RGB_S3TC_DXT1_Format: () => RGB_S3TC_DXT1_Format, + RGB_PVRTC_4BPPV1_Format: () => RGB_PVRTC_4BPPV1_Format, + RGB_PVRTC_2BPPV1_Format: () => RGB_PVRTC_2BPPV1_Format, + RGB_ETC2_Format: () => RGB_ETC2_Format, + RGB_ETC1_Format: () => RGB_ETC1_Format, + RGB_BPTC_UNSIGNED_Format: () => RGB_BPTC_UNSIGNED_Format, + RGB_BPTC_SIGNED_Format: () => RGB_BPTC_SIGNED_Format, + RGBIntegerFormat: () => RGBIntegerFormat, + RGBFormat: () => RGBFormat, + RGBDepthPacking: () => RGBDepthPacking, + RGBA_S3TC_DXT5_Format: () => RGBA_S3TC_DXT5_Format, + RGBA_S3TC_DXT3_Format: () => RGBA_S3TC_DXT3_Format, + RGBA_S3TC_DXT1_Format: () => RGBA_S3TC_DXT1_Format, + RGBA_PVRTC_4BPPV1_Format: () => RGBA_PVRTC_4BPPV1_Format, + RGBA_PVRTC_2BPPV1_Format: () => RGBA_PVRTC_2BPPV1_Format, + RGBA_ETC2_EAC_Format: () => RGBA_ETC2_EAC_Format, + RGBA_BPTC_Format: () => RGBA_BPTC_Format, + RGBA_ASTC_8x8_Format: () => RGBA_ASTC_8x8_Format, + RGBA_ASTC_8x6_Format: () => RGBA_ASTC_8x6_Format, + RGBA_ASTC_8x5_Format: () => RGBA_ASTC_8x5_Format, + RGBA_ASTC_6x6_Format: () => RGBA_ASTC_6x6_Format, + RGBA_ASTC_6x5_Format: () => RGBA_ASTC_6x5_Format, + RGBA_ASTC_5x5_Format: () => RGBA_ASTC_5x5_Format, + RGBA_ASTC_5x4_Format: () => RGBA_ASTC_5x4_Format, + RGBA_ASTC_4x4_Format: () => RGBA_ASTC_4x4_Format, + RGBA_ASTC_12x12_Format: () => RGBA_ASTC_12x12_Format, + RGBA_ASTC_12x10_Format: () => RGBA_ASTC_12x10_Format, + RGBA_ASTC_10x8_Format: () => RGBA_ASTC_10x8_Format, + RGBA_ASTC_10x6_Format: () => RGBA_ASTC_10x6_Format, + RGBA_ASTC_10x5_Format: () => RGBA_ASTC_10x5_Format, + RGBA_ASTC_10x10_Format: () => RGBA_ASTC_10x10_Format, + RGBAIntegerFormat: () => RGBAIntegerFormat, + RGBAFormat: () => RGBAFormat, + RGBADepthPacking: () => RGBADepthPacking, + REVISION: () => REVISION, + RED_RGTC1_Format: () => RED_RGTC1_Format, + RED_GREEN_RGTC2_Format: () => RED_GREEN_RGTC2_Format, + QuaternionLinearInterpolant: () => QuaternionLinearInterpolant, + QuaternionKeyframeTrack: () => QuaternionKeyframeTrack, + Quaternion: () => Quaternion, + QuadraticBezierCurve3: () => QuadraticBezierCurve3, + QuadraticBezierCurve: () => QuadraticBezierCurve, + PropertyMixer: () => PropertyMixer, + PropertyBinding: () => PropertyBinding, + PositionalAudio: () => PositionalAudio, + PolyhedronGeometry: () => PolyhedronGeometry, + PolarGridHelper: () => PolarGridHelper, + PointsMaterial: () => PointsMaterial, + Points: () => Points, + PointLightHelper: () => PointLightHelper, + PointLight: () => PointLight, + PlaneHelper: () => PlaneHelper, + PlaneGeometry: () => PlaneGeometry, + Plane: () => Plane, + PerspectiveCamera: () => PerspectiveCamera, + Path: () => Path, + PMREMGenerator: () => PMREMGenerator, + PCFSoftShadowMap: () => PCFSoftShadowMap, + PCFShadowMap: () => PCFShadowMap, + OrthographicCamera: () => OrthographicCamera, + OneMinusSrcColorFactor: () => OneMinusSrcColorFactor, + OneMinusSrcAlphaFactor: () => OneMinusSrcAlphaFactor, + OneMinusDstColorFactor: () => OneMinusDstColorFactor, + OneMinusDstAlphaFactor: () => OneMinusDstAlphaFactor, + OneMinusConstantColorFactor: () => OneMinusConstantColorFactor, + OneMinusConstantAlphaFactor: () => OneMinusConstantAlphaFactor, + OneFactor: () => OneFactor, + OctahedronGeometry: () => OctahedronGeometry, + ObjectSpaceNormalMap: () => ObjectSpaceNormalMap, + ObjectLoader: () => ObjectLoader, + Object3D: () => Object3D, + NumberKeyframeTrack: () => NumberKeyframeTrack, + NotEqualStencilFunc: () => NotEqualStencilFunc, + NotEqualDepth: () => NotEqualDepth, + NotEqualCompare: () => NotEqualCompare, + NormalBlending: () => NormalBlending, + NormalAnimationBlendMode: () => NormalAnimationBlendMode, + NoToneMapping: () => NoToneMapping, + NoColorSpace: () => NoColorSpace, + NoBlending: () => NoBlending, + NeverStencilFunc: () => NeverStencilFunc, + NeverDepth: () => NeverDepth, + NeverCompare: () => NeverCompare, + NeutralToneMapping: () => NeutralToneMapping, + NearestMipmapNearestFilter: () => NearestMipmapNearestFilter, + NearestMipmapLinearFilter: () => NearestMipmapLinearFilter, + NearestMipMapNearestFilter: () => NearestMipMapNearestFilter, + NearestMipMapLinearFilter: () => NearestMipMapLinearFilter, + NearestFilter: () => NearestFilter, + MultiplyOperation: () => MultiplyOperation, + MultiplyBlending: () => MultiplyBlending, + MixOperation: () => MixOperation, + MirroredRepeatWrapping: () => MirroredRepeatWrapping, + MinEquation: () => MinEquation, + MeshToonMaterial: () => MeshToonMaterial, + MeshStandardMaterial: () => MeshStandardMaterial, + MeshPhysicalMaterial: () => MeshPhysicalMaterial, + MeshPhongMaterial: () => MeshPhongMaterial, + MeshNormalMaterial: () => MeshNormalMaterial, + MeshMatcapMaterial: () => MeshMatcapMaterial, + MeshLambertMaterial: () => MeshLambertMaterial, + MeshDistanceMaterial: () => MeshDistanceMaterial, + MeshDepthMaterial: () => MeshDepthMaterial, + MeshBasicMaterial: () => MeshBasicMaterial, + Mesh: () => Mesh, + MaxEquation: () => MaxEquation, + Matrix4: () => Matrix4, + Matrix3: () => Matrix3, + Matrix2: () => Matrix2, + MathUtils: () => MathUtils, + MaterialLoader: () => MaterialLoader, + Material: () => Material, + MOUSE: () => MOUSE, + LuminanceFormat: () => LuminanceFormat, + LuminanceAlphaFormat: () => LuminanceAlphaFormat, + LoopRepeat: () => LoopRepeat, + LoopPingPong: () => LoopPingPong, + LoopOnce: () => LoopOnce, + LoadingManager: () => LoadingManager, + LoaderUtils: () => LoaderUtils, + Loader: () => Loader, + LinearTransfer: () => LinearTransfer, + LinearToneMapping: () => LinearToneMapping, + LinearSRGBColorSpace: () => LinearSRGBColorSpace, + LinearMipmapNearestFilter: () => LinearMipmapNearestFilter, + LinearMipmapLinearFilter: () => LinearMipmapLinearFilter, + LinearMipMapNearestFilter: () => LinearMipMapNearestFilter, + LinearMipMapLinearFilter: () => LinearMipMapLinearFilter, + LinearInterpolant: () => LinearInterpolant, + LinearFilter: () => LinearFilter, + LineSegments: () => LineSegments, + LineLoop: () => LineLoop, + LineDashedMaterial: () => LineDashedMaterial, + LineCurve3: () => LineCurve3, + LineCurve: () => LineCurve, + LineBasicMaterial: () => LineBasicMaterial, + Line3: () => Line3, + Line: () => Line, + LightProbe: () => LightProbe, + Light: () => Light, + LessStencilFunc: () => LessStencilFunc, + LessEqualStencilFunc: () => LessEqualStencilFunc, + LessEqualDepth: () => LessEqualDepth, + LessEqualCompare: () => LessEqualCompare, + LessDepth: () => LessDepth, + LessCompare: () => LessCompare, + Layers: () => Layers, + LatheGeometry: () => LatheGeometry, + LOD: () => LOD, + KeyframeTrack: () => KeyframeTrack, + KeepStencilOp: () => KeepStencilOp, + InvertStencilOp: () => InvertStencilOp, + InterpolateSmooth: () => InterpolateSmooth, + InterpolateLinear: () => InterpolateLinear, + InterpolateDiscrete: () => InterpolateDiscrete, + Interpolant: () => Interpolant, + InterleavedBufferAttribute: () => InterleavedBufferAttribute, + InterleavedBuffer: () => InterleavedBuffer, + IntType: () => IntType, + Int8BufferAttribute: () => Int8BufferAttribute, + Int32BufferAttribute: () => Int32BufferAttribute, + Int16BufferAttribute: () => Int16BufferAttribute, + InstancedMesh: () => InstancedMesh, + InstancedInterleavedBuffer: () => InstancedInterleavedBuffer, + InstancedBufferGeometry: () => InstancedBufferGeometry, + InstancedBufferAttribute: () => InstancedBufferAttribute, + IncrementWrapStencilOp: () => IncrementWrapStencilOp, + IncrementStencilOp: () => IncrementStencilOp, + ImageUtils: () => ImageUtils, + ImageLoader: () => ImageLoader, + ImageBitmapLoader: () => ImageBitmapLoader, + IcosahedronGeometry: () => IcosahedronGeometry, + HemisphereLightHelper: () => HemisphereLightHelper, + HemisphereLight: () => HemisphereLight, + HalfFloatType: () => HalfFloatType, + Group: () => Group, + GridHelper: () => GridHelper, + GreaterStencilFunc: () => GreaterStencilFunc, + GreaterEqualStencilFunc: () => GreaterEqualStencilFunc, + GreaterEqualDepth: () => GreaterEqualDepth, + GreaterEqualCompare: () => GreaterEqualCompare, + GreaterDepth: () => GreaterDepth, + GreaterCompare: () => GreaterCompare, + GLSL3: () => GLSL3, + GLSL1: () => GLSL1, + GLBufferAttribute: () => GLBufferAttribute, + Frustum: () => Frustum, + FrontSide: () => FrontSide, + FramebufferTexture: () => FramebufferTexture, + FogExp2: () => FogExp2, + Fog: () => Fog, + FloatType: () => FloatType, + Float32BufferAttribute: () => Float32BufferAttribute, + Float16BufferAttribute: () => Float16BufferAttribute, + FileLoader: () => FileLoader, + ExtrudeGeometry: () => ExtrudeGeometry, + EventDispatcher: () => EventDispatcher, + Euler: () => Euler, + EquirectangularRefractionMapping: () => EquirectangularRefractionMapping, + EquirectangularReflectionMapping: () => EquirectangularReflectionMapping, + EqualStencilFunc: () => EqualStencilFunc, + EqualDepth: () => EqualDepth, + EqualCompare: () => EqualCompare, + EllipseCurve: () => EllipseCurve, + EdgesGeometry: () => EdgesGeometry, + DynamicReadUsage: () => DynamicReadUsage, + DynamicDrawUsage: () => DynamicDrawUsage, + DynamicCopyUsage: () => DynamicCopyUsage, + DstColorFactor: () => DstColorFactor, + DstAlphaFactor: () => DstAlphaFactor, + DoubleSide: () => DoubleSide, + DodecahedronGeometry: () => DodecahedronGeometry, + DiscreteInterpolant: () => DiscreteInterpolant, + DirectionalLightHelper: () => DirectionalLightHelper, + DirectionalLight: () => DirectionalLight, + DetachedBindMode: () => DetachedBindMode, + DepthTexture: () => DepthTexture, + DepthStencilFormat: () => DepthStencilFormat, + DepthFormat: () => DepthFormat, + DefaultLoadingManager: () => DefaultLoadingManager, + DecrementWrapStencilOp: () => DecrementWrapStencilOp, + DecrementStencilOp: () => DecrementStencilOp, + DataUtils: () => DataUtils, + DataTextureLoader: () => DataTextureLoader, + DataTexture: () => DataTexture, + DataArrayTexture: () => DataArrayTexture, + Data3DTexture: () => Data3DTexture, + Cylindrical: () => Cylindrical, + CylinderGeometry: () => CylinderGeometry, + CustomToneMapping: () => CustomToneMapping, + CustomBlending: () => CustomBlending, + CurvePath: () => CurvePath, + Curve: () => Curve, + CullFaceNone: () => CullFaceNone, + CullFaceFrontBack: () => CullFaceFrontBack, + CullFaceFront: () => CullFaceFront, + CullFaceBack: () => CullFaceBack, + CubicInterpolant: () => CubicInterpolant, + CubicBezierCurve3: () => CubicBezierCurve3, + CubicBezierCurve: () => CubicBezierCurve, + CubeUVReflectionMapping: () => CubeUVReflectionMapping, + CubeTextureLoader: () => CubeTextureLoader, + CubeTexture: () => CubeTexture, + CubeRefractionMapping: () => CubeRefractionMapping, + CubeReflectionMapping: () => CubeReflectionMapping, + CubeCamera: () => CubeCamera, + Controls: () => Controls, + ConstantColorFactor: () => ConstantColorFactor, + ConstantAlphaFactor: () => ConstantAlphaFactor, + ConeGeometry: () => ConeGeometry, + CompressedTextureLoader: () => CompressedTextureLoader, + CompressedTexture: () => CompressedTexture, + CompressedCubeTexture: () => CompressedCubeTexture, + CompressedArrayTexture: () => CompressedArrayTexture, + ColorManagement: () => ColorManagement, + ColorKeyframeTrack: () => ColorKeyframeTrack, + Color: () => Color, + Clock: () => Clock, + ClampToEdgeWrapping: () => ClampToEdgeWrapping, + CircleGeometry: () => CircleGeometry, + CineonToneMapping: () => CineonToneMapping, + CatmullRomCurve3: () => CatmullRomCurve3, + CapsuleGeometry: () => CapsuleGeometry, + CanvasTexture: () => CanvasTexture, + CameraHelper: () => CameraHelper, + Camera: () => Camera, + Cache: () => Cache, + ByteType: () => ByteType, + BufferGeometryLoader: () => BufferGeometryLoader, + BufferGeometry: () => BufferGeometry, + BufferAttribute: () => BufferAttribute, + BoxHelper: () => BoxHelper, + BoxGeometry: () => BoxGeometry, + Box3Helper: () => Box3Helper, + Box3: () => Box3, + Box2: () => Box2, + BooleanKeyframeTrack: () => BooleanKeyframeTrack, + Bone: () => Bone, + BatchedMesh: () => BatchedMesh, + BasicShadowMap: () => BasicShadowMap, + BasicDepthPacking: () => BasicDepthPacking, + BackSide: () => BackSide, + AxesHelper: () => AxesHelper, + AudioLoader: () => AudioLoader, + AudioListener: () => AudioListener, + AudioContext: () => AudioContext, + AudioAnalyser: () => AudioAnalyser, + Audio: () => Audio, + AttachedBindMode: () => AttachedBindMode, + ArrowHelper: () => ArrowHelper, + ArrayCamera: () => ArrayCamera, + ArcCurve: () => ArcCurve, + AnimationUtils: () => AnimationUtils, + AnimationObjectGroup: () => AnimationObjectGroup, + AnimationMixer: () => AnimationMixer, + AnimationLoader: () => AnimationLoader, + AnimationClip: () => AnimationClip, + AnimationAction: () => AnimationAction, + AmbientLight: () => AmbientLight, + AlwaysStencilFunc: () => AlwaysStencilFunc, + AlwaysDepth: () => AlwaysDepth, + AlwaysCompare: () => AlwaysCompare, + AlphaFormat: () => AlphaFormat, + AgXToneMapping: () => AgXToneMapping, + AdditiveBlending: () => AdditiveBlending, + AdditiveAnimationBlendMode: () => AdditiveAnimationBlendMode, + AddOperation: () => AddOperation, + AddEquation: () => AddEquation, + ACESFilmicToneMapping: () => ACESFilmicToneMapping +}); + +// node_modules/three/build/three.core.js +var REVISION = "173"; +var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; +var TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; +var CullFaceNone = 0; +var CullFaceBack = 1; +var CullFaceFront = 2; +var CullFaceFrontBack = 3; +var BasicShadowMap = 0; +var PCFShadowMap = 1; +var PCFSoftShadowMap = 2; +var VSMShadowMap = 3; +var FrontSide = 0; +var BackSide = 1; +var DoubleSide = 2; +var NoBlending = 0; +var NormalBlending = 1; +var AdditiveBlending = 2; +var SubtractiveBlending = 3; +var MultiplyBlending = 4; +var CustomBlending = 5; +var AddEquation = 100; +var SubtractEquation = 101; +var ReverseSubtractEquation = 102; +var MinEquation = 103; +var MaxEquation = 104; +var ZeroFactor = 200; +var OneFactor = 201; +var SrcColorFactor = 202; +var OneMinusSrcColorFactor = 203; +var SrcAlphaFactor = 204; +var OneMinusSrcAlphaFactor = 205; +var DstAlphaFactor = 206; +var OneMinusDstAlphaFactor = 207; +var DstColorFactor = 208; +var OneMinusDstColorFactor = 209; +var SrcAlphaSaturateFactor = 210; +var ConstantColorFactor = 211; +var OneMinusConstantColorFactor = 212; +var ConstantAlphaFactor = 213; +var OneMinusConstantAlphaFactor = 214; +var NeverDepth = 0; +var AlwaysDepth = 1; +var LessDepth = 2; +var LessEqualDepth = 3; +var EqualDepth = 4; +var GreaterEqualDepth = 5; +var GreaterDepth = 6; +var NotEqualDepth = 7; +var MultiplyOperation = 0; +var MixOperation = 1; +var AddOperation = 2; +var NoToneMapping = 0; +var LinearToneMapping = 1; +var ReinhardToneMapping = 2; +var CineonToneMapping = 3; +var ACESFilmicToneMapping = 4; +var CustomToneMapping = 5; +var AgXToneMapping = 6; +var NeutralToneMapping = 7; +var AttachedBindMode = "attached"; +var DetachedBindMode = "detached"; +var UVMapping = 300; +var CubeReflectionMapping = 301; +var CubeRefractionMapping = 302; +var EquirectangularReflectionMapping = 303; +var EquirectangularRefractionMapping = 304; +var CubeUVReflectionMapping = 306; +var RepeatWrapping = 1000; +var ClampToEdgeWrapping = 1001; +var MirroredRepeatWrapping = 1002; +var NearestFilter = 1003; +var NearestMipmapNearestFilter = 1004; +var NearestMipMapNearestFilter = 1004; +var NearestMipmapLinearFilter = 1005; +var NearestMipMapLinearFilter = 1005; +var LinearFilter = 1006; +var LinearMipmapNearestFilter = 1007; +var LinearMipMapNearestFilter = 1007; +var LinearMipmapLinearFilter = 1008; +var LinearMipMapLinearFilter = 1008; +var UnsignedByteType = 1009; +var ByteType = 1010; +var ShortType = 1011; +var UnsignedShortType = 1012; +var IntType = 1013; +var UnsignedIntType = 1014; +var FloatType = 1015; +var HalfFloatType = 1016; +var UnsignedShort4444Type = 1017; +var UnsignedShort5551Type = 1018; +var UnsignedInt248Type = 1020; +var UnsignedInt5999Type = 35902; +var AlphaFormat = 1021; +var RGBFormat = 1022; +var RGBAFormat = 1023; +var LuminanceFormat = 1024; +var LuminanceAlphaFormat = 1025; +var DepthFormat = 1026; +var DepthStencilFormat = 1027; +var RedFormat = 1028; +var RedIntegerFormat = 1029; +var RGFormat = 1030; +var RGIntegerFormat = 1031; +var RGBIntegerFormat = 1032; +var RGBAIntegerFormat = 1033; +var RGB_S3TC_DXT1_Format = 33776; +var RGBA_S3TC_DXT1_Format = 33777; +var RGBA_S3TC_DXT3_Format = 33778; +var RGBA_S3TC_DXT5_Format = 33779; +var RGB_PVRTC_4BPPV1_Format = 35840; +var RGB_PVRTC_2BPPV1_Format = 35841; +var RGBA_PVRTC_4BPPV1_Format = 35842; +var RGBA_PVRTC_2BPPV1_Format = 35843; +var RGB_ETC1_Format = 36196; +var RGB_ETC2_Format = 37492; +var RGBA_ETC2_EAC_Format = 37496; +var RGBA_ASTC_4x4_Format = 37808; +var RGBA_ASTC_5x4_Format = 37809; +var RGBA_ASTC_5x5_Format = 37810; +var RGBA_ASTC_6x5_Format = 37811; +var RGBA_ASTC_6x6_Format = 37812; +var RGBA_ASTC_8x5_Format = 37813; +var RGBA_ASTC_8x6_Format = 37814; +var RGBA_ASTC_8x8_Format = 37815; +var RGBA_ASTC_10x5_Format = 37816; +var RGBA_ASTC_10x6_Format = 37817; +var RGBA_ASTC_10x8_Format = 37818; +var RGBA_ASTC_10x10_Format = 37819; +var RGBA_ASTC_12x10_Format = 37820; +var RGBA_ASTC_12x12_Format = 37821; +var RGBA_BPTC_Format = 36492; +var RGB_BPTC_SIGNED_Format = 36494; +var RGB_BPTC_UNSIGNED_Format = 36495; +var RED_RGTC1_Format = 36283; +var SIGNED_RED_RGTC1_Format = 36284; +var RED_GREEN_RGTC2_Format = 36285; +var SIGNED_RED_GREEN_RGTC2_Format = 36286; +var LoopOnce = 2200; +var LoopRepeat = 2201; +var LoopPingPong = 2202; +var InterpolateDiscrete = 2300; +var InterpolateLinear = 2301; +var InterpolateSmooth = 2302; +var ZeroCurvatureEnding = 2400; +var ZeroSlopeEnding = 2401; +var WrapAroundEnding = 2402; +var NormalAnimationBlendMode = 2500; +var AdditiveAnimationBlendMode = 2501; +var TrianglesDrawMode = 0; +var TriangleStripDrawMode = 1; +var TriangleFanDrawMode = 2; +var BasicDepthPacking = 3200; +var RGBADepthPacking = 3201; +var RGBDepthPacking = 3202; +var RGDepthPacking = 3203; +var TangentSpaceNormalMap = 0; +var ObjectSpaceNormalMap = 1; +var NoColorSpace = ""; +var SRGBColorSpace = "srgb"; +var LinearSRGBColorSpace = "srgb-linear"; +var LinearTransfer = "linear"; +var SRGBTransfer = "srgb"; +var ZeroStencilOp = 0; +var KeepStencilOp = 7680; +var ReplaceStencilOp = 7681; +var IncrementStencilOp = 7682; +var DecrementStencilOp = 7683; +var IncrementWrapStencilOp = 34055; +var DecrementWrapStencilOp = 34056; +var InvertStencilOp = 5386; +var NeverStencilFunc = 512; +var LessStencilFunc = 513; +var EqualStencilFunc = 514; +var LessEqualStencilFunc = 515; +var GreaterStencilFunc = 516; +var NotEqualStencilFunc = 517; +var GreaterEqualStencilFunc = 518; +var AlwaysStencilFunc = 519; +var NeverCompare = 512; +var LessCompare = 513; +var EqualCompare = 514; +var LessEqualCompare = 515; +var GreaterCompare = 516; +var NotEqualCompare = 517; +var GreaterEqualCompare = 518; +var AlwaysCompare = 519; +var StaticDrawUsage = 35044; +var DynamicDrawUsage = 35048; +var StreamDrawUsage = 35040; +var StaticReadUsage = 35045; +var DynamicReadUsage = 35049; +var StreamReadUsage = 35041; +var StaticCopyUsage = 35046; +var DynamicCopyUsage = 35050; +var StreamCopyUsage = 35042; +var GLSL1 = "100"; +var GLSL3 = "300 es"; +var WebGLCoordinateSystem = 2000; +var WebGPUCoordinateSystem = 2001; +var TimestampQuery = { + COMPUTE: "compute", + RENDER: "render" +}; + +class EventDispatcher { + addEventListener(type, listener) { + if (this._listeners === undefined) + this._listeners = {}; + const listeners = this._listeners; + if (listeners[type] === undefined) { + listeners[type] = []; + } + if (listeners[type].indexOf(listener) === -1) { + listeners[type].push(listener); + } + } + hasEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === undefined) + return false; + return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1; + } + removeEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === undefined) + return; + const listenerArray = listeners[type]; + if (listenerArray !== undefined) { + const index2 = listenerArray.indexOf(listener); + if (index2 !== -1) { + listenerArray.splice(index2, 1); + } + } + } + dispatchEvent(event) { + const listeners = this._listeners; + if (listeners === undefined) + return; + const listenerArray = listeners[event.type]; + if (listenerArray !== undefined) { + event.target = this; + const array = listenerArray.slice(0); + for (let i = 0, l = array.length;i < l; i++) { + array[i].call(this, event); + } + event.target = null; + } + } +} +var _lut = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"]; +var _seed = 1234567; +var DEG2RAD = Math.PI / 180; +var RAD2DEG = 180 / Math.PI; +function generateUUID() { + const d0 = Math.random() * 4294967295 | 0; + const d1 = Math.random() * 4294967295 | 0; + const d2 = Math.random() * 4294967295 | 0; + const d3 = Math.random() * 4294967295 | 0; + const uuid = _lut[d0 & 255] + _lut[d0 >> 8 & 255] + _lut[d0 >> 16 & 255] + _lut[d0 >> 24 & 255] + "-" + _lut[d1 & 255] + _lut[d1 >> 8 & 255] + "-" + _lut[d1 >> 16 & 15 | 64] + _lut[d1 >> 24 & 255] + "-" + _lut[d2 & 63 | 128] + _lut[d2 >> 8 & 255] + "-" + _lut[d2 >> 16 & 255] + _lut[d2 >> 24 & 255] + _lut[d3 & 255] + _lut[d3 >> 8 & 255] + _lut[d3 >> 16 & 255] + _lut[d3 >> 24 & 255]; + return uuid.toLowerCase(); +} +function clamp2(value2, min, max) { + return Math.max(min, Math.min(max, value2)); +} +function euclideanModulo(n, m) { + return (n % m + m) % m; +} +function mapLinear(x, a1, a2, b1, b2) { + return b1 + (x - a1) * (b2 - b1) / (a2 - a1); +} +function inverseLerp(x, y, value2) { + if (x !== y) { + return (value2 - x) / (y - x); + } else { + return 0; + } +} +function lerp(x, y, t) { + return (1 - t) * x + t * y; +} +function damp(x, y, lambda, dt) { + return lerp(x, y, 1 - Math.exp(-lambda * dt)); +} +function pingpong(x, length2 = 1) { + return length2 - Math.abs(euclideanModulo(x, length2 * 2) - length2); +} +function smoothstep(x, min, max) { + if (x <= min) + return 0; + if (x >= max) + return 1; + x = (x - min) / (max - min); + return x * x * (3 - 2 * x); +} +function smootherstep(x, min, max) { + if (x <= min) + return 0; + if (x >= max) + return 1; + x = (x - min) / (max - min); + return x * x * x * (x * (x * 6 - 15) + 10); +} +function randInt(low, high) { + return low + Math.floor(Math.random() * (high - low + 1)); +} +function randFloat(low, high) { + return low + Math.random() * (high - low); +} +function randFloatSpread(range) { + return range * (0.5 - Math.random()); +} +function seededRandom(s) { + if (s !== undefined) + _seed = s; + let t = _seed += 1831565813; + t = Math.imul(t ^ t >>> 15, t | 1); + t ^= t + Math.imul(t ^ t >>> 7, t | 61); + return ((t ^ t >>> 14) >>> 0) / 4294967296; +} +function degToRad(degrees) { + return degrees * DEG2RAD; +} +function radToDeg(radians) { + return radians * RAD2DEG; +} +function isPowerOfTwo(value2) { + return (value2 & value2 - 1) === 0 && value2 !== 0; +} +function ceilPowerOfTwo(value2) { + return Math.pow(2, Math.ceil(Math.log(value2) / Math.LN2)); +} +function floorPowerOfTwo(value2) { + return Math.pow(2, Math.floor(Math.log(value2) / Math.LN2)); +} +function setQuaternionFromProperEuler(q, a, b, c, order) { + const cos = Math.cos; + const sin = Math.sin; + const c2 = cos(b / 2); + const s2 = sin(b / 2); + const c13 = cos((a + c) / 2); + const s13 = sin((a + c) / 2); + const c1_3 = cos((a - c) / 2); + const s1_3 = sin((a - c) / 2); + const c3_1 = cos((c - a) / 2); + const s3_1 = sin((c - a) / 2); + switch (order) { + case "XYX": + q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13); + break; + case "YZY": + q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13); + break; + case "ZXZ": + q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13); + break; + case "XZX": + q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13); + break; + case "YXY": + q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13); + break; + case "ZYZ": + q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13); + break; + default: + console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + order); + } +} +function denormalize(value2, array) { + switch (array.constructor) { + case Float32Array: + return value2; + case Uint32Array: + return value2 / 4294967295; + case Uint16Array: + return value2 / 65535; + case Uint8Array: + return value2 / 255; + case Int32Array: + return Math.max(value2 / 2147483647, -1); + case Int16Array: + return Math.max(value2 / 32767, -1); + case Int8Array: + return Math.max(value2 / 127, -1); + default: + throw new Error("Invalid component type."); + } +} +function normalize2(value2, array) { + switch (array.constructor) { + case Float32Array: + return value2; + case Uint32Array: + return Math.round(value2 * 4294967295); + case Uint16Array: + return Math.round(value2 * 65535); + case Uint8Array: + return Math.round(value2 * 255); + case Int32Array: + return Math.round(value2 * 2147483647); + case Int16Array: + return Math.round(value2 * 32767); + case Int8Array: + return Math.round(value2 * 127); + default: + throw new Error("Invalid component type."); + } +} +var MathUtils = { + DEG2RAD, + RAD2DEG, + generateUUID, + clamp: clamp2, + euclideanModulo, + mapLinear, + inverseLerp, + lerp, + damp, + pingpong, + smoothstep, + smootherstep, + randInt, + randFloat, + randFloatSpread, + seededRandom, + degToRad, + radToDeg, + isPowerOfTwo, + ceilPowerOfTwo, + floorPowerOfTwo, + setQuaternionFromProperEuler, + normalize: normalize2, + denormalize +}; + +class Vector2 { + constructor(x = 0, y = 0) { + Vector2.prototype.isVector2 = true; + this.x = x; + this.y = y; + } + get width() { + return this.x; + } + set width(value2) { + this.x = value2; + } + get height() { + return this.y; + } + set height(value2) { + this.y = value2; + } + set(x, y) { + this.x = x; + this.y = y; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y); + } + copy(v) { + this.x = v.x; + this.y = v.y; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + applyMatrix3(m) { + const x = this.x, y = this.y; + const e = m.elements; + this.x = e[0] * x + e[3] * y + e[6]; + this.y = e[1] * x + e[4] * y + e[7]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + return this; + } + clamp(min, max) { + this.x = clamp2(this.x, min.x, max.x); + this.y = clamp2(this.y, min.y, max.y); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp2(this.x, minVal, maxVal); + this.y = clamp2(this.y, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp2(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y; + } + cross(v) { + return this.x * v.y - this.y * v.x; + } + lengthSq() { + return this.x * this.x + this.y * this.y; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + angle() { + const angle = Math.atan2(-this.y, -this.x) + Math.PI; + return angle; + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) + return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp2(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + return this; + } + rotateAround(center, angle) { + const c = Math.cos(angle), s = Math.sin(angle); + const x = this.x - center.x; + const y = this.y - center.y; + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + } +} + +class Matrix3 { + constructor(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + Matrix3.prototype.isMatrix3 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n13, n21, n22, n23, n31, n32, n33); + } + } + set(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + const te2 = this.elements; + te2[0] = n11; + te2[1] = n21; + te2[2] = n31; + te2[3] = n12; + te2[4] = n22; + te2[5] = n32; + te2[6] = n13; + te2[7] = n23; + te2[8] = n33; + return this; + } + identity() { + this.set(1, 0, 0, 0, 1, 0, 0, 0, 1); + return this; + } + copy(m) { + const te2 = this.elements; + const me = m.elements; + te2[0] = me[0]; + te2[1] = me[1]; + te2[2] = me[2]; + te2[3] = me[3]; + te2[4] = me[4]; + te2[5] = me[5]; + te2[6] = me[6]; + te2[7] = me[7]; + te2[8] = me[8]; + return this; + } + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrix3Column(this, 0); + yAxis.setFromMatrix3Column(this, 1); + zAxis.setFromMatrix3Column(this, 2); + return this; + } + setFromMatrix4(m) { + const me = m.elements; + this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]); + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a, b) { + const ae2 = a.elements; + const be = b.elements; + const te2 = this.elements; + const a11 = ae2[0], a12 = ae2[3], a13 = ae2[6]; + const a21 = ae2[1], a22 = ae2[4], a23 = ae2[7]; + const a31 = ae2[2], a32 = ae2[5], a33 = ae2[8]; + const b11 = be[0], b12 = be[3], b13 = be[6]; + const b21 = be[1], b22 = be[4], b23 = be[7]; + const b31 = be[2], b32 = be[5], b33 = be[8]; + te2[0] = a11 * b11 + a12 * b21 + a13 * b31; + te2[3] = a11 * b12 + a12 * b22 + a13 * b32; + te2[6] = a11 * b13 + a12 * b23 + a13 * b33; + te2[1] = a21 * b11 + a22 * b21 + a23 * b31; + te2[4] = a21 * b12 + a22 * b22 + a23 * b32; + te2[7] = a21 * b13 + a22 * b23 + a23 * b33; + te2[2] = a31 * b11 + a32 * b21 + a33 * b31; + te2[5] = a31 * b12 + a32 * b22 + a33 * b32; + te2[8] = a31 * b13 + a32 * b23 + a33 * b33; + return this; + } + multiplyScalar(s) { + const te2 = this.elements; + te2[0] *= s; + te2[3] *= s; + te2[6] *= s; + te2[1] *= s; + te2[4] *= s; + te2[7] *= s; + te2[2] *= s; + te2[5] *= s; + te2[8] *= s; + return this; + } + determinant() { + const te2 = this.elements; + const a = te2[0], b = te2[1], c = te2[2], d = te2[3], e = te2[4], f = te2[5], g = te2[6], h = te2[7], i = te2[8]; + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + } + invert() { + const te2 = this.elements, n11 = te2[0], n21 = te2[1], n31 = te2[2], n12 = te2[3], n22 = te2[4], n32 = te2[5], n13 = te2[6], n23 = te2[7], n33 = te2[8], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13; + if (det === 0) + return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te2[0] = t11 * detInv; + te2[1] = (n31 * n23 - n33 * n21) * detInv; + te2[2] = (n32 * n21 - n31 * n22) * detInv; + te2[3] = t12 * detInv; + te2[4] = (n33 * n11 - n31 * n13) * detInv; + te2[5] = (n31 * n12 - n32 * n11) * detInv; + te2[6] = t13 * detInv; + te2[7] = (n21 * n13 - n23 * n11) * detInv; + te2[8] = (n22 * n11 - n21 * n12) * detInv; + return this; + } + transpose() { + let tmp; + const m = this.elements; + tmp = m[1]; + m[1] = m[3]; + m[3] = tmp; + tmp = m[2]; + m[2] = m[6]; + m[6] = tmp; + tmp = m[5]; + m[5] = m[7]; + m[7] = tmp; + return this; + } + getNormalMatrix(matrix4) { + return this.setFromMatrix4(matrix4).invert().transpose(); + } + transposeIntoArray(r) { + const m = this.elements; + r[0] = m[0]; + r[1] = m[3]; + r[2] = m[6]; + r[3] = m[1]; + r[4] = m[4]; + r[5] = m[7]; + r[6] = m[2]; + r[7] = m[5]; + r[8] = m[8]; + return this; + } + setUvTransform(tx, ty, sx, sy, rotation2, cx, cy) { + const c = Math.cos(rotation2); + const s = Math.sin(rotation2); + this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1); + return this; + } + scale(sx, sy) { + this.premultiply(_m3.makeScale(sx, sy)); + return this; + } + rotate(theta) { + this.premultiply(_m3.makeRotation(-theta)); + return this; + } + translate(tx, ty) { + this.premultiply(_m3.makeTranslation(tx, ty)); + return this; + } + makeTranslation(x, y) { + if (x.isVector2) { + this.set(1, 0, x.x, 0, 1, x.y, 0, 0, 1); + } else { + this.set(1, 0, x, 0, 1, y, 0, 0, 1); + } + return this; + } + makeRotation(theta) { + const c = Math.cos(theta); + const s = Math.sin(theta); + this.set(c, -s, 0, s, c, 0, 0, 0, 1); + return this; + } + makeScale(x, y) { + this.set(x, 0, 0, 0, y, 0, 0, 0, 1); + return this; + } + equals(matrix) { + const te2 = this.elements; + const me = matrix.elements; + for (let i = 0;i < 9; i++) { + if (te2[i] !== me[i]) + return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 9; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te2 = this.elements; + array[offset] = te2[0]; + array[offset + 1] = te2[1]; + array[offset + 2] = te2[2]; + array[offset + 3] = te2[3]; + array[offset + 4] = te2[4]; + array[offset + 5] = te2[5]; + array[offset + 6] = te2[6]; + array[offset + 7] = te2[7]; + array[offset + 8] = te2[8]; + return array; + } + clone() { + return new this.constructor().fromArray(this.elements); + } +} +var _m3 = /* @__PURE__ */ new Matrix3; +function arrayNeedsUint32(array) { + for (let i = array.length - 1;i >= 0; --i) { + if (array[i] >= 65535) + return true; + } + return false; +} +var TYPED_ARRAYS = { + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array +}; +function getTypedArray(type, buffer) { + return new TYPED_ARRAYS[type](buffer); +} +function createElementNS(name2) { + return document.createElementNS("http://www.w3.org/1999/xhtml", name2); +} +function createCanvasElement() { + const canvas = createElementNS("canvas"); + canvas.style.display = "block"; + return canvas; +} +var _cache = {}; +function warnOnce(message) { + if (message in _cache) + return; + _cache[message] = true; + console.warn(message); +} +function probeAsync(gl, sync, interval) { + return new Promise(function(resolve, reject2) { + function probe() { + switch (gl.clientWaitSync(sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0)) { + case gl.WAIT_FAILED: + reject2(); + break; + case gl.TIMEOUT_EXPIRED: + setTimeout(probe, interval); + break; + default: + resolve(); + } + } + setTimeout(probe, interval); + }); +} +function toNormalizedProjectionMatrix(projectionMatrix) { + const m = projectionMatrix.elements; + m[2] = 0.5 * m[2] + 0.5 * m[3]; + m[6] = 0.5 * m[6] + 0.5 * m[7]; + m[10] = 0.5 * m[10] + 0.5 * m[11]; + m[14] = 0.5 * m[14] + 0.5 * m[15]; +} +function toReversedProjectionMatrix(projectionMatrix) { + const m = projectionMatrix.elements; + const isPerspectiveMatrix = m[11] === -1; + if (isPerspectiveMatrix) { + m[10] = -m[10] - 1; + m[14] = -m[14]; + } else { + m[10] = -m[10]; + m[14] = -m[14] + 1; + } +} +var LINEAR_REC709_TO_XYZ = /* @__PURE__ */ new Matrix3().set(0.4123908, 0.3575843, 0.1804808, 0.212639, 0.7151687, 0.0721923, 0.0193308, 0.1191948, 0.9505322); +var XYZ_TO_LINEAR_REC709 = /* @__PURE__ */ new Matrix3().set(3.2409699, -1.5373832, -0.4986108, -0.9692436, 1.8759675, 0.0415551, 0.0556301, -0.203977, 1.0569715); +function createColorManagement() { + const ColorManagement = { + enabled: true, + workingColorSpace: LinearSRGBColorSpace, + spaces: {}, + convert: function(color, sourceColorSpace, targetColorSpace) { + if (this.enabled === false || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) { + return color; + } + if (this.spaces[sourceColorSpace].transfer === SRGBTransfer) { + color.r = SRGBToLinear(color.r); + color.g = SRGBToLinear(color.g); + color.b = SRGBToLinear(color.b); + } + if (this.spaces[sourceColorSpace].primaries !== this.spaces[targetColorSpace].primaries) { + color.applyMatrix3(this.spaces[sourceColorSpace].toXYZ); + color.applyMatrix3(this.spaces[targetColorSpace].fromXYZ); + } + if (this.spaces[targetColorSpace].transfer === SRGBTransfer) { + color.r = LinearToSRGB(color.r); + color.g = LinearToSRGB(color.g); + color.b = LinearToSRGB(color.b); + } + return color; + }, + fromWorkingColorSpace: function(color, targetColorSpace) { + return this.convert(color, this.workingColorSpace, targetColorSpace); + }, + toWorkingColorSpace: function(color, sourceColorSpace) { + return this.convert(color, sourceColorSpace, this.workingColorSpace); + }, + getPrimaries: function(colorSpace) { + return this.spaces[colorSpace].primaries; + }, + getTransfer: function(colorSpace) { + if (colorSpace === NoColorSpace) + return LinearTransfer; + return this.spaces[colorSpace].transfer; + }, + getLuminanceCoefficients: function(target, colorSpace = this.workingColorSpace) { + return target.fromArray(this.spaces[colorSpace].luminanceCoefficients); + }, + define: function(colorSpaces) { + Object.assign(this.spaces, colorSpaces); + }, + _getMatrix: function(targetMatrix, sourceColorSpace, targetColorSpace) { + return targetMatrix.copy(this.spaces[sourceColorSpace].toXYZ).multiply(this.spaces[targetColorSpace].fromXYZ); + }, + _getDrawingBufferColorSpace: function(colorSpace) { + return this.spaces[colorSpace].outputColorSpaceConfig.drawingBufferColorSpace; + }, + _getUnpackColorSpace: function(colorSpace = this.workingColorSpace) { + return this.spaces[colorSpace].workingColorSpaceConfig.unpackColorSpace; + } + }; + const REC709_PRIMARIES = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06]; + const REC709_LUMINANCE_COEFFICIENTS = [0.2126, 0.7152, 0.0722]; + const D65 = [0.3127, 0.329]; + ColorManagement.define({ + [LinearSRGBColorSpace]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: LinearTransfer, + toXYZ: LINEAR_REC709_TO_XYZ, + fromXYZ: XYZ_TO_LINEAR_REC709, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace }, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace } + }, + [SRGBColorSpace]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: SRGBTransfer, + toXYZ: LINEAR_REC709_TO_XYZ, + fromXYZ: XYZ_TO_LINEAR_REC709, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace } + } + }); + return ColorManagement; +} +var ColorManagement = /* @__PURE__ */ createColorManagement(); +function SRGBToLinear(c) { + return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); +} +function LinearToSRGB(c) { + return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055; +} +var _canvas; + +class ImageUtils { + static getDataURL(image) { + if (/^data:/i.test(image.src)) { + return image.src; + } + if (typeof HTMLCanvasElement === "undefined") { + return image.src; + } + let canvas; + if (image instanceof HTMLCanvasElement) { + canvas = image; + } else { + if (_canvas === undefined) + _canvas = createElementNS("canvas"); + _canvas.width = image.width; + _canvas.height = image.height; + const context = _canvas.getContext("2d"); + if (image instanceof ImageData) { + context.putImageData(image, 0, 0); + } else { + context.drawImage(image, 0, 0, image.width, image.height); + } + canvas = _canvas; + } + return canvas.toDataURL("image/png"); + } + static sRGBToLinear(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + const canvas = createElementNS("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, image.width, image.height); + const imageData = context.getImageData(0, 0, image.width, image.height); + const data2 = imageData.data; + for (let i = 0;i < data2.length; i++) { + data2[i] = SRGBToLinear(data2[i] / 255) * 255; + } + context.putImageData(imageData, 0, 0); + return canvas; + } else if (image.data) { + const data2 = image.data.slice(0); + for (let i = 0;i < data2.length; i++) { + if (data2 instanceof Uint8Array || data2 instanceof Uint8ClampedArray) { + data2[i] = Math.floor(SRGBToLinear(data2[i] / 255) * 255); + } else { + data2[i] = SRGBToLinear(data2[i]); + } + } + return { + data: data2, + width: image.width, + height: image.height + }; + } else { + console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."); + return image; + } + } +} +var _sourceId = 0; + +class Source { + constructor(data2 = null) { + this.isSource = true; + Object.defineProperty(this, "id", { value: _sourceId++ }); + this.uuid = generateUUID(); + this.data = data2; + this.dataReady = true; + this.version = 0; + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + if (!isRootObject && meta.images[this.uuid] !== undefined) { + return meta.images[this.uuid]; + } + const output = { + uuid: this.uuid, + url: "" + }; + const data2 = this.data; + if (data2 !== null) { + let url; + if (Array.isArray(data2)) { + url = []; + for (let i = 0, l = data2.length;i < l; i++) { + if (data2[i].isDataTexture) { + url.push(serializeImage(data2[i].image)); + } else { + url.push(serializeImage(data2[i])); + } + } + } else { + url = serializeImage(data2); + } + output.url = url; + } + if (!isRootObject) { + meta.images[this.uuid] = output; + } + return output; + } +} +function serializeImage(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + return ImageUtils.getDataURL(image); + } else { + if (image.data) { + return { + data: Array.from(image.data), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; + } else { + console.warn("THREE.Texture: Unable to serialize Texture."); + return {}; + } + } +} +var _textureId = 0; + +class Texture extends EventDispatcher { + constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace) { + super(); + this.isTexture = true; + Object.defineProperty(this, "id", { value: _textureId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.source = new Source(image); + this.mipmaps = []; + this.mapping = mapping; + this.channel = 0; + this.wrapS = wrapS; + this.wrapT = wrapT; + this.magFilter = magFilter; + this.minFilter = minFilter; + this.anisotropy = anisotropy; + this.format = format; + this.internalFormat = null; + this.type = type; + this.offset = new Vector2(0, 0); + this.repeat = new Vector2(1, 1); + this.center = new Vector2(0, 0); + this.rotation = 0; + this.matrixAutoUpdate = true; + this.matrix = new Matrix3; + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; + this.colorSpace = colorSpace; + this.userData = {}; + this.version = 0; + this.onUpdate = null; + this.renderTarget = null; + this.isRenderTargetTexture = false; + this.pmremVersion = 0; + } + get image() { + return this.source.data; + } + set image(value2 = null) { + this.source.data = value2; + } + updateMatrix() { + this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.source = source.source; + this.mipmaps = source.mipmaps.slice(0); + this.mapping = source.mapping; + this.channel = source.channel; + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + this.anisotropy = source.anisotropy; + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + this.offset.copy(source.offset); + this.repeat.copy(source.repeat); + this.center.copy(source.center); + this.rotation = source.rotation; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy(source.matrix); + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.colorSpace = source.colorSpace; + this.renderTarget = source.renderTarget; + this.isRenderTargetTexture = source.isRenderTargetTexture; + this.userData = JSON.parse(JSON.stringify(source.userData)); + this.needsUpdate = true; + return this; + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + if (!isRootObject && meta.textures[this.uuid] !== undefined) { + return meta.textures[this.uuid]; + } + const output = { + metadata: { + version: 4.6, + type: "Texture", + generator: "Texture.toJSON" + }, + uuid: this.uuid, + name: this.name, + image: this.source.toJSON(meta).uuid, + mapping: this.mapping, + channel: this.channel, + repeat: [this.repeat.x, this.repeat.y], + offset: [this.offset.x, this.offset.y], + center: [this.center.x, this.center.y], + rotation: this.rotation, + wrap: [this.wrapS, this.wrapT], + format: this.format, + internalFormat: this.internalFormat, + type: this.type, + colorSpace: this.colorSpace, + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + flipY: this.flipY, + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + }; + if (Object.keys(this.userData).length > 0) + output.userData = this.userData; + if (!isRootObject) { + meta.textures[this.uuid] = output; + } + return output; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + transformUv(uv) { + if (this.mapping !== UVMapping) + return uv; + uv.applyMatrix3(this.matrix); + if (uv.x < 0 || uv.x > 1) { + switch (this.wrapS) { + case RepeatWrapping: + uv.x = uv.x - Math.floor(uv.x); + break; + case ClampToEdgeWrapping: + uv.x = uv.x < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping: + if (Math.abs(Math.floor(uv.x) % 2) === 1) { + uv.x = Math.ceil(uv.x) - uv.x; + } else { + uv.x = uv.x - Math.floor(uv.x); + } + break; + } + } + if (uv.y < 0 || uv.y > 1) { + switch (this.wrapT) { + case RepeatWrapping: + uv.y = uv.y - Math.floor(uv.y); + break; + case ClampToEdgeWrapping: + uv.y = uv.y < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping: + if (Math.abs(Math.floor(uv.y) % 2) === 1) { + uv.y = Math.ceil(uv.y) - uv.y; + } else { + uv.y = uv.y - Math.floor(uv.y); + } + break; + } + } + if (this.flipY) { + uv.y = 1 - uv.y; + } + return uv; + } + set needsUpdate(value2) { + if (value2 === true) { + this.version++; + this.source.needsUpdate = true; + } + } + set needsPMREMUpdate(value2) { + if (value2 === true) { + this.pmremVersion++; + } + } +} +Texture.DEFAULT_IMAGE = null; +Texture.DEFAULT_MAPPING = UVMapping; +Texture.DEFAULT_ANISOTROPY = 1; + +class Vector4 { + constructor(x = 0, y = 0, z = 0, w = 1) { + Vector4.prototype.isVector4 = true; + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + get width() { + return this.z; + } + set width(value2) { + this.z = value2; + } + get height() { + return this.w; + } + set height(value2) { + this.w = value2; + } + set(x, y, z, w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setZ(z) { + this.z = z; + return this; + } + setW(w) { + this.w = w; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + case 2: + this.z = value2; + break; + case 3: + this.w = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + case 3: + return this.w; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z, this.w); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = v.w !== undefined ? v.w : 1; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + this.w += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + return this; + } + applyMatrix4(m) { + const x = this.x, y = this.y, z = this.z, w = this.w; + const e = m.elements; + this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w; + this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w; + this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w; + this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + this.w /= v.w; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + setAxisAngleFromQuaternion(q) { + this.w = 2 * Math.acos(q.w); + const s = Math.sqrt(1 - q.w * q.w); + if (s < 0.0001) { + this.x = 1; + this.y = 0; + this.z = 0; + } else { + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; + } + return this; + } + setAxisAngleFromRotationMatrix(m) { + let angle, x, y, z; + const epsilon = 0.01, epsilon2 = 0.1, te2 = m.elements, m11 = te2[0], m12 = te2[4], m13 = te2[8], m21 = te2[1], m22 = te2[5], m23 = te2[9], m31 = te2[2], m32 = te2[6], m33 = te2[10]; + if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) { + if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) { + this.set(1, 0, 0, 0); + return this; + } + angle = Math.PI; + const xx = (m11 + 1) / 2; + const yy = (m22 + 1) / 2; + const zz = (m33 + 1) / 2; + const xy = (m12 + m21) / 4; + const xz = (m13 + m31) / 4; + const yz = (m23 + m32) / 4; + if (xx > yy && xx > zz) { + if (xx < epsilon) { + x = 0; + y = 0.707106781; + z = 0.707106781; + } else { + x = Math.sqrt(xx); + y = xy / x; + z = xz / x; + } + } else if (yy > zz) { + if (yy < epsilon) { + x = 0.707106781; + y = 0; + z = 0.707106781; + } else { + y = Math.sqrt(yy); + x = xy / y; + z = yz / y; + } + } else { + if (zz < epsilon) { + x = 0.707106781; + y = 0.707106781; + z = 0; + } else { + z = Math.sqrt(zz); + x = xz / z; + y = yz / z; + } + } + this.set(x, y, z, angle); + return this; + } + let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); + if (Math.abs(s) < 0.001) + s = 1; + this.x = (m32 - m23) / s; + this.y = (m13 - m31) / s; + this.z = (m21 - m12) / s; + this.w = Math.acos((m11 + m22 + m33 - 1) / 2); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + this.w = e[15]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + this.w = Math.min(this.w, v.w); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + this.w = Math.max(this.w, v.w); + return this; + } + clamp(min, max) { + this.x = clamp2(this.x, min.x, max.x); + this.y = clamp2(this.y, min.y, max.y); + this.z = clamp2(this.z, min.z, max.z); + this.w = clamp2(this.w, min.w, max.w); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp2(this.x, minVal, maxVal); + this.y = clamp2(this.y, minVal, maxVal); + this.z = clamp2(this.z, minVal, maxVal); + this.w = clamp2(this.w, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp2(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + this.w = Math.floor(this.w); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + this.w = Math.ceil(this.w); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + this.w = Math.round(this.w); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + this.w = Math.trunc(this.w); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + this.w += (v.w - this.w) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + this.w = v1.w + (v2.w - v1.w) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + this.w = array[offset + 3]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + array[offset + 3] = this.w; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + this.z = attribute.getZ(index2); + this.w = attribute.getW(index2); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + yield this.w; + } +} + +class RenderTarget extends EventDispatcher { + constructor(width2 = 1, height2 = 1, options = {}) { + super(); + this.isRenderTarget = true; + this.width = width2; + this.height = height2; + this.depth = 1; + this.scissor = new Vector4(0, 0, width2, height2); + this.scissorTest = false; + this.viewport = new Vector4(0, 0, width2, height2); + const image = { width: width2, height: height2, depth: 1 }; + options = Object.assign({ + generateMipmaps: false, + internalFormat: null, + minFilter: LinearFilter, + depthBuffer: true, + stencilBuffer: false, + resolveDepthBuffer: true, + resolveStencilBuffer: true, + depthTexture: null, + samples: 0, + count: 1 + }, options); + const texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + texture.flipY = false; + texture.generateMipmaps = options.generateMipmaps; + texture.internalFormat = options.internalFormat; + this.textures = []; + const count = options.count; + for (let i = 0;i < count; i++) { + this.textures[i] = texture.clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + } + this.depthBuffer = options.depthBuffer; + this.stencilBuffer = options.stencilBuffer; + this.resolveDepthBuffer = options.resolveDepthBuffer; + this.resolveStencilBuffer = options.resolveStencilBuffer; + this._depthTexture = null; + this.depthTexture = options.depthTexture; + this.samples = options.samples; + } + get texture() { + return this.textures[0]; + } + set texture(value2) { + this.textures[0] = value2; + } + set depthTexture(current) { + if (this._depthTexture !== null) + this._depthTexture.renderTarget = null; + if (current !== null) + current.renderTarget = this; + this._depthTexture = current; + } + get depthTexture() { + return this._depthTexture; + } + setSize(width2, height2, depth = 1) { + if (this.width !== width2 || this.height !== height2 || this.depth !== depth) { + this.width = width2; + this.height = height2; + this.depth = depth; + for (let i = 0, il = this.textures.length;i < il; i++) { + this.textures[i].image.width = width2; + this.textures[i].image.height = height2; + this.textures[i].image.depth = depth; + } + this.dispose(); + } + this.viewport.set(0, 0, width2, height2); + this.scissor.set(0, 0, width2, height2); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + this.scissor.copy(source.scissor); + this.scissorTest = source.scissorTest; + this.viewport.copy(source.viewport); + this.textures.length = 0; + for (let i = 0, il = source.textures.length;i < il; i++) { + this.textures[i] = source.textures[i].clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + } + const image = Object.assign({}, source.texture.image); + this.texture.source = new Source(image); + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.resolveDepthBuffer = source.resolveDepthBuffer; + this.resolveStencilBuffer = source.resolveStencilBuffer; + if (source.depthTexture !== null) + this.depthTexture = source.depthTexture.clone(); + this.samples = source.samples; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } +} + +class WebGLRenderTarget extends RenderTarget { + constructor(width2 = 1, height2 = 1, options = {}) { + super(width2, height2, options); + this.isWebGLRenderTarget = true; + } +} + +class DataArrayTexture extends Texture { + constructor(data2 = null, width2 = 1, height2 = 1, depth = 1) { + super(null); + this.isDataArrayTexture = true; + this.image = { data: data2, width: width2, height: height2, depth }; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.wrapR = ClampToEdgeWrapping; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + this.layerUpdates = new Set; + } + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + clearLayerUpdates() { + this.layerUpdates.clear(); + } +} + +class WebGLArrayRenderTarget extends WebGLRenderTarget { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isWebGLArrayRenderTarget = true; + this.depth = depth; + this.texture = new DataArrayTexture(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } +} + +class Data3DTexture extends Texture { + constructor(data2 = null, width2 = 1, height2 = 1, depth = 1) { + super(null); + this.isData3DTexture = true; + this.image = { data: data2, width: width2, height: height2, depth }; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.wrapR = ClampToEdgeWrapping; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } +} + +class WebGL3DRenderTarget extends WebGLRenderTarget { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isWebGL3DRenderTarget = true; + this.depth = depth; + this.texture = new Data3DTexture(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } +} + +class Quaternion { + constructor(x = 0, y = 0, z = 0, w = 1) { + this.isQuaternion = true; + this._x = x; + this._y = y; + this._z = z; + this._w = w; + } + static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) { + let x0 = src0[srcOffset0 + 0], y0 = src0[srcOffset0 + 1], z0 = src0[srcOffset0 + 2], w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1 + 0], y1 = src1[srcOffset1 + 1], z1 = src1[srcOffset1 + 2], w1 = src1[srcOffset1 + 3]; + if (t === 0) { + dst[dstOffset + 0] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + return; + } + if (t === 1) { + dst[dstOffset + 0] = x1; + dst[dstOffset + 1] = y1; + dst[dstOffset + 2] = z1; + dst[dstOffset + 3] = w1; + return; + } + if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) { + let s = 1 - t; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, dir = cos >= 0 ? 1 : -1, sqrSin = 1 - cos * cos; + if (sqrSin > Number.EPSILON) { + const sin = Math.sqrt(sqrSin), len = Math.atan2(sin, cos * dir); + s = Math.sin(s * len) / sin; + t = Math.sin(t * len) / sin; + } + const tDir = t * dir; + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; + if (s === 1 - t) { + const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0); + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; + } + } + dst[dstOffset] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + } + static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) { + const x0 = src0[srcOffset0]; + const y0 = src0[srcOffset0 + 1]; + const z0 = src0[srcOffset0 + 2]; + const w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1]; + const y1 = src1[srcOffset1 + 1]; + const z1 = src1[srcOffset1 + 2]; + const w1 = src1[srcOffset1 + 3]; + dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + return dst; + } + get x() { + return this._x; + } + set x(value2) { + this._x = value2; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value2) { + this._y = value2; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value2) { + this._z = value2; + this._onChangeCallback(); + } + get w() { + return this._w; + } + set w(value2) { + this._w = value2; + this._onChangeCallback(); + } + set(x, y, z, w) { + this._x = x; + this._y = y; + this._z = z; + this._w = w; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._w); + } + copy(quaternion) { + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + this._onChangeCallback(); + return this; + } + setFromEuler(euler, update = true) { + const { _x: x, _y: y, _z: z, _order: order } = euler; + const cos = Math.cos; + const sin = Math.sin; + const c1 = cos(x / 2); + const c2 = cos(y / 2); + const c3 = cos(z / 2); + const s1 = sin(x / 2); + const s2 = sin(y / 2); + const s3 = sin(z / 2); + switch (order) { + case "XYZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "YXZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "ZXY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "ZYX": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "YZX": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "XZY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + default: + console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + order); + } + if (update === true) + this._onChangeCallback(); + return this; + } + setFromAxisAngle(axis, angle) { + const halfAngle = angle / 2, s = Math.sin(halfAngle); + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos(halfAngle); + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m) { + const te2 = m.elements, m11 = te2[0], m12 = te2[4], m13 = te2[8], m21 = te2[1], m22 = te2[5], m23 = te2[9], m31 = te2[2], m32 = te2[6], m33 = te2[10], trace = m11 + m22 + m33; + if (trace > 0) { + const s = 0.5 / Math.sqrt(trace + 1); + this._w = 0.25 / s; + this._x = (m32 - m23) * s; + this._y = (m13 - m31) * s; + this._z = (m21 - m12) * s; + } else if (m11 > m22 && m11 > m33) { + const s = 2 * Math.sqrt(1 + m11 - m22 - m33); + this._w = (m32 - m23) / s; + this._x = 0.25 * s; + this._y = (m12 + m21) / s; + this._z = (m13 + m31) / s; + } else if (m22 > m33) { + const s = 2 * Math.sqrt(1 + m22 - m11 - m33); + this._w = (m13 - m31) / s; + this._x = (m12 + m21) / s; + this._y = 0.25 * s; + this._z = (m23 + m32) / s; + } else { + const s = 2 * Math.sqrt(1 + m33 - m11 - m22); + this._w = (m21 - m12) / s; + this._x = (m13 + m31) / s; + this._y = (m23 + m32) / s; + this._z = 0.25 * s; + } + this._onChangeCallback(); + return this; + } + setFromUnitVectors(vFrom, vTo) { + let r = vFrom.dot(vTo) + 1; + if (r < Number.EPSILON) { + r = 0; + if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) { + this._x = -vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + } else { + this._x = 0; + this._y = -vFrom.z; + this._z = vFrom.y; + this._w = r; + } + } else { + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + } + return this.normalize(); + } + angleTo(q) { + return 2 * Math.acos(Math.abs(clamp2(this.dot(q), -1, 1))); + } + rotateTowards(q, step) { + const angle = this.angleTo(q); + if (angle === 0) + return this; + const t = Math.min(1, step / angle); + this.slerp(q, t); + return this; + } + identity() { + return this.set(0, 0, 0, 1); + } + invert() { + return this.conjugate(); + } + conjugate() { + this._x *= -1; + this._y *= -1; + this._z *= -1; + this._onChangeCallback(); + return this; + } + dot(v) { + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + } + lengthSq() { + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + } + length() { + return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); + } + normalize() { + let l = this.length(); + if (l === 0) { + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + } else { + l = 1 / l; + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; + } + this._onChangeCallback(); + return this; + } + multiply(q) { + return this.multiplyQuaternions(this, q); + } + premultiply(q) { + return this.multiplyQuaternions(q, this); + } + multiplyQuaternions(a, b) { + const { _x: qax, _y: qay, _z: qaz, _w: qaw } = a; + const { _x: qbx, _y: qby, _z: qbz, _w: qbw } = b; + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + this._onChangeCallback(); + return this; + } + slerp(qb, t) { + if (t === 0) + return this; + if (t === 1) + return this.copy(qb); + const x = this._x, y = this._y, z = this._z, w = this._w; + let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + if (cosHalfTheta < 0) { + this._w = -qb._w; + this._x = -qb._x; + this._y = -qb._y; + this._z = -qb._z; + cosHalfTheta = -cosHalfTheta; + } else { + this.copy(qb); + } + if (cosHalfTheta >= 1) { + this._w = w; + this._x = x; + this._y = y; + this._z = z; + return this; + } + const sqrSinHalfTheta = 1 - cosHalfTheta * cosHalfTheta; + if (sqrSinHalfTheta <= Number.EPSILON) { + const s = 1 - t; + this._w = s * w + t * this._w; + this._x = s * x + t * this._x; + this._y = s * y + t * this._y; + this._z = s * z + t * this._z; + this.normalize(); + return this; + } + const sinHalfTheta = Math.sqrt(sqrSinHalfTheta); + const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta); + const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta, ratioB = Math.sin(t * halfTheta) / sinHalfTheta; + this._w = w * ratioA + this._w * ratioB; + this._x = x * ratioA + this._x * ratioB; + this._y = y * ratioA + this._y * ratioB; + this._z = z * ratioA + this._z * ratioB; + this._onChangeCallback(); + return this; + } + slerpQuaternions(qa, qb, t) { + return this.copy(qa).slerp(qb, t); + } + random() { + const theta1 = 2 * Math.PI * Math.random(); + const theta2 = 2 * Math.PI * Math.random(); + const x0 = Math.random(); + const r1 = Math.sqrt(1 - x0); + const r2 = Math.sqrt(x0); + return this.set(r1 * Math.sin(theta1), r1 * Math.cos(theta1), r2 * Math.sin(theta2), r2 * Math.cos(theta2)); + } + equals(quaternion) { + return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w; + } + fromArray(array, offset = 0) { + this._x = array[offset]; + this._y = array[offset + 1]; + this._z = array[offset + 2]; + this._w = array[offset + 3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._w; + return array; + } + fromBufferAttribute(attribute, index2) { + this._x = attribute.getX(index2); + this._y = attribute.getY(index2); + this._z = attribute.getZ(index2); + this._w = attribute.getW(index2); + this._onChangeCallback(); + return this; + } + toJSON() { + return this.toArray(); + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._w; + } +} + +class Vector3 { + constructor(x = 0, y = 0, z = 0) { + Vector3.prototype.isVector3 = true; + this.x = x; + this.y = y; + this.z = z; + } + set(x, y, z) { + if (z === undefined) + z = this.z; + this.x = x; + this.y = y; + this.z = z; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setZ(z) { + this.z = z; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + case 2: + this.z = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + return this; + } + multiplyVectors(a, b) { + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; + return this; + } + applyEuler(euler) { + return this.applyQuaternion(_quaternion$4.setFromEuler(euler)); + } + applyAxisAngle(axis, angle) { + return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle)); + } + applyMatrix3(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + this.x = e[0] * x + e[3] * y + e[6] * z; + this.y = e[1] * x + e[4] * y + e[7] * z; + this.z = e[2] * x + e[5] * y + e[8] * z; + return this; + } + applyNormalMatrix(m) { + return this.applyMatrix3(m).normalize(); + } + applyMatrix4(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]); + this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w; + this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w; + this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w; + return this; + } + applyQuaternion(q) { + const vx = this.x, vy = this.y, vz = this.z; + const { x: qx, y: qy, z: qz, w: qw } = q; + const tx = 2 * (qy * vz - qz * vy); + const ty = 2 * (qz * vx - qx * vz); + const tz = 2 * (qx * vy - qy * vx); + this.x = vx + qw * tx + qy * tz - qz * ty; + this.y = vy + qw * ty + qz * tx - qx * tz; + this.z = vz + qw * tz + qx * ty - qy * tx; + return this; + } + project(camera) { + return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix); + } + unproject(camera) { + return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld); + } + transformDirection(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + this.x = e[0] * x + e[4] * y + e[8] * z; + this.y = e[1] * x + e[5] * y + e[9] * z; + this.z = e[2] * x + e[6] * y + e[10] * z; + return this.normalize(); + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + return this; + } + clamp(min, max) { + this.x = clamp2(this.x, min.x, max.x); + this.y = clamp2(this.y, min.y, max.y); + this.z = clamp2(this.z, min.z, max.z); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp2(this.x, minVal, maxVal); + this.y = clamp2(this.y, minVal, maxVal); + this.z = clamp2(this.z, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp2(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + return this; + } + cross(v) { + return this.crossVectors(this, v); + } + crossVectors(a, b) { + const { x: ax, y: ay, z: az } = a; + const { x: bx, y: by, z: bz } = b; + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + return this; + } + projectOnVector(v) { + const denominator = v.lengthSq(); + if (denominator === 0) + return this.set(0, 0, 0); + const scalar = v.dot(this) / denominator; + return this.copy(v).multiplyScalar(scalar); + } + projectOnPlane(planeNormal) { + _vector$c.copy(this).projectOnVector(planeNormal); + return this.sub(_vector$c); + } + reflect(normal) { + return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal))); + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) + return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp2(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + return dx * dx + dy * dy + dz * dz; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z); + } + setFromSpherical(s) { + return this.setFromSphericalCoords(s.radius, s.phi, s.theta); + } + setFromSphericalCoords(radius, phi, theta) { + const sinPhiRadius = Math.sin(phi) * radius; + this.x = sinPhiRadius * Math.sin(theta); + this.y = Math.cos(phi) * radius; + this.z = sinPhiRadius * Math.cos(theta); + return this; + } + setFromCylindrical(c) { + return this.setFromCylindricalCoords(c.radius, c.theta, c.y); + } + setFromCylindricalCoords(radius, theta, y) { + this.x = radius * Math.sin(theta); + this.y = y; + this.z = radius * Math.cos(theta); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + return this; + } + setFromMatrixScale(m) { + const sx = this.setFromMatrixColumn(m, 0).length(); + const sy = this.setFromMatrixColumn(m, 1).length(); + const sz = this.setFromMatrixColumn(m, 2).length(); + this.x = sx; + this.y = sy; + this.z = sz; + return this; + } + setFromMatrixColumn(m, index2) { + return this.fromArray(m.elements, index2 * 4); + } + setFromMatrix3Column(m, index2) { + return this.fromArray(m.elements, index2 * 3); + } + setFromEuler(e) { + this.x = e._x; + this.y = e._y; + this.z = e._z; + return this; + } + setFromColor(c) { + this.x = c.r; + this.y = c.g; + this.z = c.b; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + this.z = attribute.getZ(index2); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + return this; + } + randomDirection() { + const theta = Math.random() * Math.PI * 2; + const u = Math.random() * 2 - 1; + const c = Math.sqrt(1 - u * u); + this.x = c * Math.cos(theta); + this.y = u; + this.z = c * Math.sin(theta); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + } +} +var _vector$c = /* @__PURE__ */ new Vector3; +var _quaternion$4 = /* @__PURE__ */ new Quaternion; + +class Box3 { + constructor(min = new Vector3(Infinity, Infinity, Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) { + this.isBox3 = true; + this.min = min; + this.max = max; + } + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + setFromArray(array) { + this.makeEmpty(); + for (let i = 0, il = array.length;i < il; i += 3) { + this.expandByPoint(_vector$b.fromArray(array, i)); + } + return this; + } + setFromBufferAttribute(attribute) { + this.makeEmpty(); + for (let i = 0, il = attribute.count;i < il; i++) { + this.expandByPoint(_vector$b.fromBufferAttribute(attribute, i)); + } + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length;i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size) { + const halfSize = _vector$b.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + setFromObject(object, precise = false) { + this.makeEmpty(); + return this.expandByObject(object, precise); + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = this.min.z = Infinity; + this.max.x = this.max.y = this.max.z = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + expandByObject(object, precise = false) { + object.updateWorldMatrix(false, false); + const geometry = object.geometry; + if (geometry !== undefined) { + const positionAttribute = geometry.getAttribute("position"); + if (precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true) { + for (let i = 0, l = positionAttribute.count;i < l; i++) { + if (object.isMesh === true) { + object.getVertexPosition(i, _vector$b); + } else { + _vector$b.fromBufferAttribute(positionAttribute, i); + } + _vector$b.applyMatrix4(object.matrixWorld); + this.expandByPoint(_vector$b); + } + } else { + if (object.boundingBox !== undefined) { + if (object.boundingBox === null) { + object.computeBoundingBox(); + } + _box$4.copy(object.boundingBox); + } else { + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + _box$4.copy(geometry.boundingBox); + } + _box$4.applyMatrix4(object.matrixWorld); + this.union(_box$4); + } + } + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + this.expandByObject(children[i], precise); + } + return this; + } + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y && point.z >= this.min.z && point.z <= this.max.z; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z; + } + getParameter(point, target) { + return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z)); + } + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y && box.max.z >= this.min.z && box.min.z <= this.max.z; + } + intersectsSphere(sphere) { + this.clampPoint(sphere.center, _vector$b); + return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; + } + intersectsPlane(plane) { + let min, max; + if (plane.normal.x > 0) { + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + } else { + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + } + if (plane.normal.y > 0) { + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + } else { + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + } + if (plane.normal.z > 0) { + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + } else { + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + } + return min <= -plane.constant && max >= -plane.constant; + } + intersectsTriangle(triangle) { + if (this.isEmpty()) { + return false; + } + this.getCenter(_center); + _extents.subVectors(this.max, _center); + _v0$2.subVectors(triangle.a, _center); + _v1$7.subVectors(triangle.b, _center); + _v2$4.subVectors(triangle.c, _center); + _f0.subVectors(_v1$7, _v0$2); + _f1.subVectors(_v2$4, _v1$7); + _f2.subVectors(_v0$2, _v2$4); + let axes = [ + 0, + -_f0.z, + _f0.y, + 0, + -_f1.z, + _f1.y, + 0, + -_f2.z, + _f2.y, + _f0.z, + 0, + -_f0.x, + _f1.z, + 0, + -_f1.x, + _f2.z, + 0, + -_f2.x, + -_f0.y, + _f0.x, + 0, + -_f1.y, + _f1.x, + 0, + -_f2.y, + _f2.x, + 0 + ]; + if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) { + return false; + } + axes = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) { + return false; + } + _triangleNormal.crossVectors(_f0, _f1); + axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z]; + return satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents); + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$b).distanceTo(point); + } + getBoundingSphere(target) { + if (this.isEmpty()) { + target.makeEmpty(); + } else { + this.getCenter(target.center); + target.radius = this.getSize(_vector$b).length() * 0.5; + } + return target; + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) + this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + applyMatrix4(matrix) { + if (this.isEmpty()) + return this; + _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); + _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); + this.setFromPoints(_points); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } +} +var _points = [ + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3 +]; +var _vector$b = /* @__PURE__ */ new Vector3; +var _box$4 = /* @__PURE__ */ new Box3; +var _v0$2 = /* @__PURE__ */ new Vector3; +var _v1$7 = /* @__PURE__ */ new Vector3; +var _v2$4 = /* @__PURE__ */ new Vector3; +var _f0 = /* @__PURE__ */ new Vector3; +var _f1 = /* @__PURE__ */ new Vector3; +var _f2 = /* @__PURE__ */ new Vector3; +var _center = /* @__PURE__ */ new Vector3; +var _extents = /* @__PURE__ */ new Vector3; +var _triangleNormal = /* @__PURE__ */ new Vector3; +var _testAxis = /* @__PURE__ */ new Vector3; +function satForAxes(axes, v0, v1, v2, extents) { + for (let i = 0, j = axes.length - 3;i <= j; i += 3) { + _testAxis.fromArray(axes, i); + const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); + const p0 = v0.dot(_testAxis); + const p1 = v1.dot(_testAxis); + const p2 = v2.dot(_testAxis); + if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) { + return false; + } + } + return true; +} +var _box$3 = /* @__PURE__ */ new Box3; +var _v1$6 = /* @__PURE__ */ new Vector3; +var _v2$3 = /* @__PURE__ */ new Vector3; + +class Sphere { + constructor(center = new Vector3, radius = -1) { + this.isSphere = true; + this.center = center; + this.radius = radius; + } + set(center, radius) { + this.center.copy(center); + this.radius = radius; + return this; + } + setFromPoints(points, optionalCenter) { + const center = this.center; + if (optionalCenter !== undefined) { + center.copy(optionalCenter); + } else { + _box$3.setFromPoints(points).getCenter(center); + } + let maxRadiusSq = 0; + for (let i = 0, il = points.length;i < il; i++) { + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i])); + } + this.radius = Math.sqrt(maxRadiusSq); + return this; + } + copy(sphere) { + this.center.copy(sphere.center); + this.radius = sphere.radius; + return this; + } + isEmpty() { + return this.radius < 0; + } + makeEmpty() { + this.center.set(0, 0, 0); + this.radius = -1; + return this; + } + containsPoint(point) { + return point.distanceToSquared(this.center) <= this.radius * this.radius; + } + distanceToPoint(point) { + return point.distanceTo(this.center) - this.radius; + } + intersectsSphere(sphere) { + const radiusSum = this.radius + sphere.radius; + return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum; + } + intersectsBox(box) { + return box.intersectsSphere(this); + } + intersectsPlane(plane) { + return Math.abs(plane.distanceToPoint(this.center)) <= this.radius; + } + clampPoint(point, target) { + const deltaLengthSq = this.center.distanceToSquared(point); + target.copy(point); + if (deltaLengthSq > this.radius * this.radius) { + target.sub(this.center).normalize(); + target.multiplyScalar(this.radius).add(this.center); + } + return target; + } + getBoundingBox(target) { + if (this.isEmpty()) { + target.makeEmpty(); + return target; + } + target.set(this.center, this.center); + target.expandByScalar(this.radius); + return target; + } + applyMatrix4(matrix) { + this.center.applyMatrix4(matrix); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); + return this; + } + translate(offset) { + this.center.add(offset); + return this; + } + expandByPoint(point) { + if (this.isEmpty()) { + this.center.copy(point); + this.radius = 0; + return this; + } + _v1$6.subVectors(point, this.center); + const lengthSq = _v1$6.lengthSq(); + if (lengthSq > this.radius * this.radius) { + const length2 = Math.sqrt(lengthSq); + const delta = (length2 - this.radius) * 0.5; + this.center.addScaledVector(_v1$6, delta / length2); + this.radius += delta; + } + return this; + } + union(sphere) { + if (sphere.isEmpty()) { + return this; + } + if (this.isEmpty()) { + this.copy(sphere); + return this; + } + if (this.center.equals(sphere.center) === true) { + this.radius = Math.max(this.radius, sphere.radius); + } else { + _v2$3.subVectors(sphere.center, this.center).setLength(sphere.radius); + this.expandByPoint(_v1$6.copy(sphere.center).add(_v2$3)); + this.expandByPoint(_v1$6.copy(sphere.center).sub(_v2$3)); + } + return this; + } + equals(sphere) { + return sphere.center.equals(this.center) && sphere.radius === this.radius; + } + clone() { + return new this.constructor().copy(this); + } +} +var _vector$a = /* @__PURE__ */ new Vector3; +var _segCenter = /* @__PURE__ */ new Vector3; +var _segDir = /* @__PURE__ */ new Vector3; +var _diff = /* @__PURE__ */ new Vector3; +var _edge1 = /* @__PURE__ */ new Vector3; +var _edge2 = /* @__PURE__ */ new Vector3; +var _normal$1 = /* @__PURE__ */ new Vector3; + +class Ray { + constructor(origin = new Vector3, direction = new Vector3(0, 0, -1)) { + this.origin = origin; + this.direction = direction; + } + set(origin, direction) { + this.origin.copy(origin); + this.direction.copy(direction); + return this; + } + copy(ray) { + this.origin.copy(ray.origin); + this.direction.copy(ray.direction); + return this; + } + at(t, target) { + return target.copy(this.origin).addScaledVector(this.direction, t); + } + lookAt(v) { + this.direction.copy(v).sub(this.origin).normalize(); + return this; + } + recast(t) { + this.origin.copy(this.at(t, _vector$a)); + return this; + } + closestPointToPoint(point, target) { + target.subVectors(point, this.origin); + const directionDistance = target.dot(this.direction); + if (directionDistance < 0) { + return target.copy(this.origin); + } + return target.copy(this.origin).addScaledVector(this.direction, directionDistance); + } + distanceToPoint(point) { + return Math.sqrt(this.distanceSqToPoint(point)); + } + distanceSqToPoint(point) { + const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); + if (directionDistance < 0) { + return this.origin.distanceToSquared(point); + } + _vector$a.copy(this.origin).addScaledVector(this.direction, directionDistance); + return _vector$a.distanceToSquared(point); + } + distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) { + _segCenter.copy(v0).add(v1).multiplyScalar(0.5); + _segDir.copy(v1).sub(v0).normalize(); + _diff.copy(this.origin).sub(_segCenter); + const segExtent = v0.distanceTo(v1) * 0.5; + const a01 = -this.direction.dot(_segDir); + const b0 = _diff.dot(this.direction); + const b1 = -_diff.dot(_segDir); + const c = _diff.lengthSq(); + const det = Math.abs(1 - a01 * a01); + let s0, s1, sqrDist, extDet; + if (det > 0) { + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + if (s0 >= 0) { + if (s1 >= -extDet) { + if (s1 <= extDet) { + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c; + } else { + s1 = segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } else { + s1 = -segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } else { + if (s1 <= -extDet) { + s0 = Math.max(0, -(-a01 * segExtent + b0)); + s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } else if (s1 <= extDet) { + s0 = 0; + s1 = Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = s1 * (s1 + 2 * b1) + c; + } else { + s0 = Math.max(0, -(a01 * segExtent + b0)); + s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } + } else { + s1 = a01 > 0 ? -segExtent : segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + if (optionalPointOnRay) { + optionalPointOnRay.copy(this.origin).addScaledVector(this.direction, s0); + } + if (optionalPointOnSegment) { + optionalPointOnSegment.copy(_segCenter).addScaledVector(_segDir, s1); + } + return sqrDist; + } + intersectSphere(sphere, target) { + _vector$a.subVectors(sphere.center, this.origin); + const tca = _vector$a.dot(this.direction); + const d2 = _vector$a.dot(_vector$a) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + if (d2 > radius2) + return null; + const thc = Math.sqrt(radius2 - d2); + const t0 = tca - thc; + const t1 = tca + thc; + if (t1 < 0) + return null; + if (t0 < 0) + return this.at(t1, target); + return this.at(t0, target); + } + intersectsSphere(sphere) { + return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius; + } + distanceToPlane(plane) { + const denominator = plane.normal.dot(this.direction); + if (denominator === 0) { + if (plane.distanceToPoint(this.origin) === 0) { + return 0; + } + return null; + } + const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; + return t >= 0 ? t : null; + } + intersectPlane(plane, target) { + const t = this.distanceToPlane(plane); + if (t === null) { + return null; + } + return this.at(t, target); + } + intersectsPlane(plane) { + const distToPoint = plane.distanceToPoint(this.origin); + if (distToPoint === 0) { + return true; + } + const denominator = plane.normal.dot(this.direction); + if (denominator * distToPoint < 0) { + return true; + } + return false; + } + intersectBox(box, target) { + let tmin, tmax, tymin, tymax, tzmin, tzmax; + const invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z; + const origin = this.origin; + if (invdirx >= 0) { + tmin = (box.min.x - origin.x) * invdirx; + tmax = (box.max.x - origin.x) * invdirx; + } else { + tmin = (box.max.x - origin.x) * invdirx; + tmax = (box.min.x - origin.x) * invdirx; + } + if (invdiry >= 0) { + tymin = (box.min.y - origin.y) * invdiry; + tymax = (box.max.y - origin.y) * invdiry; + } else { + tymin = (box.max.y - origin.y) * invdiry; + tymax = (box.min.y - origin.y) * invdiry; + } + if (tmin > tymax || tymin > tmax) + return null; + if (tymin > tmin || isNaN(tmin)) + tmin = tymin; + if (tymax < tmax || isNaN(tmax)) + tmax = tymax; + if (invdirz >= 0) { + tzmin = (box.min.z - origin.z) * invdirz; + tzmax = (box.max.z - origin.z) * invdirz; + } else { + tzmin = (box.max.z - origin.z) * invdirz; + tzmax = (box.min.z - origin.z) * invdirz; + } + if (tmin > tzmax || tzmin > tmax) + return null; + if (tzmin > tmin || tmin !== tmin) + tmin = tzmin; + if (tzmax < tmax || tmax !== tmax) + tmax = tzmax; + if (tmax < 0) + return null; + return this.at(tmin >= 0 ? tmin : tmax, target); + } + intersectsBox(box) { + return this.intersectBox(box, _vector$a) !== null; + } + intersectTriangle(a, b, c, backfaceCulling, target) { + _edge1.subVectors(b, a); + _edge2.subVectors(c, a); + _normal$1.crossVectors(_edge1, _edge2); + let DdN = this.direction.dot(_normal$1); + let sign; + if (DdN > 0) { + if (backfaceCulling) + return null; + sign = 1; + } else if (DdN < 0) { + sign = -1; + DdN = -DdN; + } else { + return null; + } + _diff.subVectors(this.origin, a); + const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); + if (DdQxE2 < 0) { + return null; + } + const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); + if (DdE1xQ < 0) { + return null; + } + if (DdQxE2 + DdE1xQ > DdN) { + return null; + } + const QdN = -sign * _diff.dot(_normal$1); + if (QdN < 0) { + return null; + } + return this.at(QdN / DdN, target); + } + applyMatrix4(matrix4) { + this.origin.applyMatrix4(matrix4); + this.direction.transformDirection(matrix4); + return this; + } + equals(ray) { + return ray.origin.equals(this.origin) && ray.direction.equals(this.direction); + } + clone() { + return new this.constructor().copy(this); + } +} + +class Matrix4 { + constructor(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + Matrix4.prototype.isMatrix4 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44); + } + } + set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + const te2 = this.elements; + te2[0] = n11; + te2[4] = n12; + te2[8] = n13; + te2[12] = n14; + te2[1] = n21; + te2[5] = n22; + te2[9] = n23; + te2[13] = n24; + te2[2] = n31; + te2[6] = n32; + te2[10] = n33; + te2[14] = n34; + te2[3] = n41; + te2[7] = n42; + te2[11] = n43; + te2[15] = n44; + return this; + } + identity() { + this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return this; + } + clone() { + return new Matrix4().fromArray(this.elements); + } + copy(m) { + const te2 = this.elements; + const me = m.elements; + te2[0] = me[0]; + te2[1] = me[1]; + te2[2] = me[2]; + te2[3] = me[3]; + te2[4] = me[4]; + te2[5] = me[5]; + te2[6] = me[6]; + te2[7] = me[7]; + te2[8] = me[8]; + te2[9] = me[9]; + te2[10] = me[10]; + te2[11] = me[11]; + te2[12] = me[12]; + te2[13] = me[13]; + te2[14] = me[14]; + te2[15] = me[15]; + return this; + } + copyPosition(m) { + const te2 = this.elements, me = m.elements; + te2[12] = me[12]; + te2[13] = me[13]; + te2[14] = me[14]; + return this; + } + setFromMatrix3(m) { + const me = m.elements; + this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1); + return this; + } + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrixColumn(this, 0); + yAxis.setFromMatrixColumn(this, 1); + zAxis.setFromMatrixColumn(this, 2); + return this; + } + makeBasis(xAxis, yAxis, zAxis) { + this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1); + return this; + } + extractRotation(m) { + const te2 = this.elements; + const me = m.elements; + const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length(); + const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length(); + const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length(); + te2[0] = me[0] * scaleX; + te2[1] = me[1] * scaleX; + te2[2] = me[2] * scaleX; + te2[3] = 0; + te2[4] = me[4] * scaleY; + te2[5] = me[5] * scaleY; + te2[6] = me[6] * scaleY; + te2[7] = 0; + te2[8] = me[8] * scaleZ; + te2[9] = me[9] * scaleZ; + te2[10] = me[10] * scaleZ; + te2[11] = 0; + te2[12] = 0; + te2[13] = 0; + te2[14] = 0; + te2[15] = 1; + return this; + } + makeRotationFromEuler(euler) { + const te2 = this.elements; + const { x, y, z } = euler; + const a = Math.cos(x), b = Math.sin(x); + const c = Math.cos(y), d = Math.sin(y); + const e = Math.cos(z), f = Math.sin(z); + if (euler.order === "XYZ") { + const ae2 = a * e, af = a * f, be = b * e, bf = b * f; + te2[0] = c * e; + te2[4] = -c * f; + te2[8] = d; + te2[1] = af + be * d; + te2[5] = ae2 - bf * d; + te2[9] = -b * c; + te2[2] = bf - ae2 * d; + te2[6] = be + af * d; + te2[10] = a * c; + } else if (euler.order === "YXZ") { + const ce2 = c * e, cf = c * f, de = d * e, df = d * f; + te2[0] = ce2 + df * b; + te2[4] = de * b - cf; + te2[8] = a * d; + te2[1] = a * f; + te2[5] = a * e; + te2[9] = -b; + te2[2] = cf * b - de; + te2[6] = df + ce2 * b; + te2[10] = a * c; + } else if (euler.order === "ZXY") { + const ce2 = c * e, cf = c * f, de = d * e, df = d * f; + te2[0] = ce2 - df * b; + te2[4] = -a * f; + te2[8] = de + cf * b; + te2[1] = cf + de * b; + te2[5] = a * e; + te2[9] = df - ce2 * b; + te2[2] = -a * d; + te2[6] = b; + te2[10] = a * c; + } else if (euler.order === "ZYX") { + const ae2 = a * e, af = a * f, be = b * e, bf = b * f; + te2[0] = c * e; + te2[4] = be * d - af; + te2[8] = ae2 * d + bf; + te2[1] = c * f; + te2[5] = bf * d + ae2; + te2[9] = af * d - be; + te2[2] = -d; + te2[6] = b * c; + te2[10] = a * c; + } else if (euler.order === "YZX") { + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + te2[0] = c * e; + te2[4] = bd - ac * f; + te2[8] = bc * f + ad; + te2[1] = f; + te2[5] = a * e; + te2[9] = -b * e; + te2[2] = -d * e; + te2[6] = ad * f + bc; + te2[10] = ac - bd * f; + } else if (euler.order === "XZY") { + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + te2[0] = c * e; + te2[4] = -f; + te2[8] = d * e; + te2[1] = ac * f + bd; + te2[5] = a * e; + te2[9] = ad * f - bc; + te2[2] = bc * f - ad; + te2[6] = b * e; + te2[10] = bd * f + ac; + } + te2[3] = 0; + te2[7] = 0; + te2[11] = 0; + te2[12] = 0; + te2[13] = 0; + te2[14] = 0; + te2[15] = 1; + return this; + } + makeRotationFromQuaternion(q) { + return this.compose(_zero, q, _one); + } + lookAt(eye, target, up) { + const te2 = this.elements; + _z.subVectors(eye, target); + if (_z.lengthSq() === 0) { + _z.z = 1; + } + _z.normalize(); + _x.crossVectors(up, _z); + if (_x.lengthSq() === 0) { + if (Math.abs(up.z) === 1) { + _z.x += 0.0001; + } else { + _z.z += 0.0001; + } + _z.normalize(); + _x.crossVectors(up, _z); + } + _x.normalize(); + _y.crossVectors(_z, _x); + te2[0] = _x.x; + te2[4] = _y.x; + te2[8] = _z.x; + te2[1] = _x.y; + te2[5] = _y.y; + te2[9] = _z.y; + te2[2] = _x.z; + te2[6] = _y.z; + te2[10] = _z.z; + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a, b) { + const ae2 = a.elements; + const be = b.elements; + const te2 = this.elements; + const a11 = ae2[0], a12 = ae2[4], a13 = ae2[8], a14 = ae2[12]; + const a21 = ae2[1], a22 = ae2[5], a23 = ae2[9], a24 = ae2[13]; + const a31 = ae2[2], a32 = ae2[6], a33 = ae2[10], a34 = ae2[14]; + const a41 = ae2[3], a42 = ae2[7], a43 = ae2[11], a44 = ae2[15]; + const b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; + const b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; + const b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; + const b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; + te2[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te2[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te2[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te2[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + te2[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te2[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te2[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te2[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + te2[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te2[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te2[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te2[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + te2[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te2[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te2[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te2[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + return this; + } + multiplyScalar(s) { + const te2 = this.elements; + te2[0] *= s; + te2[4] *= s; + te2[8] *= s; + te2[12] *= s; + te2[1] *= s; + te2[5] *= s; + te2[9] *= s; + te2[13] *= s; + te2[2] *= s; + te2[6] *= s; + te2[10] *= s; + te2[14] *= s; + te2[3] *= s; + te2[7] *= s; + te2[11] *= s; + te2[15] *= s; + return this; + } + determinant() { + const te2 = this.elements; + const n11 = te2[0], n12 = te2[4], n13 = te2[8], n14 = te2[12]; + const n21 = te2[1], n22 = te2[5], n23 = te2[9], n24 = te2[13]; + const n31 = te2[2], n32 = te2[6], n33 = te2[10], n34 = te2[14]; + const n41 = te2[3], n42 = te2[7], n43 = te2[11], n44 = te2[15]; + return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31); + } + transpose() { + const te2 = this.elements; + let tmp; + tmp = te2[1]; + te2[1] = te2[4]; + te2[4] = tmp; + tmp = te2[2]; + te2[2] = te2[8]; + te2[8] = tmp; + tmp = te2[6]; + te2[6] = te2[9]; + te2[9] = tmp; + tmp = te2[3]; + te2[3] = te2[12]; + te2[12] = tmp; + tmp = te2[7]; + te2[7] = te2[13]; + te2[13] = tmp; + tmp = te2[11]; + te2[11] = te2[14]; + te2[14] = tmp; + return this; + } + setPosition(x, y, z) { + const te2 = this.elements; + if (x.isVector3) { + te2[12] = x.x; + te2[13] = x.y; + te2[14] = x.z; + } else { + te2[12] = x; + te2[13] = y; + te2[14] = z; + } + return this; + } + invert() { + const te2 = this.elements, n11 = te2[0], n21 = te2[1], n31 = te2[2], n41 = te2[3], n12 = te2[4], n22 = te2[5], n32 = te2[6], n42 = te2[7], n13 = te2[8], n23 = te2[9], n33 = te2[10], n43 = te2[11], n14 = te2[12], n24 = te2[13], n34 = te2[14], n44 = te2[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + if (det === 0) + return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te2[0] = t11 * detInv; + te2[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; + te2[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; + te2[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; + te2[4] = t12 * detInv; + te2[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; + te2[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; + te2[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; + te2[8] = t13 * detInv; + te2[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; + te2[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; + te2[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; + te2[12] = t14 * detInv; + te2[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; + te2[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; + te2[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; + return this; + } + scale(v) { + const te2 = this.elements; + const { x, y, z } = v; + te2[0] *= x; + te2[4] *= y; + te2[8] *= z; + te2[1] *= x; + te2[5] *= y; + te2[9] *= z; + te2[2] *= x; + te2[6] *= y; + te2[10] *= z; + te2[3] *= x; + te2[7] *= y; + te2[11] *= z; + return this; + } + getMaxScaleOnAxis() { + const te2 = this.elements; + const scaleXSq = te2[0] * te2[0] + te2[1] * te2[1] + te2[2] * te2[2]; + const scaleYSq = te2[4] * te2[4] + te2[5] * te2[5] + te2[6] * te2[6]; + const scaleZSq = te2[8] * te2[8] + te2[9] * te2[9] + te2[10] * te2[10]; + return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); + } + makeTranslation(x, y, z) { + if (x.isVector3) { + this.set(1, 0, 0, x.x, 0, 1, 0, x.y, 0, 0, 1, x.z, 0, 0, 0, 1); + } else { + this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1); + } + return this; + } + makeRotationX(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1); + return this; + } + makeRotationY(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1); + return this; + } + makeRotationZ(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return this; + } + makeRotationAxis(axis, angle) { + const c = Math.cos(angle); + const s = Math.sin(angle); + const t = 1 - c; + const { x, y, z } = axis; + const tx = t * x, ty = t * y; + this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1); + return this; + } + makeScale(x, y, z) { + this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); + return this; + } + makeShear(xy, xz, yx, yz, zx, zy) { + this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1); + return this; + } + compose(position2, quaternion, scale2) { + const te2 = this.elements; + const { _x: x, _y: y, _z: z, _w: w } = quaternion; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; + const { x: sx, y: sy, z: sz } = scale2; + te2[0] = (1 - (yy + zz)) * sx; + te2[1] = (xy + wz) * sx; + te2[2] = (xz - wy) * sx; + te2[3] = 0; + te2[4] = (xy - wz) * sy; + te2[5] = (1 - (xx + zz)) * sy; + te2[6] = (yz + wx) * sy; + te2[7] = 0; + te2[8] = (xz + wy) * sz; + te2[9] = (yz - wx) * sz; + te2[10] = (1 - (xx + yy)) * sz; + te2[11] = 0; + te2[12] = position2.x; + te2[13] = position2.y; + te2[14] = position2.z; + te2[15] = 1; + return this; + } + decompose(position2, quaternion, scale2) { + const te2 = this.elements; + let sx = _v1$5.set(te2[0], te2[1], te2[2]).length(); + const sy = _v1$5.set(te2[4], te2[5], te2[6]).length(); + const sz = _v1$5.set(te2[8], te2[9], te2[10]).length(); + const det = this.determinant(); + if (det < 0) + sx = -sx; + position2.x = te2[12]; + position2.y = te2[13]; + position2.z = te2[14]; + _m1$2.copy(this); + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + _m1$2.elements[0] *= invSX; + _m1$2.elements[1] *= invSX; + _m1$2.elements[2] *= invSX; + _m1$2.elements[4] *= invSY; + _m1$2.elements[5] *= invSY; + _m1$2.elements[6] *= invSY; + _m1$2.elements[8] *= invSZ; + _m1$2.elements[9] *= invSZ; + _m1$2.elements[10] *= invSZ; + quaternion.setFromRotationMatrix(_m1$2); + scale2.x = sx; + scale2.y = sy; + scale2.z = sz; + return this; + } + makePerspective(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem) { + const te2 = this.elements; + const x = 2 * near / (right - left); + const y = 2 * near / (top - bottom); + const a = (right + left) / (right - left); + const b = (top + bottom) / (top - bottom); + let c, d; + if (coordinateSystem === WebGLCoordinateSystem) { + c = -(far + near) / (far - near); + d = -2 * far * near / (far - near); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + c = -far / (far - near); + d = -far * near / (far - near); + } else { + throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + coordinateSystem); + } + te2[0] = x; + te2[4] = 0; + te2[8] = a; + te2[12] = 0; + te2[1] = 0; + te2[5] = y; + te2[9] = b; + te2[13] = 0; + te2[2] = 0; + te2[6] = 0; + te2[10] = c; + te2[14] = d; + te2[3] = 0; + te2[7] = 0; + te2[11] = -1; + te2[15] = 0; + return this; + } + makeOrthographic(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem) { + const te2 = this.elements; + const w = 1 / (right - left); + const h = 1 / (top - bottom); + const p = 1 / (far - near); + const x = (right + left) * w; + const y = (top + bottom) * h; + let z, zInv; + if (coordinateSystem === WebGLCoordinateSystem) { + z = (far + near) * p; + zInv = -2 * p; + } else if (coordinateSystem === WebGPUCoordinateSystem) { + z = near * p; + zInv = -1 * p; + } else { + throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + coordinateSystem); + } + te2[0] = 2 * w; + te2[4] = 0; + te2[8] = 0; + te2[12] = -x; + te2[1] = 0; + te2[5] = 2 * h; + te2[9] = 0; + te2[13] = -y; + te2[2] = 0; + te2[6] = 0; + te2[10] = zInv; + te2[14] = -z; + te2[3] = 0; + te2[7] = 0; + te2[11] = 0; + te2[15] = 1; + return this; + } + equals(matrix) { + const te2 = this.elements; + const me = matrix.elements; + for (let i = 0;i < 16; i++) { + if (te2[i] !== me[i]) + return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 16; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te2 = this.elements; + array[offset] = te2[0]; + array[offset + 1] = te2[1]; + array[offset + 2] = te2[2]; + array[offset + 3] = te2[3]; + array[offset + 4] = te2[4]; + array[offset + 5] = te2[5]; + array[offset + 6] = te2[6]; + array[offset + 7] = te2[7]; + array[offset + 8] = te2[8]; + array[offset + 9] = te2[9]; + array[offset + 10] = te2[10]; + array[offset + 11] = te2[11]; + array[offset + 12] = te2[12]; + array[offset + 13] = te2[13]; + array[offset + 14] = te2[14]; + array[offset + 15] = te2[15]; + return array; + } +} +var _v1$5 = /* @__PURE__ */ new Vector3; +var _m1$2 = /* @__PURE__ */ new Matrix4; +var _zero = /* @__PURE__ */ new Vector3(0, 0, 0); +var _one = /* @__PURE__ */ new Vector3(1, 1, 1); +var _x = /* @__PURE__ */ new Vector3; +var _y = /* @__PURE__ */ new Vector3; +var _z = /* @__PURE__ */ new Vector3; +var _matrix$2 = /* @__PURE__ */ new Matrix4; +var _quaternion$3 = /* @__PURE__ */ new Quaternion; + +class Euler { + constructor(x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER) { + this.isEuler = true; + this._x = x; + this._y = y; + this._z = z; + this._order = order; + } + get x() { + return this._x; + } + set x(value2) { + this._x = value2; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value2) { + this._y = value2; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value2) { + this._z = value2; + this._onChangeCallback(); + } + get order() { + return this._order; + } + set order(value2) { + this._order = value2; + this._onChangeCallback(); + } + set(x, y, z, order = this._order) { + this._x = x; + this._y = y; + this._z = z; + this._order = order; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._order); + } + copy(euler) { + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m, order = this._order, update = true) { + const te2 = m.elements; + const m11 = te2[0], m12 = te2[4], m13 = te2[8]; + const m21 = te2[1], m22 = te2[5], m23 = te2[9]; + const m31 = te2[2], m32 = te2[6], m33 = te2[10]; + switch (order) { + case "XYZ": + this._y = Math.asin(clamp2(m13, -1, 1)); + if (Math.abs(m13) < 0.9999999) { + this._x = Math.atan2(-m23, m33); + this._z = Math.atan2(-m12, m11); + } else { + this._x = Math.atan2(m32, m22); + this._z = 0; + } + break; + case "YXZ": + this._x = Math.asin(-clamp2(m23, -1, 1)); + if (Math.abs(m23) < 0.9999999) { + this._y = Math.atan2(m13, m33); + this._z = Math.atan2(m21, m22); + } else { + this._y = Math.atan2(-m31, m11); + this._z = 0; + } + break; + case "ZXY": + this._x = Math.asin(clamp2(m32, -1, 1)); + if (Math.abs(m32) < 0.9999999) { + this._y = Math.atan2(-m31, m33); + this._z = Math.atan2(-m12, m22); + } else { + this._y = 0; + this._z = Math.atan2(m21, m11); + } + break; + case "ZYX": + this._y = Math.asin(-clamp2(m31, -1, 1)); + if (Math.abs(m31) < 0.9999999) { + this._x = Math.atan2(m32, m33); + this._z = Math.atan2(m21, m11); + } else { + this._x = 0; + this._z = Math.atan2(-m12, m22); + } + break; + case "YZX": + this._z = Math.asin(clamp2(m21, -1, 1)); + if (Math.abs(m21) < 0.9999999) { + this._x = Math.atan2(-m23, m22); + this._y = Math.atan2(-m31, m11); + } else { + this._x = 0; + this._y = Math.atan2(m13, m33); + } + break; + case "XZY": + this._z = Math.asin(-clamp2(m12, -1, 1)); + if (Math.abs(m12) < 0.9999999) { + this._x = Math.atan2(m32, m22); + this._y = Math.atan2(m13, m11); + } else { + this._x = Math.atan2(-m23, m33); + this._y = 0; + } + break; + default: + console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + order); + } + this._order = order; + if (update === true) + this._onChangeCallback(); + return this; + } + setFromQuaternion(q, order, update) { + _matrix$2.makeRotationFromQuaternion(q); + return this.setFromRotationMatrix(_matrix$2, order, update); + } + setFromVector3(v, order = this._order) { + return this.set(v.x, v.y, v.z, order); + } + reorder(newOrder) { + _quaternion$3.setFromEuler(this); + return this.setFromQuaternion(_quaternion$3, newOrder); + } + equals(euler) { + return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order; + } + fromArray(array) { + this._x = array[0]; + this._y = array[1]; + this._z = array[2]; + if (array[3] !== undefined) + this._order = array[3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._order; + return array; + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._order; + } +} +Euler.DEFAULT_ORDER = "XYZ"; + +class Layers { + constructor() { + this.mask = 1 | 0; + } + set(channel) { + this.mask = (1 << channel | 0) >>> 0; + } + enable(channel) { + this.mask |= 1 << channel | 0; + } + enableAll() { + this.mask = 4294967295 | 0; + } + toggle(channel) { + this.mask ^= 1 << channel | 0; + } + disable(channel) { + this.mask &= ~(1 << channel | 0); + } + disableAll() { + this.mask = 0; + } + test(layers) { + return (this.mask & layers.mask) !== 0; + } + isEnabled(channel) { + return (this.mask & (1 << channel | 0)) !== 0; + } +} +var _object3DId = 0; +var _v1$4 = /* @__PURE__ */ new Vector3; +var _q1 = /* @__PURE__ */ new Quaternion; +var _m1$1 = /* @__PURE__ */ new Matrix4; +var _target = /* @__PURE__ */ new Vector3; +var _position$3 = /* @__PURE__ */ new Vector3; +var _scale$2 = /* @__PURE__ */ new Vector3; +var _quaternion$2 = /* @__PURE__ */ new Quaternion; +var _xAxis = /* @__PURE__ */ new Vector3(1, 0, 0); +var _yAxis = /* @__PURE__ */ new Vector3(0, 1, 0); +var _zAxis = /* @__PURE__ */ new Vector3(0, 0, 1); +var _addedEvent = { type: "added" }; +var _removedEvent = { type: "removed" }; +var _childaddedEvent = { type: "childadded", child: null }; +var _childremovedEvent = { type: "childremoved", child: null }; + +class Object3D extends EventDispatcher { + constructor() { + super(); + this.isObject3D = true; + Object.defineProperty(this, "id", { value: _object3DId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "Object3D"; + this.parent = null; + this.children = []; + this.up = Object3D.DEFAULT_UP.clone(); + const position2 = new Vector3; + const rotation2 = new Euler; + const quaternion = new Quaternion; + const scale2 = new Vector3(1, 1, 1); + function onRotationChange() { + quaternion.setFromEuler(rotation2, false); + } + function onQuaternionChange() { + rotation2.setFromQuaternion(quaternion, undefined, false); + } + rotation2._onChange(onRotationChange); + quaternion._onChange(onQuaternionChange); + Object.defineProperties(this, { + position: { + configurable: true, + enumerable: true, + value: position2 + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation2 + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale2 + }, + modelViewMatrix: { + value: new Matrix4 + }, + normalMatrix: { + value: new Matrix3 + } + }); + this.matrix = new Matrix4; + this.matrixWorld = new Matrix4; + this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + this.layers = new Layers; + this.visible = true; + this.castShadow = false; + this.receiveShadow = false; + this.frustumCulled = true; + this.renderOrder = 0; + this.animations = []; + this.userData = {}; + } + onBeforeShadow() { + } + onAfterShadow() { + } + onBeforeRender() { + } + onAfterRender() { + } + applyMatrix4(matrix) { + if (this.matrixAutoUpdate) + this.updateMatrix(); + this.matrix.premultiply(matrix); + this.matrix.decompose(this.position, this.quaternion, this.scale); + } + applyQuaternion(q) { + this.quaternion.premultiply(q); + return this; + } + setRotationFromAxisAngle(axis, angle) { + this.quaternion.setFromAxisAngle(axis, angle); + } + setRotationFromEuler(euler) { + this.quaternion.setFromEuler(euler, true); + } + setRotationFromMatrix(m) { + this.quaternion.setFromRotationMatrix(m); + } + setRotationFromQuaternion(q) { + this.quaternion.copy(q); + } + rotateOnAxis(axis, angle) { + _q1.setFromAxisAngle(axis, angle); + this.quaternion.multiply(_q1); + return this; + } + rotateOnWorldAxis(axis, angle) { + _q1.setFromAxisAngle(axis, angle); + this.quaternion.premultiply(_q1); + return this; + } + rotateX(angle) { + return this.rotateOnAxis(_xAxis, angle); + } + rotateY(angle) { + return this.rotateOnAxis(_yAxis, angle); + } + rotateZ(angle) { + return this.rotateOnAxis(_zAxis, angle); + } + translateOnAxis(axis, distance) { + _v1$4.copy(axis).applyQuaternion(this.quaternion); + this.position.add(_v1$4.multiplyScalar(distance)); + return this; + } + translateX(distance) { + return this.translateOnAxis(_xAxis, distance); + } + translateY(distance) { + return this.translateOnAxis(_yAxis, distance); + } + translateZ(distance) { + return this.translateOnAxis(_zAxis, distance); + } + localToWorld(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(this.matrixWorld); + } + worldToLocal(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert()); + } + lookAt(x, y, z) { + if (x.isVector3) { + _target.copy(x); + } else { + _target.set(x, y, z); + } + const parent2 = this.parent; + this.updateWorldMatrix(true, false); + _position$3.setFromMatrixPosition(this.matrixWorld); + if (this.isCamera || this.isLight) { + _m1$1.lookAt(_position$3, _target, this.up); + } else { + _m1$1.lookAt(_target, _position$3, this.up); + } + this.quaternion.setFromRotationMatrix(_m1$1); + if (parent2) { + _m1$1.extractRotation(parent2.matrixWorld); + _q1.setFromRotationMatrix(_m1$1); + this.quaternion.premultiply(_q1.invert()); + } + } + add(object) { + if (arguments.length > 1) { + for (let i = 0;i < arguments.length; i++) { + this.add(arguments[i]); + } + return this; + } + if (object === this) { + console.error("THREE.Object3D.add: object can't be added as a child of itself.", object); + return this; + } + if (object && object.isObject3D) { + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.dispatchEvent(_addedEvent); + _childaddedEvent.child = object; + this.dispatchEvent(_childaddedEvent); + _childaddedEvent.child = null; + } else { + console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object); + } + return this; + } + remove(object) { + if (arguments.length > 1) { + for (let i = 0;i < arguments.length; i++) { + this.remove(arguments[i]); + } + return this; + } + const index2 = this.children.indexOf(object); + if (index2 !== -1) { + object.parent = null; + this.children.splice(index2, 1); + object.dispatchEvent(_removedEvent); + _childremovedEvent.child = object; + this.dispatchEvent(_childremovedEvent); + _childremovedEvent.child = null; + } + return this; + } + removeFromParent() { + const parent2 = this.parent; + if (parent2 !== null) { + parent2.remove(this); + } + return this; + } + clear() { + return this.remove(...this.children); + } + attach(object) { + this.updateWorldMatrix(true, false); + _m1$1.copy(this.matrixWorld).invert(); + if (object.parent !== null) { + object.parent.updateWorldMatrix(true, false); + _m1$1.multiply(object.parent.matrixWorld); + } + object.applyMatrix4(_m1$1); + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.updateWorldMatrix(false, true); + object.dispatchEvent(_addedEvent); + _childaddedEvent.child = object; + this.dispatchEvent(_childaddedEvent); + _childaddedEvent.child = null; + return this; + } + getObjectById(id) { + return this.getObjectByProperty("id", id); + } + getObjectByName(name2) { + return this.getObjectByProperty("name", name2); + } + getObjectByProperty(name2, value2) { + if (this[name2] === value2) + return this; + for (let i = 0, l = this.children.length;i < l; i++) { + const child = this.children[i]; + const object = child.getObjectByProperty(name2, value2); + if (object !== undefined) { + return object; + } + } + return; + } + getObjectsByProperty(name2, value2, result = []) { + if (this[name2] === value2) + result.push(this); + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + children[i].getObjectsByProperty(name2, value2, result); + } + return result; + } + getWorldPosition(target) { + this.updateWorldMatrix(true, false); + return target.setFromMatrixPosition(this.matrixWorld); + } + getWorldQuaternion(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$3, target, _scale$2); + return target; + } + getWorldScale(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$3, _quaternion$2, target); + return target; + } + getWorldDirection(target) { + this.updateWorldMatrix(true, false); + const e = this.matrixWorld.elements; + return target.set(e[8], e[9], e[10]).normalize(); + } + raycast() { + } + traverse(callback) { + callback(this); + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + children[i].traverse(callback); + } + } + traverseVisible(callback) { + if (this.visible === false) + return; + callback(this); + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + children[i].traverseVisible(callback); + } + } + traverseAncestors(callback) { + const parent2 = this.parent; + if (parent2 !== null) { + callback(parent2); + parent2.traverseAncestors(callback); + } + } + updateMatrix() { + this.matrix.compose(this.position, this.quaternion, this.scale); + this.matrixWorldNeedsUpdate = true; + } + updateMatrixWorld(force) { + if (this.matrixAutoUpdate) + this.updateMatrix(); + if (this.matrixWorldNeedsUpdate || force) { + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + this.matrixWorldNeedsUpdate = false; + force = true; + } + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + const child = children[i]; + child.updateMatrixWorld(force); + } + } + updateWorldMatrix(updateParents, updateChildren) { + const parent2 = this.parent; + if (updateParents === true && parent2 !== null) { + parent2.updateWorldMatrix(true, false); + } + if (this.matrixAutoUpdate) + this.updateMatrix(); + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + if (updateChildren === true) { + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + const child = children[i]; + child.updateWorldMatrix(false, true); + } + } + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + const output = {}; + if (isRootObject) { + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + output.metadata = { + version: 4.6, + type: "Object", + generator: "Object3D.toJSON" + }; + } + const object = {}; + object.uuid = this.uuid; + object.type = this.type; + if (this.name !== "") + object.name = this.name; + if (this.castShadow === true) + object.castShadow = true; + if (this.receiveShadow === true) + object.receiveShadow = true; + if (this.visible === false) + object.visible = false; + if (this.frustumCulled === false) + object.frustumCulled = false; + if (this.renderOrder !== 0) + object.renderOrder = this.renderOrder; + if (Object.keys(this.userData).length > 0) + object.userData = this.userData; + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + object.up = this.up.toArray(); + if (this.matrixAutoUpdate === false) + object.matrixAutoUpdate = false; + if (this.isInstancedMesh) { + object.type = "InstancedMesh"; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if (this.instanceColor !== null) + object.instanceColor = this.instanceColor.toJSON(); + } + if (this.isBatchedMesh) { + object.type = "BatchedMesh"; + object.perObjectFrustumCulled = this.perObjectFrustumCulled; + object.sortObjects = this.sortObjects; + object.drawRanges = this._drawRanges; + object.reservedRanges = this._reservedRanges; + object.visibility = this._visibility; + object.active = this._active; + object.bounds = this._bounds.map((bound) => ({ + boxInitialized: bound.boxInitialized, + boxMin: bound.box.min.toArray(), + boxMax: bound.box.max.toArray(), + sphereInitialized: bound.sphereInitialized, + sphereRadius: bound.sphere.radius, + sphereCenter: bound.sphere.center.toArray() + })); + object.maxInstanceCount = this._maxInstanceCount; + object.maxVertexCount = this._maxVertexCount; + object.maxIndexCount = this._maxIndexCount; + object.geometryInitialized = this._geometryInitialized; + object.geometryCount = this._geometryCount; + object.matricesTexture = this._matricesTexture.toJSON(meta); + if (this._colorsTexture !== null) + object.colorsTexture = this._colorsTexture.toJSON(meta); + if (this.boundingSphere !== null) { + object.boundingSphere = { + center: object.boundingSphere.center.toArray(), + radius: object.boundingSphere.radius + }; + } + if (this.boundingBox !== null) { + object.boundingBox = { + min: object.boundingBox.min.toArray(), + max: object.boundingBox.max.toArray() + }; + } + } + function serialize(library, element) { + if (library[element.uuid] === undefined) { + library[element.uuid] = element.toJSON(meta); + } + return element.uuid; + } + if (this.isScene) { + if (this.background) { + if (this.background.isColor) { + object.background = this.background.toJSON(); + } else if (this.background.isTexture) { + object.background = this.background.toJSON(meta).uuid; + } + } + if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) { + object.environment = this.environment.toJSON(meta).uuid; + } + } else if (this.isMesh || this.isLine || this.isPoints) { + object.geometry = serialize(meta.geometries, this.geometry); + const parameters = this.geometry.parameters; + if (parameters !== undefined && parameters.shapes !== undefined) { + const shapes = parameters.shapes; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + serialize(meta.shapes, shape); + } + } else { + serialize(meta.shapes, shapes); + } + } + } + if (this.isSkinnedMesh) { + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + if (this.skeleton !== undefined) { + serialize(meta.skeletons, this.skeleton); + object.skeleton = this.skeleton.uuid; + } + } + if (this.material !== undefined) { + if (Array.isArray(this.material)) { + const uuids = []; + for (let i = 0, l = this.material.length;i < l; i++) { + uuids.push(serialize(meta.materials, this.material[i])); + } + object.material = uuids; + } else { + object.material = serialize(meta.materials, this.material); + } + } + if (this.children.length > 0) { + object.children = []; + for (let i = 0;i < this.children.length; i++) { + object.children.push(this.children[i].toJSON(meta).object); + } + } + if (this.animations.length > 0) { + object.animations = []; + for (let i = 0;i < this.animations.length; i++) { + const animation = this.animations[i]; + object.animations.push(serialize(meta.animations, animation)); + } + } + if (isRootObject) { + const geometries = extractFromCache(meta.geometries); + const materials = extractFromCache(meta.materials); + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + const shapes = extractFromCache(meta.shapes); + const skeletons = extractFromCache(meta.skeletons); + const animations = extractFromCache(meta.animations); + const nodes = extractFromCache(meta.nodes); + if (geometries.length > 0) + output.geometries = geometries; + if (materials.length > 0) + output.materials = materials; + if (textures.length > 0) + output.textures = textures; + if (images.length > 0) + output.images = images; + if (shapes.length > 0) + output.shapes = shapes; + if (skeletons.length > 0) + output.skeletons = skeletons; + if (animations.length > 0) + output.animations = animations; + if (nodes.length > 0) + output.nodes = nodes; + } + output.object = object; + return output; + function extractFromCache(cache) { + const values2 = []; + for (const key2 in cache) { + const data2 = cache[key2]; + delete data2.metadata; + values2.push(data2); + } + return values2; + } + } + clone(recursive) { + return new this.constructor().copy(this, recursive); + } + copy(source, recursive = true) { + this.name = source.name; + this.up.copy(source.up); + this.position.copy(source.position); + this.rotation.order = source.rotation.order; + this.quaternion.copy(source.quaternion); + this.scale.copy(source.scale); + this.matrix.copy(source.matrix); + this.matrixWorld.copy(source.matrixWorld); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + this.layers.mask = source.layers.mask; + this.visible = source.visible; + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + this.animations = source.animations.slice(); + this.userData = JSON.parse(JSON.stringify(source.userData)); + if (recursive === true) { + for (let i = 0;i < source.children.length; i++) { + const child = source.children[i]; + this.add(child.clone()); + } + } + return this; + } +} +Object3D.DEFAULT_UP = /* @__PURE__ */ new Vector3(0, 1, 0); +Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true; +Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; +var _v0$1 = /* @__PURE__ */ new Vector3; +var _v1$3 = /* @__PURE__ */ new Vector3; +var _v2$2 = /* @__PURE__ */ new Vector3; +var _v3$2 = /* @__PURE__ */ new Vector3; +var _vab = /* @__PURE__ */ new Vector3; +var _vac = /* @__PURE__ */ new Vector3; +var _vbc = /* @__PURE__ */ new Vector3; +var _vap = /* @__PURE__ */ new Vector3; +var _vbp = /* @__PURE__ */ new Vector3; +var _vcp = /* @__PURE__ */ new Vector3; +var _v40 = /* @__PURE__ */ new Vector4; +var _v41 = /* @__PURE__ */ new Vector4; +var _v42 = /* @__PURE__ */ new Vector4; + +class Triangle { + constructor(a = new Vector3, b = new Vector3, c = new Vector3) { + this.a = a; + this.b = b; + this.c = c; + } + static getNormal(a, b, c, target) { + target.subVectors(c, b); + _v0$1.subVectors(a, b); + target.cross(_v0$1); + const targetLengthSq = target.lengthSq(); + if (targetLengthSq > 0) { + return target.multiplyScalar(1 / Math.sqrt(targetLengthSq)); + } + return target.set(0, 0, 0); + } + static getBarycoord(point, a, b, c, target) { + _v0$1.subVectors(c, a); + _v1$3.subVectors(b, a); + _v2$2.subVectors(point, a); + const dot00 = _v0$1.dot(_v0$1); + const dot01 = _v0$1.dot(_v1$3); + const dot02 = _v0$1.dot(_v2$2); + const dot11 = _v1$3.dot(_v1$3); + const dot12 = _v1$3.dot(_v2$2); + const denom = dot00 * dot11 - dot01 * dot01; + if (denom === 0) { + target.set(0, 0, 0); + return null; + } + const invDenom = 1 / denom; + const u = (dot11 * dot02 - dot01 * dot12) * invDenom; + const v = (dot00 * dot12 - dot01 * dot02) * invDenom; + return target.set(1 - u - v, v, u); + } + static containsPoint(point, a, b, c) { + if (this.getBarycoord(point, a, b, c, _v3$2) === null) { + return false; + } + return _v3$2.x >= 0 && _v3$2.y >= 0 && _v3$2.x + _v3$2.y <= 1; + } + static getInterpolation(point, p1, p2, p3, v1, v2, v3, target) { + if (this.getBarycoord(point, p1, p2, p3, _v3$2) === null) { + target.x = 0; + target.y = 0; + if ("z" in target) + target.z = 0; + if ("w" in target) + target.w = 0; + return null; + } + target.setScalar(0); + target.addScaledVector(v1, _v3$2.x); + target.addScaledVector(v2, _v3$2.y); + target.addScaledVector(v3, _v3$2.z); + return target; + } + static getInterpolatedAttribute(attr, i1, i2, i3, barycoord, target) { + _v40.setScalar(0); + _v41.setScalar(0); + _v42.setScalar(0); + _v40.fromBufferAttribute(attr, i1); + _v41.fromBufferAttribute(attr, i2); + _v42.fromBufferAttribute(attr, i3); + target.setScalar(0); + target.addScaledVector(_v40, barycoord.x); + target.addScaledVector(_v41, barycoord.y); + target.addScaledVector(_v42, barycoord.z); + return target; + } + static isFrontFacing(a, b, c, direction) { + _v0$1.subVectors(c, b); + _v1$3.subVectors(a, b); + return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false; + } + set(a, b, c) { + this.a.copy(a); + this.b.copy(b); + this.c.copy(c); + return this; + } + setFromPointsAndIndices(points, i0, i1, i2) { + this.a.copy(points[i0]); + this.b.copy(points[i1]); + this.c.copy(points[i2]); + return this; + } + setFromAttributeAndIndices(attribute, i0, i1, i2) { + this.a.fromBufferAttribute(attribute, i0); + this.b.fromBufferAttribute(attribute, i1); + this.c.fromBufferAttribute(attribute, i2); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(triangle) { + this.a.copy(triangle.a); + this.b.copy(triangle.b); + this.c.copy(triangle.c); + return this; + } + getArea() { + _v0$1.subVectors(this.c, this.b); + _v1$3.subVectors(this.a, this.b); + return _v0$1.cross(_v1$3).length() * 0.5; + } + getMidpoint(target) { + return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); + } + getNormal(target) { + return Triangle.getNormal(this.a, this.b, this.c, target); + } + getPlane(target) { + return target.setFromCoplanarPoints(this.a, this.b, this.c); + } + getBarycoord(point, target) { + return Triangle.getBarycoord(point, this.a, this.b, this.c, target); + } + getInterpolation(point, v1, v2, v3, target) { + return Triangle.getInterpolation(point, this.a, this.b, this.c, v1, v2, v3, target); + } + containsPoint(point) { + return Triangle.containsPoint(point, this.a, this.b, this.c); + } + isFrontFacing(direction) { + return Triangle.isFrontFacing(this.a, this.b, this.c, direction); + } + intersectsBox(box) { + return box.intersectsTriangle(this); + } + closestPointToPoint(p, target) { + const a = this.a, b = this.b, c = this.c; + let v, w; + _vab.subVectors(b, a); + _vac.subVectors(c, a); + _vap.subVectors(p, a); + const d1 = _vab.dot(_vap); + const d2 = _vac.dot(_vap); + if (d1 <= 0 && d2 <= 0) { + return target.copy(a); + } + _vbp.subVectors(p, b); + const d3 = _vab.dot(_vbp); + const d4 = _vac.dot(_vbp); + if (d3 >= 0 && d4 <= d3) { + return target.copy(b); + } + const vc = d1 * d4 - d3 * d2; + if (vc <= 0 && d1 >= 0 && d3 <= 0) { + v = d1 / (d1 - d3); + return target.copy(a).addScaledVector(_vab, v); + } + _vcp.subVectors(p, c); + const d5 = _vab.dot(_vcp); + const d6 = _vac.dot(_vcp); + if (d6 >= 0 && d5 <= d6) { + return target.copy(c); + } + const vb = d5 * d2 - d1 * d6; + if (vb <= 0 && d2 >= 0 && d6 <= 0) { + w = d2 / (d2 - d6); + return target.copy(a).addScaledVector(_vac, w); + } + const va = d3 * d6 - d5 * d4; + if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { + _vbc.subVectors(c, b); + w = (d4 - d3) / (d4 - d3 + (d5 - d6)); + return target.copy(b).addScaledVector(_vbc, w); + } + const denom = 1 / (va + vb + vc); + v = vb * denom; + w = vc * denom; + return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w); + } + equals(triangle) { + return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c); + } +} +var _colorKeywords = { + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + rebeccapurple: 6697881, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 +}; +var _hslA = { h: 0, s: 0, l: 0 }; +var _hslB = { h: 0, s: 0, l: 0 }; +function hue2rgb2(p, q, t) { + if (t < 0) + t += 1; + if (t > 1) + t -= 1; + if (t < 1 / 6) + return p + (q - p) * 6 * t; + if (t < 1 / 2) + return q; + if (t < 2 / 3) + return p + (q - p) * 6 * (2 / 3 - t); + return p; +} + +class Color { + constructor(r, g, b) { + this.isColor = true; + this.r = 1; + this.g = 1; + this.b = 1; + return this.set(r, g, b); + } + set(r, g, b) { + if (g === undefined && b === undefined) { + const value2 = r; + if (value2 && value2.isColor) { + this.copy(value2); + } else if (typeof value2 === "number") { + this.setHex(value2); + } else if (typeof value2 === "string") { + this.setStyle(value2); + } + } else { + this.setRGB(r, g, b); + } + return this; + } + setScalar(scalar) { + this.r = scalar; + this.g = scalar; + this.b = scalar; + return this; + } + setHex(hex, colorSpace = SRGBColorSpace) { + hex = Math.floor(hex); + this.r = (hex >> 16 & 255) / 255; + this.g = (hex >> 8 & 255) / 255; + this.b = (hex & 255) / 255; + ColorManagement.toWorkingColorSpace(this, colorSpace); + return this; + } + setRGB(r, g, b, colorSpace = ColorManagement.workingColorSpace) { + this.r = r; + this.g = g; + this.b = b; + ColorManagement.toWorkingColorSpace(this, colorSpace); + return this; + } + setHSL(h, s, l, colorSpace = ColorManagement.workingColorSpace) { + h = euclideanModulo(h, 1); + s = clamp2(s, 0, 1); + l = clamp2(l, 0, 1); + if (s === 0) { + this.r = this.g = this.b = l; + } else { + const p = l <= 0.5 ? l * (1 + s) : l + s - l * s; + const q = 2 * l - p; + this.r = hue2rgb2(q, p, h + 1 / 3); + this.g = hue2rgb2(q, p, h); + this.b = hue2rgb2(q, p, h - 1 / 3); + } + ColorManagement.toWorkingColorSpace(this, colorSpace); + return this; + } + setStyle(style, colorSpace = SRGBColorSpace) { + function handleAlpha(string) { + if (string === undefined) + return; + if (parseFloat(string) < 1) { + console.warn("THREE.Color: Alpha component of " + style + " will be ignored."); + } + } + let m; + if (m = /^(\w+)\(([^\)]*)\)/.exec(style)) { + let color; + const name2 = m[1]; + const components = m[2]; + switch (name2) { + case "rgb": + case "rgba": + if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB(Math.min(255, parseInt(color[1], 10)) / 255, Math.min(255, parseInt(color[2], 10)) / 255, Math.min(255, parseInt(color[3], 10)) / 255, colorSpace); + } + if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB(Math.min(100, parseInt(color[1], 10)) / 100, Math.min(100, parseInt(color[2], 10)) / 100, Math.min(100, parseInt(color[3], 10)) / 100, colorSpace); + } + break; + case "hsl": + case "hsla": + if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setHSL(parseFloat(color[1]) / 360, parseFloat(color[2]) / 100, parseFloat(color[3]) / 100, colorSpace); + } + break; + default: + console.warn("THREE.Color: Unknown color model " + style); + } + } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) { + const hex = m[1]; + const size = hex.length; + if (size === 3) { + return this.setRGB(parseInt(hex.charAt(0), 16) / 15, parseInt(hex.charAt(1), 16) / 15, parseInt(hex.charAt(2), 16) / 15, colorSpace); + } else if (size === 6) { + return this.setHex(parseInt(hex, 16), colorSpace); + } else { + console.warn("THREE.Color: Invalid hex color " + style); + } + } else if (style && style.length > 0) { + return this.setColorName(style, colorSpace); + } + return this; + } + setColorName(style, colorSpace = SRGBColorSpace) { + const hex = _colorKeywords[style.toLowerCase()]; + if (hex !== undefined) { + this.setHex(hex, colorSpace); + } else { + console.warn("THREE.Color: Unknown color " + style); + } + return this; + } + clone() { + return new this.constructor(this.r, this.g, this.b); + } + copy(color) { + this.r = color.r; + this.g = color.g; + this.b = color.b; + return this; + } + copySRGBToLinear(color) { + this.r = SRGBToLinear(color.r); + this.g = SRGBToLinear(color.g); + this.b = SRGBToLinear(color.b); + return this; + } + copyLinearToSRGB(color) { + this.r = LinearToSRGB(color.r); + this.g = LinearToSRGB(color.g); + this.b = LinearToSRGB(color.b); + return this; + } + convertSRGBToLinear() { + this.copySRGBToLinear(this); + return this; + } + convertLinearToSRGB() { + this.copyLinearToSRGB(this); + return this; + } + getHex(colorSpace = SRGBColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + return Math.round(clamp2(_color.r * 255, 0, 255)) * 65536 + Math.round(clamp2(_color.g * 255, 0, 255)) * 256 + Math.round(clamp2(_color.b * 255, 0, 255)); + } + getHexString(colorSpace = SRGBColorSpace) { + return ("000000" + this.getHex(colorSpace).toString(16)).slice(-6); + } + getHSL(target, colorSpace = ColorManagement.workingColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + const { r, g, b } = _color; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + let hue, saturation; + const lightness = (min + max) / 2; + if (min === max) { + hue = 0; + saturation = 0; + } else { + const delta = max - min; + saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min); + switch (max) { + case r: + hue = (g - b) / delta + (g < b ? 6 : 0); + break; + case g: + hue = (b - r) / delta + 2; + break; + case b: + hue = (r - g) / delta + 4; + break; + } + hue /= 6; + } + target.h = hue; + target.s = saturation; + target.l = lightness; + return target; + } + getRGB(target, colorSpace = ColorManagement.workingColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + target.r = _color.r; + target.g = _color.g; + target.b = _color.b; + return target; + } + getStyle(colorSpace = SRGBColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + const { r, g, b } = _color; + if (colorSpace !== SRGBColorSpace) { + return `color(${colorSpace} ${r.toFixed(3)} ${g.toFixed(3)} ${b.toFixed(3)})`; + } + return `rgb(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)})`; + } + offsetHSL(h, s, l) { + this.getHSL(_hslA); + return this.setHSL(_hslA.h + h, _hslA.s + s, _hslA.l + l); + } + add(color) { + this.r += color.r; + this.g += color.g; + this.b += color.b; + return this; + } + addColors(color1, color2) { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + return this; + } + addScalar(s) { + this.r += s; + this.g += s; + this.b += s; + return this; + } + sub(color) { + this.r = Math.max(0, this.r - color.r); + this.g = Math.max(0, this.g - color.g); + this.b = Math.max(0, this.b - color.b); + return this; + } + multiply(color) { + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + return this; + } + multiplyScalar(s) { + this.r *= s; + this.g *= s; + this.b *= s; + return this; + } + lerp(color, alpha) { + this.r += (color.r - this.r) * alpha; + this.g += (color.g - this.g) * alpha; + this.b += (color.b - this.b) * alpha; + return this; + } + lerpColors(color1, color2, alpha) { + this.r = color1.r + (color2.r - color1.r) * alpha; + this.g = color1.g + (color2.g - color1.g) * alpha; + this.b = color1.b + (color2.b - color1.b) * alpha; + return this; + } + lerpHSL(color, alpha) { + this.getHSL(_hslA); + color.getHSL(_hslB); + const h = lerp(_hslA.h, _hslB.h, alpha); + const s = lerp(_hslA.s, _hslB.s, alpha); + const l = lerp(_hslA.l, _hslB.l, alpha); + this.setHSL(h, s, l); + return this; + } + setFromVector3(v) { + this.r = v.x; + this.g = v.y; + this.b = v.z; + return this; + } + applyMatrix3(m) { + const r = this.r, g = this.g, b = this.b; + const e = m.elements; + this.r = e[0] * r + e[3] * g + e[6] * b; + this.g = e[1] * r + e[4] * g + e[7] * b; + this.b = e[2] * r + e[5] * g + e[8] * b; + return this; + } + equals(c) { + return c.r === this.r && c.g === this.g && c.b === this.b; + } + fromArray(array, offset = 0) { + this.r = array[offset]; + this.g = array[offset + 1]; + this.b = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.r; + array[offset + 1] = this.g; + array[offset + 2] = this.b; + return array; + } + fromBufferAttribute(attribute, index2) { + this.r = attribute.getX(index2); + this.g = attribute.getY(index2); + this.b = attribute.getZ(index2); + return this; + } + toJSON() { + return this.getHex(); + } + *[Symbol.iterator]() { + yield this.r; + yield this.g; + yield this.b; + } +} +var _color = /* @__PURE__ */ new Color; +Color.NAMES = _colorKeywords; +var _materialId = 0; + +class Material extends EventDispatcher { + constructor() { + super(); + this.isMaterial = true; + Object.defineProperty(this, "id", { value: _materialId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "Material"; + this.blending = NormalBlending; + this.side = FrontSide; + this.vertexColors = false; + this.opacity = 1; + this.transparent = false; + this.alphaHash = false; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; + this.blendColor = new Color(0, 0, 0); + this.blendAlpha = 0; + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; + this.stencilWriteMask = 255; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 255; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + this.shadowSide = null; + this.colorWrite = true; + this.precision = null; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + this.dithering = false; + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + this.forceSinglePass = false; + this.visible = true; + this.toneMapped = true; + this.userData = {}; + this.version = 0; + this._alphaTest = 0; + } + get alphaTest() { + return this._alphaTest; + } + set alphaTest(value2) { + if (this._alphaTest > 0 !== value2 > 0) { + this.version++; + } + this._alphaTest = value2; + } + onBeforeRender() { + } + onBeforeCompile() { + } + customProgramCacheKey() { + return this.onBeforeCompile.toString(); + } + setValues(values2) { + if (values2 === undefined) + return; + for (const key2 in values2) { + const newValue = values2[key2]; + if (newValue === undefined) { + console.warn(`THREE.Material: parameter '${key2}' has value of undefined.`); + continue; + } + const currentValue = this[key2]; + if (currentValue === undefined) { + console.warn(`THREE.Material: '${key2}' is not a property of THREE.${this.type}.`); + continue; + } + if (currentValue && currentValue.isColor) { + currentValue.set(newValue); + } else if (currentValue && currentValue.isVector3 && (newValue && newValue.isVector3)) { + currentValue.copy(newValue); + } else { + this[key2] = newValue; + } + } + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + if (isRootObject) { + meta = { + textures: {}, + images: {} + }; + } + const data2 = { + metadata: { + version: 4.6, + type: "Material", + generator: "Material.toJSON" + } + }; + data2.uuid = this.uuid; + data2.type = this.type; + if (this.name !== "") + data2.name = this.name; + if (this.color && this.color.isColor) + data2.color = this.color.getHex(); + if (this.roughness !== undefined) + data2.roughness = this.roughness; + if (this.metalness !== undefined) + data2.metalness = this.metalness; + if (this.sheen !== undefined) + data2.sheen = this.sheen; + if (this.sheenColor && this.sheenColor.isColor) + data2.sheenColor = this.sheenColor.getHex(); + if (this.sheenRoughness !== undefined) + data2.sheenRoughness = this.sheenRoughness; + if (this.emissive && this.emissive.isColor) + data2.emissive = this.emissive.getHex(); + if (this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1) + data2.emissiveIntensity = this.emissiveIntensity; + if (this.specular && this.specular.isColor) + data2.specular = this.specular.getHex(); + if (this.specularIntensity !== undefined) + data2.specularIntensity = this.specularIntensity; + if (this.specularColor && this.specularColor.isColor) + data2.specularColor = this.specularColor.getHex(); + if (this.shininess !== undefined) + data2.shininess = this.shininess; + if (this.clearcoat !== undefined) + data2.clearcoat = this.clearcoat; + if (this.clearcoatRoughness !== undefined) + data2.clearcoatRoughness = this.clearcoatRoughness; + if (this.clearcoatMap && this.clearcoatMap.isTexture) { + data2.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid; + } + if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) { + data2.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid; + } + if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) { + data2.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid; + data2.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + } + if (this.dispersion !== undefined) + data2.dispersion = this.dispersion; + if (this.iridescence !== undefined) + data2.iridescence = this.iridescence; + if (this.iridescenceIOR !== undefined) + data2.iridescenceIOR = this.iridescenceIOR; + if (this.iridescenceThicknessRange !== undefined) + data2.iridescenceThicknessRange = this.iridescenceThicknessRange; + if (this.iridescenceMap && this.iridescenceMap.isTexture) { + data2.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid; + } + if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) { + data2.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid; + } + if (this.anisotropy !== undefined) + data2.anisotropy = this.anisotropy; + if (this.anisotropyRotation !== undefined) + data2.anisotropyRotation = this.anisotropyRotation; + if (this.anisotropyMap && this.anisotropyMap.isTexture) { + data2.anisotropyMap = this.anisotropyMap.toJSON(meta).uuid; + } + if (this.map && this.map.isTexture) + data2.map = this.map.toJSON(meta).uuid; + if (this.matcap && this.matcap.isTexture) + data2.matcap = this.matcap.toJSON(meta).uuid; + if (this.alphaMap && this.alphaMap.isTexture) + data2.alphaMap = this.alphaMap.toJSON(meta).uuid; + if (this.lightMap && this.lightMap.isTexture) { + data2.lightMap = this.lightMap.toJSON(meta).uuid; + data2.lightMapIntensity = this.lightMapIntensity; + } + if (this.aoMap && this.aoMap.isTexture) { + data2.aoMap = this.aoMap.toJSON(meta).uuid; + data2.aoMapIntensity = this.aoMapIntensity; + } + if (this.bumpMap && this.bumpMap.isTexture) { + data2.bumpMap = this.bumpMap.toJSON(meta).uuid; + data2.bumpScale = this.bumpScale; + } + if (this.normalMap && this.normalMap.isTexture) { + data2.normalMap = this.normalMap.toJSON(meta).uuid; + data2.normalMapType = this.normalMapType; + data2.normalScale = this.normalScale.toArray(); + } + if (this.displacementMap && this.displacementMap.isTexture) { + data2.displacementMap = this.displacementMap.toJSON(meta).uuid; + data2.displacementScale = this.displacementScale; + data2.displacementBias = this.displacementBias; + } + if (this.roughnessMap && this.roughnessMap.isTexture) + data2.roughnessMap = this.roughnessMap.toJSON(meta).uuid; + if (this.metalnessMap && this.metalnessMap.isTexture) + data2.metalnessMap = this.metalnessMap.toJSON(meta).uuid; + if (this.emissiveMap && this.emissiveMap.isTexture) + data2.emissiveMap = this.emissiveMap.toJSON(meta).uuid; + if (this.specularMap && this.specularMap.isTexture) + data2.specularMap = this.specularMap.toJSON(meta).uuid; + if (this.specularIntensityMap && this.specularIntensityMap.isTexture) + data2.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid; + if (this.specularColorMap && this.specularColorMap.isTexture) + data2.specularColorMap = this.specularColorMap.toJSON(meta).uuid; + if (this.envMap && this.envMap.isTexture) { + data2.envMap = this.envMap.toJSON(meta).uuid; + if (this.combine !== undefined) + data2.combine = this.combine; + } + if (this.envMapRotation !== undefined) + data2.envMapRotation = this.envMapRotation.toArray(); + if (this.envMapIntensity !== undefined) + data2.envMapIntensity = this.envMapIntensity; + if (this.reflectivity !== undefined) + data2.reflectivity = this.reflectivity; + if (this.refractionRatio !== undefined) + data2.refractionRatio = this.refractionRatio; + if (this.gradientMap && this.gradientMap.isTexture) { + data2.gradientMap = this.gradientMap.toJSON(meta).uuid; + } + if (this.transmission !== undefined) + data2.transmission = this.transmission; + if (this.transmissionMap && this.transmissionMap.isTexture) + data2.transmissionMap = this.transmissionMap.toJSON(meta).uuid; + if (this.thickness !== undefined) + data2.thickness = this.thickness; + if (this.thicknessMap && this.thicknessMap.isTexture) + data2.thicknessMap = this.thicknessMap.toJSON(meta).uuid; + if (this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity) + data2.attenuationDistance = this.attenuationDistance; + if (this.attenuationColor !== undefined) + data2.attenuationColor = this.attenuationColor.getHex(); + if (this.size !== undefined) + data2.size = this.size; + if (this.shadowSide !== null) + data2.shadowSide = this.shadowSide; + if (this.sizeAttenuation !== undefined) + data2.sizeAttenuation = this.sizeAttenuation; + if (this.blending !== NormalBlending) + data2.blending = this.blending; + if (this.side !== FrontSide) + data2.side = this.side; + if (this.vertexColors === true) + data2.vertexColors = true; + if (this.opacity < 1) + data2.opacity = this.opacity; + if (this.transparent === true) + data2.transparent = true; + if (this.blendSrc !== SrcAlphaFactor) + data2.blendSrc = this.blendSrc; + if (this.blendDst !== OneMinusSrcAlphaFactor) + data2.blendDst = this.blendDst; + if (this.blendEquation !== AddEquation) + data2.blendEquation = this.blendEquation; + if (this.blendSrcAlpha !== null) + data2.blendSrcAlpha = this.blendSrcAlpha; + if (this.blendDstAlpha !== null) + data2.blendDstAlpha = this.blendDstAlpha; + if (this.blendEquationAlpha !== null) + data2.blendEquationAlpha = this.blendEquationAlpha; + if (this.blendColor && this.blendColor.isColor) + data2.blendColor = this.blendColor.getHex(); + if (this.blendAlpha !== 0) + data2.blendAlpha = this.blendAlpha; + if (this.depthFunc !== LessEqualDepth) + data2.depthFunc = this.depthFunc; + if (this.depthTest === false) + data2.depthTest = this.depthTest; + if (this.depthWrite === false) + data2.depthWrite = this.depthWrite; + if (this.colorWrite === false) + data2.colorWrite = this.colorWrite; + if (this.stencilWriteMask !== 255) + data2.stencilWriteMask = this.stencilWriteMask; + if (this.stencilFunc !== AlwaysStencilFunc) + data2.stencilFunc = this.stencilFunc; + if (this.stencilRef !== 0) + data2.stencilRef = this.stencilRef; + if (this.stencilFuncMask !== 255) + data2.stencilFuncMask = this.stencilFuncMask; + if (this.stencilFail !== KeepStencilOp) + data2.stencilFail = this.stencilFail; + if (this.stencilZFail !== KeepStencilOp) + data2.stencilZFail = this.stencilZFail; + if (this.stencilZPass !== KeepStencilOp) + data2.stencilZPass = this.stencilZPass; + if (this.stencilWrite === true) + data2.stencilWrite = this.stencilWrite; + if (this.rotation !== undefined && this.rotation !== 0) + data2.rotation = this.rotation; + if (this.polygonOffset === true) + data2.polygonOffset = true; + if (this.polygonOffsetFactor !== 0) + data2.polygonOffsetFactor = this.polygonOffsetFactor; + if (this.polygonOffsetUnits !== 0) + data2.polygonOffsetUnits = this.polygonOffsetUnits; + if (this.linewidth !== undefined && this.linewidth !== 1) + data2.linewidth = this.linewidth; + if (this.dashSize !== undefined) + data2.dashSize = this.dashSize; + if (this.gapSize !== undefined) + data2.gapSize = this.gapSize; + if (this.scale !== undefined) + data2.scale = this.scale; + if (this.dithering === true) + data2.dithering = true; + if (this.alphaTest > 0) + data2.alphaTest = this.alphaTest; + if (this.alphaHash === true) + data2.alphaHash = true; + if (this.alphaToCoverage === true) + data2.alphaToCoverage = true; + if (this.premultipliedAlpha === true) + data2.premultipliedAlpha = true; + if (this.forceSinglePass === true) + data2.forceSinglePass = true; + if (this.wireframe === true) + data2.wireframe = true; + if (this.wireframeLinewidth > 1) + data2.wireframeLinewidth = this.wireframeLinewidth; + if (this.wireframeLinecap !== "round") + data2.wireframeLinecap = this.wireframeLinecap; + if (this.wireframeLinejoin !== "round") + data2.wireframeLinejoin = this.wireframeLinejoin; + if (this.flatShading === true) + data2.flatShading = true; + if (this.visible === false) + data2.visible = false; + if (this.toneMapped === false) + data2.toneMapped = false; + if (this.fog === false) + data2.fog = false; + if (Object.keys(this.userData).length > 0) + data2.userData = this.userData; + function extractFromCache(cache) { + const values2 = []; + for (const key2 in cache) { + const data3 = cache[key2]; + delete data3.metadata; + values2.push(data3); + } + return values2; + } + if (isRootObject) { + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + if (textures.length > 0) + data2.textures = textures; + if (images.length > 0) + data2.images = images; + } + return data2; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + this.opacity = source.opacity; + this.transparent = source.transparent; + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + this.blendColor.copy(source.blendColor); + this.blendAlpha = source.blendAlpha; + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + if (srcPlanes !== null) { + const n = srcPlanes.length; + dstPlanes = new Array(n); + for (let i = 0;i !== n; ++i) { + dstPlanes[i] = srcPlanes[i].clone(); + } + } + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + this.shadowSide = source.shadowSide; + this.colorWrite = source.colorWrite; + this.precision = source.precision; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + this.dithering = source.dithering; + this.alphaTest = source.alphaTest; + this.alphaHash = source.alphaHash; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + this.forceSinglePass = source.forceSinglePass; + this.visible = source.visible; + this.toneMapped = source.toneMapped; + this.userData = JSON.parse(JSON.stringify(source.userData)); + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + onBuild() { + console.warn("Material: onBuild() has been removed."); + } +} + +class MeshBasicMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshBasicMaterial = true; + this.type = "MeshBasicMaterial"; + this.color = new Color(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } +} +var _tables = /* @__PURE__ */ _generateTables(); +function _generateTables() { + const buffer = new ArrayBuffer(4); + const floatView = new Float32Array(buffer); + const uint32View = new Uint32Array(buffer); + const baseTable = new Uint32Array(512); + const shiftTable = new Uint32Array(512); + for (let i = 0;i < 256; ++i) { + const e = i - 127; + if (e < -27) { + baseTable[i] = 0; + baseTable[i | 256] = 32768; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else if (e < -14) { + baseTable[i] = 1024 >> -e - 14; + baseTable[i | 256] = 1024 >> -e - 14 | 32768; + shiftTable[i] = -e - 1; + shiftTable[i | 256] = -e - 1; + } else if (e <= 15) { + baseTable[i] = e + 15 << 10; + baseTable[i | 256] = e + 15 << 10 | 32768; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } else if (e < 128) { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } + } + const mantissaTable = new Uint32Array(2048); + const exponentTable = new Uint32Array(64); + const offsetTable = new Uint32Array(64); + for (let i = 1;i < 1024; ++i) { + let m = i << 13; + let e = 0; + while ((m & 8388608) === 0) { + m <<= 1; + e -= 8388608; + } + m &= ~8388608; + e += 947912704; + mantissaTable[i] = m | e; + } + for (let i = 1024;i < 2048; ++i) { + mantissaTable[i] = 939524096 + (i - 1024 << 13); + } + for (let i = 1;i < 31; ++i) { + exponentTable[i] = i << 23; + } + exponentTable[31] = 1199570944; + exponentTable[32] = 2147483648; + for (let i = 33;i < 63; ++i) { + exponentTable[i] = 2147483648 + (i - 32 << 23); + } + exponentTable[63] = 3347054592; + for (let i = 1;i < 64; ++i) { + if (i !== 32) { + offsetTable[i] = 1024; + } + } + return { + floatView, + uint32View, + baseTable, + shiftTable, + mantissaTable, + exponentTable, + offsetTable + }; +} +function toHalfFloat(val2) { + if (Math.abs(val2) > 65504) + console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."); + val2 = clamp2(val2, -65504, 65504); + _tables.floatView[0] = val2; + const f = _tables.uint32View[0]; + const e = f >> 23 & 511; + return _tables.baseTable[e] + ((f & 8388607) >> _tables.shiftTable[e]); +} +function fromHalfFloat(val2) { + const m = val2 >> 10; + _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val2 & 1023)] + _tables.exponentTable[m]; + return _tables.floatView[0]; +} +var DataUtils = { + toHalfFloat, + fromHalfFloat +}; +var _vector$9 = /* @__PURE__ */ new Vector3; +var _vector2$1 = /* @__PURE__ */ new Vector2; +var _id$2 = 0; + +class BufferAttribute { + constructor(array, itemSize, normalized = false) { + if (Array.isArray(array)) { + throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); + } + this.isBufferAttribute = true; + Object.defineProperty(this, "id", { value: _id$2++ }); + this.name = ""; + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized; + this.usage = StaticDrawUsage; + this.updateRanges = []; + this.gpuType = FloatType; + this.version = 0; + } + onUploadCallback() { + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setUsage(value2) { + this.usage = value2; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.name = source.name; + this.array = new source.array.constructor(source.array); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + this.usage = source.usage; + this.gpuType = source.gpuType; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.itemSize; + index2 *= attribute.itemSize; + for (let i = 0, l = this.itemSize;i < l; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + copyArray(array) { + this.array.set(array); + return this; + } + applyMatrix3(m) { + if (this.itemSize === 2) { + for (let i = 0, l = this.count;i < l; i++) { + _vector2$1.fromBufferAttribute(this, i); + _vector2$1.applyMatrix3(m); + this.setXY(i, _vector2$1.x, _vector2$1.y); + } + } else if (this.itemSize === 3) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.applyMatrix3(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + } + return this; + } + applyMatrix4(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.applyMatrix4(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.applyNormalMatrix(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.transformDirection(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + set(value2, offset = 0) { + this.array.set(value2, offset); + return this; + } + getComponent(index2, component) { + let value2 = this.array[index2 * this.itemSize + component]; + if (this.normalized) + value2 = denormalize(value2, this.array); + return value2; + } + setComponent(index2, component, value2) { + if (this.normalized) + value2 = normalize2(value2, this.array); + this.array[index2 * this.itemSize + component] = value2; + return this; + } + getX(index2) { + let x = this.array[index2 * this.itemSize]; + if (this.normalized) + x = denormalize(x, this.array); + return x; + } + setX(index2, x) { + if (this.normalized) + x = normalize2(x, this.array); + this.array[index2 * this.itemSize] = x; + return this; + } + getY(index2) { + let y = this.array[index2 * this.itemSize + 1]; + if (this.normalized) + y = denormalize(y, this.array); + return y; + } + setY(index2, y) { + if (this.normalized) + y = normalize2(y, this.array); + this.array[index2 * this.itemSize + 1] = y; + return this; + } + getZ(index2) { + let z = this.array[index2 * this.itemSize + 2]; + if (this.normalized) + z = denormalize(z, this.array); + return z; + } + setZ(index2, z) { + if (this.normalized) + z = normalize2(z, this.array); + this.array[index2 * this.itemSize + 2] = z; + return this; + } + getW(index2) { + let w = this.array[index2 * this.itemSize + 3]; + if (this.normalized) + w = denormalize(w, this.array); + return w; + } + setW(index2, w) { + if (this.normalized) + w = normalize2(w, this.array); + this.array[index2 * this.itemSize + 3] = w; + return this; + } + setXY(index2, x, y) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + } + this.array[index2 + 0] = x; + this.array[index2 + 1] = y; + return this; + } + setXYZ(index2, x, y, z) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + } + this.array[index2 + 0] = x; + this.array[index2 + 1] = y; + this.array[index2 + 2] = z; + return this; + } + setXYZW(index2, x, y, z, w) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + w = normalize2(w, this.array); + } + this.array[index2 + 0] = x; + this.array[index2 + 1] = y; + this.array[index2 + 2] = z; + this.array[index2 + 3] = w; + return this; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + clone() { + return new this.constructor(this.array, this.itemSize).copy(this); + } + toJSON() { + const data2 = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from(this.array), + normalized: this.normalized + }; + if (this.name !== "") + data2.name = this.name; + if (this.usage !== StaticDrawUsage) + data2.usage = this.usage; + return data2; + } +} + +class Int8BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Int8Array(array), itemSize, normalized); + } +} + +class Uint8BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint8Array(array), itemSize, normalized); + } +} + +class Uint8ClampedBufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint8ClampedArray(array), itemSize, normalized); + } +} + +class Int16BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Int16Array(array), itemSize, normalized); + } +} + +class Uint16BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + } +} + +class Int32BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Int32Array(array), itemSize, normalized); + } +} + +class Uint32BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint32Array(array), itemSize, normalized); + } +} + +class Float16BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + this.isFloat16BufferAttribute = true; + } + getX(index2) { + let x = fromHalfFloat(this.array[index2 * this.itemSize]); + if (this.normalized) + x = denormalize(x, this.array); + return x; + } + setX(index2, x) { + if (this.normalized) + x = normalize2(x, this.array); + this.array[index2 * this.itemSize] = toHalfFloat(x); + return this; + } + getY(index2) { + let y = fromHalfFloat(this.array[index2 * this.itemSize + 1]); + if (this.normalized) + y = denormalize(y, this.array); + return y; + } + setY(index2, y) { + if (this.normalized) + y = normalize2(y, this.array); + this.array[index2 * this.itemSize + 1] = toHalfFloat(y); + return this; + } + getZ(index2) { + let z = fromHalfFloat(this.array[index2 * this.itemSize + 2]); + if (this.normalized) + z = denormalize(z, this.array); + return z; + } + setZ(index2, z) { + if (this.normalized) + z = normalize2(z, this.array); + this.array[index2 * this.itemSize + 2] = toHalfFloat(z); + return this; + } + getW(index2) { + let w = fromHalfFloat(this.array[index2 * this.itemSize + 3]); + if (this.normalized) + w = denormalize(w, this.array); + return w; + } + setW(index2, w) { + if (this.normalized) + w = normalize2(w, this.array); + this.array[index2 * this.itemSize + 3] = toHalfFloat(w); + return this; + } + setXY(index2, x, y) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + } + this.array[index2 + 0] = toHalfFloat(x); + this.array[index2 + 1] = toHalfFloat(y); + return this; + } + setXYZ(index2, x, y, z) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + } + this.array[index2 + 0] = toHalfFloat(x); + this.array[index2 + 1] = toHalfFloat(y); + this.array[index2 + 2] = toHalfFloat(z); + return this; + } + setXYZW(index2, x, y, z, w) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + w = normalize2(w, this.array); + } + this.array[index2 + 0] = toHalfFloat(x); + this.array[index2 + 1] = toHalfFloat(y); + this.array[index2 + 2] = toHalfFloat(z); + this.array[index2 + 3] = toHalfFloat(w); + return this; + } +} + +class Float32BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Float32Array(array), itemSize, normalized); + } +} +var _id$1 = 0; +var _m1 = /* @__PURE__ */ new Matrix4; +var _obj = /* @__PURE__ */ new Object3D; +var _offset = /* @__PURE__ */ new Vector3; +var _box$2 = /* @__PURE__ */ new Box3; +var _boxMorphTargets = /* @__PURE__ */ new Box3; +var _vector$8 = /* @__PURE__ */ new Vector3; + +class BufferGeometry extends EventDispatcher { + constructor() { + super(); + this.isBufferGeometry = true; + Object.defineProperty(this, "id", { value: _id$1++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "BufferGeometry"; + this.index = null; + this.indirect = null; + this.attributes = {}; + this.morphAttributes = {}; + this.morphTargetsRelative = false; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + this.drawRange = { start: 0, count: Infinity }; + this.userData = {}; + } + getIndex() { + return this.index; + } + setIndex(index2) { + if (Array.isArray(index2)) { + this.index = new ((arrayNeedsUint32(index2)) ? Uint32BufferAttribute : Uint16BufferAttribute)(index2, 1); + } else { + this.index = index2; + } + return this; + } + setIndirect(indirect) { + this.indirect = indirect; + return this; + } + getIndirect() { + return this.indirect; + } + getAttribute(name2) { + return this.attributes[name2]; + } + setAttribute(name2, attribute) { + this.attributes[name2] = attribute; + return this; + } + deleteAttribute(name2) { + delete this.attributes[name2]; + return this; + } + hasAttribute(name2) { + return this.attributes[name2] !== undefined; + } + addGroup(start, count, materialIndex = 0) { + this.groups.push({ + start, + count, + materialIndex + }); + } + clearGroups() { + this.groups = []; + } + setDrawRange(start, count) { + this.drawRange.start = start; + this.drawRange.count = count; + } + applyMatrix4(matrix) { + const position2 = this.attributes.position; + if (position2 !== undefined) { + position2.applyMatrix4(matrix); + position2.needsUpdate = true; + } + const normal = this.attributes.normal; + if (normal !== undefined) { + const normalMatrix = new Matrix3().getNormalMatrix(matrix); + normal.applyNormalMatrix(normalMatrix); + normal.needsUpdate = true; + } + const tangent = this.attributes.tangent; + if (tangent !== undefined) { + tangent.transformDirection(matrix); + tangent.needsUpdate = true; + } + if (this.boundingBox !== null) { + this.computeBoundingBox(); + } + if (this.boundingSphere !== null) { + this.computeBoundingSphere(); + } + return this; + } + applyQuaternion(q) { + _m1.makeRotationFromQuaternion(q); + this.applyMatrix4(_m1); + return this; + } + rotateX(angle) { + _m1.makeRotationX(angle); + this.applyMatrix4(_m1); + return this; + } + rotateY(angle) { + _m1.makeRotationY(angle); + this.applyMatrix4(_m1); + return this; + } + rotateZ(angle) { + _m1.makeRotationZ(angle); + this.applyMatrix4(_m1); + return this; + } + translate(x, y, z) { + _m1.makeTranslation(x, y, z); + this.applyMatrix4(_m1); + return this; + } + scale(x, y, z) { + _m1.makeScale(x, y, z); + this.applyMatrix4(_m1); + return this; + } + lookAt(vector) { + _obj.lookAt(vector); + _obj.updateMatrix(); + this.applyMatrix4(_obj.matrix); + return this; + } + center() { + this.computeBoundingBox(); + this.boundingBox.getCenter(_offset).negate(); + this.translate(_offset.x, _offset.y, _offset.z); + return this; + } + setFromPoints(points) { + const positionAttribute = this.getAttribute("position"); + if (positionAttribute === undefined) { + const position2 = []; + for (let i = 0, l = points.length;i < l; i++) { + const point = points[i]; + position2.push(point.x, point.y, point.z || 0); + } + this.setAttribute("position", new Float32BufferAttribute(position2, 3)); + } else { + const l = Math.min(points.length, positionAttribute.count); + for (let i = 0;i < l; i++) { + const point = points[i]; + positionAttribute.setXYZ(i, point.x, point.y, point.z || 0); + } + if (points.length > positionAttribute.count) { + console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."); + } + positionAttribute.needsUpdate = true; + } + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box3; + } + const position2 = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position2 && position2.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this); + this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(Infinity, Infinity, Infinity)); + return; + } + if (position2 !== undefined) { + this.boundingBox.setFromBufferAttribute(position2); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _box$2.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$8.addVectors(this.boundingBox.min, _box$2.min); + this.boundingBox.expandByPoint(_vector$8); + _vector$8.addVectors(this.boundingBox.max, _box$2.max); + this.boundingBox.expandByPoint(_vector$8); + } else { + this.boundingBox.expandByPoint(_box$2.min); + this.boundingBox.expandByPoint(_box$2.max); + } + } + } + } else { + this.boundingBox.makeEmpty(); + } + if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) { + console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere; + } + const position2 = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position2 && position2.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this); + this.boundingSphere.set(new Vector3, Infinity); + return; + } + if (position2) { + const center = this.boundingSphere.center; + _box$2.setFromBufferAttribute(position2); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _boxMorphTargets.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$8.addVectors(_box$2.min, _boxMorphTargets.min); + _box$2.expandByPoint(_vector$8); + _vector$8.addVectors(_box$2.max, _boxMorphTargets.max); + _box$2.expandByPoint(_vector$8); + } else { + _box$2.expandByPoint(_boxMorphTargets.min); + _box$2.expandByPoint(_boxMorphTargets.max); + } + } + } + _box$2.getCenter(center); + let maxRadiusSq = 0; + for (let i = 0, il = position2.count;i < il; i++) { + _vector$8.fromBufferAttribute(position2, i); + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); + } + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + const morphTargetsRelative = this.morphTargetsRelative; + for (let j = 0, jl = morphAttribute.count;j < jl; j++) { + _vector$8.fromBufferAttribute(morphAttribute, j); + if (morphTargetsRelative) { + _offset.fromBufferAttribute(position2, j); + _vector$8.add(_offset); + } + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); + } + } + } + this.boundingSphere.radius = Math.sqrt(maxRadiusSq); + if (isNaN(this.boundingSphere.radius)) { + console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); + } + } + } + computeTangents() { + const index2 = this.index; + const attributes = this.attributes; + if (index2 === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) { + console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); + return; + } + const positionAttribute = attributes.position; + const normalAttribute = attributes.normal; + const uvAttribute = attributes.uv; + if (this.hasAttribute("tangent") === false) { + this.setAttribute("tangent", new BufferAttribute(new Float32Array(4 * positionAttribute.count), 4)); + } + const tangentAttribute = this.getAttribute("tangent"); + const tan1 = [], tan2 = []; + for (let i = 0;i < positionAttribute.count; i++) { + tan1[i] = new Vector3; + tan2[i] = new Vector3; + } + const vA = new Vector3, vB = new Vector3, vC = new Vector3, uvA = new Vector2, uvB = new Vector2, uvC = new Vector2, sdir = new Vector3, tdir = new Vector3; + function handleTriangle(a, b, c) { + vA.fromBufferAttribute(positionAttribute, a); + vB.fromBufferAttribute(positionAttribute, b); + vC.fromBufferAttribute(positionAttribute, c); + uvA.fromBufferAttribute(uvAttribute, a); + uvB.fromBufferAttribute(uvAttribute, b); + uvC.fromBufferAttribute(uvAttribute, c); + vB.sub(vA); + vC.sub(vA); + uvB.sub(uvA); + uvC.sub(uvA); + const r = 1 / (uvB.x * uvC.y - uvC.x * uvB.y); + if (!isFinite(r)) + return; + sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r); + tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r); + tan1[a].add(sdir); + tan1[b].add(sdir); + tan1[c].add(sdir); + tan2[a].add(tdir); + tan2[b].add(tdir); + tan2[c].add(tdir); + } + let groups = this.groups; + if (groups.length === 0) { + groups = [{ + start: 0, + count: index2.count + }]; + } + for (let i = 0, il = groups.length;i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j = start, jl = start + count;j < jl; j += 3) { + handleTriangle(index2.getX(j + 0), index2.getX(j + 1), index2.getX(j + 2)); + } + } + const tmp = new Vector3, tmp2 = new Vector3; + const n = new Vector3, n2 = new Vector3; + function handleVertex(v) { + n.fromBufferAttribute(normalAttribute, v); + n2.copy(n); + const t = tan1[v]; + tmp.copy(t); + tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); + tmp2.crossVectors(n2, t); + const test = tmp2.dot(tan2[v]); + const w = test < 0 ? -1 : 1; + tangentAttribute.setXYZW(v, tmp.x, tmp.y, tmp.z, w); + } + for (let i = 0, il = groups.length;i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j = start, jl = start + count;j < jl; j += 3) { + handleVertex(index2.getX(j + 0)); + handleVertex(index2.getX(j + 1)); + handleVertex(index2.getX(j + 2)); + } + } + } + computeVertexNormals() { + const index2 = this.index; + const positionAttribute = this.getAttribute("position"); + if (positionAttribute !== undefined) { + let normalAttribute = this.getAttribute("normal"); + if (normalAttribute === undefined) { + normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3); + this.setAttribute("normal", normalAttribute); + } else { + for (let i = 0, il = normalAttribute.count;i < il; i++) { + normalAttribute.setXYZ(i, 0, 0, 0); + } + } + const pA = new Vector3, pB = new Vector3, pC = new Vector3; + const nA = new Vector3, nB = new Vector3, nC = new Vector3; + const cb = new Vector3, ab = new Vector3; + if (index2) { + for (let i = 0, il = index2.count;i < il; i += 3) { + const vA = index2.getX(i + 0); + const vB = index2.getX(i + 1); + const vC = index2.getX(i + 2); + pA.fromBufferAttribute(positionAttribute, vA); + pB.fromBufferAttribute(positionAttribute, vB); + pC.fromBufferAttribute(positionAttribute, vC); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + nA.fromBufferAttribute(normalAttribute, vA); + nB.fromBufferAttribute(normalAttribute, vB); + nC.fromBufferAttribute(normalAttribute, vC); + nA.add(cb); + nB.add(cb); + nC.add(cb); + normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z); + normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z); + normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z); + } + } else { + for (let i = 0, il = positionAttribute.count;i < il; i += 3) { + pA.fromBufferAttribute(positionAttribute, i + 0); + pB.fromBufferAttribute(positionAttribute, i + 1); + pC.fromBufferAttribute(positionAttribute, i + 2); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z); + } + } + this.normalizeNormals(); + normalAttribute.needsUpdate = true; + } + } + normalizeNormals() { + const normals = this.attributes.normal; + for (let i = 0, il = normals.count;i < il; i++) { + _vector$8.fromBufferAttribute(normals, i); + _vector$8.normalize(); + normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z); + } + } + toNonIndexed() { + function convertBufferAttribute(attribute, indices2) { + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + const array2 = new array.constructor(indices2.length * itemSize); + let index2 = 0, index22 = 0; + for (let i = 0, l = indices2.length;i < l; i++) { + if (attribute.isInterleavedBufferAttribute) { + index2 = indices2[i] * attribute.data.stride + attribute.offset; + } else { + index2 = indices2[i] * itemSize; + } + for (let j = 0;j < itemSize; j++) { + array2[index22++] = array[index2++]; + } + } + return new BufferAttribute(array2, itemSize, normalized); + } + if (this.index === null) { + console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."); + return this; + } + const geometry2 = new BufferGeometry; + const indices = this.index.array; + const attributes = this.attributes; + for (const name2 in attributes) { + const attribute = attributes[name2]; + const newAttribute = convertBufferAttribute(attribute, indices); + geometry2.setAttribute(name2, newAttribute); + } + const morphAttributes = this.morphAttributes; + for (const name2 in morphAttributes) { + const morphArray = []; + const morphAttribute = morphAttributes[name2]; + for (let i = 0, il = morphAttribute.length;i < il; i++) { + const attribute = morphAttribute[i]; + const newAttribute = convertBufferAttribute(attribute, indices); + morphArray.push(newAttribute); + } + geometry2.morphAttributes[name2] = morphArray; + } + geometry2.morphTargetsRelative = this.morphTargetsRelative; + const groups = this.groups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + geometry2.addGroup(group.start, group.count, group.materialIndex); + } + return geometry2; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "BufferGeometry", + generator: "BufferGeometry.toJSON" + } + }; + data2.uuid = this.uuid; + data2.type = this.type; + if (this.name !== "") + data2.name = this.name; + if (Object.keys(this.userData).length > 0) + data2.userData = this.userData; + if (this.parameters !== undefined) { + const parameters = this.parameters; + for (const key2 in parameters) { + if (parameters[key2] !== undefined) + data2[key2] = parameters[key2]; + } + return data2; + } + data2.data = { attributes: {} }; + const index2 = this.index; + if (index2 !== null) { + data2.data.index = { + type: index2.array.constructor.name, + array: Array.prototype.slice.call(index2.array) + }; + } + const attributes = this.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + data2.data.attributes[key2] = attribute.toJSON(data2.data); + } + const morphAttributes = {}; + let hasMorphAttributes = false; + for (const key2 in this.morphAttributes) { + const attributeArray = this.morphAttributes[key2]; + const array = []; + for (let i = 0, il = attributeArray.length;i < il; i++) { + const attribute = attributeArray[i]; + array.push(attribute.toJSON(data2.data)); + } + if (array.length > 0) { + morphAttributes[key2] = array; + hasMorphAttributes = true; + } + } + if (hasMorphAttributes) { + data2.data.morphAttributes = morphAttributes; + data2.data.morphTargetsRelative = this.morphTargetsRelative; + } + const groups = this.groups; + if (groups.length > 0) { + data2.data.groups = JSON.parse(JSON.stringify(groups)); + } + const boundingSphere = this.boundingSphere; + if (boundingSphere !== null) { + data2.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; + } + return data2; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + const data2 = {}; + this.name = source.name; + const index2 = source.index; + if (index2 !== null) { + this.setIndex(index2.clone(data2)); + } + const attributes = source.attributes; + for (const name2 in attributes) { + const attribute = attributes[name2]; + this.setAttribute(name2, attribute.clone(data2)); + } + const morphAttributes = source.morphAttributes; + for (const name2 in morphAttributes) { + const array = []; + const morphAttribute = morphAttributes[name2]; + for (let i = 0, l = morphAttribute.length;i < l; i++) { + array.push(morphAttribute[i].clone(data2)); + } + this.morphAttributes[name2] = array; + } + this.morphTargetsRelative = source.morphTargetsRelative; + const groups = source.groups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + this.addGroup(group.start, group.count, group.materialIndex); + } + const boundingBox = source.boundingBox; + if (boundingBox !== null) { + this.boundingBox = boundingBox.clone(); + } + const boundingSphere = source.boundingSphere; + if (boundingSphere !== null) { + this.boundingSphere = boundingSphere.clone(); + } + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + this.userData = source.userData; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } +} +var _inverseMatrix$3 = /* @__PURE__ */ new Matrix4; +var _ray$3 = /* @__PURE__ */ new Ray; +var _sphere$6 = /* @__PURE__ */ new Sphere; +var _sphereHitAt = /* @__PURE__ */ new Vector3; +var _vA$1 = /* @__PURE__ */ new Vector3; +var _vB$1 = /* @__PURE__ */ new Vector3; +var _vC$1 = /* @__PURE__ */ new Vector3; +var _tempA = /* @__PURE__ */ new Vector3; +var _morphA = /* @__PURE__ */ new Vector3; +var _intersectionPoint = /* @__PURE__ */ new Vector3; +var _intersectionPointWorld = /* @__PURE__ */ new Vector3; + +class Mesh extends Object3D { + constructor(geometry = new BufferGeometry, material = new MeshBasicMaterial) { + super(); + this.isMesh = true; + this.type = "Mesh"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.morphTargetInfluences !== undefined) { + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + } + if (source.morphTargetDictionary !== undefined) { + this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary); + } + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } + getVertexPosition(index2, target) { + const geometry = this.geometry; + const position2 = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + target.fromBufferAttribute(position2, index2); + const morphInfluences = this.morphTargetInfluences; + if (morphPosition && morphInfluences) { + _morphA.set(0, 0, 0); + for (let i = 0, il = morphPosition.length;i < il; i++) { + const influence = morphInfluences[i]; + const morphAttribute = morphPosition[i]; + if (influence === 0) + continue; + _tempA.fromBufferAttribute(morphAttribute, index2); + if (morphTargetsRelative) { + _morphA.addScaledVector(_tempA, influence); + } else { + _morphA.addScaledVector(_tempA.sub(target), influence); + } + } + target.add(_morphA); + } + return target; + } + raycast(raycaster, intersects) { + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === undefined) + return; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$6.copy(geometry.boundingSphere); + _sphere$6.applyMatrix4(matrixWorld); + _ray$3.copy(raycaster.ray).recast(raycaster.near); + if (_sphere$6.containsPoint(_ray$3.origin) === false) { + if (_ray$3.intersectSphere(_sphere$6, _sphereHitAt) === null) + return; + if (_ray$3.origin.distanceToSquared(_sphereHitAt) > (raycaster.far - raycaster.near) ** 2) + return; + } + _inverseMatrix$3.copy(matrixWorld).invert(); + _ray$3.copy(raycaster.ray).applyMatrix4(_inverseMatrix$3); + if (geometry.boundingBox !== null) { + if (_ray$3.intersectsBox(geometry.boundingBox) === false) + return; + } + this._computeIntersections(raycaster, intersects, _ray$3); + } + _computeIntersections(raycaster, intersects, rayLocalSpace) { + let intersection; + const geometry = this.geometry; + const material = this.material; + const index2 = geometry.index; + const position2 = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv1 = geometry.attributes.uv1; + const normal = geometry.attributes.normal; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + if (index2 !== null) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length;i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(index2.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j = start, jl = end;j < jl; j += 3) { + const a = index2.getX(j); + const b = index2.getX(j + 1); + const c = index2.getX(j + 2); + intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(j / 3); + intersection.face.materialIndex = group.materialIndex; + intersects.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i += 3) { + const a = index2.getX(i); + const b = index2.getX(i + 1); + const c = index2.getX(i + 2); + intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects.push(intersection); + } + } + } + } else if (position2 !== undefined) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length;i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(position2.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j = start, jl = end;j < jl; j += 3) { + const a = j; + const b = j + 1; + const c = j + 2; + intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(j / 3); + intersection.face.materialIndex = group.materialIndex; + intersects.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(position2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i += 3) { + const a = i; + const b = i + 1; + const c = i + 2; + intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects.push(intersection); + } + } + } + } + } +} +function checkIntersection$1(object, material, raycaster, ray, pA, pB, pC, point) { + let intersect; + if (material.side === BackSide) { + intersect = ray.intersectTriangle(pC, pB, pA, true, point); + } else { + intersect = ray.intersectTriangle(pA, pB, pC, material.side === FrontSide, point); + } + if (intersect === null) + return null; + _intersectionPointWorld.copy(point); + _intersectionPointWorld.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld); + if (distance < raycaster.near || distance > raycaster.far) + return null; + return { + distance, + point: _intersectionPointWorld.clone(), + object + }; +} +function checkGeometryIntersection(object, material, raycaster, ray, uv, uv1, normal, a, b, c) { + object.getVertexPosition(a, _vA$1); + object.getVertexPosition(b, _vB$1); + object.getVertexPosition(c, _vC$1); + const intersection = checkIntersection$1(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint); + if (intersection) { + const barycoord = new Vector3; + Triangle.getBarycoord(_intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord); + if (uv) { + intersection.uv = Triangle.getInterpolatedAttribute(uv, a, b, c, barycoord, new Vector2); + } + if (uv1) { + intersection.uv1 = Triangle.getInterpolatedAttribute(uv1, a, b, c, barycoord, new Vector2); + } + if (normal) { + intersection.normal = Triangle.getInterpolatedAttribute(normal, a, b, c, barycoord, new Vector3); + if (intersection.normal.dot(ray.direction) > 0) { + intersection.normal.multiplyScalar(-1); + } + } + const face = { + a, + b, + c, + normal: new Vector3, + materialIndex: 0 + }; + Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal); + intersection.face = face; + intersection.barycoord = barycoord; + } + return intersection; +} + +class BoxGeometry extends BufferGeometry { + constructor(width2 = 1, height2 = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) { + super(); + this.type = "BoxGeometry"; + this.parameters = { + width: width2, + height: height2, + depth, + widthSegments, + heightSegments, + depthSegments + }; + const scope = this; + widthSegments = Math.floor(widthSegments); + heightSegments = Math.floor(heightSegments); + depthSegments = Math.floor(depthSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let numberOfVertices = 0; + let groupStart = 0; + buildPlane("z", "y", "x", -1, -1, depth, height2, width2, depthSegments, heightSegments, 0); + buildPlane("z", "y", "x", 1, -1, depth, height2, -width2, depthSegments, heightSegments, 1); + buildPlane("x", "z", "y", 1, 1, width2, depth, height2, widthSegments, depthSegments, 2); + buildPlane("x", "z", "y", 1, -1, width2, depth, -height2, widthSegments, depthSegments, 3); + buildPlane("x", "y", "z", 1, -1, width2, height2, depth, widthSegments, heightSegments, 4); + buildPlane("x", "y", "z", -1, -1, width2, height2, -depth, widthSegments, heightSegments, 5); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function buildPlane(u, v, w, udir, vdir, width3, height3, depth2, gridX, gridY, materialIndex) { + const segmentWidth = width3 / gridX; + const segmentHeight = height3 / gridY; + const widthHalf = width3 / 2; + const heightHalf = height3 / 2; + const depthHalf = depth2 / 2; + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + let vertexCounter = 0; + let groupCount = 0; + const vector = new Vector3; + for (let iy = 0;iy < gridY1; iy++) { + const y = iy * segmentHeight - heightHalf; + for (let ix = 0;ix < gridX1; ix++) { + const x = ix * segmentWidth - widthHalf; + vector[u] = x * udir; + vector[v] = y * vdir; + vector[w] = depthHalf; + vertices.push(vector.x, vector.y, vector.z); + vector[u] = 0; + vector[v] = 0; + vector[w] = depth2 > 0 ? 1 : -1; + normals.push(vector.x, vector.y, vector.z); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + vertexCounter += 1; + } + } + for (let iy = 0;iy < gridY; iy++) { + for (let ix = 0;ix < gridX; ix++) { + const a = numberOfVertices + ix + gridX1 * iy; + const b = numberOfVertices + ix + gridX1 * (iy + 1); + const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1); + const d = numberOfVertices + (ix + 1) + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + groupCount += 6; + } + } + scope.addGroup(groupStart, groupCount, materialIndex); + groupStart += groupCount; + numberOfVertices += vertexCounter; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new BoxGeometry(data2.width, data2.height, data2.depth, data2.widthSegments, data2.heightSegments, data2.depthSegments); + } +} +function cloneUniforms(src) { + const dst = {}; + for (const u in src) { + dst[u] = {}; + for (const p in src[u]) { + const property2 = src[u][p]; + if (property2 && (property2.isColor || property2.isMatrix3 || property2.isMatrix4 || property2.isVector2 || property2.isVector3 || property2.isVector4 || property2.isTexture || property2.isQuaternion)) { + if (property2.isRenderTargetTexture) { + console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."); + dst[u][p] = null; + } else { + dst[u][p] = property2.clone(); + } + } else if (Array.isArray(property2)) { + dst[u][p] = property2.slice(); + } else { + dst[u][p] = property2; + } + } + } + return dst; +} +function mergeUniforms(uniforms) { + const merged = {}; + for (let u = 0;u < uniforms.length; u++) { + const tmp = cloneUniforms(uniforms[u]); + for (const p in tmp) { + merged[p] = tmp[p]; + } + } + return merged; +} +function cloneUniformsGroups(src) { + const dst = []; + for (let u = 0;u < src.length; u++) { + dst.push(src[u].clone()); + } + return dst; +} +function getUnlitUniformColorSpace(renderer2) { + const currentRenderTarget = renderer2.getRenderTarget(); + if (currentRenderTarget === null) { + return renderer2.outputColorSpace; + } + if (currentRenderTarget.isXRRenderTarget === true) { + return currentRenderTarget.texture.colorSpace; + } + return ColorManagement.workingColorSpace; +} +var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; +var default_vertex = `void main() { + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); +}`; +var default_fragment = `void main() { + gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); +}`; + +class ShaderMaterial extends Material { + constructor(parameters) { + super(); + this.isShaderMaterial = true; + this.type = "ShaderMaterial"; + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; + this.linewidth = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.fog = false; + this.lights = false; + this.clipping = false; + this.forceSinglePass = true; + this.extensions = { + clipCullDistance: false, + multiDraw: false + }; + this.defaultAttributeValues = { + color: [1, 1, 1], + uv: [0, 0], + uv1: [0, 0] + }; + this.index0AttributeName = undefined; + this.uniformsNeedUpdate = false; + this.glslVersion = null; + if (parameters !== undefined) { + this.setValues(parameters); + } + } + copy(source) { + super.copy(source); + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + this.uniforms = cloneUniforms(source.uniforms); + this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups); + this.defines = Object.assign({}, source.defines); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + this.extensions = Object.assign({}, source.extensions); + this.glslVersion = source.glslVersion; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.glslVersion = this.glslVersion; + data2.uniforms = {}; + for (const name2 in this.uniforms) { + const uniform = this.uniforms[name2]; + const value2 = uniform.value; + if (value2 && value2.isTexture) { + data2.uniforms[name2] = { + type: "t", + value: value2.toJSON(meta).uuid + }; + } else if (value2 && value2.isColor) { + data2.uniforms[name2] = { + type: "c", + value: value2.getHex() + }; + } else if (value2 && value2.isVector2) { + data2.uniforms[name2] = { + type: "v2", + value: value2.toArray() + }; + } else if (value2 && value2.isVector3) { + data2.uniforms[name2] = { + type: "v3", + value: value2.toArray() + }; + } else if (value2 && value2.isVector4) { + data2.uniforms[name2] = { + type: "v4", + value: value2.toArray() + }; + } else if (value2 && value2.isMatrix3) { + data2.uniforms[name2] = { + type: "m3", + value: value2.toArray() + }; + } else if (value2 && value2.isMatrix4) { + data2.uniforms[name2] = { + type: "m4", + value: value2.toArray() + }; + } else { + data2.uniforms[name2] = { + value: value2 + }; + } + } + if (Object.keys(this.defines).length > 0) + data2.defines = this.defines; + data2.vertexShader = this.vertexShader; + data2.fragmentShader = this.fragmentShader; + data2.lights = this.lights; + data2.clipping = this.clipping; + const extensions = {}; + for (const key2 in this.extensions) { + if (this.extensions[key2] === true) + extensions[key2] = true; + } + if (Object.keys(extensions).length > 0) + data2.extensions = extensions; + return data2; + } +} + +class Camera extends Object3D { + constructor() { + super(); + this.isCamera = true; + this.type = "Camera"; + this.matrixWorldInverse = new Matrix4; + this.projectionMatrix = new Matrix4; + this.projectionMatrixInverse = new Matrix4; + this.coordinateSystem = WebGLCoordinateSystem; + } + copy(source, recursive) { + super.copy(source, recursive); + this.matrixWorldInverse.copy(source.matrixWorldInverse); + this.projectionMatrix.copy(source.projectionMatrix); + this.projectionMatrixInverse.copy(source.projectionMatrixInverse); + this.coordinateSystem = source.coordinateSystem; + return this; + } + getWorldDirection(target) { + return super.getWorldDirection(target).negate(); + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + updateWorldMatrix(updateParents, updateChildren) { + super.updateWorldMatrix(updateParents, updateChildren); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + clone() { + return new this.constructor().copy(this); + } +} +var _v3$1 = /* @__PURE__ */ new Vector3; +var _minTarget = /* @__PURE__ */ new Vector2; +var _maxTarget = /* @__PURE__ */ new Vector2; + +class PerspectiveCamera extends Camera { + constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) { + super(); + this.isPerspectiveCamera = true; + this.type = "PerspectiveCamera"; + this.fov = fov; + this.zoom = 1; + this.near = near; + this.far = far; + this.focus = 10; + this.aspect = aspect; + this.view = null; + this.filmGauge = 35; + this.filmOffset = 0; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.fov = source.fov; + this.zoom = source.zoom; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign({}, source.view); + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + return this; + } + setFocalLength(focalLength) { + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope); + this.updateProjectionMatrix(); + } + getFocalLength() { + const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov); + return 0.5 * this.getFilmHeight() / vExtentSlope; + } + getEffectiveFOV() { + return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom); + } + getFilmWidth() { + return this.filmGauge * Math.min(this.aspect, 1); + } + getFilmHeight() { + return this.filmGauge / Math.max(this.aspect, 1); + } + getViewBounds(distance, minTarget, maxTarget) { + _v3$1.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse); + minTarget.set(_v3$1.x, _v3$1.y).multiplyScalar(-distance / _v3$1.z); + _v3$1.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse); + maxTarget.set(_v3$1.x, _v3$1.y).multiplyScalar(-distance / _v3$1.z); + } + getViewSize(distance, target) { + this.getViewBounds(distance, _minTarget, _maxTarget); + return target.subVectors(_maxTarget, _minTarget); + } + setViewOffset(fullWidth, fullHeight, x, y, width2, height2) { + this.aspect = fullWidth / fullHeight; + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width2; + this.view.height = height2; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const near = this.near; + let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom; + let height2 = 2 * top; + let width2 = this.aspect * height2; + let left = -0.5 * width2; + const view = this.view; + if (this.view !== null && this.view.enabled) { + const { fullWidth, fullHeight } = view; + left += view.offsetX * width2 / fullWidth; + top -= view.offsetY * height2 / fullHeight; + width2 *= view.width / fullWidth; + height2 *= view.height / fullHeight; + } + const skew = this.filmOffset; + if (skew !== 0) + left += near * skew / this.getFilmWidth(); + this.projectionMatrix.makePerspective(left, left + width2, top, top - height2, near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.fov = this.fov; + data2.object.zoom = this.zoom; + data2.object.near = this.near; + data2.object.far = this.far; + data2.object.focus = this.focus; + data2.object.aspect = this.aspect; + if (this.view !== null) + data2.object.view = Object.assign({}, this.view); + data2.object.filmGauge = this.filmGauge; + data2.object.filmOffset = this.filmOffset; + return data2; + } +} +var fov = -90; +var aspect = 1; + +class CubeCamera extends Object3D { + constructor(near, far, renderTarget) { + super(); + this.type = "CubeCamera"; + this.renderTarget = renderTarget; + this.coordinateSystem = null; + this.activeMipmapLevel = 0; + const cameraPX = new PerspectiveCamera(fov, aspect, near, far); + cameraPX.layers = this.layers; + this.add(cameraPX); + const cameraNX = new PerspectiveCamera(fov, aspect, near, far); + cameraNX.layers = this.layers; + this.add(cameraNX); + const cameraPY = new PerspectiveCamera(fov, aspect, near, far); + cameraPY.layers = this.layers; + this.add(cameraPY); + const cameraNY = new PerspectiveCamera(fov, aspect, near, far); + cameraNY.layers = this.layers; + this.add(cameraNY); + const cameraPZ = new PerspectiveCamera(fov, aspect, near, far); + cameraPZ.layers = this.layers; + this.add(cameraPZ); + const cameraNZ = new PerspectiveCamera(fov, aspect, near, far); + cameraNZ.layers = this.layers; + this.add(cameraNZ); + } + updateCoordinateSystem() { + const coordinateSystem = this.coordinateSystem; + const cameras = this.children.concat(); + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = cameras; + for (const camera of cameras) + this.remove(camera); + if (coordinateSystem === WebGLCoordinateSystem) { + cameraPX.up.set(0, 1, 0); + cameraPX.lookAt(1, 0, 0); + cameraNX.up.set(0, 1, 0); + cameraNX.lookAt(-1, 0, 0); + cameraPY.up.set(0, 0, -1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, 1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, 1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, 1, 0); + cameraNZ.lookAt(0, 0, -1); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + cameraPX.up.set(0, -1, 0); + cameraPX.lookAt(-1, 0, 0); + cameraNX.up.set(0, -1, 0); + cameraNX.lookAt(1, 0, 0); + cameraPY.up.set(0, 0, 1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, -1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, -1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, -1, 0); + cameraNZ.lookAt(0, 0, -1); + } else { + throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + coordinateSystem); + } + for (const camera of cameras) { + this.add(camera); + camera.updateMatrixWorld(); + } + } + update(renderer2, scene) { + if (this.parent === null) + this.updateMatrixWorld(); + const { renderTarget, activeMipmapLevel } = this; + if (this.coordinateSystem !== renderer2.coordinateSystem) { + this.coordinateSystem = renderer2.coordinateSystem; + this.updateCoordinateSystem(); + } + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children; + const currentRenderTarget = renderer2.getRenderTarget(); + const currentActiveCubeFace = renderer2.getActiveCubeFace(); + const currentActiveMipmapLevel = renderer2.getActiveMipmapLevel(); + const currentXrEnabled = renderer2.xr.enabled; + renderer2.xr.enabled = false; + const generateMipmaps = renderTarget.texture.generateMipmaps; + renderTarget.texture.generateMipmaps = false; + renderer2.setRenderTarget(renderTarget, 0, activeMipmapLevel); + renderer2.render(scene, cameraPX); + renderer2.setRenderTarget(renderTarget, 1, activeMipmapLevel); + renderer2.render(scene, cameraNX); + renderer2.setRenderTarget(renderTarget, 2, activeMipmapLevel); + renderer2.render(scene, cameraPY); + renderer2.setRenderTarget(renderTarget, 3, activeMipmapLevel); + renderer2.render(scene, cameraNY); + renderer2.setRenderTarget(renderTarget, 4, activeMipmapLevel); + renderer2.render(scene, cameraPZ); + renderTarget.texture.generateMipmaps = generateMipmaps; + renderer2.setRenderTarget(renderTarget, 5, activeMipmapLevel); + renderer2.render(scene, cameraNZ); + renderer2.setRenderTarget(currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel); + renderer2.xr.enabled = currentXrEnabled; + renderTarget.texture.needsPMREMUpdate = true; + } +} + +class CubeTexture extends Texture { + constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace) { + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; + super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCubeTexture = true; + this.flipY = false; + } + get images() { + return this.image; + } + set images(value2) { + this.image = value2; + } +} + +class WebGLCubeRenderTarget extends WebGLRenderTarget { + constructor(size = 1, options = {}) { + super(size, size, options); + this.isWebGLCubeRenderTarget = true; + const image = { width: size, height: size, depth: 1 }; + const images = [image, image, image, image, image, image]; + this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + this.texture.isRenderTargetTexture = true; + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + } + fromEquirectangularTexture(renderer2, texture) { + this.texture.type = texture.type; + this.texture.colorSpace = texture.colorSpace; + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + const shader = { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `, + fragmentShader: ` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + }; + const geometry = new BoxGeometry(5, 5, 5); + const material = new ShaderMaterial({ + name: "CubemapFromEquirect", + uniforms: cloneUniforms(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + blending: NoBlending + }); + material.uniforms.tEquirect.value = texture; + const mesh = new Mesh(geometry, material); + const currentMinFilter = texture.minFilter; + if (texture.minFilter === LinearMipmapLinearFilter) + texture.minFilter = LinearFilter; + const camera = new CubeCamera(1, 10, this); + camera.update(renderer2, mesh); + texture.minFilter = currentMinFilter; + mesh.geometry.dispose(); + mesh.material.dispose(); + return this; + } + clear(renderer2, color, depth, stencil) { + const currentRenderTarget = renderer2.getRenderTarget(); + for (let i = 0;i < 6; i++) { + renderer2.setRenderTarget(this, i); + renderer2.clear(color, depth, stencil); + } + renderer2.setRenderTarget(currentRenderTarget); + } +} + +class Group extends Object3D { + constructor() { + super(); + this.isGroup = true; + this.type = "Group"; + } +} +var _moveEvent = { type: "move" }; + +class WebXRController { + constructor() { + this._targetRay = null; + this._grip = null; + this._hand = null; + } + getHandSpace() { + if (this._hand === null) { + this._hand = new Group; + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + } + return this._hand; + } + getTargetRaySpace() { + if (this._targetRay === null) { + this._targetRay = new Group; + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3; + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3; + } + return this._targetRay; + } + getGripSpace() { + if (this._grip === null) { + this._grip = new Group; + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3; + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3; + } + return this._grip; + } + dispatchEvent(event) { + if (this._targetRay !== null) { + this._targetRay.dispatchEvent(event); + } + if (this._grip !== null) { + this._grip.dispatchEvent(event); + } + if (this._hand !== null) { + this._hand.dispatchEvent(event); + } + return this; + } + connect(inputSource) { + if (inputSource && inputSource.hand) { + const hand = this._hand; + if (hand) { + for (const inputjoint of inputSource.hand.values()) { + this._getHandJoint(hand, inputjoint); + } + } + } + this.dispatchEvent({ type: "connected", data: inputSource }); + return this; + } + disconnect(inputSource) { + this.dispatchEvent({ type: "disconnected", data: inputSource }); + if (this._targetRay !== null) { + this._targetRay.visible = false; + } + if (this._grip !== null) { + this._grip.visible = false; + } + if (this._hand !== null) { + this._hand.visible = false; + } + return this; + } + update(inputSource, frame, referenceSpace) { + let inputPose = null; + let gripPose = null; + let handPose = null; + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + if (inputSource && frame.session.visibilityState !== "visible-blurred") { + if (hand && inputSource.hand) { + handPose = true; + for (const inputjoint of inputSource.hand.values()) { + const jointPose = frame.getJointPose(inputjoint, referenceSpace); + const joint = this._getHandJoint(hand, inputjoint); + if (jointPose !== null) { + joint.matrix.fromArray(jointPose.transform.matrix); + joint.matrix.decompose(joint.position, joint.rotation, joint.scale); + joint.matrixWorldNeedsUpdate = true; + joint.jointRadius = jointPose.radius; + } + joint.visible = jointPose !== null; + } + const indexTip = hand.joints["index-finger-tip"]; + const thumbTip = hand.joints["thumb-tip"]; + const distance = indexTip.position.distanceTo(thumbTip.position); + const distanceToPinch = 0.02; + const threshold = 0.005; + if (hand.inputState.pinching && distance > distanceToPinch + threshold) { + hand.inputState.pinching = false; + this.dispatchEvent({ + type: "pinchend", + handedness: inputSource.handedness, + target: this + }); + } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) { + hand.inputState.pinching = true; + this.dispatchEvent({ + type: "pinchstart", + handedness: inputSource.handedness, + target: this + }); + } + } else { + if (grip !== null && inputSource.gripSpace) { + gripPose = frame.getPose(inputSource.gripSpace, referenceSpace); + if (gripPose !== null) { + grip.matrix.fromArray(gripPose.transform.matrix); + grip.matrix.decompose(grip.position, grip.rotation, grip.scale); + grip.matrixWorldNeedsUpdate = true; + if (gripPose.linearVelocity) { + grip.hasLinearVelocity = true; + grip.linearVelocity.copy(gripPose.linearVelocity); + } else { + grip.hasLinearVelocity = false; + } + if (gripPose.angularVelocity) { + grip.hasAngularVelocity = true; + grip.angularVelocity.copy(gripPose.angularVelocity); + } else { + grip.hasAngularVelocity = false; + } + } + } + } + if (targetRay !== null) { + inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); + if (inputPose === null && gripPose !== null) { + inputPose = gripPose; + } + if (inputPose !== null) { + targetRay.matrix.fromArray(inputPose.transform.matrix); + targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale); + targetRay.matrixWorldNeedsUpdate = true; + if (inputPose.linearVelocity) { + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy(inputPose.linearVelocity); + } else { + targetRay.hasLinearVelocity = false; + } + if (inputPose.angularVelocity) { + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy(inputPose.angularVelocity); + } else { + targetRay.hasAngularVelocity = false; + } + this.dispatchEvent(_moveEvent); + } + } + } + if (targetRay !== null) { + targetRay.visible = inputPose !== null; + } + if (grip !== null) { + grip.visible = gripPose !== null; + } + if (hand !== null) { + hand.visible = handPose !== null; + } + return this; + } + _getHandJoint(hand, inputjoint) { + if (hand.joints[inputjoint.jointName] === undefined) { + const joint = new Group; + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[inputjoint.jointName] = joint; + hand.add(joint); + } + return hand.joints[inputjoint.jointName]; + } +} + +class FogExp2 { + constructor(color, density = 0.00025) { + this.isFogExp2 = true; + this.name = ""; + this.color = new Color(color); + this.density = density; + } + clone() { + return new FogExp2(this.color, this.density); + } + toJSON() { + return { + type: "FogExp2", + name: this.name, + color: this.color.getHex(), + density: this.density + }; + } +} + +class Fog { + constructor(color, near = 1, far = 1000) { + this.isFog = true; + this.name = ""; + this.color = new Color(color); + this.near = near; + this.far = far; + } + clone() { + return new Fog(this.color, this.near, this.far); + } + toJSON() { + return { + type: "Fog", + name: this.name, + color: this.color.getHex(), + near: this.near, + far: this.far + }; + } +} + +class Scene extends Object3D { + constructor() { + super(); + this.isScene = true; + this.type = "Scene"; + this.background = null; + this.environment = null; + this.fog = null; + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + this.backgroundRotation = new Euler; + this.environmentIntensity = 1; + this.environmentRotation = new Euler; + this.overrideMaterial = null; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.background !== null) + this.background = source.background.clone(); + if (source.environment !== null) + this.environment = source.environment.clone(); + if (source.fog !== null) + this.fog = source.fog.clone(); + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + this.backgroundRotation.copy(source.backgroundRotation); + this.environmentIntensity = source.environmentIntensity; + this.environmentRotation.copy(source.environmentRotation); + if (source.overrideMaterial !== null) + this.overrideMaterial = source.overrideMaterial.clone(); + this.matrixAutoUpdate = source.matrixAutoUpdate; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + if (this.fog !== null) + data2.object.fog = this.fog.toJSON(); + if (this.backgroundBlurriness > 0) + data2.object.backgroundBlurriness = this.backgroundBlurriness; + if (this.backgroundIntensity !== 1) + data2.object.backgroundIntensity = this.backgroundIntensity; + data2.object.backgroundRotation = this.backgroundRotation.toArray(); + if (this.environmentIntensity !== 1) + data2.object.environmentIntensity = this.environmentIntensity; + data2.object.environmentRotation = this.environmentRotation.toArray(); + return data2; + } +} + +class InterleavedBuffer { + constructor(array, stride) { + this.isInterleavedBuffer = true; + this.array = array; + this.stride = stride; + this.count = array !== undefined ? array.length / stride : 0; + this.usage = StaticDrawUsage; + this.updateRanges = []; + this.version = 0; + this.uuid = generateUUID(); + } + onUploadCallback() { + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setUsage(value2) { + this.usage = value2; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.array = new source.array.constructor(source.array); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.stride; + index2 *= attribute.stride; + for (let i = 0, l = this.stride;i < l; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + set(value2, offset = 0) { + this.array.set(value2, offset); + return this; + } + clone(data2) { + if (data2.arrayBuffers === undefined) { + data2.arrayBuffers = {}; + } + if (this.array.buffer._uuid === undefined) { + this.array.buffer._uuid = generateUUID(); + } + if (data2.arrayBuffers[this.array.buffer._uuid] === undefined) { + data2.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer; + } + const array = new this.array.constructor(data2.arrayBuffers[this.array.buffer._uuid]); + const ib = new this.constructor(array, this.stride); + ib.setUsage(this.usage); + return ib; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + toJSON(data2) { + if (data2.arrayBuffers === undefined) { + data2.arrayBuffers = {}; + } + if (this.array.buffer._uuid === undefined) { + this.array.buffer._uuid = generateUUID(); + } + if (data2.arrayBuffers[this.array.buffer._uuid] === undefined) { + data2.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer)); + } + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; + } +} +var _vector$7 = /* @__PURE__ */ new Vector3; + +class InterleavedBufferAttribute { + constructor(interleavedBuffer, itemSize, offset, normalized = false) { + this.isInterleavedBufferAttribute = true; + this.name = ""; + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; + this.normalized = normalized; + } + get count() { + return this.data.count; + } + get array() { + return this.data.array; + } + set needsUpdate(value2) { + this.data.needsUpdate = value2; + } + applyMatrix4(m) { + for (let i = 0, l = this.data.count;i < l; i++) { + _vector$7.fromBufferAttribute(this, i); + _vector$7.applyMatrix4(m); + this.setXYZ(i, _vector$7.x, _vector$7.y, _vector$7.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$7.fromBufferAttribute(this, i); + _vector$7.applyNormalMatrix(m); + this.setXYZ(i, _vector$7.x, _vector$7.y, _vector$7.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$7.fromBufferAttribute(this, i); + _vector$7.transformDirection(m); + this.setXYZ(i, _vector$7.x, _vector$7.y, _vector$7.z); + } + return this; + } + getComponent(index2, component) { + let value2 = this.array[index2 * this.data.stride + this.offset + component]; + if (this.normalized) + value2 = denormalize(value2, this.array); + return value2; + } + setComponent(index2, component, value2) { + if (this.normalized) + value2 = normalize2(value2, this.array); + this.data.array[index2 * this.data.stride + this.offset + component] = value2; + return this; + } + setX(index2, x) { + if (this.normalized) + x = normalize2(x, this.array); + this.data.array[index2 * this.data.stride + this.offset] = x; + return this; + } + setY(index2, y) { + if (this.normalized) + y = normalize2(y, this.array); + this.data.array[index2 * this.data.stride + this.offset + 1] = y; + return this; + } + setZ(index2, z) { + if (this.normalized) + z = normalize2(z, this.array); + this.data.array[index2 * this.data.stride + this.offset + 2] = z; + return this; + } + setW(index2, w) { + if (this.normalized) + w = normalize2(w, this.array); + this.data.array[index2 * this.data.stride + this.offset + 3] = w; + return this; + } + getX(index2) { + let x = this.data.array[index2 * this.data.stride + this.offset]; + if (this.normalized) + x = denormalize(x, this.array); + return x; + } + getY(index2) { + let y = this.data.array[index2 * this.data.stride + this.offset + 1]; + if (this.normalized) + y = denormalize(y, this.array); + return y; + } + getZ(index2) { + let z = this.data.array[index2 * this.data.stride + this.offset + 2]; + if (this.normalized) + z = denormalize(z, this.array); + return z; + } + getW(index2) { + let w = this.data.array[index2 * this.data.stride + this.offset + 3]; + if (this.normalized) + w = denormalize(w, this.array); + return w; + } + setXY(index2, x, y) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + } + this.data.array[index2 + 0] = x; + this.data.array[index2 + 1] = y; + return this; + } + setXYZ(index2, x, y, z) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + } + this.data.array[index2 + 0] = x; + this.data.array[index2 + 1] = y; + this.data.array[index2 + 2] = z; + return this; + } + setXYZW(index2, x, y, z, w) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + w = normalize2(w, this.array); + } + this.data.array[index2 + 0] = x; + this.data.array[index2 + 1] = y; + this.data.array[index2 + 2] = z; + this.data.array[index2 + 3] = w; + return this; + } + clone(data2) { + if (data2 === undefined) { + console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0;i < this.count; i++) { + const index2 = i * this.data.stride + this.offset; + for (let j = 0;j < this.itemSize; j++) { + array.push(this.data.array[index2 + j]); + } + } + return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized); + } else { + if (data2.interleavedBuffers === undefined) { + data2.interleavedBuffers = {}; + } + if (data2.interleavedBuffers[this.data.uuid] === undefined) { + data2.interleavedBuffers[this.data.uuid] = this.data.clone(data2); + } + return new InterleavedBufferAttribute(data2.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized); + } + } + toJSON(data2) { + if (data2 === undefined) { + console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0;i < this.count; i++) { + const index2 = i * this.data.stride + this.offset; + for (let j = 0;j < this.itemSize; j++) { + array.push(this.data.array[index2 + j]); + } + } + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array, + normalized: this.normalized + }; + } else { + if (data2.interleavedBuffers === undefined) { + data2.interleavedBuffers = {}; + } + if (data2.interleavedBuffers[this.data.uuid] === undefined) { + data2.interleavedBuffers[this.data.uuid] = this.data.toJSON(data2); + } + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + } + } +} + +class SpriteMaterial extends Material { + constructor(parameters) { + super(); + this.isSpriteMaterial = true; + this.type = "SpriteMaterial"; + this.color = new Color(16777215); + this.map = null; + this.alphaMap = null; + this.rotation = 0; + this.sizeAttenuation = true; + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.rotation = source.rotation; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } +} +var _geometry; +var _intersectPoint = /* @__PURE__ */ new Vector3; +var _worldScale = /* @__PURE__ */ new Vector3; +var _mvPosition = /* @__PURE__ */ new Vector3; +var _alignedPosition = /* @__PURE__ */ new Vector2; +var _rotatedPosition = /* @__PURE__ */ new Vector2; +var _viewWorldMatrix = /* @__PURE__ */ new Matrix4; +var _vA = /* @__PURE__ */ new Vector3; +var _vB = /* @__PURE__ */ new Vector3; +var _vC = /* @__PURE__ */ new Vector3; +var _uvA = /* @__PURE__ */ new Vector2; +var _uvB = /* @__PURE__ */ new Vector2; +var _uvC = /* @__PURE__ */ new Vector2; + +class Sprite extends Object3D { + constructor(material = new SpriteMaterial) { + super(); + this.isSprite = true; + this.type = "Sprite"; + if (_geometry === undefined) { + _geometry = new BufferGeometry; + const float32Array = new Float32Array([ + -0.5, + -0.5, + 0, + 0, + 0, + 0.5, + -0.5, + 0, + 1, + 0, + 0.5, + 0.5, + 0, + 1, + 1, + -0.5, + 0.5, + 0, + 0, + 1 + ]); + const interleavedBuffer = new InterleavedBuffer(float32Array, 5); + _geometry.setIndex([0, 1, 2, 0, 2, 3]); + _geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false)); + _geometry.setAttribute("uv", new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false)); + } + this.geometry = _geometry; + this.material = material; + this.center = new Vector2(0.5, 0.5); + } + raycast(raycaster, intersects) { + if (raycaster.camera === null) { + console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'); + } + _worldScale.setFromMatrixScale(this.matrixWorld); + _viewWorldMatrix.copy(raycaster.camera.matrixWorld); + this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld); + _mvPosition.setFromMatrixPosition(this.modelViewMatrix); + if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) { + _worldScale.multiplyScalar(-_mvPosition.z); + } + const rotation2 = this.material.rotation; + let sin, cos; + if (rotation2 !== 0) { + cos = Math.cos(rotation2); + sin = Math.sin(rotation2); + } + const center = this.center; + transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos); + transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos); + transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos); + _uvA.set(0, 0); + _uvB.set(1, 0); + _uvC.set(1, 1); + let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint); + if (intersect === null) { + transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos); + _uvB.set(0, 1); + intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint); + if (intersect === null) { + return; + } + } + const distance = raycaster.ray.origin.distanceTo(_intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) + return; + intersects.push({ + distance, + point: _intersectPoint.clone(), + uv: Triangle.getInterpolation(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2), + face: null, + object: this + }); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.center !== undefined) + this.center.copy(source.center); + this.material = source.material; + return this; + } +} +function transformVertex(vertexPosition, mvPosition, center, scale2, sin, cos) { + _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale2); + if (sin !== undefined) { + _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y; + _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y; + } else { + _rotatedPosition.copy(_alignedPosition); + } + vertexPosition.copy(mvPosition); + vertexPosition.x += _rotatedPosition.x; + vertexPosition.y += _rotatedPosition.y; + vertexPosition.applyMatrix4(_viewWorldMatrix); +} +var _v1$2 = /* @__PURE__ */ new Vector3; +var _v2$1 = /* @__PURE__ */ new Vector3; + +class LOD extends Object3D { + constructor() { + super(); + this._currentLevel = 0; + this.type = "LOD"; + Object.defineProperties(this, { + levels: { + enumerable: true, + value: [] + }, + isLOD: { + value: true + } + }); + this.autoUpdate = true; + } + copy(source) { + super.copy(source, false); + const levels = source.levels; + for (let i = 0, l = levels.length;i < l; i++) { + const level = levels[i]; + this.addLevel(level.object.clone(), level.distance, level.hysteresis); + } + this.autoUpdate = source.autoUpdate; + return this; + } + addLevel(object, distance = 0, hysteresis = 0) { + distance = Math.abs(distance); + const levels = this.levels; + let l; + for (l = 0;l < levels.length; l++) { + if (distance < levels[l].distance) { + break; + } + } + levels.splice(l, 0, { distance, hysteresis, object }); + this.add(object); + return this; + } + removeLevel(distance) { + const levels = this.levels; + for (let i = 0;i < levels.length; i++) { + if (levels[i].distance === distance) { + const removedElements = levels.splice(i, 1); + this.remove(removedElements[0].object); + return true; + } + } + return false; + } + getCurrentLevel() { + return this._currentLevel; + } + getObjectForDistance(distance) { + const levels = this.levels; + if (levels.length > 0) { + let i, l; + for (i = 1, l = levels.length;i < l; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance < levelDistance) { + break; + } + } + return levels[i - 1].object; + } + return null; + } + raycast(raycaster, intersects) { + const levels = this.levels; + if (levels.length > 0) { + _v1$2.setFromMatrixPosition(this.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_v1$2); + this.getObjectForDistance(distance).raycast(raycaster, intersects); + } + } + update(camera) { + const levels = this.levels; + if (levels.length > 1) { + _v1$2.setFromMatrixPosition(camera.matrixWorld); + _v2$1.setFromMatrixPosition(this.matrixWorld); + const distance = _v1$2.distanceTo(_v2$1) / camera.zoom; + levels[0].object.visible = true; + let i, l; + for (i = 1, l = levels.length;i < l; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance >= levelDistance) { + levels[i - 1].object.visible = false; + levels[i].object.visible = true; + } else { + break; + } + } + this._currentLevel = i - 1; + for (;i < l; i++) { + levels[i].object.visible = false; + } + } + } + toJSON(meta) { + const data2 = super.toJSON(meta); + if (this.autoUpdate === false) + data2.object.autoUpdate = false; + data2.object.levels = []; + const levels = this.levels; + for (let i = 0, l = levels.length;i < l; i++) { + const level = levels[i]; + data2.object.levels.push({ + object: level.object.uuid, + distance: level.distance, + hysteresis: level.hysteresis + }); + } + return data2; + } +} +var _basePosition = /* @__PURE__ */ new Vector3; +var _skinIndex = /* @__PURE__ */ new Vector4; +var _skinWeight = /* @__PURE__ */ new Vector4; +var _vector3 = /* @__PURE__ */ new Vector3; +var _matrix4 = /* @__PURE__ */ new Matrix4; +var _vertex = /* @__PURE__ */ new Vector3; +var _sphere$5 = /* @__PURE__ */ new Sphere; +var _inverseMatrix$2 = /* @__PURE__ */ new Matrix4; +var _ray$2 = /* @__PURE__ */ new Ray; + +class SkinnedMesh extends Mesh { + constructor(geometry, material) { + super(geometry, material); + this.isSkinnedMesh = true; + this.type = "SkinnedMesh"; + this.bindMode = AttachedBindMode; + this.bindMatrix = new Matrix4; + this.bindMatrixInverse = new Matrix4; + this.boundingBox = null; + this.boundingSphere = null; + } + computeBoundingBox() { + const geometry = this.geometry; + if (this.boundingBox === null) { + this.boundingBox = new Box3; + } + this.boundingBox.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0;i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex); + this.boundingBox.expandByPoint(_vertex); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere; + } + this.boundingSphere.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0;i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex); + this.boundingSphere.expandByPoint(_vertex); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.bindMode = source.bindMode; + this.bindMatrix.copy(source.bindMatrix); + this.bindMatrixInverse.copy(source.bindMatrixInverse); + this.skeleton = source.skeleton; + if (source.boundingBox !== null) + this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) + this.boundingSphere = source.boundingSphere.clone(); + return this; + } + raycast(raycaster, intersects) { + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === undefined) + return; + if (this.boundingSphere === null) + this.computeBoundingSphere(); + _sphere$5.copy(this.boundingSphere); + _sphere$5.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$5) === false) + return; + _inverseMatrix$2.copy(matrixWorld).invert(); + _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); + if (this.boundingBox !== null) { + if (_ray$2.intersectsBox(this.boundingBox) === false) + return; + } + this._computeIntersections(raycaster, intersects, _ray$2); + } + getVertexPosition(index2, target) { + super.getVertexPosition(index2, target); + this.applyBoneTransform(index2, target); + return target; + } + bind(skeleton, bindMatrix) { + this.skeleton = skeleton; + if (bindMatrix === undefined) { + this.updateMatrixWorld(true); + this.skeleton.calculateInverses(); + bindMatrix = this.matrixWorld; + } + this.bindMatrix.copy(bindMatrix); + this.bindMatrixInverse.copy(bindMatrix).invert(); + } + pose() { + this.skeleton.pose(); + } + normalizeSkinWeights() { + const vector = new Vector4; + const skinWeight = this.geometry.attributes.skinWeight; + for (let i = 0, l = skinWeight.count;i < l; i++) { + vector.fromBufferAttribute(skinWeight, i); + const scale2 = 1 / vector.manhattanLength(); + if (scale2 !== Infinity) { + vector.multiplyScalar(scale2); + } else { + vector.set(1, 0, 0, 0); + } + skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w); + } + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.bindMode === AttachedBindMode) { + this.bindMatrixInverse.copy(this.matrixWorld).invert(); + } else if (this.bindMode === DetachedBindMode) { + this.bindMatrixInverse.copy(this.bindMatrix).invert(); + } else { + console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode); + } + } + applyBoneTransform(index2, vector) { + const skeleton = this.skeleton; + const geometry = this.geometry; + _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index2); + _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index2); + _basePosition.copy(vector).applyMatrix4(this.bindMatrix); + vector.set(0, 0, 0); + for (let i = 0;i < 4; i++) { + const weight = _skinWeight.getComponent(i); + if (weight !== 0) { + const boneIndex = _skinIndex.getComponent(i); + _matrix4.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]); + vector.addScaledVector(_vector3.copy(_basePosition).applyMatrix4(_matrix4), weight); + } + } + return vector.applyMatrix4(this.bindMatrixInverse); + } +} + +class Bone extends Object3D { + constructor() { + super(); + this.isBone = true; + this.type = "Bone"; + } +} + +class DataTexture extends Texture { + constructor(data2 = null, width2 = 1, height2 = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isDataTexture = true; + this.image = { data: data2, width: width2, height: height2 }; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } +} +var _offsetMatrix = /* @__PURE__ */ new Matrix4; +var _identityMatrix = /* @__PURE__ */ new Matrix4; + +class Skeleton { + constructor(bones = [], boneInverses = []) { + this.uuid = generateUUID(); + this.bones = bones.slice(0); + this.boneInverses = boneInverses; + this.boneMatrices = null; + this.boneTexture = null; + this.init(); + } + init() { + const bones = this.bones; + const boneInverses = this.boneInverses; + this.boneMatrices = new Float32Array(bones.length * 16); + if (boneInverses.length === 0) { + this.calculateInverses(); + } else { + if (bones.length !== boneInverses.length) { + console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."); + this.boneInverses = []; + for (let i = 0, il = this.bones.length;i < il; i++) { + this.boneInverses.push(new Matrix4); + } + } + } + } + calculateInverses() { + this.boneInverses.length = 0; + for (let i = 0, il = this.bones.length;i < il; i++) { + const inverse = new Matrix4; + if (this.bones[i]) { + inverse.copy(this.bones[i].matrixWorld).invert(); + } + this.boneInverses.push(inverse); + } + } + pose() { + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone) { + bone.matrixWorld.copy(this.boneInverses[i]).invert(); + } + } + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone) { + if (bone.parent && bone.parent.isBone) { + bone.matrix.copy(bone.parent.matrixWorld).invert(); + bone.matrix.multiply(bone.matrixWorld); + } else { + bone.matrix.copy(bone.matrixWorld); + } + bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); + } + } + } + update() { + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; + for (let i = 0, il = bones.length;i < il; i++) { + const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix; + _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]); + _offsetMatrix.toArray(boneMatrices, i * 16); + } + if (boneTexture !== null) { + boneTexture.needsUpdate = true; + } + } + clone() { + return new Skeleton(this.bones, this.boneInverses); + } + computeBoneTexture() { + let size = Math.sqrt(this.bones.length * 4); + size = Math.ceil(size / 4) * 4; + size = Math.max(size, 4); + const boneMatrices = new Float32Array(size * size * 4); + boneMatrices.set(this.boneMatrices); + const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType); + boneTexture.needsUpdate = true; + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + return this; + } + getBoneByName(name2) { + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone.name === name2) { + return bone; + } + } + return; + } + dispose() { + if (this.boneTexture !== null) { + this.boneTexture.dispose(); + this.boneTexture = null; + } + } + fromJSON(json, bones) { + this.uuid = json.uuid; + for (let i = 0, l = json.bones.length;i < l; i++) { + const uuid = json.bones[i]; + let bone = bones[uuid]; + if (bone === undefined) { + console.warn("THREE.Skeleton: No bone found with UUID:", uuid); + bone = new Bone; + } + this.bones.push(bone); + this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i])); + } + this.init(); + return this; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "Skeleton", + generator: "Skeleton.toJSON" + }, + bones: [], + boneInverses: [] + }; + data2.uuid = this.uuid; + const bones = this.bones; + const boneInverses = this.boneInverses; + for (let i = 0, l = bones.length;i < l; i++) { + const bone = bones[i]; + data2.bones.push(bone.uuid); + const boneInverse = boneInverses[i]; + data2.boneInverses.push(boneInverse.toArray()); + } + return data2; + } +} + +class InstancedBufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized, meshPerAttribute = 1) { + super(array, itemSize, normalized); + this.isInstancedBufferAttribute = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.meshPerAttribute = this.meshPerAttribute; + data2.isInstancedBufferAttribute = true; + return data2; + } +} +var _instanceLocalMatrix = /* @__PURE__ */ new Matrix4; +var _instanceWorldMatrix = /* @__PURE__ */ new Matrix4; +var _instanceIntersects = []; +var _box3 = /* @__PURE__ */ new Box3; +var _identity = /* @__PURE__ */ new Matrix4; +var _mesh$1 = /* @__PURE__ */ new Mesh; +var _sphere$4 = /* @__PURE__ */ new Sphere; + +class InstancedMesh extends Mesh { + constructor(geometry, material, count) { + super(geometry, material); + this.isInstancedMesh = true; + this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16); + this.instanceColor = null; + this.morphTexture = null; + this.count = count; + this.boundingBox = null; + this.boundingSphere = null; + for (let i = 0;i < count; i++) { + this.setMatrixAt(i, _identity); + } + } + computeBoundingBox() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingBox === null) { + this.boundingBox = new Box3; + } + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + this.boundingBox.makeEmpty(); + for (let i = 0;i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix); + _box3.copy(geometry.boundingBox).applyMatrix4(_instanceLocalMatrix); + this.boundingBox.union(_box3); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere; + } + if (geometry.boundingSphere === null) { + geometry.computeBoundingSphere(); + } + this.boundingSphere.makeEmpty(); + for (let i = 0;i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix); + _sphere$4.copy(geometry.boundingSphere).applyMatrix4(_instanceLocalMatrix); + this.boundingSphere.union(_sphere$4); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.instanceMatrix.copy(source.instanceMatrix); + if (source.morphTexture !== null) + this.morphTexture = source.morphTexture.clone(); + if (source.instanceColor !== null) + this.instanceColor = source.instanceColor.clone(); + this.count = source.count; + if (source.boundingBox !== null) + this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) + this.boundingSphere = source.boundingSphere.clone(); + return this; + } + getColorAt(index2, color) { + color.fromArray(this.instanceColor.array, index2 * 3); + } + getMatrixAt(index2, matrix) { + matrix.fromArray(this.instanceMatrix.array, index2 * 16); + } + getMorphAt(index2, object) { + const objectInfluences = object.morphTargetInfluences; + const array = this.morphTexture.source.data.data; + const len = objectInfluences.length + 1; + const dataIndex = index2 * len + 1; + for (let i = 0;i < objectInfluences.length; i++) { + objectInfluences[i] = array[dataIndex + i]; + } + } + raycast(raycaster, intersects) { + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + _mesh$1.geometry = this.geometry; + _mesh$1.material = this.material; + if (_mesh$1.material === undefined) + return; + if (this.boundingSphere === null) + this.computeBoundingSphere(); + _sphere$4.copy(this.boundingSphere); + _sphere$4.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$4) === false) + return; + for (let instanceId = 0;instanceId < raycastTimes; instanceId++) { + this.getMatrixAt(instanceId, _instanceLocalMatrix); + _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); + _mesh$1.matrixWorld = _instanceWorldMatrix; + _mesh$1.raycast(raycaster, _instanceIntersects); + for (let i = 0, l = _instanceIntersects.length;i < l; i++) { + const intersect = _instanceIntersects[i]; + intersect.instanceId = instanceId; + intersect.object = this; + intersects.push(intersect); + } + _instanceIntersects.length = 0; + } + } + setColorAt(index2, color) { + if (this.instanceColor === null) { + this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3); + } + color.toArray(this.instanceColor.array, index2 * 3); + } + setMatrixAt(index2, matrix) { + matrix.toArray(this.instanceMatrix.array, index2 * 16); + } + setMorphAt(index2, object) { + const objectInfluences = object.morphTargetInfluences; + const len = objectInfluences.length + 1; + if (this.morphTexture === null) { + this.morphTexture = new DataTexture(new Float32Array(len * this.count), len, this.count, RedFormat, FloatType); + } + const array = this.morphTexture.source.data.data; + let morphInfluencesSum = 0; + for (let i = 0;i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + const dataIndex = len * index2; + array[dataIndex] = morphBaseInfluence; + array.set(objectInfluences, dataIndex + 1); + } + updateMorphTargets() { + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + if (this.morphTexture !== null) { + this.morphTexture.dispose(); + this.morphTexture = null; + } + return this; + } +} +var _vector1 = /* @__PURE__ */ new Vector3; +var _vector2 = /* @__PURE__ */ new Vector3; +var _normalMatrix = /* @__PURE__ */ new Matrix3; + +class Plane { + constructor(normal = new Vector3(1, 0, 0), constant = 0) { + this.isPlane = true; + this.normal = normal; + this.constant = constant; + } + set(normal, constant) { + this.normal.copy(normal); + this.constant = constant; + return this; + } + setComponents(x, y, z, w) { + this.normal.set(x, y, z); + this.constant = w; + return this; + } + setFromNormalAndCoplanarPoint(normal, point) { + this.normal.copy(normal); + this.constant = -point.dot(this.normal); + return this; + } + setFromCoplanarPoints(a, b, c) { + const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); + this.setFromNormalAndCoplanarPoint(normal, a); + return this; + } + copy(plane) { + this.normal.copy(plane.normal); + this.constant = plane.constant; + return this; + } + normalize() { + const inverseNormalLength = 1 / this.normal.length(); + this.normal.multiplyScalar(inverseNormalLength); + this.constant *= inverseNormalLength; + return this; + } + negate() { + this.constant *= -1; + this.normal.negate(); + return this; + } + distanceToPoint(point) { + return this.normal.dot(point) + this.constant; + } + distanceToSphere(sphere) { + return this.distanceToPoint(sphere.center) - sphere.radius; + } + projectPoint(point, target) { + return target.copy(point).addScaledVector(this.normal, -this.distanceToPoint(point)); + } + intersectLine(line, target) { + const direction = line.delta(_vector1); + const denominator = this.normal.dot(direction); + if (denominator === 0) { + if (this.distanceToPoint(line.start) === 0) { + return target.copy(line.start); + } + return null; + } + const t = -(line.start.dot(this.normal) + this.constant) / denominator; + if (t < 0 || t > 1) { + return null; + } + return target.copy(line.start).addScaledVector(direction, t); + } + intersectsLine(line) { + const startSign = this.distanceToPoint(line.start); + const endSign = this.distanceToPoint(line.end); + return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0; + } + intersectsBox(box) { + return box.intersectsPlane(this); + } + intersectsSphere(sphere) { + return sphere.intersectsPlane(this); + } + coplanarPoint(target) { + return target.copy(this.normal).multiplyScalar(-this.constant); + } + applyMatrix4(matrix, optionalNormalMatrix) { + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix); + const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix); + const normal = this.normal.applyMatrix3(normalMatrix).normalize(); + this.constant = -referencePoint.dot(normal); + return this; + } + translate(offset) { + this.constant -= offset.dot(this.normal); + return this; + } + equals(plane) { + return plane.normal.equals(this.normal) && plane.constant === this.constant; + } + clone() { + return new this.constructor().copy(this); + } +} +var _sphere$3 = /* @__PURE__ */ new Sphere; +var _vector$6 = /* @__PURE__ */ new Vector3; + +class Frustum { + constructor(p0 = new Plane, p1 = new Plane, p2 = new Plane, p3 = new Plane, p4 = new Plane, p5 = new Plane) { + this.planes = [p0, p1, p2, p3, p4, p5]; + } + set(p0, p1, p2, p3, p4, p5) { + const planes = this.planes; + planes[0].copy(p0); + planes[1].copy(p1); + planes[2].copy(p2); + planes[3].copy(p3); + planes[4].copy(p4); + planes[5].copy(p5); + return this; + } + copy(frustum) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + planes[i].copy(frustum.planes[i]); + } + return this; + } + setFromProjectionMatrix(m, coordinateSystem = WebGLCoordinateSystem) { + const planes = this.planes; + const me = m.elements; + const me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3]; + const me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7]; + const me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11]; + const me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15]; + planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize(); + planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize(); + planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize(); + planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize(); + planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); + if (coordinateSystem === WebGLCoordinateSystem) { + planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize(); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + planes[5].setComponents(me2, me6, me10, me14).normalize(); + } else { + throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + coordinateSystem); + } + return this; + } + intersectsObject(object) { + if (object.boundingSphere !== undefined) { + if (object.boundingSphere === null) + object.computeBoundingSphere(); + _sphere$3.copy(object.boundingSphere).applyMatrix4(object.matrixWorld); + } else { + const geometry = object.geometry; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$3.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld); + } + return this.intersectsSphere(_sphere$3); + } + intersectsSprite(sprite) { + _sphere$3.center.set(0, 0, 0); + _sphere$3.radius = 0.7071067811865476; + _sphere$3.applyMatrix4(sprite.matrixWorld); + return this.intersectsSphere(_sphere$3); + } + intersectsSphere(sphere) { + const planes = this.planes; + const center = sphere.center; + const negRadius = -sphere.radius; + for (let i = 0;i < 6; i++) { + const distance = planes[i].distanceToPoint(center); + if (distance < negRadius) { + return false; + } + } + return true; + } + intersectsBox(box) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + const plane = planes[i]; + _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z; + if (plane.distanceToPoint(_vector$6) < 0) { + return false; + } + } + return true; + } + containsPoint(point) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + if (planes[i].distanceToPoint(point) < 0) { + return false; + } + } + return true; + } + clone() { + return new this.constructor().copy(this); + } +} +function ascIdSort(a, b) { + return a - b; +} +function sortOpaque(a, b) { + return a.z - b.z; +} +function sortTransparent(a, b) { + return b.z - a.z; +} + +class MultiDrawRenderList { + constructor() { + this.index = 0; + this.pool = []; + this.list = []; + } + push(start, count, z, index2) { + const pool = this.pool; + const list = this.list; + if (this.index >= pool.length) { + pool.push({ + start: -1, + count: -1, + z: -1, + index: -1 + }); + } + const item = pool[this.index]; + list.push(item); + this.index++; + item.start = start; + item.count = count; + item.z = z; + item.index = index2; + } + reset() { + this.list.length = 0; + this.index = 0; + } +} +var _matrix$1 = /* @__PURE__ */ new Matrix4; +var _whiteColor = /* @__PURE__ */ new Color(1, 1, 1); +var _frustum = /* @__PURE__ */ new Frustum; +var _box$1 = /* @__PURE__ */ new Box3; +var _sphere$2 = /* @__PURE__ */ new Sphere; +var _vector$5 = /* @__PURE__ */ new Vector3; +var _forward = /* @__PURE__ */ new Vector3; +var _temp = /* @__PURE__ */ new Vector3; +var _renderList = /* @__PURE__ */ new MultiDrawRenderList; +var _mesh = /* @__PURE__ */ new Mesh; +var _batchIntersects = []; +function copyAttributeData(src, target, targetOffset = 0) { + const itemSize = target.itemSize; + if (src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor) { + const vertexCount = src.count; + for (let i = 0;i < vertexCount; i++) { + for (let c = 0;c < itemSize; c++) { + target.setComponent(i + targetOffset, c, src.getComponent(i, c)); + } + } + } else { + target.array.set(src.array, targetOffset * itemSize); + } + target.needsUpdate = true; +} +function copyArrayContents(src, target) { + if (src.constructor !== target.constructor) { + const len = Math.min(src.length, target.length); + for (let i = 0;i < len; i++) { + target[i] = src[i]; + } + } else { + const len = Math.min(src.length, target.length); + target.set(new src.constructor(src.buffer, 0, len)); + } +} + +class BatchedMesh extends Mesh { + get maxInstanceCount() { + return this._maxInstanceCount; + } + get instanceCount() { + return this._instanceInfo.length - this._availableInstanceIds.length; + } + get unusedVertexCount() { + return this._maxVertexCount - this._nextVertexStart; + } + get unusedIndexCount() { + return this._maxIndexCount - this._nextIndexStart; + } + constructor(maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material) { + super(new BufferGeometry, material); + this.isBatchedMesh = true; + this.perObjectFrustumCulled = true; + this.sortObjects = true; + this.boundingBox = null; + this.boundingSphere = null; + this.customSort = null; + this._instanceInfo = []; + this._geometryInfo = []; + this._availableInstanceIds = []; + this._availableGeometryIds = []; + this._nextIndexStart = 0; + this._nextVertexStart = 0; + this._geometryCount = 0; + this._visibilityChanged = true; + this._geometryInitialized = false; + this._maxInstanceCount = maxInstanceCount; + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + this._multiDrawCounts = new Int32Array(maxInstanceCount); + this._multiDrawStarts = new Int32Array(maxInstanceCount); + this._multiDrawCount = 0; + this._multiDrawInstances = null; + this._matricesTexture = null; + this._indirectTexture = null; + this._colorsTexture = null; + this._initMatricesTexture(); + this._initIndirectTexture(); + } + _initMatricesTexture() { + let size = Math.sqrt(this._maxInstanceCount * 4); + size = Math.ceil(size / 4) * 4; + size = Math.max(size, 4); + const matricesArray = new Float32Array(size * size * 4); + const matricesTexture = new DataTexture(matricesArray, size, size, RGBAFormat, FloatType); + this._matricesTexture = matricesTexture; + } + _initIndirectTexture() { + let size = Math.sqrt(this._maxInstanceCount); + size = Math.ceil(size); + const indirectArray = new Uint32Array(size * size); + const indirectTexture = new DataTexture(indirectArray, size, size, RedIntegerFormat, UnsignedIntType); + this._indirectTexture = indirectTexture; + } + _initColorsTexture() { + let size = Math.sqrt(this._maxInstanceCount); + size = Math.ceil(size); + const colorsArray = new Float32Array(size * size * 4).fill(1); + const colorsTexture = new DataTexture(colorsArray, size, size, RGBAFormat, FloatType); + colorsTexture.colorSpace = ColorManagement.workingColorSpace; + this._colorsTexture = colorsTexture; + } + _initializeGeometry(reference) { + const geometry = this.geometry; + const maxVertexCount = this._maxVertexCount; + const maxIndexCount = this._maxIndexCount; + if (this._geometryInitialized === false) { + for (const attributeName in reference.attributes) { + const srcAttribute = reference.getAttribute(attributeName); + const { array, itemSize, normalized } = srcAttribute; + const dstArray = new array.constructor(maxVertexCount * itemSize); + const dstAttribute = new BufferAttribute(dstArray, itemSize, normalized); + geometry.setAttribute(attributeName, dstAttribute); + } + if (reference.getIndex() !== null) { + const indexArray = maxVertexCount > 65535 ? new Uint32Array(maxIndexCount) : new Uint16Array(maxIndexCount); + geometry.setIndex(new BufferAttribute(indexArray, 1)); + } + this._geometryInitialized = true; + } + } + _validateGeometry(geometry) { + const batchGeometry = this.geometry; + if (Boolean(geometry.getIndex()) !== Boolean(batchGeometry.getIndex())) { + throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".'); + } + for (const attributeName in batchGeometry.attributes) { + if (!geometry.hasAttribute(attributeName)) { + throw new Error(`THREE.BatchedMesh: Added geometry missing "${attributeName}". All geometries must have consistent attributes.`); + } + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + if (srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized) { + throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value."); + } + } + } + validateInstanceId(instanceId) { + const instanceInfo = this._instanceInfo; + if (instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[instanceId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.`); + } + } + validateGeometryId(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.`); + } + } + setCustomSort(func) { + this.customSort = func; + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box3; + } + const boundingBox = this.boundingBox; + const instanceInfo = this._instanceInfo; + boundingBox.makeEmpty(); + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].active === false) + continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$1); + this.getBoundingBoxAt(geometryId, _box$1).applyMatrix4(_matrix$1); + boundingBox.union(_box$1); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere; + } + const boundingSphere = this.boundingSphere; + const instanceInfo = this._instanceInfo; + boundingSphere.makeEmpty(); + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].active === false) + continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$1); + this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1); + boundingSphere.union(_sphere$2); + } + } + addInstance(geometryId) { + const atCapacity = this._instanceInfo.length >= this.maxInstanceCount; + if (atCapacity && this._availableInstanceIds.length === 0) { + throw new Error("THREE.BatchedMesh: Maximum item count reached."); + } + const instanceInfo = { + visible: true, + active: true, + geometryIndex: geometryId + }; + let drawId = null; + if (this._availableInstanceIds.length > 0) { + this._availableInstanceIds.sort(ascIdSort); + drawId = this._availableInstanceIds.shift(); + this._instanceInfo[drawId] = instanceInfo; + } else { + drawId = this._instanceInfo.length; + this._instanceInfo.push(instanceInfo); + } + const matricesTexture = this._matricesTexture; + _matrix$1.identity().toArray(matricesTexture.image.data, drawId * 16); + matricesTexture.needsUpdate = true; + const colorsTexture = this._colorsTexture; + if (colorsTexture) { + _whiteColor.toArray(colorsTexture.image.data, drawId * 4); + colorsTexture.needsUpdate = true; + } + this._visibilityChanged = true; + return drawId; + } + addGeometry(geometry, reservedVertexCount = -1, reservedIndexCount = -1) { + this._initializeGeometry(geometry); + this._validateGeometry(geometry); + const geometryInfo = { + vertexStart: -1, + vertexCount: -1, + reservedVertexCount: -1, + indexStart: -1, + indexCount: -1, + reservedIndexCount: -1, + start: -1, + count: -1, + boundingBox: null, + boundingSphere: null, + active: true + }; + const geometryInfoList = this._geometryInfo; + geometryInfo.vertexStart = this._nextVertexStart; + geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute("position").count : reservedVertexCount; + const index2 = geometry.getIndex(); + const hasIndex = index2 !== null; + if (hasIndex) { + geometryInfo.indexStart = this._nextIndexStart; + geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index2.count : reservedIndexCount; + } + if (geometryInfo.indexStart !== -1 && geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount || geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size."); + } + let geometryId; + if (this._availableGeometryIds.length > 0) { + this._availableGeometryIds.sort(ascIdSort); + geometryId = this._availableGeometryIds.shift(); + geometryInfoList[geometryId] = geometryInfo; + } else { + geometryId = this._geometryCount; + this._geometryCount++; + geometryInfoList.push(geometryInfo); + } + this.setGeometryAt(geometryId, geometry); + this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + return geometryId; + } + setGeometryAt(geometryId, geometry) { + if (geometryId >= this._geometryCount) { + throw new Error("THREE.BatchedMesh: Maximum geometry count reached."); + } + this._validateGeometry(geometry); + const batchGeometry = this.geometry; + const hasIndex = batchGeometry.getIndex() !== null; + const dstIndex = batchGeometry.getIndex(); + const srcIndex = geometry.getIndex(); + const geometryInfo = this._geometryInfo[geometryId]; + if (hasIndex && srcIndex.count > geometryInfo.reservedIndexCount || geometry.attributes.position.count > geometryInfo.reservedVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry."); + } + const vertexStart = geometryInfo.vertexStart; + const reservedVertexCount = geometryInfo.reservedVertexCount; + geometryInfo.vertexCount = geometry.getAttribute("position").count; + for (const attributeName in batchGeometry.attributes) { + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + copyAttributeData(srcAttribute, dstAttribute, vertexStart); + const itemSize = srcAttribute.itemSize; + for (let i = srcAttribute.count, l = reservedVertexCount;i < l; i++) { + const index2 = vertexStart + i; + for (let c = 0;c < itemSize; c++) { + dstAttribute.setComponent(index2, c, 0); + } + } + dstAttribute.needsUpdate = true; + dstAttribute.addUpdateRange(vertexStart * itemSize, reservedVertexCount * itemSize); + } + if (hasIndex) { + const indexStart = geometryInfo.indexStart; + const reservedIndexCount = geometryInfo.reservedIndexCount; + geometryInfo.indexCount = geometry.getIndex().count; + for (let i = 0;i < srcIndex.count; i++) { + dstIndex.setX(indexStart + i, vertexStart + srcIndex.getX(i)); + } + for (let i = srcIndex.count, l = reservedIndexCount;i < l; i++) { + dstIndex.setX(indexStart + i, vertexStart); + } + dstIndex.needsUpdate = true; + dstIndex.addUpdateRange(indexStart, geometryInfo.reservedIndexCount); + } + geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart; + geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount; + geometryInfo.boundingBox = null; + if (geometry.boundingBox !== null) { + geometryInfo.boundingBox = geometry.boundingBox.clone(); + } + geometryInfo.boundingSphere = null; + if (geometry.boundingSphere !== null) { + geometryInfo.boundingSphere = geometry.boundingSphere.clone(); + } + this._visibilityChanged = true; + return geometryId; + } + deleteGeometry(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + return this; + } + const instanceInfo = this._instanceInfo; + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].active && instanceInfo[i].geometryIndex === geometryId) { + this.deleteInstance(i); + } + } + geometryInfoList[geometryId].active = false; + this._availableGeometryIds.push(geometryId); + this._visibilityChanged = true; + return this; + } + deleteInstance(instanceId) { + this.validateInstanceId(instanceId); + this._instanceInfo[instanceId].active = false; + this._availableInstanceIds.push(instanceId); + this._visibilityChanged = true; + return this; + } + optimize() { + let nextVertexStart = 0; + let nextIndexStart = 0; + const geometryInfoList = this._geometryInfo; + const indices = geometryInfoList.map((e, i) => i).sort((a, b) => { + return geometryInfoList[a].vertexStart - geometryInfoList[b].vertexStart; + }); + const geometry = this.geometry; + for (let i = 0, l = geometryInfoList.length;i < l; i++) { + const index2 = indices[i]; + const geometryInfo = geometryInfoList[index2]; + if (geometryInfo.active === false) { + continue; + } + if (geometry.index !== null) { + if (geometryInfo.indexStart !== nextIndexStart) { + const { indexStart, vertexStart, reservedIndexCount } = geometryInfo; + const index3 = geometry.index; + const array = index3.array; + const elementDelta = nextVertexStart - vertexStart; + for (let j = indexStart;j < indexStart + reservedIndexCount; j++) { + array[j] = array[j] + elementDelta; + } + index3.array.copyWithin(nextIndexStart, indexStart, indexStart + reservedIndexCount); + index3.addUpdateRange(nextIndexStart, reservedIndexCount); + geometryInfo.indexStart = nextIndexStart; + } + nextIndexStart += geometryInfo.reservedIndexCount; + } + if (geometryInfo.vertexStart !== nextVertexStart) { + const { vertexStart, reservedVertexCount } = geometryInfo; + const attributes = geometry.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + const { array, itemSize } = attribute; + array.copyWithin(nextVertexStart * itemSize, vertexStart * itemSize, (vertexStart + reservedVertexCount) * itemSize); + attribute.addUpdateRange(nextVertexStart * itemSize, reservedVertexCount * itemSize); + } + geometryInfo.vertexStart = nextVertexStart; + } + nextVertexStart += geometryInfo.reservedVertexCount; + geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart; + this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + } + return this; + } + getBoundingBoxAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingBox === null) { + const box = new Box3; + const index2 = geometry.index; + const position2 = geometry.attributes.position; + for (let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count;i < l; i++) { + let iv = i; + if (index2) { + iv = index2.getX(iv); + } + box.expandByPoint(_vector$5.fromBufferAttribute(position2, iv)); + } + geometryInfo.boundingBox = box; + } + target.copy(geometryInfo.boundingBox); + return target; + } + getBoundingSphereAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingSphere === null) { + const sphere = new Sphere; + this.getBoundingBoxAt(geometryId, _box$1); + _box$1.getCenter(sphere.center); + const index2 = geometry.index; + const position2 = geometry.attributes.position; + let maxRadiusSq = 0; + for (let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count;i < l; i++) { + let iv = i; + if (index2) { + iv = index2.getX(iv); + } + _vector$5.fromBufferAttribute(position2, iv); + maxRadiusSq = Math.max(maxRadiusSq, sphere.center.distanceToSquared(_vector$5)); + } + sphere.radius = Math.sqrt(maxRadiusSq); + geometryInfo.boundingSphere = sphere; + } + target.copy(geometryInfo.boundingSphere); + return target; + } + setMatrixAt(instanceId, matrix) { + this.validateInstanceId(instanceId); + const matricesTexture = this._matricesTexture; + const matricesArray = this._matricesTexture.image.data; + matrix.toArray(matricesArray, instanceId * 16); + matricesTexture.needsUpdate = true; + return this; + } + getMatrixAt(instanceId, matrix) { + this.validateInstanceId(instanceId); + return matrix.fromArray(this._matricesTexture.image.data, instanceId * 16); + } + setColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + if (this._colorsTexture === null) { + this._initColorsTexture(); + } + color.toArray(this._colorsTexture.image.data, instanceId * 4); + this._colorsTexture.needsUpdate = true; + return this; + } + getColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + return color.fromArray(this._colorsTexture.image.data, instanceId * 4); + } + setVisibleAt(instanceId, value2) { + this.validateInstanceId(instanceId); + if (this._instanceInfo[instanceId].visible === value2) { + return this; + } + this._instanceInfo[instanceId].visible = value2; + this._visibilityChanged = true; + return this; + } + getVisibleAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].visible; + } + setGeometryIdAt(instanceId, geometryId) { + this.validateInstanceId(instanceId); + this.validateGeometryId(geometryId); + this._instanceInfo[instanceId].geometryIndex = geometryId; + return this; + } + getGeometryIdAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].geometryIndex; + } + getGeometryRangeAt(geometryId, target = {}) { + this.validateGeometryId(geometryId); + const geometryInfo = this._geometryInfo[geometryId]; + target.vertexStart = geometryInfo.vertexStart; + target.vertexCount = geometryInfo.vertexCount; + target.reservedVertexCount = geometryInfo.reservedVertexCount; + target.indexStart = geometryInfo.indexStart; + target.indexCount = geometryInfo.indexCount; + target.reservedIndexCount = geometryInfo.reservedIndexCount; + target.start = geometryInfo.start; + target.count = geometryInfo.count; + return target; + } + setInstanceCount(maxInstanceCount) { + const availableInstanceIds = this._availableInstanceIds; + const instanceInfo = this._instanceInfo; + availableInstanceIds.sort(ascIdSort); + while (availableInstanceIds[availableInstanceIds.length - 1] === instanceInfo.length) { + instanceInfo.pop(); + availableInstanceIds.pop(); + } + if (maxInstanceCount < instanceInfo.length) { + throw new Error(`BatchedMesh: Instance ids outside the range ${maxInstanceCount} are being used. Cannot shrink instance count.`); + } + const multiDrawCounts = new Int32Array(maxInstanceCount); + const multiDrawStarts = new Int32Array(maxInstanceCount); + copyArrayContents(this._multiDrawCounts, multiDrawCounts); + copyArrayContents(this._multiDrawStarts, multiDrawStarts); + this._multiDrawCounts = multiDrawCounts; + this._multiDrawStarts = multiDrawStarts; + this._maxInstanceCount = maxInstanceCount; + const indirectTexture = this._indirectTexture; + const matricesTexture = this._matricesTexture; + const colorsTexture = this._colorsTexture; + indirectTexture.dispose(); + this._initIndirectTexture(); + copyArrayContents(indirectTexture.image.data, this._indirectTexture.image.data); + matricesTexture.dispose(); + this._initMatricesTexture(); + copyArrayContents(matricesTexture.image.data, this._matricesTexture.image.data); + if (colorsTexture) { + colorsTexture.dispose(); + this._initColorsTexture(); + copyArrayContents(colorsTexture.image.data, this._colorsTexture.image.data); + } + } + setGeometrySize(maxVertexCount, maxIndexCount) { + const validRanges = [...this._geometryInfo].filter((info) => info.active); + const requiredVertexLength = Math.max(...validRanges.map((range) => range.vertexStart + range.reservedVertexCount)); + if (requiredVertexLength > maxVertexCount) { + throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + if (this.geometry.index) { + const requiredIndexLength = Math.max(...validRanges.map((range) => range.indexStart + range.reservedIndexCount)); + if (requiredIndexLength > maxIndexCount) { + throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + } + const oldGeometry = this.geometry; + oldGeometry.dispose(); + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + if (this._geometryInitialized) { + this._geometryInitialized = false; + this.geometry = new BufferGeometry; + this._initializeGeometry(oldGeometry); + } + const geometry = this.geometry; + if (oldGeometry.index) { + copyArrayContents(oldGeometry.index.array, geometry.index.array); + } + for (const key2 in oldGeometry.attributes) { + copyArrayContents(oldGeometry.attributes[key2].array, geometry.attributes[key2].array); + } + } + raycast(raycaster, intersects) { + const instanceInfo = this._instanceInfo; + const geometryInfoList = this._geometryInfo; + const matrixWorld = this.matrixWorld; + const batchGeometry = this.geometry; + _mesh.material = this.material; + _mesh.geometry.index = batchGeometry.index; + _mesh.geometry.attributes = batchGeometry.attributes; + if (_mesh.geometry.boundingBox === null) { + _mesh.geometry.boundingBox = new Box3; + } + if (_mesh.geometry.boundingSphere === null) { + _mesh.geometry.boundingSphere = new Sphere; + } + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (!instanceInfo[i].visible || !instanceInfo[i].active) { + continue; + } + const geometryId = instanceInfo[i].geometryIndex; + const geometryInfo = geometryInfoList[geometryId]; + _mesh.geometry.setDrawRange(geometryInfo.start, geometryInfo.count); + this.getMatrixAt(i, _mesh.matrixWorld).premultiply(matrixWorld); + this.getBoundingBoxAt(geometryId, _mesh.geometry.boundingBox); + this.getBoundingSphereAt(geometryId, _mesh.geometry.boundingSphere); + _mesh.raycast(raycaster, _batchIntersects); + for (let j = 0, l2 = _batchIntersects.length;j < l2; j++) { + const intersect = _batchIntersects[j]; + intersect.object = this; + intersect.batchId = i; + intersects.push(intersect); + } + _batchIntersects.length = 0; + } + _mesh.material = null; + _mesh.geometry.index = null; + _mesh.geometry.attributes = {}; + _mesh.geometry.setDrawRange(0, Infinity); + } + copy(source) { + super.copy(source); + this.geometry = source.geometry.clone(); + this.perObjectFrustumCulled = source.perObjectFrustumCulled; + this.sortObjects = source.sortObjects; + this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null; + this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null; + this._geometryInfo = source._geometryInfo.map((info) => ({ + ...info, + boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null, + boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null + })); + this._instanceInfo = source._instanceInfo.map((info) => ({ ...info })); + this._maxInstanceCount = source._maxInstanceCount; + this._maxVertexCount = source._maxVertexCount; + this._maxIndexCount = source._maxIndexCount; + this._geometryInitialized = source._geometryInitialized; + this._geometryCount = source._geometryCount; + this._multiDrawCounts = source._multiDrawCounts.slice(); + this._multiDrawStarts = source._multiDrawStarts.slice(); + this._matricesTexture = source._matricesTexture.clone(); + this._matricesTexture.image.data = this._matricesTexture.image.data.slice(); + if (this._colorsTexture !== null) { + this._colorsTexture = source._colorsTexture.clone(); + this._colorsTexture.image.data = this._colorsTexture.image.data.slice(); + } + return this; + } + dispose() { + this.geometry.dispose(); + this._matricesTexture.dispose(); + this._matricesTexture = null; + this._indirectTexture.dispose(); + this._indirectTexture = null; + if (this._colorsTexture !== null) { + this._colorsTexture.dispose(); + this._colorsTexture = null; + } + return this; + } + onBeforeRender(renderer2, scene, camera, geometry, material) { + if (!this._visibilityChanged && !this.perObjectFrustumCulled && !this.sortObjects) { + return; + } + const index2 = geometry.getIndex(); + const bytesPerElement = index2 === null ? 1 : index2.array.BYTES_PER_ELEMENT; + const instanceInfo = this._instanceInfo; + const multiDrawStarts = this._multiDrawStarts; + const multiDrawCounts = this._multiDrawCounts; + const geometryInfoList = this._geometryInfo; + const perObjectFrustumCulled = this.perObjectFrustumCulled; + const indirectTexture = this._indirectTexture; + const indirectArray = indirectTexture.image.data; + if (perObjectFrustumCulled) { + _matrix$1.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).multiply(this.matrixWorld); + _frustum.setFromProjectionMatrix(_matrix$1, renderer2.coordinateSystem); + } + let multiDrawCount = 0; + if (this.sortObjects) { + _matrix$1.copy(this.matrixWorld).invert(); + _vector$5.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(_matrix$1); + _forward.set(0, 0, -1).transformDirection(camera.matrixWorld).transformDirection(_matrix$1); + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$1); + this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1); + let culled = false; + if (perObjectFrustumCulled) { + culled = !_frustum.intersectsSphere(_sphere$2); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + const z = _temp.subVectors(_sphere$2.center, _vector$5).dot(_forward); + _renderList.push(geometryInfo.start, geometryInfo.count, z, i); + } + } + } + const list = _renderList.list; + const customSort = this.customSort; + if (customSort === null) { + list.sort(material.transparent ? sortTransparent : sortOpaque); + } else { + customSort.call(this, list, camera); + } + for (let i = 0, l = list.length;i < l; i++) { + const item = list[i]; + multiDrawStarts[multiDrawCount] = item.start * bytesPerElement; + multiDrawCounts[multiDrawCount] = item.count; + indirectArray[multiDrawCount] = item.index; + multiDrawCount++; + } + _renderList.reset(); + } else { + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + let culled = false; + if (perObjectFrustumCulled) { + this.getMatrixAt(i, _matrix$1); + this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1); + culled = !_frustum.intersectsSphere(_sphere$2); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + multiDrawStarts[multiDrawCount] = geometryInfo.start * bytesPerElement; + multiDrawCounts[multiDrawCount] = geometryInfo.count; + indirectArray[multiDrawCount] = i; + multiDrawCount++; + } + } + } + } + indirectTexture.needsUpdate = true; + this._multiDrawCount = multiDrawCount; + this._visibilityChanged = false; + } + onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial) { + this.onBeforeRender(renderer2, null, shadowCamera, geometry, depthMaterial); + } +} + +class LineBasicMaterial extends Material { + constructor(parameters) { + super(); + this.isLineBasicMaterial = true; + this.type = "LineBasicMaterial"; + this.color = new Color(16777215); + this.map = null; + this.linewidth = 1; + this.linecap = "round"; + this.linejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + this.fog = source.fog; + return this; + } +} +var _vStart = /* @__PURE__ */ new Vector3; +var _vEnd = /* @__PURE__ */ new Vector3; +var _inverseMatrix$1 = /* @__PURE__ */ new Matrix4; +var _ray$1 = /* @__PURE__ */ new Ray; +var _sphere$1 = /* @__PURE__ */ new Sphere; +var _intersectPointOnRay = /* @__PURE__ */ new Vector3; +var _intersectPointOnSegment = /* @__PURE__ */ new Vector3; + +class Line extends Object3D { + constructor(geometry = new BufferGeometry, material = new LineBasicMaterial) { + super(); + this.isLine = true; + this.type = "Line"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = [0]; + for (let i = 1, l = positionAttribute.count;i < l; i++) { + _vStart.fromBufferAttribute(positionAttribute, i - 1); + _vEnd.fromBufferAttribute(positionAttribute, i); + lineDistances[i] = lineDistances[i - 1]; + lineDistances[i] += _vStart.distanceTo(_vEnd); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1)); + } else { + console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + raycast(raycaster, intersects) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$1.copy(geometry.boundingSphere); + _sphere$1.applyMatrix4(matrixWorld); + _sphere$1.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere$1) === false) + return; + _inverseMatrix$1.copy(matrixWorld).invert(); + _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const step = this.isLineSegments ? 2 : 1; + const index2 = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index2 !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, l = end - 1;i < l; i += step) { + const a = index2.getX(i); + const b = index2.getX(i + 1); + const intersect = checkIntersection(this, raycaster, _ray$1, localThresholdSq, a, b, i); + if (intersect) { + intersects.push(intersect); + } + } + if (this.isLineLoop) { + const a = index2.getX(end - 1); + const b = index2.getX(start); + const intersect = checkIntersection(this, raycaster, _ray$1, localThresholdSq, a, b, end - 1); + if (intersect) { + intersects.push(intersect); + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l = end - 1;i < l; i += step) { + const intersect = checkIntersection(this, raycaster, _ray$1, localThresholdSq, i, i + 1, i); + if (intersect) { + intersects.push(intersect); + } + } + if (this.isLineLoop) { + const intersect = checkIntersection(this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1); + if (intersect) { + intersects.push(intersect); + } + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } +} +function checkIntersection(object, raycaster, ray, thresholdSq, a, b, i) { + const positionAttribute = object.geometry.attributes.position; + _vStart.fromBufferAttribute(positionAttribute, a); + _vEnd.fromBufferAttribute(positionAttribute, b); + const distSq = ray.distanceSqToSegment(_vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment); + if (distSq > thresholdSq) + return; + _intersectPointOnRay.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectPointOnRay); + if (distance < raycaster.near || distance > raycaster.far) + return; + return { + distance, + point: _intersectPointOnSegment.clone().applyMatrix4(object.matrixWorld), + index: i, + face: null, + faceIndex: null, + barycoord: null, + object + }; +} +var _start = /* @__PURE__ */ new Vector3; +var _end = /* @__PURE__ */ new Vector3; + +class LineSegments extends Line { + constructor(geometry, material) { + super(geometry, material); + this.isLineSegments = true; + this.type = "LineSegments"; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + for (let i = 0, l = positionAttribute.count;i < l; i += 2) { + _start.fromBufferAttribute(positionAttribute, i); + _end.fromBufferAttribute(positionAttribute, i + 1); + lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1]; + lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1)); + } else { + console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } +} + +class LineLoop extends Line { + constructor(geometry, material) { + super(geometry, material); + this.isLineLoop = true; + this.type = "LineLoop"; + } +} + +class PointsMaterial extends Material { + constructor(parameters) { + super(); + this.isPointsMaterial = true; + this.type = "PointsMaterial"; + this.color = new Color(16777215); + this.map = null; + this.alphaMap = null; + this.size = 1; + this.sizeAttenuation = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } +} +var _inverseMatrix = /* @__PURE__ */ new Matrix4; +var _ray = /* @__PURE__ */ new Ray; +var _sphere = /* @__PURE__ */ new Sphere; +var _position$2 = /* @__PURE__ */ new Vector3; + +class Points extends Object3D { + constructor(geometry = new BufferGeometry, material = new PointsMaterial) { + super(); + this.isPoints = true; + this.type = "Points"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + raycast(raycaster, intersects) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere.copy(geometry.boundingSphere); + _sphere.applyMatrix4(matrixWorld); + _sphere.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere) === false) + return; + _inverseMatrix.copy(matrixWorld).invert(); + _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const index2 = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index2 !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i++) { + const a = index2.getX(i); + _position$2.fromBufferAttribute(positionAttribute, a); + testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this); + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l = end;i < l; i++) { + _position$2.fromBufferAttribute(positionAttribute, i); + testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this); + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } +} +function testPoint(point, index2, localThresholdSq, matrixWorld, raycaster, intersects, object) { + const rayPointDistanceSq = _ray.distanceSqToPoint(point); + if (rayPointDistanceSq < localThresholdSq) { + const intersectPoint = new Vector3; + _ray.closestPointToPoint(point, intersectPoint); + intersectPoint.applyMatrix4(matrixWorld); + const distance = raycaster.ray.origin.distanceTo(intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) + return; + intersects.push({ + distance, + distanceToRay: Math.sqrt(rayPointDistanceSq), + point: intersectPoint, + index: index2, + face: null, + faceIndex: null, + barycoord: null, + object + }); + } +} + +class VideoTexture extends Texture { + constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoTexture = true; + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.generateMipmaps = false; + const scope = this; + function updateVideo() { + scope.needsUpdate = true; + video.requestVideoFrameCallback(updateVideo); + } + if ("requestVideoFrameCallback" in video) { + video.requestVideoFrameCallback(updateVideo); + } + } + clone() { + return new this.constructor(this.image).copy(this); + } + update() { + const video = this.image; + const hasVideoFrameCallback = "requestVideoFrameCallback" in video; + if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) { + this.needsUpdate = true; + } + } +} + +class VideoFrameTexture extends VideoTexture { + constructor(mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super({}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoFrameTexture = true; + } + update() { + } + clone() { + return new this.constructor().copy(this); + } + setFrame(frame) { + this.image = frame; + this.needsUpdate = true; + } +} + +class FramebufferTexture extends Texture { + constructor(width2, height2) { + super({ width: width2, height: height2 }); + this.isFramebufferTexture = true; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.generateMipmaps = false; + this.needsUpdate = true; + } +} + +class CompressedTexture extends Texture { + constructor(mipmaps, width2, height2, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCompressedTexture = true; + this.image = { width: width2, height: height2 }; + this.mipmaps = mipmaps; + this.flipY = false; + this.generateMipmaps = false; + } +} + +class CompressedArrayTexture extends CompressedTexture { + constructor(mipmaps, width2, height2, depth, format, type) { + super(mipmaps, width2, height2, format, type); + this.isCompressedArrayTexture = true; + this.image.depth = depth; + this.wrapR = ClampToEdgeWrapping; + this.layerUpdates = new Set; + } + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + clearLayerUpdates() { + this.layerUpdates.clear(); + } +} + +class CompressedCubeTexture extends CompressedTexture { + constructor(images, format, type) { + super(undefined, images[0].width, images[0].height, format, type, CubeReflectionMapping); + this.isCompressedCubeTexture = true; + this.isCubeTexture = true; + this.image = images; + } +} + +class CanvasTexture extends Texture { + constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isCanvasTexture = true; + this.needsUpdate = true; + } +} + +class DepthTexture extends Texture { + constructor(width2, height2, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat) { + if (format !== DepthFormat && format !== DepthStencilFormat) { + throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); + } + if (type === undefined && format === DepthFormat) + type = UnsignedIntType; + if (type === undefined && format === DepthStencilFormat) + type = UnsignedInt248Type; + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isDepthTexture = true; + this.image = { width: width2, height: height2 }; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + this.flipY = false; + this.generateMipmaps = false; + this.compareFunction = null; + } + copy(source) { + super.copy(source); + this.compareFunction = source.compareFunction; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + if (this.compareFunction !== null) + data2.compareFunction = this.compareFunction; + return data2; + } +} + +class Curve { + constructor() { + this.type = "Curve"; + this.arcLengthDivisions = 200; + } + getPoint() { + console.warn("THREE.Curve: .getPoint() not implemented."); + return null; + } + getPointAt(u, optionalTarget) { + const t = this.getUtoTmapping(u); + return this.getPoint(t, optionalTarget); + } + getPoints(divisions = 5) { + const points = []; + for (let d = 0;d <= divisions; d++) { + points.push(this.getPoint(d / divisions)); + } + return points; + } + getSpacedPoints(divisions = 5) { + const points = []; + for (let d = 0;d <= divisions; d++) { + points.push(this.getPointAt(d / divisions)); + } + return points; + } + getLength() { + const lengths = this.getLengths(); + return lengths[lengths.length - 1]; + } + getLengths(divisions = this.arcLengthDivisions) { + if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) { + return this.cacheArcLengths; + } + this.needsUpdate = false; + const cache = []; + let current, last2 = this.getPoint(0); + let sum2 = 0; + cache.push(0); + for (let p = 1;p <= divisions; p++) { + current = this.getPoint(p / divisions); + sum2 += current.distanceTo(last2); + cache.push(sum2); + last2 = current; + } + this.cacheArcLengths = cache; + return cache; + } + updateArcLengths() { + this.needsUpdate = true; + this.getLengths(); + } + getUtoTmapping(u, distance) { + const arcLengths = this.getLengths(); + let i = 0; + const il = arcLengths.length; + let targetArcLength; + if (distance) { + targetArcLength = distance; + } else { + targetArcLength = u * arcLengths[il - 1]; + } + let low = 0, high = il - 1, comparison; + while (low <= high) { + i = Math.floor(low + (high - low) / 2); + comparison = arcLengths[i] - targetArcLength; + if (comparison < 0) { + low = i + 1; + } else if (comparison > 0) { + high = i - 1; + } else { + high = i; + break; + } + } + i = high; + if (arcLengths[i] === targetArcLength) { + return i / (il - 1); + } + const lengthBefore = arcLengths[i]; + const lengthAfter = arcLengths[i + 1]; + const segmentLength = lengthAfter - lengthBefore; + const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; + const t = (i + segmentFraction) / (il - 1); + return t; + } + getTangent(t, optionalTarget) { + const delta = 0.0001; + let t1 = t - delta; + let t2 = t + delta; + if (t1 < 0) + t1 = 0; + if (t2 > 1) + t2 = 1; + const pt1 = this.getPoint(t1); + const pt2 = this.getPoint(t2); + const tangent = optionalTarget || (pt1.isVector2 ? new Vector2 : new Vector3); + tangent.copy(pt2).sub(pt1).normalize(); + return tangent; + } + getTangentAt(u, optionalTarget) { + const t = this.getUtoTmapping(u); + return this.getTangent(t, optionalTarget); + } + computeFrenetFrames(segments, closed) { + const normal = new Vector3; + const tangents = []; + const normals = []; + const binormals = []; + const vec = new Vector3; + const mat = new Matrix4; + for (let i = 0;i <= segments; i++) { + const u = i / segments; + tangents[i] = this.getTangentAt(u, new Vector3); + } + normals[0] = new Vector3; + binormals[0] = new Vector3; + let min = Number.MAX_VALUE; + const tx = Math.abs(tangents[0].x); + const ty = Math.abs(tangents[0].y); + const tz = Math.abs(tangents[0].z); + if (tx <= min) { + min = tx; + normal.set(1, 0, 0); + } + if (ty <= min) { + min = ty; + normal.set(0, 1, 0); + } + if (tz <= min) { + normal.set(0, 0, 1); + } + vec.crossVectors(tangents[0], normal).normalize(); + normals[0].crossVectors(tangents[0], vec); + binormals[0].crossVectors(tangents[0], normals[0]); + for (let i = 1;i <= segments; i++) { + normals[i] = normals[i - 1].clone(); + binormals[i] = binormals[i - 1].clone(); + vec.crossVectors(tangents[i - 1], tangents[i]); + if (vec.length() > Number.EPSILON) { + vec.normalize(); + const theta = Math.acos(clamp2(tangents[i - 1].dot(tangents[i]), -1, 1)); + normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta)); + } + binormals[i].crossVectors(tangents[i], normals[i]); + } + if (closed === true) { + let theta = Math.acos(clamp2(normals[0].dot(normals[segments]), -1, 1)); + theta /= segments; + if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) { + theta = -theta; + } + for (let i = 1;i <= segments; i++) { + normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i)); + binormals[i].crossVectors(tangents[i], normals[i]); + } + } + return { + tangents, + normals, + binormals + }; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.arcLengthDivisions = source.arcLengthDivisions; + return this; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "Curve", + generator: "Curve.toJSON" + } + }; + data2.arcLengthDivisions = this.arcLengthDivisions; + data2.type = this.type; + return data2; + } + fromJSON(json) { + this.arcLengthDivisions = json.arcLengthDivisions; + return this; + } +} + +class EllipseCurve extends Curve { + constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) { + super(); + this.isEllipseCurve = true; + this.type = "EllipseCurve"; + this.aX = aX; + this.aY = aY; + this.xRadius = xRadius; + this.yRadius = yRadius; + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; + this.aClockwise = aClockwise; + this.aRotation = aRotation; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs(deltaAngle) < Number.EPSILON; + while (deltaAngle < 0) + deltaAngle += twoPi; + while (deltaAngle > twoPi) + deltaAngle -= twoPi; + if (deltaAngle < Number.EPSILON) { + if (samePoints) { + deltaAngle = 0; + } else { + deltaAngle = twoPi; + } + } + if (this.aClockwise === true && !samePoints) { + if (deltaAngle === twoPi) { + deltaAngle = -twoPi; + } else { + deltaAngle = deltaAngle - twoPi; + } + } + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos(angle); + let y = this.aY + this.yRadius * Math.sin(angle); + if (this.aRotation !== 0) { + const cos = Math.cos(this.aRotation); + const sin = Math.sin(this.aRotation); + const tx = x - this.aX; + const ty = y - this.aY; + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; + } + return point.set(x, y); + } + copy(source) { + super.copy(source); + this.aX = source.aX; + this.aY = source.aY; + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + this.aClockwise = source.aClockwise; + this.aRotation = source.aRotation; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.aX = this.aX; + data2.aY = this.aY; + data2.xRadius = this.xRadius; + data2.yRadius = this.yRadius; + data2.aStartAngle = this.aStartAngle; + data2.aEndAngle = this.aEndAngle; + data2.aClockwise = this.aClockwise; + data2.aRotation = this.aRotation; + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.aX = json.aX; + this.aY = json.aY; + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + this.aClockwise = json.aClockwise; + this.aRotation = json.aRotation; + return this; + } +} + +class ArcCurve extends EllipseCurve { + constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + this.isArcCurve = true; + this.type = "ArcCurve"; + } +} +function CubicPoly() { + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + function init(x0, x1, t0, t1) { + c0 = x0; + c1 = t0; + c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + } + return { + initCatmullRom: function(x0, x1, x2, x3, tension) { + init(x1, x2, tension * (x2 - x0), tension * (x3 - x1)); + }, + initNonuniformCatmullRom: function(x0, x1, x2, x3, dt0, dt1, dt2) { + let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1; + let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; + t1 *= dt1; + t2 *= dt1; + init(x1, x2, t1, t2); + }, + calc: function(t) { + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; + } + }; +} +var tmp = /* @__PURE__ */ new Vector3; +var px = /* @__PURE__ */ new CubicPoly; +var py = /* @__PURE__ */ new CubicPoly; +var pz = /* @__PURE__ */ new CubicPoly; + +class CatmullRomCurve3 extends Curve { + constructor(points = [], closed = false, curveType = "centripetal", tension = 0.5) { + super(); + this.isCatmullRomCurve3 = true; + this.type = "CatmullRomCurve3"; + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + } + getPoint(t, optionalTarget = new Vector3) { + const point = optionalTarget; + const points = this.points; + const l = points.length; + const p = (l - (this.closed ? 0 : 1)) * t; + let intPoint = Math.floor(p); + let weight = p - intPoint; + if (this.closed) { + intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l; + } else if (weight === 0 && intPoint === l - 1) { + intPoint = l - 2; + weight = 1; + } + let p0, p3; + if (this.closed || intPoint > 0) { + p0 = points[(intPoint - 1) % l]; + } else { + tmp.subVectors(points[0], points[1]).add(points[0]); + p0 = tmp; + } + const p1 = points[intPoint % l]; + const p2 = points[(intPoint + 1) % l]; + if (this.closed || intPoint + 2 < l) { + p3 = points[(intPoint + 2) % l]; + } else { + tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]); + p3 = tmp; + } + if (this.curveType === "centripetal" || this.curveType === "chordal") { + const pow = this.curveType === "chordal" ? 0.5 : 0.25; + let dt0 = Math.pow(p0.distanceToSquared(p1), pow); + let dt1 = Math.pow(p1.distanceToSquared(p2), pow); + let dt2 = Math.pow(p2.distanceToSquared(p3), pow); + if (dt1 < 0.0001) + dt1 = 1; + if (dt0 < 0.0001) + dt0 = dt1; + if (dt2 < 0.0001) + dt2 = dt1; + px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2); + py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2); + pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2); + } else if (this.curveType === "catmullrom") { + px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension); + py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension); + pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension); + } + point.set(px.calc(weight), py.calc(weight), pz.calc(weight)); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l = source.points.length;i < l; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.points = []; + for (let i = 0, l = this.points.length;i < l; i++) { + const point = this.points[i]; + data2.points.push(point.toArray()); + } + data2.closed = this.closed; + data2.curveType = this.curveType; + data2.tension = this.tension; + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l = json.points.length;i < l; i++) { + const point = json.points[i]; + this.points.push(new Vector3().fromArray(point)); + } + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + return this; + } +} +function CatmullRom(t, p0, p1, p2, p3) { + const v0 = (p2 - p0) * 0.5; + const v1 = (p3 - p1) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; +} +function QuadraticBezierP0(t, p) { + const k2 = 1 - t; + return k2 * k2 * p; +} +function QuadraticBezierP1(t, p) { + return 2 * (1 - t) * t * p; +} +function QuadraticBezierP2(t, p) { + return t * t * p; +} +function QuadraticBezier(t, p0, p1, p2) { + return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2); +} +function CubicBezierP0(t, p) { + const k2 = 1 - t; + return k2 * k2 * k2 * p; +} +function CubicBezierP1(t, p) { + const k2 = 1 - t; + return 3 * k2 * k2 * t * p; +} +function CubicBezierP2(t, p) { + return 3 * (1 - t) * t * t * p; +} +function CubicBezierP3(t, p) { + return t * t * t * p; +} +function CubicBezier(t, p0, p1, p2, p3) { + return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3); +} + +class CubicBezierCurve extends Curve { + constructor(v0 = new Vector2, v1 = new Vector2, v2 = new Vector2, v3 = new Vector2) { + super(); + this.isCubicBezierCurve = true; + this.type = "CubicBezierCurve"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + data2.v3 = this.v3.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } +} + +class CubicBezierCurve3 extends Curve { + constructor(v0 = new Vector3, v1 = new Vector3, v2 = new Vector3, v3 = new Vector3) { + super(); + this.isCubicBezierCurve3 = true; + this.type = "CubicBezierCurve3"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + } + getPoint(t, optionalTarget = new Vector3) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + data2.v3 = this.v3.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } +} + +class LineCurve extends Curve { + constructor(v1 = new Vector2, v2 = new Vector2) { + super(); + this.isLineCurve = true; + this.type = "LineCurve"; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + if (t === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t).add(this.v1); + } + return point; + } + getPointAt(u, optionalTarget) { + return this.getPoint(u, optionalTarget); + } + getTangent(t, optionalTarget = new Vector2) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u, optionalTarget) { + return this.getTangent(u, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } +} + +class LineCurve3 extends Curve { + constructor(v1 = new Vector3, v2 = new Vector3) { + super(); + this.isLineCurve3 = true; + this.type = "LineCurve3"; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector3) { + const point = optionalTarget; + if (t === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t).add(this.v1); + } + return point; + } + getPointAt(u, optionalTarget) { + return this.getPoint(u, optionalTarget); + } + getTangent(t, optionalTarget = new Vector3) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u, optionalTarget) { + return this.getTangent(u, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } +} + +class QuadraticBezierCurve extends Curve { + constructor(v0 = new Vector2, v1 = new Vector2, v2 = new Vector2) { + super(); + this.isQuadraticBezierCurve = true; + this.type = "QuadraticBezierCurve"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } +} + +class QuadraticBezierCurve3 extends Curve { + constructor(v0 = new Vector3, v1 = new Vector3, v2 = new Vector3) { + super(); + this.isQuadraticBezierCurve3 = true; + this.type = "QuadraticBezierCurve3"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector3) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } +} + +class SplineCurve extends Curve { + constructor(points = []) { + super(); + this.isSplineCurve = true; + this.type = "SplineCurve"; + this.points = points; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + const points = this.points; + const p = (points.length - 1) * t; + const intPoint = Math.floor(p); + const weight = p - intPoint; + const p0 = points[intPoint === 0 ? intPoint : intPoint - 1]; + const p1 = points[intPoint]; + const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1]; + const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2]; + point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y)); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l = source.points.length;i < l; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.points = []; + for (let i = 0, l = this.points.length;i < l; i++) { + const point = this.points[i]; + data2.points.push(point.toArray()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l = json.points.length;i < l; i++) { + const point = json.points[i]; + this.points.push(new Vector2().fromArray(point)); + } + return this; + } +} +var Curves = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ArcCurve, + CatmullRomCurve3, + CubicBezierCurve, + CubicBezierCurve3, + EllipseCurve, + LineCurve, + LineCurve3, + QuadraticBezierCurve, + QuadraticBezierCurve3, + SplineCurve +}); + +class CurvePath extends Curve { + constructor() { + super(); + this.type = "CurvePath"; + this.curves = []; + this.autoClose = false; + } + add(curve) { + this.curves.push(curve); + } + closePath() { + const startPoint = this.curves[0].getPoint(0); + const endPoint = this.curves[this.curves.length - 1].getPoint(1); + if (!startPoint.equals(endPoint)) { + const lineType = startPoint.isVector2 === true ? "LineCurve" : "LineCurve3"; + this.curves.push(new Curves[lineType](endPoint, startPoint)); + } + return this; + } + getPoint(t, optionalTarget) { + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + while (i < curveLengths.length) { + if (curveLengths[i] >= d) { + const diff = curveLengths[i] - d; + const curve = this.curves[i]; + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + return curve.getPointAt(u, optionalTarget); + } + i++; + } + return null; + } + getLength() { + const lens = this.getCurveLengths(); + return lens[lens.length - 1]; + } + updateArcLengths() { + this.needsUpdate = true; + this.cacheLengths = null; + this.getCurveLengths(); + } + getCurveLengths() { + if (this.cacheLengths && this.cacheLengths.length === this.curves.length) { + return this.cacheLengths; + } + const lengths = []; + let sums = 0; + for (let i = 0, l = this.curves.length;i < l; i++) { + sums += this.curves[i].getLength(); + lengths.push(sums); + } + this.cacheLengths = lengths; + return lengths; + } + getSpacedPoints(divisions = 40) { + const points = []; + for (let i = 0;i <= divisions; i++) { + points.push(this.getPoint(i / divisions)); + } + if (this.autoClose) { + points.push(points[0]); + } + return points; + } + getPoints(divisions = 12) { + const points = []; + let last2; + for (let i = 0, curves = this.curves;i < curves.length; i++) { + const curve = curves[i]; + const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions; + const pts = curve.getPoints(resolution); + for (let j = 0;j < pts.length; j++) { + const point = pts[j]; + if (last2 && last2.equals(point)) + continue; + points.push(point); + last2 = point; + } + } + if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) { + points.push(points[0]); + } + return points; + } + copy(source) { + super.copy(source); + this.curves = []; + for (let i = 0, l = source.curves.length;i < l; i++) { + const curve = source.curves[i]; + this.curves.push(curve.clone()); + } + this.autoClose = source.autoClose; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.autoClose = this.autoClose; + data2.curves = []; + for (let i = 0, l = this.curves.length;i < l; i++) { + const curve = this.curves[i]; + data2.curves.push(curve.toJSON()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.autoClose = json.autoClose; + this.curves = []; + for (let i = 0, l = json.curves.length;i < l; i++) { + const curve = json.curves[i]; + this.curves.push(new Curves[curve.type]().fromJSON(curve)); + } + return this; + } +} + +class Path extends CurvePath { + constructor(points) { + super(); + this.type = "Path"; + this.currentPoint = new Vector2; + if (points) { + this.setFromPoints(points); + } + } + setFromPoints(points) { + this.moveTo(points[0].x, points[0].y); + for (let i = 1, l = points.length;i < l; i++) { + this.lineTo(points[i].x, points[i].y); + } + return this; + } + moveTo(x, y) { + this.currentPoint.set(x, y); + return this; + } + lineTo(x, y) { + const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y)); + this.curves.push(curve); + this.currentPoint.set(x, y); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY)); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY)); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + splineThru(pts) { + const npts = [this.currentPoint.clone()].concat(pts); + const curve = new SplineCurve(npts); + this.curves.push(curve); + this.currentPoint.copy(pts[pts.length - 1]); + return this; + } + arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + return this; + } + absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + if (this.curves.length > 0) { + const firstPoint = curve.getPoint(0); + if (!firstPoint.equals(this.currentPoint)) { + this.lineTo(firstPoint.x, firstPoint.y); + } + } + this.curves.push(curve); + const lastPoint = curve.getPoint(1); + this.currentPoint.copy(lastPoint); + return this; + } + copy(source) { + super.copy(source); + this.currentPoint.copy(source.currentPoint); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.currentPoint = this.currentPoint.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.currentPoint.fromArray(json.currentPoint); + return this; + } +} + +class LatheGeometry extends BufferGeometry { + constructor(points = [new Vector2(0, -0.5), new Vector2(0.5, 0), new Vector2(0, 0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) { + super(); + this.type = "LatheGeometry"; + this.parameters = { + points, + segments, + phiStart, + phiLength + }; + segments = Math.floor(segments); + phiLength = clamp2(phiLength, 0, Math.PI * 2); + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; + const inverseSegments = 1 / segments; + const vertex = new Vector3; + const uv = new Vector2; + const normal = new Vector3; + const curNormal = new Vector3; + const prevNormal = new Vector3; + let dx = 0; + let dy = 0; + for (let j = 0;j <= points.length - 1; j++) { + switch (j) { + case 0: + dx = points[j + 1].x - points[j].x; + dy = points[j + 1].y - points[j].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + prevNormal.copy(normal); + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + break; + case points.length - 1: + initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z); + break; + default: + dx = points[j + 1].x - points[j].x; + dy = points[j + 1].y - points[j].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + curNormal.copy(normal); + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + prevNormal.copy(curNormal); + } + } + for (let i = 0;i <= segments; i++) { + const phi = phiStart + i * inverseSegments * phiLength; + const sin = Math.sin(phi); + const cos = Math.cos(phi); + for (let j = 0;j <= points.length - 1; j++) { + vertex.x = points[j].x * sin; + vertex.y = points[j].y; + vertex.z = points[j].x * cos; + vertices.push(vertex.x, vertex.y, vertex.z); + uv.x = i / segments; + uv.y = j / (points.length - 1); + uvs.push(uv.x, uv.y); + const x = initNormals[3 * j + 0] * sin; + const y = initNormals[3 * j + 1]; + const z = initNormals[3 * j + 0] * cos; + normals.push(x, y, z); + } + } + for (let i = 0;i < segments; i++) { + for (let j = 0;j < points.length - 1; j++) { + const base = j + i * points.length; + const a = base; + const b = base + points.length; + const c = base + points.length + 1; + const d = base + 1; + indices.push(a, b, d); + indices.push(c, d, b); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new LatheGeometry(data2.points, data2.segments, data2.phiStart, data2.phiLength); + } +} + +class CapsuleGeometry extends LatheGeometry { + constructor(radius = 1, length2 = 1, capSegments = 4, radialSegments = 8) { + const path = new Path; + path.absarc(0, -length2 / 2, radius, Math.PI * 1.5, 0); + path.absarc(0, length2 / 2, radius, 0, Math.PI * 0.5); + super(path.getPoints(capSegments), radialSegments); + this.type = "CapsuleGeometry"; + this.parameters = { + radius, + length: length2, + capSegments, + radialSegments + }; + } + static fromJSON(data2) { + return new CapsuleGeometry(data2.radius, data2.length, data2.capSegments, data2.radialSegments); + } +} + +class CircleGeometry extends BufferGeometry { + constructor(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CircleGeometry"; + this.parameters = { + radius, + segments, + thetaStart, + thetaLength + }; + segments = Math.max(3, segments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex = new Vector3; + const uv = new Vector2; + vertices.push(0, 0, 0); + normals.push(0, 0, 1); + uvs.push(0.5, 0.5); + for (let s = 0, i = 3;s <= segments; s++, i += 3) { + const segment = thetaStart + s / segments * thetaLength; + vertex.x = radius * Math.cos(segment); + vertex.y = radius * Math.sin(segment); + vertices.push(vertex.x, vertex.y, vertex.z); + normals.push(0, 0, 1); + uv.x = (vertices[i] / radius + 1) / 2; + uv.y = (vertices[i + 1] / radius + 1) / 2; + uvs.push(uv.x, uv.y); + } + for (let i = 1;i <= segments; i++) { + indices.push(i, i + 1, 0); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new CircleGeometry(data2.radius, data2.segments, data2.thetaStart, data2.thetaLength); + } +} + +class CylinderGeometry extends BufferGeometry { + constructor(radiusTop = 1, radiusBottom = 1, height2 = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CylinderGeometry"; + this.parameters = { + radiusTop, + radiusBottom, + height: height2, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + const scope = this; + radialSegments = Math.floor(radialSegments); + heightSegments = Math.floor(heightSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let index2 = 0; + const indexArray = []; + const halfHeight = height2 / 2; + let groupStart = 0; + generateTorso(); + if (openEnded === false) { + if (radiusTop > 0) + generateCap(true); + if (radiusBottom > 0) + generateCap(false); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function generateTorso() { + const normal = new Vector3; + const vertex = new Vector3; + let groupCount = 0; + const slope = (radiusBottom - radiusTop) / height2; + for (let y = 0;y <= heightSegments; y++) { + const indexRow = []; + const v = y / heightSegments; + const radius = v * (radiusBottom - radiusTop) + radiusTop; + for (let x = 0;x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const sinTheta = Math.sin(theta); + const cosTheta = Math.cos(theta); + vertex.x = radius * sinTheta; + vertex.y = -v * height2 + halfHeight; + vertex.z = radius * cosTheta; + vertices.push(vertex.x, vertex.y, vertex.z); + normal.set(sinTheta, slope, cosTheta).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u, 1 - v); + indexRow.push(index2++); + } + indexArray.push(indexRow); + } + for (let x = 0;x < radialSegments; x++) { + for (let y = 0;y < heightSegments; y++) { + const a = indexArray[y][x]; + const b = indexArray[y + 1][x]; + const c = indexArray[y + 1][x + 1]; + const d = indexArray[y][x + 1]; + if (radiusTop > 0 || y !== 0) { + indices.push(a, b, d); + groupCount += 3; + } + if (radiusBottom > 0 || y !== heightSegments - 1) { + indices.push(b, c, d); + groupCount += 3; + } + } + } + scope.addGroup(groupStart, groupCount, 0); + groupStart += groupCount; + } + function generateCap(top) { + const centerIndexStart = index2; + const uv = new Vector2; + const vertex = new Vector3; + let groupCount = 0; + const radius = top === true ? radiusTop : radiusBottom; + const sign = top === true ? 1 : -1; + for (let x = 1;x <= radialSegments; x++) { + vertices.push(0, halfHeight * sign, 0); + normals.push(0, sign, 0); + uvs.push(0.5, 0.5); + index2++; + } + const centerIndexEnd = index2; + for (let x = 0;x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const cosTheta = Math.cos(theta); + const sinTheta = Math.sin(theta); + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.push(vertex.x, vertex.y, vertex.z); + normals.push(0, sign, 0); + uv.x = cosTheta * 0.5 + 0.5; + uv.y = sinTheta * 0.5 * sign + 0.5; + uvs.push(uv.x, uv.y); + index2++; + } + for (let x = 0;x < radialSegments; x++) { + const c = centerIndexStart + x; + const i = centerIndexEnd + x; + if (top === true) { + indices.push(i, i + 1, c); + } else { + indices.push(i + 1, i, c); + } + groupCount += 3; + } + scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); + groupStart += groupCount; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new CylinderGeometry(data2.radiusTop, data2.radiusBottom, data2.height, data2.radialSegments, data2.heightSegments, data2.openEnded, data2.thetaStart, data2.thetaLength); + } +} + +class ConeGeometry extends CylinderGeometry { + constructor(radius = 1, height2 = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(0, radius, height2, radialSegments, heightSegments, openEnded, thetaStart, thetaLength); + this.type = "ConeGeometry"; + this.parameters = { + radius, + height: height2, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + } + static fromJSON(data2) { + return new ConeGeometry(data2.radius, data2.height, data2.radialSegments, data2.heightSegments, data2.openEnded, data2.thetaStart, data2.thetaLength); + } +} + +class PolyhedronGeometry extends BufferGeometry { + constructor(vertices = [], indices = [], radius = 1, detail = 0) { + super(); + this.type = "PolyhedronGeometry"; + this.parameters = { + vertices, + indices, + radius, + detail + }; + const vertexBuffer = []; + const uvBuffer = []; + subdivide(detail); + applyRadius(radius); + generateUVs(); + this.setAttribute("position", new Float32BufferAttribute(vertexBuffer, 3)); + this.setAttribute("normal", new Float32BufferAttribute(vertexBuffer.slice(), 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvBuffer, 2)); + if (detail === 0) { + this.computeVertexNormals(); + } else { + this.normalizeNormals(); + } + function subdivide(detail2) { + const a = new Vector3; + const b = new Vector3; + const c = new Vector3; + for (let i = 0;i < indices.length; i += 3) { + getVertexByIndex(indices[i + 0], a); + getVertexByIndex(indices[i + 1], b); + getVertexByIndex(indices[i + 2], c); + subdivideFace(a, b, c, detail2); + } + } + function subdivideFace(a, b, c, detail2) { + const cols = detail2 + 1; + const v = []; + for (let i = 0;i <= cols; i++) { + v[i] = []; + const aj = a.clone().lerp(c, i / cols); + const bj = b.clone().lerp(c, i / cols); + const rows = cols - i; + for (let j = 0;j <= rows; j++) { + if (j === 0 && i === cols) { + v[i][j] = aj; + } else { + v[i][j] = aj.clone().lerp(bj, j / rows); + } + } + } + for (let i = 0;i < cols; i++) { + for (let j = 0;j < 2 * (cols - i) - 1; j++) { + const k2 = Math.floor(j / 2); + if (j % 2 === 0) { + pushVertex(v[i][k2 + 1]); + pushVertex(v[i + 1][k2]); + pushVertex(v[i][k2]); + } else { + pushVertex(v[i][k2 + 1]); + pushVertex(v[i + 1][k2 + 1]); + pushVertex(v[i + 1][k2]); + } + } + } + } + function applyRadius(radius2) { + const vertex = new Vector3; + for (let i = 0;i < vertexBuffer.length; i += 3) { + vertex.x = vertexBuffer[i + 0]; + vertex.y = vertexBuffer[i + 1]; + vertex.z = vertexBuffer[i + 2]; + vertex.normalize().multiplyScalar(radius2); + vertexBuffer[i + 0] = vertex.x; + vertexBuffer[i + 1] = vertex.y; + vertexBuffer[i + 2] = vertex.z; + } + } + function generateUVs() { + const vertex = new Vector3; + for (let i = 0;i < vertexBuffer.length; i += 3) { + vertex.x = vertexBuffer[i + 0]; + vertex.y = vertexBuffer[i + 1]; + vertex.z = vertexBuffer[i + 2]; + const u = azimuth(vertex) / 2 / Math.PI + 0.5; + const v = inclination(vertex) / Math.PI + 0.5; + uvBuffer.push(u, 1 - v); + } + correctUVs(); + correctSeam(); + } + function correctSeam() { + for (let i = 0;i < uvBuffer.length; i += 6) { + const x0 = uvBuffer[i + 0]; + const x1 = uvBuffer[i + 2]; + const x2 = uvBuffer[i + 4]; + const max = Math.max(x0, x1, x2); + const min = Math.min(x0, x1, x2); + if (max > 0.9 && min < 0.1) { + if (x0 < 0.2) + uvBuffer[i + 0] += 1; + if (x1 < 0.2) + uvBuffer[i + 2] += 1; + if (x2 < 0.2) + uvBuffer[i + 4] += 1; + } + } + } + function pushVertex(vertex) { + vertexBuffer.push(vertex.x, vertex.y, vertex.z); + } + function getVertexByIndex(index2, vertex) { + const stride = index2 * 3; + vertex.x = vertices[stride + 0]; + vertex.y = vertices[stride + 1]; + vertex.z = vertices[stride + 2]; + } + function correctUVs() { + const a = new Vector3; + const b = new Vector3; + const c = new Vector3; + const centroid = new Vector3; + const uvA = new Vector2; + const uvB = new Vector2; + const uvC = new Vector2; + for (let i = 0, j = 0;i < vertexBuffer.length; i += 9, j += 6) { + a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]); + b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]); + c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]); + uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]); + uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]); + uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]); + centroid.copy(a).add(b).add(c).divideScalar(3); + const azi = azimuth(centroid); + correctUV(uvA, j + 0, a, azi); + correctUV(uvB, j + 2, b, azi); + correctUV(uvC, j + 4, c, azi); + } + } + function correctUV(uv, stride, vector, azimuth2) { + if (azimuth2 < 0 && uv.x === 1) { + uvBuffer[stride] = uv.x - 1; + } + if (vector.x === 0 && vector.z === 0) { + uvBuffer[stride] = azimuth2 / 2 / Math.PI + 0.5; + } + } + function azimuth(vector) { + return Math.atan2(vector.z, -vector.x); + } + function inclination(vector) { + return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new PolyhedronGeometry(data2.vertices, data2.indices, data2.radius, data2.details); + } +} + +class DodecahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const t = (1 + Math.sqrt(5)) / 2; + const r = 1 / t; + const vertices = [ + -1, + -1, + -1, + -1, + -1, + 1, + -1, + 1, + -1, + -1, + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + 1, + 1, + -1, + 1, + 1, + 1, + 0, + -r, + -t, + 0, + -r, + t, + 0, + r, + -t, + 0, + r, + t, + -r, + -t, + 0, + -r, + t, + 0, + r, + -t, + 0, + r, + t, + 0, + -t, + 0, + -r, + t, + 0, + -r, + -t, + 0, + r, + t, + 0, + r + ]; + const indices = [ + 3, + 11, + 7, + 3, + 7, + 15, + 3, + 15, + 13, + 7, + 19, + 17, + 7, + 17, + 6, + 7, + 6, + 15, + 17, + 4, + 8, + 17, + 8, + 10, + 17, + 10, + 6, + 8, + 0, + 16, + 8, + 16, + 2, + 8, + 2, + 10, + 0, + 12, + 1, + 0, + 1, + 18, + 0, + 18, + 16, + 6, + 10, + 2, + 6, + 2, + 13, + 6, + 13, + 15, + 2, + 16, + 18, + 2, + 18, + 3, + 2, + 3, + 13, + 18, + 1, + 9, + 18, + 9, + 11, + 18, + 11, + 3, + 4, + 14, + 12, + 4, + 12, + 0, + 4, + 0, + 8, + 11, + 9, + 5, + 11, + 5, + 19, + 11, + 19, + 7, + 19, + 5, + 14, + 19, + 14, + 4, + 19, + 4, + 17, + 1, + 12, + 14, + 1, + 14, + 5, + 1, + 5, + 9 + ]; + super(vertices, indices, radius, detail); + this.type = "DodecahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new DodecahedronGeometry(data2.radius, data2.detail); + } +} +var _v0 = /* @__PURE__ */ new Vector3; +var _v1$1 = /* @__PURE__ */ new Vector3; +var _normal = /* @__PURE__ */ new Vector3; +var _triangle = /* @__PURE__ */ new Triangle; + +class EdgesGeometry extends BufferGeometry { + constructor(geometry = null, thresholdAngle = 1) { + super(); + this.type = "EdgesGeometry"; + this.parameters = { + geometry, + thresholdAngle + }; + if (geometry !== null) { + const precisionPoints = 4; + const precision = Math.pow(10, precisionPoints); + const thresholdDot = Math.cos(DEG2RAD * thresholdAngle); + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute("position"); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + const indexArr = [0, 0, 0]; + const vertKeys = ["a", "b", "c"]; + const hashes = new Array(3); + const edgeData = {}; + const vertices = []; + for (let i = 0;i < indexCount; i += 3) { + if (indexAttr) { + indexArr[0] = indexAttr.getX(i); + indexArr[1] = indexAttr.getX(i + 1); + indexArr[2] = indexAttr.getX(i + 2); + } else { + indexArr[0] = i; + indexArr[1] = i + 1; + indexArr[2] = i + 2; + } + const { a, b, c } = _triangle; + a.fromBufferAttribute(positionAttr, indexArr[0]); + b.fromBufferAttribute(positionAttr, indexArr[1]); + c.fromBufferAttribute(positionAttr, indexArr[2]); + _triangle.getNormal(_normal); + hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`; + hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`; + hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; + if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) { + continue; + } + for (let j = 0;j < 3; j++) { + const jNext = (j + 1) % 3; + const vecHash0 = hashes[j]; + const vecHash1 = hashes[jNext]; + const v0 = _triangle[vertKeys[j]]; + const v1 = _triangle[vertKeys[jNext]]; + const hash = `${vecHash0}_${vecHash1}`; + const reverseHash = `${vecHash1}_${vecHash0}`; + if (reverseHash in edgeData && edgeData[reverseHash]) { + if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) { + vertices.push(v0.x, v0.y, v0.z); + vertices.push(v1.x, v1.y, v1.z); + } + edgeData[reverseHash] = null; + } else if (!(hash in edgeData)) { + edgeData[hash] = { + index0: indexArr[j], + index1: indexArr[jNext], + normal: _normal.clone() + }; + } + } + } + for (const key2 in edgeData) { + if (edgeData[key2]) { + const { index0, index1 } = edgeData[key2]; + _v0.fromBufferAttribute(positionAttr, index0); + _v1$1.fromBufferAttribute(positionAttr, index1); + vertices.push(_v0.x, _v0.y, _v0.z); + vertices.push(_v1$1.x, _v1$1.y, _v1$1.z); + } + } + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } +} + +class Shape extends Path { + constructor(points) { + super(points); + this.uuid = generateUUID(); + this.type = "Shape"; + this.holes = []; + } + getPointsHoles(divisions) { + const holesPts = []; + for (let i = 0, l = this.holes.length;i < l; i++) { + holesPts[i] = this.holes[i].getPoints(divisions); + } + return holesPts; + } + extractPoints(divisions) { + return { + shape: this.getPoints(divisions), + holes: this.getPointsHoles(divisions) + }; + } + copy(source) { + super.copy(source); + this.holes = []; + for (let i = 0, l = source.holes.length;i < l; i++) { + const hole = source.holes[i]; + this.holes.push(hole.clone()); + } + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.uuid = this.uuid; + data2.holes = []; + for (let i = 0, l = this.holes.length;i < l; i++) { + const hole = this.holes[i]; + data2.holes.push(hole.toJSON()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.uuid = json.uuid; + this.holes = []; + for (let i = 0, l = json.holes.length;i < l; i++) { + const hole = json.holes[i]; + this.holes.push(new Path().fromJSON(hole)); + } + return this; + } +} +var Earcut = { + triangulate: function(data2, holeIndices, dim = 2) { + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data2.length; + let outerNode = linkedList(data2, 0, outerLen, dim, true); + const triangles = []; + if (!outerNode || outerNode.next === outerNode.prev) + return triangles; + let minX, minY, maxX, maxY, x, y, invSize; + if (hasHoles) + outerNode = eliminateHoles(data2, holeIndices, outerNode, dim); + if (data2.length > 80 * dim) { + minX = maxX = data2[0]; + minY = maxY = data2[1]; + for (let i = dim;i < outerLen; i += dim) { + x = data2[i]; + y = data2[i + 1]; + if (x < minX) + minX = x; + if (y < minY) + minY = y; + if (x > maxX) + maxX = x; + if (y > maxY) + maxY = y; + } + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + return triangles; + } +}; +function linkedList(data2, start, end, dim, clockwise) { + let i, last2; + if (clockwise === signedArea(data2, start, end, dim) > 0) { + for (i = start;i < end; i += dim) + last2 = insertNode(i, data2[i], data2[i + 1], last2); + } else { + for (i = end - dim;i >= start; i -= dim) + last2 = insertNode(i, data2[i], data2[i + 1], last2); + } + if (last2 && equals(last2, last2.next)) { + removeNode(last2); + last2 = last2.next; + } + return last2; +} +function filterPoints(start, end) { + if (!start) + return start; + if (!end) + end = start; + let p = start, again; + do { + again = false; + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) + break; + again = true; + } else { + p = p.next; + } + } while (again || p !== end); + return end; +} +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) + return; + if (!pass && invSize) + indexCurve(ear, minX, minY, invSize); + let stop = ear, prev, next; + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + triangles.push(prev.i / dim | 0); + triangles.push(ear.i / dim | 0); + triangles.push(next.i / dim | 0); + removeNode(ear); + ear = next.next; + stop = next.next; + continue; + } + ear = next; + if (ear === stop) { + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + break; + } + } +} +function isEar(ear) { + const a = ear.prev, b = ear, c = ear.next; + if (area(a, b, c) >= 0) + return false; + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + let p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) + return false; + p = p.next; + } + return true; +} +function isEarHashed(ear, minX, minY, invSize) { + const a = ear.prev, b = ear, c = ear.next; + if (area(a, b, c) >= 0) + return false; + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + const minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize); + let { prevZ: p, nextZ: n } = ear; + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) + return false; + p = p.prevZ; + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) + return false; + n = n.nextZ; + } + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) + return false; + p = p.prevZ; + } + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) + return false; + n = n.nextZ; + } + return true; +} +function cureLocalIntersections(start, triangles, dim) { + let p = start; + do { + const a = p.prev, b = p.next.next; + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + triangles.push(a.i / dim | 0); + triangles.push(p.i / dim | 0); + triangles.push(b.i / dim | 0); + removeNode(p); + removeNode(p.next); + p = start = b; + } + p = p.next; + } while (p !== start); + return filterPoints(p); +} +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + let a = start; + do { + let b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + let c = splitPolygon(a, b); + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} +function eliminateHoles(data2, holeIndices, outerNode, dim) { + const queue = []; + let i, len, start, end, list; + for (i = 0, len = holeIndices.length;i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data2.length; + list = linkedList(data2, start, end, dim, false); + if (list === list.next) + list.steiner = true; + queue.push(getLeftmost(list)); + } + queue.sort(compareX); + for (i = 0;i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + return outerNode; +} +function compareX(a, b) { + return a.x - b.x; +} +function eliminateHole(hole, outerNode) { + const bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + const bridgeReverse = splitPolygon(bridge, hole); + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); +} +function findHoleBridge(hole, outerNode) { + let p = outerNode, qx = -Infinity, m; + const { x: hx, y: hy } = hole; + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) + return m; + } + } + p = p.next; + } while (p !== outerNode); + if (!m) + return null; + const stop = m, mx = m.x, my = m.y; + let tanMin = Infinity, tan; + p = m; + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + tan = Math.abs(hy - p.y) / (hx - p.x); + if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) { + m = p; + tanMin = tan; + } + } + p = p.next; + } while (p !== stop); + return m; +} +function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; +} +function indexCurve(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) + p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + p.prevZ.nextZ = null; + p.prevZ = null; + sortLinked(p); +} +function sortLinked(list) { + let i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; + do { + p = list; + list = null; + tail = null; + numMerges = 0; + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0;i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) + break; + } + qSize = inSize; + while (pSize > 0 || qSize > 0 && q) { + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + if (tail) + tail.nextZ = e; + else + list = e; + e.prevZ = tail; + tail = e; + } + p = q; + } + tail.nextZ = null; + inSize *= 2; + } while (numMerges > 1); + return list; +} +function zOrder(x, y, minX, minY, invSize) { + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + x = (x | x << 8) & 16711935; + x = (x | x << 4) & 252645135; + x = (x | x << 2) & 858993459; + x = (x | x << 1) & 1431655765; + y = (y | y << 8) & 16711935; + y = (y | y << 4) & 252645135; + y = (y | y << 2) & 858993459; + y = (y | y << 1) & 1431655765; + return x | y << 1; +} +function getLeftmost(start) { + let p = start, leftmost = start; + do { + if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) + leftmost = p; + p = p.next; + } while (p !== start); + return leftmost; +} +function pointInTriangle(ax, ay, bx, by, cx, cy, px2, py2) { + return (cx - px2) * (ay - py2) >= (ax - px2) * (cy - py2) && (ax - px2) * (by - py2) >= (bx - px2) * (ay - py2) && (bx - px2) * (cy - py2) >= (cx - px2) * (by - py2); +} +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && (area(a.prev, a, b.prev) || area(a, b.prev, b)) || equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); +} +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} +function intersects(p1, q1, p2, q2) { + const o1 = sign(area(p1, q1, p2)); + const o2 = sign(area(p1, q1, q2)); + const o3 = sign(area(p2, q2, p1)); + const o4 = sign(area(p2, q2, q1)); + if (o1 !== o2 && o3 !== o4) + return true; + if (o1 === 0 && onSegment(p1, p2, q1)) + return true; + if (o2 === 0 && onSegment(p1, q2, q1)) + return true; + if (o3 === 0 && onSegment(p2, p1, q2)) + return true; + if (o4 === 0 && onSegment(p2, q1, q2)) + return true; + return false; +} +function onSegment(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); +} +function sign(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; +} +function intersectsPolygon(a, b) { + let p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) + return true; + p = p.next; + } while (p !== a); + return false; +} +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} +function middleInside(a, b) { + let p = a, inside = false; + const px2 = (a.x + b.x) / 2, py2 = (a.y + b.y) / 2; + do { + if (p.y > py2 !== p.next.y > py2 && p.next.y !== p.y && px2 < (p.next.x - p.x) * (py2 - p.y) / (p.next.y - p.y) + p.x) + inside = !inside; + p = p.next; + } while (p !== a); + return inside; +} +function splitPolygon(a, b) { + const a2 = new Node2(a.i, a.x, a.y), b2 = new Node2(b.i, b.x, b.y), an = a.next, bp = b.prev; + a.next = b; + b.prev = a; + a2.next = an; + an.prev = a2; + b2.next = a2; + a2.prev = b2; + bp.next = b2; + b2.prev = bp; + return b2; +} +function insertNode(i, x, y, last2) { + const p = new Node2(i, x, y); + if (!last2) { + p.prev = p; + p.next = p; + } else { + p.next = last2.next; + p.prev = last2; + last2.next.prev = p; + last2.next = p; + } + return p; +} +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + if (p.prevZ) + p.prevZ.nextZ = p.nextZ; + if (p.nextZ) + p.nextZ.prevZ = p.prevZ; +} +function Node2(i, x, y) { + this.i = i; + this.x = x; + this.y = y; + this.prev = null; + this.next = null; + this.z = 0; + this.prevZ = null; + this.nextZ = null; + this.steiner = false; +} +function signedArea(data2, start, end, dim) { + let sum2 = 0; + for (let i = start, j = end - dim;i < end; i += dim) { + sum2 += (data2[j] - data2[i]) * (data2[i + 1] + data2[j + 1]); + j = i; + } + return sum2; +} + +class ShapeUtils { + static area(contour) { + const n = contour.length; + let a = 0; + for (let p = n - 1, q = 0;q < n; p = q++) { + a += contour[p].x * contour[q].y - contour[q].x * contour[p].y; + } + return a * 0.5; + } + static isClockWise(pts) { + return ShapeUtils.area(pts) < 0; + } + static triangulateShape(contour, holes) { + const vertices = []; + const holeIndices = []; + const faces = []; + removeDupEndPts(contour); + addContour(vertices, contour); + let holeIndex = contour.length; + holes.forEach(removeDupEndPts); + for (let i = 0;i < holes.length; i++) { + holeIndices.push(holeIndex); + holeIndex += holes[i].length; + addContour(vertices, holes[i]); + } + const triangles = Earcut.triangulate(vertices, holeIndices); + for (let i = 0;i < triangles.length; i += 3) { + faces.push(triangles.slice(i, i + 3)); + } + return faces; + } +} +function removeDupEndPts(points) { + const l = points.length; + if (l > 2 && points[l - 1].equals(points[0])) { + points.pop(); + } +} +function addContour(vertices, contour) { + for (let i = 0;i < contour.length; i++) { + vertices.push(contour[i].x); + vertices.push(contour[i].y); + } +} + +class ExtrudeGeometry extends BufferGeometry { + constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) { + super(); + this.type = "ExtrudeGeometry"; + this.parameters = { + shapes, + options + }; + shapes = Array.isArray(shapes) ? shapes : [shapes]; + const scope = this; + const verticesArray = []; + const uvArray = []; + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + addShape(shape); + } + this.setAttribute("position", new Float32BufferAttribute(verticesArray, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvArray, 2)); + this.computeVertexNormals(); + function addShape(shape) { + const placeholder = []; + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + const extrudePath = options.extrudePath; + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + if (extrudePath) { + extrudePts = extrudePath.getSpacedPoints(steps); + extrudeByPath = true; + bevelEnabled = false; + splineTube = extrudePath.computeFrenetFrames(steps, false); + binormal = new Vector3; + normal = new Vector3; + position2 = new Vector3; + } + if (!bevelEnabled) { + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + } + const shapePoints = shape.extractPoints(curveSegments); + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + const reverse = !ShapeUtils.isClockWise(vertices); + if (reverse) { + vertices = vertices.reverse(); + for (let h = 0, hl2 = holes.length;h < hl2; h++) { + const ahole = holes[h]; + if (ShapeUtils.isClockWise(ahole)) { + holes[h] = ahole.reverse(); + } + } + } + const faces = ShapeUtils.triangulateShape(vertices, holes); + const contour = vertices; + for (let h = 0, hl2 = holes.length;h < hl2; h++) { + const ahole = holes[h]; + vertices = vertices.concat(ahole); + } + function scalePt2(pt, vec, size) { + if (!vec) + console.error("THREE.ExtrudeGeometry: vec does not exist"); + return pt.clone().addScaledVector(vec, size); + } + const vlen = vertices.length, flen = faces.length; + function getBevelVec(inPt, inPrev, inNext) { + let v_trans_x, v_trans_y, shrink_by; + const v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; + const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; + const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x; + if (Math.abs(collinear0) > Number.EPSILON) { + const v_prev_len = Math.sqrt(v_prev_lensq); + const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); + const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len; + const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len; + const ptNextShift_x = inNext.x - v_next_y / v_next_len; + const ptNextShift_y = inNext.y + v_next_x / v_next_len; + const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); + v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x; + v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; + const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y; + if (v_trans_lensq <= 2) { + return new Vector2(v_trans_x, v_trans_y); + } else { + shrink_by = Math.sqrt(v_trans_lensq / 2); + } + } else { + let direction_eq = false; + if (v_prev_x > Number.EPSILON) { + if (v_next_x > Number.EPSILON) { + direction_eq = true; + } + } else { + if (v_prev_x < -Number.EPSILON) { + if (v_next_x < -Number.EPSILON) { + direction_eq = true; + } + } else { + if (Math.sign(v_prev_y) === Math.sign(v_next_y)) { + direction_eq = true; + } + } + } + if (direction_eq) { + v_trans_x = -v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt(v_prev_lensq); + } else { + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt(v_prev_lensq / 2); + } + } + return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by); + } + const contourMovements = []; + for (let i = 0, il = contour.length, j = il - 1, k2 = i + 1;i < il; i++, j++, k2++) { + if (j === il) + j = 0; + if (k2 === il) + k2 = 0; + contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k2]); + } + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + for (let h = 0, hl2 = holes.length;h < hl2; h++) { + const ahole = holes[h]; + oneHoleMovements = []; + for (let i = 0, il = ahole.length, j = il - 1, k2 = i + 1;i < il; i++, j++, k2++) { + if (j === il) + j = 0; + if (k2 === il) + k2 = 0; + oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k2]); + } + holesMovements.push(oneHoleMovements); + verticesMovements = verticesMovements.concat(oneHoleMovements); + } + for (let b = 0;b < bevelSegments; b++) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos(t * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length;i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, -z); + } + for (let h = 0, hl2 = holes.length;h < hl2; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length;i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + v(vert.x, vert.y, -z); + } + } + } + const bs = bevelSize + bevelOffset; + for (let i = 0;i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, 0); + } else { + normal.copy(splineTube.normals[0]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y); + position2.copy(extrudePts[0]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + for (let s = 1;s <= steps; s++) { + for (let i = 0;i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, depth / steps * s); + } else { + normal.copy(splineTube.normals[s]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y); + position2.copy(extrudePts[s]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + } + for (let b = bevelSegments - 1;b >= 0; b--) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos(t * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length;i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, depth + z); + } + for (let h = 0, hl2 = holes.length;h < hl2; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length;i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + if (!extrudeByPath) { + v(vert.x, vert.y, depth + z); + } else { + v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z); + } + } + } + } + buildLidFaces(); + buildSideFaces(); + function buildLidFaces() { + const start = verticesArray.length / 3; + if (bevelEnabled) { + let layer = 0; + let offset = vlen * layer; + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[2] + offset, face[1] + offset, face[0] + offset); + } + layer = steps + bevelSegments * 2; + offset = vlen * layer; + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[0] + offset, face[1] + offset, face[2] + offset); + } + } else { + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[2], face[1], face[0]); + } + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps); + } + } + scope.addGroup(start, verticesArray.length / 3 - start, 0); + } + function buildSideFaces() { + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls(contour, layeroffset); + layeroffset += contour.length; + for (let h = 0, hl2 = holes.length;h < hl2; h++) { + const ahole = holes[h]; + sidewalls(ahole, layeroffset); + layeroffset += ahole.length; + } + scope.addGroup(start, verticesArray.length / 3 - start, 1); + } + function sidewalls(contour2, layeroffset) { + let i = contour2.length; + while (--i >= 0) { + const j = i; + let k2 = i - 1; + if (k2 < 0) + k2 = contour2.length - 1; + for (let s = 0, sl = steps + bevelSegments * 2;s < sl; s++) { + const slen1 = vlen * s; + const slen2 = vlen * (s + 1); + const a = layeroffset + j + slen1, b = layeroffset + k2 + slen1, c = layeroffset + k2 + slen2, d = layeroffset + j + slen2; + f4(a, b, c, d); + } + } + } + function v(x, y, z) { + placeholder.push(x); + placeholder.push(y); + placeholder.push(z); + } + function f3(a, b, c) { + addVertex(a); + addVertex(b); + addVertex(c); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[2]); + } + function f4(a, b, c, d) { + addVertex(a); + addVertex(b); + addVertex(d); + addVertex(b); + addVertex(c); + addVertex(d); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[3]); + addUV(uvs[1]); + addUV(uvs[2]); + addUV(uvs[3]); + } + function addVertex(index2) { + verticesArray.push(placeholder[index2 * 3 + 0]); + verticesArray.push(placeholder[index2 * 3 + 1]); + verticesArray.push(placeholder[index2 * 3 + 2]); + } + function addUV(vector2) { + uvArray.push(vector2.x); + uvArray.push(vector2.y); + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + const shapes = this.parameters.shapes; + const options = this.parameters.options; + return toJSON$1(shapes, options, data2); + } + static fromJSON(data2, shapes) { + const geometryShapes = []; + for (let j = 0, jl = data2.shapes.length;j < jl; j++) { + const shape = shapes[data2.shapes[j]]; + geometryShapes.push(shape); + } + const extrudePath = data2.options.extrudePath; + if (extrudePath !== undefined) { + data2.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath); + } + return new ExtrudeGeometry(geometryShapes, data2.options); + } +} +var WorldUVGenerator = { + generateTopUV: function(geometry, vertices, indexA, indexB, indexC) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + return [ + new Vector2(a_x, a_y), + new Vector2(b_x, b_y), + new Vector2(c_x, c_y) + ]; + }, + generateSideWallUV: function(geometry, vertices, indexA, indexB, indexC, indexD) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const a_z = vertices[indexA * 3 + 2]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const b_z = vertices[indexB * 3 + 2]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + const c_z = vertices[indexC * 3 + 2]; + const d_x = vertices[indexD * 3]; + const d_y = vertices[indexD * 3 + 1]; + const d_z = vertices[indexD * 3 + 2]; + if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) { + return [ + new Vector2(a_x, 1 - a_z), + new Vector2(b_x, 1 - b_z), + new Vector2(c_x, 1 - c_z), + new Vector2(d_x, 1 - d_z) + ]; + } else { + return [ + new Vector2(a_y, 1 - a_z), + new Vector2(b_y, 1 - b_z), + new Vector2(c_y, 1 - c_z), + new Vector2(d_y, 1 - d_z) + ]; + } + } +}; +function toJSON$1(shapes, options, data2) { + data2.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + data2.shapes.push(shape.uuid); + } + } else { + data2.shapes.push(shapes.uuid); + } + data2.options = Object.assign({}, options); + if (options.extrudePath !== undefined) + data2.options.extrudePath = options.extrudePath.toJSON(); + return data2; +} + +class IcosahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const t = (1 + Math.sqrt(5)) / 2; + const vertices = [ + -1, + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + 0, + 0, + -1, + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + t, + 0, + -1, + t, + 0, + 1, + -t, + 0, + -1, + -t, + 0, + 1 + ]; + const indices = [ + 0, + 11, + 5, + 0, + 5, + 1, + 0, + 1, + 7, + 0, + 7, + 10, + 0, + 10, + 11, + 1, + 5, + 9, + 5, + 11, + 4, + 11, + 10, + 2, + 10, + 7, + 6, + 7, + 1, + 8, + 3, + 9, + 4, + 3, + 4, + 2, + 3, + 2, + 6, + 3, + 6, + 8, + 3, + 8, + 9, + 4, + 9, + 5, + 2, + 4, + 11, + 6, + 2, + 10, + 8, + 6, + 7, + 9, + 8, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "IcosahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new IcosahedronGeometry(data2.radius, data2.detail); + } +} + +class OctahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1 + ]; + const indices = [ + 0, + 2, + 4, + 0, + 4, + 3, + 0, + 3, + 5, + 0, + 5, + 2, + 1, + 2, + 5, + 1, + 5, + 3, + 1, + 3, + 4, + 1, + 4, + 2 + ]; + super(vertices, indices, radius, detail); + this.type = "OctahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new OctahedronGeometry(data2.radius, data2.detail); + } +} + +class PlaneGeometry extends BufferGeometry { + constructor(width2 = 1, height2 = 1, widthSegments = 1, heightSegments = 1) { + super(); + this.type = "PlaneGeometry"; + this.parameters = { + width: width2, + height: height2, + widthSegments, + heightSegments + }; + const width_half = width2 / 2; + const height_half = height2 / 2; + const gridX = Math.floor(widthSegments); + const gridY = Math.floor(heightSegments); + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + const segment_width = width2 / gridX; + const segment_height = height2 / gridY; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0;iy < gridY1; iy++) { + const y = iy * segment_height - height_half; + for (let ix = 0;ix < gridX1; ix++) { + const x = ix * segment_width - width_half; + vertices.push(x, -y, 0); + normals.push(0, 0, 1); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + } + } + for (let iy = 0;iy < gridY; iy++) { + for (let ix = 0;ix < gridX; ix++) { + const a = ix + gridX1 * iy; + const b = ix + gridX1 * (iy + 1); + const c = ix + 1 + gridX1 * (iy + 1); + const d = ix + 1 + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new PlaneGeometry(data2.width, data2.height, data2.widthSegments, data2.heightSegments); + } +} + +class RingGeometry extends BufferGeometry { + constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "RingGeometry"; + this.parameters = { + innerRadius, + outerRadius, + thetaSegments, + phiSegments, + thetaStart, + thetaLength + }; + thetaSegments = Math.max(3, thetaSegments); + phiSegments = Math.max(1, phiSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let radius = innerRadius; + const radiusStep = (outerRadius - innerRadius) / phiSegments; + const vertex = new Vector3; + const uv = new Vector2; + for (let j = 0;j <= phiSegments; j++) { + for (let i = 0;i <= thetaSegments; i++) { + const segment = thetaStart + i / thetaSegments * thetaLength; + vertex.x = radius * Math.cos(segment); + vertex.y = radius * Math.sin(segment); + vertices.push(vertex.x, vertex.y, vertex.z); + normals.push(0, 0, 1); + uv.x = (vertex.x / outerRadius + 1) / 2; + uv.y = (vertex.y / outerRadius + 1) / 2; + uvs.push(uv.x, uv.y); + } + radius += radiusStep; + } + for (let j = 0;j < phiSegments; j++) { + const thetaSegmentLevel = j * (thetaSegments + 1); + for (let i = 0;i < thetaSegments; i++) { + const segment = i + thetaSegmentLevel; + const a = segment; + const b = segment + thetaSegments + 1; + const c = segment + thetaSegments + 2; + const d = segment + 1; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new RingGeometry(data2.innerRadius, data2.outerRadius, data2.thetaSegments, data2.phiSegments, data2.thetaStart, data2.thetaLength); + } +} + +class ShapeGeometry extends BufferGeometry { + constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) { + super(); + this.type = "ShapeGeometry"; + this.parameters = { + shapes, + curveSegments + }; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let groupStart = 0; + let groupCount = 0; + if (Array.isArray(shapes) === false) { + addShape(shapes); + } else { + for (let i = 0;i < shapes.length; i++) { + addShape(shapes[i]); + this.addGroup(groupStart, groupCount, i); + groupStart += groupCount; + groupCount = 0; + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function addShape(shape) { + const indexOffset = vertices.length / 3; + const points = shape.extractPoints(curveSegments); + let shapeVertices = points.shape; + const shapeHoles = points.holes; + if (ShapeUtils.isClockWise(shapeVertices) === false) { + shapeVertices = shapeVertices.reverse(); + } + for (let i = 0, l = shapeHoles.length;i < l; i++) { + const shapeHole = shapeHoles[i]; + if (ShapeUtils.isClockWise(shapeHole) === true) { + shapeHoles[i] = shapeHole.reverse(); + } + } + const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); + for (let i = 0, l = shapeHoles.length;i < l; i++) { + const shapeHole = shapeHoles[i]; + shapeVertices = shapeVertices.concat(shapeHole); + } + for (let i = 0, l = shapeVertices.length;i < l; i++) { + const vertex = shapeVertices[i]; + vertices.push(vertex.x, vertex.y, 0); + normals.push(0, 0, 1); + uvs.push(vertex.x, vertex.y); + } + for (let i = 0, l = faces.length;i < l; i++) { + const face = faces[i]; + const a = face[0] + indexOffset; + const b = face[1] + indexOffset; + const c = face[2] + indexOffset; + indices.push(a, b, c); + groupCount += 3; + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + const shapes = this.parameters.shapes; + return toJSON(shapes, data2); + } + static fromJSON(data2, shapes) { + const geometryShapes = []; + for (let j = 0, jl = data2.shapes.length;j < jl; j++) { + const shape = shapes[data2.shapes[j]]; + geometryShapes.push(shape); + } + return new ShapeGeometry(geometryShapes, data2.curveSegments); + } +} +function toJSON(shapes, data2) { + data2.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + data2.shapes.push(shape.uuid); + } + } else { + data2.shapes.push(shapes.uuid); + } + return data2; +} + +class SphereGeometry extends BufferGeometry { + constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) { + super(); + this.type = "SphereGeometry"; + this.parameters = { + radius, + widthSegments, + heightSegments, + phiStart, + phiLength, + thetaStart, + thetaLength + }; + widthSegments = Math.max(3, Math.floor(widthSegments)); + heightSegments = Math.max(2, Math.floor(heightSegments)); + const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI); + let index2 = 0; + const grid = []; + const vertex = new Vector3; + const normal = new Vector3; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0;iy <= heightSegments; iy++) { + const verticesRow = []; + const v = iy / heightSegments; + let uOffset = 0; + if (iy === 0 && thetaStart === 0) { + uOffset = 0.5 / widthSegments; + } else if (iy === heightSegments && thetaEnd === Math.PI) { + uOffset = -0.5 / widthSegments; + } + for (let ix = 0;ix <= widthSegments; ix++) { + const u = ix / widthSegments; + vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertex.y = radius * Math.cos(thetaStart + v * thetaLength); + vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertices.push(vertex.x, vertex.y, vertex.z); + normal.copy(vertex).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u + uOffset, 1 - v); + verticesRow.push(index2++); + } + grid.push(verticesRow); + } + for (let iy = 0;iy < heightSegments; iy++) { + for (let ix = 0;ix < widthSegments; ix++) { + const a = grid[iy][ix + 1]; + const b = grid[iy][ix]; + const c = grid[iy + 1][ix]; + const d = grid[iy + 1][ix + 1]; + if (iy !== 0 || thetaStart > 0) + indices.push(a, b, d); + if (iy !== heightSegments - 1 || thetaEnd < Math.PI) + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new SphereGeometry(data2.radius, data2.widthSegments, data2.heightSegments, data2.phiStart, data2.phiLength, data2.thetaStart, data2.thetaLength); + } +} + +class TetrahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + -1, + 1, + -1, + -1 + ]; + const indices = [ + 2, + 1, + 0, + 0, + 3, + 2, + 1, + 3, + 0, + 2, + 3, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "TetrahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new TetrahedronGeometry(data2.radius, data2.detail); + } +} + +class TorusGeometry extends BufferGeometry { + constructor(radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2) { + super(); + this.type = "TorusGeometry"; + this.parameters = { + radius, + tube, + radialSegments, + tubularSegments, + arc + }; + radialSegments = Math.floor(radialSegments); + tubularSegments = Math.floor(tubularSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const center = new Vector3; + const vertex = new Vector3; + const normal = new Vector3; + for (let j = 0;j <= radialSegments; j++) { + for (let i = 0;i <= tubularSegments; i++) { + const u = i / tubularSegments * arc; + const v = j / radialSegments * Math.PI * 2; + vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u); + vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u); + vertex.z = tube * Math.sin(v); + vertices.push(vertex.x, vertex.y, vertex.z); + center.x = radius * Math.cos(u); + center.y = radius * Math.sin(u); + normal.subVectors(vertex, center).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j / radialSegments); + } + } + for (let j = 1;j <= radialSegments; j++) { + for (let i = 1;i <= tubularSegments; i++) { + const a = (tubularSegments + 1) * j + i - 1; + const b = (tubularSegments + 1) * (j - 1) + i - 1; + const c = (tubularSegments + 1) * (j - 1) + i; + const d = (tubularSegments + 1) * j + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new TorusGeometry(data2.radius, data2.tube, data2.radialSegments, data2.tubularSegments, data2.arc); + } +} + +class TorusKnotGeometry extends BufferGeometry { + constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) { + super(); + this.type = "TorusKnotGeometry"; + this.parameters = { + radius, + tube, + tubularSegments, + radialSegments, + p, + q + }; + tubularSegments = Math.floor(tubularSegments); + radialSegments = Math.floor(radialSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex = new Vector3; + const normal = new Vector3; + const P1 = new Vector3; + const P2 = new Vector3; + const B = new Vector3; + const T = new Vector3; + const N = new Vector3; + for (let i = 0;i <= tubularSegments; ++i) { + const u = i / tubularSegments * p * Math.PI * 2; + calculatePositionOnCurve(u, p, q, radius, P1); + calculatePositionOnCurve(u + 0.01, p, q, radius, P2); + T.subVectors(P2, P1); + N.addVectors(P2, P1); + B.crossVectors(T, N); + N.crossVectors(B, T); + B.normalize(); + N.normalize(); + for (let j = 0;j <= radialSegments; ++j) { + const v = j / radialSegments * Math.PI * 2; + const cx = -tube * Math.cos(v); + const cy = tube * Math.sin(v); + vertex.x = P1.x + (cx * N.x + cy * B.x); + vertex.y = P1.y + (cx * N.y + cy * B.y); + vertex.z = P1.z + (cx * N.z + cy * B.z); + vertices.push(vertex.x, vertex.y, vertex.z); + normal.subVectors(vertex, P1).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j / radialSegments); + } + } + for (let j = 1;j <= tubularSegments; j++) { + for (let i = 1;i <= radialSegments; i++) { + const a = (radialSegments + 1) * (j - 1) + (i - 1); + const b = (radialSegments + 1) * j + (i - 1); + const c = (radialSegments + 1) * j + i; + const d = (radialSegments + 1) * (j - 1) + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function calculatePositionOnCurve(u, p2, q2, radius2, position2) { + const cu = Math.cos(u); + const su = Math.sin(u); + const quOverP = q2 / p2 * u; + const cs = Math.cos(quOverP); + position2.x = radius2 * (2 + cs) * 0.5 * cu; + position2.y = radius2 * (2 + cs) * su * 0.5; + position2.z = radius2 * Math.sin(quOverP) * 0.5; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new TorusKnotGeometry(data2.radius, data2.tube, data2.tubularSegments, data2.radialSegments, data2.p, data2.q); + } +} + +class TubeGeometry extends BufferGeometry { + constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) { + super(); + this.type = "TubeGeometry"; + this.parameters = { + path, + tubularSegments, + radius, + radialSegments, + closed + }; + const frames2 = path.computeFrenetFrames(tubularSegments, closed); + this.tangents = frames2.tangents; + this.normals = frames2.normals; + this.binormals = frames2.binormals; + const vertex = new Vector3; + const normal = new Vector3; + const uv = new Vector2; + let P = new Vector3; + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; + generateBufferData(); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function generateBufferData() { + for (let i = 0;i < tubularSegments; i++) { + generateSegment(i); + } + generateSegment(closed === false ? tubularSegments : 0); + generateUVs(); + generateIndices(); + } + function generateSegment(i) { + P = path.getPointAt(i / tubularSegments, P); + const N = frames2.normals[i]; + const B = frames2.binormals[i]; + for (let j = 0;j <= radialSegments; j++) { + const v = j / radialSegments * Math.PI * 2; + const sin = Math.sin(v); + const cos = -Math.cos(v); + normal.x = cos * N.x + sin * B.x; + normal.y = cos * N.y + sin * B.y; + normal.z = cos * N.z + sin * B.z; + normal.normalize(); + normals.push(normal.x, normal.y, normal.z); + vertex.x = P.x + radius * normal.x; + vertex.y = P.y + radius * normal.y; + vertex.z = P.z + radius * normal.z; + vertices.push(vertex.x, vertex.y, vertex.z); + } + } + function generateIndices() { + for (let j = 1;j <= tubularSegments; j++) { + for (let i = 1;i <= radialSegments; i++) { + const a = (radialSegments + 1) * (j - 1) + (i - 1); + const b = (radialSegments + 1) * j + (i - 1); + const c = (radialSegments + 1) * j + i; + const d = (radialSegments + 1) * (j - 1) + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + } + function generateUVs() { + for (let i = 0;i <= tubularSegments; i++) { + for (let j = 0;j <= radialSegments; j++) { + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + uvs.push(uv.x, uv.y); + } + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.path = this.parameters.path.toJSON(); + return data2; + } + static fromJSON(data2) { + return new TubeGeometry(new Curves[data2.path.type]().fromJSON(data2.path), data2.tubularSegments, data2.radius, data2.radialSegments, data2.closed); + } +} + +class WireframeGeometry extends BufferGeometry { + constructor(geometry = null) { + super(); + this.type = "WireframeGeometry"; + this.parameters = { + geometry + }; + if (geometry !== null) { + const vertices = []; + const edges = new Set; + const start = new Vector3; + const end = new Vector3; + if (geometry.index !== null) { + const position2 = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; + if (groups.length === 0) { + groups = [{ start: 0, count: indices.count, materialIndex: 0 }]; + } + for (let o = 0, ol = groups.length;o < ol; ++o) { + const group = groups[o]; + const groupStart = group.start; + const groupCount = group.count; + for (let i = groupStart, l = groupStart + groupCount;i < l; i += 3) { + for (let j = 0;j < 3; j++) { + const index1 = indices.getX(i + j); + const index2 = indices.getX(i + (j + 1) % 3); + start.fromBufferAttribute(position2, index1); + end.fromBufferAttribute(position2, index2); + if (isUniqueEdge(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + } else { + const position2 = geometry.attributes.position; + for (let i = 0, l = position2.count / 3;i < l; i++) { + for (let j = 0;j < 3; j++) { + const index1 = 3 * i + j; + const index2 = 3 * i + (j + 1) % 3; + start.fromBufferAttribute(position2, index1); + end.fromBufferAttribute(position2, index2); + if (isUniqueEdge(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } +} +function isUniqueEdge(start, end, edges) { + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; + if (edges.has(hash1) === true || edges.has(hash2) === true) { + return false; + } else { + edges.add(hash1); + edges.add(hash2); + return true; + } +} +var Geometries = /* @__PURE__ */ Object.freeze({ + __proto__: null, + BoxGeometry, + CapsuleGeometry, + CircleGeometry, + ConeGeometry, + CylinderGeometry, + DodecahedronGeometry, + EdgesGeometry, + ExtrudeGeometry, + IcosahedronGeometry, + LatheGeometry, + OctahedronGeometry, + PlaneGeometry, + PolyhedronGeometry, + RingGeometry, + ShapeGeometry, + SphereGeometry, + TetrahedronGeometry, + TorusGeometry, + TorusKnotGeometry, + TubeGeometry, + WireframeGeometry +}); + +class ShadowMaterial extends Material { + constructor(parameters) { + super(); + this.isShadowMaterial = true; + this.type = "ShadowMaterial"; + this.color = new Color(0); + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.fog = source.fog; + return this; + } +} + +class RawShaderMaterial extends ShaderMaterial { + constructor(parameters) { + super(parameters); + this.isRawShaderMaterial = true; + this.type = "RawShaderMaterial"; + } +} + +class MeshStandardMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshStandardMaterial = true; + this.type = "MeshStandardMaterial"; + this.defines = { STANDARD: "" }; + this.color = new Color(16777215); + this.roughness = 1; + this.metalness = 0; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.roughnessMap = null; + this.metalnessMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler; + this.envMapIntensity = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { STANDARD: "" }; + this.color.copy(source.color); + this.roughness = source.roughness; + this.metalness = source.metalness; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.roughnessMap = source.roughnessMap; + this.metalnessMap = source.metalnessMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.envMapIntensity = source.envMapIntensity; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } +} + +class MeshPhysicalMaterial extends MeshStandardMaterial { + constructor(parameters) { + super(); + this.isMeshPhysicalMaterial = true; + this.defines = { + STANDARD: "", + PHYSICAL: "" + }; + this.type = "MeshPhysicalMaterial"; + this.anisotropyRotation = 0; + this.anisotropyMap = null; + this.clearcoatMap = null; + this.clearcoatRoughness = 0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector2(1, 1); + this.clearcoatNormalMap = null; + this.ior = 1.5; + Object.defineProperty(this, "reflectivity", { + get: function() { + return clamp2(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1); + }, + set: function(reflectivity) { + this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity); + } + }); + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [100, 400]; + this.iridescenceThicknessMap = null; + this.sheenColor = new Color(0); + this.sheenColorMap = null; + this.sheenRoughness = 1; + this.sheenRoughnessMap = null; + this.transmissionMap = null; + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = Infinity; + this.attenuationColor = new Color(1, 1, 1); + this.specularIntensity = 1; + this.specularIntensityMap = null; + this.specularColor = new Color(1, 1, 1); + this.specularColorMap = null; + this._anisotropy = 0; + this._clearcoat = 0; + this._dispersion = 0; + this._iridescence = 0; + this._sheen = 0; + this._transmission = 0; + this.setValues(parameters); + } + get anisotropy() { + return this._anisotropy; + } + set anisotropy(value2) { + if (this._anisotropy > 0 !== value2 > 0) { + this.version++; + } + this._anisotropy = value2; + } + get clearcoat() { + return this._clearcoat; + } + set clearcoat(value2) { + if (this._clearcoat > 0 !== value2 > 0) { + this.version++; + } + this._clearcoat = value2; + } + get iridescence() { + return this._iridescence; + } + set iridescence(value2) { + if (this._iridescence > 0 !== value2 > 0) { + this.version++; + } + this._iridescence = value2; + } + get dispersion() { + return this._dispersion; + } + set dispersion(value2) { + if (this._dispersion > 0 !== value2 > 0) { + this.version++; + } + this._dispersion = value2; + } + get sheen() { + return this._sheen; + } + set sheen(value2) { + if (this._sheen > 0 !== value2 > 0) { + this.version++; + } + this._sheen = value2; + } + get transmission() { + return this._transmission; + } + set transmission(value2) { + if (this._transmission > 0 !== value2 > 0) { + this.version++; + } + this._transmission = value2; + } + copy(source) { + super.copy(source); + this.defines = { + STANDARD: "", + PHYSICAL: "" + }; + this.anisotropy = source.anisotropy; + this.anisotropyRotation = source.anisotropyRotation; + this.anisotropyMap = source.anisotropyMap; + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy(source.clearcoatNormalScale); + this.dispersion = source.dispersion; + this.ior = source.ior; + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [...source.iridescenceThicknessRange]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + this.sheen = source.sheen; + this.sheenColor.copy(source.sheenColor); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy(source.attenuationColor); + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy(source.specularColor); + this.specularColorMap = source.specularColorMap; + return this; + } +} + +class MeshPhongMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshPhongMaterial = true; + this.type = "MeshPhongMaterial"; + this.color = new Color(16777215); + this.specular = new Color(1118481); + this.shininess = 30; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.specular.copy(source.specular); + this.shininess = source.shininess; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } +} + +class MeshToonMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshToonMaterial = true; + this.defines = { TOON: "" }; + this.type = "MeshToonMaterial"; + this.color = new Color(16777215); + this.map = null; + this.gradientMap = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.gradientMap = source.gradientMap; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } +} + +class MeshNormalMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshNormalMaterial = true; + this.type = "MeshNormalMaterial"; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.flatShading = false; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.flatShading = source.flatShading; + return this; + } +} + +class MeshLambertMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshLambertMaterial = true; + this.type = "MeshLambertMaterial"; + this.color = new Color(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } +} + +class MeshDepthMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshDepthMaterial = true; + this.type = "MeshDepthMaterial"; + this.depthPacking = BasicDepthPacking; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.depthPacking = source.depthPacking; + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + return this; + } +} + +class MeshDistanceMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshDistanceMaterial = true; + this.type = "MeshDistanceMaterial"; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + return this; + } +} + +class MeshMatcapMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshMatcapMaterial = true; + this.defines = { MATCAP: "" }; + this.type = "MeshMatcapMaterial"; + this.color = new Color(16777215); + this.matcap = null; + this.map = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { MATCAP: "" }; + this.color.copy(source.color); + this.matcap = source.matcap; + this.map = source.map; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } +} + +class LineDashedMaterial extends LineBasicMaterial { + constructor(parameters) { + super(); + this.isLineDashedMaterial = true; + this.type = "LineDashedMaterial"; + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + return this; + } +} +function convertArray(array, type, forceClone) { + if (!array || !forceClone && array.constructor === type) + return array; + if (typeof type.BYTES_PER_ELEMENT === "number") { + return new type(array); + } + return Array.prototype.slice.call(array); +} +function isTypedArray(object) { + return ArrayBuffer.isView(object) && !(object instanceof DataView); +} +function getKeyframeOrder(times) { + function compareTime(i, j) { + return times[i] - times[j]; + } + const n = times.length; + const result = new Array(n); + for (let i = 0;i !== n; ++i) + result[i] = i; + result.sort(compareTime); + return result; +} +function sortedArray(values2, stride, order) { + const nValues = values2.length; + const result = new values2.constructor(nValues); + for (let i = 0, dstOffset = 0;dstOffset !== nValues; ++i) { + const srcOffset = order[i] * stride; + for (let j = 0;j !== stride; ++j) { + result[dstOffset++] = values2[srcOffset + j]; + } + } + return result; +} +function flattenJSON(jsonKeys, times, values2, valuePropertyName) { + let i = 1, key2 = jsonKeys[0]; + while (key2 !== undefined && key2[valuePropertyName] === undefined) { + key2 = jsonKeys[i++]; + } + if (key2 === undefined) + return; + let value2 = key2[valuePropertyName]; + if (value2 === undefined) + return; + if (Array.isArray(value2)) { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + values2.push.apply(values2, value2); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } else if (value2.toArray !== undefined) { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + value2.toArray(values2, values2.length); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } else { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + values2.push(value2); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } +} +function subclip(sourceClip, name2, startFrame, endFrame, fps = 30) { + const clip = sourceClip.clone(); + clip.name = name2; + const tracks = []; + for (let i = 0;i < clip.tracks.length; ++i) { + const track = clip.tracks[i]; + const valueSize = track.getValueSize(); + const times = []; + const values2 = []; + for (let j = 0;j < track.times.length; ++j) { + const frame = track.times[j] * fps; + if (frame < startFrame || frame >= endFrame) + continue; + times.push(track.times[j]); + for (let k2 = 0;k2 < valueSize; ++k2) { + values2.push(track.values[j * valueSize + k2]); + } + } + if (times.length === 0) + continue; + track.times = convertArray(times, track.times.constructor); + track.values = convertArray(values2, track.values.constructor); + tracks.push(track); + } + clip.tracks = tracks; + let minStartTime = Infinity; + for (let i = 0;i < clip.tracks.length; ++i) { + if (minStartTime > clip.tracks[i].times[0]) { + minStartTime = clip.tracks[i].times[0]; + } + } + for (let i = 0;i < clip.tracks.length; ++i) { + clip.tracks[i].shift(-1 * minStartTime); + } + clip.resetDuration(); + return clip; +} +function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) { + if (fps <= 0) + fps = 30; + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; + for (let i = 0;i < numTracks; ++i) { + const referenceTrack = referenceClip.tracks[i]; + const referenceTrackType = referenceTrack.ValueTypeName; + if (referenceTrackType === "bool" || referenceTrackType === "string") + continue; + const targetTrack = targetClip.tracks.find(function(track) { + return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType; + }); + if (targetTrack === undefined) + continue; + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); + if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + referenceOffset = referenceValueSize / 3; + } + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); + if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + targetOffset = targetValueSize / 3; + } + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; + if (referenceTime <= referenceTrack.times[0]) { + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else if (referenceTime >= referenceTrack.times[lastIndex]) { + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else { + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate(referenceTime); + referenceValue = interpolant.resultBuffer.slice(startIndex, endIndex); + } + if (referenceTrackType === "quaternion") { + const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate(); + referenceQuat.toArray(referenceValue); + } + const numTimes = targetTrack.times.length; + for (let j = 0;j < numTimes; ++j) { + const valueStart = j * targetValueSize + targetOffset; + if (referenceTrackType === "quaternion") { + Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart); + } else { + const valueEnd = targetValueSize - targetOffset * 2; + for (let k2 = 0;k2 < valueEnd; ++k2) { + targetTrack.values[valueStart + k2] -= referenceValue[k2]; + } + } + } + } + targetClip.blendMode = AdditiveAnimationBlendMode; + return targetClip; +} +var AnimationUtils = { + convertArray, + isTypedArray, + getKeyframeOrder, + sortedArray, + flattenJSON, + subclip, + makeClipAdditive +}; + +class Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; + this.settings = null; + this.DefaultSettings_ = {}; + } + evaluate(t) { + const pp = this.parameterPositions; + let i1 = this._cachedIndex, t1 = pp[i1], t0 = pp[i1 - 1]; + validate_interval: { + seek: { + let right; + linear_scan: { + forward_scan: + if (!(t < t1)) { + for (let giveUpAt = i1 + 2;; ) { + if (t1 === undefined) { + if (t < t0) + break forward_scan; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + if (i1 === giveUpAt) + break; + t0 = t1; + t1 = pp[++i1]; + if (t < t1) { + break seek; + } + } + right = pp.length; + break linear_scan; + } + if (!(t >= t0)) { + const t1global = pp[1]; + if (t < t1global) { + i1 = 2; + t0 = t1global; + } + for (let giveUpAt = i1 - 2;; ) { + if (t0 === undefined) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (i1 === giveUpAt) + break; + t1 = t0; + t0 = pp[--i1 - 1]; + if (t >= t0) { + break seek; + } + } + right = i1; + i1 = 0; + break linear_scan; + } + break validate_interval; + } + while (i1 < right) { + const mid = i1 + right >>> 1; + if (t < pp[mid]) { + right = mid; + } else { + i1 = mid + 1; + } + } + t1 = pp[i1]; + t0 = pp[i1 - 1]; + if (t0 === undefined) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (t1 === undefined) { + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + } + this._cachedIndex = i1; + this.intervalChanged_(i1, t0, t1); + } + return this.interpolate_(i1, t0, t, t1); + } + getSettings_() { + return this.settings || this.DefaultSettings_; + } + copySampleValue_(index2) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, offset = index2 * stride; + for (let i = 0;i !== stride; ++i) { + result[i] = values2[offset + i]; + } + return result; + } + interpolate_() { + throw new Error("call to abstract method"); + } + intervalChanged_() { + } +} + +class CubicInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; + this.DefaultSettings_ = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + } + intervalChanged_(i1, t0, t1) { + const pp = this.parameterPositions; + let iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[iPrev], tNext = pp[iNext]; + if (tPrev === undefined) { + switch (this.getSettings_().endingStart) { + case ZeroSlopeEnding: + iPrev = i1; + tPrev = 2 * t0 - t1; + break; + case WrapAroundEnding: + iPrev = pp.length - 2; + tPrev = t0 + pp[iPrev] - pp[iPrev + 1]; + break; + default: + iPrev = i1; + tPrev = t1; + } + } + if (tNext === undefined) { + switch (this.getSettings_().endingEnd) { + case ZeroSlopeEnding: + iNext = i1; + tNext = 2 * t1 - t0; + break; + case WrapAroundEnding: + iNext = 1; + tNext = t1 + pp[1] - pp[0]; + break; + default: + iNext = i1 - 1; + tNext = t0; + } + } + const halfDt = (t1 - t0) * 0.5, stride = this.valueSize; + this._weightPrev = halfDt / (t0 - tPrev); + this._weightNext = halfDt / (tNext - t1); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o0 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p = (t - t0) / (t1 - t0), pp = p * p, ppp = pp * p; + const sP = -wP * ppp + 2 * wP * pp - wP * p; + const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1; + const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; + for (let i = 0;i !== stride; ++i) { + result[i] = sP * values2[oP + i] + s0 * values2[o0 + i] + s1 * values2[o1 + i] + sN * values2[oN + i]; + } + return result; + } +} + +class LinearInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = (t - t0) / (t1 - t0), weight0 = 1 - weight1; + for (let i = 0;i !== stride; ++i) { + result[i] = values2[offset0 + i] * weight0 + values2[offset1 + i] * weight1; + } + return result; + } +} + +class DiscreteInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1) { + return this.copySampleValue_(i1 - 1); + } +} + +class KeyframeTrack { + constructor(name2, times, values2, interpolation) { + if (name2 === undefined) + throw new Error("THREE.KeyframeTrack: track name is undefined"); + if (times === undefined || times.length === 0) + throw new Error("THREE.KeyframeTrack: no keyframes in track named " + name2); + this.name = name2; + this.times = convertArray(times, this.TimeBufferType); + this.values = convertArray(values2, this.ValueBufferType); + this.setInterpolation(interpolation || this.DefaultInterpolation); + } + static toJSON(track) { + const trackType = track.constructor; + let json; + if (trackType.toJSON !== this.toJSON) { + json = trackType.toJSON(track); + } else { + json = { + name: track.name, + times: convertArray(track.times, Array), + values: convertArray(track.values, Array) + }; + const interpolation = track.getInterpolation(); + if (interpolation !== track.DefaultInterpolation) { + json.interpolation = interpolation; + } + } + json.type = track.ValueTypeName; + return json; + } + InterpolantFactoryMethodDiscrete(result) { + return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodLinear(result) { + return new LinearInterpolant(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodSmooth(result) { + return new CubicInterpolant(this.times, this.values, this.getValueSize(), result); + } + setInterpolation(interpolation) { + let factoryMethod; + switch (interpolation) { + case InterpolateDiscrete: + factoryMethod = this.InterpolantFactoryMethodDiscrete; + break; + case InterpolateLinear: + factoryMethod = this.InterpolantFactoryMethodLinear; + break; + case InterpolateSmooth: + factoryMethod = this.InterpolantFactoryMethodSmooth; + break; + } + if (factoryMethod === undefined) { + const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; + if (this.createInterpolant === undefined) { + if (interpolation !== this.DefaultInterpolation) { + this.setInterpolation(this.DefaultInterpolation); + } else { + throw new Error(message); + } + } + console.warn("THREE.KeyframeTrack:", message); + return this; + } + this.createInterpolant = factoryMethod; + return this; + } + getInterpolation() { + switch (this.createInterpolant) { + case this.InterpolantFactoryMethodDiscrete: + return InterpolateDiscrete; + case this.InterpolantFactoryMethodLinear: + return InterpolateLinear; + case this.InterpolantFactoryMethodSmooth: + return InterpolateSmooth; + } + } + getValueSize() { + return this.values.length / this.times.length; + } + shift(timeOffset) { + if (timeOffset !== 0) { + const times = this.times; + for (let i = 0, n = times.length;i !== n; ++i) { + times[i] += timeOffset; + } + } + return this; + } + scale(timeScale) { + if (timeScale !== 1) { + const times = this.times; + for (let i = 0, n = times.length;i !== n; ++i) { + times[i] *= timeScale; + } + } + return this; + } + trim(startTime, endTime) { + const times = this.times, nKeys = times.length; + let from = 0, to = nKeys - 1; + while (from !== nKeys && times[from] < startTime) { + ++from; + } + while (to !== -1 && times[to] > endTime) { + --to; + } + ++to; + if (from !== 0 || to !== nKeys) { + if (from >= to) { + to = Math.max(to, 1); + from = to - 1; + } + const stride = this.getValueSize(); + this.times = times.slice(from, to); + this.values = this.values.slice(from * stride, to * stride); + } + return this; + } + validate() { + let valid = true; + const valueSize = this.getValueSize(); + if (valueSize - Math.floor(valueSize) !== 0) { + console.error("THREE.KeyframeTrack: Invalid value size in track.", this); + valid = false; + } + const times = this.times, values2 = this.values, nKeys = times.length; + if (nKeys === 0) { + console.error("THREE.KeyframeTrack: Track is empty.", this); + valid = false; + } + let prevTime = null; + for (let i = 0;i !== nKeys; i++) { + const currTime = times[i]; + if (typeof currTime === "number" && isNaN(currTime)) { + console.error("THREE.KeyframeTrack: Time is not a valid number.", this, i, currTime); + valid = false; + break; + } + if (prevTime !== null && prevTime > currTime) { + console.error("THREE.KeyframeTrack: Out of order keys.", this, i, currTime, prevTime); + valid = false; + break; + } + prevTime = currTime; + } + if (values2 !== undefined) { + if (isTypedArray(values2)) { + for (let i = 0, n = values2.length;i !== n; ++i) { + const value2 = values2[i]; + if (isNaN(value2)) { + console.error("THREE.KeyframeTrack: Value is not a valid number.", this, i, value2); + valid = false; + break; + } + } + } + } + return valid; + } + optimize() { + const times = this.times.slice(), values2 = this.values.slice(), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth, lastIndex = times.length - 1; + let writeIndex = 1; + for (let i = 1;i < lastIndex; ++i) { + let keep = false; + const time2 = times[i]; + const timeNext = times[i + 1]; + if (time2 !== timeNext && (i !== 1 || time2 !== times[0])) { + if (!smoothInterpolation) { + const offset = i * stride, offsetP = offset - stride, offsetN = offset + stride; + for (let j = 0;j !== stride; ++j) { + const value2 = values2[offset + j]; + if (value2 !== values2[offsetP + j] || value2 !== values2[offsetN + j]) { + keep = true; + break; + } + } + } else { + keep = true; + } + } + if (keep) { + if (i !== writeIndex) { + times[writeIndex] = times[i]; + const readOffset = i * stride, writeOffset = writeIndex * stride; + for (let j = 0;j !== stride; ++j) { + values2[writeOffset + j] = values2[readOffset + j]; + } + } + ++writeIndex; + } + } + if (lastIndex > 0) { + times[writeIndex] = times[lastIndex]; + for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0;j !== stride; ++j) { + values2[writeOffset + j] = values2[readOffset + j]; + } + ++writeIndex; + } + if (writeIndex !== times.length) { + this.times = times.slice(0, writeIndex); + this.values = values2.slice(0, writeIndex * stride); + } else { + this.times = times; + this.values = values2; + } + return this; + } + clone() { + const times = this.times.slice(); + const values2 = this.values.slice(); + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack(this.name, times, values2); + track.createInterpolant = this.createInterpolant; + return track; + } +} +KeyframeTrack.prototype.TimeBufferType = Float32Array; +KeyframeTrack.prototype.ValueBufferType = Float32Array; +KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + +class BooleanKeyframeTrack extends KeyframeTrack { + constructor(name2, times, values2) { + super(name2, times, values2); + } +} +BooleanKeyframeTrack.prototype.ValueTypeName = "bool"; +BooleanKeyframeTrack.prototype.ValueBufferType = Array; +BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +class ColorKeyframeTrack extends KeyframeTrack { +} +ColorKeyframeTrack.prototype.ValueTypeName = "color"; + +class NumberKeyframeTrack extends KeyframeTrack { +} +NumberKeyframeTrack.prototype.ValueTypeName = "number"; + +class QuaternionLinearInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, alpha = (t - t0) / (t1 - t0); + let offset = i1 * stride; + for (let end = offset + stride;offset !== end; offset += 4) { + Quaternion.slerpFlat(result, 0, values2, offset - stride, values2, offset, alpha); + } + return result; + } +} + +class QuaternionKeyframeTrack extends KeyframeTrack { + InterpolantFactoryMethodLinear(result) { + return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result); + } +} +QuaternionKeyframeTrack.prototype.ValueTypeName = "quaternion"; +QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +class StringKeyframeTrack extends KeyframeTrack { + constructor(name2, times, values2) { + super(name2, times, values2); + } +} +StringKeyframeTrack.prototype.ValueTypeName = "string"; +StringKeyframeTrack.prototype.ValueBufferType = Array; +StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +class VectorKeyframeTrack extends KeyframeTrack { +} +VectorKeyframeTrack.prototype.ValueTypeName = "vector"; + +class AnimationClip { + constructor(name2 = "", duration = -1, tracks = [], blendMode = NormalAnimationBlendMode) { + this.name = name2; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; + this.uuid = generateUUID(); + if (this.duration < 0) { + this.resetDuration(); + } + } + static parse(json) { + const tracks = [], jsonTracks = json.tracks, frameTime = 1 / (json.fps || 1); + for (let i = 0, n = jsonTracks.length;i !== n; ++i) { + tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime)); + } + const clip = new this(json.name, json.duration, tracks, json.blendMode); + clip.uuid = json.uuid; + return clip; + } + static toJSON(clip) { + const tracks = [], clipTracks = clip.tracks; + const json = { + name: clip.name, + duration: clip.duration, + tracks, + uuid: clip.uuid, + blendMode: clip.blendMode + }; + for (let i = 0, n = clipTracks.length;i !== n; ++i) { + tracks.push(KeyframeTrack.toJSON(clipTracks[i])); + } + return json; + } + static CreateFromMorphTargetSequence(name2, morphTargetSequence, fps, noLoop) { + const numMorphTargets = morphTargetSequence.length; + const tracks = []; + for (let i = 0;i < numMorphTargets; i++) { + let times = []; + let values2 = []; + times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets); + values2.push(0, 1, 0); + const order = getKeyframeOrder(times); + times = sortedArray(times, 1, order); + values2 = sortedArray(values2, 1, order); + if (!noLoop && times[0] === 0) { + times.push(numMorphTargets); + values2.push(values2[0]); + } + tracks.push(new NumberKeyframeTrack(".morphTargetInfluences[" + morphTargetSequence[i].name + "]", times, values2).scale(1 / fps)); + } + return new this(name2, -1, tracks); + } + static findByName(objectOrClipArray, name2) { + let clipArray = objectOrClipArray; + if (!Array.isArray(objectOrClipArray)) { + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; + } + for (let i = 0;i < clipArray.length; i++) { + if (clipArray[i].name === name2) { + return clipArray[i]; + } + } + return null; + } + static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) { + const animationToMorphTargets = {}; + const pattern = /^([\w-]*?)([\d]+)$/; + for (let i = 0, il = morphTargets.length;i < il; i++) { + const morphTarget = morphTargets[i]; + const parts = morphTarget.name.match(pattern); + if (parts && parts.length > 1) { + const name2 = parts[1]; + let animationMorphTargets = animationToMorphTargets[name2]; + if (!animationMorphTargets) { + animationToMorphTargets[name2] = animationMorphTargets = []; + } + animationMorphTargets.push(morphTarget); + } + } + const clips = []; + for (const name2 in animationToMorphTargets) { + clips.push(this.CreateFromMorphTargetSequence(name2, animationToMorphTargets[name2], fps, noLoop)); + } + return clips; + } + static parseAnimation(animation, bones) { + if (!animation) { + console.error("THREE.AnimationClip: No animation in JSONLoader data."); + return null; + } + const addNonemptyTrack = function(trackType, trackName, animationKeys, propertyName, destTracks) { + if (animationKeys.length !== 0) { + const times = []; + const values2 = []; + flattenJSON(animationKeys, times, values2, propertyName); + if (times.length !== 0) { + destTracks.push(new trackType(trackName, times, values2)); + } + } + }; + const tracks = []; + const clipName = animation.name || "default"; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; + let duration = animation.length || -1; + const hierarchyTracks = animation.hierarchy || []; + for (let h = 0;h < hierarchyTracks.length; h++) { + const animationKeys = hierarchyTracks[h].keys; + if (!animationKeys || animationKeys.length === 0) + continue; + if (animationKeys[0].morphTargets) { + const morphTargetNames = {}; + let k2; + for (k2 = 0;k2 < animationKeys.length; k2++) { + if (animationKeys[k2].morphTargets) { + for (let m = 0;m < animationKeys[k2].morphTargets.length; m++) { + morphTargetNames[animationKeys[k2].morphTargets[m]] = -1; + } + } + } + for (const morphTargetName in morphTargetNames) { + const times = []; + const values2 = []; + for (let m = 0;m !== animationKeys[k2].morphTargets.length; ++m) { + const animationKey = animationKeys[k2]; + times.push(animationKey.time); + values2.push(animationKey.morphTarget === morphTargetName ? 1 : 0); + } + tracks.push(new NumberKeyframeTrack(".morphTargetInfluence[" + morphTargetName + "]", times, values2)); + } + duration = morphTargetNames.length * fps; + } else { + const boneName = ".bones[" + bones[h].name + "]"; + addNonemptyTrack(VectorKeyframeTrack, boneName + ".position", animationKeys, "pos", tracks); + addNonemptyTrack(QuaternionKeyframeTrack, boneName + ".quaternion", animationKeys, "rot", tracks); + addNonemptyTrack(VectorKeyframeTrack, boneName + ".scale", animationKeys, "scl", tracks); + } + } + if (tracks.length === 0) { + return null; + } + const clip = new this(clipName, duration, tracks, blendMode); + return clip; + } + resetDuration() { + const tracks = this.tracks; + let duration = 0; + for (let i = 0, n = tracks.length;i !== n; ++i) { + const track = this.tracks[i]; + duration = Math.max(duration, track.times[track.times.length - 1]); + } + this.duration = duration; + return this; + } + trim() { + for (let i = 0;i < this.tracks.length; i++) { + this.tracks[i].trim(0, this.duration); + } + return this; + } + validate() { + let valid = true; + for (let i = 0;i < this.tracks.length; i++) { + valid = valid && this.tracks[i].validate(); + } + return valid; + } + optimize() { + for (let i = 0;i < this.tracks.length; i++) { + this.tracks[i].optimize(); + } + return this; + } + clone() { + const tracks = []; + for (let i = 0;i < this.tracks.length; i++) { + tracks.push(this.tracks[i].clone()); + } + return new this.constructor(this.name, this.duration, tracks, this.blendMode); + } + toJSON() { + return this.constructor.toJSON(this); + } +} +function getTrackTypeForValueTypeName(typeName) { + switch (typeName.toLowerCase()) { + case "scalar": + case "double": + case "float": + case "number": + case "integer": + return NumberKeyframeTrack; + case "vector": + case "vector2": + case "vector3": + case "vector4": + return VectorKeyframeTrack; + case "color": + return ColorKeyframeTrack; + case "quaternion": + return QuaternionKeyframeTrack; + case "bool": + case "boolean": + return BooleanKeyframeTrack; + case "string": + return StringKeyframeTrack; + } + throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + typeName); +} +function parseKeyframeTrack(json) { + if (json.type === undefined) { + throw new Error("THREE.KeyframeTrack: track type undefined, can not parse"); + } + const trackType = getTrackTypeForValueTypeName(json.type); + if (json.times === undefined) { + const times = [], values2 = []; + flattenJSON(json.keys, times, values2, "value"); + json.times = times; + json.values = values2; + } + if (trackType.parse !== undefined) { + return trackType.parse(json); + } else { + return new trackType(json.name, json.times, json.values, json.interpolation); + } +} +var Cache = { + enabled: false, + files: {}, + add: function(key2, file) { + if (this.enabled === false) + return; + this.files[key2] = file; + }, + get: function(key2) { + if (this.enabled === false) + return; + return this.files[key2]; + }, + remove: function(key2) { + delete this.files[key2]; + }, + clear: function() { + this.files = {}; + } +}; + +class LoadingManager { + constructor(onLoad, onProgress, onError) { + const scope = this; + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + this.itemStart = function(url) { + itemsTotal++; + if (isLoading === false) { + if (scope.onStart !== undefined) { + scope.onStart(url, itemsLoaded, itemsTotal); + } + } + isLoading = true; + }; + this.itemEnd = function(url) { + itemsLoaded++; + if (scope.onProgress !== undefined) { + scope.onProgress(url, itemsLoaded, itemsTotal); + } + if (itemsLoaded === itemsTotal) { + isLoading = false; + if (scope.onLoad !== undefined) { + scope.onLoad(); + } + } + }; + this.itemError = function(url) { + if (scope.onError !== undefined) { + scope.onError(url); + } + }; + this.resolveURL = function(url) { + if (urlModifier) { + return urlModifier(url); + } + return url; + }; + this.setURLModifier = function(transform2) { + urlModifier = transform2; + return this; + }; + this.addHandler = function(regex, loader) { + handlers.push(regex, loader); + return this; + }; + this.removeHandler = function(regex) { + const index2 = handlers.indexOf(regex); + if (index2 !== -1) { + handlers.splice(index2, 2); + } + return this; + }; + this.getHandler = function(file) { + for (let i = 0, l = handlers.length;i < l; i += 2) { + const regex = handlers[i]; + const loader = handlers[i + 1]; + if (regex.global) + regex.lastIndex = 0; + if (regex.test(file)) { + return loader; + } + } + return null; + }; + } +} +var DefaultLoadingManager = /* @__PURE__ */ new LoadingManager; + +class Loader { + constructor(manager) { + this.manager = manager !== undefined ? manager : DefaultLoadingManager; + this.crossOrigin = "anonymous"; + this.withCredentials = false; + this.path = ""; + this.resourcePath = ""; + this.requestHeader = {}; + } + load() { + } + loadAsync(url, onProgress) { + const scope = this; + return new Promise(function(resolve, reject2) { + scope.load(url, resolve, onProgress, reject2); + }); + } + parse() { + } + setCrossOrigin(crossOrigin) { + this.crossOrigin = crossOrigin; + return this; + } + setWithCredentials(value2) { + this.withCredentials = value2; + return this; + } + setPath(path) { + this.path = path; + return this; + } + setResourcePath(resourcePath) { + this.resourcePath = resourcePath; + return this; + } + setRequestHeader(requestHeader) { + this.requestHeader = requestHeader; + return this; + } +} +Loader.DEFAULT_MATERIAL_NAME = "__DEFAULT"; +var loading = {}; + +class HttpError extends Error { + constructor(message, response) { + super(message); + this.response = response; + } +} + +class FileLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (url === undefined) + url = ""; + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const cached = Cache.get(url); + if (cached !== undefined) { + this.manager.itemStart(url); + setTimeout(() => { + if (onLoad) + onLoad(cached); + this.manager.itemEnd(url); + }, 0); + return cached; + } + if (loading[url] !== undefined) { + loading[url].push({ + onLoad, + onProgress, + onError + }); + return; + } + loading[url] = []; + loading[url].push({ + onLoad, + onProgress, + onError + }); + const req = new Request(url, { + headers: new Headers(this.requestHeader), + credentials: this.withCredentials ? "include" : "same-origin" + }); + const mimeType = this.mimeType; + const responseType = this.responseType; + fetch(req).then((response) => { + if (response.status === 200 || response.status === 0) { + if (response.status === 0) { + console.warn("THREE.FileLoader: HTTP Status 0 received."); + } + if (typeof ReadableStream === "undefined" || response.body === undefined || response.body.getReader === undefined) { + return response; + } + const callbacks = loading[url]; + const reader = response.body.getReader(); + const contentLength = response.headers.get("X-File-Size") || response.headers.get("Content-Length"); + const total = contentLength ? parseInt(contentLength) : 0; + const lengthComputable = total !== 0; + let loaded = 0; + const stream = new ReadableStream({ + start(controller) { + readData(); + function readData() { + reader.read().then(({ done, value: value2 }) => { + if (done) { + controller.close(); + } else { + loaded += value2.byteLength; + const event = new ProgressEvent("progress", { lengthComputable, loaded, total }); + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onProgress) + callback.onProgress(event); + } + controller.enqueue(value2); + readData(); + } + }, (e) => { + controller.error(e); + }); + } + } + }); + return new Response(stream); + } else { + throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response); + } + }).then((response) => { + switch (responseType) { + case "arraybuffer": + return response.arrayBuffer(); + case "blob": + return response.blob(); + case "document": + return response.text().then((text2) => { + const parser = new DOMParser; + return parser.parseFromString(text2, mimeType); + }); + case "json": + return response.json(); + default: + if (mimeType === undefined) { + return response.text(); + } else { + const re = /charset="?([^;"\s]*)"?/i; + const exec = re.exec(mimeType); + const label = exec && exec[1] ? exec[1].toLowerCase() : undefined; + const decoder = new TextDecoder(label); + return response.arrayBuffer().then((ab) => decoder.decode(ab)); + } + } + }).then((data2) => { + Cache.add(url, data2); + const callbacks = loading[url]; + delete loading[url]; + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onLoad) + callback.onLoad(data2); + } + }).catch((err) => { + const callbacks = loading[url]; + if (callbacks === undefined) { + this.manager.itemError(url); + throw err; + } + delete loading[url]; + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onError) + callback.onError(err); + } + this.manager.itemError(url); + }).finally(() => { + this.manager.itemEnd(url); + }); + this.manager.itemStart(url); + } + setResponseType(value2) { + this.responseType = value2; + return this; + } + setMimeType(value2) { + this.mimeType = value2; + return this; + } +} + +class AnimationLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const animations = []; + for (let i = 0;i < json.length; i++) { + const clip = AnimationClip.parse(json[i]); + animations.push(clip); + } + return animations; + } +} + +class CompressedTextureLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const images = []; + const texture = new CompressedTexture; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(scope.withCredentials); + let loaded = 0; + function loadTexture(i) { + loader.load(url[i], function(buffer) { + const texDatas = scope.parse(buffer, true); + images[i] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + loaded += 1; + if (loaded === 6) { + if (texDatas.mipmapCount === 1) + texture.minFilter = LinearFilter; + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + } + }, onProgress, onError); + } + if (Array.isArray(url)) { + for (let i = 0, il = url.length;i < il; ++i) { + loadTexture(i); + } + } else { + loader.load(url, function(buffer) { + const texDatas = scope.parse(buffer, true); + if (texDatas.isCubemap) { + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + for (let f = 0;f < faces; f++) { + images[f] = { mipmaps: [] }; + for (let i = 0;i < texDatas.mipmapCount; i++) { + images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]); + images[f].format = texDatas.format; + images[f].width = texDatas.width; + images[f].height = texDatas.height; + } + } + texture.image = images; + } else { + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + } + if (texDatas.mipmapCount === 1) { + texture.minFilter = LinearFilter; + } + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + }, onProgress, onError); + } + return texture; + } +} + +class ImageLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache.get(url); + if (cached !== undefined) { + scope.manager.itemStart(url); + setTimeout(function() { + if (onLoad) + onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const image = createElementNS("img"); + function onImageLoad() { + removeEventListeners(); + Cache.add(url, this); + if (onLoad) + onLoad(this); + scope.manager.itemEnd(url); + } + function onImageError(event) { + removeEventListeners(); + if (onError) + onError(event); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + } + function removeEventListeners() { + image.removeEventListener("load", onImageLoad, false); + image.removeEventListener("error", onImageError, false); + } + image.addEventListener("load", onImageLoad, false); + image.addEventListener("error", onImageError, false); + if (url.slice(0, 5) !== "data:") { + if (this.crossOrigin !== undefined) + image.crossOrigin = this.crossOrigin; + } + scope.manager.itemStart(url); + image.src = url; + return image; + } +} + +class CubeTextureLoader extends Loader { + constructor(manager) { + super(manager); + } + load(urls, onLoad, onProgress, onError) { + const texture = new CubeTexture; + texture.colorSpace = SRGBColorSpace; + const loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + let loaded = 0; + function loadTexture(i) { + loader.load(urls[i], function(image) { + texture.images[i] = image; + loaded++; + if (loaded === 6) { + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + } + }, undefined, onError); + } + for (let i = 0;i < urls.length; ++i) { + loadTexture(i); + } + return texture; + } +} + +class DataTextureLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const texture = new DataTexture; + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setPath(this.path); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(buffer) { + let texData; + try { + texData = scope.parse(buffer); + } catch (error) { + if (onError !== undefined) { + onError(error); + } else { + console.error(error); + return; + } + } + if (texData.image !== undefined) { + texture.image = texData.image; + } else if (texData.data !== undefined) { + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; + } + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + if (texData.colorSpace !== undefined) { + texture.colorSpace = texData.colorSpace; + } + if (texData.flipY !== undefined) { + texture.flipY = texData.flipY; + } + if (texData.format !== undefined) { + texture.format = texData.format; + } + if (texData.type !== undefined) { + texture.type = texData.type; + } + if (texData.mipmaps !== undefined) { + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter; + } + if (texData.mipmapCount === 1) { + texture.minFilter = LinearFilter; + } + if (texData.generateMipmaps !== undefined) { + texture.generateMipmaps = texData.generateMipmaps; + } + texture.needsUpdate = true; + if (onLoad) + onLoad(texture, texData); + }, onProgress, onError); + return texture; + } +} + +class TextureLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const texture = new Texture; + const loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + loader.load(url, function(image) { + texture.image = image; + texture.needsUpdate = true; + if (onLoad !== undefined) { + onLoad(texture); + } + }, onProgress, onError); + return texture; + } +} + +class Light extends Object3D { + constructor(color, intensity = 1) { + super(); + this.isLight = true; + this.type = "Light"; + this.color = new Color(color); + this.intensity = intensity; + } + dispose() { + } + copy(source, recursive) { + super.copy(source, recursive); + this.color.copy(source.color); + this.intensity = source.intensity; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.color = this.color.getHex(); + data2.object.intensity = this.intensity; + if (this.groundColor !== undefined) + data2.object.groundColor = this.groundColor.getHex(); + if (this.distance !== undefined) + data2.object.distance = this.distance; + if (this.angle !== undefined) + data2.object.angle = this.angle; + if (this.decay !== undefined) + data2.object.decay = this.decay; + if (this.penumbra !== undefined) + data2.object.penumbra = this.penumbra; + if (this.shadow !== undefined) + data2.object.shadow = this.shadow.toJSON(); + if (this.target !== undefined) + data2.object.target = this.target.uuid; + return data2; + } +} + +class HemisphereLight extends Light { + constructor(skyColor, groundColor, intensity) { + super(skyColor, intensity); + this.isHemisphereLight = true; + this.type = "HemisphereLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.groundColor = new Color(groundColor); + } + copy(source, recursive) { + super.copy(source, recursive); + this.groundColor.copy(source.groundColor); + return this; + } +} +var _projScreenMatrix$1 = /* @__PURE__ */ new Matrix4; +var _lightPositionWorld$1 = /* @__PURE__ */ new Vector3; +var _lookTarget$1 = /* @__PURE__ */ new Vector3; + +class LightShadow { + constructor(camera) { + this.camera = camera; + this.intensity = 1; + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; + this.mapSize = new Vector2(512, 512); + this.map = null; + this.mapPass = null; + this.matrix = new Matrix4; + this.autoUpdate = true; + this.needsUpdate = false; + this._frustum = new Frustum; + this._frameExtents = new Vector2(1, 1); + this._viewportCount = 1; + this._viewports = [ + new Vector4(0, 0, 1, 1) + ]; + } + getViewportCount() { + return this._viewportCount; + } + getFrustum() { + return this._frustum; + } + updateMatrices(light) { + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; + _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld); + shadowCamera.position.copy(_lightPositionWorld$1); + _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld); + shadowCamera.lookAt(_lookTarget$1); + shadowCamera.updateMatrixWorld(); + _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix$1); + shadowMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + shadowMatrix.multiply(_projScreenMatrix$1); + } + getViewport(viewportIndex) { + return this._viewports[viewportIndex]; + } + getFrameExtents() { + return this._frameExtents; + } + dispose() { + if (this.map) { + this.map.dispose(); + } + if (this.mapPass) { + this.mapPass.dispose(); + } + } + copy(source) { + this.camera = source.camera.clone(); + this.intensity = source.intensity; + this.bias = source.bias; + this.radius = source.radius; + this.mapSize.copy(source.mapSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + toJSON() { + const object = {}; + if (this.intensity !== 1) + object.intensity = this.intensity; + if (this.bias !== 0) + object.bias = this.bias; + if (this.normalBias !== 0) + object.normalBias = this.normalBias; + if (this.radius !== 1) + object.radius = this.radius; + if (this.mapSize.x !== 512 || this.mapSize.y !== 512) + object.mapSize = this.mapSize.toArray(); + object.camera = this.camera.toJSON(false).object; + delete object.camera.matrix; + return object; + } +} + +class SpotLightShadow extends LightShadow { + constructor() { + super(new PerspectiveCamera(50, 1, 0.5, 500)); + this.isSpotLightShadow = true; + this.focus = 1; + } + updateMatrices(light) { + const camera = this.camera; + const fov2 = RAD2DEG * 2 * light.angle * this.focus; + const aspect2 = this.mapSize.width / this.mapSize.height; + const far = light.distance || camera.far; + if (fov2 !== camera.fov || aspect2 !== camera.aspect || far !== camera.far) { + camera.fov = fov2; + camera.aspect = aspect2; + camera.far = far; + camera.updateProjectionMatrix(); + } + super.updateMatrices(light); + } + copy(source) { + super.copy(source); + this.focus = source.focus; + return this; + } +} + +class SpotLight extends Light { + constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2) { + super(color, intensity); + this.isSpotLight = true; + this.type = "SpotLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D; + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; + this.map = null; + this.shadow = new SpotLightShadow; + } + get power() { + return this.intensity * Math.PI; + } + set power(power) { + this.intensity = power / Math.PI; + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } +} +var _projScreenMatrix = /* @__PURE__ */ new Matrix4; +var _lightPositionWorld = /* @__PURE__ */ new Vector3; +var _lookTarget = /* @__PURE__ */ new Vector3; + +class PointLightShadow extends LightShadow { + constructor() { + super(new PerspectiveCamera(90, 1, 0.5, 500)); + this.isPointLightShadow = true; + this._frameExtents = new Vector2(4, 2); + this._viewportCount = 6; + this._viewports = [ + new Vector4(2, 1, 1, 1), + new Vector4(0, 1, 1, 1), + new Vector4(3, 1, 1, 1), + new Vector4(1, 1, 1, 1), + new Vector4(3, 0, 1, 1), + new Vector4(1, 0, 1, 1) + ]; + this._cubeDirections = [ + new Vector3(1, 0, 0), + new Vector3(-1, 0, 0), + new Vector3(0, 0, 1), + new Vector3(0, 0, -1), + new Vector3(0, 1, 0), + new Vector3(0, -1, 0) + ]; + this._cubeUps = [ + new Vector3(0, 1, 0), + new Vector3(0, 1, 0), + new Vector3(0, 1, 0), + new Vector3(0, 1, 0), + new Vector3(0, 0, 1), + new Vector3(0, 0, -1) + ]; + } + updateMatrices(light, viewportIndex = 0) { + const camera = this.camera; + const shadowMatrix = this.matrix; + const far = light.distance || camera.far; + if (far !== camera.far) { + camera.far = far; + camera.updateProjectionMatrix(); + } + _lightPositionWorld.setFromMatrixPosition(light.matrixWorld); + camera.position.copy(_lightPositionWorld); + _lookTarget.copy(camera.position); + _lookTarget.add(this._cubeDirections[viewportIndex]); + camera.up.copy(this._cubeUps[viewportIndex]); + camera.lookAt(_lookTarget); + camera.updateMatrixWorld(); + shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z); + _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix); + } +} + +class PointLight extends Light { + constructor(color, intensity, distance = 0, decay = 2) { + super(color, intensity); + this.isPointLight = true; + this.type = "PointLight"; + this.distance = distance; + this.decay = decay; + this.shadow = new PointLightShadow; + } + get power() { + return this.intensity * 4 * Math.PI; + } + set power(power) { + this.intensity = power / (4 * Math.PI); + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.decay = source.decay; + this.shadow = source.shadow.clone(); + return this; + } +} + +class OrthographicCamera extends Camera { + constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) { + super(); + this.isOrthographicCamera = true; + this.type = "OrthographicCamera"; + this.zoom = 1; + this.view = null; + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + this.near = near; + this.far = far; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign({}, source.view); + return this; + } + setViewOffset(fullWidth, fullHeight, x, y, width2, height2) { + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width2; + this.view.height = height2; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const dx = (this.right - this.left) / (2 * this.zoom); + const dy = (this.top - this.bottom) / (2 * this.zoom); + const cx = (this.right + this.left) / 2; + const cy = (this.top + this.bottom) / 2; + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + if (this.view !== null && this.view.enabled) { + const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom; + const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom; + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + } + this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.zoom = this.zoom; + data2.object.left = this.left; + data2.object.right = this.right; + data2.object.top = this.top; + data2.object.bottom = this.bottom; + data2.object.near = this.near; + data2.object.far = this.far; + if (this.view !== null) + data2.object.view = Object.assign({}, this.view); + return data2; + } +} + +class DirectionalLightShadow extends LightShadow { + constructor() { + super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500)); + this.isDirectionalLightShadow = true; + } +} + +class DirectionalLight extends Light { + constructor(color, intensity) { + super(color, intensity); + this.isDirectionalLight = true; + this.type = "DirectionalLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D; + this.shadow = new DirectionalLightShadow; + } + dispose() { + this.shadow.dispose(); + } + copy(source) { + super.copy(source); + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } +} + +class AmbientLight extends Light { + constructor(color, intensity) { + super(color, intensity); + this.isAmbientLight = true; + this.type = "AmbientLight"; + } +} + +class RectAreaLight extends Light { + constructor(color, intensity, width2 = 10, height2 = 10) { + super(color, intensity); + this.isRectAreaLight = true; + this.type = "RectAreaLight"; + this.width = width2; + this.height = height2; + } + get power() { + return this.intensity * this.width * this.height * Math.PI; + } + set power(power) { + this.intensity = power / (this.width * this.height * Math.PI); + } + copy(source) { + super.copy(source); + this.width = source.width; + this.height = source.height; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.width = this.width; + data2.object.height = this.height; + return data2; + } +} + +class SphericalHarmonics3 { + constructor() { + this.isSphericalHarmonics3 = true; + this.coefficients = []; + for (let i = 0;i < 9; i++) { + this.coefficients.push(new Vector3); + } + } + set(coefficients) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].copy(coefficients[i]); + } + return this; + } + zero() { + for (let i = 0;i < 9; i++) { + this.coefficients[i].set(0, 0, 0); + } + return this; + } + getAt(normal, target) { + const { x, y, z } = normal; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.282095); + target.addScaledVector(coeff[1], 0.488603 * y); + target.addScaledVector(coeff[2], 0.488603 * z); + target.addScaledVector(coeff[3], 0.488603 * x); + target.addScaledVector(coeff[4], 1.092548 * (x * y)); + target.addScaledVector(coeff[5], 1.092548 * (y * z)); + target.addScaledVector(coeff[6], 0.315392 * (3 * z * z - 1)); + target.addScaledVector(coeff[7], 1.092548 * (x * z)); + target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y)); + return target; + } + getIrradianceAt(normal, target) { + const { x, y, z } = normal; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.886227); + target.addScaledVector(coeff[1], 2 * 0.511664 * y); + target.addScaledVector(coeff[2], 2 * 0.511664 * z); + target.addScaledVector(coeff[3], 2 * 0.511664 * x); + target.addScaledVector(coeff[4], 2 * 0.429043 * x * y); + target.addScaledVector(coeff[5], 2 * 0.429043 * y * z); + target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); + target.addScaledVector(coeff[7], 2 * 0.429043 * x * z); + target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); + return target; + } + add(sh) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].add(sh.coefficients[i]); + } + return this; + } + addScaledSH(sh, s) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].addScaledVector(sh.coefficients[i], s); + } + return this; + } + scale(s) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].multiplyScalar(s); + } + return this; + } + lerp(sh, alpha) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].lerp(sh.coefficients[i], alpha); + } + return this; + } + equals(sh) { + for (let i = 0;i < 9; i++) { + if (!this.coefficients[i].equals(sh.coefficients[i])) { + return false; + } + } + return true; + } + copy(sh) { + return this.set(sh.coefficients); + } + clone() { + return new this.constructor().copy(this); + } + fromArray(array, offset = 0) { + const coefficients = this.coefficients; + for (let i = 0;i < 9; i++) { + coefficients[i].fromArray(array, offset + i * 3); + } + return this; + } + toArray(array = [], offset = 0) { + const coefficients = this.coefficients; + for (let i = 0;i < 9; i++) { + coefficients[i].toArray(array, offset + i * 3); + } + return array; + } + static getBasisAt(normal, shBasis) { + const { x, y, z } = normal; + shBasis[0] = 0.282095; + shBasis[1] = 0.488603 * y; + shBasis[2] = 0.488603 * z; + shBasis[3] = 0.488603 * x; + shBasis[4] = 1.092548 * x * y; + shBasis[5] = 1.092548 * y * z; + shBasis[6] = 0.315392 * (3 * z * z - 1); + shBasis[7] = 1.092548 * x * z; + shBasis[8] = 0.546274 * (x * x - y * y); + } +} + +class LightProbe extends Light { + constructor(sh = new SphericalHarmonics3, intensity = 1) { + super(undefined, intensity); + this.isLightProbe = true; + this.sh = sh; + } + copy(source) { + super.copy(source); + this.sh.copy(source.sh); + return this; + } + fromJSON(json) { + this.intensity = json.intensity; + this.sh.fromArray(json.sh); + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.sh = this.sh.toArray(); + return data2; + } +} + +class MaterialLoader extends Loader { + constructor(manager) { + super(manager); + this.textures = {}; + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const textures = this.textures; + function getTexture(name2) { + if (textures[name2] === undefined) { + console.warn("THREE.MaterialLoader: Undefined texture", name2); + } + return textures[name2]; + } + const material = this.createMaterialFromType(json.type); + if (json.uuid !== undefined) + material.uuid = json.uuid; + if (json.name !== undefined) + material.name = json.name; + if (json.color !== undefined && material.color !== undefined) + material.color.setHex(json.color); + if (json.roughness !== undefined) + material.roughness = json.roughness; + if (json.metalness !== undefined) + material.metalness = json.metalness; + if (json.sheen !== undefined) + material.sheen = json.sheen; + if (json.sheenColor !== undefined) + material.sheenColor = new Color().setHex(json.sheenColor); + if (json.sheenRoughness !== undefined) + material.sheenRoughness = json.sheenRoughness; + if (json.emissive !== undefined && material.emissive !== undefined) + material.emissive.setHex(json.emissive); + if (json.specular !== undefined && material.specular !== undefined) + material.specular.setHex(json.specular); + if (json.specularIntensity !== undefined) + material.specularIntensity = json.specularIntensity; + if (json.specularColor !== undefined && material.specularColor !== undefined) + material.specularColor.setHex(json.specularColor); + if (json.shininess !== undefined) + material.shininess = json.shininess; + if (json.clearcoat !== undefined) + material.clearcoat = json.clearcoat; + if (json.clearcoatRoughness !== undefined) + material.clearcoatRoughness = json.clearcoatRoughness; + if (json.dispersion !== undefined) + material.dispersion = json.dispersion; + if (json.iridescence !== undefined) + material.iridescence = json.iridescence; + if (json.iridescenceIOR !== undefined) + material.iridescenceIOR = json.iridescenceIOR; + if (json.iridescenceThicknessRange !== undefined) + material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if (json.transmission !== undefined) + material.transmission = json.transmission; + if (json.thickness !== undefined) + material.thickness = json.thickness; + if (json.attenuationDistance !== undefined) + material.attenuationDistance = json.attenuationDistance; + if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) + material.attenuationColor.setHex(json.attenuationColor); + if (json.anisotropy !== undefined) + material.anisotropy = json.anisotropy; + if (json.anisotropyRotation !== undefined) + material.anisotropyRotation = json.anisotropyRotation; + if (json.fog !== undefined) + material.fog = json.fog; + if (json.flatShading !== undefined) + material.flatShading = json.flatShading; + if (json.blending !== undefined) + material.blending = json.blending; + if (json.combine !== undefined) + material.combine = json.combine; + if (json.side !== undefined) + material.side = json.side; + if (json.shadowSide !== undefined) + material.shadowSide = json.shadowSide; + if (json.opacity !== undefined) + material.opacity = json.opacity; + if (json.transparent !== undefined) + material.transparent = json.transparent; + if (json.alphaTest !== undefined) + material.alphaTest = json.alphaTest; + if (json.alphaHash !== undefined) + material.alphaHash = json.alphaHash; + if (json.depthFunc !== undefined) + material.depthFunc = json.depthFunc; + if (json.depthTest !== undefined) + material.depthTest = json.depthTest; + if (json.depthWrite !== undefined) + material.depthWrite = json.depthWrite; + if (json.colorWrite !== undefined) + material.colorWrite = json.colorWrite; + if (json.blendSrc !== undefined) + material.blendSrc = json.blendSrc; + if (json.blendDst !== undefined) + material.blendDst = json.blendDst; + if (json.blendEquation !== undefined) + material.blendEquation = json.blendEquation; + if (json.blendSrcAlpha !== undefined) + material.blendSrcAlpha = json.blendSrcAlpha; + if (json.blendDstAlpha !== undefined) + material.blendDstAlpha = json.blendDstAlpha; + if (json.blendEquationAlpha !== undefined) + material.blendEquationAlpha = json.blendEquationAlpha; + if (json.blendColor !== undefined && material.blendColor !== undefined) + material.blendColor.setHex(json.blendColor); + if (json.blendAlpha !== undefined) + material.blendAlpha = json.blendAlpha; + if (json.stencilWriteMask !== undefined) + material.stencilWriteMask = json.stencilWriteMask; + if (json.stencilFunc !== undefined) + material.stencilFunc = json.stencilFunc; + if (json.stencilRef !== undefined) + material.stencilRef = json.stencilRef; + if (json.stencilFuncMask !== undefined) + material.stencilFuncMask = json.stencilFuncMask; + if (json.stencilFail !== undefined) + material.stencilFail = json.stencilFail; + if (json.stencilZFail !== undefined) + material.stencilZFail = json.stencilZFail; + if (json.stencilZPass !== undefined) + material.stencilZPass = json.stencilZPass; + if (json.stencilWrite !== undefined) + material.stencilWrite = json.stencilWrite; + if (json.wireframe !== undefined) + material.wireframe = json.wireframe; + if (json.wireframeLinewidth !== undefined) + material.wireframeLinewidth = json.wireframeLinewidth; + if (json.wireframeLinecap !== undefined) + material.wireframeLinecap = json.wireframeLinecap; + if (json.wireframeLinejoin !== undefined) + material.wireframeLinejoin = json.wireframeLinejoin; + if (json.rotation !== undefined) + material.rotation = json.rotation; + if (json.linewidth !== undefined) + material.linewidth = json.linewidth; + if (json.dashSize !== undefined) + material.dashSize = json.dashSize; + if (json.gapSize !== undefined) + material.gapSize = json.gapSize; + if (json.scale !== undefined) + material.scale = json.scale; + if (json.polygonOffset !== undefined) + material.polygonOffset = json.polygonOffset; + if (json.polygonOffsetFactor !== undefined) + material.polygonOffsetFactor = json.polygonOffsetFactor; + if (json.polygonOffsetUnits !== undefined) + material.polygonOffsetUnits = json.polygonOffsetUnits; + if (json.dithering !== undefined) + material.dithering = json.dithering; + if (json.alphaToCoverage !== undefined) + material.alphaToCoverage = json.alphaToCoverage; + if (json.premultipliedAlpha !== undefined) + material.premultipliedAlpha = json.premultipliedAlpha; + if (json.forceSinglePass !== undefined) + material.forceSinglePass = json.forceSinglePass; + if (json.visible !== undefined) + material.visible = json.visible; + if (json.toneMapped !== undefined) + material.toneMapped = json.toneMapped; + if (json.userData !== undefined) + material.userData = json.userData; + if (json.vertexColors !== undefined) { + if (typeof json.vertexColors === "number") { + material.vertexColors = json.vertexColors > 0 ? true : false; + } else { + material.vertexColors = json.vertexColors; + } + } + if (json.uniforms !== undefined) { + for (const name2 in json.uniforms) { + const uniform = json.uniforms[name2]; + material.uniforms[name2] = {}; + switch (uniform.type) { + case "t": + material.uniforms[name2].value = getTexture(uniform.value); + break; + case "c": + material.uniforms[name2].value = new Color().setHex(uniform.value); + break; + case "v2": + material.uniforms[name2].value = new Vector2().fromArray(uniform.value); + break; + case "v3": + material.uniforms[name2].value = new Vector3().fromArray(uniform.value); + break; + case "v4": + material.uniforms[name2].value = new Vector4().fromArray(uniform.value); + break; + case "m3": + material.uniforms[name2].value = new Matrix3().fromArray(uniform.value); + break; + case "m4": + material.uniforms[name2].value = new Matrix4().fromArray(uniform.value); + break; + default: + material.uniforms[name2].value = uniform.value; + } + } + } + if (json.defines !== undefined) + material.defines = json.defines; + if (json.vertexShader !== undefined) + material.vertexShader = json.vertexShader; + if (json.fragmentShader !== undefined) + material.fragmentShader = json.fragmentShader; + if (json.glslVersion !== undefined) + material.glslVersion = json.glslVersion; + if (json.extensions !== undefined) { + for (const key2 in json.extensions) { + material.extensions[key2] = json.extensions[key2]; + } + } + if (json.lights !== undefined) + material.lights = json.lights; + if (json.clipping !== undefined) + material.clipping = json.clipping; + if (json.size !== undefined) + material.size = json.size; + if (json.sizeAttenuation !== undefined) + material.sizeAttenuation = json.sizeAttenuation; + if (json.map !== undefined) + material.map = getTexture(json.map); + if (json.matcap !== undefined) + material.matcap = getTexture(json.matcap); + if (json.alphaMap !== undefined) + material.alphaMap = getTexture(json.alphaMap); + if (json.bumpMap !== undefined) + material.bumpMap = getTexture(json.bumpMap); + if (json.bumpScale !== undefined) + material.bumpScale = json.bumpScale; + if (json.normalMap !== undefined) + material.normalMap = getTexture(json.normalMap); + if (json.normalMapType !== undefined) + material.normalMapType = json.normalMapType; + if (json.normalScale !== undefined) { + let normalScale = json.normalScale; + if (Array.isArray(normalScale) === false) { + normalScale = [normalScale, normalScale]; + } + material.normalScale = new Vector2().fromArray(normalScale); + } + if (json.displacementMap !== undefined) + material.displacementMap = getTexture(json.displacementMap); + if (json.displacementScale !== undefined) + material.displacementScale = json.displacementScale; + if (json.displacementBias !== undefined) + material.displacementBias = json.displacementBias; + if (json.roughnessMap !== undefined) + material.roughnessMap = getTexture(json.roughnessMap); + if (json.metalnessMap !== undefined) + material.metalnessMap = getTexture(json.metalnessMap); + if (json.emissiveMap !== undefined) + material.emissiveMap = getTexture(json.emissiveMap); + if (json.emissiveIntensity !== undefined) + material.emissiveIntensity = json.emissiveIntensity; + if (json.specularMap !== undefined) + material.specularMap = getTexture(json.specularMap); + if (json.specularIntensityMap !== undefined) + material.specularIntensityMap = getTexture(json.specularIntensityMap); + if (json.specularColorMap !== undefined) + material.specularColorMap = getTexture(json.specularColorMap); + if (json.envMap !== undefined) + material.envMap = getTexture(json.envMap); + if (json.envMapRotation !== undefined) + material.envMapRotation.fromArray(json.envMapRotation); + if (json.envMapIntensity !== undefined) + material.envMapIntensity = json.envMapIntensity; + if (json.reflectivity !== undefined) + material.reflectivity = json.reflectivity; + if (json.refractionRatio !== undefined) + material.refractionRatio = json.refractionRatio; + if (json.lightMap !== undefined) + material.lightMap = getTexture(json.lightMap); + if (json.lightMapIntensity !== undefined) + material.lightMapIntensity = json.lightMapIntensity; + if (json.aoMap !== undefined) + material.aoMap = getTexture(json.aoMap); + if (json.aoMapIntensity !== undefined) + material.aoMapIntensity = json.aoMapIntensity; + if (json.gradientMap !== undefined) + material.gradientMap = getTexture(json.gradientMap); + if (json.clearcoatMap !== undefined) + material.clearcoatMap = getTexture(json.clearcoatMap); + if (json.clearcoatRoughnessMap !== undefined) + material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap); + if (json.clearcoatNormalMap !== undefined) + material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap); + if (json.clearcoatNormalScale !== undefined) + material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale); + if (json.iridescenceMap !== undefined) + material.iridescenceMap = getTexture(json.iridescenceMap); + if (json.iridescenceThicknessMap !== undefined) + material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap); + if (json.transmissionMap !== undefined) + material.transmissionMap = getTexture(json.transmissionMap); + if (json.thicknessMap !== undefined) + material.thicknessMap = getTexture(json.thicknessMap); + if (json.anisotropyMap !== undefined) + material.anisotropyMap = getTexture(json.anisotropyMap); + if (json.sheenColorMap !== undefined) + material.sheenColorMap = getTexture(json.sheenColorMap); + if (json.sheenRoughnessMap !== undefined) + material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap); + return material; + } + setTextures(value2) { + this.textures = value2; + return this; + } + createMaterialFromType(type) { + return MaterialLoader.createMaterialFromType(type); + } + static createMaterialFromType(type) { + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material + }; + return new materialLib[type]; + } +} + +class LoaderUtils { + static decodeText(array) { + console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."); + if (typeof TextDecoder !== "undefined") { + return new TextDecoder().decode(array); + } + let s = ""; + for (let i = 0, il = array.length;i < il; i++) { + s += String.fromCharCode(array[i]); + } + try { + return decodeURIComponent(escape(s)); + } catch (e) { + return s; + } + } + static extractUrlBase(url) { + const index2 = url.lastIndexOf("/"); + if (index2 === -1) + return "./"; + return url.slice(0, index2 + 1); + } + static resolveURL(url, path) { + if (typeof url !== "string" || url === "") + return ""; + if (/^https?:\/\//i.test(path) && /^\//.test(url)) { + path = path.replace(/(^https?:\/\/[^\/]+).*/i, "$1"); + } + if (/^(https?:)?\/\//i.test(url)) + return url; + if (/^data:.*,.*$/i.test(url)) + return url; + if (/^blob:.*$/i.test(url)) + return url; + return path + url; + } +} + +class InstancedBufferGeometry extends BufferGeometry { + constructor() { + super(); + this.isInstancedBufferGeometry = true; + this.type = "InstancedBufferGeometry"; + this.instanceCount = Infinity; + } + copy(source) { + super.copy(source); + this.instanceCount = source.instanceCount; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.instanceCount = this.instanceCount; + data2.isInstancedBufferGeometry = true; + return data2; + } +} + +class BufferGeometryLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const interleavedBufferMap = {}; + const arrayBufferMap = {}; + function getInterleavedBuffer(json2, uuid) { + if (interleavedBufferMap[uuid] !== undefined) + return interleavedBufferMap[uuid]; + const interleavedBuffers = json2.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[uuid]; + const buffer = getArrayBuffer(json2, interleavedBuffer.buffer); + const array = getTypedArray(interleavedBuffer.type, buffer); + const ib = new InterleavedBuffer(array, interleavedBuffer.stride); + ib.uuid = interleavedBuffer.uuid; + interleavedBufferMap[uuid] = ib; + return ib; + } + function getArrayBuffer(json2, uuid) { + if (arrayBufferMap[uuid] !== undefined) + return arrayBufferMap[uuid]; + const arrayBuffers = json2.arrayBuffers; + const arrayBuffer = arrayBuffers[uuid]; + const ab = new Uint32Array(arrayBuffer).buffer; + arrayBufferMap[uuid] = ab; + return ab; + } + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry : new BufferGeometry; + const index2 = json.data.index; + if (index2 !== undefined) { + const typedArray = getTypedArray(index2.type, index2.array); + geometry.setIndex(new BufferAttribute(typedArray, 1)); + } + const attributes = json.data.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray(attribute.type, attribute.array); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; + bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== undefined) + bufferAttribute.name = attribute.name; + if (attribute.usage !== undefined) + bufferAttribute.setUsage(attribute.usage); + geometry.setAttribute(key2, bufferAttribute); + } + const morphAttributes = json.data.morphAttributes; + if (morphAttributes) { + for (const key2 in morphAttributes) { + const attributeArray = morphAttributes[key2]; + const array = []; + for (let i = 0, il = attributeArray.length;i < il; i++) { + const attribute = attributeArray[i]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray(attribute.type, attribute.array); + bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== undefined) + bufferAttribute.name = attribute.name; + array.push(bufferAttribute); + } + geometry.morphAttributes[key2] = array; + } + } + const morphTargetsRelative = json.data.morphTargetsRelative; + if (morphTargetsRelative) { + geometry.morphTargetsRelative = true; + } + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + if (groups !== undefined) { + for (let i = 0, n = groups.length;i !== n; ++i) { + const group = groups[i]; + geometry.addGroup(group.start, group.count, group.materialIndex); + } + } + const boundingSphere = json.data.boundingSphere; + if (boundingSphere !== undefined) { + const center = new Vector3; + if (boundingSphere.center !== undefined) { + center.fromArray(boundingSphere.center); + } + geometry.boundingSphere = new Sphere(center, boundingSphere.radius); + } + if (json.name) + geometry.name = json.name; + if (json.userData) + geometry.userData = json.userData; + return geometry; + } +} + +class ObjectLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text2) { + let json = null; + try { + json = JSON.parse(text2); + } catch (error) { + if (onError !== undefined) + onError(error); + console.error("THREE:ObjectLoader: Can't parse " + url + ".", error.message); + return; + } + const metadata = json.metadata; + if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === "geometry") { + if (onError !== undefined) + onError(new Error("THREE.ObjectLoader: Can't load " + url)); + console.error("THREE.ObjectLoader: Can't load " + url); + return; + } + scope.parse(json, onLoad); + }, onProgress, onError); + } + async loadAsync(url, onProgress) { + const scope = this; + const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + const text2 = await loader.loadAsync(url, onProgress); + const json = JSON.parse(text2); + const metadata = json.metadata; + if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === "geometry") { + throw new Error("THREE.ObjectLoader: Can't load " + url); + } + return await scope.parseAsync(json); + } + parse(json, onLoad) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = this.parseImages(json.images, function() { + if (onLoad !== undefined) + onLoad(object); + }); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + if (onLoad !== undefined) { + let hasImages = false; + for (const uuid in images) { + if (images[uuid].data instanceof HTMLImageElement) { + hasImages = true; + break; + } + } + if (hasImages === false) + onLoad(object); + } + return object; + } + async parseAsync(json) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = await this.parseImagesAsync(json.images); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + return object; + } + parseShapes(json) { + const shapes = {}; + if (json !== undefined) { + for (let i = 0, l = json.length;i < l; i++) { + const shape = new Shape().fromJSON(json[i]); + shapes[shape.uuid] = shape; + } + } + return shapes; + } + parseSkeletons(json, object) { + const skeletons = {}; + const bones = {}; + object.traverse(function(child) { + if (child.isBone) + bones[child.uuid] = child; + }); + if (json !== undefined) { + for (let i = 0, l = json.length;i < l; i++) { + const skeleton = new Skeleton().fromJSON(json[i], bones); + skeletons[skeleton.uuid] = skeleton; + } + } + return skeletons; + } + parseGeometries(json, shapes) { + const geometries = {}; + if (json !== undefined) { + const bufferGeometryLoader = new BufferGeometryLoader; + for (let i = 0, l = json.length;i < l; i++) { + let geometry; + const data2 = json[i]; + switch (data2.type) { + case "BufferGeometry": + case "InstancedBufferGeometry": + geometry = bufferGeometryLoader.parse(data2); + break; + default: + if (data2.type in Geometries) { + geometry = Geometries[data2.type].fromJSON(data2, shapes); + } else { + console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data2.type}"`); + } + } + geometry.uuid = data2.uuid; + if (data2.name !== undefined) + geometry.name = data2.name; + if (data2.userData !== undefined) + geometry.userData = data2.userData; + geometries[data2.uuid] = geometry; + } + } + return geometries; + } + parseMaterials(json, textures) { + const cache = {}; + const materials = {}; + if (json !== undefined) { + const loader = new MaterialLoader; + loader.setTextures(textures); + for (let i = 0, l = json.length;i < l; i++) { + const data2 = json[i]; + if (cache[data2.uuid] === undefined) { + cache[data2.uuid] = loader.parse(data2); + } + materials[data2.uuid] = cache[data2.uuid]; + } + } + return materials; + } + parseAnimations(json) { + const animations = {}; + if (json !== undefined) { + for (let i = 0;i < json.length; i++) { + const data2 = json[i]; + const clip = AnimationClip.parse(data2); + animations[clip.uuid] = clip; + } + } + return animations; + } + parseImages(json, onLoad) { + const scope = this; + const images = {}; + let loader; + function loadImage(url) { + scope.manager.itemStart(url); + return loader.load(url, function() { + scope.manager.itemEnd(url); + }, undefined, function() { + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + } + function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return loadImage(path); + } else { + if (image.data) { + return { + data: getTypedArray(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== undefined && json.length > 0) { + const manager = new LoadingManager(onLoad); + loader = new ImageLoader(manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length;i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j = 0, jl = url.length;j < jl; j++) { + const currentUrl = url[j]; + const deserializedImage = deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source(imageArray); + } else { + const deserializedImage = deserializeImage(image.url); + images[image.uuid] = new Source(deserializedImage); + } + } + } + return images; + } + async parseImagesAsync(json) { + const scope = this; + const images = {}; + let loader; + async function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return await loader.loadAsync(path); + } else { + if (image.data) { + return { + data: getTypedArray(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== undefined && json.length > 0) { + loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length;i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j = 0, jl = url.length;j < jl; j++) { + const currentUrl = url[j]; + const deserializedImage = await deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source(imageArray); + } else { + const deserializedImage = await deserializeImage(image.url); + images[image.uuid] = new Source(deserializedImage); + } + } + } + return images; + } + parseTextures(json, images) { + function parseConstant(value2, type) { + if (typeof value2 === "number") + return value2; + console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.", value2); + return type[value2]; + } + const textures = {}; + if (json !== undefined) { + for (let i = 0, l = json.length;i < l; i++) { + const data2 = json[i]; + if (data2.image === undefined) { + console.warn('THREE.ObjectLoader: No "image" specified for', data2.uuid); + } + if (images[data2.image] === undefined) { + console.warn("THREE.ObjectLoader: Undefined image", data2.image); + } + const source = images[data2.image]; + const image = source.data; + let texture; + if (Array.isArray(image)) { + texture = new CubeTexture; + if (image.length === 6) + texture.needsUpdate = true; + } else { + if (image && image.data) { + texture = new DataTexture; + } else { + texture = new Texture; + } + if (image) + texture.needsUpdate = true; + } + texture.source = source; + texture.uuid = data2.uuid; + if (data2.name !== undefined) + texture.name = data2.name; + if (data2.mapping !== undefined) + texture.mapping = parseConstant(data2.mapping, TEXTURE_MAPPING); + if (data2.channel !== undefined) + texture.channel = data2.channel; + if (data2.offset !== undefined) + texture.offset.fromArray(data2.offset); + if (data2.repeat !== undefined) + texture.repeat.fromArray(data2.repeat); + if (data2.center !== undefined) + texture.center.fromArray(data2.center); + if (data2.rotation !== undefined) + texture.rotation = data2.rotation; + if (data2.wrap !== undefined) { + texture.wrapS = parseConstant(data2.wrap[0], TEXTURE_WRAPPING); + texture.wrapT = parseConstant(data2.wrap[1], TEXTURE_WRAPPING); + } + if (data2.format !== undefined) + texture.format = data2.format; + if (data2.internalFormat !== undefined) + texture.internalFormat = data2.internalFormat; + if (data2.type !== undefined) + texture.type = data2.type; + if (data2.colorSpace !== undefined) + texture.colorSpace = data2.colorSpace; + if (data2.minFilter !== undefined) + texture.minFilter = parseConstant(data2.minFilter, TEXTURE_FILTER); + if (data2.magFilter !== undefined) + texture.magFilter = parseConstant(data2.magFilter, TEXTURE_FILTER); + if (data2.anisotropy !== undefined) + texture.anisotropy = data2.anisotropy; + if (data2.flipY !== undefined) + texture.flipY = data2.flipY; + if (data2.generateMipmaps !== undefined) + texture.generateMipmaps = data2.generateMipmaps; + if (data2.premultiplyAlpha !== undefined) + texture.premultiplyAlpha = data2.premultiplyAlpha; + if (data2.unpackAlignment !== undefined) + texture.unpackAlignment = data2.unpackAlignment; + if (data2.compareFunction !== undefined) + texture.compareFunction = data2.compareFunction; + if (data2.userData !== undefined) + texture.userData = data2.userData; + textures[data2.uuid] = texture; + } + } + return textures; + } + parseObject(data2, geometries, materials, textures, animations) { + let object; + function getGeometry(name2) { + if (geometries[name2] === undefined) { + console.warn("THREE.ObjectLoader: Undefined geometry", name2); + } + return geometries[name2]; + } + function getMaterial(name2) { + if (name2 === undefined) + return; + if (Array.isArray(name2)) { + const array = []; + for (let i = 0, l = name2.length;i < l; i++) { + const uuid = name2[i]; + if (materials[uuid] === undefined) { + console.warn("THREE.ObjectLoader: Undefined material", uuid); + } + array.push(materials[uuid]); + } + return array; + } + if (materials[name2] === undefined) { + console.warn("THREE.ObjectLoader: Undefined material", name2); + } + return materials[name2]; + } + function getTexture(uuid) { + if (textures[uuid] === undefined) { + console.warn("THREE.ObjectLoader: Undefined texture", uuid); + } + return textures[uuid]; + } + let geometry, material; + switch (data2.type) { + case "Scene": + object = new Scene; + if (data2.background !== undefined) { + if (Number.isInteger(data2.background)) { + object.background = new Color(data2.background); + } else { + object.background = getTexture(data2.background); + } + } + if (data2.environment !== undefined) { + object.environment = getTexture(data2.environment); + } + if (data2.fog !== undefined) { + if (data2.fog.type === "Fog") { + object.fog = new Fog(data2.fog.color, data2.fog.near, data2.fog.far); + } else if (data2.fog.type === "FogExp2") { + object.fog = new FogExp2(data2.fog.color, data2.fog.density); + } + if (data2.fog.name !== "") { + object.fog.name = data2.fog.name; + } + } + if (data2.backgroundBlurriness !== undefined) + object.backgroundBlurriness = data2.backgroundBlurriness; + if (data2.backgroundIntensity !== undefined) + object.backgroundIntensity = data2.backgroundIntensity; + if (data2.backgroundRotation !== undefined) + object.backgroundRotation.fromArray(data2.backgroundRotation); + if (data2.environmentIntensity !== undefined) + object.environmentIntensity = data2.environmentIntensity; + if (data2.environmentRotation !== undefined) + object.environmentRotation.fromArray(data2.environmentRotation); + break; + case "PerspectiveCamera": + object = new PerspectiveCamera(data2.fov, data2.aspect, data2.near, data2.far); + if (data2.focus !== undefined) + object.focus = data2.focus; + if (data2.zoom !== undefined) + object.zoom = data2.zoom; + if (data2.filmGauge !== undefined) + object.filmGauge = data2.filmGauge; + if (data2.filmOffset !== undefined) + object.filmOffset = data2.filmOffset; + if (data2.view !== undefined) + object.view = Object.assign({}, data2.view); + break; + case "OrthographicCamera": + object = new OrthographicCamera(data2.left, data2.right, data2.top, data2.bottom, data2.near, data2.far); + if (data2.zoom !== undefined) + object.zoom = data2.zoom; + if (data2.view !== undefined) + object.view = Object.assign({}, data2.view); + break; + case "AmbientLight": + object = new AmbientLight(data2.color, data2.intensity); + break; + case "DirectionalLight": + object = new DirectionalLight(data2.color, data2.intensity); + object.target = data2.target || ""; + break; + case "PointLight": + object = new PointLight(data2.color, data2.intensity, data2.distance, data2.decay); + break; + case "RectAreaLight": + object = new RectAreaLight(data2.color, data2.intensity, data2.width, data2.height); + break; + case "SpotLight": + object = new SpotLight(data2.color, data2.intensity, data2.distance, data2.angle, data2.penumbra, data2.decay); + object.target = data2.target || ""; + break; + case "HemisphereLight": + object = new HemisphereLight(data2.color, data2.groundColor, data2.intensity); + break; + case "LightProbe": + object = new LightProbe().fromJSON(data2); + break; + case "SkinnedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new SkinnedMesh(geometry, material); + if (data2.bindMode !== undefined) + object.bindMode = data2.bindMode; + if (data2.bindMatrix !== undefined) + object.bindMatrix.fromArray(data2.bindMatrix); + if (data2.skeleton !== undefined) + object.skeleton = data2.skeleton; + break; + case "Mesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new Mesh(geometry, material); + break; + case "InstancedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + const count = data2.count; + const instanceMatrix = data2.instanceMatrix; + const instanceColor = data2.instanceColor; + object = new InstancedMesh(geometry, material, count); + object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16); + if (instanceColor !== undefined) + object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize); + break; + case "BatchedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new BatchedMesh(data2.maxInstanceCount, data2.maxVertexCount, data2.maxIndexCount, material); + object.geometry = geometry; + object.perObjectFrustumCulled = data2.perObjectFrustumCulled; + object.sortObjects = data2.sortObjects; + object._drawRanges = data2.drawRanges; + object._reservedRanges = data2.reservedRanges; + object._visibility = data2.visibility; + object._active = data2.active; + object._bounds = data2.bounds.map((bound) => { + const box = new Box3; + box.min.fromArray(bound.boxMin); + box.max.fromArray(bound.boxMax); + const sphere = new Sphere; + sphere.radius = bound.sphereRadius; + sphere.center.fromArray(bound.sphereCenter); + return { + boxInitialized: bound.boxInitialized, + box, + sphereInitialized: bound.sphereInitialized, + sphere + }; + }); + object._maxInstanceCount = data2.maxInstanceCount; + object._maxVertexCount = data2.maxVertexCount; + object._maxIndexCount = data2.maxIndexCount; + object._geometryInitialized = data2.geometryInitialized; + object._geometryCount = data2.geometryCount; + object._matricesTexture = getTexture(data2.matricesTexture.uuid); + if (data2.colorsTexture !== undefined) + object._colorsTexture = getTexture(data2.colorsTexture.uuid); + break; + case "LOD": + object = new LOD; + break; + case "Line": + object = new Line(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "LineLoop": + object = new LineLoop(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "LineSegments": + object = new LineSegments(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "PointCloud": + case "Points": + object = new Points(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "Sprite": + object = new Sprite(getMaterial(data2.material)); + break; + case "Group": + object = new Group; + break; + case "Bone": + object = new Bone; + break; + default: + object = new Object3D; + } + object.uuid = data2.uuid; + if (data2.name !== undefined) + object.name = data2.name; + if (data2.matrix !== undefined) { + object.matrix.fromArray(data2.matrix); + if (data2.matrixAutoUpdate !== undefined) + object.matrixAutoUpdate = data2.matrixAutoUpdate; + if (object.matrixAutoUpdate) + object.matrix.decompose(object.position, object.quaternion, object.scale); + } else { + if (data2.position !== undefined) + object.position.fromArray(data2.position); + if (data2.rotation !== undefined) + object.rotation.fromArray(data2.rotation); + if (data2.quaternion !== undefined) + object.quaternion.fromArray(data2.quaternion); + if (data2.scale !== undefined) + object.scale.fromArray(data2.scale); + } + if (data2.up !== undefined) + object.up.fromArray(data2.up); + if (data2.castShadow !== undefined) + object.castShadow = data2.castShadow; + if (data2.receiveShadow !== undefined) + object.receiveShadow = data2.receiveShadow; + if (data2.shadow) { + if (data2.shadow.intensity !== undefined) + object.shadow.intensity = data2.shadow.intensity; + if (data2.shadow.bias !== undefined) + object.shadow.bias = data2.shadow.bias; + if (data2.shadow.normalBias !== undefined) + object.shadow.normalBias = data2.shadow.normalBias; + if (data2.shadow.radius !== undefined) + object.shadow.radius = data2.shadow.radius; + if (data2.shadow.mapSize !== undefined) + object.shadow.mapSize.fromArray(data2.shadow.mapSize); + if (data2.shadow.camera !== undefined) + object.shadow.camera = this.parseObject(data2.shadow.camera); + } + if (data2.visible !== undefined) + object.visible = data2.visible; + if (data2.frustumCulled !== undefined) + object.frustumCulled = data2.frustumCulled; + if (data2.renderOrder !== undefined) + object.renderOrder = data2.renderOrder; + if (data2.userData !== undefined) + object.userData = data2.userData; + if (data2.layers !== undefined) + object.layers.mask = data2.layers; + if (data2.children !== undefined) { + const children = data2.children; + for (let i = 0;i < children.length; i++) { + object.add(this.parseObject(children[i], geometries, materials, textures, animations)); + } + } + if (data2.animations !== undefined) { + const objectAnimations = data2.animations; + for (let i = 0;i < objectAnimations.length; i++) { + const uuid = objectAnimations[i]; + object.animations.push(animations[uuid]); + } + } + if (data2.type === "LOD") { + if (data2.autoUpdate !== undefined) + object.autoUpdate = data2.autoUpdate; + const levels = data2.levels; + for (let l = 0;l < levels.length; l++) { + const level = levels[l]; + const child = object.getObjectByProperty("uuid", level.object); + if (child !== undefined) { + object.addLevel(child, level.distance, level.hysteresis); + } + } + } + return object; + } + bindSkeletons(object, skeletons) { + if (Object.keys(skeletons).length === 0) + return; + object.traverse(function(child) { + if (child.isSkinnedMesh === true && child.skeleton !== undefined) { + const skeleton = skeletons[child.skeleton]; + if (skeleton === undefined) { + console.warn("THREE.ObjectLoader: No skeleton found with UUID:", child.skeleton); + } else { + child.bind(skeleton, child.bindMatrix); + } + } + }); + } + bindLightTargets(object) { + object.traverse(function(child) { + if (child.isDirectionalLight || child.isSpotLight) { + const uuid = child.target; + const target = object.getObjectByProperty("uuid", uuid); + if (target !== undefined) { + child.target = target; + } else { + child.target = new Object3D; + } + } + }); + } +} +var TEXTURE_MAPPING = { + UVMapping, + CubeReflectionMapping, + CubeRefractionMapping, + EquirectangularReflectionMapping, + EquirectangularRefractionMapping, + CubeUVReflectionMapping +}; +var TEXTURE_WRAPPING = { + RepeatWrapping, + ClampToEdgeWrapping, + MirroredRepeatWrapping +}; +var TEXTURE_FILTER = { + NearestFilter, + NearestMipmapNearestFilter, + NearestMipmapLinearFilter, + LinearFilter, + LinearMipmapNearestFilter, + LinearMipmapLinearFilter +}; + +class ImageBitmapLoader extends Loader { + constructor(manager) { + super(manager); + this.isImageBitmapLoader = true; + if (typeof createImageBitmap === "undefined") { + console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."); + } + if (typeof fetch === "undefined") { + console.warn("THREE.ImageBitmapLoader: fetch() not supported."); + } + this.options = { premultiplyAlpha: "none" }; + } + setOptions(options) { + this.options = options; + return this; + } + load(url, onLoad, onProgress, onError) { + if (url === undefined) + url = ""; + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache.get(url); + if (cached !== undefined) { + scope.manager.itemStart(url); + if (cached.then) { + cached.then((imageBitmap) => { + if (onLoad) + onLoad(imageBitmap); + scope.manager.itemEnd(url); + }).catch((e) => { + if (onError) + onError(e); + }); + return; + } + setTimeout(function() { + if (onLoad) + onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const fetchOptions = {}; + fetchOptions.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include"; + fetchOptions.headers = this.requestHeader; + const promise = fetch(url, fetchOptions).then(function(res) { + return res.blob(); + }).then(function(blob) { + return createImageBitmap(blob, Object.assign(scope.options, { colorSpaceConversion: "none" })); + }).then(function(imageBitmap) { + Cache.add(url, imageBitmap); + if (onLoad) + onLoad(imageBitmap); + scope.manager.itemEnd(url); + return imageBitmap; + }).catch(function(e) { + if (onError) + onError(e); + Cache.remove(url); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + Cache.add(url, promise); + scope.manager.itemStart(url); + } +} +var _context; + +class AudioContext { + static getContext() { + if (_context === undefined) { + _context = new (window.AudioContext || window.webkitAudioContext); + } + return _context; + } + static setContext(value2) { + _context = value2; + } +} + +class AudioLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(buffer) { + try { + const bufferCopy = buffer.slice(0); + const context = AudioContext.getContext(); + context.decodeAudioData(bufferCopy, function(audioBuffer) { + onLoad(audioBuffer); + }).catch(handleError); + } catch (e) { + handleError(e); + } + }, onProgress, onError); + function handleError(e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + } +} +var _eyeRight = /* @__PURE__ */ new Matrix4; +var _eyeLeft = /* @__PURE__ */ new Matrix4; +var _projectionMatrix = /* @__PURE__ */ new Matrix4; + +class StereoCamera { + constructor() { + this.type = "StereoCamera"; + this.aspect = 1; + this.eyeSep = 0.064; + this.cameraL = new PerspectiveCamera; + this.cameraL.layers.enable(1); + this.cameraL.matrixAutoUpdate = false; + this.cameraR = new PerspectiveCamera; + this.cameraR.layers.enable(2); + this.cameraR.matrixAutoUpdate = false; + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; + } + update(camera) { + const cache = this._cache; + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + if (needsUpdate) { + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; + _projectionMatrix.copy(camera.projectionMatrix); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom; + let xmin, xmax; + _eyeLeft.elements[12] = -eyeSepHalf; + _eyeRight.elements[12] = eyeSepHalf; + xmin = -ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; + _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraL.projectionMatrix.copy(_projectionMatrix); + xmin = -ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraR.projectionMatrix.copy(_projectionMatrix); + } + this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft); + this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight); + } +} + +class ArrayCamera extends PerspectiveCamera { + constructor(array = []) { + super(); + this.isArrayCamera = true; + this.cameras = array; + this.index = 0; + } +} + +class Clock { + constructor(autoStart = true) { + this.autoStart = autoStart; + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; + this.running = false; + } + start() { + this.startTime = now(); + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + } + stop() { + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + } + getElapsedTime() { + this.getDelta(); + return this.elapsedTime; + } + getDelta() { + let diff = 0; + if (this.autoStart && !this.running) { + this.start(); + return 0; + } + if (this.running) { + const newTime = now(); + diff = (newTime - this.oldTime) / 1000; + this.oldTime = newTime; + this.elapsedTime += diff; + } + return diff; + } +} +function now() { + return performance.now(); +} +var _position$1 = /* @__PURE__ */ new Vector3; +var _quaternion$1 = /* @__PURE__ */ new Quaternion; +var _scale$1 = /* @__PURE__ */ new Vector3; +var _orientation$1 = /* @__PURE__ */ new Vector3; + +class AudioListener extends Object3D { + constructor() { + super(); + this.type = "AudioListener"; + this.context = AudioContext.getContext(); + this.gain = this.context.createGain(); + this.gain.connect(this.context.destination); + this.filter = null; + this.timeDelta = 0; + this._clock = new Clock; + } + getInput() { + return this.gain; + } + removeFilter() { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + this.gain.connect(this.context.destination); + this.filter = null; + } + return this; + } + getFilter() { + return this.filter; + } + setFilter(value2) { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + } else { + this.gain.disconnect(this.context.destination); + } + this.filter = value2; + this.gain.connect(this.filter); + this.filter.connect(this.context.destination); + return this; + } + getMasterVolume() { + return this.gain.gain.value; + } + setMasterVolume(value2) { + this.gain.gain.setTargetAtTime(value2, this.context.currentTime, 0.01); + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + const listener = this.context.listener; + const up = this.up; + this.timeDelta = this._clock.getDelta(); + this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1); + _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1); + if (listener.positionX) { + const endTime = this.context.currentTime + this.timeDelta; + listener.positionX.linearRampToValueAtTime(_position$1.x, endTime); + listener.positionY.linearRampToValueAtTime(_position$1.y, endTime); + listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime); + listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime); + listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime); + listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime); + listener.upX.linearRampToValueAtTime(up.x, endTime); + listener.upY.linearRampToValueAtTime(up.y, endTime); + listener.upZ.linearRampToValueAtTime(up.z, endTime); + } else { + listener.setPosition(_position$1.x, _position$1.y, _position$1.z); + listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z); + } + } +} + +class Audio extends Object3D { + constructor(listener) { + super(); + this.type = "Audio"; + this.listener = listener; + this.context = listener.context; + this.gain = this.context.createGain(); + this.gain.connect(listener.getInput()); + this.autoplay = false; + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = undefined; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = "empty"; + this._startedAt = 0; + this._progress = 0; + this._connected = false; + this.filters = []; + } + getOutput() { + return this.gain; + } + setNodeSource(audioNode) { + this.hasPlaybackControl = false; + this.sourceType = "audioNode"; + this.source = audioNode; + this.connect(); + return this; + } + setMediaElementSource(mediaElement) { + this.hasPlaybackControl = false; + this.sourceType = "mediaNode"; + this.source = this.context.createMediaElementSource(mediaElement); + this.connect(); + return this; + } + setMediaStreamSource(mediaStream) { + this.hasPlaybackControl = false; + this.sourceType = "mediaStreamNode"; + this.source = this.context.createMediaStreamSource(mediaStream); + this.connect(); + return this; + } + setBuffer(audioBuffer) { + this.buffer = audioBuffer; + this.sourceType = "buffer"; + if (this.autoplay) + this.play(); + return this; + } + play(delay = 0) { + if (this.isPlaying === true) { + console.warn("THREE.Audio: Audio is already playing."); + return; + } + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._startedAt = this.context.currentTime + delay; + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind(this); + source.start(this._startedAt, this._progress + this.offset, this.duration); + this.isPlaying = true; + this.source = source; + this.setDetune(this.detune); + this.setPlaybackRate(this.playbackRate); + return this.connect(); + } + pause() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + if (this.isPlaying === true) { + this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate; + if (this.loop === true) { + this._progress = this._progress % (this.duration || this.buffer.duration); + } + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; + } + return this; + } + stop(delay = 0) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._progress = 0; + if (this.source !== null) { + this.source.stop(this.context.currentTime + delay); + this.source.onended = null; + } + this.isPlaying = false; + return this; + } + connect() { + if (this.filters.length > 0) { + this.source.connect(this.filters[0]); + for (let i = 1, l = this.filters.length;i < l; i++) { + this.filters[i - 1].connect(this.filters[i]); + } + this.filters[this.filters.length - 1].connect(this.getOutput()); + } else { + this.source.connect(this.getOutput()); + } + this._connected = true; + return this; + } + disconnect() { + if (this._connected === false) { + return; + } + if (this.filters.length > 0) { + this.source.disconnect(this.filters[0]); + for (let i = 1, l = this.filters.length;i < l; i++) { + this.filters[i - 1].disconnect(this.filters[i]); + } + this.filters[this.filters.length - 1].disconnect(this.getOutput()); + } else { + this.source.disconnect(this.getOutput()); + } + this._connected = false; + return this; + } + getFilters() { + return this.filters; + } + setFilters(value2) { + if (!value2) + value2 = []; + if (this._connected === true) { + this.disconnect(); + this.filters = value2.slice(); + this.connect(); + } else { + this.filters = value2.slice(); + } + return this; + } + setDetune(value2) { + this.detune = value2; + if (this.isPlaying === true && this.source.detune !== undefined) { + this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01); + } + return this; + } + getDetune() { + return this.detune; + } + getFilter() { + return this.getFilters()[0]; + } + setFilter(filter2) { + return this.setFilters(filter2 ? [filter2] : []); + } + setPlaybackRate(value2) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.playbackRate = value2; + if (this.isPlaying === true) { + this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01); + } + return this; + } + getPlaybackRate() { + return this.playbackRate; + } + onEnded() { + this.isPlaying = false; + this._progress = 0; + } + getLoop() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return false; + } + return this.loop; + } + setLoop(value2) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.loop = value2; + if (this.isPlaying === true) { + this.source.loop = this.loop; + } + return this; + } + setLoopStart(value2) { + this.loopStart = value2; + return this; + } + setLoopEnd(value2) { + this.loopEnd = value2; + return this; + } + getVolume() { + return this.gain.gain.value; + } + setVolume(value2) { + this.gain.gain.setTargetAtTime(value2, this.context.currentTime, 0.01); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.sourceType !== "buffer") { + console.warn("THREE.Audio: Audio source type cannot be copied."); + return this; + } + this.autoplay = source.autoplay; + this.buffer = source.buffer; + this.detune = source.detune; + this.loop = source.loop; + this.loopStart = source.loopStart; + this.loopEnd = source.loopEnd; + this.offset = source.offset; + this.duration = source.duration; + this.playbackRate = source.playbackRate; + this.hasPlaybackControl = source.hasPlaybackControl; + this.sourceType = source.sourceType; + this.filters = source.filters.slice(); + return this; + } + clone(recursive) { + return new this.constructor(this.listener).copy(this, recursive); + } +} +var _position = /* @__PURE__ */ new Vector3; +var _quaternion = /* @__PURE__ */ new Quaternion; +var _scale = /* @__PURE__ */ new Vector3; +var _orientation = /* @__PURE__ */ new Vector3; + +class PositionalAudio extends Audio { + constructor(listener) { + super(listener); + this.panner = this.context.createPanner(); + this.panner.panningModel = "HRTF"; + this.panner.connect(this.gain); + } + connect() { + super.connect(); + this.panner.connect(this.gain); + } + disconnect() { + super.disconnect(); + this.panner.disconnect(this.gain); + } + getOutput() { + return this.panner; + } + getRefDistance() { + return this.panner.refDistance; + } + setRefDistance(value2) { + this.panner.refDistance = value2; + return this; + } + getRolloffFactor() { + return this.panner.rolloffFactor; + } + setRolloffFactor(value2) { + this.panner.rolloffFactor = value2; + return this; + } + getDistanceModel() { + return this.panner.distanceModel; + } + setDistanceModel(value2) { + this.panner.distanceModel = value2; + return this; + } + getMaxDistance() { + return this.panner.maxDistance; + } + setMaxDistance(value2) { + this.panner.maxDistance = value2; + return this; + } + setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) { + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.hasPlaybackControl === true && this.isPlaying === false) + return; + this.matrixWorld.decompose(_position, _quaternion, _scale); + _orientation.set(0, 0, 1).applyQuaternion(_quaternion); + const panner = this.panner; + if (panner.positionX) { + const endTime = this.context.currentTime + this.listener.timeDelta; + panner.positionX.linearRampToValueAtTime(_position.x, endTime); + panner.positionY.linearRampToValueAtTime(_position.y, endTime); + panner.positionZ.linearRampToValueAtTime(_position.z, endTime); + panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime); + panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime); + panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime); + } else { + panner.setPosition(_position.x, _position.y, _position.z); + panner.setOrientation(_orientation.x, _orientation.y, _orientation.z); + } + } +} + +class AudioAnalyser { + constructor(audio, fftSize = 2048) { + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; + this.data = new Uint8Array(this.analyser.frequencyBinCount); + audio.getOutput().connect(this.analyser); + } + getFrequencyData() { + this.analyser.getByteFrequencyData(this.data); + return this.data; + } + getAverageFrequency() { + let value2 = 0; + const data2 = this.getFrequencyData(); + for (let i = 0;i < data2.length; i++) { + value2 += data2[i]; + } + return value2 / data2.length; + } +} + +class PropertyMixer { + constructor(binding, typeName, valueSize) { + this.binding = binding; + this.valueSize = valueSize; + let mixFunction, mixFunctionAdditive, setIdentity; + switch (typeName) { + case "quaternion": + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; + this.buffer = new Float64Array(valueSize * 6); + this._workIndex = 5; + break; + case "string": + case "bool": + mixFunction = this._select; + mixFunctionAdditive = this._select; + setIdentity = this._setAdditiveIdentityOther; + this.buffer = new Array(valueSize * 5); + break; + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; + this.buffer = new Float64Array(valueSize * 5); + } + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + this.useCount = 0; + this.referenceCount = 0; + } + accumulate(accuIndex, weight) { + const buffer = this.buffer, stride = this.valueSize, offset = accuIndex * stride + stride; + let currentWeight = this.cumulativeWeight; + if (currentWeight === 0) { + for (let i = 0;i !== stride; ++i) { + buffer[offset + i] = buffer[i]; + } + currentWeight = weight; + } else { + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion(buffer, offset, 0, mix, stride); + } + this.cumulativeWeight = currentWeight; + } + accumulateAdditive(weight) { + const buffer = this.buffer, stride = this.valueSize, offset = stride * this._addIndex; + if (this.cumulativeWeightAdditive === 0) { + this._setIdentity(); + } + this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride); + this.cumulativeWeightAdditive += weight; + } + apply(accuIndex) { + const stride = this.valueSize, buffer = this.buffer, offset = accuIndex * stride + stride, weight = this.cumulativeWeight, weightAdditive = this.cumulativeWeightAdditive, binding = this.binding; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + if (weight < 1) { + const originalValueOffset = stride * this._origIndex; + this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride); + } + if (weightAdditive > 0) { + this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride); + } + for (let i = stride, e = stride + stride;i !== e; ++i) { + if (buffer[i] !== buffer[i + stride]) { + binding.setValue(buffer, offset); + break; + } + } + } + saveOriginalState() { + const binding = this.binding; + const buffer = this.buffer, stride = this.valueSize, originalValueOffset = stride * this._origIndex; + binding.getValue(buffer, originalValueOffset); + for (let i = stride, e = originalValueOffset;i !== e; ++i) { + buffer[i] = buffer[originalValueOffset + i % stride]; + } + this._setIdentity(); + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + } + restoreOriginalState() { + const originalValueOffset = this.valueSize * 3; + this.binding.setValue(this.buffer, originalValueOffset); + } + _setAdditiveIdentityNumeric() { + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; + for (let i = startIndex;i < endIndex; i++) { + this.buffer[i] = 0; + } + } + _setAdditiveIdentityQuaternion() { + this._setAdditiveIdentityNumeric(); + this.buffer[this._addIndex * this.valueSize + 3] = 1; + } + _setAdditiveIdentityOther() { + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; + for (let i = 0;i < this.valueSize; i++) { + this.buffer[targetIndex + i] = this.buffer[startIndex + i]; + } + } + _select(buffer, dstOffset, srcOffset, t, stride) { + if (t >= 0.5) { + for (let i = 0;i !== stride; ++i) { + buffer[dstOffset + i] = buffer[srcOffset + i]; + } + } + } + _slerp(buffer, dstOffset, srcOffset, t) { + Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t); + } + _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) { + const workOffset = this._workIndex * stride; + Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); + Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t); + } + _lerp(buffer, dstOffset, srcOffset, t, stride) { + const s = 1 - t; + for (let i = 0;i !== stride; ++i) { + const j = dstOffset + i; + buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t; + } + } + _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) { + for (let i = 0;i !== stride; ++i) { + const j = dstOffset + i; + buffer[j] = buffer[j] + buffer[srcOffset + i] * t; + } + } +} +var _RESERVED_CHARS_RE = "\\[\\]\\.:\\/"; +var _reservedRe = new RegExp("[" + _RESERVED_CHARS_RE + "]", "g"); +var _wordChar = "[^" + _RESERVED_CHARS_RE + "]"; +var _wordCharOrDot = "[^" + _RESERVED_CHARS_RE.replace("\\.", "") + "]"; +var _directoryRe = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", _wordChar); +var _nodeRe = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", _wordCharOrDot); +var _objectRe = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", _wordChar); +var _propertyRe = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", _wordChar); +var _trackRe = new RegExp("" + "^" + _directoryRe + _nodeRe + _objectRe + _propertyRe + "$"); +var _supportedObjectNames = ["material", "materials", "bones", "map"]; + +class Composite { + constructor(targetGroup, path, optionalParsedPath) { + const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_(path, parsedPath); + } + getValue(array, offset) { + this.bind(); + const firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[firstValidIndex]; + if (binding !== undefined) + binding.getValue(array, offset); + } + setValue(array, offset) { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) { + bindings[i].setValue(array, offset); + } + } + bind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) { + bindings[i].bind(); + } + } + unbind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) { + bindings[i].unbind(); + } + } +} + +class PropertyBinding { + constructor(rootNode, path, parsedPath) { + this.path = path; + this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path); + this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName); + this.rootNode = rootNode; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + static create(root, path, parsedPath) { + if (!(root && root.isAnimationObjectGroup)) { + return new PropertyBinding(root, path, parsedPath); + } else { + return new PropertyBinding.Composite(root, path, parsedPath); + } + } + static sanitizeNodeName(name2) { + return name2.replace(/\s/g, "_").replace(_reservedRe, ""); + } + static parseTrackName(trackName) { + const matches = _trackRe.exec(trackName); + if (matches === null) { + throw new Error("PropertyBinding: Cannot parse trackName: " + trackName); + } + const results = { + nodeName: matches[2], + objectName: matches[3], + objectIndex: matches[4], + propertyName: matches[5], + propertyIndex: matches[6] + }; + const lastDot = results.nodeName && results.nodeName.lastIndexOf("."); + if (lastDot !== undefined && lastDot !== -1) { + const objectName = results.nodeName.substring(lastDot + 1); + if (_supportedObjectNames.indexOf(objectName) !== -1) { + results.nodeName = results.nodeName.substring(0, lastDot); + results.objectName = objectName; + } + } + if (results.propertyName === null || results.propertyName.length === 0) { + throw new Error("PropertyBinding: can not parse propertyName from trackName: " + trackName); + } + return results; + } + static findNode(root, nodeName) { + if (nodeName === undefined || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) { + return root; + } + if (root.skeleton) { + const bone = root.skeleton.getBoneByName(nodeName); + if (bone !== undefined) { + return bone; + } + } + if (root.children) { + const searchNodeSubtree = function(children) { + for (let i = 0;i < children.length; i++) { + const childNode = children[i]; + if (childNode.name === nodeName || childNode.uuid === nodeName) { + return childNode; + } + const result = searchNodeSubtree(childNode.children); + if (result) + return result; + } + return null; + }; + const subTreeNode = searchNodeSubtree(root.children); + if (subTreeNode) { + return subTreeNode; + } + } + return null; + } + _getValue_unavailable() { + } + _setValue_unavailable() { + } + _getValue_direct(buffer, offset) { + buffer[offset] = this.targetObject[this.propertyName]; + } + _getValue_array(buffer, offset) { + const source = this.resolvedProperty; + for (let i = 0, n = source.length;i !== n; ++i) { + buffer[offset++] = source[i]; + } + } + _getValue_arrayElement(buffer, offset) { + buffer[offset] = this.resolvedProperty[this.propertyIndex]; + } + _getValue_toArray(buffer, offset) { + this.resolvedProperty.toArray(buffer, offset); + } + _setValue_direct(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + } + _setValue_direct_setNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_array(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length;i !== n; ++i) { + dest[i] = buffer[offset++]; + } + } + _setValue_array_setNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length;i !== n; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.needsUpdate = true; + } + _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length;i !== n; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_arrayElement(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + } + _setValue_arrayElement_setNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_fromArray(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + } + _setValue_fromArray_setNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.needsUpdate = true; + } + _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.matrixWorldNeedsUpdate = true; + } + _getValue_unbound(targetArray, offset) { + this.bind(); + this.getValue(targetArray, offset); + } + _setValue_unbound(sourceArray, offset) { + this.bind(); + this.setValue(sourceArray, offset); + } + bind() { + let targetObject = this.node; + const parsedPath = this.parsedPath; + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + if (!targetObject) { + targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName); + this.node = targetObject; + } + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; + if (!targetObject) { + console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + "."); + return; + } + if (objectName) { + let objectIndex = parsedPath.objectIndex; + switch (objectName) { + case "materials": + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.materials) { + console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this); + return; + } + targetObject = targetObject.material.materials; + break; + case "bones": + if (!targetObject.skeleton) { + console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this); + return; + } + targetObject = targetObject.skeleton.bones; + for (let i = 0;i < targetObject.length; i++) { + if (targetObject[i].name === objectIndex) { + objectIndex = i; + break; + } + } + break; + case "map": + if ("map" in targetObject) { + targetObject = targetObject.map; + break; + } + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.map) { + console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this); + return; + } + targetObject = targetObject.material.map; + break; + default: + if (targetObject[objectName] === undefined) { + console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this); + return; + } + targetObject = targetObject[objectName]; + } + if (objectIndex !== undefined) { + if (targetObject[objectIndex] === undefined) { + console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, targetObject); + return; + } + targetObject = targetObject[objectIndex]; + } + } + const nodeProperty = targetObject[propertyName]; + if (nodeProperty === undefined) { + const nodeName = parsedPath.nodeName; + console.error("THREE.PropertyBinding: Trying to update property for track: " + nodeName + "." + propertyName + " but it wasn't found.", targetObject); + return; + } + let versioning = this.Versioning.None; + this.targetObject = targetObject; + if (targetObject.isMaterial === true) { + versioning = this.Versioning.NeedsUpdate; + } else if (targetObject.isObject3D === true) { + versioning = this.Versioning.MatrixWorldNeedsUpdate; + } + let bindingType = this.BindingType.Direct; + if (propertyIndex !== undefined) { + if (propertyName === "morphTargetInfluences") { + if (!targetObject.geometry) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this); + return; + } + if (!targetObject.geometry.morphAttributes) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this); + return; + } + if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) { + propertyIndex = targetObject.morphTargetDictionary[propertyIndex]; + } + } + bindingType = this.BindingType.ArrayElement; + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) { + bindingType = this.BindingType.HasFromToArray; + this.resolvedProperty = nodeProperty; + } else if (Array.isArray(nodeProperty)) { + bindingType = this.BindingType.EntireArray; + this.resolvedProperty = nodeProperty; + } else { + this.propertyName = propertyName; + } + this.getValue = this.GetterByBindingType[bindingType]; + this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning]; + } + unbind() { + this.node = null; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } +} +PropertyBinding.Composite = Composite; +PropertyBinding.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 +}; +PropertyBinding.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 +}; +PropertyBinding.prototype.GetterByBindingType = [ + PropertyBinding.prototype._getValue_direct, + PropertyBinding.prototype._getValue_array, + PropertyBinding.prototype._getValue_arrayElement, + PropertyBinding.prototype._getValue_toArray +]; +PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ + [ + PropertyBinding.prototype._setValue_direct, + PropertyBinding.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding.prototype._setValue_array, + PropertyBinding.prototype._setValue_array_setNeedsUpdate, + PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding.prototype._setValue_arrayElement, + PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding.prototype._setValue_fromArray, + PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate + ] +]; + +class AnimationObjectGroup { + constructor() { + this.isAnimationObjectGroup = true; + this.uuid = generateUUID(); + this._objects = Array.prototype.slice.call(arguments); + this.nCachedObjects_ = 0; + const indices = {}; + this._indicesByUUID = indices; + for (let i = 0, n = arguments.length;i !== n; ++i) { + indices[arguments[i].uuid] = i; + } + this._paths = []; + this._parsedPaths = []; + this._bindings = []; + this._bindingsIndicesByPath = {}; + const scope = this; + this.stats = { + objects: { + get total() { + return scope._objects.length; + }, + get inUse() { + return this.total - scope.nCachedObjects_; + } + }, + get bindingsPerObject() { + return scope._bindings.length; + } + }; + } + add() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, nBindings = bindings.length; + let knownObject = undefined, nObjects = objects.length, nCachedObjects = this.nCachedObjects_; + for (let i = 0, n = arguments.length;i !== n; ++i) { + const object = arguments[i], uuid = object.uuid; + let index2 = indicesByUUID[uuid]; + if (index2 === undefined) { + index2 = nObjects++; + indicesByUUID[uuid] = index2; + objects.push(object); + for (let j = 0, m = nBindings;j !== m; ++j) { + bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j])); + } + } else if (index2 < nCachedObjects) { + knownObject = objects[index2]; + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex]; + indicesByUUID[lastCachedObject.uuid] = index2; + objects[index2] = lastCachedObject; + indicesByUUID[uuid] = firstActiveIndex; + objects[firstActiveIndex] = object; + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j], lastCached = bindingsForPath[firstActiveIndex]; + let binding = bindingsForPath[index2]; + bindingsForPath[index2] = lastCached; + if (binding === undefined) { + binding = new PropertyBinding(object, paths[j], parsedPaths[j]); + } + bindingsForPath[firstActiveIndex] = binding; + } + } else if (objects[index2] !== knownObject) { + console.error("THREE.AnimationObjectGroup: Different objects with the same UUID " + "detected. Clean the caches or recreate your infrastructure when reloading scenes."); + } + } + this.nCachedObjects_ = nCachedObjects; + } + remove() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_; + for (let i = 0, n = arguments.length;i !== n; ++i) { + const object = arguments[i], uuid = object.uuid, index2 = indicesByUUID[uuid]; + if (index2 !== undefined && index2 >= nCachedObjects) { + const lastCachedIndex = nCachedObjects++, firstActiveObject = objects[lastCachedIndex]; + indicesByUUID[firstActiveObject.uuid] = index2; + objects[index2] = firstActiveObject; + indicesByUUID[uuid] = lastCachedIndex; + objects[lastCachedIndex] = object; + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j], firstActive = bindingsForPath[lastCachedIndex], binding = bindingsForPath[index2]; + bindingsForPath[index2] = firstActive; + bindingsForPath[lastCachedIndex] = binding; + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + uncache() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_, nObjects = objects.length; + for (let i = 0, n = arguments.length;i !== n; ++i) { + const object = arguments[i], uuid = object.uuid, index2 = indicesByUUID[uuid]; + if (index2 !== undefined) { + delete indicesByUUID[uuid]; + if (index2 < nCachedObjects) { + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex], lastIndex = --nObjects, lastObject = objects[lastIndex]; + indicesByUUID[lastCachedObject.uuid] = index2; + objects[index2] = lastCachedObject; + indicesByUUID[lastObject.uuid] = firstActiveIndex; + objects[firstActiveIndex] = lastObject; + objects.pop(); + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j], lastCached = bindingsForPath[firstActiveIndex], last2 = bindingsForPath[lastIndex]; + bindingsForPath[index2] = lastCached; + bindingsForPath[firstActiveIndex] = last2; + bindingsForPath.pop(); + } + } else { + const lastIndex = --nObjects, lastObject = objects[lastIndex]; + if (lastIndex > 0) { + indicesByUUID[lastObject.uuid] = index2; + } + objects[index2] = lastObject; + objects.pop(); + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j]; + bindingsForPath[index2] = bindingsForPath[lastIndex]; + bindingsForPath.pop(); + } + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + subscribe_(path, parsedPath) { + const indicesByPath = this._bindingsIndicesByPath; + let index2 = indicesByPath[path]; + const bindings = this._bindings; + if (index2 !== undefined) + return bindings[index2]; + const paths = this._paths, parsedPaths = this._parsedPaths, objects = this._objects, nObjects = objects.length, nCachedObjects = this.nCachedObjects_, bindingsForPath = new Array(nObjects); + index2 = bindings.length; + indicesByPath[path] = index2; + paths.push(path); + parsedPaths.push(parsedPath); + bindings.push(bindingsForPath); + for (let i = nCachedObjects, n = objects.length;i !== n; ++i) { + const object = objects[i]; + bindingsForPath[i] = new PropertyBinding(object, path, parsedPath); + } + return bindingsForPath; + } + unsubscribe_(path) { + const indicesByPath = this._bindingsIndicesByPath, index2 = indicesByPath[path]; + if (index2 !== undefined) { + const paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, lastBindingsIndex = bindings.length - 1, lastBindings = bindings[lastBindingsIndex], lastBindingsPath = path[lastBindingsIndex]; + indicesByPath[lastBindingsPath] = index2; + bindings[index2] = lastBindings; + bindings.pop(); + parsedPaths[index2] = parsedPaths[lastBindingsIndex]; + parsedPaths.pop(); + paths[index2] = paths[lastBindingsIndex]; + paths.pop(); + } + } +} + +class AnimationAction { + constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) { + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; + const tracks = clip.tracks, nTracks = tracks.length, interpolants = new Array(nTracks); + const interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + for (let i = 0;i !== nTracks; ++i) { + const interpolant = tracks[i].createInterpolant(null); + interpolants[i] = interpolant; + interpolant.settings = interpolantSettings; + } + this._interpolantSettings = interpolantSettings; + this._interpolants = interpolants; + this._propertyBindings = new Array(nTracks); + this._cacheIndex = null; + this._byClipCacheIndex = null; + this._timeScaleInterpolant = null; + this._weightInterpolant = null; + this.loop = LoopRepeat; + this._loopCount = -1; + this._startTime = null; + this.time = 0; + this.timeScale = 1; + this._effectiveTimeScale = 1; + this.weight = 1; + this._effectiveWeight = 1; + this.repetitions = Infinity; + this.paused = false; + this.enabled = true; + this.clampWhenFinished = false; + this.zeroSlopeAtStart = true; + this.zeroSlopeAtEnd = true; + } + play() { + this._mixer._activateAction(this); + return this; + } + stop() { + this._mixer._deactivateAction(this); + return this.reset(); + } + reset() { + this.paused = false; + this.enabled = true; + this.time = 0; + this._loopCount = -1; + this._startTime = null; + return this.stopFading().stopWarping(); + } + isRunning() { + return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this); + } + isScheduled() { + return this._mixer._isActiveAction(this); + } + startAt(time2) { + this._startTime = time2; + return this; + } + setLoop(mode, repetitions) { + this.loop = mode; + this.repetitions = repetitions; + return this; + } + setEffectiveWeight(weight) { + this.weight = weight; + this._effectiveWeight = this.enabled ? weight : 0; + return this.stopFading(); + } + getEffectiveWeight() { + return this._effectiveWeight; + } + fadeIn(duration) { + return this._scheduleFading(duration, 0, 1); + } + fadeOut(duration) { + return this._scheduleFading(duration, 1, 0); + } + crossFadeFrom(fadeOutAction, duration, warp) { + fadeOutAction.fadeOut(duration); + this.fadeIn(duration); + if (warp) { + const fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, startEndRatio = fadeOutDuration / fadeInDuration, endStartRatio = fadeInDuration / fadeOutDuration; + fadeOutAction.warp(1, startEndRatio, duration); + this.warp(endStartRatio, 1, duration); + } + return this; + } + crossFadeTo(fadeInAction, duration, warp) { + return fadeInAction.crossFadeFrom(this, duration, warp); + } + stopFading() { + const weightInterpolant = this._weightInterpolant; + if (weightInterpolant !== null) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant(weightInterpolant); + } + return this; + } + setEffectiveTimeScale(timeScale) { + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; + return this.stopWarping(); + } + getEffectiveTimeScale() { + return this._effectiveTimeScale; + } + setDuration(duration) { + this.timeScale = this._clip.duration / duration; + return this.stopWarping(); + } + syncWith(action) { + this.time = action.time; + this.timeScale = action.timeScale; + return this.stopWarping(); + } + halt(duration) { + return this.warp(this._effectiveTimeScale, 0, duration); + } + warp(startTimeScale, endTimeScale, duration) { + const mixer = this._mixer, now2 = mixer.time, timeScale = this.timeScale; + let interpolant = this._timeScaleInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; + } + const { parameterPositions: times, sampleValues: values2 } = interpolant; + times[0] = now2; + times[1] = now2 + duration; + values2[0] = startTimeScale / timeScale; + values2[1] = endTimeScale / timeScale; + return this; + } + stopWarping() { + const timeScaleInterpolant = this._timeScaleInterpolant; + if (timeScaleInterpolant !== null) { + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant(timeScaleInterpolant); + } + return this; + } + getMixer() { + return this._mixer; + } + getClip() { + return this._clip; + } + getRoot() { + return this._localRoot || this._mixer._root; + } + _update(time2, deltaTime, timeDirection, accuIndex) { + if (!this.enabled) { + this._updateWeight(time2); + return; + } + const startTime = this._startTime; + if (startTime !== null) { + const timeRunning = (time2 - startTime) * timeDirection; + if (timeRunning < 0 || timeDirection === 0) { + deltaTime = 0; + } else { + this._startTime = null; + deltaTime = timeDirection * timeRunning; + } + } + deltaTime *= this._updateTimeScale(time2); + const clipTime = this._updateTime(deltaTime); + const weight = this._updateWeight(time2); + if (weight > 0) { + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; + switch (this.blendMode) { + case AdditiveAnimationBlendMode: + for (let j = 0, m = interpolants.length;j !== m; ++j) { + interpolants[j].evaluate(clipTime); + propertyMixers[j].accumulateAdditive(weight); + } + break; + case NormalAnimationBlendMode: + default: + for (let j = 0, m = interpolants.length;j !== m; ++j) { + interpolants[j].evaluate(clipTime); + propertyMixers[j].accumulate(accuIndex, weight); + } + } + } + } + _updateWeight(time2) { + let weight = 0; + if (this.enabled) { + weight = this.weight; + const interpolant = this._weightInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time2)[0]; + weight *= interpolantValue; + if (time2 > interpolant.parameterPositions[1]) { + this.stopFading(); + if (interpolantValue === 0) { + this.enabled = false; + } + } + } + } + this._effectiveWeight = weight; + return weight; + } + _updateTimeScale(time2) { + let timeScale = 0; + if (!this.paused) { + timeScale = this.timeScale; + const interpolant = this._timeScaleInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time2)[0]; + timeScale *= interpolantValue; + if (time2 > interpolant.parameterPositions[1]) { + this.stopWarping(); + if (timeScale === 0) { + this.paused = true; + } else { + this.timeScale = timeScale; + } + } + } + } + this._effectiveTimeScale = timeScale; + return timeScale; + } + _updateTime(deltaTime) { + const duration = this._clip.duration; + const loop = this.loop; + let time2 = this.time + deltaTime; + let loopCount = this._loopCount; + const pingPong = loop === LoopPingPong; + if (deltaTime === 0) { + if (loopCount === -1) + return time2; + return pingPong && (loopCount & 1) === 1 ? duration - time2 : time2; + } + if (loop === LoopOnce) { + if (loopCount === -1) { + this._loopCount = 0; + this._setEndings(true, true, false); + } + handle_stop: { + if (time2 >= duration) { + time2 = duration; + } else if (time2 < 0) { + time2 = 0; + } else { + this.time = time2; + break handle_stop; + } + if (this.clampWhenFinished) + this.paused = true; + else + this.enabled = false; + this.time = time2; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime < 0 ? -1 : 1 + }); + } + } else { + if (loopCount === -1) { + if (deltaTime >= 0) { + loopCount = 0; + this._setEndings(true, this.repetitions === 0, pingPong); + } else { + this._setEndings(this.repetitions === 0, true, pingPong); + } + } + if (time2 >= duration || time2 < 0) { + const loopDelta = Math.floor(time2 / duration); + time2 -= duration * loopDelta; + loopCount += Math.abs(loopDelta); + const pending = this.repetitions - loopCount; + if (pending <= 0) { + if (this.clampWhenFinished) + this.paused = true; + else + this.enabled = false; + time2 = deltaTime > 0 ? duration : 0; + this.time = time2; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime > 0 ? 1 : -1 + }); + } else { + if (pending === 1) { + const atStart = deltaTime < 0; + this._setEndings(atStart, !atStart, pingPong); + } else { + this._setEndings(false, false, pingPong); + } + this._loopCount = loopCount; + this.time = time2; + this._mixer.dispatchEvent({ + type: "loop", + action: this, + loopDelta + }); + } + } else { + this.time = time2; + } + if (pingPong && (loopCount & 1) === 1) { + return duration - time2; + } + } + return time2; + } + _setEndings(atStart, atEnd, pingPong) { + const settings = this._interpolantSettings; + if (pingPong) { + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; + } else { + if (atStart) { + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; + } else { + settings.endingStart = WrapAroundEnding; + } + if (atEnd) { + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; + } else { + settings.endingEnd = WrapAroundEnding; + } + } + } + _scheduleFading(duration, weightNow, weightThen) { + const mixer = this._mixer, now2 = mixer.time; + let interpolant = this._weightInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; + } + const { parameterPositions: times, sampleValues: values2 } = interpolant; + times[0] = now2; + values2[0] = weightNow; + times[1] = now2 + duration; + values2[1] = weightThen; + return this; + } +} +var _controlInterpolantsResultBuffer = new Float32Array(1); + +class AnimationMixer extends EventDispatcher { + constructor(root) { + super(); + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1; + } + _bindAction(action, prototypeAction) { + const root = action._localRoot || this._root, tracks = action._clip.tracks, nTracks = tracks.length, bindings = action._propertyBindings, interpolants = action._interpolants, rootUuid = root.uuid, bindingsByRoot = this._bindingsByRootAndName; + let bindingsByName = bindingsByRoot[rootUuid]; + if (bindingsByName === undefined) { + bindingsByName = {}; + bindingsByRoot[rootUuid] = bindingsByName; + } + for (let i = 0;i !== nTracks; ++i) { + const track = tracks[i], trackName = track.name; + let binding = bindingsByName[trackName]; + if (binding !== undefined) { + ++binding.referenceCount; + bindings[i] = binding; + } else { + binding = bindings[i]; + if (binding !== undefined) { + if (binding._cacheIndex === null) { + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + } + continue; + } + const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath; + binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize()); + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + bindings[i] = binding; + } + interpolants[i].resultBuffer = binding.buffer; + } + } + _activateAction(action) { + if (!this._isActiveAction(action)) { + if (action._cacheIndex === null) { + const rootUuid = (action._localRoot || this._root).uuid, clipUuid = action._clip.uuid, actionsForClip = this._actionsByClip[clipUuid]; + this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]); + this._addInactiveAction(action, clipUuid, rootUuid); + } + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length;i !== n; ++i) { + const binding = bindings[i]; + if (binding.useCount++ === 0) { + this._lendBinding(binding); + binding.saveOriginalState(); + } + } + this._lendAction(action); + } + } + _deactivateAction(action) { + if (this._isActiveAction(action)) { + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length;i !== n; ++i) { + const binding = bindings[i]; + if (--binding.useCount === 0) { + binding.restoreOriginalState(); + this._takeBackBinding(binding); + } + } + this._takeBackAction(action); + } + } + _initMemoryManager() { + this._actions = []; + this._nActiveActions = 0; + this._actionsByClip = {}; + this._bindings = []; + this._nActiveBindings = 0; + this._bindingsByRootAndName = {}; + this._controlInterpolants = []; + this._nActiveControlInterpolants = 0; + const scope = this; + this.stats = { + actions: { + get total() { + return scope._actions.length; + }, + get inUse() { + return scope._nActiveActions; + } + }, + bindings: { + get total() { + return scope._bindings.length; + }, + get inUse() { + return scope._nActiveBindings; + } + }, + controlInterpolants: { + get total() { + return scope._controlInterpolants.length; + }, + get inUse() { + return scope._nActiveControlInterpolants; + } + } + }; + } + _isActiveAction(action) { + const index2 = action._cacheIndex; + return index2 !== null && index2 < this._nActiveActions; + } + _addInactiveAction(action, clipUuid, rootUuid) { + const actions = this._actions, actionsByClip = this._actionsByClip; + let actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip === undefined) { + actionsForClip = { + knownActions: [action], + actionByRoot: {} + }; + action._byClipCacheIndex = 0; + actionsByClip[clipUuid] = actionsForClip; + } else { + const knownActions = actionsForClip.knownActions; + action._byClipCacheIndex = knownActions.length; + knownActions.push(action); + } + action._cacheIndex = actions.length; + actions.push(action); + actionsForClip.actionByRoot[rootUuid] = action; + } + _removeInactiveAction(action) { + const actions = this._actions, lastInactiveAction = actions[actions.length - 1], cacheIndex = action._cacheIndex; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + action._cacheIndex = null; + const clipUuid = action._clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid], knownActionsForClip = actionsForClip.knownActions, lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1], byClipCacheIndex = action._byClipCacheIndex; + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[byClipCacheIndex] = lastKnownAction; + knownActionsForClip.pop(); + action._byClipCacheIndex = null; + const actionByRoot = actionsForClip.actionByRoot, rootUuid = (action._localRoot || this._root).uuid; + delete actionByRoot[rootUuid]; + if (knownActionsForClip.length === 0) { + delete actionsByClip[clipUuid]; + } + this._removeInactiveBindingsForAction(action); + } + _removeInactiveBindingsForAction(action) { + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length;i !== n; ++i) { + const binding = bindings[i]; + if (--binding.referenceCount === 0) { + this._removeInactiveBinding(binding); + } + } + } + _lendAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, lastActiveIndex = this._nActiveActions++, firstInactiveAction = actions[lastActiveIndex]; + action._cacheIndex = lastActiveIndex; + actions[lastActiveIndex] = action; + firstInactiveAction._cacheIndex = prevIndex; + actions[prevIndex] = firstInactiveAction; + } + _takeBackAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, firstInactiveIndex = --this._nActiveActions, lastActiveAction = actions[firstInactiveIndex]; + action._cacheIndex = firstInactiveIndex; + actions[firstInactiveIndex] = action; + lastActiveAction._cacheIndex = prevIndex; + actions[prevIndex] = lastActiveAction; + } + _addInactiveBinding(binding, rootUuid, trackName) { + const bindingsByRoot = this._bindingsByRootAndName, bindings = this._bindings; + let bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName === undefined) { + bindingByName = {}; + bindingsByRoot[rootUuid] = bindingByName; + } + bindingByName[trackName] = binding; + binding._cacheIndex = bindings.length; + bindings.push(binding); + } + _removeInactiveBinding(binding) { + const bindings = this._bindings, propBinding = binding.binding, rootUuid = propBinding.rootNode.uuid, trackName = propBinding.path, bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid], lastInactiveBinding = bindings[bindings.length - 1], cacheIndex = binding._cacheIndex; + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[cacheIndex] = lastInactiveBinding; + bindings.pop(); + delete bindingByName[trackName]; + if (Object.keys(bindingByName).length === 0) { + delete bindingsByRoot[rootUuid]; + } + } + _lendBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, lastActiveIndex = this._nActiveBindings++, firstInactiveBinding = bindings[lastActiveIndex]; + binding._cacheIndex = lastActiveIndex; + bindings[lastActiveIndex] = binding; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = firstInactiveBinding; + } + _takeBackBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, firstInactiveIndex = --this._nActiveBindings, lastActiveBinding = bindings[firstInactiveIndex]; + binding._cacheIndex = firstInactiveIndex; + bindings[firstInactiveIndex] = binding; + lastActiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = lastActiveBinding; + } + _lendControlInterpolant() { + const interpolants = this._controlInterpolants, lastActiveIndex = this._nActiveControlInterpolants++; + let interpolant = interpolants[lastActiveIndex]; + if (interpolant === undefined) { + interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer); + interpolant.__cacheIndex = lastActiveIndex; + interpolants[lastActiveIndex] = interpolant; + } + return interpolant; + } + _takeBackControlInterpolant(interpolant) { + const interpolants = this._controlInterpolants, prevIndex = interpolant.__cacheIndex, firstInactiveIndex = --this._nActiveControlInterpolants, lastActiveInterpolant = interpolants[firstInactiveIndex]; + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[firstInactiveIndex] = interpolant; + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[prevIndex] = lastActiveInterpolant; + } + clipAction(clip, optionalRoot, blendMode) { + const root = optionalRoot || this._root, rootUuid = root.uuid; + let clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip; + const clipUuid = clipObject !== null ? clipObject.uuid : clip; + const actionsForClip = this._actionsByClip[clipUuid]; + let prototypeAction = null; + if (blendMode === undefined) { + if (clipObject !== null) { + blendMode = clipObject.blendMode; + } else { + blendMode = NormalAnimationBlendMode; + } + } + if (actionsForClip !== undefined) { + const existingAction = actionsForClip.actionByRoot[rootUuid]; + if (existingAction !== undefined && existingAction.blendMode === blendMode) { + return existingAction; + } + prototypeAction = actionsForClip.knownActions[0]; + if (clipObject === null) + clipObject = prototypeAction._clip; + } + if (clipObject === null) + return null; + const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode); + this._bindAction(newAction, prototypeAction); + this._addInactiveAction(newAction, clipUuid, rootUuid); + return newAction; + } + existingAction(clip, optionalRoot) { + const root = optionalRoot || this._root, rootUuid = root.uuid, clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip, clipUuid = clipObject ? clipObject.uuid : clip, actionsForClip = this._actionsByClip[clipUuid]; + if (actionsForClip !== undefined) { + return actionsForClip.actionByRoot[rootUuid] || null; + } + return null; + } + stopAllAction() { + const actions = this._actions, nActions = this._nActiveActions; + for (let i = nActions - 1;i >= 0; --i) { + actions[i].stop(); + } + return this; + } + update(deltaTime) { + deltaTime *= this.timeScale; + const actions = this._actions, nActions = this._nActiveActions, time2 = this.time += deltaTime, timeDirection = Math.sign(deltaTime), accuIndex = this._accuIndex ^= 1; + for (let i = 0;i !== nActions; ++i) { + const action = actions[i]; + action._update(time2, deltaTime, timeDirection, accuIndex); + } + const bindings = this._bindings, nBindings = this._nActiveBindings; + for (let i = 0;i !== nBindings; ++i) { + bindings[i].apply(accuIndex); + } + return this; + } + setTime(timeInSeconds) { + this.time = 0; + for (let i = 0;i < this._actions.length; i++) { + this._actions[i].time = 0; + } + return this.update(timeInSeconds); + } + getRoot() { + return this._root; + } + uncacheClip(clip) { + const actions = this._actions, clipUuid = clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip !== undefined) { + const actionsToRemove = actionsForClip.knownActions; + for (let i = 0, n = actionsToRemove.length;i !== n; ++i) { + const action = actionsToRemove[i]; + this._deactivateAction(action); + const cacheIndex = action._cacheIndex, lastInactiveAction = actions[actions.length - 1]; + action._cacheIndex = null; + action._byClipCacheIndex = null; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + this._removeInactiveBindingsForAction(action); + } + delete actionsByClip[clipUuid]; + } + } + uncacheRoot(root) { + const rootUuid = root.uuid, actionsByClip = this._actionsByClip; + for (const clipUuid in actionsByClip) { + const actionByRoot = actionsByClip[clipUuid].actionByRoot, action = actionByRoot[rootUuid]; + if (action !== undefined) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + const bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName !== undefined) { + for (const trackName in bindingByName) { + const binding = bindingByName[trackName]; + binding.restoreOriginalState(); + this._removeInactiveBinding(binding); + } + } + } + uncacheAction(clip, optionalRoot) { + const action = this.existingAction(clip, optionalRoot); + if (action !== null) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } +} + +class RenderTarget3D extends RenderTarget { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isRenderTarget3D = true; + this.depth = depth; + this.texture = new Data3DTexture(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } +} + +class RenderTargetArray extends RenderTarget { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isRenderTargetArray = true; + this.depth = depth; + this.texture = new DataArrayTexture(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } +} + +class Uniform { + constructor(value2) { + this.value = value2; + } + clone() { + return new Uniform(this.value.clone === undefined ? this.value : this.value.clone()); + } +} +var _id = 0; + +class UniformsGroup extends EventDispatcher { + constructor() { + super(); + this.isUniformsGroup = true; + Object.defineProperty(this, "id", { value: _id++ }); + this.name = ""; + this.usage = StaticDrawUsage; + this.uniforms = []; + } + add(uniform) { + this.uniforms.push(uniform); + return this; + } + remove(uniform) { + const index2 = this.uniforms.indexOf(uniform); + if (index2 !== -1) + this.uniforms.splice(index2, 1); + return this; + } + setName(name2) { + this.name = name2; + return this; + } + setUsage(value2) { + this.usage = value2; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + return this; + } + copy(source) { + this.name = source.name; + this.usage = source.usage; + const uniformsSource = source.uniforms; + this.uniforms.length = 0; + for (let i = 0, l = uniformsSource.length;i < l; i++) { + const uniforms = Array.isArray(uniformsSource[i]) ? uniformsSource[i] : [uniformsSource[i]]; + for (let j = 0;j < uniforms.length; j++) { + this.uniforms.push(uniforms[j].clone()); + } + } + return this; + } + clone() { + return new this.constructor().copy(this); + } +} + +class InstancedInterleavedBuffer extends InterleavedBuffer { + constructor(array, stride, meshPerAttribute = 1) { + super(array, stride); + this.isInstancedInterleavedBuffer = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + clone(data2) { + const ib = super.clone(data2); + ib.meshPerAttribute = this.meshPerAttribute; + return ib; + } + toJSON(data2) { + const json = super.toJSON(data2); + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; + return json; + } +} + +class GLBufferAttribute { + constructor(buffer, type, itemSize, elementSize, count) { + this.isGLBufferAttribute = true; + this.name = ""; + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; + this.version = 0; + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setBuffer(buffer) { + this.buffer = buffer; + return this; + } + setType(type, elementSize) { + this.type = type; + this.elementSize = elementSize; + return this; + } + setItemSize(itemSize) { + this.itemSize = itemSize; + return this; + } + setCount(count) { + this.count = count; + return this; + } +} +var _matrix = /* @__PURE__ */ new Matrix4; + +class Raycaster { + constructor(origin, direction, near = 0, far = Infinity) { + this.ray = new Ray(origin, direction); + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers; + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + } + set(origin, direction) { + this.ray.set(origin, direction); + } + setFromCamera(coords, camera) { + if (camera.isPerspectiveCamera) { + this.ray.origin.setFromMatrixPosition(camera.matrixWorld); + this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize(); + this.camera = camera; + } else if (camera.isOrthographicCamera) { + this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); + this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld); + this.camera = camera; + } else { + console.error("THREE.Raycaster: Unsupported camera type: " + camera.type); + } + } + setFromXRController(controller) { + _matrix.identity().extractRotation(controller.matrixWorld); + this.ray.origin.setFromMatrixPosition(controller.matrixWorld); + this.ray.direction.set(0, 0, -1).applyMatrix4(_matrix); + return this; + } + intersectObject(object, recursive = true, intersects2 = []) { + intersect(object, this, intersects2, recursive); + intersects2.sort(ascSort); + return intersects2; + } + intersectObjects(objects, recursive = true, intersects2 = []) { + for (let i = 0, l = objects.length;i < l; i++) { + intersect(objects[i], this, intersects2, recursive); + } + intersects2.sort(ascSort); + return intersects2; + } +} +function ascSort(a, b) { + return a.distance - b.distance; +} +function intersect(object, raycaster, intersects2, recursive) { + let propagate = true; + if (object.layers.test(raycaster.layers)) { + const result = object.raycast(raycaster, intersects2); + if (result === false) + propagate = false; + } + if (propagate === true && recursive === true) { + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + intersect(children[i], raycaster, intersects2, true); + } + } +} + +class Spherical { + constructor(radius = 1, phi = 0, theta = 0) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + set(radius, phi, theta) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + copy(other) { + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + return this; + } + makeSafe() { + const EPS = 0.000001; + this.phi = clamp2(this.phi, EPS, Math.PI - EPS); + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x, y, z) { + this.radius = Math.sqrt(x * x + y * y + z * z); + if (this.radius === 0) { + this.theta = 0; + this.phi = 0; + } else { + this.theta = Math.atan2(x, z); + this.phi = Math.acos(clamp2(y / this.radius, -1, 1)); + } + return this; + } + clone() { + return new this.constructor().copy(this); + } +} + +class Cylindrical { + constructor(radius = 1, theta = 0, y = 0) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + set(radius, theta, y) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + copy(other) { + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x, y, z) { + this.radius = Math.sqrt(x * x + z * z); + this.theta = Math.atan2(x, z); + this.y = y; + return this; + } + clone() { + return new this.constructor().copy(this); + } +} + +class Matrix2 { + constructor(n11, n12, n21, n22) { + Matrix2.prototype.isMatrix2 = true; + this.elements = [ + 1, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n21, n22); + } + } + identity() { + this.set(1, 0, 0, 1); + return this; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 4; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + set(n11, n12, n21, n22) { + const te2 = this.elements; + te2[0] = n11; + te2[2] = n12; + te2[1] = n21; + te2[3] = n22; + return this; + } +} +var _vector$4 = /* @__PURE__ */ new Vector2; + +class Box2 { + constructor(min = new Vector2(Infinity, Infinity), max = new Vector2(-Infinity, -Infinity)) { + this.isBox2 = true; + this.min = min; + this.max = max; + } + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length;i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size) { + const halfSize = _vector$4.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = Infinity; + this.max.x = this.max.y = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y; + } + getParameter(point, target) { + return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y)); + } + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y; + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$4).distanceTo(point); + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) + this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } +} +var _startP = /* @__PURE__ */ new Vector3; +var _startEnd = /* @__PURE__ */ new Vector3; + +class Line3 { + constructor(start = new Vector3, end = new Vector3) { + this.start = start; + this.end = end; + } + set(start, end) { + this.start.copy(start); + this.end.copy(end); + return this; + } + copy(line) { + this.start.copy(line.start); + this.end.copy(line.end); + return this; + } + getCenter(target) { + return target.addVectors(this.start, this.end).multiplyScalar(0.5); + } + delta(target) { + return target.subVectors(this.end, this.start); + } + distanceSq() { + return this.start.distanceToSquared(this.end); + } + distance() { + return this.start.distanceTo(this.end); + } + at(t, target) { + return this.delta(target).multiplyScalar(t).add(this.start); + } + closestPointToPointParameter(point, clampToLine) { + _startP.subVectors(point, this.start); + _startEnd.subVectors(this.end, this.start); + const startEnd2 = _startEnd.dot(_startEnd); + const startEnd_startP = _startEnd.dot(_startP); + let t = startEnd_startP / startEnd2; + if (clampToLine) { + t = clamp2(t, 0, 1); + } + return t; + } + closestPointToPoint(point, clampToLine, target) { + const t = this.closestPointToPointParameter(point, clampToLine); + return this.delta(target).multiplyScalar(t).add(this.start); + } + applyMatrix4(matrix) { + this.start.applyMatrix4(matrix); + this.end.applyMatrix4(matrix); + return this; + } + equals(line) { + return line.start.equals(this.start) && line.end.equals(this.end); + } + clone() { + return new this.constructor().copy(this); + } +} +var _vector$3 = /* @__PURE__ */ new Vector3; + +class SpotLightHelper extends Object3D { + constructor(light, color) { + super(); + this.light = light; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "SpotLightHelper"; + const geometry = new BufferGeometry; + const positions = [ + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + -1, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + -1, + 1 + ]; + for (let i = 0, j = 1, l = 32;i < l; i++, j++) { + const p1 = i / l * Math.PI * 2; + const p2 = j / l * Math.PI * 2; + positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1); + } + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + const material = new LineBasicMaterial({ fog: false, toneMapped: false }); + this.cone = new LineSegments(geometry, material); + this.add(this.cone); + this.update(); + } + dispose() { + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + if (this.parent) { + this.parent.updateWorldMatrix(true); + this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld); + } else { + this.matrix.copy(this.light.matrixWorld); + } + this.matrixWorld.copy(this.light.matrixWorld); + const coneLength = this.light.distance ? this.light.distance : 1000; + const coneWidth = coneLength * Math.tan(this.light.angle); + this.cone.scale.set(coneWidth, coneWidth, coneLength); + _vector$3.setFromMatrixPosition(this.light.target.matrixWorld); + this.cone.lookAt(_vector$3); + if (this.color !== undefined) { + this.cone.material.color.set(this.color); + } else { + this.cone.material.color.copy(this.light.color); + } + } +} +var _vector$2 = /* @__PURE__ */ new Vector3; +var _boneMatrix = /* @__PURE__ */ new Matrix4; +var _matrixWorldInv = /* @__PURE__ */ new Matrix4; + +class SkeletonHelper extends LineSegments { + constructor(object) { + const bones = getBoneList(object); + const geometry = new BufferGeometry; + const vertices = []; + const colors = []; + const color1 = new Color(0, 0, 1); + const color2 = new Color(0, 1, 0); + for (let i = 0;i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + vertices.push(0, 0, 0); + vertices.push(0, 0, 0); + colors.push(color1.r, color1.g, color1.b); + colors.push(color2.r, color2.g, color2.b); + } + } + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true }); + super(geometry, material); + this.isSkeletonHelper = true; + this.type = "SkeletonHelper"; + this.root = object; + this.bones = bones; + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + } + updateMatrixWorld(force) { + const bones = this.bones; + const geometry = this.geometry; + const position2 = geometry.getAttribute("position"); + _matrixWorldInv.copy(this.root.matrixWorld).invert(); + for (let i = 0, j = 0;i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld); + _vector$2.setFromMatrixPosition(_boneMatrix); + position2.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z); + _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld); + _vector$2.setFromMatrixPosition(_boneMatrix); + position2.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z); + j += 2; + } + } + geometry.getAttribute("position").needsUpdate = true; + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} +function getBoneList(object) { + const boneList = []; + if (object.isBone === true) { + boneList.push(object); + } + for (let i = 0;i < object.children.length; i++) { + boneList.push.apply(boneList, getBoneList(object.children[i])); + } + return boneList; +} + +class PointLightHelper extends Mesh { + constructor(light, sphereSize, color) { + const geometry = new SphereGeometry(sphereSize, 4, 2); + const material = new MeshBasicMaterial({ wireframe: true, fog: false, toneMapped: false }); + super(geometry, material); + this.light = light; + this.color = color; + this.type = "PointLightHelper"; + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; + this.update(); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + if (this.color !== undefined) { + this.material.color.set(this.color); + } else { + this.material.color.copy(this.light.color); + } + } +} +var _vector$1 = /* @__PURE__ */ new Vector3; +var _color1 = /* @__PURE__ */ new Color; +var _color2 = /* @__PURE__ */ new Color; + +class HemisphereLightHelper extends Object3D { + constructor(light, size, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "HemisphereLightHelper"; + const geometry = new OctahedronGeometry(size); + geometry.rotateY(Math.PI * 0.5); + this.material = new MeshBasicMaterial({ wireframe: true, fog: false, toneMapped: false }); + if (this.color === undefined) + this.material.vertexColors = true; + const position2 = geometry.getAttribute("position"); + const colors = new Float32Array(position2.count * 3); + geometry.setAttribute("color", new BufferAttribute(colors, 3)); + this.add(new Mesh(geometry, this.material)); + this.update(); + } + dispose() { + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + update() { + const mesh = this.children[0]; + if (this.color !== undefined) { + this.material.color.set(this.color); + } else { + const colors = mesh.geometry.getAttribute("color"); + _color1.copy(this.light.color); + _color2.copy(this.light.groundColor); + for (let i = 0, l = colors.count;i < l; i++) { + const color = i < l / 2 ? _color1 : _color2; + colors.setXYZ(i, color.r, color.g, color.b); + } + colors.needsUpdate = true; + } + this.light.updateWorldMatrix(true, false); + mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate()); + } +} + +class GridHelper extends LineSegments { + constructor(size = 10, divisions = 10, color1 = 4473924, color2 = 8947848) { + color1 = new Color(color1); + color2 = new Color(color2); + const center = divisions / 2; + const step = size / divisions; + const halfSize = size / 2; + const vertices = [], colors = []; + for (let i = 0, j = 0, k2 = -halfSize;i <= divisions; i++, k2 += step) { + vertices.push(-halfSize, 0, k2, halfSize, 0, k2); + vertices.push(k2, 0, -halfSize, k2, 0, halfSize); + const color = i === center ? color1 : color2; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + } + const geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "GridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} + +class PolarGridHelper extends LineSegments { + constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 4473924, color2 = 8947848) { + color1 = new Color(color1); + color2 = new Color(color2); + const vertices = []; + const colors = []; + if (sectors > 1) { + for (let i = 0;i < sectors; i++) { + const v = i / sectors * (Math.PI * 2); + const x = Math.sin(v) * radius; + const z = Math.cos(v) * radius; + vertices.push(0, 0, 0); + vertices.push(x, 0, z); + const color = i & 1 ? color1 : color2; + colors.push(color.r, color.g, color.b); + colors.push(color.r, color.g, color.b); + } + } + for (let i = 0;i < rings; i++) { + const color = i & 1 ? color1 : color2; + const r = radius - radius / rings * i; + for (let j = 0;j < divisions; j++) { + let v = j / divisions * (Math.PI * 2); + let x = Math.sin(v) * r; + let z = Math.cos(v) * r; + vertices.push(x, 0, z); + colors.push(color.r, color.g, color.b); + v = (j + 1) / divisions * (Math.PI * 2); + x = Math.sin(v) * r; + z = Math.cos(v) * r; + vertices.push(x, 0, z); + colors.push(color.r, color.g, color.b); + } + } + const geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "PolarGridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} +var _v1 = /* @__PURE__ */ new Vector3; +var _v2 = /* @__PURE__ */ new Vector3; +var _v3 = /* @__PURE__ */ new Vector3; + +class DirectionalLightHelper extends Object3D { + constructor(light, size, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "DirectionalLightHelper"; + if (size === undefined) + size = 1; + let geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute([ + -size, + size, + 0, + size, + size, + 0, + size, + -size, + 0, + -size, + -size, + 0, + -size, + size, + 0 + ], 3)); + const material = new LineBasicMaterial({ fog: false, toneMapped: false }); + this.lightPlane = new Line(geometry, material); + this.add(this.lightPlane); + geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3)); + this.targetLine = new Line(geometry, material); + this.add(this.targetLine); + this.update(); + } + dispose() { + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + _v1.setFromMatrixPosition(this.light.matrixWorld); + _v2.setFromMatrixPosition(this.light.target.matrixWorld); + _v3.subVectors(_v2, _v1); + this.lightPlane.lookAt(_v2); + if (this.color !== undefined) { + this.lightPlane.material.color.set(this.color); + this.targetLine.material.color.set(this.color); + } else { + this.lightPlane.material.color.copy(this.light.color); + this.targetLine.material.color.copy(this.light.color); + } + this.targetLine.lookAt(_v2); + this.targetLine.scale.z = _v3.length(); + } +} +var _vector = /* @__PURE__ */ new Vector3; +var _camera = /* @__PURE__ */ new Camera; + +class CameraHelper extends LineSegments { + constructor(camera) { + const geometry = new BufferGeometry; + const material = new LineBasicMaterial({ color: 16777215, vertexColors: true, toneMapped: false }); + const vertices = []; + const colors = []; + const pointMap = {}; + addLine("n1", "n2"); + addLine("n2", "n4"); + addLine("n4", "n3"); + addLine("n3", "n1"); + addLine("f1", "f2"); + addLine("f2", "f4"); + addLine("f4", "f3"); + addLine("f3", "f1"); + addLine("n1", "f1"); + addLine("n2", "f2"); + addLine("n3", "f3"); + addLine("n4", "f4"); + addLine("p", "n1"); + addLine("p", "n2"); + addLine("p", "n3"); + addLine("p", "n4"); + addLine("u1", "u2"); + addLine("u2", "u3"); + addLine("u3", "u1"); + addLine("c", "t"); + addLine("p", "c"); + addLine("cn1", "cn2"); + addLine("cn3", "cn4"); + addLine("cf1", "cf2"); + addLine("cf3", "cf4"); + function addLine(a, b) { + addPoint(a); + addPoint(b); + } + function addPoint(id) { + vertices.push(0, 0, 0); + colors.push(0, 0, 0); + if (pointMap[id] === undefined) { + pointMap[id] = []; + } + pointMap[id].push(vertices.length / 3 - 1); + } + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + super(geometry, material); + this.type = "CameraHelper"; + this.camera = camera; + if (this.camera.updateProjectionMatrix) + this.camera.updateProjectionMatrix(); + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; + this.pointMap = pointMap; + this.update(); + const colorFrustum = new Color(16755200); + const colorCone = new Color(16711680); + const colorUp = new Color(43775); + const colorTarget = new Color(16777215); + const colorCross = new Color(3355443); + this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross); + } + setColors(frustum, cone, up, target, cross) { + const geometry = this.geometry; + const colorAttribute = geometry.getAttribute("color"); + colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(24, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(26, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(28, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(30, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(32, up.r, up.g, up.b); + colorAttribute.setXYZ(33, up.r, up.g, up.b); + colorAttribute.setXYZ(34, up.r, up.g, up.b); + colorAttribute.setXYZ(35, up.r, up.g, up.b); + colorAttribute.setXYZ(36, up.r, up.g, up.b); + colorAttribute.setXYZ(37, up.r, up.g, up.b); + colorAttribute.setXYZ(38, target.r, target.g, target.b); + colorAttribute.setXYZ(39, target.r, target.g, target.b); + colorAttribute.setXYZ(40, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(42, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(44, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(46, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(48, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); + colorAttribute.needsUpdate = true; + } + update() { + const geometry = this.geometry; + const pointMap = this.pointMap; + const w = 1, h = 1; + _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); + const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? -1 : 0; + setPoint("c", pointMap, geometry, _camera, 0, 0, nearZ); + setPoint("t", pointMap, geometry, _camera, 0, 0, 1); + setPoint("n1", pointMap, geometry, _camera, -w, -h, nearZ); + setPoint("n2", pointMap, geometry, _camera, w, -h, nearZ); + setPoint("n3", pointMap, geometry, _camera, -w, h, nearZ); + setPoint("n4", pointMap, geometry, _camera, w, h, nearZ); + setPoint("f1", pointMap, geometry, _camera, -w, -h, 1); + setPoint("f2", pointMap, geometry, _camera, w, -h, 1); + setPoint("f3", pointMap, geometry, _camera, -w, h, 1); + setPoint("f4", pointMap, geometry, _camera, w, h, 1); + setPoint("u1", pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ); + setPoint("u2", pointMap, geometry, _camera, -w * 0.7, h * 1.1, nearZ); + setPoint("u3", pointMap, geometry, _camera, 0, h * 2, nearZ); + setPoint("cf1", pointMap, geometry, _camera, -w, 0, 1); + setPoint("cf2", pointMap, geometry, _camera, w, 0, 1); + setPoint("cf3", pointMap, geometry, _camera, 0, -h, 1); + setPoint("cf4", pointMap, geometry, _camera, 0, h, 1); + setPoint("cn1", pointMap, geometry, _camera, -w, 0, nearZ); + setPoint("cn2", pointMap, geometry, _camera, w, 0, nearZ); + setPoint("cn3", pointMap, geometry, _camera, 0, -h, nearZ); + setPoint("cn4", pointMap, geometry, _camera, 0, h, nearZ); + geometry.getAttribute("position").needsUpdate = true; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} +function setPoint(point, pointMap, geometry, camera, x, y, z) { + _vector.set(x, y, z).unproject(camera); + const points = pointMap[point]; + if (points !== undefined) { + const position2 = geometry.getAttribute("position"); + for (let i = 0, l = points.length;i < l; i++) { + position2.setXYZ(points[i], _vector.x, _vector.y, _vector.z); + } + } +} +var _box = /* @__PURE__ */ new Box3; + +class BoxHelper extends LineSegments { + constructor(object, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = new Float32Array(8 * 3); + const geometry = new BufferGeometry; + geometry.setIndex(new BufferAttribute(indices, 1)); + geometry.setAttribute("position", new BufferAttribute(positions, 3)); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.object = object; + this.type = "BoxHelper"; + this.matrixAutoUpdate = false; + this.update(); + } + update(object) { + if (object !== undefined) { + console.warn("THREE.BoxHelper: .update() has no longer arguments."); + } + if (this.object !== undefined) { + _box.setFromObject(this.object); + } + if (_box.isEmpty()) + return; + const min = _box.min; + const max = _box.max; + const position2 = this.geometry.attributes.position; + const array = position2.array; + array[0] = max.x; + array[1] = max.y; + array[2] = max.z; + array[3] = min.x; + array[4] = max.y; + array[5] = max.z; + array[6] = min.x; + array[7] = min.y; + array[8] = max.z; + array[9] = max.x; + array[10] = min.y; + array[11] = max.z; + array[12] = max.x; + array[13] = max.y; + array[14] = min.z; + array[15] = min.x; + array[16] = max.y; + array[17] = min.z; + array[18] = min.x; + array[19] = min.y; + array[20] = min.z; + array[21] = max.x; + array[22] = min.y; + array[23] = min.z; + position2.needsUpdate = true; + this.geometry.computeBoundingSphere(); + } + setFromObject(object) { + this.object = object; + this.update(); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + this.object = source.object; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} + +class Box3Helper extends LineSegments { + constructor(box, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1]; + const geometry = new BufferGeometry; + geometry.setIndex(new BufferAttribute(indices, 1)); + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.box = box; + this.type = "Box3Helper"; + this.geometry.computeBoundingSphere(); + } + updateMatrixWorld(force) { + const box = this.box; + if (box.isEmpty()) + return; + box.getCenter(this.position); + box.getSize(this.scale); + this.scale.multiplyScalar(0.5); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} + +class PlaneHelper extends Line { + constructor(plane, size = 1, hex = 16776960) { + const color = hex; + const positions = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0]; + const geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + geometry.computeBoundingSphere(); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.type = "PlaneHelper"; + this.plane = plane; + this.size = size; + const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0]; + const geometry2 = new BufferGeometry; + geometry2.setAttribute("position", new Float32BufferAttribute(positions2, 3)); + geometry2.computeBoundingSphere(); + this.add(new Mesh(geometry2, new MeshBasicMaterial({ color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false }))); + } + updateMatrixWorld(force) { + this.position.set(0, 0, 0); + this.scale.set(0.5 * this.size, 0.5 * this.size, 1); + this.lookAt(this.plane.normal); + this.translateZ(-this.plane.constant); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } +} +var _axis = /* @__PURE__ */ new Vector3; +var _lineGeometry; +var _coneGeometry; + +class ArrowHelper extends Object3D { + constructor(dir = new Vector3(0, 0, 1), origin = new Vector3(0, 0, 0), length2 = 1, color = 16776960, headLength = length2 * 0.2, headWidth = headLength * 0.2) { + super(); + this.type = "ArrowHelper"; + if (_lineGeometry === undefined) { + _lineGeometry = new BufferGeometry; + _lineGeometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3)); + _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1); + _coneGeometry.translate(0, -0.5, 0); + } + this.position.copy(origin); + this.line = new Line(_lineGeometry, new LineBasicMaterial({ color, toneMapped: false })); + this.line.matrixAutoUpdate = false; + this.add(this.line); + this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({ color, toneMapped: false })); + this.cone.matrixAutoUpdate = false; + this.add(this.cone); + this.setDirection(dir); + this.setLength(length2, headLength, headWidth); + } + setDirection(dir) { + if (dir.y > 0.99999) { + this.quaternion.set(0, 0, 0, 1); + } else if (dir.y < -0.99999) { + this.quaternion.set(1, 0, 0, 0); + } else { + _axis.set(dir.z, 0, -dir.x).normalize(); + const radians = Math.acos(dir.y); + this.quaternion.setFromAxisAngle(_axis, radians); + } + } + setLength(length2, headLength = length2 * 0.2, headWidth = headLength * 0.2) { + this.line.scale.set(1, Math.max(0.0001, length2 - headLength), 1); + this.line.updateMatrix(); + this.cone.scale.set(headWidth, headLength, headWidth); + this.cone.position.y = length2; + this.cone.updateMatrix(); + } + setColor(color) { + this.line.material.color.set(color); + this.cone.material.color.set(color); + } + copy(source) { + super.copy(source, false); + this.line.copy(source.line); + this.cone.copy(source.cone); + return this; + } + dispose() { + this.line.geometry.dispose(); + this.line.material.dispose(); + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } +} + +class AxesHelper extends LineSegments { + constructor(size = 1) { + const vertices = [ + 0, + 0, + 0, + size, + 0, + 0, + 0, + 0, + 0, + 0, + size, + 0, + 0, + 0, + 0, + 0, + 0, + size + ]; + const colors = [ + 1, + 0, + 0, + 1, + 0.6, + 0, + 0, + 1, + 0, + 0.6, + 1, + 0, + 0, + 0, + 1, + 0, + 0.6, + 1 + ]; + const geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "AxesHelper"; + } + setColors(xAxisColor, yAxisColor, zAxisColor) { + const color = new Color; + const array = this.geometry.attributes.color.array; + color.set(xAxisColor); + color.toArray(array, 0); + color.toArray(array, 3); + color.set(yAxisColor); + color.toArray(array, 6); + color.toArray(array, 9); + color.set(zAxisColor); + color.toArray(array, 12); + color.toArray(array, 15); + this.geometry.attributes.color.needsUpdate = true; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} + +class ShapePath2 { + constructor() { + this.type = "ShapePath"; + this.color = new Color; + this.subPaths = []; + this.currentPath = null; + } + moveTo(x, y) { + this.currentPath = new Path; + this.subPaths.push(this.currentPath); + this.currentPath.moveTo(x, y); + return this; + } + lineTo(x, y) { + this.currentPath.lineTo(x, y); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY); + return this; + } + splineThru(pts) { + this.currentPath.splineThru(pts); + return this; + } + toShapes(isCCW) { + function toShapesNoHoles(inSubpaths) { + const shapes2 = []; + for (let i = 0, l = inSubpaths.length;i < l; i++) { + const tmpPath2 = inSubpaths[i]; + const tmpShape2 = new Shape; + tmpShape2.curves = tmpPath2.curves; + shapes2.push(tmpShape2); + } + return shapes2; + } + function isPointInsidePolygon(inPt, inPolygon) { + const polyLen = inPolygon.length; + let inside = false; + for (let p = polyLen - 1, q = 0;q < polyLen; p = q++) { + let edgeLowPt = inPolygon[p]; + let edgeHighPt = inPolygon[q]; + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; + if (Math.abs(edgeDy) > Number.EPSILON) { + if (edgeDy < 0) { + edgeLowPt = inPolygon[q]; + edgeDx = -edgeDx; + edgeHighPt = inPolygon[p]; + edgeDy = -edgeDy; + } + if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) + continue; + if (inPt.y === edgeLowPt.y) { + if (inPt.x === edgeLowPt.x) + return true; + } else { + const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); + if (perpEdge === 0) + return true; + if (perpEdge < 0) + continue; + inside = !inside; + } + } else { + if (inPt.y !== edgeLowPt.y) + continue; + if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) + return true; + } + } + return inside; + } + const isClockWise = ShapeUtils.isClockWise; + const subPaths = this.subPaths; + if (subPaths.length === 0) + return []; + let solid, tmpPath, tmpShape; + const shapes = []; + if (subPaths.length === 1) { + tmpPath = subPaths[0]; + tmpShape = new Shape; + tmpShape.curves = tmpPath.curves; + shapes.push(tmpShape); + return shapes; + } + let holesFirst = !isClockWise(subPaths[0].getPoints()); + holesFirst = isCCW ? !holesFirst : holesFirst; + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; + newShapes[mainIdx] = undefined; + newShapeHoles[mainIdx] = []; + for (let i = 0, l = subPaths.length;i < l; i++) { + tmpPath = subPaths[i]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise(tmpPoints); + solid = isCCW ? !solid : solid; + if (solid) { + if (!holesFirst && newShapes[mainIdx]) + mainIdx++; + newShapes[mainIdx] = { s: new Shape, p: tmpPoints }; + newShapes[mainIdx].s.curves = tmpPath.curves; + if (holesFirst) + mainIdx++; + newShapeHoles[mainIdx] = []; + } else { + newShapeHoles[mainIdx].push({ h: tmpPath, p: tmpPoints[0] }); + } + } + if (!newShapes[0]) + return toShapesNoHoles(subPaths); + if (newShapes.length > 1) { + let ambiguous = false; + let toChange = 0; + for (let sIdx = 0, sLen = newShapes.length;sIdx < sLen; sIdx++) { + betterShapeHoles[sIdx] = []; + } + for (let sIdx = 0, sLen = newShapes.length;sIdx < sLen; sIdx++) { + const sho = newShapeHoles[sIdx]; + for (let hIdx = 0;hIdx < sho.length; hIdx++) { + const ho = sho[hIdx]; + let hole_unassigned = true; + for (let s2Idx = 0;s2Idx < newShapes.length; s2Idx++) { + if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) { + if (sIdx !== s2Idx) + toChange++; + if (hole_unassigned) { + hole_unassigned = false; + betterShapeHoles[s2Idx].push(ho); + } else { + ambiguous = true; + } + } + } + if (hole_unassigned) { + betterShapeHoles[sIdx].push(ho); + } + } + } + if (toChange > 0 && ambiguous === false) { + newShapeHoles = betterShapeHoles; + } + } + let tmpHoles; + for (let i = 0, il = newShapes.length;i < il; i++) { + tmpShape = newShapes[i].s; + shapes.push(tmpShape); + tmpHoles = newShapeHoles[i]; + for (let j = 0, jl = tmpHoles.length;j < jl; j++) { + tmpShape.holes.push(tmpHoles[j].h); + } + } + return shapes; + } +} + +class Controls extends EventDispatcher { + constructor(object, domElement = null) { + super(); + this.object = object; + this.domElement = domElement; + this.enabled = true; + this.state = -1; + this.keys = {}; + this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null }; + this.touches = { ONE: null, TWO: null }; + } + connect() { + } + disconnect() { + } + dispose() { + } + update() { + } +} +function contain(texture, aspect2) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect2) { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect2; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } else { + texture.repeat.x = aspect2 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } + return texture; +} +function cover(texture, aspect2) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect2) { + texture.repeat.x = aspect2 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } else { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect2; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } + return texture; +} +function fill(texture) { + texture.repeat.x = 1; + texture.repeat.y = 1; + texture.offset.x = 0; + texture.offset.y = 0; + return texture; +} +function getByteLength(width2, height2, format, type) { + const typeByteLength = getTextureTypeByteLength(type); + switch (format) { + case AlphaFormat: + return width2 * height2; + case LuminanceFormat: + return width2 * height2; + case LuminanceAlphaFormat: + return width2 * height2 * 2; + case RedFormat: + return width2 * height2 / typeByteLength.components * typeByteLength.byteLength; + case RedIntegerFormat: + return width2 * height2 / typeByteLength.components * typeByteLength.byteLength; + case RGFormat: + return width2 * height2 * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGIntegerFormat: + return width2 * height2 * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGBFormat: + return width2 * height2 * 3 / typeByteLength.components * typeByteLength.byteLength; + case RGBAFormat: + return width2 * height2 * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGBAIntegerFormat: + return width2 * height2 * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGB_S3TC_DXT1_Format: + case RGBA_S3TC_DXT1_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 8; + case RGBA_S3TC_DXT3_Format: + case RGBA_S3TC_DXT5_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGB_PVRTC_2BPPV1_Format: + case RGBA_PVRTC_2BPPV1_Format: + return Math.max(width2, 16) * Math.max(height2, 8) / 4; + case RGB_PVRTC_4BPPV1_Format: + case RGBA_PVRTC_4BPPV1_Format: + return Math.max(width2, 8) * Math.max(height2, 8) / 2; + case RGB_ETC1_Format: + case RGB_ETC2_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 8; + case RGBA_ETC2_EAC_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_4x4_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_5x4_Format: + return Math.floor((width2 + 4) / 5) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_5x5_Format: + return Math.floor((width2 + 4) / 5) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_6x5_Format: + return Math.floor((width2 + 5) / 6) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_6x6_Format: + return Math.floor((width2 + 5) / 6) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_8x5_Format: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_8x6_Format: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_8x8_Format: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 7) / 8) * 16; + case RGBA_ASTC_10x5_Format: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_10x6_Format: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_10x8_Format: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 7) / 8) * 16; + case RGBA_ASTC_10x10_Format: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 9) / 10) * 16; + case RGBA_ASTC_12x10_Format: + return Math.floor((width2 + 11) / 12) * Math.floor((height2 + 9) / 10) * 16; + case RGBA_ASTC_12x12_Format: + return Math.floor((width2 + 11) / 12) * Math.floor((height2 + 11) / 12) * 16; + case RGBA_BPTC_Format: + case RGB_BPTC_SIGNED_Format: + case RGB_BPTC_UNSIGNED_Format: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 16; + case RED_RGTC1_Format: + case SIGNED_RED_RGTC1_Format: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 8; + case RED_GREEN_RGTC2_Format: + case SIGNED_RED_GREEN_RGTC2_Format: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 16; + } + throw new Error(`Unable to determine texture byte length for ${format} format.`); +} +function getTextureTypeByteLength(type) { + switch (type) { + case UnsignedByteType: + case ByteType: + return { byteLength: 1, components: 1 }; + case UnsignedShortType: + case ShortType: + case HalfFloatType: + return { byteLength: 2, components: 1 }; + case UnsignedShort4444Type: + case UnsignedShort5551Type: + return { byteLength: 2, components: 4 }; + case UnsignedIntType: + case IntType: + case FloatType: + return { byteLength: 4, components: 1 }; + case UnsignedInt5999Type: + return { byteLength: 4, components: 3 }; + } + throw new Error(`Unknown texture type ${type}.`); +} +var TextureUtils = { + contain, + cover, + fill, + getByteLength +}; +if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { + revision: REVISION + } })); +} +if (typeof window !== "undefined") { + if (window.__THREE__) { + console.warn("WARNING: Multiple instances of Three.js being imported."); + } else { + window.__THREE__ = REVISION; + } +} + +// node_modules/three/build/three.module.js +function WebGLAnimation() { + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + function onAnimationFrame(time2, frame) { + animationLoop(time2, frame); + requestId = context.requestAnimationFrame(onAnimationFrame); + } + return { + start: function() { + if (isAnimating === true) + return; + if (animationLoop === null) + return; + requestId = context.requestAnimationFrame(onAnimationFrame); + isAnimating = true; + }, + stop: function() { + context.cancelAnimationFrame(requestId); + isAnimating = false; + }, + setAnimationLoop: function(callback) { + animationLoop = callback; + }, + setContext: function(value2) { + context = value2; + } + }; +} +function WebGLAttributes(gl) { + const buffers = new WeakMap; + function createBuffer(attribute, bufferType) { + const array = attribute.array; + const usage = attribute.usage; + const size = array.byteLength; + const buffer = gl.createBuffer(); + gl.bindBuffer(bufferType, buffer); + gl.bufferData(bufferType, array, usage); + attribute.onUploadCallback(); + let type; + if (array instanceof Float32Array) { + type = gl.FLOAT; + } else if (array instanceof Uint16Array) { + if (attribute.isFloat16BufferAttribute) { + type = gl.HALF_FLOAT; + } else { + type = gl.UNSIGNED_SHORT; + } + } else if (array instanceof Int16Array) { + type = gl.SHORT; + } else if (array instanceof Uint32Array) { + type = gl.UNSIGNED_INT; + } else if (array instanceof Int32Array) { + type = gl.INT; + } else if (array instanceof Int8Array) { + type = gl.BYTE; + } else if (array instanceof Uint8Array) { + type = gl.UNSIGNED_BYTE; + } else if (array instanceof Uint8ClampedArray) { + type = gl.UNSIGNED_BYTE; + } else { + throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + array); + } + return { + buffer, + type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version, + size + }; + } + function updateBuffer(buffer, attribute, bufferType) { + const array = attribute.array; + const updateRanges = attribute.updateRanges; + gl.bindBuffer(bufferType, buffer); + if (updateRanges.length === 0) { + gl.bufferSubData(bufferType, 0, array); + } else { + updateRanges.sort((a, b) => a.start - b.start); + let mergeIndex = 0; + for (let i = 1;i < updateRanges.length; i++) { + const previousRange = updateRanges[mergeIndex]; + const range = updateRanges[i]; + if (range.start <= previousRange.start + previousRange.count + 1) { + previousRange.count = Math.max(previousRange.count, range.start + range.count - previousRange.start); + } else { + ++mergeIndex; + updateRanges[mergeIndex] = range; + } + } + updateRanges.length = mergeIndex + 1; + for (let i = 0, l = updateRanges.length;i < l; i++) { + const range = updateRanges[i]; + gl.bufferSubData(bufferType, range.start * array.BYTES_PER_ELEMENT, array, range.start, range.count); + } + attribute.clearUpdateRanges(); + } + attribute.onUploadCallback(); + } + function get(attribute) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + return buffers.get(attribute); + } + function remove(attribute) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + const data2 = buffers.get(attribute); + if (data2) { + gl.deleteBuffer(data2.buffer); + buffers.delete(attribute); + } + } + function update(attribute, bufferType) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + if (attribute.isGLBufferAttribute) { + const cached = buffers.get(attribute); + if (!cached || cached.version < attribute.version) { + buffers.set(attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + }); + } + return; + } + const data2 = buffers.get(attribute); + if (data2 === undefined) { + buffers.set(attribute, createBuffer(attribute, bufferType)); + } else if (data2.version < attribute.version) { + if (data2.size !== attribute.array.byteLength) { + throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported."); + } + updateBuffer(data2.buffer, attribute, bufferType); + data2.version = attribute.version; + } + } + return { + get, + remove, + update + }; +} +var alphahash_fragment = `#ifdef USE_ALPHAHASH + if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard; +#endif`; +var alphahash_pars_fragment = `#ifdef USE_ALPHAHASH + const float ALPHA_HASH_SCALE = 0.05; + float hash2D( vec2 value ) { + return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) ); + } + float hash3D( vec3 value ) { + return hash2D( vec2( hash2D( value.xy ), value.z ) ); + } + float getAlphaHashThreshold( vec3 position ) { + float maxDeriv = max( + length( dFdx( position.xyz ) ), + length( dFdy( position.xyz ) ) + ); + float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv ); + vec2 pixScales = vec2( + exp2( floor( log2( pixScale ) ) ), + exp2( ceil( log2( pixScale ) ) ) + ); + vec2 alpha = vec2( + hash3D( floor( pixScales.x * position.xyz ) ), + hash3D( floor( pixScales.y * position.xyz ) ) + ); + float lerpFactor = fract( log2( pixScale ) ); + float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y; + float a = min( lerpFactor, 1.0 - lerpFactor ); + vec3 cases = vec3( + x * x / ( 2.0 * a * ( 1.0 - a ) ), + ( x - 0.5 * a ) / ( 1.0 - a ), + 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) ) + ); + float threshold = ( x < ( 1.0 - a ) ) + ? ( ( x < a ) ? cases.x : cases.y ) + : cases.z; + return clamp( threshold , 1.0e-6, 1.0 ); + } +#endif`; +var alphamap_fragment = `#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g; +#endif`; +var alphamap_pars_fragment = `#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`; +var alphatest_fragment = `#ifdef USE_ALPHATEST + #ifdef ALPHA_TO_COVERAGE + diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a ); + if ( diffuseColor.a == 0.0 ) discard; + #else + if ( diffuseColor.a < alphaTest ) discard; + #endif +#endif`; +var alphatest_pars_fragment = `#ifdef USE_ALPHATEST + uniform float alphaTest; +#endif`; +var aomap_fragment = `#ifdef USE_AOMAP + float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0; + reflectedLight.indirectDiffuse *= ambientOcclusion; + #if defined( USE_CLEARCOAT ) + clearcoatSpecularIndirect *= ambientOcclusion; + #endif + #if defined( USE_SHEEN ) + sheenSpecularIndirect *= ambientOcclusion; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) + float dotNV = saturate( dot( geometryNormal, geometryViewDir ) ); + reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness ); + #endif +#endif`; +var aomap_pars_fragment = `#ifdef USE_AOMAP + uniform sampler2D aoMap; + uniform float aoMapIntensity; +#endif`; +var batching_pars_vertex = `#ifdef USE_BATCHING + #if ! defined( GL_ANGLE_multi_draw ) + #define gl_DrawID _gl_DrawID + uniform int _gl_DrawID; + #endif + uniform highp sampler2D batchingTexture; + uniform highp usampler2D batchingIdTexture; + mat4 getBatchingMatrix( const in float i ) { + int size = textureSize( batchingTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } + float getIndirectIndex( const in int i ) { + int size = textureSize( batchingIdTexture, 0 ).x; + int x = i % size; + int y = i / size; + return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r ); + } +#endif +#ifdef USE_BATCHING_COLOR + uniform sampler2D batchingColorTexture; + vec3 getBatchingColor( const in float i ) { + int size = textureSize( batchingColorTexture, 0 ).x; + int j = int( i ); + int x = j % size; + int y = j / size; + return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb; + } +#endif`; +var batching_vertex = `#ifdef USE_BATCHING + mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) ); +#endif`; +var begin_vertex = `vec3 transformed = vec3( position ); +#ifdef USE_ALPHAHASH + vPosition = vec3( position ); +#endif`; +var beginnormal_vertex = `vec3 objectNormal = vec3( normal ); +#ifdef USE_TANGENT + vec3 objectTangent = vec3( tangent.xyz ); +#endif`; +var bsdfs = `float G_BlinnPhong_Implicit( ) { + return 0.25; +} +float D_BlinnPhong( const in float shininess, const in float dotNH ) { + return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess ); +} +vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( specularColor, 1.0, dotVH ); + float G = G_BlinnPhong_Implicit( ); + float D = D_BlinnPhong( shininess, dotNH ); + return F * ( G * D ); +} // validated`; +var iridescence_fragment = `#ifdef USE_IRIDESCENCE + const mat3 XYZ_TO_REC709 = mat3( + 3.2404542, -0.9692660, 0.0556434, + -1.5371385, 1.8760108, -0.2040259, + -0.4985314, 0.0415560, 1.0572252 + ); + vec3 Fresnel0ToIor( vec3 fresnel0 ) { + vec3 sqrtF0 = sqrt( fresnel0 ); + return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 ); + } + vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) { + return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) ); + } + float IorToFresnel0( float transmittedIor, float incidentIor ) { + return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor )); + } + vec3 evalSensitivity( float OPD, vec3 shift ) { + float phase = 2.0 * PI * OPD * 1.0e-9; + vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 ); + vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 ); + vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 ); + vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var ); + xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) ); + xyz /= 1.0685e-7; + vec3 rgb = XYZ_TO_REC709 * xyz; + return rgb; + } + vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) { + vec3 I; + float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) ); + float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) ); + float cosTheta2Sq = 1.0 - sinTheta2Sq; + if ( cosTheta2Sq < 0.0 ) { + return vec3( 1.0 ); + } + float cosTheta2 = sqrt( cosTheta2Sq ); + float R0 = IorToFresnel0( iridescenceIOR, outsideIOR ); + float R12 = F_Schlick( R0, 1.0, cosTheta1 ); + float T121 = 1.0 - R12; + float phi12 = 0.0; + if ( iridescenceIOR < outsideIOR ) phi12 = PI; + float phi21 = PI - phi12; + vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR ); + vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 ); + vec3 phi23 = vec3( 0.0 ); + if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI; + if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI; + if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI; + float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2; + vec3 phi = vec3( phi21 ) + phi23; + vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 ); + vec3 r123 = sqrt( R123 ); + vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 ); + vec3 C0 = R12 + Rs; + I = C0; + vec3 Cm = Rs - T121; + for ( int m = 1; m <= 2; ++ m ) { + Cm *= r123; + vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi ); + I += Cm * Sm; + } + return max( I, vec3( 0.0 ) ); + } +#endif`; +var bumpmap_pars_fragment = `#ifdef USE_BUMPMAP + uniform sampler2D bumpMap; + uniform float bumpScale; + vec2 dHdxy_fwd() { + vec2 dSTdx = dFdx( vBumpMapUv ); + vec2 dSTdy = dFdy( vBumpMapUv ); + float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x; + float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll; + float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll; + return vec2( dBx, dBy ); + } + vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) { + vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) ); + vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) ); + vec3 vN = surf_norm; + vec3 R1 = cross( vSigmaY, vN ); + vec3 R2 = cross( vN, vSigmaX ); + float fDet = dot( vSigmaX, R1 ) * faceDirection; + vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 ); + return normalize( abs( fDet ) * surf_norm - vGrad ); + } +#endif`; +var clipping_planes_fragment = `#if NUM_CLIPPING_PLANES > 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`; +var clipping_planes_pars_fragment = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`; +var clipping_planes_pars_vertex = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`; +var clipping_planes_vertex = `#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`; +var color_fragment = `#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`; +var color_pars_fragment = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`; +var color_pars_vertex = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`; +var color_vertex = `#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`; +var common = `#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`; +var cube_uv_reflection_fragment = `#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`; +var defaultnormal_vertex = `vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`; +var displacementmap_pars_vertex = `#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`; +var displacementmap_vertex = `#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`; +var emissivemap_fragment = `#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`; +var emissivemap_pars_fragment = `#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`; +var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; +var colorspace_pars_fragment = `vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`; +var envmap_fragment = `#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`; +var envmap_common_pars_fragment = `#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`; +var envmap_pars_fragment = `#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`; +var envmap_pars_vertex = `#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`; +var envmap_vertex = `#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`; +var fog_vertex = `#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`; +var fog_pars_vertex = `#ifdef USE_FOG + varying float vFogDepth; +#endif`; +var fog_fragment = `#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`; +var fog_pars_fragment = `#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`; +var gradientmap_pars_fragment = `#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`; +var lightmap_pars_fragment = `#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`; +var lights_lambert_fragment = `LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`; +var lights_lambert_pars_fragment = `varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`; +var lights_pars_begin = `uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`; +var envmap_physical_pars_fragment = `#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`; +var lights_toon_fragment = `ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`; +var lights_toon_pars_fragment = `varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`; +var lights_phong_fragment = `BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`; +var lights_phong_pars_fragment = `varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`; +var lights_physical_fragment = `PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`; +var lights_physical_pars_fragment = `struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`; +var lights_fragment_begin = ` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`; +var lights_fragment_maps = `#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`; +var lights_fragment_end = `#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`; +var logdepthbuf_fragment = `#if defined( USE_LOGDEPTHBUF ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`; +var logdepthbuf_pars_fragment = `#if defined( USE_LOGDEPTHBUF ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`; +var logdepthbuf_pars_vertex = `#ifdef USE_LOGDEPTHBUF + varying float vFragDepth; + varying float vIsPerspective; +#endif`; +var logdepthbuf_vertex = `#ifdef USE_LOGDEPTHBUF + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`; +var map_fragment = `#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`; +var map_pars_fragment = `#ifdef USE_MAP + uniform sampler2D map; +#endif`; +var map_particle_fragment = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`; +var map_particle_pars_fragment = `#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`; +var metalnessmap_fragment = `float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`; +var metalnessmap_pars_fragment = `#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`; +var morphinstance_vertex = `#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`; +var morphcolor_vertex = `#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`; +var morphnormal_vertex = `#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`; +var morphtarget_pars_vertex = `#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`; +var morphtarget_vertex = `#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`; +var normal_fragment_begin = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`; +var normal_fragment_maps = `#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`; +var normal_pars_fragment = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`; +var normal_pars_vertex = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`; +var normal_vertex = `#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`; +var normalmap_pars_fragment = `#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`; +var clearcoat_normal_fragment_begin = `#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`; +var clearcoat_normal_fragment_maps = `#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`; +var clearcoat_pars_fragment = `#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`; +var iridescence_pars_fragment = `#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`; +var opaque_fragment = `#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`; +var packing = `vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`; +var premultiplied_alpha_fragment = `#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`; +var project_vertex = `vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`; +var dithering_fragment = `#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`; +var dithering_pars_fragment = `#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`; +var roughnessmap_fragment = `float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`; +var roughnessmap_pars_fragment = `#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`; +var shadowmap_pars_fragment = `#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`; +var shadowmap_pars_vertex = `#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`; +var shadowmap_vertex = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`; +var shadowmask_pars_fragment = `float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`; +var skinbase_vertex = `#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`; +var skinning_pars_vertex = `#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`; +var skinning_vertex = `#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`; +var skinnormal_vertex = `#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`; +var specularmap_fragment = `float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`; +var specularmap_pars_fragment = `#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`; +var tonemapping_fragment = `#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`; +var tonemapping_pars_fragment = `#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`; +var transmission_fragment = `#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`; +var transmission_pars_fragment = `#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`; +var uv_pars_fragment = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`; +var uv_pars_vertex = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`; +var uv_vertex = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`; +var worldpos_vertex = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`; +var vertex$h = `varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`; +var fragment$h = `uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`; +var vertex$g = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`; +var fragment$g = `#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`; +var vertex$f = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`; +var fragment$f = `uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`; +var vertex$e = `#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`; +var fragment$e = `#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`; +var vertex$d = `#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`; +var fragment$d = `#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`; +var vertex$c = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`; +var fragment$c = `uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`; +var vertex$b = `uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; +var fragment$b = `uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`; +var vertex$a = `#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; +var fragment$a = `uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`; +var vertex$9 = `#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`; +var fragment$9 = `#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`; +var vertex$8 = `#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`; +var fragment$8 = `#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`; +var vertex$7 = `#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`; +var fragment$7 = `#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`; +var vertex$6 = `#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`; +var fragment$6 = `#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`; +var vertex$5 = `#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`; +var fragment$5 = `#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`; +var vertex$4 = `#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`; +var fragment$4 = `#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`; +var vertex$3 = `uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`; +var fragment$3 = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`; +var vertex$2 = `#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; +var fragment$2 = `uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`; +var vertex$1 = `uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`; +var fragment$1 = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`; +var ShaderChunk = { + alphahash_fragment, + alphahash_pars_fragment, + alphamap_fragment, + alphamap_pars_fragment, + alphatest_fragment, + alphatest_pars_fragment, + aomap_fragment, + aomap_pars_fragment, + batching_pars_vertex, + batching_vertex, + begin_vertex, + beginnormal_vertex, + bsdfs, + iridescence_fragment, + bumpmap_pars_fragment, + clipping_planes_fragment, + clipping_planes_pars_fragment, + clipping_planes_pars_vertex, + clipping_planes_vertex, + color_fragment, + color_pars_fragment, + color_pars_vertex, + color_vertex, + common, + cube_uv_reflection_fragment, + defaultnormal_vertex, + displacementmap_pars_vertex, + displacementmap_vertex, + emissivemap_fragment, + emissivemap_pars_fragment, + colorspace_fragment, + colorspace_pars_fragment, + envmap_fragment, + envmap_common_pars_fragment, + envmap_pars_fragment, + envmap_pars_vertex, + envmap_physical_pars_fragment, + envmap_vertex, + fog_vertex, + fog_pars_vertex, + fog_fragment, + fog_pars_fragment, + gradientmap_pars_fragment, + lightmap_pars_fragment, + lights_lambert_fragment, + lights_lambert_pars_fragment, + lights_pars_begin, + lights_toon_fragment, + lights_toon_pars_fragment, + lights_phong_fragment, + lights_phong_pars_fragment, + lights_physical_fragment, + lights_physical_pars_fragment, + lights_fragment_begin, + lights_fragment_maps, + lights_fragment_end, + logdepthbuf_fragment, + logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex, + logdepthbuf_vertex, + map_fragment, + map_pars_fragment, + map_particle_fragment, + map_particle_pars_fragment, + metalnessmap_fragment, + metalnessmap_pars_fragment, + morphinstance_vertex, + morphcolor_vertex, + morphnormal_vertex, + morphtarget_pars_vertex, + morphtarget_vertex, + normal_fragment_begin, + normal_fragment_maps, + normal_pars_fragment, + normal_pars_vertex, + normal_vertex, + normalmap_pars_fragment, + clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps, + clearcoat_pars_fragment, + iridescence_pars_fragment, + opaque_fragment, + packing, + premultiplied_alpha_fragment, + project_vertex, + dithering_fragment, + dithering_pars_fragment, + roughnessmap_fragment, + roughnessmap_pars_fragment, + shadowmap_pars_fragment, + shadowmap_pars_vertex, + shadowmap_vertex, + shadowmask_pars_fragment, + skinbase_vertex, + skinning_pars_vertex, + skinning_vertex, + skinnormal_vertex, + specularmap_fragment, + specularmap_pars_fragment, + tonemapping_fragment, + tonemapping_pars_fragment, + transmission_fragment, + transmission_pars_fragment, + uv_pars_fragment, + uv_pars_vertex, + uv_vertex, + worldpos_vertex, + background_vert: vertex$h, + background_frag: fragment$h, + backgroundCube_vert: vertex$g, + backgroundCube_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distanceRGBA_vert: vertex$d, + distanceRGBA_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 +}; +var UniformsLib = { + common: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaTest: { value: 0 } + }, + specularmap: { + specularMap: { value: null }, + specularMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + envmap: { + envMap: { value: null }, + envMapRotation: { value: /* @__PURE__ */ new Matrix3 }, + flipEnvMap: { value: -1 }, + reflectivity: { value: 1 }, + ior: { value: 1.5 }, + refractionRatio: { value: 0.98 } + }, + aomap: { + aoMap: { value: null }, + aoMapIntensity: { value: 1 }, + aoMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + lightmap: { + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + bumpmap: { + bumpMap: { value: null }, + bumpMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + bumpScale: { value: 1 } + }, + normalmap: { + normalMap: { value: null }, + normalMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + normalScale: { value: /* @__PURE__ */ new Vector2(1, 1) } + }, + displacementmap: { + displacementMap: { value: null }, + displacementMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + }, + emissivemap: { + emissiveMap: { value: null }, + emissiveMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + metalnessmap: { + metalnessMap: { value: null }, + metalnessMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + roughnessmap: { + roughnessMap: { value: null }, + roughnessMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + gradientmap: { + gradientMap: { value: null } + }, + fog: { + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: /* @__PURE__ */ new Color(16777215) } + }, + lights: { + ambientLightColor: { value: [] }, + lightProbe: { value: [] }, + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + directionalLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + spotLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + pointLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + ltc_1: { value: null }, + ltc_2: { value: null } + }, + points: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + size: { value: 1 }, + scale: { value: 1 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaTest: { value: 0 }, + uvTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + sprite: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + center: { value: /* @__PURE__ */ new Vector2(0.5, 0.5) }, + rotation: { value: 0 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaTest: { value: 0 } + } +}; +var ShaderLib = { + basic: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag + }, + lambert: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) } + } + ]), + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + }, + phong: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + specular: { value: /* @__PURE__ */ new Color(1118481) }, + shininess: { value: 30 } + } + ]), + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag + }, + standard: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + roughness: { value: 1 }, + metalness: { value: 0 }, + envMapIntensity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + }, + toon: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) } + } + ]), + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag + }, + matcap: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ]), + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag + }, + points: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.points, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag + }, + dashed: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ]), + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag + }, + depth: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.displacementmap + ]), + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag + }, + normal: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag + }, + sprite: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.sprite, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag + }, + background: { + uniforms: { + uvTransform: { value: /* @__PURE__ */ new Matrix3 }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag + }, + backgroundCube: { + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /* @__PURE__ */ new Matrix3 } + }, + vertexShader: ShaderChunk.backgroundCube_vert, + fragmentShader: ShaderChunk.backgroundCube_frag + }, + cube: { + uniforms: { + tCube: { value: null }, + tFlip: { value: -1 }, + opacity: { value: 1 } + }, + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag + }, + equirect: { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag + }, + distanceRGBA: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: /* @__PURE__ */ new Vector3 }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ]), + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag + }, + shadow: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: /* @__PURE__ */ new Color(0) }, + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag + } +}; +ShaderLib.physical = { + uniforms: /* @__PURE__ */ mergeUniforms([ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + clearcoatNormalScale: { value: /* @__PURE__ */ new Vector2(1, 1) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + dispersion: { value: 0 }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + sheen: { value: 0 }, + sheenColor: { value: /* @__PURE__ */ new Color(0) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + transmissionSamplerSize: { value: /* @__PURE__ */ new Vector2 }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /* @__PURE__ */ new Color(0) }, + specularColor: { value: /* @__PURE__ */ new Color(1, 1, 1) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + anisotropyVector: { value: /* @__PURE__ */ new Vector2 }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /* @__PURE__ */ new Matrix3 } + } + ]), + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag +}; +var _rgb = { r: 0, b: 0, g: 0 }; +var _e1$1 = /* @__PURE__ */ new Euler; +var _m1$12 = /* @__PURE__ */ new Matrix4; +function WebGLBackground(renderer2, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) { + const clearColor = new Color(0); + let clearAlpha = alpha === true ? 0 : 1; + let planeMesh; + let boxMesh; + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + function getBackground(scene) { + let background = scene.isScene === true ? scene.background : null; + if (background && background.isTexture) { + const usePMREM = scene.backgroundBlurriness > 0; + background = (usePMREM ? cubeuvmaps : cubemaps).get(background); + } + return background; + } + function render(scene) { + let forceClear = false; + const background = getBackground(scene); + if (background === null) { + setClear(clearColor, clearAlpha); + } else if (background && background.isColor) { + setClear(background, 1); + forceClear = true; + } + const environmentBlendMode = renderer2.xr.getEnvironmentBlendMode(); + if (environmentBlendMode === "additive") { + state.buffers.color.setClear(0, 0, 0, 1, premultipliedAlpha); + } else if (environmentBlendMode === "alpha-blend") { + state.buffers.color.setClear(0, 0, 0, 0, premultipliedAlpha); + } + if (renderer2.autoClear || forceClear) { + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + renderer2.clear(renderer2.autoClearColor, renderer2.autoClearDepth, renderer2.autoClearStencil); + } + } + function addToRenderList(renderList, scene) { + const background = getBackground(scene); + if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) { + if (boxMesh === undefined) { + boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({ + name: "BackgroundCubeMaterial", + uniforms: cloneUniforms(ShaderLib.backgroundCube.uniforms), + vertexShader: ShaderLib.backgroundCube.vertexShader, + fragmentShader: ShaderLib.backgroundCube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false + })); + boxMesh.geometry.deleteAttribute("normal"); + boxMesh.geometry.deleteAttribute("uv"); + boxMesh.onBeforeRender = function(renderer3, scene2, camera) { + this.matrixWorld.copyPosition(camera.matrixWorld); + }; + Object.defineProperty(boxMesh.material, "envMap", { + get: function() { + return this.uniforms.envMap.value; + } + }); + objects.update(boxMesh); + } + _e1$1.copy(scene.backgroundRotation); + _e1$1.x *= -1; + _e1$1.y *= -1; + _e1$1.z *= -1; + if (background.isCubeTexture && background.isRenderTargetTexture === false) { + _e1$1.y *= -1; + _e1$1.z *= -1; + } + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4(_m1$12.makeRotationFromEuler(_e1$1)); + boxMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer; + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer2.toneMapping) { + boxMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer2.toneMapping; + } + boxMesh.layers.enableAll(); + renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null); + } else if (background && background.isTexture) { + if (planeMesh === undefined) { + planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({ + name: "BackgroundMaterial", + uniforms: cloneUniforms(ShaderLib.background.uniforms), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false + })); + planeMesh.geometry.deleteAttribute("normal"); + Object.defineProperty(planeMesh.material, "map", { + get: function() { + return this.uniforms.t2D.value; + } + }); + objects.update(planeMesh); + } + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer; + if (background.matrixAutoUpdate === true) { + background.updateMatrix(); + } + planeMesh.material.uniforms.uvTransform.value.copy(background.matrix); + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer2.toneMapping) { + planeMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer2.toneMapping; + } + planeMesh.layers.enableAll(); + renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null); + } + } + function setClear(color, alpha2) { + color.getRGB(_rgb, getUnlitUniformColorSpace(renderer2)); + state.buffers.color.setClear(_rgb.r, _rgb.g, _rgb.b, alpha2, premultipliedAlpha); + } + function dispose() { + if (boxMesh !== undefined) { + boxMesh.geometry.dispose(); + boxMesh.material.dispose(); + boxMesh = undefined; + } + if (planeMesh !== undefined) { + planeMesh.geometry.dispose(); + planeMesh.material.dispose(); + planeMesh = undefined; + } + } + return { + getClearColor: function() { + return clearColor; + }, + setClearColor: function(color, alpha2 = 1) { + clearColor.set(color); + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + getClearAlpha: function() { + return clearAlpha; + }, + setClearAlpha: function(alpha2) { + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + render, + addToRenderList, + dispose + }; +} +function WebGLBindingStates(gl, attributes) { + const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const bindingStates = {}; + const defaultState = createBindingState(null); + let currentState = defaultState; + let forceUpdate = false; + function setup(object, material, program, geometry, index2) { + let updateBuffers = false; + const state = getBindingState(geometry, program, material); + if (currentState !== state) { + currentState = state; + bindVertexArrayObject(currentState.object); + } + updateBuffers = needsUpdate(object, geometry, program, index2); + if (updateBuffers) + saveCache(object, geometry, program, index2); + if (index2 !== null) { + attributes.update(index2, gl.ELEMENT_ARRAY_BUFFER); + } + if (updateBuffers || forceUpdate) { + forceUpdate = false; + setupVertexAttributes(object, material, program, geometry); + if (index2 !== null) { + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index2).buffer); + } + } + } + function createVertexArrayObject() { + return gl.createVertexArray(); + } + function bindVertexArrayObject(vao) { + return gl.bindVertexArray(vao); + } + function deleteVertexArrayObject(vao) { + return gl.deleteVertexArray(vao); + } + function getBindingState(geometry, program, material) { + const wireframe = material.wireframe === true; + let programMap = bindingStates[geometry.id]; + if (programMap === undefined) { + programMap = {}; + bindingStates[geometry.id] = programMap; + } + let stateMap = programMap[program.id]; + if (stateMap === undefined) { + stateMap = {}; + programMap[program.id] = stateMap; + } + let state = stateMap[wireframe]; + if (state === undefined) { + state = createBindingState(createVertexArrayObject()); + stateMap[wireframe] = state; + } + return state; + } + function createBindingState(vao) { + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + for (let i = 0;i < maxVertexAttributes; i++) { + newAttributes[i] = 0; + enabledAttributes[i] = 0; + attributeDivisors[i] = 0; + } + return { + geometry: null, + program: null, + wireframe: false, + newAttributes, + enabledAttributes, + attributeDivisors, + object: vao, + attributes: {}, + index: null + }; + } + function needsUpdate(object, geometry, program, index2) { + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + const cachedAttribute = cachedAttributes[name2]; + let geometryAttribute = geometryAttributes[name2]; + if (geometryAttribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + geometryAttribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + geometryAttribute = object.instanceColor; + } + if (cachedAttribute === undefined) + return true; + if (cachedAttribute.attribute !== geometryAttribute) + return true; + if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) + return true; + attributesNum++; + } + } + if (currentState.attributesNum !== attributesNum) + return true; + if (currentState.index !== index2) + return true; + return false; + } + function saveCache(object, geometry, program, index2) { + const cache = {}; + const attributes2 = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + let attribute = attributes2[name2]; + if (attribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + attribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + attribute = object.instanceColor; + } + const data2 = {}; + data2.attribute = attribute; + if (attribute && attribute.data) { + data2.data = attribute.data; + } + cache[name2] = data2; + attributesNum++; + } + } + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + currentState.index = index2; + } + function initAttributes() { + const newAttributes = currentState.newAttributes; + for (let i = 0, il = newAttributes.length;i < il; i++) { + newAttributes[i] = 0; + } + } + function enableAttribute(attribute) { + enableAttributeAndDivisor(attribute, 0); + } + function enableAttributeAndDivisor(attribute, meshPerAttribute) { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + newAttributes[attribute] = 1; + if (enabledAttributes[attribute] === 0) { + gl.enableVertexAttribArray(attribute); + enabledAttributes[attribute] = 1; + } + if (attributeDivisors[attribute] !== meshPerAttribute) { + gl.vertexAttribDivisor(attribute, meshPerAttribute); + attributeDivisors[attribute] = meshPerAttribute; + } + } + function disableUnusedAttributes() { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + for (let i = 0, il = enabledAttributes.length;i < il; i++) { + if (enabledAttributes[i] !== newAttributes[i]) { + gl.disableVertexAttribArray(i); + enabledAttributes[i] = 0; + } + } + } + function vertexAttribPointer(index2, size, type, normalized, stride, offset, integer) { + if (integer === true) { + gl.vertexAttribIPointer(index2, size, type, stride, offset); + } else { + gl.vertexAttribPointer(index2, size, type, normalized, stride, offset); + } + } + function setupVertexAttributes(object, material, program, geometry) { + initAttributes(); + const geometryAttributes = geometry.attributes; + const programAttributes = program.getAttributes(); + const materialDefaultAttributeValues = material.defaultAttributeValues; + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + let geometryAttribute = geometryAttributes[name2]; + if (geometryAttribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + geometryAttribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + geometryAttribute = object.instanceColor; + } + if (geometryAttribute !== undefined) { + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + const attribute = attributes.get(geometryAttribute); + if (attribute === undefined) + continue; + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + const integer = type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType; + if (geometryAttribute.isInterleavedBufferAttribute) { + const data2 = geometryAttribute.data; + const stride = data2.stride; + const offset = geometryAttribute.offset; + if (data2.isInstancedInterleavedBuffer) { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, data2.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { + geometry._maxInstanceCount = data2.meshPerAttribute * data2.count; + } + } else { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0;i < programAttribute.locationSize; i++) { + vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement, integer); + } + } else { + if (geometryAttribute.isInstancedBufferAttribute) { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } + } else { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0;i < programAttribute.locationSize; i++) { + vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement, integer); + } + } + } else if (materialDefaultAttributeValues !== undefined) { + const value2 = materialDefaultAttributeValues[name2]; + if (value2 !== undefined) { + switch (value2.length) { + case 2: + gl.vertexAttrib2fv(programAttribute.location, value2); + break; + case 3: + gl.vertexAttrib3fv(programAttribute.location, value2); + break; + case 4: + gl.vertexAttrib4fv(programAttribute.location, value2); + break; + default: + gl.vertexAttrib1fv(programAttribute.location, value2); + } + } + } + } + } + disableUnusedAttributes(); + } + function dispose() { + reset(); + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometryId]; + } + } + function releaseStatesOfGeometry(geometry) { + if (bindingStates[geometry.id] === undefined) + return; + const programMap = bindingStates[geometry.id]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometry.id]; + } + function releaseStatesOfProgram(program) { + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + if (programMap[program.id] === undefined) + continue; + const stateMap = programMap[program.id]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[program.id]; + } + } + function reset() { + resetDefaultState(); + forceUpdate = true; + if (currentState === defaultState) + return; + currentState = defaultState; + bindVertexArrayObject(currentState.object); + } + function resetDefaultState() { + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + } + return { + setup, + reset, + resetDefaultState, + dispose, + releaseStatesOfGeometry, + releaseStatesOfProgram, + initAttributes, + enableAttribute, + disableUnusedAttributes + }; +} +function WebGLBufferRenderer(gl, extensions, info) { + let mode; + function setMode(value2) { + mode = value2; + } + function render(start, count) { + gl.drawArrays(mode, start, count); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) + return; + gl.drawArraysInstanced(mode, start, count, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawArraysWEBGL(mode, starts, 0, counts, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0;i < starts.length; i++) { + renderInstances(starts[i], counts[i], primcount[i]); + } + } else { + extension.multiDrawArraysInstancedWEBGL(mode, starts, 0, counts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i] * primcount[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; +} +function WebGLCapabilities(gl, extensions, parameters, utils) { + let maxAnisotropy; + function getMaxAnisotropy() { + if (maxAnisotropy !== undefined) + return maxAnisotropy; + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } else { + maxAnisotropy = 0; + } + return maxAnisotropy; + } + function textureFormatReadable(textureFormat) { + if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT)) { + return false; + } + return true; + } + function textureTypeReadable(textureType) { + const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float")); + if (textureType !== UnsignedByteType && utils.convert(textureType) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE) && textureType !== FloatType && !halfFloatSupportedByExt) { + return false; + } + return true; + } + function getMaxPrecision(precision2) { + if (precision2 === "highp") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) { + return "highp"; + } + precision2 = "mediump"; + } + if (precision2 === "mediump") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) { + return "mediump"; + } + } + return "lowp"; + } + let precision = parameters.precision !== undefined ? parameters.precision : "highp"; + const maxPrecision = getMaxPrecision(precision); + if (maxPrecision !== precision) { + console.warn("THREE.WebGLRenderer:", precision, "not supported, using", maxPrecision, "instead."); + precision = maxPrecision; + } + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has("EXT_clip_control"); + const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); + const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); + const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); + const vertexTextures = maxVertexTextures > 0; + const maxSamples = gl.getParameter(gl.MAX_SAMPLES); + return { + isWebGL2: true, + getMaxAnisotropy, + getMaxPrecision, + textureFormatReadable, + textureTypeReadable, + precision, + logarithmicDepthBuffer, + reverseDepthBuffer, + maxTextures, + maxVertexTextures, + maxTextureSize, + maxCubemapSize, + maxAttributes, + maxVertexUniforms, + maxVaryings, + maxFragmentUniforms, + vertexTextures, + maxSamples + }; +} +function WebGLClipping(properties) { + const scope = this; + let globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false; + const plane = new Plane, viewNormalMatrix = new Matrix3, uniform = { value: null, needsUpdate: false }; + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + this.init = function(planes, enableLocalClipping) { + const enabled = planes.length !== 0 || enableLocalClipping || numGlobalPlanes !== 0 || localClippingEnabled; + localClippingEnabled = enableLocalClipping; + numGlobalPlanes = planes.length; + return enabled; + }; + this.beginShadows = function() { + renderingShadows = true; + projectPlanes(null); + }; + this.endShadows = function() { + renderingShadows = false; + }; + this.setGlobalState = function(planes, camera) { + globalState = projectPlanes(planes, camera, 0); + }; + this.setState = function(material, camera, useCache) { + const { clippingPlanes: planes, clipIntersection, clipShadows } = material; + const materialProperties = properties.get(material); + if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) { + if (renderingShadows) { + projectPlanes(null); + } else { + resetGlobalState(); + } + } else { + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4; + let dstArray = materialProperties.clippingState || null; + uniform.value = dstArray; + dstArray = projectPlanes(planes, camera, lGlobal, useCache); + for (let i = 0;i !== lGlobal; ++i) { + dstArray[i] = globalState[i]; + } + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + } + }; + function resetGlobalState() { + if (uniform.value !== globalState) { + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + } + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + } + function projectPlanes(planes, camera, dstOffset, skipTransform) { + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + if (nPlanes !== 0) { + dstArray = uniform.value; + if (skipTransform !== true || dstArray === null) { + const flatSize = dstOffset + nPlanes * 4, viewMatrix = camera.matrixWorldInverse; + viewNormalMatrix.getNormalMatrix(viewMatrix); + if (dstArray === null || dstArray.length < flatSize) { + dstArray = new Float32Array(flatSize); + } + for (let i = 0, i4 = dstOffset;i !== nPlanes; ++i, i4 += 4) { + plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix); + plane.normal.toArray(dstArray, i4); + dstArray[i4 + 3] = plane.constant; + } + } + uniform.value = dstArray; + uniform.needsUpdate = true; + } + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + return dstArray; + } +} +function WebGLCubeMaps(renderer2) { + let cubemaps = new WeakMap; + function mapTextureMapping(texture, mapping) { + if (mapping === EquirectangularReflectionMapping) { + texture.mapping = CubeReflectionMapping; + } else if (mapping === EquirectangularRefractionMapping) { + texture.mapping = CubeRefractionMapping; + } + return texture; + } + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) { + if (cubemaps.has(texture)) { + const cubemap = cubemaps.get(texture).texture; + return mapTextureMapping(cubemap, texture.mapping); + } else { + const image = texture.image; + if (image && image.height > 0) { + const renderTarget = new WebGLCubeRenderTarget(image.height); + renderTarget.fromEquirectangularTexture(renderer2, texture); + cubemaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return mapTextureMapping(renderTarget.texture, texture.mapping); + } else { + return null; + } + } + } + } + return texture; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemap = cubemaps.get(texture); + if (cubemap !== undefined) { + cubemaps.delete(texture); + cubemap.dispose(); + } + } + function dispose() { + cubemaps = new WeakMap; + } + return { + get, + dispose + }; +} +var LOD_MIN = 4; +var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; +var MAX_SAMPLES = 20; +var _flatCamera = /* @__PURE__ */ new OrthographicCamera; +var _clearColor = /* @__PURE__ */ new Color; +var _oldTarget = null; +var _oldActiveCubeFace = 0; +var _oldActiveMipmapLevel = 0; +var _oldXrEnabled = false; +var PHI = (1 + Math.sqrt(5)) / 2; +var INV_PHI = 1 / PHI; +var _axisDirections = [ + /* @__PURE__ */ new Vector3(-PHI, INV_PHI, 0), + /* @__PURE__ */ new Vector3(PHI, INV_PHI, 0), + /* @__PURE__ */ new Vector3(-INV_PHI, 0, PHI), + /* @__PURE__ */ new Vector3(INV_PHI, 0, PHI), + /* @__PURE__ */ new Vector3(0, PHI, -INV_PHI), + /* @__PURE__ */ new Vector3(0, PHI, INV_PHI), + /* @__PURE__ */ new Vector3(-1, 1, -1), + /* @__PURE__ */ new Vector3(1, 1, -1), + /* @__PURE__ */ new Vector3(-1, 1, 1), + /* @__PURE__ */ new Vector3(1, 1, 1) +]; + +class PMREMGenerator { + constructor(renderer2) { + this._renderer = renderer2; + this._pingPongRenderTarget = null; + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + this._compileMaterial(this._blurMaterial); + } + fromScene(scene, sigma = 0, near = 0.1, far = 100) { + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + this._setSize(256); + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget); + if (sigma > 0) { + this._blur(cubeUVRenderTarget, 0, 0, sigma); + } + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + fromEquirectangular(equirectangular, renderTarget = null) { + return this._fromTexture(equirectangular, renderTarget); + } + fromCubemap(cubemap, renderTarget = null) { + return this._fromTexture(cubemap, renderTarget); + } + compileCubemapShader() { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial(this._cubemapMaterial); + } + } + compileEquirectangularShader() { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial(this._equirectMaterial); + } + } + dispose() { + this._dispose(); + if (this._cubemapMaterial !== null) + this._cubemapMaterial.dispose(); + if (this._equirectMaterial !== null) + this._equirectMaterial.dispose(); + } + _setSize(cubeSize) { + this._lodMax = Math.floor(Math.log2(cubeSize)); + this._cubeSize = Math.pow(2, this._lodMax); + } + _dispose() { + if (this._blurMaterial !== null) + this._blurMaterial.dispose(); + if (this._pingPongRenderTarget !== null) + this._pingPongRenderTarget.dispose(); + for (let i = 0;i < this._lodPlanes.length; i++) { + this._lodPlanes[i].dispose(); + } + } + _cleanup(outputTarget) { + this._renderer.setRenderTarget(_oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel); + this._renderer.xr.enabled = _oldXrEnabled; + outputTarget.scissorTest = false; + _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height); + } + _fromTexture(texture, renderTarget) { + if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) { + this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width); + } else { + this._setSize(texture.image.width / 4); + } + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV(texture, cubeUVRenderTarget); + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + _allocateTargets() { + const width2 = 3 * Math.max(this._cubeSize, 16 * 7); + const height2 = 4 * this._cubeSize; + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + colorSpace: LinearSRGBColorSpace, + depthBuffer: false + }; + const cubeUVRenderTarget = _createRenderTarget(width2, height2, params); + if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width2 || this._pingPongRenderTarget.height !== height2) { + if (this._pingPongRenderTarget !== null) { + this._dispose(); + } + this._pingPongRenderTarget = _createRenderTarget(width2, height2, params); + const { _lodMax } = this; + ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes(_lodMax)); + this._blurMaterial = _getBlurShader(_lodMax, width2, height2); + } + return cubeUVRenderTarget; + } + _compileMaterial(material) { + const tmpMesh = new Mesh(this._lodPlanes[0], material); + this._renderer.compile(tmpMesh, _flatCamera); + } + _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) { + const fov2 = 90; + const aspect2 = 1; + const cubeCamera = new PerspectiveCamera(fov2, aspect2, near, far); + const upSign = [1, -1, 1, 1, 1, 1]; + const forwardSign = [1, 1, 1, -1, -1, -1]; + const renderer2 = this._renderer; + const originalAutoClear = renderer2.autoClear; + const toneMapping = renderer2.toneMapping; + renderer2.getClearColor(_clearColor); + renderer2.toneMapping = NoToneMapping; + renderer2.autoClear = false; + const backgroundMaterial = new MeshBasicMaterial({ + name: "PMREM.Background", + side: BackSide, + depthWrite: false, + depthTest: false + }); + const backgroundBox = new Mesh(new BoxGeometry, backgroundMaterial); + let useSolidColor = false; + const background = scene.background; + if (background) { + if (background.isColor) { + backgroundMaterial.color.copy(background); + scene.background = null; + useSolidColor = true; + } + } else { + backgroundMaterial.color.copy(_clearColor); + useSolidColor = true; + } + for (let i = 0;i < 6; i++) { + const col = i % 3; + if (col === 0) { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(forwardSign[i], 0, 0); + } else if (col === 1) { + cubeCamera.up.set(0, 0, upSign[i]); + cubeCamera.lookAt(0, forwardSign[i], 0); + } else { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(0, 0, forwardSign[i]); + } + const size = this._cubeSize; + _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size); + renderer2.setRenderTarget(cubeUVRenderTarget); + if (useSolidColor) { + renderer2.render(backgroundBox, cubeCamera); + } + renderer2.render(scene, cubeCamera); + } + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + renderer2.toneMapping = toneMapping; + renderer2.autoClear = originalAutoClear; + scene.background = background; + } + _textureToCubeUV(texture, cubeUVRenderTarget) { + const renderer2 = this._renderer; + const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping; + if (isCubeTexture) { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial(); + } + this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1; + } else { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial(); + } + } + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh(this._lodPlanes[0], material); + const uniforms = material.uniforms; + uniforms["envMap"].value = texture; + const size = this._cubeSize; + _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size); + renderer2.setRenderTarget(cubeUVRenderTarget); + renderer2.render(mesh, _flatCamera); + } + _applyPMREM(cubeUVRenderTarget) { + const renderer2 = this._renderer; + const autoClear = renderer2.autoClear; + renderer2.autoClear = false; + const n = this._lodPlanes.length; + for (let i = 1;i < n; i++) { + const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]); + const poleAxis = _axisDirections[(n - i - 1) % _axisDirections.length]; + this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis); + } + renderer2.autoClear = autoClear; + } + _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) { + const pingPongRenderTarget = this._pingPongRenderTarget; + this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, "latitudinal", poleAxis); + this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, "longitudinal", poleAxis); + } + _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) { + const renderer2 = this._renderer; + const blurMaterial = this._blurMaterial; + if (direction !== "latitudinal" && direction !== "longitudinal") { + console.error("blur direction must be either latitudinal or longitudinal!"); + } + const STANDARD_DEVIATIONS = 3; + const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial); + const blurUniforms = blurMaterial.uniforms; + const pixels = this._sizeLods[lodIn] - 1; + const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES; + if (samples > MAX_SAMPLES) { + console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`); + } + const weights = []; + let sum2 = 0; + for (let i = 0;i < MAX_SAMPLES; ++i) { + const x2 = i / sigmaPixels; + const weight = Math.exp(-x2 * x2 / 2); + weights.push(weight); + if (i === 0) { + sum2 += weight; + } else if (i < samples) { + sum2 += 2 * weight; + } + } + for (let i = 0;i < weights.length; i++) { + weights[i] = weights[i] / sum2; + } + blurUniforms["envMap"].value = targetIn.texture; + blurUniforms["samples"].value = samples; + blurUniforms["weights"].value = weights; + blurUniforms["latitudinal"].value = direction === "latitudinal"; + if (poleAxis) { + blurUniforms["poleAxis"].value = poleAxis; + } + const { _lodMax } = this; + blurUniforms["dTheta"].value = radiansPerPixel; + blurUniforms["mipInt"].value = _lodMax - lodIn; + const outputSize = this._sizeLods[lodOut]; + const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0); + const y = 4 * (this._cubeSize - outputSize); + _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize); + renderer2.setRenderTarget(targetOut); + renderer2.render(blurMesh, _flatCamera); + } +} +function _createPlanes(lodMax) { + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + let lod = lodMax; + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + for (let i = 0;i < totalLods; i++) { + const sizeLod = Math.pow(2, lod); + sizeLods.push(sizeLod); + let sigma = 1 / sizeLod; + if (i > lodMax - LOD_MIN) { + sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1]; + } else if (i === 0) { + sigma = 0; + } + sigmas.push(sigma); + const texelSize = 1 / (sizeLod - 2); + const min = -texelSize; + const max = 1 + texelSize; + const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max]; + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + const position2 = new Float32Array(positionSize * vertices * cubeFaces); + const uv = new Float32Array(uvSize * vertices * cubeFaces); + const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces); + for (let face = 0;face < cubeFaces; face++) { + const x = face % 3 * 2 / 3 - 1; + const y = face > 2 ? 0 : -1; + const coordinates = [ + x, + y, + 0, + x + 2 / 3, + y, + 0, + x + 2 / 3, + y + 1, + 0, + x, + y, + 0, + x + 2 / 3, + y + 1, + 0, + x, + y + 1, + 0 + ]; + position2.set(coordinates, positionSize * vertices * face); + uv.set(uv1, uvSize * vertices * face); + const fill2 = [face, face, face, face, face, face]; + faceIndex.set(fill2, faceIndexSize * vertices * face); + } + const planes = new BufferGeometry; + planes.setAttribute("position", new BufferAttribute(position2, positionSize)); + planes.setAttribute("uv", new BufferAttribute(uv, uvSize)); + planes.setAttribute("faceIndex", new BufferAttribute(faceIndex, faceIndexSize)); + lodPlanes.push(planes); + if (lod > LOD_MIN) { + lod--; + } + } + return { lodPlanes, sizeLods, sigmas }; +} +function _createRenderTarget(width2, height2, params) { + const cubeUVRenderTarget = new WebGLRenderTarget(width2, height2, params); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = "PMREM.cubeUv"; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; +} +function _setViewport(target, x, y, width2, height2) { + target.viewport.set(x, y, width2, height2); + target.scissor.set(x, y, width2, height2); +} +function _getBlurShader(lodMax, width2, height2) { + const weights = new Float32Array(MAX_SAMPLES); + const poleAxis = new Vector3(0, 1, 0); + const shaderMaterial = new ShaderMaterial({ + name: "SphericalGaussianBlur", + defines: { + n: MAX_SAMPLES, + CUBEUV_TEXEL_WIDTH: 1 / width2, + CUBEUV_TEXEL_HEIGHT: 1 / height2, + CUBEUV_MAX_MIP: `${lodMax}.0` + }, + uniforms: { + envMap: { value: null }, + samples: { value: 1 }, + weights: { value: weights }, + latitudinal: { value: false }, + dTheta: { value: 0 }, + mipInt: { value: 0 }, + poleAxis: { value: poleAxis } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + return shaderMaterial; +} +function _getEquirectMaterial() { + return new ShaderMaterial({ + name: "EquirectangularToCubeUV", + uniforms: { + envMap: { value: null } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); +} +function _getCubemapMaterial() { + return new ShaderMaterial({ + name: "CubemapToCubeUV", + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); +} +function _getCommonVertexShader() { + return ` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `; +} +function WebGLCubeUVMaps(renderer2) { + let cubeUVmaps = new WeakMap; + let pmremGenerator = null; + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping; + const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; + if (isEquirectMap || isCubeMap) { + let renderTarget = cubeUVmaps.get(texture); + const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0; + if (texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion) { + if (pmremGenerator === null) + pmremGenerator = new PMREMGenerator(renderer2); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + return renderTarget.texture; + } else { + if (renderTarget !== undefined) { + return renderTarget.texture; + } else { + const image = texture.image; + if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) { + if (pmremGenerator === null) + pmremGenerator = new PMREMGenerator(renderer2); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return renderTarget.texture; + } else { + return null; + } + } + } + } + } + return texture; + } + function isCubeTextureComplete(image) { + let count = 0; + const length2 = 6; + for (let i = 0;i < length2; i++) { + if (image[i] !== undefined) + count++; + } + return count === length2; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemapUV = cubeUVmaps.get(texture); + if (cubemapUV !== undefined) { + cubeUVmaps.delete(texture); + cubemapUV.dispose(); + } + } + function dispose() { + cubeUVmaps = new WeakMap; + if (pmremGenerator !== null) { + pmremGenerator.dispose(); + pmremGenerator = null; + } + } + return { + get, + dispose + }; +} +function WebGLExtensions(gl) { + const extensions = {}; + function getExtension(name2) { + if (extensions[name2] !== undefined) { + return extensions[name2]; + } + let extension; + switch (name2) { + case "WEBGL_depth_texture": + extension = gl.getExtension("WEBGL_depth_texture") || gl.getExtension("MOZ_WEBGL_depth_texture") || gl.getExtension("WEBKIT_WEBGL_depth_texture"); + break; + case "EXT_texture_filter_anisotropic": + extension = gl.getExtension("EXT_texture_filter_anisotropic") || gl.getExtension("MOZ_EXT_texture_filter_anisotropic") || gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic"); + break; + case "WEBGL_compressed_texture_s3tc": + extension = gl.getExtension("WEBGL_compressed_texture_s3tc") || gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"); + break; + case "WEBGL_compressed_texture_pvrtc": + extension = gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"); + break; + default: + extension = gl.getExtension(name2); + } + extensions[name2] = extension; + return extension; + } + return { + has: function(name2) { + return getExtension(name2) !== null; + }, + init: function() { + getExtension("EXT_color_buffer_float"); + getExtension("WEBGL_clip_cull_distance"); + getExtension("OES_texture_float_linear"); + getExtension("EXT_color_buffer_half_float"); + getExtension("WEBGL_multisampled_render_to_texture"); + getExtension("WEBGL_render_shared_exponent"); + }, + get: function(name2) { + const extension = getExtension(name2); + if (extension === null) { + warnOnce("THREE.WebGLRenderer: " + name2 + " extension not supported."); + } + return extension; + } + }; +} +function WebGLGeometries(gl, attributes, info, bindingStates) { + const geometries = {}; + const wireframeAttributes = new WeakMap; + function onGeometryDispose(event) { + const geometry = event.target; + if (geometry.index !== null) { + attributes.remove(geometry.index); + } + for (const name2 in geometry.attributes) { + attributes.remove(geometry.attributes[name2]); + } + geometry.removeEventListener("dispose", onGeometryDispose); + delete geometries[geometry.id]; + const attribute = wireframeAttributes.get(geometry); + if (attribute) { + attributes.remove(attribute); + wireframeAttributes.delete(geometry); + } + bindingStates.releaseStatesOfGeometry(geometry); + if (geometry.isInstancedBufferGeometry === true) { + delete geometry._maxInstanceCount; + } + info.memory.geometries--; + } + function get(object, geometry) { + if (geometries[geometry.id] === true) + return geometry; + geometry.addEventListener("dispose", onGeometryDispose); + geometries[geometry.id] = true; + info.memory.geometries++; + return geometry; + } + function update(geometry) { + const geometryAttributes = geometry.attributes; + for (const name2 in geometryAttributes) { + attributes.update(geometryAttributes[name2], gl.ARRAY_BUFFER); + } + } + function updateWireframeAttribute(geometry) { + const indices = []; + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + if (geometryIndex !== null) { + const array = geometryIndex.array; + version = geometryIndex.version; + for (let i = 0, l = array.length;i < l; i += 3) { + const a = array[i + 0]; + const b = array[i + 1]; + const c = array[i + 2]; + indices.push(a, b, b, c, c, a); + } + } else if (geometryPosition !== undefined) { + const array = geometryPosition.array; + version = geometryPosition.version; + for (let i = 0, l = array.length / 3 - 1;i < l; i += 3) { + const a = i + 0; + const b = i + 1; + const c = i + 2; + indices.push(a, b, b, c, c, a); + } + } else { + return; + } + const attribute = new ((arrayNeedsUint32(indices)) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1); + attribute.version = version; + const previousAttribute = wireframeAttributes.get(geometry); + if (previousAttribute) + attributes.remove(previousAttribute); + wireframeAttributes.set(geometry, attribute); + } + function getWireframeAttribute(geometry) { + const currentAttribute = wireframeAttributes.get(geometry); + if (currentAttribute) { + const geometryIndex = geometry.index; + if (geometryIndex !== null) { + if (currentAttribute.version < geometryIndex.version) { + updateWireframeAttribute(geometry); + } + } + } else { + updateWireframeAttribute(geometry); + } + return wireframeAttributes.get(geometry); + } + return { + get, + update, + getWireframeAttribute + }; +} +function WebGLIndexedBufferRenderer(gl, extensions, info) { + let mode; + function setMode(value2) { + mode = value2; + } + let type, bytesPerElement; + function setIndex(value2) { + type = value2.type; + bytesPerElement = value2.bytesPerElement; + } + function render(start, count) { + gl.drawElements(mode, count, type, start * bytesPerElement); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) + return; + gl.drawElementsInstanced(mode, count, type, start * bytesPerElement, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawElementsWEBGL(mode, counts, 0, type, starts, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0;i < starts.length; i++) { + renderInstances(starts[i] / bytesPerElement, counts[i], primcount[i]); + } + } else { + extension.multiDrawElementsInstancedWEBGL(mode, counts, 0, type, starts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i] * primcount[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; +} +function WebGLInfo(gl) { + const memory = { + geometries: 0, + textures: 0 + }; + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + function update(count, mode, instanceCount) { + render.calls++; + switch (mode) { + case gl.TRIANGLES: + render.triangles += instanceCount * (count / 3); + break; + case gl.LINES: + render.lines += instanceCount * (count / 2); + break; + case gl.LINE_STRIP: + render.lines += instanceCount * (count - 1); + break; + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + case gl.POINTS: + render.points += instanceCount * count; + break; + default: + console.error("THREE.WebGLInfo: Unknown draw mode:", mode); + break; + } + } + function reset() { + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + } + return { + memory, + render, + programs: null, + autoReset: true, + reset, + update + }; +} +function WebGLMorphtargets(gl, capabilities, textures) { + const morphTextures = new WeakMap; + const morph = new Vector4; + function update(object, geometry, program) { + const objectInfluences = object.morphTargetInfluences; + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + let entry = morphTextures.get(geometry); + if (entry === undefined || entry.count !== morphTargetsCount) { + let disposeTexture = function() { + texture.dispose(); + morphTextures.delete(geometry); + geometry.removeEventListener("dispose", disposeTexture); + }; + if (entry !== undefined) + entry.texture.dispose(); + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + let vertexDataCount = 0; + if (hasMorphPosition === true) + vertexDataCount = 1; + if (hasMorphNormals === true) + vertexDataCount = 2; + if (hasMorphColors === true) + vertexDataCount = 3; + let width2 = geometry.attributes.position.count * vertexDataCount; + let height2 = 1; + if (width2 > capabilities.maxTextureSize) { + height2 = Math.ceil(width2 / capabilities.maxTextureSize); + width2 = capabilities.maxTextureSize; + } + const buffer = new Float32Array(width2 * height2 * 4 * morphTargetsCount); + const texture = new DataArrayTexture(buffer, width2, height2, morphTargetsCount); + texture.type = FloatType; + texture.needsUpdate = true; + const vertexDataStride = vertexDataCount * 4; + for (let i = 0;i < morphTargetsCount; i++) { + const morphTarget = morphTargets[i]; + const morphNormal = morphNormals[i]; + const morphColor = morphColors[i]; + const offset = width2 * height2 * 4 * i; + for (let j = 0;j < morphTarget.count; j++) { + const stride = j * vertexDataStride; + if (hasMorphPosition === true) { + morph.fromBufferAttribute(morphTarget, j); + buffer[offset + stride + 0] = morph.x; + buffer[offset + stride + 1] = morph.y; + buffer[offset + stride + 2] = morph.z; + buffer[offset + stride + 3] = 0; + } + if (hasMorphNormals === true) { + morph.fromBufferAttribute(morphNormal, j); + buffer[offset + stride + 4] = morph.x; + buffer[offset + stride + 5] = morph.y; + buffer[offset + stride + 6] = morph.z; + buffer[offset + stride + 7] = 0; + } + if (hasMorphColors === true) { + morph.fromBufferAttribute(morphColor, j); + buffer[offset + stride + 8] = morph.x; + buffer[offset + stride + 9] = morph.y; + buffer[offset + stride + 10] = morph.z; + buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1; + } + } + } + entry = { + count: morphTargetsCount, + texture, + size: new Vector2(width2, height2) + }; + morphTextures.set(geometry, entry); + geometry.addEventListener("dispose", disposeTexture); + } + if (object.isInstancedMesh === true && object.morphTexture !== null) { + program.getUniforms().setValue(gl, "morphTexture", object.morphTexture, textures); + } else { + let morphInfluencesSum = 0; + for (let i = 0;i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence); + program.getUniforms().setValue(gl, "morphTargetInfluences", objectInfluences); + } + program.getUniforms().setValue(gl, "morphTargetsTexture", entry.texture, textures); + program.getUniforms().setValue(gl, "morphTargetsTextureSize", entry.size); + } + return { + update + }; +} +function WebGLObjects(gl, geometries, attributes, info) { + let updateMap = new WeakMap; + function update(object) { + const frame = info.render.frame; + const geometry = object.geometry; + const buffergeometry = geometries.get(object, geometry); + if (updateMap.get(buffergeometry) !== frame) { + geometries.update(buffergeometry); + updateMap.set(buffergeometry, frame); + } + if (object.isInstancedMesh) { + if (object.hasEventListener("dispose", onInstancedMeshDispose) === false) { + object.addEventListener("dispose", onInstancedMeshDispose); + } + if (updateMap.get(object) !== frame) { + attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER); + if (object.instanceColor !== null) { + attributes.update(object.instanceColor, gl.ARRAY_BUFFER); + } + updateMap.set(object, frame); + } + } + if (object.isSkinnedMesh) { + const skeleton = object.skeleton; + if (updateMap.get(skeleton) !== frame) { + skeleton.update(); + updateMap.set(skeleton, frame); + } + } + return buffergeometry; + } + function dispose() { + updateMap = new WeakMap; + } + function onInstancedMeshDispose(event) { + const instancedMesh = event.target; + instancedMesh.removeEventListener("dispose", onInstancedMeshDispose); + attributes.remove(instancedMesh.instanceMatrix); + if (instancedMesh.instanceColor !== null) + attributes.remove(instancedMesh.instanceColor); + } + return { + update, + dispose + }; +} +var emptyTexture = /* @__PURE__ */ new Texture; +var emptyShadowTexture = /* @__PURE__ */ new DepthTexture(1, 1); +var emptyArrayTexture = /* @__PURE__ */ new DataArrayTexture; +var empty3dTexture = /* @__PURE__ */ new Data3DTexture; +var emptyCubeTexture = /* @__PURE__ */ new CubeTexture; +var arrayCacheF32 = []; +var arrayCacheI32 = []; +var mat4array = new Float32Array(16); +var mat3array = new Float32Array(9); +var mat2array = new Float32Array(4); +function flatten2(array, nBlocks, blockSize) { + const firstElem = array[0]; + if (firstElem <= 0 || firstElem > 0) + return array; + const n = nBlocks * blockSize; + let r = arrayCacheF32[n]; + if (r === undefined) { + r = new Float32Array(n); + arrayCacheF32[n] = r; + } + if (nBlocks !== 0) { + firstElem.toArray(r, 0); + for (let i = 1, offset = 0;i !== nBlocks; ++i) { + offset += blockSize; + array[i].toArray(r, offset); + } + } + return r; +} +function arraysEqual(a, b) { + if (a.length !== b.length) + return false; + for (let i = 0, l = a.length;i < l; i++) { + if (a[i] !== b[i]) + return false; + } + return true; +} +function copyArray(a, b) { + for (let i = 0, l = b.length;i < l; i++) { + a[i] = b[i]; + } +} +function allocTexUnits(textures, n) { + let r = arrayCacheI32[n]; + if (r === undefined) { + r = new Int32Array(n); + arrayCacheI32[n] = r; + } + for (let i = 0;i !== n; ++i) { + r[i] = textures.allocateTextureUnit(); + } + return r; +} +function setValueV1f(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1f(this.addr, v); + cache[0] = v; +} +function setValueV2f(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2f(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform2fv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV3f(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3f(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else if (v.r !== undefined) { + if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) { + gl.uniform3f(this.addr, v.r, v.g, v.b); + cache[0] = v.r; + cache[1] = v.g; + cache[2] = v.b; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform3fv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV4f(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4f(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform4fv(this.addr, v); + copyArray(cache, v); + } +} +function setValueM2(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual(cache, v)) + return; + gl.uniformMatrix2fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) + return; + mat2array.set(elements); + gl.uniformMatrix2fv(this.addr, false, mat2array); + copyArray(cache, elements); + } +} +function setValueM3(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual(cache, v)) + return; + gl.uniformMatrix3fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) + return; + mat3array.set(elements); + gl.uniformMatrix3fv(this.addr, false, mat3array); + copyArray(cache, elements); + } +} +function setValueM4(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual(cache, v)) + return; + gl.uniformMatrix4fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) + return; + mat4array.set(elements); + gl.uniformMatrix4fv(this.addr, false, mat4array); + copyArray(cache, elements); + } +} +function setValueV1i(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1i(this.addr, v); + cache[0] = v; +} +function setValueV2i(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2i(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform2iv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV3i(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3i(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform3iv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV4i(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4i(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform4iv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV1ui(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1ui(this.addr, v); + cache[0] = v; +} +function setValueV2ui(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2ui(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform2uiv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV3ui(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3ui(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform3uiv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV4ui(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4ui(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform4uiv(this.addr, v); + copyArray(cache, v); + } +} +function setValueT1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + let emptyTexture2D; + if (this.type === gl.SAMPLER_2D_SHADOW) { + emptyShadowTexture.compareFunction = LessEqualCompare; + emptyTexture2D = emptyShadowTexture; + } else { + emptyTexture2D = emptyTexture; + } + textures.setTexture2D(v || emptyTexture2D, unit); +} +function setValueT3D1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture3D(v || empty3dTexture, unit); +} +function setValueT6(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTextureCube(v || emptyCubeTexture, unit); +} +function setValueT2DArray1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture2DArray(v || emptyArrayTexture, unit); +} +function getSingularSetter(type) { + switch (type) { + case 5126: + return setValueV1f; + case 35664: + return setValueV2f; + case 35665: + return setValueV3f; + case 35666: + return setValueV4f; + case 35674: + return setValueM2; + case 35675: + return setValueM3; + case 35676: + return setValueM4; + case 5124: + case 35670: + return setValueV1i; + case 35667: + case 35671: + return setValueV2i; + case 35668: + case 35672: + return setValueV3i; + case 35669: + case 35673: + return setValueV4i; + case 5125: + return setValueV1ui; + case 36294: + return setValueV2ui; + case 36295: + return setValueV3ui; + case 36296: + return setValueV4ui; + case 35678: + case 36198: + case 36298: + case 36306: + case 35682: + return setValueT1; + case 35679: + case 36299: + case 36307: + return setValueT3D1; + case 35680: + case 36300: + case 36308: + case 36293: + return setValueT6; + case 36289: + case 36303: + case 36311: + case 36292: + return setValueT2DArray1; + } +} +function setValueV1fArray(gl, v) { + gl.uniform1fv(this.addr, v); +} +function setValueV2fArray(gl, v) { + const data2 = flatten2(v, this.size, 2); + gl.uniform2fv(this.addr, data2); +} +function setValueV3fArray(gl, v) { + const data2 = flatten2(v, this.size, 3); + gl.uniform3fv(this.addr, data2); +} +function setValueV4fArray(gl, v) { + const data2 = flatten2(v, this.size, 4); + gl.uniform4fv(this.addr, data2); +} +function setValueM2Array(gl, v) { + const data2 = flatten2(v, this.size, 4); + gl.uniformMatrix2fv(this.addr, false, data2); +} +function setValueM3Array(gl, v) { + const data2 = flatten2(v, this.size, 9); + gl.uniformMatrix3fv(this.addr, false, data2); +} +function setValueM4Array(gl, v) { + const data2 = flatten2(v, this.size, 16); + gl.uniformMatrix4fv(this.addr, false, data2); +} +function setValueV1iArray(gl, v) { + gl.uniform1iv(this.addr, v); +} +function setValueV2iArray(gl, v) { + gl.uniform2iv(this.addr, v); +} +function setValueV3iArray(gl, v) { + gl.uniform3iv(this.addr, v); +} +function setValueV4iArray(gl, v) { + gl.uniform4iv(this.addr, v); +} +function setValueV1uiArray(gl, v) { + gl.uniform1uiv(this.addr, v); +} +function setValueV2uiArray(gl, v) { + gl.uniform2uiv(this.addr, v); +} +function setValueV3uiArray(gl, v) { + gl.uniform3uiv(this.addr, v); +} +function setValueV4uiArray(gl, v) { + gl.uniform4uiv(this.addr, v); +} +function setValueT1Array(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTexture2D(v[i] || emptyTexture, units[i]); + } +} +function setValueT3DArray(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTexture3D(v[i] || empty3dTexture, units[i]); + } +} +function setValueT6Array(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTextureCube(v[i] || emptyCubeTexture, units[i]); + } +} +function setValueT2DArrayArray(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]); + } +} +function getPureArraySetter(type) { + switch (type) { + case 5126: + return setValueV1fArray; + case 35664: + return setValueV2fArray; + case 35665: + return setValueV3fArray; + case 35666: + return setValueV4fArray; + case 35674: + return setValueM2Array; + case 35675: + return setValueM3Array; + case 35676: + return setValueM4Array; + case 5124: + case 35670: + return setValueV1iArray; + case 35667: + case 35671: + return setValueV2iArray; + case 35668: + case 35672: + return setValueV3iArray; + case 35669: + case 35673: + return setValueV4iArray; + case 5125: + return setValueV1uiArray; + case 36294: + return setValueV2uiArray; + case 36295: + return setValueV3uiArray; + case 36296: + return setValueV4uiArray; + case 35678: + case 36198: + case 36298: + case 36306: + case 35682: + return setValueT1Array; + case 35679: + case 36299: + case 36307: + return setValueT3DArray; + case 35680: + case 36300: + case 36308: + case 36293: + return setValueT6Array; + case 36289: + case 36303: + case 36311: + case 36292: + return setValueT2DArrayArray; + } +} + +class SingleUniform { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.setValue = getSingularSetter(activeInfo.type); + } +} + +class PureArrayUniform { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.size = activeInfo.size; + this.setValue = getPureArraySetter(activeInfo.type); + } +} + +class StructuredUniform { + constructor(id) { + this.id = id; + this.seq = []; + this.map = {}; + } + setValue(gl, value2, textures) { + const seq = this.seq; + for (let i = 0, n = seq.length;i !== n; ++i) { + const u = seq[i]; + u.setValue(gl, value2[u.id], textures); + } + } +} +var RePathPart = /(\w+)(\])?(\[|\.)?/g; +function addUniform(container, uniformObject) { + container.seq.push(uniformObject); + container.map[uniformObject.id] = uniformObject; +} +function parseUniform(activeInfo, addr, container) { + const path = activeInfo.name, pathLength = path.length; + RePathPart.lastIndex = 0; + while (true) { + const match = RePathPart.exec(path), matchEnd = RePathPart.lastIndex; + let id = match[1]; + const idIsIndex = match[2] === "]", subscript = match[3]; + if (idIsIndex) + id = id | 0; + if (subscript === undefined || subscript === "[" && matchEnd + 2 === pathLength) { + addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr)); + break; + } else { + const map2 = container.map; + let next = map2[id]; + if (next === undefined) { + next = new StructuredUniform(id); + addUniform(container, next); + } + container = next; + } + } +} + +class WebGLUniforms { + constructor(gl, program) { + this.seq = []; + this.map = {}; + const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (let i = 0;i < n; ++i) { + const info = gl.getActiveUniform(program, i), addr = gl.getUniformLocation(program, info.name); + parseUniform(info, addr, this); + } + } + setValue(gl, name2, value2, textures) { + const u = this.map[name2]; + if (u !== undefined) + u.setValue(gl, value2, textures); + } + setOptional(gl, object, name2) { + const v = object[name2]; + if (v !== undefined) + this.setValue(gl, name2, v); + } + static upload(gl, seq, values2, textures) { + for (let i = 0, n = seq.length;i !== n; ++i) { + const u = seq[i], v = values2[u.id]; + if (v.needsUpdate !== false) { + u.setValue(gl, v.value, textures); + } + } + } + static seqWithValue(seq, values2) { + const r = []; + for (let i = 0, n = seq.length;i !== n; ++i) { + const u = seq[i]; + if (u.id in values2) + r.push(u); + } + return r; + } +} +function WebGLShader(gl, type, string) { + const shader = gl.createShader(type); + gl.shaderSource(shader, string); + gl.compileShader(shader); + return shader; +} +var COMPLETION_STATUS_KHR = 37297; +var programIdCount = 0; +function handleSource(string, errorLine) { + const lines = string.split(` +`); + const lines2 = []; + const from = Math.max(errorLine - 6, 0); + const to = Math.min(errorLine + 6, lines.length); + for (let i = from;i < to; i++) { + const line = i + 1; + lines2.push(`${line === errorLine ? ">" : " "} ${line}: ${lines[i]}`); + } + return lines2.join(` +`); +} +var _m0 = /* @__PURE__ */ new Matrix3; +function getEncodingComponents(colorSpace) { + ColorManagement._getMatrix(_m0, ColorManagement.workingColorSpace, colorSpace); + const encodingMatrix = `mat3( ${_m0.elements.map((v) => v.toFixed(4))} )`; + switch (ColorManagement.getTransfer(colorSpace)) { + case LinearTransfer: + return [encodingMatrix, "LinearTransferOETF"]; + case SRGBTransfer: + return [encodingMatrix, "sRGBTransferOETF"]; + default: + console.warn("THREE.WebGLProgram: Unsupported color space: ", colorSpace); + return [encodingMatrix, "LinearTransferOETF"]; + } +} +function getShaderErrors(gl, shader, type) { + const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS); + const errors = gl.getShaderInfoLog(shader).trim(); + if (status && errors === "") + return ""; + const errorMatches = /ERROR: 0:(\d+)/.exec(errors); + if (errorMatches) { + const errorLine = parseInt(errorMatches[1]); + return type.toUpperCase() + ` + +` + errors + ` + +` + handleSource(gl.getShaderSource(shader), errorLine); + } else { + return errors; + } +} +function getTexelEncodingFunction(functionName, colorSpace) { + const components = getEncodingComponents(colorSpace); + return [ + `vec4 ${functionName}( vec4 value ) {`, + ` return ${components[1]}( vec4( value.rgb * ${components[0]}, value.a ) );`, + "}" + ].join(` +`); +} +function getToneMappingFunction(functionName, toneMapping) { + let toneMappingName; + switch (toneMapping) { + case LinearToneMapping: + toneMappingName = "Linear"; + break; + case ReinhardToneMapping: + toneMappingName = "Reinhard"; + break; + case CineonToneMapping: + toneMappingName = "Cineon"; + break; + case ACESFilmicToneMapping: + toneMappingName = "ACESFilmic"; + break; + case AgXToneMapping: + toneMappingName = "AgX"; + break; + case NeutralToneMapping: + toneMappingName = "Neutral"; + break; + case CustomToneMapping: + toneMappingName = "Custom"; + break; + default: + console.warn("THREE.WebGLProgram: Unsupported toneMapping:", toneMapping); + toneMappingName = "Linear"; + } + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; +} +var _v02 = /* @__PURE__ */ new Vector3; +function getLuminanceFunction() { + ColorManagement.getLuminanceCoefficients(_v02); + const r = _v02.x.toFixed(4); + const g = _v02.y.toFixed(4); + const b = _v02.z.toFixed(4); + return [ + "float luminance( const in vec3 rgb ) {", + ` const vec3 weights = vec3( ${r}, ${g}, ${b} );`, + "\treturn dot( weights, rgb );", + "}" + ].join(` +`); +} +function generateVertexExtensions(parameters) { + const chunks = [ + parameters.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "", + parameters.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : "" + ]; + return chunks.filter(filterEmptyLine).join(` +`); +} +function generateDefines(defines) { + const chunks = []; + for (const name2 in defines) { + const value2 = defines[name2]; + if (value2 === false) + continue; + chunks.push("#define " + name2 + " " + value2); + } + return chunks.join(` +`); +} +function fetchAttributeLocations(gl, program) { + const attributes = {}; + const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (let i = 0;i < n; i++) { + const info = gl.getActiveAttrib(program, i); + const name2 = info.name; + let locationSize = 1; + if (info.type === gl.FLOAT_MAT2) + locationSize = 2; + if (info.type === gl.FLOAT_MAT3) + locationSize = 3; + if (info.type === gl.FLOAT_MAT4) + locationSize = 4; + attributes[name2] = { + type: info.type, + location: gl.getAttribLocation(program, name2), + locationSize + }; + } + return attributes; +} +function filterEmptyLine(string) { + return string !== ""; +} +function replaceLightNums(string, parameters) { + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows); +} +function replaceClippingPlaneNums(string, parameters) { + return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection); +} +var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; +function resolveIncludes(string) { + return string.replace(includePattern, includeReplacer); +} +var shaderChunkMap = new Map; +function includeReplacer(match, include) { + let string = ShaderChunk[include]; + if (string === undefined) { + const newInclude = shaderChunkMap.get(include); + if (newInclude !== undefined) { + string = ShaderChunk[newInclude]; + console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude); + } else { + throw new Error("Can not resolve #include <" + include + ">"); + } + } + return resolveIncludes(string); +} +var unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; +function unrollLoops(string) { + return string.replace(unrollLoopPattern, loopReplacer); +} +function loopReplacer(match, start, end, snippet) { + let string = ""; + for (let i = parseInt(start);i < parseInt(end); i++) { + string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i + " ]").replace(/UNROLLED_LOOP_INDEX/g, i); + } + return string; +} +function generatePrecision(parameters) { + let precisionstring = `precision ${parameters.precision} float; + precision ${parameters.precision} int; + precision ${parameters.precision} sampler2D; + precision ${parameters.precision} samplerCube; + precision ${parameters.precision} sampler3D; + precision ${parameters.precision} sampler2DArray; + precision ${parameters.precision} sampler2DShadow; + precision ${parameters.precision} samplerCubeShadow; + precision ${parameters.precision} sampler2DArrayShadow; + precision ${parameters.precision} isampler2D; + precision ${parameters.precision} isampler3D; + precision ${parameters.precision} isamplerCube; + precision ${parameters.precision} isampler2DArray; + precision ${parameters.precision} usampler2D; + precision ${parameters.precision} usampler3D; + precision ${parameters.precision} usamplerCube; + precision ${parameters.precision} usampler2DArray; + `; + if (parameters.precision === "highp") { + precisionstring += ` +#define HIGH_PRECISION`; + } else if (parameters.precision === "mediump") { + precisionstring += ` +#define MEDIUM_PRECISION`; + } else if (parameters.precision === "lowp") { + precisionstring += ` +#define LOW_PRECISION`; + } + return precisionstring; +} +function generateShadowMapTypeDefine(parameters) { + let shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; + if (parameters.shadowMapType === PCFShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; + } else if (parameters.shadowMapType === PCFSoftShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; + } else if (parameters.shadowMapType === VSMShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_VSM"; + } + return shadowMapTypeDefine; +} +function generateEnvMapTypeDefine(parameters) { + let envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + break; + case CubeUVReflectionMapping: + envMapTypeDefine = "ENVMAP_TYPE_CUBE_UV"; + break; + } + } + return envMapTypeDefine; +} +function generateEnvMapModeDefine(parameters) { + let envMapModeDefine = "ENVMAP_MODE_REFLECTION"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeRefractionMapping: + envMapModeDefine = "ENVMAP_MODE_REFRACTION"; + break; + } + } + return envMapModeDefine; +} +function generateEnvMapBlendingDefine(parameters) { + let envMapBlendingDefine = "ENVMAP_BLENDING_NONE"; + if (parameters.envMap) { + switch (parameters.combine) { + case MultiplyOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_MULTIPLY"; + break; + case MixOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_MIX"; + break; + case AddOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_ADD"; + break; + } + } + return envMapBlendingDefine; +} +function generateCubeUVSize(parameters) { + const imageHeight = parameters.envMapCubeUVHeight; + if (imageHeight === null) + return null; + const maxMip = Math.log2(imageHeight) - 2; + const texelHeight = 1 / imageHeight; + const texelWidth = 1 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16)); + return { texelWidth, texelHeight, maxMip }; +} +function WebGLProgram(renderer2, cacheKey, parameters, bindingStates) { + const gl = renderer2.getContext(); + const defines = parameters.defines; + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters); + const envMapTypeDefine = generateEnvMapTypeDefine(parameters); + const envMapModeDefine = generateEnvMapModeDefine(parameters); + const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters); + const envMapCubeUVSize = generateCubeUVSize(parameters); + const customVertexExtensions = generateVertexExtensions(parameters); + const customDefines = generateDefines(defines); + const program = gl.createProgram(); + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? "#version " + parameters.glslVersion + ` +` : ""; + if (parameters.isRawShaderMaterial) { + prefixVertex = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine).join(` +`); + if (prefixVertex.length > 0) { + prefixVertex += ` +`; + } + prefixFragment = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine).join(` +`); + if (prefixFragment.length > 0) { + prefixFragment += ` +`; + } + } else { + prefixVertex = [ + generatePrecision(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "", + parameters.batching ? "#define USE_BATCHING" : "", + parameters.batchingColor ? "#define USE_BATCHING_COLOR" : "", + parameters.instancing ? "#define USE_INSTANCING" : "", + parameters.instancingColor ? "#define USE_INSTANCING_COLOR" : "", + parameters.instancingMorph ? "#define USE_INSTANCING_MORPH" : "", + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.displacementMap ? "#define USE_DISPLACEMENTMAP" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.mapUv ? "#define MAP_UV " + parameters.mapUv : "", + parameters.alphaMapUv ? "#define ALPHAMAP_UV " + parameters.alphaMapUv : "", + parameters.lightMapUv ? "#define LIGHTMAP_UV " + parameters.lightMapUv : "", + parameters.aoMapUv ? "#define AOMAP_UV " + parameters.aoMapUv : "", + parameters.emissiveMapUv ? "#define EMISSIVEMAP_UV " + parameters.emissiveMapUv : "", + parameters.bumpMapUv ? "#define BUMPMAP_UV " + parameters.bumpMapUv : "", + parameters.normalMapUv ? "#define NORMALMAP_UV " + parameters.normalMapUv : "", + parameters.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + parameters.displacementMapUv : "", + parameters.metalnessMapUv ? "#define METALNESSMAP_UV " + parameters.metalnessMapUv : "", + parameters.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + parameters.roughnessMapUv : "", + parameters.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + parameters.anisotropyMapUv : "", + parameters.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + parameters.clearcoatMapUv : "", + parameters.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + parameters.clearcoatNormalMapUv : "", + parameters.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + parameters.clearcoatRoughnessMapUv : "", + parameters.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + parameters.iridescenceMapUv : "", + parameters.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + parameters.iridescenceThicknessMapUv : "", + parameters.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + parameters.sheenColorMapUv : "", + parameters.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + parameters.sheenRoughnessMapUv : "", + parameters.specularMapUv ? "#define SPECULARMAP_UV " + parameters.specularMapUv : "", + parameters.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + parameters.specularColorMapUv : "", + parameters.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + parameters.specularIntensityMapUv : "", + parameters.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + parameters.transmissionMapUv : "", + parameters.thicknessMapUv ? "#define THICKNESSMAP_UV " + parameters.thicknessMapUv : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.skinning ? "#define USE_SKINNING" : "", + parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", + parameters.morphNormals && parameters.flatShading === false ? "#define USE_MORPHNORMALS" : "", + parameters.morphColors ? "#define USE_MORPHCOLORS" : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + parameters.morphTextureStride : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + parameters.morphTargetsCount : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "", + "uniform mat4 modelMatrix;", + "uniform mat4 modelViewMatrix;", + "uniform mat4 projectionMatrix;", + "uniform mat4 viewMatrix;", + "uniform mat3 normalMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + "#ifdef USE_INSTANCING", + "\tattribute mat4 instanceMatrix;", + "#endif", + "#ifdef USE_INSTANCING_COLOR", + "\tattribute vec3 instanceColor;", + "#endif", + "#ifdef USE_INSTANCING_MORPH", + "\tuniform sampler2D morphTexture;", + "#endif", + "attribute vec3 position;", + "attribute vec3 normal;", + "attribute vec2 uv;", + "#ifdef USE_UV1", + "\tattribute vec2 uv1;", + "#endif", + "#ifdef USE_UV2", + "\tattribute vec2 uv2;", + "#endif", + "#ifdef USE_UV3", + "\tattribute vec2 uv3;", + "#endif", + "#ifdef USE_TANGENT", + "\tattribute vec4 tangent;", + "#endif", + "#if defined( USE_COLOR_ALPHA )", + "\tattribute vec4 color;", + "#elif defined( USE_COLOR )", + "\tattribute vec3 color;", + "#endif", + "#ifdef USE_SKINNING", + "\tattribute vec4 skinIndex;", + "\tattribute vec4 skinWeight;", + "#endif", + ` +` + ].filter(filterEmptyLine).join(` +`); + prefixFragment = [ + generatePrecision(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.matcap ? "#define USE_MATCAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapTypeDefine : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.envMap ? "#define " + envMapBlendingDefine : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_WIDTH " + envMapCubeUVSize.texelWidth : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_HEIGHT " + envMapCubeUVSize.texelHeight : "", + envMapCubeUVSize ? "#define CUBEUV_MAX_MIP " + envMapCubeUVSize.maxMip + ".0" : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoat ? "#define USE_CLEARCOAT" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.dispersion ? "#define USE_DISPERSION" : "", + parameters.iridescence ? "#define USE_IRIDESCENCE" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaTest ? "#define USE_ALPHATEST" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.sheen ? "#define USE_SHEEN" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.gradientMap ? "#define USE_GRADIENTMAP" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", + parameters.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "", + "uniform mat4 viewMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + parameters.toneMapping !== NoToneMapping ? "#define TONE_MAPPING" : "", + parameters.toneMapping !== NoToneMapping ? ShaderChunk["tonemapping_pars_fragment"] : "", + parameters.toneMapping !== NoToneMapping ? getToneMappingFunction("toneMapping", parameters.toneMapping) : "", + parameters.dithering ? "#define DITHERING" : "", + parameters.opaque ? "#define OPAQUE" : "", + ShaderChunk["colorspace_pars_fragment"], + getTexelEncodingFunction("linearToOutputTexel", parameters.outputColorSpace), + getLuminanceFunction(), + parameters.useDepthPacking ? "#define DEPTH_PACKING " + parameters.depthPacking : "", + ` +` + ].filter(filterEmptyLine).join(` +`); + } + vertexShader = resolveIncludes(vertexShader); + vertexShader = replaceLightNums(vertexShader, parameters); + vertexShader = replaceClippingPlaneNums(vertexShader, parameters); + fragmentShader = resolveIncludes(fragmentShader); + fragmentShader = replaceLightNums(fragmentShader, parameters); + fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters); + vertexShader = unrollLoops(vertexShader); + fragmentShader = unrollLoops(fragmentShader); + if (parameters.isRawShaderMaterial !== true) { + versionString = `#version 300 es +`; + prefixVertex = [ + customVertexExtensions, + "#define attribute in", + "#define varying out", + "#define texture2D texture" + ].join(` +`) + ` +` + prefixVertex; + prefixFragment = [ + "#define varying in", + parameters.glslVersion === GLSL3 ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", + parameters.glslVersion === GLSL3 ? "" : "#define gl_FragColor pc_fragColor", + "#define gl_FragDepthEXT gl_FragDepth", + "#define texture2D texture", + "#define textureCube texture", + "#define texture2DProj textureProj", + "#define texture2DLodEXT textureLod", + "#define texture2DProjLodEXT textureProjLod", + "#define textureCubeLodEXT textureLod", + "#define texture2DGradEXT textureGrad", + "#define texture2DProjGradEXT textureProjGrad", + "#define textureCubeGradEXT textureGrad" + ].join(` +`) + ` +` + prefixFragment; + } + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl); + const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl); + gl.attachShader(program, glVertexShader); + gl.attachShader(program, glFragmentShader); + if (parameters.index0AttributeName !== undefined) { + gl.bindAttribLocation(program, 0, parameters.index0AttributeName); + } else if (parameters.morphTargets === true) { + gl.bindAttribLocation(program, 0, "position"); + } + gl.linkProgram(program); + function onFirstUse(self2) { + if (renderer2.debug.checkShaderErrors) { + const programLog = gl.getProgramInfoLog(program).trim(); + const vertexLog = gl.getShaderInfoLog(glVertexShader).trim(); + const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim(); + let runnable = true; + let haveDiagnostics = true; + if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) { + runnable = false; + if (typeof renderer2.debug.onShaderError === "function") { + renderer2.debug.onShaderError(gl, program, glVertexShader, glFragmentShader); + } else { + const vertexErrors = getShaderErrors(gl, glVertexShader, "vertex"); + const fragmentErrors = getShaderErrors(gl, glFragmentShader, "fragment"); + console.error("THREE.WebGLProgram: Shader Error " + gl.getError() + " - " + "VALIDATE_STATUS " + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + ` + +` + "Material Name: " + self2.name + ` +` + "Material Type: " + self2.type + ` + +` + "Program Info Log: " + programLog + ` +` + vertexErrors + ` +` + fragmentErrors); + } + } else if (programLog !== "") { + console.warn("THREE.WebGLProgram: Program Info Log:", programLog); + } else if (vertexLog === "" || fragmentLog === "") { + haveDiagnostics = false; + } + if (haveDiagnostics) { + self2.diagnostics = { + runnable, + programLog, + vertexShader: { + log: vertexLog, + prefix: prefixVertex + }, + fragmentShader: { + log: fragmentLog, + prefix: prefixFragment + } + }; + } + } + gl.deleteShader(glVertexShader); + gl.deleteShader(glFragmentShader); + cachedUniforms = new WebGLUniforms(gl, program); + cachedAttributes = fetchAttributeLocations(gl, program); + } + let cachedUniforms; + this.getUniforms = function() { + if (cachedUniforms === undefined) { + onFirstUse(this); + } + return cachedUniforms; + }; + let cachedAttributes; + this.getAttributes = function() { + if (cachedAttributes === undefined) { + onFirstUse(this); + } + return cachedAttributes; + }; + let programReady = parameters.rendererExtensionParallelShaderCompile === false; + this.isReady = function() { + if (programReady === false) { + programReady = gl.getProgramParameter(program, COMPLETION_STATUS_KHR); + } + return programReady; + }; + this.destroy = function() { + bindingStates.releaseStatesOfProgram(this); + gl.deleteProgram(program); + this.program = undefined; + }; + this.type = parameters.shaderType; + this.name = parameters.shaderName; + this.id = programIdCount++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + return this; +} +var _id2 = 0; + +class WebGLShaderCache { + constructor() { + this.shaderCache = new Map; + this.materialCache = new Map; + } + update(material) { + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + const vertexShaderStage = this._getShaderStage(vertexShader); + const fragmentShaderStage = this._getShaderStage(fragmentShader); + const materialShaders = this._getShaderCacheForMaterial(material); + if (materialShaders.has(vertexShaderStage) === false) { + materialShaders.add(vertexShaderStage); + vertexShaderStage.usedTimes++; + } + if (materialShaders.has(fragmentShaderStage) === false) { + materialShaders.add(fragmentShaderStage); + fragmentShaderStage.usedTimes++; + } + return this; + } + remove(material) { + const materialShaders = this.materialCache.get(material); + for (const shaderStage of materialShaders) { + shaderStage.usedTimes--; + if (shaderStage.usedTimes === 0) + this.shaderCache.delete(shaderStage.code); + } + this.materialCache.delete(material); + return this; + } + getVertexShaderID(material) { + return this._getShaderStage(material.vertexShader).id; + } + getFragmentShaderID(material) { + return this._getShaderStage(material.fragmentShader).id; + } + dispose() { + this.shaderCache.clear(); + this.materialCache.clear(); + } + _getShaderCacheForMaterial(material) { + const cache = this.materialCache; + let set = cache.get(material); + if (set === undefined) { + set = new Set; + cache.set(material, set); + } + return set; + } + _getShaderStage(code) { + const cache = this.shaderCache; + let stage = cache.get(code); + if (stage === undefined) { + stage = new WebGLShaderStage(code); + cache.set(code, stage); + } + return stage; + } +} + +class WebGLShaderStage { + constructor(code) { + this.id = _id2++; + this.code = code; + this.usedTimes = 0; + } +} +function WebGLPrograms(renderer2, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) { + const _programLayers = new Layers; + const _customShaders = new WebGLShaderCache; + const _activeChannels = new Set; + const programs = []; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures; + let precision = capabilities.precision; + const shaderIDs = { + MeshDepthMaterial: "depth", + MeshDistanceMaterial: "distanceRGBA", + MeshNormalMaterial: "normal", + MeshBasicMaterial: "basic", + MeshLambertMaterial: "lambert", + MeshPhongMaterial: "phong", + MeshToonMaterial: "toon", + MeshStandardMaterial: "physical", + MeshPhysicalMaterial: "physical", + MeshMatcapMaterial: "matcap", + LineBasicMaterial: "basic", + LineDashedMaterial: "dashed", + PointsMaterial: "points", + ShadowMaterial: "shadow", + SpriteMaterial: "sprite" + }; + function getChannel(value2) { + _activeChannels.add(value2); + if (value2 === 0) + return "uv"; + return `uv${value2}`; + } + function getParameters(material, lights, shadows, scene, object) { + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null; + const shaderID = shaderIDs[material.type]; + if (material.precision !== null) { + precision = capabilities.getMaxPrecision(material.precision); + if (precision !== material.precision) { + console.warn("THREE.WebGLProgram.getParameters:", material.precision, "not supported, using", precision, "instead."); + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + let morphTextureStride = 0; + if (geometry.morphAttributes.position !== undefined) + morphTextureStride = 1; + if (geometry.morphAttributes.normal !== undefined) + morphTextureStride = 2; + if (geometry.morphAttributes.color !== undefined) + morphTextureStride = 3; + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + if (shaderID) { + const shader = ShaderLib[shaderID]; + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + } else { + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + _customShaders.update(material); + customVertexShaderID = _customShaders.getVertexShaderID(material); + customFragmentShaderID = _customShaders.getFragmentShaderID(material); + } + const currentRenderTarget = renderer2.getRenderTarget(); + const reverseDepthBuffer = renderer2.state.buffers.depth.getReversed(); + const IS_INSTANCEDMESH = object.isInstancedMesh === true; + const IS_BATCHEDMESH = object.isBatchedMesh === true; + const HAS_MAP = !!material.map; + const HAS_MATCAP = !!material.matcap; + const HAS_ENVMAP = !!envMap; + const HAS_AOMAP = !!material.aoMap; + const HAS_LIGHTMAP = !!material.lightMap; + const HAS_BUMPMAP = !!material.bumpMap; + const HAS_NORMALMAP = !!material.normalMap; + const HAS_DISPLACEMENTMAP = !!material.displacementMap; + const HAS_EMISSIVEMAP = !!material.emissiveMap; + const HAS_METALNESSMAP = !!material.metalnessMap; + const HAS_ROUGHNESSMAP = !!material.roughnessMap; + const HAS_ANISOTROPY = material.anisotropy > 0; + const HAS_CLEARCOAT = material.clearcoat > 0; + const HAS_DISPERSION = material.dispersion > 0; + const HAS_IRIDESCENCE = material.iridescence > 0; + const HAS_SHEEN = material.sheen > 0; + const HAS_TRANSMISSION = material.transmission > 0; + const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !!material.anisotropyMap; + const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !!material.clearcoatMap; + const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !!material.clearcoatNormalMap; + const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !!material.clearcoatRoughnessMap; + const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !!material.iridescenceMap; + const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !!material.iridescenceThicknessMap; + const HAS_SHEEN_COLORMAP = HAS_SHEEN && !!material.sheenColorMap; + const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !!material.sheenRoughnessMap; + const HAS_SPECULARMAP = !!material.specularMap; + const HAS_SPECULAR_COLORMAP = !!material.specularColorMap; + const HAS_SPECULAR_INTENSITYMAP = !!material.specularIntensityMap; + const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !!material.transmissionMap; + const HAS_THICKNESSMAP = HAS_TRANSMISSION && !!material.thicknessMap; + const HAS_GRADIENTMAP = !!material.gradientMap; + const HAS_ALPHAMAP = !!material.alphaMap; + const HAS_ALPHATEST = material.alphaTest > 0; + const HAS_ALPHAHASH = !!material.alphaHash; + const HAS_EXTENSIONS = !!material.extensions; + let toneMapping = NoToneMapping; + if (material.toneMapped) { + if (currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true) { + toneMapping = renderer2.toneMapping; + } + } + const parameters = { + shaderID, + shaderType: material.type, + shaderName: material.name, + vertexShader, + fragmentShader, + defines: material.defines, + customVertexShaderID, + customFragmentShaderID, + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + precision, + batching: IS_BATCHEDMESH, + batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null, + instancing: IS_INSTANCEDMESH, + instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, + supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, + outputColorSpace: currentRenderTarget === null ? renderer2.outputColorSpace : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace, + alphaToCoverage: !!material.alphaToCoverage, + map: HAS_MAP, + matcap: HAS_MATCAP, + envMap: HAS_ENVMAP, + envMapMode: HAS_ENVMAP && envMap.mapping, + envMapCubeUVHeight, + aoMap: HAS_AOMAP, + lightMap: HAS_LIGHTMAP, + bumpMap: HAS_BUMPMAP, + normalMap: HAS_NORMALMAP, + displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP, + emissiveMap: HAS_EMISSIVEMAP, + normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap, + normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap, + metalnessMap: HAS_METALNESSMAP, + roughnessMap: HAS_ROUGHNESSMAP, + anisotropy: HAS_ANISOTROPY, + anisotropyMap: HAS_ANISOTROPYMAP, + clearcoat: HAS_CLEARCOAT, + clearcoatMap: HAS_CLEARCOATMAP, + clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP, + clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP, + dispersion: HAS_DISPERSION, + iridescence: HAS_IRIDESCENCE, + iridescenceMap: HAS_IRIDESCENCEMAP, + iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP, + sheen: HAS_SHEEN, + sheenColorMap: HAS_SHEEN_COLORMAP, + sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP, + specularMap: HAS_SPECULARMAP, + specularColorMap: HAS_SPECULAR_COLORMAP, + specularIntensityMap: HAS_SPECULAR_INTENSITYMAP, + transmission: HAS_TRANSMISSION, + transmissionMap: HAS_TRANSMISSIONMAP, + thicknessMap: HAS_THICKNESSMAP, + gradientMap: HAS_GRADIENTMAP, + opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false, + alphaMap: HAS_ALPHAMAP, + alphaTest: HAS_ALPHATEST, + alphaHash: HAS_ALPHAHASH, + combine: material.combine, + mapUv: HAS_MAP && getChannel(material.map.channel), + aoMapUv: HAS_AOMAP && getChannel(material.aoMap.channel), + lightMapUv: HAS_LIGHTMAP && getChannel(material.lightMap.channel), + bumpMapUv: HAS_BUMPMAP && getChannel(material.bumpMap.channel), + normalMapUv: HAS_NORMALMAP && getChannel(material.normalMap.channel), + displacementMapUv: HAS_DISPLACEMENTMAP && getChannel(material.displacementMap.channel), + emissiveMapUv: HAS_EMISSIVEMAP && getChannel(material.emissiveMap.channel), + metalnessMapUv: HAS_METALNESSMAP && getChannel(material.metalnessMap.channel), + roughnessMapUv: HAS_ROUGHNESSMAP && getChannel(material.roughnessMap.channel), + anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel(material.anisotropyMap.channel), + clearcoatMapUv: HAS_CLEARCOATMAP && getChannel(material.clearcoatMap.channel), + clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel(material.clearcoatNormalMap.channel), + clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel(material.clearcoatRoughnessMap.channel), + iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel(material.iridescenceMap.channel), + iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel(material.iridescenceThicknessMap.channel), + sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel(material.sheenColorMap.channel), + sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel(material.sheenRoughnessMap.channel), + specularMapUv: HAS_SPECULARMAP && getChannel(material.specularMap.channel), + specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel(material.specularColorMap.channel), + specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel(material.specularIntensityMap.channel), + transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel(material.transmissionMap.channel), + thicknessMapUv: HAS_THICKNESSMAP && getChannel(material.thicknessMap.channel), + alphaMapUv: HAS_ALPHAMAP && getChannel(material.alphaMap.channel), + vertexTangents: !!geometry.attributes.tangent && (HAS_NORMALMAP || HAS_ANISOTROPY), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4, + pointsUvs: object.isPoints === true && !!geometry.attributes.uv && (HAS_MAP || HAS_ALPHAMAP), + fog: !!fog, + useFog: material.fog === true, + fogExp2: !!fog && fog.isFogExp2, + flatShading: material.flatShading === true, + sizeAttenuation: material.sizeAttenuation === true, + logarithmicDepthBuffer, + reverseDepthBuffer, + skinning: object.isSkinnedMesh === true, + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount, + morphTextureStride, + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + numLightProbes: lights.numLightProbes, + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + dithering: material.dithering, + shadowMapEnabled: renderer2.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer2.shadowMap.type, + toneMapping, + decodeVideoTexture: HAS_MAP && material.map.isVideoTexture === true && ColorManagement.getTransfer(material.map.colorSpace) === SRGBTransfer, + decodeVideoTextureEmissive: HAS_EMISSIVEMAP && material.emissiveMap.isVideoTexture === true && ColorManagement.getTransfer(material.emissiveMap.colorSpace) === SRGBTransfer, + premultipliedAlpha: material.premultipliedAlpha, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + useDepthPacking: material.depthPacking >= 0, + depthPacking: material.depthPacking || 0, + index0AttributeName: material.index0AttributeName, + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has("WEBGL_clip_cull_distance"), + extensionMultiDraw: (HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH) && extensions.has("WEBGL_multi_draw"), + rendererExtensionParallelShaderCompile: extensions.has("KHR_parallel_shader_compile"), + customProgramCacheKey: material.customProgramCacheKey() + }; + parameters.vertexUv1s = _activeChannels.has(1); + parameters.vertexUv2s = _activeChannels.has(2); + parameters.vertexUv3s = _activeChannels.has(3); + _activeChannels.clear(); + return parameters; + } + function getProgramCacheKey(parameters) { + const array = []; + if (parameters.shaderID) { + array.push(parameters.shaderID); + } else { + array.push(parameters.customVertexShaderID); + array.push(parameters.customFragmentShaderID); + } + if (parameters.defines !== undefined) { + for (const name2 in parameters.defines) { + array.push(name2); + array.push(parameters.defines[name2]); + } + } + if (parameters.isRawShaderMaterial === false) { + getProgramCacheKeyParameters(array, parameters); + getProgramCacheKeyBooleans(array, parameters); + array.push(renderer2.outputColorSpace); + } + array.push(parameters.customProgramCacheKey); + return array.join(); + } + function getProgramCacheKeyParameters(array, parameters) { + array.push(parameters.precision); + array.push(parameters.outputColorSpace); + array.push(parameters.envMapMode); + array.push(parameters.envMapCubeUVHeight); + array.push(parameters.mapUv); + array.push(parameters.alphaMapUv); + array.push(parameters.lightMapUv); + array.push(parameters.aoMapUv); + array.push(parameters.bumpMapUv); + array.push(parameters.normalMapUv); + array.push(parameters.displacementMapUv); + array.push(parameters.emissiveMapUv); + array.push(parameters.metalnessMapUv); + array.push(parameters.roughnessMapUv); + array.push(parameters.anisotropyMapUv); + array.push(parameters.clearcoatMapUv); + array.push(parameters.clearcoatNormalMapUv); + array.push(parameters.clearcoatRoughnessMapUv); + array.push(parameters.iridescenceMapUv); + array.push(parameters.iridescenceThicknessMapUv); + array.push(parameters.sheenColorMapUv); + array.push(parameters.sheenRoughnessMapUv); + array.push(parameters.specularMapUv); + array.push(parameters.specularColorMapUv); + array.push(parameters.specularIntensityMapUv); + array.push(parameters.transmissionMapUv); + array.push(parameters.thicknessMapUv); + array.push(parameters.combine); + array.push(parameters.fogExp2); + array.push(parameters.sizeAttenuation); + array.push(parameters.morphTargetsCount); + array.push(parameters.morphAttributeCount); + array.push(parameters.numDirLights); + array.push(parameters.numPointLights); + array.push(parameters.numSpotLights); + array.push(parameters.numSpotLightMaps); + array.push(parameters.numHemiLights); + array.push(parameters.numRectAreaLights); + array.push(parameters.numDirLightShadows); + array.push(parameters.numPointLightShadows); + array.push(parameters.numSpotLightShadows); + array.push(parameters.numSpotLightShadowsWithMaps); + array.push(parameters.numLightProbes); + array.push(parameters.shadowMapType); + array.push(parameters.toneMapping); + array.push(parameters.numClippingPlanes); + array.push(parameters.numClipIntersection); + array.push(parameters.depthPacking); + } + function getProgramCacheKeyBooleans(array, parameters) { + _programLayers.disableAll(); + if (parameters.supportsVertexTextures) + _programLayers.enable(0); + if (parameters.instancing) + _programLayers.enable(1); + if (parameters.instancingColor) + _programLayers.enable(2); + if (parameters.instancingMorph) + _programLayers.enable(3); + if (parameters.matcap) + _programLayers.enable(4); + if (parameters.envMap) + _programLayers.enable(5); + if (parameters.normalMapObjectSpace) + _programLayers.enable(6); + if (parameters.normalMapTangentSpace) + _programLayers.enable(7); + if (parameters.clearcoat) + _programLayers.enable(8); + if (parameters.iridescence) + _programLayers.enable(9); + if (parameters.alphaTest) + _programLayers.enable(10); + if (parameters.vertexColors) + _programLayers.enable(11); + if (parameters.vertexAlphas) + _programLayers.enable(12); + if (parameters.vertexUv1s) + _programLayers.enable(13); + if (parameters.vertexUv2s) + _programLayers.enable(14); + if (parameters.vertexUv3s) + _programLayers.enable(15); + if (parameters.vertexTangents) + _programLayers.enable(16); + if (parameters.anisotropy) + _programLayers.enable(17); + if (parameters.alphaHash) + _programLayers.enable(18); + if (parameters.batching) + _programLayers.enable(19); + if (parameters.dispersion) + _programLayers.enable(20); + if (parameters.batchingColor) + _programLayers.enable(21); + array.push(_programLayers.mask); + _programLayers.disableAll(); + if (parameters.fog) + _programLayers.enable(0); + if (parameters.useFog) + _programLayers.enable(1); + if (parameters.flatShading) + _programLayers.enable(2); + if (parameters.logarithmicDepthBuffer) + _programLayers.enable(3); + if (parameters.reverseDepthBuffer) + _programLayers.enable(4); + if (parameters.skinning) + _programLayers.enable(5); + if (parameters.morphTargets) + _programLayers.enable(6); + if (parameters.morphNormals) + _programLayers.enable(7); + if (parameters.morphColors) + _programLayers.enable(8); + if (parameters.premultipliedAlpha) + _programLayers.enable(9); + if (parameters.shadowMapEnabled) + _programLayers.enable(10); + if (parameters.doubleSided) + _programLayers.enable(11); + if (parameters.flipSided) + _programLayers.enable(12); + if (parameters.useDepthPacking) + _programLayers.enable(13); + if (parameters.dithering) + _programLayers.enable(14); + if (parameters.transmission) + _programLayers.enable(15); + if (parameters.sheen) + _programLayers.enable(16); + if (parameters.opaque) + _programLayers.enable(17); + if (parameters.pointsUvs) + _programLayers.enable(18); + if (parameters.decodeVideoTexture) + _programLayers.enable(19); + if (parameters.decodeVideoTextureEmissive) + _programLayers.enable(20); + if (parameters.alphaToCoverage) + _programLayers.enable(21); + array.push(_programLayers.mask); + } + function getUniforms(material) { + const shaderID = shaderIDs[material.type]; + let uniforms; + if (shaderID) { + const shader = ShaderLib[shaderID]; + uniforms = UniformsUtils.clone(shader.uniforms); + } else { + uniforms = material.uniforms; + } + return uniforms; + } + function acquireProgram(parameters, cacheKey) { + let program; + for (let p = 0, pl2 = programs.length;p < pl2; p++) { + const preexistingProgram = programs[p]; + if (preexistingProgram.cacheKey === cacheKey) { + program = preexistingProgram; + ++program.usedTimes; + break; + } + } + if (program === undefined) { + program = new WebGLProgram(renderer2, cacheKey, parameters, bindingStates); + programs.push(program); + } + return program; + } + function releaseProgram(program) { + if (--program.usedTimes === 0) { + const i = programs.indexOf(program); + programs[i] = programs[programs.length - 1]; + programs.pop(); + program.destroy(); + } + } + function releaseShaderCache(material) { + _customShaders.remove(material); + } + function dispose() { + _customShaders.dispose(); + } + return { + getParameters, + getProgramCacheKey, + getUniforms, + acquireProgram, + releaseProgram, + releaseShaderCache, + programs, + dispose + }; +} +function WebGLProperties() { + let properties = new WeakMap; + function has2(object) { + return properties.has(object); + } + function get(object) { + let map2 = properties.get(object); + if (map2 === undefined) { + map2 = {}; + properties.set(object, map2); + } + return map2; + } + function remove(object) { + properties.delete(object); + } + function update(object, key2, value2) { + properties.get(object)[key2] = value2; + } + function dispose() { + properties = new WeakMap; + } + return { + has: has2, + get, + remove, + update, + dispose + }; +} +function painterSortStable(a, b) { + if (a.groupOrder !== b.groupOrder) { + return a.groupOrder - b.groupOrder; + } else if (a.renderOrder !== b.renderOrder) { + return a.renderOrder - b.renderOrder; + } else if (a.material.id !== b.material.id) { + return a.material.id - b.material.id; + } else if (a.z !== b.z) { + return a.z - b.z; + } else { + return a.id - b.id; + } +} +function reversePainterSortStable(a, b) { + if (a.groupOrder !== b.groupOrder) { + return a.groupOrder - b.groupOrder; + } else if (a.renderOrder !== b.renderOrder) { + return a.renderOrder - b.renderOrder; + } else if (a.z !== b.z) { + return b.z - a.z; + } else { + return a.id - b.id; + } +} +function WebGLRenderList() { + const renderItems = []; + let renderItemsIndex = 0; + const opaque = []; + const transmissive = []; + const transparent = []; + function init() { + renderItemsIndex = 0; + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + } + function getNextRenderItem(object, geometry, material, groupOrder, z, group) { + let renderItem = renderItems[renderItemsIndex]; + if (renderItem === undefined) { + renderItem = { + id: object.id, + object, + geometry, + material, + groupOrder, + renderOrder: object.renderOrder, + z, + group + }; + renderItems[renderItemsIndex] = renderItem; + } else { + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + } + renderItemsIndex++; + return renderItem; + } + function push(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.push(renderItem); + } else if (material.transparent === true) { + transparent.push(renderItem); + } else { + opaque.push(renderItem); + } + } + function unshift(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.unshift(renderItem); + } else if (material.transparent === true) { + transparent.unshift(renderItem); + } else { + opaque.unshift(renderItem); + } + } + function sort(customOpaqueSort, customTransparentSort) { + if (opaque.length > 1) + opaque.sort(customOpaqueSort || painterSortStable); + if (transmissive.length > 1) + transmissive.sort(customTransparentSort || reversePainterSortStable); + if (transparent.length > 1) + transparent.sort(customTransparentSort || reversePainterSortStable); + } + function finish() { + for (let i = renderItemsIndex, il = renderItems.length;i < il; i++) { + const renderItem = renderItems[i]; + if (renderItem.id === null) + break; + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + } + } + return { + opaque, + transmissive, + transparent, + init, + push, + unshift, + finish, + sort + }; +} +function WebGLRenderLists() { + let lists = new WeakMap; + function get(scene, renderCallDepth) { + const listArray = lists.get(scene); + let list; + if (listArray === undefined) { + list = new WebGLRenderList; + lists.set(scene, [list]); + } else { + if (renderCallDepth >= listArray.length) { + list = new WebGLRenderList; + listArray.push(list); + } else { + list = listArray[renderCallDepth]; + } + } + return list; + } + function dispose() { + lists = new WeakMap; + } + return { + get, + dispose + }; +} +function UniformsCache() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== undefined) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + direction: new Vector3, + color: new Color + }; + break; + case "SpotLight": + uniforms = { + position: new Vector3, + direction: new Vector3, + color: new Color, + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + case "PointLight": + uniforms = { + position: new Vector3, + color: new Color, + distance: 0, + decay: 0 + }; + break; + case "HemisphereLight": + uniforms = { + direction: new Vector3, + skyColor: new Color, + groundColor: new Color + }; + break; + case "RectAreaLight": + uniforms = { + color: new Color, + position: new Vector3, + halfWidth: new Vector3, + halfHeight: new Vector3 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; +} +function ShadowUniformsCache() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== undefined) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2 + }; + break; + case "SpotLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2 + }; + break; + case "PointLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2, + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; +} +var nextVersion = 0; +function shadowCastingAndTexturingLightsFirst(lightA, lightB) { + return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0); +} +function WebGLLights(extensions) { + const cache = new UniformsCache; + const shadowCache = ShadowUniformsCache(); + const state = { + version: 0, + hash: { + directionalLength: -1, + pointLength: -1, + spotLength: -1, + rectAreaLength: -1, + hemiLength: -1, + numDirectionalShadows: -1, + numPointShadows: -1, + numSpotShadows: -1, + numSpotMaps: -1, + numLightProbes: -1 + }, + ambient: [0, 0, 0], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0, + numLightProbes: 0 + }; + for (let i = 0;i < 9; i++) + state.probe.push(new Vector3); + const vector3 = new Vector3; + const matrix4 = new Matrix4; + const matrix42 = new Matrix4; + function setup(lights) { + let r = 0, g = 0, b = 0; + for (let i = 0;i < 9; i++) + state.probe[i].set(0, 0, 0); + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + let numLightProbes = 0; + lights.sort(shadowCastingAndTexturingLightsFirst); + for (let i = 0, l = lights.length;i < l; i++) { + const light = lights[i]; + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null; + if (light.isAmbientLight) { + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; + } else if (light.isLightProbe) { + for (let j = 0;j < 9; j++) { + state.probe[j].addScaledVector(light.sh.coefficients[j], intensity); + } + numLightProbes++; + } else if (light.isDirectionalLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.directionalShadow[directionalLength] = shadowUniforms; + state.directionalShadowMap[directionalLength] = shadowMap; + state.directionalShadowMatrix[directionalLength] = light.shadow.matrix; + numDirectionalShadows++; + } + state.directional[directionalLength] = uniforms; + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = cache.get(light); + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.distance = distance; + uniforms.coneCos = Math.cos(light.angle); + uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra)); + uniforms.decay = light.decay; + state.spot[spotLength] = uniforms; + const shadow = light.shadow; + if (light.map) { + state.spotLightMap[numSpotMaps] = light.map; + numSpotMaps++; + shadow.updateMatrices(light); + if (light.castShadow) + numSpotShadowsWithMaps++; + } + state.spotLightMatrix[spotLength] = shadow.matrix; + if (light.castShadow) { + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.spotShadow[spotLength] = shadowUniforms; + state.spotShadowMap[spotLength] = shadowMap; + numSpotShadows++; + } + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = cache.get(light); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + state.rectArea[rectAreaLength] = uniforms; + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + state.pointShadow[pointLength] = shadowUniforms; + state.pointShadowMap[pointLength] = shadowMap; + state.pointShadowMatrix[pointLength] = light.shadow.matrix; + numPointShadows++; + } + state.point[pointLength] = uniforms; + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = cache.get(light); + uniforms.skyColor.copy(light.color).multiplyScalar(intensity); + uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity); + state.hemi[hemiLength] = uniforms; + hemiLength++; + } + } + if (rectAreaLength > 0) { + if (extensions.has("OES_texture_float_linear") === true) { + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + } else { + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + } + } + state.ambient[0] = r; + state.ambient[1] = g; + state.ambient[2] = b; + const hash = state.hash; + if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps || hash.numLightProbes !== numLightProbes) { + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + state.numLightProbes = numLightProbes; + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + hash.numLightProbes = numLightProbes; + state.version = nextVersion++; + } + } + function setupView(lights, camera) { + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + const viewMatrix = camera.matrixWorldInverse; + for (let i = 0, l = lights.length;i < l; i++) { + const light = lights[i]; + if (light.isDirectionalLight) { + const uniforms = state.directional[directionalLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = state.spot[spotLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = state.rectArea[rectAreaLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + matrix42.identity(); + matrix4.copy(light.matrixWorld); + matrix4.premultiply(viewMatrix); + matrix42.extractRotation(matrix4); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + uniforms.halfWidth.applyMatrix4(matrix42); + uniforms.halfHeight.applyMatrix4(matrix42); + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = state.point[pointLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = state.hemi[hemiLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + uniforms.direction.transformDirection(viewMatrix); + hemiLength++; + } + } + } + return { + setup, + setupView, + state + }; +} +function WebGLRenderState(extensions) { + const lights = new WebGLLights(extensions); + const lightsArray = []; + const shadowsArray = []; + function init(camera) { + state.camera = camera; + lightsArray.length = 0; + shadowsArray.length = 0; + } + function pushLight(light) { + lightsArray.push(light); + } + function pushShadow(shadowLight) { + shadowsArray.push(shadowLight); + } + function setupLights() { + lights.setup(lightsArray); + } + function setupLightsView(camera) { + lights.setupView(lightsArray, camera); + } + const state = { + lightsArray, + shadowsArray, + camera: null, + lights, + transmissionRenderTarget: {} + }; + return { + init, + state, + setupLights, + setupLightsView, + pushLight, + pushShadow + }; +} +function WebGLRenderStates(extensions) { + let renderStates = new WeakMap; + function get(scene, renderCallDepth = 0) { + const renderStateArray = renderStates.get(scene); + let renderState; + if (renderStateArray === undefined) { + renderState = new WebGLRenderState(extensions); + renderStates.set(scene, [renderState]); + } else { + if (renderCallDepth >= renderStateArray.length) { + renderState = new WebGLRenderState(extensions); + renderStateArray.push(renderState); + } else { + renderState = renderStateArray[renderCallDepth]; + } + } + return renderState; + } + function dispose() { + renderStates = new WeakMap; + } + return { + get, + dispose + }; +} +var vertex = `void main() { + gl_Position = vec4( position, 1.0 ); +}`; +var fragment = `uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`; +function WebGLShadowMap(renderer2, objects, capabilities) { + let _frustum2 = new Frustum; + const _shadowMapSize = new Vector2, _viewportSize = new Vector2, _viewport = new Vector4, _depthMaterial = new MeshDepthMaterial({ depthPacking: RGBADepthPacking }), _distanceMaterial = new MeshDistanceMaterial, _materialCache = {}, _maxTextureSize = capabilities.maxTextureSize; + const shadowSide = { [FrontSide]: BackSide, [BackSide]: FrontSide, [DoubleSide]: DoubleSide }; + const shadowMaterialVertical = new ShaderMaterial({ + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2 }, + radius: { value: 4 } + }, + vertexShader: vertex, + fragmentShader: fragment + }); + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + const fullScreenTri = new BufferGeometry; + fullScreenTri.setAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3)); + const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); + const scope = this; + this.enabled = false; + this.autoUpdate = true; + this.needsUpdate = false; + this.type = PCFShadowMap; + let _previousType = this.type; + this.render = function(lights, scene, camera) { + if (scope.enabled === false) + return; + if (scope.autoUpdate === false && scope.needsUpdate === false) + return; + if (lights.length === 0) + return; + const currentRenderTarget = renderer2.getRenderTarget(); + const activeCubeFace = renderer2.getActiveCubeFace(); + const activeMipmapLevel = renderer2.getActiveMipmapLevel(); + const _state = renderer2.state; + _state.setBlending(NoBlending); + _state.buffers.color.setClear(1, 1, 1, 1); + _state.buffers.depth.setTest(true); + _state.setScissorTest(false); + const toVSM = _previousType !== VSMShadowMap && this.type === VSMShadowMap; + const fromVSM = _previousType === VSMShadowMap && this.type !== VSMShadowMap; + for (let i = 0, il = lights.length;i < il; i++) { + const light = lights[i]; + const shadow = light.shadow; + if (shadow === undefined) { + console.warn("THREE.WebGLShadowMap:", light, "has no shadow."); + continue; + } + if (shadow.autoUpdate === false && shadow.needsUpdate === false) + continue; + _shadowMapSize.copy(shadow.mapSize); + const shadowFrameExtents = shadow.getFrameExtents(); + _shadowMapSize.multiply(shadowFrameExtents); + _viewportSize.copy(shadow.mapSize); + if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) { + if (_shadowMapSize.x > _maxTextureSize) { + _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + } + if (_shadowMapSize.y > _maxTextureSize) { + _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + } + } + if (shadow.map === null || toVSM === true || fromVSM === true) { + const pars = this.type !== VSMShadowMap ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; + if (shadow.map !== null) { + shadow.map.dispose(); + } + shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars); + shadow.map.texture.name = light.name + ".shadowMap"; + shadow.camera.updateProjectionMatrix(); + } + renderer2.setRenderTarget(shadow.map); + renderer2.clear(); + const viewportCount = shadow.getViewportCount(); + for (let vp = 0;vp < viewportCount; vp++) { + const viewport = shadow.getViewport(vp); + _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w); + _state.viewport(_viewport); + shadow.updateMatrices(light, vp); + _frustum2 = shadow.getFrustum(); + renderObject(scene, camera, shadow.camera, light, this.type); + } + if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) { + VSMPass(shadow, camera); + } + shadow.needsUpdate = false; + } + _previousType = this.type; + scope.needsUpdate = false; + renderer2.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel); + }; + function VSMPass(shadow, camera) { + const geometry = objects.update(fullScreenMesh); + if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) { + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + } + if (shadow.mapPass === null) { + shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y); + } + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + renderer2.setRenderTarget(shadow.mapPass); + renderer2.clear(); + renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + renderer2.setRenderTarget(shadow.map); + renderer2.clear(); + renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null); + } + function getDepthMaterial(object, material, light, type) { + let result = null; + const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial; + if (customMaterial !== undefined) { + result = customMaterial; + } else { + result = light.isPointLight === true ? _distanceMaterial : _depthMaterial; + if (renderer2.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0 || material.map && material.alphaTest > 0) { + const keyA = result.uuid, keyB = material.uuid; + let materialsForVariant = _materialCache[keyA]; + if (materialsForVariant === undefined) { + materialsForVariant = {}; + _materialCache[keyA] = materialsForVariant; + } + let cachedMaterial = materialsForVariant[keyB]; + if (cachedMaterial === undefined) { + cachedMaterial = result.clone(); + materialsForVariant[keyB] = cachedMaterial; + material.addEventListener("dispose", onMaterialDispose); + } + result = cachedMaterial; + } + } + result.visible = material.visible; + result.wireframe = material.wireframe; + if (type === VSMShadowMap) { + result.side = material.shadowSide !== null ? material.shadowSide : material.side; + } else { + result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side]; + } + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.map = material.map; + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + if (light.isPointLight === true && result.isMeshDistanceMaterial === true) { + const materialProperties = renderer2.properties.get(result); + materialProperties.light = light; + } + return result; + } + function renderObject(object, camera, shadowCamera, light, type) { + if (object.visible === false) + return; + const visible = object.layers.test(camera.layers); + if (visible && (object.isMesh || object.isLine || object.isPoints)) { + if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum2.intersectsObject(object))) { + object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld); + const geometry = objects.update(object); + const material = object.material; + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let k2 = 0, kl = groups.length;k2 < kl; k2++) { + const group = groups[k2]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + const depthMaterial = getDepthMaterial(object, groupMaterial, light, type); + object.onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group); + object.onAfterShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + } + } + } else if (material.visible) { + const depthMaterial = getDepthMaterial(object, material, light, type); + object.onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null); + object.onAfterShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + } + } + } + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + renderObject(children[i], camera, shadowCamera, light, type); + } + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + for (const id in _materialCache) { + const cache = _materialCache[id]; + const uuid = event.target.uuid; + if (uuid in cache) { + const shadowMaterial = cache[uuid]; + shadowMaterial.dispose(); + delete cache[uuid]; + } + } + } +} +var reversedFuncs = { + [NeverDepth]: AlwaysDepth, + [LessDepth]: GreaterDepth, + [EqualDepth]: NotEqualDepth, + [LessEqualDepth]: GreaterEqualDepth, + [AlwaysDepth]: NeverDepth, + [GreaterDepth]: LessDepth, + [NotEqualDepth]: EqualDepth, + [GreaterEqualDepth]: LessEqualDepth +}; +function WebGLState(gl, extensions) { + function ColorBuffer() { + let locked = false; + const color = new Vector4; + let currentColorMask = null; + const currentColorClear = new Vector4(0, 0, 0, 0); + return { + setMask: function(colorMask) { + if (currentColorMask !== colorMask && !locked) { + gl.colorMask(colorMask, colorMask, colorMask, colorMask); + currentColorMask = colorMask; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(r, g, b, a, premultipliedAlpha) { + if (premultipliedAlpha === true) { + r *= a; + g *= a; + b *= a; + } + color.set(r, g, b, a); + if (currentColorClear.equals(color) === false) { + gl.clearColor(r, g, b, a); + currentColorClear.copy(color); + } + }, + reset: function() { + locked = false; + currentColorMask = null; + currentColorClear.set(-1, 0, 0, 0); + } + }; + } + function DepthBuffer() { + let locked = false; + let reversed = false; + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + return { + setReversed: function(value2) { + if (reversed !== value2) { + const ext = extensions.get("EXT_clip_control"); + if (reversed) { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT); + } else { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT); + } + const oldDepth = currentDepthClear; + currentDepthClear = null; + this.setClear(oldDepth); + } + reversed = value2; + }, + getReversed: function() { + return reversed; + }, + setTest: function(depthTest) { + if (depthTest) { + enable(gl.DEPTH_TEST); + } else { + disable(gl.DEPTH_TEST); + } + }, + setMask: function(depthMask) { + if (currentDepthMask !== depthMask && !locked) { + gl.depthMask(depthMask); + currentDepthMask = depthMask; + } + }, + setFunc: function(depthFunc) { + if (reversed) + depthFunc = reversedFuncs[depthFunc]; + if (currentDepthFunc !== depthFunc) { + switch (depthFunc) { + case NeverDepth: + gl.depthFunc(gl.NEVER); + break; + case AlwaysDepth: + gl.depthFunc(gl.ALWAYS); + break; + case LessDepth: + gl.depthFunc(gl.LESS); + break; + case LessEqualDepth: + gl.depthFunc(gl.LEQUAL); + break; + case EqualDepth: + gl.depthFunc(gl.EQUAL); + break; + case GreaterEqualDepth: + gl.depthFunc(gl.GEQUAL); + break; + case GreaterDepth: + gl.depthFunc(gl.GREATER); + break; + case NotEqualDepth: + gl.depthFunc(gl.NOTEQUAL); + break; + default: + gl.depthFunc(gl.LEQUAL); + } + currentDepthFunc = depthFunc; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(depth) { + if (currentDepthClear !== depth) { + if (reversed) { + depth = 1 - depth; + } + gl.clearDepth(depth); + currentDepthClear = depth; + } + }, + reset: function() { + locked = false; + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + reversed = false; + } + }; + } + function StencilBuffer() { + let locked = false; + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + return { + setTest: function(stencilTest) { + if (!locked) { + if (stencilTest) { + enable(gl.STENCIL_TEST); + } else { + disable(gl.STENCIL_TEST); + } + } + }, + setMask: function(stencilMask) { + if (currentStencilMask !== stencilMask && !locked) { + gl.stencilMask(stencilMask); + currentStencilMask = stencilMask; + } + }, + setFunc: function(stencilFunc, stencilRef, stencilMask) { + if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) { + gl.stencilFunc(stencilFunc, stencilRef, stencilMask); + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + } + }, + setOp: function(stencilFail, stencilZFail, stencilZPass) { + if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) { + gl.stencilOp(stencilFail, stencilZFail, stencilZPass); + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(stencil) { + if (currentStencilClear !== stencil) { + gl.clearStencil(stencil); + currentStencilClear = stencil; + } + }, + reset: function() { + locked = false; + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + } + }; + } + const colorBuffer = new ColorBuffer; + const depthBuffer = new DepthBuffer; + const stencilBuffer = new StencilBuffer; + const uboBindings = new WeakMap; + const uboProgramMap = new WeakMap; + let enabledCapabilities = {}; + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap; + let defaultDrawbuffers = []; + let currentProgram = null; + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentBlendColor = new Color(0, 0, 0); + let currentBlendAlpha = 0; + let currentPremultipledAlpha = false; + let currentFlipSided = null; + let currentCullFace = null; + let currentLineWidth = null; + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter(gl.VERSION); + if (glVersion.indexOf("WebGL") !== -1) { + version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 1; + } else if (glVersion.indexOf("OpenGL ES") !== -1) { + version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 2; + } + let currentTextureSlot = null; + let currentBoundTextures = {}; + const scissorParam = gl.getParameter(gl.SCISSOR_BOX); + const viewportParam = gl.getParameter(gl.VIEWPORT); + const currentScissor = new Vector4().fromArray(scissorParam); + const currentViewport = new Vector4().fromArray(viewportParam); + function createTexture(type, target, count, dimensions) { + const data2 = new Uint8Array(4); + const texture = gl.createTexture(); + gl.bindTexture(type, texture); + gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + for (let i = 0;i < count; i++) { + if (type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY) { + gl.texImage3D(target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data2); + } else { + gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data2); + } + } + return texture; + } + const emptyTextures = {}; + emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1); + emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); + emptyTextures[gl.TEXTURE_2D_ARRAY] = createTexture(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1); + emptyTextures[gl.TEXTURE_3D] = createTexture(gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1); + colorBuffer.setClear(0, 0, 0, 1); + depthBuffer.setClear(1); + stencilBuffer.setClear(0); + enable(gl.DEPTH_TEST); + depthBuffer.setFunc(LessEqualDepth); + setFlipSided(false); + setCullFace(CullFaceBack); + enable(gl.CULL_FACE); + setBlending(NoBlending); + function enable(id) { + if (enabledCapabilities[id] !== true) { + gl.enable(id); + enabledCapabilities[id] = true; + } + } + function disable(id) { + if (enabledCapabilities[id] !== false) { + gl.disable(id); + enabledCapabilities[id] = false; + } + } + function bindFramebuffer(target, framebuffer) { + if (currentBoundFramebuffers[target] !== framebuffer) { + gl.bindFramebuffer(target, framebuffer); + currentBoundFramebuffers[target] = framebuffer; + if (target === gl.DRAW_FRAMEBUFFER) { + currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer; + } + if (target === gl.FRAMEBUFFER) { + currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer; + } + return true; + } + return false; + } + function drawBuffers(renderTarget, framebuffer) { + let drawBuffers2 = defaultDrawbuffers; + let needsUpdate = false; + if (renderTarget) { + drawBuffers2 = currentDrawbuffers.get(framebuffer); + if (drawBuffers2 === undefined) { + drawBuffers2 = []; + currentDrawbuffers.set(framebuffer, drawBuffers2); + } + const textures = renderTarget.textures; + if (drawBuffers2.length !== textures.length || drawBuffers2[0] !== gl.COLOR_ATTACHMENT0) { + for (let i = 0, il = textures.length;i < il; i++) { + drawBuffers2[i] = gl.COLOR_ATTACHMENT0 + i; + } + drawBuffers2.length = textures.length; + needsUpdate = true; + } + } else { + if (drawBuffers2[0] !== gl.BACK) { + drawBuffers2[0] = gl.BACK; + needsUpdate = true; + } + } + if (needsUpdate) { + gl.drawBuffers(drawBuffers2); + } + } + function useProgram(program) { + if (currentProgram !== program) { + gl.useProgram(program); + currentProgram = program; + return true; + } + return false; + } + const equationToGL = { + [AddEquation]: gl.FUNC_ADD, + [SubtractEquation]: gl.FUNC_SUBTRACT, + [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT + }; + equationToGL[MinEquation] = gl.MIN; + equationToGL[MaxEquation] = gl.MAX; + const factorToGL = { + [ZeroFactor]: gl.ZERO, + [OneFactor]: gl.ONE, + [SrcColorFactor]: gl.SRC_COLOR, + [SrcAlphaFactor]: gl.SRC_ALPHA, + [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE, + [DstColorFactor]: gl.DST_COLOR, + [DstAlphaFactor]: gl.DST_ALPHA, + [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR, + [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA, + [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR, + [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA, + [ConstantColorFactor]: gl.CONSTANT_COLOR, + [OneMinusConstantColorFactor]: gl.ONE_MINUS_CONSTANT_COLOR, + [ConstantAlphaFactor]: gl.CONSTANT_ALPHA, + [OneMinusConstantAlphaFactor]: gl.ONE_MINUS_CONSTANT_ALPHA + }; + function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha) { + if (blending === NoBlending) { + if (currentBlendingEnabled === true) { + disable(gl.BLEND); + currentBlendingEnabled = false; + } + return; + } + if (currentBlendingEnabled === false) { + enable(gl.BLEND); + currentBlendingEnabled = true; + } + if (blending !== CustomBlending) { + if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) { + if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) { + gl.blendEquation(gl.FUNC_ADD); + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; + } + if (premultipliedAlpha) { + switch (blending) { + case NormalBlending: + gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending: + gl.blendFunc(gl.ONE, gl.ONE); + break; + case SubtractiveBlending: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending: + gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } else { + switch (blending) { + case NormalBlending: + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending: + gl.blendFunc(gl.SRC_ALPHA, gl.ONE); + break; + case SubtractiveBlending: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending: + gl.blendFunc(gl.ZERO, gl.SRC_COLOR); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor.set(0, 0, 0); + currentBlendAlpha = 0; + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + } + return; + } + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) { + gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]); + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + } + if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) { + gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]); + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + } + if (blendColor.equals(currentBlendColor) === false || blendAlpha !== currentBlendAlpha) { + gl.blendColor(blendColor.r, blendColor.g, blendColor.b, blendAlpha); + currentBlendColor.copy(blendColor); + currentBlendAlpha = blendAlpha; + } + currentBlending = blending; + currentPremultipledAlpha = false; + } + function setMaterial(material, frontFaceCW) { + material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE); + let flipSided = material.side === BackSide; + if (frontFaceCW) + flipSided = !flipSided; + setFlipSided(flipSided); + material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha); + depthBuffer.setFunc(material.depthFunc); + depthBuffer.setTest(material.depthTest); + depthBuffer.setMask(material.depthWrite); + colorBuffer.setMask(material.colorWrite); + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest(stencilWrite); + if (stencilWrite) { + stencilBuffer.setMask(material.stencilWriteMask); + stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask); + stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass); + } + setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits); + material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + } + function setFlipSided(flipSided) { + if (currentFlipSided !== flipSided) { + if (flipSided) { + gl.frontFace(gl.CW); + } else { + gl.frontFace(gl.CCW); + } + currentFlipSided = flipSided; + } + } + function setCullFace(cullFace) { + if (cullFace !== CullFaceNone) { + enable(gl.CULL_FACE); + if (cullFace !== currentCullFace) { + if (cullFace === CullFaceBack) { + gl.cullFace(gl.BACK); + } else if (cullFace === CullFaceFront) { + gl.cullFace(gl.FRONT); + } else { + gl.cullFace(gl.FRONT_AND_BACK); + } + } + } else { + disable(gl.CULL_FACE); + } + currentCullFace = cullFace; + } + function setLineWidth(width2) { + if (width2 !== currentLineWidth) { + if (lineWidthAvailable) + gl.lineWidth(width2); + currentLineWidth = width2; + } + } + function setPolygonOffset(polygonOffset, factor, units) { + if (polygonOffset) { + enable(gl.POLYGON_OFFSET_FILL); + if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) { + gl.polygonOffset(factor, units); + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + } + } else { + disable(gl.POLYGON_OFFSET_FILL); + } + } + function setScissorTest(scissorTest) { + if (scissorTest) { + enable(gl.SCISSOR_TEST); + } else { + disable(gl.SCISSOR_TEST); + } + } + function activeTexture(webglSlot) { + if (webglSlot === undefined) + webglSlot = gl.TEXTURE0 + maxTextures - 1; + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + } + function bindTexture(webglType, webglTexture, webglSlot) { + if (webglSlot === undefined) { + if (currentTextureSlot === null) { + webglSlot = gl.TEXTURE0 + maxTextures - 1; + } else { + webglSlot = currentTextureSlot; + } + } + let boundTexture = currentBoundTextures[webglSlot]; + if (boundTexture === undefined) { + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[webglSlot] = boundTexture; + } + if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) { + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]); + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + } + } + function unbindTexture() { + const boundTexture = currentBoundTextures[currentTextureSlot]; + if (boundTexture !== undefined && boundTexture.type !== undefined) { + gl.bindTexture(boundTexture.type, null); + boundTexture.type = undefined; + boundTexture.texture = undefined; + } + } + function compressedTexImage2D() { + try { + gl.compressedTexImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexImage3D() { + try { + gl.compressedTexImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage2D() { + try { + gl.texSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage3D() { + try { + gl.texSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage2D() { + try { + gl.compressedTexSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage3D() { + try { + gl.compressedTexSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage2D() { + try { + gl.texStorage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage3D() { + try { + gl.texStorage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage2D() { + try { + gl.texImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage3D() { + try { + gl.texImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function scissor(scissor2) { + if (currentScissor.equals(scissor2) === false) { + gl.scissor(scissor2.x, scissor2.y, scissor2.z, scissor2.w); + currentScissor.copy(scissor2); + } + } + function viewport(viewport2) { + if (currentViewport.equals(viewport2) === false) { + gl.viewport(viewport2.x, viewport2.y, viewport2.z, viewport2.w); + currentViewport.copy(viewport2); + } + } + function updateUBOMapping(uniformsGroup, program) { + let mapping = uboProgramMap.get(program); + if (mapping === undefined) { + mapping = new WeakMap; + uboProgramMap.set(program, mapping); + } + let blockIndex = mapping.get(uniformsGroup); + if (blockIndex === undefined) { + blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name); + mapping.set(uniformsGroup, blockIndex); + } + } + function uniformBlockBinding(uniformsGroup, program) { + const mapping = uboProgramMap.get(program); + const blockIndex = mapping.get(uniformsGroup); + if (uboBindings.get(program) !== blockIndex) { + gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex); + uboBindings.set(program, blockIndex); + } + } + function reset() { + gl.disable(gl.BLEND); + gl.disable(gl.CULL_FACE); + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.POLYGON_OFFSET_FILL); + gl.disable(gl.SCISSOR_TEST); + gl.disable(gl.STENCIL_TEST); + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ZERO); + gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO); + gl.blendColor(0, 0, 0, 0); + gl.colorMask(true, true, true, true); + gl.clearColor(0, 0, 0, 0); + gl.depthMask(true); + gl.depthFunc(gl.LESS); + depthBuffer.setReversed(false); + gl.clearDepth(1); + gl.stencilMask(4294967295); + gl.stencilFunc(gl.ALWAYS, 0, 4294967295); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + gl.clearStencil(0); + gl.cullFace(gl.BACK); + gl.frontFace(gl.CCW); + gl.polygonOffset(0, 0); + gl.activeTexture(gl.TEXTURE0); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); + gl.useProgram(null); + gl.lineWidth(1); + gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); + gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); + enabledCapabilities = {}; + currentTextureSlot = null; + currentBoundTextures = {}; + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap; + defaultDrawbuffers = []; + currentProgram = null; + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor = new Color(0, 0, 0); + currentBlendAlpha = 0; + currentPremultipledAlpha = false; + currentFlipSided = null; + currentCullFace = null; + currentLineWidth = null; + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height); + currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height); + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + } + return { + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + enable, + disable, + bindFramebuffer, + drawBuffers, + useProgram, + setBlending, + setMaterial, + setFlipSided, + setCullFace, + setLineWidth, + setPolygonOffset, + setScissorTest, + activeTexture, + bindTexture, + unbindTexture, + compressedTexImage2D, + compressedTexImage3D, + texImage2D, + texImage3D, + updateUBOMapping, + uniformBlockBinding, + texStorage2D, + texStorage3D, + texSubImage2D, + texSubImage3D, + compressedTexSubImage2D, + compressedTexSubImage3D, + scissor, + viewport, + reset + }; +} +function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) { + const multisampledRTTExt = extensions.has("WEBGL_multisampled_render_to_texture") ? extensions.get("WEBGL_multisampled_render_to_texture") : null; + const supportsInvalidateFramebuffer = typeof navigator === "undefined" ? false : /OculusBrowser/g.test(navigator.userAgent); + const _imageDimensions = new Vector2; + const _videoTextures = new WeakMap; + let _canvas2; + const _sources = new WeakMap; + let useOffscreenCanvas = false; + try { + useOffscreenCanvas = typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null; + } catch (err) { + } + function createCanvas(width2, height2) { + return useOffscreenCanvas ? new OffscreenCanvas(width2, height2) : createElementNS("canvas"); + } + function resizeImage(image, needsNewCanvas, maxSize) { + let scale2 = 1; + const dimensions = getDimensions(image); + if (dimensions.width > maxSize || dimensions.height > maxSize) { + scale2 = maxSize / Math.max(dimensions.width, dimensions.height); + } + if (scale2 < 1) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + const width2 = Math.floor(scale2 * dimensions.width); + const height2 = Math.floor(scale2 * dimensions.height); + if (_canvas2 === undefined) + _canvas2 = createCanvas(width2, height2); + const canvas = needsNewCanvas ? createCanvas(width2, height2) : _canvas2; + canvas.width = width2; + canvas.height = height2; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, width2, height2); + console.warn("THREE.WebGLRenderer: Texture has been resized from (" + dimensions.width + "x" + dimensions.height + ") to (" + width2 + "x" + height2 + ")."); + return canvas; + } else { + if ("data" in image) { + console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + dimensions.width + "x" + dimensions.height + ")."); + } + return image; + } + } + return image; + } + function textureNeedsGenerateMipmaps(texture) { + return texture.generateMipmaps; + } + function generateMipmap(target) { + _gl.generateMipmap(target); + } + function getTargetType(texture) { + if (texture.isWebGLCubeRenderTarget) + return _gl.TEXTURE_CUBE_MAP; + if (texture.isWebGL3DRenderTarget) + return _gl.TEXTURE_3D; + if (texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture) + return _gl.TEXTURE_2D_ARRAY; + return _gl.TEXTURE_2D; + } + function getInternalFormat(internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false) { + if (internalFormatName !== null) { + if (_gl[internalFormatName] !== undefined) + return _gl[internalFormatName]; + console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + internalFormatName + "'"); + } + let internalFormat = glFormat; + if (glFormat === _gl.RED) { + if (glType === _gl.FLOAT) + internalFormat = _gl.R32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.R16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.R8; + } + if (glFormat === _gl.RED_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.R8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.R16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.R32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.R8I; + if (glType === _gl.SHORT) + internalFormat = _gl.R16I; + if (glType === _gl.INT) + internalFormat = _gl.R32I; + } + if (glFormat === _gl.RG) { + if (glType === _gl.FLOAT) + internalFormat = _gl.RG32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.RG16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RG8; + } + if (glFormat === _gl.RG_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RG8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RG16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RG32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RG8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RG16I; + if (glType === _gl.INT) + internalFormat = _gl.RG32I; + } + if (glFormat === _gl.RGB_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RGB8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RGB16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RGB32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RGB8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RGB16I; + if (glType === _gl.INT) + internalFormat = _gl.RGB32I; + } + if (glFormat === _gl.RGBA_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RGBA8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RGBA16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RGBA32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RGBA8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RGBA16I; + if (glType === _gl.INT) + internalFormat = _gl.RGBA32I; + } + if (glFormat === _gl.RGB) { + if (glType === _gl.UNSIGNED_INT_5_9_9_9_REV) + internalFormat = _gl.RGB9_E5; + } + if (glFormat === _gl.RGBA) { + const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer(colorSpace); + if (glType === _gl.FLOAT) + internalFormat = _gl.RGBA32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.RGBA16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = transfer === SRGBTransfer ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) + internalFormat = _gl.RGBA4; + if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) + internalFormat = _gl.RGB5_A1; + } + if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) { + extensions.get("EXT_color_buffer_float"); + } + return internalFormat; + } + function getInternalDepthFormat(useStencil, depthType) { + let glInternalFormat; + if (useStencil) { + if (depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + } else if (depthType === FloatType) { + glInternalFormat = _gl.DEPTH32F_STENCIL8; + } else if (depthType === UnsignedShortType) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment."); + } + } else { + if (depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type) { + glInternalFormat = _gl.DEPTH_COMPONENT24; + } else if (depthType === FloatType) { + glInternalFormat = _gl.DEPTH_COMPONENT32F; + } else if (depthType === UnsignedShortType) { + glInternalFormat = _gl.DEPTH_COMPONENT16; + } + } + return glInternalFormat; + } + function getMipLevels(texture, image) { + if (textureNeedsGenerateMipmaps(texture) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) { + return Math.log2(Math.max(image.width, image.height)) + 1; + } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) { + return texture.mipmaps.length; + } else if (texture.isCompressedTexture && Array.isArray(texture.image)) { + return image.mipmaps.length; + } else { + return 1; + } + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + deallocateTexture(texture); + if (texture.isVideoTexture) { + _videoTextures.delete(texture); + } + } + function onRenderTargetDispose(event) { + const renderTarget = event.target; + renderTarget.removeEventListener("dispose", onRenderTargetDispose); + deallocateRenderTarget(renderTarget); + } + function deallocateTexture(texture) { + const textureProperties = properties.get(texture); + if (textureProperties.__webglInit === undefined) + return; + const source = texture.source; + const webglTextures = _sources.get(source); + if (webglTextures) { + const webglTexture = webglTextures[textureProperties.__cacheKey]; + webglTexture.usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + if (Object.keys(webglTextures).length === 0) { + _sources.delete(source); + } + } + properties.remove(texture); + } + function deleteTexture(texture) { + const textureProperties = properties.get(texture); + _gl.deleteTexture(textureProperties.__webglTexture); + const source = texture.source; + const webglTextures = _sources.get(source); + delete webglTextures[textureProperties.__cacheKey]; + info.memory.textures--; + } + function deallocateRenderTarget(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTarget.depthTexture) { + renderTarget.depthTexture.dispose(); + properties.remove(renderTarget.depthTexture); + } + if (renderTarget.isWebGLCubeRenderTarget) { + for (let i = 0;i < 6; i++) { + if (Array.isArray(renderTargetProperties.__webglFramebuffer[i])) { + for (let level = 0;level < renderTargetProperties.__webglFramebuffer[i].length; level++) + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i][level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]); + } + if (renderTargetProperties.__webglDepthbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]); + } + } else { + if (Array.isArray(renderTargetProperties.__webglFramebuffer)) { + for (let level = 0;level < renderTargetProperties.__webglFramebuffer.length; level++) + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer); + } + if (renderTargetProperties.__webglDepthbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer); + if (renderTargetProperties.__webglMultisampledFramebuffer) + _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer); + if (renderTargetProperties.__webglColorRenderbuffer) { + for (let i = 0;i < renderTargetProperties.__webglColorRenderbuffer.length; i++) { + if (renderTargetProperties.__webglColorRenderbuffer[i]) + _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]); + } + } + if (renderTargetProperties.__webglDepthRenderbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer); + } + const textures = renderTarget.textures; + for (let i = 0, il = textures.length;i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture) { + _gl.deleteTexture(attachmentProperties.__webglTexture); + info.memory.textures--; + } + properties.remove(textures[i]); + } + properties.remove(renderTarget); + } + let textureUnits = 0; + function resetTextureUnits() { + textureUnits = 0; + } + function allocateTextureUnit() { + const textureUnit = textureUnits; + if (textureUnit >= capabilities.maxTextures) { + console.warn("THREE.WebGLTextures: Trying to use " + textureUnit + " texture units while this GPU supports only " + capabilities.maxTextures); + } + textureUnits += 1; + return textureUnit; + } + function getTextureCacheKey(texture) { + const array = []; + array.push(texture.wrapS); + array.push(texture.wrapT); + array.push(texture.wrapR || 0); + array.push(texture.magFilter); + array.push(texture.minFilter); + array.push(texture.anisotropy); + array.push(texture.internalFormat); + array.push(texture.format); + array.push(texture.type); + array.push(texture.generateMipmaps); + array.push(texture.premultiplyAlpha); + array.push(texture.flipY); + array.push(texture.unpackAlignment); + array.push(texture.colorSpace); + return array.join(); + } + function setTexture2D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isVideoTexture) + updateVideoTexture(texture); + if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { + const image = texture.image; + if (image === null) { + console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found."); + } else if (image.complete === false) { + console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete"); + } else { + uploadTexture(textureProperties, texture, slot); + return; + } + } + state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture2DArray(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture3D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTextureCube(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadCubeTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + const wrappingToGL = { + [RepeatWrapping]: _gl.REPEAT, + [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE, + [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT + }; + const filterToGL = { + [NearestFilter]: _gl.NEAREST, + [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST, + [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR, + [LinearFilter]: _gl.LINEAR, + [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST, + [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR + }; + const compareToGL = { + [NeverCompare]: _gl.NEVER, + [AlwaysCompare]: _gl.ALWAYS, + [LessCompare]: _gl.LESS, + [LessEqualCompare]: _gl.LEQUAL, + [EqualCompare]: _gl.EQUAL, + [GreaterEqualCompare]: _gl.GEQUAL, + [GreaterCompare]: _gl.GREATER, + [NotEqualCompare]: _gl.NOTEQUAL + }; + function setTextureParameters(textureType, texture) { + if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false && (texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter || texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter)) { + console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."); + } + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]); + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]); + if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) { + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]); + } + _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]); + _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]); + if (texture.compareFunction) { + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE); + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[texture.compareFunction]); + } + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + if (texture.magFilter === NearestFilter) + return; + if (texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter) + return; + if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false) + return; + if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy())); + properties.get(texture).__currentAnisotropy = texture.anisotropy; + } + } + } + function initTexture(textureProperties, texture) { + let forceUpload = false; + if (textureProperties.__webglInit === undefined) { + textureProperties.__webglInit = true; + texture.addEventListener("dispose", onTextureDispose); + } + const source = texture.source; + let webglTextures = _sources.get(source); + if (webglTextures === undefined) { + webglTextures = {}; + _sources.set(source, webglTextures); + } + const textureCacheKey = getTextureCacheKey(texture); + if (textureCacheKey !== textureProperties.__cacheKey) { + if (webglTextures[textureCacheKey] === undefined) { + webglTextures[textureCacheKey] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + info.memory.textures++; + forceUpload = true; + } + webglTextures[textureCacheKey].usedTimes++; + const webglTexture = webglTextures[textureProperties.__cacheKey]; + if (webglTexture !== undefined) { + webglTextures[textureProperties.__cacheKey].usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + } + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[textureCacheKey].texture; + } + return forceUpload; + } + function uploadTexture(textureProperties, texture, slot) { + let textureType = _gl.TEXTURE_2D; + if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) + textureType = _gl.TEXTURE_2D_ARRAY; + if (texture.isData3DTexture) + textureType = _gl.TEXTURE_3D; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + let image = resizeImage(texture.image, false, capabilities.maxTextureSize); + image = verifyColorSpace(texture, image); + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + let glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture); + setTextureParameters(textureType, texture); + let mipmap; + const mipmaps = texture.mipmaps; + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; + const dataReady = source.dataReady; + const levels = getMipLevels(texture, image); + if (texture.isDepthTexture) { + glInternalFormat = getInternalDepthFormat(texture.format === DepthStencilFormat, texture.type); + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height); + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null); + } + } + } else if (texture.isDataTexture) { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data); + } + } + } else if (texture.isCompressedTexture) { + if (texture.isCompressedArrayTexture) { + if (useTexStorage && allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength(mipmap.width, mipmap.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = mipmap.data.subarray(layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT, (layerIndex + 1) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT); + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData); + } + texture.clearLayerUpdates(); + } else { + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data); + } + } + } else { + state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data); + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data); + } + } + } + } else { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else if (texture.isDataArrayTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength(image.width, image.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = image.data.subarray(layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT, (layerIndex + 1) * layerByteLength / image.data.BYTES_PER_ELEMENT); + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData); + } + texture.clearLayerUpdates(); + } else { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isData3DTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } else { + state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isFramebufferTexture) { + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } else { + let { width: width2, height: height2 } = image; + for (let i = 0;i < levels; i++) { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width2, height2, 0, glFormat, glType, null); + width2 >>= 1; + height2 >>= 1; + } + } + } + } else { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + const dimensions = getDimensions(mipmaps[0]); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + const dimensions = getDimensions(image); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image); + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(textureType); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) + texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function uploadCubeTexture(textureProperties, texture, slot) { + if (texture.image.length !== 6) + return; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture; + const isDataTexture = texture.image[0] && texture.image[0].isDataTexture; + const cubeImage = []; + for (let i = 0;i < 6; i++) { + if (!isCompressed && !isDataTexture) { + cubeImage[i] = resizeImage(texture.image[i], true, capabilities.maxCubemapSize); + } else { + cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i]; + } + cubeImage[i] = verifyColorSpace(texture, cubeImage[i]); + } + const image = cubeImage[0], glFormat = utils.convert(texture.format, texture.colorSpace), glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; + const dataReady = source.dataReady; + let levels = getMipLevels(texture, image); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + let mipmaps; + if (isCompressed) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height); + } + for (let i = 0;i < 6; i++) { + mipmaps = cubeImage[i].mipmaps; + for (let j = 0;j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else { + mipmaps = texture.mipmaps; + if (useTexStorage && allocateMemory) { + if (mipmaps.length > 0) + levels++; + const dimensions = getDimensions(cubeImage[0]); + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0;i < 6; i++) { + if (isDataTexture) { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data); + } + for (let j = 0;j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + const mipmapImage = mipmap.image[i].image; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data); + } + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]); + } + for (let j = 0;j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]); + } + } + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) + texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget, level) { + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + textureProperties.__renderTarget = renderTarget; + if (!renderTargetProperties.__hasExternalTextures) { + const width2 = Math.max(1, renderTarget.width >> level); + const height2 = Math.max(1, renderTarget.height >> level); + if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) { + state.texImage3D(textureTarget, level, glInternalFormat, width2, height2, renderTarget.depth, 0, glFormat, glType, null); + } else { + state.texImage2D(textureTarget, level, glInternalFormat, width2, height2, 0, glFormat, glType, null); + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples(renderTarget)); + } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) { + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null; + const glInternalFormat = getInternalDepthFormat(renderTarget.stencilBuffer, depthType); + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const samples = getRenderTargetSamples(renderTarget); + const isUseMultisampledRTT = useMultisampledRTT(renderTarget); + if (isUseMultisampledRTT) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (isMultisample) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } else { + const textures = renderTarget.textures; + for (let i = 0;i < textures.length; i++) { + const texture = textures[i]; + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const samples = getRenderTargetSamples(renderTarget); + if (isMultisample && useMultisampledRTT(renderTarget) === false) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + } + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + } + function setupDepthTexture(framebuffer, renderTarget) { + const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget; + if (isCube) + throw new Error("Depth Texture with cube render targets is not supported"); + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) { + throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); + } + const textureProperties = properties.get(renderTarget.depthTexture); + textureProperties.__renderTarget = renderTarget; + if (!textureProperties.__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) { + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + } + setTexture2D(renderTarget.depthTexture, 0); + const webglDepthTexture = textureProperties.__webglTexture; + const samples = getRenderTargetSamples(renderTarget); + if (renderTarget.depthTexture.format === DepthFormat) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else if (renderTarget.depthTexture.format === DepthStencilFormat) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else { + throw new Error("Unknown depthTexture format"); + } + } + function setupDepthRenderbuffer(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + if (renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__depthDisposeCallback) { + renderTargetProperties.__depthDisposeCallback(); + } + if (depthTexture) { + const disposeEvent = () => { + delete renderTargetProperties.__boundDepthTexture; + delete renderTargetProperties.__depthDisposeCallback; + depthTexture.removeEventListener("dispose", disposeEvent); + }; + depthTexture.addEventListener("dispose", disposeEvent); + renderTargetProperties.__depthDisposeCallback = disposeEvent; + } + renderTargetProperties.__boundDepthTexture = depthTexture; + } + if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) { + if (isCube) + throw new Error("target.depthTexture not supported in Cube render targets"); + setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget); + } else { + if (isCube) { + renderTargetProperties.__webglDepthbuffer = []; + for (let i = 0;i < 6; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]); + if (renderTargetProperties.__webglDepthbuffer[i] === undefined) { + renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer[i]; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } else { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + if (renderTargetProperties.__webglDepthbuffer === undefined) { + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function rebindTextures(renderTarget, colorTexture, depthTexture) { + const renderTargetProperties = properties.get(renderTarget); + if (colorTexture !== undefined) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0); + } + if (depthTexture !== undefined) { + setupDepthRenderbuffer(renderTarget); + } + } + function setupRenderTarget(renderTarget) { + const texture = renderTarget.texture; + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + renderTarget.addEventListener("dispose", onRenderTargetDispose); + const textures = renderTarget.textures; + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + const isMultipleRenderTargets = textures.length > 1; + if (!isMultipleRenderTargets) { + if (textureProperties.__webglTexture === undefined) { + textureProperties.__webglTexture = _gl.createTexture(); + } + textureProperties.__version = texture.version; + info.memory.textures++; + } + if (isCube) { + renderTargetProperties.__webglFramebuffer = []; + for (let i = 0;i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer[i] = []; + for (let level = 0;level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[i][level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer(); + } + } + } else { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer = []; + for (let level = 0;level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + } + if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length;i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture === undefined) { + attachmentProperties.__webglTexture = _gl.createTexture(); + info.memory.textures++; + } + } + } + if (renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + for (let i = 0;i < textures.length; i++) { + const texture2 = textures[i]; + renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer(); + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const glFormat = utils.convert(texture2.format, texture2.colorSpace); + const glType = utils.convert(texture2.type); + const glInternalFormat = getInternalFormat(texture2.internalFormat, glFormat, glType, texture2.colorSpace, renderTarget.isXRRenderTarget === true); + const samples = getRenderTargetSamples(renderTarget); + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + if (renderTarget.depthBuffer) { + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + } + if (isCube) { + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + for (let i = 0;i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0;level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i][level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0); + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + state.unbindTexture(); + } else if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length;i < il; i++) { + const attachment = textures[i]; + const attachmentProperties = properties.get(attachment); + state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_2D, attachment); + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0); + if (textureNeedsGenerateMipmaps(attachment)) { + generateMipmap(_gl.TEXTURE_2D); + } + } + state.unbindTexture(); + } else { + let glTextureType = _gl.TEXTURE_2D; + if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + } + state.bindTexture(glTextureType, textureProperties.__webglTexture); + setTextureParameters(glTextureType, texture); + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0;level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0); + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(glTextureType); + } + state.unbindTexture(); + } + if (renderTarget.depthBuffer) { + setupDepthRenderbuffer(renderTarget); + } + } + function updateRenderTargetMipmap(renderTarget) { + const textures = renderTarget.textures; + for (let i = 0, il = textures.length;i < il; i++) { + const texture = textures[i]; + if (textureNeedsGenerateMipmaps(texture)) { + const targetType = getTargetType(renderTarget); + const webglTexture = properties.get(texture).__webglTexture; + state.bindTexture(targetType, webglTexture); + generateMipmap(targetType); + state.unbindTexture(); + } + } + } + const invalidationArrayRead = []; + const invalidationArrayDraw = []; + function updateMultisampleRenderTarget(renderTarget) { + if (renderTarget.samples > 0) { + if (useMultisampledRTT(renderTarget) === false) { + const textures = renderTarget.textures; + const width2 = renderTarget.width; + const height2 = renderTarget.height; + let mask2 = _gl.COLOR_BUFFER_BIT; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get(renderTarget); + const isMultipleRenderTargets = textures.length > 1; + if (isMultipleRenderTargets) { + for (let i = 0;i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null); + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + for (let i = 0;i < textures.length; i++) { + if (renderTarget.resolveDepthBuffer) { + if (renderTarget.depthBuffer) + mask2 |= _gl.DEPTH_BUFFER_BIT; + if (renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer) + mask2 |= _gl.STENCIL_BUFFER_BIT; + } + if (isMultipleRenderTargets) { + _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0); + } + _gl.blitFramebuffer(0, 0, width2, height2, 0, 0, width2, height2, mask2, _gl.NEAREST); + if (supportsInvalidateFramebuffer === true) { + invalidationArrayRead.length = 0; + invalidationArrayDraw.length = 0; + invalidationArrayRead.push(_gl.COLOR_ATTACHMENT0 + i); + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false) { + invalidationArrayRead.push(depthStyle); + invalidationArrayDraw.push(depthStyle); + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, invalidationArrayDraw); + } + _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArrayRead); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + if (isMultipleRenderTargets) { + for (let i = 0;i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0); + } + } + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + } else { + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer) { + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]); + } + } + } + } + function getRenderTargetSamples(renderTarget) { + return Math.min(capabilities.maxSamples, renderTarget.samples); + } + function useMultisampledRTT(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + return renderTarget.samples > 0 && extensions.has("WEBGL_multisampled_render_to_texture") === true && renderTargetProperties.__useRenderToTexture !== false; + } + function updateVideoTexture(texture) { + const frame = info.render.frame; + if (_videoTextures.get(texture) !== frame) { + _videoTextures.set(texture, frame); + texture.update(); + } + } + function verifyColorSpace(texture, image) { + const colorSpace = texture.colorSpace; + const format = texture.format; + const type = texture.type; + if (texture.isCompressedTexture === true || texture.isVideoTexture === true) + return image; + if (colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace) { + if (ColorManagement.getTransfer(colorSpace) === SRGBTransfer) { + if (format !== RGBAFormat || type !== UnsignedByteType) { + console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."); + } + } else { + console.error("THREE.WebGLTextures: Unsupported texture color space:", colorSpace); + } + } + return image; + } + function getDimensions(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement) { + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + } else if (typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + } else { + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + } + return _imageDimensions; + } + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; +} +function WebGLUtils(gl, extensions) { + function convert(p, colorSpace = NoColorSpace) { + let extension; + const transfer = ColorManagement.getTransfer(colorSpace); + if (p === UnsignedByteType) + return gl.UNSIGNED_BYTE; + if (p === UnsignedShort4444Type) + return gl.UNSIGNED_SHORT_4_4_4_4; + if (p === UnsignedShort5551Type) + return gl.UNSIGNED_SHORT_5_5_5_1; + if (p === UnsignedInt5999Type) + return gl.UNSIGNED_INT_5_9_9_9_REV; + if (p === ByteType) + return gl.BYTE; + if (p === ShortType) + return gl.SHORT; + if (p === UnsignedShortType) + return gl.UNSIGNED_SHORT; + if (p === IntType) + return gl.INT; + if (p === UnsignedIntType) + return gl.UNSIGNED_INT; + if (p === FloatType) + return gl.FLOAT; + if (p === HalfFloatType) + return gl.HALF_FLOAT; + if (p === AlphaFormat) + return gl.ALPHA; + if (p === RGBFormat) + return gl.RGB; + if (p === RGBAFormat) + return gl.RGBA; + if (p === LuminanceFormat) + return gl.LUMINANCE; + if (p === LuminanceAlphaFormat) + return gl.LUMINANCE_ALPHA; + if (p === DepthFormat) + return gl.DEPTH_COMPONENT; + if (p === DepthStencilFormat) + return gl.DEPTH_STENCIL; + if (p === RedFormat) + return gl.RED; + if (p === RedIntegerFormat) + return gl.RED_INTEGER; + if (p === RGFormat) + return gl.RG; + if (p === RGIntegerFormat) + return gl.RG_INTEGER; + if (p === RGBAIntegerFormat) + return gl.RGBA_INTEGER; + if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) { + if (transfer === SRGBTransfer) { + extension = extensions.get("WEBGL_compressed_texture_s3tc_srgb"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format) + return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + } else { + return null; + } + } else { + extension = extensions.get("WEBGL_compressed_texture_s3tc"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format) + return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format) + return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format) + return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format) + return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + } else { + return null; + } + } + } + if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) { + extension = extensions.get("WEBGL_compressed_texture_pvrtc"); + if (extension !== null) { + if (p === RGB_PVRTC_4BPPV1_Format) + return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if (p === RGB_PVRTC_2BPPV1_Format) + return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if (p === RGBA_PVRTC_4BPPV1_Format) + return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if (p === RGBA_PVRTC_2BPPV1_Format) + return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + } else { + return null; + } + } + if (p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) { + extension = extensions.get("WEBGL_compressed_texture_etc"); + if (extension !== null) { + if (p === RGB_ETC1_Format || p === RGB_ETC2_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if (p === RGBA_ETC2_EAC_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + } else { + return null; + } + } + if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format) { + extension = extensions.get("WEBGL_compressed_texture_astc"); + if (extension !== null) { + if (p === RGBA_ASTC_4x4_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if (p === RGBA_ASTC_5x4_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if (p === RGBA_ASTC_5x5_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if (p === RGBA_ASTC_6x5_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if (p === RGBA_ASTC_6x6_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if (p === RGBA_ASTC_8x5_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if (p === RGBA_ASTC_8x6_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if (p === RGBA_ASTC_8x8_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if (p === RGBA_ASTC_10x5_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if (p === RGBA_ASTC_10x6_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if (p === RGBA_ASTC_10x8_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if (p === RGBA_ASTC_10x10_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if (p === RGBA_ASTC_12x10_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if (p === RGBA_ASTC_12x12_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + } else { + return null; + } + } + if (p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format) { + extension = extensions.get("EXT_texture_compression_bptc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + if (p === RGB_BPTC_SIGNED_Format) + return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; + if (p === RGB_BPTC_UNSIGNED_Format) + return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; + } else { + return null; + } + } + if (p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format) { + extension = extensions.get("EXT_texture_compression_rgtc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format) + return extension.COMPRESSED_RED_RGTC1_EXT; + if (p === SIGNED_RED_RGTC1_Format) + return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if (p === RED_GREEN_RGTC2_Format) + return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if (p === SIGNED_RED_GREEN_RGTC2_Format) + return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + } else { + return null; + } + } + if (p === UnsignedInt248Type) + return gl.UNSIGNED_INT_24_8; + return gl[p] !== undefined ? gl[p] : null; + } + return { convert }; +} +var _occlusion_vertex = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; +var _occlusion_fragment = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; + +class WebXRDepthSensing { + constructor() { + this.texture = null; + this.mesh = null; + this.depthNear = 0; + this.depthFar = 0; + } + init(renderer2, depthData, renderState) { + if (this.texture === null) { + const texture = new Texture; + const texProps = renderer2.properties.get(texture); + texProps.__webglTexture = depthData.texture; + if (depthData.depthNear !== renderState.depthNear || depthData.depthFar !== renderState.depthFar) { + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + } + this.texture = texture; + } + } + getMesh(cameraXR) { + if (this.texture !== null) { + if (this.mesh === null) { + const viewport = cameraXR.cameras[0].viewport; + const material = new ShaderMaterial({ + vertexShader: _occlusion_vertex, + fragmentShader: _occlusion_fragment, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + }); + this.mesh = new Mesh(new PlaneGeometry(20, 20), material); + } + } + return this.mesh; + } + reset() { + this.texture = null; + this.mesh = null; + } + getDepthTexture() { + return this.texture; + } +} + +class WebXRManager extends EventDispatcher { + constructor(renderer2, gl) { + super(); + const scope = this; + let session = null; + let framebufferScaleFactor = 1; + let referenceSpace = null; + let referenceSpaceType = "local-floor"; + let foveation = 1; + let customReferenceSpace = null; + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const depthSensing = new WebXRDepthSensing; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + const controllers = []; + const controllerInputSources = []; + const currentSize = new Vector2; + let currentPixelRatio = null; + const cameraL = new PerspectiveCamera; + cameraL.viewport = new Vector4; + const cameraR = new PerspectiveCamera; + cameraR.viewport = new Vector4; + const cameras = [cameraL, cameraR]; + const cameraXR = new ArrayCamera; + let _currentDepthNear = null; + let _currentDepthFar = null; + this.cameraAutoUpdate = true; + this.enabled = false; + this.isPresenting = false; + this.getController = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController; + controllers[index2] = controller; + } + return controller.getTargetRaySpace(); + }; + this.getControllerGrip = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController; + controllers[index2] = controller; + } + return controller.getGripSpace(); + }; + this.getHand = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController; + controllers[index2] = controller; + } + return controller.getHandSpace(); + }; + function onSessionEvent(event) { + const controllerIndex = controllerInputSources.indexOf(event.inputSource); + if (controllerIndex === -1) { + return; + } + const controller = controllers[controllerIndex]; + if (controller !== undefined) { + controller.update(event.inputSource, event.frame, customReferenceSpace || referenceSpace); + controller.dispatchEvent({ type: event.type, data: event.inputSource }); + } + } + function onSessionEnd() { + session.removeEventListener("select", onSessionEvent); + session.removeEventListener("selectstart", onSessionEvent); + session.removeEventListener("selectend", onSessionEvent); + session.removeEventListener("squeeze", onSessionEvent); + session.removeEventListener("squeezestart", onSessionEvent); + session.removeEventListener("squeezeend", onSessionEvent); + session.removeEventListener("end", onSessionEnd); + session.removeEventListener("inputsourceschange", onInputSourcesChange); + for (let i = 0;i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + if (inputSource === null) + continue; + controllerInputSources[i] = null; + controllers[i].disconnect(inputSource); + } + _currentDepthNear = null; + _currentDepthFar = null; + depthSensing.reset(); + renderer2.setRenderTarget(initialRenderTarget); + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + animation.stop(); + scope.isPresenting = false; + renderer2.setPixelRatio(currentPixelRatio); + renderer2.setSize(currentSize.width, currentSize.height, false); + scope.dispatchEvent({ type: "sessionend" }); + } + this.setFramebufferScaleFactor = function(value2) { + framebufferScaleFactor = value2; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting."); + } + }; + this.setReferenceSpaceType = function(value2) { + referenceSpaceType = value2; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change reference space type while presenting."); + } + }; + this.getReferenceSpace = function() { + return customReferenceSpace || referenceSpace; + }; + this.setReferenceSpace = function(space) { + customReferenceSpace = space; + }; + this.getBaseLayer = function() { + return glProjLayer !== null ? glProjLayer : glBaseLayer; + }; + this.getBinding = function() { + return glBinding; + }; + this.getFrame = function() { + return xrFrame; + }; + this.getSession = function() { + return session; + }; + this.setSession = async function(value2) { + session = value2; + if (session !== null) { + initialRenderTarget = renderer2.getRenderTarget(); + session.addEventListener("select", onSessionEvent); + session.addEventListener("selectstart", onSessionEvent); + session.addEventListener("selectend", onSessionEvent); + session.addEventListener("squeeze", onSessionEvent); + session.addEventListener("squeezestart", onSessionEvent); + session.addEventListener("squeezeend", onSessionEvent); + session.addEventListener("end", onSessionEnd); + session.addEventListener("inputsourceschange", onInputSourcesChange); + if (attributes.xrCompatible !== true) { + await gl.makeXRCompatible(); + } + currentPixelRatio = renderer2.getPixelRatio(); + renderer2.getSize(currentSize); + const useLayers = typeof XRWebGLBinding !== "undefined" && "createProjectionLayer" in XRWebGLBinding.prototype; + if (!useLayers) { + const layerInit = { + antialias: attributes.antialias, + alpha: true, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor + }; + glBaseLayer = new XRWebGLLayer(session, gl, layerInit); + session.updateRenderState({ baseLayer: glBaseLayer }); + renderer2.setPixelRatio(1); + renderer2.setSize(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false); + newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, { + format: RGBAFormat, + type: UnsignedByteType, + colorSpace: renderer2.outputColorSpace, + stencilBuffer: attributes.stencil + }); + } else { + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + if (attributes.depth) { + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; + } + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + glBinding = new XRWebGLBinding(session, gl); + glProjLayer = glBinding.createProjectionLayer(projectionlayerInit); + session.updateRenderState({ layers: [glProjLayer] }); + renderer2.setPixelRatio(1); + renderer2.setSize(glProjLayer.textureWidth, glProjLayer.textureHeight, false); + newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat), + stencilBuffer: attributes.stencil, + colorSpace: renderer2.outputColorSpace, + samples: attributes.antialias ? 4 : 0, + resolveDepthBuffer: glProjLayer.ignoreDepthValues === false + }); + } + newRenderTarget.isXRRenderTarget = true; + this.setFoveation(foveation); + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace(referenceSpaceType); + animation.setContext(session); + animation.start(); + scope.isPresenting = true; + scope.dispatchEvent({ type: "sessionstart" }); + } + }; + this.getEnvironmentBlendMode = function() { + if (session !== null) { + return session.environmentBlendMode; + } + }; + this.getDepthTexture = function() { + return depthSensing.getDepthTexture(); + }; + function onInputSourcesChange(event) { + for (let i = 0;i < event.removed.length; i++) { + const inputSource = event.removed[i]; + const index2 = controllerInputSources.indexOf(inputSource); + if (index2 >= 0) { + controllerInputSources[index2] = null; + controllers[index2].disconnect(inputSource); + } + } + for (let i = 0;i < event.added.length; i++) { + const inputSource = event.added[i]; + let controllerIndex = controllerInputSources.indexOf(inputSource); + if (controllerIndex === -1) { + for (let i2 = 0;i2 < controllers.length; i2++) { + if (i2 >= controllerInputSources.length) { + controllerInputSources.push(inputSource); + controllerIndex = i2; + break; + } else if (controllerInputSources[i2] === null) { + controllerInputSources[i2] = inputSource; + controllerIndex = i2; + break; + } + } + if (controllerIndex === -1) + break; + } + const controller = controllers[controllerIndex]; + if (controller) { + controller.connect(inputSource); + } + } + } + const cameraLPos = new Vector3; + const cameraRPos = new Vector3; + function setProjectionFromUnion(camera, cameraL2, cameraR2) { + cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld); + cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld); + const ipd = cameraLPos.distanceTo(cameraRPos); + const projL = cameraL2.projectionMatrix.elements; + const projR = cameraR2.projectionMatrix.elements; + const near = projL[14] / (projL[10] - 1); + const far = projL[14] / (projL[10] + 1); + const topFov = (projL[9] + 1) / projL[5]; + const bottomFov = (projL[9] - 1) / projL[5]; + const leftFov = (projL[8] - 1) / projL[0]; + const rightFov = (projR[8] + 1) / projR[0]; + const left = near * leftFov; + const right = near * rightFov; + const zOffset = ipd / (-leftFov + rightFov); + const xOffset = zOffset * -leftFov; + cameraL2.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale); + camera.translateX(xOffset); + camera.translateZ(zOffset); + camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale); + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + if (projL[10] === -1) { + camera.projectionMatrix.copy(cameraL2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraL2.projectionMatrixInverse); + } else { + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + (ipd - xOffset); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + } + } + function updateCamera(camera, parent2) { + if (parent2 === null) { + camera.matrixWorld.copy(camera.matrix); + } else { + camera.matrixWorld.multiplyMatrices(parent2.matrixWorld, camera.matrix); + } + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + } + this.updateCamera = function(camera) { + if (session === null) + return; + let depthNear = camera.near; + let depthFar = camera.far; + if (depthSensing.texture !== null) { + if (depthSensing.depthNear > 0) + depthNear = depthSensing.depthNear; + if (depthSensing.depthFar > 0) + depthFar = depthSensing.depthFar; + } + cameraXR.near = cameraR.near = cameraL.near = depthNear; + cameraXR.far = cameraR.far = cameraL.far = depthFar; + if (_currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far) { + session.updateRenderState({ + depthNear: cameraXR.near, + depthFar: cameraXR.far + }); + _currentDepthNear = cameraXR.near; + _currentDepthFar = cameraXR.far; + } + cameraL.layers.mask = camera.layers.mask | 2; + cameraR.layers.mask = camera.layers.mask | 4; + cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask; + const parent2 = camera.parent; + const cameras2 = cameraXR.cameras; + updateCamera(cameraXR, parent2); + for (let i = 0;i < cameras2.length; i++) { + updateCamera(cameras2[i], parent2); + } + if (cameras2.length === 2) { + setProjectionFromUnion(cameraXR, cameraL, cameraR); + } else { + cameraXR.projectionMatrix.copy(cameraL.projectionMatrix); + } + updateUserCamera(camera, cameraXR, parent2); + }; + function updateUserCamera(camera, cameraXR2, parent2) { + if (parent2 === null) { + camera.matrix.copy(cameraXR2.matrixWorld); + } else { + camera.matrix.copy(parent2.matrixWorld); + camera.matrix.invert(); + camera.matrix.multiply(cameraXR2.matrixWorld); + } + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.updateMatrixWorld(true); + camera.projectionMatrix.copy(cameraXR2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraXR2.projectionMatrixInverse); + if (camera.isPerspectiveCamera) { + camera.fov = RAD2DEG * 2 * Math.atan(1 / camera.projectionMatrix.elements[5]); + camera.zoom = 1; + } + } + this.getCamera = function() { + return cameraXR; + }; + this.getFoveation = function() { + if (glProjLayer === null && glBaseLayer === null) { + return; + } + return foveation; + }; + this.setFoveation = function(value2) { + foveation = value2; + if (glProjLayer !== null) { + glProjLayer.fixedFoveation = value2; + } + if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) { + glBaseLayer.fixedFoveation = value2; + } + }; + this.hasDepthSensing = function() { + return depthSensing.texture !== null; + }; + this.getDepthSensingMesh = function() { + return depthSensing.getMesh(cameraXR); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time2, frame) { + pose = frame.getViewerPose(customReferenceSpace || referenceSpace); + xrFrame = frame; + if (pose !== null) { + const views = pose.views; + if (glBaseLayer !== null) { + renderer2.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer); + renderer2.setRenderTarget(newRenderTarget); + } + let cameraXRNeedsUpdate = false; + if (views.length !== cameraXR.cameras.length) { + cameraXR.cameras.length = 0; + cameraXRNeedsUpdate = true; + } + for (let i = 0;i < views.length; i++) { + const view = views[i]; + let viewport = null; + if (glBaseLayer !== null) { + viewport = glBaseLayer.getViewport(view); + } else { + const glSubImage = glBinding.getViewSubImage(glProjLayer, view); + viewport = glSubImage.viewport; + if (i === 0) { + renderer2.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture); + renderer2.setRenderTarget(newRenderTarget); + } + } + let camera = cameras[i]; + if (camera === undefined) { + camera = new PerspectiveCamera; + camera.layers.enable(i); + camera.viewport = new Vector4; + cameras[i] = camera; + } + camera.matrix.fromArray(view.transform.matrix); + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.projectionMatrix.fromArray(view.projectionMatrix); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height); + if (i === 0) { + cameraXR.matrix.copy(camera.matrix); + cameraXR.matrix.decompose(cameraXR.position, cameraXR.quaternion, cameraXR.scale); + } + if (cameraXRNeedsUpdate === true) { + cameraXR.cameras.push(camera); + } + } + const enabledFeatures = session.enabledFeatures; + const gpuDepthSensingEnabled = enabledFeatures && enabledFeatures.includes("depth-sensing") && session.depthUsage == "gpu-optimized"; + if (gpuDepthSensingEnabled && glBinding) { + const depthData = glBinding.getDepthInformation(views[0]); + if (depthData && depthData.isValid && depthData.texture) { + depthSensing.init(renderer2, depthData, session.renderState); + } + } + } + for (let i = 0;i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + const controller = controllers[i]; + if (inputSource !== null && controller !== undefined) { + controller.update(inputSource, frame, customReferenceSpace || referenceSpace); + } + } + if (onAnimationFrameCallback) + onAnimationFrameCallback(time2, frame); + if (frame.detectedPlanes) { + scope.dispatchEvent({ type: "planesdetected", data: frame }); + } + xrFrame = null; + } + const animation = new WebGLAnimation; + animation.setAnimationLoop(onAnimationFrame); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + }; + this.dispose = function() { + }; + } +} +var _e1 = /* @__PURE__ */ new Euler; +var _m12 = /* @__PURE__ */ new Matrix4; +function WebGLMaterials(renderer2, properties) { + function refreshTransformUniform(map2, uniform) { + if (map2.matrixAutoUpdate === true) { + map2.updateMatrix(); + } + uniform.value.copy(map2.matrix); + } + function refreshFogUniforms(uniforms, fog) { + fog.color.getRGB(uniforms.fogColor.value, getUnlitUniformColorSpace(renderer2)); + if (fog.isFog) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + } else if (fog.isFogExp2) { + uniforms.fogDensity.value = fog.density; + } + } + function refreshMaterialUniforms(uniforms, material, pixelRatio, height2, transmissionRenderTarget) { + if (material.isMeshBasicMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshLambertMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshToonMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsToon(uniforms, material); + } else if (material.isMeshPhongMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsPhong(uniforms, material); + } else if (material.isMeshStandardMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsStandard(uniforms, material); + if (material.isMeshPhysicalMaterial) { + refreshUniformsPhysical(uniforms, material, transmissionRenderTarget); + } + } else if (material.isMeshMatcapMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsMatcap(uniforms, material); + } else if (material.isMeshDepthMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshDistanceMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsDistance(uniforms, material); + } else if (material.isMeshNormalMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isLineBasicMaterial) { + refreshUniformsLine(uniforms, material); + if (material.isLineDashedMaterial) { + refreshUniformsDash(uniforms, material); + } + } else if (material.isPointsMaterial) { + refreshUniformsPoints(uniforms, material, pixelRatio, height2); + } else if (material.isSpriteMaterial) { + refreshUniformsSprites(uniforms, material); + } else if (material.isShadowMaterial) { + uniforms.color.value.copy(material.color); + uniforms.opacity.value = material.opacity; + } else if (material.isShaderMaterial) { + material.uniformsNeedUpdate = false; + } + } + function refreshUniformsCommon(uniforms, material) { + uniforms.opacity.value = material.opacity; + if (material.color) { + uniforms.diffuse.value.copy(material.color); + } + if (material.emissive) { + uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity); + } + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.bumpMap) { + uniforms.bumpMap.value = material.bumpMap; + refreshTransformUniform(material.bumpMap, uniforms.bumpMapTransform); + uniforms.bumpScale.value = material.bumpScale; + if (material.side === BackSide) { + uniforms.bumpScale.value *= -1; + } + } + if (material.normalMap) { + uniforms.normalMap.value = material.normalMap; + refreshTransformUniform(material.normalMap, uniforms.normalMapTransform); + uniforms.normalScale.value.copy(material.normalScale); + if (material.side === BackSide) { + uniforms.normalScale.value.negate(); + } + } + if (material.displacementMap) { + uniforms.displacementMap.value = material.displacementMap; + refreshTransformUniform(material.displacementMap, uniforms.displacementMapTransform); + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + } + if (material.emissiveMap) { + uniforms.emissiveMap.value = material.emissiveMap; + refreshTransformUniform(material.emissiveMap, uniforms.emissiveMapTransform); + } + if (material.specularMap) { + uniforms.specularMap.value = material.specularMap; + refreshTransformUniform(material.specularMap, uniforms.specularMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + const materialProperties = properties.get(material); + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; + if (envMap) { + uniforms.envMap.value = envMap; + _e1.copy(envMapRotation); + _e1.x *= -1; + _e1.y *= -1; + _e1.z *= -1; + if (envMap.isCubeTexture && envMap.isRenderTargetTexture === false) { + _e1.y *= -1; + _e1.z *= -1; + } + uniforms.envMapRotation.value.setFromMatrix4(_m12.makeRotationFromEuler(_e1)); + uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + } + if (material.lightMap) { + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; + refreshTransformUniform(material.lightMap, uniforms.lightMapTransform); + } + if (material.aoMap) { + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + refreshTransformUniform(material.aoMap, uniforms.aoMapTransform); + } + } + function refreshUniformsLine(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + } + function refreshUniformsDash(uniforms, material) { + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + } + function refreshUniformsPoints(uniforms, material, pixelRatio, height2) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height2 * 0.5; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.uvTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsSprites(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsPhong(uniforms, material) { + uniforms.specular.value.copy(material.specular); + uniforms.shininess.value = Math.max(material.shininess, 0.0001); + } + function refreshUniformsToon(uniforms, material) { + if (material.gradientMap) { + uniforms.gradientMap.value = material.gradientMap; + } + } + function refreshUniformsStandard(uniforms, material) { + uniforms.metalness.value = material.metalness; + if (material.metalnessMap) { + uniforms.metalnessMap.value = material.metalnessMap; + refreshTransformUniform(material.metalnessMap, uniforms.metalnessMapTransform); + } + uniforms.roughness.value = material.roughness; + if (material.roughnessMap) { + uniforms.roughnessMap.value = material.roughnessMap; + refreshTransformUniform(material.roughnessMap, uniforms.roughnessMapTransform); + } + if (material.envMap) { + uniforms.envMapIntensity.value = material.envMapIntensity; + } + } + function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) { + uniforms.ior.value = material.ior; + if (material.sheen > 0) { + uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen); + uniforms.sheenRoughness.value = material.sheenRoughness; + if (material.sheenColorMap) { + uniforms.sheenColorMap.value = material.sheenColorMap; + refreshTransformUniform(material.sheenColorMap, uniforms.sheenColorMapTransform); + } + if (material.sheenRoughnessMap) { + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + refreshTransformUniform(material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform); + } + } + if (material.clearcoat > 0) { + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + if (material.clearcoatMap) { + uniforms.clearcoatMap.value = material.clearcoatMap; + refreshTransformUniform(material.clearcoatMap, uniforms.clearcoatMapTransform); + } + if (material.clearcoatRoughnessMap) { + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + refreshTransformUniform(material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform); + } + if (material.clearcoatNormalMap) { + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + refreshTransformUniform(material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform); + uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale); + if (material.side === BackSide) { + uniforms.clearcoatNormalScale.value.negate(); + } + } + } + if (material.dispersion > 0) { + uniforms.dispersion.value = material.dispersion; + } + if (material.iridescence > 0) { + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1]; + if (material.iridescenceMap) { + uniforms.iridescenceMap.value = material.iridescenceMap; + refreshTransformUniform(material.iridescenceMap, uniforms.iridescenceMapTransform); + } + if (material.iridescenceThicknessMap) { + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + refreshTransformUniform(material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform); + } + } + if (material.transmission > 0) { + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height); + if (material.transmissionMap) { + uniforms.transmissionMap.value = material.transmissionMap; + refreshTransformUniform(material.transmissionMap, uniforms.transmissionMapTransform); + } + uniforms.thickness.value = material.thickness; + if (material.thicknessMap) { + uniforms.thicknessMap.value = material.thicknessMap; + refreshTransformUniform(material.thicknessMap, uniforms.thicknessMapTransform); + } + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy(material.attenuationColor); + } + if (material.anisotropy > 0) { + uniforms.anisotropyVector.value.set(material.anisotropy * Math.cos(material.anisotropyRotation), material.anisotropy * Math.sin(material.anisotropyRotation)); + if (material.anisotropyMap) { + uniforms.anisotropyMap.value = material.anisotropyMap; + refreshTransformUniform(material.anisotropyMap, uniforms.anisotropyMapTransform); + } + } + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy(material.specularColor); + if (material.specularColorMap) { + uniforms.specularColorMap.value = material.specularColorMap; + refreshTransformUniform(material.specularColorMap, uniforms.specularColorMapTransform); + } + if (material.specularIntensityMap) { + uniforms.specularIntensityMap.value = material.specularIntensityMap; + refreshTransformUniform(material.specularIntensityMap, uniforms.specularIntensityMapTransform); + } + } + function refreshUniformsMatcap(uniforms, material) { + if (material.matcap) { + uniforms.matcap.value = material.matcap; + } + } + function refreshUniformsDistance(uniforms, material) { + const light = properties.get(material).light; + uniforms.referencePosition.value.setFromMatrixPosition(light.matrixWorld); + uniforms.nearDistance.value = light.shadow.camera.near; + uniforms.farDistance.value = light.shadow.camera.far; + } + return { + refreshFogUniforms, + refreshMaterialUniforms + }; +} +function WebGLUniformsGroups(gl, info, capabilities, state) { + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + const maxBindingPoints = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS); + function bind(uniformsGroup, program) { + const webglProgram = program.program; + state.uniformBlockBinding(uniformsGroup, webglProgram); + } + function update(uniformsGroup, program) { + let buffer = buffers[uniformsGroup.id]; + if (buffer === undefined) { + prepareUniformsGroup(uniformsGroup); + buffer = createBuffer(uniformsGroup); + buffers[uniformsGroup.id] = buffer; + uniformsGroup.addEventListener("dispose", onUniformsGroupsDispose); + } + const webglProgram = program.program; + state.updateUBOMapping(uniformsGroup, webglProgram); + const frame = info.render.frame; + if (updateList[uniformsGroup.id] !== frame) { + updateBufferData(uniformsGroup); + updateList[uniformsGroup.id] = frame; + } + } + function createBuffer(uniformsGroup) { + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + gl.bufferData(gl.UNIFORM_BUFFER, size, usage); + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer); + return buffer; + } + function allocateBindingPointIndex() { + for (let i = 0;i < maxBindingPoints; i++) { + if (allocatedBindingPoints.indexOf(i) === -1) { + allocatedBindingPoints.push(i); + return i; + } + } + console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."); + return 0; + } + function updateBufferData(uniformsGroup) { + const buffer = buffers[uniformsGroup.id]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + for (let i = 0, il = uniforms.length;i < il; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j = 0, jl = uniformArray.length;j < jl; j++) { + const uniform = uniformArray[j]; + if (hasUniformChanged(uniform, i, j, cache) === true) { + const offset = uniform.__offset; + const values2 = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + let arrayOffset = 0; + for (let k2 = 0;k2 < values2.length; k2++) { + const value2 = values2[k2]; + const info2 = getUniformSize(value2); + if (typeof value2 === "number" || typeof value2 === "boolean") { + uniform.__data[0] = value2; + gl.bufferSubData(gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data); + } else if (value2.isMatrix3) { + uniform.__data[0] = value2.elements[0]; + uniform.__data[1] = value2.elements[1]; + uniform.__data[2] = value2.elements[2]; + uniform.__data[3] = 0; + uniform.__data[4] = value2.elements[3]; + uniform.__data[5] = value2.elements[4]; + uniform.__data[6] = value2.elements[5]; + uniform.__data[7] = 0; + uniform.__data[8] = value2.elements[6]; + uniform.__data[9] = value2.elements[7]; + uniform.__data[10] = value2.elements[8]; + uniform.__data[11] = 0; + } else { + value2.toArray(uniform.__data, arrayOffset); + arrayOffset += info2.storage / Float32Array.BYTES_PER_ELEMENT; + } + } + gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data); + } + } + } + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + } + function hasUniformChanged(uniform, index2, indexArray, cache) { + const value2 = uniform.value; + const indexString = index2 + "_" + indexArray; + if (cache[indexString] === undefined) { + if (typeof value2 === "number" || typeof value2 === "boolean") { + cache[indexString] = value2; + } else { + cache[indexString] = value2.clone(); + } + return true; + } else { + const cachedObject = cache[indexString]; + if (typeof value2 === "number" || typeof value2 === "boolean") { + if (cachedObject !== value2) { + cache[indexString] = value2; + return true; + } + } else { + if (cachedObject.equals(value2) === false) { + cachedObject.copy(value2); + return true; + } + } + } + return false; + } + function prepareUniformsGroup(uniformsGroup) { + const uniforms = uniformsGroup.uniforms; + let offset = 0; + const chunkSize = 16; + for (let i = 0, l = uniforms.length;i < l; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j = 0, jl = uniformArray.length;j < jl; j++) { + const uniform = uniformArray[j]; + const values2 = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + for (let k2 = 0, kl = values2.length;k2 < kl; k2++) { + const value2 = values2[k2]; + const info2 = getUniformSize(value2); + const chunkOffset2 = offset % chunkSize; + const chunkPadding = chunkOffset2 % info2.boundary; + const chunkStart = chunkOffset2 + chunkPadding; + offset += chunkPadding; + if (chunkStart !== 0 && chunkSize - chunkStart < info2.storage) { + offset += chunkSize - chunkStart; + } + uniform.__data = new Float32Array(info2.storage / Float32Array.BYTES_PER_ELEMENT); + uniform.__offset = offset; + offset += info2.storage; + } + } + } + const chunkOffset = offset % chunkSize; + if (chunkOffset > 0) + offset += chunkSize - chunkOffset; + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + return this; + } + function getUniformSize(value2) { + const info2 = { + boundary: 0, + storage: 0 + }; + if (typeof value2 === "number" || typeof value2 === "boolean") { + info2.boundary = 4; + info2.storage = 4; + } else if (value2.isVector2) { + info2.boundary = 8; + info2.storage = 8; + } else if (value2.isVector3 || value2.isColor) { + info2.boundary = 16; + info2.storage = 12; + } else if (value2.isVector4) { + info2.boundary = 16; + info2.storage = 16; + } else if (value2.isMatrix3) { + info2.boundary = 48; + info2.storage = 48; + } else if (value2.isMatrix4) { + info2.boundary = 64; + info2.storage = 64; + } else if (value2.isTexture) { + console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."); + } else { + console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", value2); + } + return info2; + } + function onUniformsGroupsDispose(event) { + const uniformsGroup = event.target; + uniformsGroup.removeEventListener("dispose", onUniformsGroupsDispose); + const index2 = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex); + allocatedBindingPoints.splice(index2, 1); + gl.deleteBuffer(buffers[uniformsGroup.id]); + delete buffers[uniformsGroup.id]; + delete updateList[uniformsGroup.id]; + } + function dispose() { + for (const id in buffers) { + gl.deleteBuffer(buffers[id]); + } + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + } + return { + bind, + update, + dispose + }; +} + +class WebGLRenderer { + constructor(parameters = {}) { + const { + canvas = createCanvasElement(), + context = null, + depth = true, + stencil = false, + alpha = false, + antialias = false, + premultipliedAlpha = true, + preserveDrawingBuffer = false, + powerPreference = "default", + failIfMajorPerformanceCaveat = false, + reverseDepthBuffer = false + } = parameters; + this.isWebGLRenderer = true; + let _alpha; + if (context !== null) { + if (typeof WebGLRenderingContext !== "undefined" && context instanceof WebGLRenderingContext) { + throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163."); + } + _alpha = context.getContextAttributes().alpha; + } else { + _alpha = alpha; + } + const uintClearColor = new Uint32Array(4); + const intClearColor = new Int32Array(4); + let currentRenderList = null; + let currentRenderState = null; + const renderListStack = []; + const renderStateStack = []; + this.domElement = canvas; + this.debug = { + checkShaderErrors: true, + onShaderError: null + }; + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + this.sortObjects = true; + this.clippingPlanes = []; + this.localClippingEnabled = false; + this._outputColorSpace = SRGBColorSpace; + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1; + const _this = this; + let _isContextLost = false; + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = -1; + let _currentCamera = null; + const _currentViewport = new Vector4; + const _currentScissor = new Vector4; + let _currentScissorTest = null; + const _currentClearColor = new Color(0); + let _currentClearAlpha = 0; + let _width = canvas.width; + let _height = canvas.height; + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + const _viewport = new Vector4(0, 0, _width, _height); + const _scissor = new Vector4(0, 0, _width, _height); + let _scissorTest = false; + const _frustum2 = new Frustum; + let _clippingEnabled = false; + let _localClippingEnabled = false; + this.transmissionResolutionScale = 1; + const _currentProjectionMatrix = new Matrix4; + const _projScreenMatrix2 = new Matrix4; + const _vector32 = new Vector3; + const _vector4 = new Vector4; + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + let _renderBackground = false; + function getTargetPixelRatio() { + return _currentRenderTarget === null ? _pixelRatio : 1; + } + let _gl = context; + function getContext(contextName, contextAttributes) { + return canvas.getContext(contextName, contextAttributes); + } + try { + const contextAttributes = { + alpha: true, + depth, + stencil, + antialias, + premultipliedAlpha, + preserveDrawingBuffer, + powerPreference, + failIfMajorPerformanceCaveat + }; + if ("setAttribute" in canvas) + canvas.setAttribute("data-engine", `three.js r${REVISION}`); + canvas.addEventListener("webglcontextlost", onContextLost, false); + canvas.addEventListener("webglcontextrestored", onContextRestore, false); + canvas.addEventListener("webglcontextcreationerror", onContextCreationError, false); + if (_gl === null) { + const contextName = "webgl2"; + _gl = getContext(contextName, contextAttributes); + if (_gl === null) { + if (getContext(contextName)) { + throw new Error("Error creating WebGL context with your selected attributes."); + } else { + throw new Error("Error creating WebGL context."); + } + } + } + } catch (error) { + console.error("THREE.WebGLRenderer: " + error.message); + throw error; + } + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + let utils, bindingStates, uniformsGroups; + function initGLContext() { + extensions = new WebGLExtensions(_gl); + extensions.init(); + utils = new WebGLUtils(_gl, extensions); + capabilities = new WebGLCapabilities(_gl, extensions, parameters, utils); + state = new WebGLState(_gl, extensions); + if (capabilities.reverseDepthBuffer && reverseDepthBuffer) { + state.buffers.depth.setReversed(true); + } + info = new WebGLInfo(_gl); + properties = new WebGLProperties; + textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info); + cubemaps = new WebGLCubeMaps(_this); + cubeuvmaps = new WebGLCubeUVMaps(_this); + attributes = new WebGLAttributes(_gl); + bindingStates = new WebGLBindingStates(_gl, attributes); + geometries = new WebGLGeometries(_gl, attributes, info, bindingStates); + objects = new WebGLObjects(_gl, geometries, attributes, info); + morphtargets = new WebGLMorphtargets(_gl, capabilities, textures); + clipping = new WebGLClipping(properties); + programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping); + materials = new WebGLMaterials(_this, properties); + renderLists = new WebGLRenderLists; + renderStates = new WebGLRenderStates(extensions); + background = new WebGLBackground(_this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha); + shadowMap = new WebGLShadowMap(_this, objects, capabilities); + uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state); + bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info); + indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info); + info.programs = programCache.programs; + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; + } + initGLContext(); + const xr = new WebXRManager(_this, _gl); + this.xr = xr; + this.getContext = function() { + return _gl; + }; + this.getContextAttributes = function() { + return _gl.getContextAttributes(); + }; + this.forceContextLoss = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) + extension.loseContext(); + }; + this.forceContextRestore = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) + extension.restoreContext(); + }; + this.getPixelRatio = function() { + return _pixelRatio; + }; + this.setPixelRatio = function(value2) { + if (value2 === undefined) + return; + _pixelRatio = value2; + this.setSize(_width, _height, false); + }; + this.getSize = function(target) { + return target.set(_width, _height); + }; + this.setSize = function(width2, height2, updateStyle = true) { + if (xr.isPresenting) { + console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."); + return; + } + _width = width2; + _height = height2; + canvas.width = Math.floor(width2 * _pixelRatio); + canvas.height = Math.floor(height2 * _pixelRatio); + if (updateStyle === true) { + canvas.style.width = width2 + "px"; + canvas.style.height = height2 + "px"; + } + this.setViewport(0, 0, width2, height2); + }; + this.getDrawingBufferSize = function(target) { + return target.set(_width * _pixelRatio, _height * _pixelRatio).floor(); + }; + this.setDrawingBufferSize = function(width2, height2, pixelRatio) { + _width = width2; + _height = height2; + _pixelRatio = pixelRatio; + canvas.width = Math.floor(width2 * pixelRatio); + canvas.height = Math.floor(height2 * pixelRatio); + this.setViewport(0, 0, width2, height2); + }; + this.getCurrentViewport = function(target) { + return target.copy(_currentViewport); + }; + this.getViewport = function(target) { + return target.copy(_viewport); + }; + this.setViewport = function(x, y, width2, height2) { + if (x.isVector4) { + _viewport.set(x.x, x.y, x.z, x.w); + } else { + _viewport.set(x, y, width2, height2); + } + state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).round()); + }; + this.getScissor = function(target) { + return target.copy(_scissor); + }; + this.setScissor = function(x, y, width2, height2) { + if (x.isVector4) { + _scissor.set(x.x, x.y, x.z, x.w); + } else { + _scissor.set(x, y, width2, height2); + } + state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).round()); + }; + this.getScissorTest = function() { + return _scissorTest; + }; + this.setScissorTest = function(boolean) { + state.setScissorTest(_scissorTest = boolean); + }; + this.setOpaqueSort = function(method) { + _opaqueSort = method; + }; + this.setTransparentSort = function(method) { + _transparentSort = method; + }; + this.getClearColor = function(target) { + return target.copy(background.getClearColor()); + }; + this.setClearColor = function() { + background.setClearColor.apply(background, arguments); + }; + this.getClearAlpha = function() { + return background.getClearAlpha(); + }; + this.setClearAlpha = function() { + background.setClearAlpha.apply(background, arguments); + }; + this.clear = function(color = true, depth2 = true, stencil2 = true) { + let bits = 0; + if (color) { + let isIntegerFormat = false; + if (_currentRenderTarget !== null) { + const targetFormat = _currentRenderTarget.texture.format; + isIntegerFormat = targetFormat === RGBAIntegerFormat || targetFormat === RGIntegerFormat || targetFormat === RedIntegerFormat; + } + if (isIntegerFormat) { + const targetType = _currentRenderTarget.texture.type; + const isUnsignedType = targetType === UnsignedByteType || targetType === UnsignedIntType || targetType === UnsignedShortType || targetType === UnsignedInt248Type || targetType === UnsignedShort4444Type || targetType === UnsignedShort5551Type; + const clearColor = background.getClearColor(); + const a = background.getClearAlpha(); + const r = clearColor.r; + const g = clearColor.g; + const b = clearColor.b; + if (isUnsignedType) { + uintClearColor[0] = r; + uintClearColor[1] = g; + uintClearColor[2] = b; + uintClearColor[3] = a; + _gl.clearBufferuiv(_gl.COLOR, 0, uintClearColor); + } else { + intClearColor[0] = r; + intClearColor[1] = g; + intClearColor[2] = b; + intClearColor[3] = a; + _gl.clearBufferiv(_gl.COLOR, 0, intClearColor); + } + } else { + bits |= _gl.COLOR_BUFFER_BIT; + } + } + if (depth2) { + bits |= _gl.DEPTH_BUFFER_BIT; + } + if (stencil2) { + bits |= _gl.STENCIL_BUFFER_BIT; + this.state.buffers.stencil.setMask(4294967295); + } + _gl.clear(bits); + }; + this.clearColor = function() { + this.clear(true, false, false); + }; + this.clearDepth = function() { + this.clear(false, true, false); + }; + this.clearStencil = function() { + this.clear(false, false, true); + }; + this.dispose = function() { + canvas.removeEventListener("webglcontextlost", onContextLost, false); + canvas.removeEventListener("webglcontextrestored", onContextRestore, false); + canvas.removeEventListener("webglcontextcreationerror", onContextCreationError, false); + background.dispose(); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + xr.dispose(); + xr.removeEventListener("sessionstart", onXRSessionStart); + xr.removeEventListener("sessionend", onXRSessionEnd); + animation.stop(); + }; + function onContextLost(event) { + event.preventDefault(); + console.log("THREE.WebGLRenderer: Context Lost."); + _isContextLost = true; + } + function onContextRestore() { + console.log("THREE.WebGLRenderer: Context Restored."); + _isContextLost = false; + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + initGLContext(); + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + } + function onContextCreationError(event) { + console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", event.statusMessage); + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + deallocateMaterial(material); + } + function deallocateMaterial(material) { + releaseMaterialProgramReferences(material); + properties.remove(material); + } + function releaseMaterialProgramReferences(material) { + const programs = properties.get(material).programs; + if (programs !== undefined) { + programs.forEach(function(program) { + programCache.releaseProgram(program); + }); + if (material.isShaderMaterial) { + programCache.releaseShaderCache(material); + } + } + } + this.renderBufferDirect = function(camera, scene, geometry, material, object, group) { + if (scene === null) + scene = _emptyScene; + const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0; + const program = setProgram(camera, scene, geometry, material, object); + state.setMaterial(material, frontFaceCW); + let index2 = geometry.index; + let rangeFactor = 1; + if (material.wireframe === true) { + index2 = geometries.getWireframeAttribute(geometry); + if (index2 === undefined) + return; + rangeFactor = 2; + } + const drawRange = geometry.drawRange; + const position2 = geometry.attributes.position; + let drawStart = drawRange.start * rangeFactor; + let drawEnd = (drawRange.start + drawRange.count) * rangeFactor; + if (group !== null) { + drawStart = Math.max(drawStart, group.start * rangeFactor); + drawEnd = Math.min(drawEnd, (group.start + group.count) * rangeFactor); + } + if (index2 !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, index2.count); + } else if (position2 !== undefined && position2 !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, position2.count); + } + const drawCount = drawEnd - drawStart; + if (drawCount < 0 || drawCount === Infinity) + return; + bindingStates.setup(object, material, program, geometry, index2); + let attribute; + let renderer2 = bufferRenderer; + if (index2 !== null) { + attribute = attributes.get(index2); + renderer2 = indexedBufferRenderer; + renderer2.setIndex(attribute); + } + if (object.isMesh) { + if (material.wireframe === true) { + state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio()); + renderer2.setMode(_gl.LINES); + } else { + renderer2.setMode(_gl.TRIANGLES); + } + } else if (object.isLine) { + let lineWidth = material.linewidth; + if (lineWidth === undefined) + lineWidth = 1; + state.setLineWidth(lineWidth * getTargetPixelRatio()); + if (object.isLineSegments) { + renderer2.setMode(_gl.LINES); + } else if (object.isLineLoop) { + renderer2.setMode(_gl.LINE_LOOP); + } else { + renderer2.setMode(_gl.LINE_STRIP); + } + } else if (object.isPoints) { + renderer2.setMode(_gl.POINTS); + } else if (object.isSprite) { + renderer2.setMode(_gl.TRIANGLES); + } + if (object.isBatchedMesh) { + if (object._multiDrawInstances !== null) { + renderer2.renderMultiDrawInstances(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances); + } else { + if (!extensions.get("WEBGL_multi_draw")) { + const starts = object._multiDrawStarts; + const counts = object._multiDrawCounts; + const drawCount2 = object._multiDrawCount; + const bytesPerElement = index2 ? attributes.get(index2).bytesPerElement : 1; + const uniforms = properties.get(material).currentProgram.getUniforms(); + for (let i = 0;i < drawCount2; i++) { + uniforms.setValue(_gl, "_gl_DrawID", i); + renderer2.render(starts[i] / bytesPerElement, counts[i]); + } + } else { + renderer2.renderMultiDraw(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount); + } + } + } else if (object.isInstancedMesh) { + renderer2.renderInstances(drawStart, drawCount, object.count); + } else if (geometry.isInstancedBufferGeometry) { + const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min(geometry.instanceCount, maxInstanceCount); + renderer2.renderInstances(drawStart, drawCount, instanceCount); + } else { + renderer2.render(drawStart, drawCount); + } + }; + function prepareMaterial(material, scene, object) { + if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) { + material.side = BackSide; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = FrontSide; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = DoubleSide; + } else { + getProgram(material, scene, object); + } + } + this.compile = function(scene, camera, targetScene = null) { + if (targetScene === null) + targetScene = scene; + currentRenderState = renderStates.get(targetScene); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + targetScene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + if (scene !== targetScene) { + scene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + } + currentRenderState.setupLights(); + const materials2 = new Set; + scene.traverse(function(object) { + if (!(object.isMesh || object.isPoints || object.isLine || object.isSprite)) { + return; + } + const material = object.material; + if (material) { + if (Array.isArray(material)) { + for (let i = 0;i < material.length; i++) { + const material2 = material[i]; + prepareMaterial(material2, targetScene, object); + materials2.add(material2); + } + } else { + prepareMaterial(material, targetScene, object); + materials2.add(material); + } + } + }); + renderStateStack.pop(); + currentRenderState = null; + return materials2; + }; + this.compileAsync = function(scene, camera, targetScene = null) { + const materials2 = this.compile(scene, camera, targetScene); + return new Promise((resolve) => { + function checkMaterialsReady() { + materials2.forEach(function(material) { + const materialProperties = properties.get(material); + const program = materialProperties.currentProgram; + if (program.isReady()) { + materials2.delete(material); + } + }); + if (materials2.size === 0) { + resolve(scene); + return; + } + setTimeout(checkMaterialsReady, 10); + } + if (extensions.get("KHR_parallel_shader_compile") !== null) { + checkMaterialsReady(); + } else { + setTimeout(checkMaterialsReady, 10); + } + }); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time2) { + if (onAnimationFrameCallback) + onAnimationFrameCallback(time2); + } + function onXRSessionStart() { + animation.stop(); + } + function onXRSessionEnd() { + animation.start(); + } + const animation = new WebGLAnimation; + animation.setAnimationLoop(onAnimationFrame); + if (typeof self !== "undefined") + animation.setContext(self); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + xr.setAnimationLoop(callback); + callback === null ? animation.stop() : animation.start(); + }; + xr.addEventListener("sessionstart", onXRSessionStart); + xr.addEventListener("sessionend", onXRSessionEnd); + this.render = function(scene, camera) { + if (camera !== undefined && camera.isCamera !== true) { + console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera."); + return; + } + if (_isContextLost === true) + return; + if (scene.matrixWorldAutoUpdate === true) + scene.updateMatrixWorld(); + if (camera.parent === null && camera.matrixWorldAutoUpdate === true) + camera.updateMatrixWorld(); + if (xr.enabled === true && xr.isPresenting === true) { + if (xr.cameraAutoUpdate === true) + xr.updateCamera(camera); + camera = xr.getCamera(); + } + if (scene.isScene === true) + scene.onBeforeRender(_this, scene, camera, _currentRenderTarget); + currentRenderState = renderStates.get(scene, renderStateStack.length); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + _projScreenMatrix2.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + _frustum2.setFromProjectionMatrix(_projScreenMatrix2); + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled); + currentRenderList = renderLists.get(scene, renderListStack.length); + currentRenderList.init(); + renderListStack.push(currentRenderList); + if (xr.enabled === true && xr.isPresenting === true) { + const depthSensingMesh = _this.xr.getDepthSensingMesh(); + if (depthSensingMesh !== null) { + projectObject(depthSensingMesh, camera, -Infinity, _this.sortObjects); + } + } + projectObject(scene, camera, 0, _this.sortObjects); + currentRenderList.finish(); + if (_this.sortObjects === true) { + currentRenderList.sort(_opaqueSort, _transparentSort); + } + _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false; + if (_renderBackground) { + background.addToRenderList(currentRenderList, scene); + } + this.info.render.frame++; + if (_clippingEnabled === true) + clipping.beginShadows(); + const shadowsArray = currentRenderState.state.shadowsArray; + shadowMap.render(shadowsArray, scene, camera); + if (_clippingEnabled === true) + clipping.endShadows(); + if (this.info.autoReset === true) + this.info.reset(); + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + currentRenderState.setupLights(); + if (camera.isArrayCamera) { + const cameras = camera.cameras; + if (transmissiveObjects.length > 0) { + for (let i = 0, l = cameras.length;i < l; i++) { + const camera2 = cameras[i]; + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera2); + } + } + if (_renderBackground) + background.render(scene); + for (let i = 0, l = cameras.length;i < l; i++) { + const camera2 = cameras[i]; + renderScene(currentRenderList, scene, camera2, camera2.viewport); + } + } else { + if (transmissiveObjects.length > 0) + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera); + if (_renderBackground) + background.render(scene); + renderScene(currentRenderList, scene, camera); + } + if (_currentRenderTarget !== null && _currentActiveMipmapLevel === 0) { + textures.updateMultisampleRenderTarget(_currentRenderTarget); + textures.updateRenderTargetMipmap(_currentRenderTarget); + } + if (scene.isScene === true) + scene.onAfterRender(_this, scene, camera); + bindingStates.resetDefaultState(); + _currentMaterialId = -1; + _currentCamera = null; + renderStateStack.pop(); + if (renderStateStack.length > 0) { + currentRenderState = renderStateStack[renderStateStack.length - 1]; + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, currentRenderState.state.camera); + } else { + currentRenderState = null; + } + renderListStack.pop(); + if (renderListStack.length > 0) { + currentRenderList = renderListStack[renderListStack.length - 1]; + } else { + currentRenderList = null; + } + }; + function projectObject(object, camera, groupOrder, sortObjects) { + if (object.visible === false) + return; + const visible = object.layers.test(camera.layers); + if (visible) { + if (object.isGroup) { + groupOrder = object.renderOrder; + } else if (object.isLOD) { + if (object.autoUpdate === true) + object.update(camera); + } else if (object.isLight) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } else if (object.isSprite) { + if (!object.frustumCulled || _frustum2.intersectsSprite(object)) { + if (sortObjects) { + _vector4.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix2); + } + const geometry = objects.update(object); + const material = object.material; + if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector4.z, null); + } + } + } else if (object.isMesh || object.isLine || object.isPoints) { + if (!object.frustumCulled || _frustum2.intersectsObject(object)) { + const geometry = objects.update(object); + const material = object.material; + if (sortObjects) { + if (object.boundingSphere !== undefined) { + if (object.boundingSphere === null) + object.computeBoundingSphere(); + _vector4.copy(object.boundingSphere.center); + } else { + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _vector4.copy(geometry.boundingSphere.center); + } + _vector4.applyMatrix4(object.matrixWorld).applyMatrix4(_projScreenMatrix2); + } + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector4.z, group); + } + } + } else if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector4.z, null); + } + } + } + } + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + projectObject(children[i], camera, groupOrder, sortObjects); + } + } + function renderScene(currentRenderList2, scene, camera, viewport) { + const opaqueObjects = currentRenderList2.opaque; + const transmissiveObjects = currentRenderList2.transmissive; + const transparentObjects = currentRenderList2.transparent; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, camera); + if (viewport) + state.viewport(_currentViewport.copy(viewport)); + if (opaqueObjects.length > 0) + renderObjects(opaqueObjects, scene, camera); + if (transmissiveObjects.length > 0) + renderObjects(transmissiveObjects, scene, camera); + if (transparentObjects.length > 0) + renderObjects(transparentObjects, scene, camera); + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + state.setPolygonOffset(false); + } + function renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + if (overrideMaterial !== null) { + return; + } + if (currentRenderState.state.transmissionRenderTarget[camera.id] === undefined) { + currentRenderState.state.transmissionRenderTarget[camera.id] = new WebGLRenderTarget(1, 1, { + generateMipmaps: true, + type: extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float") ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: 4, + stencilBuffer: stencil, + resolveDepthBuffer: false, + resolveStencilBuffer: false, + colorSpace: ColorManagement.workingColorSpace + }); + } + const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[camera.id]; + const activeViewport = camera.viewport || _currentViewport; + transmissionRenderTarget.setSize(activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale); + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget(transmissionRenderTarget); + _this.getClearColor(_currentClearColor); + _currentClearAlpha = _this.getClearAlpha(); + if (_currentClearAlpha < 1) + _this.setClearColor(16777215, 0.5); + _this.clear(); + if (_renderBackground) + background.render(scene); + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; + const currentCameraViewport = camera.viewport; + if (camera.viewport !== undefined) + camera.viewport = undefined; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, camera); + renderObjects(opaqueObjects, scene, camera); + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + if (extensions.has("WEBGL_multisampled_render_to_texture") === false) { + let renderTargetNeedsUpdate = false; + for (let i = 0, l = transmissiveObjects.length;i < l; i++) { + const renderItem = transmissiveObjects[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = renderItem.material; + const group = renderItem.group; + if (material.side === DoubleSide && object.layers.test(camera.layers)) { + const currentSide = material.side; + material.side = BackSide; + material.needsUpdate = true; + renderObject(object, scene, camera, geometry, material, group); + material.side = currentSide; + material.needsUpdate = true; + renderTargetNeedsUpdate = true; + } + } + if (renderTargetNeedsUpdate === true) { + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + } + } + _this.setRenderTarget(currentRenderTarget); + _this.setClearColor(_currentClearColor, _currentClearAlpha); + if (currentCameraViewport !== undefined) + camera.viewport = currentCameraViewport; + _this.toneMapping = currentToneMapping; + } + function renderObjects(renderList, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + for (let i = 0, l = renderList.length;i < l; i++) { + const renderItem = renderList[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; + if (object.layers.test(camera.layers)) { + renderObject(object, scene, camera, geometry, material, group); + } + } + } + function renderObject(object, scene, camera, geometry, material, group) { + object.onBeforeRender(_this, scene, camera, geometry, material, group); + object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld); + object.normalMatrix.getNormalMatrix(object.modelViewMatrix); + material.onBeforeRender(_this, scene, camera, geometry, object, group); + if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) { + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = DoubleSide; + } else { + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + } + object.onAfterRender(_this, scene, camera, geometry, material, group); + } + function getProgram(material, scene, object) { + if (scene.isScene !== true) + scene = _emptyScene; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + const lightsStateVersion = lights.state.version; + const parameters2 = programCache.getParameters(material, lights.state, shadowsArray, scene, object); + const programCacheKey = programCache.getProgramCacheKey(parameters2); + let programs = materialProperties.programs; + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment); + materialProperties.envMapRotation = materialProperties.environment !== null && material.envMap === null ? scene.environmentRotation : material.envMapRotation; + if (programs === undefined) { + material.addEventListener("dispose", onMaterialDispose); + programs = new Map; + materialProperties.programs = programs; + } + let program = programs.get(programCacheKey); + if (program !== undefined) { + if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) { + updateCommonMaterialProperties(material, parameters2); + return program; + } + } else { + parameters2.uniforms = programCache.getUniforms(material); + material.onBeforeCompile(parameters2, _this); + program = programCache.acquireProgram(parameters2, programCacheKey); + programs.set(programCacheKey, program); + materialProperties.uniforms = parameters2.uniforms; + } + const uniforms = materialProperties.uniforms; + if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) { + uniforms.clippingPlanes = clipping.uniform; + } + updateCommonMaterialProperties(material, parameters2); + materialProperties.needsLights = materialNeedsLights(material); + materialProperties.lightsStateVersion = lightsStateVersion; + if (materialProperties.needsLights) { + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + } + materialProperties.currentProgram = program; + materialProperties.uniformsList = null; + return program; + } + function getUniformList(materialProperties) { + if (materialProperties.uniformsList === null) { + const progUniforms = materialProperties.currentProgram.getUniforms(); + materialProperties.uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, materialProperties.uniforms); + } + return materialProperties.uniformsList; + } + function updateCommonMaterialProperties(material, parameters2) { + const materialProperties = properties.get(material); + materialProperties.outputColorSpace = parameters2.outputColorSpace; + materialProperties.batching = parameters2.batching; + materialProperties.batchingColor = parameters2.batchingColor; + materialProperties.instancing = parameters2.instancing; + materialProperties.instancingColor = parameters2.instancingColor; + materialProperties.instancingMorph = parameters2.instancingMorph; + materialProperties.skinning = parameters2.skinning; + materialProperties.morphTargets = parameters2.morphTargets; + materialProperties.morphNormals = parameters2.morphNormals; + materialProperties.morphColors = parameters2.morphColors; + materialProperties.morphTargetsCount = parameters2.morphTargetsCount; + materialProperties.numClippingPlanes = parameters2.numClippingPlanes; + materialProperties.numIntersection = parameters2.numClipIntersection; + materialProperties.vertexAlphas = parameters2.vertexAlphas; + materialProperties.vertexTangents = parameters2.vertexTangents; + materialProperties.toneMapping = parameters2.toneMapping; + } + function setProgram(camera, scene, geometry, material, object) { + if (scene.isScene !== true) + scene = _emptyScene; + textures.resetTextureUnits(); + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const colorSpace = _currentRenderTarget === null ? _this.outputColorSpace : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !!geometry.attributes.tangent && (!!material.normalMap || material.anisotropy > 0); + const morphTargets = !!geometry.morphAttributes.position; + const morphNormals = !!geometry.morphAttributes.normal; + const morphColors = !!geometry.morphAttributes.color; + let toneMapping = NoToneMapping; + if (material.toneMapped) { + if (_currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true) { + toneMapping = _this.toneMapping; + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + if (_clippingEnabled === true) { + if (_localClippingEnabled === true || camera !== _currentCamera) { + const useCache = camera === _currentCamera && material.id === _currentMaterialId; + clipping.setState(material, camera, useCache); + } + } + let needsProgramChange = false; + if (material.version === materialProperties.__version) { + if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) { + needsProgramChange = true; + } else if (materialProperties.outputColorSpace !== colorSpace) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batching === false) { + needsProgramChange = true; + } else if (!object.isBatchedMesh && materialProperties.batching === true) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancing === false) { + needsProgramChange = true; + } else if (!object.isInstancedMesh && materialProperties.instancing === true) { + needsProgramChange = true; + } else if (object.isSkinnedMesh && materialProperties.skinning === false) { + needsProgramChange = true; + } else if (!object.isSkinnedMesh && materialProperties.skinning === true) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null) { + needsProgramChange = true; + } else if (materialProperties.envMap !== envMap) { + needsProgramChange = true; + } else if (material.fog === true && materialProperties.fog !== fog) { + needsProgramChange = true; + } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) { + needsProgramChange = true; + } else if (materialProperties.vertexAlphas !== vertexAlphas) { + needsProgramChange = true; + } else if (materialProperties.vertexTangents !== vertexTangents) { + needsProgramChange = true; + } else if (materialProperties.morphTargets !== morphTargets) { + needsProgramChange = true; + } else if (materialProperties.morphNormals !== morphNormals) { + needsProgramChange = true; + } else if (materialProperties.morphColors !== morphColors) { + needsProgramChange = true; + } else if (materialProperties.toneMapping !== toneMapping) { + needsProgramChange = true; + } else if (materialProperties.morphTargetsCount !== morphTargetsCount) { + needsProgramChange = true; + } + } else { + needsProgramChange = true; + materialProperties.__version = material.version; + } + let program = materialProperties.currentProgram; + if (needsProgramChange === true) { + program = getProgram(material, scene, object); + } + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + const p_uniforms = program.getUniforms(), m_uniforms = materialProperties.uniforms; + if (state.useProgram(program.program)) { + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + } + if (material.id !== _currentMaterialId) { + _currentMaterialId = material.id; + refreshMaterial = true; + } + if (refreshProgram || _currentCamera !== camera) { + const reverseDepthBuffer2 = state.buffers.depth.getReversed(); + if (reverseDepthBuffer2) { + _currentProjectionMatrix.copy(camera.projectionMatrix); + toNormalizedProjectionMatrix(_currentProjectionMatrix); + toReversedProjectionMatrix(_currentProjectionMatrix); + p_uniforms.setValue(_gl, "projectionMatrix", _currentProjectionMatrix); + } else { + p_uniforms.setValue(_gl, "projectionMatrix", camera.projectionMatrix); + } + p_uniforms.setValue(_gl, "viewMatrix", camera.matrixWorldInverse); + const uCamPos = p_uniforms.map.cameraPosition; + if (uCamPos !== undefined) { + uCamPos.setValue(_gl, _vector32.setFromMatrixPosition(camera.matrixWorld)); + } + if (capabilities.logarithmicDepthBuffer) { + p_uniforms.setValue(_gl, "logDepthBufFC", 2 / (Math.log(camera.far + 1) / Math.LN2)); + } + if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) { + p_uniforms.setValue(_gl, "isOrthographic", camera.isOrthographicCamera === true); + } + if (_currentCamera !== camera) { + _currentCamera = camera; + refreshMaterial = true; + refreshLights = true; + } + } + if (object.isSkinnedMesh) { + p_uniforms.setOptional(_gl, object, "bindMatrix"); + p_uniforms.setOptional(_gl, object, "bindMatrixInverse"); + const skeleton = object.skeleton; + if (skeleton) { + if (skeleton.boneTexture === null) + skeleton.computeBoneTexture(); + p_uniforms.setValue(_gl, "boneTexture", skeleton.boneTexture, textures); + } + } + if (object.isBatchedMesh) { + p_uniforms.setOptional(_gl, object, "batchingTexture"); + p_uniforms.setValue(_gl, "batchingTexture", object._matricesTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingIdTexture"); + p_uniforms.setValue(_gl, "batchingIdTexture", object._indirectTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingColorTexture"); + if (object._colorsTexture !== null) { + p_uniforms.setValue(_gl, "batchingColorTexture", object._colorsTexture, textures); + } + } + const morphAttributes = geometry.morphAttributes; + if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined) { + morphtargets.update(object, geometry, program); + } + if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) { + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue(_gl, "receiveShadow", object.receiveShadow); + } + if (material.isMeshGouraudMaterial && material.envMap !== null) { + m_uniforms.envMap.value = envMap; + m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + } + if (material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null) { + m_uniforms.envMapIntensity.value = scene.environmentIntensity; + } + if (refreshMaterial) { + p_uniforms.setValue(_gl, "toneMappingExposure", _this.toneMappingExposure); + if (materialProperties.needsLights) { + markUniformsLightsNeedsUpdate(m_uniforms, refreshLights); + } + if (fog && material.fog === true) { + materials.refreshFogUniforms(m_uniforms, fog); + } + materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[camera.id]); + WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + } + if (material.isShaderMaterial && material.uniformsNeedUpdate === true) { + WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + material.uniformsNeedUpdate = false; + } + if (material.isSpriteMaterial) { + p_uniforms.setValue(_gl, "center", object.center); + } + p_uniforms.setValue(_gl, "modelViewMatrix", object.modelViewMatrix); + p_uniforms.setValue(_gl, "normalMatrix", object.normalMatrix); + p_uniforms.setValue(_gl, "modelMatrix", object.matrixWorld); + if (material.isShaderMaterial || material.isRawShaderMaterial) { + const groups = material.uniformsGroups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + uniformsGroups.update(group, program); + uniformsGroups.bind(group, program); + } + } + return program; + } + function markUniformsLightsNeedsUpdate(uniforms, value2) { + uniforms.ambientLightColor.needsUpdate = value2; + uniforms.lightProbe.needsUpdate = value2; + uniforms.directionalLights.needsUpdate = value2; + uniforms.directionalLightShadows.needsUpdate = value2; + uniforms.pointLights.needsUpdate = value2; + uniforms.pointLightShadows.needsUpdate = value2; + uniforms.spotLights.needsUpdate = value2; + uniforms.spotLightShadows.needsUpdate = value2; + uniforms.rectAreaLights.needsUpdate = value2; + uniforms.hemisphereLights.needsUpdate = value2; + } + function materialNeedsLights(material) { + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true; + } + this.getActiveCubeFace = function() { + return _currentActiveCubeFace; + }; + this.getActiveMipmapLevel = function() { + return _currentActiveMipmapLevel; + }; + this.getRenderTarget = function() { + return _currentRenderTarget; + }; + this.setRenderTargetTextures = function(renderTarget, colorTexture, depthTexture) { + properties.get(renderTarget.texture).__webglTexture = colorTexture; + properties.get(renderTarget.depthTexture).__webglTexture = depthTexture; + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__hasExternalTextures = true; + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; + if (!renderTargetProperties.__autoAllocateDepthBuffer) { + if (extensions.has("WEBGL_multisampled_render_to_texture") === true) { + console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"); + renderTargetProperties.__useRenderToTexture = false; + } + } + }; + this.setRenderTargetFramebuffer = function(renderTarget, defaultFramebuffer) { + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; + }; + const _scratchFrameBuffer = _gl.createFramebuffer(); + this.setRenderTarget = function(renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) { + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + if (renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTargetProperties.__useDefaultFramebuffer !== undefined) { + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + useDefaultFramebuffer = false; + } else if (renderTargetProperties.__webglFramebuffer === undefined) { + textures.setupRenderTarget(renderTarget); + } else if (renderTargetProperties.__hasExternalTextures) { + textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture); + } else if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__boundDepthTexture !== depthTexture) { + if (depthTexture !== null && properties.has(depthTexture) && (renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height)) { + throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size."); + } + textures.setupDepthRenderbuffer(renderTarget); + } + } + const texture = renderTarget.texture; + if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + isRenderTarget3D = true; + } + const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget) { + if (Array.isArray(__webglFramebuffer[activeCubeFace])) { + framebuffer = __webglFramebuffer[activeCubeFace][activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer[activeCubeFace]; + } + isCube = true; + } else if (renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) { + framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer; + } else { + if (Array.isArray(__webglFramebuffer)) { + framebuffer = __webglFramebuffer[activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer; + } + } + _currentViewport.copy(renderTarget.viewport); + _currentScissor.copy(renderTarget.scissor); + _currentScissorTest = renderTarget.scissorTest; + } else { + _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor(); + _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(); + _currentScissorTest = _scissorTest; + } + if (activeMipmapLevel !== 0) { + framebuffer = _scratchFrameBuffer; + } + const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (framebufferBound && useDefaultFramebuffer) { + state.drawBuffers(renderTarget, framebuffer); + } + state.viewport(_currentViewport); + state.scissor(_currentScissor); + state.setScissorTest(_currentScissorTest); + if (isCube) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel); + } else if (isRenderTarget3D) { + const textureProperties = properties.get(renderTarget.texture); + const layer = activeCubeFace; + _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer); + } else if (renderTarget !== null && activeMipmapLevel !== 0) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel); + } + _currentMaterialId = -1; + }; + this.readRenderTargetPixels = function(renderTarget, x, y, width2, height2, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + return; + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + try { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); + return; + } + if (!capabilities.textureTypeReadable(textureType)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); + return; + } + if (x >= 0 && x <= renderTarget.width - width2 && (y >= 0 && y <= renderTarget.height - height2)) { + _gl.readPixels(x, y, width2, height2, utils.convert(textureFormat), utils.convert(textureType), buffer); + } + } finally { + const framebuffer2 = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer2); + } + } + }; + this.readRenderTargetPixelsAsync = async function(renderTarget, x, y, width2, height2, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format."); + } + if (!capabilities.textureTypeReadable(textureType)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type."); + } + if (x >= 0 && x <= renderTarget.width - width2 && (y >= 0 && y <= renderTarget.height - height2)) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + const glBuffer = _gl.createBuffer(); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.bufferData(_gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ); + _gl.readPixels(x, y, width2, height2, utils.convert(textureFormat), utils.convert(textureType), 0); + const currFramebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, currFramebuffer); + const sync = _gl.fenceSync(_gl.SYNC_GPU_COMMANDS_COMPLETE, 0); + _gl.flush(); + await probeAsync(_gl, sync, 4); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.getBufferSubData(_gl.PIXEL_PACK_BUFFER, 0, buffer); + _gl.deleteBuffer(glBuffer); + _gl.deleteSync(sync); + return buffer; + } else { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range."); + } + } + }; + this.copyFramebufferToTexture = function(texture, position2 = null, level = 0) { + if (texture.isTexture !== true) { + warnOnce("WebGLRenderer: copyFramebufferToTexture function signature has changed."); + position2 = arguments[0] || null; + texture = arguments[1]; + } + const levelScale = Math.pow(2, -level); + const width2 = Math.floor(texture.image.width * levelScale); + const height2 = Math.floor(texture.image.height * levelScale); + const x = position2 !== null ? position2.x : 0; + const y = position2 !== null ? position2.y : 0; + textures.setTexture2D(texture, 0); + _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, x, y, width2, height2); + state.unbindTexture(); + }; + const _srcFramebuffer = _gl.createFramebuffer(); + const _dstFramebuffer = _gl.createFramebuffer(); + this.copyTextureToTexture = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null) { + if (srcTexture.isTexture !== true) { + warnOnce("WebGLRenderer: copyTextureToTexture function signature has changed."); + dstPosition = arguments[0] || null; + srcTexture = arguments[1]; + dstTexture = arguments[2]; + dstLevel = arguments[3] || 0; + srcRegion = null; + } + if (dstLevel === null) { + if (srcLevel !== 0) { + warnOnce("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."); + dstLevel = srcLevel; + srcLevel = 0; + } else { + dstLevel = 0; + } + } + let width2, height2, depth2, minX, minY, minZ; + let dstX, dstY, dstZ; + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[dstLevel] : srcTexture.image; + if (srcRegion !== null) { + width2 = srcRegion.max.x - srcRegion.min.x; + height2 = srcRegion.max.y - srcRegion.min.y; + depth2 = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1; + minX = srcRegion.min.x; + minY = srcRegion.min.y; + minZ = srcRegion.isBox3 ? srcRegion.min.z : 0; + } else { + const levelScale = Math.pow(2, -srcLevel); + width2 = Math.floor(image.width * levelScale); + height2 = Math.floor(image.height * levelScale); + if (srcTexture.isDataArrayTexture) { + depth2 = image.depth; + } else if (srcTexture.isData3DTexture) { + depth2 = Math.floor(image.depth * levelScale); + } else { + depth2 = 1; + } + minX = 0; + minY = 0; + minZ = 0; + } + if (dstPosition !== null) { + dstX = dstPosition.x; + dstY = dstPosition.y; + dstZ = dstPosition.z; + } else { + dstX = 0; + dstY = 0; + dstZ = 0; + } + const glFormat = utils.convert(dstTexture.format); + const glType = utils.convert(dstTexture.type); + let glTarget; + if (dstTexture.isData3DTexture) { + textures.setTexture3D(dstTexture, 0); + glTarget = _gl.TEXTURE_3D; + } else if (dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture) { + textures.setTexture2DArray(dstTexture, 0); + glTarget = _gl.TEXTURE_2D_ARRAY; + } else { + textures.setTexture2D(dstTexture, 0); + glTarget = _gl.TEXTURE_2D; + } + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment); + const currentUnpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH); + const currentUnpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT); + const currentUnpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS); + const currentUnpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS); + const currentUnpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES); + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, minX); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, minY); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, minZ); + const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture; + const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture; + if (srcTexture.isDepthTexture) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + const srcRenderTargetProperties = properties.get(srcTextureProperties.__renderTarget); + const dstRenderTargetProperties = properties.get(dstTextureProperties.__renderTarget); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer); + for (let i = 0;i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(srcTexture).__webglTexture, srcLevel, minZ + i); + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(dstTexture).__webglTexture, dstLevel, dstZ + i); + } + _gl.blitFramebuffer(minX, minY, width2, height2, dstX, dstY, width2, height2, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST); + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else if (srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has(srcTexture)) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, _srcFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, _dstFramebuffer); + for (let i = 0;i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i); + } else { + _gl.framebufferTexture2D(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel); + } + if (isDst3D) { + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i); + } else { + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel); + } + if (srcLevel !== 0) { + _gl.blitFramebuffer(minX, minY, width2, height2, dstX, dstY, width2, height2, _gl.COLOR_BUFFER_BIT, _gl.NEAREST); + } else if (isDst3D) { + _gl.copyTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width2, height2); + } else { + _gl.copyTexSubImage2D(glTarget, dstLevel, dstX, dstY, minX, minY, width2, height2); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else { + if (isDst3D) { + if (srcTexture.isDataTexture || srcTexture.isData3DTexture) { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, glType, image.data); + } else if (dstTexture.isCompressedArrayTexture) { + _gl.compressedTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, image.data); + } else { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, glType, image); + } + } else { + if (srcTexture.isDataTexture) { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width2, height2, glFormat, glType, image.data); + } else if (srcTexture.isCompressedTexture) { + _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data); + } else { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width2, height2, glFormat, glType, image); + } + } + } + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, currentUnpackRowLen); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages); + if (dstLevel === 0 && dstTexture.generateMipmaps) { + _gl.generateMipmap(glTarget); + } + state.unbindTexture(); + }; + this.copyTextureToTexture3D = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0) { + if (srcTexture.isTexture !== true) { + warnOnce("WebGLRenderer: copyTextureToTexture3D function signature has changed."); + srcRegion = arguments[0] || null; + dstPosition = arguments[1] || null; + srcTexture = arguments[2]; + dstTexture = arguments[3]; + level = arguments[4] || 0; + } + warnOnce('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'); + return this.copyTextureToTexture(srcTexture, dstTexture, srcRegion, dstPosition, level); + }; + this.initRenderTarget = function(target) { + if (properties.get(target).__webglFramebuffer === undefined) { + textures.setupRenderTarget(target); + } + }; + this.initTexture = function(texture) { + if (texture.isCubeTexture) { + textures.setTextureCube(texture, 0); + } else if (texture.isData3DTexture) { + textures.setTexture3D(texture, 0); + } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + textures.setTexture2DArray(texture, 0); + } else { + textures.setTexture2D(texture, 0); + } + state.unbindTexture(); + }; + this.resetState = function() { + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + state.reset(); + bindingStates.reset(); + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + get coordinateSystem() { + return WebGLCoordinateSystem; + } + get outputColorSpace() { + return this._outputColorSpace; + } + set outputColorSpace(colorSpace) { + this._outputColorSpace = colorSpace; + const gl = this.getContext(); + gl.drawingBufferColorspace = ColorManagement._getDrawingBufferColorSpace(colorSpace); + gl.unpackColorSpace = ColorManagement._getUnpackColorSpace(); + } +} + +// src/external/ffl.js/ffl.js +var _Import = __toESM(require_struct_fu(), 1); +/*! + * Bindings for FFL, a Mii renderer, in JavaScript. + * https://github.com/ariankordi/FFL.js + * @author Arian Kordi + */ +globalThis._ = globalThis._; +globalThis.THREE = globalThis.THREE; +var _ = globalThis._; +_ = !_ ? _Import : _; +var FFLResult = { + OK: 0, + ERROR: 1, + HDB_EMPTY: 2, + FILE_INVALID: 3, + MANAGER_NOT_CONSTRUCT: 4, + FILE_LOAD_ERROR: 5, + FILE_SAVE_ERROR: 7, + RES_FS_ERROR: 9, + ODB_EMPTY: 10, + OUT_OF_MEMORY: 12, + UNKNOWN_17: 17, + FS_ERROR: 18, + FS_NOT_FOUND: 19, + MAX: 20 +}; +var FFLiShapeType = { + OPA_BEARD: 0, + OPA_FACELINE: 1, + OPA_HAIR_NORMAL: 2, + OPA_FOREHEAD_NORMAL: 3, + XLU_MASK: 4, + XLU_NOSELINE: 5, + OPA_NOSE: 6, + OPA_HAT_NORMAL: 7, + XLU_GLASS: 8, + OPA_HAIR_CAP: 9, + OPA_FOREHEAD_CAP: 10, + OPA_HAT_CAP: 11, + MAX: 12 +}; +var FFLAttributeBufferType = { + POSITION: 0, + TEXCOORD: 1, + NORMAL: 2, + TANGENT: 3, + COLOR: 4, + MAX: 5 +}; +var FFLCullMode = { + NONE: 0, + BACK: 1, + FRONT: 2, + MAX: 3 +}; +var FFLModulateMode = { + CONSTANT: 0, + TEXTURE_DIRECT: 1, + RGB_LAYERED: 2, + ALPHA: 3, + LUMINANCE_ALPHA: 4, + ALPHA_OPA: 5 +}; +var FFLModulateType = { + SHAPE_FACELINE: 0, + SHAPE_BEARD: 1, + SHAPE_NOSE: 2, + SHAPE_FOREHEAD: 3, + SHAPE_HAIR: 4, + SHAPE_CAP: 5, + SHAPE_MASK: 6, + SHAPE_NOSELINE: 7, + SHAPE_GLASS: 8, + MUSTACHE: 9, + MOUTH: 10, + EYEBROW: 11, + EYE: 12, + MOLE: 13, + FACE_MAKE: 14, + FACE_LINE: 15, + FACE_BEARD: 16, + FILL: 17, + SHAPE_MAX: 9 +}; +var FFLResourceType = { + MIDDLE: 0, + HIGH: 1, + MAX: 2 +}; +var FFLExpression = { + NORMAL: 0, + SMILE: 1, + ANGER: 2, + SORROW: 3, + PUZZLED: 3, + SURPRISE: 4, + SURPRISED: 4, + BLINK: 5, + OPEN_MOUTH: 6, + SMILE_OPEN_MOUTH: 7, + HAPPY: 7, + ANGER_OPEN_MOUTH: 8, + SORROW_OPEN_MOUTH: 9, + SURPRISE_OPEN_MOUTH: 10, + BLINK_OPEN_MOUTH: 11, + WINK_LEFT: 12, + WINK_RIGHT: 13, + WINK_LEFT_OPEN_MOUTH: 14, + WINK_RIGHT_OPEN_MOUTH: 15, + LIKE_WINK_LEFT: 16, + LIKE: 16, + LIKE_WINK_RIGHT: 17, + FRUSTRATED: 18, + BORED: 19, + BORED_OPEN_MOUTH: 20, + SIGH_MOUTH_STRAIGHT: 21, + SIGH: 22, + DISGUSTED_MOUTH_STRAIGHT: 23, + DISGUSTED: 24, + LOVE: 25, + LOVE_OPEN_MOUTH: 26, + DETERMINED_MOUTH_STRAIGHT: 27, + DETERMINED: 28, + CRY_MOUTH_STRAIGHT: 29, + CRY: 30, + BIG_SMILE_MOUTH_STRAIGHT: 31, + BIG_SMILE: 32, + CHEEKY: 33, + CHEEKY_DUPLICATE: 34, + JOJO_EYES_FUNNY_MOUTH: 35, + JOJO_EYES_FUNNY_MOUTH_OPEN: 36, + SMUG: 37, + SMUG_OPEN_MOUTH: 38, + RESOLVE: 39, + RESOLVE_OPEN_MOUTH: 40, + UNBELIEVABLE: 41, + UNBELIEVABLE_DUPLICATE: 42, + CUNNING: 43, + CUNNING_DUPLICATE: 44, + RASPBERRY: 45, + RASPBERRY_DUPLICATE: 46, + INNOCENT: 47, + INNOCENT_DUPLICATE: 48, + CAT: 49, + CAT_DUPLICATE: 50, + DOG: 51, + DOG_DUPLICATE: 52, + TASTY: 53, + TASTY_DUPLICATE: 54, + MONEY_MOUTH_STRAIGHT: 55, + MONEY: 56, + SPIRAL_MOUTH_STRAIGHT: 57, + CONFUSED: 58, + CHEERFUL_MOUTH_STRAIGHT: 59, + CHEERFUL: 60, + BLANK_61: 61, + BLANK_62: 62, + GRUMBLE_MOUTH_STRAIGHT: 63, + GRUMBLE: 64, + MOVED_MOUTH_STRAIGHT: 65, + MOVED: 66, + SINGING_MOUTH_SMALL: 67, + SINGING: 68, + STUNNED: 69, + MAX: 70 +}; +var FFLModelFlag = { + NORMAL: 1 << 0, + HAT: 1 << 1, + FACE_ONLY: 1 << 2, + FLATTEN_NOSE: 1 << 3, + NEW_EXPRESSIONS: 1 << 4, + NEW_MASK_ONLY: 1 << 5 +}; +var _uintptr = _.uint32le; +var FFLAttributeBuffer = _.struct([ + _.uint32le("size"), + _.uint32le("stride"), + _uintptr("ptr") +]); +var FFLAttributeBufferParam = _.struct([ + _.struct("attributeBuffers", [FFLAttributeBuffer], 5) +]); +var FFLPrimitiveParam = _.struct([ + _.uint32le("primitiveType"), + _.uint32le("indexCount"), + _uintptr("pAdjustMatrix"), + _uintptr("pIndexBuffer") +]); +var FFLColor = _.struct([ + _.float32le("r"), + _.float32le("g"), + _.float32le("b"), + _.float32le("a") +]); +var FFLVec3 = _.struct([ + _.float32le("x"), + _.float32le("y"), + _.float32le("z") +]); +var FFLModulateParam = _.struct([ + _.uint32le("mode"), + _.uint32le("type"), + _uintptr("pColorR"), + _uintptr("pColorG"), + _uintptr("pColorB"), + _uintptr("pTexture2D") +]); +var FFLDrawParam = _.struct([ + _.struct("attributeBufferParam", [FFLAttributeBufferParam]), + _.struct("modulateParam", [FFLModulateParam]), + _.uint32le("cullMode"), + _.struct("primitiveParam", [FFLPrimitiveParam]) +]); +var FFLCreateID = _.struct([ + _.uint8("data", 10) +]); +var FFLiCharInfo = _.struct([ + _.int32le("miiVersion"), + _.struct("faceline", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("texture"), + _.int32le("make") + ]), + _.struct("hair", [_.int32le("type"), _.int32le("color"), _.int32le("flip")]), + _.struct("eye", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("aspect"), + _.int32le("rotate"), + _.int32le("x"), + _.int32le("y") + ]), + _.struct("eyebrow", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("aspect"), + _.int32le("rotate"), + _.int32le("x"), + _.int32le("y") + ]), + _.struct("nose", [ + _.int32le("type"), + _.int32le("scale"), + _.int32le("y") + ]), + _.struct("mouth", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("aspect"), + _.int32le("y") + ]), + _.struct("beard", [ + _.int32le("mustache"), + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("y") + ]), + _.struct("glass", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("y") + ]), + _.struct("mole", [ + _.int32le("type"), + _.int32le("scale"), + _.int32le("x"), + _.int32le("y") + ]), + _.struct("body", [_.int32le("height"), _.int32le("build")]), + _.struct("personal", [ + _.char16le("name", 22), + _.char16le("creator", 22), + _.int32le("gender"), + _.int32le("birthMonth"), + _.int32le("birthDay"), + _.int32le("favoriteColor"), + _.uint8("favorite"), + _.uint8("copyable"), + _.uint8("ngWord"), + _.uint8("localonly"), + _.int32le("regionMove"), + _.int32le("fontRegion"), + _.int32le("roomIndex"), + _.int32le("positionInRoom"), + _.int32le("birthPlatform") + ]), + _.struct("createID", [FFLCreateID]), + _.uint16le("padding_0"), + _.int32le("authorType"), + _.uint8("authorID", 8) +]); +var FFLStoreData_size = 96; +var commonColorEnableMask = 1 << 31; +var commonColorMask = (color) => color | commonColorEnableMask; +var FFLAdditionalInfo = _.struct([ + _.char16le("name", 22), + _.char16le("creator", 22), + _.struct("createID", [FFLCreateID]), + _.byte("_padding0", 2), + _.struct("skinColor", [FFLColor]), + _.uint32le("flags"), + _.uint8("facelineType"), + _.uint8("hairType"), + _.byte("_padding1", 2) +]); +var FFLiRenderTexture = _.struct([ + _uintptr("pTexture2DRenderBufferColorTargetDepthTarget", 4) +]); +var FFLiFacelineTextureTempObject = _.struct([ + _uintptr("pTextureFaceLine"), + _.struct("drawParamFaceLine", [FFLDrawParam]), + _uintptr("pTextureFaceMake"), + _.struct("drawParamFaceMake", [FFLDrawParam]), + _uintptr("pTextureFaceBeard"), + _.struct("drawParamFaceBeard", [FFLDrawParam]), + _uintptr("pRenderTextureCompressorParam", 2) +]); +var FFLiRawMaskDrawParam = _.struct([ + _.struct("drawParamRawMaskPartsEye", [FFLDrawParam], 2), + _.struct("drawParamRawMaskPartsEyebrow", [FFLDrawParam], 2), + _.struct("drawParamRawMaskPartsMouth", [FFLDrawParam]), + _.struct("drawParamRawMaskPartsMustache", [FFLDrawParam], 2), + _.struct("drawParamRawMaskPartsMole", [FFLDrawParam]), + _.struct("drawParamRawMaskPartsFill", [FFLDrawParam]) +]); +var FFLiMaskTexturesTempObject = _.struct([ + _.uint8("partsTextures", 340), + _uintptr("pRawMaskDrawParam", FFLExpression.MAX), + _.byte("_remaining", 904 - 620) +]); +var FFLiTextureTempObject = _.struct([ + _.struct("maskTextures", [FFLiMaskTexturesTempObject]), + _.struct("facelineTexture", [FFLiFacelineTextureTempObject]) +]); +var FFLiMaskTextures = _.struct([ + _uintptr("pRenderTextures", FFLExpression.MAX) +]); +var FFL_RESOLUTION_MASK = 1073741823; +var FFLCharModelDesc = _.struct([ + _.uint32le("resolution"), + _.uint32le("allExpressionFlag", 3), + _.uint32le("modelFlag"), + _.uint32le("resourceType") +]); +var FFLCharModelDescDefault = { + resolution: 512, + allExpressionFlag: new Uint32Array([1, 0, 0]), + modelFlag: FFLModelFlag.NORMAL, + resourceType: FFLResourceType.HIGH +}; +var FFLBoundingBox = _.struct([ + _.struct("min", [FFLVec3]), + _.struct("max", [FFLVec3]) +]); +var FFLPartsTransform = _.struct([ + _.struct("hatTranslate", [FFLVec3]), + _.struct("headFrontRotate", [FFLVec3]), + _.struct("headFrontTranslate", [FFLVec3]), + _.struct("headSideRotate", [FFLVec3]), + _.struct("headSideTranslate", [FFLVec3]), + _.struct("headTopRotate", [FFLVec3]), + _.struct("headTopTranslate", [FFLVec3]) +]); +var FFLiCharModel = _.struct([ + _.struct("charInfo", [FFLiCharInfo]), + _.struct("charModelDesc", [FFLCharModelDesc]), + _.uint32le("expression"), + _uintptr("pTextureTempObject"), + _.struct("drawParam", [FFLDrawParam], FFLiShapeType.MAX), + _uintptr("pShapeData", FFLiShapeType.MAX), + _.struct("facelineRenderTexture", [FFLiRenderTexture]), + _uintptr("pCapGlassNoselineTextures", 3), + _.struct("maskTextures", [FFLiMaskTextures]), + _.struct("beardHairFaceCenterPos", [FFLVec3], 3), + _.struct("partsTransform", [FFLPartsTransform]), + _.uint32le("modelType"), + _.struct("boundingBox", [FFLBoundingBox], 3) +]); +var FFLDataSource = { + OFFICIAL: 0, + DEFAULT: 1, + MIDDLE_DB: 2, + STORE_DATA_OFFICIAL: 3, + STORE_DATA: 4, + BUFFER: 5, + DIRECT_POINTER: 6 +}; +var FFLCharModelSource = _.struct([ + _.uint32le("dataSource"), + _uintptr("pBuffer"), + _.uint16le("index") +]); +var FFLResourceDesc = _.struct([ + _uintptr("pData", FFLResourceType.MAX), + _.uint32le("size", FFLResourceType.MAX) +]); +var FFLTextureFormat = { + R8_UNORM: 0, + R8_G8_UNORM: 1, + R8_G8_B8_A8_UNORM: 2, + MAX: 3 +}; +var FFLTextureInfo = _.struct([ + _.uint16le("width"), + _.uint16le("height"), + _.uint8("mipCount"), + _.uint8("format"), + _.uint8("isGX2Tiled"), + _.byte("_padding", 1), + _.uint32le("imageSize"), + _uintptr("imagePtr"), + _.uint32le("mipSize"), + _uintptr("mipPtr"), + _.uint32le("mipLevelOffset", 13) +]); +var FFLTextureCallback = _.struct([ + _uintptr("pObj"), + _.uint8("useOriginalTileMode"), + _.byte("_padding", 3), + _uintptr("pCreateFunc"), + _uintptr("pDeleteFunc") +]); + +class TextureManager { + constructor(module2, setToFFLGlobal = false) { + this._module = module2; + this._textures = new Map; + this._textureCallbackPtr = 0; + this.logging = false; + this._setTextureCallback(); + if (setToFFLGlobal) { + module2._FFLSetTextureCallback(this._textureCallbackPtr); + } + } + static _allocateTextureCallback(module2, createCallback, deleteCallback) { + const ptr = module2._malloc(FFLTextureCallback.size); + const textureCallback = { + pObj: 0, + useOriginalTileMode: false, + _padding: [0, 0, 0], + pCreateFunc: createCallback, + pDeleteFunc: deleteCallback + }; + const packed = FFLTextureCallback.pack(textureCallback); + module2.HEAPU8.set(packed, ptr); + return ptr; + } + _setTextureCallback(addDeleteCallback = false) { + const mod2 = this._module; + this._createCallback = mod2.addFunction(this._textureCreateFunc.bind(this), "vppp"); + if (addDeleteCallback) { + this._deleteCallback = mod2.addFunction(this._textureDeleteFunc.bind(this), "vpp"); + } + this._textureCallbackPtr = TextureManager._allocateTextureCallback(mod2, this._createCallback, this._deleteCallback ? this._deleteCallback : 0); + } + _getTextureFormat(format) { + const useGLES2Formats = Number(REVISION) <= 136; + const r8 = useGLES2Formats ? LuminanceFormat : RedFormat; + const r8g8 = useGLES2Formats ? LuminanceAlphaFormat : RGFormat; + const textureFormatToThreeFormat = { + [FFLTextureFormat.R8_UNORM]: r8, + [FFLTextureFormat.R8_G8_UNORM]: r8g8, + [FFLTextureFormat.R8_G8_B8_A8_UNORM]: RGBAFormat + }; + const dataFormat = textureFormatToThreeFormat[format]; + if (dataFormat === undefined) { + throw new Error(`_textureCreateFunc: Unexpected FFLTextureFormat value: ${format}`); + } + return dataFormat; + } + _textureCreateFunc(_2, textureInfoPtr, texturePtrPtr) { + const u8 = this._module.HEAPU8.subarray(textureInfoPtr, textureInfoPtr + FFLTextureInfo.size); + const textureInfo = FFLTextureInfo.unpack(u8); + if (this.logging) { + console.debug(`_textureCreateFunc: width=${textureInfo.width}, height=${textureInfo.height}, format=${textureInfo.format}, imageSize=${textureInfo.imageSize}, mipCount=${textureInfo.mipCount}`); + } + const format = this._getTextureFormat(textureInfo.format); + const imageData = this._module.HEAPU8.slice(textureInfo.imagePtr, textureInfo.imagePtr + textureInfo.imageSize); + const canUseMipmaps = Number(REVISION) >= 138; + const useMipmaps = textureInfo.mipCount > 1 && canUseMipmaps; + const texture = new DataTexture(useMipmaps ? null : imageData, textureInfo.width, textureInfo.height, format, UnsignedByteType); + texture.magFilter = LinearFilter; + texture.minFilter = LinearFilter; + if (useMipmaps) { + texture.mipmaps = [{ + data: imageData, + width: textureInfo.width, + height: textureInfo.height + }]; + texture.minFilter = LinearMipmapLinearFilter; + texture.generateMipmaps = false; + this._addMipmaps(texture, textureInfo); + } + texture.needsUpdate = true; + this.set(texture.id, texture); + this._module.HEAPU32[texturePtrPtr / 4] = texture.id; + } + _addMipmaps(texture, textureInfo) { + if (textureInfo.mipPtr === 0) { + throw new Error("_addMipmaps: mipPtr is null, so the caller incorrectly assumed this texture has mipmaps"); + } + for (let mipLevel = 1;mipLevel < textureInfo.mipCount; mipLevel++) { + const mipOffset = textureInfo.mipLevelOffset[mipLevel - 1]; + const mipWidth = Math.max(1, textureInfo.width >> mipLevel); + const mipHeight = Math.max(1, textureInfo.height >> mipLevel); + const nextMipOffset = textureInfo.mipLevelOffset[mipLevel] || textureInfo.mipSize; + const end = textureInfo.mipPtr + nextMipOffset; + const start = textureInfo.mipPtr + mipOffset; + const mipData = this._module.HEAPU8.slice(start, end); + if (this.logging) { + console.debug(` - Mip ${mipLevel}: ${mipWidth}x${mipHeight}, offset=${mipOffset}, range=${start}-${end}`); + } + texture.mipmaps.push({ + data: mipData, + width: mipWidth, + height: mipHeight + }); + } + } + _textureDeleteFunc(_2, texturePtrPtr) { + const texId = this._module.HEAPU32[texturePtrPtr / 4]; + const tex = this._textures.get(texId); + if (tex && this.logging) { + console.debug("Delete texture ", tex.id); + } + } + get(id) { + const texture = this._textures.get(id); + if (!texture && this.logging) { + console.error("Unknown texture", id); + } + return texture; + } + set(id, texture) { + const disposeReal = texture.dispose.bind(texture); + texture.dispose = () => { + disposeReal(); + this.delete(id); + }; + this._textures.set(id, texture); + if (this.logging) { + console.debug("Adding texture ", texture.id); + } + } + delete(id) { + const texture = this._textures.get(id); + if (texture) { + texture.source = null; + texture.mipmaps = null; + if (this.logging) { + console.debug("Deleted texture ", id); + } + this._textures.delete(id); + } + } + disposeCallback() { + if (this._textureCallbackPtr) { + this._module._free(this._textureCallbackPtr); + this._textureCallbackPtr = 0; + } + if (this._deleteCallback) { + this._module.removeFunction(this._deleteCallback); + this._deleteCallback = 0; + } + if (this._createCallback) { + this._module.removeFunction(this._createCallback); + this._createCallback = 0; + } + } + dispose() { + this._textures.forEach((tex) => { + tex.dispose(); + }); + this._textures.clear(); + this.disposeCallback(); + } +} + +class FFLResultException extends Error { + constructor(result, funcName, message) { + if (!message) { + if (funcName) { + message = `${funcName} failed with FFLResult: ${result}`; + } else { + message = `From FFLResult: ${result}`; + } + } + super(message); + this.result = result; + } + static handleResult(result, funcName) { + switch (result) { + case FFLResult.ERROR: + throw new FFLResultWrongParam(funcName); + case FFLResult.FILE_INVALID: + throw new FFLResultBroken(funcName); + case FFLResult.MANAGER_NOT_CONSTRUCT: + throw new FFLResultNotAvailable(funcName); + case FFLResult.FILE_LOAD_ERROR: + throw new FFLResultFatal(funcName); + case FFLResult.OK: + return; + default: + throw new FFLResultException(result, funcName); + } + } +} + +class FFLResultWrongParam extends FFLResultException { + constructor(funcName) { + super(1, funcName, `${funcName} returned FFL_RESULT_WRONG_PARAM. This usually means parameters going into that function were invalid.`); + } +} + +class FFLResultBroken extends FFLResultException { + constructor(funcName, message) { + super(3, funcName, message ? message : `${funcName} returned FFL_RESULT_BROKEN. This usually indicates invalid underlying data.`); + } +} + +class BrokenInitRes extends FFLResultBroken { + constructor() { + super("FFLInitRes", 'The header for the FFL resource is probably invalid. Check the version and magic, should be "FFRA" or "ARFF".'); + } +} + +class BrokenInitModel extends FFLResultBroken { + constructor() { + super("FFLInitCharModelCPUStep", "FFLInitCharModelCPUStep failed probably because your data failed CRC or CharInfo verification (FFLiVerifyCharInfoWithReason)."); + } +} + +class FFLResultNotAvailable extends FFLResultException { + constructor(funcName) { + super(4, funcName, `Tried to call FFL function ${funcName} when FFLManager is not constructed (FFL is not initialized properly).`); + } +} + +class FFLResultFatal extends FFLResultException { + constructor(funcName) { + super(5, funcName, `Failed to uncompress or load a specific asset from the FFL resource file during call to ${funcName}`); + } +} + +class FFLiVerifyReasonException extends Error { + constructor(result) { + super(`FFLiVerifyCharInfoWithReason (CharInfo verification) failed with result: ${result}`); + this.result = result; + } +} + +class ExpressionNotSet extends Error { + constructor(expression) { + super(`Attempted to set expression ${expression}, but the mask for that expression does not exist. You must reinitialize the CharModel with this expression in the expression flags before using it.`); + this.expression = expression; + } +} +async function _loadDataIntoHeap(resource, module2) { + let heapSize; + let heapPtr; + try { + if (resource instanceof ArrayBuffer) { + resource = new Uint8Array(resource); + } + if (resource instanceof Uint8Array) { + heapSize = resource.length; + heapPtr = module2._malloc(heapSize); + console.debug(`_loadDataIntoHeap: Loading from buffer. Size: ${heapSize}, pointer: ${heapPtr}`); + module2.HEAPU8.set(resource, heapPtr); + } else if (resource instanceof Response) { + if (!resource.ok) { + throw new Error(`HTTP error while fetching resource at URL = ${resource.url}, response code = ${resource.status}`); + } + if (!resource.body) { + throw new Error(`Response body is null (resource.body = ${resource.body})`); + } + const contentLength = resource.headers.get("Content-Length"); + if (!contentLength) { + console.debug("_loadDataIntoHeap: Fetch response is missing Content-Length, falling back to reading as ArrayBuffer."); + return _loadDataIntoHeap(await resource.arrayBuffer(), module2); + } + heapSize = parseInt(contentLength, 10); + heapPtr = module2._malloc(heapSize); + console.debug(`loadDataIntoHeap: Streaming from fetch response. Size: ${heapSize}, pointer: ${heapPtr}, URL: ${resource.url}`); + const reader = resource.body.getReader(); + let offset = heapPtr; + while (true) { + const { done, value: value2 } = await reader.read(); + if (done) { + break; + } + module2.HEAPU8.set(value2, offset); + offset += value2.length; + } + } else { + throw new Error("loadDataIntoHeap: type is not Uint8Array or Response"); + } + return { pointer: heapPtr, size: heapSize }; + } catch (error) { + if (heapPtr) { + module2._free(heapPtr); + } + throw error; + } +} +async function initializeFFL(resource, moduleOrPromise) { + console.debug("initializeFFL: Entrypoint, waiting for module to be ready."); + let resourceDescPtr; + function freeResDesc() { + if (resourceDescPtr) { + module2._free(resourceDescPtr); + } + } + const resourceType = FFLResourceType.HIGH; + let module2; + if (typeof moduleOrPromise === "function") { + moduleOrPromise = moduleOrPromise(); + } + if (moduleOrPromise instanceof Promise) { + module2 = await moduleOrPromise; + } else { + module2 = moduleOrPromise; + } + if (!module2.calledRun && !module2.onRuntimeInitialized) { + await new Promise((resolve) => { + module2.onRuntimeInitialized = () => { + console.debug("initializeFFL: Emscripten runtime initialized, resolving."); + resolve(null); + }; + console.debug(`initializeFFL: module.calledRun: ${module2.calledRun}, module.onRuntimeInitialized: +${module2.onRuntimeInitialized} + // ^^ assigned and waiting.`); + }); + } else { + console.debug("initializeFFL: Assuming module is ready."); + } + let resourceDesc = null; + try { + if (resource instanceof Promise) { + resource = await resource; + } + const { pointer: heapPtr, size: heapSize } = await _loadDataIntoHeap(resource, module2); + console.debug(`initializeFFL: Resource loaded into heap. Pointer: ${heapPtr}, Size: ${heapSize}`); + resourceDesc = { pData: [0, 0], size: [0, 0] }; + resourceDesc.pData[resourceType] = heapPtr; + resourceDesc.size[resourceType] = heapSize; + const resourceDescData = FFLResourceDesc.pack(resourceDesc); + resourceDescPtr = module2._malloc(FFLResourceDesc.size); + module2.HEAPU8.set(resourceDescData, resourceDescPtr); + const result = module2._FFLInitRes(0, resourceDescPtr); + if (result === FFLResult.FILE_INVALID) { + throw new BrokenInitRes; + } + FFLResultException.handleResult(result, "FFLInitRes"); + module2._FFLInitResGPUStep(); + module2._FFLSetNormalIsSnorm8_8_8_8(true); + module2._FFLSetTextureFlipY(true); + } catch (error) { + _freeResourceDesc(resourceDesc, module2); + freeResDesc(); + console.error("initializeFFL failed:", error); + throw error; + } finally { + freeResDesc(); + } + return { + module: module2, + resourceDesc + }; +} +async function initializeFFLWithResource(module2, resourcePath) { + const querySelectorResourcePath = "meta[itemprop=ffl-js-resource-fetch-path]"; + if (!resourcePath && typeof document !== "undefined") { + const resourceFetchElement = document.querySelector(querySelectorResourcePath); + if (!resourceFetchElement || !resourceFetchElement.getAttribute("content")) { + throw new Error(`initializeFFLWithResource: Element not found or does not have "content" attribute with path to FFL resource: ${querySelectorResourcePath}`); + } + resourcePath = resourceFetchElement.getAttribute("content"); + } + if (!resourcePath) { + throw new Error("initializeFFLWithResource: resourcePath must be a string"); + } + try { + const response = await fetch(resourcePath); + const ret = await initializeFFL(response, module2); + console.debug("initializeFFLWithResource: FFLiManager and TextureManager initialized, exiting"); + return ret; + } catch (error) { + if (typeof alert !== "undefined") { + alert(`Error initializing FFL with resource: ${error}`); + } + throw error; + } +} +function _freeResourceDesc(desc, module2) { + if (!desc || !desc.pData) { + return; + } + desc.pData.forEach((ptr, i) => { + if (ptr) { + module2._free(ptr); + desc.pData[i] = 0; + } + }); +} +class CharModel { + constructor(ptr, module2, materialClass, texManager) { + this._module = module2; + this._data = null; + this._materialClass = materialClass; + this._materialTextureClass = materialClass; + this._textureManager = texManager; + this._ptr = ptr; + this.__ptr = ptr; + const charModelData = this._module.HEAPU8.subarray(ptr, ptr + FFLiCharModel.size); + this._model = FFLiCharModel.unpack(charModelData); + this._facelineTarget = null; + this._maskTargets = new Array(FFLExpression.MAX).fill(null); + this.meshes = new Group; + this._addCharModelMeshes(module2); + } + _addCharModelMeshes(module2) { + if (!this.meshes) { + throw new Error("_addCharModelMeshes: this.meshes is null or undefined, was this CharModel disposed?"); + } + for (let shapeType = 0;shapeType < FFLiShapeType.MAX; shapeType++) { + const drawParam = this._model.drawParam[shapeType]; + const mesh = drawParamToMesh(drawParam, this._materialClass, module2, this._textureManager); + if (!mesh) { + continue; + } + mesh.renderOrder = drawParam.modulateParam.type; + switch (shapeType) { + case FFLiShapeType.OPA_FACELINE: + this._facelineMesh = mesh; + break; + case FFLiShapeType.XLU_MASK: + this._maskMesh = mesh; + break; + } + this.meshes.add(mesh); + } + } + _getTextureTempObjectPtr() { + return this._model.pTextureTempObject; + } + _getTextureTempObject() { + const ptr = this._getTextureTempObjectPtr(); + return FFLiTextureTempObject.unpack(this._module.HEAPU8.subarray(ptr, ptr + FFLiTextureTempObject.size)); + } + _getPartsTransform() { + const obj = this._model.partsTransform; + const newPartsTransform = {}; + for (const key2 in obj) { + const vec = obj[key2]; + if (vec.x === undefined) { + throw new Error; + } + newPartsTransform[key2] = new Vector3(vec.x, vec.y, vec.z); + } + return newPartsTransform; + } + _getFacelineColor() { + const mod2 = this._module; + const facelineColor = this._model.charInfo.faceline.color; + const colorPtr = mod2._malloc(FFLColor.size); + mod2._FFLGetFacelineColor(colorPtr, facelineColor); + const color = _getFFLColor3(_getFFLColor(colorPtr, mod2.HEAPF32)); + mod2._free(colorPtr); + return color; + } + _getFavoriteColor() { + const mod2 = this._module; + const favoriteColor = this._model.charInfo.personal.favoriteColor; + const colorPtr = mod2._malloc(FFLColor.size); + mod2._FFLGetFavoriteColor(colorPtr, favoriteColor); + const color = _getFFLColor3(_getFFLColor(colorPtr, mod2.HEAPF32)); + mod2._free(colorPtr); + return color; + } + _getCharInfoUint8Array() { + return FFLiCharInfo.pack(this._model.charInfo); + } + _getPartsTexturesPtr() { + return this._model.pTextureTempObject + FFLiTextureTempObject.fields.maskTextures.offset + FFLiMaskTexturesTempObject.fields.partsTextures.offset; + } + _getFacelineTempObjectPtr() { + return this._model.pTextureTempObject + FFLiTextureTempObject.fields.facelineTexture.offset; + } + _getMaskTempObjectPtr() { + return this._model.pTextureTempObject + FFLiTextureTempObject.fields.maskTextures.offset; + } + _getExpressionFlagPtr() { + return this._ptr + FFLiCharModel.fields.charModelDesc.offset + FFLCharModelDesc.fields.allExpressionFlag.offset; + } + _getBoundingBox() { + const bbox = this._model.boundingBox[this._model.modelType]; + if (!(bbox.max.x === 0 && bbox.max.y === 0 && bbox.max.z === 0)) { + const min = new Vector3(bbox.min.x, bbox.min.y, bbox.min.z); + const max = new Vector3(bbox.max.x, bbox.max.y, bbox.max.z); + return new Box3(min, max); + } + const excludeFromBox = [FFLModulateType.SHAPE_MASK, FFLModulateType.SHAPE_GLASS]; + const box = new Box3; + if (!this.meshes) { + throw new Error("_getBoundingBox: this.meshes is null."); + } + this.meshes.traverse((child) => { + if (!(child instanceof Mesh) || excludeFromBox.indexOf(child.geometry.userData.modulateType) !== -1) { + return; + } + box.expandByObject(child); + }); + return box; + } + _getResolution() { + return this._model.charModelDesc.resolution & FFL_RESOLUTION_MASK; + } + _finalizeCharModel() { + if (!this._ptr) { + return; + } + this._module._FFLDeleteCharModel(this._ptr); + this._module._free(this._ptr); + this._ptr = 0; + } + disposeTargets() { + if (this._facelineTarget) { + console.debug(`Disposing target ${this._facelineTarget.texture.id} for faceline`); + this._facelineTarget.dispose(); + this._facelineTarget = null; + } + this._maskTargets.forEach((target, i) => { + if (!target) { + return; + } + console.debug(`Disposing target ${target.texture.id} for mask ${i}`); + target.dispose(); + this._maskTargets[i] = null; + }); + } + dispose(disposeTargets = true) { + console.debug("CharModel.dispose: ptr =", this.__ptr); + this._finalizeCharModel(); + if (this.meshes) { + this._facelineMesh = null; + this._maskMesh = null; + disposeMeshes(this.meshes); + this.meshes = null; + } + if (disposeTargets) { + this.disposeTargets(); + } + if (this._textureManager) { + this._textureManager.dispose(); + this._textureManager = null; + } + } + getStoreData() { + const charInfoData = this._getCharInfoUint8Array(); + const mod2 = this._module; + const charInfoPtr = mod2._malloc(FFLiCharInfo.size); + const storeDataPtr = mod2._malloc(FFLStoreData_size); + mod2.HEAPU8.set(charInfoData, charInfoPtr); + const result = mod2._FFLpGetStoreDataFromCharInfo(storeDataPtr, charInfoPtr); + const storeData = mod2.HEAPU8.slice(storeDataPtr, storeDataPtr + FFLStoreData_size); + mod2._free(charInfoPtr); + mod2._free(storeDataPtr); + if (!result) { + throw new Error("getStoreData: call to FFLpGetStoreDataFromCharInfo returned false, CharInfo verification probably failed"); + } + return storeData; + } + setExpression(expression) { + this._model.expression = expression; + const targ = this._maskTargets[expression]; + if (!targ || !targ.texture) { + throw new ExpressionNotSet(expression); + } + const mesh = this._maskMesh; + if (!mesh || !(mesh instanceof Mesh)) { + if (expression === FFLExpression.BLANK_61 || expression === FFLExpression.BLANK_62) { + return; + } + throw new Error("setExpression: mask mesh does not exist, cannot set expression on it"); + } + targ.texture._target = targ; + mesh.material.map = targ.texture; + mesh.material.needsUpdate = true; + } + getFaceline() { + if (this._facelineTarget) { + return this._facelineTarget; + } + return null; + } + getMask(expression = this.expression) { + if (this._maskTargets && this._maskTargets[expression]) { + return this._maskTargets[expression]; + } + return null; + } + get expression() { + return this._model.expression; + } + get charInfo() { + return this._model.charInfo; + } + get facelineColor() { + if (!this._facelineColor) { + this._facelineColor = this._getFacelineColor(); + } + return this._facelineColor; + } + get favoriteColor() { + if (!this._favoriteColor) { + this._favoriteColor = this._getFavoriteColor(); + } + return this._favoriteColor; + } + get gender() { + return this._model.charInfo.personal.gender; + } + get partsTransform() { + if (!this._partsTransform) { + this._partsTransform = this._getPartsTransform(); + } + return this._partsTransform; + } + get boundingBox() { + if (!this._boundingBox) { + this._boundingBox = this._getBoundingBox(); + } + return this._boundingBox; + } + static BodyScaleMode = { + Apply: 0, + Limit: 1 + }; + getBodyScale(scaleMode = CharModel.BodyScaleMode.Apply) { + const build = this._model.charInfo.body.build; + const height2 = this._model.charInfo.body.height; + const bodyScale = new Vector3; + switch (scaleMode) { + case CharModel.BodyScaleMode.Apply: { + bodyScale.x = build * (height2 * 0.003671875 + 0.4) / 128 + height2 * 0.001796875 + 0.4; + bodyScale.y = height2 * 0.006015625 + 0.5; + break; + } + case CharModel.BodyScaleMode.Limit: { + const heightFactor = height2 / 128; + bodyScale.y = heightFactor * 0.55 + 0.6; + bodyScale.x = heightFactor * 0.3 + 0.6; + bodyScale.x = (heightFactor * 0.6 + 0.8 - bodyScale.x) * (build / 128) + bodyScale.x; + break; + } + default: + throw new Error(`getBodyScale: Unexpected value for scaleMode: ${scaleMode}`); + } + bodyScale.z = bodyScale.x; + return bodyScale; + } +} +var PantsColor = { + GrayNormal: 0, + BluePresent: 1, + RedRegular: 2, + GoldSpecial: 3 +}; +var pantsColors = { + [PantsColor.GrayNormal]: new Color(4212558), + [PantsColor.BluePresent]: new Color(2637946), + [PantsColor.RedRegular]: new Color(7348245), + [PantsColor.GoldSpecial]: new Color(12623920) +}; +function _allocateModelSource(data2, module2) { + const bufferPtr = module2._malloc(FFLiCharInfo.size); + const modelSource = { + dataSource: FFLDataSource.DIRECT_POINTER, + pBuffer: bufferPtr, + index: 0 + }; + if (!(data2 instanceof Uint8Array)) { + try { + if (typeof data2 !== "object") { + throw new Error("_allocateModelSource: data passed in is not FFLiCharInfo object or Uint8Array"); + } + data2 = FFLiCharInfo.pack(data2); + } catch (e) { + module2._free(bufferPtr); + throw e; + } + } + function setStudioData(src) { + const studio = StudioCharInfo.unpack(src); + const charInfo = convertStudioCharInfoToFFLiCharInfo(studio); + data2 = FFLiCharInfo.pack(charInfo); + module2.HEAPU8.set(data2, bufferPtr); + } + function callGetCharInfoFunc(data3, size, funcName) { + const dataPtr = module2._malloc(size); + module2.HEAPU8.set(data3, dataPtr); + const result = module2[funcName](bufferPtr, dataPtr); + module2._free(dataPtr); + if (!result) { + module2._free(bufferPtr); + throw new Error(`_allocateModelSource: call to ${funcName} returned false, CharInfo verification probably failed`); + } + } + switch (data2.length) { + case FFLStoreData_size: { + callGetCharInfoFunc(data2, FFLStoreData_size, "_FFLpGetCharInfoFromStoreData"); + break; + } + case 74: + case 76: { + callGetCharInfoFunc(data2, 74, "_FFLpGetCharInfoFromMiiDataOfficialRFL"); + break; + } + case FFLiCharInfo.size: + module2.HEAPU8.set(data2, bufferPtr); + break; + case StudioCharInfo.size + 1: { + data2 = studioURLObfuscationDecode(data2); + setStudioData(data2); + break; + } + case StudioCharInfo.size: { + setStudioData(data2); + break; + } + default: { + module2._free(bufferPtr); + throw new Error(`_allocateModelSource: Unknown data length: ${data2.length}`); + } + } + return modelSource; +} +function verifyCharInfo(data2, module2, verifyName = false) { + let charInfoPtr = 0; + let charInfoAllocated = false; + if (typeof data2 === "number") { + charInfoPtr = data2; + charInfoAllocated = false; + } else { + charInfoAllocated = true; + charInfoPtr = module2._malloc(FFLiCharInfo.size); + module2.HEAPU8.set(data2, charInfoPtr); + } + const result = module2._FFLiVerifyCharInfoWithReason(charInfoPtr, verifyName); + if (charInfoAllocated) { + module2._free(charInfoPtr); + } + if (result !== 0) { + throw new FFLiVerifyReasonException(result); + } +} +function makeExpressionFlag(expressions) { + function checkRange(i) { + if (i >= FFLExpression.MAX) { + throw new Error(`makeExpressionFlag: input out of range: got ${i}, max: ${FFLExpression.MAX}`); + } + } + function warnIfChangesShapes(i) { + const expressionsDisablingNose = [49, 50, 51, 52, 61, 62]; + const expressionsDisablingMask = [61, 62]; + const prefix = `makeExpressionFlag > warnIfChangesShapes: An expression was enabled (${i}) that is meant to disable nose or mask shape for the entire CharModel, so it is only recommended to set this as a single expression rather than as one of multiple.`; + if (expressionsDisablingNose.indexOf(i) !== -1) { + console.warn(`${prefix} (nose shape)`); + } + if (expressionsDisablingMask.indexOf(i) !== -1) { + console.warn(`${prefix} (in this case, MASK SHAPE so there is supposed to be NO FACE)`); + } + } + const flags = new Uint32Array([0, 0, 0]); + if (typeof expressions === "number") { + expressions = [expressions]; + } else if (!Array.isArray(expressions)) { + throw new Error("makeExpressionFlag: expected array or single number"); + } + for (const index2 of expressions) { + checkRange(index2); + warnIfChangesShapes(index2); + const part = Math.floor(index2 / 32); + const bitIndex = index2 % 32; + flags[part] |= 1 << bitIndex; + } + return flags; +} +function createCharModel(data2, modelDesc, materialClass, module2, verify = true) { + modelDesc = modelDesc || FFLCharModelDescDefault; + if (!module2 || !module2._malloc) { + throw new Error("createCharModel: module is null or does not have ._malloc."); + } + if (!data2) { + throw new Error("createCharModel: data is null or undefined."); + } + if (typeof modelDesc !== "object" || modelDesc.allExpressionFlag === undefined) { + throw new Error("createCharModel: modelDesc argument is invalid, make sure it is FFLCharModelDesc."); + } + const modelSourcePtr = module2._malloc(FFLCharModelSource.size); + const modelDescPtr = module2._malloc(FFLCharModelDesc.size); + const charModelPtr = module2._malloc(FFLiCharModel.size); + const modelSource = _allocateModelSource(data2, module2); + const charInfoPtr = modelSource.pBuffer; + const modelSourceBuffer = FFLCharModelSource.pack(modelSource); + module2.HEAPU8.set(modelSourceBuffer, modelSourcePtr); + modelDesc.modelFlag |= FFLModelFlag.NEW_EXPRESSIONS; + const modelDescBuffer = FFLCharModelDesc.pack(modelDesc); + module2.HEAPU8.set(modelDescBuffer, modelDescPtr); + let textureManager = null; + try { + if (verify) { + verifyCharInfo(charInfoPtr, module2, false); + } + textureManager = new TextureManager(module2, false); + const result = module2._FFLInitCharModelCPUStepWithCallback(charModelPtr, modelSourcePtr, modelDescPtr, textureManager._textureCallbackPtr); + if (result === FFLResult.FILE_INVALID) { + throw new BrokenInitModel; + } + FFLResultException.handleResult(result, "FFLInitCharModelCPUStep"); + } catch (error) { + if (textureManager) { + textureManager.dispose(); + } + module2._free(charModelPtr); + throw error; + } finally { + module2._free(modelSourcePtr); + module2._free(modelDescPtr); + module2._free(charInfoPtr); + if (textureManager) { + textureManager.disposeCallback(); + } + } + const charModel = new CharModel(charModelPtr, module2, materialClass, textureManager); + charModel._data = data2; + console.debug(`createCharModel: Initialized for "${charModel._model.charInfo.personal.name}", ptr =`, charModelPtr); + return charModel; +} +function matSupportsFFL(material) { + return "modulateMode" in material.prototype; +} +function drawParamToMesh(drawParam, materialClass, module2, texManager) { + if (!drawParam) { + throw new Error("drawParamToMesh: drawParam may be null."); + } + if (!texManager) { + throw new Error("drawParamToMesh: Passed in TextureManager is null or undefined, is it constructed?"); + } + if (typeof materialClass !== "function") { + throw new Error("drawParamToMesh: materialClass is unexpectedly not a function."); + } + if (drawParam.primitiveParam.indexCount === 0) { + return null; + } + const geometry = _bindDrawParamGeometry(drawParam, module2); + const cullModeToThreeSide = { + [FFLCullMode.NONE]: DoubleSide, + [FFLCullMode.BACK]: FrontSide, + [FFLCullMode.FRONT]: BackSide, + [FFLCullMode.MAX]: DoubleSide + }; + const side = cullModeToThreeSide[drawParam.cullMode]; + if (side === undefined) { + throw new Error(`drawParamToMesh: Unexpected value for FFLCullMode: ${drawParam.cullMode}`); + } + const texture = _getTextureFromModulateParam(drawParam.modulateParam, texManager); + const isFFLMaterial = matSupportsFFL(materialClass); + const params = _applyModulateParam(drawParam.modulateParam, module2, isFFLMaterial); + const materialParam = { + side, + map: texture, + ...params + }; + if (geometry.attributes.tangent === undefined && "useSpecularModeBlinn" in materialClass.prototype) { + materialParam.useSpecularModeBlinn = true; + } + const material = new materialClass(materialParam); + const mesh = new Mesh(geometry, material); + if (drawParam.primitiveParam.pAdjustMatrix !== 0) { + _applyAdjustMatrixToMesh(drawParam.primitiveParam.pAdjustMatrix, mesh, module2.HEAPF32); + } + if (mesh.geometry.userData) { + mesh.geometry.userData.modulateMode = drawParam.modulateParam.mode; + mesh.geometry.userData.modulateType = drawParam.modulateParam.type; + mesh.geometry.userData.color = params.color instanceof Color ? [params.color.r, params.color.g, params.color.b, 1] : [1, 1, 1, 1]; + mesh.geometry.userData.cullMode = drawParam.cullMode; + } + return mesh; +} +function _bindDrawParamGeometry(drawParam, module2) { + function unexpectedStride(typeStr, stride) { + throw new Error(`_bindDrawParamGeometry: Unexpected stride for attribute ${typeStr}: ${stride}`); + } + const attributes = drawParam.attributeBufferParam.attributeBuffers; + const positionBuffer = attributes[FFLAttributeBufferType.POSITION]; + if (positionBuffer.size === 0) { + throw new Error("_bindDrawParamGeometry: Position buffer must not have size of 0"); + } + const vertexCount = positionBuffer.size / positionBuffer.stride; + const geometry = new BufferGeometry; + const indexPtr = drawParam.primitiveParam.pIndexBuffer / 2; + const indexCount = drawParam.primitiveParam.indexCount; + const indices = module2.HEAPU16.subarray(indexPtr, indexPtr + indexCount); + geometry.setIndex(new Uint16BufferAttribute(indices, 1)); + for (const typeStr in attributes) { + const buffer = attributes[typeStr]; + const type = parseInt(typeStr); + if (buffer.size === 0) { + continue; + } + switch (type) { + case FFLAttributeBufferType.POSITION: { + if (buffer.stride === 16) { + const ptr = buffer.ptr / 4; + const data2 = module2.HEAPF32.subarray(ptr, ptr + vertexCount * 4); + const interleavedBuffer = new InterleavedBuffer(data2, 4); + geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0)); + } else if (buffer.stride === 6) { + const ptr = buffer.ptr / 2; + const data2 = module2.HEAPU16.subarray(ptr, ptr + vertexCount * 3); + geometry.setAttribute("position", new Float16BufferAttribute(data2, 3)); + } else { + unexpectedStride(typeStr, buffer.stride); + } + break; + } + case FFLAttributeBufferType.NORMAL: { + const data2 = module2.HEAP8.subarray(buffer.ptr, buffer.ptr + buffer.size); + geometry.setAttribute("normal", new Int8BufferAttribute(data2, buffer.stride, true)); + break; + } + case FFLAttributeBufferType.TANGENT: { + const data2 = module2.HEAP8.subarray(buffer.ptr, buffer.ptr + buffer.size); + geometry.setAttribute("tangent", new Int8BufferAttribute(data2, buffer.stride, true)); + break; + } + case FFLAttributeBufferType.TEXCOORD: { + if (buffer.stride === 8) { + const ptr = buffer.ptr / 4; + const data2 = module2.HEAPF32.subarray(ptr, ptr + vertexCount * 2); + geometry.setAttribute("uv", new Float32BufferAttribute(data2, 2)); + } else if (buffer.stride === 4) { + const ptr = buffer.ptr / 2; + const data2 = module2.HEAPU16.subarray(ptr, ptr + vertexCount * 2); + geometry.setAttribute("uv", new Float16BufferAttribute(data2, 2)); + } else { + unexpectedStride(typeStr, buffer.stride); + } + break; + } + case FFLAttributeBufferType.COLOR: { + if (buffer.stride === 0) { + break; + } + const data2 = module2.HEAPU8.subarray(buffer.ptr, buffer.ptr + buffer.size); + geometry.setAttribute("_color", new Uint8BufferAttribute(data2, buffer.stride, true)); + break; + } + } + } + return geometry; +} +function _getTextureFromModulateParam(modulateParam, textureManager) { + if (!modulateParam.pTexture2D || modulateParam.pTexture2D === 1) { + return null; + } + const texturePtr = modulateParam.pTexture2D; + const texture = textureManager.get(texturePtr); + if (!texture) { + throw new Error(`_getTextureFromModulateParam: Texture not found for ${texturePtr}.`); + } + const applyMirrorTypes = [ + FFLModulateType.SHAPE_FACELINE, + FFLModulateType.SHAPE_CAP, + FFLModulateType.SHAPE_GLASS + ]; + if (applyMirrorTypes.indexOf(modulateParam.type) !== -1) { + texture.wrapS = MirroredRepeatWrapping; + texture.wrapT = MirroredRepeatWrapping; + texture.needsUpdate = true; + } + return texture; +} +function _getBlendOptionsFromModulateType(modulateType, modulateMode) { + if (modulateMode !== 0 && modulateType >= FFLModulateType.SHAPE_MAX && modulateType <= FFLModulateType.MOLE) { + return { + blending: CustomBlending, + blendSrc: OneMinusDstAlphaFactor, + blendSrcAlpha: SrcAlphaFactor, + blendDst: DstAlphaFactor + }; + } else if (modulateMode !== 0 && modulateType >= FFLModulateType.FACE_MAKE && modulateType <= FFLModulateType.FILL) { + return { + blending: CustomBlending, + blendSrc: SrcAlphaFactor, + blendDst: OneMinusSrcAlphaFactor, + blendSrcAlpha: OneFactor, + blendDstAlpha: OneFactor + }; + } + return {}; +} +function _applyModulateParam(modulateParam, module2, forFFLMaterial = true) { + let color = null; + let color4 = null; + const f32 = module2.HEAPF32; + if (modulateParam.pColorG !== 0 && modulateParam.pColorB !== 0) { + color = [ + _getFFLColor3(_getFFLColor(modulateParam.pColorR, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorG, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorB, f32)) + ]; + if (self.eyeScleraHack && modulateParam.type === 12) { + color = [ + _getFFLColor3(_getFFLColor(modulateParam.pColorR, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorB, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorB, f32)) + ]; + } + } else if (modulateParam.pColorR !== 0) { + color4 = _getFFLColor(modulateParam.pColorR, f32); + color = _getFFLColor3(color4); + } + const opacity = color4 ? color4.a : 1; + const transparent = modulateParam.type >= FFLModulateType.SHAPE_MASK; + const lightEnable = !(modulateParam.type >= FFLModulateType.SHAPE_MAX && modulateParam.mode !== FFLModulateMode.CONSTANT); + const modulateModeType = forFFLMaterial ? { + modulateMode: modulateParam.mode, + modulateType: modulateParam.type + } : {}; + const param = Object.assign(modulateModeType, { + color, + opacity, + transparent, + depthWrite: !transparent, + ..._getBlendOptionsFromModulateType(modulateParam.type, modulateParam.mode) + }); + if (!lightEnable) { + param.lightEnable = lightEnable; + } + return param; +} +function _getFFLColor(colorPtr, heapf32) { + if (!colorPtr) { + throw new Error("_getFFLColor: Received null pointer"); + } + const colorData = heapf32.subarray(colorPtr / 4, colorPtr / 4 + 4); + return { r: colorData[0], g: colorData[1], b: colorData[2], a: colorData[3] }; +} +function _getFFLColor3(color) { + return new Color(color.r, color.g, color.b); +} +function _applyAdjustMatrixToMesh(pMtx, mesh, heapf32) { + const ptr = pMtx / 4; + const m = heapf32.slice(ptr, ptr + 48 / 4); + function matrixFromRowMajor3x4(m2) { + const matrix2 = new Matrix4; + matrix2.set(m2[0], m2[4], m2[8], m2[3], m2[1], m2[5], m2[9], m2[7], m2[2], m2[6], m2[10], m2[11], 0, 0, 0, 1); + return matrix2; + } + const matrix = matrixFromRowMajor3x4(m); + mesh.scale.setFromMatrixScale(matrix); + mesh.position.setFromMatrixPosition(matrix); + if (matrix.elements[0] === -1) { + mesh.scale.x = -1; + } +} +function initCharModelTextures(charModel, renderer2, materialClass = charModel._materialClass) { + if (!(renderer2 instanceof WebGLRenderer) && renderer2["isWebGPURenderer"] === undefined) { + throw new Error("initCharModelTextures: renderer is an invalid or unexpected type."); + } + const module2 = charModel._module; + charModel._materialTextureClass = materialClass; + const textureTempObject = charModel._getTextureTempObject(); + _drawFacelineTexture(charModel, textureTempObject, renderer2, module2, materialClass); + const clearAlpha = renderer2.getClearAlpha(); + clearAlpha !== 0 && renderer2.setClearAlpha(0); + _drawMaskTextures(charModel, textureTempObject, renderer2, module2, materialClass); + charModel._finalizeCharModel(); + charModel.setExpression(charModel.expression); + clearAlpha !== 0 && renderer2.setClearAlpha(clearAlpha); + if (!matSupportsFFL(charModel._materialClass)) { + if (!matSupportsFFL(charModel._materialTextureClass)) { + console.warn("initCharModelTextures: charModel._materialClass does not support modulateMode (no getter), but the _materialTextureClass is either the same or also does not support modulateMode so textures will look wrong"); + } else { + convertModelTexturesToRGBA(charModel, renderer2, charModel._materialTextureClass); + } + } +} +function _drawFacelineTexture(charModel, textureTempObject, renderer2, module2, materialClass) { + const facelineTempObjectPtr = charModel._getFacelineTempObjectPtr(); + module2._FFLiInvalidateTempObjectFacelineTexture(facelineTempObjectPtr); + const drawParams = [ + textureTempObject.facelineTexture.drawParamFaceMake, + textureTempObject.facelineTexture.drawParamFaceLine, + textureTempObject.facelineTexture.drawParamFaceBeard + ].filter((dp) => dp && dp.modulateParam.pTexture2D !== 0); + if (drawParams.length === 0) { + console.debug("_drawFacelineTexture: Skipping faceline texture."); + return; + } + const bgColor = charModel.facelineColor; + const { scene: offscreenScene } = createSceneFromDrawParams(drawParams, bgColor, materialClass, charModel._module, charModel._textureManager); + const width2 = charModel._getResolution() / 2; + const height2 = charModel._getResolution(); + const options = { + depthBuffer: false, + stencilBuffer: false, + wrapS: MirroredRepeatWrapping, + wrapT: MirroredRepeatWrapping + }; + const target = createAndRenderToTarget(offscreenScene, getIdentCamera(), renderer2, width2, height2, options); + console.debug(`Creating target ${target.texture.id} for faceline`); + _setFaceline(charModel, target); + module2._FFLiDeleteTempObjectFacelineTexture(facelineTempObjectPtr, charModel._ptr, charModel._model.charModelDesc.resourceType); + disposeMeshes(offscreenScene); +} +function _drawMaskTextures(charModel, textureTempObject, renderer2, module2, materialClass) { + const maskTempObjectPtr = charModel._getMaskTempObjectPtr(); + const expressionFlagPtr = charModel._getExpressionFlagPtr(); + const scenes = []; + for (let i = 0;i < charModel._model.maskTextures.pRenderTextures.length; i++) { + if (charModel._model.maskTextures.pRenderTextures[i] === 0) { + continue; + } + const rawMaskDrawParamPtr = textureTempObject.maskTextures.pRawMaskDrawParam[i]; + const rawMaskDrawParam = FFLiRawMaskDrawParam.unpack(module2.HEAPU8.subarray(rawMaskDrawParamPtr, rawMaskDrawParamPtr + FFLiRawMaskDrawParam.size)); + module2._FFLiInvalidateRawMask(rawMaskDrawParamPtr); + const { target, scene } = _drawMaskTexture(charModel, rawMaskDrawParam, renderer2, module2, materialClass); + console.debug(`Creating target ${target.texture.id} for mask ${i}`); + charModel._maskTargets[i] = target; + scenes.push(scene); + } + scenes.forEach((scene) => { + disposeMeshes(scene); + }); + module2._FFLiDeleteTempObjectMaskTextures(maskTempObjectPtr, expressionFlagPtr, charModel._model.charModelDesc.resourceType); + module2._FFLiDeleteTextureTempObject(charModel._ptr); +} +function _drawMaskTexture(charModel, rawMaskParam, renderer2, module2, materialClass) { + const drawParams = [ + rawMaskParam.drawParamRawMaskPartsMustache[0], + rawMaskParam.drawParamRawMaskPartsMustache[1], + rawMaskParam.drawParamRawMaskPartsMouth, + rawMaskParam.drawParamRawMaskPartsEyebrow[0], + rawMaskParam.drawParamRawMaskPartsEyebrow[1], + rawMaskParam.drawParamRawMaskPartsEye[0], + rawMaskParam.drawParamRawMaskPartsEye[1], + rawMaskParam.drawParamRawMaskPartsMole + ].filter((dp) => dp && dp.primitiveParam.indexCount !== 0); + if (drawParams.length === 0) { + throw new Error("_drawMaskTexture: All DrawParams are empty."); + } + const options = { + depthBuffer: false, + stencilBuffer: false + }; + const { scene: offscreenScene } = createSceneFromDrawParams(drawParams, null, materialClass, module2, charModel._textureManager); + const width2 = charModel._getResolution(); + const target = createAndRenderToTarget(offscreenScene, getIdentCamera(), renderer2, width2, width2, options); + return { target, scene: offscreenScene }; +} +function _setFaceline(charModel, target) { + if (!target || !target.texture) { + throw new Error("setFaceline: passed in RenderTarget is invalid"); + } + charModel._facelineTarget = target; + const mesh = charModel._facelineMesh; + if (!mesh || !(mesh instanceof Mesh)) { + throw new Error("setFaceline: faceline shape does not exist"); + } + target.texture._target = target; + mesh.material.map = target.texture; + mesh.material.needsUpdate = true; +} +function _texDrawRGBATarget(renderer2, material, userData, materialTextureClass) { + const plane = new PlaneGeometry(2, 2); + const scene = new Scene; + const bgClearRGBMesh = new Mesh(plane, new MeshBasicMaterial({ + color: material.color, + transparent: true, + opacity: 0, + blending: NoBlending + })); + scene.add(bgClearRGBMesh); + if (!material.map) { + throw new Error("_texDrawRGBATarget: material.map is null or undefined"); + } + const tex = material.map; + const texMat = new materialTextureClass({ + map: tex, + modulateMode: userData.modulateMode, + color: material.color, + lightEnable: false + }); + texMat.blending = NoBlending; + texMat.transparent = true; + const textureMesh = new Mesh(plane, texMat); + scene.add(textureMesh); + const target = createAndRenderToTarget(scene, getIdentCamera(false), renderer2, tex.image.width, tex.image.height, { + wrapS: tex.wrapS, + wrapT: tex.wrapT, + depthBuffer: false, + stencilBuffer: false + }); + target.texture._target = target; + material.map.dispose(); + material.map = target.texture; + material.color = new Color(1, 1, 1); + userData.modulateMode = 1; + return target; +} +function convertModelTexturesToRGBA(charModel, renderer2, materialTextureClass) { + const convertTextureForTypes = [ + FFLModulateType.SHAPE_CAP, + FFLModulateType.SHAPE_NOSELINE, + FFLModulateType.SHAPE_GLASS + ]; + if (!charModel.meshes) { + throw new Error("convertModelTexturesToRGBA: charModel.meshes is null."); + } + charModel.meshes.traverse((mesh) => { + if (!(mesh instanceof Mesh) || !mesh.geometry.userData.modulateType || !mesh.material.map || convertTextureForTypes.indexOf(mesh.geometry.userData.modulateType) === -1) { + return; + } + const target = _texDrawRGBATarget(renderer2, mesh.material, mesh.geometry.userData, materialTextureClass); + charModel._maskTargets.push(target); + }); +} +function createSceneFromDrawParams(drawParams, bgColor, ...drawParamArgs) { + const scene = new Scene; + scene.background = bgColor || null; + const meshes = []; + drawParams.forEach((param) => { + const mesh = drawParamToMesh(param, ...drawParamArgs); + if (mesh) { + scene.add(mesh); + meshes.push(mesh); + } + }); + return { scene, meshes }; +} +function getIdentCamera(flipY = false) { + const camera = new OrthographicCamera(-1, 1, flipY ? -1 : 1, flipY ? 1 : -1, 0.1, 10); + camera.position.z = 1; + return camera; +} +function createAndRenderToTarget(scene, camera, renderer2, width2, height2, targetOptions = {}) { + const options = { + minFilter: LinearFilter, + magFilter: LinearFilter, + ...targetOptions + }; + const renderTarget = renderer2["isWebGPURenderer"] === undefined ? new WebGLRenderTarget(width2, height2, options) : new RenderTarget(width2, height2, options); + const prevTarget = renderer2.getRenderTarget(); + renderer2.setRenderTarget(renderTarget); + renderer2.render(scene, camera); + renderer2.setRenderTarget(prevTarget); + return renderTarget; +} +function disposeMeshes(group, scene) { + function disposeMaterial(material) { + if (material.map) { + material.map.dispose(); + } + material.dispose(); + } + group.traverse((child) => { + if (!(child instanceof Mesh)) { + return; + } + if (child.geometry) { + child.geometry.dispose(); + } + if (child.material) { + Array.isArray(child.material) ? child.material.forEach((material) => { + disposeMaterial(material); + }) : disposeMaterial(child.material); + } + }); + if (scene && scene instanceof Scene) { + scene.remove(group); + } + group.children = []; +} +var ViewType = { + Face: 0, + MakeIcon: 1, + IconFovy45: 2 +}; +var StudioCharInfo = _.struct([ + _.uint8("beardColor"), + _.uint8("beardType"), + _.uint8("build"), + _.uint8("eyeAspect"), + _.uint8("eyeColor"), + _.uint8("eyeRotate"), + _.uint8("eyeScale"), + _.uint8("eyeType"), + _.uint8("eyeX"), + _.uint8("eyeY"), + _.uint8("eyebrowAspect"), + _.uint8("eyebrowColor"), + _.uint8("eyebrowRotate"), + _.uint8("eyebrowScale"), + _.uint8("eyebrowType"), + _.uint8("eyebrowX"), + _.uint8("eyebrowY"), + _.uint8("facelineColor"), + _.uint8("facelineMake"), + _.uint8("facelineType"), + _.uint8("facelineWrinkle"), + _.uint8("favoriteColor"), + _.uint8("gender"), + _.uint8("glassColor"), + _.uint8("glassScale"), + _.uint8("glassType"), + _.uint8("glassY"), + _.uint8("hairColor"), + _.uint8("hairFlip"), + _.uint8("hairType"), + _.uint8("height"), + _.uint8("moleScale"), + _.uint8("moleType"), + _.uint8("moleX"), + _.uint8("moleY"), + _.uint8("mouthAspect"), + _.uint8("mouthColor"), + _.uint8("mouthScale"), + _.uint8("mouthType"), + _.uint8("mouthY"), + _.uint8("mustacheScale"), + _.uint8("mustacheType"), + _.uint8("mustacheY"), + _.uint8("noseScale"), + _.uint8("noseType"), + _.uint8("noseY") +]); +function convertStudioCharInfoToFFLiCharInfo(src) { + return { + miiVersion: 0, + faceline: { + type: src.facelineType, + color: src.facelineColor, + texture: src.facelineWrinkle, + make: src.facelineMake + }, + hair: { + type: src.hairType, + color: commonColorMask(src.hairColor), + flip: src.hairFlip + }, + eye: { + type: src.eyeType, + color: commonColorMask(src.eyeColor), + scale: src.eyeScale, + aspect: src.eyeAspect, + rotate: src.eyeRotate, + x: src.eyeX, + y: src.eyeY + }, + eyebrow: { + type: src.eyebrowType, + color: commonColorMask(src.eyebrowColor), + scale: src.eyebrowScale, + aspect: src.eyebrowAspect, + rotate: src.eyebrowRotate, + x: src.eyebrowX, + y: src.eyebrowY + }, + nose: { + type: src.noseType, + scale: src.noseScale, + y: src.noseY + }, + mouth: { + type: src.mouthType, + color: commonColorMask(src.mouthColor), + scale: src.mouthScale, + aspect: src.mouthAspect, + y: src.mouthY + }, + beard: { + mustache: src.mustacheType, + type: src.beardType, + color: commonColorMask(src.beardColor), + scale: src.mustacheScale, + y: src.mustacheY + }, + glass: { + type: src.glassType, + color: commonColorMask(src.glassColor), + scale: src.glassScale, + y: src.glassY + }, + mole: { + type: src.moleType, + scale: src.moleScale, + x: src.moleX, + y: src.moleY + }, + body: { + height: src.height, + build: src.build + }, + personal: { + name: "", + creator: "", + gender: src.gender, + birthMonth: 0, + birthDay: 0, + favoriteColor: src.favoriteColor, + favorite: 0, + copyable: 0, + ngWord: 0, + localonly: 0, + regionMove: 0, + fontRegion: 0, + roomIndex: 0, + positionInRoom: 0, + birthPlatform: 3 + }, + createID: { + data: new Array(10).fill(0) + }, + padding_0: 0, + authorType: 0, + authorID: new Array(8).fill(0) + }; +} +function studioURLObfuscationDecode(data2) { + const decodedData = new Uint8Array(data2); + const random2 = decodedData[0]; + let previous = random2; + for (let i = 1;i < 48; i++) { + const encodedByte = decodedData[i]; + const original = (encodedByte - 7 + 256) % 256; + decodedData[i - 1] = original ^ previous; + previous = encodedByte; + } + return decodedData.slice(0, StudioCharInfo.size); +} +function stripSpaces(str) { + return str.replace(/\s+/g, ""); +} +function hexToUint8Array(hex) { + const match = hex.match(/.{1,2}/g); + const arr = (match ? match : []).map(function(byte) { + return parseInt(byte, 16); + }); + return new Uint8Array(arr); +} +function base64ToUint8Array(base64) { + const normalizedBase64 = base64.replace(/-/g, "+").replace(/_/g, "/"); + function padBase64(str) { + while (str.length % 4 !== 0) { + str += "="; + } + return str; + } + const paddedBase64 = padBase64(normalizedBase64); + const binaryString = atob(paddedBase64); + const len = binaryString.length; + const bytes = new Uint8Array(len); + for (let i = 0;i < len; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function parseHexOrB64ToUint8Array(text2) { + let inputData; + const textData = stripSpaces(text2); + if (/^[0-9a-fA-F]+$/.test(textData)) { + inputData = hexToUint8Array(textData); + } else { + inputData = base64ToUint8Array(textData); + } + return inputData; +} + +// src/util/allocateArray.ts +function allocateArray(size, data2) { + if (data2.length > size) + throw new RangeError(`Tried to fill ${data2.length} bytes into a ${size}-byte array`); + let array = new Uint8Array(size); + for (var i = 0;i < data2.length; i++) { + array[i] = data2[i]; + } + return array; +} + +// src/util/dataConvert.ts +function dataToBase64(data2) { + return btoa(String.fromCharCode.apply(null, data2)); +} +function dataToHex(data2) { + return Array.from(data2, (i) => i.toString(16).padStart(2, "0")).join(""); +} +function encodeUTF16LE(str) { + const buffer = new ArrayBuffer(str.length * 2); + const view = new DataView(buffer); + for (let i = 0;i < str.length; i++) { + view.setUint16(i * 2, str.charCodeAt(i), true); + } + return new Uint8Array(buffer); +} +function decodeUTF16LE(bytes) { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let result = ""; + for (let i = 0;i < view.byteLength; i += 2) { + result += String.fromCharCode(view.getUint16(i, true)); + } + return result; +} + +// src/util/Numbers.ts +var ArrayNum = (number) => Array.from(Array(number).keys()); +var RandomInt = (max) => Math.floor(Math.random() * max); +function randomizeUint8Array(arr) { + if (!(arr instanceof Uint8Array)) { + throw new TypeError("Expected a Uint8Array"); + } + function randomize() { + for (let i = 0;i < arr.length; i++) { + arr[i] = Math.floor(Math.random() * 256); + } + } + if (typeof window !== "undefined") { + if (window.crypto && window.crypto.getRandomValues) { + window.crypto.getRandomValues(arr); + } else + randomize(); + } else { + randomize(); + } + return arr; +} + +// src/class/struct/FFLStoreData.ts +var import_struct_fu = __toESM(require_struct_fu(), 1); +var FFLiCreateID = import_struct_fu.default.struct([ + import_struct_fu.default.ubit("flag_normal", 1), + import_struct_fu.default.ubit("flag_1", 1), + import_struct_fu.default.ubit("flag_temporary", 1), + import_struct_fu.default.ubit("flag_3", 1), + import_struct_fu.default.ubit("create_date1", 14), + import_struct_fu.default.ubit("create_date2", 14), + import_struct_fu.default.byte("base", 6) +]); +var FFLiAuthorID = import_struct_fu.default.struct([import_struct_fu.default.byte("data", 8)]); +var Ver3StoreData = import_struct_fu.default.struct([ + import_struct_fu.default.ubitLE("mii_version", 8), + import_struct_fu.default.ubitLE("copyable", 1), + import_struct_fu.default.ubitLE("ng_word", 1), + import_struct_fu.default.ubitLE("region_move", 2), + import_struct_fu.default.ubitLE("font_region", 2), + import_struct_fu.default.ubitLE("reserved_0", 2), + import_struct_fu.default.ubitLE("room_index", 4), + import_struct_fu.default.ubitLE("position_in_room", 4), + import_struct_fu.default.ubitLE("author_type", 4), + import_struct_fu.default.ubitLE("birth_platform", 3), + import_struct_fu.default.ubitLE("reserved_1"), + import_struct_fu.default.struct("author_id", [FFLiAuthorID]), + import_struct_fu.default.struct("create_id", [FFLiCreateID]), + import_struct_fu.default.byte("reserved_2", 2), + import_struct_fu.default.ubitLE("gender", 1), + import_struct_fu.default.ubitLE("birth_month", 4), + import_struct_fu.default.ubitLE("birth_day", 5), + import_struct_fu.default.ubitLE("favorite_color", 4), + import_struct_fu.default.ubitLE("favorite", 1), + import_struct_fu.default.ubitLE("padding_0", 1), + import_struct_fu.default.char16le("name", 20), + import_struct_fu.default.uint8("height"), + import_struct_fu.default.uint8("build"), + import_struct_fu.default.ubitLE("localonly", 1), + import_struct_fu.default.ubitLE("face_type", 4), + import_struct_fu.default.ubitLE("face_color", 3), + import_struct_fu.default.ubitLE("face_tex", 4), + import_struct_fu.default.ubitLE("face_make", 4), + import_struct_fu.default.ubitLE("hair_type", 8), + import_struct_fu.default.ubitLE("hair_color", 3), + import_struct_fu.default.ubitLE("hair_flip", 1), + import_struct_fu.default.ubitLE("padding_1", 4), + import_struct_fu.default.ubitLE("eye_type", 6), + import_struct_fu.default.ubitLE("eye_color", 3), + import_struct_fu.default.ubitLE("eye_scale", 4), + import_struct_fu.default.ubitLE("eye_aspect", 3), + import_struct_fu.default.ubitLE("eye_rotate", 5), + import_struct_fu.default.ubitLE("eye_x", 4), + import_struct_fu.default.ubitLE("eye_y", 5), + import_struct_fu.default.ubitLE("padding_2", 2), + import_struct_fu.default.ubitLE("eyebrow_type", 5), + import_struct_fu.default.ubitLE("eyebrow_color", 3), + import_struct_fu.default.ubitLE("eyebrow_scale", 4), + import_struct_fu.default.ubitLE("eyebrow_aspect", 3), + import_struct_fu.default.ubitLE("padding_3", 1), + import_struct_fu.default.ubitLE("eyebrow_rotate", 5), + import_struct_fu.default.ubitLE("eyebrow_x", 4), + import_struct_fu.default.ubitLE("eyebrow_y", 5), + import_struct_fu.default.ubitLE("padding_4", 2), + import_struct_fu.default.ubitLE("nose_type", 5), + import_struct_fu.default.ubitLE("nose_scale", 4), + import_struct_fu.default.ubitLE("nose_y", 5), + import_struct_fu.default.ubitLE("padding_5", 2), + import_struct_fu.default.ubitLE("mouth_type", 6), + import_struct_fu.default.ubitLE("mouth_color", 3), + import_struct_fu.default.ubitLE("mouth_scale", 4), + import_struct_fu.default.ubitLE("mouth_aspect", 3), + import_struct_fu.default.ubitLE("mouth_y", 5), + import_struct_fu.default.ubitLE("mustache_type", 3), + import_struct_fu.default.ubitLE("padding_6", 8), + import_struct_fu.default.ubitLE("beard_type", 3), + import_struct_fu.default.ubitLE("beard_color", 3), + import_struct_fu.default.ubitLE("beard_scale", 4), + import_struct_fu.default.ubitLE("beard_y", 5), + import_struct_fu.default.ubitLE("padding_7", 1), + import_struct_fu.default.ubitLE("glasses_type", 4), + import_struct_fu.default.ubitLE("glasses_color", 3), + import_struct_fu.default.ubitLE("glasses_scale", 4), + import_struct_fu.default.ubitLE("glass_y", 5), + import_struct_fu.default.ubitLE("mole_type", 1), + import_struct_fu.default.ubitLE("mole_scale", 4), + import_struct_fu.default.ubitLE("mole_x", 5), + import_struct_fu.default.ubitLE("mole_y", 5), + import_struct_fu.default.ubitLE("padding_8", 1), + import_struct_fu.default.char16le("creator", 20), + import_struct_fu.default.uint16le("padding_9"), + import_struct_fu.default.uint16("checksum") +]); +function calculateCRC16(storeData) { + const data2 = storeData.subarray(0, 94); + console.log(data2); + let crc = 0; + for (const byte of data2) { + for (let bit = 7;bit >= 0; bit--) { + const flag = (crc & 32768) != 0; + crc = (crc << 1 | byte >> bit & 1) ^ (flag ? 4129 : 0); + } + } + for (let i = 16;i > 0; i--) { + const flag = (crc & 32768) != 0; + crc = crc << 1 ^ (flag ? 4129 : 0); + } + return crc & 65535; +} + +// src/class/struct/MiiCreatorV3Data.ts +var import_struct_fu4 = __toESM(require_struct_fu(), 1); + +// src/class/struct/MiiCreatorV4Data.ts +var import_struct_fu3 = __toESM(require_struct_fu(), 1); + +// src/class/struct/RFLStoreData.ts +var import_struct_fu2 = __toESM(require_struct_fu(), 1); + +// src/constants/ColorTables.ts +var MiiFavoriteColorLookupTable = { + 0: 13770260, + 1: 16739865, + 2: 16767008, + 3: 7918112, + 4: 30768, + 5: 673980, + 6: 3975902, + 7: 16079485, + 8: 7547053, + 9: 4732952, + 10: 14737632, + 11: 1579028 +}; +var MiiFavoriteColorVec3Table = { + 0: [0.8235294117647058, 0.11764705882352941, 0.0784313725490196], + 1: [1, 0.43137254901960786, 0.09803921568627451], + 2: [1, 0.8470588235294118, 0.12549019607843137], + 3: [0.47058823529411764, 0.8235294117647058, 0.12549019607843137], + 4: [0, 0.47058823529411764, 0.18823529411764706], + 5: [0.0392156862745098, 0.2823529411764706, 0.7372549019607844], + 6: [0.23529411764705882, 0.6666666666666666, 0.8705882352941177], + 7: [0.9607843137254902, 0.35294117647058826, 0.49019607843137253], + 8: [0.45098039215686275, 0.1568627450980392, 0.6784313725490196], + 9: [0.2823529411764706, 0.2196078431372549, 0.09411764705882353], + 10: [0.8784313725490196, 0.8784313725490196, 0.8784313725490196], + 11: [0.09411764705882353, 0.09411764705882353, 0.0784313725490196] +}; +var MiiFavoriteColorIconTable = { + 0: { top: "#d21e14", bottom: "#630e09" }, + 1: { top: "#ff6e19", bottom: "#78340c" }, + 2: { top: "#ffd820", bottom: "#78660f" }, + 3: { top: "#78d220", bottom: "#38630f" }, + 4: { top: "#007830", bottom: "#003817" }, + 5: { top: "#0a48bc", bottom: "#052258" }, + 6: { top: "#3caade", bottom: "#1c5068" }, + 7: { top: "#f55a7d", bottom: "#732a3b" }, + 8: { top: "#7328ad", bottom: "#361351" }, + 9: { top: "#483818", bottom: "#221a0b" }, + 10: { top: "#e0e0e0", bottom: "#696969" }, + 11: { top: "#181814", bottom: "#0b0b09" } +}; +var MiiSkinColorTable = { + 0: "#FFD3AD", + 1: "#FEB66B", + 2: "#DE7942", + 3: "#FFAA8C", + 4: "#AD5129", + 5: "#632C18", + 6: "#ffbea5", + 7: "#ffc58f", + 8: "#8c3c23", + 9: "#3c2d23" +}; +var SwitchMiiColorTable = [ + "#2d2828", + "#402010", + "#5c180a", + "#7c3a14", + "#787880", + "#4e3e10", + "#885818", + "#d0a04a", + "#000000", + "#6c7070", + "#663c2c", + "#605e30", + "#4654a8", + "#387058", + "#603810", + "#a81008", + "#203068", + "#a86000", + "#787068", + "#d85208", + "#f00c08", + "#f54848", + "#f09a74", + "#8c5040", + "#842626", + "#ff7366", + "#ffa6a6", + "#ffc0ba", + "#732e3b", + "#991f3d", + "#8a173e", + "#b53e42", + "#c71e56", + "#b05381", + "#c7546e", + "#fa7597", + "#fcacc9", + "#ffc9d8", + "#311c40", + "#37283d", + "#4c184d", + "#6f42b3", + "#855cb8", + "#c083cc", + "#a893c9", + "#c5ace6", + "#eebefa", + "#d2c5ed", + "#191f40", + "#123f66", + "#2a82d4", + "#57b4f2", + "#7ac5de", + "#89a6fa", + "#84bdfa", + "#a1e3ff", + "#0b2e36", + "#013d3b", + "#0d4f59", + "#236663", + "#307e8c", + "#4faeb0", + "#7ac49e", + "#7fd4c0", + "#87e5b6", + "#0a4a35", + "#437a00", + "#027562", + "#369970", + "#4bad1a", + "#92bf0a", + "#63c788", + "#9ee042", + "#96de7e", + "#bbf2aa", + "#99932b", + "#a69563", + "#ccc039", + "#ccb987", + "#d9cc82", + "#d5d96f", + "#d5e683", + "#d8fa9d", + "#7d4500", + "#e6bb7a", + "#fee24a", + "#fade82", + "#f7ea9c", + "#faf89b", + "#a64d1e", + "#ff960d", + "#d19b69", + "#ffb266", + "#ffc28c", + "#e5cfb1", + "#414141", + "#9b9b9b", + "#bebebe", + "#dcd7cd", + "#ffffff" +]; +var SwitchMiiColorTableLip = [ + "#171414", + "#201008", + "#2e0c05", + "#4a230c", + "#54545a", + "#271f08", + "#52350e", + "#b18028", + "#000000", + "#4c4e4e", + "#331e16", + "#3a381d", + "#2a3265", + "#274e3e", + "#301c08", + "#650a05", + "#101834", + "#764300", + "#544e49", + "#823018", + "#780c0c", + "#882028", + "#dc7850", + "#461e0a", + "#4f1717", + "#99453d", + "#e68585", + "#e6a19b", + "#451c23", + "#5c1325", + "#530e25", + "#6d2528", + "#771234", + "#6a324d", + "#773242", + "#af526a", + "#e38cac", + "#e6abbb", + "#190e20", + "#1c141f", + "#260c27", + "#43286b", + "#50376e", + "#865c8f", + "#76678d", + "#ab90cf", + "#d4a0e1", + "#b8aad5", + "#0d1020", + "#092033", + "#1d5b94", + "#3297da", + "#5cadc8", + "#6786e1", + "#629fe1", + "#80c7e6", + "#06171b", + "#011f1e", + "#07282d", + "#184745", + "#225862", + "#308b8d", + "#60b087", + "#63bfa9", + "#69ce9b", + "#05251b", + "#284900", + "#01463b", + "#266b4e", + "#2c8a00", + "#6e9900", + "#47b36f", + "#82ca1f", + "#7ac860", + "#9eda8c", + "#6b671e", + "#746845", + "#a39816", + "#b8a36d", + "#c3b565", + "#bfc351", + "#bdcf64", + "#bce17d", + "#4b2900", + "#cfa15a", + "#e5c622", + "#e1c35f", + "#ded07c", + "#e1df7a", + "#642e12", + "#cc780a", + "#bc824c", + "#e69240", + "#e6a469", + "#ceb696", + "#212121", + "#7c7c7c", + "#ababab", + "#c6c1b6", + "#d9d9d9" +]; +var SwitchMiiColorTableSRGB = [ + [0.1764706, 0.1568628, 0.1568628], + [0.2509804, 0.1254902, 0.0627451], + [0.3607844, 0.0941177, 0.0392157], + [0.4862746, 0.227451, 0.0784314], + [0.4705883, 0.4705883, 0.5019608], + [0.3058824, 0.2431373, 0.0627451], + [0.5333334, 0.3450981, 0.0941177], + [0.8156863, 0.627451, 0.2901961], + [0, 0, 0], + [0.4235295, 0.4392157, 0.4392157], + [0.4, 0.2352942, 0.1725491], + [0.3764706, 0.3686275, 0.1882353], + [0.2745099, 0.3294118, 0.6588236], + [0.2196079, 0.4392157, 0.3450981], + [0.3764706, 0.2196079, 0.0627451], + [0.6588236, 0.0627451, 0.0313726], + [0.1254902, 0.1882353, 0.4078432], + [0.6588236, 0.3764706, 0], + [0.4705883, 0.4392157, 0.4078432], + [0.8470589, 0.3215687, 0.0313726], + [0.9411765, 0.0470589, 0.0313726], + [0.9607844, 0.282353, 0.282353], + [0.9411765, 0.6039216, 0.454902], + [0.5490197, 0.3137255, 0.2509804], + [0.5176471, 0.1490197, 0.1490197], + [1, 0.4509804, 0.4], + [1, 0.6509804, 0.6509804], + [1, 0.7529412, 0.7294118], + [0.4509804, 0.1803922, 0.2313726], + [0.6, 0.1215687, 0.2392157], + [0.5411765, 0.0901961, 0.2431373], + [0.709804, 0.2431373, 0.2588236], + [0.7803922, 0.1176471, 0.337255], + [0.6901961, 0.3254902, 0.5058824], + [0.7803922, 0.3294118, 0.4313726], + [0.9803922, 0.4588236, 0.5921569], + [0.9882353, 0.6745099, 0.7882353], + [1, 0.7882353, 0.8470589], + [0.1921569, 0.109804, 0.2509804], + [0.2156863, 0.1568628, 0.2392157], + [0.2980393, 0.0941177, 0.3019608], + [0.4352942, 0.2588236, 0.7019608], + [0.5215687, 0.3607844, 0.7215687], + [0.7529412, 0.5137255, 0.8], + [0.6588236, 0.5764706, 0.7882353], + [0.7725491, 0.6745099, 0.9019608], + [0.9333334, 0.7450981, 0.9803922], + [0.8235295, 0.7725491, 0.9294118], + [0.0980393, 0.1215687, 0.2509804], + [0.0705883, 0.2470589, 0.4], + [0.1647059, 0.509804, 0.8313726], + [0.3411765, 0.7058824, 0.9490197], + [0.4784314, 0.7725491, 0.8705883], + [0.537255, 0.6509804, 0.9803922], + [0.5176471, 0.7411765, 0.9803922], + [0.6313726, 0.8901961, 1], + [0.0431373, 0.1803922, 0.2117648], + [0.0039216, 0.2392157, 0.2313726], + [0.0509804, 0.309804, 0.3490197], + [0.137255, 0.4, 0.3882353], + [0.1882353, 0.4941177, 0.5490197], + [0.309804, 0.682353, 0.6901961], + [0.4784314, 0.7686275, 0.6196079], + [0.4980393, 0.8313726, 0.7529412], + [0.5294118, 0.8980393, 0.7137255], + [0.0392157, 0.2901961, 0.2078432], + [0.2627451, 0.4784314, 0], + [0.0078432, 0.4588236, 0.3843138], + [0.2117648, 0.6, 0.4392157], + [0.2941177, 0.6784314, 0.1019608], + [0.5725491, 0.7490197, 0.0392157], + [0.3882353, 0.7803922, 0.5333334], + [0.6196079, 0.8784314, 0.2588236], + [0.5882353, 0.8705883, 0.4941177], + [0.7333334, 0.9490197, 0.6666667], + [0.6, 0.5764706, 0.1686275], + [0.6509804, 0.5843138, 0.3882353], + [0.8, 0.7529412, 0.2235295], + [0.8, 0.7254902, 0.5294118], + [0.8509804, 0.8, 0.509804], + [0.8352942, 0.8509804, 0.4352942], + [0.8352942, 0.9019608, 0.5137255], + [0.8470589, 0.9803922, 0.6156863], + [0.4901961, 0.2705883, 0], + [0.9019608, 0.7333334, 0.4784314], + [0.9960785, 0.8862746, 0.2901961], + [0.9803922, 0.8705883, 0.509804], + [0.9686275, 0.9176471, 0.6117648], + [0.9803922, 0.9725491, 0.6078432], + [0.6509804, 0.3019608, 0.1176471], + [1, 0.5882353, 0.0509804], + [0.8196079, 0.6078432, 0.4117648], + [1, 0.6980393, 0.4], + [1, 0.7607844, 0.5490197], + [0.8980393, 0.8117648, 0.6941177], + [0.254902, 0.254902, 0.254902], + [0.6078432, 0.6078432, 0.6078432], + [0.7450981, 0.7450981, 0.7450981], + [0.8627451, 0.8431373, 0.8039216], + [1, 1, 1] +]; +var MiiSwitchSkinColorList = { + 0: "#ffd3ad", + 1: "#ffb66b", + 2: "#de7942", + 3: "#ffaa8c", + 4: "#ad5129", + 5: "#632c18", + 6: "#ffbea5", + 7: "#ffc58f", + 8: "#8c3c23", + 9: "#3c2d23" +}; +var MiiSwitchSkinColorSRGB = [ + [1, 0.8274509906768799, 0.6784313917160034], + [1, 0.7137255072593689, 0.41960790753364563], + [0.8705883026123047, 0.4745098948478699, 0.25882360339164734], + [1, 0.6666666865348816, 0.5490196943283081], + [0.6784313917160034, 0.3176470994949341, 0.16078439354896545], + [0.38823530077934265, 0.17254909873008728, 0.09411770105361938], + [1, 0.7450981140136719, 0.64705890417099], + [1, 0.7725490927696228, 0.5607843995094299], + [0.5490196943283081, 0.2352941930294037, 0.137254998087883], + [0.2352941930294037, 0.1764705926179886, 0.137254998087883] +]; +var ToVer3GlassTypeTable = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 1, + 2, + 1, + 3, + 7, + 7, + 6, + 7, + 8, + 7, + 7 +]; +var ToVer3HairColorTable = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 0, + 4, + 3, + 5, + 4, + 4, + 6, + 2, + 0, + 6, + 4, + 3, + 2, + 2, + 7, + 3, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 0, + 0, + 4, + 4, + 4, + 4, + 4, + 4, + 0, + 0, + 0, + 4, + 4, + 4, + 4, + 4, + 4, + 5, + 5, + 5, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 5, + 7, + 5, + 7, + 7, + 7, + 7, + 7, + 6, + 7, + 7, + 7, + 7, + 7, + 3, + 7, + 7, + 7, + 7, + 7, + 0, + 4, + 4, + 4, + 4 +]; +var ToVer3EyeColorTable = [ + 0, + 2, + 2, + 2, + 1, + 3, + 2, + 3, + 0, + 1, + 2, + 3, + 4, + 5, + 2, + 2, + 4, + 2, + 1, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 0, + 0, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 1, + 0, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 0, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 2, + 2, + 3, + 3, + 3, + 3, + 2, + 2, + 2, + 2, + 2, + 1, + 1, + 1, + 1, + 1, + 1 +]; +var ToVer3MouthColorTable = [ + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 3, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 1, + 4, + 4, + 4, + 0, + 1, + 2, + 3, + 4, + 4, + 2, + 3, + 3, + 4, + 4, + 4, + 4, + 1, + 4, + 4, + 2, + 3, + 3, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 3, + 3, + 3, + 4, + 4, + 4, + 3, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 4, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 3, + 3, + 3, + 3, + 3, + 3, + 4, + 4, + 3, + 3, + 3, + 3, + 3, + 3, + 4, + 3, + 3, + 3, + 3, + 3, + 4, + 0, + 3, + 3, + 3, + 3, + 4, + 3, + 3, + 3, + 3 +]; +var ToVer3GlassColorTable = [ + 0, + 1, + 1, + 1, + 5, + 1, + 1, + 4, + 0, + 5, + 1, + 1, + 3, + 5, + 1, + 2, + 3, + 4, + 5, + 4, + 2, + 2, + 4, + 4, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 0, + 0, + 0, + 5, + 5, + 5, + 5, + 5, + 5, + 0, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 1, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 5, + 5, + 5, + 5, + 5, + 5 +]; +var ToVer3FacelineColorTable = [0, 1, 2, 3, 4, 5, 0, 1, 5, 5]; +var Ver3FacelineColorTable = [0, 1, 2, 3, 4, 5]; +var Ver3HairColorTable = [8, 1, 2, 3, 4, 5, 6, 7]; +var Ver3EyeColorTable = [8, 9, 10, 11, 12, 13]; +var Ver3MouthColorTable = [19, 20, 21, 22, 23]; +var Ver3GlassColorTable = [8, 14, 15, 16, 17, 18, 0]; +var ForbiddenShirtPantColors = [, 7, 22, 78, 79, 84, 91, 92, 93, 94]; + +// src/class/struct/RFLStoreData.ts +var RFLCreateID = import_struct_fu2.default.struct([import_struct_fu2.default.uint8("data", 8)]); +var RFLCharData = import_struct_fu2.default.struct([ + import_struct_fu2.default.ubit("padding0", 1), + import_struct_fu2.default.ubit("gender", 1), + import_struct_fu2.default.ubit("birthMonth", 4), + import_struct_fu2.default.ubit("birthDay", 5), + import_struct_fu2.default.ubit("favoriteColor", 4), + import_struct_fu2.default.ubit("favorite", 1), + import_struct_fu2.default.char16be("name", 20), + import_struct_fu2.default.uint8("height"), + import_struct_fu2.default.uint8("build"), + import_struct_fu2.default.struct("create_id", [RFLCreateID]), + import_struct_fu2.default.ubit("faceType", 3), + import_struct_fu2.default.ubit("faceColor", 3), + import_struct_fu2.default.ubit("faceTex", 4), + import_struct_fu2.default.ubit("padding_2", 3), + import_struct_fu2.default.ubit("localonly", 1), + import_struct_fu2.default.ubit("type", 2), + import_struct_fu2.default.ubit("hairType", 7), + import_struct_fu2.default.ubit("hairColor", 3), + import_struct_fu2.default.ubit("hairFlip", 1), + import_struct_fu2.default.ubit("padding_3", 5), + import_struct_fu2.default.ubit("eyebrowType", 5), + import_struct_fu2.default.ubit("eyebrowRotate", 5), + import_struct_fu2.default.ubit("padding_4", 6), + import_struct_fu2.default.ubit("eyebrowColor", 3), + import_struct_fu2.default.ubit("eyebrowScale", 4), + import_struct_fu2.default.ubit("eyebrowY", 5), + import_struct_fu2.default.ubit("eyebrowX", 4), + import_struct_fu2.default.ubit("eyeType", 6), + import_struct_fu2.default.ubit("eyeRotate", 5), + import_struct_fu2.default.ubit("eyeY", 5), + import_struct_fu2.default.ubit("eyeColor", 3), + import_struct_fu2.default.ubit("eyeScale", 4), + import_struct_fu2.default.ubit("eyeX", 4), + import_struct_fu2.default.ubit("padding_5", 5), + import_struct_fu2.default.ubit("noseType", 4), + import_struct_fu2.default.ubit("noseScale", 4), + import_struct_fu2.default.ubit("noseY", 5), + import_struct_fu2.default.ubit("padding_6", 3), + import_struct_fu2.default.ubit("mouthType", 5), + import_struct_fu2.default.ubit("mouthColor", 2), + import_struct_fu2.default.ubit("mouthScale", 4), + import_struct_fu2.default.ubit("mouthY", 5), + import_struct_fu2.default.ubit("glassType", 4), + import_struct_fu2.default.ubit("glassColor", 3), + import_struct_fu2.default.ubit("glassScale", 4), + import_struct_fu2.default.ubit("glassY", 5), + import_struct_fu2.default.ubit("mustacheType", 2), + import_struct_fu2.default.ubit("beardType", 2), + import_struct_fu2.default.ubit("beardColor", 3), + import_struct_fu2.default.ubit("beardScale", 4), + import_struct_fu2.default.ubit("beardY", 5), + import_struct_fu2.default.ubit("moleType", 1), + import_struct_fu2.default.ubit("moleScale", 4), + import_struct_fu2.default.ubit("moleY", 5), + import_struct_fu2.default.ubit("moleX", 5), + import_struct_fu2.default.ubit("padding_8", 1), + import_struct_fu2.default.char16be("creatorName", 20) +]); +var RFLStoreData = import_struct_fu2.default.struct([ + import_struct_fu2.default.struct([RFLCharData]), + import_struct_fu2.default.uint16("checksum") +]); +var Ver1ToVer3FacelineTex = [ + [0, 0], + [1, 0], + [6, 0], + [9, 0], + [0, 5], + [0, 2], + [0, 3], + [0, 7], + [0, 8], + [10, 0], + [0, 9], + [0, 11] +]; +function RFLStoreDataToMiiCreatorV4Data(input) { + const output = EmptyMiiCreatorV4Data(); + console.log("input rfl data:", input); + output.beardColor = Ver3HairColorTable[input.beardColor]; + output.beardType = input.beardType; + output.birthDay = input.birthDay; + output.birthMonth = input.birthMonth; + output.build = input.build; + output.createId.set(RFLCreateID.pack(input.create_id), 0); + output.creator = input.creatorName; + output.eyeColor = Ver3EyeColorTable[input.eyeColor]; + output.eyeRotate = input.eyeRotate; + output.eyeScale = input.eyeScale; + output.eyeType = input.eyeType; + output.eyeX = input.eyeX; + output.eyeY = input.eyeY; + output.eyebrowColor = Ver3HairColorTable[input.eyebrowColor]; + output.eyebrowRotate = input.eyebrowRotate; + output.eyebrowScale = input.eyebrowScale; + output.eyebrowType = input.eyebrowType; + output.eyebrowX = input.eyebrowX; + output.eyebrowY = input.eyebrowY; + output.facelineColor = Ver3FacelineColorTable[input.faceColor]; + output.facelineType = input.faceType; + output.facelineMake = Ver1ToVer3FacelineTex[input.faceTex][0]; + output.facelineWrinkle = Ver1ToVer3FacelineTex[input.faceTex][1]; + output.favorite = input.favorite; + output.favoriteColor = input.favoriteColor; + output.gender = input.gender; + output.glassColor = Ver3GlassColorTable[input.glassColor]; + output.glassScale = input.glassScale; + output.glassType = input.glassType; + output.glassY = input.glassY; + output.hairColor = Ver3HairColorTable[input.hairColor]; + output.hairFlip = input.hairFlip; + output.hairType = input.hairType; + output.height = input.height; + output.moleScale = input.moleScale; + output.moleType = input.moleType; + output.moleX = input.moleX; + output.moleY = input.moleY; + output.mouthColor = Ver3MouthColorTable[input.mouthColor]; + output.mouthScale = input.mouthScale; + output.mouthType = input.mouthType; + output.mouthY = input.mouthY; + output.mustacheScale = input.beardScale; + output.mustacheType = input.mustacheType; + output.mustacheY = input.beardY; + output.noseScale = input.noseScale; + output.noseType = input.noseType; + output.noseY = input.noseY; + output.nickname = input.name; + output.creator = input.creatorName; + output.facePaintColor = -1; + output.hatCommonColor = -1; + output.hatFavoriteColor = -1; + output.hatType = -1; + output.wigType = -1; + output.pantsColor = -1; + output.personality = -1; + output.shirtColor = -1; + return output; +} + +// src/class/struct/MiiCreatorV4Data.ts +var MiiCreatorV4Data = import_struct_fu3.default.struct([ + import_struct_fu3.default.uint8("miicVersion"), + import_struct_fu3.default.uint8("originPlatform"), + import_struct_fu3.default.byte("authorId", 8), + import_struct_fu3.default.byte("createId", 10), + import_struct_fu3.default.char16le("creator", 20), + import_struct_fu3.default.char16le("nickname", 20), + import_struct_fu3.default.uint8("beardColor"), + import_struct_fu3.default.uint8("beardType"), + import_struct_fu3.default.uint8("birthDay"), + import_struct_fu3.default.uint8("birthMonth"), + import_struct_fu3.default.uint16("birthYear"), + import_struct_fu3.default.uint8("build"), + import_struct_fu3.default.uint8("eyeAspect"), + import_struct_fu3.default.uint8("eyebrowAspect"), + import_struct_fu3.default.uint8("eyebrowColor"), + import_struct_fu3.default.uint8("eyebrowRotate"), + import_struct_fu3.default.uint8("eyebrowScale"), + import_struct_fu3.default.uint8("eyebrowType"), + import_struct_fu3.default.uint8("eyebrowX"), + import_struct_fu3.default.uint8("eyebrowY"), + import_struct_fu3.default.uint8("eyeColor"), + import_struct_fu3.default.uint8("eyeRotate"), + import_struct_fu3.default.uint8("eyeScale"), + import_struct_fu3.default.uint8("eyeType"), + import_struct_fu3.default.uint8("eyeX"), + import_struct_fu3.default.uint8("eyeY"), + import_struct_fu3.default.uint8("facelineColor"), + import_struct_fu3.default.uint8("facelineMake"), + import_struct_fu3.default.uint8("facelineType"), + import_struct_fu3.default.uint8("facelineWrinkle"), + import_struct_fu3.default.uint8("facePaintColor"), + import_struct_fu3.default.uint8("favorite"), + import_struct_fu3.default.uint8("favoriteColor"), + import_struct_fu3.default.uint8("fontRegion"), + import_struct_fu3.default.uint8("gender"), + import_struct_fu3.default.uint8("glassColor"), + import_struct_fu3.default.uint8("glassScale"), + import_struct_fu3.default.uint8("glassType"), + import_struct_fu3.default.uint8("glassY"), + import_struct_fu3.default.uint8("hairColor"), + import_struct_fu3.default.uint8("hairFlip"), + import_struct_fu3.default.uint8("hairType"), + import_struct_fu3.default.uint8("hatFavoriteColor"), + import_struct_fu3.default.uint8("hatCommonColor"), + import_struct_fu3.default.uint8("hatType"), + import_struct_fu3.default.uint8("height"), + import_struct_fu3.default.uint8("wigType"), + import_struct_fu3.default.uint8("moleScale"), + import_struct_fu3.default.uint8("moleType"), + import_struct_fu3.default.uint8("moleX"), + import_struct_fu3.default.uint8("moleY"), + import_struct_fu3.default.uint8("mouthAspect"), + import_struct_fu3.default.uint8("mouthColor"), + import_struct_fu3.default.uint8("mouthScale"), + import_struct_fu3.default.uint8("mouthType"), + import_struct_fu3.default.uint8("mouthY"), + import_struct_fu3.default.uint8("mustacheScale"), + import_struct_fu3.default.uint8("mustacheType"), + import_struct_fu3.default.uint8("mustacheY"), + import_struct_fu3.default.uint8("noseScale"), + import_struct_fu3.default.uint8("noseType"), + import_struct_fu3.default.uint8("noseY"), + import_struct_fu3.default.uint8("pantsColor"), + import_struct_fu3.default.uint8("personality"), + import_struct_fu3.default.uint8("regionMove"), + import_struct_fu3.default.uint8("shirtColor"), + import_struct_fu3.default.uint8("special"), + import_struct_fu3.default.uint8("temporary"), + import_struct_fu3.default.uint8("eyeSclera"), + import_struct_fu3.default.uint8("clothesType"), + import_struct_fu3.default.uint8("shoesColor") +]); +var MiiCreatorV4AppendData = import_struct_fu3.default.struct([ + import_struct_fu3.default.uint8("miicVersion"), + import_struct_fu3.default.uint8("eyebrowColor"), + import_struct_fu3.default.uint8("eyeColor"), + import_struct_fu3.default.uint8("facelineColor"), + import_struct_fu3.default.uint8("glassColor"), + import_struct_fu3.default.uint8("glassType"), + import_struct_fu3.default.uint8("hairColor"), + import_struct_fu3.default.uint8("mouthColor"), + import_struct_fu3.default.uint8("hatType"), + import_struct_fu3.default.uint8("facePaintColor"), + import_struct_fu3.default.uint8("hatCommonColor"), + import_struct_fu3.default.uint8("hatFavoriteColor"), + import_struct_fu3.default.uint8("pantsColor"), + import_struct_fu3.default.uint8("personality"), + import_struct_fu3.default.uint8("shirtColor"), + import_struct_fu3.default.uint8("birthYear"), + import_struct_fu3.default.uint8("wigType"), + import_struct_fu3.default.uint8("originPlatform"), + import_struct_fu3.default.uint8("eyeSclera"), + import_struct_fu3.default.uint8("clothesType"), + import_struct_fu3.default.uint8("shoesColor") +]); +var EmptyMiiCreatorData = { + miicVersion: 4, + originPlatform: 5 /* Mii_Creator_v4 */, + authorId: new Uint8Array(8), + createId: new Uint8Array(10), + creator: "???", + nickname: "MISSING", + beardColor: 0, + beardType: 0, + birthDay: 0, + birthMonth: 0, + birthYear: 0, + build: 0, + eyebrowAspect: 3, + eyebrowColor: 0, + eyebrowRotate: 0, + eyebrowScale: 0, + eyebrowType: 0, + eyebrowX: 0, + eyebrowY: 0, + eyeAspect: 3, + eyeColor: 0, + eyeRotate: 0, + eyeScale: 0, + eyeType: 0, + eyeX: 0, + eyeY: 0, + facelineColor: 0, + facelineMake: 0, + facelineType: 0, + facelineWrinkle: 0, + facePaintColor: -1, + favorite: 0, + favoriteColor: 0, + fontRegion: 0, + gender: 0, + glassColor: 0, + glassScale: 0, + glassType: 0, + glassY: 0, + hairColor: 0, + hairFlip: 0, + hairType: 0, + hatFavoriteColor: -1, + hatCommonColor: -1, + hatType: -1, + height: 0, + wigType: -1, + moleScale: 0, + moleType: 0, + moleX: 0, + moleY: 0, + mouthAspect: 3, + mouthColor: 0, + mouthScale: 0, + mouthType: 0, + mouthY: 0, + mustacheScale: 0, + mustacheType: 0, + mustacheY: 0, + noseScale: 0, + noseType: 0, + noseY: 0, + pantsColor: -1, + personality: -1, + regionMove: 0, + shirtColor: -1, + special: 0, + temporary: 0, + eyeSclera: 0, + clothesType: -1, + shoesColor: -1 +}; +var EmptyMiiCreatorV4Data = () => ({ ...EmptyMiiCreatorData }); +function MiiCreatorV4DataToFFSD(input, pack = false, appendBytes = false) { + const output = { + author_id: FFLiAuthorID.unpack(input.authorId), + author_type: 0, + beard_color: ToVer3HairColorTable[input.beardColor], + beard_scale: input.mustacheScale, + beard_type: input.beardType, + beard_y: input.mustacheY, + birth_day: input.birthDay, + birth_month: input.birthMonth, + birth_platform: Math.max(2, Math.min(input.originPlatform, 3 /* FFL_Wii_U */)), + build: input.build, + checksum: 0, + copyable: 1, + create_id: FFLiCreateID.unpack(input.createId), + creator: input.creator, + eye_aspect: input.eyeAspect, + eye_color: ToVer3EyeColorTable[input.eyeColor], + eye_rotate: input.eyeRotate, + eye_scale: input.eyeScale, + eye_type: input.eyeType, + eye_x: input.eyeX, + eye_y: input.eyeY, + eyebrow_aspect: input.eyebrowAspect, + eyebrow_color: ToVer3HairColorTable[input.eyebrowColor], + eyebrow_rotate: input.eyebrowRotate, + eyebrow_scale: input.eyebrowScale, + eyebrow_type: input.eyebrowType, + eyebrow_x: input.eyebrowX, + eyebrow_y: input.eyebrowY, + face_color: ToVer3FacelineColorTable[input.facelineColor], + face_make: input.facelineMake, + face_tex: input.facelineWrinkle, + face_type: input.facelineType, + favorite: input.favorite, + favorite_color: input.favoriteColor, + font_region: input.fontRegion, + gender: input.gender, + glass_y: input.glassY, + glasses_color: ToVer3GlassColorTable[input.glassColor], + glasses_scale: input.glassScale, + glasses_type: ToVer3GlassTypeTable[input.glassType], + hair_color: ToVer3HairColorTable[input.hairColor], + hair_flip: input.hairFlip, + hair_type: input.hairType, + height: input.height, + localonly: 0, + mii_version: 3 /* FFL_Wii_U */, + mole_scale: input.moleScale, + mole_type: input.moleType, + mole_x: input.moleX, + mole_y: input.moleY, + mouth_aspect: input.mouthAspect, + mouth_color: ToVer3MouthColorTable[input.mouthColor], + mouth_scale: input.mouthScale, + mouth_type: input.mouthType, + mouth_y: input.mouthY, + mustache_type: input.mustacheType, + name: input.nickname, + ng_word: 0, + nose_scale: input.noseScale, + nose_type: input.noseType, + nose_y: input.noseY, + position_in_room: 0, + room_index: 0, + region_move: 0 + }; + output.create_id.flag_normal = Number(!input.special); + output.checksum = calculateCRC16(Ver3StoreData.pack(output)); + if (pack) { + if (appendBytes) { + const ffsdOutput = Ver3StoreData.pack(output); + const appendedBytes = MiiCreatorV4AppendData.pack(input); + const finalArray = new Uint8Array(ffsdOutput.length + appendedBytes.length); + finalArray.set(ffsdOutput, 0); + finalArray.set(appendedBytes, ffsdOutput.length); + return finalArray; + } + return Ver3StoreData.pack(output); + } else + return output; +} +var validationThing = { + beardColor: { type: 0 /* Number */, default: 0, min: 0, max: 99 }, + beardType: { type: 0 /* Number */, default: 0, min: 0, max: 5 }, + build: { type: 0 /* Number */, default: 64, min: 0, max: 127 }, + eyeAspect: { type: 0 /* Number */, default: 3, min: 0, max: 6 }, + eyeColor: { type: 0 /* Number */, default: 8, min: 0, max: 99 }, + eyeRotate: { type: 0 /* Number */, default: 4, min: 0, max: 7 }, + eyeScale: { type: 0 /* Number */, default: 4, min: 0, max: 7 }, + eyeSclera: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + eyeType: { type: 0 /* Number */, default: 2, min: 0, max: 59 }, + eyeX: { type: 0 /* Number */, default: 2, min: 0, max: 12 }, + eyeY: { type: 0 /* Number */, default: 12, min: 0, max: 18 }, + eyebrowAspect: { type: 0 /* Number */, default: 3, min: 0, max: 6 }, + eyebrowColor: { type: 0 /* Number */, default: 1, min: 0, max: 99 }, + eyebrowRotate: { type: 0 /* Number */, default: 6, min: 0, max: 11 }, + eyebrowScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + eyebrowType: { type: 0 /* Number */, default: 6, min: 0, max: 24 }, + eyebrowX: { type: 0 /* Number */, default: 2, min: 0, max: 12 }, + eyebrowY: { type: 0 /* Number */, default: 10, min: 3, max: 18 }, + facelineColor: { type: 0 /* Number */, default: 0, min: 0, max: 9 }, + facelineMake: { type: 0 /* Number */, default: 0, min: 0, max: 11 }, + facelineType: { type: 0 /* Number */, default: 0, min: 0, max: 11 }, + facelineWrinkle: { type: 0 /* Number */, default: 0, min: 0, max: 11 }, + favoriteColor: { type: 0 /* Number */, default: 0, min: 0, max: 11 }, + fontRegion: { type: 0 /* Number */, default: 0, min: 0, max: 3 }, + gender: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + glassColor: { type: 0 /* Number */, default: 8, min: 0, max: 99 }, + glassScale: { type: 0 /* Number */, default: 4, min: 0, max: 7 }, + glassType: { type: 0 /* Number */, default: 0, min: 0, max: 19 }, + glassY: { type: 0 /* Number */, default: 10, min: 0, max: 20 }, + hairColor: { type: 0 /* Number */, default: 1, min: 0, max: 99 }, + hairFlip: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + hairType: { type: 0 /* Number */, default: 33, min: 0, max: 131 }, + height: { type: 0 /* Number */, default: 64, min: 0, max: 127 }, + miicVersion: { type: 0 /* Number */, default: 4, min: 0, max: 4 }, + moleScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + moleType: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + moleX: { type: 0 /* Number */, default: 2, min: 0, max: 16 }, + moleY: { type: 0 /* Number */, default: 20, min: 0, max: 30 }, + mouthAspect: { type: 0 /* Number */, default: 3, min: 0, max: 6 }, + mouthColor: { type: 0 /* Number */, default: 19, min: 0, max: 99 }, + mouthScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + mouthType: { type: 0 /* Number */, default: 23, min: 0, max: 35 }, + mouthY: { type: 0 /* Number */, default: 13, min: 0, max: 18 }, + mustacheScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + mustacheType: { type: 0 /* Number */, default: 0, min: 0, max: 5 }, + mustacheY: { type: 0 /* Number */, default: 10, min: 0, max: 16 }, + creator: { type: 1 /* String */, default: "", min: 0, max: 10 }, + nickname: { type: 1 /* String */, default: "Mii", min: 1, max: 10 }, + noseScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + noseType: { type: 0 /* Number */, default: 1, min: 0, max: 17 }, + noseY: { type: 0 /* Number */, default: 9, min: 0, max: 18 }, + regionMove: { type: 0 /* Number */, default: 0, min: 0, max: 3 }, + authorId: { + type: 2 /* Array */, + default: [0, 0, 0, 0, 0, 0, 0, 0], + size: 8, + min: 0, + max: 255 + }, + birthDay: { type: 0 /* Number */, default: 0, min: 0, max: 31 }, + birthMonth: { type: 0 /* Number */, default: 0, min: 0, max: 12 }, + birthYear: { type: 0 /* Number */, default: 0, min: 0, max: 9999 }, + createId: { + type: 2 /* Array */, + default: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + size: 10, + min: 0, + max: 255 + }, + facePaintColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + favorite: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + hatCommonColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + hatFavoriteColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + hatType: { type: 0 /* Number */, default: -1, min: -1, max: 9 }, + wigType: { type: 0 /* Number */, default: -1, min: -1, max: 254 }, + clothesType: { type: 0 /* Number */, default: -1, min: -1, max: 254 }, + shoesColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + originPlatform: { + type: 0 /* Number */, + default: 5 /* Mii_Creator_v4 */, + min: 0, + max: 6 /* Origin_Platform_Max */ + }, + pantsColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + personality: { type: 0 /* Number */, default: -1, min: -1, max: 255 }, + shirtColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + special: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + temporary: { type: 0 /* Number */, default: 0, min: 0, max: 1 } +}; +function validate(input) { + let valid = true, reasons = []; + Object.keys(input).forEach((i) => { + function fail(reason = i) { + valid = false; + reasons.push(reason); + } + const prop = validationThing[i]; + if (!prop) { + alert("A prop is missing: " + i); + return; + } + }); + if (valid) + reasons.push("Valid"); + return { valid, reasons }; +} + +// src/class/struct/MiiCreatorV3Data.ts +var MiiCreatorV3Data = import_struct_fu4.default.struct([ + import_struct_fu4.default.struct([Ver3StoreData]), + import_struct_fu4.default.uint8("ext_faceline_color"), + import_struct_fu4.default.uint8("ext_hair_color"), + import_struct_fu4.default.uint8("ext_eye_color"), + import_struct_fu4.default.uint8("ext_eyebrow_color"), + import_struct_fu4.default.uint8("ext_mouth_color"), + import_struct_fu4.default.uint8("ext_beard_color"), + import_struct_fu4.default.uint8("ext_glass_color"), + import_struct_fu4.default.uint8("ext_glass_type"), + import_struct_fu4.default.uint8("ext_hat_type"), + import_struct_fu4.default.uint8("ext_hat_color"), + import_struct_fu4.default.uint8("ext_face_paint_color"), + import_struct_fu4.default.uint8("ext_shirt_color") +]); +function MiiCreatorV3DataToMiiCreatorV4Data(input) { + const data2 = EmptyMiiCreatorV4Data(); + switch (input.birth_platform) { + case 0: + data2.originPlatform = 0 /* RFL_Wii */; + break; + case 1: + data2.originPlatform = 1 /* NFL_DS */; + break; + case 2: + data2.originPlatform = 2 /* CFL_3DS */; + break; + case 3: + data2.originPlatform = 3 /* FFL_Wii_U */; + break; + } + if (input.ext_beard_color || input.ext_eye_color || input.ext_eyebrow_color || input.ext_face_paint_color || input.ext_faceline_color || input.ext_glass_color || input.ext_glass_type || input.ext_hair_color || input.ext_hat_color || input.ext_hat_type || input.ext_mouth_color || input.ext_shirt_color) { + data2.originPlatform = 5 /* Mii_Creator_v3 */; + } + data2.authorId = input.author_id.data; + data2.beardColor = input.ext_beard_color || Ver3HairColorTable[input.beard_color]; + data2.beardType = input.beard_type; + data2.birthDay = input.birth_day; + data2.birthMonth = input.birth_month; + data2.build = input.build; + data2.createId = FFLiCreateID.pack(input.create_id); + data2.creator = input.creator; + data2.eyeAspect = input.eye_aspect; + data2.eyebrowAspect = input.eyebrow_aspect; + data2.eyebrowColor = input.ext_eyebrow_color || Ver3HairColorTable[input.eyebrow_color]; + data2.eyebrowRotate = input.eyebrow_rotate; + data2.eyebrowScale = input.eyebrow_scale; + data2.eyebrowType = input.eyebrow_type; + data2.eyebrowX = input.eyebrow_x; + data2.eyebrowY = input.eyebrow_y; + data2.eyeColor = input.ext_eye_color || Ver3EyeColorTable[input.eye_color]; + data2.eyeRotate = input.eye_rotate; + data2.eyeScale = input.eye_scale; + data2.eyeType = input.eye_type; + data2.eyeX = input.eye_x; + data2.eyeY = input.eye_y; + data2.facelineColor = input.face_color; + data2.facelineMake = input.face_make; + data2.facelineType = input.face_type; + data2.facelineWrinkle = input.face_tex; + data2.facePaintColor = input.ext_face_paint_color - 1 || -1; + data2.favorite = input.favorite; + data2.favoriteColor = input.favorite_color; + data2.fontRegion = input.font_region; + data2.gender = input.gender; + data2.glassColor = input.ext_glass_color || Ver3GlassColorTable[input.glasses_color]; + data2.glassScale = input.glasses_scale; + data2.glassType = input.ext_glass_type || input.glasses_type; + data2.glassY = input.glass_y; + data2.hairColor = input.ext_hair_color || Ver3HairColorTable[input.hair_color]; + data2.hairFlip = input.hair_flip; + data2.hairType = input.hair_type; + data2.hatFavoriteColor = input.ext_hat_color !== 0 ? input.ext_hat_color - 1 : -1; + data2.hatType = input.ext_hat_type !== 0 ? input.ext_hat_type - 1 : -1; + data2.height = input.height; + data2.moleScale = input.mole_scale; + data2.moleType = input.mole_type; + data2.moleX = input.mole_x; + data2.moleY = input.mole_y; + data2.mouthAspect = input.mouth_aspect; + data2.mouthColor = input.ext_mouth_color || Ver3MouthColorTable[input.mouth_color]; + data2.mouthScale = input.mouth_scale; + data2.mouthType = input.mouth_type; + data2.mouthY = input.mouth_y; + data2.mustacheScale = input.beard_scale; + data2.mustacheType = input.mustache_type; + data2.mustacheY = input.beard_y; + data2.nickname = input.name; + data2.noseScale = input.nose_scale; + data2.noseType = input.nose_type; + data2.noseY = input.nose_y; + data2.regionMove = input.region_move; + if (input.create_id.flag_temporary !== 0) + data2.special = Number(!input.create_id.flag_normal); + data2.temporary = Number(input.create_id.flag_temporary); + return data2; +} + +// src/class/struct/NnMiiCharInfo.ts +var import_struct_fu5 = __toESM(require_struct_fu(), 1); +var NnMiiCharInfo = import_struct_fu5.default.struct([ + import_struct_fu5.default.byte("createId", 16), + import_struct_fu5.default.char16le("nickname", 22), + import_struct_fu5.default.uint8("fontRegion"), + import_struct_fu5.default.uint8("favoriteColor"), + import_struct_fu5.default.uint8("gender"), + import_struct_fu5.default.uint8("height"), + import_struct_fu5.default.uint8("build"), + import_struct_fu5.default.uint8("type"), + import_struct_fu5.default.uint8("regionMove"), + import_struct_fu5.default.uint8("facelineType"), + import_struct_fu5.default.uint8("facelineColor"), + import_struct_fu5.default.uint8("facelineWrinkle"), + import_struct_fu5.default.uint8("facelineMake"), + import_struct_fu5.default.uint8("hairType"), + import_struct_fu5.default.uint8("hairColor"), + import_struct_fu5.default.uint8("hairFlip"), + import_struct_fu5.default.uint8("eyeType"), + import_struct_fu5.default.uint8("eyeColor"), + import_struct_fu5.default.uint8("eyeScale"), + import_struct_fu5.default.uint8("eyeAspect"), + import_struct_fu5.default.uint8("eyeRotate"), + import_struct_fu5.default.uint8("eyeX"), + import_struct_fu5.default.uint8("eyeY"), + import_struct_fu5.default.uint8("eyebrowType"), + import_struct_fu5.default.uint8("eyebrowColor"), + import_struct_fu5.default.uint8("eyebrowScale"), + import_struct_fu5.default.uint8("eyebrowAspect"), + import_struct_fu5.default.uint8("eyebrowRotate"), + import_struct_fu5.default.uint8("eyebrowX"), + import_struct_fu5.default.uint8("eyebrowY"), + import_struct_fu5.default.uint8("noseType"), + import_struct_fu5.default.uint8("noseScale"), + import_struct_fu5.default.uint8("noseY"), + import_struct_fu5.default.uint8("mouthType"), + import_struct_fu5.default.uint8("mouthColor"), + import_struct_fu5.default.uint8("mouthScale"), + import_struct_fu5.default.uint8("mouthAspect"), + import_struct_fu5.default.uint8("mouthY"), + import_struct_fu5.default.uint8("beardColor"), + import_struct_fu5.default.uint8("beardType"), + import_struct_fu5.default.uint8("mustacheType"), + import_struct_fu5.default.uint8("mustacheScale"), + import_struct_fu5.default.uint8("mustacheY"), + import_struct_fu5.default.uint8("glassType"), + import_struct_fu5.default.uint8("glassColor"), + import_struct_fu5.default.uint8("glassScale"), + import_struct_fu5.default.uint8("glassY"), + import_struct_fu5.default.uint8("moleType"), + import_struct_fu5.default.uint8("moleScale"), + import_struct_fu5.default.uint8("moleX"), + import_struct_fu5.default.uint8("moleY"), + import_struct_fu5.default.uint8("reserved") +]); + +// src/class/struct/StudioData.ts +var import_struct_fu6 = __toESM(require_struct_fu(), 1); +var StudioData = import_struct_fu6.default.struct([ + import_struct_fu6.default.uint8("beardColor"), + import_struct_fu6.default.uint8("beardType"), + import_struct_fu6.default.uint8("build"), + import_struct_fu6.default.uint8("eyeAspect"), + import_struct_fu6.default.uint8("eyeColor"), + import_struct_fu6.default.uint8("eyeRotate"), + import_struct_fu6.default.uint8("eyeScale"), + import_struct_fu6.default.uint8("eyeType"), + import_struct_fu6.default.uint8("eyeX"), + import_struct_fu6.default.uint8("eyeY"), + import_struct_fu6.default.uint8("eyebrowAspect"), + import_struct_fu6.default.uint8("eyebrowColor"), + import_struct_fu6.default.uint8("eyebrowRotate"), + import_struct_fu6.default.uint8("eyebrowScale"), + import_struct_fu6.default.uint8("eyebrowType"), + import_struct_fu6.default.uint8("eyebrowX"), + import_struct_fu6.default.uint8("eyebrowY"), + import_struct_fu6.default.uint8("facelineColor"), + import_struct_fu6.default.uint8("facelineMake"), + import_struct_fu6.default.uint8("facelineType"), + import_struct_fu6.default.uint8("facelineWrinkle"), + import_struct_fu6.default.uint8("favoriteColor"), + import_struct_fu6.default.uint8("gender"), + import_struct_fu6.default.uint8("glassColor"), + import_struct_fu6.default.uint8("glassScale"), + import_struct_fu6.default.uint8("glassType"), + import_struct_fu6.default.uint8("glassY"), + import_struct_fu6.default.uint8("hairColor"), + import_struct_fu6.default.uint8("hairFlip"), + import_struct_fu6.default.uint8("hairType"), + import_struct_fu6.default.uint8("height"), + import_struct_fu6.default.uint8("moleScale"), + import_struct_fu6.default.uint8("moleType"), + import_struct_fu6.default.uint8("moleX"), + import_struct_fu6.default.uint8("moleY"), + import_struct_fu6.default.uint8("mouthAspect"), + import_struct_fu6.default.uint8("mouthColor"), + import_struct_fu6.default.uint8("mouthScale"), + import_struct_fu6.default.uint8("mouthType"), + import_struct_fu6.default.uint8("mouthY"), + import_struct_fu6.default.uint8("mustacheScale"), + import_struct_fu6.default.uint8("mustacheType"), + import_struct_fu6.default.uint8("mustacheY"), + import_struct_fu6.default.uint8("noseScale"), + import_struct_fu6.default.uint8("noseType"), + import_struct_fu6.default.uint8("noseY") +]); + +// node_modules/gettext.js/lib/gettext.js +/*! gettext.js - Guillaume Potier - MIT Licensed */ +var i18n = function(options) { + options = options || {}; + this && (this.__version = "2.0.0"); + var defaults2 = { + domain: "messages", + locale: (typeof document !== "undefined" ? document.documentElement.getAttribute("lang") : false) || "en", + plural_func: function(n) { + return { nplurals: 2, plural: n != 1 ? 1 : 0 }; + }, + ctxt_delimiter: String.fromCharCode(4) + }; + var _8 = { + isObject: function(obj) { + var type = typeof obj; + return type === "function" || type === "object" && !!obj; + }, + isArray: function(obj) { + return toString.call(obj) === "[object Array]"; + } + }; + var _plural_funcs = {}, _locale = options.locale || defaults2.locale, _domain = options.domain || defaults2.domain, _dictionary = {}, _plural_forms = {}, _ctxt_delimiter = options.ctxt_delimiter || defaults2.ctxt_delimiter; + if (options.messages) { + _dictionary[_domain] = {}; + _dictionary[_domain][_locale] = options.messages; + } + if (options.plural_forms) { + _plural_forms[_locale] = options.plural_forms; + } + var strfmt = function(fmt) { + var args = arguments; + return fmt.replace(/%%/g, "%% ").replace(/%(\d+)/g, function(str, p1) { + return args[p1]; + }).replace(/%% /g, "%"); + }; + var removeContext = function(str) { + if (str.indexOf(_ctxt_delimiter) !== -1) { + var parts = str.split(_ctxt_delimiter); + return parts[1]; + } + return str; + }; + var expand_locale = function(locale) { + var locales = [locale], i = locale.lastIndexOf("-"); + while (i > 0) { + locale = locale.slice(0, i); + locales.push(locale); + i = locale.lastIndexOf("-"); + } + return locales; + }; + var normalizeLocale = function(locale) { + locale = locale.replace("_", "-"); + var i = locale.search(/[.@]/); + if (i != -1) + locale = locale.slice(0, i); + return locale; + }; + var getPluralFunc = function(plural_form) { + var pf_re = new RegExp("^\\s*nplurals\\s*=\\s*[0-9]+\\s*;\\s*plural\\s*=\\s*(?:\\s|[-\\?\\|&=!<>+*/%:;n0-9_()])+"); + var match = plural_form.match(pf_re); + if (!match || match[0] !== plural_form) + throw new Error(strfmt('The plural form "%1" is not valid', plural_form)); + return new Function("n", "var plural, nplurals; " + plural_form + " return { nplurals: nplurals, plural: (plural === true ? 1 : (plural ? plural : 0)) };"); + }; + var t = function(messages, n, options2) { + if (!options2.plural_form) + return strfmt.apply(this, [removeContext(messages[0])].concat(Array.prototype.slice.call(arguments, 3))); + var plural; + if (options2.plural_func) { + plural = options2.plural_func(n); + } else if (!_plural_funcs[_locale]) { + _plural_funcs[_locale] = getPluralFunc(_plural_forms[_locale]); + plural = _plural_funcs[_locale](n); + } else { + plural = _plural_funcs[_locale](n); + } + if (typeof plural.plural === "undefined" || plural.plural > plural.nplurals || messages.length <= plural.plural) + plural.plural = 0; + return strfmt.apply(this, [removeContext(messages[plural.plural])].concat(Array.prototype.slice.call(arguments, 3))); + }; + return { + strfmt, + expand_locale, + __: function() { + return this.gettext.apply(this, arguments); + }, + _n: function() { + return this.ngettext.apply(this, arguments); + }, + _p: function() { + return this.pgettext.apply(this, arguments); + }, + setMessages: function(domain, locale, messages, plural_forms) { + if (!domain || !locale || !messages) + throw new Error("You must provide a domain, a locale and messages"); + if (typeof domain !== "string" || typeof locale !== "string" || !_8.isObject(messages)) + throw new Error("Invalid arguments"); + locale = normalizeLocale(locale); + if (plural_forms) + _plural_forms[locale] = plural_forms; + if (!_dictionary[domain]) + _dictionary[domain] = {}; + _dictionary[domain][locale] = messages; + return this; + }, + loadJSON: function(jsonData, domain) { + if (!_8.isObject(jsonData)) + jsonData = JSON.parse(jsonData); + if (!jsonData[""] || !jsonData[""]["language"] || !jsonData[""]["plural-forms"]) + throw new Error('Wrong JSON, it must have an empty key ("") with "language" and "plural-forms" information'); + var headers = jsonData[""]; + delete jsonData[""]; + return this.setMessages(domain || defaults2.domain, headers["language"], jsonData, headers["plural-forms"]); + }, + setLocale: function(locale) { + _locale = normalizeLocale(locale); + return this; + }, + getLocale: function() { + return _locale; + }, + textdomain: function(domain) { + if (!domain) + return _domain; + _domain = domain; + return this; + }, + gettext: function(msgid) { + return this.dcnpgettext.apply(this, [undefined, undefined, msgid, undefined, undefined].concat(Array.prototype.slice.call(arguments, 1))); + }, + ngettext: function(msgid, msgid_plural, n) { + return this.dcnpgettext.apply(this, [undefined, undefined, msgid, msgid_plural, n].concat(Array.prototype.slice.call(arguments, 3))); + }, + pgettext: function(msgctxt, msgid) { + return this.dcnpgettext.apply(this, [undefined, msgctxt, msgid, undefined, undefined].concat(Array.prototype.slice.call(arguments, 2))); + }, + dcnpgettext: function(domain, msgctxt, msgid, msgid_plural, n) { + domain = domain || _domain; + if (typeof msgid !== "string") + throw new Error(this.strfmt('Msgid "%1" is not a valid translatable string', msgid)); + var translation, options2 = { plural_form: false }, key2 = msgctxt ? msgctxt + _ctxt_delimiter + msgid : msgid, exist, locale, locales = expand_locale(_locale); + for (var i in locales) { + locale = locales[i]; + exist = _dictionary[domain] && _dictionary[domain][locale] && _dictionary[domain][locale][key2]; + if (msgid_plural) { + exist = exist && typeof _dictionary[domain][locale][key2] !== "string"; + } else { + exist = exist && typeof _dictionary[domain][locale][key2] === "string"; + } + if (exist) { + break; + } + } + if (!exist) { + translation = msgid; + options2.plural_func = defaults2.plural_func; + } else { + translation = _dictionary[domain][locale][key2]; + } + if (!msgid_plural) + return t.apply(this, [[translation], n, options2].concat(Array.prototype.slice.call(arguments, 5))); + options2.plural_form = true; + return t.apply(this, [exist ? translation : [msgid, msgid_plural], n, options2].concat(Array.prototype.slice.call(arguments, 5))); + } + }; +}; +var gettext_default = i18n; + +// src/util/Lang.ts +var localization = gettext_default(); +var _8 = () => localization.gettext.bind(localization); + +// src/class/MiiData.ts +var __ = _8(); + +class Mii { + miicVersion; + originPlatform; + authorId; + createId; + creator; + nickname; + beardColor; + beardType; + birthDay; + birthMonth; + birthYear; + build; + clothesType; + eyeAspect; + eyebrowAspect; + eyebrowColor; + eyebrowRotate; + eyebrowScale; + eyebrowType; + eyebrowX; + eyebrowY; + eyeColor; + eyeRotate; + eyeScale; + eyeSclera; + eyeType; + eyeX; + eyeY; + facelineColor; + facelineMake; + facelineType; + facelineWrinkle; + facePaintColor; + favorite; + favoriteColor; + fontRegion; + gender; + glassColor; + glassScale; + glassType; + glassY; + hairColor; + hairFlip; + hairType; + hatCommonColor; + hatFavoriteColor; + hatType; + height; + wigType; + moleScale; + moleType; + moleX; + moleY; + mouthAspect; + mouthColor; + mouthScale; + mouthType; + mouthY; + mustacheScale; + mustacheType; + mustacheY; + temporary; + noseScale; + noseType; + noseY; + pantsColor; + personality; + regionMove; + shirtColor; + shoesColor; + special; + valid; + constructor(initData) { + let importData; + if (typeof initData === "string") + importData = parseHexOrB64ToUint8Array(initData); + else + importData = initData; + this.import(Mii.parseData(importData)); + } + static parseData(input) { + let data2 = EmptyMiiCreatorV4Data(); + let tempArray; + switch (input.length) { + case 46: + case 47: + tempArray = allocateArray(48, input); + data2 = { ...EmptyMiiCreatorV4Data(), ...StudioData.unpack(tempArray) }; + data2.originPlatform = 5 /* Mii_Creator_v4 */; + data2.nickname = "Mii"; + data2.creator = ""; + break; + case 74: + case 76: + tempArray = allocateArray(96, input); + data2 = RFLStoreDataToMiiCreatorV4Data(RFLStoreData.unpack(tempArray)); + break; + case 87: + case 88: + tempArray = allocateArray(88, input); + const d = NnMiiCharInfo.unpack(tempArray); + var tmpCreateId = new Uint8Array(10); + tmpCreateId.set(d.createId.slice(0, 10), 0); + d.createId = tmpCreateId; + data2 = { ...data2, ...d }; + data2.createId.set(d.createId.slice(0, 10), 0); + data2.authorId.set(d.createId.slice(10), 0); + data2.creator = ""; + data2.originPlatform = 4 /* nn_mii_Switch */; + break; + case 92: + case 96: + tempArray = allocateArray(108, input); + data2 = MiiCreatorV3DataToMiiCreatorV4Data(MiiCreatorV3Data.unpack(MiiCreatorV3Data.pack(Ver3StoreData.unpack(tempArray)))); + break; + case 104: + case 106: + case 108: + tempArray = allocateArray(108, input); + data2 = MiiCreatorV3DataToMiiCreatorV4Data(MiiCreatorV3Data.unpack(tempArray)); + break; + case 114: + tempArray = allocateArray(123, input); + data2 = MiiCreatorV3DataToMiiCreatorV4Data(MiiCreatorV3Data.unpack(MiiCreatorV3Data.pack(Ver3StoreData.unpack(tempArray)))); + break; + case 122: + case 123: + case 124: + case 125: + case 126: + tempArray = allocateArray(126, input); + data2 = MiiCreatorV4Data.unpack(tempArray); + if (input.length < 126) { + data2.shoesColor = -1; + } + if (input.length < 125) { + data2.clothesType = -1; + } + break; + default: + throw new Error(__("Mii data type not supported (%1 bytes)", input.length)); + } + if (data2.facePaintColor === 255) + data2.facePaintColor = -1; + if (data2.hatCommonColor === 255) + data2.hatCommonColor = -1; + if (data2.hatFavoriteColor === 255) + data2.hatFavoriteColor = -1; + if (data2.hatType === 255) + data2.hatType = -1; + if (data2.pantsColor === 255) + data2.pantsColor = -1; + if (data2.personality === 255) + data2.personality = -1; + if (data2.shirtColor === 255) + data2.shirtColor = -1; + if (data2.wigType === 255) + data2.wigType = -1; + if (data2.clothesType === 255) + data2.clothesType = -1; + if (data2.shoesColor === 255) + data2.shoesColor = -1; + return data2; + } + static parseDataBinary(input) { + const data2 = Mii.parseData(input); + return MiiCreatorV4Data.pack(data2); + } + #getObject(override = null) { + return { + miicVersion: this.miicVersion, + originPlatform: this.originPlatform, + authorId: this.authorId, + createId: this.createId, + creator: this.creator, + nickname: this.nickname, + beardColor: this.beardColor, + beardType: this.beardType, + birthDay: this.birthDay, + birthMonth: this.birthMonth, + birthYear: this.birthYear, + build: this.build, + clothesType: this.clothesType, + eyeAspect: this.eyeAspect, + eyebrowAspect: this.eyebrowAspect, + eyebrowColor: this.eyebrowColor, + eyebrowRotate: this.eyebrowRotate, + eyebrowScale: this.eyebrowScale, + eyebrowType: this.eyebrowType, + eyebrowX: this.eyebrowX, + eyebrowY: this.eyebrowY, + eyeColor: this.eyeColor, + eyeRotate: this.eyeRotate, + eyeScale: this.eyeScale, + eyeSclera: this.eyeSclera, + eyeType: this.eyeType, + eyeX: this.eyeX, + eyeY: this.eyeY, + facelineColor: this.facelineColor, + facelineMake: this.facelineMake, + facelineType: this.facelineType, + facelineWrinkle: this.facelineWrinkle, + facePaintColor: this.facePaintColor, + favorite: this.favorite, + favoriteColor: this.favoriteColor, + fontRegion: this.fontRegion, + gender: this.gender, + glassColor: this.glassColor, + glassScale: this.glassScale, + glassType: this.glassType, + glassY: this.glassY, + hairColor: this.hairColor, + hairFlip: this.hairFlip, + hairType: this.hairType, + hatCommonColor: this.hatCommonColor, + hatFavoriteColor: this.hatFavoriteColor, + hatType: this.hatType, + height: this.height, + wigType: this.wigType, + moleScale: this.moleScale, + moleType: this.moleType, + moleX: this.moleX, + moleY: this.moleY, + mouthAspect: this.mouthAspect, + mouthColor: this.mouthColor, + mouthScale: this.mouthScale, + mouthType: this.mouthType, + mouthY: this.mouthY, + mustacheScale: this.mustacheScale, + mustacheType: this.mustacheType, + mustacheY: this.mustacheY, + temporary: this.temporary, + noseScale: this.noseScale, + noseType: this.noseType, + noseY: this.noseY, + pantsColor: this.pantsColor, + personality: this.personality, + regionMove: this.regionMove, + shirtColor: this.shirtColor, + shoesColor: this.shoesColor, + special: this.special, + ...override + }; + } + #getNicknameSafe() { + if (this.nickname.trim() !== "") + return this.nickname; + else + return "A Mii"; + } + verify() { + return validate(this.#getObject()); + } + validate() { + const verify = this.verify(); + if (verify.valid === true) + this.valid = true; + else { + this.valid = false; + console.warn(`${this.#getNicknameSafe()} has invalid data:`, verify.reasons.join(", ")); + console.warn(this.export()); + throw new Error(`Mii data for ${this.nickname} is not valid: ${verify.reasons.join(", ")}`); + } + } + import(data2) { + this.miicVersion = data2.miicVersion; + this.originPlatform = data2.originPlatform; + this.authorId = data2.authorId; + this.createId = data2.createId; + this.creator = data2.creator; + this.nickname = data2.nickname; + this.beardColor = data2.beardColor; + this.beardType = data2.beardType; + this.birthDay = data2.birthDay; + this.birthMonth = data2.birthMonth; + this.birthYear = data2.birthYear; + this.build = data2.build; + this.clothesType = data2.clothesType; + this.eyeAspect = data2.eyeAspect; + this.eyebrowAspect = data2.eyebrowAspect; + this.eyebrowColor = data2.eyebrowColor; + this.eyebrowRotate = data2.eyebrowRotate; + this.eyebrowScale = data2.eyebrowScale; + this.eyebrowType = data2.eyebrowType; + this.eyebrowX = data2.eyebrowX; + this.eyebrowY = data2.eyebrowY; + this.eyeColor = data2.eyeColor; + this.eyeRotate = data2.eyeRotate; + this.eyeScale = data2.eyeScale; + this.eyeSclera = data2.eyeSclera; + this.eyeType = data2.eyeType; + this.eyeX = data2.eyeX; + this.eyeY = data2.eyeY; + this.facelineColor = data2.facelineColor; + this.facelineMake = data2.facelineMake; + this.facelineType = data2.facelineType; + this.facelineWrinkle = data2.facelineWrinkle; + this.facePaintColor = data2.facePaintColor; + this.favorite = data2.favorite; + this.favoriteColor = data2.favoriteColor; + this.fontRegion = data2.fontRegion; + this.gender = data2.gender; + this.glassColor = data2.glassColor; + this.glassScale = data2.glassScale; + this.glassType = data2.glassType; + this.glassY = data2.glassY; + this.hairColor = data2.hairColor; + this.hairFlip = data2.hairFlip; + this.hairType = data2.hairType; + this.hatFavoriteColor = data2.hatFavoriteColor; + this.hatCommonColor = data2.hatCommonColor; + this.hatType = data2.hatType; + this.height = data2.height; + this.wigType = data2.wigType; + this.moleScale = data2.moleScale; + this.moleType = data2.moleType; + this.moleX = data2.moleX; + this.moleY = data2.moleY; + this.mouthAspect = data2.mouthAspect; + this.mouthColor = data2.mouthColor; + this.mouthScale = data2.mouthScale; + this.mouthType = data2.mouthType; + this.mouthY = data2.mouthY; + this.mustacheScale = data2.mustacheScale; + this.mustacheType = data2.mustacheType; + this.mustacheY = data2.mustacheY; + this.noseScale = data2.noseScale; + this.noseType = data2.noseType; + this.noseY = data2.noseY; + this.pantsColor = data2.pantsColor; + this.personality = data2.personality; + this.regionMove = data2.regionMove; + this.shirtColor = data2.shirtColor; + this.special = data2.special; + this.shoesColor = data2.shoesColor; + this.temporary = data2.temporary; + if (this.originPlatform === 2 /* CFL_3DS */ || this.originPlatform === 3 /* FFL_Wii_U */) { + const createId = FFLiCreateID.unpack(this.createId); + if (!createId.flag_normal) { + this.special = 1; + } + if (createId.flag_temporary) { + this.special = 0; + this.temporary = 1; + } + } + this.fixInternalIDs(); + } + export(outputFormat = "miic") { + this.fixInternalIDs(); + switch (outputFormat) { + case "rsd": + throw new Error("RSD format is not yet supported."); + default: + case "miic": + return MiiCreatorV4Data.pack(this.#getObject()); + case "studioData": + return StudioData.pack(this.#getObject({ + facelineColor: this.facePaintColor !== -1 ? this.facePaintColor + 10 : this.facelineColor + })); + case "switchCharInfo": + return NnMiiCharInfo.pack(this.#getObject()); + case "ffsd": + return MiiCreatorV4DataToFFSD(this.#getObject(), true); + case "ffsd_append_miic": + return MiiCreatorV4DataToFFSD(this.#getObject(), true, true); + } + } + exportHex(outputFormat) { + const data2 = this.export(outputFormat); + return dataToHex(data2); + } + exportBase64(outputFormat) { + const data2 = this.export(outputFormat); + return dataToBase64(data2); + } + hasExtendedColors() { + return false; + } + fixInternalIDs() { + const createId = FFLiCreateID.unpack(this.createId); + const authorId = this.authorId; + if (Array.from(createId.base).every((e) => e === 0)) { + createId.base = randomizeUint8Array(createId.base); + } + if (Array.from(authorId).every((e) => e === 0)) { + this.authorId = randomizeUint8Array(authorId); + } + if (createId.flag_normal === 0 && this.special === 0) { + createId.flag_normal = 1; + } + if (createId.flag_normal === 1 && this.special === 1) { + createId.flag_normal = 0; + } + if (createId.flag_temporary === 0 && this.temporary === 1) { + createId.flag_temporary = 1; + } + if (createId.flag_temporary === 1 && this.temporary === 0) { + createId.flag_temporary = 0; + } + this.createId = FFLiCreateID.pack(createId); + } +} + +// src/util/miiImageUtils.ts +var import_qrjs_min = __toESM(require_qrjs_min(), 1); + +// src/external/mii-frontend/sjcl.min.js +var sjcl = { cipher: {}, hash: {}, keyexchange: {}, mode: {}, misc: {}, codec: {}, exception: { corrupt: function(a) { + this.toString = function() { + return "CORRUPT: " + this.message; + }; + this.message = a; +}, invalid: function(a) { + this.toString = function() { + return "INVALID: " + this.message; + }; + this.message = a; +}, bug: function(a) { + this.toString = function() { + return "BUG: " + this.message; + }; + this.message = a; +}, notReady: function(a) { + this.toString = function() { + return "NOT READY: " + this.message; + }; + this.message = a; +} } }; +sjcl.cipher.aes = function(a) { + this.s[0][0][0] || this.O(); + var b, c, d, e, f = this.s[0][4], g = this.s[1]; + b = a.length; + var h = 1; + if (b !== 4 && b !== 6 && b !== 8) + throw new sjcl.exception.invalid("invalid aes key size"); + this.b = [d = a.slice(0), e = []]; + for (a = b;a < 4 * b + 28; a++) { + c = d[a - 1]; + if (a % b === 0 || b === 8 && a % b === 4) + c = f[c >>> 24] << 24 ^ f[c >> 16 & 255] << 16 ^ f[c >> 8 & 255] << 8 ^ f[c & 255], a % b === 0 && (c = c << 8 ^ c >>> 24 ^ h << 24, h = h << 1 ^ 283 * (h >> 7)); + d[a] = d[a - b] ^ c; + } + for (b = 0;a; b++, a--) + c = d[b & 3 ? a : a - 4], e[b] = 4 >= a || 4 > b ? c : g[0][f[c >>> 24]] ^ g[1][f[c >> 16 & 255]] ^ g[2][f[c >> 8 & 255]] ^ g[3][f[c & 255]]; +}; +sjcl.cipher.aes.prototype = { encrypt: function(a) { + return t(this, a, 0); +}, decrypt: function(a) { + return t(this, a, 1); +}, s: [[[], [], [], [], []], [[], [], [], [], []]], O: function() { + var a = this.s[0], b = this.s[1], c = a[4], d = b[4], e, f, g, h = [], k2 = [], l, n, m, p; + for (e = 0;256 > e; e++) + k2[(h[e] = e << 1 ^ 283 * (e >> 7)) ^ e] = e; + for (f = g = 0;!c[f]; f ^= l || 1, g = k2[g] || 1) + for (m = g ^ g << 1 ^ g << 2 ^ g << 3 ^ g << 4, m = m >> 8 ^ m & 255 ^ 99, c[f] = m, d[m] = f, n = h[e = h[l = h[f]]], p = 16843009 * n ^ 65537 * e ^ 257 * l ^ 16843008 * f, n = 257 * h[m] ^ 16843008 * m, e = 0;4 > e; e++) + a[e][f] = n = n << 24 ^ n >>> 8, b[e][m] = p = p << 24 ^ p >>> 8; + for (e = 0;5 > e; e++) + a[e] = a[e].slice(0), b[e] = b[e].slice(0); +} }; +function t(a, b, c) { + if (b.length !== 4) + throw new sjcl.exception.invalid("invalid aes block size"); + var d = a.b[c], e = b[0] ^ d[0], f = b[c ? 3 : 1] ^ d[1], g = b[2] ^ d[2]; + b = b[c ? 1 : 3] ^ d[3]; + var h, k2, l, n = d.length / 4 - 2, m, p = 4, r = [0, 0, 0, 0]; + h = a.s[c]; + a = h[0]; + var q = h[1], v = h[2], w = h[3], x = h[4]; + for (m = 0;m < n; m++) + h = a[e >>> 24] ^ q[f >> 16 & 255] ^ v[g >> 8 & 255] ^ w[b & 255] ^ d[p], k2 = a[f >>> 24] ^ q[g >> 16 & 255] ^ v[b >> 8 & 255] ^ w[e & 255] ^ d[p + 1], l = a[g >>> 24] ^ q[b >> 16 & 255] ^ v[e >> 8 & 255] ^ w[f & 255] ^ d[p + 2], b = a[b >>> 24] ^ q[e >> 16 & 255] ^ v[f >> 8 & 255] ^ w[g & 255] ^ d[p + 3], p += 4, e = h, f = k2, g = l; + for (m = 0;4 > m; m++) + r[c ? 3 & -m : m] = x[e >>> 24] << 24 ^ x[f >> 16 & 255] << 16 ^ x[g >> 8 & 255] << 8 ^ x[b & 255] ^ d[p++], h = e, e = f, f = g, g = b, b = h; + return r; +} +sjcl.bitArray = { bitSlice: function(a, b, c) { + a = sjcl.bitArray.$(a.slice(b / 32), 32 - (b & 31)).slice(1); + return c === undefined ? a : sjcl.bitArray.clamp(a, c - b); +}, extract: function(a, b, c) { + var d = Math.floor(-b - c & 31); + return ((b + c - 1 ^ b) & -32 ? a[b / 32 | 0] << 32 - d ^ a[b / 32 + 1 | 0] >>> d : a[b / 32 | 0] >>> d) & (1 << c) - 1; +}, concat: function(a, b) { + if (a.length === 0 || b.length === 0) + return a.concat(b); + var c = a[a.length - 1], d = sjcl.bitArray.getPartial(c); + return d === 32 ? a.concat(b) : sjcl.bitArray.$(b, d, c | 0, a.slice(0, a.length - 1)); +}, bitLength: function(a) { + var b = a.length; + return b === 0 ? 0 : 32 * (b - 1) + sjcl.bitArray.getPartial(a[b - 1]); +}, clamp: function(a, b) { + if (32 * a.length < b) + return a; + a = a.slice(0, Math.ceil(b / 32)); + var c = a.length; + b = b & 31; + 0 < c && b && (a[c - 1] = sjcl.bitArray.partial(b, a[c - 1] & 2147483648 >> b - 1, 1)); + return a; +}, partial: function(a, b, c) { + return a === 32 ? b : (c ? b | 0 : b << 32 - a) + 1099511627776 * a; +}, getPartial: function(a) { + return Math.round(a / 1099511627776) || 32; +}, equal: function(a, b) { + if (sjcl.bitArray.bitLength(a) !== sjcl.bitArray.bitLength(b)) + return false; + var c = 0, d; + for (d = 0;d < a.length; d++) + c |= a[d] ^ b[d]; + return c === 0; +}, $: function(a, b, c, d) { + var e; + e = 0; + for (d === undefined && (d = []);32 <= b; b -= 32) + d.push(c), c = 0; + if (b === 0) + return d.concat(a); + for (e = 0;e < a.length; e++) + d.push(c | a[e] >>> b), c = a[e] << 32 - b; + e = a.length ? a[a.length - 1] : 0; + a = sjcl.bitArray.getPartial(e); + d.push(sjcl.bitArray.partial(b + a & 31, 32 < b + a ? c : d.pop(), 1)); + return d; +}, i: function(a, b) { + return [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2], a[3] ^ b[3]]; +}, byteswapM: function(a) { + var b, c; + for (b = 0;b < a.length; ++b) + c = a[b], a[b] = c >>> 24 | c >>> 8 & 65280 | (c & 65280) << 8 | c << 24; + return a; +} }; +sjcl.codec.utf8String = { fromBits: function(a) { + var b = "", c = sjcl.bitArray.bitLength(a), d, e; + for (d = 0;d < c / 8; d++) + (d & 3) === 0 && (e = a[d / 4]), b += String.fromCharCode(e >>> 8 >>> 8 >>> 8), e <<= 8; + return decodeURIComponent(escape(b)); +}, toBits: function(a) { + a = unescape(encodeURIComponent(a)); + var b = [], c, d = 0; + for (c = 0;c < a.length; c++) + d = d << 8 | a.charCodeAt(c), (c & 3) === 3 && (b.push(d), d = 0); + c & 3 && b.push(sjcl.bitArray.partial(8 * (c & 3), d)); + return b; +} }; +sjcl.codec.hex = { fromBits: function(a) { + var b = "", c; + for (c = 0;c < a.length; c++) + b += ((a[c] | 0) + 263882790666240).toString(16).substr(4); + return b.substr(0, sjcl.bitArray.bitLength(a) / 4); +}, toBits: function(a) { + var b, c = [], d; + a = a.replace(/\s|0x/g, ""); + d = a.length; + a = a + "00000000"; + for (b = 0;b < a.length; b += 8) + c.push(parseInt(a.substr(b, 8), 16) ^ 0); + return sjcl.bitArray.clamp(c, 4 * d); +} }; +sjcl.codec.base32 = { B: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", X: "0123456789ABCDEFGHIJKLMNOPQRSTUV", BITS: 32, BASE: 5, REMAINING: 27, fromBits: function(a, b, c) { + var d = sjcl.codec.base32.BASE, e = sjcl.codec.base32.REMAINING, f = "", g = 0, h = sjcl.codec.base32.B, k2 = 0, l = sjcl.bitArray.bitLength(a); + c && (h = sjcl.codec.base32.X); + for (c = 0;f.length * d < l; ) + f += h.charAt((k2 ^ a[c] >>> g) >>> e), g < d ? (k2 = a[c] << d - g, g += e, c++) : (k2 <<= d, g -= d); + for (;f.length & 7 && !b; ) + f += "="; + return f; +}, toBits: function(a, b) { + a = a.replace(/\s|=/g, "").toUpperCase(); + var c = sjcl.codec.base32.BITS, d = sjcl.codec.base32.BASE, e = sjcl.codec.base32.REMAINING, f = [], g, h = 0, k2 = sjcl.codec.base32.B, l = 0, n, m = "base32"; + b && (k2 = sjcl.codec.base32.X, m = "base32hex"); + for (g = 0;g < a.length; g++) { + n = k2.indexOf(a.charAt(g)); + if (0 > n) { + if (!b) + try { + return sjcl.codec.base32hex.toBits(a); + } catch (p) { + } + throw new sjcl.exception.invalid("this isn't " + m + "!"); + } + h > e ? (h -= e, f.push(l ^ n >>> h), l = n << c - h) : (h += d, l ^= n << c - h); + } + h & 56 && f.push(sjcl.bitArray.partial(h & 56, l, 1)); + return f; +} }; +sjcl.codec.base32hex = { fromBits: function(a, b) { + return sjcl.codec.base32.fromBits(a, b, 1); +}, toBits: function(a) { + return sjcl.codec.base32.toBits(a, 1); +} }; +sjcl.codec.base64 = { B: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", fromBits: function(a, b, c) { + var d = "", e = 0, f = sjcl.codec.base64.B, g = 0, h = sjcl.bitArray.bitLength(a); + c && (f = f.substr(0, 62) + "-_"); + for (c = 0;6 * d.length < h; ) + d += f.charAt((g ^ a[c] >>> e) >>> 26), 6 > e ? (g = a[c] << 6 - e, e += 26, c++) : (g <<= 6, e -= 6); + for (;d.length & 3 && !b; ) + d += "="; + return d; +}, toBits: function(a, b) { + a = a.replace(/\s|=/g, ""); + var c = [], d, e = 0, f = sjcl.codec.base64.B, g = 0, h; + b && (f = f.substr(0, 62) + "-_"); + for (d = 0;d < a.length; d++) { + h = f.indexOf(a.charAt(d)); + if (0 > h) + throw new sjcl.exception.invalid("this isn't base64!"); + 26 < e ? (e -= 26, c.push(g ^ h >>> e), g = h << 32 - e) : (e += 6, g ^= h << 32 - e); + } + e & 56 && c.push(sjcl.bitArray.partial(e & 56, g, 1)); + return c; +} }; +sjcl.codec.base64url = { fromBits: function(a) { + return sjcl.codec.base64.fromBits(a, 1, 1); +}, toBits: function(a) { + return sjcl.codec.base64.toBits(a, 1); +} }; +sjcl.hash.sha256 = function(a) { + this.b[0] || this.O(); + a ? (this.F = a.F.slice(0), this.A = a.A.slice(0), this.l = a.l) : this.reset(); +}; +sjcl.hash.sha256.hash = function(a) { + return new sjcl.hash.sha256().update(a).finalize(); +}; +sjcl.hash.sha256.prototype = { blockSize: 512, reset: function() { + this.F = this.Y.slice(0); + this.A = []; + this.l = 0; + return this; +}, update: function(a) { + typeof a === "string" && (a = sjcl.codec.utf8String.toBits(a)); + var b, c = this.A = sjcl.bitArray.concat(this.A, a); + b = this.l; + a = this.l = b + sjcl.bitArray.bitLength(a); + if (9007199254740991 < a) + throw new sjcl.exception.invalid("Cannot hash more than 2^53 - 1 bits"); + if (typeof Uint32Array !== "undefined") { + var d = new Uint32Array(c), e = 0; + for (b = 512 + b - (512 + b & 511);b <= a; b += 512) + u(this, d.subarray(16 * e, 16 * (e + 1))), e += 1; + c.splice(0, 16 * e); + } else + for (b = 512 + b - (512 + b & 511);b <= a; b += 512) + u(this, c.splice(0, 16)); + return this; +}, finalize: function() { + var a, b = this.A, c = this.F, b = sjcl.bitArray.concat(b, [sjcl.bitArray.partial(1, 1)]); + for (a = b.length + 2;a & 15; a++) + b.push(0); + b.push(Math.floor(this.l / 4294967296)); + for (b.push(this.l | 0);b.length; ) + u(this, b.splice(0, 16)); + this.reset(); + return c; +}, Y: [], b: [], O: function() { + function a(a2) { + return 4294967296 * (a2 - Math.floor(a2)) | 0; + } + for (var b = 0, c = 2, d, e;64 > b; c++) { + e = true; + for (d = 2;d * d <= c; d++) + if (c % d === 0) { + e = false; + break; + } + e && (8 > b && (this.Y[b] = a(Math.pow(c, 0.5))), this.b[b] = a(Math.pow(c, 1 / 3)), b++); + } +} }; +function u(a, b) { + var c, d, e, f = a.F, g = a.b, h = f[0], k2 = f[1], l = f[2], n = f[3], m = f[4], p = f[5], r = f[6], q = f[7]; + for (c = 0;64 > c; c++) + 16 > c ? d = b[c] : (d = b[c + 1 & 15], e = b[c + 14 & 15], d = b[c & 15] = (d >>> 7 ^ d >>> 18 ^ d >>> 3 ^ d << 25 ^ d << 14) + (e >>> 17 ^ e >>> 19 ^ e >>> 10 ^ e << 15 ^ e << 13) + b[c & 15] + b[c + 9 & 15] | 0), d = d + q + (m >>> 6 ^ m >>> 11 ^ m >>> 25 ^ m << 26 ^ m << 21 ^ m << 7) + (r ^ m & (p ^ r)) + g[c], q = r, r = p, p = m, m = n + d | 0, n = l, l = k2, k2 = h, h = d + (k2 & l ^ n & (k2 ^ l)) + (k2 >>> 2 ^ k2 >>> 13 ^ k2 >>> 22 ^ k2 << 30 ^ k2 << 19 ^ k2 << 10) | 0; + f[0] = f[0] + h | 0; + f[1] = f[1] + k2 | 0; + f[2] = f[2] + l | 0; + f[3] = f[3] + n | 0; + f[4] = f[4] + m | 0; + f[5] = f[5] + p | 0; + f[6] = f[6] + r | 0; + f[7] = f[7] + q | 0; +} +sjcl.mode.ccm = { name: "ccm", G: [], listenProgress: function(a) { + sjcl.mode.ccm.G.push(a); +}, unListenProgress: function(a) { + a = sjcl.mode.ccm.G.indexOf(a); + -1 < a && sjcl.mode.ccm.G.splice(a, 1); +}, fa: function(a) { + var b = sjcl.mode.ccm.G.slice(), c; + for (c = 0;c < b.length; c += 1) + b[c](a); +}, encrypt: function(a, b, c, d, e) { + var f, g = b.slice(0), h = sjcl.bitArray, k2 = h.bitLength(c) / 8, l = h.bitLength(g) / 8; + e = e || 64; + d = d || []; + if (7 > k2) + throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes"); + for (f = 2;4 > f && l >>> 8 * f; f++) + ; + f < 15 - k2 && (f = 15 - k2); + c = h.clamp(c, 8 * (15 - f)); + b = sjcl.mode.ccm.V(a, b, c, d, e, f); + g = sjcl.mode.ccm.C(a, g, c, b, e, f); + return h.concat(g.data, g.tag); +}, decrypt: function(a, b, c, d, e) { + e = e || 64; + d = d || []; + var f = sjcl.bitArray, g = f.bitLength(c) / 8, h = f.bitLength(b), k2 = f.clamp(b, h - e), l = f.bitSlice(b, h - e), h = (h - e) / 8; + if (7 > g) + throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes"); + for (b = 2;4 > b && h >>> 8 * b; b++) + ; + b < 15 - g && (b = 15 - g); + c = f.clamp(c, 8 * (15 - b)); + k2 = sjcl.mode.ccm.C(a, k2, c, l, e, b); + a = sjcl.mode.ccm.V(a, k2.data, c, d, e, b); + if (!f.equal(k2.tag, a)) + throw new sjcl.exception.corrupt("ccm: tag doesn't match"); + return k2.data; +}, na: function(a, b, c, d, e, f) { + var g = [], h = sjcl.bitArray, k2 = h.i; + d = [h.partial(8, (b.length ? 64 : 0) | d - 2 << 2 | f - 1)]; + d = h.concat(d, c); + d[3] |= e; + d = a.encrypt(d); + if (b.length) + for (c = h.bitLength(b) / 8, 65279 >= c ? g = [h.partial(16, c)] : 4294967295 >= c && (g = h.concat([h.partial(16, 65534)], [c])), g = h.concat(g, b), b = 0;b < g.length; b += 4) + d = a.encrypt(k2(d, g.slice(b, b + 4).concat([0, 0, 0]))); + return d; +}, V: function(a, b, c, d, e, f) { + var g = sjcl.bitArray, h = g.i; + e /= 8; + if (e % 2 || 4 > e || 16 < e) + throw new sjcl.exception.invalid("ccm: invalid tag length"); + if (4294967295 < d.length || 4294967295 < b.length) + throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data"); + c = sjcl.mode.ccm.na(a, d, c, e, g.bitLength(b) / 8, f); + for (d = 0;d < b.length; d += 4) + c = a.encrypt(h(c, b.slice(d, d + 4).concat([0, 0, 0]))); + return g.clamp(c, 8 * e); +}, C: function(a, b, c, d, e, f) { + var g, h = sjcl.bitArray; + g = h.i; + var k2 = b.length, l = h.bitLength(b), n = k2 / 50, m = n; + c = h.concat([h.partial(8, f - 1)], c).concat([0, 0, 0]).slice(0, 4); + d = h.bitSlice(g(d, a.encrypt(c)), 0, e); + if (!k2) + return { tag: d, data: [] }; + for (g = 0;g < k2; g += 4) + g > n && (sjcl.mode.ccm.fa(g / k2), n += m), c[3]++, e = a.encrypt(c), b[g] ^= e[0], b[g + 1] ^= e[1], b[g + 2] ^= e[2], b[g + 3] ^= e[3]; + return { tag: d, data: h.clamp(b, l) }; +} }; +sjcl.mode.ocb2 = { name: "ocb2", encrypt: function(a, b, c, d, e, f) { + if (sjcl.bitArray.bitLength(c) !== 128) + throw new sjcl.exception.invalid("ocb iv must be 128 bits"); + var g, h = sjcl.mode.ocb2.S, k2 = sjcl.bitArray, l = k2.i, n = [0, 0, 0, 0]; + c = h(a.encrypt(c)); + var m, p = []; + d = d || []; + e = e || 64; + for (g = 0;g + 4 < b.length; g += 4) + m = b.slice(g, g + 4), n = l(n, m), p = p.concat(l(c, a.encrypt(l(c, m)))), c = h(c); + m = b.slice(g); + b = k2.bitLength(m); + g = a.encrypt(l(c, [0, 0, 0, b])); + m = k2.clamp(l(m.concat([0, 0, 0]), g), b); + n = l(n, l(m.concat([0, 0, 0]), g)); + n = a.encrypt(l(n, l(c, h(c)))); + d.length && (n = l(n, f ? d : sjcl.mode.ocb2.pmac(a, d))); + return p.concat(k2.concat(m, k2.clamp(n, e))); +}, decrypt: function(a, b, c, d, e, f) { + if (sjcl.bitArray.bitLength(c) !== 128) + throw new sjcl.exception.invalid("ocb iv must be 128 bits"); + e = e || 64; + var g = sjcl.mode.ocb2.S, h = sjcl.bitArray, k2 = h.i, l = [0, 0, 0, 0], n = g(a.encrypt(c)), m, p, r = sjcl.bitArray.bitLength(b) - e, q = []; + d = d || []; + for (c = 0;c + 4 < r / 32; c += 4) + m = k2(n, a.decrypt(k2(n, b.slice(c, c + 4)))), l = k2(l, m), q = q.concat(m), n = g(n); + p = r - 32 * c; + m = a.encrypt(k2(n, [0, 0, 0, p])); + m = k2(m, h.clamp(b.slice(c), p).concat([ + 0, + 0, + 0 + ])); + l = k2(l, m); + l = a.encrypt(k2(l, k2(n, g(n)))); + d.length && (l = k2(l, f ? d : sjcl.mode.ocb2.pmac(a, d))); + if (!h.equal(h.clamp(l, e), h.bitSlice(b, r))) + throw new sjcl.exception.corrupt("ocb: tag doesn't match"); + return q.concat(h.clamp(m, p)); +}, pmac: function(a, b) { + var c, d = sjcl.mode.ocb2.S, e = sjcl.bitArray, f = e.i, g = [0, 0, 0, 0], h = a.encrypt([0, 0, 0, 0]), h = f(h, d(d(h))); + for (c = 0;c + 4 < b.length; c += 4) + h = d(h), g = f(g, a.encrypt(f(h, b.slice(c, c + 4)))); + c = b.slice(c); + 128 > e.bitLength(c) && (h = f(h, d(h)), c = e.concat(c, [-2147483648, 0, 0, 0])); + g = f(g, c); + return a.encrypt(f(d(f(h, d(h))), g)); +}, S: function(a) { + return [a[0] << 1 ^ a[1] >>> 31, a[1] << 1 ^ a[2] >>> 31, a[2] << 1 ^ a[3] >>> 31, a[3] << 1 ^ 135 * (a[0] >>> 31)]; +} }; +sjcl.mode.gcm = { name: "gcm", encrypt: function(a, b, c, d, e) { + var f = b.slice(0); + b = sjcl.bitArray; + d = d || []; + a = sjcl.mode.gcm.C(true, a, f, d, c, e || 128); + return b.concat(a.data, a.tag); +}, decrypt: function(a, b, c, d, e) { + var f = b.slice(0), g = sjcl.bitArray, h = g.bitLength(f); + e = e || 128; + d = d || []; + e <= h ? (b = g.bitSlice(f, h - e), f = g.bitSlice(f, 0, h - e)) : (b = f, f = []); + a = sjcl.mode.gcm.C(false, a, f, d, c, e); + if (!g.equal(a.tag, b)) + throw new sjcl.exception.corrupt("gcm: tag doesn't match"); + return a.data; +}, ka: function(a, b) { + var c, d, e, f, g, h = sjcl.bitArray.i; + e = [ + 0, + 0, + 0, + 0 + ]; + f = b.slice(0); + for (c = 0;128 > c; c++) { + (d = (a[Math.floor(c / 32)] & 1 << 31 - c % 32) !== 0) && (e = h(e, f)); + g = (f[3] & 1) !== 0; + for (d = 3;0 < d; d--) + f[d] = f[d] >>> 1 | (f[d - 1] & 1) << 31; + f[0] >>>= 1; + g && (f[0] ^= -520093696); + } + return e; +}, j: function(a, b, c) { + var d, e = c.length; + b = b.slice(0); + for (d = 0;d < e; d += 4) + b[0] ^= 4294967295 & c[d], b[1] ^= 4294967295 & c[d + 1], b[2] ^= 4294967295 & c[d + 2], b[3] ^= 4294967295 & c[d + 3], b = sjcl.mode.gcm.ka(b, a); + return b; +}, C: function(a, b, c, d, e, f) { + var g, h, k2, l, n, m, p, r, q = sjcl.bitArray; + m = c.length; + p = q.bitLength(c); + r = q.bitLength(d); + h = q.bitLength(e); + g = b.encrypt([0, 0, 0, 0]); + h === 96 ? (e = e.slice(0), e = q.concat(e, [1])) : (e = sjcl.mode.gcm.j(g, [0, 0, 0, 0], e), e = sjcl.mode.gcm.j(g, e, [0, 0, Math.floor(h / 4294967296), h & 4294967295])); + h = sjcl.mode.gcm.j(g, [0, 0, 0, 0], d); + n = e.slice(0); + d = h.slice(0); + a || (d = sjcl.mode.gcm.j(g, h, c)); + for (l = 0;l < m; l += 4) + n[3]++, k2 = b.encrypt(n), c[l] ^= k2[0], c[l + 1] ^= k2[1], c[l + 2] ^= k2[2], c[l + 3] ^= k2[3]; + c = q.clamp(c, p); + a && (d = sjcl.mode.gcm.j(g, h, c)); + a = [Math.floor(r / 4294967296), r & 4294967295, Math.floor(p / 4294967296), p & 4294967295]; + d = sjcl.mode.gcm.j(g, d, a); + k2 = b.encrypt(e); + d[0] ^= k2[0]; + d[1] ^= k2[1]; + d[2] ^= k2[2]; + d[3] ^= k2[3]; + return { tag: q.bitSlice(d, 0, f), data: c }; +} }; +sjcl.misc.hmac = function(a, b) { + this.W = b = b || sjcl.hash.sha256; + var c = [[], []], d, e = b.prototype.blockSize / 32; + this.w = [new b, new b]; + a.length > e && (a = b.hash(a)); + for (d = 0;d < e; d++) + c[0][d] = a[d] ^ 909522486, c[1][d] = a[d] ^ 1549556828; + this.w[0].update(c[0]); + this.w[1].update(c[1]); + this.R = new b(this.w[0]); +}; +sjcl.misc.hmac.prototype.encrypt = sjcl.misc.hmac.prototype.mac = function(a) { + if (this.aa) + throw new sjcl.exception.invalid("encrypt on already updated hmac called!"); + this.update(a); + return this.digest(a); +}; +sjcl.misc.hmac.prototype.reset = function() { + this.R = new this.W(this.w[0]); + this.aa = false; +}; +sjcl.misc.hmac.prototype.update = function(a) { + this.aa = true; + this.R.update(a); +}; +sjcl.misc.hmac.prototype.digest = function() { + var a = this.R.finalize(), a = new this.W(this.w[1]).update(a).finalize(); + this.reset(); + return a; +}; +sjcl.misc.pbkdf2 = function(a, b, c, d, e) { + c = c || 1e4; + if (0 > d || 0 > c) + throw new sjcl.exception.invalid("invalid params to pbkdf2"); + typeof a === "string" && (a = sjcl.codec.utf8String.toBits(a)); + typeof b === "string" && (b = sjcl.codec.utf8String.toBits(b)); + e = e || sjcl.misc.hmac; + a = new e(a); + var f, g, h, k2, l = [], n = sjcl.bitArray; + for (k2 = 1;32 * l.length < (d || 1); k2++) { + e = f = a.encrypt(n.concat(b, [k2])); + for (g = 1;g < c; g++) + for (f = a.encrypt(f), h = 0;h < f.length; h++) + e[h] ^= f[h]; + l = l.concat(e); + } + d && (l = n.clamp(l, d)); + return l; +}; +sjcl.prng = function(a) { + this.c = [new sjcl.hash.sha256]; + this.m = [0]; + this.P = 0; + this.H = {}; + this.N = 0; + this.U = {}; + this.Z = this.f = this.o = this.ha = 0; + this.b = [0, 0, 0, 0, 0, 0, 0, 0]; + this.h = [0, 0, 0, 0]; + this.L = undefined; + this.M = a; + this.D = false; + this.K = { progress: {}, seeded: {} }; + this.u = this.ga = 0; + this.I = 1; + this.J = 2; + this.ca = 65536; + this.T = [0, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024]; + this.da = 30000; + this.ba = 80; +}; +sjcl.prng.prototype = { + randomWords: function(a, b) { + var c = [], d; + d = this.isReady(b); + var e; + if (d === this.u) + throw new sjcl.exception.notReady("generator isn't seeded"); + if (d & this.J) { + d = !(d & this.I); + e = []; + var f = 0, g; + this.Z = e[0] = new Date().valueOf() + this.da; + for (g = 0;16 > g; g++) + e.push(4294967296 * Math.random() | 0); + for (g = 0;g < this.c.length && (e = e.concat(this.c[g].finalize()), f += this.m[g], this.m[g] = 0, d || !(this.P & 1 << g)); g++) + ; + this.P >= 1 << this.c.length && (this.c.push(new sjcl.hash.sha256), this.m.push(0)); + this.f -= f; + f > this.o && (this.o = f); + this.P++; + this.b = sjcl.hash.sha256.hash(this.b.concat(e)); + this.L = new sjcl.cipher.aes(this.b); + for (d = 0;4 > d && (this.h[d] = this.h[d] + 1 | 0, !this.h[d]); d++) + ; + } + for (d = 0;d < a; d += 4) + (d + 1) % this.ca === 0 && y(this), e = z(this), c.push(e[0], e[1], e[2], e[3]); + y(this); + return c.slice(0, a); + }, + setDefaultParanoia: function(a, b) { + if (a === 0 && b !== "Setting paranoia=0 will ruin your security; use it only for testing") + throw new sjcl.exception.invalid("Setting paranoia=0 will ruin your security; use it only for testing"); + this.M = a; + }, + addEntropy: function(a, b, c) { + c = c || "user"; + var d, e, f = new Date().valueOf(), g = this.H[c], h = this.isReady(), k2 = 0; + d = this.U[c]; + d === undefined && (d = this.U[c] = this.ha++); + g === undefined && (g = this.H[c] = 0); + this.H[c] = (this.H[c] + 1) % this.c.length; + switch (typeof a) { + case "number": + b === undefined && (b = 1); + this.c[g].update([d, this.N++, 1, b, f, 1, a | 0]); + break; + case "object": + c = Object.prototype.toString.call(a); + if (c === "[object Uint32Array]") { + e = []; + for (c = 0;c < a.length; c++) + e.push(a[c]); + a = e; + } else + for (c !== "[object Array]" && (k2 = 1), c = 0;c < a.length && !k2; c++) + typeof a[c] !== "number" && (k2 = 1); + if (!k2) { + if (b === undefined) + for (c = b = 0;c < a.length; c++) + for (e = a[c];0 < e; ) + b++, e = e >>> 1; + this.c[g].update([d, this.N++, 2, b, f, a.length].concat(a)); + } + break; + case "string": + b === undefined && (b = a.length); + this.c[g].update([d, this.N++, 3, b, f, a.length]); + this.c[g].update(a); + break; + default: + k2 = 1; + } + if (k2) + throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string"); + this.m[g] += b; + this.f += b; + h === this.u && (this.isReady() !== this.u && A("seeded", Math.max(this.o, this.f)), A("progress", this.getProgress())); + }, + isReady: function(a) { + a = this.T[a !== undefined ? a : this.M]; + return this.o && this.o >= a ? this.m[0] > this.ba && new Date().valueOf() > this.Z ? this.J | this.I : this.I : this.f >= a ? this.J | this.u : this.u; + }, + getProgress: function(a) { + a = this.T[a ? a : this.M]; + return this.o >= a ? 1 : this.f > a ? 1 : this.f / a; + }, + startCollectors: function() { + if (!this.D) { + this.a = { loadTimeCollector: B(this, this.ma), mouseCollector: B(this, this.oa), keyboardCollector: B(this, this.la), accelerometerCollector: B(this, this.ea), touchCollector: B(this, this.qa) }; + if (window.addEventListener) + window.addEventListener("load", this.a.loadTimeCollector, false), window.addEventListener("mousemove", this.a.mouseCollector, false), window.addEventListener("keypress", this.a.keyboardCollector, false), window.addEventListener("devicemotion", this.a.accelerometerCollector, false), window.addEventListener("touchmove", this.a.touchCollector, false); + else if (document.attachEvent) + document.attachEvent("onload", this.a.loadTimeCollector), document.attachEvent("onmousemove", this.a.mouseCollector), document.attachEvent("keypress", this.a.keyboardCollector); + else + throw new sjcl.exception.bug("can't attach event"); + this.D = true; + } + }, + stopCollectors: function() { + this.D && (window.removeEventListener ? (window.removeEventListener("load", this.a.loadTimeCollector, false), window.removeEventListener("mousemove", this.a.mouseCollector, false), window.removeEventListener("keypress", this.a.keyboardCollector, false), window.removeEventListener("devicemotion", this.a.accelerometerCollector, false), window.removeEventListener("touchmove", this.a.touchCollector, false)) : document.detachEvent && (document.detachEvent("onload", this.a.loadTimeCollector), document.detachEvent("onmousemove", this.a.mouseCollector), document.detachEvent("keypress", this.a.keyboardCollector)), this.D = false); + }, + addEventListener: function(a, b) { + this.K[a][this.ga++] = b; + }, + removeEventListener: function(a, b) { + var c, d, e = this.K[a], f = []; + for (d in e) + e.hasOwnProperty(d) && e[d] === b && f.push(d); + for (c = 0;c < f.length; c++) + d = f[c], delete e[d]; + }, + la: function() { + C2(this, 1); + }, + oa: function(a) { + var b, c; + try { + b = a.x || a.clientX || a.offsetX || 0, c = a.y || a.clientY || a.offsetY || 0; + } catch (d) { + c = b = 0; + } + b != 0 && c != 0 && this.addEntropy([b, c], 2, "mouse"); + C2(this, 0); + }, + qa: function(a) { + a = a.touches[0] || a.changedTouches[0]; + this.addEntropy([a.pageX || a.clientX, a.pageY || a.clientY], 1, "touch"); + C2(this, 0); + }, + ma: function() { + C2(this, 2); + }, + ea: function(a) { + a = a.accelerationIncludingGravity.x || a.accelerationIncludingGravity.y || a.accelerationIncludingGravity.z; + if (window.orientation) { + var b = window.orientation; + typeof b === "number" && this.addEntropy(b, 1, "accelerometer"); + } + a && this.addEntropy(a, 2, "accelerometer"); + C2(this, 0); + } +}; +function A(a, b) { + var c, d = sjcl.random.K[a], e = []; + for (c in d) + d.hasOwnProperty(c) && e.push(d[c]); + for (c = 0;c < e.length; c++) + e[c](b); +} +function C2(a, b) { + typeof window !== "undefined" && window.performance && typeof window.performance.now === "function" ? a.addEntropy(window.performance.now(), b, "loadtime") : a.addEntropy(new Date().valueOf(), b, "loadtime"); +} +function y(a) { + a.b = z(a).concat(z(a)); + a.L = new sjcl.cipher.aes(a.b); +} +function z(a) { + for (var b = 0;4 > b && (a.h[b] = a.h[b] + 1 | 0, !a.h[b]); b++) + ; + return a.L.encrypt(a.h); +} +function B(a, b) { + return function() { + b.apply(a, arguments); + }; +} +sjcl.random = new sjcl.prng(6); +a: + try { + if (G = typeof module_sjcl_min !== "undefined" && exports_sjcl_min) { + try { + H = (init_crypto(), __toCommonJS(exports_crypto)); + } catch (a) { + H = null; + } + G = E2 = H; + } + if (G && E2.randomBytes) + D = E2.randomBytes(128), D = new Uint32Array(new Uint8Array(D).buffer), sjcl.random.addEntropy(D, 1024, "crypto['randomBytes']"); + else if (typeof window !== "undefined" && typeof Uint32Array !== "undefined") { + F = new Uint32Array(32); + if (window.crypto && window.crypto.getRandomValues) + window.crypto.getRandomValues(F); + else if (window.msCrypto && window.msCrypto.getRandomValues) + window.msCrypto.getRandomValues(F); + else + break a; + sjcl.random.addEntropy(F, 1024, "crypto['getRandomValues']"); + } + } catch (a) { + typeof window !== "undefined" && window.console && (console.log("There was an error collecting entropy from the browser:"), console.log(a)); + } +var D; +var E2; +var F; +var G; +var H; +sjcl.json = { defaults: { v: 1, iter: 1e4, ks: 128, ts: 64, mode: "ccm", adata: "", cipher: "aes" }, ja: function(a, b, c, d) { + c = c || {}; + d = d || {}; + var e = sjcl.json, f = e.g({ iv: sjcl.random.randomWords(4, 0) }, e.defaults), g; + e.g(f, c); + c = f.adata; + typeof f.salt === "string" && (f.salt = sjcl.codec.base64.toBits(f.salt)); + typeof f.iv === "string" && (f.iv = sjcl.codec.base64.toBits(f.iv)); + if (!sjcl.mode[f.mode] || !sjcl.cipher[f.cipher] || typeof a === "string" && 100 >= f.iter || f.ts !== 64 && f.ts !== 96 && f.ts !== 128 || f.ks !== 128 && f.ks !== 192 && f.ks !== 256 || 2 > f.iv.length || 4 < f.iv.length) + throw new sjcl.exception.invalid("json encrypt: invalid parameters"); + typeof a === "string" ? (g = sjcl.misc.cachedPbkdf2(a, f), a = g.key.slice(0, f.ks / 32), f.salt = g.salt) : sjcl.ecc && a instanceof sjcl.ecc.elGamal.publicKey && (g = a.kem(), f.kemtag = g.tag, a = g.key.slice(0, f.ks / 32)); + typeof b === "string" && (b = sjcl.codec.utf8String.toBits(b)); + typeof c === "string" && (f.adata = c = sjcl.codec.utf8String.toBits(c)); + g = new sjcl.cipher[f.cipher](a); + e.g(d, f); + d.key = a; + f.ct = f.mode === "ccm" && sjcl.arrayBuffer && sjcl.arrayBuffer.ccm && b instanceof ArrayBuffer ? sjcl.arrayBuffer.ccm.encrypt(g, b, f.iv, c, f.ts) : sjcl.mode[f.mode].encrypt(g, b, f.iv, c, f.ts); + return f; +}, encrypt: function(a, b, c, d) { + var e = sjcl.json, f = e.ja.apply(e, arguments); + return e.encode(f); +}, ia: function(a, b, c, d) { + c = c || {}; + d = d || {}; + var e = sjcl.json; + b = e.g(e.g(e.g({}, e.defaults), b), c, true); + var f, g; + f = b.adata; + typeof b.salt === "string" && (b.salt = sjcl.codec.base64.toBits(b.salt)); + typeof b.iv === "string" && (b.iv = sjcl.codec.base64.toBits(b.iv)); + if (!sjcl.mode[b.mode] || !sjcl.cipher[b.cipher] || typeof a === "string" && 100 >= b.iter || b.ts !== 64 && b.ts !== 96 && b.ts !== 128 || b.ks !== 128 && b.ks !== 192 && b.ks !== 256 || !b.iv || 2 > b.iv.length || 4 < b.iv.length) + throw new sjcl.exception.invalid("json decrypt: invalid parameters"); + typeof a === "string" ? (g = sjcl.misc.cachedPbkdf2(a, b), a = g.key.slice(0, b.ks / 32), b.salt = g.salt) : sjcl.ecc && a instanceof sjcl.ecc.elGamal.secretKey && (a = a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0, b.ks / 32)); + typeof f === "string" && (f = sjcl.codec.utf8String.toBits(f)); + g = new sjcl.cipher[b.cipher](a); + f = b.mode === "ccm" && sjcl.arrayBuffer && sjcl.arrayBuffer.ccm && b.ct instanceof ArrayBuffer ? sjcl.arrayBuffer.ccm.decrypt(g, b.ct, b.iv, b.tag, f, b.ts) : sjcl.mode[b.mode].decrypt(g, b.ct, b.iv, f, b.ts); + e.g(d, b); + d.key = a; + return c.raw === 1 ? f : sjcl.codec.utf8String.fromBits(f); +}, decrypt: function(a, b, c, d) { + var e = sjcl.json; + return e.ia(a, e.decode(b), c, d); +}, encode: function(a) { + var b, c = "{", d = ""; + for (b in a) + if (a.hasOwnProperty(b)) { + if (!b.match(/^[a-z0-9]+$/i)) + throw new sjcl.exception.invalid("json encode: invalid property name"); + c += d + '"' + b + '":'; + d = ","; + switch (typeof a[b]) { + case "number": + case "boolean": + c += a[b]; + break; + case "string": + c += '"' + escape(a[b]) + '"'; + break; + case "object": + c += '"' + sjcl.codec.base64.fromBits(a[b], 0) + '"'; + break; + default: + throw new sjcl.exception.bug("json encode: unsupported type"); + } + } + return c + "}"; +}, decode: function(a) { + a = a.replace(/\s/g, ""); + if (!a.match(/^\{.*\}$/)) + throw new sjcl.exception.invalid("json decode: this isn't json!"); + a = a.replace(/^\{|\}$/g, "").split(/,/); + var b = {}, c, d; + for (c = 0;c < a.length; c++) { + if (!(d = a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i))) + throw new sjcl.exception.invalid("json decode: this isn't json!"); + d[3] != null ? b[d[2]] = parseInt(d[3], 10) : d[4] != null ? b[d[2]] = d[2].match(/^(ct|adata|salt|iv)$/) ? sjcl.codec.base64.toBits(d[4]) : unescape(d[4]) : d[5] != null && (b[d[2]] = d[5] === "true"); + } + return b; +}, g: function(a, b, c) { + a === undefined && (a = {}); + if (b === undefined) + return a; + for (var d in b) + if (b.hasOwnProperty(d)) { + if (c && a[d] !== undefined && a[d] !== b[d]) + throw new sjcl.exception.invalid("required parameter overridden"); + a[d] = b[d]; + } + return a; +}, sa: function(a, b) { + var c = {}, d; + for (d in a) + a.hasOwnProperty(d) && a[d] !== b[d] && (c[d] = a[d]); + return c; +}, ra: function(a, b) { + var c = {}, d; + for (d = 0;d < b.length; d++) + a[b[d]] !== undefined && (c[b[d]] = a[b[d]]); + return c; +} }; +sjcl.encrypt = sjcl.json.encrypt; +sjcl.decrypt = sjcl.json.decrypt; +sjcl.misc.pa = {}; +sjcl.misc.cachedPbkdf2 = function(a, b) { + var c = sjcl.misc.pa, d; + b = b || {}; + d = b.iter || 1000; + c = c[a] = c[a] || {}; + d = c[d] = c[d] || { firstSalt: b.salt && b.salt.length ? b.salt.slice(0) : sjcl.random.randomWords(2, 0) }; + c = b.salt === undefined ? d.firstSalt : b.salt; + d[c] = d[c] || sjcl.misc.pbkdf2(a, c, b.iter); + return { key: d[c].slice(0), salt: c.slice(0) }; +}; +sjcl.codec.bytes = { + fromBits: function(arr) { + var out = [], bl2 = sjcl.bitArray.bitLength(arr), i, tmp2; + for (i = 0;i < bl2 / 8; i++) { + if ((i & 3) === 0) { + tmp2 = arr[i / 4]; + } + out.push(tmp2 >>> 24); + tmp2 <<= 8; + } + return out; + }, + toBits: function(bytes) { + var out = [], i, tmp2 = 0; + for (i = 0;i < bytes.length; i++) { + tmp2 = tmp2 << 8 | bytes[i]; + if ((i & 3) === 3) { + out.push(tmp2); + tmp2 = 0; + } + } + if (i & 3) { + out.push(sjcl.bitArray.partial(8 * (i & 3), tmp2)); + } + return out; + } +}; +var sjcl_min_default = { + cipher: { + aes: sjcl.cipher.aes + }, + bitArray: { + bitSlice: sjcl.bitArray.bitSlice, + bitLength: sjcl.bitArray.bitLength, + clamp: sjcl.bitArray.clamp + }, + mode: { + ccm: sjcl.mode.ccm + }, + codec: { + bytes: sjcl.codec.bytes, + utf8String: sjcl.codec.utf8String, + hex: sjcl.codec.hex, + base32: sjcl.codec.base32, + base32hex: sjcl.codec.base32hex, + base64: sjcl.codec.base64 + } +}; + +// src/util/EncodeQRCode.ts +var crc16 = function crc162(data2) { + let crc = 0; + let msb = crc >> 8; + let lsb = crc & 255; + for (let i = 0;i < data2.length; i++) { + let c = data2[i]; + let x = c ^ msb; + x ^= x >> 4; + msb = (lsb ^ x >> 3 ^ x << 4) & 255; + lsb = (x ^ x << 5) & 255; + } + crc = (msb << 8) + lsb; + return crc; +}; +var encryptAndEncodeVer3StoreDataToQRCodeFormat = (data2) => { + const nonce = data2.slice(12, 20); + console.log("nonce:", Array.from(nonce).map((s) => s.toString(16)).join("")); + let content2 = [...data2.slice(0, 12), ...data2.slice(20)]; + console.log("content:", content2.map((s) => s.toString(16)).join("")); + const checksumContent = [ + ...data2.slice(0, 12), + ...nonce, + ...data2.slice(20, -2) + ]; + console.log("checksumContent:", checksumContent.map((s) => s.toString(16)).join("")); + const newChecksum = crc16(new Uint8Array(checksumContent)); + console.log("checksum:", newChecksum.toString(16)); + const newChecksumArray = [newChecksum >> 8 & 255, newChecksum & 255]; + content2 = [...content2.slice(0, -2), ...newChecksumArray]; + const cipher = new sjcl_min_default.cipher.aes([ + 1509720446, + 1682369121, + -1875608800, + -373436846 + ]); + const paddedContent = new Uint8Array([...content2, ...new Array(8).fill(0)]); + const paddedContentBits = sjcl_min_default.codec.bytes.toBits(Array.from(paddedContent)); + const nonceBits = sjcl_min_default.codec.bytes.toBits([...nonce, 0, 0, 0, 0]); + const encryptedBits = sjcl_min_default.mode.ccm.encrypt(cipher, paddedContentBits, nonceBits, [], 128); + const encryptedBytes = sjcl_min_default.codec.bytes.fromBits(encryptedBits); + const correctEncryptedContentLength = encryptedBytes.length - 8 - 16; + const encryptedContentCorrected = encryptedBytes.slice(0, correctEncryptedContentLength); + const tag = encryptedBytes.slice(encryptedBytes.length - 16); + const result = [...nonce, ...encryptedContentCorrected, ...tag]; + return result; +}; + +// src/config.ts +var useRendererServer = false; +var fflResourcePath = [ + "/FFLResLow.dat", + "/FFLResMiddle.dat", + "/FFLResHigh.dat" +]; +var fflResourcesNames = ["Low", "Middle", "High"]; +var baseURL = "https://mii-renderer.nxw.pw/miis/image"; +var newApiParams = true; +var nnidFetchOrigin = "https://mii-unsecure.ariankordi.net"; +var __2 = _8(); +var Config = { + renderer: { + baseURL, + useRendererServer, + fflResourcePath, + fflResourcesNames, + renderFFLMakeIcon: `${baseURL}.png?shaderType=miitomo&type=fflmakeicon&width=360&verifyCharInfo=0`, + renderHeadshotURL: `${baseURL}.png?shaderType=wiiu&type=face&width=260&verifyCharInfo=0`, + renderHeadshotURLNoParams: `${baseURL}.png`, + renderFullBodyURL: `${baseURL}.png?shaderType=wiiu&type=all_body_sugar&width=420&verifyCharInfo=0&scale=1`, + renderFullBodyAltURL: `${baseURL}.png?shaderType=wiiu&type=all_body_sugar&width=960&verifyCharInfo=0&scale=1`, + render3DHeadURL: `${baseURL}.glb?shaderType=wiiu&type=face&width=260&verifyCharInfo=0`, + renderFaceURL: `${baseURL}.png?scale=1&drawStageMode=mask_only&verifyCharInfo=0`, + hatTypeParam: newApiParams ? "headwearIndex" : "hatType", + hatTypeAdd: newApiParams ? 0 : 0, + hatColorParam: newApiParams ? "headwearColor" : "hatColor", + hatColorAdd: newApiParams ? -1 : 0, + allow3DMode: true + }, + apis: { + nnidRandomURL: `${nnidFetchOrigin}/mii_data_random`, + nnidFetchURL: (nnid) => `${nnidFetchOrigin}/mii_data/${nnid}`, + pnidFetchURL: (pnid) => `${nnidFetchOrigin}/mii_data/${pnid}?api_id=1`, + useSentry: true, + sentryURL: "https://5671de45addd464980ccd49e08d6d108@app.glitchtip.com/10073" + }, + mii: { + scalingMode: "scaleApply" + }, + version: { + string: "v1.0.0 r1", + name: __2("BETA"), + changelog: ` +

The update changelog hasn't been written yet, so just ignore this for now

+ ` + } +}; + +// src/constants/EditorIcons.ts +var EditorIcons_default = { + loading: ``, + error: ``, + eyes: ``, + eyebrows: ``, + details: ` + + + +`, + save: ``, + scale: ``, + nose: ``, + mouth: ``, + glasses: ``, + mole: ``, + head: ``, + hair: ``, + hat: ``, + clothes: ``, + favoriteColor: ``, + facialHair: ``, + gender: ``, + genderMale: ``, + genderFemale: ``, + genderMaleLg: ``, + genderFemaleLg: ``, + favorite: ``, + special: ``, + personal: ``, + sparkle: ``, + positionMoveDown: ``, + positionMoveUp: ``, + positionPushIn: ``, + positionPushOut: ``, + positionRotateCW: ``, + positionRotateCCW: ``, + positionSizeDown: ``, + positionSizeUp: ``, + positionStretchIn: ``, + positionStretchOut: ``, + positionHairFlip: ``, + positionHairFlipped: ``, + scaleShort: ``, + scaleTall: ``, + scaleThin: ``, + scaleFat: ``, + face: ``, + face_makeup: ``, + face_wrinkles: ``, + face_paint: ``, + color: ``, + contact_discord: ``, + contact_email: ``, + contact_github: `` +}; + +// src/ui/components/Notify.ts +var notifyBox; +var Notify_default = { + show: function(title, description, callback, callbackTitle = "") { + if (notifyBox === undefined) + notifyBox = new Html("div").class("notify-box").appendTo("body"); + let notifyTitle = new Html("div").class("notify-title").text(title); + let notifyDescription = new Html("div").class("notify-text").text(description); + playSound("notice"); + let notify = new Html("div").class("notify", "slideIn").appendMany(notifyTitle, notifyDescription).appendTo(notifyBox); + if (callback) { + notify.append(new Html("button").on("click", callback).text(callbackTitle)); + } + setTimeout(() => { + notify.classOff("slideIn").classOn("slideOut"); + setTimeout(() => { + notify.cleanup(); + }, 500); + }, 5000); + } +}; + +// src/util/ModelLoader.ts +var import_jszip2 = __toESM(require_lib(), 1); +var import_localforage2 = __toESM(require_localforage(), 1); +// node_modules/three/examples/jsm/animation/CCDIKSolver.js +var _q = new Quaternion; +var _targetPos = new Vector3; +var _targetVec = new Vector3; +var _effectorPos = new Vector3; +var _effectorVec = new Vector3; +var _linkPos = new Vector3; +var _invLinkQ = new Quaternion; +var _linkScale = new Vector3; +var _axis2 = new Vector3; +var _vector4 = new Vector3; +var _matrix2 = new Matrix4; +// node_modules/three/examples/jsm/controls/ArcballControls.js +var STATE = { + IDLE: Symbol(), + ROTATE: Symbol(), + PAN: Symbol(), + SCALE: Symbol(), + FOV: Symbol(), + FOCUS: Symbol(), + ZROTATE: Symbol(), + TOUCH_MULTI: Symbol(), + ANIMATION_FOCUS: Symbol(), + ANIMATION_ROTATE: Symbol() +}; +var INPUT = { + NONE: Symbol(), + ONE_FINGER: Symbol(), + ONE_FINGER_SWITCHED: Symbol(), + TWO_FINGER: Symbol(), + MULT_FINGER: Symbol(), + CURSOR: Symbol() +}; +var _transformation = { + camera: new Matrix4, + gizmos: new Matrix4 +}; +var _raycaster = new Raycaster; +var _offset2 = new Vector3; +var _gizmoMatrixStateTemp = new Matrix4; +var _cameraMatrixStateTemp = new Matrix4; +var _scalePointTemp = new Vector3; +// node_modules/three/examples/jsm/controls/DragControls.js +var _plane = new Plane; +var _pointer = new Vector2; +var _offset3 = new Vector3; +var _diff2 = new Vector2; +var _previousPointer = new Vector2; +var _intersection = new Vector3; +var _worldPosition = new Vector3; +var _inverseMatrix2 = new Matrix4; +var _up = new Vector3; +var _right = new Vector3; +// node_modules/three/examples/jsm/controls/FirstPersonControls.js +var _lookDirection = new Vector3; +var _spherical = new Spherical; +var _target2 = new Vector3; +var _targetPosition = new Vector3; +// node_modules/three/examples/jsm/controls/FlyControls.js +var _tmpQuaternion = new Quaternion; +// node_modules/three/examples/jsm/controls/OrbitControls.js +var _ray2 = new Ray; +var _plane2 = new Plane; +var _TILT_LIMIT = Math.cos(70 * MathUtils.DEG2RAD); +var _v = new Vector3; +var _twoPI = 2 * Math.PI; +// node_modules/three/examples/jsm/controls/PointerLockControls.js +var _euler = new Euler(0, 0, 0, "YXZ"); +var _vector6 = new Vector3; +var _PI_2 = Math.PI / 2; +// node_modules/three/examples/jsm/controls/TrackballControls.js +var _v22 = new Vector2; +var _mouseChange = new Vector2; +var _objectUp = new Vector3; +var _pan = new Vector3; +var _axis3 = new Vector3; +var _quaternion2 = new Quaternion; +var _eyeDirection = new Vector3; +var _objectUpDirection = new Vector3; +var _objectSidewaysDirection = new Vector3; +var _moveDirection = new Vector3; +// node_modules/three/examples/jsm/controls/TransformControls.js +var _raycaster2 = new Raycaster; +var _tempVector = new Vector3; +var _tempVector2 = new Vector3; +var _tempQuaternion = new Quaternion; +var _unit = { + X: new Vector3(1, 0, 0), + Y: new Vector3(0, 1, 0), + Z: new Vector3(0, 0, 1) +}; +var _tempEuler = new Euler; +var _alignVector = new Vector3(0, 1, 0); +var _zeroVector = new Vector3(0, 0, 0); +var _lookAtMatrix = new Matrix4; +var _tempQuaternion2 = new Quaternion; +var _identityQuaternion = new Quaternion; +var _dirVector = new Vector3; +var _tempMatrix = new Matrix4; +var _unitX = new Vector3(1, 0, 0); +var _unitY = new Vector3(0, 1, 0); +var _unitZ = new Vector3(0, 0, 1); +var _v12 = new Vector3; +var _v23 = new Vector3; +var _v32 = new Vector3; +// node_modules/three/examples/jsm/csm/CSMFrustum.js +var inverseProjectionMatrix = new Matrix4; + +class CSMFrustum { + constructor(data2) { + data2 = data2 || {}; + this.zNear = data2.webGL === true ? -1 : 0; + this.vertices = { + near: [ + new Vector3, + new Vector3, + new Vector3, + new Vector3 + ], + far: [ + new Vector3, + new Vector3, + new Vector3, + new Vector3 + ] + }; + if (data2.projectionMatrix !== undefined) { + this.setFromProjectionMatrix(data2.projectionMatrix, data2.maxFar || 1e4); + } + } + setFromProjectionMatrix(projectionMatrix, maxFar) { + const zNear = this.zNear; + const isOrthographic = projectionMatrix.elements[2 * 4 + 3] === 0; + inverseProjectionMatrix.copy(projectionMatrix).invert(); + this.vertices.near[0].set(1, 1, zNear); + this.vertices.near[1].set(1, -1, zNear); + this.vertices.near[2].set(-1, -1, zNear); + this.vertices.near[3].set(-1, 1, zNear); + this.vertices.near.forEach(function(v) { + v.applyMatrix4(inverseProjectionMatrix); + }); + this.vertices.far[0].set(1, 1, 1); + this.vertices.far[1].set(1, -1, 1); + this.vertices.far[2].set(-1, -1, 1); + this.vertices.far[3].set(-1, 1, 1); + this.vertices.far.forEach(function(v) { + v.applyMatrix4(inverseProjectionMatrix); + const absZ = Math.abs(v.z); + if (isOrthographic) { + v.z *= Math.min(maxFar / absZ, 1); + } else { + v.multiplyScalar(Math.min(maxFar / absZ, 1)); + } + }); + return this.vertices; + } + split(breaks, target) { + while (breaks.length > target.length) { + target.push(new CSMFrustum); + } + target.length = breaks.length; + for (let i = 0;i < breaks.length; i++) { + const cascade = target[i]; + if (i === 0) { + for (let j = 0;j < 4; j++) { + cascade.vertices.near[j].copy(this.vertices.near[j]); + } + } else { + for (let j = 0;j < 4; j++) { + cascade.vertices.near[j].lerpVectors(this.vertices.near[j], this.vertices.far[j], breaks[i - 1]); + } + } + if (i === breaks.length - 1) { + for (let j = 0;j < 4; j++) { + cascade.vertices.far[j].copy(this.vertices.far[j]); + } + } else { + for (let j = 0;j < 4; j++) { + cascade.vertices.far[j].lerpVectors(this.vertices.near[j], this.vertices.far[j], breaks[i]); + } + } + } + } + toSpace(cameraMatrix, target) { + for (let i = 0;i < 4; i++) { + target.vertices.near[i].copy(this.vertices.near[i]).applyMatrix4(cameraMatrix); + target.vertices.far[i].copy(this.vertices.far[i]).applyMatrix4(cameraMatrix); + } + } +} + +// node_modules/three/examples/jsm/csm/CSMShader.js +var CSMShader = { + lights_fragment_begin: ` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); + +vec3 geometryClearcoatNormal = vec3( 0.0 ); + +#ifdef USE_CLEARCOAT + + geometryClearcoatNormal = clearcoatNormal; + +#endif + +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + // Iridescence F0 approximation + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif + +IncidentLight directLight; + +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + + pointLight = pointLights[ i ]; + + getPointLightInfo( pointLight, geometryPosition, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + + spotLight = spotLights[ i ]; + + getSpotLightInfo( spotLight, geometryPosition, directLight ); + + // spot lights are ordered [shadows with maps, shadows without maps, maps without shadows, none] + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + + #endif + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES ) + + DirectionalLight directionalLight; + float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear); + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + + #if defined( USE_SHADOWMAP ) && defined( CSM_FADE ) + vec2 cascade; + float cascadeCenter; + float closestEdge; + float margin; + float csmx; + float csmy; + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + + #if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + // NOTE: Depth gets larger away from the camera. + // cascade.x is closer, cascade.y is further + cascade = CSM_cascades[ i ]; + cascadeCenter = ( cascade.x + cascade.y ) / 2.0; + closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y; + margin = 0.25 * pow( closestEdge, 2.0 ); + csmx = cascade.x - margin / 2.0; + csmy = cascade.y + margin / 2.0; + if( linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) { + + float dist = min( linearDepth - csmx, csmy - linearDepth ); + float ratio = clamp( dist / margin, 0.0, 1.0 ); + + vec3 prevColor = directLight.color; + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + + bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter; + directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 ); + + ReflectedLight prevLight = reflectedLight; + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter; + float blendRatio = shouldBlend ? ratio : 1.0; + + reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio ); + reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio ); + reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio ); + reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio ); + + } + #endif + + } + #pragma unroll_loop_end + #elif defined (USE_SHADOWMAP) + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + + #if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + + directionalLightShadow = directionalLightShadows[ i ]; + if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + + if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + #endif + + } + #pragma unroll_loop_end + + #elif ( NUM_DIR_LIGHT_SHADOWS > 0 ) + // note: no loop here - all CSM lights are in fact one light only + getDirectionalLightInfo( directionalLights[0], directLight ); + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + #endif + + #if ( NUM_DIR_LIGHTS > NUM_DIR_LIGHT_SHADOWS) + // compute the lights not casting shadows (if any) + + #pragma unroll_loop_start + for ( int i = NUM_DIR_LIGHT_SHADOWS; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + + getDirectionalLightInfo( directionalLight, directLight ); + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + + #endif + +#endif + + +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !defined( USE_CSM ) && !defined( CSM_CASCADES ) + + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + + getDirectionalLightInfo( directionalLight, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + + RectAreaLight rectAreaLight; + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if defined( RE_IndirectDiffuse ) + + vec3 iblIrradiance = vec3( 0.0 ); + + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + + #if defined( USE_LIGHT_PROBES ) + + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + + #endif + + #if ( NUM_HEMI_LIGHTS > 0 ) + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + + } + #pragma unroll_loop_end + + #endif + +#endif + +#if defined( RE_IndirectSpecular ) + + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); + +#endif +`, + lights_pars_begin: ` +#if defined( USE_CSM ) && defined( CSM_CASCADES ) +uniform vec2 CSM_cascades[CSM_CASCADES]; +uniform float cameraNear; +uniform float shadowFar; +#endif + ` + ShaderChunk.lights_pars_begin +}; + +// node_modules/three/examples/jsm/csm/CSM.js +var _cameraToLightMatrix = new Matrix4; +var _lightSpaceFrustum = new CSMFrustum({ webGL: true }); +var _center2 = new Vector3; +var _bbox = new Box3; +var _lightOrientationMatrix = new Matrix4; +var _lightOrientationMatrixInverse = new Matrix4; +var _up2 = new Vector3(0, 1, 0); +// node_modules/three/examples/jsm/postprocessing/Pass.js +class Pass { + constructor() { + this.isPass = true; + this.enabled = true; + this.needsSwap = true; + this.clear = false; + this.renderToScreen = false; + } + setSize() { + } + render() { + console.error("THREE.Pass: .render() must be implemented in derived pass."); + } + dispose() { + } +} +var _camera2 = new OrthographicCamera(-1, 1, 1, -1, 0, 1); + +class FullscreenTriangleGeometry extends BufferGeometry { + constructor() { + super(); + this.setAttribute("position", new Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3)); + this.setAttribute("uv", new Float32BufferAttribute([0, 2, 0, 0, 2, 0], 2)); + } +} +var _geometry2 = new FullscreenTriangleGeometry; + +class FullScreenQuad { + constructor(material) { + this._mesh = new Mesh(_geometry2, material); + } + dispose() { + this._mesh.geometry.dispose(); + } + render(renderer2) { + renderer2.render(this._mesh, _camera2); + } + get material() { + return this._mesh.material; + } + set material(value2) { + this._mesh.material = value2; + } +} +// node_modules/three/examples/jsm/exporters/DRACOExporter.js +class DRACOExporter { + parse(object, options = {}) { + options = Object.assign({ + decodeSpeed: 5, + encodeSpeed: 5, + encoderMethod: DRACOExporter.MESH_EDGEBREAKER_ENCODING, + quantization: [16, 8, 8, 8, 8], + exportUvs: true, + exportNormals: true, + exportColor: false + }, options); + if (DracoEncoderModule === undefined) { + throw new Error("THREE.DRACOExporter: required the draco_encoder to work."); + } + const geometry = object.geometry; + const dracoEncoder = DracoEncoderModule(); + const encoder = new dracoEncoder.Encoder; + let builder; + let dracoObject; + if (object.isMesh === true) { + builder = new dracoEncoder.MeshBuilder; + dracoObject = new dracoEncoder.Mesh; + const vertices = geometry.getAttribute("position"); + builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); + const faces = geometry.getIndex(); + if (faces !== null) { + builder.AddFacesToMesh(dracoObject, faces.count / 3, faces.array); + } else { + const faces2 = new (vertices.count > 65535 ? Uint32Array : Uint16Array)(vertices.count); + for (let i = 0;i < faces2.length; i++) { + faces2[i] = i; + } + builder.AddFacesToMesh(dracoObject, vertices.count, faces2); + } + if (options.exportNormals === true) { + const normals = geometry.getAttribute("normal"); + if (normals !== undefined) { + builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.NORMAL, normals.count, normals.itemSize, normals.array); + } + } + if (options.exportUvs === true) { + const uvs = geometry.getAttribute("uv"); + if (uvs !== undefined) { + builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.TEX_COORD, uvs.count, uvs.itemSize, uvs.array); + } + } + if (options.exportColor === true) { + const colors = geometry.getAttribute("color"); + if (colors !== undefined) { + const array = createVertexColorSRGBArray(colors); + builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, array); + } + } + } else if (object.isPoints === true) { + builder = new dracoEncoder.PointCloudBuilder; + dracoObject = new dracoEncoder.PointCloud; + const vertices = geometry.getAttribute("position"); + builder.AddFloatAttribute(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); + if (options.exportColor === true) { + const colors = geometry.getAttribute("color"); + if (colors !== undefined) { + const array = createVertexColorSRGBArray(colors); + builder.AddFloatAttribute(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, array); + } + } + } else { + throw new Error("DRACOExporter: Unsupported object type."); + } + const encodedData = new dracoEncoder.DracoInt8Array; + const encodeSpeed = options.encodeSpeed !== undefined ? options.encodeSpeed : 5; + const decodeSpeed = options.decodeSpeed !== undefined ? options.decodeSpeed : 5; + encoder.SetSpeedOptions(encodeSpeed, decodeSpeed); + if (options.encoderMethod !== undefined) { + encoder.SetEncodingMethod(options.encoderMethod); + } + if (options.quantization !== undefined) { + for (let i = 0;i < 5; i++) { + if (options.quantization[i] !== undefined) { + encoder.SetAttributeQuantization(i, options.quantization[i]); + } + } + } + let length2; + if (object.isMesh === true) { + length2 = encoder.EncodeMeshToDracoBuffer(dracoObject, encodedData); + } else { + length2 = encoder.EncodePointCloudToDracoBuffer(dracoObject, true, encodedData); + } + dracoEncoder.destroy(dracoObject); + if (length2 === 0) { + throw new Error("THREE.DRACOExporter: Draco encoding failed."); + } + const outputData = new Int8Array(new ArrayBuffer(length2)); + for (let i = 0;i < length2; i++) { + outputData[i] = encodedData.GetValue(i); + } + dracoEncoder.destroy(encodedData); + dracoEncoder.destroy(encoder); + dracoEncoder.destroy(builder); + return outputData; + } +} +function createVertexColorSRGBArray(attribute) { + const _color3 = new Color; + const count = attribute.count; + const itemSize = attribute.itemSize; + const array = new Float32Array(count * itemSize); + for (let i = 0, il = count;i < il; i++) { + _color3.fromBufferAttribute(attribute, i); + ColorManagement.fromWorkingColorSpace(_color3, SRGBColorSpace); + array[i * itemSize] = _color3.r; + array[i * itemSize + 1] = _color3.g; + array[i * itemSize + 2] = _color3.b; + if (itemSize === 4) { + array[i * itemSize + 3] = attribute.getW(i); + } + } + return array; +} +DRACOExporter.MESH_EDGEBREAKER_ENCODING = 1; +DRACOExporter.MESH_SEQUENTIAL_ENCODING = 0; +DRACOExporter.POINT_CLOUD = 0; +DRACOExporter.TRIANGULAR_MESH = 1; +DRACOExporter.INVALID = -1; +DRACOExporter.POSITION = 0; +DRACOExporter.NORMAL = 1; +DRACOExporter.COLOR = 2; +DRACOExporter.TEX_COORD = 3; +DRACOExporter.GENERIC = 4; +// node_modules/three/examples/jsm/libs/fflate.module.js +/*! +fflate - fast JavaScript compression/decompression + +Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE +version 0.8.2 +*/ +var u8 = Uint8Array; +var u16 = Uint16Array; +var i32 = Int32Array; +var fleb = new u8([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, 0, 0, 0]); +var fdeb = new u8([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, 0, 0]); +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +var freb = function(eb2, start) { + var b = new u16(31); + for (var i = 0;i < 31; ++i) { + b[i] = start += 1 << eb2[i - 1]; + } + var r = new i32(b[30]); + for (var i = 1;i < 30; ++i) { + for (var j = b[i];j < b[i + 1]; ++j) { + r[j] = j - b[i] << 5 | i; + } + } + return { b, r }; +}; +var _a = freb(fleb, 2); +var fl2 = _a.b; +var revfl = _a.r; +fl2[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0); +var fd = _b.b; +var revfd = _b.r; +var rev = new u16(32768); +for (i = 0;i < 32768; ++i) { + x = (i & 43690) >> 1 | (i & 21845) << 1; + x = (x & 52428) >> 2 | (x & 13107) << 2; + x = (x & 61680) >> 4 | (x & 3855) << 4; + rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1; +} +var x; +var i; +var flt = new u8(288); +for (i = 0;i < 144; ++i) + flt[i] = 8; +var i; +for (i = 144;i < 256; ++i) + flt[i] = 9; +var i; +for (i = 256;i < 280; ++i) + flt[i] = 7; +var i; +for (i = 280;i < 288; ++i) + flt[i] = 8; +var i; +var fdt = new u8(32); +for (i = 0;i < 32; ++i) + fdt[i] = 5; +var i; +var et2 = /* @__PURE__ */ new u8(0); +var td2 = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder; +var tds = 0; +try { + td2.decode(et2, { stream: true }); + tds = 1; +} catch (e) { +} + +// node_modules/three/examples/jsm/exporters/EXRExporter.js +var textEncoder = new TextEncoder; +// node_modules/three/examples/jsm/exporters/GLTFExporter.js +var KHR_mesh_quantization_ExtraAttrTypes = { + POSITION: [ + "byte", + "byte normalized", + "unsigned byte", + "unsigned byte normalized", + "short", + "short normalized", + "unsigned short", + "unsigned short normalized" + ], + NORMAL: [ + "byte normalized", + "short normalized" + ], + TANGENT: [ + "byte normalized", + "short normalized" + ], + TEXCOORD: [ + "byte", + "byte normalized", + "unsigned byte", + "short", + "short normalized", + "unsigned short" + ] +}; + +class GLTFExporter { + constructor() { + this.textureUtils = null; + this.pluginCallbacks = []; + this.register(function(writer) { + return new GLTFLightExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsUnlitExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsTransmissionExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsVolumeExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsIorExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsSpecularExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsClearcoatExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsDispersionExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsIridescenceExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsSheenExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsAnisotropyExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsEmissiveStrengthExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsBumpExtension(writer); + }); + this.register(function(writer) { + return new GLTFMeshGpuInstancing(writer); + }); + } + register(callback) { + if (this.pluginCallbacks.indexOf(callback) === -1) { + this.pluginCallbacks.push(callback); + } + return this; + } + unregister(callback) { + if (this.pluginCallbacks.indexOf(callback) !== -1) { + this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); + } + return this; + } + setTextureUtils(utils) { + this.textureUtils = utils; + return this; + } + parse(input, onDone, onError, options) { + const writer = new GLTFWriter; + const plugins = []; + for (let i = 0, il = this.pluginCallbacks.length;i < il; i++) { + plugins.push(this.pluginCallbacks[i](writer)); + } + writer.setPlugins(plugins); + writer.setTextureUtils(this.textureUtils); + writer.writeAsync(input, onDone, options).catch(onError); + } + parseAsync(input, options) { + const scope = this; + return new Promise(function(resolve, reject2) { + scope.parse(input, resolve, reject2, options); + }); + } +} +var WEBGL_CONSTANTS = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6, + BYTE: 5120, + UNSIGNED_BYTE: 5121, + SHORT: 5122, + UNSIGNED_SHORT: 5123, + INT: 5124, + UNSIGNED_INT: 5125, + FLOAT: 5126, + ARRAY_BUFFER: 34962, + ELEMENT_ARRAY_BUFFER: 34963, + NEAREST: 9728, + LINEAR: 9729, + NEAREST_MIPMAP_NEAREST: 9984, + LINEAR_MIPMAP_NEAREST: 9985, + NEAREST_MIPMAP_LINEAR: 9986, + LINEAR_MIPMAP_LINEAR: 9987, + CLAMP_TO_EDGE: 33071, + MIRRORED_REPEAT: 33648, + REPEAT: 10497 +}; +var KHR_MESH_QUANTIZATION = "KHR_mesh_quantization"; +var THREE_TO_WEBGL = {}; +THREE_TO_WEBGL[NearestFilter] = WEBGL_CONSTANTS.NEAREST; +THREE_TO_WEBGL[NearestMipmapNearestFilter] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST; +THREE_TO_WEBGL[NearestMipmapLinearFilter] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR; +THREE_TO_WEBGL[LinearFilter] = WEBGL_CONSTANTS.LINEAR; +THREE_TO_WEBGL[LinearMipmapNearestFilter] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST; +THREE_TO_WEBGL[LinearMipmapLinearFilter] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR; +THREE_TO_WEBGL[ClampToEdgeWrapping] = WEBGL_CONSTANTS.CLAMP_TO_EDGE; +THREE_TO_WEBGL[RepeatWrapping] = WEBGL_CONSTANTS.REPEAT; +THREE_TO_WEBGL[MirroredRepeatWrapping] = WEBGL_CONSTANTS.MIRRORED_REPEAT; +var PATH_PROPERTIES = { + scale: "scale", + position: "translation", + quaternion: "rotation", + morphTargetInfluences: "weights" +}; +var DEFAULT_SPECULAR_COLOR = new Color; +var GLB_HEADER_BYTES = 12; +var GLB_HEADER_MAGIC = 1179937895; +var GLB_VERSION = 2; +var GLB_CHUNK_PREFIX_BYTES = 8; +var GLB_CHUNK_TYPE_JSON = 1313821514; +var GLB_CHUNK_TYPE_BIN = 5130562; +function equalArray(array1, array2) { + return array1.length === array2.length && array1.every(function(element, index2) { + return element === array2[index2]; + }); +} +function stringToArrayBuffer(text2) { + return new TextEncoder().encode(text2).buffer; +} +function isIdentityMatrix(matrix) { + return equalArray(matrix.elements, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); +} +function getMinMax(attribute, start, count) { + const output = { + min: new Array(attribute.itemSize).fill(Number.POSITIVE_INFINITY), + max: new Array(attribute.itemSize).fill(Number.NEGATIVE_INFINITY) + }; + for (let i = start;i < start + count; i++) { + for (let a = 0;a < attribute.itemSize; a++) { + let value2; + if (attribute.itemSize > 4) { + value2 = attribute.array[i * attribute.itemSize + a]; + } else { + if (a === 0) + value2 = attribute.getX(i); + else if (a === 1) + value2 = attribute.getY(i); + else if (a === 2) + value2 = attribute.getZ(i); + else if (a === 3) + value2 = attribute.getW(i); + if (attribute.normalized === true) { + value2 = MathUtils.normalize(value2, attribute.array); + } + } + output.min[a] = Math.min(output.min[a], value2); + output.max[a] = Math.max(output.max[a], value2); + } + } + return output; +} +function getPaddedBufferSize(bufferSize) { + return Math.ceil(bufferSize / 4) * 4; +} +function getPaddedArrayBuffer(arrayBuffer, paddingByte = 0) { + const paddedLength = getPaddedBufferSize(arrayBuffer.byteLength); + if (paddedLength !== arrayBuffer.byteLength) { + const array = new Uint8Array(paddedLength); + array.set(new Uint8Array(arrayBuffer)); + if (paddingByte !== 0) { + for (let i = arrayBuffer.byteLength;i < paddedLength; i++) { + array[i] = paddingByte; + } + } + return array.buffer; + } + return arrayBuffer; +} +function getCanvas() { + if (typeof document === "undefined" && typeof OffscreenCanvas !== "undefined") { + return new OffscreenCanvas(1, 1); + } + return document.createElement("canvas"); +} +function getToBlobPromise(canvas, mimeType) { + if (canvas.toBlob !== undefined) { + return new Promise((resolve) => canvas.toBlob(resolve, mimeType)); + } + let quality; + if (mimeType === "image/jpeg") { + quality = 0.92; + } else if (mimeType === "image/webp") { + quality = 0.8; + } + return canvas.convertToBlob({ + type: mimeType, + quality + }); +} + +class GLTFWriter { + constructor() { + this.plugins = []; + this.options = {}; + this.pending = []; + this.buffers = []; + this.byteOffset = 0; + this.buffers = []; + this.nodeMap = new Map; + this.skins = []; + this.extensionsUsed = {}; + this.extensionsRequired = {}; + this.uids = new Map; + this.uid = 0; + this.json = { + asset: { + version: "2.0", + generator: "THREE.GLTFExporter r" + REVISION + } + }; + this.cache = { + meshes: new Map, + attributes: new Map, + attributesNormalized: new Map, + materials: new Map, + textures: new Map, + images: new Map + }; + this.textureUtils = null; + } + setPlugins(plugins) { + this.plugins = plugins; + } + setTextureUtils(utils) { + this.textureUtils = utils; + } + async writeAsync(input, onDone, options = {}) { + this.options = Object.assign({ + binary: false, + trs: false, + onlyVisible: true, + maxTextureSize: Infinity, + animations: [], + includeCustomExtensions: false + }, options); + if (this.options.animations.length > 0) { + this.options.trs = true; + } + await this.processInputAsync(input); + await Promise.all(this.pending); + const writer = this; + const buffers = writer.buffers; + const json = writer.json; + options = writer.options; + const extensionsUsed = writer.extensionsUsed; + const extensionsRequired = writer.extensionsRequired; + const blob = new Blob(buffers, { type: "application/octet-stream" }); + const extensionsUsedList = Object.keys(extensionsUsed); + const extensionsRequiredList = Object.keys(extensionsRequired); + if (extensionsUsedList.length > 0) + json.extensionsUsed = extensionsUsedList; + if (extensionsRequiredList.length > 0) + json.extensionsRequired = extensionsRequiredList; + if (json.buffers && json.buffers.length > 0) + json.buffers[0].byteLength = blob.size; + if (options.binary === true) { + const reader = new FileReader; + reader.readAsArrayBuffer(blob); + reader.onloadend = function() { + const binaryChunk = getPaddedArrayBuffer(reader.result); + const binaryChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); + binaryChunkPrefix.setUint32(0, binaryChunk.byteLength, true); + binaryChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_BIN, true); + const jsonChunk = getPaddedArrayBuffer(stringToArrayBuffer(JSON.stringify(json)), 32); + const jsonChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); + jsonChunkPrefix.setUint32(0, jsonChunk.byteLength, true); + jsonChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_JSON, true); + const header = new ArrayBuffer(GLB_HEADER_BYTES); + const headerView = new DataView(header); + headerView.setUint32(0, GLB_HEADER_MAGIC, true); + headerView.setUint32(4, GLB_VERSION, true); + const totalByteLength = GLB_HEADER_BYTES + jsonChunkPrefix.byteLength + jsonChunk.byteLength + binaryChunkPrefix.byteLength + binaryChunk.byteLength; + headerView.setUint32(8, totalByteLength, true); + const glbBlob = new Blob([ + header, + jsonChunkPrefix, + jsonChunk, + binaryChunkPrefix, + binaryChunk + ], { type: "application/octet-stream" }); + const glbReader = new FileReader; + glbReader.readAsArrayBuffer(glbBlob); + glbReader.onloadend = function() { + onDone(glbReader.result); + }; + }; + } else { + if (json.buffers && json.buffers.length > 0) { + const reader = new FileReader; + reader.readAsDataURL(blob); + reader.onloadend = function() { + const base64data = reader.result; + json.buffers[0].uri = base64data; + onDone(json); + }; + } else { + onDone(json); + } + } + } + serializeUserData(object, objectDef) { + if (Object.keys(object.userData).length === 0) + return; + const options = this.options; + const extensionsUsed = this.extensionsUsed; + try { + const json = JSON.parse(JSON.stringify(object.userData)); + if (options.includeCustomExtensions && json.gltfExtensions) { + if (objectDef.extensions === undefined) + objectDef.extensions = {}; + for (const extensionName in json.gltfExtensions) { + objectDef.extensions[extensionName] = json.gltfExtensions[extensionName]; + extensionsUsed[extensionName] = true; + } + delete json.gltfExtensions; + } + if (Object.keys(json).length > 0) + objectDef.extras = json; + } catch (error) { + console.warn("THREE.GLTFExporter: userData of '" + object.name + "' " + "won't be serialized because of JSON.stringify error - " + error.message); + } + } + getUID(attribute, isRelativeCopy = false) { + if (this.uids.has(attribute) === false) { + const uids2 = new Map; + uids2.set(true, this.uid++); + uids2.set(false, this.uid++); + this.uids.set(attribute, uids2); + } + const uids = this.uids.get(attribute); + return uids.get(isRelativeCopy); + } + isNormalizedNormalAttribute(normal) { + const cache = this.cache; + if (cache.attributesNormalized.has(normal)) + return false; + const v = new Vector3; + for (let i = 0, il = normal.count;i < il; i++) { + if (Math.abs(v.fromBufferAttribute(normal, i).length() - 1) > 0.0005) + return false; + } + return true; + } + createNormalizedNormalAttribute(normal) { + const cache = this.cache; + if (cache.attributesNormalized.has(normal)) + return cache.attributesNormalized.get(normal); + const attribute = normal.clone(); + const v = new Vector3; + for (let i = 0, il = attribute.count;i < il; i++) { + v.fromBufferAttribute(attribute, i); + if (v.x === 0 && v.y === 0 && v.z === 0) { + v.setX(1); + } else { + v.normalize(); + } + attribute.setXYZ(i, v.x, v.y, v.z); + } + cache.attributesNormalized.set(normal, attribute); + return attribute; + } + applyTextureTransform(mapDef, texture) { + let didTransform = false; + const transformDef = {}; + if (texture.offset.x !== 0 || texture.offset.y !== 0) { + transformDef.offset = texture.offset.toArray(); + didTransform = true; + } + if (texture.rotation !== 0) { + transformDef.rotation = texture.rotation; + didTransform = true; + } + if (texture.repeat.x !== 1 || texture.repeat.y !== 1) { + transformDef.scale = texture.repeat.toArray(); + didTransform = true; + } + if (didTransform) { + mapDef.extensions = mapDef.extensions || {}; + mapDef.extensions["KHR_texture_transform"] = transformDef; + this.extensionsUsed["KHR_texture_transform"] = true; + } + } + async buildMetalRoughTextureAsync(metalnessMap, roughnessMap) { + if (metalnessMap === roughnessMap) + return metalnessMap; + function getEncodingConversion(map2) { + if (map2.colorSpace === SRGBColorSpace) { + return function SRGBToLinear(c) { + return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); + }; + } + return function LinearToLinear(c) { + return c; + }; + } + if (metalnessMap instanceof CompressedTexture) { + metalnessMap = await this.decompressTextureAsync(metalnessMap); + } + if (roughnessMap instanceof CompressedTexture) { + roughnessMap = await this.decompressTextureAsync(roughnessMap); + } + const metalness = metalnessMap ? metalnessMap.image : null; + const roughness = roughnessMap ? roughnessMap.image : null; + const width2 = Math.max(metalness ? metalness.width : 0, roughness ? roughness.width : 0); + const height2 = Math.max(metalness ? metalness.height : 0, roughness ? roughness.height : 0); + const canvas = getCanvas(); + canvas.width = width2; + canvas.height = height2; + const context = canvas.getContext("2d", { + willReadFrequently: true + }); + context.fillStyle = "#00ffff"; + context.fillRect(0, 0, width2, height2); + const composite = context.getImageData(0, 0, width2, height2); + if (metalness) { + context.drawImage(metalness, 0, 0, width2, height2); + const convert = getEncodingConversion(metalnessMap); + const data2 = context.getImageData(0, 0, width2, height2).data; + for (let i = 2;i < data2.length; i += 4) { + composite.data[i] = convert(data2[i] / 256) * 256; + } + } + if (roughness) { + context.drawImage(roughness, 0, 0, width2, height2); + const convert = getEncodingConversion(roughnessMap); + const data2 = context.getImageData(0, 0, width2, height2).data; + for (let i = 1;i < data2.length; i += 4) { + composite.data[i] = convert(data2[i] / 256) * 256; + } + } + context.putImageData(composite, 0, 0); + const reference = metalnessMap || roughnessMap; + const texture = reference.clone(); + texture.source = new Source(canvas); + texture.colorSpace = NoColorSpace; + texture.channel = (metalnessMap || roughnessMap).channel; + if (metalnessMap && roughnessMap && metalnessMap.channel !== roughnessMap.channel) { + console.warn("THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match."); + } + console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."); + return texture; + } + async decompressTextureAsync(texture, maxTextureSize = Infinity) { + if (this.textureUtils === null) { + throw new Error("THREE.GLTFExporter: setTextureUtils() must be called to process compressed textures."); + } + return await this.textureUtils.decompress(texture, maxTextureSize); + } + processBuffer(buffer) { + const json = this.json; + const buffers = this.buffers; + if (!json.buffers) + json.buffers = [{ byteLength: 0 }]; + buffers.push(buffer); + return 0; + } + processBufferView(attribute, componentType, start, count, target) { + const json = this.json; + if (!json.bufferViews) + json.bufferViews = []; + let componentSize; + switch (componentType) { + case WEBGL_CONSTANTS.BYTE: + case WEBGL_CONSTANTS.UNSIGNED_BYTE: + componentSize = 1; + break; + case WEBGL_CONSTANTS.SHORT: + case WEBGL_CONSTANTS.UNSIGNED_SHORT: + componentSize = 2; + break; + default: + componentSize = 4; + } + let byteStride = attribute.itemSize * componentSize; + if (target === WEBGL_CONSTANTS.ARRAY_BUFFER) { + byteStride = Math.ceil(byteStride / 4) * 4; + } + const byteLength = getPaddedBufferSize(count * byteStride); + const dataView = new DataView(new ArrayBuffer(byteLength)); + let offset = 0; + for (let i = start;i < start + count; i++) { + for (let a = 0;a < attribute.itemSize; a++) { + let value2; + if (attribute.itemSize > 4) { + value2 = attribute.array[i * attribute.itemSize + a]; + } else { + if (a === 0) + value2 = attribute.getX(i); + else if (a === 1) + value2 = attribute.getY(i); + else if (a === 2) + value2 = attribute.getZ(i); + else if (a === 3) + value2 = attribute.getW(i); + if (attribute.normalized === true) { + value2 = MathUtils.normalize(value2, attribute.array); + } + } + if (componentType === WEBGL_CONSTANTS.FLOAT) { + dataView.setFloat32(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.INT) { + dataView.setInt32(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_INT) { + dataView.setUint32(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.SHORT) { + dataView.setInt16(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT) { + dataView.setUint16(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.BYTE) { + dataView.setInt8(offset, value2); + } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE) { + dataView.setUint8(offset, value2); + } + offset += componentSize; + } + if (offset % byteStride !== 0) { + offset += byteStride - offset % byteStride; + } + } + const bufferViewDef = { + buffer: this.processBuffer(dataView.buffer), + byteOffset: this.byteOffset, + byteLength + }; + if (target !== undefined) + bufferViewDef.target = target; + if (target === WEBGL_CONSTANTS.ARRAY_BUFFER) { + bufferViewDef.byteStride = byteStride; + } + this.byteOffset += byteLength; + json.bufferViews.push(bufferViewDef); + const output = { + id: json.bufferViews.length - 1, + byteLength: 0 + }; + return output; + } + processBufferViewImage(blob) { + const writer = this; + const json = writer.json; + if (!json.bufferViews) + json.bufferViews = []; + return new Promise(function(resolve) { + const reader = new FileReader; + reader.readAsArrayBuffer(blob); + reader.onloadend = function() { + const buffer = getPaddedArrayBuffer(reader.result); + const bufferViewDef = { + buffer: writer.processBuffer(buffer), + byteOffset: writer.byteOffset, + byteLength: buffer.byteLength + }; + writer.byteOffset += buffer.byteLength; + resolve(json.bufferViews.push(bufferViewDef) - 1); + }; + }); + } + processAccessor(attribute, geometry, start, count) { + const json = this.json; + const types = { + 1: "SCALAR", + 2: "VEC2", + 3: "VEC3", + 4: "VEC4", + 9: "MAT3", + 16: "MAT4" + }; + let componentType; + if (attribute.array.constructor === Float32Array) { + componentType = WEBGL_CONSTANTS.FLOAT; + } else if (attribute.array.constructor === Int32Array) { + componentType = WEBGL_CONSTANTS.INT; + } else if (attribute.array.constructor === Uint32Array) { + componentType = WEBGL_CONSTANTS.UNSIGNED_INT; + } else if (attribute.array.constructor === Int16Array) { + componentType = WEBGL_CONSTANTS.SHORT; + } else if (attribute.array.constructor === Uint16Array) { + componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT; + } else if (attribute.array.constructor === Int8Array) { + componentType = WEBGL_CONSTANTS.BYTE; + } else if (attribute.array.constructor === Uint8Array) { + componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE; + } else { + throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: " + attribute.array.constructor.name); + } + if (start === undefined) + start = 0; + if (count === undefined || count === Infinity) + count = attribute.count; + if (count === 0) + return null; + const minMax = getMinMax(attribute, start, count); + let bufferViewTarget; + if (geometry !== undefined) { + bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER; + } + const bufferView = this.processBufferView(attribute, componentType, start, count, bufferViewTarget); + const accessorDef = { + bufferView: bufferView.id, + byteOffset: bufferView.byteOffset, + componentType, + count, + max: minMax.max, + min: minMax.min, + type: types[attribute.itemSize] + }; + if (attribute.normalized === true) + accessorDef.normalized = true; + if (!json.accessors) + json.accessors = []; + return json.accessors.push(accessorDef) - 1; + } + processImage(image, format, flipY, mimeType = "image/png") { + if (image !== null) { + const writer = this; + const cache = writer.cache; + const json = writer.json; + const options = writer.options; + const pending = writer.pending; + if (!cache.images.has(image)) + cache.images.set(image, {}); + const cachedImages = cache.images.get(image); + const key2 = mimeType + ":flipY/" + flipY.toString(); + if (cachedImages[key2] !== undefined) + return cachedImages[key2]; + if (!json.images) + json.images = []; + const imageDef = { mimeType }; + const canvas = getCanvas(); + canvas.width = Math.min(image.width, options.maxTextureSize); + canvas.height = Math.min(image.height, options.maxTextureSize); + const ctx = canvas.getContext("2d", { + willReadFrequently: true + }); + if (flipY === true) { + ctx.translate(0, canvas.height); + ctx.scale(1, -1); + } + if (image.data !== undefined) { + if (format !== RGBAFormat) { + console.error("GLTFExporter: Only RGBAFormat is supported.", format); + } + if (image.width > options.maxTextureSize || image.height > options.maxTextureSize) { + console.warn("GLTFExporter: Image size is bigger than maxTextureSize", image); + } + const data2 = new Uint8ClampedArray(image.height * image.width * 4); + for (let i = 0;i < data2.length; i += 4) { + data2[i + 0] = image.data[i + 0]; + data2[i + 1] = image.data[i + 1]; + data2[i + 2] = image.data[i + 2]; + data2[i + 3] = image.data[i + 3]; + } + ctx.putImageData(new ImageData(data2, image.width, image.height), 0, 0); + } else { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof OffscreenCanvas !== "undefined" && image instanceof OffscreenCanvas) { + ctx.drawImage(image, 0, 0, canvas.width, canvas.height); + } else { + throw new Error("THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas."); + } + } + if (options.binary === true) { + pending.push(getToBlobPromise(canvas, mimeType).then((blob) => writer.processBufferViewImage(blob)).then((bufferViewIndex) => { + imageDef.bufferView = bufferViewIndex; + })); + } else { + if (canvas.toDataURL !== undefined) { + imageDef.uri = canvas.toDataURL(mimeType); + } else { + pending.push(getToBlobPromise(canvas, mimeType).then((blob) => new FileReader().readAsDataURL(blob)).then((dataURL) => { + imageDef.uri = dataURL; + })); + } + } + const index2 = json.images.push(imageDef) - 1; + cachedImages[key2] = index2; + return index2; + } else { + throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture."); + } + } + processSampler(map2) { + const json = this.json; + if (!json.samplers) + json.samplers = []; + const samplerDef = { + magFilter: THREE_TO_WEBGL[map2.magFilter], + minFilter: THREE_TO_WEBGL[map2.minFilter], + wrapS: THREE_TO_WEBGL[map2.wrapS], + wrapT: THREE_TO_WEBGL[map2.wrapT] + }; + return json.samplers.push(samplerDef) - 1; + } + async processTextureAsync(map2) { + const writer = this; + const options = writer.options; + const cache = this.cache; + const json = this.json; + if (cache.textures.has(map2)) + return cache.textures.get(map2); + if (!json.textures) + json.textures = []; + if (map2 instanceof CompressedTexture) { + map2 = await this.decompressTextureAsync(map2, options.maxTextureSize); + } + let mimeType = map2.userData.mimeType; + if (mimeType === "image/webp") + mimeType = "image/png"; + const textureDef = { + sampler: this.processSampler(map2), + source: this.processImage(map2.image, map2.format, map2.flipY, mimeType) + }; + if (map2.name) + textureDef.name = map2.name; + await this._invokeAllAsync(async function(ext) { + ext.writeTexture && await ext.writeTexture(map2, textureDef); + }); + const index2 = json.textures.push(textureDef) - 1; + cache.textures.set(map2, index2); + return index2; + } + async processMaterialAsync(material) { + const cache = this.cache; + const json = this.json; + if (cache.materials.has(material)) + return cache.materials.get(material); + if (material.isShaderMaterial) { + console.warn("GLTFExporter: THREE.ShaderMaterial not supported."); + return null; + } + if (!json.materials) + json.materials = []; + const materialDef = { pbrMetallicRoughness: {} }; + if (material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true) { + console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results."); + } + const color = material.color.toArray().concat([material.opacity]); + if (!equalArray(color, [1, 1, 1, 1])) { + materialDef.pbrMetallicRoughness.baseColorFactor = color; + } + if (material.isMeshStandardMaterial) { + materialDef.pbrMetallicRoughness.metallicFactor = material.metalness; + materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness; + } else { + materialDef.pbrMetallicRoughness.metallicFactor = 0; + materialDef.pbrMetallicRoughness.roughnessFactor = 1; + } + if (material.metalnessMap || material.roughnessMap) { + const metalRoughTexture = await this.buildMetalRoughTextureAsync(material.metalnessMap, material.roughnessMap); + const metalRoughMapDef = { + index: await this.processTextureAsync(metalRoughTexture), + texCoord: metalRoughTexture.channel + }; + this.applyTextureTransform(metalRoughMapDef, metalRoughTexture); + materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef; + } + if (material.map) { + const baseColorMapDef = { + index: await this.processTextureAsync(material.map), + texCoord: material.map.channel + }; + this.applyTextureTransform(baseColorMapDef, material.map); + materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef; + } + if (material.emissive) { + const emissive = material.emissive; + const maxEmissiveComponent = Math.max(emissive.r, emissive.g, emissive.b); + if (maxEmissiveComponent > 0) { + materialDef.emissiveFactor = material.emissive.toArray(); + } + if (material.emissiveMap) { + const emissiveMapDef = { + index: await this.processTextureAsync(material.emissiveMap), + texCoord: material.emissiveMap.channel + }; + this.applyTextureTransform(emissiveMapDef, material.emissiveMap); + materialDef.emissiveTexture = emissiveMapDef; + } + } + if (material.normalMap) { + const normalMapDef = { + index: await this.processTextureAsync(material.normalMap), + texCoord: material.normalMap.channel + }; + if (material.normalScale && material.normalScale.x !== 1) { + normalMapDef.scale = material.normalScale.x; + } + this.applyTextureTransform(normalMapDef, material.normalMap); + materialDef.normalTexture = normalMapDef; + } + if (material.aoMap) { + const occlusionMapDef = { + index: await this.processTextureAsync(material.aoMap), + texCoord: material.aoMap.channel + }; + if (material.aoMapIntensity !== 1) { + occlusionMapDef.strength = material.aoMapIntensity; + } + this.applyTextureTransform(occlusionMapDef, material.aoMap); + materialDef.occlusionTexture = occlusionMapDef; + } + if (material.transparent) { + materialDef.alphaMode = "BLEND"; + } else { + if (material.alphaTest > 0) { + materialDef.alphaMode = "MASK"; + materialDef.alphaCutoff = material.alphaTest; + } + } + if (material.side === DoubleSide) + materialDef.doubleSided = true; + if (material.name !== "") + materialDef.name = material.name; + this.serializeUserData(material, materialDef); + await this._invokeAllAsync(async function(ext) { + ext.writeMaterialAsync && await ext.writeMaterialAsync(material, materialDef); + }); + const index2 = json.materials.push(materialDef) - 1; + cache.materials.set(material, index2); + return index2; + } + async processMeshAsync(mesh) { + const cache = this.cache; + const json = this.json; + const meshCacheKeyParts = [mesh.geometry.uuid]; + if (Array.isArray(mesh.material)) { + for (let i = 0, l = mesh.material.length;i < l; i++) { + meshCacheKeyParts.push(mesh.material[i].uuid); + } + } else { + meshCacheKeyParts.push(mesh.material.uuid); + } + const meshCacheKey = meshCacheKeyParts.join(":"); + if (cache.meshes.has(meshCacheKey)) + return cache.meshes.get(meshCacheKey); + const geometry = mesh.geometry; + let mode; + if (mesh.isLineSegments) { + mode = WEBGL_CONSTANTS.LINES; + } else if (mesh.isLineLoop) { + mode = WEBGL_CONSTANTS.LINE_LOOP; + } else if (mesh.isLine) { + mode = WEBGL_CONSTANTS.LINE_STRIP; + } else if (mesh.isPoints) { + mode = WEBGL_CONSTANTS.POINTS; + } else { + mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES; + } + const meshDef = {}; + const attributes = {}; + const primitives = []; + const targets = []; + const nameConversion = { + uv: "TEXCOORD_0", + uv1: "TEXCOORD_1", + uv2: "TEXCOORD_2", + uv3: "TEXCOORD_3", + color: "COLOR_0", + skinWeight: "WEIGHTS_0", + skinIndex: "JOINTS_0" + }; + const originalNormal = geometry.getAttribute("normal"); + if (originalNormal !== undefined && !this.isNormalizedNormalAttribute(originalNormal)) { + console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."); + geometry.setAttribute("normal", this.createNormalizedNormalAttribute(originalNormal)); + } + let modifiedAttribute = null; + for (let attributeName in geometry.attributes) { + if (attributeName.slice(0, 5) === "morph") + continue; + const attribute = geometry.attributes[attributeName]; + attributeName = nameConversion[attributeName] || attributeName.toUpperCase(); + const validVertexAttributes = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/; + if (!validVertexAttributes.test(attributeName)) + attributeName = "_" + attributeName; + if (cache.attributes.has(this.getUID(attribute))) { + attributes[attributeName] = cache.attributes.get(this.getUID(attribute)); + continue; + } + modifiedAttribute = null; + const array = attribute.array; + if (attributeName === "JOINTS_0" && !(array instanceof Uint16Array) && !(array instanceof Uint8Array)) { + console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'); + modifiedAttribute = new BufferAttribute(new Uint16Array(array), attribute.itemSize, attribute.normalized); + } else if ((array instanceof Uint32Array || array instanceof Int32Array) && !attributeName.startsWith("_")) { + console.warn(`GLTFExporter: Attribute "${attributeName}" converted to type FLOAT.`); + modifiedAttribute = GLTFExporter.Utils.toFloat32BufferAttribute(attribute); + } + const accessor = this.processAccessor(modifiedAttribute || attribute, geometry); + if (accessor !== null) { + if (!attributeName.startsWith("_")) { + this.detectMeshQuantization(attributeName, attribute); + } + attributes[attributeName] = accessor; + cache.attributes.set(this.getUID(attribute), accessor); + } + } + if (originalNormal !== undefined) + geometry.setAttribute("normal", originalNormal); + if (Object.keys(attributes).length === 0) + return null; + if (mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0) { + const weights = []; + const targetNames = []; + const reverseDictionary = {}; + if (mesh.morphTargetDictionary !== undefined) { + for (const key2 in mesh.morphTargetDictionary) { + reverseDictionary[mesh.morphTargetDictionary[key2]] = key2; + } + } + for (let i = 0;i < mesh.morphTargetInfluences.length; ++i) { + const target = {}; + let warned = false; + for (const attributeName in geometry.morphAttributes) { + if (attributeName !== "position" && attributeName !== "normal") { + if (!warned) { + console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."); + warned = true; + } + continue; + } + const attribute = geometry.morphAttributes[attributeName][i]; + const gltfAttributeName = attributeName.toUpperCase(); + const baseAttribute = geometry.attributes[attributeName]; + if (cache.attributes.has(this.getUID(attribute, true))) { + target[gltfAttributeName] = cache.attributes.get(this.getUID(attribute, true)); + continue; + } + const relativeAttribute = attribute.clone(); + if (!geometry.morphTargetsRelative) { + for (let j = 0, jl = attribute.count;j < jl; j++) { + for (let a = 0;a < attribute.itemSize; a++) { + if (a === 0) + relativeAttribute.setX(j, attribute.getX(j) - baseAttribute.getX(j)); + if (a === 1) + relativeAttribute.setY(j, attribute.getY(j) - baseAttribute.getY(j)); + if (a === 2) + relativeAttribute.setZ(j, attribute.getZ(j) - baseAttribute.getZ(j)); + if (a === 3) + relativeAttribute.setW(j, attribute.getW(j) - baseAttribute.getW(j)); + } + } + } + target[gltfAttributeName] = this.processAccessor(relativeAttribute, geometry); + cache.attributes.set(this.getUID(baseAttribute, true), target[gltfAttributeName]); + } + targets.push(target); + weights.push(mesh.morphTargetInfluences[i]); + if (mesh.morphTargetDictionary !== undefined) + targetNames.push(reverseDictionary[i]); + } + meshDef.weights = weights; + if (targetNames.length > 0) { + meshDef.extras = {}; + meshDef.extras.targetNames = targetNames; + } + } + const isMultiMaterial = Array.isArray(mesh.material); + if (isMultiMaterial && geometry.groups.length === 0) + return null; + let didForceIndices = false; + if (isMultiMaterial && geometry.index === null) { + const indices = []; + for (let i = 0, il = geometry.attributes.position.count;i < il; i++) { + indices[i] = i; + } + geometry.setIndex(indices); + didForceIndices = true; + } + const materials = isMultiMaterial ? mesh.material : [mesh.material]; + const groups = isMultiMaterial ? geometry.groups : [{ materialIndex: 0, start: undefined, count: undefined }]; + for (let i = 0, il = groups.length;i < il; i++) { + const primitive = { + mode, + attributes + }; + this.serializeUserData(geometry, primitive); + if (targets.length > 0) + primitive.targets = targets; + if (geometry.index !== null) { + let cacheKey = this.getUID(geometry.index); + if (groups[i].start !== undefined || groups[i].count !== undefined) { + cacheKey += ":" + groups[i].start + ":" + groups[i].count; + } + if (cache.attributes.has(cacheKey)) { + primitive.indices = cache.attributes.get(cacheKey); + } else { + primitive.indices = this.processAccessor(geometry.index, geometry, groups[i].start, groups[i].count); + cache.attributes.set(cacheKey, primitive.indices); + } + if (primitive.indices === null) + delete primitive.indices; + } + const material = await this.processMaterialAsync(materials[groups[i].materialIndex]); + if (material !== null) + primitive.material = material; + primitives.push(primitive); + } + if (didForceIndices === true) { + geometry.setIndex(null); + } + meshDef.primitives = primitives; + if (!json.meshes) + json.meshes = []; + await this._invokeAllAsync(function(ext) { + ext.writeMesh && ext.writeMesh(mesh, meshDef); + }); + const index2 = json.meshes.push(meshDef) - 1; + cache.meshes.set(meshCacheKey, index2); + return index2; + } + detectMeshQuantization(attributeName, attribute) { + if (this.extensionsUsed[KHR_MESH_QUANTIZATION]) + return; + let attrType = undefined; + switch (attribute.array.constructor) { + case Int8Array: + attrType = "byte"; + break; + case Uint8Array: + attrType = "unsigned byte"; + break; + case Int16Array: + attrType = "short"; + break; + case Uint16Array: + attrType = "unsigned short"; + break; + default: + return; + } + if (attribute.normalized) + attrType += " normalized"; + const attrNamePrefix = attributeName.split("_", 1)[0]; + if (KHR_mesh_quantization_ExtraAttrTypes[attrNamePrefix] && KHR_mesh_quantization_ExtraAttrTypes[attrNamePrefix].includes(attrType)) { + this.extensionsUsed[KHR_MESH_QUANTIZATION] = true; + this.extensionsRequired[KHR_MESH_QUANTIZATION] = true; + } + } + processCamera(camera) { + const json = this.json; + if (!json.cameras) + json.cameras = []; + const isOrtho = camera.isOrthographicCamera; + const cameraDef = { + type: isOrtho ? "orthographic" : "perspective" + }; + if (isOrtho) { + cameraDef.orthographic = { + xmag: camera.right * 2, + ymag: camera.top * 2, + zfar: camera.far <= 0 ? 0.001 : camera.far, + znear: camera.near < 0 ? 0 : camera.near + }; + } else { + cameraDef.perspective = { + aspectRatio: camera.aspect, + yfov: MathUtils.degToRad(camera.fov), + zfar: camera.far <= 0 ? 0.001 : camera.far, + znear: camera.near < 0 ? 0 : camera.near + }; + } + if (camera.name !== "") + cameraDef.name = camera.type; + return json.cameras.push(cameraDef) - 1; + } + processAnimation(clip, root) { + const json = this.json; + const nodeMap = this.nodeMap; + if (!json.animations) + json.animations = []; + clip = GLTFExporter.Utils.mergeMorphTargetTracks(clip.clone(), root); + const tracks = clip.tracks; + const channels = []; + const samplers = []; + for (let i = 0;i < tracks.length; ++i) { + const track = tracks[i]; + const trackBinding = PropertyBinding.parseTrackName(track.name); + let trackNode = PropertyBinding.findNode(root, trackBinding.nodeName); + const trackProperty = PATH_PROPERTIES[trackBinding.propertyName]; + if (trackBinding.objectName === "bones") { + if (trackNode.isSkinnedMesh === true) { + trackNode = trackNode.skeleton.getBoneByName(trackBinding.objectIndex); + } else { + trackNode = undefined; + } + } + if (!trackNode || !trackProperty) { + console.warn('THREE.GLTFExporter: Could not export animation track "%s".', track.name); + continue; + } + const inputItemSize = 1; + let outputItemSize = track.values.length / track.times.length; + if (trackProperty === PATH_PROPERTIES.morphTargetInfluences) { + outputItemSize /= trackNode.morphTargetInfluences.length; + } + let interpolation; + if (track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true) { + interpolation = "CUBICSPLINE"; + outputItemSize /= 3; + } else if (track.getInterpolation() === InterpolateDiscrete) { + interpolation = "STEP"; + } else { + interpolation = "LINEAR"; + } + samplers.push({ + input: this.processAccessor(new BufferAttribute(track.times, inputItemSize)), + output: this.processAccessor(new BufferAttribute(track.values, outputItemSize)), + interpolation + }); + channels.push({ + sampler: samplers.length - 1, + target: { + node: nodeMap.get(trackNode), + path: trackProperty + } + }); + } + json.animations.push({ + name: clip.name || "clip_" + json.animations.length, + samplers, + channels + }); + return json.animations.length - 1; + } + processSkin(object) { + const json = this.json; + const nodeMap = this.nodeMap; + const node = json.nodes[nodeMap.get(object)]; + const skeleton = object.skeleton; + if (skeleton === undefined) + return null; + const rootJoint = object.skeleton.bones[0]; + if (rootJoint === undefined) + return null; + const joints = []; + const inverseBindMatrices = new Float32Array(skeleton.bones.length * 16); + const temporaryBoneInverse = new Matrix4; + for (let i = 0;i < skeleton.bones.length; ++i) { + joints.push(nodeMap.get(skeleton.bones[i])); + temporaryBoneInverse.copy(skeleton.boneInverses[i]); + temporaryBoneInverse.multiply(object.bindMatrix).toArray(inverseBindMatrices, i * 16); + } + if (json.skins === undefined) + json.skins = []; + json.skins.push({ + inverseBindMatrices: this.processAccessor(new BufferAttribute(inverseBindMatrices, 16)), + joints, + skeleton: nodeMap.get(rootJoint) + }); + const skinIndex = node.skin = json.skins.length - 1; + return skinIndex; + } + async processNodeAsync(object) { + const json = this.json; + const options = this.options; + const nodeMap = this.nodeMap; + if (!json.nodes) + json.nodes = []; + const nodeDef = {}; + if (options.trs) { + const rotation2 = object.quaternion.toArray(); + const position2 = object.position.toArray(); + const scale2 = object.scale.toArray(); + if (!equalArray(rotation2, [0, 0, 0, 1])) { + nodeDef.rotation = rotation2; + } + if (!equalArray(position2, [0, 0, 0])) { + nodeDef.translation = position2; + } + if (!equalArray(scale2, [1, 1, 1])) { + nodeDef.scale = scale2; + } + } else { + if (object.matrixAutoUpdate) { + object.updateMatrix(); + } + if (isIdentityMatrix(object.matrix) === false) { + nodeDef.matrix = object.matrix.elements; + } + } + if (object.name !== "") + nodeDef.name = String(object.name); + this.serializeUserData(object, nodeDef); + if (object.isMesh || object.isLine || object.isPoints) { + const meshIndex = await this.processMeshAsync(object); + if (meshIndex !== null) + nodeDef.mesh = meshIndex; + } else if (object.isCamera) { + nodeDef.camera = this.processCamera(object); + } + if (object.isSkinnedMesh) + this.skins.push(object); + if (object.children.length > 0) { + const children = []; + for (let i = 0, l = object.children.length;i < l; i++) { + const child = object.children[i]; + if (child.visible || options.onlyVisible === false) { + const nodeIndex2 = await this.processNodeAsync(child); + if (nodeIndex2 !== null) + children.push(nodeIndex2); + } + } + if (children.length > 0) + nodeDef.children = children; + } + await this._invokeAllAsync(function(ext) { + ext.writeNode && ext.writeNode(object, nodeDef); + }); + const nodeIndex = json.nodes.push(nodeDef) - 1; + nodeMap.set(object, nodeIndex); + return nodeIndex; + } + async processSceneAsync(scene) { + const json = this.json; + const options = this.options; + if (!json.scenes) { + json.scenes = []; + json.scene = 0; + } + const sceneDef = {}; + if (scene.name !== "") + sceneDef.name = scene.name; + json.scenes.push(sceneDef); + const nodes = []; + for (let i = 0, l = scene.children.length;i < l; i++) { + const child = scene.children[i]; + if (child.visible || options.onlyVisible === false) { + const nodeIndex = await this.processNodeAsync(child); + if (nodeIndex !== null) + nodes.push(nodeIndex); + } + } + if (nodes.length > 0) + sceneDef.nodes = nodes; + this.serializeUserData(scene, sceneDef); + } + async processObjectsAsync(objects) { + const scene = new Scene; + scene.name = "AuxScene"; + for (let i = 0;i < objects.length; i++) { + scene.children.push(objects[i]); + } + await this.processSceneAsync(scene); + } + async processInputAsync(input) { + const options = this.options; + input = input instanceof Array ? input : [input]; + await this._invokeAllAsync(function(ext) { + ext.beforeParse && ext.beforeParse(input); + }); + const objectsWithoutScene = []; + for (let i = 0;i < input.length; i++) { + if (input[i] instanceof Scene) { + await this.processSceneAsync(input[i]); + } else { + objectsWithoutScene.push(input[i]); + } + } + if (objectsWithoutScene.length > 0) { + await this.processObjectsAsync(objectsWithoutScene); + } + for (let i = 0;i < this.skins.length; ++i) { + this.processSkin(this.skins[i]); + } + for (let i = 0;i < options.animations.length; ++i) { + this.processAnimation(options.animations[i], input[0]); + } + await this._invokeAllAsync(function(ext) { + ext.afterParse && ext.afterParse(input); + }); + } + async _invokeAllAsync(func) { + for (let i = 0, il = this.plugins.length;i < il; i++) { + await func(this.plugins[i]); + } + } +} + +class GLTFLightExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_lights_punctual"; + } + writeNode(light, nodeDef) { + if (!light.isLight) + return; + if (!light.isDirectionalLight && !light.isPointLight && !light.isSpotLight) { + console.warn("THREE.GLTFExporter: Only directional, point, and spot lights are supported.", light); + return; + } + const writer = this.writer; + const json = writer.json; + const extensionsUsed = writer.extensionsUsed; + const lightDef = {}; + if (light.name) + lightDef.name = light.name; + lightDef.color = light.color.toArray(); + lightDef.intensity = light.intensity; + if (light.isDirectionalLight) { + lightDef.type = "directional"; + } else if (light.isPointLight) { + lightDef.type = "point"; + if (light.distance > 0) + lightDef.range = light.distance; + } else if (light.isSpotLight) { + lightDef.type = "spot"; + if (light.distance > 0) + lightDef.range = light.distance; + lightDef.spot = {}; + lightDef.spot.innerConeAngle = (1 - light.penumbra) * light.angle; + lightDef.spot.outerConeAngle = light.angle; + } + if (light.decay !== undefined && light.decay !== 2) { + console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, " + "and expects light.decay=2."); + } + if (light.target && (light.target.parent !== light || light.target.position.x !== 0 || light.target.position.y !== 0 || light.target.position.z !== -1)) { + console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, " + "make light.target a child of the light with position 0,0,-1."); + } + if (!extensionsUsed[this.name]) { + json.extensions = json.extensions || {}; + json.extensions[this.name] = { lights: [] }; + extensionsUsed[this.name] = true; + } + const lights = json.extensions[this.name].lights; + lights.push(lightDef); + nodeDef.extensions = nodeDef.extensions || {}; + nodeDef.extensions[this.name] = { light: lights.length - 1 }; + } +} + +class GLTFMaterialsUnlitExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_unlit"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshBasicMaterial) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = {}; + extensionsUsed[this.name] = true; + materialDef.pbrMetallicRoughness.metallicFactor = 0; + materialDef.pbrMetallicRoughness.roughnessFactor = 0.9; + } +} + +class GLTFMaterialsClearcoatExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_clearcoat"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.clearcoat === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.clearcoatFactor = material.clearcoat; + if (material.clearcoatMap) { + const clearcoatMapDef = { + index: await writer.processTextureAsync(material.clearcoatMap), + texCoord: material.clearcoatMap.channel + }; + writer.applyTextureTransform(clearcoatMapDef, material.clearcoatMap); + extensionDef.clearcoatTexture = clearcoatMapDef; + } + extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness; + if (material.clearcoatRoughnessMap) { + const clearcoatRoughnessMapDef = { + index: await writer.processTextureAsync(material.clearcoatRoughnessMap), + texCoord: material.clearcoatRoughnessMap.channel + }; + writer.applyTextureTransform(clearcoatRoughnessMapDef, material.clearcoatRoughnessMap); + extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef; + } + if (material.clearcoatNormalMap) { + const clearcoatNormalMapDef = { + index: await writer.processTextureAsync(material.clearcoatNormalMap), + texCoord: material.clearcoatNormalMap.channel + }; + if (material.clearcoatNormalScale.x !== 1) + clearcoatNormalMapDef.scale = material.clearcoatNormalScale.x; + writer.applyTextureTransform(clearcoatNormalMapDef, material.clearcoatNormalMap); + extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef; + } + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsDispersionExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_dispersion"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.dispersion === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.dispersion = material.dispersion; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsIridescenceExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_iridescence"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.iridescence === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.iridescenceFactor = material.iridescence; + if (material.iridescenceMap) { + const iridescenceMapDef = { + index: await writer.processTextureAsync(material.iridescenceMap), + texCoord: material.iridescenceMap.channel + }; + writer.applyTextureTransform(iridescenceMapDef, material.iridescenceMap); + extensionDef.iridescenceTexture = iridescenceMapDef; + } + extensionDef.iridescenceIor = material.iridescenceIOR; + extensionDef.iridescenceThicknessMinimum = material.iridescenceThicknessRange[0]; + extensionDef.iridescenceThicknessMaximum = material.iridescenceThicknessRange[1]; + if (material.iridescenceThicknessMap) { + const iridescenceThicknessMapDef = { + index: await writer.processTextureAsync(material.iridescenceThicknessMap), + texCoord: material.iridescenceThicknessMap.channel + }; + writer.applyTextureTransform(iridescenceThicknessMapDef, material.iridescenceThicknessMap); + extensionDef.iridescenceThicknessTexture = iridescenceThicknessMapDef; + } + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsTransmissionExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_transmission"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.transmission === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.transmissionFactor = material.transmission; + if (material.transmissionMap) { + const transmissionMapDef = { + index: await writer.processTextureAsync(material.transmissionMap), + texCoord: material.transmissionMap.channel + }; + writer.applyTextureTransform(transmissionMapDef, material.transmissionMap); + extensionDef.transmissionTexture = transmissionMapDef; + } + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsVolumeExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_volume"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.transmission === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.thicknessFactor = material.thickness; + if (material.thicknessMap) { + const thicknessMapDef = { + index: await writer.processTextureAsync(material.thicknessMap), + texCoord: material.thicknessMap.channel + }; + writer.applyTextureTransform(thicknessMapDef, material.thicknessMap); + extensionDef.thicknessTexture = thicknessMapDef; + } + if (material.attenuationDistance !== Infinity) { + extensionDef.attenuationDistance = material.attenuationDistance; + } + extensionDef.attenuationColor = material.attenuationColor.toArray(); + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsIorExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_ior"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.ior === 1.5) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.ior = material.ior; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsSpecularExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_specular"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.specularIntensity === 1 && material.specularColor.equals(DEFAULT_SPECULAR_COLOR) && !material.specularIntensityMap && !material.specularColorMap) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.specularIntensityMap) { + const specularIntensityMapDef = { + index: await writer.processTextureAsync(material.specularIntensityMap), + texCoord: material.specularIntensityMap.channel + }; + writer.applyTextureTransform(specularIntensityMapDef, material.specularIntensityMap); + extensionDef.specularTexture = specularIntensityMapDef; + } + if (material.specularColorMap) { + const specularColorMapDef = { + index: await writer.processTextureAsync(material.specularColorMap), + texCoord: material.specularColorMap.channel + }; + writer.applyTextureTransform(specularColorMapDef, material.specularColorMap); + extensionDef.specularColorTexture = specularColorMapDef; + } + extensionDef.specularFactor = material.specularIntensity; + extensionDef.specularColorFactor = material.specularColor.toArray(); + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsSheenExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_sheen"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.sheen == 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.sheenRoughnessMap) { + const sheenRoughnessMapDef = { + index: await writer.processTextureAsync(material.sheenRoughnessMap), + texCoord: material.sheenRoughnessMap.channel + }; + writer.applyTextureTransform(sheenRoughnessMapDef, material.sheenRoughnessMap); + extensionDef.sheenRoughnessTexture = sheenRoughnessMapDef; + } + if (material.sheenColorMap) { + const sheenColorMapDef = { + index: await writer.processTextureAsync(material.sheenColorMap), + texCoord: material.sheenColorMap.channel + }; + writer.applyTextureTransform(sheenColorMapDef, material.sheenColorMap); + extensionDef.sheenColorTexture = sheenColorMapDef; + } + extensionDef.sheenRoughnessFactor = material.sheenRoughness; + extensionDef.sheenColorFactor = material.sheenColor.toArray(); + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsAnisotropyExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_anisotropy"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.anisotropy == 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.anisotropyMap) { + const anisotropyMapDef = { index: await writer.processTextureAsync(material.anisotropyMap) }; + writer.applyTextureTransform(anisotropyMapDef, material.anisotropyMap); + extensionDef.anisotropyTexture = anisotropyMapDef; + } + extensionDef.anisotropyStrength = material.anisotropy; + extensionDef.anisotropyRotation = material.anisotropyRotation; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsEmissiveStrengthExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_emissive_strength"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshStandardMaterial || material.emissiveIntensity === 1) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.emissiveStrength = material.emissiveIntensity; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsBumpExtension { + constructor(writer) { + this.writer = writer; + this.name = "EXT_materials_bump"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshStandardMaterial || material.bumpScale === 1 && !material.bumpMap) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.bumpMap) { + const bumpMapDef = { + index: await writer.processTextureAsync(material.bumpMap), + texCoord: material.bumpMap.channel + }; + writer.applyTextureTransform(bumpMapDef, material.bumpMap); + extensionDef.bumpTexture = bumpMapDef; + } + extensionDef.bumpFactor = material.bumpScale; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMeshGpuInstancing { + constructor(writer) { + this.writer = writer; + this.name = "EXT_mesh_gpu_instancing"; + } + writeNode(object, nodeDef) { + if (!object.isInstancedMesh) + return; + const writer = this.writer; + const mesh = object; + const translationAttr = new Float32Array(mesh.count * 3); + const rotationAttr = new Float32Array(mesh.count * 4); + const scaleAttr = new Float32Array(mesh.count * 3); + const matrix = new Matrix4; + const position2 = new Vector3; + const quaternion = new Quaternion; + const scale2 = new Vector3; + for (let i = 0;i < mesh.count; i++) { + mesh.getMatrixAt(i, matrix); + matrix.decompose(position2, quaternion, scale2); + position2.toArray(translationAttr, i * 3); + quaternion.toArray(rotationAttr, i * 4); + scale2.toArray(scaleAttr, i * 3); + } + const attributes = { + TRANSLATION: writer.processAccessor(new BufferAttribute(translationAttr, 3)), + ROTATION: writer.processAccessor(new BufferAttribute(rotationAttr, 4)), + SCALE: writer.processAccessor(new BufferAttribute(scaleAttr, 3)) + }; + if (mesh.instanceColor) + attributes._COLOR_0 = writer.processAccessor(mesh.instanceColor); + nodeDef.extensions = nodeDef.extensions || {}; + nodeDef.extensions[this.name] = { attributes }; + writer.extensionsUsed[this.name] = true; + writer.extensionsRequired[this.name] = true; + } +} +GLTFExporter.Utils = { + insertKeyframe: function(track, time2) { + const tolerance = 0.001; + const valueSize = track.getValueSize(); + const times = new track.TimeBufferType(track.times.length + 1); + const values2 = new track.ValueBufferType(track.values.length + valueSize); + const interpolant = track.createInterpolant(new track.ValueBufferType(valueSize)); + let index2; + if (track.times.length === 0) { + times[0] = time2; + for (let i = 0;i < valueSize; i++) { + values2[i] = 0; + } + index2 = 0; + } else if (time2 < track.times[0]) { + if (Math.abs(track.times[0] - time2) < tolerance) + return 0; + times[0] = time2; + times.set(track.times, 1); + values2.set(interpolant.evaluate(time2), 0); + values2.set(track.values, valueSize); + index2 = 0; + } else if (time2 > track.times[track.times.length - 1]) { + if (Math.abs(track.times[track.times.length - 1] - time2) < tolerance) { + return track.times.length - 1; + } + times[times.length - 1] = time2; + times.set(track.times, 0); + values2.set(track.values, 0); + values2.set(interpolant.evaluate(time2), track.values.length); + index2 = times.length - 1; + } else { + for (let i = 0;i < track.times.length; i++) { + if (Math.abs(track.times[i] - time2) < tolerance) + return i; + if (track.times[i] < time2 && track.times[i + 1] > time2) { + times.set(track.times.slice(0, i + 1), 0); + times[i + 1] = time2; + times.set(track.times.slice(i + 1), i + 2); + values2.set(track.values.slice(0, (i + 1) * valueSize), 0); + values2.set(interpolant.evaluate(time2), (i + 1) * valueSize); + values2.set(track.values.slice((i + 1) * valueSize), (i + 2) * valueSize); + index2 = i + 1; + break; + } + } + } + track.times = times; + track.values = values2; + return index2; + }, + mergeMorphTargetTracks: function(clip, root) { + const tracks = []; + const mergedTracks = {}; + const sourceTracks = clip.tracks; + for (let i = 0;i < sourceTracks.length; ++i) { + let sourceTrack = sourceTracks[i]; + const sourceTrackBinding = PropertyBinding.parseTrackName(sourceTrack.name); + const sourceTrackNode = PropertyBinding.findNode(root, sourceTrackBinding.nodeName); + if (sourceTrackBinding.propertyName !== "morphTargetInfluences" || sourceTrackBinding.propertyIndex === undefined) { + tracks.push(sourceTrack); + continue; + } + if (sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear) { + if (sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation."); + } + console.warn("THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead."); + sourceTrack = sourceTrack.clone(); + sourceTrack.setInterpolation(InterpolateLinear); + } + const targetCount = sourceTrackNode.morphTargetInfluences.length; + const targetIndex = sourceTrackNode.morphTargetDictionary[sourceTrackBinding.propertyIndex]; + if (targetIndex === undefined) { + throw new Error("THREE.GLTFExporter: Morph target name not found: " + sourceTrackBinding.propertyIndex); + } + let mergedTrack; + if (mergedTracks[sourceTrackNode.uuid] === undefined) { + mergedTrack = sourceTrack.clone(); + const values2 = new mergedTrack.ValueBufferType(targetCount * mergedTrack.times.length); + for (let j = 0;j < mergedTrack.times.length; j++) { + values2[j * targetCount + targetIndex] = mergedTrack.values[j]; + } + mergedTrack.name = (sourceTrackBinding.nodeName || "") + ".morphTargetInfluences"; + mergedTrack.values = values2; + mergedTracks[sourceTrackNode.uuid] = mergedTrack; + tracks.push(mergedTrack); + continue; + } + const sourceInterpolant = sourceTrack.createInterpolant(new sourceTrack.ValueBufferType(1)); + mergedTrack = mergedTracks[sourceTrackNode.uuid]; + for (let j = 0;j < mergedTrack.times.length; j++) { + mergedTrack.values[j * targetCount + targetIndex] = sourceInterpolant.evaluate(mergedTrack.times[j]); + } + for (let j = 0;j < sourceTrack.times.length; j++) { + const keyframeIndex = this.insertKeyframe(mergedTrack, sourceTrack.times[j]); + mergedTrack.values[keyframeIndex * targetCount + targetIndex] = sourceTrack.values[j]; + } + } + clip.tracks = tracks; + return clip; + }, + toFloat32BufferAttribute: function(srcAttribute) { + const dstAttribute = new BufferAttribute(new Float32Array(srcAttribute.count * srcAttribute.itemSize), srcAttribute.itemSize, false); + if (!srcAttribute.normalized && !srcAttribute.isInterleavedBufferAttribute) { + dstAttribute.array.set(srcAttribute.array); + return dstAttribute; + } + for (let i = 0, il = srcAttribute.count;i < il; i++) { + for (let j = 0;j < srcAttribute.itemSize; j++) { + dstAttribute.setComponent(i, j, srcAttribute.getComponent(i, j)); + } + } + return dstAttribute; + } +}; +// node_modules/three/examples/jsm/libs/ktx-parse.module.js +var t3 = 0; +var n = 2; +var g = 1; +var u2 = 2; +var T2 = 0; +var C3 = 1; +var R = 10; +var it = 0; +var ct = 9; +var yt = 15; +var xt2 = 16; +var wt = 22; +var Ft = 37; +var Ct = 43; +var te2 = 76; +var ae2 = 83; +var ge = 97; +var ue2 = 100; +var we = 103; +var Ae = 109; +var In = 165; +var Sn = 166; +var pi = 1000066000; +class Ii { + constructor() { + this.vkFormat = 0, this.typeSize = 1, this.pixelWidth = 0, this.pixelHeight = 0, this.pixelDepth = 0, this.layerCount = 0, this.faceCount = 1, this.supercompressionScheme = 0, this.levels = [], this.dataFormatDescriptor = [{ vendorId: 0, descriptorType: 0, descriptorBlockSize: 0, versionNumber: 2, colorModel: 0, colorPrimaries: 1, transferFunction: 2, flags: 0, texelBlockDimension: [0, 0, 0, 0], bytesPlane: [0, 0, 0, 0, 0, 0, 0, 0], samples: [] }], this.keyValue = {}, this.globalData = null; + } +} + +class Si { + constructor(t4, e, n2, i) { + this._dataView = undefined, this._littleEndian = undefined, this._offset = undefined, this._dataView = new DataView(t4.buffer, t4.byteOffset + e, n2), this._littleEndian = i, this._offset = 0; + } + _nextUint8() { + const t4 = this._dataView.getUint8(this._offset); + return this._offset += 1, t4; + } + _nextUint16() { + const t4 = this._dataView.getUint16(this._offset, this._littleEndian); + return this._offset += 2, t4; + } + _nextUint32() { + const t4 = this._dataView.getUint32(this._offset, this._littleEndian); + return this._offset += 4, t4; + } + _nextUint64() { + const t4 = this._dataView.getUint32(this._offset, this._littleEndian) + 2 ** 32 * this._dataView.getUint32(this._offset + 4, this._littleEndian); + return this._offset += 8, t4; + } + _nextInt32() { + const t4 = this._dataView.getInt32(this._offset, this._littleEndian); + return this._offset += 4, t4; + } + _nextUint8Array(t4) { + const e = new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + this._offset, t4); + return this._offset += t4, e; + } + _skip(t4) { + return this._offset += t4, this; + } + _scan(t4, e) { + e === undefined && (e = 0); + const n2 = this._offset; + let i = 0; + for (;this._dataView.getUint8(this._offset) !== e && i < t4; ) + i++, this._offset++; + return i < t4 && this._offset++, new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + n2, i); + } +} +var Fi2 = new Uint8Array([0]); +var Oi2 = [171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10]; +function Ti(t4) { + return new TextDecoder().decode(t4); +} +function Pi2(t4) { + const e = new Uint8Array(t4.buffer, t4.byteOffset, Oi2.length); + if (e[0] !== Oi2[0] || e[1] !== Oi2[1] || e[2] !== Oi2[2] || e[3] !== Oi2[3] || e[4] !== Oi2[4] || e[5] !== Oi2[5] || e[6] !== Oi2[6] || e[7] !== Oi2[7] || e[8] !== Oi2[8] || e[9] !== Oi2[9] || e[10] !== Oi2[10] || e[11] !== Oi2[11]) + throw new Error("Missing KTX 2.0 identifier."); + const n2 = new Ii, i = 17 * Uint32Array.BYTES_PER_ELEMENT, s = new Si(t4, Oi2.length, i, true); + n2.vkFormat = s._nextUint32(), n2.typeSize = s._nextUint32(), n2.pixelWidth = s._nextUint32(), n2.pixelHeight = s._nextUint32(), n2.pixelDepth = s._nextUint32(), n2.layerCount = s._nextUint32(), n2.faceCount = s._nextUint32(); + const a = s._nextUint32(); + n2.supercompressionScheme = s._nextUint32(); + const r = s._nextUint32(), o = s._nextUint32(), l = s._nextUint32(), f = s._nextUint32(), h = s._nextUint64(), U = s._nextUint64(), c = new Si(t4, Oi2.length + i, 3 * a * 8, true); + for (let e2 = 0;e2 < a; e2++) + n2.levels.push({ levelData: new Uint8Array(t4.buffer, t4.byteOffset + c._nextUint64(), c._nextUint64()), uncompressedByteLength: c._nextUint64() }); + const _9 = new Si(t4, r, o, true), p = { vendorId: _9._skip(4)._nextUint16(), descriptorType: _9._nextUint16(), versionNumber: _9._nextUint16(), descriptorBlockSize: _9._nextUint16(), colorModel: _9._nextUint8(), colorPrimaries: _9._nextUint8(), transferFunction: _9._nextUint8(), flags: _9._nextUint8(), texelBlockDimension: [_9._nextUint8(), _9._nextUint8(), _9._nextUint8(), _9._nextUint8()], bytesPlane: [_9._nextUint8(), _9._nextUint8(), _9._nextUint8(), _9._nextUint8(), _9._nextUint8(), _9._nextUint8(), _9._nextUint8(), _9._nextUint8()], samples: [] }, g2 = (p.descriptorBlockSize / 4 - 6) / 4; + for (let t5 = 0;t5 < g2; t5++) { + const e2 = { bitOffset: _9._nextUint16(), bitLength: _9._nextUint8(), channelType: _9._nextUint8(), samplePosition: [_9._nextUint8(), _9._nextUint8(), _9._nextUint8(), _9._nextUint8()], sampleLower: -Infinity, sampleUpper: Infinity }; + 64 & e2.channelType ? (e2.sampleLower = _9._nextInt32(), e2.sampleUpper = _9._nextInt32()) : (e2.sampleLower = _9._nextUint32(), e2.sampleUpper = _9._nextUint32()), p.samples[t5] = e2; + } + n2.dataFormatDescriptor.length = 0, n2.dataFormatDescriptor.push(p); + const y3 = new Si(t4, l, f, true); + for (;y3._offset < f; ) { + const t5 = y3._nextUint32(), e2 = y3._scan(t5), i3 = Ti(e2); + if (n2.keyValue[i3] = y3._nextUint8Array(t5 - e2.byteLength - 1), i3.match(/^ktx/i)) { + const t6 = Ti(n2.keyValue[i3]); + n2.keyValue[i3] = t6.substring(0, t6.lastIndexOf("\x00")); + } + y3._skip(t5 % 4 ? 4 - t5 % 4 : 0); + } + if (U <= 0) + return n2; + const x = new Si(t4, h, U, true), u3 = x._nextUint16(), b = x._nextUint16(), d = x._nextUint32(), w = x._nextUint32(), m = x._nextUint32(), D = x._nextUint32(), B2 = []; + for (let t5 = 0;t5 < a; t5++) + B2.push({ imageFlags: x._nextUint32(), rgbSliceByteOffset: x._nextUint32(), rgbSliceByteLength: x._nextUint32(), alphaSliceByteOffset: x._nextUint32(), alphaSliceByteLength: x._nextUint32() }); + const L = h + x._offset, v = L + d, A2 = v + w, k2 = A2 + m, V3 = new Uint8Array(t4.buffer, t4.byteOffset + L, d), I2 = new Uint8Array(t4.buffer, t4.byteOffset + v, w), S = new Uint8Array(t4.buffer, t4.byteOffset + A2, m), F = new Uint8Array(t4.buffer, t4.byteOffset + k2, D); + return n2.globalData = { endpointCount: u3, selectorCount: b, imageDescs: B2, endpointsData: V3, selectorsData: I2, tablesData: S, extendedData: F }, n2; +} + +// node_modules/three/examples/jsm/exporters/KTX2Exporter.js +var VK_FORMAT_MAP = { + [RGBAFormat]: { + [FloatType]: { + [NoColorSpace]: Ae, + [LinearSRGBColorSpace]: Ae + }, + [HalfFloatType]: { + [NoColorSpace]: ge, + [LinearSRGBColorSpace]: ge + }, + [UnsignedByteType]: { + [NoColorSpace]: Ft, + [LinearSRGBColorSpace]: Ft, + [SRGBColorSpace]: Ct + } + }, + [RGFormat]: { + [FloatType]: { + [NoColorSpace]: we, + [LinearSRGBColorSpace]: we + }, + [HalfFloatType]: { + [NoColorSpace]: ae2, + [LinearSRGBColorSpace]: ae2 + }, + [UnsignedByteType]: { + [NoColorSpace]: xt2, + [LinearSRGBColorSpace]: xt2, + [SRGBColorSpace]: wt + } + }, + [RedFormat]: { + [FloatType]: { + [NoColorSpace]: ue2, + [LinearSRGBColorSpace]: ue2 + }, + [HalfFloatType]: { + [NoColorSpace]: te2, + [LinearSRGBColorSpace]: te2 + }, + [UnsignedByteType]: { + [NoColorSpace]: ct, + [LinearSRGBColorSpace]: ct, + [SRGBColorSpace]: yt + } + } +}; +var KHR_DF_CHANNEL_SAMPLE_LOWER_UPPER = { + [FloatType]: [3212836864, 1065353216], + [HalfFloatType]: [3212836864, 1065353216], + [UnsignedByteType]: [0, 255] +}; +// node_modules/three/examples/jsm/math/ConvexHull.js +var _v13 = new Vector3; +var _line3 = new Line3; +var _plane3 = new Plane; +var _closestPoint = new Vector3; +var _triangle2 = new Triangle; +// node_modules/three/examples/jsm/geometries/ParametricGeometry.js +class ParametricGeometry extends BufferGeometry { + constructor(func = (u3, v, target) => target.set(u3, v, Math.cos(u3) * Math.sin(v)), slices = 8, stacks = 8) { + super(); + this.type = "ParametricGeometry"; + this.parameters = { + func, + slices, + stacks + }; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const EPS = 0.00001; + const normal = new Vector3; + const p0 = new Vector3, p1 = new Vector3; + const pu = new Vector3, pv = new Vector3; + const sliceCount = slices + 1; + for (let i = 0;i <= stacks; i++) { + const v = i / stacks; + for (let j2 = 0;j2 <= slices; j2++) { + const u3 = j2 / slices; + func(u3, v, p0); + vertices.push(p0.x, p0.y, p0.z); + if (u3 - EPS >= 0) { + func(u3 - EPS, v, p1); + pu.subVectors(p0, p1); + } else { + func(u3 + EPS, v, p1); + pu.subVectors(p1, p0); + } + if (v - EPS >= 0) { + func(u3, v - EPS, p1); + pv.subVectors(p0, p1); + } else { + func(u3, v + EPS, p1); + pv.subVectors(p1, p0); + } + normal.crossVectors(pu, pv).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u3, v); + } + } + for (let i = 0;i < stacks; i++) { + for (let j2 = 0;j2 < slices; j2++) { + const a = i * sliceCount + j2; + const b = i * sliceCount + j2 + 1; + const c = (i + 1) * sliceCount + j2 + 1; + const d = (i + 1) * sliceCount + j2; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } +} + +// node_modules/three/examples/jsm/geometries/ParametricGeometries.js +var ParametricGeometries = { + klein: function(v, u3, target) { + u3 *= Math.PI; + v *= 2 * Math.PI; + u3 = u3 * 2; + let x2, z2; + if (u3 < Math.PI) { + x2 = 3 * Math.cos(u3) * (1 + Math.sin(u3)) + 2 * (1 - Math.cos(u3) / 2) * Math.cos(u3) * Math.cos(v); + z2 = -8 * Math.sin(u3) - 2 * (1 - Math.cos(u3) / 2) * Math.sin(u3) * Math.cos(v); + } else { + x2 = 3 * Math.cos(u3) * (1 + Math.sin(u3)) + 2 * (1 - Math.cos(u3) / 2) * Math.cos(v + Math.PI); + z2 = -8 * Math.sin(u3); + } + const y3 = -2 * (1 - Math.cos(u3) / 2) * Math.sin(v); + target.set(x2, y3, z2); + }, + plane: function(width2, height2) { + return function(u3, v, target) { + const x2 = u3 * width2; + const y3 = 0; + const z2 = v * height2; + target.set(x2, y3, z2); + }; + }, + mobius: function(u3, t4, target) { + u3 = u3 - 0.5; + const v = 2 * Math.PI * t4; + const a = 2; + const x2 = Math.cos(v) * (a + u3 * Math.cos(v / 2)); + const y3 = Math.sin(v) * (a + u3 * Math.cos(v / 2)); + const z2 = u3 * Math.sin(v / 2); + target.set(x2, y3, z2); + }, + mobius3d: function(u3, t4, target) { + u3 *= Math.PI; + t4 *= 2 * Math.PI; + u3 = u3 * 2; + const phi = u3 / 2; + const major = 2.25, a = 0.125, b = 0.65; + let x2 = a * Math.cos(t4) * Math.cos(phi) - b * Math.sin(t4) * Math.sin(phi); + const z2 = a * Math.cos(t4) * Math.sin(phi) + b * Math.sin(t4) * Math.cos(phi); + const y3 = (major + x2) * Math.sin(u3); + x2 = (major + x2) * Math.cos(u3); + target.set(x2, y3, z2); + } +}; +ParametricGeometries.TubeGeometry = class TubeGeometry2 extends ParametricGeometry { + constructor(path, segments = 64, radius = 1, segmentsRadius = 8, closed = false) { + const numpoints = segments + 1; + const frames2 = path.computeFrenetFrames(segments, closed), tangents = frames2.tangents, normals = frames2.normals, binormals = frames2.binormals; + const position2 = new Vector3; + function ParametricTube(u3, v, target) { + v *= 2 * Math.PI; + const i = Math.floor(u3 * (numpoints - 1)); + path.getPointAt(u3, position2); + const normal = normals[i]; + const binormal = binormals[i]; + const cx = -radius * Math.cos(v); + const cy = radius * Math.sin(v); + position2.x += cx * normal.x + cy * binormal.x; + position2.y += cx * normal.y + cy * binormal.y; + position2.z += cx * normal.z + cy * binormal.z; + target.copy(position2); + } + super(ParametricTube, segments, segmentsRadius); + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; + this.path = path; + this.segments = segments; + this.radius = radius; + this.segmentsRadius = segmentsRadius; + this.closed = closed; + } +}; +ParametricGeometries.TorusKnotGeometry = class TorusKnotGeometry2 extends ParametricGeometries.TubeGeometry { + constructor(radius = 200, tube = 40, segmentsT = 64, segmentsR = 8, p = 2, q2 = 3) { + + class TorusKnotCurve extends Curve { + getPoint(t4, optionalTarget = new Vector3) { + const point = optionalTarget; + t4 *= Math.PI * 2; + const r = 0.5; + const x2 = (1 + r * Math.cos(q2 * t4)) * Math.cos(p * t4); + const y3 = (1 + r * Math.cos(q2 * t4)) * Math.sin(p * t4); + const z2 = r * Math.sin(q2 * t4); + return point.set(x2, y3, z2).multiplyScalar(radius); + } + } + const segments = segmentsT; + const radiusSegments = segmentsR; + const extrudePath = new TorusKnotCurve; + super(extrudePath, segments, tube, radiusSegments, true, false); + this.radius = radius; + this.tube = tube; + this.segmentsT = segmentsT; + this.segmentsR = segmentsR; + this.p = p; + this.q = q2; + } +}; +ParametricGeometries.SphereGeometry = class SphereGeometry2 extends ParametricGeometry { + constructor(size, u3, v) { + function sphere(u4, v2, target) { + u4 *= Math.PI; + v2 *= 2 * Math.PI; + const x2 = size * Math.sin(u4) * Math.cos(v2); + const y3 = size * Math.sin(u4) * Math.sin(v2); + const z2 = size * Math.cos(u4); + target.set(x2, y3, z2); + } + super(sphere, u3, v); + } +}; +ParametricGeometries.PlaneGeometry = class PlaneGeometry2 extends ParametricGeometry { + constructor(width2, depth, segmentsWidth, segmentsDepth) { + function plane(u3, v, target) { + const x2 = u3 * width2; + const y3 = 0; + const z2 = v * depth; + target.set(x2, y3, z2); + } + super(plane, segmentsWidth, segmentsDepth); + } +}; +// node_modules/three/examples/jsm/geometries/RoundedBoxGeometry.js +var _tempNormal = new Vector3; +// node_modules/three/examples/jsm/utils/BufferGeometryUtils.js +function toTrianglesDrawMode(geometry, drawMode) { + if (drawMode === TrianglesDrawMode) { + console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."); + return geometry; + } + if (drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode) { + let index2 = geometry.getIndex(); + if (index2 === null) { + const indices = []; + const position2 = geometry.getAttribute("position"); + if (position2 !== undefined) { + for (let i = 0;i < position2.count; i++) { + indices.push(i); + } + geometry.setIndex(indices); + index2 = geometry.getIndex(); + } else { + console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."); + return geometry; + } + } + const numberOfTriangles = index2.count - 2; + const newIndices = []; + if (drawMode === TriangleFanDrawMode) { + for (let i = 1;i <= numberOfTriangles; i++) { + newIndices.push(index2.getX(0)); + newIndices.push(index2.getX(i)); + newIndices.push(index2.getX(i + 1)); + } + } else { + for (let i = 0;i < numberOfTriangles; i++) { + if (i % 2 === 0) { + newIndices.push(index2.getX(i)); + newIndices.push(index2.getX(i + 1)); + newIndices.push(index2.getX(i + 2)); + } else { + newIndices.push(index2.getX(i + 2)); + newIndices.push(index2.getX(i + 1)); + newIndices.push(index2.getX(i)); + } + } + } + if (newIndices.length / 3 !== numberOfTriangles) { + console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles."); + } + const newGeometry = geometry.clone(); + newGeometry.setIndex(newIndices); + newGeometry.clearGroups(); + return newGeometry; + } else { + console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:", drawMode); + return geometry; + } +} +// node_modules/three/examples/jsm/helpers/VertexNormalsHelper.js +var _v14 = new Vector3; +var _v24 = new Vector3; +var _normalMatrix2 = new Matrix3; +// node_modules/three/examples/jsm/helpers/VertexTangentsHelper.js +var _v15 = new Vector3; +var _v25 = new Vector3; +// node_modules/three/examples/jsm/interactive/HTMLMesh.js +var canvases = new WeakMap; +// node_modules/three/examples/jsm/interactive/InteractiveGroup.js +var _pointer2 = new Vector2; +var _raycaster3 = new Raycaster; +// node_modules/three/examples/jsm/interactive/SelectionBox.js +var _frustum2 = new Frustum; +var _center3 = new Vector3; +var _tmpPoint = new Vector3; +var _vecNear = new Vector3; +var _vecTopLeft = new Vector3; +var _vecTopRight = new Vector3; +var _vecDownRight = new Vector3; +var _vecDownLeft = new Vector3; +var _vecFarTopLeft = new Vector3; +var _vecFarTopRight = new Vector3; +var _vecFarDownRight = new Vector3; +var _vecFarDownLeft = new Vector3; +var _vectemp1 = new Vector3; +var _vectemp2 = new Vector3; +var _vectemp3 = new Vector3; +var _matrix3 = new Matrix4; +var _quaternion3 = new Quaternion; +var _scale2 = new Vector3; +// node_modules/three/examples/jsm/lights/RectAreaLightTexturesLib.js +class RectAreaLightTexturesLib { + static init() { + const LTC_MAT_1 = [1, 0, 0, 0.00002, 1, 0, 0, 0.000503905, 1, 0, 0, 0.00201562, 1, 0, 0, 0.00453516, 1, 0, 0, 0.00806253, 1, 0, 0, 0.0125978, 1, 0, 0, 0.018141, 1, 0, 0, 0.0246924, 1, 0, 0, 0.0322525, 1, 0, 0, 0.0408213, 1, 0, 0, 0.0503999, 1, 0, 0, 0.0609894, 1, 0, 0, 0.0725906, 1, 0, 0, 0.0852058, 1, 0, 0, 0.0988363, 1, 0, 0, 0.113484, 1, 0, 0, 0.129153, 1, 0, 0, 0.145839, 1, 0, 0, 0.163548, 1, 0, 0, 0.182266, 1, 0, 0, 0.201942, 1, 0, 0, 0.222314, 1, 0, 0, 0.241906, 1, 0, 0, 0.262314, 1, 0, 0, 0.285754, 1, 0, 0, 0.310159, 1, 0, 0, 0.335426, 1, 0, 0, 0.361341, 1, 0, 0, 0.387445, 1, 0, 0, 0.412784, 1, 0, 0, 0.438197, 1, 0, 0, 0.466966, 1, 0, 0, 0.49559, 1, 0, 0, 0.523448, 1, 0, 0, 0.549938, 1, 0, 0, 0.57979, 1, 0, 0, 0.608746, 1, 0, 0, 0.636185, 1, 0, 0, 0.664748, 1, 0, 0, 0.69313, 1, 0, 0, 0.71966, 1, 0, 0, 0.747662, 1, 0, 0, 0.774023, 1, 0, 0, 0.799775, 1, 0, 0, 0.825274, 1, 0, 0, 0.849156, 1, 0, 0, 0.873248, 1, 0, 0, 0.89532, 1, 0, 0, 0.917565, 1, 0, 0, 0.937863, 1, 0, 0, 0.958139, 1, 0, 0, 0.976563, 1, 0, 0, 0.994658, 1, 0, 0, 1.0112, 1, 0, 0, 1.02712, 1, 0, 0, 1.04189, 1, 0, 0, 1.05568, 1, 0, 0, 1.06877, 1, 0, 0, 1.08058, 1, 0, 0, 1.09194, 1, 0, 0, 1.10191, 1, 0, 0, 1.11161, 1, 0, 0, 1.1199, 1, 0, 0, 1.12813, 0.999547, -0.000000448815, 0.0224417, 0.0000199902, 0.999495, -0.0000113079, 0.0224406, 0.000503651, 0.999496, -0.0000452317, 0.0224406, 0.00201461, 0.999496, -0.000101772, 0.0224406, 0.00453287, 0.999495, -0.000180928, 0.0224406, 0.00805845, 0.999497, -0.000282702, 0.0224406, 0.0125914, 0.999496, -0.000407096, 0.0224406, 0.0181319, 0.999498, -0.000554114, 0.0224406, 0.02468, 0.999499, -0.000723768, 0.0224406, 0.0322363, 0.999495, -0.000916058, 0.0224405, 0.0408009, 0.999499, -0.00113101, 0.0224408, 0.050375, 0.999494, -0.00136863, 0.0224405, 0.0609586, 0.999489, -0.00162896, 0.0224401, 0.0725537, 0.999489, -0.00191201, 0.0224414, 0.0851619, 0.999498, -0.00221787, 0.0224413, 0.0987867, 0.999492, -0.00254642, 0.0224409, 0.113426, 0.999507, -0.00289779, 0.0224417, 0.129088, 0.999494, -0.0032716, 0.0224386, 0.145767, 0.999546, -0.0036673, 0.0224424, 0.163472, 0.999543, -0.00408166, 0.0224387, 0.182182, 0.999499, -0.00450056, 0.0224338, 0.201843, 0.999503, -0.00483661, 0.0224203, 0.222198, 0.999546, -0.00452928, 0.022315, 0.241714, 0.999508, -0.00587403, 0.0224329, 0.262184, 0.999509, -0.00638806, 0.0224271, 0.285609, 0.999501, -0.00691028, 0.0224166, 0.309998, 0.999539, -0.00741979, 0.0223989, 0.335262, 0.999454, -0.00786282, 0.0223675, 0.361154, 0.999529, -0.00811928, 0.0222828, 0.387224, 0.999503, -0.00799941, 0.0221063, 0.41252, 0.999561, -0.00952753, 0.0223057, 0.438006, 0.999557, -0.0099134, 0.0222065, 0.466735, 0.999541, -0.0100935, 0.0220402, 0.495332, 0.999562, -0.00996821, 0.0218067, 0.523197, 0.999556, -0.0105031, 0.0217096, 0.550223, 0.999561, -0.0114191, 0.0217215, 0.579498, 0.999588, -0.0111818, 0.0213357, 0.608416, 0.999633, -0.0107725, 0.0208689, 0.635965, 0.999527, -0.0121671, 0.0210149, 0.664476, 0.999508, -0.0116005, 0.020431, 0.692786, 0.999568, -0.0115604, 0.0199791, 0.719709, 0.999671, -0.0121117, 0.0197415, 0.74737, 0.999688, -0.0110769, 0.0188846, 0.773692, 0.99962, -0.0122368, 0.0188452, 0.799534, 0.999823, -0.0110325, 0.0178001, 0.825046, 0.999599, -0.0114923, 0.0174221, 0.849075, 0.999619, -0.0105923, 0.0164345, 0.872999, 0.999613, -0.0105988, 0.0158227, 0.895371, 0.99964, -0.00979861, 0.0148131, 0.917364, 0.99977, -0.00967238, 0.0140721, 0.938002, 0.999726, -0.00869175, 0.0129543, 0.957917, 0.99973, -0.00866872, 0.0122329, 0.976557, 0.999773, -0.00731956, 0.0108958, 0.994459, 0.999811, -0.00756027, 0.0102715, 1.01118, 0.999862, -0.00583732, 0.00878781, 1.02701, 0.999835, -0.00631438, 0.00827529, 1.04186, 0.999871, -0.00450785, 0.00674583, 1.05569, 0.999867, -0.00486079, 0.00621041, 1.06861, 0.999939, -0.00322072, 0.00478301, 1.08064, 0.999918, -0.00318199, 0.00406395, 1.09181, 1.00003, -0.00193348, 0.00280682, 1.10207, 0.999928, -0.00153729, 0.00198741, 1.11152, 0.999933, -0.000623666, 0.000917714, 1.12009, 1, -0.00000102387, 0.000000907581, 1.12813, 0.997866, -0.000000896716, 0.0448334, 0.0000199584, 0.997987, -0.0000225945, 0.0448389, 0.000502891, 0.997987, -0.0000903781, 0.0448388, 0.00201156, 0.997985, -0.000203351, 0.0448388, 0.00452602, 0.997986, -0.000361514, 0.0448388, 0.00804629, 0.997987, -0.00056487, 0.0448389, 0.0125724, 0.997988, -0.000813423, 0.0448389, 0.0181045, 0.997984, -0.00110718, 0.0448387, 0.0246427, 0.997985, -0.00144616, 0.0448388, 0.0321875, 0.997987, -0.00183038, 0.044839, 0.0407392, 0.997983, -0.00225987, 0.0448387, 0.0502986, 0.997991, -0.00273467, 0.0448389, 0.0608667, 0.997984, -0.00325481, 0.0448384, 0.0724444, 0.998002, -0.00382043, 0.044839, 0.0850348, 0.997997, -0.00443145, 0.0448396, 0.0986372, 0.998007, -0.00508796, 0.0448397, 0.113255, 0.998008, -0.00578985, 0.04484, 0.128891, 0.998003, -0.00653683, 0.0448384, 0.145548, 0.997983, -0.00732713, 0.0448358, 0.163221, 0.997985, -0.00815454, 0.0448358, 0.181899, 0.998005, -0.00898985, 0.0448286, 0.201533, 0.998026, -0.00964404, 0.0447934, 0.221821, 0.998055, -0.00922677, 0.044611, 0.241282, 0.99804, -0.0117361, 0.0448245, 0.261791, 0.998048, -0.0127628, 0.0448159, 0.285181, 0.998088, -0.0138055, 0.0447996, 0.30954, 0.998058, -0.0148206, 0.0447669, 0.334751, 0.998099, -0.0156998, 0.044697, 0.36061, 0.998116, -0.0161976, 0.0445122, 0.386603, 0.998195, -0.015945, 0.0441711, 0.411844, 0.998168, -0.0183947, 0.0444255, 0.43773, 0.998184, -0.0197913, 0.0443809, 0.466009, 0.998251, -0.0201426, 0.0440689, 0.494574, 0.998305, -0.0198847, 0.0435632, 0.522405, 0.998273, -0.0210577, 0.043414, 0.549967, 0.998254, -0.0227901, 0.0433943, 0.578655, 0.998349, -0.0223108, 0.0426529, 0.60758, 0.99843, -0.0223088, 0.042, 0.635524, 0.998373, -0.0241141, 0.0418987, 0.663621, 0.998425, -0.0231446, 0.0408118, 0.691906, 0.998504, -0.0233684, 0.0400565, 0.719339, 0.998443, -0.0241652, 0.0394634, 0.74643, 0.99848, -0.0228715, 0.0380002, 0.773086, 0.998569, -0.023519, 0.0372322, 0.798988, 0.998619, -0.0223108, 0.0356468, 0.824249, 0.998594, -0.0223105, 0.034523, 0.848808, 0.998622, -0.0213426, 0.0328887, 0.87227, 0.998669, -0.0207912, 0.0314374, 0.895157, 0.998705, -0.0198416, 0.0296925, 0.916769, 0.998786, -0.0189168, 0.0279634, 0.937773, 0.998888, -0.0178811, 0.0261597, 0.957431, 0.99906, -0.0166845, 0.0242159, 0.976495, 0.999038, -0.0155464, 0.0222638, 0.994169, 0.999237, -0.0141349, 0.0201967, 1.01112, 0.999378, -0.0129324, 0.0181744, 1.02692, 0.999433, -0.0113192, 0.0159898, 1.04174, 0.999439, -0.0101244, 0.0140385, 1.05559, 0.999614, -0.00837456, 0.0117826, 1.06852, 0.999722, -0.00721769, 0.00983745, 1.08069, 0.999817, -0.00554067, 0.00769002, 1.09176, 0.99983, -0.00426961, 0.005782, 1.10211, 0.999964, -0.00273904, 0.00374503, 1.11152, 1.00001, -0.00136739, 0.00187176, 1.12031, 0.999946, 0.0000393227, -0.000028919, 1.12804, 0.995847, -0.0000013435, 0.0671785, 0.000019916, 0.995464, -0.0000338387, 0.0671527, 0.000501622, 0.99547, -0.000135355, 0.0671531, 0.00200649, 0.995471, -0.00030455, 0.0671532, 0.00451461, 0.99547, -0.000541423, 0.0671531, 0.008026, 0.995471, -0.00084598, 0.0671531, 0.0125407, 0.99547, -0.00121823, 0.0671531, 0.0180589, 0.99547, -0.00165817, 0.0671531, 0.0245806, 0.995463, -0.00216583, 0.0671526, 0.0321062, 0.995468, -0.00274127, 0.0671527, 0.0406366, 0.995474, -0.00338447, 0.0671534, 0.0501717, 0.995473, -0.00409554, 0.0671533, 0.0607131, 0.995478, -0.00487451, 0.0671531, 0.0722618, 0.995476, -0.00572148, 0.0671532, 0.0848191, 0.995477, -0.00663658, 0.0671539, 0.0983882, 0.995498, -0.00761986, 0.0671541, 0.112972, 0.995509, -0.00867094, 0.0671542, 0.128568, 0.995509, -0.00978951, 0.0671531, 0.145183, 0.995503, -0.0109725, 0.0671491, 0.162808, 0.995501, -0.012211, 0.0671465, 0.181441, 0.99553, -0.0134565, 0.0671371, 0.201015, 0.99555, -0.014391, 0.0670831, 0.221206, 0.99558, -0.014351, 0.0668883, 0.240813, 0.995577, -0.0173997, 0.0671055, 0.261257, 0.995602, -0.0191111, 0.0671178, 0.284467, 0.995623, -0.0206705, 0.0670946, 0.308765, 0.995658, -0.022184, 0.0670472, 0.333905, 0.995705, -0.0234832, 0.0669417, 0.359677, 0.995719, -0.0241933, 0.0666714, 0.385554, 0.995786, -0.0243539, 0.066266, 0.410951, 0.995887, -0.0271866, 0.0664367, 0.437163, 0.995944, -0.0296012, 0.0664931, 0.464842, 0.996004, -0.0301045, 0.0660105, 0.49332, 0.996128, -0.0298311, 0.0652694, 0.521131, 0.996253, -0.0316426, 0.0650739, 0.549167, 0.996244, -0.0339043, 0.0649433, 0.57737, 0.996309, -0.033329, 0.0638926, 0.606073, 0.996417, -0.0338935, 0.0630849, 0.634527, 0.996372, -0.0353104, 0.0625083, 0.66256, 0.996542, -0.0348942, 0.0611986, 0.690516, 0.996568, -0.0351614, 0.060069, 0.718317, 0.996711, -0.0354317, 0.0588522, 0.74528, 0.996671, -0.0349513, 0.0571902, 0.772061, 0.996865, -0.0345622, 0.0555321, 0.798089, 0.996802, -0.0342566, 0.0537816, 0.823178, 0.996992, -0.0330862, 0.0516095, 0.847949, 0.996944, -0.0324666, 0.0495537, 0.871431, 0.997146, -0.0309544, 0.0470302, 0.894357, 0.997189, -0.0299372, 0.0446043, 0.916142, 0.997471, -0.0281389, 0.0418812, 0.937193, 0.997515, -0.0268702, 0.0391823, 0.957, 0.997812, -0.0247166, 0.0361338, 0.975936, 0.998027, -0.0233525, 0.0333945, 0.99391, 0.998233, -0.0209839, 0.0301917, 1.01075, 0.998481, -0.0194309, 0.027271, 1.02669, 0.998859, -0.0169728, 0.0240162, 1.04173, 0.99894, -0.0152322, 0.0210517, 1.05551, 0.999132, -0.0127497, 0.0178632, 1.06856, 0.999369, -0.0108282, 0.014787, 1.08054, 0.999549, -0.00845886, 0.0116185, 1.09185, 0.999805, -0.0063937, 0.00867209, 1.10207, 0.99985, -0.00414582, 0.00566823, 1.1117, 0.999912, -0.00207443, 0.00277562, 1.12022, 1.00001, 0.0000870226, -0.000053766, 1.12832, 0.991943, -0.00000178672, 0.0893382, 0.0000198384, 0.991952, -0.0000450183, 0.089339, 0.000499849, 0.991956, -0.000180074, 0.0893394, 0.0019994, 0.991955, -0.000405167, 0.0893393, 0.00449867, 0.991953, -0.000720298, 0.0893391, 0.00799764, 0.991955, -0.00112548, 0.0893393, 0.0124964, 0.991957, -0.0016207, 0.0893395, 0.0179951, 0.991958, -0.00220601, 0.0893396, 0.0244939, 0.991947, -0.00288137, 0.0893385, 0.0319929, 0.991962, -0.00364693, 0.0893399, 0.0404933, 0.991965, -0.00450264, 0.0893399, 0.049995, 0.99198, -0.00544862, 0.0893411, 0.0604995, 0.99197, -0.00648491, 0.0893397, 0.0720074, 0.991976, -0.00761164, 0.089341, 0.0845207, 0.99198, -0.00882891, 0.0893405, 0.0980413, 0.991982, -0.0101367, 0.0893396, 0.112571, 0.992008, -0.011535, 0.0893415, 0.128115, 0.992026, -0.0130228, 0.0893414, 0.144672, 0.992064, -0.0145966, 0.0893418, 0.162241, 0.992041, -0.0162421, 0.0893359, 0.180801, 0.992086, -0.0178888, 0.0893214, 0.200302, 0.992157, -0.0190368, 0.0892401, 0.220332, 0.992181, -0.0195584, 0.0890525, 0.240144, 0.992175, -0.0227257, 0.0892153, 0.260728, 0.99221, -0.0254195, 0.089304, 0.283473, 0.99222, -0.0274883, 0.0892703, 0.307673, 0.992317, -0.0294905, 0.0892027, 0.332729, 0.992374, -0.0311861, 0.0890577, 0.358387, 0.992505, -0.0320656, 0.0886994, 0.384102, 0.992568, -0.0329715, 0.0883198, 0.409767, 0.992675, -0.036006, 0.0883602, 0.436145, 0.992746, -0.0392897, 0.0884591, 0.463217, 0.992873, -0.0399337, 0.0878287, 0.491557, 0.992934, -0.040231, 0.0870108, 0.519516, 0.993091, -0.0422013, 0.0865857, 0.547741, 0.993259, -0.0443503, 0.0861937, 0.575792, 0.993455, -0.0446368, 0.0851187, 0.604233, 0.993497, -0.0454299, 0.0840576, 0.632925, 0.993694, -0.0463296, 0.0829671, 0.660985, 0.993718, -0.0470619, 0.0817185, 0.688714, 0.993973, -0.0468838, 0.0800294, 0.716743, 0.994207, -0.046705, 0.0781286, 0.74377, 0.994168, -0.0469698, 0.0763337, 0.77042, 0.9945, -0.0456816, 0.0738184, 0.796659, 0.994356, -0.0455518, 0.0715545, 0.821868, 0.994747, -0.0439488, 0.0686085, 0.846572, 0.994937, -0.0430056, 0.065869, 0.870435, 0.995142, -0.0413414, 0.0626446, 0.893272, 0.995451, -0.0396521, 0.05929, 0.915376, 0.995445, -0.0378453, 0.0558503, 0.936196, 0.995967, -0.0355219, 0.0520949, 0.956376, 0.996094, -0.0335146, 0.048377, 0.975327, 0.996622, -0.030682, 0.0442575, 0.993471, 0.996938, -0.0285504, 0.0404693, 1.01052, 0.997383, -0.0253399, 0.0360903, 1.02637, 0.997714, -0.0231651, 0.0322176, 1.04139, 0.998249, -0.0198138, 0.0278433, 1.05542, 0.998596, -0.0174337, 0.0238759, 1.06846, 0.998946, -0.0141349, 0.0195944, 1.08056, 0.99928, -0.0115603, 0.0156279, 1.09181, 0.999507, -0.00839065, 0.0114607, 1.10213, 0.999697, -0.005666, 0.00763325, 1.11169, 0.999869, -0.00269902, 0.00364946, 1.12042, 1.00001, 0.0000623836, -0.0000319288, 1.12832, 0.987221, -0.00000222675, 0.111332, 0.0000197456, 0.98739, -0.0000561116, 0.111351, 0.000497563, 0.987448, -0.000224453, 0.111357, 0.00199031, 0.987441, -0.000505019, 0.111357, 0.0044782, 0.987442, -0.000897816, 0.111357, 0.00796129, 0.987442, -0.00140284, 0.111357, 0.0124396, 0.987444, -0.00202012, 0.111357, 0.0179132, 0.987442, -0.00274964, 0.111357, 0.0243824, 0.987446, -0.00359147, 0.111357, 0.0318474, 0.987435, -0.00454562, 0.111356, 0.0403086, 0.987461, -0.00561225, 0.111358, 0.0497678, 0.987458, -0.00679125, 0.111358, 0.0602239, 0.987443, -0.0080828, 0.111356, 0.0716792, 0.987476, -0.0094872, 0.111358, 0.0841364, 0.98749, -0.0110044, 0.111361, 0.097597, 0.987508, -0.0126344, 0.111362, 0.112062, 0.987494, -0.0143767, 0.111357, 0.127533, 0.987526, -0.0162307, 0.111359, 0.144015, 0.987558, -0.0181912, 0.111361, 0.161502, 0.987602, -0.0202393, 0.111355, 0.179979, 0.987692, -0.022273, 0.111346, 0.199386, 0.987702, -0.0235306, 0.111215, 0.219183, 0.987789, -0.0247628, 0.111061, 0.239202, 0.987776, -0.0280668, 0.111171, 0.259957, 0.987856, -0.0316751, 0.111327, 0.282198, 0.987912, -0.0342468, 0.111282, 0.306294, 0.988, -0.0367205, 0.111198, 0.331219, 0.988055, -0.0387766, 0.110994, 0.356708, 0.988241, -0.0397722, 0.110547, 0.382234, 0.988399, -0.0416076, 0.110198, 0.408227, 0.988539, -0.0448192, 0.110137, 0.434662, 0.988661, -0.0483793, 0.110143, 0.461442, 0.988967, -0.0495895, 0.109453, 0.489318, 0.989073, -0.0506797, 0.108628, 0.517516, 0.989274, -0.0526953, 0.108003, 0.545844, 0.989528, -0.054578, 0.107255, 0.573823, 0.989709, -0.0561503, 0.106294, 0.601944, 0.989991, -0.056866, 0.104896, 0.630855, 0.990392, -0.0572914, 0.103336, 0.658925, 0.990374, -0.0586224, 0.10189, 0.686661, 0.990747, -0.0584764, 0.099783, 0.714548, 0.991041, -0.0582662, 0.0974309, 0.74186, 0.991236, -0.0584118, 0.0951678, 0.768422, 0.991585, -0.0573055, 0.0921581, 0.794817, 0.991984, -0.0564241, 0.0891167, 0.820336, 0.9921, -0.0553608, 0.085805, 0.84493, 0.992749, -0.0533816, 0.0820354, 0.868961, 0.99288, -0.0518661, 0.0782181, 0.891931, 0.993511, -0.0492492, 0.0738935, 0.914186, 0.993617, -0.0471956, 0.0696402, 0.93532, 0.99411, -0.044216, 0.0649659, 0.95543, 0.994595, -0.0416654, 0.0603177, 0.974685, 0.994976, -0.0384314, 0.0553493, 0.992807, 0.995579, -0.0353491, 0.0503942, 1.00996, 0.996069, -0.0319787, 0.0452123, 1.02606, 0.996718, -0.028472, 0.0400112, 1.04114, 0.997173, -0.0250789, 0.0349456, 1.05517, 0.997818, -0.0213326, 0.029653, 1.0683, 0.998318, -0.0178509, 0.024549, 1.0805, 0.998853, -0.0141118, 0.0194197, 1.09177, 0.999218, -0.0105914, 0.0143869, 1.1022, 0.999594, -0.00693474, 0.00943517, 1.11175, 0.99975, -0.00340478, 0.00464051, 1.12056, 1.00001, 0.000109172, -0.000112821, 1.12853, 0.983383, -0.00000266524, 0.133358, 0.0000196534, 0.981942, -0.0000671009, 0.133162, 0.000494804, 0.981946, -0.000268405, 0.133163, 0.00197923, 0.981944, -0.000603912, 0.133163, 0.00445326, 0.981941, -0.00107362, 0.133162, 0.00791693, 0.981946, -0.00167755, 0.133163, 0.0123703, 0.981944, -0.00241569, 0.133162, 0.0178135, 0.981945, -0.00328807, 0.133163, 0.0242466, 0.981945, -0.00429472, 0.133162, 0.03167, 0.981955, -0.00543573, 0.133164, 0.0400846, 0.981951, -0.00671105, 0.133163, 0.0494901, 0.981968, -0.00812092, 0.133165, 0.0598886, 0.981979, -0.00966541, 0.133166, 0.0712811, 0.981996, -0.0113446, 0.133168, 0.083669, 0.982014, -0.0131585, 0.133169, 0.0970533, 0.982011, -0.0151073, 0.133167, 0.111438, 0.982062, -0.0171906, 0.133172, 0.126826, 0.9821, -0.0194067, 0.133175, 0.143215, 0.982149, -0.0217502, 0.133176, 0.160609, 0.982163, -0.0241945, 0.133173, 0.178981, 0.982247, -0.0265907, 0.133148, 0.198249, 0.982291, -0.027916, 0.132974, 0.217795, 0.982396, -0.0299663, 0.132868, 0.238042, 0.982456, -0.0334544, 0.132934, 0.258901, 0.982499, -0.0378636, 0.133137, 0.280639, 0.982617, -0.0409274, 0.133085, 0.304604, 0.98274, -0.0438523, 0.132985, 0.329376, 0.982944, -0.0462288, 0.132728, 0.354697, 0.98308, -0.0475995, 0.132228, 0.380102, 0.983391, -0.0501901, 0.131924, 0.406256, 0.983514, -0.0535899, 0.131737, 0.432735, 0.98373, -0.0571858, 0.131567, 0.459359, 0.984056, -0.0592353, 0.130932, 0.486637, 0.984234, -0.0610488, 0.130092, 0.51509, 0.984748, -0.0630758, 0.12923, 0.543461, 0.985073, -0.0647398, 0.128174, 0.571376, 0.985195, -0.0671941, 0.127133, 0.599414, 0.985734, -0.0681345, 0.125576, 0.628134, 0.986241, -0.0686089, 0.123639, 0.656399, 0.986356, -0.0698511, 0.121834, 0.684258, 0.986894, -0.0700931, 0.119454, 0.711818, 0.987382, -0.0698321, 0.116718, 0.739511, 0.988109, -0.0693975, 0.113699, 0.766267, 0.988363, -0.0689584, 0.110454, 0.792456, 0.989112, -0.0672353, 0.106602, 0.81813, 0.989241, -0.0662034, 0.10267, 0.842889, 0.990333, -0.0638938, 0.0981381, 0.867204, 0.990591, -0.0618534, 0.0935388, 0.89038, 0.991106, -0.0593117, 0.088553, 0.912576, 0.991919, -0.0562676, 0.0832187, 0.934118, 0.992111, -0.0534085, 0.0778302, 0.954254, 0.992997, -0.0495459, 0.0720453, 0.973722, 0.993317, -0.0463707, 0.0663458, 0.991949, 0.994133, -0.0421245, 0.0601883, 1.00936, 0.994705, -0.0384977, 0.0542501, 1.02559, 0.995495, -0.0340956, 0.0479862, 1.04083, 0.996206, -0.030105, 0.041887, 1.05497, 0.996971, -0.0256095, 0.0355355, 1.06824, 0.997796, -0.0213932, 0.0293655, 1.08056, 0.998272, -0.0169612, 0.0232926, 1.09182, 0.998857, -0.0126756, 0.0172786, 1.10219, 0.99939, -0.00832486, 0.0113156, 1.11192, 0.999752, -0.00410826, 0.00557892, 1.12075, 1, 0.000150957, -0.000119101, 1.12885, 0.975169, -0.00000309397, 0.154669, 0.0000195073, 0.975439, -0.0000779608, 0.154712, 0.000491534, 0.975464, -0.000311847, 0.154716, 0.00196617, 0.975464, -0.000701656, 0.154716, 0.00442387, 0.975462, -0.0012474, 0.154715, 0.0078647, 0.975461, -0.00194906, 0.154715, 0.0122886, 0.975464, -0.00280667, 0.154715, 0.0176959, 0.975468, -0.00382025, 0.154716, 0.0240867, 0.975471, -0.00498985, 0.154716, 0.0314612, 0.975472, -0.00631541, 0.154717, 0.0398199, 0.975486, -0.00779719, 0.154718, 0.0491639, 0.975489, -0.00943505, 0.154718, 0.0594932, 0.975509, -0.0112295, 0.154721, 0.0708113, 0.97554, -0.0131802, 0.154724, 0.0831176, 0.975557, -0.0152876, 0.154726, 0.096415, 0.975585, -0.0175512, 0.154728, 0.110705, 0.975605, -0.0199713, 0.154729, 0.125992, 0.975645, -0.0225447, 0.154729, 0.142272, 0.975711, -0.0252649, 0.154735, 0.159549, 0.975788, -0.0280986, 0.154736, 0.177805, 0.975872, -0.0308232, 0.154704, 0.196911, 0.975968, -0.0324841, 0.154525, 0.216324, 0.976063, -0.0351281, 0.154432, 0.236628, 0.976157, -0.0388618, 0.15446, 0.257539, 0.976204, -0.0437704, 0.154665, 0.278975, 0.976358, -0.047514, 0.154652, 0.302606, 0.976571, -0.0508638, 0.154535, 0.327204, 0.976725, -0.0534995, 0.154221, 0.352276, 0.977013, -0.0555547, 0.153737, 0.377696, 0.977294, -0.0586728, 0.153403, 0.403855, 0.977602, -0.0622715, 0.15312, 0.430333, 0.977932, -0.0658166, 0.152755, 0.456855, 0.978241, -0.0689877, 0.152233, 0.483668, 0.978602, -0.0712805, 0.15132, 0.512097, 0.979234, -0.0732775, 0.150235, 0.540455, 0.97977, -0.075163, 0.148978, 0.568486, 0.979995, -0.0778026, 0.147755, 0.596524, 0.98078, -0.0791854, 0.146019, 0.624825, 0.981628, -0.0799666, 0.143906, 0.653403, 0.982067, -0.0808532, 0.141561, 0.681445, 0.98271, -0.0816024, 0.139025, 0.708918, 0.983734, -0.0812511, 0.135764, 0.736594, 0.98431, -0.0806201, 0.132152, 0.763576, 0.985071, -0.0801605, 0.12846, 0.789797, 0.98618, -0.0784208, 0.124084, 0.815804, 0.986886, -0.0766643, 0.1193, 0.840869, 0.987485, -0.0747744, 0.114236, 0.864952, 0.988431, -0.0716701, 0.108654, 0.888431, 0.988886, -0.0691609, 0.102994, 0.910963, 0.990024, -0.0654048, 0.0967278, 0.932629, 0.990401, -0.0619765, 0.090384, 0.95313, 0.991093, -0.0579296, 0.0837885, 0.972587, 0.992018, -0.0536576, 0.0770171, 0.991184, 0.992536, -0.0493719, 0.0701486, 1.00863, 0.993421, -0.0444813, 0.062953, 1.02494, 0.993928, -0.040008, 0.0560455, 1.04017, 0.994994, -0.0347982, 0.04856, 1.05463, 0.995866, -0.0301017, 0.0416152, 1.06807, 0.996916, -0.0248225, 0.0342597, 1.08039, 0.997766, -0.0199229, 0.0271668, 1.09177, 0.998479, -0.0147422, 0.0201387, 1.10235, 0.99921, -0.00980173, 0.0131944, 1.11206, 0.999652, -0.0047426, 0.00640712, 1.12104, 0.999998, 0.0000891673, -0.00010379, 1.12906, 0.967868, -0.00000351885, 0.175947, 0.0000193569, 0.968001, -0.0000886733, 0.175972, 0.000487782, 0.96801, -0.000354697, 0.175973, 0.00195115, 0.968012, -0.000798063, 0.175974, 0.00439006, 0.968011, -0.00141879, 0.175973, 0.00780461, 0.968011, -0.00221686, 0.175973, 0.0121948, 0.968016, -0.00319231, 0.175974, 0.0175607, 0.968019, -0.00434515, 0.175974, 0.0239027, 0.968018, -0.00567538, 0.175974, 0.0312208, 0.968033, -0.00718308, 0.175977, 0.0395158, 0.968049, -0.00886836, 0.175979, 0.0487885, 0.968047, -0.0107312, 0.175978, 0.0590394, 0.968072, -0.0127719, 0.175981, 0.0702705, 0.968108, -0.0149905, 0.175986, 0.0824836, 0.968112, -0.0173866, 0.175985, 0.0956783, 0.968173, -0.0199611, 0.175993, 0.109862, 0.96827, -0.0227128, 0.176008, 0.125033, 0.968292, -0.025639, 0.17601, 0.141193, 0.968339, -0.0287299, 0.176007, 0.158336, 0.968389, -0.0319399, 0.176001, 0.176441, 0.968501, -0.034941, 0.175962, 0.195359, 0.968646, -0.0370812, 0.175793, 0.214686, 0.968789, -0.0402329, 0.175708, 0.234973, 0.96886, -0.0442601, 0.1757, 0.255871, 0.969013, -0.049398, 0.175876, 0.277238, 0.969242, -0.0539932, 0.17594, 0.300326, 0.969419, -0.0577299, 0.175781, 0.324702, 0.969763, -0.0605643, 0.175432, 0.349527, 0.970093, -0.0634488, 0.174992, 0.374976, 0.970361, -0.0670589, 0.174611, 0.401097, 0.970825, -0.0708246, 0.174226, 0.427496, 0.971214, -0.0742871, 0.173684, 0.453858, 0.971622, -0.0782608, 0.173186, 0.480637, 0.972175, -0.0813151, 0.172288, 0.508655, 0.972944, -0.0832678, 0.170979, 0.536973, 0.973595, -0.0855964, 0.169573, 0.565138, 0.974345, -0.0882163, 0.168152, 0.593222, 0.975233, -0.0901671, 0.166314, 0.621201, 0.976239, -0.0912111, 0.163931, 0.649919, 0.977289, -0.0916959, 0.161106, 0.678011, 0.978076, -0.0927061, 0.158272, 0.705717, 0.979533, -0.0925562, 0.15475, 0.733228, 0.980335, -0.0918159, 0.150638, 0.760454, 0.981808, -0.0908508, 0.146201, 0.786918, 0.983061, -0.0896172, 0.141386, 0.812953, 0.984148, -0.0871588, 0.135837, 0.838281, 0.985047, -0.0850624, 0.130135, 0.862594, 0.986219, -0.0818541, 0.123882, 0.88633, 0.987043, -0.0784523, 0.117126, 0.908952, 0.988107, -0.0749601, 0.110341, 0.930744, 0.988955, -0.0703548, 0.102885, 0.951728, 0.989426, -0.0662798, 0.0954167, 0.971166, 0.990421, -0.0610834, 0.0876331, 0.989984, 0.991032, -0.0562936, 0.0797785, 1.00765, 0.992041, -0.0508154, 0.0718166, 1.02434, 0.992794, -0.0454045, 0.0637125, 1.03976, 0.993691, -0.0398194, 0.0555338, 1.05418, 0.994778, -0.0341482, 0.0473388, 1.06772, 0.995915, -0.028428, 0.0391016, 1.08028, 0.997109, -0.022642, 0.0309953, 1.09185, 0.998095, -0.0168738, 0.0230288, 1.10247, 0.998985, -0.0111274, 0.0150722, 1.11229, 0.999581, -0.00543881, 0.00740605, 1.12131, 1.00003, 0.000162239, -0.000105549, 1.12946, 0.959505, -0.00000393734, 0.196876, 0.0000191893, 0.959599, -0.0000992157, 0.196895, 0.000483544, 0.959641, -0.000396868, 0.196903, 0.0019342, 0.959599, -0.000892948, 0.196895, 0.00435193, 0.959603, -0.00158747, 0.196896, 0.0077368, 0.959604, -0.00248042, 0.196896, 0.0120888, 0.959605, -0.00357184, 0.196896, 0.0174082, 0.959605, -0.00486169, 0.196896, 0.0236949, 0.959613, -0.00635008, 0.196897, 0.0309497, 0.959619, -0.00803696, 0.196898, 0.0391725, 0.959636, -0.00992255, 0.196901, 0.0483649, 0.959634, -0.0120067, 0.1969, 0.0585266, 0.959675, -0.0142898, 0.196906, 0.0696609, 0.959712, -0.0167717, 0.196911, 0.0817678, 0.959752, -0.0194524, 0.196918, 0.0948494, 0.959807, -0.0223321, 0.196925, 0.10891, 0.959828, -0.0254091, 0.196924, 0.123947, 0.959906, -0.0286815, 0.196934, 0.139968, 0.960005, -0.0321371, 0.196944, 0.156968, 0.960071, -0.0357114, 0.196936, 0.17491, 0.960237, -0.0389064, 0.196882, 0.193597, 0.960367, -0.041623, 0.196731, 0.21285, 0.960562, -0.0452655, 0.196654, 0.233075, 0.960735, -0.0496207, 0.196643, 0.253941, 0.960913, -0.0549379, 0.196774, 0.275278, 0.961121, -0.0603414, 0.196893, 0.297733, 0.96139, -0.0644244, 0.196717, 0.321877, 0.961818, -0.067556, 0.196314, 0.346476, 0.962175, -0.0712709, 0.195917, 0.371907, 0.96255, -0.0752848, 0.1955, 0.397916, 0.963164, -0.0792073, 0.195026, 0.424229, 0.963782, -0.0828225, 0.194424, 0.450637, 0.964306, -0.0873119, 0.193831, 0.477288, 0.964923, -0.0911051, 0.192973, 0.504716, 0.966048, -0.093251, 0.19151, 0.533053, 0.967024, -0.0958983, 0.190013, 0.561366, 0.968038, -0.09835, 0.188253, 0.589464, 0.969152, -0.100754, 0.186257, 0.617433, 0.970557, -0.102239, 0.183775, 0.645801, 0.972104, -0.102767, 0.180645, 0.674278, 0.973203, -0.103492, 0.177242, 0.702004, 0.975123, -0.103793, 0.17345, 0.729529, 0.97641, -0.102839, 0.168886, 0.756712, 0.978313, -0.101687, 0.163892, 0.783801, 0.980036, -0.100314, 0.158439, 0.809671, 0.981339, -0.097836, 0.152211, 0.835402, 0.982794, -0.0950006, 0.145679, 0.860081, 0.984123, -0.0920994, 0.138949, 0.883757, 0.984918, -0.0878641, 0.131283, 0.90685, 0.985999, -0.083939, 0.123464, 0.928786, 0.987151, -0.0791234, 0.115324, 0.94983, 0.987827, -0.0739332, 0.106854, 0.96962, 0.988806, -0.0688088, 0.0982691, 0.98861, 0.989588, -0.0628962, 0.0893456, 1.00667, 0.990438, -0.0573146, 0.0805392, 1.02344, 0.991506, -0.0509433, 0.0713725, 1.03933, 0.992492, -0.0448724, 0.0623732, 1.05378, 0.993663, -0.0383497, 0.0530838, 1.06747, 0.994956, -0.0319593, 0.0439512, 1.08007, 0.99634, -0.025401, 0.0347803, 1.09182, 0.99761, -0.0189687, 0.0257954, 1.1025, 0.99863, -0.0124441, 0.0169893, 1.11247, 0.99947, -0.00614003, 0.00829498, 1.12151, 1.00008, 0.000216624, -0.000146107, 1.12993, 0.950129, -0.00000434955, 0.217413, 0.0000190081, 0.950264, -0.00010957, 0.217444, 0.00047884, 0.9503, -0.000438299, 0.217451, 0.00191543, 0.950246, -0.000986124, 0.21744, 0.00430951, 0.950246, -0.00175311, 0.21744, 0.00766137, 0.950245, -0.00273923, 0.21744, 0.011971, 0.950253, -0.00394453, 0.217441, 0.0172385, 0.950258, -0.00536897, 0.217442, 0.0234641, 0.950267, -0.00701262, 0.217444, 0.030648, 0.950277, -0.00887551, 0.217446, 0.038791, 0.950284, -0.0109576, 0.217446, 0.0478931, 0.950312, -0.0132591, 0.217451, 0.0579568, 0.950334, -0.01578, 0.217454, 0.0689821, 0.950378, -0.0185204, 0.217462, 0.0809714, 0.950417, -0.0214803, 0.217467, 0.0939265, 0.950488, -0.0246594, 0.217479, 0.10785, 0.950534, -0.0280565, 0.217483, 0.122743, 0.950633, -0.0316685, 0.217498, 0.138611, 0.950698, -0.0354787, 0.217499, 0.155442, 0.950844, -0.0394003, 0.217507, 0.173208, 0.950999, -0.0426812, 0.217419, 0.191605, 0.951221, -0.0461302, 0.217317, 0.21084, 0.951412, -0.0502131, 0.217238, 0.230945, 0.951623, -0.0549183, 0.21722, 0.251745, 0.951867, -0.0604493, 0.217306, 0.273001, 0.952069, -0.0665189, 0.217466, 0.294874, 0.952459, -0.0709179, 0.217266, 0.318732, 0.952996, -0.0746112, 0.216891, 0.34318, 0.953425, -0.0789252, 0.216503, 0.36849, 0.953885, -0.0833293, 0.216042, 0.394373, 0.954617, -0.087371, 0.215469, 0.420505, 0.955429, -0.0914054, 0.214802, 0.446907, 0.956068, -0.0961671, 0.214146, 0.473522, 0.957094, -0.10048, 0.213286, 0.50052, 0.958372, -0.103248, 0.211796, 0.528715, 0.959654, -0.106033, 0.21016, 0.557065, 0.961305, -0.108384, 0.208149, 0.585286, 0.962785, -0.111122, 0.206024, 0.613334, 0.964848, -0.112981, 0.203442, 0.641334, 0.966498, -0.113717, 0.19996, 0.669955, 0.968678, -0.114121, 0.196105, 0.698094, 0.970489, -0.114524, 0.191906, 0.725643, 0.972903, -0.113792, 0.186963, 0.752856, 0.974701, -0.112406, 0.181343, 0.780013, 0.976718, -0.110685, 0.175185, 0.806268, 0.978905, -0.108468, 0.168535, 0.832073, 0.980267, -0.105061, 0.161106, 0.857149, 0.981967, -0.101675, 0.153387, 0.881145, 0.983063, -0.0974492, 0.145199, 0.904255, 0.984432, -0.0925815, 0.136527, 0.926686, 0.985734, -0.0877983, 0.127584, 0.947901, 0.986228, -0.081884, 0.118125, 0.968111, 0.98719, -0.0761208, 0.108594, 0.98719, 0.988228, -0.0698196, 0.0989996, 1.00559, 0.989046, -0.0632739, 0.0890074, 1.02246, 0.990242, -0.056522, 0.0790832, 1.03841, 0.991252, -0.0495272, 0.0689182, 1.05347, 0.992542, -0.0425373, 0.0588592, 1.06724, 0.994096, -0.0353198, 0.0486833, 1.08009, 0.995593, -0.028235, 0.0385977, 1.09177, 0.99711, -0.0209511, 0.0286457, 1.10274, 0.998263, -0.0139289, 0.0188497, 1.11262, 0.999254, -0.0067359, 0.009208, 1.12191, 0.999967, 0.000141846, -0.0000657764, 1.13024, 0.935608, -0.00000474692, 0.236466, 0.0000187817, 0.93996, -0.00011971, 0.237568, 0.000473646, 0.939959, -0.000478845, 0.237567, 0.0018946, 0.939954, -0.0010774, 0.237566, 0.00426284, 0.939956, -0.00191538, 0.237566, 0.00757842, 0.939954, -0.00299277, 0.237566, 0.0118413, 0.93996, -0.00430961, 0.237567, 0.0170518, 0.939969, -0.00586589, 0.237569, 0.02321, 0.939982, -0.00766166, 0.237572, 0.0303164, 0.939987, -0.00969686, 0.237572, 0.0383711, 0.939997, -0.0119715, 0.237574, 0.0473751, 0.940031, -0.0144858, 0.237581, 0.0573298, 0.940073, -0.0172399, 0.237589, 0.0682366, 0.94012, -0.0202335, 0.237598, 0.080097, 0.940162, -0.0234663, 0.237604, 0.0929116, 0.940237, -0.0269387, 0.237615, 0.106686, 0.940328, -0.0306489, 0.237632, 0.121421, 0.940419, -0.0345917, 0.237645, 0.137115, 0.940522, -0.0387481, 0.237654, 0.153766, 0.940702, -0.0429906, 0.237661, 0.17133, 0.940871, -0.0465089, 0.237561, 0.189502, 0.941103, -0.050531, 0.23748, 0.208616, 0.941369, -0.0550657, 0.237423, 0.228595, 0.941641, -0.0601337, 0.237399, 0.249287, 0.941903, -0.0658804, 0.237443, 0.270467, 0.942224, -0.0722674, 0.237597, 0.292024, 0.942633, -0.0771788, 0.237419, 0.315272, 0.943172, -0.0815623, 0.237068, 0.339579, 0.943691, -0.0863973, 0.236682, 0.364717, 0.944382, -0.0911536, 0.236213, 0.390435, 0.945392, -0.0952967, 0.235562, 0.416425, 0.946185, -0.0998948, 0.234832, 0.442772, 0.947212, -0.104796, 0.234114, 0.469347, 0.948778, -0.10928, 0.233222, 0.496162, 0.950149, -0.113081, 0.231845, 0.523978, 0.951989, -0.115893, 0.230005, 0.552295, 0.953921, -0.11846, 0.227862, 0.580569, 0.955624, -0.12115, 0.225439, 0.608698, 0.958234, -0.123373, 0.222635, 0.636696, 0.960593, -0.124519, 0.219093, 0.665208, 0.963201, -0.124736, 0.214749, 0.693557, 0.965642, -0.125012, 0.210059, 0.721334, 0.968765, -0.124661, 0.204935, 0.748613, 0.971753, -0.122996, 0.198661, 0.776224, 0.973751, -0.120998, 0.191823, 0.802461, 0.976709, -0.118583, 0.184359, 0.828399, 0.977956, -0.115102, 0.176437, 0.853693, 0.979672, -0.111077, 0.167681, 0.877962, 0.981816, -0.10688, 0.158872, 0.901564, 0.98238, -0.101469, 0.149398, 0.924057, 0.983964, -0.0960013, 0.139436, 0.945751, 0.984933, -0.0899626, 0.12943, 0.966272, 0.985694, -0.0832973, 0.11894, 0.985741, 0.986822, -0.0767082, 0.108349, 1.00407, 0.987725, -0.0693614, 0.0976026, 1.02154, 0.98877, -0.06211, 0.086652, 1.03757, 0.990129, -0.0544143, 0.0756182, 1.05296, 0.991337, -0.046744, 0.0645753, 1.06683, 0.992978, -0.0387931, 0.0534683, 1.0798, 0.994676, -0.030973, 0.0424137, 1.09181, 0.99645, -0.0230311, 0.0314035, 1.10286, 0.997967, -0.0152065, 0.0206869, 1.11291, 0.99922, -0.00744837, 0.010155, 1.12237, 1.00002, 0.000240209, -0.0000752767, 1.13089, 0.922948, -0.00000515351, 0.255626, 0.0000186069, 0.928785, -0.000129623, 0.257244, 0.000468009, 0.928761, -0.00051849, 0.257237, 0.00187202, 0.928751, -0.0011666, 0.257235, 0.00421204, 0.928751, -0.00207395, 0.257234, 0.0074881, 0.928754, -0.00324055, 0.257235, 0.0117002, 0.92876, -0.00466639, 0.257236, 0.0168486, 0.928763, -0.00635149, 0.257237, 0.0229334, 0.928774, -0.00829584, 0.257239, 0.029955, 0.928791, -0.0104995, 0.257243, 0.0379139, 0.928804, -0.0129623, 0.257245, 0.0468108, 0.928847, -0.0156846, 0.257255, 0.0566473, 0.92889, -0.0186661, 0.257263, 0.0674246, 0.928924, -0.0219067, 0.257268, 0.0791433, 0.928989, -0.0254066, 0.257282, 0.0918076, 0.92909, -0.0291651, 0.257301, 0.105419, 0.92918, -0.0331801, 0.257316, 0.119978, 0.92929, -0.0374469, 0.257332, 0.135491, 0.929453, -0.041939, 0.257357, 0.151948, 0.929586, -0.0464612, 0.257347, 0.169275, 0.929858, -0.0503426, 0.257269, 0.187257, 0.930125, -0.0548409, 0.257199, 0.206204, 0.930403, -0.0598063, 0.257149, 0.22601, 0.930726, -0.0652437, 0.257122, 0.246561, 0.931098, -0.0712376, 0.257153, 0.267618, 0.931396, -0.0777506, 0.257237, 0.288993, 0.931947, -0.0832374, 0.257124, 0.311527, 0.932579, -0.0883955, 0.25683, 0.335697, 0.933194, -0.0937037, 0.256444, 0.360634, 0.934013, -0.0987292, 0.255939, 0.386126, 0.935307, -0.103215, 0.255282, 0.412018, 0.936374, -0.108234, 0.254538, 0.438292, 0.93776, -0.113234, 0.253728, 0.464805, 0.939599, -0.118013, 0.25275, 0.491464, 0.941036, -0.122661, 0.251404, 0.518751, 0.94337, -0.125477, 0.249435, 0.547133, 0.945318, -0.128374, 0.247113, 0.575456, 0.947995, -0.130996, 0.244441, 0.60372, 0.950818, -0.133438, 0.241352, 0.63174, 0.954378, -0.135004, 0.237849, 0.659971, 0.957151, -0.135313, 0.233188, 0.688478, 0.960743, -0.13521, 0.228001, 0.716767, 0.964352, -0.135007, 0.222249, 0.744349, 0.967273, -0.133523, 0.21542, 0.771786, 0.969767, -0.131155, 0.208039, 0.798639, 0.973195, -0.128492, 0.200076, 0.824774, 0.975557, -0.125094, 0.191451, 0.850222, 0.977692, -0.120578, 0.18184, 0.874761, 0.98026, -0.115882, 0.172102, 0.898497, 0.981394, -0.110372, 0.161859, 0.921636, 0.982386, -0.10415, 0.15108, 0.943467, 0.983783, -0.0978128, 0.140407, 0.964045, 0.98422, -0.0906171, 0.129058, 0.98398, 0.985447, -0.0832921, 0.117614, 1.00276, 0.986682, -0.0754412, 0.10585, 1.02047, 0.987326, -0.0673885, 0.0940943, 1.03678, 0.988707, -0.0592565, 0.0822093, 1.05218, 0.990185, -0.050717, 0.070192, 1.06652, 0.991866, -0.0423486, 0.0582081, 1.07965, 0.993897, -0.0336118, 0.0460985, 1.09188, 0.995841, -0.0252178, 0.0342737, 1.10307, 0.997605, -0.0164893, 0.0224829, 1.11324, 0.999037, -0.00817112, 0.0110647, 1.12262, 1.00003, 0.000291686, -0.000168673, 1.13139, 0.915304, -0.00000552675, 0.275999, 0.0000183285, 0.91668, -0.000139285, 0.276414, 0.000461914, 0.916664, -0.00055713, 0.276409, 0.00184763, 0.916653, -0.00125354, 0.276406, 0.00415715, 0.916651, -0.00222851, 0.276405, 0.00739053, 0.916655, -0.00348205, 0.276406, 0.0115478, 0.916653, -0.00501414, 0.276405, 0.0166291, 0.916667, -0.00682478, 0.276409, 0.0226346, 0.91668, -0.00891398, 0.276412, 0.0295648, 0.91669, -0.0112817, 0.276413, 0.0374199, 0.916727, -0.013928, 0.276422, 0.0462016, 0.916759, -0.0168528, 0.276429, 0.0559101, 0.916793, -0.0200558, 0.276436, 0.0665466, 0.916849, -0.0235373, 0.276448, 0.0781139, 0.916964, -0.0272973, 0.276474, 0.0906156, 0.917047, -0.0313344, 0.276491, 0.104051, 0.917152, -0.0356465, 0.276511, 0.118424, 0.917286, -0.0402271, 0.276533, 0.133736, 0.917469, -0.0450408, 0.276564, 0.149978, 0.917686, -0.0497872, 0.276563, 0.167057, 0.917953, -0.0540937, 0.276493, 0.184846, 0.918228, -0.0590709, 0.276437, 0.203614, 0.918572, -0.0644277, 0.276398, 0.223212, 0.918918, -0.0702326, 0.276362, 0.243584, 0.919356, -0.076484, 0.276383, 0.264465, 0.919842, -0.0830808, 0.276434, 0.285701, 0.920451, -0.0892972, 0.276407, 0.307559, 0.921113, -0.095016, 0.276128, 0.331501, 0.921881, -0.100771, 0.275754, 0.356207, 0.923027, -0.106029, 0.275254, 0.381477, 0.924364, -0.111029, 0.274595, 0.40722, 0.925818, -0.116345, 0.273841, 0.433385, 0.92746, -0.121424, 0.272913, 0.459848, 0.929167, -0.12657, 0.271837, 0.486493, 0.931426, -0.131581, 0.270575, 0.513432, 0.934001, -0.135038, 0.268512, 0.541502, 0.936296, -0.138039, 0.266135, 0.569658, 0.939985, -0.140687, 0.263271, 0.598375, 0.943516, -0.143247, 0.260058, 0.626563, 0.94782, -0.145135, 0.256138, 0.654711, 0.951023, -0.145733, 0.251154, 0.683285, 0.955338, -0.145554, 0.245562, 0.711831, 0.959629, -0.145008, 0.239265, 0.739573, 0.963123, -0.144003, 0.232064, 0.767027, 0.966742, -0.141289, 0.224036, 0.794359, 0.969991, -0.138247, 0.215305, 0.820361, 0.973403, -0.134786, 0.206051, 0.846548, 0.975317, -0.129966, 0.195914, 0.871541, 0.977647, -0.12471, 0.185184, 0.895313, 0.980137, -0.119086, 0.174161, 0.918398, 0.981031, -0.112297, 0.162792, 0.940679, 0.982037, -0.105372, 0.150952, 0.961991, 0.983164, -0.097821, 0.138921, 0.981913, 0.983757, -0.0897245, 0.126611, 1.00109, 0.985036, -0.0815974, 0.114228, 1.01902, 0.986289, -0.0727725, 0.101389, 1.03604, 0.987329, -0.0639323, 0.0886476, 1.05149, 0.989193, -0.0548109, 0.0756837, 1.06619, 0.990716, -0.045687, 0.0627581, 1.07948, 0.992769, -0.0364315, 0.0498337, 1.09172, 0.99524, -0.0271761, 0.0370305, 1.1033, 0.997154, -0.0179609, 0.0243959, 1.11353, 0.998845, -0.00878063, 0.0119567, 1.12319, 1.00002, 0.000259038, -0.000108146, 1.13177, 0.903945, -0.00000591681, 0.295126, 0.0000181226, 0.903668, -0.000148672, 0.295037, 0.000455367, 0.903677, -0.000594683, 0.29504, 0.00182145, 0.903673, -0.00133805, 0.295039, 0.00409831, 0.903666, -0.00237872, 0.295036, 0.00728584, 0.903668, -0.00371676, 0.295037, 0.0113842, 0.903679, -0.00535212, 0.29504, 0.0163936, 0.903684, -0.00728479, 0.295041, 0.0223141, 0.903698, -0.00951473, 0.295044, 0.0291462, 0.903718, -0.0120419, 0.295049, 0.0368904, 0.903754, -0.0148664, 0.295058, 0.0455477, 0.903801, -0.017988, 0.29507, 0.0551194, 0.903851, -0.0214064, 0.295082, 0.0656058, 0.903921, -0.0251219, 0.295097, 0.0770109, 0.904002, -0.0291337, 0.295116, 0.0893354, 0.904111, -0.033441, 0.29514, 0.102583, 0.904246, -0.0380415, 0.295169, 0.116755, 0.904408, -0.0429258, 0.295202, 0.131853, 0.904637, -0.0480468, 0.295245, 0.147869, 0.904821, -0.0529208, 0.295214, 0.164658, 0.905163, -0.0577748, 0.295185, 0.182274, 0.905469, -0.0631763, 0.295143, 0.200828, 0.905851, -0.068917, 0.295112, 0.2202, 0.906322, -0.0750861, 0.295104, 0.240372, 0.906761, -0.0815855, 0.295086, 0.261082, 0.90735, -0.0882138, 0.295095, 0.282123, 0.908087, -0.095082, 0.295139, 0.303563, 0.908826, -0.101488, 0.29492, 0.327028, 0.909832, -0.107577, 0.294577, 0.351464, 0.911393, -0.113033, 0.294115, 0.376497, 0.912804, -0.118629, 0.293446, 0.402115, 0.914081, -0.124232, 0.292581, 0.428111, 0.91637, -0.129399, 0.29166, 0.454442, 0.91814, -0.134892, 0.290422, 0.481024, 0.921179, -0.140069, 0.289194, 0.507924, 0.924544, -0.144431, 0.287421, 0.535557, 0.927995, -0.147498, 0.284867, 0.563984, 0.931556, -0.150197, 0.281722, 0.5923, 0.935777, -0.152711, 0.278207, 0.620832, 0.940869, -0.154836, 0.274148, 0.649069, 0.945994, -0.155912, 0.269057, 0.677746, 0.949634, -0.155641, 0.262799, 0.706293, 0.955032, -0.154809, 0.256097, 0.734278, 0.95917, -0.153678, 0.248618, 0.761751, 0.962931, -0.151253, 0.239794, 0.789032, 0.966045, -0.147625, 0.230281, 0.815422, 0.96971, -0.143964, 0.220382, 0.841787, 0.972747, -0.139464, 0.209846, 0.867446, 0.975545, -0.133459, 0.198189, 0.892004, 0.978381, -0.127424, 0.186362, 0.915458, 0.979935, -0.120506, 0.173964, 0.937948, 0.980948, -0.11282, 0.161429, 0.959732, 0.982234, -0.104941, 0.148557, 0.980118, 0.982767, -0.0962905, 0.135508, 0.999463, 0.983544, -0.0873625, 0.122338, 1.01756, 0.984965, -0.0783447, 0.108669, 1.03492, 0.986233, -0.0684798, 0.0949911, 1.05087, 0.987796, -0.0590867, 0.0811386, 1.0656, 0.989885, -0.0489145, 0.0673099, 1.0794, 0.991821, -0.0391, 0.0535665, 1.09174, 0.99448, -0.029087, 0.0397529, 1.10341, 0.996769, -0.019114, 0.0261463, 1.11383, 0.998641, -0.00947007, 0.0128731, 1.1237, 0.999978, 0.000446316, -0.000169093, 1.13253, 0.888362, -0.00000627064, 0.312578, 0.0000178215, 0.889988, -0.000157791, 0.313148, 0.000448451, 0.889825, -0.000631076, 0.313092, 0.00179356, 0.88984, -0.00141994, 0.313097, 0.00403554, 0.889828, -0.0025243, 0.313092, 0.00717429, 0.889831, -0.00394421, 0.313093, 0.0112099, 0.889831, -0.00567962, 0.313093, 0.0161425, 0.889844, -0.00773051, 0.313096, 0.0219724, 0.889858, -0.0100968, 0.3131, 0.0286999, 0.889882, -0.0127786, 0.313106, 0.0363256, 0.889918, -0.0157757, 0.313116, 0.0448509, 0.889967, -0.0190878, 0.313129, 0.0542758, 0.89003, -0.022715, 0.313145, 0.0646032, 0.890108, -0.0266566, 0.313165, 0.0758339, 0.890218, -0.0309131, 0.313193, 0.0879729, 0.890351, -0.0354819, 0.313226, 0.101019, 0.89051, -0.0403613, 0.313263, 0.114979, 0.890672, -0.0455385, 0.313294, 0.129848, 0.890882, -0.0509444, 0.313333, 0.145616, 0.891189, -0.0559657, 0.313324, 0.162122, 0.891457, -0.0613123, 0.313281, 0.179524, 0.891856, -0.0671488, 0.313281, 0.197855, 0.892312, -0.0732732, 0.313268, 0.216991, 0.892819, -0.0797865, 0.313263, 0.236924, 0.893369, -0.0865269, 0.313247, 0.257433, 0.894045, -0.0931592, 0.313205, 0.278215, 0.894884, -0.100532, 0.313276, 0.299467, 0.895832, -0.107716, 0.313205, 0.322276, 0.897043, -0.114099, 0.312873, 0.34642, 0.898515, -0.119941, 0.312331, 0.371187, 0.900191, -0.126044, 0.311731, 0.396656, 0.90188, -0.131808, 0.310859, 0.422488, 0.904359, -0.137289, 0.309857, 0.448744, 0.906923, -0.142991, 0.308714, 0.475239, 0.910634, -0.148253, 0.307465, 0.501983, 0.914502, -0.153332, 0.305774, 0.529254, 0.919046, -0.156646, 0.303156, 0.557709, 0.923194, -0.159612, 0.299928, 0.586267, 0.928858, -0.162027, 0.296245, 0.614925, 0.934464, -0.164203, 0.291832, 0.643187, 0.939824, -0.165602, 0.286565, 0.671601, 0.944582, -0.165383, 0.280073, 0.700213, 0.949257, -0.164439, 0.272891, 0.728432, 0.954389, -0.162953, 0.264771, 0.756082, 0.958595, -0.161007, 0.255927, 0.78369, 0.962138, -0.157243, 0.245769, 0.810769, 0.966979, -0.152872, 0.235127, 0.836999, 0.969566, -0.148209, 0.22347, 0.862684, 0.972372, -0.142211, 0.211147, 0.887847, 0.975916, -0.135458, 0.198606, 0.911843, 0.978026, -0.128398, 0.185498, 0.934795, 0.979686, -0.120313, 0.17171, 0.956787, 0.980748, -0.11166, 0.158159, 0.978046, 0.981622, -0.103035, 0.144399, 0.997693, 0.982356, -0.0930328, 0.13001, 1.01642, 0.983308, -0.0834627, 0.115778, 1.03366, 0.985037, -0.0732249, 0.101327, 1.05014, 0.986493, -0.0628145, 0.086554, 1.06507, 0.988484, -0.0526556, 0.0720413, 1.07907, 0.991051, -0.0415744, 0.0571151, 1.09189, 0.993523, -0.0314275, 0.0426643, 1.10369, 0.99628, -0.0203603, 0.0279325, 1.11423, 0.998344, -0.0102446, 0.0138182, 1.12421, 0.999997, 0.00042612, -0.000193628, 1.1333, 0.871555, -0.00000660007, 0.329176, 0.0000174749, 0.875255, -0.000166579, 0.330571, 0.000441051, 0.875644, -0.000666394, 0.330718, 0.00176441, 0.875159, -0.00149903, 0.330536, 0.00396899, 0.87516, -0.00266493, 0.330536, 0.007056, 0.875158, -0.00416393, 0.330535, 0.0110251, 0.87516, -0.00599598, 0.330535, 0.0158764, 0.875163, -0.00816108, 0.330536, 0.0216101, 0.875174, -0.0106591, 0.330538, 0.0282266, 0.875199, -0.0134899, 0.330545, 0.0357266, 0.875257, -0.0166538, 0.330563, 0.0441117, 0.875304, -0.0201501, 0.330575, 0.0533821, 0.875373, -0.0239785, 0.330595, 0.0635395, 0.875464, -0.0281389, 0.330619, 0.0745872, 0.875565, -0.0326301, 0.330645, 0.0865255, 0.875691, -0.0374516, 0.330676, 0.0993599, 0.875897, -0.0425993, 0.330733, 0.113093, 0.876091, -0.0480576, 0.330776, 0.127722, 0.876353, -0.0537216, 0.330826, 0.143227, 0.876649, -0.0589807, 0.330809, 0.159462, 0.877034, -0.0647865, 0.330819, 0.176642, 0.877443, -0.0709789, 0.330817, 0.194702, 0.877956, -0.0774782, 0.330832, 0.213577, 0.878499, -0.0843175, 0.330822, 0.233246, 0.879144, -0.0912714, 0.330804, 0.253512, 0.879982, -0.0980824, 0.330766, 0.274137, 0.88097, -0.105823, 0.330864, 0.295209, 0.882051, -0.113671, 0.330896, 0.317226, 0.883397, -0.120303, 0.330545, 0.341068, 0.884987, -0.12667, 0.330068, 0.365613, 0.886789, -0.133118, 0.329418, 0.390807, 0.889311, -0.139024, 0.328683, 0.416494, 0.891995, -0.144971, 0.327729, 0.442618, 0.895106, -0.150747, 0.326521, 0.469131, 0.899527, -0.156283, 0.325229, 0.495921, 0.90504, -0.161707, 0.32378, 0.523162, 0.909875, -0.165661, 0.32122, 0.55092, 0.91561, -0.168755, 0.317942, 0.579928, 0.921225, -0.171193, 0.313983, 0.608539, 0.927308, -0.17319, 0.309636, 0.636854, 0.933077, -0.174819, 0.304262, 0.66523, 0.938766, -0.175002, 0.297563, 0.693609, 0.943667, -0.173946, 0.289613, 0.722157, 0.949033, -0.172221, 0.281227, 0.750021, 0.953765, -0.169869, 0.271545, 0.777466, 0.95804, -0.166578, 0.261034, 0.804853, 0.962302, -0.161761, 0.249434, 0.831569, 0.966544, -0.156636, 0.237484, 0.857779, 0.969372, -0.150784, 0.224395, 0.883051, 0.972486, -0.143672, 0.210786, 0.907864, 0.975853, -0.135772, 0.196556, 0.931223, 0.977975, -0.127942, 0.182307, 0.954061, 0.979122, -0.118347, 0.167607, 0.97531, 0.980719, -0.109112, 0.152739, 0.995666, 0.981223, -0.0991789, 0.137932, 1.01475, 0.98216, -0.0883553, 0.122692, 1.03253, 0.983379, -0.0780825, 0.107493, 1.04917, 0.985434, -0.0665646, 0.0917791, 1.06464, 0.987332, -0.0557714, 0.0764949, 1.07896, 0.990004, -0.0442805, 0.060721, 1.09199, 0.992975, -0.0331676, 0.0452284, 1.10393, 0.995811, -0.0219547, 0.0297934, 1.11476, 0.9982, -0.0107613, 0.0146415, 1.12484, 1.00002, 0.000248678, -0.00014555, 1.13413, 0.859519, -0.00000693595, 0.347264, 0.0000171673, 0.859843, -0.00017503, 0.347394, 0.000433219, 0.859656, -0.000700076, 0.347319, 0.00173277, 0.859671, -0.00157517, 0.347325, 0.00389875, 0.859669, -0.00280028, 0.347324, 0.00693112, 0.85967, -0.0043754, 0.347324, 0.01083, 0.859665, -0.00630049, 0.347321, 0.0155954, 0.859685, -0.0085755, 0.347328, 0.0212278, 0.859694, -0.0112003, 0.347329, 0.0277273, 0.859718, -0.0141747, 0.347336, 0.0350946, 0.85976, -0.0174988, 0.347348, 0.0433314, 0.85982, -0.0211722, 0.347366, 0.0524384, 0.859892, -0.0251941, 0.347387, 0.0624168, 0.860006, -0.0295649, 0.347422, 0.0732708, 0.860122, -0.0342825, 0.347453, 0.0849999, 0.860282, -0.0393462, 0.347499, 0.0976102, 0.860482, -0.0447513, 0.347554, 0.111104, 0.860719, -0.0504775, 0.347614, 0.125479, 0.860998, -0.0563577, 0.347666, 0.140703, 0.861322, -0.0619473, 0.347662, 0.156681, 0.861724, -0.0681277, 0.347684, 0.173597, 0.862198, -0.0746567, 0.347709, 0.191371, 0.862733, -0.0815234, 0.347727, 0.209976, 0.863371, -0.0886643, 0.347744, 0.229351, 0.86414, -0.0957908, 0.347734, 0.24934, 0.865138, -0.102912, 0.34772, 0.269797, 0.866182, -0.110924, 0.3478, 0.290654, 0.867436, -0.119223, 0.347911, 0.312074, 0.869087, -0.126197, 0.347649, 0.335438, 0.870859, -0.133145, 0.347222, 0.359732, 0.872997, -0.139869, 0.346645, 0.38467, 0.875939, -0.146089, 0.345935, 0.41019, 0.879012, -0.152334, 0.345012, 0.436218, 0.883353, -0.15821, 0.343924, 0.462641, 0.888362, -0.164097, 0.342636, 0.489449, 0.895026, -0.169528, 0.341351, 0.516629, 0.900753, -0.174408, 0.339115, 0.544109, 0.906814, -0.17751, 0.335809, 0.572857, 0.912855, -0.180101, 0.331597, 0.601554, 0.919438, -0.182116, 0.32698, 0.630198, 0.925962, -0.183494, 0.321449, 0.658404, 0.931734, -0.184159, 0.314595, 0.686625, 0.93762, -0.18304, 0.306462, 0.71531, 0.943858, -0.181323, 0.297514, 0.744272, 0.948662, -0.178683, 0.287447, 0.771462, 0.953299, -0.175379, 0.276166, 0.798593, 0.957346, -0.170395, 0.263758, 0.8256, 0.962565, -0.165042, 0.251019, 0.852575, 0.966075, -0.158655, 0.237011, 0.878316, 0.969048, -0.151707, 0.222518, 0.90329, 0.972423, -0.143271, 0.207848, 0.927745, 0.975833, -0.134824, 0.192463, 0.950859, 0.977629, -0.125444, 0.1768, 0.972947, 0.978995, -0.114949, 0.161033, 0.993263, 0.980533, -0.104936, 0.145523, 1.01337, 0.980745, -0.0935577, 0.129799, 1.03128, 0.981814, -0.0822956, 0.113486, 1.04825, 0.983943, -0.0710082, 0.0972925, 1.06405, 0.986141, -0.0587931, 0.0808138, 1.0785, 0.988878, -0.0472755, 0.0644915, 1.09204, 0.992132, -0.0349128, 0.0478128, 1.10413, 0.9953, -0.0232407, 0.031621, 1.11527, 0.998117, -0.0112713, 0.0154935, 1.12551, 1.00003, 0.000339743, -0.000195763, 1.13504, 0.845441, -0.00000729126, 0.364305, 0.0000169208, 0.843588, -0.000183164, 0.363506, 0.000425067, 0.843412, -0.00073253, 0.36343, 0.00169999, 0.843401, -0.00164818, 0.363426, 0.00382495, 0.843399, -0.00293008, 0.363425, 0.00679993, 0.843401, -0.00457822, 0.363425, 0.010625, 0.843394, -0.00659249, 0.363421, 0.0153002, 0.843398, -0.00897282, 0.363421, 0.0208258, 0.843415, -0.0117191, 0.363426, 0.0272024, 0.843438, -0.0148312, 0.363432, 0.0344305, 0.843483, -0.018309, 0.363447, 0.0425116, 0.84356, -0.0221521, 0.363472, 0.0514471, 0.843646, -0.0263597, 0.363499, 0.061238, 0.843743, -0.0309315, 0.363527, 0.0718873, 0.84388, -0.0358658, 0.363569, 0.0833969, 0.844079, -0.0411624, 0.363631, 0.0957742, 0.844279, -0.0468128, 0.363688, 0.109015, 0.844549, -0.0527923, 0.363761, 0.123124, 0.844858, -0.0588204, 0.363817, 0.138044, 0.84522, -0.0647573, 0.36383, 0.153755, 0.845669, -0.0713181, 0.363879, 0.170394, 0.846155, -0.0781697, 0.363908, 0.187861, 0.846789, -0.0853913, 0.363969, 0.206176, 0.847502, -0.0928086, 0.363999, 0.225244, 0.8484, -0.10005, 0.363997, 0.244926, 0.849461, -0.107615, 0.364008, 0.265188, 0.850562, -0.115814, 0.364055, 0.28587, 0.851962, -0.124334, 0.364179, 0.306926, 0.854326, -0.131995, 0.364233, 0.329605, 0.856295, -0.139338, 0.363856, 0.35359, 0.858857, -0.146346, 0.363347, 0.37831, 0.862428, -0.152994, 0.362807, 0.403722, 0.866203, -0.159463, 0.361963, 0.429537, 0.871629, -0.165623, 0.36112, 0.456, 0.877365, -0.171649, 0.359917, 0.482773, 0.883744, -0.177151, 0.35848, 0.509705, 0.890693, -0.182381, 0.356523, 0.537215, 0.897278, -0.186076, 0.3533, 0.565493, 0.903958, -0.188602, 0.349095, 0.594293, 0.910908, -0.190755, 0.344215, 0.623165, 0.918117, -0.192063, 0.338606, 0.651573, 0.924644, -0.192758, 0.331544, 0.679869, 0.931054, -0.192238, 0.323163, 0.708668, 0.937303, -0.190035, 0.313529, 0.737201, 0.943387, -0.187162, 0.303152, 0.764977, 0.948494, -0.183876, 0.29146, 0.792683, 0.952546, -0.178901, 0.277917, 0.819228, 0.958077, -0.173173, 0.264753, 0.846559, 0.962462, -0.16645, 0.25002, 0.872962, 0.966569, -0.159452, 0.234873, 0.898729, 0.969108, -0.15074, 0.218752, 0.923126, 0.973072, -0.141523, 0.202673, 0.947278, 0.975452, -0.132075, 0.186326, 0.969938, 0.977784, -0.121257, 0.169396, 0.991325, 0.97899, -0.110182, 0.153044, 1.01123, 0.979777, -0.0989634, 0.136485, 1.0299, 0.980865, -0.0865894, 0.119343, 1.04727, 0.982432, -0.0746115, 0.102452, 1.06341, 0.984935, -0.0621822, 0.0852423, 1.07834, 0.987776, -0.0495694, 0.0678546, 1.092, 0.99103, -0.0372386, 0.0506917, 1.1043, 0.99474, -0.0244353, 0.0333316, 1.11576, 0.997768, -0.0121448, 0.0164348, 1.12617, 1.00003, 0.00031774, -0.000169504, 1.13598, 0.825551, -0.00000756799, 0.378425, 0.0000165099, 0.82664, -0.000190922, 0.378923, 0.000416504, 0.826323, -0.000763495, 0.378779, 0.0016656, 0.826359, -0.00171789, 0.378795, 0.00374768, 0.82636, -0.00305402, 0.378795, 0.00666259, 0.826368, -0.00477185, 0.378798, 0.0104104, 0.826364, -0.00687131, 0.378795, 0.0149912, 0.826368, -0.00935232, 0.378795, 0.0204054, 0.826376, -0.0122146, 0.378797, 0.0266532, 0.826399, -0.0154581, 0.378803, 0.0337355, 0.82646, -0.0190825, 0.378824, 0.0416537, 0.826525, -0.0230873, 0.378846, 0.0504091, 0.826614, -0.0274719, 0.378876, 0.0600032, 0.82674, -0.0322355, 0.378917, 0.0704393, 0.826888, -0.0373766, 0.378964, 0.0817195, 0.827078, -0.0428936, 0.379024, 0.0938492, 0.827318, -0.0487778, 0.379099, 0.106828, 0.82764, -0.0549935, 0.379199, 0.120659, 0.827926, -0.0611058, 0.379227, 0.13526, 0.828325, -0.0675054, 0.379275, 0.150713, 0.828801, -0.0743455, 0.379332, 0.167034, 0.8294, -0.0815523, 0.379415, 0.184209, 0.830094, -0.0890779, 0.379495, 0.202203, 0.8309, -0.096736, 0.379555, 0.220945, 0.831943, -0.104135, 0.379577, 0.240306, 0.833037, -0.112106, 0.379604, 0.260317, 0.834278, -0.120554, 0.379668, 0.2808, 0.836192, -0.129128, 0.3799, 0.301654, 0.838671, -0.137541, 0.380109, 0.323502, 0.840939, -0.14523, 0.379809, 0.347176, 0.844575, -0.15248, 0.379593, 0.371706, 0.848379, -0.159607, 0.37909, 0.39688, 0.853616, -0.166267, 0.378617, 0.422702, 0.858921, -0.172698, 0.377746, 0.448919, 0.865324, -0.178823, 0.376749, 0.475661, 0.872207, -0.184542, 0.375363, 0.502599, 0.880018, -0.189836, 0.373657, 0.529914, 0.88694, -0.194294, 0.370673, 0.557683, 0.894779, -0.197022, 0.36662, 0.586848, 0.902242, -0.199108, 0.36138, 0.615831, 0.909914, -0.200398, 0.355434, 0.644478, 0.917088, -0.20094, 0.348173, 0.672905, 0.923888, -0.200671, 0.339482, 0.701327, 0.930495, -0.198773, 0.32956, 0.730101, 0.937247, -0.195394, 0.318363, 0.758383, 0.943108, -0.191956, 0.306323, 0.786539, 0.948296, -0.187227, 0.292576, 0.813637, 0.953472, -0.181165, 0.278234, 0.840793, 0.958485, -0.174119, 0.263054, 0.867712, 0.962714, -0.166564, 0.246756, 0.893635, 0.966185, -0.158181, 0.229945, 0.919028, 0.970146, -0.148275, 0.212633, 0.943413, 0.973491, -0.138157, 0.195229, 0.966627, 0.975741, -0.127574, 0.178048, 0.988817, 0.977238, -0.11554, 0.160312, 1.00924, 0.978411, -0.10364, 0.142857, 1.02845, 0.979811, -0.0913122, 0.125317, 1.04648, 0.98116, -0.0782558, 0.107627, 1.06284, 0.983543, -0.0655957, 0.0895862, 1.07798, 0.986789, -0.0520411, 0.0713756, 1.092, 0.990292, -0.0389727, 0.053228, 1.10484, 0.994187, -0.025808, 0.0351945, 1.11642, 0.997499, -0.0126071, 0.0173198, 1.12703, 0.999999, 0.000275604, -0.000148602, 1.13674, 0.81075, -0.0000078735, 0.394456, 0.0000161829, 0.808692, -0.000198293, 0.393453, 0.000407564, 0.80846, -0.000792877, 0.39334, 0.00162965, 0.808595, -0.00178416, 0.393407, 0.00366711, 0.808597, -0.00317182, 0.393408, 0.00651934, 0.808598, -0.00495589, 0.393408, 0.0101866, 0.808591, -0.00713627, 0.393403, 0.0146689, 0.808592, -0.00971285, 0.393402, 0.0199667, 0.80861, -0.0126855, 0.393407, 0.0260803, 0.808633, -0.0160538, 0.393413, 0.0330107, 0.80868, -0.0198175, 0.393429, 0.0407589, 0.808748, -0.0239758, 0.393453, 0.0493264, 0.808854, -0.0285286, 0.39349, 0.0587161, 0.808992, -0.0334748, 0.39354, 0.0689304, 0.809141, -0.0388116, 0.393588, 0.0799707, 0.809352, -0.0445375, 0.39366, 0.0918432, 0.809608, -0.0506427, 0.393742, 0.104549, 0.809915, -0.0570708, 0.393834, 0.118085, 0.810253, -0.0633526, 0.393885, 0.132377, 0.810687, -0.0700966, 0.393953, 0.147537, 0.811233, -0.0772274, 0.394047, 0.163543, 0.811865, -0.0847629, 0.394148, 0.180394, 0.812648, -0.0925663, 0.394265, 0.198051, 0.813583, -0.100416, 0.394363, 0.216443, 0.814683, -0.108119, 0.394402, 0.235502, 0.815948, -0.11644, 0.394489, 0.255242, 0.817278, -0.125036, 0.394542, 0.275441, 0.819605, -0.133655, 0.39486, 0.296094, 0.822256, -0.142682, 0.395248, 0.317309, 0.825349, -0.150756, 0.395241, 0.340516, 0.829605, -0.158392, 0.395285, 0.364819, 0.83391, -0.165801, 0.394922, 0.389736, 0.839808, -0.172677, 0.394691, 0.415409, 0.845708, -0.179448, 0.394006, 0.441546, 0.853025, -0.185746, 0.393279, 0.46832, 0.859666, -0.191684, 0.391655, 0.495302, 0.86789, -0.197146, 0.390068, 0.52262, 0.875845, -0.201904, 0.38727, 0.550336, 0.882634, -0.205023, 0.382688, 0.578825, 0.891076, -0.207098, 0.377543, 0.608103, 0.900589, -0.208474, 0.371752, 0.63723, 0.90791, -0.209068, 0.364016, 0.665769, 0.915971, -0.208655, 0.355593, 0.694428, 0.923455, -0.20729, 0.345439, 0.723224, 0.931514, -0.203821, 0.334099, 0.751925, 0.937885, -0.19986, 0.321069, 0.780249, 0.943136, -0.194993, 0.306571, 0.8077, 0.948818, -0.189132, 0.291556, 0.83497, 0.954433, -0.181617, 0.275745, 0.86188, 0.959078, -0.173595, 0.258695, 0.888562, 0.962705, -0.164855, 0.240825, 0.914008, 0.966753, -0.155129, 0.22268, 0.939145, 0.970704, -0.144241, 0.204542, 0.963393, 0.973367, -0.133188, 0.185927, 0.985983, 0.975984, -0.121146, 0.167743, 1.00704, 0.976994, -0.108366, 0.149218, 1.02715, 0.978485, -0.0956746, 0.13131, 1.0455, 0.980074, -0.0820733, 0.112513, 1.06221, 0.98225, -0.0684061, 0.0938323, 1.07782, 0.98553, -0.0549503, 0.0749508, 1.09199, 0.989529, -0.0407857, 0.055848, 1.10508, 0.993536, -0.0271978, 0.0368581, 1.11684, 0.997247, -0.0132716, 0.0181845, 1.12789, 1, 0.000431817, -0.000198809, 1.13792, 0.785886, -0.00000812608, 0.405036, 0.0000157669, 0.790388, -0.000205278, 0.407355, 0.000398297, 0.790145, -0.000820824, 0.407231, 0.00159263, 0.790135, -0.00184681, 0.407226, 0.00358336, 0.790119, -0.00328316, 0.407218, 0.00637039, 0.790126, -0.00512988, 0.40722, 0.0099539, 0.79013, -0.00738684, 0.407221, 0.0143339, 0.790135, -0.0100538, 0.407221, 0.0195107, 0.790134, -0.0131306, 0.407217, 0.0254848, 0.79016, -0.0166169, 0.407224, 0.0322572, 0.790197, -0.020512, 0.407236, 0.0398284, 0.790273, -0.0248157, 0.407263, 0.0482014, 0.790381, -0.029527, 0.407304, 0.0573777, 0.790521, -0.0346446, 0.407355, 0.0673602, 0.790704, -0.0401665, 0.40742, 0.0781522, 0.790925, -0.0460896, 0.407499, 0.0897582, 0.791195, -0.0524017, 0.407589, 0.10218, 0.791522, -0.0590121, 0.407691, 0.11541, 0.791878, -0.0654876, 0.407748, 0.12939, 0.792361, -0.0725207, 0.407849, 0.144237, 0.792942, -0.0799844, 0.407963, 0.159924, 0.79362, -0.0877896, 0.408087, 0.176425, 0.794529, -0.0958451, 0.408259, 0.193733, 0.795521, -0.103827, 0.408362, 0.211756, 0.796778, -0.111937, 0.408482, 0.230524, 0.798027, -0.120521, 0.408547, 0.249967, 0.799813, -0.129242, 0.408721, 0.269926, 0.802387, -0.138048, 0.409148, 0.290338, 0.805279, -0.147301, 0.409641, 0.311193, 0.809251, -0.155895, 0.410154, 0.333611, 0.813733, -0.163942, 0.410297, 0.357615, 0.819081, -0.171666, 0.410373, 0.382339, 0.825427, -0.178905, 0.410348, 0.407828, 0.83172, -0.185812, 0.409486, 0.434034, 0.83877, -0.192318, 0.408776, 0.460493, 0.845817, -0.198249, 0.407176, 0.487346, 0.854664, -0.204034, 0.405719, 0.514832, 0.863495, -0.208908, 0.403282, 0.542401, 0.871883, -0.212765, 0.399293, 0.570683, 0.88065, -0.214911, 0.393803, 0.599947, 0.89004, -0.216214, 0.387536, 0.62932, 0.898476, -0.216745, 0.379846, 0.658319, 0.906738, -0.216387, 0.370625, 0.687138, 0.914844, -0.215053, 0.360139, 0.71601, 0.923877, -0.212007, 0.348849, 0.745124, 0.931925, -0.207481, 0.335639, 0.773366, 0.938054, -0.202418, 0.320798, 0.801636, 0.943895, -0.196507, 0.304772, 0.829055, 0.949468, -0.189009, 0.288033, 0.856097, 0.955152, -0.180539, 0.270532, 0.88301, 0.959403, -0.171437, 0.251639, 0.909296, 0.963309, -0.161661, 0.232563, 0.934868, 0.967399, -0.150425, 0.213231, 0.959662, 0.972009, -0.138659, 0.194247, 0.98302, 0.97433, -0.126595, 0.174718, 1.00517, 0.975823, -0.113205, 0.155518, 1.02566, 0.976371, -0.0996096, 0.136709, 1.04418, 0.978705, -0.0860754, 0.117571, 1.06146, 0.981477, -0.0714438, 0.0980046, 1.07777, 0.984263, -0.0572304, 0.0782181, 1.09214, 0.988423, -0.0428875, 0.0584052, 1.10553, 0.993, -0.0282442, 0.038522, 1.11758, 0.99704, -0.0140183, 0.0190148, 1.12864, 0.999913, 0.000369494, -0.000145203, 1.13901, 0.777662, -0.0000084153, 0.423844, 0.0000154403, 0.770458, -0.000211714, 0.419915, 0.00038845, 0.770716, -0.000846888, 0.420055, 0.00155386, 0.770982, -0.00190567, 0.420202, 0.00349653, 0.770981, -0.00338782, 0.420201, 0.00621606, 0.77098, -0.00529338, 0.4202, 0.00971274, 0.770983, -0.00762223, 0.4202, 0.0139867, 0.770985, -0.0103741, 0.420198, 0.0190381, 0.770996, -0.0135489, 0.4202, 0.0248677, 0.771029, -0.0171461, 0.420212, 0.0314764, 0.771052, -0.0211647, 0.420215, 0.0388648, 0.771131, -0.0256048, 0.420245, 0.047036, 0.771235, -0.0304647, 0.420284, 0.0559911, 0.771383, -0.0357436, 0.420341, 0.0657346, 0.771591, -0.0414392, 0.420423, 0.0762694, 0.771819, -0.0475462, 0.420506, 0.0875984, 0.772123, -0.0540506, 0.420617, 0.099727, 0.772464, -0.060797, 0.42072, 0.112637, 0.772855, -0.0675393, 0.420799, 0.126313, 0.773317, -0.0748323, 0.420893, 0.140824, 0.773981, -0.0825681, 0.421058, 0.15617, 0.774746, -0.0906307, 0.421226, 0.172322, 0.77566, -0.0988982, 0.421397, 0.189253, 0.776837, -0.106994, 0.421569, 0.206912, 0.778097, -0.115528, 0.421704, 0.225359, 0.779588, -0.124317, 0.421849, 0.24447, 0.781574, -0.133139, 0.422097, 0.264156, 0.784451, -0.142179, 0.422615, 0.284318, 0.787682, -0.15165, 0.423269, 0.304902, 0.792433, -0.160771, 0.424396, 0.3265, 0.797359, -0.169166, 0.424772, 0.35014, 0.803986, -0.177149, 0.425475, 0.374768, 0.809504, -0.184745, 0.424996, 0.399928, 0.815885, -0.19173, 0.424247, 0.425796, 0.823513, -0.198525, 0.423515, 0.452287, 0.832549, -0.204709, 0.422787, 0.479321, 0.841653, -0.210447, 0.421187, 0.506718, 0.850401, -0.215501, 0.418519, 0.53432, 0.859854, -0.219752, 0.414715, 0.56242, 0.869364, -0.222305, 0.409462, 0.591558, 0.878837, -0.223744, 0.402926, 0.621074, 0.888636, -0.224065, 0.395043, 0.650538, 0.898132, -0.223742, 0.38564, 0.679538, 0.907181, -0.222308, 0.375378, 0.708674, 0.915621, -0.219837, 0.363212, 0.737714, 0.9239, -0.215233, 0.349313, 0.767014, 0.931644, -0.209592, 0.334162, 0.795133, 0.938887, -0.203644, 0.317943, 0.823228, 0.945282, -0.196349, 0.300581, 0.850822, 0.950758, -0.18742, 0.282195, 0.877594, 0.956146, -0.177879, 0.262481, 0.904564, 0.960355, -0.167643, 0.242487, 0.930741, 0.965256, -0.156671, 0.222668, 0.955868, 0.968029, -0.144123, 0.201907, 0.979869, 0.97251, -0.131305, 0.18202, 1.00291, 0.974925, -0.118335, 0.161909, 1.02392, 0.975402, -0.103714, 0.142129, 1.0433, 0.976987, -0.089415, 0.122447, 1.06089, 0.979677, -0.0748858, 0.102248, 1.07713, 0.983184, -0.0596086, 0.0814851, 1.09218, 0.987466, -0.0447671, 0.0609484, 1.10585, 0.992348, -0.0295217, 0.0401835, 1.11829, 0.996674, -0.0143917, 0.0198163, 1.12966, 1.00003, 0.000321364, -0.000149983, 1.1402, 0.757901, -0.00000869074, 0.436176, 0.0000151011, 0.751195, -0.000217848, 0.432317, 0.000378533, 0.751178, -0.000871373, 0.432307, 0.0015141, 0.751195, -0.00196061, 0.432317, 0.0034068, 0.751198, -0.00348552, 0.432318, 0.00605659, 0.751195, -0.00544599, 0.432315, 0.00946353, 0.751207, -0.00784203, 0.43232, 0.013628, 0.751213, -0.0106732, 0.43232, 0.0185499, 0.751221, -0.0139393, 0.432319, 0.0242302, 0.751244, -0.0176398, 0.432325, 0.0306694, 0.7513, -0.0217743, 0.432348, 0.0378698, 0.751358, -0.0263412, 0.432367, 0.0458321, 0.751458, -0.0313396, 0.432404, 0.0545587, 0.751608, -0.0367682, 0.432464, 0.0640543, 0.7518, -0.0426246, 0.43254, 0.0743222, 0.752065, -0.0489031, 0.432645, 0.0853668, 0.752376, -0.0555828, 0.432762, 0.0971911, 0.752715, -0.0623861, 0.432859, 0.109768, 0.753137, -0.069415, 0.432958, 0.123126, 0.753676, -0.0770039, 0.433099, 0.137308, 0.754345, -0.084971, 0.433272, 0.15229, 0.755235, -0.0932681, 0.433504, 0.168075, 0.756186, -0.10171, 0.433693, 0.184625, 0.757363, -0.110019, 0.433857, 0.201897, 0.75884, -0.11887, 0.434102, 0.220014, 0.760467, -0.127881, 0.434306, 0.238778, 0.762969, -0.136766, 0.434751, 0.258172, 0.765823, -0.14612, 0.43529, 0.278062, 0.769676, -0.15566, 0.436236, 0.298437, 0.774909, -0.165177, 0.437754, 0.319532, 0.77994, -0.17402, 0.438343, 0.342505, 0.785757, -0.182201, 0.438609, 0.366693, 0.792487, -0.190104, 0.438762, 0.391668, 0.80038, -0.197438, 0.438795, 0.417494, 0.808494, -0.204365, 0.438226, 0.443933, 0.817695, -0.210714, 0.437283, 0.470929, 0.828111, -0.216651, 0.436087, 0.498569, 0.837901, -0.221804, 0.433717, 0.526165, 0.847813, -0.226318, 0.430133, 0.554155, 0.858314, -0.229297, 0.425213, 0.582822, 0.868891, -0.230999, 0.418576, 0.612847, 0.878941, -0.231155, 0.410405, 0.642445, 0.888809, -0.230935, 0.400544, 0.672024, 0.898089, -0.229343, 0.389613, 0.701366, 0.908081, -0.226886, 0.377197, 0.730763, 0.916819, -0.222676, 0.363397, 0.759642, 0.924968, -0.216835, 0.347437, 0.788775, 0.932906, -0.210245, 0.32995, 0.817135, 0.940025, -0.202992, 0.312262, 0.844912, 0.946101, -0.19436, 0.293313, 0.872164, 0.952835, -0.184125, 0.273638, 0.899443, 0.957347, -0.173657, 0.252385, 0.926389, 0.961434, -0.162204, 0.231038, 0.951947, 0.965522, -0.14979, 0.209834, 0.976751, 0.969412, -0.136307, 0.188821, 1.00022, 0.973902, -0.122527, 0.168013, 1.02229, 0.974045, -0.108213, 0.147634, 1.04199, 0.975775, -0.0927397, 0.12705, 1.06019, 0.978383, -0.0778212, 0.106309, 1.07711, 0.98211, -0.0621216, 0.0849279, 1.09245, 0.986517, -0.0463847, 0.0633519, 1.10651, 0.991696, -0.0309353, 0.0419698, 1.11903, 0.996349, -0.0150914, 0.0206272, 1.13073, 1.00003, 0.000442449, -0.000231396, 1.14146, 0.727498, -0.00000885074, 0.441528, 0.0000145832, 0.730897, -0.000223525, 0.443589, 0.000368298, 0.730796, -0.000893996, 0.443528, 0.00147303, 0.730805, -0.00201149, 0.443533, 0.00331433, 0.730814, -0.00357596, 0.443538, 0.00589222, 0.730815, -0.00558734, 0.443538, 0.00920678, 0.730822, -0.00804544, 0.44354, 0.0132582, 0.730836, -0.0109501, 0.443545, 0.0180468, 0.730848, -0.0143008, 0.443546, 0.0235732, 0.730871, -0.0180969, 0.443552, 0.0298382, 0.730915, -0.022338, 0.443567, 0.0368438, 0.730982, -0.0270225, 0.443591, 0.044591, 0.731076, -0.0321491, 0.443627, 0.0530831, 0.731245, -0.0377166, 0.443699, 0.0623243, 0.73144, -0.0437216, 0.443777, 0.0723181, 0.7317, -0.0501576, 0.443881, 0.0830691, 0.732034, -0.0569942, 0.444014, 0.0945809, 0.732388, -0.0638756, 0.444113, 0.106825, 0.732853, -0.071203, 0.444247, 0.119859, 0.733473, -0.0790076, 0.444442, 0.13369, 0.734195, -0.0871937, 0.444645, 0.148304, 0.735069, -0.095696, 0.444877, 0.163702, 0.736169, -0.10426, 0.445133, 0.179861, 0.73747, -0.112853, 0.44537, 0.196778, 0.738991, -0.12199, 0.445651, 0.214496, 0.740865, -0.131153, 0.445958, 0.232913, 0.743637, -0.140245, 0.446548, 0.251977, 0.746797, -0.149722, 0.447246, 0.271551, 0.751517, -0.159341, 0.448656, 0.291774, 0.756156, -0.169106, 0.449866, 0.312455, 0.761519, -0.178436, 0.450919, 0.334552, 0.768295, -0.186904, 0.451776, 0.358491, 0.776613, -0.195117, 0.452832, 0.383446, 0.783966, -0.202695, 0.45249, 0.408945, 0.793542, -0.20985, 0.452587, 0.435364, 0.803192, -0.216403, 0.451852, 0.462336, 0.813892, -0.22251, 0.450708, 0.48987, 0.824968, -0.227676, 0.4486, 0.517697, 0.835859, -0.232443, 0.445156, 0.545975, 0.846825, -0.235775, 0.440351, 0.574483, 0.858085, -0.237897, 0.433641, 0.604246, 0.868825, -0.238074, 0.425354, 0.634101, 0.879638, -0.237661, 0.415383, 0.664201, 0.889966, -0.236186, 0.404136, 0.693918, 0.899479, -0.233599, 0.390917, 0.723481, 0.908769, -0.229737, 0.376352, 0.75258, 0.917966, -0.223836, 0.360372, 0.781764, 0.926304, -0.217067, 0.342551, 0.811139, 0.934626, -0.209309, 0.324238, 0.839585, 0.941841, -0.20071, 0.304484, 0.867044, 0.94789, -0.190602, 0.283607, 0.894579, 0.954196, -0.179253, 0.262205, 0.921743, 0.958383, -0.167646, 0.239847, 0.948026, 0.963119, -0.155073, 0.218078, 0.973296, 0.966941, -0.141426, 0.195899, 0.998135, 0.970836, -0.126849, 0.174121, 1.02021, 0.973301, -0.112296, 0.153052, 1.04085, 0.97448, -0.0964965, 0.131733, 1.05946, 0.977045, -0.080489, 0.10997, 1.07693, 0.980751, -0.064844, 0.0881657, 1.09254, 0.985475, -0.0481938, 0.0657987, 1.10697, 0.991089, -0.0319185, 0.0435215, 1.12004, 0.996122, -0.0158088, 0.0214779, 1.13173, 1.00001, 0.000372455, -0.000200295, 1.14291, 0.708622, -0.00000907597, 0.45304, 0.0000141962, 0.711162, -0.000228911, 0.454662, 0.000358052, 0.709812, -0.000914446, 0.453797, 0.00143034, 0.709865, -0.00205819, 0.453834, 0.00321935, 0.709864, -0.00365894, 0.453833, 0.00572331, 0.709855, -0.00571692, 0.453826, 0.00894278, 0.709862, -0.00823201, 0.453828, 0.012878, 0.709875, -0.011204, 0.453832, 0.0175295, 0.709896, -0.0146323, 0.453839, 0.0228978, 0.709925, -0.0185163, 0.453847, 0.0289839, 0.709974, -0.0228551, 0.453866, 0.0357894, 0.710045, -0.0276473, 0.453892, 0.0433161, 0.710133, -0.032891, 0.453924, 0.0515665, 0.710292, -0.0385851, 0.453992, 0.0605458, 0.710485, -0.0447254, 0.45407, 0.0702574, 0.710769, -0.0513051, 0.454192, 0.0807077, 0.711106, -0.0582733, 0.454329, 0.091896, 0.711516, -0.0652866, 0.45446, 0.103814, 0.712071, -0.0728426, 0.454653, 0.116508, 0.712676, -0.0808307, 0.45484, 0.129968, 0.713476, -0.0892216, 0.455096, 0.144206, 0.714377, -0.0979047, 0.455346, 0.159212, 0.715579, -0.106531, 0.455647, 0.174973, 0.716977, -0.115492, 0.455961, 0.191504, 0.71862, -0.124821, 0.456315, 0.208835, 0.72084, -0.134079, 0.4568, 0.226869, 0.723786, -0.143427, 0.457521, 0.245582, 0.727464, -0.153061, 0.458475, 0.264957, 0.732771, -0.162768, 0.460239, 0.284948, 0.736515, -0.172627, 0.460899, 0.30522, 0.743519, -0.182487, 0.463225, 0.326717, 0.750041, -0.191295, 0.464027, 0.350113, 0.758589, -0.199746, 0.465227, 0.374782, 0.767703, -0.207584, 0.465877, 0.400226, 0.777484, -0.214973, 0.465996, 0.426442, 0.788792, -0.221796, 0.466019, 0.453688, 0.800194, -0.228038, 0.465083, 0.481246, 0.811234, -0.233346, 0.462506, 0.509086, 0.822859, -0.238073, 0.459257, 0.537338, 0.835082, -0.241764, 0.454863, 0.566108, 0.846332, -0.244241, 0.448163, 0.595126, 0.858355, -0.244736, 0.439709, 0.625574, 0.87034, -0.244278, 0.429837, 0.65617, 0.881027, -0.24255, 0.418002, 0.686029, 0.891007, -0.239912, 0.404325, 0.716039, 0.900874, -0.236133, 0.389222, 0.745518, 0.911072, -0.230672, 0.373269, 0.775026, 0.920359, -0.22356, 0.355083, 0.804521, 0.928604, -0.215591, 0.335533, 0.834045, 0.937175, -0.206503, 0.315278, 0.861612, 0.942825, -0.196684, 0.293653, 0.889131, 0.949805, -0.185116, 0.271503, 0.916853, 0.955535, -0.172703, 0.248821, 0.943541, 0.959843, -0.159978, 0.225591, 0.970132, 0.964393, -0.146375, 0.202719, 0.994709, 0.968008, -0.131269, 0.179928, 1.0186, 0.971013, -0.11569, 0.158007, 1.03928, 0.973334, -0.1003, 0.13624, 1.05887, 0.975775, -0.0833352, 0.1138, 1.07652, 0.979579, -0.0668981, 0.0913141, 1.09297, 0.984323, -0.0500902, 0.0683051, 1.10734, 0.990351, -0.0332377, 0.0451771, 1.12084, 0.995823, -0.0161491, 0.0221705, 1.13296, 1.0001, 0.000234083, -0.000108712, 1.14441, 0.683895, -0.00000924677, 0.46015, 0.0000137429, 0.68833, -0.000233383, 0.463134, 0.000346865, 0.688368, -0.000933547, 0.463159, 0.00138748, 0.688367, -0.00210049, 0.463159, 0.00312187, 0.688369, -0.00373415, 0.463159, 0.00555004, 0.688377, -0.00583449, 0.463163, 0.00867216, 0.688386, -0.00840128, 0.463166, 0.0124884, 0.688398, -0.0114343, 0.463169, 0.0169993, 0.688418, -0.0149329, 0.463175, 0.0222054, 0.688453, -0.0188964, 0.463188, 0.028108, 0.688515, -0.0233239, 0.463214, 0.0347085, 0.68857, -0.0282136, 0.463231, 0.0420091, 0.688679, -0.033564, 0.463276, 0.0500132, 0.688854, -0.0393733, 0.463356, 0.0587255, 0.689038, -0.0456354, 0.46343, 0.0681476, 0.689321, -0.0523433, 0.463553, 0.0782897, 0.689662, -0.059412, 0.463693, 0.0891501, 0.690188, -0.0665736, 0.4639, 0.100735, 0.690755, -0.0743106, 0.464107, 0.113074, 0.691405, -0.0824722, 0.464329, 0.126161, 0.692198, -0.0910484, 0.464585, 0.140007, 0.693196, -0.0998778, 0.464893, 0.154612, 0.69454, -0.108651, 0.465285, 0.169984, 0.695921, -0.117855, 0.465596, 0.186106, 0.697749, -0.12734, 0.466056, 0.203034, 0.700375, -0.136714, 0.466771, 0.220703, 0.703395, -0.146386, 0.467579, 0.239062, 0.707904, -0.156096, 0.469067, 0.258188, 0.711673, -0.165904, 0.469851, 0.277759, 0.717489, -0.175812, 0.471815, 0.297935, 0.724051, -0.185931, 0.47389, 0.318916, 0.731965, -0.195238, 0.47587, 0.341591, 0.741151, -0.204021, 0.477523, 0.366062, 0.751416, -0.212113, 0.478881, 0.391396, 0.761848, -0.21979, 0.479226, 0.417599, 0.771886, -0.2267, 0.478495, 0.444401, 0.783998, -0.232991, 0.477622, 0.472084, 0.796523, -0.238645, 0.475833, 0.500193, 0.808851, -0.243396, 0.472568, 0.52865, 0.821191, -0.247226, 0.467857, 0.557362, 0.834261, -0.250102, 0.461871, 0.586768, 0.846762, -0.251056, 0.453543, 0.617085, 0.859867, -0.250604, 0.443494, 0.647659, 0.871948, -0.248783, 0.431711, 0.678119, 0.882967, -0.245855, 0.417911, 0.708399, 0.892826, -0.242168, 0.401993, 0.738256, 0.90332, -0.237062, 0.385371, 0.767999, 0.913633, -0.22997, 0.366837, 0.798191, 0.922774, -0.221687, 0.346372, 0.827756, 0.931371, -0.212345, 0.325682, 0.856425, 0.938929, -0.20206, 0.303665, 0.884299, 0.944821, -0.190981, 0.280786, 0.912023, 0.951792, -0.178065, 0.2573, 0.939669, 0.957712, -0.164634, 0.233448, 0.96655, 0.961912, -0.150863, 0.209504, 0.992366, 0.966382, -0.13577, 0.18597, 1.01633, 0.969588, -0.119593, 0.162905, 1.03843, 0.971777, -0.103203, 0.14053, 1.05841, 0.97433, -0.0865888, 0.117909, 1.07632, 0.978686, -0.0690829, 0.0944101, 1.09326, 0.983281, -0.0516568, 0.0705671, 1.10796, 0.989562, -0.034558, 0.0468592, 1.12182, 0.995465, -0.0167808, 0.0229846, 1.1342, 0.999991, 0.000373016, -0.000235606, 1.1459, 0.662251, -0.00000939016, 0.468575, 0.0000132714, 0.666634, -0.000237624, 0.471675, 0.000335842, 0.666411, -0.000950385, 0.471516, 0.00134321, 0.666399, -0.00213833, 0.471509, 0.00302221, 0.666386, -0.0038014, 0.471499, 0.00537283, 0.666405, -0.00593958, 0.471511, 0.00839533, 0.666406, -0.00855253, 0.471508, 0.0120898, 0.666428, -0.0116401, 0.471519, 0.0164569, 0.666444, -0.0152015, 0.471522, 0.0214971, 0.66649, -0.0192362, 0.471543, 0.027212, 0.666537, -0.0237428, 0.471558, 0.033603, 0.666617, -0.0287198, 0.471591, 0.0406728, 0.666718, -0.0341647, 0.471631, 0.0484238, 0.666889, -0.0400759, 0.47171, 0.0568621, 0.667104, -0.0464479, 0.471805, 0.0659915, 0.667374, -0.0532677, 0.471923, 0.0758178, 0.667772, -0.0603805, 0.472098, 0.0863425, 0.668371, -0.0677392, 0.472363, 0.0975917, 0.668971, -0.0756028, 0.472596, 0.109567, 0.669696, -0.0839293, 0.472869, 0.122272, 0.670481, -0.0926683, 0.473126, 0.135718, 0.6715, -0.1016, 0.473442, 0.149914, 0.672911, -0.110566, 0.47389, 0.164882, 0.674512, -0.119984, 0.474354, 0.180602, 0.67651, -0.129574, 0.474922, 0.19711, 0.679292, -0.139106, 0.475764, 0.214371, 0.682798, -0.148993, 0.476886, 0.232405, 0.686955, -0.158737, 0.478179, 0.251153, 0.691406, -0.168754, 0.479432, 0.270436, 0.697438, -0.178703, 0.481481, 0.290374, 0.704761, -0.188955, 0.484143, 0.311044, 0.713599, -0.198814, 0.487007, 0.333003, 0.723194, -0.207869, 0.488962, 0.357144, 0.732601, -0.216189, 0.489815, 0.382169, 0.744193, -0.22398, 0.490888, 0.408227, 0.754907, -0.231156, 0.490355, 0.434928, 0.767403, -0.23747, 0.489548, 0.462599, 0.78107, -0.243503, 0.488274, 0.490908, 0.793893, -0.248114, 0.484843, 0.519421, 0.807296, -0.25222, 0.4803, 0.548561, 0.820529, -0.255265, 0.474097, 0.577772, 0.833716, -0.256741, 0.466041, 0.607782, 0.848403, -0.25637, 0.456547, 0.638807, 0.860755, -0.254804, 0.443946, 0.670058, 0.874012, -0.251834, 0.430852, 0.700749, 0.885619, -0.247867, 0.414903, 0.731446, 0.896069, -0.242634, 0.397276, 0.761191, 0.906266, -0.236093, 0.378535, 0.791053, 0.916759, -0.227543, 0.358038, 0.821298, 0.92523, -0.21783, 0.335705, 0.850747, 0.93436, -0.207534, 0.313797, 0.879258, 0.941631, -0.195983, 0.289671, 0.907734, 0.947564, -0.183567, 0.265319, 0.935206, 0.953681, -0.169345, 0.240815, 0.962739, 0.960008, -0.154909, 0.216119, 0.989227, 0.964145, -0.140161, 0.192096, 1.01465, 0.968171, -0.123411, 0.167855, 1.03737, 0.969859, -0.106525, 0.144817, 1.05767, 0.972666, -0.0891023, 0.12149, 1.0761, 0.977055, -0.0718094, 0.0975306, 1.09336, 0.982527, -0.0534213, 0.0730217, 1.10878, 0.989001, -0.0355579, 0.0483366, 1.12285, 0.99512, -0.0176383, 0.023938, 1.13548, 1.00007, 0.000368831, -0.000211581, 1.14744, 0.651047, -0.00000960845, 0.484101, 0.000012922, 0.644145, -0.000241347, 0.478968, 0.000324578, 0.64396, -0.000965142, 0.478831, 0.00129798, 0.64396, -0.00217154, 0.47883, 0.00292046, 0.643968, -0.00386049, 0.478835, 0.00519202, 0.643974, -0.00603186, 0.478838, 0.0081128, 0.643977, -0.0086854, 0.478836, 0.011683, 0.643982, -0.0118207, 0.478834, 0.0159031, 0.644024, -0.0154374, 0.478856, 0.0207743, 0.644059, -0.0195343, 0.478868, 0.0262975, 0.644122, -0.0241103, 0.478896, 0.0324747, 0.644207, -0.0291638, 0.478933, 0.039309, 0.64432, -0.0346919, 0.478981, 0.0468029, 0.644481, -0.0406919, 0.479053, 0.0549614, 0.644722, -0.047159, 0.479169, 0.0637909, 0.645013, -0.0540748, 0.479302, 0.0732974, 0.645503, -0.0612001, 0.479541, 0.0834898, 0.646117, -0.0687303, 0.479829, 0.0943873, 0.646707, -0.0767846, 0.480061, 0.105991, 0.647431, -0.0852465, 0.480343, 0.11831, 0.64831, -0.0940719, 0.48066, 0.131348, 0.649486, -0.103056, 0.481083, 0.14514, 0.650864, -0.112261, 0.481528, 0.159676, 0.652604, -0.121852, 0.482102, 0.174979, 0.654825, -0.131505, 0.482813, 0.191079, 0.657876, -0.141189, 0.483876, 0.207927, 0.661339, -0.151239, 0.48499, 0.225586, 0.665463, -0.161091, 0.486279, 0.243947, 0.670542, -0.171235, 0.487968, 0.262957, 0.677361, -0.181347, 0.49053, 0.282781, 0.685672, -0.191679, 0.493862, 0.303311, 0.694551, -0.201781, 0.49699, 0.324607, 0.703753, -0.211164, 0.498884, 0.347916, 0.713703, -0.219675, 0.500086, 0.372628, 0.725911, -0.227836, 0.501554, 0.398694, 0.73862, -0.23533, 0.502193, 0.425529, 0.752118, -0.241786, 0.501811, 0.453209, 0.76579, -0.247865, 0.500185, 0.481381, 0.779568, -0.252696, 0.497159, 0.51011, 0.793991, -0.256802, 0.492765, 0.539322, 0.808182, -0.259942, 0.486827, 0.569078, 0.821698, -0.261703, 0.478386, 0.598818, 0.836009, -0.262006, 0.468772, 0.629762, 0.849824, -0.260333, 0.456352, 0.661366, 0.863888, -0.257398, 0.442533, 0.69295, 0.876585, -0.253264, 0.426573, 0.723608, 0.888665, -0.248026, 0.408964, 0.754378, 0.899537, -0.241487, 0.389677, 0.784761, 0.9094, -0.233463, 0.368516, 0.814688, 0.920166, -0.223397, 0.346624, 0.845009, 0.928899, -0.21255, 0.322717, 0.874431, 0.937156, -0.200869, 0.298698, 0.902922, 0.943861, -0.188387, 0.273491, 0.931356, 0.949557, -0.174341, 0.247866, 0.958854, 0.955862, -0.158994, 0.222496, 0.986098, 0.961721, -0.143664, 0.197522, 1.01229, 0.965976, -0.127412, 0.17302, 1.03571, 0.968652, -0.109798, 0.148954, 1.05699, 0.971084, -0.0916787, 0.125044, 1.07587, 0.975584, -0.0739634, 0.100577, 1.09372, 0.98122, -0.055322, 0.0753666, 1.10948, 0.988253, -0.0366825, 0.0498899, 1.12394, 0.99482, -0.0180389, 0.024611, 1.13694, 1.00001, 0.000229839, -0.000188283, 1.14919, 0.613867, -0.00000964198, 0.479449, 0.0000123452, 0.621485, -0.000244534, 0.485399, 0.000313091, 0.621429, -0.000978202, 0.485353, 0.00125245, 0.62112, -0.00220004, 0.485114, 0.00281687, 0.621119, -0.0039111, 0.485112, 0.00500783, 0.621122, -0.00611091, 0.485112, 0.00782498, 0.621133, -0.00879922, 0.485117, 0.0112687, 0.621152, -0.0119756, 0.485125, 0.0153394, 0.621183, -0.0156396, 0.485139, 0.0200382, 0.621227, -0.0197898, 0.485158, 0.0253663, 0.621298, -0.0244253, 0.485192, 0.0313261, 0.621388, -0.0295441, 0.485233, 0.0379204, 0.621507, -0.0351432, 0.485286, 0.0451523, 0.621693, -0.0412198, 0.485378, 0.0530277, 0.621933, -0.0477673, 0.485495, 0.0615522, 0.622232, -0.0547574, 0.485635, 0.0707316, 0.622809, -0.0619417, 0.485943, 0.0805883, 0.623407, -0.069625, 0.486232, 0.0911267, 0.62406, -0.077796, 0.486516, 0.102354, 0.624835, -0.0863731, 0.486838, 0.114279, 0.625758, -0.095251, 0.487188, 0.126902, 0.627043, -0.104299, 0.487695, 0.140285, 0.628438, -0.113724, 0.488163, 0.154397, 0.630325, -0.123417, 0.488858, 0.169267, 0.632801, -0.133137, 0.489754, 0.184941, 0.635784, -0.143052, 0.490815, 0.20136, 0.639406, -0.153132, 0.492048, 0.218643, 0.643872, -0.163143, 0.49363, 0.236615, 0.6499, -0.17333, 0.496009, 0.255449, 0.657201, -0.183622, 0.498994, 0.275006, 0.666221, -0.194019, 0.502888, 0.295354, 0.674419, -0.204192, 0.505459, 0.316244, 0.683729, -0.21406, 0.507771, 0.33849, 0.695584, -0.222854, 0.510245, 0.363166, 0.708583, -0.231315, 0.512293, 0.389071, 0.721233, -0.238911, 0.512747, 0.415737, 0.735134, -0.245657, 0.512482, 0.443331, 0.750179, -0.251879, 0.511526, 0.471891, 0.765073, -0.256911, 0.508935, 0.500892, 0.779794, -0.261144, 0.504341, 0.530294, 0.794801, -0.264316, 0.498515, 0.560144, 0.810339, -0.266276, 0.491015, 0.590213, 0.824818, -0.266981, 0.481126, 0.620865, 0.839375, -0.265778, 0.468685, 0.652687, 0.853043, -0.262748, 0.453925, 0.684759, 0.867335, -0.258474, 0.437912, 0.716209, 0.88037, -0.253187, 0.419648, 0.747508, 0.891711, -0.246476, 0.39982, 0.77797, 0.902896, -0.238735, 0.37879, 0.808586, 0.913601, -0.22885, 0.355891, 0.838843, 0.923019, -0.217656, 0.331773, 0.869014, 0.933432, -0.205539, 0.307356, 0.898512, 0.939691, -0.192595, 0.281321, 0.9269, 0.946938, -0.178945, 0.255441, 0.955297, 0.952372, -0.163587, 0.229013, 0.983231, 0.95909, -0.147214, 0.203179, 1.00971, 0.963675, -0.13064, 0.17792, 1.03438, 0.968247, -0.113121, 0.152898, 1.05625, 0.97001, -0.0945824, 0.128712, 1.07598, 0.974458, -0.0755648, 0.103349, 1.094, 0.980168, -0.0571998, 0.0776731, 1.1104, 0.987295, -0.0377994, 0.0514445, 1.12491, 0.994432, -0.0186417, 0.025429, 1.13851, 0.999975, 0.000542714, -0.000282356, 1.15108, 0.592656, -0.00000980249, 0.486018, 0.0000119532, 0.598467, -0.000247275, 0.490781, 0.000301531, 0.597934, -0.000988317, 0.490343, 0.00120517, 0.597903, -0.00222366, 0.490319, 0.0027116, 0.597913, -0.00395315, 0.490327, 0.00482077, 0.597919, -0.00617653, 0.490329, 0.00753264, 0.597936, -0.00889375, 0.490339, 0.0108478, 0.597956, -0.0121043, 0.490347, 0.0147668, 0.597992, -0.0158073, 0.490365, 0.0192905, 0.598032, -0.0200017, 0.490382, 0.0244204, 0.598109, -0.0246865, 0.49042, 0.0301593, 0.598215, -0.0298594, 0.490474, 0.03651, 0.59833, -0.0355167, 0.490524, 0.0434757, 0.598525, -0.0416559, 0.490624, 0.0510629, 0.598778, -0.0482692, 0.490753, 0.0592781, 0.599135, -0.0553114, 0.49094, 0.0681304, 0.599802, -0.062542, 0.491328, 0.0776467, 0.600361, -0.0703638, 0.491598, 0.0878184, 0.60101, -0.0786256, 0.491882, 0.0986573, 0.601811, -0.0872962, 0.492232, 0.11018, 0.602861, -0.0962284, 0.492684, 0.1224, 0.604167, -0.10538, 0.493213, 0.135354, 0.605693, -0.114896, 0.493799, 0.149034, 0.607682, -0.124654, 0.494576, 0.163469, 0.610672, -0.13456, 0.4959, 0.178747, 0.613313, -0.144581, 0.496713, 0.194723, 0.617603, -0.154703, 0.498499, 0.211617, 0.622174, -0.16489, 0.500188, 0.229183, 0.628855, -0.175164, 0.503072, 0.247786, 0.636963, -0.185565, 0.506798, 0.267116, 0.644866, -0.195911, 0.509719, 0.28702, 0.653741, -0.206104, 0.512776, 0.307763, 0.664942, -0.216447, 0.516812, 0.329631, 0.67633, -0.22552, 0.519181, 0.353515, 0.690012, -0.234316, 0.521681, 0.379226, 0.704243, -0.242032, 0.523129, 0.405901, 0.719396, -0.249172, 0.523768, 0.433585, 0.734471, -0.255543, 0.522541, 0.462085, 0.750539, -0.260697, 0.520217, 0.491233, 0.766365, -0.26501, 0.516293, 0.521094, 0.781677, -0.268409, 0.509708, 0.551014, 0.797132, -0.270399, 0.501944, 0.581463, 0.812655, -0.271247, 0.492025, 0.612402, 0.828592, -0.270708, 0.480424, 0.643798, 0.844044, -0.268085, 0.465955, 0.67682, 0.857305, -0.263459, 0.448425, 0.708496, 0.87114, -0.258151, 0.430243, 0.74046, 0.884936, -0.251171, 0.410578, 0.771583, 0.895772, -0.243305, 0.38862, 0.802234, 0.906961, -0.234037, 0.365214, 0.833179, 0.917775, -0.222714, 0.34116, 0.86353, 0.927883, -0.210175, 0.31572, 0.893557, 0.936617, -0.196925, 0.289159, 0.922976, 0.943384, -0.182788, 0.261996, 0.951606, 0.949713, -0.167965, 0.235324, 0.979958, 0.955818, -0.151109, 0.208408, 1.00765, 0.961344, -0.133834, 0.182591, 1.03329, 0.965469, -0.115987, 0.156958, 1.0557, 0.968693, -0.09746, 0.132239, 1.07583, 0.973165, -0.0778514, 0.106195, 1.09451, 0.979387, -0.0585067, 0.0797669, 1.11137, 0.98671, -0.0390409, 0.0530263, 1.12643, 0.994093, -0.019408, 0.0263163, 1.14016, 1.00002, 0.000540029, -0.000194487, 1.15299, 0.574483, -0.00000989066, 0.494533, 0.0000114896, 0.574478, -0.000249127, 0.494528, 0.000289403, 0.574607, -0.000996811, 0.494637, 0.00115797, 0.574396, -0.00224241, 0.494458, 0.00260498, 0.574377, -0.00398632, 0.49444, 0.00463102, 0.574386, -0.00622836, 0.494445, 0.00723623, 0.574401, -0.0089683, 0.494453, 0.010421, 0.574419, -0.0122056, 0.49446, 0.0141859, 0.574459, -0.0159396, 0.494481, 0.0185322, 0.574525, -0.0201692, 0.49452, 0.0234617, 0.574587, -0.0248924, 0.494547, 0.0289762, 0.574697, -0.0301074, 0.494604, 0.0350797, 0.574853, -0.0358114, 0.494688, 0.0417767, 0.575027, -0.041999, 0.494772, 0.0490718, 0.575294, -0.0486618, 0.494915, 0.0569728, 0.575733, -0.0557148, 0.495173, 0.0654955, 0.576356, -0.0630489, 0.495537, 0.0746612, 0.576944, -0.0709285, 0.495836, 0.0844615, 0.57765, -0.0792723, 0.496177, 0.0949142, 0.578491, -0.0880167, 0.496563, 0.10603, 0.579639, -0.0969462, 0.497096, 0.117841, 0.580989, -0.10622, 0.497684, 0.130367, 0.582587, -0.115861, 0.498337, 0.143609, 0.584951, -0.125605, 0.499414, 0.157625, 0.587602, -0.135608, 0.500518, 0.172413, 0.59076, -0.145742, 0.501767, 0.187999, 0.594992, -0.155934, 0.503542, 0.20445, 0.600656, -0.166303, 0.506135, 0.221764, 0.607816, -0.176681, 0.509542, 0.24002, 0.61522, -0.187071, 0.51263, 0.258992, 0.623702, -0.197465, 0.516021, 0.278773, 0.634192, -0.207816, 0.520422, 0.299377, 0.644936, -0.218183, 0.524073, 0.320802, 0.657888, -0.2278, 0.528049, 0.34384, 0.670666, -0.236747, 0.52986, 0.36916, 0.685626, -0.24484, 0.531892, 0.395867, 0.701304, -0.252071, 0.532727, 0.423488, 0.717727, -0.258714, 0.532146, 0.452201, 0.733914, -0.264211, 0.529883, 0.481579, 0.750529, -0.26859, 0.5259, 0.511558, 0.76747, -0.272046, 0.51999, 0.542042, 0.785189, -0.274225, 0.513083, 0.572799, 0.800954, -0.275189, 0.502936, 0.603816, 0.816962, -0.274946, 0.490921, 0.635461, 0.83336, -0.272695, 0.47684, 0.6676, 0.848143, -0.268223, 0.459405, 0.70051, 0.861818, -0.262768, 0.440319, 0.732902, 0.876828, -0.255872, 0.420123, 0.765084, 0.889312, -0.247703, 0.398379, 0.796391, 0.900412, -0.238381, 0.374496, 0.827333, 0.912251, -0.227783, 0.349874, 0.858385, 0.921792, -0.214832, 0.323181, 0.888652, 0.931273, -0.200949, 0.296624, 0.917763, 0.940295, -0.186537, 0.269211, 0.947878, 0.946812, -0.171538, 0.241447, 0.977016, 0.953588, -0.155254, 0.213829, 1.00501, 0.958841, -0.137156, 0.186807, 1.03179, 0.963746, -0.118699, 0.160706, 1.05502, 0.966468, -0.0998358, 0.135504, 1.07568, 0.971178, -0.0805186, 0.109131, 1.09479, 0.97831, -0.0599348, 0.0818293, 1.1123, 0.985886, -0.0399661, 0.0545872, 1.12771, 0.994021, -0.0198682, 0.0269405, 1.14186, 1.00009, 0.000271022, -0.00012989, 1.15514, 0.538716, -0.00000990918, 0.486732, 0.0000109675, 0.550656, -0.000250642, 0.497518, 0.000277412, 0.55057, -0.00100265, 0.497441, 0.00110974, 0.550903, -0.00225672, 0.497733, 0.00249779, 0.550568, -0.00401046, 0.497438, 0.00443906, 0.550574, -0.00626613, 0.49744, 0.00693637, 0.550591, -0.0090226, 0.497449, 0.00998921, 0.550623, -0.0122795, 0.497469, 0.0135984, 0.550667, -0.0160361, 0.497495, 0.0177654, 0.550724, -0.0202908, 0.497526, 0.0224915, 0.550792, -0.0250421, 0.497557, 0.0277795, 0.550918, -0.0302878, 0.49763, 0.0336334, 0.551058, -0.0360241, 0.497701, 0.0400573, 0.551276, -0.0422473, 0.497824, 0.0470585, 0.551551, -0.0489441, 0.497977, 0.0546433, 0.552074, -0.0559596, 0.498312, 0.0628367, 0.552681, -0.0633978, 0.498679, 0.071646, 0.553324, -0.0713176, 0.499031, 0.0810746, 0.554011, -0.0797268, 0.499365, 0.091129, 0.55488, -0.0885238, 0.499779, 0.101837, 0.556171, -0.0974417, 0.500444, 0.113239, 0.557498, -0.106841, 0.501025, 0.125316, 0.559299, -0.116533, 0.501864, 0.138128, 0.561647, -0.126298, 0.502967, 0.151695, 0.564347, -0.136388, 0.504129, 0.16604, 0.567863, -0.146576, 0.505713, 0.181207, 0.572569, -0.156832, 0.507953, 0.197259, 0.578919, -0.167323, 0.511186, 0.214258, 0.585387, -0.177712, 0.514042, 0.232038, 0.593134, -0.188184, 0.517484, 0.250733, 0.603295, -0.198717, 0.522345, 0.270454, 0.613854, -0.209177, 0.526751, 0.290807, 0.626092, -0.219644, 0.531595, 0.312202, 0.637868, -0.229494, 0.534721, 0.334435, 0.652458, -0.238718, 0.538304, 0.359184, 0.666985, -0.247061, 0.539875, 0.385637, 0.683301, -0.254652, 0.541042, 0.41328, 0.69998, -0.261376, 0.540735, 0.441903, 0.717824, -0.267085, 0.539139, 0.471609, 0.734617, -0.271465, 0.534958, 0.501446, 0.753663, -0.27528, 0.53032, 0.532571, 0.770512, -0.277617, 0.522134, 0.563641, 0.787356, -0.278525, 0.51206, 0.595067, 0.806252, -0.278512, 0.50119, 0.627226, 0.822061, -0.277023, 0.486791, 0.659402, 0.838959, -0.273175, 0.470467, 0.692874, 0.85379, -0.267238, 0.450688, 0.725702, 0.868268, -0.260327, 0.429741, 0.75832, 0.881994, -0.251946, 0.407223, 0.790189, 0.893885, -0.242432, 0.383214, 0.821625, 0.905118, -0.231904, 0.357297, 0.853011, 0.916045, -0.219545, 0.330733, 0.883773, 0.927614, -0.205378, 0.303916, 0.914435, 0.936005, -0.190388, 0.275941, 0.944502, 0.944533, -0.1749, 0.247493, 0.974439, 0.950758, -0.158588, 0.218996, 1.00286, 0.957078, -0.141027, 0.191559, 1.0304, 0.962448, -0.121507, 0.164457, 1.05466, 0.964993, -0.102068, 0.138636, 1.0761, 0.970017, -0.0822598, 0.111861, 1.09541, 0.97661, -0.062033, 0.0843438, 1.11317, 0.985073, -0.0409832, 0.0558496, 1.12911, 0.993515, -0.020146, 0.0275331, 1.1438, 1.00006, 0.00027329, -0.000107883, 1.15736, 0.525324, -0.00000999341, 0.498153, 0.0000105385, 0.526513, -0.000251605, 0.499277, 0.000265329, 0.526517, -0.00100641, 0.499282, 0.0010613, 0.526588, -0.00226466, 0.499337, 0.00238823, 0.526539, -0.0040255, 0.499302, 0.00424535, 0.526547, -0.00628954, 0.499306, 0.00663364, 0.526561, -0.00905628, 0.499313, 0.00955337, 0.526593, -0.0123253, 0.499334, 0.0130054, 0.526642, -0.0160957, 0.499365, 0.0169911, 0.5267, -0.0203661, 0.499396, 0.0215122, 0.526792, -0.0251347, 0.499451, 0.0265718, 0.526904, -0.0303985, 0.499511, 0.0321732, 0.527079, -0.0361554, 0.499617, 0.0383231, 0.527285, -0.0423982, 0.499731, 0.045026, 0.527602, -0.0491121, 0.499924, 0.0522936, 0.528166, -0.0561127, 0.500306, 0.0601528, 0.52879, -0.0635988, 0.5007, 0.0686059, 0.529421, -0.071581, 0.501048, 0.0776518, 0.530144, -0.0799854, 0.501421, 0.0873148, 0.531062, -0.0888032, 0.501884, 0.0976084, 0.532374, -0.0977643, 0.50259, 0.108588, 0.533828, -0.107197, 0.50329, 0.120234, 0.53581, -0.116887, 0.504312, 0.132602, 0.538063, -0.126755, 0.505365, 0.145721, 0.5409, -0.136819, 0.506668, 0.159617, 0.544882, -0.147117, 0.508731, 0.174369, 0.550238, -0.157446, 0.511601, 0.190028, 0.556038, -0.167988, 0.514431, 0.206587, 0.563031, -0.178364, 0.517808, 0.224046, 0.571543, -0.189007, 0.521937, 0.242503, 0.582255, -0.199546, 0.527415, 0.261977, 0.59272, -0.210084, 0.531682, 0.282162, 0.605648, -0.220448, 0.537123, 0.303426, 0.61785, -0.230593, 0.540664, 0.325323, 0.632223, -0.240238, 0.544467, 0.348993, 0.648819, -0.24887, 0.547594, 0.375462, 0.665825, -0.256657, 0.54912, 0.403024, 0.683389, -0.263711, 0.549294, 0.431773, 0.701495, -0.269666, 0.547649, 0.461494, 0.719197, -0.274169, 0.543786, 0.491623, 0.737906, -0.278124, 0.538644, 0.522994, 0.756652, -0.280632, 0.531057, 0.554775, 0.775279, -0.281741, 0.521972, 0.586441, 0.792688, -0.281652, 0.509613, 0.618596, 0.811894, -0.280345, 0.496497, 0.651462, 0.827938, -0.277128, 0.47968, 0.684023, 0.844837, -0.271646, 0.460688, 0.718024, 0.859239, -0.264397, 0.438872, 0.751207, 0.874088, -0.256144, 0.41577, 0.784232, 0.887693, -0.246311, 0.391369, 0.816191, 0.899402, -0.235497, 0.365872, 0.847828, 0.910973, -0.223631, 0.338618, 0.87934, 0.92204, -0.209874, 0.310803, 0.910325, 0.930987, -0.194265, 0.281802, 0.940695, 0.94, -0.178125, 0.252836, 0.970958, 0.948018, -0.161479, 0.224239, 1.00078, 0.955141, -0.144038, 0.195857, 1.0288, 0.960513, -0.124915, 0.168487, 1.05371, 0.963964, -0.104284, 0.141495, 1.07596, 0.968713, -0.0838732, 0.114437, 1.09628, 0.975524, -0.0635579, 0.0863105, 1.11448, 0.98431, -0.042291, 0.0574774, 1.13069, 0.992916, -0.0209131, 0.0284343, 1.14568, 0.999926, 0.000743097, -0.000379265, 1.15955, 0.501042, -0.00000998428, 0.498726, 0.0000100306, 0.502992, -0.000252112, 0.500665, 0.000253283, 0.502417, -0.00100791, 0.500092, 0.00101259, 0.502965, -0.00226919, 0.500621, 0.00227978, 0.502318, -0.00403109, 0.499994, 0.00405011, 0.502333, -0.00629832, 0.500005, 0.00632868, 0.502362, -0.00906907, 0.500027, 0.00911446, 0.502369, -0.0123423, 0.500023, 0.0124078, 0.50243, -0.0161178, 0.500066, 0.016211, 0.502493, -0.0203937, 0.500103, 0.0205256, 0.502592, -0.0251684, 0.500166, 0.0253548, 0.502707, -0.0304389, 0.50023, 0.0307029, 0.502881, -0.0362015, 0.500335, 0.0365753, 0.503124, -0.0424507, 0.500488, 0.0429798, 0.503443, -0.0491582, 0.500686, 0.0499268, 0.504083, -0.0561476, 0.501155, 0.0574541, 0.504668, -0.0636846, 0.501524, 0.0655408, 0.505319, -0.0716834, 0.501904, 0.0742072, 0.50609, -0.0800925, 0.502321, 0.0834699, 0.507122, -0.0888425, 0.502896, 0.0933603, 0.508414, -0.097855, 0.503603, 0.10391, 0.509955, -0.107304, 0.504416, 0.115113, 0.512061, -0.116921, 0.505565, 0.127054, 0.514419, -0.12689, 0.506732, 0.139709, 0.517529, -0.136934, 0.508338, 0.153173, 0.522085, -0.147327, 0.510987, 0.167528, 0.526986, -0.157612, 0.513527, 0.182708, 0.533122, -0.168213, 0.516717, 0.198881, 0.540807, -0.178688, 0.520832, 0.215986, 0.550687, -0.189511, 0.52632, 0.234335, 0.560567, -0.199998, 0.531009, 0.253375, 0.571698, -0.210652, 0.535839, 0.273499, 0.584364, -0.220917, 0.541091, 0.294355, 0.599066, -0.23137, 0.546875, 0.316525, 0.614148, -0.241206, 0.551306, 0.339671, 0.631157, -0.250379, 0.555187, 0.36531, 0.647919, -0.258397, 0.556595, 0.392767, 0.666112, -0.265528, 0.556949, 0.421397, 0.686158, -0.271827, 0.556617, 0.451433, 0.704838, -0.27674, 0.552975, 0.482131, 0.723957, -0.280733, 0.547814, 0.513458, 0.74262, -0.283359, 0.53997, 0.545446, 0.762009, -0.284541, 0.530422, 0.57775, 0.781314, -0.284507, 0.518546, 0.610434, 0.799116, -0.283309, 0.504178, 0.643178, 0.817604, -0.280378, 0.48843, 0.676248, 0.83459, -0.275619, 0.469457, 0.709698, 0.850974, -0.26856, 0.447698, 0.744245, 0.866747, -0.260094, 0.424791, 0.777695, 0.881412, -0.249929, 0.399913, 0.810392, 0.8936, -0.239137, 0.37308, 0.842872, 0.905943, -0.226818, 0.345705, 0.874677, 0.916408, -0.213699, 0.31706, 0.906257, 0.927215, -0.198428, 0.288444, 0.936881, 0.935625, -0.181643, 0.258329, 0.96795, 0.944076, -0.164386, 0.228488, 0.998216, 0.951229, -0.146339, 0.199763, 1.02689, 0.958793, -0.127709, 0.172153, 1.0535, 0.963219, -0.107244, 0.144989, 1.07646, 0.967562, -0.0857764, 0.11685, 1.09675, 0.974866, -0.0645377, 0.0880571, 1.11576, 0.983353, -0.0431732, 0.0587352, 1.13227, 0.992503, -0.0218356, 0.0294181, 1.1478, 1.00003, 0.000605203, -0.000231013, 1.16207, 0.482935, -0.0000101177, 0.504695, 0.00000968142, 0.477554, -0.000251521, 0.499071, 0.000240676, 0.477904, -0.00100683, 0.499436, 0.00096342, 0.478368, -0.00226636, 0.499899, 0.0021687, 0.477977, -0.00402719, 0.499513, 0.00385384, 0.477993, -0.00629226, 0.499525, 0.0060221, 0.478011, -0.00906011, 0.499536, 0.00867289, 0.478051, -0.0123305, 0.499566, 0.0118074, 0.478089, -0.016102, 0.499587, 0.0154269, 0.478171, -0.0203736, 0.499645, 0.0195341, 0.478254, -0.025143, 0.499692, 0.0241318, 0.47839, -0.0304071, 0.499779, 0.0292247, 0.478588, -0.0361631, 0.499911, 0.0348196, 0.478812, -0.0424023, 0.500046, 0.0409231, 0.479208, -0.0490724, 0.500326, 0.047552, 0.479841, -0.0560722, 0.500805, 0.0547377, 0.480392, -0.0636125, 0.501152, 0.0624607, 0.481068, -0.0716134, 0.501561, 0.0707473, 0.481898, -0.0800062, 0.502054, 0.0796118, 0.483022, -0.0886568, 0.502728, 0.0890974, 0.484332, -0.0977553, 0.503479, 0.0992099, 0.486126, -0.107173, 0.504546, 0.10999, 0.488066, -0.11677, 0.50557, 0.121476, 0.490521, -0.126725, 0.506849, 0.133672, 0.494232, -0.136793, 0.50911, 0.146731, 0.498302, -0.147116, 0.511345, 0.160577, 0.503565, -0.157446, 0.514344, 0.175335, 0.510902, -0.168121, 0.518824, 0.191207, 0.519263, -0.178799, 0.523666, 0.208058, 0.528204, -0.189407, 0.528296, 0.225875, 0.538854, -0.200145, 0.533724, 0.244782, 0.551278, -0.210701, 0.539833, 0.264753, 0.565222, -0.221303, 0.546131, 0.285745, 0.579403, -0.231688, 0.551496, 0.307592, 0.595469, -0.241718, 0.556809, 0.330582, 0.610929, -0.250992, 0.559641, 0.354995, 0.629433, -0.259602, 0.562379, 0.382471, 0.648504, -0.267038, 0.563676, 0.411126, 0.66756, -0.273388, 0.562092, 0.440924, 0.689143, -0.278788, 0.560807, 0.472118, 0.709056, -0.282783, 0.555701, 0.503774, 0.729855, -0.285836, 0.548698, 0.536364, 0.748954, -0.287078, 0.538544, 0.56895, 0.768373, -0.287133, 0.526711, 0.601991, 0.78827, -0.285839, 0.512511, 0.635403, 0.807465, -0.283238, 0.496323, 0.668797, 0.825194, -0.27906, 0.477638, 0.702584, 0.842203, -0.272286, 0.456253, 0.736393, 0.857749, -0.263854, 0.432412, 0.77096, 0.874799, -0.253943, 0.407806, 0.80489, 0.887497, -0.24237, 0.38033, 0.83771, 0.89966, -0.230278, 0.352446, 0.870376, 0.911753, -0.21646, 0.323268, 0.902256, 0.923011, -0.202071, 0.294314, 0.933306, 0.932375, -0.185519, 0.264104, 0.965177, 0.940537, -0.167604, 0.234035, 0.996303, 0.948904, -0.149068, 0.20412, 1.0261, 0.955263, -0.129539, 0.175431, 1.05304, 0.960303, -0.109932, 0.148116, 1.07617, 0.965512, -0.0880572, 0.119693, 1.09742, 0.973466, -0.0660548, 0.0901619, 1.11721, 0.98284, -0.0439228, 0.0599875, 1.13436, 0.992216, -0.0219588, 0.0298975, 1.15006, 0.999946, 0.000119402, -0.0000208547, 1.16471, 0.447827, -0.0000100414, 0.491543, 0.00000914833, 0.454778, -0.000251257, 0.499172, 0.00022891, 0.453519, -0.00100342, 0.497787, 0.000914184, 0.45357, -0.00225776, 0.497847, 0.00205701, 0.453578, -0.00401371, 0.497855, 0.00365705, 0.45357, -0.00627107, 0.497841, 0.00571453, 0.453598, -0.00902968, 0.497864, 0.00823019, 0.453627, -0.0122888, 0.497882, 0.0112049, 0.453684, -0.0160475, 0.497923, 0.0146405, 0.453764, -0.0203044, 0.49798, 0.0185394, 0.453866, -0.0250576, 0.498049, 0.0229054, 0.453996, -0.0303028, 0.49813, 0.0277424, 0.454196, -0.0360379, 0.498267, 0.0330587, 0.454457, -0.0422521, 0.498445, 0.0388613, 0.454926, -0.0488393, 0.498812, 0.0451767, 0.455525, -0.0558653, 0.499272, 0.0520153, 0.456074, -0.0633772, 0.499625, 0.0593754, 0.456752, -0.0713606, 0.500049, 0.0672751, 0.457648, -0.07971, 0.500615, 0.0757447, 0.458849, -0.0883032, 0.501399, 0.0848231, 0.46029, -0.0974095, 0.502293, 0.0945135, 0.462, -0.106729, 0.503301, 0.104848, 0.464121, -0.116354, 0.504533, 0.115884, 0.466889, -0.126214, 0.506172, 0.127652, 0.470744, -0.136324, 0.508667, 0.14024, 0.47488, -0.146595, 0.510995, 0.153673, 0.480845, -0.157027, 0.514832, 0.168053, 0.488262, -0.167658, 0.519506, 0.183508, 0.496547, -0.178343, 0.524347, 0.199948, 0.506254, -0.188916, 0.52983, 0.217503, 0.517961, -0.199975, 0.536357, 0.236272, 0.531484, -0.210624, 0.543641, 0.256096, 0.545496, -0.221227, 0.550048, 0.277085, 0.559497, -0.231568, 0.555076, 0.298615, 0.575752, -0.241698, 0.560541, 0.321547, 0.591999, -0.251172, 0.564156, 0.345602, 0.610654, -0.260178, 0.567607, 0.371851, 0.630484, -0.268094, 0.56923, 0.40076, 0.651807, -0.274661, 0.569779, 0.430801, 0.67239, -0.280331, 0.566791, 0.461939, 0.693024, -0.284501, 0.562007, 0.493854, 0.715473, -0.287852, 0.555791, 0.526992, 0.736323, -0.28929, 0.546345, 0.560102, 0.755771, -0.289405, 0.534, 0.593543, 0.775424, -0.2881, 0.519114, 0.627256, 0.795447, -0.285562, 0.502543, 0.661464, 0.815319, -0.281416, 0.484773, 0.695206, 0.831769, -0.275523, 0.463445, 0.729044, 0.849464, -0.267516, 0.440269, 0.764069, 0.866775, -0.257584, 0.415049, 0.799089, 0.881252, -0.245817, 0.388049, 0.831948, 0.894209, -0.233127, 0.35889, 0.865526, 0.906922, -0.219579, 0.329915, 0.89818, 0.919686, -0.204491, 0.300441, 0.930013, 0.929044, -0.188962, 0.269445, 0.962061, 0.938393, -0.171079, 0.238402, 0.994214, 0.94661, -0.15199, 0.208204, 1.02533, 0.953095, -0.131953, 0.178653, 1.0529, 0.958644, -0.111233, 0.150684, 1.0771, 0.963925, -0.0903098, 0.122359, 1.09855, 0.971995, -0.0680505, 0.0923342, 1.11874, 0.981658, -0.0448512, 0.0614195, 1.13635, 0.991649, -0.0221931, 0.0303582, 1.15238, 0.999985, 0.000393403, -0.000111086, 1.16772, 0.396806, -0.00000971563, 0.457671, 0.00000842355, 0.429186, -0.000249421, 0.495017, 0.00021625, 0.429324, -0.000998052, 0.495173, 0.000865322, 0.429175, -0.00224487, 0.494999, 0.00194637, 0.429129, -0.00399041, 0.494952, 0.00346004, 0.429153, -0.00623476, 0.494974, 0.00540684, 0.429168, -0.0089773, 0.494983, 0.00778714, 0.429207, -0.0122175, 0.495012, 0.0106022, 0.429257, -0.0159542, 0.495047, 0.0138535, 0.429338, -0.0201864, 0.495106, 0.0175443, 0.429431, -0.0249104, 0.495165, 0.0216774, 0.429587, -0.0301252, 0.495279, 0.0262594, 0.429796, -0.0358249, 0.495432, 0.0312968, 0.430065, -0.0419972, 0.495621, 0.0367985, 0.430588, -0.0485144, 0.496061, 0.042798, 0.43113, -0.0555028, 0.496472, 0.0492914, 0.431743, -0.0629852, 0.496904, 0.0562907, 0.432448, -0.0709256, 0.497369, 0.0638056, 0.433414, -0.0791942, 0.498032, 0.071885, 0.434638, -0.0877346, 0.498854, 0.0805517, 0.43611, -0.0968056, 0.499812, 0.0898047, 0.437859, -0.106002, 0.500891, 0.0997142, 0.440017, -0.115648, 0.502198, 0.110289, 0.443236, -0.125427, 0.504389, 0.121644, 0.44697, -0.135492, 0.506809, 0.133769, 0.451689, -0.145746, 0.509858, 0.146787, 0.45811, -0.156219, 0.514247, 0.160793, 0.465305, -0.166834, 0.518816, 0.175791, 0.474085, -0.177546, 0.524331, 0.191906, 0.484808, -0.188262, 0.53104, 0.209199, 0.49732, -0.199346, 0.538511, 0.227825, 0.509693, -0.209951, 0.544554, 0.247269, 0.524367, -0.220533, 0.551616, 0.267978, 0.539228, -0.231082, 0.557368, 0.289672, 0.55644, -0.241342, 0.563782, 0.31268, 0.574204, -0.250964, 0.568851, 0.33651, 0.593388, -0.260306, 0.57312, 0.362219, 0.613358, -0.268667, 0.574916, 0.390322, 0.634512, -0.275591, 0.575053, 0.420478, 0.65563, -0.281328, 0.572404, 0.451614, 0.678265, -0.285948, 0.568893, 0.484112, 0.70011, -0.289408, 0.561878, 0.517348, 0.723005, -0.291328, 0.55359, 0.551355, 0.743744, -0.291418, 0.541099, 0.585109, 0.763949, -0.290252, 0.526489, 0.619487, 0.784186, -0.287648, 0.509496, 0.65404, 0.804304, -0.283782, 0.491484, 0.688649, 0.823629, -0.278067, 0.470517, 0.723133, 0.84094, -0.270588, 0.44705, 0.757163, 0.857852, -0.261188, 0.421252, 0.792816, 0.874934, -0.249313, 0.394191, 0.827248, 0.888709, -0.236492, 0.365359, 0.861074, 0.902589, -0.222185, 0.336016, 0.894417, 0.914201, -0.207314, 0.30527, 0.926825, 0.925978, -0.191146, 0.274532, 0.9595, 0.93512, -0.174135, 0.243393, 0.991583, 0.943656, -0.155231, 0.212414, 1.02356, 0.951719, -0.134403, 0.182005, 1.05239, 0.957164, -0.113023, 0.153043, 1.07754, 0.962656, -0.0914493, 0.124186, 1.09984, 0.970695, -0.0694179, 0.0941654, 1.12, 0.980749, -0.0466199, 0.0629671, 1.13849, 0.991205, -0.0227032, 0.0311146, 1.15494, 0.999884, 0.000632388, -0.000254483, 1.1706, 0.379821, -0.00000957289, 0.460637, 0.00000789337, 0.405188, -0.000247483, 0.491396, 0.000204064, 0.404796, -0.000989434, 0.490914, 0.000815853, 0.40483, -0.00222607, 0.490949, 0.00183559, 0.40473, -0.00395723, 0.49084, 0.00326332, 0.404731, -0.00618287, 0.490836, 0.00509945, 0.404768, -0.00890258, 0.490871, 0.00734463, 0.404791, -0.0121156, 0.490883, 0.00999992, 0.404857, -0.0158214, 0.490938, 0.0130676, 0.404943, -0.0200178, 0.491004, 0.0165503, 0.405059, -0.0247027, 0.491093, 0.0204521, 0.405213, -0.0298729, 0.491205, 0.0247788, 0.405399, -0.0355226, 0.491333, 0.0295373, 0.405731, -0.0416352, 0.491604, 0.034741, 0.406303, -0.0480807, 0.492116, 0.0404255, 0.406814, -0.0550458, 0.492506, 0.0465732, 0.407404, -0.0624652, 0.492926, 0.0532058, 0.408149, -0.0702958, 0.493442, 0.0603442, 0.409128, -0.0784623, 0.494136, 0.0680297, 0.410408, -0.087007, 0.495054, 0.0762786, 0.411813, -0.0959639, 0.495962, 0.0851046, 0.413735, -0.105075, 0.497257, 0.0945878, 0.416137, -0.114646, 0.498882, 0.104725, 0.41934, -0.124394, 0.501132, 0.11563, 0.423326, -0.134328, 0.503883, 0.127325, 0.428419, -0.14458, 0.50747, 0.139911, 0.43484, -0.154979, 0.511964, 0.153481, 0.442641, -0.165628, 0.517328, 0.168114, 0.452511, -0.176365, 0.524258, 0.183995, 0.463473, -0.187298, 0.531248, 0.200953, 0.475564, -0.198244, 0.538367, 0.219176, 0.488664, -0.208938, 0.545175, 0.238514, 0.504073, -0.219599, 0.553227, 0.259129, 0.520832, -0.230378, 0.560653, 0.280997, 0.538455, -0.240703, 0.567523, 0.303821, 0.55709, -0.250548, 0.573287, 0.327948, 0.576646, -0.259964, 0.577795, 0.353362, 0.596705, -0.268721, 0.580077, 0.380336, 0.618053, -0.276054, 0.58018, 0.4101, 0.640303, -0.282176, 0.578747, 0.44161, 0.662365, -0.286931, 0.574294, 0.474106, 0.684542, -0.290521, 0.567035, 0.507549, 0.707984, -0.292672, 0.558687, 0.541853, 0.730913, -0.293189, 0.547606, 0.576581, 0.752948, -0.292199, 0.533471, 0.61172, 0.773452, -0.289508, 0.516395, 0.646339, 0.794715, -0.285716, 0.497873, 0.682131, 0.814251, -0.280051, 0.476845, 0.716396, 0.833057, -0.272873, 0.453449, 0.751503, 0.84959, -0.263982, 0.427857, 0.786085, 0.867022, -0.252745, 0.400335, 0.821355, 0.882277, -0.239655, 0.371304, 0.85646, 0.895375, -0.225386, 0.340397, 0.890828, 0.909347, -0.209587, 0.310005, 0.923532, 0.921885, -0.193433, 0.2796, 0.956419, 0.932127, -0.176135, 0.247276, 0.989445, 0.941869, -0.157872, 0.216186, 1.02221, 0.949735, -0.137577, 0.185602, 1.05195, 0.956617, -0.115285, 0.155767, 1.07822, 0.961974, -0.0928418, 0.126103, 1.10149, 0.96972, -0.0700592, 0.0956758, 1.12207, 0.98012, -0.0474671, 0.0643269, 1.1408, 0.990825, -0.0238113, 0.0320863, 1.1577, 0.999876, 0.000381574, -0.0000812203, 1.17403, 0.367636, -0.00000961342, 0.469176, 0.00000753287, 0.380377, -0.000244772, 0.485434, 0.000191797, 0.380416, -0.000978857, 0.485475, 0.000767015, 0.380376, -0.00220165, 0.485435, 0.00172522, 0.380419, -0.00391408, 0.485487, 0.00306734, 0.380438, -0.00611549, 0.485505, 0.00479332, 0.380462, -0.00880558, 0.485525, 0.00690391, 0.380496, -0.0119837, 0.485551, 0.00940039, 0.38056, -0.0156487, 0.485605, 0.0122848, 0.38064, -0.0197988, 0.485666, 0.0155601, 0.380767, -0.0244324, 0.48577, 0.0192313, 0.380909, -0.0295444, 0.485871, 0.0233032, 0.381142, -0.0351321, 0.48606, 0.0277861, 0.381472, -0.0411535, 0.486336, 0.0326939, 0.382015, -0.0475408, 0.486833, 0.0380565, 0.382523, -0.0544395, 0.487231, 0.0438615, 0.383129, -0.061784, 0.487683, 0.0501332, 0.383952, -0.0695085, 0.488313, 0.0568996, 0.38498, -0.0775819, 0.489077, 0.0641952, 0.386331, -0.0860443, 0.490113, 0.0720324, 0.387788, -0.0948406, 0.491099, 0.0804379, 0.389808, -0.103899, 0.492566, 0.0894899, 0.39252, -0.113313, 0.494601, 0.0992098, 0.395493, -0.123007, 0.496619, 0.109641, 0.399826, -0.132859, 0.499912, 0.120919, 0.405341, -0.143077, 0.504061, 0.133107, 0.411932, -0.153465, 0.508905, 0.146263, 0.420591, -0.164108, 0.515482, 0.160544, 0.43101, -0.174893, 0.523191, 0.176123, 0.441881, -0.185839, 0.53026, 0.192757, 0.453919, -0.196633, 0.537295, 0.210535, 0.468715, -0.207611, 0.546156, 0.229886, 0.485182, -0.218517, 0.555173, 0.250543, 0.501926, -0.229249, 0.562728, 0.27221, 0.51785, -0.239481, 0.567494, 0.294892, 0.536947, -0.249395, 0.573889, 0.318987, 0.557115, -0.259, 0.578831, 0.344348, 0.577966, -0.268075, 0.582055, 0.371223, 0.599489, -0.276115, 0.583307, 0.399834, 0.62479, -0.282523, 0.583902, 0.431415, 0.647504, -0.287663, 0.57953, 0.464301, 0.670601, -0.291538, 0.573103, 0.498123, 0.693539, -0.293842, 0.563731, 0.532662, 0.717385, -0.294681, 0.553169, 0.567925, 0.741533, -0.293717, 0.539908, 0.603502, 0.762142, -0.291156, 0.521902, 0.639074, 0.783014, -0.28719, 0.502815, 0.674439, 0.805158, -0.281773, 0.482598, 0.710497, 0.823646, -0.274682, 0.458949, 0.7456, 0.841879, -0.266184, 0.433129, 0.781085, 0.859515, -0.255682, 0.406064, 0.816, 0.875335, -0.242849, 0.376509, 0.851074, 0.890147, -0.228329, 0.345502, 0.886473, 0.903144, -0.212491, 0.31428, 0.920751, 0.916618, -0.195695, 0.282994, 0.954606, 0.927953, -0.178267, 0.251091, 0.988402, 0.937414, -0.159549, 0.219107, 1.02141, 0.946823, -0.140022, 0.18896, 1.05167, 0.954651, -0.118154, 0.158667, 1.07819, 0.959955, -0.0946636, 0.128808, 1.1025, 0.96858, -0.0711792, 0.0973787, 1.12391, 0.97938, -0.0475046, 0.0650965, 1.14322, 0.990498, -0.024059, 0.0326267, 1.16077, 0.999844, -0.0000512408, 0.000112444, 1.17727, 0.316912, -0.00000934977, 0.425996, 0.00000695559, 0.356423, -0.000241372, 0.479108, 0.000179562, 0.356272, -0.000965292, 0.478897, 0.00071811, 0.356262, -0.00217182, 0.478894, 0.00161574, 0.356265, -0.00386092, 0.478895, 0.00287261, 0.356278, -0.0060324, 0.478905, 0.00448907, 0.356293, -0.00868565, 0.478914, 0.00646572, 0.356346, -0.0118207, 0.478965, 0.00880438, 0.356395, -0.0154355, 0.479001, 0.0115066, 0.356484, -0.019529, 0.479075, 0.0145762, 0.356609, -0.0240991, 0.47918, 0.018018, 0.356766, -0.0291413, 0.479305, 0.0218379, 0.357009, -0.0346498, 0.479512, 0.0260454, 0.357424, -0.0405462, 0.479909, 0.0306657, 0.357899, -0.0468825, 0.480337, 0.0357054, 0.358424, -0.0536887, 0.480771, 0.0411728, 0.359041, -0.0609416, 0.481242, 0.0470841, 0.359903, -0.0685239, 0.481943, 0.0534831, 0.360932, -0.0764883, 0.482741, 0.0603795, 0.362196, -0.0848364, 0.483688, 0.0678028, 0.363847, -0.0935002, 0.484947, 0.0758086, 0.365972, -0.102471, 0.486588, 0.0844173, 0.368741, -0.111751, 0.488787, 0.0937199, 0.372146, -0.121334, 0.491405, 0.103732, 0.377114, -0.131147, 0.495604, 0.114608, 0.38226, -0.141213, 0.499436, 0.126345, 0.389609, -0.151632, 0.505334, 0.139116, 0.397925, -0.162073, 0.51168, 0.152995, 0.407824, -0.172819, 0.518876, 0.168071, 0.420014, -0.183929, 0.527639, 0.184495, 0.434266, -0.195032, 0.537588, 0.20232, 0.447352, -0.205792, 0.544379, 0.221189, 0.463726, -0.216704, 0.553422, 0.241616, 0.481406, -0.227531, 0.562074, 0.263298, 0.498707, -0.238017, 0.568227, 0.286116, 0.518039, -0.247936, 0.574473, 0.3101, 0.538277, -0.257437, 0.579191, 0.335401, 0.561166, -0.266829, 0.584807, 0.362246, 0.583189, -0.275329, 0.586476, 0.390609, 0.606024, -0.28234, 0.585578, 0.420998, 0.632419, -0.287924, 0.584496, 0.454357, 0.656128, -0.291972, 0.577766, 0.488233, 0.679953, -0.29456, 0.56875, 0.523248, 0.704654, -0.295816, 0.558388, 0.559168, 0.729016, -0.295157, 0.544826, 0.595326, 0.752062, -0.292779, 0.528273, 0.631864, 0.773138, -0.288681, 0.508482, 0.667793, 0.794869, -0.283358, 0.487341, 0.704035, 0.815101, -0.27608, 0.46354, 0.739925, 0.834212, -0.26767, 0.438672, 0.775539, 0.852368, -0.257397, 0.411239, 0.810895, 0.870207, -0.245689, 0.3829, 0.846472, 0.884063, -0.231452, 0.351496, 0.881788, 0.898284, -0.215561, 0.31895, 0.917438, 0.912964, -0.198208, 0.287367, 0.952422, 0.924666, -0.180426, 0.254487, 0.987551, 0.934429, -0.161525, 0.222226, 1.02142, 0.943485, -0.141197, 0.191143, 1.05218, 0.9521, -0.120085, 0.161112, 1.07937, 0.957876, -0.0975881, 0.130982, 1.10403, 0.966943, -0.0726842, 0.0990553, 1.12616, 0.978313, -0.0483705, 0.0662818, 1.14619, 0.990048, -0.0239072, 0.0329243, 1.16413, 0.999984, 0.000461885, -0.0000772859, 1.18099, 0.321287, -0.00000935049, 0.455413, 0.00000659662, 0.332595, -0.000237513, 0.471437, 0.000167562, 0.332729, -0.000949964, 0.471618, 0.000670192, 0.332305, -0.00213618, 0.471028, 0.00150712, 0.332326, -0.00379765, 0.471055, 0.00267959, 0.332344, -0.00593353, 0.471072, 0.00418751, 0.332356, -0.00854349, 0.471077, 0.00603172, 0.332403, -0.0116268, 0.471121, 0.00821362, 0.332461, -0.0151824, 0.47117, 0.0107357, 0.332552, -0.0192088, 0.471251, 0.0136014, 0.332657, -0.0237024, 0.47133, 0.0168152, 0.332835, -0.0286615, 0.471487, 0.0203853, 0.333083, -0.0340765, 0.471708, 0.0243212, 0.333547, -0.0398563, 0.47219, 0.0286518, 0.333989, -0.0460916, 0.472587, 0.0333763, 0.334532, -0.0527897, 0.473054, 0.0385084, 0.335167, -0.0599284, 0.473568, 0.0440638, 0.33608, -0.0673514, 0.474362, 0.0500962, 0.337146, -0.0752237, 0.475231, 0.0566022, 0.338462, -0.083418, 0.476282, 0.0636272, 0.34014, -0.0919382, 0.477615, 0.0712153, 0.342341, -0.100741, 0.479404, 0.079417, 0.345088, -0.109905, 0.481618, 0.0882631, 0.349049, -0.119369, 0.485081, 0.0978851, 0.353939, -0.129033, 0.489317, 0.108336, 0.359893, -0.139038, 0.494309, 0.119698, 0.366945, -0.149411, 0.499983, 0.132024, 0.375814, -0.159843, 0.507185, 0.145558, 0.387112, -0.170664, 0.516392, 0.160433, 0.40023, -0.181897, 0.526519, 0.176648, 0.412555, -0.192785, 0.53423, 0.193922, 0.427023, -0.203663, 0.542741, 0.212662, 0.443685, -0.214695, 0.552066, 0.232944, 0.461499, -0.225561, 0.560762, 0.254495, 0.480975, -0.236257, 0.569421, 0.277531, 0.501, -0.24639, 0.576101, 0.301724, 0.521691, -0.256101, 0.581493, 0.327112, 0.543478, -0.265289, 0.585221, 0.353917, 0.566094, -0.273938, 0.587614, 0.381941, 0.589578, -0.281679, 0.587991, 0.41172, 0.614583, -0.287655, 0.585928, 0.444148, 0.641813, -0.292228, 0.582092, 0.478617, 0.666189, -0.295172, 0.57398, 0.51397, 0.690475, -0.29648, 0.561676, 0.550118, 0.715543, -0.296203, 0.548758, 0.586933, 0.740405, -0.293999, 0.532792, 0.62384, 0.762183, -0.28998, 0.512735, 0.660723, 0.786069, -0.28478, 0.492402, 0.69807, 0.806812, -0.277568, 0.469058, 0.734422, 0.826987, -0.268951, 0.443017, 0.770946, 0.844588, -0.259049, 0.415501, 0.80699, 0.863725, -0.2471, 0.387328, 0.842107, 0.879137, -0.234157, 0.356108, 0.878078, 0.894634, -0.218719, 0.324315, 0.914058, 0.909162, -0.201293, 0.291813, 0.949922, 0.92072, -0.18267, 0.258474, 0.985337, 0.93158, -0.163212, 0.225593, 1.0205, 0.941238, -0.142771, 0.193986, 1.05273, 0.949293, -0.120956, 0.163392, 1.08075, 0.956226, -0.0985743, 0.132934, 1.10559, 0.96546, -0.075118, 0.101255, 1.12823, 0.977403, -0.0497921, 0.0675441, 1.149, 0.989648, -0.0241574, 0.0334681, 1.16765, 1.00001, 0.0005762, -0.000184807, 1.18519, 0.303474, -0.00000916603, 0.4542, 0.0000061243, 0.308894, -0.000232869, 0.462306, 0.000155592, 0.309426, -0.000931661, 0.463093, 0.000622499, 0.308643, -0.0020949, 0.461933, 0.00139979, 0.308651, -0.0037242, 0.461941, 0.00248874, 0.308662, -0.00581873, 0.46195, 0.00388933, 0.308687, -0.00837818, 0.461974, 0.00560247, 0.308728, -0.0114016, 0.462011, 0.00762948, 0.308789, -0.0148884, 0.462067, 0.00997326, 0.308882, -0.0188369, 0.462151, 0.0126375, 0.309007, -0.0232436, 0.462263, 0.0156271, 0.30918, -0.0281054, 0.462417, 0.0189498, 0.309442, -0.0334065, 0.462667, 0.0226167, 0.309901, -0.0390589, 0.463162, 0.0266614, 0.310331, -0.0452042, 0.463555, 0.0310715, 0.310858, -0.0517735, 0.464019, 0.0358698, 0.311576, -0.0587359, 0.464669, 0.0410848, 0.312436, -0.0660383, 0.465406, 0.0467453, 0.313526, -0.0737266, 0.466339, 0.0528718, 0.314903, -0.0817574, 0.467504, 0.0595039, 0.316814, -0.090167, 0.469226, 0.0666888, 0.318965, -0.0987555, 0.470981, 0.0744658, 0.322077, -0.107792, 0.473814, 0.082912, 0.325947, -0.117098, 0.477241, 0.0920846, 0.331008, -0.126602, 0.48184, 0.102137, 0.337893, -0.136619, 0.488334, 0.113135, 0.345106, -0.146838, 0.494415, 0.12511, 0.355111, -0.157357, 0.503275, 0.138356, 0.365095, -0.167955, 0.510966, 0.152686, 0.378344, -0.179157, 0.521508, 0.16856, 0.391599, -0.190143, 0.530455, 0.18561, 0.407786, -0.20123, 0.541275, 0.204308, 0.425294, -0.212456, 0.551784, 0.224623, 0.444021, -0.223568, 0.561493, 0.246172, 0.463418, -0.234154, 0.569886, 0.268979, 0.484077, -0.244546, 0.577116, 0.293411, 0.505513, -0.254301, 0.582914, 0.318936, 0.527672, -0.263564, 0.587208, 0.345856, 0.550565, -0.272332, 0.589277, 0.374054, 0.573656, -0.280011, 0.588426, 0.403276, 0.59827, -0.286924, 0.587504, 0.43474, 0.624731, -0.291994, 0.583401, 0.468767, 0.652396, -0.295159, 0.576997, 0.504411, 0.67732, -0.296954, 0.565863, 0.54114, 0.703147, -0.296877, 0.552316, 0.57816, 0.728715, -0.295147, 0.536773, 0.616124, 0.752448, -0.291275, 0.51771, 0.653885, 0.775169, -0.285905, 0.496087, 0.691537, 0.799307, -0.279064, 0.474232, 0.729251, 0.819482, -0.270294, 0.447676, 0.766267, 0.837659, -0.260032, 0.419656, 0.802616, 0.856903, -0.248497, 0.391328, 0.838583, 0.873325, -0.235252, 0.360285, 0.874711, 0.889788, -0.221126, 0.329215, 0.91077, 0.904486, -0.204304, 0.296392, 0.94653, 0.917711, -0.185562, 0.262159, 0.983828, 0.928969, -0.165635, 0.229142, 1.01955, 0.939707, -0.14442, 0.19673, 1.05317, 0.948167, -0.122147, 0.165095, 1.0823, 0.955222, -0.099098, 0.13451, 1.10791, 0.964401, -0.0755332, 0.102476, 1.1312, 0.976605, -0.0513817, 0.0689667, 1.15218, 0.989085, -0.0258499, 0.034506, 1.17129, 0.999908, 0.000617773, -0.000271268, 1.18961, 0.285803, -0.00000905752, 0.452348, 0.00000572272, 0.284689, -0.00022732, 0.450581, 0.000143626, 0.285263, -0.000910214, 0.451482, 0.000575099, 0.285302, -0.00204784, 0.451553, 0.00129395, 0.285318, -0.00364057, 0.451574, 0.0023006, 0.28533, -0.00568813, 0.451585, 0.00359547, 0.285361, -0.00819001, 0.451618, 0.00517934, 0.285397, -0.0111458, 0.45165, 0.007054, 0.285447, -0.0145536, 0.451688, 0.00922167, 0.285527, -0.0184127, 0.451758, 0.0116869, 0.285688, -0.0227207, 0.451929, 0.0144555, 0.28584, -0.0274712, 0.452055, 0.0175341, 0.286136, -0.0326278, 0.452369, 0.0209406, 0.286574, -0.0381792, 0.452853, 0.0246965, 0.287012, -0.0441879, 0.453272, 0.0287996, 0.287542, -0.0506096, 0.453752, 0.033268, 0.288299, -0.0573634, 0.454488, 0.0381504, 0.289186, -0.0645458, 0.455294, 0.0434447, 0.290302, -0.0720405, 0.456301, 0.0491973, 0.291776, -0.0799046, 0.457648, 0.0554453, 0.29372, -0.088117, 0.459483, 0.0622311, 0.296052, -0.0965328, 0.461571, 0.0695992, 0.299563, -0.105409, 0.465085, 0.077658, 0.30335, -0.114553, 0.468506, 0.0864176, 0.309167, -0.123917, 0.474423, 0.0961078, 0.31529, -0.13381, 0.47995, 0.106643, 0.324163, -0.144021, 0.488592, 0.118322, 0.333272, -0.154382, 0.496461, 0.131133, 0.344224, -0.165015, 0.50562, 0.145208, 0.357733, -0.176168, 0.516719, 0.16073, 0.373046, -0.187468, 0.528513, 0.177807, 0.38788, -0.198488, 0.537713, 0.196072, 0.405133, -0.209545, 0.547999, 0.21605, 0.423845, -0.220724, 0.55759, 0.237484, 0.443777, -0.231518, 0.566246, 0.26039, 0.464824, -0.242035, 0.574326, 0.284835, 0.486635, -0.251898, 0.58037, 0.310518, 0.51012, -0.261304, 0.58568, 0.337678, 0.535301, -0.270384, 0.590197, 0.366242, 0.559193, -0.27841, 0.590569, 0.395873, 0.583544, -0.285325, 0.588161, 0.426857, 0.608834, -0.291113, 0.584249, 0.459477, 0.635753, -0.294882, 0.57763, 0.494734, 0.664367, -0.297088, 0.569479, 0.532023, 0.689688, -0.297364, 0.555064, 0.569629, 0.715732, -0.295949, 0.539522, 0.608124, 0.741307, -0.292259, 0.521613, 0.646231, 0.764949, -0.287063, 0.49969, 0.684938, 0.788599, -0.28012, 0.476747, 0.723548, 0.81048, -0.27153, 0.45116, 0.761135, 0.831372, -0.261289, 0.424101, 0.798916, 0.850092, -0.249559, 0.39443, 0.835952, 0.867777, -0.236348, 0.363849, 0.871606, 0.884632, -0.221569, 0.332477, 0.907843, 0.90047, -0.20618, 0.300667, 0.944187, 0.914524, -0.188771, 0.266552, 0.981371, 0.926892, -0.168362, 0.232349, 1.01841, 0.937951, -0.146761, 0.199359, 1.05308, 0.947236, -0.123813, 0.1675, 1.0839, 0.954367, -0.099984, 0.136166, 1.11047, 0.963907, -0.0759278, 0.103808, 1.13414, 0.976218, -0.0511367, 0.0697061, 1.15575, 0.988772, -0.0267415, 0.0352529, 1.17531, 0.999888, -0.000520778, 0.000289926, 1.19389, 0.263546, -0.00000883274, 0.441896, 0.00000526783, 0.262352, -0.000221849, 0.439889, 0.000132311, 0.262325, -0.000886683, 0.439848, 0.000528824, 0.26228, -0.00199476, 0.439765, 0.00118975, 0.262372, -0.00354671, 0.439922, 0.00211568, 0.26239, -0.00554141, 0.439941, 0.00330652, 0.262412, -0.00797888, 0.439961, 0.00476346, 0.262453, -0.0108584, 0.440002, 0.00648818, 0.262528, -0.0141788, 0.440085, 0.0084835, 0.262615, -0.017938, 0.440166, 0.0107533, 0.262744, -0.0221346, 0.440291, 0.0133044, 0.262939, -0.026762, 0.440493, 0.0161445, 0.263277, -0.0317573, 0.440889, 0.0192974, 0.26368, -0.0371832, 0.441338, 0.0227699, 0.264106, -0.0430371, 0.441753, 0.0265698, 0.264624, -0.0493035, 0.442227, 0.0307178, 0.265378, -0.0558669, 0.442985, 0.0352616, 0.266253, -0.0628718, 0.443795, 0.0401968, 0.267478, -0.0701569, 0.445008, 0.04559, 0.269062, -0.077845, 0.446599, 0.0514539, 0.270926, -0.0857941, 0.448349, 0.0578382, 0.273693, -0.0940773, 0.451221, 0.0648363, 0.276746, -0.102704, 0.454097, 0.0724389, 0.281693, -0.111735, 0.459517, 0.0808744, 0.287335, -0.121004, 0.46531, 0.0901551, 0.29448, -0.130734, 0.472605, 0.100371, 0.30257, -0.140777, 0.480251, 0.111644, 0.312465, -0.15111, 0.489444, 0.124111, 0.324856, -0.16189, 0.500919, 0.137979, 0.33774, -0.172946, 0.511317, 0.153163, 0.35255, -0.184152, 0.522684, 0.169817, 0.367786, -0.19522, 0.53248, 0.187886, 0.385474, -0.20632, 0.543326, 0.207634, 0.404976, -0.217744, 0.554109, 0.229165, 0.425203, -0.228691, 0.563395, 0.252068, 0.446704, -0.239299, 0.571565, 0.276471, 0.468951, -0.249348, 0.577935, 0.302323, 0.493487, -0.258933, 0.584309, 0.329882, 0.517861, -0.268009, 0.58773, 0.358525, 0.543309, -0.276238, 0.589612, 0.388585, 0.569704, -0.28356, 0.589294, 0.419787, 0.594871, -0.289497, 0.585137, 0.452114, 0.622555, -0.294452, 0.580356, 0.486466, 0.651167, -0.296918, 0.57185, 0.523079, 0.677332, -0.297647, 0.558428, 0.5611, 0.703718, -0.296321, 0.542232, 0.599592, 0.730262, -0.293339, 0.524541, 0.639138, 0.754304, -0.288036, 0.502691, 0.677978, 0.778051, -0.281018, 0.479212, 0.716537, 0.801557, -0.272414, 0.454071, 0.75586, 0.822559, -0.262419, 0.425952, 0.794477, 0.843051, -0.250702, 0.397313, 0.832664, 0.86232, -0.237264, 0.366534, 0.869876, 0.879044, -0.222716, 0.334816, 0.906973, 0.896362, -0.206827, 0.303143, 0.943558, 0.910342, -0.189659, 0.269699, 0.979759, 0.924119, -0.171108, 0.236411, 1.01718, 0.935374, -0.149579, 0.202224, 1.05289, 0.944295, -0.126295, 0.16989, 1.08496, 0.952227, -0.101511, 0.138089, 1.11256, 0.962041, -0.0766392, 0.105053, 1.1375, 0.97528, -0.0511967, 0.070329, 1.15983, 0.988476, -0.025463, 0.0351268, 1.17987, 0.999962, 0.0000286808, 0.0000145564, 1.19901, 0.227089, -0.00000841413, 0.404216, 0.00000472707, 0.239725, -0.000215083, 0.426708, 0.000120833, 0.239904, -0.000860718, 0.427028, 0.000483555, 0.239911, -0.00193661, 0.427039, 0.00108806, 0.239914, -0.00344276, 0.42704, 0.00193457, 0.239933, -0.00537907, 0.427064, 0.00302363, 0.239944, -0.00774482, 0.427065, 0.00435604, 0.239993, -0.01054, 0.427122, 0.00593398, 0.240052, -0.0137626, 0.427179, 0.00775987, 0.240148, -0.0174115, 0.427279, 0.00983854, 0.240278, -0.021484, 0.42741, 0.0121763, 0.240472, -0.0259729, 0.427618, 0.0147827, 0.240839, -0.0308131, 0.428086, 0.0176837, 0.241201, -0.0360893, 0.428482, 0.0208775, 0.241626, -0.0417723, 0.428907, 0.0243821, 0.242207, -0.0478337, 0.42952, 0.0282228, 0.24298, -0.0542199, 0.430332, 0.0324333, 0.243881, -0.0610015, 0.431222, 0.0370252, 0.245123, -0.0680874, 0.432512, 0.0420535, 0.24667, -0.0755482, 0.434088, 0.0475414, 0.248779, -0.0832873, 0.436323, 0.0535542, 0.251665, -0.0913546, 0.439509, 0.0601716, 0.255305, -0.0998489, 0.443478, 0.0674282, 0.260049, -0.108576, 0.448713, 0.0754673, 0.266192, -0.117754, 0.455524, 0.084339, 0.273158, -0.127294, 0.4627, 0.0941683, 0.282131, -0.137311, 0.472068, 0.10515, 0.293332, -0.147736, 0.483565, 0.117402, 0.304667, -0.158357, 0.493702, 0.130824, 0.317785, -0.169274, 0.504708, 0.145724, 0.333245, -0.180595, 0.517107, 0.16215, 0.349843, -0.191892, 0.528849, 0.180149, 0.367944, -0.203168, 0.540301, 0.199746, 0.387579, -0.214443, 0.551514, 0.221047, 0.408247, -0.225624, 0.560906, 0.243981, 0.43014, -0.236422, 0.56959, 0.268513, 0.452669, -0.24654, 0.576098, 0.294409, 0.476196, -0.256157, 0.580925, 0.322002, 0.501157, -0.265289, 0.584839, 0.351052, 0.527632, -0.273671, 0.587614, 0.3812, 0.555754, -0.281254, 0.589119, 0.412994, 0.581682, -0.287448, 0.585204, 0.445498, 0.608196, -0.292614, 0.579006, 0.479505, 0.635661, -0.296068, 0.571297, 0.514643, 0.664999, -0.297395, 0.560855, 0.552213, 0.691039, -0.296645, 0.544525, 0.591365, 0.7179, -0.293785, 0.526535, 0.630883, 0.744059, -0.289089, 0.50545, 0.670932, 0.76863, -0.282239, 0.482514, 0.710904, 0.793273, -0.273688, 0.457246, 0.750259, 0.814731, -0.26328, 0.428872, 0.78948, 0.835603, -0.251526, 0.399384, 0.828597, 0.85489, -0.238339, 0.368811, 0.866892, 0.872828, -0.223607, 0.336617, 0.90563, 0.889462, -0.207538, 0.303997, 0.943538, 0.904929, -0.190297, 0.270812, 0.980591, 0.919101, -0.172034, 0.237453, 1.01935, 0.930536, -0.152058, 0.204431, 1.05498, 0.941223, -0.129515, 0.172495, 1.08717, 0.94982, -0.104263, 0.140175, 1.11551, 0.960592, -0.0781944, 0.106465, 1.14098, 0.974629, -0.051688, 0.0711592, 1.16418, 0.98811, -0.0253929, 0.0354432, 1.18465, 1.00004, 0.000804378, -0.000330876, 1.20462, 0.214668, -0.00000821282, 0.406619, 0.00000433582, 0.218053, -0.000208144, 0.413025, 0.000109887, 0.217987, -0.000832212, 0.412901, 0.000439362, 0.217971, -0.00187246, 0.412876, 0.000988623, 0.217968, -0.00332855, 0.41286, 0.00175772, 0.217985, -0.00520055, 0.412882, 0.00274729, 0.218014, -0.00748814, 0.412916, 0.00395842, 0.218054, -0.0101901, 0.412957, 0.00539274, 0.218106, -0.0133057, 0.413005, 0.00705348, 0.218217, -0.0168342, 0.413139, 0.00894581, 0.218338, -0.0207707, 0.413258, 0.0110754, 0.21855, -0.0251001, 0.413509, 0.0134551, 0.218913, -0.0297861, 0.413992, 0.0161081, 0.219265, -0.0348956, 0.414383, 0.0190307, 0.219696, -0.0403909, 0.414839, 0.0222458, 0.220329, -0.0462003, 0.415567, 0.025792, 0.220989, -0.0524208, 0.41621, 0.0296637, 0.222027, -0.058948, 0.417385, 0.0339323, 0.223301, -0.0658208, 0.418779, 0.0386055, 0.224988, -0.0730347, 0.420665, 0.0437355, 0.227211, -0.0805274, 0.423198, 0.0493844, 0.230131, -0.088395, 0.426566, 0.0556135, 0.233908, -0.0966208, 0.43091, 0.0624829, 0.239092, -0.105223, 0.437148, 0.0701636, 0.245315, -0.11424, 0.444302, 0.0786949, 0.253166, -0.12368, 0.453262, 0.0882382, 0.262374, -0.133569, 0.463211, 0.0988682, 0.273145, -0.143836, 0.474271, 0.110727, 0.285512, -0.154577, 0.4863, 0.123945, 0.299512, -0.165501, 0.498817, 0.138581, 0.314287, -0.176698, 0.510341, 0.154676, 0.331083, -0.188066, 0.522583, 0.172459, 0.349615, -0.199597, 0.534879, 0.191979, 0.369318, -0.210843, 0.546083, 0.21309, 0.390377, -0.222068, 0.5562, 0.235998, 0.412411, -0.233059, 0.564704, 0.260518, 0.435715, -0.24357, 0.572314, 0.286795, 0.461196, -0.253356, 0.579395, 0.314559, 0.485587, -0.262362, 0.581985, 0.343581, 0.511908, -0.270895, 0.584347, 0.374367, 0.539798, -0.278452, 0.58505, 0.406015, 0.567974, -0.284877, 0.583344, 0.439168, 0.594303, -0.290124, 0.577348, 0.473005, 0.622951, -0.294183, 0.570751, 0.508534, 0.652404, -0.296389, 0.561541, 0.544764, 0.679291, -0.296605, 0.546426, 0.582927, 0.706437, -0.294095, 0.528599, 0.622681, 0.734485, -0.28978, 0.508676, 0.663567, 0.758841, -0.283363, 0.484768, 0.704092, 0.78537, -0.275015, 0.460434, 0.745101, 0.807315, -0.264689, 0.432166, 0.784712, 0.8271, -0.252597, 0.401807, 0.824241, 0.849191, -0.239154, 0.371458, 0.863803, 0.867046, -0.224451, 0.338873, 0.903063, 0.8852, -0.208342, 0.306175, 0.942763, 0.901771, -0.190684, 0.272759, 0.981559, 0.915958, -0.172105, 0.239306, 1.02048, 0.928046, -0.152214, 0.206071, 1.05765, 0.939961, -0.130247, 0.17367, 1.08999, 0.948711, -0.10672, 0.142201, 1.11829, 0.959305, -0.0808688, 0.108454, 1.14467, 0.973009, -0.0539145, 0.0728109, 1.16839, 0.987631, -0.0262947, 0.0360625, 1.19004, 0.999978, 0.00132758, -0.000559424, 1.21058, 0.193925, -0.00000793421, 0.391974, 0.00000392537, 0.196746, -0.000200315, 0.397675, 0.0000991033, 0.19667, -0.000801099, 0.397521, 0.000396342, 0.196633, -0.00180246, 0.397445, 0.000891829, 0.196654, -0.00320443, 0.397482, 0.00158582, 0.196659, -0.00500647, 0.39748, 0.00247867, 0.196683, -0.0072086, 0.397506, 0.00357167, 0.196728, -0.00981001, 0.397562, 0.00486675, 0.196792, -0.0128096, 0.397633, 0.00636707, 0.19689, -0.0162055, 0.397746, 0.00807752, 0.197017, -0.0199943, 0.397884, 0.0100052, 0.19729, -0.024139, 0.39827, 0.0121691, 0.197583, -0.0286671, 0.398639, 0.0145755, 0.197927, -0.0335858, 0.399034, 0.0172355, 0.198383, -0.0388806, 0.399554, 0.0201718, 0.199002, -0.0444736, 0.400289, 0.0234194, 0.199739, -0.0504583, 0.401111, 0.026984, 0.200784, -0.056729, 0.402349, 0.0309217, 0.202075, -0.0633643, 0.403841, 0.0352496, 0.203898, -0.0703247, 0.406076, 0.0400313, 0.206199, -0.0775565, 0.408841, 0.0453282, 0.209252, -0.085184, 0.41259, 0.0511794, 0.213638, -0.0931994, 0.418288, 0.0577459, 0.21881, -0.101617, 0.424681, 0.0650508, 0.225642, -0.11052, 0.433429, 0.0732759, 0.233717, -0.119772, 0.442897, 0.0824683, 0.242823, -0.129505, 0.452888, 0.0927484, 0.254772, -0.139906, 0.466407, 0.104417, 0.266603, -0.150402, 0.477413, 0.117211, 0.28073, -0.161395, 0.490519, 0.131598, 0.295399, -0.172465, 0.50201, 0.147407, 0.312705, -0.183982, 0.515311, 0.165031, 0.331335, -0.195532, 0.52786, 0.184336, 0.351037, -0.206971, 0.5392, 0.205361, 0.372175, -0.218117, 0.54941, 0.228043, 0.394548, -0.229327, 0.558642, 0.25267, 0.419598, -0.240052, 0.567861, 0.279071, 0.443922, -0.249937, 0.573332, 0.306882, 0.471495, -0.259407, 0.58013, 0.33661, 0.496769, -0.267749, 0.580564, 0.367328, 0.524951, -0.275524, 0.581696, 0.399753, 0.55318, -0.282148, 0.579885, 0.433134, 0.581577, -0.287533, 0.575471, 0.467534, 0.609231, -0.291612, 0.567445, 0.502943, 0.637478, -0.293911, 0.557657, 0.53871, 0.667795, -0.295096, 0.546535, 0.576568, 0.694272, -0.294073, 0.529561, 0.614929, 0.722937, -0.290386, 0.510561, 0.655909, 0.749682, -0.284481, 0.487846, 0.697663, 0.774754, -0.276188, 0.462487, 0.738515, 0.799301, -0.266215, 0.43481, 0.779802, 0.820762, -0.254116, 0.404879, 0.820045, 0.843231, -0.240393, 0.374559, 0.860294, 0.861857, -0.225503, 0.341582, 0.900965, 0.880815, -0.209382, 0.308778, 0.941727, 0.89766, -0.19155, 0.275232, 0.980916, 0.912926, -0.172346, 0.240938, 1.02162, 0.926391, -0.151799, 0.207223, 1.0597, 0.938429, -0.129968, 0.17484, 1.09291, 0.947834, -0.10651, 0.142984, 1.12248, 0.958432, -0.0824098, 0.109902, 1.149, 0.972402, -0.0565242, 0.0744454, 1.1733, 0.987191, -0.028427, 0.0373794, 1.19538, 0.999975, 0.0000385685, -0.00004203, 1.21676, 0.178114, -0.00000766075, 0.385418, 0.00000354027, 0.176074, -0.000191966, 0.381002, 0.0000887135, 0.17601, -0.000767549, 0.380861, 0.000354715, 0.17598, -0.00172696, 0.380798, 0.000798168, 0.175994, -0.00307012, 0.380824, 0.00141928, 0.176017, -0.00479684, 0.380858, 0.00221859, 0.176019, -0.00690648, 0.380839, 0.00319714, 0.176072, -0.00939888, 0.380913, 0.0043572, 0.176131, -0.0122726, 0.380979, 0.005702, 0.176239, -0.0155264, 0.38112, 0.00723689, 0.176371, -0.0191551, 0.381272, 0.00896907, 0.176638, -0.023117, 0.381669, 0.0109194, 0.176912, -0.0274633, 0.382015, 0.0130903, 0.177279, -0.032173, 0.382476, 0.0154949, 0.17774, -0.0372219, 0.383041, 0.0181669, 0.178344, -0.0426132, 0.38378, 0.0211209, 0.179153, -0.0483309, 0.384773, 0.0243899, 0.180197, -0.0543447, 0.386076, 0.0280062, 0.181581, -0.0607122, 0.387809, 0.032004, 0.18344, -0.0673855, 0.390205, 0.036453, 0.186139, -0.0743989, 0.393944, 0.0414162, 0.189432, -0.0817731, 0.39832, 0.0469394, 0.193795, -0.0895464, 0.404188, 0.0531442, 0.199641, -0.0978264, 0.4121, 0.0601374, 0.206679, -0.106499, 0.421425, 0.0680078, 0.214865, -0.115654, 0.431504, 0.076919, 0.224406, -0.125268, 0.442526, 0.0868835, 0.235876, -0.135475, 0.455465, 0.0981875, 0.248335, -0.146023, 0.4681, 0.110759, 0.262868, -0.157016, 0.482069, 0.124885, 0.278962, -0.168245, 0.496182, 0.140645, 0.295082, -0.17958, 0.507401, 0.157838, 0.313738, -0.191227, 0.520252, 0.17695, 0.333573, -0.202718, 0.531708, 0.197817, 0.356433, -0.214424, 0.544509, 0.220785, 0.378853, -0.225492, 0.55373, 0.245306, 0.402717, -0.236236, 0.561348, 0.271593, 0.428375, -0.246568, 0.568538, 0.299776, 0.454724, -0.255941, 0.573462, 0.329433, 0.482291, -0.264511, 0.576356, 0.360598, 0.509706, -0.272129, 0.576446, 0.393204, 0.538805, -0.278979, 0.575298, 0.427227, 0.568919, -0.284528, 0.572154, 0.462157, 0.596804, -0.288801, 0.564691, 0.497997, 0.625987, -0.291334, 0.555134, 0.534467, 0.656414, -0.292722, 0.545051, 0.571736, 0.683916, -0.292185, 0.528813, 0.610158, 0.711809, -0.290043, 0.51106, 0.649061, 0.739547, -0.285246, 0.490103, 0.690081, 0.766914, -0.277647, 0.465523, 0.732554, 0.791375, -0.267603, 0.437718, 0.773982, 0.814772, -0.256109, 0.40882, 0.81609, 0.836691, -0.242281, 0.377823, 0.856849, 0.856984, -0.227155, 0.34496, 0.898363, 0.876332, -0.210395, 0.311335, 0.939471, 0.894988, -0.192612, 0.277703, 0.980799, 0.911113, -0.173236, 0.243019, 1.02215, 0.924092, -0.152258, 0.209037, 1.06139, 0.936828, -0.129575, 0.175909, 1.09635, 0.946869, -0.10594, 0.143852, 1.12707, 0.958284, -0.081318, 0.110289, 1.15419, 0.972325, -0.0556133, 0.0747232, 1.17909, 0.986878, -0.0297899, 0.0383149, 1.20163, 0.999936, -0.00197169, 0.000912402, 1.22338, 0.151174, -0.00000720365, 0.351531, 0.00000309789, 0.155594, -0.00018279, 0.361806, 0.000078608, 0.156099, -0.000731569, 0.362982, 0.000314615, 0.156053, -0.00164578, 0.362869, 0.000707845, 0.156093, -0.0029261, 0.362961, 0.00125884, 0.156099, -0.00457155, 0.362959, 0.00196783, 0.15612, -0.00658224, 0.362982, 0.00283622, 0.156168, -0.00895774, 0.363048, 0.00386625, 0.156221, -0.0116962, 0.363101, 0.00506109, 0.156324, -0.0147973, 0.363241, 0.00642675, 0.156476, -0.0182503, 0.363448, 0.00797175, 0.156731, -0.0220266, 0.36384, 0.00971484, 0.156994, -0.026176, 0.364179, 0.0116575, 0.157341, -0.0306701, 0.36462, 0.0138207, 0.157867, -0.0354591, 0.365364, 0.0162356, 0.15846, -0.0406141, 0.366111, 0.0189092, 0.159308, -0.0460519, 0.367248, 0.021885, 0.160426, -0.0518096, 0.368767, 0.0252004, 0.161877, -0.0578906, 0.370745, 0.0288825, 0.163995, -0.0642812, 0.373831, 0.0330139, 0.16655, -0.0710067, 0.377366, 0.0376283, 0.170237, -0.0781522, 0.382799, 0.0428493, 0.175096, -0.0857172, 0.389915, 0.0487324, 0.181069, -0.0938025, 0.398487, 0.0554214, 0.188487, -0.102363, 0.408799, 0.0630189, 0.197029, -0.111343, 0.419991, 0.071634, 0.206684, -0.120812, 0.431455, 0.0812797, 0.218698, -0.131033, 0.445746, 0.0923651, 0.230726, -0.141373, 0.457471, 0.104545, 0.245516, -0.152387, 0.472388, 0.118449, 0.261551, -0.163628, 0.486671, 0.133923, 0.277437, -0.174814, 0.49762, 0.150849, 0.296662, -0.186713, 0.51162, 0.169924, 0.31795, -0.198513, 0.525435, 0.190848, 0.339422, -0.210119, 0.536267, 0.213504, 0.362143, -0.221354, 0.545982, 0.237947, 0.387198, -0.23224, 0.555364, 0.264427, 0.412349, -0.24257, 0.561489, 0.292519, 0.439274, -0.252284, 0.566903, 0.322561, 0.466779, -0.261023, 0.569614, 0.353952, 0.496011, -0.26899, 0.571589, 0.387278, 0.524964, -0.275498, 0.570325, 0.421356, 0.556518, -0.281449, 0.568792, 0.457314, 0.584363, -0.285526, 0.560268, 0.493199, 0.614214, -0.28844, 0.55205, 0.530276, 0.645684, -0.289777, 0.541906, 0.56855, 0.673446, -0.289722, 0.526464, 0.606927, 0.701924, -0.287792, 0.509872, 0.645945, 0.73037, -0.284315, 0.490649, 0.685564, 0.757405, -0.278804, 0.467964, 0.726511, 0.784025, -0.269543, 0.441468, 0.768601, 0.808255, -0.258117, 0.41216, 0.811321, 0.830739, -0.244728, 0.380606, 0.853496, 0.851914, -0.229428, 0.348111, 0.895374, 0.872586, -0.212508, 0.314732, 0.937674, 0.891581, -0.194025, 0.280338, 0.979869, 0.907641, -0.174711, 0.245203, 1.02253, 0.922233, -0.153509, 0.21077, 1.06371, 0.935878, -0.130418, 0.177399, 1.09972, 0.946338, -0.105558, 0.144507, 1.13124, 0.957265, -0.080059, 0.110508, 1.15973, 0.971668, -0.0539766, 0.0742311, 1.18515, 0.9866, -0.0277101, 0.0375224, 1.20858, 1.00021, -0.000515531, 0.000135226, 1.23135, 0.137468, -0.00000686011, 0.345041, 0.00000273315, 0.13703, -0.000173378, 0.343936, 0.0000690761, 0.136986, -0.000693048, 0.34383, 0.000276126, 0.136964, -0.00155931, 0.343761, 0.000621337, 0.137003, -0.00277211, 0.343863, 0.00110494, 0.137012, -0.00433103, 0.343868, 0.00172744, 0.137043, -0.00623606, 0.343916, 0.00249022, 0.13709, -0.0084868, 0.343986, 0.00339559, 0.137145, -0.0110814, 0.344045, 0.00444687, 0.137242, -0.0140187, 0.344177, 0.00565007, 0.137431, -0.0172713, 0.344491, 0.00701868, 0.137644, -0.0208605, 0.344805, 0.00856042, 0.13791, -0.024792, 0.345172, 0.0102863, 0.138295, -0.0290461, 0.345734, 0.0122185, 0.138764, -0.0335957, 0.346371, 0.0143771, 0.139415, -0.038467, 0.347298, 0.0167894, 0.140272, -0.0436176, 0.348527, 0.0194895, 0.141457, -0.0491016, 0.350276, 0.0225043, 0.14303, -0.0548764, 0.352646, 0.0258962, 0.145289, -0.0610096, 0.356206, 0.0297168, 0.148502, -0.0674777, 0.361488, 0.0340562, 0.152188, -0.074345, 0.367103, 0.0389534, 0.157359, -0.0817442, 0.375247, 0.0445541, 0.16379, -0.0896334, 0.385064, 0.0509535, 0.171376, -0.098005, 0.396082, 0.0582611, 0.179901, -0.106817, 0.407418, 0.06654, 0.189892, -0.116239, 0.420031, 0.075994, 0.201838, -0.12627, 0.434321, 0.0867239, 0.214311, -0.136701, 0.447631, 0.0987517, 0.228902, -0.147616, 0.462046, 0.112353, 0.245107, -0.158871, 0.476942, 0.127605, 0.262292, -0.170261, 0.490285, 0.144469, 0.281215, -0.182017, 0.503783, 0.163282, 0.301058, -0.193729, 0.515505, 0.183873, 0.322752, -0.205512, 0.52682, 0.206466, 0.347547, -0.217214, 0.539473, 0.231194, 0.370969, -0.227966, 0.546625, 0.257288, 0.397533, -0.238555, 0.55472, 0.285789, 0.42398, -0.248278, 0.559468, 0.315746, 0.452928, -0.257422, 0.564095, 0.347724, 0.482121, -0.265306, 0.565426, 0.380922, 0.510438, -0.272043, 0.563205, 0.415639, 0.541188, -0.277614, 0.561087, 0.451702, 0.571667, -0.281927, 0.554922, 0.48845, 0.602432, -0.285015, 0.546838, 0.526442, 0.634126, -0.286512, 0.537415, 0.564896, 0.662816, -0.286388, 0.522906, 0.604037, 0.692411, -0.284734, 0.507003, 0.643795, 0.720946, -0.281297, 0.488398, 0.68298, 0.748293, -0.276262, 0.466353, 0.723466, 0.776931, -0.269978, 0.443573, 0.764565, 0.801065, -0.260305, 0.415279, 0.805838, 0.825843, -0.247426, 0.384773, 0.849985, 0.84807, -0.232437, 0.352555, 0.893174, 0.869122, -0.215806, 0.318642, 0.936564, 0.888963, -0.197307, 0.28381, 0.980253, 0.905547, -0.177203, 0.247888, 1.02463, 0.918554, -0.155542, 0.212904, 1.06714, 0.931395, -0.131948, 0.1787, 1.10451, 0.941749, -0.106723, 0.145902, 1.13694, 0.954551, -0.0804939, 0.111193, 1.1666, 0.970279, -0.0534239, 0.0744697, 1.19249, 0.986117, -0.0257452, 0.0368788, 1.21665, 0.999938, 0.00190634, -0.0010291, 1.23981, 0.118493, -0.00000647439, 0.32272, 0.0000023772, 0.118765, -0.000163023, 0.323456, 0.0000598573, 0.118772, -0.00065212, 0.323477, 0.000239447, 0.118843, -0.00146741, 0.323657, 0.000538881, 0.118804, -0.00260846, 0.323553, 0.00095826, 0.118826, -0.00407576, 0.323595, 0.00149845, 0.118846, -0.00586826, 0.323617, 0.00216047, 0.118886, -0.00798578, 0.32367, 0.00294679, 0.118947, -0.0104273, 0.323753, 0.00386124, 0.119055, -0.0131909, 0.323922, 0.00490999, 0.119241, -0.0162444, 0.324251, 0.00610804, 0.11944, -0.0196339, 0.324544, 0.00745805, 0.119739, -0.0233378, 0.325026, 0.00897805, 0.12011, -0.0273179, 0.325586, 0.0106895, 0.120571, -0.0316143, 0.326231, 0.0126073, 0.12124, -0.0361939, 0.327264, 0.0147654, 0.122162, -0.0410511, 0.328733, 0.0172001, 0.123378, -0.0462233, 0.330659, 0.0199375, 0.125183, -0.0517109, 0.333754, 0.0230498, 0.127832, -0.0575652, 0.338507, 0.026597, 0.130909, -0.0637441, 0.343666, 0.0306345, 0.135221, -0.0704302, 0.351063, 0.035273, 0.14082, -0.0776364, 0.360604, 0.0406137, 0.146781, -0.0852293, 0.369638, 0.0466788, 0.155121, -0.0935351, 0.3827, 0.0537628, 0.16398, -0.102234, 0.39522, 0.0617985, 0.173926, -0.111465, 0.40793, 0.07097, 0.185137, -0.121296, 0.42105, 0.0813426, 0.19826, -0.13169, 0.435735, 0.0931596, 0.212938, -0.142614, 0.450932, 0.106547, 0.229046, -0.153884, 0.465726, 0.121575, 0.246246, -0.165382, 0.479461, 0.138286, 0.264637, -0.176806, 0.492106, 0.15666, 0.284959, -0.188793, 0.504774, 0.17728, 0.308157, -0.200763, 0.518805, 0.19988, 0.330951, -0.21239, 0.528231, 0.224293, 0.3549, -0.223521, 0.536376, 0.250541, 0.381502, -0.234169, 0.544846, 0.278902, 0.409529, -0.244077, 0.551717, 0.309227, 0.437523, -0.253363, 0.55517, 0.341426, 0.467624, -0.261659, 0.557772, 0.37518, 0.497268, -0.268498, 0.556442, 0.41007, 0.528294, -0.274018, 0.553915, 0.446445, 0.559053, -0.278169, 0.549153, 0.483779, 0.589329, -0.281229, 0.539878, 0.522249, 0.622503, -0.282902, 0.53162, 0.561754, 0.652382, -0.282815, 0.518119, 0.601544, 0.681847, -0.281247, 0.502187, 0.641574, 0.712285, -0.277986, 0.484824, 0.682633, 0.740094, -0.273017, 0.463483, 0.723426, 0.768478, -0.266692, 0.441299, 0.763747, 0.794556, -0.258358, 0.415238, 0.805565, 0.819408, -0.248807, 0.386912, 0.847254, 0.843411, -0.236214, 0.356165, 0.891091, 0.862397, -0.219794, 0.320562, 0.936174, 0.883113, -0.201768, 0.285322, 0.982562, 0.90023, -0.181672, 0.249713, 1.02862, 0.915192, -0.159279, 0.214546, 1.07163, 0.928458, -0.134725, 0.180285, 1.10995, 0.94069, -0.10913, 0.147119, 1.14354, 0.953409, -0.0821315, 0.112492, 1.17372, 0.969537, -0.0542677, 0.0752014, 1.20043, 0.985612, -0.0259096, 0.0370361, 1.22528, 0.999835, 0.00298198, -0.00151801, 1.24959, 0.10097, -0.00000602574, 0.300277, 0.00000202619, 0.101577, -0.000152164, 0.302077, 0.0000511662, 0.101572, -0.000608889, 0.302066, 0.000204751, 0.101566, -0.00136997, 0.302047, 0.000460753, 0.101592, -0.00243557, 0.302114, 0.000819497, 0.101608, -0.0038053, 0.30214, 0.00128154, 0.101627, -0.00547906, 0.30216, 0.0018483, 0.101669, -0.00745647, 0.302224, 0.00252223, 0.101732, -0.00973615, 0.302318, 0.00330716, 0.101844, -0.0123097, 0.302513, 0.00421061, 0.102025, -0.0151681, 0.30285, 0.00524481, 0.102224, -0.0183334, 0.303166, 0.0064154, 0.102515, -0.0217819, 0.303654, 0.00774063, 0.102886, -0.0255067, 0.304243, 0.0092398, 0.103395, -0.029514, 0.305089, 0.0109339, 0.104109, -0.0337912, 0.306301, 0.0128561, 0.105074, -0.0383565, 0.30798, 0.0150338, 0.10654, -0.0432132, 0.310726, 0.0175228, 0.108478, -0.0484244, 0.314351, 0.0203648, 0.111015, -0.0539339, 0.319032, 0.0236325, 0.114682, -0.0598885, 0.32605, 0.0274188, 0.11911, -0.0663375, 0.334109, 0.0317905, 0.124736, -0.0733011, 0.344013, 0.0368502, 0.131479, -0.0807744, 0.355358, 0.0427104, 0.139283, -0.0888204, 0.367614, 0.0494788, 0.148054, -0.0973394, 0.380072, 0.0572367, 0.159037, -0.10665, 0.395678, 0.0662704, 0.169794, -0.116221, 0.40795, 0.0763192, 0.18314, -0.126632, 0.423546, 0.087956, 0.197515, -0.137383, 0.438213, 0.101042, 0.213514, -0.148641, 0.453248, 0.115827, 0.23065, -0.160117, 0.46688, 0.132283, 0.249148, -0.171807, 0.479962, 0.150644, 0.270219, -0.183695, 0.494618, 0.171073, 0.292338, -0.195574, 0.506937, 0.193378, 0.314999, -0.207205, 0.516463, 0.217585, 0.340991, -0.218955, 0.528123, 0.24428, 0.367982, -0.229917, 0.537025, 0.272784, 0.39432, -0.239737, 0.541627, 0.302742, 0.423364, -0.249048, 0.546466, 0.335112, 0.453751, -0.257329, 0.549466, 0.369032, 0.48416, -0.264623, 0.549503, 0.404577, 0.515262, -0.270411, 0.547008, 0.441337, 0.547036, -0.274581, 0.542249, 0.479162, 0.576614, -0.277266, 0.533015, 0.517904, 0.611143, -0.279144, 0.525512, 0.558508, 0.640989, -0.279001, 0.51154, 0.598995, 0.671182, -0.277324, 0.495641, 0.639935, 0.700848, -0.273908, 0.477526, 0.681017, 0.729862, -0.269063, 0.457955, 0.722764, 0.758273, -0.262282, 0.434846, 0.764349, 0.784121, -0.254281, 0.409203, 0.806206, 0.809798, -0.24505, 0.382694, 0.848617, 0.834953, -0.233861, 0.354034, 0.892445, 0.856817, -0.221308, 0.321764, 0.936263, 0.877609, -0.205996, 0.288118, 0.982401, 0.897489, -0.186702, 0.253277, 1.02975, 0.913792, -0.164618, 0.217963, 1.07488, 0.92785, -0.140023, 0.183221, 1.11487, 0.940378, -0.11328, 0.149385, 1.14947, 0.95273, -0.0853958, 0.114152, 1.1807, 0.969059, -0.0568698, 0.0769845, 1.20912, 0.985574, -0.0276502, 0.0381186, 1.23498, 0.999943, 0.00239052, -0.00126861, 1.25987, 0.0852715, -0.00000560067, 0.279021, 0.00000171162, 0.0854143, -0.000140871, 0.279483, 0.0000430516, 0.0854191, -0.000563385, 0.2795, 0.000172184, 0.0854188, -0.00126753, 0.279493, 0.000387464, 0.0854229, -0.00225337, 0.279501, 0.00068918, 0.0854443, -0.00352086, 0.279549, 0.00107803, 0.0854697, -0.00506962, 0.279591, 0.00155536, 0.0855093, -0.00689873, 0.279652, 0.00212354, 0.0855724, -0.00900821, 0.279752, 0.00278703, 0.0856991, -0.0113799, 0.280011, 0.0035551, 0.085855, -0.0140314, 0.280297, 0.00443449, 0.0860682, -0.016963, 0.280682, 0.00543636, 0.086344, -0.0201438, 0.281159, 0.0065788, 0.0867426, -0.0235999, 0.281886, 0.00787977, 0.087239, -0.0273069, 0.282745, 0.0093606, 0.0879815, -0.031269, 0.284139, 0.011056, 0.0891258, -0.035531, 0.28647, 0.0130065, 0.0906909, -0.0400947, 0.289708, 0.0152495, 0.0927624, -0.0449638, 0.293904, 0.0178454, 0.0958376, -0.0502427, 0.300471, 0.0208915, 0.0995827, -0.0559514, 0.30806, 0.0244247, 0.104526, -0.0622152, 0.317874, 0.0285721, 0.110532, -0.0690046, 0.329332, 0.0334227, 0.117385, -0.0763068, 0.341217, 0.0390466, 0.12522, -0.084184, 0.353968, 0.0455786, 0.134037, -0.0925248, 0.366797, 0.0530773, 0.144014, -0.101487, 0.380209, 0.0617424, 0.156013, -0.111273, 0.395956, 0.071777, 0.168872, -0.121431, 0.41053, 0.0830905, 0.183089, -0.132105, 0.425073, 0.0959341, 0.198763, -0.143286, 0.439833, 0.110448, 0.216159, -0.154841, 0.454507, 0.126769, 0.234859, -0.166588, 0.468368, 0.14495, 0.255879, -0.178626, 0.482846, 0.165233, 0.27677, -0.190218, 0.493489, 0.187217, 0.301184, -0.202227, 0.506549, 0.211659, 0.325852, -0.213764, 0.5158, 0.237922, 0.352824, -0.22487, 0.525442, 0.26632, 0.380882, -0.235246, 0.532487, 0.296691, 0.410137, -0.244847, 0.537703, 0.329179, 0.439787, -0.253122, 0.540361, 0.363135, 0.472291, -0.260517, 0.542734, 0.399222, 0.501856, -0.266519, 0.538826, 0.436352, 0.534816, -0.270905, 0.535152, 0.474505, 0.565069, -0.273826, 0.525979, 0.513988, 0.597154, -0.275333, 0.516394, 0.554852, 0.630473, -0.275314, 0.506206, 0.596592, 0.660574, -0.273323, 0.489769, 0.638117, 0.692015, -0.270008, 0.472578, 0.680457, 0.720647, -0.265001, 0.452134, 0.723008, 0.750528, -0.258311, 0.430344, 0.765954, 0.777568, -0.250046, 0.405624, 0.809012, 0.80387, -0.240114, 0.378339, 0.852425, 0.828439, -0.228737, 0.349877, 0.895346, 0.851472, -0.216632, 0.318968, 0.940695, 0.873906, -0.202782, 0.287489, 0.987235, 0.89467, -0.187059, 0.254394, 1.03348, 0.912281, -0.168818, 0.221294, 1.07812, 0.927358, -0.146494, 0.18675, 1.11928, 0.940385, -0.120009, 0.152322, 1.15609, 0.952672, -0.0917183, 0.117514, 1.18875, 0.968496, -0.0620321, 0.0797405, 1.21821, 0.985236, -0.0314945, 0.0402383, 1.24523, 0.99998, -0.000575153, 0.000110644, 1.27133, 0.0702429, -0.00000512222, 0.255273, 0.00000140947, 0.0702981, -0.000128826, 0.255469, 0.0000354488, 0.0703691, -0.000515562, 0.255727, 0.000141874, 0.0703805, -0.00116, 0.255754, 0.00031929, 0.0703961, -0.00206224, 0.255813, 0.000567999, 0.0704102, -0.00322223, 0.255839, 0.00088871, 0.0704298, -0.00463928, 0.255863, 0.00128272, 0.0704759, -0.00631375, 0.255953, 0.00175283, 0.0705434, -0.00824317, 0.256079, 0.00230342, 0.0706693, -0.010412, 0.25636, 0.0029443, 0.0708189, -0.0128439, 0.256647, 0.00368031, 0.0710364, -0.0155177, 0.257084, 0.00452614, 0.0713223, -0.0184374, 0.257637, 0.00549706, 0.0717182, -0.0216002, 0.258416, 0.00661246, 0.072321, -0.0249966, 0.259699, 0.00790147, 0.0731446, -0.0286566, 0.261475, 0.0093884, 0.0743352, -0.0325888, 0.264132, 0.0111186, 0.0760676, -0.036843, 0.26815, 0.013145, 0.078454, -0.0414292, 0.273636, 0.0155251, 0.0818618, -0.0464634, 0.281653, 0.0183525, 0.0857382, -0.0519478, 0.289992, 0.0216642, 0.0908131, -0.0579836, 0.30066, 0.0255956, 0.0967512, -0.0645124, 0.312204, 0.0301954, 0.103717, -0.0716505, 0.325001, 0.0356017, 0.111596, -0.0793232, 0.338129, 0.041896, 0.120933, -0.087645, 0.352853, 0.0492447, 0.130787, -0.096492, 0.366192, 0.0576749, 0.142311, -0.105973, 0.380864, 0.0673969, 0.155344, -0.116182, 0.396575, 0.0785899, 0.169535, -0.126815, 0.411443, 0.0912377, 0.185173, -0.138015, 0.426256, 0.105607, 0.201755, -0.149325, 0.439607, 0.121551, 0.221334, -0.161207, 0.455467, 0.139608, 0.241461, -0.173162, 0.469096, 0.159591, 0.26294, -0.18504, 0.481014, 0.18156, 0.286776, -0.196881, 0.493291, 0.205781, 0.311596, -0.208311, 0.503556, 0.231819, 0.338667, -0.219671, 0.513268, 0.260274, 0.366021, -0.230451, 0.519414, 0.290862, 0.395875, -0.240131, 0.526766, 0.323196, 0.425564, -0.248566, 0.52905, 0.357071, 0.457094, -0.256195, 0.530796, 0.393262, 0.488286, -0.262331, 0.528703, 0.430797, 0.522291, -0.267141, 0.52727, 0.470231, 0.554172, -0.270411, 0.519848, 0.510477, 0.586427, -0.271986, 0.510307, 0.551594, 0.619638, -0.27192, 0.499158, 0.593849, 0.650656, -0.269817, 0.483852, 0.636314, 0.68284, -0.266267, 0.467515, 0.679679, 0.714356, -0.26113, 0.44931, 0.723884, 0.742717, -0.254067, 0.425789, 0.767245, 0.770894, -0.245652, 0.401144, 0.811819, 0.797358, -0.235554, 0.374224, 0.856315, 0.823377, -0.223896, 0.346167, 0.901077, 0.847456, -0.210865, 0.316056, 0.946502, 0.870697, -0.196574, 0.284503, 0.993711, 0.891068, -0.180814, 0.251628, 1.04134, 0.909267, -0.163314, 0.219065, 1.08609, 0.925653, -0.143304, 0.186446, 1.12702, 0.940017, -0.121322, 0.153416, 1.16371, 0.952398, -0.0973872, 0.120334, 1.19712, 0.967568, -0.0698785, 0.08352, 1.22791, 0.984772, -0.0390031, 0.0439209, 1.25672, 1.00026, -0.0070087, 0.00315668, 1.28428, 0.0556653, -0.00000459654, 0.227325, 0.00000112556, 0.0565238, -0.000116382, 0.230826, 0.0000284985, 0.0565717, -0.000465666, 0.231026, 0.000114036, 0.0565859, -0.00104773, 0.231079, 0.000256656, 0.0565761, -0.00186255, 0.231025, 0.00045663, 0.0565913, -0.00291002, 0.231058, 0.000714664, 0.0566108, -0.00418998, 0.231085, 0.00103224, 0.0566532, -0.00570206, 0.231169, 0.00141202, 0.0567473, -0.00743666, 0.231417, 0.00186018, 0.0568567, -0.00940298, 0.231661, 0.00238264, 0.0569859, -0.0115991, 0.231895, 0.00298699, 0.0572221, -0.0140096, 0.232456, 0.00368957, 0.057519, -0.0166508, 0.233096, 0.00450303, 0.0579534, -0.01951, 0.234094, 0.00544945, 0.0585922, -0.0225991, 0.235629, 0.00655564, 0.0595647, -0.0259416, 0.238106, 0.00785724, 0.0609109, -0.0295661, 0.241557, 0.00939127, 0.0628751, -0.0335126, 0.246652, 0.0112198, 0.0656908, -0.0378604, 0.254091, 0.0134168, 0.0691347, -0.0426543, 0.262666, 0.0160374, 0.0732165, -0.0478967, 0.272029, 0.0191514, 0.0782863, -0.0536716, 0.283007, 0.0228597, 0.0843973, -0.0600683, 0.295732, 0.0272829, 0.0913598, -0.0670095, 0.308779, 0.032484, 0.0994407, -0.0745516, 0.322886, 0.0385886, 0.108189, -0.082712, 0.336408, 0.0457133, 0.118574, -0.0914927, 0.351692, 0.0539832, 0.129989, -0.100854, 0.366502, 0.0635162, 0.142722, -0.110837, 0.381675, 0.0744386, 0.156654, -0.121353, 0.3963, 0.0868483, 0.172151, -0.132414, 0.411477, 0.100963, 0.188712, -0.143809, 0.42508, 0.116795, 0.208093, -0.155765, 0.441328, 0.134715, 0.227936, -0.167608, 0.454328, 0.154396, 0.249495, -0.179579, 0.467235, 0.176179, 0.27362, -0.191488, 0.480248, 0.200193, 0.296371, -0.202618, 0.487886, 0.225775, 0.324234, -0.214133, 0.499632, 0.25441, 0.353049, -0.225212, 0.509532, 0.285077, 0.381785, -0.234875, 0.514265, 0.317047, 0.414038, -0.244205, 0.521282, 0.351874, 0.445251, -0.252145, 0.522931, 0.388279, 0.476819, -0.258433, 0.520947, 0.425825, 0.509209, -0.263411, 0.517669, 0.465104, 0.542759, -0.266732, 0.512841, 0.505741, 0.574822, -0.268263, 0.503317, 0.547611, 0.609324, -0.268489, 0.493035, 0.590953, 0.641772, -0.266941, 0.478816, 0.63488, 0.674049, -0.263297, 0.462863, 0.679072, 0.705071, -0.257618, 0.442931, 0.723487, 0.734709, -0.250625, 0.421299, 0.768708, 0.763704, -0.24179, 0.397085, 0.814375, 0.791818, -0.231115, 0.370577, 0.859907, 0.817439, -0.21922, 0.34232, 0.906715, 0.843202, -0.205658, 0.312627, 0.953943, 0.866639, -0.190563, 0.280933, 1.00185, 0.888129, -0.173978, 0.248393, 1.05105, 0.907239, -0.155485, 0.216007, 1.09704, 0.923893, -0.134782, 0.183233, 1.13857, 0.938882, -0.11249, 0.150376, 1.17539, 0.952464, -0.0890706, 0.117177, 1.20924, 0.968529, -0.0646523, 0.0813095, 1.24055, 0.984763, -0.038606, 0.0439378, 1.27018, 1.00053, -0.01238, 0.00598668, 1.29873, 0.0437928, -0.00000409594, 0.204012, 0.000000879224, 0.0440166, -0.000103395, 0.205049, 0.0000221946, 0.0440529, -0.000413633, 0.205225, 0.0000887981, 0.0440493, -0.000930594, 0.2052, 0.000199858, 0.0439884, -0.00165352, 0.204901, 0.000355495, 0.0440716, -0.0025849, 0.205255, 0.000556983, 0.0440968, -0.00372222, 0.205311, 0.000805326, 0.0441359, -0.00506478, 0.205391, 0.00110333, 0.0442231, -0.00660384, 0.205638, 0.00145768, 0.0443254, -0.00835246, 0.205877, 0.00187275, 0.0444832, -0.0102992, 0.20627, 0.00235938, 0.0447001, -0.0124449, 0.206796, 0.0029299, 0.0450168, -0.0147935, 0.207593, 0.0036005, 0.0454816, -0.017336, 0.208819, 0.00439246, 0.0462446, -0.0201156, 0.211036, 0.00533864, 0.0473694, -0.0231568, 0.214388, 0.00646984, 0.0490191, -0.0264941, 0.219357, 0.00783856, 0.0512776, -0.030184, 0.226061, 0.00950182, 0.0541279, -0.0342661, 0.234094, 0.0115156, 0.0578989, -0.0388539, 0.244297, 0.0139687, 0.0620835, -0.0438735, 0.254457, 0.0169015, 0.0673497, -0.04951, 0.266706, 0.0204554, 0.0731759, -0.0556263, 0.278753, 0.0246606, 0.0803937, -0.0624585, 0.29309, 0.0297126, 0.0879287, -0.0697556, 0.305856, 0.0355868, 0.0970669, -0.0778795, 0.321059, 0.0425768, 0.106508, -0.0863541, 0.333873, 0.05056, 0.11776, -0.0955935, 0.349008, 0.0598972, 0.130081, -0.105438, 0.363776, 0.0706314, 0.144454, -0.115899, 0.380112, 0.0828822, 0.1596, -0.126827, 0.394843, 0.0967611, 0.176097, -0.138161, 0.409033, 0.112381, 0.194726, -0.149904, 0.424257, 0.129952, 0.213944, -0.161675, 0.436945, 0.149333, 0.235516, -0.173659, 0.450176, 0.170892, 0.260564, -0.185963, 0.466305, 0.194984, 0.285183, -0.197582, 0.477328, 0.220805, 0.311095, -0.208697, 0.486566, 0.248694, 0.338924, -0.219519, 0.494811, 0.279015, 0.369757, -0.229766, 0.504065, 0.311725, 0.3996, -0.238879, 0.507909, 0.345844, 0.430484, -0.246802, 0.509805, 0.381749, 0.46413, -0.253924, 0.511436, 0.420251, 0.497077, -0.259319, 0.508787, 0.459957, 0.530434, -0.263297, 0.50394, 0.501356, 0.565725, -0.265619, 0.49804, 0.544252, 0.599254, -0.265842, 0.487346, 0.587856, 0.631251, -0.263978, 0.472975, 0.631969, 0.663972, -0.26043, 0.457135, 0.677471, 0.697724, -0.255358, 0.439844, 0.723744, 0.727725, -0.248308, 0.417872, 0.770653, 0.756417, -0.239181, 0.39273, 0.817357, 0.785419, -0.22814, 0.367839, 0.864221, 0.81266, -0.215681, 0.339449, 0.912701, 0.839391, -0.201623, 0.309279, 0.962419, 0.86366, -0.185624, 0.278029, 1.0122, 0.885028, -0.16797, 0.245294, 1.06186, 0.904639, -0.148336, 0.212689, 1.10934, 0.922048, -0.12637, 0.179616, 1.15063, 0.936952, -0.102928, 0.146749, 1.18885, 0.951895, -0.0785268, 0.112733, 1.22352, 0.967198, -0.0530153, 0.0760056, 1.25681, 0.984405, -0.02649, 0.0383183, 1.28762, 1.00021, 0.00070019, -0.00020039, 1.31656, 0.0325964, -0.00000355447, 0.176706, 0.000000655682, 0.0329333, -0.0000899174, 0.178527, 0.0000165869, 0.0329181, -0.000359637, 0.178453, 0.0000663498, 0.0329085, -0.000808991, 0.178383, 0.000149332, 0.0329181, -0.00143826, 0.178394, 0.000265873, 0.0329425, -0.00224678, 0.178517, 0.000416597, 0.0329511, -0.00323575, 0.17849, 0.000603299, 0.033011, -0.00439875, 0.178695, 0.000829422, 0.0330733, -0.00574059, 0.178843, 0.00109908, 0.0331857, -0.00725896, 0.179176, 0.00141933, 0.0333445, -0.00895289, 0.179618, 0.0017999, 0.0335674, -0.0108219, 0.180238, 0.00225316, 0.033939, -0.0128687, 0.181417, 0.00279765, 0.0345239, -0.015114, 0.183395, 0.0034564, 0.0354458, -0.017596, 0.186616, 0.00425864, 0.0368313, -0.0203524, 0.191547, 0.00524936, 0.0386115, -0.0234105, 0.197508, 0.00647033, 0.0410303, -0.0268509, 0.205395, 0.00798121, 0.0442245, -0.0307481, 0.215365, 0.0098557, 0.0478659, -0.0350863, 0.225595, 0.0121417, 0.0522416, -0.0399506, 0.236946, 0.0149385, 0.0574513, -0.045357, 0.249442, 0.0183189, 0.0631208, -0.0512863, 0.261222, 0.0223644, 0.0701124, -0.0579273, 0.275418, 0.0272418, 0.0777331, -0.0650652, 0.288989, 0.0329458, 0.0862709, -0.0728813, 0.302546, 0.0396819, 0.096103, -0.081363, 0.317164, 0.04757, 0.106976, -0.0904463, 0.331733, 0.0567012, 0.119175, -0.100105, 0.34661, 0.067202, 0.132919, -0.110375, 0.362249, 0.0792588, 0.147727, -0.121115, 0.376978, 0.0928672, 0.163618, -0.132299, 0.390681, 0.108228, 0.182234, -0.143887, 0.406571, 0.125502, 0.201809, -0.155827, 0.42042, 0.144836, 0.225041, -0.168357, 0.438411, 0.166706, 0.247621, -0.18004, 0.450368, 0.189909, 0.27097, -0.191536, 0.460083, 0.215251, 0.296658, -0.203024, 0.469765, 0.243164, 0.325892, -0.214056, 0.481837, 0.273388, 0.35406, -0.224104, 0.487474, 0.305344, 0.384372, -0.233489, 0.492773, 0.339741, 0.41749, -0.241874, 0.498451, 0.376287, 0.45013, -0.248834, 0.499632, 0.414195, 0.481285, -0.254658, 0.495233, 0.454077, 0.519183, -0.259367, 0.496401, 0.496352, 0.551544, -0.261818, 0.487686, 0.538798, 0.587349, -0.262964, 0.479453, 0.583626, 0.621679, -0.262128, 0.467709, 0.629451, 0.654991, -0.258998, 0.452123, 0.67566, 0.686873, -0.254119, 0.433495, 0.723248, 0.719801, -0.246946, 0.413657, 0.771156, 0.750355, -0.237709, 0.390366, 0.81989, 0.780033, -0.226549, 0.364947, 0.868601, 0.809254, -0.214186, 0.337256, 0.920034, 0.836576, -0.199639, 0.307395, 0.971706, 0.861774, -0.183169, 0.275431, 1.02479, 0.885707, -0.165111, 0.243431, 1.07837, 0.904742, -0.144363, 0.210921, 1.12783, 0.915604, -0.121305, 0.17647, 1.17254, 0.930959, -0.0962119, 0.143106, 1.21012, 0.948404, -0.069969, 0.108112, 1.24474, 0.967012, -0.0427586, 0.0708478, 1.27718, 0.984183, -0.0147043, 0.032335, 1.3083, 0.999577, 0.0142165, -0.00726867, 1.3382, 0.0229227, -0.00000299799, 0.148623, 0.000000462391, 0.0232194, -0.0000758796, 0.15054, 0.0000117033, 0.0232315, -0.000303636, 0.15063, 0.0000468397, 0.0232354, -0.000683189, 0.150624, 0.000105472, 0.0232092, -0.0012136, 0.150445, 0.000187744, 0.0232523, -0.00189765, 0.150679, 0.000294847, 0.0232828, -0.00273247, 0.150789, 0.000428013, 0.0233371, -0.00371287, 0.150995, 0.000591134, 0.0234015, -0.00484794, 0.15118, 0.000787642, 0.023514, -0.00612877, 0.151562, 0.00102547, 0.023679, -0.00756125, 0.152116, 0.00131351, 0.0239559, -0.00914651, 0.153162, 0.00166594, 0.0244334, -0.010904, 0.155133, 0.00210182, 0.025139, -0.0128615, 0.158035, 0.00264406, 0.0262598, -0.0150628, 0.162751, 0.00332923, 0.0277875, -0.0175532, 0.168944, 0.00419773, 0.0298472, -0.0203981, 0.176835, 0.00530034, 0.0325444, -0.023655, 0.186686, 0.00669777, 0.0355581, -0.0272982, 0.196248, 0.00842661, 0.0392841, -0.0314457, 0.207352, 0.0105854, 0.0436815, -0.0361157, 0.219279, 0.0132458, 0.0485272, -0.0412932, 0.230728, 0.0164736, 0.0541574, -0.0470337, 0.242994, 0.0203715, 0.0609479, -0.0535002, 0.257042, 0.0250953, 0.0685228, -0.0605409, 0.27102, 0.0306856, 0.0768042, -0.0680553, 0.28406, 0.037193, 0.0864844, -0.0765011, 0.299186, 0.0449795, 0.0969415, -0.0852674, 0.3132, 0.0538316, 0.108478, -0.0947333, 0.327138, 0.0641149, 0.121705, -0.10481, 0.342345, 0.0759185, 0.136743, -0.115474, 0.358472, 0.0894116, 0.152986, -0.126536, 0.374067, 0.104562, 0.170397, -0.138061, 0.388267, 0.121632, 0.191392, -0.150203, 0.406467, 0.140996, 0.211566, -0.161751, 0.418641, 0.161696, 0.233567, -0.173407, 0.430418, 0.184557, 0.257769, -0.185397, 0.44277, 0.210092, 0.28531, -0.197048, 0.457191, 0.237827, 0.311726, -0.20784, 0.464712, 0.267253, 0.340537, -0.218345, 0.472539, 0.299332, 0.372921, -0.228306, 0.482331, 0.333988, 0.402924, -0.236665, 0.484378, 0.369722, 0.434475, -0.244097, 0.484717, 0.407836, 0.469736, -0.250547, 0.487093, 0.448465, 0.505045, -0.25511, 0.485575, 0.490263, 0.540262, -0.258444, 0.481225, 0.534495, 0.576347, -0.259903, 0.473481, 0.579451, 0.608656, -0.259572, 0.4603, 0.625604, 0.646679, -0.257908, 0.450341, 0.674511, 0.679902, -0.253663, 0.431561, 0.723269, 0.714159, -0.247419, 0.412684, 0.773263, 0.745345, -0.239122, 0.389388, 0.824182, 0.778248, -0.228837, 0.365361, 0.876634, 0.807208, -0.216197, 0.337667, 0.92945, 0.835019, -0.201772, 0.307197, 0.985261, 0.860261, -0.185291, 0.274205, 1.04299, 0.877601, -0.165809, 0.240178, 1.09816, 0.898211, -0.143897, 0.207571, 1.14694, 0.915789, -0.119513, 0.174904, 1.19008, 0.931831, -0.0932919, 0.141423, 1.2297, 0.949244, -0.0656528, 0.105603, 1.26553, 0.967527, -0.0370262, 0.0679551, 1.29986, 0.984139, -0.00730117, 0.0283133, 1.33252, 0.999713, 0.0234648, -0.0121785, 1.36397, 0.0152135, -0.00000245447, 0.122795, 0.000000304092, 0.0151652, -0.0000615778, 0.122399, 0.0000076292, 0.0151181, -0.000245948, 0.122023, 0.0000304802, 0.0151203, -0.000553394, 0.12203, 0.0000686634, 0.015125, -0.000983841, 0.122037, 0.000122463, 0.0151427, -0.00153774, 0.12214, 0.000192706, 0.0151708, -0.0022103, 0.122237, 0.000281219, 0.0152115, -0.00300741, 0.12238, 0.000390804, 0.0152877, -0.00392494, 0.1227, 0.000526317, 0.015412, -0.00496597, 0.123244, 0.00069443, 0.0156201, -0.00613314, 0.124228, 0.00090547, 0.0159658, -0.00744113, 0.125945, 0.0011732, 0.0165674, -0.00892546, 0.129098, 0.00151888, 0.017487, -0.010627, 0.133865, 0.00197007, 0.018839, -0.0126043, 0.140682, 0.0025637, 0.020554, -0.0148814, 0.148534, 0.00333637, 0.0226727, -0.0175123, 0.157381, 0.00433738, 0.0251879, -0.0205266, 0.166685, 0.00561664, 0.0283635, -0.0240319, 0.177796, 0.00725563, 0.0318694, -0.0279432, 0.188251, 0.00928811, 0.0361044, -0.0324313, 0.200038, 0.011835, 0.0406656, -0.0373527, 0.210685, 0.0149146, 0.0463846, -0.0430132, 0.224182, 0.0187254, 0.0525696, -0.0491013, 0.23634, 0.0232283, 0.0598083, -0.0559175, 0.250013, 0.0286521, 0.0679437, -0.0633657, 0.263981, 0.0350634, 0.0771181, -0.0714602, 0.278072, 0.0425882, 0.0881273, -0.0803502, 0.29511, 0.0514487, 0.0996628, -0.0896903, 0.309976, 0.0615766, 0.112702, -0.099644, 0.325611, 0.0732139, 0.126488, -0.109829, 0.339321, 0.0862324, 0.142625, -0.120859, 0.35574, 0.101275, 0.15953, -0.131956, 0.369845, 0.117892, 0.176991, -0.143145, 0.38146, 0.136205, 0.199715, -0.155292, 0.40052, 0.157252, 0.220787, -0.167066, 0.412055, 0.179966, 0.243697, -0.178396, 0.423133, 0.204418, 0.272106, -0.190433, 0.439524, 0.232141, 0.297637, -0.201265, 0.447041, 0.261109, 0.325273, -0.211834, 0.454488, 0.292627, 0.357219, -0.221889, 0.465004, 0.326669, 0.387362, -0.230729, 0.468527, 0.362426, 0.423131, -0.23924, 0.475836, 0.401533, 0.45543, -0.246067, 0.475017, 0.441902, 0.493393, -0.251557, 0.478017, 0.484239, 0.526253, -0.255571, 0.4709, 0.528586, 0.560554, -0.257752, 0.463167, 0.574346, 0.599306, -0.258076, 0.456452, 0.621655, 0.634541, -0.256471, 0.443725, 0.670492, 0.668907, -0.253283, 0.428719, 0.721943, 0.705619, -0.247562, 0.411348, 0.772477, 0.739034, -0.240626, 0.388939, 0.8264, 0.771408, -0.231493, 0.36425, 0.881702, 0.803312, -0.220125, 0.337321, 0.9385, 0.828457, -0.206645, 0.305364, 0.997437, 0.854819, -0.190664, 0.273715, 1.05693, 0.878666, -0.171429, 0.242218, 1.11251, 0.898404, -0.149235, 0.209556, 1.16398, 0.917416, -0.12435, 0.176863, 1.21014, 0.933133, -0.0972703, 0.142775, 1.25178, 0.95066, -0.0683607, 0.106735, 1.29028, 0.968589, -0.0378724, 0.0681609, 1.32703, 0.984776, -0.00605712, 0.0273966, 1.36158, 0.99994, 0.0263276, -0.0138124, 1.3943, 0.00867437, -0.00000186005, 0.0928979, 0.000000173682, 0.00864003, -0.0000466389, 0.0925237, 0.00000435505, 0.00864593, -0.000186594, 0.0925806, 0.0000174322, 0.00864095, -0.000419639, 0.0924903, 0.0000392862, 0.00863851, -0.000746272, 0.0924589, 0.0000702598, 0.00868531, -0.00116456, 0.0929, 0.000111188, 0.00869667, -0.00167711, 0.0928529, 0.000163867, 0.00874332, -0.00228051, 0.0930914, 0.00023104, 0.00882709, -0.00297864, 0.0935679, 0.00031741, 0.00898874, -0.00377557, 0.0946165, 0.000430186, 0.00929346, -0.00469247, 0.0967406, 0.000580383, 0.00978271, -0.00575491, 0.100084, 0.000783529, 0.0105746, -0.00701514, 0.105447, 0.00106304, 0.0116949, -0.00851797, 0.112494, 0.00144685, 0.0130419, -0.0102757, 0.119876, 0.00196439, 0.0148375, -0.012381, 0.129034, 0.00266433, 0.0168725, -0.01482, 0.137812, 0.00358364, 0.0193689, -0.0176563, 0.147696, 0.00478132, 0.0222691, -0.0209211, 0.157795, 0.00631721, 0.0256891, -0.0246655, 0.168431, 0.00826346, 0.0294686, -0.0288597, 0.178587, 0.0106714, 0.0340412, -0.0336441, 0.190251, 0.0136629, 0.0393918, -0.039033, 0.202999, 0.0173272, 0.0453947, -0.0450087, 0.215655, 0.0217448, 0.0521936, -0.0515461, 0.228686, 0.0269941, 0.0600279, -0.058817, 0.242838, 0.033272, 0.0692398, -0.0667228, 0.258145, 0.0406457, 0.0793832, -0.0752401, 0.273565, 0.0492239, 0.0902297, -0.0841851, 0.287735, 0.0590105, 0.102014, -0.0936479, 0.301161, 0.0702021, 0.116054, -0.103967, 0.317438, 0.0832001, 0.13191, -0.114622, 0.334166, 0.0977951, 0.148239, -0.125452, 0.348192, 0.113985, 0.165809, -0.136453, 0.361094, 0.131928, 0.184616, -0.147648, 0.373534, 0.151811, 0.207491, -0.159607, 0.39101, 0.174476, 0.230106, -0.171119, 0.402504, 0.198798, 0.257036, -0.182906, 0.418032, 0.225796, 0.281172, -0.193605, 0.425468, 0.254027, 0.312034, -0.204771, 0.440379, 0.285713, 0.340402, -0.214988, 0.445406, 0.319196, 0.370231, -0.224711, 0.44968, 0.35537, 0.407105, -0.233516, 0.460747, 0.393838, 0.439037, -0.240801, 0.460624, 0.433747, 0.47781, -0.24762, 0.465957, 0.477234, 0.510655, -0.251823, 0.460054, 0.52044, 0.550584, -0.255552, 0.459172, 0.567853, 0.585872, -0.257036, 0.450311, 0.615943, 0.620466, -0.257535, 0.437763, 0.667693, 0.660496, -0.255248, 0.426639, 0.718988, 0.695578, -0.251141, 0.409185, 0.772503, 0.732176, -0.244718, 0.39015, 0.827023, 0.760782, -0.236782, 0.362594, 0.885651, 0.79422, -0.225923, 0.33711, 0.943756, 0.824521, -0.213855, 0.308272, 1.00874, 0.854964, -0.197723, 0.278529, 1.06764, 0.878065, -0.179209, 0.246208, 1.12836, 0.899834, -0.157569, 0.21329, 1.18318, 0.918815, -0.133206, 0.181038, 1.23161, 0.934934, -0.106545, 0.146993, 1.27644, 0.952115, -0.0780574, 0.111175, 1.31842, 0.96906, -0.0478279, 0.0728553, 1.35839, 0.985178, -0.0160014, 0.032579, 1.39697, 1.00039, 0.0173126, -0.0095256, 1.43312, 0.00384146, -0.00000124311, 0.0613583, 0.0000000778271, 0.00390023, -0.0000314043, 0.0622919, 0.00000196626, 0.00389971, -0.000125622, 0.0622632, 0.00000787379, 0.00389491, -0.000282352, 0.0620659, 0.00001778, 0.00391618, -0.000502512, 0.0624687, 0.0000320918, 0.00392662, -0.000784458, 0.0625113, 0.0000515573, 0.00396053, -0.00112907, 0.0628175, 0.0000778668, 0.00401911, -0.00153821, 0.0633286, 0.000113811, 0.00414994, -0.0020208, 0.0646443, 0.00016445, 0.00441223, -0.00260007, 0.0673886, 0.000237734, 0.00484427, -0.0033097, 0.0716528, 0.000345929, 0.00549109, -0.00418966, 0.0774998, 0.000505987, 0.00636293, -0.00527331, 0.0844758, 0.000739208, 0.00746566, -0.00660428, 0.0921325, 0.00107347, 0.00876625, -0.00818826, 0.0997067, 0.00153691, 0.0103125, -0.0100811, 0.107433, 0.00217153, 0.0123309, -0.0123643, 0.117088, 0.00303427, 0.0146274, -0.0150007, 0.126438, 0.00416018, 0.0172295, -0.0180531, 0.135672, 0.00561513, 0.0204248, -0.0215962, 0.146244, 0.007478, 0.0241597, -0.0256234, 0.157481, 0.00981046, 0.0284693, -0.0302209, 0.169125, 0.0127148, 0.033445, -0.0353333, 0.181659, 0.0162453, 0.0391251, -0.0410845, 0.1944, 0.0205417, 0.0454721, -0.0473451, 0.207082, 0.0256333, 0.0530983, -0.0542858, 0.221656, 0.0317036, 0.0615356, -0.0618384, 0.236036, 0.0388319, 0.0703363, -0.0697631, 0.248398, 0.046974, 0.0810391, -0.0784757, 0.263611, 0.0565246, 0.0920144, -0.0873488, 0.275857, 0.0671724, 0.105584, -0.0973652, 0.292555, 0.0798105, 0.119506, -0.107271, 0.306333, 0.0935945, 0.134434, -0.117608, 0.318888, 0.109106, 0.153399, -0.128938, 0.337552, 0.127074, 0.171258, -0.139944, 0.349955, 0.14643, 0.191059, -0.151288, 0.361545, 0.168, 0.215069, -0.163018, 0.378421, 0.192082, 0.237838, -0.174226, 0.38879, 0.217838, 0.266965, -0.186063, 0.405857, 0.246931, 0.292827, -0.196909, 0.414146, 0.277505, 0.324352, -0.207473, 0.426955, 0.310711, 0.354427, -0.217713, 0.433429, 0.346794, 0.389854, -0.227183, 0.443966, 0.385237, 0.420749, -0.235131, 0.44471, 0.424955, 0.459597, -0.242786, 0.451729, 0.468446, 0.495316, -0.248767, 0.45072, 0.513422, 0.534903, -0.253351, 0.450924, 0.560618, 0.572369, -0.256277, 0.445266, 0.609677, 0.612383, -0.2576, 0.438798, 0.660995, 0.644037, -0.256931, 0.421693, 0.713807, 0.686749, -0.254036, 0.4109, 0.767616, 0.719814, -0.249785, 0.390151, 0.82533, 0.754719, -0.244283, 0.367847, 0.888311, 0.792022, -0.235076, 0.345013, 0.948177, 0.822404, -0.225061, 0.316193, 1.01661, 0.853084, -0.211113, 0.287013, 1.08075, 0.879871, -0.19449, 0.255424, 1.14501, 0.901655, -0.174023, 0.222879, 1.20203, 0.919957, -0.1509, 0.18989, 1.25698, 0.938412, -0.124923, 0.15606, 1.30588, 0.953471, -0.0968139, 0.120512, 1.3529, 0.970451, -0.066734, 0.0828515, 1.3986, 0.985522, -0.034734, 0.0424458, 1.44148, 1.00099, -0.00102222, 0.000678929, 1.48398, 0.000965494, -0.000000627338, 0.0306409, 0.0000000197672, 0.00099168, -0.0000158573, 0.0314638, 0.000000499803, 0.000991068, -0.0000634012, 0.031363, 0.00000200682, 0.000974567, -0.00014144, 0.03036, 0.00000457312, 0.000998079, -0.000252812, 0.031496, 0.00000860131, 0.00102243, -0.000396506, 0.0319955, 0.0000148288, 0.00107877, -0.000577593, 0.0331376, 0.0000249141, 0.00121622, -0.000816816, 0.0359396, 0.0000423011, 0.0014455, -0.00113761, 0.0399652, 0.0000724613, 0.00178791, -0.00156959, 0.0450556, 0.000123929, 0.00225668, -0.00214064, 0.0508025, 0.000208531, 0.00285627, -0.00287655, 0.0568443, 0.000341969, 0.0035991, -0.00380271, 0.0630892, 0.000544158, 0.00455524, -0.00496264, 0.0702204, 0.000842423, 0.00569143, -0.0063793, 0.0773426, 0.00126704, 0.00716928, -0.00813531, 0.0860839, 0.00186642, 0.00885307, -0.0101946, 0.0944079, 0.00267014, 0.0109316, -0.0126386, 0.103951, 0.00374033, 0.0133704, -0.0154876, 0.113786, 0.0051304, 0.0161525, -0.0187317, 0.123477, 0.00688858, 0.0194267, -0.0224652, 0.133986, 0.00910557, 0.0230967, -0.0265976, 0.143979, 0.0118074, 0.0273627, -0.0312848, 0.154645, 0.0151266, 0.0323898, -0.0365949, 0.166765, 0.0191791, 0.0379225, -0.0422914, 0.177932, 0.0239236, 0.0447501, -0.0487469, 0.19167, 0.0296568, 0.0519391, -0.0556398, 0.203224, 0.0362924, 0.0599464, -0.0631646, 0.215652, 0.0440585, 0.0702427, -0.0714308, 0.232089, 0.0531619, 0.0806902, -0.0800605, 0.245258, 0.0634564, 0.0923194, -0.0892815, 0.258609, 0.0752481, 0.106938, -0.09931, 0.276654, 0.0888914, 0.121238, -0.109575, 0.289847, 0.104055, 0.138817, -0.120461, 0.307566, 0.121266, 0.15595, -0.131209, 0.320117, 0.139944, 0.178418, -0.143049, 0.339677, 0.161591, 0.197875, -0.154074, 0.349886, 0.184303, 0.224368, -0.166307, 0.369352, 0.210669, 0.252213, -0.178051, 0.386242, 0.238895, 0.277321, -0.189335, 0.395294, 0.269182, 0.310332, -0.200683, 0.412148, 0.302508, 0.338809, -0.210856, 0.418266, 0.337264, 0.372678, -0.220655, 0.428723, 0.374881, 0.405632, -0.230053, 0.433887, 0.415656, 0.442293, -0.237993, 0.439911, 0.457982, 0.477256, -0.244897, 0.440175, 0.502831, 0.515592, -0.250657, 0.441079, 0.550277, 0.550969, -0.255459, 0.435219, 0.601102, 0.592883, -0.257696, 0.432882, 0.651785, 0.629092, -0.259894, 0.421054, 0.708961, 0.672033, -0.258592, 0.41177, 0.763806, 0.709147, -0.256525, 0.395267, 0.824249, 0.745367, -0.254677, 0.375013, 0.8951, 0.784715, -0.247892, 0.353906, 0.959317, 0.818107, -0.240162, 0.327801, 1.03153, 0.847895, -0.229741, 0.298821, 1.10601, 0.879603, -0.213084, 0.269115, 1.164, 0.902605, -0.195242, 0.236606, 1.22854, 0.922788, -0.174505, 0.203442, 1.29017, 0.944831, -0.150169, 0.169594, 1.34157, 0.959656, -0.124099, 0.135909, 1.3956, 0.972399, -0.0960626, 0.0990563, 1.45128, 0.986549, -0.0657097, 0.0602348, 1.50312, 1.00013, -0.0333558, 0.0186694, 1.55364, 0.00000619747, -0.0000001, 0.00778326, 0.0000000000796756, 0.0000000237499, -0.0000000999999, 0.0000282592, 0.000000000114596, 0.00000100292, -0.00000166369, 0.000250354, 0.00000000677492, 0.00000350752, -0.00000637769, 0.000357289, 0.0000000631655, 0.00000826445, -0.0000174689, 0.000516179, 0.00000031851, 0.0000242481, -0.0000450868, 0.0010223, 0.00000130577, 0.0000455631, -0.000089044, 0.00144302, 0.00000374587, 0.0000971222, -0.000178311, 0.00241912, 0.0000102584, 0.000171403, -0.000313976, 0.00354938, 0.0000236481, 0.000292747, -0.000520026, 0.00513765, 0.0000496014, 0.000789827, -0.00118187, 0.0238621, 0.000139056, 0.00114093, -0.00171827, 0.0286691, 0.000244093, 0.00176119, -0.00249667, 0.0368565, 0.000420623, 0.0022233, -0.00333742, 0.0400469, 0.00065673, 0.00343382, -0.00481976, 0.0535751, 0.00109323, 0.00427602, -0.00600755, 0.057099, 0.00155268, 0.00461435, -0.00737637, 0.0551084, 0.00215031, 0.00695698, -0.00971401, 0.0715767, 0.00316529, 0.00867619, -0.0120943, 0.0793314, 0.00436995, 0.0106694, -0.0148202, 0.0869391, 0.0058959, 0.0140351, -0.0183501, 0.101572, 0.00798757, 0.0168939, -0.022006, 0.11018, 0.0104233, 0.020197, -0.0261568, 0.119041, 0.0134167, 0.0254702, -0.0312778, 0.135404, 0.0173009, 0.0298384, -0.0362469, 0.1437, 0.0215428, 0.035159, -0.042237, 0.15512, 0.0268882, 0.0427685, -0.0488711, 0.17128, 0.033235, 0.0494848, -0.0557997, 0.181813, 0.0404443, 0.0592394, -0.0635578, 0.198745, 0.0490043, 0.0681463, -0.071838, 0.210497, 0.0588239, 0.0804753, -0.0809297, 0.228864, 0.0702835, 0.0942205, -0.0906488, 0.247008, 0.0834012, 0.106777, -0.100216, 0.258812, 0.0975952, 0.124471, -0.110827, 0.278617, 0.114162, 0.138389, -0.121193, 0.287049, 0.131983, 0.159543, -0.13253, 0.307151, 0.152541, 0.176432, -0.143611, 0.31564, 0.174673, 0.201723, -0.15548, 0.33538, 0.199842, 0.229721, -0.167166, 0.355256, 0.227097, 0.250206, -0.178238, 0.360047, 0.256014, 0.282118, -0.189905, 0.378761, 0.28855, 0.312821, -0.201033, 0.39181, 0.323348, 0.341482, -0.211584, 0.397716, 0.360564, 0.377368, -0.221314, 0.410141, 0.400004, 0.418229, -0.230474, 0.423485, 0.442371, 0.444881, -0.239443, 0.418874, 0.488796, 0.488899, -0.245987, 0.427545, 0.535012, 0.520317, -0.253948, 0.422147, 0.589678, 0.568566, -0.256616, 0.42719, 0.637683, 0.599607, -0.26376, 0.415114, 0.703363, 0.64222, -0.268687, 0.408715, 0.771363, 0.685698, -0.2694, 0.399722, 0.83574, 0.732327, -0.266642, 0.388651, 0.897764, 0.769873, -0.267712, 0.369198, 0.983312, 0.806733, -0.263479, 0.346802, 1.06222, 0.843466, -0.254575, 0.321368, 1.13477, 0.873008, -0.242749, 0.29211, 1.20712, 0.908438, -0.22725, 0.262143, 1.27465, 0.936321, -0.207621, 0.228876, 1.33203, 0.950353, -0.187932, 0.19484, 1.40439, 0.96442, -0.165154, 0.163178, 1.4732, 0.979856, -0.139302, 0.127531, 1.53574, 0.982561, -0.11134, 0.0903457, 1.59982, 0.996389, -0.0808124, 0.0489007, 1.6577]; + const LTC_MAT_2 = [1, 0, 0, 0, 1, 0.000000000000000000000000000000791421, 0, 0, 1, 0.00000000000000000000000104392, 0, 0, 1, 0.00000000000000000000349405, 0, 0, 1, 0.00000000000000000109923, 0, 0, 1, 0.0000000000000000947414, 0, 0, 1, 0.00000000000000359627, 0, 0, 1, 0.0000000000000772053, 0, 0, 1, 0.00000000000108799, 0, 0, 1, 0.0000000000110655, 0, 0, 1, 0.0000000000865818, 0, 0, 0.999998, 0.000000000545037, 0, 0, 0.999994, 0.00000000285095, 0, 0, 0.999989, 0.0000000126931, 0, 0, 0.999973, 0.0000000489938, 0, 0, 0.999947, 0.000000166347, 0, 0, 0.999894, 0.000000502694, 0, 0, 0.999798, 0.00000136532, 0, 0, 0.999617, 0.00000335898, 0, 0, 0.999234, 0.00000752126, 0, 0, 0.998258, 0.0000152586, 0, 0, 0.99504, 0.0000266207, 0, 0, 0.980816, 0.0000236802, 0, 0, 0.967553, 0.00000207684, 0, 0, 0.966877, 0.00000403733, 0, 0, 0.965752, 0.00000741174, 0, 0, 0.96382, 0.0000127746, 0, 0, 0.960306, 0.0000202792, 0, 0, 0.953619, 0.0000280232, 0, 0, 0.941103, 0.0000278816, 0, 0, 0.926619, 0.0000160221, 0, 0, 0.920983, 0.0000235164, 0, 0, 0.912293, 0.0000311924, 0, 0.0158731, 0.899277, 0.0000348118, 0, 0.0476191, 0.880884, 0.000026041, 0, 0.0793651, 0.870399, 0.0000338726, 0, 0.111111, 0.856138, 0.0000392906, 0, 0.142857, 0.837436, 0.0000372874, 0, 0.174603, 0.820973, 0.0000392558, 0, 0.206349, 0.803583, 0.0000434658, 0, 0.238095, 0.782168, 0.000040256, 0, 0.269841, 0.764107, 0.0000448159, 0, 0.301587, 0.743092, 0.0000457627, 0, 0.333333, 0.721626, 0.0000455314, 0, 0.365079, 0.700375, 0.0000477335, 0, 0.396825, 0.677334, 0.0000461072, 0, 0.428571, 0.655702, 0.0000484393, 0, 0.460317, 0.632059, 0.0000464583, 0, 0.492064, 0.610125, 0.0000483923, 0, 0.52381, 0.58653, 0.0000464342, 0, 0.555556, 0.564508, 0.0000477033, 0, 0.587302, 0.541405, 0.0000459263, 0, 0.619048, 0.519556, 0.000046412, 0, 0.650794, 0.497292, 0.0000448913, 0, 0.68254, 0.475898, 0.0000445789, 0, 0.714286, 0.454722, 0.0000433496, 0, 0.746032, 0.434042, 0.0000423054, 0, 0.777778, 0.414126, 0.0000413737, 0, 0.809524, 0.394387, 0.0000397265, 0, 0.84127, 0.375841, 0.0000390709, 0, 0.873016, 0.357219, 0.0000369938, 0, 0.904762, 0.340084, 0.0000365618, 0, 0.936508, 0.322714, 0.0000342533, 0, 0.968254, 0.306974, 0.0000339596, 0, 1, 1, 0.00000000000000000101524, 0, 0, 1, 0.0000000000000000010292, 0, 0, 1, 0.00000000000000000130908, 0, 0, 1, 0.00000000000000000473331, 0, 0, 1, 0.0000000000000000625319, 0, 0, 1, 0.00000000000000107932, 0, 0, 1, 0.0000000000000163779, 0, 0, 1, 0.000000000000203198, 0, 0, 1, 0.00000000000204717, 0, 0, 0.999999, 0.0000000000168995, 0, 0, 0.999998, 0.000000000115855, 0, 0, 0.999996, 0.00000000066947, 0, 0, 0.999991, 0.00000000330863, 0, 0, 0.999983, 0.0000000141737, 0, 0, 0.999968, 0.0000000532626, 0, 0, 0.99994, 0.000000177431, 0, 0, 0.999891, 0.000000528835, 0, 0, 0.999797, 0.00000142169, 0, 0, 0.999617, 0.00000347057, 0, 0, 0.999227, 0.0000077231, 0, 0, 0.998239, 0.0000155753, 0, 0, 0.994937, 0.0000268495, 0, 0, 0.980225, 0.0000213742, 0, 0, 0.967549, 0.0000021631, 0, 0, 0.966865, 0.00000417989, 0, 0, 0.965739, 0.00000763341, 0, 0, 0.963794, 0.0000130892, 0, 0, 0.960244, 0.0000206456, 0, 0, 0.953495, 0.0000282016, 0, 0.000148105, 0.940876, 0.0000271581, 0, 0.002454, 0.926569, 0.0000164159, 0, 0.00867491, 0.920905, 0.0000239521, 0, 0.01956, 0.912169, 0.0000315127, 0, 0.035433, 0.899095, 0.0000346626, 0, 0.056294, 0.882209, 0.0000290223, 0, 0.0818191, 0.870272, 0.0000342992, 0, 0.111259, 0.855977, 0.0000394164, 0, 0.142857, 0.837431, 0.0000372343, 0, 0.174603, 0.820826, 0.0000396691, 0, 0.206349, 0.803408, 0.0000435395, 0, 0.238095, 0.782838, 0.0000419579, 0, 0.269841, 0.763941, 0.0000450953, 0, 0.301587, 0.742904, 0.0000455847, 0, 0.333333, 0.721463, 0.0000458833, 0, 0.365079, 0.700197, 0.0000477159, 0, 0.396825, 0.677501, 0.0000470641, 0, 0.428571, 0.655527, 0.0000484732, 0, 0.460317, 0.6324, 0.0000476834, 0, 0.492064, 0.609964, 0.0000484213, 0, 0.52381, 0.586839, 0.0000475541, 0, 0.555556, 0.564353, 0.0000476951, 0, 0.587302, 0.541589, 0.0000467611, 0, 0.619048, 0.519413, 0.0000463493, 0, 0.650794, 0.497337, 0.0000453994, 0, 0.68254, 0.475797, 0.0000445308, 0, 0.714286, 0.454659, 0.0000435787, 0, 0.746032, 0.434065, 0.0000424839, 0, 0.777778, 0.414018, 0.000041436, 0, 0.809524, 0.39455, 0.0000401902, 0, 0.84127, 0.375742, 0.0000390813, 0, 0.873016, 0.357501, 0.0000377116, 0, 0.904762, 0.339996, 0.000036535, 0, 0.936508, 0.323069, 0.0000351265, 0, 0.968254, 0.306897, 0.0000339112, 0, 1, 1, 0.0000000000000010396, 0, 0, 1, 0.00000000000000104326, 0, 0, 1, 0.00000000000000110153, 0, 0, 1, 0.00000000000000144668, 0, 0, 1, 0.0000000000000034528, 0, 0, 1, 0.0000000000000175958, 0, 0, 1, 0.00000000000012627, 0, 0, 1, 0.000000000000936074, 0, 0, 1, 0.00000000000645742, 0, 0, 0.999998, 0.0000000000401228, 0, 0, 0.999997, 0.000000000222338, 0, 0, 0.999995, 0.0000000010967, 0, 0, 0.999991, 0.00000000482132, 0, 0, 0.999981, 0.0000000189434, 0, 0, 0.999967, 0.0000000667716, 0, 0, 0.999938, 0.000000212066, 0, 0, 0.999886, 0.00000060977, 0, 0, 0.999792, 0.00000159504, 0, 0, 0.999608, 0.00000381191, 0, 0, 0.999209, 0.00000833727, 0, 0, 0.998179, 0.0000165288, 0, 0, 0.994605, 0.0000274387, 0, 0, 0.979468, 0.0000167316, 0, 0, 0.967529, 0.00000242877, 0, 0, 0.966836, 0.00000461696, 0, 0, 0.96569, 0.00000830977, 0, 0, 0.963706, 0.0000140427, 0, 0.00000244659, 0.960063, 0.0000217353, 0, 0.000760774, 0.953113, 0.0000286606, 0, 0.00367261, 0.940192, 0.0000247691, 0, 0.00940263, 0.927731, 0.0000195814, 0, 0.018333, 0.920669, 0.0000252531, 0, 0.0306825, 0.911799, 0.0000324277, 0, 0.0465556, 0.89857, 0.0000340982, 0, 0.0659521, 0.883283, 0.0000319622, 0, 0.0887677, 0.86989, 0.000035548, 0, 0.114784, 0.855483, 0.0000397143, 0, 0.143618, 0.837987, 0.0000391665, 0, 0.174606, 0.820546, 0.0000411306, 0, 0.206349, 0.802878, 0.0000436753, 0, 0.238095, 0.783402, 0.0000444, 0, 0.269841, 0.763439, 0.0000458726, 0, 0.301587, 0.742925, 0.0000467097, 0, 0.333333, 0.721633, 0.0000478887, 0, 0.365079, 0.69985, 0.0000481251, 0, 0.396825, 0.67783, 0.0000491811, 0, 0.428571, 0.655126, 0.0000488199, 0, 0.460318, 0.632697, 0.0000496025, 0, 0.492064, 0.609613, 0.000048829, 0, 0.52381, 0.587098, 0.0000492754, 0, 0.555556, 0.564119, 0.0000482625, 0, 0.587302, 0.541813, 0.0000482807, 0, 0.619048, 0.519342, 0.0000471552, 0, 0.650794, 0.497514, 0.0000466765, 0, 0.68254, 0.475879, 0.0000455582, 0, 0.714286, 0.454789, 0.0000446007, 0, 0.746032, 0.434217, 0.0000435382, 0, 0.777778, 0.414086, 0.0000421753, 0, 0.809524, 0.394744, 0.0000412093, 0, 0.84127, 0.375782, 0.0000396634, 0, 0.873016, 0.357707, 0.0000386419, 0, 0.904762, 0.340038, 0.0000370345, 0, 0.936508, 0.323284, 0.0000359725, 0, 0.968254, 0.306954, 0.00003436, 0, 1, 1, 0.0000000000000599567, 0, 0, 1, 0.0000000000000600497, 0, 0, 1, 0.0000000000000614839, 0, 0, 1, 0.0000000000000686641, 0, 0, 1, 0.0000000000000972658, 0, 0, 1, 0.000000000000221271, 0, 0, 1, 0.000000000000833195, 0, 0, 1, 0.00000000000403601, 0, 0, 0.999999, 0.0000000000206001, 0, 0, 0.999998, 0.000000000101739, 0, 0, 0.999997, 0.000000000470132, 0, 0, 0.999993, 0.00000000200436, 0, 0, 0.999988, 0.00000000783682, 0, 0, 0.999979, 0.0000000280338, 0, 0, 0.999962, 0.0000000917033, 0, 0, 0.999933, 0.000000274514, 0, 0, 0.999881, 0.000000753201, 0, 0, 0.999783, 0.00000189826, 0, 0, 0.999594, 0.00000440279, 0, 0, 0.999178, 0.0000093898, 0, 0, 0.998073, 0.0000181265, 0, 0, 0.993993, 0.0000280487, 0, 0, 0.979982, 0.0000149422, 0, 0, 0.968145, 0.00000378481, 0, 0, 0.966786, 0.0000053771, 0, 0, 0.965611, 0.00000947508, 0, 0.0000388934, 0.963557, 0.0000156616, 0, 0.0009693, 0.959752, 0.0000235144, 0, 0.00370329, 0.952461, 0.0000291568, 0, 0.00868428, 0.940193, 0.0000240102, 0, 0.0161889, 0.929042, 0.0000231235, 0, 0.0263948, 0.920266, 0.0000273968, 0, 0.0394088, 0.911178, 0.0000337915, 0, 0.0552818, 0.897873, 0.0000333629, 0, 0.0740138, 0.884053, 0.0000351405, 0, 0.0955539, 0.869455, 0.0000378034, 0, 0.119795, 0.854655, 0.0000399378, 0, 0.14656, 0.838347, 0.0000419108, 0, 0.175573, 0.820693, 0.0000440831, 0, 0.206388, 0.802277, 0.0000445599, 0, 0.238095, 0.783634, 0.0000472691, 0, 0.269841, 0.763159, 0.0000476984, 0, 0.301587, 0.742914, 0.0000491487, 0, 0.333333, 0.721662, 0.0000502312, 0, 0.365079, 0.699668, 0.0000502817, 0, 0.396825, 0.677839, 0.000051406, 0, 0.428571, 0.655091, 0.0000511095, 0, 0.460317, 0.632665, 0.0000516067, 0, 0.492064, 0.609734, 0.0000512255, 0, 0.52381, 0.587043, 0.0000510263, 0, 0.555556, 0.564298, 0.000050565, 0, 0.587302, 0.541769, 0.0000497951, 0, 0.619048, 0.519529, 0.0000492698, 0, 0.650794, 0.497574, 0.0000482066, 0, 0.68254, 0.476028, 0.0000473689, 0, 0.714286, 0.454961, 0.0000461941, 0, 0.746032, 0.434341, 0.0000450618, 0, 0.777778, 0.414364, 0.0000438355, 0, 0.809524, 0.394832, 0.0000424196, 0, 0.84127, 0.376109, 0.0000412563, 0, 0.873016, 0.35779, 0.0000396226, 0, 0.904762, 0.340379, 0.0000384886, 0, 0.936508, 0.323385, 0.0000368214, 0, 0.968254, 0.307295, 0.0000356636, 0, 1, 1, 0.00000000000106465, 0, 0, 1, 0.00000000000106555, 0, 0, 1, 0.00000000000107966, 0, 0, 1, 0.00000000000114601, 0, 0, 1, 0.00000000000137123, 0, 0, 1, 0.0000000000021243, 0, 0, 0.999999, 0.00000000000489653, 0, 0, 0.999999, 0.0000000000160283, 0, 0, 0.999998, 0.000000000062269, 0, 0, 0.999997, 0.000000000251859, 0, 0, 0.999996, 0.000000000996192, 0, 0, 0.999992, 0.00000000374531, 0, 0, 0.999986, 0.0000000132022, 0, 0, 0.999975, 0.0000000433315, 0, 0, 0.999959, 0.000000131956, 0, 0, 0.999927, 0.000000372249, 0, 0, 0.999871, 0.000000972461, 0, 0, 0.999771, 0.00000235343, 0, 0, 0.999572, 0.0000052768, 0, 0, 0.999133, 0.0000109237, 0, 0, 0.997912, 0.0000203675, 0, 0, 0.993008, 0.0000279396, 0, 0, 0.980645, 0.0000139604, 0, 0, 0.970057, 0.00000646596, 0, 0, 0.966717, 0.0000065089, 0, 0.0000474145, 0.965497, 0.0000111863, 0, 0.00089544, 0.96334, 0.0000179857, 0, 0.0032647, 0.959294, 0.0000259045, 0, 0.0075144, 0.951519, 0.0000292327, 0, 0.0138734, 0.940517, 0.0000249769, 0, 0.0224952, 0.93014, 0.000026803, 0, 0.0334828, 0.91972, 0.0000303656, 0, 0.0468973, 0.910294, 0.0000353323, 0, 0.0627703, 0.897701, 0.0000351002, 0, 0.0811019, 0.884522, 0.0000388104, 0, 0.10186, 0.869489, 0.0000412932, 0, 0.124985, 0.853983, 0.0000415781, 0, 0.150372, 0.838425, 0.0000454066, 0, 0.177868, 0.820656, 0.0000471624, 0, 0.207245, 0.801875, 0.0000475243, 0, 0.238143, 0.783521, 0.0000505621, 0, 0.269841, 0.763131, 0.000050721, 0, 0.301587, 0.74261, 0.0000523293, 0, 0.333333, 0.72148, 0.0000528699, 0, 0.365079, 0.699696, 0.0000538677, 0, 0.396825, 0.677592, 0.0000539255, 0, 0.428571, 0.65525, 0.0000546367, 0, 0.460317, 0.632452, 0.0000541348, 0, 0.492064, 0.609903, 0.0000544976, 0, 0.52381, 0.586928, 0.0000536201, 0, 0.555556, 0.564464, 0.0000535185, 0, 0.587302, 0.541801, 0.0000524949, 0, 0.619048, 0.519681, 0.000051812, 0, 0.650794, 0.497685, 0.0000507687, 0, 0.68254, 0.47622, 0.0000496243, 0, 0.714286, 0.455135, 0.0000485714, 0, 0.746032, 0.4346, 0.0000471847, 0, 0.777778, 0.414564, 0.0000459294, 0, 0.809524, 0.395165, 0.0000444705, 0, 0.84127, 0.376333, 0.0000430772, 0, 0.873016, 0.358197, 0.0000416229, 0, 0.904762, 0.34064, 0.0000401019, 0, 0.936508, 0.323816, 0.0000386623, 0, 0.968254, 0.307581, 0.0000370933, 0, 1, 1, 0.00000000000991541, 0, 0, 1, 0.00000000000992077, 0, 0, 1, 0.0000000000100041, 0, 0, 1, 0.000000000010385, 0, 0, 1, 0.0000000000115777, 0, 0, 1, 0.0000000000150215, 0, 0, 0.999999, 0.0000000000254738, 0, 0, 0.999999, 0.0000000000598822, 0, 0, 0.999998, 0.000000000179597, 0, 0, 0.999997, 0.000000000602367, 0, 0, 0.999994, 0.00000000206835, 0, 0, 0.99999, 0.00000000694952, 0, 0, 0.999984, 0.0000000223363, 0, 0, 0.999972, 0.0000000678578, 0, 0, 0.999952, 0.000000193571, 0, 0, 0.999919, 0.000000516594, 0, 0, 0.99986, 0.00000128739, 0, 0, 0.999753, 0.00000299298, 0, 0, 0.999546, 0.00000648258, 0, 0, 0.999074, 0.0000129985, 0, 0, 0.997671, 0.0000232176, 0, 0, 0.991504, 0.0000256701, 0, 0, 0.981148, 0.0000131141, 0, 0, 0.971965, 0.00000869048, 0, 0.0000280182, 0.966624, 0.00000808301, 0, 0.000695475, 0.965344, 0.0000135235, 0, 0.00265522, 0.963048, 0.0000210592, 0, 0.00622975, 0.958673, 0.0000287473, 0, 0.0116234, 0.950262, 0.0000281379, 0, 0.018976, 0.940836, 0.0000271089, 0, 0.0283844, 0.930996, 0.000030926, 0, 0.0399151, 0.919848, 0.0000348359, 0, 0.0536063, 0.909136, 0.0000366092, 0, 0.0694793, 0.897554, 0.0000384162, 0, 0.0875342, 0.884691, 0.0000430971, 0, 0.107749, 0.869414, 0.0000447803, 0, 0.130087, 0.853462, 0.0000452858, 0, 0.154481, 0.838187, 0.0000495769, 0, 0.180833, 0.820381, 0.0000502709, 0, 0.209005, 0.801844, 0.0000522713, 0, 0.238791, 0.783061, 0.0000541505, 0, 0.269869, 0.763205, 0.0000553712, 0, 0.301587, 0.742362, 0.0000564909, 0, 0.333333, 0.721393, 0.0000572646, 0, 0.365079, 0.699676, 0.0000581012, 0, 0.396825, 0.677395, 0.000058096, 0, 0.428571, 0.655208, 0.0000585766, 0, 0.460317, 0.632451, 0.0000583602, 0, 0.492064, 0.609839, 0.0000580234, 0, 0.52381, 0.587093, 0.0000577161, 0, 0.555556, 0.564467, 0.0000568447, 0, 0.587302, 0.542043, 0.0000563166, 0, 0.619048, 0.519826, 0.000055156, 0, 0.650794, 0.497952, 0.0000541682, 0, 0.68254, 0.476477, 0.0000528971, 0, 0.714286, 0.455412, 0.0000514952, 0, 0.746032, 0.434926, 0.0000502222, 0, 0.777778, 0.4149, 0.0000485779, 0, 0.809524, 0.395552, 0.0000472242, 0, 0.84127, 0.376712, 0.0000454891, 0, 0.873016, 0.358622, 0.0000440924, 0, 0.904762, 0.341048, 0.0000422984, 0, 0.936508, 0.324262, 0.0000408582, 0, 0.968254, 0.308013, 0.0000390839, 0, 1, 1, 0.0000000000613913, 0, 0, 1, 0.0000000000614145, 0, 0, 1, 0.0000000000617708, 0, 0, 1, 0.0000000000633717, 0, 0, 1, 0.0000000000681648, 0, 0, 1, 0.0000000000808291, 0, 0, 1, 0.000000000114608, 0, 0, 0.999998, 0.000000000210507, 0, 0, 0.999997, 0.000000000499595, 0, 0, 0.999995, 0.00000000139897, 0, 0, 0.999994, 0.00000000419818, 0, 0, 0.999988, 0.0000000127042, 0, 0, 0.999979, 0.0000000375153, 0, 0, 0.999965, 0.000000106206, 0, 0, 0.999945, 0.000000285381, 0, 0, 0.999908, 0.000000723611, 0, 0, 0.999846, 0.0000017255, 0, 0, 0.999733, 0.00000386104, 0, 0, 0.999511, 0.00000808493, 0, 0, 0.998993, 0.0000156884, 0, 0, 0.997326, 0.0000265538, 0, 0, 0.989706, 0.0000206466, 0, 0, 0.981713, 0.0000130756, 0, 0.0000070005, 0.973636, 0.0000106473, 0, 0.000464797, 0.966509, 0.000010194, 0, 0.00201743, 0.965149, 0.0000165881, 0, 0.00497549, 0.962669, 0.0000249147, 0, 0.00953262, 0.95786, 0.0000317449, 0, 0.0158211, 0.949334, 0.0000281045, 0, 0.0239343, 0.941041, 0.0000303263, 0, 0.0339372, 0.931575, 0.0000356754, 0, 0.0458738, 0.920102, 0.0000397075, 0, 0.059772, 0.908002, 0.0000384886, 0, 0.075645, 0.897269, 0.000043027, 0, 0.0934929, 0.884559, 0.0000479925, 0, 0.113302, 0.869161, 0.000048246, 0, 0.135045, 0.853342, 0.0000509505, 0, 0.158678, 0.837633, 0.0000542846, 0, 0.184136, 0.820252, 0.0000554139, 0, 0.211325, 0.801872, 0.0000581412, 0, 0.240113, 0.782418, 0.0000585535, 0, 0.270306, 0.7631, 0.0000610923, 0, 0.301594, 0.742183, 0.0000613678, 0, 0.333333, 0.721098, 0.0000627275, 0, 0.365079, 0.699512, 0.0000629413, 0, 0.396825, 0.677372, 0.0000636351, 0, 0.428571, 0.655059, 0.0000633555, 0, 0.460317, 0.632567, 0.0000636513, 0, 0.492064, 0.609784, 0.0000628965, 0, 0.52381, 0.587237, 0.0000625546, 0, 0.555556, 0.564525, 0.0000615825, 0, 0.587302, 0.542181, 0.0000605048, 0, 0.619048, 0.520017, 0.0000596329, 0, 0.650794, 0.498204, 0.0000581516, 0, 0.68254, 0.476742, 0.0000569186, 0, 0.714286, 0.455803, 0.0000553833, 0, 0.746032, 0.435251, 0.0000537807, 0, 0.777778, 0.415374, 0.0000522025, 0, 0.809524, 0.395921, 0.0000503421, 0, 0.84127, 0.377253, 0.0000488211, 0, 0.873016, 0.359021, 0.0000468234, 0, 0.904762, 0.341637, 0.0000453269, 0, 0.936508, 0.3247, 0.0000433014, 0, 0.968254, 0.308625, 0.0000418007, 0, 1, 1, 0.000000000286798, 0, 0, 1, 0.000000000286877, 0, 0, 1, 0.000000000288094, 0, 0, 1, 0.000000000293506, 0, 0, 1, 0.000000000309262, 0, 0, 0.999999, 0.000000000348593, 0, 0, 0.999999, 0.000000000444582, 0, 0, 0.999998, 0.000000000688591, 0, 0, 0.999996, 0.00000000134391, 0, 0, 0.999993, 0.00000000317438, 0, 0, 0.999989, 0.00000000835609, 0, 0, 0.999983, 0.0000000228677, 0, 0, 0.999974, 0.0000000623361, 0, 0, 0.999959, 0.000000165225, 0, 0, 0.999936, 0.000000419983, 0, 0, 0.999896, 0.00000101546, 0, 0, 0.99983, 0.00000232376, 0, 0, 0.999709, 0.0000050156, 0, 0, 0.999469, 0.000010167, 0, 0, 0.998886, 0.0000190775, 0, 0, 0.996819, 0.0000300511, 0, 0, 0.988837, 0.0000185092, 0, 0.000000168222, 0.982178, 0.0000134622, 0, 0.000259622, 0.975017, 0.0000125961, 0, 0.00142595, 0.967101, 0.000013507, 0, 0.00382273, 0.964905, 0.0000205003, 0, 0.00764164, 0.96218, 0.000029546, 0, 0.0130121, 0.956821, 0.0000343738, 0, 0.0200253, 0.948829, 0.0000305063, 0, 0.0287452, 0.941092, 0.0000346487, 0, 0.039218, 0.931883, 0.0000412061, 0, 0.0514748, 0.920211, 0.0000444651, 0, 0.0655351, 0.907307, 0.0000431252, 0, 0.0814082, 0.89684, 0.0000490382, 0, 0.0990939, 0.884119, 0.000053334, 0, 0.118583, 0.869148, 0.000054114, 0, 0.139856, 0.853377, 0.0000578536, 0, 0.162882, 0.836753, 0.0000592285, 0, 0.187615, 0.820063, 0.0000622787, 0, 0.213991, 0.801694, 0.0000645492, 0, 0.241918, 0.782116, 0.000065353, 0, 0.271267, 0.762673, 0.0000674344, 0, 0.301847, 0.742133, 0.0000682788, 0, 0.333333, 0.720779, 0.0000691959, 0, 0.365079, 0.699386, 0.0000696817, 0, 0.396826, 0.67732, 0.0000699583, 0, 0.428572, 0.654888, 0.0000698447, 0, 0.460318, 0.632499, 0.0000694063, 0, 0.492064, 0.609825, 0.0000691612, 0, 0.52381, 0.587287, 0.0000681576, 0, 0.555556, 0.564743, 0.0000674138, 0, 0.587302, 0.542409, 0.0000661617, 0, 0.619048, 0.520282, 0.0000647785, 0, 0.650794, 0.498506, 0.0000633836, 0, 0.68254, 0.477102, 0.0000615905, 0, 0.714286, 0.456167, 0.0000601013, 0, 0.746032, 0.435728, 0.0000581457, 0, 0.777778, 0.415809, 0.0000564215, 0, 0.809524, 0.396517, 0.0000544997, 0, 0.84127, 0.377737, 0.0000525061, 0, 0.873016, 0.359698, 0.0000506831, 0, 0.904762, 0.342164, 0.000048568, 0, 0.936508, 0.325417, 0.0000467826, 0, 0.968254, 0.309186, 0.0000446736, 0, 1, 1, 0.00000000109018, 0, 0, 1, 0.0000000010904, 0, 0, 1, 0.00000000109393, 0, 0, 1, 0.0000000011095, 0, 0, 1, 0.000000001154, 0, 0, 1, 0.00000000126089, 0, 0, 0.999999, 0.0000000015059, 0, 0, 0.999997, 0.00000000207899, 0, 0, 0.999994, 0.00000000348164, 0, 0, 0.999993, 0.00000000705728, 0, 0, 0.999987, 0.0000000163692, 0, 0, 0.999981, 0.0000000406033, 0, 0, 0.999969, 0.00000010245, 0, 0, 0.999953, 0.000000255023, 0, 0, 0.999925, 0.00000061511, 0, 0, 0.999881, 0.00000142218, 0, 0, 0.99981, 0.00000313086, 0, 0, 0.99968, 0.00000653119, 0, 0, 0.999418, 0.000012832, 0, 0, 0.998748, 0.0000232497, 0, 0, 0.996066, 0.0000329522, 0, 0, 0.988379, 0.0000179613, 0, 0.000108799, 0.982567, 0.0000143715, 0, 0.000921302, 0.976097, 0.0000148096, 0, 0.00280738, 0.968475, 0.0000178905, 0, 0.00596622, 0.964606, 0.0000253921, 0, 0.0105284, 0.961564, 0.0000348623, 0, 0.0165848, 0.955517, 0.0000357612, 0, 0.0242, 0.948381, 0.0000343493, 0, 0.03342, 0.941095, 0.0000405849, 0, 0.0442777, 0.931923, 0.0000475394, 0, 0.0567958, 0.91996, 0.0000484328, 0, 0.0709879, 0.907419, 0.0000502146, 0, 0.086861, 0.89618, 0.0000561654, 0, 0.104415, 0.88337, 0.0000587612, 0, 0.123643, 0.869046, 0.0000618057, 0, 0.144531, 0.853278, 0.0000657392, 0, 0.167057, 0.836091, 0.000066303, 0, 0.191188, 0.819644, 0.0000704445, 0, 0.216878, 0.801246, 0.0000714071, 0, 0.244062, 0.782031, 0.0000740093, 0, 0.272649, 0.762066, 0.000074685, 0, 0.302509, 0.741964, 0.0000766647, 0, 0.333442, 0.720554, 0.0000766328, 0, 0.365079, 0.699098, 0.0000777857, 0, 0.396826, 0.677189, 0.0000774633, 0, 0.428572, 0.65484, 0.0000776235, 0, 0.460318, 0.632496, 0.0000770316, 0, 0.492064, 0.609908, 0.0000762669, 0, 0.52381, 0.587312, 0.0000753972, 0, 0.555556, 0.564938, 0.0000739994, 0, 0.587302, 0.542577, 0.0000728382, 0, 0.619048, 0.52062, 0.000071112, 0, 0.650794, 0.498819, 0.0000694004, 0, 0.68254, 0.477555, 0.0000675575, 0, 0.714286, 0.456568, 0.0000653449, 0, 0.746032, 0.436278, 0.0000636068, 0, 0.777778, 0.41637, 0.0000613466, 0, 0.809524, 0.397144, 0.0000594177, 0, 0.84127, 0.378412, 0.0000570987, 0, 0.873016, 0.360376, 0.0000550419, 0, 0.904762, 0.342906, 0.0000527422, 0, 0.936508, 0.326136, 0.0000506544, 0, 0.968254, 0.30997, 0.0000484307, 0, 1, 1, 0.00000000354014, 0, 0, 1, 0.00000000354073, 0, 0, 1, 0.00000000354972, 0, 0, 1, 0.00000000358929, 0, 0, 1, 0.00000000370093, 0, 0, 0.999999, 0.00000000396194, 0, 0, 0.999998, 0.00000000453352, 0, 0, 0.999997, 0.00000000578828, 0, 0, 0.999994, 0.00000000863812, 0, 0, 0.999991, 0.0000000153622, 0, 0, 0.999985, 0.0000000316356, 0, 0, 0.999977, 0.0000000712781, 0, 0, 0.999964, 0.000000166725, 0, 0, 0.999945, 0.000000390501, 0, 0, 0.999912, 0.000000895622, 0, 0, 0.999866, 0.00000198428, 0, 0, 0.999786, 0.00000421038, 0, 0, 0.999647, 0.00000850239, 0, 0, 0.999356, 0.0000162059, 0, 0, 0.998563, 0.0000282652, 0, 0, 0.994928, 0.0000336309, 0, 0.0000244244, 0.987999, 0.0000178458, 0, 0.000523891, 0.982893, 0.0000159162, 0, 0.00194729, 0.977044, 0.0000178056, 0, 0.00451099, 0.969972, 0.0000230624, 0, 0.00835132, 0.964237, 0.0000313922, 0, 0.013561, 0.960791, 0.0000406145, 0, 0.0202056, 0.954292, 0.0000372796, 0, 0.0283321, 0.948052, 0.0000403199, 0, 0.0379739, 0.940938, 0.0000479537, 0, 0.0491551, 0.931689, 0.0000545292, 0, 0.0618918, 0.91987, 0.000054038, 0, 0.0761941, 0.907665, 0.0000589909, 0, 0.0920672, 0.895281, 0.0000642651, 0, 0.109511, 0.882621, 0.0000659707, 0, 0.12852, 0.86873, 0.0000709973, 0, 0.149085, 0.853008, 0.0000742221, 0, 0.171189, 0.835944, 0.0000761754, 0, 0.194809, 0.818949, 0.0000797052, 0, 0.21991, 0.800951, 0.0000812434, 0, 0.246447, 0.781847, 0.0000838075, 0, 0.274352, 0.761649, 0.000084501, 0, 0.303535, 0.74152, 0.0000860258, 0, 0.333857, 0.720495, 0.0000866233, 0, 0.365104, 0.698742, 0.0000868326, 0, 0.396826, 0.677096, 0.000087133, 0, 0.428572, 0.654782, 0.0000863497, 0, 0.460318, 0.632335, 0.0000860206, 0, 0.492064, 0.610031, 0.0000849337, 0, 0.52381, 0.587457, 0.0000838279, 0, 0.555556, 0.56513, 0.000082309, 0, 0.587302, 0.542877, 0.0000803542, 0, 0.619048, 0.5209, 0.0000786928, 0, 0.650794, 0.499291, 0.0000765171, 0, 0.68254, 0.477971, 0.0000744753, 0, 0.714286, 0.457221, 0.000072209, 0, 0.746032, 0.436803, 0.0000697448, 0, 0.777778, 0.417083, 0.0000675333, 0, 0.809524, 0.397749, 0.0000648058, 0, 0.84127, 0.379177, 0.0000625759, 0, 0.873016, 0.361061, 0.0000598584, 0, 0.904762, 0.343713, 0.0000575797, 0, 0.936508, 0.326894, 0.0000549999, 0, 0.968254, 0.310816, 0.0000527482, 0, 1, 1, 0.000000010153, 0, 0, 1, 0.0000000101544, 0, 0, 1, 0.0000000101751, 0, 0, 1, 0.0000000102662, 0, 0, 1, 0.000000010521, 0, 0, 0.999999, 0.0000000111049, 0, 0, 0.999999, 0.0000000123408, 0, 0, 0.999996, 0.000000014924, 0, 0, 0.999992, 0.0000000204471, 0, 0, 0.999989, 0.0000000326539, 0, 0, 0.99998, 0.0000000603559, 0, 0, 0.999971, 0.000000123936, 0, 0, 0.999955, 0.000000269058, 0, 0, 0.999933, 0.000000593604, 0, 0, 0.999901, 0.00000129633, 0, 0, 0.999847, 0.00000275621, 0, 0, 0.999761, 0.00000564494, 0, 0, 0.999607, 0.0000110485, 0, 0, 0.999282, 0.0000204388, 0, 0, 0.99831, 0.0000341084, 0, 0.00000022038, 0.993288, 0.0000294949, 0, 0.000242388, 0.987855, 0.0000192736, 0, 0.0012503, 0.983167, 0.0000182383, 0, 0.0032745, 0.977908, 0.0000218633, 0, 0.00646321, 0.971194, 0.0000290662, 0, 0.0109133, 0.963867, 0.0000386401, 0, 0.0166927, 0.95982, 0.0000462827, 0, 0.0238494, 0.953497, 0.0000420705, 0, 0.0324178, 0.947621, 0.0000477743, 0, 0.0424225, 0.940611, 0.0000568258, 0, 0.0538808, 0.931174, 0.0000618061, 0, 0.0668047, 0.919919, 0.0000627098, 0, 0.0812014, 0.907856, 0.0000694714, 0, 0.0970745, 0.894509, 0.0000735008, 0, 0.114424, 0.881954, 0.0000763369, 0, 0.133246, 0.868309, 0.0000821896, 0, 0.153534, 0.852511, 0.000083769, 0, 0.175275, 0.835821, 0.0000881615, 0, 0.198453, 0.817981, 0.0000896368, 0, 0.223042, 0.800504, 0.0000930906, 0, 0.249009, 0.78141, 0.0000945056, 0, 0.276304, 0.761427, 0.0000963605, 0, 0.304862, 0.74094, 0.0000968088, 0, 0.334584, 0.720233, 0.0000981481, 0, 0.365322, 0.698592, 0.0000979122, 0, 0.396826, 0.676763, 0.0000981057, 0, 0.428571, 0.654808, 0.0000973956, 0, 0.460318, 0.632326, 0.0000962619, 0, 0.492064, 0.610049, 0.0000952996, 0, 0.52381, 0.58763, 0.0000933334, 0, 0.555556, 0.565261, 0.0000917573, 0, 0.587302, 0.543244, 0.0000896636, 0, 0.619048, 0.521273, 0.0000873304, 0, 0.650794, 0.499818, 0.0000852648, 0, 0.68254, 0.478536, 0.0000823961, 0, 0.714286, 0.457826, 0.000079939, 0, 0.746032, 0.437549, 0.000077126, 0, 0.777778, 0.41776, 0.0000743043, 0, 0.809524, 0.39863, 0.0000716426, 0, 0.84127, 0.379954, 0.0000686456, 0, 0.873016, 0.362025, 0.0000660514, 0, 0.904762, 0.344581, 0.0000630755, 0, 0.936508, 0.327909, 0.0000605439, 0, 0.968254, 0.311736, 0.0000576345, 0, 1, 1, 0.0000000263344, 0, 0, 1, 0.0000000263373, 0, 0, 1, 0.0000000263815, 0, 0, 1, 0.0000000265753, 0, 0, 1, 0.0000000271132, 0, 0, 0.999999, 0.0000000283279, 0, 0, 0.999997, 0.000000030833, 0, 0, 0.999995, 0.0000000358711, 0, 0, 0.999992, 0.0000000461266, 0, 0, 0.999985, 0.000000067574, 0, 0, 0.999977, 0.00000011358, 0, 0, 0.999966, 0.000000213657, 0, 0, 0.999948, 0.000000431151, 0, 0, 0.999923, 0.000000896656, 0, 0, 0.999884, 0.00000186603, 0, 0, 0.999826, 0.00000381115, 0, 0, 0.999732, 0.00000754184, 0, 0, 0.999561, 0.0000143192, 0, 0, 0.999191, 0.0000257061, 0, 0, 0.997955, 0.0000405724, 0, 0.0000744132, 0.992228, 0.0000276537, 0, 0.000716477, 0.987638, 0.0000208885, 0, 0.0022524, 0.983395, 0.0000215226, 0, 0.00484816, 0.978614, 0.0000270795, 0, 0.00860962, 0.972389, 0.0000365282, 0, 0.0136083, 0.964392, 0.0000474747, 0, 0.0198941, 0.95861, 0.0000509141, 0, 0.0275023, 0.952806, 0.000048963, 0, 0.0364584, 0.94712, 0.0000571119, 0, 0.04678, 0.940104, 0.0000671704, 0, 0.0584799, 0.930398, 0.0000687586, 0, 0.0715665, 0.919866, 0.0000738161, 0, 0.086045, 0.907853, 0.0000813235, 0, 0.101918, 0.894078, 0.0000834582, 0, 0.119186, 0.881177, 0.0000892093, 0, 0.137845, 0.867575, 0.0000944548, 0, 0.157891, 0.852107, 0.0000969607, 0, 0.179316, 0.835502, 0.000101456, 0, 0.202106, 0.81756, 0.000103256, 0, 0.226243, 0.79984, 0.000106954, 0, 0.251704, 0.780998, 0.000108066, 0, 0.278451, 0.761132, 0.000110111, 0, 0.306436, 0.740429, 0.000110459, 0, 0.335586, 0.719836, 0.000111219, 0, 0.365796, 0.698467, 0.00011145, 0, 0.3969, 0.676446, 0.000110393, 0, 0.428571, 0.654635, 0.000110035, 0, 0.460318, 0.632411, 0.000108548, 0, 0.492064, 0.609986, 0.000106963, 0, 0.52381, 0.587872, 0.000105238, 0, 0.555556, 0.565528, 0.000102665, 0, 0.587302, 0.543563, 0.000100543, 0, 0.619048, 0.52176, 0.0000976182, 0, 0.650794, 0.500188, 0.0000947099, 0, 0.68254, 0.479204, 0.0000919929, 0, 0.714286, 0.458413, 0.0000886139, 0, 0.746032, 0.438314, 0.0000857839, 0, 0.777778, 0.418573, 0.000082411, 0, 0.809524, 0.39947, 0.0000792211, 0, 0.84127, 0.380892, 0.0000759546, 0, 0.873016, 0.362953, 0.0000727571, 0, 0.904762, 0.345601, 0.0000695738, 0, 0.936508, 0.328895, 0.0000664907, 0, 0.968254, 0.312808, 0.0000634277, 0, 1, 1, 0.0000000628647, 0, 0, 1, 0.0000000628705, 0, 0, 1, 0.0000000629587, 0, 0, 1, 0.0000000633441, 0, 0, 0.999999, 0.0000000644087, 0, 0, 0.999998, 0.0000000667856, 0, 0, 0.999997, 0.0000000715889, 0, 0, 0.999995, 0.0000000809577, 0, 0, 0.999989, 0.0000000992764, 0, 0, 0.999983, 0.000000135834, 0, 0, 0.999974, 0.000000210482, 0, 0, 0.999959, 0.000000365215, 0, 0, 0.999939, 0.000000686693, 0, 0, 0.999911, 0.0000013472, 0, 0, 0.999868, 0.0000026731, 0, 0, 0.999804, 0.00000524756, 0, 0, 0.9997, 0.0000100403, 0, 0, 0.99951, 0.0000185019, 0, 0, 0.999078, 0.0000322036, 0, 0.00000620676, 0.997428, 0.0000470002, 0, 0.000341552, 0.99162, 0.0000287123, 0, 0.00143727, 0.987479, 0.0000234706, 0, 0.00349201, 0.983582, 0.0000260083, 0, 0.0066242, 0.979186, 0.0000337927, 0, 0.0109113, 0.97325, 0.0000454689, 0, 0.0164064, 0.965221, 0.0000573759, 0, 0.0231463, 0.957262, 0.0000544114, 0, 0.0311571, 0.952211, 0.0000587006, 0, 0.0404572, 0.946631, 0.0000692256, 0, 0.0510592, 0.939391, 0.0000787819, 0, 0.0629723, 0.929795, 0.0000792368, 0, 0.0762025, 0.91965, 0.0000875075, 0, 0.090753, 0.907737, 0.0000950903, 0, 0.106626, 0.893899, 0.0000972963, 0, 0.123822, 0.880239, 0.00010459, 0, 0.142337, 0.866562, 0.000107689, 0, 0.16217, 0.85164, 0.000113081, 0, 0.183314, 0.835021, 0.000116636, 0, 0.20576, 0.817311, 0.000120074, 0, 0.229496, 0.798845, 0.000121921, 0, 0.254502, 0.780479, 0.00012475, 0, 0.280753, 0.760694, 0.000125255, 0, 0.308212, 0.740142, 0.000126719, 0, 0.336825, 0.719248, 0.00012636, 0, 0.366517, 0.698209, 0.000126712, 0, 0.397167, 0.676398, 0.000125769, 0, 0.428578, 0.654378, 0.000124432, 0, 0.460318, 0.632484, 0.000123272, 0, 0.492064, 0.610113, 0.00012085, 0, 0.52381, 0.587931, 0.000118411, 0, 0.555556, 0.565872, 0.00011569, 0, 0.587302, 0.543814, 0.000112521, 0, 0.619048, 0.522265, 0.000109737, 0, 0.650794, 0.500835, 0.000106228, 0, 0.68254, 0.479818, 0.000102591, 0, 0.714286, 0.459258, 0.0000991288, 0, 0.746032, 0.439061, 0.0000952325, 0, 0.777778, 0.419552, 0.000091895, 0, 0.809524, 0.400399, 0.0000879051, 0, 0.84127, 0.381976, 0.0000844775, 0, 0.873016, 0.364009, 0.0000806316, 0, 0.904762, 0.346761, 0.0000771848, 0, 0.936508, 0.330049, 0.0000735429, 0, 0.968254, 0.314018, 0.0000702103, 0, 1, 1, 0.000000139968, 0, 0, 1, 0.000000139979, 0, 0, 1, 0.000000140145, 0, 0, 1, 0.00000014087, 0, 0, 0.999999, 0.000000142865, 0, 0, 0.999998, 0.000000147279, 0, 0, 0.999997, 0.000000156057, 0, 0, 0.999992, 0.00000017276, 0, 0, 0.999989, 0.000000204352, 0, 0, 0.99998, 0.00000026494, 0, 0, 0.999969, 0.000000383435, 0, 0, 0.999953, 0.000000618641, 0, 0, 0.999929, 0.00000108755, 0, 0, 0.999898, 0.00000201497, 0, 0, 0.999849, 0.00000381346, 0, 0, 0.999778, 0.00000719815, 0, 0, 0.999661, 0.0000133215, 0, 0, 0.999451, 0.0000238313, 0, 0, 0.998936, 0.0000401343, 0, 0.000113724, 0.99662, 0.0000517346, 0, 0.000820171, 0.991094, 0.0000304323, 0, 0.00238143, 0.987487, 0.0000281757, 0, 0.00493527, 0.983731, 0.0000320048, 0, 0.00856859, 0.979647, 0.0000423905, 0, 0.0133393, 0.973837, 0.0000562935, 0, 0.0192863, 0.96584, 0.0000677442, 0, 0.0264369, 0.956309, 0.0000623073, 0, 0.03481, 0.951523, 0.0000704131, 0, 0.0444184, 0.946003, 0.0000836594, 0, 0.0552713, 0.938454, 0.0000911736, 0, 0.0673749, 0.929279, 0.0000938264, 0, 0.0807329, 0.919239, 0.000103754, 0, 0.0953479, 0.907293, 0.000109928, 0, 0.111221, 0.893936, 0.000115257, 0, 0.128352, 0.879674, 0.000122265, 0, 0.14674, 0.865668, 0.000125733, 0, 0.166382, 0.850998, 0.000132305, 0, 0.187276, 0.834498, 0.000134844, 0, 0.209413, 0.816903, 0.000139276, 0, 0.232786, 0.798235, 0.000140984, 0, 0.257382, 0.779724, 0.00014378, 0, 0.283181, 0.760251, 0.000144623, 0, 0.310156, 0.739808, 0.000145228, 0, 0.338269, 0.718762, 0.00014539, 0, 0.367461, 0.697815, 0.000144432, 0, 0.397646, 0.67631, 0.000143893, 0, 0.428685, 0.654278, 0.000141846, 0, 0.460318, 0.632347, 0.00013935, 0, 0.492064, 0.610296, 0.000137138, 0, 0.52381, 0.588039, 0.000133806, 0, 0.555556, 0.566218, 0.000130755, 0, 0.587302, 0.544346, 0.000127128, 0, 0.619048, 0.522701, 0.000123002, 0, 0.650794, 0.501542, 0.000119443, 0, 0.68254, 0.480508, 0.000115055, 0, 0.714286, 0.460092, 0.000111032, 0, 0.746032, 0.440021, 0.000106635, 0, 0.777778, 0.420446, 0.000102162, 0, 0.809524, 0.401512, 0.000098184, 0, 0.84127, 0.38299, 0.0000936497, 0, 0.873016, 0.365232, 0.000089813, 0, 0.904762, 0.347865, 0.0000853073, 0, 0.936508, 0.331342, 0.0000817068, 0, 0.968254, 0.315202, 0.0000773818, 0, 1, 1, 0.00000029368, 0, 0, 1, 0.0000002937, 0, 0, 1, 0.000000293998, 0, 0, 1, 0.000000295298, 0, 0, 0.999999, 0.000000298865, 0, 0, 0.999998, 0.0000003067, 0, 0, 0.999995, 0.000000322082, 0, 0, 0.999992, 0.000000350767, 0, 0, 0.999986, 0.000000403538, 0, 0, 0.999976, 0.000000501372, 0, 0, 0.999964, 0.00000068562, 0, 0, 0.999945, 0.0000010374, 0, 0, 0.999919, 0.00000171269, 0, 0, 0.999882, 0.00000300175, 0, 0, 0.999829, 0.00000542144, 0, 0, 0.999749, 0.00000984182, 0, 0, 0.99962, 0.0000176213, 0, 0, 0.999382, 0.0000305995, 0, 0.0000138418, 0.998751, 0.0000496686, 0, 0.000389844, 0.995344, 0.0000510733, 0, 0.00150343, 0.990768, 0.0000345829, 0, 0.00352451, 0.987464, 0.0000342841, 0, 0.00655379, 0.983846, 0.0000399072, 0, 0.0106554, 0.980007, 0.0000533219, 0, 0.0158723, 0.974494, 0.0000696992, 0, 0.0222333, 0.96622, 0.0000776754, 0, 0.029758, 0.956273, 0.0000747718, 0, 0.0384596, 0.950952, 0.0000864611, 0, 0.0483473, 0.945215, 0.000100464, 0, 0.0594266, 0.937287, 0.000103729, 0, 0.0717019, 0.928649, 0.000111665, 0, 0.0851752, 0.918791, 0.00012353, 0, 0.0998479, 0.906685, 0.000127115, 0, 0.115721, 0.893706, 0.00013628, 0, 0.132794, 0.879248, 0.000142427, 0, 0.151067, 0.864685, 0.000148091, 0, 0.170538, 0.850032, 0.000153517, 0, 0.191204, 0.833853, 0.000157322, 0, 0.213063, 0.816353, 0.000161086, 0, 0.236107, 0.797834, 0.000164111, 0, 0.260329, 0.778831, 0.000165446, 0, 0.285714, 0.759756, 0.000167492, 0, 0.312243, 0.739419, 0.000166928, 0, 0.339887, 0.718491, 0.000167, 0, 0.368604, 0.697392, 0.000165674, 0, 0.398329, 0.676102, 0.000163815, 0, 0.428961, 0.654243, 0.000162003, 0, 0.460331, 0.632176, 0.000158831, 0, 0.492064, 0.610407, 0.000155463, 0, 0.52381, 0.588394, 0.000152062, 0, 0.555556, 0.56645, 0.000147665, 0, 0.587302, 0.5449, 0.00014375, 0, 0.619048, 0.523276, 0.000138905, 0, 0.650794, 0.502179, 0.000134189, 0, 0.68254, 0.481359, 0.000129392, 0, 0.714286, 0.46092, 0.000124556, 0, 0.746032, 0.441084, 0.00011957, 0, 0.777778, 0.421517, 0.000114652, 0, 0.809524, 0.402721, 0.000109688, 0, 0.84127, 0.384222, 0.000104667, 0, 0.873016, 0.366534, 0.0000999633, 0, 0.904762, 0.349205, 0.0000950177, 0, 0.936508, 0.332702, 0.0000907301, 0, 0.968254, 0.316599, 0.0000859769, 0, 1, 1, 0.000000585473, 0, 0, 1, 0.000000585507, 0, 0, 1, 0.00000058602, 0, 0, 0.999999, 0.000000588259, 0, 0, 0.999999, 0.000000594381, 0, 0, 0.999998, 0.000000607754, 0, 0, 0.999995, 0.000000633729, 0, 0, 0.99999, 0.00000068137, 0, 0, 0.999984, 0.000000767003, 0, 0, 0.999973, 0.000000921212, 0, 0, 0.999959, 0.00000120218, 0, 0, 0.999936, 0.00000172024, 0, 0, 0.999907, 0.00000268088, 0, 0, 0.999866, 0.00000445512, 0, 0, 0.999806, 0.00000768481, 0, 0, 0.999716, 0.00001342, 0, 0, 0.999576, 0.0000232473, 0, 0, 0.9993, 0.0000391694, 0, 0.000129917, 0.998498, 0.0000608429, 0, 0.000845035, 0.994132, 0.0000489743, 0, 0.00237616, 0.99031, 0.0000384644, 0, 0.00484456, 0.987409, 0.0000421768, 0, 0.00832472, 0.983981, 0.0000504854, 0, 0.0128643, 0.980268, 0.0000671028, 0, 0.0184947, 0.974875, 0.0000852749, 0, 0.025237, 0.966063, 0.000085531, 0, 0.0331046, 0.956779, 0.0000900588, 0, 0.0421067, 0.950259, 0.00010577, 0, 0.0522487, 0.944239, 0.000119458, 0, 0.0635343, 0.936341, 0.000122164, 0, 0.0759654, 0.928047, 0.000134929, 0, 0.0895434, 0.918065, 0.000145544, 0, 0.104269, 0.906267, 0.000150531, 0, 0.120142, 0.893419, 0.000161652, 0, 0.137163, 0.878758, 0.00016593, 0, 0.15533, 0.863699, 0.000174014, 0, 0.174645, 0.848876, 0.000177877, 0, 0.195106, 0.833032, 0.000184049, 0, 0.21671, 0.815557, 0.000186088, 0, 0.239454, 0.797323, 0.00019054, 0, 0.263332, 0.778124, 0.000191765, 0, 0.288336, 0.758929, 0.000192535, 0, 0.314451, 0.738979, 0.000192688, 0, 0.341658, 0.718213, 0.000191522, 0, 0.369924, 0.696947, 0.000190491, 0, 0.399202, 0.675807, 0.000187913, 0, 0.429416, 0.654147, 0.000184451, 0, 0.460447, 0.63229, 0.000181442, 0, 0.492064, 0.610499, 0.000177139, 0, 0.523809, 0.588747, 0.000172596, 0, 0.555555, 0.566783, 0.000167457, 0, 0.587301, 0.545359, 0.000162518, 0, 0.619048, 0.523984, 0.000156818, 0, 0.650794, 0.502917, 0.000151884, 0, 0.68254, 0.482294, 0.000145514, 0, 0.714286, 0.461945, 0.000140199, 0, 0.746032, 0.442133, 0.000134101, 0, 0.777778, 0.422705, 0.000128374, 0, 0.809524, 0.403916, 0.000122996, 0, 0.84127, 0.38554, 0.000116808, 0, 0.873016, 0.367909, 0.000111973, 0, 0.904762, 0.350651, 0.000105938, 0, 0.936508, 0.334208, 0.000101355, 0, 0.968254, 0.318123, 0.0000957629, 0, 1, 1, 0.00000111633, 0, 0, 1, 0.00000111639, 0, 0, 1, 0.00000111725, 0, 0, 1, 0.00000112096, 0, 0, 0.999999, 0.0000011311, 0, 0, 0.999997, 0.00000115315, 0, 0, 0.999995, 0.0000011956, 0, 0, 0.999989, 0.00000127239, 0, 0, 0.999981, 0.00000140772, 0, 0, 0.999969, 0.00000164541, 0, 0, 0.999952, 0.00000206607, 0, 0, 0.999928, 0.00000281783, 0, 0, 0.999895, 0.00000416835, 0, 0, 0.999848, 0.00000658728, 0, 0, 0.999781, 0.0000108648, 0, 0, 0.999682, 0.0000182579, 0, 0, 0.999523, 0.0000306003, 0, 0.0000159122, 0.999205, 0.0000499862, 0, 0.000391184, 0.998131, 0.000073306, 0, 0.00147534, 0.993334, 0.0000513229, 0, 0.0034227, 0.99016, 0.0000467783, 0, 0.00632232, 0.987321, 0.0000523413, 0, 0.0102295, 0.984099, 0.000064267, 0, 0.0151794, 0.980432, 0.0000843042, 0, 0.0211947, 0.974976, 0.000102819, 0, 0.0282899, 0.966429, 0.0000996234, 0, 0.0364739, 0.957633, 0.000111074, 0, 0.0457522, 0.949422, 0.000128644, 0, 0.0561278, 0.943045, 0.000140076, 0, 0.0676023, 0.935448, 0.000146349, 0, 0.0801762, 0.927225, 0.000161854, 0, 0.0938499, 0.917033, 0.000169135, 0, 0.108623, 0.905762, 0.000179987, 0, 0.124496, 0.892879, 0.000189832, 0, 0.141469, 0.878435, 0.000195881, 0, 0.159541, 0.863114, 0.00020466, 0, 0.178713, 0.84776, 0.000209473, 0, 0.198985, 0.832084, 0.000214861, 0, 0.220355, 0.814915, 0.000217695, 0, 0.242823, 0.796711, 0.000220313, 0, 0.266385, 0.777603, 0.00022313, 0, 0.291036, 0.757991, 0.000222471, 0, 0.316767, 0.738371, 0.000222869, 0, 0.343563, 0.717872, 0.000221243, 0, 0.371402, 0.696619, 0.000218089, 0, 0.400248, 0.675379, 0.00021562, 0, 0.430047, 0.65411, 0.00021169, 0, 0.460709, 0.63241, 0.000206947, 0, 0.492079, 0.61046, 0.000201709, 0, 0.52381, 0.58903, 0.000196753, 0, 0.555556, 0.567267, 0.000189637, 0, 0.587302, 0.545886, 0.000184735, 0, 0.619048, 0.524714, 0.000177257, 0, 0.650794, 0.503789, 0.000171424, 0, 0.68254, 0.483204, 0.000164688, 0, 0.714286, 0.462976, 0.000157172, 0, 0.746032, 0.443294, 0.000151341, 0, 0.777778, 0.423988, 0.000143737, 0, 0.809524, 0.405325, 0.000138098, 0, 0.84127, 0.386981, 0.000130698, 0, 0.873016, 0.369436, 0.000125276, 0, 0.904762, 0.35219, 0.000118349, 0, 0.936508, 0.335804, 0.00011312, 0, 0.968254, 0.319749, 0.000106687, 0, 1, 1, 0.00000204685, 0, 0, 1, 0.00000204694, 0, 0, 1, 0.00000204831, 0, 0, 0.999999, 0.00000205428, 0, 0, 0.999999, 0.00000207056, 0, 0, 0.999997, 0.00000210581, 0, 0, 0.999993, 0.0000021732, 0, 0, 0.999987, 0.00000229365, 0, 0, 0.999979, 0.00000250243, 0, 0, 0.999965, 0.00000286127, 0, 0, 0.999947, 0.00000348028, 0, 0, 0.999918, 0.00000455588, 0, 0, 0.999881, 0.00000643303, 0, 0, 0.999828, 0.00000970064, 0, 0, 0.999753, 0.0000153233, 0, 0, 0.999642, 0.000024793, 0, 0, 0.999464, 0.0000402032, 0, 0.000122947, 0.999089, 0.0000635852, 0, 0.000807414, 0.997567, 0.0000857026, 0, 0.00227206, 0.992903, 0.0000594912, 0, 0.00462812, 0.990011, 0.0000578515, 0, 0.00794162, 0.987192, 0.000065399, 0, 0.0122534, 0.98418, 0.0000819675, 0, 0.0175888, 0.980491, 0.000105514, 0, 0.0239635, 0.974779, 0.000121532, 0, 0.031387, 0.96675, 0.000119144, 0, 0.0398644, 0.958248, 0.000136125, 0, 0.0493982, 0.948884, 0.000155408, 0, 0.0599896, 0.941673, 0.000162281, 0, 0.0716382, 0.934521, 0.000176754, 0, 0.0843437, 0.926205, 0.000192873, 0, 0.0981056, 0.916089, 0.000200038, 0, 0.112923, 0.904963, 0.000213624, 0, 0.128796, 0.892089, 0.000221834, 0, 0.145725, 0.878028, 0.000232619, 0, 0.163709, 0.86249, 0.000238632, 0, 0.182749, 0.846587, 0.000247002, 0, 0.202847, 0.830988, 0.000250702, 0, 0.224001, 0.814165, 0.000255562, 0, 0.246214, 0.796135, 0.000257505, 0, 0.269482, 0.777052, 0.000258625, 0, 0.293805, 0.757201, 0.000258398, 0, 0.319176, 0.737655, 0.000256714, 0, 0.345587, 0.717477, 0.000255187, 0, 0.373021, 0.696433, 0.000251792, 0, 0.401454, 0.675084, 0.000247223, 0, 0.430844, 0.653907, 0.000242213, 0, 0.461125, 0.632561, 0.000237397, 0, 0.492187, 0.610658, 0.000229313, 0, 0.52381, 0.589322, 0.000224402, 0, 0.555556, 0.567857, 0.000216116, 0, 0.587302, 0.54652, 0.000209124, 0, 0.619048, 0.525433, 0.000201601, 0, 0.650794, 0.504679, 0.000192957, 0, 0.68254, 0.484203, 0.000186052, 0, 0.714286, 0.464203, 0.000177672, 0, 0.746032, 0.444549, 0.000170005, 0, 0.777778, 0.425346, 0.000162401, 0, 0.809524, 0.406706, 0.0001544, 0, 0.84127, 0.388576, 0.000147437, 0, 0.873016, 0.37094, 0.000139493, 0, 0.904762, 0.353996, 0.000133219, 0, 0.936508, 0.337391, 0.000125573, 0, 0.968254, 0.321648, 0.000119867, 0, 1, 1, 0.00000362511, 0, 0, 1, 0.00000362525, 0, 0, 1, 0.00000362739, 0, 0, 0.999999, 0.00000363673, 0, 0, 0.999998, 0.00000366214, 0, 0, 0.999996, 0.00000371698, 0, 0, 0.999992, 0.00000382116, 0, 0, 0.999986, 0.00000400554, 0, 0, 0.999976, 0.00000432058, 0, 0, 0.999961, 0.00000485194, 0, 0, 0.999938, 0.00000574808, 0, 0, 0.999908, 0.00000726643, 0, 0, 0.999865, 0.00000984707, 0, 0, 0.999807, 0.0000142217, 0, 0, 0.999723, 0.0000215581, 0, 0, 0.999602, 0.0000336114, 0, 0.0000119113, 0.999398, 0.0000527353, 0, 0.000355813, 0.998946, 0.0000805809, 0, 0.00137768, 0.996647, 0.0000942908, 0, 0.00322469, 0.992298, 0.0000668733, 0, 0.00597897, 0.989802, 0.0000716564, 0, 0.00968903, 0.987019, 0.0000821355, 0, 0.0143845, 0.984219, 0.000104555, 0, 0.0200831, 0.980425, 0.000131245, 0, 0.0267948, 0.974241, 0.000139613, 0, 0.034525, 0.967006, 0.000145931, 0, 0.0432757, 0.95893, 0.000167153, 0, 0.0530471, 0.949157, 0.000188146, 0, 0.0638386, 0.94062, 0.000194625, 0, 0.0756487, 0.933509, 0.000213721, 0, 0.0884762, 0.925088, 0.000229616, 0, 0.10232, 0.915178, 0.000239638, 0, 0.117178, 0.904093, 0.000254814, 0, 0.133051, 0.891337, 0.000263685, 0, 0.149939, 0.877326, 0.000274789, 0, 0.167841, 0.861794, 0.000280534, 0, 0.18676, 0.845758, 0.000289534, 0, 0.206696, 0.829792, 0.000294446, 0, 0.22765, 0.813037, 0.000296877, 0, 0.249625, 0.795285, 0.000300217, 0, 0.27262, 0.776323, 0.000299826, 0, 0.296636, 0.756673, 0.000299787, 0, 0.321671, 0.736856, 0.000297867, 0, 0.347718, 0.716883, 0.000294052, 0, 0.374768, 0.696089, 0.000289462, 0, 0.402804, 0.67505, 0.000285212, 0, 0.431796, 0.653509, 0.00027653, 0, 0.461695, 0.63258, 0.000271759, 0, 0.49242, 0.61104, 0.000262811, 0, 0.523822, 0.589567, 0.000255151, 0, 0.555556, 0.568322, 0.000246434, 0, 0.587302, 0.547235, 0.000237061, 0, 0.619048, 0.52616, 0.000228343, 0, 0.650794, 0.505716, 0.000219236, 0, 0.68254, 0.485274, 0.000209595, 0, 0.714286, 0.465411, 0.000201011, 0, 0.746032, 0.445854, 0.00019109, 0, 0.777778, 0.426911, 0.000182897, 0, 0.809524, 0.408222, 0.000173569, 0, 0.84127, 0.390307, 0.000165496, 0, 0.873016, 0.372624, 0.000156799, 0, 0.904762, 0.355804, 0.00014917, 0, 0.936508, 0.33924, 0.000140907, 0, 0.968254, 0.323534, 0.000134062, 0, 1, 1, 0.00000622487, 0, 0, 1, 0.0000062251, 0, 0, 1, 0.00000622837, 0, 0, 0.999999, 0.00000624259, 0, 0, 0.999998, 0.00000628127, 0, 0, 0.999996, 0.00000636451, 0, 0, 0.999991, 0.0000065218, 0, 0, 0.999984, 0.00000679782, 0, 0, 0.999973, 0.00000726361, 0, 0, 0.999955, 0.00000803644, 0, 0, 0.999931, 0.00000931397, 0, 0, 0.999896, 0.0000114299, 0, 0, 0.999847, 0.0000149402, 0, 0, 0.999784, 0.0000207461, 0, 0, 0.999692, 0.0000302493, 0, 0, 0.999554, 0.0000454957, 0, 0.0000997275, 0.999326, 0.0000690762, 0, 0.000724813, 0.998757, 0.000101605, 0, 0.0020972, 0.995367, 0.0000958745, 0, 0.00432324, 0.99209, 0.0000832808, 0, 0.00746347, 0.989517, 0.0000887601, 0, 0.0115534, 0.987008, 0.00010564, 0, 0.0166134, 0.98421, 0.000133179, 0, 0.0226552, 0.98021, 0.000161746, 0, 0.0296838, 0.973676, 0.000161821, 0, 0.0377016, 0.967052, 0.000178635, 0, 0.0467079, 0.959385, 0.000206765, 0, 0.0567013, 0.949461, 0.00022476, 0, 0.0676796, 0.939578, 0.00023574, 0, 0.0796403, 0.932416, 0.00025893, 0, 0.0925812, 0.923759, 0.000271228, 0, 0.106501, 0.914223, 0.000289165, 0, 0.121397, 0.902942, 0.000301156, 0, 0.13727, 0.890419, 0.000313852, 0, 0.15412, 0.876639, 0.000324408, 0, 0.171946, 0.861316, 0.00033249, 0, 0.190751, 0.84496, 0.000338497, 0, 0.210537, 0.828427, 0.000345861, 0, 0.231305, 0.811871, 0.000347863, 0, 0.253057, 0.794397, 0.000350225, 0, 0.275797, 0.775726, 0.000349915, 0, 0.299525, 0.75617, 0.000347297, 0, 0.324242, 0.736091, 0.000344232, 0, 0.349947, 0.716213, 0.000340835, 0, 0.376633, 0.695736, 0.000332369, 0, 0.404289, 0.674961, 0.000327943, 0, 0.432895, 0.653518, 0.000318533, 0, 0.462415, 0.632574, 0.000310391, 0, 0.492788, 0.61134, 0.000300755, 0, 0.523909, 0.590017, 0.000290506, 0, 0.555556, 0.568752, 0.000280446, 0, 0.587302, 0.548061, 0.000269902, 0, 0.619048, 0.52711, 0.000258815, 0, 0.650794, 0.506682, 0.000248481, 0, 0.68254, 0.486524, 0.000237141, 0, 0.714286, 0.466812, 0.000226872, 0, 0.746032, 0.44732, 0.000216037, 0, 0.777778, 0.428473, 0.000205629, 0, 0.809524, 0.409921, 0.000195691, 0, 0.84127, 0.392028, 0.000185457, 0, 0.873016, 0.374606, 0.000176436, 0, 0.904762, 0.357601, 0.000166508, 0, 0.936508, 0.341348, 0.000158385, 0, 0.968254, 0.32542, 0.000149203, 0, 1, 1, 0.0000103967, 0, 0, 1, 0.000010397, 0, 0, 1, 0.0000104019, 0, 0, 0.999999, 0.0000104231, 0, 0, 0.999998, 0.0000104806, 0, 0, 0.999995, 0.0000106042, 0, 0, 0.999991, 0.0000108366, 0, 0, 0.999982, 0.0000112415, 0, 0, 0.999968, 0.0000119174, 0, 0, 0.99995, 0.0000130227, 0, 0, 0.999922, 0.0000148176, 0, 0, 0.999884, 0.0000177303, 0, 0, 0.99983, 0.0000224564, 0, 0, 0.999758, 0.0000300966, 0, 0, 0.999654, 0.0000423193, 0, 0.00000549083, 0.999503, 0.0000614848, 0, 0.000296087, 0.999237, 0.0000903576, 0, 0.00123144, 0.998491, 0.0001271, 0, 0.00295954, 0.994594, 0.000107754, 0, 0.00555829, 0.99178, 0.000103025, 0, 0.00907209, 0.989265, 0.00011154, 0, 0.0135257, 0.986998, 0.000136296, 0, 0.0189327, 0.984137, 0.000169154, 0, 0.0252993, 0.979798, 0.000196671, 0, 0.0326272, 0.97337, 0.000196678, 0, 0.0409157, 0.967239, 0.000223121, 0, 0.0501623, 0.959543, 0.000253809, 0, 0.0603638, 0.949466, 0.000265972, 0, 0.0715171, 0.939074, 0.000288372, 0, 0.0836187, 0.931118, 0.000310983, 0, 0.0966657, 0.922525, 0.000325561, 0, 0.110656, 0.912983, 0.000345725, 0, 0.125588, 0.901617, 0.0003556, 0, 0.141461, 0.889487, 0.000374012, 0, 0.158275, 0.875787, 0.000383445, 0, 0.176031, 0.860654, 0.000393972, 0, 0.19473, 0.844417, 0.000400311, 0, 0.214374, 0.82741, 0.000405004, 0, 0.234967, 0.810545, 0.000407378, 0, 0.256512, 0.793312, 0.000407351, 0, 0.279011, 0.774847, 0.000406563, 0, 0.302468, 0.755621, 0.000404903, 0, 0.326887, 0.735511, 0.000397486, 0, 0.352266, 0.715435, 0.00039357, 0, 0.378605, 0.695403, 0.000384739, 0, 0.405897, 0.674681, 0.000376108, 0, 0.43413, 0.65359, 0.000365997, 0, 0.463277, 0.632471, 0.000354957, 0, 0.493295, 0.61151, 0.000343593, 0, 0.524106, 0.59064, 0.000331841, 0, 0.555561, 0.569386, 0.000318891, 0, 0.587302, 0.548785, 0.0003072, 0, 0.619048, 0.528146, 0.00029361, 0, 0.650794, 0.507872, 0.000281709, 0, 0.68254, 0.487805, 0.000268627, 0, 0.714286, 0.468196, 0.000255887, 0, 0.746032, 0.448922, 0.000243997, 0, 0.777778, 0.430093, 0.000231662, 0, 0.809524, 0.411845, 0.000220339, 0, 0.84127, 0.393808, 0.000208694, 0, 0.873016, 0.376615, 0.000198045, 0, 0.904762, 0.359655, 0.000187375, 0, 0.936508, 0.343452, 0.000177371, 0, 0.968254, 0.32765, 0.000167525, 0, 1, 1, 0.0000169351, 0, 0, 1, 0.0000169356, 0, 0, 1, 0.0000169427, 0, 0, 0.999999, 0.0000169736, 0, 0, 0.999998, 0.0000170575, 0, 0, 0.999995, 0.0000172372, 0, 0, 0.99999, 0.0000175739, 0, 0, 0.999979, 0.0000181568, 0, 0, 0.999966, 0.0000191206, 0, 0, 0.999944, 0.000020677, 0, 0, 0.999912, 0.0000231644, 0, 0, 0.999869, 0.0000271268, 0, 0, 0.999811, 0.0000334272, 0, 0, 0.99973, 0.0000433979, 0, 0, 0.999617, 0.0000590083, 0, 0.0000680315, 0.999445, 0.0000829497, 0, 0.000612796, 0.999138, 0.000118019, 0, 0.00187408, 0.998095, 0.000156712, 0, 0.00395791, 0.993919, 0.000125054, 0, 0.00692144, 0.991333, 0.000126091, 0, 0.0107962, 0.989226, 0.000144912, 0, 0.0155986, 0.986954, 0.000175737, 0, 0.0213364, 0.983982, 0.000213883, 0, 0.0280114, 0.979128, 0.000234526, 0, 0.0356226, 0.973327, 0.000243725, 0, 0.0441668, 0.967416, 0.0002773, 0, 0.0536399, 0.959729, 0.000308799, 0, 0.0640376, 0.949758, 0.000322447, 0, 0.0753554, 0.939173, 0.000350021, 0, 0.0875893, 0.9296, 0.000370089, 0, 0.100736, 0.921181, 0.000391365, 0, 0.114793, 0.91164, 0.000413636, 0, 0.129759, 0.900435, 0.000427068, 0, 0.145632, 0.888183, 0.000441046, 0, 0.162412, 0.874772, 0.000454968, 0, 0.180101, 0.859566, 0.000461882, 0, 0.1987, 0.843579, 0.000471556, 0, 0.218213, 0.826453, 0.000474335, 0, 0.238641, 0.809164, 0.000477078, 0, 0.259989, 0.792179, 0.00047755, 0, 0.282262, 0.773866, 0.000472573, 0, 0.305464, 0.754944, 0.000469765, 0, 0.329599, 0.735133, 0.000462371, 0, 0.35467, 0.714858, 0.000453674, 0, 0.380678, 0.694829, 0.000443888, 0, 0.407622, 0.674453, 0.000432052, 0, 0.435493, 0.653685, 0.000420315, 0, 0.464275, 0.632666, 0.000406829, 0, 0.493938, 0.611676, 0.000392234, 0, 0.524422, 0.591193, 0.000379208, 0, 0.555624, 0.570145, 0.00036319, 0, 0.587302, 0.549566, 0.000349111, 0, 0.619048, 0.529278, 0.000334166, 0, 0.650794, 0.509026, 0.000318456, 0, 0.68254, 0.489186, 0.00030449, 0, 0.714286, 0.469662, 0.000289051, 0, 0.746032, 0.450691, 0.000275494, 0, 0.777778, 0.431841, 0.000261437, 0, 0.809524, 0.413752, 0.000247846, 0, 0.84127, 0.395951, 0.000235085, 0, 0.873016, 0.378633, 0.000222245, 0, 0.904762, 0.36194, 0.000210533, 0, 0.936508, 0.345599, 0.000198494, 0, 0.968254, 0.329999, 0.000188133, 0, 1, 1, 0.0000269663, 0, 0, 1, 0.000026967, 0, 0, 1, 0.0000269772, 0, 0, 0.999999, 0.0000270214, 0, 0, 0.999998, 0.0000271415, 0, 0, 0.999994, 0.000027398, 0, 0, 0.999988, 0.0000278771, 0, 0, 0.999977, 0.0000287019, 0, 0, 0.999961, 0.0000300544, 0, 0, 0.999937, 0.0000322138, 0, 0, 0.999904, 0.0000356163, 0, 0, 0.999854, 0.0000409465, 0, 0, 0.99979, 0.0000492651, 0, 0, 0.999699, 0.0000621722, 0, 0.00000088288, 0.999572, 0.0000819715, 0, 0.000223369, 0.999381, 0.000111689, 0, 0.00105414, 0.999016, 0.000153862, 0, 0.0026493, 0.997437, 0.000187667, 0, 0.00508608, 0.993545, 0.000155672, 0, 0.00840554, 0.991135, 0.000161455, 0, 0.012629, 0.989157, 0.000188241, 0, 0.0177661, 0.986874, 0.000226229, 0, 0.0238198, 0.983714, 0.000268668, 0, 0.0307887, 0.978301, 0.000277109, 0, 0.0386688, 0.973227, 0.000303446, 0, 0.0474554, 0.967317, 0.000341851, 0, 0.0571428, 0.959477, 0.000370885, 0, 0.0677256, 0.950012, 0.000392753, 0, 0.0791988, 0.939484, 0.00042781, 0, 0.0915576, 0.928135, 0.000443866, 0, 0.104798, 0.919819, 0.000472959, 0, 0.118918, 0.910049, 0.000491551, 0, 0.133915, 0.899181, 0.000512616, 0, 0.149788, 0.886881, 0.000523563, 0, 0.166537, 0.87359, 0.000540183, 0, 0.184164, 0.858613, 0.000547386, 0, 0.202669, 0.842809, 0.000554809, 0, 0.222056, 0.825727, 0.000558316, 0, 0.242329, 0.808086, 0.000557824, 0, 0.263492, 0.790728, 0.000556346, 0, 0.285551, 0.772987, 0.000552672, 0, 0.30851, 0.7541, 0.000543738, 0, 0.332376, 0.734669, 0.000536107, 0, 0.357153, 0.714411, 0.000523342, 0, 0.382845, 0.694196, 0.000512238, 0, 0.409454, 0.674252, 0.000497465, 0, 0.436977, 0.65357, 0.000481096, 0, 0.465404, 0.632999, 0.000467054, 0, 0.494713, 0.611994, 0.000448771, 0, 0.524864, 0.591604, 0.000431889, 0, 0.555779, 0.571134, 0.000415238, 0, 0.587302, 0.550528, 0.000396369, 0, 0.619048, 0.530292, 0.000379477, 0, 0.650794, 0.510364, 0.000361488, 0, 0.68254, 0.490749, 0.000343787, 0, 0.714286, 0.471266, 0.000327822, 0, 0.746032, 0.452462, 0.000310626, 0, 0.777778, 0.433907, 0.000295352, 0, 0.809524, 0.415659, 0.000279179, 0, 0.84127, 0.398138, 0.000264685, 0, 0.873016, 0.380833, 0.000249905, 0, 0.904762, 0.364247, 0.000236282, 0, 0.936508, 0.348041, 0.000222905, 0, 0.968254, 0.332389, 0.000210522, 0, 1, 1, 0.0000420604, 0, 0, 1, 0.0000420614, 0, 0, 1, 0.0000420757, 0, 0, 0.999999, 0.000042138, 0, 0, 0.999997, 0.0000423067, 0, 0, 0.999993, 0.0000426668, 0, 0, 0.999986, 0.0000433372, 0, 0, 0.999974, 0.0000444857, 0, 0, 0.999956, 0.0000463554, 0, 0, 0.99993, 0.0000493105, 0, 0, 0.999892, 0.0000539077, 0, 0, 0.999838, 0.0000610005, 0, 0, 0.999767, 0.0000718822, 0, 0, 0.999666, 0.0000884581, 0, 0.0000365471, 0.999525, 0.000113398, 0, 0.000485623, 0.999311, 0.000150043, 0, 0.00162096, 0.998865, 0.000200063, 0, 0.00355319, 0.996278, 0.000211014, 0, 0.00633818, 0.992956, 0.000189672, 0, 0.0100043, 0.991017, 0.000210262, 0, 0.0145648, 0.989055, 0.000244292, 0, 0.0200237, 0.986741, 0.000290481, 0, 0.0263798, 0.983288, 0.000334303, 0, 0.033629, 0.977784, 0.000340307, 0, 0.0417652, 0.973037, 0.000377864, 0, 0.0507821, 0.967181, 0.0004239, 0, 0.060673, 0.958971, 0.000443854, 0, 0.0714314, 0.950093, 0.000483039, 0, 0.0830518, 0.939552, 0.000517934, 0, 0.0955288, 0.927678, 0.000539449, 0, 0.108859, 0.918278, 0.000568604, 0, 0.123038, 0.908449, 0.000588505, 0, 0.138065, 0.897713, 0.000612473, 0, 0.153938, 0.885533, 0.000625575, 0, 0.170657, 0.872131, 0.00063854, 0, 0.188224, 0.857517, 0.000647034, 0, 0.20664, 0.841796, 0.00065209, 0, 0.225909, 0.824726, 0.0006544, 0, 0.246035, 0.807297, 0.000655744, 0, 0.267022, 0.789058, 0.000646716, 0, 0.288878, 0.77189, 0.000643898, 0, 0.311607, 0.753082, 0.000629973, 0, 0.335216, 0.7341, 0.000621564, 0, 0.359713, 0.714094, 0.000605171, 0, 0.385103, 0.693839, 0.000588752, 0, 0.41139, 0.673891, 0.000573294, 0, 0.438576, 0.653565, 0.000552682, 0, 0.466656, 0.633326, 0.000533446, 0, 0.495617, 0.612582, 0.000514635, 0, 0.525431, 0.59205, 0.00049303, 0, 0.556041, 0.571918, 0.000471842, 0, 0.587338, 0.551572, 0.000451713, 0, 0.619048, 0.531553, 0.000430049, 0, 0.650794, 0.51175, 0.000410445, 0, 0.68254, 0.49238, 0.000390098, 0, 0.714286, 0.473143, 0.000370033, 0, 0.746032, 0.45423, 0.000351205, 0, 0.777778, 0.435963, 0.000332049, 0, 0.809524, 0.41787, 0.000315021, 0, 0.84127, 0.400387, 0.000297315, 0, 0.873016, 0.383332, 0.000281385, 0, 0.904762, 0.366665, 0.000265397, 0, 0.936508, 0.350633, 0.000250601, 0, 0.968254, 0.334964, 0.00023589, 0, 1, 1, 0.0000643736, 0, 0, 1, 0.000064375, 0, 0, 1, 0.0000643947, 0, 0, 0.999999, 0.000064481, 0, 0, 0.999997, 0.0000647143, 0, 0, 0.999994, 0.0000652119, 0, 0, 0.999985, 0.0000661359, 0, 0, 0.999972, 0.0000677116, 0, 0, 0.999952, 0.0000702599, 0, 0, 0.999922, 0.0000742517, 0, 0, 0.99988, 0.0000803906, 0, 0, 0.99982, 0.0000897315, 0, 0, 0.999741, 0.000103838, 0, 0, 0.999629, 0.00012496, 0, 0.000149024, 0.999474, 0.000156161, 0, 0.000861027, 0.999229, 0.000201034, 0, 0.00231198, 0.998662, 0.000259069, 0, 0.00458147, 0.995299, 0.000245439, 0, 0.00770895, 0.992732, 0.00024498, 0, 0.0117126, 0.990847, 0.000273211, 0, 0.0165989, 0.988911, 0.000316492, 0, 0.0223674, 0.98654, 0.00037161, 0, 0.0290135, 0.982636, 0.000410352, 0, 0.0365309, 0.977346, 0.000421756, 0, 0.0449117, 0.972909, 0.000475578, 0, 0.0541481, 0.966821, 0.000522482, 0, 0.0642326, 0.958686, 0.000545008, 0, 0.075158, 0.949754, 0.000589286, 0, 0.0869181, 0.939184, 0.000619995, 0, 0.0995074, 0.927505, 0.000654266, 0, 0.112922, 0.916606, 0.000682362, 0, 0.127157, 0.906707, 0.000704286, 0, 0.142212, 0.895937, 0.000725909, 0, 0.158085, 0.883913, 0.000743939, 0, 0.174776, 0.870642, 0.000755157, 0, 0.192287, 0.856241, 0.000764387, 0, 0.210619, 0.84069, 0.000771032, 0, 0.229775, 0.823728, 0.000765906, 0, 0.249761, 0.806481, 0.000767604, 0, 0.270582, 0.787924, 0.000754385, 0, 0.292243, 0.770588, 0.000749668, 0, 0.314753, 0.751991, 0.000731613, 0, 0.338118, 0.733407, 0.000717655, 0, 0.362347, 0.713688, 0.000700604, 0, 0.387447, 0.693595, 0.000678765, 0, 0.413424, 0.673426, 0.000657042, 0, 0.440284, 0.65359, 0.000635892, 0, 0.468027, 0.633576, 0.000611569, 0, 0.496645, 0.613144, 0.000586011, 0, 0.526122, 0.592711, 0.000563111, 0, 0.556417, 0.572722, 0.000537699, 0, 0.587451, 0.552762, 0.000512556, 0, 0.619048, 0.532985, 0.000489757, 0, 0.650794, 0.513219, 0.000464139, 0, 0.68254, 0.493992, 0.000442193, 0, 0.714286, 0.47509, 0.000418629, 0, 0.746032, 0.456287, 0.000397045, 0, 0.777778, 0.438152, 0.000375504, 0, 0.809524, 0.420294, 0.00035492, 0, 0.84127, 0.402749, 0.000335327, 0, 0.873016, 0.385879, 0.000316422, 0, 0.904762, 0.369352, 0.000298333, 0, 0.936508, 0.353301, 0.000281417, 0, 0.968254, 0.337781, 0.000265203, 0, 1, 1, 0.0000968267, 0, 0, 1, 0.0000968284, 0, 0, 1, 0.0000968556, 0, 0, 0.999999, 0.0000969733, 0, 0, 0.999997, 0.0000972913, 0, 0, 0.999993, 0.0000979688, 0, 0, 0.999984, 0.0000992239, 0, 0, 0.999969, 0.000101356, 0, 0, 0.999946, 0.000104784, 0, 0, 0.999913, 0.000110111, 0, 0, 0.999868, 0.000118217, 0, 0, 0.999801, 0.000130396, 0, 0, 0.999712, 0.000148523, 0, 0.0000124907, 0.999589, 0.000175233, 0, 0.000355405, 0.999416, 0.000213999, 0, 0.0013528, 0.999136, 0.000268529, 0, 0.00312557, 0.998367, 0.000333088, 0, 0.00573045, 0.994701, 0.000304757, 0, 0.00919397, 0.992497, 0.000318031, 0, 0.0135261, 0.990608, 0.000353863, 0, 0.0187278, 0.988715, 0.000409044, 0, 0.0247947, 0.986241, 0.000472967, 0, 0.0317196, 0.981696, 0.000495104, 0, 0.039494, 0.977097, 0.000532873, 0, 0.0481087, 0.972583, 0.000594447, 0, 0.0575549, 0.966142, 0.000636867, 0, 0.0678242, 0.95823, 0.000669899, 0, 0.0789089, 0.949677, 0.000719499, 0, 0.0908023, 0.939226, 0.000750584, 0, 0.103499, 0.927501, 0.000793183, 0, 0.116993, 0.915199, 0.00081995, 0, 0.131282, 0.90498, 0.000847654, 0, 0.146364, 0.894243, 0.000868929, 0, 0.162237, 0.882154, 0.000884278, 0, 0.178902, 0.869161, 0.000898108, 0, 0.196358, 0.854751, 0.000901254, 0, 0.21461, 0.839368, 0.00090679, 0, 0.23366, 0.822874, 0.000901541, 0, 0.253512, 0.805514, 0.000897297, 0, 0.274174, 0.78716, 0.000881856, 0, 0.29565, 0.769061, 0.000870032, 0, 0.31795, 0.751, 0.000851719, 0, 0.341081, 0.732614, 0.000830671, 0, 0.365053, 0.713171, 0.000806569, 0, 0.389874, 0.693472, 0.00078338, 0, 0.415553, 0.673528, 0.000756404, 0, 0.442098, 0.653397, 0.000726872, 0, 0.469512, 0.633781, 0.000700494, 0, 0.497794, 0.613877, 0.00067105, 0, 0.526935, 0.593506, 0.000640361, 0, 0.556908, 0.573667, 0.000613502, 0, 0.587657, 0.553932, 0.000583177, 0, 0.61906, 0.534345, 0.000554375, 0, 0.650794, 0.515042, 0.000527811, 0, 0.68254, 0.495674, 0.000499367, 0, 0.714286, 0.477132, 0.00047429, 0, 0.746032, 0.458609, 0.000447726, 0, 0.777778, 0.440354, 0.000424205, 0, 0.809524, 0.422765, 0.000399549, 0, 0.84127, 0.405472, 0.000378315, 0, 0.873016, 0.388482, 0.000355327, 0, 0.904762, 0.372191, 0.000336122, 0, 0.936508, 0.356099, 0.000315247, 0, 0.968254, 0.340737, 0.00029794, 0, 1, 1, 0.000143327, 0, 0, 1, 0.00014333, 0, 0, 1, 0.000143366, 0, 0, 0.999999, 0.000143524, 0, 0, 0.999996, 0.000143952, 0, 0, 0.999991, 0.000144862, 0, 0, 0.999981, 0.000146544, 0, 0, 0.999966, 0.000149391, 0, 0, 0.999941, 0.000153946, 0, 0, 0.999905, 0.000160971, 0, 0, 0.999852, 0.000171562, 0, 0, 0.99978, 0.00018729, 0, 0, 0.999681, 0.000210386, 0, 0.0000826239, 0.999546, 0.000243906, 0, 0.000664807, 0.999352, 0.000291739, 0, 0.00196192, 0.999027, 0.000357419, 0, 0.00405941, 0.997886, 0.000422349, 0, 0.00699664, 0.99419, 0.000385008, 0, 0.0107896, 0.99214, 0.000409775, 0, 0.0154415, 0.990274, 0.000456418, 0, 0.0209488, 0.988455, 0.000527008, 0, 0.0273037, 0.985804, 0.000597685, 0, 0.0344969, 0.98103, 0.000613124, 0, 0.0425183, 0.976674, 0.000668321, 0, 0.0513575, 0.972021, 0.000736985, 0, 0.0610046, 0.965274, 0.000773789, 0, 0.0714508, 0.958046, 0.000830852, 0, 0.0826877, 0.949333, 0.000875766, 0, 0.0947085, 0.939135, 0.000917088, 0, 0.107507, 0.927119, 0.000952244, 0, 0.121078, 0.91469, 0.000990626, 0, 0.135419, 0.903006, 0.00101304, 0, 0.150526, 0.892368, 0.00103834, 0, 0.166399, 0.880231, 0.00105002, 0, 0.183038, 0.867432, 0.00106331, 0, 0.200443, 0.853208, 0.00106783, 0, 0.218618, 0.837956, 0.00106458, 0, 0.237566, 0.821772, 0.00105945, 0, 0.257291, 0.804328, 0.00104685, 0, 0.2778, 0.786465, 0.00103178, 0, 0.2991, 0.768004, 0.00101077, 0, 0.321199, 0.74972, 0.000985504, 0, 0.344106, 0.731682, 0.000962893, 0, 0.36783, 0.712813, 0.000932146, 0, 0.392383, 0.693139, 0.00089871, 0, 0.417774, 0.673566, 0.000869678, 0, 0.444013, 0.653483, 0.000835525, 0, 0.471107, 0.633891, 0.000799853, 0, 0.49906, 0.614433, 0.000766838, 0, 0.527869, 0.594586, 0.000732227, 0, 0.557517, 0.574769, 0.000696442, 0, 0.587966, 0.555149, 0.000663935, 0, 0.61913, 0.535898, 0.000629826, 0, 0.650794, 0.516753, 0.000596486, 0, 0.68254, 0.497816, 0.000567078, 0, 0.714286, 0.479034, 0.000534399, 0, 0.746032, 0.460975, 0.000507013, 0, 0.777778, 0.442935, 0.000477421, 0, 0.809524, 0.425263, 0.000451101, 0, 0.84127, 0.408248, 0.000424964, 0, 0.873016, 0.391339, 0.00039993, 0, 0.904762, 0.37513, 0.000377619, 0, 0.936508, 0.359172, 0.000354418, 0, 0.968254, 0.343876, 0.000334823, 0, 1, 1, 0.000209042, 0, 0, 1, 0.000209045, 0, 0, 1, 0.000209093, 0, 0, 0.999999, 0.000209304, 0, 0, 0.999996, 0.000209871, 0, 0, 0.999991, 0.000211078, 0, 0, 0.999979, 0.000213304, 0, 0, 0.999963, 0.000217061, 0, 0, 0.999933, 0.000223042, 0, 0, 0.999894, 0.000232206, 0, 0, 0.999837, 0.000245901, 0, 0, 0.999756, 0.000266023, 0, 0.00000102927, 0.999648, 0.000295204, 0, 0.000233468, 0.999499, 0.000336958, 0, 0.00108237, 0.999283, 0.000395563, 0, 0.00268832, 0.998896, 0.000473785, 0, 0.00511138, 0.997006, 0.000520008, 0, 0.00837705, 0.993819, 0.000497261, 0, 0.0124928, 0.991632, 0.000523722, 0, 0.0174561, 0.989875, 0.000587258, 0, 0.0232596, 0.988109, 0.000676329, 0, 0.0298932, 0.985155, 0.000747701, 0, 0.0373453, 0.980479, 0.000768803, 0, 0.0456045, 0.976271, 0.000841054, 0, 0.0546593, 0.971347, 0.000911469, 0, 0.0644994, 0.964528, 0.000953057, 0, 0.0751152, 0.957632, 0.00102221, 0, 0.0864981, 0.948681, 0.00106122, 0, 0.0986407, 0.938716, 0.00111857, 0, 0.111537, 0.926629, 0.00114762, 0, 0.125182, 0.914025, 0.00118995, 0, 0.139571, 0.901026, 0.00121228, 0, 0.154703, 0.890358, 0.00123946, 0, 0.170576, 0.878283, 0.0012527, 0, 0.18719, 0.865459, 0.00125536, 0, 0.204547, 0.851407, 0.00126134, 0, 0.222648, 0.836276, 0.00124759, 0, 0.241498, 0.820436, 0.00124443, 0, 0.261101, 0.803253, 0.00122071, 0, 0.281465, 0.785562, 0.00120107, 0, 0.302595, 0.76718, 0.00117762, 0, 0.324501, 0.748551, 0.00114289, 0, 0.347192, 0.730564, 0.00110872, 0, 0.370679, 0.712253, 0.00107636, 0, 0.394973, 0.692867, 0.00103646, 0, 0.420085, 0.673695, 0.000996793, 0, 0.446027, 0.653912, 0.00095675, 0, 0.47281, 0.634129, 0.000916739, 0, 0.500441, 0.615004, 0.000874401, 0, 0.528921, 0.595587, 0.000833411, 0, 0.558244, 0.575965, 0.000794556, 0, 0.588384, 0.5566, 0.00075196, 0, 0.619281, 0.537428, 0.000716381, 0, 0.650795, 0.518623, 0.000676558, 0, 0.68254, 0.499964, 0.00064074, 0, 0.714286, 0.481356, 0.000605984, 0, 0.746032, 0.463279, 0.000570256, 0, 0.777778, 0.445673, 0.000540138, 0, 0.809524, 0.428032, 0.000507299, 0, 0.84127, 0.411112, 0.000479553, 0, 0.873016, 0.394444, 0.000450737, 0, 0.904762, 0.378247, 0.000424269, 0, 0.936508, 0.362415, 0.000399111, 0, 0.968254, 0.347103, 0.000375274, 0, 1, 1, 0.000300729, 0, 0, 1, 0.000300733, 0, 0, 1, 0.000300797, 0, 0, 0.999998, 0.000301072, 0, 0, 0.999996, 0.000301817, 0, 0, 0.999989, 0.000303398, 0, 0, 0.999977, 0.000306309, 0, 0, 0.999958, 0.000311209, 0, 0, 0.999927, 0.000318975, 0, 0, 0.999884, 0.000330804, 0, 0, 0.99982, 0.00034834, 0, 0, 0.999733, 0.000373854, 0, 0.0000326995, 0.999613, 0.000410424, 0, 0.000477174, 0.999447, 0.000462047, 0, 0.00161099, 0.999204, 0.000533322, 0, 0.00353153, 0.998725, 0.000624964, 0, 0.00627965, 0.995871, 0.000631786, 0, 0.0098693, 0.993194, 0.000632017, 0, 0.0143011, 0.991541, 0.00068923, 0, 0.019568, 0.989773, 0.000766892, 0, 0.0256593, 0.987647, 0.000863668, 0, 0.0325625, 0.984193, 0.000922089, 0, 0.0402647, 0.980016, 0.000970749, 0, 0.0487532, 0.975859, 0.00106027, 0, 0.058016, 0.970514, 0.00112239, 0, 0.0680419, 0.963625, 0.00117212, 0, 0.0788208, 0.956959, 0.00125211, 0, 0.0903439, 0.947956, 0.00129411, 0, 0.102604, 0.93809, 0.00135879, 0, 0.115594, 0.92659, 0.00139309, 0, 0.129309, 0.913829, 0.00143253, 0, 0.143745, 0.90005, 0.00145809, 0, 0.158901, 0.888129, 0.0014748, 0, 0.174774, 0.87607, 0.00148756, 0, 0.191365, 0.863461, 0.00148714, 0, 0.208674, 0.849594, 0.00148892, 0, 0.226705, 0.834531, 0.00146496, 0, 0.245461, 0.81903, 0.0014579, 0, 0.264947, 0.802122, 0.00143039, 0, 0.28517, 0.78445, 0.00139717, 0, 0.306137, 0.766434, 0.00136312, 0, 0.327857, 0.747816, 0.00132597, 0, 0.350341, 0.729519, 0.00128323, 0, 0.373598, 0.711454, 0.00123803, 0, 0.397642, 0.692699, 0.00119097, 0, 0.422485, 0.673723, 0.00114565, 0, 0.448139, 0.654386, 0.00109552, 0, 0.474619, 0.634673, 0.00104553, 0, 0.501933, 0.615554, 0.00099985, 0, 0.530089, 0.596462, 0.000948207, 0, 0.559087, 0.577385, 0.000902299, 0, 0.588913, 0.558257, 0.000856448, 0, 0.619525, 0.5392, 0.000810395, 0, 0.650826, 0.520543, 0.000768558, 0, 0.68254, 0.502206, 0.0007239, 0, 0.714286, 0.48402, 0.000685794, 0, 0.746032, 0.465779, 0.00064471, 0, 0.777778, 0.448455, 0.000609583, 0, 0.809524, 0.431091, 0.00057227, 0, 0.84127, 0.414147, 0.00054042, 0, 0.873016, 0.39765, 0.000506545, 0, 0.904762, 0.381576, 0.000477635, 0, 0.936508, 0.365881, 0.000448446, 0, 0.968254, 0.350582, 0.000421424, 0, 1, 1, 0.000427144, 0, 0, 1, 0.000427151, 0, 0, 1, 0.000427232, 0, 0, 0.999998, 0.00042759, 0, 0, 0.999995, 0.000428555, 0, 0, 0.999988, 0.000430603, 0, 0, 0.999976, 0.000434368, 0, 0, 0.999952, 0.000440688, 0, 0, 0.999919, 0.000450667, 0, 0, 0.999871, 0.00046578, 0, 0, 0.999801, 0.000488024, 0, 0, 0.999704, 0.000520092, 0, 0.000129791, 0.999572, 0.000565553, 0, 0.000821056, 0.999389, 0.000628906, 0, 0.00225241, 0.999114, 0.000714911, 0, 0.00449109, 0.998488, 0.000819218, 0, 0.00756249, 0.995234, 0.00080415, 0, 0.0114716, 0.993021, 0.000830181, 0, 0.0162131, 0.991407, 0.000902645, 0, 0.021776, 0.989625, 0.000996934, 0, 0.0281471, 0.987064, 0.00109707, 0, 0.0353118, 0.983265, 0.00114353, 0, 0.0432562, 0.979535, 0.0012272, 0, 0.0519665, 0.975224, 0.00132642, 0, 0.0614298, 0.969574, 0.00138092, 0, 0.0716348, 0.963021, 0.00145896, 0, 0.0825709, 0.956046, 0.00152834, 0, 0.094229, 0.947136, 0.00158217, 0, 0.106602, 0.937313, 0.0016347, 0, 0.119682, 0.926073, 0.00168383, 0, 0.133465, 0.913121, 0.00171627, 0, 0.147947, 0.899165, 0.00174229, 0, 0.163125, 0.885891, 0.00176137, 0, 0.178998, 0.873783, 0.00176406, 0, 0.195566, 0.861331, 0.00176156, 0, 0.21283, 0.847569, 0.00175346, 0, 0.230793, 0.832785, 0.00172753, 0, 0.249459, 0.817442, 0.00170204, 0, 0.268832, 0.800613, 0.00166576, 0, 0.28892, 0.783597, 0.00162909, 0, 0.30973, 0.76571, 0.0015826, 0, 0.331271, 0.747021, 0.00153106, 0, 0.353554, 0.728593, 0.00148036, 0, 0.37659, 0.710661, 0.00142808, 0, 0.400391, 0.692426, 0.00136906, 0, 0.424973, 0.673623, 0.00131066, 0, 0.450347, 0.65494, 0.00125569, 0, 0.476531, 0.635448, 0.00119517, 0, 0.503535, 0.616221, 0.00113828, 0, 0.531372, 0.597531, 0.0010816, 0, 0.560047, 0.578795, 0.00102673, 0, 0.589554, 0.559892, 0.000970985, 0, 0.619869, 0.541307, 0.000919773, 0, 0.650923, 0.522608, 0.000868479, 0, 0.68254, 0.504484, 0.00082137, 0, 0.714286, 0.486603, 0.000772916, 0, 0.746032, 0.468802, 0.000730353, 0, 0.777778, 0.451172, 0.000684955, 0, 0.809524, 0.434348, 0.000647565, 0, 0.84127, 0.417445, 0.000605863, 0, 0.873016, 0.401077, 0.000571885, 0, 0.904762, 0.385039, 0.000536034, 0, 0.936508, 0.369483, 0.000504227, 0, 0.968254, 0.354272, 0.000473165, 0, 1, 1, 0.000599525, 0, 0, 1, 0.000599533, 0, 0, 1, 0.000599639, 0, 0, 0.999998, 0.000600097, 0, 0, 0.999994, 0.000601336, 0, 0, 0.999987, 0.000603958, 0, 0, 0.999972, 0.000608775, 0, 0, 0.999949, 0.000616842, 0, 0, 0.999912, 0.000629534, 0, 0, 0.999857, 0.000648658, 0, 0, 0.999781, 0.000676615, 0, 0.00000538873, 0.999674, 0.000716574, 0, 0.000308602, 0.999528, 0.000772641, 0, 0.00127003, 0.999326, 0.000849806, 0, 0.00300783, 0.999009, 0.000952682, 0, 0.00556637, 0.998112, 0.00106394, 0, 0.00895889, 0.994496, 0.00102228, 0, 0.0131827, 0.992806, 0.00108586, 0, 0.0182277, 0.991211, 0.0011759, 0, 0.0240795, 0.989415, 0.00128955, 0, 0.030723, 0.986499, 0.00139038, 0, 0.0381418, 0.982679, 0.00144539, 0, 0.046321, 0.978839, 0.00153954, 0, 0.0552459, 0.974295, 0.00164417, 0, 0.0649034, 0.968784, 0.00171517, 0, 0.0752814, 0.962324, 0.00180282, 0, 0.0863693, 0.954956, 0.00186387, 0, 0.0981578, 0.94624, 0.00193817, 0, 0.110639, 0.936517, 0.00198156, 0, 0.123806, 0.925186, 0.00203042, 0, 0.137655, 0.91252, 0.0020664, 0, 0.15218, 0.898441, 0.00207822, 0, 0.16738, 0.884394, 0.0020992, 0, 0.183253, 0.871273, 0.00208748, 0, 0.199799, 0.859057, 0.00208686, 0, 0.21702, 0.845243, 0.00205519, 0, 0.234918, 0.830723, 0.00202868, 0, 0.253496, 0.815801, 0.00199501, 0, 0.272761, 0.79914, 0.00194193, 0, 0.292719, 0.782372, 0.00188824, 0, 0.313377, 0.76482, 0.00183695, 0, 0.334745, 0.746586, 0.00177418, 0, 0.356833, 0.7281, 0.00170628, 0, 0.379654, 0.709842, 0.00164063, 0, 0.403221, 0.692019, 0.00157355, 0, 0.427548, 0.67364, 0.00150262, 0, 0.452651, 0.655277, 0.00143473, 0, 0.478545, 0.636438, 0.00136371, 0, 0.505246, 0.617364, 0.00129911, 0, 0.532768, 0.598603, 0.00123014, 0, 0.561122, 0.580195, 0.00116587, 0, 0.590309, 0.561786, 0.00110398, 0, 0.620318, 0.543377, 0.00104148, 0, 0.651102, 0.525093, 0.000983984, 0, 0.682545, 0.506791, 0.00092667, 0, 0.714286, 0.489291, 0.000874326, 0, 0.746032, 0.471811, 0.000821734, 0, 0.777778, 0.454435, 0.000774698, 0, 0.809524, 0.437493, 0.000727302, 0, 0.84127, 0.420977, 0.000684039, 0, 0.873016, 0.404729, 0.00064373, 0, 0.904762, 0.388756, 0.00060285, 0, 0.936508, 0.373344, 0.00056765, 0, 0.968254, 0.358191, 0.000531929, 0, 1, 1, 0.000832169, 0, 0, 1, 0.000832178, 0, 0, 1, 0.00083231, 0, 0, 0.999998, 0.000832893, 0, 0, 0.999995, 0.000834465, 0, 0, 0.999985, 0.000837791, 0, 0, 0.999969, 0.000843893, 0, 0, 0.999944, 0.000854086, 0, 0, 0.999903, 0.000870071, 0, 0, 0.999843, 0.000894042, 0, 0, 0.999759, 0.000928865, 0, 0.0000531805, 0.999643, 0.000978242, 0, 0.000579365, 0.99948, 0.00104684, 0, 0.00182774, 0.999255, 0.00114012, 0, 0.00387804, 0.998885, 0.00126188, 0, 0.00675709, 0.997405, 0.00135888, 0, 0.010468, 0.99424, 0.00133626, 0, 0.0150018, 0.992458, 0.00140905, 0, 0.0203443, 0.990929, 0.00152305, 0, 0.0264786, 0.989116, 0.00165882, 0, 0.0333875, 0.985624, 0.00174128, 0, 0.0410536, 0.982003, 0.00182108, 0, 0.0494609, 0.978336, 0.00194498, 0, 0.0585941, 0.973184, 0.00202708, 0, 0.0684396, 0.9678, 0.00212166, 0, 0.0789851, 0.961348, 0.00221366, 0, 0.0902199, 0.953841, 0.00228219, 0, 0.102134, 0.94534, 0.00235662, 0, 0.114721, 0.935552, 0.00240572, 0, 0.127972, 0.924064, 0.00244405, 0, 0.141884, 0.911827, 0.00247557, 0, 0.156451, 0.897731, 0.00248374, 0, 0.171672, 0.883409, 0.00249863, 0, 0.187545, 0.868625, 0.00246688, 0, 0.20407, 0.856529, 0.00246523, 0, 0.221249, 0.842999, 0.00242368, 0, 0.239083, 0.828505, 0.00237354, 0, 0.257578, 0.813825, 0.00232588, 0, 0.276738, 0.797813, 0.00226731, 0, 0.296569, 0.781097, 0.00219704, 0, 0.31708, 0.764038, 0.00212394, 0, 0.338281, 0.746067, 0.00204786, 0, 0.360181, 0.727687, 0.00196728, 0, 0.382794, 0.709571, 0.00188779, 0, 0.406133, 0.691503, 0.00180532, 0, 0.430213, 0.673673, 0.00171849, 0, 0.45505, 0.655732, 0.00164147, 0, 0.480662, 0.637399, 0.00155858, 0, 0.507065, 0.618616, 0.00147641, 0, 0.534278, 0.60005, 0.00140125, 0, 0.562313, 0.581713, 0.00132441, 0, 0.59118, 0.563546, 0.00125014, 0, 0.620875, 0.545605, 0.00118249, 0, 0.651373, 0.527559, 0.0011116, 0, 0.682593, 0.509764, 0.00104979, 0, 0.714286, 0.49193, 0.000985977, 0, 0.746032, 0.475011, 0.000928592, 0, 0.777778, 0.457878, 0.000873466, 0, 0.809524, 0.440979, 0.000819585, 0, 0.84127, 0.424613, 0.000772365, 0, 0.873016, 0.408549, 0.000722195, 0, 0.904762, 0.392771, 0.000680014, 0, 0.936508, 0.377317, 0.000636797, 0, 0.968254, 0.362352, 0.000598318, 0, 1, 1, 0.00114313, 0, 0, 1, 0.00114314, 0, 0, 0.999999, 0.00114331, 0, 0, 0.999998, 0.00114404, 0, 0, 0.999994, 0.00114601, 0, 0, 0.999984, 0.00115019, 0, 0, 0.999967, 0.00115784, 0, 0, 0.999937, 0.0011706, 0, 0, 0.999894, 0.00119054, 0, 0, 0.999828, 0.00122031, 0, 0, 0.999735, 0.00126331, 0, 0.000169263, 0.999606, 0.00132382, 0, 0.000949167, 0.999426, 0.0014071, 0, 0.00249668, 0.999173, 0.00151895, 0, 0.00486392, 0.99873, 0.00166102, 0, 0.00806323, 0.996243, 0.0017023, 0, 0.0120895, 0.993779, 0.00172782, 0, 0.0169288, 0.9919, 0.0018108, 0, 0.0225633, 0.990524, 0.00196028, 0, 0.028974, 0.98868, 0.00212014, 0, 0.036142, 0.984663, 0.00217598, 0, 0.044049, 0.981457, 0.00230563, 0, 0.0526781, 0.977608, 0.00243966, 0, 0.0620137, 0.972215, 0.00251336, 0, 0.0720418, 0.966798, 0.0026285, 0, 0.0827499, 0.960241, 0.00271409, 0, 0.0941271, 0.952489, 0.00278381, 0, 0.106164, 0.944127, 0.00285399, 0, 0.118852, 0.934282, 0.00290994, 0, 0.132185, 0.923271, 0.00294558, 0, 0.146157, 0.910803, 0.00296269, 0, 0.160766, 0.896705, 0.00296803, 0, 0.176007, 0.88238, 0.00296637, 0, 0.19188, 0.867116, 0.00293163, 0, 0.208385, 0.853636, 0.00289418, 0, 0.225523, 0.840469, 0.00284663, 0, 0.243296, 0.82639, 0.00278594, 0, 0.261709, 0.811759, 0.00271618, 0, 0.280767, 0.796113, 0.00263187, 0, 0.300476, 0.779518, 0.00254589, 0, 0.320845, 0.763142, 0.00246003, 0, 0.341883, 0.745464, 0.00236529, 0, 0.363601, 0.727491, 0.00226536, 0, 0.386011, 0.709414, 0.00216375, 0, 0.409128, 0.691396, 0.00207127, 0, 0.432967, 0.67368, 0.00197106, 0, 0.457545, 0.656049, 0.00187022, 0, 0.482881, 0.638188, 0.00177605, 0, 0.508992, 0.620177, 0.00168482, 0, 0.535899, 0.601506, 0.00158909, 0, 0.563619, 0.58362, 0.00150583, 0, 0.592165, 0.565496, 0.00141791, 0, 0.621544, 0.54789, 0.00133693, 0, 0.651743, 0.530323, 0.00126038, 0, 0.682709, 0.512795, 0.00118556, 0, 0.714286, 0.495199, 0.00111527, 0, 0.746032, 0.478101, 0.0010489, 0, 0.777778, 0.461511, 0.000984264, 0, 0.809524, 0.444879, 0.00092591, 0, 0.84127, 0.428424, 0.000866582, 0, 0.873016, 0.412495, 0.000814463, 0, 0.904762, 0.396975, 0.000764498, 0, 0.936508, 0.381614, 0.000715967, 0, 0.968254, 0.366732, 0.000672483, 0, 1, 1, 0.00155501, 0, 0, 1, 0.00155503, 0, 0, 1, 0.00155524, 0, 0, 0.999998, 0.00155615, 0, 0, 0.999994, 0.0015586, 0, 0, 0.999983, 0.00156379, 0, 0, 0.999963, 0.0015733, 0, 0, 0.999932, 0.00158911, 0, 0, 0.999882, 0.00161376, 0, 0, 0.99981, 0.00165041, 0, 0.0000100875, 0.999708, 0.00170304, 0, 0.000367658, 0.999565, 0.00177658, 0, 0.0014234, 0.999368, 0.00187688, 0, 0.00327939, 0.999081, 0.00200989, 0, 0.00596629, 0.99852, 0.00217177, 0, 0.0094852, 0.99549, 0.0021745, 0, 0.013824, 0.993252, 0.00222357, 0, 0.0189642, 0.991727, 0.00235022, 0, 0.0248856, 0.989951, 0.00250561, 0, 0.0315669, 0.988029, 0.00268829, 0, 0.0389882, 0.984029, 0.0027496, 0, 0.0471302, 0.980683, 0.00289793, 0, 0.0559754, 0.976554, 0.00303315, 0, 0.0655081, 0.97139, 0.00313257, 0, 0.0757138, 0.965544, 0.00323656, 0, 0.08658, 0.95912, 0.00333432, 0, 0.0980954, 0.951183, 0.0034039, 0, 0.110251, 0.942974, 0.00347515, 0, 0.123038, 0.932642, 0.00350381, 0, 0.13645, 0.922158, 0.00354519, 0, 0.150482, 0.909404, 0.00353851, 0, 0.165129, 0.896071, 0.0035435, 0, 0.18039, 0.881206, 0.00349936, 0, 0.196263, 0.866077, 0.00347256, 0, 0.212748, 0.85093, 0.003415, 0, 0.229847, 0.837703, 0.00333367, 0, 0.247561, 0.823878, 0.003249, 0, 0.265895, 0.809449, 0.00316347, 0, 0.284854, 0.794379, 0.00306351, 0, 0.304445, 0.778138, 0.0029499, 0, 0.324675, 0.761997, 0.00284099, 0, 0.345555, 0.744938, 0.00272104, 0, 0.367095, 0.727212, 0.00260715, 0, 0.389309, 0.709549, 0.00248855, 0, 0.41221, 0.691704, 0.00236783, 0, 0.435814, 0.673689, 0.00225178, 0, 0.460138, 0.656453, 0.00213765, 0, 0.485203, 0.639128, 0.00202178, 0, 0.511028, 0.621512, 0.00191443, 0, 0.537634, 0.603598, 0.00180977, 0, 0.565041, 0.58559, 0.00170456, 0, 0.593268, 0.567852, 0.00160927, 0, 0.622327, 0.5503, 0.00151395, 0, 0.652217, 0.533033, 0.00142499, 0, 0.682907, 0.515942, 0.00133955, 0, 0.714296, 0.498814, 0.0012602, 0, 0.746032, 0.481595, 0.00118188, 0, 0.777778, 0.465117, 0.00111171, 0, 0.809524, 0.448865, 0.00104091, 0, 0.84127, 0.432711, 0.000976618, 0, 0.873016, 0.416822, 0.00091859, 0, 0.904762, 0.401272, 0.000857704, 0, 0.936508, 0.386226, 0.000807172, 0, 0.968254, 0.371321, 0.00075464, 0, 1, 1, 0.00209596, 0, 0, 1, 0.00209598, 0, 0, 1, 0.00209624, 0, 0, 0.999997, 0.00209736, 0, 0, 0.999991, 0.00210039, 0, 0, 0.999979, 0.00210678, 0, 0, 0.999959, 0.00211847, 0, 0, 0.999925, 0.0021379, 0, 0, 0.99987, 0.00216809, 0, 0, 0.999791, 0.00221281, 0, 0.0000681487, 0.999677, 0.00227669, 0, 0.000658161, 0.999521, 0.00236533, 0, 0.00200635, 0.999301, 0.00248514, 0, 0.0041779, 0.998977, 0.00264185, 0, 0.00718648, 0.998191, 0.00281695, 0, 0.0110239, 0.994801, 0.00278518, 0, 0.015672, 0.993091, 0.00288774, 0, 0.0211091, 0.991571, 0.00303931, 0, 0.0273123, 0.9897, 0.00321643, 0, 0.034259, 0.987023, 0.00337332, 0, 0.0419282, 0.983289, 0.00346146, 0, 0.0502998, 0.979892, 0.00363704, 0, 0.0593562, 0.975111, 0.00373601, 0, 0.069081, 0.970351, 0.0038842, 0, 0.0794598, 0.964131, 0.00397053, 0, 0.0904798, 0.957747, 0.00408078, 0, 0.10213, 0.949536, 0.00413533, 0, 0.1144, 0.941372, 0.00420305, 0, 0.127284, 0.931049, 0.00422815, 0, 0.140772, 0.920647, 0.00425048, 0, 0.154862, 0.908033, 0.0042281, 0, 0.169548, 0.895028, 0.00422026, 0, 0.184828, 0.879968, 0.00415042, 0, 0.200701, 0.864875, 0.00408821, 0, 0.217167, 0.84918, 0.00400909, 0, 0.234227, 0.834934, 0.00391178, 0, 0.251884, 0.821397, 0.00380066, 0, 0.270141, 0.807135, 0.00367974, 0, 0.289004, 0.792363, 0.00355172, 0, 0.308479, 0.776661, 0.003411, 0, 0.328575, 0.760705, 0.00328123, 0, 0.349301, 0.744408, 0.00314003, 0, 0.370668, 0.726994, 0.0029906, 0, 0.392689, 0.709598, 0.00285034, 0, 0.415379, 0.692112, 0.00271179, 0, 0.438754, 0.674435, 0.00257185, 0, 0.46283, 0.65676, 0.00243425, 0, 0.48763, 0.639982, 0.00230351, 0, 0.513173, 0.622983, 0.0021777, 0, 0.539482, 0.605471, 0.00204991, 0, 0.566579, 0.58796, 0.00193759, 0, 0.594488, 0.570463, 0.00181976, 0, 0.623226, 0.553058, 0.00171497, 0, 0.6528, 0.535894, 0.00161109, 0, 0.683198, 0.519089, 0.00151394, 0, 0.714354, 0.502454, 0.00142122, 0, 0.746032, 0.485681, 0.00133488, 0, 0.777778, 0.468935, 0.00124975, 0, 0.809524, 0.452951, 0.00117309, 0, 0.84127, 0.437139, 0.00110155, 0, 0.873016, 0.421446, 0.00103124, 0, 0.904762, 0.405951, 0.000966387, 0, 0.936508, 0.391003, 0.000908119, 0, 0.968254, 0.376198, 0.000848057, 0, 1, 1, 0.00280076, 0, 0, 1, 0.00280078, 0, 0, 0.999999, 0.00280109, 0, 0, 0.999997, 0.00280246, 0, 0, 0.999992, 0.00280616, 0, 0, 0.999979, 0.00281396, 0, 0, 0.999956, 0.00282822, 0, 0, 0.999916, 0.00285186, 0, 0, 0.999857, 0.0028885, 0, 0, 0.999768, 0.00294259, 0, 0.000196026, 0.999645, 0.00301946, 0, 0.00104842, 0.99947, 0.00312541, 0, 0.00270199, 0.999229, 0.00326733, 0, 0.00519449, 0.998852, 0.00344992, 0, 0.00852602, 0.997558, 0.00361052, 0, 0.0126804, 0.994417, 0.0035898, 0, 0.017635, 0.992824, 0.00372393, 0, 0.023365, 0.991344, 0.00390695, 0, 0.0298456, 0.989337, 0.00410392, 0, 0.0370529, 0.985811, 0.00420987, 0, 0.0449651, 0.982772, 0.00437488, 0, 0.0535615, 0.979001, 0.00455069, 0, 0.0628243, 0.974102, 0.00464462, 0, 0.0727368, 0.969197, 0.00480577, 0, 0.0832844, 0.962759, 0.00487818, 0, 0.0944545, 0.956207, 0.00498176, 0, 0.106236, 0.947909, 0.00503392, 0, 0.118619, 0.939596, 0.00507474, 0, 0.131595, 0.929642, 0.00509798, 0, 0.145159, 0.918807, 0.00508476, 0, 0.159305, 0.906921, 0.00505634, 0, 0.174028, 0.893312, 0.00498845, 0, 0.189327, 0.878933, 0.0049133, 0, 0.2052, 0.863986, 0.0048259, 0, 0.221647, 0.847936, 0.00470848, 0, 0.23867, 0.832253, 0.00456889, 0, 0.25627, 0.818619, 0.00442726, 0, 0.274453, 0.804788, 0.00427677, 0, 0.293222, 0.790241, 0.00411906, 0, 0.312585, 0.775162, 0.00394833, 0, 0.33255, 0.759463, 0.00377366, 0, 0.353126, 0.743598, 0.00361026, 0, 0.374324, 0.72697, 0.00343627, 0, 0.396158, 0.709646, 0.00326422, 0, 0.418641, 0.69277, 0.00309717, 0, 0.44179, 0.675371, 0.0029356, 0, 0.465624, 0.657863, 0.00277712, 0, 0.490163, 0.640772, 0.00261738, 0, 0.515429, 0.624441, 0.0024737, 0, 0.541445, 0.607497, 0.00233125, 0, 0.568236, 0.590438, 0.00218994, 0, 0.595828, 0.573224, 0.0020664, 0, 0.624242, 0.556168, 0.00193526, 0, 0.653496, 0.539232, 0.00182463, 0, 0.683588, 0.522352, 0.00170735, 0, 0.714482, 0.506172, 0.00160555, 0, 0.746032, 0.489842, 0.00150451, 0, 0.777778, 0.473463, 0.00140938, 0, 0.809524, 0.457266, 0.00132568, 0, 0.84127, 0.441609, 0.0012376, 0, 0.873016, 0.426348, 0.00116265, 0, 0.904762, 0.411002, 0.00108935, 0, 0.936508, 0.396045, 0.00101946, 0, 0.968254, 0.381448, 0.000955665, 0, 1, 1, 0.0037121, 0, 0, 1, 0.00371213, 0, 0, 1, 0.00371251, 0, 0, 0.999997, 0.00371417, 0, 0, 0.99999, 0.00371863, 0, 0, 0.999977, 0.00372807, 0, 0, 0.99995, 0.00374529, 0, 0, 0.999908, 0.0037738, 0, 0, 0.999843, 0.00381789, 0, 0.0000123596, 0.999745, 0.00388273, 0, 0.000407442, 0.999608, 0.00397443, 0, 0.0015447, 0.999415, 0.00409998, 0, 0.00351385, 0.999143, 0.00426662, 0, 0.0063316, 0.9987, 0.00447625, 0, 0.00998679, 0.996363, 0.00455323, 0, 0.0144569, 0.994021, 0.00461052, 0, 0.0197151, 0.992372, 0.00476359, 0, 0.0257344, 0.991007, 0.00499101, 0, 0.0324882, 0.988767, 0.0051972, 0, 0.0399517, 0.984872, 0.00528407, 0, 0.0481022, 0.982004, 0.00548926, 0, 0.0569191, 0.977714, 0.00564385, 0, 0.0663839, 0.973076, 0.0057693, 0, 0.0764801, 0.967565, 0.0058924, 0, 0.0871928, 0.961384, 0.00599629, 0, 0.0985095, 0.954435, 0.00605998, 0, 0.110419, 0.946303, 0.0061133, 0, 0.122912, 0.937662, 0.00612028, 0, 0.13598, 0.927867, 0.00612209, 0, 0.149617, 0.916475, 0.00604813, 0, 0.163817, 0.90541, 0.00603088, 0, 0.178577, 0.891591, 0.00592218, 0, 0.193894, 0.877573, 0.00578854, 0, 0.209767, 0.862511, 0.00566648, 0, 0.226196, 0.846861, 0.00551481, 0, 0.243182, 0.83068, 0.00533754, 0, 0.260728, 0.815725, 0.00515487, 0, 0.278837, 0.802321, 0.0049655, 0, 0.297515, 0.787826, 0.00475421, 0, 0.316768, 0.773454, 0.00456002, 0, 0.336605, 0.758224, 0.00434727, 0, 0.357034, 0.74265, 0.00414444, 0, 0.378067, 0.726729, 0.00393738, 0, 0.399717, 0.710155, 0.00373575, 0, 0.421998, 0.693312, 0.00353736, 0, 0.444928, 0.67653, 0.00334368, 0, 0.468523, 0.659444, 0.00315981, 0, 0.492806, 0.642051, 0.00297809, 0, 0.517798, 0.625758, 0.00280592, 0, 0.543525, 0.609615, 0.00264254, 0, 0.570012, 0.592919, 0.00248459, 0, 0.597288, 0.576298, 0.00233327, 0, 0.625379, 0.559489, 0.00219519, 0, 0.654307, 0.542891, 0.00205441, 0, 0.684084, 0.526255, 0.00193385, 0, 0.714693, 0.509853, 0.00180745, 0, 0.746044, 0.494131, 0.00169817, 0, 0.777778, 0.478114, 0.0015913, 0, 0.809524, 0.462274, 0.00148981, 0, 0.84127, 0.446412, 0.00139537, 0, 0.873016, 0.431274, 0.00130984, 0, 0.904762, 0.41635, 0.00122403, 0, 0.936508, 0.401476, 0.00114809, 0, 0.968254, 0.386993, 0.00107563, 0, 1, 1, 0.00488216, 0, 0, 1, 0.0048822, 0, 0, 1, 0.00488265, 0, 0, 0.999997, 0.00488463, 0, 0, 0.999988, 0.00488999, 0, 0, 0.999974, 0.00490129, 0, 0, 0.999946, 0.00492191, 0, 0, 0.999897, 0.00495598, 0, 0, 0.999825, 0.00500855, 0, 0.0000744791, 0.999718, 0.00508559, 0, 0.000712744, 0.999565, 0.005194, 0, 0.00215249, 0.999352, 0.00534147, 0, 0.00444576, 0.999046, 0.00553523, 0, 0.00759218, 0.998492, 0.00577016, 0, 0.0115714, 0.995564, 0.00578487, 0, 0.0163557, 0.993339, 0.00586414, 0, 0.021915, 0.991834, 0.00606002, 0, 0.0282201, 0.990496, 0.00633312, 0, 0.0352433, 0.987826, 0.00651941, 0, 0.042959, 0.98383, 0.00660842, 0, 0.0513439, 0.98109, 0.00685523, 0, 0.0603772, 0.976131, 0.00695778, 0, 0.0700402, 0.971922, 0.00714236, 0, 0.0803163, 0.965901, 0.00721437, 0, 0.0911908, 0.959606, 0.00732017, 0, 0.102651, 0.952504, 0.00735788, 0, 0.114686, 0.944365, 0.00738493, 0, 0.127286, 0.935652, 0.00737969, 0, 0.140443, 0.925813, 0.00733612, 0, 0.154151, 0.914397, 0.00723094, 0, 0.168405, 0.903257, 0.00714002, 0, 0.183201, 0.890015, 0.00700149, 0, 0.198536, 0.876014, 0.00682813, 0, 0.214409, 0.861436, 0.00665567, 0, 0.23082, 0.845752, 0.00644526, 0, 0.24777, 0.829169, 0.00621635, 0, 0.265263, 0.813435, 0.00597789, 0, 0.283301, 0.799701, 0.00575694, 0, 0.301889, 0.785726, 0.00549866, 0, 0.321035, 0.77152, 0.0052503, 0, 0.340746, 0.75683, 0.00499619, 0, 0.361032, 0.741951, 0.0047543, 0, 0.381904, 0.726367, 0.0045084, 0, 0.403374, 0.710537, 0.00426784, 0, 0.425457, 0.693965, 0.00403487, 0, 0.448169, 0.677724, 0.0038075, 0, 0.47153, 0.66117, 0.00359431, 0, 0.495561, 0.644274, 0.00338354, 0, 0.520284, 0.627449, 0.00318163, 0, 0.545725, 0.611645, 0.00299672, 0, 0.571911, 0.595614, 0.00281016, 0, 0.598873, 0.579426, 0.00264252, 0, 0.62664, 0.563016, 0.00247509, 0, 0.655239, 0.546728, 0.00232647, 0, 0.684692, 0.530539, 0.00217803, 0, 0.714999, 0.514164, 0.00204216, 0, 0.746106, 0.498344, 0.00191403, 0, 0.777778, 0.482957, 0.00179203, 0, 0.809524, 0.467336, 0.00167695, 0, 0.84127, 0.451994, 0.00157567, 0, 0.873016, 0.436514, 0.00147113, 0, 0.904762, 0.42178, 0.00138034, 0, 0.936508, 0.407271, 0.00129219, 0, 0.968254, 0.392822, 0.0012098, 0, 1, 1, 0.00637427, 0, 0, 1, 0.00637431, 0, 0, 0.999999, 0.00637485, 0, 0, 0.999996, 0.00637721, 0, 0, 0.999987, 0.00638357, 0, 0, 0.999971, 0.006397, 0, 0, 0.999939, 0.00642142, 0, 0, 0.999888, 0.00646177, 0, 0, 0.999807, 0.00652387, 0, 0.000207916, 0.999689, 0.00661454, 0, 0.00112051, 0.99952, 0.00674155, 0, 0.00287719, 0.999283, 0.00691313, 0, 0.00550145, 0.998936, 0.00713598, 0, 0.00897928, 0.998165, 0.00738501, 0, 0.0132829, 0.994847, 0.00734388, 0, 0.01838, 0.993182, 0.00749991, 0, 0.0242381, 0.991665, 0.0077246, 0, 0.030826, 0.989708, 0.00797579, 0, 0.0381152, 0.986663, 0.00813011, 0, 0.0460794, 0.983288, 0.00830365, 0, 0.0546951, 0.980104, 0.00853496, 0, 0.0639411, 0.974855, 0.00861045, 0, 0.0737988, 0.97045, 0.00879133, 0, 0.0842516, 0.964509, 0.00886377, 0, 0.0952848, 0.957594, 0.00890346, 0, 0.106886, 0.950546, 0.00893289, 0, 0.119044, 0.942225, 0.00890074, 0, 0.131749, 0.933365, 0.00886826, 0, 0.144994, 0.923202, 0.0087316, 0, 0.158772, 0.912605, 0.00863082, 0, 0.173078, 0.901099, 0.00847403, 0, 0.187908, 0.888177, 0.00825838, 0, 0.203261, 0.873955, 0.00801834, 0, 0.219134, 0.860091, 0.00779026, 0, 0.235527, 0.84434, 0.00752478, 0, 0.252443, 0.828517, 0.00724074, 0, 0.269883, 0.81239, 0.00693769, 0, 0.287851, 0.79721, 0.00664817, 0, 0.306352, 0.783489, 0.00634763, 0, 0.325393, 0.769514, 0.00604221, 0, 0.344981, 0.755419, 0.00573568, 0, 0.365126, 0.741083, 0.00544359, 0, 0.385839, 0.726059, 0.00515515, 0, 0.407132, 0.710809, 0.00487139, 0, 0.42902, 0.695052, 0.00459846, 0, 0.45152, 0.678886, 0.00433412, 0, 0.474651, 0.663042, 0.00407981, 0, 0.498433, 0.646634, 0.00384264, 0, 0.52289, 0.630117, 0.00360897, 0, 0.548048, 0.613804, 0.00338863, 0, 0.573936, 0.598338, 0.00318486, 0, 0.600584, 0.582687, 0.00298377, 0, 0.628027, 0.566809, 0.00280082, 0, 0.656295, 0.550817, 0.00262255, 0, 0.685417, 0.534937, 0.00245835, 0, 0.715406, 0.519151, 0.00230574, 0, 0.74624, 0.503118, 0.0021549, 0, 0.777778, 0.487723, 0.00202008, 0, 0.809524, 0.472725, 0.00189355, 0, 0.84127, 0.457599, 0.00177108, 0, 0.873016, 0.442558, 0.00165843, 0, 0.904762, 0.427624, 0.00155494, 0, 0.936508, 0.413171, 0.00145273, 0, 0.968254, 0.399122, 0.00136454, 0, 1, 1, 0.00826496, 0, 0, 1, 0.00826499, 0, 0, 1, 0.00826564, 0, 0, 0.999996, 0.00826842, 0, 0, 0.999987, 0.00827589, 0, 0, 0.999967, 0.00829167, 0, 0, 0.999933, 0.00832037, 0, 0, 0.999876, 0.00836768, 0, 0.0000109338, 0.999786, 0.00844031, 0, 0.000427145, 0.999655, 0.00854603, 0, 0.0016384, 0.999468, 0.00869337, 0, 0.00372392, 0.999203, 0.008891, 0, 0.00668513, 0.998803, 0.00914387, 0, 0.0104968, 0.99748, 0.00935838, 0, 0.015125, 0.994446, 0.00933309, 0, 0.0205338, 0.99292, 0.00953084, 0, 0.0266884, 0.991414, 0.0097893, 0, 0.0335565, 0.989049, 0.0100228, 0, 0.0411086, 0.98582, 0.0101664, 0, 0.0493181, 0.982441, 0.0103582, 0, 0.0581613, 0.978595, 0.0105292, 0, 0.0676169, 0.973495, 0.0106274, 0, 0.0776661, 0.968405, 0.0107261, 0, 0.0882926, 0.962717, 0.0108234, 0, 0.0994817, 0.955478, 0.0108102, 0, 0.111221, 0.948275, 0.0107914, 0, 0.123499, 0.940006, 0.0107161, 0, 0.136308, 0.930831, 0.0106309, 0, 0.149639, 0.920648, 0.0104083, 0, 0.163485, 0.910205, 0.0102312, 0, 0.177843, 0.898445, 0.0100051, 0, 0.192707, 0.885986, 0.00971928, 0, 0.208077, 0.872204, 0.00940747, 0, 0.22395, 0.858436, 0.0091085, 0, 0.240326, 0.843454, 0.00876595, 0, 0.257208, 0.827437, 0.00839794, 0, 0.274596, 0.811488, 0.00803692, 0, 0.292496, 0.796039, 0.00767352, 0, 0.310911, 0.781083, 0.0073097, 0, 0.329849, 0.767642, 0.00694032, 0, 0.349316, 0.753901, 0.00657476, 0, 0.369323, 0.740131, 0.00622699, 0, 0.38988, 0.725845, 0.0058838, 0, 0.410999, 0.710991, 0.00555586, 0, 0.432696, 0.696002, 0.00523089, 0, 0.454987, 0.680461, 0.00492494, 0, 0.47789, 0.664875, 0.00463464, 0, 0.501426, 0.649273, 0.00435422, 0, 0.52562, 0.63302, 0.0040875, 0, 0.550498, 0.61705, 0.00384075, 0, 0.576089, 0.601154, 0.00359557, 0, 0.602427, 0.586008, 0.00337636, 0, 0.629544, 0.570699, 0.00316019, 0, 0.657479, 0.555166, 0.00296033, 0, 0.686264, 0.539645, 0.00277552, 0, 0.715924, 0.524159, 0.00259499, 0, 0.746459, 0.508682, 0.00243257, 0, 0.777789, 0.493163, 0.00227851, 0, 0.809524, 0.478004, 0.00213083, 0, 0.84127, 0.46347, 0.00199502, 0, 0.873016, 0.448778, 0.00186967, 0, 0.904762, 0.434105, 0.00174732, 0, 0.936508, 0.419576, 0.00163861, 0, 0.968254, 0.405541, 0.00153341, 0, 1, 1, 0.0106462, 0, 0, 1, 0.0106462, 0, 0, 0.999999, 0.010647, 0, 0, 0.999995, 0.0106502, 0, 0, 0.999985, 0.0106589, 0, 0, 0.999964, 0.0106773, 0, 0, 0.999925, 0.0107106, 0, 0, 0.999861, 0.0107655, 0, 0.0000712986, 0.999763, 0.0108497, 0, 0.000743959, 0.999616, 0.0109716, 0, 0.00227361, 0.999408, 0.0111408, 0, 0.0046983, 0.999112, 0.0113659, 0, 0.00800158, 0.998637, 0.0116475, 0, 0.0121493, 0.996223, 0.0117231, 0, 0.0171023, 0.994006, 0.0118064, 0, 0.0228218, 0.992444, 0.0120254, 0, 0.0292711, 0.991028, 0.0123314, 0, 0.036417, 0.98803, 0.0124954, 0, 0.0442295, 0.984816, 0.0126538, 0, 0.0526815, 0.981399, 0.0128537, 0, 0.0617492, 0.977085, 0.0129694, 0, 0.0714114, 0.972154, 0.013091, 0, 0.0816495, 0.966617, 0.0131166, 0, 0.0924472, 0.960628, 0.0131583, 0, 0.10379, 0.953295, 0.0131094, 0, 0.115665, 0.94575, 0.0129966, 0, 0.128062, 0.937654, 0.0128796, 0, 0.140972, 0.927716, 0.0126477, 0, 0.154387, 0.917932, 0.0123889, 0, 0.168301, 0.907719, 0.012131, 0, 0.182709, 0.89584, 0.0118013, 0, 0.197608, 0.883526, 0.0114145, 0, 0.212994, 0.870301, 0.0110075, 0, 0.228867, 0.856272, 0.0106019, 0, 0.245227, 0.842251, 0.0101938, 0, 0.262074, 0.826466, 0.00973254, 0, 0.279412, 0.810859, 0.0092846, 0, 0.297244, 0.795051, 0.00883304, 0, 0.315575, 0.780053, 0.00840272, 0, 0.334412, 0.76575, 0.00796438, 0, 0.35376, 0.752298, 0.00752526, 0, 0.373631, 0.739153, 0.00711486, 0, 0.394034, 0.725514, 0.00670361, 0, 0.414983, 0.711473, 0.00632656, 0, 0.436491, 0.696936, 0.00595206, 0, 0.458575, 0.682126, 0.00559191, 0, 0.481253, 0.667027, 0.00525362, 0, 0.504547, 0.651875, 0.00493805, 0, 0.528481, 0.636463, 0.00462848, 0, 0.553081, 0.620641, 0.00433936, 0, 0.578377, 0.604931, 0.00407, 0, 0.604404, 0.589549, 0.00380864, 0, 0.631197, 0.574712, 0.00357049, 0, 0.658795, 0.559775, 0.00334466, 0, 0.687238, 0.544514, 0.00312505, 0, 0.716559, 0.529555, 0.00293199, 0, 0.746776, 0.514402, 0.00274204, 0, 0.777849, 0.499302, 0.00256647, 0, 0.809524, 0.484114, 0.00239901, 0, 0.84127, 0.469308, 0.00225148, 0, 0.873016, 0.455133, 0.00210178, 0, 0.904762, 0.440939, 0.0019727, 0, 0.936508, 0.426627, 0.00184382, 0, 0.968254, 0.412509, 0.00172548, 0, 1, 1, 0.013628, 0, 0, 1, 0.0136281, 0, 0, 0.999999, 0.0136289, 0, 0, 0.999995, 0.0136327, 0, 0, 0.999983, 0.0136427, 0, 0, 0.99996, 0.0136638, 0, 0, 0.999917, 0.0137022, 0, 0, 0.999846, 0.0137652, 0, 0.000204597, 0.999736, 0.0138615, 0, 0.00116837, 0.999573, 0.0140007, 0, 0.00303325, 0.99934, 0.0141927, 0, 0.00580613, 0.999004, 0.0144457, 0, 0.00945626, 0.998407, 0.0147489, 0, 0.0139421, 0.995464, 0.014731, 0, 0.0192202, 0.993328, 0.0148283, 0, 0.0252495, 0.991799, 0.0150797, 0, 0.0319921, 0.990397, 0.0154316, 0, 0.0394138, 0.986835, 0.0155005, 0, 0.0474843, 0.983938, 0.0157308, 0, 0.0561763, 0.980154, 0.0158753, 0, 0.0654661, 0.975659, 0.0159581, 0, 0.0753326, 0.970171, 0.0159832, 0, 0.0857571, 0.964803, 0.0160084, 0, 0.0967236, 0.958366, 0.0159484, 0, 0.108218, 0.950613, 0.0158001, 0, 0.120227, 0.942874, 0.0155845, 0, 0.132741, 0.935005, 0.0154292, 0, 0.145751, 0.924991, 0.0150742, 0, 0.159249, 0.914814, 0.0146757, 0, 0.17323, 0.904743, 0.0143097, 0, 0.187687, 0.893216, 0.0138695, 0, 0.202619, 0.880769, 0.0133706, 0, 0.218021, 0.868136, 0.0128606, 0, 0.233894, 0.85469, 0.0123403, 0, 0.250238, 0.840593, 0.0118091, 0, 0.267052, 0.825808, 0.011253, 0, 0.284341, 0.81009, 0.0107099, 0, 0.302106, 0.79504, 0.0101636, 0, 0.320354, 0.779757, 0.00964041, 0, 0.33909, 0.764697, 0.00911896, 0, 0.358322, 0.750913, 0.00859533, 0, 0.378059, 0.738175, 0.00811592, 0, 0.398311, 0.725242, 0.00764504, 0, 0.41909, 0.711864, 0.00718885, 0, 0.440412, 0.698009, 0.00675843, 0, 0.462292, 0.683841, 0.00634984, 0, 0.484748, 0.669391, 0.00595502, 0, 0.507802, 0.654731, 0.00558671, 0, 0.531477, 0.639805, 0.00523578, 0, 0.555802, 0.624789, 0.00490834, 0, 0.580805, 0.609325, 0.00459448, 0, 0.606522, 0.593975, 0.00430342, 0, 0.63299, 0.578983, 0.00403019, 0, 0.66025, 0.564442, 0.0037707, 0, 0.688346, 0.549835, 0.0035316, 0, 0.717319, 0.535039, 0.00330255, 0, 0.7472, 0.520403, 0.00308932, 0, 0.777982, 0.505687, 0.00289335, 0, 0.809524, 0.490939, 0.00270818, 0, 0.84127, 0.476233, 0.0025343, 0, 0.873016, 0.461624, 0.00237097, 0, 0.904762, 0.447833, 0.00222065, 0, 0.936508, 0.433992, 0.00207561, 0, 0.968254, 0.420147, 0.00194955, 0, 1, 1, 0.0173415, 0, 0, 1, 0.0173416, 0, 0, 0.999999, 0.0173426, 0, 0, 0.999995, 0.0173468, 0, 0, 0.999983, 0.0173582, 0, 0, 0.999954, 0.0173822, 0, 0, 0.999908, 0.0174258, 0, 0.00000669501, 0.999828, 0.0174973, 0, 0.000427399, 0.999705, 0.0176063, 0, 0.00171019, 0.999524, 0.0177631, 0, 0.0039248, 0.999263, 0.0179781, 0, 0.00705382, 0.998878, 0.018258, 0, 0.0110552, 0.998012, 0.0185551, 0, 0.0158812, 0.994614, 0.0184264, 0, 0.0214852, 0.993132, 0.0186385, 0, 0.0278239, 0.991563, 0.0189067, 0, 0.0348585, 0.989298, 0.0191577, 0, 0.0425544, 0.986036, 0.0192522, 0, 0.050881, 0.982558, 0.0194063, 0, 0.059811, 0.978531, 0.019486, 0, 0.0693209, 0.974198, 0.0195847, 0, 0.0793895, 0.968148, 0.0194749, 0, 0.0899984, 0.962565, 0.0194277, 0, 0.101132, 0.956041, 0.0192991, 0, 0.112775, 0.947749, 0.0189893, 0, 0.124917, 0.94018, 0.018704, 0, 0.137547, 0.93165, 0.0183458, 0, 0.150655, 0.921798, 0.0178775, 0, 0.164236, 0.911573, 0.0173618, 0, 0.178281, 0.901569, 0.0168482, 0, 0.192788, 0.890341, 0.016265, 0, 0.207752, 0.877835, 0.0156199, 0, 0.223171, 0.865472, 0.0149516, 0, 0.239044, 0.852905, 0.0143274, 0, 0.255371, 0.838906, 0.0136643, 0, 0.272153, 0.824888, 0.0129903, 0, 0.289393, 0.809977, 0.0123218, 0, 0.307093, 0.794697, 0.0116572, 0, 0.325259, 0.780028, 0.0110307, 0, 0.343896, 0.765124, 0.0104236, 0, 0.363012, 0.750411, 0.0098219, 0, 0.382617, 0.737264, 0.00924397, 0, 0.402719, 0.724799, 0.00868719, 0, 0.423332, 0.712253, 0.00816476, 0, 0.444469, 0.699267, 0.00767262, 0, 0.466146, 0.685618, 0.00719746, 0, 0.488383, 0.671736, 0.00673916, 0, 0.511199, 0.657777, 0.00631937, 0, 0.534618, 0.643497, 0.00592411, 0, 0.558668, 0.62889, 0.00553928, 0, 0.58338, 0.614299, 0.0051934, 0, 0.608787, 0.599197, 0.00485985, 0, 0.634929, 0.584175, 0.00454357, 0, 0.661849, 0.569541, 0.00425787, 0, 0.689594, 0.555193, 0.00397905, 0, 0.718211, 0.540947, 0.00372364, 0, 0.747742, 0.526593, 0.00348599, 0, 0.778205, 0.512335, 0.00326103, 0, 0.80953, 0.498017, 0.00305137, 0, 0.84127, 0.483609, 0.00285485, 0, 0.873016, 0.469368, 0.00267472, 0, 0.904762, 0.455037, 0.00249945, 0, 0.936508, 0.441493, 0.00234792, 0, 0.968254, 0.428147, 0.00219936, 0, 1, 1, 0.0219422, 0, 0, 1, 0.0219423, 0, 0, 0.999998, 0.0219434, 0, 0, 0.999993, 0.0219481, 0, 0, 0.999981, 0.021961, 0, 0, 0.999949, 0.0219879, 0, 0, 0.999896, 0.0220367, 0, 0.0000593194, 0.999808, 0.0221167, 0, 0.00075364, 0.99967, 0.0222383, 0, 0.00237884, 0.999466, 0.0224125, 0, 0.00495612, 0.999174, 0.0226495, 0, 0.00844887, 0.998725, 0.0229525, 0, 0.0128058, 0.996979, 0.0231123, 0, 0.0179742, 0.994317, 0.0230742, 0, 0.0239047, 0.992781, 0.0232895, 0, 0.0305526, 0.991191, 0.0235734, 0, 0.0378786, 0.987787, 0.0236152, 0, 0.0458475, 0.985092, 0.0237994, 0, 0.0544287, 0.981121, 0.0238553, 0, 0.0635952, 0.976924, 0.0238706, 0, 0.0733233, 0.97218, 0.0238704, 0, 0.0835922, 0.965956, 0.0236598, 0, 0.0943839, 0.959998, 0.0234735, 0, 0.105682, 0.953245, 0.0232277, 0, 0.117474, 0.944445, 0.0226973, 0, 0.129747, 0.937087, 0.0223527, 0, 0.142491, 0.928341, 0.0218144, 0, 0.155697, 0.9184, 0.0211516, 0, 0.169358, 0.907959, 0.0204553, 0, 0.183469, 0.89808, 0.0197673, 0, 0.198024, 0.887047, 0.0189915, 0, 0.21302, 0.875221, 0.0182082, 0, 0.228455, 0.86269, 0.0173584, 0, 0.244329, 0.850735, 0.0165718, 0, 0.260639, 0.837545, 0.0157524, 0, 0.277389, 0.823639, 0.0149482, 0, 0.29458, 0.809699, 0.0141431, 0, 0.312216, 0.794797, 0.0133527, 0, 0.3303, 0.780578, 0.0126193, 0, 0.34884, 0.766019, 0.0118914, 0, 0.367842, 0.751447, 0.0111839, 0, 0.387315, 0.737275, 0.010514, 0, 0.40727, 0.724545, 0.00987277, 0, 0.427717, 0.712644, 0.00926569, 0, 0.448671, 0.700432, 0.00869029, 0, 0.470149, 0.687664, 0.00814691, 0, 0.492167, 0.674288, 0.00763012, 0, 0.514746, 0.660966, 0.00714437, 0, 0.537911, 0.647264, 0.00668457, 0, 0.561688, 0.633431, 0.00626581, 0, 0.586108, 0.619133, 0.00585593, 0, 0.611206, 0.604935, 0.00548188, 0, 0.637022, 0.590236, 0.00513288, 0, 0.663599, 0.575473, 0.0047906, 0, 0.690989, 0.561228, 0.00448895, 0, 0.719242, 0.547054, 0.00420233, 0, 0.748411, 0.533175, 0.00392869, 0, 0.778531, 0.519163, 0.00367445, 0, 0.809583, 0.505328, 0.00344097, 0, 0.84127, 0.491446, 0.00322003, 0, 0.873016, 0.477356, 0.00301283, 0, 0.904762, 0.46356, 0.00282592, 0, 0.936508, 0.449623, 0.00264956, 0, 0.968254, 0.436068, 0.00246956, 0, 1, 1, 0.0276135, 0, 0, 1, 0.0276136, 0, 0, 0.999998, 0.0276148, 0, 0, 0.999993, 0.0276201, 0, 0, 0.999976, 0.0276342, 0, 0, 0.999945, 0.027664, 0, 0, 0.999884, 0.0277179, 0, 0.00018679, 0.999784, 0.027806, 0, 0.00119607, 0.99963, 0.0279394, 0, 0.00318407, 0.999401, 0.0281295, 0, 0.00613601, 0.999066, 0.0283858, 0, 0.00999963, 0.998524, 0.0287027, 0, 0.0147164, 0.995702, 0.0286256, 0, 0.0202295, 0.993593, 0.0286733, 0, 0.0264876, 0.992067, 0.0288989, 0, 0.0334452, 0.990548, 0.0292135, 0, 0.0410621, 0.986775, 0.0291296, 0, 0.0493032, 0.984054, 0.0293099, 0, 0.0581381, 0.979481, 0.0291881, 0, 0.0675397, 0.975297, 0.0291598, 0, 0.0774848, 0.96981, 0.028954, 0, 0.0879528, 0.963524, 0.028628, 0, 0.0989258, 0.957398, 0.0283135, 0, 0.110388, 0.950088, 0.0278469, 0, 0.122327, 0.941538, 0.0271798, 0, 0.134729, 0.933332, 0.0265388, 0, 0.147587, 0.924392, 0.0257776, 0, 0.160889, 0.914581, 0.024916, 0, 0.174631, 0.904347, 0.0240242, 0, 0.188806, 0.894324, 0.0231229, 0, 0.203409, 0.883724, 0.022153, 0, 0.218437, 0.872207, 0.0211355, 0, 0.233888, 0.859927, 0.0201048, 0, 0.249761, 0.848373, 0.0191263, 0, 0.266056, 0.836023, 0.0181306, 0, 0.282774, 0.82289, 0.0171718, 0, 0.299917, 0.809324, 0.0162196, 0, 0.317488, 0.795361, 0.0152622, 0, 0.335493, 0.781253, 0.01439, 0, 0.353936, 0.767338, 0.013533, 0, 0.372825, 0.753156, 0.0127244, 0, 0.392168, 0.739122, 0.0119454, 0, 0.411976, 0.725358, 0.0112054, 0, 0.432259, 0.712949, 0.010487, 0, 0.453032, 0.701621, 0.00984032, 0, 0.47431, 0.689703, 0.00921495, 0, 0.496111, 0.677216, 0.00862492, 0, 0.518456, 0.664217, 0.00806882, 0, 0.541367, 0.65137, 0.00755922, 0, 0.564872, 0.638, 0.00705705, 0, 0.589001, 0.62453, 0.00661266, 0, 0.613789, 0.610601, 0.00618432, 0, 0.639277, 0.59676, 0.00578033, 0, 0.66551, 0.582433, 0.00540927, 0, 0.692539, 0.568026, 0.00506104, 0, 0.720422, 0.55414, 0.0047353, 0, 0.749216, 0.540178, 0.00442889, 0, 0.778974, 0.526513, 0.00414363, 0, 0.809711, 0.512954, 0.00388237, 0, 0.84127, 0.499403, 0.00362875, 0, 0.873016, 0.486026, 0.00340827, 0, 0.904762, 0.472345, 0.00318598, 0, 0.936508, 0.458828, 0.00297635, 0, 0.968254, 0.445379, 0.00279447, 0, 1, 1, 0.0345716, 0, 0, 1, 0.0345717, 0, 0, 0.999999, 0.034573, 0, 0, 0.999991, 0.0345787, 0, 0, 0.999974, 0.0345941, 0, 0, 0.999937, 0.0346263, 0, 0.00000188589, 0.999869, 0.0346847, 0, 0.000409238, 0.999757, 0.0347798, 0, 0.0017674, 0.999582, 0.0349233, 0, 0.00413658, 0.999322, 0.0351265, 0, 0.00747408, 0.998939, 0.0353967, 0, 0.0117157, 0.998219, 0.0357018, 0, 0.0167966, 0.994974, 0.0354726, 0, 0.0226572, 0.993201, 0.0355621, 0, 0.0292445, 0.991573, 0.0357641, 0, 0.0365123, 0.989301, 0.0359252, 0, 0.0444203, 0.985712, 0.0358017, 0, 0.0529334, 0.982411, 0.0358353, 0, 0.0620214, 0.977827, 0.035617, 0, 0.0716574, 0.973278, 0.0354398, 0, 0.0818186, 0.967397, 0.0350483, 0, 0.0924846, 0.960696, 0.0344795, 0, 0.103638, 0.954349, 0.0339861, 0, 0.115263, 0.946066, 0.0331323, 0, 0.127348, 0.938012, 0.032359, 0, 0.13988, 0.929413, 0.0314413, 0, 0.152849, 0.920355, 0.0304103, 0, 0.166248, 0.910586, 0.0292785, 0, 0.18007, 0.900609, 0.0281391, 0, 0.194308, 0.890093, 0.0269103, 0, 0.208958, 0.880013, 0.0257269, 0, 0.224018, 0.869001, 0.0244671, 0, 0.239485, 0.85751, 0.0232252, 0, 0.255359, 0.84582, 0.0220117, 0, 0.271638, 0.834383, 0.0208274, 0, 0.288324, 0.822158, 0.0196628, 0, 0.305419, 0.809056, 0.0185306, 0, 0.322927, 0.795832, 0.0174174, 0, 0.340851, 0.782547, 0.0163758, 0, 0.359199, 0.7689, 0.015391, 0, 0.377975, 0.755526, 0.0144488, 0, 0.397189, 0.741681, 0.0135372, 0, 0.416851, 0.728178, 0.0126957, 0, 0.436971, 0.714642, 0.0118812, 0, 0.457564, 0.702756, 0.0111165, 0, 0.478644, 0.69175, 0.0104145, 0, 0.500229, 0.680159, 0.00974439, 0, 0.522339, 0.668073, 0.00911926, 0, 0.544997, 0.655405, 0.00851393, 0, 0.56823, 0.642921, 0.00797637, 0, 0.592068, 0.629993, 0.00745119, 0, 0.616546, 0.616828, 0.00696972, 0, 0.641705, 0.603305, 0.00652425, 0, 0.66759, 0.589833, 0.00610188, 0, 0.694255, 0.575945, 0.00570834, 0, 0.72176, 0.561745, 0.00533384, 0, 0.750168, 0.548277, 0.00500001, 0, 0.779545, 0.534467, 0.00467582, 0, 0.809933, 0.521032, 0.00438092, 0, 0.841272, 0.507877, 0.00410348, 0, 0.873016, 0.494654, 0.00383618, 0, 0.904762, 0.481592, 0.00358699, 0, 0.936508, 0.468509, 0.00337281, 0, 0.968254, 0.455293, 0.00316196, 0, 1, 1, 0.0430698, 0, 0, 1, 0.0430699, 0, 0, 0.999998, 0.0430713, 0, 0, 0.999991, 0.0430773, 0, 0, 0.99997, 0.0430936, 0, 0, 0.999928, 0.0431277, 0, 0.0000406396, 0.999852, 0.0431893, 0, 0.000744376, 0.999724, 0.0432895, 0, 0.0024806, 0.999527, 0.0434397, 0, 0.00524779, 0.99923, 0.0436507, 0, 0.00898164, 0.998783, 0.0439255, 0, 0.0136083, 0.997507, 0.0441104, 0, 0.0190582, 0.994418, 0.0438225, 0, 0.0252694, 0.992864, 0.0439396, 0, 0.0321879, 0.991127, 0.0440962, 0, 0.039767, 0.987331, 0.0438408, 0, 0.0479667, 0.984819, 0.0438991, 0, 0.056752, 0.980384, 0.0435906, 0, 0.0660929, 0.975846, 0.0432543, 0, 0.075963, 0.970748, 0.0428293, 0, 0.0863398, 0.964303, 0.042153, 0, 0.0972035, 0.95772, 0.0414111, 0, 0.108537, 0.950747, 0.0405893, 0, 0.120325, 0.942533, 0.0394887, 0, 0.132554, 0.934045, 0.0383544, 0, 0.145215, 0.924942, 0.037057, 0, 0.158296, 0.915811, 0.0356993, 0, 0.17179, 0.90612, 0.0342401, 0, 0.185691, 0.896434, 0.0328078, 0, 0.199993, 0.886021, 0.031288, 0, 0.214691, 0.876081, 0.0297776, 0, 0.229782, 0.865608, 0.0282334, 0, 0.245265, 0.854924, 0.026749, 0, 0.261138, 0.843607, 0.02526, 0, 0.277401, 0.832456, 0.0238214, 0, 0.294056, 0.821342, 0.0224682, 0, 0.311104, 0.809303, 0.0211297, 0, 0.328548, 0.796468, 0.0198387, 0, 0.346394, 0.784046, 0.0186227, 0, 0.364645, 0.771262, 0.0174561, 0, 0.38331, 0.758118, 0.0163806, 0, 0.402396, 0.745075, 0.0153287, 0, 0.421912, 0.731926, 0.0143647, 0, 0.44187, 0.71863, 0.0134363, 0, 0.462283, 0.705414, 0.0125603, 0, 0.483165, 0.693792, 0.0117508, 0, 0.504535, 0.683108, 0.0110016, 0, 0.52641, 0.67183, 0.0102757, 0, 0.548816, 0.66015, 0.00962044, 0, 0.571776, 0.647907, 0.00898031, 0, 0.595323, 0.635734, 0.00840811, 0, 0.619489, 0.623208, 0.00786211, 0, 0.644317, 0.610438, 0.00734953, 0, 0.669852, 0.597345, 0.00687688, 0, 0.696148, 0.584138, 0.00643469, 0, 0.723267, 0.5707, 0.00602236, 0, 0.75128, 0.556966, 0.0056324, 0, 0.780258, 0.543607, 0.00528277, 0, 0.810268, 0.530213, 0.00493999, 0, 0.841311, 0.516912, 0.00462265, 0, 0.873016, 0.503916, 0.0043307, 0, 0.904762, 0.491146, 0.00406858, 0, 0.936508, 0.478439, 0.00381436, 0, 0.968254, 0.465834, 0.00358003, 0, 1, 1, 0.0534039, 0, 0, 1, 0.053404, 0, 0, 0.999998, 0.0534055, 0, 0, 0.999989, 0.0534116, 0, 0, 0.999968, 0.0534283, 0, 0, 0.999918, 0.0534633, 0, 0.000155895, 0.99983, 0.0535262, 0, 0.00120914, 0.999685, 0.0536281, 0, 0.00334944, 0.999461, 0.0537799, 0, 0.00653077, 0.999119, 0.0539902, 0, 0.0106718, 0.998582, 0.0542524, 0, 0.0156907, 0.995919, 0.0540318, 0, 0.0215147, 0.993735, 0.0538914, 0, 0.0280801, 0.992126, 0.0539557, 0, 0.0353323, 0.990266, 0.0540401, 0, 0.0432247, 0.986317, 0.0536064, 0, 0.0517172, 0.983213, 0.0534425, 0, 0.0607754, 0.978303, 0.0528622, 0, 0.0703698, 0.973665, 0.0523363, 0, 0.0804742, 0.968091, 0.0516165, 0, 0.0910667, 0.961026, 0.0505434, 0, 0.102128, 0.954333, 0.049523, 0, 0.113641, 0.946372, 0.0481698, 0, 0.125591, 0.938254, 0.0467674, 0, 0.137965, 0.929516, 0.0452341, 0, 0.150754, 0.920106, 0.0435083, 0, 0.163947, 0.910899, 0.0417399, 0, 0.177537, 0.901532, 0.0399389, 0, 0.191516, 0.891919, 0.0380901, 0, 0.205881, 0.882006, 0.0362341, 0, 0.220626, 0.871965, 0.0343444, 0, 0.235749, 0.862145, 0.0324832, 0, 0.251248, 0.852058, 0.0306681, 0, 0.267121, 0.84161, 0.0289097, 0, 0.283368, 0.830806, 0.0272079, 0, 0.299992, 0.820476, 0.0256089, 0, 0.316992, 0.809514, 0.0240394, 0, 0.334374, 0.797865, 0.0225379, 0, 0.35214, 0.785621, 0.0211235, 0, 0.370296, 0.773765, 0.0197908, 0, 0.388849, 0.761629, 0.0185235, 0, 0.407807, 0.748891, 0.0173358, 0, 0.427178, 0.736437, 0.0162305, 0, 0.446974, 0.723707, 0.0151778, 0, 0.467207, 0.710606, 0.0141791, 0, 0.487892, 0.698019, 0.0132592, 0, 0.509046, 0.686203, 0.0123887, 0, 0.530687, 0.675692, 0.0115976, 0, 0.552839, 0.664826, 0.0108325, 0, 0.575527, 0.65349, 0.0101348, 0, 0.59878, 0.641774, 0.00947756, 0, 0.622634, 0.629794, 0.00886058, 0, 0.647128, 0.617647, 0.00828526, 0, 0.672308, 0.60534, 0.00775312, 0, 0.698231, 0.592718, 0.00726033, 0, 0.724958, 0.579746, 0.00679731, 0, 0.752563, 0.566763, 0.00636111, 0, 0.781127, 0.553515, 0.00595228, 0, 0.810733, 0.540118, 0.00556876, 0, 0.841426, 0.527325, 0.00523051, 0, 0.873016, 0.514265, 0.00490712, 0, 0.904762, 0.501406, 0.00460297, 0, 0.936508, 0.488922, 0.00431247, 0, 0.968254, 0.476541, 0.0040472, 0, 1, 1, 0.0659184, 0, 0, 1, 0.0659185, 0, 0, 0.999998, 0.06592, 0, 0, 0.999988, 0.0659259, 0, 0, 0.999963, 0.0659423, 0, 0, 0.999907, 0.0659764, 0, 0.000374198, 0.999806, 0.0660376, 0, 0.00182071, 0.999639, 0.0661361, 0, 0.0043894, 0.999378, 0.0662814, 0, 0.00800055, 0.998985, 0.0664779, 0, 0.0125594, 0.998285, 0.0666914, 0, 0.0179786, 0.995071, 0.0661989, 0, 0.0241822, 0.993172, 0.0660454, 0, 0.031106, 0.991438, 0.0660105, 0, 0.0386952, 0.988428, 0.0656875, 0, 0.0469032, 0.985218, 0.0652913, 0, 0.0556905, 0.981128, 0.0647107, 0, 0.065023, 0.976015, 0.0638491, 0, 0.0748717, 0.97097, 0.062993, 0, 0.0852112, 0.964582, 0.0617927, 0, 0.0960199, 0.957383, 0.0603626, 0, 0.107279, 0.949969, 0.0588128, 0, 0.118971, 0.941843, 0.0570274, 0, 0.131084, 0.933624, 0.0551885, 0, 0.143604, 0.924543, 0.053122, 0, 0.156521, 0.914919, 0.0508897, 0, 0.169825, 0.905773, 0.0486418, 0, 0.18351, 0.896434, 0.0463364, 0, 0.197569, 0.887195, 0.0440623, 0, 0.211997, 0.877706, 0.0417799, 0, 0.226789, 0.867719, 0.03945, 0, 0.241944, 0.858587, 0.037243, 0, 0.257458, 0.849317, 0.0350956, 0, 0.273331, 0.839585, 0.0329852, 0, 0.289563, 0.829856, 0.0310028, 0, 0.306154, 0.819589, 0.0290953, 0, 0.323108, 0.809714, 0.0272738, 0, 0.340426, 0.79934, 0.0255631, 0, 0.358113, 0.788224, 0.0239175, 0, 0.376175, 0.776619, 0.0223831, 0, 0.394616, 0.76521, 0.0209298, 0, 0.413445, 0.753716, 0.0195786, 0, 0.432671, 0.741564, 0.0183001, 0, 0.452305, 0.729413, 0.0171259, 0, 0.472358, 0.717146, 0.0159933, 0, 0.492845, 0.70436, 0.0149495, 0, 0.513783, 0.69219, 0.0139681, 0, 0.535189, 0.680289, 0.0130577, 0, 0.557087, 0.669611, 0.0122198, 0, 0.5795, 0.659113, 0.0114174, 0, 0.602459, 0.648148, 0.0106729, 0, 0.625997, 0.636905, 0.00998997, 0, 0.650154, 0.625154, 0.00934313, 0, 0.674976, 0.613481, 0.00874839, 0, 0.700518, 0.60154, 0.00818265, 0, 0.726845, 0.58943, 0.00766889, 0, 0.754032, 0.576828, 0.00717153, 0, 0.782167, 0.564194, 0.00672696, 0, 0.811344, 0.551501, 0.00630863, 0, 0.841644, 0.538635, 0.00592177, 0, 0.873016, 0.525724, 0.00554888, 0, 0.904762, 0.513209, 0.00520225, 0, 0.936508, 0.500457, 0.00488231, 0, 0.968254, 0.48799, 0.00457153, 0, 1, 1, 0.0810131, 0, 0, 1, 0.0810133, 0, 0, 0.999997, 0.0810145, 0, 0, 0.999985, 0.08102, 0, 0, 0.999956, 0.0810347, 0, 0.0000195026, 0.999893, 0.0810656, 0, 0.000719316, 0.999777, 0.0811205, 0, 0.00259774, 0.999583, 0.081208, 0, 0.00561807, 0.999281, 0.0813343, 0, 0.00967472, 0.998813, 0.0814969, 0, 0.0146627, 0.997597, 0.0815217, 0, 0.0204902, 0.994379, 0.0808502, 0, 0.0270802, 0.992744, 0.0806792, 0, 0.0343674, 0.990745, 0.0804589, 0, 0.0422974, 0.986646, 0.0796107, 0, 0.0508242, 0.983611, 0.0790913, 0, 0.0599087, 0.978869, 0.0780746, 0, 0.0695175, 0.973475, 0.0768218, 0, 0.0796223, 0.967845, 0.0754926, 0, 0.0901983, 0.960778, 0.0737063, 0, 0.101224, 0.953333, 0.0718052, 0, 0.112682, 0.945274, 0.0695946, 0, 0.124555, 0.936955, 0.0672492, 0, 0.136831, 0.928319, 0.0647732, 0, 0.149496, 0.919075, 0.0620947, 0, 0.162542, 0.909114, 0.0591816, 0, 0.175958, 0.900137, 0.0563917, 0, 0.189739, 0.891069, 0.0535392, 0, 0.203877, 0.882262, 0.0507642, 0, 0.218368, 0.873232, 0.0479793, 0, 0.233208, 0.864042, 0.045226, 0, 0.248393, 0.855002, 0.0425413, 0, 0.263923, 0.846569, 0.0400126, 0, 0.279796, 0.837714, 0.0375269, 0, 0.296012, 0.828918, 0.0352027, 0, 0.312573, 0.819783, 0.0330011, 0, 0.329479, 0.810129, 0.0308908, 0, 0.346734, 0.800866, 0.0289112, 0, 0.364342, 0.79093, 0.0270255, 0, 0.382307, 0.780593, 0.0252758, 0, 0.400637, 0.769511, 0.0236178, 0, 0.419337, 0.758558, 0.0220652, 0, 0.438418, 0.747632, 0.0206289, 0, 0.457889, 0.736146, 0.0192873, 0, 0.477761, 0.724093, 0.0180333, 0, 0.49805, 0.71234, 0.0168264, 0, 0.51877, 0.700201, 0.015746, 0, 0.53994, 0.687949, 0.0147027, 0, 0.561581, 0.676163, 0.0137512, 0, 0.583718, 0.665001, 0.0128655, 0, 0.60638, 0.65472, 0.0120366, 0, 0.629599, 0.644213, 0.0112604, 0, 0.653415, 0.633382, 0.0105413, 0, 0.677874, 0.62212, 0.00986498, 0, 0.70303, 0.610631, 0.00923308, 0, 0.728948, 0.599078, 0.00864206, 0, 0.755706, 0.587519, 0.00811784, 0, 0.783396, 0.575505, 0.00761237, 0, 0.812121, 0.563148, 0.00713949, 0, 0.841989, 0.550828, 0.00668379, 0, 0.873035, 0.538458, 0.00627715, 0, 0.904762, 0.525905, 0.00588336, 0, 0.936508, 0.513517, 0.00552687, 0, 0.968254, 0.501395, 0.00519681, 0, 1, 1, 0.0991506, 0, 0, 1, 0.0991504, 0, 0, 0.999996, 0.0991515, 0, 0, 0.999984, 0.0991558, 0, 0, 0.999947, 0.0991672, 0, 0.000114389, 0.999874, 0.0991912, 0, 0.00121503, 0.999739, 0.0992331, 0, 0.00356108, 0.999514, 0.0992983, 0, 0.00705578, 0.999159, 0.0993877, 0, 0.011574, 0.998586, 0.0994837, 0, 0.017003, 0.995731, 0.0988425, 0, 0.0232484, 0.993384, 0.098276, 0, 0.0302318, 0.991615, 0.0979269, 0, 0.0378884, 0.989029, 0.0973432, 0, 0.0461641, 0.985373, 0.0963539, 0, 0.0550136, 0.981278, 0.0952306, 0, 0.0643988, 0.975777, 0.0936233, 0, 0.0742868, 0.970526, 0.0920219, 0, 0.0846501, 0.963755, 0.0898912, 0, 0.0954644, 0.956676, 0.0876064, 0, 0.106709, 0.948099, 0.0847751, 0, 0.118367, 0.939718, 0.0818638, 0, 0.130423, 0.931305, 0.078857, 0, 0.142862, 0.922342, 0.0756127, 0, 0.155674, 0.912842, 0.0721473, 0, 0.168849, 0.903304, 0.0686195, 0, 0.182378, 0.89411, 0.0650589, 0, 0.196255, 0.885512, 0.0616022, 0, 0.210473, 0.877193, 0.0582434, 0, 0.225027, 0.86877, 0.0548979, 0, 0.239915, 0.860267, 0.0516095, 0, 0.255132, 0.851915, 0.048468, 0, 0.270678, 0.843912, 0.0454447, 0, 0.286551, 0.83604, 0.0425612, 0, 0.302751, 0.828245, 0.0398752, 0, 0.31928, 0.820159, 0.0373198, 0, 0.336138, 0.81167, 0.034916, 0, 0.35333, 0.802659, 0.0326402, 0, 0.370858, 0.793921, 0.0304901, 0, 0.388728, 0.784713, 0.0284857, 0, 0.406944, 0.774946, 0.0266186, 0, 0.425515, 0.76448, 0.0248593, 0, 0.444449, 0.753793, 0.0232114, 0, 0.463756, 0.743506, 0.0217039, 0, 0.483447, 0.732555, 0.0202841, 0, 0.503535, 0.720965, 0.0189648, 0, 0.524036, 0.709422, 0.0177189, 0, 0.544968, 0.697756, 0.0165626, 0, 0.56635, 0.685565, 0.015483, 0, 0.588208, 0.673987, 0.0144892, 0, 0.610569, 0.66244, 0.0135607, 0, 0.633466, 0.651675, 0.0126956, 0, 0.656936, 0.641598, 0.0118788, 0, 0.681025, 0.63121, 0.0111261, 0, 0.705788, 0.620514, 0.010437, 0, 0.731289, 0.609366, 0.00978747, 0, 0.757606, 0.598137, 0.00917257, 0, 0.784834, 0.586966, 0.00859778, 0, 0.813085, 0.575549, 0.00806803, 0, 0.842485, 0.563797, 0.00757294, 0, 0.87313, 0.551758, 0.00710592, 0, 0.904762, 0.539894, 0.0066841, 0, 0.936508, 0.527901, 0.00627901, 0, 0.968254, 0.515819, 0.00590506, 0, 1, 1, 0.120864, 0, 0, 1, 0.120864, 0, 0, 0.999996, 0.120864, 0, 0, 0.99998, 0.120867, 0, 0, 0.99994, 0.120872, 0, 0.000323781, 0.999852, 0.120884, 0, 0.00188693, 0.999693, 0.120903, 0, 0.00473489, 0.999426, 0.120929, 0, 0.00872704, 0.999002, 0.120955, 0, 0.0137237, 0.998235, 0.120918, 0, 0.0196068, 0.994608, 0.119764, 0, 0.0262803, 0.992997, 0.119265, 0, 0.0336657, 0.990968, 0.11863, 0, 0.0416987, 0.987002, 0.117261, 0, 0.0503261, 0.983524, 0.116009, 0, 0.0595035, 0.97875, 0.114252, 0, 0.0691935, 0.972652, 0.11193, 0, 0.0793645, 0.966613, 0.109555, 0, 0.0899894, 0.959275, 0.106612, 0, 0.101045, 0.951272, 0.103375, 0, 0.112512, 0.942323, 0.0996594, 0, 0.124372, 0.933679, 0.0958841, 0, 0.136611, 0.924822, 0.0919265, 0, 0.149216, 0.915742, 0.0878061, 0, 0.162176, 0.906348, 0.0834894, 0, 0.175482, 0.896883, 0.079085, 0, 0.189125, 0.88774, 0.0746745, 0, 0.203098, 0.87986, 0.0705773, 0, 0.217396, 0.871998, 0.0665005, 0, 0.232015, 0.864325, 0.0625413, 0, 0.24695, 0.856685, 0.0586781, 0, 0.2622, 0.84925, 0.0550063, 0, 0.277761, 0.841719, 0.0514727, 0, 0.293634, 0.834755, 0.0481398, 0, 0.309819, 0.827853, 0.0450172, 0, 0.326315, 0.820888, 0.0420969, 0, 0.343126, 0.813616, 0.0393702, 0, 0.360254, 0.805767, 0.0367771, 0, 0.377701, 0.797338, 0.0343274, 0, 0.395474, 0.789122, 0.0320529, 0, 0.413577, 0.780601, 0.0299485, 0, 0.432018, 0.771424, 0.0279812, 0, 0.450804, 0.761502, 0.0261054, 0, 0.469944, 0.751166, 0.0243942, 0, 0.489451, 0.741276, 0.0228087, 0, 0.509337, 0.730898, 0.0213265, 0, 0.529617, 0.719878, 0.0199307, 0, 0.550307, 0.708379, 0.0186574, 0, 0.571428, 0.697165, 0.0174446, 0, 0.593003, 0.685554, 0.0163144, 0, 0.615059, 0.673631, 0.015276, 0, 0.637628, 0.662385, 0.0143003, 0, 0.660746, 0.651059, 0.0134112, 0, 0.68446, 0.640451, 0.0125794, 0, 0.70882, 0.630536, 0.011793, 0, 0.733893, 0.620316, 0.0110547, 0, 0.759756, 0.609722, 0.0103668, 0, 0.786505, 0.598804, 0.00973009, 0, 0.814259, 0.587871, 0.00912812, 0, 0.843157, 0.577121, 0.00858916, 0, 0.87334, 0.566019, 0.00807333, 0, 0.904762, 0.554664, 0.00759687, 0, 0.936508, 0.543101, 0.00714759, 0, 0.968254, 0.531558, 0.00673418, 0, 1, 1, 0.146767, 0, 0, 1, 0.146767, 0, 0, 0.999997, 0.146767, 0, 0, 0.999977, 0.146765, 0, 0.00000320658, 0.999929, 0.146762, 0, 0.000682576, 0.999823, 0.146753, 0, 0.00276402, 0.999633, 0.146735, 0, 0.00614771, 0.999314, 0.146699, 0, 0.0106613, 0.998796, 0.14662, 0, 0.0161546, 0.997124, 0.146107, 0, 0.0225063, 0.994062, 0.144857, 0, 0.0296198, 0.992154, 0.144011, 0, 0.037417, 0.989186, 0.142712, 0, 0.0458348, 0.985279, 0.140926, 0, 0.0548211, 0.980826, 0.13885, 0, 0.0643326, 0.975056, 0.136168, 0, 0.074333, 0.969005, 0.133217, 0, 0.0847917, 0.961554, 0.12959, 0, 0.0956828, 0.954206, 0.125886, 0, 0.106984, 0.945046, 0.121335, 0, 0.118675, 0.935678, 0.116492, 0, 0.130741, 0.926748, 0.111635, 0, 0.143166, 0.917764, 0.106625, 0, 0.155939, 0.908358, 0.101325, 0, 0.169049, 0.899219, 0.0960249, 0, 0.182487, 0.890089, 0.0906527, 0, 0.196245, 0.881488, 0.0853905, 0, 0.210317, 0.874031, 0.0804177, 0, 0.224697, 0.866932, 0.0756005, 0, 0.23938, 0.859976, 0.0709019, 0, 0.254364, 0.853375, 0.0664391, 0, 0.269646, 0.846971, 0.0622012, 0, 0.285223, 0.840483, 0.058129, 0, 0.301096, 0.833969, 0.0542762, 0, 0.317265, 0.82806, 0.0507042, 0, 0.333729, 0.822128, 0.047368, 0, 0.350491, 0.815989, 0.044272, 0, 0.367554, 0.809336, 0.0413444, 0, 0.38492, 0.802177, 0.038601, 0, 0.402594, 0.79441, 0.0360227, 0, 0.420582, 0.786573, 0.0336383, 0, 0.438891, 0.778619, 0.0314321, 0, 0.457527, 0.77, 0.029362, 0, 0.476499, 0.760698, 0.0274102, 0, 0.49582, 0.750932, 0.0256146, 0, 0.5155, 0.740993, 0.023974, 0, 0.535555, 0.731159, 0.0224182, 0, 0.556, 0.720836, 0.0209889, 0, 0.576855, 0.709913, 0.0196411, 0, 0.598143, 0.698415, 0.0183824, 0, 0.619888, 0.68745, 0.0172222, 0, 0.642123, 0.676154, 0.0161509, 0, 0.664883, 0.664383, 0.0151397, 0, 0.688211, 0.6533, 0.0141873, 0, 0.71216, 0.642072, 0.0133105, 0, 0.736792, 0.631412, 0.0124932, 0, 0.762186, 0.621622, 0.0117408, 0, 0.788439, 0.611681, 0.0110358, 0, 0.815672, 0.60142, 0.0103775, 0, 0.844034, 0.59083, 0.00975623, 0, 0.873699, 0.580254, 0.00918084, 0, 0.904765, 0.569841, 0.00864721, 0, 0.936508, 0.559224, 0.00815731, 0, 0.968254, 0.548315, 0.00767924, 0, 1, 1, 0.177563, 0, 0, 1, 0.177563, 0, 0, 0.999994, 0.177562, 0, 0, 0.999972, 0.177555, 0, 0.0000664171, 0.999914, 0.177536, 0, 0.0012276, 0.999787, 0.177496, 0, 0.00388025, 0.999556, 0.17742, 0, 0.00783463, 0.999165, 0.177285, 0, 0.0128953, 0.9985, 0.177037, 0, 0.0189053, 0.995388, 0.175634, 0, 0.025742, 0.993102, 0.174375, 0, 0.033309, 0.990992, 0.173121, 0, 0.0415298, 0.986932, 0.170896, 0, 0.0503425, 0.982786, 0.16847, 0, 0.0596964, 0.977592, 0.165455, 0, 0.0695498, 0.971075, 0.161676, 0, 0.0798676, 0.963967, 0.157458, 0, 0.0906201, 0.956397, 0.152836, 0, 0.101783, 0.947489, 0.147467, 0, 0.113333, 0.937564, 0.14145, 0, 0.125254, 0.928182, 0.135383, 0, 0.137529, 0.919027, 0.129212, 0, 0.150144, 0.909618, 0.12276, 0, 0.163088, 0.900492, 0.116273, 0, 0.176351, 0.891671, 0.1098, 0, 0.189924, 0.883146, 0.103362, 0, 0.203799, 0.875151, 0.0970799, 0, 0.21797, 0.868338, 0.0911732, 0, 0.232433, 0.862033, 0.0854966, 0, 0.247182, 0.856107, 0.0800691, 0, 0.262216, 0.850644, 0.0749618, 0, 0.27753, 0.845261, 0.070079, 0, 0.293124, 0.839885, 0.0654321, 0, 0.308997, 0.834609, 0.0610975, 0, 0.325149, 0.829083, 0.0569741, 0, 0.341581, 0.82404, 0.0531736, 0, 0.358294, 0.818968, 0.049665, 0, 0.37529, 0.813496, 0.0463856, 0, 0.392573, 0.807533, 0.0433217, 0, 0.410148, 0.80099, 0.0404402, 0, 0.428019, 0.793891, 0.0377578, 0, 0.446192, 0.786281, 0.0352616, 0, 0.464676, 0.778773, 0.0329577, 0, 0.483478, 0.770737, 0.030808, 0, 0.502608, 0.762094, 0.0287964, 0, 0.522079, 0.752898, 0.0269254, 0, 0.541905, 0.743306, 0.0251926, 0, 0.5621, 0.733416, 0.023595, 0, 0.582684, 0.723742, 0.0221155, 0, 0.603677, 0.713542, 0.0207435, 0, 0.625106, 0.702755, 0.019434, 0, 0.646998, 0.691484, 0.0182046, 0, 0.66939, 0.680531, 0.0170771, 0, 0.692324, 0.66953, 0.0160339, 0, 0.715849, 0.658126, 0.0150677, 0, 0.740028, 0.646933, 0.0141551, 0, 0.764937, 0.636107, 0.0133179, 0, 0.790673, 0.625271, 0.0125284, 0, 0.817358, 0.615225, 0.0117937, 0, 0.84515, 0.605678, 0.0111181, 0, 0.874244, 0.59583, 0.0104759, 0, 0.904828, 0.585704, 0.00986672, 0, 0.936508, 0.575413, 0.00929712, 0, 0.968254, 0.565373, 0.00876713, 0, 1, 1, 0.214058, 0, 0, 0.999999, 0.214058, 0, 0, 0.999994, 0.214055, 0, 0, 0.999966, 0.214039, 0, 0.000259642, 0.999893, 0.213998, 0, 0.00200075, 0.999737, 0.21391, 0, 0.00527775, 0.999449, 0.213745, 0, 0.00983959, 0.99896, 0.213458, 0, 0.0154755, 0.9979, 0.212855, 0, 0.0220249, 0.994278, 0.210779, 0, 0.0293654, 0.992254, 0.20926, 0, 0.0374021, 0.98881, 0.206908, 0, 0.0460604, 0.984715, 0.204009, 0, 0.0552802, 0.979738, 0.200471, 0, 0.0650127, 0.972884, 0.195813, 0, 0.0752175, 0.965996, 0.190856, 0, 0.0858612, 0.957974, 0.185077, 0, 0.0969155, 0.949155, 0.17868, 0, 0.108356, 0.939288, 0.171513, 0, 0.120163, 0.928996, 0.163838, 0, 0.132319, 0.919563, 0.156246, 0, 0.144808, 0.910004, 0.148359, 0, 0.157618, 0.900791, 0.140417, 0, 0.170737, 0.892135, 0.132569, 0, 0.184155, 0.883803, 0.124741, 0, 0.197866, 0.876034, 0.117091, 0, 0.211861, 0.869219, 0.109835, 0, 0.226134, 0.863062, 0.102859, 0, 0.240682, 0.857795, 0.0962928, 0, 0.255499, 0.853009, 0.0900725, 0, 0.270583, 0.848603, 0.0842101, 0, 0.285931, 0.844335, 0.0786527, 0, 0.301542, 0.840208, 0.0734397, 0, 0.317415, 0.836035, 0.0685334, 0, 0.33355, 0.83172, 0.0639275, 0, 0.349948, 0.827135, 0.0595909, 0, 0.36661, 0.822797, 0.0556204, 0, 0.383539, 0.818387, 0.0519394, 0, 0.400738, 0.813565, 0.0485317, 0, 0.41821, 0.808142, 0.0453138, 0, 0.435961, 0.802212, 0.0423354, 0, 0.453997, 0.79573, 0.0395553, 0, 0.472324, 0.788741, 0.036988, 0, 0.490951, 0.781093, 0.0345688, 0, 0.509887, 0.773597, 0.0323297, 0, 0.529144, 0.765622, 0.0302719, 0, 0.548735, 0.757083, 0.0283477, 0, 0.568674, 0.747992, 0.0265562, 0, 0.588979, 0.738591, 0.0248844, 0, 0.609671, 0.728719, 0.0233342, 0, 0.630773, 0.719146, 0.0219081, 0, 0.652314, 0.709165, 0.0205711, 0, 0.674328, 0.69875, 0.0193248, 0, 0.696854, 0.687884, 0.0181582, 0, 0.719942, 0.676818, 0.0170746, 0, 0.743651, 0.666247, 0.0160718, 0, 0.768057, 0.655284, 0.0151262, 0, 0.793253, 0.64401, 0.0142561, 0, 0.819363, 0.633353, 0.0134327, 0, 0.846547, 0.622674, 0.012653, 0, 0.875017, 0.612265, 0.0119354, 0, 0.905021, 0.602455, 0.0112533, 0, 0.936508, 0.593147, 0.0106234, 0, 0.968254, 0.583592, 0.0100213, 0, 1, 1, 0.25717, 0, 0, 1, 0.25717, 0, 0, 0.999992, 0.257164, 0, 0, 0.999958, 0.257135, 0, 0.000641715, 0.999864, 0.25706, 0, 0.00305314, 0.999666, 0.256897, 0, 0.00700975, 0.999302, 0.256596, 0, 0.0122194, 0.998663, 0.25607, 0, 0.0184622, 0.995607, 0.254123, 0, 0.0255773, 0.993094, 0.252081, 0, 0.0334439, 0.9907, 0.249867, 0, 0.0419696, 0.98594, 0.246118, 0, 0.0510823, 0.981214, 0.242049, 0, 0.0607242, 0.974966, 0.236869, 0, 0.0708486, 0.967589, 0.230724, 0, 0.081417, 0.95915, 0.223635, 0, 0.0923974, 0.950257, 0.21596, 0, 0.103763, 0.940165, 0.207296, 0, 0.115491, 0.929396, 0.197901, 0, 0.127562, 0.919288, 0.188437, 0, 0.13996, 0.909428, 0.178762, 0, 0.15267, 0.900105, 0.169072, 0, 0.165679, 0.891418, 0.159478, 0, 0.178979, 0.883347, 0.15002, 0, 0.192558, 0.875992, 0.140813, 0, 0.20641, 0.869466, 0.13196, 0, 0.220529, 0.863699, 0.123501, 0, 0.234907, 0.858553, 0.115436, 0, 0.249542, 0.854379, 0.107901, 0, 0.264428, 0.850894, 0.10088, 0, 0.279564, 0.847632, 0.0942296, 0, 0.294947, 0.844571, 0.0879861, 0, 0.310575, 0.84163, 0.0821534, 0, 0.326448, 0.838542, 0.0766409, 0, 0.342566, 0.835412, 0.0715322, 0, 0.358929, 0.831899, 0.0666883, 0, 0.37554, 0.828177, 0.0622175, 0, 0.392399, 0.82416, 0.0580452, 0, 0.409511, 0.820393, 0.054267, 0, 0.426878, 0.816068, 0.0507172, 0, 0.444506, 0.811201, 0.0474041, 0, 0.4624, 0.805785, 0.0443174, 0, 0.480566, 0.799878, 0.0414562, 0, 0.499013, 0.793469, 0.0388147, 0, 0.517749, 0.786473, 0.0363453, 0, 0.536785, 0.778874, 0.0340225, 0, 0.556134, 0.771277, 0.0318599, 0, 0.575809, 0.763426, 0.0298859, 0, 0.595827, 0.755044, 0.0280357, 0, 0.616207, 0.746161, 0.0262979, 0, 0.636973, 0.737124, 0.0247295, 0, 0.65815, 0.72761, 0.0232514, 0, 0.679772, 0.717822, 0.0218755, 0, 0.701876, 0.708279, 0.0205942, 0, 0.724509, 0.698333, 0.0193947, 0, 0.74773, 0.68802, 0.0182717, 0, 0.771609, 0.677321, 0.0172044, 0, 0.79624, 0.666504, 0.0162122, 0, 0.821743, 0.656184, 0.0152924, 0, 0.84828, 0.64556, 0.0144326, 0, 0.876069, 0.634636, 0.0136157, 0, 0.905404, 0.624124, 0.0128612, 0, 0.936508, 0.613914, 0.0121435, 0, 0.968254, 0.603589, 0.0114887, 0, 1, 1, 0.307946, 0, 0, 0.999999, 0.307945, 0, 0, 0.999988, 0.307934, 0, 0.0000204479, 0.999944, 0.307886, 0, 0.00127833, 0.999824, 0.307756, 0, 0.00445047, 0.999565, 0.30748, 0, 0.00914673, 0.999085, 0.306966, 0, 0.0150498, 0.998103, 0.306004, 0, 0.0219367, 0.994249, 0.303028, 0, 0.0296485, 0.991807, 0.300435, 0, 0.038068, 0.987773, 0.296554, 0, 0.0471062, 0.982673, 0.2916, 0, 0.0566942, 0.976623, 0.285641, 0, 0.0667768, 0.968757, 0.27815, 0, 0.0773099, 0.959849, 0.269529, 0, 0.088257, 0.950663, 0.260248, 0, 0.0995879, 0.940129, 0.249704, 0, 0.111277, 0.92895, 0.238291, 0, 0.123304, 0.917996, 0.226501, 0, 0.13565, 0.907813, 0.214669, 0, 0.148299, 0.898305, 0.202835, 0, 0.161237, 0.889626, 0.191158, 0, 0.174455, 0.88175, 0.179695, 0, 0.187941, 0.874715, 0.168548, 0, 0.201687, 0.868746, 0.15792, 0, 0.215687, 0.863703, 0.147807, 0, 0.229933, 0.859315, 0.138149, 0, 0.24442, 0.855538, 0.128993, 0, 0.259145, 0.852428, 0.120414, 0, 0.274103, 0.850168, 0.112498, 0, 0.289293, 0.848132, 0.105054, 0, 0.304711, 0.846291, 0.0981087, 0, 0.320357, 0.844431, 0.0915942, 0, 0.33623, 0.842493, 0.0855056, 0, 0.35233, 0.840368, 0.0798204, 0, 0.368658, 0.83798, 0.0745097, 0, 0.385214, 0.83523, 0.0695424, 0, 0.402002, 0.832091, 0.0649092, 0, 0.419023, 0.828667, 0.0606291, 0, 0.436282, 0.824805, 0.0566523, 0, 0.453782, 0.820988, 0.0530229, 0, 0.471529, 0.816635, 0.0496364, 0, 0.489528, 0.811725, 0.0464658, 0, 0.507788, 0.806316, 0.0435082, 0, 0.526317, 0.800469, 0.0407873, 0, 0.545124, 0.794107, 0.038255, 0, 0.564221, 0.787218, 0.0358825, 0, 0.583621, 0.779872, 0.0336785, 0, 0.603341, 0.772097, 0.0316379, 0, 0.623397, 0.764484, 0.0297379, 0, 0.643812, 0.756428, 0.0279581, 0, 0.664611, 0.748022, 0.0263153, 0, 0.685824, 0.739268, 0.0247799, 0, 0.707488, 0.73024, 0.0233385, 0, 0.729646, 0.720893, 0.0220035, 0, 0.752354, 0.71119, 0.0207555, 0, 0.77568, 0.701791, 0.0195843, 0, 0.799715, 0.692184, 0.0184891, 0, 0.824574, 0.682258, 0.0174541, 0, 0.850417, 0.67206, 0.0164873, 0, 0.877466, 0.661717, 0.0155959, 0, 0.90604, 0.651462, 0.0147519, 0, 0.936528, 0.641467, 0.0139727, 0, 0.968254, 0.631229, 0.0132363, 0, 1, 1, 0.367573, 0, 0, 0.999999, 0.367571, 0, 0, 0.999984, 0.367553, 0, 0.000183382, 0.999925, 0.367473, 0, 0.00225254, 0.999759, 0.367259, 0, 0.00628165, 0.99941, 0.366801, 0, 0.0117858, 0.998739, 0.365946, 0, 0.0184359, 0.995529, 0.363191, 0, 0.0260114, 0.992875, 0.360171, 0, 0.0343581, 0.989135, 0.355981, 0, 0.0433637, 0.984166, 0.350401, 0, 0.0529438, 0.977871, 0.343348, 0, 0.0630334, 0.96951, 0.334341, 0, 0.0735805, 0.959964, 0.323862, 0, 0.0845437, 0.950162, 0.312521, 0, 0.095889, 0.938882, 0.299577, 0, 0.107588, 0.926992, 0.285573, 0, 0.119617, 0.915589, 0.271212, 0, 0.131957, 0.904791, 0.256611, 0, 0.144591, 0.895177, 0.242224, 0, 0.157503, 0.886403, 0.227952, 0, 0.170682, 0.878957, 0.214192, 0, 0.184117, 0.872418, 0.200795, 0, 0.197799, 0.867029, 0.188015, 0, 0.21172, 0.862835, 0.175975, 0, 0.225873, 0.859411, 0.164526, 0, 0.240253, 0.856655, 0.153693, 0, 0.254854, 0.854519, 0.14352, 0, 0.269673, 0.852828, 0.13397, 0, 0.284707, 0.851412, 0.124984, 0, 0.299953, 0.850609, 0.116748, 0, 0.315408, 0.849855, 0.10905, 0, 0.331073, 0.849017, 0.101839, 0, 0.346946, 0.848079, 0.0951359, 0, 0.363028, 0.846911, 0.0888774, 0, 0.379318, 0.845445, 0.0830375, 0, 0.395818, 0.84362, 0.0775844, 0, 0.41253, 0.841411, 0.0725054, 0, 0.429457, 0.838768, 0.0677691, 0, 0.446602, 0.835801, 0.0634016, 0, 0.463968, 0.832341, 0.0593095, 0, 0.481561, 0.828424, 0.0555121, 0, 0.499386, 0.824312, 0.052024, 0, 0.51745, 0.819918, 0.0487865, 0, 0.535761, 0.815072, 0.0457801, 0, 0.554328, 0.809863, 0.0430184, 0, 0.573162, 0.804164, 0.0404245, 0, 0.592275, 0.798034, 0.0380146, 0, 0.611681, 0.791436, 0.0357436, 0, 0.631398, 0.784498, 0.0336475, 0, 0.651445, 0.777125, 0.0316666, 0, 0.671845, 0.769365, 0.0298122, 0, 0.692628, 0.761579, 0.0281001, 0, 0.713827, 0.753746, 0.0265049, 0, 0.735484, 0.745573, 0.0250067, 0, 0.75765, 0.737083, 0.0236026, 0, 0.78039, 0.728545, 0.0223302, 0, 0.803789, 0.719691, 0.0211243, 0, 0.82796, 0.710569, 0.0199983, 0, 0.853056, 0.701216, 0.0189569, 0, 0.879298, 0.692094, 0.0179702, 0, 0.907014, 0.682909, 0.0170418, 0, 0.936691, 0.673509, 0.0161732, 0, 0.968254, 0.663863, 0.0153406, 0, 1, 1, 0.437395, 0, 0, 0.999998, 0.437394, 0, 0, 0.99998, 0.437363, 0, 0.000616704, 0.999891, 0.437232, 0, 0.00367925, 0.999656, 0.436877, 0, 0.00867446, 0.999148, 0.436121, 0, 0.0150679, 0.997959, 0.434564, 0, 0.022531, 0.993464, 0.430134, 0, 0.0308507, 0.990606, 0.426077, 0, 0.0398805, 0.985027, 0.419397, 0, 0.0495148, 0.978491, 0.41118, 0, 0.0596749, 0.969643, 0.40048, 0, 0.0703001, 0.959189, 0.38769, 0, 0.0813427, 0.948223, 0.373575, 0, 0.0927641, 0.935955, 0.357622, 0, 0.104533, 0.923237, 0.34043, 0, 0.116624, 0.911074, 0.322735, 0, 0.129015, 0.899724, 0.30479, 0, 0.141687, 0.890189, 0.287392, 0, 0.154626, 0.881796, 0.270248, 0, 0.167818, 0.874781, 0.253659, 0, 0.181252, 0.869166, 0.237786, 0, 0.194918, 0.864725, 0.222618, 0, 0.208807, 0.861565, 0.208356, 0, 0.222913, 0.859284, 0.194867, 0, 0.237229, 0.857677, 0.18212, 0, 0.25175, 0.856714, 0.17018, 0, 0.266473, 0.856155, 0.158969, 0, 0.281392, 0.8558, 0.148413, 0, 0.296505, 0.855672, 0.138578, 0, 0.311811, 0.855538, 0.129345, 0, 0.327306, 0.855689, 0.120861, 0, 0.342991, 0.855767, 0.112969, 0, 0.358864, 0.855618, 0.105593, 0, 0.374925, 0.85525, 0.0987451, 0, 0.391176, 0.854583, 0.0923727, 0, 0.407616, 0.853534, 0.0864143, 0, 0.424249, 0.852061, 0.0808338, 0, 0.441076, 0.850253, 0.0756771, 0, 0.4581, 0.848004, 0.0708612, 0, 0.475324, 0.845333, 0.0663784, 0, 0.492754, 0.842376, 0.0622631, 0, 0.510394, 0.838956, 0.0584112, 0, 0.528251, 0.835121, 0.0548328, 0, 0.546331, 0.830842, 0.0514838, 0, 0.564644, 0.826212, 0.048355, 0, 0.583198, 0.821522, 0.0454714, 0, 0.602005, 0.816551, 0.0428263, 0, 0.621078, 0.811211, 0.0403612, 0, 0.640434, 0.805479, 0.038039, 0, 0.660089, 0.799409, 0.0358739, 0, 0.680066, 0.79306, 0.0338727, 0, 0.70039, 0.786395, 0.0319985, 0, 0.721094, 0.779416, 0.030241, 0, 0.742215, 0.77214, 0.0285951, 0, 0.7638, 0.764636, 0.0270747, 0, 0.785912, 0.756836, 0.0256354, 0, 0.808628, 0.749315, 0.0243027, 0, 0.832055, 0.741561, 0.0230497, 0, 0.856338, 0.733589, 0.0218801, 0, 0.88169, 0.725479, 0.020784, 0, 0.908441, 0.717255, 0.0197702, 0, 0.937125, 0.708829, 0.0188168, 0, 0.968254, 0.700191, 0.0179113, 0, 1, 1, 0.518937, 0, 0, 0.999998, 0.518933, 0, 0, 0.999967, 0.518883, 0, 0.00147741, 0.999832, 0.51866, 0, 0.00573221, 0.999466, 0.518057, 0, 0.011826, 0.998644, 0.516752, 0, 0.0192116, 0.994458, 0.512347, 0, 0.027573, 0.991223, 0.507675, 0, 0.0367099, 0.985515, 0.500188, 0, 0.046487, 0.978308, 0.490408, 0, 0.0568071, 0.968359, 0.477357, 0, 0.0675984, 0.95682, 0.461752, 0, 0.0788059, 0.943929, 0.443796, 0, 0.090386, 0.930224, 0.423893, 0, 0.102304, 0.916514, 0.402682, 0, 0.114532, 0.903653, 0.380914, 0, 0.127047, 0.892315, 0.359212, 0, 0.139828, 0.882942, 0.338102, 0, 0.152861, 0.875438, 0.31773, 0, 0.16613, 0.869642, 0.298186, 0, 0.179624, 0.865304, 0.279491, 0, 0.193332, 0.862382, 0.261804, 0, 0.207247, 0.860666, 0.245146, 0, 0.22136, 0.859788, 0.229406, 0, 0.235666, 0.859608, 0.214605, 0, 0.250158, 0.859912, 0.200691, 0, 0.264832, 0.86053, 0.187623, 0, 0.279684, 0.861368, 0.17539, 0, 0.294711, 0.862237, 0.163901, 0, 0.309911, 0.863127, 0.153175, 0, 0.32528, 0.863923, 0.143147, 0, 0.340819, 0.864567, 0.133781, 0, 0.356524, 0.865013, 0.125042, 0, 0.372397, 0.86539, 0.116952, 0, 0.388438, 0.865591, 0.109476, 0, 0.404645, 0.865517, 0.102542, 0, 0.421022, 0.865084, 0.0960688, 0, 0.437569, 0.864309, 0.0900499, 0, 0.454287, 0.863151, 0.0844328, 0, 0.471181, 0.861649, 0.0792218, 0, 0.488253, 0.859742, 0.0743482, 0, 0.505507, 0.857446, 0.0697963, 0, 0.522947, 0.854757, 0.0655364, 0, 0.54058, 0.851783, 0.061608, 0, 0.558412, 0.848516, 0.0579701, 0, 0.576449, 0.844897, 0.0545742, 0, 0.594701, 0.840956, 0.0514167, 0, 0.613178, 0.836676, 0.0484598, 0, 0.631892, 0.832075, 0.0456934, 0, 0.650856, 0.827191, 0.0431178, 0, 0.670088, 0.822295, 0.0407718, 0, 0.689606, 0.817294, 0.0386032, 0, 0.709434, 0.812013, 0.0365675, 0, 0.7296, 0.806465, 0.0346547, 0, 0.750138, 0.800691, 0.0328717, 0, 0.771093, 0.794709, 0.031211, 0, 0.792519, 0.788493, 0.0296504, 0, 0.814488, 0.782049, 0.0281782, 0, 0.837097, 0.775403, 0.0267965, 0, 0.860481, 0.76857, 0.0255002, 0, 0.884842, 0.761536, 0.0242759, 0, 0.910494, 0.754303, 0.0231142, 0, 0.937985, 0.74692, 0.0220305, 0, 0.968254, 0.739745, 0.0210192, 0, 1, 1, 0.613914, 0, 0, 0.999996, 0.613907, 0, 0.0000963597, 0.999942, 0.613814, 0, 0.00301247, 0.999704, 0.613407, 0, 0.00870385, 0.999046, 0.612302, 0, 0.0160714, 0.995516, 0.608266, 0, 0.0245899, 0.991726, 0.602863, 0, 0.0339681, 0.985157, 0.593956, 0, 0.0440254, 0.97642, 0.581748, 0, 0.0546409, 0.964404, 0.565183, 0, 0.0657284, 0.950601, 0.545273, 0, 0.0772246, 0.935158, 0.522129, 0, 0.0890812, 0.919364, 0.496782, 0, 0.10126, 0.904754, 0.470571, 0, 0.113731, 0.89176, 0.444037, 0, 0.126469, 0.881492, 0.418322, 0, 0.139454, 0.873656, 0.393522, 0, 0.15267, 0.868053, 0.369795, 0, 0.166101, 0.864336, 0.347171, 0, 0.179736, 0.862259, 0.325737, 0, 0.193565, 0.861556, 0.305532, 0, 0.207578, 0.861776, 0.286416, 0, 0.221769, 0.862661, 0.268355, 0, 0.23613, 0.864015, 0.251334, 0, 0.250656, 0.865711, 0.235352, 0, 0.265343, 0.867519, 0.220302, 0, 0.280187, 0.869351, 0.206161, 0, 0.295183, 0.871144, 0.192908, 0, 0.31033, 0.872839, 0.180505, 0, 0.325624, 0.874307, 0.168848, 0, 0.341065, 0.875667, 0.158021, 0, 0.35665, 0.876758, 0.147877, 0, 0.37238, 0.87764, 0.138441, 0, 0.388253, 0.878237, 0.129627, 0, 0.404269, 0.878563, 0.121415, 0, 0.42043, 0.878572, 0.113741, 0, 0.436735, 0.87842, 0.106652, 0, 0.453187, 0.878057, 0.100097, 0, 0.469786, 0.877413, 0.0940128, 0, 0.486536, 0.87646, 0.0883462, 0, 0.503439, 0.875233, 0.0830924, 0, 0.520498, 0.8737, 0.0781975, 0, 0.537717, 0.871873, 0.07364, 0, 0.555102, 0.86978, 0.0694103, 0, 0.572657, 0.867405, 0.0654696, 0, 0.59039, 0.864751, 0.0617914, 0, 0.608307, 0.861818, 0.0583491, 0, 0.626419, 0.858645, 0.0551443, 0, 0.644733, 0.855307, 0.0521894, 0, 0.663264, 0.851736, 0.0494334, 0, 0.682025, 0.847927, 0.0468504, 0, 0.701032, 0.843888, 0.0444261, 0, 0.720308, 0.839629, 0.0421497, 0, 0.739875, 0.835158, 0.0400082, 0, 0.759764, 0.830509, 0.0380076, 0, 0.780014, 0.825714, 0.0361488, 0, 0.800673, 0.820729, 0.0343956, 0, 0.821803, 0.815751, 0.0327781, 0, 0.843492, 0.810752, 0.031275, 0, 0.86586, 0.805587, 0.0298542, 0, 0.889087, 0.800317, 0.0285397, 0, 0.913466, 0.79489, 0.0272948, 0, 0.93952, 0.789314, 0.0261139, 0, 0.96835, 0.783593, 0.0249938, 0, 1, 1, 0.724258, 0, 0, 0.999992, 0.724243, 0, 0.000726889, 0.99987, 0.724044, 0, 0.00569574, 0.999336, 0.72317, 0, 0.0131702, 0.996271, 0.719432, 0, 0.0220738, 0.991159, 0.712576, 0, 0.0319405, 0.982465, 0.700927, 0, 0.0425202, 0.97049, 0.684297, 0, 0.0536599, 0.953973, 0.661244, 0, 0.065258, 0.935546, 0.633804, 0, 0.0772427, 0.916596, 0.603071, 0, 0.0895616, 0.899353, 0.57105, 0, 0.102175, 0.885216, 0.539206, 0, 0.11505, 0.875076, 0.508714, 0, 0.128164, 0.868334, 0.479571, 0, 0.141495, 0.864414, 0.451796, 0, 0.155026, 0.862678, 0.425328, 0, 0.168745, 0.862835, 0.400352, 0, 0.182639, 0.864067, 0.376532, 0, 0.196699, 0.866086, 0.35391, 0, 0.210915, 0.868557, 0.332424, 0, 0.225282, 0.871271, 0.312053, 0, 0.239792, 0.874058, 0.292764, 0, 0.25444, 0.8768, 0.27453, 0, 0.269223, 0.87939, 0.257297, 0, 0.284135, 0.8819, 0.24114, 0, 0.299174, 0.884187, 0.225934, 0, 0.314337, 0.886262, 0.211669, 0, 0.329622, 0.888119, 0.198311, 0, 0.345026, 0.889709, 0.185783, 0, 0.360549, 0.891054, 0.174063, 0, 0.376189, 0.892196, 0.163143, 0, 0.391946, 0.893101, 0.152952, 0, 0.407819, 0.893803, 0.143475, 0, 0.423808, 0.894277, 0.134647, 0, 0.439914, 0.894532, 0.126434, 0, 0.456137, 0.894576, 0.1188, 0, 0.472479, 0.894393, 0.111694, 0, 0.48894, 0.893976, 0.105069, 0, 0.505523, 0.893346, 0.0989077, 0, 0.52223, 0.892502, 0.0931724, 0, 0.539064, 0.891441, 0.0878276, 0, 0.556028, 0.890276, 0.082903, 0, 0.573125, 0.888972, 0.0783505, 0, 0.590361, 0.887469, 0.0741083, 0, 0.607741, 0.885785, 0.0701633, 0, 0.62527, 0.883914, 0.0664835, 0, 0.642957, 0.881872, 0.0630567, 0, 0.660809, 0.879651, 0.0598527, 0, 0.678836, 0.877267, 0.0568615, 0, 0.69705, 0.874717, 0.05406, 0, 0.715465, 0.872012, 0.0514378, 0, 0.734098, 0.869157, 0.0489805, 0, 0.752968, 0.866155, 0.0466727, 0, 0.772101, 0.863014, 0.0445056, 0, 0.791529, 0.859748, 0.0424733, 0, 0.81129, 0.856416, 0.0405957, 0, 0.831438, 0.852958, 0.0388273, 0, 0.852044, 0.849382, 0.0371619, 0, 0.87321, 0.845694, 0.0355959, 0, 0.89509, 0.841893, 0.0341155, 0, 0.917932, 0.837981, 0.0327141, 0, 0.942204, 0.833963, 0.0313856, 0, 0.968981, 0.829847, 0.0301275, 0, 1, 1, 0.85214, 0, 0, 0.999969, 0.852095, 0, 0.00279627, 0.999483, 0.851408, 0, 0.0107635, 0.994545, 0.84579, 0, 0.0206454, 0.986188, 0.835231, 0, 0.0315756, 0.969847, 0.814687, 0, 0.0432021, 0.945951, 0.783735, 0, 0.0553396, 0.91917, 0.746074, 0, 0.0678766, 0.895488, 0.706938, 0, 0.0807395, 0.878232, 0.669534, 0, 0.0938767, 0.868252, 0.635168, 0, 0.10725, 0.863873, 0.603069, 0, 0.120832, 0.863369, 0.572514, 0, 0.134598, 0.86545, 0.543169, 0, 0.148533, 0.868803, 0.514578, 0, 0.16262, 0.872794, 0.486762, 0, 0.176849, 0.87702, 0.459811, 0, 0.19121, 0.881054, 0.433654, 0, 0.205694, 0.884974, 0.408574, 0, 0.220294, 0.888587, 0.384525, 0, 0.235005, 0.891877, 0.36156, 0, 0.24982, 0.894793, 0.339661, 0, 0.264737, 0.89743, 0.318913, 0, 0.279751, 0.899796, 0.299302, 0, 0.294859, 0.901943, 0.280843, 0, 0.310058, 0.903858, 0.263481, 0, 0.325346, 0.905574, 0.247197, 0, 0.340721, 0.907069, 0.231915, 0, 0.356181, 0.908379, 0.217614, 0, 0.371725, 0.90952, 0.20425, 0, 0.387353, 0.910483, 0.191758, 0, 0.403063, 0.91128, 0.180092, 0, 0.418854, 0.911936, 0.169222, 0, 0.434727, 0.912454, 0.159098, 0, 0.450682, 0.912835, 0.149668, 0, 0.466718, 0.913078, 0.140884, 0, 0.482837, 0.913192, 0.132709, 0, 0.499038, 0.913175, 0.125095, 0, 0.515324, 0.91304, 0.118012, 0, 0.531695, 0.912781, 0.111417, 0, 0.548153, 0.91241, 0.105281, 0, 0.5647, 0.911924, 0.0995691, 0, 0.581338, 0.911331, 0.0942531, 0, 0.59807, 0.910637, 0.0893076, 0, 0.6149, 0.90984, 0.0846998, 0, 0.63183, 0.908941, 0.0804044, 0, 0.648865, 0.907944, 0.0763984, 0, 0.666011, 0.906857, 0.0726638, 0, 0.683273, 0.90568, 0.0691783, 0, 0.700659, 0.904416, 0.0659222, 0, 0.718176, 0.903067, 0.0628782, 0, 0.735834, 0.901637, 0.0600307, 0, 0.753646, 0.900128, 0.0573647, 0, 0.771625, 0.898544, 0.0548668, 0, 0.78979, 0.89689, 0.052527, 0, 0.808162, 0.895165, 0.0503306, 0, 0.826771, 0.893371, 0.0482668, 0, 0.845654, 0.891572, 0.0463605, 0, 0.864863, 0.889763, 0.0445998, 0, 0.884472, 0.887894, 0.0429451, 0, 0.904592, 0.885967, 0.0413884, 0, 0.925407, 0.883984, 0.0399225, 0, 0.947271, 0.881945, 0.0385405, 0, 0.97105, 0.879854, 0.0372362, 0, 1, 0.999804, 0.995833, 0, 0, 0.938155, 0.933611, 0, 0.0158731, 0.864755, 0.854311, 0, 0.0317461, 0.888594, 0.865264, 0, 0.0476191, 0.905575, 0.863922, 0, 0.0634921, 0.915125, 0.850558, 0, 0.0793651, 0.920665, 0.829254, 0, 0.0952381, 0.924073, 0.802578, 0, 0.111111, 0.926304, 0.772211, 0, 0.126984, 0.927829, 0.739366, 0, 0.142857, 0.928924, 0.705033, 0, 0.15873, 0.92973, 0.670019, 0, 0.174603, 0.930339, 0.634993, 0, 0.190476, 0.930811, 0.600485, 0, 0.206349, 0.931191, 0.566897, 0, 0.222222, 0.93149, 0.534485, 0, 0.238095, 0.931737, 0.503429, 0, 0.253968, 0.931939, 0.473811, 0, 0.269841, 0.932108, 0.445668, 0, 0.285714, 0.93225, 0.418993, 0, 0.301587, 0.932371, 0.393762, 0, 0.31746, 0.932474, 0.369939, 0, 0.333333, 0.932562, 0.347479, 0, 0.349206, 0.932638, 0.326336, 0, 0.365079, 0.932703, 0.306462, 0, 0.380952, 0.93276, 0.287805, 0, 0.396825, 0.932809, 0.270313, 0, 0.412698, 0.932851, 0.253933, 0, 0.428571, 0.932887, 0.23861, 0, 0.444444, 0.932917, 0.224289, 0, 0.460317, 0.932943, 0.210917, 0, 0.47619, 0.932965, 0.19844, 0, 0.492063, 0.932982, 0.186807, 0, 0.507937, 0.932995, 0.175966, 0, 0.52381, 0.933005, 0.165869, 0, 0.539683, 0.933011, 0.156468, 0, 0.555556, 0.933013, 0.147719, 0, 0.571429, 0.933013, 0.139579, 0, 0.587302, 0.93301, 0.132007, 0, 0.603175, 0.933004, 0.124965, 0, 0.619048, 0.932994, 0.118416, 0, 0.634921, 0.932982, 0.112326, 0, 0.650794, 0.932968, 0.106663, 0, 0.666667, 0.93295, 0.101397, 0, 0.68254, 0.932931, 0.0964993, 0, 0.698413, 0.932908, 0.0919438, 0, 0.714286, 0.932883, 0.0877057, 0, 0.730159, 0.932856, 0.0837623, 0, 0.746032, 0.932827, 0.0800921, 0, 0.761905, 0.932796, 0.0766754, 0, 0.777778, 0.932762, 0.0734936, 0, 0.793651, 0.932727, 0.0705296, 0, 0.809524, 0.932689, 0.0677676, 0, 0.825397, 0.93265, 0.0651929, 0, 0.84127, 0.932609, 0.0627917, 0, 0.857143, 0.932565, 0.0605515, 0, 0.873016, 0.932521, 0.0584606, 0, 0.888889, 0.932474, 0.0565082, 0, 0.904762, 0.932427, 0.0546841, 0, 0.920635, 0.932377, 0.0529793, 0, 0.936508, 0.932326, 0.0513851, 0, 0.952381, 0.932274, 0.0498936, 0, 0.968254, 0.93222, 0.0484975, 0, 0.984127, 0.932164, 0.0471899, 0, 1]; + const ltc_float_1 = new Float32Array(LTC_MAT_1); + const ltc_float_2 = new Float32Array(LTC_MAT_2); + const LTC_FLOAT_1 = new DataTexture(ltc_float_1, 64, 64, RGBAFormat, FloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); + const LTC_FLOAT_2 = new DataTexture(ltc_float_2, 64, 64, RGBAFormat, FloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); + LTC_FLOAT_1.needsUpdate = true; + LTC_FLOAT_2.needsUpdate = true; + const ltc_half_1 = new Uint16Array(LTC_MAT_1.length); + LTC_MAT_1.forEach(function(x2, index2) { + ltc_half_1[index2] = DataUtils.toHalfFloat(x2); + }); + const ltc_half_2 = new Uint16Array(LTC_MAT_2.length); + LTC_MAT_2.forEach(function(x2, index2) { + ltc_half_2[index2] = DataUtils.toHalfFloat(x2); + }); + const LTC_HALF_1 = new DataTexture(ltc_half_1, 64, 64, RGBAFormat, HalfFloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); + const LTC_HALF_2 = new DataTexture(ltc_half_2, 64, 64, RGBAFormat, HalfFloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); + LTC_HALF_1.needsUpdate = true; + LTC_HALF_2.needsUpdate = true; + this.LTC_HALF_1 = LTC_HALF_1; + this.LTC_HALF_2 = LTC_HALF_2; + this.LTC_FLOAT_1 = LTC_FLOAT_1; + this.LTC_FLOAT_2 = LTC_FLOAT_2; + return this; + } +} +RectAreaLightTexturesLib.LTC_HALF_1 = null; +RectAreaLightTexturesLib.LTC_HALF_1 = null; +RectAreaLightTexturesLib.LTC_FLOAT_1 = null; +RectAreaLightTexturesLib.LTC_FLOAT_2 = null; +// node_modules/three/examples/jsm/lines/LineSegmentsGeometry.js +var _box2 = new Box3; +var _vector7 = new Vector3; + +// node_modules/three/examples/jsm/lines/LineMaterial.js +UniformsLib.line = { + worldUnits: { value: 1 }, + linewidth: { value: 1 }, + resolution: { value: new Vector2(1, 1) }, + dashOffset: { value: 0 }, + dashScale: { value: 1 }, + dashSize: { value: 1 }, + gapSize: { value: 1 } +}; +ShaderLib["line"] = { + uniforms: UniformsUtils.merge([ + UniformsLib.common, + UniformsLib.fog, + UniformsLib.line + ]), + vertexShader: ` + #include + #include + #include + #include + #include + + uniform float linewidth; + uniform vec2 resolution; + + attribute vec3 instanceStart; + attribute vec3 instanceEnd; + + attribute vec3 instanceColorStart; + attribute vec3 instanceColorEnd; + + #ifdef WORLD_UNITS + + varying vec4 worldPos; + varying vec3 worldStart; + varying vec3 worldEnd; + + #ifdef USE_DASH + + varying vec2 vUv; + + #endif + + #else + + varying vec2 vUv; + + #endif + + #ifdef USE_DASH + + uniform float dashScale; + attribute float instanceDistanceStart; + attribute float instanceDistanceEnd; + varying float vLineDistance; + + #endif + + void trimSegment( const in vec4 start, inout vec4 end ) { + + // trim end segment so it terminates between the camera plane and the near plane + + // conservative estimate of the near plane + float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column + float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column + float nearEstimate = - 0.5 * b / a; + + float alpha = ( nearEstimate - start.z ) / ( end.z - start.z ); + + end.xyz = mix( start.xyz, end.xyz, alpha ); + + } + + void main() { + + #ifdef USE_COLOR + + vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd; + + #endif + + #ifdef USE_DASH + + vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd; + vUv = uv; + + #endif + + float aspect = resolution.x / resolution.y; + + // camera space + vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 ); + vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 ); + + #ifdef WORLD_UNITS + + worldStart = start.xyz; + worldEnd = end.xyz; + + #else + + vUv = uv; + + #endif + + // special case for perspective projection, and segments that terminate either in, or behind, the camera plane + // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space + // but we need to perform ndc-space calculations in the shader, so we must address this issue directly + // perhaps there is a more elegant solution -- WestLangley + + bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column + + if ( perspective ) { + + if ( start.z < 0.0 && end.z >= 0.0 ) { + + trimSegment( start, end ); + + } else if ( end.z < 0.0 && start.z >= 0.0 ) { + + trimSegment( end, start ); + + } + + } + + // clip space + vec4 clipStart = projectionMatrix * start; + vec4 clipEnd = projectionMatrix * end; + + // ndc space + vec3 ndcStart = clipStart.xyz / clipStart.w; + vec3 ndcEnd = clipEnd.xyz / clipEnd.w; + + // direction + vec2 dir = ndcEnd.xy - ndcStart.xy; + + // account for clip-space aspect ratio + dir.x *= aspect; + dir = normalize( dir ); + + #ifdef WORLD_UNITS + + vec3 worldDir = normalize( end.xyz - start.xyz ); + vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) ); + vec3 worldUp = normalize( cross( worldDir, tmpFwd ) ); + vec3 worldFwd = cross( worldDir, worldUp ); + worldPos = position.y < 0.5 ? start: end; + + // height offset + float hw = linewidth * 0.5; + worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp; + + // don't extend the line if we're rendering dashes because we + // won't be rendering the endcaps + #ifndef USE_DASH + + // cap extension + worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir; + + // add width to the box + worldPos.xyz += worldFwd * hw; + + // endcaps + if ( position.y > 1.0 || position.y < 0.0 ) { + + worldPos.xyz -= worldFwd * 2.0 * hw; + + } + + #endif + + // project the worldpos + vec4 clip = projectionMatrix * worldPos; + + // shift the depth of the projected points so the line + // segments overlap neatly + vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd; + clip.z = clipPose.z * clip.w; + + #else + + vec2 offset = vec2( dir.y, - dir.x ); + // undo aspect ratio adjustment + dir.x /= aspect; + offset.x /= aspect; + + // sign flip + if ( position.x < 0.0 ) offset *= - 1.0; + + // endcaps + if ( position.y < 0.0 ) { + + offset += - dir; + + } else if ( position.y > 1.0 ) { + + offset += dir; + + } + + // adjust for linewidth + offset *= linewidth; + + // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ... + offset /= resolution.y; + + // select end + vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd; + + // back to clip space + offset *= clip.w; + + clip.xy += offset; + + #endif + + gl_Position = clip; + + vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation + + #include + #include + #include + + } + `, + fragmentShader: ` + uniform vec3 diffuse; + uniform float opacity; + uniform float linewidth; + + #ifdef USE_DASH + + uniform float dashOffset; + uniform float dashSize; + uniform float gapSize; + + #endif + + varying float vLineDistance; + + #ifdef WORLD_UNITS + + varying vec4 worldPos; + varying vec3 worldStart; + varying vec3 worldEnd; + + #ifdef USE_DASH + + varying vec2 vUv; + + #endif + + #else + + varying vec2 vUv; + + #endif + + #include + #include + #include + #include + #include + + vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) { + + float mua; + float mub; + + vec3 p13 = p1 - p3; + vec3 p43 = p4 - p3; + + vec3 p21 = p2 - p1; + + float d1343 = dot( p13, p43 ); + float d4321 = dot( p43, p21 ); + float d1321 = dot( p13, p21 ); + float d4343 = dot( p43, p43 ); + float d2121 = dot( p21, p21 ); + + float denom = d2121 * d4343 - d4321 * d4321; + + float numer = d1343 * d4321 - d1321 * d4343; + + mua = numer / denom; + mua = clamp( mua, 0.0, 1.0 ); + mub = ( d1343 + d4321 * ( mua ) ) / d4343; + mub = clamp( mub, 0.0, 1.0 ); + + return vec2( mua, mub ); + + } + + void main() { + + #include + + #ifdef USE_DASH + + if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps + + if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX + + #endif + + float alpha = opacity; + + #ifdef WORLD_UNITS + + // Find the closest points on the view ray and the line segment + vec3 rayEnd = normalize( worldPos.xyz ) * 1e5; + vec3 lineDir = worldEnd - worldStart; + vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd ); + + vec3 p1 = worldStart + lineDir * params.x; + vec3 p2 = rayEnd * params.y; + vec3 delta = p1 - p2; + float len = length( delta ); + float norm = len / linewidth; + + #ifndef USE_DASH + + #ifdef USE_ALPHA_TO_COVERAGE + + float dnorm = fwidth( norm ); + alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm ); + + #else + + if ( norm > 0.5 ) { + + discard; + + } + + #endif + + #endif + + #else + + #ifdef USE_ALPHA_TO_COVERAGE + + // artifacts appear on some hardware if a derivative is taken within a conditional + float a = vUv.x; + float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; + float len2 = a * a + b * b; + float dlen = fwidth( len2 ); + + if ( abs( vUv.y ) > 1.0 ) { + + alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 ); + + } + + #else + + if ( abs( vUv.y ) > 1.0 ) { + + float a = vUv.x; + float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; + float len2 = a * a + b * b; + + if ( len2 > 1.0 ) discard; + + } + + #endif + + #endif + + vec4 diffuseColor = vec4( diffuse, alpha ); + + #include + #include + + gl_FragColor = vec4( diffuseColor.rgb, alpha ); + + #include + #include + #include + #include + + } + ` +}; + +// node_modules/three/examples/jsm/lines/LineSegments2.js +var _viewport = new Vector4; +var _start2 = new Vector3; +var _end2 = new Vector3; +var _start4 = new Vector4; +var _end4 = new Vector4; +var _ssOrigin = new Vector4; +var _ssOrigin3 = new Vector3; +var _mvMatrix = new Matrix4; +var _line = new Line3; +var _closestPoint2 = new Vector3; +var _box4 = new Box3; +var _sphere2 = new Sphere; +var _clipToWorldVector = new Vector4; +// node_modules/three/examples/jsm/lines/Wireframe.js +var _start3 = new Vector3; +var _end3 = new Vector3; +var _viewport2 = new Vector4; +// node_modules/three/examples/jsm/loaders/3DMLoader.js +var _taskCache = new WeakMap; +// node_modules/three/examples/jsm/loaders/DRACOLoader.js +var _taskCache2 = new WeakMap; +// node_modules/three/examples/jsm/loaders/FBXLoader.js +var tempEuler = new Euler; +var tempVec = new Vector3; +// node_modules/three/examples/jsm/loaders/GLTFLoader.js +class GLTFLoader extends Loader { + constructor(manager) { + super(manager); + this.dracoLoader = null; + this.ktx2Loader = null; + this.meshoptDecoder = null; + this.pluginCallbacks = []; + this.register(function(parser) { + return new GLTFMaterialsClearcoatExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsDispersionExtension2(parser); + }); + this.register(function(parser) { + return new GLTFTextureBasisUExtension(parser); + }); + this.register(function(parser) { + return new GLTFTextureWebPExtension(parser); + }); + this.register(function(parser) { + return new GLTFTextureAVIFExtension(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsSheenExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsTransmissionExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsVolumeExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsIorExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsEmissiveStrengthExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsSpecularExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsIridescenceExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsAnisotropyExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsBumpExtension2(parser); + }); + this.register(function(parser) { + return new GLTFLightsExtension(parser); + }); + this.register(function(parser) { + return new GLTFMeshoptCompression(parser); + }); + this.register(function(parser) { + return new GLTFMeshGpuInstancing2(parser); + }); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + let resourcePath; + if (this.resourcePath !== "") { + resourcePath = this.resourcePath; + } else if (this.path !== "") { + const relativeUrl = LoaderUtils.extractUrlBase(url); + resourcePath = LoaderUtils.resolveURL(relativeUrl, this.path); + } else { + resourcePath = LoaderUtils.extractUrlBase(url); + } + this.manager.itemStart(url); + const _onError = function(e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(data2) { + try { + scope.parse(data2, resourcePath, function(gltf) { + onLoad(gltf); + scope.manager.itemEnd(url); + }, _onError); + } catch (e) { + _onError(e); + } + }, onProgress, _onError); + } + setDRACOLoader(dracoLoader) { + this.dracoLoader = dracoLoader; + return this; + } + setKTX2Loader(ktx2Loader) { + this.ktx2Loader = ktx2Loader; + return this; + } + setMeshoptDecoder(meshoptDecoder) { + this.meshoptDecoder = meshoptDecoder; + return this; + } + register(callback) { + if (this.pluginCallbacks.indexOf(callback) === -1) { + this.pluginCallbacks.push(callback); + } + return this; + } + unregister(callback) { + if (this.pluginCallbacks.indexOf(callback) !== -1) { + this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); + } + return this; + } + parse(data2, path, onLoad, onError) { + let json; + const extensions = {}; + const plugins = {}; + const textDecoder = new TextDecoder; + if (typeof data2 === "string") { + json = JSON.parse(data2); + } else if (data2 instanceof ArrayBuffer) { + const magic = textDecoder.decode(new Uint8Array(data2, 0, 4)); + if (magic === BINARY_EXTENSION_HEADER_MAGIC) { + try { + extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data2); + } catch (error) { + if (onError) + onError(error); + return; + } + json = JSON.parse(extensions[EXTENSIONS.KHR_BINARY_GLTF].content); + } else { + json = JSON.parse(textDecoder.decode(data2)); + } + } else { + json = data2; + } + if (json.asset === undefined || json.asset.version[0] < 2) { + if (onError) + onError(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")); + return; + } + const parser = new GLTFParser(json, { + path: path || this.resourcePath || "", + crossOrigin: this.crossOrigin, + requestHeader: this.requestHeader, + manager: this.manager, + ktx2Loader: this.ktx2Loader, + meshoptDecoder: this.meshoptDecoder + }); + parser.fileLoader.setRequestHeader(this.requestHeader); + for (let i = 0;i < this.pluginCallbacks.length; i++) { + const plugin = this.pluginCallbacks[i](parser); + if (!plugin.name) + console.error("THREE.GLTFLoader: Invalid plugin found: missing name"); + plugins[plugin.name] = plugin; + extensions[plugin.name] = true; + } + if (json.extensionsUsed) { + for (let i = 0;i < json.extensionsUsed.length; ++i) { + const extensionName = json.extensionsUsed[i]; + const extensionsRequired = json.extensionsRequired || []; + switch (extensionName) { + case EXTENSIONS.KHR_MATERIALS_UNLIT: + extensions[extensionName] = new GLTFMaterialsUnlitExtension2; + break; + case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: + extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader); + break; + case EXTENSIONS.KHR_TEXTURE_TRANSFORM: + extensions[extensionName] = new GLTFTextureTransformExtension; + break; + case EXTENSIONS.KHR_MESH_QUANTIZATION: + extensions[extensionName] = new GLTFMeshQuantizationExtension; + break; + default: + if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === undefined) { + console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".'); + } + } + } + } + parser.setExtensions(extensions); + parser.setPlugins(plugins); + parser.parse(onLoad, onError); + } + parseAsync(data2, path) { + const scope = this; + return new Promise(function(resolve, reject2) { + scope.parse(data2, path, resolve, reject2); + }); + } +} +function GLTFRegistry() { + let objects = {}; + return { + get: function(key2) { + return objects[key2]; + }, + add: function(key2, object) { + objects[key2] = object; + }, + remove: function(key2) { + delete objects[key2]; + }, + removeAll: function() { + objects = {}; + } + }; +} +var EXTENSIONS = { + KHR_BINARY_GLTF: "KHR_binary_glTF", + KHR_DRACO_MESH_COMPRESSION: "KHR_draco_mesh_compression", + KHR_LIGHTS_PUNCTUAL: "KHR_lights_punctual", + KHR_MATERIALS_CLEARCOAT: "KHR_materials_clearcoat", + KHR_MATERIALS_DISPERSION: "KHR_materials_dispersion", + KHR_MATERIALS_IOR: "KHR_materials_ior", + KHR_MATERIALS_SHEEN: "KHR_materials_sheen", + KHR_MATERIALS_SPECULAR: "KHR_materials_specular", + KHR_MATERIALS_TRANSMISSION: "KHR_materials_transmission", + KHR_MATERIALS_IRIDESCENCE: "KHR_materials_iridescence", + KHR_MATERIALS_ANISOTROPY: "KHR_materials_anisotropy", + KHR_MATERIALS_UNLIT: "KHR_materials_unlit", + KHR_MATERIALS_VOLUME: "KHR_materials_volume", + KHR_TEXTURE_BASISU: "KHR_texture_basisu", + KHR_TEXTURE_TRANSFORM: "KHR_texture_transform", + KHR_MESH_QUANTIZATION: "KHR_mesh_quantization", + KHR_MATERIALS_EMISSIVE_STRENGTH: "KHR_materials_emissive_strength", + EXT_MATERIALS_BUMP: "EXT_materials_bump", + EXT_TEXTURE_WEBP: "EXT_texture_webp", + EXT_TEXTURE_AVIF: "EXT_texture_avif", + EXT_MESHOPT_COMPRESSION: "EXT_meshopt_compression", + EXT_MESH_GPU_INSTANCING: "EXT_mesh_gpu_instancing" +}; + +class GLTFLightsExtension { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; + this.cache = { refs: {}, uses: {} }; + } + _markDefs() { + const parser = this.parser; + const nodeDefs = this.parser.json.nodes || []; + for (let nodeIndex = 0, nodeLength = nodeDefs.length;nodeIndex < nodeLength; nodeIndex++) { + const nodeDef = nodeDefs[nodeIndex]; + if (nodeDef.extensions && nodeDef.extensions[this.name] && nodeDef.extensions[this.name].light !== undefined) { + parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light); + } + } + } + _loadLight(lightIndex) { + const parser = this.parser; + const cacheKey = "light:" + lightIndex; + let dependency = parser.cache.get(cacheKey); + if (dependency) + return dependency; + const json = parser.json; + const extensions = json.extensions && json.extensions[this.name] || {}; + const lightDefs = extensions.lights || []; + const lightDef = lightDefs[lightIndex]; + let lightNode; + const color = new Color(16777215); + if (lightDef.color !== undefined) + color.setRGB(lightDef.color[0], lightDef.color[1], lightDef.color[2], LinearSRGBColorSpace); + const range = lightDef.range !== undefined ? lightDef.range : 0; + switch (lightDef.type) { + case "directional": + lightNode = new DirectionalLight(color); + lightNode.target.position.set(0, 0, -1); + lightNode.add(lightNode.target); + break; + case "point": + lightNode = new PointLight(color); + lightNode.distance = range; + break; + case "spot": + lightNode = new SpotLight(color); + lightNode.distance = range; + lightDef.spot = lightDef.spot || {}; + lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0; + lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4; + lightNode.angle = lightDef.spot.outerConeAngle; + lightNode.penumbra = 1 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle; + lightNode.target.position.set(0, 0, -1); + lightNode.add(lightNode.target); + break; + default: + throw new Error("THREE.GLTFLoader: Unexpected light type: " + lightDef.type); + } + lightNode.position.set(0, 0, 0); + assignExtrasToUserData(lightNode, lightDef); + if (lightDef.intensity !== undefined) + lightNode.intensity = lightDef.intensity; + lightNode.name = parser.createUniqueName(lightDef.name || "light_" + lightIndex); + dependency = Promise.resolve(lightNode); + parser.cache.add(cacheKey, dependency); + return dependency; + } + getDependency(type, index2) { + if (type !== "light") + return; + return this._loadLight(index2); + } + createNodeAttachment(nodeIndex) { + const self2 = this; + const parser = this.parser; + const json = parser.json; + const nodeDef = json.nodes[nodeIndex]; + const lightDef = nodeDef.extensions && nodeDef.extensions[this.name] || {}; + const lightIndex = lightDef.light; + if (lightIndex === undefined) + return null; + return this._loadLight(lightIndex).then(function(light) { + return parser._getNodeRef(self2.cache, lightIndex, light); + }); + } +} + +class GLTFMaterialsUnlitExtension2 { + constructor() { + this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; + } + getMaterialType() { + return MeshBasicMaterial; + } + extendParams(materialParams, materialDef, parser) { + const pending = []; + materialParams.color = new Color(1, 1, 1); + materialParams.opacity = 1; + const metallicRoughness = materialDef.pbrMetallicRoughness; + if (metallicRoughness) { + if (Array.isArray(metallicRoughness.baseColorFactor)) { + const array = metallicRoughness.baseColorFactor; + materialParams.color.setRGB(array[0], array[1], array[2], LinearSRGBColorSpace); + materialParams.opacity = array[3]; + } + if (metallicRoughness.baseColorTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, SRGBColorSpace)); + } + } + return Promise.all(pending); + } +} + +class GLTFMaterialsEmissiveStrengthExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const emissiveStrength = materialDef.extensions[this.name].emissiveStrength; + if (emissiveStrength !== undefined) { + materialParams.emissiveIntensity = emissiveStrength; + } + return Promise.resolve(); + } +} + +class GLTFMaterialsClearcoatExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + if (extension.clearcoatFactor !== undefined) { + materialParams.clearcoat = extension.clearcoatFactor; + } + if (extension.clearcoatTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "clearcoatMap", extension.clearcoatTexture)); + } + if (extension.clearcoatRoughnessFactor !== undefined) { + materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor; + } + if (extension.clearcoatRoughnessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "clearcoatRoughnessMap", extension.clearcoatRoughnessTexture)); + } + if (extension.clearcoatNormalTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "clearcoatNormalMap", extension.clearcoatNormalTexture)); + if (extension.clearcoatNormalTexture.scale !== undefined) { + const scale2 = extension.clearcoatNormalTexture.scale; + materialParams.clearcoatNormalScale = new Vector2(scale2, scale2); + } + } + return Promise.all(pending); + } +} + +class GLTFMaterialsDispersionExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_DISPERSION; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const extension = materialDef.extensions[this.name]; + materialParams.dispersion = extension.dispersion !== undefined ? extension.dispersion : 0; + return Promise.resolve(); + } +} + +class GLTFMaterialsIridescenceExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + if (extension.iridescenceFactor !== undefined) { + materialParams.iridescence = extension.iridescenceFactor; + } + if (extension.iridescenceTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "iridescenceMap", extension.iridescenceTexture)); + } + if (extension.iridescenceIor !== undefined) { + materialParams.iridescenceIOR = extension.iridescenceIor; + } + if (materialParams.iridescenceThicknessRange === undefined) { + materialParams.iridescenceThicknessRange = [100, 400]; + } + if (extension.iridescenceThicknessMinimum !== undefined) { + materialParams.iridescenceThicknessRange[0] = extension.iridescenceThicknessMinimum; + } + if (extension.iridescenceThicknessMaximum !== undefined) { + materialParams.iridescenceThicknessRange[1] = extension.iridescenceThicknessMaximum; + } + if (extension.iridescenceThicknessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "iridescenceThicknessMap", extension.iridescenceThicknessTexture)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsSheenExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_SHEEN; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + materialParams.sheenColor = new Color(0, 0, 0); + materialParams.sheenRoughness = 0; + materialParams.sheen = 1; + const extension = materialDef.extensions[this.name]; + if (extension.sheenColorFactor !== undefined) { + const colorFactor = extension.sheenColorFactor; + materialParams.sheenColor.setRGB(colorFactor[0], colorFactor[1], colorFactor[2], LinearSRGBColorSpace); + } + if (extension.sheenRoughnessFactor !== undefined) { + materialParams.sheenRoughness = extension.sheenRoughnessFactor; + } + if (extension.sheenColorTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "sheenColorMap", extension.sheenColorTexture, SRGBColorSpace)); + } + if (extension.sheenRoughnessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "sheenRoughnessMap", extension.sheenRoughnessTexture)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsTransmissionExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + if (extension.transmissionFactor !== undefined) { + materialParams.transmission = extension.transmissionFactor; + } + if (extension.transmissionTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "transmissionMap", extension.transmissionTexture)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsVolumeExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_VOLUME; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0; + if (extension.thicknessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "thicknessMap", extension.thicknessTexture)); + } + materialParams.attenuationDistance = extension.attenuationDistance || Infinity; + const colorArray = extension.attenuationColor || [1, 1, 1]; + materialParams.attenuationColor = new Color().setRGB(colorArray[0], colorArray[1], colorArray[2], LinearSRGBColorSpace); + return Promise.all(pending); + } +} + +class GLTFMaterialsIorExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_IOR; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const extension = materialDef.extensions[this.name]; + materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5; + return Promise.resolve(); + } +} + +class GLTFMaterialsSpecularExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1; + if (extension.specularTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "specularIntensityMap", extension.specularTexture)); + } + const colorArray = extension.specularColorFactor || [1, 1, 1]; + materialParams.specularColor = new Color().setRGB(colorArray[0], colorArray[1], colorArray[2], LinearSRGBColorSpace); + if (extension.specularColorTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "specularColorMap", extension.specularColorTexture, SRGBColorSpace)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsBumpExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.EXT_MATERIALS_BUMP; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + materialParams.bumpScale = extension.bumpFactor !== undefined ? extension.bumpFactor : 1; + if (extension.bumpTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "bumpMap", extension.bumpTexture)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsAnisotropyExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + if (extension.anisotropyStrength !== undefined) { + materialParams.anisotropy = extension.anisotropyStrength; + } + if (extension.anisotropyRotation !== undefined) { + materialParams.anisotropyRotation = extension.anisotropyRotation; + } + if (extension.anisotropyTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "anisotropyMap", extension.anisotropyTexture)); + } + return Promise.all(pending); + } +} + +class GLTFTextureBasisUExtension { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_TEXTURE_BASISU; + } + loadTexture(textureIndex) { + const parser = this.parser; + const json = parser.json; + const textureDef = json.textures[textureIndex]; + if (!textureDef.extensions || !textureDef.extensions[this.name]) { + return null; + } + const extension = textureDef.extensions[this.name]; + const loader = parser.options.ktx2Loader; + if (!loader) { + if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) { + throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures"); + } else { + return null; + } + } + return parser.loadTextureImage(textureIndex, extension.source, loader); + } +} + +class GLTFTextureWebPExtension { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.EXT_TEXTURE_WEBP; + this.isSupported = null; + } + loadTexture(textureIndex) { + const name2 = this.name; + const parser = this.parser; + const json = parser.json; + const textureDef = json.textures[textureIndex]; + if (!textureDef.extensions || !textureDef.extensions[name2]) { + return null; + } + const extension = textureDef.extensions[name2]; + const source = json.images[extension.source]; + let loader = parser.textureLoader; + if (source.uri) { + const handler = parser.options.manager.getHandler(source.uri); + if (handler !== null) + loader = handler; + } + return this.detectSupport().then(function(isSupported) { + if (isSupported) + return parser.loadTextureImage(textureIndex, extension.source, loader); + if (json.extensionsRequired && json.extensionsRequired.indexOf(name2) >= 0) { + throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported."); + } + return parser.loadTexture(textureIndex); + }); + } + detectSupport() { + if (!this.isSupported) { + this.isSupported = new Promise(function(resolve) { + const image = new Image; + image.src = "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA"; + image.onload = image.onerror = function() { + resolve(image.height === 1); + }; + }); + } + return this.isSupported; + } +} + +class GLTFTextureAVIFExtension { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.EXT_TEXTURE_AVIF; + this.isSupported = null; + } + loadTexture(textureIndex) { + const name2 = this.name; + const parser = this.parser; + const json = parser.json; + const textureDef = json.textures[textureIndex]; + if (!textureDef.extensions || !textureDef.extensions[name2]) { + return null; + } + const extension = textureDef.extensions[name2]; + const source = json.images[extension.source]; + let loader = parser.textureLoader; + if (source.uri) { + const handler = parser.options.manager.getHandler(source.uri); + if (handler !== null) + loader = handler; + } + return this.detectSupport().then(function(isSupported) { + if (isSupported) + return parser.loadTextureImage(textureIndex, extension.source, loader); + if (json.extensionsRequired && json.extensionsRequired.indexOf(name2) >= 0) { + throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported."); + } + return parser.loadTexture(textureIndex); + }); + } + detectSupport() { + if (!this.isSupported) { + this.isSupported = new Promise(function(resolve) { + const image = new Image; + image.src = "data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI="; + image.onload = image.onerror = function() { + resolve(image.height === 1); + }; + }); + } + return this.isSupported; + } +} + +class GLTFMeshoptCompression { + constructor(parser) { + this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION; + this.parser = parser; + } + loadBufferView(index2) { + const json = this.parser.json; + const bufferView = json.bufferViews[index2]; + if (bufferView.extensions && bufferView.extensions[this.name]) { + const extensionDef = bufferView.extensions[this.name]; + const buffer = this.parser.getDependency("buffer", extensionDef.buffer); + const decoder = this.parser.options.meshoptDecoder; + if (!decoder || !decoder.supported) { + if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) { + throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files"); + } else { + return null; + } + } + return buffer.then(function(res) { + const byteOffset = extensionDef.byteOffset || 0; + const byteLength = extensionDef.byteLength || 0; + const count = extensionDef.count; + const stride = extensionDef.byteStride; + const source = new Uint8Array(res, byteOffset, byteLength); + if (decoder.decodeGltfBufferAsync) { + return decoder.decodeGltfBufferAsync(count, stride, source, extensionDef.mode, extensionDef.filter).then(function(res2) { + return res2.buffer; + }); + } else { + return decoder.ready.then(function() { + const result = new ArrayBuffer(count * stride); + decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter); + return result; + }); + } + }); + } else { + return null; + } + } +} + +class GLTFMeshGpuInstancing2 { + constructor(parser) { + this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING; + this.parser = parser; + } + createNodeMesh(nodeIndex) { + const json = this.parser.json; + const nodeDef = json.nodes[nodeIndex]; + if (!nodeDef.extensions || !nodeDef.extensions[this.name] || nodeDef.mesh === undefined) { + return null; + } + const meshDef = json.meshes[nodeDef.mesh]; + for (const primitive of meshDef.primitives) { + if (primitive.mode !== WEBGL_CONSTANTS2.TRIANGLES && primitive.mode !== WEBGL_CONSTANTS2.TRIANGLE_STRIP && primitive.mode !== WEBGL_CONSTANTS2.TRIANGLE_FAN && primitive.mode !== undefined) { + return null; + } + } + const extensionDef = nodeDef.extensions[this.name]; + const attributesDef = extensionDef.attributes; + const pending = []; + const attributes = {}; + for (const key2 in attributesDef) { + pending.push(this.parser.getDependency("accessor", attributesDef[key2]).then((accessor) => { + attributes[key2] = accessor; + return attributes[key2]; + })); + } + if (pending.length < 1) { + return null; + } + pending.push(this.parser.createNodeMesh(nodeIndex)); + return Promise.all(pending).then((results) => { + const nodeObject = results.pop(); + const meshes = nodeObject.isGroup ? nodeObject.children : [nodeObject]; + const count = results[0].count; + const instancedMeshes = []; + for (const mesh of meshes) { + const m = new Matrix4; + const p = new Vector3; + const q2 = new Quaternion; + const s = new Vector3(1, 1, 1); + const instancedMesh = new InstancedMesh(mesh.geometry, mesh.material, count); + for (let i = 0;i < count; i++) { + if (attributes.TRANSLATION) { + p.fromBufferAttribute(attributes.TRANSLATION, i); + } + if (attributes.ROTATION) { + q2.fromBufferAttribute(attributes.ROTATION, i); + } + if (attributes.SCALE) { + s.fromBufferAttribute(attributes.SCALE, i); + } + instancedMesh.setMatrixAt(i, m.compose(p, q2, s)); + } + for (const attributeName in attributes) { + if (attributeName === "_COLOR_0") { + const attr = attributes[attributeName]; + instancedMesh.instanceColor = new InstancedBufferAttribute(attr.array, attr.itemSize, attr.normalized); + } else if (attributeName !== "TRANSLATION" && attributeName !== "ROTATION" && attributeName !== "SCALE") { + mesh.geometry.setAttribute(attributeName, attributes[attributeName]); + } + } + Object3D.prototype.copy.call(instancedMesh, mesh); + this.parser.assignFinalMaterial(instancedMesh); + instancedMeshes.push(instancedMesh); + } + if (nodeObject.isGroup) { + nodeObject.clear(); + nodeObject.add(...instancedMeshes); + return nodeObject; + } + return instancedMeshes[0]; + }); + } +} +var BINARY_EXTENSION_HEADER_MAGIC = "glTF"; +var BINARY_EXTENSION_HEADER_LENGTH = 12; +var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 1313821514, BIN: 5130562 }; + +class GLTFBinaryExtension { + constructor(data2) { + this.name = EXTENSIONS.KHR_BINARY_GLTF; + this.content = null; + this.body = null; + const headerView = new DataView(data2, 0, BINARY_EXTENSION_HEADER_LENGTH); + const textDecoder = new TextDecoder; + this.header = { + magic: textDecoder.decode(new Uint8Array(data2.slice(0, 4))), + version: headerView.getUint32(4, true), + length: headerView.getUint32(8, true) + }; + if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) { + throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header."); + } else if (this.header.version < 2) { + throw new Error("THREE.GLTFLoader: Legacy binary file detected."); + } + const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH; + const chunkView = new DataView(data2, BINARY_EXTENSION_HEADER_LENGTH); + let chunkIndex = 0; + while (chunkIndex < chunkContentsLength) { + const chunkLength = chunkView.getUint32(chunkIndex, true); + chunkIndex += 4; + const chunkType = chunkView.getUint32(chunkIndex, true); + chunkIndex += 4; + if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) { + const contentArray = new Uint8Array(data2, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength); + this.content = textDecoder.decode(contentArray); + } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) { + const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; + this.body = data2.slice(byteOffset, byteOffset + chunkLength); + } + chunkIndex += chunkLength; + } + if (this.content === null) { + throw new Error("THREE.GLTFLoader: JSON content not found."); + } + } +} + +class GLTFDracoMeshCompressionExtension { + constructor(json, dracoLoader) { + if (!dracoLoader) { + throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided."); + } + this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; + this.json = json; + this.dracoLoader = dracoLoader; + this.dracoLoader.preload(); + } + decodePrimitive(primitive, parser) { + const json = this.json; + const dracoLoader = this.dracoLoader; + const bufferViewIndex = primitive.extensions[this.name].bufferView; + const gltfAttributeMap = primitive.extensions[this.name].attributes; + const threeAttributeMap = {}; + const attributeNormalizedMap = {}; + const attributeTypeMap = {}; + for (const attributeName in gltfAttributeMap) { + const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); + threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName]; + } + for (const attributeName in primitive.attributes) { + const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); + if (gltfAttributeMap[attributeName] !== undefined) { + const accessorDef = json.accessors[primitive.attributes[attributeName]]; + const componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; + attributeTypeMap[threeAttributeName] = componentType.name; + attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true; + } + } + return parser.getDependency("bufferView", bufferViewIndex).then(function(bufferView) { + return new Promise(function(resolve, reject2) { + dracoLoader.decodeDracoFile(bufferView, function(geometry) { + for (const attributeName in geometry.attributes) { + const attribute = geometry.attributes[attributeName]; + const normalized = attributeNormalizedMap[attributeName]; + if (normalized !== undefined) + attribute.normalized = normalized; + } + resolve(geometry); + }, threeAttributeMap, attributeTypeMap, LinearSRGBColorSpace, reject2); + }); + }); + } +} + +class GLTFTextureTransformExtension { + constructor() { + this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; + } + extendTexture(texture, transform2) { + if ((transform2.texCoord === undefined || transform2.texCoord === texture.channel) && transform2.offset === undefined && transform2.rotation === undefined && transform2.scale === undefined) { + return texture; + } + texture = texture.clone(); + if (transform2.texCoord !== undefined) { + texture.channel = transform2.texCoord; + } + if (transform2.offset !== undefined) { + texture.offset.fromArray(transform2.offset); + } + if (transform2.rotation !== undefined) { + texture.rotation = transform2.rotation; + } + if (transform2.scale !== undefined) { + texture.repeat.fromArray(transform2.scale); + } + texture.needsUpdate = true; + return texture; + } +} + +class GLTFMeshQuantizationExtension { + constructor() { + this.name = EXTENSIONS.KHR_MESH_QUANTIZATION; + } +} + +class GLTFCubicSplineInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + copySampleValue_(index2) { + const result = this.resultBuffer, values2 = this.sampleValues, valueSize = this.valueSize, offset = index2 * valueSize * 3 + valueSize; + for (let i = 0;i !== valueSize; i++) { + result[i] = values2[offset + i]; + } + return result; + } + interpolate_(i1, t02, t4, t1) { + const result = this.resultBuffer; + const values2 = this.sampleValues; + const stride = this.valueSize; + const stride2 = stride * 2; + const stride3 = stride * 3; + const td3 = t1 - t02; + const p = (t4 - t02) / td3; + const pp = p * p; + const ppp = pp * p; + const offset1 = i1 * stride3; + const offset0 = offset1 - stride3; + const s22 = -2 * ppp + 3 * pp; + const s3 = ppp - pp; + const s0 = 1 - s22; + const s1 = s3 - pp + p; + for (let i = 0;i !== stride; i++) { + const p0 = values2[offset0 + i + stride]; + const m0 = values2[offset0 + i + stride2] * td3; + const p1 = values2[offset1 + i + stride]; + const m1 = values2[offset1 + i] * td3; + result[i] = s0 * p0 + s1 * m0 + s22 * p1 + s3 * m1; + } + return result; + } +} +var _q2 = new Quaternion; + +class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant { + interpolate_(i1, t02, t4, t1) { + const result = super.interpolate_(i1, t02, t4, t1); + _q2.fromArray(result).normalize().toArray(result); + return result; + } +} +var WEBGL_CONSTANTS2 = { + FLOAT: 5126, + FLOAT_MAT3: 35675, + FLOAT_MAT4: 35676, + FLOAT_VEC2: 35664, + FLOAT_VEC3: 35665, + FLOAT_VEC4: 35666, + LINEAR: 9729, + REPEAT: 10497, + SAMPLER_2D: 35678, + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6, + UNSIGNED_BYTE: 5121, + UNSIGNED_SHORT: 5123 +}; +var WEBGL_COMPONENT_TYPES = { + 5120: Int8Array, + 5121: Uint8Array, + 5122: Int16Array, + 5123: Uint16Array, + 5125: Uint32Array, + 5126: Float32Array +}; +var WEBGL_FILTERS = { + 9728: NearestFilter, + 9729: LinearFilter, + 9984: NearestMipmapNearestFilter, + 9985: LinearMipmapNearestFilter, + 9986: NearestMipmapLinearFilter, + 9987: LinearMipmapLinearFilter +}; +var WEBGL_WRAPPINGS = { + 33071: ClampToEdgeWrapping, + 33648: MirroredRepeatWrapping, + 10497: RepeatWrapping +}; +var WEBGL_TYPE_SIZES = { + SCALAR: 1, + VEC2: 2, + VEC3: 3, + VEC4: 4, + MAT2: 4, + MAT3: 9, + MAT4: 16 +}; +var ATTRIBUTES = { + POSITION: "position", + NORMAL: "normal", + TANGENT: "tangent", + TEXCOORD_0: "uv", + TEXCOORD_1: "uv1", + TEXCOORD_2: "uv2", + TEXCOORD_3: "uv3", + COLOR_0: "color", + WEIGHTS_0: "skinWeight", + JOINTS_0: "skinIndex" +}; +var PATH_PROPERTIES2 = { + scale: "scale", + translation: "position", + rotation: "quaternion", + weights: "morphTargetInfluences" +}; +var INTERPOLATION = { + CUBICSPLINE: undefined, + LINEAR: InterpolateLinear, + STEP: InterpolateDiscrete +}; +var ALPHA_MODES = { + OPAQUE: "OPAQUE", + MASK: "MASK", + BLEND: "BLEND" +}; +function createDefaultMaterial(cache) { + if (cache["DefaultMaterial"] === undefined) { + cache["DefaultMaterial"] = new MeshStandardMaterial({ + color: 16777215, + emissive: 0, + metalness: 1, + roughness: 1, + transparent: false, + depthTest: true, + side: FrontSide + }); + } + return cache["DefaultMaterial"]; +} +function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) { + for (const name2 in objectDef.extensions) { + if (knownExtensions[name2] === undefined) { + object.userData.gltfExtensions = object.userData.gltfExtensions || {}; + object.userData.gltfExtensions[name2] = objectDef.extensions[name2]; + } + } +} +function assignExtrasToUserData(object, gltfDef) { + if (gltfDef.extras !== undefined) { + if (typeof gltfDef.extras === "object") { + Object.assign(object.userData, gltfDef.extras); + } else { + console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, " + gltfDef.extras); + } + } +} +function addMorphTargets(geometry, targets, parser) { + let hasMorphPosition = false; + let hasMorphNormal = false; + let hasMorphColor = false; + for (let i = 0, il = targets.length;i < il; i++) { + const target = targets[i]; + if (target.POSITION !== undefined) + hasMorphPosition = true; + if (target.NORMAL !== undefined) + hasMorphNormal = true; + if (target.COLOR_0 !== undefined) + hasMorphColor = true; + if (hasMorphPosition && hasMorphNormal && hasMorphColor) + break; + } + if (!hasMorphPosition && !hasMorphNormal && !hasMorphColor) + return Promise.resolve(geometry); + const pendingPositionAccessors = []; + const pendingNormalAccessors = []; + const pendingColorAccessors = []; + for (let i = 0, il = targets.length;i < il; i++) { + const target = targets[i]; + if (hasMorphPosition) { + const pendingAccessor = target.POSITION !== undefined ? parser.getDependency("accessor", target.POSITION) : geometry.attributes.position; + pendingPositionAccessors.push(pendingAccessor); + } + if (hasMorphNormal) { + const pendingAccessor = target.NORMAL !== undefined ? parser.getDependency("accessor", target.NORMAL) : geometry.attributes.normal; + pendingNormalAccessors.push(pendingAccessor); + } + if (hasMorphColor) { + const pendingAccessor = target.COLOR_0 !== undefined ? parser.getDependency("accessor", target.COLOR_0) : geometry.attributes.color; + pendingColorAccessors.push(pendingAccessor); + } + } + return Promise.all([ + Promise.all(pendingPositionAccessors), + Promise.all(pendingNormalAccessors), + Promise.all(pendingColorAccessors) + ]).then(function(accessors) { + const morphPositions = accessors[0]; + const morphNormals = accessors[1]; + const morphColors = accessors[2]; + if (hasMorphPosition) + geometry.morphAttributes.position = morphPositions; + if (hasMorphNormal) + geometry.morphAttributes.normal = morphNormals; + if (hasMorphColor) + geometry.morphAttributes.color = morphColors; + geometry.morphTargetsRelative = true; + return geometry; + }); +} +function updateMorphTargets(mesh, meshDef) { + mesh.updateMorphTargets(); + if (meshDef.weights !== undefined) { + for (let i = 0, il = meshDef.weights.length;i < il; i++) { + mesh.morphTargetInfluences[i] = meshDef.weights[i]; + } + } + if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) { + const targetNames = meshDef.extras.targetNames; + if (mesh.morphTargetInfluences.length === targetNames.length) { + mesh.morphTargetDictionary = {}; + for (let i = 0, il = targetNames.length;i < il; i++) { + mesh.morphTargetDictionary[targetNames[i]] = i; + } + } else { + console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names."); + } + } +} +function createPrimitiveKey(primitiveDef) { + let geometryKey; + const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]; + if (dracoExtension) { + geometryKey = "draco:" + dracoExtension.bufferView + ":" + dracoExtension.indices + ":" + createAttributesKey(dracoExtension.attributes); + } else { + geometryKey = primitiveDef.indices + ":" + createAttributesKey(primitiveDef.attributes) + ":" + primitiveDef.mode; + } + if (primitiveDef.targets !== undefined) { + for (let i = 0, il = primitiveDef.targets.length;i < il; i++) { + geometryKey += ":" + createAttributesKey(primitiveDef.targets[i]); + } + } + return geometryKey; +} +function createAttributesKey(attributes) { + let attributesKey = ""; + const keys2 = Object.keys(attributes).sort(); + for (let i = 0, il = keys2.length;i < il; i++) { + attributesKey += keys2[i] + ":" + attributes[keys2[i]] + ";"; + } + return attributesKey; +} +function getNormalizedComponentScale(constructor) { + switch (constructor) { + case Int8Array: + return 1 / 127; + case Uint8Array: + return 1 / 255; + case Int16Array: + return 1 / 32767; + case Uint16Array: + return 1 / 65535; + default: + throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type."); + } +} +function getImageURIMimeType(uri) { + if (uri.search(/\.jpe?g($|\?)/i) > 0 || uri.search(/^data\:image\/jpeg/) === 0) + return "image/jpeg"; + if (uri.search(/\.webp($|\?)/i) > 0 || uri.search(/^data\:image\/webp/) === 0) + return "image/webp"; + if (uri.search(/\.ktx2($|\?)/i) > 0 || uri.search(/^data\:image\/ktx2/) === 0) + return "image/ktx2"; + return "image/png"; +} +var _identityMatrix2 = new Matrix4; + +class GLTFParser { + constructor(json = {}, options = {}) { + this.json = json; + this.extensions = {}; + this.plugins = {}; + this.options = options; + this.cache = new GLTFRegistry; + this.associations = new Map; + this.primitiveCache = {}; + this.nodeCache = {}; + this.meshCache = { refs: {}, uses: {} }; + this.cameraCache = { refs: {}, uses: {} }; + this.lightCache = { refs: {}, uses: {} }; + this.sourceCache = {}; + this.textureCache = {}; + this.nodeNamesUsed = {}; + let isSafari2 = false; + let safariVersion = -1; + let isFirefox = false; + let firefoxVersion = -1; + if (typeof navigator !== "undefined") { + const userAgent = navigator.userAgent; + isSafari2 = /^((?!chrome|android).)*safari/i.test(userAgent) === true; + const safariMatch = userAgent.match(/Version\/(\d+)/); + safariVersion = isSafari2 && safariMatch ? parseInt(safariMatch[1], 10) : -1; + isFirefox = userAgent.indexOf("Firefox") > -1; + firefoxVersion = isFirefox ? userAgent.match(/Firefox\/([0-9]+)\./)[1] : -1; + } + if (typeof createImageBitmap === "undefined" || isSafari2 && safariVersion < 17 || isFirefox && firefoxVersion < 98) { + this.textureLoader = new TextureLoader(this.options.manager); + } else { + this.textureLoader = new ImageBitmapLoader(this.options.manager); + } + this.textureLoader.setCrossOrigin(this.options.crossOrigin); + this.textureLoader.setRequestHeader(this.options.requestHeader); + this.fileLoader = new FileLoader(this.options.manager); + this.fileLoader.setResponseType("arraybuffer"); + if (this.options.crossOrigin === "use-credentials") { + this.fileLoader.setWithCredentials(true); + } + } + setExtensions(extensions) { + this.extensions = extensions; + } + setPlugins(plugins) { + this.plugins = plugins; + } + parse(onLoad, onError) { + const parser = this; + const json = this.json; + const extensions = this.extensions; + this.cache.removeAll(); + this.nodeCache = {}; + this._invokeAll(function(ext) { + return ext._markDefs && ext._markDefs(); + }); + Promise.all(this._invokeAll(function(ext) { + return ext.beforeRoot && ext.beforeRoot(); + })).then(function() { + return Promise.all([ + parser.getDependencies("scene"), + parser.getDependencies("animation"), + parser.getDependencies("camera") + ]); + }).then(function(dependencies) { + const result = { + scene: dependencies[0][json.scene || 0], + scenes: dependencies[0], + animations: dependencies[1], + cameras: dependencies[2], + asset: json.asset, + parser, + userData: {} + }; + addUnknownExtensionsToUserData(extensions, result, json); + assignExtrasToUserData(result, json); + return Promise.all(parser._invokeAll(function(ext) { + return ext.afterRoot && ext.afterRoot(result); + })).then(function() { + for (const scene of result.scenes) { + scene.updateMatrixWorld(); + } + onLoad(result); + }); + }).catch(onError); + } + _markDefs() { + const nodeDefs = this.json.nodes || []; + const skinDefs = this.json.skins || []; + const meshDefs = this.json.meshes || []; + for (let skinIndex = 0, skinLength = skinDefs.length;skinIndex < skinLength; skinIndex++) { + const joints = skinDefs[skinIndex].joints; + for (let i = 0, il = joints.length;i < il; i++) { + nodeDefs[joints[i]].isBone = true; + } + } + for (let nodeIndex = 0, nodeLength = nodeDefs.length;nodeIndex < nodeLength; nodeIndex++) { + const nodeDef = nodeDefs[nodeIndex]; + if (nodeDef.mesh !== undefined) { + this._addNodeRef(this.meshCache, nodeDef.mesh); + if (nodeDef.skin !== undefined) { + meshDefs[nodeDef.mesh].isSkinnedMesh = true; + } + } + if (nodeDef.camera !== undefined) { + this._addNodeRef(this.cameraCache, nodeDef.camera); + } + } + } + _addNodeRef(cache, index2) { + if (index2 === undefined) + return; + if (cache.refs[index2] === undefined) { + cache.refs[index2] = cache.uses[index2] = 0; + } + cache.refs[index2]++; + } + _getNodeRef(cache, index2, object) { + if (cache.refs[index2] <= 1) + return object; + const ref = object.clone(); + const updateMappings = (original, clone) => { + const mappings = this.associations.get(original); + if (mappings != null) { + this.associations.set(clone, mappings); + } + for (const [i, child] of original.children.entries()) { + updateMappings(child, clone.children[i]); + } + }; + updateMappings(object, ref); + ref.name += "_instance_" + cache.uses[index2]++; + return ref; + } + _invokeOne(func) { + const extensions = Object.values(this.plugins); + extensions.push(this); + for (let i = 0;i < extensions.length; i++) { + const result = func(extensions[i]); + if (result) + return result; + } + return null; + } + _invokeAll(func) { + const extensions = Object.values(this.plugins); + extensions.unshift(this); + const pending = []; + for (let i = 0;i < extensions.length; i++) { + const result = func(extensions[i]); + if (result) + pending.push(result); + } + return pending; + } + getDependency(type, index2) { + const cacheKey = type + ":" + index2; + let dependency = this.cache.get(cacheKey); + if (!dependency) { + switch (type) { + case "scene": + dependency = this.loadScene(index2); + break; + case "node": + dependency = this._invokeOne(function(ext) { + return ext.loadNode && ext.loadNode(index2); + }); + break; + case "mesh": + dependency = this._invokeOne(function(ext) { + return ext.loadMesh && ext.loadMesh(index2); + }); + break; + case "accessor": + dependency = this.loadAccessor(index2); + break; + case "bufferView": + dependency = this._invokeOne(function(ext) { + return ext.loadBufferView && ext.loadBufferView(index2); + }); + break; + case "buffer": + dependency = this.loadBuffer(index2); + break; + case "material": + dependency = this._invokeOne(function(ext) { + return ext.loadMaterial && ext.loadMaterial(index2); + }); + break; + case "texture": + dependency = this._invokeOne(function(ext) { + return ext.loadTexture && ext.loadTexture(index2); + }); + break; + case "skin": + dependency = this.loadSkin(index2); + break; + case "animation": + dependency = this._invokeOne(function(ext) { + return ext.loadAnimation && ext.loadAnimation(index2); + }); + break; + case "camera": + dependency = this.loadCamera(index2); + break; + default: + dependency = this._invokeOne(function(ext) { + return ext != this && ext.getDependency && ext.getDependency(type, index2); + }); + if (!dependency) { + throw new Error("Unknown type: " + type); + } + break; + } + this.cache.add(cacheKey, dependency); + } + return dependency; + } + getDependencies(type) { + let dependencies = this.cache.get(type); + if (!dependencies) { + const parser = this; + const defs = this.json[type + (type === "mesh" ? "es" : "s")] || []; + dependencies = Promise.all(defs.map(function(def, index2) { + return parser.getDependency(type, index2); + })); + this.cache.add(type, dependencies); + } + return dependencies; + } + loadBuffer(bufferIndex) { + const bufferDef = this.json.buffers[bufferIndex]; + const loader = this.fileLoader; + if (bufferDef.type && bufferDef.type !== "arraybuffer") { + throw new Error("THREE.GLTFLoader: " + bufferDef.type + " buffer type is not supported."); + } + if (bufferDef.uri === undefined && bufferIndex === 0) { + return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body); + } + const options = this.options; + return new Promise(function(resolve, reject2) { + loader.load(LoaderUtils.resolveURL(bufferDef.uri, options.path), resolve, undefined, function() { + reject2(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".')); + }); + }); + } + loadBufferView(bufferViewIndex) { + const bufferViewDef = this.json.bufferViews[bufferViewIndex]; + return this.getDependency("buffer", bufferViewDef.buffer).then(function(buffer) { + const byteLength = bufferViewDef.byteLength || 0; + const byteOffset = bufferViewDef.byteOffset || 0; + return buffer.slice(byteOffset, byteOffset + byteLength); + }); + } + loadAccessor(accessorIndex) { + const parser = this; + const json = this.json; + const accessorDef = this.json.accessors[accessorIndex]; + if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) { + const itemSize = WEBGL_TYPE_SIZES[accessorDef.type]; + const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; + const normalized = accessorDef.normalized === true; + const array = new TypedArray(accessorDef.count * itemSize); + return Promise.resolve(new BufferAttribute(array, itemSize, normalized)); + } + const pendingBufferViews = []; + if (accessorDef.bufferView !== undefined) { + pendingBufferViews.push(this.getDependency("bufferView", accessorDef.bufferView)); + } else { + pendingBufferViews.push(null); + } + if (accessorDef.sparse !== undefined) { + pendingBufferViews.push(this.getDependency("bufferView", accessorDef.sparse.indices.bufferView)); + pendingBufferViews.push(this.getDependency("bufferView", accessorDef.sparse.values.bufferView)); + } + return Promise.all(pendingBufferViews).then(function(bufferViews) { + const bufferView = bufferViews[0]; + const itemSize = WEBGL_TYPE_SIZES[accessorDef.type]; + const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; + const elementBytes = TypedArray.BYTES_PER_ELEMENT; + const itemBytes = elementBytes * itemSize; + const byteOffset = accessorDef.byteOffset || 0; + const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined; + const normalized = accessorDef.normalized === true; + let array, bufferAttribute; + if (byteStride && byteStride !== itemBytes) { + const ibSlice = Math.floor(byteOffset / byteStride); + const ibCacheKey = "InterleavedBuffer:" + accessorDef.bufferView + ":" + accessorDef.componentType + ":" + ibSlice + ":" + accessorDef.count; + let ib = parser.cache.get(ibCacheKey); + if (!ib) { + array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); + ib = new InterleavedBuffer(array, byteStride / elementBytes); + parser.cache.add(ibCacheKey, ib); + } + bufferAttribute = new InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized); + } else { + if (bufferView === null) { + array = new TypedArray(accessorDef.count * itemSize); + } else { + array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize); + } + bufferAttribute = new BufferAttribute(array, itemSize, normalized); + } + if (accessorDef.sparse !== undefined) { + const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; + const TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType]; + const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; + const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; + const sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices); + const sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize); + if (bufferView !== null) { + bufferAttribute = new BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized); + } + bufferAttribute.normalized = false; + for (let i = 0, il = sparseIndices.length;i < il; i++) { + const index2 = sparseIndices[i]; + bufferAttribute.setX(index2, sparseValues[i * itemSize]); + if (itemSize >= 2) + bufferAttribute.setY(index2, sparseValues[i * itemSize + 1]); + if (itemSize >= 3) + bufferAttribute.setZ(index2, sparseValues[i * itemSize + 2]); + if (itemSize >= 4) + bufferAttribute.setW(index2, sparseValues[i * itemSize + 3]); + if (itemSize >= 5) + throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute."); + } + bufferAttribute.normalized = normalized; + } + return bufferAttribute; + }); + } + loadTexture(textureIndex) { + const json = this.json; + const options = this.options; + const textureDef = json.textures[textureIndex]; + const sourceIndex = textureDef.source; + const sourceDef = json.images[sourceIndex]; + let loader = this.textureLoader; + if (sourceDef.uri) { + const handler = options.manager.getHandler(sourceDef.uri); + if (handler !== null) + loader = handler; + } + return this.loadTextureImage(textureIndex, sourceIndex, loader); + } + loadTextureImage(textureIndex, sourceIndex, loader) { + const parser = this; + const json = this.json; + const textureDef = json.textures[textureIndex]; + const sourceDef = json.images[sourceIndex]; + const cacheKey = (sourceDef.uri || sourceDef.bufferView) + ":" + textureDef.sampler; + if (this.textureCache[cacheKey]) { + return this.textureCache[cacheKey]; + } + const promise = this.loadImageSource(sourceIndex, loader).then(function(texture) { + texture.flipY = false; + texture.name = textureDef.name || sourceDef.name || ""; + if (texture.name === "" && typeof sourceDef.uri === "string" && sourceDef.uri.startsWith("data:image/") === false) { + texture.name = sourceDef.uri; + } + const samplers = json.samplers || {}; + const sampler = samplers[textureDef.sampler] || {}; + texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || LinearFilter; + texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || LinearMipmapLinearFilter; + texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || RepeatWrapping; + texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || RepeatWrapping; + texture.generateMipmaps = !texture.isCompressedTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; + parser.associations.set(texture, { textures: textureIndex }); + return texture; + }).catch(function() { + return null; + }); + this.textureCache[cacheKey] = promise; + return promise; + } + loadImageSource(sourceIndex, loader) { + const parser = this; + const json = this.json; + const options = this.options; + if (this.sourceCache[sourceIndex] !== undefined) { + return this.sourceCache[sourceIndex].then((texture) => texture.clone()); + } + const sourceDef = json.images[sourceIndex]; + const URL2 = self.URL || self.webkitURL; + let sourceURI = sourceDef.uri || ""; + let isObjectURL = false; + if (sourceDef.bufferView !== undefined) { + sourceURI = parser.getDependency("bufferView", sourceDef.bufferView).then(function(bufferView) { + isObjectURL = true; + const blob = new Blob([bufferView], { type: sourceDef.mimeType }); + sourceURI = URL2.createObjectURL(blob); + return sourceURI; + }); + } else if (sourceDef.uri === undefined) { + throw new Error("THREE.GLTFLoader: Image " + sourceIndex + " is missing URI and bufferView"); + } + const promise = Promise.resolve(sourceURI).then(function(sourceURI2) { + return new Promise(function(resolve, reject2) { + let onLoad = resolve; + if (loader.isImageBitmapLoader === true) { + onLoad = function(imageBitmap) { + const texture = new Texture(imageBitmap); + texture.needsUpdate = true; + resolve(texture); + }; + } + loader.load(LoaderUtils.resolveURL(sourceURI2, options.path), onLoad, undefined, reject2); + }); + }).then(function(texture) { + if (isObjectURL === true) { + URL2.revokeObjectURL(sourceURI); + } + assignExtrasToUserData(texture, sourceDef); + texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType(sourceDef.uri); + return texture; + }).catch(function(error) { + console.error("THREE.GLTFLoader: Couldn't load texture", sourceURI); + throw error; + }); + this.sourceCache[sourceIndex] = promise; + return promise; + } + assignTexture(materialParams, mapName, mapDef, colorSpace) { + const parser = this; + return this.getDependency("texture", mapDef.index).then(function(texture) { + if (!texture) + return null; + if (mapDef.texCoord !== undefined && mapDef.texCoord > 0) { + texture = texture.clone(); + texture.channel = mapDef.texCoord; + } + if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) { + const transform2 = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined; + if (transform2) { + const gltfReference = parser.associations.get(texture); + texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform2); + parser.associations.set(texture, gltfReference); + } + } + if (colorSpace !== undefined) { + texture.colorSpace = colorSpace; + } + materialParams[mapName] = texture; + return texture; + }); + } + assignFinalMaterial(mesh) { + const geometry = mesh.geometry; + let material = mesh.material; + const useDerivativeTangents = geometry.attributes.tangent === undefined; + const useVertexColors = geometry.attributes.color !== undefined; + const useFlatShading = geometry.attributes.normal === undefined; + if (mesh.isPoints) { + const cacheKey = "PointsMaterial:" + material.uuid; + let pointsMaterial = this.cache.get(cacheKey); + if (!pointsMaterial) { + pointsMaterial = new PointsMaterial; + Material.prototype.copy.call(pointsMaterial, material); + pointsMaterial.color.copy(material.color); + pointsMaterial.map = material.map; + pointsMaterial.sizeAttenuation = false; + this.cache.add(cacheKey, pointsMaterial); + } + material = pointsMaterial; + } else if (mesh.isLine) { + const cacheKey = "LineBasicMaterial:" + material.uuid; + let lineMaterial = this.cache.get(cacheKey); + if (!lineMaterial) { + lineMaterial = new LineBasicMaterial; + Material.prototype.copy.call(lineMaterial, material); + lineMaterial.color.copy(material.color); + lineMaterial.map = material.map; + this.cache.add(cacheKey, lineMaterial); + } + material = lineMaterial; + } + if (useDerivativeTangents || useVertexColors || useFlatShading) { + let cacheKey = "ClonedMaterial:" + material.uuid + ":"; + if (useDerivativeTangents) + cacheKey += "derivative-tangents:"; + if (useVertexColors) + cacheKey += "vertex-colors:"; + if (useFlatShading) + cacheKey += "flat-shading:"; + let cachedMaterial = this.cache.get(cacheKey); + if (!cachedMaterial) { + cachedMaterial = material.clone(); + if (useVertexColors) + cachedMaterial.vertexColors = true; + if (useFlatShading) + cachedMaterial.flatShading = true; + if (useDerivativeTangents) { + if (cachedMaterial.normalScale) + cachedMaterial.normalScale.y *= -1; + if (cachedMaterial.clearcoatNormalScale) + cachedMaterial.clearcoatNormalScale.y *= -1; + } + this.cache.add(cacheKey, cachedMaterial); + this.associations.set(cachedMaterial, this.associations.get(material)); + } + material = cachedMaterial; + } + mesh.material = material; + } + getMaterialType() { + return MeshStandardMaterial; + } + loadMaterial(materialIndex) { + const parser = this; + const json = this.json; + const extensions = this.extensions; + const materialDef = json.materials[materialIndex]; + let materialType; + const materialParams = {}; + const materialExtensions = materialDef.extensions || {}; + const pending = []; + if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) { + const kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT]; + materialType = kmuExtension.getMaterialType(); + pending.push(kmuExtension.extendParams(materialParams, materialDef, parser)); + } else { + const metallicRoughness = materialDef.pbrMetallicRoughness || {}; + materialParams.color = new Color(1, 1, 1); + materialParams.opacity = 1; + if (Array.isArray(metallicRoughness.baseColorFactor)) { + const array = metallicRoughness.baseColorFactor; + materialParams.color.setRGB(array[0], array[1], array[2], LinearSRGBColorSpace); + materialParams.opacity = array[3]; + } + if (metallicRoughness.baseColorTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, SRGBColorSpace)); + } + materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1; + materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1; + if (metallicRoughness.metallicRoughnessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "metalnessMap", metallicRoughness.metallicRoughnessTexture)); + pending.push(parser.assignTexture(materialParams, "roughnessMap", metallicRoughness.metallicRoughnessTexture)); + } + materialType = this._invokeOne(function(ext) { + return ext.getMaterialType && ext.getMaterialType(materialIndex); + }); + pending.push(Promise.all(this._invokeAll(function(ext) { + return ext.extendMaterialParams && ext.extendMaterialParams(materialIndex, materialParams); + }))); + } + if (materialDef.doubleSided === true) { + materialParams.side = DoubleSide; + } + const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; + if (alphaMode === ALPHA_MODES.BLEND) { + materialParams.transparent = true; + materialParams.depthWrite = false; + } else { + materialParams.transparent = false; + if (alphaMode === ALPHA_MODES.MASK) { + materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5; + } + } + if (materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial) { + pending.push(parser.assignTexture(materialParams, "normalMap", materialDef.normalTexture)); + materialParams.normalScale = new Vector2(1, 1); + if (materialDef.normalTexture.scale !== undefined) { + const scale2 = materialDef.normalTexture.scale; + materialParams.normalScale.set(scale2, scale2); + } + } + if (materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial) { + pending.push(parser.assignTexture(materialParams, "aoMap", materialDef.occlusionTexture)); + if (materialDef.occlusionTexture.strength !== undefined) { + materialParams.aoMapIntensity = materialDef.occlusionTexture.strength; + } + } + if (materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial) { + const emissiveFactor = materialDef.emissiveFactor; + materialParams.emissive = new Color().setRGB(emissiveFactor[0], emissiveFactor[1], emissiveFactor[2], LinearSRGBColorSpace); + } + if (materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial) { + pending.push(parser.assignTexture(materialParams, "emissiveMap", materialDef.emissiveTexture, SRGBColorSpace)); + } + return Promise.all(pending).then(function() { + const material = new materialType(materialParams); + if (materialDef.name) + material.name = materialDef.name; + assignExtrasToUserData(material, materialDef); + parser.associations.set(material, { materials: materialIndex }); + if (materialDef.extensions) + addUnknownExtensionsToUserData(extensions, material, materialDef); + return material; + }); + } + createUniqueName(originalName) { + const sanitizedName = PropertyBinding.sanitizeNodeName(originalName || ""); + if (sanitizedName in this.nodeNamesUsed) { + return sanitizedName + "_" + ++this.nodeNamesUsed[sanitizedName]; + } else { + this.nodeNamesUsed[sanitizedName] = 0; + return sanitizedName; + } + } + loadGeometries(primitives) { + const parser = this; + const extensions = this.extensions; + const cache = this.primitiveCache; + function createDracoPrimitive(primitive) { + return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function(geometry) { + return addPrimitiveAttributes(geometry, primitive, parser); + }); + } + const pending = []; + for (let i = 0, il = primitives.length;i < il; i++) { + const primitive = primitives[i]; + const cacheKey = createPrimitiveKey(primitive); + const cached = cache[cacheKey]; + if (cached) { + pending.push(cached.promise); + } else { + let geometryPromise; + if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) { + geometryPromise = createDracoPrimitive(primitive); + } else { + geometryPromise = addPrimitiveAttributes(new BufferGeometry, primitive, parser); + } + cache[cacheKey] = { primitive, promise: geometryPromise }; + pending.push(geometryPromise); + } + } + return Promise.all(pending); + } + loadMesh(meshIndex) { + const parser = this; + const json = this.json; + const extensions = this.extensions; + const meshDef = json.meshes[meshIndex]; + const primitives = meshDef.primitives; + const pending = []; + for (let i = 0, il = primitives.length;i < il; i++) { + const material = primitives[i].material === undefined ? createDefaultMaterial(this.cache) : this.getDependency("material", primitives[i].material); + pending.push(material); + } + pending.push(parser.loadGeometries(primitives)); + return Promise.all(pending).then(function(results) { + const materials = results.slice(0, results.length - 1); + const geometries = results[results.length - 1]; + const meshes = []; + for (let i = 0, il = geometries.length;i < il; i++) { + const geometry = geometries[i]; + const primitive = primitives[i]; + let mesh; + const material = materials[i]; + if (primitive.mode === WEBGL_CONSTANTS2.TRIANGLES || primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_FAN || primitive.mode === undefined) { + mesh = meshDef.isSkinnedMesh === true ? new SkinnedMesh(geometry, material) : new Mesh(geometry, material); + if (mesh.isSkinnedMesh === true) { + mesh.normalizeSkinWeights(); + } + if (primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_STRIP) { + mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleStripDrawMode); + } else if (primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_FAN) { + mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleFanDrawMode); + } + } else if (primitive.mode === WEBGL_CONSTANTS2.LINES) { + mesh = new LineSegments(geometry, material); + } else if (primitive.mode === WEBGL_CONSTANTS2.LINE_STRIP) { + mesh = new Line(geometry, material); + } else if (primitive.mode === WEBGL_CONSTANTS2.LINE_LOOP) { + mesh = new LineLoop(geometry, material); + } else if (primitive.mode === WEBGL_CONSTANTS2.POINTS) { + mesh = new Points(geometry, material); + } else { + throw new Error("THREE.GLTFLoader: Primitive mode unsupported: " + primitive.mode); + } + if (Object.keys(mesh.geometry.morphAttributes).length > 0) { + updateMorphTargets(mesh, meshDef); + } + mesh.name = parser.createUniqueName(meshDef.name || "mesh_" + meshIndex); + assignExtrasToUserData(mesh, meshDef); + if (primitive.extensions) + addUnknownExtensionsToUserData(extensions, mesh, primitive); + parser.assignFinalMaterial(mesh); + meshes.push(mesh); + } + for (let i = 0, il = meshes.length;i < il; i++) { + parser.associations.set(meshes[i], { + meshes: meshIndex, + primitives: i + }); + } + if (meshes.length === 1) { + if (meshDef.extensions) + addUnknownExtensionsToUserData(extensions, meshes[0], meshDef); + return meshes[0]; + } + const group = new Group; + if (meshDef.extensions) + addUnknownExtensionsToUserData(extensions, group, meshDef); + parser.associations.set(group, { meshes: meshIndex }); + for (let i = 0, il = meshes.length;i < il; i++) { + group.add(meshes[i]); + } + return group; + }); + } + loadCamera(cameraIndex) { + let camera; + const cameraDef = this.json.cameras[cameraIndex]; + const params = cameraDef[cameraDef.type]; + if (!params) { + console.warn("THREE.GLTFLoader: Missing camera parameters."); + return; + } + if (cameraDef.type === "perspective") { + camera = new PerspectiveCamera(MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2000000); + } else if (cameraDef.type === "orthographic") { + camera = new OrthographicCamera(-params.xmag, params.xmag, params.ymag, -params.ymag, params.znear, params.zfar); + } + if (cameraDef.name) + camera.name = this.createUniqueName(cameraDef.name); + assignExtrasToUserData(camera, cameraDef); + return Promise.resolve(camera); + } + loadSkin(skinIndex) { + const skinDef = this.json.skins[skinIndex]; + const pending = []; + for (let i = 0, il = skinDef.joints.length;i < il; i++) { + pending.push(this._loadNodeShallow(skinDef.joints[i])); + } + if (skinDef.inverseBindMatrices !== undefined) { + pending.push(this.getDependency("accessor", skinDef.inverseBindMatrices)); + } else { + pending.push(null); + } + return Promise.all(pending).then(function(results) { + const inverseBindMatrices = results.pop(); + const jointNodes = results; + const bones = []; + const boneInverses = []; + for (let i = 0, il = jointNodes.length;i < il; i++) { + const jointNode = jointNodes[i]; + if (jointNode) { + bones.push(jointNode); + const mat = new Matrix4; + if (inverseBindMatrices !== null) { + mat.fromArray(inverseBindMatrices.array, i * 16); + } + boneInverses.push(mat); + } else { + console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[i]); + } + } + return new Skeleton(bones, boneInverses); + }); + } + loadAnimation(animationIndex) { + const json = this.json; + const parser = this; + const animationDef = json.animations[animationIndex]; + const animationName = animationDef.name ? animationDef.name : "animation_" + animationIndex; + const pendingNodes = []; + const pendingInputAccessors = []; + const pendingOutputAccessors = []; + const pendingSamplers = []; + const pendingTargets = []; + for (let i = 0, il = animationDef.channels.length;i < il; i++) { + const channel = animationDef.channels[i]; + const sampler = animationDef.samplers[channel.sampler]; + const target = channel.target; + const name2 = target.node; + const input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input; + const output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output; + if (target.node === undefined) + continue; + pendingNodes.push(this.getDependency("node", name2)); + pendingInputAccessors.push(this.getDependency("accessor", input)); + pendingOutputAccessors.push(this.getDependency("accessor", output)); + pendingSamplers.push(sampler); + pendingTargets.push(target); + } + return Promise.all([ + Promise.all(pendingNodes), + Promise.all(pendingInputAccessors), + Promise.all(pendingOutputAccessors), + Promise.all(pendingSamplers), + Promise.all(pendingTargets) + ]).then(function(dependencies) { + const nodes = dependencies[0]; + const inputAccessors = dependencies[1]; + const outputAccessors = dependencies[2]; + const samplers = dependencies[3]; + const targets = dependencies[4]; + const tracks = []; + for (let i = 0, il = nodes.length;i < il; i++) { + const node = nodes[i]; + const inputAccessor = inputAccessors[i]; + const outputAccessor = outputAccessors[i]; + const sampler = samplers[i]; + const target = targets[i]; + if (node === undefined) + continue; + if (node.updateMatrix) { + node.updateMatrix(); + } + const createdTracks = parser._createAnimationTracks(node, inputAccessor, outputAccessor, sampler, target); + if (createdTracks) { + for (let k2 = 0;k2 < createdTracks.length; k2++) { + tracks.push(createdTracks[k2]); + } + } + } + return new AnimationClip(animationName, undefined, tracks); + }); + } + createNodeMesh(nodeIndex) { + const json = this.json; + const parser = this; + const nodeDef = json.nodes[nodeIndex]; + if (nodeDef.mesh === undefined) + return null; + return parser.getDependency("mesh", nodeDef.mesh).then(function(mesh) { + const node = parser._getNodeRef(parser.meshCache, nodeDef.mesh, mesh); + if (nodeDef.weights !== undefined) { + node.traverse(function(o) { + if (!o.isMesh) + return; + for (let i = 0, il = nodeDef.weights.length;i < il; i++) { + o.morphTargetInfluences[i] = nodeDef.weights[i]; + } + }); + } + return node; + }); + } + loadNode(nodeIndex) { + const json = this.json; + const parser = this; + const nodeDef = json.nodes[nodeIndex]; + const nodePending = parser._loadNodeShallow(nodeIndex); + const childPending = []; + const childrenDef = nodeDef.children || []; + for (let i = 0, il = childrenDef.length;i < il; i++) { + childPending.push(parser.getDependency("node", childrenDef[i])); + } + const skeletonPending = nodeDef.skin === undefined ? Promise.resolve(null) : parser.getDependency("skin", nodeDef.skin); + return Promise.all([ + nodePending, + Promise.all(childPending), + skeletonPending + ]).then(function(results) { + const node = results[0]; + const children = results[1]; + const skeleton = results[2]; + if (skeleton !== null) { + node.traverse(function(mesh) { + if (!mesh.isSkinnedMesh) + return; + mesh.bind(skeleton, _identityMatrix2); + }); + } + for (let i = 0, il = children.length;i < il; i++) { + node.add(children[i]); + } + return node; + }); + } + _loadNodeShallow(nodeIndex) { + const json = this.json; + const extensions = this.extensions; + const parser = this; + if (this.nodeCache[nodeIndex] !== undefined) { + return this.nodeCache[nodeIndex]; + } + const nodeDef = json.nodes[nodeIndex]; + const nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : ""; + const pending = []; + const meshPromise = parser._invokeOne(function(ext) { + return ext.createNodeMesh && ext.createNodeMesh(nodeIndex); + }); + if (meshPromise) { + pending.push(meshPromise); + } + if (nodeDef.camera !== undefined) { + pending.push(parser.getDependency("camera", nodeDef.camera).then(function(camera) { + return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera); + })); + } + parser._invokeAll(function(ext) { + return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex); + }).forEach(function(promise) { + pending.push(promise); + }); + this.nodeCache[nodeIndex] = Promise.all(pending).then(function(objects) { + let node; + if (nodeDef.isBone === true) { + node = new Bone; + } else if (objects.length > 1) { + node = new Group; + } else if (objects.length === 1) { + node = objects[0]; + } else { + node = new Object3D; + } + if (node !== objects[0]) { + for (let i = 0, il = objects.length;i < il; i++) { + node.add(objects[i]); + } + } + if (nodeDef.name) { + node.userData.name = nodeDef.name; + node.name = nodeName; + } + assignExtrasToUserData(node, nodeDef); + if (nodeDef.extensions) + addUnknownExtensionsToUserData(extensions, node, nodeDef); + if (nodeDef.matrix !== undefined) { + const matrix = new Matrix4; + matrix.fromArray(nodeDef.matrix); + node.applyMatrix4(matrix); + } else { + if (nodeDef.translation !== undefined) { + node.position.fromArray(nodeDef.translation); + } + if (nodeDef.rotation !== undefined) { + node.quaternion.fromArray(nodeDef.rotation); + } + if (nodeDef.scale !== undefined) { + node.scale.fromArray(nodeDef.scale); + } + } + if (!parser.associations.has(node)) { + parser.associations.set(node, {}); + } + parser.associations.get(node).nodes = nodeIndex; + return node; + }); + return this.nodeCache[nodeIndex]; + } + loadScene(sceneIndex) { + const extensions = this.extensions; + const sceneDef = this.json.scenes[sceneIndex]; + const parser = this; + const scene = new Group; + if (sceneDef.name) + scene.name = parser.createUniqueName(sceneDef.name); + assignExtrasToUserData(scene, sceneDef); + if (sceneDef.extensions) + addUnknownExtensionsToUserData(extensions, scene, sceneDef); + const nodeIds = sceneDef.nodes || []; + const pending = []; + for (let i = 0, il = nodeIds.length;i < il; i++) { + pending.push(parser.getDependency("node", nodeIds[i])); + } + return Promise.all(pending).then(function(nodes) { + for (let i = 0, il = nodes.length;i < il; i++) { + scene.add(nodes[i]); + } + const reduceAssociations = (node) => { + const reducedAssociations = new Map; + for (const [key2, value2] of parser.associations) { + if (key2 instanceof Material || key2 instanceof Texture) { + reducedAssociations.set(key2, value2); + } + } + node.traverse((node2) => { + const mappings = parser.associations.get(node2); + if (mappings != null) { + reducedAssociations.set(node2, mappings); + } + }); + return reducedAssociations; + }; + parser.associations = reduceAssociations(scene); + return scene; + }); + } + _createAnimationTracks(node, inputAccessor, outputAccessor, sampler, target) { + const tracks = []; + const targetName = node.name ? node.name : node.uuid; + const targetNames = []; + if (PATH_PROPERTIES2[target.path] === PATH_PROPERTIES2.weights) { + node.traverse(function(object) { + if (object.morphTargetInfluences) { + targetNames.push(object.name ? object.name : object.uuid); + } + }); + } else { + targetNames.push(targetName); + } + let TypedKeyframeTrack; + switch (PATH_PROPERTIES2[target.path]) { + case PATH_PROPERTIES2.weights: + TypedKeyframeTrack = NumberKeyframeTrack; + break; + case PATH_PROPERTIES2.rotation: + TypedKeyframeTrack = QuaternionKeyframeTrack; + break; + case PATH_PROPERTIES2.position: + case PATH_PROPERTIES2.scale: + TypedKeyframeTrack = VectorKeyframeTrack; + break; + default: + switch (outputAccessor.itemSize) { + case 1: + TypedKeyframeTrack = NumberKeyframeTrack; + break; + case 2: + case 3: + default: + TypedKeyframeTrack = VectorKeyframeTrack; + break; + } + break; + } + const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : InterpolateLinear; + const outputArray = this._getArrayFromAccessor(outputAccessor); + for (let j2 = 0, jl = targetNames.length;j2 < jl; j2++) { + const track = new TypedKeyframeTrack(targetNames[j2] + "." + PATH_PROPERTIES2[target.path], inputAccessor.array, outputArray, interpolation); + if (sampler.interpolation === "CUBICSPLINE") { + this._createCubicSplineTrackInterpolant(track); + } + tracks.push(track); + } + return tracks; + } + _getArrayFromAccessor(accessor) { + let outputArray = accessor.array; + if (accessor.normalized) { + const scale2 = getNormalizedComponentScale(outputArray.constructor); + const scaled = new Float32Array(outputArray.length); + for (let j2 = 0, jl = outputArray.length;j2 < jl; j2++) { + scaled[j2] = outputArray[j2] * scale2; + } + outputArray = scaled; + } + return outputArray; + } + _createCubicSplineTrackInterpolant(track) { + track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) { + const interpolantType = this instanceof QuaternionKeyframeTrack ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant; + return new interpolantType(this.times, this.values, this.getValueSize() / 3, result); + }; + track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true; + } +} +function computeBounds(geometry, primitiveDef, parser) { + const attributes = primitiveDef.attributes; + const box = new Box3; + if (attributes.POSITION !== undefined) { + const accessor = parser.json.accessors[attributes.POSITION]; + const min = accessor.min; + const max = accessor.max; + if (min !== undefined && max !== undefined) { + box.set(new Vector3(min[0], min[1], min[2]), new Vector3(max[0], max[1], max[2])); + if (accessor.normalized) { + const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]); + box.min.multiplyScalar(boxScale); + box.max.multiplyScalar(boxScale); + } + } else { + console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION."); + return; + } + } else { + return; + } + const targets = primitiveDef.targets; + if (targets !== undefined) { + const maxDisplacement = new Vector3; + const vector = new Vector3; + for (let i = 0, il = targets.length;i < il; i++) { + const target = targets[i]; + if (target.POSITION !== undefined) { + const accessor = parser.json.accessors[target.POSITION]; + const min = accessor.min; + const max = accessor.max; + if (min !== undefined && max !== undefined) { + vector.setX(Math.max(Math.abs(min[0]), Math.abs(max[0]))); + vector.setY(Math.max(Math.abs(min[1]), Math.abs(max[1]))); + vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max[2]))); + if (accessor.normalized) { + const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]); + vector.multiplyScalar(boxScale); + } + maxDisplacement.max(vector); + } else { + console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION."); + } + } + } + box.expandByVector(maxDisplacement); + } + geometry.boundingBox = box; + const sphere = new Sphere; + box.getCenter(sphere.center); + sphere.radius = box.min.distanceTo(box.max) / 2; + geometry.boundingSphere = sphere; +} +function addPrimitiveAttributes(geometry, primitiveDef, parser) { + const attributes = primitiveDef.attributes; + const pending = []; + function assignAttributeAccessor(accessorIndex, attributeName) { + return parser.getDependency("accessor", accessorIndex).then(function(accessor) { + geometry.setAttribute(attributeName, accessor); + }); + } + for (const gltfAttributeName in attributes) { + const threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); + if (threeAttributeName in geometry.attributes) + continue; + pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName)); + } + if (primitiveDef.indices !== undefined && !geometry.index) { + const accessor = parser.getDependency("accessor", primitiveDef.indices).then(function(accessor2) { + geometry.setIndex(accessor2); + }); + pending.push(accessor); + } + if (ColorManagement.workingColorSpace !== LinearSRGBColorSpace && "COLOR_0" in attributes) { + console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ColorManagement.workingColorSpace}" not supported.`); + } + assignExtrasToUserData(geometry, primitiveDef); + computeBounds(geometry, primitiveDef, parser); + return Promise.all(pending).then(function() { + return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry; + }); +} +// node_modules/three/examples/jsm/utils/WorkerPool.js +class WorkerPool { + constructor(pool = 4) { + this.pool = pool; + this.queue = []; + this.workers = []; + this.workersResolve = []; + this.workerStatus = 0; + } + _initWorker(workerId) { + if (!this.workers[workerId]) { + const worker = this.workerCreator(); + worker.addEventListener("message", this._onMessage.bind(this, workerId)); + this.workers[workerId] = worker; + } + } + _getIdleWorker() { + for (let i = 0;i < this.pool; i++) + if (!(this.workerStatus & 1 << i)) + return i; + return -1; + } + _onMessage(workerId, msg) { + const resolve = this.workersResolve[workerId]; + resolve && resolve(msg); + if (this.queue.length) { + const { resolve: resolve2, msg: msg2, transfer } = this.queue.shift(); + this.workersResolve[workerId] = resolve2; + this.workers[workerId].postMessage(msg2, transfer); + } else { + this.workerStatus ^= 1 << workerId; + } + } + setWorkerCreator(workerCreator) { + this.workerCreator = workerCreator; + } + setWorkerLimit(pool) { + this.pool = pool; + } + postMessage(msg, transfer) { + return new Promise((resolve) => { + const workerId = this._getIdleWorker(); + if (workerId !== -1) { + this._initWorker(workerId); + this.workerStatus |= 1 << workerId; + this.workersResolve[workerId] = resolve; + this.workers[workerId].postMessage(msg, transfer); + } else { + this.queue.push({ resolve, msg, transfer }); + } + }); + } + dispose() { + this.workers.forEach((worker) => worker.terminate()); + this.workersResolve.length = 0; + this.workers.length = 0; + this.queue.length = 0; + this.workerStatus = 0; + } +} + +// node_modules/three/examples/jsm/libs/zstddec.module.js +var A2; +var I2; +var B2; +var g2 = { env: { emscripten_notify_memory_growth: function(A4) { + B2 = new Uint8Array(I2.exports.memory.buffer); +} } }; + +class Q { + init() { + return A2 || (A2 = typeof fetch != "undefined" ? fetch("data:application/wasm;base64," + C4).then((A4) => A4.arrayBuffer()).then((A4) => WebAssembly.instantiate(A4, g2)).then(this._init) : WebAssembly.instantiate(Buffer.from(C4, "base64"), g2).then(this._init), A2); + } + _init(A4) { + I2 = A4.instance, g2.env.emscripten_notify_memory_growth(0); + } + decode(A4, g3 = 0) { + if (!I2) + throw new Error("ZSTDDecoder: Await .init() before decoding."); + const Q3 = A4.byteLength, C4 = I2.exports.malloc(Q3); + B2.set(A4, C4), g3 = g3 || Number(I2.exports.ZSTD_findDecompressedSize(C4, Q3)); + const E2 = I2.exports.malloc(g3), i = I2.exports.ZSTD_decompress(E2, g3, C4, Q3), D = B2.slice(E2, E2 + i); + return I2.exports.free(C4), I2.exports.free(E2), D; + } +} +var C4 = "AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDBgEACQkHBgICAAYGAgQUBwYGAwIGAAMCAQgBBwUGCgoEEQAEBAEIAwgDBQgDEA8IAAcABAUBcAECAgUEAQCAAgYJAX8BQaCgwAILB2AHBm1lbW9yeQIABm1hbGxvYwAoBGZyZWUAJgxaU1REX2lzRXJyb3IAaBlaU1REX2ZpbmREZWNvbXByZXNzZWRTaXplAFQPWlNURF9kZWNvbXByZXNzAEoGX3N0YXJ0ACQJBwEAQQELASQKussBaA8AIAAgACgCBCABajYCBAsZACAAKAIAIAAoAgRBH3F0QQAgAWtBH3F2CwgAIABBiH9LC34BBH9BAyEBIAAoAgQiA0EgTQRAIAAoAggiASAAKAIQTwRAIAAQDQ8LIAAoAgwiAiABRgRAQQFBAiADQSBJGw8LIAAgASABIAJrIANBA3YiBCABIARrIAJJIgEbIgJrIgQ2AgggACADIAJBA3RrNgIEIAAgBCgAADYCAAsgAQsUAQF/IAAgARACIQIgACABEAEgAgv3AQECfyACRQRAIABCADcCACAAQQA2AhAgAEIANwIIQbh/DwsgACABNgIMIAAgAUEEajYCECACQQRPBEAgACABIAJqIgFBfGoiAzYCCCAAIAMoAAA2AgAgAUF/ai0AACIBBEAgAEEIIAEQFGs2AgQgAg8LIABBADYCBEF/DwsgACABNgIIIAAgAS0AACIDNgIAIAJBfmoiBEEBTQRAIARBAWtFBEAgACABLQACQRB0IANyIgM2AgALIAAgAS0AAUEIdCADajYCAAsgASACakF/ai0AACIBRQRAIABBADYCBEFsDwsgAEEoIAEQFCACQQN0ams2AgQgAgsWACAAIAEpAAA3AAAgACABKQAINwAICy8BAX8gAUECdEGgHWooAgAgACgCAEEgIAEgACgCBGprQR9xdnEhAiAAIAEQASACCyEAIAFCz9bTvtLHq9lCfiAAfEIfiUKHla+vmLbem55/fgsdAQF/IAAoAgggACgCDEYEfyAAKAIEQSBGBUEACwuCBAEDfyACQYDAAE8EQCAAIAEgAhBnIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAsMACAAIAEpAAA3AAALQQECfyAAKAIIIgEgACgCEEkEQEEDDwsgACAAKAIEIgJBB3E2AgQgACABIAJBA3ZrIgE2AgggACABKAAANgIAQQALDAAgACABKAIANgAAC/cCAQJ/AkAgACABRg0AAkAgASACaiAASwRAIAAgAmoiBCABSw0BCyAAIAEgAhALDwsgACABc0EDcSEDAkACQCAAIAFJBEAgAwRAIAAhAwwDCyAAQQNxRQRAIAAhAwwCCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigCACACaiAAQQZ2IgFBAnRBsB5qKAIAaiAAQSBxIgBFaiABRSAAQQV2cWoFQbh/CwsdACAAKAKQ4gEQWiAAQQA2AqDiASAAQgA3A5DiAQu1AwEFfyMAQZACayIKJABBuH8hBgJAIAVFDQAgBCwAACIIQf8BcSEHAkAgCEF/TARAIAdBgn9qQQF2IgggBU8NAkFsIQYgB0GBf2oiBUGAAk8NAiAEQQFqIQdBACEGA0AgBiAFTwRAIAUhBiAIIQcMAwUgACAGaiAHIAZBAXZqIgQtAABBBHY6AAAgACAGQQFyaiAELQAAQQ9xOgAAIAZBAmohBgwBCwAACwALIAcgBU8NASAAIARBAWogByAKEFMiBhADDQELIAYhBEEAIQYgAUEAQTQQECEJQQAhBQNAIAQgBkcEQCAAIAZqIggtAAAiAUELSwRAQWwhBgwDBSAJIAFBAnRqIgEgASgCAEEBajYCACAGQQFqIQZBASAILQAAdEEBdSAFaiEFDAILAAsLQWwhBiAFRQ0AIAUQFEEBaiIBQQxLDQAgAyABNgIAQQFBASABdCAFayIDEBQiAXQgA0cNACAAIARqIAFBAWoiADoAACAJIABBAnRqIgAgACgCAEEBajYCACAJKAIEIgBBAkkgAEEBcXINACACIARBAWo2AgAgB0EBaiEGCyAKQZACaiQAIAYLxhEBDH8jAEHwAGsiBSQAQWwhCwJAIANBCkkNACACLwAAIQogAi8AAiEJIAIvAAQhByAFQQhqIAQQDgJAIAMgByAJIApqakEGaiIMSQ0AIAUtAAohCCAFQdgAaiACQQZqIgIgChAGIgsQAw0BIAVBQGsgAiAKaiICIAkQBiILEAMNASAFQShqIAIgCWoiAiAHEAYiCxADDQEgBUEQaiACIAdqIAMgDGsQBiILEAMNASAAIAFqIg9BfWohECAEQQRqIQZBASELIAAgAUEDakECdiIDaiIMIANqIgIgA2oiDiEDIAIhBCAMIQcDQCALIAMgEElxBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgCS0AAyELIAcgBiAFQUBrIAgQAkECdGoiCS8BADsAACAFQUBrIAktAAIQASAJLQADIQogBCAGIAVBKGogCBACQQJ0aiIJLwEAOwAAIAVBKGogCS0AAhABIAktAAMhCSADIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgDS0AAyENIAAgC2oiCyAGIAVB2ABqIAgQAkECdGoiAC8BADsAACAFQdgAaiAALQACEAEgAC0AAyEAIAcgCmoiCiAGIAVBQGsgCBACQQJ0aiIHLwEAOwAAIAVBQGsgBy0AAhABIActAAMhByAEIAlqIgkgBiAFQShqIAgQAkECdGoiBC8BADsAACAFQShqIAQtAAIQASAELQADIQQgAyANaiIDIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgACALaiEAIAcgCmohByAEIAlqIQQgAyANLQADaiEDIAVB2ABqEA0gBUFAaxANciAFQShqEA1yIAVBEGoQDXJFIQsMAQsLIAQgDksgByACS3INAEFsIQsgACAMSw0BIAxBfWohCQNAQQAgACAJSSAFQdgAahAEGwRAIAAgBiAFQdgAaiAIEAJBAnRqIgovAQA7AAAgBUHYAGogCi0AAhABIAAgCi0AA2oiACAGIAVB2ABqIAgQAkECdGoiCi8BADsAACAFQdgAaiAKLQACEAEgACAKLQADaiEADAEFIAxBfmohCgNAIAVB2ABqEAQgACAKS3JFBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgACAJLQADaiEADAELCwNAIAAgCk0EQCAAIAYgBUHYAGogCBACQQJ0aiIJLwEAOwAAIAVB2ABqIAktAAIQASAAIAktAANqIQAMAQsLAkAgACAMTw0AIAAgBiAFQdgAaiAIEAIiAEECdGoiDC0AADoAACAMLQADQQFGBEAgBUHYAGogDC0AAhABDAELIAUoAlxBH0sNACAFQdgAaiAGIABBAnRqLQACEAEgBSgCXEEhSQ0AIAVBIDYCXAsgAkF9aiEMA0BBACAHIAxJIAVBQGsQBBsEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiIAIAYgBUFAayAIEAJBAnRqIgcvAQA7AAAgBUFAayAHLQACEAEgACAHLQADaiEHDAEFIAJBfmohDANAIAVBQGsQBCAHIAxLckUEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwNAIAcgDE0EQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwJAIAcgAk8NACAHIAYgBUFAayAIEAIiAEECdGoiAi0AADoAACACLQADQQFGBEAgBUFAayACLQACEAEMAQsgBSgCREEfSw0AIAVBQGsgBiAAQQJ0ai0AAhABIAUoAkRBIUkNACAFQSA2AkQLIA5BfWohAgNAQQAgBCACSSAFQShqEAQbBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2oiACAGIAVBKGogCBACQQJ0aiIELwEAOwAAIAVBKGogBC0AAhABIAAgBC0AA2ohBAwBBSAOQX5qIQIDQCAFQShqEAQgBCACS3JFBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsDQCAEIAJNBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsCQCAEIA5PDQAgBCAGIAVBKGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBKGogAi0AAhABDAELIAUoAixBH0sNACAFQShqIAYgAEECdGotAAIQASAFKAIsQSFJDQAgBUEgNgIsCwNAQQAgAyAQSSAFQRBqEAQbBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2oiACAGIAVBEGogCBACQQJ0aiICLwEAOwAAIAVBEGogAi0AAhABIAAgAi0AA2ohAwwBBSAPQX5qIQIDQCAFQRBqEAQgAyACS3JFBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsDQCADIAJNBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsCQCADIA9PDQAgAyAGIAVBEGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBEGogAi0AAhABDAELIAUoAhRBH0sNACAFQRBqIAYgAEECdGotAAIQASAFKAIUQSFJDQAgBUEgNgIUCyABQWwgBUHYAGoQCiAFQUBrEApxIAVBKGoQCnEgBUEQahAKcRshCwwJCwAACwALAAALAAsAAAsACwAACwALQWwhCwsgBUHwAGokACALC7UEAQ5/IwBBEGsiBiQAIAZBBGogABAOQVQhBQJAIARB3AtJDQAgBi0ABCEHIANB8ARqQQBB7AAQECEIIAdBDEsNACADQdwJaiIJIAggBkEIaiAGQQxqIAEgAhAxIhAQA0UEQCAGKAIMIgQgB0sNASADQdwFaiEPIANBpAVqIREgAEEEaiESIANBqAVqIQEgBCEFA0AgBSICQX9qIQUgCCACQQJ0aigCAEUNAAsgAkEBaiEOQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgASALaiAKNgIAIAVBAWohBSAKIAxqIQoMAQsLIAEgCjYCAEEAIQUgBigCCCELA0AgBSALRkUEQCABIAUgCWotAAAiDEECdGoiDSANKAIAIg1BAWo2AgAgDyANQQF0aiINIAw6AAEgDSAFOgAAIAVBAWohBQwBCwtBACEBIANBADYCqAUgBEF/cyAHaiEJQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgAyALaiABNgIAIAwgBSAJanQgAWohASAFQQFqIQUMAQsLIAcgBEEBaiIBIAJrIgRrQQFqIQgDQEEBIQUgBCAIT0UEQANAIAUgDk9FBEAgBUECdCIJIAMgBEE0bGpqIAMgCWooAgAgBHY2AgAgBUEBaiEFDAELCyAEQQFqIQQMAQsLIBIgByAPIAogESADIAIgARBkIAZBAToABSAGIAc6AAYgACAGKAIENgIACyAQIQULIAZBEGokACAFC8ENAQt/IwBB8ABrIgUkAEFsIQkCQCADQQpJDQAgAi8AACEKIAIvAAIhDCACLwAEIQYgBUEIaiAEEA4CQCADIAYgCiAMampBBmoiDUkNACAFLQAKIQcgBUHYAGogAkEGaiICIAoQBiIJEAMNASAFQUBrIAIgCmoiAiAMEAYiCRADDQEgBUEoaiACIAxqIgIgBhAGIgkQAw0BIAVBEGogAiAGaiADIA1rEAYiCRADDQEgACABaiIOQX1qIQ8gBEEEaiEGQQEhCSAAIAFBA2pBAnYiAmoiCiACaiIMIAJqIg0hAyAMIQQgCiECA0AgCSADIA9JcQRAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAACAGIAVBQGsgBxACQQF0aiIILQAAIQsgBUFAayAILQABEAEgAiALOgAAIAYgBUEoaiAHEAJBAXRqIggtAAAhCyAFQShqIAgtAAEQASAEIAs6AAAgBiAFQRBqIAcQAkEBdGoiCC0AACELIAVBEGogCC0AARABIAMgCzoAACAGIAVB2ABqIAcQAkEBdGoiCC0AACELIAVB2ABqIAgtAAEQASAAIAs6AAEgBiAFQUBrIAcQAkEBdGoiCC0AACELIAVBQGsgCC0AARABIAIgCzoAASAGIAVBKGogBxACQQF0aiIILQAAIQsgBUEoaiAILQABEAEgBCALOgABIAYgBUEQaiAHEAJBAXRqIggtAAAhCyAFQRBqIAgtAAEQASADIAs6AAEgA0ECaiEDIARBAmohBCACQQJqIQIgAEECaiEAIAkgBUHYAGoQDUVxIAVBQGsQDUVxIAVBKGoQDUVxIAVBEGoQDUVxIQkMAQsLIAQgDUsgAiAMS3INAEFsIQkgACAKSw0BIApBfWohCQNAIAVB2ABqEAQgACAJT3JFBEAgBiAFQdgAaiAHEAJBAXRqIggtAAAhCyAFQdgAaiAILQABEAEgACALOgAAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAASAAQQJqIQAMAQsLA0AgBUHYAGoQBCAAIApPckUEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCwNAIAAgCkkEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCyAMQX1qIQADQCAFQUBrEAQgAiAAT3JFBEAgBiAFQUBrIAcQAkEBdGoiCi0AACEJIAVBQGsgCi0AARABIAIgCToAACAGIAVBQGsgBxACQQF0aiIKLQAAIQkgBUFAayAKLQABEAEgAiAJOgABIAJBAmohAgwBCwsDQCAFQUBrEAQgAiAMT3JFBEAgBiAFQUBrIAcQAkEBdGoiAC0AACEKIAVBQGsgAC0AARABIAIgCjoAACACQQFqIQIMAQsLA0AgAiAMSQRAIAYgBUFAayAHEAJBAXRqIgAtAAAhCiAFQUBrIAAtAAEQASACIAo6AAAgAkEBaiECDAELCyANQX1qIQADQCAFQShqEAQgBCAAT3JFBEAgBiAFQShqIAcQAkEBdGoiAi0AACEKIAVBKGogAi0AARABIAQgCjoAACAGIAVBKGogBxACQQF0aiICLQAAIQogBUEoaiACLQABEAEgBCAKOgABIARBAmohBAwBCwsDQCAFQShqEAQgBCANT3JFBEAgBiAFQShqIAcQAkEBdGoiAC0AACECIAVBKGogAC0AARABIAQgAjoAACAEQQFqIQQMAQsLA0AgBCANSQRAIAYgBUEoaiAHEAJBAXRqIgAtAAAhAiAFQShqIAAtAAEQASAEIAI6AAAgBEEBaiEEDAELCwNAIAVBEGoQBCADIA9PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIAYgBUEQaiAHEAJBAXRqIgAtAAAhAiAFQRBqIAAtAAEQASADIAI6AAEgA0ECaiEDDAELCwNAIAVBEGoQBCADIA5PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIANBAWohAwwBCwsDQCADIA5JBEAgBiAFQRBqIAcQAkEBdGoiAC0AACECIAVBEGogAC0AARABIAMgAjoAACADQQFqIQMMAQsLIAFBbCAFQdgAahAKIAVBQGsQCnEgBUEoahAKcSAFQRBqEApxGyEJDAELQWwhCQsgBUHwAGokACAJC8oCAQR/IwBBIGsiBSQAIAUgBBAOIAUtAAIhByAFQQhqIAIgAxAGIgIQA0UEQCAEQQRqIQIgACABaiIDQX1qIQQDQCAFQQhqEAQgACAET3JFBEAgAiAFQQhqIAcQAkEBdGoiBi0AACEIIAVBCGogBi0AARABIAAgCDoAACACIAVBCGogBxACQQF0aiIGLQAAIQggBUEIaiAGLQABEAEgACAIOgABIABBAmohAAwBCwsDQCAFQQhqEAQgACADT3JFBEAgAiAFQQhqIAcQAkEBdGoiBC0AACEGIAVBCGogBC0AARABIAAgBjoAACAAQQFqIQAMAQsLA0AgACADT0UEQCACIAVBCGogBxACQQF0aiIELQAAIQYgBUEIaiAELQABEAEgACAGOgAAIABBAWohAAwBCwsgAUFsIAVBCGoQChshAgsgBUEgaiQAIAILtgMBCX8jAEEQayIGJAAgBkEANgIMIAZBADYCCEFUIQQCQAJAIANBQGsiDCADIAZBCGogBkEMaiABIAIQMSICEAMNACAGQQRqIAAQDiAGKAIMIgcgBi0ABEEBaksNASAAQQRqIQogBkEAOgAFIAYgBzoABiAAIAYoAgQ2AgAgB0EBaiEJQQEhBANAIAQgCUkEQCADIARBAnRqIgEoAgAhACABIAU2AgAgACAEQX9qdCAFaiEFIARBAWohBAwBCwsgB0EBaiEHQQAhBSAGKAIIIQkDQCAFIAlGDQEgAyAFIAxqLQAAIgRBAnRqIgBBASAEdEEBdSILIAAoAgAiAWoiADYCACAHIARrIQhBACEEAkAgC0EDTQRAA0AgBCALRg0CIAogASAEakEBdGoiACAIOgABIAAgBToAACAEQQFqIQQMAAALAAsDQCABIABPDQEgCiABQQF0aiIEIAg6AAEgBCAFOgAAIAQgCDoAAyAEIAU6AAIgBCAIOgAFIAQgBToABCAEIAg6AAcgBCAFOgAGIAFBBGohAQwAAAsACyAFQQFqIQUMAAALAAsgAiEECyAGQRBqJAAgBAutAQECfwJAQYQgKAIAIABHIAAoAgBBAXYiAyABa0F4aiICQXhxQQhHcgR/IAIFIAMQJ0UNASACQQhqC0EQSQ0AIAAgACgCACICQQFxIAAgAWpBD2pBeHEiASAAa0EBdHI2AgAgASAANgIEIAEgASgCAEEBcSAAIAJBAXZqIAFrIgJBAXRyNgIAQYQgIAEgAkH/////B3FqQQRqQYQgKAIAIABGGyABNgIAIAEQJQsLygIBBX8CQAJAAkAgAEEIIABBCEsbZ0EfcyAAaUEBR2oiAUEESSAAIAF2cg0AIAFBAnRB/B5qKAIAIgJFDQADQCACQXhqIgMoAgBBAXZBeGoiBSAATwRAIAIgBUEIIAVBCEsbZ0Efc0ECdEGAH2oiASgCAEYEQCABIAIoAgQ2AgALDAMLIARBHksNASAEQQFqIQQgAigCBCICDQALC0EAIQMgAUEgTw0BA0AgAUECdEGAH2ooAgAiAkUEQCABQR5LIQIgAUEBaiEBIAJFDQEMAwsLIAIgAkF4aiIDKAIAQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgBGBEAgASACKAIENgIACwsgAigCACIBBEAgASACKAIENgIECyACKAIEIgEEQCABIAIoAgA2AgALIAMgAygCAEEBcjYCACADIAAQNwsgAwvhCwINfwV+IwBB8ABrIgckACAHIAAoAvDhASIINgJcIAEgAmohDSAIIAAoAoDiAWohDwJAAkAgBUUEQCABIQQMAQsgACgCxOABIRAgACgCwOABIREgACgCvOABIQ4gAEEBNgKM4QFBACEIA0AgCEEDRwRAIAcgCEECdCICaiAAIAJqQazQAWooAgA2AkQgCEEBaiEIDAELC0FsIQwgB0EYaiADIAQQBhADDQEgB0EsaiAHQRhqIAAoAgAQEyAHQTRqIAdBGGogACgCCBATIAdBPGogB0EYaiAAKAIEEBMgDUFgaiESIAEhBEEAIQwDQCAHKAIwIAcoAixBA3RqKQIAIhRCEIinQf8BcSEIIAcoAkAgBygCPEEDdGopAgAiFUIQiKdB/wFxIQsgBygCOCAHKAI0QQN0aikCACIWQiCIpyEJIBVCIIghFyAUQiCIpyECAkAgFkIQiKdB/wFxIgNBAk8EQAJAIAZFIANBGUlyRQRAIAkgB0EYaiADQSAgBygCHGsiCiAKIANLGyIKEAUgAyAKayIDdGohCSAHQRhqEAQaIANFDQEgB0EYaiADEAUgCWohCQwBCyAHQRhqIAMQBSAJaiEJIAdBGGoQBBoLIAcpAkQhGCAHIAk2AkQgByAYNwNIDAELAkAgA0UEQCACBEAgBygCRCEJDAMLIAcoAkghCQwBCwJAAkAgB0EYakEBEAUgCSACRWpqIgNBA0YEQCAHKAJEQX9qIgMgA0VqIQkMAQsgA0ECdCAHaigCRCIJIAlFaiEJIANBAUYNAQsgByAHKAJINgJMCwsgByAHKAJENgJIIAcgCTYCRAsgF6chAyALBEAgB0EYaiALEAUgA2ohAwsgCCALakEUTwRAIAdBGGoQBBoLIAgEQCAHQRhqIAgQBSACaiECCyAHQRhqEAQaIAcgB0EYaiAUQhiIp0H/AXEQCCAUp0H//wNxajYCLCAHIAdBGGogFUIYiKdB/wFxEAggFadB//8DcWo2AjwgB0EYahAEGiAHIAdBGGogFkIYiKdB/wFxEAggFqdB//8DcWo2AjQgByACNgJgIAcoAlwhCiAHIAk2AmggByADNgJkAkACQAJAIAQgAiADaiILaiASSw0AIAIgCmoiEyAPSw0AIA0gBGsgC0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ"; + +// node_modules/three/examples/jsm/math/ColorSpaces.js +var DisplayP3ColorSpace = "display-p3"; +var LinearDisplayP3ColorSpace = "display-p3-linear"; + +// node_modules/three/examples/jsm/loaders/KTX2Loader.js +var _taskCache3 = new WeakMap; +var _activeLoaders = 0; +var _zstd; + +class KTX2Loader extends Loader { + constructor(manager) { + super(manager); + this.transcoderPath = ""; + this.transcoderBinary = null; + this.transcoderPending = null; + this.workerPool = new WorkerPool; + this.workerSourceURL = ""; + this.workerConfig = null; + if (typeof MSC_TRANSCODER !== "undefined") { + console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder".' + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'); + } + } + setTranscoderPath(path) { + this.transcoderPath = path; + return this; + } + setWorkerLimit(num) { + this.workerPool.setWorkerLimit(num); + return this; + } + async detectSupportAsync(renderer2) { + this.workerConfig = { + astcSupported: await renderer2.hasFeatureAsync("texture-compression-astc"), + astcHDRSupported: false, + etc1Supported: await renderer2.hasFeatureAsync("texture-compression-etc1"), + etc2Supported: await renderer2.hasFeatureAsync("texture-compression-etc2"), + dxtSupported: await renderer2.hasFeatureAsync("texture-compression-bc"), + bptcSupported: await renderer2.hasFeatureAsync("texture-compression-bptc"), + pvrtcSupported: await renderer2.hasFeatureAsync("texture-compression-pvrtc") + }; + return this; + } + detectSupport(renderer2) { + if (renderer2.isWebGPURenderer === true) { + this.workerConfig = { + astcSupported: renderer2.hasFeature("texture-compression-astc"), + astcHDRSupported: false, + etc1Supported: renderer2.hasFeature("texture-compression-etc1"), + etc2Supported: renderer2.hasFeature("texture-compression-etc2"), + dxtSupported: renderer2.hasFeature("texture-compression-bc"), + bptcSupported: renderer2.hasFeature("texture-compression-bptc"), + pvrtcSupported: renderer2.hasFeature("texture-compression-pvrtc") + }; + } else { + this.workerConfig = { + astcSupported: renderer2.extensions.has("WEBGL_compressed_texture_astc"), + astcHDRSupported: renderer2.extensions.has("WEBGL_compressed_texture_astc") && renderer2.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"), + etc1Supported: renderer2.extensions.has("WEBGL_compressed_texture_etc1"), + etc2Supported: renderer2.extensions.has("WEBGL_compressed_texture_etc"), + dxtSupported: renderer2.extensions.has("WEBGL_compressed_texture_s3tc"), + bptcSupported: renderer2.extensions.has("EXT_texture_compression_bptc"), + pvrtcSupported: renderer2.extensions.has("WEBGL_compressed_texture_pvrtc") || renderer2.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc") + }; + } + return this; + } + init() { + if (!this.transcoderPending) { + const jsLoader = new FileLoader(this.manager); + jsLoader.setPath(this.transcoderPath); + jsLoader.setWithCredentials(this.withCredentials); + const jsContent = jsLoader.loadAsync("basis_transcoder.js"); + const binaryLoader = new FileLoader(this.manager); + binaryLoader.setPath(this.transcoderPath); + binaryLoader.setResponseType("arraybuffer"); + binaryLoader.setWithCredentials(this.withCredentials); + const binaryContent = binaryLoader.loadAsync("basis_transcoder.wasm"); + this.transcoderPending = Promise.all([jsContent, binaryContent]).then(([jsContent2, binaryContent2]) => { + const fn = KTX2Loader.BasisWorker.toString(); + const body = [ + "/* constants */", + "let _EngineFormat = " + JSON.stringify(KTX2Loader.EngineFormat), + "let _EngineType = " + JSON.stringify(KTX2Loader.EngineType), + "let _TranscoderFormat = " + JSON.stringify(KTX2Loader.TranscoderFormat), + "let _BasisFormat = " + JSON.stringify(KTX2Loader.BasisFormat), + "/* basis_transcoder.js */", + jsContent2, + "/* worker */", + fn.substring(fn.indexOf("{") + 1, fn.lastIndexOf("}")) + ].join(` +`); + this.workerSourceURL = URL.createObjectURL(new Blob([body])); + this.transcoderBinary = binaryContent2; + this.workerPool.setWorkerCreator(() => { + const worker = new Worker(this.workerSourceURL); + const transcoderBinary = this.transcoderBinary.slice(0); + worker.postMessage({ type: "init", config: this.workerConfig, transcoderBinary }, [transcoderBinary]); + return worker; + }); + }); + if (_activeLoaders > 0) { + console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues." + " Use a single KTX2Loader instance, or call .dispose() on old instances."); + } + _activeLoaders++; + } + return this.transcoderPending; + } + load(url, onLoad, onProgress, onError) { + if (this.workerConfig === null) { + throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`."); + } + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setWithCredentials(this.withCredentials); + loader.load(url, (buffer) => { + this.parse(buffer, onLoad, onError); + }, onProgress, onError); + } + parse(buffer, onLoad, onError) { + if (this.workerConfig === null) { + throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`."); + } + if (_taskCache3.has(buffer)) { + const cachedTask = _taskCache3.get(buffer); + return cachedTask.promise.then(onLoad).catch(onError); + } + this._createTexture(buffer).then((texture) => onLoad ? onLoad(texture) : null).catch(onError); + } + _createTextureFrom(transcodeResult, container) { + const { type: messageType, error, data: { faces, width: width2, height: height2, format, type, dfdFlags } } = transcodeResult; + if (messageType === "error") + return Promise.reject(error); + let texture; + if (container.faceCount === 6) { + texture = new CompressedCubeTexture(faces, format, type); + } else { + const mipmaps = faces[0].mipmaps; + texture = container.layerCount > 1 ? new CompressedArrayTexture(mipmaps, width2, height2, container.layerCount, format, type) : new CompressedTexture(mipmaps, width2, height2, format, type); + } + texture.minFilter = faces[0].mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; + texture.magFilter = LinearFilter; + texture.generateMipmaps = false; + texture.needsUpdate = true; + texture.colorSpace = parseColorSpace(container); + texture.premultiplyAlpha = !!(dfdFlags & g); + return texture; + } + async _createTexture(buffer, config = {}) { + const container = Pi2(new Uint8Array(buffer)); + const isBasisHDR = container.vkFormat === pi && container.dataFormatDescriptor[0].colorModel === 167; + const needsTranscoder = container.vkFormat === it || isBasisHDR && !this.workerConfig.astcHDRSupported; + if (!needsTranscoder) { + return createRawTexture(container); + } + const taskConfig = config; + const texturePending = this.init().then(() => { + return this.workerPool.postMessage({ type: "transcode", buffer, taskConfig }, [buffer]); + }).then((e) => this._createTextureFrom(e.data, container)); + _taskCache3.set(buffer, { promise: texturePending }); + return texturePending; + } + dispose() { + this.workerPool.dispose(); + if (this.workerSourceURL) + URL.revokeObjectURL(this.workerSourceURL); + _activeLoaders--; + return this; + } +} +KTX2Loader.BasisFormat = { + ETC1S: 0, + UASTC: 1, + UASTC_HDR: 2 +}; +KTX2Loader.TranscoderFormat = { + ETC1: 0, + ETC2: 1, + BC1: 2, + BC3: 3, + BC4: 4, + BC5: 5, + BC7_M6_OPAQUE_ONLY: 6, + BC7_M5: 7, + PVRTC1_4_RGB: 8, + PVRTC1_4_RGBA: 9, + ASTC_4x4: 10, + ATC_RGB: 11, + ATC_RGBA_INTERPOLATED_ALPHA: 12, + RGBA32: 13, + RGB565: 14, + BGR565: 15, + RGBA4444: 16, + BC6H: 22, + RGB_HALF: 24, + RGBA_HALF: 25 +}; +KTX2Loader.EngineFormat = { + RGBAFormat, + RGBA_ASTC_4x4_Format, + RGB_BPTC_UNSIGNED_Format, + RGBA_BPTC_Format, + RGBA_ETC2_EAC_Format, + RGBA_PVRTC_4BPPV1_Format, + RGBA_S3TC_DXT5_Format, + RGB_ETC1_Format, + RGB_ETC2_Format, + RGB_PVRTC_4BPPV1_Format, + RGBA_S3TC_DXT1_Format +}; +KTX2Loader.EngineType = { + UnsignedByteType, + HalfFloatType, + FloatType +}; +KTX2Loader.BasisWorker = function() { + let config; + let transcoderPending; + let BasisModule; + const EngineFormat = _EngineFormat; + const EngineType = _EngineType; + const TranscoderFormat = _TranscoderFormat; + const BasisFormat = _BasisFormat; + self.addEventListener("message", function(e) { + const message = e.data; + switch (message.type) { + case "init": + config = message.config; + init(message.transcoderBinary); + break; + case "transcode": + transcoderPending.then(() => { + try { + const { faces, buffers, width: width2, height: height2, hasAlpha, format, type, dfdFlags } = transcode(message.buffer); + self.postMessage({ type: "transcode", id: message.id, data: { faces, width: width2, height: height2, hasAlpha, format, type, dfdFlags } }, buffers); + } catch (error) { + console.error(error); + self.postMessage({ type: "error", id: message.id, error: error.message }); + } + }); + break; + } + }); + function init(wasmBinary) { + transcoderPending = new Promise((resolve) => { + BasisModule = { wasmBinary, onRuntimeInitialized: resolve }; + BASIS(BasisModule); + }).then(() => { + BasisModule.initializeBasis(); + if (BasisModule.KTX2File === undefined) { + console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder."); + } + }); + } + function transcode(buffer) { + const ktx2File = new BasisModule.KTX2File(new Uint8Array(buffer)); + function cleanup() { + ktx2File.close(); + ktx2File.delete(); + } + if (!ktx2File.isValid()) { + cleanup(); + throw new Error("THREE.KTX2Loader:\tInvalid or unsupported .ktx2 file"); + } + let basisFormat; + if (ktx2File.isUASTC()) { + basisFormat = BasisFormat.UASTC; + } else if (ktx2File.isETC1S()) { + basisFormat = BasisFormat.ETC1S; + } else if (ktx2File.isHDR()) { + basisFormat = BasisFormat.UASTC_HDR; + } else { + throw new Error("THREE.KTX2Loader: Unknown Basis encoding"); + } + const width2 = ktx2File.getWidth(); + const height2 = ktx2File.getHeight(); + const layerCount = ktx2File.getLayers() || 1; + const levelCount = ktx2File.getLevels(); + const faceCount = ktx2File.getFaces(); + const hasAlpha = ktx2File.getHasAlpha(); + const dfdFlags = ktx2File.getDFDFlags(); + const { transcoderFormat, engineFormat, engineType } = getTranscoderFormat(basisFormat, width2, height2, hasAlpha); + if (!width2 || !height2 || !levelCount) { + cleanup(); + throw new Error("THREE.KTX2Loader:\tInvalid texture"); + } + if (!ktx2File.startTranscoding()) { + cleanup(); + throw new Error("THREE.KTX2Loader: .startTranscoding failed"); + } + const faces = []; + const buffers = []; + for (let face = 0;face < faceCount; face++) { + const mipmaps = []; + for (let mip = 0;mip < levelCount; mip++) { + const layerMips = []; + let mipWidth, mipHeight; + for (let layer = 0;layer < layerCount; layer++) { + const levelInfo = ktx2File.getImageLevelInfo(mip, layer, face); + if (face === 0 && mip === 0 && layer === 0 && (levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0)) { + console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions."); + } + if (levelCount > 1) { + mipWidth = levelInfo.origWidth; + mipHeight = levelInfo.origHeight; + } else { + mipWidth = levelInfo.width; + mipHeight = levelInfo.height; + } + let dst = new Uint8Array(ktx2File.getImageTranscodedSizeInBytes(mip, layer, 0, transcoderFormat)); + const status = ktx2File.transcodeImage(dst, mip, layer, face, transcoderFormat, 0, -1, -1); + if (engineType === EngineType.HalfFloatType) { + dst = new Uint16Array(dst.buffer, dst.byteOffset, dst.byteLength / Uint16Array.BYTES_PER_ELEMENT); + } + if (!status) { + cleanup(); + throw new Error("THREE.KTX2Loader: .transcodeImage failed."); + } + layerMips.push(dst); + } + const mipData = concat(layerMips); + mipmaps.push({ data: mipData, width: mipWidth, height: mipHeight }); + buffers.push(mipData.buffer); + } + faces.push({ mipmaps, width: width2, height: height2, format: engineFormat, type: engineType }); + } + cleanup(); + return { faces, buffers, width: width2, height: height2, hasAlpha, dfdFlags, format: engineFormat, type: engineType }; + } + const FORMAT_OPTIONS = [ + { + if: "astcSupported", + basisFormat: [BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4], + engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: Infinity, + priorityUASTC: 1, + needsPowerOfTwo: false + }, + { + if: "bptcSupported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5], + engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 3, + priorityUASTC: 2, + needsPowerOfTwo: false + }, + { + if: "dxtSupported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3], + engineFormat: [EngineFormat.RGBA_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 4, + priorityUASTC: 5, + needsPowerOfTwo: false + }, + { + if: "etc2Supported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2], + engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 1, + priorityUASTC: 3, + needsPowerOfTwo: false + }, + { + if: "etc1Supported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.ETC1], + engineFormat: [EngineFormat.RGB_ETC1_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 2, + priorityUASTC: 4, + needsPowerOfTwo: false + }, + { + if: "pvrtcSupported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA], + engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 5, + priorityUASTC: 6, + needsPowerOfTwo: true + }, + { + if: "bptcSupported", + basisFormat: [BasisFormat.UASTC_HDR], + transcoderFormat: [TranscoderFormat.BC6H], + engineFormat: [EngineFormat.RGB_BPTC_UNSIGNED_Format], + engineType: [EngineType.HalfFloatType], + priorityHDR: 1, + needsPowerOfTwo: false + }, + { + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.RGBA32, TranscoderFormat.RGBA32], + engineFormat: [EngineFormat.RGBAFormat, EngineFormat.RGBAFormat], + engineType: [EngineType.UnsignedByteType, EngineType.UnsignedByteType], + priorityETC1S: 100, + priorityUASTC: 100, + needsPowerOfTwo: false + }, + { + basisFormat: [BasisFormat.UASTC_HDR], + transcoderFormat: [TranscoderFormat.RGBA_HALF], + engineFormat: [EngineFormat.RGBAFormat], + engineType: [EngineType.HalfFloatType], + priorityHDR: 100, + needsPowerOfTwo: false + } + ]; + const OPTIONS = { + [BasisFormat.ETC1S]: FORMAT_OPTIONS.filter((opt) => opt.basisFormat.includes(BasisFormat.ETC1S)).sort((a, b) => a.priorityUASTC - b.priorityUASTC), + [BasisFormat.UASTC]: FORMAT_OPTIONS.filter((opt) => opt.basisFormat.includes(BasisFormat.UASTC)).sort((a, b) => a.priorityUASTC - b.priorityUASTC), + [BasisFormat.UASTC_HDR]: FORMAT_OPTIONS.filter((opt) => opt.basisFormat.includes(BasisFormat.UASTC_HDR)).sort((a, b) => a.priorityHDR - b.priorityHDR) + }; + function getTranscoderFormat(basisFormat, width2, height2, hasAlpha) { + const options = OPTIONS[basisFormat]; + for (let i = 0;i < options.length; i++) { + const opt = options[i]; + if (opt.if && !config[opt.if]) + continue; + if (!opt.basisFormat.includes(basisFormat)) + continue; + if (hasAlpha && opt.transcoderFormat.length < 2) + continue; + if (opt.needsPowerOfTwo && !(isPowerOfTwo2(width2) && isPowerOfTwo2(height2))) + continue; + const transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0]; + const engineFormat = opt.engineFormat[hasAlpha ? 1 : 0]; + const engineType = opt.engineType[0]; + return { transcoderFormat, engineFormat, engineType }; + } + throw new Error("THREE.KTX2Loader: Failed to identify transcoding target."); + } + function isPowerOfTwo2(value2) { + if (value2 <= 2) + return true; + return (value2 & value2 - 1) === 0 && value2 !== 0; + } + function concat(arrays) { + if (arrays.length === 1) + return arrays[0]; + let totalByteLength = 0; + for (let i = 0;i < arrays.length; i++) { + const array = arrays[i]; + totalByteLength += array.byteLength; + } + const result = new Uint8Array(totalByteLength); + let byteOffset = 0; + for (let i = 0;i < arrays.length; i++) { + const array = arrays[i]; + result.set(array, byteOffset); + byteOffset += array.byteLength; + } + return result; + } +}; +var UNCOMPRESSED_FORMATS = new Set([RGBAFormat, RGFormat, RedFormat]); +var FORMAT_MAP = { + [Ae]: RGBAFormat, + [ge]: RGBAFormat, + [Ft]: RGBAFormat, + [Ct]: RGBAFormat, + [we]: RGFormat, + [ae2]: RGFormat, + [xt2]: RGFormat, + [wt]: RGFormat, + [ue2]: RedFormat, + [te2]: RedFormat, + [yt]: RedFormat, + [ct]: RedFormat, + [pi]: RGBA_ASTC_4x4_Format, + [Sn]: RGBA_ASTC_6x6_Format, + [In]: RGBA_ASTC_6x6_Format +}; +var TYPE_MAP = { + [Ae]: FloatType, + [ge]: HalfFloatType, + [Ft]: UnsignedByteType, + [Ct]: UnsignedByteType, + [we]: FloatType, + [ae2]: HalfFloatType, + [xt2]: UnsignedByteType, + [wt]: UnsignedByteType, + [ue2]: FloatType, + [te2]: HalfFloatType, + [yt]: UnsignedByteType, + [ct]: UnsignedByteType, + [pi]: HalfFloatType, + [Sn]: UnsignedByteType, + [In]: UnsignedByteType +}; +async function createRawTexture(container) { + const { vkFormat } = container; + if (FORMAT_MAP[vkFormat] === undefined) { + throw new Error("THREE.KTX2Loader: Unsupported vkFormat."); + } + let zstd; + if (container.supercompressionScheme === n) { + if (!_zstd) { + _zstd = new Promise(async (resolve) => { + const zstd2 = new Q; + await zstd2.init(); + resolve(zstd2); + }); + } + zstd = await _zstd; + } + const mipmaps = []; + for (let levelIndex = 0;levelIndex < container.levels.length; levelIndex++) { + const levelWidth = Math.max(1, container.pixelWidth >> levelIndex); + const levelHeight = Math.max(1, container.pixelHeight >> levelIndex); + const levelDepth = container.pixelDepth ? Math.max(1, container.pixelDepth >> levelIndex) : 0; + const level = container.levels[levelIndex]; + let levelData; + if (container.supercompressionScheme === t3) { + levelData = level.levelData; + } else if (container.supercompressionScheme === n) { + levelData = zstd.decode(level.levelData, level.uncompressedByteLength); + } else { + throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme."); + } + let data2; + if (TYPE_MAP[vkFormat] === FloatType) { + data2 = new Float32Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Float32Array.BYTES_PER_ELEMENT); + } else if (TYPE_MAP[vkFormat] === HalfFloatType) { + data2 = new Uint16Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT); + } else { + data2 = levelData; + } + mipmaps.push({ + data: data2, + width: levelWidth, + height: levelHeight, + depth: levelDepth + }); + } + let texture; + if (UNCOMPRESSED_FORMATS.has(FORMAT_MAP[vkFormat])) { + texture = container.pixelDepth === 0 ? new DataTexture(mipmaps[0].data, container.pixelWidth, container.pixelHeight) : new Data3DTexture(mipmaps[0].data, container.pixelWidth, container.pixelHeight, container.pixelDepth); + } else { + if (container.pixelDepth > 0) + throw new Error("THREE.KTX2Loader: Unsupported pixelDepth."); + texture = new CompressedTexture(mipmaps, container.pixelWidth, container.pixelHeight); + texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; + texture.magFilter = LinearFilter; + } + texture.mipmaps = mipmaps; + texture.type = TYPE_MAP[vkFormat]; + texture.format = FORMAT_MAP[vkFormat]; + texture.colorSpace = parseColorSpace(container); + texture.needsUpdate = true; + return Promise.resolve(texture); +} +function parseColorSpace(container) { + const dfd = container.dataFormatDescriptor[0]; + if (dfd.colorPrimaries === C3) { + return dfd.transferFunction === u2 ? SRGBColorSpace : LinearSRGBColorSpace; + } else if (dfd.colorPrimaries === R) { + return dfd.transferFunction === u2 ? DisplayP3ColorSpace : LinearDisplayP3ColorSpace; + } else if (dfd.colorPrimaries === T2) { + return NoColorSpace; + } else { + console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${dfd.colorPrimaries}"`); + return NoColorSpace; + } +} +// node_modules/three/examples/jsm/loaders/KTXLoader.js +var HEADER_LEN = 12 + 13 * 4; +// node_modules/three/examples/jsm/loaders/LDrawLoader.js +var _tempVec0 = new Vector3; +var _tempVec1 = new Vector3; +var _ray3 = new Ray; +// node_modules/three/examples/jsm/libs/lottie_canvas.module.js +var exports_lottie_canvas_module = {}; +__export(exports_lottie_canvas_module, { + default: () => lottie +}); +var lottie = {}; +if (typeof document !== "undefined") { + function createTag(type) { + return document.createElement(type); + } + function extendPrototype(sources, destination) { + var i; + var len = sources.length; + var sourcePrototype; + for (i = 0;i < len; i += 1) { + sourcePrototype = sources[i].prototype; + for (var attr in sourcePrototype) { + if (Object.prototype.hasOwnProperty.call(sourcePrototype, attr)) + destination.prototype[attr] = sourcePrototype[attr]; + } + } + } + function getDescriptor(object, prop) { + return Object.getOwnPropertyDescriptor(object, prop); + } + function createProxyFunction(prototype) { + function ProxyFunction() { + } + ProxyFunction.prototype = prototype; + return ProxyFunction; + } + function createSizedArray(len) { + return Array.apply(null, { length: len }); + } + function ProjectInterface$1() { + return {}; + } + function roundValues(flag) { + _shouldRoundValues = !!flag; + } + function bmRnd(value2) { + if (_shouldRoundValues) { + return Math.round(value2); + } + return value2; + } + function styleDiv(element) { + element.style.position = "absolute"; + element.style.top = 0; + element.style.left = 0; + element.style.display = "block"; + element.style.transformOrigin = "0 0"; + element.style.webkitTransformOrigin = "0 0"; + element.style.backfaceVisibility = "visible"; + element.style.webkitBackfaceVisibility = "visible"; + element.style.transformStyle = "preserve-3d"; + element.style.webkitTransformStyle = "preserve-3d"; + element.style.mozTransformStyle = "preserve-3d"; + } + function BMEnterFrameEvent(type, currentTime, totalTime, frameMultiplier) { + this.type = type; + this.currentTime = currentTime; + this.totalTime = totalTime; + this.direction = frameMultiplier < 0 ? -1 : 1; + } + function BMCompleteEvent(type, frameMultiplier) { + this.type = type; + this.direction = frameMultiplier < 0 ? -1 : 1; + } + function BMCompleteLoopEvent(type, totalLoops, currentLoop, frameMultiplier) { + this.type = type; + this.currentLoop = currentLoop; + this.totalLoops = totalLoops; + this.direction = frameMultiplier < 0 ? -1 : 1; + } + function BMSegmentStartEvent(type, firstFrame, totalFrames) { + this.type = type; + this.firstFrame = firstFrame; + this.totalFrames = totalFrames; + } + function BMDestroyEvent(type, target) { + this.type = type; + this.target = target; + } + function BMRenderFrameErrorEvent(nativeError, currentTime) { + this.type = "renderFrameError"; + this.nativeError = nativeError; + this.currentTime = currentTime; + } + function BMConfigErrorEvent(nativeError) { + this.type = "configError"; + this.nativeError = nativeError; + } + function BMAnimationConfigErrorEvent(type, nativeError) { + this.type = type; + this.nativeError = nativeError; + } + function HSVtoRGB(h, s, v) { + var r; + var g3; + var b; + var i; + var f; + var p; + var q2; + var t4; + i = Math.floor(h * 6); + f = h * 6 - i; + p = v * (1 - s); + q2 = v * (1 - f * s); + t4 = v * (1 - (1 - f) * s); + switch (i % 6) { + case 0: + r = v; + g3 = t4; + b = p; + break; + case 1: + r = q2; + g3 = v; + b = p; + break; + case 2: + r = p; + g3 = v; + b = t4; + break; + case 3: + r = p; + g3 = q2; + b = v; + break; + case 4: + r = t4; + g3 = p; + b = v; + break; + case 5: + r = v; + g3 = p; + b = q2; + break; + default: + break; + } + return [ + r, + g3, + b + ]; + } + function RGBtoHSV(r, g3, b) { + var max = Math.max(r, g3, b); + var min = Math.min(r, g3, b); + var d = max - min; + var h; + var s = max === 0 ? 0 : d / max; + var v = max / 255; + switch (max) { + case min: + h = 0; + break; + case r: + h = g3 - b + d * (g3 < b ? 6 : 0); + h /= 6 * d; + break; + case g3: + h = b - r + d * 2; + h /= 6 * d; + break; + case b: + h = r - g3 + d * 4; + h /= 6 * d; + break; + default: + break; + } + return [ + h, + s, + v + ]; + } + function addSaturationToRGB(color, offset) { + var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255); + hsv[1] += offset; + if (hsv[1] > 1) { + hsv[1] = 1; + } else if (hsv[1] <= 0) { + hsv[1] = 0; + } + return HSVtoRGB(hsv[0], hsv[1], hsv[2]); + } + function addBrightnessToRGB(color, offset) { + var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255); + hsv[2] += offset; + if (hsv[2] > 1) { + hsv[2] = 1; + } else if (hsv[2] < 0) { + hsv[2] = 0; + } + return HSVtoRGB(hsv[0], hsv[1], hsv[2]); + } + function addHueToRGB(color, offset) { + var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255); + hsv[0] += offset / 360; + if (hsv[0] > 1) { + hsv[0] -= 1; + } else if (hsv[0] < 0) { + hsv[0] += 1; + } + return HSVtoRGB(hsv[0], hsv[1], hsv[2]); + } + function createNS(type) { + return document.createElementNS(svgNS, type); + } + function BaseEvent() { + } + function getRenderer(key2) { + return renderers[key2]; + } + function bezFunction() { + var math = Math; + function pointOnLine2D(x1, y1, x2, y22, x3, y3) { + var det1 = x1 * y22 + y1 * x3 + x2 * y3 - x3 * y22 - y3 * x1 - x2 * y1; + return det1 > -0.001 && det1 < 0.001; + } + function pointOnLine3D(x1, y1, z1, x2, y22, z2, x3, y3, z3) { + if (z1 === 0 && z2 === 0 && z3 === 0) { + return pointOnLine2D(x1, y1, x2, y22, x3, y3); + } + var dist1 = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y22 - y1, 2) + math.pow(z2 - z1, 2)); + var dist2 = math.sqrt(math.pow(x3 - x1, 2) + math.pow(y3 - y1, 2) + math.pow(z3 - z1, 2)); + var dist3 = math.sqrt(math.pow(x3 - x2, 2) + math.pow(y3 - y22, 2) + math.pow(z3 - z2, 2)); + var diffDist; + if (dist1 > dist2) { + if (dist1 > dist3) { + diffDist = dist1 - dist2 - dist3; + } else { + diffDist = dist3 - dist2 - dist1; + } + } else if (dist3 > dist2) { + diffDist = dist3 - dist2 - dist1; + } else { + diffDist = dist2 - dist1 - dist3; + } + return diffDist > -0.0001 && diffDist < 0.0001; + } + var getBezierLength = function() { + return function(pt1, pt2, pt3, pt4) { + var curveSegments = getDefaultCurveSegments(); + var k2; + var i; + var len; + var ptCoord; + var perc; + var addedLength = 0; + var ptDistance; + var point = []; + var lastPoint = []; + var lengthData = bezierLengthPool.newElement(); + len = pt3.length; + for (k2 = 0;k2 < curveSegments; k2 += 1) { + perc = k2 / (curveSegments - 1); + ptDistance = 0; + for (i = 0;i < len; i += 1) { + ptCoord = bmPow(1 - perc, 3) * pt1[i] + 3 * bmPow(1 - perc, 2) * perc * pt3[i] + 3 * (1 - perc) * bmPow(perc, 2) * pt4[i] + bmPow(perc, 3) * pt2[i]; + point[i] = ptCoord; + if (lastPoint[i] !== null) { + ptDistance += bmPow(point[i] - lastPoint[i], 2); + } + lastPoint[i] = point[i]; + } + if (ptDistance) { + ptDistance = bmSqrt(ptDistance); + addedLength += ptDistance; + } + lengthData.percents[k2] = perc; + lengthData.lengths[k2] = addedLength; + } + lengthData.addedLength = addedLength; + return lengthData; + }; + }(); + function getSegmentsLength(shapeData) { + var segmentsLength = segmentsLengthPool.newElement(); + var closed = shapeData.c; + var pathV = shapeData.v; + var pathO = shapeData.o; + var pathI = shapeData.i; + var i; + var len = shapeData._length; + var lengths = segmentsLength.lengths; + var totalLength = 0; + for (i = 0;i < len - 1; i += 1) { + lengths[i] = getBezierLength(pathV[i], pathV[i + 1], pathO[i], pathI[i + 1]); + totalLength += lengths[i].addedLength; + } + if (closed && len) { + lengths[i] = getBezierLength(pathV[i], pathV[0], pathO[i], pathI[0]); + totalLength += lengths[i].addedLength; + } + segmentsLength.totalLength = totalLength; + return segmentsLength; + } + function BezierData(length2) { + this.segmentLength = 0; + this.points = new Array(length2); + } + function PointData(partial2, point) { + this.partialLength = partial2; + this.point = point; + } + var buildBezierData = function() { + var storedData = {}; + return function(pt1, pt2, pt3, pt4) { + var bezierName = (pt1[0] + "_" + pt1[1] + "_" + pt2[0] + "_" + pt2[1] + "_" + pt3[0] + "_" + pt3[1] + "_" + pt4[0] + "_" + pt4[1]).replace(/\./g, "p"); + if (!storedData[bezierName]) { + var curveSegments = getDefaultCurveSegments(); + var k2; + var i; + var len; + var ptCoord; + var perc; + var addedLength = 0; + var ptDistance; + var point; + var lastPoint = null; + if (pt1.length === 2 && (pt1[0] !== pt2[0] || pt1[1] !== pt2[1]) && pointOnLine2D(pt1[0], pt1[1], pt2[0], pt2[1], pt1[0] + pt3[0], pt1[1] + pt3[1]) && pointOnLine2D(pt1[0], pt1[1], pt2[0], pt2[1], pt2[0] + pt4[0], pt2[1] + pt4[1])) { + curveSegments = 2; + } + var bezierData = new BezierData(curveSegments); + len = pt3.length; + for (k2 = 0;k2 < curveSegments; k2 += 1) { + point = createSizedArray(len); + perc = k2 / (curveSegments - 1); + ptDistance = 0; + for (i = 0;i < len; i += 1) { + ptCoord = bmPow(1 - perc, 3) * pt1[i] + 3 * bmPow(1 - perc, 2) * perc * (pt1[i] + pt3[i]) + 3 * (1 - perc) * bmPow(perc, 2) * (pt2[i] + pt4[i]) + bmPow(perc, 3) * pt2[i]; + point[i] = ptCoord; + if (lastPoint !== null) { + ptDistance += bmPow(point[i] - lastPoint[i], 2); + } + } + ptDistance = bmSqrt(ptDistance); + addedLength += ptDistance; + bezierData.points[k2] = new PointData(ptDistance, point); + lastPoint = point; + } + bezierData.segmentLength = addedLength; + storedData[bezierName] = bezierData; + } + return storedData[bezierName]; + }; + }(); + function getDistancePerc(perc, bezierData) { + var percents = bezierData.percents; + var lengths = bezierData.lengths; + var len = percents.length; + var initPos = bmFloor((len - 1) * perc); + var lengthPos = perc * bezierData.addedLength; + var lPerc = 0; + if (initPos === len - 1 || initPos === 0 || lengthPos === lengths[initPos]) { + return percents[initPos]; + } + var dir = lengths[initPos] > lengthPos ? -1 : 1; + var flag = true; + while (flag) { + if (lengths[initPos] <= lengthPos && lengths[initPos + 1] > lengthPos) { + lPerc = (lengthPos - lengths[initPos]) / (lengths[initPos + 1] - lengths[initPos]); + flag = false; + } else { + initPos += dir; + } + if (initPos < 0 || initPos >= len - 1) { + if (initPos === len - 1) { + return percents[initPos]; + } + flag = false; + } + } + return percents[initPos] + (percents[initPos + 1] - percents[initPos]) * lPerc; + } + function getPointInSegment(pt1, pt2, pt3, pt4, percent, bezierData) { + var t1 = getDistancePerc(percent, bezierData); + var u1 = 1 - t1; + var ptX = math.round((u1 * u1 * u1 * pt1[0] + (t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1) * pt3[0] + (t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1) * pt4[0] + t1 * t1 * t1 * pt2[0]) * 1000) / 1000; + var ptY = math.round((u1 * u1 * u1 * pt1[1] + (t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1) * pt3[1] + (t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1) * pt4[1] + t1 * t1 * t1 * pt2[1]) * 1000) / 1000; + return [ptX, ptY]; + } + var bezierSegmentPoints = createTypedArray("float32", 8); + function getNewSegment(pt1, pt2, pt3, pt4, startPerc, endPerc, bezierData) { + if (startPerc < 0) { + startPerc = 0; + } else if (startPerc > 1) { + startPerc = 1; + } + var t02 = getDistancePerc(startPerc, bezierData); + endPerc = endPerc > 1 ? 1 : endPerc; + var t1 = getDistancePerc(endPerc, bezierData); + var i; + var len = pt1.length; + var u02 = 1 - t02; + var u1 = 1 - t1; + var u0u0u0 = u02 * u02 * u02; + var t0u0u0_3 = t02 * u02 * u02 * 3; + var t0t0u0_3 = t02 * t02 * u02 * 3; + var t0t0t0 = t02 * t02 * t02; + var u0u0u1 = u02 * u02 * u1; + var t0u0u1_3 = t02 * u02 * u1 + u02 * t02 * u1 + u02 * u02 * t1; + var t0t0u1_3 = t02 * t02 * u1 + u02 * t02 * t1 + t02 * u02 * t1; + var t0t0t1 = t02 * t02 * t1; + var u0u1u1 = u02 * u1 * u1; + var t0u1u1_3 = t02 * u1 * u1 + u02 * t1 * u1 + u02 * u1 * t1; + var t0t1u1_3 = t02 * t1 * u1 + u02 * t1 * t1 + t02 * u1 * t1; + var t0t1t1 = t02 * t1 * t1; + var u1u1u1 = u1 * u1 * u1; + var t1u1u1_3 = t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1; + var t1t1u1_3 = t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1; + var t1t1t1 = t1 * t1 * t1; + for (i = 0;i < len; i += 1) { + bezierSegmentPoints[i * 4] = math.round((u0u0u0 * pt1[i] + t0u0u0_3 * pt3[i] + t0t0u0_3 * pt4[i] + t0t0t0 * pt2[i]) * 1000) / 1000; + bezierSegmentPoints[i * 4 + 1] = math.round((u0u0u1 * pt1[i] + t0u0u1_3 * pt3[i] + t0t0u1_3 * pt4[i] + t0t0t1 * pt2[i]) * 1000) / 1000; + bezierSegmentPoints[i * 4 + 2] = math.round((u0u1u1 * pt1[i] + t0u1u1_3 * pt3[i] + t0t1u1_3 * pt4[i] + t0t1t1 * pt2[i]) * 1000) / 1000; + bezierSegmentPoints[i * 4 + 3] = math.round((u1u1u1 * pt1[i] + t1u1u1_3 * pt3[i] + t1t1u1_3 * pt4[i] + t1t1t1 * pt2[i]) * 1000) / 1000; + } + return bezierSegmentPoints; + } + return { + getSegmentsLength, + getNewSegment, + getPointInSegment, + buildBezierData, + pointOnLine2D, + pointOnLine3D + }; + } + function DynamicPropertyContainer() { + } + function ShapePath() { + this.c = false; + this._length = 0; + this._maxLength = 8; + this.v = createSizedArray(this._maxLength); + this.o = createSizedArray(this._maxLength); + this.i = createSizedArray(this._maxLength); + } + function ShapeCollection() { + this._length = 0; + this._maxLength = 4; + this.shapes = createSizedArray(this._maxLength); + } + function setLocation(href) { + setLocationHref(href); + } + function searchAnimations() { + if (standalone === true) { + animationManager.searchAnimations(animationData, standalone, renderer); + } else { + animationManager.searchAnimations(); + } + } + function setSubframeRendering(flag) { + setSubframeEnabled(flag); + } + function setPrefix(prefix) { + setIdPrefix(prefix); + } + function loadAnimation(params) { + if (standalone === true) { + params.animationData = JSON.parse(animationData); + } + return animationManager.loadAnimation(params); + } + function setQuality(value2) { + if (typeof value2 === "string") { + switch (value2) { + case "high": + setDefaultCurveSegments(200); + break; + default: + case "medium": + setDefaultCurveSegments(50); + break; + case "low": + setDefaultCurveSegments(10); + break; + } + } else if (!isNaN(value2) && value2 > 1) { + setDefaultCurveSegments(value2); + } + if (getDefaultCurveSegments() >= 50) { + roundValues(false); + } else { + roundValues(true); + } + } + function inBrowser() { + return typeof navigator !== "undefined"; + } + function installPlugin(type, plugin) { + if (type === "expressions") { + setExpressionsPlugin(plugin); + } + } + function getFactory(name2) { + switch (name2) { + case "propertyFactory": + return PropertyFactory; + case "shapePropertyFactory": + return ShapePropertyFactory; + case "matrix": + return Matrix; + default: + return null; + } + } + function checkReady() { + if (document.readyState === "complete") { + clearInterval(readyStateCheckInterval); + searchAnimations(); + } + } + function getQueryVariable(variable) { + var vars = queryString.split("&"); + for (var i = 0;i < vars.length; i += 1) { + var pair = vars[i].split("="); + if (decodeURIComponent(pair[0]) == variable) { + return decodeURIComponent(pair[1]); + } + } + return null; + } + function ShapeModifier() { + } + function TrimModifier() { + } + function PuckerAndBloatModifier() { + } + function RepeaterModifier() { + } + function RoundCornersModifier() { + } + function getFontProperties(fontData) { + var styles = fontData.fStyle ? fontData.fStyle.split(" ") : []; + var fWeight = "normal"; + var fStyle = "normal"; + var len = styles.length; + var styleName; + for (var i = 0;i < len; i += 1) { + styleName = styles[i].toLowerCase(); + switch (styleName) { + case "italic": + fStyle = "italic"; + break; + case "bold": + fWeight = "700"; + break; + case "black": + fWeight = "900"; + break; + case "medium": + fWeight = "500"; + break; + case "regular": + case "normal": + fWeight = "400"; + break; + case "light": + case "thin": + fWeight = "200"; + break; + default: + break; + } + } + return { + style: fStyle, + weight: fontData.fWeight || fWeight + }; + } + function RenderableElement() { + } + function SliderEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function AngleEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function ColorEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 1, 0, container); + } + function PointEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 1, 0, container); + } + function LayerIndexEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function MaskIndexEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function CheckboxEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function NoValueEffect() { + this.p = {}; + } + function EffectsManager(data2, element) { + var effects = data2.ef || []; + this.effectElements = []; + var i; + var len = effects.length; + var effectItem; + for (i = 0;i < len; i += 1) { + effectItem = new GroupEffect(effects[i], element); + this.effectElements.push(effectItem); + } + } + function GroupEffect(data2, element) { + this.init(data2, element); + } + function BaseElement() { + } + function FrameElement() { + } + function FootageElement(data2, globalData2, comp2) { + this.initFrame(); + this.initRenderable(); + this.assetData = globalData2.getAssetData(data2.refId); + this.footageData = globalData2.imageLoader.getAsset(this.assetData); + this.initBaseData(data2, globalData2, comp2); + } + function AudioElement(data2, globalData2, comp2) { + this.initFrame(); + this.initRenderable(); + this.assetData = globalData2.getAssetData(data2.refId); + this.initBaseData(data2, globalData2, comp2); + this._isPlaying = false; + this._canPlay = false; + var assetPath = this.globalData.getAssetsPath(this.assetData); + this.audio = this.globalData.audioController.createAudio(assetPath); + this._currentTime = 0; + this.globalData.audioController.addAudio(this); + this._volumeMultiplier = 1; + this._volume = 1; + this._previousVolume = null; + this.tm = data2.tm ? PropertyFactory.getProp(this, data2.tm, 0, globalData2.frameRate, this) : { _placeholder: true }; + this.lv = PropertyFactory.getProp(this, data2.au && data2.au.lv ? data2.au.lv : { k: [100] }, 1, 0.01, this); + } + function BaseRenderer() { + } + function TransformElement() { + } + function MaskElement(data2, element, globalData2) { + this.data = data2; + this.element = element; + this.globalData = globalData2; + this.storedData = []; + this.masksProperties = this.data.masksProperties || []; + this.maskElement = null; + var defs = this.globalData.defs; + var i; + var len = this.masksProperties ? this.masksProperties.length : 0; + this.viewData = createSizedArray(len); + this.solidPath = ""; + var path; + var properties = this.masksProperties; + var count = 0; + var currentMasks = []; + var j2; + var jLen; + var layerId = createElementID(); + var rect; + var expansor; + var feMorph; + var x2; + var maskType = "clipPath"; + var maskRef = "clip-path"; + for (i = 0;i < len; i += 1) { + if (properties[i].mode !== "a" && properties[i].mode !== "n" || properties[i].inv || properties[i].o.k !== 100 || properties[i].o.x) { + maskType = "mask"; + maskRef = "mask"; + } + if ((properties[i].mode === "s" || properties[i].mode === "i") && count === 0) { + rect = createNS("rect"); + rect.setAttribute("fill", "#ffffff"); + rect.setAttribute("width", this.element.comp.data.w || 0); + rect.setAttribute("height", this.element.comp.data.h || 0); + currentMasks.push(rect); + } else { + rect = null; + } + path = createNS("path"); + if (properties[i].mode === "n") { + this.viewData[i] = { + op: PropertyFactory.getProp(this.element, properties[i].o, 0, 0.01, this.element), + prop: ShapePropertyFactory.getShapeProp(this.element, properties[i], 3), + elem: path, + lastPath: "" + }; + defs.appendChild(path); + } else { + count += 1; + path.setAttribute("fill", properties[i].mode === "s" ? "#000000" : "#ffffff"); + path.setAttribute("clip-rule", "nonzero"); + var filterID; + if (properties[i].x.k !== 0) { + maskType = "mask"; + maskRef = "mask"; + x2 = PropertyFactory.getProp(this.element, properties[i].x, 0, null, this.element); + filterID = createElementID(); + expansor = createNS("filter"); + expansor.setAttribute("id", filterID); + feMorph = createNS("feMorphology"); + feMorph.setAttribute("operator", "erode"); + feMorph.setAttribute("in", "SourceGraphic"); + feMorph.setAttribute("radius", "0"); + expansor.appendChild(feMorph); + defs.appendChild(expansor); + path.setAttribute("stroke", properties[i].mode === "s" ? "#000000" : "#ffffff"); + } else { + feMorph = null; + x2 = null; + } + this.storedData[i] = { + elem: path, + x: x2, + expan: feMorph, + lastPath: "", + lastOperator: "", + filterId: filterID, + lastRadius: 0 + }; + if (properties[i].mode === "i") { + jLen = currentMasks.length; + var g3 = createNS("g"); + for (j2 = 0;j2 < jLen; j2 += 1) { + g3.appendChild(currentMasks[j2]); + } + var mask2 = createNS("mask"); + mask2.setAttribute("mask-type", "alpha"); + mask2.setAttribute("id", layerId + "_" + count); + mask2.appendChild(path); + defs.appendChild(mask2); + g3.setAttribute("mask", "url(" + getLocationHref() + "#" + layerId + "_" + count + ")"); + currentMasks.length = 0; + currentMasks.push(g3); + } else { + currentMasks.push(path); + } + if (properties[i].inv && !this.solidPath) { + this.solidPath = this.createLayerSolidPath(); + } + this.viewData[i] = { + elem: path, + lastPath: "", + op: PropertyFactory.getProp(this.element, properties[i].o, 0, 0.01, this.element), + prop: ShapePropertyFactory.getShapeProp(this.element, properties[i], 3), + invRect: rect + }; + if (!this.viewData[i].prop.k) { + this.drawPath(properties[i], this.viewData[i].prop.v, this.viewData[i]); + } + } + } + this.maskElement = createNS(maskType); + len = currentMasks.length; + for (i = 0;i < len; i += 1) { + this.maskElement.appendChild(currentMasks[i]); + } + if (count > 0) { + this.maskElement.setAttribute("id", layerId); + this.element.maskedElement.setAttribute(maskRef, "url(" + getLocationHref() + "#" + layerId + ")"); + defs.appendChild(this.maskElement); + } + if (this.viewData.length) { + this.element.addRenderableComponent(this); + } + } + function SVGEffects(elem2) { + var i; + var source = "SourceGraphic"; + var len = elem2.data.ef ? elem2.data.ef.length : 0; + var filId = createElementID(); + var fil = filtersFactory.createFilter(filId, true); + var count = 0; + this.filters = []; + var filterManager; + for (i = 0;i < len; i += 1) { + filterManager = null; + var type = elem2.data.ef[i].ty; + if (registeredEffects[type]) { + var Effect = registeredEffects[type].effect; + filterManager = new Effect(fil, elem2.effectsManager.effectElements[i], elem2, idPrefix + count, source); + source = idPrefix + count; + if (registeredEffects[type].countsAsEffect) { + count += 1; + } + } + if (filterManager) { + this.filters.push(filterManager); + } + } + if (count) { + elem2.globalData.defs.appendChild(fil); + elem2.layerElement.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")"); + } + if (this.filters.length) { + elem2.addRenderableComponent(this); + } + } + function registerEffect(id, effect2, countsAsEffect) { + registeredEffects[id] = { + effect: effect2, + countsAsEffect + }; + } + function SVGBaseElement() { + } + function HierarchyElement() { + } + function RenderableDOMElement() { + } + function IImageElement(data2, globalData2, comp2) { + this.assetData = globalData2.getAssetData(data2.refId); + this.initElement(data2, globalData2, comp2); + this.sourceRect = { + top: 0, + left: 0, + width: this.assetData.w, + height: this.assetData.h + }; + } + function ProcessedElement(element, position2) { + this.elem = element; + this.pos = position2; + } + function IShapeElement() { + } + function SVGShapeData(transformers, level, shape) { + this.caches = []; + this.styles = []; + this.transformers = transformers; + this.lStr = ""; + this.sh = shape; + this.lvl = level; + this._isAnimated = !!shape.k; + var i = 0; + var len = transformers.length; + while (i < len) { + if (transformers[i].mProps.dynamicProperties.length) { + this._isAnimated = true; + break; + } + i += 1; + } + } + function SVGStyleData(data2, level) { + this.data = data2; + this.type = data2.ty; + this.d = ""; + this.lvl = level; + this._mdf = false; + this.closed = data2.hd === true; + this.pElem = createNS("path"); + this.msElem = null; + } + function DashProperty(elem2, data2, renderer2, container) { + this.elem = elem2; + this.frameId = -1; + this.dataProps = createSizedArray(data2.length); + this.renderer = renderer2; + this.k = false; + this.dashStr = ""; + this.dashArray = createTypedArray("float32", data2.length ? data2.length - 1 : 0); + this.dashoffset = createTypedArray("float32", 1); + this.initDynamicPropertyContainer(container); + var i; + var len = data2.length || 0; + var prop; + for (i = 0;i < len; i += 1) { + prop = PropertyFactory.getProp(elem2, data2[i].v, 0, 0, this); + this.k = prop.k || this.k; + this.dataProps[i] = { n: data2[i].n, p: prop }; + } + if (!this.k) { + this.getValue(true); + } + this._isAnimated = this.k; + } + function SVGStrokeStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, this); + this.w = PropertyFactory.getProp(elem2, data2.w, 0, null, this); + this.d = new DashProperty(elem2, data2.d || {}, "svg", this); + this.c = PropertyFactory.getProp(elem2, data2.c, 1, 255, this); + this.style = styleOb; + this._isAnimated = !!this._isAnimated; + } + function SVGFillStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, this); + this.c = PropertyFactory.getProp(elem2, data2.c, 1, 255, this); + this.style = styleOb; + } + function SVGNoStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.style = styleOb; + } + function GradientProperty(elem2, data2, container) { + this.data = data2; + this.c = createTypedArray("uint8c", data2.p * 4); + var cLength = data2.k.k[0].s ? data2.k.k[0].s.length - data2.p * 4 : data2.k.k.length - data2.p * 4; + this.o = createTypedArray("float32", cLength); + this._cmdf = false; + this._omdf = false; + this._collapsable = this.checkCollapsable(); + this._hasOpacity = cLength; + this.initDynamicPropertyContainer(container); + this.prop = PropertyFactory.getProp(elem2, data2.k, 1, null, this); + this.k = this.prop.k; + this.getValue(true); + } + function SVGGradientFillStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.initGradientData(elem2, data2, styleOb); + } + function SVGGradientStrokeStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.w = PropertyFactory.getProp(elem2, data2.w, 0, null, this); + this.d = new DashProperty(elem2, data2.d || {}, "svg", this); + this.initGradientData(elem2, data2, styleOb); + this._isAnimated = !!this._isAnimated; + } + function ShapeGroupData() { + this.it = []; + this.prevViewData = []; + this.gr = createNS("g"); + } + function SVGTransformData(mProps, op, container) { + this.transform = { + mProps, + op, + container + }; + this.elements = []; + this._isAnimated = this.transform.mProps.dynamicProperties.length || this.transform.op.effectsSequence.length; + } + function SVGShapeElement(data2, globalData2, comp2) { + this.shapes = []; + this.shapesData = data2.shapes; + this.stylesList = []; + this.shapeModifiers = []; + this.itemsData = []; + this.processedElements = []; + this.animatedContents = []; + this.initElement(data2, globalData2, comp2); + this.prevViewData = []; + } + function LetterProps(o, sw, sc, fc, m, p) { + this.o = o; + this.sw = sw; + this.sc = sc; + this.fc = fc; + this.m = m; + this.p = p; + this._mdf = { + o: true, + sw: !!sw, + sc: !!sc, + fc: !!fc, + m: true, + p: true + }; + } + function TextProperty(elem2, data2) { + this._frameId = initialDefaultFrame; + this.pv = ""; + this.v = ""; + this.kf = false; + this._isFirstFrame = true; + this._mdf = false; + this.data = data2; + this.elem = elem2; + this.comp = this.elem.comp; + this.keysIndex = 0; + this.canResize = false; + this.minimumFontSize = 1; + this.effectsSequence = []; + this.currentData = { + ascent: 0, + boxWidth: this.defaultBoxWidth, + f: "", + fStyle: "", + fWeight: "", + fc: "", + j: "", + justifyOffset: "", + l: [], + lh: 0, + lineWidths: [], + ls: "", + of: "", + s: "", + sc: "", + sw: 0, + t: 0, + tr: 0, + sz: 0, + ps: null, + fillColorAnim: false, + strokeColorAnim: false, + strokeWidthAnim: false, + yOffset: 0, + finalSize: 0, + finalText: [], + finalLineHeight: 0, + __complete: false + }; + this.copyData(this.currentData, this.data.d.k[0].s); + if (!this.searchProperty()) { + this.completeTextData(this.currentData); + } + } + function TextAnimatorDataProperty(elem2, animatorProps, container) { + var defaultData = { propType: false }; + var getProp = PropertyFactory.getProp; + var textAnimatorAnimatables = animatorProps.a; + this.a = { + r: textAnimatorAnimatables.r ? getProp(elem2, textAnimatorAnimatables.r, 0, degToRads, container) : defaultData, + rx: textAnimatorAnimatables.rx ? getProp(elem2, textAnimatorAnimatables.rx, 0, degToRads, container) : defaultData, + ry: textAnimatorAnimatables.ry ? getProp(elem2, textAnimatorAnimatables.ry, 0, degToRads, container) : defaultData, + sk: textAnimatorAnimatables.sk ? getProp(elem2, textAnimatorAnimatables.sk, 0, degToRads, container) : defaultData, + sa: textAnimatorAnimatables.sa ? getProp(elem2, textAnimatorAnimatables.sa, 0, degToRads, container) : defaultData, + s: textAnimatorAnimatables.s ? getProp(elem2, textAnimatorAnimatables.s, 1, 0.01, container) : defaultData, + a: textAnimatorAnimatables.a ? getProp(elem2, textAnimatorAnimatables.a, 1, 0, container) : defaultData, + o: textAnimatorAnimatables.o ? getProp(elem2, textAnimatorAnimatables.o, 0, 0.01, container) : defaultData, + p: textAnimatorAnimatables.p ? getProp(elem2, textAnimatorAnimatables.p, 1, 0, container) : defaultData, + sw: textAnimatorAnimatables.sw ? getProp(elem2, textAnimatorAnimatables.sw, 0, 0, container) : defaultData, + sc: textAnimatorAnimatables.sc ? getProp(elem2, textAnimatorAnimatables.sc, 1, 0, container) : defaultData, + fc: textAnimatorAnimatables.fc ? getProp(elem2, textAnimatorAnimatables.fc, 1, 0, container) : defaultData, + fh: textAnimatorAnimatables.fh ? getProp(elem2, textAnimatorAnimatables.fh, 0, 0, container) : defaultData, + fs: textAnimatorAnimatables.fs ? getProp(elem2, textAnimatorAnimatables.fs, 0, 0.01, container) : defaultData, + fb: textAnimatorAnimatables.fb ? getProp(elem2, textAnimatorAnimatables.fb, 0, 0.01, container) : defaultData, + t: textAnimatorAnimatables.t ? getProp(elem2, textAnimatorAnimatables.t, 0, 0, container) : defaultData + }; + this.s = TextSelectorProp.getTextSelectorProp(elem2, animatorProps.s, container); + this.s.t = animatorProps.s.t; + } + function TextAnimatorProperty(textData, renderType, elem2) { + this._isFirstFrame = true; + this._hasMaskedPath = false; + this._frameId = -1; + this._textData = textData; + this._renderType = renderType; + this._elem = elem2; + this._animatorsData = createSizedArray(this._textData.a.length); + this._pathData = {}; + this._moreOptions = { + alignment: {} + }; + this.renderedLetters = []; + this.lettersChangedFlag = false; + this.initDynamicPropertyContainer(elem2); + } + function ITextElement() { + } + function SVGTextLottieElement(data2, globalData2, comp2) { + this.textSpans = []; + this.renderType = "svg"; + this.initElement(data2, globalData2, comp2); + } + function ISolidElement(data2, globalData2, comp2) { + this.initElement(data2, globalData2, comp2); + } + function NullElement(data2, globalData2, comp2) { + this.initFrame(); + this.initBaseData(data2, globalData2, comp2); + this.initFrame(); + this.initTransform(data2, globalData2, comp2); + this.initHierarchy(); + } + function SVGRendererBase() { + } + function ICompElement() { + } + function SVGCompElement(data2, globalData2, comp2) { + this.layers = data2.layers; + this.supports3d = true; + this.completeLayers = false; + this.pendingElements = []; + this.elements = this.layers ? createSizedArray(this.layers.length) : []; + this.initElement(data2, globalData2, comp2); + this.tm = data2.tm ? PropertyFactory.getProp(this, data2.tm, 0, globalData2.frameRate, this) : { _placeholder: true }; + } + function SVGRenderer(animationItem, config) { + this.animationItem = animationItem; + this.layers = null; + this.renderedFrame = -1; + this.svgElement = createNS("svg"); + var ariaLabel = ""; + if (config && config.title) { + var titleElement = createNS("title"); + var titleId = createElementID(); + titleElement.setAttribute("id", titleId); + titleElement.textContent = config.title; + this.svgElement.appendChild(titleElement); + ariaLabel += titleId; + } + if (config && config.description) { + var descElement = createNS("desc"); + var descId = createElementID(); + descElement.setAttribute("id", descId); + descElement.textContent = config.description; + this.svgElement.appendChild(descElement); + ariaLabel += " " + descId; + } + if (ariaLabel) { + this.svgElement.setAttribute("aria-labelledby", ariaLabel); + } + var defs = createNS("defs"); + this.svgElement.appendChild(defs); + var maskElement = createNS("g"); + this.svgElement.appendChild(maskElement); + this.layerElement = maskElement; + this.renderConfig = { + preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet", + imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice", + contentVisibility: config && config.contentVisibility || "visible", + progressiveLoad: config && config.progressiveLoad || false, + hideOnTransparent: !(config && config.hideOnTransparent === false), + viewBoxOnly: config && config.viewBoxOnly || false, + viewBoxSize: config && config.viewBoxSize || false, + className: config && config.className || "", + id: config && config.id || "", + focusable: config && config.focusable, + filterSize: { + width: config && config.filterSize && config.filterSize.width || "100%", + height: config && config.filterSize && config.filterSize.height || "100%", + x: config && config.filterSize && config.filterSize.x || "0%", + y: config && config.filterSize && config.filterSize.y || "0%" + }, + width: config && config.width, + height: config && config.height + }; + this.globalData = { + _mdf: false, + frameNum: -1, + defs, + renderConfig: this.renderConfig + }; + this.elements = []; + this.pendingElements = []; + this.destroyed = false; + this.rendererType = "svg"; + } + function CVContextData() { + this.saved = []; + this.cArrPos = 0; + this.cTr = new Matrix; + this.cO = 1; + var i; + var len = 15; + this.savedOp = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + this.saved[i] = createTypedArray("float32", 16); + } + this._length = len; + } + function ShapeTransformManager() { + this.sequences = {}; + this.sequenceList = []; + this.transform_key_count = 0; + } + function CVEffects() { + } + function CVMaskElement(data2, element) { + this.data = data2; + this.element = element; + this.masksProperties = this.data.masksProperties || []; + this.viewData = createSizedArray(this.masksProperties.length); + var i; + var len = this.masksProperties.length; + var hasMasks = false; + for (i = 0;i < len; i += 1) { + if (this.masksProperties[i].mode !== "n") { + hasMasks = true; + } + this.viewData[i] = ShapePropertyFactory.getShapeProp(this.element, this.masksProperties[i], 3); + } + this.hasMasks = hasMasks; + if (hasMasks) { + this.element.addRenderableComponent(this); + } + } + function CVBaseElement() { + } + function CVShapeData(element, data2, styles, transformsManager) { + this.styledShapes = []; + this.tr = [0, 0, 0, 0, 0, 0]; + var ty2 = 4; + if (data2.ty === "rc") { + ty2 = 5; + } else if (data2.ty === "el") { + ty2 = 6; + } else if (data2.ty === "sr") { + ty2 = 7; + } + this.sh = ShapePropertyFactory.getShapeProp(element, data2, ty2, element); + var i; + var len = styles.length; + var styledShape; + for (i = 0;i < len; i += 1) { + if (!styles[i].closed) { + styledShape = { + transforms: transformsManager.addTransformSequence(styles[i].transforms), + trNodes: [] + }; + this.styledShapes.push(styledShape); + styles[i].elements.push(styledShape); + } + } + } + function CVShapeElement(data2, globalData2, comp2) { + this.shapes = []; + this.shapesData = data2.shapes; + this.stylesList = []; + this.itemsData = []; + this.prevViewData = []; + this.shapeModifiers = []; + this.processedElements = []; + this.transformsManager = new ShapeTransformManager; + this.initElement(data2, globalData2, comp2); + } + function CVTextElement(data2, globalData2, comp2) { + this.textSpans = []; + this.yOffset = 0; + this.fillColorAnim = false; + this.strokeColorAnim = false; + this.strokeWidthAnim = false; + this.stroke = false; + this.fill = false; + this.justifyOffset = 0; + this.currentRender = null; + this.renderType = "canvas"; + this.values = { + fill: "rgba(0,0,0,0)", + stroke: "rgba(0,0,0,0)", + sWidth: 0, + fValue: "" + }; + this.initElement(data2, globalData2, comp2); + } + function CVImageElement(data2, globalData2, comp2) { + this.assetData = globalData2.getAssetData(data2.refId); + this.img = globalData2.imageLoader.getAsset(this.assetData); + this.initElement(data2, globalData2, comp2); + } + function CVSolidElement(data2, globalData2, comp2) { + this.initElement(data2, globalData2, comp2); + } + function CanvasRendererBase(animationItem, config) { + this.animationItem = animationItem; + this.renderConfig = { + clearCanvas: config && config.clearCanvas !== undefined ? config.clearCanvas : true, + context: config && config.context || null, + progressiveLoad: config && config.progressiveLoad || false, + preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet", + imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice", + contentVisibility: config && config.contentVisibility || "visible", + className: config && config.className || "", + id: config && config.id || "" + }; + this.renderConfig.dpr = config && config.dpr || 1; + if (this.animationItem.wrapper) { + this.renderConfig.dpr = config && config.dpr || window.devicePixelRatio || 1; + } + this.renderedFrame = -1; + this.globalData = { + frameNum: -1, + _mdf: false, + renderConfig: this.renderConfig, + currentGlobalAlpha: -1 + }; + this.contextData = new CVContextData; + this.elements = []; + this.pendingElements = []; + this.transformMat = new Matrix; + this.completeLayers = false; + this.rendererType = "canvas"; + } + function CVCompElement(data2, globalData2, comp2) { + this.completeLayers = false; + this.layers = data2.layers; + this.pendingElements = []; + this.elements = createSizedArray(this.layers.length); + this.initElement(data2, globalData2, comp2); + this.tm = data2.tm ? PropertyFactory.getProp(this, data2.tm, 0, globalData2.frameRate, this) : { _placeholder: true }; + } + function CanvasRenderer(animationItem, config) { + this.animationItem = animationItem; + this.renderConfig = { + clearCanvas: config && config.clearCanvas !== undefined ? config.clearCanvas : true, + context: config && config.context || null, + progressiveLoad: config && config.progressiveLoad || false, + preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet", + imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice", + contentVisibility: config && config.contentVisibility || "visible", + className: config && config.className || "", + id: config && config.id || "" + }; + this.renderConfig.dpr = config && config.dpr || 1; + if (this.animationItem.wrapper) { + this.renderConfig.dpr = config && config.dpr || window.devicePixelRatio || 1; + } + this.renderedFrame = -1; + this.globalData = { + frameNum: -1, + _mdf: false, + renderConfig: this.renderConfig, + currentGlobalAlpha: -1 + }; + this.contextData = new CVContextData; + this.elements = []; + this.pendingElements = []; + this.transformMat = new Matrix; + this.completeLayers = false; + this.rendererType = "canvas"; + } + function seedRandom(pool, math) { + var global2 = this, width2 = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width2, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask2 = width2 - 1, nodecrypto; + function seedrandom(seed, options, callback) { + var key2 = []; + options = options === true ? { entropy: true } : options || {}; + var shortseed = mixkey(flatten3(options.entropy ? [seed, tostring(pool)] : seed === null ? autoseed() : seed, 3), key2); + var arc4 = new ARC4(key2); + var prng = function() { + var n2 = arc4.g(chunks), d = startdenom, x2 = 0; + while (n2 < significance) { + n2 = (n2 + x2) * width2; + d *= width2; + x2 = arc4.g(1); + } + while (n2 >= overflow) { + n2 /= 2; + d /= 2; + x2 >>>= 1; + } + return (n2 + x2) / d; + }; + prng.int32 = function() { + return arc4.g(4) | 0; + }; + prng.quick = function() { + return arc4.g(4) / 4294967296; + }; + prng.double = prng; + mixkey(tostring(arc4.S), pool); + return (options.pass || callback || function(prng2, seed2, is_math_call, state) { + if (state) { + if (state.S) { + copy(state, arc4); + } + prng2.state = function() { + return copy(arc4, {}); + }; + } + if (is_math_call) { + math[rngname] = prng2; + return seed2; + } else + return prng2; + })(prng, shortseed, "global" in options ? options.global : this == math, options.state); + } + math["seed" + rngname] = seedrandom; + function ARC4(key2) { + var t4, keylen = key2.length, me = this, i = 0, j2 = me.i = me.j = 0, s = me.S = []; + if (!keylen) { + key2 = [keylen++]; + } + while (i < width2) { + s[i] = i++; + } + for (i = 0;i < width2; i++) { + s[i] = s[j2 = mask2 & j2 + key2[i % keylen] + (t4 = s[i])]; + s[j2] = t4; + } + me.g = function(count) { + var t5, r = 0, i3 = me.i, j4 = me.j, s3 = me.S; + while (count--) { + t5 = s3[i3 = mask2 & i3 + 1]; + r = r * width2 + s3[mask2 & (s3[i3] = s3[j4 = mask2 & j4 + t5]) + (s3[j4] = t5)]; + } + me.i = i3; + me.j = j4; + return r; + }; + } + function copy(f, t4) { + t4.i = f.i; + t4.j = f.j; + t4.S = f.S.slice(); + return t4; + } + function flatten3(obj, depth) { + var result = [], typ = typeof obj, prop; + if (depth && typ == "object") { + for (prop in obj) { + try { + result.push(flatten3(obj[prop], depth - 1)); + } catch (e) { + } + } + } + return result.length ? result : typ == "string" ? obj : obj + "\x00"; + } + function mixkey(seed, key2) { + var stringseed = seed + "", smear, j2 = 0; + while (j2 < stringseed.length) { + key2[mask2 & j2] = mask2 & (smear ^= key2[mask2 & j2] * 19) + stringseed.charCodeAt(j2++); + } + return tostring(key2); + } + function autoseed() { + try { + if (nodecrypto) { + return tostring(nodecrypto.randomBytes(width2)); + } + var out = new Uint8Array(width2); + (global2.crypto || global2.msCrypto).getRandomValues(out); + return tostring(out); + } catch (e) { + var browser = global2.navigator, plugins = browser && browser.plugins; + return [+new Date, global2, plugins, global2.screen, tostring(pool)]; + } + } + function tostring(a) { + return String.fromCharCode.apply(0, a); + } + mixkey(math.random(), pool); + } + function initialize$2(BMMath2) { + seedRandom([], BMMath2); + } + function addPropertyDecorator() { + function loopOut2(type, duration, durationFlag) { + if (!this.k || !this.keyframes) { + return this.pv; + } + type = type ? type.toLowerCase() : ""; + var currentFrame = this.comp.renderedFrame; + var keyframes = this.keyframes; + var lastKeyFrame = keyframes[keyframes.length - 1].t; + if (currentFrame <= lastKeyFrame) { + return this.pv; + } + var cycleDuration; + var firstKeyFrame; + if (!durationFlag) { + if (!duration || duration > keyframes.length - 1) { + duration = keyframes.length - 1; + } + firstKeyFrame = keyframes[keyframes.length - 1 - duration].t; + cycleDuration = lastKeyFrame - firstKeyFrame; + } else { + if (!duration) { + cycleDuration = Math.max(0, lastKeyFrame - this.elem.data.ip); + } else { + cycleDuration = Math.abs(lastKeyFrame - this.elem.comp.globalData.frameRate * duration); + } + firstKeyFrame = lastKeyFrame - cycleDuration; + } + var i; + var len; + var ret; + if (type === "pingpong") { + var iterations = Math.floor((currentFrame - firstKeyFrame) / cycleDuration); + if (iterations % 2 !== 0) { + return this.getValueAtTime((cycleDuration - (currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + } + } else if (type === "offset") { + var initV = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0); + var endV = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0); + var current = this.getValueAtTime(((currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + var repeats = Math.floor((currentFrame - firstKeyFrame) / cycleDuration); + if (this.pv.length) { + ret = new Array(initV.length); + len = ret.length; + for (i = 0;i < len; i += 1) { + ret[i] = (endV[i] - initV[i]) * repeats + current[i]; + } + return ret; + } + return (endV - initV) * repeats + current; + } else if (type === "continue") { + var lastValue = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0); + var nextLastValue = this.getValueAtTime((lastKeyFrame - 0.001) / this.comp.globalData.frameRate, 0); + if (this.pv.length) { + ret = new Array(lastValue.length); + len = ret.length; + for (i = 0;i < len; i += 1) { + ret[i] = lastValue[i] + (lastValue[i] - nextLastValue[i]) * ((currentFrame - lastKeyFrame) / this.comp.globalData.frameRate) / 0.0005; + } + return ret; + } + return lastValue + (lastValue - nextLastValue) * ((currentFrame - lastKeyFrame) / 0.001); + } + return this.getValueAtTime(((currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + } + function loopIn2(type, duration, durationFlag) { + if (!this.k) { + return this.pv; + } + type = type ? type.toLowerCase() : ""; + var currentFrame = this.comp.renderedFrame; + var keyframes = this.keyframes; + var firstKeyFrame = keyframes[0].t; + if (currentFrame >= firstKeyFrame) { + return this.pv; + } + var cycleDuration; + var lastKeyFrame; + if (!durationFlag) { + if (!duration || duration > keyframes.length - 1) { + duration = keyframes.length - 1; + } + lastKeyFrame = keyframes[duration].t; + cycleDuration = lastKeyFrame - firstKeyFrame; + } else { + if (!duration) { + cycleDuration = Math.max(0, this.elem.data.op - firstKeyFrame); + } else { + cycleDuration = Math.abs(this.elem.comp.globalData.frameRate * duration); + } + lastKeyFrame = firstKeyFrame + cycleDuration; + } + var i; + var len; + var ret; + if (type === "pingpong") { + var iterations = Math.floor((firstKeyFrame - currentFrame) / cycleDuration); + if (iterations % 2 === 0) { + return this.getValueAtTime(((firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + } + } else if (type === "offset") { + var initV = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0); + var endV = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0); + var current = this.getValueAtTime((cycleDuration - (firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + var repeats = Math.floor((firstKeyFrame - currentFrame) / cycleDuration) + 1; + if (this.pv.length) { + ret = new Array(initV.length); + len = ret.length; + for (i = 0;i < len; i += 1) { + ret[i] = current[i] - (endV[i] - initV[i]) * repeats; + } + return ret; + } + return current - (endV - initV) * repeats; + } else if (type === "continue") { + var firstValue = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0); + var nextFirstValue = this.getValueAtTime((firstKeyFrame + 0.001) / this.comp.globalData.frameRate, 0); + if (this.pv.length) { + ret = new Array(firstValue.length); + len = ret.length; + for (i = 0;i < len; i += 1) { + ret[i] = firstValue[i] + (firstValue[i] - nextFirstValue[i]) * (firstKeyFrame - currentFrame) / 0.001; + } + return ret; + } + return firstValue + (firstValue - nextFirstValue) * (firstKeyFrame - currentFrame) / 0.001; + } + return this.getValueAtTime((cycleDuration - ((firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame)) / this.comp.globalData.frameRate, 0); + } + function smooth2(width2, samples) { + if (!this.k) { + return this.pv; + } + width2 = (width2 || 0.4) * 0.5; + samples = Math.floor(samples || 5); + if (samples <= 1) { + return this.pv; + } + var currentTime = this.comp.renderedFrame / this.comp.globalData.frameRate; + var initFrame = currentTime - width2; + var endFrame = currentTime + width2; + var sampleFrequency = samples > 1 ? (endFrame - initFrame) / (samples - 1) : 1; + var i = 0; + var j2 = 0; + var value2; + if (this.pv.length) { + value2 = createTypedArray("float32", this.pv.length); + } else { + value2 = 0; + } + var sampleValue; + while (i < samples) { + sampleValue = this.getValueAtTime(initFrame + i * sampleFrequency); + if (this.pv.length) { + for (j2 = 0;j2 < this.pv.length; j2 += 1) { + value2[j2] += sampleValue[j2]; + } + } else { + value2 += sampleValue; + } + i += 1; + } + if (this.pv.length) { + for (j2 = 0;j2 < this.pv.length; j2 += 1) { + value2[j2] /= samples; + } + } else { + value2 /= samples; + } + return value2; + } + function getTransformValueAtTime(time2) { + if (!this._transformCachingAtTime) { + this._transformCachingAtTime = { + v: new Matrix + }; + } + var matrix = this._transformCachingAtTime.v; + matrix.cloneFromProps(this.pre.props); + if (this.appliedTransformations < 1) { + var anchor = this.a.getValueAtTime(time2); + matrix.translate(-anchor[0] * this.a.mult, -anchor[1] * this.a.mult, anchor[2] * this.a.mult); + } + if (this.appliedTransformations < 2) { + var scale2 = this.s.getValueAtTime(time2); + matrix.scale(scale2[0] * this.s.mult, scale2[1] * this.s.mult, scale2[2] * this.s.mult); + } + if (this.sk && this.appliedTransformations < 3) { + var skew = this.sk.getValueAtTime(time2); + var skewAxis = this.sa.getValueAtTime(time2); + matrix.skewFromAxis(-skew * this.sk.mult, skewAxis * this.sa.mult); + } + if (this.r && this.appliedTransformations < 4) { + var rotation2 = this.r.getValueAtTime(time2); + matrix.rotate(-rotation2 * this.r.mult); + } else if (!this.r && this.appliedTransformations < 4) { + var rotationZ = this.rz.getValueAtTime(time2); + var rotationY = this.ry.getValueAtTime(time2); + var rotationX = this.rx.getValueAtTime(time2); + var orientation = this.or.getValueAtTime(time2); + matrix.rotateZ(-rotationZ * this.rz.mult).rotateY(rotationY * this.ry.mult).rotateX(rotationX * this.rx.mult).rotateZ(-orientation[2] * this.or.mult).rotateY(orientation[1] * this.or.mult).rotateX(orientation[0] * this.or.mult); + } + if (this.data.p && this.data.p.s) { + var positionX = this.px.getValueAtTime(time2); + var positionY = this.py.getValueAtTime(time2); + if (this.data.p.z) { + var positionZ = this.pz.getValueAtTime(time2); + matrix.translate(positionX * this.px.mult, positionY * this.py.mult, -positionZ * this.pz.mult); + } else { + matrix.translate(positionX * this.px.mult, positionY * this.py.mult, 0); + } + } else { + var position2 = this.p.getValueAtTime(time2); + matrix.translate(position2[0] * this.p.mult, position2[1] * this.p.mult, -position2[2] * this.p.mult); + } + return matrix; + } + function getTransformStaticValueAtTime() { + return this.v.clone(new Matrix); + } + var getTransformProperty = TransformPropertyFactory.getTransformProperty; + TransformPropertyFactory.getTransformProperty = function(elem2, data2, container) { + var prop = getTransformProperty(elem2, data2, container); + if (prop.dynamicProperties.length) { + prop.getValueAtTime = getTransformValueAtTime.bind(prop); + } else { + prop.getValueAtTime = getTransformStaticValueAtTime.bind(prop); + } + prop.setGroupProperty = expressionHelpers.setGroupProperty; + return prop; + }; + var propertyGetProp = PropertyFactory.getProp; + PropertyFactory.getProp = function(elem2, data2, type, mult, container) { + var prop = propertyGetProp(elem2, data2, type, mult, container); + if (prop.kf) { + prop.getValueAtTime = expressionHelpers.getValueAtTime.bind(prop); + } else { + prop.getValueAtTime = expressionHelpers.getStaticValueAtTime.bind(prop); + } + prop.setGroupProperty = expressionHelpers.setGroupProperty; + prop.loopOut = loopOut2; + prop.loopIn = loopIn2; + prop.smooth = smooth2; + prop.getVelocityAtTime = expressionHelpers.getVelocityAtTime.bind(prop); + prop.getSpeedAtTime = expressionHelpers.getSpeedAtTime.bind(prop); + prop.numKeys = data2.a === 1 ? data2.k.length : 0; + prop.propertyIndex = data2.ix; + var value2 = 0; + if (type !== 0) { + value2 = createTypedArray("float32", data2.a === 1 ? data2.k[0].s.length : data2.k.length); + } + prop._cachingAtTime = { + lastFrame: initialDefaultFrame, + lastIndex: 0, + value: value2 + }; + expressionHelpers.searchExpressions(elem2, data2, prop); + if (prop.k) { + container.addDynamicProperty(prop); + } + return prop; + }; + function getShapeValueAtTime(frameNum) { + if (!this._cachingAtTime) { + this._cachingAtTime = { + shapeValue: shapePool.clone(this.pv), + lastIndex: 0, + lastTime: initialDefaultFrame + }; + } + frameNum *= this.elem.globalData.frameRate; + frameNum -= this.offsetTime; + if (frameNum !== this._cachingAtTime.lastTime) { + this._cachingAtTime.lastIndex = this._cachingAtTime.lastTime < frameNum ? this._caching.lastIndex : 0; + this._cachingAtTime.lastTime = frameNum; + this.interpolateShape(frameNum, this._cachingAtTime.shapeValue, this._cachingAtTime); + } + return this._cachingAtTime.shapeValue; + } + var ShapePropertyConstructorFunction = ShapePropertyFactory.getConstructorFunction(); + var KeyframedShapePropertyConstructorFunction = ShapePropertyFactory.getKeyframedConstructorFunction(); + function ShapeExpressions() { + } + ShapeExpressions.prototype = { + vertices: function(prop, time2) { + if (this.k) { + this.getValue(); + } + var shapePath = this.v; + if (time2 !== undefined) { + shapePath = this.getValueAtTime(time2, 0); + } + var i; + var len = shapePath._length; + var vertices = shapePath[prop]; + var points = shapePath.v; + var arr = createSizedArray(len); + for (i = 0;i < len; i += 1) { + if (prop === "i" || prop === "o") { + arr[i] = [vertices[i][0] - points[i][0], vertices[i][1] - points[i][1]]; + } else { + arr[i] = [vertices[i][0], vertices[i][1]]; + } + } + return arr; + }, + points: function(time2) { + return this.vertices("v", time2); + }, + inTangents: function(time2) { + return this.vertices("i", time2); + }, + outTangents: function(time2) { + return this.vertices("o", time2); + }, + isClosed: function() { + return this.v.c; + }, + pointOnPath: function(perc, time2) { + var shapePath = this.v; + if (time2 !== undefined) { + shapePath = this.getValueAtTime(time2, 0); + } + if (!this._segmentsLength) { + this._segmentsLength = bez.getSegmentsLength(shapePath); + } + var segmentsLength = this._segmentsLength; + var lengths = segmentsLength.lengths; + var lengthPos = segmentsLength.totalLength * perc; + var i = 0; + var len = lengths.length; + var accumulatedLength = 0; + var pt; + while (i < len) { + if (accumulatedLength + lengths[i].addedLength > lengthPos) { + var initIndex = i; + var endIndex = shapePath.c && i === len - 1 ? 0 : i + 1; + var segmentPerc = (lengthPos - accumulatedLength) / lengths[i].addedLength; + pt = bez.getPointInSegment(shapePath.v[initIndex], shapePath.v[endIndex], shapePath.o[initIndex], shapePath.i[endIndex], segmentPerc, lengths[i]); + break; + } else { + accumulatedLength += lengths[i].addedLength; + } + i += 1; + } + if (!pt) { + pt = shapePath.c ? [shapePath.v[0][0], shapePath.v[0][1]] : [shapePath.v[shapePath._length - 1][0], shapePath.v[shapePath._length - 1][1]]; + } + return pt; + }, + vectorOnPath: function(perc, time2, vectorType) { + if (perc == 1) { + perc = this.v.c; + } else if (perc == 0) { + perc = 0.999; + } + var pt1 = this.pointOnPath(perc, time2); + var pt2 = this.pointOnPath(perc + 0.001, time2); + var xLength = pt2[0] - pt1[0]; + var yLength = pt2[1] - pt1[1]; + var magnitude = Math.sqrt(Math.pow(xLength, 2) + Math.pow(yLength, 2)); + if (magnitude === 0) { + return [0, 0]; + } + var unitVector = vectorType === "tangent" ? [xLength / magnitude, yLength / magnitude] : [-yLength / magnitude, xLength / magnitude]; + return unitVector; + }, + tangentOnPath: function(perc, time2) { + return this.vectorOnPath(perc, time2, "tangent"); + }, + normalOnPath: function(perc, time2) { + return this.vectorOnPath(perc, time2, "normal"); + }, + setGroupProperty: expressionHelpers.setGroupProperty, + getValueAtTime: expressionHelpers.getStaticValueAtTime + }; + extendPrototype([ShapeExpressions], ShapePropertyConstructorFunction); + extendPrototype([ShapeExpressions], KeyframedShapePropertyConstructorFunction); + KeyframedShapePropertyConstructorFunction.prototype.getValueAtTime = getShapeValueAtTime; + KeyframedShapePropertyConstructorFunction.prototype.initiateExpression = ExpressionManager.initiateExpression; + var propertyGetShapeProp = ShapePropertyFactory.getShapeProp; + ShapePropertyFactory.getShapeProp = function(elem2, data2, type, arr, trims) { + var prop = propertyGetShapeProp(elem2, data2, type, arr, trims); + prop.propertyIndex = data2.ix; + prop.lock = false; + if (type === 3) { + expressionHelpers.searchExpressions(elem2, data2.pt, prop); + } else if (type === 4) { + expressionHelpers.searchExpressions(elem2, data2.ks, prop); + } + if (prop.k) { + elem2.addDynamicProperty(prop); + } + return prop; + }; + } + function initialize$1() { + addPropertyDecorator(); + } + function addDecorator() { + function searchExpressions() { + if (this.data.d.x) { + this.calculateExpression = ExpressionManager.initiateExpression.bind(this)(this.elem, this.data.d, this); + this.addEffect(this.getExpressionValue.bind(this)); + return true; + } + return null; + } + TextProperty.prototype.getExpressionValue = function(currentValue, text2) { + var newValue = this.calculateExpression(text2); + if (currentValue.t !== newValue) { + var newData = {}; + this.copyData(newData, currentValue); + newData.t = newValue.toString(); + newData.__complete = false; + return newData; + } + return currentValue; + }; + TextProperty.prototype.searchProperty = function() { + var isKeyframed = this.searchKeyframes(); + var hasExpressions = this.searchExpressions(); + this.kf = isKeyframed || hasExpressions; + return this.kf; + }; + TextProperty.prototype.searchExpressions = searchExpressions; + } + function initialize() { + addDecorator(); + } + const svgNS = "http://www.w3.org/2000/svg"; + let locationHref = ""; + let _useWebWorker = false; + const initialDefaultFrame = -999999; + const setWebWorker = (flag) => { + _useWebWorker = !!flag; + }; + const getWebWorker = () => _useWebWorker; + const setLocationHref = (value2) => { + locationHref = value2; + }; + const getLocationHref = () => locationHref; + const audioControllerFactory = function() { + function AudioController(audioFactory) { + this.audios = []; + this.audioFactory = audioFactory; + this._volume = 1; + this._isMuted = false; + } + AudioController.prototype = { + addAudio: function(audio) { + this.audios.push(audio); + }, + pause: function() { + var i; + var len = this.audios.length; + for (i = 0;i < len; i += 1) { + this.audios[i].pause(); + } + }, + resume: function() { + var i; + var len = this.audios.length; + for (i = 0;i < len; i += 1) { + this.audios[i].resume(); + } + }, + setRate: function(rateValue) { + var i; + var len = this.audios.length; + for (i = 0;i < len; i += 1) { + this.audios[i].setRate(rateValue); + } + }, + createAudio: function(assetPath) { + if (this.audioFactory) { + return this.audioFactory(assetPath); + } + if (window.Howl) { + return new window.Howl({ + src: [assetPath] + }); + } + return { + isPlaying: false, + play: function() { + this.isPlaying = true; + }, + seek: function() { + this.isPlaying = false; + }, + playing: function() { + }, + rate: function() { + }, + setVolume: function() { + } + }; + }, + setAudioFactory: function(audioFactory) { + this.audioFactory = audioFactory; + }, + setVolume: function(value2) { + this._volume = value2; + this._updateVolume(); + }, + mute: function() { + this._isMuted = true; + this._updateVolume(); + }, + unmute: function() { + this._isMuted = false; + this._updateVolume(); + }, + getVolume: function() { + return this._volume; + }, + _updateVolume: function() { + var i; + var len = this.audios.length; + for (i = 0;i < len; i += 1) { + this.audios[i].volume(this._volume * (this._isMuted ? 0 : 1)); + } + } + }; + return function() { + return new AudioController; + }; + }(); + const createTypedArray = function() { + function createRegularArray(type, len) { + var i = 0; + var arr = []; + var value2; + switch (type) { + case "int16": + case "uint8c": + value2 = 1; + break; + default: + value2 = 1.1; + break; + } + for (i = 0;i < len; i += 1) { + arr.push(value2); + } + return arr; + } + function createTypedArrayFactory(type, len) { + if (type === "float32") { + return new Float32Array(len); + } + if (type === "int16") { + return new Int16Array(len); + } + if (type === "uint8c") { + return new Uint8ClampedArray(len); + } + return createRegularArray(type, len); + } + if (typeof Uint8ClampedArray === "function" && typeof Float32Array === "function") { + return createTypedArrayFactory; + } + return createRegularArray; + }(); + let subframeEnabled = true; + let expressionsPlugin = null; + let idPrefix$1 = ""; + const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); + let _shouldRoundValues = false; + const bmPow = Math.pow; + const bmSqrt = Math.sqrt; + const bmFloor = Math.floor; + const bmMax = Math.max; + const bmMin = Math.min; + const BMMath = {}; + (function() { + var propertyNames = ["abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "atan2", "ceil", "cbrt", "expm1", "clz32", "cos", "cosh", "exp", "floor", "fround", "hypot", "imul", "log", "log1p", "log2", "log10", "max", "min", "pow", "random", "round", "sign", "sin", "sinh", "sqrt", "tan", "tanh", "trunc", "E", "LN10", "LN2", "LOG10E", "LOG2E", "PI", "SQRT1_2", "SQRT2"]; + var i; + var len = propertyNames.length; + for (i = 0;i < len; i += 1) { + BMMath[propertyNames[i]] = Math[propertyNames[i]]; + } + })(); + BMMath.random = Math.random; + BMMath.abs = function(val2) { + var tOfVal = typeof val2; + if (tOfVal === "object" && val2.length) { + var absArr = createSizedArray(val2.length); + var i; + var len = val2.length; + for (i = 0;i < len; i += 1) { + absArr[i] = Math.abs(val2[i]); + } + return absArr; + } + return Math.abs(val2); + }; + let defaultCurveSegments = 150; + const degToRads = Math.PI / 180; + const roundCorner = 0.5519; + const createElementID = function() { + var _count = 0; + return function createID() { + _count += 1; + return idPrefix$1 + "__lottie_element_" + _count; + }; + }(); + const rgbToHex = function() { + var colorMap = []; + var i; + var hex; + for (i = 0;i < 256; i += 1) { + hex = i.toString(16); + colorMap[i] = hex.length === 1 ? "0" + hex : hex; + } + return function(r, g3, b) { + if (r < 0) { + r = 0; + } + if (g3 < 0) { + g3 = 0; + } + if (b < 0) { + b = 0; + } + return "#" + colorMap[r] + colorMap[g3] + colorMap[b]; + }; + }(); + const setSubframeEnabled = (flag) => { + subframeEnabled = !!flag; + }; + const getSubframeEnabled = () => subframeEnabled; + const setExpressionsPlugin = (value2) => { + expressionsPlugin = value2; + }; + const getExpressionsPlugin = () => expressionsPlugin; + const setDefaultCurveSegments = (value2) => { + defaultCurveSegments = value2; + }; + const getDefaultCurveSegments = () => defaultCurveSegments; + const setIdPrefix = (value2) => { + idPrefix$1 = value2; + }; + const getIdPrefix = () => idPrefix$1; + const dataManager = function() { + var _counterId = 1; + var processes = []; + var workerFn; + var workerInstance; + var workerProxy = { + onmessage: function() { + }, + postMessage: function(path) { + workerFn({ + data: path + }); + } + }; + var _workerSelf = { + postMessage: function(data2) { + workerProxy.onmessage({ + data: data2 + }); + } + }; + function createWorker(fn) { + if (window.Worker && window.Blob && getWebWorker()) { + var blob = new Blob(["var _workerSelf = self; self.onmessage = ", fn.toString()], { type: "text/javascript" }); + var url = URL.createObjectURL(blob); + return new Worker(url); + } + workerFn = fn; + return workerProxy; + } + function setupWorker() { + if (!workerInstance) { + workerInstance = createWorker(function workerStart(e) { + function dataFunctionManager() { + function completeLayers(layers, comps) { + var layerData; + var i; + var len = layers.length; + var j2; + var jLen; + var k2; + var kLen; + for (i = 0;i < len; i += 1) { + layerData = layers[i]; + if ("ks" in layerData && !layerData.completed) { + layerData.completed = true; + if (layerData.tt) { + layers[i - 1].td = layerData.tt; + } + if (layerData.hasMask) { + var maskProps = layerData.masksProperties; + jLen = maskProps.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (maskProps[j2].pt.k.i) { + convertPathsToAbsoluteValues(maskProps[j2].pt.k); + } else { + kLen = maskProps[j2].pt.k.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + if (maskProps[j2].pt.k[k2].s) { + convertPathsToAbsoluteValues(maskProps[j2].pt.k[k2].s[0]); + } + if (maskProps[j2].pt.k[k2].e) { + convertPathsToAbsoluteValues(maskProps[j2].pt.k[k2].e[0]); + } + } + } + } + } + if (layerData.ty === 0) { + layerData.layers = findCompLayers(layerData.refId, comps); + completeLayers(layerData.layers, comps); + } else if (layerData.ty === 4) { + completeShapes(layerData.shapes); + } else if (layerData.ty === 5) { + completeText(layerData); + } + } + } + } + function completeChars(chars, assets) { + if (chars) { + var i = 0; + var len = chars.length; + for (i = 0;i < len; i += 1) { + if (chars[i].t === 1) { + chars[i].data.layers = findCompLayers(chars[i].data.refId, assets); + completeLayers(chars[i].data.layers, assets); + } + } + } + } + function findComp(id, comps) { + var i = 0; + var len = comps.length; + while (i < len) { + if (comps[i].id === id) { + return comps[i]; + } + i += 1; + } + return null; + } + function findCompLayers(id, comps) { + var comp2 = findComp(id, comps); + if (comp2) { + if (!comp2.layers.__used) { + comp2.layers.__used = true; + return comp2.layers; + } + return JSON.parse(JSON.stringify(comp2.layers)); + } + return null; + } + function completeShapes(arr) { + var i; + var len = arr.length; + var j2; + var jLen; + for (i = len - 1;i >= 0; i -= 1) { + if (arr[i].ty === "sh") { + if (arr[i].ks.k.i) { + convertPathsToAbsoluteValues(arr[i].ks.k); + } else { + jLen = arr[i].ks.k.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (arr[i].ks.k[j2].s) { + convertPathsToAbsoluteValues(arr[i].ks.k[j2].s[0]); + } + if (arr[i].ks.k[j2].e) { + convertPathsToAbsoluteValues(arr[i].ks.k[j2].e[0]); + } + } + } + } else if (arr[i].ty === "gr") { + completeShapes(arr[i].it); + } + } + } + function convertPathsToAbsoluteValues(path) { + var i; + var len = path.i.length; + for (i = 0;i < len; i += 1) { + path.i[i][0] += path.v[i][0]; + path.i[i][1] += path.v[i][1]; + path.o[i][0] += path.v[i][0]; + path.o[i][1] += path.v[i][1]; + } + } + function checkVersion(minimum, animVersionString) { + var animVersion = animVersionString ? animVersionString.split(".") : [100, 100, 100]; + if (minimum[0] > animVersion[0]) { + return true; + } + if (animVersion[0] > minimum[0]) { + return false; + } + if (minimum[1] > animVersion[1]) { + return true; + } + if (animVersion[1] > minimum[1]) { + return false; + } + if (minimum[2] > animVersion[2]) { + return true; + } + if (animVersion[2] > minimum[2]) { + return false; + } + return null; + } + var checkText = function() { + var minimumVersion = [4, 4, 14]; + function updateTextLayer(textLayer) { + var documentData = textLayer.t.d; + textLayer.t.d = { + k: [ + { + s: documentData, + t: 0 + } + ] + }; + } + function iterateLayers(layers) { + var i; + var len = layers.length; + for (i = 0;i < len; i += 1) { + if (layers[i].ty === 5) { + updateTextLayer(layers[i]); + } + } + } + return function(animationData2) { + if (checkVersion(minimumVersion, animationData2.v)) { + iterateLayers(animationData2.layers); + if (animationData2.assets) { + var i; + var len = animationData2.assets.length; + for (i = 0;i < len; i += 1) { + if (animationData2.assets[i].layers) { + iterateLayers(animationData2.assets[i].layers); + } + } + } + } + }; + }(); + var checkChars = function() { + var minimumVersion = [4, 7, 99]; + return function(animationData2) { + if (animationData2.chars && !checkVersion(minimumVersion, animationData2.v)) { + var i; + var len = animationData2.chars.length; + for (i = 0;i < len; i += 1) { + var charData = animationData2.chars[i]; + if (charData.data && charData.data.shapes) { + completeShapes(charData.data.shapes); + charData.data.ip = 0; + charData.data.op = 99999; + charData.data.st = 0; + charData.data.sr = 1; + charData.data.ks = { + p: { k: [0, 0], a: 0 }, + s: { k: [100, 100], a: 0 }, + a: { k: [0, 0], a: 0 }, + r: { k: 0, a: 0 }, + o: { k: 100, a: 0 } + }; + if (!animationData2.chars[i].t) { + charData.data.shapes.push({ + ty: "no" + }); + charData.data.shapes[0].it.push({ + p: { k: [0, 0], a: 0 }, + s: { k: [100, 100], a: 0 }, + a: { k: [0, 0], a: 0 }, + r: { k: 0, a: 0 }, + o: { k: 100, a: 0 }, + sk: { k: 0, a: 0 }, + sa: { k: 0, a: 0 }, + ty: "tr" + }); + } + } + } + } + }; + }(); + var checkPathProperties = function() { + var minimumVersion = [5, 7, 15]; + function updateTextLayer(textLayer) { + var pathData = textLayer.t.p; + if (typeof pathData.a === "number") { + pathData.a = { + a: 0, + k: pathData.a + }; + } + if (typeof pathData.p === "number") { + pathData.p = { + a: 0, + k: pathData.p + }; + } + if (typeof pathData.r === "number") { + pathData.r = { + a: 0, + k: pathData.r + }; + } + } + function iterateLayers(layers) { + var i; + var len = layers.length; + for (i = 0;i < len; i += 1) { + if (layers[i].ty === 5) { + updateTextLayer(layers[i]); + } + } + } + return function(animationData2) { + if (checkVersion(minimumVersion, animationData2.v)) { + iterateLayers(animationData2.layers); + if (animationData2.assets) { + var i; + var len = animationData2.assets.length; + for (i = 0;i < len; i += 1) { + if (animationData2.assets[i].layers) { + iterateLayers(animationData2.assets[i].layers); + } + } + } + } + }; + }(); + var checkColors = function() { + var minimumVersion = [4, 1, 9]; + function iterateShapes(shapes) { + var i; + var len = shapes.length; + var j2; + var jLen; + for (i = 0;i < len; i += 1) { + if (shapes[i].ty === "gr") { + iterateShapes(shapes[i].it); + } else if (shapes[i].ty === "fl" || shapes[i].ty === "st") { + if (shapes[i].c.k && shapes[i].c.k[0].i) { + jLen = shapes[i].c.k.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (shapes[i].c.k[j2].s) { + shapes[i].c.k[j2].s[0] /= 255; + shapes[i].c.k[j2].s[1] /= 255; + shapes[i].c.k[j2].s[2] /= 255; + shapes[i].c.k[j2].s[3] /= 255; + } + if (shapes[i].c.k[j2].e) { + shapes[i].c.k[j2].e[0] /= 255; + shapes[i].c.k[j2].e[1] /= 255; + shapes[i].c.k[j2].e[2] /= 255; + shapes[i].c.k[j2].e[3] /= 255; + } + } + } else { + shapes[i].c.k[0] /= 255; + shapes[i].c.k[1] /= 255; + shapes[i].c.k[2] /= 255; + shapes[i].c.k[3] /= 255; + } + } + } + } + function iterateLayers(layers) { + var i; + var len = layers.length; + for (i = 0;i < len; i += 1) { + if (layers[i].ty === 4) { + iterateShapes(layers[i].shapes); + } + } + } + return function(animationData2) { + if (checkVersion(minimumVersion, animationData2.v)) { + iterateLayers(animationData2.layers); + if (animationData2.assets) { + var i; + var len = animationData2.assets.length; + for (i = 0;i < len; i += 1) { + if (animationData2.assets[i].layers) { + iterateLayers(animationData2.assets[i].layers); + } + } + } + } + }; + }(); + var checkShapes = function() { + var minimumVersion = [4, 4, 18]; + function completeClosingShapes(arr) { + var i; + var len = arr.length; + var j2; + var jLen; + for (i = len - 1;i >= 0; i -= 1) { + if (arr[i].ty === "sh") { + if (arr[i].ks.k.i) { + arr[i].ks.k.c = arr[i].closed; + } else { + jLen = arr[i].ks.k.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (arr[i].ks.k[j2].s) { + arr[i].ks.k[j2].s[0].c = arr[i].closed; + } + if (arr[i].ks.k[j2].e) { + arr[i].ks.k[j2].e[0].c = arr[i].closed; + } + } + } + } else if (arr[i].ty === "gr") { + completeClosingShapes(arr[i].it); + } + } + } + function iterateLayers(layers) { + var layerData; + var i; + var len = layers.length; + var j2; + var jLen; + var k2; + var kLen; + for (i = 0;i < len; i += 1) { + layerData = layers[i]; + if (layerData.hasMask) { + var maskProps = layerData.masksProperties; + jLen = maskProps.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (maskProps[j2].pt.k.i) { + maskProps[j2].pt.k.c = maskProps[j2].cl; + } else { + kLen = maskProps[j2].pt.k.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + if (maskProps[j2].pt.k[k2].s) { + maskProps[j2].pt.k[k2].s[0].c = maskProps[j2].cl; + } + if (maskProps[j2].pt.k[k2].e) { + maskProps[j2].pt.k[k2].e[0].c = maskProps[j2].cl; + } + } + } + } + } + if (layerData.ty === 4) { + completeClosingShapes(layerData.shapes); + } + } + } + return function(animationData2) { + if (checkVersion(minimumVersion, animationData2.v)) { + iterateLayers(animationData2.layers); + if (animationData2.assets) { + var i; + var len = animationData2.assets.length; + for (i = 0;i < len; i += 1) { + if (animationData2.assets[i].layers) { + iterateLayers(animationData2.assets[i].layers); + } + } + } + } + }; + }(); + function completeData(animationData2) { + if (animationData2.__complete) { + return; + } + checkColors(animationData2); + checkText(animationData2); + checkChars(animationData2); + checkPathProperties(animationData2); + checkShapes(animationData2); + completeLayers(animationData2.layers, animationData2.assets); + completeChars(animationData2.chars, animationData2.assets); + animationData2.__complete = true; + } + function completeText(data2) { + if (data2.t.a.length === 0 && !("m" in data2.t.p)) { + } + } + var moduleOb = {}; + moduleOb.completeData = completeData; + moduleOb.checkColors = checkColors; + moduleOb.checkChars = checkChars; + moduleOb.checkPathProperties = checkPathProperties; + moduleOb.checkShapes = checkShapes; + moduleOb.completeLayers = completeLayers; + return moduleOb; + } + if (!_workerSelf.dataManager) { + _workerSelf.dataManager = dataFunctionManager(); + } + if (!_workerSelf.assetLoader) { + _workerSelf.assetLoader = function() { + function formatResponse(xhr) { + var contentTypeHeader = xhr.getResponseHeader("content-type"); + if (contentTypeHeader && xhr.responseType === "json" && contentTypeHeader.indexOf("json") !== -1) { + return xhr.response; + } + if (xhr.response && typeof xhr.response === "object") { + return xhr.response; + } + if (xhr.response && typeof xhr.response === "string") { + return JSON.parse(xhr.response); + } + if (xhr.responseText) { + return JSON.parse(xhr.responseText); + } + return null; + } + function loadAsset(path, fullPath, callback, errorCallback) { + var response; + var xhr = new XMLHttpRequest; + try { + xhr.responseType = "json"; + } catch (err) { + } + xhr.onreadystatechange = function() { + if (xhr.readyState === 4) { + if (xhr.status === 200) { + response = formatResponse(xhr); + callback(response); + } else { + try { + response = formatResponse(xhr); + callback(response); + } catch (err) { + if (errorCallback) { + errorCallback(err); + } + } + } + } + }; + try { + xhr.open("GET", path, true); + } catch (error) { + xhr.open("GET", fullPath + "/" + path, true); + } + xhr.send(); + } + return { + load: loadAsset + }; + }(); + } + if (e.data.type === "loadAnimation") { + _workerSelf.assetLoader.load(e.data.path, e.data.fullPath, function(data2) { + _workerSelf.dataManager.completeData(data2); + _workerSelf.postMessage({ + id: e.data.id, + payload: data2, + status: "success" + }); + }, function() { + _workerSelf.postMessage({ + id: e.data.id, + status: "error" + }); + }); + } else if (e.data.type === "complete") { + var animation = e.data.animation; + _workerSelf.dataManager.completeData(animation); + _workerSelf.postMessage({ + id: e.data.id, + payload: animation, + status: "success" + }); + } else if (e.data.type === "loadData") { + _workerSelf.assetLoader.load(e.data.path, e.data.fullPath, function(data2) { + _workerSelf.postMessage({ + id: e.data.id, + payload: data2, + status: "success" + }); + }, function() { + _workerSelf.postMessage({ + id: e.data.id, + status: "error" + }); + }); + } + }); + workerInstance.onmessage = function(event) { + var data2 = event.data; + var id = data2.id; + var process2 = processes[id]; + processes[id] = null; + if (data2.status === "success") { + process2.onComplete(data2.payload); + } else if (process2.onError) { + process2.onError(); + } + }; + } + } + function createProcess(onComplete, onError) { + _counterId += 1; + var id = "processId_" + _counterId; + processes[id] = { + onComplete, + onError + }; + return id; + } + function loadAnimation2(path, onComplete, onError) { + setupWorker(); + var processId = createProcess(onComplete, onError); + workerInstance.postMessage({ + type: "loadAnimation", + path, + fullPath: window.location.origin + window.location.pathname, + id: processId + }); + } + function loadData(path, onComplete, onError) { + setupWorker(); + var processId = createProcess(onComplete, onError); + workerInstance.postMessage({ + type: "loadData", + path, + fullPath: window.location.origin + window.location.pathname, + id: processId + }); + } + function completeAnimation(anim, onComplete, onError) { + setupWorker(); + var processId = createProcess(onComplete, onError); + workerInstance.postMessage({ + type: "complete", + animation: anim, + id: processId + }); + } + return { + loadAnimation: loadAnimation2, + loadData, + completeAnimation + }; + }(); + const ImagePreloader = function() { + var proxyImage = function() { + var canvas = createTag("canvas"); + canvas.width = 1; + canvas.height = 1; + var ctx = canvas.getContext("2d"); + ctx.fillStyle = "rgba(0,0,0,0)"; + ctx.fillRect(0, 0, 1, 1); + return canvas; + }(); + function imageLoaded() { + this.loadedAssets += 1; + if (this.loadedAssets === this.totalImages && this.loadedFootagesCount === this.totalFootages) { + if (this.imagesLoadedCb) { + this.imagesLoadedCb(null); + } + } + } + function footageLoaded() { + this.loadedFootagesCount += 1; + if (this.loadedAssets === this.totalImages && this.loadedFootagesCount === this.totalFootages) { + if (this.imagesLoadedCb) { + this.imagesLoadedCb(null); + } + } + } + function getAssetsPath(assetData, assetsPath, originalPath) { + var path = ""; + if (assetData.e) { + path = assetData.p; + } else if (assetsPath) { + var imagePath = assetData.p; + if (imagePath.indexOf("images/") !== -1) { + imagePath = imagePath.split("/")[1]; + } + path = assetsPath + imagePath; + } else { + path = originalPath; + path += assetData.u ? assetData.u : ""; + path += assetData.p; + } + return path; + } + function testImageLoaded(img) { + var _count = 0; + var intervalId = setInterval(function() { + var box = img.getBBox(); + if (box.width || _count > 500) { + this._imageLoaded(); + clearInterval(intervalId); + } + _count += 1; + }.bind(this), 50); + } + function createImageData(assetData) { + var path = getAssetsPath(assetData, this.assetsPath, this.path); + var img = createNS("image"); + if (isSafari) { + this.testImageLoaded(img); + } else { + img.addEventListener("load", this._imageLoaded, false); + } + img.addEventListener("error", function() { + ob2.img = proxyImage; + this._imageLoaded(); + }.bind(this), false); + img.setAttributeNS("http://www.w3.org/1999/xlink", "href", path); + if (this._elementHelper.append) { + this._elementHelper.append(img); + } else { + this._elementHelper.appendChild(img); + } + var ob2 = { + img, + assetData + }; + return ob2; + } + function createImgData(assetData) { + var path = getAssetsPath(assetData, this.assetsPath, this.path); + var img = createTag("img"); + img.crossOrigin = "anonymous"; + img.addEventListener("load", this._imageLoaded, false); + img.addEventListener("error", function() { + ob2.img = proxyImage; + this._imageLoaded(); + }.bind(this), false); + img.src = path; + var ob2 = { + img, + assetData + }; + return ob2; + } + function createFootageData(data2) { + var ob2 = { + assetData: data2 + }; + var path = getAssetsPath(data2, this.assetsPath, this.path); + dataManager.loadData(path, function(footageData) { + ob2.img = footageData; + this._footageLoaded(); + }.bind(this), function() { + ob2.img = {}; + this._footageLoaded(); + }.bind(this)); + return ob2; + } + function loadAssets(assets, cb) { + this.imagesLoadedCb = cb; + var i; + var len = assets.length; + for (i = 0;i < len; i += 1) { + if (!assets[i].layers) { + if (!assets[i].t || assets[i].t === "seq") { + this.totalImages += 1; + this.images.push(this._createImageData(assets[i])); + } else if (assets[i].t === 3) { + this.totalFootages += 1; + this.images.push(this.createFootageData(assets[i])); + } + } + } + } + function setPath(path) { + this.path = path || ""; + } + function setAssetsPath(path) { + this.assetsPath = path || ""; + } + function getAsset(assetData) { + var i = 0; + var len = this.images.length; + while (i < len) { + if (this.images[i].assetData === assetData) { + return this.images[i].img; + } + i += 1; + } + return null; + } + function destroy() { + this.imagesLoadedCb = null; + this.images.length = 0; + } + function loadedImages() { + return this.totalImages === this.loadedAssets; + } + function loadedFootages() { + return this.totalFootages === this.loadedFootagesCount; + } + function setCacheType(type, elementHelper) { + if (type === "svg") { + this._elementHelper = elementHelper; + this._createImageData = this.createImageData.bind(this); + } else { + this._createImageData = this.createImgData.bind(this); + } + } + function ImagePreloaderFactory() { + this._imageLoaded = imageLoaded.bind(this); + this._footageLoaded = footageLoaded.bind(this); + this.testImageLoaded = testImageLoaded.bind(this); + this.createFootageData = createFootageData.bind(this); + this.assetsPath = ""; + this.path = ""; + this.totalImages = 0; + this.totalFootages = 0; + this.loadedAssets = 0; + this.loadedFootagesCount = 0; + this.imagesLoadedCb = null; + this.images = []; + } + ImagePreloaderFactory.prototype = { + loadAssets, + setAssetsPath, + setPath, + loadedImages, + loadedFootages, + destroy, + getAsset, + createImgData, + createImageData, + imageLoaded, + footageLoaded, + setCacheType + }; + return ImagePreloaderFactory; + }(); + BaseEvent.prototype = { + triggerEvent: function(eventName, args) { + if (this._cbs[eventName]) { + var callbacks = this._cbs[eventName]; + for (var i = 0;i < callbacks.length; i += 1) { + callbacks[i](args); + } + } + }, + addEventListener: function(eventName, callback) { + if (!this._cbs[eventName]) { + this._cbs[eventName] = []; + } + this._cbs[eventName].push(callback); + return function() { + this.removeEventListener(eventName, callback); + }.bind(this); + }, + removeEventListener: function(eventName, callback) { + if (!callback) { + this._cbs[eventName] = null; + } else if (this._cbs[eventName]) { + var i = 0; + var len = this._cbs[eventName].length; + while (i < len) { + if (this._cbs[eventName][i] === callback) { + this._cbs[eventName].splice(i, 1); + i -= 1; + len -= 1; + } + i += 1; + } + if (!this._cbs[eventName].length) { + this._cbs[eventName] = null; + } + } + } + }; + const markerParser = function() { + function parsePayloadLines(payload) { + var lines = payload.split(`\r +`); + var keys2 = {}; + var line; + var keysCount = 0; + for (var i = 0;i < lines.length; i += 1) { + line = lines[i].split(":"); + if (line.length === 2) { + keys2[line[0]] = line[1].trim(); + keysCount += 1; + } + } + if (keysCount === 0) { + throw new Error; + } + return keys2; + } + return function(_markers) { + var markers = []; + for (var i = 0;i < _markers.length; i += 1) { + var _marker = _markers[i]; + var markerData = { + time: _marker.tm, + duration: _marker.dr + }; + try { + markerData.payload = JSON.parse(_markers[i].cm); + } catch (_9) { + try { + markerData.payload = parsePayloadLines(_markers[i].cm); + } catch (__3) { + markerData.payload = { + name: _markers[i].cm + }; + } + } + markers.push(markerData); + } + return markers; + }; + }(); + const ProjectInterface = function() { + function registerComposition(comp2) { + this.compositions.push(comp2); + } + return function() { + function _thisProjectFunction(name2) { + var i = 0; + var len = this.compositions.length; + while (i < len) { + if (this.compositions[i].data && this.compositions[i].data.nm === name2) { + if (this.compositions[i].prepareFrame && this.compositions[i].data.xt) { + this.compositions[i].prepareFrame(this.currentFrame); + } + return this.compositions[i].compInterface; + } + i += 1; + } + return null; + } + _thisProjectFunction.compositions = []; + _thisProjectFunction.currentFrame = 0; + _thisProjectFunction.registerComposition = registerComposition; + return _thisProjectFunction; + }; + }(); + const renderers = {}; + const registerRenderer = (key2, value2) => { + renderers[key2] = value2; + }; + const AnimationItem = function() { + this._cbs = []; + this.name = ""; + this.path = ""; + this.isLoaded = false; + this.currentFrame = 0; + this.currentRawFrame = 0; + this.firstFrame = 0; + this.totalFrames = 0; + this.frameRate = 0; + this.frameMult = 0; + this.playSpeed = 1; + this.playDirection = 1; + this.playCount = 0; + this.animationData = {}; + this.assets = []; + this.isPaused = true; + this.autoplay = false; + this.loop = true; + this.renderer = null; + this.animationID = createElementID(); + this.assetsPath = ""; + this.timeCompleted = 0; + this.segmentPos = 0; + this.isSubframeEnabled = getSubframeEnabled(); + this.segments = []; + this._idle = true; + this._completedLoop = false; + this.projectInterface = ProjectInterface(); + this.imagePreloader = new ImagePreloader; + this.audioController = audioControllerFactory(); + this.markers = []; + this.configAnimation = this.configAnimation.bind(this); + this.onSetupError = this.onSetupError.bind(this); + this.onSegmentComplete = this.onSegmentComplete.bind(this); + this.drawnFrameEvent = new BMEnterFrameEvent("drawnFrame", 0, 0, 0); + }; + extendPrototype([BaseEvent], AnimationItem); + AnimationItem.prototype.setParams = function(params) { + if (params.wrapper || params.container) { + this.wrapper = params.wrapper || params.container; + } + var animType = "svg"; + if (params.animType) { + animType = params.animType; + } else if (params.renderer) { + animType = params.renderer; + } + const RendererClass = getRenderer(animType); + this.renderer = new RendererClass(this, params.rendererSettings); + this.imagePreloader.setCacheType(animType, this.renderer.globalData.defs); + this.renderer.setProjectInterface(this.projectInterface); + this.animType = animType; + if (params.loop === "" || params.loop === null || params.loop === undefined || params.loop === true) { + this.loop = true; + } else if (params.loop === false) { + this.loop = false; + } else { + this.loop = parseInt(params.loop, 10); + } + this.autoplay = "autoplay" in params ? params.autoplay : true; + this.name = params.name ? params.name : ""; + this.autoloadSegments = Object.prototype.hasOwnProperty.call(params, "autoloadSegments") ? params.autoloadSegments : true; + this.assetsPath = params.assetsPath; + this.initialSegment = params.initialSegment; + if (params.audioFactory) { + this.audioController.setAudioFactory(params.audioFactory); + } + if (params.animationData) { + this.setupAnimation(params.animationData); + } else if (params.path) { + if (params.path.lastIndexOf("\\") !== -1) { + this.path = params.path.substr(0, params.path.lastIndexOf("\\") + 1); + } else { + this.path = params.path.substr(0, params.path.lastIndexOf("/") + 1); + } + this.fileName = params.path.substr(params.path.lastIndexOf("/") + 1); + this.fileName = this.fileName.substr(0, this.fileName.lastIndexOf(".json")); + dataManager.loadAnimation(params.path, this.configAnimation, this.onSetupError); + } + }; + AnimationItem.prototype.onSetupError = function() { + this.trigger("data_failed"); + }; + AnimationItem.prototype.setupAnimation = function(data2) { + dataManager.completeAnimation(data2, this.configAnimation); + }; + AnimationItem.prototype.setData = function(wrapper, animationData2) { + if (animationData2) { + if (typeof animationData2 !== "object") { + animationData2 = JSON.parse(animationData2); + } + } + var params = { + wrapper, + animationData: animationData2 + }; + var wrapperAttributes = wrapper.attributes; + params.path = wrapperAttributes.getNamedItem("data-animation-path") ? wrapperAttributes.getNamedItem("data-animation-path").value : wrapperAttributes.getNamedItem("data-bm-path") ? wrapperAttributes.getNamedItem("data-bm-path").value : wrapperAttributes.getNamedItem("bm-path") ? wrapperAttributes.getNamedItem("bm-path").value : ""; + params.animType = wrapperAttributes.getNamedItem("data-anim-type") ? wrapperAttributes.getNamedItem("data-anim-type").value : wrapperAttributes.getNamedItem("data-bm-type") ? wrapperAttributes.getNamedItem("data-bm-type").value : wrapperAttributes.getNamedItem("bm-type") ? wrapperAttributes.getNamedItem("bm-type").value : wrapperAttributes.getNamedItem("data-bm-renderer") ? wrapperAttributes.getNamedItem("data-bm-renderer").value : wrapperAttributes.getNamedItem("bm-renderer") ? wrapperAttributes.getNamedItem("bm-renderer").value : "canvas"; + var loop = wrapperAttributes.getNamedItem("data-anim-loop") ? wrapperAttributes.getNamedItem("data-anim-loop").value : wrapperAttributes.getNamedItem("data-bm-loop") ? wrapperAttributes.getNamedItem("data-bm-loop").value : wrapperAttributes.getNamedItem("bm-loop") ? wrapperAttributes.getNamedItem("bm-loop").value : ""; + if (loop === "false") { + params.loop = false; + } else if (loop === "true") { + params.loop = true; + } else if (loop !== "") { + params.loop = parseInt(loop, 10); + } + var autoplay = wrapperAttributes.getNamedItem("data-anim-autoplay") ? wrapperAttributes.getNamedItem("data-anim-autoplay").value : wrapperAttributes.getNamedItem("data-bm-autoplay") ? wrapperAttributes.getNamedItem("data-bm-autoplay").value : wrapperAttributes.getNamedItem("bm-autoplay") ? wrapperAttributes.getNamedItem("bm-autoplay").value : true; + params.autoplay = autoplay !== "false"; + params.name = wrapperAttributes.getNamedItem("data-name") ? wrapperAttributes.getNamedItem("data-name").value : wrapperAttributes.getNamedItem("data-bm-name") ? wrapperAttributes.getNamedItem("data-bm-name").value : wrapperAttributes.getNamedItem("bm-name") ? wrapperAttributes.getNamedItem("bm-name").value : ""; + var prerender = wrapperAttributes.getNamedItem("data-anim-prerender") ? wrapperAttributes.getNamedItem("data-anim-prerender").value : wrapperAttributes.getNamedItem("data-bm-prerender") ? wrapperAttributes.getNamedItem("data-bm-prerender").value : wrapperAttributes.getNamedItem("bm-prerender") ? wrapperAttributes.getNamedItem("bm-prerender").value : ""; + if (prerender === "false") { + params.prerender = false; + } + this.setParams(params); + }; + AnimationItem.prototype.includeLayers = function(data2) { + if (data2.op > this.animationData.op) { + this.animationData.op = data2.op; + this.totalFrames = Math.floor(data2.op - this.animationData.ip); + } + var layers = this.animationData.layers; + var i; + var len = layers.length; + var newLayers = data2.layers; + var j2; + var jLen = newLayers.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + i = 0; + while (i < len) { + if (layers[i].id === newLayers[j2].id) { + layers[i] = newLayers[j2]; + break; + } + i += 1; + } + } + if (data2.chars || data2.fonts) { + this.renderer.globalData.fontManager.addChars(data2.chars); + this.renderer.globalData.fontManager.addFonts(data2.fonts, this.renderer.globalData.defs); + } + if (data2.assets) { + len = data2.assets.length; + for (i = 0;i < len; i += 1) { + this.animationData.assets.push(data2.assets[i]); + } + } + this.animationData.__complete = false; + dataManager.completeAnimation(this.animationData, this.onSegmentComplete); + }; + AnimationItem.prototype.onSegmentComplete = function(data2) { + this.animationData = data2; + var expressionsPlugin2 = getExpressionsPlugin(); + if (expressionsPlugin2) { + expressionsPlugin2.initExpressions(this); + } + this.loadNextSegment(); + }; + AnimationItem.prototype.loadNextSegment = function() { + var segments = this.animationData.segments; + if (!segments || segments.length === 0 || !this.autoloadSegments) { + this.trigger("data_ready"); + this.timeCompleted = this.totalFrames; + return; + } + var segment = segments.shift(); + this.timeCompleted = segment.time * this.frameRate; + var segmentPath = this.path + this.fileName + "_" + this.segmentPos + ".json"; + this.segmentPos += 1; + dataManager.loadData(segmentPath, this.includeLayers.bind(this), function() { + this.trigger("data_failed"); + }.bind(this)); + }; + AnimationItem.prototype.loadSegments = function() { + var segments = this.animationData.segments; + if (!segments) { + this.timeCompleted = this.totalFrames; + } + this.loadNextSegment(); + }; + AnimationItem.prototype.imagesLoaded = function() { + this.trigger("loaded_images"); + this.checkLoaded(); + }; + AnimationItem.prototype.preloadImages = function() { + this.imagePreloader.setAssetsPath(this.assetsPath); + this.imagePreloader.setPath(this.path); + this.imagePreloader.loadAssets(this.animationData.assets, this.imagesLoaded.bind(this)); + }; + AnimationItem.prototype.configAnimation = function(animData) { + if (!this.renderer) { + return; + } + try { + this.animationData = animData; + if (this.initialSegment) { + this.totalFrames = Math.floor(this.initialSegment[1] - this.initialSegment[0]); + this.firstFrame = Math.round(this.initialSegment[0]); + } else { + this.totalFrames = Math.floor(this.animationData.op - this.animationData.ip); + this.firstFrame = Math.round(this.animationData.ip); + } + this.renderer.configAnimation(animData); + if (!animData.assets) { + animData.assets = []; + } + this.assets = this.animationData.assets; + this.frameRate = this.animationData.fr; + this.frameMult = this.animationData.fr / 1000; + this.renderer.searchExtraCompositions(animData.assets); + this.markers = markerParser(animData.markers || []); + this.trigger("config_ready"); + this.preloadImages(); + this.loadSegments(); + this.updaFrameModifier(); + this.waitForFontsLoaded(); + if (this.isPaused) { + this.audioController.pause(); + } + } catch (error) { + this.triggerConfigError(error); + } + }; + AnimationItem.prototype.waitForFontsLoaded = function() { + if (!this.renderer) { + return; + } + if (this.renderer.globalData.fontManager.isLoaded) { + this.checkLoaded(); + } else { + setTimeout(this.waitForFontsLoaded.bind(this), 20); + } + }; + AnimationItem.prototype.checkLoaded = function() { + if (!this.isLoaded && this.renderer.globalData.fontManager.isLoaded && (this.imagePreloader.loadedImages() || this.renderer.rendererType !== "canvas") && this.imagePreloader.loadedFootages()) { + this.isLoaded = true; + var expressionsPlugin2 = getExpressionsPlugin(); + if (expressionsPlugin2) { + expressionsPlugin2.initExpressions(this); + } + this.renderer.initItems(); + setTimeout(function() { + this.trigger("DOMLoaded"); + }.bind(this), 0); + this.gotoFrame(); + if (this.autoplay) { + this.play(); + } + } + }; + AnimationItem.prototype.resize = function() { + this.renderer.updateContainerSize(); + }; + AnimationItem.prototype.setSubframe = function(flag) { + this.isSubframeEnabled = !!flag; + }; + AnimationItem.prototype.gotoFrame = function() { + this.currentFrame = this.isSubframeEnabled ? this.currentRawFrame : ~~this.currentRawFrame; + if (this.timeCompleted !== this.totalFrames && this.currentFrame > this.timeCompleted) { + this.currentFrame = this.timeCompleted; + } + this.trigger("enterFrame"); + this.renderFrame(); + this.trigger("drawnFrame"); + }; + AnimationItem.prototype.renderFrame = function() { + if (this.isLoaded === false || !this.renderer) { + return; + } + try { + this.renderer.renderFrame(this.currentFrame + this.firstFrame); + } catch (error) { + this.triggerRenderFrameError(error); + } + }; + AnimationItem.prototype.play = function(name2) { + if (name2 && this.name !== name2) { + return; + } + if (this.isPaused === true) { + this.isPaused = false; + this.trigger("_pause"); + this.audioController.resume(); + if (this._idle) { + this._idle = false; + this.trigger("_active"); + } + } + }; + AnimationItem.prototype.pause = function(name2) { + if (name2 && this.name !== name2) { + return; + } + if (this.isPaused === false) { + this.isPaused = true; + this.trigger("_play"); + this._idle = true; + this.trigger("_idle"); + this.audioController.pause(); + } + }; + AnimationItem.prototype.togglePause = function(name2) { + if (name2 && this.name !== name2) { + return; + } + if (this.isPaused === true) { + this.play(); + } else { + this.pause(); + } + }; + AnimationItem.prototype.stop = function(name2) { + if (name2 && this.name !== name2) { + return; + } + this.pause(); + this.playCount = 0; + this._completedLoop = false; + this.setCurrentRawFrameValue(0); + }; + AnimationItem.prototype.getMarkerData = function(markerName) { + var marker; + for (var i = 0;i < this.markers.length; i += 1) { + marker = this.markers[i]; + if (marker.payload && marker.payload.name === markerName) { + return marker; + } + } + return null; + }; + AnimationItem.prototype.goToAndStop = function(value2, isFrame, name2) { + if (name2 && this.name !== name2) { + return; + } + var numValue = Number(value2); + if (isNaN(numValue)) { + var marker = this.getMarkerData(value2); + if (marker) { + this.goToAndStop(marker.time, true); + } + } else if (isFrame) { + this.setCurrentRawFrameValue(value2); + } else { + this.setCurrentRawFrameValue(value2 * this.frameModifier); + } + this.pause(); + }; + AnimationItem.prototype.goToAndPlay = function(value2, isFrame, name2) { + if (name2 && this.name !== name2) { + return; + } + var numValue = Number(value2); + if (isNaN(numValue)) { + var marker = this.getMarkerData(value2); + if (marker) { + if (!marker.duration) { + this.goToAndStop(marker.time, true); + } else { + this.playSegments([marker.time, marker.time + marker.duration], true); + } + } + } else { + this.goToAndStop(numValue, isFrame, name2); + } + this.play(); + }; + AnimationItem.prototype.advanceTime = function(value2) { + if (this.isPaused === true || this.isLoaded === false) { + return; + } + var nextValue = this.currentRawFrame + value2 * this.frameModifier; + var _isComplete = false; + if (nextValue >= this.totalFrames - 1 && this.frameModifier > 0) { + if (!this.loop || this.playCount === this.loop) { + if (!this.checkSegments(nextValue > this.totalFrames ? nextValue % this.totalFrames : 0)) { + _isComplete = true; + nextValue = this.totalFrames - 1; + } + } else if (nextValue >= this.totalFrames) { + this.playCount += 1; + if (!this.checkSegments(nextValue % this.totalFrames)) { + this.setCurrentRawFrameValue(nextValue % this.totalFrames); + this._completedLoop = true; + this.trigger("loopComplete"); + } + } else { + this.setCurrentRawFrameValue(nextValue); + } + } else if (nextValue < 0) { + if (!this.checkSegments(nextValue % this.totalFrames)) { + if (this.loop && !(this.playCount-- <= 0 && this.loop !== true)) { + this.setCurrentRawFrameValue(this.totalFrames + nextValue % this.totalFrames); + if (!this._completedLoop) { + this._completedLoop = true; + } else { + this.trigger("loopComplete"); + } + } else { + _isComplete = true; + nextValue = 0; + } + } + } else { + this.setCurrentRawFrameValue(nextValue); + } + if (_isComplete) { + this.setCurrentRawFrameValue(nextValue); + this.pause(); + this.trigger("complete"); + } + }; + AnimationItem.prototype.adjustSegment = function(arr, offset) { + this.playCount = 0; + if (arr[1] < arr[0]) { + if (this.frameModifier > 0) { + if (this.playSpeed < 0) { + this.setSpeed(-this.playSpeed); + } else { + this.setDirection(-1); + } + } + this.totalFrames = arr[0] - arr[1]; + this.timeCompleted = this.totalFrames; + this.firstFrame = arr[1]; + this.setCurrentRawFrameValue(this.totalFrames - 0.001 - offset); + } else if (arr[1] > arr[0]) { + if (this.frameModifier < 0) { + if (this.playSpeed < 0) { + this.setSpeed(-this.playSpeed); + } else { + this.setDirection(1); + } + } + this.totalFrames = arr[1] - arr[0]; + this.timeCompleted = this.totalFrames; + this.firstFrame = arr[0]; + this.setCurrentRawFrameValue(0.001 + offset); + } + this.trigger("segmentStart"); + }; + AnimationItem.prototype.setSegment = function(init, end) { + var pendingFrame = -1; + if (this.isPaused) { + if (this.currentRawFrame + this.firstFrame < init) { + pendingFrame = init; + } else if (this.currentRawFrame + this.firstFrame > end) { + pendingFrame = end - init; + } + } + this.firstFrame = init; + this.totalFrames = end - init; + this.timeCompleted = this.totalFrames; + if (pendingFrame !== -1) { + this.goToAndStop(pendingFrame, true); + } + }; + AnimationItem.prototype.playSegments = function(arr, forceFlag) { + if (forceFlag) { + this.segments.length = 0; + } + if (typeof arr[0] === "object") { + var i; + var len = arr.length; + for (i = 0;i < len; i += 1) { + this.segments.push(arr[i]); + } + } else { + this.segments.push(arr); + } + if (this.segments.length && forceFlag) { + this.adjustSegment(this.segments.shift(), 0); + } + if (this.isPaused) { + this.play(); + } + }; + AnimationItem.prototype.resetSegments = function(forceFlag) { + this.segments.length = 0; + this.segments.push([this.animationData.ip, this.animationData.op]); + if (forceFlag) { + this.checkSegments(0); + } + }; + AnimationItem.prototype.checkSegments = function(offset) { + if (this.segments.length) { + this.adjustSegment(this.segments.shift(), offset); + return true; + } + return false; + }; + AnimationItem.prototype.destroy = function(name2) { + if (name2 && this.name !== name2 || !this.renderer) { + return; + } + this.renderer.destroy(); + this.imagePreloader.destroy(); + this.trigger("destroy"); + this._cbs = null; + this.onEnterFrame = null; + this.onLoopComplete = null; + this.onComplete = null; + this.onSegmentStart = null; + this.onDestroy = null; + this.renderer = null; + this.renderer = null; + this.imagePreloader = null; + this.projectInterface = null; + }; + AnimationItem.prototype.setCurrentRawFrameValue = function(value2) { + this.currentRawFrame = value2; + this.gotoFrame(); + }; + AnimationItem.prototype.setSpeed = function(val2) { + this.playSpeed = val2; + this.updaFrameModifier(); + }; + AnimationItem.prototype.setDirection = function(val2) { + this.playDirection = val2 < 0 ? -1 : 1; + this.updaFrameModifier(); + }; + AnimationItem.prototype.setVolume = function(val2, name2) { + if (name2 && this.name !== name2) { + return; + } + this.audioController.setVolume(val2); + }; + AnimationItem.prototype.getVolume = function() { + return this.audioController.getVolume(); + }; + AnimationItem.prototype.mute = function(name2) { + if (name2 && this.name !== name2) { + return; + } + this.audioController.mute(); + }; + AnimationItem.prototype.unmute = function(name2) { + if (name2 && this.name !== name2) { + return; + } + this.audioController.unmute(); + }; + AnimationItem.prototype.updaFrameModifier = function() { + this.frameModifier = this.frameMult * this.playSpeed * this.playDirection; + this.audioController.setRate(this.playSpeed * this.playDirection); + }; + AnimationItem.prototype.getPath = function() { + return this.path; + }; + AnimationItem.prototype.getAssetsPath = function(assetData) { + var path = ""; + if (assetData.e) { + path = assetData.p; + } else if (this.assetsPath) { + var imagePath = assetData.p; + if (imagePath.indexOf("images/") !== -1) { + imagePath = imagePath.split("/")[1]; + } + path = this.assetsPath + imagePath; + } else { + path = this.path; + path += assetData.u ? assetData.u : ""; + path += assetData.p; + } + return path; + }; + AnimationItem.prototype.getAssetData = function(id) { + var i = 0; + var len = this.assets.length; + while (i < len) { + if (id === this.assets[i].id) { + return this.assets[i]; + } + i += 1; + } + return null; + }; + AnimationItem.prototype.hide = function() { + this.renderer.hide(); + }; + AnimationItem.prototype.show = function() { + this.renderer.show(); + }; + AnimationItem.prototype.getDuration = function(isFrame) { + return isFrame ? this.totalFrames : this.totalFrames / this.frameRate; + }; + AnimationItem.prototype.updateDocumentData = function(path, documentData, index2) { + try { + var element = this.renderer.getElementByPath(path); + element.updateDocumentData(documentData, index2); + } catch (error) { + } + }; + AnimationItem.prototype.trigger = function(name2) { + if (this._cbs && this._cbs[name2]) { + switch (name2) { + case "enterFrame": + this.triggerEvent(name2, new BMEnterFrameEvent(name2, this.currentFrame, this.totalFrames, this.frameModifier)); + break; + case "drawnFrame": + this.drawnFrameEvent.currentTime = this.currentFrame; + this.drawnFrameEvent.totalTime = this.totalFrames; + this.drawnFrameEvent.direction = this.frameModifier; + this.triggerEvent(name2, this.drawnFrameEvent); + break; + case "loopComplete": + this.triggerEvent(name2, new BMCompleteLoopEvent(name2, this.loop, this.playCount, this.frameMult)); + break; + case "complete": + this.triggerEvent(name2, new BMCompleteEvent(name2, this.frameMult)); + break; + case "segmentStart": + this.triggerEvent(name2, new BMSegmentStartEvent(name2, this.firstFrame, this.totalFrames)); + break; + case "destroy": + this.triggerEvent(name2, new BMDestroyEvent(name2, this)); + break; + default: + this.triggerEvent(name2); + } + } + if (name2 === "enterFrame" && this.onEnterFrame) { + this.onEnterFrame.call(this, new BMEnterFrameEvent(name2, this.currentFrame, this.totalFrames, this.frameMult)); + } + if (name2 === "loopComplete" && this.onLoopComplete) { + this.onLoopComplete.call(this, new BMCompleteLoopEvent(name2, this.loop, this.playCount, this.frameMult)); + } + if (name2 === "complete" && this.onComplete) { + this.onComplete.call(this, new BMCompleteEvent(name2, this.frameMult)); + } + if (name2 === "segmentStart" && this.onSegmentStart) { + this.onSegmentStart.call(this, new BMSegmentStartEvent(name2, this.firstFrame, this.totalFrames)); + } + if (name2 === "destroy" && this.onDestroy) { + this.onDestroy.call(this, new BMDestroyEvent(name2, this)); + } + }; + AnimationItem.prototype.triggerRenderFrameError = function(nativeError) { + var error = new BMRenderFrameErrorEvent(nativeError, this.currentFrame); + this.triggerEvent("error", error); + if (this.onError) { + this.onError.call(this, error); + } + }; + AnimationItem.prototype.triggerConfigError = function(nativeError) { + var error = new BMConfigErrorEvent(nativeError, this.currentFrame); + this.triggerEvent("error", error); + if (this.onError) { + this.onError.call(this, error); + } + }; + const animationManager = function() { + var moduleOb = {}; + var registeredAnimations = []; + var initTime = 0; + var len = 0; + var playingAnimationsNum = 0; + var _stopped = true; + var _isFrozen = false; + function removeElement(ev) { + var i = 0; + var animItem = ev.target; + while (i < len) { + if (registeredAnimations[i].animation === animItem) { + registeredAnimations.splice(i, 1); + i -= 1; + len -= 1; + if (!animItem.isPaused) { + subtractPlayingCount(); + } + } + i += 1; + } + } + function registerAnimation(element, animationData2) { + if (!element) { + return null; + } + var i = 0; + while (i < len) { + if (registeredAnimations[i].elem === element && registeredAnimations[i].elem !== null) { + return registeredAnimations[i].animation; + } + i += 1; + } + var animItem = new AnimationItem; + setupAnimation(animItem, element); + animItem.setData(element, animationData2); + return animItem; + } + function getRegisteredAnimations() { + var i; + var lenAnims = registeredAnimations.length; + var animations = []; + for (i = 0;i < lenAnims; i += 1) { + animations.push(registeredAnimations[i].animation); + } + return animations; + } + function addPlayingCount() { + playingAnimationsNum += 1; + activate(); + } + function subtractPlayingCount() { + playingAnimationsNum -= 1; + } + function setupAnimation(animItem, element) { + animItem.addEventListener("destroy", removeElement); + animItem.addEventListener("_active", addPlayingCount); + animItem.addEventListener("_idle", subtractPlayingCount); + registeredAnimations.push({ elem: element, animation: animItem }); + len += 1; + } + function loadAnimation2(params) { + var animItem = new AnimationItem; + setupAnimation(animItem, null); + animItem.setParams(params); + return animItem; + } + function setSpeed(val2, animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.setSpeed(val2, animation); + } + } + function setDirection(val2, animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.setDirection(val2, animation); + } + } + function play(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.play(animation); + } + } + function resume(nowTime) { + var elapsedTime = nowTime - initTime; + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.advanceTime(elapsedTime); + } + initTime = nowTime; + if (playingAnimationsNum && !_isFrozen) { + window.requestAnimationFrame(resume); + } else { + _stopped = true; + } + } + function first2(nowTime) { + initTime = nowTime; + window.requestAnimationFrame(resume); + } + function pause(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.pause(animation); + } + } + function goToAndStop(value2, isFrame, animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.goToAndStop(value2, isFrame, animation); + } + } + function stop(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.stop(animation); + } + } + function togglePause(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.togglePause(animation); + } + } + function destroy(animation) { + var i; + for (i = len - 1;i >= 0; i -= 1) { + registeredAnimations[i].animation.destroy(animation); + } + } + function searchAnimations2(animationData2, standalone2, renderer2) { + var animElements = [].concat([].slice.call(document.getElementsByClassName("lottie")), [].slice.call(document.getElementsByClassName("bodymovin"))); + var i; + var lenAnims = animElements.length; + for (i = 0;i < lenAnims; i += 1) { + if (renderer2) { + animElements[i].setAttribute("data-bm-type", renderer2); + } + registerAnimation(animElements[i], animationData2); + } + if (standalone2 && lenAnims === 0) { + if (!renderer2) { + renderer2 = "svg"; + } + var body = document.getElementsByTagName("body")[0]; + body.innerText = ""; + var div2 = createTag("div"); + div2.style.width = "100%"; + div2.style.height = "100%"; + div2.setAttribute("data-bm-type", renderer2); + body.appendChild(div2); + registerAnimation(div2, animationData2); + } + } + function resize() { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.resize(); + } + } + function activate() { + if (!_isFrozen && playingAnimationsNum) { + if (_stopped) { + window.requestAnimationFrame(first2); + _stopped = false; + } + } + } + function freeze() { + _isFrozen = true; + } + function unfreeze() { + _isFrozen = false; + activate(); + } + function setVolume(val2, animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.setVolume(val2, animation); + } + } + function mute(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.mute(animation); + } + } + function unmute(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.unmute(animation); + } + } + moduleOb.registerAnimation = registerAnimation; + moduleOb.loadAnimation = loadAnimation2; + moduleOb.setSpeed = setSpeed; + moduleOb.setDirection = setDirection; + moduleOb.play = play; + moduleOb.pause = pause; + moduleOb.stop = stop; + moduleOb.togglePause = togglePause; + moduleOb.searchAnimations = searchAnimations2; + moduleOb.resize = resize; + moduleOb.goToAndStop = goToAndStop; + moduleOb.destroy = destroy; + moduleOb.freeze = freeze; + moduleOb.unfreeze = unfreeze; + moduleOb.setVolume = setVolume; + moduleOb.mute = mute; + moduleOb.unmute = unmute; + moduleOb.getRegisteredAnimations = getRegisteredAnimations; + return moduleOb; + }(); + const BezierFactory = function() { + var ob2 = {}; + ob2.getBezierEasing = getBezierEasing; + var beziers = {}; + function getBezierEasing(a, b, c, d, nm2) { + var str = nm2 || ("bez_" + a + "_" + b + "_" + c + "_" + d).replace(/\./g, "p"); + if (beziers[str]) { + return beziers[str]; + } + var bezEasing = new BezierEasing([a, b, c, d]); + beziers[str] = bezEasing; + return bezEasing; + } + var NEWTON_ITERATIONS = 4; + var NEWTON_MIN_SLOPE = 0.001; + var SUBDIVISION_PRECISION = 0.0000001; + var SUBDIVISION_MAX_ITERATIONS = 10; + var kSplineTableSize = 11; + var kSampleStepSize = 1 / (kSplineTableSize - 1); + var float32ArraySupported = typeof Float32Array === "function"; + function A4(aA1, aA2) { + return 1 - 3 * aA2 + 3 * aA1; + } + function B3(aA1, aA2) { + return 3 * aA2 - 6 * aA1; + } + function C5(aA1) { + return 3 * aA1; + } + function calcBezier(aT, aA1, aA2) { + return ((A4(aA1, aA2) * aT + B3(aA1, aA2)) * aT + C5(aA1)) * aT; + } + function getSlope(aT, aA1, aA2) { + return 3 * A4(aA1, aA2) * aT * aT + 2 * B3(aA1, aA2) * aT + C5(aA1); + } + function binarySubdivide(aX, aA, aB, mX1, mX2) { + var currentX, currentT, i = 0; + do { + currentT = aA + (aB - aA) / 2; + currentX = calcBezier(currentT, mX1, mX2) - aX; + if (currentX > 0) { + aB = currentT; + } else { + aA = currentT; + } + } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS); + return currentT; + } + function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { + for (var i = 0;i < NEWTON_ITERATIONS; ++i) { + var currentSlope = getSlope(aGuessT, mX1, mX2); + if (currentSlope === 0) + return aGuessT; + var currentX = calcBezier(aGuessT, mX1, mX2) - aX; + aGuessT -= currentX / currentSlope; + } + return aGuessT; + } + function BezierEasing(points) { + this._p = points; + this._mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize); + this._precomputed = false; + this.get = this.get.bind(this); + } + BezierEasing.prototype = { + get: function(x2) { + var mX1 = this._p[0], mY1 = this._p[1], mX2 = this._p[2], mY2 = this._p[3]; + if (!this._precomputed) + this._precompute(); + if (mX1 === mY1 && mX2 === mY2) + return x2; + if (x2 === 0) + return 0; + if (x2 === 1) + return 1; + return calcBezier(this._getTForX(x2), mY1, mY2); + }, + _precompute: function() { + var mX1 = this._p[0], mY1 = this._p[1], mX2 = this._p[2], mY2 = this._p[3]; + this._precomputed = true; + if (mX1 !== mY1 || mX2 !== mY2) { + this._calcSampleValues(); + } + }, + _calcSampleValues: function() { + var mX1 = this._p[0], mX2 = this._p[2]; + for (var i = 0;i < kSplineTableSize; ++i) { + this._mSampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); + } + }, + _getTForX: function(aX) { + var mX1 = this._p[0], mX2 = this._p[2], mSampleValues = this._mSampleValues; + var intervalStart = 0; + var currentSample = 1; + var lastSample = kSplineTableSize - 1; + for (;currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) { + intervalStart += kSampleStepSize; + } + --currentSample; + var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]); + var guessForT = intervalStart + dist * kSampleStepSize; + var initialSlope = getSlope(guessForT, mX1, mX2); + if (initialSlope >= NEWTON_MIN_SLOPE) { + return newtonRaphsonIterate(aX, guessForT, mX1, mX2); + } + if (initialSlope === 0) { + return guessForT; + } + return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2); + } + }; + return ob2; + }(); + const pooling = function() { + function double(arr) { + return arr.concat(createSizedArray(arr.length)); + } + return { + double + }; + }(); + const poolFactory = function() { + return function(initialLength, _create, _release) { + var _length = 0; + var _maxLength = initialLength; + var pool = createSizedArray(_maxLength); + var ob2 = { + newElement, + release + }; + function newElement() { + var element; + if (_length) { + _length -= 1; + element = pool[_length]; + } else { + element = _create(); + } + return element; + } + function release(element) { + if (_length === _maxLength) { + pool = pooling.double(pool); + _maxLength *= 2; + } + if (_release) { + _release(element); + } + pool[_length] = element; + _length += 1; + } + return ob2; + }; + }(); + const bezierLengthPool = function() { + function create() { + return { + addedLength: 0, + percents: createTypedArray("float32", getDefaultCurveSegments()), + lengths: createTypedArray("float32", getDefaultCurveSegments()) + }; + } + return poolFactory(8, create); + }(); + const segmentsLengthPool = function() { + function create() { + return { + lengths: [], + totalLength: 0 + }; + } + function release(element) { + var i; + var len = element.lengths.length; + for (i = 0;i < len; i += 1) { + bezierLengthPool.release(element.lengths[i]); + } + element.lengths.length = 0; + } + return poolFactory(8, create, release); + }(); + const bez = bezFunction(); + const PropertyFactory = function() { + var initFrame = initialDefaultFrame; + var mathAbs = Math.abs; + function interpolateValue(frameNum, caching) { + var offsetTime = this.offsetTime; + var newValue; + if (this.propType === "multidimensional") { + newValue = createTypedArray("float32", this.pv.length); + } + var iterationIndex = caching.lastIndex; + var i = iterationIndex; + var len = this.keyframes.length - 1; + var flag = true; + var keyData; + var nextKeyData; + var keyframeMetadata; + while (flag) { + keyData = this.keyframes[i]; + nextKeyData = this.keyframes[i + 1]; + if (i === len - 1 && frameNum >= nextKeyData.t - offsetTime) { + if (keyData.h) { + keyData = nextKeyData; + } + iterationIndex = 0; + break; + } + if (nextKeyData.t - offsetTime > frameNum) { + iterationIndex = i; + break; + } + if (i < len - 1) { + i += 1; + } else { + iterationIndex = 0; + flag = false; + } + } + keyframeMetadata = this.keyframesMetadata[i] || {}; + var k2; + var kLen; + var perc; + var jLen; + var j2; + var fnc; + var nextKeyTime = nextKeyData.t - offsetTime; + var keyTime = keyData.t - offsetTime; + var endValue; + if (keyData.to) { + if (!keyframeMetadata.bezierData) { + keyframeMetadata.bezierData = bez.buildBezierData(keyData.s, nextKeyData.s || keyData.e, keyData.to, keyData.ti); + } + var bezierData = keyframeMetadata.bezierData; + if (frameNum >= nextKeyTime || frameNum < keyTime) { + var ind = frameNum >= nextKeyTime ? bezierData.points.length - 1 : 0; + kLen = bezierData.points[ind].point.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + newValue[k2] = bezierData.points[ind].point[k2]; + } + } else { + if (keyframeMetadata.__fnct) { + fnc = keyframeMetadata.__fnct; + } else { + fnc = BezierFactory.getBezierEasing(keyData.o.x, keyData.o.y, keyData.i.x, keyData.i.y, keyData.n).get; + keyframeMetadata.__fnct = fnc; + } + perc = fnc((frameNum - keyTime) / (nextKeyTime - keyTime)); + var distanceInLine = bezierData.segmentLength * perc; + var segmentPerc; + var addedLength = caching.lastFrame < frameNum && caching._lastKeyframeIndex === i ? caching._lastAddedLength : 0; + j2 = caching.lastFrame < frameNum && caching._lastKeyframeIndex === i ? caching._lastPoint : 0; + flag = true; + jLen = bezierData.points.length; + while (flag) { + addedLength += bezierData.points[j2].partialLength; + if (distanceInLine === 0 || perc === 0 || j2 === bezierData.points.length - 1) { + kLen = bezierData.points[j2].point.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + newValue[k2] = bezierData.points[j2].point[k2]; + } + break; + } else if (distanceInLine >= addedLength && distanceInLine < addedLength + bezierData.points[j2 + 1].partialLength) { + segmentPerc = (distanceInLine - addedLength) / bezierData.points[j2 + 1].partialLength; + kLen = bezierData.points[j2].point.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + newValue[k2] = bezierData.points[j2].point[k2] + (bezierData.points[j2 + 1].point[k2] - bezierData.points[j2].point[k2]) * segmentPerc; + } + break; + } + if (j2 < jLen - 1) { + j2 += 1; + } else { + flag = false; + } + } + caching._lastPoint = j2; + caching._lastAddedLength = addedLength - bezierData.points[j2].partialLength; + caching._lastKeyframeIndex = i; + } + } else { + var outX; + var outY; + var inX; + var inY; + var keyValue; + len = keyData.s.length; + endValue = nextKeyData.s || keyData.e; + if (this.sh && keyData.h !== 1) { + if (frameNum >= nextKeyTime) { + newValue[0] = endValue[0]; + newValue[1] = endValue[1]; + newValue[2] = endValue[2]; + } else if (frameNum <= keyTime) { + newValue[0] = keyData.s[0]; + newValue[1] = keyData.s[1]; + newValue[2] = keyData.s[2]; + } else { + var quatStart = createQuaternion(keyData.s); + var quatEnd = createQuaternion(endValue); + var time2 = (frameNum - keyTime) / (nextKeyTime - keyTime); + quaternionToEuler(newValue, slerp(quatStart, quatEnd, time2)); + } + } else { + for (i = 0;i < len; i += 1) { + if (keyData.h !== 1) { + if (frameNum >= nextKeyTime) { + perc = 1; + } else if (frameNum < keyTime) { + perc = 0; + } else { + if (keyData.o.x.constructor === Array) { + if (!keyframeMetadata.__fnct) { + keyframeMetadata.__fnct = []; + } + if (!keyframeMetadata.__fnct[i]) { + outX = keyData.o.x[i] === undefined ? keyData.o.x[0] : keyData.o.x[i]; + outY = keyData.o.y[i] === undefined ? keyData.o.y[0] : keyData.o.y[i]; + inX = keyData.i.x[i] === undefined ? keyData.i.x[0] : keyData.i.x[i]; + inY = keyData.i.y[i] === undefined ? keyData.i.y[0] : keyData.i.y[i]; + fnc = BezierFactory.getBezierEasing(outX, outY, inX, inY).get; + keyframeMetadata.__fnct[i] = fnc; + } else { + fnc = keyframeMetadata.__fnct[i]; + } + } else if (!keyframeMetadata.__fnct) { + outX = keyData.o.x; + outY = keyData.o.y; + inX = keyData.i.x; + inY = keyData.i.y; + fnc = BezierFactory.getBezierEasing(outX, outY, inX, inY).get; + keyData.keyframeMetadata = fnc; + } else { + fnc = keyframeMetadata.__fnct; + } + perc = fnc((frameNum - keyTime) / (nextKeyTime - keyTime)); + } + } + endValue = nextKeyData.s || keyData.e; + keyValue = keyData.h === 1 ? keyData.s[i] : keyData.s[i] + (endValue[i] - keyData.s[i]) * perc; + if (this.propType === "multidimensional") { + newValue[i] = keyValue; + } else { + newValue = keyValue; + } + } + } + } + caching.lastIndex = iterationIndex; + return newValue; + } + function slerp(a, b, t4) { + var out = []; + var ax = a[0]; + var ay = a[1]; + var az = a[2]; + var aw = a[3]; + var bx = b[0]; + var by = b[1]; + var bz = b[2]; + var bw2 = b[3]; + var omega; + var cosom; + var sinom; + var scale0; + var scale1; + cosom = ax * bx + ay * by + az * bz + aw * bw2; + if (cosom < 0) { + cosom = -cosom; + bx = -bx; + by = -by; + bz = -bz; + bw2 = -bw2; + } + if (1 - cosom > 0.000001) { + omega = Math.acos(cosom); + sinom = Math.sin(omega); + scale0 = Math.sin((1 - t4) * omega) / sinom; + scale1 = Math.sin(t4 * omega) / sinom; + } else { + scale0 = 1 - t4; + scale1 = t4; + } + out[0] = scale0 * ax + scale1 * bx; + out[1] = scale0 * ay + scale1 * by; + out[2] = scale0 * az + scale1 * bz; + out[3] = scale0 * aw + scale1 * bw2; + return out; + } + function quaternionToEuler(out, quat) { + var qx = quat[0]; + var qy = quat[1]; + var qz = quat[2]; + var qw = quat[3]; + var heading = Math.atan2(2 * qy * qw - 2 * qx * qz, 1 - 2 * qy * qy - 2 * qz * qz); + var attitude = Math.asin(2 * qx * qy + 2 * qz * qw); + var bank = Math.atan2(2 * qx * qw - 2 * qy * qz, 1 - 2 * qx * qx - 2 * qz * qz); + out[0] = heading / degToRads; + out[1] = attitude / degToRads; + out[2] = bank / degToRads; + } + function createQuaternion(values2) { + var heading = values2[0] * degToRads; + var attitude = values2[1] * degToRads; + var bank = values2[2] * degToRads; + var c1 = Math.cos(heading / 2); + var c2 = Math.cos(attitude / 2); + var c3 = Math.cos(bank / 2); + var s1 = Math.sin(heading / 2); + var s22 = Math.sin(attitude / 2); + var s3 = Math.sin(bank / 2); + var w = c1 * c2 * c3 - s1 * s22 * s3; + var x2 = s1 * s22 * c3 + c1 * c2 * s3; + var y3 = s1 * c2 * c3 + c1 * s22 * s3; + var z2 = c1 * s22 * c3 - s1 * c2 * s3; + return [x2, y3, z2, w]; + } + function getValueAtCurrentTime() { + var frameNum = this.comp.renderedFrame - this.offsetTime; + var initTime = this.keyframes[0].t - this.offsetTime; + var endTime = this.keyframes[this.keyframes.length - 1].t - this.offsetTime; + if (!(frameNum === this._caching.lastFrame || this._caching.lastFrame !== initFrame && (this._caching.lastFrame >= endTime && frameNum >= endTime || this._caching.lastFrame < initTime && frameNum < initTime))) { + if (this._caching.lastFrame >= frameNum) { + this._caching._lastKeyframeIndex = -1; + this._caching.lastIndex = 0; + } + var renderResult = this.interpolateValue(frameNum, this._caching); + this.pv = renderResult; + } + this._caching.lastFrame = frameNum; + return this.pv; + } + function setVValue(val2) { + var multipliedValue; + if (this.propType === "unidimensional") { + multipliedValue = val2 * this.mult; + if (mathAbs(this.v - multipliedValue) > 0.00001) { + this.v = multipliedValue; + this._mdf = true; + } + } else { + var i = 0; + var len = this.v.length; + while (i < len) { + multipliedValue = val2[i] * this.mult; + if (mathAbs(this.v[i] - multipliedValue) > 0.00001) { + this.v[i] = multipliedValue; + this._mdf = true; + } + i += 1; + } + } + } + function processEffectsSequence() { + if (this.elem.globalData.frameId === this.frameId || !this.effectsSequence.length) { + return; + } + if (this.lock) { + this.setVValue(this.pv); + return; + } + this.lock = true; + this._mdf = this._isFirstFrame; + var i; + var len = this.effectsSequence.length; + var finalValue = this.kf ? this.pv : this.data.k; + for (i = 0;i < len; i += 1) { + finalValue = this.effectsSequence[i](finalValue); + } + this.setVValue(finalValue); + this._isFirstFrame = false; + this.lock = false; + this.frameId = this.elem.globalData.frameId; + } + function addEffect(effectFunction) { + this.effectsSequence.push(effectFunction); + this.container.addDynamicProperty(this); + } + function ValueProperty(elem2, data2, mult, container) { + this.propType = "unidimensional"; + this.mult = mult || 1; + this.data = data2; + this.v = mult ? data2.k * mult : data2.k; + this.pv = data2.k; + this._mdf = false; + this.elem = elem2; + this.container = container; + this.comp = elem2.comp; + this.k = false; + this.kf = false; + this.vel = 0; + this.effectsSequence = []; + this._isFirstFrame = true; + this.getValue = processEffectsSequence; + this.setVValue = setVValue; + this.addEffect = addEffect; + } + function MultiDimensionalProperty(elem2, data2, mult, container) { + this.propType = "multidimensional"; + this.mult = mult || 1; + this.data = data2; + this._mdf = false; + this.elem = elem2; + this.container = container; + this.comp = elem2.comp; + this.k = false; + this.kf = false; + this.frameId = -1; + var i; + var len = data2.k.length; + this.v = createTypedArray("float32", len); + this.pv = createTypedArray("float32", len); + this.vel = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + this.v[i] = data2.k[i] * this.mult; + this.pv[i] = data2.k[i]; + } + this._isFirstFrame = true; + this.effectsSequence = []; + this.getValue = processEffectsSequence; + this.setVValue = setVValue; + this.addEffect = addEffect; + } + function KeyframedValueProperty(elem2, data2, mult, container) { + this.propType = "unidimensional"; + this.keyframes = data2.k; + this.keyframesMetadata = []; + this.offsetTime = elem2.data.st; + this.frameId = -1; + this._caching = { + lastFrame: initFrame, + lastIndex: 0, + value: 0, + _lastKeyframeIndex: -1 + }; + this.k = true; + this.kf = true; + this.data = data2; + this.mult = mult || 1; + this.elem = elem2; + this.container = container; + this.comp = elem2.comp; + this.v = initFrame; + this.pv = initFrame; + this._isFirstFrame = true; + this.getValue = processEffectsSequence; + this.setVValue = setVValue; + this.interpolateValue = interpolateValue; + this.effectsSequence = [getValueAtCurrentTime.bind(this)]; + this.addEffect = addEffect; + } + function KeyframedMultidimensionalProperty(elem2, data2, mult, container) { + this.propType = "multidimensional"; + var i; + var len = data2.k.length; + var s; + var e; + var to; + var ti; + for (i = 0;i < len - 1; i += 1) { + if (data2.k[i].to && data2.k[i].s && data2.k[i + 1] && data2.k[i + 1].s) { + s = data2.k[i].s; + e = data2.k[i + 1].s; + to = data2.k[i].to; + ti = data2.k[i].ti; + if (s.length === 2 && !(s[0] === e[0] && s[1] === e[1]) && bez.pointOnLine2D(s[0], s[1], e[0], e[1], s[0] + to[0], s[1] + to[1]) && bez.pointOnLine2D(s[0], s[1], e[0], e[1], e[0] + ti[0], e[1] + ti[1]) || s.length === 3 && !(s[0] === e[0] && s[1] === e[1] && s[2] === e[2]) && bez.pointOnLine3D(s[0], s[1], s[2], e[0], e[1], e[2], s[0] + to[0], s[1] + to[1], s[2] + to[2]) && bez.pointOnLine3D(s[0], s[1], s[2], e[0], e[1], e[2], e[0] + ti[0], e[1] + ti[1], e[2] + ti[2])) { + data2.k[i].to = null; + data2.k[i].ti = null; + } + if (s[0] === e[0] && s[1] === e[1] && to[0] === 0 && to[1] === 0 && ti[0] === 0 && ti[1] === 0) { + if (s.length === 2 || s[2] === e[2] && to[2] === 0 && ti[2] === 0) { + data2.k[i].to = null; + data2.k[i].ti = null; + } + } + } + } + this.effectsSequence = [getValueAtCurrentTime.bind(this)]; + this.data = data2; + this.keyframes = data2.k; + this.keyframesMetadata = []; + this.offsetTime = elem2.data.st; + this.k = true; + this.kf = true; + this._isFirstFrame = true; + this.mult = mult || 1; + this.elem = elem2; + this.container = container; + this.comp = elem2.comp; + this.getValue = processEffectsSequence; + this.setVValue = setVValue; + this.interpolateValue = interpolateValue; + this.frameId = -1; + var arrLen = data2.k[0].s.length; + this.v = createTypedArray("float32", arrLen); + this.pv = createTypedArray("float32", arrLen); + for (i = 0;i < arrLen; i += 1) { + this.v[i] = initFrame; + this.pv[i] = initFrame; + } + this._caching = { lastFrame: initFrame, lastIndex: 0, value: createTypedArray("float32", arrLen) }; + this.addEffect = addEffect; + } + function getProp(elem2, data2, type, mult, container) { + var p; + if (!data2.k.length) { + p = new ValueProperty(elem2, data2, mult, container); + } else if (typeof data2.k[0] === "number") { + p = new MultiDimensionalProperty(elem2, data2, mult, container); + } else { + switch (type) { + case 0: + p = new KeyframedValueProperty(elem2, data2, mult, container); + break; + case 1: + p = new KeyframedMultidimensionalProperty(elem2, data2, mult, container); + break; + default: + break; + } + } + if (p.effectsSequence.length) { + container.addDynamicProperty(p); + } + return p; + } + var ob2 = { + getProp + }; + return ob2; + }(); + DynamicPropertyContainer.prototype = { + addDynamicProperty: function(prop) { + if (this.dynamicProperties.indexOf(prop) === -1) { + this.dynamicProperties.push(prop); + this.container.addDynamicProperty(this); + this._isAnimated = true; + } + }, + iterateDynamicProperties: function() { + this._mdf = false; + var i; + var len = this.dynamicProperties.length; + for (i = 0;i < len; i += 1) { + this.dynamicProperties[i].getValue(); + if (this.dynamicProperties[i]._mdf) { + this._mdf = true; + } + } + }, + initDynamicPropertyContainer: function(container) { + this.container = container; + this.dynamicProperties = []; + this._mdf = false; + this._isAnimated = false; + } + }; + const pointPool = function() { + function create() { + return createTypedArray("float32", 2); + } + return poolFactory(8, create); + }(); + ShapePath.prototype.setPathData = function(closed, len) { + this.c = closed; + this.setLength(len); + var i = 0; + while (i < len) { + this.v[i] = pointPool.newElement(); + this.o[i] = pointPool.newElement(); + this.i[i] = pointPool.newElement(); + i += 1; + } + }; + ShapePath.prototype.setLength = function(len) { + while (this._maxLength < len) { + this.doubleArrayLength(); + } + this._length = len; + }; + ShapePath.prototype.doubleArrayLength = function() { + this.v = this.v.concat(createSizedArray(this._maxLength)); + this.i = this.i.concat(createSizedArray(this._maxLength)); + this.o = this.o.concat(createSizedArray(this._maxLength)); + this._maxLength *= 2; + }; + ShapePath.prototype.setXYAt = function(x2, y3, type, pos, replace) { + var arr; + this._length = Math.max(this._length, pos + 1); + if (this._length >= this._maxLength) { + this.doubleArrayLength(); + } + switch (type) { + case "v": + arr = this.v; + break; + case "i": + arr = this.i; + break; + case "o": + arr = this.o; + break; + default: + arr = []; + break; + } + if (!arr[pos] || arr[pos] && !replace) { + arr[pos] = pointPool.newElement(); + } + arr[pos][0] = x2; + arr[pos][1] = y3; + }; + ShapePath.prototype.setTripleAt = function(vX, vY, oX, oY, iX, iY, pos, replace) { + this.setXYAt(vX, vY, "v", pos, replace); + this.setXYAt(oX, oY, "o", pos, replace); + this.setXYAt(iX, iY, "i", pos, replace); + }; + ShapePath.prototype.reverse = function() { + var newPath = new ShapePath; + newPath.setPathData(this.c, this._length); + var vertices = this.v; + var outPoints = this.o; + var inPoints = this.i; + var init = 0; + if (this.c) { + newPath.setTripleAt(vertices[0][0], vertices[0][1], inPoints[0][0], inPoints[0][1], outPoints[0][0], outPoints[0][1], 0, false); + init = 1; + } + var cnt = this._length - 1; + var len = this._length; + var i; + for (i = init;i < len; i += 1) { + newPath.setTripleAt(vertices[cnt][0], vertices[cnt][1], inPoints[cnt][0], inPoints[cnt][1], outPoints[cnt][0], outPoints[cnt][1], i, false); + cnt -= 1; + } + return newPath; + }; + const shapePool = function() { + function create() { + return new ShapePath; + } + function release(shapePath) { + var len = shapePath._length; + var i; + for (i = 0;i < len; i += 1) { + pointPool.release(shapePath.v[i]); + pointPool.release(shapePath.i[i]); + pointPool.release(shapePath.o[i]); + shapePath.v[i] = null; + shapePath.i[i] = null; + shapePath.o[i] = null; + } + shapePath._length = 0; + shapePath.c = false; + } + function clone(shape) { + var cloned = factory.newElement(); + var i; + var len = shape._length === undefined ? shape.v.length : shape._length; + cloned.setLength(len); + cloned.c = shape.c; + for (i = 0;i < len; i += 1) { + cloned.setTripleAt(shape.v[i][0], shape.v[i][1], shape.o[i][0], shape.o[i][1], shape.i[i][0], shape.i[i][1], i); + } + return cloned; + } + var factory = poolFactory(4, create, release); + factory.clone = clone; + return factory; + }(); + ShapeCollection.prototype.addShape = function(shapeData) { + if (this._length === this._maxLength) { + this.shapes = this.shapes.concat(createSizedArray(this._maxLength)); + this._maxLength *= 2; + } + this.shapes[this._length] = shapeData; + this._length += 1; + }; + ShapeCollection.prototype.releaseShapes = function() { + var i; + for (i = 0;i < this._length; i += 1) { + shapePool.release(this.shapes[i]); + } + this._length = 0; + }; + const shapeCollectionPool = function() { + var ob2 = { + newShapeCollection, + release + }; + var _length = 0; + var _maxLength = 4; + var pool = createSizedArray(_maxLength); + function newShapeCollection() { + var shapeCollection; + if (_length) { + _length -= 1; + shapeCollection = pool[_length]; + } else { + shapeCollection = new ShapeCollection; + } + return shapeCollection; + } + function release(shapeCollection) { + var i; + var len = shapeCollection._length; + for (i = 0;i < len; i += 1) { + shapePool.release(shapeCollection.shapes[i]); + } + shapeCollection._length = 0; + if (_length === _maxLength) { + pool = pooling.double(pool); + _maxLength *= 2; + } + pool[_length] = shapeCollection; + _length += 1; + } + return ob2; + }(); + const ShapePropertyFactory = function() { + var initFrame = -999999; + function interpolateShape(frameNum, previousValue, caching) { + var iterationIndex = caching.lastIndex; + var keyPropS; + var keyPropE; + var isHold; + var j2; + var k2; + var jLen; + var kLen; + var perc; + var vertexValue; + var kf = this.keyframes; + if (frameNum < kf[0].t - this.offsetTime) { + keyPropS = kf[0].s[0]; + isHold = true; + iterationIndex = 0; + } else if (frameNum >= kf[kf.length - 1].t - this.offsetTime) { + keyPropS = kf[kf.length - 1].s ? kf[kf.length - 1].s[0] : kf[kf.length - 2].e[0]; + isHold = true; + } else { + var i = iterationIndex; + var len = kf.length - 1; + var flag = true; + var keyData; + var nextKeyData; + var keyframeMetadata; + while (flag) { + keyData = kf[i]; + nextKeyData = kf[i + 1]; + if (nextKeyData.t - this.offsetTime > frameNum) { + break; + } + if (i < len - 1) { + i += 1; + } else { + flag = false; + } + } + keyframeMetadata = this.keyframesMetadata[i] || {}; + isHold = keyData.h === 1; + iterationIndex = i; + if (!isHold) { + if (frameNum >= nextKeyData.t - this.offsetTime) { + perc = 1; + } else if (frameNum < keyData.t - this.offsetTime) { + perc = 0; + } else { + var fnc; + if (keyframeMetadata.__fnct) { + fnc = keyframeMetadata.__fnct; + } else { + fnc = BezierFactory.getBezierEasing(keyData.o.x, keyData.o.y, keyData.i.x, keyData.i.y).get; + keyframeMetadata.__fnct = fnc; + } + perc = fnc((frameNum - (keyData.t - this.offsetTime)) / (nextKeyData.t - this.offsetTime - (keyData.t - this.offsetTime))); + } + keyPropE = nextKeyData.s ? nextKeyData.s[0] : keyData.e[0]; + } + keyPropS = keyData.s[0]; + } + jLen = previousValue._length; + kLen = keyPropS.i[0].length; + caching.lastIndex = iterationIndex; + for (j2 = 0;j2 < jLen; j2 += 1) { + for (k2 = 0;k2 < kLen; k2 += 1) { + vertexValue = isHold ? keyPropS.i[j2][k2] : keyPropS.i[j2][k2] + (keyPropE.i[j2][k2] - keyPropS.i[j2][k2]) * perc; + previousValue.i[j2][k2] = vertexValue; + vertexValue = isHold ? keyPropS.o[j2][k2] : keyPropS.o[j2][k2] + (keyPropE.o[j2][k2] - keyPropS.o[j2][k2]) * perc; + previousValue.o[j2][k2] = vertexValue; + vertexValue = isHold ? keyPropS.v[j2][k2] : keyPropS.v[j2][k2] + (keyPropE.v[j2][k2] - keyPropS.v[j2][k2]) * perc; + previousValue.v[j2][k2] = vertexValue; + } + } + } + function interpolateShapeCurrentTime() { + var frameNum = this.comp.renderedFrame - this.offsetTime; + var initTime = this.keyframes[0].t - this.offsetTime; + var endTime = this.keyframes[this.keyframes.length - 1].t - this.offsetTime; + var lastFrame = this._caching.lastFrame; + if (!(lastFrame !== initFrame && (lastFrame < initTime && frameNum < initTime || lastFrame > endTime && frameNum > endTime))) { + this._caching.lastIndex = lastFrame < frameNum ? this._caching.lastIndex : 0; + this.interpolateShape(frameNum, this.pv, this._caching); + } + this._caching.lastFrame = frameNum; + return this.pv; + } + function resetShape() { + this.paths = this.localShapeCollection; + } + function shapesEqual(shape1, shape2) { + if (shape1._length !== shape2._length || shape1.c !== shape2.c) { + return false; + } + var i; + var len = shape1._length; + for (i = 0;i < len; i += 1) { + if (shape1.v[i][0] !== shape2.v[i][0] || shape1.v[i][1] !== shape2.v[i][1] || shape1.o[i][0] !== shape2.o[i][0] || shape1.o[i][1] !== shape2.o[i][1] || shape1.i[i][0] !== shape2.i[i][0] || shape1.i[i][1] !== shape2.i[i][1]) { + return false; + } + } + return true; + } + function setVValue(newPath) { + if (!shapesEqual(this.v, newPath)) { + this.v = shapePool.clone(newPath); + this.localShapeCollection.releaseShapes(); + this.localShapeCollection.addShape(this.v); + this._mdf = true; + this.paths = this.localShapeCollection; + } + } + function processEffectsSequence() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + if (!this.effectsSequence.length) { + this._mdf = false; + return; + } + if (this.lock) { + this.setVValue(this.pv); + return; + } + this.lock = true; + this._mdf = false; + var finalValue; + if (this.kf) { + finalValue = this.pv; + } else if (this.data.ks) { + finalValue = this.data.ks.k; + } else { + finalValue = this.data.pt.k; + } + var i; + var len = this.effectsSequence.length; + for (i = 0;i < len; i += 1) { + finalValue = this.effectsSequence[i](finalValue); + } + this.setVValue(finalValue); + this.lock = false; + this.frameId = this.elem.globalData.frameId; + } + function ShapeProperty(elem2, data2, type) { + this.propType = "shape"; + this.comp = elem2.comp; + this.container = elem2; + this.elem = elem2; + this.data = data2; + this.k = false; + this.kf = false; + this._mdf = false; + var pathData = type === 3 ? data2.pt.k : data2.ks.k; + this.v = shapePool.clone(pathData); + this.pv = shapePool.clone(this.v); + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.paths = this.localShapeCollection; + this.paths.addShape(this.v); + this.reset = resetShape; + this.effectsSequence = []; + } + function addEffect(effectFunction) { + this.effectsSequence.push(effectFunction); + this.container.addDynamicProperty(this); + } + ShapeProperty.prototype.interpolateShape = interpolateShape; + ShapeProperty.prototype.getValue = processEffectsSequence; + ShapeProperty.prototype.setVValue = setVValue; + ShapeProperty.prototype.addEffect = addEffect; + function KeyframedShapeProperty(elem2, data2, type) { + this.propType = "shape"; + this.comp = elem2.comp; + this.elem = elem2; + this.container = elem2; + this.offsetTime = elem2.data.st; + this.keyframes = type === 3 ? data2.pt.k : data2.ks.k; + this.keyframesMetadata = []; + this.k = true; + this.kf = true; + var len = this.keyframes[0].s[0].i.length; + this.v = shapePool.newElement(); + this.v.setPathData(this.keyframes[0].s[0].c, len); + this.pv = shapePool.clone(this.v); + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.paths = this.localShapeCollection; + this.paths.addShape(this.v); + this.lastFrame = initFrame; + this.reset = resetShape; + this._caching = { lastFrame: initFrame, lastIndex: 0 }; + this.effectsSequence = [interpolateShapeCurrentTime.bind(this)]; + } + KeyframedShapeProperty.prototype.getValue = processEffectsSequence; + KeyframedShapeProperty.prototype.interpolateShape = interpolateShape; + KeyframedShapeProperty.prototype.setVValue = setVValue; + KeyframedShapeProperty.prototype.addEffect = addEffect; + var EllShapeProperty = function() { + var cPoint = roundCorner; + function EllShapePropertyFactory(elem2, data2) { + this.v = shapePool.newElement(); + this.v.setPathData(true, 4); + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.paths = this.localShapeCollection; + this.localShapeCollection.addShape(this.v); + this.d = data2.d; + this.elem = elem2; + this.comp = elem2.comp; + this.frameId = -1; + this.initDynamicPropertyContainer(elem2); + this.p = PropertyFactory.getProp(elem2, data2.p, 1, 0, this); + this.s = PropertyFactory.getProp(elem2, data2.s, 1, 0, this); + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.k = false; + this.convertEllToPath(); + } + } + EllShapePropertyFactory.prototype = { + reset: resetShape, + getValue: function() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + if (this._mdf) { + this.convertEllToPath(); + } + }, + convertEllToPath: function() { + var p0 = this.p.v[0]; + var p1 = this.p.v[1]; + var s0 = this.s.v[0] / 2; + var s1 = this.s.v[1] / 2; + var _cw = this.d !== 3; + var _v4 = this.v; + _v4.v[0][0] = p0; + _v4.v[0][1] = p1 - s1; + _v4.v[1][0] = _cw ? p0 + s0 : p0 - s0; + _v4.v[1][1] = p1; + _v4.v[2][0] = p0; + _v4.v[2][1] = p1 + s1; + _v4.v[3][0] = _cw ? p0 - s0 : p0 + s0; + _v4.v[3][1] = p1; + _v4.i[0][0] = _cw ? p0 - s0 * cPoint : p0 + s0 * cPoint; + _v4.i[0][1] = p1 - s1; + _v4.i[1][0] = _cw ? p0 + s0 : p0 - s0; + _v4.i[1][1] = p1 - s1 * cPoint; + _v4.i[2][0] = _cw ? p0 + s0 * cPoint : p0 - s0 * cPoint; + _v4.i[2][1] = p1 + s1; + _v4.i[3][0] = _cw ? p0 - s0 : p0 + s0; + _v4.i[3][1] = p1 + s1 * cPoint; + _v4.o[0][0] = _cw ? p0 + s0 * cPoint : p0 - s0 * cPoint; + _v4.o[0][1] = p1 - s1; + _v4.o[1][0] = _cw ? p0 + s0 : p0 - s0; + _v4.o[1][1] = p1 + s1 * cPoint; + _v4.o[2][0] = _cw ? p0 - s0 * cPoint : p0 + s0 * cPoint; + _v4.o[2][1] = p1 + s1; + _v4.o[3][0] = _cw ? p0 - s0 : p0 + s0; + _v4.o[3][1] = p1 - s1 * cPoint; + } + }; + extendPrototype([DynamicPropertyContainer], EllShapePropertyFactory); + return EllShapePropertyFactory; + }(); + var StarShapeProperty = function() { + function StarShapePropertyFactory(elem2, data2) { + this.v = shapePool.newElement(); + this.v.setPathData(true, 0); + this.elem = elem2; + this.comp = elem2.comp; + this.data = data2; + this.frameId = -1; + this.d = data2.d; + this.initDynamicPropertyContainer(elem2); + if (data2.sy === 1) { + this.ir = PropertyFactory.getProp(elem2, data2.ir, 0, 0, this); + this.is = PropertyFactory.getProp(elem2, data2.is, 0, 0.01, this); + this.convertToPath = this.convertStarToPath; + } else { + this.convertToPath = this.convertPolygonToPath; + } + this.pt = PropertyFactory.getProp(elem2, data2.pt, 0, 0, this); + this.p = PropertyFactory.getProp(elem2, data2.p, 1, 0, this); + this.r = PropertyFactory.getProp(elem2, data2.r, 0, degToRads, this); + this.or = PropertyFactory.getProp(elem2, data2.or, 0, 0, this); + this.os = PropertyFactory.getProp(elem2, data2.os, 0, 0.01, this); + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.localShapeCollection.addShape(this.v); + this.paths = this.localShapeCollection; + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.k = false; + this.convertToPath(); + } + } + StarShapePropertyFactory.prototype = { + reset: resetShape, + getValue: function() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + if (this._mdf) { + this.convertToPath(); + } + }, + convertStarToPath: function() { + var numPts = Math.floor(this.pt.v) * 2; + var angle = Math.PI * 2 / numPts; + var longFlag = true; + var longRad = this.or.v; + var shortRad = this.ir.v; + var longRound = this.os.v; + var shortRound = this.is.v; + var longPerimSegment = 2 * Math.PI * longRad / (numPts * 2); + var shortPerimSegment = 2 * Math.PI * shortRad / (numPts * 2); + var i; + var rad; + var roundness; + var perimSegment; + var currentAng = -Math.PI / 2; + currentAng += this.r.v; + var dir = this.data.d === 3 ? -1 : 1; + this.v._length = 0; + for (i = 0;i < numPts; i += 1) { + rad = longFlag ? longRad : shortRad; + roundness = longFlag ? longRound : shortRound; + perimSegment = longFlag ? longPerimSegment : shortPerimSegment; + var x2 = rad * Math.cos(currentAng); + var y3 = rad * Math.sin(currentAng); + var ox = x2 === 0 && y3 === 0 ? 0 : y3 / Math.sqrt(x2 * x2 + y3 * y3); + var oy = x2 === 0 && y3 === 0 ? 0 : -x2 / Math.sqrt(x2 * x2 + y3 * y3); + x2 += +this.p.v[0]; + y3 += +this.p.v[1]; + this.v.setTripleAt(x2, y3, x2 - ox * perimSegment * roundness * dir, y3 - oy * perimSegment * roundness * dir, x2 + ox * perimSegment * roundness * dir, y3 + oy * perimSegment * roundness * dir, i, true); + longFlag = !longFlag; + currentAng += angle * dir; + } + }, + convertPolygonToPath: function() { + var numPts = Math.floor(this.pt.v); + var angle = Math.PI * 2 / numPts; + var rad = this.or.v; + var roundness = this.os.v; + var perimSegment = 2 * Math.PI * rad / (numPts * 4); + var i; + var currentAng = -Math.PI * 0.5; + var dir = this.data.d === 3 ? -1 : 1; + currentAng += this.r.v; + this.v._length = 0; + for (i = 0;i < numPts; i += 1) { + var x2 = rad * Math.cos(currentAng); + var y3 = rad * Math.sin(currentAng); + var ox = x2 === 0 && y3 === 0 ? 0 : y3 / Math.sqrt(x2 * x2 + y3 * y3); + var oy = x2 === 0 && y3 === 0 ? 0 : -x2 / Math.sqrt(x2 * x2 + y3 * y3); + x2 += +this.p.v[0]; + y3 += +this.p.v[1]; + this.v.setTripleAt(x2, y3, x2 - ox * perimSegment * roundness * dir, y3 - oy * perimSegment * roundness * dir, x2 + ox * perimSegment * roundness * dir, y3 + oy * perimSegment * roundness * dir, i, true); + currentAng += angle * dir; + } + this.paths.length = 0; + this.paths[0] = this.v; + } + }; + extendPrototype([DynamicPropertyContainer], StarShapePropertyFactory); + return StarShapePropertyFactory; + }(); + var RectShapeProperty = function() { + function RectShapePropertyFactory(elem2, data2) { + this.v = shapePool.newElement(); + this.v.c = true; + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.localShapeCollection.addShape(this.v); + this.paths = this.localShapeCollection; + this.elem = elem2; + this.comp = elem2.comp; + this.frameId = -1; + this.d = data2.d; + this.initDynamicPropertyContainer(elem2); + this.p = PropertyFactory.getProp(elem2, data2.p, 1, 0, this); + this.s = PropertyFactory.getProp(elem2, data2.s, 1, 0, this); + this.r = PropertyFactory.getProp(elem2, data2.r, 0, 0, this); + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.k = false; + this.convertRectToPath(); + } + } + RectShapePropertyFactory.prototype = { + convertRectToPath: function() { + var p0 = this.p.v[0]; + var p1 = this.p.v[1]; + var v0 = this.s.v[0] / 2; + var v1 = this.s.v[1] / 2; + var round = bmMin(v0, v1, this.r.v); + var cPoint = round * (1 - roundCorner); + this.v._length = 0; + if (this.d === 2 || this.d === 1) { + this.v.setTripleAt(p0 + v0, p1 - v1 + round, p0 + v0, p1 - v1 + round, p0 + v0, p1 - v1 + cPoint, 0, true); + this.v.setTripleAt(p0 + v0, p1 + v1 - round, p0 + v0, p1 + v1 - cPoint, p0 + v0, p1 + v1 - round, 1, true); + if (round !== 0) { + this.v.setTripleAt(p0 + v0 - round, p1 + v1, p0 + v0 - round, p1 + v1, p0 + v0 - cPoint, p1 + v1, 2, true); + this.v.setTripleAt(p0 - v0 + round, p1 + v1, p0 - v0 + cPoint, p1 + v1, p0 - v0 + round, p1 + v1, 3, true); + this.v.setTripleAt(p0 - v0, p1 + v1 - round, p0 - v0, p1 + v1 - round, p0 - v0, p1 + v1 - cPoint, 4, true); + this.v.setTripleAt(p0 - v0, p1 - v1 + round, p0 - v0, p1 - v1 + cPoint, p0 - v0, p1 - v1 + round, 5, true); + this.v.setTripleAt(p0 - v0 + round, p1 - v1, p0 - v0 + round, p1 - v1, p0 - v0 + cPoint, p1 - v1, 6, true); + this.v.setTripleAt(p0 + v0 - round, p1 - v1, p0 + v0 - cPoint, p1 - v1, p0 + v0 - round, p1 - v1, 7, true); + } else { + this.v.setTripleAt(p0 - v0, p1 + v1, p0 - v0 + cPoint, p1 + v1, p0 - v0, p1 + v1, 2); + this.v.setTripleAt(p0 - v0, p1 - v1, p0 - v0, p1 - v1 + cPoint, p0 - v0, p1 - v1, 3); + } + } else { + this.v.setTripleAt(p0 + v0, p1 - v1 + round, p0 + v0, p1 - v1 + cPoint, p0 + v0, p1 - v1 + round, 0, true); + if (round !== 0) { + this.v.setTripleAt(p0 + v0 - round, p1 - v1, p0 + v0 - round, p1 - v1, p0 + v0 - cPoint, p1 - v1, 1, true); + this.v.setTripleAt(p0 - v0 + round, p1 - v1, p0 - v0 + cPoint, p1 - v1, p0 - v0 + round, p1 - v1, 2, true); + this.v.setTripleAt(p0 - v0, p1 - v1 + round, p0 - v0, p1 - v1 + round, p0 - v0, p1 - v1 + cPoint, 3, true); + this.v.setTripleAt(p0 - v0, p1 + v1 - round, p0 - v0, p1 + v1 - cPoint, p0 - v0, p1 + v1 - round, 4, true); + this.v.setTripleAt(p0 - v0 + round, p1 + v1, p0 - v0 + round, p1 + v1, p0 - v0 + cPoint, p1 + v1, 5, true); + this.v.setTripleAt(p0 + v0 - round, p1 + v1, p0 + v0 - cPoint, p1 + v1, p0 + v0 - round, p1 + v1, 6, true); + this.v.setTripleAt(p0 + v0, p1 + v1 - round, p0 + v0, p1 + v1 - round, p0 + v0, p1 + v1 - cPoint, 7, true); + } else { + this.v.setTripleAt(p0 - v0, p1 - v1, p0 - v0 + cPoint, p1 - v1, p0 - v0, p1 - v1, 1, true); + this.v.setTripleAt(p0 - v0, p1 + v1, p0 - v0, p1 + v1 - cPoint, p0 - v0, p1 + v1, 2, true); + this.v.setTripleAt(p0 + v0, p1 + v1, p0 + v0 - cPoint, p1 + v1, p0 + v0, p1 + v1, 3, true); + } + } + }, + getValue: function() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + if (this._mdf) { + this.convertRectToPath(); + } + }, + reset: resetShape + }; + extendPrototype([DynamicPropertyContainer], RectShapePropertyFactory); + return RectShapePropertyFactory; + }(); + function getShapeProp(elem2, data2, type) { + var prop; + if (type === 3 || type === 4) { + var dataProp = type === 3 ? data2.pt : data2.ks; + var keys2 = dataProp.k; + if (keys2.length) { + prop = new KeyframedShapeProperty(elem2, data2, type); + } else { + prop = new ShapeProperty(elem2, data2, type); + } + } else if (type === 5) { + prop = new RectShapeProperty(elem2, data2); + } else if (type === 6) { + prop = new EllShapeProperty(elem2, data2); + } else if (type === 7) { + prop = new StarShapeProperty(elem2, data2); + } + if (prop.k) { + elem2.addDynamicProperty(prop); + } + return prop; + } + function getConstructorFunction() { + return ShapeProperty; + } + function getKeyframedConstructorFunction() { + return KeyframedShapeProperty; + } + var ob2 = {}; + ob2.getShapeProp = getShapeProp; + ob2.getConstructorFunction = getConstructorFunction; + ob2.getKeyframedConstructorFunction = getKeyframedConstructorFunction; + return ob2; + }(); + /*! + Transformation Matrix v2.0 + (c) Epistemex 2014-2015 + www.epistemex.com + By Ken Fyrstenberg + Contributions by leeoniya. + License: MIT, header required. + */ + const Matrix = function() { + var _cos = Math.cos; + var _sin = Math.sin; + var _tan = Math.tan; + var _rnd = Math.round; + function reset() { + this.props[0] = 1; + this.props[1] = 0; + this.props[2] = 0; + this.props[3] = 0; + this.props[4] = 0; + this.props[5] = 1; + this.props[6] = 0; + this.props[7] = 0; + this.props[8] = 0; + this.props[9] = 0; + this.props[10] = 1; + this.props[11] = 0; + this.props[12] = 0; + this.props[13] = 0; + this.props[14] = 0; + this.props[15] = 1; + return this; + } + function rotate(angle) { + if (angle === 0) { + return this; + } + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + } + function rotateX(angle) { + if (angle === 0) { + return this; + } + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(1, 0, 0, 0, 0, mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1); + } + function rotateY(angle) { + if (angle === 0) { + return this; + } + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(mCos, 0, mSin, 0, 0, 1, 0, 0, -mSin, 0, mCos, 0, 0, 0, 0, 1); + } + function rotateZ(angle) { + if (angle === 0) { + return this; + } + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + } + function shear(sx, sy) { + return this._t(1, sy, sx, 1, 0, 0); + } + function skew(ax, ay) { + return this.shear(_tan(ax), _tan(ay)); + } + function skewFromAxis(ax, angle) { + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(mCos, mSin, 0, 0, -mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)._t(1, 0, 0, 0, _tan(ax), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + } + function scale2(sx, sy, sz) { + if (!sz && sz !== 0) { + sz = 1; + } + if (sx === 1 && sy === 1 && sz === 1) { + return this; + } + return this._t(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, 0, 0, 0, 1); + } + function setTransform(a, b, c, d, e, f, g3, h, i, j2, k2, l2, m, n2, o, p) { + this.props[0] = a; + this.props[1] = b; + this.props[2] = c; + this.props[3] = d; + this.props[4] = e; + this.props[5] = f; + this.props[6] = g3; + this.props[7] = h; + this.props[8] = i; + this.props[9] = j2; + this.props[10] = k2; + this.props[11] = l2; + this.props[12] = m; + this.props[13] = n2; + this.props[14] = o; + this.props[15] = p; + return this; + } + function translate(tx, ty2, tz) { + tz = tz || 0; + if (tx !== 0 || ty2 !== 0 || tz !== 0) { + return this._t(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, tx, ty2, tz, 1); + } + return this; + } + function transform2(a2, b22, c2, d2, e2, f2, g22, h2, i22, j2, k2, l2, m2, n2, o2, p2) { + var _p2 = this.props; + if (a2 === 1 && b22 === 0 && c2 === 0 && d2 === 0 && e2 === 0 && f2 === 1 && g22 === 0 && h2 === 0 && i22 === 0 && j2 === 0 && k2 === 1 && l2 === 0) { + _p2[12] = _p2[12] * a2 + _p2[15] * m2; + _p2[13] = _p2[13] * f2 + _p2[15] * n2; + _p2[14] = _p2[14] * k2 + _p2[15] * o2; + _p2[15] *= p2; + this._identityCalculated = false; + return this; + } + var a1 = _p2[0]; + var b1 = _p2[1]; + var c1 = _p2[2]; + var d1 = _p2[3]; + var e1 = _p2[4]; + var f1 = _p2[5]; + var g1 = _p2[6]; + var h1 = _p2[7]; + var i1 = _p2[8]; + var j1 = _p2[9]; + var k12 = _p2[10]; + var l1 = _p2[11]; + var m1 = _p2[12]; + var n1 = _p2[13]; + var o1 = _p2[14]; + var p1 = _p2[15]; + _p2[0] = a1 * a2 + b1 * e2 + c1 * i22 + d1 * m2; + _p2[1] = a1 * b22 + b1 * f2 + c1 * j2 + d1 * n2; + _p2[2] = a1 * c2 + b1 * g22 + c1 * k2 + d1 * o2; + _p2[3] = a1 * d2 + b1 * h2 + c1 * l2 + d1 * p2; + _p2[4] = e1 * a2 + f1 * e2 + g1 * i22 + h1 * m2; + _p2[5] = e1 * b22 + f1 * f2 + g1 * j2 + h1 * n2; + _p2[6] = e1 * c2 + f1 * g22 + g1 * k2 + h1 * o2; + _p2[7] = e1 * d2 + f1 * h2 + g1 * l2 + h1 * p2; + _p2[8] = i1 * a2 + j1 * e2 + k12 * i22 + l1 * m2; + _p2[9] = i1 * b22 + j1 * f2 + k12 * j2 + l1 * n2; + _p2[10] = i1 * c2 + j1 * g22 + k12 * k2 + l1 * o2; + _p2[11] = i1 * d2 + j1 * h2 + k12 * l2 + l1 * p2; + _p2[12] = m1 * a2 + n1 * e2 + o1 * i22 + p1 * m2; + _p2[13] = m1 * b22 + n1 * f2 + o1 * j2 + p1 * n2; + _p2[14] = m1 * c2 + n1 * g22 + o1 * k2 + p1 * o2; + _p2[15] = m1 * d2 + n1 * h2 + o1 * l2 + p1 * p2; + this._identityCalculated = false; + return this; + } + function isIdentity() { + if (!this._identityCalculated) { + this._identity = !(this.props[0] !== 1 || this.props[1] !== 0 || this.props[2] !== 0 || this.props[3] !== 0 || this.props[4] !== 0 || this.props[5] !== 1 || this.props[6] !== 0 || this.props[7] !== 0 || this.props[8] !== 0 || this.props[9] !== 0 || this.props[10] !== 1 || this.props[11] !== 0 || this.props[12] !== 0 || this.props[13] !== 0 || this.props[14] !== 0 || this.props[15] !== 1); + this._identityCalculated = true; + } + return this._identity; + } + function equals2(matr) { + var i = 0; + while (i < 16) { + if (matr.props[i] !== this.props[i]) { + return false; + } + i += 1; + } + return true; + } + function clone(matr) { + var i; + for (i = 0;i < 16; i += 1) { + matr.props[i] = this.props[i]; + } + return matr; + } + function cloneFromProps(props) { + var i; + for (i = 0;i < 16; i += 1) { + this.props[i] = props[i]; + } + } + function applyToPoint(x2, y3, z2) { + return { + x: x2 * this.props[0] + y3 * this.props[4] + z2 * this.props[8] + this.props[12], + y: x2 * this.props[1] + y3 * this.props[5] + z2 * this.props[9] + this.props[13], + z: x2 * this.props[2] + y3 * this.props[6] + z2 * this.props[10] + this.props[14] + }; + } + function applyToX(x2, y3, z2) { + return x2 * this.props[0] + y3 * this.props[4] + z2 * this.props[8] + this.props[12]; + } + function applyToY(x2, y3, z2) { + return x2 * this.props[1] + y3 * this.props[5] + z2 * this.props[9] + this.props[13]; + } + function applyToZ(x2, y3, z2) { + return x2 * this.props[2] + y3 * this.props[6] + z2 * this.props[10] + this.props[14]; + } + function getInverseMatrix() { + var determinant = this.props[0] * this.props[5] - this.props[1] * this.props[4]; + var a = this.props[5] / determinant; + var b = -this.props[1] / determinant; + var c = -this.props[4] / determinant; + var d = this.props[0] / determinant; + var e = (this.props[4] * this.props[13] - this.props[5] * this.props[12]) / determinant; + var f = -(this.props[0] * this.props[13] - this.props[1] * this.props[12]) / determinant; + var inverseMatrix = new Matrix; + inverseMatrix.props[0] = a; + inverseMatrix.props[1] = b; + inverseMatrix.props[4] = c; + inverseMatrix.props[5] = d; + inverseMatrix.props[12] = e; + inverseMatrix.props[13] = f; + return inverseMatrix; + } + function inversePoint(pt) { + var inverseMatrix = this.getInverseMatrix(); + return inverseMatrix.applyToPointArray(pt[0], pt[1], pt[2] || 0); + } + function inversePoints(pts) { + var i; + var len = pts.length; + var retPts = []; + for (i = 0;i < len; i += 1) { + retPts[i] = inversePoint(pts[i]); + } + return retPts; + } + function applyToTriplePoints(pt1, pt2, pt3) { + var arr = createTypedArray("float32", 6); + if (this.isIdentity()) { + arr[0] = pt1[0]; + arr[1] = pt1[1]; + arr[2] = pt2[0]; + arr[3] = pt2[1]; + arr[4] = pt3[0]; + arr[5] = pt3[1]; + } else { + var p0 = this.props[0]; + var p1 = this.props[1]; + var p4 = this.props[4]; + var p5 = this.props[5]; + var p12 = this.props[12]; + var p13 = this.props[13]; + arr[0] = pt1[0] * p0 + pt1[1] * p4 + p12; + arr[1] = pt1[0] * p1 + pt1[1] * p5 + p13; + arr[2] = pt2[0] * p0 + pt2[1] * p4 + p12; + arr[3] = pt2[0] * p1 + pt2[1] * p5 + p13; + arr[4] = pt3[0] * p0 + pt3[1] * p4 + p12; + arr[5] = pt3[0] * p1 + pt3[1] * p5 + p13; + } + return arr; + } + function applyToPointArray(x2, y3, z2) { + var arr; + if (this.isIdentity()) { + arr = [x2, y3, z2]; + } else { + arr = [ + x2 * this.props[0] + y3 * this.props[4] + z2 * this.props[8] + this.props[12], + x2 * this.props[1] + y3 * this.props[5] + z2 * this.props[9] + this.props[13], + x2 * this.props[2] + y3 * this.props[6] + z2 * this.props[10] + this.props[14] + ]; + } + return arr; + } + function applyToPointStringified(x2, y3) { + if (this.isIdentity()) { + return x2 + "," + y3; + } + var _p2 = this.props; + return Math.round((x2 * _p2[0] + y3 * _p2[4] + _p2[12]) * 100) / 100 + "," + Math.round((x2 * _p2[1] + y3 * _p2[5] + _p2[13]) * 100) / 100; + } + function toCSS() { + var i = 0; + var props = this.props; + var cssValue = "matrix3d("; + var v = 1e4; + while (i < 16) { + cssValue += _rnd(props[i] * v) / v; + cssValue += i === 15 ? ")" : ","; + i += 1; + } + return cssValue; + } + function roundMatrixProperty(val2) { + var v = 1e4; + if (val2 < 0.000001 && val2 > 0 || val2 > -0.000001 && val2 < 0) { + return _rnd(val2 * v) / v; + } + return val2; + } + function to2dCSS() { + var props = this.props; + var _a2 = roundMatrixProperty(props[0]); + var _b2 = roundMatrixProperty(props[1]); + var _c = roundMatrixProperty(props[4]); + var _d2 = roundMatrixProperty(props[5]); + var _e = roundMatrixProperty(props[12]); + var _f = roundMatrixProperty(props[13]); + return "matrix(" + _a2 + "," + _b2 + "," + _c + "," + _d2 + "," + _e + "," + _f + ")"; + } + return function() { + this.reset = reset; + this.rotate = rotate; + this.rotateX = rotateX; + this.rotateY = rotateY; + this.rotateZ = rotateZ; + this.skew = skew; + this.skewFromAxis = skewFromAxis; + this.shear = shear; + this.scale = scale2; + this.setTransform = setTransform; + this.translate = translate; + this.transform = transform2; + this.applyToPoint = applyToPoint; + this.applyToX = applyToX; + this.applyToY = applyToY; + this.applyToZ = applyToZ; + this.applyToPointArray = applyToPointArray; + this.applyToTriplePoints = applyToTriplePoints; + this.applyToPointStringified = applyToPointStringified; + this.toCSS = toCSS; + this.to2dCSS = to2dCSS; + this.clone = clone; + this.cloneFromProps = cloneFromProps; + this.equals = equals2; + this.inversePoints = inversePoints; + this.inversePoint = inversePoint; + this.getInverseMatrix = getInverseMatrix; + this._t = this.transform; + this.isIdentity = isIdentity; + this._identity = true; + this._identityCalculated = false; + this.props = createTypedArray("float32", 16); + this.reset(); + }; + }(); + standalone = "__[STANDALONE]__"; + animationData = "__[ANIMATIONDATA]__"; + renderer = ""; + lottie.play = animationManager.play; + lottie.pause = animationManager.pause; + lottie.setLocationHref = setLocation; + lottie.togglePause = animationManager.togglePause; + lottie.setSpeed = animationManager.setSpeed; + lottie.setDirection = animationManager.setDirection; + lottie.stop = animationManager.stop; + lottie.searchAnimations = searchAnimations; + lottie.registerAnimation = animationManager.registerAnimation; + lottie.loadAnimation = loadAnimation; + lottie.setSubframeRendering = setSubframeRendering; + lottie.resize = animationManager.resize; + lottie.goToAndStop = animationManager.goToAndStop; + lottie.destroy = animationManager.destroy; + lottie.setQuality = setQuality; + lottie.inBrowser = inBrowser; + lottie.installPlugin = installPlugin; + lottie.freeze = animationManager.freeze; + lottie.unfreeze = animationManager.unfreeze; + lottie.setVolume = animationManager.setVolume; + lottie.mute = animationManager.mute; + lottie.unmute = animationManager.unmute; + lottie.getRegisteredAnimations = animationManager.getRegisteredAnimations; + lottie.useWebWorker = setWebWorker; + lottie.setIDPrefix = setPrefix; + lottie.__getFactory = getFactory; + lottie.version = "[[BM_VERSION]]"; + queryString = ""; + if (standalone) { + scripts = document.getElementsByTagName("script"); + index2 = scripts.length - 1; + myScript = scripts[index2] || { + src: "" + }; + queryString = myScript.src ? myScript.src.replace(/^[^\?]+\??/, "") : ""; + renderer = getQueryVariable("renderer"); + } + readyStateCheckInterval = setInterval(checkReady, 100); + try { + if (!(typeof exports_lottie_canvas_module === "object" && typeof module_lottie_canvas_module !== "undefined") && !(typeof define === "function" && define.amd)) { + window.bodymovin = lottie; + } + } catch (err) { + } + const ShapeModifiers = function() { + var ob2 = {}; + var modifiers = {}; + ob2.registerModifier = registerModifier; + ob2.getModifier = getModifier; + function registerModifier(nm2, factory) { + if (!modifiers[nm2]) { + modifiers[nm2] = factory; + } + } + function getModifier(nm2, elem2, data2) { + return new modifiers[nm2](elem2, data2); + } + return ob2; + }(); + ShapeModifier.prototype.initModifierProperties = function() { + }; + ShapeModifier.prototype.addShapeToModifier = function() { + }; + ShapeModifier.prototype.addShape = function(data2) { + if (!this.closed) { + data2.sh.container.addDynamicProperty(data2.sh); + var shapeData = { shape: data2.sh, data: data2, localShapeCollection: shapeCollectionPool.newShapeCollection() }; + this.shapes.push(shapeData); + this.addShapeToModifier(shapeData); + if (this._isAnimated) { + data2.setAsAnimated(); + } + } + }; + ShapeModifier.prototype.init = function(elem2, data2) { + this.shapes = []; + this.elem = elem2; + this.initDynamicPropertyContainer(elem2); + this.initModifierProperties(elem2, data2); + this.frameId = initialDefaultFrame; + this.closed = false; + this.k = false; + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.getValue(true); + } + }; + ShapeModifier.prototype.processKeys = function() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + }; + extendPrototype([DynamicPropertyContainer], ShapeModifier); + extendPrototype([ShapeModifier], TrimModifier); + TrimModifier.prototype.initModifierProperties = function(elem2, data2) { + this.s = PropertyFactory.getProp(elem2, data2.s, 0, 0.01, this); + this.e = PropertyFactory.getProp(elem2, data2.e, 0, 0.01, this); + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0, this); + this.sValue = 0; + this.eValue = 0; + this.getValue = this.processKeys; + this.m = data2.m; + this._isAnimated = !!this.s.effectsSequence.length || !!this.e.effectsSequence.length || !!this.o.effectsSequence.length; + }; + TrimModifier.prototype.addShapeToModifier = function(shapeData) { + shapeData.pathsData = []; + }; + TrimModifier.prototype.calculateShapeEdges = function(s, e, shapeLength, addedLength, totalModifierLength) { + var segments = []; + if (e <= 1) { + segments.push({ + s, + e + }); + } else if (s >= 1) { + segments.push({ + s: s - 1, + e: e - 1 + }); + } else { + segments.push({ + s, + e: 1 + }); + segments.push({ + s: 0, + e: e - 1 + }); + } + var shapeSegments = []; + var i; + var len = segments.length; + var segmentOb; + for (i = 0;i < len; i += 1) { + segmentOb = segments[i]; + if (!(segmentOb.e * totalModifierLength < addedLength || segmentOb.s * totalModifierLength > addedLength + shapeLength)) { + var shapeS; + var shapeE; + if (segmentOb.s * totalModifierLength <= addedLength) { + shapeS = 0; + } else { + shapeS = (segmentOb.s * totalModifierLength - addedLength) / shapeLength; + } + if (segmentOb.e * totalModifierLength >= addedLength + shapeLength) { + shapeE = 1; + } else { + shapeE = (segmentOb.e * totalModifierLength - addedLength) / shapeLength; + } + shapeSegments.push([shapeS, shapeE]); + } + } + if (!shapeSegments.length) { + shapeSegments.push([0, 0]); + } + return shapeSegments; + }; + TrimModifier.prototype.releasePathsData = function(pathsData) { + var i; + var len = pathsData.length; + for (i = 0;i < len; i += 1) { + segmentsLengthPool.release(pathsData[i]); + } + pathsData.length = 0; + return pathsData; + }; + TrimModifier.prototype.processShapes = function(_isFirstFrame) { + var s; + var e; + if (this._mdf || _isFirstFrame) { + var o = this.o.v % 360 / 360; + if (o < 0) { + o += 1; + } + if (this.s.v > 1) { + s = 1 + o; + } else if (this.s.v < 0) { + s = 0 + o; + } else { + s = this.s.v + o; + } + if (this.e.v > 1) { + e = 1 + o; + } else if (this.e.v < 0) { + e = 0 + o; + } else { + e = this.e.v + o; + } + if (s > e) { + var _s = s; + s = e; + e = _s; + } + s = Math.round(s * 1e4) * 0.0001; + e = Math.round(e * 1e4) * 0.0001; + this.sValue = s; + this.eValue = e; + } else { + s = this.sValue; + e = this.eValue; + } + var shapePaths; + var i; + var len = this.shapes.length; + var j2; + var jLen; + var pathsData; + var pathData; + var totalShapeLength; + var totalModifierLength = 0; + if (e === s) { + for (i = 0;i < len; i += 1) { + this.shapes[i].localShapeCollection.releaseShapes(); + this.shapes[i].shape._mdf = true; + this.shapes[i].shape.paths = this.shapes[i].localShapeCollection; + if (this._mdf) { + this.shapes[i].pathsData.length = 0; + } + } + } else if (!(e === 1 && s === 0 || e === 0 && s === 1)) { + var segments = []; + var shapeData; + var localShapeCollection; + for (i = 0;i < len; i += 1) { + shapeData = this.shapes[i]; + if (!shapeData.shape._mdf && !this._mdf && !_isFirstFrame && this.m !== 2) { + shapeData.shape.paths = shapeData.localShapeCollection; + } else { + shapePaths = shapeData.shape.paths; + jLen = shapePaths._length; + totalShapeLength = 0; + if (!shapeData.shape._mdf && shapeData.pathsData.length) { + totalShapeLength = shapeData.totalShapeLength; + } else { + pathsData = this.releasePathsData(shapeData.pathsData); + for (j2 = 0;j2 < jLen; j2 += 1) { + pathData = bez.getSegmentsLength(shapePaths.shapes[j2]); + pathsData.push(pathData); + totalShapeLength += pathData.totalLength; + } + shapeData.totalShapeLength = totalShapeLength; + shapeData.pathsData = pathsData; + } + totalModifierLength += totalShapeLength; + shapeData.shape._mdf = true; + } + } + var shapeS = s; + var shapeE = e; + var addedLength = 0; + var edges; + for (i = len - 1;i >= 0; i -= 1) { + shapeData = this.shapes[i]; + if (shapeData.shape._mdf) { + localShapeCollection = shapeData.localShapeCollection; + localShapeCollection.releaseShapes(); + if (this.m === 2 && len > 1) { + edges = this.calculateShapeEdges(s, e, shapeData.totalShapeLength, addedLength, totalModifierLength); + addedLength += shapeData.totalShapeLength; + } else { + edges = [[shapeS, shapeE]]; + } + jLen = edges.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + shapeS = edges[j2][0]; + shapeE = edges[j2][1]; + segments.length = 0; + if (shapeE <= 1) { + segments.push({ + s: shapeData.totalShapeLength * shapeS, + e: shapeData.totalShapeLength * shapeE + }); + } else if (shapeS >= 1) { + segments.push({ + s: shapeData.totalShapeLength * (shapeS - 1), + e: shapeData.totalShapeLength * (shapeE - 1) + }); + } else { + segments.push({ + s: shapeData.totalShapeLength * shapeS, + e: shapeData.totalShapeLength + }); + segments.push({ + s: 0, + e: shapeData.totalShapeLength * (shapeE - 1) + }); + } + var newShapesData = this.addShapes(shapeData, segments[0]); + if (segments[0].s !== segments[0].e) { + if (segments.length > 1) { + var lastShapeInCollection = shapeData.shape.paths.shapes[shapeData.shape.paths._length - 1]; + if (lastShapeInCollection.c) { + var lastShape = newShapesData.pop(); + this.addPaths(newShapesData, localShapeCollection); + newShapesData = this.addShapes(shapeData, segments[1], lastShape); + } else { + this.addPaths(newShapesData, localShapeCollection); + newShapesData = this.addShapes(shapeData, segments[1]); + } + } + this.addPaths(newShapesData, localShapeCollection); + } + } + shapeData.shape.paths = localShapeCollection; + } + } + } else if (this._mdf) { + for (i = 0;i < len; i += 1) { + this.shapes[i].pathsData.length = 0; + this.shapes[i].shape._mdf = true; + } + } + }; + TrimModifier.prototype.addPaths = function(newPaths, localShapeCollection) { + var i; + var len = newPaths.length; + for (i = 0;i < len; i += 1) { + localShapeCollection.addShape(newPaths[i]); + } + }; + TrimModifier.prototype.addSegment = function(pt1, pt2, pt3, pt4, shapePath, pos, newShape) { + shapePath.setXYAt(pt2[0], pt2[1], "o", pos); + shapePath.setXYAt(pt3[0], pt3[1], "i", pos + 1); + if (newShape) { + shapePath.setXYAt(pt1[0], pt1[1], "v", pos); + } + shapePath.setXYAt(pt4[0], pt4[1], "v", pos + 1); + }; + TrimModifier.prototype.addSegmentFromArray = function(points, shapePath, pos, newShape) { + shapePath.setXYAt(points[1], points[5], "o", pos); + shapePath.setXYAt(points[2], points[6], "i", pos + 1); + if (newShape) { + shapePath.setXYAt(points[0], points[4], "v", pos); + } + shapePath.setXYAt(points[3], points[7], "v", pos + 1); + }; + TrimModifier.prototype.addShapes = function(shapeData, shapeSegment, shapePath) { + var pathsData = shapeData.pathsData; + var shapePaths = shapeData.shape.paths.shapes; + var i; + var len = shapeData.shape.paths._length; + var j2; + var jLen; + var addedLength = 0; + var currentLengthData; + var segmentCount; + var lengths; + var segment; + var shapes = []; + var initPos; + var newShape = true; + if (!shapePath) { + shapePath = shapePool.newElement(); + segmentCount = 0; + initPos = 0; + } else { + segmentCount = shapePath._length; + initPos = shapePath._length; + } + shapes.push(shapePath); + for (i = 0;i < len; i += 1) { + lengths = pathsData[i].lengths; + shapePath.c = shapePaths[i].c; + jLen = shapePaths[i].c ? lengths.length : lengths.length + 1; + for (j2 = 1;j2 < jLen; j2 += 1) { + currentLengthData = lengths[j2 - 1]; + if (addedLength + currentLengthData.addedLength < shapeSegment.s) { + addedLength += currentLengthData.addedLength; + shapePath.c = false; + } else if (addedLength > shapeSegment.e) { + shapePath.c = false; + break; + } else { + if (shapeSegment.s <= addedLength && shapeSegment.e >= addedLength + currentLengthData.addedLength) { + this.addSegment(shapePaths[i].v[j2 - 1], shapePaths[i].o[j2 - 1], shapePaths[i].i[j2], shapePaths[i].v[j2], shapePath, segmentCount, newShape); + newShape = false; + } else { + segment = bez.getNewSegment(shapePaths[i].v[j2 - 1], shapePaths[i].v[j2], shapePaths[i].o[j2 - 1], shapePaths[i].i[j2], (shapeSegment.s - addedLength) / currentLengthData.addedLength, (shapeSegment.e - addedLength) / currentLengthData.addedLength, lengths[j2 - 1]); + this.addSegmentFromArray(segment, shapePath, segmentCount, newShape); + newShape = false; + shapePath.c = false; + } + addedLength += currentLengthData.addedLength; + segmentCount += 1; + } + } + if (shapePaths[i].c && lengths.length) { + currentLengthData = lengths[j2 - 1]; + if (addedLength <= shapeSegment.e) { + var segmentLength = lengths[j2 - 1].addedLength; + if (shapeSegment.s <= addedLength && shapeSegment.e >= addedLength + segmentLength) { + this.addSegment(shapePaths[i].v[j2 - 1], shapePaths[i].o[j2 - 1], shapePaths[i].i[0], shapePaths[i].v[0], shapePath, segmentCount, newShape); + newShape = false; + } else { + segment = bez.getNewSegment(shapePaths[i].v[j2 - 1], shapePaths[i].v[0], shapePaths[i].o[j2 - 1], shapePaths[i].i[0], (shapeSegment.s - addedLength) / segmentLength, (shapeSegment.e - addedLength) / segmentLength, lengths[j2 - 1]); + this.addSegmentFromArray(segment, shapePath, segmentCount, newShape); + newShape = false; + shapePath.c = false; + } + } else { + shapePath.c = false; + } + addedLength += currentLengthData.addedLength; + segmentCount += 1; + } + if (shapePath._length) { + shapePath.setXYAt(shapePath.v[initPos][0], shapePath.v[initPos][1], "i", initPos); + shapePath.setXYAt(shapePath.v[shapePath._length - 1][0], shapePath.v[shapePath._length - 1][1], "o", shapePath._length - 1); + } + if (addedLength > shapeSegment.e) { + break; + } + if (i < len - 1) { + shapePath = shapePool.newElement(); + newShape = true; + shapes.push(shapePath); + segmentCount = 0; + } + } + return shapes; + }; + extendPrototype([ShapeModifier], PuckerAndBloatModifier); + PuckerAndBloatModifier.prototype.initModifierProperties = function(elem2, data2) { + this.getValue = this.processKeys; + this.amount = PropertyFactory.getProp(elem2, data2.a, 0, null, this); + this._isAnimated = !!this.amount.effectsSequence.length; + }; + PuckerAndBloatModifier.prototype.processPath = function(path, amount) { + var percent = amount / 100; + var centerPoint = [0, 0]; + var pathLength = path._length; + var i = 0; + for (i = 0;i < pathLength; i += 1) { + centerPoint[0] += path.v[i][0]; + centerPoint[1] += path.v[i][1]; + } + centerPoint[0] /= pathLength; + centerPoint[1] /= pathLength; + var clonedPath = shapePool.newElement(); + clonedPath.c = path.c; + var vX; + var vY; + var oX; + var oY; + var iX; + var iY; + for (i = 0;i < pathLength; i += 1) { + vX = path.v[i][0] + (centerPoint[0] - path.v[i][0]) * percent; + vY = path.v[i][1] + (centerPoint[1] - path.v[i][1]) * percent; + oX = path.o[i][0] + (centerPoint[0] - path.o[i][0]) * -percent; + oY = path.o[i][1] + (centerPoint[1] - path.o[i][1]) * -percent; + iX = path.i[i][0] + (centerPoint[0] - path.i[i][0]) * -percent; + iY = path.i[i][1] + (centerPoint[1] - path.i[i][1]) * -percent; + clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, i); + } + return clonedPath; + }; + PuckerAndBloatModifier.prototype.processShapes = function(_isFirstFrame) { + var shapePaths; + var i; + var len = this.shapes.length; + var j2; + var jLen; + var amount = this.amount.v; + if (amount !== 0) { + var shapeData; + var localShapeCollection; + for (i = 0;i < len; i += 1) { + shapeData = this.shapes[i]; + localShapeCollection = shapeData.localShapeCollection; + if (!(!shapeData.shape._mdf && !this._mdf && !_isFirstFrame)) { + localShapeCollection.releaseShapes(); + shapeData.shape._mdf = true; + shapePaths = shapeData.shape.paths.shapes; + jLen = shapeData.shape.paths._length; + for (j2 = 0;j2 < jLen; j2 += 1) { + localShapeCollection.addShape(this.processPath(shapePaths[j2], amount)); + } + } + shapeData.shape.paths = shapeData.localShapeCollection; + } + } + if (!this.dynamicProperties.length) { + this._mdf = false; + } + }; + const TransformPropertyFactory = function() { + var defaultVector = [0, 0]; + function applyToMatrix(mat) { + var _mdf = this._mdf; + this.iterateDynamicProperties(); + this._mdf = this._mdf || _mdf; + if (this.a) { + mat.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]); + } + if (this.s) { + mat.scale(this.s.v[0], this.s.v[1], this.s.v[2]); + } + if (this.sk) { + mat.skewFromAxis(-this.sk.v, this.sa.v); + } + if (this.r) { + mat.rotate(-this.r.v); + } else { + mat.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]); + } + if (this.data.p.s) { + if (this.data.p.z) { + mat.translate(this.px.v, this.py.v, -this.pz.v); + } else { + mat.translate(this.px.v, this.py.v, 0); + } + } else { + mat.translate(this.p.v[0], this.p.v[1], -this.p.v[2]); + } + } + function processKeys(forceRender) { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + if (this._isDirty) { + this.precalculateMatrix(); + this._isDirty = false; + } + this.iterateDynamicProperties(); + if (this._mdf || forceRender) { + var frameRate; + this.v.cloneFromProps(this.pre.props); + if (this.appliedTransformations < 1) { + this.v.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]); + } + if (this.appliedTransformations < 2) { + this.v.scale(this.s.v[0], this.s.v[1], this.s.v[2]); + } + if (this.sk && this.appliedTransformations < 3) { + this.v.skewFromAxis(-this.sk.v, this.sa.v); + } + if (this.r && this.appliedTransformations < 4) { + this.v.rotate(-this.r.v); + } else if (!this.r && this.appliedTransformations < 4) { + this.v.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]); + } + if (this.autoOriented) { + var v1; + var v2; + frameRate = this.elem.globalData.frameRate; + if (this.p && this.p.keyframes && this.p.getValueAtTime) { + if (this.p._caching.lastFrame + this.p.offsetTime <= this.p.keyframes[0].t) { + v1 = this.p.getValueAtTime((this.p.keyframes[0].t + 0.01) / frameRate, 0); + v2 = this.p.getValueAtTime(this.p.keyframes[0].t / frameRate, 0); + } else if (this.p._caching.lastFrame + this.p.offsetTime >= this.p.keyframes[this.p.keyframes.length - 1].t) { + v1 = this.p.getValueAtTime(this.p.keyframes[this.p.keyframes.length - 1].t / frameRate, 0); + v2 = this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length - 1].t - 0.05) / frameRate, 0); + } else { + v1 = this.p.pv; + v2 = this.p.getValueAtTime((this.p._caching.lastFrame + this.p.offsetTime - 0.01) / frameRate, this.p.offsetTime); + } + } else if (this.px && this.px.keyframes && this.py.keyframes && this.px.getValueAtTime && this.py.getValueAtTime) { + v1 = []; + v2 = []; + var px2 = this.px; + var py2 = this.py; + if (px2._caching.lastFrame + px2.offsetTime <= px2.keyframes[0].t) { + v1[0] = px2.getValueAtTime((px2.keyframes[0].t + 0.01) / frameRate, 0); + v1[1] = py2.getValueAtTime((py2.keyframes[0].t + 0.01) / frameRate, 0); + v2[0] = px2.getValueAtTime(px2.keyframes[0].t / frameRate, 0); + v2[1] = py2.getValueAtTime(py2.keyframes[0].t / frameRate, 0); + } else if (px2._caching.lastFrame + px2.offsetTime >= px2.keyframes[px2.keyframes.length - 1].t) { + v1[0] = px2.getValueAtTime(px2.keyframes[px2.keyframes.length - 1].t / frameRate, 0); + v1[1] = py2.getValueAtTime(py2.keyframes[py2.keyframes.length - 1].t / frameRate, 0); + v2[0] = px2.getValueAtTime((px2.keyframes[px2.keyframes.length - 1].t - 0.01) / frameRate, 0); + v2[1] = py2.getValueAtTime((py2.keyframes[py2.keyframes.length - 1].t - 0.01) / frameRate, 0); + } else { + v1 = [px2.pv, py2.pv]; + v2[0] = px2.getValueAtTime((px2._caching.lastFrame + px2.offsetTime - 0.01) / frameRate, px2.offsetTime); + v2[1] = py2.getValueAtTime((py2._caching.lastFrame + py2.offsetTime - 0.01) / frameRate, py2.offsetTime); + } + } else { + v2 = defaultVector; + v1 = v2; + } + this.v.rotate(-Math.atan2(v1[1] - v2[1], v1[0] - v2[0])); + } + if (this.data.p && this.data.p.s) { + if (this.data.p.z) { + this.v.translate(this.px.v, this.py.v, -this.pz.v); + } else { + this.v.translate(this.px.v, this.py.v, 0); + } + } else { + this.v.translate(this.p.v[0], this.p.v[1], -this.p.v[2]); + } + } + this.frameId = this.elem.globalData.frameId; + } + function precalculateMatrix() { + if (!this.a.k) { + this.pre.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]); + this.appliedTransformations = 1; + } else { + return; + } + if (!this.s.effectsSequence.length) { + this.pre.scale(this.s.v[0], this.s.v[1], this.s.v[2]); + this.appliedTransformations = 2; + } else { + return; + } + if (this.sk) { + if (!this.sk.effectsSequence.length && !this.sa.effectsSequence.length) { + this.pre.skewFromAxis(-this.sk.v, this.sa.v); + this.appliedTransformations = 3; + } else { + return; + } + } + if (this.r) { + if (!this.r.effectsSequence.length) { + this.pre.rotate(-this.r.v); + this.appliedTransformations = 4; + } + } else if (!this.rz.effectsSequence.length && !this.ry.effectsSequence.length && !this.rx.effectsSequence.length && !this.or.effectsSequence.length) { + this.pre.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]); + this.appliedTransformations = 4; + } + } + function autoOrient() { + } + function addDynamicProperty(prop) { + this._addDynamicProperty(prop); + this.elem.addDynamicProperty(prop); + this._isDirty = true; + } + function TransformProperty(elem2, data2, container) { + this.elem = elem2; + this.frameId = -1; + this.propType = "transform"; + this.data = data2; + this.v = new Matrix; + this.pre = new Matrix; + this.appliedTransformations = 0; + this.initDynamicPropertyContainer(container || elem2); + if (data2.p && data2.p.s) { + this.px = PropertyFactory.getProp(elem2, data2.p.x, 0, 0, this); + this.py = PropertyFactory.getProp(elem2, data2.p.y, 0, 0, this); + if (data2.p.z) { + this.pz = PropertyFactory.getProp(elem2, data2.p.z, 0, 0, this); + } + } else { + this.p = PropertyFactory.getProp(elem2, data2.p || { k: [0, 0, 0] }, 1, 0, this); + } + if (data2.rx) { + this.rx = PropertyFactory.getProp(elem2, data2.rx, 0, degToRads, this); + this.ry = PropertyFactory.getProp(elem2, data2.ry, 0, degToRads, this); + this.rz = PropertyFactory.getProp(elem2, data2.rz, 0, degToRads, this); + if (data2.or.k[0].ti) { + var i; + var len = data2.or.k.length; + for (i = 0;i < len; i += 1) { + data2.or.k[i].to = null; + data2.or.k[i].ti = null; + } + } + this.or = PropertyFactory.getProp(elem2, data2.or, 1, degToRads, this); + this.or.sh = true; + } else { + this.r = PropertyFactory.getProp(elem2, data2.r || { k: 0 }, 0, degToRads, this); + } + if (data2.sk) { + this.sk = PropertyFactory.getProp(elem2, data2.sk, 0, degToRads, this); + this.sa = PropertyFactory.getProp(elem2, data2.sa, 0, degToRads, this); + } + this.a = PropertyFactory.getProp(elem2, data2.a || { k: [0, 0, 0] }, 1, 0, this); + this.s = PropertyFactory.getProp(elem2, data2.s || { k: [100, 100, 100] }, 1, 0.01, this); + if (data2.o) { + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, elem2); + } else { + this.o = { _mdf: false, v: 1 }; + } + this._isDirty = true; + if (!this.dynamicProperties.length) { + this.getValue(true); + } + } + TransformProperty.prototype = { + applyToMatrix, + getValue: processKeys, + precalculateMatrix, + autoOrient + }; + extendPrototype([DynamicPropertyContainer], TransformProperty); + TransformProperty.prototype.addDynamicProperty = addDynamicProperty; + TransformProperty.prototype._addDynamicProperty = DynamicPropertyContainer.prototype.addDynamicProperty; + function getTransformProperty(elem2, data2, container) { + return new TransformProperty(elem2, data2, container); + } + return { + getTransformProperty + }; + }(); + extendPrototype([ShapeModifier], RepeaterModifier); + RepeaterModifier.prototype.initModifierProperties = function(elem2, data2) { + this.getValue = this.processKeys; + this.c = PropertyFactory.getProp(elem2, data2.c, 0, null, this); + this.o = PropertyFactory.getProp(elem2, data2.o, 0, null, this); + this.tr = TransformPropertyFactory.getTransformProperty(elem2, data2.tr, this); + this.so = PropertyFactory.getProp(elem2, data2.tr.so, 0, 0.01, this); + this.eo = PropertyFactory.getProp(elem2, data2.tr.eo, 0, 0.01, this); + this.data = data2; + if (!this.dynamicProperties.length) { + this.getValue(true); + } + this._isAnimated = !!this.dynamicProperties.length; + this.pMatrix = new Matrix; + this.rMatrix = new Matrix; + this.sMatrix = new Matrix; + this.tMatrix = new Matrix; + this.matrix = new Matrix; + }; + RepeaterModifier.prototype.applyTransforms = function(pMatrix, rMatrix, sMatrix, transform2, perc, inv) { + var dir = inv ? -1 : 1; + var scaleX = transform2.s.v[0] + (1 - transform2.s.v[0]) * (1 - perc); + var scaleY = transform2.s.v[1] + (1 - transform2.s.v[1]) * (1 - perc); + pMatrix.translate(transform2.p.v[0] * dir * perc, transform2.p.v[1] * dir * perc, transform2.p.v[2]); + rMatrix.translate(-transform2.a.v[0], -transform2.a.v[1], transform2.a.v[2]); + rMatrix.rotate(-transform2.r.v * dir * perc); + rMatrix.translate(transform2.a.v[0], transform2.a.v[1], transform2.a.v[2]); + sMatrix.translate(-transform2.a.v[0], -transform2.a.v[1], transform2.a.v[2]); + sMatrix.scale(inv ? 1 / scaleX : scaleX, inv ? 1 / scaleY : scaleY); + sMatrix.translate(transform2.a.v[0], transform2.a.v[1], transform2.a.v[2]); + }; + RepeaterModifier.prototype.init = function(elem2, arr, pos, elemsData) { + this.elem = elem2; + this.arr = arr; + this.pos = pos; + this.elemsData = elemsData; + this._currentCopies = 0; + this._elements = []; + this._groups = []; + this.frameId = -1; + this.initDynamicPropertyContainer(elem2); + this.initModifierProperties(elem2, arr[pos]); + while (pos > 0) { + pos -= 1; + this._elements.unshift(arr[pos]); + } + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.getValue(true); + } + }; + RepeaterModifier.prototype.resetElements = function(elements) { + var i; + var len = elements.length; + for (i = 0;i < len; i += 1) { + elements[i]._processed = false; + if (elements[i].ty === "gr") { + this.resetElements(elements[i].it); + } + } + }; + RepeaterModifier.prototype.cloneElements = function(elements) { + var newElements = JSON.parse(JSON.stringify(elements)); + this.resetElements(newElements); + return newElements; + }; + RepeaterModifier.prototype.changeGroupRender = function(elements, renderFlag) { + var i; + var len = elements.length; + for (i = 0;i < len; i += 1) { + elements[i]._render = renderFlag; + if (elements[i].ty === "gr") { + this.changeGroupRender(elements[i].it, renderFlag); + } + } + }; + RepeaterModifier.prototype.processShapes = function(_isFirstFrame) { + var items; + var itemsTransform; + var i; + var dir; + var cont; + var hasReloaded = false; + if (this._mdf || _isFirstFrame) { + var copies = Math.ceil(this.c.v); + if (this._groups.length < copies) { + while (this._groups.length < copies) { + var group = { + it: this.cloneElements(this._elements), + ty: "gr" + }; + group.it.push({ + a: { a: 0, ix: 1, k: [0, 0] }, + nm: "Transform", + o: { a: 0, ix: 7, k: 100 }, + p: { a: 0, ix: 2, k: [0, 0] }, + r: { a: 1, ix: 6, k: [{ s: 0, e: 0, t: 0 }, { s: 0, e: 0, t: 1 }] }, + s: { a: 0, ix: 3, k: [100, 100] }, + sa: { a: 0, ix: 5, k: 0 }, + sk: { a: 0, ix: 4, k: 0 }, + ty: "tr" + }); + this.arr.splice(0, 0, group); + this._groups.splice(0, 0, group); + this._currentCopies += 1; + } + this.elem.reloadShapes(); + hasReloaded = true; + } + cont = 0; + var renderFlag; + for (i = 0;i <= this._groups.length - 1; i += 1) { + renderFlag = cont < copies; + this._groups[i]._render = renderFlag; + this.changeGroupRender(this._groups[i].it, renderFlag); + if (!renderFlag) { + var elems = this.elemsData[i].it; + var transformData = elems[elems.length - 1]; + if (transformData.transform.op.v !== 0) { + transformData.transform.op._mdf = true; + transformData.transform.op.v = 0; + } else { + transformData.transform.op._mdf = false; + } + } + cont += 1; + } + this._currentCopies = copies; + var offset = this.o.v; + var offsetModulo = offset % 1; + var roundOffset = offset > 0 ? Math.floor(offset) : Math.ceil(offset); + var pProps = this.pMatrix.props; + var rProps = this.rMatrix.props; + var sProps = this.sMatrix.props; + this.pMatrix.reset(); + this.rMatrix.reset(); + this.sMatrix.reset(); + this.tMatrix.reset(); + this.matrix.reset(); + var iteration = 0; + if (offset > 0) { + while (iteration < roundOffset) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, false); + iteration += 1; + } + if (offsetModulo) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, offsetModulo, false); + iteration += offsetModulo; + } + } else if (offset < 0) { + while (iteration > roundOffset) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, true); + iteration -= 1; + } + if (offsetModulo) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, -offsetModulo, true); + iteration -= offsetModulo; + } + } + i = this.data.m === 1 ? 0 : this._currentCopies - 1; + dir = this.data.m === 1 ? 1 : -1; + cont = this._currentCopies; + var j2; + var jLen; + while (cont) { + items = this.elemsData[i].it; + itemsTransform = items[items.length - 1].transform.mProps.v.props; + jLen = itemsTransform.length; + items[items.length - 1].transform.mProps._mdf = true; + items[items.length - 1].transform.op._mdf = true; + items[items.length - 1].transform.op.v = this._currentCopies === 1 ? this.so.v : this.so.v + (this.eo.v - this.so.v) * (i / (this._currentCopies - 1)); + if (iteration !== 0) { + if (i !== 0 && dir === 1 || i !== this._currentCopies - 1 && dir === -1) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, false); + } + this.matrix.transform(rProps[0], rProps[1], rProps[2], rProps[3], rProps[4], rProps[5], rProps[6], rProps[7], rProps[8], rProps[9], rProps[10], rProps[11], rProps[12], rProps[13], rProps[14], rProps[15]); + this.matrix.transform(sProps[0], sProps[1], sProps[2], sProps[3], sProps[4], sProps[5], sProps[6], sProps[7], sProps[8], sProps[9], sProps[10], sProps[11], sProps[12], sProps[13], sProps[14], sProps[15]); + this.matrix.transform(pProps[0], pProps[1], pProps[2], pProps[3], pProps[4], pProps[5], pProps[6], pProps[7], pProps[8], pProps[9], pProps[10], pProps[11], pProps[12], pProps[13], pProps[14], pProps[15]); + for (j2 = 0;j2 < jLen; j2 += 1) { + itemsTransform[j2] = this.matrix.props[j2]; + } + this.matrix.reset(); + } else { + this.matrix.reset(); + for (j2 = 0;j2 < jLen; j2 += 1) { + itemsTransform[j2] = this.matrix.props[j2]; + } + } + iteration += 1; + cont -= 1; + i += dir; + } + } else { + cont = this._currentCopies; + i = 0; + dir = 1; + while (cont) { + items = this.elemsData[i].it; + itemsTransform = items[items.length - 1].transform.mProps.v.props; + items[items.length - 1].transform.mProps._mdf = false; + items[items.length - 1].transform.op._mdf = false; + cont -= 1; + i += dir; + } + } + return hasReloaded; + }; + RepeaterModifier.prototype.addShape = function() { + }; + extendPrototype([ShapeModifier], RoundCornersModifier); + RoundCornersModifier.prototype.initModifierProperties = function(elem2, data2) { + this.getValue = this.processKeys; + this.rd = PropertyFactory.getProp(elem2, data2.r, 0, null, this); + this._isAnimated = !!this.rd.effectsSequence.length; + }; + RoundCornersModifier.prototype.processPath = function(path, round) { + var clonedPath = shapePool.newElement(); + clonedPath.c = path.c; + var i; + var len = path._length; + var currentV; + var currentI; + var currentO; + var closerV; + var distance; + var newPosPerc; + var index2 = 0; + var vX; + var vY; + var oX; + var oY; + var iX; + var iY; + for (i = 0;i < len; i += 1) { + currentV = path.v[i]; + currentO = path.o[i]; + currentI = path.i[i]; + if (currentV[0] === currentO[0] && currentV[1] === currentO[1] && currentV[0] === currentI[0] && currentV[1] === currentI[1]) { + if ((i === 0 || i === len - 1) && !path.c) { + clonedPath.setTripleAt(currentV[0], currentV[1], currentO[0], currentO[1], currentI[0], currentI[1], index2); + index2 += 1; + } else { + if (i === 0) { + closerV = path.v[len - 1]; + } else { + closerV = path.v[i - 1]; + } + distance = Math.sqrt(Math.pow(currentV[0] - closerV[0], 2) + Math.pow(currentV[1] - closerV[1], 2)); + newPosPerc = distance ? Math.min(distance / 2, round) / distance : 0; + iX = currentV[0] + (closerV[0] - currentV[0]) * newPosPerc; + vX = iX; + iY = currentV[1] - (currentV[1] - closerV[1]) * newPosPerc; + vY = iY; + oX = vX - (vX - currentV[0]) * roundCorner; + oY = vY - (vY - currentV[1]) * roundCorner; + clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, index2); + index2 += 1; + if (i === len - 1) { + closerV = path.v[0]; + } else { + closerV = path.v[i + 1]; + } + distance = Math.sqrt(Math.pow(currentV[0] - closerV[0], 2) + Math.pow(currentV[1] - closerV[1], 2)); + newPosPerc = distance ? Math.min(distance / 2, round) / distance : 0; + oX = currentV[0] + (closerV[0] - currentV[0]) * newPosPerc; + vX = oX; + oY = currentV[1] + (closerV[1] - currentV[1]) * newPosPerc; + vY = oY; + iX = vX - (vX - currentV[0]) * roundCorner; + iY = vY - (vY - currentV[1]) * roundCorner; + clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, index2); + index2 += 1; + } + } else { + clonedPath.setTripleAt(path.v[i][0], path.v[i][1], path.o[i][0], path.o[i][1], path.i[i][0], path.i[i][1], index2); + index2 += 1; + } + } + return clonedPath; + }; + RoundCornersModifier.prototype.processShapes = function(_isFirstFrame) { + var shapePaths; + var i; + var len = this.shapes.length; + var j2; + var jLen; + var rd = this.rd.v; + if (rd !== 0) { + var shapeData; + var localShapeCollection; + for (i = 0;i < len; i += 1) { + shapeData = this.shapes[i]; + localShapeCollection = shapeData.localShapeCollection; + if (!(!shapeData.shape._mdf && !this._mdf && !_isFirstFrame)) { + localShapeCollection.releaseShapes(); + shapeData.shape._mdf = true; + shapePaths = shapeData.shape.paths.shapes; + jLen = shapeData.shape.paths._length; + for (j2 = 0;j2 < jLen; j2 += 1) { + localShapeCollection.addShape(this.processPath(shapePaths[j2], rd)); + } + } + shapeData.shape.paths = shapeData.localShapeCollection; + } + } + if (!this.dynamicProperties.length) { + this._mdf = false; + } + }; + const FontManager = function() { + var maxWaitingTime = 5000; + var emptyChar = { + w: 0, + size: 0, + shapes: [], + data: { + shapes: [] + } + }; + var combinedCharacters = []; + combinedCharacters = combinedCharacters.concat([ + 2304, + 2305, + 2306, + 2307, + 2362, + 2363, + 2364, + 2364, + 2366, + 2367, + 2368, + 2369, + 2370, + 2371, + 2372, + 2373, + 2374, + 2375, + 2376, + 2377, + 2378, + 2379, + 2380, + 2381, + 2382, + 2383, + 2387, + 2388, + 2389, + 2390, + 2391, + 2402, + 2403 + ]); + var surrogateModifiers = [ + "d83cdffb", + "d83cdffc", + "d83cdffd", + "d83cdffe", + "d83cdfff" + ]; + var zeroWidthJoiner = [65039, 8205]; + function trimFontOptions(font) { + var familyArray = font.split(","); + var i; + var len = familyArray.length; + var enabledFamilies = []; + for (i = 0;i < len; i += 1) { + if (familyArray[i] !== "sans-serif" && familyArray[i] !== "monospace") { + enabledFamilies.push(familyArray[i]); + } + } + return enabledFamilies.join(","); + } + function setUpNode(font, family) { + var parentNode = createTag("span"); + parentNode.setAttribute("aria-hidden", true); + parentNode.style.fontFamily = family; + var node = createTag("span"); + node.innerText = "giItT1WQy@!-/#"; + parentNode.style.position = "absolute"; + parentNode.style.left = "-10000px"; + parentNode.style.top = "-10000px"; + parentNode.style.fontSize = "300px"; + parentNode.style.fontVariant = "normal"; + parentNode.style.fontStyle = "normal"; + parentNode.style.fontWeight = "normal"; + parentNode.style.letterSpacing = "0"; + parentNode.appendChild(node); + document.body.appendChild(parentNode); + var width2 = node.offsetWidth; + node.style.fontFamily = trimFontOptions(font) + ", " + family; + return { node, w: width2, parent: parentNode }; + } + function checkLoadedFonts() { + var i; + var len = this.fonts.length; + var node; + var w; + var loadedCount = len; + for (i = 0;i < len; i += 1) { + if (this.fonts[i].loaded) { + loadedCount -= 1; + } else if (this.fonts[i].fOrigin === "n" || this.fonts[i].origin === 0) { + this.fonts[i].loaded = true; + } else { + node = this.fonts[i].monoCase.node; + w = this.fonts[i].monoCase.w; + if (node.offsetWidth !== w) { + loadedCount -= 1; + this.fonts[i].loaded = true; + } else { + node = this.fonts[i].sansCase.node; + w = this.fonts[i].sansCase.w; + if (node.offsetWidth !== w) { + loadedCount -= 1; + this.fonts[i].loaded = true; + } + } + if (this.fonts[i].loaded) { + this.fonts[i].sansCase.parent.parentNode.removeChild(this.fonts[i].sansCase.parent); + this.fonts[i].monoCase.parent.parentNode.removeChild(this.fonts[i].monoCase.parent); + } + } + } + if (loadedCount !== 0 && Date.now() - this.initTime < maxWaitingTime) { + setTimeout(this.checkLoadedFontsBinded, 20); + } else { + setTimeout(this.setIsLoadedBinded, 10); + } + } + function createHelper(fontData, def) { + var engine = document.body && def ? "svg" : "canvas"; + var helper; + var fontProps = getFontProperties(fontData); + if (engine === "svg") { + var tHelper = createNS("text"); + tHelper.style.fontSize = "100px"; + tHelper.setAttribute("font-family", fontData.fFamily); + tHelper.setAttribute("font-style", fontProps.style); + tHelper.setAttribute("font-weight", fontProps.weight); + tHelper.textContent = "1"; + if (fontData.fClass) { + tHelper.style.fontFamily = "inherit"; + tHelper.setAttribute("class", fontData.fClass); + } else { + tHelper.style.fontFamily = fontData.fFamily; + } + def.appendChild(tHelper); + helper = tHelper; + } else { + var tCanvasHelper = new OffscreenCanvas(500, 500).getContext("2d"); + tCanvasHelper.font = fontProps.style + " " + fontProps.weight + " 100px " + fontData.fFamily; + helper = tCanvasHelper; + } + function measure(text2) { + if (engine === "svg") { + helper.textContent = text2; + return helper.getComputedTextLength(); + } + return helper.measureText(text2).width; + } + return { + measureText: measure + }; + } + function addFonts(fontData, defs) { + if (!fontData) { + this.isLoaded = true; + return; + } + if (this.chars) { + this.isLoaded = true; + this.fonts = fontData.list; + return; + } + if (!document.body) { + this.isLoaded = true; + fontData.list.forEach((data2) => { + data2.helper = createHelper(data2); + data2.cache = {}; + }); + this.fonts = fontData.list; + return; + } + var fontArr = fontData.list; + var i; + var len = fontArr.length; + var _pendingFonts = len; + for (i = 0;i < len; i += 1) { + var shouldLoadFont = true; + var loadedSelector; + var j2; + fontArr[i].loaded = false; + fontArr[i].monoCase = setUpNode(fontArr[i].fFamily, "monospace"); + fontArr[i].sansCase = setUpNode(fontArr[i].fFamily, "sans-serif"); + if (!fontArr[i].fPath) { + fontArr[i].loaded = true; + _pendingFonts -= 1; + } else if (fontArr[i].fOrigin === "p" || fontArr[i].origin === 3) { + loadedSelector = document.querySelectorAll('style[f-forigin="p"][f-family="' + fontArr[i].fFamily + '"], style[f-origin="3"][f-family="' + fontArr[i].fFamily + '"]'); + if (loadedSelector.length > 0) { + shouldLoadFont = false; + } + if (shouldLoadFont) { + var s = createTag("style"); + s.setAttribute("f-forigin", fontArr[i].fOrigin); + s.setAttribute("f-origin", fontArr[i].origin); + s.setAttribute("f-family", fontArr[i].fFamily); + s.type = "text/css"; + s.innerText = "@font-face {font-family: " + fontArr[i].fFamily + "; font-style: normal; src: url('" + fontArr[i].fPath + "');}"; + defs.appendChild(s); + } + } else if (fontArr[i].fOrigin === "g" || fontArr[i].origin === 1) { + loadedSelector = document.querySelectorAll('link[f-forigin="g"], link[f-origin="1"]'); + for (j2 = 0;j2 < loadedSelector.length; j2 += 1) { + if (loadedSelector[j2].href.indexOf(fontArr[i].fPath) !== -1) { + shouldLoadFont = false; + } + } + if (shouldLoadFont) { + var l2 = createTag("link"); + l2.setAttribute("f-forigin", fontArr[i].fOrigin); + l2.setAttribute("f-origin", fontArr[i].origin); + l2.type = "text/css"; + l2.rel = "stylesheet"; + l2.href = fontArr[i].fPath; + document.body.appendChild(l2); + } + } else if (fontArr[i].fOrigin === "t" || fontArr[i].origin === 2) { + loadedSelector = document.querySelectorAll('script[f-forigin="t"], script[f-origin="2"]'); + for (j2 = 0;j2 < loadedSelector.length; j2 += 1) { + if (fontArr[i].fPath === loadedSelector[j2].src) { + shouldLoadFont = false; + } + } + if (shouldLoadFont) { + var sc = createTag("link"); + sc.setAttribute("f-forigin", fontArr[i].fOrigin); + sc.setAttribute("f-origin", fontArr[i].origin); + sc.setAttribute("rel", "stylesheet"); + sc.setAttribute("href", fontArr[i].fPath); + defs.appendChild(sc); + } + } + fontArr[i].helper = createHelper(fontArr[i], defs); + fontArr[i].cache = {}; + this.fonts.push(fontArr[i]); + } + if (_pendingFonts === 0) { + this.isLoaded = true; + } else { + setTimeout(this.checkLoadedFonts.bind(this), 100); + } + } + function addChars(chars) { + if (!chars) { + return; + } + if (!this.chars) { + this.chars = []; + } + var i; + var len = chars.length; + var j2; + var jLen = this.chars.length; + var found; + for (i = 0;i < len; i += 1) { + j2 = 0; + found = false; + while (j2 < jLen) { + if (this.chars[j2].style === chars[i].style && this.chars[j2].fFamily === chars[i].fFamily && this.chars[j2].ch === chars[i].ch) { + found = true; + } + j2 += 1; + } + if (!found) { + this.chars.push(chars[i]); + jLen += 1; + } + } + } + function getCharData(char, style, font) { + var i = 0; + var len = this.chars.length; + while (i < len) { + if (this.chars[i].ch === char && this.chars[i].style === style && this.chars[i].fFamily === font) { + return this.chars[i]; + } + i += 1; + } + if ((typeof char === "string" && char.charCodeAt(0) !== 13 || !char) && console && console.warn && !this._warned) { + this._warned = true; + console.warn("Missing character from exported characters list: ", char, style, font); + } + return emptyChar; + } + function measureText(char, fontName, size) { + var fontData = this.getFontByName(fontName); + var index2 = char.charCodeAt(0); + if (!fontData.cache[index2 + 1]) { + var tHelper = fontData.helper; + if (char === " ") { + var doubleSize = tHelper.measureText("|" + char + "|"); + var singleSize = tHelper.measureText("||"); + fontData.cache[index2 + 1] = (doubleSize - singleSize) / 100; + } else { + fontData.cache[index2 + 1] = tHelper.measureText(char) / 100; + } + } + return fontData.cache[index2 + 1] * size; + } + function getFontByName(name2) { + var i = 0; + var len = this.fonts.length; + while (i < len) { + if (this.fonts[i].fName === name2) { + return this.fonts[i]; + } + i += 1; + } + return this.fonts[0]; + } + function isModifier(firstCharCode, secondCharCode) { + var sum2 = firstCharCode.toString(16) + secondCharCode.toString(16); + return surrogateModifiers.indexOf(sum2) !== -1; + } + function isZeroWidthJoiner(firstCharCode, secondCharCode) { + if (!secondCharCode) { + return firstCharCode === zeroWidthJoiner[1]; + } + return firstCharCode === zeroWidthJoiner[0] && secondCharCode === zeroWidthJoiner[1]; + } + function isCombinedCharacter(char) { + return combinedCharacters.indexOf(char) !== -1; + } + function setIsLoaded() { + this.isLoaded = true; + } + var Font = function() { + this.fonts = []; + this.chars = null; + this.typekitLoaded = 0; + this.isLoaded = false; + this._warned = false; + this.initTime = Date.now(); + this.setIsLoadedBinded = this.setIsLoaded.bind(this); + this.checkLoadedFontsBinded = this.checkLoadedFonts.bind(this); + }; + Font.isModifier = isModifier; + Font.isZeroWidthJoiner = isZeroWidthJoiner; + Font.isCombinedCharacter = isCombinedCharacter; + var fontPrototype = { + addChars, + addFonts, + getCharData, + getFontByName, + measureText, + checkLoadedFonts, + setIsLoaded + }; + Font.prototype = fontPrototype; + return Font; + }(); + RenderableElement.prototype = { + initRenderable: function() { + this.isInRange = false; + this.hidden = false; + this.isTransparent = false; + this.renderableComponents = []; + }, + addRenderableComponent: function(component) { + if (this.renderableComponents.indexOf(component) === -1) { + this.renderableComponents.push(component); + } + }, + removeRenderableComponent: function(component) { + if (this.renderableComponents.indexOf(component) !== -1) { + this.renderableComponents.splice(this.renderableComponents.indexOf(component), 1); + } + }, + prepareRenderableFrame: function(num) { + this.checkLayerLimits(num); + }, + checkTransparency: function() { + if (this.finalTransform.mProp.o.v <= 0) { + if (!this.isTransparent && this.globalData.renderConfig.hideOnTransparent) { + this.isTransparent = true; + this.hide(); + } + } else if (this.isTransparent) { + this.isTransparent = false; + this.show(); + } + }, + checkLayerLimits: function(num) { + if (this.data.ip - this.data.st <= num && this.data.op - this.data.st > num) { + if (this.isInRange !== true) { + this.globalData._mdf = true; + this._mdf = true; + this.isInRange = true; + this.show(); + } + } else if (this.isInRange !== false) { + this.globalData._mdf = true; + this.isInRange = false; + this.hide(); + } + }, + renderRenderable: function() { + var i; + var len = this.renderableComponents.length; + for (i = 0;i < len; i += 1) { + this.renderableComponents[i].renderFrame(this._isFirstFrame); + } + }, + sourceRectAtTime: function() { + return { + top: 0, + left: 0, + width: 100, + height: 100 + }; + }, + getLayerSize: function() { + if (this.data.ty === 5) { + return { w: this.data.textData.width, h: this.data.textData.height }; + } + return { w: this.data.width, h: this.data.height }; + } + }; + const MaskManagerInterface = function() { + function MaskInterface(mask2, data2) { + this._mask = mask2; + this._data = data2; + } + Object.defineProperty(MaskInterface.prototype, "maskPath", { + get: function() { + if (this._mask.prop.k) { + this._mask.prop.getValue(); + } + return this._mask.prop; + } + }); + Object.defineProperty(MaskInterface.prototype, "maskOpacity", { + get: function() { + if (this._mask.op.k) { + this._mask.op.getValue(); + } + return this._mask.op.v * 100; + } + }); + var MaskManager = function(maskManager) { + var _masksInterfaces = createSizedArray(maskManager.viewData.length); + var i; + var len = maskManager.viewData.length; + for (i = 0;i < len; i += 1) { + _masksInterfaces[i] = new MaskInterface(maskManager.viewData[i], maskManager.masksProperties[i]); + } + var maskFunction = function(name2) { + i = 0; + while (i < len) { + if (maskManager.masksProperties[i].nm === name2) { + return _masksInterfaces[i]; + } + i += 1; + } + return null; + }; + return maskFunction; + }; + return MaskManager; + }(); + const ExpressionPropertyInterface = function() { + var defaultUnidimensionalValue = { pv: 0, v: 0, mult: 1 }; + var defaultMultidimensionalValue = { pv: [0, 0, 0], v: [0, 0, 0], mult: 1 }; + function completeProperty(expressionValue, property2, type) { + Object.defineProperty(expressionValue, "velocity", { + get: function() { + return property2.getVelocityAtTime(property2.comp.currentFrame); + } + }); + expressionValue.numKeys = property2.keyframes ? property2.keyframes.length : 0; + expressionValue.key = function(pos) { + if (!expressionValue.numKeys) { + return 0; + } + var value2 = ""; + if ("s" in property2.keyframes[pos - 1]) { + value2 = property2.keyframes[pos - 1].s; + } else if ("e" in property2.keyframes[pos - 2]) { + value2 = property2.keyframes[pos - 2].e; + } else { + value2 = property2.keyframes[pos - 2].s; + } + var valueProp = type === "unidimensional" ? new Number(value2) : Object.assign({}, value2); + valueProp.time = property2.keyframes[pos - 1].t / property2.elem.comp.globalData.frameRate; + valueProp.value = type === "unidimensional" ? value2[0] : value2; + return valueProp; + }; + expressionValue.valueAtTime = property2.getValueAtTime; + expressionValue.speedAtTime = property2.getSpeedAtTime; + expressionValue.velocityAtTime = property2.getVelocityAtTime; + expressionValue.propertyGroup = property2.propertyGroup; + } + function UnidimensionalPropertyInterface(property2) { + if (!property2 || !("pv" in property2)) { + property2 = defaultUnidimensionalValue; + } + var mult = 1 / property2.mult; + var val2 = property2.pv * mult; + var expressionValue = new Number(val2); + expressionValue.value = val2; + completeProperty(expressionValue, property2, "unidimensional"); + return function() { + if (property2.k) { + property2.getValue(); + } + val2 = property2.v * mult; + if (expressionValue.value !== val2) { + expressionValue = new Number(val2); + expressionValue.value = val2; + completeProperty(expressionValue, property2, "unidimensional"); + } + return expressionValue; + }; + } + function MultidimensionalPropertyInterface(property2) { + if (!property2 || !("pv" in property2)) { + property2 = defaultMultidimensionalValue; + } + var mult = 1 / property2.mult; + var len = property2.data && property2.data.l || property2.pv.length; + var expressionValue = createTypedArray("float32", len); + var arrValue = createTypedArray("float32", len); + expressionValue.value = arrValue; + completeProperty(expressionValue, property2, "multidimensional"); + return function() { + if (property2.k) { + property2.getValue(); + } + for (var i = 0;i < len; i += 1) { + arrValue[i] = property2.v[i] * mult; + expressionValue[i] = arrValue[i]; + } + return expressionValue; + }; + } + function defaultGetter() { + return defaultUnidimensionalValue; + } + return function(property2) { + if (!property2) { + return defaultGetter; + } + if (property2.propType === "unidimensional") { + return UnidimensionalPropertyInterface(property2); + } + return MultidimensionalPropertyInterface(property2); + }; + }(); + const TransformExpressionInterface = function() { + return function(transform2) { + function _thisFunction(name2) { + switch (name2) { + case "scale": + case "Scale": + case "ADBE Scale": + case 6: + return _thisFunction.scale; + case "rotation": + case "Rotation": + case "ADBE Rotation": + case "ADBE Rotate Z": + case 10: + return _thisFunction.rotation; + case "ADBE Rotate X": + return _thisFunction.xRotation; + case "ADBE Rotate Y": + return _thisFunction.yRotation; + case "position": + case "Position": + case "ADBE Position": + case 2: + return _thisFunction.position; + case "ADBE Position_0": + return _thisFunction.xPosition; + case "ADBE Position_1": + return _thisFunction.yPosition; + case "ADBE Position_2": + return _thisFunction.zPosition; + case "anchorPoint": + case "AnchorPoint": + case "Anchor Point": + case "ADBE AnchorPoint": + case 1: + return _thisFunction.anchorPoint; + case "opacity": + case "Opacity": + case 11: + return _thisFunction.opacity; + default: + return null; + } + } + Object.defineProperty(_thisFunction, "rotation", { + get: ExpressionPropertyInterface(transform2.r || transform2.rz) + }); + Object.defineProperty(_thisFunction, "zRotation", { + get: ExpressionPropertyInterface(transform2.rz || transform2.r) + }); + Object.defineProperty(_thisFunction, "xRotation", { + get: ExpressionPropertyInterface(transform2.rx) + }); + Object.defineProperty(_thisFunction, "yRotation", { + get: ExpressionPropertyInterface(transform2.ry) + }); + Object.defineProperty(_thisFunction, "scale", { + get: ExpressionPropertyInterface(transform2.s) + }); + var _px; + var _py; + var _pz; + var _transformFactory; + if (transform2.p) { + _transformFactory = ExpressionPropertyInterface(transform2.p); + } else { + _px = ExpressionPropertyInterface(transform2.px); + _py = ExpressionPropertyInterface(transform2.py); + if (transform2.pz) { + _pz = ExpressionPropertyInterface(transform2.pz); + } + } + Object.defineProperty(_thisFunction, "position", { + get: function() { + if (transform2.p) { + return _transformFactory(); + } + return [ + _px(), + _py(), + _pz ? _pz() : 0 + ]; + } + }); + Object.defineProperty(_thisFunction, "xPosition", { + get: ExpressionPropertyInterface(transform2.px) + }); + Object.defineProperty(_thisFunction, "yPosition", { + get: ExpressionPropertyInterface(transform2.py) + }); + Object.defineProperty(_thisFunction, "zPosition", { + get: ExpressionPropertyInterface(transform2.pz) + }); + Object.defineProperty(_thisFunction, "anchorPoint", { + get: ExpressionPropertyInterface(transform2.a) + }); + Object.defineProperty(_thisFunction, "opacity", { + get: ExpressionPropertyInterface(transform2.o) + }); + Object.defineProperty(_thisFunction, "skew", { + get: ExpressionPropertyInterface(transform2.sk) + }); + Object.defineProperty(_thisFunction, "skewAxis", { + get: ExpressionPropertyInterface(transform2.sa) + }); + Object.defineProperty(_thisFunction, "orientation", { + get: ExpressionPropertyInterface(transform2.or) + }); + return _thisFunction; + }; + }(); + const LayerExpressionInterface = function() { + function getMatrix(time2) { + var toWorldMat = new Matrix; + if (time2 !== undefined) { + var propMatrix = this._elem.finalTransform.mProp.getValueAtTime(time2); + propMatrix.clone(toWorldMat); + } else { + var transformMat = this._elem.finalTransform.mProp; + transformMat.applyToMatrix(toWorldMat); + } + return toWorldMat; + } + function toWorldVec(arr, time2) { + var toWorldMat = this.getMatrix(time2); + toWorldMat.props[12] = 0; + toWorldMat.props[13] = 0; + toWorldMat.props[14] = 0; + return this.applyPoint(toWorldMat, arr); + } + function toWorld2(arr, time2) { + var toWorldMat = this.getMatrix(time2); + return this.applyPoint(toWorldMat, arr); + } + function fromWorldVec(arr, time2) { + var toWorldMat = this.getMatrix(time2); + toWorldMat.props[12] = 0; + toWorldMat.props[13] = 0; + toWorldMat.props[14] = 0; + return this.invertPoint(toWorldMat, arr); + } + function fromWorld2(arr, time2) { + var toWorldMat = this.getMatrix(time2); + return this.invertPoint(toWorldMat, arr); + } + function applyPoint(matrix, arr) { + if (this._elem.hierarchy && this._elem.hierarchy.length) { + var i; + var len = this._elem.hierarchy.length; + for (i = 0;i < len; i += 1) { + this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(matrix); + } + } + return matrix.applyToPointArray(arr[0], arr[1], arr[2] || 0); + } + function invertPoint(matrix, arr) { + if (this._elem.hierarchy && this._elem.hierarchy.length) { + var i; + var len = this._elem.hierarchy.length; + for (i = 0;i < len; i += 1) { + this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(matrix); + } + } + return matrix.inversePoint(arr); + } + function fromComp2(arr) { + var toWorldMat = new Matrix; + toWorldMat.reset(); + this._elem.finalTransform.mProp.applyToMatrix(toWorldMat); + if (this._elem.hierarchy && this._elem.hierarchy.length) { + var i; + var len = this._elem.hierarchy.length; + for (i = 0;i < len; i += 1) { + this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(toWorldMat); + } + return toWorldMat.inversePoint(arr); + } + return toWorldMat.inversePoint(arr); + } + function sampleImage() { + return [1, 1, 1, 1]; + } + return function(elem2) { + var transformInterface; + function _registerMaskInterface(maskManager) { + _thisLayerFunction.mask = new MaskManagerInterface(maskManager, elem2); + } + function _registerEffectsInterface(effects) { + _thisLayerFunction.effect = effects; + } + function _thisLayerFunction(name2) { + switch (name2) { + case "ADBE Root Vectors Group": + case "Contents": + case 2: + return _thisLayerFunction.shapeInterface; + case 1: + case 6: + case "Transform": + case "transform": + case "ADBE Transform Group": + return transformInterface; + case 4: + case "ADBE Effect Parade": + case "effects": + case "Effects": + return _thisLayerFunction.effect; + case "ADBE Text Properties": + return _thisLayerFunction.textInterface; + default: + return null; + } + } + _thisLayerFunction.getMatrix = getMatrix; + _thisLayerFunction.invertPoint = invertPoint; + _thisLayerFunction.applyPoint = applyPoint; + _thisLayerFunction.toWorld = toWorld2; + _thisLayerFunction.toWorldVec = toWorldVec; + _thisLayerFunction.fromWorld = fromWorld2; + _thisLayerFunction.fromWorldVec = fromWorldVec; + _thisLayerFunction.toComp = toWorld2; + _thisLayerFunction.fromComp = fromComp2; + _thisLayerFunction.sampleImage = sampleImage; + _thisLayerFunction.sourceRectAtTime = elem2.sourceRectAtTime.bind(elem2); + _thisLayerFunction._elem = elem2; + transformInterface = TransformExpressionInterface(elem2.finalTransform.mProp); + var anchorPointDescriptor = getDescriptor(transformInterface, "anchorPoint"); + Object.defineProperties(_thisLayerFunction, { + hasParent: { + get: function() { + return elem2.hierarchy.length; + } + }, + parent: { + get: function() { + return elem2.hierarchy[0].layerInterface; + } + }, + rotation: getDescriptor(transformInterface, "rotation"), + scale: getDescriptor(transformInterface, "scale"), + position: getDescriptor(transformInterface, "position"), + opacity: getDescriptor(transformInterface, "opacity"), + anchorPoint: anchorPointDescriptor, + anchor_point: anchorPointDescriptor, + transform: { + get: function() { + return transformInterface; + } + }, + active: { + get: function() { + return elem2.isInRange; + } + } + }); + _thisLayerFunction.startTime = elem2.data.st; + _thisLayerFunction.index = elem2.data.ind; + _thisLayerFunction.source = elem2.data.refId; + _thisLayerFunction.height = elem2.data.ty === 0 ? elem2.data.h : 100; + _thisLayerFunction.width = elem2.data.ty === 0 ? elem2.data.w : 100; + _thisLayerFunction.inPoint = elem2.data.ip / elem2.comp.globalData.frameRate; + _thisLayerFunction.outPoint = elem2.data.op / elem2.comp.globalData.frameRate; + _thisLayerFunction._name = elem2.data.nm; + _thisLayerFunction.registerMaskInterface = _registerMaskInterface; + _thisLayerFunction.registerEffectsInterface = _registerEffectsInterface; + return _thisLayerFunction; + }; + }(); + const propertyGroupFactory = function() { + return function(interfaceFunction, parentPropertyGroup) { + return function(val2) { + val2 = val2 === undefined ? 1 : val2; + if (val2 <= 0) { + return interfaceFunction; + } + return parentPropertyGroup(val2 - 1); + }; + }; + }(); + const PropertyInterface = function() { + return function(propertyName, propertyGroup) { + var interfaceFunction = { + _name: propertyName + }; + function _propertyGroup(val2) { + val2 = val2 === undefined ? 1 : val2; + if (val2 <= 0) { + return interfaceFunction; + } + return propertyGroup(val2 - 1); + } + return _propertyGroup; + }; + }(); + const EffectsExpressionInterface = function() { + var ob2 = { + createEffectsInterface + }; + function createEffectsInterface(elem2, propertyGroup) { + if (elem2.effectsManager) { + var effectElements = []; + var effectsData = elem2.data.ef; + var i; + var len = elem2.effectsManager.effectElements.length; + for (i = 0;i < len; i += 1) { + effectElements.push(createGroupInterface(effectsData[i], elem2.effectsManager.effectElements[i], propertyGroup, elem2)); + } + var effects = elem2.data.ef || []; + var groupInterface = function(name2) { + i = 0; + len = effects.length; + while (i < len) { + if (name2 === effects[i].nm || name2 === effects[i].mn || name2 === effects[i].ix) { + return effectElements[i]; + } + i += 1; + } + return null; + }; + Object.defineProperty(groupInterface, "numProperties", { + get: function() { + return effects.length; + } + }); + return groupInterface; + } + return null; + } + function createGroupInterface(data2, elements, propertyGroup, elem2) { + function groupInterface(name2) { + var effects = data2.ef; + var i3 = 0; + var len2 = effects.length; + while (i3 < len2) { + if (name2 === effects[i3].nm || name2 === effects[i3].mn || name2 === effects[i3].ix) { + if (effects[i3].ty === 5) { + return effectElements[i3]; + } + return effectElements[i3](); + } + i3 += 1; + } + throw new Error; + } + var _propertyGroup = propertyGroupFactory(groupInterface, propertyGroup); + var effectElements = []; + var i; + var len = data2.ef.length; + for (i = 0;i < len; i += 1) { + if (data2.ef[i].ty === 5) { + effectElements.push(createGroupInterface(data2.ef[i], elements.effectElements[i], elements.effectElements[i].propertyGroup, elem2)); + } else { + effectElements.push(createValueInterface(elements.effectElements[i], data2.ef[i].ty, elem2, _propertyGroup)); + } + } + if (data2.mn === "ADBE Color Control") { + Object.defineProperty(groupInterface, "color", { + get: function() { + return effectElements[0](); + } + }); + } + Object.defineProperties(groupInterface, { + numProperties: { + get: function() { + return data2.np; + } + }, + _name: { value: data2.nm }, + propertyGroup: { value: _propertyGroup } + }); + groupInterface.enabled = data2.en !== 0; + groupInterface.active = groupInterface.enabled; + return groupInterface; + } + function createValueInterface(element, type, elem2, propertyGroup) { + var expressionProperty = ExpressionPropertyInterface(element.p); + function interfaceFunction() { + if (type === 10) { + return elem2.comp.compInterface(element.p.v); + } + return expressionProperty(); + } + if (element.p.setGroupProperty) { + element.p.setGroupProperty(PropertyInterface("", propertyGroup)); + } + return interfaceFunction; + } + return ob2; + }(); + const CompExpressionInterface = function() { + return function(comp2) { + function _thisLayerFunction(name2) { + var i = 0; + var len = comp2.layers.length; + while (i < len) { + if (comp2.layers[i].nm === name2 || comp2.layers[i].ind === name2) { + return comp2.elements[i].layerInterface; + } + i += 1; + } + return null; + } + Object.defineProperty(_thisLayerFunction, "_name", { value: comp2.data.nm }); + _thisLayerFunction.layer = _thisLayerFunction; + _thisLayerFunction.pixelAspect = 1; + _thisLayerFunction.height = comp2.data.h || comp2.globalData.compSize.h; + _thisLayerFunction.width = comp2.data.w || comp2.globalData.compSize.w; + _thisLayerFunction.pixelAspect = 1; + _thisLayerFunction.frameDuration = 1 / comp2.globalData.frameRate; + _thisLayerFunction.displayStartTime = 0; + _thisLayerFunction.numLayers = comp2.layers.length; + return _thisLayerFunction; + }; + }(); + const ShapePathInterface = function() { + return function pathInterfaceFactory(shape, view, propertyGroup) { + var prop = view.sh; + function interfaceFunction(val2) { + if (val2 === "Shape" || val2 === "shape" || val2 === "Path" || val2 === "path" || val2 === "ADBE Vector Shape" || val2 === 2) { + return interfaceFunction.path; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + prop.setGroupProperty(PropertyInterface("Path", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + path: { + get: function() { + if (prop.k) { + prop.getValue(); + } + return prop; + } + }, + shape: { + get: function() { + if (prop.k) { + prop.getValue(); + } + return prop; + } + }, + _name: { value: shape.nm }, + ix: { value: shape.ix }, + propertyIndex: { value: shape.ix }, + mn: { value: shape.mn }, + propertyGroup: { value: propertyGroup } + }); + return interfaceFunction; + }; + }(); + const ShapeExpressionInterface = function() { + function iterateElements(shapes, view, propertyGroup) { + var arr = []; + var i; + var len = shapes ? shapes.length : 0; + for (i = 0;i < len; i += 1) { + if (shapes[i].ty === "gr") { + arr.push(groupInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "fl") { + arr.push(fillInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "st") { + arr.push(strokeInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "tm") { + arr.push(trimInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "tr") { + } else if (shapes[i].ty === "el") { + arr.push(ellipseInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "sr") { + arr.push(starInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "sh") { + arr.push(ShapePathInterface(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "rc") { + arr.push(rectInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "rd") { + arr.push(roundedInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "rp") { + arr.push(repeaterInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "gf") { + arr.push(gradientFillInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else { + arr.push(defaultInterfaceFactory(shapes[i], view[i], propertyGroup)); + } + } + return arr; + } + function contentsInterfaceFactory(shape, view, propertyGroup) { + var interfaces; + var interfaceFunction = function _interfaceFunction(value2) { + var i = 0; + var len = interfaces.length; + while (i < len) { + if (interfaces[i]._name === value2 || interfaces[i].mn === value2 || interfaces[i].propertyIndex === value2 || interfaces[i].ix === value2 || interfaces[i].ind === value2) { + return interfaces[i]; + } + i += 1; + } + if (typeof value2 === "number") { + return interfaces[value2 - 1]; + } + return null; + }; + interfaceFunction.propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + interfaces = iterateElements(shape.it, view.it, interfaceFunction.propertyGroup); + interfaceFunction.numProperties = interfaces.length; + var transformInterface = transformInterfaceFactory(shape.it[shape.it.length - 1], view.it[view.it.length - 1], interfaceFunction.propertyGroup); + interfaceFunction.transform = transformInterface; + interfaceFunction.propertyIndex = shape.cix; + interfaceFunction._name = shape.nm; + return interfaceFunction; + } + function groupInterfaceFactory(shape, view, propertyGroup) { + var interfaceFunction = function _interfaceFunction(value2) { + switch (value2) { + case "ADBE Vectors Group": + case "Contents": + case 2: + return interfaceFunction.content; + default: + return interfaceFunction.transform; + } + }; + interfaceFunction.propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var content2 = contentsInterfaceFactory(shape, view, interfaceFunction.propertyGroup); + var transformInterface = transformInterfaceFactory(shape.it[shape.it.length - 1], view.it[view.it.length - 1], interfaceFunction.propertyGroup); + interfaceFunction.content = content2; + interfaceFunction.transform = transformInterface; + Object.defineProperty(interfaceFunction, "_name", { + get: function() { + return shape.nm; + } + }); + interfaceFunction.numProperties = shape.np; + interfaceFunction.propertyIndex = shape.ix; + interfaceFunction.nm = shape.nm; + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function fillInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(val2) { + if (val2 === "Color" || val2 === "color") { + return interfaceFunction.color; + } + if (val2 === "Opacity" || val2 === "opacity") { + return interfaceFunction.opacity; + } + return null; + } + Object.defineProperties(interfaceFunction, { + color: { + get: ExpressionPropertyInterface(view.c) + }, + opacity: { + get: ExpressionPropertyInterface(view.o) + }, + _name: { value: shape.nm }, + mn: { value: shape.mn } + }); + view.c.setGroupProperty(PropertyInterface("Color", propertyGroup)); + view.o.setGroupProperty(PropertyInterface("Opacity", propertyGroup)); + return interfaceFunction; + } + function gradientFillInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(val2) { + if (val2 === "Start Point" || val2 === "start point") { + return interfaceFunction.startPoint; + } + if (val2 === "End Point" || val2 === "end point") { + return interfaceFunction.endPoint; + } + if (val2 === "Opacity" || val2 === "opacity") { + return interfaceFunction.opacity; + } + return null; + } + Object.defineProperties(interfaceFunction, { + startPoint: { + get: ExpressionPropertyInterface(view.s) + }, + endPoint: { + get: ExpressionPropertyInterface(view.e) + }, + opacity: { + get: ExpressionPropertyInterface(view.o) + }, + type: { + get: function() { + return "a"; + } + }, + _name: { value: shape.nm }, + mn: { value: shape.mn } + }); + view.s.setGroupProperty(PropertyInterface("Start Point", propertyGroup)); + view.e.setGroupProperty(PropertyInterface("End Point", propertyGroup)); + view.o.setGroupProperty(PropertyInterface("Opacity", propertyGroup)); + return interfaceFunction; + } + function defaultInterfaceFactory() { + function interfaceFunction() { + return null; + } + return interfaceFunction; + } + function strokeInterfaceFactory(shape, view, propertyGroup) { + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var _dashPropertyGroup = propertyGroupFactory(dashOb, _propertyGroup); + function addPropertyToDashOb(i3) { + Object.defineProperty(dashOb, shape.d[i3].nm, { + get: ExpressionPropertyInterface(view.d.dataProps[i3].p) + }); + } + var i; + var len = shape.d ? shape.d.length : 0; + var dashOb = {}; + for (i = 0;i < len; i += 1) { + addPropertyToDashOb(i); + view.d.dataProps[i].p.setGroupProperty(_dashPropertyGroup); + } + function interfaceFunction(val2) { + if (val2 === "Color" || val2 === "color") { + return interfaceFunction.color; + } + if (val2 === "Opacity" || val2 === "opacity") { + return interfaceFunction.opacity; + } + if (val2 === "Stroke Width" || val2 === "stroke width") { + return interfaceFunction.strokeWidth; + } + return null; + } + Object.defineProperties(interfaceFunction, { + color: { + get: ExpressionPropertyInterface(view.c) + }, + opacity: { + get: ExpressionPropertyInterface(view.o) + }, + strokeWidth: { + get: ExpressionPropertyInterface(view.w) + }, + dash: { + get: function() { + return dashOb; + } + }, + _name: { value: shape.nm }, + mn: { value: shape.mn } + }); + view.c.setGroupProperty(PropertyInterface("Color", _propertyGroup)); + view.o.setGroupProperty(PropertyInterface("Opacity", _propertyGroup)); + view.w.setGroupProperty(PropertyInterface("Stroke Width", _propertyGroup)); + return interfaceFunction; + } + function trimInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(val2) { + if (val2 === shape.e.ix || val2 === "End" || val2 === "end") { + return interfaceFunction.end; + } + if (val2 === shape.s.ix) { + return interfaceFunction.start; + } + if (val2 === shape.o.ix) { + return interfaceFunction.offset; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + interfaceFunction.propertyIndex = shape.ix; + view.s.setGroupProperty(PropertyInterface("Start", _propertyGroup)); + view.e.setGroupProperty(PropertyInterface("End", _propertyGroup)); + view.o.setGroupProperty(PropertyInterface("Offset", _propertyGroup)); + interfaceFunction.propertyIndex = shape.ix; + interfaceFunction.propertyGroup = propertyGroup; + Object.defineProperties(interfaceFunction, { + start: { + get: ExpressionPropertyInterface(view.s) + }, + end: { + get: ExpressionPropertyInterface(view.e) + }, + offset: { + get: ExpressionPropertyInterface(view.o) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function transformInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.a.ix === value2 || value2 === "Anchor Point") { + return interfaceFunction.anchorPoint; + } + if (shape.o.ix === value2 || value2 === "Opacity") { + return interfaceFunction.opacity; + } + if (shape.p.ix === value2 || value2 === "Position") { + return interfaceFunction.position; + } + if (shape.r.ix === value2 || value2 === "Rotation" || value2 === "ADBE Vector Rotation") { + return interfaceFunction.rotation; + } + if (shape.s.ix === value2 || value2 === "Scale") { + return interfaceFunction.scale; + } + if (shape.sk && shape.sk.ix === value2 || value2 === "Skew") { + return interfaceFunction.skew; + } + if (shape.sa && shape.sa.ix === value2 || value2 === "Skew Axis") { + return interfaceFunction.skewAxis; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + view.transform.mProps.o.setGroupProperty(PropertyInterface("Opacity", _propertyGroup)); + view.transform.mProps.p.setGroupProperty(PropertyInterface("Position", _propertyGroup)); + view.transform.mProps.a.setGroupProperty(PropertyInterface("Anchor Point", _propertyGroup)); + view.transform.mProps.s.setGroupProperty(PropertyInterface("Scale", _propertyGroup)); + view.transform.mProps.r.setGroupProperty(PropertyInterface("Rotation", _propertyGroup)); + if (view.transform.mProps.sk) { + view.transform.mProps.sk.setGroupProperty(PropertyInterface("Skew", _propertyGroup)); + view.transform.mProps.sa.setGroupProperty(PropertyInterface("Skew Angle", _propertyGroup)); + } + view.transform.op.setGroupProperty(PropertyInterface("Opacity", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + opacity: { + get: ExpressionPropertyInterface(view.transform.mProps.o) + }, + position: { + get: ExpressionPropertyInterface(view.transform.mProps.p) + }, + anchorPoint: { + get: ExpressionPropertyInterface(view.transform.mProps.a) + }, + scale: { + get: ExpressionPropertyInterface(view.transform.mProps.s) + }, + rotation: { + get: ExpressionPropertyInterface(view.transform.mProps.r) + }, + skew: { + get: ExpressionPropertyInterface(view.transform.mProps.sk) + }, + skewAxis: { + get: ExpressionPropertyInterface(view.transform.mProps.sa) + }, + _name: { value: shape.nm } + }); + interfaceFunction.ty = "tr"; + interfaceFunction.mn = shape.mn; + interfaceFunction.propertyGroup = propertyGroup; + return interfaceFunction; + } + function ellipseInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.p.ix === value2) { + return interfaceFunction.position; + } + if (shape.s.ix === value2) { + return interfaceFunction.size; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + interfaceFunction.propertyIndex = shape.ix; + var prop = view.sh.ty === "tm" ? view.sh.prop : view.sh; + prop.s.setGroupProperty(PropertyInterface("Size", _propertyGroup)); + prop.p.setGroupProperty(PropertyInterface("Position", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + size: { + get: ExpressionPropertyInterface(prop.s) + }, + position: { + get: ExpressionPropertyInterface(prop.p) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function starInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.p.ix === value2) { + return interfaceFunction.position; + } + if (shape.r.ix === value2) { + return interfaceFunction.rotation; + } + if (shape.pt.ix === value2) { + return interfaceFunction.points; + } + if (shape.or.ix === value2 || value2 === "ADBE Vector Star Outer Radius") { + return interfaceFunction.outerRadius; + } + if (shape.os.ix === value2) { + return interfaceFunction.outerRoundness; + } + if (shape.ir && (shape.ir.ix === value2 || value2 === "ADBE Vector Star Inner Radius")) { + return interfaceFunction.innerRadius; + } + if (shape.is && shape.is.ix === value2) { + return interfaceFunction.innerRoundness; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var prop = view.sh.ty === "tm" ? view.sh.prop : view.sh; + interfaceFunction.propertyIndex = shape.ix; + prop.or.setGroupProperty(PropertyInterface("Outer Radius", _propertyGroup)); + prop.os.setGroupProperty(PropertyInterface("Outer Roundness", _propertyGroup)); + prop.pt.setGroupProperty(PropertyInterface("Points", _propertyGroup)); + prop.p.setGroupProperty(PropertyInterface("Position", _propertyGroup)); + prop.r.setGroupProperty(PropertyInterface("Rotation", _propertyGroup)); + if (shape.ir) { + prop.ir.setGroupProperty(PropertyInterface("Inner Radius", _propertyGroup)); + prop.is.setGroupProperty(PropertyInterface("Inner Roundness", _propertyGroup)); + } + Object.defineProperties(interfaceFunction, { + position: { + get: ExpressionPropertyInterface(prop.p) + }, + rotation: { + get: ExpressionPropertyInterface(prop.r) + }, + points: { + get: ExpressionPropertyInterface(prop.pt) + }, + outerRadius: { + get: ExpressionPropertyInterface(prop.or) + }, + outerRoundness: { + get: ExpressionPropertyInterface(prop.os) + }, + innerRadius: { + get: ExpressionPropertyInterface(prop.ir) + }, + innerRoundness: { + get: ExpressionPropertyInterface(prop.is) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function rectInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.p.ix === value2) { + return interfaceFunction.position; + } + if (shape.r.ix === value2) { + return interfaceFunction.roundness; + } + if (shape.s.ix === value2 || value2 === "Size" || value2 === "ADBE Vector Rect Size") { + return interfaceFunction.size; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var prop = view.sh.ty === "tm" ? view.sh.prop : view.sh; + interfaceFunction.propertyIndex = shape.ix; + prop.p.setGroupProperty(PropertyInterface("Position", _propertyGroup)); + prop.s.setGroupProperty(PropertyInterface("Size", _propertyGroup)); + prop.r.setGroupProperty(PropertyInterface("Rotation", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + position: { + get: ExpressionPropertyInterface(prop.p) + }, + roundness: { + get: ExpressionPropertyInterface(prop.r) + }, + size: { + get: ExpressionPropertyInterface(prop.s) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function roundedInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.r.ix === value2 || value2 === "Round Corners 1") { + return interfaceFunction.radius; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var prop = view; + interfaceFunction.propertyIndex = shape.ix; + prop.rd.setGroupProperty(PropertyInterface("Radius", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + radius: { + get: ExpressionPropertyInterface(prop.rd) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function repeaterInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.c.ix === value2 || value2 === "Copies") { + return interfaceFunction.copies; + } + if (shape.o.ix === value2 || value2 === "Offset") { + return interfaceFunction.offset; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var prop = view; + interfaceFunction.propertyIndex = shape.ix; + prop.c.setGroupProperty(PropertyInterface("Copies", _propertyGroup)); + prop.o.setGroupProperty(PropertyInterface("Offset", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + copies: { + get: ExpressionPropertyInterface(prop.c) + }, + offset: { + get: ExpressionPropertyInterface(prop.o) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + return function(shapes, view, propertyGroup) { + var interfaces; + function _interfaceFunction(value2) { + if (typeof value2 === "number") { + value2 = value2 === undefined ? 1 : value2; + if (value2 === 0) { + return propertyGroup; + } + return interfaces[value2 - 1]; + } + var i = 0; + var len = interfaces.length; + while (i < len) { + if (interfaces[i]._name === value2) { + return interfaces[i]; + } + i += 1; + } + return null; + } + function parentGroupWrapper() { + return propertyGroup; + } + _interfaceFunction.propertyGroup = propertyGroupFactory(_interfaceFunction, parentGroupWrapper); + interfaces = iterateElements(shapes, view, _interfaceFunction.propertyGroup); + _interfaceFunction.numProperties = interfaces.length; + _interfaceFunction._name = "Contents"; + return _interfaceFunction; + }; + }(); + const TextExpressionInterface = function() { + return function(elem2) { + var _prevValue; + var _sourceText; + function _thisLayerFunction(name2) { + switch (name2) { + case "ADBE Text Document": + return _thisLayerFunction.sourceText; + default: + return null; + } + } + Object.defineProperty(_thisLayerFunction, "sourceText", { + get: function() { + elem2.textProperty.getValue(); + var stringValue = elem2.textProperty.currentData.t; + if (stringValue !== _prevValue) { + elem2.textProperty.currentData.t = _prevValue; + _sourceText = new String(stringValue); + _sourceText.value = stringValue || new String(stringValue); + } + return _sourceText; + } + }); + return _thisLayerFunction; + }; + }(); + const getBlendMode = function() { + var blendModeEnums = { + 0: "source-over", + 1: "multiply", + 2: "screen", + 3: "overlay", + 4: "darken", + 5: "lighten", + 6: "color-dodge", + 7: "color-burn", + 8: "hard-light", + 9: "soft-light", + 10: "difference", + 11: "exclusion", + 12: "hue", + 13: "saturation", + 14: "color", + 15: "luminosity" + }; + return function(mode) { + return blendModeEnums[mode] || ""; + }; + }(); + extendPrototype([DynamicPropertyContainer], GroupEffect); + GroupEffect.prototype.getValue = GroupEffect.prototype.iterateDynamicProperties; + GroupEffect.prototype.init = function(data2, element) { + this.data = data2; + this.effectElements = []; + this.initDynamicPropertyContainer(element); + var i; + var len = this.data.ef.length; + var eff; + var effects = this.data.ef; + for (i = 0;i < len; i += 1) { + eff = null; + switch (effects[i].ty) { + case 0: + eff = new SliderEffect(effects[i], element, this); + break; + case 1: + eff = new AngleEffect(effects[i], element, this); + break; + case 2: + eff = new ColorEffect(effects[i], element, this); + break; + case 3: + eff = new PointEffect(effects[i], element, this); + break; + case 4: + case 7: + eff = new CheckboxEffect(effects[i], element, this); + break; + case 10: + eff = new LayerIndexEffect(effects[i], element, this); + break; + case 11: + eff = new MaskIndexEffect(effects[i], element, this); + break; + case 5: + eff = new EffectsManager(effects[i], element, this); + break; + default: + eff = new NoValueEffect(effects[i], element, this); + break; + } + if (eff) { + this.effectElements.push(eff); + } + } + }; + BaseElement.prototype = { + checkMasks: function() { + if (!this.data.hasMask) { + return false; + } + var i = 0; + var len = this.data.masksProperties.length; + while (i < len) { + if (this.data.masksProperties[i].mode !== "n" && this.data.masksProperties[i].cl !== false) { + return true; + } + i += 1; + } + return false; + }, + initExpressions: function() { + this.layerInterface = LayerExpressionInterface(this); + if (this.data.hasMask && this.maskManager) { + this.layerInterface.registerMaskInterface(this.maskManager); + } + var effectsInterface = EffectsExpressionInterface.createEffectsInterface(this, this.layerInterface); + this.layerInterface.registerEffectsInterface(effectsInterface); + if (this.data.ty === 0 || this.data.xt) { + this.compInterface = CompExpressionInterface(this); + } else if (this.data.ty === 4) { + this.layerInterface.shapeInterface = ShapeExpressionInterface(this.shapesData, this.itemsData, this.layerInterface); + this.layerInterface.content = this.layerInterface.shapeInterface; + } else if (this.data.ty === 5) { + this.layerInterface.textInterface = TextExpressionInterface(this); + this.layerInterface.text = this.layerInterface.textInterface; + } + }, + setBlendMode: function() { + var blendModeValue = getBlendMode(this.data.bm); + var elem2 = this.baseElement || this.layerElement; + elem2.style["mix-blend-mode"] = blendModeValue; + }, + initBaseData: function(data2, globalData2, comp2) { + this.globalData = globalData2; + this.comp = comp2; + this.data = data2; + this.layerId = createElementID(); + if (!this.data.sr) { + this.data.sr = 1; + } + this.effectsManager = new EffectsManager(this.data, this, this.dynamicProperties); + }, + getType: function() { + return this.type; + }, + sourceRectAtTime: function() { + } + }; + FrameElement.prototype = { + initFrame: function() { + this._isFirstFrame = false; + this.dynamicProperties = []; + this._mdf = false; + }, + prepareProperties: function(num, isVisible) { + var i; + var len = this.dynamicProperties.length; + for (i = 0;i < len; i += 1) { + if (isVisible || this._isParent && this.dynamicProperties[i].propType === "transform") { + this.dynamicProperties[i].getValue(); + if (this.dynamicProperties[i]._mdf) { + this.globalData._mdf = true; + this._mdf = true; + } + } + } + }, + addDynamicProperty: function(prop) { + if (this.dynamicProperties.indexOf(prop) === -1) { + this.dynamicProperties.push(prop); + } + } + }; + const FootageInterface = function() { + var outlineInterfaceFactory = function(elem2) { + var currentPropertyName = ""; + var currentProperty = elem2.getFootageData(); + function init() { + currentPropertyName = ""; + currentProperty = elem2.getFootageData(); + return searchProperty; + } + function searchProperty(value2) { + if (currentProperty[value2]) { + currentPropertyName = value2; + currentProperty = currentProperty[value2]; + if (typeof currentProperty === "object") { + return searchProperty; + } + return currentProperty; + } + var propertyNameIndex = value2.indexOf(currentPropertyName); + if (propertyNameIndex !== -1) { + var index2 = parseInt(value2.substr(propertyNameIndex + currentPropertyName.length), 10); + currentProperty = currentProperty[index2]; + if (typeof currentProperty === "object") { + return searchProperty; + } + return currentProperty; + } + return ""; + } + return init; + }; + var dataInterfaceFactory = function(elem2) { + function interfaceFunction(value2) { + if (value2 === "Outline") { + return interfaceFunction.outlineInterface(); + } + return null; + } + interfaceFunction._name = "Outline"; + interfaceFunction.outlineInterface = outlineInterfaceFactory(elem2); + return interfaceFunction; + }; + return function(elem2) { + function _interfaceFunction(value2) { + if (value2 === "Data") { + return _interfaceFunction.dataInterface; + } + return null; + } + _interfaceFunction._name = "Data"; + _interfaceFunction.dataInterface = dataInterfaceFactory(elem2); + return _interfaceFunction; + }; + }(); + FootageElement.prototype.prepareFrame = function() { + }; + extendPrototype([RenderableElement, BaseElement, FrameElement], FootageElement); + FootageElement.prototype.getBaseElement = function() { + return null; + }; + FootageElement.prototype.renderFrame = function() { + }; + FootageElement.prototype.destroy = function() { + }; + FootageElement.prototype.initExpressions = function() { + this.layerInterface = FootageInterface(this); + }; + FootageElement.prototype.getFootageData = function() { + return this.footageData; + }; + AudioElement.prototype.prepareFrame = function(num) { + this.prepareRenderableFrame(num, true); + this.prepareProperties(num, true); + if (!this.tm._placeholder) { + var timeRemapped = this.tm.v; + this._currentTime = timeRemapped; + } else { + this._currentTime = num / this.data.sr; + } + this._volume = this.lv.v[0]; + var totalVolume = this._volume * this._volumeMultiplier; + if (this._previousVolume !== totalVolume) { + this._previousVolume = totalVolume; + this.audio.volume(totalVolume); + } + }; + extendPrototype([RenderableElement, BaseElement, FrameElement], AudioElement); + AudioElement.prototype.renderFrame = function() { + if (this.isInRange && this._canPlay) { + if (!this._isPlaying) { + this.audio.play(); + this.audio.seek(this._currentTime / this.globalData.frameRate); + this._isPlaying = true; + } else if (!this.audio.playing() || Math.abs(this._currentTime / this.globalData.frameRate - this.audio.seek()) > 0.1) { + this.audio.seek(this._currentTime / this.globalData.frameRate); + } + } + }; + AudioElement.prototype.show = function() { + }; + AudioElement.prototype.hide = function() { + this.audio.pause(); + this._isPlaying = false; + }; + AudioElement.prototype.pause = function() { + this.audio.pause(); + this._isPlaying = false; + this._canPlay = false; + }; + AudioElement.prototype.resume = function() { + this._canPlay = true; + }; + AudioElement.prototype.setRate = function(rateValue) { + this.audio.rate(rateValue); + }; + AudioElement.prototype.volume = function(volumeValue) { + this._volumeMultiplier = volumeValue; + this._previousVolume = volumeValue * this._volume; + this.audio.volume(this._previousVolume); + }; + AudioElement.prototype.getBaseElement = function() { + return null; + }; + AudioElement.prototype.destroy = function() { + }; + AudioElement.prototype.sourceRectAtTime = function() { + }; + AudioElement.prototype.initExpressions = function() { + }; + BaseRenderer.prototype.checkLayers = function(num) { + var i; + var len = this.layers.length; + var data2; + this.completeLayers = true; + for (i = len - 1;i >= 0; i -= 1) { + if (!this.elements[i]) { + data2 = this.layers[i]; + if (data2.ip - data2.st <= num - this.layers[i].st && data2.op - data2.st > num - this.layers[i].st) { + this.buildItem(i); + } + } + this.completeLayers = this.elements[i] ? this.completeLayers : false; + } + this.checkPendingElements(); + }; + BaseRenderer.prototype.createItem = function(layer) { + switch (layer.ty) { + case 2: + return this.createImage(layer); + case 0: + return this.createComp(layer); + case 1: + return this.createSolid(layer); + case 3: + return this.createNull(layer); + case 4: + return this.createShape(layer); + case 5: + return this.createText(layer); + case 6: + return this.createAudio(layer); + case 13: + return this.createCamera(layer); + case 15: + return this.createFootage(layer); + default: + return this.createNull(layer); + } + }; + BaseRenderer.prototype.createCamera = function() { + throw new Error("You're using a 3d camera. Try the html renderer."); + }; + BaseRenderer.prototype.createAudio = function(data2) { + return new AudioElement(data2, this.globalData, this); + }; + BaseRenderer.prototype.createFootage = function(data2) { + return new FootageElement(data2, this.globalData, this); + }; + BaseRenderer.prototype.buildAllItems = function() { + var i; + var len = this.layers.length; + for (i = 0;i < len; i += 1) { + this.buildItem(i); + } + this.checkPendingElements(); + }; + BaseRenderer.prototype.includeLayers = function(newLayers) { + this.completeLayers = false; + var i; + var len = newLayers.length; + var j2; + var jLen = this.layers.length; + for (i = 0;i < len; i += 1) { + j2 = 0; + while (j2 < jLen) { + if (this.layers[j2].id === newLayers[i].id) { + this.layers[j2] = newLayers[i]; + break; + } + j2 += 1; + } + } + }; + BaseRenderer.prototype.setProjectInterface = function(pInterface) { + this.globalData.projectInterface = pInterface; + }; + BaseRenderer.prototype.initItems = function() { + if (!this.globalData.progressiveLoad) { + this.buildAllItems(); + } + }; + BaseRenderer.prototype.buildElementParenting = function(element, parentName, hierarchy) { + var elements = this.elements; + var layers = this.layers; + var i = 0; + var len = layers.length; + while (i < len) { + if (layers[i].ind == parentName) { + if (!elements[i] || elements[i] === true) { + this.buildItem(i); + this.addPendingElement(element); + } else { + hierarchy.push(elements[i]); + elements[i].setAsParent(); + if (layers[i].parent !== undefined) { + this.buildElementParenting(element, layers[i].parent, hierarchy); + } else { + element.setHierarchy(hierarchy); + } + } + } + i += 1; + } + }; + BaseRenderer.prototype.addPendingElement = function(element) { + this.pendingElements.push(element); + }; + BaseRenderer.prototype.searchExtraCompositions = function(assets) { + var i; + var len = assets.length; + for (i = 0;i < len; i += 1) { + if (assets[i].xt) { + var comp2 = this.createComp(assets[i]); + comp2.initExpressions(); + this.globalData.projectInterface.registerComposition(comp2); + } + } + }; + BaseRenderer.prototype.getElementByPath = function(path) { + var pathValue = path.shift(); + var element; + if (typeof pathValue === "number") { + element = this.elements[pathValue]; + } else { + var i; + var len = this.elements.length; + for (i = 0;i < len; i += 1) { + if (this.elements[i].data.nm === pathValue) { + element = this.elements[i]; + break; + } + } + } + if (path.length === 0) { + return element; + } + return element.getElementByPath(path); + }; + BaseRenderer.prototype.setupGlobalData = function(animData, fontsContainer) { + this.globalData.fontManager = new FontManager; + this.globalData.fontManager.addChars(animData.chars); + this.globalData.fontManager.addFonts(animData.fonts, fontsContainer); + this.globalData.getAssetData = this.animationItem.getAssetData.bind(this.animationItem); + this.globalData.getAssetsPath = this.animationItem.getAssetsPath.bind(this.animationItem); + this.globalData.imageLoader = this.animationItem.imagePreloader; + this.globalData.audioController = this.animationItem.audioController; + this.globalData.frameId = 0; + this.globalData.frameRate = animData.fr; + this.globalData.nm = animData.nm; + this.globalData.compSize = { + w: animData.w, + h: animData.h + }; + }; + TransformElement.prototype = { + initTransform: function() { + this.finalTransform = { + mProp: this.data.ks ? TransformPropertyFactory.getTransformProperty(this, this.data.ks, this) : { o: 0 }, + _matMdf: false, + _opMdf: false, + mat: new Matrix + }; + if (this.data.ao) { + this.finalTransform.mProp.autoOriented = true; + } + if (this.data.ty !== 11) { + } + }, + renderTransform: function() { + this.finalTransform._opMdf = this.finalTransform.mProp.o._mdf || this._isFirstFrame; + this.finalTransform._matMdf = this.finalTransform.mProp._mdf || this._isFirstFrame; + if (this.hierarchy) { + var mat; + var finalMat = this.finalTransform.mat; + var i = 0; + var len = this.hierarchy.length; + if (!this.finalTransform._matMdf) { + while (i < len) { + if (this.hierarchy[i].finalTransform.mProp._mdf) { + this.finalTransform._matMdf = true; + break; + } + i += 1; + } + } + if (this.finalTransform._matMdf) { + mat = this.finalTransform.mProp.v.props; + finalMat.cloneFromProps(mat); + for (i = 0;i < len; i += 1) { + mat = this.hierarchy[i].finalTransform.mProp.v.props; + finalMat.transform(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5], mat[6], mat[7], mat[8], mat[9], mat[10], mat[11], mat[12], mat[13], mat[14], mat[15]); + } + } + } + }, + globalToLocal: function(pt) { + var transforms = []; + transforms.push(this.finalTransform); + var flag = true; + var comp2 = this.comp; + while (flag) { + if (comp2.finalTransform) { + if (comp2.data.hasMask) { + transforms.splice(0, 0, comp2.finalTransform); + } + comp2 = comp2.comp; + } else { + flag = false; + } + } + var i; + var len = transforms.length; + var ptNew; + for (i = 0;i < len; i += 1) { + ptNew = transforms[i].mat.applyToPointArray(0, 0, 0); + pt = [pt[0] - ptNew[0], pt[1] - ptNew[1], 0]; + } + return pt; + }, + mHelper: new Matrix + }; + MaskElement.prototype.getMaskProperty = function(pos) { + return this.viewData[pos].prop; + }; + MaskElement.prototype.renderFrame = function(isFirstFrame) { + var finalMat = this.element.finalTransform.mat; + var i; + var len = this.masksProperties.length; + for (i = 0;i < len; i += 1) { + if (this.viewData[i].prop._mdf || isFirstFrame) { + this.drawPath(this.masksProperties[i], this.viewData[i].prop.v, this.viewData[i]); + } + if (this.viewData[i].op._mdf || isFirstFrame) { + this.viewData[i].elem.setAttribute("fill-opacity", this.viewData[i].op.v); + } + if (this.masksProperties[i].mode !== "n") { + if (this.viewData[i].invRect && (this.element.finalTransform.mProp._mdf || isFirstFrame)) { + this.viewData[i].invRect.setAttribute("transform", finalMat.getInverseMatrix().to2dCSS()); + } + if (this.storedData[i].x && (this.storedData[i].x._mdf || isFirstFrame)) { + var feMorph = this.storedData[i].expan; + if (this.storedData[i].x.v < 0) { + if (this.storedData[i].lastOperator !== "erode") { + this.storedData[i].lastOperator = "erode"; + this.storedData[i].elem.setAttribute("filter", "url(" + getLocationHref() + "#" + this.storedData[i].filterId + ")"); + } + feMorph.setAttribute("radius", -this.storedData[i].x.v); + } else { + if (this.storedData[i].lastOperator !== "dilate") { + this.storedData[i].lastOperator = "dilate"; + this.storedData[i].elem.setAttribute("filter", null); + } + this.storedData[i].elem.setAttribute("stroke-width", this.storedData[i].x.v * 2); + } + } + } + } + }; + MaskElement.prototype.getMaskelement = function() { + return this.maskElement; + }; + MaskElement.prototype.createLayerSolidPath = function() { + var path = "M0,0 "; + path += " h" + this.globalData.compSize.w; + path += " v" + this.globalData.compSize.h; + path += " h-" + this.globalData.compSize.w; + path += " v-" + this.globalData.compSize.h + " "; + return path; + }; + MaskElement.prototype.drawPath = function(pathData, pathNodes, viewData) { + var pathString = " M" + pathNodes.v[0][0] + "," + pathNodes.v[0][1]; + var i; + var len; + len = pathNodes._length; + for (i = 1;i < len; i += 1) { + pathString += " C" + pathNodes.o[i - 1][0] + "," + pathNodes.o[i - 1][1] + " " + pathNodes.i[i][0] + "," + pathNodes.i[i][1] + " " + pathNodes.v[i][0] + "," + pathNodes.v[i][1]; + } + if (pathNodes.c && len > 1) { + pathString += " C" + pathNodes.o[i - 1][0] + "," + pathNodes.o[i - 1][1] + " " + pathNodes.i[0][0] + "," + pathNodes.i[0][1] + " " + pathNodes.v[0][0] + "," + pathNodes.v[0][1]; + } + if (viewData.lastPath !== pathString) { + var pathShapeValue = ""; + if (viewData.elem) { + if (pathNodes.c) { + pathShapeValue = pathData.inv ? this.solidPath + pathString : pathString; + } + viewData.elem.setAttribute("d", pathShapeValue); + } + viewData.lastPath = pathString; + } + }; + MaskElement.prototype.destroy = function() { + this.element = null; + this.globalData = null; + this.maskElement = null; + this.data = null; + this.masksProperties = null; + }; + const filtersFactory = function() { + var ob2 = {}; + ob2.createFilter = createFilter; + ob2.createAlphaToLuminanceFilter = createAlphaToLuminanceFilter; + function createFilter(filId, skipCoordinates) { + var fil = createNS("filter"); + fil.setAttribute("id", filId); + if (skipCoordinates !== true) { + fil.setAttribute("filterUnits", "objectBoundingBox"); + fil.setAttribute("x", "0%"); + fil.setAttribute("y", "0%"); + fil.setAttribute("width", "100%"); + fil.setAttribute("height", "100%"); + } + return fil; + } + function createAlphaToLuminanceFilter() { + var feColorMatrix = createNS("feColorMatrix"); + feColorMatrix.setAttribute("type", "matrix"); + feColorMatrix.setAttribute("color-interpolation-filters", "sRGB"); + feColorMatrix.setAttribute("values", "0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1"); + return feColorMatrix; + } + return ob2; + }(); + const featureSupport = function() { + var ob2 = { + maskType: true + }; + if (/MSIE 10/i.test(navigator.userAgent) || /MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent) || /Edge\/\d./i.test(navigator.userAgent)) { + ob2.maskType = false; + } + return ob2; + }(); + registeredEffects = {}; + idPrefix = "filter_result_"; + SVGEffects.prototype.renderFrame = function(_isFirstFrame) { + var i; + var len = this.filters.length; + for (i = 0;i < len; i += 1) { + this.filters[i].renderFrame(_isFirstFrame); + } + }; + SVGBaseElement.prototype = { + initRendererElement: function() { + this.layerElement = createNS("g"); + }, + createContainerElements: function() { + this.matteElement = createNS("g"); + this.transformedElement = this.layerElement; + this.maskedElement = this.layerElement; + this._sizeChanged = false; + var layerElementParent = null; + var filId; + var fil; + var gg; + if (this.data.td) { + if (this.data.td == 3 || this.data.td == 1) { + var masker = createNS("mask"); + masker.setAttribute("id", this.layerId); + masker.setAttribute("mask-type", this.data.td == 3 ? "luminance" : "alpha"); + masker.appendChild(this.layerElement); + layerElementParent = masker; + this.globalData.defs.appendChild(masker); + if (!featureSupport.maskType && this.data.td == 1) { + masker.setAttribute("mask-type", "luminance"); + filId = createElementID(); + fil = filtersFactory.createFilter(filId); + this.globalData.defs.appendChild(fil); + fil.appendChild(filtersFactory.createAlphaToLuminanceFilter()); + gg = createNS("g"); + gg.appendChild(this.layerElement); + layerElementParent = gg; + masker.appendChild(gg); + gg.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")"); + } + } else if (this.data.td == 2) { + var maskGroup = createNS("mask"); + maskGroup.setAttribute("id", this.layerId); + maskGroup.setAttribute("mask-type", "alpha"); + var maskGrouper = createNS("g"); + maskGroup.appendChild(maskGrouper); + filId = createElementID(); + fil = filtersFactory.createFilter(filId); + var feCTr = createNS("feComponentTransfer"); + feCTr.setAttribute("in", "SourceGraphic"); + fil.appendChild(feCTr); + var feFunc = createNS("feFuncA"); + feFunc.setAttribute("type", "table"); + feFunc.setAttribute("tableValues", "1.0 0.0"); + feCTr.appendChild(feFunc); + this.globalData.defs.appendChild(fil); + var alphaRect = createNS("rect"); + alphaRect.setAttribute("width", this.comp.data.w); + alphaRect.setAttribute("height", this.comp.data.h); + alphaRect.setAttribute("x", "0"); + alphaRect.setAttribute("y", "0"); + alphaRect.setAttribute("fill", "#ffffff"); + alphaRect.setAttribute("opacity", "0"); + maskGrouper.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")"); + maskGrouper.appendChild(alphaRect); + maskGrouper.appendChild(this.layerElement); + layerElementParent = maskGrouper; + if (!featureSupport.maskType) { + maskGroup.setAttribute("mask-type", "luminance"); + fil.appendChild(filtersFactory.createAlphaToLuminanceFilter()); + gg = createNS("g"); + maskGrouper.appendChild(alphaRect); + gg.appendChild(this.layerElement); + layerElementParent = gg; + maskGrouper.appendChild(gg); + } + this.globalData.defs.appendChild(maskGroup); + } + } else if (this.data.tt) { + this.matteElement.appendChild(this.layerElement); + layerElementParent = this.matteElement; + this.baseElement = this.matteElement; + } else { + this.baseElement = this.layerElement; + } + if (this.data.ln) { + this.layerElement.setAttribute("id", this.data.ln); + } + if (this.data.cl) { + this.layerElement.setAttribute("class", this.data.cl); + } + if (this.data.ty === 0 && !this.data.hd) { + var cp = createNS("clipPath"); + var pt = createNS("path"); + pt.setAttribute("d", "M0,0 L" + this.data.w + ",0 L" + this.data.w + "," + this.data.h + " L0," + this.data.h + "z"); + var clipId = createElementID(); + cp.setAttribute("id", clipId); + cp.appendChild(pt); + this.globalData.defs.appendChild(cp); + if (this.checkMasks()) { + var cpGroup = createNS("g"); + cpGroup.setAttribute("clip-path", "url(" + getLocationHref() + "#" + clipId + ")"); + cpGroup.appendChild(this.layerElement); + this.transformedElement = cpGroup; + if (layerElementParent) { + layerElementParent.appendChild(this.transformedElement); + } else { + this.baseElement = this.transformedElement; + } + } else { + this.layerElement.setAttribute("clip-path", "url(" + getLocationHref() + "#" + clipId + ")"); + } + } + if (this.data.bm !== 0) { + this.setBlendMode(); + } + }, + renderElement: function() { + if (this.finalTransform._matMdf) { + this.transformedElement.setAttribute("transform", this.finalTransform.mat.to2dCSS()); + } + if (this.finalTransform._opMdf) { + this.transformedElement.setAttribute("opacity", this.finalTransform.mProp.o.v); + } + }, + destroyBaseElement: function() { + this.layerElement = null; + this.matteElement = null; + this.maskManager.destroy(); + }, + getBaseElement: function() { + if (this.data.hd) { + return null; + } + return this.baseElement; + }, + createRenderableComponents: function() { + this.maskManager = new MaskElement(this.data, this, this.globalData); + this.renderableEffectsManager = new SVGEffects(this); + }, + setMatte: function(id) { + if (!this.matteElement) { + return; + } + this.matteElement.setAttribute("mask", "url(" + getLocationHref() + "#" + id + ")"); + } + }; + HierarchyElement.prototype = { + initHierarchy: function() { + this.hierarchy = []; + this._isParent = false; + this.checkParenting(); + }, + setHierarchy: function(hierarchy) { + this.hierarchy = hierarchy; + }, + setAsParent: function() { + this._isParent = true; + }, + checkParenting: function() { + if (this.data.parent !== undefined) { + this.comp.buildElementParenting(this, this.data.parent, []); + } + } + }; + (function() { + var _prototype = { + initElement: function(data2, globalData2, comp2) { + this.initFrame(); + this.initBaseData(data2, globalData2, comp2); + this.initTransform(data2, globalData2, comp2); + this.initHierarchy(); + this.initRenderable(); + this.initRendererElement(); + this.createContainerElements(); + this.createRenderableComponents(); + this.createContent(); + this.hide(); + }, + hide: function() { + if (!this.hidden && (!this.isInRange || this.isTransparent)) { + var elem2 = this.baseElement || this.layerElement; + elem2.style.display = "none"; + this.hidden = true; + } + }, + show: function() { + if (this.isInRange && !this.isTransparent) { + if (!this.data.hd) { + var elem2 = this.baseElement || this.layerElement; + elem2.style.display = "block"; + } + this.hidden = false; + this._isFirstFrame = true; + } + }, + renderFrame: function() { + if (this.data.hd || this.hidden) { + return; + } + this.renderTransform(); + this.renderRenderable(); + this.renderElement(); + this.renderInnerContent(); + if (this._isFirstFrame) { + this._isFirstFrame = false; + } + }, + renderInnerContent: function() { + }, + prepareFrame: function(num) { + this._mdf = false; + this.prepareRenderableFrame(num); + this.prepareProperties(num, this.isInRange); + this.checkTransparency(); + }, + destroy: function() { + this.innerElem = null; + this.destroyBaseElement(); + } + }; + extendPrototype([RenderableElement, createProxyFunction(_prototype)], RenderableDOMElement); + })(); + extendPrototype([BaseElement, TransformElement, SVGBaseElement, HierarchyElement, FrameElement, RenderableDOMElement], IImageElement); + IImageElement.prototype.createContent = function() { + var assetPath = this.globalData.getAssetsPath(this.assetData); + this.innerElem = createNS("image"); + this.innerElem.setAttribute("width", this.assetData.w + "px"); + this.innerElem.setAttribute("height", this.assetData.h + "px"); + this.innerElem.setAttribute("preserveAspectRatio", this.assetData.pr || this.globalData.renderConfig.imagePreserveAspectRatio); + this.innerElem.setAttributeNS("http://www.w3.org/1999/xlink", "href", assetPath); + this.layerElement.appendChild(this.innerElem); + }; + IImageElement.prototype.sourceRectAtTime = function() { + return this.sourceRect; + }; + IShapeElement.prototype = { + addShapeToModifiers: function(data2) { + var i; + var len = this.shapeModifiers.length; + for (i = 0;i < len; i += 1) { + this.shapeModifiers[i].addShape(data2); + } + }, + isShapeInAnimatedModifiers: function(data2) { + var i = 0; + var len = this.shapeModifiers.length; + while (i < len) { + if (this.shapeModifiers[i].isAnimatedWithShape(data2)) { + return true; + } + } + return false; + }, + renderModifiers: function() { + if (!this.shapeModifiers.length) { + return; + } + var i; + var len = this.shapes.length; + for (i = 0;i < len; i += 1) { + this.shapes[i].sh.reset(); + } + len = this.shapeModifiers.length; + var shouldBreakProcess; + for (i = len - 1;i >= 0; i -= 1) { + shouldBreakProcess = this.shapeModifiers[i].processShapes(this._isFirstFrame); + if (shouldBreakProcess) { + break; + } + } + }, + searchProcessedElement: function(elem2) { + var elements = this.processedElements; + var i = 0; + var len = elements.length; + while (i < len) { + if (elements[i].elem === elem2) { + return elements[i].pos; + } + i += 1; + } + return 0; + }, + addProcessedElement: function(elem2, pos) { + var elements = this.processedElements; + var i = elements.length; + while (i) { + i -= 1; + if (elements[i].elem === elem2) { + elements[i].pos = pos; + return; + } + } + elements.push(new ProcessedElement(elem2, pos)); + }, + prepareFrame: function(num) { + this.prepareRenderableFrame(num); + this.prepareProperties(num, this.isInRange); + } + }; + const lineCapEnum = { + 1: "butt", + 2: "round", + 3: "square" + }; + const lineJoinEnum = { + 1: "miter", + 2: "round", + 3: "bevel" + }; + SVGShapeData.prototype.setAsAnimated = function() { + this._isAnimated = true; + }; + SVGStyleData.prototype.reset = function() { + this.d = ""; + this._mdf = false; + }; + DashProperty.prototype.getValue = function(forceRender) { + if (this.elem.globalData.frameId === this.frameId && !forceRender) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + this._mdf = this._mdf || forceRender; + if (this._mdf) { + var i = 0; + var len = this.dataProps.length; + if (this.renderer === "svg") { + this.dashStr = ""; + } + for (i = 0;i < len; i += 1) { + if (this.dataProps[i].n !== "o") { + if (this.renderer === "svg") { + this.dashStr += " " + this.dataProps[i].p.v; + } else { + this.dashArray[i] = this.dataProps[i].p.v; + } + } else { + this.dashoffset[0] = this.dataProps[i].p.v; + } + } + } + }; + extendPrototype([DynamicPropertyContainer], DashProperty); + extendPrototype([DynamicPropertyContainer], SVGStrokeStyleData); + extendPrototype([DynamicPropertyContainer], SVGFillStyleData); + extendPrototype([DynamicPropertyContainer], SVGNoStyleData); + GradientProperty.prototype.comparePoints = function(values2, points) { + var i = 0; + var len = this.o.length / 2; + var diff; + while (i < len) { + diff = Math.abs(values2[i * 4] - values2[points * 4 + i * 2]); + if (diff > 0.01) { + return false; + } + i += 1; + } + return true; + }; + GradientProperty.prototype.checkCollapsable = function() { + if (this.o.length / 2 !== this.c.length / 4) { + return false; + } + if (this.data.k.k[0].s) { + var i = 0; + var len = this.data.k.k.length; + while (i < len) { + if (!this.comparePoints(this.data.k.k[i].s, this.data.p)) { + return false; + } + i += 1; + } + } else if (!this.comparePoints(this.data.k.k, this.data.p)) { + return false; + } + return true; + }; + GradientProperty.prototype.getValue = function(forceRender) { + this.prop.getValue(); + this._mdf = false; + this._cmdf = false; + this._omdf = false; + if (this.prop._mdf || forceRender) { + var i; + var len = this.data.p * 4; + var mult; + var val2; + for (i = 0;i < len; i += 1) { + mult = i % 4 === 0 ? 100 : 255; + val2 = Math.round(this.prop.v[i] * mult); + if (this.c[i] !== val2) { + this.c[i] = val2; + this._cmdf = !forceRender; + } + } + if (this.o.length) { + len = this.prop.v.length; + for (i = this.data.p * 4;i < len; i += 1) { + mult = i % 2 === 0 ? 100 : 1; + val2 = i % 2 === 0 ? Math.round(this.prop.v[i] * 100) : this.prop.v[i]; + if (this.o[i - this.data.p * 4] !== val2) { + this.o[i - this.data.p * 4] = val2; + this._omdf = !forceRender; + } + } + } + this._mdf = !forceRender; + } + }; + extendPrototype([DynamicPropertyContainer], GradientProperty); + SVGGradientFillStyleData.prototype.initGradientData = function(elem2, data2, styleOb) { + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, this); + this.s = PropertyFactory.getProp(elem2, data2.s, 1, null, this); + this.e = PropertyFactory.getProp(elem2, data2.e, 1, null, this); + this.h = PropertyFactory.getProp(elem2, data2.h || { k: 0 }, 0, 0.01, this); + this.a = PropertyFactory.getProp(elem2, data2.a || { k: 0 }, 0, degToRads, this); + this.g = new GradientProperty(elem2, data2.g, this); + this.style = styleOb; + this.stops = []; + this.setGradientData(styleOb.pElem, data2); + this.setGradientOpacity(data2, styleOb); + this._isAnimated = !!this._isAnimated; + }; + SVGGradientFillStyleData.prototype.setGradientData = function(pathElement, data2) { + var gradientId = createElementID(); + var gfill = createNS(data2.t === 1 ? "linearGradient" : "radialGradient"); + gfill.setAttribute("id", gradientId); + gfill.setAttribute("spreadMethod", "pad"); + gfill.setAttribute("gradientUnits", "userSpaceOnUse"); + var stops = []; + var stop; + var j2; + var jLen; + jLen = data2.g.p * 4; + for (j2 = 0;j2 < jLen; j2 += 4) { + stop = createNS("stop"); + gfill.appendChild(stop); + stops.push(stop); + } + pathElement.setAttribute(data2.ty === "gf" ? "fill" : "stroke", "url(" + getLocationHref() + "#" + gradientId + ")"); + this.gf = gfill; + this.cst = stops; + }; + SVGGradientFillStyleData.prototype.setGradientOpacity = function(data2, styleOb) { + if (this.g._hasOpacity && !this.g._collapsable) { + var stop; + var j2; + var jLen; + var mask2 = createNS("mask"); + var maskElement = createNS("path"); + mask2.appendChild(maskElement); + var opacityId = createElementID(); + var maskId = createElementID(); + mask2.setAttribute("id", maskId); + var opFill = createNS(data2.t === 1 ? "linearGradient" : "radialGradient"); + opFill.setAttribute("id", opacityId); + opFill.setAttribute("spreadMethod", "pad"); + opFill.setAttribute("gradientUnits", "userSpaceOnUse"); + jLen = data2.g.k.k[0].s ? data2.g.k.k[0].s.length : data2.g.k.k.length; + var stops = this.stops; + for (j2 = data2.g.p * 4;j2 < jLen; j2 += 2) { + stop = createNS("stop"); + stop.setAttribute("stop-color", "rgb(255,255,255)"); + opFill.appendChild(stop); + stops.push(stop); + } + maskElement.setAttribute(data2.ty === "gf" ? "fill" : "stroke", "url(" + getLocationHref() + "#" + opacityId + ")"); + if (data2.ty === "gs") { + maskElement.setAttribute("stroke-linecap", lineCapEnum[data2.lc || 2]); + maskElement.setAttribute("stroke-linejoin", lineJoinEnum[data2.lj || 2]); + if (data2.lj === 1) { + maskElement.setAttribute("stroke-miterlimit", data2.ml); + } + } + this.of = opFill; + this.ms = mask2; + this.ost = stops; + this.maskId = maskId; + styleOb.msElem = maskElement; + } + }; + extendPrototype([DynamicPropertyContainer], SVGGradientFillStyleData); + extendPrototype([SVGGradientFillStyleData, DynamicPropertyContainer], SVGGradientStrokeStyleData); + const buildShapeString = function(pathNodes, length2, closed, mat) { + if (length2 === 0) { + return ""; + } + var _o = pathNodes.o; + var _i = pathNodes.i; + var _v4 = pathNodes.v; + var i; + var shapeString = " M" + mat.applyToPointStringified(_v4[0][0], _v4[0][1]); + for (i = 1;i < length2; i += 1) { + shapeString += " C" + mat.applyToPointStringified(_o[i - 1][0], _o[i - 1][1]) + " " + mat.applyToPointStringified(_i[i][0], _i[i][1]) + " " + mat.applyToPointStringified(_v4[i][0], _v4[i][1]); + } + if (closed && length2) { + shapeString += " C" + mat.applyToPointStringified(_o[i - 1][0], _o[i - 1][1]) + " " + mat.applyToPointStringified(_i[0][0], _i[0][1]) + " " + mat.applyToPointStringified(_v4[0][0], _v4[0][1]); + shapeString += "z"; + } + return shapeString; + }; + const SVGElementsRenderer = function() { + var _identityMatrix3 = new Matrix; + var _matrixHelper = new Matrix; + var ob2 = { + createRenderFunction + }; + function createRenderFunction(data2) { + switch (data2.ty) { + case "fl": + return renderFill; + case "gf": + return renderGradient; + case "gs": + return renderGradientStroke; + case "st": + return renderStroke; + case "sh": + case "el": + case "rc": + case "sr": + return renderPath; + case "tr": + return renderContentTransform; + case "no": + return renderNoop; + default: + return null; + } + } + function renderContentTransform(styleData, itemData, isFirstFrame) { + if (isFirstFrame || itemData.transform.op._mdf) { + itemData.transform.container.setAttribute("opacity", itemData.transform.op.v); + } + if (isFirstFrame || itemData.transform.mProps._mdf) { + itemData.transform.container.setAttribute("transform", itemData.transform.mProps.v.to2dCSS()); + } + } + function renderNoop() { + } + function renderPath(styleData, itemData, isFirstFrame) { + var j2; + var jLen; + var pathStringTransformed; + var redraw; + var pathNodes; + var l2; + var lLen = itemData.styles.length; + var lvl = itemData.lvl; + var paths; + var mat; + var props; + var iterations; + var k2; + for (l2 = 0;l2 < lLen; l2 += 1) { + redraw = itemData.sh._mdf || isFirstFrame; + if (itemData.styles[l2].lvl < lvl) { + mat = _matrixHelper.reset(); + iterations = lvl - itemData.styles[l2].lvl; + k2 = itemData.transformers.length - 1; + while (!redraw && iterations > 0) { + redraw = itemData.transformers[k2].mProps._mdf || redraw; + iterations -= 1; + k2 -= 1; + } + if (redraw) { + iterations = lvl - itemData.styles[l2].lvl; + k2 = itemData.transformers.length - 1; + while (iterations > 0) { + props = itemData.transformers[k2].mProps.v.props; + mat.transform(props[0], props[1], props[2], props[3], props[4], props[5], props[6], props[7], props[8], props[9], props[10], props[11], props[12], props[13], props[14], props[15]); + iterations -= 1; + k2 -= 1; + } + } + } else { + mat = _identityMatrix3; + } + paths = itemData.sh.paths; + jLen = paths._length; + if (redraw) { + pathStringTransformed = ""; + for (j2 = 0;j2 < jLen; j2 += 1) { + pathNodes = paths.shapes[j2]; + if (pathNodes && pathNodes._length) { + pathStringTransformed += buildShapeString(pathNodes, pathNodes._length, pathNodes.c, mat); + } + } + itemData.caches[l2] = pathStringTransformed; + } else { + pathStringTransformed = itemData.caches[l2]; + } + itemData.styles[l2].d += styleData.hd === true ? "" : pathStringTransformed; + itemData.styles[l2]._mdf = redraw || itemData.styles[l2]._mdf; + } + } + function renderFill(styleData, itemData, isFirstFrame) { + var styleElem = itemData.style; + if (itemData.c._mdf || isFirstFrame) { + styleElem.pElem.setAttribute("fill", "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"); + } + if (itemData.o._mdf || isFirstFrame) { + styleElem.pElem.setAttribute("fill-opacity", itemData.o.v); + } + } + function renderGradientStroke(styleData, itemData, isFirstFrame) { + renderGradient(styleData, itemData, isFirstFrame); + renderStroke(styleData, itemData, isFirstFrame); + } + function renderGradient(styleData, itemData, isFirstFrame) { + var gfill = itemData.gf; + var hasOpacity = itemData.g._hasOpacity; + var pt1 = itemData.s.v; + var pt2 = itemData.e.v; + if (itemData.o._mdf || isFirstFrame) { + var attr = styleData.ty === "gf" ? "fill-opacity" : "stroke-opacity"; + itemData.style.pElem.setAttribute(attr, itemData.o.v); + } + if (itemData.s._mdf || isFirstFrame) { + var attr1 = styleData.t === 1 ? "x1" : "cx"; + var attr2 = attr1 === "x1" ? "y1" : "cy"; + gfill.setAttribute(attr1, pt1[0]); + gfill.setAttribute(attr2, pt1[1]); + if (hasOpacity && !itemData.g._collapsable) { + itemData.of.setAttribute(attr1, pt1[0]); + itemData.of.setAttribute(attr2, pt1[1]); + } + } + var stops; + var i; + var len; + var stop; + if (itemData.g._cmdf || isFirstFrame) { + stops = itemData.cst; + var cValues = itemData.g.c; + len = stops.length; + for (i = 0;i < len; i += 1) { + stop = stops[i]; + stop.setAttribute("offset", cValues[i * 4] + "%"); + stop.setAttribute("stop-color", "rgb(" + cValues[i * 4 + 1] + "," + cValues[i * 4 + 2] + "," + cValues[i * 4 + 3] + ")"); + } + } + if (hasOpacity && (itemData.g._omdf || isFirstFrame)) { + var oValues = itemData.g.o; + if (itemData.g._collapsable) { + stops = itemData.cst; + } else { + stops = itemData.ost; + } + len = stops.length; + for (i = 0;i < len; i += 1) { + stop = stops[i]; + if (!itemData.g._collapsable) { + stop.setAttribute("offset", oValues[i * 2] + "%"); + } + stop.setAttribute("stop-opacity", oValues[i * 2 + 1]); + } + } + if (styleData.t === 1) { + if (itemData.e._mdf || isFirstFrame) { + gfill.setAttribute("x2", pt2[0]); + gfill.setAttribute("y2", pt2[1]); + if (hasOpacity && !itemData.g._collapsable) { + itemData.of.setAttribute("x2", pt2[0]); + itemData.of.setAttribute("y2", pt2[1]); + } + } + } else { + var rad; + if (itemData.s._mdf || itemData.e._mdf || isFirstFrame) { + rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); + gfill.setAttribute("r", rad); + if (hasOpacity && !itemData.g._collapsable) { + itemData.of.setAttribute("r", rad); + } + } + if (itemData.e._mdf || itemData.h._mdf || itemData.a._mdf || isFirstFrame) { + if (!rad) { + rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); + } + var ang = Math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]); + var percent = itemData.h.v; + if (percent >= 1) { + percent = 0.99; + } else if (percent <= -1) { + percent = -0.99; + } + var dist = rad * percent; + var x2 = Math.cos(ang + itemData.a.v) * dist + pt1[0]; + var y3 = Math.sin(ang + itemData.a.v) * dist + pt1[1]; + gfill.setAttribute("fx", x2); + gfill.setAttribute("fy", y3); + if (hasOpacity && !itemData.g._collapsable) { + itemData.of.setAttribute("fx", x2); + itemData.of.setAttribute("fy", y3); + } + } + } + } + function renderStroke(styleData, itemData, isFirstFrame) { + var styleElem = itemData.style; + var d = itemData.d; + if (d && (d._mdf || isFirstFrame) && d.dashStr) { + styleElem.pElem.setAttribute("stroke-dasharray", d.dashStr); + styleElem.pElem.setAttribute("stroke-dashoffset", d.dashoffset[0]); + } + if (itemData.c && (itemData.c._mdf || isFirstFrame)) { + styleElem.pElem.setAttribute("stroke", "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"); + } + if (itemData.o._mdf || isFirstFrame) { + styleElem.pElem.setAttribute("stroke-opacity", itemData.o.v); + } + if (itemData.w._mdf || isFirstFrame) { + styleElem.pElem.setAttribute("stroke-width", itemData.w.v); + if (styleElem.msElem) { + styleElem.msElem.setAttribute("stroke-width", itemData.w.v); + } + } + } + return ob2; + }(); + extendPrototype([BaseElement, TransformElement, SVGBaseElement, IShapeElement, HierarchyElement, FrameElement, RenderableDOMElement], SVGShapeElement); + SVGShapeElement.prototype.initSecondaryElement = function() { + }; + SVGShapeElement.prototype.identityMatrix = new Matrix; + SVGShapeElement.prototype.buildExpressionInterface = function() { + }; + SVGShapeElement.prototype.createContent = function() { + this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, this.layerElement, 0, [], true); + this.filterUniqueShapes(); + }; + SVGShapeElement.prototype.filterUniqueShapes = function() { + var i; + var len = this.shapes.length; + var shape; + var j2; + var jLen = this.stylesList.length; + var style; + var tempShapes = []; + var areAnimated = false; + for (j2 = 0;j2 < jLen; j2 += 1) { + style = this.stylesList[j2]; + areAnimated = false; + tempShapes.length = 0; + for (i = 0;i < len; i += 1) { + shape = this.shapes[i]; + if (shape.styles.indexOf(style) !== -1) { + tempShapes.push(shape); + areAnimated = shape._isAnimated || areAnimated; + } + } + if (tempShapes.length > 1 && areAnimated) { + this.setShapesAsAnimated(tempShapes); + } + } + }; + SVGShapeElement.prototype.setShapesAsAnimated = function(shapes) { + var i; + var len = shapes.length; + for (i = 0;i < len; i += 1) { + shapes[i].setAsAnimated(); + } + }; + SVGShapeElement.prototype.createStyleElement = function(data2, level) { + var elementData; + var styleOb = new SVGStyleData(data2, level); + var pathElement = styleOb.pElem; + if (data2.ty === "st") { + elementData = new SVGStrokeStyleData(this, data2, styleOb); + } else if (data2.ty === "fl") { + elementData = new SVGFillStyleData(this, data2, styleOb); + } else if (data2.ty === "gf" || data2.ty === "gs") { + var GradientConstructor = data2.ty === "gf" ? SVGGradientFillStyleData : SVGGradientStrokeStyleData; + elementData = new GradientConstructor(this, data2, styleOb); + this.globalData.defs.appendChild(elementData.gf); + if (elementData.maskId) { + this.globalData.defs.appendChild(elementData.ms); + this.globalData.defs.appendChild(elementData.of); + pathElement.setAttribute("mask", "url(" + getLocationHref() + "#" + elementData.maskId + ")"); + } + } else if (data2.ty === "no") { + elementData = new SVGNoStyleData(this, data2, styleOb); + } + if (data2.ty === "st" || data2.ty === "gs") { + pathElement.setAttribute("stroke-linecap", lineCapEnum[data2.lc || 2]); + pathElement.setAttribute("stroke-linejoin", lineJoinEnum[data2.lj || 2]); + pathElement.setAttribute("fill-opacity", "0"); + if (data2.lj === 1) { + pathElement.setAttribute("stroke-miterlimit", data2.ml); + } + } + if (data2.r === 2) { + pathElement.setAttribute("fill-rule", "evenodd"); + } + if (data2.ln) { + pathElement.setAttribute("id", data2.ln); + } + if (data2.cl) { + pathElement.setAttribute("class", data2.cl); + } + if (data2.bm) { + pathElement.style["mix-blend-mode"] = getBlendMode(data2.bm); + } + this.stylesList.push(styleOb); + this.addToAnimatedContents(data2, elementData); + return elementData; + }; + SVGShapeElement.prototype.createGroupElement = function(data2) { + var elementData = new ShapeGroupData; + if (data2.ln) { + elementData.gr.setAttribute("id", data2.ln); + } + if (data2.cl) { + elementData.gr.setAttribute("class", data2.cl); + } + if (data2.bm) { + elementData.gr.style["mix-blend-mode"] = getBlendMode(data2.bm); + } + return elementData; + }; + SVGShapeElement.prototype.createTransformElement = function(data2, container) { + var transformProperty = TransformPropertyFactory.getTransformProperty(this, data2, this); + var elementData = new SVGTransformData(transformProperty, transformProperty.o, container); + this.addToAnimatedContents(data2, elementData); + return elementData; + }; + SVGShapeElement.prototype.createShapeElement = function(data2, ownTransformers, level) { + var ty2 = 4; + if (data2.ty === "rc") { + ty2 = 5; + } else if (data2.ty === "el") { + ty2 = 6; + } else if (data2.ty === "sr") { + ty2 = 7; + } + var shapeProperty = ShapePropertyFactory.getShapeProp(this, data2, ty2, this); + var elementData = new SVGShapeData(ownTransformers, level, shapeProperty); + this.shapes.push(elementData); + this.addShapeToModifiers(elementData); + this.addToAnimatedContents(data2, elementData); + return elementData; + }; + SVGShapeElement.prototype.addToAnimatedContents = function(data2, element) { + var i = 0; + var len = this.animatedContents.length; + while (i < len) { + if (this.animatedContents[i].element === element) { + return; + } + i += 1; + } + this.animatedContents.push({ + fn: SVGElementsRenderer.createRenderFunction(data2), + element, + data: data2 + }); + }; + SVGShapeElement.prototype.setElementStyles = function(elementData) { + var arr = elementData.styles; + var j2; + var jLen = this.stylesList.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (!this.stylesList[j2].closed) { + arr.push(this.stylesList[j2]); + } + } + }; + SVGShapeElement.prototype.reloadShapes = function() { + this._isFirstFrame = true; + var i; + var len = this.itemsData.length; + for (i = 0;i < len; i += 1) { + this.prevViewData[i] = this.itemsData[i]; + } + this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, this.layerElement, 0, [], true); + this.filterUniqueShapes(); + len = this.dynamicProperties.length; + for (i = 0;i < len; i += 1) { + this.dynamicProperties[i].getValue(); + } + this.renderModifiers(); + }; + SVGShapeElement.prototype.searchShapes = function(arr, itemsData, prevViewData, container, level, transformers, render) { + var ownTransformers = [].concat(transformers); + var i; + var len = arr.length - 1; + var j2; + var jLen; + var ownStyles = []; + var ownModifiers = []; + var currentTransform; + var modifier; + var processedPos; + for (i = len;i >= 0; i -= 1) { + processedPos = this.searchProcessedElement(arr[i]); + if (!processedPos) { + arr[i]._render = render; + } else { + itemsData[i] = prevViewData[processedPos - 1]; + } + if (arr[i].ty === "fl" || arr[i].ty === "st" || arr[i].ty === "gf" || arr[i].ty === "gs" || arr[i].ty === "no") { + if (!processedPos) { + itemsData[i] = this.createStyleElement(arr[i], level); + } else { + itemsData[i].style.closed = false; + } + if (arr[i]._render) { + if (itemsData[i].style.pElem.parentNode !== container) { + container.appendChild(itemsData[i].style.pElem); + } + } + ownStyles.push(itemsData[i].style); + } else if (arr[i].ty === "gr") { + if (!processedPos) { + itemsData[i] = this.createGroupElement(arr[i]); + } else { + jLen = itemsData[i].it.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + itemsData[i].prevViewData[j2] = itemsData[i].it[j2]; + } + } + this.searchShapes(arr[i].it, itemsData[i].it, itemsData[i].prevViewData, itemsData[i].gr, level + 1, ownTransformers, render); + if (arr[i]._render) { + if (itemsData[i].gr.parentNode !== container) { + container.appendChild(itemsData[i].gr); + } + } + } else if (arr[i].ty === "tr") { + if (!processedPos) { + itemsData[i] = this.createTransformElement(arr[i], container); + } + currentTransform = itemsData[i].transform; + ownTransformers.push(currentTransform); + } else if (arr[i].ty === "sh" || arr[i].ty === "rc" || arr[i].ty === "el" || arr[i].ty === "sr") { + if (!processedPos) { + itemsData[i] = this.createShapeElement(arr[i], ownTransformers, level); + } + this.setElementStyles(itemsData[i]); + } else if (arr[i].ty === "tm" || arr[i].ty === "rd" || arr[i].ty === "ms" || arr[i].ty === "pb") { + if (!processedPos) { + modifier = ShapeModifiers.getModifier(arr[i].ty); + modifier.init(this, arr[i]); + itemsData[i] = modifier; + this.shapeModifiers.push(modifier); + } else { + modifier = itemsData[i]; + modifier.closed = false; + } + ownModifiers.push(modifier); + } else if (arr[i].ty === "rp") { + if (!processedPos) { + modifier = ShapeModifiers.getModifier(arr[i].ty); + itemsData[i] = modifier; + modifier.init(this, arr, i, itemsData); + this.shapeModifiers.push(modifier); + render = false; + } else { + modifier = itemsData[i]; + modifier.closed = true; + } + ownModifiers.push(modifier); + } + this.addProcessedElement(arr[i], i + 1); + } + len = ownStyles.length; + for (i = 0;i < len; i += 1) { + ownStyles[i].closed = true; + } + len = ownModifiers.length; + for (i = 0;i < len; i += 1) { + ownModifiers[i].closed = true; + } + }; + SVGShapeElement.prototype.renderInnerContent = function() { + this.renderModifiers(); + var i; + var len = this.stylesList.length; + for (i = 0;i < len; i += 1) { + this.stylesList[i].reset(); + } + this.renderShape(); + for (i = 0;i < len; i += 1) { + if (this.stylesList[i]._mdf || this._isFirstFrame) { + if (this.stylesList[i].msElem) { + this.stylesList[i].msElem.setAttribute("d", this.stylesList[i].d); + this.stylesList[i].d = "M0 0" + this.stylesList[i].d; + } + this.stylesList[i].pElem.setAttribute("d", this.stylesList[i].d || "M0 0"); + } + } + }; + SVGShapeElement.prototype.renderShape = function() { + var i; + var len = this.animatedContents.length; + var animatedContent; + for (i = 0;i < len; i += 1) { + animatedContent = this.animatedContents[i]; + if ((this._isFirstFrame || animatedContent.element._isAnimated) && animatedContent.data !== true) { + animatedContent.fn(animatedContent.data, animatedContent.element, this._isFirstFrame); + } + } + }; + SVGShapeElement.prototype.destroy = function() { + this.destroyBaseElement(); + this.shapesData = null; + this.itemsData = null; + }; + LetterProps.prototype.update = function(o, sw, sc, fc, m, p) { + this._mdf.o = false; + this._mdf.sw = false; + this._mdf.sc = false; + this._mdf.fc = false; + this._mdf.m = false; + this._mdf.p = false; + var updated = false; + if (this.o !== o) { + this.o = o; + this._mdf.o = true; + updated = true; + } + if (this.sw !== sw) { + this.sw = sw; + this._mdf.sw = true; + updated = true; + } + if (this.sc !== sc) { + this.sc = sc; + this._mdf.sc = true; + updated = true; + } + if (this.fc !== fc) { + this.fc = fc; + this._mdf.fc = true; + updated = true; + } + if (this.m !== m) { + this.m = m; + this._mdf.m = true; + updated = true; + } + if (p.length && (this.p[0] !== p[0] || this.p[1] !== p[1] || this.p[4] !== p[4] || this.p[5] !== p[5] || this.p[12] !== p[12] || this.p[13] !== p[13])) { + this.p = p; + this._mdf.p = true; + updated = true; + } + return updated; + }; + TextProperty.prototype.defaultBoxWidth = [0, 0]; + TextProperty.prototype.copyData = function(obj, data2) { + for (var s in data2) { + if (Object.prototype.hasOwnProperty.call(data2, s)) { + obj[s] = data2[s]; + } + } + return obj; + }; + TextProperty.prototype.setCurrentData = function(data2) { + if (!data2.__complete) { + this.completeTextData(data2); + } + this.currentData = data2; + this.currentData.boxWidth = this.currentData.boxWidth || this.defaultBoxWidth; + this._mdf = true; + }; + TextProperty.prototype.searchProperty = function() { + return this.searchKeyframes(); + }; + TextProperty.prototype.searchKeyframes = function() { + this.kf = this.data.d.k.length > 1; + if (this.kf) { + this.addEffect(this.getKeyframeValue.bind(this)); + } + return this.kf; + }; + TextProperty.prototype.addEffect = function(effectFunction) { + this.effectsSequence.push(effectFunction); + this.elem.addDynamicProperty(this); + }; + TextProperty.prototype.getValue = function(_finalValue) { + if ((this.elem.globalData.frameId === this.frameId || !this.effectsSequence.length) && !_finalValue) { + return; + } + this.currentData.t = this.data.d.k[this.keysIndex].s.t; + var currentValue = this.currentData; + var currentIndex = this.keysIndex; + if (this.lock) { + this.setCurrentData(this.currentData); + return; + } + this.lock = true; + this._mdf = false; + var i; + var len = this.effectsSequence.length; + var finalValue = _finalValue || this.data.d.k[this.keysIndex].s; + for (i = 0;i < len; i += 1) { + if (currentIndex !== this.keysIndex) { + finalValue = this.effectsSequence[i](finalValue, finalValue.t); + } else { + finalValue = this.effectsSequence[i](this.currentData, finalValue.t); + } + } + if (currentValue !== finalValue) { + this.setCurrentData(finalValue); + } + this.v = this.currentData; + this.pv = this.v; + this.lock = false; + this.frameId = this.elem.globalData.frameId; + }; + TextProperty.prototype.getKeyframeValue = function() { + var textKeys = this.data.d.k; + var frameNum = this.elem.comp.renderedFrame; + var i = 0; + var len = textKeys.length; + while (i <= len - 1) { + if (i === len - 1 || textKeys[i + 1].t > frameNum) { + break; + } + i += 1; + } + if (this.keysIndex !== i) { + this.keysIndex = i; + } + return this.data.d.k[this.keysIndex].s; + }; + TextProperty.prototype.buildFinalText = function(text2) { + var charactersArray = []; + var i = 0; + var len = text2.length; + var charCode; + var secondCharCode; + var shouldCombine = false; + while (i < len) { + charCode = text2.charCodeAt(i); + if (FontManager.isCombinedCharacter(charCode)) { + charactersArray[charactersArray.length - 1] += text2.charAt(i); + } else if (charCode >= 55296 && charCode <= 56319) { + secondCharCode = text2.charCodeAt(i + 1); + if (secondCharCode >= 56320 && secondCharCode <= 57343) { + if (shouldCombine || FontManager.isModifier(charCode, secondCharCode)) { + charactersArray[charactersArray.length - 1] += text2.substr(i, 2); + shouldCombine = false; + } else { + charactersArray.push(text2.substr(i, 2)); + } + i += 1; + } else { + charactersArray.push(text2.charAt(i)); + } + } else if (charCode > 56319) { + secondCharCode = text2.charCodeAt(i + 1); + if (FontManager.isZeroWidthJoiner(charCode, secondCharCode)) { + shouldCombine = true; + charactersArray[charactersArray.length - 1] += text2.substr(i, 2); + i += 1; + } else { + charactersArray.push(text2.charAt(i)); + } + } else if (FontManager.isZeroWidthJoiner(charCode)) { + charactersArray[charactersArray.length - 1] += text2.charAt(i); + shouldCombine = true; + } else { + charactersArray.push(text2.charAt(i)); + } + i += 1; + } + return charactersArray; + }; + TextProperty.prototype.completeTextData = function(documentData) { + documentData.__complete = true; + var fontManager = this.elem.globalData.fontManager; + var data2 = this.data; + var letters = []; + var i; + var len; + var newLineFlag; + var index2 = 0; + var val2; + var anchorGrouping = data2.m.g; + var currentSize = 0; + var currentPos = 0; + var currentLine = 0; + var lineWidths = []; + var lineWidth = 0; + var maxLineWidth = 0; + var j2; + var jLen; + var fontData = fontManager.getFontByName(documentData.f); + var charData; + var cLength = 0; + var fontProps = getFontProperties(fontData); + documentData.fWeight = fontProps.weight; + documentData.fStyle = fontProps.style; + documentData.finalSize = documentData.s; + documentData.finalText = this.buildFinalText(documentData.t); + len = documentData.finalText.length; + documentData.finalLineHeight = documentData.lh; + var trackingOffset = documentData.tr / 1000 * documentData.finalSize; + var charCode; + if (documentData.sz) { + var flag = true; + var boxWidth = documentData.sz[0]; + var boxHeight = documentData.sz[1]; + var currentHeight; + var finalText; + while (flag) { + finalText = this.buildFinalText(documentData.t); + currentHeight = 0; + lineWidth = 0; + len = finalText.length; + trackingOffset = documentData.tr / 1000 * documentData.finalSize; + var lastSpaceIndex = -1; + for (i = 0;i < len; i += 1) { + charCode = finalText[i].charCodeAt(0); + newLineFlag = false; + if (finalText[i] === " ") { + lastSpaceIndex = i; + } else if (charCode === 13 || charCode === 3) { + lineWidth = 0; + newLineFlag = true; + currentHeight += documentData.finalLineHeight || documentData.finalSize * 1.2; + } + if (fontManager.chars) { + charData = fontManager.getCharData(finalText[i], fontData.fStyle, fontData.fFamily); + cLength = newLineFlag ? 0 : charData.w * documentData.finalSize / 100; + } else { + cLength = fontManager.measureText(finalText[i], documentData.f, documentData.finalSize); + } + if (lineWidth + cLength > boxWidth && finalText[i] !== " ") { + if (lastSpaceIndex === -1) { + len += 1; + } else { + i = lastSpaceIndex; + } + currentHeight += documentData.finalLineHeight || documentData.finalSize * 1.2; + finalText.splice(i, lastSpaceIndex === i ? 1 : 0, "\r"); + lastSpaceIndex = -1; + lineWidth = 0; + } else { + lineWidth += cLength; + lineWidth += trackingOffset; + } + } + currentHeight += fontData.ascent * documentData.finalSize / 100; + if (this.canResize && documentData.finalSize > this.minimumFontSize && boxHeight < currentHeight) { + documentData.finalSize -= 1; + documentData.finalLineHeight = documentData.finalSize * documentData.lh / documentData.s; + } else { + documentData.finalText = finalText; + len = documentData.finalText.length; + flag = false; + } + } + } + lineWidth = -trackingOffset; + cLength = 0; + var uncollapsedSpaces = 0; + var currentChar; + for (i = 0;i < len; i += 1) { + newLineFlag = false; + currentChar = documentData.finalText[i]; + charCode = currentChar.charCodeAt(0); + if (charCode === 13 || charCode === 3) { + uncollapsedSpaces = 0; + lineWidths.push(lineWidth); + maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth; + lineWidth = -2 * trackingOffset; + val2 = ""; + newLineFlag = true; + currentLine += 1; + } else { + val2 = currentChar; + } + if (fontManager.chars) { + charData = fontManager.getCharData(currentChar, fontData.fStyle, fontManager.getFontByName(documentData.f).fFamily); + cLength = newLineFlag ? 0 : charData.w * documentData.finalSize / 100; + } else { + cLength = fontManager.measureText(val2, documentData.f, documentData.finalSize); + } + if (currentChar === " ") { + uncollapsedSpaces += cLength + trackingOffset; + } else { + lineWidth += cLength + trackingOffset + uncollapsedSpaces; + uncollapsedSpaces = 0; + } + letters.push({ + l: cLength, + an: cLength, + add: currentSize, + n: newLineFlag, + anIndexes: [], + val: val2, + line: currentLine, + animatorJustifyOffset: 0 + }); + if (anchorGrouping == 2) { + currentSize += cLength; + if (val2 === "" || val2 === " " || i === len - 1) { + if (val2 === "" || val2 === " ") { + currentSize -= cLength; + } + while (currentPos <= i) { + letters[currentPos].an = currentSize; + letters[currentPos].ind = index2; + letters[currentPos].extra = cLength; + currentPos += 1; + } + index2 += 1; + currentSize = 0; + } + } else if (anchorGrouping == 3) { + currentSize += cLength; + if (val2 === "" || i === len - 1) { + if (val2 === "") { + currentSize -= cLength; + } + while (currentPos <= i) { + letters[currentPos].an = currentSize; + letters[currentPos].ind = index2; + letters[currentPos].extra = cLength; + currentPos += 1; + } + currentSize = 0; + index2 += 1; + } + } else { + letters[index2].ind = index2; + letters[index2].extra = 0; + index2 += 1; + } + } + documentData.l = letters; + maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth; + lineWidths.push(lineWidth); + if (documentData.sz) { + documentData.boxWidth = documentData.sz[0]; + documentData.justifyOffset = 0; + } else { + documentData.boxWidth = maxLineWidth; + switch (documentData.j) { + case 1: + documentData.justifyOffset = -documentData.boxWidth; + break; + case 2: + documentData.justifyOffset = -documentData.boxWidth / 2; + break; + default: + documentData.justifyOffset = 0; + } + } + documentData.lineWidths = lineWidths; + var animators = data2.a; + var animatorData; + var letterData; + jLen = animators.length; + var based; + var ind; + var indexes = []; + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorData = animators[j2]; + if (animatorData.a.sc) { + documentData.strokeColorAnim = true; + } + if (animatorData.a.sw) { + documentData.strokeWidthAnim = true; + } + if (animatorData.a.fc || animatorData.a.fh || animatorData.a.fs || animatorData.a.fb) { + documentData.fillColorAnim = true; + } + ind = 0; + based = animatorData.s.b; + for (i = 0;i < len; i += 1) { + letterData = letters[i]; + letterData.anIndexes[j2] = ind; + if (based == 1 && letterData.val !== "" || based == 2 && letterData.val !== "" && letterData.val !== " " || based == 3 && (letterData.n || letterData.val == " " || i == len - 1) || based == 4 && (letterData.n || i == len - 1)) { + if (animatorData.s.rn === 1) { + indexes.push(ind); + } + ind += 1; + } + } + data2.a[j2].s.totalChars = ind; + var currentInd = -1; + var newInd; + if (animatorData.s.rn === 1) { + for (i = 0;i < len; i += 1) { + letterData = letters[i]; + if (currentInd != letterData.anIndexes[j2]) { + currentInd = letterData.anIndexes[j2]; + newInd = indexes.splice(Math.floor(Math.random() * indexes.length), 1)[0]; + } + letterData.anIndexes[j2] = newInd; + } + } + } + documentData.yOffset = documentData.finalLineHeight || documentData.finalSize * 1.2; + documentData.ls = documentData.ls || 0; + documentData.ascent = fontData.ascent * documentData.finalSize / 100; + }; + TextProperty.prototype.updateDocumentData = function(newData, index2) { + index2 = index2 === undefined ? this.keysIndex : index2; + var dData = this.copyData({}, this.data.d.k[index2].s); + dData = this.copyData(dData, newData); + this.data.d.k[index2].s = dData; + this.recalculate(index2); + this.elem.addDynamicProperty(this); + }; + TextProperty.prototype.recalculate = function(index2) { + var dData = this.data.d.k[index2].s; + dData.__complete = false; + this.keysIndex = 0; + this._isFirstFrame = true; + this.getValue(dData); + }; + TextProperty.prototype.canResizeFont = function(_canResize) { + this.canResize = _canResize; + this.recalculate(this.keysIndex); + this.elem.addDynamicProperty(this); + }; + TextProperty.prototype.setMinimumFontSize = function(_fontValue) { + this.minimumFontSize = Math.floor(_fontValue) || 1; + this.recalculate(this.keysIndex); + this.elem.addDynamicProperty(this); + }; + const TextSelectorProp = function() { + var max = Math.max; + var min = Math.min; + var floor = Math.floor; + function TextSelectorPropFactory(elem2, data2) { + this._currentTextLength = -1; + this.k = false; + this.data = data2; + this.elem = elem2; + this.comp = elem2.comp; + this.finalS = 0; + this.finalE = 0; + this.initDynamicPropertyContainer(elem2); + this.s = PropertyFactory.getProp(elem2, data2.s || { k: 0 }, 0, 0, this); + if ("e" in data2) { + this.e = PropertyFactory.getProp(elem2, data2.e, 0, 0, this); + } else { + this.e = { v: 100 }; + } + this.o = PropertyFactory.getProp(elem2, data2.o || { k: 0 }, 0, 0, this); + this.xe = PropertyFactory.getProp(elem2, data2.xe || { k: 0 }, 0, 0, this); + this.ne = PropertyFactory.getProp(elem2, data2.ne || { k: 0 }, 0, 0, this); + this.sm = PropertyFactory.getProp(elem2, data2.sm || { k: 100 }, 0, 0, this); + this.a = PropertyFactory.getProp(elem2, data2.a, 0, 0.01, this); + if (!this.dynamicProperties.length) { + this.getValue(); + } + } + TextSelectorPropFactory.prototype = { + getMult: function(ind) { + if (this._currentTextLength !== this.elem.textProperty.currentData.l.length) { + this.getValue(); + } + var x1 = 0; + var y1 = 0; + var x2 = 1; + var y22 = 1; + if (this.ne.v > 0) { + x1 = this.ne.v / 100; + } else { + y1 = -this.ne.v / 100; + } + if (this.xe.v > 0) { + x2 = 1 - this.xe.v / 100; + } else { + y22 = 1 + this.xe.v / 100; + } + var easer = BezierFactory.getBezierEasing(x1, y1, x2, y22).get; + var mult = 0; + var s = this.finalS; + var e = this.finalE; + var type = this.data.sh; + if (type === 2) { + if (e === s) { + mult = ind >= e ? 1 : 0; + } else { + mult = max(0, min(0.5 / (e - s) + (ind - s) / (e - s), 1)); + } + mult = easer(mult); + } else if (type === 3) { + if (e === s) { + mult = ind >= e ? 0 : 1; + } else { + mult = 1 - max(0, min(0.5 / (e - s) + (ind - s) / (e - s), 1)); + } + mult = easer(mult); + } else if (type === 4) { + if (e === s) { + mult = 0; + } else { + mult = max(0, min(0.5 / (e - s) + (ind - s) / (e - s), 1)); + if (mult < 0.5) { + mult *= 2; + } else { + mult = 1 - 2 * (mult - 0.5); + } + } + mult = easer(mult); + } else if (type === 5) { + if (e === s) { + mult = 0; + } else { + var tot = e - s; + ind = min(max(0, ind + 0.5 - s), e - s); + var x3 = -tot / 2 + ind; + var a = tot / 2; + mult = Math.sqrt(1 - x3 * x3 / (a * a)); + } + mult = easer(mult); + } else if (type === 6) { + if (e === s) { + mult = 0; + } else { + ind = min(max(0, ind + 0.5 - s), e - s); + mult = (1 + Math.cos(Math.PI + Math.PI * 2 * ind / (e - s))) / 2; + } + mult = easer(mult); + } else { + if (ind >= floor(s)) { + if (ind - s < 0) { + mult = max(0, min(min(e, 1) - (s - ind), 1)); + } else { + mult = max(0, min(e - ind, 1)); + } + } + mult = easer(mult); + } + if (this.sm.v !== 100) { + var smoothness = this.sm.v * 0.01; + if (smoothness === 0) { + smoothness = 0.00000001; + } + var threshold = 0.5 - smoothness * 0.5; + if (mult < threshold) { + mult = 0; + } else { + mult = (mult - threshold) / smoothness; + if (mult > 1) { + mult = 1; + } + } + } + return mult * this.a.v; + }, + getValue: function(newCharsFlag) { + this.iterateDynamicProperties(); + this._mdf = newCharsFlag || this._mdf; + this._currentTextLength = this.elem.textProperty.currentData.l.length || 0; + if (newCharsFlag && this.data.r === 2) { + this.e.v = this._currentTextLength; + } + var divisor = this.data.r === 2 ? 1 : 100 / this.data.totalChars; + var o = this.o.v / divisor; + var s = this.s.v / divisor + o; + var e = this.e.v / divisor + o; + if (s > e) { + var _s = s; + s = e; + e = _s; + } + this.finalS = s; + this.finalE = e; + } + }; + extendPrototype([DynamicPropertyContainer], TextSelectorPropFactory); + function getTextSelectorProp(elem2, data2, arr) { + return new TextSelectorPropFactory(elem2, data2, arr); + } + return { + getTextSelectorProp + }; + }(); + TextAnimatorProperty.prototype.searchProperties = function() { + var i; + var len = this._textData.a.length; + var animatorProps; + var getProp = PropertyFactory.getProp; + for (i = 0;i < len; i += 1) { + animatorProps = this._textData.a[i]; + this._animatorsData[i] = new TextAnimatorDataProperty(this._elem, animatorProps, this); + } + if (this._textData.p && "m" in this._textData.p) { + this._pathData = { + a: getProp(this._elem, this._textData.p.a, 0, 0, this), + f: getProp(this._elem, this._textData.p.f, 0, 0, this), + l: getProp(this._elem, this._textData.p.l, 0, 0, this), + r: getProp(this._elem, this._textData.p.r, 0, 0, this), + p: getProp(this._elem, this._textData.p.p, 0, 0, this), + m: this._elem.maskManager.getMaskProperty(this._textData.p.m) + }; + this._hasMaskedPath = true; + } else { + this._hasMaskedPath = false; + } + this._moreOptions.alignment = getProp(this._elem, this._textData.m.a, 1, 0, this); + }; + TextAnimatorProperty.prototype.getMeasures = function(documentData, lettersChangedFlag) { + this.lettersChangedFlag = lettersChangedFlag; + if (!this._mdf && !this._isFirstFrame && !lettersChangedFlag && (!this._hasMaskedPath || !this._pathData.m._mdf)) { + return; + } + this._isFirstFrame = false; + var alignment = this._moreOptions.alignment.v; + var animators = this._animatorsData; + var textData = this._textData; + var matrixHelper = this.mHelper; + var renderType = this._renderType; + var renderedLettersCount = this.renderedLetters.length; + var xPos; + var yPos; + var i; + var len; + var letters = documentData.l; + var pathInfo; + var currentLength; + var currentPoint; + var segmentLength; + var flag; + var pointInd; + var segmentInd; + var prevPoint; + var points; + var segments; + var partialLength; + var totalLength; + var perc; + var tanAngle; + var mask2; + if (this._hasMaskedPath) { + mask2 = this._pathData.m; + if (!this._pathData.n || this._pathData._mdf) { + var paths = mask2.v; + if (this._pathData.r.v) { + paths = paths.reverse(); + } + pathInfo = { + tLength: 0, + segments: [] + }; + len = paths._length - 1; + var bezierData; + totalLength = 0; + for (i = 0;i < len; i += 1) { + bezierData = bez.buildBezierData(paths.v[i], paths.v[i + 1], [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]], [paths.i[i + 1][0] - paths.v[i + 1][0], paths.i[i + 1][1] - paths.v[i + 1][1]]); + pathInfo.tLength += bezierData.segmentLength; + pathInfo.segments.push(bezierData); + totalLength += bezierData.segmentLength; + } + i = len; + if (mask2.v.c) { + bezierData = bez.buildBezierData(paths.v[i], paths.v[0], [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]], [paths.i[0][0] - paths.v[0][0], paths.i[0][1] - paths.v[0][1]]); + pathInfo.tLength += bezierData.segmentLength; + pathInfo.segments.push(bezierData); + totalLength += bezierData.segmentLength; + } + this._pathData.pi = pathInfo; + } + pathInfo = this._pathData.pi; + currentLength = this._pathData.f.v; + segmentInd = 0; + pointInd = 1; + segmentLength = 0; + flag = true; + segments = pathInfo.segments; + if (currentLength < 0 && mask2.v.c) { + if (pathInfo.tLength < Math.abs(currentLength)) { + currentLength = -Math.abs(currentLength) % pathInfo.tLength; + } + segmentInd = segments.length - 1; + points = segments[segmentInd].points; + pointInd = points.length - 1; + while (currentLength < 0) { + currentLength += points[pointInd].partialLength; + pointInd -= 1; + if (pointInd < 0) { + segmentInd -= 1; + points = segments[segmentInd].points; + pointInd = points.length - 1; + } + } + } + points = segments[segmentInd].points; + prevPoint = points[pointInd - 1]; + currentPoint = points[pointInd]; + partialLength = currentPoint.partialLength; + } + len = letters.length; + xPos = 0; + yPos = 0; + var yOff = documentData.finalSize * 1.2 * 0.714; + var firstLine = true; + var animatorProps; + var animatorSelector; + var j2; + var jLen; + var letterValue; + jLen = animators.length; + var mult; + var ind = -1; + var offf; + var xPathPos; + var yPathPos; + var initPathPos = currentLength; + var initSegmentInd = segmentInd; + var initPointInd = pointInd; + var currentLine = -1; + var elemOpacity; + var sc; + var sw; + var fc; + var k2; + var letterSw; + var letterSc; + var letterFc; + var letterM = ""; + var letterP = this.defaultPropsArray; + var letterO; + if (documentData.j === 2 || documentData.j === 1) { + var animatorJustifyOffset = 0; + var animatorFirstCharOffset = 0; + var justifyOffsetMult = documentData.j === 2 ? -0.5 : -1; + var lastIndex = 0; + var isNewLine = true; + for (i = 0;i < len; i += 1) { + if (letters[i].n) { + if (animatorJustifyOffset) { + animatorJustifyOffset += animatorFirstCharOffset; + } + while (lastIndex < i) { + letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset; + lastIndex += 1; + } + animatorJustifyOffset = 0; + isNewLine = true; + } else { + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.t.propType) { + if (isNewLine && documentData.j === 2) { + animatorFirstCharOffset += animatorProps.t.v * justifyOffsetMult; + } + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + animatorJustifyOffset += animatorProps.t.v * mult[0] * justifyOffsetMult; + } else { + animatorJustifyOffset += animatorProps.t.v * mult * justifyOffsetMult; + } + } + } + isNewLine = false; + } + } + if (animatorJustifyOffset) { + animatorJustifyOffset += animatorFirstCharOffset; + } + while (lastIndex < i) { + letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset; + lastIndex += 1; + } + } + for (i = 0;i < len; i += 1) { + matrixHelper.reset(); + elemOpacity = 1; + if (letters[i].n) { + xPos = 0; + yPos += documentData.yOffset; + yPos += firstLine ? 1 : 0; + currentLength = initPathPos; + firstLine = false; + if (this._hasMaskedPath) { + segmentInd = initSegmentInd; + pointInd = initPointInd; + points = segments[segmentInd].points; + prevPoint = points[pointInd - 1]; + currentPoint = points[pointInd]; + partialLength = currentPoint.partialLength; + segmentLength = 0; + } + letterM = ""; + letterFc = ""; + letterSw = ""; + letterO = ""; + letterP = this.defaultPropsArray; + } else { + if (this._hasMaskedPath) { + if (currentLine !== letters[i].line) { + switch (documentData.j) { + case 1: + currentLength += totalLength - documentData.lineWidths[letters[i].line]; + break; + case 2: + currentLength += (totalLength - documentData.lineWidths[letters[i].line]) / 2; + break; + default: + break; + } + currentLine = letters[i].line; + } + if (ind !== letters[i].ind) { + if (letters[ind]) { + currentLength += letters[ind].extra; + } + currentLength += letters[i].an / 2; + ind = letters[i].ind; + } + currentLength += alignment[0] * letters[i].an * 0.005; + var animatorOffset = 0; + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.p.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + animatorOffset += animatorProps.p.v[0] * mult[0]; + } else { + animatorOffset += animatorProps.p.v[0] * mult; + } + } + if (animatorProps.a.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + animatorOffset += animatorProps.a.v[0] * mult[0]; + } else { + animatorOffset += animatorProps.a.v[0] * mult; + } + } + } + flag = true; + if (this._pathData.a.v) { + currentLength = letters[0].an * 0.5 + (totalLength - this._pathData.f.v - letters[0].an * 0.5 - letters[letters.length - 1].an * 0.5) * ind / (len - 1); + currentLength += this._pathData.f.v; + } + while (flag) { + if (segmentLength + partialLength >= currentLength + animatorOffset || !points) { + perc = (currentLength + animatorOffset - segmentLength) / currentPoint.partialLength; + xPathPos = prevPoint.point[0] + (currentPoint.point[0] - prevPoint.point[0]) * perc; + yPathPos = prevPoint.point[1] + (currentPoint.point[1] - prevPoint.point[1]) * perc; + matrixHelper.translate(-alignment[0] * letters[i].an * 0.005, -(alignment[1] * yOff) * 0.01); + flag = false; + } else if (points) { + segmentLength += currentPoint.partialLength; + pointInd += 1; + if (pointInd >= points.length) { + pointInd = 0; + segmentInd += 1; + if (!segments[segmentInd]) { + if (mask2.v.c) { + pointInd = 0; + segmentInd = 0; + points = segments[segmentInd].points; + } else { + segmentLength -= currentPoint.partialLength; + points = null; + } + } else { + points = segments[segmentInd].points; + } + } + if (points) { + prevPoint = currentPoint; + currentPoint = points[pointInd]; + partialLength = currentPoint.partialLength; + } + } + } + offf = letters[i].an / 2 - letters[i].add; + matrixHelper.translate(-offf, 0, 0); + } else { + offf = letters[i].an / 2 - letters[i].add; + matrixHelper.translate(-offf, 0, 0); + matrixHelper.translate(-alignment[0] * letters[i].an * 0.005, -alignment[1] * yOff * 0.01, 0); + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.t.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (xPos !== 0 || documentData.j !== 0) { + if (this._hasMaskedPath) { + if (mult.length) { + currentLength += animatorProps.t.v * mult[0]; + } else { + currentLength += animatorProps.t.v * mult; + } + } else if (mult.length) { + xPos += animatorProps.t.v * mult[0]; + } else { + xPos += animatorProps.t.v * mult; + } + } + } + } + if (documentData.strokeWidthAnim) { + sw = documentData.sw || 0; + } + if (documentData.strokeColorAnim) { + if (documentData.sc) { + sc = [documentData.sc[0], documentData.sc[1], documentData.sc[2]]; + } else { + sc = [0, 0, 0]; + } + } + if (documentData.fillColorAnim && documentData.fc) { + fc = [documentData.fc[0], documentData.fc[1], documentData.fc[2]]; + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.a.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + matrixHelper.translate(-animatorProps.a.v[0] * mult[0], -animatorProps.a.v[1] * mult[1], animatorProps.a.v[2] * mult[2]); + } else { + matrixHelper.translate(-animatorProps.a.v[0] * mult, -animatorProps.a.v[1] * mult, animatorProps.a.v[2] * mult); + } + } + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.s.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + matrixHelper.scale(1 + (animatorProps.s.v[0] - 1) * mult[0], 1 + (animatorProps.s.v[1] - 1) * mult[1], 1); + } else { + matrixHelper.scale(1 + (animatorProps.s.v[0] - 1) * mult, 1 + (animatorProps.s.v[1] - 1) * mult, 1); + } + } + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (animatorProps.sk.propType) { + if (mult.length) { + matrixHelper.skewFromAxis(-animatorProps.sk.v * mult[0], animatorProps.sa.v * mult[1]); + } else { + matrixHelper.skewFromAxis(-animatorProps.sk.v * mult, animatorProps.sa.v * mult); + } + } + if (animatorProps.r.propType) { + if (mult.length) { + matrixHelper.rotateZ(-animatorProps.r.v * mult[2]); + } else { + matrixHelper.rotateZ(-animatorProps.r.v * mult); + } + } + if (animatorProps.ry.propType) { + if (mult.length) { + matrixHelper.rotateY(animatorProps.ry.v * mult[1]); + } else { + matrixHelper.rotateY(animatorProps.ry.v * mult); + } + } + if (animatorProps.rx.propType) { + if (mult.length) { + matrixHelper.rotateX(animatorProps.rx.v * mult[0]); + } else { + matrixHelper.rotateX(animatorProps.rx.v * mult); + } + } + if (animatorProps.o.propType) { + if (mult.length) { + elemOpacity += (animatorProps.o.v * mult[0] - elemOpacity) * mult[0]; + } else { + elemOpacity += (animatorProps.o.v * mult - elemOpacity) * mult; + } + } + if (documentData.strokeWidthAnim && animatorProps.sw.propType) { + if (mult.length) { + sw += animatorProps.sw.v * mult[0]; + } else { + sw += animatorProps.sw.v * mult; + } + } + if (documentData.strokeColorAnim && animatorProps.sc.propType) { + for (k2 = 0;k2 < 3; k2 += 1) { + if (mult.length) { + sc[k2] += (animatorProps.sc.v[k2] - sc[k2]) * mult[0]; + } else { + sc[k2] += (animatorProps.sc.v[k2] - sc[k2]) * mult; + } + } + } + if (documentData.fillColorAnim && documentData.fc) { + if (animatorProps.fc.propType) { + for (k2 = 0;k2 < 3; k2 += 1) { + if (mult.length) { + fc[k2] += (animatorProps.fc.v[k2] - fc[k2]) * mult[0]; + } else { + fc[k2] += (animatorProps.fc.v[k2] - fc[k2]) * mult; + } + } + } + if (animatorProps.fh.propType) { + if (mult.length) { + fc = addHueToRGB(fc, animatorProps.fh.v * mult[0]); + } else { + fc = addHueToRGB(fc, animatorProps.fh.v * mult); + } + } + if (animatorProps.fs.propType) { + if (mult.length) { + fc = addSaturationToRGB(fc, animatorProps.fs.v * mult[0]); + } else { + fc = addSaturationToRGB(fc, animatorProps.fs.v * mult); + } + } + if (animatorProps.fb.propType) { + if (mult.length) { + fc = addBrightnessToRGB(fc, animatorProps.fb.v * mult[0]); + } else { + fc = addBrightnessToRGB(fc, animatorProps.fb.v * mult); + } + } + } + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.p.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (this._hasMaskedPath) { + if (mult.length) { + matrixHelper.translate(0, animatorProps.p.v[1] * mult[0], -animatorProps.p.v[2] * mult[1]); + } else { + matrixHelper.translate(0, animatorProps.p.v[1] * mult, -animatorProps.p.v[2] * mult); + } + } else if (mult.length) { + matrixHelper.translate(animatorProps.p.v[0] * mult[0], animatorProps.p.v[1] * mult[1], -animatorProps.p.v[2] * mult[2]); + } else { + matrixHelper.translate(animatorProps.p.v[0] * mult, animatorProps.p.v[1] * mult, -animatorProps.p.v[2] * mult); + } + } + } + if (documentData.strokeWidthAnim) { + letterSw = sw < 0 ? 0 : sw; + } + if (documentData.strokeColorAnim) { + letterSc = "rgb(" + Math.round(sc[0] * 255) + "," + Math.round(sc[1] * 255) + "," + Math.round(sc[2] * 255) + ")"; + } + if (documentData.fillColorAnim && documentData.fc) { + letterFc = "rgb(" + Math.round(fc[0] * 255) + "," + Math.round(fc[1] * 255) + "," + Math.round(fc[2] * 255) + ")"; + } + if (this._hasMaskedPath) { + matrixHelper.translate(0, -documentData.ls); + matrixHelper.translate(0, alignment[1] * yOff * 0.01 + yPos, 0); + if (this._pathData.p.v) { + tanAngle = (currentPoint.point[1] - prevPoint.point[1]) / (currentPoint.point[0] - prevPoint.point[0]); + var rot = Math.atan(tanAngle) * 180 / Math.PI; + if (currentPoint.point[0] < prevPoint.point[0]) { + rot += 180; + } + matrixHelper.rotate(-rot * Math.PI / 180); + } + matrixHelper.translate(xPathPos, yPathPos, 0); + currentLength -= alignment[0] * letters[i].an * 0.005; + if (letters[i + 1] && ind !== letters[i + 1].ind) { + currentLength += letters[i].an / 2; + currentLength += documentData.tr * 0.001 * documentData.finalSize; + } + } else { + matrixHelper.translate(xPos, yPos, 0); + if (documentData.ps) { + matrixHelper.translate(documentData.ps[0], documentData.ps[1] + documentData.ascent, 0); + } + switch (documentData.j) { + case 1: + matrixHelper.translate(letters[i].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i].line]), 0, 0); + break; + case 2: + matrixHelper.translate(letters[i].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i].line]) / 2, 0, 0); + break; + default: + break; + } + matrixHelper.translate(0, -documentData.ls); + matrixHelper.translate(offf, 0, 0); + matrixHelper.translate(alignment[0] * letters[i].an * 0.005, alignment[1] * yOff * 0.01, 0); + xPos += letters[i].l + documentData.tr * 0.001 * documentData.finalSize; + } + if (renderType === "html") { + letterM = matrixHelper.toCSS(); + } else if (renderType === "svg") { + letterM = matrixHelper.to2dCSS(); + } else { + letterP = [matrixHelper.props[0], matrixHelper.props[1], matrixHelper.props[2], matrixHelper.props[3], matrixHelper.props[4], matrixHelper.props[5], matrixHelper.props[6], matrixHelper.props[7], matrixHelper.props[8], matrixHelper.props[9], matrixHelper.props[10], matrixHelper.props[11], matrixHelper.props[12], matrixHelper.props[13], matrixHelper.props[14], matrixHelper.props[15]]; + } + letterO = elemOpacity; + } + if (renderedLettersCount <= i) { + letterValue = new LetterProps(letterO, letterSw, letterSc, letterFc, letterM, letterP); + this.renderedLetters.push(letterValue); + renderedLettersCount += 1; + this.lettersChangedFlag = true; + } else { + letterValue = this.renderedLetters[i]; + this.lettersChangedFlag = letterValue.update(letterO, letterSw, letterSc, letterFc, letterM, letterP) || this.lettersChangedFlag; + } + } + }; + TextAnimatorProperty.prototype.getValue = function() { + if (this._elem.globalData.frameId === this._frameId) { + return; + } + this._frameId = this._elem.globalData.frameId; + this.iterateDynamicProperties(); + }; + TextAnimatorProperty.prototype.mHelper = new Matrix; + TextAnimatorProperty.prototype.defaultPropsArray = []; + extendPrototype([DynamicPropertyContainer], TextAnimatorProperty); + ITextElement.prototype.initElement = function(data2, globalData2, comp2) { + this.lettersChangedFlag = true; + this.initFrame(); + this.initBaseData(data2, globalData2, comp2); + this.textProperty = new TextProperty(this, data2.t, this.dynamicProperties); + this.textAnimator = new TextAnimatorProperty(data2.t, this.renderType, this); + this.initTransform(data2, globalData2, comp2); + this.initHierarchy(); + this.initRenderable(); + this.initRendererElement(); + this.createContainerElements(); + this.createRenderableComponents(); + this.createContent(); + this.hide(); + this.textAnimator.searchProperties(this.dynamicProperties); + }; + ITextElement.prototype.prepareFrame = function(num) { + this._mdf = false; + this.prepareRenderableFrame(num); + this.prepareProperties(num, this.isInRange); + if (this.textProperty._mdf || this.textProperty._isFirstFrame) { + this.buildNewText(); + this.textProperty._isFirstFrame = false; + this.textProperty._mdf = false; + } + }; + ITextElement.prototype.createPathShape = function(matrixHelper, shapes) { + var j2; + var jLen = shapes.length; + var pathNodes; + var shapeStr = ""; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (shapes[j2].ty === "sh") { + pathNodes = shapes[j2].ks.k; + shapeStr += buildShapeString(pathNodes, pathNodes.i.length, true, matrixHelper); + } + } + return shapeStr; + }; + ITextElement.prototype.updateDocumentData = function(newData, index2) { + this.textProperty.updateDocumentData(newData, index2); + }; + ITextElement.prototype.canResizeFont = function(_canResize) { + this.textProperty.canResizeFont(_canResize); + }; + ITextElement.prototype.setMinimumFontSize = function(_fontSize) { + this.textProperty.setMinimumFontSize(_fontSize); + }; + ITextElement.prototype.applyTextPropertiesToMatrix = function(documentData, matrixHelper, lineNumber, xPos, yPos) { + if (documentData.ps) { + matrixHelper.translate(documentData.ps[0], documentData.ps[1] + documentData.ascent, 0); + } + matrixHelper.translate(0, -documentData.ls, 0); + switch (documentData.j) { + case 1: + matrixHelper.translate(documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[lineNumber]), 0, 0); + break; + case 2: + matrixHelper.translate(documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[lineNumber]) / 2, 0, 0); + break; + default: + break; + } + matrixHelper.translate(xPos, yPos, 0); + }; + ITextElement.prototype.buildColor = function(colorData) { + return "rgb(" + Math.round(colorData[0] * 255) + "," + Math.round(colorData[1] * 255) + "," + Math.round(colorData[2] * 255) + ")"; + }; + ITextElement.prototype.emptyProp = new LetterProps; + ITextElement.prototype.destroy = function() { + }; + emptyShapeData = { + shapes: [] + }; + extendPrototype([BaseElement, TransformElement, SVGBaseElement, HierarchyElement, FrameElement, RenderableDOMElement, ITextElement], SVGTextLottieElement); + SVGTextLottieElement.prototype.createContent = function() { + if (this.data.singleShape && !this.globalData.fontManager.chars) { + this.textContainer = createNS("text"); + } + }; + SVGTextLottieElement.prototype.buildTextContents = function(textArray) { + var i = 0; + var len = textArray.length; + var textContents = []; + var currentTextContent = ""; + while (i < len) { + if (textArray[i] === String.fromCharCode(13) || textArray[i] === String.fromCharCode(3)) { + textContents.push(currentTextContent); + currentTextContent = ""; + } else { + currentTextContent += textArray[i]; + } + i += 1; + } + textContents.push(currentTextContent); + return textContents; + }; + SVGTextLottieElement.prototype.buildShapeData = function(data2, scale2) { + if (data2.shapes && data2.shapes.length) { + var shape = data2.shapes[0]; + if (shape.it) { + var shapeItem = shape.it[shape.it.length - 1]; + if (shapeItem.s) { + shapeItem.s.k[0] = scale2; + shapeItem.s.k[1] = scale2; + } + } + } + return data2; + }; + SVGTextLottieElement.prototype.buildNewText = function() { + this.addDynamicProperty(this); + var i; + var len; + var documentData = this.textProperty.currentData; + this.renderedLetters = createSizedArray(documentData ? documentData.l.length : 0); + if (documentData.fc) { + this.layerElement.setAttribute("fill", this.buildColor(documentData.fc)); + } else { + this.layerElement.setAttribute("fill", "rgba(0,0,0,0)"); + } + if (documentData.sc) { + this.layerElement.setAttribute("stroke", this.buildColor(documentData.sc)); + this.layerElement.setAttribute("stroke-width", documentData.sw); + } + this.layerElement.setAttribute("font-size", documentData.finalSize); + var fontData = this.globalData.fontManager.getFontByName(documentData.f); + if (fontData.fClass) { + this.layerElement.setAttribute("class", fontData.fClass); + } else { + this.layerElement.setAttribute("font-family", fontData.fFamily); + var fWeight = documentData.fWeight; + var fStyle = documentData.fStyle; + this.layerElement.setAttribute("font-style", fStyle); + this.layerElement.setAttribute("font-weight", fWeight); + } + this.layerElement.setAttribute("aria-label", documentData.t); + var letters = documentData.l || []; + var usesGlyphs = !!this.globalData.fontManager.chars; + len = letters.length; + var tSpan; + var matrixHelper = this.mHelper; + var shapeStr = ""; + var singleShape = this.data.singleShape; + var xPos = 0; + var yPos = 0; + var firstLine = true; + var trackingOffset = documentData.tr * 0.001 * documentData.finalSize; + if (singleShape && !usesGlyphs && !documentData.sz) { + var tElement = this.textContainer; + var justify = "start"; + switch (documentData.j) { + case 1: + justify = "end"; + break; + case 2: + justify = "middle"; + break; + default: + justify = "start"; + break; + } + tElement.setAttribute("text-anchor", justify); + tElement.setAttribute("letter-spacing", trackingOffset); + var textContent = this.buildTextContents(documentData.finalText); + len = textContent.length; + yPos = documentData.ps ? documentData.ps[1] + documentData.ascent : 0; + for (i = 0;i < len; i += 1) { + tSpan = this.textSpans[i].span || createNS("tspan"); + tSpan.textContent = textContent[i]; + tSpan.setAttribute("x", 0); + tSpan.setAttribute("y", yPos); + tSpan.style.display = "inherit"; + tElement.appendChild(tSpan); + if (!this.textSpans[i]) { + this.textSpans[i] = { + span: null, + glyph: null + }; + } + this.textSpans[i].span = tSpan; + yPos += documentData.finalLineHeight; + } + this.layerElement.appendChild(tElement); + } else { + var cachedSpansLength = this.textSpans.length; + var charData; + for (i = 0;i < len; i += 1) { + if (!this.textSpans[i]) { + this.textSpans[i] = { + span: null, + childSpan: null, + glyph: null + }; + } + if (!usesGlyphs || !singleShape || i === 0) { + tSpan = cachedSpansLength > i ? this.textSpans[i].span : createNS(usesGlyphs ? "g" : "text"); + if (cachedSpansLength <= i) { + tSpan.setAttribute("stroke-linecap", "butt"); + tSpan.setAttribute("stroke-linejoin", "round"); + tSpan.setAttribute("stroke-miterlimit", "4"); + this.textSpans[i].span = tSpan; + if (usesGlyphs) { + var childSpan = createNS("g"); + tSpan.appendChild(childSpan); + this.textSpans[i].childSpan = childSpan; + } + this.textSpans[i].span = tSpan; + this.layerElement.appendChild(tSpan); + } + tSpan.style.display = "inherit"; + } + matrixHelper.reset(); + if (singleShape) { + if (letters[i].n) { + xPos = -trackingOffset; + yPos += documentData.yOffset; + yPos += firstLine ? 1 : 0; + firstLine = false; + } + this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i].line, xPos, yPos); + xPos += letters[i].l || 0; + xPos += trackingOffset; + } + if (usesGlyphs) { + charData = this.globalData.fontManager.getCharData(documentData.finalText[i], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily); + var glyphElement; + if (charData.t === 1) { + glyphElement = new SVGCompElement(charData.data, this.globalData, this); + } else { + var data2 = emptyShapeData; + if (charData.data && charData.data.shapes) { + data2 = this.buildShapeData(charData.data, documentData.finalSize); + } + glyphElement = new SVGShapeElement(data2, this.globalData, this); + } + if (this.textSpans[i].glyph) { + var glyph = this.textSpans[i].glyph; + this.textSpans[i].childSpan.removeChild(glyph.layerElement); + glyph.destroy(); + } + this.textSpans[i].glyph = glyphElement; + glyphElement._debug = true; + glyphElement.prepareFrame(0); + glyphElement.renderFrame(); + this.textSpans[i].childSpan.appendChild(glyphElement.layerElement); + if (charData.t === 1) { + this.textSpans[i].childSpan.setAttribute("transform", "scale(" + documentData.finalSize / 100 + "," + documentData.finalSize / 100 + ")"); + } + } else { + if (singleShape) { + tSpan.setAttribute("transform", "translate(" + matrixHelper.props[12] + "," + matrixHelper.props[13] + ")"); + } + tSpan.textContent = letters[i].val; + tSpan.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space", "preserve"); + } + } + if (singleShape && tSpan) { + tSpan.setAttribute("d", shapeStr); + } + } + while (i < this.textSpans.length) { + this.textSpans[i].span.style.display = "none"; + i += 1; + } + this._sizeChanged = true; + }; + SVGTextLottieElement.prototype.sourceRectAtTime = function() { + this.prepareFrame(this.comp.renderedFrame - this.data.st); + this.renderInnerContent(); + if (this._sizeChanged) { + this._sizeChanged = false; + var textBox = this.layerElement.getBBox(); + this.bbox = { + top: textBox.y, + left: textBox.x, + width: textBox.width, + height: textBox.height + }; + } + return this.bbox; + }; + SVGTextLottieElement.prototype.getValue = function() { + var i; + var len = this.textSpans.length; + var glyphElement; + this.renderedFrame = this.comp.renderedFrame; + for (i = 0;i < len; i += 1) { + glyphElement = this.textSpans[i].glyph; + if (glyphElement) { + glyphElement.prepareFrame(this.comp.renderedFrame - this.data.st); + if (glyphElement._mdf) { + this._mdf = true; + } + } + } + }; + SVGTextLottieElement.prototype.renderInnerContent = function() { + if (!this.data.singleShape || this._mdf) { + this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag); + if (this.lettersChangedFlag || this.textAnimator.lettersChangedFlag) { + this._sizeChanged = true; + var i; + var len; + var renderedLetters = this.textAnimator.renderedLetters; + var letters = this.textProperty.currentData.l; + len = letters.length; + var renderedLetter; + var textSpan; + var glyphElement; + for (i = 0;i < len; i += 1) { + if (!letters[i].n) { + renderedLetter = renderedLetters[i]; + textSpan = this.textSpans[i].span; + glyphElement = this.textSpans[i].glyph; + if (glyphElement) { + glyphElement.renderFrame(); + } + if (renderedLetter._mdf.m) { + textSpan.setAttribute("transform", renderedLetter.m); + } + if (renderedLetter._mdf.o) { + textSpan.setAttribute("opacity", renderedLetter.o); + } + if (renderedLetter._mdf.sw) { + textSpan.setAttribute("stroke-width", renderedLetter.sw); + } + if (renderedLetter._mdf.sc) { + textSpan.setAttribute("stroke", renderedLetter.sc); + } + if (renderedLetter._mdf.fc) { + textSpan.setAttribute("fill", renderedLetter.fc); + } + } + } + } + } + }; + extendPrototype([IImageElement], ISolidElement); + ISolidElement.prototype.createContent = function() { + var rect = createNS("rect"); + rect.setAttribute("width", this.data.sw); + rect.setAttribute("height", this.data.sh); + rect.setAttribute("fill", this.data.sc); + this.layerElement.appendChild(rect); + }; + NullElement.prototype.prepareFrame = function(num) { + this.prepareProperties(num, true); + }; + NullElement.prototype.renderFrame = function() { + }; + NullElement.prototype.getBaseElement = function() { + return null; + }; + NullElement.prototype.destroy = function() { + }; + NullElement.prototype.sourceRectAtTime = function() { + }; + NullElement.prototype.hide = function() { + }; + extendPrototype([BaseElement, TransformElement, HierarchyElement, FrameElement], NullElement); + extendPrototype([BaseRenderer], SVGRendererBase); + SVGRendererBase.prototype.createNull = function(data2) { + return new NullElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.createShape = function(data2) { + return new SVGShapeElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.createText = function(data2) { + return new SVGTextLottieElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.createImage = function(data2) { + return new IImageElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.createSolid = function(data2) { + return new ISolidElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.configAnimation = function(animData) { + this.svgElement.setAttribute("xmlns", "http://www.w3.org/2000/svg"); + if (this.renderConfig.viewBoxSize) { + this.svgElement.setAttribute("viewBox", this.renderConfig.viewBoxSize); + } else { + this.svgElement.setAttribute("viewBox", "0 0 " + animData.w + " " + animData.h); + } + if (!this.renderConfig.viewBoxOnly) { + this.svgElement.setAttribute("width", animData.w); + this.svgElement.setAttribute("height", animData.h); + this.svgElement.style.width = "100%"; + this.svgElement.style.height = "100%"; + this.svgElement.style.transform = "translate3d(0,0,0)"; + this.svgElement.style.contentVisibility = this.renderConfig.contentVisibility; + } + if (this.renderConfig.width) { + this.svgElement.setAttribute("width", this.renderConfig.width); + } + if (this.renderConfig.height) { + this.svgElement.setAttribute("height", this.renderConfig.height); + } + if (this.renderConfig.className) { + this.svgElement.setAttribute("class", this.renderConfig.className); + } + if (this.renderConfig.id) { + this.svgElement.setAttribute("id", this.renderConfig.id); + } + if (this.renderConfig.focusable !== undefined) { + this.svgElement.setAttribute("focusable", this.renderConfig.focusable); + } + this.svgElement.setAttribute("preserveAspectRatio", this.renderConfig.preserveAspectRatio); + this.animationItem.wrapper.appendChild(this.svgElement); + var defs = this.globalData.defs; + this.setupGlobalData(animData, defs); + this.globalData.progressiveLoad = this.renderConfig.progressiveLoad; + this.data = animData; + var maskElement = createNS("clipPath"); + var rect = createNS("rect"); + rect.setAttribute("width", animData.w); + rect.setAttribute("height", animData.h); + rect.setAttribute("x", 0); + rect.setAttribute("y", 0); + var maskId = createElementID(); + maskElement.setAttribute("id", maskId); + maskElement.appendChild(rect); + this.layerElement.setAttribute("clip-path", "url(" + getLocationHref() + "#" + maskId + ")"); + defs.appendChild(maskElement); + this.layers = animData.layers; + this.elements = createSizedArray(animData.layers.length); + }; + SVGRendererBase.prototype.destroy = function() { + if (this.animationItem.wrapper) { + this.animationItem.wrapper.innerText = ""; + } + this.layerElement = null; + this.globalData.defs = null; + var i; + var len = this.layers ? this.layers.length : 0; + for (i = 0;i < len; i += 1) { + if (this.elements[i]) { + this.elements[i].destroy(); + } + } + this.elements.length = 0; + this.destroyed = true; + this.animationItem = null; + }; + SVGRendererBase.prototype.updateContainerSize = function() { + }; + SVGRendererBase.prototype.buildItem = function(pos) { + var elements = this.elements; + if (elements[pos] || this.layers[pos].ty === 99) { + return; + } + elements[pos] = true; + var element = this.createItem(this.layers[pos]); + elements[pos] = element; + if (getExpressionsPlugin()) { + if (this.layers[pos].ty === 0) { + this.globalData.projectInterface.registerComposition(element); + } + element.initExpressions(); + } + this.appendElementInPos(element, pos); + if (this.layers[pos].tt) { + if (!this.elements[pos - 1] || this.elements[pos - 1] === true) { + this.buildItem(pos - 1); + this.addPendingElement(element); + } else { + element.setMatte(elements[pos - 1].layerId); + } + } + }; + SVGRendererBase.prototype.checkPendingElements = function() { + while (this.pendingElements.length) { + var element = this.pendingElements.pop(); + element.checkParenting(); + if (element.data.tt) { + var i = 0; + var len = this.elements.length; + while (i < len) { + if (this.elements[i] === element) { + element.setMatte(this.elements[i - 1].layerId); + break; + } + i += 1; + } + } + } + }; + SVGRendererBase.prototype.renderFrame = function(num) { + if (this.renderedFrame === num || this.destroyed) { + return; + } + if (num === null) { + num = this.renderedFrame; + } else { + this.renderedFrame = num; + } + this.globalData.frameNum = num; + this.globalData.frameId += 1; + this.globalData.projectInterface.currentFrame = num; + this.globalData._mdf = false; + var i; + var len = this.layers.length; + if (!this.completeLayers) { + this.checkLayers(num); + } + for (i = len - 1;i >= 0; i -= 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].prepareFrame(num - this.layers[i].st); + } + } + if (this.globalData._mdf) { + for (i = 0;i < len; i += 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].renderFrame(); + } + } + } + }; + SVGRendererBase.prototype.appendElementInPos = function(element, pos) { + var newElement = element.getBaseElement(); + if (!newElement) { + return; + } + var i = 0; + var nextElement; + while (i < pos) { + if (this.elements[i] && this.elements[i] !== true && this.elements[i].getBaseElement()) { + nextElement = this.elements[i].getBaseElement(); + } + i += 1; + } + if (nextElement) { + this.layerElement.insertBefore(newElement, nextElement); + } else { + this.layerElement.appendChild(newElement); + } + }; + SVGRendererBase.prototype.hide = function() { + this.layerElement.style.display = "none"; + }; + SVGRendererBase.prototype.show = function() { + this.layerElement.style.display = "block"; + }; + extendPrototype([BaseElement, TransformElement, HierarchyElement, FrameElement, RenderableDOMElement], ICompElement); + ICompElement.prototype.initElement = function(data2, globalData2, comp2) { + this.initFrame(); + this.initBaseData(data2, globalData2, comp2); + this.initTransform(data2, globalData2, comp2); + this.initRenderable(); + this.initHierarchy(); + this.initRendererElement(); + this.createContainerElements(); + this.createRenderableComponents(); + if (this.data.xt || !globalData2.progressiveLoad) { + this.buildAllItems(); + } + this.hide(); + }; + ICompElement.prototype.prepareFrame = function(num) { + this._mdf = false; + this.prepareRenderableFrame(num); + this.prepareProperties(num, this.isInRange); + if (!this.isInRange && !this.data.xt) { + return; + } + if (!this.tm._placeholder) { + var timeRemapped = this.tm.v; + if (timeRemapped === this.data.op) { + timeRemapped = this.data.op - 1; + } + this.renderedFrame = timeRemapped; + } else { + this.renderedFrame = num / this.data.sr; + } + var i; + var len = this.elements.length; + if (!this.completeLayers) { + this.checkLayers(this.renderedFrame); + } + for (i = len - 1;i >= 0; i -= 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].prepareFrame(this.renderedFrame - this.layers[i].st); + if (this.elements[i]._mdf) { + this._mdf = true; + } + } + } + }; + ICompElement.prototype.renderInnerContent = function() { + var i; + var len = this.layers.length; + for (i = 0;i < len; i += 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].renderFrame(); + } + } + }; + ICompElement.prototype.setElements = function(elems) { + this.elements = elems; + }; + ICompElement.prototype.getElements = function() { + return this.elements; + }; + ICompElement.prototype.destroyElements = function() { + var i; + var len = this.layers.length; + for (i = 0;i < len; i += 1) { + if (this.elements[i]) { + this.elements[i].destroy(); + } + } + }; + ICompElement.prototype.destroy = function() { + this.destroyElements(); + this.destroyBaseElement(); + }; + extendPrototype([SVGRendererBase, ICompElement, SVGBaseElement], SVGCompElement); + SVGCompElement.prototype.createComp = function(data2) { + return new SVGCompElement(data2, this.globalData, this); + }; + extendPrototype([SVGRendererBase], SVGRenderer); + SVGRenderer.prototype.createComp = function(data2) { + return new SVGCompElement(data2, this.globalData, this); + }; + CVContextData.prototype.duplicate = function() { + var newLength = this._length * 2; + var currentSavedOp = this.savedOp; + this.savedOp = createTypedArray("float32", newLength); + this.savedOp.set(currentSavedOp); + var i = 0; + for (i = this._length;i < newLength; i += 1) { + this.saved[i] = createTypedArray("float32", 16); + } + this._length = newLength; + }; + CVContextData.prototype.reset = function() { + this.cArrPos = 0; + this.cTr.reset(); + this.cO = 1; + }; + ShapeTransformManager.prototype = { + addTransformSequence: function(transforms) { + var i; + var len = transforms.length; + var key2 = "_"; + for (i = 0;i < len; i += 1) { + key2 += transforms[i].transform.key + "_"; + } + var sequence = this.sequences[key2]; + if (!sequence) { + sequence = { + transforms: [].concat(transforms), + finalTransform: new Matrix, + _mdf: false + }; + this.sequences[key2] = sequence; + this.sequenceList.push(sequence); + } + return sequence; + }, + processSequence: function(sequence, isFirstFrame) { + var i = 0; + var len = sequence.transforms.length; + var _mdf = isFirstFrame; + while (i < len && !isFirstFrame) { + if (sequence.transforms[i].transform.mProps._mdf) { + _mdf = true; + break; + } + i += 1; + } + if (_mdf) { + var props; + sequence.finalTransform.reset(); + for (i = len - 1;i >= 0; i -= 1) { + props = sequence.transforms[i].transform.mProps.v.props; + sequence.finalTransform.transform(props[0], props[1], props[2], props[3], props[4], props[5], props[6], props[7], props[8], props[9], props[10], props[11], props[12], props[13], props[14], props[15]); + } + } + sequence._mdf = _mdf; + }, + processSequences: function(isFirstFrame) { + var i; + var len = this.sequenceList.length; + for (i = 0;i < len; i += 1) { + this.processSequence(this.sequenceList[i], isFirstFrame); + } + }, + getNewKey: function() { + this.transform_key_count += 1; + return "_" + this.transform_key_count; + } + }; + CVEffects.prototype.renderFrame = function() { + }; + CVMaskElement.prototype.renderFrame = function() { + if (!this.hasMasks) { + return; + } + var transform2 = this.element.finalTransform.mat; + var ctx = this.element.canvasContext; + var i; + var len = this.masksProperties.length; + var pt; + var pts; + var data2; + ctx.beginPath(); + for (i = 0;i < len; i += 1) { + if (this.masksProperties[i].mode !== "n") { + if (this.masksProperties[i].inv) { + ctx.moveTo(0, 0); + ctx.lineTo(this.element.globalData.compSize.w, 0); + ctx.lineTo(this.element.globalData.compSize.w, this.element.globalData.compSize.h); + ctx.lineTo(0, this.element.globalData.compSize.h); + ctx.lineTo(0, 0); + } + data2 = this.viewData[i].v; + pt = transform2.applyToPointArray(data2.v[0][0], data2.v[0][1], 0); + ctx.moveTo(pt[0], pt[1]); + var j2; + var jLen = data2._length; + for (j2 = 1;j2 < jLen; j2 += 1) { + pts = transform2.applyToTriplePoints(data2.o[j2 - 1], data2.i[j2], data2.v[j2]); + ctx.bezierCurveTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]); + } + pts = transform2.applyToTriplePoints(data2.o[j2 - 1], data2.i[0], data2.v[0]); + ctx.bezierCurveTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]); + } + } + this.element.globalData.renderer.save(true); + ctx.clip(); + }; + CVMaskElement.prototype.getMaskProperty = MaskElement.prototype.getMaskProperty; + CVMaskElement.prototype.destroy = function() { + this.element = null; + }; + CVBaseElement.prototype = { + createElements: function() { + }, + initRendererElement: function() { + }, + createContainerElements: function() { + this.canvasContext = this.globalData.canvasContext; + this.renderableEffectsManager = new CVEffects(this); + }, + createContent: function() { + }, + setBlendMode: function() { + var globalData2 = this.globalData; + if (globalData2.blendMode !== this.data.bm) { + globalData2.blendMode = this.data.bm; + var blendModeValue = getBlendMode(this.data.bm); + globalData2.canvasContext.globalCompositeOperation = blendModeValue; + } + }, + createRenderableComponents: function() { + this.maskManager = new CVMaskElement(this.data, this); + }, + hideElement: function() { + if (!this.hidden && (!this.isInRange || this.isTransparent)) { + this.hidden = true; + } + }, + showElement: function() { + if (this.isInRange && !this.isTransparent) { + this.hidden = false; + this._isFirstFrame = true; + this.maskManager._isFirstFrame = true; + } + }, + renderFrame: function() { + if (this.hidden || this.data.hd) { + return; + } + this.renderTransform(); + this.renderRenderable(); + this.setBlendMode(); + var forceRealStack = this.data.ty === 0; + this.globalData.renderer.save(forceRealStack); + this.globalData.renderer.ctxTransform(this.finalTransform.mat.props); + this.globalData.renderer.ctxOpacity(this.finalTransform.mProp.o.v); + this.renderInnerContent(); + this.globalData.renderer.restore(forceRealStack); + if (this.maskManager.hasMasks) { + this.globalData.renderer.restore(true); + } + if (this._isFirstFrame) { + this._isFirstFrame = false; + } + }, + destroy: function() { + this.canvasContext = null; + this.data = null; + this.globalData = null; + this.maskManager.destroy(); + }, + mHelper: new Matrix + }; + CVBaseElement.prototype.hide = CVBaseElement.prototype.hideElement; + CVBaseElement.prototype.show = CVBaseElement.prototype.showElement; + CVShapeData.prototype.setAsAnimated = SVGShapeData.prototype.setAsAnimated; + extendPrototype([BaseElement, TransformElement, CVBaseElement, IShapeElement, HierarchyElement, FrameElement, RenderableElement], CVShapeElement); + CVShapeElement.prototype.initElement = RenderableDOMElement.prototype.initElement; + CVShapeElement.prototype.transformHelper = { opacity: 1, _opMdf: false }; + CVShapeElement.prototype.dashResetter = []; + CVShapeElement.prototype.createContent = function() { + this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, true, []); + }; + CVShapeElement.prototype.createStyleElement = function(data2, transforms) { + var styleElem = { + data: data2, + type: data2.ty, + preTransforms: this.transformsManager.addTransformSequence(transforms), + transforms: [], + elements: [], + closed: data2.hd === true + }; + var elementData = {}; + if (data2.ty === "fl" || data2.ty === "st") { + elementData.c = PropertyFactory.getProp(this, data2.c, 1, 255, this); + if (!elementData.c.k) { + styleElem.co = "rgb(" + bmFloor(elementData.c.v[0]) + "," + bmFloor(elementData.c.v[1]) + "," + bmFloor(elementData.c.v[2]) + ")"; + } + } else if (data2.ty === "gf" || data2.ty === "gs") { + elementData.s = PropertyFactory.getProp(this, data2.s, 1, null, this); + elementData.e = PropertyFactory.getProp(this, data2.e, 1, null, this); + elementData.h = PropertyFactory.getProp(this, data2.h || { k: 0 }, 0, 0.01, this); + elementData.a = PropertyFactory.getProp(this, data2.a || { k: 0 }, 0, degToRads, this); + elementData.g = new GradientProperty(this, data2.g, this); + } + elementData.o = PropertyFactory.getProp(this, data2.o, 0, 0.01, this); + if (data2.ty === "st" || data2.ty === "gs") { + styleElem.lc = lineCapEnum[data2.lc || 2]; + styleElem.lj = lineJoinEnum[data2.lj || 2]; + if (data2.lj == 1) { + styleElem.ml = data2.ml; + } + elementData.w = PropertyFactory.getProp(this, data2.w, 0, null, this); + if (!elementData.w.k) { + styleElem.wi = elementData.w.v; + } + if (data2.d) { + var d = new DashProperty(this, data2.d, "canvas", this); + elementData.d = d; + if (!elementData.d.k) { + styleElem.da = elementData.d.dashArray; + styleElem.do = elementData.d.dashoffset[0]; + } + } + } else { + styleElem.r = data2.r === 2 ? "evenodd" : "nonzero"; + } + this.stylesList.push(styleElem); + elementData.style = styleElem; + return elementData; + }; + CVShapeElement.prototype.createGroupElement = function() { + var elementData = { + it: [], + prevViewData: [] + }; + return elementData; + }; + CVShapeElement.prototype.createTransformElement = function(data2) { + var elementData = { + transform: { + opacity: 1, + _opMdf: false, + key: this.transformsManager.getNewKey(), + op: PropertyFactory.getProp(this, data2.o, 0, 0.01, this), + mProps: TransformPropertyFactory.getTransformProperty(this, data2, this) + } + }; + return elementData; + }; + CVShapeElement.prototype.createShapeElement = function(data2) { + var elementData = new CVShapeData(this, data2, this.stylesList, this.transformsManager); + this.shapes.push(elementData); + this.addShapeToModifiers(elementData); + return elementData; + }; + CVShapeElement.prototype.reloadShapes = function() { + this._isFirstFrame = true; + var i; + var len = this.itemsData.length; + for (i = 0;i < len; i += 1) { + this.prevViewData[i] = this.itemsData[i]; + } + this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, true, []); + len = this.dynamicProperties.length; + for (i = 0;i < len; i += 1) { + this.dynamicProperties[i].getValue(); + } + this.renderModifiers(); + this.transformsManager.processSequences(this._isFirstFrame); + }; + CVShapeElement.prototype.addTransformToStyleList = function(transform2) { + var i; + var len = this.stylesList.length; + for (i = 0;i < len; i += 1) { + if (!this.stylesList[i].closed) { + this.stylesList[i].transforms.push(transform2); + } + } + }; + CVShapeElement.prototype.removeTransformFromStyleList = function() { + var i; + var len = this.stylesList.length; + for (i = 0;i < len; i += 1) { + if (!this.stylesList[i].closed) { + this.stylesList[i].transforms.pop(); + } + } + }; + CVShapeElement.prototype.closeStyles = function(styles) { + var i; + var len = styles.length; + for (i = 0;i < len; i += 1) { + styles[i].closed = true; + } + }; + CVShapeElement.prototype.searchShapes = function(arr, itemsData, prevViewData, shouldRender, transforms) { + var i; + var len = arr.length - 1; + var j2; + var jLen; + var ownStyles = []; + var ownModifiers = []; + var processedPos; + var modifier; + var currentTransform; + var ownTransforms = [].concat(transforms); + for (i = len;i >= 0; i -= 1) { + processedPos = this.searchProcessedElement(arr[i]); + if (!processedPos) { + arr[i]._shouldRender = shouldRender; + } else { + itemsData[i] = prevViewData[processedPos - 1]; + } + if (arr[i].ty === "fl" || arr[i].ty === "st" || arr[i].ty === "gf" || arr[i].ty === "gs") { + if (!processedPos) { + itemsData[i] = this.createStyleElement(arr[i], ownTransforms); + } else { + itemsData[i].style.closed = false; + } + ownStyles.push(itemsData[i].style); + } else if (arr[i].ty === "gr") { + if (!processedPos) { + itemsData[i] = this.createGroupElement(arr[i]); + } else { + jLen = itemsData[i].it.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + itemsData[i].prevViewData[j2] = itemsData[i].it[j2]; + } + } + this.searchShapes(arr[i].it, itemsData[i].it, itemsData[i].prevViewData, shouldRender, ownTransforms); + } else if (arr[i].ty === "tr") { + if (!processedPos) { + currentTransform = this.createTransformElement(arr[i]); + itemsData[i] = currentTransform; + } + ownTransforms.push(itemsData[i]); + this.addTransformToStyleList(itemsData[i]); + } else if (arr[i].ty === "sh" || arr[i].ty === "rc" || arr[i].ty === "el" || arr[i].ty === "sr") { + if (!processedPos) { + itemsData[i] = this.createShapeElement(arr[i]); + } + } else if (arr[i].ty === "tm" || arr[i].ty === "rd" || arr[i].ty === "pb") { + if (!processedPos) { + modifier = ShapeModifiers.getModifier(arr[i].ty); + modifier.init(this, arr[i]); + itemsData[i] = modifier; + this.shapeModifiers.push(modifier); + } else { + modifier = itemsData[i]; + modifier.closed = false; + } + ownModifiers.push(modifier); + } else if (arr[i].ty === "rp") { + if (!processedPos) { + modifier = ShapeModifiers.getModifier(arr[i].ty); + itemsData[i] = modifier; + modifier.init(this, arr, i, itemsData); + this.shapeModifiers.push(modifier); + shouldRender = false; + } else { + modifier = itemsData[i]; + modifier.closed = true; + } + ownModifiers.push(modifier); + } + this.addProcessedElement(arr[i], i + 1); + } + this.removeTransformFromStyleList(); + this.closeStyles(ownStyles); + len = ownModifiers.length; + for (i = 0;i < len; i += 1) { + ownModifiers[i].closed = true; + } + }; + CVShapeElement.prototype.renderInnerContent = function() { + this.transformHelper.opacity = 1; + this.transformHelper._opMdf = false; + this.renderModifiers(); + this.transformsManager.processSequences(this._isFirstFrame); + this.renderShape(this.transformHelper, this.shapesData, this.itemsData, true); + }; + CVShapeElement.prototype.renderShapeTransform = function(parentTransform, groupTransform) { + if (parentTransform._opMdf || groupTransform.op._mdf || this._isFirstFrame) { + groupTransform.opacity = parentTransform.opacity; + groupTransform.opacity *= groupTransform.op.v; + groupTransform._opMdf = true; + } + }; + CVShapeElement.prototype.drawLayer = function() { + var i; + var len = this.stylesList.length; + var j2; + var jLen; + var k2; + var kLen; + var elems; + var nodes; + var renderer2 = this.globalData.renderer; + var ctx = this.globalData.canvasContext; + var type; + var currentStyle; + for (i = 0;i < len; i += 1) { + currentStyle = this.stylesList[i]; + type = currentStyle.type; + if (!((type === "st" || type === "gs") && currentStyle.wi === 0 || !currentStyle.data._shouldRender || currentStyle.coOp === 0 || this.globalData.currentGlobalAlpha === 0)) { + renderer2.save(); + elems = currentStyle.elements; + if (type === "st" || type === "gs") { + ctx.strokeStyle = type === "st" ? currentStyle.co : currentStyle.grd; + ctx.lineWidth = currentStyle.wi; + ctx.lineCap = currentStyle.lc; + ctx.lineJoin = currentStyle.lj; + ctx.miterLimit = currentStyle.ml || 0; + } else { + ctx.fillStyle = type === "fl" ? currentStyle.co : currentStyle.grd; + } + renderer2.ctxOpacity(currentStyle.coOp); + if (type !== "st" && type !== "gs") { + ctx.beginPath(); + } + renderer2.ctxTransform(currentStyle.preTransforms.finalTransform.props); + jLen = elems.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (type === "st" || type === "gs") { + ctx.beginPath(); + if (currentStyle.da) { + ctx.setLineDash(currentStyle.da); + ctx.lineDashOffset = currentStyle.do; + } + } + nodes = elems[j2].trNodes; + kLen = nodes.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + if (nodes[k2].t === "m") { + ctx.moveTo(nodes[k2].p[0], nodes[k2].p[1]); + } else if (nodes[k2].t === "c") { + ctx.bezierCurveTo(nodes[k2].pts[0], nodes[k2].pts[1], nodes[k2].pts[2], nodes[k2].pts[3], nodes[k2].pts[4], nodes[k2].pts[5]); + } else { + ctx.closePath(); + } + } + if (type === "st" || type === "gs") { + ctx.stroke(); + if (currentStyle.da) { + ctx.setLineDash(this.dashResetter); + } + } + } + if (type !== "st" && type !== "gs") { + ctx.fill(currentStyle.r); + } + renderer2.restore(); + } + } + }; + CVShapeElement.prototype.renderShape = function(parentTransform, items, data2, isMain) { + var i; + var len = items.length - 1; + var groupTransform; + groupTransform = parentTransform; + for (i = len;i >= 0; i -= 1) { + if (items[i].ty === "tr") { + groupTransform = data2[i].transform; + this.renderShapeTransform(parentTransform, groupTransform); + } else if (items[i].ty === "sh" || items[i].ty === "el" || items[i].ty === "rc" || items[i].ty === "sr") { + this.renderPath(items[i], data2[i]); + } else if (items[i].ty === "fl") { + this.renderFill(items[i], data2[i], groupTransform); + } else if (items[i].ty === "st") { + this.renderStroke(items[i], data2[i], groupTransform); + } else if (items[i].ty === "gf" || items[i].ty === "gs") { + this.renderGradientFill(items[i], data2[i], groupTransform); + } else if (items[i].ty === "gr") { + this.renderShape(groupTransform, items[i].it, data2[i].it); + } else if (items[i].ty === "tm") { + } + } + if (isMain) { + this.drawLayer(); + } + }; + CVShapeElement.prototype.renderStyledShape = function(styledShape, shape) { + if (this._isFirstFrame || shape._mdf || styledShape.transforms._mdf) { + var shapeNodes = styledShape.trNodes; + var paths = shape.paths; + var i; + var len; + var j2; + var jLen = paths._length; + shapeNodes.length = 0; + var groupTransformMat = styledShape.transforms.finalTransform; + for (j2 = 0;j2 < jLen; j2 += 1) { + var pathNodes = paths.shapes[j2]; + if (pathNodes && pathNodes.v) { + len = pathNodes._length; + for (i = 1;i < len; i += 1) { + if (i === 1) { + shapeNodes.push({ + t: "m", + p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0) + }); + } + shapeNodes.push({ + t: "c", + pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[i], pathNodes.v[i]) + }); + } + if (len === 1) { + shapeNodes.push({ + t: "m", + p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0) + }); + } + if (pathNodes.c && len) { + shapeNodes.push({ + t: "c", + pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[0], pathNodes.v[0]) + }); + shapeNodes.push({ + t: "z" + }); + } + } + } + styledShape.trNodes = shapeNodes; + } + }; + CVShapeElement.prototype.renderPath = function(pathData, itemData) { + if (pathData.hd !== true && pathData._shouldRender) { + var i; + var len = itemData.styledShapes.length; + for (i = 0;i < len; i += 1) { + this.renderStyledShape(itemData.styledShapes[i], itemData.sh); + } + } + }; + CVShapeElement.prototype.renderFill = function(styleData, itemData, groupTransform) { + var styleElem = itemData.style; + if (itemData.c._mdf || this._isFirstFrame) { + styleElem.co = "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"; + } + if (itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame) { + styleElem.coOp = itemData.o.v * groupTransform.opacity; + } + }; + CVShapeElement.prototype.renderGradientFill = function(styleData, itemData, groupTransform) { + var styleElem = itemData.style; + var grd; + if (!styleElem.grd || itemData.g._mdf || itemData.s._mdf || itemData.e._mdf || styleData.t !== 1 && (itemData.h._mdf || itemData.a._mdf)) { + var ctx = this.globalData.canvasContext; + var pt1 = itemData.s.v; + var pt2 = itemData.e.v; + if (styleData.t === 1) { + grd = ctx.createLinearGradient(pt1[0], pt1[1], pt2[0], pt2[1]); + } else { + var rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); + var ang = Math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]); + var percent = itemData.h.v; + if (percent >= 1) { + percent = 0.99; + } else if (percent <= -1) { + percent = -0.99; + } + var dist = rad * percent; + var x2 = Math.cos(ang + itemData.a.v) * dist + pt1[0]; + var y3 = Math.sin(ang + itemData.a.v) * dist + pt1[1]; + grd = ctx.createRadialGradient(x2, y3, 0, pt1[0], pt1[1], rad); + } + var i; + var len = styleData.g.p; + var cValues = itemData.g.c; + var opacity = 1; + for (i = 0;i < len; i += 1) { + if (itemData.g._hasOpacity && itemData.g._collapsable) { + opacity = itemData.g.o[i * 2 + 1]; + } + grd.addColorStop(cValues[i * 4] / 100, "rgba(" + cValues[i * 4 + 1] + "," + cValues[i * 4 + 2] + "," + cValues[i * 4 + 3] + "," + opacity + ")"); + } + styleElem.grd = grd; + } + styleElem.coOp = itemData.o.v * groupTransform.opacity; + }; + CVShapeElement.prototype.renderStroke = function(styleData, itemData, groupTransform) { + var styleElem = itemData.style; + var d = itemData.d; + if (d && (d._mdf || this._isFirstFrame)) { + styleElem.da = d.dashArray; + styleElem.do = d.dashoffset[0]; + } + if (itemData.c._mdf || this._isFirstFrame) { + styleElem.co = "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"; + } + if (itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame) { + styleElem.coOp = itemData.o.v * groupTransform.opacity; + } + if (itemData.w._mdf || this._isFirstFrame) { + styleElem.wi = itemData.w.v; + } + }; + CVShapeElement.prototype.destroy = function() { + this.shapesData = null; + this.globalData = null; + this.canvasContext = null; + this.stylesList.length = 0; + this.itemsData.length = 0; + }; + extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement, ITextElement], CVTextElement); + CVTextElement.prototype.tHelper = createTag("canvas").getContext("2d"); + CVTextElement.prototype.buildNewText = function() { + var documentData = this.textProperty.currentData; + this.renderedLetters = createSizedArray(documentData.l ? documentData.l.length : 0); + var hasFill = false; + if (documentData.fc) { + hasFill = true; + this.values.fill = this.buildColor(documentData.fc); + } else { + this.values.fill = "rgba(0,0,0,0)"; + } + this.fill = hasFill; + var hasStroke = false; + if (documentData.sc) { + hasStroke = true; + this.values.stroke = this.buildColor(documentData.sc); + this.values.sWidth = documentData.sw; + } + var fontData = this.globalData.fontManager.getFontByName(documentData.f); + var i; + var len; + var letters = documentData.l; + var matrixHelper = this.mHelper; + this.stroke = hasStroke; + this.values.fValue = documentData.finalSize + "px " + this.globalData.fontManager.getFontByName(documentData.f).fFamily; + len = documentData.finalText.length; + var charData; + var shapeData; + var k2; + var kLen; + var shapes; + var j2; + var jLen; + var pathNodes; + var commands; + var pathArr; + var singleShape = this.data.singleShape; + var trackingOffset = documentData.tr * 0.001 * documentData.finalSize; + var xPos = 0; + var yPos = 0; + var firstLine = true; + var cnt = 0; + for (i = 0;i < len; i += 1) { + charData = this.globalData.fontManager.getCharData(documentData.finalText[i], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily); + shapeData = charData && charData.data || {}; + matrixHelper.reset(); + if (singleShape && letters[i].n) { + xPos = -trackingOffset; + yPos += documentData.yOffset; + yPos += firstLine ? 1 : 0; + firstLine = false; + } + shapes = shapeData.shapes ? shapeData.shapes[0].it : []; + jLen = shapes.length; + matrixHelper.scale(documentData.finalSize / 100, documentData.finalSize / 100); + if (singleShape) { + this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i].line, xPos, yPos); + } + commands = createSizedArray(jLen - 1); + var commandsCounter = 0; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (shapes[j2].ty === "sh") { + kLen = shapes[j2].ks.k.i.length; + pathNodes = shapes[j2].ks.k; + pathArr = []; + for (k2 = 1;k2 < kLen; k2 += 1) { + if (k2 === 1) { + pathArr.push(matrixHelper.applyToX(pathNodes.v[0][0], pathNodes.v[0][1], 0), matrixHelper.applyToY(pathNodes.v[0][0], pathNodes.v[0][1], 0)); + } + pathArr.push(matrixHelper.applyToX(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToY(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToX(pathNodes.i[k2][0], pathNodes.i[k2][1], 0), matrixHelper.applyToY(pathNodes.i[k2][0], pathNodes.i[k2][1], 0), matrixHelper.applyToX(pathNodes.v[k2][0], pathNodes.v[k2][1], 0), matrixHelper.applyToY(pathNodes.v[k2][0], pathNodes.v[k2][1], 0)); + } + pathArr.push(matrixHelper.applyToX(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToY(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToX(pathNodes.i[0][0], pathNodes.i[0][1], 0), matrixHelper.applyToY(pathNodes.i[0][0], pathNodes.i[0][1], 0), matrixHelper.applyToX(pathNodes.v[0][0], pathNodes.v[0][1], 0), matrixHelper.applyToY(pathNodes.v[0][0], pathNodes.v[0][1], 0)); + commands[commandsCounter] = pathArr; + commandsCounter += 1; + } + } + if (singleShape) { + xPos += letters[i].l; + xPos += trackingOffset; + } + if (this.textSpans[cnt]) { + this.textSpans[cnt].elem = commands; + } else { + this.textSpans[cnt] = { elem: commands }; + } + cnt += 1; + } + }; + CVTextElement.prototype.renderInnerContent = function() { + var ctx = this.canvasContext; + ctx.font = this.values.fValue; + ctx.lineCap = "butt"; + ctx.lineJoin = "miter"; + ctx.miterLimit = 4; + if (!this.data.singleShape) { + this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag); + } + var i; + var len; + var j2; + var jLen; + var k2; + var kLen; + var renderedLetters = this.textAnimator.renderedLetters; + var letters = this.textProperty.currentData.l; + len = letters.length; + var renderedLetter; + var lastFill = null; + var lastStroke = null; + var lastStrokeW = null; + var commands; + var pathArr; + for (i = 0;i < len; i += 1) { + if (!letters[i].n) { + renderedLetter = renderedLetters[i]; + if (renderedLetter) { + this.globalData.renderer.save(); + this.globalData.renderer.ctxTransform(renderedLetter.p); + this.globalData.renderer.ctxOpacity(renderedLetter.o); + } + if (this.fill) { + if (renderedLetter && renderedLetter.fc) { + if (lastFill !== renderedLetter.fc) { + lastFill = renderedLetter.fc; + ctx.fillStyle = renderedLetter.fc; + } + } else if (lastFill !== this.values.fill) { + lastFill = this.values.fill; + ctx.fillStyle = this.values.fill; + } + commands = this.textSpans[i].elem; + jLen = commands.length; + this.globalData.canvasContext.beginPath(); + for (j2 = 0;j2 < jLen; j2 += 1) { + pathArr = commands[j2]; + kLen = pathArr.length; + this.globalData.canvasContext.moveTo(pathArr[0], pathArr[1]); + for (k2 = 2;k2 < kLen; k2 += 6) { + this.globalData.canvasContext.bezierCurveTo(pathArr[k2], pathArr[k2 + 1], pathArr[k2 + 2], pathArr[k2 + 3], pathArr[k2 + 4], pathArr[k2 + 5]); + } + } + this.globalData.canvasContext.closePath(); + this.globalData.canvasContext.fill(); + } + if (this.stroke) { + if (renderedLetter && renderedLetter.sw) { + if (lastStrokeW !== renderedLetter.sw) { + lastStrokeW = renderedLetter.sw; + ctx.lineWidth = renderedLetter.sw; + } + } else if (lastStrokeW !== this.values.sWidth) { + lastStrokeW = this.values.sWidth; + ctx.lineWidth = this.values.sWidth; + } + if (renderedLetter && renderedLetter.sc) { + if (lastStroke !== renderedLetter.sc) { + lastStroke = renderedLetter.sc; + ctx.strokeStyle = renderedLetter.sc; + } + } else if (lastStroke !== this.values.stroke) { + lastStroke = this.values.stroke; + ctx.strokeStyle = this.values.stroke; + } + commands = this.textSpans[i].elem; + jLen = commands.length; + this.globalData.canvasContext.beginPath(); + for (j2 = 0;j2 < jLen; j2 += 1) { + pathArr = commands[j2]; + kLen = pathArr.length; + this.globalData.canvasContext.moveTo(pathArr[0], pathArr[1]); + for (k2 = 2;k2 < kLen; k2 += 6) { + this.globalData.canvasContext.bezierCurveTo(pathArr[k2], pathArr[k2 + 1], pathArr[k2 + 2], pathArr[k2 + 3], pathArr[k2 + 4], pathArr[k2 + 5]); + } + } + this.globalData.canvasContext.closePath(); + this.globalData.canvasContext.stroke(); + } + if (renderedLetter) { + this.globalData.renderer.restore(); + } + } + } + }; + extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement], CVImageElement); + CVImageElement.prototype.initElement = SVGShapeElement.prototype.initElement; + CVImageElement.prototype.prepareFrame = IImageElement.prototype.prepareFrame; + CVImageElement.prototype.createContent = function() { + if (this.img.width && (this.assetData.w !== this.img.width || this.assetData.h !== this.img.height)) { + var canvas = createTag("canvas"); + canvas.width = this.assetData.w; + canvas.height = this.assetData.h; + var ctx = canvas.getContext("2d"); + var imgW = this.img.width; + var imgH = this.img.height; + var imgRel = imgW / imgH; + var canvasRel = this.assetData.w / this.assetData.h; + var widthCrop; + var heightCrop; + var par = this.assetData.pr || this.globalData.renderConfig.imagePreserveAspectRatio; + if (imgRel > canvasRel && par === "xMidYMid slice" || imgRel < canvasRel && par !== "xMidYMid slice") { + heightCrop = imgH; + widthCrop = heightCrop * canvasRel; + } else { + widthCrop = imgW; + heightCrop = widthCrop / canvasRel; + } + ctx.drawImage(this.img, (imgW - widthCrop) / 2, (imgH - heightCrop) / 2, widthCrop, heightCrop, 0, 0, this.assetData.w, this.assetData.h); + this.img = canvas; + } + }; + CVImageElement.prototype.renderInnerContent = function() { + this.canvasContext.drawImage(this.img, 0, 0); + }; + CVImageElement.prototype.destroy = function() { + this.img = null; + }; + extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement], CVSolidElement); + CVSolidElement.prototype.initElement = SVGShapeElement.prototype.initElement; + CVSolidElement.prototype.prepareFrame = IImageElement.prototype.prepareFrame; + CVSolidElement.prototype.renderInnerContent = function() { + var ctx = this.canvasContext; + ctx.fillStyle = this.data.sc; + ctx.fillRect(0, 0, this.data.sw, this.data.sh); + }; + extendPrototype([BaseRenderer], CanvasRendererBase); + CanvasRendererBase.prototype.createShape = function(data2) { + return new CVShapeElement(data2, this.globalData, this); + }; + CanvasRendererBase.prototype.createText = function(data2) { + return new CVTextElement(data2, this.globalData, this); + }; + CanvasRendererBase.prototype.createImage = function(data2) { + return new CVImageElement(data2, this.globalData, this); + }; + CanvasRendererBase.prototype.createSolid = function(data2) { + return new CVSolidElement(data2, this.globalData, this); + }; + CanvasRendererBase.prototype.createNull = SVGRenderer.prototype.createNull; + CanvasRendererBase.prototype.ctxTransform = function(props) { + if (props[0] === 1 && props[1] === 0 && props[4] === 0 && props[5] === 1 && props[12] === 0 && props[13] === 0) { + return; + } + if (!this.renderConfig.clearCanvas) { + this.canvasContext.transform(props[0], props[1], props[4], props[5], props[12], props[13]); + return; + } + this.transformMat.cloneFromProps(props); + var cProps = this.contextData.cTr.props; + this.transformMat.transform(cProps[0], cProps[1], cProps[2], cProps[3], cProps[4], cProps[5], cProps[6], cProps[7], cProps[8], cProps[9], cProps[10], cProps[11], cProps[12], cProps[13], cProps[14], cProps[15]); + this.contextData.cTr.cloneFromProps(this.transformMat.props); + var trProps = this.contextData.cTr.props; + this.canvasContext.setTransform(trProps[0], trProps[1], trProps[4], trProps[5], trProps[12], trProps[13]); + }; + CanvasRendererBase.prototype.ctxOpacity = function(op) { + if (!this.renderConfig.clearCanvas) { + this.canvasContext.globalAlpha *= op < 0 ? 0 : op; + this.globalData.currentGlobalAlpha = this.contextData.cO; + return; + } + this.contextData.cO *= op < 0 ? 0 : op; + if (this.globalData.currentGlobalAlpha !== this.contextData.cO) { + this.canvasContext.globalAlpha = this.contextData.cO; + this.globalData.currentGlobalAlpha = this.contextData.cO; + } + }; + CanvasRendererBase.prototype.reset = function() { + if (!this.renderConfig.clearCanvas) { + this.canvasContext.restore(); + return; + } + this.contextData.reset(); + }; + CanvasRendererBase.prototype.save = function(actionFlag) { + if (!this.renderConfig.clearCanvas) { + this.canvasContext.save(); + return; + } + if (actionFlag) { + this.canvasContext.save(); + } + var props = this.contextData.cTr.props; + if (this.contextData._length <= this.contextData.cArrPos) { + this.contextData.duplicate(); + } + var i; + var arr = this.contextData.saved[this.contextData.cArrPos]; + for (i = 0;i < 16; i += 1) { + arr[i] = props[i]; + } + this.contextData.savedOp[this.contextData.cArrPos] = this.contextData.cO; + this.contextData.cArrPos += 1; + }; + CanvasRendererBase.prototype.restore = function(actionFlag) { + if (!this.renderConfig.clearCanvas) { + this.canvasContext.restore(); + return; + } + if (actionFlag) { + this.canvasContext.restore(); + this.globalData.blendMode = "source-over"; + } + this.contextData.cArrPos -= 1; + var popped = this.contextData.saved[this.contextData.cArrPos]; + var i; + var arr = this.contextData.cTr.props; + for (i = 0;i < 16; i += 1) { + arr[i] = popped[i]; + } + this.canvasContext.setTransform(popped[0], popped[1], popped[4], popped[5], popped[12], popped[13]); + popped = this.contextData.savedOp[this.contextData.cArrPos]; + this.contextData.cO = popped; + if (this.globalData.currentGlobalAlpha !== popped) { + this.canvasContext.globalAlpha = popped; + this.globalData.currentGlobalAlpha = popped; + } + }; + CanvasRendererBase.prototype.configAnimation = function(animData) { + if (this.animationItem.wrapper) { + this.animationItem.container = createTag("canvas"); + var containerStyle = this.animationItem.container.style; + containerStyle.width = "100%"; + containerStyle.height = "100%"; + var origin = "0px 0px 0px"; + containerStyle.transformOrigin = origin; + containerStyle.mozTransformOrigin = origin; + containerStyle.webkitTransformOrigin = origin; + containerStyle["-webkit-transform"] = origin; + containerStyle.contentVisibility = this.renderConfig.contentVisibility; + this.animationItem.wrapper.appendChild(this.animationItem.container); + this.canvasContext = this.animationItem.container.getContext("2d"); + if (this.renderConfig.className) { + this.animationItem.container.setAttribute("class", this.renderConfig.className); + } + if (this.renderConfig.id) { + this.animationItem.container.setAttribute("id", this.renderConfig.id); + } + } else { + this.canvasContext = this.renderConfig.context; + } + this.data = animData; + this.layers = animData.layers; + this.transformCanvas = { + w: animData.w, + h: animData.h, + sx: 0, + sy: 0, + tx: 0, + ty: 0 + }; + this.setupGlobalData(animData, document.body); + this.globalData.canvasContext = this.canvasContext; + this.globalData.renderer = this; + this.globalData.isDashed = false; + this.globalData.progressiveLoad = this.renderConfig.progressiveLoad; + this.globalData.transformCanvas = this.transformCanvas; + this.elements = createSizedArray(animData.layers.length); + this.updateContainerSize(); + }; + CanvasRendererBase.prototype.updateContainerSize = function() { + this.reset(); + var elementWidth; + var elementHeight; + if (this.animationItem.wrapper && this.animationItem.container) { + elementWidth = this.animationItem.wrapper.offsetWidth; + elementHeight = this.animationItem.wrapper.offsetHeight; + this.animationItem.container.setAttribute("width", elementWidth * this.renderConfig.dpr); + this.animationItem.container.setAttribute("height", elementHeight * this.renderConfig.dpr); + } else { + elementWidth = this.canvasContext.canvas.width * this.renderConfig.dpr; + elementHeight = this.canvasContext.canvas.height * this.renderConfig.dpr; + } + var elementRel; + var animationRel; + if (this.renderConfig.preserveAspectRatio.indexOf("meet") !== -1 || this.renderConfig.preserveAspectRatio.indexOf("slice") !== -1) { + var par = this.renderConfig.preserveAspectRatio.split(" "); + var fillType = par[1] || "meet"; + var pos = par[0] || "xMidYMid"; + var xPos = pos.substr(0, 4); + var yPos = pos.substr(4); + elementRel = elementWidth / elementHeight; + animationRel = this.transformCanvas.w / this.transformCanvas.h; + if (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice") { + this.transformCanvas.sx = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr); + this.transformCanvas.sy = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr); + } else { + this.transformCanvas.sx = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr); + this.transformCanvas.sy = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr); + } + if (xPos === "xMid" && (animationRel < elementRel && fillType === "meet" || animationRel > elementRel && fillType === "slice")) { + this.transformCanvas.tx = (elementWidth - this.transformCanvas.w * (elementHeight / this.transformCanvas.h)) / 2 * this.renderConfig.dpr; + } else if (xPos === "xMax" && (animationRel < elementRel && fillType === "meet" || animationRel > elementRel && fillType === "slice")) { + this.transformCanvas.tx = (elementWidth - this.transformCanvas.w * (elementHeight / this.transformCanvas.h)) * this.renderConfig.dpr; + } else { + this.transformCanvas.tx = 0; + } + if (yPos === "YMid" && (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice")) { + this.transformCanvas.ty = (elementHeight - this.transformCanvas.h * (elementWidth / this.transformCanvas.w)) / 2 * this.renderConfig.dpr; + } else if (yPos === "YMax" && (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice")) { + this.transformCanvas.ty = (elementHeight - this.transformCanvas.h * (elementWidth / this.transformCanvas.w)) * this.renderConfig.dpr; + } else { + this.transformCanvas.ty = 0; + } + } else if (this.renderConfig.preserveAspectRatio === "none") { + this.transformCanvas.sx = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr); + this.transformCanvas.sy = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr); + this.transformCanvas.tx = 0; + this.transformCanvas.ty = 0; + } else { + this.transformCanvas.sx = this.renderConfig.dpr; + this.transformCanvas.sy = this.renderConfig.dpr; + this.transformCanvas.tx = 0; + this.transformCanvas.ty = 0; + } + this.transformCanvas.props = [this.transformCanvas.sx, 0, 0, 0, 0, this.transformCanvas.sy, 0, 0, 0, 0, 1, 0, this.transformCanvas.tx, this.transformCanvas.ty, 0, 1]; + this.ctxTransform(this.transformCanvas.props); + this.canvasContext.beginPath(); + this.canvasContext.rect(0, 0, this.transformCanvas.w, this.transformCanvas.h); + this.canvasContext.closePath(); + this.canvasContext.clip(); + this.renderFrame(this.renderedFrame, true); + }; + CanvasRendererBase.prototype.destroy = function() { + if (this.renderConfig.clearCanvas && this.animationItem.wrapper) { + this.animationItem.wrapper.innerText = ""; + } + var i; + var len = this.layers ? this.layers.length : 0; + for (i = len - 1;i >= 0; i -= 1) { + if (this.elements[i]) { + this.elements[i].destroy(); + } + } + this.elements.length = 0; + this.globalData.canvasContext = null; + this.animationItem.container = null; + this.destroyed = true; + }; + CanvasRendererBase.prototype.renderFrame = function(num, forceRender) { + if (this.renderedFrame === num && this.renderConfig.clearCanvas === true && !forceRender || this.destroyed || num === -1) { + return; + } + this.renderedFrame = num; + this.globalData.frameNum = num - this.animationItem._isFirstFrame; + this.globalData.frameId += 1; + this.globalData._mdf = !this.renderConfig.clearCanvas || forceRender; + this.globalData.projectInterface.currentFrame = num; + var i; + var len = this.layers.length; + if (!this.completeLayers) { + this.checkLayers(num); + } + for (i = 0;i < len; i += 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].prepareFrame(num - this.layers[i].st); + } + } + if (this.globalData._mdf) { + if (this.renderConfig.clearCanvas === true) { + this.canvasContext.clearRect(0, 0, this.transformCanvas.w, this.transformCanvas.h); + } else { + this.save(); + } + for (i = len - 1;i >= 0; i -= 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].renderFrame(); + } + } + if (this.renderConfig.clearCanvas !== true) { + this.restore(); + } + } + }; + CanvasRendererBase.prototype.buildItem = function(pos) { + var elements = this.elements; + if (elements[pos] || this.layers[pos].ty === 99) { + return; + } + var element = this.createItem(this.layers[pos], this, this.globalData); + elements[pos] = element; + element.initExpressions(); + }; + CanvasRendererBase.prototype.checkPendingElements = function() { + while (this.pendingElements.length) { + var element = this.pendingElements.pop(); + element.checkParenting(); + } + }; + CanvasRendererBase.prototype.hide = function() { + this.animationItem.container.style.display = "none"; + }; + CanvasRendererBase.prototype.show = function() { + this.animationItem.container.style.display = "block"; + }; + extendPrototype([CanvasRendererBase, ICompElement, CVBaseElement], CVCompElement); + CVCompElement.prototype.renderInnerContent = function() { + var ctx = this.canvasContext; + ctx.beginPath(); + ctx.moveTo(0, 0); + ctx.lineTo(this.data.w, 0); + ctx.lineTo(this.data.w, this.data.h); + ctx.lineTo(0, this.data.h); + ctx.lineTo(0, 0); + ctx.clip(); + var i; + var len = this.layers.length; + for (i = len - 1;i >= 0; i -= 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].renderFrame(); + } + } + }; + CVCompElement.prototype.destroy = function() { + var i; + var len = this.layers.length; + for (i = len - 1;i >= 0; i -= 1) { + if (this.elements[i]) { + this.elements[i].destroy(); + } + } + this.layers = null; + this.elements = null; + }; + CVCompElement.prototype.createComp = function(data2) { + return new CVCompElement(data2, this.globalData, this); + }; + extendPrototype([CanvasRendererBase], CanvasRenderer); + CanvasRenderer.prototype.createComp = function(data2) { + return new CVCompElement(data2, this.globalData, this); + }; + registerRenderer("canvas", CanvasRenderer); + ShapeModifiers.registerModifier("tm", TrimModifier); + ShapeModifiers.registerModifier("pb", PuckerAndBloatModifier); + ShapeModifiers.registerModifier("rp", RepeaterModifier); + ShapeModifiers.registerModifier("rd", RoundCornersModifier); + const Expressions = function() { + var ob2 = {}; + ob2.initExpressions = initExpressions; + function initExpressions(animation) { + var stackCount = 0; + var registers = []; + function pushExpression() { + stackCount += 1; + } + function popExpression() { + stackCount -= 1; + if (stackCount === 0) { + releaseInstances(); + } + } + function registerExpressionProperty(expression) { + if (registers.indexOf(expression) === -1) { + registers.push(expression); + } + } + function releaseInstances() { + var i; + var len = registers.length; + for (i = 0;i < len; i += 1) { + registers[i].release(); + } + registers.length = 0; + } + animation.renderer.compInterface = CompExpressionInterface(animation.renderer); + animation.renderer.globalData.projectInterface.registerComposition(animation.renderer); + animation.renderer.globalData.pushExpression = pushExpression; + animation.renderer.globalData.popExpression = popExpression; + animation.renderer.globalData.registerExpressionProperty = registerExpressionProperty; + } + return ob2; + }(); + propTypes = { + SHAPE: "shape" + }; + const ExpressionManager = function() { + var ob = {}; + var Math = BMMath; + var window = null; + var document = null; + var XMLHttpRequest = null; + var fetch = null; + var frames = null; + initialize$2(BMMath); + function $bm_isInstanceOfArray(arr) { + return arr.constructor === Array || arr.constructor === Float32Array; + } + function isNumerable(tOfV, v) { + return tOfV === "number" || tOfV === "boolean" || tOfV === "string" || v instanceof Number; + } + function $bm_neg(a) { + var tOfA = typeof a; + if (tOfA === "number" || tOfA === "boolean" || a instanceof Number) { + return -a; + } + if ($bm_isInstanceOfArray(a)) { + var i; + var lenA = a.length; + var retArr = []; + for (i = 0;i < lenA; i += 1) { + retArr[i] = -a[i]; + } + return retArr; + } + if (a.propType) { + return a.v; + } + return -a; + } + var easeInBez = BezierFactory.getBezierEasing(0.333, 0, 0.833, 0.833, "easeIn").get; + var easeOutBez = BezierFactory.getBezierEasing(0.167, 0.167, 0.667, 1, "easeOut").get; + var easeInOutBez = BezierFactory.getBezierEasing(0.33, 0, 0.667, 1, "easeInOut").get; + function sum(a, b) { + var tOfA = typeof a; + var tOfB = typeof b; + if (tOfA === "string" || tOfB === "string") { + return a + b; + } + if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { + return a + b; + } + if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { + a = a.slice(0); + a[0] += b; + return a; + } + if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { + b = b.slice(0); + b[0] = a + b[0]; + return b; + } + if ($bm_isInstanceOfArray(a) && $bm_isInstanceOfArray(b)) { + var i = 0; + var lenA = a.length; + var lenB = b.length; + var retArr = []; + while (i < lenA || i < lenB) { + if ((typeof a[i] === "number" || a[i] instanceof Number) && (typeof b[i] === "number" || b[i] instanceof Number)) { + retArr[i] = a[i] + b[i]; + } else { + retArr[i] = b[i] === undefined ? a[i] : a[i] || b[i]; + } + i += 1; + } + return retArr; + } + return 0; + } + var add = sum; + function sub(a, b) { + var tOfA = typeof a; + var tOfB = typeof b; + if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { + if (tOfA === "string") { + a = parseInt(a, 10); + } + if (tOfB === "string") { + b = parseInt(b, 10); + } + return a - b; + } + if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { + a = a.slice(0); + a[0] -= b; + return a; + } + if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { + b = b.slice(0); + b[0] = a - b[0]; + return b; + } + if ($bm_isInstanceOfArray(a) && $bm_isInstanceOfArray(b)) { + var i = 0; + var lenA = a.length; + var lenB = b.length; + var retArr = []; + while (i < lenA || i < lenB) { + if ((typeof a[i] === "number" || a[i] instanceof Number) && (typeof b[i] === "number" || b[i] instanceof Number)) { + retArr[i] = a[i] - b[i]; + } else { + retArr[i] = b[i] === undefined ? a[i] : a[i] || b[i]; + } + i += 1; + } + return retArr; + } + return 0; + } + function mul(a, b) { + var tOfA = typeof a; + var tOfB = typeof b; + var arr; + if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { + return a * b; + } + var i; + var len; + if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { + len = a.length; + arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = a[i] * b; + } + return arr; + } + if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { + len = b.length; + arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = a * b[i]; + } + return arr; + } + return 0; + } + function div(a, b) { + var tOfA = typeof a; + var tOfB = typeof b; + var arr; + if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { + return a / b; + } + var i; + var len; + if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { + len = a.length; + arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = a[i] / b; + } + return arr; + } + if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { + len = b.length; + arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = a / b[i]; + } + return arr; + } + return 0; + } + function mod(a, b) { + if (typeof a === "string") { + a = parseInt(a, 10); + } + if (typeof b === "string") { + b = parseInt(b, 10); + } + return a % b; + } + var $bm_sum = sum; + var $bm_sub = sub; + var $bm_mul = mul; + var $bm_div = div; + var $bm_mod = mod; + function clamp(num, min, max) { + if (min > max) { + var mm2 = max; + max = min; + min = mm2; + } + return Math.min(Math.max(num, min), max); + } + function radiansToDegrees(val2) { + return val2 / degToRads; + } + var radians_to_degrees = radiansToDegrees; + function degreesToRadians(val2) { + return val2 * degToRads; + } + var degrees_to_radians = radiansToDegrees; + var helperLengthArray = [0, 0, 0, 0, 0, 0]; + function length(arr1, arr2) { + if (typeof arr1 === "number" || arr1 instanceof Number) { + arr2 = arr2 || 0; + return Math.abs(arr1 - arr2); + } + if (!arr2) { + arr2 = helperLengthArray; + } + var i; + var len = Math.min(arr1.length, arr2.length); + var addedLength = 0; + for (i = 0;i < len; i += 1) { + addedLength += Math.pow(arr2[i] - arr1[i], 2); + } + return Math.sqrt(addedLength); + } + function normalize(vec) { + return div(vec, length(vec)); + } + function rgbToHsl(val2) { + var r = val2[0]; + var g3 = val2[1]; + var b = val2[2]; + var max = Math.max(r, g3, b); + var min = Math.min(r, g3, b); + var h; + var s; + var l2 = (max + min) / 2; + if (max === min) { + h = 0; + s = 0; + } else { + var d = max - min; + s = l2 > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g3 - b) / d + (g3 < b ? 6 : 0); + break; + case g3: + h = (b - r) / d + 2; + break; + case b: + h = (r - g3) / d + 4; + break; + default: + break; + } + h /= 6; + } + return [h, s, l2, val2[3]]; + } + function hue2rgb(p, q2, t4) { + if (t4 < 0) + t4 += 1; + if (t4 > 1) + t4 -= 1; + if (t4 < 1 / 6) + return p + (q2 - p) * 6 * t4; + if (t4 < 1 / 2) + return q2; + if (t4 < 2 / 3) + return p + (q2 - p) * (2 / 3 - t4) * 6; + return p; + } + function hslToRgb(val2) { + var h = val2[0]; + var s = val2[1]; + var l2 = val2[2]; + var r; + var g3; + var b; + if (s === 0) { + r = l2; + b = l2; + g3 = l2; + } else { + var q2 = l2 < 0.5 ? l2 * (1 + s) : l2 + s - l2 * s; + var p = 2 * l2 - q2; + r = hue2rgb(p, q2, h + 1 / 3); + g3 = hue2rgb(p, q2, h); + b = hue2rgb(p, q2, h - 1 / 3); + } + return [r, g3, b, val2[3]]; + } + function linear(t4, tMin, tMax, value1, value2) { + if (value1 === undefined || value2 === undefined) { + value1 = tMin; + value2 = tMax; + tMin = 0; + tMax = 1; + } + if (tMax < tMin) { + var _tMin = tMax; + tMax = tMin; + tMin = _tMin; + } + if (t4 <= tMin) { + return value1; + } + if (t4 >= tMax) { + return value2; + } + var perc = tMax === tMin ? 0 : (t4 - tMin) / (tMax - tMin); + if (!value1.length) { + return value1 + (value2 - value1) * perc; + } + var i; + var len = value1.length; + var arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = value1[i] + (value2[i] - value1[i]) * perc; + } + return arr; + } + function random(min, max) { + if (max === undefined) { + if (min === undefined) { + min = 0; + max = 1; + } else { + max = min; + min = undefined; + } + } + if (max.length) { + var i; + var len = max.length; + if (!min) { + min = createTypedArray("float32", len); + } + var arr = createTypedArray("float32", len); + var rnd = BMMath.random(); + for (i = 0;i < len; i += 1) { + arr[i] = min[i] + rnd * (max[i] - min[i]); + } + return arr; + } + if (min === undefined) { + min = 0; + } + var rndm = BMMath.random(); + return min + rndm * (max - min); + } + function createPath(points, inTangents, outTangents, closed) { + var i; + var len = points.length; + var path = shapePool.newElement(); + path.setPathData(!!closed, len); + var arrPlaceholder = [0, 0]; + var inVertexPoint; + var outVertexPoint; + for (i = 0;i < len; i += 1) { + inVertexPoint = inTangents && inTangents[i] ? inTangents[i] : arrPlaceholder; + outVertexPoint = outTangents && outTangents[i] ? outTangents[i] : arrPlaceholder; + path.setTripleAt(points[i][0], points[i][1], outVertexPoint[0] + points[i][0], outVertexPoint[1] + points[i][1], inVertexPoint[0] + points[i][0], inVertexPoint[1] + points[i][1], i, true); + } + return path; + } + function initiateExpression(elem, data, property) { + var val = data.x; + var needsVelocity = /velocity(?![\w\d])/.test(val); + var _needsRandom = val.indexOf("random") !== -1; + var elemType = elem.data.ty; + var transform; + var $bm_transform; + var content; + var effect; + var thisProperty = property; + thisProperty.valueAtTime = thisProperty.getValueAtTime; + Object.defineProperty(thisProperty, "value", { + get: function() { + return thisProperty.v; + } + }); + elem.comp.frameDuration = 1 / elem.comp.globalData.frameRate; + elem.comp.displayStartTime = 0; + var inPoint = elem.data.ip / elem.comp.globalData.frameRate; + var outPoint = elem.data.op / elem.comp.globalData.frameRate; + var width = elem.data.sw ? elem.data.sw : 0; + var height = elem.data.sh ? elem.data.sh : 0; + var name = elem.data.nm; + var loopIn; + var loop_in; + var loopOut; + var loop_out; + var smooth; + var toWorld; + var fromWorld; + var fromComp; + var toComp; + var fromCompToSurface; + var position; + var rotation; + var anchorPoint; + var scale; + var thisLayer; + var thisComp; + var mask; + var valueAtTime; + var velocityAtTime; + var scoped_bm_rt; + var expression_function = eval("[function _expression_function(){" + val + ";scoped_bm_rt=$bm_rt}]")[0]; + var numKeys = property.kf ? data.k.length : 0; + var active = !this.data || this.data.hd !== true; + var wiggle = function wiggle(freq, amp) { + var iWiggle; + var j2; + var lenWiggle = this.pv.length ? this.pv.length : 1; + var addedAmps = createTypedArray("float32", lenWiggle); + freq = 5; + var iterations = Math.floor(time * freq); + iWiggle = 0; + j2 = 0; + while (iWiggle < iterations) { + for (j2 = 0;j2 < lenWiggle; j2 += 1) { + addedAmps[j2] += -amp + amp * 2 * BMMath.random(); + } + iWiggle += 1; + } + var periods = time * freq; + var perc = periods - Math.floor(periods); + var arr = createTypedArray("float32", lenWiggle); + if (lenWiggle > 1) { + for (j2 = 0;j2 < lenWiggle; j2 += 1) { + arr[j2] = this.pv[j2] + addedAmps[j2] + (-amp + amp * 2 * BMMath.random()) * perc; + } + return arr; + } + return this.pv + addedAmps[0] + (-amp + amp * 2 * BMMath.random()) * perc; + }.bind(this); + if (thisProperty.loopIn) { + loopIn = thisProperty.loopIn.bind(thisProperty); + loop_in = loopIn; + } + if (thisProperty.loopOut) { + loopOut = thisProperty.loopOut.bind(thisProperty); + loop_out = loopOut; + } + if (thisProperty.smooth) { + smooth = thisProperty.smooth.bind(thisProperty); + } + function loopInDuration(type, duration) { + return loopIn(type, duration, true); + } + function loopOutDuration(type, duration) { + return loopOut(type, duration, true); + } + if (this.getValueAtTime) { + valueAtTime = this.getValueAtTime.bind(this); + } + if (this.getVelocityAtTime) { + velocityAtTime = this.getVelocityAtTime.bind(this); + } + var comp = elem.comp.globalData.projectInterface.bind(elem.comp.globalData.projectInterface); + function lookAt(elem1, elem2) { + var fVec = [elem2[0] - elem1[0], elem2[1] - elem1[1], elem2[2] - elem1[2]]; + var pitch = Math.atan2(fVec[0], Math.sqrt(fVec[1] * fVec[1] + fVec[2] * fVec[2])) / degToRads; + var yaw = -Math.atan2(fVec[1], fVec[2]) / degToRads; + return [yaw, pitch, 0]; + } + function easeOut(t4, tMin, tMax, val1, val2) { + return applyEase(easeOutBez, t4, tMin, tMax, val1, val2); + } + function easeIn(t4, tMin, tMax, val1, val2) { + return applyEase(easeInBez, t4, tMin, tMax, val1, val2); + } + function ease(t4, tMin, tMax, val1, val2) { + return applyEase(easeInOutBez, t4, tMin, tMax, val1, val2); + } + function applyEase(fn, t4, tMin, tMax, val1, val2) { + if (val1 === undefined) { + val1 = tMin; + val2 = tMax; + } else { + t4 = (t4 - tMin) / (tMax - tMin); + } + if (t4 > 1) { + t4 = 1; + } else if (t4 < 0) { + t4 = 0; + } + var mult = fn(t4); + if ($bm_isInstanceOfArray(val1)) { + var iKey; + var lenKey = val1.length; + var arr = createTypedArray("float32", lenKey); + for (iKey = 0;iKey < lenKey; iKey += 1) { + arr[iKey] = (val2[iKey] - val1[iKey]) * mult + val1[iKey]; + } + return arr; + } + return (val2 - val1) * mult + val1; + } + function nearestKey(time2) { + var iKey; + var lenKey = data.k.length; + var index2; + var keyTime; + if (!data.k.length || typeof data.k[0] === "number") { + index2 = 0; + keyTime = 0; + } else { + index2 = -1; + time2 *= elem.comp.globalData.frameRate; + if (time2 < data.k[0].t) { + index2 = 1; + keyTime = data.k[0].t; + } else { + for (iKey = 0;iKey < lenKey - 1; iKey += 1) { + if (time2 === data.k[iKey].t) { + index2 = iKey + 1; + keyTime = data.k[iKey].t; + break; + } else if (time2 > data.k[iKey].t && time2 < data.k[iKey + 1].t) { + if (time2 - data.k[iKey].t > data.k[iKey + 1].t - time2) { + index2 = iKey + 2; + keyTime = data.k[iKey + 1].t; + } else { + index2 = iKey + 1; + keyTime = data.k[iKey].t; + } + break; + } + } + if (index2 === -1) { + index2 = iKey + 1; + keyTime = data.k[iKey].t; + } + } + } + var obKey = {}; + obKey.index = index2; + obKey.time = keyTime / elem.comp.globalData.frameRate; + return obKey; + } + function key(ind) { + var obKey; + var iKey; + var lenKey; + if (!data.k.length || typeof data.k[0] === "number") { + throw new Error("The property has no keyframe at index " + ind); + } + ind -= 1; + obKey = { + time: data.k[ind].t / elem.comp.globalData.frameRate, + value: [] + }; + var arr = Object.prototype.hasOwnProperty.call(data.k[ind], "s") ? data.k[ind].s : data.k[ind - 1].e; + lenKey = arr.length; + for (iKey = 0;iKey < lenKey; iKey += 1) { + obKey[iKey] = arr[iKey]; + obKey.value[iKey] = arr[iKey]; + } + return obKey; + } + function framesToTime(fr, fps) { + if (!fps) { + fps = elem.comp.globalData.frameRate; + } + return fr / fps; + } + function timeToFrames(t4, fps) { + if (!t4 && t4 !== 0) { + t4 = time; + } + if (!fps) { + fps = elem.comp.globalData.frameRate; + } + return t4 * fps; + } + function seedRandom(seed) { + BMMath.seedrandom(randSeed + seed); + } + function sourceRectAtTime() { + return elem.sourceRectAtTime(); + } + function substring(init, end) { + if (typeof value === "string") { + if (end === undefined) { + return value.substring(init); + } + return value.substring(init, end); + } + return ""; + } + function substr(init, end) { + if (typeof value === "string") { + if (end === undefined) { + return value.substr(init); + } + return value.substr(init, end); + } + return ""; + } + function posterizeTime(framesPerSecond) { + time = framesPerSecond === 0 ? 0 : Math.floor(time * framesPerSecond) / framesPerSecond; + value = valueAtTime(time); + } + var time; + var velocity; + var value; + var text; + var textIndex; + var textTotal; + var selectorValue; + var index = elem.data.ind; + var hasParent = !!(elem.hierarchy && elem.hierarchy.length); + var parent; + var randSeed = Math.floor(Math.random() * 1e6); + var globalData = elem.globalData; + function executeExpression(_value) { + value = _value; + if (this.frameExpressionId === elem.globalData.frameId && this.propType !== "textSelector") { + return value; + } + if (this.propType === "textSelector") { + textIndex = this.textIndex; + textTotal = this.textTotal; + selectorValue = this.selectorValue; + } + if (!thisLayer) { + text = elem.layerInterface.text; + thisLayer = elem.layerInterface; + thisComp = elem.comp.compInterface; + toWorld = thisLayer.toWorld.bind(thisLayer); + fromWorld = thisLayer.fromWorld.bind(thisLayer); + fromComp = thisLayer.fromComp.bind(thisLayer); + toComp = thisLayer.toComp.bind(thisLayer); + mask = thisLayer.mask ? thisLayer.mask.bind(thisLayer) : null; + fromCompToSurface = fromComp; + } + if (!transform) { + transform = elem.layerInterface("ADBE Transform Group"); + $bm_transform = transform; + if (transform) { + anchorPoint = transform.anchorPoint; + } + } + if (elemType === 4 && !content) { + content = thisLayer("ADBE Root Vectors Group"); + } + if (!effect) { + effect = thisLayer(4); + } + hasParent = !!(elem.hierarchy && elem.hierarchy.length); + if (hasParent && !parent) { + parent = elem.hierarchy[0].layerInterface; + } + time = this.comp.renderedFrame / this.comp.globalData.frameRate; + if (_needsRandom) { + seedRandom(randSeed + time); + } + if (needsVelocity) { + velocity = velocityAtTime(time); + } + expression_function(); + this.frameExpressionId = elem.globalData.frameId; + scoped_bm_rt = scoped_bm_rt.propType === propTypes.SHAPE ? scoped_bm_rt.v : scoped_bm_rt; + return scoped_bm_rt; + } + executeExpression.__preventDeadCodeRemoval = [$bm_transform, anchorPoint, time, velocity, inPoint, outPoint, width, height, name, loop_in, loop_out, smooth, toComp, fromCompToSurface, toWorld, fromWorld, mask, position, rotation, scale, thisComp, numKeys, active, wiggle, loopInDuration, loopOutDuration, comp, lookAt, easeOut, easeIn, ease, nearestKey, key, text, textIndex, textTotal, selectorValue, framesToTime, timeToFrames, sourceRectAtTime, substring, substr, posterizeTime, index, globalData]; + return executeExpression; + } + ob.initiateExpression = initiateExpression; + ob.__preventDeadCodeRemoval = [window, document, XMLHttpRequest, fetch, frames, $bm_neg, add, $bm_sum, $bm_sub, $bm_mul, $bm_div, $bm_mod, clamp, radians_to_degrees, degreesToRadians, degrees_to_radians, normalize, rgbToHsl, hslToRgb, linear, random, createPath]; + return ob; + }(); + const expressionHelpers = function() { + function searchExpressions(elem2, data2, prop) { + if (data2.x) { + prop.k = true; + prop.x = true; + prop.initiateExpression = ExpressionManager.initiateExpression; + prop.effectsSequence.push(prop.initiateExpression(elem2, data2, prop).bind(prop)); + } + } + function getValueAtTime(frameNum) { + frameNum *= this.elem.globalData.frameRate; + frameNum -= this.offsetTime; + if (frameNum !== this._cachingAtTime.lastFrame) { + this._cachingAtTime.lastIndex = this._cachingAtTime.lastFrame < frameNum ? this._cachingAtTime.lastIndex : 0; + this._cachingAtTime.value = this.interpolateValue(frameNum, this._cachingAtTime); + this._cachingAtTime.lastFrame = frameNum; + } + return this._cachingAtTime.value; + } + function getSpeedAtTime(frameNum) { + var delta = -0.01; + var v1 = this.getValueAtTime(frameNum); + var v2 = this.getValueAtTime(frameNum + delta); + var speed = 0; + if (v1.length) { + var i; + for (i = 0;i < v1.length; i += 1) { + speed += Math.pow(v2[i] - v1[i], 2); + } + speed = Math.sqrt(speed) * 100; + } else { + speed = 0; + } + return speed; + } + function getVelocityAtTime(frameNum) { + if (this.vel !== undefined) { + return this.vel; + } + var delta = -0.001; + var v1 = this.getValueAtTime(frameNum); + var v2 = this.getValueAtTime(frameNum + delta); + var velocity2; + if (v1.length) { + velocity2 = createTypedArray("float32", v1.length); + var i; + for (i = 0;i < v1.length; i += 1) { + velocity2[i] = (v2[i] - v1[i]) / delta; + } + } else { + velocity2 = (v2 - v1) / delta; + } + return velocity2; + } + function getStaticValueAtTime() { + return this.pv; + } + function setGroupProperty(propertyGroup) { + this.propertyGroup = propertyGroup; + } + return { + searchExpressions, + getSpeedAtTime, + getVelocityAtTime, + getValueAtTime, + getStaticValueAtTime, + setGroupProperty + }; + }(); + setExpressionsPlugin(Expressions); + initialize$1(); + initialize(); +} +var standalone; +var animationData; +var renderer; +var queryString; +var scripts; +var index2; +var myScript; +var readyStateCheckInterval; +var registeredEffects; +var idPrefix; +var emptyShapeData; +var propTypes; +// node_modules/three/examples/jsm/loaders/OBJLoader.js +var _vA2 = new Vector3; +var _vB2 = new Vector3; +var _vC2 = new Vector3; +var _ab = new Vector3; +var _cb = new Vector3; +var _color3 = new Color; +// node_modules/three/examples/jsm/loaders/PLYLoader.js +var _color5 = new Color; +// node_modules/three/examples/jsm/loaders/UltraHDRLoader.js +var SRGB_TO_LINEAR = Array(1024).fill(0).map((_9, value2) => Math.pow(value2 / 255 * 0.9478672986 + 0.0521327014, 2.4)); +// node_modules/three/examples/jsm/loaders/RGBMLoader.js +var UPNG = {}; +UPNG.toRGBA8 = function(out) { + var { width: w, height: h } = out; + if (out.tabs.acTL == null) + return [UPNG.toRGBA8.decodeImage(out.data, w, h, out).buffer]; + var frms = []; + if (out.frames[0].data == null) + out.frames[0].data = out.data; + var len = w * h * 4, img = new Uint8Array(len), empty = new Uint8Array(len), prev = new Uint8Array(len); + for (var i = 0;i < out.frames.length; i++) { + var frm = out.frames[i]; + var fx = frm.rect.x, fy = frm.rect.y, fw = frm.rect.width, fh = frm.rect.height; + var fdata = UPNG.toRGBA8.decodeImage(frm.data, fw, fh, out); + if (i != 0) + for (var j2 = 0;j2 < len; j2++) + prev[j2] = img[j2]; + if (frm.blend == 0) + UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 0); + else if (frm.blend == 1) + UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 1); + frms.push(img.buffer.slice(0)); + if (frm.dispose == 1) + UPNG._copyTile(empty, fw, fh, img, w, h, fx, fy, 0); + else if (frm.dispose == 2) + for (var j2 = 0;j2 < len; j2++) + img[j2] = prev[j2]; + } + return frms; +}; +UPNG.toRGBA8.decodeImage = function(data2, w, h, out) { + var area2 = w * h, bpp = UPNG.decode._getBPP(out); + var bpl = Math.ceil(w * bpp / 8); + var bf2 = new Uint8Array(area2 * 4), bf32 = new Uint32Array(bf2.buffer); + var { ctype, depth } = out; + var rs = UPNG._bin.readUshort; + if (ctype == 6) { + var qarea = area2 << 2; + if (depth == 8) + for (var i = 0;i < qarea; i += 4) { + bf2[i] = data2[i]; + bf2[i + 1] = data2[i + 1]; + bf2[i + 2] = data2[i + 2]; + bf2[i + 3] = data2[i + 3]; + } + if (depth == 16) + for (var i = 0;i < qarea; i++) { + bf2[i] = data2[i << 1]; + } + } else if (ctype == 2) { + var ts = out.tabs["tRNS"]; + if (ts == null) { + if (depth == 8) + for (var i = 0;i < area2; i++) { + var ti = i * 3; + bf32[i] = 255 << 24 | data2[ti + 2] << 16 | data2[ti + 1] << 8 | data2[ti]; + } + if (depth == 16) + for (var i = 0;i < area2; i++) { + var ti = i * 6; + bf32[i] = 255 << 24 | data2[ti + 4] << 16 | data2[ti + 2] << 8 | data2[ti]; + } + } else { + var tr = ts[0], tg = ts[1], tb = ts[2]; + if (depth == 8) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 3; + bf32[i] = 255 << 24 | data2[ti + 2] << 16 | data2[ti + 1] << 8 | data2[ti]; + if (data2[ti] == tr && data2[ti + 1] == tg && data2[ti + 2] == tb) + bf2[qi + 3] = 0; + } + if (depth == 16) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 6; + bf32[i] = 255 << 24 | data2[ti + 4] << 16 | data2[ti + 2] << 8 | data2[ti]; + if (rs(data2, ti) == tr && rs(data2, ti + 2) == tg && rs(data2, ti + 4) == tb) + bf2[qi + 3] = 0; + } + } + } else if (ctype == 3) { + var p = out.tabs["PLTE"], ap2 = out.tabs["tRNS"], tl2 = ap2 ? ap2.length : 0; + if (depth == 1) + for (var y3 = 0;y3 < h; y3++) { + var s0 = y3 * bpl, t02 = y3 * w; + for (var i = 0;i < w; i++) { + var qi = t02 + i << 2, j2 = data2[s0 + (i >> 3)] >> 7 - ((i & 7) << 0) & 1, cj = 3 * j2; + bf2[qi] = p[cj]; + bf2[qi + 1] = p[cj + 1]; + bf2[qi + 2] = p[cj + 2]; + bf2[qi + 3] = j2 < tl2 ? ap2[j2] : 255; + } + } + if (depth == 2) + for (var y3 = 0;y3 < h; y3++) { + var s0 = y3 * bpl, t02 = y3 * w; + for (var i = 0;i < w; i++) { + var qi = t02 + i << 2, j2 = data2[s0 + (i >> 2)] >> 6 - ((i & 3) << 1) & 3, cj = 3 * j2; + bf2[qi] = p[cj]; + bf2[qi + 1] = p[cj + 1]; + bf2[qi + 2] = p[cj + 2]; + bf2[qi + 3] = j2 < tl2 ? ap2[j2] : 255; + } + } + if (depth == 4) + for (var y3 = 0;y3 < h; y3++) { + var s0 = y3 * bpl, t02 = y3 * w; + for (var i = 0;i < w; i++) { + var qi = t02 + i << 2, j2 = data2[s0 + (i >> 1)] >> 4 - ((i & 1) << 2) & 15, cj = 3 * j2; + bf2[qi] = p[cj]; + bf2[qi + 1] = p[cj + 1]; + bf2[qi + 2] = p[cj + 2]; + bf2[qi + 3] = j2 < tl2 ? ap2[j2] : 255; + } + } + if (depth == 8) + for (var i = 0;i < area2; i++) { + var qi = i << 2, j2 = data2[i], cj = 3 * j2; + bf2[qi] = p[cj]; + bf2[qi + 1] = p[cj + 1]; + bf2[qi + 2] = p[cj + 2]; + bf2[qi + 3] = j2 < tl2 ? ap2[j2] : 255; + } + } else if (ctype == 4) { + if (depth == 8) + for (var i = 0;i < area2; i++) { + var qi = i << 2, di2 = i << 1, gr = data2[di2]; + bf2[qi] = gr; + bf2[qi + 1] = gr; + bf2[qi + 2] = gr; + bf2[qi + 3] = data2[di2 + 1]; + } + if (depth == 16) + for (var i = 0;i < area2; i++) { + var qi = i << 2, di2 = i << 2, gr = data2[di2]; + bf2[qi] = gr; + bf2[qi + 1] = gr; + bf2[qi + 2] = gr; + bf2[qi + 3] = data2[di2 + 2]; + } + } else if (ctype == 0) { + var tr = out.tabs["tRNS"] ? out.tabs["tRNS"] : -1; + for (var y3 = 0;y3 < h; y3++) { + var off = y3 * bpl, to = y3 * w; + if (depth == 1) + for (var x2 = 0;x2 < w; x2++) { + var gr = 255 * (data2[off + (x2 >>> 3)] >>> 7 - (x2 & 7) & 1), al2 = gr == tr * 255 ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + else if (depth == 2) + for (var x2 = 0;x2 < w; x2++) { + var gr = 85 * (data2[off + (x2 >>> 2)] >>> 6 - ((x2 & 3) << 1) & 3), al2 = gr == tr * 85 ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + else if (depth == 4) + for (var x2 = 0;x2 < w; x2++) { + var gr = 17 * (data2[off + (x2 >>> 1)] >>> 4 - ((x2 & 1) << 2) & 15), al2 = gr == tr * 17 ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + else if (depth == 8) + for (var x2 = 0;x2 < w; x2++) { + var gr = data2[off + x2], al2 = gr == tr ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + else if (depth == 16) + for (var x2 = 0;x2 < w; x2++) { + var gr = data2[off + (x2 << 1)], al2 = rs(data2, off + (x2 << 1)) == tr ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + } + } + return bf2; +}; +UPNG.decode = function(buff) { + var data2 = new Uint8Array(buff), offset = 8, bin = UPNG._bin, rUs = bin.readUshort, rUi = bin.readUint; + var out = { tabs: {}, frames: [] }; + var dd2 = new Uint8Array(data2.length), doff = 0; + var fd2, foff = 0; + var text2, keyw, bfr; + var mgck = [137, 80, 78, 71, 13, 10, 26, 10]; + for (var i = 0;i < 8; i++) + if (data2[i] != mgck[i]) + throw new Error("The input is not a PNG file!"); + while (offset < data2.length) { + var len = bin.readUint(data2, offset); + offset += 4; + var type = bin.readASCII(data2, offset, 4); + offset += 4; + if (type == "IHDR") { + UPNG.decode._IHDR(data2, offset, out); + } else if (type == "CgBI") { + out.tabs[type] = data2.slice(offset, offset + 4); + } else if (type == "IDAT") { + for (var i = 0;i < len; i++) + dd2[doff + i] = data2[offset + i]; + doff += len; + } else if (type == "acTL") { + out.tabs[type] = { num_frames: rUi(data2, offset), num_plays: rUi(data2, offset + 4) }; + fd2 = new Uint8Array(data2.length); + } else if (type == "fcTL") { + if (foff != 0) { + var fr = out.frames[out.frames.length - 1]; + fr.data = UPNG.decode._decompress(out, fd2.slice(0, foff), fr.rect.width, fr.rect.height); + foff = 0; + } + var rct = { x: rUi(data2, offset + 12), y: rUi(data2, offset + 16), width: rUi(data2, offset + 4), height: rUi(data2, offset + 8) }; + var del = rUs(data2, offset + 22); + del = rUs(data2, offset + 20) / (del == 0 ? 100 : del); + var frm = { rect: rct, delay: Math.round(del * 1000), dispose: data2[offset + 24], blend: data2[offset + 25] }; + out.frames.push(frm); + } else if (type == "fdAT") { + for (var i = 0;i < len - 4; i++) + fd2[foff + i] = data2[offset + i + 4]; + foff += len - 4; + } else if (type == "pHYs") { + out.tabs[type] = [bin.readUint(data2, offset), bin.readUint(data2, offset + 4), data2[offset + 8]]; + } else if (type == "cHRM") { + out.tabs[type] = []; + for (var i = 0;i < 8; i++) + out.tabs[type].push(bin.readUint(data2, offset + i * 4)); + } else if (type == "tEXt" || type == "zTXt") { + if (out.tabs[type] == null) + out.tabs[type] = {}; + var nz = bin.nextZero(data2, offset); + keyw = bin.readASCII(data2, offset, nz - offset); + var tl2 = offset + len - nz - 1; + if (type == "tEXt") + text2 = bin.readASCII(data2, nz + 1, tl2); + else { + bfr = UPNG.decode._inflate(data2.slice(nz + 2, nz + 2 + tl2)); + text2 = bin.readUTF8(bfr, 0, bfr.length); + } + out.tabs[type][keyw] = text2; + } else if (type == "iTXt") { + if (out.tabs[type] == null) + out.tabs[type] = {}; + var nz = 0, off = offset; + nz = bin.nextZero(data2, off); + keyw = bin.readASCII(data2, off, nz - off); + off = nz + 1; + var cflag = data2[off]; + off += 2; + nz = bin.nextZero(data2, off); + bin.readASCII(data2, off, nz - off); + off = nz + 1; + nz = bin.nextZero(data2, off); + bin.readUTF8(data2, off, nz - off); + off = nz + 1; + var tl2 = len - (off - offset); + if (cflag == 0) + text2 = bin.readUTF8(data2, off, tl2); + else { + bfr = UPNG.decode._inflate(data2.slice(off, off + tl2)); + text2 = bin.readUTF8(bfr, 0, bfr.length); + } + out.tabs[type][keyw] = text2; + } else if (type == "PLTE") { + out.tabs[type] = bin.readBytes(data2, offset, len); + } else if (type == "hIST") { + var pl2 = out.tabs["PLTE"].length / 3; + out.tabs[type] = []; + for (var i = 0;i < pl2; i++) + out.tabs[type].push(rUs(data2, offset + i * 2)); + } else if (type == "tRNS") { + if (out.ctype == 3) + out.tabs[type] = bin.readBytes(data2, offset, len); + else if (out.ctype == 0) + out.tabs[type] = rUs(data2, offset); + else if (out.ctype == 2) + out.tabs[type] = [rUs(data2, offset), rUs(data2, offset + 2), rUs(data2, offset + 4)]; + } else if (type == "gAMA") + out.tabs[type] = bin.readUint(data2, offset) / 1e5; + else if (type == "sRGB") + out.tabs[type] = data2[offset]; + else if (type == "bKGD") { + if (out.ctype == 0 || out.ctype == 4) + out.tabs[type] = [rUs(data2, offset)]; + else if (out.ctype == 2 || out.ctype == 6) + out.tabs[type] = [rUs(data2, offset), rUs(data2, offset + 2), rUs(data2, offset + 4)]; + else if (out.ctype == 3) + out.tabs[type] = data2[offset]; + } else if (type == "IEND") { + break; + } + offset += len; + bin.readUint(data2, offset); + offset += 4; + } + if (foff != 0) { + var fr = out.frames[out.frames.length - 1]; + fr.data = UPNG.decode._decompress(out, fd2.slice(0, foff), fr.rect.width, fr.rect.height); + } + out.data = UPNG.decode._decompress(out, dd2, out.width, out.height); + delete out.compress; + delete out.interlace; + delete out.filter; + return out; +}; +UPNG.decode._decompress = function(out, dd2, w, h) { + var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w * bpp / 8), buff = new Uint8Array((bpl + 1 + out.interlace) * h); + if (out.tabs["CgBI"]) + dd2 = UPNG.inflateRaw(dd2, buff); + else + dd2 = UPNG.decode._inflate(dd2, buff); + if (out.interlace == 0) + dd2 = UPNG.decode._filterZero(dd2, out, 0, w, h); + else if (out.interlace == 1) + dd2 = UPNG.decode._readInterlace(dd2, out); + return dd2; +}; +UPNG.decode._inflate = function(data2, buff) { + var out = UPNG["inflateRaw"](new Uint8Array(data2.buffer, 2, data2.length - 6), buff); + return out; +}; +UPNG.inflateRaw = function() { + var H = {}; + H.H = {}; + H.H.N = function(N, W) { + var R2 = Uint8Array, i = 0, m = 0, J2 = 0, h = 0, Q3 = 0, X = 0, u3 = 0, w = 0, d = 0, v, C5; + if (N[0] == 3 && N[1] == 0) + return W ? W : new R2(0); + var V3 = H.H, n2 = V3.b, A4 = V3.e, l2 = V3.R, M = V3.n, I3 = V3.A, e = V3.Z, b = V3.m, Z3 = W == null; + if (Z3) + W = new R2(N.length >>> 2 << 5); + while (i == 0) { + i = n2(N, d, 1); + m = n2(N, d + 1, 2); + d += 3; + if (m == 0) { + if ((d & 7) != 0) + d += 8 - (d & 7); + var D = (d >>> 3) + 4, q2 = N[D - 4] | N[D - 3] << 8; + if (Z3) + W = H.H.W(W, w + q2); + W.set(new R2(N.buffer, N.byteOffset + D, q2), w); + d = D + q2 << 3; + w += q2; + continue; + } + if (Z3) + W = H.H.W(W, w + (1 << 17)); + if (m == 1) { + v = b.J; + C5 = b.h; + X = (1 << 9) - 1; + u3 = (1 << 5) - 1; + } + if (m == 2) { + J2 = A4(N, d, 5) + 257; + h = A4(N, d + 5, 5) + 1; + Q3 = A4(N, d + 10, 4) + 4; + d += 14; + var j2 = 1; + for (var c = 0;c < 38; c += 2) { + b.Q[c] = 0; + b.Q[c + 1] = 0; + } + for (var c = 0;c < Q3; c++) { + var K = A4(N, d + c * 3, 3); + b.Q[(b.X[c] << 1) + 1] = K; + if (K > j2) + j2 = K; + } + d += 3 * Q3; + M(b.Q, j2); + I3(b.Q, j2, b.u); + v = b.w; + C5 = b.d; + d = l2(b.u, (1 << j2) - 1, J2 + h, N, d, b.v); + var r = V3.V(b.v, 0, J2, b.C); + X = (1 << r) - 1; + var S = V3.V(b.v, J2, h, b.D); + u3 = (1 << S) - 1; + M(b.C, r); + I3(b.C, r, v); + M(b.D, S); + I3(b.D, S, C5); + } + while (true) { + var T3 = v[e(N, d) & X]; + d += T3 & 15; + var p = T3 >>> 4; + if (p >>> 8 == 0) { + W[w++] = p; + } else if (p == 256) { + break; + } else { + var z2 = w + p - 254; + if (p > 264) { + var _9 = b.q[p - 257]; + z2 = w + (_9 >>> 3) + A4(N, d, _9 & 7); + d += _9 & 7; + } + var $2 = C5[e(N, d) & u3]; + d += $2 & 15; + var s = $2 >>> 4, Y = b.c[s], a = (Y >>> 4) + n2(N, d, Y & 15); + d += Y & 15; + while (w < z2) { + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + } + w = z2; + } + } + } + return W.length == w ? W : W.slice(0, w); + }; + H.H.W = function(N, W) { + var R2 = N.length; + if (W <= R2) + return N; + var V3 = new Uint8Array(R2 << 1); + V3.set(N, 0); + return V3; + }; + H.H.R = function(N, W, R2, V3, n2, A4) { + var l2 = H.H.e, M = H.H.Z, I3 = 0; + while (I3 < R2) { + var e = N[M(V3, n2) & W]; + n2 += e & 15; + var b = e >>> 4; + if (b <= 15) { + A4[I3] = b; + I3++; + } else { + var Z3 = 0, m = 0; + if (b == 16) { + m = 3 + l2(V3, n2, 2); + n2 += 2; + Z3 = A4[I3 - 1]; + } else if (b == 17) { + m = 3 + l2(V3, n2, 3); + n2 += 3; + } else if (b == 18) { + m = 11 + l2(V3, n2, 7); + n2 += 7; + } + var J2 = I3 + m; + while (I3 < J2) { + A4[I3] = Z3; + I3++; + } + } + } + return n2; + }; + H.H.V = function(N, W, R2, V3) { + var n2 = 0, A4 = 0, l2 = V3.length >>> 1; + while (A4 < R2) { + var M = N[A4 + W]; + V3[A4 << 1] = 0; + V3[(A4 << 1) + 1] = M; + if (M > n2) + n2 = M; + A4++; + } + while (A4 < l2) { + V3[A4 << 1] = 0; + V3[(A4 << 1) + 1] = 0; + A4++; + } + return n2; + }; + H.H.n = function(N, W) { + var R2 = H.H.m, V3 = N.length, n2, A4, l2, M, I3, e = R2.j; + for (var M = 0;M <= W; M++) + e[M] = 0; + for (M = 1;M < V3; M += 2) + e[N[M]]++; + var b = R2.K; + n2 = 0; + e[0] = 0; + for (A4 = 1;A4 <= W; A4++) { + n2 = n2 + e[A4 - 1] << 1; + b[A4] = n2; + } + for (l2 = 0;l2 < V3; l2 += 2) { + I3 = N[l2 + 1]; + if (I3 != 0) { + N[l2] = b[I3]; + b[I3]++; + } + } + }; + H.H.A = function(N, W, R2) { + var V3 = N.length, n2 = H.H.m, A4 = n2.r; + for (var l2 = 0;l2 < V3; l2 += 2) + if (N[l2 + 1] != 0) { + var M = l2 >> 1, I3 = N[l2 + 1], e = M << 4 | I3, b = W - I3, Z3 = N[l2] << b, m = Z3 + (1 << b); + while (Z3 != m) { + var J2 = A4[Z3] >>> 15 - W; + R2[J2] = e; + Z3++; + } + } + }; + H.H.l = function(N, W) { + var R2 = H.H.m.r, V3 = 15 - W; + for (var n2 = 0;n2 < N.length; n2 += 2) { + var A4 = N[n2] << W - N[n2 + 1]; + N[n2] = R2[A4] >>> V3; + } + }; + H.H.M = function(N, W, R2) { + R2 = R2 << (W & 7); + var V3 = W >>> 3; + N[V3] |= R2; + N[V3 + 1] |= R2 >>> 8; + }; + H.H.I = function(N, W, R2) { + R2 = R2 << (W & 7); + var V3 = W >>> 3; + N[V3] |= R2; + N[V3 + 1] |= R2 >>> 8; + N[V3 + 2] |= R2 >>> 16; + }; + H.H.e = function(N, W, R2) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8) >>> (W & 7) & (1 << R2) - 1; + }; + H.H.b = function(N, W, R2) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7) & (1 << R2) - 1; + }; + H.H.Z = function(N, W) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7); + }; + H.H.i = function(N, W) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16 | N[(W >>> 3) + 3] << 24) >>> (W & 7); + }; + H.H.m = function() { + var N = Uint16Array, W = Uint32Array; + return { K: new N(16), j: new N(16), X: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], S: [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, 999, 999, 999], T: [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, 0, 0, 0], q: new N(32), 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, 65535, 65535], z: [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, 0, 0], c: new W(32), J: new N(512), _: [], h: new N(32), $: [], w: new N(32768), C: [], v: [], d: new N(32768), D: [], u: new N(512), Q: [], r: new N(1 << 15), s: new W(286), Y: new W(30), a: new W(19), t: new W(15000), k: new N(1 << 16), g: new N(1 << 15) }; + }(); + (function() { + var N = H.H.m, W = 1 << 15; + for (var R2 = 0;R2 < W; R2++) { + var V3 = R2; + V3 = (V3 & 2863311530) >>> 1 | (V3 & 1431655765) << 1; + V3 = (V3 & 3435973836) >>> 2 | (V3 & 858993459) << 2; + V3 = (V3 & 4042322160) >>> 4 | (V3 & 252645135) << 4; + V3 = (V3 & 4278255360) >>> 8 | (V3 & 16711935) << 8; + N.r[R2] = (V3 >>> 16 | V3 << 16) >>> 17; + } + function n2(A4, l2, M) { + while (l2-- != 0) + A4.push(0, M); + } + for (var R2 = 0;R2 < 32; R2++) { + N.q[R2] = N.S[R2] << 3 | N.T[R2]; + N.c[R2] = N.p[R2] << 4 | N.z[R2]; + } + n2(N._, 144, 8); + n2(N._, 255 - 143, 9); + n2(N._, 279 - 255, 7); + n2(N._, 287 - 279, 8); + H.H.n(N._, 9); + H.H.A(N._, 9, N.J); + H.H.l(N._, 9); + n2(N.$, 32, 5); + H.H.n(N.$, 5); + H.H.A(N.$, 5, N.h); + H.H.l(N.$, 5); + n2(N.Q, 19, 0); + n2(N.C, 286, 0); + n2(N.D, 30, 0); + n2(N.v, 320, 0); + })(); + return H.H.N; +}(); +UPNG.decode._readInterlace = function(data2, out) { + var { width: w, height: h } = out; + var bpp = UPNG.decode._getBPP(out), cbpp = bpp >> 3, bpl = Math.ceil(w * bpp / 8); + var img = new Uint8Array(h * bpl); + var di2 = 0; + var starting_row = [0, 0, 4, 0, 2, 0, 1]; + var starting_col = [0, 4, 0, 2, 0, 1, 0]; + var row_increment = [8, 8, 8, 4, 4, 2, 2]; + var col_increment = [8, 8, 4, 4, 2, 2, 1]; + var pass = 0; + while (pass < 7) { + var ri2 = row_increment[pass], ci = col_increment[pass]; + var sw = 0, sh = 0; + var cr = starting_row[pass]; + while (cr < h) { + cr += ri2; + sh++; + } + var cc = starting_col[pass]; + while (cc < w) { + cc += ci; + sw++; + } + var bpll = Math.ceil(sw * bpp / 8); + UPNG.decode._filterZero(data2, out, di2, sw, sh); + var y3 = 0, row = starting_row[pass]; + var val2; + while (row < h) { + var col = starting_col[pass]; + var cdi = di2 + y3 * bpll << 3; + while (col < w) { + if (bpp == 1) { + val2 = data2[cdi >> 3]; + val2 = val2 >> 7 - (cdi & 7) & 1; + img[row * bpl + (col >> 3)] |= val2 << 7 - ((col & 7) << 0); + } + if (bpp == 2) { + val2 = data2[cdi >> 3]; + val2 = val2 >> 6 - (cdi & 7) & 3; + img[row * bpl + (col >> 2)] |= val2 << 6 - ((col & 3) << 1); + } + if (bpp == 4) { + val2 = data2[cdi >> 3]; + val2 = val2 >> 4 - (cdi & 7) & 15; + img[row * bpl + (col >> 1)] |= val2 << 4 - ((col & 1) << 2); + } + if (bpp >= 8) { + var ii = row * bpl + col * cbpp; + for (var j2 = 0;j2 < cbpp; j2++) + img[ii + j2] = data2[(cdi >> 3) + j2]; + } + cdi += bpp; + col += ci; + } + y3++; + row += ri2; + } + if (sw * sh != 0) + di2 += sh * (1 + bpll); + pass = pass + 1; + } + return img; +}; +UPNG.decode._getBPP = function(out) { + var noc = [1, null, 3, 1, 2, null, 4][out.ctype]; + return noc * out.depth; +}; +UPNG.decode._filterZero = function(data2, out, off, w, h) { + var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w * bpp / 8), paeth = UPNG.decode._paeth; + bpp = Math.ceil(bpp / 8); + var i, di2, type = data2[off], x2 = 0; + if (type > 1) + data2[off] = [0, 0, 1][type - 2]; + if (type == 3) + for (x2 = bpp;x2 < bpl; x2++) + data2[x2 + 1] = data2[x2 + 1] + (data2[x2 + 1 - bpp] >>> 1) & 255; + for (var y3 = 0;y3 < h; y3++) { + i = off + y3 * bpl; + di2 = i + y3 + 1; + type = data2[di2 - 1]; + x2 = 0; + if (type == 0) + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2]; + else if (type == 1) { + for (;x2 < bpp; x2++) + data2[i + x2] = data2[di2 + x2]; + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2] + data2[i + x2 - bpp]; + } else if (type == 2) { + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2] + data2[i + x2 - bpl]; + } else if (type == 3) { + for (;x2 < bpp; x2++) + data2[i + x2] = data2[di2 + x2] + (data2[i + x2 - bpl] >>> 1); + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2] + (data2[i + x2 - bpl] + data2[i + x2 - bpp] >>> 1); + } else { + for (;x2 < bpp; x2++) + data2[i + x2] = data2[di2 + x2] + paeth(0, data2[i + x2 - bpl], 0); + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2] + paeth(data2[i + x2 - bpp], data2[i + x2 - bpl], data2[i + x2 - bpp - bpl]); + } + } + return data2; +}; +UPNG.decode._paeth = function(a, b, c) { + var p = a + b - c, pa2 = p - a, pb = p - b, pc2 = p - c; + if (pa2 * pa2 <= pb * pb && pa2 * pa2 <= pc2 * pc2) + return a; + else if (pb * pb <= pc2 * pc2) + return b; + return c; +}; +UPNG.decode._IHDR = function(data2, offset, out) { + var bin = UPNG._bin; + out.width = bin.readUint(data2, offset); + offset += 4; + out.height = bin.readUint(data2, offset); + offset += 4; + out.depth = data2[offset]; + offset++; + out.ctype = data2[offset]; + offset++; + out.compress = data2[offset]; + offset++; + out.filter = data2[offset]; + offset++; + out.interlace = data2[offset]; + offset++; +}; +UPNG._bin = { + nextZero: function(data2, p) { + while (data2[p] != 0) + p++; + return p; + }, + readUshort: function(buff, p) { + return buff[p] << 8 | buff[p + 1]; + }, + writeUshort: function(buff, p, n2) { + buff[p] = n2 >> 8 & 255; + buff[p + 1] = n2 & 255; + }, + readUint: function(buff, p) { + return buff[p] * (256 * 256 * 256) + (buff[p + 1] << 16 | buff[p + 2] << 8 | buff[p + 3]); + }, + writeUint: function(buff, p, n2) { + buff[p] = n2 >> 24 & 255; + buff[p + 1] = n2 >> 16 & 255; + buff[p + 2] = n2 >> 8 & 255; + buff[p + 3] = n2 & 255; + }, + readASCII: function(buff, p, l2) { + var s = ""; + for (var i = 0;i < l2; i++) + s += String.fromCharCode(buff[p + i]); + return s; + }, + writeASCII: function(data2, p, s) { + for (var i = 0;i < s.length; i++) + data2[p + i] = s.charCodeAt(i); + }, + readBytes: function(buff, p, l2) { + var arr = []; + for (var i = 0;i < l2; i++) + arr.push(buff[p + i]); + return arr; + }, + pad: function(n2) { + return n2.length < 2 ? "0" + n2 : n2; + }, + readUTF8: function(buff, p, l2) { + var s = "", ns; + for (var i = 0;i < l2; i++) + s += "%" + UPNG._bin.pad(buff[p + i].toString(16)); + try { + ns = decodeURIComponent(s); + } catch (e) { + return UPNG._bin.readASCII(buff, p, l2); + } + return ns; + } +}; +UPNG._copyTile = function(sb, sw, sh, tb, tw, th2, xoff, yoff, mode) { + var w = Math.min(sw, tw), h = Math.min(sh, th2); + var si = 0, ti = 0; + for (var y3 = 0;y3 < h; y3++) + for (var x2 = 0;x2 < w; x2++) { + if (xoff >= 0 && yoff >= 0) { + si = y3 * sw + x2 << 2; + ti = (yoff + y3) * tw + xoff + x2 << 2; + } else { + si = (-yoff + y3) * sw - xoff + x2 << 2; + ti = y3 * tw + x2 << 2; + } + if (mode == 0) { + tb[ti] = sb[si]; + tb[ti + 1] = sb[si + 1]; + tb[ti + 2] = sb[si + 2]; + tb[ti + 3] = sb[si + 3]; + } else if (mode == 1) { + var fa = sb[si + 3] * (1 / 255), fr = sb[si] * fa, fg = sb[si + 1] * fa, fb = sb[si + 2] * fa; + var ba2 = tb[ti + 3] * (1 / 255), br = tb[ti] * ba2, bg = tb[ti + 1] * ba2, bb = tb[ti + 2] * ba2; + var ifa = 1 - fa, oa = fa + ba2 * ifa, ioa = oa == 0 ? 0 : 1 / oa; + tb[ti + 3] = 255 * oa; + tb[ti + 0] = (fr + br * ifa) * ioa; + tb[ti + 1] = (fg + bg * ifa) * ioa; + tb[ti + 2] = (fb + bb * ifa) * ioa; + } else if (mode == 2) { + var fa = sb[si + 3], fr = sb[si], fg = sb[si + 1], fb = sb[si + 2]; + var ba2 = tb[ti + 3], br = tb[ti], bg = tb[ti + 1], bb = tb[ti + 2]; + if (fa == ba2 && fr == br && fg == bg && fb == bb) { + tb[ti] = 0; + tb[ti + 1] = 0; + tb[ti + 2] = 0; + tb[ti + 3] = 0; + } else { + tb[ti] = fr; + tb[ti + 1] = fg; + tb[ti + 2] = fb; + tb[ti + 3] = fa; + } + } else if (mode == 3) { + var fa = sb[si + 3], fr = sb[si], fg = sb[si + 1], fb = sb[si + 2]; + var ba2 = tb[ti + 3], br = tb[ti], bg = tb[ti + 1], bb = tb[ti + 2]; + if (fa == ba2 && fr == br && fg == bg && fb == bb) + continue; + if (fa < 220 && ba2 > 20) + return false; + } + } + return true; +}; +// node_modules/three/examples/jsm/libs/utif.module.js +var UTIF = {}; +(function() { + var W = function a1() { + function W2(p) { + this.message = "JPEG error: " + p; + } + W2.prototype = new Error; + W2.prototype.name = "JpegError"; + W2.constructor = W2; + return W2; + }(), ak = function ag() { + var p = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]), t4 = 4017, ac = 799, ah = 3406, ao = 2276, ar2 = 1567, ai = 3784, s = 5793, ad = 2896; + function ak2(Q3) { + if (Q3 == null) + Q3 = {}; + if (Q3.w == null) + Q3.w = -1; + this.V = Q3.n; + this.N = Q3.w; + } + function a5(Q3, h) { + var f = 0, G2 = [], n2, E2, a = 16, F; + while (a > 0 && !Q3[a - 1]) { + a--; + } + G2.push({ children: [], index: 0 }); + var C5 = G2[0]; + for (n2 = 0;n2 < a; n2++) { + for (E2 = 0;E2 < Q3[n2]; E2++) { + C5 = G2.pop(); + C5.children[C5.index] = h[f]; + while (C5.index > 0) { + C5 = G2.pop(); + } + C5.index++; + G2.push(C5); + while (G2.length <= n2) { + G2.push(F = { children: [], index: 0 }); + C5.children[C5.index] = F.children; + C5 = F; + } + f++; + } + if (n2 + 1 < a) { + G2.push(F = { children: [], index: 0 }); + C5.children[C5.index] = F.children; + C5 = F; + } + } + return G2[0].children; + } + function a2(Q3, h, f) { + return 64 * ((Q3.P + 1) * h + f); + } + function a7(Q3, h, f, G2, n2, E2, a, C5, F, d) { + if (d == null) + d = false; + var { m: T3, Z: U } = f, z2 = h, J2 = 0, V3 = 0, r = 0, D = 0, a8, q2 = 0, X, O, _9, N, e, K, x2 = 0, k2, g3, R2, c; + function Y() { + if (V3 > 0) { + V3--; + return J2 >> V3 & 1; + } + J2 = Q3[h++]; + if (J2 === 255) { + var I3 = Q3[h++]; + if (I3) { + if (I3 === 220 && d) { + h += 2; + var l2 = Z3(Q3, h); + h += 2; + if (l2 > 0 && l2 !== f.s) { + throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data", l2); + } + } else if (I3 === 217) { + if (d) { + var M = q2 * 8; + if (M > 0 && M < f.s / 10) { + throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, " + "possibly caused by incorrect `scanLines` parameter", M); + } + } + throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data"); + } + throw new W("unexpected marker"); + } + } + V3 = 7; + return J2 >>> 7; + } + function u3(I3) { + var l2 = I3; + while (true) { + l2 = l2[Y()]; + switch (typeof l2) { + case "number": + return l2; + case "object": + continue; + } + throw new W("invalid huffman sequence"); + } + } + function m(I3) { + var e2 = 0; + while (I3 > 0) { + e2 = e2 << 1 | Y(); + I3--; + } + return e2; + } + function j2(I3) { + if (I3 === 1) { + return Y() === 1 ? 1 : -1; + } + var e2 = m(I3); + if (e2 >= 1 << I3 - 1) { + return e2; + } + return e2 + (-1 << I3) + 1; + } + function v(X2, I3) { + var l2 = u3(X2.J), M = l2 === 0 ? 0 : j2(l2), N4 = 1; + X2.D[I3] = X2.Q += M; + while (N4 < 64) { + var S = u3(X2.i), i = S & 15, A4 = S >> 4; + if (i === 0) { + if (A4 < 15) { + break; + } + N4 += 16; + continue; + } + N4 += A4; + var o = p[N4]; + X2.D[I3 + o] = j2(i); + N4++; + } + } + function $2(X2, I3) { + var l2 = u3(X2.J), M = l2 === 0 ? 0 : j2(l2) << F; + X2.D[I3] = X2.Q += M; + } + function b(X2, I3) { + X2.D[I3] |= Y() << F; + } + function P(X2, I3) { + if (r > 0) { + r--; + return; + } + var N4 = E2, l2 = a; + while (N4 <= l2) { + var M = u3(X2.i), S = M & 15, i = M >> 4; + if (S === 0) { + if (i < 15) { + r = m(i) + (1 << i) - 1; + break; + } + N4 += 16; + continue; + } + N4 += i; + var A4 = p[N4]; + X2.D[I3 + A4] = j2(S) * (1 << F); + N4++; + } + } + function a4(X2, I3) { + var N4 = E2, l2 = a, M = 0, S, i; + while (N4 <= l2) { + var A4 = I3 + p[N4], o = X2.D[A4] < 0 ? -1 : 1; + switch (D) { + case 0: + i = u3(X2.i); + S = i & 15; + M = i >> 4; + if (S === 0) { + if (M < 15) { + r = m(M) + (1 << M); + D = 4; + } else { + M = 16; + D = 1; + } + } else { + if (S !== 1) { + throw new W("invalid ACn encoding"); + } + a8 = j2(S); + D = M ? 2 : 3; + } + continue; + case 1: + case 2: + if (X2.D[A4]) { + X2.D[A4] += o * (Y() << F); + } else { + M--; + if (M === 0) { + D = D === 2 ? 3 : 0; + } + } + break; + case 3: + if (X2.D[A4]) { + X2.D[A4] += o * (Y() << F); + } else { + X2.D[A4] = a8 << F; + D = 0; + } + break; + case 4: + if (X2.D[A4]) { + X2.D[A4] += o * (Y() << F); + } + break; + } + N4++; + } + if (D === 4) { + r--; + if (r === 0) { + D = 0; + } + } + } + function H(X2, I3, x3, l2, M) { + var S = x3 / T3 | 0, i = x3 % T3; + q2 = S * X2.A + l2; + var A4 = i * X2.h + M, o = a2(X2, q2, A4); + I3(X2, o); + } + function w(X2, I3, x3) { + q2 = x3 / X2.P | 0; + var l2 = x3 % X2.P, M = a2(X2, q2, l2); + I3(X2, M); + } + var y3 = G2.length; + if (U) { + if (E2 === 0) { + K = C5 === 0 ? $2 : b; + } else { + K = C5 === 0 ? P : a4; + } + } else { + K = v; + } + if (y3 === 1) { + g3 = G2[0].P * G2[0].c; + } else { + g3 = T3 * f.R; + } + while (x2 <= g3) { + var L = n2 ? Math.min(g3 - x2, n2) : g3; + if (L > 0) { + for (O = 0;O < y3; O++) { + G2[O].Q = 0; + } + r = 0; + if (y3 === 1) { + X = G2[0]; + for (e = 0;e < L; e++) { + w(X, K, x2); + x2++; + } + } else { + for (e = 0;e < L; e++) { + for (O = 0;O < y3; O++) { + X = G2[O]; + R2 = X.h; + c = X.A; + for (_9 = 0;_9 < c; _9++) { + for (N = 0;N < R2; N++) { + H(X, K, x2, _9, N); + } + } + } + x2++; + } + } + } + V3 = 0; + k2 = an(Q3, h); + if (!k2) { + break; + } + if (k2.u) { + var a6 = L > 0 ? "unexpected" : "excessive"; + h = k2.offset; + } + if (k2.M >= 65488 && k2.M <= 65495) { + h += 2; + } else { + break; + } + } + return h - z2; + } + function al2(Q3, h, f) { + var { $: G2, D: n2 } = Q3, E2, a, C5, F, d, T3, U, z2, J2, V3, Y, u3, m, j2, v, $2, b; + if (!G2) { + throw new W("missing required Quantization Table."); + } + for (var r = 0;r < 64; r += 8) { + J2 = n2[h + r]; + V3 = n2[h + r + 1]; + Y = n2[h + r + 2]; + u3 = n2[h + r + 3]; + m = n2[h + r + 4]; + j2 = n2[h + r + 5]; + v = n2[h + r + 6]; + $2 = n2[h + r + 7]; + J2 *= G2[r]; + if ((V3 | Y | u3 | m | j2 | v | $2) === 0) { + b = s * J2 + 512 >> 10; + f[r] = b; + f[r + 1] = b; + f[r + 2] = b; + f[r + 3] = b; + f[r + 4] = b; + f[r + 5] = b; + f[r + 6] = b; + f[r + 7] = b; + continue; + } + V3 *= G2[r + 1]; + Y *= G2[r + 2]; + u3 *= G2[r + 3]; + m *= G2[r + 4]; + j2 *= G2[r + 5]; + v *= G2[r + 6]; + $2 *= G2[r + 7]; + E2 = s * J2 + 128 >> 8; + a = s * m + 128 >> 8; + C5 = Y; + F = v; + d = ad * (V3 - $2) + 128 >> 8; + z2 = ad * (V3 + $2) + 128 >> 8; + T3 = u3 << 4; + U = j2 << 4; + E2 = E2 + a + 1 >> 1; + a = E2 - a; + b = C5 * ai + F * ar2 + 128 >> 8; + C5 = C5 * ar2 - F * ai + 128 >> 8; + F = b; + d = d + U + 1 >> 1; + U = d - U; + z2 = z2 + T3 + 1 >> 1; + T3 = z2 - T3; + E2 = E2 + F + 1 >> 1; + F = E2 - F; + a = a + C5 + 1 >> 1; + C5 = a - C5; + b = d * ao + z2 * ah + 2048 >> 12; + d = d * ah - z2 * ao + 2048 >> 12; + z2 = b; + b = T3 * ac + U * t4 + 2048 >> 12; + T3 = T3 * t4 - U * ac + 2048 >> 12; + U = b; + f[r] = E2 + z2; + f[r + 7] = E2 - z2; + f[r + 1] = a + U; + f[r + 6] = a - U; + f[r + 2] = C5 + T3; + f[r + 5] = C5 - T3; + f[r + 3] = F + d; + f[r + 4] = F - d; + } + for (var P = 0;P < 8; ++P) { + J2 = f[P]; + V3 = f[P + 8]; + Y = f[P + 16]; + u3 = f[P + 24]; + m = f[P + 32]; + j2 = f[P + 40]; + v = f[P + 48]; + $2 = f[P + 56]; + if ((V3 | Y | u3 | m | j2 | v | $2) === 0) { + b = s * J2 + 8192 >> 14; + if (b < -2040) { + b = 0; + } else if (b >= 2024) { + b = 255; + } else { + b = b + 2056 >> 4; + } + n2[h + P] = b; + n2[h + P + 8] = b; + n2[h + P + 16] = b; + n2[h + P + 24] = b; + n2[h + P + 32] = b; + n2[h + P + 40] = b; + n2[h + P + 48] = b; + n2[h + P + 56] = b; + continue; + } + E2 = s * J2 + 2048 >> 12; + a = s * m + 2048 >> 12; + C5 = Y; + F = v; + d = ad * (V3 - $2) + 2048 >> 12; + z2 = ad * (V3 + $2) + 2048 >> 12; + T3 = u3; + U = j2; + E2 = (E2 + a + 1 >> 1) + 4112; + a = E2 - a; + b = C5 * ai + F * ar2 + 2048 >> 12; + C5 = C5 * ar2 - F * ai + 2048 >> 12; + F = b; + d = d + U + 1 >> 1; + U = d - U; + z2 = z2 + T3 + 1 >> 1; + T3 = z2 - T3; + E2 = E2 + F + 1 >> 1; + F = E2 - F; + a = a + C5 + 1 >> 1; + C5 = a - C5; + b = d * ao + z2 * ah + 2048 >> 12; + d = d * ah - z2 * ao + 2048 >> 12; + z2 = b; + b = T3 * ac + U * t4 + 2048 >> 12; + T3 = T3 * t4 - U * ac + 2048 >> 12; + U = b; + J2 = E2 + z2; + $2 = E2 - z2; + V3 = a + U; + v = a - U; + Y = C5 + T3; + j2 = C5 - T3; + u3 = F + d; + m = F - d; + if (J2 < 16) { + J2 = 0; + } else if (J2 >= 4080) { + J2 = 255; + } else { + J2 >>= 4; + } + if (V3 < 16) { + V3 = 0; + } else if (V3 >= 4080) { + V3 = 255; + } else { + V3 >>= 4; + } + if (Y < 16) { + Y = 0; + } else if (Y >= 4080) { + Y = 255; + } else { + Y >>= 4; + } + if (u3 < 16) { + u3 = 0; + } else if (u3 >= 4080) { + u3 = 255; + } else { + u3 >>= 4; + } + if (m < 16) { + m = 0; + } else if (m >= 4080) { + m = 255; + } else { + m >>= 4; + } + if (j2 < 16) { + j2 = 0; + } else if (j2 >= 4080) { + j2 = 255; + } else { + j2 >>= 4; + } + if (v < 16) { + v = 0; + } else if (v >= 4080) { + v = 255; + } else { + v >>= 4; + } + if ($2 < 16) { + $2 = 0; + } else if ($2 >= 4080) { + $2 = 255; + } else { + $2 >>= 4; + } + n2[h + P] = J2; + n2[h + P + 8] = V3; + n2[h + P + 16] = Y; + n2[h + P + 24] = u3; + n2[h + P + 32] = m; + n2[h + P + 40] = j2; + n2[h + P + 48] = v; + n2[h + P + 56] = $2; + } + } + function a0(Q3, h) { + var { P: f, c: G2 } = h, n2 = new Int16Array(64); + for (var E2 = 0;E2 < G2; E2++) { + for (var a = 0;a < f; a++) { + var C5 = a2(h, E2, a); + al2(h, C5, n2); + } + } + return h.D; + } + function an(Q3, h, f) { + if (f == null) + f = h; + var G2 = Q3.length - 1, n2 = f < h ? f : h; + if (h >= G2) { + return null; + } + var E2 = Z3(Q3, h); + if (E2 >= 65472 && E2 <= 65534) { + return { u: null, M: E2, offset: h }; + } + var a = Z3(Q3, n2); + while (!(a >= 65472 && a <= 65534)) { + if (++n2 >= G2) { + return null; + } + a = Z3(Q3, n2); + } + return { u: E2.toString(16), M: a, offset: n2 }; + } + ak2.prototype = { parse(Q3, h) { + if (h == null) + h = {}; + var f = h.F, E2 = 0, a = null, C5 = null, F, d, T3 = 0; + function G2() { + var o = Z3(Q3, E2); + E2 += 2; + var B3 = E2 + o - 2, V4 = an(Q3, B3, E2); + if (V4 && V4.u) { + B3 = V4.offset; + } + var ab = Q3.subarray(E2, B3); + E2 += ab.length; + return ab; + } + function n2(F3) { + var o = Math.ceil(F3.o / 8 / F3.X), B3 = Math.ceil(F3.s / 8 / F3.B); + for (var Y2 = 0;Y2 < F3.W.length; Y2++) { + R2 = F3.W[Y2]; + var ab = Math.ceil(Math.ceil(F3.o / 8) * R2.h / F3.X), af = Math.ceil(Math.ceil(F3.s / 8) * R2.A / F3.B), ap2 = o * R2.h, aq = B3 * R2.A, ae3 = 64 * aq * (ap2 + 1); + R2.D = new Int16Array(ae3); + R2.P = ab; + R2.c = af; + } + F3.m = o; + F3.R = B3; + } + var U = [], z2 = [], J2 = [], V3 = Z3(Q3, E2); + E2 += 2; + if (V3 !== 65496) { + throw new W("SOI not found"); + } + V3 = Z3(Q3, E2); + E2 += 2; + markerLoop: + while (V3 !== 65497) { + var Y, u3, m; + switch (V3) { + case 65504: + case 65505: + case 65506: + case 65507: + case 65508: + case 65509: + case 65510: + case 65511: + case 65512: + case 65513: + case 65514: + case 65515: + case 65516: + case 65517: + case 65518: + case 65519: + case 65534: + var j2 = G2(); + if (V3 === 65504) { + if (j2[0] === 74 && j2[1] === 70 && j2[2] === 73 && j2[3] === 70 && j2[4] === 0) { + a = { version: { d: j2[5], T: j2[6] }, K: j2[7], j: j2[8] << 8 | j2[9], H: j2[10] << 8 | j2[11], S: j2[12], I: j2[13], C: j2.subarray(14, 14 + 3 * j2[12] * j2[13]) }; + } + } + if (V3 === 65518) { + if (j2[0] === 65 && j2[1] === 100 && j2[2] === 111 && j2[3] === 98 && j2[4] === 101) { + C5 = { version: j2[5] << 8 | j2[6], k: j2[7] << 8 | j2[8], q: j2[9] << 8 | j2[10], a: j2[11] }; + } + } + break; + case 65499: + var v = Z3(Q3, E2), b; + E2 += 2; + var $2 = v + E2 - 2; + while (E2 < $2) { + var r = Q3[E2++], P = new Uint16Array(64); + if (r >> 4 === 0) { + for (u3 = 0;u3 < 64; u3++) { + b = p[u3]; + P[b] = Q3[E2++]; + } + } else if (r >> 4 === 1) { + for (u3 = 0;u3 < 64; u3++) { + b = p[u3]; + P[b] = Z3(Q3, E2); + E2 += 2; + } + } else { + throw new W("DQT - invalid table spec"); + } + U[r & 15] = P; + } + break; + case 65472: + case 65473: + case 65474: + if (F) { + throw new W("Only single frame JPEGs supported"); + } + E2 += 2; + F = {}; + F.G = V3 === 65473; + F.Z = V3 === 65474; + F.precision = Q3[E2++]; + var D = Z3(Q3, E2), a4, q2 = 0, H = 0; + E2 += 2; + F.s = f || D; + F.o = Z3(Q3, E2); + E2 += 2; + F.W = []; + F._ = {}; + var a8 = Q3[E2++]; + for (Y = 0;Y < a8; Y++) { + a4 = Q3[E2]; + var w = Q3[E2 + 1] >> 4, y3 = Q3[E2 + 1] & 15; + if (q2 < w) { + q2 = w; + } + if (H < y3) { + H = y3; + } + var X = Q3[E2 + 2]; + m = F.W.push({ h: w, A: y3, L: X, $: null }); + F._[a4] = m - 1; + E2 += 3; + } + F.X = q2; + F.B = H; + n2(F); + break; + case 65476: + var O = Z3(Q3, E2); + E2 += 2; + for (Y = 2;Y < O; ) { + var _9 = Q3[E2++], N = new Uint8Array(16), e = 0; + for (u3 = 0;u3 < 16; u3++, E2++) { + e += N[u3] = Q3[E2]; + } + var K = new Uint8Array(e); + for (u3 = 0;u3 < e; u3++, E2++) { + K[u3] = Q3[E2]; + } + Y += 17 + e; + (_9 >> 4 === 0 ? J2 : z2)[_9 & 15] = a5(N, K); + } + break; + case 65501: + E2 += 2; + d = Z3(Q3, E2); + E2 += 2; + break; + case 65498: + var x2 = ++T3 === 1 && !f, R2; + E2 += 2; + var k2 = Q3[E2++], g3 = []; + for (Y = 0;Y < k2; Y++) { + var c = Q3[E2++], L = F._[c]; + R2 = F.W[L]; + R2.index = c; + var a6 = Q3[E2++]; + R2.J = J2[a6 >> 4]; + R2.i = z2[a6 & 15]; + g3.push(R2); + } + var I3 = Q3[E2++], l2 = Q3[E2++], M = Q3[E2++]; + try { + var S = a7(Q3, E2, F, g3, d, I3, l2, M >> 4, M & 15, x2); + E2 += S; + } catch (ex) { + if (ex instanceof DNLMarkerError) { + return this.parse(Q3, { F: ex.s }); + } else if (ex instanceof EOIMarkerError) { + break markerLoop; + } + throw ex; + } + break; + case 65500: + E2 += 4; + break; + case 65535: + if (Q3[E2] !== 255) { + E2--; + } + break; + default: + var i = an(Q3, E2 - 2, E2 - 3); + if (i && i.u) { + E2 = i.offset; + break; + } + if (E2 >= Q3.length - 1) { + break markerLoop; + } + throw new W("JpegImage.parse - unknown marker: " + V3.toString(16)); + } + V3 = Z3(Q3, E2); + E2 += 2; + } + this.width = F.o; + this.height = F.s; + this.g = a; + this.b = C5; + this.W = []; + for (Y = 0;Y < F.W.length; Y++) { + R2 = F.W[Y]; + var A4 = U[R2.L]; + if (A4) { + R2.$ = A4; + } + this.W.push({ index: R2.index, e: a0(F, R2), l: R2.h / F.X, t: R2.A / F.B, P: R2.P, c: R2.c }); + } + this.p = this.W.length; + return; + }, Y(Q3, h, f) { + if (f == null) + f = false; + var G2 = this.width / Q3, n2 = this.height / h, E2, a, C5, F, d, T3, U, z2, J2, V3, Y = 0, u3, m = this.W.length, j2 = Q3 * h * m, v = new Uint8ClampedArray(j2), $2 = new Uint32Array(Q3), b = 4294967288, r; + for (U = 0;U < m; U++) { + E2 = this.W[U]; + a = E2.l * G2; + C5 = E2.t * n2; + Y = U; + u3 = E2.e; + F = E2.P + 1 << 3; + if (a !== r) { + for (d = 0;d < Q3; d++) { + z2 = 0 | d * a; + $2[d] = (z2 & b) << 3 | z2 & 7; + } + r = a; + } + for (T3 = 0;T3 < h; T3++) { + z2 = 0 | T3 * C5; + V3 = F * (z2 & b) | (z2 & 7) << 3; + for (d = 0;d < Q3; d++) { + v[Y] = u3[V3 + $2[d]]; + Y += m; + } + } + } + var P = this.V; + if (!f && m === 4 && !P) { + P = new Int32Array([-256, 255, -256, 255, -256, 255, -256, 255]); + } + if (P) { + for (U = 0;U < j2; ) { + for (z2 = 0, J2 = 0;z2 < m; z2++, U++, J2 += 2) { + v[U] = (v[U] * P[J2] >> 8) + P[J2 + 1]; + } + } + } + return v; + }, get f() { + if (this.b) { + return !!this.b.a; + } + if (this.p === 3) { + if (this.N === 0) { + return false; + } else if (this.W[0].index === 82 && this.W[1].index === 71 && this.W[2].index === 66) { + return false; + } + return true; + } + if (this.N === 1) { + return true; + } + return false; + }, z: function aj(Q3) { + var h, f, G2; + for (var n2 = 0, E2 = Q3.length;n2 < E2; n2 += 3) { + h = Q3[n2]; + f = Q3[n2 + 1]; + G2 = Q3[n2 + 2]; + Q3[n2] = h - 179.456 + 1.402 * G2; + Q3[n2 + 1] = h + 135.459 - 0.344 * f - 0.714 * G2; + Q3[n2 + 2] = h - 226.816 + 1.772 * f; + } + return Q3; + }, O: function aa(Q3) { + var h, f, G2, n2, E2 = 0; + for (var a = 0, C5 = Q3.length;a < C5; a += 4) { + h = Q3[a]; + f = Q3[a + 1]; + G2 = Q3[a + 2]; + n2 = Q3[a + 3]; + Q3[E2++] = -122.67195406894 + f * (-0.0000660635669420364 * f + 0.000437130475926232 * G2 - 0.000054080610064599 * h + 0.00048449797120281 * n2 - 0.154362151871126) + G2 * (-0.000957964378445773 * G2 + 0.000817076911346625 * h - 0.00477271405408747 * n2 + 1.53380253221734) + h * (0.000961250184130688 * h - 0.00266257332283933 * n2 + 0.48357088451265) + n2 * (-0.000336197177618394 * n2 + 0.484791561490776); + Q3[E2++] = 107.268039397724 + f * (0.0000219927104525741 * f - 0.000640992018297945 * G2 + 0.000659397001245577 * h + 0.000426105652938837 * n2 - 0.176491792462875) + G2 * (-0.000778269941513683 * G2 + 0.00130872261408275 * h + 0.000770482631801132 * n2 - 0.151051492775562) + h * (0.00126935368114843 * h - 0.00265090189010898 * n2 + 0.25802910206845) + n2 * (-0.000318913117588328 * n2 - 0.213742400323665); + Q3[E2++] = -20.810012546947 + f * (-0.000570115196973677 * f - 0.0000263409051004589 * G2 + 0.0020741088115012 * h - 0.00288260236853442 * n2 + 0.814272968359295) + G2 * (-0.0000153496057440975 * G2 - 0.000132689043961446 * h + 0.000560833691242812 * n2 - 0.195152027534049) + h * (0.00174418132927582 * h - 0.00255243321439347 * n2 + 0.116935020465145) + n2 * (-0.000343531996510555 * n2 + 0.24165260232407); + } + return Q3.subarray(0, E2); + }, r: function a3(Q3) { + var h, f, G2; + for (var n2 = 0, E2 = Q3.length;n2 < E2; n2 += 4) { + h = Q3[n2]; + f = Q3[n2 + 1]; + G2 = Q3[n2 + 2]; + Q3[n2] = 434.456 - h - 1.402 * G2; + Q3[n2 + 1] = 119.541 - h + 0.344 * f + 0.714 * G2; + Q3[n2 + 2] = 481.816 - h - 1.772 * f; + } + return Q3; + }, U: function as(Q3) { + var h, f, G2, n2, E2 = 0; + for (var a = 0, C5 = Q3.length;a < C5; a += 4) { + h = Q3[a]; + f = Q3[a + 1]; + G2 = Q3[a + 2]; + n2 = Q3[a + 3]; + Q3[E2++] = 255 + h * (-0.00006747147073602441 * h + 0.0008379262121013727 * f + 0.0002894718188643294 * G2 + 0.003264231057537806 * n2 - 1.1185611867203937) + f * (0.000026374107616089405 * f - 0.00008626949158638572 * G2 - 0.0002748769067499491 * n2 - 0.02155688794978967) + G2 * (-0.00003878099212869363 * G2 - 0.0003267808279485286 * n2 + 0.0686742238595345) - n2 * (0.0003361971776183937 * n2 + 0.7430659151342254); + Q3[E2++] = 255 + h * (0.00013596372813588848 * h + 0.000924537132573585 * f + 0.00010567359618683593 * G2 + 0.0004791864687436512 * n2 - 0.3109689587515875) + f * (-0.00023545346108370344 * f + 0.0002702845253534714 * G2 + 0.0020200308977307156 * n2 - 0.7488052167015494) + G2 * (0.00006834815998235662 * G2 + 0.00015168452363460973 * n2 - 0.09751927774728933) - n2 * (0.0003189131175883281 * n2 + 0.7364883807733168); + Q3[E2++] = 255 + h * (0.000013598650411385307 * h + 0.00012423956175490851 * f + 0.0004751985097583589 * G2 - 0.0000036729317476630422 * n2 - 0.05562186980264034) + f * (0.00016141380598724676 * f + 0.0009692239130725186 * G2 + 0.0007782692450036253 * n2 - 0.44015232367526463) + G2 * (0.0000005068882914068769 * G2 + 0.0017778369011375071 * n2 - 0.7591454649749609) - n2 * (0.0003435319965105553 * n2 + 0.7063770186160144); + } + return Q3.subarray(0, E2); + }, getData: function(Q3) { + var { width: h, height: f, forceRGB: G2, isSourcePDF: n2 } = Q3; + if (this.p > 4) { + throw new W("Unsupported color mode"); + } + var E2 = this.Y(h, f, n2); + if (this.p === 1 && G2) { + var a = E2.length, C5 = new Uint8ClampedArray(a * 3), F = 0; + for (var d = 0;d < a; d++) { + var T3 = E2[d]; + C5[F++] = T3; + C5[F++] = T3; + C5[F++] = T3; + } + return C5; + } else if (this.p === 3 && this.f) { + return this.z(E2); + } else if (this.p === 4) { + if (this.f) { + if (G2) { + return this.O(E2); + } + return this.r(E2); + } else if (G2) { + return this.U(E2); + } + } + return E2; + } }; + return ak2; + }(); + function a9(p, t4) { + return p[t4] << 24 >> 24; + } + function Z3(p, t4) { + return p[t4] << 8 | p[t4 + 1]; + } + function am(p, t4) { + return (p[t4] << 24 | p[t4 + 1] << 16 | p[t4 + 2] << 8 | p[t4 + 3]) >>> 0; + } + UTIF.JpegDecoder = ak; +})(); +UTIF.encodeImage = function(rgba, w, h, metadata) { + var idf = { + t256: [w], + t257: [h], + t258: [8, 8, 8, 8], + t259: [1], + t262: [2], + t273: [1000], + t277: [4], + t278: [h], + t279: [w * h * 4], + t282: [[72, 1]], + t283: [[72, 1]], + t284: [1], + t286: [[0, 1]], + t287: [[0, 1]], + t296: [1], + t305: ["Photopea (UTIF.js)"], + t338: [1] + }; + if (metadata) + for (var i in metadata) + idf[i] = metadata[i]; + var prfx = new Uint8Array(UTIF.encode([idf])); + var img = new Uint8Array(rgba); + var data2 = new Uint8Array(1000 + w * h * 4); + for (var i = 0;i < prfx.length; i++) + data2[i] = prfx[i]; + for (var i = 0;i < img.length; i++) + data2[1000 + i] = img[i]; + return data2.buffer; +}; +UTIF.encode = function(ifds) { + var LE = false; + var data2 = new Uint8Array(20000), offset = 4, bin = LE ? UTIF._binLE : UTIF._binBE; + data2[0] = data2[1] = LE ? 73 : 77; + bin.writeUshort(data2, 2, 42); + var ifdo = 8; + bin.writeUint(data2, offset, ifdo); + offset += 4; + for (var i = 0;i < ifds.length; i++) { + var noffs = UTIF._writeIFD(bin, UTIF._types.basic, data2, ifdo, ifds[i]); + ifdo = noffs[1]; + if (i < ifds.length - 1) { + if ((ifdo & 3) != 0) + ifdo += 4 - (ifdo & 3); + bin.writeUint(data2, noffs[0], ifdo); + } + } + return data2.slice(0, ifdo).buffer; +}; +UTIF.decode = function(buff, prm) { + if (prm == null) + prm = { parseMN: true, debug: false }; + var data2 = new Uint8Array(buff), offset = 0; + var id = UTIF._binBE.readASCII(data2, offset, 2); + offset += 2; + var bin = id == "II" ? UTIF._binLE : UTIF._binBE; + var num = bin.readUshort(data2, offset); + offset += 2; + var ifdo = bin.readUint(data2, offset); + offset += 4; + var ifds = []; + while (true) { + var cnt = bin.readUshort(data2, ifdo), typ = bin.readUshort(data2, ifdo + 4); + if (cnt != 0) { + if (typ < 1 || 13 < typ) { + log("error in TIFF"); + break; + } + } + UTIF._readIFD(bin, data2, ifdo, ifds, 0, prm); + ifdo = bin.readUint(data2, ifdo + 2 + cnt * 12); + if (ifdo == 0) + break; + } + return ifds; +}; +UTIF.decodeImage = function(buff, img, ifds) { + if (img.data) + return; + var data2 = new Uint8Array(buff); + var id = UTIF._binBE.readASCII(data2, 0, 2); + if (img["t256"] == null) + return; + img.isLE = id == "II"; + img.width = img["t256"][0]; + img.height = img["t257"][0]; + var cmpr = img["t259"] ? img["t259"][0] : 1; + var fo = img["t266"] ? img["t266"][0] : 1; + if (img["t284"] && img["t284"][0] == 2) + log("PlanarConfiguration 2 should not be used!"); + if (cmpr == 7 && img["t258"] && img["t258"].length > 3) + img["t258"] = img["t258"].slice(0, 3); + var spp = img["t277"] ? img["t277"][0] : 1; + var bps = img["t258"] ? img["t258"][0] : 1; + var bipp = bps * spp; + if (cmpr == 1 && img["t279"] != null && img["t278"] && img["t262"][0] == 32803) { + bipp = Math.round(img["t279"][0] * 8 / (img.width * img["t278"][0])); + } + if (img["t50885"] && img["t50885"][0] == 4) + bipp = img["t258"][0] * 3; + var bipl = Math.ceil(img.width * bipp / 8) * 8; + var soff = img["t273"]; + if (soff == null || img["t322"]) + soff = img["t324"]; + var bcnt = img["t279"]; + if (cmpr == 1 && soff.length == 1) + bcnt = [img.height * (bipl >>> 3)]; + if (bcnt == null || img["t322"]) + bcnt = img["t325"]; + var bytes = new Uint8Array(img.height * (bipl >>> 3)), bilen = 0; + if (img["t322"] != null) { + var tw = img["t322"][0], th2 = img["t323"][0]; + var tx = Math.floor((img.width + tw - 1) / tw); + var ty2 = Math.floor((img.height + th2 - 1) / th2); + var tbuff = new Uint8Array(Math.ceil(tw * th2 * bipp / 8) | 0); + console.log("====", tx, ty2); + for (var y3 = 0;y3 < ty2; y3++) + for (var x2 = 0;x2 < tx; x2++) { + var i = y3 * tx + x2; + tbuff.fill(0); + UTIF.decode._decompress(img, ifds, data2, soff[i], bcnt[i], cmpr, tbuff, 0, fo, tw, th2); + if (cmpr == 6) + bytes = tbuff; + else + UTIF._copyTile(tbuff, Math.ceil(tw * bipp / 8) | 0, th2, bytes, Math.ceil(img.width * bipp / 8) | 0, img.height, Math.ceil(x2 * tw * bipp / 8) | 0, y3 * th2); + } + bilen = bytes.length * 8; + } else { + if (soff == null) + return; + var rps = img["t278"] ? img["t278"][0] : img.height; + rps = Math.min(rps, img.height); + for (var i = 0;i < soff.length; i++) { + UTIF.decode._decompress(img, ifds, data2, soff[i], bcnt[i], cmpr, bytes, Math.ceil(bilen / 8) | 0, fo, img.width, rps); + bilen += bipl * rps; + } + bilen = Math.min(bilen, bytes.length * 8); + } + img.data = new Uint8Array(bytes.buffer, 0, Math.ceil(bilen / 8) | 0); +}; +UTIF.decode._decompress = function(img, ifds, data2, off, len, cmpr, tgt, toff, fo, w, h) { + if (img["t271"] && img["t271"][0] == "Panasonic" && img["t45"] && img["t45"][0] == 6) + cmpr = 34316; + if (false) { + } else if (cmpr == 1) + for (var j2 = 0;j2 < len; j2++) + tgt[toff + j2] = data2[off + j2]; + else if (cmpr == 2) + UTIF.decode._decodeG2(data2, off, len, tgt, toff, w, fo); + else if (cmpr == 3) + UTIF.decode._decodeG3(data2, off, len, tgt, toff, w, fo, img["t292"] ? (img["t292"][0] & 1) == 1 : false); + else if (cmpr == 4) + UTIF.decode._decodeG4(data2, off, len, tgt, toff, w, fo); + else if (cmpr == 5) + UTIF.decode._decodeLZW(data2, off, len, tgt, toff, 8); + else if (cmpr == 6) + UTIF.decode._decodeOldJPEG(img, data2, off, len, tgt, toff); + else if (cmpr == 7 || cmpr == 34892) + UTIF.decode._decodeNewJPEG(img, data2, off, len, tgt, toff); + else if (cmpr == 8 || cmpr == 32946) { + var src = new Uint8Array(data2.buffer, off + 2, len - 6); + var bin = UTIF._inflateRaw(src); + if (toff + bin.length <= tgt.length) + tgt.set(bin, toff); + } else if (cmpr == 9) + UTIF.decode._decodeVC5(data2, off, len, tgt, toff, img["t33422"]); + else if (cmpr == 32767) + UTIF.decode._decodeARW(img, data2, off, len, tgt, toff); + else if (cmpr == 32773) + UTIF.decode._decodePackBits(data2, off, len, tgt, toff); + else if (cmpr == 32809) + UTIF.decode._decodeThunder(data2, off, len, tgt, toff); + else if (cmpr == 34316) + UTIF.decode._decodePanasonic(img, data2, off, len, tgt, toff); + else if (cmpr == 34713) + UTIF.decode._decodeNikon(img, ifds, data2, off, len, tgt, toff); + else if (cmpr == 34676) + UTIF.decode._decodeLogLuv32(img, data2, off, len, tgt, toff); + else + log("Unknown compression", cmpr); + var bps = img["t258"] ? Math.min(32, img["t258"][0]) : 1; + var noc = img["t277"] ? img["t277"][0] : 1, bpp = bps * noc >>> 3, bpl = Math.ceil(bps * noc * w / 8); + if (bps == 16 && !img.isLE && img["t33422"] == null) + for (var y3 = 0;y3 < h; y3++) { + var roff = toff + y3 * bpl; + for (var x2 = 1;x2 < bpl; x2 += 2) { + var t4 = tgt[roff + x2]; + tgt[roff + x2] = tgt[roff + x2 - 1]; + tgt[roff + x2 - 1] = t4; + } + } + if (img["t317"] && img["t317"][0] == 2) { + for (var y3 = 0;y3 < h; y3++) { + var ntoff = toff + y3 * bpl; + if (bps == 16) + for (var j2 = bpp;j2 < bpl; j2 += 2) { + var nv = (tgt[ntoff + j2 + 1] << 8 | tgt[ntoff + j2]) + (tgt[ntoff + j2 - bpp + 1] << 8 | tgt[ntoff + j2 - bpp]); + tgt[ntoff + j2] = nv & 255; + tgt[ntoff + j2 + 1] = nv >>> 8 & 255; + } + else if (noc == 3) + for (var j2 = 3;j2 < bpl; j2 += 3) { + tgt[ntoff + j2] = tgt[ntoff + j2] + tgt[ntoff + j2 - 3] & 255; + tgt[ntoff + j2 + 1] = tgt[ntoff + j2 + 1] + tgt[ntoff + j2 - 2] & 255; + tgt[ntoff + j2 + 2] = tgt[ntoff + j2 + 2] + tgt[ntoff + j2 - 1] & 255; + } + else + for (var j2 = bpp;j2 < bpl; j2++) + tgt[ntoff + j2] = tgt[ntoff + j2] + tgt[ntoff + j2 - bpp] & 255; + } + } +}; +UTIF.decode._decodePanasonic = function(img, data2, off, len, tgt, toff) { + var img_buffer = data2.buffer; + var rawWidth = img["t2"][0]; + var rawHeight = img["t3"][0]; + var bitsPerSample = img["t10"][0]; + var RW2_Format = img["t45"][0]; + var bidx = 0; + var imageIndex = 0; + var vpos = 0; + var byte = 0; + var arr_a, arr_b; + var bytes = RW2_Format == 6 ? new Uint32Array(18) : new Uint8Array(16); + var i, j2, sh, pred = [0, 0], nonz = [0, 0], isOdd, idx = 0, pixel_base; + var row, col, crow; + var buffer = new Uint8Array(16384); + var result = new Uint16Array(tgt.buffer); + function getDataRaw(bits) { + if (vpos == 0) { + var arr_a2 = new Uint8Array(img_buffer, off + imageIndex + 8184, 16384 - 8184); + var arr_b2 = new Uint8Array(img_buffer, off + imageIndex, 8184); + buffer.set(arr_a2); + buffer.set(arr_b2, arr_a2.length); + imageIndex += 16384; + } + if (RW2_Format == 5) { + for (i = 0;i < 16; i++) { + bytes[i] = buffer[vpos++]; + vpos &= 16383; + } + } else { + vpos = vpos - bits & 131071; + byte = vpos >> 3 ^ 16368; + return (buffer[byte] | buffer[byte + 1] << 8) >> (vpos & 7) & ~(-1 << bits); + } + } + function getBufferDataRW6(i3) { + return buffer[vpos + 15 - i3]; + } + function readPageRW6() { + bytes[0] = getBufferDataRW6(0) << 6 | getBufferDataRW6(1) >> 2; + bytes[1] = ((getBufferDataRW6(1) & 3) << 12 | getBufferDataRW6(2) << 4 | getBufferDataRW6(3) >> 4) & 16383; + bytes[2] = getBufferDataRW6(3) >> 2 & 3; + bytes[3] = (getBufferDataRW6(3) & 3) << 8 | getBufferDataRW6(4); + bytes[4] = getBufferDataRW6(5) << 2 | getBufferDataRW6(6) >> 6; + bytes[5] = (getBufferDataRW6(6) & 63) << 4 | getBufferDataRW6(7) >> 4; + bytes[6] = getBufferDataRW6(7) >> 2 & 3; + bytes[7] = (getBufferDataRW6(7) & 3) << 8 | getBufferDataRW6(8); + bytes[8] = getBufferDataRW6(9) << 2 & 1020 | getBufferDataRW6(10) >> 6; + bytes[9] = (getBufferDataRW6(10) << 4 | getBufferDataRW6(11) >> 4) & 1023; + bytes[10] = getBufferDataRW6(11) >> 2 & 3; + bytes[11] = (getBufferDataRW6(11) & 3) << 8 | getBufferDataRW6(12); + bytes[12] = (getBufferDataRW6(13) << 2 & 1020 | getBufferDataRW6(14) >> 6) & 1023; + bytes[13] = (getBufferDataRW6(14) << 4 | getBufferDataRW6(15) >> 4) & 1023; + vpos += 16; + byte = 0; + } + function readPageRw6_bps12() { + bytes[0] = getBufferDataRW6(0) << 4 | getBufferDataRW6(1) >> 4; + bytes[1] = ((getBufferDataRW6(1) & 15) << 8 | getBufferDataRW6(2)) & 4095; + bytes[2] = getBufferDataRW6(3) >> 6 & 3; + bytes[3] = (getBufferDataRW6(3) & 63) << 2 | getBufferDataRW6(4) >> 6; + bytes[4] = (getBufferDataRW6(4) & 63) << 2 | getBufferDataRW6(5) >> 6; + bytes[5] = (getBufferDataRW6(5) & 63) << 2 | getBufferDataRW6(6) >> 6; + bytes[6] = getBufferDataRW6(6) >> 4 & 3; + bytes[7] = (getBufferDataRW6(6) & 15) << 4 | getBufferDataRW6(7) >> 4; + bytes[8] = (getBufferDataRW6(7) & 15) << 4 | getBufferDataRW6(8) >> 4; + bytes[9] = (getBufferDataRW6(8) & 15) << 4 | getBufferDataRW6(9) >> 4; + bytes[10] = getBufferDataRW6(9) >> 2 & 3; + bytes[11] = (getBufferDataRW6(9) & 3) << 6 | getBufferDataRW6(10) >> 2; + bytes[12] = (getBufferDataRW6(10) & 3) << 6 | getBufferDataRW6(11) >> 2; + bytes[13] = (getBufferDataRW6(11) & 3) << 6 | getBufferDataRW6(12) >> 2; + bytes[14] = getBufferDataRW6(12) & 3; + bytes[15] = getBufferDataRW6(13); + bytes[16] = getBufferDataRW6(14); + bytes[17] = getBufferDataRW6(15); + vpos += 16; + byte = 0; + } + function resetPredNonzeros() { + pred[0] = 0; + pred[1] = 0; + nonz[0] = 0; + nonz[1] = 0; + } + if (RW2_Format == 7) { + throw RW2_Format; + } else if (RW2_Format == 6) { + var is12bit = bitsPerSample == 12, readPageRw6Fn = is12bit ? readPageRw6_bps12 : readPageRW6, pixelsPerBlock = is12bit ? 14 : 11, pixelbase0 = is12bit ? 128 : 512, pixelbase_compare = is12bit ? 2048 : 8192, spix_compare = is12bit ? 16383 : 65535, pixel_mask = is12bit ? 4095 : 16383, blocksperrow = rawWidth / pixelsPerBlock, rowbytes = blocksperrow * 16, bufferSize = is12bit ? 18 : 14; + for (row = 0;row < rawHeight - 15; row += 16) { + var rowstoread = Math.min(16, rawHeight - row); + var readlen = rowbytes * rowstoread; + buffer = new Uint8Array(img_buffer, off + bidx, readlen); + vpos = 0; + bidx += readlen; + for (crow = 0, col = 0;crow < rowstoread; crow++, col = 0) { + idx = (row + crow) * rawWidth; + for (var rblock = 0;rblock < blocksperrow; rblock++) { + readPageRw6Fn(); + resetPredNonzeros(); + sh = 0; + pixel_base = 0; + for (i = 0;i < pixelsPerBlock; i++) { + isOdd = i & 1; + if (i % 3 == 2) { + var base = byte < bufferSize ? bytes[byte++] : 0; + if (base == 3) + base = 4; + pixel_base = pixelbase0 << base; + sh = 1 << base; + } + var epixel = byte < bufferSize ? bytes[byte++] : 0; + if (pred[isOdd]) { + epixel *= sh; + if (pixel_base < pixelbase_compare && nonz[isOdd] > pixel_base) + epixel += nonz[isOdd] - pixel_base; + nonz[isOdd] = epixel; + } else { + pred[isOdd] = epixel; + if (epixel) + nonz[isOdd] = epixel; + else + epixel = nonz[isOdd]; + } + result[idx + col++] = epixel - 15 <= spix_compare ? epixel - 15 & spix_compare : epixel + 2147483633 >> 31 & pixel_mask; + } + } + } + } + } else if (RW2_Format == 5) { + var blockSize = bitsPerSample == 12 ? 10 : 9; + for (row = 0;row < rawHeight; row++) { + for (col = 0;col < rawWidth; col += blockSize) { + getDataRaw(0); + if (bitsPerSample == 12) { + result[idx++] = ((bytes[1] & 15) << 8) + bytes[0]; + result[idx++] = 16 * bytes[2] + (bytes[1] >> 4); + result[idx++] = ((bytes[4] & 15) << 8) + bytes[3]; + result[idx++] = 16 * bytes[5] + (bytes[4] >> 4); + result[idx++] = ((bytes[7] & 15) << 8) + bytes[6]; + result[idx++] = 16 * bytes[8] + (bytes[7] >> 4); + result[idx++] = ((bytes[10] & 15) << 8) + bytes[9]; + result[idx++] = 16 * bytes[11] + (bytes[10] >> 4); + result[idx++] = ((bytes[13] & 15) << 8) + bytes[12]; + result[idx++] = 16 * bytes[14] + (bytes[13] >> 4); + } else if (bitsPerSample == 14) { + result[idx++] = bytes[0] + ((bytes[1] & 63) << 8); + result[idx++] = (bytes[1] >> 6) + 4 * bytes[2] + ((bytes[3] & 15) << 10); + result[idx++] = (bytes[3] >> 4) + 16 * bytes[4] + ((bytes[5] & 3) << 12); + result[idx++] = ((bytes[5] & 252) >> 2) + (bytes[6] << 6); + result[idx++] = bytes[7] + ((bytes[8] & 63) << 8); + result[idx++] = (bytes[8] >> 6) + 4 * bytes[9] + ((bytes[10] & 15) << 10); + result[idx++] = (bytes[10] >> 4) + 16 * bytes[11] + ((bytes[12] & 3) << 12); + result[idx++] = ((bytes[12] & 252) >> 2) + (bytes[13] << 6); + result[idx++] = bytes[14] + ((bytes[15] & 63) << 8); + } + } + } + } else if (RW2_Format == 4) { + for (row = 0;row < rawHeight; row++) { + for (col = 0;col < rawWidth; col++) { + i = col % 14; + isOdd = i & 1; + if (i == 0) + resetPredNonzeros(); + if (i % 3 == 2) + sh = 4 >> 3 - getDataRaw(2); + if (nonz[isOdd]) { + j2 = getDataRaw(8); + if (j2 != 0) { + pred[isOdd] -= 128 << sh; + if (pred[isOdd] < 0 || sh == 4) + pred[isOdd] &= ~(-1 << sh); + pred[isOdd] += j2 << sh; + } + } else { + nonz[isOdd] = getDataRaw(8); + if (nonz[isOdd] || i > 11) + pred[isOdd] = nonz[isOdd] << 4 | getDataRaw(4); + } + result[idx++] = pred[col & 1]; + } + } + } else + throw RW2_Format; +}; +UTIF.decode._decodeVC5 = function() { + var x2 = [1, 0, 1, 0, 2, 2, 1, 1, 3, 7, 1, 2, 5, 25, 1, 3, 6, 48, 1, 4, 6, 54, 1, 5, 7, 111, 1, 8, 7, 99, 1, 6, 7, 105, 12, 0, 7, 107, 1, 7, 8, 209, 20, 0, 8, 212, 1, 9, 8, 220, 1, 10, 9, 393, 1, 11, 9, 394, 32, 0, 9, 416, 1, 12, 9, 427, 1, 13, 10, 887, 1, 18, 10, 784, 1, 14, 10, 790, 1, 15, 10, 835, 60, 0, 10, 852, 1, 16, 10, 885, 1, 17, 11, 1571, 1, 19, 11, 1668, 1, 20, 11, 1669, 100, 0, 11, 1707, 1, 21, 11, 1772, 1, 22, 12, 3547, 1, 29, 12, 3164, 1, 24, 12, 3166, 1, 25, 12, 3140, 1, 23, 12, 3413, 1, 26, 12, 3537, 1, 27, 12, 3539, 1, 28, 13, 7093, 1, 35, 13, 6283, 1, 30, 13, 6331, 1, 31, 13, 6335, 180, 0, 13, 6824, 1, 32, 13, 7072, 1, 33, 13, 7077, 320, 0, 13, 7076, 1, 34, 14, 12565, 1, 36, 14, 12661, 1, 37, 14, 12669, 1, 38, 14, 13651, 1, 39, 14, 14184, 1, 40, 15, 28295, 1, 46, 15, 28371, 1, 47, 15, 25320, 1, 42, 15, 25336, 1, 43, 15, 25128, 1, 41, 15, 27300, 1, 44, 15, 28293, 1, 45, 16, 50259, 1, 48, 16, 50643, 1, 49, 16, 50675, 1, 50, 16, 56740, 1, 53, 16, 56584, 1, 51, 16, 56588, 1, 52, 17, 113483, 1, 61, 17, 113482, 1, 60, 17, 101285, 1, 55, 17, 101349, 1, 56, 17, 109205, 1, 57, 17, 109207, 1, 58, 17, 100516, 1, 54, 17, 113171, 1, 59, 18, 202568, 1, 62, 18, 202696, 1, 63, 18, 218408, 1, 64, 18, 218412, 1, 65, 18, 226340, 1, 66, 18, 226356, 1, 67, 18, 226358, 1, 68, 19, 402068, 1, 69, 19, 405138, 1, 70, 19, 405394, 1, 71, 19, 436818, 1, 72, 19, 436826, 1, 73, 19, 452714, 1, 75, 19, 452718, 1, 76, 19, 452682, 1, 74, 20, 804138, 1, 77, 20, 810279, 1, 78, 20, 810790, 1, 79, 20, 873638, 1, 80, 20, 873654, 1, 81, 20, 905366, 1, 82, 20, 905430, 1, 83, 20, 905438, 1, 84, 21, 1608278, 1, 85, 21, 1620557, 1, 86, 21, 1621582, 1, 87, 21, 1621583, 1, 88, 21, 1747310, 1, 89, 21, 1810734, 1, 90, 21, 1810735, 1, 91, 21, 1810863, 1, 92, 21, 1810879, 1, 93, 22, 3621725, 1, 99, 22, 3621757, 1, 100, 22, 3241112, 1, 94, 22, 3494556, 1, 95, 22, 3494557, 1, 96, 22, 3494622, 1, 97, 22, 3494623, 1, 98, 23, 6482227, 1, 102, 23, 6433117, 1, 101, 23, 6989117, 1, 103, 23, 6989119, 1, 105, 23, 6989118, 1, 104, 23, 7243449, 1, 106, 23, 7243512, 1, 107, 24, 13978233, 1, 111, 24, 12964453, 1, 109, 24, 12866232, 1, 108, 24, 14486897, 1, 113, 24, 13978232, 1, 110, 24, 14486896, 1, 112, 24, 14487026, 1, 114, 24, 14487027, 1, 115, 25, 25732598, 1, 225, 25, 25732597, 1, 189, 25, 25732596, 1, 188, 25, 25732595, 1, 203, 25, 25732594, 1, 202, 25, 25732593, 1, 197, 25, 25732592, 1, 207, 25, 25732591, 1, 169, 25, 25732590, 1, 223, 25, 25732589, 1, 159, 25, 25732522, 1, 235, 25, 25732579, 1, 152, 25, 25732575, 1, 192, 25, 25732489, 1, 179, 25, 25732573, 1, 201, 25, 25732472, 1, 172, 25, 25732576, 1, 149, 25, 25732488, 1, 178, 25, 25732566, 1, 120, 25, 25732571, 1, 219, 25, 25732577, 1, 150, 25, 25732487, 1, 127, 25, 25732506, 1, 211, 25, 25732548, 1, 125, 25, 25732588, 1, 158, 25, 25732486, 1, 247, 25, 25732467, 1, 238, 25, 25732508, 1, 163, 25, 25732552, 1, 228, 25, 25732603, 1, 183, 25, 25732513, 1, 217, 25, 25732587, 1, 168, 25, 25732520, 1, 122, 25, 25732484, 1, 128, 25, 25732562, 1, 249, 25, 25732505, 1, 187, 25, 25732504, 1, 186, 25, 25732483, 1, 136, 25, 25928905, 1, 181, 25, 25732560, 1, 255, 25, 25732500, 1, 230, 25, 25732482, 1, 135, 25, 25732555, 1, 233, 25, 25732568, 1, 222, 25, 25732583, 1, 145, 25, 25732481, 1, 134, 25, 25732586, 1, 167, 25, 25732521, 1, 248, 25, 25732518, 1, 209, 25, 25732480, 1, 243, 25, 25732512, 1, 216, 25, 25732509, 1, 164, 25, 25732547, 1, 140, 25, 25732479, 1, 157, 25, 25732544, 1, 239, 25, 25732574, 1, 191, 25, 25732564, 1, 251, 25, 25732478, 1, 156, 25, 25732546, 1, 139, 25, 25732498, 1, 242, 25, 25732557, 1, 133, 25, 25732477, 1, 162, 25, 25732515, 1, 213, 25, 25732584, 1, 165, 25, 25732514, 1, 212, 25, 25732476, 1, 227, 25, 25732494, 1, 198, 25, 25732531, 1, 236, 25, 25732530, 1, 234, 25, 25732529, 1, 117, 25, 25732528, 1, 215, 25, 25732527, 1, 124, 25, 25732526, 1, 123, 25, 25732525, 1, 254, 25, 25732524, 1, 253, 25, 25732523, 1, 148, 25, 25732570, 1, 218, 25, 25732580, 1, 146, 25, 25732581, 1, 147, 25, 25732569, 1, 224, 25, 25732533, 1, 143, 25, 25732540, 1, 184, 25, 25732541, 1, 185, 25, 25732585, 1, 166, 25, 25732556, 1, 132, 25, 25732485, 1, 129, 25, 25732563, 1, 250, 25, 25732578, 1, 151, 25, 25732501, 1, 119, 25, 25732502, 1, 193, 25, 25732536, 1, 176, 25, 25732496, 1, 245, 25, 25732553, 1, 229, 25, 25732516, 1, 206, 25, 25732582, 1, 144, 25, 25732517, 1, 208, 25, 25732558, 1, 137, 25, 25732543, 1, 241, 25, 25732466, 1, 237, 25, 25732507, 1, 190, 25, 25732542, 1, 240, 25, 25732551, 1, 131, 25, 25732554, 1, 232, 25, 25732565, 1, 252, 25, 25732475, 1, 171, 25, 25732493, 1, 205, 25, 25732492, 1, 204, 25, 25732491, 1, 118, 25, 25732490, 1, 214, 25, 25928904, 1, 180, 25, 25732549, 1, 126, 25, 25732602, 1, 182, 25, 25732539, 1, 175, 25, 25732545, 1, 141, 25, 25732559, 1, 138, 25, 25732537, 1, 177, 25, 25732534, 1, 153, 25, 25732503, 1, 194, 25, 25732606, 1, 160, 25, 25732567, 1, 121, 25, 25732538, 1, 174, 25, 25732497, 1, 246, 25, 25732550, 1, 130, 25, 25732572, 1, 200, 25, 25732474, 1, 170, 25, 25732511, 1, 221, 25, 25732601, 1, 196, 25, 25732532, 1, 142, 25, 25732519, 1, 210, 25, 25732495, 1, 199, 25, 25732605, 1, 155, 25, 25732535, 1, 154, 25, 25732499, 1, 244, 25, 25732510, 1, 220, 25, 25732600, 1, 195, 25, 25732607, 1, 161, 25, 25732604, 1, 231, 25, 25732473, 1, 173, 25, 25732599, 1, 226, 26, 51465122, 1, 116, 26, 51465123, 0, 1], o, C5, k2, P = [3, 3, 3, 3, 2, 2, 2, 1, 1, 1], V3 = 24576, ar2 = 16384, H = 8192, az = ar2 | H; + function d(t4) { + var E2 = t4[1], h = t4[0][E2 >>> 3] >>> 7 - (E2 & 7) & 1; + t4[1]++; + return h; + } + function ag2(t4, E2) { + if (o == null) { + o = {}; + for (var h = 0;h < x2.length; h += 4) + o[x2[h + 1]] = x2.slice(h, h + 4); + } + var L = d(t4), g3 = o[L]; + while (g3 == null) { + L = L << 1 | d(t4); + g3 = o[L]; + } + var n2 = g3[3]; + if (n2 != 0) + n2 = d(t4) == 0 ? n2 : -n2; + E2[0] = g3[2]; + E2[1] = n2; + } + function m(t4, E2) { + for (var h = 0;h < E2; h++) { + if ((t4 & 1) == 1) + t4++; + t4 = t4 >>> 1; + } + return t4; + } + function A4(t4, E2) { + return t4 >> E2; + } + function O(t4, E2, h, L, g3, n2) { + E2[h] = A4(A4(11 * t4[g3] - 4 * t4[g3 + n2] + t4[g3 + n2 + n2] + 4, 3) + t4[L], 1); + E2[h + n2] = A4(A4(5 * t4[g3] + 4 * t4[g3 + n2] - t4[g3 + n2 + n2] + 4, 3) - t4[L], 1); + } + function J2(t4, E2, h, L, g3, n2) { + var W = t4[g3 - n2] - t4[g3 + n2], j2 = t4[g3], $2 = t4[L]; + E2[h] = A4(A4(W + 4, 3) + j2 + $2, 1); + E2[h + n2] = A4(A4(-W + 4, 3) + j2 - $2, 1); + } + function y3(t4, E2, h, L, g3, n2) { + E2[h] = A4(A4(5 * t4[g3] + 4 * t4[g3 - n2] - t4[g3 - n2 - n2] + 4, 3) + t4[L], 1); + E2[h + n2] = A4(A4(11 * t4[g3] - 4 * t4[g3 - n2] + t4[g3 - n2 - n2] + 4, 3) - t4[L], 1); + } + function q2(t4) { + t4 = t4 < 0 ? 0 : t4 > 4095 ? 4095 : t4; + t4 = k2[t4] >>> 2; + return t4; + } + function av(t4, E2, h, L, g3, n2) { + L = new Uint16Array(L.buffer); + var W = Date.now(), j2 = UTIF._binBE, $2 = E2 + h, r, u3, X, I3, ax, a3, R2, ai, aa, ap2, ah, ae3, aD, al2, i, aE, T3, B3; + E2 += 4; + var a5 = n2[0] == 1; + while (E2 < $2) { + var S = j2.readShort(t4, E2), s = j2.readUshort(t4, E2 + 2); + E2 += 4; + if (S == 12) + r = s; + else if (S == 20) + u3 = s; + else if (S == 21) + X = s; + else if (S == 48) + I3 = s; + else if (S == 53) + ax = s; + else if (S == 35) + a3 = s; + else if (S == 62) + R2 = s; + else if (S == 101) + ai = s; + else if (S == 109) + aa = s; + else if (S == 84) + ap2 = s; + else if (S == 106) + ah = s; + else if (S == 107) + ae3 = s; + else if (S == 108) + aD = s; + else if (S == 102) + al2 = s; + else if (S == 104) + i = s; + else if (S == 105) + aE = s; + else { + var F = S < 0 ? -S : S, D = F & 65280, _9 = 0; + if (F & az) { + if (F & H) { + _9 = s & 65535; + _9 += (F & 255) << 16; + } else { + _9 = s & 65535; + } + } + if ((F & V3) == V3) { + if (T3 == null) { + T3 = []; + for (var M = 0;M < 4; M++) + T3[M] = new Int16Array((u3 >>> 1) * (X >>> 1)); + B3 = new Int16Array((u3 >>> 1) * (X >>> 1)); + C5 = new Int16Array(1024); + for (var M = 0;M < 1024; M++) { + var aG = M - 512, p = Math.abs(aG), r = Math.floor(768 * p * p * p / (255 * 255 * 255)) + p; + C5[M] = Math.sign(aG) * r; + } + k2 = new Uint16Array(4096); + var aA = (1 << 16) - 1; + for (var M = 0;M < 4096; M++) { + var at = M, a1 = aA * (Math.pow(113, at / 4095) - 1) / 112; + k2[M] = Math.min(a1, aA); + } + } + var w = T3[R2], v = m(u3, 1 + P[I3]), N = m(X, 1 + P[I3]); + if (I3 == 0) { + for (var b = 0;b < N; b++) + for (var G2 = 0;G2 < v; G2++) { + var c = E2 + (b * v + G2) * 2; + w[b * (u3 >>> 1) + G2] = t4[c] << 8 | t4[c + 1]; + } + } else { + var a7 = [t4, E2 * 8], a4 = [], ay = 0, aw = v * N, f = [0, 0], Q3 = 0, s = 0; + while (ay < aw) { + ag2(a7, f); + Q3 = f[0]; + s = f[1]; + while (Q3 > 0) { + a4[ay++] = s; + Q3--; + } + } + var l2 = (I3 - 1) % 3, aF = l2 != 1 ? v : 0, a2 = l2 != 0 ? N : 0; + for (var b = 0;b < N; b++) { + var af = (b + a2) * (u3 >>> 1) + aF, au = b * v; + for (var G2 = 0;G2 < v; G2++) + w[af + G2] = C5[a4[au + G2] + 512] * ax; + } + if (l2 == 2) { + var i = u3 >>> 1, an = v * 2, a9 = N * 2; + for (var b = 0;b < N; b++) { + for (var G2 = 0;G2 < an; G2++) { + var M = b * 2 * i + G2, a = b * i + G2, e = N * i + a; + if (b == 0) + O(w, B3, M, e, a, i); + else if (b == N - 1) + y3(w, B3, M, e, a, i); + else + J2(w, B3, M, e, a, i); + } + } + var Z3 = w; + w = B3; + B3 = Z3; + for (var b = 0;b < a9; b++) { + for (var G2 = 0;G2 < v; G2++) { + var M = b * i + 2 * G2, a = b * i + G2, e = v + a; + if (G2 == 0) + O(w, B3, M, e, a, 1); + else if (G2 == v - 1) + y3(w, B3, M, e, a, 1); + else + J2(w, B3, M, e, a, 1); + } + } + var Z3 = w; + w = B3; + B3 = Z3; + var aC = [], aB = 2 - ~~((I3 - 1) / 3); + for (var K = 0;K < 3; K++) + aC[K] = aa >> 14 - K * 2 & 3; + var a6 = aC[aB]; + if (a6 != 0) + for (var b = 0;b < a9; b++) + for (var G2 = 0;G2 < an; G2++) { + var M = b * i + G2; + w[M] = w[M] << a6; + } + } + } + if (I3 == 9 && R2 == 3) { + var a8 = T3[0], ab = T3[1], aq = T3[2], as = T3[3]; + for (var b = 0;b < X; b += 2) + for (var G2 = 0;G2 < u3; G2 += 2) { + var U = b * u3 + G2, c = (b >>> 1) * (u3 >>> 1) + (G2 >>> 1), z2 = a8[c], ao = ab[c] - 2048, ak = aq[c] - 2048, ad = as[c] - 2048, aj = (ao << 1) + z2, a0 = (ak << 1) + z2, aH = z2 + ad, am = z2 - ad; + if (a5) { + L[U] = q2(aH); + L[U + 1] = q2(a0); + L[U + u3] = q2(aj); + L[U + u3 + 1] = q2(am); + } else { + L[U] = q2(aj); + L[U + 1] = q2(aH); + L[U + u3] = q2(am); + L[U + u3 + 1] = q2(a0); + } + } + } + E2 += _9 * 4; + } else if (F == 16388) { + E2 += _9 * 4; + } else if (D == 8192 || D == 8448 || D == 9216) { + } else + throw F.toString(16); + } + } + console.log(Date.now() - W); + } + return av; +}(); +UTIF.decode._decodeLogLuv32 = function(img, data2, off, len, tgt, toff) { + var w = img.width, qw = w * 4; + var io = 0, out = new Uint8Array(qw); + while (io < len) { + var oo = 0; + while (oo < qw) { + var c = data2[off + io]; + io++; + if (c < 128) { + for (var j2 = 0;j2 < c; j2++) + out[oo + j2] = data2[off + io + j2]; + oo += c; + io += c; + } else { + c = c - 126; + for (var j2 = 0;j2 < c; j2++) + out[oo + j2] = data2[off + io]; + oo += c; + io++; + } + } + for (var x2 = 0;x2 < w; x2++) { + tgt[toff + 0] = out[x2]; + tgt[toff + 1] = out[x2 + w]; + tgt[toff + 2] = out[x2 + w * 2]; + tgt[toff + 4] = out[x2 + w * 3]; + toff += 6; + } + } +}; +UTIF.decode._ljpeg_diff = function(data2, prm, huff) { + var getbithuff = UTIF.decode._getbithuff; + var len, diff; + len = getbithuff(data2, prm, huff[0], huff); + diff = getbithuff(data2, prm, len, 0); + if ((diff & 1 << len - 1) == 0) + diff -= (1 << len) - 1; + return diff; +}; +UTIF.decode._decodeARW = function(img, inp, off, src_length, tgt, toff) { + var raw_width = img["t256"][0], height2 = img["t257"][0], tiff_bps = img["t258"][0]; + var bin = img.isLE ? UTIF._binLE : UTIF._binBE; + var arw2 = raw_width * height2 == src_length || raw_width * height2 * 1.5 == src_length; + if (!arw2) { + height2 += 8; + var prm = [off, 0, 0, 0]; + var huff = new Uint16Array(32770); + var tab = [ + 3857, + 3856, + 3599, + 3342, + 3085, + 2828, + 2571, + 2314, + 2057, + 1800, + 1543, + 1286, + 1029, + 772, + 771, + 768, + 514, + 513 + ]; + var i, c, n2, col, row, sum2 = 0; + var ljpeg_diff = UTIF.decode._ljpeg_diff; + huff[0] = 15; + for (n2 = i = 0;i < 18; i++) { + var lim = 32768 >>> (tab[i] >>> 8); + for (var c = 0;c < lim; c++) + huff[++n2] = tab[i]; + } + for (col = raw_width;col--; ) + for (row = 0;row < height2 + 1; row += 2) { + if (row == height2) + row = 1; + sum2 += ljpeg_diff(inp, prm, huff); + if (row < height2) { + var clr = sum2 & 4095; + UTIF.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps); + } + } + return; + } + if (raw_width * height2 * 1.5 == src_length) { + for (var i = 0;i < src_length; i += 3) { + var b0 = inp[off + i + 0], b1 = inp[off + i + 1], b22 = inp[off + i + 2]; + tgt[toff + i] = b1 << 4 | b0 >>> 4; + tgt[toff + i + 1] = b0 << 4 | b22 >>> 4; + tgt[toff + i + 2] = b22 << 4 | b1 >>> 4; + } + return; + } + var pix = new Uint16Array(16); + var row, col, val2, max, min, imax, imin, sh, bit, i, dp; + var data2 = new Uint8Array(raw_width + 1); + for (row = 0;row < height2; row++) { + for (var j2 = 0;j2 < raw_width; j2++) + data2[j2] = inp[off++]; + for (dp = 0, col = 0;col < raw_width - 30; dp += 16) { + max = 2047 & (val2 = bin.readUint(data2, dp)); + min = 2047 & val2 >>> 11; + imax = 15 & val2 >>> 22; + imin = 15 & val2 >>> 26; + for (sh = 0;sh < 4 && 128 << sh <= max - min; sh++) + ; + for (bit = 30, i = 0;i < 16; i++) + if (i == imax) + pix[i] = max; + else if (i == imin) + pix[i] = min; + else { + pix[i] = ((bin.readUshort(data2, dp + (bit >> 3)) >>> (bit & 7) & 127) << sh) + min; + if (pix[i] > 2047) + pix[i] = 2047; + bit += 7; + } + for (i = 0;i < 16; i++, col += 2) { + var clr = pix[i] << 1; + UTIF.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps); + } + col -= col & 1 ? 1 : 31; + } + } +}; +UTIF.decode._decodeNikon = function(img, imgs, data2, off, src_length, tgt, toff) { + var nikon_tree = [ + [ + 0, + 0, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 5, + 4, + 3, + 6, + 2, + 7, + 1, + 0, + 8, + 9, + 11, + 10, + 12 + ], + [ + 0, + 0, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 57, + 90, + 56, + 39, + 22, + 5, + 4, + 3, + 2, + 1, + 0, + 11, + 12, + 12 + ], + [ + 0, + 0, + 1, + 4, + 2, + 3, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 5, + 4, + 6, + 3, + 7, + 2, + 8, + 1, + 9, + 0, + 10, + 11, + 12 + ], + [ + 0, + 0, + 1, + 4, + 3, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 5, + 6, + 4, + 7, + 8, + 3, + 9, + 2, + 1, + 0, + 10, + 11, + 12, + 13, + 14 + ], + [ + 0, + 0, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 8, + 92, + 75, + 58, + 41, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + 0, + 13, + 14 + ], + [ + 0, + 0, + 1, + 4, + 2, + 2, + 3, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 6, + 8, + 5, + 9, + 4, + 10, + 3, + 11, + 12, + 2, + 0, + 1, + 13, + 14 + ] + ]; + var raw_width = img["t256"][0], height2 = img["t257"][0], tiff_bps = img["t258"][0]; + var tree = 0, split = 0; + var make_decoder = UTIF.decode._make_decoder; + var getbithuff = UTIF.decode._getbithuff; + var mn = imgs[0].exifIFD.makerNote, md = mn["t150"] ? mn["t150"] : mn["t140"], mdo = 0; + var ver0 = md[mdo++], ver1 = md[mdo++]; + if (ver0 == 73 || ver1 == 88) + mdo += 2110; + if (ver0 == 70) + tree = 2; + if (tiff_bps == 14) + tree += 3; + var vpred = [[0, 0], [0, 0]], bin = img.isLE ? UTIF._binLE : UTIF._binBE; + for (var i = 0;i < 2; i++) + for (var j2 = 0;j2 < 2; j2++) { + vpred[i][j2] = bin.readShort(md, mdo); + mdo += 2; + } + var max = 1 << tiff_bps & 32767, step = 0; + var csize = bin.readShort(md, mdo); + mdo += 2; + if (csize > 1) + step = Math.floor(max / (csize - 1)); + if (ver0 == 68 && ver1 == 32 && step > 0) + split = bin.readShort(md, 562); + var i; + var row, col; + var len, shl, diff; + var min_v = 0; + var hpred = [0, 0]; + var huff = make_decoder(nikon_tree[tree]); + var prm = [off, 0, 0, 0]; + for (min_v = row = 0;row < height2; row++) { + if (split && row == split) { + huff = make_decoder(nikon_tree[tree + 1]); + } + for (col = 0;col < raw_width; col++) { + i = getbithuff(data2, prm, huff[0], huff); + len = i & 15; + shl = i >>> 4; + diff = (getbithuff(data2, prm, len - shl, 0) << 1) + 1 << shl >>> 1; + if ((diff & 1 << len - 1) == 0) + diff -= (1 << len) - (shl == 0 ? 1 : 0); + if (col < 2) + hpred[col] = vpred[row & 1][col] += diff; + else + hpred[col & 1] += diff; + var clr = Math.min(Math.max(hpred[col & 1], 0), (1 << tiff_bps) - 1); + var bti = (row * raw_width + col) * tiff_bps; + UTIF.decode._putsF(tgt, bti, clr << 16 - tiff_bps); + } + } +}; +UTIF.decode._putsF = function(dt, pos, val2) { + val2 = val2 << 8 - (pos & 7); + var o = pos >>> 3; + dt[o] |= val2 >>> 16; + dt[o + 1] |= val2 >>> 8; + dt[o + 2] |= val2; +}; +UTIF.decode._getbithuff = function(data2, prm, nbits, huff) { + var zero_after_ff = 0; + var get_byte = UTIF.decode._get_byte; + var c; + var off = prm[0], bitbuf = prm[1], vbits = prm[2], reset = prm[3]; + if (nbits == 0 || vbits < 0) + return 0; + while (!reset && vbits < nbits && (c = data2[off++]) != -1 && !(reset = zero_after_ff && c == 255 && data2[off++])) { + bitbuf = (bitbuf << 8) + c; + vbits += 8; + } + c = bitbuf << 32 - vbits >>> 32 - nbits; + if (huff) { + vbits -= huff[c + 1] >>> 8; + c = huff[c + 1] & 255; + } else + vbits -= nbits; + if (vbits < 0) + throw "e"; + prm[0] = off; + prm[1] = bitbuf; + prm[2] = vbits; + prm[3] = reset; + return c; +}; +UTIF.decode._make_decoder = function(source) { + var max, len, h, i, j2; + var huff = []; + for (max = 16;max != 0 && !source[max]; max--) + ; + var si = 17; + huff[0] = max; + for (h = len = 1;len <= max; len++) + for (i = 0;i < source[len]; i++, ++si) + for (j2 = 0;j2 < 1 << max - len; j2++) + if (h <= 1 << max) + huff[h++] = len << 8 | source[si]; + return huff; +}; +UTIF.decode._decodeNewJPEG = function(img, data2, off, len, tgt, toff) { + len = Math.min(len, data2.length - off); + var tables = img["t347"], tlen = tables ? tables.length : 0, buff = new Uint8Array(tlen + len); + if (tables) { + var SOI = 216, EOI2 = 217, boff = 0; + for (var i = 0;i < tlen - 1; i++) { + if (tables[i] == 255 && tables[i + 1] == EOI2) + break; + buff[boff++] = tables[i]; + } + var byte1 = data2[off], byte2 = data2[off + 1]; + if (byte1 != 255 || byte2 != SOI) { + buff[boff++] = byte1; + buff[boff++] = byte2; + } + for (var i = 2;i < len; i++) + buff[boff++] = data2[off + i]; + } else + for (var i = 0;i < len; i++) + buff[i] = data2[off + i]; + if (img["t262"][0] == 32803 || img["t259"][0] == 7 && img["t262"][0] == 34892) { + var bps = img["t258"][0]; + var out = UTIF.LosslessJpegDecode(buff), olen = out.length; + if (false) { + } else if (bps == 16) { + if (img.isLE) + for (var i = 0;i < olen; i++) { + tgt[toff + (i << 1)] = out[i] & 255; + tgt[toff + (i << 1) + 1] = out[i] >>> 8; + } + else + for (var i = 0;i < olen; i++) { + tgt[toff + (i << 1)] = out[i] >>> 8; + tgt[toff + (i << 1) + 1] = out[i] & 255; + } + } else if (bps == 14 || bps == 12 || bps == 10) { + var rst = 16 - bps; + for (var i = 0;i < olen; i++) + UTIF.decode._putsF(tgt, i * bps, out[i] << rst); + } else if (bps == 8) { + for (var i = 0;i < olen; i++) + tgt[toff + i] = out[i]; + } else + throw new Error("unsupported bit depth " + bps); + } else { + var parser = new UTIF.JpegDecoder; + parser.parse(buff); + var decoded = parser.getData({ width: parser.width, height: parser.height, forceRGB: true, isSourcePDF: false }); + for (var i = 0;i < decoded.length; i++) + tgt[toff + i] = decoded[i]; + } + if (img["t262"][0] == 6) + img["t262"][0] = 2; +}; +UTIF.decode._decodeOldJPEGInit = function(img, data2, off, len) { + var SOI = 216, EOI2 = 217, DQT = 219, DHT = 196, DRI = 221, SOF0 = 192, SOS2 = 218; + var joff = 0, soff = 0, tables, sosMarker2, isTiled = false, i, j2, k2; + var jpgIchgFmt = img["t513"], jifoff = jpgIchgFmt ? jpgIchgFmt[0] : 0; + var jpgIchgFmtLen = img["t514"], jiflen = jpgIchgFmtLen ? jpgIchgFmtLen[0] : 0; + var soffTag = img["t324"] || img["t273"] || jpgIchgFmt; + var ycbcrss = img["t530"], ssx = 0, ssy = 0; + var spp = img["t277"] ? img["t277"][0] : 1; + var jpgresint = img["t515"]; + if (soffTag) { + soff = soffTag[0]; + isTiled = soffTag.length > 1; + } + if (!isTiled) { + if (data2[off] == 255 && data2[off + 1] == SOI) + return { jpegOffset: off }; + if (jpgIchgFmt != null) { + if (data2[off + jifoff] == 255 && data2[off + jifoff + 1] == SOI) + joff = off + jifoff; + else + log("JPEGInterchangeFormat does not point to SOI"); + if (jpgIchgFmtLen == null) + log("JPEGInterchangeFormatLength field is missing"); + else if (jifoff >= soff || jifoff + jiflen <= soff) + log("JPEGInterchangeFormatLength field value is invalid"); + if (joff != null) + return { jpegOffset: joff }; + } + } + if (ycbcrss != null) { + ssx = ycbcrss[0]; + ssy = ycbcrss[1]; + } + if (jpgIchgFmt != null) { + if (jpgIchgFmtLen != null) + if (jiflen >= 2 && jifoff + jiflen <= soff) { + if (data2[off + jifoff + jiflen - 2] == 255 && data2[off + jifoff + jiflen - 1] == SOI) + tables = new Uint8Array(jiflen - 2); + else + tables = new Uint8Array(jiflen); + for (i = 0;i < tables.length; i++) + tables[i] = data2[off + jifoff + i]; + log("Incorrect JPEG interchange format: using JPEGInterchangeFormat offset to derive tables"); + } else + log("JPEGInterchangeFormat+JPEGInterchangeFormatLength > offset to first strip or tile"); + } + if (tables == null) { + var ooff = 0, out = []; + out[ooff++] = 255; + out[ooff++] = SOI; + var qtables = img["t519"]; + if (qtables == null) + throw new Error("JPEGQTables tag is missing"); + for (i = 0;i < qtables.length; i++) { + out[ooff++] = 255; + out[ooff++] = DQT; + out[ooff++] = 0; + out[ooff++] = 67; + out[ooff++] = i; + for (j2 = 0;j2 < 64; j2++) + out[ooff++] = data2[off + qtables[i] + j2]; + } + for (k2 = 0;k2 < 2; k2++) { + var htables = img[k2 == 0 ? "t520" : "t521"]; + if (htables == null) + throw new Error((k2 == 0 ? "JPEGDCTables" : "JPEGACTables") + " tag is missing"); + for (i = 0;i < htables.length; i++) { + out[ooff++] = 255; + out[ooff++] = DHT; + var nc = 19; + for (j2 = 0;j2 < 16; j2++) + nc += data2[off + htables[i] + j2]; + out[ooff++] = nc >>> 8; + out[ooff++] = nc & 255; + out[ooff++] = i | k2 << 4; + for (j2 = 0;j2 < 16; j2++) + out[ooff++] = data2[off + htables[i] + j2]; + for (j2 = 0;j2 < nc; j2++) + out[ooff++] = data2[off + htables[i] + 16 + j2]; + } + } + out[ooff++] = 255; + out[ooff++] = SOF0; + out[ooff++] = 0; + out[ooff++] = 8 + 3 * spp; + out[ooff++] = 8; + out[ooff++] = img.height >>> 8 & 255; + out[ooff++] = img.height & 255; + out[ooff++] = img.width >>> 8 & 255; + out[ooff++] = img.width & 255; + out[ooff++] = spp; + if (spp == 1) { + out[ooff++] = 1; + out[ooff++] = 17; + out[ooff++] = 0; + } else + for (i = 0;i < 3; i++) { + out[ooff++] = i + 1; + out[ooff++] = i != 0 ? 17 : (ssx & 15) << 4 | ssy & 15; + out[ooff++] = i; + } + if (jpgresint != null && jpgresint[0] != 0) { + out[ooff++] = 255; + out[ooff++] = DRI; + out[ooff++] = 0; + out[ooff++] = 4; + out[ooff++] = jpgresint[0] >>> 8 & 255; + out[ooff++] = jpgresint[0] & 255; + } + tables = new Uint8Array(out); + } + var sofpos = -1; + i = 0; + while (i < tables.length - 1) { + if (tables[i] == 255 && tables[i + 1] == SOF0) { + sofpos = i; + break; + } + i++; + } + if (sofpos == -1) { + var tmptab = new Uint8Array(tables.length + 10 + 3 * spp); + tmptab.set(tables); + var tmpoff = tables.length; + sofpos = tables.length; + tables = tmptab; + tables[tmpoff++] = 255; + tables[tmpoff++] = SOF0; + tables[tmpoff++] = 0; + tables[tmpoff++] = 8 + 3 * spp; + tables[tmpoff++] = 8; + tables[tmpoff++] = img.height >>> 8 & 255; + tables[tmpoff++] = img.height & 255; + tables[tmpoff++] = img.width >>> 8 & 255; + tables[tmpoff++] = img.width & 255; + tables[tmpoff++] = spp; + if (spp == 1) { + tables[tmpoff++] = 1; + tables[tmpoff++] = 17; + tables[tmpoff++] = 0; + } else + for (i = 0;i < 3; i++) { + tables[tmpoff++] = i + 1; + tables[tmpoff++] = i != 0 ? 17 : (ssx & 15) << 4 | ssy & 15; + tables[tmpoff++] = i; + } + } + if (data2[soff] == 255 && data2[soff + 1] == SOS2) { + var soslen = data2[soff + 2] << 8 | data2[soff + 3]; + sosMarker2 = new Uint8Array(soslen + 2); + sosMarker2[0] = data2[soff]; + sosMarker2[1] = data2[soff + 1]; + sosMarker2[2] = data2[soff + 2]; + sosMarker2[3] = data2[soff + 3]; + for (i = 0;i < soslen - 2; i++) + sosMarker2[i + 4] = data2[soff + i + 4]; + } else { + sosMarker2 = new Uint8Array(2 + 6 + 2 * spp); + var sosoff = 0; + sosMarker2[sosoff++] = 255; + sosMarker2[sosoff++] = SOS2; + sosMarker2[sosoff++] = 0; + sosMarker2[sosoff++] = 6 + 2 * spp; + sosMarker2[sosoff++] = spp; + if (spp == 1) { + sosMarker2[sosoff++] = 1; + sosMarker2[sosoff++] = 0; + } else + for (i = 0;i < 3; i++) { + sosMarker2[sosoff++] = i + 1; + sosMarker2[sosoff++] = i << 4 | i; + } + sosMarker2[sosoff++] = 0; + sosMarker2[sosoff++] = 63; + sosMarker2[sosoff++] = 0; + } + return { jpegOffset: off, tables, sosMarker: sosMarker2, sofPosition: sofpos }; +}; +UTIF.decode._decodeOldJPEG = function(img, data2, off, len, tgt, toff) { + var i, dlen, tlen, buff, buffoff; + var jpegData = UTIF.decode._decodeOldJPEGInit(img, data2, off, len); + if (jpegData.jpegOffset != null) { + dlen = off + len - jpegData.jpegOffset; + buff = new Uint8Array(dlen); + for (i = 0;i < dlen; i++) + buff[i] = data2[jpegData.jpegOffset + i]; + } else { + tlen = jpegData.tables.length; + buff = new Uint8Array(tlen + jpegData.sosMarker.length + len + 2); + buff.set(jpegData.tables); + buffoff = tlen; + buff[jpegData.sofPosition + 5] = img.height >>> 8 & 255; + buff[jpegData.sofPosition + 6] = img.height & 255; + buff[jpegData.sofPosition + 7] = img.width >>> 8 & 255; + buff[jpegData.sofPosition + 8] = img.width & 255; + if (data2[off] != 255 || data2[off + 1] != SOS) { + buff.set(jpegData.sosMarker, buffoff); + buffoff += sosMarker.length; + } + for (i = 0;i < len; i++) + buff[buffoff++] = data2[off + i]; + buff[buffoff++] = 255; + buff[buffoff++] = EOI; + } + var parser = new UTIF.JpegDecoder; + parser.parse(buff); + var decoded = parser.getData({ width: parser.width, height: parser.height, forceRGB: true, isSourcePDF: false }); + for (var i = 0;i < decoded.length; i++) + tgt[toff + i] = decoded[i]; + if (img["t262"] && img["t262"][0] == 6) + img["t262"][0] = 2; +}; +UTIF.decode._decodePackBits = function(data2, off, len, tgt, toff) { + var sa = new Int8Array(data2.buffer), ta = new Int8Array(tgt.buffer), lim = off + len; + while (off < lim) { + var n2 = sa[off]; + off++; + if (n2 >= 0 && n2 < 128) + for (var i = 0;i < n2 + 1; i++) { + ta[toff] = sa[off]; + toff++; + off++; + } + if (n2 >= -127 && n2 < 0) { + for (var i = 0;i < -n2 + 1; i++) { + ta[toff] = sa[off]; + toff++; + } + off++; + } + } + return toff; +}; +UTIF.decode._decodeThunder = function(data2, off, len, tgt, toff) { + var d2 = [0, 1, 0, -1], d32 = [0, 1, 2, 3, 0, -3, -2, -1]; + var lim = off + len, qoff = toff * 2, px2 = 0; + while (off < lim) { + var b = data2[off], msk = b >>> 6, n2 = b & 63; + off++; + if (msk == 3) { + px2 = n2 & 15; + tgt[qoff >>> 1] |= px2 << 4 * (1 - qoff & 1); + qoff++; + } + if (msk == 0) + for (var i = 0;i < n2; i++) { + tgt[qoff >>> 1] |= px2 << 4 * (1 - qoff & 1); + qoff++; + } + if (msk == 2) + for (var i = 0;i < 2; i++) { + var d = n2 >>> 3 * (1 - i) & 7; + if (d != 4) { + px2 += d32[d]; + tgt[qoff >>> 1] |= px2 << 4 * (1 - qoff & 1); + qoff++; + } + } + if (msk == 1) + for (var i = 0;i < 3; i++) { + var d = n2 >>> 2 * (2 - i) & 3; + if (d != 2) { + px2 += d2[d]; + tgt[qoff >>> 1] |= px2 << 4 * (1 - qoff & 1); + qoff++; + } + } + } +}; +UTIF.decode._dmap = { "1": 0, "011": 1, "000011": 2, "0000011": 3, "010": -1, "000010": -2, "0000010": -3 }; +UTIF.decode._lens = function() { + var addKeys = function(lens, arr, i0, inc) { + for (var i = 0;i < arr.length; i++) + lens[arr[i]] = i0 + i * inc; + }; + var termW = "00110101,000111,0111,1000,1011,1100,1110,1111,10011,10100,00111,01000,001000,000011,110100,110101," + "101010,101011,0100111,0001100,0001000,0010111,0000011,0000100,0101000,0101011,0010011,0100100,0011000,00000010,00000011,00011010," + "00011011,00010010,00010011,00010100,00010101,00010110,00010111,00101000,00101001,00101010,00101011,00101100,00101101,00000100,00000101,00001010," + "00001011,01010010,01010011,01010100,01010101,00100100,00100101,01011000,01011001,01011010,01011011,01001010,01001011,00110010,00110011,00110100"; + var termB = "0000110111,010,11,10,011,0011,0010,00011,000101,000100,0000100,0000101,0000111,00000100,00000111,000011000," + "0000010111,0000011000,0000001000,00001100111,00001101000,00001101100,00000110111,00000101000,00000010111,00000011000,000011001010,000011001011,000011001100,000011001101,000001101000,000001101001," + "000001101010,000001101011,000011010010,000011010011,000011010100,000011010101,000011010110,000011010111,000001101100,000001101101,000011011010,000011011011,000001010100,000001010101,000001010110,000001010111," + "000001100100,000001100101,000001010010,000001010011,000000100100,000000110111,000000111000,000000100111,000000101000,000001011000,000001011001,000000101011,000000101100,000001011010,000001100110,000001100111"; + var makeW = "11011,10010,010111,0110111,00110110,00110111,01100100,01100101,01101000,01100111,011001100,011001101,011010010,011010011,011010100,011010101,011010110," + "011010111,011011000,011011001,011011010,011011011,010011000,010011001,010011010,011000,010011011"; + var makeB = "0000001111,000011001000,000011001001,000001011011,000000110011,000000110100,000000110101,0000001101100,0000001101101,0000001001010,0000001001011,0000001001100," + "0000001001101,0000001110010,0000001110011,0000001110100,0000001110101,0000001110110,0000001110111,0000001010010,0000001010011,0000001010100,0000001010101,0000001011010," + "0000001011011,0000001100100,0000001100101"; + var makeA = "00000001000,00000001100,00000001101,000000010010,000000010011,000000010100,000000010101,000000010110,000000010111,000000011100,000000011101,000000011110,000000011111"; + termW = termW.split(","); + termB = termB.split(","); + makeW = makeW.split(","); + makeB = makeB.split(","); + makeA = makeA.split(","); + var lensW = {}, lensB = {}; + addKeys(lensW, termW, 0, 1); + addKeys(lensW, makeW, 64, 64); + addKeys(lensW, makeA, 1792, 64); + addKeys(lensB, termB, 0, 1); + addKeys(lensB, makeB, 64, 64); + addKeys(lensB, makeA, 1792, 64); + return [lensW, lensB]; +}(); +UTIF.decode._decodeG4 = function(data2, off, slen, tgt, toff, w, fo) { + var U = UTIF.decode, boff = off << 3, len = 0, wrd = ""; + var line = [], pline = []; + for (var i = 0;i < w; i++) + pline.push(0); + pline = U._makeDiff(pline); + var a0 = 0, a1 = 0, a2 = 0, b1 = 0, b22 = 0, clr = 0; + var y3 = 0, mode = "", toRead = 0; + var bipl = Math.ceil(w / 8) * 8; + while (boff >>> 3 < off + slen) { + b1 = U._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b22 = U._findDiff(pline, b1, clr); + var bit = 0; + if (fo == 1) + bit = data2[boff >>> 3] >>> 7 - (boff & 7) & 1; + if (fo == 2) + bit = data2[boff >>> 3] >>> (boff & 7) & 1; + boff++; + wrd += bit; + if (mode == "H") { + if (U._lens[clr][wrd] != null) { + var dl3 = U._lens[clr][wrd]; + wrd = ""; + len += dl3; + if (dl3 < 64) { + U._addNtimes(line, len, clr); + a0 += len; + clr = 1 - clr; + len = 0; + toRead--; + if (toRead == 0) + mode = ""; + } + } + } else { + if (wrd == "0001") { + wrd = ""; + U._addNtimes(line, b22 - a0, clr); + a0 = b22; + } + if (wrd == "001") { + wrd = ""; + mode = "H"; + toRead = 2; + } + if (U._dmap[wrd] != null) { + a1 = b1 + U._dmap[wrd]; + U._addNtimes(line, a1 - a0, clr); + a0 = a1; + wrd = ""; + clr = 1 - clr; + } + } + if (line.length == w && mode == "") { + U._writeBits(line, tgt, toff * 8 + y3 * bipl); + clr = 0; + y3++; + a0 = 0; + pline = U._makeDiff(line); + line = []; + } + } +}; +UTIF.decode._findDiff = function(line, x2, clr) { + for (var i = 0;i < line.length; i += 2) + if (line[i] >= x2 && line[i + 1] == clr) + return line[i]; +}; +UTIF.decode._makeDiff = function(line) { + var out = []; + if (line[0] == 1) + out.push(0, 1); + for (var i = 1;i < line.length; i++) + if (line[i - 1] != line[i]) + out.push(i, line[i]); + out.push(line.length, 0, line.length, 1); + return out; +}; +UTIF.decode._decodeG2 = function(data2, off, slen, tgt, toff, w, fo) { + var U = UTIF.decode, boff = off << 3, len = 0, wrd = ""; + var line = []; + var clr = 0; + var y3 = 0; + var bipl = Math.ceil(w / 8) * 8; + while (boff >>> 3 < off + slen) { + var bit = 0; + if (fo == 1) + bit = data2[boff >>> 3] >>> 7 - (boff & 7) & 1; + if (fo == 2) + bit = data2[boff >>> 3] >>> (boff & 7) & 1; + boff++; + wrd += bit; + len = U._lens[clr][wrd]; + if (len != null) { + U._addNtimes(line, len, clr); + wrd = ""; + if (len < 64) + clr = 1 - clr; + if (line.length == w) { + U._writeBits(line, tgt, toff * 8 + y3 * bipl); + line = []; + y3++; + clr = 0; + if ((boff & 7) != 0) + boff += 8 - (boff & 7); + if (len >= 64) + boff += 8; + } + } + } +}; +UTIF.decode._decodeG3 = function(data2, off, slen, tgt, toff, w, fo, twoDim) { + var U = UTIF.decode, boff = off << 3, len = 0, wrd = ""; + var line = [], pline = []; + for (var i = 0;i < w; i++) + line.push(0); + var a0 = 0, a1 = 0, a2 = 0, b1 = 0, b22 = 0, clr = 0; + var y3 = -1, mode = "", toRead = 0, is1D = true; + var bipl = Math.ceil(w / 8) * 8; + while (boff >>> 3 < off + slen) { + b1 = U._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b22 = U._findDiff(pline, b1, clr); + var bit = 0; + if (fo == 1) + bit = data2[boff >>> 3] >>> 7 - (boff & 7) & 1; + if (fo == 2) + bit = data2[boff >>> 3] >>> (boff & 7) & 1; + boff++; + wrd += bit; + if (is1D) { + if (U._lens[clr][wrd] != null) { + var dl3 = U._lens[clr][wrd]; + wrd = ""; + len += dl3; + if (dl3 < 64) { + U._addNtimes(line, len, clr); + clr = 1 - clr; + len = 0; + } + } + } else { + if (mode == "H") { + if (U._lens[clr][wrd] != null) { + var dl3 = U._lens[clr][wrd]; + wrd = ""; + len += dl3; + if (dl3 < 64) { + U._addNtimes(line, len, clr); + a0 += len; + clr = 1 - clr; + len = 0; + toRead--; + if (toRead == 0) + mode = ""; + } + } + } else { + if (wrd == "0001") { + wrd = ""; + U._addNtimes(line, b22 - a0, clr); + a0 = b22; + } + if (wrd == "001") { + wrd = ""; + mode = "H"; + toRead = 2; + } + if (U._dmap[wrd] != null) { + a1 = b1 + U._dmap[wrd]; + U._addNtimes(line, a1 - a0, clr); + a0 = a1; + wrd = ""; + clr = 1 - clr; + } + } + } + if (wrd.endsWith("000000000001")) { + if (y3 >= 0) + U._writeBits(line, tgt, toff * 8 + y3 * bipl); + if (twoDim) { + if (fo == 1) + is1D = (data2[boff >>> 3] >>> 7 - (boff & 7) & 1) == 1; + if (fo == 2) + is1D = (data2[boff >>> 3] >>> (boff & 7) & 1) == 1; + boff++; + } + wrd = ""; + clr = 0; + y3++; + a0 = 0; + pline = U._makeDiff(line); + line = []; + } + } + if (line.length == w) + U._writeBits(line, tgt, toff * 8 + y3 * bipl); +}; +UTIF.decode._addNtimes = function(arr, n2, val2) { + for (var i = 0;i < n2; i++) + arr.push(val2); +}; +UTIF.decode._writeBits = function(bits, tgt, boff) { + for (var i = 0;i < bits.length; i++) + tgt[boff + i >>> 3] |= bits[i] << 7 - (boff + i & 7); +}; +UTIF.decode._decodeLZW = UTIF.decode._decodeLZW = function() { + var e, U, Z3, u3, K = 0, V3 = 0, g3 = 0, N = 0, O = function() { + var S = e >>> 3, A4 = U[S] << 16 | U[S + 1] << 8 | U[S + 2], j2 = A4 >>> 24 - (e & 7) - V3 & (1 << V3) - 1; + e += V3; + return j2; + }, h = new Uint32Array(4096 * 4), w = 0, m = function(S) { + if (S == w) + return; + w = S; + g3 = 1 << S; + N = g3 + 1; + for (var A4 = 0;A4 < N + 1; A4++) { + h[4 * A4] = h[4 * A4 + 3] = A4; + h[4 * A4 + 1] = 65535; + h[4 * A4 + 2] = 1; + } + }, i = function(S) { + V3 = S + 1; + K = N + 1; + }, D = function(S) { + var A4 = S << 2, j2 = h[A4 + 2], a = u3 + j2 - 1; + while (A4 != 65535) { + Z3[a--] = h[A4]; + A4 = h[A4 + 1]; + } + u3 += j2; + }, L = function(S, A4) { + var j2 = K << 2, a = S << 2; + h[j2] = h[(A4 << 2) + 3]; + h[j2 + 1] = a; + h[j2 + 2] = h[a + 2] + 1; + h[j2 + 3] = h[a + 3]; + K++; + if (K + 1 == 1 << V3 && V3 != 12) + V3++; + }, T3 = function(S, A4, j2, a, n2, q2) { + e = A4 << 3; + U = S; + Z3 = a; + u3 = n2; + var B3 = A4 + j2 << 3, _9 = 0, t4 = 0; + m(q2); + i(q2); + while (e < B3 && (_9 = O()) != N) { + if (_9 == g3) { + i(q2); + _9 = O(); + if (_9 == N) + break; + D(_9); + } else { + if (_9 < K) { + D(_9); + L(t4, _9); + } else { + L(t4, t4); + D(K - 1); + } + } + t4 = _9; + } + return u3; + }; + return T3; +}(); +UTIF.tags = {}; +UTIF._types = function() { + var main = new Array(250); + main.fill(0); + main = main.concat([0, 0, 0, 0, 4, 3, 3, 3, 3, 3, 0, 0, 3, 0, 0, 0, 3, 0, 0, 2, 2, 2, 2, 4, 3, 0, 0, 3, 4, 4, 3, 3, 5, 5, 3, 2, 5, 5, 0, 0, 0, 0, 4, 4, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 5, 5, 3, 0, 3, 3, 4, 4, 4, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + var rest = { 33432: 2, 33434: 5, 33437: 5, 34665: 4, 34850: 3, 34853: 4, 34855: 3, 34864: 3, 34866: 4, 36864: 7, 36867: 2, 36868: 2, 37121: 7, 37377: 10, 37378: 5, 37380: 10, 37381: 5, 37383: 3, 37384: 3, 37385: 3, 37386: 5, 37510: 7, 37520: 2, 37521: 2, 37522: 2, 40960: 7, 40961: 3, 40962: 4, 40963: 4, 40965: 4, 41486: 5, 41487: 5, 41488: 3, 41985: 3, 41986: 3, 41987: 3, 41988: 5, 41989: 3, 41990: 3, 41993: 3, 41994: 3, 41995: 7, 41996: 3, 42032: 2, 42033: 2, 42034: 5, 42036: 2, 42037: 2, 59932: 7 }; + return { + basic: { + main, + rest + }, + gps: { + main: [1, 2, 5, 2, 5, 1, 5, 5, 0, 9], + rest: { 18: 2, 29: 2 } + } + }; +}(); +UTIF._readIFD = function(bin, data2, offset, ifds, depth, prm) { + var cnt = bin.readUshort(data2, offset); + offset += 2; + var ifd = {}; + if (prm.debug) + log(" ".repeat(depth), ifds.length - 1, ">>>----------------"); + for (var i = 0;i < cnt; i++) { + var tag = bin.readUshort(data2, offset); + offset += 2; + var type = bin.readUshort(data2, offset); + offset += 2; + var num = bin.readUint(data2, offset); + offset += 4; + var voff = bin.readUint(data2, offset); + offset += 4; + var arr = []; + if (type == 1 || type == 7) { + var no = num < 5 ? offset - 4 : voff; + if (no + num > data2.buffer.byteLength) + num = data2.buffer.byteLength - no; + arr = new Uint8Array(data2.buffer, no, num); + } + if (type == 2) { + var o02 = num < 5 ? offset - 4 : voff, c = data2[o02], len = Math.max(0, Math.min(num - 1, data2.length - o02)); + if (c < 128 || len == 0) + arr.push(bin.readASCII(data2, o02, len)); + else + arr = new Uint8Array(data2.buffer, o02, len); + } + if (type == 3) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readUshort(data2, (num < 3 ? offset - 4 : voff) + 2 * j2)); + } + if (type == 4 || type == 13) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readUint(data2, (num < 2 ? offset - 4 : voff) + 4 * j2)); + } + if (type == 5 || type == 10) { + var ri2 = type == 5 ? bin.readUint : bin.readInt; + for (var j2 = 0;j2 < num; j2++) + arr.push([ri2(data2, voff + j2 * 8), ri2(data2, voff + j2 * 8 + 4)]); + } + if (type == 8) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readShort(data2, (num < 3 ? offset - 4 : voff) + 2 * j2)); + } + if (type == 9) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readInt(data2, (num < 2 ? offset - 4 : voff) + 4 * j2)); + } + if (type == 11) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readFloat(data2, voff + j2 * 4)); + } + if (type == 12) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readDouble(data2, voff + j2 * 8)); + } + if (num != 0 && arr.length == 0) { + log(tag, "unknown TIFF tag type: ", type, "num:", num); + if (i == 0) + return; + continue; + } + if (prm.debug) + log(" ".repeat(depth), tag, type, UTIF.tags[tag], arr); + ifd["t" + tag] = arr; + if (tag == 330 && ifd["t272"] && ifd["t272"][0] == "DSLR-A100") { + } else if (tag == 330 || tag == 34665 || tag == 34853 || tag == 50740 && bin.readUshort(data2, bin.readUint(arr, 0)) < 300 || tag == 61440) { + var oarr = tag == 50740 ? [bin.readUint(arr, 0)] : arr; + var subfd = []; + for (var j2 = 0;j2 < oarr.length; j2++) + UTIF._readIFD(bin, data2, oarr[j2], subfd, depth + 1, prm); + if (tag == 330) + ifd.subIFD = subfd; + if (tag == 34665) + ifd.exifIFD = subfd[0]; + if (tag == 34853) + ifd.gpsiIFD = subfd[0]; + if (tag == 50740) + ifd.dngPrvt = subfd[0]; + if (tag == 61440) + ifd.fujiIFD = subfd[0]; + } + if (tag == 37500 && prm.parseMN) { + var mn = arr; + if (bin.readASCII(mn, 0, 5) == "Nikon") + ifd.makerNote = UTIF["decode"](mn.slice(10).buffer)[0]; + else if (bin.readASCII(mn, 0, 5) == "OLYMP" || bin.readASCII(mn, 0, 9) == "OM SYSTEM") { + var inds = [8208, 8224, 8240, 8256, 8272]; + var subsub = []; + UTIF._readIFD(bin, mn, mn[1] == 77 ? 16 : mn[5] == 85 ? 12 : 8, subsub, depth + 1, prm); + var obj = ifd.makerNote = subsub.pop(); + for (var j2 = 0;j2 < inds.length; j2++) { + var k2 = "t" + inds[j2]; + if (obj[k2] == null) + continue; + UTIF._readIFD(bin, mn, obj[k2][0], subsub, depth + 1, prm); + obj[k2] = subsub.pop(); + } + if (obj["t12288"]) { + UTIF._readIFD(bin, obj["t12288"], 0, subsub, depth + 1, prm); + obj["t12288"] = subsub.pop(); + } + } else if (bin.readUshort(data2, voff) < 300 && bin.readUshort(data2, voff + 4) <= 12) { + var subsub = []; + UTIF._readIFD(bin, data2, voff, subsub, depth + 1, prm); + ifd.makerNote = subsub[0]; + } + } + } + ifds.push(ifd); + if (prm.debug) + log(" ".repeat(depth), "<<<---------------"); + return offset; +}; +UTIF._writeIFD = function(bin, types, data2, offset, ifd) { + var keys2 = Object.keys(ifd), knum = keys2.length; + if (ifd["exifIFD"]) + knum--; + if (ifd["gpsiIFD"]) + knum--; + bin.writeUshort(data2, offset, knum); + offset += 2; + var eoff = offset + knum * 12 + 4; + for (var ki2 = 0;ki2 < keys2.length; ki2++) { + var key2 = keys2[ki2]; + if (key2 == "t34665" || key2 == "t34853") + continue; + if (key2 == "exifIFD") + key2 = "t34665"; + if (key2 == "gpsiIFD") + key2 = "t34853"; + var tag = parseInt(key2.slice(1)), type = types.main[tag]; + if (type == null) + type = types.rest[tag]; + if (type == null || type == 0) + throw new Error("unknown type of tag: " + tag); + var val2 = ifd[key2]; + if (tag == 34665) { + var outp = UTIF._writeIFD(bin, types, data2, eoff, ifd["exifIFD"]); + val2 = [eoff]; + eoff = outp[1]; + } + if (tag == 34853) { + var outp = UTIF._writeIFD(bin, UTIF._types.gps, data2, eoff, ifd["gpsiIFD"]); + val2 = [eoff]; + eoff = outp[1]; + } + if (type == 2) + val2 = val2[0] + "\x00"; + var num = val2.length; + bin.writeUshort(data2, offset, tag); + offset += 2; + bin.writeUshort(data2, offset, type); + offset += 2; + bin.writeUint(data2, offset, num); + offset += 4; + var dlen = [-1, 1, 1, 2, 4, 8, 0, 1, 0, 4, 8, 0, 8][type] * num; + var toff = offset; + if (dlen > 4) { + bin.writeUint(data2, offset, eoff); + toff = eoff; + } + if (type == 1 || type == 7) { + for (var i = 0;i < num; i++) + data2[toff + i] = val2[i]; + } else if (type == 2) { + bin.writeASCII(data2, toff, val2); + } else if (type == 3) { + for (var i = 0;i < num; i++) + bin.writeUshort(data2, toff + 2 * i, val2[i]); + } else if (type == 4) { + for (var i = 0;i < num; i++) + bin.writeUint(data2, toff + 4 * i, val2[i]); + } else if (type == 5 || type == 10) { + var wr = type == 5 ? bin.writeUint : bin.writeInt; + for (var i = 0;i < num; i++) { + var v = val2[i], nu = v[0], de = v[1]; + if (nu == null) + throw "e"; + wr(data2, toff + 8 * i, nu); + wr(data2, toff + 8 * i + 4, de); + } + } else if (type == 9) { + for (var i = 0;i < num; i++) + bin.writeInt(data2, toff + 4 * i, val2[i]); + } else if (type == 12) { + for (var i = 0;i < num; i++) + bin.writeDouble(data2, toff + 8 * i, val2[i]); + } else + throw type; + if (dlen > 4) { + dlen += dlen & 1; + eoff += dlen; + } + offset += 4; + } + return [offset, eoff]; +}; +UTIF.toRGBA8 = function(out, scl) { + function gamma(x3) { + return x3 < 0.0031308 ? 12.92 * x3 : 1.055 * Math.pow(x3, 1 / 2.4) - 0.055; + } + var { width: w, height: h } = out, area2 = w * h, qarea = area2 * 4, data2 = out.data; + var img = new Uint8Array(area2 * 4); + var intp = out["t262"] ? out["t262"][0] : 2, bps = out["t258"] ? Math.min(32, out["t258"][0]) : 1; + if (out["t262"] == null && bps == 1) + intp = 0; + var smpls = out["t277"] ? out["t277"][0] : out["t258"] ? out["t258"].length : [1, 1, 3, 1, 1, 4, 3][intp]; + var sfmt = out["t339"] ? out["t339"][0] : null; + if (intp == 1 && bps == 32 && sfmt != 3) + throw "e"; + var bpl = Math.ceil(smpls * bps * w / 8); + if (false) { + } else if (intp == 0) { + scl = 1 / 256; + for (var y3 = 0;y3 < h; y3++) { + var off = y3 * bpl, io = y3 * w; + if (bps == 1) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + (i >> 3)] >> 7 - (i & 7) & 1; + img[qi] = img[qi + 1] = img[qi + 2] = (1 - px2) * 255; + img[qi + 3] = 255; + } + if (bps == 4) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + (i >> 1)] >> 4 - 4 * (i & 1) & 15; + img[qi] = img[qi + 1] = img[qi + 2] = (15 - px2) * 17; + img[qi + 3] = 255; + } + if (bps == 8) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + i]; + img[qi] = img[qi + 1] = img[qi + 2] = 255 - px2; + img[qi + 3] = 255; + } + if (bps == 16) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, o = off + 2 * i, px2 = data2[o + 1] << 8 | data2[o]; + img[qi] = img[qi + 1] = img[qi + 2] = Math.min(255, 255 - ~~(px2 * scl)); + img[qi + 3] = 255; + } + } + } else if (intp == 1) { + if (scl == null) + scl = 1 / 256; + var f32 = (data2.length & 3) == 0 ? new Float32Array(data2.buffer) : null; + for (var y3 = 0;y3 < h; y3++) { + var off = y3 * bpl, io = y3 * w; + if (bps == 1) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + (i >> 3)] >> 7 - (i & 7) & 1; + img[qi] = img[qi + 1] = img[qi + 2] = px2 * 255; + img[qi + 3] = 255; + } + if (bps == 2) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + (i >> 2)] >> 6 - 2 * (i & 3) & 3; + img[qi] = img[qi + 1] = img[qi + 2] = px2 * 85; + img[qi + 3] = 255; + } + if (bps == 8) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + i * smpls]; + img[qi] = img[qi + 1] = img[qi + 2] = px2; + img[qi + 3] = 255; + } + if (bps == 16) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, o = off + 2 * i, px2 = data2[o + 1] << 8 | data2[o]; + img[qi] = img[qi + 1] = img[qi + 2] = Math.min(255, ~~(px2 * scl)); + img[qi + 3] = 255; + } + if (bps == 32) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, o = (off >>> 2) + i, px2 = f32[o]; + img[qi] = img[qi + 1] = img[qi + 2] = ~~(0.5 + 255 * px2); + img[qi + 3] = 255; + } + } + } else if (intp == 2) { + if (bps == 8) { + if (smpls == 1) + for (var i = 0;i < area2; i++) { + img[4 * i] = img[4 * i + 1] = img[4 * i + 2] = data2[i]; + img[4 * i + 3] = 255; + } + if (smpls == 3) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 3; + img[qi] = data2[ti]; + img[qi + 1] = data2[ti + 1]; + img[qi + 2] = data2[ti + 2]; + img[qi + 3] = 255; + } + if (smpls >= 4) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * smpls; + img[qi] = data2[ti]; + img[qi + 1] = data2[ti + 1]; + img[qi + 2] = data2[ti + 2]; + img[qi + 3] = data2[ti + 3]; + } + } else if (bps == 16) { + if (smpls == 4) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 8 + 1; + img[qi] = data2[ti]; + img[qi + 1] = data2[ti + 2]; + img[qi + 2] = data2[ti + 4]; + img[qi + 3] = data2[ti + 6]; + } + if (smpls == 3) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 6 + 1; + img[qi] = data2[ti]; + img[qi + 1] = data2[ti + 2]; + img[qi + 2] = data2[ti + 4]; + img[qi + 3] = 255; + } + } else if (bps == 32) { + var ndt = new Float32Array(data2.buffer); + var min = 0; + for (var i = 0;i < ndt.length; i++) + min = Math.min(min, ndt[i]); + if (min < 0) + for (var i = 0;i < data2.length; i += 4) { + var t4 = data2[i]; + data2[i] = data2[i + 3]; + data2[i + 3] = t4; + t4 = data2[i + 1]; + data2[i + 1] = data2[i + 2]; + data2[i + 2] = t4; + } + var pmap = []; + for (var i = 0;i < 65536; i++) + pmap.push(gamma(i / 65535)); + for (var i = 0;i < ndt.length; i++) { + var cv = Math.max(0, Math.min(1, ndt[i])); + ndt[i] = pmap[~~(0.5 + cv * 65535)]; + } + if (smpls == 3) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 3; + img[qi] = ~~(0.5 + ndt[ti] * 255); + img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255); + img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255); + img[qi + 3] = 255; + } + else if (smpls == 4) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 4; + img[qi] = ~~(0.5 + ndt[ti] * 255); + img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255); + img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255); + img[qi + 3] = ~~(0.5 + ndt[ti + 3] * 255); + } + else + throw smpls; + } else + throw bps; + } else if (intp == 3) { + var map2 = out["t320"]; + var cn = 1 << bps; + var nexta = bps == 8 && smpls > 1 && out["t338"] && out["t338"][0] != 0; + for (var y3 = 0;y3 < h; y3++) + for (var x2 = 0;x2 < w; x2++) { + var i = y3 * w + x2; + var qi = i << 2, mi = 0; + var dof = y3 * bpl; + if (false) { + } else if (bps == 1) + mi = data2[dof + (x2 >>> 3)] >>> 7 - (x2 & 7) & 1; + else if (bps == 2) + mi = data2[dof + (x2 >>> 2)] >>> 6 - 2 * (x2 & 3) & 3; + else if (bps == 4) + mi = data2[dof + (x2 >>> 1)] >>> 4 - 4 * (x2 & 1) & 15; + else if (bps == 8) + mi = data2[dof + x2 * smpls]; + else + throw bps; + img[qi] = map2[mi] >> 8; + img[qi + 1] = map2[cn + mi] >> 8; + img[qi + 2] = map2[cn + cn + mi] >> 8; + img[qi + 3] = nexta ? data2[dof + x2 * smpls + 1] : 255; + } + } else if (intp == 5) { + var gotAlpha = smpls > 4 ? 1 : 0; + for (var i = 0;i < area2; i++) { + var qi = i << 2, si = i * smpls; + if (window.UDOC) { + var C5 = data2[si], M = data2[si + 1], Y = data2[si + 2], K = data2[si + 3]; + var c = UDOC.C.cmykToRgb([C5 * (1 / 255), M * (1 / 255), Y * (1 / 255), K * (1 / 255)]); + img[qi] = ~~(0.5 + 255 * c[0]); + img[qi + 1] = ~~(0.5 + 255 * c[1]); + img[qi + 2] = ~~(0.5 + 255 * c[2]); + } else { + var C5 = 255 - data2[si], M = 255 - data2[si + 1], Y = 255 - data2[si + 2], K = (255 - data2[si + 3]) * (1 / 255); + img[qi] = ~~(C5 * K + 0.5); + img[qi + 1] = ~~(M * K + 0.5); + img[qi + 2] = ~~(Y * K + 0.5); + } + img[qi + 3] = 255 * (1 - gotAlpha) + data2[si + 4] * gotAlpha; + } + } else if (intp == 6 && out["t278"]) { + var rps = out["t278"][0]; + for (var y3 = 0;y3 < h; y3 += rps) { + var i = y3 * w, len = rps * w; + for (var j2 = 0;j2 < len; j2++) { + var qi = 4 * (i + j2), si = 3 * i + 4 * (j2 >>> 1); + var Y = data2[si + (j2 & 1)], Cb = data2[si + 2] - 128, Cr3 = data2[si + 3] - 128; + var r = Y + ((Cr3 >> 2) + (Cr3 >> 3) + (Cr3 >> 5)); + var g3 = Y - ((Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ((Cr3 >> 1) + (Cr3 >> 3) + (Cr3 >> 4) + (Cr3 >> 5)); + var b = Y + (Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)); + img[qi] = Math.max(0, Math.min(255, r)); + img[qi + 1] = Math.max(0, Math.min(255, g3)); + img[qi + 2] = Math.max(0, Math.min(255, b)); + img[qi + 3] = 255; + } + } + } else if (intp == 32845) { + for (var y3 = 0;y3 < h; y3++) + for (var x2 = 0;x2 < w; x2++) { + var si = (y3 * w + x2) * 6, qi = (y3 * w + x2) * 4; + var L = data2[si + 1] << 8 | data2[si]; + var L = Math.pow(2, (L + 0.5) / 256 - 64); + var u3 = (data2[si + 3] + 0.5) / 410; + var v = (data2[si + 5] + 0.5) / 410; + var sX = 9 * u3 / (6 * u3 - 16 * v + 12); + var sY = 4 * v / (6 * u3 - 16 * v + 12); + var bY = L; + var X = sX * bY / sY, Y = bY, Z3 = (1 - sX - sY) * bY / sY; + var r = 2.69 * X - 1.276 * Y - 0.414 * Z3; + var g3 = -1.022 * X + 1.978 * Y + 0.044 * Z3; + var b = 0.061 * X - 0.224 * Y + 1.163 * Z3; + img[qi] = gamma(Math.min(r, 1)) * 255; + img[qi + 1] = gamma(Math.min(g3, 1)) * 255; + img[qi + 2] = gamma(Math.min(b, 1)) * 255; + img[qi + 3] = 255; + } + } else + log("Unknown Photometric interpretation: " + intp); + return img; +}; +UTIF.replaceIMG = function(imgs) { + if (imgs == null) + imgs = document.getElementsByTagName("img"); + var sufs = ["tif", "tiff", "dng", "cr2", "nef"]; + for (var i = 0;i < imgs.length; i++) { + var img = imgs[i], src = img.getAttribute("src"); + if (src == null) + continue; + var suff = src.split(".").pop().toLowerCase(); + if (sufs.indexOf(suff) == -1) + continue; + var xhr = new XMLHttpRequest; + UTIF._xhrs.push(xhr); + UTIF._imgs.push(img); + xhr.open("GET", src); + xhr.responseType = "arraybuffer"; + xhr.onload = UTIF._imgLoaded; + xhr.send(); + } +}; +UTIF._xhrs = []; +UTIF._imgs = []; +UTIF._imgLoaded = function(e) { + var ind = UTIF._xhrs.indexOf(e.target), img = UTIF._imgs[ind]; + UTIF._xhrs.splice(ind, 1); + UTIF._imgs.splice(ind, 1); + img.setAttribute("src", UTIF.bufferToURI(e.target.response)); +}; +UTIF.bufferToURI = function(buff) { + var ifds = UTIF.decode(buff); + var vsns = ifds, ma = 0, page = vsns[0]; + if (ifds[0].subIFD) + vsns = vsns.concat(ifds[0].subIFD); + for (var i = 0;i < vsns.length; i++) { + var img = vsns[i]; + if (img["t258"] == null || img["t258"].length < 3) + continue; + var ar2 = img["t256"] * img["t257"]; + if (ar2 > ma) { + ma = ar2; + page = img; + } + } + UTIF.decodeImage(buff, page, ifds); + var rgba = UTIF.toRGBA8(page), w = page.width, h = page.height; + var cnv = document.createElement("canvas"); + cnv.width = w; + cnv.height = h; + var ctx = cnv.getContext("2d"); + var imgd = new ImageData(new Uint8ClampedArray(rgba.buffer), w, h); + ctx.putImageData(imgd, 0, 0); + return cnv.toDataURL(); +}; +UTIF._binBE = { + nextZero: function(data2, o) { + while (data2[o] != 0) + o++; + return o; + }, + readUshort: function(buff, p) { + return buff[p] << 8 | buff[p + 1]; + }, + readShort: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 1]; + a[1] = buff[p + 0]; + return UTIF._binBE.i16[0]; + }, + readInt: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 3]; + a[1] = buff[p + 2]; + a[2] = buff[p + 1]; + a[3] = buff[p + 0]; + return UTIF._binBE.i32[0]; + }, + readUint: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 3]; + a[1] = buff[p + 2]; + a[2] = buff[p + 1]; + a[3] = buff[p + 0]; + return UTIF._binBE.ui32[0]; + }, + readASCII: function(buff, p, l2) { + var s = ""; + for (var i = 0;i < l2; i++) + s += String.fromCharCode(buff[p + i]); + return s; + }, + readFloat: function(buff, p) { + var a = UTIF._binBE.ui8; + for (var i = 0;i < 4; i++) + a[i] = buff[p + 3 - i]; + return UTIF._binBE.fl32[0]; + }, + readDouble: function(buff, p) { + var a = UTIF._binBE.ui8; + for (var i = 0;i < 8; i++) + a[i] = buff[p + 7 - i]; + return UTIF._binBE.fl64[0]; + }, + writeUshort: function(buff, p, n2) { + buff[p] = n2 >> 8 & 255; + buff[p + 1] = n2 & 255; + }, + writeInt: function(buff, p, n2) { + var a = UTIF._binBE.ui8; + UTIF._binBE.i32[0] = n2; + buff[p + 3] = a[0]; + buff[p + 2] = a[1]; + buff[p + 1] = a[2]; + buff[p + 0] = a[3]; + }, + writeUint: function(buff, p, n2) { + buff[p] = n2 >> 24 & 255; + buff[p + 1] = n2 >> 16 & 255; + buff[p + 2] = n2 >> 8 & 255; + buff[p + 3] = n2 >> 0 & 255; + }, + writeASCII: function(buff, p, s) { + for (var i = 0;i < s.length; i++) + buff[p + i] = s.charCodeAt(i); + }, + writeDouble: function(buff, p, n2) { + UTIF._binBE.fl64[0] = n2; + for (var i = 0;i < 8; i++) + buff[p + i] = UTIF._binBE.ui8[7 - i]; + } +}; +UTIF._binBE.ui8 = new Uint8Array(8); +UTIF._binBE.i16 = new Int16Array(UTIF._binBE.ui8.buffer); +UTIF._binBE.i32 = new Int32Array(UTIF._binBE.ui8.buffer); +UTIF._binBE.ui32 = new Uint32Array(UTIF._binBE.ui8.buffer); +UTIF._binBE.fl32 = new Float32Array(UTIF._binBE.ui8.buffer); +UTIF._binBE.fl64 = new Float64Array(UTIF._binBE.ui8.buffer); +UTIF._binLE = { + nextZero: UTIF._binBE.nextZero, + readUshort: function(buff, p) { + return buff[p + 1] << 8 | buff[p]; + }, + readShort: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 0]; + a[1] = buff[p + 1]; + return UTIF._binBE.i16[0]; + }, + readInt: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 0]; + a[1] = buff[p + 1]; + a[2] = buff[p + 2]; + a[3] = buff[p + 3]; + return UTIF._binBE.i32[0]; + }, + readUint: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 0]; + a[1] = buff[p + 1]; + a[2] = buff[p + 2]; + a[3] = buff[p + 3]; + return UTIF._binBE.ui32[0]; + }, + readASCII: UTIF._binBE.readASCII, + readFloat: function(buff, p) { + var a = UTIF._binBE.ui8; + for (var i = 0;i < 4; i++) + a[i] = buff[p + i]; + return UTIF._binBE.fl32[0]; + }, + readDouble: function(buff, p) { + var a = UTIF._binBE.ui8; + for (var i = 0;i < 8; i++) + a[i] = buff[p + i]; + return UTIF._binBE.fl64[0]; + }, + writeUshort: function(buff, p, n2) { + buff[p] = n2 & 255; + buff[p + 1] = n2 >> 8 & 255; + }, + writeInt: function(buff, p, n2) { + var a = UTIF._binBE.ui8; + UTIF._binBE.i32[0] = n2; + buff[p + 0] = a[0]; + buff[p + 1] = a[1]; + buff[p + 2] = a[2]; + buff[p + 3] = a[3]; + }, + writeUint: function(buff, p, n2) { + buff[p] = n2 >>> 0 & 255; + buff[p + 1] = n2 >>> 8 & 255; + buff[p + 2] = n2 >>> 16 & 255; + buff[p + 3] = n2 >>> 24 & 255; + }, + writeASCII: UTIF._binBE.writeASCII +}; +UTIF._copyTile = function(tb, tw, th2, b, w, h, xoff, yoff) { + var xlim = Math.min(tw, w - xoff); + var ylim = Math.min(th2, h - yoff); + for (var y3 = 0;y3 < ylim; y3++) { + var tof = (yoff + y3) * w + xoff; + var sof = y3 * tw; + for (var x2 = 0;x2 < xlim; x2++) + b[tof + x2] = tb[sof + x2]; + } +}; +UTIF._inflateRaw = function() { + var H = {}; + H.H = {}; + H.H.N = function(N, W) { + var R2 = Uint8Array, i = 0, m = 0, J2 = 0, h = 0, Q3 = 0, X = 0, u3 = 0, w = 0, d = 0, v, C5; + if (N[0] == 3 && N[1] == 0) + return W ? W : new R2(0); + var V3 = H.H, n2 = V3.b, A4 = V3.e, l2 = V3.R, M = V3.n, I3 = V3.A, e = V3.Z, b = V3.m, Z3 = W == null; + if (Z3) + W = new R2(N.length >>> 2 << 5); + while (i == 0) { + i = n2(N, d, 1); + m = n2(N, d + 1, 2); + d += 3; + if (m == 0) { + if ((d & 7) != 0) + d += 8 - (d & 7); + var D = (d >>> 3) + 4, q2 = N[D - 4] | N[D - 3] << 8; + if (Z3) + W = H.H.W(W, w + q2); + W.set(new R2(N.buffer, N.byteOffset + D, q2), w); + d = D + q2 << 3; + w += q2; + continue; + } + if (Z3) + W = H.H.W(W, w + (1 << 17)); + if (m == 1) { + v = b.J; + C5 = b.h; + X = (1 << 9) - 1; + u3 = (1 << 5) - 1; + } + if (m == 2) { + J2 = A4(N, d, 5) + 257; + h = A4(N, d + 5, 5) + 1; + Q3 = A4(N, d + 10, 4) + 4; + d += 14; + var E2 = d, j2 = 1; + for (var c = 0;c < 38; c += 2) { + b.Q[c] = 0; + b.Q[c + 1] = 0; + } + for (var c = 0;c < Q3; c++) { + var K = A4(N, d + c * 3, 3); + b.Q[(b.X[c] << 1) + 1] = K; + if (K > j2) + j2 = K; + } + d += 3 * Q3; + M(b.Q, j2); + I3(b.Q, j2, b.u); + v = b.w; + C5 = b.d; + d = l2(b.u, (1 << j2) - 1, J2 + h, N, d, b.v); + var r = V3.V(b.v, 0, J2, b.C); + X = (1 << r) - 1; + var S = V3.V(b.v, J2, h, b.D); + u3 = (1 << S) - 1; + M(b.C, r); + I3(b.C, r, v); + M(b.D, S); + I3(b.D, S, C5); + } + while (true) { + var T3 = v[e(N, d) & X]; + d += T3 & 15; + var p = T3 >>> 4; + if (p >>> 8 == 0) { + W[w++] = p; + } else if (p == 256) { + break; + } else { + var z2 = w + p - 254; + if (p > 264) { + var _9 = b.q[p - 257]; + z2 = w + (_9 >>> 3) + A4(N, d, _9 & 7); + d += _9 & 7; + } + var $2 = C5[e(N, d) & u3]; + d += $2 & 15; + var s = $2 >>> 4, Y = b.c[s], a = (Y >>> 4) + n2(N, d, Y & 15); + d += Y & 15; + while (w < z2) { + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + } + w = z2; + } + } + } + return W.length == w ? W : W.slice(0, w); + }; + H.H.W = function(N, W) { + var R2 = N.length; + if (W <= R2) + return N; + var V3 = new Uint8Array(R2 << 1); + V3.set(N, 0); + return V3; + }; + H.H.R = function(N, W, R2, V3, n2, A4) { + var l2 = H.H.e, M = H.H.Z, I3 = 0; + while (I3 < R2) { + var e = N[M(V3, n2) & W]; + n2 += e & 15; + var b = e >>> 4; + if (b <= 15) { + A4[I3] = b; + I3++; + } else { + var Z3 = 0, m = 0; + if (b == 16) { + m = 3 + l2(V3, n2, 2); + n2 += 2; + Z3 = A4[I3 - 1]; + } else if (b == 17) { + m = 3 + l2(V3, n2, 3); + n2 += 3; + } else if (b == 18) { + m = 11 + l2(V3, n2, 7); + n2 += 7; + } + var J2 = I3 + m; + while (I3 < J2) { + A4[I3] = Z3; + I3++; + } + } + } + return n2; + }; + H.H.V = function(N, W, R2, V3) { + var n2 = 0, A4 = 0, l2 = V3.length >>> 1; + while (A4 < R2) { + var M = N[A4 + W]; + V3[A4 << 1] = 0; + V3[(A4 << 1) + 1] = M; + if (M > n2) + n2 = M; + A4++; + } + while (A4 < l2) { + V3[A4 << 1] = 0; + V3[(A4 << 1) + 1] = 0; + A4++; + } + return n2; + }; + H.H.n = function(N, W) { + var R2 = H.H.m, V3 = N.length, n2, A4, l2, M, I3, e = R2.j; + for (var M = 0;M <= W; M++) + e[M] = 0; + for (M = 1;M < V3; M += 2) + e[N[M]]++; + var b = R2.K; + n2 = 0; + e[0] = 0; + for (A4 = 1;A4 <= W; A4++) { + n2 = n2 + e[A4 - 1] << 1; + b[A4] = n2; + } + for (l2 = 0;l2 < V3; l2 += 2) { + I3 = N[l2 + 1]; + if (I3 != 0) { + N[l2] = b[I3]; + b[I3]++; + } + } + }; + H.H.A = function(N, W, R2) { + var V3 = N.length, n2 = H.H.m, A4 = n2.r; + for (var l2 = 0;l2 < V3; l2 += 2) + if (N[l2 + 1] != 0) { + var M = l2 >> 1, I3 = N[l2 + 1], e = M << 4 | I3, b = W - I3, Z3 = N[l2] << b, m = Z3 + (1 << b); + while (Z3 != m) { + var J2 = A4[Z3] >>> 15 - W; + R2[J2] = e; + Z3++; + } + } + }; + H.H.l = function(N, W) { + var R2 = H.H.m.r, V3 = 15 - W; + for (var n2 = 0;n2 < N.length; n2 += 2) { + var A4 = N[n2] << W - N[n2 + 1]; + N[n2] = R2[A4] >>> V3; + } + }; + H.H.M = function(N, W, R2) { + R2 = R2 << (W & 7); + var V3 = W >>> 3; + N[V3] |= R2; + N[V3 + 1] |= R2 >>> 8; + }; + H.H.I = function(N, W, R2) { + R2 = R2 << (W & 7); + var V3 = W >>> 3; + N[V3] |= R2; + N[V3 + 1] |= R2 >>> 8; + N[V3 + 2] |= R2 >>> 16; + }; + H.H.e = function(N, W, R2) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8) >>> (W & 7) & (1 << R2) - 1; + }; + H.H.b = function(N, W, R2) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7) & (1 << R2) - 1; + }; + H.H.Z = function(N, W) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7); + }; + H.H.i = function(N, W) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16 | N[(W >>> 3) + 3] << 24) >>> (W & 7); + }; + H.H.m = function() { + var N = Uint16Array, W = Uint32Array; + return { K: new N(16), j: new N(16), X: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], S: [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, 999, 999, 999], T: [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, 0, 0, 0], q: new N(32), 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, 65535, 65535], z: [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, 0, 0], c: new W(32), J: new N(512), _: [], h: new N(32), $: [], w: new N(32768), C: [], v: [], d: new N(32768), D: [], u: new N(512), Q: [], r: new N(1 << 15), s: new W(286), Y: new W(30), a: new W(19), t: new W(15000), k: new N(1 << 16), g: new N(1 << 15) }; + }(); + (function() { + var N = H.H.m, W = 1 << 15; + for (var R2 = 0;R2 < W; R2++) { + var V3 = R2; + V3 = (V3 & 2863311530) >>> 1 | (V3 & 1431655765) << 1; + V3 = (V3 & 3435973836) >>> 2 | (V3 & 858993459) << 2; + V3 = (V3 & 4042322160) >>> 4 | (V3 & 252645135) << 4; + V3 = (V3 & 4278255360) >>> 8 | (V3 & 16711935) << 8; + N.r[R2] = (V3 >>> 16 | V3 << 16) >>> 17; + } + function n2(A4, l2, M) { + while (l2-- != 0) + A4.push(0, M); + } + for (var R2 = 0;R2 < 32; R2++) { + N.q[R2] = N.S[R2] << 3 | N.T[R2]; + N.c[R2] = N.p[R2] << 4 | N.z[R2]; + } + n2(N._, 144, 8); + n2(N._, 255 - 143, 9); + n2(N._, 279 - 255, 7); + n2(N._, 287 - 279, 8); + H.H.n(N._, 9); + H.H.A(N._, 9, N.J); + H.H.l(N._, 9); + n2(N.$, 32, 5); + H.H.n(N.$, 5); + H.H.A(N.$, 5, N.h); + H.H.l(N.$, 5); + n2(N.Q, 19, 0); + n2(N.C, 286, 0); + n2(N.D, 30, 0); + n2(N.v, 320, 0); + })(); + return H.H.N; +}(); +UTIF.LosslessJpegDecode = function() { + var b, O; + function l2() { + return b[O++]; + } + function m() { + return b[O++] << 8 | b[O++]; + } + function a0(h) { + var V3 = l2(), I3 = [0, 0, 0, 255], f = [], G2 = 8; + for (var w = 0;w < 16; w++) + f[w] = l2(); + for (var w = 0;w < 16; w++) { + for (var x2 = 0;x2 < f[w]; x2++) { + var T3 = z2(I3, 0, w + 1, 1); + I3[T3 + 3] = l2(); + } + } + var E2 = new Uint8Array(1 << G2); + h[V3] = [new Uint8Array(I3), E2]; + for (var w = 0;w < 1 << G2; w++) { + var s = G2, _9 = w, Y = 0, F = 0; + while (I3[Y + 3] == 255 && s != 0) { + F = _9 >> --s & 1; + Y = I3[Y + F]; + } + E2[w] = Y; + } + } + function z2(h, V3, I3, f) { + if (h[V3 + 3] != 255) + return 0; + if (I3 == 0) + return V3; + for (var w = 0;w < 2; w++) { + if (h[V3 + w] == 0) { + h[V3 + w] = h.length; + h.push(0, 0, f, 255); + } + var x2 = z2(h, h[V3 + w], I3 - 1, f + 1); + if (x2 != 0) + return x2; + } + return 0; + } + function i(h) { + var { b: V3, f: I3 } = h; + while (V3 < 25 && h.a < h.d) { + var f = h.data[h.a++]; + if (f == 255 && !h.c) + h.a++; + I3 = I3 << 8 | f; + V3 += 8; + } + if (V3 < 0) + throw "e"; + h.b = V3; + h.f = I3; + } + function H(h, V3) { + if (V3.b < h) + i(V3); + return V3.f >> (V3.b -= h) & 65535 >> 16 - h; + } + function g3(h, V3) { + var I3 = h[0], f = 0, w = 255, x2 = 0; + if (V3.b < 16) + i(V3); + var T3 = V3.f >> V3.b - 8 & 255; + f = h[1][T3]; + w = I3[f + 3]; + V3.b -= I3[f + 2]; + while (w == 255) { + x2 = V3.f >> --V3.b & 1; + f = I3[f + x2]; + w = I3[f + 3]; + } + return w; + } + function P(h, V3) { + if (h < 32768 >> 16 - V3) + h += -(1 << V3) + 1; + return h; + } + function a2(h, V3) { + var I3 = g3(h, V3); + if (I3 == 0) + return 0; + if (I3 == 16) + return -32768; + var f = H(I3, V3); + return P(f, I3); + } + function X(h, V3, I3, f, w, x2) { + var T3 = 0; + for (var G2 = 0;G2 < x2; G2++) { + var s = G2 * V3; + for (var _9 = 0;_9 < V3; _9 += w) { + T3++; + for (var Y = 0;Y < w; Y++) + h[s + _9 + Y] = a2(f[Y], I3); + } + if (I3.e != 0 && T3 % I3.e == 0 && G2 != 0) { + var { a: F, data: t4 } = I3; + while (t4[F] != 255 || !(208 <= t4[F + 1] && t4[F + 1] <= 215)) + F--; + I3.a = F + 2; + I3.f = 0; + I3.b = 0; + } + } + } + function o(h, V3) { + return P(H(h, V3), h); + } + function a1(h, V3, I3, f, w) { + var x2 = b.length - O; + for (var T3 = 0;T3 < x2; T3 += 4) { + var G2 = b[O + T3]; + b[O + T3] = b[O + T3 + 3]; + b[O + T3 + 3] = G2; + var G2 = b[O + T3 + 1]; + b[O + T3 + 1] = b[O + T3 + 2]; + b[O + T3 + 2] = G2; + } + for (var E2 = 0;E2 < w; E2++) { + var s = 32768, _9 = 32768; + for (var Y = 0;Y < V3; Y += 2) { + var F = g3(f, I3), t4 = g3(f, I3); + if (F != 0) + s += o(F, I3); + if (t4 != 0) + _9 += o(t4, I3); + h[E2 * V3 + Y] = s & 65535; + h[E2 * V3 + Y + 1] = _9 & 65535; + } + } + } + function C5(h) { + b = h; + O = 0; + if (m() != 65496) + throw "e"; + var V3 = [], I3 = 0, f = 0, w = 0, x2 = [], T3 = [], G2 = [], E2 = 0, s = 0, _9 = 0; + while (true) { + var Y = m(); + if (Y == 65535) { + O--; + continue; + } + var F = m(); + if (Y == 65475) { + f = l2(); + s = m(); + _9 = m(); + E2 = l2(); + for (var t4 = 0;t4 < E2; t4++) { + var a = l2(), J2 = l2(), r = l2(); + if (r != 0) + throw "e"; + V3[a] = [t4, J2 >> 4, J2 & 15]; + } + } else if (Y == 65476) { + var a3 = O + F - 2; + while (O < a3) + a0(T3); + } else if (Y == 65498) { + O++; + for (var t4 = 0;t4 < E2; t4++) { + var a5 = l2(), v = V3[a5]; + G2[v[0]] = T3[l2() >>> 4]; + x2[v[0]] = v.slice(1); + } + I3 = l2(); + O += 2; + break; + } else if (Y == 65501) { + w = m(); + } else { + O += F - 2; + } + } + var a4 = f > 8 ? Uint16Array : Uint8Array, $2 = new a4(s * _9 * E2), M = { b: 0, f: 0, c: I3 == 8, a: O, data: b, d: b.length, e: w }; + if (M.c) + a1($2, _9 * E2, M, G2[0], s); + else { + var c = [], p = 0, D = 0; + for (var t4 = 0;t4 < E2; t4++) { + var N = x2[t4], S = N[0], K = N[1]; + if (S > p) + p = S; + if (K > D) + D = K; + c.push(S * K); + } + if (p != 1 || D != 1) { + if (E2 != 3 || c[1] != 1 || c[2] != 1) + throw "e"; + if (p != 2 || D != 1 && D != 2) + throw "e"; + var u3 = [], Z3 = 0; + for (var t4 = 0;t4 < E2; t4++) { + for (var R2 = 0;R2 < c[t4]; R2++) + u3.push(G2[t4]); + Z3 += c[t4]; + } + var B3 = _9 / p, e = s / D, d = B3 * e; + X($2, B3 * Z3, M, u3, Z3, e); + j2($2, I3, B3, e, Z3 - 2, Z3, Z3, f); + var A4 = new Uint16Array(d * c[0]); + if (p == 2 && D == 2) { + for (var t4 = 0;t4 < d; t4++) { + A4[4 * t4] = $2[6 * t4]; + A4[4 * t4 + 1] = $2[6 * t4 + 1]; + A4[4 * t4 + 2] = $2[6 * t4 + 2]; + A4[4 * t4 + 3] = $2[6 * t4 + 3]; + } + j2(A4, I3, B3 * 4, e, 0, 1, 1, f); + for (var t4 = 0;t4 < d; t4++) { + $2[6 * t4] = A4[4 * t4]; + $2[6 * t4 + 1] = A4[4 * t4 + 1]; + $2[6 * t4 + 2] = A4[4 * t4 + 2]; + $2[6 * t4 + 3] = A4[4 * t4 + 3]; + } + } + if (p == 2 && D == 1) { + for (var t4 = 0;t4 < d; t4++) { + A4[2 * t4] = $2[4 * t4]; + A4[2 * t4 + 1] = $2[4 * t4 + 1]; + } + j2(A4, I3, B3 * 2, e, 0, 1, 1, f); + for (var t4 = 0;t4 < d; t4++) { + $2[4 * t4] = A4[2 * t4]; + $2[4 * t4 + 1] = A4[2 * t4 + 1]; + } + } + var n2 = $2.slice(0); + for (var K = 0;K < s; K++) { + if (D == 2) + for (var S = 0;S < _9; S++) { + var q2 = (K * _9 + S) * E2, k2 = ((K >>> 1) * B3 + (S >>> 1)) * Z3, y3 = (K & 1) * 2 + (S & 1); + $2[q2] = n2[k2 + y3]; + $2[q2 + 1] = n2[k2 + 4]; + $2[q2 + 2] = n2[k2 + 5]; + } + else + for (var S = 0;S < _9; S++) { + var q2 = (K * _9 + S) * E2, k2 = (K * B3 + (S >>> 1)) * Z3, y3 = S & 1; + $2[q2] = n2[k2 + y3]; + $2[q2 + 1] = n2[k2 + 2]; + $2[q2 + 2] = n2[k2 + 3]; + } + } + } else { + X($2, _9 * E2, M, G2, E2, s); + if (w == 0) + j2($2, I3, _9, s, 0, E2, E2, f); + else { + var U = Math.floor(w / _9); + for (var K = 0;K < s; K += U) { + var L = $2.slice(K * _9 * E2, (K + U) * _9 * E2); + j2(L, I3, _9, U, 0, E2, E2, f); + $2.set(L, K * _9 * E2); + } + } + } + } + return $2; + } + function j2(h, V3, I3, f, w, x2, G2, E2) { + var s = I3 * G2; + for (var _9 = w;_9 < x2; _9++) + h[_9] += 1 << E2 - 1; + for (var Y = G2;Y < s; Y += G2) + for (var _9 = w;_9 < x2; _9++) + h[Y + _9] += h[Y + _9 - G2]; + for (var F = 1;F < f; F++) { + var t4 = F * s; + for (var _9 = w;_9 < x2; _9++) + h[t4 + _9] += h[t4 + _9 - s]; + for (var Y = G2;Y < s; Y += G2) { + for (var _9 = w;_9 < x2; _9++) { + var a = t4 + Y + _9, J2 = a - s, r = h[a - G2], Q3 = 0; + if (V3 == 0) + Q3 = 0; + else if (V3 == 1) + Q3 = r; + else if (V3 == 2) + Q3 = h[J2]; + else if (V3 == 3) + Q3 = h[J2 - G2]; + else if (V3 == 4) + Q3 = r + (h[J2] - h[J2 - G2]); + else if (V3 == 5) + Q3 = r + (h[J2] - h[J2 - G2] >>> 1); + else if (V3 == 6) + Q3 = h[J2] + (r - h[J2 - G2] >>> 1); + else if (V3 == 7) + Q3 = r + h[J2] >>> 1; + else + throw V3; + h[a] += Q3; + } + } + } + } + return C5; +}(); +(function() { + var G2 = 0, F = 1, i = 2, b = 3, J2 = 4, N = 5, E2 = 6, s = 7, c = 8, T3 = 9, a3 = 10, f = 11, q2 = 12, M = 13, m = 14, x2 = 15, L = 16, $2 = 17, p = 18; + function a5(t4) { + var Z3 = UTIF._binBE.readUshort, u3 = { b: Z3(t4, 0), i: t4[2], C: t4[3], u: t4[4], q: Z3(t4, 5), k: Z3(t4, 7), e: Z3(t4, 9), l: Z3(t4, 11), s: t4[13], d: Z3(t4, 14) }; + if (u3.b != 18771 || u3.i > 1 || u3.q < 6 || u3.q % 6 || u3.e < 768 || u3.e % 24 || u3.l != 768 || u3.k < u3.l || u3.k % u3.l || u3.k - u3.e >= u3.l || u3.s > 16 || u3.s != u3.k / u3.l || u3.s != Math.ceil(u3.e / u3.l) || u3.d != u3.q / 6 || u3.u != 12 && u3.u != 14 && u3.u != 16 || u3.C != 16 && u3.C != 0) { + throw "Invalid data"; + } + if (u3.i == 0) { + throw "Not implemented. We need this file!"; + } + u3.h = u3.C == 16; + u3.m = (u3.h ? u3.l * 2 / 3 : u3.l >>> 1) | 0; + u3.A = u3.m + 2; + u3.f = 64; + u3.g = (1 << u3.u) - 1; + u3.n = 4 * u3.u; + return u3; + } + function a7(t4, Z3) { + var u3 = new Array(Z3.s), e = 4 * Z3.s, Q3 = 16 + e; + if (e & 12) + Q3 += 16 - (e & 12); + for (var V3 = 0, O = 16;V3 < Z3.s; O += 4) { + var o = UTIF._binBE.readUint(t4, O); + u3[V3] = t4.slice(Q3, Q3 + o); + u3[V3].j = 0; + u3[V3].a = 0; + Q3 += o; + V3++; + } + if (Q3 != t4.length) + throw "Invalid data"; + return u3; + } + function a6(t4, Z3) { + for (var u3 = -Z3[4], e = 0;u3 <= Z3[4]; e++, u3++) { + t4[e] = u3 <= -Z3[3] ? -4 : u3 <= -Z3[2] ? -3 : u3 <= -Z3[1] ? -2 : u3 < -Z3[0] ? -1 : u3 <= Z3[0] ? 0 : u3 < Z3[1] ? 1 : u3 < Z3[2] ? 2 : u3 < Z3[3] ? 3 : 4; + } + } + function a1(t4, Z3, u3) { + var e = [Z3, 3 * Z3 + 18, 5 * Z3 + 67, 7 * Z3 + 276, u3]; + t4.o = Z3; + t4.w = (e[4] + 2 * Z3) / (2 * Z3 + 1) + 1 | 0; + t4.v = Math.ceil(Math.log2(t4.w)); + t4.t = 9; + a6(t4.c, e); + } + function a2(t4) { + var Z3 = { c: new Int8Array(2 << t4.u) }; + a1(Z3, 0, t4.g); + return Z3; + } + function D(t4) { + var Z3 = [[], [], []], u3 = Math.max(2, t4.w + 32 >>> 6); + for (var e = 0;e < 3; e++) { + for (var Q3 = 0;Q3 < 41; Q3++) { + Z3[e][Q3] = [u3, 1]; + } + } + return Z3; + } + function a4(t4) { + for (var Z3 = -1, u3 = 0;!u3; Z3++) { + u3 = t4[t4.j] >>> 7 - t4.a & 1; + t4.a++; + t4.a &= 7; + if (!t4.a) + t4.j++; + } + return Z3; + } + function K(t4, Z3) { + var u3 = 0, e = 8 - t4.a, Q3 = t4.j, V3 = t4.a; + if (Z3) { + if (Z3 >= e) { + do { + u3 <<= e; + Z3 -= e; + u3 |= t4[t4.j] & (1 << e) - 1; + t4.j++; + e = 8; + } while (Z3 >= 8); + } + if (Z3) { + u3 <<= Z3; + e -= Z3; + u3 |= t4[t4.j] >>> e & (1 << Z3) - 1; + } + t4.a = 8 - e; + } + return u3; + } + function a0(t4, Z3) { + var u3 = 0; + if (Z3 < t4) { + while (u3 <= 14 && Z3 << ++u3 < t4) + ; + } + return u3; + } + function r(t4, Z3, u3, e, Q3, V3, O, o) { + if (o == null) + o = 0; + var X = V3 + 1, k2 = X % 2, j2 = 0, I3 = 0, a = 0, l2, R2, w = e[Q3], S = e[Q3 - 1], H = e[Q3 - 2][X], g3 = S[X - 1], Y = S[X], P = S[X + 1], A4 = w[X - 1], v = w[X + 1], y3 = Math.abs, d, C5, n2, h; + if (k2) { + d = y3(P - Y); + C5 = y3(H - Y); + n2 = y3(g3 - Y); + } + if (k2) { + h = d > n2 && C5 < d ? H + g3 : d < n2 && C5 < n2 ? H + P : P + g3; + h = h + 2 * Y >>> 2; + if (o) { + w[X] = h; + return; + } + l2 = Z3.t * Z3.c[t4.g + Y - H] + Z3.c[t4.g + g3 - Y]; + } else { + h = Y > g3 && Y > P || Y < g3 && Y < P ? v + A4 + 2 * Y >>> 2 : A4 + v >>> 1; + l2 = Z3.t * Z3.c[t4.g + Y - g3] + Z3.c[t4.g + g3 - A4]; + } + R2 = y3(l2); + var W = a4(u3); + if (W < t4.n - Z3.v - 1) { + var z2 = a0(O[R2][0], O[R2][1]); + a = K(u3, z2) + (W << z2); + } else { + a = K(u3, Z3.v) + 1; + } + a = a & 1 ? -1 - (a >>> 1) : a >>> 1; + O[R2][0] += y3(a); + if (O[R2][1] == t4.f) { + O[R2][0] >>>= 1; + O[R2][1] >>>= 1; + } + O[R2][1]++; + h = l2 < 0 ? h - a : h + a; + if (t4.i) { + if (h < 0) + h += Z3.w; + else if (h > t4.g) + h -= Z3.w; + } + w[X] = h >= 0 ? Math.min(h, t4.g) : 0; + } + function U(t4, Z3, u3) { + var e = t4[0].length; + for (var Q3 = Z3;Q3 <= u3; Q3++) { + t4[Q3][0] = t4[Q3 - 1][1]; + t4[Q3][e - 1] = t4[Q3 - 1][e - 2]; + } + } + function B3(t4) { + U(t4, s, q2); + U(t4, i, J2); + U(t4, x2, $2); + } + function _9(t4, Z3, u3, e, Q3, V3, O, o, X, k2, j2, I3, a) { + var l2 = 0, R2 = 1, w = Q3 < M && Q3 > J2; + while (R2 < t4.m) { + if (l2 < t4.m) { + r(t4, Z3, u3, e, Q3, l2, O[X], t4.h && (w && k2 || !w && (j2 || (l2 & I3) == a))); + r(t4, Z3, u3, e, V3, l2, O[X], t4.h && (!w && k2 || w && (j2 || (l2 & I3) == a))); + l2 += 2; + } + if (l2 > 8) { + r(t4, Z3, u3, e, Q3, R2, o[X]); + r(t4, Z3, u3, e, V3, R2, o[X]); + R2 += 2; + } + } + B3(e); + } + function a8(t4, Z3, u3, e, Q3, V3) { + _9(t4, Z3, u3, e, i, s, Q3, V3, 0, 0, 1, 0, 8); + _9(t4, Z3, u3, e, c, x2, Q3, V3, 1, 0, 1, 0, 8); + _9(t4, Z3, u3, e, b, T3, Q3, V3, 2, 1, 0, 3, 0); + _9(t4, Z3, u3, e, a3, L, Q3, V3, 0, 0, 0, 3, 2); + _9(t4, Z3, u3, e, J2, f, Q3, V3, 1, 0, 0, 3, 2); + _9(t4, Z3, u3, e, q2, $2, Q3, V3, 2, 1, 0, 3, 0); + } + function a9(t4, Z3, u3, e, Q3, V3) { + var O = V3.length, o = t4.l; + if (Q3 + 1 == t4.s) + o = t4.e - Q3 * t4.l; + var X = 6 * t4.e * e + Q3 * t4.l; + for (var k2 = 0;k2 < 6; k2++) { + for (var j2 = 0;j2 < o; j2++) { + var I3 = V3[k2 % O][j2 % O], a; + if (I3 == 0) { + a = i + (k2 >>> 1); + } else if (I3 == 2) { + a = x2 + (k2 >>> 1); + } else { + a = s + k2; + } + var l2 = t4.h ? (j2 * 2 / 3 & 2147483646 | j2 % 3 & 1) + (j2 % 3 >>> 1) : j2 >>> 1; + Z3[X + j2] = u3[a][l2 + 1]; + } + X += t4.e; + } + } + UTIF._decompressRAF = function(t4, Z3) { + var u3 = a5(t4), e = a7(t4, u3), Q3 = a2(u3), V3 = new Int16Array(u3.e * u3.q); + if (Z3 == null) { + Z3 = u3.h ? [[1, 1, 0, 1, 1, 2], [1, 1, 2, 1, 1, 0], [2, 0, 1, 0, 2, 1], [1, 1, 2, 1, 1, 0], [1, 1, 0, 1, 1, 2], [0, 2, 1, 2, 0, 1]] : [[0, 1], [3, 2]]; + } + var O = [[G2, b], [F, J2], [N, f], [E2, q2], [M, L], [m, $2]], o = []; + for (var X = 0;X < p; X++) { + o[X] = new Uint16Array(u3.A); + } + for (var k2 = 0;k2 < u3.s; k2++) { + var j2 = D(Q3), I3 = D(Q3); + for (var X = 0;X < p; X++) { + for (var a = 0;a < u3.A; a++) { + o[X][a] = 0; + } + } + for (var l2 = 0;l2 < u3.d; l2++) { + a8(u3, Q3, e[k2], o, j2, I3); + for (var X = 0;X < 6; X++) { + for (var a = 0;a < u3.A; a++) { + o[O[X][0]][a] = o[O[X][1]][a]; + } + } + a9(u3, V3, o, l2, k2, Z3); + for (var X = i;X < p; X++) { + if ([N, E2, M, m].indexOf(X) == -1) { + for (var a = 0;a < u3.A; a++) { + o[X][a] = 0; + } + } + } + B3(o); + } + } + return V3; + }; +})(); +// node_modules/three/examples/jsm/libs/opentype.module.js +/*! https://mths.be/codepointat v0.2.0 by @mathias */ +if (!String.prototype.codePointAt) { + (function() { + var defineProperty = function() { + try { + var object = {}; + var $defineProperty = Object.defineProperty; + var result = $defineProperty(object, object, object) && $defineProperty; + } catch (error) { + } + return result; + }(); + var codePointAt = function(position2) { + if (this == null) { + throw TypeError(); + } + var string = String(this); + var size = string.length; + var index2 = position2 ? Number(position2) : 0; + if (index2 != index2) { + index2 = 0; + } + if (index2 < 0 || index2 >= size) { + return; + } + var first2 = string.charCodeAt(index2); + var second; + if (first2 >= 55296 && first2 <= 56319 && size > index2 + 1) { + second = string.charCodeAt(index2 + 1); + if (second >= 56320 && second <= 57343) { + return (first2 - 55296) * 1024 + second - 56320 + 65536; + } + } + return first2; + }; + if (defineProperty) { + defineProperty(String.prototype, "codePointAt", { + value: codePointAt, + configurable: true, + writable: true + }); + } else { + String.prototype.codePointAt = codePointAt; + } + })(); +} +function Tree() { + this.table = new Uint16Array(16); + this.trans = new Uint16Array(288); +} +var sltree = new Tree; +var sdtree = new Tree; +var length_bits = new Uint8Array(30); +var length_base = new Uint16Array(30); +var dist_bits = new Uint8Array(30); +var dist_base = new Uint16Array(30); +var clcidx = new Uint8Array([ + 16, + 17, + 18, + 0, + 8, + 7, + 9, + 6, + 10, + 5, + 11, + 4, + 12, + 3, + 13, + 2, + 14, + 1, + 15 +]); +var code_tree = new Tree; +var lengths = new Uint8Array(288 + 32); +function tinf_build_bits_base(bits, base, delta, first2) { + var i, sum2; + for (i = 0;i < delta; ++i) { + bits[i] = 0; + } + for (i = 0;i < 30 - delta; ++i) { + bits[i + delta] = i / delta | 0; + } + for (sum2 = first2, i = 0;i < 30; ++i) { + base[i] = sum2; + sum2 += 1 << bits[i]; + } +} +function tinf_build_fixed_trees(lt, dt) { + var i; + for (i = 0;i < 7; ++i) { + lt.table[i] = 0; + } + lt.table[7] = 24; + lt.table[8] = 152; + lt.table[9] = 112; + for (i = 0;i < 24; ++i) { + lt.trans[i] = 256 + i; + } + for (i = 0;i < 144; ++i) { + lt.trans[24 + i] = i; + } + for (i = 0;i < 8; ++i) { + lt.trans[24 + 144 + i] = 280 + i; + } + for (i = 0;i < 112; ++i) { + lt.trans[24 + 144 + 8 + i] = 144 + i; + } + for (i = 0;i < 5; ++i) { + dt.table[i] = 0; + } + dt.table[5] = 32; + for (i = 0;i < 32; ++i) { + dt.trans[i] = i; + } +} +var offs = new Uint16Array(16); +tinf_build_fixed_trees(sltree, sdtree); +tinf_build_bits_base(length_bits, length_base, 4, 3); +tinf_build_bits_base(dist_bits, dist_base, 2, 1); +length_bits[28] = 0; +length_base[28] = 258; +function derive(v0, v1, v2, v32, t4) { + return Math.pow(1 - t4, 3) * v0 + 3 * Math.pow(1 - t4, 2) * t4 * v1 + 3 * (1 - t4) * Math.pow(t4, 2) * v2 + Math.pow(t4, 3) * v32; +} +function BoundingBox() { + this.x1 = Number.NaN; + this.y1 = Number.NaN; + this.x2 = Number.NaN; + this.y2 = Number.NaN; +} +BoundingBox.prototype.isEmpty = function() { + return isNaN(this.x1) || isNaN(this.y1) || isNaN(this.x2) || isNaN(this.y2); +}; +BoundingBox.prototype.addPoint = function(x2, y3) { + if (typeof x2 === "number") { + if (isNaN(this.x1) || isNaN(this.x2)) { + this.x1 = x2; + this.x2 = x2; + } + if (x2 < this.x1) { + this.x1 = x2; + } + if (x2 > this.x2) { + this.x2 = x2; + } + } + if (typeof y3 === "number") { + if (isNaN(this.y1) || isNaN(this.y2)) { + this.y1 = y3; + this.y2 = y3; + } + if (y3 < this.y1) { + this.y1 = y3; + } + if (y3 > this.y2) { + this.y2 = y3; + } + } +}; +BoundingBox.prototype.addX = function(x2) { + this.addPoint(x2, null); +}; +BoundingBox.prototype.addY = function(y3) { + this.addPoint(null, y3); +}; +BoundingBox.prototype.addBezier = function(x02, y0, x1, y1, x2, y22, x3, y3) { + var p0 = [x02, y0]; + var p1 = [x1, y1]; + var p2 = [x2, y22]; + var p32 = [x3, y3]; + this.addPoint(x02, y0); + this.addPoint(x3, y3); + for (var i = 0;i <= 1; i++) { + var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; + var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p32[i]; + var c = 3 * p1[i] - 3 * p0[i]; + if (a === 0) { + if (b === 0) { + continue; + } + var t4 = -c / b; + if (0 < t4 && t4 < 1) { + if (i === 0) { + this.addX(derive(p0[i], p1[i], p2[i], p32[i], t4)); + } + if (i === 1) { + this.addY(derive(p0[i], p1[i], p2[i], p32[i], t4)); + } + } + continue; + } + var b2ac = Math.pow(b, 2) - 4 * c * a; + if (b2ac < 0) { + continue; + } + var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); + if (0 < t1 && t1 < 1) { + if (i === 0) { + this.addX(derive(p0[i], p1[i], p2[i], p32[i], t1)); + } + if (i === 1) { + this.addY(derive(p0[i], p1[i], p2[i], p32[i], t1)); + } + } + var t22 = (-b - Math.sqrt(b2ac)) / (2 * a); + if (0 < t22 && t22 < 1) { + if (i === 0) { + this.addX(derive(p0[i], p1[i], p2[i], p32[i], t22)); + } + if (i === 1) { + this.addY(derive(p0[i], p1[i], p2[i], p32[i], t22)); + } + } + } +}; +BoundingBox.prototype.addQuad = function(x02, y0, x1, y1, x2, y3) { + var cp1x = x02 + 2 / 3 * (x1 - x02); + var cp1y = y0 + 2 / 3 * (y1 - y0); + var cp2x = cp1x + 1 / 3 * (x2 - x02); + var cp2y = cp1y + 1 / 3 * (y3 - y0); + this.addBezier(x02, y0, cp1x, cp1y, cp2x, cp2y, x2, y3); +}; +function Path2() { + this.commands = []; + this.fill = "black"; + this.stroke = null; + this.strokeWidth = 1; +} +Path2.prototype.moveTo = function(x2, y3) { + this.commands.push({ + type: "M", + x: x2, + y: y3 + }); +}; +Path2.prototype.lineTo = function(x2, y3) { + this.commands.push({ + type: "L", + x: x2, + y: y3 + }); +}; +Path2.prototype.curveTo = Path2.prototype.bezierCurveTo = function(x1, y1, x2, y22, x3, y3) { + this.commands.push({ + type: "C", + x1, + y1, + x2, + y2: y22, + x: x3, + y: y3 + }); +}; +Path2.prototype.quadTo = Path2.prototype.quadraticCurveTo = function(x1, y1, x2, y3) { + this.commands.push({ + type: "Q", + x1, + y1, + x: x2, + y: y3 + }); +}; +Path2.prototype.close = Path2.prototype.closePath = function() { + this.commands.push({ + type: "Z" + }); +}; +Path2.prototype.extend = function(pathOrCommands) { + if (pathOrCommands.commands) { + pathOrCommands = pathOrCommands.commands; + } else if (pathOrCommands instanceof BoundingBox) { + var box = pathOrCommands; + this.moveTo(box.x1, box.y1); + this.lineTo(box.x2, box.y1); + this.lineTo(box.x2, box.y2); + this.lineTo(box.x1, box.y2); + this.close(); + return; + } + Array.prototype.push.apply(this.commands, pathOrCommands); +}; +Path2.prototype.getBoundingBox = function() { + var box = new BoundingBox; + var startX = 0; + var startY = 0; + var prevX = 0; + var prevY = 0; + for (var i = 0;i < this.commands.length; i++) { + var cmd = this.commands[i]; + switch (cmd.type) { + case "M": + box.addPoint(cmd.x, cmd.y); + startX = prevX = cmd.x; + startY = prevY = cmd.y; + break; + case "L": + box.addPoint(cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case "Q": + box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case "C": + box.addBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case "Z": + prevX = startX; + prevY = startY; + break; + default: + throw new Error("Unexpected path command " + cmd.type); + } + } + if (box.isEmpty()) { + box.addPoint(0, 0); + } + return box; +}; +Path2.prototype.draw = function(ctx) { + ctx.beginPath(); + for (var i = 0;i < this.commands.length; i += 1) { + var cmd = this.commands[i]; + if (cmd.type === "M") { + ctx.moveTo(cmd.x, cmd.y); + } else if (cmd.type === "L") { + ctx.lineTo(cmd.x, cmd.y); + } else if (cmd.type === "C") { + ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === "Q") { + ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); + } else if (cmd.type === "Z") { + ctx.closePath(); + } + } + if (this.fill) { + ctx.fillStyle = this.fill; + ctx.fill(); + } + if (this.stroke) { + ctx.strokeStyle = this.stroke; + ctx.lineWidth = this.strokeWidth; + ctx.stroke(); + } +}; +Path2.prototype.toPathData = function(decimalPlaces) { + decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2; + function floatToString(v) { + if (Math.round(v) === v) { + return "" + Math.round(v); + } else { + return v.toFixed(decimalPlaces); + } + } + function packValues() { + var arguments$1 = arguments; + var s = ""; + for (var i3 = 0;i3 < arguments.length; i3 += 1) { + var v = arguments$1[i3]; + if (v >= 0 && i3 > 0) { + s += " "; + } + s += floatToString(v); + } + return s; + } + var d = ""; + for (var i = 0;i < this.commands.length; i += 1) { + var cmd = this.commands[i]; + if (cmd.type === "M") { + d += "M" + packValues(cmd.x, cmd.y); + } else if (cmd.type === "L") { + d += "L" + packValues(cmd.x, cmd.y); + } else if (cmd.type === "C") { + d += "C" + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === "Q") { + d += "Q" + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y); + } else if (cmd.type === "Z") { + d += "Z"; + } + } + return d; +}; +Path2.prototype.toSVG = function(decimalPlaces) { + var svg = '= 0 && v <= 255, "Byte value should be between 0 and 255."); + return [v]; +}; +sizeOf.BYTE = constant(1); +encode.CHAR = function(v) { + return [v.charCodeAt(0)]; +}; +sizeOf.CHAR = constant(1); +encode.CHARARRAY = function(v) { + if (typeof v === "undefined") { + v = ""; + console.warn("Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name."); + } + var b = []; + for (var i = 0;i < v.length; i += 1) { + b[i] = v.charCodeAt(i); + } + return b; +}; +sizeOf.CHARARRAY = function(v) { + if (typeof v === "undefined") { + return 0; + } + return v.length; +}; +encode.USHORT = function(v) { + return [v >> 8 & 255, v & 255]; +}; +sizeOf.USHORT = constant(2); +encode.SHORT = function(v) { + if (v >= LIMIT16) { + v = -(2 * LIMIT16 - v); + } + return [v >> 8 & 255, v & 255]; +}; +sizeOf.SHORT = constant(2); +encode.UINT24 = function(v) { + return [v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.UINT24 = constant(3); +encode.ULONG = function(v) { + return [v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.ULONG = constant(4); +encode.LONG = function(v) { + if (v >= LIMIT32) { + v = -(2 * LIMIT32 - v); + } + return [v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.LONG = constant(4); +encode.FIXED = encode.ULONG; +sizeOf.FIXED = sizeOf.ULONG; +encode.FWORD = encode.SHORT; +sizeOf.FWORD = sizeOf.SHORT; +encode.UFWORD = encode.USHORT; +sizeOf.UFWORD = sizeOf.USHORT; +encode.LONGDATETIME = function(v) { + return [0, 0, 0, 0, v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.LONGDATETIME = constant(8); +encode.TAG = function(v) { + check.argument(v.length === 4, "Tag should be exactly 4 ASCII characters."); + return [ + v.charCodeAt(0), + v.charCodeAt(1), + v.charCodeAt(2), + v.charCodeAt(3) + ]; +}; +sizeOf.TAG = constant(4); +encode.Card8 = encode.BYTE; +sizeOf.Card8 = sizeOf.BYTE; +encode.Card16 = encode.USHORT; +sizeOf.Card16 = sizeOf.USHORT; +encode.OffSize = encode.BYTE; +sizeOf.OffSize = sizeOf.BYTE; +encode.SID = encode.USHORT; +sizeOf.SID = sizeOf.USHORT; +encode.NUMBER = function(v) { + if (v >= -107 && v <= 107) { + return [v + 139]; + } else if (v >= 108 && v <= 1131) { + v = v - 108; + return [(v >> 8) + 247, v & 255]; + } else if (v >= -1131 && v <= -108) { + v = -v - 108; + return [(v >> 8) + 251, v & 255]; + } else if (v >= -32768 && v <= 32767) { + return encode.NUMBER16(v); + } else { + return encode.NUMBER32(v); + } +}; +sizeOf.NUMBER = function(v) { + return encode.NUMBER(v).length; +}; +encode.NUMBER16 = function(v) { + return [28, v >> 8 & 255, v & 255]; +}; +sizeOf.NUMBER16 = constant(3); +encode.NUMBER32 = function(v) { + return [29, v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.NUMBER32 = constant(5); +encode.REAL = function(v) { + var value2 = v.toString(); + var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value2); + if (m) { + var epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length)); + value2 = (Math.round(v * epsilon) / epsilon).toString(); + } + var nibbles = ""; + for (var i = 0, ii = value2.length;i < ii; i += 1) { + var c = value2[i]; + if (c === "e") { + nibbles += value2[++i] === "-" ? "c" : "b"; + } else if (c === ".") { + nibbles += "a"; + } else if (c === "-") { + nibbles += "e"; + } else { + nibbles += c; + } + } + nibbles += nibbles.length & 1 ? "f" : "ff"; + var out = [30]; + for (var i$1 = 0, ii$1 = nibbles.length;i$1 < ii$1; i$1 += 2) { + out.push(parseInt(nibbles.substr(i$1, 2), 16)); + } + return out; +}; +sizeOf.REAL = function(v) { + return encode.REAL(v).length; +}; +encode.NAME = encode.CHARARRAY; +sizeOf.NAME = sizeOf.CHARARRAY; +encode.STRING = encode.CHARARRAY; +sizeOf.STRING = sizeOf.CHARARRAY; +decode.UTF8 = function(data2, offset, numBytes) { + var codePoints = []; + var numChars = numBytes; + for (var j2 = 0;j2 < numChars; j2++, offset += 1) { + codePoints[j2] = data2.getUint8(offset); + } + return String.fromCharCode.apply(null, codePoints); +}; +decode.UTF16 = function(data2, offset, numBytes) { + var codePoints = []; + var numChars = numBytes / 2; + for (var j2 = 0;j2 < numChars; j2++, offset += 2) { + codePoints[j2] = data2.getUint16(offset); + } + return String.fromCharCode.apply(null, codePoints); +}; +encode.UTF16 = function(v) { + var b = []; + for (var i = 0;i < v.length; i += 1) { + var codepoint = v.charCodeAt(i); + b[b.length] = codepoint >> 8 & 255; + b[b.length] = codepoint & 255; + } + return b; +}; +sizeOf.UTF16 = function(v) { + return v.length * 2; +}; +var eightBitMacEncodings = { + "x-mac-croatian": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø" + "¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ", + "x-mac-cyrillic": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ" + "јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю", + "x-mac-gaelic": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø" + "ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ", + "x-mac-greek": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ" + "άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­", + "x-mac-icelandic": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø" + "¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", + "x-mac-inuit": "ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ" + "ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł", + "x-mac-ce": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ" + "ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ", + macintosh: "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø" + "¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", + "x-mac-romanian": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș" + "¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", + "x-mac-turkish": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø" + "¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ" +}; +decode.MACSTRING = function(dataView, offset, dataLength, encoding) { + var table = eightBitMacEncodings[encoding]; + if (table === undefined) { + return; + } + var result = ""; + for (var i = 0;i < dataLength; i++) { + var c = dataView.getUint8(offset + i); + if (c <= 127) { + result += String.fromCharCode(c); + } else { + result += table[c & 127]; + } + } + return result; +}; +var macEncodingTableCache = typeof WeakMap === "function" && new WeakMap; +var macEncodingCacheKeys; +var getMacEncodingTable = function(encoding) { + if (!macEncodingCacheKeys) { + macEncodingCacheKeys = {}; + for (var e in eightBitMacEncodings) { + macEncodingCacheKeys[e] = new String(e); + } + } + var cacheKey = macEncodingCacheKeys[encoding]; + if (cacheKey === undefined) { + return; + } + if (macEncodingTableCache) { + var cachedTable = macEncodingTableCache.get(cacheKey); + if (cachedTable !== undefined) { + return cachedTable; + } + } + var decodingTable = eightBitMacEncodings[encoding]; + if (decodingTable === undefined) { + return; + } + var encodingTable = {}; + for (var i = 0;i < decodingTable.length; i++) { + encodingTable[decodingTable.charCodeAt(i)] = i + 128; + } + if (macEncodingTableCache) { + macEncodingTableCache.set(cacheKey, encodingTable); + } + return encodingTable; +}; +encode.MACSTRING = function(str, encoding) { + var table = getMacEncodingTable(encoding); + if (table === undefined) { + return; + } + var result = []; + for (var i = 0;i < str.length; i++) { + var c = str.charCodeAt(i); + if (c >= 128) { + c = table[c]; + if (c === undefined) { + return; + } + } + result[i] = c; + } + return result; +}; +sizeOf.MACSTRING = function(str, encoding) { + var b = encode.MACSTRING(str, encoding); + if (b !== undefined) { + return b.length; + } else { + return 0; + } +}; +function isByteEncodable(value2) { + return value2 >= -128 && value2 <= 127; +} +function encodeVarDeltaRunAsZeroes(deltas, pos, result) { + var runLength = 0; + var numDeltas = deltas.length; + while (pos < numDeltas && runLength < 64 && deltas[pos] === 0) { + ++pos; + ++runLength; + } + result.push(128 | runLength - 1); + return pos; +} +function encodeVarDeltaRunAsBytes(deltas, offset, result) { + var runLength = 0; + var numDeltas = deltas.length; + var pos = offset; + while (pos < numDeltas && runLength < 64) { + var value2 = deltas[pos]; + if (!isByteEncodable(value2)) { + break; + } + if (value2 === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) { + break; + } + ++pos; + ++runLength; + } + result.push(runLength - 1); + for (var i = offset;i < pos; ++i) { + result.push(deltas[i] + 256 & 255); + } + return pos; +} +function encodeVarDeltaRunAsWords(deltas, offset, result) { + var runLength = 0; + var numDeltas = deltas.length; + var pos = offset; + while (pos < numDeltas && runLength < 64) { + var value2 = deltas[pos]; + if (value2 === 0) { + break; + } + if (isByteEncodable(value2) && pos + 1 < numDeltas && isByteEncodable(deltas[pos + 1])) { + break; + } + ++pos; + ++runLength; + } + result.push(64 | runLength - 1); + for (var i = offset;i < pos; ++i) { + var val2 = deltas[i]; + result.push(val2 + 65536 >> 8 & 255, val2 + 256 & 255); + } + return pos; +} +encode.VARDELTAS = function(deltas) { + var pos = 0; + var result = []; + while (pos < deltas.length) { + var value2 = deltas[pos]; + if (value2 === 0) { + pos = encodeVarDeltaRunAsZeroes(deltas, pos, result); + } else if (value2 >= -128 && value2 <= 127) { + pos = encodeVarDeltaRunAsBytes(deltas, pos, result); + } else { + pos = encodeVarDeltaRunAsWords(deltas, pos, result); + } + } + return result; +}; +encode.INDEX = function(l2) { + var offset = 1; + var offsets = [offset]; + var data2 = []; + for (var i = 0;i < l2.length; i += 1) { + var v = encode.OBJECT(l2[i]); + Array.prototype.push.apply(data2, v); + offset += v.length; + offsets.push(offset); + } + if (data2.length === 0) { + return [0, 0]; + } + var encodedOffsets = []; + var offSize = 1 + Math.floor(Math.log(offset) / Math.log(2)) / 8 | 0; + var offsetEncoder = [undefined, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize]; + for (var i$1 = 0;i$1 < offsets.length; i$1 += 1) { + var encodedOffset = offsetEncoder(offsets[i$1]); + Array.prototype.push.apply(encodedOffsets, encodedOffset); + } + return Array.prototype.concat(encode.Card16(l2.length), encode.OffSize(offSize), encodedOffsets, data2); +}; +sizeOf.INDEX = function(v) { + return encode.INDEX(v).length; +}; +encode.DICT = function(m) { + var d = []; + var keys2 = Object.keys(m); + var length2 = keys2.length; + for (var i = 0;i < length2; i += 1) { + var k2 = parseInt(keys2[i], 0); + var v = m[k2]; + d = d.concat(encode.OPERAND(v.value, v.type)); + d = d.concat(encode.OPERATOR(k2)); + } + return d; +}; +sizeOf.DICT = function(m) { + return encode.DICT(m).length; +}; +encode.OPERATOR = function(v) { + if (v < 1200) { + return [v]; + } else { + return [12, v - 1200]; + } +}; +encode.OPERAND = function(v, type) { + var d = []; + if (Array.isArray(type)) { + for (var i = 0;i < type.length; i += 1) { + check.argument(v.length === type.length, "Not enough arguments given for type" + type); + d = d.concat(encode.OPERAND(v[i], type[i])); + } + } else { + if (type === "SID") { + d = d.concat(encode.NUMBER(v)); + } else if (type === "offset") { + d = d.concat(encode.NUMBER32(v)); + } else if (type === "number") { + d = d.concat(encode.NUMBER(v)); + } else if (type === "real") { + d = d.concat(encode.REAL(v)); + } else { + throw new Error("Unknown operand type " + type); + } + } + return d; +}; +encode.OP = encode.BYTE; +sizeOf.OP = sizeOf.BYTE; +var wmm = typeof WeakMap === "function" && new WeakMap; +encode.CHARSTRING = function(ops) { + if (wmm) { + var cachedValue = wmm.get(ops); + if (cachedValue !== undefined) { + return cachedValue; + } + } + var d = []; + var length2 = ops.length; + for (var i = 0;i < length2; i += 1) { + var op = ops[i]; + d = d.concat(encode[op.type](op.value)); + } + if (wmm) { + wmm.set(ops, d); + } + return d; +}; +sizeOf.CHARSTRING = function(ops) { + return encode.CHARSTRING(ops).length; +}; +encode.OBJECT = function(v) { + var encodingFunction = encode[v.type]; + check.argument(encodingFunction !== undefined, "No encoding function for type " + v.type); + return encodingFunction(v.value); +}; +sizeOf.OBJECT = function(v) { + var sizeOfFunction = sizeOf[v.type]; + check.argument(sizeOfFunction !== undefined, "No sizeOf function for type " + v.type); + return sizeOfFunction(v.value); +}; +encode.TABLE = function(table) { + var d = []; + var length2 = table.fields.length; + var subtables = []; + var subtableOffsets = []; + for (var i = 0;i < length2; i += 1) { + var field = table.fields[i]; + var encodingFunction = encode[field.type]; + check.argument(encodingFunction !== undefined, "No encoding function for field type " + field.type + " (" + field.name + ")"); + var value2 = table[field.name]; + if (value2 === undefined) { + value2 = field.value; + } + var bytes = encodingFunction(value2); + if (field.type === "TABLE") { + subtableOffsets.push(d.length); + d = d.concat([0, 0]); + subtables.push(bytes); + } else { + d = d.concat(bytes); + } + } + for (var i$1 = 0;i$1 < subtables.length; i$1 += 1) { + var o = subtableOffsets[i$1]; + var offset = d.length; + check.argument(offset < 65536, "Table " + table.tableName + " too big."); + d[o] = offset >> 8; + d[o + 1] = offset & 255; + d = d.concat(subtables[i$1]); + } + return d; +}; +sizeOf.TABLE = function(table) { + var numBytes = 0; + var length2 = table.fields.length; + for (var i = 0;i < length2; i += 1) { + var field = table.fields[i]; + var sizeOfFunction = sizeOf[field.type]; + check.argument(sizeOfFunction !== undefined, "No sizeOf function for field type " + field.type + " (" + field.name + ")"); + var value2 = table[field.name]; + if (value2 === undefined) { + value2 = field.value; + } + numBytes += sizeOfFunction(value2); + if (field.type === "TABLE") { + numBytes += 2; + } + } + return numBytes; +}; +encode.RECORD = encode.TABLE; +sizeOf.RECORD = sizeOf.TABLE; +encode.LITERAL = function(v) { + return v; +}; +sizeOf.LITERAL = function(v) { + return v.length; +}; +function Table(tableName, fields, options) { + if (fields.length && (fields[0].name !== "coverageFormat" || fields[0].value === 1)) { + for (var i = 0;i < fields.length; i += 1) { + var field = fields[i]; + this[field.name] = field.value; + } + } + this.tableName = tableName; + this.fields = fields; + if (options) { + var optionKeys = Object.keys(options); + for (var i$1 = 0;i$1 < optionKeys.length; i$1 += 1) { + var k2 = optionKeys[i$1]; + var v = options[k2]; + if (this[k2] !== undefined) { + this[k2] = v; + } + } + } +} +Table.prototype.encode = function() { + return encode.TABLE(this); +}; +Table.prototype.sizeOf = function() { + return sizeOf.TABLE(this); +}; +function ushortList(itemName, list, count) { + if (count === undefined) { + count = list.length; + } + var fields = new Array(list.length + 1); + fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; + for (var i = 0;i < list.length; i++) { + fields[i + 1] = { name: itemName + i, type: "USHORT", value: list[i] }; + } + return fields; +} +function tableList(itemName, records, itemCallback) { + var count = records.length; + var fields = new Array(count + 1); + fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; + for (var i = 0;i < count; i++) { + fields[i + 1] = { name: itemName + i, type: "TABLE", value: itemCallback(records[i], i) }; + } + return fields; +} +function recordList(itemName, records, itemCallback) { + var count = records.length; + var fields = []; + fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; + for (var i = 0;i < count; i++) { + fields = fields.concat(itemCallback(records[i], i)); + } + return fields; +} +function Coverage(coverageTable) { + if (coverageTable.format === 1) { + Table.call(this, "coverageTable", [{ name: "coverageFormat", type: "USHORT", value: 1 }].concat(ushortList("glyph", coverageTable.glyphs))); + } else if (coverageTable.format === 2) { + Table.call(this, "coverageTable", [{ name: "coverageFormat", type: "USHORT", value: 2 }].concat(recordList("rangeRecord", coverageTable.ranges, function(RangeRecord) { + return [ + { name: "startGlyphID", type: "USHORT", value: RangeRecord.start }, + { name: "endGlyphID", type: "USHORT", value: RangeRecord.end }, + { name: "startCoverageIndex", type: "USHORT", value: RangeRecord.index } + ]; + }))); + } else { + check.assert(false, "Coverage format must be 1 or 2."); + } +} +Coverage.prototype = Object.create(Table.prototype); +Coverage.prototype.constructor = Coverage; +function ScriptList(scriptListTable) { + Table.call(this, "scriptListTable", recordList("scriptRecord", scriptListTable, function(scriptRecord, i) { + var script = scriptRecord.script; + var defaultLangSys = script.defaultLangSys; + check.assert(!!defaultLangSys, "Unable to write GSUB: script " + scriptRecord.tag + " has no default language system."); + return [ + { name: "scriptTag" + i, type: "TAG", value: scriptRecord.tag }, + { name: "script" + i, type: "TABLE", value: new Table("scriptTable", [ + { name: "defaultLangSys", type: "TABLE", value: new Table("defaultLangSys", [ + { name: "lookupOrder", type: "USHORT", value: 0 }, + { name: "reqFeatureIndex", type: "USHORT", value: defaultLangSys.reqFeatureIndex } + ].concat(ushortList("featureIndex", defaultLangSys.featureIndexes))) } + ].concat(recordList("langSys", script.langSysRecords, function(langSysRecord, i3) { + var langSys = langSysRecord.langSys; + return [ + { name: "langSysTag" + i3, type: "TAG", value: langSysRecord.tag }, + { name: "langSys" + i3, type: "TABLE", value: new Table("langSys", [ + { name: "lookupOrder", type: "USHORT", value: 0 }, + { name: "reqFeatureIndex", type: "USHORT", value: langSys.reqFeatureIndex } + ].concat(ushortList("featureIndex", langSys.featureIndexes))) } + ]; + }))) } + ]; + })); +} +ScriptList.prototype = Object.create(Table.prototype); +ScriptList.prototype.constructor = ScriptList; +function FeatureList(featureListTable) { + Table.call(this, "featureListTable", recordList("featureRecord", featureListTable, function(featureRecord, i) { + var feature = featureRecord.feature; + return [ + { name: "featureTag" + i, type: "TAG", value: featureRecord.tag }, + { name: "feature" + i, type: "TABLE", value: new Table("featureTable", [ + { name: "featureParams", type: "USHORT", value: feature.featureParams } + ].concat(ushortList("lookupListIndex", feature.lookupListIndexes))) } + ]; + })); +} +FeatureList.prototype = Object.create(Table.prototype); +FeatureList.prototype.constructor = FeatureList; +function LookupList(lookupListTable, subtableMakers) { + Table.call(this, "lookupListTable", tableList("lookup", lookupListTable, function(lookupTable) { + var subtableCallback = subtableMakers[lookupTable.lookupType]; + check.assert(!!subtableCallback, "Unable to write GSUB lookup type " + lookupTable.lookupType + " tables."); + return new Table("lookupTable", [ + { name: "lookupType", type: "USHORT", value: lookupTable.lookupType }, + { name: "lookupFlag", type: "USHORT", value: lookupTable.lookupFlag } + ].concat(tableList("subtable", lookupTable.subtables, subtableCallback))); + })); +} +LookupList.prototype = Object.create(Table.prototype); +LookupList.prototype.constructor = LookupList; +var table = { + Table, + Record: Table, + Coverage, + ScriptList, + FeatureList, + LookupList, + ushortList, + tableList, + recordList +}; +function getByte(dataView, offset) { + return dataView.getUint8(offset); +} +function getUShort(dataView, offset) { + return dataView.getUint16(offset, false); +} +function getShort(dataView, offset) { + return dataView.getInt16(offset, false); +} +function getULong(dataView, offset) { + return dataView.getUint32(offset, false); +} +function getFixed(dataView, offset) { + var decimal = dataView.getInt16(offset, false); + var fraction = dataView.getUint16(offset + 2, false); + return decimal + fraction / 65535; +} +function getTag(dataView, offset) { + var tag = ""; + for (var i = offset;i < offset + 4; i += 1) { + tag += String.fromCharCode(dataView.getInt8(i)); + } + return tag; +} +function getOffset(dataView, offset, offSize) { + var v = 0; + for (var i = 0;i < offSize; i += 1) { + v <<= 8; + v += dataView.getUint8(offset + i); + } + return v; +} +function getBytes(dataView, startOffset, endOffset) { + var bytes = []; + for (var i = startOffset;i < endOffset; i += 1) { + bytes.push(dataView.getUint8(i)); + } + return bytes; +} +function bytesToString(bytes) { + var s = ""; + for (var i = 0;i < bytes.length; i += 1) { + s += String.fromCharCode(bytes[i]); + } + return s; +} +var typeOffsets = { + byte: 1, + uShort: 2, + short: 2, + uLong: 4, + fixed: 4, + longDateTime: 8, + tag: 4 +}; +function Parser(data2, offset) { + this.data = data2; + this.offset = offset; + this.relativeOffset = 0; +} +Parser.prototype.parseByte = function() { + var v = this.data.getUint8(this.offset + this.relativeOffset); + this.relativeOffset += 1; + return v; +}; +Parser.prototype.parseChar = function() { + var v = this.data.getInt8(this.offset + this.relativeOffset); + this.relativeOffset += 1; + return v; +}; +Parser.prototype.parseCard8 = Parser.prototype.parseByte; +Parser.prototype.parseUShort = function() { + var v = this.data.getUint16(this.offset + this.relativeOffset); + this.relativeOffset += 2; + return v; +}; +Parser.prototype.parseCard16 = Parser.prototype.parseUShort; +Parser.prototype.parseSID = Parser.prototype.parseUShort; +Parser.prototype.parseOffset16 = Parser.prototype.parseUShort; +Parser.prototype.parseShort = function() { + var v = this.data.getInt16(this.offset + this.relativeOffset); + this.relativeOffset += 2; + return v; +}; +Parser.prototype.parseF2Dot14 = function() { + var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384; + this.relativeOffset += 2; + return v; +}; +Parser.prototype.parseULong = function() { + var v = getULong(this.data, this.offset + this.relativeOffset); + this.relativeOffset += 4; + return v; +}; +Parser.prototype.parseOffset32 = Parser.prototype.parseULong; +Parser.prototype.parseFixed = function() { + var v = getFixed(this.data, this.offset + this.relativeOffset); + this.relativeOffset += 4; + return v; +}; +Parser.prototype.parseString = function(length2) { + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + var string = ""; + this.relativeOffset += length2; + for (var i = 0;i < length2; i++) { + string += String.fromCharCode(dataView.getUint8(offset + i)); + } + return string; +}; +Parser.prototype.parseTag = function() { + return this.parseString(4); +}; +Parser.prototype.parseLongDateTime = function() { + var v = getULong(this.data, this.offset + this.relativeOffset + 4); + v -= 2082844800; + this.relativeOffset += 8; + return v; +}; +Parser.prototype.parseVersion = function(minorBase) { + var major = getUShort(this.data, this.offset + this.relativeOffset); + var minor = getUShort(this.data, this.offset + this.relativeOffset + 2); + this.relativeOffset += 4; + if (minorBase === undefined) { + minorBase = 4096; + } + return major + minor / minorBase / 10; +}; +Parser.prototype.skip = function(type, amount) { + if (amount === undefined) { + amount = 1; + } + this.relativeOffset += typeOffsets[type] * amount; +}; +Parser.prototype.parseULongList = function(count) { + if (count === undefined) { + count = this.parseULong(); + } + var offsets = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0;i < count; i++) { + offsets[i] = dataView.getUint32(offset); + offset += 4; + } + this.relativeOffset += count * 4; + return offsets; +}; +Parser.prototype.parseOffset16List = Parser.prototype.parseUShortList = function(count) { + if (count === undefined) { + count = this.parseUShort(); + } + var offsets = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0;i < count; i++) { + offsets[i] = dataView.getUint16(offset); + offset += 2; + } + this.relativeOffset += count * 2; + return offsets; +}; +Parser.prototype.parseShortList = function(count) { + var list = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0;i < count; i++) { + list[i] = dataView.getInt16(offset); + offset += 2; + } + this.relativeOffset += count * 2; + return list; +}; +Parser.prototype.parseByteList = function(count) { + var list = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0;i < count; i++) { + list[i] = dataView.getUint8(offset++); + } + this.relativeOffset += count; + return list; +}; +Parser.prototype.parseList = function(count, itemCallback) { + if (!itemCallback) { + itemCallback = count; + count = this.parseUShort(); + } + var list = new Array(count); + for (var i = 0;i < count; i++) { + list[i] = itemCallback.call(this); + } + return list; +}; +Parser.prototype.parseList32 = function(count, itemCallback) { + if (!itemCallback) { + itemCallback = count; + count = this.parseULong(); + } + var list = new Array(count); + for (var i = 0;i < count; i++) { + list[i] = itemCallback.call(this); + } + return list; +}; +Parser.prototype.parseRecordList = function(count, recordDescription) { + if (!recordDescription) { + recordDescription = count; + count = this.parseUShort(); + } + var records = new Array(count); + var fields = Object.keys(recordDescription); + for (var i = 0;i < count; i++) { + var rec = {}; + for (var j2 = 0;j2 < fields.length; j2++) { + var fieldName = fields[j2]; + var fieldType = recordDescription[fieldName]; + rec[fieldName] = fieldType.call(this); + } + records[i] = rec; + } + return records; +}; +Parser.prototype.parseRecordList32 = function(count, recordDescription) { + if (!recordDescription) { + recordDescription = count; + count = this.parseULong(); + } + var records = new Array(count); + var fields = Object.keys(recordDescription); + for (var i = 0;i < count; i++) { + var rec = {}; + for (var j2 = 0;j2 < fields.length; j2++) { + var fieldName = fields[j2]; + var fieldType = recordDescription[fieldName]; + rec[fieldName] = fieldType.call(this); + } + records[i] = rec; + } + return records; +}; +Parser.prototype.parseStruct = function(description) { + if (typeof description === "function") { + return description.call(this); + } else { + var fields = Object.keys(description); + var struct = {}; + for (var j2 = 0;j2 < fields.length; j2++) { + var fieldName = fields[j2]; + var fieldType = description[fieldName]; + struct[fieldName] = fieldType.call(this); + } + return struct; + } +}; +Parser.prototype.parseValueRecord = function(valueFormat) { + if (valueFormat === undefined) { + valueFormat = this.parseUShort(); + } + if (valueFormat === 0) { + return; + } + var valueRecord = {}; + if (valueFormat & 1) { + valueRecord.xPlacement = this.parseShort(); + } + if (valueFormat & 2) { + valueRecord.yPlacement = this.parseShort(); + } + if (valueFormat & 4) { + valueRecord.xAdvance = this.parseShort(); + } + if (valueFormat & 8) { + valueRecord.yAdvance = this.parseShort(); + } + if (valueFormat & 16) { + valueRecord.xPlaDevice = undefined; + this.parseShort(); + } + if (valueFormat & 32) { + valueRecord.yPlaDevice = undefined; + this.parseShort(); + } + if (valueFormat & 64) { + valueRecord.xAdvDevice = undefined; + this.parseShort(); + } + if (valueFormat & 128) { + valueRecord.yAdvDevice = undefined; + this.parseShort(); + } + return valueRecord; +}; +Parser.prototype.parseValueRecordList = function() { + var valueFormat = this.parseUShort(); + var valueCount = this.parseUShort(); + var values2 = new Array(valueCount); + for (var i = 0;i < valueCount; i++) { + values2[i] = this.parseValueRecord(valueFormat); + } + return values2; +}; +Parser.prototype.parsePointer = function(description) { + var structOffset = this.parseOffset16(); + if (structOffset > 0) { + return new Parser(this.data, this.offset + structOffset).parseStruct(description); + } + return; +}; +Parser.prototype.parsePointer32 = function(description) { + var structOffset = this.parseOffset32(); + if (structOffset > 0) { + return new Parser(this.data, this.offset + structOffset).parseStruct(description); + } + return; +}; +Parser.prototype.parseListOfLists = function(itemCallback) { + var offsets = this.parseOffset16List(); + var count = offsets.length; + var relativeOffset = this.relativeOffset; + var list = new Array(count); + for (var i = 0;i < count; i++) { + var start = offsets[i]; + if (start === 0) { + list[i] = undefined; + continue; + } + this.relativeOffset = start; + if (itemCallback) { + var subOffsets = this.parseOffset16List(); + var subList = new Array(subOffsets.length); + for (var j2 = 0;j2 < subOffsets.length; j2++) { + this.relativeOffset = start + subOffsets[j2]; + subList[j2] = itemCallback.call(this); + } + list[i] = subList; + } else { + list[i] = this.parseUShortList(); + } + } + this.relativeOffset = relativeOffset; + return list; +}; +Parser.prototype.parseCoverage = function() { + var startOffset = this.offset + this.relativeOffset; + var format = this.parseUShort(); + var count = this.parseUShort(); + if (format === 1) { + return { + format: 1, + glyphs: this.parseUShortList(count) + }; + } else if (format === 2) { + var ranges = new Array(count); + for (var i = 0;i < count; i++) { + ranges[i] = { + start: this.parseUShort(), + end: this.parseUShort(), + index: this.parseUShort() + }; + } + return { + format: 2, + ranges + }; + } + throw new Error("0x" + startOffset.toString(16) + ": Coverage format must be 1 or 2."); +}; +Parser.prototype.parseClassDef = function() { + var startOffset = this.offset + this.relativeOffset; + var format = this.parseUShort(); + if (format === 1) { + return { + format: 1, + startGlyph: this.parseUShort(), + classes: this.parseUShortList() + }; + } else if (format === 2) { + return { + format: 2, + ranges: this.parseRecordList({ + start: Parser.uShort, + end: Parser.uShort, + classId: Parser.uShort + }) + }; + } + throw new Error("0x" + startOffset.toString(16) + ": ClassDef format must be 1 or 2."); +}; +Parser.list = function(count, itemCallback) { + return function() { + return this.parseList(count, itemCallback); + }; +}; +Parser.list32 = function(count, itemCallback) { + return function() { + return this.parseList32(count, itemCallback); + }; +}; +Parser.recordList = function(count, recordDescription) { + return function() { + return this.parseRecordList(count, recordDescription); + }; +}; +Parser.recordList32 = function(count, recordDescription) { + return function() { + return this.parseRecordList32(count, recordDescription); + }; +}; +Parser.pointer = function(description) { + return function() { + return this.parsePointer(description); + }; +}; +Parser.pointer32 = function(description) { + return function() { + return this.parsePointer32(description); + }; +}; +Parser.tag = Parser.prototype.parseTag; +Parser.byte = Parser.prototype.parseByte; +Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort; +Parser.uShortList = Parser.prototype.parseUShortList; +Parser.uLong = Parser.offset32 = Parser.prototype.parseULong; +Parser.uLongList = Parser.prototype.parseULongList; +Parser.struct = Parser.prototype.parseStruct; +Parser.coverage = Parser.prototype.parseCoverage; +Parser.classDef = Parser.prototype.parseClassDef; +var langSysTable = { + reserved: Parser.uShort, + reqFeatureIndex: Parser.uShort, + featureIndexes: Parser.uShortList +}; +Parser.prototype.parseScriptList = function() { + return this.parsePointer(Parser.recordList({ + tag: Parser.tag, + script: Parser.pointer({ + defaultLangSys: Parser.pointer(langSysTable), + langSysRecords: Parser.recordList({ + tag: Parser.tag, + langSys: Parser.pointer(langSysTable) + }) + }) + })) || []; +}; +Parser.prototype.parseFeatureList = function() { + return this.parsePointer(Parser.recordList({ + tag: Parser.tag, + feature: Parser.pointer({ + featureParams: Parser.offset16, + lookupListIndexes: Parser.uShortList + }) + })) || []; +}; +Parser.prototype.parseLookupList = function(lookupTableParsers) { + return this.parsePointer(Parser.list(Parser.pointer(function() { + var lookupType = this.parseUShort(); + check.argument(1 <= lookupType && lookupType <= 9, "GPOS/GSUB lookup type " + lookupType + " unknown."); + var lookupFlag = this.parseUShort(); + var useMarkFilteringSet = lookupFlag & 16; + return { + lookupType, + lookupFlag, + subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])), + markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined + }; + }))) || []; +}; +Parser.prototype.parseFeatureVariationsList = function() { + return this.parsePointer32(function() { + var majorVersion = this.parseUShort(); + var minorVersion = this.parseUShort(); + check.argument(majorVersion === 1 && minorVersion < 1, "GPOS/GSUB feature variations table unknown."); + var featureVariations = this.parseRecordList32({ + conditionSetOffset: Parser.offset32, + featureTableSubstitutionOffset: Parser.offset32 + }); + return featureVariations; + }) || []; +}; +var parse = { + getByte, + getCard8: getByte, + getUShort, + getCard16: getUShort, + getShort, + getULong, + getFixed, + getTag, + getOffset, + getBytes, + bytesToString, + Parser +}; +function parseCmapTableFormat12(cmap, p) { + p.parseUShort(); + cmap.length = p.parseULong(); + cmap.language = p.parseULong(); + var groupCount; + cmap.groupCount = groupCount = p.parseULong(); + cmap.glyphIndexMap = {}; + for (var i = 0;i < groupCount; i += 1) { + var startCharCode = p.parseULong(); + var endCharCode = p.parseULong(); + var startGlyphId = p.parseULong(); + for (var c = startCharCode;c <= endCharCode; c += 1) { + cmap.glyphIndexMap[c] = startGlyphId; + startGlyphId++; + } + } +} +function parseCmapTableFormat4(cmap, p, data2, start, offset) { + cmap.length = p.parseUShort(); + cmap.language = p.parseUShort(); + var segCount; + cmap.segCount = segCount = p.parseUShort() >> 1; + p.skip("uShort", 3); + cmap.glyphIndexMap = {}; + var endCountParser = new parse.Parser(data2, start + offset + 14); + var startCountParser = new parse.Parser(data2, start + offset + 16 + segCount * 2); + var idDeltaParser = new parse.Parser(data2, start + offset + 16 + segCount * 4); + var idRangeOffsetParser = new parse.Parser(data2, start + offset + 16 + segCount * 6); + var glyphIndexOffset = start + offset + 16 + segCount * 8; + for (var i = 0;i < segCount - 1; i += 1) { + var glyphIndex = undefined; + var endCount = endCountParser.parseUShort(); + var startCount = startCountParser.parseUShort(); + var idDelta = idDeltaParser.parseShort(); + var idRangeOffset = idRangeOffsetParser.parseUShort(); + for (var c = startCount;c <= endCount; c += 1) { + if (idRangeOffset !== 0) { + glyphIndexOffset = idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2; + glyphIndexOffset += idRangeOffset; + glyphIndexOffset += (c - startCount) * 2; + glyphIndex = parse.getUShort(data2, glyphIndexOffset); + if (glyphIndex !== 0) { + glyphIndex = glyphIndex + idDelta & 65535; + } + } else { + glyphIndex = c + idDelta & 65535; + } + cmap.glyphIndexMap[c] = glyphIndex; + } + } +} +function parseCmapTable(data2, start) { + var cmap = {}; + cmap.version = parse.getUShort(data2, start); + check.argument(cmap.version === 0, "cmap table version should be 0."); + cmap.numTables = parse.getUShort(data2, start + 2); + var offset = -1; + for (var i = cmap.numTables - 1;i >= 0; i -= 1) { + var platformId = parse.getUShort(data2, start + 4 + i * 8); + var encodingId = parse.getUShort(data2, start + 4 + i * 8 + 2); + if (platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10) || platformId === 0 && (encodingId === 0 || encodingId === 1 || encodingId === 2 || encodingId === 3 || encodingId === 4)) { + offset = parse.getULong(data2, start + 4 + i * 8 + 4); + break; + } + } + if (offset === -1) { + throw new Error("No valid cmap sub-tables found."); + } + var p = new parse.Parser(data2, start + offset); + cmap.format = p.parseUShort(); + if (cmap.format === 12) { + parseCmapTableFormat12(cmap, p); + } else if (cmap.format === 4) { + parseCmapTableFormat4(cmap, p, data2, start, offset); + } else { + throw new Error("Only format 4 and 12 cmap tables are supported (found format " + cmap.format + ")."); + } + return cmap; +} +function addSegment(t4, code, glyphIndex) { + t4.segments.push({ + end: code, + start: code, + delta: -(code - glyphIndex), + offset: 0, + glyphIndex + }); +} +function addTerminatorSegment(t4) { + t4.segments.push({ + end: 65535, + start: 65535, + delta: 1, + offset: 0 + }); +} +function makeCmapTable(glyphs) { + var isPlan0Only = true; + var i; + for (i = glyphs.length - 1;i > 0; i -= 1) { + var g3 = glyphs.get(i); + if (g3.unicode > 65535) { + console.log("Adding CMAP format 12 (needed!)"); + isPlan0Only = false; + break; + } + } + var cmapTable = [ + { name: "version", type: "USHORT", value: 0 }, + { name: "numTables", type: "USHORT", value: isPlan0Only ? 1 : 2 }, + { name: "platformID", type: "USHORT", value: 3 }, + { name: "encodingID", type: "USHORT", value: 1 }, + { name: "offset", type: "ULONG", value: isPlan0Only ? 12 : 12 + 8 } + ]; + if (!isPlan0Only) { + cmapTable = cmapTable.concat([ + { name: "cmap12PlatformID", type: "USHORT", value: 3 }, + { name: "cmap12EncodingID", type: "USHORT", value: 10 }, + { name: "cmap12Offset", type: "ULONG", value: 0 } + ]); + } + cmapTable = cmapTable.concat([ + { name: "format", type: "USHORT", value: 4 }, + { name: "cmap4Length", type: "USHORT", value: 0 }, + { name: "language", type: "USHORT", value: 0 }, + { name: "segCountX2", type: "USHORT", value: 0 }, + { name: "searchRange", type: "USHORT", value: 0 }, + { name: "entrySelector", type: "USHORT", value: 0 }, + { name: "rangeShift", type: "USHORT", value: 0 } + ]); + var t4 = new table.Table("cmap", cmapTable); + t4.segments = []; + for (i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + for (var j2 = 0;j2 < glyph.unicodes.length; j2 += 1) { + addSegment(t4, glyph.unicodes[j2], i); + } + t4.segments = t4.segments.sort(function(a, b) { + return a.start - b.start; + }); + } + addTerminatorSegment(t4); + var segCount = t4.segments.length; + var segCountToRemove = 0; + var endCounts = []; + var startCounts = []; + var idDeltas = []; + var idRangeOffsets = []; + var glyphIds = []; + var cmap12Groups = []; + for (i = 0;i < segCount; i += 1) { + var segment = t4.segments[i]; + if (segment.end <= 65535 && segment.start <= 65535) { + endCounts = endCounts.concat({ name: "end_" + i, type: "USHORT", value: segment.end }); + startCounts = startCounts.concat({ name: "start_" + i, type: "USHORT", value: segment.start }); + idDeltas = idDeltas.concat({ name: "idDelta_" + i, type: "SHORT", value: segment.delta }); + idRangeOffsets = idRangeOffsets.concat({ name: "idRangeOffset_" + i, type: "USHORT", value: segment.offset }); + if (segment.glyphId !== undefined) { + glyphIds = glyphIds.concat({ name: "glyph_" + i, type: "USHORT", value: segment.glyphId }); + } + } else { + segCountToRemove += 1; + } + if (!isPlan0Only && segment.glyphIndex !== undefined) { + cmap12Groups = cmap12Groups.concat({ name: "cmap12Start_" + i, type: "ULONG", value: segment.start }); + cmap12Groups = cmap12Groups.concat({ name: "cmap12End_" + i, type: "ULONG", value: segment.end }); + cmap12Groups = cmap12Groups.concat({ name: "cmap12Glyph_" + i, type: "ULONG", value: segment.glyphIndex }); + } + } + t4.segCountX2 = (segCount - segCountToRemove) * 2; + t4.searchRange = Math.pow(2, Math.floor(Math.log(segCount - segCountToRemove) / Math.log(2))) * 2; + t4.entrySelector = Math.log(t4.searchRange / 2) / Math.log(2); + t4.rangeShift = t4.segCountX2 - t4.searchRange; + t4.fields = t4.fields.concat(endCounts); + t4.fields.push({ name: "reservedPad", type: "USHORT", value: 0 }); + t4.fields = t4.fields.concat(startCounts); + t4.fields = t4.fields.concat(idDeltas); + t4.fields = t4.fields.concat(idRangeOffsets); + t4.fields = t4.fields.concat(glyphIds); + t4.cmap4Length = 14 + endCounts.length * 2 + 2 + startCounts.length * 2 + idDeltas.length * 2 + idRangeOffsets.length * 2 + glyphIds.length * 2; + if (!isPlan0Only) { + var cmap12Length = 16 + cmap12Groups.length * 4; + t4.cmap12Offset = 12 + 2 * 2 + 4 + t4.cmap4Length; + t4.fields = t4.fields.concat([ + { name: "cmap12Format", type: "USHORT", value: 12 }, + { name: "cmap12Reserved", type: "USHORT", value: 0 }, + { name: "cmap12Length", type: "ULONG", value: cmap12Length }, + { name: "cmap12Language", type: "ULONG", value: 0 }, + { name: "cmap12nGroups", type: "ULONG", value: cmap12Groups.length / 3 } + ]); + t4.fields = t4.fields.concat(cmap12Groups); + } + return t4; +} +var cmap = { parse: parseCmapTable, make: makeCmapTable }; +var cffStandardStrings = [ + ".notdef", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quoteright", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "quoteleft", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "exclamdown", + "cent", + "sterling", + "fraction", + "yen", + "florin", + "section", + "currency", + "quotesingle", + "quotedblleft", + "guillemotleft", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "endash", + "dagger", + "daggerdbl", + "periodcentered", + "paragraph", + "bullet", + "quotesinglbase", + "quotedblbase", + "quotedblright", + "guillemotright", + "ellipsis", + "perthousand", + "questiondown", + "grave", + "acute", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "dieresis", + "ring", + "cedilla", + "hungarumlaut", + "ogonek", + "caron", + "emdash", + "AE", + "ordfeminine", + "Lslash", + "Oslash", + "OE", + "ordmasculine", + "ae", + "dotlessi", + "lslash", + "oslash", + "oe", + "germandbls", + "onesuperior", + "logicalnot", + "mu", + "trademark", + "Eth", + "onehalf", + "plusminus", + "Thorn", + "onequarter", + "divide", + "brokenbar", + "degree", + "thorn", + "threequarters", + "twosuperior", + "registered", + "minus", + "eth", + "multiply", + "threesuperior", + "copyright", + "Aacute", + "Acircumflex", + "Adieresis", + "Agrave", + "Aring", + "Atilde", + "Ccedilla", + "Eacute", + "Ecircumflex", + "Edieresis", + "Egrave", + "Iacute", + "Icircumflex", + "Idieresis", + "Igrave", + "Ntilde", + "Oacute", + "Ocircumflex", + "Odieresis", + "Ograve", + "Otilde", + "Scaron", + "Uacute", + "Ucircumflex", + "Udieresis", + "Ugrave", + "Yacute", + "Ydieresis", + "Zcaron", + "aacute", + "acircumflex", + "adieresis", + "agrave", + "aring", + "atilde", + "ccedilla", + "eacute", + "ecircumflex", + "edieresis", + "egrave", + "iacute", + "icircumflex", + "idieresis", + "igrave", + "ntilde", + "oacute", + "ocircumflex", + "odieresis", + "ograve", + "otilde", + "scaron", + "uacute", + "ucircumflex", + "udieresis", + "ugrave", + "yacute", + "ydieresis", + "zcaron", + "exclamsmall", + "Hungarumlautsmall", + "dollaroldstyle", + "dollarsuperior", + "ampersandsmall", + "Acutesmall", + "parenleftsuperior", + "parenrightsuperior", + "266 ff", + "onedotenleader", + "zerooldstyle", + "oneoldstyle", + "twooldstyle", + "threeoldstyle", + "fouroldstyle", + "fiveoldstyle", + "sixoldstyle", + "sevenoldstyle", + "eightoldstyle", + "nineoldstyle", + "commasuperior", + "threequartersemdash", + "periodsuperior", + "questionsmall", + "asuperior", + "bsuperior", + "centsuperior", + "dsuperior", + "esuperior", + "isuperior", + "lsuperior", + "msuperior", + "nsuperior", + "osuperior", + "rsuperior", + "ssuperior", + "tsuperior", + "ff", + "ffi", + "ffl", + "parenleftinferior", + "parenrightinferior", + "Circumflexsmall", + "hyphensuperior", + "Gravesmall", + "Asmall", + "Bsmall", + "Csmall", + "Dsmall", + "Esmall", + "Fsmall", + "Gsmall", + "Hsmall", + "Ismall", + "Jsmall", + "Ksmall", + "Lsmall", + "Msmall", + "Nsmall", + "Osmall", + "Psmall", + "Qsmall", + "Rsmall", + "Ssmall", + "Tsmall", + "Usmall", + "Vsmall", + "Wsmall", + "Xsmall", + "Ysmall", + "Zsmall", + "colonmonetary", + "onefitted", + "rupiah", + "Tildesmall", + "exclamdownsmall", + "centoldstyle", + "Lslashsmall", + "Scaronsmall", + "Zcaronsmall", + "Dieresissmall", + "Brevesmall", + "Caronsmall", + "Dotaccentsmall", + "Macronsmall", + "figuredash", + "hypheninferior", + "Ogoneksmall", + "Ringsmall", + "Cedillasmall", + "questiondownsmall", + "oneeighth", + "threeeighths", + "fiveeighths", + "seveneighths", + "onethird", + "twothirds", + "zerosuperior", + "foursuperior", + "fivesuperior", + "sixsuperior", + "sevensuperior", + "eightsuperior", + "ninesuperior", + "zeroinferior", + "oneinferior", + "twoinferior", + "threeinferior", + "fourinferior", + "fiveinferior", + "sixinferior", + "seveninferior", + "eightinferior", + "nineinferior", + "centinferior", + "dollarinferior", + "periodinferior", + "commainferior", + "Agravesmall", + "Aacutesmall", + "Acircumflexsmall", + "Atildesmall", + "Adieresissmall", + "Aringsmall", + "AEsmall", + "Ccedillasmall", + "Egravesmall", + "Eacutesmall", + "Ecircumflexsmall", + "Edieresissmall", + "Igravesmall", + "Iacutesmall", + "Icircumflexsmall", + "Idieresissmall", + "Ethsmall", + "Ntildesmall", + "Ogravesmall", + "Oacutesmall", + "Ocircumflexsmall", + "Otildesmall", + "Odieresissmall", + "OEsmall", + "Oslashsmall", + "Ugravesmall", + "Uacutesmall", + "Ucircumflexsmall", + "Udieresissmall", + "Yacutesmall", + "Thornsmall", + "Ydieresissmall", + "001.000", + "001.001", + "001.002", + "001.003", + "Black", + "Bold", + "Book", + "Light", + "Medium", + "Regular", + "Roman", + "Semibold" +]; +var cffStandardEncoding = [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quoteright", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "quoteleft", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "exclamdown", + "cent", + "sterling", + "fraction", + "yen", + "florin", + "section", + "currency", + "quotesingle", + "quotedblleft", + "guillemotleft", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "", + "endash", + "dagger", + "daggerdbl", + "periodcentered", + "", + "paragraph", + "bullet", + "quotesinglbase", + "quotedblbase", + "quotedblright", + "guillemotright", + "ellipsis", + "perthousand", + "", + "questiondown", + "", + "grave", + "acute", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "dieresis", + "", + "ring", + "cedilla", + "", + "hungarumlaut", + "ogonek", + "caron", + "emdash", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "AE", + "", + "ordfeminine", + "", + "", + "", + "", + "Lslash", + "Oslash", + "OE", + "ordmasculine", + "", + "", + "", + "", + "", + "ae", + "", + "", + "", + "dotlessi", + "", + "", + "lslash", + "oslash", + "oe", + "germandbls" +]; +var cffExpertEncoding = [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "space", + "exclamsmall", + "Hungarumlautsmall", + "", + "dollaroldstyle", + "dollarsuperior", + "ampersandsmall", + "Acutesmall", + "parenleftsuperior", + "parenrightsuperior", + "twodotenleader", + "onedotenleader", + "comma", + "hyphen", + "period", + "fraction", + "zerooldstyle", + "oneoldstyle", + "twooldstyle", + "threeoldstyle", + "fouroldstyle", + "fiveoldstyle", + "sixoldstyle", + "sevenoldstyle", + "eightoldstyle", + "nineoldstyle", + "colon", + "semicolon", + "commasuperior", + "threequartersemdash", + "periodsuperior", + "questionsmall", + "", + "asuperior", + "bsuperior", + "centsuperior", + "dsuperior", + "esuperior", + "", + "", + "isuperior", + "", + "", + "lsuperior", + "msuperior", + "nsuperior", + "osuperior", + "", + "", + "rsuperior", + "ssuperior", + "tsuperior", + "", + "ff", + "fi", + "fl", + "ffi", + "ffl", + "parenleftinferior", + "", + "parenrightinferior", + "Circumflexsmall", + "hyphensuperior", + "Gravesmall", + "Asmall", + "Bsmall", + "Csmall", + "Dsmall", + "Esmall", + "Fsmall", + "Gsmall", + "Hsmall", + "Ismall", + "Jsmall", + "Ksmall", + "Lsmall", + "Msmall", + "Nsmall", + "Osmall", + "Psmall", + "Qsmall", + "Rsmall", + "Ssmall", + "Tsmall", + "Usmall", + "Vsmall", + "Wsmall", + "Xsmall", + "Ysmall", + "Zsmall", + "colonmonetary", + "onefitted", + "rupiah", + "Tildesmall", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "exclamdownsmall", + "centoldstyle", + "Lslashsmall", + "", + "", + "Scaronsmall", + "Zcaronsmall", + "Dieresissmall", + "Brevesmall", + "Caronsmall", + "", + "Dotaccentsmall", + "", + "", + "Macronsmall", + "", + "", + "figuredash", + "hypheninferior", + "", + "", + "Ogoneksmall", + "Ringsmall", + "Cedillasmall", + "", + "", + "", + "onequarter", + "onehalf", + "threequarters", + "questiondownsmall", + "oneeighth", + "threeeighths", + "fiveeighths", + "seveneighths", + "onethird", + "twothirds", + "", + "", + "zerosuperior", + "onesuperior", + "twosuperior", + "threesuperior", + "foursuperior", + "fivesuperior", + "sixsuperior", + "sevensuperior", + "eightsuperior", + "ninesuperior", + "zeroinferior", + "oneinferior", + "twoinferior", + "threeinferior", + "fourinferior", + "fiveinferior", + "sixinferior", + "seveninferior", + "eightinferior", + "nineinferior", + "centinferior", + "dollarinferior", + "periodinferior", + "commainferior", + "Agravesmall", + "Aacutesmall", + "Acircumflexsmall", + "Atildesmall", + "Adieresissmall", + "Aringsmall", + "AEsmall", + "Ccedillasmall", + "Egravesmall", + "Eacutesmall", + "Ecircumflexsmall", + "Edieresissmall", + "Igravesmall", + "Iacutesmall", + "Icircumflexsmall", + "Idieresissmall", + "Ethsmall", + "Ntildesmall", + "Ogravesmall", + "Oacutesmall", + "Ocircumflexsmall", + "Otildesmall", + "Odieresissmall", + "OEsmall", + "Oslashsmall", + "Ugravesmall", + "Uacutesmall", + "Ucircumflexsmall", + "Udieresissmall", + "Yacutesmall", + "Thornsmall", + "Ydieresissmall" +]; +var standardNames = [ + ".notdef", + ".null", + "nonmarkingreturn", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quotesingle", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "grave", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "Adieresis", + "Aring", + "Ccedilla", + "Eacute", + "Ntilde", + "Odieresis", + "Udieresis", + "aacute", + "agrave", + "acircumflex", + "adieresis", + "atilde", + "aring", + "ccedilla", + "eacute", + "egrave", + "ecircumflex", + "edieresis", + "iacute", + "igrave", + "icircumflex", + "idieresis", + "ntilde", + "oacute", + "ograve", + "ocircumflex", + "odieresis", + "otilde", + "uacute", + "ugrave", + "ucircumflex", + "udieresis", + "dagger", + "degree", + "cent", + "sterling", + "section", + "bullet", + "paragraph", + "germandbls", + "registered", + "copyright", + "trademark", + "acute", + "dieresis", + "notequal", + "AE", + "Oslash", + "infinity", + "plusminus", + "lessequal", + "greaterequal", + "yen", + "mu", + "partialdiff", + "summation", + "product", + "pi", + "integral", + "ordfeminine", + "ordmasculine", + "Omega", + "ae", + "oslash", + "questiondown", + "exclamdown", + "logicalnot", + "radical", + "florin", + "approxequal", + "Delta", + "guillemotleft", + "guillemotright", + "ellipsis", + "nonbreakingspace", + "Agrave", + "Atilde", + "Otilde", + "OE", + "oe", + "endash", + "emdash", + "quotedblleft", + "quotedblright", + "quoteleft", + "quoteright", + "divide", + "lozenge", + "ydieresis", + "Ydieresis", + "fraction", + "currency", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "daggerdbl", + "periodcentered", + "quotesinglbase", + "quotedblbase", + "perthousand", + "Acircumflex", + "Ecircumflex", + "Aacute", + "Edieresis", + "Egrave", + "Iacute", + "Icircumflex", + "Idieresis", + "Igrave", + "Oacute", + "Ocircumflex", + "apple", + "Ograve", + "Uacute", + "Ucircumflex", + "Ugrave", + "dotlessi", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "ring", + "cedilla", + "hungarumlaut", + "ogonek", + "caron", + "Lslash", + "lslash", + "Scaron", + "scaron", + "Zcaron", + "zcaron", + "brokenbar", + "Eth", + "eth", + "Yacute", + "yacute", + "Thorn", + "thorn", + "minus", + "multiply", + "onesuperior", + "twosuperior", + "threesuperior", + "onehalf", + "onequarter", + "threequarters", + "franc", + "Gbreve", + "gbreve", + "Idotaccent", + "Scedilla", + "scedilla", + "Cacute", + "cacute", + "Ccaron", + "ccaron", + "dcroat" +]; +function DefaultEncoding(font) { + this.font = font; +} +DefaultEncoding.prototype.charToGlyphIndex = function(c) { + var code = c.codePointAt(0); + var glyphs = this.font.glyphs; + if (glyphs) { + for (var i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + for (var j2 = 0;j2 < glyph.unicodes.length; j2 += 1) { + if (glyph.unicodes[j2] === code) { + return i; + } + } + } + } + return null; +}; +function CmapEncoding(cmap2) { + this.cmap = cmap2; +} +CmapEncoding.prototype.charToGlyphIndex = function(c) { + return this.cmap.glyphIndexMap[c.codePointAt(0)] || 0; +}; +function CffEncoding(encoding, charset) { + this.encoding = encoding; + this.charset = charset; +} +CffEncoding.prototype.charToGlyphIndex = function(s) { + var code = s.codePointAt(0); + var charName = this.encoding[code]; + return this.charset.indexOf(charName); +}; +function GlyphNames(post) { + switch (post.version) { + case 1: + this.names = standardNames.slice(); + break; + case 2: + this.names = new Array(post.numberOfGlyphs); + for (var i = 0;i < post.numberOfGlyphs; i++) { + if (post.glyphNameIndex[i] < standardNames.length) { + this.names[i] = standardNames[post.glyphNameIndex[i]]; + } else { + this.names[i] = post.names[post.glyphNameIndex[i] - standardNames.length]; + } + } + break; + case 2.5: + this.names = new Array(post.numberOfGlyphs); + for (var i$1 = 0;i$1 < post.numberOfGlyphs; i$1++) { + this.names[i$1] = standardNames[i$1 + post.glyphNameIndex[i$1]]; + } + break; + case 3: + this.names = []; + break; + default: + this.names = []; + break; + } +} +GlyphNames.prototype.nameToGlyphIndex = function(name2) { + return this.names.indexOf(name2); +}; +GlyphNames.prototype.glyphIndexToName = function(gid) { + return this.names[gid]; +}; +function line(ctx, x1, y1, x2, y22) { + ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y22); + ctx.stroke(); +} +var draw = { line }; +function getPathDefinition(glyph, path) { + var _path = path || new Path2; + return { + configurable: true, + get: function() { + if (typeof _path === "function") { + _path = _path(); + } + return _path; + }, + set: function(p) { + _path = p; + } + }; +} +function Glyph(options) { + this.bindConstructorValues(options); +} +Glyph.prototype.bindConstructorValues = function(options) { + this.index = options.index || 0; + this.name = options.name || null; + this.unicode = options.unicode || undefined; + this.unicodes = options.unicodes || options.unicode !== undefined ? [options.unicode] : []; + if ("xMin" in options) { + this.xMin = options.xMin; + } + if ("yMin" in options) { + this.yMin = options.yMin; + } + if ("xMax" in options) { + this.xMax = options.xMax; + } + if ("yMax" in options) { + this.yMax = options.yMax; + } + if ("advanceWidth" in options) { + this.advanceWidth = options.advanceWidth; + } + Object.defineProperty(this, "path", getPathDefinition(this, options.path)); +}; +Glyph.prototype.addUnicode = function(unicode) { + if (this.unicodes.length === 0) { + this.unicode = unicode; + } + this.unicodes.push(unicode); +}; +Glyph.prototype.getBoundingBox = function() { + return this.path.getBoundingBox(); +}; +Glyph.prototype.getPath = function(x2, y3, fontSize, options, font) { + x2 = x2 !== undefined ? x2 : 0; + y3 = y3 !== undefined ? y3 : 0; + fontSize = fontSize !== undefined ? fontSize : 72; + var commands; + var hPoints; + if (!options) { + options = {}; + } + var xScale = options.xScale; + var yScale = options.yScale; + if (options.hinting && font && font.hinting) { + hPoints = this.path && font.hinting.exec(this, fontSize); + } + if (hPoints) { + commands = font.hinting.getCommands(hPoints); + x2 = Math.round(x2); + y3 = Math.round(y3); + xScale = yScale = 1; + } else { + commands = this.path.commands; + var scale2 = 1 / (this.path.unitsPerEm || 1000) * fontSize; + if (xScale === undefined) { + xScale = scale2; + } + if (yScale === undefined) { + yScale = scale2; + } + } + var p = new Path2; + for (var i = 0;i < commands.length; i += 1) { + var cmd = commands[i]; + if (cmd.type === "M") { + p.moveTo(x2 + cmd.x * xScale, y3 + -cmd.y * yScale); + } else if (cmd.type === "L") { + p.lineTo(x2 + cmd.x * xScale, y3 + -cmd.y * yScale); + } else if (cmd.type === "Q") { + p.quadraticCurveTo(x2 + cmd.x1 * xScale, y3 + -cmd.y1 * yScale, x2 + cmd.x * xScale, y3 + -cmd.y * yScale); + } else if (cmd.type === "C") { + p.curveTo(x2 + cmd.x1 * xScale, y3 + -cmd.y1 * yScale, x2 + cmd.x2 * xScale, y3 + -cmd.y2 * yScale, x2 + cmd.x * xScale, y3 + -cmd.y * yScale); + } else if (cmd.type === "Z") { + p.closePath(); + } + } + return p; +}; +Glyph.prototype.getContours = function() { + if (this.points === undefined) { + return []; + } + var contours = []; + var currentContour = []; + for (var i = 0;i < this.points.length; i += 1) { + var pt = this.points[i]; + currentContour.push(pt); + if (pt.lastPointOfContour) { + contours.push(currentContour); + currentContour = []; + } + } + check.argument(currentContour.length === 0, "There are still points left in the current contour."); + return contours; +}; +Glyph.prototype.getMetrics = function() { + var commands = this.path.commands; + var xCoords = []; + var yCoords = []; + for (var i = 0;i < commands.length; i += 1) { + var cmd = commands[i]; + if (cmd.type !== "Z") { + xCoords.push(cmd.x); + yCoords.push(cmd.y); + } + if (cmd.type === "Q" || cmd.type === "C") { + xCoords.push(cmd.x1); + yCoords.push(cmd.y1); + } + if (cmd.type === "C") { + xCoords.push(cmd.x2); + yCoords.push(cmd.y2); + } + } + var metrics = { + xMin: Math.min.apply(null, xCoords), + yMin: Math.min.apply(null, yCoords), + xMax: Math.max.apply(null, xCoords), + yMax: Math.max.apply(null, yCoords), + leftSideBearing: this.leftSideBearing + }; + if (!isFinite(metrics.xMin)) { + metrics.xMin = 0; + } + if (!isFinite(metrics.xMax)) { + metrics.xMax = this.advanceWidth; + } + if (!isFinite(metrics.yMin)) { + metrics.yMin = 0; + } + if (!isFinite(metrics.yMax)) { + metrics.yMax = 0; + } + metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin); + return metrics; +}; +Glyph.prototype.draw = function(ctx, x2, y3, fontSize, options) { + this.getPath(x2, y3, fontSize, options).draw(ctx); +}; +Glyph.prototype.drawPoints = function(ctx, x2, y3, fontSize) { + function drawCircles(l2, x3, y4, scale3) { + ctx.beginPath(); + for (var j2 = 0;j2 < l2.length; j2 += 1) { + ctx.moveTo(x3 + l2[j2].x * scale3, y4 + l2[j2].y * scale3); + ctx.arc(x3 + l2[j2].x * scale3, y4 + l2[j2].y * scale3, 2, 0, Math.PI * 2, false); + } + ctx.closePath(); + ctx.fill(); + } + x2 = x2 !== undefined ? x2 : 0; + y3 = y3 !== undefined ? y3 : 0; + fontSize = fontSize !== undefined ? fontSize : 24; + var scale2 = 1 / this.path.unitsPerEm * fontSize; + var blueCircles = []; + var redCircles = []; + var path = this.path; + for (var i = 0;i < path.commands.length; i += 1) { + var cmd = path.commands[i]; + if (cmd.x !== undefined) { + blueCircles.push({ x: cmd.x, y: -cmd.y }); + } + if (cmd.x1 !== undefined) { + redCircles.push({ x: cmd.x1, y: -cmd.y1 }); + } + if (cmd.x2 !== undefined) { + redCircles.push({ x: cmd.x2, y: -cmd.y2 }); + } + } + ctx.fillStyle = "blue"; + drawCircles(blueCircles, x2, y3, scale2); + ctx.fillStyle = "red"; + drawCircles(redCircles, x2, y3, scale2); +}; +Glyph.prototype.drawMetrics = function(ctx, x2, y3, fontSize) { + var scale2; + x2 = x2 !== undefined ? x2 : 0; + y3 = y3 !== undefined ? y3 : 0; + fontSize = fontSize !== undefined ? fontSize : 24; + scale2 = 1 / this.path.unitsPerEm * fontSize; + ctx.lineWidth = 1; + ctx.strokeStyle = "black"; + draw.line(ctx, x2, -1e4, x2, 1e4); + draw.line(ctx, -1e4, y3, 1e4, y3); + var xMin = this.xMin || 0; + var yMin = this.yMin || 0; + var xMax = this.xMax || 0; + var yMax = this.yMax || 0; + var advanceWidth = this.advanceWidth || 0; + ctx.strokeStyle = "blue"; + draw.line(ctx, x2 + xMin * scale2, -1e4, x2 + xMin * scale2, 1e4); + draw.line(ctx, x2 + xMax * scale2, -1e4, x2 + xMax * scale2, 1e4); + draw.line(ctx, -1e4, y3 + -yMin * scale2, 1e4, y3 + -yMin * scale2); + draw.line(ctx, -1e4, y3 + -yMax * scale2, 1e4, y3 + -yMax * scale2); + ctx.strokeStyle = "green"; + draw.line(ctx, x2 + advanceWidth * scale2, -1e4, x2 + advanceWidth * scale2, 1e4); +}; +function defineDependentProperty(glyph, externalName, internalName) { + Object.defineProperty(glyph, externalName, { + get: function() { + glyph.path; + return glyph[internalName]; + }, + set: function(newValue) { + glyph[internalName] = newValue; + }, + enumerable: true, + configurable: true + }); +} +function GlyphSet(font, glyphs) { + this.font = font; + this.glyphs = {}; + if (Array.isArray(glyphs)) { + for (var i = 0;i < glyphs.length; i++) { + var glyph = glyphs[i]; + glyph.path.unitsPerEm = font.unitsPerEm; + this.glyphs[i] = glyph; + } + } + this.length = glyphs && glyphs.length || 0; +} +GlyphSet.prototype.get = function(index2) { + if (this.glyphs[index2] === undefined) { + this.font._push(index2); + if (typeof this.glyphs[index2] === "function") { + this.glyphs[index2] = this.glyphs[index2](); + } + var glyph = this.glyphs[index2]; + var unicodeObj = this.font._IndexToUnicodeMap[index2]; + if (unicodeObj) { + for (var j2 = 0;j2 < unicodeObj.unicodes.length; j2++) { + glyph.addUnicode(unicodeObj.unicodes[j2]); + } + } + if (this.font.cffEncoding) { + if (this.font.isCIDFont) { + glyph.name = "gid" + index2; + } else { + glyph.name = this.font.cffEncoding.charset[index2]; + } + } else if (this.font.glyphNames.names) { + glyph.name = this.font.glyphNames.glyphIndexToName(index2); + } + this.glyphs[index2].advanceWidth = this.font._hmtxTableData[index2].advanceWidth; + this.glyphs[index2].leftSideBearing = this.font._hmtxTableData[index2].leftSideBearing; + } else { + if (typeof this.glyphs[index2] === "function") { + this.glyphs[index2] = this.glyphs[index2](); + } + } + return this.glyphs[index2]; +}; +GlyphSet.prototype.push = function(index2, loader) { + this.glyphs[index2] = loader; + this.length++; +}; +function glyphLoader(font, index2) { + return new Glyph({ index: index2, font }); +} +function ttfGlyphLoader(font, index2, parseGlyph, data2, position2, buildPath) { + return function() { + var glyph = new Glyph({ index: index2, font }); + glyph.path = function() { + parseGlyph(glyph, data2, position2); + var path = buildPath(font.glyphs, glyph); + path.unitsPerEm = font.unitsPerEm; + return path; + }; + defineDependentProperty(glyph, "xMin", "_xMin"); + defineDependentProperty(glyph, "xMax", "_xMax"); + defineDependentProperty(glyph, "yMin", "_yMin"); + defineDependentProperty(glyph, "yMax", "_yMax"); + return glyph; + }; +} +function cffGlyphLoader(font, index2, parseCFFCharstring, charstring) { + return function() { + var glyph = new Glyph({ index: index2, font }); + glyph.path = function() { + var path = parseCFFCharstring(font, glyph, charstring); + path.unitsPerEm = font.unitsPerEm; + return path; + }; + return glyph; + }; +} +var glyphset = { GlyphSet, glyphLoader, ttfGlyphLoader, cffGlyphLoader }; +function equals2(a, b) { + if (a === b) { + return true; + } else if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return false; + } + for (var i = 0;i < a.length; i += 1) { + if (!equals2(a[i], b[i])) { + return false; + } + } + return true; + } else { + return false; + } +} +function calcCFFSubroutineBias(subrs) { + var bias; + if (subrs.length < 1240) { + bias = 107; + } else if (subrs.length < 33900) { + bias = 1131; + } else { + bias = 32768; + } + return bias; +} +function parseCFFIndex(data2, start, conversionFn) { + var offsets = []; + var objects = []; + var count = parse.getCard16(data2, start); + var objectOffset; + var endOffset; + if (count !== 0) { + var offsetSize = parse.getByte(data2, start + 2); + objectOffset = start + (count + 1) * offsetSize + 2; + var pos = start + 3; + for (var i = 0;i < count + 1; i += 1) { + offsets.push(parse.getOffset(data2, pos, offsetSize)); + pos += offsetSize; + } + endOffset = objectOffset + offsets[count]; + } else { + endOffset = start + 2; + } + for (var i$1 = 0;i$1 < offsets.length - 1; i$1 += 1) { + var value2 = parse.getBytes(data2, objectOffset + offsets[i$1], objectOffset + offsets[i$1 + 1]); + if (conversionFn) { + value2 = conversionFn(value2); + } + objects.push(value2); + } + return { objects, startOffset: start, endOffset }; +} +function parseCFFIndexLowMemory(data2, start) { + var offsets = []; + var count = parse.getCard16(data2, start); + var objectOffset; + var endOffset; + if (count !== 0) { + var offsetSize = parse.getByte(data2, start + 2); + objectOffset = start + (count + 1) * offsetSize + 2; + var pos = start + 3; + for (var i = 0;i < count + 1; i += 1) { + offsets.push(parse.getOffset(data2, pos, offsetSize)); + pos += offsetSize; + } + endOffset = objectOffset + offsets[count]; + } else { + endOffset = start + 2; + } + return { offsets, startOffset: start, endOffset }; +} +function getCffIndexObject(i, offsets, data2, start, conversionFn) { + var count = parse.getCard16(data2, start); + var objectOffset = 0; + if (count !== 0) { + var offsetSize = parse.getByte(data2, start + 2); + objectOffset = start + (count + 1) * offsetSize + 2; + } + var value2 = parse.getBytes(data2, objectOffset + offsets[i], objectOffset + offsets[i + 1]); + if (conversionFn) { + value2 = conversionFn(value2); + } + return value2; +} +function parseFloatOperand(parser) { + var s = ""; + var eof = 15; + var lookup = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "E", "E-", null, "-"]; + while (true) { + var b = parser.parseByte(); + var n1 = b >> 4; + var n2 = b & 15; + if (n1 === eof) { + break; + } + s += lookup[n1]; + if (n2 === eof) { + break; + } + s += lookup[n2]; + } + return parseFloat(s); +} +function parseOperand(parser, b0) { + var b1; + var b22; + var b3; + var b4; + if (b0 === 28) { + b1 = parser.parseByte(); + b22 = parser.parseByte(); + return b1 << 8 | b22; + } + if (b0 === 29) { + b1 = parser.parseByte(); + b22 = parser.parseByte(); + b3 = parser.parseByte(); + b4 = parser.parseByte(); + return b1 << 24 | b22 << 16 | b3 << 8 | b4; + } + if (b0 === 30) { + return parseFloatOperand(parser); + } + if (b0 >= 32 && b0 <= 246) { + return b0 - 139; + } + if (b0 >= 247 && b0 <= 250) { + b1 = parser.parseByte(); + return (b0 - 247) * 256 + b1 + 108; + } + if (b0 >= 251 && b0 <= 254) { + b1 = parser.parseByte(); + return -(b0 - 251) * 256 - b1 - 108; + } + throw new Error("Invalid b0 " + b0); +} +function entriesToObject(entries) { + var o = {}; + for (var i = 0;i < entries.length; i += 1) { + var key2 = entries[i][0]; + var values2 = entries[i][1]; + var value2 = undefined; + if (values2.length === 1) { + value2 = values2[0]; + } else { + value2 = values2; + } + if (o.hasOwnProperty(key2) && !isNaN(o[key2])) { + throw new Error("Object " + o + " already has key " + key2); + } + o[key2] = value2; + } + return o; +} +function parseCFFDict(data2, start, size) { + start = start !== undefined ? start : 0; + var parser = new parse.Parser(data2, start); + var entries = []; + var operands = []; + size = size !== undefined ? size : data2.length; + while (parser.relativeOffset < size) { + var op = parser.parseByte(); + if (op <= 21) { + if (op === 12) { + op = 1200 + parser.parseByte(); + } + entries.push([op, operands]); + operands = []; + } else { + operands.push(parseOperand(parser, op)); + } + } + return entriesToObject(entries); +} +function getCFFString(strings, index2) { + if (index2 <= 390) { + index2 = cffStandardStrings[index2]; + } else { + index2 = strings[index2 - 391]; + } + return index2; +} +function interpretDict(dict, meta, strings) { + var newDict = {}; + var value2; + for (var i = 0;i < meta.length; i += 1) { + var m = meta[i]; + if (Array.isArray(m.type)) { + var values2 = []; + values2.length = m.type.length; + for (var j2 = 0;j2 < m.type.length; j2++) { + value2 = dict[m.op] !== undefined ? dict[m.op][j2] : undefined; + if (value2 === undefined) { + value2 = m.value !== undefined && m.value[j2] !== undefined ? m.value[j2] : null; + } + if (m.type[j2] === "SID") { + value2 = getCFFString(strings, value2); + } + values2[j2] = value2; + } + newDict[m.name] = values2; + } else { + value2 = dict[m.op]; + if (value2 === undefined) { + value2 = m.value !== undefined ? m.value : null; + } + if (m.type === "SID") { + value2 = getCFFString(strings, value2); + } + newDict[m.name] = value2; + } + } + return newDict; +} +function parseCFFHeader(data2, start) { + var header = {}; + header.formatMajor = parse.getCard8(data2, start); + header.formatMinor = parse.getCard8(data2, start + 1); + header.size = parse.getCard8(data2, start + 2); + header.offsetSize = parse.getCard8(data2, start + 3); + header.startOffset = start; + header.endOffset = start + 4; + return header; +} +var TOP_DICT_META = [ + { name: "version", op: 0, type: "SID" }, + { name: "notice", op: 1, type: "SID" }, + { name: "copyright", op: 1200, type: "SID" }, + { name: "fullName", op: 2, type: "SID" }, + { name: "familyName", op: 3, type: "SID" }, + { name: "weight", op: 4, type: "SID" }, + { name: "isFixedPitch", op: 1201, type: "number", value: 0 }, + { name: "italicAngle", op: 1202, type: "number", value: 0 }, + { name: "underlinePosition", op: 1203, type: "number", value: -100 }, + { name: "underlineThickness", op: 1204, type: "number", value: 50 }, + { name: "paintType", op: 1205, type: "number", value: 0 }, + { name: "charstringType", op: 1206, type: "number", value: 2 }, + { + name: "fontMatrix", + op: 1207, + type: ["real", "real", "real", "real", "real", "real"], + value: [0.001, 0, 0, 0.001, 0, 0] + }, + { name: "uniqueId", op: 13, type: "number" }, + { name: "fontBBox", op: 5, type: ["number", "number", "number", "number"], value: [0, 0, 0, 0] }, + { name: "strokeWidth", op: 1208, type: "number", value: 0 }, + { name: "xuid", op: 14, type: [], value: null }, + { name: "charset", op: 15, type: "offset", value: 0 }, + { name: "encoding", op: 16, type: "offset", value: 0 }, + { name: "charStrings", op: 17, type: "offset", value: 0 }, + { name: "private", op: 18, type: ["number", "offset"], value: [0, 0] }, + { name: "ros", op: 1230, type: ["SID", "SID", "number"] }, + { name: "cidFontVersion", op: 1231, type: "number", value: 0 }, + { name: "cidFontRevision", op: 1232, type: "number", value: 0 }, + { name: "cidFontType", op: 1233, type: "number", value: 0 }, + { name: "cidCount", op: 1234, type: "number", value: 8720 }, + { name: "uidBase", op: 1235, type: "number" }, + { name: "fdArray", op: 1236, type: "offset" }, + { name: "fdSelect", op: 1237, type: "offset" }, + { name: "fontName", op: 1238, type: "SID" } +]; +var PRIVATE_DICT_META = [ + { name: "subrs", op: 19, type: "offset", value: 0 }, + { name: "defaultWidthX", op: 20, type: "number", value: 0 }, + { name: "nominalWidthX", op: 21, type: "number", value: 0 } +]; +function parseCFFTopDict(data2, strings) { + var dict = parseCFFDict(data2, 0, data2.byteLength); + return interpretDict(dict, TOP_DICT_META, strings); +} +function parseCFFPrivateDict(data2, start, size, strings) { + var dict = parseCFFDict(data2, start, size); + return interpretDict(dict, PRIVATE_DICT_META, strings); +} +function gatherCFFTopDicts(data2, start, cffIndex, strings) { + var topDictArray = []; + for (var iTopDict = 0;iTopDict < cffIndex.length; iTopDict += 1) { + var topDictData = new DataView(new Uint8Array(cffIndex[iTopDict]).buffer); + var topDict = parseCFFTopDict(topDictData, strings); + topDict._subrs = []; + topDict._subrsBias = 0; + topDict._defaultWidthX = 0; + topDict._nominalWidthX = 0; + var privateSize = topDict.private[0]; + var privateOffset = topDict.private[1]; + if (privateSize !== 0 && privateOffset !== 0) { + var privateDict = parseCFFPrivateDict(data2, privateOffset + start, privateSize, strings); + topDict._defaultWidthX = privateDict.defaultWidthX; + topDict._nominalWidthX = privateDict.nominalWidthX; + if (privateDict.subrs !== 0) { + var subrOffset = privateOffset + privateDict.subrs; + var subrIndex = parseCFFIndex(data2, subrOffset + start); + topDict._subrs = subrIndex.objects; + topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs); + } + topDict._privateDict = privateDict; + } + topDictArray.push(topDict); + } + return topDictArray; +} +function parseCFFCharset(data2, start, nGlyphs, strings) { + var sid; + var count; + var parser = new parse.Parser(data2, start); + nGlyphs -= 1; + var charset = [".notdef"]; + var format = parser.parseCard8(); + if (format === 0) { + for (var i = 0;i < nGlyphs; i += 1) { + sid = parser.parseSID(); + charset.push(getCFFString(strings, sid)); + } + } else if (format === 1) { + while (charset.length <= nGlyphs) { + sid = parser.parseSID(); + count = parser.parseCard8(); + for (var i$1 = 0;i$1 <= count; i$1 += 1) { + charset.push(getCFFString(strings, sid)); + sid += 1; + } + } + } else if (format === 2) { + while (charset.length <= nGlyphs) { + sid = parser.parseSID(); + count = parser.parseCard16(); + for (var i$2 = 0;i$2 <= count; i$2 += 1) { + charset.push(getCFFString(strings, sid)); + sid += 1; + } + } + } else { + throw new Error("Unknown charset format " + format); + } + return charset; +} +function parseCFFEncoding(data2, start, charset) { + var code; + var enc = {}; + var parser = new parse.Parser(data2, start); + var format = parser.parseCard8(); + if (format === 0) { + var nCodes = parser.parseCard8(); + for (var i = 0;i < nCodes; i += 1) { + code = parser.parseCard8(); + enc[code] = i; + } + } else if (format === 1) { + var nRanges = parser.parseCard8(); + code = 1; + for (var i$1 = 0;i$1 < nRanges; i$1 += 1) { + var first2 = parser.parseCard8(); + var nLeft = parser.parseCard8(); + for (var j2 = first2;j2 <= first2 + nLeft; j2 += 1) { + enc[j2] = code; + code += 1; + } + } + } else { + throw new Error("Unknown encoding format " + format); + } + return new CffEncoding(enc, charset); +} +function parseCFFCharstring(font, glyph, code) { + var c1x; + var c1y; + var c2x; + var c2y; + var p = new Path2; + var stack = []; + var nStems = 0; + var haveWidth = false; + var open = false; + var x2 = 0; + var y3 = 0; + var subrs; + var subrsBias; + var defaultWidthX; + var nominalWidthX; + if (font.isCIDFont) { + var fdIndex = font.tables.cff.topDict._fdSelect[glyph.index]; + var fdDict = font.tables.cff.topDict._fdArray[fdIndex]; + subrs = fdDict._subrs; + subrsBias = fdDict._subrsBias; + defaultWidthX = fdDict._defaultWidthX; + nominalWidthX = fdDict._nominalWidthX; + } else { + subrs = font.tables.cff.topDict._subrs; + subrsBias = font.tables.cff.topDict._subrsBias; + defaultWidthX = font.tables.cff.topDict._defaultWidthX; + nominalWidthX = font.tables.cff.topDict._nominalWidthX; + } + var width2 = defaultWidthX; + function newContour(x3, y4) { + if (open) { + p.closePath(); + } + p.moveTo(x3, y4); + open = true; + } + function parseStems() { + var hasWidthArg; + hasWidthArg = stack.length % 2 !== 0; + if (hasWidthArg && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + } + nStems += stack.length >> 1; + stack.length = 0; + haveWidth = true; + } + function parse2(code2) { + var b1; + var b22; + var b3; + var b4; + var codeIndex; + var subrCode; + var jpx; + var jpy; + var c3x; + var c3y; + var c4x; + var c4y; + var i = 0; + while (i < code2.length) { + var v = code2[i]; + i += 1; + switch (v) { + case 1: + parseStems(); + break; + case 3: + parseStems(); + break; + case 4: + if (stack.length > 1 && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + haveWidth = true; + } + y3 += stack.pop(); + newContour(x2, y3); + break; + case 5: + while (stack.length > 0) { + x2 += stack.shift(); + y3 += stack.shift(); + p.lineTo(x2, y3); + } + break; + case 6: + while (stack.length > 0) { + x2 += stack.shift(); + p.lineTo(x2, y3); + if (stack.length === 0) { + break; + } + y3 += stack.shift(); + p.lineTo(x2, y3); + } + break; + case 7: + while (stack.length > 0) { + y3 += stack.shift(); + p.lineTo(x2, y3); + if (stack.length === 0) { + break; + } + x2 += stack.shift(); + p.lineTo(x2, y3); + } + break; + case 8: + while (stack.length > 0) { + c1x = x2 + stack.shift(); + c1y = y3 + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y3 = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x2, y3); + } + break; + case 10: + codeIndex = stack.pop() + subrsBias; + subrCode = subrs[codeIndex]; + if (subrCode) { + parse2(subrCode); + } + break; + case 11: + return; + case 12: + v = code2[i]; + i += 1; + switch (v) { + case 35: + c1x = x2 + stack.shift(); + c1y = y3 + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + jpx = c2x + stack.shift(); + jpy = c2y + stack.shift(); + c3x = jpx + stack.shift(); + c3y = jpy + stack.shift(); + c4x = c3x + stack.shift(); + c4y = c3y + stack.shift(); + x2 = c4x + stack.shift(); + y3 = c4y + stack.shift(); + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x2, y3); + break; + case 34: + c1x = x2 + stack.shift(); + c1y = y3; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + jpx = c2x + stack.shift(); + jpy = c2y; + c3x = jpx + stack.shift(); + c3y = c2y; + c4x = c3x + stack.shift(); + c4y = y3; + x2 = c4x + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x2, y3); + break; + case 36: + c1x = x2 + stack.shift(); + c1y = y3 + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + jpx = c2x + stack.shift(); + jpy = c2y; + c3x = jpx + stack.shift(); + c3y = c2y; + c4x = c3x + stack.shift(); + c4y = c3y + stack.shift(); + x2 = c4x + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x2, y3); + break; + case 37: + c1x = x2 + stack.shift(); + c1y = y3 + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + jpx = c2x + stack.shift(); + jpy = c2y + stack.shift(); + c3x = jpx + stack.shift(); + c3y = jpy + stack.shift(); + c4x = c3x + stack.shift(); + c4y = c3y + stack.shift(); + if (Math.abs(c4x - x2) > Math.abs(c4y - y3)) { + x2 = c4x + stack.shift(); + } else { + y3 = c4y + stack.shift(); + } + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x2, y3); + break; + default: + console.log("Glyph " + glyph.index + ": unknown operator " + 1200 + v); + stack.length = 0; + } + break; + case 14: + if (stack.length > 0 && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + haveWidth = true; + } + if (open) { + p.closePath(); + open = false; + } + break; + case 18: + parseStems(); + break; + case 19: + case 20: + parseStems(); + i += nStems + 7 >> 3; + break; + case 21: + if (stack.length > 2 && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + haveWidth = true; + } + y3 += stack.pop(); + x2 += stack.pop(); + newContour(x2, y3); + break; + case 22: + if (stack.length > 1 && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + haveWidth = true; + } + x2 += stack.pop(); + newContour(x2, y3); + break; + case 23: + parseStems(); + break; + case 24: + while (stack.length > 2) { + c1x = x2 + stack.shift(); + c1y = y3 + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y3 = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x2, y3); + } + x2 += stack.shift(); + y3 += stack.shift(); + p.lineTo(x2, y3); + break; + case 25: + while (stack.length > 6) { + x2 += stack.shift(); + y3 += stack.shift(); + p.lineTo(x2, y3); + } + c1x = x2 + stack.shift(); + c1y = y3 + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y3 = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x2, y3); + break; + case 26: + if (stack.length % 2) { + x2 += stack.shift(); + } + while (stack.length > 0) { + c1x = x2; + c1y = y3 + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x; + y3 = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x2, y3); + } + break; + case 27: + if (stack.length % 2) { + y3 += stack.shift(); + } + while (stack.length > 0) { + c1x = x2 + stack.shift(); + c1y = y3; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y3 = c2y; + p.curveTo(c1x, c1y, c2x, c2y, x2, y3); + } + break; + case 28: + b1 = code2[i]; + b22 = code2[i + 1]; + stack.push((b1 << 24 | b22 << 16) >> 16); + i += 2; + break; + case 29: + codeIndex = stack.pop() + font.gsubrsBias; + subrCode = font.gsubrs[codeIndex]; + if (subrCode) { + parse2(subrCode); + } + break; + case 30: + while (stack.length > 0) { + c1x = x2; + c1y = y3 + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y3 = c2y + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x2, y3); + if (stack.length === 0) { + break; + } + c1x = x2 + stack.shift(); + c1y = y3; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + y3 = c2y + stack.shift(); + x2 = c2x + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x2, y3); + } + break; + case 31: + while (stack.length > 0) { + c1x = x2 + stack.shift(); + c1y = y3; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + y3 = c2y + stack.shift(); + x2 = c2x + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x2, y3); + if (stack.length === 0) { + break; + } + c1x = x2; + c1y = y3 + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y3 = c2y + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x2, y3); + } + break; + default: + if (v < 32) { + console.log("Glyph " + glyph.index + ": unknown operator " + v); + } else if (v < 247) { + stack.push(v - 139); + } else if (v < 251) { + b1 = code2[i]; + i += 1; + stack.push((v - 247) * 256 + b1 + 108); + } else if (v < 255) { + b1 = code2[i]; + i += 1; + stack.push(-(v - 251) * 256 - b1 - 108); + } else { + b1 = code2[i]; + b22 = code2[i + 1]; + b3 = code2[i + 2]; + b4 = code2[i + 3]; + i += 4; + stack.push((b1 << 24 | b22 << 16 | b3 << 8 | b4) / 65536); + } + } + } + } + parse2(code); + glyph.advanceWidth = width2; + return p; +} +function parseCFFFDSelect(data2, start, nGlyphs, fdArrayCount) { + var fdSelect = []; + var fdIndex; + var parser = new parse.Parser(data2, start); + var format = parser.parseCard8(); + if (format === 0) { + for (var iGid = 0;iGid < nGlyphs; iGid++) { + fdIndex = parser.parseCard8(); + if (fdIndex >= fdArrayCount) { + throw new Error("CFF table CID Font FDSelect has bad FD index value " + fdIndex + " (FD count " + fdArrayCount + ")"); + } + fdSelect.push(fdIndex); + } + } else if (format === 3) { + var nRanges = parser.parseCard16(); + var first2 = parser.parseCard16(); + if (first2 !== 0) { + throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID " + first2); + } + var next; + for (var iRange = 0;iRange < nRanges; iRange++) { + fdIndex = parser.parseCard8(); + next = parser.parseCard16(); + if (fdIndex >= fdArrayCount) { + throw new Error("CFF table CID Font FDSelect has bad FD index value " + fdIndex + " (FD count " + fdArrayCount + ")"); + } + if (next > nGlyphs) { + throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID " + next); + } + for (;first2 < next; first2++) { + fdSelect.push(fdIndex); + } + first2 = next; + } + if (next !== nGlyphs) { + throw new Error("CFF Table CID Font FDSelect format 3 range has bad final GID " + next); + } + } else { + throw new Error("CFF Table CID Font FDSelect table has unsupported format " + format); + } + return fdSelect; +} +function parseCFFTable(data2, start, font, opt) { + font.tables.cff = {}; + var header = parseCFFHeader(data2, start); + var nameIndex = parseCFFIndex(data2, header.endOffset, parse.bytesToString); + var topDictIndex = parseCFFIndex(data2, nameIndex.endOffset); + var stringIndex = parseCFFIndex(data2, topDictIndex.endOffset, parse.bytesToString); + var globalSubrIndex = parseCFFIndex(data2, stringIndex.endOffset); + font.gsubrs = globalSubrIndex.objects; + font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs); + var topDictArray = gatherCFFTopDicts(data2, start, topDictIndex.objects, stringIndex.objects); + if (topDictArray.length !== 1) { + throw new Error("CFF table has too many fonts in 'FontSet' - count of fonts NameIndex.length = " + topDictArray.length); + } + var topDict = topDictArray[0]; + font.tables.cff.topDict = topDict; + if (topDict._privateDict) { + font.defaultWidthX = topDict._privateDict.defaultWidthX; + font.nominalWidthX = topDict._privateDict.nominalWidthX; + } + if (topDict.ros[0] !== undefined && topDict.ros[1] !== undefined) { + font.isCIDFont = true; + } + if (font.isCIDFont) { + var fdArrayOffset = topDict.fdArray; + var fdSelectOffset = topDict.fdSelect; + if (fdArrayOffset === 0 || fdSelectOffset === 0) { + throw new Error("Font is marked as a CID font, but FDArray and/or FDSelect information is missing"); + } + fdArrayOffset += start; + var fdArrayIndex = parseCFFIndex(data2, fdArrayOffset); + var fdArray = gatherCFFTopDicts(data2, start, fdArrayIndex.objects, stringIndex.objects); + topDict._fdArray = fdArray; + fdSelectOffset += start; + topDict._fdSelect = parseCFFFDSelect(data2, fdSelectOffset, font.numGlyphs, fdArray.length); + } + var privateDictOffset = start + topDict.private[1]; + var privateDict = parseCFFPrivateDict(data2, privateDictOffset, topDict.private[0], stringIndex.objects); + font.defaultWidthX = privateDict.defaultWidthX; + font.nominalWidthX = privateDict.nominalWidthX; + if (privateDict.subrs !== 0) { + var subrOffset = privateDictOffset + privateDict.subrs; + var subrIndex = parseCFFIndex(data2, subrOffset); + font.subrs = subrIndex.objects; + font.subrsBias = calcCFFSubroutineBias(font.subrs); + } else { + font.subrs = []; + font.subrsBias = 0; + } + var charStringsIndex; + if (opt.lowMemory) { + charStringsIndex = parseCFFIndexLowMemory(data2, start + topDict.charStrings); + font.nGlyphs = charStringsIndex.offsets.length; + } else { + charStringsIndex = parseCFFIndex(data2, start + topDict.charStrings); + font.nGlyphs = charStringsIndex.objects.length; + } + var charset = parseCFFCharset(data2, start + topDict.charset, font.nGlyphs, stringIndex.objects); + if (topDict.encoding === 0) { + font.cffEncoding = new CffEncoding(cffStandardEncoding, charset); + } else if (topDict.encoding === 1) { + font.cffEncoding = new CffEncoding(cffExpertEncoding, charset); + } else { + font.cffEncoding = parseCFFEncoding(data2, start + topDict.encoding, charset); + } + font.encoding = font.encoding || font.cffEncoding; + font.glyphs = new glyphset.GlyphSet(font); + if (opt.lowMemory) { + font._push = function(i3) { + var charString2 = getCffIndexObject(i3, charStringsIndex.offsets, data2, start + topDict.charStrings); + font.glyphs.push(i3, glyphset.cffGlyphLoader(font, i3, parseCFFCharstring, charString2)); + }; + } else { + for (var i = 0;i < font.nGlyphs; i += 1) { + var charString = charStringsIndex.objects[i]; + font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); + } + } +} +function encodeString(s, strings) { + var sid; + var i = cffStandardStrings.indexOf(s); + if (i >= 0) { + sid = i; + } + i = strings.indexOf(s); + if (i >= 0) { + sid = i + cffStandardStrings.length; + } else { + sid = cffStandardStrings.length + strings.length; + strings.push(s); + } + return sid; +} +function makeHeader() { + return new table.Record("Header", [ + { name: "major", type: "Card8", value: 1 }, + { name: "minor", type: "Card8", value: 0 }, + { name: "hdrSize", type: "Card8", value: 4 }, + { name: "major", type: "Card8", value: 1 } + ]); +} +function makeNameIndex(fontNames) { + var t4 = new table.Record("Name INDEX", [ + { name: "names", type: "INDEX", value: [] } + ]); + t4.names = []; + for (var i = 0;i < fontNames.length; i += 1) { + t4.names.push({ name: "name_" + i, type: "NAME", value: fontNames[i] }); + } + return t4; +} +function makeDict(meta, attrs, strings) { + var m = {}; + for (var i = 0;i < meta.length; i += 1) { + var entry = meta[i]; + var value2 = attrs[entry.name]; + if (value2 !== undefined && !equals2(value2, entry.value)) { + if (entry.type === "SID") { + value2 = encodeString(value2, strings); + } + m[entry.op] = { name: entry.name, type: entry.type, value: value2 }; + } + } + return m; +} +function makeTopDict(attrs, strings) { + var t4 = new table.Record("Top DICT", [ + { name: "dict", type: "DICT", value: {} } + ]); + t4.dict = makeDict(TOP_DICT_META, attrs, strings); + return t4; +} +function makeTopDictIndex(topDict) { + var t4 = new table.Record("Top DICT INDEX", [ + { name: "topDicts", type: "INDEX", value: [] } + ]); + t4.topDicts = [{ name: "topDict_0", type: "TABLE", value: topDict }]; + return t4; +} +function makeStringIndex(strings) { + var t4 = new table.Record("String INDEX", [ + { name: "strings", type: "INDEX", value: [] } + ]); + t4.strings = []; + for (var i = 0;i < strings.length; i += 1) { + t4.strings.push({ name: "string_" + i, type: "STRING", value: strings[i] }); + } + return t4; +} +function makeGlobalSubrIndex() { + return new table.Record("Global Subr INDEX", [ + { name: "subrs", type: "INDEX", value: [] } + ]); +} +function makeCharsets(glyphNames, strings) { + var t4 = new table.Record("Charsets", [ + { name: "format", type: "Card8", value: 0 } + ]); + for (var i = 0;i < glyphNames.length; i += 1) { + var glyphName = glyphNames[i]; + var glyphSID = encodeString(glyphName, strings); + t4.fields.push({ name: "glyph_" + i, type: "SID", value: glyphSID }); + } + return t4; +} +function glyphToOps(glyph) { + var ops = []; + var path = glyph.path; + ops.push({ name: "width", type: "NUMBER", value: glyph.advanceWidth }); + var x2 = 0; + var y3 = 0; + for (var i = 0;i < path.commands.length; i += 1) { + var dx = undefined; + var dy2 = undefined; + var cmd = path.commands[i]; + if (cmd.type === "Q") { + var _13 = 1 / 3; + var _23 = 2 / 3; + cmd = { + type: "C", + x: cmd.x, + y: cmd.y, + x1: Math.round(_13 * x2 + _23 * cmd.x1), + y1: Math.round(_13 * y3 + _23 * cmd.y1), + x2: Math.round(_13 * cmd.x + _23 * cmd.x1), + y2: Math.round(_13 * cmd.y + _23 * cmd.y1) + }; + } + if (cmd.type === "M") { + dx = Math.round(cmd.x - x2); + dy2 = Math.round(cmd.y - y3); + ops.push({ name: "dx", type: "NUMBER", value: dx }); + ops.push({ name: "dy", type: "NUMBER", value: dy2 }); + ops.push({ name: "rmoveto", type: "OP", value: 21 }); + x2 = Math.round(cmd.x); + y3 = Math.round(cmd.y); + } else if (cmd.type === "L") { + dx = Math.round(cmd.x - x2); + dy2 = Math.round(cmd.y - y3); + ops.push({ name: "dx", type: "NUMBER", value: dx }); + ops.push({ name: "dy", type: "NUMBER", value: dy2 }); + ops.push({ name: "rlineto", type: "OP", value: 5 }); + x2 = Math.round(cmd.x); + y3 = Math.round(cmd.y); + } else if (cmd.type === "C") { + var dx1 = Math.round(cmd.x1 - x2); + var dy1 = Math.round(cmd.y1 - y3); + var dx2 = Math.round(cmd.x2 - cmd.x1); + var dy22 = Math.round(cmd.y2 - cmd.y1); + dx = Math.round(cmd.x - cmd.x2); + dy2 = Math.round(cmd.y - cmd.y2); + ops.push({ name: "dx1", type: "NUMBER", value: dx1 }); + ops.push({ name: "dy1", type: "NUMBER", value: dy1 }); + ops.push({ name: "dx2", type: "NUMBER", value: dx2 }); + ops.push({ name: "dy2", type: "NUMBER", value: dy22 }); + ops.push({ name: "dx", type: "NUMBER", value: dx }); + ops.push({ name: "dy", type: "NUMBER", value: dy2 }); + ops.push({ name: "rrcurveto", type: "OP", value: 8 }); + x2 = Math.round(cmd.x); + y3 = Math.round(cmd.y); + } + } + ops.push({ name: "endchar", type: "OP", value: 14 }); + return ops; +} +function makeCharStringsIndex(glyphs) { + var t4 = new table.Record("CharStrings INDEX", [ + { name: "charStrings", type: "INDEX", value: [] } + ]); + for (var i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + var ops = glyphToOps(glyph); + t4.charStrings.push({ name: glyph.name, type: "CHARSTRING", value: ops }); + } + return t4; +} +function makePrivateDict(attrs, strings) { + var t4 = new table.Record("Private DICT", [ + { name: "dict", type: "DICT", value: {} } + ]); + t4.dict = makeDict(PRIVATE_DICT_META, attrs, strings); + return t4; +} +function makeCFFTable(glyphs, options) { + var t4 = new table.Table("CFF ", [ + { name: "header", type: "RECORD" }, + { name: "nameIndex", type: "RECORD" }, + { name: "topDictIndex", type: "RECORD" }, + { name: "stringIndex", type: "RECORD" }, + { name: "globalSubrIndex", type: "RECORD" }, + { name: "charsets", type: "RECORD" }, + { name: "charStringsIndex", type: "RECORD" }, + { name: "privateDict", type: "RECORD" } + ]); + var fontScale = 1 / options.unitsPerEm; + var attrs = { + version: options.version, + fullName: options.fullName, + familyName: options.familyName, + weight: options.weightName, + fontBBox: options.fontBBox || [0, 0, 0, 0], + fontMatrix: [fontScale, 0, 0, fontScale, 0, 0], + charset: 999, + encoding: 0, + charStrings: 999, + private: [0, 999] + }; + var privateAttrs = {}; + var glyphNames = []; + var glyph; + for (var i = 1;i < glyphs.length; i += 1) { + glyph = glyphs.get(i); + glyphNames.push(glyph.name); + } + var strings = []; + t4.header = makeHeader(); + t4.nameIndex = makeNameIndex([options.postScriptName]); + var topDict = makeTopDict(attrs, strings); + t4.topDictIndex = makeTopDictIndex(topDict); + t4.globalSubrIndex = makeGlobalSubrIndex(); + t4.charsets = makeCharsets(glyphNames, strings); + t4.charStringsIndex = makeCharStringsIndex(glyphs); + t4.privateDict = makePrivateDict(privateAttrs, strings); + t4.stringIndex = makeStringIndex(strings); + var startOffset = t4.header.sizeOf() + t4.nameIndex.sizeOf() + t4.topDictIndex.sizeOf() + t4.stringIndex.sizeOf() + t4.globalSubrIndex.sizeOf(); + attrs.charset = startOffset; + attrs.encoding = 0; + attrs.charStrings = attrs.charset + t4.charsets.sizeOf(); + attrs.private[1] = attrs.charStrings + t4.charStringsIndex.sizeOf(); + topDict = makeTopDict(attrs, strings); + t4.topDictIndex = makeTopDictIndex(topDict); + return t4; +} +var cff = { parse: parseCFFTable, make: makeCFFTable }; +function parseHeadTable(data2, start) { + var head = {}; + var p = new parse.Parser(data2, start); + head.version = p.parseVersion(); + head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000; + head.checkSumAdjustment = p.parseULong(); + head.magicNumber = p.parseULong(); + check.argument(head.magicNumber === 1594834165, "Font header has wrong magic number."); + head.flags = p.parseUShort(); + head.unitsPerEm = p.parseUShort(); + head.created = p.parseLongDateTime(); + head.modified = p.parseLongDateTime(); + head.xMin = p.parseShort(); + head.yMin = p.parseShort(); + head.xMax = p.parseShort(); + head.yMax = p.parseShort(); + head.macStyle = p.parseUShort(); + head.lowestRecPPEM = p.parseUShort(); + head.fontDirectionHint = p.parseShort(); + head.indexToLocFormat = p.parseShort(); + head.glyphDataFormat = p.parseShort(); + return head; +} +function makeHeadTable(options) { + var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800; + var createdTimestamp = timestamp; + if (options.createdTimestamp) { + createdTimestamp = options.createdTimestamp + 2082844800; + } + return new table.Table("head", [ + { name: "version", type: "FIXED", value: 65536 }, + { name: "fontRevision", type: "FIXED", value: 65536 }, + { name: "checkSumAdjustment", type: "ULONG", value: 0 }, + { name: "magicNumber", type: "ULONG", value: 1594834165 }, + { name: "flags", type: "USHORT", value: 0 }, + { name: "unitsPerEm", type: "USHORT", value: 1000 }, + { name: "created", type: "LONGDATETIME", value: createdTimestamp }, + { name: "modified", type: "LONGDATETIME", value: timestamp }, + { name: "xMin", type: "SHORT", value: 0 }, + { name: "yMin", type: "SHORT", value: 0 }, + { name: "xMax", type: "SHORT", value: 0 }, + { name: "yMax", type: "SHORT", value: 0 }, + { name: "macStyle", type: "USHORT", value: 0 }, + { name: "lowestRecPPEM", type: "USHORT", value: 0 }, + { name: "fontDirectionHint", type: "SHORT", value: 2 }, + { name: "indexToLocFormat", type: "SHORT", value: 0 }, + { name: "glyphDataFormat", type: "SHORT", value: 0 } + ], options); +} +var head = { parse: parseHeadTable, make: makeHeadTable }; +function parseHheaTable(data2, start) { + var hhea = {}; + var p = new parse.Parser(data2, start); + hhea.version = p.parseVersion(); + hhea.ascender = p.parseShort(); + hhea.descender = p.parseShort(); + hhea.lineGap = p.parseShort(); + hhea.advanceWidthMax = p.parseUShort(); + hhea.minLeftSideBearing = p.parseShort(); + hhea.minRightSideBearing = p.parseShort(); + hhea.xMaxExtent = p.parseShort(); + hhea.caretSlopeRise = p.parseShort(); + hhea.caretSlopeRun = p.parseShort(); + hhea.caretOffset = p.parseShort(); + p.relativeOffset += 8; + hhea.metricDataFormat = p.parseShort(); + hhea.numberOfHMetrics = p.parseUShort(); + return hhea; +} +function makeHheaTable(options) { + return new table.Table("hhea", [ + { name: "version", type: "FIXED", value: 65536 }, + { name: "ascender", type: "FWORD", value: 0 }, + { name: "descender", type: "FWORD", value: 0 }, + { name: "lineGap", type: "FWORD", value: 0 }, + { name: "advanceWidthMax", type: "UFWORD", value: 0 }, + { name: "minLeftSideBearing", type: "FWORD", value: 0 }, + { name: "minRightSideBearing", type: "FWORD", value: 0 }, + { name: "xMaxExtent", type: "FWORD", value: 0 }, + { name: "caretSlopeRise", type: "SHORT", value: 1 }, + { name: "caretSlopeRun", type: "SHORT", value: 0 }, + { name: "caretOffset", type: "SHORT", value: 0 }, + { name: "reserved1", type: "SHORT", value: 0 }, + { name: "reserved2", type: "SHORT", value: 0 }, + { name: "reserved3", type: "SHORT", value: 0 }, + { name: "reserved4", type: "SHORT", value: 0 }, + { name: "metricDataFormat", type: "SHORT", value: 0 }, + { name: "numberOfHMetrics", type: "USHORT", value: 0 } + ], options); +} +var hhea = { parse: parseHheaTable, make: makeHheaTable }; +function parseHmtxTableAll(data2, start, numMetrics, numGlyphs, glyphs) { + var advanceWidth; + var leftSideBearing; + var p = new parse.Parser(data2, start); + for (var i = 0;i < numGlyphs; i += 1) { + if (i < numMetrics) { + advanceWidth = p.parseUShort(); + leftSideBearing = p.parseShort(); + } + var glyph = glyphs.get(i); + glyph.advanceWidth = advanceWidth; + glyph.leftSideBearing = leftSideBearing; + } +} +function parseHmtxTableOnLowMemory(font, data2, start, numMetrics, numGlyphs) { + font._hmtxTableData = {}; + var advanceWidth; + var leftSideBearing; + var p = new parse.Parser(data2, start); + for (var i = 0;i < numGlyphs; i += 1) { + if (i < numMetrics) { + advanceWidth = p.parseUShort(); + leftSideBearing = p.parseShort(); + } + font._hmtxTableData[i] = { + advanceWidth, + leftSideBearing + }; + } +} +function parseHmtxTable(font, data2, start, numMetrics, numGlyphs, glyphs, opt) { + if (opt.lowMemory) { + parseHmtxTableOnLowMemory(font, data2, start, numMetrics, numGlyphs); + } else { + parseHmtxTableAll(data2, start, numMetrics, numGlyphs, glyphs); + } +} +function makeHmtxTable(glyphs) { + var t4 = new table.Table("hmtx", []); + for (var i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + var advanceWidth = glyph.advanceWidth || 0; + var leftSideBearing = glyph.leftSideBearing || 0; + t4.fields.push({ name: "advanceWidth_" + i, type: "USHORT", value: advanceWidth }); + t4.fields.push({ name: "leftSideBearing_" + i, type: "SHORT", value: leftSideBearing }); + } + return t4; +} +var hmtx = { parse: parseHmtxTable, make: makeHmtxTable }; +function makeLtagTable(tags) { + var result = new table.Table("ltag", [ + { name: "version", type: "ULONG", value: 1 }, + { name: "flags", type: "ULONG", value: 0 }, + { name: "numTags", type: "ULONG", value: tags.length } + ]); + var stringPool = ""; + var stringPoolOffset = 12 + tags.length * 4; + for (var i = 0;i < tags.length; ++i) { + var pos = stringPool.indexOf(tags[i]); + if (pos < 0) { + pos = stringPool.length; + stringPool += tags[i]; + } + result.fields.push({ name: "offset " + i, type: "USHORT", value: stringPoolOffset + pos }); + result.fields.push({ name: "length " + i, type: "USHORT", value: tags[i].length }); + } + result.fields.push({ name: "stringPool", type: "CHARARRAY", value: stringPool }); + return result; +} +function parseLtagTable(data2, start) { + var p = new parse.Parser(data2, start); + var tableVersion = p.parseULong(); + check.argument(tableVersion === 1, "Unsupported ltag table version."); + p.skip("uLong", 1); + var numTags = p.parseULong(); + var tags = []; + for (var i = 0;i < numTags; i++) { + var tag = ""; + var offset = start + p.parseUShort(); + var length2 = p.parseUShort(); + for (var j2 = offset;j2 < offset + length2; ++j2) { + tag += String.fromCharCode(data2.getInt8(j2)); + } + tags.push(tag); + } + return tags; +} +var ltag = { make: makeLtagTable, parse: parseLtagTable }; +function parseMaxpTable(data2, start) { + var maxp = {}; + var p = new parse.Parser(data2, start); + maxp.version = p.parseVersion(); + maxp.numGlyphs = p.parseUShort(); + if (maxp.version === 1) { + maxp.maxPoints = p.parseUShort(); + maxp.maxContours = p.parseUShort(); + maxp.maxCompositePoints = p.parseUShort(); + maxp.maxCompositeContours = p.parseUShort(); + maxp.maxZones = p.parseUShort(); + maxp.maxTwilightPoints = p.parseUShort(); + maxp.maxStorage = p.parseUShort(); + maxp.maxFunctionDefs = p.parseUShort(); + maxp.maxInstructionDefs = p.parseUShort(); + maxp.maxStackElements = p.parseUShort(); + maxp.maxSizeOfInstructions = p.parseUShort(); + maxp.maxComponentElements = p.parseUShort(); + maxp.maxComponentDepth = p.parseUShort(); + } + return maxp; +} +function makeMaxpTable(numGlyphs) { + return new table.Table("maxp", [ + { name: "version", type: "FIXED", value: 20480 }, + { name: "numGlyphs", type: "USHORT", value: numGlyphs } + ]); +} +var maxp = { parse: parseMaxpTable, make: makeMaxpTable }; +var nameTableNames = [ + "copyright", + "fontFamily", + "fontSubfamily", + "uniqueID", + "fullName", + "version", + "postScriptName", + "trademark", + "manufacturer", + "designer", + "description", + "manufacturerURL", + "designerURL", + "license", + "licenseURL", + "reserved", + "preferredFamily", + "preferredSubfamily", + "compatibleFullName", + "sampleText", + "postScriptFindFontName", + "wwsFamily", + "wwsSubfamily" +]; +var macLanguages = { + 0: "en", + 1: "fr", + 2: "de", + 3: "it", + 4: "nl", + 5: "sv", + 6: "es", + 7: "da", + 8: "pt", + 9: "no", + 10: "he", + 11: "ja", + 12: "ar", + 13: "fi", + 14: "el", + 15: "is", + 16: "mt", + 17: "tr", + 18: "hr", + 19: "zh-Hant", + 20: "ur", + 21: "hi", + 22: "th", + 23: "ko", + 24: "lt", + 25: "pl", + 26: "hu", + 27: "es", + 28: "lv", + 29: "se", + 30: "fo", + 31: "fa", + 32: "ru", + 33: "zh", + 34: "nl-BE", + 35: "ga", + 36: "sq", + 37: "ro", + 38: "cz", + 39: "sk", + 40: "si", + 41: "yi", + 42: "sr", + 43: "mk", + 44: "bg", + 45: "uk", + 46: "be", + 47: "uz", + 48: "kk", + 49: "az-Cyrl", + 50: "az-Arab", + 51: "hy", + 52: "ka", + 53: "mo", + 54: "ky", + 55: "tg", + 56: "tk", + 57: "mn-CN", + 58: "mn", + 59: "ps", + 60: "ks", + 61: "ku", + 62: "sd", + 63: "bo", + 64: "ne", + 65: "sa", + 66: "mr", + 67: "bn", + 68: "as", + 69: "gu", + 70: "pa", + 71: "or", + 72: "ml", + 73: "kn", + 74: "ta", + 75: "te", + 76: "si", + 77: "my", + 78: "km", + 79: "lo", + 80: "vi", + 81: "id", + 82: "tl", + 83: "ms", + 84: "ms-Arab", + 85: "am", + 86: "ti", + 87: "om", + 88: "so", + 89: "sw", + 90: "rw", + 91: "rn", + 92: "ny", + 93: "mg", + 94: "eo", + 128: "cy", + 129: "eu", + 130: "ca", + 131: "la", + 132: "qu", + 133: "gn", + 134: "ay", + 135: "tt", + 136: "ug", + 137: "dz", + 138: "jv", + 139: "su", + 140: "gl", + 141: "af", + 142: "br", + 143: "iu", + 144: "gd", + 145: "gv", + 146: "ga", + 147: "to", + 148: "el-polyton", + 149: "kl", + 150: "az", + 151: "nn" +}; +var macLanguageToScript = { + 0: 0, + 1: 0, + 2: 0, + 3: 0, + 4: 0, + 5: 0, + 6: 0, + 7: 0, + 8: 0, + 9: 0, + 10: 5, + 11: 1, + 12: 4, + 13: 0, + 14: 6, + 15: 0, + 16: 0, + 17: 0, + 18: 0, + 19: 2, + 20: 4, + 21: 9, + 22: 21, + 23: 3, + 24: 29, + 25: 29, + 26: 29, + 27: 29, + 28: 29, + 29: 0, + 30: 0, + 31: 4, + 32: 7, + 33: 25, + 34: 0, + 35: 0, + 36: 0, + 37: 0, + 38: 29, + 39: 29, + 40: 0, + 41: 5, + 42: 7, + 43: 7, + 44: 7, + 45: 7, + 46: 7, + 47: 7, + 48: 7, + 49: 7, + 50: 4, + 51: 24, + 52: 23, + 53: 7, + 54: 7, + 55: 7, + 56: 7, + 57: 27, + 58: 7, + 59: 4, + 60: 4, + 61: 4, + 62: 4, + 63: 26, + 64: 9, + 65: 9, + 66: 9, + 67: 13, + 68: 13, + 69: 11, + 70: 10, + 71: 12, + 72: 17, + 73: 16, + 74: 14, + 75: 15, + 76: 18, + 77: 19, + 78: 20, + 79: 22, + 80: 30, + 81: 0, + 82: 0, + 83: 0, + 84: 4, + 85: 28, + 86: 28, + 87: 28, + 88: 0, + 89: 0, + 90: 0, + 91: 0, + 92: 0, + 93: 0, + 94: 0, + 128: 0, + 129: 0, + 130: 0, + 131: 0, + 132: 0, + 133: 0, + 134: 0, + 135: 7, + 136: 4, + 137: 26, + 138: 0, + 139: 0, + 140: 0, + 141: 0, + 142: 0, + 143: 28, + 144: 0, + 145: 0, + 146: 0, + 147: 0, + 148: 6, + 149: 0, + 150: 0, + 151: 0 +}; +var windowsLanguages = { + 1078: "af", + 1052: "sq", + 1156: "gsw", + 1118: "am", + 5121: "ar-DZ", + 15361: "ar-BH", + 3073: "ar", + 2049: "ar-IQ", + 11265: "ar-JO", + 13313: "ar-KW", + 12289: "ar-LB", + 4097: "ar-LY", + 6145: "ary", + 8193: "ar-OM", + 16385: "ar-QA", + 1025: "ar-SA", + 10241: "ar-SY", + 7169: "aeb", + 14337: "ar-AE", + 9217: "ar-YE", + 1067: "hy", + 1101: "as", + 2092: "az-Cyrl", + 1068: "az", + 1133: "ba", + 1069: "eu", + 1059: "be", + 2117: "bn", + 1093: "bn-IN", + 8218: "bs-Cyrl", + 5146: "bs", + 1150: "br", + 1026: "bg", + 1027: "ca", + 3076: "zh-HK", + 5124: "zh-MO", + 2052: "zh", + 4100: "zh-SG", + 1028: "zh-TW", + 1155: "co", + 1050: "hr", + 4122: "hr-BA", + 1029: "cs", + 1030: "da", + 1164: "prs", + 1125: "dv", + 2067: "nl-BE", + 1043: "nl", + 3081: "en-AU", + 10249: "en-BZ", + 4105: "en-CA", + 9225: "en-029", + 16393: "en-IN", + 6153: "en-IE", + 8201: "en-JM", + 17417: "en-MY", + 5129: "en-NZ", + 13321: "en-PH", + 18441: "en-SG", + 7177: "en-ZA", + 11273: "en-TT", + 2057: "en-GB", + 1033: "en", + 12297: "en-ZW", + 1061: "et", + 1080: "fo", + 1124: "fil", + 1035: "fi", + 2060: "fr-BE", + 3084: "fr-CA", + 1036: "fr", + 5132: "fr-LU", + 6156: "fr-MC", + 4108: "fr-CH", + 1122: "fy", + 1110: "gl", + 1079: "ka", + 3079: "de-AT", + 1031: "de", + 5127: "de-LI", + 4103: "de-LU", + 2055: "de-CH", + 1032: "el", + 1135: "kl", + 1095: "gu", + 1128: "ha", + 1037: "he", + 1081: "hi", + 1038: "hu", + 1039: "is", + 1136: "ig", + 1057: "id", + 1117: "iu", + 2141: "iu-Latn", + 2108: "ga", + 1076: "xh", + 1077: "zu", + 1040: "it", + 2064: "it-CH", + 1041: "ja", + 1099: "kn", + 1087: "kk", + 1107: "km", + 1158: "quc", + 1159: "rw", + 1089: "sw", + 1111: "kok", + 1042: "ko", + 1088: "ky", + 1108: "lo", + 1062: "lv", + 1063: "lt", + 2094: "dsb", + 1134: "lb", + 1071: "mk", + 2110: "ms-BN", + 1086: "ms", + 1100: "ml", + 1082: "mt", + 1153: "mi", + 1146: "arn", + 1102: "mr", + 1148: "moh", + 1104: "mn", + 2128: "mn-CN", + 1121: "ne", + 1044: "nb", + 2068: "nn", + 1154: "oc", + 1096: "or", + 1123: "ps", + 1045: "pl", + 1046: "pt", + 2070: "pt-PT", + 1094: "pa", + 1131: "qu-BO", + 2155: "qu-EC", + 3179: "qu", + 1048: "ro", + 1047: "rm", + 1049: "ru", + 9275: "smn", + 4155: "smj-NO", + 5179: "smj", + 3131: "se-FI", + 1083: "se", + 2107: "se-SE", + 8251: "sms", + 6203: "sma-NO", + 7227: "sms", + 1103: "sa", + 7194: "sr-Cyrl-BA", + 3098: "sr", + 6170: "sr-Latn-BA", + 2074: "sr-Latn", + 1132: "nso", + 1074: "tn", + 1115: "si", + 1051: "sk", + 1060: "sl", + 11274: "es-AR", + 16394: "es-BO", + 13322: "es-CL", + 9226: "es-CO", + 5130: "es-CR", + 7178: "es-DO", + 12298: "es-EC", + 17418: "es-SV", + 4106: "es-GT", + 18442: "es-HN", + 2058: "es-MX", + 19466: "es-NI", + 6154: "es-PA", + 15370: "es-PY", + 10250: "es-PE", + 20490: "es-PR", + 3082: "es", + 1034: "es", + 21514: "es-US", + 14346: "es-UY", + 8202: "es-VE", + 2077: "sv-FI", + 1053: "sv", + 1114: "syr", + 1064: "tg", + 2143: "tzm", + 1097: "ta", + 1092: "tt", + 1098: "te", + 1054: "th", + 1105: "bo", + 1055: "tr", + 1090: "tk", + 1152: "ug", + 1058: "uk", + 1070: "hsb", + 1056: "ur", + 2115: "uz-Cyrl", + 1091: "uz", + 1066: "vi", + 1106: "cy", + 1160: "wo", + 1157: "sah", + 1144: "ii", + 1130: "yo" +}; +function getLanguageCode(platformID, languageID, ltag2) { + switch (platformID) { + case 0: + if (languageID === 65535) { + return "und"; + } else if (ltag2) { + return ltag2[languageID]; + } + break; + case 1: + return macLanguages[languageID]; + case 3: + return windowsLanguages[languageID]; + } + return; +} +var utf16 = "utf-16"; +var macScriptEncodings = { + 0: "macintosh", + 1: "x-mac-japanese", + 2: "x-mac-chinesetrad", + 3: "x-mac-korean", + 6: "x-mac-greek", + 7: "x-mac-cyrillic", + 9: "x-mac-devanagai", + 10: "x-mac-gurmukhi", + 11: "x-mac-gujarati", + 12: "x-mac-oriya", + 13: "x-mac-bengali", + 14: "x-mac-tamil", + 15: "x-mac-telugu", + 16: "x-mac-kannada", + 17: "x-mac-malayalam", + 18: "x-mac-sinhalese", + 19: "x-mac-burmese", + 20: "x-mac-khmer", + 21: "x-mac-thai", + 22: "x-mac-lao", + 23: "x-mac-georgian", + 24: "x-mac-armenian", + 25: "x-mac-chinesesimp", + 26: "x-mac-tibetan", + 27: "x-mac-mongolian", + 28: "x-mac-ethiopic", + 29: "x-mac-ce", + 30: "x-mac-vietnamese", + 31: "x-mac-extarabic" +}; +var macLanguageEncodings = { + 15: "x-mac-icelandic", + 17: "x-mac-turkish", + 18: "x-mac-croatian", + 24: "x-mac-ce", + 25: "x-mac-ce", + 26: "x-mac-ce", + 27: "x-mac-ce", + 28: "x-mac-ce", + 30: "x-mac-icelandic", + 37: "x-mac-romanian", + 38: "x-mac-ce", + 39: "x-mac-ce", + 40: "x-mac-ce", + 143: "x-mac-inuit", + 146: "x-mac-gaelic" +}; +function getEncoding(platformID, encodingID, languageID) { + switch (platformID) { + case 0: + return utf16; + case 1: + return macLanguageEncodings[languageID] || macScriptEncodings[encodingID]; + case 3: + if (encodingID === 1 || encodingID === 10) { + return utf16; + } + break; + } + return; +} +function parseNameTable(data2, start, ltag2) { + var name2 = {}; + var p = new parse.Parser(data2, start); + var format = p.parseUShort(); + var count = p.parseUShort(); + var stringOffset = p.offset + p.parseUShort(); + for (var i = 0;i < count; i++) { + var platformID = p.parseUShort(); + var encodingID = p.parseUShort(); + var languageID = p.parseUShort(); + var nameID = p.parseUShort(); + var property2 = nameTableNames[nameID] || nameID; + var byteLength = p.parseUShort(); + var offset = p.parseUShort(); + var language = getLanguageCode(platformID, languageID, ltag2); + var encoding = getEncoding(platformID, encodingID, languageID); + if (encoding !== undefined && language !== undefined) { + var text2 = undefined; + if (encoding === utf16) { + text2 = decode.UTF16(data2, stringOffset + offset, byteLength); + } else { + text2 = decode.MACSTRING(data2, stringOffset + offset, byteLength, encoding); + } + if (text2) { + var translations = name2[property2]; + if (translations === undefined) { + translations = name2[property2] = {}; + } + translations[language] = text2; + } + } + } + var langTagCount = 0; + if (format === 1) { + langTagCount = p.parseUShort(); + } + return name2; +} +function reverseDict(dict) { + var result = {}; + for (var key2 in dict) { + result[dict[key2]] = parseInt(key2); + } + return result; +} +function makeNameRecord(platformID, encodingID, languageID, nameID, length2, offset) { + return new table.Record("NameRecord", [ + { name: "platformID", type: "USHORT", value: platformID }, + { name: "encodingID", type: "USHORT", value: encodingID }, + { name: "languageID", type: "USHORT", value: languageID }, + { name: "nameID", type: "USHORT", value: nameID }, + { name: "length", type: "USHORT", value: length2 }, + { name: "offset", type: "USHORT", value: offset } + ]); +} +function findSubArray(needle, haystack) { + var needleLength = needle.length; + var limit = haystack.length - needleLength + 1; + loop: + for (var pos = 0;pos < limit; pos++) { + for (;pos < limit; pos++) { + for (var k2 = 0;k2 < needleLength; k2++) { + if (haystack[pos + k2] !== needle[k2]) { + continue loop; + } + } + return pos; + } + } + return -1; +} +function addStringToPool(s, pool) { + var offset = findSubArray(s, pool); + if (offset < 0) { + offset = pool.length; + var i = 0; + var len = s.length; + for (;i < len; ++i) { + pool.push(s[i]); + } + } + return offset; +} +function makeNameTable(names, ltag2) { + var nameID; + var nameIDs = []; + var namesWithNumericKeys = {}; + var nameTableIds = reverseDict(nameTableNames); + for (var key2 in names) { + var id = nameTableIds[key2]; + if (id === undefined) { + id = key2; + } + nameID = parseInt(id); + if (isNaN(nameID)) { + throw new Error('Name table entry "' + key2 + '" does not exist, see nameTableNames for complete list.'); + } + namesWithNumericKeys[nameID] = names[key2]; + nameIDs.push(nameID); + } + var macLanguageIds = reverseDict(macLanguages); + var windowsLanguageIds = reverseDict(windowsLanguages); + var nameRecords = []; + var stringPool = []; + for (var i = 0;i < nameIDs.length; i++) { + nameID = nameIDs[i]; + var translations = namesWithNumericKeys[nameID]; + for (var lang in translations) { + var text2 = translations[lang]; + var macPlatform = 1; + var macLanguage = macLanguageIds[lang]; + var macScript = macLanguageToScript[macLanguage]; + var macEncoding = getEncoding(macPlatform, macScript, macLanguage); + var macName = encode.MACSTRING(text2, macEncoding); + if (macName === undefined) { + macPlatform = 0; + macLanguage = ltag2.indexOf(lang); + if (macLanguage < 0) { + macLanguage = ltag2.length; + ltag2.push(lang); + } + macScript = 4; + macName = encode.UTF16(text2); + } + var macNameOffset = addStringToPool(macName, stringPool); + nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage, nameID, macName.length, macNameOffset)); + var winLanguage = windowsLanguageIds[lang]; + if (winLanguage !== undefined) { + var winName = encode.UTF16(text2); + var winNameOffset = addStringToPool(winName, stringPool); + nameRecords.push(makeNameRecord(3, 1, winLanguage, nameID, winName.length, winNameOffset)); + } + } + } + nameRecords.sort(function(a, b) { + return a.platformID - b.platformID || a.encodingID - b.encodingID || a.languageID - b.languageID || a.nameID - b.nameID; + }); + var t4 = new table.Table("name", [ + { name: "format", type: "USHORT", value: 0 }, + { name: "count", type: "USHORT", value: nameRecords.length }, + { name: "stringOffset", type: "USHORT", value: 6 + nameRecords.length * 12 } + ]); + for (var r = 0;r < nameRecords.length; r++) { + t4.fields.push({ name: "record_" + r, type: "RECORD", value: nameRecords[r] }); + } + t4.fields.push({ name: "strings", type: "LITERAL", value: stringPool }); + return t4; +} +var _name = { parse: parseNameTable, make: makeNameTable }; +var unicodeRanges = [ + { begin: 0, end: 127 }, + { begin: 128, end: 255 }, + { begin: 256, end: 383 }, + { begin: 384, end: 591 }, + { begin: 592, end: 687 }, + { begin: 688, end: 767 }, + { begin: 768, end: 879 }, + { begin: 880, end: 1023 }, + { begin: 11392, end: 11519 }, + { begin: 1024, end: 1279 }, + { begin: 1328, end: 1423 }, + { begin: 1424, end: 1535 }, + { begin: 42240, end: 42559 }, + { begin: 1536, end: 1791 }, + { begin: 1984, end: 2047 }, + { begin: 2304, end: 2431 }, + { begin: 2432, end: 2559 }, + { begin: 2560, end: 2687 }, + { begin: 2688, end: 2815 }, + { begin: 2816, end: 2943 }, + { begin: 2944, end: 3071 }, + { begin: 3072, end: 3199 }, + { begin: 3200, end: 3327 }, + { begin: 3328, end: 3455 }, + { begin: 3584, end: 3711 }, + { begin: 3712, end: 3839 }, + { begin: 4256, end: 4351 }, + { begin: 6912, end: 7039 }, + { begin: 4352, end: 4607 }, + { begin: 7680, end: 7935 }, + { begin: 7936, end: 8191 }, + { begin: 8192, end: 8303 }, + { begin: 8304, end: 8351 }, + { begin: 8352, end: 8399 }, + { begin: 8400, end: 8447 }, + { begin: 8448, end: 8527 }, + { begin: 8528, end: 8591 }, + { begin: 8592, end: 8703 }, + { begin: 8704, end: 8959 }, + { begin: 8960, end: 9215 }, + { begin: 9216, end: 9279 }, + { begin: 9280, end: 9311 }, + { begin: 9312, end: 9471 }, + { begin: 9472, end: 9599 }, + { begin: 9600, end: 9631 }, + { begin: 9632, end: 9727 }, + { begin: 9728, end: 9983 }, + { begin: 9984, end: 10175 }, + { begin: 12288, end: 12351 }, + { begin: 12352, end: 12447 }, + { begin: 12448, end: 12543 }, + { begin: 12544, end: 12591 }, + { begin: 12592, end: 12687 }, + { begin: 43072, end: 43135 }, + { begin: 12800, end: 13055 }, + { begin: 13056, end: 13311 }, + { begin: 44032, end: 55215 }, + { begin: 55296, end: 57343 }, + { begin: 67840, end: 67871 }, + { begin: 19968, end: 40959 }, + { begin: 57344, end: 63743 }, + { begin: 12736, end: 12783 }, + { begin: 64256, end: 64335 }, + { begin: 64336, end: 65023 }, + { begin: 65056, end: 65071 }, + { begin: 65040, end: 65055 }, + { begin: 65104, end: 65135 }, + { begin: 65136, end: 65279 }, + { begin: 65280, end: 65519 }, + { begin: 65520, end: 65535 }, + { begin: 3840, end: 4095 }, + { begin: 1792, end: 1871 }, + { begin: 1920, end: 1983 }, + { begin: 3456, end: 3583 }, + { begin: 4096, end: 4255 }, + { begin: 4608, end: 4991 }, + { begin: 5024, end: 5119 }, + { begin: 5120, end: 5759 }, + { begin: 5760, end: 5791 }, + { begin: 5792, end: 5887 }, + { begin: 6016, end: 6143 }, + { begin: 6144, end: 6319 }, + { begin: 10240, end: 10495 }, + { begin: 40960, end: 42127 }, + { begin: 5888, end: 5919 }, + { begin: 66304, end: 66351 }, + { begin: 66352, end: 66383 }, + { begin: 66560, end: 66639 }, + { begin: 118784, end: 119039 }, + { begin: 119808, end: 120831 }, + { begin: 1044480, end: 1048573 }, + { begin: 65024, end: 65039 }, + { begin: 917504, end: 917631 }, + { begin: 6400, end: 6479 }, + { begin: 6480, end: 6527 }, + { begin: 6528, end: 6623 }, + { begin: 6656, end: 6687 }, + { begin: 11264, end: 11359 }, + { begin: 11568, end: 11647 }, + { begin: 19904, end: 19967 }, + { begin: 43008, end: 43055 }, + { begin: 65536, end: 65663 }, + { begin: 65856, end: 65935 }, + { begin: 66432, end: 66463 }, + { begin: 66464, end: 66527 }, + { begin: 66640, end: 66687 }, + { begin: 66688, end: 66735 }, + { begin: 67584, end: 67647 }, + { begin: 68096, end: 68191 }, + { begin: 119552, end: 119647 }, + { begin: 73728, end: 74751 }, + { begin: 119648, end: 119679 }, + { begin: 7040, end: 7103 }, + { begin: 7168, end: 7247 }, + { begin: 7248, end: 7295 }, + { begin: 43136, end: 43231 }, + { begin: 43264, end: 43311 }, + { begin: 43312, end: 43359 }, + { begin: 43520, end: 43615 }, + { begin: 65936, end: 65999 }, + { begin: 66000, end: 66047 }, + { begin: 66208, end: 66271 }, + { begin: 127024, end: 127135 } +]; +function getUnicodeRange(unicode) { + for (var i = 0;i < unicodeRanges.length; i += 1) { + var range = unicodeRanges[i]; + if (unicode >= range.begin && unicode < range.end) { + return i; + } + } + return -1; +} +function parseOS2Table(data2, start) { + var os2 = {}; + var p = new parse.Parser(data2, start); + os2.version = p.parseUShort(); + os2.xAvgCharWidth = p.parseShort(); + os2.usWeightClass = p.parseUShort(); + os2.usWidthClass = p.parseUShort(); + os2.fsType = p.parseUShort(); + os2.ySubscriptXSize = p.parseShort(); + os2.ySubscriptYSize = p.parseShort(); + os2.ySubscriptXOffset = p.parseShort(); + os2.ySubscriptYOffset = p.parseShort(); + os2.ySuperscriptXSize = p.parseShort(); + os2.ySuperscriptYSize = p.parseShort(); + os2.ySuperscriptXOffset = p.parseShort(); + os2.ySuperscriptYOffset = p.parseShort(); + os2.yStrikeoutSize = p.parseShort(); + os2.yStrikeoutPosition = p.parseShort(); + os2.sFamilyClass = p.parseShort(); + os2.panose = []; + for (var i = 0;i < 10; i++) { + os2.panose[i] = p.parseByte(); + } + os2.ulUnicodeRange1 = p.parseULong(); + os2.ulUnicodeRange2 = p.parseULong(); + os2.ulUnicodeRange3 = p.parseULong(); + os2.ulUnicodeRange4 = p.parseULong(); + os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte()); + os2.fsSelection = p.parseUShort(); + os2.usFirstCharIndex = p.parseUShort(); + os2.usLastCharIndex = p.parseUShort(); + os2.sTypoAscender = p.parseShort(); + os2.sTypoDescender = p.parseShort(); + os2.sTypoLineGap = p.parseShort(); + os2.usWinAscent = p.parseUShort(); + os2.usWinDescent = p.parseUShort(); + if (os2.version >= 1) { + os2.ulCodePageRange1 = p.parseULong(); + os2.ulCodePageRange2 = p.parseULong(); + } + if (os2.version >= 2) { + os2.sxHeight = p.parseShort(); + os2.sCapHeight = p.parseShort(); + os2.usDefaultChar = p.parseUShort(); + os2.usBreakChar = p.parseUShort(); + os2.usMaxContent = p.parseUShort(); + } + return os2; +} +function makeOS2Table(options) { + return new table.Table("OS/2", [ + { name: "version", type: "USHORT", value: 3 }, + { name: "xAvgCharWidth", type: "SHORT", value: 0 }, + { name: "usWeightClass", type: "USHORT", value: 0 }, + { name: "usWidthClass", type: "USHORT", value: 0 }, + { name: "fsType", type: "USHORT", value: 0 }, + { name: "ySubscriptXSize", type: "SHORT", value: 650 }, + { name: "ySubscriptYSize", type: "SHORT", value: 699 }, + { name: "ySubscriptXOffset", type: "SHORT", value: 0 }, + { name: "ySubscriptYOffset", type: "SHORT", value: 140 }, + { name: "ySuperscriptXSize", type: "SHORT", value: 650 }, + { name: "ySuperscriptYSize", type: "SHORT", value: 699 }, + { name: "ySuperscriptXOffset", type: "SHORT", value: 0 }, + { name: "ySuperscriptYOffset", type: "SHORT", value: 479 }, + { name: "yStrikeoutSize", type: "SHORT", value: 49 }, + { name: "yStrikeoutPosition", type: "SHORT", value: 258 }, + { name: "sFamilyClass", type: "SHORT", value: 0 }, + { name: "bFamilyType", type: "BYTE", value: 0 }, + { name: "bSerifStyle", type: "BYTE", value: 0 }, + { name: "bWeight", type: "BYTE", value: 0 }, + { name: "bProportion", type: "BYTE", value: 0 }, + { name: "bContrast", type: "BYTE", value: 0 }, + { name: "bStrokeVariation", type: "BYTE", value: 0 }, + { name: "bArmStyle", type: "BYTE", value: 0 }, + { name: "bLetterform", type: "BYTE", value: 0 }, + { name: "bMidline", type: "BYTE", value: 0 }, + { name: "bXHeight", type: "BYTE", value: 0 }, + { name: "ulUnicodeRange1", type: "ULONG", value: 0 }, + { name: "ulUnicodeRange2", type: "ULONG", value: 0 }, + { name: "ulUnicodeRange3", type: "ULONG", value: 0 }, + { name: "ulUnicodeRange4", type: "ULONG", value: 0 }, + { name: "achVendID", type: "CHARARRAY", value: "XXXX" }, + { name: "fsSelection", type: "USHORT", value: 0 }, + { name: "usFirstCharIndex", type: "USHORT", value: 0 }, + { name: "usLastCharIndex", type: "USHORT", value: 0 }, + { name: "sTypoAscender", type: "SHORT", value: 0 }, + { name: "sTypoDescender", type: "SHORT", value: 0 }, + { name: "sTypoLineGap", type: "SHORT", value: 0 }, + { name: "usWinAscent", type: "USHORT", value: 0 }, + { name: "usWinDescent", type: "USHORT", value: 0 }, + { name: "ulCodePageRange1", type: "ULONG", value: 0 }, + { name: "ulCodePageRange2", type: "ULONG", value: 0 }, + { name: "sxHeight", type: "SHORT", value: 0 }, + { name: "sCapHeight", type: "SHORT", value: 0 }, + { name: "usDefaultChar", type: "USHORT", value: 0 }, + { name: "usBreakChar", type: "USHORT", value: 0 }, + { name: "usMaxContext", type: "USHORT", value: 0 } + ], options); +} +var os2 = { parse: parseOS2Table, make: makeOS2Table, unicodeRanges, getUnicodeRange }; +function parsePostTable(data2, start) { + var post = {}; + var p = new parse.Parser(data2, start); + post.version = p.parseVersion(); + post.italicAngle = p.parseFixed(); + post.underlinePosition = p.parseShort(); + post.underlineThickness = p.parseShort(); + post.isFixedPitch = p.parseULong(); + post.minMemType42 = p.parseULong(); + post.maxMemType42 = p.parseULong(); + post.minMemType1 = p.parseULong(); + post.maxMemType1 = p.parseULong(); + switch (post.version) { + case 1: + post.names = standardNames.slice(); + break; + case 2: + post.numberOfGlyphs = p.parseUShort(); + post.glyphNameIndex = new Array(post.numberOfGlyphs); + for (var i = 0;i < post.numberOfGlyphs; i++) { + post.glyphNameIndex[i] = p.parseUShort(); + } + post.names = []; + for (var i$1 = 0;i$1 < post.numberOfGlyphs; i$1++) { + if (post.glyphNameIndex[i$1] >= standardNames.length) { + var nameLength = p.parseChar(); + post.names.push(p.parseString(nameLength)); + } + } + break; + case 2.5: + post.numberOfGlyphs = p.parseUShort(); + post.offset = new Array(post.numberOfGlyphs); + for (var i$2 = 0;i$2 < post.numberOfGlyphs; i$2++) { + post.offset[i$2] = p.parseChar(); + } + break; + } + return post; +} +function makePostTable() { + return new table.Table("post", [ + { name: "version", type: "FIXED", value: 196608 }, + { name: "italicAngle", type: "FIXED", value: 0 }, + { name: "underlinePosition", type: "FWORD", value: 0 }, + { name: "underlineThickness", type: "FWORD", value: 0 }, + { name: "isFixedPitch", type: "ULONG", value: 0 }, + { name: "minMemType42", type: "ULONG", value: 0 }, + { name: "maxMemType42", type: "ULONG", value: 0 }, + { name: "minMemType1", type: "ULONG", value: 0 }, + { name: "maxMemType1", type: "ULONG", value: 0 } + ]); +} +var post = { parse: parsePostTable, make: makePostTable }; +var subtableParsers = new Array(9); +subtableParsers[1] = function parseLookup1() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat: 1, + coverage: this.parsePointer(Parser.coverage), + deltaGlyphId: this.parseUShort() + }; + } else if (substFormat === 2) { + return { + substFormat: 2, + coverage: this.parsePointer(Parser.coverage), + substitute: this.parseOffset16List() + }; + } + check.assert(false, "0x" + start.toString(16) + ": lookup type 1 format must be 1 or 2."); +}; +subtableParsers[2] = function parseLookup2() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB Multiple Substitution Subtable identifier-format must be 1"); + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + sequences: this.parseListOfLists() + }; +}; +subtableParsers[3] = function parseLookup3() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB Alternate Substitution Subtable identifier-format must be 1"); + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + alternateSets: this.parseListOfLists() + }; +}; +subtableParsers[4] = function parseLookup4() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB ligature table identifier-format must be 1"); + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + ligatureSets: this.parseListOfLists(function() { + return { + ligGlyph: this.parseUShort(), + components: this.parseUShortList(this.parseUShort() - 1) + }; + }) + }; +}; +var lookupRecordDesc = { + sequenceIndex: Parser.uShort, + lookupListIndex: Parser.uShort +}; +subtableParsers[5] = function parseLookup5() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + ruleSets: this.parseListOfLists(function() { + var glyphCount2 = this.parseUShort(); + var substCount2 = this.parseUShort(); + return { + input: this.parseUShortList(glyphCount2 - 1), + lookupRecords: this.parseRecordList(substCount2, lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 2) { + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + classDef: this.parsePointer(Parser.classDef), + classSets: this.parseListOfLists(function() { + var glyphCount2 = this.parseUShort(); + var substCount2 = this.parseUShort(); + return { + classes: this.parseUShortList(glyphCount2 - 1), + lookupRecords: this.parseRecordList(substCount2, lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 3) { + var glyphCount = this.parseUShort(); + var substCount = this.parseUShort(); + return { + substFormat, + coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)), + lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) + }; + } + check.assert(false, "0x" + start.toString(16) + ": lookup type 5 format must be 1, 2 or 3."); +}; +subtableParsers[6] = function parseLookup6() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat: 1, + coverage: this.parsePointer(Parser.coverage), + chainRuleSets: this.parseListOfLists(function() { + return { + backtrack: this.parseUShortList(), + input: this.parseUShortList(this.parseShort() - 1), + lookahead: this.parseUShortList(), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 2) { + return { + substFormat: 2, + coverage: this.parsePointer(Parser.coverage), + backtrackClassDef: this.parsePointer(Parser.classDef), + inputClassDef: this.parsePointer(Parser.classDef), + lookaheadClassDef: this.parsePointer(Parser.classDef), + chainClassSet: this.parseListOfLists(function() { + return { + backtrack: this.parseUShortList(), + input: this.parseUShortList(this.parseShort() - 1), + lookahead: this.parseUShortList(), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 3) { + return { + substFormat: 3, + backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), + inputCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + } + check.assert(false, "0x" + start.toString(16) + ": lookup type 6 format must be 1, 2 or 3."); +}; +subtableParsers[7] = function parseLookup7() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB Extension Substitution subtable identifier-format must be 1"); + var extensionLookupType = this.parseUShort(); + var extensionParser = new Parser(this.data, this.offset + this.parseULong()); + return { + substFormat: 1, + lookupType: extensionLookupType, + extension: subtableParsers[extensionLookupType].call(extensionParser) + }; +}; +subtableParsers[8] = function parseLookup8() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1"); + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), + substitutes: this.parseUShortList() + }; +}; +function parseGsubTable(data2, start) { + start = start || 0; + var p = new Parser(data2, start); + var tableVersion = p.parseVersion(1); + check.argument(tableVersion === 1 || tableVersion === 1.1, "Unsupported GSUB table version."); + if (tableVersion === 1) { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers) + }; + } else { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers), + variations: p.parseFeatureVariationsList() + }; + } +} +var subtableMakers = new Array(9); +subtableMakers[1] = function makeLookup1(subtable) { + if (subtable.substFormat === 1) { + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 1 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }, + { name: "deltaGlyphID", type: "USHORT", value: subtable.deltaGlyphId } + ]); + } else { + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 2 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.ushortList("substitute", subtable.substitute))); + } +}; +subtableMakers[2] = function makeLookup2(subtable) { + check.assert(subtable.substFormat === 1, "Lookup type 2 substFormat must be 1."); + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 1 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.tableList("seqSet", subtable.sequences, function(sequenceSet) { + return new table.Table("sequenceSetTable", table.ushortList("sequence", sequenceSet)); + }))); +}; +subtableMakers[3] = function makeLookup3(subtable) { + check.assert(subtable.substFormat === 1, "Lookup type 3 substFormat must be 1."); + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 1 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.tableList("altSet", subtable.alternateSets, function(alternateSet) { + return new table.Table("alternateSetTable", table.ushortList("alternate", alternateSet)); + }))); +}; +subtableMakers[4] = function makeLookup4(subtable) { + check.assert(subtable.substFormat === 1, "Lookup type 4 substFormat must be 1."); + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 1 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.tableList("ligSet", subtable.ligatureSets, function(ligatureSet) { + return new table.Table("ligatureSetTable", table.tableList("ligature", ligatureSet, function(ligature) { + return new table.Table("ligatureTable", [{ name: "ligGlyph", type: "USHORT", value: ligature.ligGlyph }].concat(table.ushortList("component", ligature.components, ligature.components.length + 1))); + })); + }))); +}; +subtableMakers[6] = function makeLookup6(subtable) { + if (subtable.substFormat === 1) { + var returnTable = new table.Table("chainContextTable", [ + { name: "substFormat", type: "USHORT", value: subtable.substFormat }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.tableList("chainRuleSet", subtable.chainRuleSets, function(chainRuleSet) { + return new table.Table("chainRuleSetTable", table.tableList("chainRule", chainRuleSet, function(chainRule) { + var tableData2 = table.ushortList("backtrackGlyph", chainRule.backtrack, chainRule.backtrack.length).concat(table.ushortList("inputGlyph", chainRule.input, chainRule.input.length + 1)).concat(table.ushortList("lookaheadGlyph", chainRule.lookahead, chainRule.lookahead.length)).concat(table.ushortList("substitution", [], chainRule.lookupRecords.length)); + chainRule.lookupRecords.forEach(function(record, i) { + tableData2 = tableData2.concat({ name: "sequenceIndex" + i, type: "USHORT", value: record.sequenceIndex }).concat({ name: "lookupListIndex" + i, type: "USHORT", value: record.lookupListIndex }); + }); + return new table.Table("chainRuleTable", tableData2); + })); + }))); + return returnTable; + } else if (subtable.substFormat === 2) { + check.assert(false, "lookup type 6 format 2 is not yet supported."); + } else if (subtable.substFormat === 3) { + var tableData = [ + { name: "substFormat", type: "USHORT", value: subtable.substFormat } + ]; + tableData.push({ name: "backtrackGlyphCount", type: "USHORT", value: subtable.backtrackCoverage.length }); + subtable.backtrackCoverage.forEach(function(coverage, i) { + tableData.push({ name: "backtrackCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) }); + }); + tableData.push({ name: "inputGlyphCount", type: "USHORT", value: subtable.inputCoverage.length }); + subtable.inputCoverage.forEach(function(coverage, i) { + tableData.push({ name: "inputCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) }); + }); + tableData.push({ name: "lookaheadGlyphCount", type: "USHORT", value: subtable.lookaheadCoverage.length }); + subtable.lookaheadCoverage.forEach(function(coverage, i) { + tableData.push({ name: "lookaheadCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) }); + }); + tableData.push({ name: "substitutionCount", type: "USHORT", value: subtable.lookupRecords.length }); + subtable.lookupRecords.forEach(function(record, i) { + tableData = tableData.concat({ name: "sequenceIndex" + i, type: "USHORT", value: record.sequenceIndex }).concat({ name: "lookupListIndex" + i, type: "USHORT", value: record.lookupListIndex }); + }); + var returnTable$1 = new table.Table("chainContextTable", tableData); + return returnTable$1; + } + check.assert(false, "lookup type 6 format must be 1, 2 or 3."); +}; +function makeGsubTable(gsub) { + return new table.Table("GSUB", [ + { name: "version", type: "ULONG", value: 65536 }, + { name: "scripts", type: "TABLE", value: new table.ScriptList(gsub.scripts) }, + { name: "features", type: "TABLE", value: new table.FeatureList(gsub.features) }, + { name: "lookups", type: "TABLE", value: new table.LookupList(gsub.lookups, subtableMakers) } + ]); +} +var gsub = { parse: parseGsubTable, make: makeGsubTable }; +function parseMetaTable(data2, start) { + var p = new parse.Parser(data2, start); + var tableVersion = p.parseULong(); + check.argument(tableVersion === 1, "Unsupported META table version."); + p.parseULong(); + p.parseULong(); + var numDataMaps = p.parseULong(); + var tags = {}; + for (var i = 0;i < numDataMaps; i++) { + var tag = p.parseTag(); + var dataOffset = p.parseULong(); + var dataLength = p.parseULong(); + var text2 = decode.UTF8(data2, start + dataOffset, dataLength); + tags[tag] = text2; + } + return tags; +} +function makeMetaTable(tags) { + var numTags = Object.keys(tags).length; + var stringPool = ""; + var stringPoolOffset = 16 + numTags * 12; + var result = new table.Table("meta", [ + { name: "version", type: "ULONG", value: 1 }, + { name: "flags", type: "ULONG", value: 0 }, + { name: "offset", type: "ULONG", value: stringPoolOffset }, + { name: "numTags", type: "ULONG", value: numTags } + ]); + for (var tag in tags) { + var pos = stringPool.length; + stringPool += tags[tag]; + result.fields.push({ name: "tag " + tag, type: "TAG", value: tag }); + result.fields.push({ name: "offset " + tag, type: "ULONG", value: stringPoolOffset + pos }); + result.fields.push({ name: "length " + tag, type: "ULONG", value: tags[tag].length }); + } + result.fields.push({ name: "stringPool", type: "CHARARRAY", value: stringPool }); + return result; +} +var meta = { parse: parseMetaTable, make: makeMetaTable }; +function parseColrTable(data2, start) { + var p = new Parser(data2, start); + var version = p.parseUShort(); + check.argument(version === 0, "Only COLRv0 supported."); + var numBaseGlyphRecords = p.parseUShort(); + var baseGlyphRecordsOffset = p.parseOffset32(); + var layerRecordsOffset = p.parseOffset32(); + var numLayerRecords = p.parseUShort(); + p.relativeOffset = baseGlyphRecordsOffset; + var baseGlyphRecords = p.parseRecordList(numBaseGlyphRecords, { + glyphID: Parser.uShort, + firstLayerIndex: Parser.uShort, + numLayers: Parser.uShort + }); + p.relativeOffset = layerRecordsOffset; + var layerRecords = p.parseRecordList(numLayerRecords, { + glyphID: Parser.uShort, + paletteIndex: Parser.uShort + }); + return { + version, + baseGlyphRecords, + layerRecords + }; +} +function makeColrTable(ref) { + var version = ref.version; + if (version === undefined) + version = 0; + var baseGlyphRecords = ref.baseGlyphRecords; + if (baseGlyphRecords === undefined) + baseGlyphRecords = []; + var layerRecords = ref.layerRecords; + if (layerRecords === undefined) + layerRecords = []; + check.argument(version === 0, "Only COLRv0 supported."); + var baseGlyphRecordsOffset = 14; + var layerRecordsOffset = baseGlyphRecordsOffset + baseGlyphRecords.length * 6; + return new table.Table("COLR", [ + { name: "version", type: "USHORT", value: version }, + { name: "numBaseGlyphRecords", type: "USHORT", value: baseGlyphRecords.length }, + { name: "baseGlyphRecordsOffset", type: "ULONG", value: baseGlyphRecordsOffset }, + { name: "layerRecordsOffset", type: "ULONG", value: layerRecordsOffset }, + { name: "numLayerRecords", type: "USHORT", value: layerRecords.length } + ].concat(baseGlyphRecords.map(function(glyph, i) { + return [ + { name: "glyphID_" + i, type: "USHORT", value: glyph.glyphID }, + { name: "firstLayerIndex_" + i, type: "USHORT", value: glyph.firstLayerIndex }, + { name: "numLayers_" + i, type: "USHORT", value: glyph.numLayers } + ]; + }).flat(), layerRecords.map(function(layer, i) { + return [ + { name: "LayerGlyphID_" + i, type: "USHORT", value: layer.glyphID }, + { name: "paletteIndex_" + i, type: "USHORT", value: layer.paletteIndex } + ]; + }).flat())); +} +var colr = { parse: parseColrTable, make: makeColrTable }; +function parseCpalTable(data2, start) { + var p = new Parser(data2, start); + var version = p.parseShort(); + var numPaletteEntries = p.parseShort(); + var numPalettes = p.parseShort(); + var numColorRecords = p.parseShort(); + var colorRecordsArrayOffset = p.parseOffset32(); + var colorRecordIndices = p.parseUShortList(numPalettes); + p.relativeOffset = colorRecordsArrayOffset; + var colorRecords = p.parseULongList(numColorRecords); + return { + version, + numPaletteEntries, + colorRecords, + colorRecordIndices + }; +} +function makeCpalTable(ref) { + var version = ref.version; + if (version === undefined) + version = 0; + var numPaletteEntries = ref.numPaletteEntries; + if (numPaletteEntries === undefined) + numPaletteEntries = 0; + var colorRecords = ref.colorRecords; + if (colorRecords === undefined) + colorRecords = []; + var colorRecordIndices = ref.colorRecordIndices; + if (colorRecordIndices === undefined) + colorRecordIndices = [0]; + check.argument(version === 0, "Only CPALv0 are supported."); + check.argument(colorRecords.length, "No colorRecords given."); + check.argument(colorRecordIndices.length, "No colorRecordIndices given."); + check.argument(!numPaletteEntries && colorRecordIndices.length == 1, "Can't infer numPaletteEntries on multiple colorRecordIndices"); + return new table.Table("CPAL", [ + { name: "version", type: "USHORT", value: version }, + { name: "numPaletteEntries", type: "USHORT", value: numPaletteEntries || colorRecords.length }, + { name: "numPalettes", type: "USHORT", value: colorRecordIndices.length }, + { name: "numColorRecords", type: "USHORT", value: colorRecords.length }, + { name: "colorRecordsArrayOffset", type: "ULONG", value: 12 + 2 * colorRecordIndices.length } + ].concat(colorRecordIndices.map(function(palette, i) { + return { name: "colorRecordIndices_" + i, type: "USHORT", value: palette }; + }), colorRecords.map(function(color, i) { + return { name: "colorRecords_" + i, type: "ULONG", value: color }; + }))); +} +var cpal = { parse: parseCpalTable, make: makeCpalTable }; +function log2(v) { + return Math.log(v) / Math.log(2) | 0; +} +function computeCheckSum(bytes) { + while (bytes.length % 4 !== 0) { + bytes.push(0); + } + var sum2 = 0; + for (var i = 0;i < bytes.length; i += 4) { + sum2 += (bytes[i] << 24) + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + bytes[i + 3]; + } + sum2 %= Math.pow(2, 32); + return sum2; +} +function makeTableRecord(tag, checkSum, offset, length2) { + return new table.Record("Table Record", [ + { name: "tag", type: "TAG", value: tag !== undefined ? tag : "" }, + { name: "checkSum", type: "ULONG", value: checkSum !== undefined ? checkSum : 0 }, + { name: "offset", type: "ULONG", value: offset !== undefined ? offset : 0 }, + { name: "length", type: "ULONG", value: length2 !== undefined ? length2 : 0 } + ]); +} +function makeSfntTable(tables) { + var sfnt = new table.Table("sfnt", [ + { name: "version", type: "TAG", value: "OTTO" }, + { name: "numTables", type: "USHORT", value: 0 }, + { name: "searchRange", type: "USHORT", value: 0 }, + { name: "entrySelector", type: "USHORT", value: 0 }, + { name: "rangeShift", type: "USHORT", value: 0 } + ]); + sfnt.tables = tables; + sfnt.numTables = tables.length; + var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables)); + sfnt.searchRange = 16 * highestPowerOf2; + sfnt.entrySelector = log2(highestPowerOf2); + sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange; + var recordFields = []; + var tableFields = []; + var offset = sfnt.sizeOf() + makeTableRecord().sizeOf() * sfnt.numTables; + while (offset % 4 !== 0) { + offset += 1; + tableFields.push({ name: "padding", type: "BYTE", value: 0 }); + } + for (var i = 0;i < tables.length; i += 1) { + var t4 = tables[i]; + check.argument(t4.tableName.length === 4, "Table name" + t4.tableName + " is invalid."); + var tableLength = t4.sizeOf(); + var tableRecord = makeTableRecord(t4.tableName, computeCheckSum(t4.encode()), offset, tableLength); + recordFields.push({ name: tableRecord.tag + " Table Record", type: "RECORD", value: tableRecord }); + tableFields.push({ name: t4.tableName + " table", type: "RECORD", value: t4 }); + offset += tableLength; + check.argument(!isNaN(offset), "Something went wrong calculating the offset."); + while (offset % 4 !== 0) { + offset += 1; + tableFields.push({ name: "padding", type: "BYTE", value: 0 }); + } + } + recordFields.sort(function(r1, r2) { + if (r1.value.tag > r2.value.tag) { + return 1; + } else { + return -1; + } + }); + sfnt.fields = sfnt.fields.concat(recordFields); + sfnt.fields = sfnt.fields.concat(tableFields); + return sfnt; +} +function metricsForChar(font, chars, notFoundMetrics) { + for (var i = 0;i < chars.length; i += 1) { + var glyphIndex = font.charToGlyphIndex(chars[i]); + if (glyphIndex > 0) { + var glyph = font.glyphs.get(glyphIndex); + return glyph.getMetrics(); + } + } + return notFoundMetrics; +} +function average(vs2) { + var sum2 = 0; + for (var i = 0;i < vs2.length; i += 1) { + sum2 += vs2[i]; + } + return sum2 / vs2.length; +} +function fontToSfntTable(font) { + var xMins = []; + var yMins = []; + var xMaxs = []; + var yMaxs = []; + var advanceWidths = []; + var leftSideBearings = []; + var rightSideBearings = []; + var firstCharIndex; + var lastCharIndex = 0; + var ulUnicodeRange1 = 0; + var ulUnicodeRange2 = 0; + var ulUnicodeRange3 = 0; + var ulUnicodeRange4 = 0; + for (var i = 0;i < font.glyphs.length; i += 1) { + var glyph = font.glyphs.get(i); + var unicode = glyph.unicode | 0; + if (isNaN(glyph.advanceWidth)) { + throw new Error("Glyph " + glyph.name + " (" + i + "): advanceWidth is not a number."); + } + if (firstCharIndex > unicode || firstCharIndex === undefined) { + if (unicode > 0) { + firstCharIndex = unicode; + } + } + if (lastCharIndex < unicode) { + lastCharIndex = unicode; + } + var position2 = os2.getUnicodeRange(unicode); + if (position2 < 32) { + ulUnicodeRange1 |= 1 << position2; + } else if (position2 < 64) { + ulUnicodeRange2 |= 1 << position2 - 32; + } else if (position2 < 96) { + ulUnicodeRange3 |= 1 << position2 - 64; + } else if (position2 < 123) { + ulUnicodeRange4 |= 1 << position2 - 96; + } else { + throw new Error("Unicode ranges bits > 123 are reserved for internal usage"); + } + if (glyph.name === ".notdef") { + continue; + } + var metrics = glyph.getMetrics(); + xMins.push(metrics.xMin); + yMins.push(metrics.yMin); + xMaxs.push(metrics.xMax); + yMaxs.push(metrics.yMax); + leftSideBearings.push(metrics.leftSideBearing); + rightSideBearings.push(metrics.rightSideBearing); + advanceWidths.push(glyph.advanceWidth); + } + var globals = { + xMin: Math.min.apply(null, xMins), + yMin: Math.min.apply(null, yMins), + xMax: Math.max.apply(null, xMaxs), + yMax: Math.max.apply(null, yMaxs), + advanceWidthMax: Math.max.apply(null, advanceWidths), + advanceWidthAvg: average(advanceWidths), + minLeftSideBearing: Math.min.apply(null, leftSideBearings), + maxLeftSideBearing: Math.max.apply(null, leftSideBearings), + minRightSideBearing: Math.min.apply(null, rightSideBearings) + }; + globals.ascender = font.ascender; + globals.descender = font.descender; + var headTable = head.make({ + flags: 3, + unitsPerEm: font.unitsPerEm, + xMin: globals.xMin, + yMin: globals.yMin, + xMax: globals.xMax, + yMax: globals.yMax, + lowestRecPPEM: 3, + createdTimestamp: font.createdTimestamp + }); + var hheaTable = hhea.make({ + ascender: globals.ascender, + descender: globals.descender, + advanceWidthMax: globals.advanceWidthMax, + minLeftSideBearing: globals.minLeftSideBearing, + minRightSideBearing: globals.minRightSideBearing, + xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin), + numberOfHMetrics: font.glyphs.length + }); + var maxpTable = maxp.make(font.glyphs.length); + var os2Table = os2.make(Object.assign({ + xAvgCharWidth: Math.round(globals.advanceWidthAvg), + usFirstCharIndex: firstCharIndex, + usLastCharIndex: lastCharIndex, + ulUnicodeRange1, + ulUnicodeRange2, + ulUnicodeRange3, + ulUnicodeRange4, + sTypoAscender: globals.ascender, + sTypoDescender: globals.descender, + sTypoLineGap: 0, + usWinAscent: globals.yMax, + usWinDescent: Math.abs(globals.yMin), + ulCodePageRange1: 1, + sxHeight: metricsForChar(font, "xyvw", { yMax: Math.round(globals.ascender / 2) }).yMax, + sCapHeight: metricsForChar(font, "HIKLEFJMNTZBDPRAGOQSUVWXY", globals).yMax, + usDefaultChar: font.hasChar(" ") ? 32 : 0, + usBreakChar: font.hasChar(" ") ? 32 : 0 + }, font.tables.os2)); + var hmtxTable = hmtx.make(font.glyphs); + var cmapTable = cmap.make(font.glyphs); + var englishFamilyName = font.getEnglishName("fontFamily"); + var englishStyleName = font.getEnglishName("fontSubfamily"); + var englishFullName = englishFamilyName + " " + englishStyleName; + var postScriptName = font.getEnglishName("postScriptName"); + if (!postScriptName) { + postScriptName = englishFamilyName.replace(/\s/g, "") + "-" + englishStyleName; + } + var names = {}; + for (var n2 in font.names) { + names[n2] = font.names[n2]; + } + if (!names.uniqueID) { + names.uniqueID = { en: font.getEnglishName("manufacturer") + ":" + englishFullName }; + } + if (!names.postScriptName) { + names.postScriptName = { en: postScriptName }; + } + if (!names.preferredFamily) { + names.preferredFamily = font.names.fontFamily; + } + if (!names.preferredSubfamily) { + names.preferredSubfamily = font.names.fontSubfamily; + } + var languageTags = []; + var nameTable = _name.make(names, languageTags); + var ltagTable = languageTags.length > 0 ? ltag.make(languageTags) : undefined; + var postTable = post.make(); + var cffTable = cff.make(font.glyphs, { + version: font.getEnglishName("version"), + fullName: englishFullName, + familyName: englishFamilyName, + weightName: englishStyleName, + postScriptName, + unitsPerEm: font.unitsPerEm, + fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax] + }); + var metaTable = font.metas && Object.keys(font.metas).length > 0 ? meta.make(font.metas) : undefined; + var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable]; + if (ltagTable) { + tables.push(ltagTable); + } + if (font.tables.gsub) { + tables.push(gsub.make(font.tables.gsub)); + } + if (font.tables.cpal) { + tables.push(cpal.make(font.tables.cpal)); + } + if (font.tables.colr) { + tables.push(colr.make(font.tables.colr)); + } + if (metaTable) { + tables.push(metaTable); + } + var sfntTable = makeSfntTable(tables); + var bytes = sfntTable.encode(); + var checkSum = computeCheckSum(bytes); + var tableFields = sfntTable.fields; + var checkSumAdjusted = false; + for (var i$1 = 0;i$1 < tableFields.length; i$1 += 1) { + if (tableFields[i$1].name === "head table") { + tableFields[i$1].value.checkSumAdjustment = 2981146554 - checkSum; + checkSumAdjusted = true; + break; + } + } + if (!checkSumAdjusted) { + throw new Error("Could not find head table with checkSum to adjust."); + } + return sfntTable; +} +var sfnt = { make: makeSfntTable, fontToTable: fontToSfntTable, computeCheckSum }; +function searchTag(arr, tag) { + var imin = 0; + var imax = arr.length - 1; + while (imin <= imax) { + var imid = imin + imax >>> 1; + var val2 = arr[imid].tag; + if (val2 === tag) { + return imid; + } else if (val2 < tag) { + imin = imid + 1; + } else { + imax = imid - 1; + } + } + return -imin - 1; +} +function binSearch(arr, value2) { + var imin = 0; + var imax = arr.length - 1; + while (imin <= imax) { + var imid = imin + imax >>> 1; + var val2 = arr[imid]; + if (val2 === value2) { + return imid; + } else if (val2 < value2) { + imin = imid + 1; + } else { + imax = imid - 1; + } + } + return -imin - 1; +} +function searchRange(ranges, value2) { + var range; + var imin = 0; + var imax = ranges.length - 1; + while (imin <= imax) { + var imid = imin + imax >>> 1; + range = ranges[imid]; + var start = range.start; + if (start === value2) { + return range; + } else if (start < value2) { + imin = imid + 1; + } else { + imax = imid - 1; + } + } + if (imin > 0) { + range = ranges[imin - 1]; + if (value2 > range.end) { + return 0; + } + return range; + } +} +function Layout(font, tableName) { + this.font = font; + this.tableName = tableName; +} +Layout.prototype = { + searchTag, + binSearch, + getTable: function(create) { + var layout = this.font.tables[this.tableName]; + if (!layout && create) { + layout = this.font.tables[this.tableName] = this.createDefaultTable(); + } + return layout; + }, + getScriptNames: function() { + var layout = this.getTable(); + if (!layout) { + return []; + } + return layout.scripts.map(function(script) { + return script.tag; + }); + }, + getDefaultScriptName: function() { + var layout = this.getTable(); + if (!layout) { + return; + } + var hasLatn = false; + for (var i = 0;i < layout.scripts.length; i++) { + var name2 = layout.scripts[i].tag; + if (name2 === "DFLT") { + return name2; + } + if (name2 === "latn") { + hasLatn = true; + } + } + if (hasLatn) { + return "latn"; + } + }, + getScriptTable: function(script, create) { + var layout = this.getTable(create); + if (layout) { + script = script || "DFLT"; + var scripts = layout.scripts; + var pos = searchTag(layout.scripts, script); + if (pos >= 0) { + return scripts[pos].script; + } else if (create) { + var scr = { + tag: script, + script: { + defaultLangSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] }, + langSysRecords: [] + } + }; + scripts.splice(-1 - pos, 0, scr); + return scr.script; + } + } + }, + getLangSysTable: function(script, language, create) { + var scriptTable = this.getScriptTable(script, create); + if (scriptTable) { + if (!language || language === "dflt" || language === "DFLT") { + return scriptTable.defaultLangSys; + } + var pos = searchTag(scriptTable.langSysRecords, language); + if (pos >= 0) { + return scriptTable.langSysRecords[pos].langSys; + } else if (create) { + var langSysRecord = { + tag: language, + langSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] } + }; + scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord); + return langSysRecord.langSys; + } + } + }, + getFeatureTable: function(script, language, feature, create) { + var langSysTable2 = this.getLangSysTable(script, language, create); + if (langSysTable2) { + var featureRecord; + var featIndexes = langSysTable2.featureIndexes; + var allFeatures = this.font.tables[this.tableName].features; + for (var i = 0;i < featIndexes.length; i++) { + featureRecord = allFeatures[featIndexes[i]]; + if (featureRecord.tag === feature) { + return featureRecord.feature; + } + } + if (create) { + var index2 = allFeatures.length; + check.assert(index2 === 0 || feature >= allFeatures[index2 - 1].tag, "Features must be added in alphabetical order."); + featureRecord = { + tag: feature, + feature: { params: 0, lookupListIndexes: [] } + }; + allFeatures.push(featureRecord); + featIndexes.push(index2); + return featureRecord.feature; + } + } + }, + getLookupTables: function(script, language, feature, lookupType, create) { + var featureTable = this.getFeatureTable(script, language, feature, create); + var tables = []; + if (featureTable) { + var lookupTable; + var lookupListIndexes = featureTable.lookupListIndexes; + var allLookups = this.font.tables[this.tableName].lookups; + for (var i = 0;i < lookupListIndexes.length; i++) { + lookupTable = allLookups[lookupListIndexes[i]]; + if (lookupTable.lookupType === lookupType) { + tables.push(lookupTable); + } + } + if (tables.length === 0 && create) { + lookupTable = { + lookupType, + lookupFlag: 0, + subtables: [], + markFilteringSet: undefined + }; + var index2 = allLookups.length; + allLookups.push(lookupTable); + lookupListIndexes.push(index2); + return [lookupTable]; + } + } + return tables; + }, + getGlyphClass: function(classDefTable, glyphIndex) { + switch (classDefTable.format) { + case 1: + if (classDefTable.startGlyph <= glyphIndex && glyphIndex < classDefTable.startGlyph + classDefTable.classes.length) { + return classDefTable.classes[glyphIndex - classDefTable.startGlyph]; + } + return 0; + case 2: + var range = searchRange(classDefTable.ranges, glyphIndex); + return range ? range.classId : 0; + } + }, + getCoverageIndex: function(coverageTable, glyphIndex) { + switch (coverageTable.format) { + case 1: + var index2 = binSearch(coverageTable.glyphs, glyphIndex); + return index2 >= 0 ? index2 : -1; + case 2: + var range = searchRange(coverageTable.ranges, glyphIndex); + return range ? range.index + glyphIndex - range.start : -1; + } + }, + expandCoverage: function(coverageTable) { + if (coverageTable.format === 1) { + return coverageTable.glyphs; + } else { + var glyphs = []; + var ranges = coverageTable.ranges; + for (var i = 0;i < ranges.length; i++) { + var range = ranges[i]; + var start = range.start; + var end = range.end; + for (var j2 = start;j2 <= end; j2++) { + glyphs.push(j2); + } + } + return glyphs; + } + } +}; +function Position(font) { + Layout.call(this, font, "gpos"); +} +Position.prototype = Layout.prototype; +Position.prototype.init = function() { + var script = this.getDefaultScriptName(); + this.defaultKerningTables = this.getKerningTables(script); +}; +Position.prototype.getKerningValue = function(kerningLookups, leftIndex, rightIndex) { + for (var i = 0;i < kerningLookups.length; i++) { + var subtables = kerningLookups[i].subtables; + for (var j2 = 0;j2 < subtables.length; j2++) { + var subtable = subtables[j2]; + var covIndex = this.getCoverageIndex(subtable.coverage, leftIndex); + if (covIndex < 0) { + continue; + } + switch (subtable.posFormat) { + case 1: + var pairSet = subtable.pairSets[covIndex]; + for (var k2 = 0;k2 < pairSet.length; k2++) { + var pair = pairSet[k2]; + if (pair.secondGlyph === rightIndex) { + return pair.value1 && pair.value1.xAdvance || 0; + } + } + break; + case 2: + var class1 = this.getGlyphClass(subtable.classDef1, leftIndex); + var class2 = this.getGlyphClass(subtable.classDef2, rightIndex); + var pair$1 = subtable.classRecords[class1][class2]; + return pair$1.value1 && pair$1.value1.xAdvance || 0; + } + } + } + return 0; +}; +Position.prototype.getKerningTables = function(script, language) { + if (this.font.tables.gpos) { + return this.getLookupTables(script, language, "kern", 2); + } +}; +function Substitution(font) { + Layout.call(this, font, "gsub"); +} +function arraysEqual2(ar1, ar2) { + var n2 = ar1.length; + if (n2 !== ar2.length) { + return false; + } + for (var i = 0;i < n2; i++) { + if (ar1[i] !== ar2[i]) { + return false; + } + } + return true; +} +function getSubstFormat(lookupTable, format, defaultSubtable) { + var subtables = lookupTable.subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + if (subtable.substFormat === format) { + return subtable; + } + } + if (defaultSubtable) { + subtables.push(defaultSubtable); + return defaultSubtable; + } + return; +} +Substitution.prototype = Layout.prototype; +Substitution.prototype.createDefaultTable = function() { + return { + version: 1, + scripts: [{ + tag: "DFLT", + script: { + defaultLangSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] }, + langSysRecords: [] + } + }], + features: [], + lookups: [] + }; +}; +Substitution.prototype.getSingle = function(feature, script, language) { + var substitutions = []; + var lookupTables = this.getLookupTables(script, language, feature, 1); + for (var idx = 0;idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var j2 = undefined; + if (subtable.substFormat === 1) { + var delta = subtable.deltaGlyphId; + for (j2 = 0;j2 < glyphs.length; j2++) { + var glyph = glyphs[j2]; + substitutions.push({ sub: glyph, by: glyph + delta }); + } + } else { + var substitute = subtable.substitute; + for (j2 = 0;j2 < glyphs.length; j2++) { + substitutions.push({ sub: glyphs[j2], by: substitute[j2] }); + } + } + } + } + return substitutions; +}; +Substitution.prototype.getMultiple = function(feature, script, language) { + var substitutions = []; + var lookupTables = this.getLookupTables(script, language, feature, 2); + for (var idx = 0;idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var j2 = undefined; + for (j2 = 0;j2 < glyphs.length; j2++) { + var glyph = glyphs[j2]; + var replacements = subtable.sequences[j2]; + substitutions.push({ sub: glyph, by: replacements }); + } + } + } + return substitutions; +}; +Substitution.prototype.getAlternates = function(feature, script, language) { + var alternates = []; + var lookupTables = this.getLookupTables(script, language, feature, 3); + for (var idx = 0;idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var alternateSets = subtable.alternateSets; + for (var j2 = 0;j2 < glyphs.length; j2++) { + alternates.push({ sub: glyphs[j2], by: alternateSets[j2] }); + } + } + } + return alternates; +}; +Substitution.prototype.getLigatures = function(feature, script, language) { + var ligatures = []; + var lookupTables = this.getLookupTables(script, language, feature, 4); + for (var idx = 0;idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var ligatureSets = subtable.ligatureSets; + for (var j2 = 0;j2 < glyphs.length; j2++) { + var startGlyph = glyphs[j2]; + var ligSet = ligatureSets[j2]; + for (var k2 = 0;k2 < ligSet.length; k2++) { + var lig = ligSet[k2]; + ligatures.push({ + sub: [startGlyph].concat(lig.components), + by: lig.ligGlyph + }); + } + } + } + } + return ligatures; +}; +Substitution.prototype.addSingle = function(feature, substitution, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 1, true)[0]; + var subtable = getSubstFormat(lookupTable, 2, { + substFormat: 2, + coverage: { format: 1, glyphs: [] }, + substitute: [] + }); + check.assert(subtable.coverage.format === 1, "Single: unable to modify coverage table format " + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.substitute.splice(pos, 0, 0); + } + subtable.substitute[pos] = substitution.by; +}; +Substitution.prototype.addMultiple = function(feature, substitution, script, language) { + check.assert(substitution.by instanceof Array && substitution.by.length > 1, 'Multiple: "by" must be an array of two or more ids'); + var lookupTable = this.getLookupTables(script, language, feature, 2, true)[0]; + var subtable = getSubstFormat(lookupTable, 1, { + substFormat: 1, + coverage: { format: 1, glyphs: [] }, + sequences: [] + }); + check.assert(subtable.coverage.format === 1, "Multiple: unable to modify coverage table format " + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.sequences.splice(pos, 0, 0); + } + subtable.sequences[pos] = substitution.by; +}; +Substitution.prototype.addAlternate = function(feature, substitution, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 3, true)[0]; + var subtable = getSubstFormat(lookupTable, 1, { + substFormat: 1, + coverage: { format: 1, glyphs: [] }, + alternateSets: [] + }); + check.assert(subtable.coverage.format === 1, "Alternate: unable to modify coverage table format " + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.alternateSets.splice(pos, 0, 0); + } + subtable.alternateSets[pos] = substitution.by; +}; +Substitution.prototype.addLigature = function(feature, ligature, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 4, true)[0]; + var subtable = lookupTable.subtables[0]; + if (!subtable) { + subtable = { + substFormat: 1, + coverage: { format: 1, glyphs: [] }, + ligatureSets: [] + }; + lookupTable.subtables[0] = subtable; + } + check.assert(subtable.coverage.format === 1, "Ligature: unable to modify coverage table format " + subtable.coverage.format); + var coverageGlyph = ligature.sub[0]; + var ligComponents = ligature.sub.slice(1); + var ligatureTable = { + ligGlyph: ligature.by, + components: ligComponents + }; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos >= 0) { + var ligatureSet = subtable.ligatureSets[pos]; + for (var i = 0;i < ligatureSet.length; i++) { + if (arraysEqual2(ligatureSet[i].components, ligComponents)) { + return; + } + } + ligatureSet.push(ligatureTable); + } else { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.ligatureSets.splice(pos, 0, [ligatureTable]); + } +}; +Substitution.prototype.getFeature = function(feature, script, language) { + if (/ss\d\d/.test(feature)) { + return this.getSingle(feature, script, language); + } + switch (feature) { + case "aalt": + case "salt": + return this.getSingle(feature, script, language).concat(this.getAlternates(feature, script, language)); + case "dlig": + case "liga": + case "rlig": + return this.getLigatures(feature, script, language); + case "ccmp": + return this.getMultiple(feature, script, language).concat(this.getLigatures(feature, script, language)); + case "stch": + return this.getMultiple(feature, script, language); + } + return; +}; +Substitution.prototype.add = function(feature, sub2, script, language) { + if (/ss\d\d/.test(feature)) { + return this.addSingle(feature, sub2, script, language); + } + switch (feature) { + case "aalt": + case "salt": + if (typeof sub2.by === "number") { + return this.addSingle(feature, sub2, script, language); + } + return this.addAlternate(feature, sub2, script, language); + case "dlig": + case "liga": + case "rlig": + return this.addLigature(feature, sub2, script, language); + case "ccmp": + if (sub2.by instanceof Array) { + return this.addMultiple(feature, sub2, script, language); + } + return this.addLigature(feature, sub2, script, language); + } + return; +}; +function checkArgument(expression, message) { + if (!expression) { + throw message; + } +} +function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { + var v; + if ((flag & shortVectorBitMask) > 0) { + v = p.parseByte(); + if ((flag & sameBitMask) === 0) { + v = -v; + } + v = previousValue + v; + } else { + if ((flag & sameBitMask) > 0) { + v = previousValue; + } else { + v = previousValue + p.parseShort(); + } + } + return v; +} +function parseGlyph(glyph, data2, start) { + var p = new parse.Parser(data2, start); + glyph.numberOfContours = p.parseShort(); + glyph._xMin = p.parseShort(); + glyph._yMin = p.parseShort(); + glyph._xMax = p.parseShort(); + glyph._yMax = p.parseShort(); + var flags; + var flag; + if (glyph.numberOfContours > 0) { + var endPointIndices = glyph.endPointIndices = []; + for (var i = 0;i < glyph.numberOfContours; i += 1) { + endPointIndices.push(p.parseUShort()); + } + glyph.instructionLength = p.parseUShort(); + glyph.instructions = []; + for (var i$1 = 0;i$1 < glyph.instructionLength; i$1 += 1) { + glyph.instructions.push(p.parseByte()); + } + var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; + flags = []; + for (var i$2 = 0;i$2 < numberOfCoordinates; i$2 += 1) { + flag = p.parseByte(); + flags.push(flag); + if ((flag & 8) > 0) { + var repeatCount = p.parseByte(); + for (var j2 = 0;j2 < repeatCount; j2 += 1) { + flags.push(flag); + i$2 += 1; + } + } + } + check.argument(flags.length === numberOfCoordinates, "Bad flags."); + if (endPointIndices.length > 0) { + var points = []; + var point; + if (numberOfCoordinates > 0) { + for (var i$3 = 0;i$3 < numberOfCoordinates; i$3 += 1) { + flag = flags[i$3]; + point = {}; + point.onCurve = !!(flag & 1); + point.lastPointOfContour = endPointIndices.indexOf(i$3) >= 0; + points.push(point); + } + var px2 = 0; + for (var i$4 = 0;i$4 < numberOfCoordinates; i$4 += 1) { + flag = flags[i$4]; + point = points[i$4]; + point.x = parseGlyphCoordinate(p, flag, px2, 2, 16); + px2 = point.x; + } + var py2 = 0; + for (var i$5 = 0;i$5 < numberOfCoordinates; i$5 += 1) { + flag = flags[i$5]; + point = points[i$5]; + point.y = parseGlyphCoordinate(p, flag, py2, 4, 32); + py2 = point.y; + } + } + glyph.points = points; + } else { + glyph.points = []; + } + } else if (glyph.numberOfContours === 0) { + glyph.points = []; + } else { + glyph.isComposite = true; + glyph.points = []; + glyph.components = []; + var moreComponents = true; + while (moreComponents) { + flags = p.parseUShort(); + var component = { + glyphIndex: p.parseUShort(), + xScale: 1, + scale01: 0, + scale10: 0, + yScale: 1, + dx: 0, + dy: 0 + }; + if ((flags & 1) > 0) { + if ((flags & 2) > 0) { + component.dx = p.parseShort(); + component.dy = p.parseShort(); + } else { + component.matchedPoints = [p.parseUShort(), p.parseUShort()]; + } + } else { + if ((flags & 2) > 0) { + component.dx = p.parseChar(); + component.dy = p.parseChar(); + } else { + component.matchedPoints = [p.parseByte(), p.parseByte()]; + } + } + if ((flags & 8) > 0) { + component.xScale = component.yScale = p.parseF2Dot14(); + } else if ((flags & 64) > 0) { + component.xScale = p.parseF2Dot14(); + component.yScale = p.parseF2Dot14(); + } else if ((flags & 128) > 0) { + component.xScale = p.parseF2Dot14(); + component.scale01 = p.parseF2Dot14(); + component.scale10 = p.parseF2Dot14(); + component.yScale = p.parseF2Dot14(); + } + glyph.components.push(component); + moreComponents = !!(flags & 32); + } + if (flags & 256) { + glyph.instructionLength = p.parseUShort(); + glyph.instructions = []; + for (var i$6 = 0;i$6 < glyph.instructionLength; i$6 += 1) { + glyph.instructions.push(p.parseByte()); + } + } + } +} +function transformPoints(points, transform2) { + var newPoints = []; + for (var i = 0;i < points.length; i += 1) { + var pt = points[i]; + var newPt = { + x: transform2.xScale * pt.x + transform2.scale01 * pt.y + transform2.dx, + y: transform2.scale10 * pt.x + transform2.yScale * pt.y + transform2.dy, + onCurve: pt.onCurve, + lastPointOfContour: pt.lastPointOfContour + }; + newPoints.push(newPt); + } + return newPoints; +} +function getContours(points) { + var contours = []; + var currentContour = []; + for (var i = 0;i < points.length; i += 1) { + var pt = points[i]; + currentContour.push(pt); + if (pt.lastPointOfContour) { + contours.push(currentContour); + currentContour = []; + } + } + check.argument(currentContour.length === 0, "There are still points left in the current contour."); + return contours; +} +function getPath(points) { + var p = new Path2; + if (!points) { + return p; + } + var contours = getContours(points); + for (var contourIndex = 0;contourIndex < contours.length; ++contourIndex) { + var contour = contours[contourIndex]; + var prev = null; + var curr = contour[contour.length - 1]; + var next = contour[0]; + if (curr.onCurve) { + p.moveTo(curr.x, curr.y); + } else { + if (next.onCurve) { + p.moveTo(next.x, next.y); + } else { + var start = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 }; + p.moveTo(start.x, start.y); + } + } + for (var i = 0;i < contour.length; ++i) { + prev = curr; + curr = next; + next = contour[(i + 1) % contour.length]; + if (curr.onCurve) { + p.lineTo(curr.x, curr.y); + } else { + var prev2 = prev; + var next2 = next; + if (!prev.onCurve) { + prev2 = { x: (curr.x + prev.x) * 0.5, y: (curr.y + prev.y) * 0.5 }; + } + if (!next.onCurve) { + next2 = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 }; + } + p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y); + } + } + p.closePath(); + } + return p; +} +function buildPath(glyphs, glyph) { + if (glyph.isComposite) { + for (var j2 = 0;j2 < glyph.components.length; j2 += 1) { + var component = glyph.components[j2]; + var componentGlyph = glyphs.get(component.glyphIndex); + componentGlyph.getPath(); + if (componentGlyph.points) { + var transformedPoints = undefined; + if (component.matchedPoints === undefined) { + transformedPoints = transformPoints(componentGlyph.points, component); + } else { + if (component.matchedPoints[0] > glyph.points.length - 1 || component.matchedPoints[1] > componentGlyph.points.length - 1) { + throw Error("Matched points out of range in " + glyph.name); + } + var firstPt = glyph.points[component.matchedPoints[0]]; + var secondPt = componentGlyph.points[component.matchedPoints[1]]; + var transform2 = { + xScale: component.xScale, + scale01: component.scale01, + scale10: component.scale10, + yScale: component.yScale, + dx: 0, + dy: 0 + }; + secondPt = transformPoints([secondPt], transform2)[0]; + transform2.dx = firstPt.x - secondPt.x; + transform2.dy = firstPt.y - secondPt.y; + transformedPoints = transformPoints(componentGlyph.points, transform2); + } + glyph.points = glyph.points.concat(transformedPoints); + } + } + } + return getPath(glyph.points); +} +function parseGlyfTableAll(data2, start, loca, font) { + var glyphs = new glyphset.GlyphSet(font); + for (var i = 0;i < loca.length - 1; i += 1) { + var offset = loca[i]; + var nextOffset = loca[i + 1]; + if (offset !== nextOffset) { + glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data2, start + offset, buildPath)); + } else { + glyphs.push(i, glyphset.glyphLoader(font, i)); + } + } + return glyphs; +} +function parseGlyfTableOnLowMemory(data2, start, loca, font) { + var glyphs = new glyphset.GlyphSet(font); + font._push = function(i) { + var offset = loca[i]; + var nextOffset = loca[i + 1]; + if (offset !== nextOffset) { + glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data2, start + offset, buildPath)); + } else { + glyphs.push(i, glyphset.glyphLoader(font, i)); + } + }; + return glyphs; +} +function parseGlyfTable(data2, start, loca, font, opt) { + if (opt.lowMemory) { + return parseGlyfTableOnLowMemory(data2, start, loca, font); + } else { + return parseGlyfTableAll(data2, start, loca, font); + } +} +var glyf = { getPath, parse: parseGlyfTable }; +var instructionTable; +var exec; +var execGlyph; +var execComponent; +function Hinting(font) { + this.font = font; + this.getCommands = function(hPoints) { + return glyf.getPath(hPoints).commands; + }; + this._fpgmState = this._prepState = undefined; + this._errorState = 0; +} +function roundOff(v) { + return v; +} +function roundToGrid(v) { + return Math.sign(v) * Math.round(Math.abs(v)); +} +function roundToDoubleGrid(v) { + return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2; +} +function roundToHalfGrid(v) { + return Math.sign(v) * (Math.round(Math.abs(v) + 0.5) - 0.5); +} +function roundUpToGrid(v) { + return Math.sign(v) * Math.ceil(Math.abs(v)); +} +function roundDownToGrid(v) { + return Math.sign(v) * Math.floor(Math.abs(v)); +} +var roundSuper = function(v) { + var period = this.srPeriod; + var phase = this.srPhase; + var threshold = this.srThreshold; + var sign2 = 1; + if (v < 0) { + v = -v; + sign2 = -1; + } + v += threshold - phase; + v = Math.trunc(v / period) * period; + v += phase; + if (v < 0) { + return phase * sign2; + } + return v * sign2; +}; +var xUnitVector = { + x: 1, + y: 0, + axis: "x", + distance: function(p1, p2, o1, o2) { + return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x); + }, + interpolate: function(p, rp1, rp2, pv) { + var do1; + var do2; + var doa1; + var doa2; + var dm1; + var dm2; + var dt; + if (!pv || pv === this) { + do1 = p.xo - rp1.xo; + do2 = p.xo - rp2.xo; + dm1 = rp1.x - rp1.xo; + dm2 = rp2.x - rp2.xo; + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + p.x = p.xo + (dm1 + dm2) / 2; + return; + } + p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt; + return; + } + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); + }, + normalSlope: Number.NEGATIVE_INFINITY, + setRelative: function(p, rp, d, pv, org) { + if (!pv || pv === this) { + p.x = (org ? rp.xo : rp.x) + d; + return; + } + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + p.x = rpdx + (p.y - rpdy) / pv.normalSlope; + }, + slope: 0, + touch: function(p) { + p.xTouched = true; + }, + touched: function(p) { + return p.xTouched; + }, + untouch: function(p) { + p.xTouched = false; + } +}; +var yUnitVector = { + x: 0, + y: 1, + axis: "y", + distance: function(p1, p2, o1, o2) { + return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y); + }, + interpolate: function(p, rp1, rp2, pv) { + var do1; + var do2; + var doa1; + var doa2; + var dm1; + var dm2; + var dt; + if (!pv || pv === this) { + do1 = p.yo - rp1.yo; + do2 = p.yo - rp2.yo; + dm1 = rp1.y - rp1.yo; + dm2 = rp2.y - rp2.yo; + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + p.y = p.yo + (dm1 + dm2) / 2; + return; + } + p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt; + return; + } + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); + }, + normalSlope: 0, + setRelative: function(p, rp, d, pv, org) { + if (!pv || pv === this) { + p.y = (org ? rp.yo : rp.y) + d; + return; + } + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + p.y = rpdy + pv.normalSlope * (p.x - rpdx); + }, + slope: Number.POSITIVE_INFINITY, + touch: function(p) { + p.yTouched = true; + }, + touched: function(p) { + return p.yTouched; + }, + untouch: function(p) { + p.yTouched = false; + } +}; +Object.freeze(xUnitVector); +Object.freeze(yUnitVector); +function UnitVector(x2, y3) { + this.x = x2; + this.y = y3; + this.axis = undefined; + this.slope = y3 / x2; + this.normalSlope = -x2 / y3; + Object.freeze(this); +} +UnitVector.prototype.distance = function(p1, p2, o1, o2) { + return this.x * xUnitVector.distance(p1, p2, o1, o2) + this.y * yUnitVector.distance(p1, p2, o1, o2); +}; +UnitVector.prototype.interpolate = function(p, rp1, rp2, pv) { + var dm1; + var dm2; + var do1; + var do2; + var doa1; + var doa2; + var dt; + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + this.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); +}; +UnitVector.prototype.setRelative = function(p, rp, d, pv, org) { + pv = pv || this; + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + var pvns = pv.normalSlope; + var fvs = this.slope; + var px2 = p.x; + var py2 = p.y; + p.x = (fvs * px2 - pvns * rpdx + rpdy - py2) / (fvs - pvns); + p.y = fvs * (p.x - px2) + py2; +}; +UnitVector.prototype.touch = function(p) { + p.xTouched = true; + p.yTouched = true; +}; +function getUnitVector(x2, y3) { + var d = Math.sqrt(x2 * x2 + y3 * y3); + x2 /= d; + y3 /= d; + if (x2 === 1 && y3 === 0) { + return xUnitVector; + } else if (x2 === 0 && y3 === 1) { + return yUnitVector; + } else { + return new UnitVector(x2, y3); + } +} +function HPoint(x2, y3, lastPointOfContour, onCurve) { + this.x = this.xo = Math.round(x2 * 64) / 64; + this.y = this.yo = Math.round(y3 * 64) / 64; + this.lastPointOfContour = lastPointOfContour; + this.onCurve = onCurve; + this.prevPointOnContour = undefined; + this.nextPointOnContour = undefined; + this.xTouched = false; + this.yTouched = false; + Object.preventExtensions(this); +} +HPoint.prototype.nextTouched = function(v) { + var p = this.nextPointOnContour; + while (!v.touched(p) && p !== this) { + p = p.nextPointOnContour; + } + return p; +}; +HPoint.prototype.prevTouched = function(v) { + var p = this.prevPointOnContour; + while (!v.touched(p) && p !== this) { + p = p.prevPointOnContour; + } + return p; +}; +var HPZero = Object.freeze(new HPoint(0, 0)); +var defaultState = { + cvCutIn: 17 / 16, + deltaBase: 9, + deltaShift: 0.125, + loop: 1, + minDis: 1, + autoFlip: true +}; +function State(env, prog) { + this.env = env; + this.stack = []; + this.prog = prog; + switch (env) { + case "glyf": + this.zp0 = this.zp1 = this.zp2 = 1; + this.rp0 = this.rp1 = this.rp2 = 0; + case "prep": + this.fv = this.pv = this.dpv = xUnitVector; + this.round = roundToGrid; + } +} +Hinting.prototype.exec = function(glyph, ppem) { + if (typeof ppem !== "number") { + throw new Error("Point size is not a number!"); + } + if (this._errorState > 2) { + return; + } + var font = this.font; + var prepState = this._prepState; + if (!prepState || prepState.ppem !== ppem) { + var fpgmState = this._fpgmState; + if (!fpgmState) { + State.prototype = defaultState; + fpgmState = this._fpgmState = new State("fpgm", font.tables.fpgm); + fpgmState.funcs = []; + fpgmState.font = font; + if (exports_opentype_module.DEBUG) { + console.log("---EXEC FPGM---"); + fpgmState.step = -1; + } + try { + exec(fpgmState); + } catch (e) { + console.log("Hinting error in FPGM:" + e); + this._errorState = 3; + return; + } + } + State.prototype = fpgmState; + prepState = this._prepState = new State("prep", font.tables.prep); + prepState.ppem = ppem; + var oCvt = font.tables.cvt; + if (oCvt) { + var cvt = prepState.cvt = new Array(oCvt.length); + var scale2 = ppem / font.unitsPerEm; + for (var c = 0;c < oCvt.length; c++) { + cvt[c] = oCvt[c] * scale2; + } + } else { + prepState.cvt = []; + } + if (exports_opentype_module.DEBUG) { + console.log("---EXEC PREP---"); + prepState.step = -1; + } + try { + exec(prepState); + } catch (e) { + if (this._errorState < 2) { + console.log("Hinting error in PREP:" + e); + } + this._errorState = 2; + } + } + if (this._errorState > 1) { + return; + } + try { + return execGlyph(glyph, prepState); + } catch (e) { + if (this._errorState < 1) { + console.log("Hinting error:" + e); + console.log("Note: further hinting errors are silenced"); + } + this._errorState = 1; + return; + } +}; +execGlyph = function(glyph, prepState) { + var xScale = prepState.ppem / prepState.font.unitsPerEm; + var yScale = xScale; + var components = glyph.components; + var contours; + var gZone; + var state; + State.prototype = prepState; + if (!components) { + state = new State("glyf", glyph.instructions); + if (exports_opentype_module.DEBUG) { + console.log("---EXEC GLYPH---"); + state.step = -1; + } + execComponent(glyph, state, xScale, yScale); + gZone = state.gZone; + } else { + var font = prepState.font; + gZone = []; + contours = []; + for (var i = 0;i < components.length; i++) { + var c = components[i]; + var cg = font.glyphs.get(c.glyphIndex); + state = new State("glyf", cg.instructions); + if (exports_opentype_module.DEBUG) { + console.log("---EXEC COMP " + i + "---"); + state.step = -1; + } + execComponent(cg, state, xScale, yScale); + var dx = Math.round(c.dx * xScale); + var dy2 = Math.round(c.dy * yScale); + var gz = state.gZone; + var cc = state.contours; + for (var pi2 = 0;pi2 < gz.length; pi2++) { + var p = gz[pi2]; + p.xTouched = p.yTouched = false; + p.xo = p.x = p.x + dx; + p.yo = p.y = p.y + dy2; + } + var gLen = gZone.length; + gZone.push.apply(gZone, gz); + for (var j2 = 0;j2 < cc.length; j2++) { + contours.push(cc[j2] + gLen); + } + } + if (glyph.instructions && !state.inhibitGridFit) { + state = new State("glyf", glyph.instructions); + state.gZone = state.z0 = state.z1 = state.z2 = gZone; + state.contours = contours; + gZone.push(new HPoint(0, 0), new HPoint(Math.round(glyph.advanceWidth * xScale), 0)); + if (exports_opentype_module.DEBUG) { + console.log("---EXEC COMPOSITE---"); + state.step = -1; + } + exec(state); + gZone.length -= 2; + } + } + return gZone; +}; +execComponent = function(glyph, state, xScale, yScale) { + var points = glyph.points || []; + var pLen = points.length; + var gZone = state.gZone = state.z0 = state.z1 = state.z2 = []; + var contours = state.contours = []; + var cp; + for (var i = 0;i < pLen; i++) { + cp = points[i]; + gZone[i] = new HPoint(cp.x * xScale, cp.y * yScale, cp.lastPointOfContour, cp.onCurve); + } + var sp; + var np2; + for (var i$1 = 0;i$1 < pLen; i$1++) { + cp = gZone[i$1]; + if (!sp) { + sp = cp; + contours.push(i$1); + } + if (cp.lastPointOfContour) { + cp.nextPointOnContour = sp; + sp.prevPointOnContour = cp; + sp = undefined; + } else { + np2 = gZone[i$1 + 1]; + cp.nextPointOnContour = np2; + np2.prevPointOnContour = cp; + } + } + if (state.inhibitGridFit) { + return; + } + if (exports_opentype_module.DEBUG) { + console.log("PROCESSING GLYPH", state.stack); + for (var i$2 = 0;i$2 < pLen; i$2++) { + console.log(i$2, gZone[i$2].x, gZone[i$2].y); + } + } + gZone.push(new HPoint(0, 0), new HPoint(Math.round(glyph.advanceWidth * xScale), 0)); + exec(state); + gZone.length -= 2; + if (exports_opentype_module.DEBUG) { + console.log("FINISHED GLYPH", state.stack); + for (var i$3 = 0;i$3 < pLen; i$3++) { + console.log(i$3, gZone[i$3].x, gZone[i$3].y); + } + } +}; +exec = function(state) { + var prog = state.prog; + if (!prog) { + return; + } + var pLen = prog.length; + var ins; + for (state.ip = 0;state.ip < pLen; state.ip++) { + if (exports_opentype_module.DEBUG) { + state.step++; + } + ins = instructionTable[prog[state.ip]]; + if (!ins) { + throw new Error("unknown instruction: 0x" + Number(prog[state.ip]).toString(16)); + } + ins(state); + } +}; +function initTZone(state) { + var tZone = state.tZone = new Array(state.gZone.length); + for (var i = 0;i < tZone.length; i++) { + tZone[i] = new HPoint(0, 0); + } +} +function skip(state, handleElse) { + var prog = state.prog; + var ip = state.ip; + var nesting = 1; + var ins; + do { + ins = prog[++ip]; + if (ins === 88) { + nesting++; + } else if (ins === 89) { + nesting--; + } else if (ins === 64) { + ip += prog[ip + 1] + 1; + } else if (ins === 65) { + ip += 2 * prog[ip + 1] + 1; + } else if (ins >= 176 && ins <= 183) { + ip += ins - 176 + 1; + } else if (ins >= 184 && ins <= 191) { + ip += (ins - 184 + 1) * 2; + } else if (handleElse && nesting === 1 && ins === 27) { + break; + } + } while (nesting > 0); + state.ip = ip; +} +function SVTCA(v, state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SVTCA[" + v.axis + "]"); + } + state.fv = state.pv = state.dpv = v; +} +function SPVTCA(v, state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SPVTCA[" + v.axis + "]"); + } + state.pv = state.dpv = v; +} +function SFVTCA(v, state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SFVTCA[" + v.axis + "]"); + } + state.fv = v; +} +function SPVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + if (exports_opentype_module.DEBUG) { + console.log("SPVTL[" + a + "]", p2i, p1i); + } + var dx; + var dy2; + if (!a) { + dx = p1.x - p2.x; + dy2 = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy2 = p1.x - p2.x; + } + state.pv = state.dpv = getUnitVector(dx, dy2); +} +function SFVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + if (exports_opentype_module.DEBUG) { + console.log("SFVTL[" + a + "]", p2i, p1i); + } + var dx; + var dy2; + if (!a) { + dx = p1.x - p2.x; + dy2 = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy2 = p1.x - p2.x; + } + state.fv = getUnitVector(dx, dy2); +} +function SPVFS(state) { + var stack = state.stack; + var y3 = stack.pop(); + var x2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SPVFS[]", y3, x2); + } + state.pv = state.dpv = getUnitVector(x2, y3); +} +function SFVFS(state) { + var stack = state.stack; + var y3 = stack.pop(); + var x2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SPVFS[]", y3, x2); + } + state.fv = getUnitVector(x2, y3); +} +function GPV(state) { + var stack = state.stack; + var pv = state.pv; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GPV[]"); + } + stack.push(pv.x * 16384); + stack.push(pv.y * 16384); +} +function GFV(state) { + var stack = state.stack; + var fv = state.fv; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GFV[]"); + } + stack.push(fv.x * 16384); + stack.push(fv.y * 16384); +} +function SFVTPV(state) { + state.fv = state.pv; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SFVTPV[]"); + } +} +function ISECT(state) { + var stack = state.stack; + var pa0i = stack.pop(); + var pa1i = stack.pop(); + var pb0i = stack.pop(); + var pb1i = stack.pop(); + var pi2 = stack.pop(); + var z0 = state.z0; + var z1 = state.z1; + var pa0 = z0[pa0i]; + var pa1 = z0[pa1i]; + var pb0 = z1[pb0i]; + var pb1 = z1[pb1i]; + var p = state.z2[pi2]; + if (exports_opentype_module.DEBUG) { + console.log("ISECT[], ", pa0i, pa1i, pb0i, pb1i, pi2); + } + var x1 = pa0.x; + var y1 = pa0.y; + var x2 = pa1.x; + var y22 = pa1.y; + var x3 = pb0.x; + var y3 = pb0.y; + var x4 = pb1.x; + var y4 = pb1.y; + var div2 = (x1 - x2) * (y3 - y4) - (y1 - y22) * (x3 - x4); + var f1 = x1 * y22 - y1 * x2; + var f2 = x3 * y4 - y3 * x4; + p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div2; + p.y = (f1 * (y3 - y4) - f2 * (y1 - y22)) / div2; +} +function SRP0(state) { + state.rp0 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SRP0[]", state.rp0); + } +} +function SRP1(state) { + state.rp1 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SRP1[]", state.rp1); + } +} +function SRP2(state) { + state.rp2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SRP2[]", state.rp2); + } +} +function SZP0(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SZP0[]", n2); + } + state.zp0 = n2; + switch (n2) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z0 = state.tZone; + break; + case 1: + state.z0 = state.gZone; + break; + default: + throw new Error("Invalid zone pointer"); + } +} +function SZP1(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SZP1[]", n2); + } + state.zp1 = n2; + switch (n2) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z1 = state.tZone; + break; + case 1: + state.z1 = state.gZone; + break; + default: + throw new Error("Invalid zone pointer"); + } +} +function SZP2(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SZP2[]", n2); + } + state.zp2 = n2; + switch (n2) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z2 = state.tZone; + break; + case 1: + state.z2 = state.gZone; + break; + default: + throw new Error("Invalid zone pointer"); + } +} +function SZPS(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SZPS[]", n2); + } + state.zp0 = state.zp1 = state.zp2 = n2; + switch (n2) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z0 = state.z1 = state.z2 = state.tZone; + break; + case 1: + state.z0 = state.z1 = state.z2 = state.gZone; + break; + default: + throw new Error("Invalid zone pointer"); + } +} +function SLOOP(state) { + state.loop = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SLOOP[]", state.loop); + } +} +function RTG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RTG[]"); + } + state.round = roundToGrid; +} +function RTHG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RTHG[]"); + } + state.round = roundToHalfGrid; +} +function SMD(state) { + var d = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SMD[]", d); + } + state.minDis = d / 64; +} +function ELSE(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ELSE[]"); + } + skip(state, false); +} +function JMPR(state) { + var o = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "JMPR[]", o); + } + state.ip += o - 1; +} +function SCVTCI(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SCVTCI[]", n2); + } + state.cvCutIn = n2 / 64; +} +function DUP(state) { + var stack = state.stack; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DUP[]"); + } + stack.push(stack[stack.length - 1]); +} +function POP(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "POP[]"); + } + state.stack.pop(); +} +function CLEAR(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "CLEAR[]"); + } + state.stack.length = 0; +} +function SWAP(state) { + var stack = state.stack; + var a = stack.pop(); + var b = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SWAP[]"); + } + stack.push(a); + stack.push(b); +} +function DEPTH(state) { + var stack = state.stack; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DEPTH[]"); + } + stack.push(stack.length); +} +function LOOPCALL(state) { + var stack = state.stack; + var fn = stack.pop(); + var c = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "LOOPCALL[]", fn, c); + } + var cip = state.ip; + var cprog = state.prog; + state.prog = state.funcs[fn]; + for (var i = 0;i < c; i++) { + exec(state); + if (exports_opentype_module.DEBUG) { + console.log(++state.step, i + 1 < c ? "next loopcall" : "done loopcall", i); + } + } + state.ip = cip; + state.prog = cprog; +} +function CALL(state) { + var fn = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "CALL[]", fn); + } + var cip = state.ip; + var cprog = state.prog; + state.prog = state.funcs[fn]; + exec(state); + state.ip = cip; + state.prog = cprog; + if (exports_opentype_module.DEBUG) { + console.log(++state.step, "returning from", fn); + } +} +function CINDEX(state) { + var stack = state.stack; + var k2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "CINDEX[]", k2); + } + stack.push(stack[stack.length - k2]); +} +function MINDEX(state) { + var stack = state.stack; + var k2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MINDEX[]", k2); + } + stack.push(stack.splice(stack.length - k2, 1)[0]); +} +function FDEF(state) { + if (state.env !== "fpgm") { + throw new Error("FDEF not allowed here"); + } + var stack = state.stack; + var prog = state.prog; + var ip = state.ip; + var fn = stack.pop(); + var ipBegin = ip; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "FDEF[]", fn); + } + while (prog[++ip] !== 45) { + } + state.ip = ip; + state.funcs[fn] = prog.slice(ipBegin + 1, ip); +} +function MDAP(round, state) { + var pi2 = state.stack.pop(); + var p = state.z0[pi2]; + var fv = state.fv; + var pv = state.pv; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MDAP[" + round + "]", pi2); + } + var d = pv.distance(p, HPZero); + if (round) { + d = state.round(d); + } + fv.setRelative(p, HPZero, d, pv); + fv.touch(p); + state.rp0 = state.rp1 = pi2; +} +function IUP(v, state) { + var z2 = state.z2; + var pLen = z2.length - 2; + var cp; + var pp; + var np2; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "IUP[" + v.axis + "]"); + } + for (var i = 0;i < pLen; i++) { + cp = z2[i]; + if (v.touched(cp)) { + continue; + } + pp = cp.prevTouched(v); + if (pp === cp) { + continue; + } + np2 = cp.nextTouched(v); + if (pp === np2) { + v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true); + } + v.interpolate(cp, pp, np2, v); + } +} +function SHP(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1)[rpi]; + var fv = state.fv; + var pv = state.pv; + var loop = state.loop; + var z2 = state.z2; + while (loop--) { + var pi2 = stack.pop(); + var p = z2[pi2]; + var d = pv.distance(rp, rp, false, true); + fv.setRelative(p, p, d, pv); + fv.touch(p); + if (exports_opentype_module.DEBUG) { + console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "SHP[" + (a ? "rp1" : "rp2") + "]", pi2); + } + } + state.loop = 1; +} +function SHC(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1)[rpi]; + var fv = state.fv; + var pv = state.pv; + var ci = stack.pop(); + var sp = state.z2[state.contours[ci]]; + var p = sp; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SHC[" + a + "]", ci); + } + var d = pv.distance(rp, rp, false, true); + do { + if (p !== rp) { + fv.setRelative(p, p, d, pv); + } + p = p.nextPointOnContour; + } while (p !== sp); +} +function SHZ(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1)[rpi]; + var fv = state.fv; + var pv = state.pv; + var e = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SHZ[" + a + "]", e); + } + var z2; + switch (e) { + case 0: + z2 = state.tZone; + break; + case 1: + z2 = state.gZone; + break; + default: + throw new Error("Invalid zone"); + } + var p; + var d = pv.distance(rp, rp, false, true); + var pLen = z2.length - 2; + for (var i = 0;i < pLen; i++) { + p = z2[i]; + fv.setRelative(p, p, d, pv); + } +} +function SHPIX(state) { + var stack = state.stack; + var loop = state.loop; + var fv = state.fv; + var d = stack.pop() / 64; + var z2 = state.z2; + while (loop--) { + var pi2 = stack.pop(); + var p = z2[pi2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "SHPIX[]", pi2, d); + } + fv.setRelative(p, p, d); + fv.touch(p); + } + state.loop = 1; +} +function IP(state) { + var stack = state.stack; + var rp1i = state.rp1; + var rp2i = state.rp2; + var loop = state.loop; + var rp1 = state.z0[rp1i]; + var rp2 = state.z1[rp2i]; + var fv = state.fv; + var pv = state.dpv; + var z2 = state.z2; + while (loop--) { + var pi2 = stack.pop(); + var p = z2[pi2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "IP[]", pi2, rp1i, "<->", rp2i); + } + fv.interpolate(p, rp1, rp2, pv); + fv.touch(p); + } + state.loop = 1; +} +function MSIRP(a, state) { + var stack = state.stack; + var d = stack.pop() / 64; + var pi2 = stack.pop(); + var p = state.z1[pi2]; + var rp0 = state.z0[state.rp0]; + var fv = state.fv; + var pv = state.pv; + fv.setRelative(p, rp0, d, pv); + fv.touch(p); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MSIRP[" + a + "]", d, pi2); + } + state.rp1 = state.rp0; + state.rp2 = pi2; + if (a) { + state.rp0 = pi2; + } +} +function ALIGNRP(state) { + var stack = state.stack; + var rp0i = state.rp0; + var rp0 = state.z0[rp0i]; + var loop = state.loop; + var fv = state.fv; + var pv = state.pv; + var z1 = state.z1; + while (loop--) { + var pi2 = stack.pop(); + var p = z1[pi2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "ALIGNRP[]", pi2); + } + fv.setRelative(p, rp0, 0, pv); + fv.touch(p); + } + state.loop = 1; +} +function RTDG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RTDG[]"); + } + state.round = roundToDoubleGrid; +} +function MIAP(round, state) { + var stack = state.stack; + var n2 = stack.pop(); + var pi2 = stack.pop(); + var p = state.z0[pi2]; + var fv = state.fv; + var pv = state.pv; + var cv = state.cvt[n2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MIAP[" + round + "]", n2, "(", cv, ")", pi2); + } + var d = pv.distance(p, HPZero); + if (round) { + if (Math.abs(d - cv) < state.cvCutIn) { + d = cv; + } + d = state.round(d); + } + fv.setRelative(p, HPZero, d, pv); + if (state.zp0 === 0) { + p.xo = p.x; + p.yo = p.y; + } + fv.touch(p); + state.rp0 = state.rp1 = pi2; +} +function NPUSHB(state) { + var prog = state.prog; + var ip = state.ip; + var stack = state.stack; + var n2 = prog[++ip]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NPUSHB[]", n2); + } + for (var i = 0;i < n2; i++) { + stack.push(prog[++ip]); + } + state.ip = ip; +} +function NPUSHW(state) { + var ip = state.ip; + var prog = state.prog; + var stack = state.stack; + var n2 = prog[++ip]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NPUSHW[]", n2); + } + for (var i = 0;i < n2; i++) { + var w = prog[++ip] << 8 | prog[++ip]; + if (w & 32768) { + w = -((w ^ 65535) + 1); + } + stack.push(w); + } + state.ip = ip; +} +function WS(state) { + var stack = state.stack; + var store = state.store; + if (!store) { + store = state.store = []; + } + var v = stack.pop(); + var l2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "WS", v, l2); + } + store[l2] = v; +} +function RS(state) { + var stack = state.stack; + var store = state.store; + var l2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RS", l2); + } + var v = store && store[l2] || 0; + stack.push(v); +} +function WCVTP(state) { + var stack = state.stack; + var v = stack.pop(); + var l2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "WCVTP", v, l2); + } + state.cvt[l2] = v / 64; +} +function RCVT(state) { + var stack = state.stack; + var cvte = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RCVT", cvte); + } + stack.push(state.cvt[cvte] * 64); +} +function GC(a, state) { + var stack = state.stack; + var pi2 = stack.pop(); + var p = state.z2[pi2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GC[" + a + "]", pi2); + } + stack.push(state.dpv.distance(p, HPZero, a, false) * 64); +} +function MD(a, state) { + var stack = state.stack; + var pi2 = stack.pop(); + var pi1 = stack.pop(); + var p2 = state.z1[pi2]; + var p1 = state.z0[pi1]; + var d = state.dpv.distance(p1, p2, a, a); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MD[" + a + "]", pi2, pi1, "->", d); + } + state.stack.push(Math.round(d * 64)); +} +function MPPEM(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MPPEM[]"); + } + state.stack.push(state.ppem); +} +function FLIPON(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "FLIPON[]"); + } + state.autoFlip = true; +} +function LT(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "LT[]", e2, e1); + } + stack.push(e1 < e2 ? 1 : 0); +} +function LTEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "LTEQ[]", e2, e1); + } + stack.push(e1 <= e2 ? 1 : 0); +} +function GT(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GT[]", e2, e1); + } + stack.push(e1 > e2 ? 1 : 0); +} +function GTEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GTEQ[]", e2, e1); + } + stack.push(e1 >= e2 ? 1 : 0); +} +function EQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "EQ[]", e2, e1); + } + stack.push(e2 === e1 ? 1 : 0); +} +function NEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NEQ[]", e2, e1); + } + stack.push(e2 !== e1 ? 1 : 0); +} +function ODD(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ODD[]", n2); + } + stack.push(Math.trunc(n2) % 2 ? 1 : 0); +} +function EVEN(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "EVEN[]", n2); + } + stack.push(Math.trunc(n2) % 2 ? 0 : 1); +} +function IF(state) { + var test = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "IF[]", test); + } + if (!test) { + skip(state, true); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "EIF[]"); + } + } +} +function EIF(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "EIF[]"); + } +} +function AND(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "AND[]", e2, e1); + } + stack.push(e2 && e1 ? 1 : 0); +} +function OR(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "OR[]", e2, e1); + } + stack.push(e2 || e1 ? 1 : 0); +} +function NOT(state) { + var stack = state.stack; + var e = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NOT[]", e); + } + stack.push(e ? 0 : 1); +} +function DELTAP123(b, state) { + var stack = state.stack; + var n2 = stack.pop(); + var fv = state.fv; + var pv = state.pv; + var ppem = state.ppem; + var base = state.deltaBase + (b - 1) * 16; + var ds = state.deltaShift; + var z0 = state.z0; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DELTAP[" + b + "]", n2, stack); + } + for (var i = 0;i < n2; i++) { + var pi2 = stack.pop(); + var arg = stack.pop(); + var appem = base + ((arg & 240) >> 4); + if (appem !== ppem) { + continue; + } + var mag = (arg & 15) - 8; + if (mag >= 0) { + mag++; + } + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DELTAPFIX", pi2, "by", mag * ds); + } + var p = z0[pi2]; + fv.setRelative(p, p, mag * ds, pv); + } +} +function SDB(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SDB[]", n2); + } + state.deltaBase = n2; +} +function SDS(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SDS[]", n2); + } + state.deltaShift = Math.pow(0.5, n2); +} +function ADD(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ADD[]", n2, n1); + } + stack.push(n1 + n2); +} +function SUB(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SUB[]", n2, n1); + } + stack.push(n1 - n2); +} +function DIV(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DIV[]", n2, n1); + } + stack.push(n1 * 64 / n2); +} +function MUL(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MUL[]", n2, n1); + } + stack.push(n1 * n2 / 64); +} +function ABS(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ABS[]", n2); + } + stack.push(Math.abs(n2)); +} +function NEG(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NEG[]", n2); + } + stack.push(-n2); +} +function FLOOR(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "FLOOR[]", n2); + } + stack.push(Math.floor(n2 / 64) * 64); +} +function CEILING(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "CEILING[]", n2); + } + stack.push(Math.ceil(n2 / 64) * 64); +} +function ROUND(dt, state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ROUND[]"); + } + stack.push(state.round(n2 / 64) * 64); +} +function WCVTF(state) { + var stack = state.stack; + var v = stack.pop(); + var l2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "WCVTF[]", v, l2); + } + state.cvt[l2] = v * state.ppem / state.font.unitsPerEm; +} +function DELTAC123(b, state) { + var stack = state.stack; + var n2 = stack.pop(); + var ppem = state.ppem; + var base = state.deltaBase + (b - 1) * 16; + var ds = state.deltaShift; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DELTAC[" + b + "]", n2, stack); + } + for (var i = 0;i < n2; i++) { + var c = stack.pop(); + var arg = stack.pop(); + var appem = base + ((arg & 240) >> 4); + if (appem !== ppem) { + continue; + } + var mag = (arg & 15) - 8; + if (mag >= 0) { + mag++; + } + var delta = mag * ds; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DELTACFIX", c, "by", delta); + } + state.cvt[c] += delta; + } +} +function SROUND(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SROUND[]", n2); + } + state.round = roundSuper; + var period; + switch (n2 & 192) { + case 0: + period = 0.5; + break; + case 64: + period = 1; + break; + case 128: + period = 2; + break; + default: + throw new Error("invalid SROUND value"); + } + state.srPeriod = period; + switch (n2 & 48) { + case 0: + state.srPhase = 0; + break; + case 16: + state.srPhase = 0.25 * period; + break; + case 32: + state.srPhase = 0.5 * period; + break; + case 48: + state.srPhase = 0.75 * period; + break; + default: + throw new Error("invalid SROUND value"); + } + n2 &= 15; + if (n2 === 0) { + state.srThreshold = 0; + } else { + state.srThreshold = (n2 / 8 - 0.5) * period; + } +} +function S45ROUND(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "S45ROUND[]", n2); + } + state.round = roundSuper; + var period; + switch (n2 & 192) { + case 0: + period = Math.sqrt(2) / 2; + break; + case 64: + period = Math.sqrt(2); + break; + case 128: + period = 2 * Math.sqrt(2); + break; + default: + throw new Error("invalid S45ROUND value"); + } + state.srPeriod = period; + switch (n2 & 48) { + case 0: + state.srPhase = 0; + break; + case 16: + state.srPhase = 0.25 * period; + break; + case 32: + state.srPhase = 0.5 * period; + break; + case 48: + state.srPhase = 0.75 * period; + break; + default: + throw new Error("invalid S45ROUND value"); + } + n2 &= 15; + if (n2 === 0) { + state.srThreshold = 0; + } else { + state.srThreshold = (n2 / 8 - 0.5) * period; + } +} +function ROFF(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ROFF[]"); + } + state.round = roundOff; +} +function RUTG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RUTG[]"); + } + state.round = roundUpToGrid; +} +function RDTG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RDTG[]"); + } + state.round = roundDownToGrid; +} +function SCANCTRL(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SCANCTRL[]", n2); + } +} +function SDPVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SDPVTL[" + a + "]", p2i, p1i); + } + var dx; + var dy2; + if (!a) { + dx = p1.x - p2.x; + dy2 = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy2 = p1.x - p2.x; + } + state.dpv = getUnitVector(dx, dy2); +} +function GETINFO(state) { + var stack = state.stack; + var sel = stack.pop(); + var r = 0; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GETINFO[]", sel); + } + if (sel & 1) { + r = 35; + } + if (sel & 32) { + r |= 4096; + } + stack.push(r); +} +function ROLL(state) { + var stack = state.stack; + var a = stack.pop(); + var b = stack.pop(); + var c = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ROLL[]"); + } + stack.push(b); + stack.push(a); + stack.push(c); +} +function MAX(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MAX[]", e2, e1); + } + stack.push(Math.max(e1, e2)); +} +function MIN(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MIN[]", e2, e1); + } + stack.push(Math.min(e1, e2)); +} +function SCANTYPE(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SCANTYPE[]", n2); + } +} +function INSTCTRL(state) { + var s = state.stack.pop(); + var v = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "INSTCTRL[]", s, v); + } + switch (s) { + case 1: + state.inhibitGridFit = !!v; + return; + case 2: + state.ignoreCvt = !!v; + return; + default: + throw new Error("invalid INSTCTRL[] selector"); + } +} +function PUSHB(n2, state) { + var stack = state.stack; + var prog = state.prog; + var ip = state.ip; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "PUSHB[" + n2 + "]"); + } + for (var i = 0;i < n2; i++) { + stack.push(prog[++ip]); + } + state.ip = ip; +} +function PUSHW(n2, state) { + var ip = state.ip; + var prog = state.prog; + var stack = state.stack; + if (exports_opentype_module.DEBUG) { + console.log(state.ip, "PUSHW[" + n2 + "]"); + } + for (var i = 0;i < n2; i++) { + var w = prog[++ip] << 8 | prog[++ip]; + if (w & 32768) { + w = -((w ^ 65535) + 1); + } + stack.push(w); + } + state.ip = ip; +} +function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) { + var stack = state.stack; + var cvte = indirect && stack.pop(); + var pi2 = stack.pop(); + var rp0i = state.rp0; + var rp = state.z0[rp0i]; + var p = state.z1[pi2]; + var md = state.minDis; + var fv = state.fv; + var pv = state.dpv; + var od2; + var d; + var sign2; + var cv; + d = od2 = pv.distance(p, rp, true, true); + sign2 = d >= 0 ? 1 : -1; + d = Math.abs(d); + if (indirect) { + cv = state.cvt[cvte]; + if (ro && Math.abs(d - cv) < state.cvCutIn) { + d = cv; + } + } + if (keepD && d < md) { + d = md; + } + if (ro) { + d = state.round(d); + } + fv.setRelative(p, rp, sign2 * d, pv); + fv.touch(p); + if (exports_opentype_module.DEBUG) { + console.log(state.step, (indirect ? "MIRP[" : "MDRP[") + (setRp0 ? "M" : "m") + (keepD ? ">" : "_") + (ro ? "R" : "_") + (dt === 0 ? "Gr" : dt === 1 ? "Bl" : dt === 2 ? "Wh" : "") + "]", indirect ? cvte + "(" + state.cvt[cvte] + "," + cv + ")" : "", pi2, "(d =", od2, "->", sign2 * d, ")"); + } + state.rp1 = state.rp0; + state.rp2 = pi2; + if (setRp0) { + state.rp0 = pi2; + } +} +instructionTable = [ + SVTCA.bind(undefined, yUnitVector), + SVTCA.bind(undefined, xUnitVector), + SPVTCA.bind(undefined, yUnitVector), + SPVTCA.bind(undefined, xUnitVector), + SFVTCA.bind(undefined, yUnitVector), + SFVTCA.bind(undefined, xUnitVector), + SPVTL.bind(undefined, 0), + SPVTL.bind(undefined, 1), + SFVTL.bind(undefined, 0), + SFVTL.bind(undefined, 1), + SPVFS, + SFVFS, + GPV, + GFV, + SFVTPV, + ISECT, + SRP0, + SRP1, + SRP2, + SZP0, + SZP1, + SZP2, + SZPS, + SLOOP, + RTG, + RTHG, + SMD, + ELSE, + JMPR, + SCVTCI, + undefined, + undefined, + DUP, + POP, + CLEAR, + SWAP, + DEPTH, + CINDEX, + MINDEX, + undefined, + undefined, + undefined, + LOOPCALL, + CALL, + FDEF, + undefined, + MDAP.bind(undefined, 0), + MDAP.bind(undefined, 1), + IUP.bind(undefined, yUnitVector), + IUP.bind(undefined, xUnitVector), + SHP.bind(undefined, 0), + SHP.bind(undefined, 1), + SHC.bind(undefined, 0), + SHC.bind(undefined, 1), + SHZ.bind(undefined, 0), + SHZ.bind(undefined, 1), + SHPIX, + IP, + MSIRP.bind(undefined, 0), + MSIRP.bind(undefined, 1), + ALIGNRP, + RTDG, + MIAP.bind(undefined, 0), + MIAP.bind(undefined, 1), + NPUSHB, + NPUSHW, + WS, + RS, + WCVTP, + RCVT, + GC.bind(undefined, 0), + GC.bind(undefined, 1), + undefined, + MD.bind(undefined, 0), + MD.bind(undefined, 1), + MPPEM, + undefined, + FLIPON, + undefined, + undefined, + LT, + LTEQ, + GT, + GTEQ, + EQ, + NEQ, + ODD, + EVEN, + IF, + EIF, + AND, + OR, + NOT, + DELTAP123.bind(undefined, 1), + SDB, + SDS, + ADD, + SUB, + DIV, + MUL, + ABS, + NEG, + FLOOR, + CEILING, + ROUND.bind(undefined, 0), + ROUND.bind(undefined, 1), + ROUND.bind(undefined, 2), + ROUND.bind(undefined, 3), + undefined, + undefined, + undefined, + undefined, + WCVTF, + DELTAP123.bind(undefined, 2), + DELTAP123.bind(undefined, 3), + DELTAC123.bind(undefined, 1), + DELTAC123.bind(undefined, 2), + DELTAC123.bind(undefined, 3), + SROUND, + S45ROUND, + undefined, + undefined, + ROFF, + undefined, + RUTG, + RDTG, + POP, + POP, + undefined, + undefined, + undefined, + undefined, + undefined, + SCANCTRL, + SDPVTL.bind(undefined, 0), + SDPVTL.bind(undefined, 1), + GETINFO, + undefined, + ROLL, + MAX, + MIN, + SCANTYPE, + INSTCTRL, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + PUSHB.bind(undefined, 1), + PUSHB.bind(undefined, 2), + PUSHB.bind(undefined, 3), + PUSHB.bind(undefined, 4), + PUSHB.bind(undefined, 5), + PUSHB.bind(undefined, 6), + PUSHB.bind(undefined, 7), + PUSHB.bind(undefined, 8), + PUSHW.bind(undefined, 1), + PUSHW.bind(undefined, 2), + PUSHW.bind(undefined, 3), + PUSHW.bind(undefined, 4), + PUSHW.bind(undefined, 5), + PUSHW.bind(undefined, 6), + PUSHW.bind(undefined, 7), + PUSHW.bind(undefined, 8), + MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 0), + MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 1), + MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 2), + MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 3), + MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 0), + MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 1), + MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 2), + MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 3), + MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 0), + MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 1), + MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 2), + MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 3), + MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 0), + MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 1), + MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 2), + MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 3), + MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 0), + MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 1), + MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 2), + MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 3), + MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 0), + MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 1), + MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 2), + MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 3), + MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 0), + MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 1), + MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 2), + MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 3), + MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 0), + MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 1), + MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 2), + MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 3), + MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 0), + MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 1), + MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 2), + MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 3), + MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 0), + MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 1), + MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 2), + MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 3), + MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 0), + MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 1), + MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 2), + MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 3), + MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 0), + MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 1), + MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 2), + MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 3), + MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 0), + MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 1), + MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 2), + MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 3), + MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 0), + MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 1), + MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 2), + MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 3), + MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 0), + MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 1), + MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 2), + MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 3), + MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 0), + MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 1), + MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 2), + MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 3) +]; +function Token(char) { + this.char = char; + this.state = {}; + this.activeState = null; +} +function ContextRange(startIndex, endOffset, contextName) { + this.contextName = contextName; + this.startIndex = startIndex; + this.endOffset = endOffset; +} +function ContextChecker(contextName, checkStart, checkEnd) { + this.contextName = contextName; + this.openRange = null; + this.ranges = []; + this.checkStart = checkStart; + this.checkEnd = checkEnd; +} +function ContextParams(context, currentIndex) { + this.context = context; + this.index = currentIndex; + this.length = context.length; + this.current = context[currentIndex]; + this.backtrack = context.slice(0, currentIndex); + this.lookahead = context.slice(currentIndex + 1); +} +function Event2(eventId) { + this.eventId = eventId; + this.subscribers = []; +} +function initializeCoreEvents(events) { + var this$1 = this; + var coreEvents = [ + "start", + "end", + "next", + "newToken", + "contextStart", + "contextEnd", + "insertToken", + "removeToken", + "removeRange", + "replaceToken", + "replaceRange", + "composeRUD", + "updateContextsRanges" + ]; + coreEvents.forEach(function(eventId) { + Object.defineProperty(this$1.events, eventId, { + value: new Event2(eventId) + }); + }); + if (!!events) { + coreEvents.forEach(function(eventId) { + var event = events[eventId]; + if (typeof event === "function") { + this$1.events[eventId].subscribe(event); + } + }); + } + var requiresContextUpdate = [ + "insertToken", + "removeToken", + "removeRange", + "replaceToken", + "replaceRange", + "composeRUD" + ]; + requiresContextUpdate.forEach(function(eventId) { + this$1.events[eventId].subscribe(this$1.updateContextsRanges); + }); +} +function Tokenizer(events) { + this.tokens = []; + this.registeredContexts = {}; + this.contextCheckers = []; + this.events = {}; + this.registeredModifiers = []; + initializeCoreEvents.call(this, events); +} +Token.prototype.setState = function(key2, value2) { + this.state[key2] = value2; + this.activeState = { key: key2, value: this.state[key2] }; + return this.activeState; +}; +Token.prototype.getState = function(stateId) { + return this.state[stateId] || null; +}; +Tokenizer.prototype.inboundIndex = function(index2) { + return index2 >= 0 && index2 < this.tokens.length; +}; +Tokenizer.prototype.composeRUD = function(RUDs) { + var this$1 = this; + var silent = true; + var state = RUDs.map(function(RUD) { + return this$1[RUD[0]].apply(this$1, RUD.slice(1).concat(silent)); + }); + var hasFAILObject = function(obj) { + return typeof obj === "object" && obj.hasOwnProperty("FAIL"); + }; + if (state.every(hasFAILObject)) { + return { + FAIL: "composeRUD: one or more operations hasn't completed successfully", + report: state.filter(hasFAILObject) + }; + } + this.dispatch("composeRUD", [state.filter(function(op) { + return !hasFAILObject(op); + })]); +}; +Tokenizer.prototype.replaceRange = function(startIndex, offset, tokens, silent) { + offset = offset !== null ? offset : this.tokens.length; + var isTokenType = tokens.every(function(token) { + return token instanceof Token; + }); + if (!isNaN(startIndex) && this.inboundIndex(startIndex) && isTokenType) { + var replaced = this.tokens.splice.apply(this.tokens, [startIndex, offset].concat(tokens)); + if (!silent) { + this.dispatch("replaceToken", [startIndex, offset, tokens]); + } + return [replaced, tokens]; + } else { + return { FAIL: "replaceRange: invalid tokens or startIndex." }; + } +}; +Tokenizer.prototype.replaceToken = function(index2, token, silent) { + if (!isNaN(index2) && this.inboundIndex(index2) && token instanceof Token) { + var replaced = this.tokens.splice(index2, 1, token); + if (!silent) { + this.dispatch("replaceToken", [index2, token]); + } + return [replaced[0], token]; + } else { + return { FAIL: "replaceToken: invalid token or index." }; + } +}; +Tokenizer.prototype.removeRange = function(startIndex, offset, silent) { + offset = !isNaN(offset) ? offset : this.tokens.length; + var tokens = this.tokens.splice(startIndex, offset); + if (!silent) { + this.dispatch("removeRange", [tokens, startIndex, offset]); + } + return tokens; +}; +Tokenizer.prototype.removeToken = function(index2, silent) { + if (!isNaN(index2) && this.inboundIndex(index2)) { + var token = this.tokens.splice(index2, 1); + if (!silent) { + this.dispatch("removeToken", [token, index2]); + } + return token; + } else { + return { FAIL: "removeToken: invalid token index." }; + } +}; +Tokenizer.prototype.insertToken = function(tokens, index2, silent) { + var tokenType = tokens.every(function(token) { + return token instanceof Token; + }); + if (tokenType) { + this.tokens.splice.apply(this.tokens, [index2, 0].concat(tokens)); + if (!silent) { + this.dispatch("insertToken", [tokens, index2]); + } + return tokens; + } else { + return { FAIL: "insertToken: invalid token(s)." }; + } +}; +Tokenizer.prototype.registerModifier = function(modifierId, condition, modifier) { + this.events.newToken.subscribe(function(token, contextParams) { + var conditionParams = [token, contextParams]; + var canApplyModifier = condition === null || condition.apply(this, conditionParams) === true; + var modifierParams = [token, contextParams]; + if (canApplyModifier) { + var newStateValue = modifier.apply(this, modifierParams); + token.setState(modifierId, newStateValue); + } + }); + this.registeredModifiers.push(modifierId); +}; +Event2.prototype.subscribe = function(eventHandler) { + if (typeof eventHandler === "function") { + return this.subscribers.push(eventHandler) - 1; + } else { + return { FAIL: "invalid '" + this.eventId + "' event handler" }; + } +}; +Event2.prototype.unsubscribe = function(subsId) { + this.subscribers.splice(subsId, 1); +}; +ContextParams.prototype.setCurrentIndex = function(index2) { + this.index = index2; + this.current = this.context[index2]; + this.backtrack = this.context.slice(0, index2); + this.lookahead = this.context.slice(index2 + 1); +}; +ContextParams.prototype.get = function(offset) { + switch (true) { + case offset === 0: + return this.current; + case (offset < 0 && Math.abs(offset) <= this.backtrack.length): + return this.backtrack.slice(offset)[0]; + case (offset > 0 && offset <= this.lookahead.length): + return this.lookahead[offset - 1]; + default: + return null; + } +}; +Tokenizer.prototype.rangeToText = function(range) { + if (range instanceof ContextRange) { + return this.getRangeTokens(range).map(function(token) { + return token.char; + }).join(""); + } +}; +Tokenizer.prototype.getText = function() { + return this.tokens.map(function(token) { + return token.char; + }).join(""); +}; +Tokenizer.prototype.getContext = function(contextName) { + var context = this.registeredContexts[contextName]; + return context ? context : null; +}; +Tokenizer.prototype.on = function(eventName, eventHandler) { + var event = this.events[eventName]; + if (!!event) { + return event.subscribe(eventHandler); + } else { + return null; + } +}; +Tokenizer.prototype.dispatch = function(eventName, args) { + var this$1 = this; + var event = this.events[eventName]; + if (event instanceof Event2) { + event.subscribers.forEach(function(subscriber) { + subscriber.apply(this$1, args || []); + }); + } +}; +Tokenizer.prototype.registerContextChecker = function(contextName, contextStartCheck, contextEndCheck) { + if (!!this.getContext(contextName)) { + return { + FAIL: "context name '" + contextName + "' is already registered." + }; + } + if (typeof contextStartCheck !== "function") { + return { + FAIL: "missing context start check." + }; + } + if (typeof contextEndCheck !== "function") { + return { + FAIL: "missing context end check." + }; + } + var contextCheckers = new ContextChecker(contextName, contextStartCheck, contextEndCheck); + this.registeredContexts[contextName] = contextCheckers; + this.contextCheckers.push(contextCheckers); + return contextCheckers; +}; +Tokenizer.prototype.getRangeTokens = function(range) { + var endIndex = range.startIndex + range.endOffset; + return [].concat(this.tokens.slice(range.startIndex, endIndex)); +}; +Tokenizer.prototype.getContextRanges = function(contextName) { + var context = this.getContext(contextName); + if (!!context) { + return context.ranges; + } else { + return { FAIL: "context checker '" + contextName + "' is not registered." }; + } +}; +Tokenizer.prototype.resetContextsRanges = function() { + var registeredContexts = this.registeredContexts; + for (var contextName in registeredContexts) { + if (registeredContexts.hasOwnProperty(contextName)) { + var context = registeredContexts[contextName]; + context.ranges = []; + } + } +}; +Tokenizer.prototype.updateContextsRanges = function() { + this.resetContextsRanges(); + var chars = this.tokens.map(function(token) { + return token.char; + }); + for (var i = 0;i < chars.length; i++) { + var contextParams = new ContextParams(chars, i); + this.runContextCheck(contextParams); + } + this.dispatch("updateContextsRanges", [this.registeredContexts]); +}; +Tokenizer.prototype.setEndOffset = function(offset, contextName) { + var startIndex = this.getContext(contextName).openRange.startIndex; + var range = new ContextRange(startIndex, offset, contextName); + var ranges = this.getContext(contextName).ranges; + range.rangeId = contextName + "." + ranges.length; + ranges.push(range); + this.getContext(contextName).openRange = null; + return range; +}; +Tokenizer.prototype.runContextCheck = function(contextParams) { + var this$1 = this; + var index2 = contextParams.index; + this.contextCheckers.forEach(function(contextChecker) { + var contextName = contextChecker.contextName; + var openRange = this$1.getContext(contextName).openRange; + if (!openRange && contextChecker.checkStart(contextParams)) { + openRange = new ContextRange(index2, null, contextName); + this$1.getContext(contextName).openRange = openRange; + this$1.dispatch("contextStart", [contextName, index2]); + } + if (!!openRange && contextChecker.checkEnd(contextParams)) { + var offset = index2 - openRange.startIndex + 1; + var range = this$1.setEndOffset(offset, contextName); + this$1.dispatch("contextEnd", [contextName, range]); + } + }); +}; +Tokenizer.prototype.tokenize = function(text2) { + this.tokens = []; + this.resetContextsRanges(); + var chars = Array.from(text2); + this.dispatch("start"); + for (var i = 0;i < chars.length; i++) { + var char = chars[i]; + var contextParams = new ContextParams(chars, i); + this.dispatch("next", [contextParams]); + this.runContextCheck(contextParams); + var token = new Token(char); + this.tokens.push(token); + this.dispatch("newToken", [token, contextParams]); + } + this.dispatch("end", [this.tokens]); + return this.tokens; +}; +function isArabicChar(c) { + return /[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(c); +} +function isIsolatedArabicChar(char) { + return /[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(char); +} +function isTashkeelArabicChar(char) { + return /[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(char); +} +function isLatinChar(c) { + return /[A-z]/.test(c); +} +function isWhiteSpace(c) { + return /\s/.test(c); +} +function FeatureQuery(font) { + this.font = font; + this.features = {}; +} +function SubstitutionAction(action) { + this.id = action.id; + this.tag = action.tag; + this.substitution = action.substitution; +} +function lookupCoverage(glyphIndex, coverage) { + if (!glyphIndex) { + return -1; + } + switch (coverage.format) { + case 1: + return coverage.glyphs.indexOf(glyphIndex); + case 2: + var ranges = coverage.ranges; + for (var i = 0;i < ranges.length; i++) { + var range = ranges[i]; + if (glyphIndex >= range.start && glyphIndex <= range.end) { + var offset = glyphIndex - range.start; + return range.index + offset; + } + } + break; + default: + return -1; + } + return -1; +} +function singleSubstitutionFormat1(glyphIndex, subtable) { + var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (substituteIndex === -1) { + return null; + } + return glyphIndex + subtable.deltaGlyphId; +} +function singleSubstitutionFormat2(glyphIndex, subtable) { + var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (substituteIndex === -1) { + return null; + } + return subtable.substitute[substituteIndex]; +} +function lookupCoverageList(coverageList, contextParams) { + var lookupList = []; + for (var i = 0;i < coverageList.length; i++) { + var coverage = coverageList[i]; + var glyphIndex = contextParams.current; + glyphIndex = Array.isArray(glyphIndex) ? glyphIndex[0] : glyphIndex; + var lookupIndex = lookupCoverage(glyphIndex, coverage); + if (lookupIndex !== -1) { + lookupList.push(lookupIndex); + } + } + if (lookupList.length !== coverageList.length) { + return -1; + } + return lookupList; +} +function chainingSubstitutionFormat3(contextParams, subtable) { + var lookupsCount = subtable.inputCoverage.length + subtable.lookaheadCoverage.length + subtable.backtrackCoverage.length; + if (contextParams.context.length < lookupsCount) { + return []; + } + var inputLookups = lookupCoverageList(subtable.inputCoverage, contextParams); + if (inputLookups === -1) { + return []; + } + var lookaheadOffset = subtable.inputCoverage.length - 1; + if (contextParams.lookahead.length < subtable.lookaheadCoverage.length) { + return []; + } + var lookaheadContext = contextParams.lookahead.slice(lookaheadOffset); + while (lookaheadContext.length && isTashkeelArabicChar(lookaheadContext[0].char)) { + lookaheadContext.shift(); + } + var lookaheadParams = new ContextParams(lookaheadContext, 0); + var lookaheadLookups = lookupCoverageList(subtable.lookaheadCoverage, lookaheadParams); + var backtrackContext = [].concat(contextParams.backtrack); + backtrackContext.reverse(); + while (backtrackContext.length && isTashkeelArabicChar(backtrackContext[0].char)) { + backtrackContext.shift(); + } + if (backtrackContext.length < subtable.backtrackCoverage.length) { + return []; + } + var backtrackParams = new ContextParams(backtrackContext, 0); + var backtrackLookups = lookupCoverageList(subtable.backtrackCoverage, backtrackParams); + var contextRulesMatch = inputLookups.length === subtable.inputCoverage.length && lookaheadLookups.length === subtable.lookaheadCoverage.length && backtrackLookups.length === subtable.backtrackCoverage.length; + var substitutions = []; + if (contextRulesMatch) { + for (var i = 0;i < subtable.lookupRecords.length; i++) { + var lookupRecord = subtable.lookupRecords[i]; + var lookupListIndex = lookupRecord.lookupListIndex; + var lookupTable = this.getLookupByIndex(lookupListIndex); + for (var s = 0;s < lookupTable.subtables.length; s++) { + var subtable$1 = lookupTable.subtables[s]; + var lookup = this.getLookupMethod(lookupTable, subtable$1); + var substitutionType = this.getSubstitutionType(lookupTable, subtable$1); + if (substitutionType === "12") { + for (var n2 = 0;n2 < inputLookups.length; n2++) { + var glyphIndex = contextParams.get(n2); + var substitution = lookup(glyphIndex); + if (substitution) { + substitutions.push(substitution); + } + } + } + } + } + } + return substitutions; +} +function ligatureSubstitutionFormat1(contextParams, subtable) { + var glyphIndex = contextParams.current; + var ligSetIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (ligSetIndex === -1) { + return null; + } + var ligature; + var ligatureSet = subtable.ligatureSets[ligSetIndex]; + for (var s = 0;s < ligatureSet.length; s++) { + ligature = ligatureSet[s]; + for (var l2 = 0;l2 < ligature.components.length; l2++) { + var lookaheadItem = contextParams.lookahead[l2]; + var component = ligature.components[l2]; + if (lookaheadItem !== component) { + break; + } + if (l2 === ligature.components.length - 1) { + return ligature; + } + } + } + return null; +} +function decompositionSubstitutionFormat1(glyphIndex, subtable) { + var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (substituteIndex === -1) { + return null; + } + return subtable.sequences[substituteIndex]; +} +FeatureQuery.prototype.getDefaultScriptFeaturesIndexes = function() { + var scripts = this.font.tables.gsub.scripts; + for (var s = 0;s < scripts.length; s++) { + var script = scripts[s]; + if (script.tag === "DFLT") { + return script.script.defaultLangSys.featureIndexes; + } + } + return []; +}; +FeatureQuery.prototype.getScriptFeaturesIndexes = function(scriptTag) { + var tables = this.font.tables; + if (!tables.gsub) { + return []; + } + if (!scriptTag) { + return this.getDefaultScriptFeaturesIndexes(); + } + var scripts = this.font.tables.gsub.scripts; + for (var i = 0;i < scripts.length; i++) { + var script = scripts[i]; + if (script.tag === scriptTag && script.script.defaultLangSys) { + return script.script.defaultLangSys.featureIndexes; + } else { + var langSysRecords = script.langSysRecords; + if (!!langSysRecords) { + for (var j2 = 0;j2 < langSysRecords.length; j2++) { + var langSysRecord = langSysRecords[j2]; + if (langSysRecord.tag === scriptTag) { + var langSys = langSysRecord.langSys; + return langSys.featureIndexes; + } + } + } + } + } + return this.getDefaultScriptFeaturesIndexes(); +}; +FeatureQuery.prototype.mapTagsToFeatures = function(features, scriptTag) { + var tags = {}; + for (var i = 0;i < features.length; i++) { + var tag = features[i].tag; + var feature = features[i].feature; + tags[tag] = feature; + } + this.features[scriptTag].tags = tags; +}; +FeatureQuery.prototype.getScriptFeatures = function(scriptTag) { + var features = this.features[scriptTag]; + if (this.features.hasOwnProperty(scriptTag)) { + return features; + } + var featuresIndexes = this.getScriptFeaturesIndexes(scriptTag); + if (!featuresIndexes) { + return null; + } + var gsub2 = this.font.tables.gsub; + features = featuresIndexes.map(function(index2) { + return gsub2.features[index2]; + }); + this.features[scriptTag] = features; + this.mapTagsToFeatures(features, scriptTag); + return features; +}; +FeatureQuery.prototype.getSubstitutionType = function(lookupTable, subtable) { + var lookupType = lookupTable.lookupType.toString(); + var substFormat = subtable.substFormat.toString(); + return lookupType + substFormat; +}; +FeatureQuery.prototype.getLookupMethod = function(lookupTable, subtable) { + var this$1 = this; + var substitutionType = this.getSubstitutionType(lookupTable, subtable); + switch (substitutionType) { + case "11": + return function(glyphIndex) { + return singleSubstitutionFormat1.apply(this$1, [glyphIndex, subtable]); + }; + case "12": + return function(glyphIndex) { + return singleSubstitutionFormat2.apply(this$1, [glyphIndex, subtable]); + }; + case "63": + return function(contextParams) { + return chainingSubstitutionFormat3.apply(this$1, [contextParams, subtable]); + }; + case "41": + return function(contextParams) { + return ligatureSubstitutionFormat1.apply(this$1, [contextParams, subtable]); + }; + case "21": + return function(glyphIndex) { + return decompositionSubstitutionFormat1.apply(this$1, [glyphIndex, subtable]); + }; + default: + throw new Error("lookupType: " + lookupTable.lookupType + " - " + "substFormat: " + subtable.substFormat + " " + "is not yet supported"); + } +}; +FeatureQuery.prototype.lookupFeature = function(query) { + var contextParams = query.contextParams; + var currentIndex = contextParams.index; + var feature = this.getFeature({ + tag: query.tag, + script: query.script + }); + if (!feature) { + return new Error("font '" + this.font.names.fullName.en + "' " + "doesn't support feature '" + query.tag + "' " + "for script '" + query.script + "'."); + } + var lookups = this.getFeatureLookups(feature); + var substitutions = [].concat(contextParams.context); + for (var l2 = 0;l2 < lookups.length; l2++) { + var lookupTable = lookups[l2]; + var subtables = this.getLookupSubtables(lookupTable); + for (var s = 0;s < subtables.length; s++) { + var subtable = subtables[s]; + var substType = this.getSubstitutionType(lookupTable, subtable); + var lookup = this.getLookupMethod(lookupTable, subtable); + var substitution = undefined; + switch (substType) { + case "11": + substitution = lookup(contextParams.current); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 11, + tag: query.tag, + substitution + })); + } + break; + case "12": + substitution = lookup(contextParams.current); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 12, + tag: query.tag, + substitution + })); + } + break; + case "63": + substitution = lookup(contextParams); + if (Array.isArray(substitution) && substitution.length) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 63, + tag: query.tag, + substitution + })); + } + break; + case "41": + substitution = lookup(contextParams); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 41, + tag: query.tag, + substitution + })); + } + break; + case "21": + substitution = lookup(contextParams.current); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 21, + tag: query.tag, + substitution + })); + } + break; + } + contextParams = new ContextParams(substitutions, currentIndex); + if (Array.isArray(substitution) && !substitution.length) { + continue; + } + substitution = null; + } + } + return substitutions.length ? substitutions : null; +}; +FeatureQuery.prototype.supports = function(query) { + if (!query.script) { + return false; + } + this.getScriptFeatures(query.script); + var supportedScript = this.features.hasOwnProperty(query.script); + if (!query.tag) { + return supportedScript; + } + var supportedFeature = this.features[query.script].some(function(feature) { + return feature.tag === query.tag; + }); + return supportedScript && supportedFeature; +}; +FeatureQuery.prototype.getLookupSubtables = function(lookupTable) { + return lookupTable.subtables || null; +}; +FeatureQuery.prototype.getLookupByIndex = function(index2) { + var lookups = this.font.tables.gsub.lookups; + return lookups[index2] || null; +}; +FeatureQuery.prototype.getFeatureLookups = function(feature) { + return feature.lookupListIndexes.map(this.getLookupByIndex.bind(this)); +}; +FeatureQuery.prototype.getFeature = function getFeature(query) { + if (!this.font) { + return { FAIL: "No font was found" }; + } + if (!this.features.hasOwnProperty(query.script)) { + this.getScriptFeatures(query.script); + } + var scriptFeatures = this.features[query.script]; + if (!scriptFeatures) { + return { FAIL: "No feature for script " + query.script }; + } + if (!scriptFeatures.tags[query.tag]) { + return null; + } + return this.features[query.script].tags[query.tag]; +}; +function arabicWordStartCheck(contextParams) { + var char = contextParams.current; + var prevChar = contextParams.get(-1); + return prevChar === null && isArabicChar(char) || !isArabicChar(prevChar) && isArabicChar(char); +} +function arabicWordEndCheck(contextParams) { + var nextChar = contextParams.get(1); + return nextChar === null || !isArabicChar(nextChar); +} +var arabicWordCheck = { + startCheck: arabicWordStartCheck, + endCheck: arabicWordEndCheck +}; +function arabicSentenceStartCheck(contextParams) { + var char = contextParams.current; + var prevChar = contextParams.get(-1); + return (isArabicChar(char) || isTashkeelArabicChar(char)) && !isArabicChar(prevChar); +} +function arabicSentenceEndCheck(contextParams) { + var nextChar = contextParams.get(1); + switch (true) { + case nextChar === null: + return true; + case (!isArabicChar(nextChar) && !isTashkeelArabicChar(nextChar)): + var nextIsWhitespace = isWhiteSpace(nextChar); + if (!nextIsWhitespace) { + return true; + } + if (nextIsWhitespace) { + var arabicCharAhead = false; + arabicCharAhead = contextParams.lookahead.some(function(c) { + return isArabicChar(c) || isTashkeelArabicChar(c); + }); + if (!arabicCharAhead) { + return true; + } + } + break; + default: + return false; + } +} +var arabicSentenceCheck = { + startCheck: arabicSentenceStartCheck, + endCheck: arabicSentenceEndCheck +}; +function singleSubstitutionFormat1$1(action, tokens, index2) { + tokens[index2].setState(action.tag, action.substitution); +} +function singleSubstitutionFormat2$1(action, tokens, index2) { + tokens[index2].setState(action.tag, action.substitution); +} +function chainingSubstitutionFormat3$1(action, tokens, index2) { + action.substitution.forEach(function(subst, offset) { + var token = tokens[index2 + offset]; + token.setState(action.tag, subst); + }); +} +function ligatureSubstitutionFormat1$1(action, tokens, index2) { + var token = tokens[index2]; + token.setState(action.tag, action.substitution.ligGlyph); + var compsCount = action.substitution.components.length; + for (var i = 0;i < compsCount; i++) { + token = tokens[index2 + i + 1]; + token.setState("deleted", true); + } +} +var SUBSTITUTIONS = { + 11: singleSubstitutionFormat1$1, + 12: singleSubstitutionFormat2$1, + 63: chainingSubstitutionFormat3$1, + 41: ligatureSubstitutionFormat1$1 +}; +function applySubstitution(action, tokens, index2) { + if (action instanceof SubstitutionAction && SUBSTITUTIONS[action.id]) { + SUBSTITUTIONS[action.id](action, tokens, index2); + } +} +function willConnectPrev(charContextParams) { + var backtrack = [].concat(charContextParams.backtrack); + for (var i = backtrack.length - 1;i >= 0; i--) { + var prevChar = backtrack[i]; + var isolated = isIsolatedArabicChar(prevChar); + var tashkeel = isTashkeelArabicChar(prevChar); + if (!isolated && !tashkeel) { + return true; + } + if (isolated) { + return false; + } + } + return false; +} +function willConnectNext(charContextParams) { + if (isIsolatedArabicChar(charContextParams.current)) { + return false; + } + for (var i = 0;i < charContextParams.lookahead.length; i++) { + var nextChar = charContextParams.lookahead[i]; + var tashkeel = isTashkeelArabicChar(nextChar); + if (!tashkeel) { + return true; + } + } + return false; +} +function arabicPresentationForms(range) { + var this$1 = this; + var script = "arab"; + var tags = this.featuresTags[script]; + var tokens = this.tokenizer.getRangeTokens(range); + if (tokens.length === 1) { + return; + } + var contextParams = new ContextParams(tokens.map(function(token) { + return token.getState("glyphIndex"); + }), 0); + var charContextParams = new ContextParams(tokens.map(function(token) { + return token.char; + }), 0); + tokens.forEach(function(token, index2) { + if (isTashkeelArabicChar(token.char)) { + return; + } + contextParams.setCurrentIndex(index2); + charContextParams.setCurrentIndex(index2); + var CONNECT = 0; + if (willConnectPrev(charContextParams)) { + CONNECT |= 1; + } + if (willConnectNext(charContextParams)) { + CONNECT |= 2; + } + var tag; + switch (CONNECT) { + case 1: + tag = "fina"; + break; + case 2: + tag = "init"; + break; + case 3: + tag = "medi"; + break; + } + if (tags.indexOf(tag) === -1) { + return; + } + var substitutions = this$1.query.lookupFeature({ + tag, + script, + contextParams + }); + if (substitutions instanceof Error) { + return console.info(substitutions.message); + } + substitutions.forEach(function(action, index3) { + if (action instanceof SubstitutionAction) { + applySubstitution(action, tokens, index3); + contextParams.context[index3] = action.substitution; + } + }); + }); +} +function getContextParams(tokens, index2) { + var context = tokens.map(function(token) { + return token.activeState.value; + }); + return new ContextParams(context, index2 || 0); +} +function arabicRequiredLigatures(range) { + var this$1 = this; + var script = "arab"; + var tokens = this.tokenizer.getRangeTokens(range); + var contextParams = getContextParams(tokens); + contextParams.context.forEach(function(glyphIndex, index2) { + contextParams.setCurrentIndex(index2); + var substitutions = this$1.query.lookupFeature({ + tag: "rlig", + script, + contextParams + }); + if (substitutions.length) { + substitutions.forEach(function(action) { + return applySubstitution(action, tokens, index2); + }); + contextParams = getContextParams(tokens); + } + }); +} +function latinWordStartCheck(contextParams) { + var char = contextParams.current; + var prevChar = contextParams.get(-1); + return prevChar === null && isLatinChar(char) || !isLatinChar(prevChar) && isLatinChar(char); +} +function latinWordEndCheck(contextParams) { + var nextChar = contextParams.get(1); + return nextChar === null || !isLatinChar(nextChar); +} +var latinWordCheck = { + startCheck: latinWordStartCheck, + endCheck: latinWordEndCheck +}; +function getContextParams$1(tokens, index2) { + var context = tokens.map(function(token) { + return token.activeState.value; + }); + return new ContextParams(context, index2 || 0); +} +function latinLigature(range) { + var this$1 = this; + var script = "latn"; + var tokens = this.tokenizer.getRangeTokens(range); + var contextParams = getContextParams$1(tokens); + contextParams.context.forEach(function(glyphIndex, index2) { + contextParams.setCurrentIndex(index2); + var substitutions = this$1.query.lookupFeature({ + tag: "liga", + script, + contextParams + }); + if (substitutions.length) { + substitutions.forEach(function(action) { + return applySubstitution(action, tokens, index2); + }); + contextParams = getContextParams$1(tokens); + } + }); +} +function Bidi(baseDir) { + this.baseDir = baseDir || "ltr"; + this.tokenizer = new Tokenizer; + this.featuresTags = {}; +} +Bidi.prototype.setText = function(text2) { + this.text = text2; +}; +Bidi.prototype.contextChecks = { + latinWordCheck, + arabicWordCheck, + arabicSentenceCheck +}; +function registerContextChecker(checkId) { + var check2 = this.contextChecks[checkId + "Check"]; + return this.tokenizer.registerContextChecker(checkId, check2.startCheck, check2.endCheck); +} +function tokenizeText() { + registerContextChecker.call(this, "latinWord"); + registerContextChecker.call(this, "arabicWord"); + registerContextChecker.call(this, "arabicSentence"); + return this.tokenizer.tokenize(this.text); +} +function reverseArabicSentences() { + var this$1 = this; + var ranges = this.tokenizer.getContextRanges("arabicSentence"); + ranges.forEach(function(range) { + var rangeTokens = this$1.tokenizer.getRangeTokens(range); + this$1.tokenizer.replaceRange(range.startIndex, range.endOffset, rangeTokens.reverse()); + }); +} +Bidi.prototype.registerFeatures = function(script, tags) { + var this$1 = this; + var supportedTags = tags.filter(function(tag) { + return this$1.query.supports({ script, tag }); + }); + if (!this.featuresTags.hasOwnProperty(script)) { + this.featuresTags[script] = supportedTags; + } else { + this.featuresTags[script] = this.featuresTags[script].concat(supportedTags); + } +}; +Bidi.prototype.applyFeatures = function(font, features) { + if (!font) { + throw new Error("No valid font was provided to apply features"); + } + if (!this.query) { + this.query = new FeatureQuery(font); + } + for (var f = 0;f < features.length; f++) { + var feature = features[f]; + if (!this.query.supports({ script: feature.script })) { + continue; + } + this.registerFeatures(feature.script, feature.tags); + } +}; +Bidi.prototype.registerModifier = function(modifierId, condition, modifier) { + this.tokenizer.registerModifier(modifierId, condition, modifier); +}; +function checkGlyphIndexStatus() { + if (this.tokenizer.registeredModifiers.indexOf("glyphIndex") === -1) { + throw new Error("glyphIndex modifier is required to apply " + "arabic presentation features."); + } +} +function applyArabicPresentationForms() { + var this$1 = this; + var script = "arab"; + if (!this.featuresTags.hasOwnProperty(script)) { + return; + } + checkGlyphIndexStatus.call(this); + var ranges = this.tokenizer.getContextRanges("arabicWord"); + ranges.forEach(function(range) { + arabicPresentationForms.call(this$1, range); + }); +} +function applyArabicRequireLigatures() { + var this$1 = this; + var script = "arab"; + if (!this.featuresTags.hasOwnProperty(script)) { + return; + } + var tags = this.featuresTags[script]; + if (tags.indexOf("rlig") === -1) { + return; + } + checkGlyphIndexStatus.call(this); + var ranges = this.tokenizer.getContextRanges("arabicWord"); + ranges.forEach(function(range) { + arabicRequiredLigatures.call(this$1, range); + }); +} +function applyLatinLigatures() { + var this$1 = this; + var script = "latn"; + if (!this.featuresTags.hasOwnProperty(script)) { + return; + } + var tags = this.featuresTags[script]; + if (tags.indexOf("liga") === -1) { + return; + } + checkGlyphIndexStatus.call(this); + var ranges = this.tokenizer.getContextRanges("latinWord"); + ranges.forEach(function(range) { + latinLigature.call(this$1, range); + }); +} +Bidi.prototype.checkContextReady = function(contextId) { + return !!this.tokenizer.getContext(contextId); +}; +Bidi.prototype.applyFeaturesToContexts = function() { + if (this.checkContextReady("arabicWord")) { + applyArabicPresentationForms.call(this); + applyArabicRequireLigatures.call(this); + } + if (this.checkContextReady("latinWord")) { + applyLatinLigatures.call(this); + } + if (this.checkContextReady("arabicSentence")) { + reverseArabicSentences.call(this); + } +}; +Bidi.prototype.processText = function(text2) { + if (!this.text || this.text !== text2) { + this.setText(text2); + tokenizeText.call(this); + this.applyFeaturesToContexts(); + } +}; +Bidi.prototype.getBidiText = function(text2) { + this.processText(text2); + return this.tokenizer.getText(); +}; +Bidi.prototype.getTextGlyphs = function(text2) { + this.processText(text2); + var indexes = []; + for (var i = 0;i < this.tokenizer.tokens.length; i++) { + var token = this.tokenizer.tokens[i]; + if (token.state.deleted) { + continue; + } + var index2 = token.activeState.value; + indexes.push(Array.isArray(index2) ? index2[0] : index2); + } + return indexes; +}; +function Font(options) { + options = options || {}; + options.tables = options.tables || {}; + if (!options.empty) { + checkArgument(options.familyName, "When creating a new Font object, familyName is required."); + checkArgument(options.styleName, "When creating a new Font object, styleName is required."); + checkArgument(options.unitsPerEm, "When creating a new Font object, unitsPerEm is required."); + checkArgument(options.ascender, "When creating a new Font object, ascender is required."); + checkArgument(options.descender <= 0, "When creating a new Font object, negative descender value is required."); + this.names = { + fontFamily: { en: options.familyName || " " }, + fontSubfamily: { en: options.styleName || " " }, + fullName: { en: options.fullName || options.familyName + " " + options.styleName }, + postScriptName: { en: options.postScriptName || (options.familyName + options.styleName).replace(/\s/g, "") }, + designer: { en: options.designer || " " }, + designerURL: { en: options.designerURL || " " }, + manufacturer: { en: options.manufacturer || " " }, + manufacturerURL: { en: options.manufacturerURL || " " }, + license: { en: options.license || " " }, + licenseURL: { en: options.licenseURL || " " }, + version: { en: options.version || "Version 0.1" }, + description: { en: options.description || " " }, + copyright: { en: options.copyright || " " }, + trademark: { en: options.trademark || " " } + }; + this.unitsPerEm = options.unitsPerEm || 1000; + this.ascender = options.ascender; + this.descender = options.descender; + this.createdTimestamp = options.createdTimestamp; + this.tables = Object.assign(options.tables, { + os2: Object.assign({ + usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM, + usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM, + fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR + }, options.tables.os2) + }); + } + this.supported = true; + this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []); + this.encoding = new DefaultEncoding(this); + this.position = new Position(this); + this.substitution = new Substitution(this); + this.tables = this.tables || {}; + this._push = null; + this._hmtxTableData = {}; + Object.defineProperty(this, "hinting", { + get: function() { + if (this._hinting) { + return this._hinting; + } + if (this.outlinesFormat === "truetype") { + return this._hinting = new Hinting(this); + } + } + }); +} +Font.prototype.hasChar = function(c) { + return this.encoding.charToGlyphIndex(c) !== null; +}; +Font.prototype.charToGlyphIndex = function(s) { + return this.encoding.charToGlyphIndex(s); +}; +Font.prototype.charToGlyph = function(c) { + var glyphIndex = this.charToGlyphIndex(c); + var glyph = this.glyphs.get(glyphIndex); + if (!glyph) { + glyph = this.glyphs.get(0); + } + return glyph; +}; +Font.prototype.updateFeatures = function(options) { + return this.defaultRenderOptions.features.map(function(feature) { + if (feature.script === "latn") { + return { + script: "latn", + tags: feature.tags.filter(function(tag) { + return options[tag]; + }) + }; + } else { + return feature; + } + }); +}; +Font.prototype.stringToGlyphs = function(s, options) { + var this$1 = this; + var bidi = new Bidi; + var charToGlyphIndexMod = function(token) { + return this$1.charToGlyphIndex(token.char); + }; + bidi.registerModifier("glyphIndex", null, charToGlyphIndexMod); + var features = options ? this.updateFeatures(options.features) : this.defaultRenderOptions.features; + bidi.applyFeatures(this, features); + var indexes = bidi.getTextGlyphs(s); + var length2 = indexes.length; + var glyphs = new Array(length2); + var notdef = this.glyphs.get(0); + for (var i = 0;i < length2; i += 1) { + glyphs[i] = this.glyphs.get(indexes[i]) || notdef; + } + return glyphs; +}; +Font.prototype.nameToGlyphIndex = function(name2) { + return this.glyphNames.nameToGlyphIndex(name2); +}; +Font.prototype.nameToGlyph = function(name2) { + var glyphIndex = this.nameToGlyphIndex(name2); + var glyph = this.glyphs.get(glyphIndex); + if (!glyph) { + glyph = this.glyphs.get(0); + } + return glyph; +}; +Font.prototype.glyphIndexToName = function(gid) { + if (!this.glyphNames.glyphIndexToName) { + return ""; + } + return this.glyphNames.glyphIndexToName(gid); +}; +Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) { + leftGlyph = leftGlyph.index || leftGlyph; + rightGlyph = rightGlyph.index || rightGlyph; + var gposKerning = this.position.defaultKerningTables; + if (gposKerning) { + return this.position.getKerningValue(gposKerning, leftGlyph, rightGlyph); + } + return this.kerningPairs[leftGlyph + "," + rightGlyph] || 0; +}; +Font.prototype.defaultRenderOptions = { + kerning: true, + features: [ + { script: "arab", tags: ["init", "medi", "fina", "rlig"] }, + { script: "latn", tags: ["liga", "rlig"] } + ] +}; +Font.prototype.forEachGlyph = function(text2, x2, y3, fontSize, options, callback) { + x2 = x2 !== undefined ? x2 : 0; + y3 = y3 !== undefined ? y3 : 0; + fontSize = fontSize !== undefined ? fontSize : 72; + options = Object.assign({}, this.defaultRenderOptions, options); + var fontScale = 1 / this.unitsPerEm * fontSize; + var glyphs = this.stringToGlyphs(text2, options); + var kerningLookups; + if (options.kerning) { + var script = options.script || this.position.getDefaultScriptName(); + kerningLookups = this.position.getKerningTables(script, options.language); + } + for (var i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs[i]; + callback.call(this, glyph, x2, y3, fontSize, options); + if (glyph.advanceWidth) { + x2 += glyph.advanceWidth * fontScale; + } + if (options.kerning && i < glyphs.length - 1) { + var kerningValue = kerningLookups ? this.position.getKerningValue(kerningLookups, glyph.index, glyphs[i + 1].index) : this.getKerningValue(glyph, glyphs[i + 1]); + x2 += kerningValue * fontScale; + } + if (options.letterSpacing) { + x2 += options.letterSpacing * fontSize; + } else if (options.tracking) { + x2 += options.tracking / 1000 * fontSize; + } + } + return x2; +}; +Font.prototype.getPath = function(text2, x2, y3, fontSize, options) { + var fullPath = new Path2; + this.forEachGlyph(text2, x2, y3, fontSize, options, function(glyph, gX, gY, gFontSize) { + var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); + fullPath.extend(glyphPath); + }); + return fullPath; +}; +Font.prototype.getPaths = function(text2, x2, y3, fontSize, options) { + var glyphPaths = []; + this.forEachGlyph(text2, x2, y3, fontSize, options, function(glyph, gX, gY, gFontSize) { + var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); + glyphPaths.push(glyphPath); + }); + return glyphPaths; +}; +Font.prototype.getAdvanceWidth = function(text2, fontSize, options) { + return this.forEachGlyph(text2, 0, 0, fontSize, options, function() { + }); +}; +Font.prototype.draw = function(ctx, text2, x2, y3, fontSize, options) { + this.getPath(text2, x2, y3, fontSize, options).draw(ctx); +}; +Font.prototype.drawPoints = function(ctx, text2, x2, y3, fontSize, options) { + this.forEachGlyph(text2, x2, y3, fontSize, options, function(glyph, gX, gY, gFontSize) { + glyph.drawPoints(ctx, gX, gY, gFontSize); + }); +}; +Font.prototype.drawMetrics = function(ctx, text2, x2, y3, fontSize, options) { + this.forEachGlyph(text2, x2, y3, fontSize, options, function(glyph, gX, gY, gFontSize) { + glyph.drawMetrics(ctx, gX, gY, gFontSize); + }); +}; +Font.prototype.getEnglishName = function(name2) { + var translations = this.names[name2]; + if (translations) { + return translations.en; + } +}; +Font.prototype.validate = function() { + var _this = this; + function assert(predicate, message) { + } + function assertNamePresent(name2) { + var englishName = _this.getEnglishName(name2); + assert(englishName && englishName.trim().length > 0); + } + assertNamePresent("fontFamily"); + assertNamePresent("weightName"); + assertNamePresent("manufacturer"); + assertNamePresent("copyright"); + assertNamePresent("version"); + assert(this.unitsPerEm > 0); +}; +Font.prototype.toTables = function() { + return sfnt.fontToTable(this); +}; +Font.prototype.toBuffer = function() { + console.warn("Font.toBuffer is deprecated. Use Font.toArrayBuffer instead."); + return this.toArrayBuffer(); +}; +Font.prototype.toArrayBuffer = function() { + var sfntTable = this.toTables(); + var bytes = sfntTable.encode(); + var buffer = new ArrayBuffer(bytes.length); + var intArray = new Uint8Array(buffer); + for (var i = 0;i < bytes.length; i++) { + intArray[i] = bytes[i]; + } + return buffer; +}; +Font.prototype.download = function(fileName) { + var familyName = this.getEnglishName("fontFamily"); + var styleName = this.getEnglishName("fontSubfamily"); + fileName = fileName || familyName.replace(/\s/g, "") + "-" + styleName + ".otf"; + var arrayBuffer = this.toArrayBuffer(); + window.URL = window.URL || window.webkitURL; + if (window.URL) { + var dataView = new DataView(arrayBuffer); + var blob = new Blob([dataView], { type: "font/opentype" }); + var link = document.createElement("a"); + link.href = window.URL.createObjectURL(blob); + link.download = fileName; + var event = document.createEvent("MouseEvents"); + event.initEvent("click", true, false); + link.dispatchEvent(event); + } else { + console.warn("Font file could not be downloaded. Try using a different browser."); + } +}; +Font.prototype.fsSelectionValues = { + ITALIC: 1, + UNDERSCORE: 2, + NEGATIVE: 4, + OUTLINED: 8, + STRIKEOUT: 16, + BOLD: 32, + REGULAR: 64, + USER_TYPO_METRICS: 128, + WWS: 256, + OBLIQUE: 512 +}; +Font.prototype.usWidthClasses = { + ULTRA_CONDENSED: 1, + EXTRA_CONDENSED: 2, + CONDENSED: 3, + SEMI_CONDENSED: 4, + MEDIUM: 5, + SEMI_EXPANDED: 6, + EXPANDED: 7, + EXTRA_EXPANDED: 8, + ULTRA_EXPANDED: 9 +}; +Font.prototype.usWeightClasses = { + THIN: 100, + EXTRA_LIGHT: 200, + LIGHT: 300, + NORMAL: 400, + MEDIUM: 500, + SEMI_BOLD: 600, + BOLD: 700, + EXTRA_BOLD: 800, + BLACK: 900 +}; +var subtableParsers$1 = new Array(10); +subtableParsers$1[1] = function parseLookup12() { + var start = this.offset + this.relativeOffset; + var posformat = this.parseUShort(); + if (posformat === 1) { + return { + posFormat: 1, + coverage: this.parsePointer(Parser.coverage), + value: this.parseValueRecord() + }; + } else if (posformat === 2) { + return { + posFormat: 2, + coverage: this.parsePointer(Parser.coverage), + values: this.parseValueRecordList() + }; + } + check.assert(false, "0x" + start.toString(16) + ": GPOS lookup type 1 format must be 1 or 2."); +}; +subtableParsers$1[2] = function parseLookup22() { + var start = this.offset + this.relativeOffset; + var posFormat = this.parseUShort(); + check.assert(posFormat === 1 || posFormat === 2, "0x" + start.toString(16) + ": GPOS lookup type 2 format must be 1 or 2."); + var coverage = this.parsePointer(Parser.coverage); + var valueFormat1 = this.parseUShort(); + var valueFormat2 = this.parseUShort(); + if (posFormat === 1) { + return { + posFormat, + coverage, + valueFormat1, + valueFormat2, + pairSets: this.parseList(Parser.pointer(Parser.list(function() { + return { + secondGlyph: this.parseUShort(), + value1: this.parseValueRecord(valueFormat1), + value2: this.parseValueRecord(valueFormat2) + }; + }))) + }; + } else if (posFormat === 2) { + var classDef1 = this.parsePointer(Parser.classDef); + var classDef2 = this.parsePointer(Parser.classDef); + var class1Count = this.parseUShort(); + var class2Count = this.parseUShort(); + return { + posFormat, + coverage, + valueFormat1, + valueFormat2, + classDef1, + classDef2, + class1Count, + class2Count, + classRecords: this.parseList(class1Count, Parser.list(class2Count, function() { + return { + value1: this.parseValueRecord(valueFormat1), + value2: this.parseValueRecord(valueFormat2) + }; + })) + }; + } +}; +subtableParsers$1[3] = function parseLookup32() { + return { error: "GPOS Lookup 3 not supported" }; +}; +subtableParsers$1[4] = function parseLookup42() { + return { error: "GPOS Lookup 4 not supported" }; +}; +subtableParsers$1[5] = function parseLookup52() { + return { error: "GPOS Lookup 5 not supported" }; +}; +subtableParsers$1[6] = function parseLookup62() { + return { error: "GPOS Lookup 6 not supported" }; +}; +subtableParsers$1[7] = function parseLookup72() { + return { error: "GPOS Lookup 7 not supported" }; +}; +subtableParsers$1[8] = function parseLookup82() { + return { error: "GPOS Lookup 8 not supported" }; +}; +subtableParsers$1[9] = function parseLookup9() { + return { error: "GPOS Lookup 9 not supported" }; +}; +var subtableMakers$1 = new Array(10); +// node_modules/three/examples/jsm/libs/chevrotain.module.min.js +/*! chevrotain - v9.0.1 */ +var R2 = (t4, e) => () => (e || (e = { exports: {} }, t4(e.exports, e)), e.exports); +var Er2 = R2((Pt) => { + Object.defineProperty(Pt, "__esModule", { value: true }); + Pt.VERSION = undefined; + Pt.VERSION = "9.0.1"; +}); +var k2 = R2((exports, module) => { + var __spreadArray = exports && exports.__spreadArray || function(t4, e) { + for (var r = 0, n2 = e.length, i = t4.length;r < n2; r++, i++) + t4[i] = e[r]; + return t4; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toFastProperties = exports.timer = exports.peek = exports.isES2015MapSupported = exports.PRINT_WARNING = exports.PRINT_ERROR = exports.packArray = exports.IDENTITY = exports.NOOP = exports.merge = exports.groupBy = exports.defaults = exports.assignNoOverwrite = exports.assign = exports.zipObject = exports.sortBy = exports.indexOf = exports.some = exports.difference = exports.every = exports.isObject = exports.isRegExp = exports.isArray = exports.partial = exports.uniq = exports.compact = exports.reduce = exports.findAll = exports.find = exports.cloneObj = exports.cloneArr = exports.contains = exports.has = exports.pick = exports.reject = exports.filter = exports.dropRight = exports.drop = exports.isFunction = exports.isUndefined = exports.isString = exports.forEach = exports.last = exports.first = exports.flatten = exports.map = exports.mapValues = exports.values = exports.keys = exports.isEmpty = undefined; + function isEmpty(t4) { + return t4 && t4.length === 0; + } + exports.isEmpty = isEmpty; + function keys(t4) { + return t4 == null ? [] : Object.keys(t4); + } + exports.keys = keys; + function values(t4) { + for (var e = [], r = Object.keys(t4), n2 = 0;n2 < r.length; n2++) + e.push(t4[r[n2]]); + return e; + } + exports.values = values; + function mapValues(t4, e) { + for (var r = [], n2 = keys(t4), i = 0;i < n2.length; i++) { + var a = n2[i]; + r.push(e.call(null, t4[a], a)); + } + return r; + } + exports.mapValues = mapValues; + function map(t4, e) { + for (var r = [], n2 = 0;n2 < t4.length; n2++) + r.push(e.call(null, t4[n2], n2)); + return r; + } + exports.map = map; + function flatten(t4) { + for (var e = [], r = 0;r < t4.length; r++) { + var n2 = t4[r]; + Array.isArray(n2) ? e = e.concat(flatten(n2)) : e.push(n2); + } + return e; + } + exports.flatten = flatten; + function first(t4) { + return isEmpty(t4) ? undefined : t4[0]; + } + exports.first = first; + function last(t4) { + var e = t4 && t4.length; + return e ? t4[e - 1] : undefined; + } + exports.last = last; + function forEach(t4, e) { + if (Array.isArray(t4)) + for (var r = 0;r < t4.length; r++) + e.call(null, t4[r], r); + else if (isObject(t4)) + for (var n2 = keys(t4), r = 0;r < n2.length; r++) { + var i = n2[r], a = t4[i]; + e.call(null, a, i); + } + else + throw Error("non exhaustive match"); + } + exports.forEach = forEach; + function isString(t4) { + return typeof t4 == "string"; + } + exports.isString = isString; + function isUndefined(t4) { + return t4 === undefined; + } + exports.isUndefined = isUndefined; + function isFunction(t4) { + return t4 instanceof Function; + } + exports.isFunction = isFunction; + function drop(t4, e) { + return e === undefined && (e = 1), t4.slice(e, t4.length); + } + exports.drop = drop; + function dropRight(t4, e) { + return e === undefined && (e = 1), t4.slice(0, t4.length - e); + } + exports.dropRight = dropRight; + function filter(t4, e) { + var r = []; + if (Array.isArray(t4)) + for (var n2 = 0;n2 < t4.length; n2++) { + var i = t4[n2]; + e.call(null, i) && r.push(i); + } + return r; + } + exports.filter = filter; + function reject(t4, e) { + return filter(t4, function(r) { + return !e(r); + }); + } + exports.reject = reject; + function pick(t4, e) { + for (var r = Object.keys(t4), n2 = {}, i = 0;i < r.length; i++) { + var a = r[i], o = t4[a]; + e(o) && (n2[a] = o); + } + return n2; + } + exports.pick = pick; + function has(t4, e) { + return isObject(t4) ? t4.hasOwnProperty(e) : false; + } + exports.has = has; + function contains(t4, e) { + return find(t4, function(r) { + return r === e; + }) !== undefined; + } + exports.contains = contains; + function cloneArr(t4) { + for (var e = [], r = 0;r < t4.length; r++) + e.push(t4[r]); + return e; + } + exports.cloneArr = cloneArr; + function cloneObj(t4) { + var e = {}; + for (var r in t4) + Object.prototype.hasOwnProperty.call(t4, r) && (e[r] = t4[r]); + return e; + } + exports.cloneObj = cloneObj; + function find(t4, e) { + for (var r = 0;r < t4.length; r++) { + var n2 = t4[r]; + if (e.call(null, n2)) + return n2; + } + } + exports.find = find; + function findAll(t4, e) { + for (var r = [], n2 = 0;n2 < t4.length; n2++) { + var i = t4[n2]; + e.call(null, i) && r.push(i); + } + return r; + } + exports.findAll = findAll; + function reduce(t4, e, r) { + for (var n2 = Array.isArray(t4), i = n2 ? t4 : values(t4), a = n2 ? [] : keys(t4), o = r, s = 0;s < i.length; s++) + o = e.call(null, o, i[s], n2 ? s : a[s]); + return o; + } + exports.reduce = reduce; + function compact(t4) { + return reject(t4, function(e) { + return e == null; + }); + } + exports.compact = compact; + function uniq(t4, e) { + e === undefined && (e = function(n2) { + return n2; + }); + var r = []; + return reduce(t4, function(n2, i) { + var a = e(i); + return contains(r, a) ? n2 : (r.push(a), n2.concat(i)); + }, []); + } + exports.uniq = uniq; + function partial(t4) { + for (var e = [], r = 1;r < arguments.length; r++) + e[r - 1] = arguments[r]; + var n2 = [null], i = n2.concat(e); + return Function.bind.apply(t4, i); + } + exports.partial = partial; + function isArray(t4) { + return Array.isArray(t4); + } + exports.isArray = isArray; + function isRegExp(t4) { + return t4 instanceof RegExp; + } + exports.isRegExp = isRegExp; + function isObject(t4) { + return t4 instanceof Object; + } + exports.isObject = isObject; + function every(t4, e) { + for (var r = 0;r < t4.length; r++) + if (!e(t4[r], r)) + return false; + return true; + } + exports.every = every; + function difference(t4, e) { + return reject(t4, function(r) { + return contains(e, r); + }); + } + exports.difference = difference; + function some(t4, e) { + for (var r = 0;r < t4.length; r++) + if (e(t4[r])) + return true; + return false; + } + exports.some = some; + function indexOf(t4, e) { + for (var r = 0;r < t4.length; r++) + if (t4[r] === e) + return r; + return -1; + } + exports.indexOf = indexOf; + function sortBy(t4, e) { + var r = cloneArr(t4); + return r.sort(function(n2, i) { + return e(n2) - e(i); + }), r; + } + exports.sortBy = sortBy; + function zipObject(t4, e) { + if (t4.length !== e.length) + throw Error("can't zipObject with different number of keys and values!"); + for (var r = {}, n2 = 0;n2 < t4.length; n2++) + r[t4[n2]] = e[n2]; + return r; + } + exports.zipObject = zipObject; + function assign(t4) { + for (var e = [], r = 1;r < arguments.length; r++) + e[r - 1] = arguments[r]; + for (var n2 = 0;n2 < e.length; n2++) + for (var i = e[n2], a = keys(i), o = 0;o < a.length; o++) { + var s = a[o]; + t4[s] = i[s]; + } + return t4; + } + exports.assign = assign; + function assignNoOverwrite(t4) { + for (var e = [], r = 1;r < arguments.length; r++) + e[r - 1] = arguments[r]; + for (var n2 = 0;n2 < e.length; n2++) + for (var i = e[n2], a = keys(i), o = 0;o < a.length; o++) { + var s = a[o]; + has(t4, s) || (t4[s] = i[s]); + } + return t4; + } + exports.assignNoOverwrite = assignNoOverwrite; + function defaults() { + for (var t4 = [], e = 0;e < arguments.length; e++) + t4[e] = arguments[e]; + return assignNoOverwrite.apply(undefined, __spreadArray([{}], t4)); + } + exports.defaults = defaults; + function groupBy(t4, e) { + var r = {}; + return forEach(t4, function(n2) { + var i = e(n2), a = r[i]; + a ? a.push(n2) : r[i] = [n2]; + }), r; + } + exports.groupBy = groupBy; + function merge(t4, e) { + for (var r = cloneObj(t4), n2 = keys(e), i = 0;i < n2.length; i++) { + var a = n2[i], o = e[a]; + r[a] = o; + } + return r; + } + exports.merge = merge; + function NOOP() { + } + exports.NOOP = NOOP; + function IDENTITY(t4) { + return t4; + } + exports.IDENTITY = IDENTITY; + function packArray(t4) { + for (var e = [], r = 0;r < t4.length; r++) { + var n2 = t4[r]; + e.push(n2 !== undefined ? n2 : undefined); + } + return e; + } + exports.packArray = packArray; + function PRINT_ERROR(t4) { + console && console.error && console.error("Error: " + t4); + } + exports.PRINT_ERROR = PRINT_ERROR; + function PRINT_WARNING(t4) { + console && console.warn && console.warn("Warning: " + t4); + } + exports.PRINT_WARNING = PRINT_WARNING; + function isES2015MapSupported() { + return typeof Map == "function"; + } + exports.isES2015MapSupported = isES2015MapSupported; + function peek(t4) { + return t4[t4.length - 1]; + } + exports.peek = peek; + function timer(t4) { + var e = new Date().getTime(), r = t4(), n2 = new Date().getTime(), i = n2 - e; + return { time: i, value: r }; + } + exports.timer = timer; + function toFastProperties(toBecomeFast) { + function FakeConstructor() { + } + FakeConstructor.prototype = toBecomeFast; + var fakeInstance = new FakeConstructor; + function fakeAccess() { + return typeof fakeInstance.bar; + } + return fakeAccess(), fakeAccess(), toBecomeFast; + eval(toBecomeFast); + } + exports.toFastProperties = toFastProperties; +}); +var xt3 = R2((sn2, St) => { + (function(t4, e) { + typeof define == "function" && define.amd ? define([], e) : typeof St == "object" && St.exports ? St.exports = e() : t4.regexpToAst = e(); + })(typeof self != "undefined" ? self : sn2, function() { + function t4() { + } + t4.prototype.saveState = function() { + return { idx: this.idx, input: this.input, groupIdx: this.groupIdx }; + }, t4.prototype.restoreState = function(u3) { + this.idx = u3.idx, this.input = u3.input, this.groupIdx = u3.groupIdx; + }, t4.prototype.pattern = function(u3) { + this.idx = 0, this.input = u3, this.groupIdx = 0, this.consumeChar("/"); + var d = this.disjunction(); + this.consumeChar("/"); + for (var A4 = { type: "Flags", loc: { begin: this.idx, end: u3.length }, global: false, ignoreCase: false, multiLine: false, unicode: false, sticky: false };this.isRegExpFlag(); ) + switch (this.popChar()) { + case "g": + o(A4, "global"); + break; + case "i": + o(A4, "ignoreCase"); + break; + case "m": + o(A4, "multiLine"); + break; + case "u": + o(A4, "unicode"); + break; + case "y": + o(A4, "sticky"); + break; + } + if (this.idx !== this.input.length) + throw Error("Redundant input: " + this.input.substring(this.idx)); + return { type: "Pattern", flags: A4, value: d, loc: this.loc(0) }; + }, t4.prototype.disjunction = function() { + var u3 = [], d = this.idx; + for (u3.push(this.alternative());this.peekChar() === "|"; ) + this.consumeChar("|"), u3.push(this.alternative()); + return { type: "Disjunction", value: u3, loc: this.loc(d) }; + }, t4.prototype.alternative = function() { + for (var u3 = [], d = this.idx;this.isTerm(); ) + u3.push(this.term()); + return { type: "Alternative", value: u3, loc: this.loc(d) }; + }, t4.prototype.term = function() { + return this.isAssertion() ? this.assertion() : this.atom(); + }, t4.prototype.assertion = function() { + var u3 = this.idx; + switch (this.popChar()) { + case "^": + return { type: "StartAnchor", loc: this.loc(u3) }; + case "$": + return { type: "EndAnchor", loc: this.loc(u3) }; + case "\\": + switch (this.popChar()) { + case "b": + return { type: "WordBoundary", loc: this.loc(u3) }; + case "B": + return { type: "NonWordBoundary", loc: this.loc(u3) }; + } + throw Error("Invalid Assertion Escape"); + case "(": + this.consumeChar("?"); + var d; + switch (this.popChar()) { + case "=": + d = "Lookahead"; + break; + case "!": + d = "NegativeLookahead"; + break; + } + s(d); + var A4 = this.disjunction(); + return this.consumeChar(")"), { type: d, value: A4, loc: this.loc(u3) }; + } + c(); + }, t4.prototype.quantifier = function(u3) { + var d, A4 = this.idx; + switch (this.popChar()) { + case "*": + d = { atLeast: 0, atMost: Infinity }; + break; + case "+": + d = { atLeast: 1, atMost: Infinity }; + break; + case "?": + d = { atLeast: 0, atMost: 1 }; + break; + case "{": + var _9 = this.integerIncludingZero(); + switch (this.popChar()) { + case "}": + d = { atLeast: _9, atMost: _9 }; + break; + case ",": + var g3; + this.isDigit() ? (g3 = this.integerIncludingZero(), d = { atLeast: _9, atMost: g3 }) : d = { atLeast: _9, atMost: Infinity }, this.consumeChar("}"); + break; + } + if (u3 === true && d === undefined) + return; + s(d); + break; + } + if (!(u3 === true && d === undefined)) + return s(d), this.peekChar(0) === "?" ? (this.consumeChar("?"), d.greedy = false) : d.greedy = true, d.type = "Quantifier", d.loc = this.loc(A4), d; + }, t4.prototype.atom = function() { + var u3, d = this.idx; + switch (this.peekChar()) { + case ".": + u3 = this.dotAll(); + break; + case "\\": + u3 = this.atomEscape(); + break; + case "[": + u3 = this.characterClass(); + break; + case "(": + u3 = this.group(); + break; + } + return u3 === undefined && this.isPatternCharacter() && (u3 = this.patternCharacter()), s(u3), u3.loc = this.loc(d), this.isQuantifier() && (u3.quantifier = this.quantifier()), u3; + }, t4.prototype.dotAll = function() { + return this.consumeChar("."), { type: "Set", complement: true, value: [i(` +`), i("\r"), i("\u2028"), i("\u2029")] }; + }, t4.prototype.atomEscape = function() { + switch (this.consumeChar("\\"), this.peekChar()) { + case "1": + case "2": + case "3": + case "4": + case "5": + case "6": + case "7": + case "8": + case "9": + return this.decimalEscapeAtom(); + case "d": + case "D": + case "s": + case "S": + case "w": + case "W": + return this.characterClassEscape(); + case "f": + case "n": + case "r": + case "t": + case "v": + return this.controlEscapeAtom(); + case "c": + return this.controlLetterEscapeAtom(); + case "0": + return this.nulCharacterAtom(); + case "x": + return this.hexEscapeSequenceAtom(); + case "u": + return this.regExpUnicodeEscapeSequenceAtom(); + default: + return this.identityEscapeAtom(); + } + }, t4.prototype.decimalEscapeAtom = function() { + var u3 = this.positiveInteger(); + return { type: "GroupBackReference", value: u3 }; + }, t4.prototype.characterClassEscape = function() { + var u3, d = false; + switch (this.popChar()) { + case "d": + u3 = p; + break; + case "D": + u3 = p, d = true; + break; + case "s": + u3 = m; + break; + case "S": + u3 = m, d = true; + break; + case "w": + u3 = l2; + break; + case "W": + u3 = l2, d = true; + break; + } + return s(u3), { type: "Set", value: u3, complement: d }; + }, t4.prototype.controlEscapeAtom = function() { + var u3; + switch (this.popChar()) { + case "f": + u3 = i("\f"); + break; + case "n": + u3 = i(` +`); + break; + case "r": + u3 = i("\r"); + break; + case "t": + u3 = i("\t"); + break; + case "v": + u3 = i("\v"); + break; + } + return s(u3), { type: "Character", value: u3 }; + }, t4.prototype.controlLetterEscapeAtom = function() { + this.consumeChar("c"); + var u3 = this.popChar(); + if (/[a-zA-Z]/.test(u3) === false) + throw Error("Invalid "); + var d = u3.toUpperCase().charCodeAt(0) - 64; + return { type: "Character", value: d }; + }, t4.prototype.nulCharacterAtom = function() { + return this.consumeChar("0"), { type: "Character", value: i("\x00") }; + }, t4.prototype.hexEscapeSequenceAtom = function() { + return this.consumeChar("x"), this.parseHexDigits(2); + }, t4.prototype.regExpUnicodeEscapeSequenceAtom = function() { + return this.consumeChar("u"), this.parseHexDigits(4); + }, t4.prototype.identityEscapeAtom = function() { + var u3 = this.popChar(); + return { type: "Character", value: i(u3) }; + }, t4.prototype.classPatternCharacterAtom = function() { + switch (this.peekChar()) { + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + case "\\": + case "]": + throw Error("TBD"); + default: + var u3 = this.popChar(); + return { type: "Character", value: i(u3) }; + } + }, t4.prototype.characterClass = function() { + var u3 = [], d = false; + for (this.consumeChar("["), this.peekChar(0) === "^" && (this.consumeChar("^"), d = true);this.isClassAtom(); ) { + var A4 = this.classAtom(), _9 = A4.type === "Character"; + if (_9 && this.isRangeDash()) { + this.consumeChar("-"); + var g3 = this.classAtom(), y3 = g3.type === "Character"; + if (y3) { + if (g3.value < A4.value) + throw Error("Range out of order in character class"); + u3.push({ from: A4.value, to: g3.value }); + } else + a(A4.value, u3), u3.push(i("-")), a(g3.value, u3); + } else + a(A4.value, u3); + } + return this.consumeChar("]"), { type: "Set", complement: d, value: u3 }; + }, t4.prototype.classAtom = function() { + switch (this.peekChar()) { + case "]": + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + throw Error("TBD"); + case "\\": + return this.classEscape(); + default: + return this.classPatternCharacterAtom(); + } + }, t4.prototype.classEscape = function() { + switch (this.consumeChar("\\"), this.peekChar()) { + case "b": + return this.consumeChar("b"), { type: "Character", value: i("\b") }; + case "d": + case "D": + case "s": + case "S": + case "w": + case "W": + return this.characterClassEscape(); + case "f": + case "n": + case "r": + case "t": + case "v": + return this.controlEscapeAtom(); + case "c": + return this.controlLetterEscapeAtom(); + case "0": + return this.nulCharacterAtom(); + case "x": + return this.hexEscapeSequenceAtom(); + case "u": + return this.regExpUnicodeEscapeSequenceAtom(); + default: + return this.identityEscapeAtom(); + } + }, t4.prototype.group = function() { + var u3 = true; + switch (this.consumeChar("("), this.peekChar(0)) { + case "?": + this.consumeChar("?"), this.consumeChar(":"), u3 = false; + break; + default: + this.groupIdx++; + break; + } + var d = this.disjunction(); + this.consumeChar(")"); + var A4 = { type: "Group", capturing: u3, value: d }; + return u3 && (A4.idx = this.groupIdx), A4; + }, t4.prototype.positiveInteger = function() { + var u3 = this.popChar(); + if (n2.test(u3) === false) + throw Error("Expecting a positive integer"); + for (;r.test(this.peekChar(0)); ) + u3 += this.popChar(); + return parseInt(u3, 10); + }, t4.prototype.integerIncludingZero = function() { + var u3 = this.popChar(); + if (r.test(u3) === false) + throw Error("Expecting an integer"); + for (;r.test(this.peekChar(0)); ) + u3 += this.popChar(); + return parseInt(u3, 10); + }, t4.prototype.patternCharacter = function() { + var u3 = this.popChar(); + switch (u3) { + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + case "^": + case "$": + case "\\": + case ".": + case "*": + case "+": + case "?": + case "(": + case ")": + case "[": + case "|": + throw Error("TBD"); + default: + return { type: "Character", value: i(u3) }; + } + }, t4.prototype.isRegExpFlag = function() { + switch (this.peekChar(0)) { + case "g": + case "i": + case "m": + case "u": + case "y": + return true; + default: + return false; + } + }, t4.prototype.isRangeDash = function() { + return this.peekChar() === "-" && this.isClassAtom(1); + }, t4.prototype.isDigit = function() { + return r.test(this.peekChar(0)); + }, t4.prototype.isClassAtom = function(u3) { + switch (u3 === undefined && (u3 = 0), this.peekChar(u3)) { + case "]": + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + return false; + default: + return true; + } + }, t4.prototype.isTerm = function() { + return this.isAtom() || this.isAssertion(); + }, t4.prototype.isAtom = function() { + if (this.isPatternCharacter()) + return true; + switch (this.peekChar(0)) { + case ".": + case "\\": + case "[": + case "(": + return true; + default: + return false; + } + }, t4.prototype.isAssertion = function() { + switch (this.peekChar(0)) { + case "^": + case "$": + return true; + case "\\": + switch (this.peekChar(1)) { + case "b": + case "B": + return true; + default: + return false; + } + case "(": + return this.peekChar(1) === "?" && (this.peekChar(2) === "=" || this.peekChar(2) === "!"); + default: + return false; + } + }, t4.prototype.isQuantifier = function() { + var u3 = this.saveState(); + try { + return this.quantifier(true) !== undefined; + } catch (d) { + return false; + } finally { + this.restoreState(u3); + } + }, t4.prototype.isPatternCharacter = function() { + switch (this.peekChar()) { + case "^": + case "$": + case "\\": + case ".": + case "*": + case "+": + case "?": + case "(": + case ")": + case "[": + case "|": + case "/": + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + return false; + default: + return true; + } + }, t4.prototype.parseHexDigits = function(u3) { + for (var d = "", A4 = 0;A4 < u3; A4++) { + var _9 = this.popChar(); + if (e.test(_9) === false) + throw Error("Expecting a HexDecimal digits"); + d += _9; + } + var g3 = parseInt(d, 16); + return { type: "Character", value: g3 }; + }, t4.prototype.peekChar = function(u3) { + return u3 === undefined && (u3 = 0), this.input[this.idx + u3]; + }, t4.prototype.popChar = function() { + var u3 = this.peekChar(0); + return this.consumeChar(), u3; + }, t4.prototype.consumeChar = function(u3) { + if (u3 !== undefined && this.input[this.idx] !== u3) + throw Error("Expected: '" + u3 + "' but found: '" + this.input[this.idx] + "' at offset: " + this.idx); + if (this.idx >= this.input.length) + throw Error("Unexpected end of input"); + this.idx++; + }, t4.prototype.loc = function(u3) { + return { begin: u3, end: this.idx }; + }; + var e = /[0-9a-fA-F]/, r = /[0-9]/, n2 = /[1-9]/; + function i(u3) { + return u3.charCodeAt(0); + } + function a(u3, d) { + u3.length !== undefined ? u3.forEach(function(A4) { + d.push(A4); + }) : d.push(u3); + } + function o(u3, d) { + if (u3[d] === true) + throw "duplicate flag " + d; + u3[d] = true; + } + function s(u3) { + if (u3 === undefined) + throw Error("Internal Error - Should never get here!"); + } + function c() { + throw Error("Internal Error - Should never get here!"); + } + var f, p = []; + for (f = i("0");f <= i("9"); f++) + p.push(f); + var l2 = [i("_")].concat(p); + for (f = i("a");f <= i("z"); f++) + l2.push(f); + for (f = i("A");f <= i("Z"); f++) + l2.push(f); + var m = [i(" "), i("\f"), i(` +`), i("\r"), i("\t"), i("\v"), i("\t"), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i("\u2028"), i("\u2029"), i(" "), i(" "), i(" "), i("\uFEFF")]; + function v() { + } + return v.prototype.visitChildren = function(u3) { + for (var d in u3) { + var A4 = u3[d]; + u3.hasOwnProperty(d) && (A4.type !== undefined ? this.visit(A4) : Array.isArray(A4) && A4.forEach(function(_9) { + this.visit(_9); + }, this)); + } + }, v.prototype.visit = function(u3) { + switch (u3.type) { + case "Pattern": + this.visitPattern(u3); + break; + case "Flags": + this.visitFlags(u3); + break; + case "Disjunction": + this.visitDisjunction(u3); + break; + case "Alternative": + this.visitAlternative(u3); + break; + case "StartAnchor": + this.visitStartAnchor(u3); + break; + case "EndAnchor": + this.visitEndAnchor(u3); + break; + case "WordBoundary": + this.visitWordBoundary(u3); + break; + case "NonWordBoundary": + this.visitNonWordBoundary(u3); + break; + case "Lookahead": + this.visitLookahead(u3); + break; + case "NegativeLookahead": + this.visitNegativeLookahead(u3); + break; + case "Character": + this.visitCharacter(u3); + break; + case "Set": + this.visitSet(u3); + break; + case "Group": + this.visitGroup(u3); + break; + case "GroupBackReference": + this.visitGroupBackReference(u3); + break; + case "Quantifier": + this.visitQuantifier(u3); + break; + } + this.visitChildren(u3); + }, v.prototype.visitPattern = function(u3) { + }, v.prototype.visitFlags = function(u3) { + }, v.prototype.visitDisjunction = function(u3) { + }, v.prototype.visitAlternative = function(u3) { + }, v.prototype.visitStartAnchor = function(u3) { + }, v.prototype.visitEndAnchor = function(u3) { + }, v.prototype.visitWordBoundary = function(u3) { + }, v.prototype.visitNonWordBoundary = function(u3) { + }, v.prototype.visitLookahead = function(u3) { + }, v.prototype.visitNegativeLookahead = function(u3) { + }, v.prototype.visitCharacter = function(u3) { + }, v.prototype.visitSet = function(u3) { + }, v.prototype.visitGroup = function(u3) { + }, v.prototype.visitGroupBackReference = function(u3) { + }, v.prototype.visitQuantifier = function(u3) { + }, { RegExpParser: t4, BaseRegExpVisitor: v, VERSION: "0.5.0" }; + }); +}); +var Lt = R2((He2) => { + Object.defineProperty(He2, "__esModule", { value: true }); + He2.clearRegExpParserCache = He2.getRegExpAst = undefined; + var Ga2 = xt3(), Ct2 = {}, Wa = new Ga2.RegExpParser; + function Ba2(t4) { + var e = t4.toString(); + if (Ct2.hasOwnProperty(e)) + return Ct2[e]; + var r = Wa.pattern(e); + return Ct2[e] = r, r; + } + He2.getRegExpAst = Ba2; + function qa() { + Ct2 = {}; + } + He2.clearRegExpParserCache = qa; +}); +var pn2 = R2((re) => { + var ja = re && re.__extends || function() { + var t4 = function(e, r) { + return t4 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t4(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t4(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(re, "__esModule", { value: true }); + re.canMatchCharCode = re.firstCharOptimizedIndices = re.getOptimizedStartCodesIndices = re.failedOptimizationPrefixMsg = undefined; + var un = xt3(), pe2 = k2(), cn = Lt(), Ce = Tr(), ln = "Complement Sets are not supported for first char optimization"; + re.failedOptimizationPrefixMsg = `Unable to use "first char" lexer optimizations: +`; + function Va(t4, e) { + e === undefined && (e = false); + try { + var r = cn.getRegExpAst(t4), n2 = Mt(r.value, {}, r.flags.ignoreCase); + return n2; + } catch (a) { + if (a.message === ln) + e && pe2.PRINT_WARNING("" + re.failedOptimizationPrefixMsg + ("\tUnable to optimize: < " + t4.toString() + ` > +`) + ` Complement Sets cannot be automatically optimized. + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`); + else { + var i = ""; + e && (i = ` + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`), pe2.PRINT_ERROR(re.failedOptimizationPrefixMsg + ` +` + ("\tFailed parsing: < " + t4.toString() + ` > +`) + ("\tUsing the regexp-to-ast library version: " + un.VERSION + ` +`) + "\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues" + i); + } + } + return []; + } + re.getOptimizedStartCodesIndices = Va; + function Mt(t4, e, r) { + switch (t4.type) { + case "Disjunction": + for (var n2 = 0;n2 < t4.value.length; n2++) + Mt(t4.value[n2], e, r); + break; + case "Alternative": + for (var i = t4.value, n2 = 0;n2 < i.length; n2++) { + var a = i[n2]; + switch (a.type) { + case "EndAnchor": + case "GroupBackReference": + case "Lookahead": + case "NegativeLookahead": + case "StartAnchor": + case "WordBoundary": + case "NonWordBoundary": + continue; + } + var o = a; + switch (o.type) { + case "Character": + bt(o.value, e, r); + break; + case "Set": + if (o.complement === true) + throw Error(ln); + pe2.forEach(o.value, function(f) { + if (typeof f == "number") + bt(f, e, r); + else { + var p = f; + if (r === true) + for (var l2 = p.from;l2 <= p.to; l2++) + bt(l2, e, r); + else { + for (var l2 = p.from;l2 <= p.to && l2 < Ce.minOptimizationVal; l2++) + bt(l2, e, r); + if (p.to >= Ce.minOptimizationVal) + for (var m = p.from >= Ce.minOptimizationVal ? p.from : Ce.minOptimizationVal, v = p.to, u3 = Ce.charCodeToOptimizedIndex(m), d = Ce.charCodeToOptimizedIndex(v), A4 = u3;A4 <= d; A4++) + e[A4] = A4; + } + } + }); + break; + case "Group": + Mt(o.value, e, r); + break; + default: + throw Error("Non Exhaustive Match"); + } + var s = o.quantifier !== undefined && o.quantifier.atLeast === 0; + if (o.type === "Group" && yr(o) === false || o.type !== "Group" && s === false) + break; + } + break; + default: + throw Error("non exhaustive match!"); + } + return pe2.values(e); + } + re.firstCharOptimizedIndices = Mt; + function bt(t4, e, r) { + var n2 = Ce.charCodeToOptimizedIndex(t4); + e[n2] = n2, r === true && Ka(t4, e); + } + function Ka(t4, e) { + var r = String.fromCharCode(t4), n2 = r.toUpperCase(); + if (n2 !== r) { + var i = Ce.charCodeToOptimizedIndex(n2.charCodeAt(0)); + e[i] = i; + } else { + var a = r.toLowerCase(); + if (a !== r) { + var i = Ce.charCodeToOptimizedIndex(a.charCodeAt(0)); + e[i] = i; + } + } + } + function fn(t4, e) { + return pe2.find(t4.value, function(r) { + if (typeof r == "number") + return pe2.contains(e, r); + var n2 = r; + return pe2.find(e, function(i) { + return n2.from <= i && i <= n2.to; + }) !== undefined; + }); + } + function yr(t4) { + return t4.quantifier && t4.quantifier.atLeast === 0 ? true : t4.value ? pe2.isArray(t4.value) ? pe2.every(t4.value, yr) : yr(t4.value) : false; + } + var za = function(t4) { + ja(e, t4); + function e(r) { + var n2 = t4.call(this) || this; + return n2.targetCharCodes = r, n2.found = false, n2; + } + return e.prototype.visitChildren = function(r) { + if (this.found !== true) { + switch (r.type) { + case "Lookahead": + this.visitLookahead(r); + return; + case "NegativeLookahead": + this.visitNegativeLookahead(r); + return; + } + t4.prototype.visitChildren.call(this, r); + } + }, e.prototype.visitCharacter = function(r) { + pe2.contains(this.targetCharCodes, r.value) && (this.found = true); + }, e.prototype.visitSet = function(r) { + r.complement ? fn(r, this.targetCharCodes) === undefined && (this.found = true) : fn(r, this.targetCharCodes) !== undefined && (this.found = true); + }, e; + }(un.BaseRegExpVisitor); + function Ha2(t4, e) { + if (e instanceof RegExp) { + var r = cn.getRegExpAst(e), n2 = new za(t4); + return n2.visit(r), n2.found; + } else + return pe2.find(e, function(i) { + return pe2.contains(t4, i.charCodeAt(0)); + }) !== undefined; + } + re.canMatchCharCode = Ha2; +}); +var Tr = R2((T3) => { + var hn2 = T3 && T3.__extends || function() { + var t4 = function(e, r) { + return t4 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t4(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t4(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(T3, "__esModule", { value: true }); + T3.charCodeToOptimizedIndex = T3.minOptimizationVal = T3.buildLineBreakIssueMessage = T3.LineTerminatorOptimizedTester = T3.isShortPattern = T3.isCustomPattern = T3.cloneEmptyGroups = T3.performWarningRuntimeChecks = T3.performRuntimeChecks = T3.addStickyFlag = T3.addStartOfInput = T3.findUnreachablePatterns = T3.findModesThatDoNotExist = T3.findInvalidGroupType = T3.findDuplicatePatterns = T3.findUnsupportedFlags = T3.findStartOfInputAnchor = T3.findEmptyMatchRegExps = T3.findEndOfInputAnchor = T3.findInvalidPatterns = T3.findMissingPatterns = T3.validatePatterns = T3.analyzeTokenTypes = T3.enableSticky = T3.disableSticky = T3.SUPPORT_STICKY = T3.MODES = T3.DEFAULT_MODE = undefined; + var dn = xt3(), F = ft(), h = k2(), Ye = pn2(), vn = Lt(), Ae2 = "PATTERN"; + T3.DEFAULT_MODE = "defaultMode"; + T3.MODES = "modes"; + T3.SUPPORT_STICKY = typeof new RegExp("(?:)").sticky == "boolean"; + function Ya2() { + T3.SUPPORT_STICKY = false; + } + T3.disableSticky = Ya2; + function Xa2() { + T3.SUPPORT_STICKY = true; + } + T3.enableSticky = Xa2; + function Za(t4, e) { + e = h.defaults(e, { useSticky: T3.SUPPORT_STICKY, debug: false, safeMode: false, positionTracking: "full", lineTerminatorCharacters: ["\r", ` +`], tracer: function(g3, y3) { + return y3(); + } }); + var r = e.tracer; + r("initCharCodeToOptimizedIndexMap", function() { + $a(); + }); + var n2; + r("Reject Lexer.NA", function() { + n2 = h.reject(t4, function(g3) { + return g3[Ae2] === F.Lexer.NA; + }); + }); + var i = false, a; + r("Transform Patterns", function() { + i = false, a = h.map(n2, function(g3) { + var y3 = g3[Ae2]; + if (h.isRegExp(y3)) { + var b = y3.source; + return b.length === 1 && b !== "^" && b !== "$" && b !== "." && !y3.ignoreCase ? b : b.length === 2 && b[0] === "\\" && !h.contains(["d", "D", "s", "S", "t", "r", "n", "t", "0", "c", "b", "B", "f", "v", "w", "W"], b[1]) ? b[1] : e.useSticky ? gr(y3) : _r(y3); + } else { + if (h.isFunction(y3)) + return i = true, { exec: y3 }; + if (h.has(y3, "exec")) + return i = true, y3; + if (typeof y3 == "string") { + if (y3.length === 1) + return y3; + var L = y3.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"), se2 = new RegExp(L); + return e.useSticky ? gr(se2) : _r(se2); + } else + throw Error("non exhaustive match"); + } + }); + }); + var o, s, c, f, p; + r("misc mapping", function() { + o = h.map(n2, function(g3) { + return g3.tokenTypeIdx; + }), s = h.map(n2, function(g3) { + var y3 = g3.GROUP; + if (y3 !== F.Lexer.SKIPPED) { + if (h.isString(y3)) + return y3; + if (h.isUndefined(y3)) + return false; + throw Error("non exhaustive match"); + } + }), c = h.map(n2, function(g3) { + var y3 = g3.LONGER_ALT; + if (y3) { + var b = h.indexOf(n2, y3); + return b; + } + }), f = h.map(n2, function(g3) { + return g3.PUSH_MODE; + }), p = h.map(n2, function(g3) { + return h.has(g3, "POP_MODE"); + }); + }); + var l2; + r("Line Terminator Handling", function() { + var g3 = Tn(e.lineTerminatorCharacters); + l2 = h.map(n2, function(y3) { + return false; + }), e.positionTracking !== "onlyOffset" && (l2 = h.map(n2, function(y3) { + if (h.has(y3, "LINE_BREAKS")) + return y3.LINE_BREAKS; + if (En(y3, g3) === false) + return Ye.canMatchCharCode(g3, y3.PATTERN); + })); + }); + var m, v, u3, d; + r("Misc Mapping #2", function() { + m = h.map(n2, Ar), v = h.map(a, mn), u3 = h.reduce(n2, function(g3, y3) { + var b = y3.GROUP; + return h.isString(b) && b !== F.Lexer.SKIPPED && (g3[b] = []), g3; + }, {}), d = h.map(a, function(g3, y3) { + return { pattern: a[y3], longerAlt: c[y3], canLineTerminator: l2[y3], isCustom: m[y3], short: v[y3], group: s[y3], push: f[y3], pop: p[y3], tokenTypeIdx: o[y3], tokenType: n2[y3] }; + }); + }); + var A4 = true, _9 = []; + return e.safeMode || r("First Char Optimization", function() { + _9 = h.reduce(n2, function(g3, y3, b) { + if (typeof y3.PATTERN == "string") { + var L = y3.PATTERN.charCodeAt(0), se2 = Or(L); + Rr(g3, se2, d[b]); + } else if (h.isArray(y3.START_CHARS_HINT)) { + var fe; + h.forEach(y3.START_CHARS_HINT, function(ue3) { + var Q3 = typeof ue3 == "string" ? ue3.charCodeAt(0) : ue3, te3 = Or(Q3); + fe !== te3 && (fe = te3, Rr(g3, te3, d[b])); + }); + } else if (h.isRegExp(y3.PATTERN)) + if (y3.PATTERN.unicode) + A4 = false, e.ensureOptimizations && h.PRINT_ERROR("" + Ye.failedOptimizationPrefixMsg + ("\tUnable to analyze < " + y3.PATTERN.toString() + ` > pattern. +`) + ` The regexp unicode flag is not currently supported by the regexp-to-ast library. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`); + else { + var Z3 = Ye.getOptimizedStartCodesIndices(y3.PATTERN, e.ensureOptimizations); + h.isEmpty(Z3) && (A4 = false), h.forEach(Z3, function(ue3) { + Rr(g3, ue3, d[b]); + }); + } + else + e.ensureOptimizations && h.PRINT_ERROR("" + Ye.failedOptimizationPrefixMsg + ("\tTokenType: <" + y3.name + `> is using a custom token pattern without providing parameter. +`) + ` This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`), A4 = false; + return g3; + }, []); + }), r("ArrayPacking", function() { + _9 = h.packArray(_9); + }), { emptyGroups: u3, patternIdxToConfig: d, charCodeToPatternIdxToConfig: _9, hasCustom: i, canBeOptimized: A4 }; + } + T3.analyzeTokenTypes = Za; + function Ja2(t4, e) { + var r = [], n2 = yn2(t4); + r = r.concat(n2.errors); + var i = _n(n2.valid), a = i.valid; + return r = r.concat(i.errors), r = r.concat(Qa(a)), r = r.concat(gn(a)), r = r.concat(An(a, e)), r = r.concat(Rn(a)), r; + } + T3.validatePatterns = Ja2; + function Qa(t4) { + var e = [], r = h.filter(t4, function(n2) { + return h.isRegExp(n2[Ae2]); + }); + return e = e.concat(On(r)), e = e.concat(In2(r)), e = e.concat(kn2(r)), e = e.concat(Pn(r)), e = e.concat(Nn(r)), e; + } + function yn2(t4) { + var e = h.filter(t4, function(i) { + return !h.has(i, Ae2); + }), r = h.map(e, function(i) { + return { message: "Token Type: ->" + i.name + "<- missing static 'PATTERN' property", type: F.LexerDefinitionErrorType.MISSING_PATTERN, tokenTypes: [i] }; + }), n2 = h.difference(t4, e); + return { errors: r, valid: n2 }; + } + T3.findMissingPatterns = yn2; + function _n(t4) { + var e = h.filter(t4, function(i) { + var a = i[Ae2]; + return !h.isRegExp(a) && !h.isFunction(a) && !h.has(a, "exec") && !h.isString(a); + }), r = h.map(e, function(i) { + return { message: "Token Type: ->" + i.name + "<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.", type: F.LexerDefinitionErrorType.INVALID_PATTERN, tokenTypes: [i] }; + }), n2 = h.difference(t4, e); + return { errors: r, valid: n2 }; + } + T3.findInvalidPatterns = _n; + var eo = /[^\\][\$]/; + function On(t4) { + var e = function(i) { + hn2(a, i); + function a() { + var o = i !== null && i.apply(this, arguments) || this; + return o.found = false, o; + } + return a.prototype.visitEndAnchor = function(o) { + this.found = true; + }, a; + }(dn.BaseRegExpVisitor), r = h.filter(t4, function(i) { + var a = i[Ae2]; + try { + var o = vn.getRegExpAst(a), s = new e; + return s.visit(o), s.found; + } catch (c) { + return eo.test(a.source); + } + }), n2 = h.map(r, function(i) { + return { message: `Unexpected RegExp Anchor Error: + Token Type: ->` + i.name + `<- static 'PATTERN' cannot contain end of input anchor '$' + See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`, type: F.LexerDefinitionErrorType.EOI_ANCHOR_FOUND, tokenTypes: [i] }; + }); + return n2; + } + T3.findEndOfInputAnchor = On; + function Nn(t4) { + var e = h.filter(t4, function(n2) { + var i = n2[Ae2]; + return i.test(""); + }), r = h.map(e, function(n2) { + return { message: "Token Type: ->" + n2.name + "<- static 'PATTERN' must not match an empty string", type: F.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN, tokenTypes: [n2] }; + }); + return r; + } + T3.findEmptyMatchRegExps = Nn; + var to = /[^\\[][\^]|^\^/; + function In2(t4) { + var e = function(i) { + hn2(a, i); + function a() { + var o = i !== null && i.apply(this, arguments) || this; + return o.found = false, o; + } + return a.prototype.visitStartAnchor = function(o) { + this.found = true; + }, a; + }(dn.BaseRegExpVisitor), r = h.filter(t4, function(i) { + var a = i[Ae2]; + try { + var o = vn.getRegExpAst(a), s = new e; + return s.visit(o), s.found; + } catch (c) { + return to.test(a.source); + } + }), n2 = h.map(r, function(i) { + return { message: `Unexpected RegExp Anchor Error: + Token Type: ->` + i.name + `<- static 'PATTERN' cannot contain start of input anchor '^' + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`, type: F.LexerDefinitionErrorType.SOI_ANCHOR_FOUND, tokenTypes: [i] }; + }); + return n2; + } + T3.findStartOfInputAnchor = In2; + function kn2(t4) { + var e = h.filter(t4, function(n2) { + var i = n2[Ae2]; + return i instanceof RegExp && (i.multiline || i.global); + }), r = h.map(e, function(n2) { + return { message: "Token Type: ->" + n2.name + "<- static 'PATTERN' may NOT contain global('g') or multiline('m')", type: F.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND, tokenTypes: [n2] }; + }); + return r; + } + T3.findUnsupportedFlags = kn2; + function Pn(t4) { + var e = [], r = h.map(t4, function(a) { + return h.reduce(t4, function(o, s) { + return a.PATTERN.source === s.PATTERN.source && !h.contains(e, s) && s.PATTERN !== F.Lexer.NA && (e.push(s), o.push(s)), o; + }, []); + }); + r = h.compact(r); + var n2 = h.filter(r, function(a) { + return a.length > 1; + }), i = h.map(n2, function(a) { + var o = h.map(a, function(c) { + return c.name; + }), s = h.first(a).PATTERN; + return { message: "The same RegExp pattern ->" + s + "<-" + ("has been used in all of the following Token Types: " + o.join(", ") + " <-"), type: F.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND, tokenTypes: a }; + }); + return i; + } + T3.findDuplicatePatterns = Pn; + function gn(t4) { + var e = h.filter(t4, function(n2) { + if (!h.has(n2, "GROUP")) + return false; + var i = n2.GROUP; + return i !== F.Lexer.SKIPPED && i !== F.Lexer.NA && !h.isString(i); + }), r = h.map(e, function(n2) { + return { message: "Token Type: ->" + n2.name + "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String", type: F.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND, tokenTypes: [n2] }; + }); + return r; + } + T3.findInvalidGroupType = gn; + function An(t4, e) { + var r = h.filter(t4, function(i) { + return i.PUSH_MODE !== undefined && !h.contains(e, i.PUSH_MODE); + }), n2 = h.map(r, function(i) { + var a = "Token Type: ->" + i.name + "<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->" + i.PUSH_MODE + "<-which does not exist"; + return { message: a, type: F.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST, tokenTypes: [i] }; + }); + return n2; + } + T3.findModesThatDoNotExist = An; + function Rn(t4) { + var e = [], r = h.reduce(t4, function(n2, i, a) { + var o = i.PATTERN; + return o === F.Lexer.NA || (h.isString(o) ? n2.push({ str: o, idx: a, tokenType: i }) : h.isRegExp(o) && no(o) && n2.push({ str: o.source, idx: a, tokenType: i })), n2; + }, []); + return h.forEach(t4, function(n2, i) { + h.forEach(r, function(a) { + var { str: o, idx: s, tokenType: c } = a; + if (i < s && ro(o, n2.PATTERN)) { + var f = "Token: ->" + c.name + `<- can never be matched. +` + ("Because it appears AFTER the Token Type ->" + n2.name + "<-") + `in the lexer's definition. +See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`; + e.push({ message: f, type: F.LexerDefinitionErrorType.UNREACHABLE_PATTERN, tokenTypes: [n2, c] }); + } + }); + }), e; + } + T3.findUnreachablePatterns = Rn; + function ro(t4, e) { + if (h.isRegExp(e)) { + var r = e.exec(t4); + return r !== null && r.index === 0; + } else { + if (h.isFunction(e)) + return e(t4, 0, [], {}); + if (h.has(e, "exec")) + return e.exec(t4, 0, [], {}); + if (typeof e == "string") + return e === t4; + throw Error("non exhaustive match"); + } + } + function no(t4) { + var e = [".", "\\", "[", "]", "|", "^", "$", "(", ")", "?", "*", "+", "{"]; + return h.find(e, function(r) { + return t4.source.indexOf(r) !== -1; + }) === undefined; + } + function _r(t4) { + var e = t4.ignoreCase ? "i" : ""; + return new RegExp("^(?:" + t4.source + ")", e); + } + T3.addStartOfInput = _r; + function gr(t4) { + var e = t4.ignoreCase ? "iy" : "y"; + return new RegExp("" + t4.source, e); + } + T3.addStickyFlag = gr; + function io(t4, e, r) { + var n2 = []; + return h.has(t4, T3.DEFAULT_MODE) || n2.push({ message: "A MultiMode Lexer cannot be initialized without a <" + T3.DEFAULT_MODE + `> property in its definition +`, type: F.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE }), h.has(t4, T3.MODES) || n2.push({ message: "A MultiMode Lexer cannot be initialized without a <" + T3.MODES + `> property in its definition +`, type: F.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY }), h.has(t4, T3.MODES) && h.has(t4, T3.DEFAULT_MODE) && !h.has(t4.modes, t4.defaultMode) && n2.push({ message: "A MultiMode Lexer cannot be initialized with a " + T3.DEFAULT_MODE + ": <" + t4.defaultMode + `>which does not exist +`, type: F.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST }), h.has(t4, T3.MODES) && h.forEach(t4.modes, function(i, a) { + h.forEach(i, function(o, s) { + h.isUndefined(o) && n2.push({ message: "A Lexer cannot be initialized using an undefined Token Type. Mode:" + ("<" + a + "> at index: <" + s + `> +`), type: F.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED }); + }); + }), n2; + } + T3.performRuntimeChecks = io; + function ao(t4, e, r) { + var n2 = [], i = false, a = h.compact(h.flatten(h.mapValues(t4.modes, function(c) { + return c; + }))), o = h.reject(a, function(c) { + return c[Ae2] === F.Lexer.NA; + }), s = Tn(r); + return e && h.forEach(o, function(c) { + var f = En(c, s); + if (f !== false) { + var p = Sn2(c, f), l2 = { message: p, type: f.issue, tokenType: c }; + n2.push(l2); + } else + h.has(c, "LINE_BREAKS") ? c.LINE_BREAKS === true && (i = true) : Ye.canMatchCharCode(s, c.PATTERN) && (i = true); + }), e && !i && n2.push({ message: `Warning: No LINE_BREAKS Found. + This Lexer has been defined to track line and column information, + But none of the Token Types can be identified as matching a line terminator. + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS + for details.`, type: F.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS }), n2; + } + T3.performWarningRuntimeChecks = ao; + function oo(t4) { + var e = {}, r = h.keys(t4); + return h.forEach(r, function(n2) { + var i = t4[n2]; + if (h.isArray(i)) + e[n2] = []; + else + throw Error("non exhaustive match"); + }), e; + } + T3.cloneEmptyGroups = oo; + function Ar(t4) { + var e = t4.PATTERN; + if (h.isRegExp(e)) + return false; + if (h.isFunction(e)) + return true; + if (h.has(e, "exec")) + return true; + if (h.isString(e)) + return false; + throw Error("non exhaustive match"); + } + T3.isCustomPattern = Ar; + function mn(t4) { + return h.isString(t4) && t4.length === 1 ? t4.charCodeAt(0) : false; + } + T3.isShortPattern = mn; + T3.LineTerminatorOptimizedTester = { test: function(t4) { + for (var e = t4.length, r = this.lastIndex;r < e; r++) { + var n2 = t4.charCodeAt(r); + if (n2 === 10) + return this.lastIndex = r + 1, true; + if (n2 === 13) + return t4.charCodeAt(r + 1) === 10 ? this.lastIndex = r + 2 : this.lastIndex = r + 1, true; + } + return false; + }, lastIndex: 0 }; + function En(t4, e) { + if (h.has(t4, "LINE_BREAKS")) + return false; + if (h.isRegExp(t4.PATTERN)) { + try { + Ye.canMatchCharCode(e, t4.PATTERN); + } catch (r) { + return { issue: F.LexerDefinitionErrorType.IDENTIFY_TERMINATOR, errMsg: r.message }; + } + return false; + } else { + if (h.isString(t4.PATTERN)) + return false; + if (Ar(t4)) + return { issue: F.LexerDefinitionErrorType.CUSTOM_LINE_BREAK }; + throw Error("non exhaustive match"); + } + } + function Sn2(t4, e) { + if (e.issue === F.LexerDefinitionErrorType.IDENTIFY_TERMINATOR) + return `Warning: unable to identify line terminator usage in pattern. +` + ("\tThe problem is in the <" + t4.name + `> Token Type +`) + ("\t Root cause: " + e.errMsg + `. +`) + "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR"; + if (e.issue === F.LexerDefinitionErrorType.CUSTOM_LINE_BREAK) + return `Warning: A Custom Token Pattern should specify the option. +` + ("\tThe problem is in the <" + t4.name + `> Token Type +`) + "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK"; + throw Error("non exhaustive match"); + } + T3.buildLineBreakIssueMessage = Sn2; + function Tn(t4) { + var e = h.map(t4, function(r) { + return h.isString(r) && r.length > 0 ? r.charCodeAt(0) : r; + }); + return e; + } + function Rr(t4, e, r) { + t4[e] === undefined ? t4[e] = [r] : t4[e].push(r); + } + T3.minOptimizationVal = 256; + var Ft2 = []; + function Or(t4) { + return t4 < T3.minOptimizationVal ? t4 : Ft2[t4]; + } + T3.charCodeToOptimizedIndex = Or; + function $a() { + if (h.isEmpty(Ft2)) { + Ft2 = new Array(65536); + for (var t4 = 0;t4 < 65536; t4++) + Ft2[t4] = t4 > 255 ? 255 + ~~(t4 / 255) : t4; + } + } +}); +var Xe = R2((N) => { + Object.defineProperty(N, "__esModule", { value: true }); + N.isTokenType = N.hasExtendingTokensTypesMapProperty = N.hasExtendingTokensTypesProperty = N.hasCategoriesProperty = N.hasShortKeyProperty = N.singleAssignCategoriesToksMap = N.assignCategoriesMapProp = N.assignCategoriesTokensProp = N.assignTokenDefaultProps = N.expandCategories = N.augmentTokenTypes = N.tokenIdxToClass = N.tokenShortNameIdx = N.tokenStructuredMatcherNoCategories = N.tokenStructuredMatcher = undefined; + var V3 = k2(); + function so(t4, e) { + var r = t4.tokenTypeIdx; + return r === e.tokenTypeIdx ? true : e.isParent === true && e.categoryMatchesMap[r] === true; + } + N.tokenStructuredMatcher = so; + function uo(t4, e) { + return t4.tokenTypeIdx === e.tokenTypeIdx; + } + N.tokenStructuredMatcherNoCategories = uo; + N.tokenShortNameIdx = 1; + N.tokenIdxToClass = {}; + function co2(t4) { + var e = xn(t4); + Cn(e), Mn(e), Ln2(e), V3.forEach(e, function(r) { + r.isParent = r.categoryMatches.length > 0; + }); + } + N.augmentTokenTypes = co2; + function xn(t4) { + for (var e = V3.cloneArr(t4), r = t4, n2 = true;n2; ) { + r = V3.compact(V3.flatten(V3.map(r, function(a) { + return a.CATEGORIES; + }))); + var i = V3.difference(r, e); + e = e.concat(i), V3.isEmpty(i) ? n2 = false : r = i; + } + return e; + } + N.expandCategories = xn; + function Cn(t4) { + V3.forEach(t4, function(e) { + bn(e) || (N.tokenIdxToClass[N.tokenShortNameIdx] = e, e.tokenTypeIdx = N.tokenShortNameIdx++), Nr(e) && !V3.isArray(e.CATEGORIES) && (e.CATEGORIES = [e.CATEGORIES]), Nr(e) || (e.CATEGORIES = []), Fn(e) || (e.categoryMatches = []), wn(e) || (e.categoryMatchesMap = {}); + }); + } + N.assignTokenDefaultProps = Cn; + function Ln2(t4) { + V3.forEach(t4, function(e) { + e.categoryMatches = [], V3.forEach(e.categoryMatchesMap, function(r, n2) { + e.categoryMatches.push(N.tokenIdxToClass[n2].tokenTypeIdx); + }); + }); + } + N.assignCategoriesTokensProp = Ln2; + function Mn(t4) { + V3.forEach(t4, function(e) { + Ir([], e); + }); + } + N.assignCategoriesMapProp = Mn; + function Ir(t4, e) { + V3.forEach(t4, function(r) { + e.categoryMatchesMap[r.tokenTypeIdx] = true; + }), V3.forEach(e.CATEGORIES, function(r) { + var n2 = t4.concat(e); + V3.contains(n2, r) || Ir(n2, r); + }); + } + N.singleAssignCategoriesToksMap = Ir; + function bn(t4) { + return V3.has(t4, "tokenTypeIdx"); + } + N.hasShortKeyProperty = bn; + function Nr(t4) { + return V3.has(t4, "CATEGORIES"); + } + N.hasCategoriesProperty = Nr; + function Fn(t4) { + return V3.has(t4, "categoryMatches"); + } + N.hasExtendingTokensTypesProperty = Fn; + function wn(t4) { + return V3.has(t4, "categoryMatchesMap"); + } + N.hasExtendingTokensTypesMapProperty = wn; + function lo(t4) { + return V3.has(t4, "tokenTypeIdx"); + } + N.isTokenType = lo; +}); +var kr = R2((wt2) => { + Object.defineProperty(wt2, "__esModule", { value: true }); + wt2.defaultLexerErrorProvider = undefined; + wt2.defaultLexerErrorProvider = { buildUnableToPopLexerModeMessage: function(t4) { + return "Unable to pop Lexer Mode after encountering Token ->" + t4.image + "<- The Mode Stack is empty"; + }, buildUnexpectedCharactersMessage: function(t4, e, r, n2, i) { + return "unexpected character: ->" + t4.charAt(e) + "<- at offset: " + e + "," + (" skipped " + r + " characters."); + } }; +}); +var ft = R2((qe) => { + Object.defineProperty(qe, "__esModule", { value: true }); + qe.Lexer = qe.LexerDefinitionErrorType = undefined; + var Ee = Tr(), w = k2(), fo = Xe(), po2 = kr(), ho = Lt(), vo2; + (function(t4) { + t4[t4.MISSING_PATTERN = 0] = "MISSING_PATTERN", t4[t4.INVALID_PATTERN = 1] = "INVALID_PATTERN", t4[t4.EOI_ANCHOR_FOUND = 2] = "EOI_ANCHOR_FOUND", t4[t4.UNSUPPORTED_FLAGS_FOUND = 3] = "UNSUPPORTED_FLAGS_FOUND", t4[t4.DUPLICATE_PATTERNS_FOUND = 4] = "DUPLICATE_PATTERNS_FOUND", t4[t4.INVALID_GROUP_TYPE_FOUND = 5] = "INVALID_GROUP_TYPE_FOUND", t4[t4.PUSH_MODE_DOES_NOT_EXIST = 6] = "PUSH_MODE_DOES_NOT_EXIST", t4[t4.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE = 7] = "MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE", t4[t4.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY = 8] = "MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY", t4[t4.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST = 9] = "MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST", t4[t4.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED = 10] = "LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED", t4[t4.SOI_ANCHOR_FOUND = 11] = "SOI_ANCHOR_FOUND", t4[t4.EMPTY_MATCH_PATTERN = 12] = "EMPTY_MATCH_PATTERN", t4[t4.NO_LINE_BREAKS_FLAGS = 13] = "NO_LINE_BREAKS_FLAGS", t4[t4.UNREACHABLE_PATTERN = 14] = "UNREACHABLE_PATTERN", t4[t4.IDENTIFY_TERMINATOR = 15] = "IDENTIFY_TERMINATOR", t4[t4.CUSTOM_LINE_BREAK = 16] = "CUSTOM_LINE_BREAK"; + })(vo2 = qe.LexerDefinitionErrorType || (qe.LexerDefinitionErrorType = {})); + var pt = { deferDefinitionErrorsHandling: false, positionTracking: "full", lineTerminatorsPattern: /\n|\r\n?/g, lineTerminatorCharacters: [` +`, "\r"], ensureOptimizations: false, safeMode: false, errorMessageProvider: po2.defaultLexerErrorProvider, traceInitPerf: false, skipValidations: false }; + Object.freeze(pt); + var mo = function() { + function t4(e, r) { + var n2 = this; + if (r === undefined && (r = pt), this.lexerDefinition = e, this.lexerDefinitionErrors = [], this.lexerDefinitionWarning = [], this.patternIdxToConfig = {}, this.charCodeToPatternIdxToConfig = {}, this.modes = [], this.emptyGroups = {}, this.config = undefined, this.trackStartLines = true, this.trackEndLines = true, this.hasCustom = false, this.canModeBeOptimized = {}, typeof r == "boolean") + throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. +a boolean 2nd argument is no longer supported`); + this.config = w.merge(pt, r); + var i = this.config.traceInitPerf; + i === true ? (this.traceInitMaxIdent = Infinity, this.traceInitPerf = true) : typeof i == "number" && (this.traceInitMaxIdent = i, this.traceInitPerf = true), this.traceInitIndent = -1, this.TRACE_INIT("Lexer Constructor", function() { + var a, o = true; + n2.TRACE_INIT("Lexer Config handling", function() { + if (n2.config.lineTerminatorsPattern === pt.lineTerminatorsPattern) + n2.config.lineTerminatorsPattern = Ee.LineTerminatorOptimizedTester; + else if (n2.config.lineTerminatorCharacters === pt.lineTerminatorCharacters) + throw Error(`Error: Missing property on the Lexer config. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`); + if (r.safeMode && r.ensureOptimizations) + throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.'); + n2.trackStartLines = /full|onlyStart/i.test(n2.config.positionTracking), n2.trackEndLines = /full/i.test(n2.config.positionTracking), w.isArray(e) ? (a = { modes: {} }, a.modes[Ee.DEFAULT_MODE] = w.cloneArr(e), a[Ee.DEFAULT_MODE] = Ee.DEFAULT_MODE) : (o = false, a = w.cloneObj(e)); + }), n2.config.skipValidations === false && (n2.TRACE_INIT("performRuntimeChecks", function() { + n2.lexerDefinitionErrors = n2.lexerDefinitionErrors.concat(Ee.performRuntimeChecks(a, n2.trackStartLines, n2.config.lineTerminatorCharacters)); + }), n2.TRACE_INIT("performWarningRuntimeChecks", function() { + n2.lexerDefinitionWarning = n2.lexerDefinitionWarning.concat(Ee.performWarningRuntimeChecks(a, n2.trackStartLines, n2.config.lineTerminatorCharacters)); + })), a.modes = a.modes ? a.modes : {}, w.forEach(a.modes, function(p, l2) { + a.modes[l2] = w.reject(p, function(m) { + return w.isUndefined(m); + }); + }); + var s = w.keys(a.modes); + if (w.forEach(a.modes, function(p, l2) { + n2.TRACE_INIT("Mode: <" + l2 + "> processing", function() { + if (n2.modes.push(l2), n2.config.skipValidations === false && n2.TRACE_INIT("validatePatterns", function() { + n2.lexerDefinitionErrors = n2.lexerDefinitionErrors.concat(Ee.validatePatterns(p, s)); + }), w.isEmpty(n2.lexerDefinitionErrors)) { + fo.augmentTokenTypes(p); + var m; + n2.TRACE_INIT("analyzeTokenTypes", function() { + m = Ee.analyzeTokenTypes(p, { lineTerminatorCharacters: n2.config.lineTerminatorCharacters, positionTracking: r.positionTracking, ensureOptimizations: r.ensureOptimizations, safeMode: r.safeMode, tracer: n2.TRACE_INIT.bind(n2) }); + }), n2.patternIdxToConfig[l2] = m.patternIdxToConfig, n2.charCodeToPatternIdxToConfig[l2] = m.charCodeToPatternIdxToConfig, n2.emptyGroups = w.merge(n2.emptyGroups, m.emptyGroups), n2.hasCustom = m.hasCustom || n2.hasCustom, n2.canModeBeOptimized[l2] = m.canBeOptimized; + } + }); + }), n2.defaultMode = a.defaultMode, !w.isEmpty(n2.lexerDefinitionErrors) && !n2.config.deferDefinitionErrorsHandling) { + var c = w.map(n2.lexerDefinitionErrors, function(p) { + return p.message; + }), f = c.join(`----------------------- +`); + throw new Error(`Errors detected in definition of Lexer: +` + f); + } + w.forEach(n2.lexerDefinitionWarning, function(p) { + w.PRINT_WARNING(p.message); + }), n2.TRACE_INIT("Choosing sub-methods implementations", function() { + if (Ee.SUPPORT_STICKY ? (n2.chopInput = w.IDENTITY, n2.match = n2.matchWithTest) : (n2.updateLastIndex = w.NOOP, n2.match = n2.matchWithExec), o && (n2.handleModes = w.NOOP), n2.trackStartLines === false && (n2.computeNewColumn = w.IDENTITY), n2.trackEndLines === false && (n2.updateTokenEndLineColumnLocation = w.NOOP), /full/i.test(n2.config.positionTracking)) + n2.createTokenInstance = n2.createFullToken; + else if (/onlyStart/i.test(n2.config.positionTracking)) + n2.createTokenInstance = n2.createStartOnlyToken; + else if (/onlyOffset/i.test(n2.config.positionTracking)) + n2.createTokenInstance = n2.createOffsetOnlyToken; + else + throw Error('Invalid config option: "' + n2.config.positionTracking + '"'); + n2.hasCustom ? (n2.addToken = n2.addTokenUsingPush, n2.handlePayload = n2.handlePayloadWithCustom) : (n2.addToken = n2.addTokenUsingMemberAccess, n2.handlePayload = n2.handlePayloadNoCustom); + }), n2.TRACE_INIT("Failed Optimization Warnings", function() { + var p = w.reduce(n2.canModeBeOptimized, function(l2, m, v) { + return m === false && l2.push(v), l2; + }, []); + if (r.ensureOptimizations && !w.isEmpty(p)) + throw Error("Lexer Modes: < " + p.join(", ") + ` > cannot be optimized. + Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. + Or inspect the console log for details on how to resolve these issues.`); + }), n2.TRACE_INIT("clearRegExpParserCache", function() { + ho.clearRegExpParserCache(); + }), n2.TRACE_INIT("toFastProperties", function() { + w.toFastProperties(n2); + }); + }); + } + return t4.prototype.tokenize = function(e, r) { + if (r === undefined && (r = this.defaultMode), !w.isEmpty(this.lexerDefinitionErrors)) { + var n2 = w.map(this.lexerDefinitionErrors, function(o) { + return o.message; + }), i = n2.join(`----------------------- +`); + throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: +` + i); + } + var a = this.tokenizeInternal(e, r); + return a; + }, t4.prototype.tokenizeInternal = function(e, r) { + var n2 = this, i, a, o, s, c, f, p, l2, m, v, u3, d, A4, _9, g3, y3 = e, b = y3.length, L = 0, se2 = 0, fe = this.hasCustom ? 0 : Math.floor(e.length / 10), Z3 = new Array(fe), ue3 = [], Q3 = this.trackStartLines ? 1 : undefined, te3 = this.trackStartLines ? 1 : undefined, xe = Ee.cloneEmptyGroups(this.emptyGroups), it2 = this.trackStartLines, at = this.config.lineTerminatorsPattern, Ke2 = 0, we2 = [], ot2 = [], It = [], Qr3 = []; + Object.freeze(Qr3); + var st = undefined; + function Jr2() { + return we2; + } + function en(J2) { + var lt = Ee.charCodeToOptimizedIndex(J2), ze = ot2[lt]; + return ze === undefined ? Qr3 : ze; + } + var wa = function(J2) { + if (It.length === 1 && J2.tokenType.PUSH_MODE === undefined) { + var lt = n2.config.errorMessageProvider.buildUnableToPopLexerModeMessage(J2); + ue3.push({ offset: J2.startOffset, line: J2.startLine !== undefined ? J2.startLine : undefined, column: J2.startColumn !== undefined ? J2.startColumn : undefined, length: J2.image.length, message: lt }); + } else { + It.pop(); + var ze = w.last(It); + we2 = n2.patternIdxToConfig[ze], ot2 = n2.charCodeToPatternIdxToConfig[ze], Ke2 = we2.length; + var Ua = n2.canModeBeOptimized[ze] && n2.config.safeMode === false; + ot2 && Ua ? st = en : st = Jr2; + } + }; + function tn2(J2) { + It.push(J2), ot2 = this.charCodeToPatternIdxToConfig[J2], we2 = this.patternIdxToConfig[J2], Ke2 = we2.length, Ke2 = we2.length; + var lt = this.canModeBeOptimized[J2] && this.config.safeMode === false; + ot2 && lt ? st = en : st = Jr2; + } + tn2.call(this, r); + for (var me;L < b; ) { + c = null; + var rn3 = y3.charCodeAt(L), nn = st(rn3), Da = nn.length; + for (i = 0;i < Da; i++) { + me = nn[i]; + var De = me.pattern; + f = null; + var ut2 = me.short; + if (ut2 !== false ? rn3 === ut2 && (c = De) : me.isCustom === true ? (g3 = De.exec(y3, L, Z3, xe), g3 !== null ? (c = g3[0], g3.payload !== undefined && (f = g3.payload)) : c = null) : (this.updateLastIndex(De, L), c = this.match(De, e, L)), c !== null) { + if (s = me.longerAlt, s !== undefined) { + var fr = we2[s], pr2 = fr.pattern; + p = null, fr.isCustom === true ? (g3 = pr2.exec(y3, L, Z3, xe), g3 !== null ? (o = g3[0], g3.payload !== undefined && (p = g3.payload)) : o = null) : (this.updateLastIndex(pr2, L), o = this.match(pr2, e, L)), o && o.length > c.length && (c = o, f = p, me = fr); + } + break; + } + } + if (c !== null) { + if (l2 = c.length, m = me.group, m !== undefined && (v = me.tokenTypeIdx, u3 = this.createTokenInstance(c, L, v, me.tokenType, Q3, te3, l2), this.handlePayload(u3, f), m === false ? se2 = this.addToken(Z3, se2, u3) : xe[m].push(u3)), e = this.chopInput(e, l2), L = L + l2, te3 = this.computeNewColumn(te3, l2), it2 === true && me.canLineTerminator === true) { + var kt = 0, hr = undefined, dr = undefined; + at.lastIndex = 0; + do + hr = at.test(c), hr === true && (dr = at.lastIndex - 1, kt++); + while (hr === true); + kt !== 0 && (Q3 = Q3 + kt, te3 = l2 - dr, this.updateTokenEndLineColumnLocation(u3, m, dr, kt, Q3, te3, l2)); + } + this.handleModes(me, wa, tn2, u3); + } else { + for (var vr = L, an = Q3, on2 = te3, ct2 = false;!ct2 && L < b; ) + for (A4 = y3.charCodeAt(L), e = this.chopInput(e, 1), L++, a = 0;a < Ke2; a++) { + var mr = we2[a], De = mr.pattern, ut2 = mr.short; + if (ut2 !== false ? y3.charCodeAt(L) === ut2 && (ct2 = true) : mr.isCustom === true ? ct2 = De.exec(y3, L, Z3, xe) !== null : (this.updateLastIndex(De, L), ct2 = De.exec(e) !== null), ct2 === true) + break; + } + d = L - vr, _9 = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(y3, vr, d, an, on2), ue3.push({ offset: vr, line: an, column: on2, length: d, message: _9 }); + } + } + return this.hasCustom || (Z3.length = se2), { tokens: Z3, groups: xe, errors: ue3 }; + }, t4.prototype.handleModes = function(e, r, n2, i) { + if (e.pop === true) { + var a = e.push; + r(i), a !== undefined && n2.call(this, a); + } else + e.push !== undefined && n2.call(this, e.push); + }, t4.prototype.chopInput = function(e, r) { + return e.substring(r); + }, t4.prototype.updateLastIndex = function(e, r) { + e.lastIndex = r; + }, t4.prototype.updateTokenEndLineColumnLocation = function(e, r, n2, i, a, o, s) { + var c, f; + r !== undefined && (c = n2 === s - 1, f = c ? -1 : 0, i === 1 && c === true || (e.endLine = a + f, e.endColumn = o - 1 + -f)); + }, t4.prototype.computeNewColumn = function(e, r) { + return e + r; + }, t4.prototype.createTokenInstance = function() { + for (var e = [], r = 0;r < arguments.length; r++) + e[r] = arguments[r]; + return null; + }, t4.prototype.createOffsetOnlyToken = function(e, r, n2, i) { + return { image: e, startOffset: r, tokenTypeIdx: n2, tokenType: i }; + }, t4.prototype.createStartOnlyToken = function(e, r, n2, i, a, o) { + return { image: e, startOffset: r, startLine: a, startColumn: o, tokenTypeIdx: n2, tokenType: i }; + }, t4.prototype.createFullToken = function(e, r, n2, i, a, o, s) { + return { image: e, startOffset: r, endOffset: r + s - 1, startLine: a, endLine: a, startColumn: o, endColumn: o + s - 1, tokenTypeIdx: n2, tokenType: i }; + }, t4.prototype.addToken = function(e, r, n2) { + return 666; + }, t4.prototype.addTokenUsingPush = function(e, r, n2) { + return e.push(n2), r; + }, t4.prototype.addTokenUsingMemberAccess = function(e, r, n2) { + return e[r] = n2, r++, r; + }, t4.prototype.handlePayload = function(e, r) { + }, t4.prototype.handlePayloadNoCustom = function(e, r) { + }, t4.prototype.handlePayloadWithCustom = function(e, r) { + r !== null && (e.payload = r); + }, t4.prototype.match = function(e, r, n2) { + return null; + }, t4.prototype.matchWithTest = function(e, r, n2) { + var i = e.test(r); + return i === true ? r.substring(n2, e.lastIndex) : null; + }, t4.prototype.matchWithExec = function(e, r) { + var n2 = e.exec(r); + return n2 !== null ? n2[0] : n2; + }, t4.prototype.TRACE_INIT = function(e, r) { + if (this.traceInitPerf === true) { + this.traceInitIndent++; + var n2 = new Array(this.traceInitIndent + 1).join("\t"); + this.traceInitIndent < this.traceInitMaxIdent && console.log(n2 + "--> <" + e + ">"); + var i = w.timer(r), a = i.time, o = i.value, s = a > 10 ? console.warn : console.log; + return this.traceInitIndent < this.traceInitMaxIdent && s(n2 + "<-- <" + e + "> time: " + a + "ms"), this.traceInitIndent--, o; + } else + return r(); + }, t4.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.", t4.NA = /NOT_APPLICABLE/, t4; + }(); + qe.Lexer = mo; +}); +var Ue = R2((H) => { + Object.defineProperty(H, "__esModule", { value: true }); + H.tokenMatcher = H.createTokenInstance = H.EOF = H.createToken = H.hasTokenLabel = H.tokenName = H.tokenLabel = undefined; + var Te2 = k2(), Eo = ft(), Pr = Xe(); + function To(t4) { + return Dn(t4) ? t4.LABEL : t4.name; + } + H.tokenLabel = To; + function yo(t4) { + return t4.name; + } + H.tokenName = yo; + function Dn(t4) { + return Te2.isString(t4.LABEL) && t4.LABEL !== ""; + } + H.hasTokenLabel = Dn; + var _o = "parent", Un = "categories", Gn = "label", Wn = "group", Bn = "push_mode", qn = "pop_mode", jn = "longer_alt", Vn = "line_breaks", Kn = "start_chars_hint"; + function zn(t4) { + return go(t4); + } + H.createToken = zn; + function go(t4) { + var e = t4.pattern, r = {}; + if (r.name = t4.name, Te2.isUndefined(e) || (r.PATTERN = e), Te2.has(t4, _o)) + throw `The parent property is no longer supported. +See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.`; + return Te2.has(t4, Un) && (r.CATEGORIES = t4[Un]), Pr.augmentTokenTypes([r]), Te2.has(t4, Gn) && (r.LABEL = t4[Gn]), Te2.has(t4, Wn) && (r.GROUP = t4[Wn]), Te2.has(t4, qn) && (r.POP_MODE = t4[qn]), Te2.has(t4, Bn) && (r.PUSH_MODE = t4[Bn]), Te2.has(t4, jn) && (r.LONGER_ALT = t4[jn]), Te2.has(t4, Vn) && (r.LINE_BREAKS = t4[Vn]), Te2.has(t4, Kn) && (r.START_CHARS_HINT = t4[Kn]), r; + } + H.EOF = zn({ name: "EOF", pattern: Eo.Lexer.NA }); + Pr.augmentTokenTypes([H.EOF]); + function Ao2(t4, e, r, n2, i, a, o, s) { + return { image: e, startOffset: r, endOffset: n2, startLine: i, endLine: a, startColumn: o, endColumn: s, tokenTypeIdx: t4.tokenTypeIdx, tokenType: t4 }; + } + H.createTokenInstance = Ao2; + function Ro(t4, e) { + return Pr.tokenStructuredMatcher(t4, e); + } + H.tokenMatcher = Ro; +}); +var ne = R2((S) => { + var Le = S && S.__extends || function() { + var t4 = function(e, r) { + return t4 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t4(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t4(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(S, "__esModule", { value: true }); + S.serializeProduction = S.serializeGrammar = S.Terminal = S.Alternation = S.RepetitionWithSeparator = S.Repetition = S.RepetitionMandatoryWithSeparator = S.RepetitionMandatory = S.Option = S.Alternative = S.Rule = S.NonTerminal = S.AbstractProduction = undefined; + var G2 = k2(), Oo = Ue(), Re = function() { + function t4(e) { + this._definition = e; + } + return Object.defineProperty(t4.prototype, "definition", { get: function() { + return this._definition; + }, set: function(e) { + this._definition = e; + }, enumerable: false, configurable: true }), t4.prototype.accept = function(e) { + e.visit(this), G2.forEach(this.definition, function(r) { + r.accept(e); + }); + }, t4; + }(); + S.AbstractProduction = Re; + var Hn = function(t4) { + Le(e, t4); + function e(r) { + var n2 = t4.call(this, []) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return Object.defineProperty(e.prototype, "definition", { get: function() { + return this.referencedRule !== undefined ? this.referencedRule.definition : []; + }, set: function(r) { + }, enumerable: false, configurable: true }), e.prototype.accept = function(r) { + r.visit(this); + }, e; + }(Re); + S.NonTerminal = Hn; + var Yn = function(t4) { + Le(e, t4); + function e(r) { + var n2 = t4.call(this, r.definition) || this; + return n2.orgText = "", G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.Rule = Yn; + var Xn = function(t4) { + Le(e, t4); + function e(r) { + var n2 = t4.call(this, r.definition) || this; + return n2.ignoreAmbiguities = false, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.Alternative = Xn; + var $n = function(t4) { + Le(e, t4); + function e(r) { + var n2 = t4.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.Option = $n; + var Zn = function(t4) { + Le(e, t4); + function e(r) { + var n2 = t4.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.RepetitionMandatory = Zn; + var Qn = function(t4) { + Le(e, t4); + function e(r) { + var n2 = t4.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.RepetitionMandatoryWithSeparator = Qn; + var Jn = function(t4) { + Le(e, t4); + function e(r) { + var n2 = t4.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.Repetition = Jn; + var ei = function(t4) { + Le(e, t4); + function e(r) { + var n2 = t4.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.RepetitionWithSeparator = ei; + var ti = function(t4) { + Le(e, t4); + function e(r) { + var n2 = t4.call(this, r.definition) || this; + return n2.idx = 1, n2.ignoreAmbiguities = false, n2.hasPredicates = false, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return Object.defineProperty(e.prototype, "definition", { get: function() { + return this._definition; + }, set: function(r) { + this._definition = r; + }, enumerable: false, configurable: true }), e; + }(Re); + S.Alternation = ti; + var Dt = function() { + function t4(e) { + this.idx = 1, G2.assign(this, G2.pick(e, function(r) { + return r !== undefined; + })); + } + return t4.prototype.accept = function(e) { + e.visit(this); + }, t4; + }(); + S.Terminal = Dt; + function No2(t4) { + return G2.map(t4, ht); + } + S.serializeGrammar = No2; + function ht(t4) { + function e(i) { + return G2.map(i, ht); + } + if (t4 instanceof Hn) + return { type: "NonTerminal", name: t4.nonTerminalName, idx: t4.idx }; + if (t4 instanceof Xn) + return { type: "Alternative", definition: e(t4.definition) }; + if (t4 instanceof $n) + return { type: "Option", idx: t4.idx, definition: e(t4.definition) }; + if (t4 instanceof Zn) + return { type: "RepetitionMandatory", idx: t4.idx, definition: e(t4.definition) }; + if (t4 instanceof Qn) + return { type: "RepetitionMandatoryWithSeparator", idx: t4.idx, separator: ht(new Dt({ terminalType: t4.separator })), definition: e(t4.definition) }; + if (t4 instanceof ei) + return { type: "RepetitionWithSeparator", idx: t4.idx, separator: ht(new Dt({ terminalType: t4.separator })), definition: e(t4.definition) }; + if (t4 instanceof Jn) + return { type: "Repetition", idx: t4.idx, definition: e(t4.definition) }; + if (t4 instanceof ti) + return { type: "Alternation", idx: t4.idx, definition: e(t4.definition) }; + if (t4 instanceof Dt) { + var r = { type: "Terminal", name: t4.terminalType.name, label: Oo.tokenLabel(t4.terminalType), idx: t4.idx }, n2 = t4.terminalType.PATTERN; + return t4.terminalType.PATTERN && (r.pattern = G2.isRegExp(n2) ? n2.source : n2), r; + } else { + if (t4 instanceof Yn) + return { type: "Rule", name: t4.name, orgText: t4.orgText, definition: e(t4.definition) }; + throw Error("non exhaustive match"); + } + } + S.serializeProduction = ht; +}); +var Gt = R2((Ut3) => { + Object.defineProperty(Ut3, "__esModule", { value: true }); + Ut3.RestWalker = undefined; + var Sr = k2(), ie = ne(), Io = function() { + function t4() { + } + return t4.prototype.walk = function(e, r) { + var n2 = this; + r === undefined && (r = []), Sr.forEach(e.definition, function(i, a) { + var o = Sr.drop(e.definition, a + 1); + if (i instanceof ie.NonTerminal) + n2.walkProdRef(i, o, r); + else if (i instanceof ie.Terminal) + n2.walkTerminal(i, o, r); + else if (i instanceof ie.Alternative) + n2.walkFlat(i, o, r); + else if (i instanceof ie.Option) + n2.walkOption(i, o, r); + else if (i instanceof ie.RepetitionMandatory) + n2.walkAtLeastOne(i, o, r); + else if (i instanceof ie.RepetitionMandatoryWithSeparator) + n2.walkAtLeastOneSep(i, o, r); + else if (i instanceof ie.RepetitionWithSeparator) + n2.walkManySep(i, o, r); + else if (i instanceof ie.Repetition) + n2.walkMany(i, o, r); + else if (i instanceof ie.Alternation) + n2.walkOr(i, o, r); + else + throw Error("non exhaustive match"); + }); + }, t4.prototype.walkTerminal = function(e, r, n2) { + }, t4.prototype.walkProdRef = function(e, r, n2) { + }, t4.prototype.walkFlat = function(e, r, n2) { + var i = r.concat(n2); + this.walk(e, i); + }, t4.prototype.walkOption = function(e, r, n2) { + var i = r.concat(n2); + this.walk(e, i); + }, t4.prototype.walkAtLeastOne = function(e, r, n2) { + var i = [new ie.Option({ definition: e.definition })].concat(r, n2); + this.walk(e, i); + }, t4.prototype.walkAtLeastOneSep = function(e, r, n2) { + var i = ri2(e, r, n2); + this.walk(e, i); + }, t4.prototype.walkMany = function(e, r, n2) { + var i = [new ie.Option({ definition: e.definition })].concat(r, n2); + this.walk(e, i); + }, t4.prototype.walkManySep = function(e, r, n2) { + var i = ri2(e, r, n2); + this.walk(e, i); + }, t4.prototype.walkOr = function(e, r, n2) { + var i = this, a = r.concat(n2); + Sr.forEach(e.definition, function(o) { + var s = new ie.Alternative({ definition: [o] }); + i.walk(s, a); + }); + }, t4; + }(); + Ut3.RestWalker = Io; + function ri2(t4, e, r) { + var n2 = [new ie.Option({ definition: [new ie.Terminal({ terminalType: t4.separator })].concat(t4.definition) })], i = n2.concat(e, r); + return i; + } +}); +var $e = R2((Wt) => { + Object.defineProperty(Wt, "__esModule", { value: true }); + Wt.GAstVisitor = undefined; + var Oe = ne(), ko2 = function() { + function t4() { + } + return t4.prototype.visit = function(e) { + var r = e; + switch (r.constructor) { + case Oe.NonTerminal: + return this.visitNonTerminal(r); + case Oe.Alternative: + return this.visitAlternative(r); + case Oe.Option: + return this.visitOption(r); + case Oe.RepetitionMandatory: + return this.visitRepetitionMandatory(r); + case Oe.RepetitionMandatoryWithSeparator: + return this.visitRepetitionMandatoryWithSeparator(r); + case Oe.RepetitionWithSeparator: + return this.visitRepetitionWithSeparator(r); + case Oe.Repetition: + return this.visitRepetition(r); + case Oe.Alternation: + return this.visitAlternation(r); + case Oe.Terminal: + return this.visitTerminal(r); + case Oe.Rule: + return this.visitRule(r); + default: + throw Error("non exhaustive match"); + } + }, t4.prototype.visitNonTerminal = function(e) { + }, t4.prototype.visitAlternative = function(e) { + }, t4.prototype.visitOption = function(e) { + }, t4.prototype.visitRepetition = function(e) { + }, t4.prototype.visitRepetitionMandatory = function(e) { + }, t4.prototype.visitRepetitionMandatoryWithSeparator = function(e) { + }, t4.prototype.visitRepetitionWithSeparator = function(e) { + }, t4.prototype.visitAlternation = function(e) { + }, t4.prototype.visitTerminal = function(e) { + }, t4.prototype.visitRule = function(e) { + }, t4; + }(); + Wt.GAstVisitor = ko2; +}); +var vt = R2((X) => { + var Po = X && X.__extends || function() { + var t4 = function(e, r) { + return t4 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t4(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t4(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(X, "__esModule", { value: true }); + X.collectMethods = X.DslMethodsCollectorVisitor = X.getProductionDslName = X.isBranchingProd = X.isOptionalProd = X.isSequenceProd = undefined; + var dt = k2(), W = ne(), So = $e(); + function xo(t4) { + return t4 instanceof W.Alternative || t4 instanceof W.Option || t4 instanceof W.Repetition || t4 instanceof W.RepetitionMandatory || t4 instanceof W.RepetitionMandatoryWithSeparator || t4 instanceof W.RepetitionWithSeparator || t4 instanceof W.Terminal || t4 instanceof W.Rule; + } + X.isSequenceProd = xo; + function xr(t4, e) { + e === undefined && (e = []); + var r = t4 instanceof W.Option || t4 instanceof W.Repetition || t4 instanceof W.RepetitionWithSeparator; + return r ? true : t4 instanceof W.Alternation ? dt.some(t4.definition, function(n2) { + return xr(n2, e); + }) : t4 instanceof W.NonTerminal && dt.contains(e, t4) ? false : t4 instanceof W.AbstractProduction ? (t4 instanceof W.NonTerminal && e.push(t4), dt.every(t4.definition, function(n2) { + return xr(n2, e); + })) : false; + } + X.isOptionalProd = xr; + function Co(t4) { + return t4 instanceof W.Alternation; + } + X.isBranchingProd = Co; + function Lo(t4) { + if (t4 instanceof W.NonTerminal) + return "SUBRULE"; + if (t4 instanceof W.Option) + return "OPTION"; + if (t4 instanceof W.Alternation) + return "OR"; + if (t4 instanceof W.RepetitionMandatory) + return "AT_LEAST_ONE"; + if (t4 instanceof W.RepetitionMandatoryWithSeparator) + return "AT_LEAST_ONE_SEP"; + if (t4 instanceof W.RepetitionWithSeparator) + return "MANY_SEP"; + if (t4 instanceof W.Repetition) + return "MANY"; + if (t4 instanceof W.Terminal) + return "CONSUME"; + throw Error("non exhaustive match"); + } + X.getProductionDslName = Lo; + var ni = function(t4) { + Po(e, t4); + function e() { + var r = t4 !== null && t4.apply(this, arguments) || this; + return r.separator = "-", r.dslMethods = { option: [], alternation: [], repetition: [], repetitionWithSeparator: [], repetitionMandatory: [], repetitionMandatoryWithSeparator: [] }, r; + } + return e.prototype.reset = function() { + this.dslMethods = { option: [], alternation: [], repetition: [], repetitionWithSeparator: [], repetitionMandatory: [], repetitionMandatoryWithSeparator: [] }; + }, e.prototype.visitTerminal = function(r) { + var n2 = r.terminalType.name + this.separator + "Terminal"; + dt.has(this.dslMethods, n2) || (this.dslMethods[n2] = []), this.dslMethods[n2].push(r); + }, e.prototype.visitNonTerminal = function(r) { + var n2 = r.nonTerminalName + this.separator + "Terminal"; + dt.has(this.dslMethods, n2) || (this.dslMethods[n2] = []), this.dslMethods[n2].push(r); + }, e.prototype.visitOption = function(r) { + this.dslMethods.option.push(r); + }, e.prototype.visitRepetitionWithSeparator = function(r) { + this.dslMethods.repetitionWithSeparator.push(r); + }, e.prototype.visitRepetitionMandatory = function(r) { + this.dslMethods.repetitionMandatory.push(r); + }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) { + this.dslMethods.repetitionMandatoryWithSeparator.push(r); + }, e.prototype.visitRepetition = function(r) { + this.dslMethods.repetition.push(r); + }, e.prototype.visitAlternation = function(r) { + this.dslMethods.alternation.push(r); + }, e; + }(So.GAstVisitor); + X.DslMethodsCollectorVisitor = ni; + var Bt = new ni; + function Mo2(t4) { + Bt.reset(), t4.accept(Bt); + var e = Bt.dslMethods; + return Bt.reset(), e; + } + X.collectMethods = Mo2; +}); +var Lr = R2((Ne) => { + Object.defineProperty(Ne, "__esModule", { value: true }); + Ne.firstForTerminal = Ne.firstForBranching = Ne.firstForSequence = Ne.first = undefined; + var qt = k2(), ii = ne(), Cr3 = vt(); + function jt(t4) { + if (t4 instanceof ii.NonTerminal) + return jt(t4.referencedRule); + if (t4 instanceof ii.Terminal) + return si(t4); + if (Cr3.isSequenceProd(t4)) + return ai(t4); + if (Cr3.isBranchingProd(t4)) + return oi(t4); + throw Error("non exhaustive match"); + } + Ne.first = jt; + function ai(t4) { + for (var e = [], r = t4.definition, n2 = 0, i = r.length > n2, a, o = true;i && o; ) + a = r[n2], o = Cr3.isOptionalProd(a), e = e.concat(jt(a)), n2 = n2 + 1, i = r.length > n2; + return qt.uniq(e); + } + Ne.firstForSequence = ai; + function oi(t4) { + var e = qt.map(t4.definition, function(r) { + return jt(r); + }); + return qt.uniq(qt.flatten(e)); + } + Ne.firstForBranching = oi; + function si(t4) { + return [t4.terminalType]; + } + Ne.firstForTerminal = si; +}); +var Mr = R2((Vt) => { + Object.defineProperty(Vt, "__esModule", { value: true }); + Vt.IN = undefined; + Vt.IN = "_~IN~_"; +}); +var pi2 = R2((he) => { + var bo = he && he.__extends || function() { + var t4 = function(e, r) { + return t4 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t4(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t4(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(he, "__esModule", { value: true }); + he.buildInProdFollowPrefix = he.buildBetweenProdsFollowPrefix = he.computeAllProdsFollows = he.ResyncFollowsWalker = undefined; + var Fo = Gt(), wo = Lr(), ui = k2(), ci = Mr(), Do = ne(), fi = function(t4) { + bo(e, t4); + function e(r) { + var n2 = t4.call(this) || this; + return n2.topProd = r, n2.follows = {}, n2; + } + return e.prototype.startWalking = function() { + return this.walk(this.topProd), this.follows; + }, e.prototype.walkTerminal = function(r, n2, i) { + }, e.prototype.walkProdRef = function(r, n2, i) { + var a = li(r.referencedRule, r.idx) + this.topProd.name, o = n2.concat(i), s = new Do.Alternative({ definition: o }), c = wo.first(s); + this.follows[a] = c; + }, e; + }(Fo.RestWalker); + he.ResyncFollowsWalker = fi; + function Uo(t4) { + var e = {}; + return ui.forEach(t4, function(r) { + var n2 = new fi(r).startWalking(); + ui.assign(e, n2); + }), e; + } + he.computeAllProdsFollows = Uo; + function li(t4, e) { + return t4.name + e + ci.IN; + } + he.buildBetweenProdsFollowPrefix = li; + function Go2(t4) { + var e = t4.terminalType.name; + return e + t4.idx + ci.IN; + } + he.buildInProdFollowPrefix = Go2; +}); +var mt = R2((Me) => { + Object.defineProperty(Me, "__esModule", { value: true }); + Me.defaultGrammarValidatorErrorProvider = Me.defaultGrammarResolverErrorProvider = Me.defaultParserErrorProvider = undefined; + var Ze2 = Ue(), Wo = k2(), ye = k2(), br = ne(), hi = vt(); + Me.defaultParserErrorProvider = { buildMismatchTokenMessage: function(t4) { + var { expected: e, actual: r, previous: n2, ruleName: i } = t4, a = Ze2.hasTokenLabel(e), o = a ? "--> " + Ze2.tokenLabel(e) + " <--" : "token of type --> " + e.name + " <--", s = "Expecting " + o + " but found --> '" + r.image + "' <--"; + return s; + }, buildNotAllInputParsedMessage: function(t4) { + var { firstRedundant: e, ruleName: r } = t4; + return "Redundant input, expecting EOF but found: " + e.image; + }, buildNoViableAltMessage: function(t4) { + var { expectedPathsPerAlt: e, actual: r, previous: n2, customUserDescription: i, ruleName: a } = t4, o = "Expecting: ", s = ye.first(r).image, c = ` +but found: '` + s + "'"; + if (i) + return o + i + c; + var f = ye.reduce(e, function(v, u3) { + return v.concat(u3); + }, []), p = ye.map(f, function(v) { + return "[" + ye.map(v, function(u3) { + return Ze2.tokenLabel(u3); + }).join(", ") + "]"; + }), l2 = ye.map(p, function(v, u3) { + return " " + (u3 + 1) + ". " + v; + }), m = `one of these possible Token sequences: +` + l2.join(` +`); + return o + m + c; + }, buildEarlyExitMessage: function(t4) { + var { expectedIterationPaths: e, actual: r, customUserDescription: n2, ruleName: i } = t4, a = "Expecting: ", o = ye.first(r).image, s = ` +but found: '` + o + "'"; + if (n2) + return a + n2 + s; + var c = ye.map(e, function(p) { + return "[" + ye.map(p, function(l2) { + return Ze2.tokenLabel(l2); + }).join(",") + "]"; + }), f = `expecting at least one iteration which starts with one of these possible Token sequences:: + ` + ("<" + c.join(" ,") + ">"); + return a + f + s; + } }; + Object.freeze(Me.defaultParserErrorProvider); + Me.defaultGrammarResolverErrorProvider = { buildRuleNotFoundError: function(t4, e) { + var r = "Invalid grammar, reference to a rule which is not defined: ->" + e.nonTerminalName + `<- +inside top level rule: ->` + t4.name + "<-"; + return r; + } }; + Me.defaultGrammarValidatorErrorProvider = { buildDuplicateFoundError: function(t4, e) { + function r(p) { + return p instanceof br.Terminal ? p.terminalType.name : p instanceof br.NonTerminal ? p.nonTerminalName : ""; + } + var n2 = t4.name, i = ye.first(e), a = i.idx, o = hi.getProductionDslName(i), s = r(i), c = a > 0, f = "->" + o + (c ? a : "") + "<- " + (s ? "with argument: ->" + s + "<-" : "") + ` + appears more than once (` + e.length + " times) in the top level rule: ->" + n2 + `<-. + For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES + `; + return f = f.replace(/[ \t]+/g, " "), f = f.replace(/\s\s+/g, ` +`), f; + }, buildNamespaceConflictError: function(t4) { + var e = `Namespace conflict found in grammar. +` + ("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <" + t4.name + `>. +`) + `To resolve this make sure each Terminal and Non-Terminal names are unique +This is easy to accomplish by using the convention that Terminal names start with an uppercase letter +and Non-Terminal names start with a lower case letter.`; + return e; + }, buildAlternationPrefixAmbiguityError: function(t4) { + var e = ye.map(t4.prefixPath, function(i) { + return Ze2.tokenLabel(i); + }).join(", "), r = t4.alternation.idx === 0 ? "" : t4.alternation.idx, n2 = "Ambiguous alternatives: <" + t4.ambiguityIndices.join(" ,") + `> due to common lookahead prefix +` + ("in inside <" + t4.topLevelRule.name + `> Rule, +`) + ("<" + e + `> may appears as a prefix path in all these alternatives. +`) + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX +For Further details.`; + return n2; + }, buildAlternationAmbiguityError: function(t4) { + var e = ye.map(t4.prefixPath, function(i) { + return Ze2.tokenLabel(i); + }).join(", "), r = t4.alternation.idx === 0 ? "" : t4.alternation.idx, n2 = "Ambiguous Alternatives Detected: <" + t4.ambiguityIndices.join(" ,") + "> in " + (" inside <" + t4.topLevelRule.name + `> Rule, +`) + ("<" + e + `> may appears as a prefix path in all these alternatives. +`); + return n2 = n2 + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`, n2; + }, buildEmptyRepetitionError: function(t4) { + var e = hi.getProductionDslName(t4.repetition); + t4.repetition.idx !== 0 && (e += t4.repetition.idx); + var r = "The repetition <" + e + "> within Rule <" + t4.topLevelRule.name + `> can never consume any tokens. +This could lead to an infinite loop.`; + return r; + }, buildTokenNameError: function(t4) { + return "deprecated"; + }, buildEmptyAlternationError: function(t4) { + var e = "Ambiguous empty alternative: <" + (t4.emptyChoiceIdx + 1) + ">" + (" in inside <" + t4.topLevelRule.name + `> Rule. +`) + "Only the last alternative may be an empty alternative."; + return e; + }, buildTooManyAlternativesError: function(t4) { + var e = `An Alternation cannot have more than 256 alternatives: +` + (" inside <" + t4.topLevelRule.name + `> Rule. + has ` + (t4.alternation.definition.length + 1) + " alternatives."); + return e; + }, buildLeftRecursionError: function(t4) { + var e = t4.topLevelRule.name, r = Wo.map(t4.leftRecursionPath, function(a) { + return a.name; + }), n2 = e + " --> " + r.concat([e]).join(" --> "), i = `Left Recursion found in grammar. +` + ("rule: <" + e + `> can be invoked from itself (directly or indirectly) +`) + (`without consuming any Tokens. The grammar path that causes this is: + ` + n2 + ` +`) + ` To fix this refactor your grammar to remove the left recursion. +see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring.`; + return i; + }, buildInvalidRuleNameError: function(t4) { + return "deprecated"; + }, buildDuplicateRuleNameError: function(t4) { + var e; + t4.topLevelRule instanceof br.Rule ? e = t4.topLevelRule.name : e = t4.topLevelRule; + var r = "Duplicate definition, rule: ->" + e + "<- is already defined in the grammar: ->" + t4.grammarName + "<-"; + return r; + } }; +}); +var mi = R2((Ge) => { + var Bo2 = Ge && Ge.__extends || function() { + var t4 = function(e, r) { + return t4 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t4(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t4(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(Ge, "__esModule", { value: true }); + Ge.GastRefResolverVisitor = Ge.resolveGrammar = undefined; + var qo = ce2(), di2 = k2(), jo = $e(); + function Vo2(t4, e) { + var r = new vi(t4, e); + return r.resolveRefs(), r.errors; + } + Ge.resolveGrammar = Vo2; + var vi = function(t4) { + Bo2(e, t4); + function e(r, n2) { + var i = t4.call(this) || this; + return i.nameToTopRule = r, i.errMsgProvider = n2, i.errors = [], i; + } + return e.prototype.resolveRefs = function() { + var r = this; + di2.forEach(di2.values(this.nameToTopRule), function(n2) { + r.currTopLevel = n2, n2.accept(r); + }); + }, e.prototype.visitNonTerminal = function(r) { + var n2 = this.nameToTopRule[r.nonTerminalName]; + if (n2) + r.referencedRule = n2; + else { + var i = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, r); + this.errors.push({ message: i, type: qo.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF, ruleName: this.currTopLevel.name, unresolvedRefName: r.nonTerminalName }); + } + }, e; + }(jo.GAstVisitor); + Ge.GastRefResolverVisitor = vi; +}); +var Tt3 = R2((j2) => { + var je = j2 && j2.__extends || function() { + var t4 = function(e, r) { + return t4 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t4(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t4(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(j2, "__esModule", { value: true }); + j2.nextPossibleTokensAfter = j2.possiblePathsFrom = j2.NextTerminalAfterAtLeastOneSepWalker = j2.NextTerminalAfterAtLeastOneWalker = j2.NextTerminalAfterManySepWalker = j2.NextTerminalAfterManyWalker = j2.AbstractNextTerminalAfterProductionWalker = j2.NextAfterTokenWalker = j2.AbstractNextPossibleTokensWalker = undefined; + var Ei = Gt(), I3 = k2(), Ko = Lr(), O = ne(), Ti2 = function(t4) { + je(e, t4); + function e(r, n2) { + var i = t4.call(this) || this; + return i.topProd = r, i.path = n2, i.possibleTokTypes = [], i.nextProductionName = "", i.nextProductionOccurrence = 0, i.found = false, i.isAtEndOfPath = false, i; + } + return e.prototype.startWalking = function() { + if (this.found = false, this.path.ruleStack[0] !== this.topProd.name) + throw Error("The path does not start with the walker's top Rule!"); + return this.ruleStack = I3.cloneArr(this.path.ruleStack).reverse(), this.occurrenceStack = I3.cloneArr(this.path.occurrenceStack).reverse(), this.ruleStack.pop(), this.occurrenceStack.pop(), this.updateExpectedNext(), this.walk(this.topProd), this.possibleTokTypes; + }, e.prototype.walk = function(r, n2) { + n2 === undefined && (n2 = []), this.found || t4.prototype.walk.call(this, r, n2); + }, e.prototype.walkProdRef = function(r, n2, i) { + if (r.referencedRule.name === this.nextProductionName && r.idx === this.nextProductionOccurrence) { + var a = n2.concat(i); + this.updateExpectedNext(), this.walk(r.referencedRule, a); + } + }, e.prototype.updateExpectedNext = function() { + I3.isEmpty(this.ruleStack) ? (this.nextProductionName = "", this.nextProductionOccurrence = 0, this.isAtEndOfPath = true) : (this.nextProductionName = this.ruleStack.pop(), this.nextProductionOccurrence = this.occurrenceStack.pop()); + }, e; + }(Ei.RestWalker); + j2.AbstractNextPossibleTokensWalker = Ti2; + var zo = function(t4) { + je(e, t4); + function e(r, n2) { + var i = t4.call(this, r, n2) || this; + return i.path = n2, i.nextTerminalName = "", i.nextTerminalOccurrence = 0, i.nextTerminalName = i.path.lastTok.name, i.nextTerminalOccurrence = i.path.lastTokOccurrence, i; + } + return e.prototype.walkTerminal = function(r, n2, i) { + if (this.isAtEndOfPath && r.terminalType.name === this.nextTerminalName && r.idx === this.nextTerminalOccurrence && !this.found) { + var a = n2.concat(i), o = new O.Alternative({ definition: a }); + this.possibleTokTypes = Ko.first(o), this.found = true; + } + }, e; + }(Ti2); + j2.NextAfterTokenWalker = zo; + var Et2 = function(t4) { + je(e, t4); + function e(r, n2) { + var i = t4.call(this) || this; + return i.topRule = r, i.occurrence = n2, i.result = { token: undefined, occurrence: undefined, isEndOfRule: undefined }, i; + } + return e.prototype.startWalking = function() { + return this.walk(this.topRule), this.result; + }, e; + }(Ei.RestWalker); + j2.AbstractNextTerminalAfterProductionWalker = Et2; + var Ho = function(t4) { + je(e, t4); + function e() { + return t4 !== null && t4.apply(this, arguments) || this; + } + return e.prototype.walkMany = function(r, n2, i) { + if (r.idx === this.occurrence) { + var a = I3.first(n2.concat(i)); + this.result.isEndOfRule = a === undefined, a instanceof O.Terminal && (this.result.token = a.terminalType, this.result.occurrence = a.idx); + } else + t4.prototype.walkMany.call(this, r, n2, i); + }, e; + }(Et2); + j2.NextTerminalAfterManyWalker = Ho; + var Yo = function(t4) { + je(e, t4); + function e() { + return t4 !== null && t4.apply(this, arguments) || this; + } + return e.prototype.walkManySep = function(r, n2, i) { + if (r.idx === this.occurrence) { + var a = I3.first(n2.concat(i)); + this.result.isEndOfRule = a === undefined, a instanceof O.Terminal && (this.result.token = a.terminalType, this.result.occurrence = a.idx); + } else + t4.prototype.walkManySep.call(this, r, n2, i); + }, e; + }(Et2); + j2.NextTerminalAfterManySepWalker = Yo; + var Xo2 = function(t4) { + je(e, t4); + function e() { + return t4 !== null && t4.apply(this, arguments) || this; + } + return e.prototype.walkAtLeastOne = function(r, n2, i) { + if (r.idx === this.occurrence) { + var a = I3.first(n2.concat(i)); + this.result.isEndOfRule = a === undefined, a instanceof O.Terminal && (this.result.token = a.terminalType, this.result.occurrence = a.idx); + } else + t4.prototype.walkAtLeastOne.call(this, r, n2, i); + }, e; + }(Et2); + j2.NextTerminalAfterAtLeastOneWalker = Xo2; + var $o = function(t4) { + je(e, t4); + function e() { + return t4 !== null && t4.apply(this, arguments) || this; + } + return e.prototype.walkAtLeastOneSep = function(r, n2, i) { + if (r.idx === this.occurrence) { + var a = I3.first(n2.concat(i)); + this.result.isEndOfRule = a === undefined, a instanceof O.Terminal && (this.result.token = a.terminalType, this.result.occurrence = a.idx); + } else + t4.prototype.walkAtLeastOneSep.call(this, r, n2, i); + }, e; + }(Et2); + j2.NextTerminalAfterAtLeastOneSepWalker = $o; + function yi2(t4, e, r) { + r === undefined && (r = []), r = I3.cloneArr(r); + var n2 = [], i = 0; + function a(f) { + return f.concat(I3.drop(t4, i + 1)); + } + function o(f) { + var p = yi2(a(f), e, r); + return n2.concat(p); + } + for (;r.length < e && i < t4.length; ) { + var s = t4[i]; + if (s instanceof O.Alternative) + return o(s.definition); + if (s instanceof O.NonTerminal) + return o(s.definition); + if (s instanceof O.Option) + n2 = o(s.definition); + else if (s instanceof O.RepetitionMandatory) { + var c = s.definition.concat([new O.Repetition({ definition: s.definition })]); + return o(c); + } else if (s instanceof O.RepetitionMandatoryWithSeparator) { + var c = [new O.Alternative({ definition: s.definition }), new O.Repetition({ definition: [new O.Terminal({ terminalType: s.separator })].concat(s.definition) })]; + return o(c); + } else if (s instanceof O.RepetitionWithSeparator) { + var c = s.definition.concat([new O.Repetition({ definition: [new O.Terminal({ terminalType: s.separator })].concat(s.definition) })]); + n2 = o(c); + } else if (s instanceof O.Repetition) { + var c = s.definition.concat([new O.Repetition({ definition: s.definition })]); + n2 = o(c); + } else { + if (s instanceof O.Alternation) + return I3.forEach(s.definition, function(f) { + I3.isEmpty(f.definition) === false && (n2 = o(f.definition)); + }), n2; + if (s instanceof O.Terminal) + r.push(s.terminalType); + else + throw Error("non exhaustive match"); + } + i++; + } + return n2.push({ partialPath: r, suffixDef: I3.drop(t4, i) }), n2; + } + j2.possiblePathsFrom = yi2; + function Qo(t4, e, r, n2) { + var i = "EXIT_NONE_TERMINAL", a = [i], o = "EXIT_ALTERNATIVE", s = false, c = e.length, f = c - n2 - 1, p = [], l2 = []; + for (l2.push({ idx: -1, def: t4, ruleStack: [], occurrenceStack: [] });!I3.isEmpty(l2); ) { + var m = l2.pop(); + if (m === o) { + s && I3.last(l2).idx <= f && l2.pop(); + continue; + } + var { def: v, idx: u3, ruleStack: d, occurrenceStack: A4 } = m; + if (!I3.isEmpty(v)) { + var _9 = v[0]; + if (_9 === i) { + var g3 = { idx: u3, def: I3.drop(v), ruleStack: I3.dropRight(d), occurrenceStack: I3.dropRight(A4) }; + l2.push(g3); + } else if (_9 instanceof O.Terminal) + if (u3 < c - 1) { + var y3 = u3 + 1, b = e[y3]; + if (r(b, _9.terminalType)) { + var g3 = { idx: y3, def: I3.drop(v), ruleStack: d, occurrenceStack: A4 }; + l2.push(g3); + } + } else if (u3 === c - 1) + p.push({ nextTokenType: _9.terminalType, nextTokenOccurrence: _9.idx, ruleStack: d, occurrenceStack: A4 }), s = true; + else + throw Error("non exhaustive match"); + else if (_9 instanceof O.NonTerminal) { + var L = I3.cloneArr(d); + L.push(_9.nonTerminalName); + var se2 = I3.cloneArr(A4); + se2.push(_9.idx); + var g3 = { idx: u3, def: _9.definition.concat(a, I3.drop(v)), ruleStack: L, occurrenceStack: se2 }; + l2.push(g3); + } else if (_9 instanceof O.Option) { + var fe = { idx: u3, def: I3.drop(v), ruleStack: d, occurrenceStack: A4 }; + l2.push(fe), l2.push(o); + var Z3 = { idx: u3, def: _9.definition.concat(I3.drop(v)), ruleStack: d, occurrenceStack: A4 }; + l2.push(Z3); + } else if (_9 instanceof O.RepetitionMandatory) { + var ue3 = new O.Repetition({ definition: _9.definition, idx: _9.idx }), Q3 = _9.definition.concat([ue3], I3.drop(v)), g3 = { idx: u3, def: Q3, ruleStack: d, occurrenceStack: A4 }; + l2.push(g3); + } else if (_9 instanceof O.RepetitionMandatoryWithSeparator) { + var te3 = new O.Terminal({ terminalType: _9.separator }), ue3 = new O.Repetition({ definition: [te3].concat(_9.definition), idx: _9.idx }), Q3 = _9.definition.concat([ue3], I3.drop(v)), g3 = { idx: u3, def: Q3, ruleStack: d, occurrenceStack: A4 }; + l2.push(g3); + } else if (_9 instanceof O.RepetitionWithSeparator) { + var fe = { idx: u3, def: I3.drop(v), ruleStack: d, occurrenceStack: A4 }; + l2.push(fe), l2.push(o); + var te3 = new O.Terminal({ terminalType: _9.separator }), xe = new O.Repetition({ definition: [te3].concat(_9.definition), idx: _9.idx }), Q3 = _9.definition.concat([xe], I3.drop(v)), Z3 = { idx: u3, def: Q3, ruleStack: d, occurrenceStack: A4 }; + l2.push(Z3); + } else if (_9 instanceof O.Repetition) { + var fe = { idx: u3, def: I3.drop(v), ruleStack: d, occurrenceStack: A4 }; + l2.push(fe), l2.push(o); + var xe = new O.Repetition({ definition: _9.definition, idx: _9.idx }), Q3 = _9.definition.concat([xe], I3.drop(v)), Z3 = { idx: u3, def: Q3, ruleStack: d, occurrenceStack: A4 }; + l2.push(Z3); + } else if (_9 instanceof O.Alternation) + for (var it2 = _9.definition.length - 1;it2 >= 0; it2--) { + var at = _9.definition[it2], Ke2 = { idx: u3, def: at.definition.concat(I3.drop(v)), ruleStack: d, occurrenceStack: A4 }; + l2.push(Ke2), l2.push(o); + } + else if (_9 instanceof O.Alternative) + l2.push({ idx: u3, def: _9.definition.concat(I3.drop(v)), ruleStack: d, occurrenceStack: A4 }); + else if (_9 instanceof O.Rule) + l2.push(Zo(_9, u3, d, A4)); + else + throw Error("non exhaustive match"); + } + } + return p; + } + j2.nextPossibleTokensAfter = Qo; + function Zo(t4, e, r, n2) { + var i = I3.cloneArr(r); + i.push(t4.name); + var a = I3.cloneArr(n2); + return a.push(1), { idx: e, def: t4.definition, ruleStack: i, occurrenceStack: a }; + } +}); +var yt2 = R2((C5) => { + var _i = C5 && C5.__extends || function() { + var t4 = function(e, r) { + return t4 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t4(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t4(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(C5, "__esModule", { value: true }); + C5.areTokenCategoriesNotUsed = C5.isStrictPrefixOfPath = C5.containsPath = C5.getLookaheadPathsForOptionalProd = C5.getLookaheadPathsForOr = C5.lookAheadSequenceFromAlternatives = C5.buildSingleAlternativeLookaheadFunction = C5.buildAlternativesLookAheadFunc = C5.buildLookaheadFuncForOptionalProd = C5.buildLookaheadFuncForOr = C5.getProdType = C5.PROD_TYPE = undefined; + var D = k2(), gi = Tt3(), Jo2 = Gt(), Kt = Xe(), We = ne(), es = $e(), z2; + (function(t4) { + t4[t4.OPTION = 0] = "OPTION", t4[t4.REPETITION = 1] = "REPETITION", t4[t4.REPETITION_MANDATORY = 2] = "REPETITION_MANDATORY", t4[t4.REPETITION_MANDATORY_WITH_SEPARATOR = 3] = "REPETITION_MANDATORY_WITH_SEPARATOR", t4[t4.REPETITION_WITH_SEPARATOR = 4] = "REPETITION_WITH_SEPARATOR", t4[t4.ALTERNATION = 5] = "ALTERNATION"; + })(z2 = C5.PROD_TYPE || (C5.PROD_TYPE = {})); + function ts(t4) { + if (t4 instanceof We.Option) + return z2.OPTION; + if (t4 instanceof We.Repetition) + return z2.REPETITION; + if (t4 instanceof We.RepetitionMandatory) + return z2.REPETITION_MANDATORY; + if (t4 instanceof We.RepetitionMandatoryWithSeparator) + return z2.REPETITION_MANDATORY_WITH_SEPARATOR; + if (t4 instanceof We.RepetitionWithSeparator) + return z2.REPETITION_WITH_SEPARATOR; + if (t4 instanceof We.Alternation) + return z2.ALTERNATION; + throw Error("non exhaustive match"); + } + C5.getProdType = ts; + function rs(t4, e, r, n2, i, a) { + var o = Ai(t4, e, r), s = Fr(o) ? Kt.tokenStructuredMatcherNoCategories : Kt.tokenStructuredMatcher; + return a(o, n2, s, i); + } + C5.buildLookaheadFuncForOr = rs; + function ns(t4, e, r, n2, i, a) { + var o = Ri(t4, e, i, r), s = Fr(o) ? Kt.tokenStructuredMatcherNoCategories : Kt.tokenStructuredMatcher; + return a(o[0], s, n2); + } + C5.buildLookaheadFuncForOptionalProd = ns; + function is(t4, e, r, n2) { + var i = t4.length, a = D.every(t4, function(c) { + return D.every(c, function(f) { + return f.length === 1; + }); + }); + if (e) + return function(c) { + for (var f = D.map(c, function(y3) { + return y3.GATE; + }), p = 0;p < i; p++) { + var l2 = t4[p], m = l2.length, v = f[p]; + if (v !== undefined && v.call(this) === false) + continue; + e: + for (var u3 = 0;u3 < m; u3++) { + for (var d = l2[u3], A4 = d.length, _9 = 0;_9 < A4; _9++) { + var g3 = this.LA(_9 + 1); + if (r(g3, d[_9]) === false) + continue e; + } + return p; + } + } + }; + if (a && !n2) { + var o = D.map(t4, function(c) { + return D.flatten(c); + }), s = D.reduce(o, function(c, f, p) { + return D.forEach(f, function(l2) { + D.has(c, l2.tokenTypeIdx) || (c[l2.tokenTypeIdx] = p), D.forEach(l2.categoryMatches, function(m) { + D.has(c, m) || (c[m] = p); + }); + }), c; + }, []); + return function() { + var c = this.LA(1); + return s[c.tokenTypeIdx]; + }; + } else + return function() { + for (var c = 0;c < i; c++) { + var f = t4[c], p = f.length; + e: + for (var l2 = 0;l2 < p; l2++) { + for (var m = f[l2], v = m.length, u3 = 0;u3 < v; u3++) { + var d = this.LA(u3 + 1); + if (r(d, m[u3]) === false) + continue e; + } + return c; + } + } + }; + } + C5.buildAlternativesLookAheadFunc = is; + function as(t4, e, r) { + var n2 = D.every(t4, function(f) { + return f.length === 1; + }), i = t4.length; + if (n2 && !r) { + var a = D.flatten(t4); + if (a.length === 1 && D.isEmpty(a[0].categoryMatches)) { + var o = a[0], s = o.tokenTypeIdx; + return function() { + return this.LA(1).tokenTypeIdx === s; + }; + } else { + var c = D.reduce(a, function(f, p, l2) { + return f[p.tokenTypeIdx] = true, D.forEach(p.categoryMatches, function(m) { + f[m] = true; + }), f; + }, []); + return function() { + var f = this.LA(1); + return c[f.tokenTypeIdx] === true; + }; + } + } else + return function() { + e: + for (var f = 0;f < i; f++) { + for (var p = t4[f], l2 = p.length, m = 0;m < l2; m++) { + var v = this.LA(m + 1); + if (e(v, p[m]) === false) + continue e; + } + return true; + } + return false; + }; + } + C5.buildSingleAlternativeLookaheadFunction = as; + var os3 = function(t4) { + _i(e, t4); + function e(r, n2, i) { + var a = t4.call(this) || this; + return a.topProd = r, a.targetOccurrence = n2, a.targetProdType = i, a; + } + return e.prototype.startWalking = function() { + return this.walk(this.topProd), this.restDef; + }, e.prototype.checkIsTarget = function(r, n2, i, a) { + return r.idx === this.targetOccurrence && this.targetProdType === n2 ? (this.restDef = i.concat(a), true) : false; + }, e.prototype.walkOption = function(r, n2, i) { + this.checkIsTarget(r, z2.OPTION, n2, i) || t4.prototype.walkOption.call(this, r, n2, i); + }, e.prototype.walkAtLeastOne = function(r, n2, i) { + this.checkIsTarget(r, z2.REPETITION_MANDATORY, n2, i) || t4.prototype.walkOption.call(this, r, n2, i); + }, e.prototype.walkAtLeastOneSep = function(r, n2, i) { + this.checkIsTarget(r, z2.REPETITION_MANDATORY_WITH_SEPARATOR, n2, i) || t4.prototype.walkOption.call(this, r, n2, i); + }, e.prototype.walkMany = function(r, n2, i) { + this.checkIsTarget(r, z2.REPETITION, n2, i) || t4.prototype.walkOption.call(this, r, n2, i); + }, e.prototype.walkManySep = function(r, n2, i) { + this.checkIsTarget(r, z2.REPETITION_WITH_SEPARATOR, n2, i) || t4.prototype.walkOption.call(this, r, n2, i); + }, e; + }(Jo2.RestWalker), Oi3 = function(t4) { + _i(e, t4); + function e(r, n2, i) { + var a = t4.call(this) || this; + return a.targetOccurrence = r, a.targetProdType = n2, a.targetRef = i, a.result = [], a; + } + return e.prototype.checkIsTarget = function(r, n2) { + r.idx === this.targetOccurrence && this.targetProdType === n2 && (this.targetRef === undefined || r === this.targetRef) && (this.result = r.definition); + }, e.prototype.visitOption = function(r) { + this.checkIsTarget(r, z2.OPTION); + }, e.prototype.visitRepetition = function(r) { + this.checkIsTarget(r, z2.REPETITION); + }, e.prototype.visitRepetitionMandatory = function(r) { + this.checkIsTarget(r, z2.REPETITION_MANDATORY); + }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) { + this.checkIsTarget(r, z2.REPETITION_MANDATORY_WITH_SEPARATOR); + }, e.prototype.visitRepetitionWithSeparator = function(r) { + this.checkIsTarget(r, z2.REPETITION_WITH_SEPARATOR); + }, e.prototype.visitAlternation = function(r) { + this.checkIsTarget(r, z2.ALTERNATION); + }, e; + }(es.GAstVisitor); + function Ni(t4) { + for (var e = new Array(t4), r = 0;r < t4; r++) + e[r] = []; + return e; + } + function wr(t4) { + for (var e = [""], r = 0;r < t4.length; r++) { + for (var n2 = t4[r], i = [], a = 0;a < e.length; a++) { + var o = e[a]; + i.push(o + "_" + n2.tokenTypeIdx); + for (var s = 0;s < n2.categoryMatches.length; s++) { + var c = "_" + n2.categoryMatches[s]; + i.push(o + c); + } + } + e = i; + } + return e; + } + function ss(t4, e, r) { + for (var n2 = 0;n2 < t4.length; n2++) + if (n2 !== r) + for (var i = t4[n2], a = 0;a < e.length; a++) { + var o = e[a]; + if (i[o] === true) + return false; + } + return true; + } + function Dr(t4, e) { + for (var r = D.map(t4, function(p) { + return gi.possiblePathsFrom([p], 1); + }), n2 = Ni(r.length), i = D.map(r, function(p) { + var l2 = {}; + return D.forEach(p, function(m) { + var v = wr(m.partialPath); + D.forEach(v, function(u3) { + l2[u3] = true; + }); + }), l2; + }), a = r, o = 1;o <= e; o++) { + var s = a; + a = Ni(s.length); + for (var c = function(p) { + for (var l2 = s[p], m = 0;m < l2.length; m++) { + var v = l2[m].partialPath, u3 = l2[m].suffixDef, d = wr(v), A4 = ss(i, d, p); + if (A4 || D.isEmpty(u3) || v.length === e) { + var _9 = n2[p]; + if (Ii2(_9, v) === false) { + _9.push(v); + for (var g3 = 0;g3 < d.length; g3++) { + var y3 = d[g3]; + i[p][y3] = true; + } + } + } else { + var b = gi.possiblePathsFrom(u3, o + 1, v); + a[p] = a[p].concat(b), D.forEach(b, function(L) { + var se2 = wr(L.partialPath); + D.forEach(se2, function(fe) { + i[p][fe] = true; + }); + }); + } + } + }, f = 0;f < s.length; f++) + c(f); + } + return n2; + } + C5.lookAheadSequenceFromAlternatives = Dr; + function Ai(t4, e, r, n2) { + var i = new Oi3(t4, z2.ALTERNATION, n2); + return e.accept(i), Dr(i.result, r); + } + C5.getLookaheadPathsForOr = Ai; + function Ri(t4, e, r, n2) { + var i = new Oi3(t4, r); + e.accept(i); + var a = i.result, o = new os3(e, t4, r), s = o.startWalking(), c = new We.Alternative({ definition: a }), f = new We.Alternative({ definition: s }); + return Dr([c, f], n2); + } + C5.getLookaheadPathsForOptionalProd = Ri; + function Ii2(t4, e) { + e: + for (var r = 0;r < t4.length; r++) { + var n2 = t4[r]; + if (n2.length === e.length) { + for (var i = 0;i < n2.length; i++) { + var a = e[i], o = n2[i], s = a === o || o.categoryMatchesMap[a.tokenTypeIdx] !== undefined; + if (s === false) + continue e; + } + return true; + } + } + return false; + } + C5.containsPath = Ii2; + function us(t4, e) { + return t4.length < e.length && D.every(t4, function(r, n2) { + var i = e[n2]; + return r === i || i.categoryMatchesMap[r.tokenTypeIdx]; + }); + } + C5.isStrictPrefixOfPath = us; + function Fr(t4) { + return D.every(t4, function(e) { + return D.every(e, function(r) { + return D.every(r, function(n2) { + return D.isEmpty(n2.categoryMatches); + }); + }); + }); + } + C5.areTokenCategoriesNotUsed = Fr; +}); +var jr = R2((x2) => { + var Ur = x2 && x2.__extends || function() { + var t4 = function(e, r) { + return t4 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t4(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t4(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(x2, "__esModule", { value: true }); + x2.checkPrefixAlternativesAmbiguities = x2.validateSomeNonEmptyLookaheadPath = x2.validateTooManyAlts = x2.RepetionCollector = x2.validateAmbiguousAlternationAlternatives = x2.validateEmptyOrAlternative = x2.getFirstNoneTerminal = x2.validateNoLeftRecursion = x2.validateRuleIsOverridden = x2.validateRuleDoesNotAlreadyExist = x2.OccurrenceValidationCollector = x2.identifyProductionForDuplicates = x2.validateGrammar = undefined; + var M = k2(), B3 = k2(), Ie2 = ce2(), Gr2 = vt(), Qe = yt2(), cs = Tt3(), _e = ne(), Wr = $e(); + function ps(t4, e, r, n2, i) { + var a = M.map(t4, function(v) { + return ls(v, n2); + }), o = M.map(t4, function(v) { + return Br(v, v, n2); + }), s = [], c = [], f = []; + B3.every(o, B3.isEmpty) && (s = B3.map(t4, function(v) { + return Pi3(v, n2); + }), c = B3.map(t4, function(v) { + return Si2(v, e, n2); + }), f = Ci(t4, e, n2)); + var p = fs(t4, r, n2), l2 = B3.map(t4, function(v) { + return xi(v, n2); + }), m = B3.map(t4, function(v) { + return ki2(v, t4, i, n2); + }); + return M.flatten(a.concat(f, o, s, c, p, l2, m)); + } + x2.validateGrammar = ps; + function ls(t4, e) { + var r = new bi; + t4.accept(r); + var n2 = r.allProductions, i = M.groupBy(n2, Li), a = M.pick(i, function(s) { + return s.length > 1; + }), o = M.map(M.values(a), function(s) { + var c = M.first(s), f = e.buildDuplicateFoundError(t4, s), p = Gr2.getProductionDslName(c), l2 = { message: f, type: Ie2.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS, ruleName: t4.name, dslName: p, occurrence: c.idx }, m = Mi(c); + return m && (l2.parameter = m), l2; + }); + return o; + } + function Li(t4) { + return Gr2.getProductionDslName(t4) + "_#_" + t4.idx + "_#_" + Mi(t4); + } + x2.identifyProductionForDuplicates = Li; + function Mi(t4) { + return t4 instanceof _e.Terminal ? t4.terminalType.name : t4 instanceof _e.NonTerminal ? t4.nonTerminalName : ""; + } + var bi = function(t4) { + Ur(e, t4); + function e() { + var r = t4 !== null && t4.apply(this, arguments) || this; + return r.allProductions = [], r; + } + return e.prototype.visitNonTerminal = function(r) { + this.allProductions.push(r); + }, e.prototype.visitOption = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionWithSeparator = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionMandatory = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetition = function(r) { + this.allProductions.push(r); + }, e.prototype.visitAlternation = function(r) { + this.allProductions.push(r); + }, e.prototype.visitTerminal = function(r) { + this.allProductions.push(r); + }, e; + }(Wr.GAstVisitor); + x2.OccurrenceValidationCollector = bi; + function ki2(t4, e, r, n2) { + var i = [], a = B3.reduce(e, function(s, c) { + return c.name === t4.name ? s + 1 : s; + }, 0); + if (a > 1) { + var o = n2.buildDuplicateRuleNameError({ topLevelRule: t4, grammarName: r }); + i.push({ message: o, type: Ie2.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, ruleName: t4.name }); + } + return i; + } + x2.validateRuleDoesNotAlreadyExist = ki2; + function hs(t4, e, r) { + var n2 = [], i; + return M.contains(e, t4) || (i = "Invalid rule override, rule: ->" + t4 + "<- cannot be overridden in the grammar: ->" + r + "<-as it is not defined in any of the super grammars ", n2.push({ message: i, type: Ie2.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE, ruleName: t4 })), n2; + } + x2.validateRuleIsOverridden = hs; + function Br(t4, e, r, n2) { + n2 === undefined && (n2 = []); + var i = [], a = _t(e.definition); + if (M.isEmpty(a)) + return []; + var o = t4.name, s = M.contains(a, t4); + s && i.push({ message: r.buildLeftRecursionError({ topLevelRule: t4, leftRecursionPath: n2 }), type: Ie2.ParserDefinitionErrorType.LEFT_RECURSION, ruleName: o }); + var c = M.difference(a, n2.concat([t4])), f = M.map(c, function(p) { + var l2 = M.cloneArr(n2); + return l2.push(p), Br(t4, p, r, l2); + }); + return i.concat(M.flatten(f)); + } + x2.validateNoLeftRecursion = Br; + function _t(t4) { + var e = []; + if (M.isEmpty(t4)) + return e; + var r = M.first(t4); + if (r instanceof _e.NonTerminal) + e.push(r.referencedRule); + else if (r instanceof _e.Alternative || r instanceof _e.Option || r instanceof _e.RepetitionMandatory || r instanceof _e.RepetitionMandatoryWithSeparator || r instanceof _e.RepetitionWithSeparator || r instanceof _e.Repetition) + e = e.concat(_t(r.definition)); + else if (r instanceof _e.Alternation) + e = M.flatten(M.map(r.definition, function(o) { + return _t(o.definition); + })); + else if (!(r instanceof _e.Terminal)) + throw Error("non exhaustive match"); + var n2 = Gr2.isOptionalProd(r), i = t4.length > 1; + if (n2 && i) { + var a = M.drop(t4); + return e.concat(_t(a)); + } else + return e; + } + x2.getFirstNoneTerminal = _t; + var qr2 = function(t4) { + Ur(e, t4); + function e() { + var r = t4 !== null && t4.apply(this, arguments) || this; + return r.alternations = [], r; + } + return e.prototype.visitAlternation = function(r) { + this.alternations.push(r); + }, e; + }(Wr.GAstVisitor); + function Pi3(t4, e) { + var r = new qr2; + t4.accept(r); + var n2 = r.alternations, i = M.reduce(n2, function(a, o) { + var s = M.dropRight(o.definition), c = M.map(s, function(f, p) { + var l2 = cs.nextPossibleTokensAfter([f], [], null, 1); + return M.isEmpty(l2) ? { message: e.buildEmptyAlternationError({ topLevelRule: t4, alternation: o, emptyChoiceIdx: p }), type: Ie2.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT, ruleName: t4.name, occurrence: o.idx, alternative: p + 1 } : null; + }); + return a.concat(M.compact(c)); + }, []); + return i; + } + x2.validateEmptyOrAlternative = Pi3; + function Si2(t4, e, r) { + var n2 = new qr2; + t4.accept(n2); + var i = n2.alternations; + i = B3.reject(i, function(o) { + return o.ignoreAmbiguities === true; + }); + var a = M.reduce(i, function(o, s) { + var c = s.idx, f = s.maxLookahead || e, p = Qe.getLookaheadPathsForOr(c, t4, f, s), l2 = ds(p, s, t4, r), m = Fi3(p, s, t4, r); + return o.concat(l2, m); + }, []); + return a; + } + x2.validateAmbiguousAlternationAlternatives = Si2; + var wi = function(t4) { + Ur(e, t4); + function e() { + var r = t4 !== null && t4.apply(this, arguments) || this; + return r.allProductions = [], r; + } + return e.prototype.visitRepetitionWithSeparator = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionMandatory = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetition = function(r) { + this.allProductions.push(r); + }, e; + }(Wr.GAstVisitor); + x2.RepetionCollector = wi; + function xi(t4, e) { + var r = new qr2; + t4.accept(r); + var n2 = r.alternations, i = M.reduce(n2, function(a, o) { + return o.definition.length > 255 && a.push({ message: e.buildTooManyAlternativesError({ topLevelRule: t4, alternation: o }), type: Ie2.ParserDefinitionErrorType.TOO_MANY_ALTS, ruleName: t4.name, occurrence: o.idx }), a; + }, []); + return i; + } + x2.validateTooManyAlts = xi; + function Ci(t4, e, r) { + var n2 = []; + return B3.forEach(t4, function(i) { + var a = new wi; + i.accept(a); + var o = a.allProductions; + B3.forEach(o, function(s) { + var c = Qe.getProdType(s), f = s.maxLookahead || e, p = s.idx, l2 = Qe.getLookaheadPathsForOptionalProd(p, i, c, f), m = l2[0]; + if (B3.isEmpty(B3.flatten(m))) { + var v = r.buildEmptyRepetitionError({ topLevelRule: i, repetition: s }); + n2.push({ message: v, type: Ie2.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD, ruleName: i.name }); + } + }); + }), n2; + } + x2.validateSomeNonEmptyLookaheadPath = Ci; + function ds(t4, e, r, n2) { + var i = [], a = B3.reduce(t4, function(s, c, f) { + return e.definition[f].ignoreAmbiguities === true || B3.forEach(c, function(p) { + var l2 = [f]; + B3.forEach(t4, function(m, v) { + f !== v && Qe.containsPath(m, p) && e.definition[v].ignoreAmbiguities !== true && l2.push(v); + }), l2.length > 1 && !Qe.containsPath(i, p) && (i.push(p), s.push({ alts: l2, path: p })); + }), s; + }, []), o = M.map(a, function(s) { + var c = B3.map(s.alts, function(p) { + return p + 1; + }), f = n2.buildAlternationAmbiguityError({ topLevelRule: r, alternation: e, ambiguityIndices: c, prefixPath: s.path }); + return { message: f, type: Ie2.ParserDefinitionErrorType.AMBIGUOUS_ALTS, ruleName: r.name, occurrence: e.idx, alternatives: [s.alts] }; + }); + return o; + } + function Fi3(t4, e, r, n2) { + var i = [], a = B3.reduce(t4, function(o, s, c) { + var f = B3.map(s, function(p) { + return { idx: c, path: p }; + }); + return o.concat(f); + }, []); + return B3.forEach(a, function(o) { + var s = e.definition[o.idx]; + if (s.ignoreAmbiguities !== true) { + var { idx: c, path: f } = o, p = B3.findAll(a, function(m) { + return e.definition[m.idx].ignoreAmbiguities !== true && m.idx < c && Qe.isStrictPrefixOfPath(m.path, f); + }), l2 = B3.map(p, function(m) { + var v = [m.idx + 1, c + 1], u3 = e.idx === 0 ? "" : e.idx, d = n2.buildAlternationPrefixAmbiguityError({ topLevelRule: r, alternation: e, ambiguityIndices: v, prefixPath: m.path }); + return { message: d, type: Ie2.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS, ruleName: r.name, occurrence: u3, alternatives: v }; + }); + i = i.concat(l2); + } + }), i; + } + x2.checkPrefixAlternativesAmbiguities = Fi3; + function fs(t4, e, r) { + var n2 = [], i = B3.map(e, function(a) { + return a.name; + }); + return B3.forEach(t4, function(a) { + var o = a.name; + if (B3.contains(i, o)) { + var s = r.buildNamespaceConflictError(a); + n2.push({ message: s, type: Ie2.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE, ruleName: o }); + } + }), n2; + } +}); +var Ui2 = R2((Je) => { + Object.defineProperty(Je, "__esModule", { value: true }); + Je.validateGrammar = Je.resolveGrammar = undefined; + var Vr = k2(), vs2 = mi(), ms = jr(), Di = mt(); + function Es2(t4) { + t4 = Vr.defaults(t4, { errMsgProvider: Di.defaultGrammarResolverErrorProvider }); + var e = {}; + return Vr.forEach(t4.rules, function(r) { + e[r.name] = r; + }), vs2.resolveGrammar(e, t4.errMsgProvider); + } + Je.resolveGrammar = Es2; + function Ts(t4) { + return t4 = Vr.defaults(t4, { errMsgProvider: Di.defaultGrammarValidatorErrorProvider }), ms.validateGrammar(t4.rules, t4.maxLookahead, t4.tokenTypes, t4.errMsgProvider, t4.grammarName); + } + Je.validateGrammar = Ts; +}); +var et3 = R2((ae3) => { + var gt = ae3 && ae3.__extends || function() { + var t4 = function(e, r) { + return t4 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t4(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t4(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(ae3, "__esModule", { value: true }); + ae3.EarlyExitException = ae3.NotAllInputParsedException = ae3.NoViableAltException = ae3.MismatchedTokenException = ae3.isRecognitionException = undefined; + var ys = k2(), Gi2 = "MismatchedTokenException", Wi3 = "NoViableAltException", Bi = "EarlyExitException", qi = "NotAllInputParsedException", ji2 = [Gi2, Wi3, Bi, qi]; + Object.freeze(ji2); + function _s(t4) { + return ys.contains(ji2, t4.name); + } + ae3.isRecognitionException = _s; + var zt = function(t4) { + gt(e, t4); + function e(r, n2) { + var i = this.constructor, a = t4.call(this, r) || this; + return a.token = n2, a.resyncedTokens = [], Object.setPrototypeOf(a, i.prototype), Error.captureStackTrace && Error.captureStackTrace(a, a.constructor), a; + } + return e; + }(Error), gs = function(t4) { + gt(e, t4); + function e(r, n2, i) { + var a = t4.call(this, r, n2) || this; + return a.previousToken = i, a.name = Gi2, a; + } + return e; + }(zt); + ae3.MismatchedTokenException = gs; + var As2 = function(t4) { + gt(e, t4); + function e(r, n2, i) { + var a = t4.call(this, r, n2) || this; + return a.previousToken = i, a.name = Wi3, a; + } + return e; + }(zt); + ae3.NoViableAltException = As2; + var Rs = function(t4) { + gt(e, t4); + function e(r, n2) { + var i = t4.call(this, r, n2) || this; + return i.name = qi, i; + } + return e; + }(zt); + ae3.NotAllInputParsedException = Rs; + var Os = function(t4) { + gt(e, t4); + function e(r, n2, i) { + var a = t4.call(this, r, n2) || this; + return a.previousToken = i, a.name = Bi, a; + } + return e; + }(zt); + ae3.EarlyExitException = Os; +}); +var zr = R2(($2) => { + Object.defineProperty($2, "__esModule", { value: true }); + $2.attemptInRepetitionRecovery = $2.Recoverable = $2.InRuleRecoveryException = $2.IN_RULE_RECOVERY_EXCEPTION = $2.EOF_FOLLOW_KEY = undefined; + var Ht = Ue(), de = k2(), Ns = et3(), Is = Mr(), ks = ce2(); + $2.EOF_FOLLOW_KEY = {}; + $2.IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException"; + function Kr2(t4) { + this.name = $2.IN_RULE_RECOVERY_EXCEPTION, this.message = t4; + } + $2.InRuleRecoveryException = Kr2; + Kr2.prototype = Error.prototype; + var Ps = function() { + function t4() { + } + return t4.prototype.initRecoverable = function(e) { + this.firstAfterRepMap = {}, this.resyncFollows = {}, this.recoveryEnabled = de.has(e, "recoveryEnabled") ? e.recoveryEnabled : ks.DEFAULT_PARSER_CONFIG.recoveryEnabled, this.recoveryEnabled && (this.attemptInRepetitionRecovery = Vi); + }, t4.prototype.getTokenToInsert = function(e) { + var r = Ht.createTokenInstance(e, "", NaN, NaN, NaN, NaN, NaN, NaN); + return r.isInsertedInRecovery = true, r; + }, t4.prototype.canTokenTypeBeInsertedInRecovery = function(e) { + return true; + }, t4.prototype.tryInRepetitionRecovery = function(e, r, n2, i) { + for (var a = this, o = this.findReSyncTokenType(), s = this.exportLexerState(), c = [], f = false, p = this.LA(1), l2 = this.LA(1), m = function() { + var v = a.LA(0), u3 = a.errorMessageProvider.buildMismatchTokenMessage({ expected: i, actual: p, previous: v, ruleName: a.getCurrRuleFullName() }), d = new Ns.MismatchedTokenException(u3, p, a.LA(0)); + d.resyncedTokens = de.dropRight(c), a.SAVE_ERROR(d); + };!f; ) + if (this.tokenMatcher(l2, i)) { + m(); + return; + } else if (n2.call(this)) { + m(), e.apply(this, r); + return; + } else + this.tokenMatcher(l2, o) ? f = true : (l2 = this.SKIP_TOKEN(), this.addToResyncTokens(l2, c)); + this.importLexerState(s); + }, t4.prototype.shouldInRepetitionRecoveryBeTried = function(e, r, n2) { + return !(n2 === false || e === undefined || r === undefined || this.tokenMatcher(this.LA(1), e) || this.isBackTracking() || this.canPerformInRuleRecovery(e, this.getFollowsForInRuleRecovery(e, r))); + }, t4.prototype.getFollowsForInRuleRecovery = function(e, r) { + var n2 = this.getCurrentGrammarPath(e, r), i = this.getNextPossibleTokenTypes(n2); + return i; + }, t4.prototype.tryInRuleRecovery = function(e, r) { + if (this.canRecoverWithSingleTokenInsertion(e, r)) { + var n2 = this.getTokenToInsert(e); + return n2; + } + if (this.canRecoverWithSingleTokenDeletion(e)) { + var i = this.SKIP_TOKEN(); + return this.consumeToken(), i; + } + throw new Kr2("sad sad panda"); + }, t4.prototype.canPerformInRuleRecovery = function(e, r) { + return this.canRecoverWithSingleTokenInsertion(e, r) || this.canRecoverWithSingleTokenDeletion(e); + }, t4.prototype.canRecoverWithSingleTokenInsertion = function(e, r) { + var n2 = this; + if (!this.canTokenTypeBeInsertedInRecovery(e) || de.isEmpty(r)) + return false; + var i = this.LA(1), a = de.find(r, function(o) { + return n2.tokenMatcher(i, o); + }) !== undefined; + return a; + }, t4.prototype.canRecoverWithSingleTokenDeletion = function(e) { + var r = this.tokenMatcher(this.LA(2), e); + return r; + }, t4.prototype.isInCurrentRuleReSyncSet = function(e) { + var r = this.getCurrFollowKey(), n2 = this.getFollowSetFromFollowKey(r); + return de.contains(n2, e); + }, t4.prototype.findReSyncTokenType = function() { + for (var e = this.flattenFollowSet(), r = this.LA(1), n2 = 2;; ) { + var i = r.tokenType; + if (de.contains(e, i)) + return i; + r = this.LA(n2), n2++; + } + }, t4.prototype.getCurrFollowKey = function() { + if (this.RULE_STACK.length === 1) + return $2.EOF_FOLLOW_KEY; + var e = this.getLastExplicitRuleShortName(), r = this.getLastExplicitRuleOccurrenceIndex(), n2 = this.getPreviousExplicitRuleShortName(); + return { ruleName: this.shortRuleNameToFullName(e), idxInCallingRule: r, inRule: this.shortRuleNameToFullName(n2) }; + }, t4.prototype.buildFullFollowKeyStack = function() { + var e = this, r = this.RULE_STACK, n2 = this.RULE_OCCURRENCE_STACK; + return de.map(r, function(i, a) { + return a === 0 ? $2.EOF_FOLLOW_KEY : { ruleName: e.shortRuleNameToFullName(i), idxInCallingRule: n2[a], inRule: e.shortRuleNameToFullName(r[a - 1]) }; + }); + }, t4.prototype.flattenFollowSet = function() { + var e = this, r = de.map(this.buildFullFollowKeyStack(), function(n2) { + return e.getFollowSetFromFollowKey(n2); + }); + return de.flatten(r); + }, t4.prototype.getFollowSetFromFollowKey = function(e) { + if (e === $2.EOF_FOLLOW_KEY) + return [Ht.EOF]; + var r = e.ruleName + e.idxInCallingRule + Is.IN + e.inRule; + return this.resyncFollows[r]; + }, t4.prototype.addToResyncTokens = function(e, r) { + return this.tokenMatcher(e, Ht.EOF) || r.push(e), r; + }, t4.prototype.reSyncTo = function(e) { + for (var r = [], n2 = this.LA(1);this.tokenMatcher(n2, e) === false; ) + n2 = this.SKIP_TOKEN(), this.addToResyncTokens(n2, r); + return de.dropRight(r); + }, t4.prototype.attemptInRepetitionRecovery = function(e, r, n2, i, a, o, s) { + }, t4.prototype.getCurrentGrammarPath = function(e, r) { + var n2 = this.getHumanReadableRuleStack(), i = de.cloneArr(this.RULE_OCCURRENCE_STACK), a = { ruleStack: n2, occurrenceStack: i, lastTok: e, lastTokOccurrence: r }; + return a; + }, t4.prototype.getHumanReadableRuleStack = function() { + var e = this; + return de.map(this.RULE_STACK, function(r) { + return e.shortRuleNameToFullName(r); + }); + }, t4; + }(); + $2.Recoverable = Ps; + function Vi(t4, e, r, n2, i, a, o) { + var s = this.getKeyForAutomaticLookahead(n2, i), c = this.firstAfterRepMap[s]; + if (c === undefined) { + var f = this.getCurrRuleFullName(), p = this.getGAstProductions()[f], l2 = new a(p, i); + c = l2.startWalking(), this.firstAfterRepMap[s] = c; + } + var { token: m, occurrence: v, isEndOfRule: u3 } = c; + this.RULE_STACK.length === 1 && u3 && m === undefined && (m = Ht.EOF, v = 1), this.shouldInRepetitionRecoveryBeTried(m, v, o) && this.tryInRepetitionRecovery(t4, e, r, m); + } + $2.attemptInRepetitionRecovery = Vi; +}); +var Yt = R2((P) => { + Object.defineProperty(P, "__esModule", { value: true }); + P.getKeyForAutomaticLookahead = P.AT_LEAST_ONE_SEP_IDX = P.MANY_SEP_IDX = P.AT_LEAST_ONE_IDX = P.MANY_IDX = P.OPTION_IDX = P.OR_IDX = P.BITS_FOR_ALT_IDX = P.BITS_FOR_RULE_IDX = P.BITS_FOR_OCCURRENCE_IDX = P.BITS_FOR_METHOD_TYPE = undefined; + P.BITS_FOR_METHOD_TYPE = 4; + P.BITS_FOR_OCCURRENCE_IDX = 8; + P.BITS_FOR_RULE_IDX = 12; + P.BITS_FOR_ALT_IDX = 8; + P.OR_IDX = 1 << P.BITS_FOR_OCCURRENCE_IDX; + P.OPTION_IDX = 2 << P.BITS_FOR_OCCURRENCE_IDX; + P.MANY_IDX = 3 << P.BITS_FOR_OCCURRENCE_IDX; + P.AT_LEAST_ONE_IDX = 4 << P.BITS_FOR_OCCURRENCE_IDX; + P.MANY_SEP_IDX = 5 << P.BITS_FOR_OCCURRENCE_IDX; + P.AT_LEAST_ONE_SEP_IDX = 6 << P.BITS_FOR_OCCURRENCE_IDX; + function Ss(t4, e, r) { + return r | e | t4; + } + P.getKeyForAutomaticLookahead = Ss; + var ic = 32 - P.BITS_FOR_ALT_IDX; +}); +var zi = R2((Xt2) => { + Object.defineProperty(Xt2, "__esModule", { value: true }); + Xt2.LooksAhead = undefined; + var be = yt2(), ge2 = k2(), Ki = ce2(), Fe = Yt(), Ve = vt(), xs = function() { + function t4() { + } + return t4.prototype.initLooksAhead = function(e) { + this.dynamicTokensEnabled = ge2.has(e, "dynamicTokensEnabled") ? e.dynamicTokensEnabled : Ki.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled, this.maxLookahead = ge2.has(e, "maxLookahead") ? e.maxLookahead : Ki.DEFAULT_PARSER_CONFIG.maxLookahead, this.lookAheadFuncsCache = ge2.isES2015MapSupported() ? new Map : [], ge2.isES2015MapSupported() ? (this.getLaFuncFromCache = this.getLaFuncFromMap, this.setLaFuncCache = this.setLaFuncCacheUsingMap) : (this.getLaFuncFromCache = this.getLaFuncFromObj, this.setLaFuncCache = this.setLaFuncUsingObj); + }, t4.prototype.preComputeLookaheadFunctions = function(e) { + var r = this; + ge2.forEach(e, function(n2) { + r.TRACE_INIT(n2.name + " Rule Lookahead", function() { + var i = Ve.collectMethods(n2), a = i.alternation, o = i.repetition, s = i.option, c = i.repetitionMandatory, f = i.repetitionMandatoryWithSeparator, p = i.repetitionWithSeparator; + ge2.forEach(a, function(l2) { + var m = l2.idx === 0 ? "" : l2.idx; + r.TRACE_INIT("" + Ve.getProductionDslName(l2) + m, function() { + var v = be.buildLookaheadFuncForOr(l2.idx, n2, l2.maxLookahead || r.maxLookahead, l2.hasPredicates, r.dynamicTokensEnabled, r.lookAheadBuilderForAlternatives), u3 = Fe.getKeyForAutomaticLookahead(r.fullRuleNameToShort[n2.name], Fe.OR_IDX, l2.idx); + r.setLaFuncCache(u3, v); + }); + }), ge2.forEach(o, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.MANY_IDX, be.PROD_TYPE.REPETITION, l2.maxLookahead, Ve.getProductionDslName(l2)); + }), ge2.forEach(s, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.OPTION_IDX, be.PROD_TYPE.OPTION, l2.maxLookahead, Ve.getProductionDslName(l2)); + }), ge2.forEach(c, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.AT_LEAST_ONE_IDX, be.PROD_TYPE.REPETITION_MANDATORY, l2.maxLookahead, Ve.getProductionDslName(l2)); + }), ge2.forEach(f, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.AT_LEAST_ONE_SEP_IDX, be.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, l2.maxLookahead, Ve.getProductionDslName(l2)); + }), ge2.forEach(p, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.MANY_SEP_IDX, be.PROD_TYPE.REPETITION_WITH_SEPARATOR, l2.maxLookahead, Ve.getProductionDslName(l2)); + }); + }); + }); + }, t4.prototype.computeLookaheadFunc = function(e, r, n2, i, a, o) { + var s = this; + this.TRACE_INIT("" + o + (r === 0 ? "" : r), function() { + var c = be.buildLookaheadFuncForOptionalProd(r, e, a || s.maxLookahead, s.dynamicTokensEnabled, i, s.lookAheadBuilderForOptional), f = Fe.getKeyForAutomaticLookahead(s.fullRuleNameToShort[e.name], n2, r); + s.setLaFuncCache(f, c); + }); + }, t4.prototype.lookAheadBuilderForOptional = function(e, r, n2) { + return be.buildSingleAlternativeLookaheadFunction(e, r, n2); + }, t4.prototype.lookAheadBuilderForAlternatives = function(e, r, n2, i) { + return be.buildAlternativesLookAheadFunc(e, r, n2, i); + }, t4.prototype.getKeyForAutomaticLookahead = function(e, r) { + var n2 = this.getLastExplicitRuleShortName(); + return Fe.getKeyForAutomaticLookahead(n2, e, r); + }, t4.prototype.getLaFuncFromCache = function(e) { + }, t4.prototype.getLaFuncFromMap = function(e) { + return this.lookAheadFuncsCache.get(e); + }, t4.prototype.getLaFuncFromObj = function(e) { + return this.lookAheadFuncsCache[e]; + }, t4.prototype.setLaFuncCache = function(e, r) { + }, t4.prototype.setLaFuncCacheUsingMap = function(e, r) { + this.lookAheadFuncsCache.set(e, r); + }, t4.prototype.setLaFuncUsingObj = function(e, r) { + this.lookAheadFuncsCache[e] = r; + }, t4; + }(); + Xt2.LooksAhead = xs; +}); +var Hi = R2((ke) => { + Object.defineProperty(ke, "__esModule", { value: true }); + ke.addNoneTerminalToCst = ke.addTerminalToCst = ke.setNodeLocationFull = ke.setNodeLocationOnlyOffset = undefined; + function Cs(t4, e) { + isNaN(t4.startOffset) === true ? (t4.startOffset = e.startOffset, t4.endOffset = e.endOffset) : t4.endOffset < e.endOffset && (t4.endOffset = e.endOffset); + } + ke.setNodeLocationOnlyOffset = Cs; + function Ls(t4, e) { + isNaN(t4.startOffset) === true ? (t4.startOffset = e.startOffset, t4.startColumn = e.startColumn, t4.startLine = e.startLine, t4.endOffset = e.endOffset, t4.endColumn = e.endColumn, t4.endLine = e.endLine) : t4.endOffset < e.endOffset && (t4.endOffset = e.endOffset, t4.endColumn = e.endColumn, t4.endLine = e.endLine); + } + ke.setNodeLocationFull = Ls; + function Ms(t4, e, r) { + t4.children[r] === undefined ? t4.children[r] = [e] : t4.children[r].push(e); + } + ke.addTerminalToCst = Ms; + function bs(t4, e, r) { + t4.children[e] === undefined ? t4.children[e] = [r] : t4.children[e].push(r); + } + ke.addNoneTerminalToCst = bs; +}); +var Hr = R2((Be) => { + Object.defineProperty(Be, "__esModule", { value: true }); + Be.defineNameProp = Be.functionName = Be.classNameFromInstance = undefined; + var Fs = k2(); + function ws2(t4) { + return Yi(t4.constructor); + } + Be.classNameFromInstance = ws2; + var Xi = "name"; + function Yi(t4) { + var e = t4.name; + return e || "anonymous"; + } + Be.functionName = Yi; + function Ds2(t4, e) { + var r = Object.getOwnPropertyDescriptor(t4, Xi); + return Fs.isUndefined(r) || r.configurable ? (Object.defineProperty(t4, Xi, { enumerable: false, configurable: true, writable: false, value: e }), true) : false; + } + Be.defineNameProp = Ds2; +}); +var ea = R2((Y) => { + Object.defineProperty(Y, "__esModule", { value: true }); + Y.validateRedundantMethods = Y.validateMissingCstMethods = Y.validateVisitor = Y.CstVisitorDefinitionError = Y.createBaseVisitorConstructorWithDefaults = Y.createBaseSemanticVisitorConstructor = Y.defaultVisit = undefined; + var ve = k2(), At2 = Hr(); + function $i(t4, e) { + for (var r = ve.keys(t4), n2 = r.length, i = 0;i < n2; i++) + for (var a = r[i], o = t4[a], s = o.length, c = 0;c < s; c++) { + var f = o[c]; + f.tokenTypeIdx === undefined && this[f.name](f.children, e); + } + } + Y.defaultVisit = $i; + function Us(t4, e) { + var r = function() { + }; + At2.defineNameProp(r, t4 + "BaseSemantics"); + var n2 = { visit: function(i, a) { + if (ve.isArray(i) && (i = i[0]), !ve.isUndefined(i)) + return this[i.name](i.children, a); + }, validateVisitor: function() { + var i = Zi(this, e); + if (!ve.isEmpty(i)) { + var a = ve.map(i, function(o) { + return o.msg; + }); + throw Error("Errors Detected in CST Visitor <" + At2.functionName(this.constructor) + `>: + ` + ("" + a.join(` + +`).replace(/\n/g, ` + `))); + } + } }; + return r.prototype = n2, r.prototype.constructor = r, r._RULE_NAMES = e, r; + } + Y.createBaseSemanticVisitorConstructor = Us; + function Gs(t4, e, r) { + var n2 = function() { + }; + At2.defineNameProp(n2, t4 + "BaseSemanticsWithDefaults"); + var i = Object.create(r.prototype); + return ve.forEach(e, function(a) { + i[a] = $i; + }), n2.prototype = i, n2.prototype.constructor = n2, n2; + } + Y.createBaseVisitorConstructorWithDefaults = Gs; + var Yr; + (function(t4) { + t4[t4.REDUNDANT_METHOD = 0] = "REDUNDANT_METHOD", t4[t4.MISSING_METHOD = 1] = "MISSING_METHOD"; + })(Yr = Y.CstVisitorDefinitionError || (Y.CstVisitorDefinitionError = {})); + function Zi(t4, e) { + var r = Qi(t4, e), n2 = Ji(t4, e); + return r.concat(n2); + } + Y.validateVisitor = Zi; + function Qi(t4, e) { + var r = ve.map(e, function(n2) { + if (!ve.isFunction(t4[n2])) + return { msg: "Missing visitor method: <" + n2 + "> on " + At2.functionName(t4.constructor) + " CST Visitor.", type: Yr.MISSING_METHOD, methodName: n2 }; + }); + return ve.compact(r); + } + Y.validateMissingCstMethods = Qi; + var Ws2 = ["constructor", "visit", "validateVisitor"]; + function Ji(t4, e) { + var r = []; + for (var n2 in t4) + ve.isFunction(t4[n2]) && !ve.contains(Ws2, n2) && !ve.contains(e, n2) && r.push({ msg: "Redundant visitor method: <" + n2 + "> on " + At2.functionName(t4.constructor) + ` CST Visitor +There is no Grammar Rule corresponding to this method's name. +`, type: Yr.REDUNDANT_METHOD, methodName: n2 }); + return r; + } + Y.validateRedundantMethods = Ji; +}); +var ra = R2(($t) => { + Object.defineProperty($t, "__esModule", { value: true }); + $t.TreeBuilder = undefined; + var tt3 = Hi(), K = k2(), ta = ea(), Bs = ce2(), qs = function() { + function t4() { + } + return t4.prototype.initTreeBuilder = function(e) { + if (this.CST_STACK = [], this.outputCst = e.outputCst, this.nodeLocationTracking = K.has(e, "nodeLocationTracking") ? e.nodeLocationTracking : Bs.DEFAULT_PARSER_CONFIG.nodeLocationTracking, !this.outputCst) + this.cstInvocationStateUpdate = K.NOOP, this.cstFinallyStateUpdate = K.NOOP, this.cstPostTerminal = K.NOOP, this.cstPostNonTerminal = K.NOOP, this.cstPostRule = K.NOOP; + else if (/full/i.test(this.nodeLocationTracking)) + this.recoveryEnabled ? (this.setNodeLocationFromToken = tt3.setNodeLocationFull, this.setNodeLocationFromNode = tt3.setNodeLocationFull, this.cstPostRule = K.NOOP, this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery) : (this.setNodeLocationFromToken = K.NOOP, this.setNodeLocationFromNode = K.NOOP, this.cstPostRule = this.cstPostRuleFull, this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular); + else if (/onlyOffset/i.test(this.nodeLocationTracking)) + this.recoveryEnabled ? (this.setNodeLocationFromToken = tt3.setNodeLocationOnlyOffset, this.setNodeLocationFromNode = tt3.setNodeLocationOnlyOffset, this.cstPostRule = K.NOOP, this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery) : (this.setNodeLocationFromToken = K.NOOP, this.setNodeLocationFromNode = K.NOOP, this.cstPostRule = this.cstPostRuleOnlyOffset, this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular); + else if (/none/i.test(this.nodeLocationTracking)) + this.setNodeLocationFromToken = K.NOOP, this.setNodeLocationFromNode = K.NOOP, this.cstPostRule = K.NOOP, this.setInitialNodeLocation = K.NOOP; + else + throw Error('Invalid config option: "' + e.nodeLocationTracking + '"'); + }, t4.prototype.setInitialNodeLocationOnlyOffsetRecovery = function(e) { + e.location = { startOffset: NaN, endOffset: NaN }; + }, t4.prototype.setInitialNodeLocationOnlyOffsetRegular = function(e) { + e.location = { startOffset: this.LA(1).startOffset, endOffset: NaN }; + }, t4.prototype.setInitialNodeLocationFullRecovery = function(e) { + e.location = { startOffset: NaN, startLine: NaN, startColumn: NaN, endOffset: NaN, endLine: NaN, endColumn: NaN }; + }, t4.prototype.setInitialNodeLocationFullRegular = function(e) { + var r = this.LA(1); + e.location = { startOffset: r.startOffset, startLine: r.startLine, startColumn: r.startColumn, endOffset: NaN, endLine: NaN, endColumn: NaN }; + }, t4.prototype.cstInvocationStateUpdate = function(e, r) { + var n2 = { name: e, children: {} }; + this.setInitialNodeLocation(n2), this.CST_STACK.push(n2); + }, t4.prototype.cstFinallyStateUpdate = function() { + this.CST_STACK.pop(); + }, t4.prototype.cstPostRuleFull = function(e) { + var r = this.LA(0), n2 = e.location; + n2.startOffset <= r.startOffset ? (n2.endOffset = r.endOffset, n2.endLine = r.endLine, n2.endColumn = r.endColumn) : (n2.startOffset = NaN, n2.startLine = NaN, n2.startColumn = NaN); + }, t4.prototype.cstPostRuleOnlyOffset = function(e) { + var r = this.LA(0), n2 = e.location; + n2.startOffset <= r.startOffset ? n2.endOffset = r.endOffset : n2.startOffset = NaN; + }, t4.prototype.cstPostTerminal = function(e, r) { + var n2 = this.CST_STACK[this.CST_STACK.length - 1]; + tt3.addTerminalToCst(n2, r, e), this.setNodeLocationFromToken(n2.location, r); + }, t4.prototype.cstPostNonTerminal = function(e, r) { + var n2 = this.CST_STACK[this.CST_STACK.length - 1]; + tt3.addNoneTerminalToCst(n2, r, e), this.setNodeLocationFromNode(n2.location, e.location); + }, t4.prototype.getBaseCstVisitorConstructor = function() { + if (K.isUndefined(this.baseCstVisitorConstructor)) { + var e = ta.createBaseSemanticVisitorConstructor(this.className, K.keys(this.gastProductionsCache)); + return this.baseCstVisitorConstructor = e, e; + } + return this.baseCstVisitorConstructor; + }, t4.prototype.getBaseCstVisitorConstructorWithDefaults = function() { + if (K.isUndefined(this.baseCstVisitorWithDefaultsConstructor)) { + var e = ta.createBaseVisitorConstructorWithDefaults(this.className, K.keys(this.gastProductionsCache), this.getBaseCstVisitorConstructor()); + return this.baseCstVisitorWithDefaultsConstructor = e, e; + } + return this.baseCstVisitorWithDefaultsConstructor; + }, t4.prototype.getLastExplicitRuleShortName = function() { + var e = this.RULE_STACK; + return e[e.length - 1]; + }, t4.prototype.getPreviousExplicitRuleShortName = function() { + var e = this.RULE_STACK; + return e[e.length - 2]; + }, t4.prototype.getLastExplicitRuleOccurrenceIndex = function() { + var e = this.RULE_OCCURRENCE_STACK; + return e[e.length - 1]; + }, t4; + }(); + $t.TreeBuilder = qs; +}); +var ia = R2((Zt) => { + Object.defineProperty(Zt, "__esModule", { value: true }); + Zt.LexerAdapter = undefined; + var na = ce2(), js = function() { + function t4() { + } + return t4.prototype.initLexerAdapter = function() { + this.tokVector = [], this.tokVectorLength = 0, this.currIdx = -1; + }, Object.defineProperty(t4.prototype, "input", { get: function() { + return this.tokVector; + }, set: function(e) { + if (this.selfAnalysisDone !== true) + throw Error("Missing invocation at the end of the Parser's constructor."); + this.reset(), this.tokVector = e, this.tokVectorLength = e.length; + }, enumerable: false, configurable: true }), t4.prototype.SKIP_TOKEN = function() { + return this.currIdx <= this.tokVector.length - 2 ? (this.consumeToken(), this.LA(1)) : na.END_OF_FILE; + }, t4.prototype.LA = function(e) { + var r = this.currIdx + e; + return r < 0 || this.tokVectorLength <= r ? na.END_OF_FILE : this.tokVector[r]; + }, t4.prototype.consumeToken = function() { + this.currIdx++; + }, t4.prototype.exportLexerState = function() { + return this.currIdx; + }, t4.prototype.importLexerState = function(e) { + this.currIdx = e; + }, t4.prototype.resetLexerState = function() { + this.currIdx = -1; + }, t4.prototype.moveToTerminatedState = function() { + this.currIdx = this.tokVector.length - 1; + }, t4.prototype.getLexerPosition = function() { + return this.exportLexerState(); + }, t4; + }(); + Zt.LexerAdapter = js; +}); +var oa = R2((Qt) => { + Object.defineProperty(Qt, "__esModule", { value: true }); + Qt.RecognizerApi = undefined; + var aa = k2(), Vs = et3(), Xr = ce2(), Ks2 = mt(), zs = jr(), Hs = ne(), Ys = function() { + function t4() { + } + return t4.prototype.ACTION = function(e) { + return e.call(this); + }, t4.prototype.consume = function(e, r, n2) { + return this.consumeInternal(r, e, n2); + }, t4.prototype.subrule = function(e, r, n2) { + return this.subruleInternal(r, e, n2); + }, t4.prototype.option = function(e, r) { + return this.optionInternal(r, e); + }, t4.prototype.or = function(e, r) { + return this.orInternal(r, e); + }, t4.prototype.many = function(e, r) { + return this.manyInternal(e, r); + }, t4.prototype.atLeastOne = function(e, r) { + return this.atLeastOneInternal(e, r); + }, t4.prototype.CONSUME = function(e, r) { + return this.consumeInternal(e, 0, r); + }, t4.prototype.CONSUME1 = function(e, r) { + return this.consumeInternal(e, 1, r); + }, t4.prototype.CONSUME2 = function(e, r) { + return this.consumeInternal(e, 2, r); + }, t4.prototype.CONSUME3 = function(e, r) { + return this.consumeInternal(e, 3, r); + }, t4.prototype.CONSUME4 = function(e, r) { + return this.consumeInternal(e, 4, r); + }, t4.prototype.CONSUME5 = function(e, r) { + return this.consumeInternal(e, 5, r); + }, t4.prototype.CONSUME6 = function(e, r) { + return this.consumeInternal(e, 6, r); + }, t4.prototype.CONSUME7 = function(e, r) { + return this.consumeInternal(e, 7, r); + }, t4.prototype.CONSUME8 = function(e, r) { + return this.consumeInternal(e, 8, r); + }, t4.prototype.CONSUME9 = function(e, r) { + return this.consumeInternal(e, 9, r); + }, t4.prototype.SUBRULE = function(e, r) { + return this.subruleInternal(e, 0, r); + }, t4.prototype.SUBRULE1 = function(e, r) { + return this.subruleInternal(e, 1, r); + }, t4.prototype.SUBRULE2 = function(e, r) { + return this.subruleInternal(e, 2, r); + }, t4.prototype.SUBRULE3 = function(e, r) { + return this.subruleInternal(e, 3, r); + }, t4.prototype.SUBRULE4 = function(e, r) { + return this.subruleInternal(e, 4, r); + }, t4.prototype.SUBRULE5 = function(e, r) { + return this.subruleInternal(e, 5, r); + }, t4.prototype.SUBRULE6 = function(e, r) { + return this.subruleInternal(e, 6, r); + }, t4.prototype.SUBRULE7 = function(e, r) { + return this.subruleInternal(e, 7, r); + }, t4.prototype.SUBRULE8 = function(e, r) { + return this.subruleInternal(e, 8, r); + }, t4.prototype.SUBRULE9 = function(e, r) { + return this.subruleInternal(e, 9, r); + }, t4.prototype.OPTION = function(e) { + return this.optionInternal(e, 0); + }, t4.prototype.OPTION1 = function(e) { + return this.optionInternal(e, 1); + }, t4.prototype.OPTION2 = function(e) { + return this.optionInternal(e, 2); + }, t4.prototype.OPTION3 = function(e) { + return this.optionInternal(e, 3); + }, t4.prototype.OPTION4 = function(e) { + return this.optionInternal(e, 4); + }, t4.prototype.OPTION5 = function(e) { + return this.optionInternal(e, 5); + }, t4.prototype.OPTION6 = function(e) { + return this.optionInternal(e, 6); + }, t4.prototype.OPTION7 = function(e) { + return this.optionInternal(e, 7); + }, t4.prototype.OPTION8 = function(e) { + return this.optionInternal(e, 8); + }, t4.prototype.OPTION9 = function(e) { + return this.optionInternal(e, 9); + }, t4.prototype.OR = function(e) { + return this.orInternal(e, 0); + }, t4.prototype.OR1 = function(e) { + return this.orInternal(e, 1); + }, t4.prototype.OR2 = function(e) { + return this.orInternal(e, 2); + }, t4.prototype.OR3 = function(e) { + return this.orInternal(e, 3); + }, t4.prototype.OR4 = function(e) { + return this.orInternal(e, 4); + }, t4.prototype.OR5 = function(e) { + return this.orInternal(e, 5); + }, t4.prototype.OR6 = function(e) { + return this.orInternal(e, 6); + }, t4.prototype.OR7 = function(e) { + return this.orInternal(e, 7); + }, t4.prototype.OR8 = function(e) { + return this.orInternal(e, 8); + }, t4.prototype.OR9 = function(e) { + return this.orInternal(e, 9); + }, t4.prototype.MANY = function(e) { + this.manyInternal(0, e); + }, t4.prototype.MANY1 = function(e) { + this.manyInternal(1, e); + }, t4.prototype.MANY2 = function(e) { + this.manyInternal(2, e); + }, t4.prototype.MANY3 = function(e) { + this.manyInternal(3, e); + }, t4.prototype.MANY4 = function(e) { + this.manyInternal(4, e); + }, t4.prototype.MANY5 = function(e) { + this.manyInternal(5, e); + }, t4.prototype.MANY6 = function(e) { + this.manyInternal(6, e); + }, t4.prototype.MANY7 = function(e) { + this.manyInternal(7, e); + }, t4.prototype.MANY8 = function(e) { + this.manyInternal(8, e); + }, t4.prototype.MANY9 = function(e) { + this.manyInternal(9, e); + }, t4.prototype.MANY_SEP = function(e) { + this.manySepFirstInternal(0, e); + }, t4.prototype.MANY_SEP1 = function(e) { + this.manySepFirstInternal(1, e); + }, t4.prototype.MANY_SEP2 = function(e) { + this.manySepFirstInternal(2, e); + }, t4.prototype.MANY_SEP3 = function(e) { + this.manySepFirstInternal(3, e); + }, t4.prototype.MANY_SEP4 = function(e) { + this.manySepFirstInternal(4, e); + }, t4.prototype.MANY_SEP5 = function(e) { + this.manySepFirstInternal(5, e); + }, t4.prototype.MANY_SEP6 = function(e) { + this.manySepFirstInternal(6, e); + }, t4.prototype.MANY_SEP7 = function(e) { + this.manySepFirstInternal(7, e); + }, t4.prototype.MANY_SEP8 = function(e) { + this.manySepFirstInternal(8, e); + }, t4.prototype.MANY_SEP9 = function(e) { + this.manySepFirstInternal(9, e); + }, t4.prototype.AT_LEAST_ONE = function(e) { + this.atLeastOneInternal(0, e); + }, t4.prototype.AT_LEAST_ONE1 = function(e) { + return this.atLeastOneInternal(1, e); + }, t4.prototype.AT_LEAST_ONE2 = function(e) { + this.atLeastOneInternal(2, e); + }, t4.prototype.AT_LEAST_ONE3 = function(e) { + this.atLeastOneInternal(3, e); + }, t4.prototype.AT_LEAST_ONE4 = function(e) { + this.atLeastOneInternal(4, e); + }, t4.prototype.AT_LEAST_ONE5 = function(e) { + this.atLeastOneInternal(5, e); + }, t4.prototype.AT_LEAST_ONE6 = function(e) { + this.atLeastOneInternal(6, e); + }, t4.prototype.AT_LEAST_ONE7 = function(e) { + this.atLeastOneInternal(7, e); + }, t4.prototype.AT_LEAST_ONE8 = function(e) { + this.atLeastOneInternal(8, e); + }, t4.prototype.AT_LEAST_ONE9 = function(e) { + this.atLeastOneInternal(9, e); + }, t4.prototype.AT_LEAST_ONE_SEP = function(e) { + this.atLeastOneSepFirstInternal(0, e); + }, t4.prototype.AT_LEAST_ONE_SEP1 = function(e) { + this.atLeastOneSepFirstInternal(1, e); + }, t4.prototype.AT_LEAST_ONE_SEP2 = function(e) { + this.atLeastOneSepFirstInternal(2, e); + }, t4.prototype.AT_LEAST_ONE_SEP3 = function(e) { + this.atLeastOneSepFirstInternal(3, e); + }, t4.prototype.AT_LEAST_ONE_SEP4 = function(e) { + this.atLeastOneSepFirstInternal(4, e); + }, t4.prototype.AT_LEAST_ONE_SEP5 = function(e) { + this.atLeastOneSepFirstInternal(5, e); + }, t4.prototype.AT_LEAST_ONE_SEP6 = function(e) { + this.atLeastOneSepFirstInternal(6, e); + }, t4.prototype.AT_LEAST_ONE_SEP7 = function(e) { + this.atLeastOneSepFirstInternal(7, e); + }, t4.prototype.AT_LEAST_ONE_SEP8 = function(e) { + this.atLeastOneSepFirstInternal(8, e); + }, t4.prototype.AT_LEAST_ONE_SEP9 = function(e) { + this.atLeastOneSepFirstInternal(9, e); + }, t4.prototype.RULE = function(e, r, n2) { + if (n2 === undefined && (n2 = Xr.DEFAULT_RULE_CONFIG), aa.contains(this.definedRulesNames, e)) { + var i = Ks2.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({ topLevelRule: e, grammarName: this.className }), a = { message: i, type: Xr.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, ruleName: e }; + this.definitionErrors.push(a); + } + this.definedRulesNames.push(e); + var o = this.defineRule(e, r, n2); + return this[e] = o, o; + }, t4.prototype.OVERRIDE_RULE = function(e, r, n2) { + n2 === undefined && (n2 = Xr.DEFAULT_RULE_CONFIG); + var i = []; + i = i.concat(zs.validateRuleIsOverridden(e, this.definedRulesNames, this.className)), this.definitionErrors = this.definitionErrors.concat(i); + var a = this.defineRule(e, r, n2); + return this[e] = a, a; + }, t4.prototype.BACKTRACK = function(e, r) { + return function() { + this.isBackTrackingStack.push(1); + var n2 = this.saveRecogState(); + try { + return e.apply(this, r), true; + } catch (i) { + if (Vs.isRecognitionException(i)) + return false; + throw i; + } finally { + this.reloadRecogState(n2), this.isBackTrackingStack.pop(); + } + }; + }, t4.prototype.getGAstProductions = function() { + return this.gastProductionsCache; + }, t4.prototype.getSerializedGastProductions = function() { + return Hs.serializeGrammar(aa.values(this.gastProductionsCache)); + }, t4; + }(); + Qt.RecognizerApi = Ys; +}); +var la = R2((Jt2) => { + Object.defineProperty(Jt2, "__esModule", { value: true }); + Jt2.RecognizerEngine = undefined; + var q2 = k2(), le = Yt(), er = et3(), sa = yt2(), rt2 = Tt3(), ua = ce2(), Xs = zr(), ca = Ue(), Rt = Xe(), $s = Hr(), Zs = function() { + function t4() { + } + return t4.prototype.initRecognizerEngine = function(e, r) { + if (this.className = $s.classNameFromInstance(this), this.shortRuleNameToFull = {}, this.fullRuleNameToShort = {}, this.ruleShortNameIdx = 256, this.tokenMatcher = Rt.tokenStructuredMatcherNoCategories, this.definedRulesNames = [], this.tokensMap = {}, this.isBackTrackingStack = [], this.RULE_STACK = [], this.RULE_OCCURRENCE_STACK = [], this.gastProductionsCache = {}, q2.has(r, "serializedGrammar")) + throw Error(`The Parser's configuration can no longer contain a property. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 + For Further details.`); + if (q2.isArray(e)) { + if (q2.isEmpty(e)) + throw Error(`A Token Vocabulary cannot be empty. + Note that the first argument for the parser constructor + is no longer a Token vector (since v4.0).`); + if (typeof e[0].startOffset == "number") + throw Error(`The Parser constructor no longer accepts a token vector as the first argument. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 + For Further details.`); + } + if (q2.isArray(e)) + this.tokensMap = q2.reduce(e, function(o, s) { + return o[s.name] = s, o; + }, {}); + else if (q2.has(e, "modes") && q2.every(q2.flatten(q2.values(e.modes)), Rt.isTokenType)) { + var n2 = q2.flatten(q2.values(e.modes)), i = q2.uniq(n2); + this.tokensMap = q2.reduce(i, function(o, s) { + return o[s.name] = s, o; + }, {}); + } else if (q2.isObject(e)) + this.tokensMap = q2.cloneObj(e); + else + throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition"); + this.tokensMap.EOF = ca.EOF; + var a = q2.every(q2.values(e), function(o) { + return q2.isEmpty(o.categoryMatches); + }); + this.tokenMatcher = a ? Rt.tokenStructuredMatcherNoCategories : Rt.tokenStructuredMatcher, Rt.augmentTokenTypes(q2.values(this.tokensMap)); + }, t4.prototype.defineRule = function(e, r, n2) { + if (this.selfAnalysisDone) + throw Error("Grammar rule <" + e + `> may not be defined after the 'performSelfAnalysis' method has been called' +Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`); + var i = q2.has(n2, "resyncEnabled") ? n2.resyncEnabled : ua.DEFAULT_RULE_CONFIG.resyncEnabled, a = q2.has(n2, "recoveryValueFunc") ? n2.recoveryValueFunc : ua.DEFAULT_RULE_CONFIG.recoveryValueFunc, o = this.ruleShortNameIdx << le.BITS_FOR_METHOD_TYPE + le.BITS_FOR_OCCURRENCE_IDX; + this.ruleShortNameIdx++, this.shortRuleNameToFull[o] = e, this.fullRuleNameToShort[e] = o; + function s(p) { + try { + if (this.outputCst === true) { + r.apply(this, p); + var l2 = this.CST_STACK[this.CST_STACK.length - 1]; + return this.cstPostRule(l2), l2; + } else + return r.apply(this, p); + } catch (m) { + return this.invokeRuleCatch(m, i, a); + } finally { + this.ruleFinallyStateUpdate(); + } + } + var c = function(p, l2) { + return p === undefined && (p = 0), this.ruleInvocationStateUpdate(o, e, p), s.call(this, l2); + }, f = "ruleName"; + return c[f] = e, c.originalGrammarAction = r, c; + }, t4.prototype.invokeRuleCatch = function(e, r, n2) { + var i = this.RULE_STACK.length === 1, a = r && !this.isBackTracking() && this.recoveryEnabled; + if (er.isRecognitionException(e)) { + var o = e; + if (a) { + var s = this.findReSyncTokenType(); + if (this.isInCurrentRuleReSyncSet(s)) + if (o.resyncedTokens = this.reSyncTo(s), this.outputCst) { + var c = this.CST_STACK[this.CST_STACK.length - 1]; + return c.recoveredNode = true, c; + } else + return n2(); + else { + if (this.outputCst) { + var c = this.CST_STACK[this.CST_STACK.length - 1]; + c.recoveredNode = true, o.partialCstResult = c; + } + throw o; + } + } else { + if (i) + return this.moveToTerminatedState(), n2(); + throw o; + } + } else + throw e; + }, t4.prototype.optionInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.OPTION_IDX, r); + return this.optionInternalLogic(e, r, n2); + }, t4.prototype.optionInternalLogic = function(e, r, n2) { + var i = this, a = this.getLaFuncFromCache(n2), o, s; + if (e.DEF !== undefined) { + if (o = e.DEF, s = e.GATE, s !== undefined) { + var c = a; + a = function() { + return s.call(i) && c.call(i); + }; + } + } else + o = e; + if (a.call(this) === true) + return o.call(this); + }, t4.prototype.atLeastOneInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.AT_LEAST_ONE_IDX, e); + return this.atLeastOneInternalLogic(e, r, n2); + }, t4.prototype.atLeastOneInternalLogic = function(e, r, n2) { + var i = this, a = this.getLaFuncFromCache(n2), o, s; + if (r.DEF !== undefined) { + if (o = r.DEF, s = r.GATE, s !== undefined) { + var c = a; + a = function() { + return s.call(i) && c.call(i); + }; + } + } else + o = r; + if (a.call(this) === true) + for (var f = this.doSingleRepetition(o);a.call(this) === true && f === true; ) + f = this.doSingleRepetition(o); + else + throw this.raiseEarlyExitException(e, sa.PROD_TYPE.REPETITION_MANDATORY, r.ERR_MSG); + this.attemptInRepetitionRecovery(this.atLeastOneInternal, [e, r], a, le.AT_LEAST_ONE_IDX, e, rt2.NextTerminalAfterAtLeastOneWalker); + }, t4.prototype.atLeastOneSepFirstInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.AT_LEAST_ONE_SEP_IDX, e); + this.atLeastOneSepFirstInternalLogic(e, r, n2); + }, t4.prototype.atLeastOneSepFirstInternalLogic = function(e, r, n2) { + var i = this, a = r.DEF, o = r.SEP, s = this.getLaFuncFromCache(n2); + if (s.call(this) === true) { + a.call(this); + for (var c = function() { + return i.tokenMatcher(i.LA(1), o); + };this.tokenMatcher(this.LA(1), o) === true; ) + this.CONSUME(o), a.call(this); + this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [e, o, c, a, rt2.NextTerminalAfterAtLeastOneSepWalker], c, le.AT_LEAST_ONE_SEP_IDX, e, rt2.NextTerminalAfterAtLeastOneSepWalker); + } else + throw this.raiseEarlyExitException(e, sa.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, r.ERR_MSG); + }, t4.prototype.manyInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.MANY_IDX, e); + return this.manyInternalLogic(e, r, n2); + }, t4.prototype.manyInternalLogic = function(e, r, n2) { + var i = this, a = this.getLaFuncFromCache(n2), o, s; + if (r.DEF !== undefined) { + if (o = r.DEF, s = r.GATE, s !== undefined) { + var c = a; + a = function() { + return s.call(i) && c.call(i); + }; + } + } else + o = r; + for (var f = true;a.call(this) === true && f === true; ) + f = this.doSingleRepetition(o); + this.attemptInRepetitionRecovery(this.manyInternal, [e, r], a, le.MANY_IDX, e, rt2.NextTerminalAfterManyWalker, f); + }, t4.prototype.manySepFirstInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.MANY_SEP_IDX, e); + this.manySepFirstInternalLogic(e, r, n2); + }, t4.prototype.manySepFirstInternalLogic = function(e, r, n2) { + var i = this, a = r.DEF, o = r.SEP, s = this.getLaFuncFromCache(n2); + if (s.call(this) === true) { + a.call(this); + for (var c = function() { + return i.tokenMatcher(i.LA(1), o); + };this.tokenMatcher(this.LA(1), o) === true; ) + this.CONSUME(o), a.call(this); + this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [e, o, c, a, rt2.NextTerminalAfterManySepWalker], c, le.MANY_SEP_IDX, e, rt2.NextTerminalAfterManySepWalker); + } + }, t4.prototype.repetitionSepSecondInternal = function(e, r, n2, i, a) { + for (;n2(); ) + this.CONSUME(r), i.call(this); + this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [e, r, n2, i, a], n2, le.AT_LEAST_ONE_SEP_IDX, e, a); + }, t4.prototype.doSingleRepetition = function(e) { + var r = this.getLexerPosition(); + e.call(this); + var n2 = this.getLexerPosition(); + return n2 > r; + }, t4.prototype.orInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.OR_IDX, r), i = q2.isArray(e) ? e : e.DEF, a = this.getLaFuncFromCache(n2), o = a.call(this, i); + if (o !== undefined) { + var s = i[o]; + return s.ALT.call(this); + } + this.raiseNoAltException(r, e.ERR_MSG); + }, t4.prototype.ruleFinallyStateUpdate = function() { + if (this.RULE_STACK.pop(), this.RULE_OCCURRENCE_STACK.pop(), this.cstFinallyStateUpdate(), this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) { + var e = this.LA(1), r = this.errorMessageProvider.buildNotAllInputParsedMessage({ firstRedundant: e, ruleName: this.getCurrRuleFullName() }); + this.SAVE_ERROR(new er.NotAllInputParsedException(r, e)); + } + }, t4.prototype.subruleInternal = function(e, r, n2) { + var i; + try { + var a = n2 !== undefined ? n2.ARGS : undefined; + return i = e.call(this, r, a), this.cstPostNonTerminal(i, n2 !== undefined && n2.LABEL !== undefined ? n2.LABEL : e.ruleName), i; + } catch (o) { + this.subruleInternalError(o, n2, e.ruleName); + } + }, t4.prototype.subruleInternalError = function(e, r, n2) { + throw er.isRecognitionException(e) && e.partialCstResult !== undefined && (this.cstPostNonTerminal(e.partialCstResult, r !== undefined && r.LABEL !== undefined ? r.LABEL : n2), delete e.partialCstResult), e; + }, t4.prototype.consumeInternal = function(e, r, n2) { + var i; + try { + var a = this.LA(1); + this.tokenMatcher(a, e) === true ? (this.consumeToken(), i = a) : this.consumeInternalError(e, a, n2); + } catch (o) { + i = this.consumeInternalRecovery(e, r, o); + } + return this.cstPostTerminal(n2 !== undefined && n2.LABEL !== undefined ? n2.LABEL : e.name, i), i; + }, t4.prototype.consumeInternalError = function(e, r, n2) { + var i, a = this.LA(0); + throw n2 !== undefined && n2.ERR_MSG ? i = n2.ERR_MSG : i = this.errorMessageProvider.buildMismatchTokenMessage({ expected: e, actual: r, previous: a, ruleName: this.getCurrRuleFullName() }), this.SAVE_ERROR(new er.MismatchedTokenException(i, r, a)); + }, t4.prototype.consumeInternalRecovery = function(e, r, n2) { + if (this.recoveryEnabled && n2.name === "MismatchedTokenException" && !this.isBackTracking()) { + var i = this.getFollowsForInRuleRecovery(e, r); + try { + return this.tryInRuleRecovery(e, i); + } catch (a) { + throw a.name === Xs.IN_RULE_RECOVERY_EXCEPTION ? n2 : a; + } + } else + throw n2; + }, t4.prototype.saveRecogState = function() { + var e = this.errors, r = q2.cloneArr(this.RULE_STACK); + return { errors: e, lexerState: this.exportLexerState(), RULE_STACK: r, CST_STACK: this.CST_STACK }; + }, t4.prototype.reloadRecogState = function(e) { + this.errors = e.errors, this.importLexerState(e.lexerState), this.RULE_STACK = e.RULE_STACK; + }, t4.prototype.ruleInvocationStateUpdate = function(e, r, n2) { + this.RULE_OCCURRENCE_STACK.push(n2), this.RULE_STACK.push(e), this.cstInvocationStateUpdate(r, e); + }, t4.prototype.isBackTracking = function() { + return this.isBackTrackingStack.length !== 0; + }, t4.prototype.getCurrRuleFullName = function() { + var e = this.getLastExplicitRuleShortName(); + return this.shortRuleNameToFull[e]; + }, t4.prototype.shortRuleNameToFullName = function(e) { + return this.shortRuleNameToFull[e]; + }, t4.prototype.isAtEndOfInput = function() { + return this.tokenMatcher(this.LA(1), ca.EOF); + }, t4.prototype.reset = function() { + this.resetLexerState(), this.isBackTrackingStack = [], this.errors = [], this.RULE_STACK = [], this.CST_STACK = [], this.RULE_OCCURRENCE_STACK = []; + }, t4; + }(); + Jt2.RecognizerEngine = Zs; +}); +var pa2 = R2((tr) => { + Object.defineProperty(tr, "__esModule", { value: true }); + tr.ErrorHandler = undefined; + var $r2 = et3(), Zr = k2(), fa = yt2(), Qs = ce2(), Js = function() { + function t4() { + } + return t4.prototype.initErrorHandler = function(e) { + this._errors = [], this.errorMessageProvider = Zr.has(e, "errorMessageProvider") ? e.errorMessageProvider : Qs.DEFAULT_PARSER_CONFIG.errorMessageProvider; + }, t4.prototype.SAVE_ERROR = function(e) { + if ($r2.isRecognitionException(e)) + return e.context = { ruleStack: this.getHumanReadableRuleStack(), ruleOccurrenceStack: Zr.cloneArr(this.RULE_OCCURRENCE_STACK) }, this._errors.push(e), e; + throw Error("Trying to save an Error which is not a RecognitionException"); + }, Object.defineProperty(t4.prototype, "errors", { get: function() { + return Zr.cloneArr(this._errors); + }, set: function(e) { + this._errors = e; + }, enumerable: false, configurable: true }), t4.prototype.raiseEarlyExitException = function(e, r, n2) { + for (var i = this.getCurrRuleFullName(), a = this.getGAstProductions()[i], o = fa.getLookaheadPathsForOptionalProd(e, a, r, this.maxLookahead), s = o[0], c = [], f = 1;f <= this.maxLookahead; f++) + c.push(this.LA(f)); + var p = this.errorMessageProvider.buildEarlyExitMessage({ expectedIterationPaths: s, actual: c, previous: this.LA(0), customUserDescription: n2, ruleName: i }); + throw this.SAVE_ERROR(new $r2.EarlyExitException(p, this.LA(1), this.LA(0))); + }, t4.prototype.raiseNoAltException = function(e, r) { + for (var n2 = this.getCurrRuleFullName(), i = this.getGAstProductions()[n2], a = fa.getLookaheadPathsForOr(e, i, this.maxLookahead), o = [], s = 1;s <= this.maxLookahead; s++) + o.push(this.LA(s)); + var c = this.LA(0), f = this.errorMessageProvider.buildNoViableAltMessage({ expectedPathsPerAlt: a, actual: o, previous: c, customUserDescription: r, ruleName: this.getCurrRuleFullName() }); + throw this.SAVE_ERROR(new $r2.NoViableAltException(f, this.LA(1), c)); + }, t4; + }(); + tr.ErrorHandler = Js; +}); +var va = R2((rr) => { + Object.defineProperty(rr, "__esModule", { value: true }); + rr.ContentAssist = undefined; + var ha = Tt3(), da = k2(), eu = function() { + function t4() { + } + return t4.prototype.initContentAssist = function() { + }, t4.prototype.computeContentAssist = function(e, r) { + var n2 = this.gastProductionsCache[e]; + if (da.isUndefined(n2)) + throw Error("Rule ->" + e + "<- does not exist in this grammar."); + return ha.nextPossibleTokensAfter([n2], r, this.tokenMatcher, this.maxLookahead); + }, t4.prototype.getNextPossibleTokenTypes = function(e) { + var r = da.first(e.ruleStack), n2 = this.getGAstProductions(), i = n2[r], a = new ha.NextAfterTokenWalker(i, e).startWalking(); + return a; + }, t4; + }(); + rr.ContentAssist = eu; +}); +var Ra = R2((nr) => { + Object.defineProperty(nr, "__esModule", { value: true }); + nr.GastRecorder = undefined; + var oe = k2(), Pe = ne(), tu = ft(), ma = Xe(), Ea = Ue(), ru = ce2(), nu = Yt(), ir2 = { description: "This Object indicates the Parser is during Recording Phase" }; + Object.freeze(ir2); + var Ta = true, ya = Math.pow(2, nu.BITS_FOR_OCCURRENCE_IDX) - 1, _a2 = Ea.createToken({ name: "RECORDING_PHASE_TOKEN", pattern: tu.Lexer.NA }); + ma.augmentTokenTypes([_a2]); + var ga = Ea.createTokenInstance(_a2, `This IToken indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`, -1, -1, -1, -1, -1, -1); + Object.freeze(ga); + var iu = { name: `This CSTNode indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`, children: {} }, ou2 = function() { + function t4() { + } + return t4.prototype.initGastRecorder = function(e) { + this.recordingProdStack = [], this.RECORDING_PHASE = false; + }, t4.prototype.enableRecording = function() { + var e = this; + this.RECORDING_PHASE = true, this.TRACE_INIT("Enable Recording", function() { + for (var r = function(i) { + var a = i > 0 ? i : ""; + e["CONSUME" + a] = function(o, s) { + return this.consumeInternalRecord(o, i, s); + }, e["SUBRULE" + a] = function(o, s) { + return this.subruleInternalRecord(o, i, s); + }, e["OPTION" + a] = function(o) { + return this.optionInternalRecord(o, i); + }, e["OR" + a] = function(o) { + return this.orInternalRecord(o, i); + }, e["MANY" + a] = function(o) { + this.manyInternalRecord(i, o); + }, e["MANY_SEP" + a] = function(o) { + this.manySepFirstInternalRecord(i, o); + }, e["AT_LEAST_ONE" + a] = function(o) { + this.atLeastOneInternalRecord(i, o); + }, e["AT_LEAST_ONE_SEP" + a] = function(o) { + this.atLeastOneSepFirstInternalRecord(i, o); + }; + }, n2 = 0;n2 < 10; n2++) + r(n2); + e.consume = function(i, a, o) { + return this.consumeInternalRecord(a, i, o); + }, e.subrule = function(i, a, o) { + return this.subruleInternalRecord(a, i, o); + }, e.option = function(i, a) { + return this.optionInternalRecord(a, i); + }, e.or = function(i, a) { + return this.orInternalRecord(a, i); + }, e.many = function(i, a) { + this.manyInternalRecord(i, a); + }, e.atLeastOne = function(i, a) { + this.atLeastOneInternalRecord(i, a); + }, e.ACTION = e.ACTION_RECORD, e.BACKTRACK = e.BACKTRACK_RECORD, e.LA = e.LA_RECORD; + }); + }, t4.prototype.disableRecording = function() { + var e = this; + this.RECORDING_PHASE = false, this.TRACE_INIT("Deleting Recording methods", function() { + for (var r = 0;r < 10; r++) { + var n2 = r > 0 ? r : ""; + delete e["CONSUME" + n2], delete e["SUBRULE" + n2], delete e["OPTION" + n2], delete e["OR" + n2], delete e["MANY" + n2], delete e["MANY_SEP" + n2], delete e["AT_LEAST_ONE" + n2], delete e["AT_LEAST_ONE_SEP" + n2]; + } + delete e.consume, delete e.subrule, delete e.option, delete e.or, delete e.many, delete e.atLeastOne, delete e.ACTION, delete e.BACKTRACK, delete e.LA; + }); + }, t4.prototype.ACTION_RECORD = function(e) { + }, t4.prototype.BACKTRACK_RECORD = function(e, r) { + return function() { + return true; + }; + }, t4.prototype.LA_RECORD = function(e) { + return ru.END_OF_FILE; + }, t4.prototype.topLevelRuleRecord = function(e, r) { + try { + var n2 = new Pe.Rule({ definition: [], name: e }); + return n2.name = e, this.recordingProdStack.push(n2), r.call(this), this.recordingProdStack.pop(), n2; + } catch (i) { + if (i.KNOWN_RECORDER_ERROR !== true) + try { + i.message = i.message + ` + This error was thrown during the "grammar recording phase" For more info see: + https://chevrotain.io/docs/guide/internals.html#grammar-recording`; + } catch (a) { + throw i; + } + throw i; + } + }, t4.prototype.optionInternalRecord = function(e, r) { + return Ot.call(this, Pe.Option, e, r); + }, t4.prototype.atLeastOneInternalRecord = function(e, r) { + Ot.call(this, Pe.RepetitionMandatory, r, e); + }, t4.prototype.atLeastOneSepFirstInternalRecord = function(e, r) { + Ot.call(this, Pe.RepetitionMandatoryWithSeparator, r, e, Ta); + }, t4.prototype.manyInternalRecord = function(e, r) { + Ot.call(this, Pe.Repetition, r, e); + }, t4.prototype.manySepFirstInternalRecord = function(e, r) { + Ot.call(this, Pe.RepetitionWithSeparator, r, e, Ta); + }, t4.prototype.orInternalRecord = function(e, r) { + return au.call(this, e, r); + }, t4.prototype.subruleInternalRecord = function(e, r, n2) { + if (ar2(r), !e || oe.has(e, "ruleName") === false) { + var i = new Error(" argument is invalid" + (" expecting a Parser method reference but got: <" + JSON.stringify(e) + ">") + (` + inside top level rule: <` + this.recordingProdStack[0].name + ">")); + throw i.KNOWN_RECORDER_ERROR = true, i; + } + var a = oe.peek(this.recordingProdStack), o = e.ruleName, s = new Pe.NonTerminal({ idx: r, nonTerminalName: o, referencedRule: undefined }); + return a.definition.push(s), this.outputCst ? iu : ir2; + }, t4.prototype.consumeInternalRecord = function(e, r, n2) { + if (ar2(r), !ma.hasShortKeyProperty(e)) { + var i = new Error(" argument is invalid" + (" expecting a TokenType reference but got: <" + JSON.stringify(e) + ">") + (` + inside top level rule: <` + this.recordingProdStack[0].name + ">")); + throw i.KNOWN_RECORDER_ERROR = true, i; + } + var a = oe.peek(this.recordingProdStack), o = new Pe.Terminal({ idx: r, terminalType: e }); + return a.definition.push(o), ga; + }, t4; + }(); + nr.GastRecorder = ou2; + function Ot(t4, e, r, n2) { + n2 === undefined && (n2 = false), ar2(r); + var i = oe.peek(this.recordingProdStack), a = oe.isFunction(e) ? e : e.DEF, o = new t4({ definition: [], idx: r }); + return n2 && (o.separator = e.SEP), oe.has(e, "MAX_LOOKAHEAD") && (o.maxLookahead = e.MAX_LOOKAHEAD), this.recordingProdStack.push(o), a.call(this), i.definition.push(o), this.recordingProdStack.pop(), ir2; + } + function au(t4, e) { + var r = this; + ar2(e); + var n2 = oe.peek(this.recordingProdStack), i = oe.isArray(t4) === false, a = i === false ? t4 : t4.DEF, o = new Pe.Alternation({ definition: [], idx: e, ignoreAmbiguities: i && t4.IGNORE_AMBIGUITIES === true }); + oe.has(t4, "MAX_LOOKAHEAD") && (o.maxLookahead = t4.MAX_LOOKAHEAD); + var s = oe.some(a, function(c) { + return oe.isFunction(c.GATE); + }); + return o.hasPredicates = s, n2.definition.push(o), oe.forEach(a, function(c) { + var f = new Pe.Alternative({ definition: [] }); + o.definition.push(f), oe.has(c, "IGNORE_AMBIGUITIES") ? f.ignoreAmbiguities = c.IGNORE_AMBIGUITIES : oe.has(c, "GATE") && (f.ignoreAmbiguities = true), r.recordingProdStack.push(f), c.ALT.call(r), r.recordingProdStack.pop(); + }), ir2; + } + function Aa2(t4) { + return t4 === 0 ? "" : "" + t4; + } + function ar2(t4) { + if (t4 < 0 || t4 > ya) { + var e = new Error("Invalid DSL Method idx value: <" + t4 + `> + ` + ("Idx value must be a none negative value smaller than " + (ya + 1))); + throw e.KNOWN_RECORDER_ERROR = true, e; + } + } +}); +var Na = R2((or2) => { + Object.defineProperty(or2, "__esModule", { value: true }); + or2.PerformanceTracer = undefined; + var Oa2 = k2(), su = ce2(), uu = function() { + function t4() { + } + return t4.prototype.initPerformanceTracer = function(e) { + if (Oa2.has(e, "traceInitPerf")) { + var r = e.traceInitPerf, n2 = typeof r == "number"; + this.traceInitMaxIdent = n2 ? r : Infinity, this.traceInitPerf = n2 ? r > 0 : r; + } else + this.traceInitMaxIdent = 0, this.traceInitPerf = su.DEFAULT_PARSER_CONFIG.traceInitPerf; + this.traceInitIndent = -1; + }, t4.prototype.TRACE_INIT = function(e, r) { + if (this.traceInitPerf === true) { + this.traceInitIndent++; + var n2 = new Array(this.traceInitIndent + 1).join("\t"); + this.traceInitIndent < this.traceInitMaxIdent && console.log(n2 + "--> <" + e + ">"); + var i = Oa2.timer(r), a = i.time, o = i.value, s = a > 10 ? console.warn : console.log; + return this.traceInitIndent < this.traceInitMaxIdent && s(n2 + "<-- <" + e + "> time: " + a + "ms"), this.traceInitIndent--, o; + } else + return r(); + }, t4; + }(); + or2.PerformanceTracer = uu; +}); +var Ia = R2((sr) => { + Object.defineProperty(sr, "__esModule", { value: true }); + sr.applyMixins = undefined; + function cu2(t4, e) { + e.forEach(function(r) { + var n2 = r.prototype; + Object.getOwnPropertyNames(n2).forEach(function(i) { + if (i !== "constructor") { + var a = Object.getOwnPropertyDescriptor(n2, i); + a && (a.get || a.set) ? Object.defineProperty(t4.prototype, i, a) : t4.prototype[i] = r.prototype[i]; + } + }); + }); + } + sr.applyMixins = cu2; +}); +var ce2 = R2((U) => { + var ka = U && U.__extends || function() { + var t4 = function(e, r) { + return t4 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t4(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t4(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(U, "__esModule", { value: true }); + U.EmbeddedActionsParser = U.CstParser = U.Parser = U.EMPTY_ALT = U.ParserDefinitionErrorType = U.DEFAULT_RULE_CONFIG = U.DEFAULT_PARSER_CONFIG = U.END_OF_FILE = undefined; + var ee = k2(), lu = pi2(), Pa = Ue(), Sa = mt(), xa = Ui2(), fu2 = zr(), pu = zi(), hu = ra(), du = ia(), vu = oa(), mu2 = la(), Eu2 = pa2(), Tu2 = va(), yu = Ra(), _u2 = Na(), gu = Ia(); + U.END_OF_FILE = Pa.createTokenInstance(Pa.EOF, "", NaN, NaN, NaN, NaN, NaN, NaN); + Object.freeze(U.END_OF_FILE); + U.DEFAULT_PARSER_CONFIG = Object.freeze({ recoveryEnabled: false, maxLookahead: 3, dynamicTokensEnabled: false, outputCst: true, errorMessageProvider: Sa.defaultParserErrorProvider, nodeLocationTracking: "none", traceInitPerf: false, skipValidations: false }); + U.DEFAULT_RULE_CONFIG = Object.freeze({ recoveryValueFunc: function() { + }, resyncEnabled: true }); + var Au2; + (function(t4) { + t4[t4.INVALID_RULE_NAME = 0] = "INVALID_RULE_NAME", t4[t4.DUPLICATE_RULE_NAME = 1] = "DUPLICATE_RULE_NAME", t4[t4.INVALID_RULE_OVERRIDE = 2] = "INVALID_RULE_OVERRIDE", t4[t4.DUPLICATE_PRODUCTIONS = 3] = "DUPLICATE_PRODUCTIONS", t4[t4.UNRESOLVED_SUBRULE_REF = 4] = "UNRESOLVED_SUBRULE_REF", t4[t4.LEFT_RECURSION = 5] = "LEFT_RECURSION", t4[t4.NONE_LAST_EMPTY_ALT = 6] = "NONE_LAST_EMPTY_ALT", t4[t4.AMBIGUOUS_ALTS = 7] = "AMBIGUOUS_ALTS", t4[t4.CONFLICT_TOKENS_RULES_NAMESPACE = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE", t4[t4.INVALID_TOKEN_NAME = 9] = "INVALID_TOKEN_NAME", t4[t4.NO_NON_EMPTY_LOOKAHEAD = 10] = "NO_NON_EMPTY_LOOKAHEAD", t4[t4.AMBIGUOUS_PREFIX_ALTS = 11] = "AMBIGUOUS_PREFIX_ALTS", t4[t4.TOO_MANY_ALTS = 12] = "TOO_MANY_ALTS"; + })(Au2 = U.ParserDefinitionErrorType || (U.ParserDefinitionErrorType = {})); + function Ru(t4) { + return t4 === undefined && (t4 = undefined), function() { + return t4; + }; + } + U.EMPTY_ALT = Ru; + var ur2 = function() { + function t4(e, r) { + this.definitionErrors = [], this.selfAnalysisDone = false; + var n2 = this; + if (n2.initErrorHandler(r), n2.initLexerAdapter(), n2.initLooksAhead(r), n2.initRecognizerEngine(e, r), n2.initRecoverable(r), n2.initTreeBuilder(r), n2.initContentAssist(), n2.initGastRecorder(r), n2.initPerformanceTracer(r), ee.has(r, "ignoredIssues")) + throw new Error(`The IParserConfig property has been deprecated. + Please use the flag on the relevant DSL method instead. + See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES + For further details.`); + this.skipValidations = ee.has(r, "skipValidations") ? r.skipValidations : U.DEFAULT_PARSER_CONFIG.skipValidations; + } + return t4.performSelfAnalysis = function(e) { + throw Error("The **static** `performSelfAnalysis` method has been deprecated.\t\nUse the **instance** method with the same name instead."); + }, t4.prototype.performSelfAnalysis = function() { + var e = this; + this.TRACE_INIT("performSelfAnalysis", function() { + var r; + e.selfAnalysisDone = true; + var n2 = e.className; + e.TRACE_INIT("toFastProps", function() { + ee.toFastProperties(e); + }), e.TRACE_INIT("Grammar Recording", function() { + try { + e.enableRecording(), ee.forEach(e.definedRulesNames, function(a) { + var o = e[a], s = o.originalGrammarAction, c = undefined; + e.TRACE_INIT(a + " Rule", function() { + c = e.topLevelRuleRecord(a, s); + }), e.gastProductionsCache[a] = c; + }); + } finally { + e.disableRecording(); + } + }); + var i = []; + if (e.TRACE_INIT("Grammar Resolving", function() { + i = xa.resolveGrammar({ rules: ee.values(e.gastProductionsCache) }), e.definitionErrors = e.definitionErrors.concat(i); + }), e.TRACE_INIT("Grammar Validations", function() { + if (ee.isEmpty(i) && e.skipValidations === false) { + var a = xa.validateGrammar({ rules: ee.values(e.gastProductionsCache), maxLookahead: e.maxLookahead, tokenTypes: ee.values(e.tokensMap), errMsgProvider: Sa.defaultGrammarValidatorErrorProvider, grammarName: n2 }); + e.definitionErrors = e.definitionErrors.concat(a); + } + }), ee.isEmpty(e.definitionErrors) && (e.recoveryEnabled && e.TRACE_INIT("computeAllProdsFollows", function() { + var a = lu.computeAllProdsFollows(ee.values(e.gastProductionsCache)); + e.resyncFollows = a; + }), e.TRACE_INIT("ComputeLookaheadFunctions", function() { + e.preComputeLookaheadFunctions(ee.values(e.gastProductionsCache)); + })), !t4.DEFER_DEFINITION_ERRORS_HANDLING && !ee.isEmpty(e.definitionErrors)) + throw r = ee.map(e.definitionErrors, function(a) { + return a.message; + }), new Error(`Parser Definition Errors detected: + ` + r.join(` +------------------------------- +`)); + }); + }, t4.DEFER_DEFINITION_ERRORS_HANDLING = false, t4; + }(); + U.Parser = ur2; + gu.applyMixins(ur2, [fu2.Recoverable, pu.LooksAhead, hu.TreeBuilder, du.LexerAdapter, mu2.RecognizerEngine, vu.RecognizerApi, Eu2.ErrorHandler, Tu2.ContentAssist, yu.GastRecorder, _u2.PerformanceTracer]); + var Ou2 = function(t4) { + ka(e, t4); + function e(r, n2) { + n2 === undefined && (n2 = U.DEFAULT_PARSER_CONFIG); + var i = this, a = ee.cloneObj(n2); + return a.outputCst = true, i = t4.call(this, r, a) || this, i; + } + return e; + }(ur2); + U.CstParser = Ou2; + var Nu = function(t4) { + ka(e, t4); + function e(r, n2) { + n2 === undefined && (n2 = U.DEFAULT_PARSER_CONFIG); + var i = this, a = ee.cloneObj(n2); + return a.outputCst = false, i = t4.call(this, r, a) || this, i; + } + return e; + }(ur2); + U.EmbeddedActionsParser = Nu; +}); +var La = R2((cr) => { + Object.defineProperty(cr, "__esModule", { value: true }); + cr.createSyntaxDiagramsCode = undefined; + var Ca = Er2(); + function Iu2(t4, e) { + var r = e === undefined ? {} : e, n2 = r.resourceBase, i = n2 === undefined ? "https://unpkg.com/chevrotain@" + Ca.VERSION + "/diagrams/" : n2, a = r.css, o = a === undefined ? "https://unpkg.com/chevrotain@" + Ca.VERSION + "/diagrams/diagrams.css" : a, s = ` + + + + + +`, c = ` + +`, f = ` + + + + +`, p = ` +
+`, l2 = ` + +`, m = ` + +`; + return s + c + f + p + l2 + m; + } + cr.createSyntaxDiagramsCode = Iu2; +}); +var Fa = R2((E2) => { + Object.defineProperty(E2, "__esModule", { value: true }); + E2.Parser = E2.createSyntaxDiagramsCode = E2.clearCache = E2.GAstVisitor = E2.serializeProduction = E2.serializeGrammar = E2.Terminal = E2.Rule = E2.RepetitionWithSeparator = E2.RepetitionMandatoryWithSeparator = E2.RepetitionMandatory = E2.Repetition = E2.Option = E2.NonTerminal = E2.Alternative = E2.Alternation = E2.defaultLexerErrorProvider = E2.NoViableAltException = E2.NotAllInputParsedException = E2.MismatchedTokenException = E2.isRecognitionException = E2.EarlyExitException = E2.defaultParserErrorProvider = E2.tokenName = E2.tokenMatcher = E2.tokenLabel = E2.EOF = E2.createTokenInstance = E2.createToken = E2.LexerDefinitionErrorType = E2.Lexer = E2.EMPTY_ALT = E2.ParserDefinitionErrorType = E2.EmbeddedActionsParser = E2.CstParser = E2.VERSION = undefined; + var ku2 = Er2(); + Object.defineProperty(E2, "VERSION", { enumerable: true, get: function() { + return ku2.VERSION; + } }); + var lr = ce2(); + Object.defineProperty(E2, "CstParser", { enumerable: true, get: function() { + return lr.CstParser; + } }); + Object.defineProperty(E2, "EmbeddedActionsParser", { enumerable: true, get: function() { + return lr.EmbeddedActionsParser; + } }); + Object.defineProperty(E2, "ParserDefinitionErrorType", { enumerable: true, get: function() { + return lr.ParserDefinitionErrorType; + } }); + Object.defineProperty(E2, "EMPTY_ALT", { enumerable: true, get: function() { + return lr.EMPTY_ALT; + } }); + var Ma = ft(); + Object.defineProperty(E2, "Lexer", { enumerable: true, get: function() { + return Ma.Lexer; + } }); + Object.defineProperty(E2, "LexerDefinitionErrorType", { enumerable: true, get: function() { + return Ma.LexerDefinitionErrorType; + } }); + var nt2 = Ue(); + Object.defineProperty(E2, "createToken", { enumerable: true, get: function() { + return nt2.createToken; + } }); + Object.defineProperty(E2, "createTokenInstance", { enumerable: true, get: function() { + return nt2.createTokenInstance; + } }); + Object.defineProperty(E2, "EOF", { enumerable: true, get: function() { + return nt2.EOF; + } }); + Object.defineProperty(E2, "tokenLabel", { enumerable: true, get: function() { + return nt2.tokenLabel; + } }); + Object.defineProperty(E2, "tokenMatcher", { enumerable: true, get: function() { + return nt2.tokenMatcher; + } }); + Object.defineProperty(E2, "tokenName", { enumerable: true, get: function() { + return nt2.tokenName; + } }); + var Pu2 = mt(); + Object.defineProperty(E2, "defaultParserErrorProvider", { enumerable: true, get: function() { + return Pu2.defaultParserErrorProvider; + } }); + var Nt = et3(); + Object.defineProperty(E2, "EarlyExitException", { enumerable: true, get: function() { + return Nt.EarlyExitException; + } }); + Object.defineProperty(E2, "isRecognitionException", { enumerable: true, get: function() { + return Nt.isRecognitionException; + } }); + Object.defineProperty(E2, "MismatchedTokenException", { enumerable: true, get: function() { + return Nt.MismatchedTokenException; + } }); + Object.defineProperty(E2, "NotAllInputParsedException", { enumerable: true, get: function() { + return Nt.NotAllInputParsedException; + } }); + Object.defineProperty(E2, "NoViableAltException", { enumerable: true, get: function() { + return Nt.NoViableAltException; + } }); + var Su = kr(); + Object.defineProperty(E2, "defaultLexerErrorProvider", { enumerable: true, get: function() { + return Su.defaultLexerErrorProvider; + } }); + var Se2 = ne(); + Object.defineProperty(E2, "Alternation", { enumerable: true, get: function() { + return Se2.Alternation; + } }); + Object.defineProperty(E2, "Alternative", { enumerable: true, get: function() { + return Se2.Alternative; + } }); + Object.defineProperty(E2, "NonTerminal", { enumerable: true, get: function() { + return Se2.NonTerminal; + } }); + Object.defineProperty(E2, "Option", { enumerable: true, get: function() { + return Se2.Option; + } }); + Object.defineProperty(E2, "Repetition", { enumerable: true, get: function() { + return Se2.Repetition; + } }); + Object.defineProperty(E2, "RepetitionMandatory", { enumerable: true, get: function() { + return Se2.RepetitionMandatory; + } }); + Object.defineProperty(E2, "RepetitionMandatoryWithSeparator", { enumerable: true, get: function() { + return Se2.RepetitionMandatoryWithSeparator; + } }); + Object.defineProperty(E2, "RepetitionWithSeparator", { enumerable: true, get: function() { + return Se2.RepetitionWithSeparator; + } }); + Object.defineProperty(E2, "Rule", { enumerable: true, get: function() { + return Se2.Rule; + } }); + Object.defineProperty(E2, "Terminal", { enumerable: true, get: function() { + return Se2.Terminal; + } }); + var ba2 = ne(); + Object.defineProperty(E2, "serializeGrammar", { enumerable: true, get: function() { + return ba2.serializeGrammar; + } }); + Object.defineProperty(E2, "serializeProduction", { enumerable: true, get: function() { + return ba2.serializeProduction; + } }); + var xu2 = $e(); + Object.defineProperty(E2, "GAstVisitor", { enumerable: true, get: function() { + return xu2.GAstVisitor; + } }); + function Cu() { + console.warn(`The clearCache function was 'soft' removed from the Chevrotain API. + It performs no action other than printing this message. + Please avoid using it as it will be completely removed in the future`); + } + E2.clearCache = Cu; + var Lu = La(); + Object.defineProperty(E2, "createSyntaxDiagramsCode", { enumerable: true, get: function() { + return Lu.createSyntaxDiagramsCode; + } }); + var Mu2 = function() { + function t4() { + throw new Error(`The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead. +See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_7-0-0`); + } + return t4; + }(); + E2.Parser = Mu2; +}); +var chevrotain_module_min_default = Fa(); + +// node_modules/three/examples/jsm/loaders/VRMLLoader.js +var CstParser = chevrotain_module_min_default.CstParser; +// node_modules/three/examples/jsm/materials/MeshGouraudMaterial.js +var GouraudShader = { + name: "GouraudShader", + uniforms: UniformsUtils.merge([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: new Color(0) } + } + ]), + vertexShader: ` + + #define GOURAUD + + varying vec3 vLightFront; + varying vec3 vIndirectFront; + + #ifdef DOUBLE_SIDED + varying vec3 vLightBack; + varying vec3 vIndirectBack; + #endif + + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + void main() { + + #include + #include + #include + + #include + #include + #include + #include + #include + + #include + #include + #include + #include + #include + #include + + #include + #include + + // inlining legacy + + vec3 diffuse = vec3( 1.0 ); + + vec3 geometryPosition = mvPosition.xyz; + vec3 geometryNormal = normalize( transformedNormal ); + vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz ); + + vec3 backGeometryNormal = - geometryNormal; + + vLightFront = vec3( 0.0 ); + vIndirectFront = vec3( 0.0 ); + #ifdef DOUBLE_SIDED + vLightBack = vec3( 0.0 ); + vIndirectBack = vec3( 0.0 ); + #endif + + IncidentLight directLight; + float dotNL; + vec3 directLightColor_Diffuse; + + vIndirectFront += getAmbientLightIrradiance( ambientLightColor ); + + #if defined( USE_LIGHT_PROBES ) + + vIndirectFront += getLightProbeIrradiance( lightProbe, geometryNormal ); + + #endif + + #ifdef DOUBLE_SIDED + + vIndirectBack += getAmbientLightIrradiance( ambientLightColor ); + + #if defined( USE_LIGHT_PROBES ) + + vIndirectBack += getLightProbeIrradiance( lightProbe, backGeometryNormal ); + + #endif + + #endif + + #if NUM_POINT_LIGHTS > 0 + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + + getPointLightInfo( pointLights[ i ], geometryPosition, directLight ); + + dotNL = dot( geometryNormal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + + #ifdef DOUBLE_SIDED + + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + + #endif + + } + #pragma unroll_loop_end + + #endif + + #if NUM_SPOT_LIGHTS > 0 + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + + getSpotLightInfo( spotLights[ i ], geometryPosition, directLight ); + + dotNL = dot( geometryNormal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + + #ifdef DOUBLE_SIDED + + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + + #endif + } + #pragma unroll_loop_end + + #endif + + #if NUM_DIR_LIGHTS > 0 + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + getDirectionalLightInfo( directionalLights[ i ], directLight ); + + dotNL = dot( geometryNormal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + + #ifdef DOUBLE_SIDED + + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + + #endif + + } + #pragma unroll_loop_end + + #endif + + #if NUM_HEMI_LIGHTS > 0 + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + + vIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + + #ifdef DOUBLE_SIDED + + vIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometryNormal ); + + #endif + + } + #pragma unroll_loop_end + + #endif + + #include + #include + + }`, + fragmentShader: ` + + #define GOURAUD + + uniform vec3 diffuse; + uniform vec3 emissive; + uniform float opacity; + + varying vec3 vLightFront; + varying vec3 vIndirectFront; + + #ifdef DOUBLE_SIDED + varying vec3 vLightBack; + varying vec3 vIndirectBack; + #endif + + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + void main() { + + #include + + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + + #include + #include + #include + #include + #include + #include + #include + + // accumulation + + #ifdef DOUBLE_SIDED + + reflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack; + + #else + + reflectedLight.indirectDiffuse += vIndirectFront; + + #endif + + #ifdef USE_LIGHTMAP + + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + reflectedLight.indirectDiffuse += lightMapIrradiance; + + #endif + + reflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb ); + + #ifdef DOUBLE_SIDED + + reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack; + + #else + + reflectedLight.directDiffuse = vLightFront; + + #endif + + reflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask(); + + // modulation + + #include + + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + + #include + + #include + #include + #include + #include + #include + #include + + }` +}; +// node_modules/three/examples/jsm/math/Capsule.js +class Capsule { + constructor(start = new Vector3(0, 0, 0), end = new Vector3(0, 1, 0), radius = 1) { + this.start = start; + this.end = end; + this.radius = radius; + } + clone() { + return new Capsule(this.start.clone(), this.end.clone(), this.radius); + } + set(start, end, radius) { + this.start.copy(start); + this.end.copy(end); + this.radius = radius; + } + copy(capsule) { + this.start.copy(capsule.start); + this.end.copy(capsule.end); + this.radius = capsule.radius; + } + getCenter(target) { + return target.copy(this.end).add(this.start).multiplyScalar(0.5); + } + translate(v) { + this.start.add(v); + this.end.add(v); + } + checkAABBAxis(p1x, p1y, p2x, p2y, minx, maxx, miny, maxy, radius) { + return (minx - p1x < radius || minx - p2x < radius) && (p1x - maxx < radius || p2x - maxx < radius) && (miny - p1y < radius || miny - p2y < radius) && (p1y - maxy < radius || p2y - maxy < radius); + } + intersectsBox(box) { + return this.checkAABBAxis(this.start.x, this.start.y, this.end.x, this.end.y, box.min.x, box.max.x, box.min.y, box.max.y, this.radius) && this.checkAABBAxis(this.start.x, this.start.z, this.end.x, this.end.z, box.min.x, box.max.x, box.min.z, box.max.z, this.radius) && this.checkAABBAxis(this.start.y, this.start.z, this.end.y, this.end.z, box.min.y, box.max.y, box.min.z, box.max.z, this.radius); + } +} +// node_modules/three/examples/jsm/math/ImprovedNoise.js +var _p2 = [ + 151, + 160, + 137, + 91, + 90, + 15, + 131, + 13, + 201, + 95, + 96, + 53, + 194, + 233, + 7, + 225, + 140, + 36, + 103, + 30, + 69, + 142, + 8, + 99, + 37, + 240, + 21, + 10, + 23, + 190, + 6, + 148, + 247, + 120, + 234, + 75, + 0, + 26, + 197, + 62, + 94, + 252, + 219, + 203, + 117, + 35, + 11, + 32, + 57, + 177, + 33, + 88, + 237, + 149, + 56, + 87, + 174, + 20, + 125, + 136, + 171, + 168, + 68, + 175, + 74, + 165, + 71, + 134, + 139, + 48, + 27, + 166, + 77, + 146, + 158, + 231, + 83, + 111, + 229, + 122, + 60, + 211, + 133, + 230, + 220, + 105, + 92, + 41, + 55, + 46, + 245, + 40, + 244, + 102, + 143, + 54, + 65, + 25, + 63, + 161, + 1, + 216, + 80, + 73, + 209, + 76, + 132, + 187, + 208, + 89, + 18, + 169, + 200, + 196, + 135, + 130, + 116, + 188, + 159, + 86, + 164, + 100, + 109, + 198, + 173, + 186, + 3, + 64, + 52, + 217, + 226, + 250, + 124, + 123, + 5, + 202, + 38, + 147, + 118, + 126, + 255, + 82, + 85, + 212, + 207, + 206, + 59, + 227, + 47, + 16, + 58, + 17, + 182, + 189, + 28, + 42, + 223, + 183, + 170, + 213, + 119, + 248, + 152, + 2, + 44, + 154, + 163, + 70, + 221, + 153, + 101, + 155, + 167, + 43, + 172, + 9, + 129, + 22, + 39, + 253, + 19, + 98, + 108, + 110, + 79, + 113, + 224, + 232, + 178, + 185, + 112, + 104, + 218, + 246, + 97, + 228, + 251, + 34, + 242, + 193, + 238, + 210, + 144, + 12, + 191, + 179, + 162, + 241, + 81, + 51, + 145, + 235, + 249, + 14, + 239, + 107, + 49, + 192, + 214, + 31, + 181, + 199, + 106, + 157, + 184, + 84, + 204, + 176, + 115, + 121, + 50, + 45, + 127, + 4, + 150, + 254, + 138, + 236, + 205, + 93, + 222, + 114, + 67, + 29, + 24, + 72, + 243, + 141, + 128, + 195, + 78, + 66, + 215, + 61, + 156, + 180 +]; +for (let i = 0;i < 256; i++) { + _p2[256 + i] = _p2[i]; +} +// node_modules/three/examples/jsm/math/MeshSurfaceSampler.js +var _face = new Triangle; +var _color6 = new Vector3; +var _uva = new Vector2; +var _uvb = new Vector2; +var _uvc = new Vector2; +// node_modules/three/examples/jsm/math/OBB.js +var a = { + c: null, + u: [new Vector3, new Vector3, new Vector3], + e: [] +}; +var b = { + c: null, + u: [new Vector3, new Vector3, new Vector3], + e: [] +}; +var R3 = [[], [], []]; +var AbsR = [[], [], []]; +var t5 = []; +var xAxis = new Vector3; +var yAxis = new Vector3; +var zAxis = new Vector3; +var v1 = new Vector3; +var size = new Vector3; +var closestPoint = new Vector3; +var rotationMatrix = new Matrix3; +var aabb = new Box3; +var matrix = new Matrix4; +var inverse = new Matrix4; +var localRay = new Ray; + +class OBB { + constructor(center = new Vector3, halfSize = new Vector3, rotation2 = new Matrix3) { + this.center = center; + this.halfSize = halfSize; + this.rotation = rotation2; + } + set(center, halfSize, rotation2) { + this.center = center; + this.halfSize = halfSize; + this.rotation = rotation2; + return this; + } + copy(obb) { + this.center.copy(obb.center); + this.halfSize.copy(obb.halfSize); + this.rotation.copy(obb.rotation); + return this; + } + clone() { + return new this.constructor().copy(this); + } + getSize(result) { + return result.copy(this.halfSize).multiplyScalar(2); + } + clampPoint(point, result) { + const halfSize = this.halfSize; + v1.subVectors(point, this.center); + this.rotation.extractBasis(xAxis, yAxis, zAxis); + result.copy(this.center); + const x2 = MathUtils.clamp(v1.dot(xAxis), -halfSize.x, halfSize.x); + result.add(xAxis.multiplyScalar(x2)); + const y3 = MathUtils.clamp(v1.dot(yAxis), -halfSize.y, halfSize.y); + result.add(yAxis.multiplyScalar(y3)); + const z2 = MathUtils.clamp(v1.dot(zAxis), -halfSize.z, halfSize.z); + result.add(zAxis.multiplyScalar(z2)); + return result; + } + containsPoint(point) { + v1.subVectors(point, this.center); + this.rotation.extractBasis(xAxis, yAxis, zAxis); + return Math.abs(v1.dot(xAxis)) <= this.halfSize.x && Math.abs(v1.dot(yAxis)) <= this.halfSize.y && Math.abs(v1.dot(zAxis)) <= this.halfSize.z; + } + intersectsBox3(box3) { + return this.intersectsOBB(obb.fromBox3(box3)); + } + intersectsSphere(sphere) { + this.clampPoint(sphere.center, closestPoint); + return closestPoint.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; + } + intersectsOBB(obb, epsilon = Number.EPSILON) { + a.c = this.center; + a.e[0] = this.halfSize.x; + a.e[1] = this.halfSize.y; + a.e[2] = this.halfSize.z; + this.rotation.extractBasis(a.u[0], a.u[1], a.u[2]); + b.c = obb.center; + b.e[0] = obb.halfSize.x; + b.e[1] = obb.halfSize.y; + b.e[2] = obb.halfSize.z; + obb.rotation.extractBasis(b.u[0], b.u[1], b.u[2]); + for (let i = 0;i < 3; i++) { + for (let j2 = 0;j2 < 3; j2++) { + R3[i][j2] = a.u[i].dot(b.u[j2]); + } + } + v1.subVectors(b.c, a.c); + t5[0] = v1.dot(a.u[0]); + t5[1] = v1.dot(a.u[1]); + t5[2] = v1.dot(a.u[2]); + for (let i = 0;i < 3; i++) { + for (let j2 = 0;j2 < 3; j2++) { + AbsR[i][j2] = Math.abs(R3[i][j2]) + epsilon; + } + } + let ra2, rb; + for (let i = 0;i < 3; i++) { + ra2 = a.e[i]; + rb = b.e[0] * AbsR[i][0] + b.e[1] * AbsR[i][1] + b.e[2] * AbsR[i][2]; + if (Math.abs(t5[i]) > ra2 + rb) + return false; + } + for (let i = 0;i < 3; i++) { + ra2 = a.e[0] * AbsR[0][i] + a.e[1] * AbsR[1][i] + a.e[2] * AbsR[2][i]; + rb = b.e[i]; + if (Math.abs(t5[0] * R3[0][i] + t5[1] * R3[1][i] + t5[2] * R3[2][i]) > ra2 + rb) + return false; + } + ra2 = a.e[1] * AbsR[2][0] + a.e[2] * AbsR[1][0]; + rb = b.e[1] * AbsR[0][2] + b.e[2] * AbsR[0][1]; + if (Math.abs(t5[2] * R3[1][0] - t5[1] * R3[2][0]) > ra2 + rb) + return false; + ra2 = a.e[1] * AbsR[2][1] + a.e[2] * AbsR[1][1]; + rb = b.e[0] * AbsR[0][2] + b.e[2] * AbsR[0][0]; + if (Math.abs(t5[2] * R3[1][1] - t5[1] * R3[2][1]) > ra2 + rb) + return false; + ra2 = a.e[1] * AbsR[2][2] + a.e[2] * AbsR[1][2]; + rb = b.e[0] * AbsR[0][1] + b.e[1] * AbsR[0][0]; + if (Math.abs(t5[2] * R3[1][2] - t5[1] * R3[2][2]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[2][0] + a.e[2] * AbsR[0][0]; + rb = b.e[1] * AbsR[1][2] + b.e[2] * AbsR[1][1]; + if (Math.abs(t5[0] * R3[2][0] - t5[2] * R3[0][0]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[2][1] + a.e[2] * AbsR[0][1]; + rb = b.e[0] * AbsR[1][2] + b.e[2] * AbsR[1][0]; + if (Math.abs(t5[0] * R3[2][1] - t5[2] * R3[0][1]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[2][2] + a.e[2] * AbsR[0][2]; + rb = b.e[0] * AbsR[1][1] + b.e[1] * AbsR[1][0]; + if (Math.abs(t5[0] * R3[2][2] - t5[2] * R3[0][2]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[1][0] + a.e[1] * AbsR[0][0]; + rb = b.e[1] * AbsR[2][2] + b.e[2] * AbsR[2][1]; + if (Math.abs(t5[1] * R3[0][0] - t5[0] * R3[1][0]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[1][1] + a.e[1] * AbsR[0][1]; + rb = b.e[0] * AbsR[2][2] + b.e[2] * AbsR[2][0]; + if (Math.abs(t5[1] * R3[0][1] - t5[0] * R3[1][1]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[1][2] + a.e[1] * AbsR[0][2]; + rb = b.e[0] * AbsR[2][1] + b.e[1] * AbsR[2][0]; + if (Math.abs(t5[1] * R3[0][2] - t5[0] * R3[1][2]) > ra2 + rb) + return false; + return true; + } + intersectsPlane(plane) { + this.rotation.extractBasis(xAxis, yAxis, zAxis); + const r = this.halfSize.x * Math.abs(plane.normal.dot(xAxis)) + this.halfSize.y * Math.abs(plane.normal.dot(yAxis)) + this.halfSize.z * Math.abs(plane.normal.dot(zAxis)); + const d = plane.normal.dot(this.center) - plane.constant; + return Math.abs(d) <= r; + } + intersectRay(ray, result) { + this.getSize(size); + aabb.setFromCenterAndSize(v1.set(0, 0, 0), size); + matrix.setFromMatrix3(this.rotation); + matrix.setPosition(this.center); + inverse.copy(matrix).invert(); + localRay.copy(ray).applyMatrix4(inverse); + if (localRay.intersectBox(aabb, result)) { + return result.applyMatrix4(matrix); + } else { + return null; + } + } + intersectsRay(ray) { + return this.intersectRay(ray, v1) !== null; + } + fromBox3(box3) { + box3.getCenter(this.center); + box3.getSize(this.halfSize).multiplyScalar(0.5); + this.rotation.identity(); + return this; + } + equals(obb) { + return obb.center.equals(this.center) && obb.halfSize.equals(this.halfSize) && obb.rotation.equals(this.rotation); + } + applyMatrix4(matrix2) { + const e = matrix2.elements; + let sx = v1.set(e[0], e[1], e[2]).length(); + const sy = v1.set(e[4], e[5], e[6]).length(); + const sz = v1.set(e[8], e[9], e[10]).length(); + const det = matrix2.determinant(); + if (det < 0) + sx = -sx; + rotationMatrix.setFromMatrix4(matrix2); + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + rotationMatrix.elements[0] *= invSX; + rotationMatrix.elements[1] *= invSX; + rotationMatrix.elements[2] *= invSX; + rotationMatrix.elements[3] *= invSY; + rotationMatrix.elements[4] *= invSY; + rotationMatrix.elements[5] *= invSY; + rotationMatrix.elements[6] *= invSZ; + rotationMatrix.elements[7] *= invSZ; + rotationMatrix.elements[8] *= invSZ; + this.rotation.multiply(rotationMatrix); + this.halfSize.x *= sx; + this.halfSize.y *= sy; + this.halfSize.z *= sz; + v1.setFromMatrixPosition(matrix2); + this.center.add(v1); + return this; + } +} +var obb = new OBB; +// node_modules/three/examples/jsm/math/Octree.js +var _v16 = new Vector3; +var _v26 = new Vector3; +var _point1 = new Vector3; +var _point2 = new Vector3; +var _plane4 = new Plane; +var _line1 = new Line3; +var _line2 = new Line3; +var _sphere3 = new Sphere; +var _capsule = new Capsule; +var _temp1 = new Vector3; +var _temp2 = new Vector3; +var _temp3 = new Vector3; +// node_modules/three/examples/jsm/math/SimplexNoise.js +class SimplexNoise { + constructor(r = Math) { + this.grad3 = [ + [1, 1, 0], + [-1, 1, 0], + [1, -1, 0], + [-1, -1, 0], + [1, 0, 1], + [-1, 0, 1], + [1, 0, -1], + [-1, 0, -1], + [0, 1, 1], + [0, -1, 1], + [0, 1, -1], + [0, -1, -1] + ]; + this.grad4 = [ + [0, 1, 1, 1], + [0, 1, 1, -1], + [0, 1, -1, 1], + [0, 1, -1, -1], + [0, -1, 1, 1], + [0, -1, 1, -1], + [0, -1, -1, 1], + [0, -1, -1, -1], + [1, 0, 1, 1], + [1, 0, 1, -1], + [1, 0, -1, 1], + [1, 0, -1, -1], + [-1, 0, 1, 1], + [-1, 0, 1, -1], + [-1, 0, -1, 1], + [-1, 0, -1, -1], + [1, 1, 0, 1], + [1, 1, 0, -1], + [1, -1, 0, 1], + [1, -1, 0, -1], + [-1, 1, 0, 1], + [-1, 1, 0, -1], + [-1, -1, 0, 1], + [-1, -1, 0, -1], + [1, 1, 1, 0], + [1, 1, -1, 0], + [1, -1, 1, 0], + [1, -1, -1, 0], + [-1, 1, 1, 0], + [-1, 1, -1, 0], + [-1, -1, 1, 0], + [-1, -1, -1, 0] + ]; + this.p = []; + for (let i = 0;i < 256; i++) { + this.p[i] = Math.floor(r.random() * 256); + } + this.perm = []; + for (let i = 0;i < 512; i++) { + this.perm[i] = this.p[i & 255]; + } + this.simplex = [ + [0, 1, 2, 3], + [0, 1, 3, 2], + [0, 0, 0, 0], + [0, 2, 3, 1], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 2, 3, 0], + [0, 2, 1, 3], + [0, 0, 0, 0], + [0, 3, 1, 2], + [0, 3, 2, 1], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 3, 2, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 2, 0, 3], + [0, 0, 0, 0], + [1, 3, 0, 2], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [2, 3, 0, 1], + [2, 3, 1, 0], + [1, 0, 2, 3], + [1, 0, 3, 2], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [2, 0, 3, 1], + [0, 0, 0, 0], + [2, 1, 3, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [2, 0, 1, 3], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [3, 0, 1, 2], + [3, 0, 2, 1], + [0, 0, 0, 0], + [3, 1, 2, 0], + [2, 1, 0, 3], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [3, 1, 0, 2], + [0, 0, 0, 0], + [3, 2, 0, 1], + [3, 2, 1, 0] + ]; + } + dot(g3, x2, y3) { + return g3[0] * x2 + g3[1] * y3; + } + dot3(g3, x2, y3, z2) { + return g3[0] * x2 + g3[1] * y3 + g3[2] * z2; + } + dot4(g3, x2, y3, z2, w) { + return g3[0] * x2 + g3[1] * y3 + g3[2] * z2 + g3[3] * w; + } + noise(xin, yin) { + let n0; + let n1; + let n2; + const F22 = 0.5 * (Math.sqrt(3) - 1); + const s = (xin + yin) * F22; + const i = Math.floor(xin + s); + const j2 = Math.floor(yin + s); + const G2 = (3 - Math.sqrt(3)) / 6; + const t4 = (i + j2) * G2; + const X0 = i - t4; + const Y0 = j2 - t4; + const x02 = xin - X0; + const y0 = yin - Y0; + let i1; + let j1; + if (x02 > y0) { + i1 = 1; + j1 = 0; + } else { + i1 = 0; + j1 = 1; + } + const x1 = x02 - i1 + G2; + const y1 = y0 - j1 + G2; + const x2 = x02 - 1 + 2 * G2; + const y22 = y0 - 1 + 2 * G2; + const ii = i & 255; + const jj = j2 & 255; + const gi0 = this.perm[ii + this.perm[jj]] % 12; + const gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12; + const gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12; + let t02 = 0.5 - x02 * x02 - y0 * y0; + if (t02 < 0) + n0 = 0; + else { + t02 *= t02; + n0 = t02 * t02 * this.dot(this.grad3[gi0], x02, y0); + } + let t1 = 0.5 - x1 * x1 - y1 * y1; + if (t1 < 0) + n1 = 0; + else { + t1 *= t1; + n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1); + } + let t22 = 0.5 - x2 * x2 - y22 * y22; + if (t22 < 0) + n2 = 0; + else { + t22 *= t22; + n2 = t22 * t22 * this.dot(this.grad3[gi2], x2, y22); + } + return 70 * (n0 + n1 + n2); + } + noise3d(xin, yin, zin) { + let n0; + let n1; + let n2; + let n32; + const F3 = 1 / 3; + const s = (xin + yin + zin) * F3; + const i = Math.floor(xin + s); + const j2 = Math.floor(yin + s); + const k4 = Math.floor(zin + s); + const G3 = 1 / 6; + const t4 = (i + j2 + k4) * G3; + const X0 = i - t4; + const Y0 = j2 - t4; + const Z02 = k4 - t4; + const x02 = xin - X0; + const y0 = yin - Y0; + const z0 = zin - Z02; + let i1; + let j1; + let k12; + let i22; + let j22; + let k22; + if (x02 >= y0) { + if (y0 >= z0) { + i1 = 1; + j1 = 0; + k12 = 0; + i22 = 1; + j22 = 1; + k22 = 0; + } else if (x02 >= z0) { + i1 = 1; + j1 = 0; + k12 = 0; + i22 = 1; + j22 = 0; + k22 = 1; + } else { + i1 = 0; + j1 = 0; + k12 = 1; + i22 = 1; + j22 = 0; + k22 = 1; + } + } else { + if (y0 < z0) { + i1 = 0; + j1 = 0; + k12 = 1; + i22 = 0; + j22 = 1; + k22 = 1; + } else if (x02 < z0) { + i1 = 0; + j1 = 1; + k12 = 0; + i22 = 0; + j22 = 1; + k22 = 1; + } else { + i1 = 0; + j1 = 1; + k12 = 0; + i22 = 1; + j22 = 1; + k22 = 0; + } + } + const x1 = x02 - i1 + G3; + const y1 = y0 - j1 + G3; + const z1 = z0 - k12 + G3; + const x2 = x02 - i22 + 2 * G3; + const y22 = y0 - j22 + 2 * G3; + const z2 = z0 - k22 + 2 * G3; + const x3 = x02 - 1 + 3 * G3; + const y3 = y0 - 1 + 3 * G3; + const z3 = z0 - 1 + 3 * G3; + const ii = i & 255; + const jj = j2 & 255; + const kk = k4 & 255; + const gi0 = this.perm[ii + this.perm[jj + this.perm[kk]]] % 12; + const gi1 = this.perm[ii + i1 + this.perm[jj + j1 + this.perm[kk + k12]]] % 12; + const gi2 = this.perm[ii + i22 + this.perm[jj + j22 + this.perm[kk + k22]]] % 12; + const gi3 = this.perm[ii + 1 + this.perm[jj + 1 + this.perm[kk + 1]]] % 12; + let t02 = 0.6 - x02 * x02 - y0 * y0 - z0 * z0; + if (t02 < 0) + n0 = 0; + else { + t02 *= t02; + n0 = t02 * t02 * this.dot3(this.grad3[gi0], x02, y0, z0); + } + let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1; + if (t1 < 0) + n1 = 0; + else { + t1 *= t1; + n1 = t1 * t1 * this.dot3(this.grad3[gi1], x1, y1, z1); + } + let t22 = 0.6 - x2 * x2 - y22 * y22 - z2 * z2; + if (t22 < 0) + n2 = 0; + else { + t22 *= t22; + n2 = t22 * t22 * this.dot3(this.grad3[gi2], x2, y22, z2); + } + let t32 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3; + if (t32 < 0) + n32 = 0; + else { + t32 *= t32; + n32 = t32 * t32 * this.dot3(this.grad3[gi3], x3, y3, z3); + } + return 32 * (n0 + n1 + n2 + n32); + } + noise4d(x2, y3, z2, w) { + const grad4 = this.grad4; + const simplex = this.simplex; + const perm = this.perm; + const F4 = (Math.sqrt(5) - 1) / 4; + const G4 = (5 - Math.sqrt(5)) / 20; + let n0; + let n1; + let n2; + let n32; + let n4; + const s = (x2 + y3 + z2 + w) * F4; + const i = Math.floor(x2 + s); + const j2 = Math.floor(y3 + s); + const k4 = Math.floor(z2 + s); + const l2 = Math.floor(w + s); + const t4 = (i + j2 + k4 + l2) * G4; + const X0 = i - t4; + const Y0 = j2 - t4; + const Z02 = k4 - t4; + const W02 = l2 - t4; + const x02 = x2 - X0; + const y0 = y3 - Y0; + const z0 = z2 - Z02; + const w02 = w - W02; + const c1 = x02 > y0 ? 32 : 0; + const c2 = x02 > z0 ? 16 : 0; + const c3 = y0 > z0 ? 8 : 0; + const c4 = x02 > w02 ? 4 : 0; + const c5 = y0 > w02 ? 2 : 0; + const c6 = z0 > w02 ? 1 : 0; + const c = c1 + c2 + c3 + c4 + c5 + c6; + const i1 = simplex[c][0] >= 3 ? 1 : 0; + const j1 = simplex[c][1] >= 3 ? 1 : 0; + const k12 = simplex[c][2] >= 3 ? 1 : 0; + const l1 = simplex[c][3] >= 3 ? 1 : 0; + const i22 = simplex[c][0] >= 2 ? 1 : 0; + const j22 = simplex[c][1] >= 2 ? 1 : 0; + const k22 = simplex[c][2] >= 2 ? 1 : 0; + const l22 = simplex[c][3] >= 2 ? 1 : 0; + const i3 = simplex[c][0] >= 1 ? 1 : 0; + const j32 = simplex[c][1] >= 1 ? 1 : 0; + const k32 = simplex[c][2] >= 1 ? 1 : 0; + const l3 = simplex[c][3] >= 1 ? 1 : 0; + const x1 = x02 - i1 + G4; + const y1 = y0 - j1 + G4; + const z1 = z0 - k12 + G4; + const w1 = w02 - l1 + G4; + const x22 = x02 - i22 + 2 * G4; + const y22 = y0 - j22 + 2 * G4; + const z22 = z0 - k22 + 2 * G4; + const w2 = w02 - l22 + 2 * G4; + const x3 = x02 - i3 + 3 * G4; + const y32 = y0 - j32 + 3 * G4; + const z3 = z0 - k32 + 3 * G4; + const w3 = w02 - l3 + 3 * G4; + const x4 = x02 - 1 + 4 * G4; + const y4 = y0 - 1 + 4 * G4; + const z4 = z0 - 1 + 4 * G4; + const w4 = w02 - 1 + 4 * G4; + const ii = i & 255; + const jj = j2 & 255; + const kk = k4 & 255; + const ll = l2 & 255; + const gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; + const gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k12 + perm[ll + l1]]]] % 32; + const gi2 = perm[ii + i22 + perm[jj + j22 + perm[kk + k22 + perm[ll + l22]]]] % 32; + const gi3 = perm[ii + i3 + perm[jj + j32 + perm[kk + k32 + perm[ll + l3]]]] % 32; + const gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; + let t02 = 0.6 - x02 * x02 - y0 * y0 - z0 * z0 - w02 * w02; + if (t02 < 0) + n0 = 0; + else { + t02 *= t02; + n0 = t02 * t02 * this.dot4(grad4[gi0], x02, y0, z0, w02); + } + let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; + if (t1 < 0) + n1 = 0; + else { + t1 *= t1; + n1 = t1 * t1 * this.dot4(grad4[gi1], x1, y1, z1, w1); + } + let t22 = 0.6 - x22 * x22 - y22 * y22 - z22 * z22 - w2 * w2; + if (t22 < 0) + n2 = 0; + else { + t22 *= t22; + n2 = t22 * t22 * this.dot4(grad4[gi2], x22, y22, z22, w2); + } + let t32 = 0.6 - x3 * x3 - y32 * y32 - z3 * z3 - w3 * w3; + if (t32 < 0) + n32 = 0; + else { + t32 *= t32; + n32 = t32 * t32 * this.dot4(grad4[gi3], x3, y32, z3, w3); + } + let t42 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; + if (t42 < 0) + n4 = 0; + else { + t42 *= t42; + n4 = t42 * t42 * this.dot4(grad4[gi4], x4, y4, z4, w4); + } + return 27 * (n0 + n1 + n2 + n32 + n4); + } +} +// node_modules/three/examples/jsm/misc/ConvexObjectBreaker.js +var _v17 = new Vector3; +// node_modules/three/examples/jsm/misc/Gyroscope.js +var _translationObject = new Vector3; +var _quaternionObject = new Quaternion; +var _scaleObject = new Vector3; +var _translationWorld = new Vector3; +var _quaternionWorld = new Quaternion; +var _scaleWorld = new Vector3; +// node_modules/three/examples/jsm/modifiers/CurveModifier.js +var matrix2 = new Matrix4; +// node_modules/three/examples/jsm/modifiers/EdgeSplitModifier.js +var _A = new Vector3; +var _B = new Vector3; +var _C = new Vector3; +// node_modules/three/examples/jsm/modifiers/SimplifyModifier.js +var _cb2 = new Vector3; +var _ab2 = new Vector3; +// node_modules/three/examples/jsm/objects/Lensflare.js +class Lensflare extends Mesh { + constructor() { + super(Lensflare.Geometry, new MeshBasicMaterial({ opacity: 0, transparent: true })); + this.isLensflare = true; + this.type = "Lensflare"; + this.frustumCulled = false; + this.renderOrder = Infinity; + const positionScreen = new Vector3; + const positionView = new Vector3; + const tempMap = new FramebufferTexture(16, 16); + const occlusionMap = new FramebufferTexture(16, 16); + let currentType = UnsignedByteType; + const geometry = Lensflare.Geometry; + const material1a = new RawShaderMaterial({ + uniforms: { + scale: { value: null }, + screenPosition: { value: null } + }, + vertexShader: ` + + precision highp float; + + uniform vec3 screenPosition; + uniform vec2 scale; + + attribute vec3 position; + + void main() { + + gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); + + }`, + fragmentShader: ` + + precision highp float; + + void main() { + + gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 ); + + }`, + depthTest: true, + depthWrite: false, + transparent: false + }); + const material1b = new RawShaderMaterial({ + uniforms: { + map: { value: tempMap }, + scale: { value: null }, + screenPosition: { value: null } + }, + vertexShader: ` + + precision highp float; + + uniform vec3 screenPosition; + uniform vec2 scale; + + attribute vec3 position; + attribute vec2 uv; + + varying vec2 vUV; + + void main() { + + vUV = uv; + + gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); + + }`, + fragmentShader: ` + + precision highp float; + + uniform sampler2D map; + + varying vec2 vUV; + + void main() { + + gl_FragColor = texture2D( map, vUV ); + + }`, + depthTest: false, + depthWrite: false, + transparent: false + }); + const mesh1 = new Mesh(geometry, material1a); + const elements = []; + const shader = LensflareElement.Shader; + const material2 = new RawShaderMaterial({ + name: shader.name, + uniforms: { + map: { value: null }, + occlusionMap: { value: occlusionMap }, + color: { value: new Color(16777215) }, + scale: { value: new Vector2 }, + screenPosition: { value: new Vector3 } + }, + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + blending: AdditiveBlending, + transparent: true, + depthWrite: false + }); + const mesh2 = new Mesh(geometry, material2); + this.addElement = function(element) { + elements.push(element); + }; + const scale2 = new Vector2; + const screenPositionPixels = new Vector2; + const validArea = new Box2; + const viewport = new Vector4; + this.onBeforeRender = function(renderer2, scene, camera) { + renderer2.getCurrentViewport(viewport); + const renderTarget = renderer2.getRenderTarget(); + const type = renderTarget !== null ? renderTarget.texture.type : UnsignedByteType; + if (currentType !== type) { + tempMap.dispose(); + occlusionMap.dispose(); + tempMap.type = occlusionMap.type = type; + currentType = type; + } + const invAspect = viewport.w / viewport.z; + const halfViewportWidth = viewport.z / 2; + const halfViewportHeight = viewport.w / 2; + let size2 = 16 / viewport.w; + scale2.set(size2 * invAspect, size2); + validArea.min.set(viewport.x, viewport.y); + validArea.max.set(viewport.x + (viewport.z - 16), viewport.y + (viewport.w - 16)); + positionView.setFromMatrixPosition(this.matrixWorld); + positionView.applyMatrix4(camera.matrixWorldInverse); + if (positionView.z > 0) + return; + positionScreen.copy(positionView).applyMatrix4(camera.projectionMatrix); + screenPositionPixels.x = viewport.x + positionScreen.x * halfViewportWidth + halfViewportWidth - 8; + screenPositionPixels.y = viewport.y + positionScreen.y * halfViewportHeight + halfViewportHeight - 8; + if (validArea.containsPoint(screenPositionPixels)) { + renderer2.copyFramebufferToTexture(tempMap, screenPositionPixels); + let uniforms = material1a.uniforms; + uniforms["scale"].value = scale2; + uniforms["screenPosition"].value = positionScreen; + renderer2.renderBufferDirect(camera, null, geometry, material1a, mesh1, null); + renderer2.copyFramebufferToTexture(occlusionMap, screenPositionPixels); + uniforms = material1b.uniforms; + uniforms["scale"].value = scale2; + uniforms["screenPosition"].value = positionScreen; + renderer2.renderBufferDirect(camera, null, geometry, material1b, mesh1, null); + const vecX = -positionScreen.x * 2; + const vecY = -positionScreen.y * 2; + for (let i = 0, l2 = elements.length;i < l2; i++) { + const element = elements[i]; + const uniforms2 = material2.uniforms; + uniforms2["color"].value.copy(element.color); + uniforms2["map"].value = element.texture; + uniforms2["screenPosition"].value.x = positionScreen.x + vecX * element.distance; + uniforms2["screenPosition"].value.y = positionScreen.y + vecY * element.distance; + size2 = element.size / viewport.w; + const invAspect2 = viewport.w / viewport.z; + uniforms2["scale"].value.set(size2 * invAspect2, size2); + material2.uniformsNeedUpdate = true; + renderer2.renderBufferDirect(camera, null, geometry, material2, mesh2, null); + } + } + }; + this.dispose = function() { + material1a.dispose(); + material1b.dispose(); + material2.dispose(); + tempMap.dispose(); + occlusionMap.dispose(); + for (let i = 0, l2 = elements.length;i < l2; i++) { + elements[i].texture.dispose(); + } + }; + } +} + +class LensflareElement { + constructor(texture, size2 = 1, distance = 0, color = new Color(16777215)) { + this.texture = texture; + this.size = size2; + this.distance = distance; + this.color = color; + } +} +LensflareElement.Shader = { + name: "LensflareElementShader", + uniforms: { + map: { value: null }, + occlusionMap: { value: null }, + color: { value: null }, + scale: { value: null }, + screenPosition: { value: null } + }, + vertexShader: ` + + precision highp float; + + uniform vec3 screenPosition; + uniform vec2 scale; + + uniform sampler2D occlusionMap; + + attribute vec3 position; + attribute vec2 uv; + + varying vec2 vUV; + varying float vVisibility; + + void main() { + + vUV = uv; + + vec2 pos = position.xy; + + vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ); + visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) ); + visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) ); + visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ); + visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) ); + visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ); + visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) ); + visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ); + visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) ); + + vVisibility = visibility.r / 9.0; + vVisibility *= 1.0 - visibility.g / 9.0; + vVisibility *= visibility.b / 9.0; + + gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 ); + + }`, + fragmentShader: ` + + precision highp float; + + uniform sampler2D map; + uniform vec3 color; + + varying vec2 vUV; + varying float vVisibility; + + void main() { + + vec4 texture = texture2D( map, vUV ); + texture.a *= vVisibility; + gl_FragColor = texture; + gl_FragColor.rgb *= color; + + }` +}; +Lensflare.Geometry = function() { + const geometry = new BufferGeometry; + const float32Array = new Float32Array([ + -1, + -1, + 0, + 0, + 0, + 1, + -1, + 0, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + -1, + 1, + 0, + 0, + 1 + ]); + const interleavedBuffer = new InterleavedBuffer(float32Array, 5); + geometry.setIndex([0, 1, 2, 0, 2, 3]); + geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false)); + geometry.setAttribute("uv", new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false)); + return geometry; +}(); +// node_modules/three/examples/jsm/objects/MarchingCubes.js +var edgeTable = new Int32Array([ + 0, + 265, + 515, + 778, + 1030, + 1295, + 1541, + 1804, + 2060, + 2309, + 2575, + 2822, + 3082, + 3331, + 3593, + 3840, + 400, + 153, + 915, + 666, + 1430, + 1183, + 1941, + 1692, + 2460, + 2197, + 2975, + 2710, + 3482, + 3219, + 3993, + 3728, + 560, + 825, + 51, + 314, + 1590, + 1855, + 1077, + 1340, + 2620, + 2869, + 2111, + 2358, + 3642, + 3891, + 3129, + 3376, + 928, + 681, + 419, + 170, + 1958, + 1711, + 1445, + 1196, + 2988, + 2725, + 2479, + 2214, + 4010, + 3747, + 3497, + 3232, + 1120, + 1385, + 1635, + 1898, + 102, + 367, + 613, + 876, + 3180, + 3429, + 3695, + 3942, + 2154, + 2403, + 2665, + 2912, + 1520, + 1273, + 2035, + 1786, + 502, + 255, + 1013, + 764, + 3580, + 3317, + 4095, + 3830, + 2554, + 2291, + 3065, + 2800, + 1616, + 1881, + 1107, + 1370, + 598, + 863, + 85, + 348, + 3676, + 3925, + 3167, + 3414, + 2650, + 2899, + 2137, + 2384, + 1984, + 1737, + 1475, + 1226, + 966, + 719, + 453, + 204, + 4044, + 3781, + 3535, + 3270, + 3018, + 2755, + 2505, + 2240, + 2240, + 2505, + 2755, + 3018, + 3270, + 3535, + 3781, + 4044, + 204, + 453, + 719, + 966, + 1226, + 1475, + 1737, + 1984, + 2384, + 2137, + 2899, + 2650, + 3414, + 3167, + 3925, + 3676, + 348, + 85, + 863, + 598, + 1370, + 1107, + 1881, + 1616, + 2800, + 3065, + 2291, + 2554, + 3830, + 4095, + 3317, + 3580, + 764, + 1013, + 255, + 502, + 1786, + 2035, + 1273, + 1520, + 2912, + 2665, + 2403, + 2154, + 3942, + 3695, + 3429, + 3180, + 876, + 613, + 367, + 102, + 1898, + 1635, + 1385, + 1120, + 3232, + 3497, + 3747, + 4010, + 2214, + 2479, + 2725, + 2988, + 1196, + 1445, + 1711, + 1958, + 170, + 419, + 681, + 928, + 3376, + 3129, + 3891, + 3642, + 2358, + 2111, + 2869, + 2620, + 1340, + 1077, + 1855, + 1590, + 314, + 51, + 825, + 560, + 3728, + 3993, + 3219, + 3482, + 2710, + 2975, + 2197, + 2460, + 1692, + 1941, + 1183, + 1430, + 666, + 915, + 153, + 400, + 3840, + 3593, + 3331, + 3082, + 2822, + 2575, + 2309, + 2060, + 1804, + 1541, + 1295, + 1030, + 778, + 515, + 265, + 0 +]); +var triTable = new Int32Array([ + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 8, + 3, + 9, + 8, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 1, + 2, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 2, + 10, + 0, + 2, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 8, + 3, + 2, + 10, + 8, + 10, + 9, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 11, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 11, + 2, + 8, + 11, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 9, + 0, + 2, + 3, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 11, + 2, + 1, + 9, + 11, + 9, + 8, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 10, + 1, + 11, + 10, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 10, + 1, + 0, + 8, + 10, + 8, + 11, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 9, + 0, + 3, + 11, + 9, + 11, + 10, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 8, + 10, + 10, + 8, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 7, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 3, + 0, + 7, + 3, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 8, + 4, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 1, + 9, + 4, + 7, + 1, + 7, + 3, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 8, + 4, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 4, + 7, + 3, + 0, + 4, + 1, + 2, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 2, + 10, + 9, + 0, + 2, + 8, + 4, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 10, + 9, + 2, + 9, + 7, + 2, + 7, + 3, + 7, + 9, + 4, + -1, + -1, + -1, + -1, + 8, + 4, + 7, + 3, + 11, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 4, + 7, + 11, + 2, + 4, + 2, + 0, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 0, + 1, + 8, + 4, + 7, + 2, + 3, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 7, + 11, + 9, + 4, + 11, + 9, + 11, + 2, + 9, + 2, + 1, + -1, + -1, + -1, + -1, + 3, + 10, + 1, + 3, + 11, + 10, + 7, + 8, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 11, + 10, + 1, + 4, + 11, + 1, + 0, + 4, + 7, + 11, + 4, + -1, + -1, + -1, + -1, + 4, + 7, + 8, + 9, + 0, + 11, + 9, + 11, + 10, + 11, + 0, + 3, + -1, + -1, + -1, + -1, + 4, + 7, + 11, + 4, + 11, + 9, + 9, + 11, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + 0, + 8, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 5, + 4, + 1, + 5, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 5, + 4, + 8, + 3, + 5, + 3, + 1, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 9, + 5, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 8, + 1, + 2, + 10, + 4, + 9, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 2, + 10, + 5, + 4, + 2, + 4, + 0, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 10, + 5, + 3, + 2, + 5, + 3, + 5, + 4, + 3, + 4, + 8, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + 2, + 3, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 11, + 2, + 0, + 8, + 11, + 4, + 9, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 5, + 4, + 0, + 1, + 5, + 2, + 3, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 1, + 5, + 2, + 5, + 8, + 2, + 8, + 11, + 4, + 8, + 5, + -1, + -1, + -1, + -1, + 10, + 3, + 11, + 10, + 1, + 3, + 9, + 5, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 9, + 5, + 0, + 8, + 1, + 8, + 10, + 1, + 8, + 11, + 10, + -1, + -1, + -1, + -1, + 5, + 4, + 0, + 5, + 0, + 11, + 5, + 11, + 10, + 11, + 0, + 3, + -1, + -1, + -1, + -1, + 5, + 4, + 8, + 5, + 8, + 10, + 10, + 8, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 7, + 8, + 5, + 7, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 3, + 0, + 9, + 5, + 3, + 5, + 7, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 7, + 8, + 0, + 1, + 7, + 1, + 5, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 5, + 3, + 3, + 5, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 7, + 8, + 9, + 5, + 7, + 10, + 1, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 1, + 2, + 9, + 5, + 0, + 5, + 3, + 0, + 5, + 7, + 3, + -1, + -1, + -1, + -1, + 8, + 0, + 2, + 8, + 2, + 5, + 8, + 5, + 7, + 10, + 5, + 2, + -1, + -1, + -1, + -1, + 2, + 10, + 5, + 2, + 5, + 3, + 3, + 5, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 9, + 5, + 7, + 8, + 9, + 3, + 11, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 7, + 9, + 7, + 2, + 9, + 2, + 0, + 2, + 7, + 11, + -1, + -1, + -1, + -1, + 2, + 3, + 11, + 0, + 1, + 8, + 1, + 7, + 8, + 1, + 5, + 7, + -1, + -1, + -1, + -1, + 11, + 2, + 1, + 11, + 1, + 7, + 7, + 1, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 8, + 8, + 5, + 7, + 10, + 1, + 3, + 10, + 3, + 11, + -1, + -1, + -1, + -1, + 5, + 7, + 0, + 5, + 0, + 9, + 7, + 11, + 0, + 1, + 0, + 10, + 11, + 10, + 0, + -1, + 11, + 10, + 0, + 11, + 0, + 3, + 10, + 5, + 0, + 8, + 0, + 7, + 5, + 7, + 0, + -1, + 11, + 10, + 5, + 7, + 11, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 6, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 0, + 1, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 8, + 3, + 1, + 9, + 8, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 6, + 5, + 2, + 6, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 6, + 5, + 1, + 2, + 6, + 3, + 0, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 6, + 5, + 9, + 0, + 6, + 0, + 2, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 9, + 8, + 5, + 8, + 2, + 5, + 2, + 6, + 3, + 2, + 8, + -1, + -1, + -1, + -1, + 2, + 3, + 11, + 10, + 6, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 0, + 8, + 11, + 2, + 0, + 10, + 6, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 2, + 3, + 11, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 10, + 6, + 1, + 9, + 2, + 9, + 11, + 2, + 9, + 8, + 11, + -1, + -1, + -1, + -1, + 6, + 3, + 11, + 6, + 5, + 3, + 5, + 1, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 11, + 0, + 11, + 5, + 0, + 5, + 1, + 5, + 11, + 6, + -1, + -1, + -1, + -1, + 3, + 11, + 6, + 0, + 3, + 6, + 0, + 6, + 5, + 0, + 5, + 9, + -1, + -1, + -1, + -1, + 6, + 5, + 9, + 6, + 9, + 11, + 11, + 9, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 10, + 6, + 4, + 7, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 3, + 0, + 4, + 7, + 3, + 6, + 5, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 9, + 0, + 5, + 10, + 6, + 8, + 4, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 6, + 5, + 1, + 9, + 7, + 1, + 7, + 3, + 7, + 9, + 4, + -1, + -1, + -1, + -1, + 6, + 1, + 2, + 6, + 5, + 1, + 4, + 7, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 5, + 5, + 2, + 6, + 3, + 0, + 4, + 3, + 4, + 7, + -1, + -1, + -1, + -1, + 8, + 4, + 7, + 9, + 0, + 5, + 0, + 6, + 5, + 0, + 2, + 6, + -1, + -1, + -1, + -1, + 7, + 3, + 9, + 7, + 9, + 4, + 3, + 2, + 9, + 5, + 9, + 6, + 2, + 6, + 9, + -1, + 3, + 11, + 2, + 7, + 8, + 4, + 10, + 6, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 10, + 6, + 4, + 7, + 2, + 4, + 2, + 0, + 2, + 7, + 11, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 4, + 7, + 8, + 2, + 3, + 11, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + 9, + 2, + 1, + 9, + 11, + 2, + 9, + 4, + 11, + 7, + 11, + 4, + 5, + 10, + 6, + -1, + 8, + 4, + 7, + 3, + 11, + 5, + 3, + 5, + 1, + 5, + 11, + 6, + -1, + -1, + -1, + -1, + 5, + 1, + 11, + 5, + 11, + 6, + 1, + 0, + 11, + 7, + 11, + 4, + 0, + 4, + 11, + -1, + 0, + 5, + 9, + 0, + 6, + 5, + 0, + 3, + 6, + 11, + 6, + 3, + 8, + 4, + 7, + -1, + 6, + 5, + 9, + 6, + 9, + 11, + 4, + 7, + 9, + 7, + 11, + 9, + -1, + -1, + -1, + -1, + 10, + 4, + 9, + 6, + 4, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 10, + 6, + 4, + 9, + 10, + 0, + 8, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 0, + 1, + 10, + 6, + 0, + 6, + 4, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 3, + 1, + 8, + 1, + 6, + 8, + 6, + 4, + 6, + 1, + 10, + -1, + -1, + -1, + -1, + 1, + 4, + 9, + 1, + 2, + 4, + 2, + 6, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 8, + 1, + 2, + 9, + 2, + 4, + 9, + 2, + 6, + 4, + -1, + -1, + -1, + -1, + 0, + 2, + 4, + 4, + 2, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 3, + 2, + 8, + 2, + 4, + 4, + 2, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 4, + 9, + 10, + 6, + 4, + 11, + 2, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 2, + 2, + 8, + 11, + 4, + 9, + 10, + 4, + 10, + 6, + -1, + -1, + -1, + -1, + 3, + 11, + 2, + 0, + 1, + 6, + 0, + 6, + 4, + 6, + 1, + 10, + -1, + -1, + -1, + -1, + 6, + 4, + 1, + 6, + 1, + 10, + 4, + 8, + 1, + 2, + 1, + 11, + 8, + 11, + 1, + -1, + 9, + 6, + 4, + 9, + 3, + 6, + 9, + 1, + 3, + 11, + 6, + 3, + -1, + -1, + -1, + -1, + 8, + 11, + 1, + 8, + 1, + 0, + 11, + 6, + 1, + 9, + 1, + 4, + 6, + 4, + 1, + -1, + 3, + 11, + 6, + 3, + 6, + 0, + 0, + 6, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 6, + 4, + 8, + 11, + 6, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 10, + 6, + 7, + 8, + 10, + 8, + 9, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 7, + 3, + 0, + 10, + 7, + 0, + 9, + 10, + 6, + 7, + 10, + -1, + -1, + -1, + -1, + 10, + 6, + 7, + 1, + 10, + 7, + 1, + 7, + 8, + 1, + 8, + 0, + -1, + -1, + -1, + -1, + 10, + 6, + 7, + 10, + 7, + 1, + 1, + 7, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 6, + 1, + 6, + 8, + 1, + 8, + 9, + 8, + 6, + 7, + -1, + -1, + -1, + -1, + 2, + 6, + 9, + 2, + 9, + 1, + 6, + 7, + 9, + 0, + 9, + 3, + 7, + 3, + 9, + -1, + 7, + 8, + 0, + 7, + 0, + 6, + 6, + 0, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 3, + 2, + 6, + 7, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 3, + 11, + 10, + 6, + 8, + 10, + 8, + 9, + 8, + 6, + 7, + -1, + -1, + -1, + -1, + 2, + 0, + 7, + 2, + 7, + 11, + 0, + 9, + 7, + 6, + 7, + 10, + 9, + 10, + 7, + -1, + 1, + 8, + 0, + 1, + 7, + 8, + 1, + 10, + 7, + 6, + 7, + 10, + 2, + 3, + 11, + -1, + 11, + 2, + 1, + 11, + 1, + 7, + 10, + 6, + 1, + 6, + 7, + 1, + -1, + -1, + -1, + -1, + 8, + 9, + 6, + 8, + 6, + 7, + 9, + 1, + 6, + 11, + 6, + 3, + 1, + 3, + 6, + -1, + 0, + 9, + 1, + 11, + 6, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 8, + 0, + 7, + 0, + 6, + 3, + 11, + 0, + 11, + 6, + 0, + -1, + -1, + -1, + -1, + 7, + 11, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 6, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 8, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 1, + 9, + 8, + 3, + 1, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 1, + 2, + 6, + 11, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 3, + 0, + 8, + 6, + 11, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 9, + 0, + 2, + 10, + 9, + 6, + 11, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 6, + 11, + 7, + 2, + 10, + 3, + 10, + 8, + 3, + 10, + 9, + 8, + -1, + -1, + -1, + -1, + 7, + 2, + 3, + 6, + 2, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 0, + 8, + 7, + 6, + 0, + 6, + 2, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 7, + 6, + 2, + 3, + 7, + 0, + 1, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 6, + 2, + 1, + 8, + 6, + 1, + 9, + 8, + 8, + 7, + 6, + -1, + -1, + -1, + -1, + 10, + 7, + 6, + 10, + 1, + 7, + 1, + 3, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 7, + 6, + 1, + 7, + 10, + 1, + 8, + 7, + 1, + 0, + 8, + -1, + -1, + -1, + -1, + 0, + 3, + 7, + 0, + 7, + 10, + 0, + 10, + 9, + 6, + 10, + 7, + -1, + -1, + -1, + -1, + 7, + 6, + 10, + 7, + 10, + 8, + 8, + 10, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 6, + 8, + 4, + 11, + 8, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 6, + 11, + 3, + 0, + 6, + 0, + 4, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 6, + 11, + 8, + 4, + 6, + 9, + 0, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 4, + 6, + 9, + 6, + 3, + 9, + 3, + 1, + 11, + 3, + 6, + -1, + -1, + -1, + -1, + 6, + 8, + 4, + 6, + 11, + 8, + 2, + 10, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 3, + 0, + 11, + 0, + 6, + 11, + 0, + 4, + 6, + -1, + -1, + -1, + -1, + 4, + 11, + 8, + 4, + 6, + 11, + 0, + 2, + 9, + 2, + 10, + 9, + -1, + -1, + -1, + -1, + 10, + 9, + 3, + 10, + 3, + 2, + 9, + 4, + 3, + 11, + 3, + 6, + 4, + 6, + 3, + -1, + 8, + 2, + 3, + 8, + 4, + 2, + 4, + 6, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 4, + 2, + 4, + 6, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 9, + 0, + 2, + 3, + 4, + 2, + 4, + 6, + 4, + 3, + 8, + -1, + -1, + -1, + -1, + 1, + 9, + 4, + 1, + 4, + 2, + 2, + 4, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 1, + 3, + 8, + 6, + 1, + 8, + 4, + 6, + 6, + 10, + 1, + -1, + -1, + -1, + -1, + 10, + 1, + 0, + 10, + 0, + 6, + 6, + 0, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 6, + 3, + 4, + 3, + 8, + 6, + 10, + 3, + 0, + 3, + 9, + 10, + 9, + 3, + -1, + 10, + 9, + 4, + 6, + 10, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 9, + 5, + 7, + 6, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 4, + 9, + 5, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 0, + 1, + 5, + 4, + 0, + 7, + 6, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 7, + 6, + 8, + 3, + 4, + 3, + 5, + 4, + 3, + 1, + 5, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + 10, + 1, + 2, + 7, + 6, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 6, + 11, + 7, + 1, + 2, + 10, + 0, + 8, + 3, + 4, + 9, + 5, + -1, + -1, + -1, + -1, + 7, + 6, + 11, + 5, + 4, + 10, + 4, + 2, + 10, + 4, + 0, + 2, + -1, + -1, + -1, + -1, + 3, + 4, + 8, + 3, + 5, + 4, + 3, + 2, + 5, + 10, + 5, + 2, + 11, + 7, + 6, + -1, + 7, + 2, + 3, + 7, + 6, + 2, + 5, + 4, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + 0, + 8, + 6, + 0, + 6, + 2, + 6, + 8, + 7, + -1, + -1, + -1, + -1, + 3, + 6, + 2, + 3, + 7, + 6, + 1, + 5, + 0, + 5, + 4, + 0, + -1, + -1, + -1, + -1, + 6, + 2, + 8, + 6, + 8, + 7, + 2, + 1, + 8, + 4, + 8, + 5, + 1, + 5, + 8, + -1, + 9, + 5, + 4, + 10, + 1, + 6, + 1, + 7, + 6, + 1, + 3, + 7, + -1, + -1, + -1, + -1, + 1, + 6, + 10, + 1, + 7, + 6, + 1, + 0, + 7, + 8, + 7, + 0, + 9, + 5, + 4, + -1, + 4, + 0, + 10, + 4, + 10, + 5, + 0, + 3, + 10, + 6, + 10, + 7, + 3, + 7, + 10, + -1, + 7, + 6, + 10, + 7, + 10, + 8, + 5, + 4, + 10, + 4, + 8, + 10, + -1, + -1, + -1, + -1, + 6, + 9, + 5, + 6, + 11, + 9, + 11, + 8, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 6, + 11, + 0, + 6, + 3, + 0, + 5, + 6, + 0, + 9, + 5, + -1, + -1, + -1, + -1, + 0, + 11, + 8, + 0, + 5, + 11, + 0, + 1, + 5, + 5, + 6, + 11, + -1, + -1, + -1, + -1, + 6, + 11, + 3, + 6, + 3, + 5, + 5, + 3, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 9, + 5, + 11, + 9, + 11, + 8, + 11, + 5, + 6, + -1, + -1, + -1, + -1, + 0, + 11, + 3, + 0, + 6, + 11, + 0, + 9, + 6, + 5, + 6, + 9, + 1, + 2, + 10, + -1, + 11, + 8, + 5, + 11, + 5, + 6, + 8, + 0, + 5, + 10, + 5, + 2, + 0, + 2, + 5, + -1, + 6, + 11, + 3, + 6, + 3, + 5, + 2, + 10, + 3, + 10, + 5, + 3, + -1, + -1, + -1, + -1, + 5, + 8, + 9, + 5, + 2, + 8, + 5, + 6, + 2, + 3, + 8, + 2, + -1, + -1, + -1, + -1, + 9, + 5, + 6, + 9, + 6, + 0, + 0, + 6, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 5, + 8, + 1, + 8, + 0, + 5, + 6, + 8, + 3, + 8, + 2, + 6, + 2, + 8, + -1, + 1, + 5, + 6, + 2, + 1, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 3, + 6, + 1, + 6, + 10, + 3, + 8, + 6, + 5, + 6, + 9, + 8, + 9, + 6, + -1, + 10, + 1, + 0, + 10, + 0, + 6, + 9, + 5, + 0, + 5, + 6, + 0, + -1, + -1, + -1, + -1, + 0, + 3, + 8, + 5, + 6, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 5, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 5, + 10, + 7, + 5, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 5, + 10, + 11, + 7, + 5, + 8, + 3, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 11, + 7, + 5, + 10, + 11, + 1, + 9, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 7, + 5, + 10, + 11, + 7, + 9, + 8, + 1, + 8, + 3, + 1, + -1, + -1, + -1, + -1, + 11, + 1, + 2, + 11, + 7, + 1, + 7, + 5, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 1, + 2, + 7, + 1, + 7, + 5, + 7, + 2, + 11, + -1, + -1, + -1, + -1, + 9, + 7, + 5, + 9, + 2, + 7, + 9, + 0, + 2, + 2, + 11, + 7, + -1, + -1, + -1, + -1, + 7, + 5, + 2, + 7, + 2, + 11, + 5, + 9, + 2, + 3, + 2, + 8, + 9, + 8, + 2, + -1, + 2, + 5, + 10, + 2, + 3, + 5, + 3, + 7, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 2, + 0, + 8, + 5, + 2, + 8, + 7, + 5, + 10, + 2, + 5, + -1, + -1, + -1, + -1, + 9, + 0, + 1, + 5, + 10, + 3, + 5, + 3, + 7, + 3, + 10, + 2, + -1, + -1, + -1, + -1, + 9, + 8, + 2, + 9, + 2, + 1, + 8, + 7, + 2, + 10, + 2, + 5, + 7, + 5, + 2, + -1, + 1, + 3, + 5, + 3, + 7, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 7, + 0, + 7, + 1, + 1, + 7, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 0, + 3, + 9, + 3, + 5, + 5, + 3, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 8, + 7, + 5, + 9, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 8, + 4, + 5, + 10, + 8, + 10, + 11, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 0, + 4, + 5, + 11, + 0, + 5, + 10, + 11, + 11, + 3, + 0, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 8, + 4, + 10, + 8, + 10, + 11, + 10, + 4, + 5, + -1, + -1, + -1, + -1, + 10, + 11, + 4, + 10, + 4, + 5, + 11, + 3, + 4, + 9, + 4, + 1, + 3, + 1, + 4, + -1, + 2, + 5, + 1, + 2, + 8, + 5, + 2, + 11, + 8, + 4, + 5, + 8, + -1, + -1, + -1, + -1, + 0, + 4, + 11, + 0, + 11, + 3, + 4, + 5, + 11, + 2, + 11, + 1, + 5, + 1, + 11, + -1, + 0, + 2, + 5, + 0, + 5, + 9, + 2, + 11, + 5, + 4, + 5, + 8, + 11, + 8, + 5, + -1, + 9, + 4, + 5, + 2, + 11, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 5, + 10, + 3, + 5, + 2, + 3, + 4, + 5, + 3, + 8, + 4, + -1, + -1, + -1, + -1, + 5, + 10, + 2, + 5, + 2, + 4, + 4, + 2, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 10, + 2, + 3, + 5, + 10, + 3, + 8, + 5, + 4, + 5, + 8, + 0, + 1, + 9, + -1, + 5, + 10, + 2, + 5, + 2, + 4, + 1, + 9, + 2, + 9, + 4, + 2, + -1, + -1, + -1, + -1, + 8, + 4, + 5, + 8, + 5, + 3, + 3, + 5, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 4, + 5, + 1, + 0, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 4, + 5, + 8, + 5, + 3, + 9, + 0, + 5, + 0, + 3, + 5, + -1, + -1, + -1, + -1, + 9, + 4, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 11, + 7, + 4, + 9, + 11, + 9, + 10, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 4, + 9, + 7, + 9, + 11, + 7, + 9, + 10, + 11, + -1, + -1, + -1, + -1, + 1, + 10, + 11, + 1, + 11, + 4, + 1, + 4, + 0, + 7, + 4, + 11, + -1, + -1, + -1, + -1, + 3, + 1, + 4, + 3, + 4, + 8, + 1, + 10, + 4, + 7, + 4, + 11, + 10, + 11, + 4, + -1, + 4, + 11, + 7, + 9, + 11, + 4, + 9, + 2, + 11, + 9, + 1, + 2, + -1, + -1, + -1, + -1, + 9, + 7, + 4, + 9, + 11, + 7, + 9, + 1, + 11, + 2, + 11, + 1, + 0, + 8, + 3, + -1, + 11, + 7, + 4, + 11, + 4, + 2, + 2, + 4, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 7, + 4, + 11, + 4, + 2, + 8, + 3, + 4, + 3, + 2, + 4, + -1, + -1, + -1, + -1, + 2, + 9, + 10, + 2, + 7, + 9, + 2, + 3, + 7, + 7, + 4, + 9, + -1, + -1, + -1, + -1, + 9, + 10, + 7, + 9, + 7, + 4, + 10, + 2, + 7, + 8, + 7, + 0, + 2, + 0, + 7, + -1, + 3, + 7, + 10, + 3, + 10, + 2, + 7, + 4, + 10, + 1, + 10, + 0, + 4, + 0, + 10, + -1, + 1, + 10, + 2, + 8, + 7, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 9, + 1, + 4, + 1, + 7, + 7, + 1, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 9, + 1, + 4, + 1, + 7, + 0, + 8, + 1, + 8, + 7, + 1, + -1, + -1, + -1, + -1, + 4, + 0, + 3, + 7, + 4, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 8, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 10, + 8, + 10, + 11, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 9, + 3, + 9, + 11, + 11, + 9, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 10, + 0, + 10, + 8, + 8, + 10, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 1, + 10, + 11, + 3, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 11, + 1, + 11, + 9, + 9, + 11, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 9, + 3, + 9, + 11, + 1, + 2, + 9, + 2, + 11, + 9, + -1, + -1, + -1, + -1, + 0, + 2, + 11, + 8, + 0, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 2, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 3, + 8, + 2, + 8, + 10, + 10, + 8, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 10, + 2, + 0, + 9, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 3, + 8, + 2, + 8, + 10, + 0, + 1, + 8, + 1, + 10, + 8, + -1, + -1, + -1, + -1, + 1, + 10, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 3, + 8, + 9, + 1, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 9, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 3, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1 +]); +// node_modules/three/examples/jsm/objects/Reflector.js +class Reflector extends Mesh { + constructor(geometry, options = {}) { + super(geometry); + this.isReflector = true; + this.type = "Reflector"; + this.camera = new PerspectiveCamera; + const scope = this; + const color = options.color !== undefined ? new Color(options.color) : new Color(8355711); + const textureWidth = options.textureWidth || 512; + const textureHeight = options.textureHeight || 512; + const clipBias = options.clipBias || 0; + const shader = options.shader || Reflector.ReflectorShader; + const multisample = options.multisample !== undefined ? options.multisample : 4; + const reflectorPlane = new Plane; + const normal = new Vector3; + const reflectorWorldPosition = new Vector3; + const cameraWorldPosition = new Vector3; + const rotationMatrix2 = new Matrix4; + const lookAtPosition = new Vector3(0, 0, -1); + const clipPlane = new Vector4; + const view = new Vector3; + const target = new Vector3; + const q2 = new Vector4; + const textureMatrix = new Matrix4; + const virtualCamera = this.camera; + const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, { samples: multisample, type: HalfFloatType }); + const material = new ShaderMaterial({ + name: shader.name !== undefined ? shader.name : "unspecified", + uniforms: UniformsUtils.clone(shader.uniforms), + fragmentShader: shader.fragmentShader, + vertexShader: shader.vertexShader + }); + material.uniforms["tDiffuse"].value = renderTarget.texture; + material.uniforms["color"].value = color; + material.uniforms["textureMatrix"].value = textureMatrix; + this.material = material; + this.onBeforeRender = function(renderer2, scene, camera) { + reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld); + cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); + rotationMatrix2.extractRotation(scope.matrixWorld); + normal.set(0, 0, 1); + normal.applyMatrix4(rotationMatrix2); + view.subVectors(reflectorWorldPosition, cameraWorldPosition); + if (view.dot(normal) > 0) + return; + view.reflect(normal).negate(); + view.add(reflectorWorldPosition); + rotationMatrix2.extractRotation(camera.matrixWorld); + lookAtPosition.set(0, 0, -1); + lookAtPosition.applyMatrix4(rotationMatrix2); + lookAtPosition.add(cameraWorldPosition); + target.subVectors(reflectorWorldPosition, lookAtPosition); + target.reflect(normal).negate(); + target.add(reflectorWorldPosition); + virtualCamera.position.copy(view); + virtualCamera.up.set(0, 1, 0); + virtualCamera.up.applyMatrix4(rotationMatrix2); + virtualCamera.up.reflect(normal); + virtualCamera.lookAt(target); + virtualCamera.far = camera.far; + virtualCamera.updateMatrixWorld(); + virtualCamera.projectionMatrix.copy(camera.projectionMatrix); + textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + textureMatrix.multiply(virtualCamera.projectionMatrix); + textureMatrix.multiply(virtualCamera.matrixWorldInverse); + textureMatrix.multiply(scope.matrixWorld); + reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition); + reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse); + clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant); + const projectionMatrix = virtualCamera.projectionMatrix; + q2.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; + q2.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; + q2.z = -1; + q2.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; + clipPlane.multiplyScalar(2 / clipPlane.dot(q2)); + projectionMatrix.elements[2] = clipPlane.x; + projectionMatrix.elements[6] = clipPlane.y; + projectionMatrix.elements[10] = clipPlane.z + 1 - clipBias; + projectionMatrix.elements[14] = clipPlane.w; + scope.visible = false; + const currentRenderTarget = renderer2.getRenderTarget(); + const currentXrEnabled = renderer2.xr.enabled; + const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate; + renderer2.xr.enabled = false; + renderer2.shadowMap.autoUpdate = false; + renderer2.setRenderTarget(renderTarget); + renderer2.state.buffers.depth.setMask(true); + if (renderer2.autoClear === false) + renderer2.clear(); + renderer2.render(scene, virtualCamera); + renderer2.xr.enabled = currentXrEnabled; + renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate; + renderer2.setRenderTarget(currentRenderTarget); + const viewport = camera.viewport; + if (viewport !== undefined) { + renderer2.state.viewport(viewport); + } + scope.visible = true; + }; + this.getRenderTarget = function() { + return renderTarget; + }; + this.dispose = function() { + renderTarget.dispose(); + scope.material.dispose(); + }; + } +} +Reflector.ReflectorShader = { + name: "ReflectorShader", + uniforms: { + color: { + value: null + }, + tDiffuse: { + value: null + }, + textureMatrix: { + value: null + } + }, + vertexShader: ` + uniform mat4 textureMatrix; + varying vec4 vUv; + + #include + #include + + void main() { + + vUv = textureMatrix * vec4( position, 1.0 ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + #include + + }`, + fragmentShader: ` + uniform vec3 color; + uniform sampler2D tDiffuse; + varying vec4 vUv; + + #include + + float blendOverlay( float base, float blend ) { + + return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); + + } + + vec3 blendOverlay( vec3 base, vec3 blend ) { + + return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); + + } + + void main() { + + #include + + vec4 base = texture2DProj( tDiffuse, vUv ); + gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); + + #include + #include + + }` +}; +// node_modules/three/examples/jsm/objects/ReflectorForSSRPass.js +class ReflectorForSSRPass extends Mesh { + constructor(geometry, options = {}) { + super(geometry); + this.isReflectorForSSRPass = true; + this.type = "ReflectorForSSRPass"; + const scope = this; + const color = options.color !== undefined ? new Color(options.color) : new Color(8355711); + const textureWidth = options.textureWidth || 512; + const textureHeight = options.textureHeight || 512; + const clipBias = options.clipBias || 0; + const shader = options.shader || ReflectorForSSRPass.ReflectorShader; + const useDepthTexture = options.useDepthTexture === true; + const yAxis2 = new Vector3(0, 1, 0); + const vecTemp0 = new Vector3; + const vecTemp1 = new Vector3; + scope.needsUpdate = false; + scope.maxDistance = ReflectorForSSRPass.ReflectorShader.uniforms.maxDistance.value; + scope.opacity = ReflectorForSSRPass.ReflectorShader.uniforms.opacity.value; + scope.color = color; + scope.resolution = options.resolution || new Vector2(window.innerWidth, window.innerHeight); + scope._distanceAttenuation = ReflectorForSSRPass.ReflectorShader.defines.DISTANCE_ATTENUATION; + Object.defineProperty(scope, "distanceAttenuation", { + get() { + return scope._distanceAttenuation; + }, + set(val2) { + if (scope._distanceAttenuation === val2) + return; + scope._distanceAttenuation = val2; + scope.material.defines.DISTANCE_ATTENUATION = val2; + scope.material.needsUpdate = true; + } + }); + scope._fresnel = ReflectorForSSRPass.ReflectorShader.defines.FRESNEL; + Object.defineProperty(scope, "fresnel", { + get() { + return scope._fresnel; + }, + set(val2) { + if (scope._fresnel === val2) + return; + scope._fresnel = val2; + scope.material.defines.FRESNEL = val2; + scope.material.needsUpdate = true; + } + }); + const normal = new Vector3; + const reflectorWorldPosition = new Vector3; + const cameraWorldPosition = new Vector3; + const rotationMatrix2 = new Matrix4; + const lookAtPosition = new Vector3(0, 0, -1); + const view = new Vector3; + const target = new Vector3; + const textureMatrix = new Matrix4; + const virtualCamera = new PerspectiveCamera; + let depthTexture; + if (useDepthTexture) { + depthTexture = new DepthTexture; + depthTexture.type = UnsignedShortType; + depthTexture.minFilter = NearestFilter; + depthTexture.magFilter = NearestFilter; + } + const parameters = { + depthTexture: useDepthTexture ? depthTexture : null, + type: HalfFloatType + }; + const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, parameters); + const material = new ShaderMaterial({ + name: shader.name !== undefined ? shader.name : "unspecified", + transparent: useDepthTexture, + defines: Object.assign({}, ReflectorForSSRPass.ReflectorShader.defines, { + useDepthTexture + }), + uniforms: UniformsUtils.clone(shader.uniforms), + fragmentShader: shader.fragmentShader, + vertexShader: shader.vertexShader + }); + material.uniforms["tDiffuse"].value = renderTarget.texture; + material.uniforms["color"].value = scope.color; + material.uniforms["textureMatrix"].value = textureMatrix; + if (useDepthTexture) { + material.uniforms["tDepth"].value = renderTarget.depthTexture; + } + this.material = material; + const globalPlane = new Plane(new Vector3(0, 1, 0), clipBias); + const globalPlanes = [globalPlane]; + this.doRender = function(renderer2, scene, camera) { + material.uniforms["maxDistance"].value = scope.maxDistance; + material.uniforms["color"].value = scope.color; + material.uniforms["opacity"].value = scope.opacity; + vecTemp0.copy(camera.position).normalize(); + vecTemp1.copy(vecTemp0).reflect(yAxis2); + material.uniforms["fresnelCoe"].value = (vecTemp0.dot(vecTemp1) + 1) / 2; + reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld); + cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); + rotationMatrix2.extractRotation(scope.matrixWorld); + normal.set(0, 0, 1); + normal.applyMatrix4(rotationMatrix2); + view.subVectors(reflectorWorldPosition, cameraWorldPosition); + if (view.dot(normal) > 0) + return; + view.reflect(normal).negate(); + view.add(reflectorWorldPosition); + rotationMatrix2.extractRotation(camera.matrixWorld); + lookAtPosition.set(0, 0, -1); + lookAtPosition.applyMatrix4(rotationMatrix2); + lookAtPosition.add(cameraWorldPosition); + target.subVectors(reflectorWorldPosition, lookAtPosition); + target.reflect(normal).negate(); + target.add(reflectorWorldPosition); + virtualCamera.position.copy(view); + virtualCamera.up.set(0, 1, 0); + virtualCamera.up.applyMatrix4(rotationMatrix2); + virtualCamera.up.reflect(normal); + virtualCamera.lookAt(target); + virtualCamera.far = camera.far; + virtualCamera.updateMatrixWorld(); + virtualCamera.projectionMatrix.copy(camera.projectionMatrix); + material.uniforms["virtualCameraNear"].value = camera.near; + material.uniforms["virtualCameraFar"].value = camera.far; + material.uniforms["virtualCameraMatrixWorld"].value = virtualCamera.matrixWorld; + material.uniforms["virtualCameraProjectionMatrix"].value = camera.projectionMatrix; + material.uniforms["virtualCameraProjectionMatrixInverse"].value = camera.projectionMatrixInverse; + material.uniforms["resolution"].value = scope.resolution; + textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + textureMatrix.multiply(virtualCamera.projectionMatrix); + textureMatrix.multiply(virtualCamera.matrixWorldInverse); + textureMatrix.multiply(scope.matrixWorld); + const currentRenderTarget = renderer2.getRenderTarget(); + const currentXrEnabled = renderer2.xr.enabled; + const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate; + const currentClippingPlanes = renderer2.clippingPlanes; + renderer2.xr.enabled = false; + renderer2.shadowMap.autoUpdate = false; + renderer2.clippingPlanes = globalPlanes; + renderer2.setRenderTarget(renderTarget); + renderer2.state.buffers.depth.setMask(true); + if (renderer2.autoClear === false) + renderer2.clear(); + renderer2.render(scene, virtualCamera); + renderer2.xr.enabled = currentXrEnabled; + renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate; + renderer2.clippingPlanes = currentClippingPlanes; + renderer2.setRenderTarget(currentRenderTarget); + const viewport = camera.viewport; + if (viewport !== undefined) { + renderer2.state.viewport(viewport); + } + }; + this.getRenderTarget = function() { + return renderTarget; + }; + } +} +ReflectorForSSRPass.ReflectorShader = { + name: "ReflectorShader", + defines: { + DISTANCE_ATTENUATION: true, + FRESNEL: true + }, + uniforms: { + color: { value: null }, + tDiffuse: { value: null }, + tDepth: { value: null }, + textureMatrix: { value: new Matrix4 }, + maxDistance: { value: 180 }, + opacity: { value: 0.5 }, + fresnelCoe: { value: null }, + virtualCameraNear: { value: null }, + virtualCameraFar: { value: null }, + virtualCameraProjectionMatrix: { value: new Matrix4 }, + virtualCameraMatrixWorld: { value: new Matrix4 }, + virtualCameraProjectionMatrixInverse: { value: new Matrix4 }, + resolution: { value: new Vector2 } + }, + vertexShader: ` + uniform mat4 textureMatrix; + varying vec4 vUv; + + void main() { + + vUv = textureMatrix * vec4( position, 1.0 ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + uniform vec3 color; + uniform sampler2D tDiffuse; + uniform sampler2D tDepth; + uniform float maxDistance; + uniform float opacity; + uniform float fresnelCoe; + uniform float virtualCameraNear; + uniform float virtualCameraFar; + uniform mat4 virtualCameraProjectionMatrix; + uniform mat4 virtualCameraProjectionMatrixInverse; + uniform mat4 virtualCameraMatrixWorld; + uniform vec2 resolution; + varying vec4 vUv; + #include + float blendOverlay( float base, float blend ) { + return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); + } + vec3 blendOverlay( vec3 base, vec3 blend ) { + return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); + } + float getDepth( const in vec2 uv ) { + return texture2D( tDepth, uv ).x; + } + float getViewZ( const in float depth ) { + return perspectiveDepthToViewZ( depth, virtualCameraNear, virtualCameraFar ); + } + vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { + vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc + clipPosition *= clipW; //clip + return ( virtualCameraProjectionMatrixInverse * clipPosition ).xyz;//view + } + void main() { + vec4 base = texture2DProj( tDiffuse, vUv ); + #ifdef useDepthTexture + vec2 uv=(gl_FragCoord.xy-.5)/resolution.xy; + uv.x=1.-uv.x; + float depth = texture2DProj( tDepth, vUv ).r; + float viewZ = getViewZ( depth ); + float clipW = virtualCameraProjectionMatrix[2][3] * viewZ+virtualCameraProjectionMatrix[3][3]; + vec3 viewPosition=getViewPosition( uv, depth, clipW ); + vec3 worldPosition=(virtualCameraMatrixWorld*vec4(viewPosition,1)).xyz; + if(worldPosition.y>maxDistance) discard; + float op=opacity; + #ifdef DISTANCE_ATTENUATION + float ratio=1.-(worldPosition.y/maxDistance); + float attenuation=ratio*ratio; + op=opacity*attenuation; + #endif + #ifdef FRESNEL + op*=fresnelCoe; + #endif + gl_FragColor = vec4( blendOverlay( base.rgb, color ), op ); + #else + gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); + #endif + } + ` +}; +// node_modules/three/examples/jsm/objects/Refractor.js +class Refractor extends Mesh { + constructor(geometry, options = {}) { + super(geometry); + this.isRefractor = true; + this.type = "Refractor"; + this.camera = new PerspectiveCamera; + const scope = this; + const color = options.color !== undefined ? new Color(options.color) : new Color(8355711); + const textureWidth = options.textureWidth || 512; + const textureHeight = options.textureHeight || 512; + const clipBias = options.clipBias || 0; + const shader = options.shader || Refractor.RefractorShader; + const multisample = options.multisample !== undefined ? options.multisample : 4; + const virtualCamera = this.camera; + virtualCamera.matrixAutoUpdate = false; + virtualCamera.userData.refractor = true; + const refractorPlane = new Plane; + const textureMatrix = new Matrix4; + const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, { samples: multisample, type: HalfFloatType }); + this.material = new ShaderMaterial({ + name: shader.name !== undefined ? shader.name : "unspecified", + uniforms: UniformsUtils.clone(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + transparent: true + }); + this.material.uniforms["color"].value = color; + this.material.uniforms["tDiffuse"].value = renderTarget.texture; + this.material.uniforms["textureMatrix"].value = textureMatrix; + const visible = function() { + const refractorWorldPosition = new Vector3; + const cameraWorldPosition = new Vector3; + const rotationMatrix2 = new Matrix4; + const view = new Vector3; + const normal = new Vector3; + return function visible(camera) { + refractorWorldPosition.setFromMatrixPosition(scope.matrixWorld); + cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); + view.subVectors(refractorWorldPosition, cameraWorldPosition); + rotationMatrix2.extractRotation(scope.matrixWorld); + normal.set(0, 0, 1); + normal.applyMatrix4(rotationMatrix2); + return view.dot(normal) < 0; + }; + }(); + const updateRefractorPlane = function() { + const normal = new Vector3; + const position2 = new Vector3; + const quaternion = new Quaternion; + const scale2 = new Vector3; + return function updateRefractorPlane() { + scope.matrixWorld.decompose(position2, quaternion, scale2); + normal.set(0, 0, 1).applyQuaternion(quaternion).normalize(); + normal.negate(); + refractorPlane.setFromNormalAndCoplanarPoint(normal, position2); + }; + }(); + const updateVirtualCamera = function() { + const clipPlane = new Plane; + const clipVector = new Vector4; + const q2 = new Vector4; + return function updateVirtualCamera(camera) { + virtualCamera.matrixWorld.copy(camera.matrixWorld); + virtualCamera.matrixWorldInverse.copy(virtualCamera.matrixWorld).invert(); + virtualCamera.projectionMatrix.copy(camera.projectionMatrix); + virtualCamera.far = camera.far; + clipPlane.copy(refractorPlane); + clipPlane.applyMatrix4(virtualCamera.matrixWorldInverse); + clipVector.set(clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.constant); + const projectionMatrix = virtualCamera.projectionMatrix; + q2.x = (Math.sign(clipVector.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; + q2.y = (Math.sign(clipVector.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; + q2.z = -1; + q2.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; + clipVector.multiplyScalar(2 / clipVector.dot(q2)); + projectionMatrix.elements[2] = clipVector.x; + projectionMatrix.elements[6] = clipVector.y; + projectionMatrix.elements[10] = clipVector.z + 1 - clipBias; + projectionMatrix.elements[14] = clipVector.w; + }; + }(); + function updateTextureMatrix(camera) { + textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + textureMatrix.multiply(camera.projectionMatrix); + textureMatrix.multiply(camera.matrixWorldInverse); + textureMatrix.multiply(scope.matrixWorld); + } + function render(renderer2, scene, camera) { + scope.visible = false; + const currentRenderTarget = renderer2.getRenderTarget(); + const currentXrEnabled = renderer2.xr.enabled; + const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate; + renderer2.xr.enabled = false; + renderer2.shadowMap.autoUpdate = false; + renderer2.setRenderTarget(renderTarget); + if (renderer2.autoClear === false) + renderer2.clear(); + renderer2.render(scene, virtualCamera); + renderer2.xr.enabled = currentXrEnabled; + renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate; + renderer2.setRenderTarget(currentRenderTarget); + const viewport = camera.viewport; + if (viewport !== undefined) { + renderer2.state.viewport(viewport); + } + scope.visible = true; + } + this.onBeforeRender = function(renderer2, scene, camera) { + if (camera.userData.refractor === true) + return; + if (!visible(camera) === true) + return; + updateRefractorPlane(); + updateTextureMatrix(camera); + updateVirtualCamera(camera); + render(renderer2, scene, camera); + }; + this.getRenderTarget = function() { + return renderTarget; + }; + this.dispose = function() { + renderTarget.dispose(); + scope.material.dispose(); + }; + } +} +Refractor.RefractorShader = { + name: "RefractorShader", + uniforms: { + color: { + value: null + }, + tDiffuse: { + value: null + }, + textureMatrix: { + value: null + } + }, + vertexShader: ` + + uniform mat4 textureMatrix; + + varying vec4 vUv; + + void main() { + + vUv = textureMatrix * vec4( position, 1.0 ); + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform vec3 color; + uniform sampler2D tDiffuse; + + varying vec4 vUv; + + float blendOverlay( float base, float blend ) { + + return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); + + } + + vec3 blendOverlay( vec3 base, vec3 blend ) { + + return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); + + } + + void main() { + + vec4 base = texture2DProj( tDiffuse, vUv ); + gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); + + #include + #include + + }` +}; +// node_modules/three/examples/jsm/objects/ShadowMesh.js +var _shadowMatrix = new Matrix4; +// node_modules/three/examples/jsm/objects/Sky.js +class Sky extends Mesh { + constructor() { + const shader = Sky.SkyShader; + const material = new ShaderMaterial({ + name: shader.name, + uniforms: UniformsUtils.clone(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + depthWrite: false + }); + super(new BoxGeometry(1, 1, 1), material); + this.isSky = true; + } +} +Sky.SkyShader = { + name: "SkyShader", + uniforms: { + turbidity: { value: 2 }, + rayleigh: { value: 1 }, + mieCoefficient: { value: 0.005 }, + mieDirectionalG: { value: 0.8 }, + sunPosition: { value: new Vector3 }, + up: { value: new Vector3(0, 1, 0) } + }, + vertexShader: ` + uniform vec3 sunPosition; + uniform float rayleigh; + uniform float turbidity; + uniform float mieCoefficient; + uniform vec3 up; + + varying vec3 vWorldPosition; + varying vec3 vSunDirection; + varying float vSunfade; + varying vec3 vBetaR; + varying vec3 vBetaM; + varying float vSunE; + + // constants for atmospheric scattering + const float e = 2.71828182845904523536028747135266249775724709369995957; + const float pi = 3.141592653589793238462643383279502884197169; + + // wavelength of used primaries, according to preetham + const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 ); + // this pre-calculation replaces older TotalRayleigh(vec3 lambda) function: + // (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn)) + const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 ); + + // mie stuff + // K coefficient for the primaries + const float v = 4.0; + const vec3 K = vec3( 0.686, 0.678, 0.666 ); + // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K + const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 ); + + // earth shadow hack + // cutoffAngle = pi / 1.95; + const float cutoffAngle = 1.6110731556870734; + const float steepness = 1.5; + const float EE = 1000.0; + + float sunIntensity( float zenithAngleCos ) { + zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 ); + return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) ); + } + + vec3 totalMie( float T ) { + float c = ( 0.2 * T ) * 10E-18; + return 0.434 * c * MieConst; + } + + void main() { + + vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); + vWorldPosition = worldPosition.xyz; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + gl_Position.z = gl_Position.w; // set z to camera.far + + vSunDirection = normalize( sunPosition ); + + vSunE = sunIntensity( dot( vSunDirection, up ) ); + + vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 ); + + float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) ); + + // extinction (absorption + out scattering) + // rayleigh coefficients + vBetaR = totalRayleigh * rayleighCoefficient; + + // mie coefficients + vBetaM = totalMie( turbidity ) * mieCoefficient; + + }`, + fragmentShader: ` + varying vec3 vWorldPosition; + varying vec3 vSunDirection; + varying float vSunfade; + varying vec3 vBetaR; + varying vec3 vBetaM; + varying float vSunE; + + uniform float mieDirectionalG; + uniform vec3 up; + + // constants for atmospheric scattering + const float pi = 3.141592653589793238462643383279502884197169; + + const float n = 1.0003; // refractive index of air + const float N = 2.545E25; // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius) + + // optical length at zenith for molecules + const float rayleighZenithLength = 8.4E3; + const float mieZenithLength = 1.25E3; + // 66 arc seconds -> degrees, and the cosine of that + const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324; + + // 3.0 / ( 16.0 * pi ) + const float THREE_OVER_SIXTEENPI = 0.05968310365946075; + // 1.0 / ( 4.0 * pi ) + const float ONE_OVER_FOURPI = 0.07957747154594767; + + float rayleighPhase( float cosTheta ) { + return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) ); + } + + float hgPhase( float cosTheta, float g ) { + float g2 = pow( g, 2.0 ); + float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 ); + return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse ); + } + + void main() { + + vec3 direction = normalize( vWorldPosition - cameraPosition ); + + // optical length + // cutoff angle at 90 to avoid singularity in next formula. + float zenithAngle = acos( max( 0.0, dot( up, direction ) ) ); + float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) ); + float sR = rayleighZenithLength * inverse; + float sM = mieZenithLength * inverse; + + // combined extinction factor + vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) ); + + // in scattering + float cosTheta = dot( direction, vSunDirection ); + + float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 ); + vec3 betaRTheta = vBetaR * rPhase; + + float mPhase = hgPhase( cosTheta, mieDirectionalG ); + vec3 betaMTheta = vBetaM * mPhase; + + vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) ); + Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) ); + + // nightsky + float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2] + float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2] + vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 ); + vec3 L0 = vec3( 0.1 ) * Fex; + + // composition + solar disc + float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta ); + L0 += ( vSunE * 19000.0 * Fex ) * sundisk; + + vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 ); + + vec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) ); + + gl_FragColor = vec4( retColor, 1.0 ); + + #include + #include + + }` +}; +// node_modules/three/examples/jsm/objects/Water2.js +class Water extends Mesh { + constructor(geometry, options = {}) { + super(geometry); + this.isWater = true; + this.type = "Water"; + const scope = this; + const color = options.color !== undefined ? new Color(options.color) : new Color(16777215); + const textureWidth = options.textureWidth !== undefined ? options.textureWidth : 512; + const textureHeight = options.textureHeight !== undefined ? options.textureHeight : 512; + const clipBias = options.clipBias !== undefined ? options.clipBias : 0; + const flowDirection = options.flowDirection !== undefined ? options.flowDirection : new Vector2(1, 0); + const flowSpeed = options.flowSpeed !== undefined ? options.flowSpeed : 0.03; + const reflectivity = options.reflectivity !== undefined ? options.reflectivity : 0.02; + const scale2 = options.scale !== undefined ? options.scale : 1; + const shader = options.shader !== undefined ? options.shader : Water.WaterShader; + const textureLoader = new TextureLoader; + const flowMap = options.flowMap || undefined; + const normalMap0 = options.normalMap0 || textureLoader.load("textures/water/Water_1_M_Normal.jpg"); + const normalMap1 = options.normalMap1 || textureLoader.load("textures/water/Water_2_M_Normal.jpg"); + const cycle = 0.15; + const halfCycle = cycle * 0.5; + const textureMatrix = new Matrix4; + const clock = new Clock; + if (Reflector === undefined) { + console.error("THREE.Water: Required component Reflector not found."); + return; + } + if (Refractor === undefined) { + console.error("THREE.Water: Required component Refractor not found."); + return; + } + const reflector = new Reflector(geometry, { + textureWidth, + textureHeight, + clipBias + }); + const refractor = new Refractor(geometry, { + textureWidth, + textureHeight, + clipBias + }); + reflector.matrixAutoUpdate = false; + refractor.matrixAutoUpdate = false; + this.material = new ShaderMaterial({ + name: shader.name, + uniforms: UniformsUtils.merge([ + UniformsLib["fog"], + shader.uniforms + ]), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + transparent: true, + fog: true + }); + if (flowMap !== undefined) { + this.material.defines.USE_FLOWMAP = ""; + this.material.uniforms["tFlowMap"] = { + type: "t", + value: flowMap + }; + } else { + this.material.uniforms["flowDirection"] = { + type: "v2", + value: flowDirection + }; + } + normalMap0.wrapS = normalMap0.wrapT = RepeatWrapping; + normalMap1.wrapS = normalMap1.wrapT = RepeatWrapping; + this.material.uniforms["tReflectionMap"].value = reflector.getRenderTarget().texture; + this.material.uniforms["tRefractionMap"].value = refractor.getRenderTarget().texture; + this.material.uniforms["tNormalMap0"].value = normalMap0; + this.material.uniforms["tNormalMap1"].value = normalMap1; + this.material.uniforms["color"].value = color; + this.material.uniforms["reflectivity"].value = reflectivity; + this.material.uniforms["textureMatrix"].value = textureMatrix; + this.material.uniforms["config"].value.x = 0; + this.material.uniforms["config"].value.y = halfCycle; + this.material.uniforms["config"].value.z = halfCycle; + this.material.uniforms["config"].value.w = scale2; + function updateTextureMatrix(camera) { + textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + textureMatrix.multiply(camera.projectionMatrix); + textureMatrix.multiply(camera.matrixWorldInverse); + textureMatrix.multiply(scope.matrixWorld); + } + function updateFlow() { + const delta = clock.getDelta(); + const config = scope.material.uniforms["config"]; + config.value.x += flowSpeed * delta; + config.value.y = config.value.x + halfCycle; + if (config.value.x >= cycle) { + config.value.x = 0; + config.value.y = halfCycle; + } else if (config.value.y >= cycle) { + config.value.y = config.value.y - cycle; + } + } + this.onBeforeRender = function(renderer2, scene, camera) { + updateTextureMatrix(camera); + updateFlow(); + scope.visible = false; + reflector.matrixWorld.copy(scope.matrixWorld); + refractor.matrixWorld.copy(scope.matrixWorld); + reflector.onBeforeRender(renderer2, scene, camera); + refractor.onBeforeRender(renderer2, scene, camera); + scope.visible = true; + }; + } +} +Water.WaterShader = { + name: "WaterShader", + uniforms: { + color: { + type: "c", + value: null + }, + reflectivity: { + type: "f", + value: 0 + }, + tReflectionMap: { + type: "t", + value: null + }, + tRefractionMap: { + type: "t", + value: null + }, + tNormalMap0: { + type: "t", + value: null + }, + tNormalMap1: { + type: "t", + value: null + }, + textureMatrix: { + type: "m4", + value: null + }, + config: { + type: "v4", + value: new Vector4 + } + }, + vertexShader: ` + + #include + #include + #include + + uniform mat4 textureMatrix; + + varying vec4 vCoord; + varying vec2 vUv; + varying vec3 vToEye; + + void main() { + + vUv = uv; + vCoord = textureMatrix * vec4( position, 1.0 ); + + vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); + vToEye = cameraPosition - worldPosition.xyz; + + vec4 mvPosition = viewMatrix * worldPosition; // used in fog_vertex + gl_Position = projectionMatrix * mvPosition; + + #include + #include + + }`, + fragmentShader: ` + + #include + #include + #include + + uniform sampler2D tReflectionMap; + uniform sampler2D tRefractionMap; + uniform sampler2D tNormalMap0; + uniform sampler2D tNormalMap1; + + #ifdef USE_FLOWMAP + uniform sampler2D tFlowMap; + #else + uniform vec2 flowDirection; + #endif + + uniform vec3 color; + uniform float reflectivity; + uniform vec4 config; + + varying vec4 vCoord; + varying vec2 vUv; + varying vec3 vToEye; + + void main() { + + #include + + float flowMapOffset0 = config.x; + float flowMapOffset1 = config.y; + float halfCycle = config.z; + float scale = config.w; + + vec3 toEye = normalize( vToEye ); + + // determine flow direction + vec2 flow; + #ifdef USE_FLOWMAP + flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0; + #else + flow = flowDirection; + #endif + flow.x *= - 1.0; + + // sample normal maps (distort uvs with flowdata) + vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 ); + vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 ); + + // linear interpolate to get the final normal color + float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle; + vec4 normalColor = mix( normalColor0, normalColor1, flowLerp ); + + // calculate normal vector + vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) ); + + // calculate the fresnel term to blend reflection and refraction maps + float theta = max( dot( toEye, normal ), 0.0 ); + float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 ); + + // calculate final uv coords + vec3 coord = vCoord.xyz / vCoord.w; + vec2 uv = coord.xy + coord.z * normal.xz * 0.05; + + vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) ); + vec4 refractColor = texture2D( tRefractionMap, uv ); + + // multiply water color with the mix of both textures + gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance ); + + #include + #include + #include + + }` +}; +// node_modules/three/examples/jsm/physics/RapierPhysics.js +var _scale3 = new Vector3(1, 1, 1); +var ZERO = new Vector3; +// node_modules/three/examples/jsm/shaders/CopyShader.js +var CopyShader = { + name: "CopyShader", + uniforms: { + tDiffuse: { value: null }, + opacity: { value: 1 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform float opacity; + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + gl_FragColor = opacity * texel; + + + }` +}; +// node_modules/three/examples/jsm/shaders/ConvolutionShader.js +var ConvolutionShader = { + name: "ConvolutionShader", + defines: { + KERNEL_SIZE_FLOAT: "25.0", + KERNEL_SIZE_INT: "25" + }, + uniforms: { + tDiffuse: { value: null }, + uImageIncrement: { value: new Vector2(0.001953125, 0) }, + cKernel: { value: [] } + }, + vertexShader: ` + + uniform vec2 uImageIncrement; + + varying vec2 vUv; + + void main() { + + vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform float cKernel[ KERNEL_SIZE_INT ]; + + uniform sampler2D tDiffuse; + uniform vec2 uImageIncrement; + + varying vec2 vUv; + + void main() { + + vec2 imageCoord = vUv; + vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 ); + + for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) { + + sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ]; + imageCoord += uImageIncrement; + + } + + gl_FragColor = sum; + + }`, + buildKernel: function(sigma) { + const kMaxKernelSize = 25; + let kernelSize = 2 * Math.ceil(sigma * 3) + 1; + if (kernelSize > kMaxKernelSize) + kernelSize = kMaxKernelSize; + const halfWidth = (kernelSize - 1) * 0.5; + const values2 = new Array(kernelSize); + let sum2 = 0; + for (let i = 0;i < kernelSize; ++i) { + values2[i] = gauss(i - halfWidth, sigma); + sum2 += values2[i]; + } + for (let i = 0;i < kernelSize; ++i) + values2[i] /= sum2; + return values2; + } +}; +function gauss(x2, sigma) { + return Math.exp(-(x2 * x2) / (2 * sigma * sigma)); +} + +// node_modules/three/examples/jsm/postprocessing/BloomPass.js +class BloomPass extends Pass { + constructor(strength = 1, kernelSize = 25, sigma = 4) { + super(); + this.renderTargetX = new WebGLRenderTarget(1, 1, { type: HalfFloatType }); + this.renderTargetX.texture.name = "BloomPass.x"; + this.renderTargetY = new WebGLRenderTarget(1, 1, { type: HalfFloatType }); + this.renderTargetY.texture.name = "BloomPass.y"; + this.combineUniforms = UniformsUtils.clone(CombineShader.uniforms); + this.combineUniforms["strength"].value = strength; + this.materialCombine = new ShaderMaterial({ + name: CombineShader.name, + uniforms: this.combineUniforms, + vertexShader: CombineShader.vertexShader, + fragmentShader: CombineShader.fragmentShader, + blending: AdditiveBlending, + transparent: true + }); + const convolutionShader = ConvolutionShader; + this.convolutionUniforms = UniformsUtils.clone(convolutionShader.uniforms); + this.convolutionUniforms["uImageIncrement"].value = BloomPass.blurX; + this.convolutionUniforms["cKernel"].value = ConvolutionShader.buildKernel(sigma); + this.materialConvolution = new ShaderMaterial({ + name: convolutionShader.name, + uniforms: this.convolutionUniforms, + vertexShader: convolutionShader.vertexShader, + fragmentShader: convolutionShader.fragmentShader, + defines: { + KERNEL_SIZE_FLOAT: kernelSize.toFixed(1), + KERNEL_SIZE_INT: kernelSize.toFixed(0) + } + }); + this.needsSwap = false; + this.fsQuad = new FullScreenQuad(null); + } + render(renderer2, writeBuffer, readBuffer, deltaTime, maskActive) { + if (maskActive) + renderer2.state.buffers.stencil.setTest(false); + this.fsQuad.material = this.materialConvolution; + this.convolutionUniforms["tDiffuse"].value = readBuffer.texture; + this.convolutionUniforms["uImageIncrement"].value = BloomPass.blurX; + renderer2.setRenderTarget(this.renderTargetX); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.convolutionUniforms["tDiffuse"].value = this.renderTargetX.texture; + this.convolutionUniforms["uImageIncrement"].value = BloomPass.blurY; + renderer2.setRenderTarget(this.renderTargetY); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.materialCombine; + this.combineUniforms["tDiffuse"].value = this.renderTargetY.texture; + if (maskActive) + renderer2.state.buffers.stencil.setTest(true); + renderer2.setRenderTarget(readBuffer); + if (this.clear) + renderer2.clear(); + this.fsQuad.render(renderer2); + } + setSize(width2, height2) { + this.renderTargetX.setSize(width2, height2); + this.renderTargetY.setSize(width2, height2); + } + dispose() { + this.renderTargetX.dispose(); + this.renderTargetY.dispose(); + this.materialCombine.dispose(); + this.materialConvolution.dispose(); + this.fsQuad.dispose(); + } +} +var CombineShader = { + name: "CombineShader", + uniforms: { + tDiffuse: { value: null }, + strength: { value: 1 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform float strength; + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + gl_FragColor = strength * texel; + + }` +}; +BloomPass.blurX = new Vector2(0.001953125, 0); +BloomPass.blurY = new Vector2(0, 0.001953125); +// node_modules/three/examples/jsm/shaders/DotScreenShader.js +var DotScreenShader = { + name: "DotScreenShader", + uniforms: { + tDiffuse: { value: null }, + tSize: { value: new Vector2(256, 256) }, + center: { value: new Vector2(0.5, 0.5) }, + angle: { value: 1.57 }, + scale: { value: 1 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform vec2 center; + uniform float angle; + uniform float scale; + uniform vec2 tSize; + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + float pattern() { + + float s = sin( angle ), c = cos( angle ); + + vec2 tex = vUv * tSize - center; + vec2 point = vec2( c * tex.x - s * tex.y, s * tex.x + c * tex.y ) * scale; + + return ( sin( point.x ) * sin( point.y ) ) * 4.0; + + } + + void main() { + + vec4 color = texture2D( tDiffuse, vUv ); + + float average = ( color.r + color.g + color.b ) / 3.0; + + gl_FragColor = vec4( vec3( average * 10.0 - 5.0 + pattern() ), color.a ); + + }` +}; +// node_modules/three/examples/jsm/shaders/GTAOShader.js +var GTAOShader = { + name: "GTAOShader", + defines: { + PERSPECTIVE_CAMERA: 1, + SAMPLES: 16, + NORMAL_VECTOR_TYPE: 1, + DEPTH_SWIZZLING: "x", + SCREEN_SPACE_RADIUS: 0, + SCREEN_SPACE_RADIUS_SCALE: 100, + SCENE_CLIP_BOX: 0 + }, + uniforms: { + tNormal: { value: null }, + tDepth: { value: null }, + tNoise: { value: null }, + resolution: { value: new Vector2 }, + cameraNear: { value: null }, + cameraFar: { value: null }, + cameraProjectionMatrix: { value: new Matrix4 }, + cameraProjectionMatrixInverse: { value: new Matrix4 }, + cameraWorldMatrix: { value: new Matrix4 }, + radius: { value: 0.25 }, + distanceExponent: { value: 1 }, + thickness: { value: 1 }, + distanceFallOff: { value: 1 }, + scale: { value: 1 }, + sceneBoxMin: { value: new Vector3(-1, -1, -1) }, + sceneBoxMax: { value: new Vector3(1, 1, 1) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + varying vec2 vUv; + uniform highp sampler2D tNormal; + uniform highp sampler2D tDepth; + uniform sampler2D tNoise; + uniform vec2 resolution; + uniform float cameraNear; + uniform float cameraFar; + uniform mat4 cameraProjectionMatrix; + uniform mat4 cameraProjectionMatrixInverse; + uniform mat4 cameraWorldMatrix; + uniform float radius; + uniform float distanceExponent; + uniform float thickness; + uniform float distanceFallOff; + uniform float scale; + #if SCENE_CLIP_BOX == 1 + uniform vec3 sceneBoxMin; + uniform vec3 sceneBoxMax; + #endif + + #include + #include + + #ifndef FRAGMENT_OUTPUT + #define FRAGMENT_OUTPUT vec4(vec3(ao), 1.) + #endif + + vec3 getViewPosition(const in vec2 screenPosition, const in float depth) { + vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); + vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; + return viewSpacePosition.xyz / viewSpacePosition.w; + } + + float getDepth(const vec2 uv) { + return textureLod(tDepth, uv.xy, 0.0).DEPTH_SWIZZLING; + } + + float fetchDepth(const ivec2 uv) { + return texelFetch(tDepth, uv.xy, 0).DEPTH_SWIZZLING; + } + + float getViewZ(const in float depth) { + #if PERSPECTIVE_CAMERA == 1 + return perspectiveDepthToViewZ(depth, cameraNear, cameraFar); + #else + return orthographicDepthToViewZ(depth, cameraNear, cameraFar); + #endif + } + + vec3 computeNormalFromDepth(const vec2 uv) { + vec2 size = vec2(textureSize(tDepth, 0)); + ivec2 p = ivec2(uv * size); + float c0 = fetchDepth(p); + float l2 = fetchDepth(p - ivec2(2, 0)); + float l1 = fetchDepth(p - ivec2(1, 0)); + float r1 = fetchDepth(p + ivec2(1, 0)); + float r2 = fetchDepth(p + ivec2(2, 0)); + float b2 = fetchDepth(p - ivec2(0, 2)); + float b1 = fetchDepth(p - ivec2(0, 1)); + float t1 = fetchDepth(p + ivec2(0, 1)); + float t2 = fetchDepth(p + ivec2(0, 2)); + float dl = abs((2.0 * l1 - l2) - c0); + float dr = abs((2.0 * r1 - r2) - c0); + float db = abs((2.0 * b1 - b2) - c0); + float dt = abs((2.0 * t1 - t2) - c0); + vec3 ce = getViewPosition(uv, c0).xyz; + vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; + vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; + return normalize(cross(dpdx, dpdy)); + } + + vec3 getViewNormal(const vec2 uv) { + #if NORMAL_VECTOR_TYPE == 2 + return normalize(textureLod(tNormal, uv, 0.).rgb); + #elif NORMAL_VECTOR_TYPE == 1 + return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); + #else + return computeNormalFromDepth(uv); + #endif + } + + vec3 getSceneUvAndDepth(vec3 sampleViewPos) { + vec4 sampleClipPos = cameraProjectionMatrix * vec4(sampleViewPos, 1.); + vec2 sampleUv = sampleClipPos.xy / sampleClipPos.w * 0.5 + 0.5; + float sampleSceneDepth = getDepth(sampleUv); + return vec3(sampleUv, sampleSceneDepth); + } + + void main() { + float depth = getDepth(vUv.xy); + if (depth >= 1.0) { + discard; + return; + } + vec3 viewPos = getViewPosition(vUv, depth); + vec3 viewNormal = getViewNormal(vUv); + + float radiusToUse = radius; + float distanceFalloffToUse = thickness; + #if SCREEN_SPACE_RADIUS == 1 + float radiusScale = getViewPosition(vec2(0.5 + float(SCREEN_SPACE_RADIUS_SCALE) / resolution.x, 0.0), depth).x; + radiusToUse *= radiusScale; + distanceFalloffToUse *= radiusScale; + #endif + + #if SCENE_CLIP_BOX == 1 + vec3 worldPos = (cameraWorldMatrix * vec4(viewPos, 1.0)).xyz; + float boxDistance = length(max(vec3(0.0), max(sceneBoxMin - worldPos, worldPos - sceneBoxMax))); + if (boxDistance > radiusToUse) { + discard; + return; + } + #endif + + vec2 noiseResolution = vec2(textureSize(tNoise, 0)); + vec2 noiseUv = vUv * resolution / noiseResolution; + vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); + vec3 randomVec = noiseTexel.xyz * 2.0 - 1.0; + vec3 tangent = normalize(vec3(randomVec.xy, 0.)); + vec3 bitangent = vec3(-tangent.y, tangent.x, 0.); + mat3 kernelMatrix = mat3(tangent, bitangent, vec3(0., 0., 1.)); + + const int DIRECTIONS = SAMPLES < 30 ? 3 : 5; + const int STEPS = (SAMPLES + DIRECTIONS - 1) / DIRECTIONS; + float ao = 0.0; + for (int i = 0; i < DIRECTIONS; ++i) { + + float angle = float(i) / float(DIRECTIONS) * PI; + vec4 sampleDir = vec4(cos(angle), sin(angle), 0., 0.5 + 0.5 * noiseTexel.w); + sampleDir.xyz = normalize(kernelMatrix * sampleDir.xyz); + + vec3 viewDir = normalize(-viewPos.xyz); + vec3 sliceBitangent = normalize(cross(sampleDir.xyz, viewDir)); + vec3 sliceTangent = cross(sliceBitangent, viewDir); + vec3 normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent)); + + vec3 tangentToNormalInSlice = cross(normalInSlice, sliceBitangent); + vec2 cosHorizons = vec2(dot(viewDir, tangentToNormalInSlice), dot(viewDir, -tangentToNormalInSlice)); + + for (int j = 0; j < STEPS; ++j) { + vec3 sampleViewOffset = sampleDir.xyz * radiusToUse * sampleDir.w * pow(float(j + 1) / float(STEPS), distanceExponent); + + vec3 sampleSceneUvDepth = getSceneUvAndDepth(viewPos + sampleViewOffset); + vec3 sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); + vec3 viewDelta = sampleSceneViewPos - viewPos; + if (abs(viewDelta.z) < thickness) { + float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); + cosHorizons.x += max(0., (sampleCosHorizon - cosHorizons.x) * mix(1., 2. / float(j + 2), distanceFallOff)); + } + + sampleSceneUvDepth = getSceneUvAndDepth(viewPos - sampleViewOffset); + sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); + viewDelta = sampleSceneViewPos - viewPos; + if (abs(viewDelta.z) < thickness) { + float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); + cosHorizons.y += max(0., (sampleCosHorizon - cosHorizons.y) * mix(1., 2. / float(j + 2), distanceFallOff)); + } + } + + vec2 sinHorizons = sqrt(1. - cosHorizons * cosHorizons); + float nx = dot(normalInSlice, sliceTangent); + float ny = dot(normalInSlice, viewDir); + float nxb = 1. / 2. * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y); + float nyb = 1. / 2. * (2. - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y); + float occlusion = nx * nxb + ny * nyb; + ao += occlusion; + } + + ao = clamp(ao / float(DIRECTIONS), 0., 1.); + #if SCENE_CLIP_BOX == 1 + ao = mix(ao, 1., smoothstep(0., radiusToUse, boxDistance)); + #endif + ao = pow(ao, scale); + + gl_FragColor = FRAGMENT_OUTPUT; + }` +}; +var GTAODepthShader = { + name: "GTAODepthShader", + defines: { + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDepth: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null } + }, + vertexShader: ` + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + uniform sampler2D tDepth; + uniform float cameraNear; + uniform float cameraFar; + varying vec2 vUv; + + #include + + float getLinearDepth( const in vec2 screenPosition ) { + #if PERSPECTIVE_CAMERA == 1 + float fragCoordZ = texture2D( tDepth, screenPosition ).x; + float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); + return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + #else + return texture2D( tDepth, screenPosition ).x; + #endif + } + + void main() { + float depth = getLinearDepth( vUv ); + gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); + + }` +}; +var GTAOBlendShader = { + name: "GTAOBlendShader", + uniforms: { + tDiffuse: { value: null }, + intensity: { value: 1 } + }, + vertexShader: ` + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + uniform float intensity; + uniform sampler2D tDiffuse; + varying vec2 vUv; + + void main() { + vec4 texel = texture2D( tDiffuse, vUv ); + gl_FragColor = vec4(mix(vec3(1.), texel.rgb, intensity), texel.a); + }` +}; +function generateMagicSquareNoise(size2 = 5) { + const noiseSize = Math.floor(size2) % 2 === 0 ? Math.floor(size2) + 1 : Math.floor(size2); + const magicSquare = generateMagicSquare(noiseSize); + const noiseSquareSize = magicSquare.length; + const data2 = new Uint8Array(noiseSquareSize * 4); + for (let inx = 0;inx < noiseSquareSize; ++inx) { + const iAng = magicSquare[inx]; + const angle = 2 * Math.PI * iAng / noiseSquareSize; + const randomVec = new Vector3(Math.cos(angle), Math.sin(angle), 0).normalize(); + data2[inx * 4] = (randomVec.x * 0.5 + 0.5) * 255; + data2[inx * 4 + 1] = (randomVec.y * 0.5 + 0.5) * 255; + data2[inx * 4 + 2] = 127; + data2[inx * 4 + 3] = 255; + } + const noiseTexture = new DataTexture(data2, noiseSize, noiseSize); + noiseTexture.wrapS = RepeatWrapping; + noiseTexture.wrapT = RepeatWrapping; + noiseTexture.needsUpdate = true; + return noiseTexture; +} +function generateMagicSquare(size2) { + const noiseSize = Math.floor(size2) % 2 === 0 ? Math.floor(size2) + 1 : Math.floor(size2); + const noiseSquareSize = noiseSize * noiseSize; + const magicSquare = Array(noiseSquareSize).fill(0); + let i = Math.floor(noiseSize / 2); + let j2 = noiseSize - 1; + for (let num = 1;num <= noiseSquareSize; ) { + if (i === -1 && j2 === noiseSize) { + j2 = noiseSize - 2; + i = 0; + } else { + if (j2 === noiseSize) { + j2 = 0; + } + if (i < 0) { + i = noiseSize - 1; + } + } + if (magicSquare[i * noiseSize + j2] !== 0) { + j2 -= 2; + i++; + continue; + } else { + magicSquare[i * noiseSize + j2] = num++; + } + j2++; + i--; + } + return magicSquare; +} + +// node_modules/three/examples/jsm/shaders/PoissonDenoiseShader.js +var PoissonDenoiseShader = { + name: "PoissonDenoiseShader", + defines: { + SAMPLES: 16, + SAMPLE_VECTORS: generatePdSamplePointInitializer(16, 2, 1), + NORMAL_VECTOR_TYPE: 1, + DEPTH_VALUE_SOURCE: 0 + }, + uniforms: { + tDiffuse: { value: null }, + tNormal: { value: null }, + tDepth: { value: null }, + tNoise: { value: null }, + resolution: { value: new Vector2 }, + cameraProjectionMatrixInverse: { value: new Matrix4 }, + lumaPhi: { value: 5 }, + depthPhi: { value: 5 }, + normalPhi: { value: 5 }, + radius: { value: 4 }, + index: { value: 0 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + + varying vec2 vUv; + + uniform sampler2D tDiffuse; + uniform sampler2D tNormal; + uniform sampler2D tDepth; + uniform sampler2D tNoise; + uniform vec2 resolution; + uniform mat4 cameraProjectionMatrixInverse; + uniform float lumaPhi; + uniform float depthPhi; + uniform float normalPhi; + uniform float radius; + uniform int index; + + #include + #include + + #ifndef SAMPLE_LUMINANCE + #define SAMPLE_LUMINANCE dot(vec3(0.2125, 0.7154, 0.0721), a) + #endif + + #ifndef FRAGMENT_OUTPUT + #define FRAGMENT_OUTPUT vec4(denoised, 1.) + #endif + + float getLuminance(const in vec3 a) { + return SAMPLE_LUMINANCE; + } + + const vec3 poissonDisk[SAMPLES] = SAMPLE_VECTORS; + + vec3 getViewPosition(const in vec2 screenPosition, const in float depth) { + vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); + vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; + return viewSpacePosition.xyz / viewSpacePosition.w; + } + + float getDepth(const vec2 uv) { + #if DEPTH_VALUE_SOURCE == 1 + return textureLod(tDepth, uv.xy, 0.0).a; + #else + return textureLod(tDepth, uv.xy, 0.0).r; + #endif + } + + float fetchDepth(const ivec2 uv) { + #if DEPTH_VALUE_SOURCE == 1 + return texelFetch(tDepth, uv.xy, 0).a; + #else + return texelFetch(tDepth, uv.xy, 0).r; + #endif + } + + vec3 computeNormalFromDepth(const vec2 uv) { + vec2 size = vec2(textureSize(tDepth, 0)); + ivec2 p = ivec2(uv * size); + float c0 = fetchDepth(p); + float l2 = fetchDepth(p - ivec2(2, 0)); + float l1 = fetchDepth(p - ivec2(1, 0)); + float r1 = fetchDepth(p + ivec2(1, 0)); + float r2 = fetchDepth(p + ivec2(2, 0)); + float b2 = fetchDepth(p - ivec2(0, 2)); + float b1 = fetchDepth(p - ivec2(0, 1)); + float t1 = fetchDepth(p + ivec2(0, 1)); + float t2 = fetchDepth(p + ivec2(0, 2)); + float dl = abs((2.0 * l1 - l2) - c0); + float dr = abs((2.0 * r1 - r2) - c0); + float db = abs((2.0 * b1 - b2) - c0); + float dt = abs((2.0 * t1 - t2) - c0); + vec3 ce = getViewPosition(uv, c0).xyz; + vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz + : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; + vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz + : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; + return normalize(cross(dpdx, dpdy)); + } + + vec3 getViewNormal(const vec2 uv) { + #if NORMAL_VECTOR_TYPE == 2 + return normalize(textureLod(tNormal, uv, 0.).rgb); + #elif NORMAL_VECTOR_TYPE == 1 + return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); + #else + return computeNormalFromDepth(uv); + #endif + } + + void denoiseSample(in vec3 center, in vec3 viewNormal, in vec3 viewPos, in vec2 sampleUv, inout vec3 denoised, inout float totalWeight) { + vec4 sampleTexel = textureLod(tDiffuse, sampleUv, 0.0); + float sampleDepth = getDepth(sampleUv); + vec3 sampleNormal = getViewNormal(sampleUv); + vec3 neighborColor = sampleTexel.rgb; + vec3 viewPosSample = getViewPosition(sampleUv, sampleDepth); + + float normalDiff = dot(viewNormal, sampleNormal); + float normalSimilarity = pow(max(normalDiff, 0.), normalPhi); + float lumaDiff = abs(getLuminance(neighborColor) - getLuminance(center)); + float lumaSimilarity = max(1.0 - lumaDiff / lumaPhi, 0.0); + float depthDiff = abs(dot(viewPos - viewPosSample, viewNormal)); + float depthSimilarity = max(1. - depthDiff / depthPhi, 0.); + float w = lumaSimilarity * depthSimilarity * normalSimilarity; + + denoised += w * neighborColor; + totalWeight += w; + } + + void main() { + float depth = getDepth(vUv.xy); + vec3 viewNormal = getViewNormal(vUv); + if (depth == 1. || dot(viewNormal, viewNormal) == 0.) { + discard; + return; + } + vec4 texel = textureLod(tDiffuse, vUv, 0.0); + vec3 center = texel.rgb; + vec3 viewPos = getViewPosition(vUv, depth); + + vec2 noiseResolution = vec2(textureSize(tNoise, 0)); + vec2 noiseUv = vUv * resolution / noiseResolution; + vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); + vec2 noiseVec = vec2(sin(noiseTexel[index % 4] * 2. * PI), cos(noiseTexel[index % 4] * 2. * PI)); + mat2 rotationMatrix = mat2(noiseVec.x, -noiseVec.y, noiseVec.x, noiseVec.y); + + float totalWeight = 1.0; + vec3 denoised = texel.rgb; + for (int i = 0; i < SAMPLES; i++) { + vec3 sampleDir = poissonDisk[i]; + vec2 offset = rotationMatrix * (sampleDir.xy * (1. + sampleDir.z * (radius - 1.)) / resolution); + vec2 sampleUv = vUv + offset; + denoiseSample(center, viewNormal, viewPos, sampleUv, denoised, totalWeight); + } + + if (totalWeight > 0.) { + denoised /= totalWeight; + } + gl_FragColor = FRAGMENT_OUTPUT; + }` +}; +function generatePdSamplePointInitializer(samples, rings, radiusExponent) { + const poissonDisk = generateDenoiseSamples(samples, rings, radiusExponent); + let glslCode = "vec3[SAMPLES]("; + for (let i = 0;i < samples; i++) { + const sample = poissonDisk[i]; + glslCode += `vec3(${sample.x}, ${sample.y}, ${sample.z})${i < samples - 1 ? "," : ")"}`; + } + return glslCode; +} +function generateDenoiseSamples(numSamples, numRings, radiusExponent) { + const samples = []; + for (let i = 0;i < numSamples; i++) { + const angle = 2 * Math.PI * numRings * i / numSamples; + const radius = Math.pow(i / (numSamples - 1), radiusExponent); + samples.push(new Vector3(Math.cos(angle), Math.sin(angle), radius)); + } + return samples; +} + +// node_modules/three/examples/jsm/postprocessing/GTAOPass.js +class GTAOPass extends Pass { + constructor(scene, camera, width2, height2, parameters, aoParameters, pdParameters) { + super(); + this.width = width2 !== undefined ? width2 : 512; + this.height = height2 !== undefined ? height2 : 512; + this.clear = true; + this.camera = camera; + this.scene = scene; + this.output = 0; + this._renderGBuffer = true; + this._visibilityCache = new Map; + this.blendIntensity = 1; + this.pdRings = 2; + this.pdRadiusExponent = 2; + this.pdSamples = 16; + this.gtaoNoiseTexture = generateMagicSquareNoise(); + this.pdNoiseTexture = this.generateNoise(); + this.gtaoRenderTarget = new WebGLRenderTarget(this.width, this.height, { type: HalfFloatType }); + this.pdRenderTarget = this.gtaoRenderTarget.clone(); + this.gtaoMaterial = new ShaderMaterial({ + defines: Object.assign({}, GTAOShader.defines), + uniforms: UniformsUtils.clone(GTAOShader.uniforms), + vertexShader: GTAOShader.vertexShader, + fragmentShader: GTAOShader.fragmentShader, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + this.gtaoMaterial.defines.PERSPECTIVE_CAMERA = this.camera.isPerspectiveCamera ? 1 : 0; + this.gtaoMaterial.uniforms.tNoise.value = this.gtaoNoiseTexture; + this.gtaoMaterial.uniforms.resolution.value.set(this.width, this.height); + this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near; + this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far; + this.normalMaterial = new MeshNormalMaterial; + this.normalMaterial.blending = NoBlending; + this.pdMaterial = new ShaderMaterial({ + defines: Object.assign({}, PoissonDenoiseShader.defines), + uniforms: UniformsUtils.clone(PoissonDenoiseShader.uniforms), + vertexShader: PoissonDenoiseShader.vertexShader, + fragmentShader: PoissonDenoiseShader.fragmentShader, + depthTest: false, + depthWrite: false + }); + this.pdMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture; + this.pdMaterial.uniforms.tNoise.value = this.pdNoiseTexture; + this.pdMaterial.uniforms.resolution.value.set(this.width, this.height); + this.pdMaterial.uniforms.lumaPhi.value = 10; + this.pdMaterial.uniforms.depthPhi.value = 2; + this.pdMaterial.uniforms.normalPhi.value = 3; + this.pdMaterial.uniforms.radius.value = 8; + this.depthRenderMaterial = new ShaderMaterial({ + defines: Object.assign({}, GTAODepthShader.defines), + uniforms: UniformsUtils.clone(GTAODepthShader.uniforms), + vertexShader: GTAODepthShader.vertexShader, + fragmentShader: GTAODepthShader.fragmentShader, + blending: NoBlending + }); + this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near; + this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far; + this.copyMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(CopyShader.uniforms), + vertexShader: CopyShader.vertexShader, + fragmentShader: CopyShader.fragmentShader, + transparent: true, + depthTest: false, + depthWrite: false, + blendSrc: DstColorFactor, + blendDst: ZeroFactor, + blendEquation: AddEquation, + blendSrcAlpha: DstAlphaFactor, + blendDstAlpha: ZeroFactor, + blendEquationAlpha: AddEquation + }); + this.blendMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(GTAOBlendShader.uniforms), + vertexShader: GTAOBlendShader.vertexShader, + fragmentShader: GTAOBlendShader.fragmentShader, + transparent: true, + depthTest: false, + depthWrite: false, + blending: CustomBlending, + blendSrc: DstColorFactor, + blendDst: ZeroFactor, + blendEquation: AddEquation, + blendSrcAlpha: DstAlphaFactor, + blendDstAlpha: ZeroFactor, + blendEquationAlpha: AddEquation + }); + this.fsQuad = new FullScreenQuad(null); + this.originalClearColor = new Color; + this.setGBuffer(parameters ? parameters.depthTexture : undefined, parameters ? parameters.normalTexture : undefined); + if (aoParameters !== undefined) { + this.updateGtaoMaterial(aoParameters); + } + if (pdParameters !== undefined) { + this.updatePdMaterial(pdParameters); + } + } + dispose() { + this.gtaoNoiseTexture.dispose(); + this.pdNoiseTexture.dispose(); + this.normalRenderTarget.dispose(); + this.gtaoRenderTarget.dispose(); + this.pdRenderTarget.dispose(); + this.normalMaterial.dispose(); + this.pdMaterial.dispose(); + this.copyMaterial.dispose(); + this.depthRenderMaterial.dispose(); + this.fsQuad.dispose(); + } + get gtaoMap() { + return this.pdRenderTarget.texture; + } + setGBuffer(depthTexture, normalTexture) { + if (depthTexture !== undefined) { + this.depthTexture = depthTexture; + this.normalTexture = normalTexture; + this._renderGBuffer = false; + } else { + this.depthTexture = new DepthTexture; + this.depthTexture.format = DepthStencilFormat; + this.depthTexture.type = UnsignedInt248Type; + this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType, + depthTexture: this.depthTexture + }); + this.normalTexture = this.normalRenderTarget.texture; + this._renderGBuffer = true; + } + const normalVectorType = this.normalTexture ? 1 : 0; + const depthValueSource = this.depthTexture === this.normalTexture ? "w" : "x"; + this.gtaoMaterial.defines.NORMAL_VECTOR_TYPE = normalVectorType; + this.gtaoMaterial.defines.DEPTH_SWIZZLING = depthValueSource; + this.gtaoMaterial.uniforms.tNormal.value = this.normalTexture; + this.gtaoMaterial.uniforms.tDepth.value = this.depthTexture; + this.pdMaterial.defines.NORMAL_VECTOR_TYPE = normalVectorType; + this.pdMaterial.defines.DEPTH_SWIZZLING = depthValueSource; + this.pdMaterial.uniforms.tNormal.value = this.normalTexture; + this.pdMaterial.uniforms.tDepth.value = this.depthTexture; + this.depthRenderMaterial.uniforms.tDepth.value = this.normalRenderTarget.depthTexture; + } + setSceneClipBox(box) { + if (box) { + this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX !== 1; + this.gtaoMaterial.defines.SCENE_CLIP_BOX = 1; + this.gtaoMaterial.uniforms.sceneBoxMin.value.copy(box.min); + this.gtaoMaterial.uniforms.sceneBoxMax.value.copy(box.max); + } else { + this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX === 0; + this.gtaoMaterial.defines.SCENE_CLIP_BOX = 0; + } + } + updateGtaoMaterial(parameters) { + if (parameters.radius !== undefined) { + this.gtaoMaterial.uniforms.radius.value = parameters.radius; + } + if (parameters.distanceExponent !== undefined) { + this.gtaoMaterial.uniforms.distanceExponent.value = parameters.distanceExponent; + } + if (parameters.thickness !== undefined) { + this.gtaoMaterial.uniforms.thickness.value = parameters.thickness; + } + if (parameters.distanceFallOff !== undefined) { + this.gtaoMaterial.uniforms.distanceFallOff.value = parameters.distanceFallOff; + this.gtaoMaterial.needsUpdate = true; + } + if (parameters.scale !== undefined) { + this.gtaoMaterial.uniforms.scale.value = parameters.scale; + } + if (parameters.samples !== undefined && parameters.samples !== this.gtaoMaterial.defines.SAMPLES) { + this.gtaoMaterial.defines.SAMPLES = parameters.samples; + this.gtaoMaterial.needsUpdate = true; + } + if (parameters.screenSpaceRadius !== undefined && (parameters.screenSpaceRadius ? 1 : 0) !== this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS) { + this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS = parameters.screenSpaceRadius ? 1 : 0; + this.gtaoMaterial.needsUpdate = true; + } + } + updatePdMaterial(parameters) { + let updateShader = false; + if (parameters.lumaPhi !== undefined) { + this.pdMaterial.uniforms.lumaPhi.value = parameters.lumaPhi; + } + if (parameters.depthPhi !== undefined) { + this.pdMaterial.uniforms.depthPhi.value = parameters.depthPhi; + } + if (parameters.normalPhi !== undefined) { + this.pdMaterial.uniforms.normalPhi.value = parameters.normalPhi; + } + if (parameters.radius !== undefined && parameters.radius !== this.radius) { + this.pdMaterial.uniforms.radius.value = parameters.radius; + } + if (parameters.radiusExponent !== undefined && parameters.radiusExponent !== this.pdRadiusExponent) { + this.pdRadiusExponent = parameters.radiusExponent; + updateShader = true; + } + if (parameters.rings !== undefined && parameters.rings !== this.pdRings) { + this.pdRings = parameters.rings; + updateShader = true; + } + if (parameters.samples !== undefined && parameters.samples !== this.pdSamples) { + this.pdSamples = parameters.samples; + updateShader = true; + } + if (updateShader) { + this.pdMaterial.defines.SAMPLES = this.pdSamples; + this.pdMaterial.defines.SAMPLE_VECTORS = generatePdSamplePointInitializer(this.pdSamples, this.pdRings, this.pdRadiusExponent); + this.pdMaterial.needsUpdate = true; + } + } + render(renderer2, writeBuffer, readBuffer) { + if (this._renderGBuffer) { + this.overrideVisibility(); + this.renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 7829503, 1); + this.restoreVisibility(); + } + this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near; + this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far; + this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix); + this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); + this.gtaoMaterial.uniforms.cameraWorldMatrix.value.copy(this.camera.matrixWorld); + this.renderPass(renderer2, this.gtaoMaterial, this.gtaoRenderTarget, 16777215, 1); + this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); + this.renderPass(renderer2, this.pdMaterial, this.pdRenderTarget, 16777215, 1); + switch (this.output) { + case GTAOPass.OUTPUT.Off: + break; + case GTAOPass.OUTPUT.Diffuse: + this.copyMaterial.uniforms.tDiffuse.value = readBuffer.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.AO: + this.copyMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.Denoise: + this.copyMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.Depth: + this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near; + this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far; + this.renderPass(renderer2, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.Normal: + this.copyMaterial.uniforms.tDiffuse.value = this.normalRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.Default: + this.copyMaterial.uniforms.tDiffuse.value = readBuffer.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + this.blendMaterial.uniforms.intensity.value = this.blendIntensity; + this.blendMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture; + this.renderPass(renderer2, this.blendMaterial, this.renderToScreen ? null : writeBuffer); + break; + default: + console.warn("THREE.GTAOPass: Unknown output type."); + } + } + renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.fsQuad.material = passMaterial; + this.fsQuad.render(renderer2); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.overrideMaterial = overrideMaterial; + renderer2.render(this.scene, this.camera); + this.scene.overrideMaterial = null; + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + setSize(width2, height2) { + this.width = width2; + this.height = height2; + this.gtaoRenderTarget.setSize(width2, height2); + this.normalRenderTarget.setSize(width2, height2); + this.pdRenderTarget.setSize(width2, height2); + this.gtaoMaterial.uniforms.resolution.value.set(width2, height2); + this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix); + this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); + this.pdMaterial.uniforms.resolution.value.set(width2, height2); + this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); + } + overrideVisibility() { + const scene = this.scene; + const cache = this._visibilityCache; + scene.traverse(function(object) { + cache.set(object, object.visible); + if (object.isPoints || object.isLine) + object.visible = false; + }); + } + restoreVisibility() { + const scene = this.scene; + const cache = this._visibilityCache; + scene.traverse(function(object) { + const visible = cache.get(object); + object.visible = visible; + }); + cache.clear(); + } + generateNoise(size2 = 64) { + const simplex = new SimplexNoise; + const arraySize = size2 * size2 * 4; + const data2 = new Uint8Array(arraySize); + for (let i = 0;i < size2; i++) { + for (let j2 = 0;j2 < size2; j2++) { + const x2 = i; + const y3 = j2; + data2[(i * size2 + j2) * 4] = (simplex.noise(x2, y3) * 0.5 + 0.5) * 255; + data2[(i * size2 + j2) * 4 + 1] = (simplex.noise(x2 + size2, y3) * 0.5 + 0.5) * 255; + data2[(i * size2 + j2) * 4 + 2] = (simplex.noise(x2, y3 + size2) * 0.5 + 0.5) * 255; + data2[(i * size2 + j2) * 4 + 3] = (simplex.noise(x2 + size2, y3 + size2) * 0.5 + 0.5) * 255; + } + } + const noiseTexture = new DataTexture(data2, size2, size2, RGBAFormat, UnsignedByteType); + noiseTexture.wrapS = RepeatWrapping; + noiseTexture.wrapT = RepeatWrapping; + noiseTexture.needsUpdate = true; + return noiseTexture; + } +} +GTAOPass.OUTPUT = { + Off: -1, + Default: 0, + Diffuse: 1, + Depth: 2, + Normal: 3, + AO: 4, + Denoise: 5 +}; +// node_modules/three/examples/jsm/shaders/HalftoneShader.js +var HalftoneShader = { + name: "HalftoneShader", + uniforms: { + tDiffuse: { value: null }, + shape: { value: 1 }, + radius: { value: 4 }, + rotateR: { value: Math.PI / 12 * 1 }, + rotateG: { value: Math.PI / 12 * 2 }, + rotateB: { value: Math.PI / 12 * 3 }, + scatter: { value: 0 }, + width: { value: 1 }, + height: { value: 1 }, + blending: { value: 1 }, + blendingMode: { value: 1 }, + greyscale: { value: false }, + disable: { value: false } + }, + vertexShader: ` + + varying vec2 vUV; + + void main() { + + vUV = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + + }`, + fragmentShader: ` + + #define SQRT2_MINUS_ONE 0.41421356 + #define SQRT2_HALF_MINUS_ONE 0.20710678 + #define PI2 6.28318531 + #define SHAPE_DOT 1 + #define SHAPE_ELLIPSE 2 + #define SHAPE_LINE 3 + #define SHAPE_SQUARE 4 + #define BLENDING_LINEAR 1 + #define BLENDING_MULTIPLY 2 + #define BLENDING_ADD 3 + #define BLENDING_LIGHTER 4 + #define BLENDING_DARKER 5 + uniform sampler2D tDiffuse; + uniform float radius; + uniform float rotateR; + uniform float rotateG; + uniform float rotateB; + uniform float scatter; + uniform float width; + uniform float height; + uniform int shape; + uniform bool disable; + uniform float blending; + uniform int blendingMode; + varying vec2 vUV; + uniform bool greyscale; + const int samples = 8; + + float blend( float a, float b, float t ) { + + // linear blend + return a * ( 1.0 - t ) + b * t; + + } + + float hypot( float x, float y ) { + + // vector magnitude + return sqrt( x * x + y * y ); + + } + + float rand( vec2 seed ){ + + // get pseudo-random number + return fract( sin( dot( seed.xy, vec2( 12.9898, 78.233 ) ) ) * 43758.5453 ); + + } + + float distanceToDotRadius( float channel, vec2 coord, vec2 normal, vec2 p, float angle, float rad_max ) { + + // apply shape-specific transforms + float dist = hypot( coord.x - p.x, coord.y - p.y ); + float rad = channel; + + if ( shape == SHAPE_DOT ) { + + rad = pow( abs( rad ), 1.125 ) * rad_max; + + } else if ( shape == SHAPE_ELLIPSE ) { + + rad = pow( abs( rad ), 1.125 ) * rad_max; + + if ( dist != 0.0 ) { + float dot_p = abs( ( p.x - coord.x ) / dist * normal.x + ( p.y - coord.y ) / dist * normal.y ); + dist = ( dist * ( 1.0 - SQRT2_HALF_MINUS_ONE ) ) + dot_p * dist * SQRT2_MINUS_ONE; + } + + } else if ( shape == SHAPE_LINE ) { + + rad = pow( abs( rad ), 1.5) * rad_max; + float dot_p = ( p.x - coord.x ) * normal.x + ( p.y - coord.y ) * normal.y; + dist = hypot( normal.x * dot_p, normal.y * dot_p ); + + } else if ( shape == SHAPE_SQUARE ) { + + float theta = atan( p.y - coord.y, p.x - coord.x ) - angle; + float sin_t = abs( sin( theta ) ); + float cos_t = abs( cos( theta ) ); + rad = pow( abs( rad ), 1.4 ); + rad = rad_max * ( rad + ( ( sin_t > cos_t ) ? rad - sin_t * rad : rad - cos_t * rad ) ); + + } + + return rad - dist; + + } + + struct Cell { + + // grid sample positions + vec2 normal; + vec2 p1; + vec2 p2; + vec2 p3; + vec2 p4; + float samp2; + float samp1; + float samp3; + float samp4; + + }; + + vec4 getSample( vec2 point ) { + + // multi-sampled point + vec4 tex = texture2D( tDiffuse, vec2( point.x / width, point.y / height ) ); + float base = rand( vec2( floor( point.x ), floor( point.y ) ) ) * PI2; + float step = PI2 / float( samples ); + float dist = radius * 0.66; + + for ( int i = 0; i < samples; ++i ) { + + float r = base + step * float( i ); + vec2 coord = point + vec2( cos( r ) * dist, sin( r ) * dist ); + tex += texture2D( tDiffuse, vec2( coord.x / width, coord.y / height ) ); + + } + + tex /= float( samples ) + 1.0; + return tex; + + } + + float getDotColour( Cell c, vec2 p, int channel, float angle, float aa ) { + + // get colour for given point + float dist_c_1, dist_c_2, dist_c_3, dist_c_4, res; + + if ( channel == 0 ) { + + c.samp1 = getSample( c.p1 ).r; + c.samp2 = getSample( c.p2 ).r; + c.samp3 = getSample( c.p3 ).r; + c.samp4 = getSample( c.p4 ).r; + + } else if (channel == 1) { + + c.samp1 = getSample( c.p1 ).g; + c.samp2 = getSample( c.p2 ).g; + c.samp3 = getSample( c.p3 ).g; + c.samp4 = getSample( c.p4 ).g; + + } else { + + c.samp1 = getSample( c.p1 ).b; + c.samp3 = getSample( c.p3 ).b; + c.samp2 = getSample( c.p2 ).b; + c.samp4 = getSample( c.p4 ).b; + + } + + dist_c_1 = distanceToDotRadius( c.samp1, c.p1, c.normal, p, angle, radius ); + dist_c_2 = distanceToDotRadius( c.samp2, c.p2, c.normal, p, angle, radius ); + dist_c_3 = distanceToDotRadius( c.samp3, c.p3, c.normal, p, angle, radius ); + dist_c_4 = distanceToDotRadius( c.samp4, c.p4, c.normal, p, angle, radius ); + res = ( dist_c_1 > 0.0 ) ? clamp( dist_c_1 / aa, 0.0, 1.0 ) : 0.0; + res += ( dist_c_2 > 0.0 ) ? clamp( dist_c_2 / aa, 0.0, 1.0 ) : 0.0; + res += ( dist_c_3 > 0.0 ) ? clamp( dist_c_3 / aa, 0.0, 1.0 ) : 0.0; + res += ( dist_c_4 > 0.0 ) ? clamp( dist_c_4 / aa, 0.0, 1.0 ) : 0.0; + res = clamp( res, 0.0, 1.0 ); + + return res; + + } + + Cell getReferenceCell( vec2 p, vec2 origin, float grid_angle, float step ) { + + // get containing cell + Cell c; + + // calc grid + vec2 n = vec2( cos( grid_angle ), sin( grid_angle ) ); + float threshold = step * 0.5; + float dot_normal = n.x * ( p.x - origin.x ) + n.y * ( p.y - origin.y ); + float dot_line = -n.y * ( p.x - origin.x ) + n.x * ( p.y - origin.y ); + vec2 offset = vec2( n.x * dot_normal, n.y * dot_normal ); + float offset_normal = mod( hypot( offset.x, offset.y ), step ); + float normal_dir = ( dot_normal < 0.0 ) ? 1.0 : -1.0; + float normal_scale = ( ( offset_normal < threshold ) ? -offset_normal : step - offset_normal ) * normal_dir; + float offset_line = mod( hypot( ( p.x - offset.x ) - origin.x, ( p.y - offset.y ) - origin.y ), step ); + float line_dir = ( dot_line < 0.0 ) ? 1.0 : -1.0; + float line_scale = ( ( offset_line < threshold ) ? -offset_line : step - offset_line ) * line_dir; + + // get closest corner + c.normal = n; + c.p1.x = p.x - n.x * normal_scale + n.y * line_scale; + c.p1.y = p.y - n.y * normal_scale - n.x * line_scale; + + // scatter + if ( scatter != 0.0 ) { + + float off_mag = scatter * threshold * 0.5; + float off_angle = rand( vec2( floor( c.p1.x ), floor( c.p1.y ) ) ) * PI2; + c.p1.x += cos( off_angle ) * off_mag; + c.p1.y += sin( off_angle ) * off_mag; + + } + + // find corners + float normal_step = normal_dir * ( ( offset_normal < threshold ) ? step : -step ); + float line_step = line_dir * ( ( offset_line < threshold ) ? step : -step ); + c.p2.x = c.p1.x - n.x * normal_step; + c.p2.y = c.p1.y - n.y * normal_step; + c.p3.x = c.p1.x + n.y * line_step; + c.p3.y = c.p1.y - n.x * line_step; + c.p4.x = c.p1.x - n.x * normal_step + n.y * line_step; + c.p4.y = c.p1.y - n.y * normal_step - n.x * line_step; + + return c; + + } + + float blendColour( float a, float b, float t ) { + + // blend colours + if ( blendingMode == BLENDING_LINEAR ) { + return blend( a, b, 1.0 - t ); + } else if ( blendingMode == BLENDING_ADD ) { + return blend( a, min( 1.0, a + b ), t ); + } else if ( blendingMode == BLENDING_MULTIPLY ) { + return blend( a, max( 0.0, a * b ), t ); + } else if ( blendingMode == BLENDING_LIGHTER ) { + return blend( a, max( a, b ), t ); + } else if ( blendingMode == BLENDING_DARKER ) { + return blend( a, min( a, b ), t ); + } else { + return blend( a, b, 1.0 - t ); + } + + } + + void main() { + + if ( ! disable ) { + + // setup + vec2 p = vec2( vUV.x * width, vUV.y * height ); + vec2 origin = vec2( 0, 0 ); + float aa = ( radius < 2.5 ) ? radius * 0.5 : 1.25; + + // get channel samples + Cell cell_r = getReferenceCell( p, origin, rotateR, radius ); + Cell cell_g = getReferenceCell( p, origin, rotateG, radius ); + Cell cell_b = getReferenceCell( p, origin, rotateB, radius ); + float r = getDotColour( cell_r, p, 0, rotateR, aa ); + float g = getDotColour( cell_g, p, 1, rotateG, aa ); + float b = getDotColour( cell_b, p, 2, rotateB, aa ); + + // blend with original + vec4 colour = texture2D( tDiffuse, vUV ); + r = blendColour( r, colour.r, blending ); + g = blendColour( g, colour.g, blending ); + b = blendColour( b, colour.b, blending ); + + if ( greyscale ) { + r = g = b = (r + b + g) / 3.0; + } + + gl_FragColor = vec4( r, g, b, 1.0 ); + + } else { + + gl_FragColor = texture2D( tDiffuse, vUV ); + + } + + }` +}; +// node_modules/three/examples/jsm/postprocessing/OutlinePass.js +class OutlinePass extends Pass { + constructor(resolution, scene, camera, selectedObjects) { + super(); + this.renderScene = scene; + this.renderCamera = camera; + this.selectedObjects = selectedObjects !== undefined ? selectedObjects : []; + this.visibleEdgeColor = new Color(1, 1, 1); + this.hiddenEdgeColor = new Color(0.1, 0.04, 0.02); + this.edgeGlow = 0; + this.usePatternTexture = false; + this.edgeThickness = 1; + this.edgeStrength = 3; + this.downSampleRatio = 2; + this.pulsePeriod = 0; + this._visibilityCache = new Map; + this._selectionCache = new Set; + this.resolution = resolution !== undefined ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256); + const resx = Math.round(this.resolution.x / this.downSampleRatio); + const resy = Math.round(this.resolution.y / this.downSampleRatio); + this.renderTargetMaskBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y); + this.renderTargetMaskBuffer.texture.name = "OutlinePass.mask"; + this.renderTargetMaskBuffer.texture.generateMipmaps = false; + this.depthMaterial = new MeshDepthMaterial; + this.depthMaterial.side = DoubleSide; + this.depthMaterial.depthPacking = RGBADepthPacking; + this.depthMaterial.blending = NoBlending; + this.prepareMaskMaterial = this.getPrepareMaskMaterial(); + this.prepareMaskMaterial.side = DoubleSide; + this.prepareMaskMaterial.fragmentShader = replaceDepthToViewZ(this.prepareMaskMaterial.fragmentShader, this.renderCamera); + this.renderTargetDepthBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { type: HalfFloatType }); + this.renderTargetDepthBuffer.texture.name = "OutlinePass.depth"; + this.renderTargetDepthBuffer.texture.generateMipmaps = false; + this.renderTargetMaskDownSampleBuffer = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + this.renderTargetMaskDownSampleBuffer.texture.name = "OutlinePass.depthDownSample"; + this.renderTargetMaskDownSampleBuffer.texture.generateMipmaps = false; + this.renderTargetBlurBuffer1 = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + this.renderTargetBlurBuffer1.texture.name = "OutlinePass.blur1"; + this.renderTargetBlurBuffer1.texture.generateMipmaps = false; + this.renderTargetBlurBuffer2 = new WebGLRenderTarget(Math.round(resx / 2), Math.round(resy / 2), { type: HalfFloatType }); + this.renderTargetBlurBuffer2.texture.name = "OutlinePass.blur2"; + this.renderTargetBlurBuffer2.texture.generateMipmaps = false; + this.edgeDetectionMaterial = this.getEdgeDetectionMaterial(); + this.renderTargetEdgeBuffer1 = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + this.renderTargetEdgeBuffer1.texture.name = "OutlinePass.edge1"; + this.renderTargetEdgeBuffer1.texture.generateMipmaps = false; + this.renderTargetEdgeBuffer2 = new WebGLRenderTarget(Math.round(resx / 2), Math.round(resy / 2), { type: HalfFloatType }); + this.renderTargetEdgeBuffer2.texture.name = "OutlinePass.edge2"; + this.renderTargetEdgeBuffer2.texture.generateMipmaps = false; + const MAX_EDGE_THICKNESS = 4; + const MAX_EDGE_GLOW = 4; + this.separableBlurMaterial1 = this.getSeparableBlurMaterial(MAX_EDGE_THICKNESS); + this.separableBlurMaterial1.uniforms["texSize"].value.set(resx, resy); + this.separableBlurMaterial1.uniforms["kernelRadius"].value = 1; + this.separableBlurMaterial2 = this.getSeparableBlurMaterial(MAX_EDGE_GLOW); + this.separableBlurMaterial2.uniforms["texSize"].value.set(Math.round(resx / 2), Math.round(resy / 2)); + this.separableBlurMaterial2.uniforms["kernelRadius"].value = MAX_EDGE_GLOW; + this.overlayMaterial = this.getOverlayMaterial(); + const copyShader = CopyShader; + this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); + this.materialCopy = new ShaderMaterial({ + uniforms: this.copyUniforms, + vertexShader: copyShader.vertexShader, + fragmentShader: copyShader.fragmentShader, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + this.enabled = true; + this.needsSwap = false; + this._oldClearColor = new Color; + this.oldClearAlpha = 1; + this.fsQuad = new FullScreenQuad(null); + this.tempPulseColor1 = new Color; + this.tempPulseColor2 = new Color; + this.textureMatrix = new Matrix4; + function replaceDepthToViewZ(string, camera2) { + const type = camera2.isPerspectiveCamera ? "perspective" : "orthographic"; + return string.replace(/DEPTH_TO_VIEW_Z/g, type + "DepthToViewZ"); + } + } + dispose() { + this.renderTargetMaskBuffer.dispose(); + this.renderTargetDepthBuffer.dispose(); + this.renderTargetMaskDownSampleBuffer.dispose(); + this.renderTargetBlurBuffer1.dispose(); + this.renderTargetBlurBuffer2.dispose(); + this.renderTargetEdgeBuffer1.dispose(); + this.renderTargetEdgeBuffer2.dispose(); + this.depthMaterial.dispose(); + this.prepareMaskMaterial.dispose(); + this.edgeDetectionMaterial.dispose(); + this.separableBlurMaterial1.dispose(); + this.separableBlurMaterial2.dispose(); + this.overlayMaterial.dispose(); + this.materialCopy.dispose(); + this.fsQuad.dispose(); + } + setSize(width2, height2) { + this.renderTargetMaskBuffer.setSize(width2, height2); + this.renderTargetDepthBuffer.setSize(width2, height2); + let resx = Math.round(width2 / this.downSampleRatio); + let resy = Math.round(height2 / this.downSampleRatio); + this.renderTargetMaskDownSampleBuffer.setSize(resx, resy); + this.renderTargetBlurBuffer1.setSize(resx, resy); + this.renderTargetEdgeBuffer1.setSize(resx, resy); + this.separableBlurMaterial1.uniforms["texSize"].value.set(resx, resy); + resx = Math.round(resx / 2); + resy = Math.round(resy / 2); + this.renderTargetBlurBuffer2.setSize(resx, resy); + this.renderTargetEdgeBuffer2.setSize(resx, resy); + this.separableBlurMaterial2.uniforms["texSize"].value.set(resx, resy); + } + updateSelectionCache() { + const cache = this._selectionCache; + function gatherSelectedMeshesCallBack(object) { + if (object.isMesh) + cache.add(object); + } + cache.clear(); + for (let i = 0;i < this.selectedObjects.length; i++) { + const selectedObject = this.selectedObjects[i]; + selectedObject.traverse(gatherSelectedMeshesCallBack); + } + } + changeVisibilityOfSelectedObjects(bVisible) { + const cache = this._visibilityCache; + for (const mesh of this._selectionCache) { + if (bVisible === true) { + mesh.visible = cache.get(mesh); + } else { + cache.set(mesh, mesh.visible); + mesh.visible = bVisible; + } + } + } + changeVisibilityOfNonSelectedObjects(bVisible) { + const visibilityCache = this._visibilityCache; + const selectionCache = this._selectionCache; + function VisibilityChangeCallBack(object) { + if (object.isMesh || object.isSprite) { + if (!selectionCache.has(object)) { + const visibility = object.visible; + if (bVisible === false || visibilityCache.get(object) === true) { + object.visible = bVisible; + } + visibilityCache.set(object, visibility); + } + } else if (object.isPoints || object.isLine) { + if (bVisible === true) { + object.visible = visibilityCache.get(object); + } else { + visibilityCache.set(object, object.visible); + object.visible = bVisible; + } + } + } + this.renderScene.traverse(VisibilityChangeCallBack); + } + updateTextureMatrix() { + this.textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + this.textureMatrix.multiply(this.renderCamera.projectionMatrix); + this.textureMatrix.multiply(this.renderCamera.matrixWorldInverse); + } + render(renderer2, writeBuffer, readBuffer, deltaTime, maskActive) { + if (this.selectedObjects.length > 0) { + renderer2.getClearColor(this._oldClearColor); + this.oldClearAlpha = renderer2.getClearAlpha(); + const oldAutoClear = renderer2.autoClear; + renderer2.autoClear = false; + if (maskActive) + renderer2.state.buffers.stencil.setTest(false); + renderer2.setClearColor(16777215, 1); + this.updateSelectionCache(); + this.changeVisibilityOfSelectedObjects(false); + const currentBackground = this.renderScene.background; + this.renderScene.background = null; + this.renderScene.overrideMaterial = this.depthMaterial; + renderer2.setRenderTarget(this.renderTargetDepthBuffer); + renderer2.clear(); + renderer2.render(this.renderScene, this.renderCamera); + this.changeVisibilityOfSelectedObjects(true); + this._visibilityCache.clear(); + this.updateTextureMatrix(); + this.changeVisibilityOfNonSelectedObjects(false); + this.renderScene.overrideMaterial = this.prepareMaskMaterial; + this.prepareMaskMaterial.uniforms["cameraNearFar"].value.set(this.renderCamera.near, this.renderCamera.far); + this.prepareMaskMaterial.uniforms["depthTexture"].value = this.renderTargetDepthBuffer.texture; + this.prepareMaskMaterial.uniforms["textureMatrix"].value = this.textureMatrix; + renderer2.setRenderTarget(this.renderTargetMaskBuffer); + renderer2.clear(); + renderer2.render(this.renderScene, this.renderCamera); + this.renderScene.overrideMaterial = null; + this.changeVisibilityOfNonSelectedObjects(true); + this._visibilityCache.clear(); + this._selectionCache.clear(); + this.renderScene.background = currentBackground; + this.fsQuad.material = this.materialCopy; + this.copyUniforms["tDiffuse"].value = this.renderTargetMaskBuffer.texture; + renderer2.setRenderTarget(this.renderTargetMaskDownSampleBuffer); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.tempPulseColor1.copy(this.visibleEdgeColor); + this.tempPulseColor2.copy(this.hiddenEdgeColor); + if (this.pulsePeriod > 0) { + const scalar = (1 + 0.25) / 2 + Math.cos(performance.now() * 0.01 / this.pulsePeriod) * (1 - 0.25) / 2; + this.tempPulseColor1.multiplyScalar(scalar); + this.tempPulseColor2.multiplyScalar(scalar); + } + this.fsQuad.material = this.edgeDetectionMaterial; + this.edgeDetectionMaterial.uniforms["maskTexture"].value = this.renderTargetMaskDownSampleBuffer.texture; + this.edgeDetectionMaterial.uniforms["texSize"].value.set(this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height); + this.edgeDetectionMaterial.uniforms["visibleEdgeColor"].value = this.tempPulseColor1; + this.edgeDetectionMaterial.uniforms["hiddenEdgeColor"].value = this.tempPulseColor2; + renderer2.setRenderTarget(this.renderTargetEdgeBuffer1); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.separableBlurMaterial1; + this.separableBlurMaterial1.uniforms["colorTexture"].value = this.renderTargetEdgeBuffer1.texture; + this.separableBlurMaterial1.uniforms["direction"].value = OutlinePass.BlurDirectionX; + this.separableBlurMaterial1.uniforms["kernelRadius"].value = this.edgeThickness; + renderer2.setRenderTarget(this.renderTargetBlurBuffer1); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.separableBlurMaterial1.uniforms["colorTexture"].value = this.renderTargetBlurBuffer1.texture; + this.separableBlurMaterial1.uniforms["direction"].value = OutlinePass.BlurDirectionY; + renderer2.setRenderTarget(this.renderTargetEdgeBuffer1); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.separableBlurMaterial2; + this.separableBlurMaterial2.uniforms["colorTexture"].value = this.renderTargetEdgeBuffer1.texture; + this.separableBlurMaterial2.uniforms["direction"].value = OutlinePass.BlurDirectionX; + renderer2.setRenderTarget(this.renderTargetBlurBuffer2); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.separableBlurMaterial2.uniforms["colorTexture"].value = this.renderTargetBlurBuffer2.texture; + this.separableBlurMaterial2.uniforms["direction"].value = OutlinePass.BlurDirectionY; + renderer2.setRenderTarget(this.renderTargetEdgeBuffer2); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.overlayMaterial; + this.overlayMaterial.uniforms["maskTexture"].value = this.renderTargetMaskBuffer.texture; + this.overlayMaterial.uniforms["edgeTexture1"].value = this.renderTargetEdgeBuffer1.texture; + this.overlayMaterial.uniforms["edgeTexture2"].value = this.renderTargetEdgeBuffer2.texture; + this.overlayMaterial.uniforms["patternTexture"].value = this.patternTexture; + this.overlayMaterial.uniforms["edgeStrength"].value = this.edgeStrength; + this.overlayMaterial.uniforms["edgeGlow"].value = this.edgeGlow; + this.overlayMaterial.uniforms["usePatternTexture"].value = this.usePatternTexture; + if (maskActive) + renderer2.state.buffers.stencil.setTest(true); + renderer2.setRenderTarget(readBuffer); + this.fsQuad.render(renderer2); + renderer2.setClearColor(this._oldClearColor, this.oldClearAlpha); + renderer2.autoClear = oldAutoClear; + } + if (this.renderToScreen) { + this.fsQuad.material = this.materialCopy; + this.copyUniforms["tDiffuse"].value = readBuffer.texture; + renderer2.setRenderTarget(null); + this.fsQuad.render(renderer2); + } + } + getPrepareMaskMaterial() { + return new ShaderMaterial({ + uniforms: { + depthTexture: { value: null }, + cameraNearFar: { value: new Vector2(0.5, 0.5) }, + textureMatrix: { value: null } + }, + vertexShader: `#include + #include + + varying vec4 projTexCoord; + varying vec4 vPosition; + uniform mat4 textureMatrix; + + void main() { + + #include + #include + #include + #include + #include + + vPosition = mvPosition; + + vec4 worldPosition = vec4( transformed, 1.0 ); + + #ifdef USE_INSTANCING + + worldPosition = instanceMatrix * worldPosition; + + #endif + + worldPosition = modelMatrix * worldPosition; + + projTexCoord = textureMatrix * worldPosition; + + }`, + fragmentShader: `#include + varying vec4 vPosition; + varying vec4 projTexCoord; + uniform sampler2D depthTexture; + uniform vec2 cameraNearFar; + + void main() { + + float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord )); + float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y ); + float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0; + gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0); + + }` + }); + } + getEdgeDetectionMaterial() { + return new ShaderMaterial({ + uniforms: { + maskTexture: { value: null }, + texSize: { value: new Vector2(0.5, 0.5) }, + visibleEdgeColor: { value: new Vector3(1, 1, 1) }, + hiddenEdgeColor: { value: new Vector3(1, 1, 1) } + }, + vertexShader: `varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `varying vec2 vUv; + + uniform sampler2D maskTexture; + uniform vec2 texSize; + uniform vec3 visibleEdgeColor; + uniform vec3 hiddenEdgeColor; + + void main() { + vec2 invSize = 1.0 / texSize; + vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize); + vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy); + vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy); + vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw); + vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw); + float diff1 = (c1.r - c2.r)*0.5; + float diff2 = (c3.r - c4.r)*0.5; + float d = length( vec2(diff1, diff2) ); + float a1 = min(c1.g, c2.g); + float a2 = min(c3.g, c4.g); + float visibilityFactor = min(a1, a2); + vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor; + gl_FragColor = vec4(edgeColor, 1.0) * vec4(d); + }` + }); + } + getSeparableBlurMaterial(maxRadius) { + return new ShaderMaterial({ + defines: { + MAX_RADIUS: maxRadius + }, + uniforms: { + colorTexture: { value: null }, + texSize: { value: new Vector2(0.5, 0.5) }, + direction: { value: new Vector2(0.5, 0.5) }, + kernelRadius: { value: 1 } + }, + vertexShader: `varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `#include + varying vec2 vUv; + uniform sampler2D colorTexture; + uniform vec2 texSize; + uniform vec2 direction; + uniform float kernelRadius; + + float gaussianPdf(in float x, in float sigma) { + return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma; + } + + void main() { + vec2 invSize = 1.0 / texSize; + float sigma = kernelRadius/2.0; + float weightSum = gaussianPdf(0.0, sigma); + vec4 diffuseSum = texture2D( colorTexture, vUv) * weightSum; + vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS); + vec2 uvOffset = delta; + for( int i = 1; i <= MAX_RADIUS; i ++ ) { + float x = kernelRadius * float(i) / float(MAX_RADIUS); + float w = gaussianPdf(x, sigma); + vec4 sample1 = texture2D( colorTexture, vUv + uvOffset); + vec4 sample2 = texture2D( colorTexture, vUv - uvOffset); + diffuseSum += ((sample1 + sample2) * w); + weightSum += (2.0 * w); + uvOffset += delta; + } + gl_FragColor = diffuseSum/weightSum; + }` + }); + } + getOverlayMaterial() { + return new ShaderMaterial({ + uniforms: { + maskTexture: { value: null }, + edgeTexture1: { value: null }, + edgeTexture2: { value: null }, + patternTexture: { value: null }, + edgeStrength: { value: 1 }, + edgeGlow: { value: 1 }, + usePatternTexture: { value: 0 } + }, + vertexShader: `varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `varying vec2 vUv; + + uniform sampler2D maskTexture; + uniform sampler2D edgeTexture1; + uniform sampler2D edgeTexture2; + uniform sampler2D patternTexture; + uniform float edgeStrength; + uniform float edgeGlow; + uniform bool usePatternTexture; + + void main() { + vec4 edgeValue1 = texture2D(edgeTexture1, vUv); + vec4 edgeValue2 = texture2D(edgeTexture2, vUv); + vec4 maskColor = texture2D(maskTexture, vUv); + vec4 patternColor = texture2D(patternTexture, 6.0 * vUv); + float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5; + vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow; + vec4 finalColor = edgeStrength * maskColor.r * edgeValue; + if(usePatternTexture) + finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r); + gl_FragColor = finalColor; + }`, + blending: AdditiveBlending, + depthTest: false, + depthWrite: false, + transparent: true + }); + } +} +OutlinePass.BlurDirectionX = new Vector2(1, 0); +OutlinePass.BlurDirectionY = new Vector2(0, 1); +// node_modules/three/examples/jsm/shaders/SAOShader.js +var SAOShader = { + name: "SAOShader", + defines: { + NUM_SAMPLES: 7, + NUM_RINGS: 4, + DIFFUSE_TEXTURE: 0, + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDepth: { value: null }, + tDiffuse: { value: null }, + tNormal: { value: null }, + size: { value: new Vector2(512, 512) }, + cameraNear: { value: 1 }, + cameraFar: { value: 100 }, + cameraProjectionMatrix: { value: new Matrix4 }, + cameraInverseProjectionMatrix: { value: new Matrix4 }, + scale: { value: 1 }, + intensity: { value: 0.1 }, + bias: { value: 0.5 }, + minResolution: { value: 0 }, + kernelRadius: { value: 100 }, + randomSeed: { value: 0 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + #include + + varying vec2 vUv; + + #if DIFFUSE_TEXTURE == 1 + uniform sampler2D tDiffuse; + #endif + + uniform highp sampler2D tDepth; + uniform highp sampler2D tNormal; + + uniform float cameraNear; + uniform float cameraFar; + uniform mat4 cameraProjectionMatrix; + uniform mat4 cameraInverseProjectionMatrix; + + uniform float scale; + uniform float intensity; + uniform float bias; + uniform float kernelRadius; + uniform float minResolution; + uniform vec2 size; + uniform float randomSeed; + + // RGBA depth + + #include + + vec4 getDefaultColor( const in vec2 screenPosition ) { + #if DIFFUSE_TEXTURE == 1 + return texture2D( tDiffuse, vUv ); + #else + return vec4( 1.0 ); + #endif + } + + float getDepth( const in vec2 screenPosition ) { + return texture2D( tDepth, screenPosition ).x; + } + + float getViewZ( const in float depth ) { + #if PERSPECTIVE_CAMERA == 1 + return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + #else + return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + #endif + } + + vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) { + float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3]; + vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 ); + clipPosition *= clipW; // unprojection. + + return ( cameraInverseProjectionMatrix * clipPosition ).xyz; + } + + vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPosition ) { + return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); + } + + float scaleDividedByCameraFar; + float minResolutionMultipliedByCameraFar; + + float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) { + vec3 viewDelta = sampleViewPosition - centerViewPosition; + float viewDistance = length( viewDelta ); + float scaledScreenDistance = scaleDividedByCameraFar * viewDistance; + + return max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - bias) / (1.0 + pow2( scaledScreenDistance ) ); + } + + // moving costly divides into consts + const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES ); + const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES ); + + float getAmbientOcclusion( const in vec3 centerViewPosition ) { + // precompute some variables require in getOcclusion. + scaleDividedByCameraFar = scale / cameraFar; + minResolutionMultipliedByCameraFar = minResolution * cameraFar; + vec3 centerViewNormal = getViewNormal( centerViewPosition, vUv ); + + // jsfiddle that shows sample pattern: https://jsfiddle.net/a16ff1p7/ + float angle = rand( vUv + randomSeed ) * PI2; + vec2 radius = vec2( kernelRadius * INV_NUM_SAMPLES ) / size; + vec2 radiusStep = radius; + + float occlusionSum = 0.0; + float weightSum = 0.0; + + for( int i = 0; i < NUM_SAMPLES; i ++ ) { + vec2 sampleUv = vUv + vec2( cos( angle ), sin( angle ) ) * radius; + radius += radiusStep; + angle += ANGLE_STEP; + + float sampleDepth = getDepth( sampleUv ); + if( sampleDepth >= ( 1.0 - EPSILON ) ) { + continue; + } + + float sampleViewZ = getViewZ( sampleDepth ); + vec3 sampleViewPosition = getViewPosition( sampleUv, sampleDepth, sampleViewZ ); + occlusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition ); + weightSum += 1.0; + } + + if( weightSum == 0.0 ) discard; + + return occlusionSum * ( intensity / weightSum ); + } + + void main() { + float centerDepth = getDepth( vUv ); + if( centerDepth >= ( 1.0 - EPSILON ) ) { + discard; + } + + float centerViewZ = getViewZ( centerDepth ); + vec3 viewPosition = getViewPosition( vUv, centerDepth, centerViewZ ); + + float ambientOcclusion = getAmbientOcclusion( viewPosition ); + + gl_FragColor = getDefaultColor( vUv ); + gl_FragColor.xyz *= 1.0 - ambientOcclusion; + }` +}; + +// node_modules/three/examples/jsm/shaders/DepthLimitedBlurShader.js +var DepthLimitedBlurShader = { + name: "DepthLimitedBlurShader", + defines: { + KERNEL_RADIUS: 4, + DEPTH_PACKING: 1, + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDiffuse: { value: null }, + size: { value: new Vector2(512, 512) }, + sampleUvOffsets: { value: [new Vector2(0, 0)] }, + sampleWeights: { value: [1] }, + tDepth: { value: null }, + cameraNear: { value: 10 }, + cameraFar: { value: 1000 }, + depthCutoff: { value: 10 } + }, + vertexShader: ` + + #include + + uniform vec2 size; + + varying vec2 vUv; + varying vec2 vInvSize; + + void main() { + vUv = uv; + vInvSize = 1.0 / size; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + + #include + #include + + uniform sampler2D tDiffuse; + uniform sampler2D tDepth; + + uniform float cameraNear; + uniform float cameraFar; + uniform float depthCutoff; + + uniform vec2 sampleUvOffsets[ KERNEL_RADIUS + 1 ]; + uniform float sampleWeights[ KERNEL_RADIUS + 1 ]; + + varying vec2 vUv; + varying vec2 vInvSize; + + float getDepth( const in vec2 screenPosition ) { + #if DEPTH_PACKING == 1 + return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) ); + #else + return texture2D( tDepth, screenPosition ).x; + #endif + } + + float getViewZ( const in float depth ) { + #if PERSPECTIVE_CAMERA == 1 + return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + #else + return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + #endif + } + + void main() { + float depth = getDepth( vUv ); + if( depth >= ( 1.0 - EPSILON ) ) { + discard; + } + + float centerViewZ = -getViewZ( depth ); + bool rBreak = false, lBreak = false; + + float weightSum = sampleWeights[0]; + vec4 diffuseSum = texture2D( tDiffuse, vUv ) * weightSum; + + for( int i = 1; i <= KERNEL_RADIUS; i ++ ) { + + float sampleWeight = sampleWeights[i]; + vec2 sampleUvOffset = sampleUvOffsets[i] * vInvSize; + + vec2 sampleUv = vUv + sampleUvOffset; + float viewZ = -getViewZ( getDepth( sampleUv ) ); + + if( abs( viewZ - centerViewZ ) > depthCutoff ) rBreak = true; + + if( ! rBreak ) { + diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight; + weightSum += sampleWeight; + } + + sampleUv = vUv - sampleUvOffset; + viewZ = -getViewZ( getDepth( sampleUv ) ); + + if( abs( viewZ - centerViewZ ) > depthCutoff ) lBreak = true; + + if( ! lBreak ) { + diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight; + weightSum += sampleWeight; + } + + } + + gl_FragColor = diffuseSum / weightSum; + }` +}; +var BlurShaderUtils = { + createSampleWeights: function(kernelRadius, stdDev) { + const weights = []; + for (let i = 0;i <= kernelRadius; i++) { + weights.push(gaussian(i, stdDev)); + } + return weights; + }, + createSampleOffsets: function(kernelRadius, uvIncrement) { + const offsets = []; + for (let i = 0;i <= kernelRadius; i++) { + offsets.push(uvIncrement.clone().multiplyScalar(i)); + } + return offsets; + }, + configure: function(material, kernelRadius, stdDev, uvIncrement) { + material.defines["KERNEL_RADIUS"] = kernelRadius; + material.uniforms["sampleUvOffsets"].value = BlurShaderUtils.createSampleOffsets(kernelRadius, uvIncrement); + material.uniforms["sampleWeights"].value = BlurShaderUtils.createSampleWeights(kernelRadius, stdDev); + material.needsUpdate = true; + } +}; +function gaussian(x2, stdDev) { + return Math.exp(-(x2 * x2) / (2 * (stdDev * stdDev))) / (Math.sqrt(2 * Math.PI) * stdDev); +} + +// node_modules/three/examples/jsm/postprocessing/SAOPass.js +class SAOPass extends Pass { + constructor(scene, camera, resolution = new Vector2(256, 256)) { + super(); + this.scene = scene; + this.camera = camera; + this.clear = true; + this.needsSwap = false; + this.originalClearColor = new Color; + this._oldClearColor = new Color; + this.oldClearAlpha = 1; + this.params = { + output: 0, + saoBias: 0.5, + saoIntensity: 0.18, + saoScale: 1, + saoKernelRadius: 100, + saoMinResolution: 0, + saoBlur: true, + saoBlurRadius: 8, + saoBlurStdDev: 4, + saoBlurDepthCutoff: 0.01 + }; + this.resolution = new Vector2(resolution.x, resolution.y); + this.saoRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { type: HalfFloatType }); + this.blurIntermediateRenderTarget = this.saoRenderTarget.clone(); + const depthTexture = new DepthTexture; + depthTexture.format = DepthStencilFormat; + depthTexture.type = UnsignedInt248Type; + this.normalRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType, + depthTexture + }); + this.normalMaterial = new MeshNormalMaterial; + this.normalMaterial.blending = NoBlending; + this.saoMaterial = new ShaderMaterial({ + defines: Object.assign({}, SAOShader.defines), + fragmentShader: SAOShader.fragmentShader, + vertexShader: SAOShader.vertexShader, + uniforms: UniformsUtils.clone(SAOShader.uniforms) + }); + this.saoMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0; + this.saoMaterial.uniforms["tDepth"].value = depthTexture; + this.saoMaterial.uniforms["tNormal"].value = this.normalRenderTarget.texture; + this.saoMaterial.uniforms["size"].value.set(this.resolution.x, this.resolution.y); + this.saoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.saoMaterial.uniforms["cameraProjectionMatrix"].value = this.camera.projectionMatrix; + this.saoMaterial.blending = NoBlending; + this.vBlurMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(DepthLimitedBlurShader.uniforms), + defines: Object.assign({}, DepthLimitedBlurShader.defines), + vertexShader: DepthLimitedBlurShader.vertexShader, + fragmentShader: DepthLimitedBlurShader.fragmentShader + }); + this.vBlurMaterial.defines["DEPTH_PACKING"] = 0; + this.vBlurMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0; + this.vBlurMaterial.uniforms["tDiffuse"].value = this.saoRenderTarget.texture; + this.vBlurMaterial.uniforms["tDepth"].value = depthTexture; + this.vBlurMaterial.uniforms["size"].value.set(this.resolution.x, this.resolution.y); + this.vBlurMaterial.blending = NoBlending; + this.hBlurMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(DepthLimitedBlurShader.uniforms), + defines: Object.assign({}, DepthLimitedBlurShader.defines), + vertexShader: DepthLimitedBlurShader.vertexShader, + fragmentShader: DepthLimitedBlurShader.fragmentShader + }); + this.hBlurMaterial.defines["DEPTH_PACKING"] = 0; + this.hBlurMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0; + this.hBlurMaterial.uniforms["tDiffuse"].value = this.blurIntermediateRenderTarget.texture; + this.hBlurMaterial.uniforms["tDepth"].value = depthTexture; + this.hBlurMaterial.uniforms["size"].value.set(this.resolution.x, this.resolution.y); + this.hBlurMaterial.blending = NoBlending; + this.materialCopy = new ShaderMaterial({ + uniforms: UniformsUtils.clone(CopyShader.uniforms), + vertexShader: CopyShader.vertexShader, + fragmentShader: CopyShader.fragmentShader, + blending: NoBlending + }); + this.materialCopy.transparent = true; + this.materialCopy.depthTest = false; + this.materialCopy.depthWrite = false; + this.materialCopy.blending = CustomBlending; + this.materialCopy.blendSrc = DstColorFactor; + this.materialCopy.blendDst = ZeroFactor; + this.materialCopy.blendEquation = AddEquation; + this.materialCopy.blendSrcAlpha = DstAlphaFactor; + this.materialCopy.blendDstAlpha = ZeroFactor; + this.materialCopy.blendEquationAlpha = AddEquation; + this.fsQuad = new FullScreenQuad(null); + } + render(renderer2, writeBuffer, readBuffer) { + if (this.renderToScreen) { + this.materialCopy.blending = NoBlending; + this.materialCopy.uniforms["tDiffuse"].value = readBuffer.texture; + this.materialCopy.needsUpdate = true; + this.renderPass(renderer2, this.materialCopy, null); + } + renderer2.getClearColor(this._oldClearColor); + this.oldClearAlpha = renderer2.getClearAlpha(); + const oldAutoClear = renderer2.autoClear; + renderer2.autoClear = false; + this.saoMaterial.uniforms["bias"].value = this.params.saoBias; + this.saoMaterial.uniforms["intensity"].value = this.params.saoIntensity; + this.saoMaterial.uniforms["scale"].value = this.params.saoScale; + this.saoMaterial.uniforms["kernelRadius"].value = this.params.saoKernelRadius; + this.saoMaterial.uniforms["minResolution"].value = this.params.saoMinResolution; + this.saoMaterial.uniforms["cameraNear"].value = this.camera.near; + this.saoMaterial.uniforms["cameraFar"].value = this.camera.far; + const depthCutoff = this.params.saoBlurDepthCutoff * (this.camera.far - this.camera.near); + this.vBlurMaterial.uniforms["depthCutoff"].value = depthCutoff; + this.hBlurMaterial.uniforms["depthCutoff"].value = depthCutoff; + this.vBlurMaterial.uniforms["cameraNear"].value = this.camera.near; + this.vBlurMaterial.uniforms["cameraFar"].value = this.camera.far; + this.hBlurMaterial.uniforms["cameraNear"].value = this.camera.near; + this.hBlurMaterial.uniforms["cameraFar"].value = this.camera.far; + this.params.saoBlurRadius = Math.floor(this.params.saoBlurRadius); + if (this.prevStdDev !== this.params.saoBlurStdDev || this.prevNumSamples !== this.params.saoBlurRadius) { + BlurShaderUtils.configure(this.vBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2(0, 1)); + BlurShaderUtils.configure(this.hBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2(1, 0)); + this.prevStdDev = this.params.saoBlurStdDev; + this.prevNumSamples = this.params.saoBlurRadius; + } + this.renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 7829503, 1); + this.renderPass(renderer2, this.saoMaterial, this.saoRenderTarget, 16777215, 1); + if (this.params.saoBlur) { + this.renderPass(renderer2, this.vBlurMaterial, this.blurIntermediateRenderTarget, 16777215, 1); + this.renderPass(renderer2, this.hBlurMaterial, this.saoRenderTarget, 16777215, 1); + } + const outputMaterial = this.materialCopy; + if (this.params.output === SAOPass.OUTPUT.Normal) { + this.materialCopy.uniforms["tDiffuse"].value = this.normalRenderTarget.texture; + this.materialCopy.needsUpdate = true; + } else { + this.materialCopy.uniforms["tDiffuse"].value = this.saoRenderTarget.texture; + this.materialCopy.needsUpdate = true; + } + if (this.params.output === SAOPass.OUTPUT.Default) { + outputMaterial.blending = CustomBlending; + } else { + outputMaterial.blending = NoBlending; + } + this.renderPass(renderer2, outputMaterial, this.renderToScreen ? null : readBuffer); + renderer2.setClearColor(this._oldClearColor, this.oldClearAlpha); + renderer2.autoClear = oldAutoClear; + } + renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.fsQuad.material = passMaterial; + this.fsQuad.render(renderer2); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.overrideMaterial = overrideMaterial; + renderer2.render(this.scene, this.camera); + this.scene.overrideMaterial = null; + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + setSize(width2, height2) { + this.saoRenderTarget.setSize(width2, height2); + this.blurIntermediateRenderTarget.setSize(width2, height2); + this.normalRenderTarget.setSize(width2, height2); + this.saoMaterial.uniforms["size"].value.set(width2, height2); + this.saoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.saoMaterial.uniforms["cameraProjectionMatrix"].value = this.camera.projectionMatrix; + this.saoMaterial.needsUpdate = true; + this.vBlurMaterial.uniforms["size"].value.set(width2, height2); + this.vBlurMaterial.needsUpdate = true; + this.hBlurMaterial.uniforms["size"].value.set(width2, height2); + this.hBlurMaterial.needsUpdate = true; + } + dispose() { + this.saoRenderTarget.dispose(); + this.blurIntermediateRenderTarget.dispose(); + this.normalRenderTarget.dispose(); + this.normalMaterial.dispose(); + this.saoMaterial.dispose(); + this.vBlurMaterial.dispose(); + this.hBlurMaterial.dispose(); + this.materialCopy.dispose(); + this.fsQuad.dispose(); + } +} +SAOPass.OUTPUT = { + Default: 0, + SAO: 1, + Normal: 2 +}; +// node_modules/three/examples/jsm/shaders/SMAAShader.js +var SMAAEdgesShader = { + name: "SMAAEdgesShader", + defines: { + SMAA_THRESHOLD: "0.1" + }, + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2(1 / 1024, 1 / 512) } + }, + vertexShader: ` + + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 3 ]; + + void SMAAEdgeDetectionVS( vec2 texcoord ) { + vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component + vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component + vOffset[ 2 ] = texcoord.xyxy + resolution.xyxy * vec4( -2.0, 0.0, 0.0, 2.0 ); // WebGL port note: Changed sign in W component + } + + void main() { + + vUv = uv; + + SMAAEdgeDetectionVS( vUv ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + varying vec4 vOffset[ 3 ]; + + vec4 SMAAColorEdgeDetectionPS( vec2 texcoord, vec4 offset[3], sampler2D colorTex ) { + vec2 threshold = vec2( SMAA_THRESHOLD, SMAA_THRESHOLD ); + + // Calculate color deltas: + vec4 delta; + vec3 C = texture2D( colorTex, texcoord ).rgb; + + vec3 Cleft = texture2D( colorTex, offset[0].xy ).rgb; + vec3 t = abs( C - Cleft ); + delta.x = max( max( t.r, t.g ), t.b ); + + vec3 Ctop = texture2D( colorTex, offset[0].zw ).rgb; + t = abs( C - Ctop ); + delta.y = max( max( t.r, t.g ), t.b ); + + // We do the usual threshold: + vec2 edges = step( threshold, delta.xy ); + + // Then discard if there is no edge: + if ( dot( edges, vec2( 1.0, 1.0 ) ) == 0.0 ) + discard; + + // Calculate right and bottom deltas: + vec3 Cright = texture2D( colorTex, offset[1].xy ).rgb; + t = abs( C - Cright ); + delta.z = max( max( t.r, t.g ), t.b ); + + vec3 Cbottom = texture2D( colorTex, offset[1].zw ).rgb; + t = abs( C - Cbottom ); + delta.w = max( max( t.r, t.g ), t.b ); + + // Calculate the maximum delta in the direct neighborhood: + float maxDelta = max( max( max( delta.x, delta.y ), delta.z ), delta.w ); + + // Calculate left-left and top-top deltas: + vec3 Cleftleft = texture2D( colorTex, offset[2].xy ).rgb; + t = abs( C - Cleftleft ); + delta.z = max( max( t.r, t.g ), t.b ); + + vec3 Ctoptop = texture2D( colorTex, offset[2].zw ).rgb; + t = abs( C - Ctoptop ); + delta.w = max( max( t.r, t.g ), t.b ); + + // Calculate the final maximum delta: + maxDelta = max( max( maxDelta, delta.z ), delta.w ); + + // Local contrast adaptation in action: + edges.xy *= step( 0.5 * maxDelta, delta.xy ); + + return vec4( edges, 0.0, 0.0 ); + } + + void main() { + + gl_FragColor = SMAAColorEdgeDetectionPS( vUv, vOffset, tDiffuse ); + + }` +}; +var SMAAWeightsShader = { + name: "SMAAWeightsShader", + defines: { + SMAA_MAX_SEARCH_STEPS: "8", + SMAA_AREATEX_MAX_DISTANCE: "16", + SMAA_AREATEX_PIXEL_SIZE: "( 1.0 / vec2( 160.0, 560.0 ) )", + SMAA_AREATEX_SUBTEX_SIZE: "( 1.0 / 7.0 )" + }, + uniforms: { + tDiffuse: { value: null }, + tArea: { value: null }, + tSearch: { value: null }, + resolution: { value: new Vector2(1 / 1024, 1 / 512) } + }, + vertexShader: ` + + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 3 ]; + varying vec2 vPixcoord; + + void SMAABlendingWeightCalculationVS( vec2 texcoord ) { + vPixcoord = texcoord / resolution; + + // We will use these offsets for the searches later on (see @PSEUDO_GATHER4): + vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.25, 0.125, 1.25, 0.125 ); // WebGL port note: Changed sign in Y and W components + vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.125, 0.25, -0.125, -1.25 ); // WebGL port note: Changed sign in Y and W components + + // And these for the searches, they indicate the ends of the loops: + vOffset[ 2 ] = vec4( vOffset[ 0 ].xz, vOffset[ 1 ].yw ) + vec4( -2.0, 2.0, -2.0, 2.0 ) * resolution.xxyy * float( SMAA_MAX_SEARCH_STEPS ); + + } + + void main() { + + vUv = uv; + + SMAABlendingWeightCalculationVS( vUv ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + #define SMAASampleLevelZeroOffset( tex, coord, offset ) texture2D( tex, coord + float( offset ) * resolution, 0.0 ) + + uniform sampler2D tDiffuse; + uniform sampler2D tArea; + uniform sampler2D tSearch; + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[3]; + varying vec2 vPixcoord; + + #if __VERSION__ == 100 + vec2 round( vec2 x ) { + return sign( x ) * floor( abs( x ) + 0.5 ); + } + #endif + + float SMAASearchLength( sampler2D searchTex, vec2 e, float bias, float scale ) { + // Not required if searchTex accesses are set to point: + // float2 SEARCH_TEX_PIXEL_SIZE = 1.0 / float2(66.0, 33.0); + // e = float2(bias, 0.0) + 0.5 * SEARCH_TEX_PIXEL_SIZE + + // e * float2(scale, 1.0) * float2(64.0, 32.0) * SEARCH_TEX_PIXEL_SIZE; + e.r = bias + e.r * scale; + return 255.0 * texture2D( searchTex, e, 0.0 ).r; + } + + float SMAASearchXLeft( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + /** + * @PSEUDO_GATHER4 + * This texcoord has been offset by (-0.25, -0.125) in the vertex shader to + * sample between edge, thus fetching four edges in a row. + * Sampling with different offsets in each direction allows to disambiguate + * which edges are active from the four fetched ones. + */ + vec2 e = vec2( 0.0, 1.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord -= vec2( 2.0, 0.0 ) * resolution; + if ( ! ( texcoord.x > end && e.g > 0.8281 && e.r == 0.0 ) ) break; + } + + // We correct the previous (-0.25, -0.125) offset we applied: + texcoord.x += 0.25 * resolution.x; + + // The searches are bias by 1, so adjust the coords accordingly: + texcoord.x += resolution.x; + + // Disambiguate the length added by the last step: + texcoord.x += 2.0 * resolution.x; // Undo last step + texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5); + + return texcoord.x; + } + + float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + vec2 e = vec2( 0.0, 1.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord += vec2( 2.0, 0.0 ) * resolution; + if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break; + } + + texcoord.x -= 0.25 * resolution.x; + texcoord.x -= resolution.x; + texcoord.x -= 2.0 * resolution.x; + texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 ); + + return texcoord.x; + } + + float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + vec2 e = vec2( 1.0, 0.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord += vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign + if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break; + } + + texcoord.y -= 0.25 * resolution.y; // WebGL port note: Changed sign + texcoord.y -= resolution.y; // WebGL port note: Changed sign + texcoord.y -= 2.0 * resolution.y; // WebGL port note: Changed sign + texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 ); // WebGL port note: Changed sign + + return texcoord.y; + } + + float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + vec2 e = vec2( 1.0, 0.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord -= vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign + if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break; + } + + texcoord.y += 0.25 * resolution.y; // WebGL port note: Changed sign + texcoord.y += resolution.y; // WebGL port note: Changed sign + texcoord.y += 2.0 * resolution.y; // WebGL port note: Changed sign + texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 ); // WebGL port note: Changed sign + + return texcoord.y; + } + + vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) { + // Rounding prevents precision errors of bilinear filtering: + vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist; + + // We do a scale and bias for mapping to texel space: + texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE ); + + // Move to proper place, according to the subpixel offset: + texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset; + + return texture2D( areaTex, texcoord, 0.0 ).rg; + } + + vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) { + vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 ); + + vec2 e = texture2D( edgesTex, texcoord ).rg; + + if ( e.g > 0.0 ) { // Edge at north + vec2 d; + + // Find the distance to the left: + vec2 coords; + coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x ); + coords.y = offset[ 1 ].y; // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET) + d.x = coords.x; + + // Now fetch the left crossing edges, two at a time using bilinear + // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to + // discern what value each edge has: + float e1 = texture2D( edgesTex, coords, 0.0 ).r; + + // Find the distance to the right: + coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y ); + d.y = coords.x; + + // We want the distances to be in pixel units (doing this here allow to + // better interleave arithmetic and memory accesses): + d = d / resolution.x - pixcoord.x; + + // SMAAArea below needs a sqrt, as the areas texture is compressed + // quadratically: + vec2 sqrt_d = sqrt( abs( d ) ); + + // Fetch the right crossing edges: + coords.y -= 1.0 * resolution.y; // WebGL port note: Added + float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r; + + // Ok, we know how this pattern looks like, now it is time for getting + // the actual area: + weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) ); + } + + if ( e.r > 0.0 ) { // Edge at west + vec2 d; + + // Find the distance to the top: + vec2 coords; + + coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z ); + coords.x = offset[ 0 ].x; // offset[1].x = texcoord.x - 0.25 * resolution.x; + d.x = coords.y; + + // Fetch the top crossing edges: + float e1 = texture2D( edgesTex, coords, 0.0 ).g; + + // Find the distance to the bottom: + coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w ); + d.y = coords.y; + + // We want the distances to be in pixel units: + d = d / resolution.y - pixcoord.y; + + // SMAAArea below needs a sqrt, as the areas texture is compressed + // quadratically: + vec2 sqrt_d = sqrt( abs( d ) ); + + // Fetch the bottom crossing edges: + coords.y -= 1.0 * resolution.y; // WebGL port note: Added + float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g; + + // Get the area for this direction: + weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) ); + } + + return weights; + } + + void main() { + + gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) ); + + }` +}; +var SMAABlendShader = { + name: "SMAABlendShader", + uniforms: { + tDiffuse: { value: null }, + tColor: { value: null }, + resolution: { value: new Vector2(1 / 1024, 1 / 512) } + }, + vertexShader: ` + + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 2 ]; + + void SMAANeighborhoodBlendingVS( vec2 texcoord ) { + vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component + vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component + } + + void main() { + + vUv = uv; + + SMAANeighborhoodBlendingVS( vUv ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform sampler2D tColor; + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 2 ]; + + vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) { + // Fetch the blending weights for current pixel: + vec4 a; + a.xz = texture2D( blendTex, texcoord ).xz; + a.y = texture2D( blendTex, offset[ 1 ].zw ).g; + a.w = texture2D( blendTex, offset[ 1 ].xy ).a; + + // Is there any blending weight with a value greater than 0.0? + if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) { + return texture2D( colorTex, texcoord, 0.0 ); + } else { + // Up to 4 lines can be crossing a pixel (one through each edge). We + // favor blending by choosing the line with the maximum weight for each + // direction: + vec2 offset; + offset.x = a.a > a.b ? a.a : -a.b; // left vs. right + offset.y = a.g > a.r ? -a.g : a.r; // top vs. bottom // WebGL port note: Changed signs + + // Then we go in the direction that has the maximum weight: + if ( abs( offset.x ) > abs( offset.y )) { // horizontal vs. vertical + offset.y = 0.0; + } else { + offset.x = 0.0; + } + + // Fetch the opposite color and lerp by hand: + vec4 C = texture2D( colorTex, texcoord, 0.0 ); + texcoord += sign( offset ) * resolution; + vec4 Cop = texture2D( colorTex, texcoord, 0.0 ); + float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y ); + + // WebGL port note: Added gamma correction + C.xyz = pow(C.xyz, vec3(2.2)); + Cop.xyz = pow(Cop.xyz, vec3(2.2)); + vec4 mixed = mix(C, Cop, s); + mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2)); + + return mixed; + } + } + + void main() { + + gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse ); + + }` +}; +// node_modules/three/examples/jsm/shaders/SSAOShader.js +var SSAOShader = { + name: "SSAOShader", + defines: { + PERSPECTIVE_CAMERA: 1, + KERNEL_SIZE: 32 + }, + uniforms: { + tNormal: { value: null }, + tDepth: { value: null }, + tNoise: { value: null }, + kernel: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null }, + resolution: { value: new Vector2 }, + cameraProjectionMatrix: { value: new Matrix4 }, + cameraInverseProjectionMatrix: { value: new Matrix4 }, + kernelRadius: { value: 8 }, + minDistance: { value: 0.005 }, + maxDistance: { value: 0.05 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + uniform highp sampler2D tNormal; + uniform highp sampler2D tDepth; + uniform sampler2D tNoise; + + uniform vec3 kernel[ KERNEL_SIZE ]; + + uniform vec2 resolution; + + uniform float cameraNear; + uniform float cameraFar; + uniform mat4 cameraProjectionMatrix; + uniform mat4 cameraInverseProjectionMatrix; + + uniform float kernelRadius; + uniform float minDistance; // avoid artifacts caused by neighbour fragments with minimal depth difference + uniform float maxDistance; // avoid the influence of fragments which are too far away + + varying vec2 vUv; + + #include + + float getDepth( const in vec2 screenPosition ) { + + return texture2D( tDepth, screenPosition ).x; + + } + + float getLinearDepth( const in vec2 screenPosition ) { + + #if PERSPECTIVE_CAMERA == 1 + + float fragCoordZ = texture2D( tDepth, screenPosition ).x; + float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); + return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + + #else + + return texture2D( tDepth, screenPosition ).x; + + #endif + + } + + float getViewZ( const in float depth ) { + + #if PERSPECTIVE_CAMERA == 1 + + return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + + #else + + return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + + #endif + + } + + vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) { + + float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3]; + + vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 ); + + clipPosition *= clipW; // unprojection. + + return ( cameraInverseProjectionMatrix * clipPosition ).xyz; + + } + + vec3 getViewNormal( const in vec2 screenPosition ) { + + return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); + + } + + void main() { + + float depth = getDepth( vUv ); + + if ( depth == 1.0 ) { + + gl_FragColor = vec4( 1.0 ); // don't influence background + + } else { + + float viewZ = getViewZ( depth ); + + vec3 viewPosition = getViewPosition( vUv, depth, viewZ ); + vec3 viewNormal = getViewNormal( vUv ); + + vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 ); + vec3 random = vec3( texture2D( tNoise, vUv * noiseScale ).r ); + + // compute matrix used to reorient a kernel vector + + vec3 tangent = normalize( random - viewNormal * dot( random, viewNormal ) ); + vec3 bitangent = cross( viewNormal, tangent ); + mat3 kernelMatrix = mat3( tangent, bitangent, viewNormal ); + + float occlusion = 0.0; + + for ( int i = 0; i < KERNEL_SIZE; i ++ ) { + + vec3 sampleVector = kernelMatrix * kernel[ i ]; // reorient sample vector in view space + vec3 samplePoint = viewPosition + ( sampleVector * kernelRadius ); // calculate sample point + + vec4 samplePointNDC = cameraProjectionMatrix * vec4( samplePoint, 1.0 ); // project point and calculate NDC + samplePointNDC /= samplePointNDC.w; + + vec2 samplePointUv = samplePointNDC.xy * 0.5 + 0.5; // compute uv coordinates + + float realDepth = getLinearDepth( samplePointUv ); // get linear depth from depth texture + float sampleDepth = viewZToOrthographicDepth( samplePoint.z, cameraNear, cameraFar ); // compute linear depth of the sample view Z value + float delta = sampleDepth - realDepth; + + if ( delta > minDistance && delta < maxDistance ) { // if fragment is before sample point, increase occlusion + + occlusion += 1.0; + + } + + } + + occlusion = clamp( occlusion / float( KERNEL_SIZE ), 0.0, 1.0 ); + + gl_FragColor = vec4( vec3( 1.0 - occlusion ), 1.0 ); + + } + + }` +}; +var SSAODepthShader = { + name: "SSAODepthShader", + defines: { + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDepth: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null } + }, + vertexShader: `varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: `uniform sampler2D tDepth; + + uniform float cameraNear; + uniform float cameraFar; + + varying vec2 vUv; + + #include + + float getLinearDepth( const in vec2 screenPosition ) { + + #if PERSPECTIVE_CAMERA == 1 + + float fragCoordZ = texture2D( tDepth, screenPosition ).x; + float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); + return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + + #else + + return texture2D( tDepth, screenPosition ).x; + + #endif + + } + + void main() { + + float depth = getLinearDepth( vUv ); + gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); + + }` +}; +var SSAOBlurShader = { + name: "SSAOBlurShader", + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2 } + }, + vertexShader: `varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: `uniform sampler2D tDiffuse; + + uniform vec2 resolution; + + varying vec2 vUv; + + void main() { + + vec2 texelSize = ( 1.0 / resolution ); + float result = 0.0; + + for ( int i = - 2; i <= 2; i ++ ) { + + for ( int j = - 2; j <= 2; j ++ ) { + + vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize; + result += texture2D( tDiffuse, vUv + offset ).r; + + } + + } + + gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 ); + + }` +}; + +// node_modules/three/examples/jsm/postprocessing/SSAOPass.js +class SSAOPass extends Pass { + constructor(scene, camera, width2, height2, kernelSize = 32) { + super(); + this.width = width2 !== undefined ? width2 : 512; + this.height = height2 !== undefined ? height2 : 512; + this.clear = true; + this.needsSwap = false; + this.camera = camera; + this.scene = scene; + this.kernelRadius = 8; + this.kernel = []; + this.noiseTexture = null; + this.output = 0; + this.minDistance = 0.005; + this.maxDistance = 0.1; + this._visibilityCache = new Map; + this.generateSampleKernel(kernelSize); + this.generateRandomKernelRotations(); + const depthTexture = new DepthTexture; + depthTexture.format = DepthStencilFormat; + depthTexture.type = UnsignedInt248Type; + this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType, + depthTexture + }); + this.ssaoRenderTarget = new WebGLRenderTarget(this.width, this.height, { type: HalfFloatType }); + this.blurRenderTarget = this.ssaoRenderTarget.clone(); + this.ssaoMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSAOShader.defines), + uniforms: UniformsUtils.clone(SSAOShader.uniforms), + vertexShader: SSAOShader.vertexShader, + fragmentShader: SSAOShader.fragmentShader, + blending: NoBlending + }); + this.ssaoMaterial.defines["KERNEL_SIZE"] = kernelSize; + this.ssaoMaterial.uniforms["tNormal"].value = this.normalRenderTarget.texture; + this.ssaoMaterial.uniforms["tDepth"].value = this.normalRenderTarget.depthTexture; + this.ssaoMaterial.uniforms["tNoise"].value = this.noiseTexture; + this.ssaoMaterial.uniforms["kernel"].value = this.kernel; + this.ssaoMaterial.uniforms["cameraNear"].value = this.camera.near; + this.ssaoMaterial.uniforms["cameraFar"].value = this.camera.far; + this.ssaoMaterial.uniforms["resolution"].value.set(this.width, this.height); + this.ssaoMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); + this.ssaoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.normalMaterial = new MeshNormalMaterial; + this.normalMaterial.blending = NoBlending; + this.blurMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSAOBlurShader.defines), + uniforms: UniformsUtils.clone(SSAOBlurShader.uniforms), + vertexShader: SSAOBlurShader.vertexShader, + fragmentShader: SSAOBlurShader.fragmentShader + }); + this.blurMaterial.uniforms["tDiffuse"].value = this.ssaoRenderTarget.texture; + this.blurMaterial.uniforms["resolution"].value.set(this.width, this.height); + this.depthRenderMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSAODepthShader.defines), + uniforms: UniformsUtils.clone(SSAODepthShader.uniforms), + vertexShader: SSAODepthShader.vertexShader, + fragmentShader: SSAODepthShader.fragmentShader, + blending: NoBlending + }); + this.depthRenderMaterial.uniforms["tDepth"].value = this.normalRenderTarget.depthTexture; + this.depthRenderMaterial.uniforms["cameraNear"].value = this.camera.near; + this.depthRenderMaterial.uniforms["cameraFar"].value = this.camera.far; + this.copyMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(CopyShader.uniforms), + vertexShader: CopyShader.vertexShader, + fragmentShader: CopyShader.fragmentShader, + transparent: true, + depthTest: false, + depthWrite: false, + blendSrc: DstColorFactor, + blendDst: ZeroFactor, + blendEquation: AddEquation, + blendSrcAlpha: DstAlphaFactor, + blendDstAlpha: ZeroFactor, + blendEquationAlpha: AddEquation + }); + this.fsQuad = new FullScreenQuad(null); + this.originalClearColor = new Color; + } + dispose() { + this.normalRenderTarget.dispose(); + this.ssaoRenderTarget.dispose(); + this.blurRenderTarget.dispose(); + this.normalMaterial.dispose(); + this.blurMaterial.dispose(); + this.copyMaterial.dispose(); + this.depthRenderMaterial.dispose(); + this.fsQuad.dispose(); + } + render(renderer2, writeBuffer, readBuffer) { + this.overrideVisibility(); + this.renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 7829503, 1); + this.restoreVisibility(); + this.ssaoMaterial.uniforms["kernelRadius"].value = this.kernelRadius; + this.ssaoMaterial.uniforms["minDistance"].value = this.minDistance; + this.ssaoMaterial.uniforms["maxDistance"].value = this.maxDistance; + this.renderPass(renderer2, this.ssaoMaterial, this.ssaoRenderTarget); + this.renderPass(renderer2, this.blurMaterial, this.blurRenderTarget); + switch (this.output) { + case SSAOPass.OUTPUT.SSAO: + this.copyMaterial.uniforms["tDiffuse"].value = this.ssaoRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer); + break; + case SSAOPass.OUTPUT.Blur: + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer); + break; + case SSAOPass.OUTPUT.Depth: + this.renderPass(renderer2, this.depthRenderMaterial, this.renderToScreen ? null : readBuffer); + break; + case SSAOPass.OUTPUT.Normal: + this.copyMaterial.uniforms["tDiffuse"].value = this.normalRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer); + break; + case SSAOPass.OUTPUT.Default: + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget.texture; + this.copyMaterial.blending = CustomBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer); + break; + default: + console.warn("THREE.SSAOPass: Unknown output type."); + } + } + renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.fsQuad.material = passMaterial; + this.fsQuad.render(renderer2); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.overrideMaterial = overrideMaterial; + renderer2.render(this.scene, this.camera); + this.scene.overrideMaterial = null; + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + setSize(width2, height2) { + this.width = width2; + this.height = height2; + this.ssaoRenderTarget.setSize(width2, height2); + this.normalRenderTarget.setSize(width2, height2); + this.blurRenderTarget.setSize(width2, height2); + this.ssaoMaterial.uniforms["resolution"].value.set(width2, height2); + this.ssaoMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); + this.ssaoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.blurMaterial.uniforms["resolution"].value.set(width2, height2); + } + generateSampleKernel(kernelSize) { + const kernel = this.kernel; + for (let i = 0;i < kernelSize; i++) { + const sample = new Vector3; + sample.x = Math.random() * 2 - 1; + sample.y = Math.random() * 2 - 1; + sample.z = Math.random(); + sample.normalize(); + let scale2 = i / kernelSize; + scale2 = MathUtils.lerp(0.1, 1, scale2 * scale2); + sample.multiplyScalar(scale2); + kernel.push(sample); + } + } + generateRandomKernelRotations() { + const width2 = 4, height2 = 4; + const simplex = new SimplexNoise; + const size2 = width2 * height2; + const data2 = new Float32Array(size2); + for (let i = 0;i < size2; i++) { + const x2 = Math.random() * 2 - 1; + const y3 = Math.random() * 2 - 1; + const z2 = 0; + data2[i] = simplex.noise3d(x2, y3, z2); + } + this.noiseTexture = new DataTexture(data2, width2, height2, RedFormat, FloatType); + this.noiseTexture.wrapS = RepeatWrapping; + this.noiseTexture.wrapT = RepeatWrapping; + this.noiseTexture.needsUpdate = true; + } + overrideVisibility() { + const scene = this.scene; + const cache = this._visibilityCache; + scene.traverse(function(object) { + cache.set(object, object.visible); + if (object.isPoints || object.isLine) + object.visible = false; + }); + } + restoreVisibility() { + const scene = this.scene; + const cache = this._visibilityCache; + scene.traverse(function(object) { + const visible = cache.get(object); + object.visible = visible; + }); + cache.clear(); + } +} +SSAOPass.OUTPUT = { + Default: 0, + SSAO: 1, + Blur: 2, + Depth: 3, + Normal: 4 +}; +// node_modules/three/examples/jsm/shaders/SSRShader.js +var SSRShader = { + name: "SSRShader", + defines: { + MAX_STEP: 0, + PERSPECTIVE_CAMERA: true, + DISTANCE_ATTENUATION: true, + FRESNEL: true, + INFINITE_THICK: false, + SELECTIVE: false + }, + uniforms: { + tDiffuse: { value: null }, + tNormal: { value: null }, + tMetalness: { value: null }, + tDepth: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null }, + resolution: { value: new Vector2 }, + cameraProjectionMatrix: { value: new Matrix4 }, + cameraInverseProjectionMatrix: { value: new Matrix4 }, + opacity: { value: 0.5 }, + maxDistance: { value: 180 }, + cameraRange: { value: 0 }, + thickness: { value: 0.018 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + } + + `, + fragmentShader: ` + // precision highp float; + precision highp sampler2D; + varying vec2 vUv; + uniform sampler2D tDepth; + uniform sampler2D tNormal; + uniform sampler2D tMetalness; + uniform sampler2D tDiffuse; + uniform float cameraRange; + uniform vec2 resolution; + uniform float opacity; + uniform float cameraNear; + uniform float cameraFar; + uniform float maxDistance; + uniform float thickness; + uniform mat4 cameraProjectionMatrix; + uniform mat4 cameraInverseProjectionMatrix; + #include + float pointToLineDistance(vec3 x0, vec3 x1, vec3 x2) { + //x0: point, x1: linePointA, x2: linePointB + //https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html + return length(cross(x0-x1,x0-x2))/length(x2-x1); + } + float pointPlaneDistance(vec3 point,vec3 planePoint,vec3 planeNormal){ + // https://mathworld.wolfram.com/Point-PlaneDistance.html + //// https://en.wikipedia.org/wiki/Plane_(geometry) + //// http://paulbourke.net/geometry/pointlineplane/ + float a=planeNormal.x,b=planeNormal.y,c=planeNormal.z; + float x0=point.x,y0=point.y,z0=point.z; + float x=planePoint.x,y=planePoint.y,z=planePoint.z; + float d=-(a*x+b*y+c*z); + float distance=(a*x0+b*y0+c*z0+d)/sqrt(a*a+b*b+c*c); + return distance; + } + float getDepth( const in vec2 uv ) { + return texture2D( tDepth, uv ).x; + } + float getViewZ( const in float depth ) { + #ifdef PERSPECTIVE_CAMERA + return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + #else + return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + #endif + } + vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { + vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc + clipPosition *= clipW; //clip + return ( cameraInverseProjectionMatrix * clipPosition ).xyz;//view + } + vec3 getViewNormal( const in vec2 uv ) { + return unpackRGBToNormal( texture2D( tNormal, uv ).xyz ); + } + vec2 viewPositionToXY(vec3 viewPosition){ + vec2 xy; + vec4 clip=cameraProjectionMatrix*vec4(viewPosition,1); + xy=clip.xy;//clip + float clipW=clip.w; + xy/=clipW;//NDC + xy=(xy+1.)/2.;//uv + xy*=resolution;//screen + return xy; + } + void main(){ + #ifdef SELECTIVE + float metalness=texture2D(tMetalness,vUv).r; + if(metalness==0.) return; + #endif + + float depth = getDepth( vUv ); + float viewZ = getViewZ( depth ); + if(-viewZ>=cameraFar) return; + + float clipW = cameraProjectionMatrix[2][3] * viewZ+cameraProjectionMatrix[3][3]; + vec3 viewPosition=getViewPosition( vUv, depth, clipW ); + + vec2 d0=gl_FragCoord.xy; + vec2 d1; + + vec3 viewNormal=getViewNormal( vUv ); + + #ifdef PERSPECTIVE_CAMERA + vec3 viewIncidentDir=normalize(viewPosition); + vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal); + #else + vec3 viewIncidentDir=vec3(0,0,-1); + vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal); + #endif + + float maxReflectRayLen=maxDistance/dot(-viewIncidentDir,viewNormal); + // dot(a,b)==length(a)*length(b)*cos(theta) // https://www.mathsisfun.com/algebra/vectors-dot-product.html + // if(a.isNormalized&&b.isNormalized) dot(a,b)==cos(theta) + // maxDistance/maxReflectRayLen=cos(theta) + // maxDistance/maxReflectRayLen==dot(a,b) + // maxReflectRayLen==maxDistance/dot(a,b) + + vec3 d1viewPosition=viewPosition+viewReflectDir*maxReflectRayLen; + #ifdef PERSPECTIVE_CAMERA + if(d1viewPosition.z>-cameraNear){ + //https://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx + float t=(-cameraNear-viewPosition.z)/viewReflectDir.z; + d1viewPosition=viewPosition+viewReflectDir*t; + } + #endif + d1=viewPositionToXY(d1viewPosition); + + float totalLen=length(d1-d0); + float xLen=d1.x-d0.x; + float yLen=d1.y-d0.y; + float totalStep=max(abs(xLen),abs(yLen)); + float xSpan=xLen/totalStep; + float ySpan=yLen/totalStep; + for(float i=0.;i=totalStep) break; + vec2 xy=vec2(d0.x+i*xSpan,d0.y+i*ySpan); + if(xy.x<0.||xy.x>resolution.x||xy.y<0.||xy.y>resolution.y) break; + float s=length(xy-d0)/totalLen; + vec2 uv=xy/resolution; + + float d = getDepth(uv); + float vZ = getViewZ( d ); + if(-vZ>=cameraFar) continue; + float cW = cameraProjectionMatrix[2][3] * vZ+cameraProjectionMatrix[3][3]; + vec3 vP=getViewPosition( uv, d, cW ); + + #ifdef PERSPECTIVE_CAMERA + // https://comp.nus.edu.sg/~lowkl/publications/lowk_persp_interp_techrep.pdf + float recipVPZ=1./viewPosition.z; + float viewReflectRayZ=1./(recipVPZ+s*(1./d1viewPosition.z-recipVPZ)); + #else + float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z); + #endif + + // if(viewReflectRayZ>vZ) continue; // will cause "npm run make-screenshot webgl_postprocessing_ssr" high probability hang. + // https://github.com/mrdoob/three.js/pull/21539#issuecomment-821061164 + if(viewReflectRayZ<=vZ){ + + bool hit; + #ifdef INFINITE_THICK + hit=true; + #else + float away=pointToLineDistance(vP,viewPosition,d1viewPosition); + + float minThickness; + vec2 xyNeighbor=xy; + xyNeighbor.x+=1.; + vec2 uvNeighbor=xyNeighbor/resolution; + vec3 vPNeighbor=getViewPosition(uvNeighbor,d,cW); + minThickness=vPNeighbor.x-vP.x; + minThickness*=3.; + float tk=max(minThickness,thickness); + + hit=away<=tk; + #endif + + if(hit){ + vec3 vN=getViewNormal( uv ); + if(dot(viewReflectDir,vN)>=0.) continue; + float distance=pointPlaneDistance(vP,viewPosition,viewNormal); + if(distance>maxDistance) break; + float op=opacity; + #ifdef DISTANCE_ATTENUATION + float ratio=1.-(distance/maxDistance); + float attenuation=ratio*ratio; + op=opacity*attenuation; + #endif + #ifdef FRESNEL + float fresnelCoe=(dot(viewIncidentDir,viewReflectDir)+1.)/2.; + op*=fresnelCoe; + #endif + vec4 reflectColor=texture2D(tDiffuse,uv); + gl_FragColor.xyz=reflectColor.xyz; + gl_FragColor.a=op; + break; + } + } + } + } + ` +}; +var SSRDepthShader = { + name: "SSRDepthShader", + defines: { + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDepth: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + } + + `, + fragmentShader: ` + + uniform sampler2D tDepth; + + uniform float cameraNear; + uniform float cameraFar; + + varying vec2 vUv; + + #include + + float getLinearDepth( const in vec2 uv ) { + + #if PERSPECTIVE_CAMERA == 1 + + float fragCoordZ = texture2D( tDepth, uv ).x; + float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); + return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + + #else + + return texture2D( tDepth, uv ).x; + + #endif + + } + + void main() { + + float depth = getLinearDepth( vUv ); + float d = 1.0 - depth; + // d=(d-.999)*1000.; + gl_FragColor = vec4( vec3( d ), 1.0 ); + + } + + ` +}; +var SSRBlurShader = { + name: "SSRBlurShader", + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2 }, + opacity: { value: 0.5 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + } + + `, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform vec2 resolution; + varying vec2 vUv; + void main() { + //reverse engineering from PhotoShop blur filter, then change coefficient + + vec2 texelSize = ( 1.0 / resolution ); + + vec4 c=texture2D(tDiffuse,vUv); + + vec2 offset; + + offset=(vec2(-1,0))*texelSize; + vec4 cl=texture2D(tDiffuse,vUv+offset); + + offset=(vec2(1,0))*texelSize; + vec4 cr=texture2D(tDiffuse,vUv+offset); + + offset=(vec2(0,-1))*texelSize; + vec4 cb=texture2D(tDiffuse,vUv+offset); + + offset=(vec2(0,1))*texelSize; + vec4 ct=texture2D(tDiffuse,vUv+offset); + + // float coeCenter=.5; + // float coeSide=.125; + float coeCenter=.2; + float coeSide=.2; + float a=c.a*coeCenter+cl.a*coeSide+cr.a*coeSide+cb.a*coeSide+ct.a*coeSide; + vec3 rgb=(c.rgb*c.a*coeCenter+cl.rgb*cl.a*coeSide+cr.rgb*cr.a*coeSide+cb.rgb*cb.a*coeSide+ct.rgb*ct.a*coeSide)/a; + gl_FragColor=vec4(rgb,a); + + } + ` +}; + +// node_modules/three/examples/jsm/postprocessing/SSRPass.js +class SSRPass extends Pass { + constructor({ renderer: renderer2, scene, camera, width: width2, height: height2, selects, bouncing = false, groundReflector }) { + super(); + this.width = width2 !== undefined ? width2 : 512; + this.height = height2 !== undefined ? height2 : 512; + this.clear = true; + this.renderer = renderer2; + this.scene = scene; + this.camera = camera; + this.groundReflector = groundReflector; + this.opacity = SSRShader.uniforms.opacity.value; + this.output = 0; + this.maxDistance = SSRShader.uniforms.maxDistance.value; + this.thickness = SSRShader.uniforms.thickness.value; + this.tempColor = new Color; + this._selects = selects; + this.selective = Array.isArray(this._selects); + Object.defineProperty(this, "selects", { + get() { + return this._selects; + }, + set(val2) { + if (this._selects === val2) + return; + this._selects = val2; + if (Array.isArray(val2)) { + this.selective = true; + this.ssrMaterial.defines.SELECTIVE = true; + this.ssrMaterial.needsUpdate = true; + } else { + this.selective = false; + this.ssrMaterial.defines.SELECTIVE = false; + this.ssrMaterial.needsUpdate = true; + } + } + }); + this._bouncing = bouncing; + Object.defineProperty(this, "bouncing", { + get() { + return this._bouncing; + }, + set(val2) { + if (this._bouncing === val2) + return; + this._bouncing = val2; + if (val2) { + this.ssrMaterial.uniforms["tDiffuse"].value = this.prevRenderTarget.texture; + } else { + this.ssrMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + } + } + }); + this.blur = true; + this._distanceAttenuation = SSRShader.defines.DISTANCE_ATTENUATION; + Object.defineProperty(this, "distanceAttenuation", { + get() { + return this._distanceAttenuation; + }, + set(val2) { + if (this._distanceAttenuation === val2) + return; + this._distanceAttenuation = val2; + this.ssrMaterial.defines.DISTANCE_ATTENUATION = val2; + this.ssrMaterial.needsUpdate = true; + } + }); + this._fresnel = SSRShader.defines.FRESNEL; + Object.defineProperty(this, "fresnel", { + get() { + return this._fresnel; + }, + set(val2) { + if (this._fresnel === val2) + return; + this._fresnel = val2; + this.ssrMaterial.defines.FRESNEL = val2; + this.ssrMaterial.needsUpdate = true; + } + }); + this._infiniteThick = SSRShader.defines.INFINITE_THICK; + Object.defineProperty(this, "infiniteThick", { + get() { + return this._infiniteThick; + }, + set(val2) { + if (this._infiniteThick === val2) + return; + this._infiniteThick = val2; + this.ssrMaterial.defines.INFINITE_THICK = val2; + this.ssrMaterial.needsUpdate = true; + } + }); + const depthTexture = new DepthTexture; + depthTexture.type = UnsignedShortType; + depthTexture.minFilter = NearestFilter; + depthTexture.magFilter = NearestFilter; + this.beautyRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType, + depthTexture, + depthBuffer: true + }); + this.prevRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter + }); + this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType + }); + this.metalnessRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType + }); + this.ssrRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter + }); + this.blurRenderTarget = this.ssrRenderTarget.clone(); + this.blurRenderTarget2 = this.ssrRenderTarget.clone(); + this.ssrMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSRShader.defines, { + MAX_STEP: Math.sqrt(this.width * this.width + this.height * this.height) + }), + uniforms: UniformsUtils.clone(SSRShader.uniforms), + vertexShader: SSRShader.vertexShader, + fragmentShader: SSRShader.fragmentShader, + blending: NoBlending + }); + this.ssrMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.ssrMaterial.uniforms["tNormal"].value = this.normalRenderTarget.texture; + this.ssrMaterial.defines.SELECTIVE = this.selective; + this.ssrMaterial.needsUpdate = true; + this.ssrMaterial.uniforms["tMetalness"].value = this.metalnessRenderTarget.texture; + this.ssrMaterial.uniforms["tDepth"].value = this.beautyRenderTarget.depthTexture; + this.ssrMaterial.uniforms["cameraNear"].value = this.camera.near; + this.ssrMaterial.uniforms["cameraFar"].value = this.camera.far; + this.ssrMaterial.uniforms["thickness"].value = this.thickness; + this.ssrMaterial.uniforms["resolution"].value.set(this.width, this.height); + this.ssrMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); + this.ssrMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.normalMaterial = new MeshNormalMaterial; + this.normalMaterial.blending = NoBlending; + this.metalnessOnMaterial = new MeshBasicMaterial({ + color: "white" + }); + this.metalnessOffMaterial = new MeshBasicMaterial({ + color: "black" + }); + this.blurMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSRBlurShader.defines), + uniforms: UniformsUtils.clone(SSRBlurShader.uniforms), + vertexShader: SSRBlurShader.vertexShader, + fragmentShader: SSRBlurShader.fragmentShader + }); + this.blurMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.blurMaterial.uniforms["resolution"].value.set(this.width, this.height); + this.blurMaterial2 = new ShaderMaterial({ + defines: Object.assign({}, SSRBlurShader.defines), + uniforms: UniformsUtils.clone(SSRBlurShader.uniforms), + vertexShader: SSRBlurShader.vertexShader, + fragmentShader: SSRBlurShader.fragmentShader + }); + this.blurMaterial2.uniforms["tDiffuse"].value = this.blurRenderTarget.texture; + this.blurMaterial2.uniforms["resolution"].value.set(this.width, this.height); + this.depthRenderMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSRDepthShader.defines), + uniforms: UniformsUtils.clone(SSRDepthShader.uniforms), + vertexShader: SSRDepthShader.vertexShader, + fragmentShader: SSRDepthShader.fragmentShader, + blending: NoBlending + }); + this.depthRenderMaterial.uniforms["tDepth"].value = this.beautyRenderTarget.depthTexture; + this.depthRenderMaterial.uniforms["cameraNear"].value = this.camera.near; + this.depthRenderMaterial.uniforms["cameraFar"].value = this.camera.far; + this.copyMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(CopyShader.uniforms), + vertexShader: CopyShader.vertexShader, + fragmentShader: CopyShader.fragmentShader, + transparent: true, + depthTest: false, + depthWrite: false, + blendSrc: SrcAlphaFactor, + blendDst: OneMinusSrcAlphaFactor, + blendEquation: AddEquation, + blendSrcAlpha: SrcAlphaFactor, + blendDstAlpha: OneMinusSrcAlphaFactor, + blendEquationAlpha: AddEquation + }); + this.fsQuad = new FullScreenQuad(null); + this.originalClearColor = new Color; + } + dispose() { + this.beautyRenderTarget.dispose(); + this.prevRenderTarget.dispose(); + this.normalRenderTarget.dispose(); + this.metalnessRenderTarget.dispose(); + this.ssrRenderTarget.dispose(); + this.blurRenderTarget.dispose(); + this.blurRenderTarget2.dispose(); + this.normalMaterial.dispose(); + this.metalnessOnMaterial.dispose(); + this.metalnessOffMaterial.dispose(); + this.blurMaterial.dispose(); + this.blurMaterial2.dispose(); + this.copyMaterial.dispose(); + this.depthRenderMaterial.dispose(); + this.fsQuad.dispose(); + } + render(renderer2, writeBuffer) { + renderer2.setRenderTarget(this.beautyRenderTarget); + renderer2.clear(); + if (this.groundReflector) { + this.groundReflector.visible = false; + this.groundReflector.doRender(this.renderer, this.scene, this.camera); + this.groundReflector.visible = true; + } + renderer2.render(this.scene, this.camera); + if (this.groundReflector) + this.groundReflector.visible = false; + this.renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 0, 0); + if (this.selective) { + this.renderMetalness(renderer2, this.metalnessOnMaterial, this.metalnessRenderTarget, 0, 0); + } + this.ssrMaterial.uniforms["opacity"].value = this.opacity; + this.ssrMaterial.uniforms["maxDistance"].value = this.maxDistance; + this.ssrMaterial.uniforms["thickness"].value = this.thickness; + this.renderPass(renderer2, this.ssrMaterial, this.ssrRenderTarget); + if (this.blur) { + this.renderPass(renderer2, this.blurMaterial, this.blurRenderTarget); + this.renderPass(renderer2, this.blurMaterial2, this.blurRenderTarget2); + } + switch (this.output) { + case SSRPass.OUTPUT.Default: + if (this.bouncing) { + this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.prevRenderTarget); + if (this.blur) + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture; + else + this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.copyMaterial.blending = NormalBlending; + this.renderPass(renderer2, this.copyMaterial, this.prevRenderTarget); + this.copyMaterial.uniforms["tDiffuse"].value = this.prevRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + } else { + this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + if (this.blur) + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture; + else + this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.copyMaterial.blending = NormalBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + } + break; + case SSRPass.OUTPUT.SSR: + if (this.blur) + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture; + else + this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + if (this.bouncing) { + if (this.blur) + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture; + else + this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.prevRenderTarget); + this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.copyMaterial.blending = NormalBlending; + this.renderPass(renderer2, this.copyMaterial, this.prevRenderTarget); + } + break; + case SSRPass.OUTPUT.Beauty: + this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case SSRPass.OUTPUT.Depth: + this.renderPass(renderer2, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer); + break; + case SSRPass.OUTPUT.Normal: + this.copyMaterial.uniforms["tDiffuse"].value = this.normalRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case SSRPass.OUTPUT.Metalness: + this.copyMaterial.uniforms["tDiffuse"].value = this.metalnessRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + default: + console.warn("THREE.SSRPass: Unknown output type."); + } + } + renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) { + this.originalClearColor.copy(renderer2.getClearColor(this.tempColor)); + const originalClearAlpha = renderer2.getClearAlpha(this.tempColor); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.fsQuad.material = passMaterial; + this.fsQuad.render(renderer2); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + this.originalClearColor.copy(renderer2.getClearColor(this.tempColor)); + const originalClearAlpha = renderer2.getClearAlpha(this.tempColor); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.overrideMaterial = overrideMaterial; + renderer2.render(this.scene, this.camera); + this.scene.overrideMaterial = null; + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderMetalness(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + this.originalClearColor.copy(renderer2.getClearColor(this.tempColor)); + const originalClearAlpha = renderer2.getClearAlpha(this.tempColor); + const originalAutoClear = renderer2.autoClear; + const originalBackground = this.scene.background; + const originalFog = this.scene.fog; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + this.scene.background = null; + this.scene.fog = null; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.traverseVisible((child) => { + child._SSRPassBackupMaterial = child.material; + if (this._selects.includes(child)) { + child.material = this.metalnessOnMaterial; + } else { + child.material = this.metalnessOffMaterial; + } + }); + renderer2.render(this.scene, this.camera); + this.scene.traverseVisible((child) => { + child.material = child._SSRPassBackupMaterial; + }); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + this.scene.background = originalBackground; + this.scene.fog = originalFog; + } + setSize(width2, height2) { + this.width = width2; + this.height = height2; + this.ssrMaterial.defines.MAX_STEP = Math.sqrt(width2 * width2 + height2 * height2); + this.ssrMaterial.needsUpdate = true; + this.beautyRenderTarget.setSize(width2, height2); + this.prevRenderTarget.setSize(width2, height2); + this.ssrRenderTarget.setSize(width2, height2); + this.normalRenderTarget.setSize(width2, height2); + this.metalnessRenderTarget.setSize(width2, height2); + this.blurRenderTarget.setSize(width2, height2); + this.blurRenderTarget2.setSize(width2, height2); + this.ssrMaterial.uniforms["resolution"].value.set(width2, height2); + this.ssrMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); + this.ssrMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.blurMaterial.uniforms["resolution"].value.set(width2, height2); + this.blurMaterial2.uniforms["resolution"].value.set(width2, height2); + } +} +SSRPass.OUTPUT = { + Default: 0, + SSR: 1, + Beauty: 3, + Depth: 4, + Normal: 5, + Metalness: 7 +}; +// node_modules/three/examples/jsm/shaders/LuminosityHighPassShader.js +var LuminosityHighPassShader = { + name: "LuminosityHighPassShader", + shaderID: "luminosityHighPass", + uniforms: { + tDiffuse: { value: null }, + luminosityThreshold: { value: 1 }, + smoothWidth: { value: 1 }, + defaultColor: { value: new Color(0) }, + defaultOpacity: { value: 0 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform vec3 defaultColor; + uniform float defaultOpacity; + uniform float luminosityThreshold; + uniform float smoothWidth; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + + float v = luminance( texel.xyz ); + + vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity ); + + float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v ); + + gl_FragColor = mix( outputColor, texel, alpha ); + + }` +}; + +// node_modules/three/examples/jsm/postprocessing/UnrealBloomPass.js +class UnrealBloomPass extends Pass { + constructor(resolution, strength, radius, threshold) { + super(); + this.strength = strength !== undefined ? strength : 1; + this.radius = radius; + this.threshold = threshold; + this.resolution = resolution !== undefined ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256); + this.clearColor = new Color(0, 0, 0); + this.renderTargetsHorizontal = []; + this.renderTargetsVertical = []; + this.nMips = 5; + let resx = Math.round(this.resolution.x / 2); + let resy = Math.round(this.resolution.y / 2); + this.renderTargetBright = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + this.renderTargetBright.texture.name = "UnrealBloomPass.bright"; + this.renderTargetBright.texture.generateMipmaps = false; + for (let i = 0;i < this.nMips; i++) { + const renderTargetHorizontal = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + renderTargetHorizontal.texture.name = "UnrealBloomPass.h" + i; + renderTargetHorizontal.texture.generateMipmaps = false; + this.renderTargetsHorizontal.push(renderTargetHorizontal); + const renderTargetVertical = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + renderTargetVertical.texture.name = "UnrealBloomPass.v" + i; + renderTargetVertical.texture.generateMipmaps = false; + this.renderTargetsVertical.push(renderTargetVertical); + resx = Math.round(resx / 2); + resy = Math.round(resy / 2); + } + const highPassShader = LuminosityHighPassShader; + this.highPassUniforms = UniformsUtils.clone(highPassShader.uniforms); + this.highPassUniforms["luminosityThreshold"].value = threshold; + this.highPassUniforms["smoothWidth"].value = 0.01; + this.materialHighPassFilter = new ShaderMaterial({ + uniforms: this.highPassUniforms, + vertexShader: highPassShader.vertexShader, + fragmentShader: highPassShader.fragmentShader + }); + this.separableBlurMaterials = []; + const kernelSizeArray = [3, 5, 7, 9, 11]; + resx = Math.round(this.resolution.x / 2); + resy = Math.round(this.resolution.y / 2); + for (let i = 0;i < this.nMips; i++) { + this.separableBlurMaterials.push(this.getSeparableBlurMaterial(kernelSizeArray[i])); + this.separableBlurMaterials[i].uniforms["invSize"].value = new Vector2(1 / resx, 1 / resy); + resx = Math.round(resx / 2); + resy = Math.round(resy / 2); + } + this.compositeMaterial = this.getCompositeMaterial(this.nMips); + this.compositeMaterial.uniforms["blurTexture1"].value = this.renderTargetsVertical[0].texture; + this.compositeMaterial.uniforms["blurTexture2"].value = this.renderTargetsVertical[1].texture; + this.compositeMaterial.uniforms["blurTexture3"].value = this.renderTargetsVertical[2].texture; + this.compositeMaterial.uniforms["blurTexture4"].value = this.renderTargetsVertical[3].texture; + this.compositeMaterial.uniforms["blurTexture5"].value = this.renderTargetsVertical[4].texture; + this.compositeMaterial.uniforms["bloomStrength"].value = strength; + this.compositeMaterial.uniforms["bloomRadius"].value = 0.1; + const bloomFactors = [1, 0.8, 0.6, 0.4, 0.2]; + this.compositeMaterial.uniforms["bloomFactors"].value = bloomFactors; + this.bloomTintColors = [new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1)]; + this.compositeMaterial.uniforms["bloomTintColors"].value = this.bloomTintColors; + const copyShader = CopyShader; + this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); + this.blendMaterial = new ShaderMaterial({ + uniforms: this.copyUniforms, + vertexShader: copyShader.vertexShader, + fragmentShader: copyShader.fragmentShader, + blending: AdditiveBlending, + depthTest: false, + depthWrite: false, + transparent: true + }); + this.enabled = true; + this.needsSwap = false; + this._oldClearColor = new Color; + this.oldClearAlpha = 1; + this.basic = new MeshBasicMaterial; + this.fsQuad = new FullScreenQuad(null); + } + dispose() { + for (let i = 0;i < this.renderTargetsHorizontal.length; i++) { + this.renderTargetsHorizontal[i].dispose(); + } + for (let i = 0;i < this.renderTargetsVertical.length; i++) { + this.renderTargetsVertical[i].dispose(); + } + this.renderTargetBright.dispose(); + for (let i = 0;i < this.separableBlurMaterials.length; i++) { + this.separableBlurMaterials[i].dispose(); + } + this.compositeMaterial.dispose(); + this.blendMaterial.dispose(); + this.basic.dispose(); + this.fsQuad.dispose(); + } + setSize(width2, height2) { + let resx = Math.round(width2 / 2); + let resy = Math.round(height2 / 2); + this.renderTargetBright.setSize(resx, resy); + for (let i = 0;i < this.nMips; i++) { + this.renderTargetsHorizontal[i].setSize(resx, resy); + this.renderTargetsVertical[i].setSize(resx, resy); + this.separableBlurMaterials[i].uniforms["invSize"].value = new Vector2(1 / resx, 1 / resy); + resx = Math.round(resx / 2); + resy = Math.round(resy / 2); + } + } + render(renderer2, writeBuffer, readBuffer, deltaTime, maskActive) { + renderer2.getClearColor(this._oldClearColor); + this.oldClearAlpha = renderer2.getClearAlpha(); + const oldAutoClear = renderer2.autoClear; + renderer2.autoClear = false; + renderer2.setClearColor(this.clearColor, 0); + if (maskActive) + renderer2.state.buffers.stencil.setTest(false); + if (this.renderToScreen) { + this.fsQuad.material = this.basic; + this.basic.map = readBuffer.texture; + renderer2.setRenderTarget(null); + renderer2.clear(); + this.fsQuad.render(renderer2); + } + this.highPassUniforms["tDiffuse"].value = readBuffer.texture; + this.highPassUniforms["luminosityThreshold"].value = this.threshold; + this.fsQuad.material = this.materialHighPassFilter; + renderer2.setRenderTarget(this.renderTargetBright); + renderer2.clear(); + this.fsQuad.render(renderer2); + let inputRenderTarget = this.renderTargetBright; + for (let i = 0;i < this.nMips; i++) { + this.fsQuad.material = this.separableBlurMaterials[i]; + this.separableBlurMaterials[i].uniforms["colorTexture"].value = inputRenderTarget.texture; + this.separableBlurMaterials[i].uniforms["direction"].value = UnrealBloomPass.BlurDirectionX; + renderer2.setRenderTarget(this.renderTargetsHorizontal[i]); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.separableBlurMaterials[i].uniforms["colorTexture"].value = this.renderTargetsHorizontal[i].texture; + this.separableBlurMaterials[i].uniforms["direction"].value = UnrealBloomPass.BlurDirectionY; + renderer2.setRenderTarget(this.renderTargetsVertical[i]); + renderer2.clear(); + this.fsQuad.render(renderer2); + inputRenderTarget = this.renderTargetsVertical[i]; + } + this.fsQuad.material = this.compositeMaterial; + this.compositeMaterial.uniforms["bloomStrength"].value = this.strength; + this.compositeMaterial.uniforms["bloomRadius"].value = this.radius; + this.compositeMaterial.uniforms["bloomTintColors"].value = this.bloomTintColors; + renderer2.setRenderTarget(this.renderTargetsHorizontal[0]); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.blendMaterial; + this.copyUniforms["tDiffuse"].value = this.renderTargetsHorizontal[0].texture; + if (maskActive) + renderer2.state.buffers.stencil.setTest(true); + if (this.renderToScreen) { + renderer2.setRenderTarget(null); + this.fsQuad.render(renderer2); + } else { + renderer2.setRenderTarget(readBuffer); + this.fsQuad.render(renderer2); + } + renderer2.setClearColor(this._oldClearColor, this.oldClearAlpha); + renderer2.autoClear = oldAutoClear; + } + getSeparableBlurMaterial(kernelRadius) { + const coefficients = []; + for (let i = 0;i < kernelRadius; i++) { + coefficients.push(0.39894 * Math.exp(-0.5 * i * i / (kernelRadius * kernelRadius)) / kernelRadius); + } + return new ShaderMaterial({ + defines: { + KERNEL_RADIUS: kernelRadius + }, + uniforms: { + colorTexture: { value: null }, + invSize: { value: new Vector2(0.5, 0.5) }, + direction: { value: new Vector2(0.5, 0.5) }, + gaussianCoefficients: { value: coefficients } + }, + vertexShader: `varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `#include + varying vec2 vUv; + uniform sampler2D colorTexture; + uniform vec2 invSize; + uniform vec2 direction; + uniform float gaussianCoefficients[KERNEL_RADIUS]; + + void main() { + float weightSum = gaussianCoefficients[0]; + vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum; + for( int i = 1; i < KERNEL_RADIUS; i ++ ) { + float x = float(i); + float w = gaussianCoefficients[i]; + vec2 uvOffset = direction * invSize * x; + vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb; + vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb; + diffuseSum += (sample1 + sample2) * w; + weightSum += 2.0 * w; + } + gl_FragColor = vec4(diffuseSum/weightSum, 1.0); + }` + }); + } + getCompositeMaterial(nMips) { + return new ShaderMaterial({ + defines: { + NUM_MIPS: nMips + }, + uniforms: { + blurTexture1: { value: null }, + blurTexture2: { value: null }, + blurTexture3: { value: null }, + blurTexture4: { value: null }, + blurTexture5: { value: null }, + bloomStrength: { value: 1 }, + bloomFactors: { value: null }, + bloomTintColors: { value: null }, + bloomRadius: { value: 0 } + }, + vertexShader: `varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `varying vec2 vUv; + uniform sampler2D blurTexture1; + uniform sampler2D blurTexture2; + uniform sampler2D blurTexture3; + uniform sampler2D blurTexture4; + uniform sampler2D blurTexture5; + uniform float bloomStrength; + uniform float bloomRadius; + uniform float bloomFactors[NUM_MIPS]; + uniform vec3 bloomTintColors[NUM_MIPS]; + + float lerpBloomFactor(const in float factor) { + float mirrorFactor = 1.2 - factor; + return mix(factor, mirrorFactor, bloomRadius); + } + + void main() { + gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + + lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + + lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + + lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + + lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) ); + }` + }); + } +} +UnrealBloomPass.BlurDirectionX = new Vector2(1, 0); +UnrealBloomPass.BlurDirectionY = new Vector2(0, 1); +// node_modules/three/examples/jsm/renderers/CSS2DRenderer.js +var _vector8 = new Vector3; +var _viewMatrix = new Matrix4; +var _viewProjectionMatrix = new Matrix4; +var _a2 = new Vector3; +var _b2 = new Vector3; +// node_modules/three/examples/jsm/renderers/CSS3DRenderer.js +var _position2 = new Vector3; +var _quaternion4 = new Quaternion; +var _scale4 = new Vector3; +var _matrix5 = new Matrix4; +var _matrix22 = new Matrix4; +// node_modules/three/examples/jsm/shaders/BokehShader2.js +var BokehShader2 = { + name: "BokehShader", + uniforms: { + textureWidth: { value: 1 }, + textureHeight: { value: 1 }, + focalDepth: { value: 1 }, + focalLength: { value: 24 }, + fstop: { value: 0.9 }, + tColor: { value: null }, + tDepth: { value: null }, + maxblur: { value: 1 }, + showFocus: { value: 0 }, + manualdof: { value: 0 }, + vignetting: { value: 0 }, + depthblur: { value: 0 }, + threshold: { value: 0.5 }, + gain: { value: 2 }, + bias: { value: 0.5 }, + fringe: { value: 0.7 }, + znear: { value: 0.1 }, + zfar: { value: 100 }, + noise: { value: 1 }, + dithering: { value: 0.0001 }, + pentagon: { value: 0 }, + shaderFocus: { value: 1 }, + focusCoords: { value: new Vector2 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + #include + + varying vec2 vUv; + + uniform sampler2D tColor; + uniform sampler2D tDepth; + uniform float textureWidth; + uniform float textureHeight; + + uniform float focalDepth; //focal distance value in meters, but you may use autofocus option below + uniform float focalLength; //focal length in mm + uniform float fstop; //f-stop value + uniform bool showFocus; //show debug focus point and focal range (red = focal point, green = focal range) + + /* + make sure that these two values are the same for your camera, otherwise distances will be wrong. + */ + + uniform float znear; // camera clipping start + uniform float zfar; // camera clipping end + + //------------------------------------------ + //user variables + + const int samples = SAMPLES; //samples on the first ring + const int rings = RINGS; //ring count + + const int maxringsamples = rings * samples; + + uniform bool manualdof; // manual dof calculation + float ndofstart = 1.0; // near dof blur start + float ndofdist = 2.0; // near dof blur falloff distance + float fdofstart = 1.0; // far dof blur start + float fdofdist = 3.0; // far dof blur falloff distance + + float CoC = 0.03; //circle of confusion size in mm (35mm film = 0.03mm) + + uniform bool vignetting; // use optical lens vignetting + + float vignout = 1.3; // vignetting outer border + float vignin = 0.0; // vignetting inner border + float vignfade = 22.0; // f-stops till vignette fades + + uniform bool shaderFocus; + // disable if you use external focalDepth value + + uniform vec2 focusCoords; + // autofocus point on screen (0.0,0.0 - left lower corner, 1.0,1.0 - upper right) + // if center of screen use vec2(0.5, 0.5); + + uniform float maxblur; + //clamp value of max blur (0.0 = no blur, 1.0 default) + + uniform float threshold; // highlight threshold; + uniform float gain; // highlight gain; + + uniform float bias; // bokeh edge bias + uniform float fringe; // bokeh chromatic aberration / fringing + + uniform bool noise; //use noise instead of pattern for sample dithering + + uniform float dithering; + + uniform bool depthblur; // blur the depth buffer + float dbsize = 1.25; // depth blur size + + /* + next part is experimental + not looking good with small sample and ring count + looks okay starting from samples = 4, rings = 4 + */ + + uniform bool pentagon; //use pentagon as bokeh shape? + float feather = 0.4; //pentagon shape feather + + //------------------------------------------ + + float penta(vec2 coords) { + //pentagonal shape + float scale = float(rings) - 1.3; + vec4 HS0 = vec4( 1.0, 0.0, 0.0, 1.0); + vec4 HS1 = vec4( 0.309016994, 0.951056516, 0.0, 1.0); + vec4 HS2 = vec4(-0.809016994, 0.587785252, 0.0, 1.0); + vec4 HS3 = vec4(-0.809016994,-0.587785252, 0.0, 1.0); + vec4 HS4 = vec4( 0.309016994,-0.951056516, 0.0, 1.0); + vec4 HS5 = vec4( 0.0 ,0.0 , 1.0, 1.0); + + vec4 one = vec4( 1.0 ); + + vec4 P = vec4((coords),vec2(scale, scale)); + + vec4 dist = vec4(0.0); + float inorout = -4.0; + + dist.x = dot( P, HS0 ); + dist.y = dot( P, HS1 ); + dist.z = dot( P, HS2 ); + dist.w = dot( P, HS3 ); + + dist = smoothstep( -feather, feather, dist ); + + inorout += dot( dist, one ); + + dist.x = dot( P, HS4 ); + dist.y = HS5.w - abs( P.z ); + + dist = smoothstep( -feather, feather, dist ); + inorout += dist.x; + + return clamp( inorout, 0.0, 1.0 ); + } + + float bdepth(vec2 coords) { + // Depth buffer blur + float d = 0.0; + float kernel[9]; + vec2 offset[9]; + + vec2 wh = vec2(1.0/textureWidth,1.0/textureHeight) * dbsize; + + offset[0] = vec2(-wh.x,-wh.y); + offset[1] = vec2( 0.0, -wh.y); + offset[2] = vec2( wh.x -wh.y); + + offset[3] = vec2(-wh.x, 0.0); + offset[4] = vec2( 0.0, 0.0); + offset[5] = vec2( wh.x, 0.0); + + offset[6] = vec2(-wh.x, wh.y); + offset[7] = vec2( 0.0, wh.y); + offset[8] = vec2( wh.x, wh.y); + + kernel[0] = 1.0/16.0; kernel[1] = 2.0/16.0; kernel[2] = 1.0/16.0; + kernel[3] = 2.0/16.0; kernel[4] = 4.0/16.0; kernel[5] = 2.0/16.0; + kernel[6] = 1.0/16.0; kernel[7] = 2.0/16.0; kernel[8] = 1.0/16.0; + + + for( int i=0; i<9; i++ ) { + float tmp = texture2D(tDepth, coords + offset[i]).r; + d += tmp * kernel[i]; + } + + return d; + } + + + vec3 color(vec2 coords,float blur) { + //processing the sample + + vec3 col = vec3(0.0); + vec2 texel = vec2(1.0/textureWidth,1.0/textureHeight); + + col.r = texture2D(tColor,coords + vec2(0.0,1.0)*texel*fringe*blur).r; + col.g = texture2D(tColor,coords + vec2(-0.866,-0.5)*texel*fringe*blur).g; + col.b = texture2D(tColor,coords + vec2(0.866,-0.5)*texel*fringe*blur).b; + + vec3 lumcoeff = vec3(0.299,0.587,0.114); + float lum = dot(col.rgb, lumcoeff); + float thresh = max((lum-threshold)*gain, 0.0); + return col+mix(vec3(0.0),col,thresh*blur); + } + + vec3 debugFocus(vec3 col, float blur, float depth) { + float edge = 0.002*depth; //distance based edge smoothing + float m = clamp(smoothstep(0.0,edge,blur),0.0,1.0); + float e = clamp(smoothstep(1.0-edge,1.0,blur),0.0,1.0); + + col = mix(col,vec3(1.0,0.5,0.0),(1.0-m)*0.6); + col = mix(col,vec3(0.0,0.5,1.0),((1.0-e)-(1.0-m))*0.2); + + return col; + } + + float linearize(float depth) { + return -zfar * znear / (depth * (zfar - znear) - zfar); + } + + float vignette() { + float dist = distance(vUv.xy, vec2(0.5,0.5)); + dist = smoothstep(vignout+(fstop/vignfade), vignin+(fstop/vignfade), dist); + return clamp(dist,0.0,1.0); + } + + float gather(float i, float j, int ringsamples, inout vec3 col, float w, float h, float blur) { + float rings2 = float(rings); + float step = PI*2.0 / float(ringsamples); + float pw = cos(j*step)*i; + float ph = sin(j*step)*i; + float p = 1.0; + if (pentagon) { + p = penta(vec2(pw,ph)); + } + col += color(vUv.xy + vec2(pw*w,ph*h), blur) * mix(1.0, i/rings2, bias) * p; + return 1.0 * mix(1.0, i /rings2, bias) * p; + } + + void main() { + //scene depth calculation + + float depth = linearize(texture2D(tDepth,vUv.xy).x); + + // Blur depth? + if ( depthblur ) { + depth = linearize(bdepth(vUv.xy)); + } + + //focal plane calculation + + float fDepth = focalDepth; + + if (shaderFocus) { + + fDepth = linearize(texture2D(tDepth,focusCoords).x); + + } + + // dof blur factor calculation + + float blur = 0.0; + + if (manualdof) { + float a = depth-fDepth; // Focal plane + float b = (a-fdofstart)/fdofdist; // Far DoF + float c = (-a-ndofstart)/ndofdist; // Near Dof + blur = (a>0.0) ? b : c; + } else { + float f = focalLength; // focal length in mm + float d = fDepth*1000.0; // focal plane in mm + float o = depth*1000.0; // depth in mm + + float a = (o*f)/(o-f); + float b = (d*f)/(d-f); + float c = (d-f)/(d*fstop*CoC); + + blur = abs(a-b)*c; + } + + blur = clamp(blur,0.0,1.0); + + // calculation of pattern for dithering + + vec2 noise = vec2(rand(vUv.xy), rand( vUv.xy + vec2( 0.4, 0.6 ) ) )*dithering*blur; + + // getting blur x and y step factor + + float w = (1.0/textureWidth)*blur*maxblur+noise.x; + float h = (1.0/textureHeight)*blur*maxblur+noise.y; + + // calculation of final color + + vec3 col = vec3(0.0); + + if(blur < 0.05) { + //some optimization thingy + col = texture2D(tColor, vUv.xy).rgb; + } else { + col = texture2D(tColor, vUv.xy).rgb; + float s = 1.0; + int ringsamples; + + for (int i = 1; i <= rings; i++) { + /*unboxstart*/ + ringsamples = i * samples; + + for (int j = 0 ; j < maxringsamples ; j++) { + if (j >= ringsamples) break; + s += gather(float(i), float(j), ringsamples, col, w, h, blur); + } + /*unboxend*/ + } + + col /= s; //divide by sample count + } + + if (showFocus) { + col = debugFocus(col, blur, depth); + } + + if (vignetting) { + col *= vignette(); + } + + gl_FragColor.rgb = col; + gl_FragColor.a = 1.0; + + #include + #include + }` +}; +// node_modules/three/examples/jsm/shaders/ColorCorrectionShader.js +var ColorCorrectionShader = { + name: "ColorCorrectionShader", + uniforms: { + tDiffuse: { value: null }, + powRGB: { value: new Vector3(2, 2, 2) }, + mulRGB: { value: new Vector3(1, 1, 1) }, + addRGB: { value: new Vector3(0, 0, 0) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform vec3 powRGB; + uniform vec3 mulRGB; + uniform vec3 addRGB; + + varying vec2 vUv; + + void main() { + + gl_FragColor = texture2D( tDiffuse, vUv ); + gl_FragColor.rgb = mulRGB * pow( ( gl_FragColor.rgb + addRGB ), powRGB ); + + }` +}; +// node_modules/three/examples/jsm/shaders/ColorifyShader.js +var ColorifyShader = { + name: "ColorifyShader", + uniforms: { + tDiffuse: { value: null }, + color: { value: new Color(16777215) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform vec3 color; + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + + float v = luminance( texel.xyz ); + + gl_FragColor = vec4( v * color, texel.w ); + + }` +}; +// node_modules/three/examples/jsm/shaders/FXAAShader.js +var FXAAShader = { + name: "FXAAShader", + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2(1 / 1024, 1 / 512) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + // FXAA algorithm from NVIDIA, C# implementation by Jasper Flick, GLSL port by Dave Hoskins + // http://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf + // https://catlikecoding.com/unity/tutorials/advanced-rendering/fxaa/ + + uniform sampler2D tDiffuse; + uniform vec2 resolution; + varying vec2 vUv; + + #define EDGE_STEP_COUNT 6 + #define EDGE_GUESS 8.0 + #define EDGE_STEPS 1.0, 1.5, 2.0, 2.0, 2.0, 4.0 + const float edgeSteps[EDGE_STEP_COUNT] = float[EDGE_STEP_COUNT]( EDGE_STEPS ); + + float _ContrastThreshold = 0.0312; + float _RelativeThreshold = 0.063; + float _SubpixelBlending = 1.0; + + vec4 Sample( sampler2D tex2D, vec2 uv ) { + + return texture( tex2D, uv ); + + } + + float SampleLuminance( sampler2D tex2D, vec2 uv ) { + + return dot( Sample( tex2D, uv ).rgb, vec3( 0.3, 0.59, 0.11 ) ); + + } + + float SampleLuminance( sampler2D tex2D, vec2 texSize, vec2 uv, float uOffset, float vOffset ) { + + uv += texSize * vec2(uOffset, vOffset); + return SampleLuminance(tex2D, uv); + + } + + struct LuminanceData { + + float m, n, e, s, w; + float ne, nw, se, sw; + float highest, lowest, contrast; + + }; + + LuminanceData SampleLuminanceNeighborhood( sampler2D tex2D, vec2 texSize, vec2 uv ) { + + LuminanceData l; + l.m = SampleLuminance( tex2D, uv ); + l.n = SampleLuminance( tex2D, texSize, uv, 0.0, 1.0 ); + l.e = SampleLuminance( tex2D, texSize, uv, 1.0, 0.0 ); + l.s = SampleLuminance( tex2D, texSize, uv, 0.0, -1.0 ); + l.w = SampleLuminance( tex2D, texSize, uv, -1.0, 0.0 ); + + l.ne = SampleLuminance( tex2D, texSize, uv, 1.0, 1.0 ); + l.nw = SampleLuminance( tex2D, texSize, uv, -1.0, 1.0 ); + l.se = SampleLuminance( tex2D, texSize, uv, 1.0, -1.0 ); + l.sw = SampleLuminance( tex2D, texSize, uv, -1.0, -1.0 ); + + l.highest = max( max( max( max( l.n, l.e ), l.s ), l.w ), l.m ); + l.lowest = min( min( min( min( l.n, l.e ), l.s ), l.w ), l.m ); + l.contrast = l.highest - l.lowest; + return l; + + } + + bool ShouldSkipPixel( LuminanceData l ) { + + float threshold = max( _ContrastThreshold, _RelativeThreshold * l.highest ); + return l.contrast < threshold; + + } + + float DeterminePixelBlendFactor( LuminanceData l ) { + + float f = 2.0 * ( l.n + l.e + l.s + l.w ); + f += l.ne + l.nw + l.se + l.sw; + f *= 1.0 / 12.0; + f = abs( f - l.m ); + f = clamp( f / l.contrast, 0.0, 1.0 ); + + float blendFactor = smoothstep( 0.0, 1.0, f ); + return blendFactor * blendFactor * _SubpixelBlending; + + } + + struct EdgeData { + + bool isHorizontal; + float pixelStep; + float oppositeLuminance, gradient; + + }; + + EdgeData DetermineEdge( vec2 texSize, LuminanceData l ) { + + EdgeData e; + float horizontal = + abs( l.n + l.s - 2.0 * l.m ) * 2.0 + + abs( l.ne + l.se - 2.0 * l.e ) + + abs( l.nw + l.sw - 2.0 * l.w ); + float vertical = + abs( l.e + l.w - 2.0 * l.m ) * 2.0 + + abs( l.ne + l.nw - 2.0 * l.n ) + + abs( l.se + l.sw - 2.0 * l.s ); + e.isHorizontal = horizontal >= vertical; + + float pLuminance = e.isHorizontal ? l.n : l.e; + float nLuminance = e.isHorizontal ? l.s : l.w; + float pGradient = abs( pLuminance - l.m ); + float nGradient = abs( nLuminance - l.m ); + + e.pixelStep = e.isHorizontal ? texSize.y : texSize.x; + + if (pGradient < nGradient) { + + e.pixelStep = -e.pixelStep; + e.oppositeLuminance = nLuminance; + e.gradient = nGradient; + + } else { + + e.oppositeLuminance = pLuminance; + e.gradient = pGradient; + + } + + return e; + + } + + float DetermineEdgeBlendFactor( sampler2D tex2D, vec2 texSize, LuminanceData l, EdgeData e, vec2 uv ) { + + vec2 uvEdge = uv; + vec2 edgeStep; + if (e.isHorizontal) { + + uvEdge.y += e.pixelStep * 0.5; + edgeStep = vec2( texSize.x, 0.0 ); + + } else { + + uvEdge.x += e.pixelStep * 0.5; + edgeStep = vec2( 0.0, texSize.y ); + + } + + float edgeLuminance = ( l.m + e.oppositeLuminance ) * 0.5; + float gradientThreshold = e.gradient * 0.25; + + vec2 puv = uvEdge + edgeStep * edgeSteps[0]; + float pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; + bool pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; + + for ( int i = 1; i < EDGE_STEP_COUNT && !pAtEnd; i++ ) { + + puv += edgeStep * edgeSteps[i]; + pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; + pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; + + } + + if ( !pAtEnd ) { + + puv += edgeStep * EDGE_GUESS; + + } + + vec2 nuv = uvEdge - edgeStep * edgeSteps[0]; + float nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; + bool nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; + + for ( int i = 1; i < EDGE_STEP_COUNT && !nAtEnd; i++ ) { + + nuv -= edgeStep * edgeSteps[i]; + nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; + nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; + + } + + if ( !nAtEnd ) { + + nuv -= edgeStep * EDGE_GUESS; + + } + + float pDistance, nDistance; + if ( e.isHorizontal ) { + + pDistance = puv.x - uv.x; + nDistance = uv.x - nuv.x; + + } else { + + pDistance = puv.y - uv.y; + nDistance = uv.y - nuv.y; + + } + + float shortestDistance; + bool deltaSign; + if ( pDistance <= nDistance ) { + + shortestDistance = pDistance; + deltaSign = pLuminanceDelta >= 0.0; + + } else { + + shortestDistance = nDistance; + deltaSign = nLuminanceDelta >= 0.0; + + } + + if ( deltaSign == ( l.m - edgeLuminance >= 0.0 ) ) { + + return 0.0; + + } + + return 0.5 - shortestDistance / ( pDistance + nDistance ); + + } + + vec4 ApplyFXAA( sampler2D tex2D, vec2 texSize, vec2 uv ) { + + LuminanceData luminance = SampleLuminanceNeighborhood( tex2D, texSize, uv ); + if ( ShouldSkipPixel( luminance ) ) { + + return Sample( tex2D, uv ); + + } + + float pixelBlend = DeterminePixelBlendFactor( luminance ); + EdgeData edge = DetermineEdge( texSize, luminance ); + float edgeBlend = DetermineEdgeBlendFactor( tex2D, texSize, luminance, edge, uv ); + float finalBlend = max( pixelBlend, edgeBlend ); + + if (edge.isHorizontal) { + + uv.y += edge.pixelStep * finalBlend; + + } else { + + uv.x += edge.pixelStep * finalBlend; + + } + + return Sample( tex2D, uv ); + + } + + void main() { + + gl_FragColor = ApplyFXAA( tDiffuse, resolution.xy, vUv ); + + }` +}; +// node_modules/three/examples/jsm/shaders/FreiChenShader.js +var FreiChenShader = { + name: "FreiChenShader", + uniforms: { + tDiffuse: { value: null }, + aspect: { value: new Vector2(512, 512) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + varying vec2 vUv; + + uniform vec2 aspect; + + vec2 texel = vec2( 1.0 / aspect.x, 1.0 / aspect.y ); + + + mat3 G[9]; + + // hard coded matrix values!!!! as suggested in https://github.com/neilmendoza/ofxPostProcessing/blob/master/src/EdgePass.cpp#L45 + + const mat3 g0 = mat3( 0.3535533845424652, 0, -0.3535533845424652, 0.5, 0, -0.5, 0.3535533845424652, 0, -0.3535533845424652 ); + const mat3 g1 = mat3( 0.3535533845424652, 0.5, 0.3535533845424652, 0, 0, 0, -0.3535533845424652, -0.5, -0.3535533845424652 ); + const mat3 g2 = mat3( 0, 0.3535533845424652, -0.5, -0.3535533845424652, 0, 0.3535533845424652, 0.5, -0.3535533845424652, 0 ); + const mat3 g3 = mat3( 0.5, -0.3535533845424652, 0, -0.3535533845424652, 0, 0.3535533845424652, 0, 0.3535533845424652, -0.5 ); + const mat3 g4 = mat3( 0, -0.5, 0, 0.5, 0, 0.5, 0, -0.5, 0 ); + const mat3 g5 = mat3( -0.5, 0, 0.5, 0, 0, 0, 0.5, 0, -0.5 ); + const mat3 g6 = mat3( 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.6666666865348816, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204 ); + const mat3 g7 = mat3( -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, 0.6666666865348816, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408 ); + const mat3 g8 = mat3( 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408 ); + + void main(void) + { + + G[0] = g0, + G[1] = g1, + G[2] = g2, + G[3] = g3, + G[4] = g4, + G[5] = g5, + G[6] = g6, + G[7] = g7, + G[8] = g8; + + mat3 I; + float cnv[9]; + vec3 sample; + + /* fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */ + for (float i=0.0; i<3.0; i++) { + for (float j=0.0; j<3.0; j++) { + sample = texture2D(tDiffuse, vUv + texel * vec2(i-1.0,j-1.0) ).rgb; + I[int(i)][int(j)] = length(sample); + } + } + + /* calculate the convolution values for all the masks */ + for (int i=0; i<9; i++) { + float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]); + cnv[i] = dp3 * dp3; + } + + float M = (cnv[0] + cnv[1]) + (cnv[2] + cnv[3]); + float S = (cnv[4] + cnv[5]) + (cnv[6] + cnv[7]) + (cnv[8] + M); + + gl_FragColor = vec4(vec3(sqrt(M/S)), 1.0); + }` +}; +// node_modules/three/examples/jsm/shaders/GodRaysShader.js +var GodRaysGenerateShader = { + name: "GodRaysGenerateShader", + uniforms: { + tInput: { + value: null + }, + fStepSize: { + value: 1 + }, + vSunPositionScreenSpace: { + value: new Vector3 + } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + #define TAPS_PER_PASS 6.0 + + varying vec2 vUv; + + uniform sampler2D tInput; + + uniform vec3 vSunPositionScreenSpace; + uniform float fStepSize; // filter step size + + void main() { + + // delta from current pixel to "sun" position + + vec2 delta = vSunPositionScreenSpace.xy - vUv; + float dist = length( delta ); + + // Step vector (uv space) + + vec2 stepv = fStepSize * delta / dist; + + // Number of iterations between pixel and sun + + float iters = dist/fStepSize; + + vec2 uv = vUv.xy; + float col = 0.0; + + // This breaks ANGLE in Chrome 22 + // - see http://code.google.com/p/chromium/issues/detail?id=153105 + + /* + // Unrolling didn't do much on my hardware (ATI Mobility Radeon 3450), + // so i've just left the loop + + "for ( float i = 0.0; i < TAPS_PER_PASS; i += 1.0 ) {", + + // Accumulate samples, making sure we don't walk past the light source. + + // The check for uv.y < 1 would not be necessary with "border" UV wrap + // mode, with a black border color. I don't think this is currently + // exposed by three.js. As a result there might be artifacts when the + // sun is to the left, right or bottom of screen as these cases are + // not specifically handled. + + " col += ( i <= iters && uv.y < 1.0 ? texture2D( tInput, uv ).r : 0.0 );", + " uv += stepv;", + + "}", + */ + + // Unrolling loop manually makes it work in ANGLE + + float f = min( 1.0, max( vSunPositionScreenSpace.z / 1000.0, 0.0 ) ); // used to fade out godrays + + if ( 0.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 1.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 2.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 3.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 4.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 5.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + // Should technically be dividing by 'iters but 'TAPS_PER_PASS' smooths out + // objectionable artifacts, in particular near the sun position. The side + // effect is that the result is darker than it should be around the sun, as + // TAPS_PER_PASS is greater than the number of samples actually accumulated. + // When the result is inverted (in the shader 'godrays_combine this produces + // a slight bright spot at the position of the sun, even when it is occluded. + + gl_FragColor = vec4( col/TAPS_PER_PASS ); + gl_FragColor.a = 1.0; + + }` +}; +var GodRaysFakeSunShader = { + name: "GodRaysFakeSunShader", + uniforms: { + vSunPositionScreenSpace: { + value: new Vector3 + }, + fAspect: { + value: 1 + }, + sunColor: { + value: new Color(16772608) + }, + bgColor: { + value: new Color(0) + } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + varying vec2 vUv; + + uniform vec3 vSunPositionScreenSpace; + uniform float fAspect; + + uniform vec3 sunColor; + uniform vec3 bgColor; + + void main() { + + vec2 diff = vUv - vSunPositionScreenSpace.xy; + + // Correct for aspect ratio + + diff.x *= fAspect; + + float prop = clamp( length( diff ) / 0.5, 0.0, 1.0 ); + prop = 0.35 * pow( 1.0 - prop, 3.0 ); + + gl_FragColor.xyz = ( vSunPositionScreenSpace.z > 0.0 ) ? mix( sunColor, bgColor, 1.0 - prop ) : bgColor; + gl_FragColor.w = 1.0; + + }` +}; +// node_modules/three/examples/jsm/shaders/HorizontalBlurShader.js +var HorizontalBlurShader = { + name: "HorizontalBlurShader", + uniforms: { + tDiffuse: { value: null }, + h: { value: 1 / 512 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform float h; + + varying vec2 vUv; + + void main() { + + vec4 sum = vec4( 0.0 ); + + sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ) * 0.051; + sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; + sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ) * 0.051; + + gl_FragColor = sum; + + }` +}; +// node_modules/three/examples/jsm/shaders/HorizontalTiltShiftShader.js +var HorizontalTiltShiftShader = { + name: "HorizontalTiltShiftShader", + uniforms: { + tDiffuse: { value: null }, + h: { value: 1 / 512 }, + r: { value: 0.35 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform float h; + uniform float r; + + varying vec2 vUv; + + void main() { + + vec4 sum = vec4( 0.0 ); + + float hh = h * abs( r - vUv.y ); + + sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * hh, vUv.y ) ) * 0.051; + sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * hh, vUv.y ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * hh, vUv.y ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * hh, vUv.y ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; + sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * hh, vUv.y ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * hh, vUv.y ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * hh, vUv.y ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * hh, vUv.y ) ) * 0.051; + + gl_FragColor = sum; + + }` +}; +// node_modules/three/examples/jsm/shaders/NormalMapShader.js +var NormalMapShader = { + name: "NormalMapShader", + uniforms: { + heightMap: { value: null }, + resolution: { value: new Vector2(512, 512) }, + scale: { value: new Vector2(1, 1) }, + height: { value: 0.05 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform float height; + uniform vec2 resolution; + uniform sampler2D heightMap; + + varying vec2 vUv; + + void main() { + + float val = texture2D( heightMap, vUv ).x; + + float valU = texture2D( heightMap, vUv + vec2( 1.0 / resolution.x, 0.0 ) ).x; + float valV = texture2D( heightMap, vUv + vec2( 0.0, 1.0 / resolution.y ) ).x; + + gl_FragColor = vec4( ( 0.5 * normalize( vec3( val - valU, val - valV, height ) ) + 0.5 ), 1.0 ); + + }` +}; +// node_modules/three/examples/jsm/shaders/SobelOperatorShader.js +var SobelOperatorShader = { + name: "SobelOperatorShader", + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform vec2 resolution; + varying vec2 vUv; + + void main() { + + vec2 texel = vec2( 1.0 / resolution.x, 1.0 / resolution.y ); + + // kernel definition (in glsl matrices are filled in column-major order) + + const mat3 Gx = mat3( -1, -2, -1, 0, 0, 0, 1, 2, 1 ); // x direction kernel + const mat3 Gy = mat3( -1, 0, 1, -2, 0, 2, -1, 0, 1 ); // y direction kernel + + // fetch the 3x3 neighbourhood of a fragment + + // first column + + float tx0y0 = texture2D( tDiffuse, vUv + texel * vec2( -1, -1 ) ).r; + float tx0y1 = texture2D( tDiffuse, vUv + texel * vec2( -1, 0 ) ).r; + float tx0y2 = texture2D( tDiffuse, vUv + texel * vec2( -1, 1 ) ).r; + + // second column + + float tx1y0 = texture2D( tDiffuse, vUv + texel * vec2( 0, -1 ) ).r; + float tx1y1 = texture2D( tDiffuse, vUv + texel * vec2( 0, 0 ) ).r; + float tx1y2 = texture2D( tDiffuse, vUv + texel * vec2( 0, 1 ) ).r; + + // third column + + float tx2y0 = texture2D( tDiffuse, vUv + texel * vec2( 1, -1 ) ).r; + float tx2y1 = texture2D( tDiffuse, vUv + texel * vec2( 1, 0 ) ).r; + float tx2y2 = texture2D( tDiffuse, vUv + texel * vec2( 1, 1 ) ).r; + + // gradient value in x direction + + float valueGx = Gx[0][0] * tx0y0 + Gx[1][0] * tx1y0 + Gx[2][0] * tx2y0 + + Gx[0][1] * tx0y1 + Gx[1][1] * tx1y1 + Gx[2][1] * tx2y1 + + Gx[0][2] * tx0y2 + Gx[1][2] * tx1y2 + Gx[2][2] * tx2y2; + + // gradient value in y direction + + float valueGy = Gy[0][0] * tx0y0 + Gy[1][0] * tx1y0 + Gy[2][0] * tx2y0 + + Gy[0][1] * tx0y1 + Gy[1][1] * tx1y1 + Gy[2][1] * tx2y1 + + Gy[0][2] * tx0y2 + Gy[1][2] * tx1y2 + Gy[2][2] * tx2y2; + + // magnitude of the total gradient + + float G = sqrt( ( valueGx * valueGx ) + ( valueGy * valueGy ) ); + + gl_FragColor = vec4( vec3( G ), 1 ); + + }` +}; +// node_modules/three/examples/jsm/shaders/SubsurfaceScatteringShader.js +function replaceAll(string, find2, replace) { + return string.split(find2).join(replace); +} +var meshphong_frag_head = ShaderChunk["meshphong_frag"].slice(0, ShaderChunk["meshphong_frag"].indexOf("void main() {")); +var meshphong_frag_body = ShaderChunk["meshphong_frag"].slice(ShaderChunk["meshphong_frag"].indexOf("void main() {")); +var SubsurfaceScatteringShader = { + name: "SubsurfaceScatteringShader", + uniforms: UniformsUtils.merge([ + ShaderLib["phong"].uniforms, + { + thicknessMap: { value: null }, + thicknessColor: { value: new Color(16777215) }, + thicknessDistortion: { value: 0.1 }, + thicknessAmbient: { value: 0 }, + thicknessAttenuation: { value: 0.1 }, + thicknessPower: { value: 2 }, + thicknessScale: { value: 10 } + } + ]), + vertexShader: [ + "#define USE_UV", + ShaderChunk["meshphong_vert"] + ].join(` +`), + fragmentShader: [ + "#define USE_UV", + "#define SUBSURFACE", + meshphong_frag_head, + "uniform sampler2D thicknessMap;", + "uniform float thicknessPower;", + "uniform float thicknessScale;", + "uniform float thicknessDistortion;", + "uniform float thicknessAmbient;", + "uniform float thicknessAttenuation;", + "uniform vec3 thicknessColor;", + "void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, inout ReflectedLight reflectedLight) {", + "\tvec3 thickness = thicknessColor * texture2D(thicknessMap, uv).r;", + "\tvec3 scatteringHalf = normalize(directLight.direction + (geometryNormal * thicknessDistortion));", + "\tfloat scatteringDot = pow(saturate(dot(geometryViewDir, -scatteringHalf)), thicknessPower) * thicknessScale;", + "\tvec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;", + "\treflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;", + "}", + meshphong_frag_body.replace("#include ", replaceAll(ShaderChunk["lights_fragment_begin"], "RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );", [ + "RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );", + "#if defined( SUBSURFACE ) && defined( USE_UV )", + " RE_Direct_Scattering(directLight, vUv, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, reflectedLight);", + "#endif" + ].join(` +`))) + ].join(` +`) +}; +// node_modules/three/examples/jsm/shaders/ToonShader.js +var ToonShader1 = { + uniforms: { + uDirLightPos: { value: new Vector3 }, + uDirLightColor: { value: new Color(15658734) }, + uAmbientLightColor: { value: new Color(328965) }, + uBaseColor: { value: new Color(16777215) } + }, + vertexShader: ` + + varying vec3 vNormal; + varying vec3 vRefract; + + void main() { + + vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); + vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); + vec3 worldNormal = normalize ( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal ); + + vNormal = normalize( normalMatrix * normal ); + + vec3 I = worldPosition.xyz - cameraPosition; + vRefract = refract( normalize( I ), worldNormal, 1.02 ); + + gl_Position = projectionMatrix * mvPosition; + + }`, + fragmentShader: ` + + uniform vec3 uBaseColor; + + uniform vec3 uDirLightPos; + uniform vec3 uDirLightColor; + + uniform vec3 uAmbientLightColor; + + varying vec3 vNormal; + + varying vec3 vRefract; + + void main() { + + float directionalLightWeighting = max( dot( normalize( vNormal ), uDirLightPos ), 0.0); + vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; + + float intensity = smoothstep( - 0.5, 1.0, pow( length(lightWeighting), 20.0 ) ); + intensity += length(lightWeighting) * 0.2; + + float cameraWeighting = dot( normalize( vNormal ), vRefract ); + intensity += pow( 1.0 - length( cameraWeighting ), 6.0 ); + intensity = intensity * 0.2 + 0.3; + + if ( intensity < 0.50 ) { + + gl_FragColor = vec4( 2.0 * intensity * uBaseColor, 1.0 ); + + } else { + + gl_FragColor = vec4( 1.0 - 2.0 * ( 1.0 - intensity ) * ( 1.0 - uBaseColor ), 1.0 ); + + } + + #include + + }` +}; +var ToonShader2 = { + uniforms: { + uDirLightPos: { value: new Vector3 }, + uDirLightColor: { value: new Color(15658734) }, + uAmbientLightColor: { value: new Color(328965) }, + uBaseColor: { value: new Color(15658734) }, + uLineColor1: { value: new Color(8421504) }, + uLineColor2: { value: new Color(0) }, + uLineColor3: { value: new Color(0) }, + uLineColor4: { value: new Color(0) } + }, + vertexShader: ` + + varying vec3 vNormal; + + void main() { + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + vNormal = normalize( normalMatrix * normal ); + + }`, + fragmentShader: ` + + uniform vec3 uBaseColor; + uniform vec3 uLineColor1; + uniform vec3 uLineColor2; + uniform vec3 uLineColor3; + uniform vec3 uLineColor4; + + uniform vec3 uDirLightPos; + uniform vec3 uDirLightColor; + + uniform vec3 uAmbientLightColor; + + varying vec3 vNormal; + + void main() { + + float camera = max( dot( normalize( vNormal ), vec3( 0.0, 0.0, 1.0 ) ), 0.4); + float light = max( dot( normalize( vNormal ), uDirLightPos ), 0.0); + + gl_FragColor = vec4( uBaseColor, 1.0 ); + + if ( length(uAmbientLightColor + uDirLightColor * light) < 1.00 ) { + + gl_FragColor *= vec4( uLineColor1, 1.0 ); + + } + + if ( length(uAmbientLightColor + uDirLightColor * camera) < 0.50 ) { + + gl_FragColor *= vec4( uLineColor2, 1.0 ); + + } + + #include + + }` +}; +var ToonShaderHatching = { + uniforms: { + uDirLightPos: { value: new Vector3 }, + uDirLightColor: { value: new Color(15658734) }, + uAmbientLightColor: { value: new Color(328965) }, + uBaseColor: { value: new Color(16777215) }, + uLineColor1: { value: new Color(0) }, + uLineColor2: { value: new Color(0) }, + uLineColor3: { value: new Color(0) }, + uLineColor4: { value: new Color(0) } + }, + vertexShader: ` + + varying vec3 vNormal; + + void main() { + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + vNormal = normalize( normalMatrix * normal ); + + }`, + fragmentShader: ` + + uniform vec3 uBaseColor; + uniform vec3 uLineColor1; + uniform vec3 uLineColor2; + uniform vec3 uLineColor3; + uniform vec3 uLineColor4; + + uniform vec3 uDirLightPos; + uniform vec3 uDirLightColor; + + uniform vec3 uAmbientLightColor; + + varying vec3 vNormal; + + void main() { + + float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0); + vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; + + gl_FragColor = vec4( uBaseColor, 1.0 ); + + if ( length(lightWeighting) < 1.00 ) { + + if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) { + + gl_FragColor = vec4( uLineColor1, 1.0 ); + + } + + } + + if ( length(lightWeighting) < 0.75 ) { + + if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) { + + gl_FragColor = vec4( uLineColor2, 1.0 ); + + } + + } + + if ( length(lightWeighting) < 0.50 ) { + + if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) { + + gl_FragColor = vec4( uLineColor3, 1.0 ); + + } + + } + + if ( length(lightWeighting) < 0.3465 ) { + + if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) { + + gl_FragColor = vec4( uLineColor4, 1.0 ); + + } + + } + + #include + + }` +}; +var ToonShaderDotted = { + uniforms: { + uDirLightPos: { value: new Vector3 }, + uDirLightColor: { value: new Color(15658734) }, + uAmbientLightColor: { value: new Color(328965) }, + uBaseColor: { value: new Color(16777215) }, + uLineColor1: { value: new Color(0) } + }, + vertexShader: ` + + varying vec3 vNormal; + + void main() { + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + vNormal = normalize( normalMatrix * normal ); + + }`, + fragmentShader: ` + + uniform vec3 uBaseColor; + uniform vec3 uLineColor1; + uniform vec3 uLineColor2; + uniform vec3 uLineColor3; + uniform vec3 uLineColor4; + + uniform vec3 uDirLightPos; + uniform vec3 uDirLightColor; + + uniform vec3 uAmbientLightColor; + + varying vec3 vNormal; + + void main() { + + float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0); + vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; + + gl_FragColor = vec4( uBaseColor, 1.0 ); + + if ( length(lightWeighting) < 1.00 ) { + + if ( ( mod(gl_FragCoord.x, 4.001) + mod(gl_FragCoord.y, 4.0) ) > 6.00 ) { + + gl_FragColor = vec4( uLineColor1, 1.0 ); + + } + + } + + if ( length(lightWeighting) < 0.50 ) { + + if ( ( mod(gl_FragCoord.x + 2.0, 4.001) + mod(gl_FragCoord.y + 2.0, 4.0) ) > 6.00 ) { + + gl_FragColor = vec4( uLineColor1, 1.0 ); + + } + + } + + #include + + }` +}; +// node_modules/three/examples/jsm/shaders/TriangleBlurShader.js +var TriangleBlurShader = { + name: "TriangleBlurShader", + uniforms: { + texture: { value: null }, + delta: { value: new Vector2(1, 1) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + #include + + #define ITERATIONS 10.0 + + uniform sampler2D texture; + uniform vec2 delta; + + varying vec2 vUv; + + void main() { + + vec4 color = vec4( 0.0 ); + + float total = 0.0; + + // randomize the lookup values to hide the fixed number of samples + + float offset = rand( vUv ); + + for ( float t = -ITERATIONS; t <= ITERATIONS; t ++ ) { + + float percent = ( t + offset - 0.5 ) / ITERATIONS; + float weight = 1.0 - abs( percent ); + + color += texture2D( texture, vUv + delta * percent ) * weight; + total += weight; + + } + + gl_FragColor = color / total; + + }` +}; +// node_modules/three/examples/jsm/shaders/VelocityShader.js +var VelocityShader = { + name: "VelocityShader", + uniforms: UniformsUtils.merge([ + UniformsLib.common, + UniformsLib.displacementmap, + { + modelMatrixPrev: { value: new Matrix4 }, + currentProjectionViewMatrix: { value: new Matrix4 }, + previousProjectionViewMatrix: { value: new Matrix4 } + } + ]), + vertexShader: ` +#define NORMAL + +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + + varying vec3 vViewPosition; + +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +uniform mat4 previousProjectionViewMatrix; +uniform mat4 currentProjectionViewMatrix; + +uniform mat4 modelMatrixPrev; + +varying vec4 clipPositionCurrent; +varying vec4 clipPositionPrevious; + +void main() { + + + #include + + #include + #include + #include + #include + #include + #include + + #include + #include + #include + #include + #include + +#ifdef USE_SKINNING + + vec4 mvPosition = modelViewMatrix * skinned; + clipPositionCurrent = currentProjectionViewMatrix * modelMatrix * skinned; + clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * skinned; + +#else + + vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 ); + clipPositionCurrent = currentProjectionViewMatrix * modelMatrix * vec4( transformed, 1.0 ); + clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * vec4( transformed, 1.0 ); + +#endif + + gl_Position = projectionMatrix * mvPosition; + + #include + #include +} +`, + fragmentShader: ` +#define NORMAL + +uniform float opacity; + +#include +#include +#include +#include +#include +#include +#include + +varying vec4 clipPositionCurrent; +varying vec4 clipPositionPrevious; + +void main() { + + vec4 diffuseColor = vec4( 1.0 ); + diffuseColor.a = opacity; + + #include + #include + #include + + vec2 ndcPositionCurrent = clipPositionCurrent.xy/clipPositionCurrent.w; + vec2 ndcPositionPrevious = clipPositionPrevious.xy/clipPositionPrevious.w; + vec2 vel = ( ndcPositionCurrent - ndcPositionPrevious ) * 0.5; + vel = vel * 0.5 + 0.5; + vec2 v1 = packDepthToRG(vel.x); + vec2 v2 = packDepthToRG(vel.y); + gl_FragColor = vec4(v1.x, v1.y, v2.x, v2.y); + + #include + +} + +` +}; +// node_modules/three/examples/jsm/shaders/VerticalBlurShader.js +var VerticalBlurShader = { + name: "VerticalBlurShader", + uniforms: { + tDiffuse: { value: null }, + v: { value: 1 / 512 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform float v; + + varying vec2 vUv; + + void main() { + + vec4 sum = vec4( 0.0 ); + + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ) * 0.051; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ) * 0.051; + + gl_FragColor = sum; + + }` +}; +// node_modules/three/examples/jsm/shaders/VerticalTiltShiftShader.js +var VerticalTiltShiftShader = { + name: "VerticalTiltShiftShader", + uniforms: { + tDiffuse: { value: null }, + v: { value: 1 / 512 }, + r: { value: 0.35 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform float v; + uniform float r; + + varying vec2 vUv; + + void main() { + + vec4 sum = vec4( 0.0 ); + + float vv = v * abs( r - vUv.y ); + + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * vv ) ) * 0.051; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * vv ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * vv ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * vv ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * vv ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * vv ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * vv ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * vv ) ) * 0.051; + + gl_FragColor = sum; + + }` +}; +// node_modules/three/examples/jsm/shaders/VolumeShader.js +var VolumeRenderShader1 = { + uniforms: { + u_size: { value: new Vector3(1, 1, 1) }, + u_renderstyle: { value: 0 }, + u_renderthreshold: { value: 0.5 }, + u_clim: { value: new Vector2(1, 1) }, + u_data: { value: null }, + u_cmdata: { value: null } + }, + vertexShader: ` + + varying vec4 v_nearpos; + varying vec4 v_farpos; + varying vec3 v_position; + + void main() { + // Prepare transforms to map to "camera view". See also: + // https://threejs.org/docs/#api/renderers/webgl/WebGLProgram + mat4 viewtransformf = modelViewMatrix; + mat4 viewtransformi = inverse(modelViewMatrix); + + // Project local vertex coordinate to camera position. Then do a step + // backward (in cam coords) to the near clipping plane, and project back. Do + // the same for the far clipping plane. This gives us all the information we + // need to calculate the ray and truncate it to the viewing cone. + vec4 position4 = vec4(position, 1.0); + vec4 pos_in_cam = viewtransformf * position4; + + // Intersection of ray and near clipping plane (z = -1 in clip coords) + pos_in_cam.z = -pos_in_cam.w; + v_nearpos = viewtransformi * pos_in_cam; + + // Intersection of ray and far clipping plane (z = +1 in clip coords) + pos_in_cam.z = pos_in_cam.w; + v_farpos = viewtransformi * pos_in_cam; + + // Set varyings and output pos + v_position = position; + gl_Position = projectionMatrix * viewMatrix * modelMatrix * position4; + }`, + fragmentShader: ` + + precision highp float; + precision mediump sampler3D; + + uniform vec3 u_size; + uniform int u_renderstyle; + uniform float u_renderthreshold; + uniform vec2 u_clim; + + uniform sampler3D u_data; + uniform sampler2D u_cmdata; + + varying vec3 v_position; + varying vec4 v_nearpos; + varying vec4 v_farpos; + + // The maximum distance through our rendering volume is sqrt(3). + const int MAX_STEPS = 887; // 887 for 512^3, 1774 for 1024^3 + const int REFINEMENT_STEPS = 4; + const float relative_step_size = 1.0; + const vec4 ambient_color = vec4(0.2, 0.4, 0.2, 1.0); + const vec4 diffuse_color = vec4(0.8, 0.2, 0.2, 1.0); + const vec4 specular_color = vec4(1.0, 1.0, 1.0, 1.0); + const float shininess = 40.0; + + void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray); + void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray); + + float sample1(vec3 texcoords); + vec4 apply_colormap(float val); + vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray); + + + void main() { + // Normalize clipping plane info + vec3 farpos = v_farpos.xyz / v_farpos.w; + vec3 nearpos = v_nearpos.xyz / v_nearpos.w; + + // Calculate unit vector pointing in the view direction through this fragment. + vec3 view_ray = normalize(nearpos.xyz - farpos.xyz); + + // Compute the (negative) distance to the front surface or near clipping plane. + // v_position is the back face of the cuboid, so the initial distance calculated in the dot + // product below is the distance from near clip plane to the back of the cuboid + float distance = dot(nearpos - v_position, view_ray); + distance = max(distance, min((-0.5 - v_position.x) / view_ray.x, + (u_size.x - 0.5 - v_position.x) / view_ray.x)); + distance = max(distance, min((-0.5 - v_position.y) / view_ray.y, + (u_size.y - 0.5 - v_position.y) / view_ray.y)); + distance = max(distance, min((-0.5 - v_position.z) / view_ray.z, + (u_size.z - 0.5 - v_position.z) / view_ray.z)); + + // Now we have the starting position on the front surface + vec3 front = v_position + view_ray * distance; + + // Decide how many steps to take + int nsteps = int(-distance / relative_step_size + 0.5); + if ( nsteps < 1 ) + discard; + + // Get starting location and step vector in texture coordinates + vec3 step = ((v_position - front) / u_size) / float(nsteps); + vec3 start_loc = front / u_size; + + // For testing: show the number of steps. This helps to establish + // whether the rays are correctly oriented + //'gl_FragColor = vec4(0.0, float(nsteps) / 1.0 / u_size.x, 1.0, 1.0); + //'return; + + if (u_renderstyle == 0) + cast_mip(start_loc, step, nsteps, view_ray); + else if (u_renderstyle == 1) + cast_iso(start_loc, step, nsteps, view_ray); + + if (gl_FragColor.a < 0.05) + discard; + } + + + float sample1(vec3 texcoords) { + /* Sample float value from a 3D texture. Assumes intensity data. */ + return texture(u_data, texcoords.xyz).r; + } + + + vec4 apply_colormap(float val) { + val = (val - u_clim[0]) / (u_clim[1] - u_clim[0]); + return texture2D(u_cmdata, vec2(val, 0.5)); + } + + + void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) { + + float max_val = -1e6; + int max_i = 100; + vec3 loc = start_loc; + + // Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with + // non-constant expression. So we use a hard-coded max, and an additional condition + // inside the loop. + for (int iter=0; iter= nsteps) + break; + // Sample from the 3D texture + float val = sample1(loc); + // Apply MIP operation + if (val > max_val) { + max_val = val; + max_i = iter; + } + // Advance location deeper into the volume + loc += step; + } + + // Refine location, gives crispier images + vec3 iloc = start_loc + step * (float(max_i) - 0.5); + vec3 istep = step / float(REFINEMENT_STEPS); + for (int i=0; i= nsteps) + break; + + // Sample from the 3D texture + float val = sample1(loc); + + if (val > low_threshold) { + // Take the last interval in smaller steps + vec3 iloc = loc - 0.5 * step; + vec3 istep = step / float(REFINEMENT_STEPS); + for (int i=0; i u_renderthreshold) { + gl_FragColor = add_lighting(val, iloc, dstep, view_ray); + return; + } + iloc += istep; + } + } + + // Advance location deeper into the volume + loc += step; + } + } + + + vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray) + { + // Calculate color by incorporating lighting + + // View direction + vec3 V = normalize(view_ray); + + // calculate normal vector from gradient + vec3 N; + float val1, val2; + val1 = sample1(loc + vec3(-step[0], 0.0, 0.0)); + val2 = sample1(loc + vec3(+step[0], 0.0, 0.0)); + N[0] = val1 - val2; + val = max(max(val1, val2), val); + val1 = sample1(loc + vec3(0.0, -step[1], 0.0)); + val2 = sample1(loc + vec3(0.0, +step[1], 0.0)); + N[1] = val1 - val2; + val = max(max(val1, val2), val); + val1 = sample1(loc + vec3(0.0, 0.0, -step[2])); + val2 = sample1(loc + vec3(0.0, 0.0, +step[2])); + N[2] = val1 - val2; + val = max(max(val1, val2), val); + + float gm = length(N); // gradient magnitude + N = normalize(N); + + // Flip normal so it points towards viewer + float Nselect = float(dot(N, V) > 0.0); + N = (2.0 * Nselect - 1.0) * N; // == Nselect * N - (1.0-Nselect)*N; + + // Init colors + vec4 ambient_color = vec4(0.0, 0.0, 0.0, 0.0); + vec4 diffuse_color = vec4(0.0, 0.0, 0.0, 0.0); + vec4 specular_color = vec4(0.0, 0.0, 0.0, 0.0); + + // note: could allow multiple lights + for (int i=0; i<1; i++) + { + // Get light direction (make sure to prevent zero devision) + vec3 L = normalize(view_ray); //lightDirs[i]; + float lightEnabled = float( length(L) > 0.0 ); + L = normalize(L + (1.0 - lightEnabled)); + + // Calculate lighting properties + float lambertTerm = clamp(dot(N, L), 0.0, 1.0); + vec3 H = normalize(L+V); // Halfway vector + float specularTerm = pow(max(dot(H, N), 0.0), shininess); + + // Calculate mask + float mask1 = lightEnabled; + + // Calculate colors + ambient_color += mask1 * ambient_color; // * gl_LightSource[i].ambient; + diffuse_color += mask1 * lambertTerm; + specular_color += mask1 * specularTerm * specular_color; + } + + // Calculate final color by componing different components + vec4 final_color; + vec4 color = apply_colormap(val); + final_color = color * (ambient_color + diffuse_color) + specular_color; + final_color.a = color.a; + return final_color; + }` +}; +// node_modules/three/examples/jsm/utils/SkeletonUtils.js +var exports_SkeletonUtils = {}; +__export(exports_SkeletonUtils, { + retargetClip: () => retargetClip, + retarget: () => retarget, + clone: () => clone +}); +function getBoneName(bone, options) { + if (options.getBoneName !== undefined) { + return options.getBoneName(bone); + } + return options.names[bone.name]; +} +function retarget(target, source, options = {}) { + const quat = new Quaternion, scale2 = new Vector3, relativeMatrix = new Matrix4, globalMatrix = new Matrix4; + options.preserveBoneMatrix = options.preserveBoneMatrix !== undefined ? options.preserveBoneMatrix : true; + options.preserveBonePositions = options.preserveBonePositions !== undefined ? options.preserveBonePositions : true; + options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false; + options.hip = options.hip !== undefined ? options.hip : "hip"; + options.hipInfluence = options.hipInfluence !== undefined ? options.hipInfluence : new Vector3(1, 1, 1); + options.scale = options.scale !== undefined ? options.scale : 1; + options.names = options.names || {}; + const sourceBones = source.isObject3D ? source.skeleton.bones : getBones(source), bones = target.isObject3D ? target.skeleton.bones : getBones(target); + let bone, name2, boneTo, bonesPosition; + if (target.isObject3D) { + target.skeleton.pose(); + } else { + options.useTargetMatrix = true; + options.preserveBoneMatrix = false; + } + if (options.preserveBonePositions) { + bonesPosition = []; + for (let i = 0;i < bones.length; i++) { + bonesPosition.push(bones[i].position.clone()); + } + } + if (options.preserveBoneMatrix) { + target.updateMatrixWorld(); + target.matrixWorld.identity(); + for (let i = 0;i < target.children.length; ++i) { + target.children[i].updateMatrixWorld(true); + } + } + for (let i = 0;i < bones.length; ++i) { + bone = bones[i]; + name2 = getBoneName(bone, options); + boneTo = getBoneByName(name2, sourceBones); + globalMatrix.copy(bone.matrixWorld); + if (boneTo) { + boneTo.updateMatrixWorld(); + if (options.useTargetMatrix) { + relativeMatrix.copy(boneTo.matrixWorld); + } else { + relativeMatrix.copy(target.matrixWorld).invert(); + relativeMatrix.multiply(boneTo.matrixWorld); + } + scale2.setFromMatrixScale(relativeMatrix); + relativeMatrix.scale(scale2.set(1 / scale2.x, 1 / scale2.y, 1 / scale2.z)); + globalMatrix.makeRotationFromQuaternion(quat.setFromRotationMatrix(relativeMatrix)); + if (target.isObject3D) { + if (options.localOffsets) { + if (options.localOffsets[bone.name]) { + globalMatrix.multiply(options.localOffsets[bone.name]); + } + } + } + globalMatrix.copyPosition(relativeMatrix); + } + if (name2 === options.hip) { + globalMatrix.elements[12] *= options.scale * options.hipInfluence.x; + globalMatrix.elements[13] *= options.scale * options.hipInfluence.y; + globalMatrix.elements[14] *= options.scale * options.hipInfluence.z; + if (options.hipPosition !== undefined) { + globalMatrix.elements[12] += options.hipPosition.x * options.scale; + globalMatrix.elements[13] += options.hipPosition.y * options.scale; + globalMatrix.elements[14] += options.hipPosition.z * options.scale; + } + } + if (bone.parent) { + bone.matrix.copy(bone.parent.matrixWorld).invert(); + bone.matrix.multiply(globalMatrix); + } else { + bone.matrix.copy(globalMatrix); + } + bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); + bone.updateMatrixWorld(); + } + if (options.preserveBonePositions) { + for (let i = 0;i < bones.length; ++i) { + bone = bones[i]; + name2 = getBoneName(bone, options) || bone.name; + if (name2 !== options.hip) { + bone.position.copy(bonesPosition[i]); + } + } + } + if (options.preserveBoneMatrix) { + target.updateMatrixWorld(true); + } +} +function retargetClip(target, source, clip, options = {}) { + options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false; + options.fps = options.fps !== undefined ? options.fps : Math.max(...clip.tracks.map((track) => track.times.length)) / clip.duration; + options.names = options.names || []; + if (!source.isObject3D) { + source = getHelperFromSkeleton(source); + } + const numFrames = Math.round(clip.duration * (options.fps / 1000) * 1000), delta = clip.duration / (numFrames - 1), convertedTracks = [], mixer = new AnimationMixer(source), bones = getBones(target.skeleton), boneDatas = []; + let positionOffset, bone, boneTo, boneData, name2; + mixer.clipAction(clip).play(); + let start = 0, end = numFrames; + if (options.trim !== undefined) { + start = Math.round(options.trim[0] * options.fps); + end = Math.min(Math.round(options.trim[1] * options.fps), numFrames) - start; + mixer.update(options.trim[0]); + } else { + mixer.update(0); + } + source.updateMatrixWorld(); + for (let frame = 0;frame < end; ++frame) { + const time2 = frame * delta; + retarget(target, source, options); + for (let j2 = 0;j2 < bones.length; ++j2) { + bone = bones[j2]; + name2 = getBoneName(bone, options) || bone.name; + boneTo = getBoneByName(name2, source.skeleton); + if (boneTo) { + boneData = boneDatas[j2] = boneDatas[j2] || { bone }; + if (options.hip === name2) { + if (!boneData.pos) { + boneData.pos = { + times: new Float32Array(end), + values: new Float32Array(end * 3) + }; + } + if (options.useFirstFramePosition) { + if (frame === 0) { + positionOffset = bone.position.clone(); + } + bone.position.sub(positionOffset); + } + boneData.pos.times[frame] = time2; + bone.position.toArray(boneData.pos.values, frame * 3); + } + if (!boneData.quat) { + boneData.quat = { + times: new Float32Array(end), + values: new Float32Array(end * 4) + }; + } + boneData.quat.times[frame] = time2; + bone.quaternion.toArray(boneData.quat.values, frame * 4); + } + } + if (frame === end - 2) { + mixer.update(delta - 0.0000001); + } else { + mixer.update(delta); + } + source.updateMatrixWorld(); + } + for (let i = 0;i < boneDatas.length; ++i) { + boneData = boneDatas[i]; + if (boneData) { + if (boneData.pos) { + convertedTracks.push(new VectorKeyframeTrack(".bones[" + boneData.bone.name + "].position", boneData.pos.times, boneData.pos.values)); + } + convertedTracks.push(new QuaternionKeyframeTrack(".bones[" + boneData.bone.name + "].quaternion", boneData.quat.times, boneData.quat.values)); + } + } + mixer.uncacheAction(clip); + return new AnimationClip(clip.name, -1, convertedTracks); +} +function clone(source) { + const sourceLookup = new Map; + const cloneLookup = new Map; + const clone2 = source.clone(); + parallelTraverse(source, clone2, function(sourceNode, clonedNode) { + sourceLookup.set(clonedNode, sourceNode); + cloneLookup.set(sourceNode, clonedNode); + }); + clone2.traverse(function(node) { + if (!node.isSkinnedMesh) + return; + const clonedMesh = node; + const sourceMesh = sourceLookup.get(node); + const sourceBones = sourceMesh.skeleton.bones; + clonedMesh.skeleton = sourceMesh.skeleton.clone(); + clonedMesh.bindMatrix.copy(sourceMesh.bindMatrix); + clonedMesh.skeleton.bones = sourceBones.map(function(bone) { + return cloneLookup.get(bone); + }); + clonedMesh.bind(clonedMesh.skeleton, clonedMesh.bindMatrix); + }); + return clone2; +} +function getBoneByName(name2, skeleton) { + for (let i = 0, bones = getBones(skeleton);i < bones.length; i++) { + if (name2 === bones[i].name) + return bones[i]; + } +} +function getBones(skeleton) { + return Array.isArray(skeleton) ? skeleton : skeleton.bones; +} +function getHelperFromSkeleton(skeleton) { + const source = new SkeletonHelper(skeleton.bones[0]); + source.skeleton = skeleton; + return source; +} +function parallelTraverse(a2, b3, callback) { + callback(a2, b3); + for (let i = 0;i < a2.children.length; i++) { + parallelTraverse(a2.children[i], b3.children[i], callback); + } +} +// node_modules/three/examples/jsm/utils/SortUtils.js +var POWER = 3; +var BIT_MAX = 32; +var BIN_BITS = 1 << POWER; +var BIN_SIZE = 1 << BIN_BITS; +var BIN_MAX = BIN_SIZE - 1; +var ITERATIONS = BIT_MAX / BIN_BITS; +var bins = new Array(ITERATIONS); +var bins_buffer = new ArrayBuffer((ITERATIONS + 1) * BIN_SIZE * 4); +var c = 0; +for (let i = 0;i < ITERATIONS + 1; i++) { + bins[i] = new Uint32Array(bins_buffer, c, BIN_SIZE); + c += BIN_SIZE * 4; +} +// node_modules/three/examples/jsm/webxr/VRButton.js +class VRButton { + static createButton(renderer2, sessionInit = {}) { + const button = document.createElement("button"); + function showEnterVR() { + let currentSession = null; + async function onSessionStarted(session) { + session.addEventListener("end", onSessionEnded); + await renderer2.xr.setSession(session); + button.textContent = "EXIT VR"; + currentSession = session; + } + function onSessionEnded() { + currentSession.removeEventListener("end", onSessionEnded); + button.textContent = "ENTER VR"; + currentSession = null; + } + button.style.display = ""; + button.style.cursor = "pointer"; + button.style.left = "calc(50% - 50px)"; + button.style.width = "100px"; + button.textContent = "ENTER VR"; + const sessionOptions = { + ...sessionInit, + optionalFeatures: [ + "local-floor", + "bounded-floor", + "layers", + ...sessionInit.optionalFeatures || [] + ] + }; + button.onmouseenter = function() { + button.style.opacity = "1.0"; + }; + button.onmouseleave = function() { + button.style.opacity = "0.5"; + }; + button.onclick = function() { + if (currentSession === null) { + navigator.xr.requestSession("immersive-vr", sessionOptions).then(onSessionStarted); + } else { + currentSession.end(); + if (navigator.xr.offerSession !== undefined) { + navigator.xr.offerSession("immersive-vr", sessionOptions).then(onSessionStarted).catch((err) => { + console.warn(err); + }); + } + } + }; + if (navigator.xr.offerSession !== undefined) { + navigator.xr.offerSession("immersive-vr", sessionOptions).then(onSessionStarted).catch((err) => { + console.warn(err); + }); + } + } + function disableButton() { + button.style.display = ""; + button.style.cursor = "auto"; + button.style.left = "calc(50% - 75px)"; + button.style.width = "150px"; + button.onmouseenter = null; + button.onmouseleave = null; + button.onclick = null; + } + function showWebXRNotFound() { + disableButton(); + button.textContent = "VR NOT SUPPORTED"; + } + function showVRNotAllowed(exception) { + disableButton(); + console.warn("Exception when trying to call xr.isSessionSupported", exception); + button.textContent = "VR NOT ALLOWED"; + } + function stylizeElement(element) { + element.style.position = "absolute"; + element.style.bottom = "20px"; + element.style.padding = "12px 6px"; + element.style.border = "1px solid #fff"; + element.style.borderRadius = "4px"; + element.style.background = "rgba(0,0,0,0.1)"; + element.style.color = "#fff"; + element.style.font = "normal 13px sans-serif"; + element.style.textAlign = "center"; + element.style.opacity = "0.5"; + element.style.outline = "none"; + element.style.zIndex = "999"; + } + if ("xr" in navigator) { + button.id = "VRButton"; + button.style.display = "none"; + stylizeElement(button); + navigator.xr.isSessionSupported("immersive-vr").then(function(supported) { + supported ? showEnterVR() : showWebXRNotFound(); + if (supported && VRButton.xrSessionIsGranted) { + button.click(); + } + }).catch(showVRNotAllowed); + return button; + } else { + const message = document.createElement("a"); + if (window.isSecureContext === false) { + message.href = document.location.href.replace(/^http:/, "https:"); + message.innerHTML = "WEBXR NEEDS HTTPS"; + } else { + message.href = "https://immersiveweb.dev/"; + message.innerHTML = "WEBXR NOT AVAILABLE"; + } + message.style.left = "calc(50% - 90px)"; + message.style.width = "180px"; + message.style.textDecoration = "none"; + stylizeElement(message); + return message; + } + } + static registerSessionGrantedListener() { + if (typeof navigator !== "undefined" && "xr" in navigator) { + if (/WebXRViewer\//i.test(navigator.userAgent)) + return; + navigator.xr.addEventListener("sessiongranted", () => { + VRButton.xrSessionIsGranted = true; + }); + } + } +} +VRButton.xrSessionIsGranted = false; +VRButton.registerSessionGrantedListener(); +// node_modules/three/examples/jsm/libs/motion-controllers.module.js +var Constants = { + Handedness: Object.freeze({ + NONE: "none", + LEFT: "left", + RIGHT: "right" + }), + ComponentState: Object.freeze({ + DEFAULT: "default", + TOUCHED: "touched", + PRESSED: "pressed" + }), + ComponentProperty: Object.freeze({ + BUTTON: "button", + X_AXIS: "xAxis", + Y_AXIS: "yAxis", + STATE: "state" + }), + ComponentType: Object.freeze({ + TRIGGER: "trigger", + SQUEEZE: "squeeze", + TOUCHPAD: "touchpad", + THUMBSTICK: "thumbstick", + BUTTON: "button" + }), + ButtonTouchThreshold: 0.05, + AxisTouchThreshold: 0.1, + VisualResponseProperty: Object.freeze({ + TRANSFORM: "transform", + VISIBILITY: "visibility" + }) +}; +var defaultComponentValues = { + xAxis: 0, + yAxis: 0, + button: 0, + state: Constants.ComponentState.DEFAULT +}; +// node_modules/three/examples/jsm/webxr/XRHandPrimitiveModel.js +var _matrix7 = new Matrix4; +var _vector9 = new Vector3; +// src/constants/BodyShaderTypes.ts +var BodyType; +((BodyType2) => { + BodyType2["WiiU"] = "wiiu"; + BodyType2["Switch"] = "switch"; + BodyType2["Miitomo"] = "miitomo"; + BodyType2["StreetPass"] = "streetpass"; +})(BodyType ||= {}); +var ShaderType; +((ShaderType2) => { + ShaderType2["WiiU"] = "wiiu"; + ShaderType2["Switch"] = "switch"; + ShaderType2["LightDisabled"] = "lightDisabled"; + ShaderType2["Miitomo"] = "miitomo"; + ShaderType2["MiitomoBasic"] = "miitomo_basic"; + ShaderType2["WiiUBlinn"] = "wiiu_blinn"; + ShaderType2["WiiUFFLIconWithBody"] = "wiiu_ffliconwithbody"; + ShaderType2["WiiUToon"] = "wiiu_toon"; + ShaderType2["ThreeToon"] = "three_toon"; + ShaderType2["ThreePhong"] = "three_phong"; +})(ShaderType ||= {}); +function adjustShaderQuery(params, shader) { + switch (shader) { + case "wiiu" /* WiiU */: + case "switch" /* Switch */: + case "miitomo" /* Miitomo */: + params.set("shaderType", shader); + break; + case "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */: + params.set("shaderType", "ffliconwithbody"); + break; + case "wiiu_toon" /* WiiUToon */: + params.set("shaderType", "wiiu"); + break; + case "wiiu_blinn" /* WiiUBlinn */: + params.set("shaderType", "wiiu_blinn"); + break; + case "lightDisabled" /* LightDisabled */: + params.set("shaderType", "wiiu"); + params.set("lightEnable", "0"); + break; + default: + console.warn(`unknown shader type: ${shader}`); + } +} + +// src/util/ModelLoader.ts +//! NOTE: THIS ASSUMES THE ROOT IS THE PUBLIC FOLDER +var root = "/"; +var setRoot = (newRoot) => { + root = newRoot; +}; +var gltfLoader = new GLTFLoader; +var imageLoader = new ImageBitmapLoader; +function makeModelPath(gender, modelName) { + return `${root}assets/models/miiBody${gender}_${modelName}.glb`; +} +async function loadBodyModel(modelPath) { + const model = await gltfLoader.loadAsync(modelPath); + var mixer = new AnimationMixer(model.scene); + const scene = model.scene; + if (model.animations.length > 0) { + const idleClip = model.animations[0]; + const idleAnim = mixer.clipAction(idleClip, scene); + idleAnim.stop(); + try { + const clip = model.animations.find((a2) => a2.name === "Pose.01"); + const anim = mixer.clipAction(clip, scene); + anim.play(); + anim.timeScale = 0; + anim.paused = true; + mixer.update(0); + } catch (e) { + } + } else + console.warn("Body model has no animations"); + return model; +} +var bodyType = "wiiu"; +async function loadBodyModels(input, alsoLoadStreetPass = false) { + if (Object.keys(bodyModels).length > 0) { + bodyModels = {}; + } + bodyType = input || await import_localforage2.default.getItem("settings_bodyModel") || "wiiu"; + bodyModelName = bodyType; + if (bodyType === "streetpass" /* StreetPass */) { + isStreetPassBody = true; + } + if (bodyModels.highM) { + bodyModels.highM.scene.traverse((o) => { + if (o.isMesh) { + o.dispose(); + } + }); + } + if (bodyModels.highF) { + bodyModels.highF.scene.traverse((o) => { + if (o.isMesh) { + o.dispose(); + } + }); + } + bodyModels.highM = await loadBodyModel(makeModelPath("M", bodyType)); + bodyModels.highF = await loadBodyModel(makeModelPath("F", bodyType)); + if (alsoLoadStreetPass) { + bodyModels.lowM = await loadBodyModel(makeModelPath("M", "streetpass")); + bodyModels.lowF = await loadBodyModel(makeModelPath("F", "streetpass")); + } +} +async function loadHatModels() { + hatModels = []; + const data2 = await fetch(root + "assets/models/hat_models_bundle.zip").then((j2) => j2.blob()); + const zip = await import_jszip2.default.loadAsync(data2); + let promises = []; + const fileList = Object.keys(zip.files); + for (const file of fileList) { + promises.push(zip.files[file].async("blob")); + } + const resolves = await Promise.all(promises); + for (let i = 0;i < fileList.length; i++) { + console.log("File:", fileList[i]); + const url = URL.createObjectURL(resolves[i]); + const gltf = await gltfLoader.loadAsync(url); + hatModels[i] = gltf.scene; + URL.revokeObjectURL(url); + } +} +async function loadClothesTextures() { + clothesTextures = {}; + imageLoader.setOptions({ imageOrientation: "flipY" }); + const data2 = await fetch(root + "assets/images/mii_clothes_textures_bundle.zip").then((j2) => j2.blob()); + console.log("Got it"); + const zip = await import_jszip2.default.loadAsync(data2); + console.log("Got zip"); + let promises = []; + const fileList = Object.keys(zip.files); + for (const file of fileList) { + promises.push(zip.files[file].async("blob")); + } + const resolves = await Promise.all(promises); + console.log("Got files"); + for (let i = 0;i < fileList.length; i++) { + const url = URL.createObjectURL(resolves[i]); + let result; + console.log("Loading texture"); + result = new CanvasTexture(await imageLoader.loadAsync(url)); + console.log("Loading texture done"); + const fileName = fileList[i].split("."); + fileName.pop(); + clothesTextures[fileName.join(".")] = result; + console.log("Loading " + fileName.join(".")); + URL.revokeObjectURL(url); + } + console.log("Done"); +} +var bodyModels = { + highM: null, + highF: null, + lowM: null, + lowF: null +}; +var bodyModelName = "wiiu"; +var hatModels = []; +var clothesTextures = {}; +var isStreetPassBody = false; +var isStreetPass = () => isStreetPassBody; +var getBodyModels = () => bodyModels; +var getHatModels = () => hatModels; +var getLoadedBodyModelName = () => bodyModelName; +var getClothesTextures = () => clothesTextures; + +// src/class/3d/shader/ShaderUtils.ts +var import_FFLShaderMaterial2 = __toESM(require_FFLShaderMaterial(), 1); +var import_LUTShaderMaterial2 = __toESM(require_LUTShaderMaterial(), 1); +var import_localforage3 = __toESM(require_localforage(), 1); + +// src/class/3d/shader/FFLShaderAlternateMaterial.ts +var import_FFLShaderMaterial = __toESM(require_FFLShaderMaterial(), 1); +var import_LUTShaderMaterial = __toESM(require_LUTShaderMaterial(), 1); + +// src/class/3d/shader/fflShaderConst.ts +var FFLToonMaterial = { + ambient: new Color(0.8, 0.8, 0.8), + diffuse: new Color(0.8, 0.8, 0.8), + specular: new Color(0.1, 0.1, 0.1), + specularPower: 0.01, + specularMode: 0 +}; +var cLightAmbientFFLIconWithBody = new Color(0.5, 0.5, 0.5); +var cLightDiffuseFFLIconWithBody = new Color(0.9, 0.9, 0.9); +var cLightSpecularFFLIconWithBody = new Color(1, 1, 1); +var cLightDirGlossy = new Vector3(-0.35, 1, 0.8); +var cLightDirFFLIconWithBody = new Vector3(-0.5, 0.366, 0.785); +var cRimColor = new Vector4(0.3, 0.3, 0.3, 1); +var cPantsColorGray = [0.25098, 0.27451, 0.30588]; +var cPantsColorRed = [0.43922, 0.12549, 0.06275]; +var cPantsColorBlue = [0.15686, 0.25098, 0.47059]; +var cPantsColorGold = [0.75294, 0.62745, 0.18824]; +var cPantsColorRedHex = "#902010"; +var cPantsColorGoldHex = "#c0a030"; +var MiiFavoriteFFLColorLookupTable = { + 0: [0.824, 0.118, 0.078], + 1: [1, 0.431, 0.098], + 2: [1, 0.847, 0.125], + 3: [0.471, 0.824, 0.125], + 4: [0, 0.471, 0.188], + 5: [0.039, 0.282, 0.706], + 6: [0.235, 0.667, 0.871], + 7: [0.961, 0.353, 0.49], + 8: [0.451, 0.157, 0.678], + 9: [0.282, 0.22, 0.094], + 10: [0.878, 0.878, 0.878], + 11: [0.094, 0.094, 0.078] +}; + +// src/class/3d/shader/FFLShaderAlternateMaterial.ts +class FFLShaderBlinnMaterial extends import_FFLShaderMaterial.default { + constructor(options = {}) { + options = Object.assign({ + useSpecularModeBlinn: true + }, options); + super(options); + if (this.uniforms.u_material_specular_power) + this.uniforms.u_material_specular_power.value = 2; + } +} +class FFLShaderToonMaterial extends import_FFLShaderMaterial.default { + constructor(options = {}) { + options = Object.assign({}, options); + super(options); + this.uniforms.u_light_dir.value = cLightDirGlossy; + if (this.uniforms.u_material_ambient) { + this.uniforms.u_material_ambient.value = FFLToonMaterial.ambient; + this.uniforms.u_material_diffuse.value = FFLToonMaterial.diffuse; + this.uniforms.u_material_specular.value = FFLToonMaterial.specular; + this.uniforms.u_material_specular_power.value = FFLToonMaterial.specularPower; + this.uniforms.u_material_specular_mode.value = FFLToonMaterial.specularMode; + } + } +} + +class FFLShaderBrightMaterial extends import_FFLShaderMaterial.default { + constructor(options = {}) { + options = Object.assign({}, options); + super(options); + this.uniforms.u_light_dir.value = cLightDirFFLIconWithBody; + this.uniforms.u_light_ambient.value = cLightAmbientFFLIconWithBody; + this.uniforms.u_light_diffuse.value = cLightDiffuseFFLIconWithBody; + this.uniforms.u_light_specular.value = cLightSpecularFFLIconWithBody; + } +} + +class LUTShaderPretendoMaterial extends import_LUTShaderMaterial.default { + constructor(options = {}) { + options = Object.assign({}, options); + super(options); + this.uniforms.uDirLightDirAndType0.value = new Vector4(-0.2, 0.5, 0.8, -1); + this.uniforms.uDirLightDirAndType1.value = new Vector4(0, -0.19612, 0.98058, -1); + this.uniforms.uHSLightGroundColor.value = new Color(14793111).convertLinearToSRGB(); + this.uniforms.uHSLightSkyColor.value = new Color(14800590).convertLinearToSRGB(); + this.uniforms.uDirLightColor0.value = new Color(5919571).convertLinearToSRGB(); + this.uniforms.uDirLightColor1.value = new Color(1710104).convertLinearToSRGB(); + } +} + +// src/class/3d/shader/ShaderUtils.ts +var getSettingSafe = async (key2) => { + const value2 = await import_localforage3.default.getItem("settings_" + key2); + if (value2 == null && key2 === "shaderType") { + return "wiiu"; + } + return value2; +}; +function traverseAddShader(model, shaderType) { + model.traverse((n2) => { + const node = n2; + if (node.isMesh) { + traverseMesh(node, shaderType); + } + }); +} +async function traverseMesh(node, shaderType) { + const shaderSetting = shaderType || await getSettingSafe("shaderType"); + const originalMaterial = node.material; + const userData = node.geometry.userData; + if (userData.ignore !== undefined) { + if (userData.ignore === 1) + return; + } + let modulateType = userData.modulateType; + if (userData.modulateType === undefined) + console.warn(`Mesh "${node.name}" is missing "modulateType" in userData.`); + const lightEnable = modulateType > 5 ? false : true; + let materialParam = modulateType !== undefined ? modulateType && modulateType < 9 ? import_FFLShaderMaterial2.default.materialParams[modulateType] : import_FFLShaderMaterial2.default.materialParams[0] : import_FFLShaderMaterial2.default.materialParams[0]; + let modulateMode = userData.modulateMode === undefined ? 0 : userData.modulateMode; + let modulateColor; + if (!userData.modulateColor) { + console.warn(`Mesh "${node.name}" is missing "modulateColor" in userData.`); + modulateColor = new Vector4(1, 0, 0, 1); + } else { + modulateColor = new Vector4(...userData.modulateColor, 1); + } + ColorManagement.enabled = false; + const defines = {}; + if (originalMaterial.map) { + defines.USE_MAP = ""; + originalMaterial.map.colorSpace = LinearSRGBColorSpace; + originalMaterial.needsUpdate = true; + } + let side = originalMaterial.side; + if (userData.cullMode !== undefined) { + switch (userData.cullMode) { + case 0: + side = DoubleSide; + break; + case 1: + side = FrontSide; + break; + case 2: + side = BackSide; + break; + } + } + let finalMat; + const isUsingShader = await isShaderMaterial(); + let modulate = isUsingShader ? { + modulateMode, + modulateType, + lightEnable: shaderSetting === "lightDisabled" /* LightDisabled */ ? false : true + } : {}; + const params = { + color: new Color(...modulateColor), + ...modulate, + map: originalMaterial.map || undefined, + side + }; + let shaderMaterial = await getShaderMaterialFromShaderType(shaderSetting); + finalMat = new shaderMaterial(params); + node.material = finalMat; +} +async function isShaderMaterial(shader = undefined) { + let shaderType = shader || await getSettingSafe("shaderType"); + switch (shaderType) { + case "wiiu" /* WiiU */: + case "wiiu_blinn" /* WiiUBlinn */: + case "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */: + case "wiiu_toon" /* WiiUToon */: + case "switch" /* Switch */: + case "miitomo" /* Miitomo */: + case "miitomo_basic" /* MiitomoBasic */: + return true; + case "lightDisabled" /* LightDisabled */: + case "three_toon" /* ThreeToon */: + case "three_phong" /* ThreePhong */: + return false; + } +} +async function getShaderMaterialFromShaderType(type) { + const shaderType = type || await getSettingSafe("shaderType"); + switch (shaderType) { + case "wiiu" /* WiiU */: + return import_FFLShaderMaterial2.default; + case "lightDisabled" /* LightDisabled */: + return MeshBasicMaterial; + case "wiiu_blinn" /* WiiUBlinn */: + return FFLShaderBlinnMaterial; + case "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */: + return FFLShaderBrightMaterial; + case "wiiu_toon" /* WiiUToon */: + return FFLShaderToonMaterial; + case "switch" /* Switch */: + return import_FFLShaderMaterial2.default; + case "miitomo" /* Miitomo */: + return import_LUTShaderMaterial2.default; + case "miitomo_basic" /* MiitomoBasic */: + return LUTShaderPretendoMaterial; + case "three_toon" /* ThreeToon */: + return MeshToonMaterial; + case "three_phong" /* ThreePhong */: + return MeshPhongMaterial; + } +} +var ThreeMaterialStandardLights = (scene) => { + const intensity = Number(REVISION) >= 155 ? Math.PI : 1; + const ambientLight = new AmbientLight(new Color(0.73, 0.73, 0.73), intensity); + const directionalLight = new DirectionalLight(new Color(0.6, 0.6, 0.6), intensity); + directionalLight.position.set(-0.455, 0.348, 0.5); + ambientLight.name = "ambientLight"; + directionalLight.name = "directionalLight"; + scene.add(ambientLight, directionalLight); +}; +var ThreeMaterialToonLights = (scene) => { + const intensity = 2.5; + const ambientLight = new AmbientLight(new Color(0.73, 0.73, 0.73), intensity); + const directionalLight = new DirectionalLight(new Color(0.6, 0.6, 0.6), intensity); + directionalLight.position.set(-0.255, 0.348, 0.5); + ambientLight.name = "ambientLight"; + directionalLight.name = "directionalLight"; + scene.add(ambientLight, directionalLight); +}; +async function getSimpleMaterialAddLights(type) { + const shaderType = type || await getSettingSafe("shaderType"); + switch (shaderType) { + case "wiiu" /* WiiU */: + case "wiiu_blinn" /* WiiUBlinn */: + case "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */: + case "wiiu_toon" /* WiiUToon */: + case "switch" /* Switch */: + case "miitomo" /* Miitomo */: + case "miitomo_basic" /* MiitomoBasic */: + return; + case "lightDisabled" /* LightDisabled */: + case "three_phong" /* ThreePhong */: + return ThreeMaterialStandardLights; + case "three_toon" /* ThreeToon */: + return ThreeMaterialToonLights; + } +} +function cleanupLights(scene) { + let amb = scene.getObjectByName("ambientLight"); + let dir = scene.getObjectByName("directionalLight"); + if (amb) + scene.remove(amb); + if (dir) + scene.remove(dir); +} + +// src/constants/Extensions.ts +var ExtHatNameList = [ + "Cap", + "Beanie", + "Top Hat", + "Ribbon", + "Bow", + "Cat Ears", + "Straw Hat", + "Hijab", + "Bike Helmet" +]; +var ExtClothesList = ["LS+Pants", "SS+Shorts", "TT+Shorts"]; +var HatTypeList = [ + 1 /* HAT */, + 1 /* HAT */, + 1 /* HAT */, + 4 /* SIDE */, + 4 /* SIDE */, + 0 /* HEAD */, + 1 /* HAT */, + 6 /* BALD */, + 1 /* HAT */ +]; +var ClothesTypeList = [ + 0 /* COLOR_MIXED */, + 0 /* COLOR_MIXED */, + 0 /* COLOR_MIXED */, + 0 /* COLOR_MIXED */ +]; + +// src/util/camera.js +var ViewType2 = { + Face: 0, + MakeIcon: 1, + IconFovy45: 2, + AllBody: 3, + AllBodySugar: 4, + CreditIcon: 5 +}; +function getCameraForViewType(viewType, width2 = 1, height2 = 1, miiHeight = 1) { + const aspect2 = width2 / height2; + switch (viewType) { + case ViewType2.Face: { + const fovy = 15; + const camera = new PerspectiveCamera(fovy, aspect2, 0.1, 1000); + camera.position.set(0, 34.5, 380); + camera.lookAt(0, 34.3, 0); + return camera; + } + case ViewType2.MakeIcon: { + const fovy = 9.8762; + const camera = new PerspectiveCamera(fovy, aspect2, 500, 1000); + camera.position.set(0, 34.5, 600); + camera.lookAt(0, 34.5, 0); + return camera; + } + case ViewType2.IconFovy45: { + const camera = new PerspectiveCamera(45, aspect2, 50, 1000); + camera.position.set(0, 34, 110); + camera.lookAt(0, 34, 0); + return camera; + } + case ViewType2.AllBody: { + const fovy = 15; + const camera = new PerspectiveCamera(fovy, aspect2, 50, 1500); + camera.position.set(0, 50, 900); + camera.lookAt(0, 105, 0); + return camera; + } + case ViewType2.AllBodySugar: { + const fovy = 15; + const camera = new PerspectiveCamera(fovy, aspect2, 50, 15000); + const posStart = new Vector3(0, 65, 550); + const atStart = new Vector3(0, 65, 0); + const posEnd = new Vector3(0, 75, 850); + const atEnd = new Vector3(0, 88, 0); + const t4 = (miiHeight - 0.5) / (1.264 - 0.5); + const pos = new Vector3(posStart.x + t4 * (posEnd.x - posStart.x), posStart.y + t4 * (posEnd.y - posStart.y), posStart.z + t4 * (posEnd.z - posStart.z)); + const at = new Vector3(atStart.x + t4 * (atEnd.x - atStart.x), atStart.y + t4 * (atEnd.y - atStart.y), atStart.z + t4 * (atEnd.z - atStart.z)); + camera.position.copy(pos); + camera.lookAt(at); + return camera; + } + case ViewType2.CreditIcon: { + const fovy = 15; + const camera = new PerspectiveCamera(fovy, aspect2, 0.1, 1000); + camera.position.set(-60, 34.5, 380); + camera.lookAt(0, 34.3, 0); + return camera; + } + default: + throw new Error("getCameraForViewType: not implemented"); + } +} + +// src/util/rendertarget.js +var isWorker = false; +if (typeof window === "undefined") { + isWorker = true; +} +function renderTargetToDataURL(renderTarget, renderer2, flipY = false, blob = true) { + return new Promise((resolve) => { + const scene = new Scene; + scene.background = null; + const material = new MeshBasicMaterial({ + side: DoubleSide, + map: renderTarget.texture, + transparent: true + }); + const plane = new PlaneGeometry(2, 2); + const mesh = new Mesh(plane, material); + scene.add(mesh); + const camera = getIdentCamera(flipY); + const prevTarget = renderer2.getRenderTarget(); + const prevColorSpace = renderer2.outputColorSpace; + const size2 = new Vector2; + renderer2.getSize(size2); + renderer2.setRenderTarget(null); + renderer2.outputColorSpace = ColorManagement ? ColorManagement.workingColorSpace : null; + renderer2.setSize(renderTarget.width, renderTarget.height, false); + renderer2.render(scene, camera); + function cleanup() { + material.dispose(); + plane.dispose(); + scene.remove(mesh); + renderer2.outputColorSpace = prevColorSpace; + renderer2.setSize(size2.x, size2.y, false); + renderer2.setRenderTarget(prevTarget); + } + if (blob) { + const ok = (blob2) => { + resolve({ type: "blob", result: blob2 }); + cleanup(); + }; + if (isWorker) { + renderer2.domElement.convertToBlob({ type: "image/png" }).then(ok); + } else { + renderer2.domElement.toBlob(ok); + } + } else { + const result = renderer2.domElement.toDataURL("image/png"); + resolve({ type: "dataURL", result }); + cleanup(); + } + }); +} +async function renderTargetToDataTexture(renderTarget, renderer2, flipY = false, filtering = true) { + const { width: width2, height: height2 } = renderTarget; + let buf = new Uint8Array(width2 * height2 * 4); + await renderer2.readRenderTargetPixelsAsync(renderTarget, 0, 0, width2, height2, buf); + const dataTexture = new DataTexture(buf, width2, height2, RGBAFormat, UnsignedByteType); + dataTexture.needsUpdate = true; + if (flipY) { + dataTexture.flipY = true; + } + if (filtering) { + dataTexture.minFilter = LinearFilter; + dataTexture.magFilter = LinearFilter; + } + return dataTexture; +} + +// src/class/3d/shader/ColorMix.ts +function ColorMixShaderMaterial(texture, r, g3, b3) { + return new ShaderMaterial({ + uniforms: { + u_texture: { value: texture }, + u_const1: { value: r }, + u_const2: { value: g3 }, + u_const3: { value: b3 } + }, + vertexShader: ` + varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + } + `, + fragmentShader: ` + uniform sampler2D u_texture; + uniform vec4 u_const1; + uniform vec4 u_const2; + uniform vec4 u_const3; + varying vec2 vUv; + + void main() { + vec4 texColor = texture2D(u_texture, vUv); + + // Optionally discard low-alpha texture pixels. + if (texColor.a <= 0.2) { + discard; + } + +// Mix RGB channels using each constant’s color (rgb) +vec3 mixedColor = texColor.r * u_const1.rgb + + texColor.g * u_const2.rgb + + texColor.b * u_const3.rgb; + +// Use the texture's own alpha +float mixedAlpha = texColor.a; + +// Premultiply the mixed color by its alpha +gl_FragColor = vec4(mixedColor * mixedAlpha, mixedAlpha); + } + ` + }); +} +function colorMixTexture(tex, constR = new Vector4(0, 1, 1, 1), constG = new Vector4(1, 1, 0, 1), constB = new Vector4(1, 1, 0, 1), constA, rendererMain, textureResolution) { + return new Promise((resolve) => { + const scene = new Scene; + let width2, height2; + if (tex instanceof ImageBitmap) { + width2 = tex.width; + height2 = tex.height; + } else { + width2 = tex.image.width; + height2 = tex.image.height; + } + if (textureResolution) { + let aspect2 = width2 / height2; + width2 = textureResolution; + height2 = textureResolution / aspect2; + } + console.log("HI ITS ME CLOTHING TEX RENDERER, IDK WTF I DID", width2, height2); + const renderSize = new Vector2(0, 0); + rendererMain.getSize(renderSize); + console.log("[CMT DEBUG] width, height", width2, height2); + const camera = new OrthographicCamera(width2 / -2, width2 / 2, height2 / 2, height2 / -2, 0.1, 1000); + camera.position.z = 1; + console.log("[CMT DEBUG] camera Created!"); + const renderer2 = rendererMain; + console.log("[CMT DEBUG] renderer Created!"); + let oldClearColor = new Color; + renderer2.getClearColor(oldClearColor); + let oldClearAlpha = renderer2.getClearAlpha(); + renderer2.setClearColor(constA, 1); + console.log("[CMT DEBUG] using red for alpha."); + renderer2.setSize(width2, height2, false); + console.log("[CMT DEBUG] set renderer size OK."); + if (typeof window !== "undefined") + window.camera = camera; + const geometry = new PlaneGeometry(width2, height2); + console.log("[CMT DEBUG] create geometry OK"); + const plane = new Mesh(geometry, ColorMixShaderMaterial(tex, constR, constG, constB)); + console.log("[CMT DEBUG] create mesh OK"); + scene.add(plane); + console.log("[CMT DEBUG] add mesh to scene"); + function render() { + console.log("[CMT DEBUG] render scene OK"); + function finalize(blob) { + if (blob === null) + return console.error("blob is null???"); + resolve(blob); + renderer2.setClearColor(0); + renderer2.setClearAlpha(0); + geometry.dispose(); + plane.material.dispose(); + console.log("[CMT DEBUG] disposed of scene OK"); + } + renderer2.setSize(width2, height2, false); + renderer2.render(scene, camera); + renderer2.setClearAlpha(0); + if (typeof document === "undefined") { + renderer2.domElement.convertToBlob({ type: "image/png" }).then(finalize); + } else { + renderer2.domElement.toBlob(finalize); + } + } + console.log("[CMT DEBUG] preparing render"); + render(); + }); +} + +// src/ui/pages/library/util/3DModel.ts +function loadBlobTexture(blob) { + return new Promise((resolve) => { + var texture = new Texture; + var url = URL.createObjectURL(blob); + var image = new Image; + image.src = url; + image.onload = function() { + texture.image = image; + texture.needsUpdate = true; + resolve(texture); + setTimeout(() => { + URL.revokeObjectURL(url); + }, 1e4); + }; + }); +} +function loadBlobTextureWorker(blob, width2 = 512, height2 = 512) { + return new Promise((resolve) => { + createImageBitmap(blob, 0, 0, width2, height2).then((r) => { + console.log("bitmap canvas texture created"); + return resolve(new CanvasTexture(r)); + }); + }); +} + +// src/util/IconRendering.ts +var import_FFLShaderMaterial3 = __toESM(require_FFLShaderMaterial(), 1); +var defaultParams = { + type: ViewType2.Face, + expression: 0, + characterYRotate: 0, + modelFlag: FFLCharModelDescDefault, + drawBody: true +}; +function createMiiRender(request) { + return new Promise(async (resolve) => { + let dataInput; + if (typeof request.data === "string") + dataInput = parseHexOrB64ToUint8Array(request.data); + else + dataInput = request.data; + let scene = new Scene; + const isTemporary = request.isTemporary !== false; + const mii = new Mii(dataInput); + const localModule = request.module; + if (localModule === undefined) + throw new Error("Module NOT ready."); + let modelFlag = FFLModelFlag.NORMAL; + if (request.additionalInfo.hatType !== -1) { + switch (HatTypeList[request.additionalInfo.hatType]) { + case 1 /* HAT */: + modelFlag = FFLModelFlag.HAT; + break; + case 2 /* FACE_ONLY */: + modelFlag = FFLModelFlag.FACE_ONLY; + break; + case 6 /* BALD */: + mii.hairType = 30; + dataInput = mii.export("studioData"); + break; + } + } + console.log("miic additional info:", JSON.stringify(request.additionalInfo)); + const shaderMaterial = await getShaderMaterialFromShaderType(request.shaderType); + const isUsingShader = await isShaderMaterial(request.shaderType); + let lights = await getSimpleMaterialAddLights(request.shaderType); + if (lights) { + lights(scene); + } + let texResolution = request.texResolution || 512; + if (request.size > 512) { + texResolution = 1024; + } else if (request.size > 1024) { + texResolution = 2048; + } + let expressions = []; + if (Array.isArray(request.expression)) { + expressions.push(...request.expression); + } else { + expressions.push(isNaN(request.expression) ? FFLExpression.NORMAL : request.expression); + } + const charModel = createCharModel(dataInput, { + resolution: texResolution, + resourceType: FFLResourceType.HIGH, + allExpressionFlag: makeExpressionFlag(expressions), + modelFlag + }, shaderMaterial, localModule, false); + charModel._materialTextureClass = import_FFLShaderMaterial3.default; + charModel._materialClass = shaderMaterial; + if (request.additionalInfo.eyeSclera === 1 && mii.eyeColor !== 8) { + self.eyeScleraHack = true; + } + initCharModelTextures(charModel, request.renderer, charModel._materialTextureClass); + if (request.additionalInfo.eyeSclera === 1 && mii.eyeColor !== 8) { + self.eyeScleraHack = false; + } + let miiGroup, headModel; + if (isTemporary) { + miiGroup = scene; + miiGroup.background = null; + } else { + miiGroup = new Group; + headModel = new Group; + } + const gender = charModel._model.charInfo.personal.gender; + const bodyScale = charModel.getBodyScale(); + let hatModel; + if (request.additionalInfo.hatType !== -1) { + let hatColor = [0, 0, 0]; + if (isTemporary) + hatModel = getHatModels()[request.additionalInfo.hatType].clone(true); + else + hatModel = getHatModels()[request.additionalInfo.hatType].clone(true); + hatColor = MiiFavoriteColorVec3Table[mii.favoriteColor % Object.keys(MiiFavoriteColorVec3Table).length]; + if (request.additionalInfo.hatFavoriteColor !== -1) { + hatColor = MiiFavoriteColorVec3Table[request.additionalInfo.hatFavoriteColor]; + } + if (request.additionalInfo.hatCommonColor !== -1) { + hatColor = SwitchMiiColorTableSRGB[request.additionalInfo.hatCommonColor]; + } + console.log("additional info:", request.additionalInfo, "hat model:", hatModel); + hatModel.traverse((m) => { + if (m.isMesh) { + const oldMat = m.material.map; + let modulate = isUsingShader ? { + modulateType: 5 /* FFL_MODULATE_TYPE_SHAPE_CAP */, + modulateMode: 2 + } : {}; + m.material = new shaderMaterial({ + ...modulate, + color: new Color(...hatColor), + opacity: 1, + map: oldMat + }); + } + }); + if (isTemporary) { + miiGroup.add(hatModel); + } else { + headModel.add(hatModel); + } + const shiftPos = charModel.partsTransform.hatTranslate.y; + if (request.drawBody) { + if (isTemporary) { + hatModel.position.set(0, bodyScale.y * 75 + shiftPos, 0); + } else { + hatModel.position.set(0, shiftPos, 0); + } + } else { + charModel.partsTransform.hatTranslate.y; + hatModel.position.set(0, shiftPos, 0); + } + } + const headMesh = charModel.meshes.clone(); + if (isTemporary) { + miiGroup.add(headMesh); + } else { + headModel.add(headMesh); + } + let iconCamera; + if (isTemporary) + iconCamera = getCameraForViewType(request.type, undefined, undefined, bodyScale.y); + let bodyModel, bodyModelBody, bodyModelHands, bodyModelLegs, bodyModelAnims; + if (headModel !== undefined) { + miiGroup.add(headModel); + } + let prefix = "high"; + if (request.bodyModelType !== undefined) { + prefix = request.bodyModelType; + } + if (request.drawBody && getBodyModels()[prefix + "M"] !== null) { + switch (gender) { + case 0: { + if (isTemporary) + bodyModel = getBodyModels()[prefix + "M"].scene; + else + bodyModel = exports_SkeletonUtils.clone(getBodyModels()[prefix + "M"].scene); + if (bodyModel === null) + throw "Tried to make an icon before body models were loaded."; + bodyModelBody = bodyModel.getObjectByName("body_m"); + bodyModelHands = bodyModel.getObjectByName("hands_m"); + bodyModelLegs = bodyModel.getObjectByName("legs_m"); + if (!isTemporary) + bodyModelAnims = getBodyModels()[prefix + "M"].animations; + break; + } + case 1: { + if (isTemporary) + bodyModel = getBodyModels()[prefix + "F"].scene; + else + bodyModel = exports_SkeletonUtils.clone(getBodyModels()[prefix + "F"].scene); + if (bodyModel === null) + throw "Tried to make an icon before body models were loaded."; + bodyModelBody = bodyModel.getObjectByName("body_f"); + bodyModelHands = bodyModel.getObjectByName("hands_f"); + bodyModelLegs = bodyModel.getObjectByName("legs_f"); + if (!isTemporary) + bodyModelAnims = getBodyModels()[prefix + "F"].animations; + break; + } + default: + throw new Error(`Gender ${gender} is outisde range 0, 1`); + } + bodyModel.scale.set(bodyScale.x * 7, bodyScale.y * 7, bodyScale.z * 7); + bodyModel.position.set(0, 0, 0); + miiGroup.add(bodyModel); + var shirtColor = MiiFavoriteColorVec3Table[mii.favoriteColor % Object.keys(MiiFavoriteColorVec3Table).length]; + if (request.additionalInfo.shirtColor !== -1 && !ForbiddenShirtPantColors.includes(request.additionalInfo.shirtColor)) { + shirtColor = SwitchMiiColorTableSRGB[request.additionalInfo.shirtColor]; + } + let modulate = isUsingShader ? { + modulateType: 9 /* FFL_MODULATE_TYPE_SHAPE_BODY */, + modulateMode: 0 + } : {}; + bodyModelBody.material = new charModel._materialClass({ + ...modulate, + color: new Color(...shirtColor), + opacity: 1 + }); + if (bodyModelHands) + bodyModelHands.material = bodyModelBody.material; + var pantsColor = cPantsColorGray; + if (request.additionalInfo.favorite === 1) { + pantsColor = cPantsColorRed; + } + if (request.additionalInfo.special === 1) { + pantsColor = cPantsColorGold; + } + if (request.additionalInfo.temporary === 1) { + pantsColor = cPantsColorBlue; + } + if (request.additionalInfo.pantsColor !== -1 && !ForbiddenShirtPantColors.includes(request.additionalInfo.pantsColor)) { + pantsColor = SwitchMiiColorTableSRGB[request.additionalInfo.pantsColor]; + } + modulate = isUsingShader ? { + modulateType: 10 /* FFL_MODULATE_TYPE_SHAPE_PANTS */, + modulateMode: 0 + } : {}; + bodyModelLegs.material = new charModel._materialClass({ + ...modulate, + color: new Color(...pantsColor), + opacity: 1 + }); + const nBody = bodyModelBody; + const nLegs = bodyModelLegs; + ColorManagement.enabled = false; + if (request.additionalInfo.clothesType !== undefined && request.additionalInfo.clothesType !== -1 && request.bodyModelType !== "low" /* low */ && getLoadedBodyModelName() === "wiiu" && request.additionalInfo.clothesType < ExtClothesList.length) { + console.log("clothing update"); + let shirtTexture, pantsTexture = null; + const suffix = mii.gender == 1 ? "F" : ""; + let key2 = `${getLoadedBodyModelName()}_${ExtClothesList[request.additionalInfo.clothesType]}${suffix}`; + let shirtKey = key2; + if (getLoadedBodyModelName() === "miitomo") { + shirtKey = key2 + "_Top"; + } + let shoesColor = request.additionalInfo.shoesColor !== -1 && request.additionalInfo.shoesColor < 100 ? SwitchMiiColorTableSRGB[request.additionalInfo.shoesColor] : [1, 1, 1]; + switch (ClothesTypeList[request.additionalInfo.clothesType]) { + case 0 /* COLOR_MIXED */: { + const colorMixR = new Vector4(...shirtColor, 1), colorMixG = new Vector4(...shoesColor, 1), colorMixB = new Vector4(...pantsColor, 1), colorMixA = charModel ? request.clothingLinearColors !== true ? charModel.facelineColor : charModel.facelineColor.convertSRGBToLinear() : 16711680; + let tex = await colorMixTexture(getClothesTextures()[shirtKey], colorMixR, colorMixG, colorMixB, colorMixA, request.textureRenderer || request.renderer, request.texResolution); + shirtTexture = await loadBlobTextureWorker(tex, request.texResolution, request.texResolution); + break; + } + case 1 /* TEXTURE_COLOR */: { + shirtTexture = getClothesTextures()[shirtKey + suffix]; + break; + } + default: + alert("Something isn't right here"); + throw "???"; + } + request.renderer.initTexture(shirtTexture); + let nBodyMat = nBody.material; + let nLegsMat = nLegs.material; + nBodyMat.dispose(); + nLegsMat.dispose(); + let modulate2 = isUsingShader ? { + modulateType: 9, + modulateMode: 1, + color: new Color(0) + } : { color: new Color(16777215) }; + const params = { + ...modulate2, + map: shirtTexture + }; + const newBodyMat = new (await getShaderMaterialFromShaderType(request.shaderType))(params); + if (getLoadedBodyModelName() !== "miitomo") { + nBody.material = newBodyMat; + nLegs.material = newBodyMat; + } + console.log("mat changed!", newBodyMat, nBody, nLegs); + } + if (isTemporary) { + headMesh.position.set(0, bodyScale.y * 75, 0); + } else { + headModel.position.set(0, bodyScale.y * 75, 0); + } + if (isTemporary) + switch (request.type) { + case ViewType2.Face: + case ViewType2.MakeIcon: + case ViewType2.IconFovy45: + case ViewType2.CreditIcon: { + iconCamera.position.y += bodyScale.y * 76; + } + } + if (request.bodyModelType === "low" /* low */) { + bodyModelHands.visible = false; + } + if (isStreetPass()) { + console.log("is streetpass"); + var scaleVec = new Vector3; + bodyModel.getWorldScale(scaleVec); + const handScaleX = 1 / scaleVec.x * 5; + const handScaleY = 1 / scaleVec.y * 5; + console.log(handScaleX, handScaleY); + bodyModel.getObjectByName("handLPs").scale.set(handScaleX, handScaleY, handScaleX); + bodyModel.getObjectByName("handRPs").scale.set(handScaleX, handScaleY, handScaleX); + } else { + console.log("not streetpass"); + } + } + if (isTemporary) { + const target = createAndRenderToTarget(miiGroup, iconCamera, request.renderer, request.size, request.size); + setTimeout(() => { + const dataURL = renderTargetToDataURL(target, request.renderer); + target.dispose(); + charModel.dispose(); + if (request.drawBody) { + bodyModelBody.material.dispose(); + bodyModelLegs.material.dispose(); + } + if (hatModel) { + hatModel.traverse((n2) => { + if (!n2.isMesh) + return; + n2.geometry.dispose(); + n2.material.dispose(); + }); + } + resolve(dataURL); + }, 0); + } else { + return resolve({ + bodyModel, + bodyModelBody, + bodyModelHands, + bodyModelLegs, + charModel, + headModel, + miiGroup, + bodyModelAnims + }); + } + }); +} + +// src/util/SettingsHelper.ts +var import_localforage5 = __toESM(require_localforage(), 1); + +// src/ui/pages/Settings.ts +var import_localforage4 = __toESM(require_localforage(), 1); +var needsToNotify = true; +var __3 = _8(); +var resourceRefreshFlag = false; +var updateSettings = async (force = false) => { + await checkPrevSettings(); + function askRefreshNotice() { + if (needsToNotify && force === false) { + Notify_default.show(__3("Refresh to apply changes"), __3("Icons won't be affected until you reload."), () => { + location.reload(); + }, "Refresh"); + needsToNotify = false; + setTimeout(() => { + needsToNotify = true; + }, 5000); + } + } + let useBgm = await import_localforage4.default.getItem("settings_bgm"); + if (useBgm === true) + getMusicManager().unmute(); + else if (useBgm === false) + getMusicManager().mute(); + let useSfx = await import_localforage4.default.getItem("settings_sfx"); + if (useSfx === true) + getSoundManager().unmute(); + else if (useSfx === false) + getSoundManager().mute(); + const wiiu = await import_localforage4.default.getItem("settings_wiiu"); + if (wiiu) { + await import_localforage4.default.removeItem("settings_wiiu"); + await import_localforage4.default.setItem("settings_theme", "wiiu"); + } + const theme = await import_localforage4.default.getItem("settings_theme"); + if (theme === null) { + await setSetting("theme", "default"); + } else if (theme === "wiiu") { + await setSetting("theme", "default"); + } + document.documentElement.dataset.theme = String(await import_localforage4.default.getItem("settings_theme")); + if (prevSetting["theme"] !== await import_localforage4.default.getItem("settings_theme") || force) { + setTimeout(async () => { + document.dispatchEvent(new CustomEvent("theme-change")); + }, 33.33); + } + if (prevSetting["resourceType"] !== await import_localforage4.default.getItem("settings_resourceType")) { + console.log("comparing", prevSetting["resourceType"], "to", await import_localforage4.default.getItem("settings_resourceType"), "FAILED"); + resourceRefreshFlag = true; + } + if (prevSetting["shaderType"] !== await import_localforage4.default.getItem("settings_shaderType")) { + console.log("shaderType changed!!!"); + askRefreshNotice(); + let currentShader = await getSetting("shaderType"); + document.dispatchEvent(new CustomEvent("library-shader-update")); + if (Html.qsa("img[data-src]") !== null) + Html.qsa("img[data-src]").forEach((img) => { + const image = img.elm; + const source = image.src.trim() || image.dataset.src; + let sourceToUpdate = image.src.trim() !== "" ? "src" : "data-src"; + console.log(sourceToUpdate); + if (!source.includes("?")) + return; + const params = new URLSearchParams(source.split("?").pop()); + params.delete("shaderType"); + params.delete("lightEnable"); + adjustShaderQuery(params, currentShader); + if (sourceToUpdate === "src") { + image.src = `${source.split("?")[0]}?${params.toString()}`; + } else if (sourceToUpdate === "data-src") { + image.dataset.src = `${source.split("?")[0]}?${params.toString()}`; + } + }); + } + if (prevSetting["bodyModel"] !== await import_localforage4.default.getItem("settings_bodyModel")) { + console.log("bodyModel changed!!!"); + askRefreshNotice(); + let bodyType2 = await getSetting("bodyModel"); + document.dispatchEvent(new CustomEvent("library-body-update")); + if (Html.qsa("img[data-src]") !== null) + Html.qsa("img[data-src]").forEach((img) => { + const image = img.elm; + const source = image.src.trim() || image.dataset.src; + let sourceToUpdate = image.src.trim() !== "" ? "src" : "data-src"; + if (!source.includes("?")) + return; + const params = new URLSearchParams(source.split("?").pop()); + params.delete("bodyType"); + params.set("bodyType", bodyType2); + if (sourceToUpdate === "src") { + image.src = `${source.split("?")[0]}?${params.toString()}`; + } else if (sourceToUpdate === "data-src") { + image.dataset.src = `${source.split("?")[0]}?${params.toString()}`; + } + }); + } + await updatePrevSettings(); +}; +var prevSetting = {}; +var prefix = "settings_"; +async function checkPrevSettings() { + for (const key2 in settingsInfo) { + let prefixedKey = prefix + key2; + if (prevSetting[key2] === undefined) { + prevSetting[key2] = await import_localforage4.default.getItem(prefixedKey); + } + } +} +async function updatePrevSettings() { + for (const key2 in settingsInfo) { + let prefixedKey = prefix + key2; + prevSetting[key2] = await import_localforage4.default.getItem(prefixedKey); + } +} +await updatePrevSettings(); +async function Settings() { + const modal = Modal_default.modal(__3("Settings"), "", "body", { + text: "Cancel", + callback(e) { + if (resourceRefreshFlag) { + Modal_default.modal(__3("Notice"), __3("A refresh is required to apply resource changes."), "body", { + text: __3("OK"), + callback(e2) { + location.reload(); + } + }); + } + } + }); + const modalBody = modal.qs(".modal-body").clear(); + modalBody.elm.style.setProperty("align-items", "flex-start", "important"); + modalBody.elm.style.setProperty("max-width", "600px"); + async function checkConditions() { + const items = [...elements]; + const allSettings = {}; + for (const key2 in settingsInfo) { + allSettings[key2] = await getSetting(key2); + } + for (const [key2, element] of items) { + if (settingsInfo[key2].condition) { + let result = settingsInfo[key2].condition(allSettings); + if (result === true) { + element.style.display = "flex"; + } else { + element.style.display = "none"; + } + } + } + } + let elements = new Map; + for (const key2 in settingsInfo) { + let prefixedKey = prefix + key2; + if (await import_localforage4.default.getItem(prefixedKey) === null) { + await import_localforage4.default.setItem(prefixedKey, settingsInfo[key2].default); + } + prevSetting[key2] = await import_localforage4.default.getItem(prefixedKey); + switch (settingsInfo[key2].type) { + case "checkbox": + const checkboxDiv = new Html("div").class("col").appendMany(new Html("div").class("flex-group").style({ "justify-content": "flex-start" }).appendMany(AddButtonSounds(new Html("input").attr({ + id: prefixedKey, + type: "checkbox", + checked: await import_localforage4.default.getItem(prefixedKey) === true ? true : undefined + }).on("input", async (e) => { + prevSetting[key2] = await import_localforage4.default.getItem(prefixedKey); + await import_localforage4.default.setItem(prefixedKey, e.target.checked); + updateSettings(); + checkConditions(); + }), "hover", "select_misc"), new Html("label").attr({ for: prefixedKey }).text(settingsInfo[key2].label)), new Html("small").text(settingsInfo[key2].description)); + elements.set(key2, checkboxDiv.elm); + modalBody.append(checkboxDiv); + break; + case "multi": + const val2 = await import_localforage4.default.getItem(prefixedKey); + let options = await Promise.all(settingsInfo[key2].choices.map(async (c2) => { + let colorSpan = undefined; + let isActive = false; + if (typeof c2.isColor !== "undefined") { + colorSpan = new Html("span").style({ + width: "1.2em", + height: "1.2em", + "border-radius": "6px" + }); + colorSpan.style({ + "background-color": "var(--hover)", + border: "1px solid var(--stroke)" + }); + const value2 = await import_localforage4.default.getItem(prefixedKey); + if (typeof value2 === "string") { + if (value2.startsWith("#")) { + colorSpan.style({ "background-color": value2 }); + isActive = true; + } + } + } + const multiButton = new Html("button").class(c2.value === val2 || isActive ? "selected-setting" : undefined).attr({ "data-setting": prefixedKey }).text(settingsInfo[key2].default === c2.value ? `${c2.label} ${__3("(Default)")}` : c2.label); + if (colorSpan !== undefined) { + colorSpan.prependTo(multiButton); + } + const button = AddButtonSounds(multiButton, "hover", "select_misc"); + if (c2.disabled) { + button.attr({ disabled: true }); + } else { + multiButton.on("click", async (e) => { + prevSetting[key2] = String(await import_localforage4.default.getItem(prefixedKey)); + let isActive2 = false; + if (typeof c2.isColor !== "undefined") { + const color = new Html("input").attr({ type: "color" }).style({ position: "fixed", opacity: "0" }).appendTo("body"); + if (prevSetting[key2].startsWith("#")) { + color.val(prevSetting[key2]); + isActive2 = true; + } + color.elm.click(); + color.on("change", (e2) => { + import_localforage4.default.setItem(prefixedKey, color.getValue()); + if (colorSpan) + colorSpan.style({ "background-color": color.getValue() }); + color.cleanup(); + isActive2 = true; + }); + } else { + await import_localforage4.default.setItem(prefixedKey, c2.value); + } + updateSettings(); + checkConditions(); + const t4 = e.target; + t4.parentElement.querySelectorAll(`[data-setting="${prefixedKey}"]`).forEach((p) => { + p.classList.remove("selected-setting"); + }); + if (c2.isColor !== undefined) { + if (isActive2) { + t4.classList.add("selected-setting"); + } + const color = String(await import_localforage4.default.getItem(prefixedKey)); + if (colorSpan) + colorSpan.style({ "background-color": color }); + } else + t4.classList.add("selected-setting"); + }); + } + return button; + })); + let multiDiv = new Html("div").class("col").appendMany(new Html("label").text(settingsInfo[key2].label), new Html("small").text(settingsInfo[key2].description), new Html("div").class("flex-group").style({ "justify-content": "flex-start" }).appendMany(...options)); + elements.set(key2, multiDiv.elm); + modalBody.append(multiDiv); + break; + case "non-settings-multi": + const nonSettingsMulti = new Html("div").class("col").appendMany(new Html("label").text(settingsInfo[key2].label), new Html("small").text(settingsInfo[key2].description), new Html("div").class("flex-group").style({ "justify-content": "flex-start" }).appendMany(...settingsInfo[key2].choices.map((c2) => { + const button = AddButtonSounds(new Html("button").attr({ disabled: c2.disabled }).class(c2.type).text(c2.label).on("click", async (e) => { + c2.select(); + }), "hover", "select_misc"); + if (c2.disabled) { + button.attr({ disabled: true }); + } + return button; + }))); + if (settingsInfo[key2].render) { + settingsInfo[key2].render(nonSettingsMulti); + } + elements.set(key2, nonSettingsMulti.elm); + modalBody.append(nonSettingsMulti); + break; + } + } + await checkConditions(); +} +async function replayUpdateNotice() { + await setSetting(`has-seen-${Config.version.string}`, false); +} + +// src/util/SettingsHelper.ts +var __4 = _8(); +__4("Low"); +__4("Middle"); +__4("High"); +var settingsInfo = { + bgm: { + type: "checkbox", + label: __4("Enable background music"), + default: true, + description: __4("Toggle background music depending on the theme.") + }, + sfx: { + type: "checkbox", + label: __4("Enable sound effects"), + default: true, + description: __4("Toggle sound effects for buttons and inputs.") + }, + accessibilityFeature: { + type: "checkbox", + label: __4("Enable accessibility features"), + default: false, + description: __4("The editor UI will be tweaked to be more accessible.") + }, + autoCloseCustomRender: { + type: "checkbox", + label: __4("Auto-close custom render menu"), + default: true, + description: __4("The custom render menu will automatically close when pressing save.") + }, + autoCloseQrScan: { + type: "checkbox", + label: __4("Auto-close QR scan menu"), + default: true, + description: __4("The QR code scanner will disappear after a successful scan.") + }, + allowQrCamera: { + type: "checkbox", + label: __4("Allow using camera in QR scanner"), + default: true, + description: __4("When this is disabled, the camera won't be used and some errors may not appear.") + }, + editMode: { + type: "multi", + label: __4("Editing Mode"), + description: __4("Changes the default edit mode option."), + default: "3d", + choices: [ + { label: __4("2D"), value: "2d" }, + { label: __4("3D"), value: "3d" } + ] + }, + theme: { + type: "multi", + label: __4("Theme"), + default: "default", + description: __4("When this is set to Normal, your device's color theme preferences will be used."), + choices: [ + { label: __4("Normal"), value: "default" }, + { label: __4("Wii U"), value: "wiiu", disabled: true } + ] + }, + resourceType: { + type: "multi", + label: __4("Resource Type"), + default: String(Config.renderer.fflResourcePath.length - 1), + description: __4(`This changes model/texture quality. +* Low resource cannot use some shader features.`), + choices: [ + ...Config.renderer.fflResourcesNames.map((n2, i) => ({ + label: __4(n2), + value: String(i) + })) + ] + }, + shaderType: { + type: "multi", + label: __4("Shader Type"), + description: __4("Change the lighting used in icons, renders and the editor."), + default: "wiiu" /* WiiU */, + choices: [ + { label: __4("No Lighting"), value: "lightDisabled" /* LightDisabled */ }, + { label: __4("Simple"), value: "three_phong" /* ThreePhong */ }, + { label: __4("Toon"), value: "three_toon" /* ThreeToon */ }, + { label: __4("Wii U"), value: "wiiu" /* WiiU */ }, + { label: __4("Wii U (Blinn)"), value: "wiiu_blinn" /* WiiUBlinn */ }, + { label: __4("Wii U (Bright)"), value: "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */ }, + { label: __4("Wii U (Toon)"), value: "wiiu_toon" /* WiiUToon */ }, + { label: __4("Miitomo"), value: "miitomo" /* Miitomo */ }, + { label: __4("Miitomo (Basic)"), value: "miitomo_basic" /* MiitomoBasic */ } + ] + }, + bodyModel: { + type: "multi", + label: __4("Body Model"), + description: __4("Pose selections are different depending on the body model you use."), + default: "wiiu" /* WiiU */, + choices: [ + { label: __4("Wii U"), value: "wiiu" /* WiiU */ }, + { label: __4("Switch"), value: "switch" /* Switch */, disabled: true }, + { label: __4("Miitomo"), value: "miitomo" /* Miitomo */ } + ] + }, + bodyModelHands: { + type: "checkbox", + label: __4("Color hands to skin tone"), + default: false, + description: __4("The hands of the body will match the Mii's skin tone."), + condition: (settings) => settings.bodyModel !== "wiiu" + }, + customRenderGreenScreen: { + type: "multi", + label: __4("Use background in custom render"), + default: "off", + description: __4("The custom render will have a solid color background."), + choices: [ + { label: __4("Disabled"), value: "off" }, + { label: __4("Green"), value: "green" }, + { label: __4("Blue"), value: "blue" }, + { label: __4("Black"), value: "black" }, + { label: __4("White"), value: "white" }, + { label: __4("Custom"), value: "custom", isColor: true } + ] + }, + personalMii: { + type: "non-settings-multi", + label: __4("Personal Mii"), + description: __4("Manage your choice of Personal Mii."), + choices: [ + { + label: __4("Choose"), + async select() { + } + } + ] + }, + saveData: { + type: "non-settings-multi", + label: __4("Save Data"), + description: __4("Not implemented yet."), + choices: [ + { + label: __4("Import"), + disabled: true + }, + { + label: __4("Export"), + disabled: true + }, + { + label: __4("Delete"), + type: "danger", + async select() { + }, + disabled: true + } + ] + }, + updateNotices: { + type: "non-settings-multi", + label: __4("Update Notices"), + description: __4("View the last update notice if you missed it."), + choices: [ + { + label: __4("Review update notice"), + select() { + replayUpdateNotice(); + } + } + ] + } +}; +var getSetting = async (key2) => { + const result = await import_localforage5.default.getItem("settings_" + key2); + if (result === null) { + if (settingsInfo[key2]) + return settingsInfo[key2].default; + else + return null; + } else + return result; +}; +var setSetting = async (key2, value2) => { + return await import_localforage5.default.setItem("settings_" + key2, value2); +}; + +// src/util/FFLLoader.ts +var __5 = _8(); +var FFLModule; +var FFLWorker; +var getFFL = () => FFLModule; +var getFFLWorkerExists = () => FFLWorker !== undefined; +var getFFLWorkerMakeIcon = (request, useBlob = true) => { + if (FFLWorker === undefined) + throw new Error("FFL worker told to make icon, but it wasn't initialized"); + return new Promise((resolve, reject2) => { + sendMessageToWorker({ + type: "MakeIcon", + useBlob, + request: { + ...defaultParams, + ...request + } + }).then((resp) => resolve(resp)).catch((err) => reject2(err)); + }); +}; +var sendMessageToWorker; +async function prepareFFL() { + if (Config.renderer.useRendererServer !== false) { + return console.log("why do you"); + } + var m = Modal_default.modal(__5("Notice"), __5("Mii Creator is loading assets, please wait...")); + FFLModule = (await Promise.resolve().then(() => __toESM(require_ffl_emscripten(), 1))).default; + FFLModule = await FFLModule({ + locateFile: (path) => { + return "/dist/" + path; + } + }); + console.log(FFLModule); + console.log("We've got FFL!"); + await loadBodyModels(); + await loadHatModels(); + await loadClothesTextures(); + let { module: module2 } = await initializeFFLWithResource(FFLModule, Config.renderer.fflResourcePath[await getSetting("resourceType")]); + FFLModule = module2; + if (window.Worker) { + if (window.OffscreenCanvas) { + const tempOffscreenCanvas = document.createElement("canvas"); + const offscreenCanvas = tempOffscreenCanvas.transferControlToOffscreen(); + FFLWorker = new Worker("./dist/worker.js", { type: "module" }); + sendMessageToWorker = (data2) => { + return new Promise((resolve, reject2) => { + const requestId = Math.random().toString(36).substring(7); + function handleMessage(event) { + const { id, result, error } = event.data; + if (id === requestId) { + FFLWorker.removeEventListener("message", handleMessage); + if (error) { + Notify_default.show("Worker error", error); + resolve(null); + } else + resolve(result); + } + } + FFLWorker.addEventListener("message", handleMessage); + FFLWorker.postMessage({ id: requestId, ...data2 }); + }); + }; + FFLWorker.postMessage({ + type: "Init", + resourcePath: Config.renderer.fflResourcePath[await getSetting("resourceType")], + offscreenCanvas, + devicePixelRatio: window.devicePixelRatio + }, [offscreenCanvas]); + await new Promise((resolve) => { + FFLWorker.onmessage = (e) => { + if (e.data.ready) { + resolve(); + } + }; + }); + } else { + Modal_default.modal(__5("Notice"), __5("Your browser doesn't support OffscreenCanvas, so Mii Creator may experience lag."), "body", ...buttonsOkCancel); + } + } else { + Modal_default.modal(__5("Notice"), __5("Your browser doesn't support Web Workers, so Mii Creator may experience lag."), "body", ...buttonsOkCancel); + } + console.log("Ready!"); + closeModal(m); +} + +// src/util/miiImageUtils.ts +var makeQrCodeImage = async (mii) => { + let convertedVer3Data, ver3QRData; + const miiU8 = mii.export("ffsd_append_miic"); + convertedVer3Data = new Mii(miiU8).export("ffsd"); + ver3QRData = encryptAndEncodeVer3StoreDataToQRCodeFormat(convertedVer3Data); + ver3QRData = new Uint8Array([...ver3QRData, ...miiU8.subarray(96)]); + const png = import_qrjs_min.default.generatePNG(ver3QRData, { margin: 0 }); + const img = new Image(431, 431); + img.src = URL.createObjectURL(await (await fetch(png)).blob()); + return new Promise((resolve) => { + img.onload = () => { + return resolve(img); + }; + }); +}; +var getBackground = async (extended) => { + let url = ""; + if (extended) { + url = "./assets/images/bg_qr_miic.png"; + } else { + url = "./assets/images/bg_qr_wiiu.png"; + } + const blob = await (await fetch(url)).blob(); + const img = new Image(1280, 720); + img.src = URL.createObjectURL(blob); + return new Promise((resolve) => { + img.onload = () => { + return resolve(img); + }; + }); +}; +function loadImage(url) { + return new Promise((resolve, reject2) => { + const img = new Image; + img.crossOrigin = "anonymous"; + img.src = url; + img.onload = () => { + resolve(img); + }; + img.onerror = (e) => { + reject2(e); + }; + }); +} +var QRCodeCanvas = async (mii, extendedColors = true) => { + let render, renderPos = { y: 0, x: 0, width: 0, height: 0 }; + if (Config.renderer.useRendererServer) { + render = await loadImage(`${Config.renderer.renderFullBodyAltURL}&data=${encodeURIComponent(mii.exportHex("studioData"))}&${Config.renderer.hatTypeParam}=${mii.hatType + 1 + Config.renderer.hatTypeAdd}&${Config.renderer.hatColorParam}=${mii.hatFavoriteColor - 1 + Config.renderer.hatColorAdd}`); + renderPos = { x: 54, y: -54, width: 714, height: 953 }; + } else { + let mii2 = new Mii(mii.export("studioData")); + mii2.beardColor = Ver3HairColorTable[ToVer3HairColorTable[mii2.beardColor]]; + mii2.eyeColor = Ver3EyeColorTable[ToVer3EyeColorTable[mii2.eyeColor]]; + mii2.eyebrowColor = Ver3HairColorTable[ToVer3HairColorTable[mii2.eyebrowColor]]; + mii2.facelineColor = Ver3FacelineColorTable[ToVer3FacelineColorTable[mii2.facelineColor]]; + mii2.glassColor = Ver3GlassColorTable[ToVer3GlassColorTable[mii2.glassColor]]; + mii2.glassType = ToVer3GlassTypeTable[mii2.glassType]; + mii2.hairColor = Ver3HairColorTable[ToVer3HairColorTable[mii2.hairColor]]; + mii2.mouthColor = Ver3MouthColorTable[ToVer3MouthColorTable[mii2.mouthColor]]; + mii2.facePaintColor = -1; + mii2.hatType = -1; + mii2.eyeSclera = 0; + const renderResult = await getFFLWorkerMakeIcon({ + data: mii2.export("studioData"), + additionalInfo: { + favorite: mii2.favorite, + hatCommonColor: mii2.hatCommonColor, + hatFavoriteColor: mii2.hatFavoriteColor, + hatType: mii2.hatType, + pantsColor: mii2.pantsColor, + shirtColor: mii2.shirtColor, + special: mii2.special, + temporary: mii2.temporary, + eyeSclera: mii2.eyeSclera, + wigType: mii2.wigType, + clothesType: mii2.clothesType, + shoesColor: mii2.shoesColor + }, + size: 720, + expression: 0, + type: ViewType2.AllBodySugar + }); + let imageURL = renderResult; + const img = new Image(720, 720); + img.src = imageURL; + render = await new Promise((resolve) => { + img.onload = () => { + return resolve(img); + }; + }); + renderPos = { x: -65, y: -54, width: 952, height: 952 }; + } + console.log("got render"); + const qrCodeSource = await makeQrCodeImage(mii); + const background = await getBackground(extendedColors); + let favoriteIcon = undefined; + if (mii.favorite === 1 || mii.special === 1) { + console.log("loading favorite icon"); + favoriteIcon = await new Promise((resolve) => { + var img = new Image; + img.onload = function() { + resolve(img); + }; + if (mii.favorite === 1) + img.src = "data:image/svg+xml," + encodeURIComponent(EditorIcons_default.favorite); + if (mii.special === 1) + img.src = "data:image/svg+xml," + encodeURIComponent(EditorIcons_default.special); + }); + console.log("loaded favorite icon"); + } + const canvas = document.createElement("canvas"); + canvas.width = 1280; + canvas.height = 720; + const ctx = canvas.getContext("2d"); + ctx.drawImage(background, 0, 0); + ctx.font = '500 24px "NTLG", sans-serif'; + ctx.textAlign = "left"; + ctx.textBaseline = "top"; + ctx.fillStyle = "#cccccc"; + ctx.fillText(`${location.origin}`, 32, 667); + ctx.font = '500 24px "NTLG", sans-serif'; + ctx.textAlign = "right"; + ctx.textBaseline = "top"; + ctx.fillStyle = "#cccccc"; + ctx.fillText(`Made with Mii Creator ${Config.version.string}`, 1248, 667); + ctx.drawImage(render, renderPos.x, renderPos.y, renderPos.width, renderPos.height); + ctx.fillStyle = "#ffffff"; + ctx.beginPath(); + ctx.roundRect(769, 79, 463, 463, [16, 16, 0, 0]); + ctx.fill(); + ctx.drawImage(qrCodeSource, 797, 107, 408, 408); + ctx.fillStyle = "#707070"; + ctx.beginPath(); + ctx.roundRect(769, 542, 463, 99, [0, 0, 16, 16]); + ctx.fill(); + if (favoriteIcon) { + ctx.drawImage(favoriteIcon, 1172, 480, 102, 102); + console.log("drawing favorite icon"); + } + ctx.fillStyle = "#ffffff"; + ctx.textAlign = "center"; + ctx.textBaseline = "middle"; + ctx.font = '500 38px "NTLG", sans-serif'; + ctx.fillText(mii.nickname, 1005, 591); + const canvasPngImage = canvas.toDataURL("png", 100); + return canvasPngImage; +}; +async function createMiiCard(parent2, name2, username, link, message, studioData, extra = "") { + new Html("div").class("flex-group").style({ + gap: "0", + "justify-content": "flex-start", + "text-align": "left" + }).appendMany(new Html("img").attr({ + width: 96, + draggable: "false", + src: await getMiiIcon(studioData, "creditIcon", "creditIcon", 128) + }).style({ width: "96px", height: "96px" }), new Html("div").class("col").style({ gap: "12px", flex: "1" }).appendMany(new Html("small").appendMany(new Html("span").text(name2).style({ + display: "inline", + width: "max-content" + }), AddButtonSounds(new Html("a").text(`(@${username})`).attr({ target: "_blank", href: link }))).style({ display: "flex", gap: "8px" }), new Html("div").html(message))).appendTo(parent2); +} +function createIconCard(parent2, name2, link, message, icon) { + let msg; + if (link !== "") { + msg = new Html("a").attr({ href: link, target: "_blank" }).html(message); + } else { + msg = new Html("div").html(message); + } + new Html("div").class("flex-group").style({ + gap: "0", + "justify-content": "flex-start", + "text-align": "left" + }).appendMany(new Html("div").html(icon).style({ width: "96px", height: "96px" }), new Html("div").class("col").style({ gap: "12px", flex: "1" }).appendMany(new Html("small").appendMany(new Html("span").text(name2).style({ + display: "inline", + width: "max-content" + })).style({ display: "flex", gap: "8px" }), msg)).appendTo(parent2); +} + +// src/util/downloadLink.ts +function downloadLink(url, name2) { + const a2 = document.createElement("a"); + a2.href = url; + a2.download = name2; + document.body.appendChild(a2); + a2.click(); + setTimeout(() => { + a2.remove(); + }, 1000); +} +var link = document.createElement("a"); +function saveBlob(blob, filename) { + if (link.href) { + URL.revokeObjectURL(link.href); + } + link.href = URL.createObjectURL(blob); + link.download = filename || "data.json"; + link.dispatchEvent(new MouseEvent("click")); +} +function saveArrayBuffer(buffer, filename) { + saveBlob(new Blob([buffer], { type: "application/octet-stream" }), filename); +} + +// src/ui/pages/library/select.ts +var import_localforage12 = __toESM(require_localforage(), 1); + +// src/ui/components/TabList.ts +function TabList(tabs, type = 0 /* Square */) { + const tabList = new Html("div").class("tab-list"); + const tabContent = new Html("div").class("tab-content"); + function selectTab(tabElm, tabSelect, update = true) { + if (update !== false) { + tabList.qsa(".tab").forEach((tab) => tab?.classOff("active")); + tabElm.classOn("active"); + tabContent.clear(); + } + tabSelect(tabContent); + } + for (const tab of tabs) { + let tabElm = AddButtonSounds(new Html("div").classOn("tab").html(tab.icon).on("click", async () => { + selectTab(tabElm, tab.select, tab.update); + }).appendTo(tabList), "hover", "select_tab"); + switch (type) { + case 0 /* Square */: + tabElm.classOn("tab-square"); + break; + case 1 /* NotSquare */: + tabElm.classOn("tab-rectangle"); + break; + } + if (typeof tab.type !== "undefined") { + tabElm.classOn(tab.type); + } + } + selectTab(Html.from(tabList.elm.children[0]), tabs[0].select); + return { list: tabList, content: tabContent }; +} + +// node_modules/camera-controls/dist/camera-controls.module.js +/*! + * camera-controls + * https://github.com/yomotsu/camera-controls + * (c) 2017 @yomotsu + * Released under the MIT License. + */ +var MOUSE_BUTTON = { + LEFT: 1, + RIGHT: 2, + MIDDLE: 4 +}; +var ACTION = Object.freeze({ + NONE: 0, + ROTATE: 1, + TRUCK: 2, + OFFSET: 4, + DOLLY: 8, + ZOOM: 16, + TOUCH_ROTATE: 32, + TOUCH_TRUCK: 64, + TOUCH_OFFSET: 128, + TOUCH_DOLLY: 256, + TOUCH_ZOOM: 512, + TOUCH_DOLLY_TRUCK: 1024, + TOUCH_DOLLY_OFFSET: 2048, + TOUCH_DOLLY_ROTATE: 4096, + TOUCH_ZOOM_TRUCK: 8192, + TOUCH_ZOOM_OFFSET: 16384, + TOUCH_ZOOM_ROTATE: 32768 +}); +var DOLLY_DIRECTION = { + NONE: 0, + IN: 1, + OUT: -1 +}; +function isPerspectiveCamera(camera) { + return camera.isPerspectiveCamera; +} +function isOrthographicCamera(camera) { + return camera.isOrthographicCamera; +} +var PI_2 = Math.PI * 2; +var PI_HALF = Math.PI / 2; +var EPSILON = 0.00001; +var DEG2RAD2 = Math.PI / 180; +function clamp3(value2, min, max) { + return Math.max(min, Math.min(max, value2)); +} +function approxZero(number, error = EPSILON) { + return Math.abs(number) < error; +} +function approxEquals(a2, b3, error = EPSILON) { + return approxZero(a2 - b3, error); +} +function roundToStep(value2, step) { + return Math.round(value2 / step) * step; +} +function infinityToMaxNumber(value2) { + if (isFinite(value2)) + return value2; + if (value2 < 0) + return -Number.MAX_VALUE; + return Number.MAX_VALUE; +} +function maxNumberToInfinity(value2) { + if (Math.abs(value2) < Number.MAX_VALUE) + return value2; + return value2 * Infinity; +} +function smoothDamp(current, target, currentVelocityRef, smoothTime, maxSpeed = Infinity, deltaTime) { + smoothTime = Math.max(0.0001, smoothTime); + const omega = 2 / smoothTime; + const x2 = omega * deltaTime; + const exp = 1 / (1 + x2 + 0.48 * x2 * x2 + 0.235 * x2 * x2 * x2); + let change = current - target; + const originalTo = target; + const maxChange = maxSpeed * smoothTime; + change = clamp3(change, -maxChange, maxChange); + target = current - change; + const temp = (currentVelocityRef.value + omega * change) * deltaTime; + currentVelocityRef.value = (currentVelocityRef.value - omega * temp) * exp; + let output = target + (change + temp) * exp; + if (originalTo - current > 0 === output > originalTo) { + output = originalTo; + currentVelocityRef.value = (output - originalTo) / deltaTime; + } + return output; +} +function smoothDampVec3(current, target, currentVelocityRef, smoothTime, maxSpeed = Infinity, deltaTime, out) { + smoothTime = Math.max(0.0001, smoothTime); + const omega = 2 / smoothTime; + const x2 = omega * deltaTime; + const exp = 1 / (1 + x2 + 0.48 * x2 * x2 + 0.235 * x2 * x2 * x2); + let targetX = target.x; + let targetY = target.y; + let targetZ = target.z; + let changeX = current.x - targetX; + let changeY = current.y - targetY; + let changeZ = current.z - targetZ; + const originalToX = targetX; + const originalToY = targetY; + const originalToZ = targetZ; + const maxChange = maxSpeed * smoothTime; + const maxChangeSq = maxChange * maxChange; + const magnitudeSq = changeX * changeX + changeY * changeY + changeZ * changeZ; + if (magnitudeSq > maxChangeSq) { + const magnitude = Math.sqrt(magnitudeSq); + changeX = changeX / magnitude * maxChange; + changeY = changeY / magnitude * maxChange; + changeZ = changeZ / magnitude * maxChange; + } + targetX = current.x - changeX; + targetY = current.y - changeY; + targetZ = current.z - changeZ; + const tempX = (currentVelocityRef.x + omega * changeX) * deltaTime; + const tempY = (currentVelocityRef.y + omega * changeY) * deltaTime; + const tempZ = (currentVelocityRef.z + omega * changeZ) * deltaTime; + currentVelocityRef.x = (currentVelocityRef.x - omega * tempX) * exp; + currentVelocityRef.y = (currentVelocityRef.y - omega * tempY) * exp; + currentVelocityRef.z = (currentVelocityRef.z - omega * tempZ) * exp; + out.x = targetX + (changeX + tempX) * exp; + out.y = targetY + (changeY + tempY) * exp; + out.z = targetZ + (changeZ + tempZ) * exp; + const origMinusCurrentX = originalToX - current.x; + const origMinusCurrentY = originalToY - current.y; + const origMinusCurrentZ = originalToZ - current.z; + const outMinusOrigX = out.x - originalToX; + const outMinusOrigY = out.y - originalToY; + const outMinusOrigZ = out.z - originalToZ; + if (origMinusCurrentX * outMinusOrigX + origMinusCurrentY * outMinusOrigY + origMinusCurrentZ * outMinusOrigZ > 0) { + out.x = originalToX; + out.y = originalToY; + out.z = originalToZ; + currentVelocityRef.x = (out.x - originalToX) / deltaTime; + currentVelocityRef.y = (out.y - originalToY) / deltaTime; + currentVelocityRef.z = (out.z - originalToZ) / deltaTime; + } + return out; +} +function extractClientCoordFromEvent(pointers, out) { + out.set(0, 0); + pointers.forEach((pointer) => { + out.x += pointer.clientX; + out.y += pointer.clientY; + }); + out.x /= pointers.length; + out.y /= pointers.length; +} +function notSupportedInOrthographicCamera(camera, message) { + if (isOrthographicCamera(camera)) { + console.warn(`${message} is not supported in OrthographicCamera`); + return true; + } + return false; +} + +class EventDispatcher2 { + constructor() { + this._listeners = {}; + } + addEventListener(type, listener) { + const listeners = this._listeners; + if (listeners[type] === undefined) + listeners[type] = []; + if (listeners[type].indexOf(listener) === -1) + listeners[type].push(listener); + } + hasEventListener(type, listener) { + const listeners = this._listeners; + return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1; + } + removeEventListener(type, listener) { + const listeners = this._listeners; + const listenerArray = listeners[type]; + if (listenerArray !== undefined) { + const index2 = listenerArray.indexOf(listener); + if (index2 !== -1) + listenerArray.splice(index2, 1); + } + } + removeAllEventListeners(type) { + if (!type) { + this._listeners = {}; + return; + } + if (Array.isArray(this._listeners[type])) + this._listeners[type].length = 0; + } + dispatchEvent(event) { + const listeners = this._listeners; + const listenerArray = listeners[event.type]; + if (listenerArray !== undefined) { + event.target = this; + const array = listenerArray.slice(0); + for (let i = 0, l2 = array.length;i < l2; i++) { + array[i].call(this, event); + } + } + } +} +var _a3; +var VERSION = "2.9.0"; +var TOUCH_DOLLY_FACTOR = 1 / 8; +var isMac = /Mac/.test((_a3 = globalThis === null || globalThis === undefined ? undefined : globalThis.navigator) === null || _a3 === undefined ? undefined : _a3.platform); +var THREE2; +var _ORIGIN; +var _AXIS_Y; +var _AXIS_Z; +var _v27; +var _v3A; +var _v3B; +var _v3C; +var _cameraDirection; +var _xColumn; +var _yColumn; +var _zColumn; +var _deltaTarget; +var _deltaOffset; +var _sphericalA; +var _sphericalB; +var _box3A; +var _box3B; +var _sphere4; +var _quaternionA; +var _quaternionB; +var _rotationMatrix; +var _raycaster4; + +class CameraControls extends EventDispatcher2 { + static install(libs) { + THREE2 = libs.THREE; + _ORIGIN = Object.freeze(new THREE2.Vector3(0, 0, 0)); + _AXIS_Y = Object.freeze(new THREE2.Vector3(0, 1, 0)); + _AXIS_Z = Object.freeze(new THREE2.Vector3(0, 0, 1)); + _v27 = new THREE2.Vector2; + _v3A = new THREE2.Vector3; + _v3B = new THREE2.Vector3; + _v3C = new THREE2.Vector3; + _cameraDirection = new THREE2.Vector3; + _xColumn = new THREE2.Vector3; + _yColumn = new THREE2.Vector3; + _zColumn = new THREE2.Vector3; + _deltaTarget = new THREE2.Vector3; + _deltaOffset = new THREE2.Vector3; + _sphericalA = new THREE2.Spherical; + _sphericalB = new THREE2.Spherical; + _box3A = new THREE2.Box3; + _box3B = new THREE2.Box3; + _sphere4 = new THREE2.Sphere; + _quaternionA = new THREE2.Quaternion; + _quaternionB = new THREE2.Quaternion; + _rotationMatrix = new THREE2.Matrix4; + _raycaster4 = new THREE2.Raycaster; + } + static get ACTION() { + return ACTION; + } + constructor(camera, domElement) { + super(); + this.minPolarAngle = 0; + this.maxPolarAngle = Math.PI; + this.minAzimuthAngle = -Infinity; + this.maxAzimuthAngle = Infinity; + this.minDistance = Number.EPSILON; + this.maxDistance = Infinity; + this.infinityDolly = false; + this.minZoom = 0.01; + this.maxZoom = Infinity; + this.smoothTime = 0.25; + this.draggingSmoothTime = 0.125; + this.maxSpeed = Infinity; + this.azimuthRotateSpeed = 1; + this.polarRotateSpeed = 1; + this.dollySpeed = 1; + this.dollyDragInverted = false; + this.truckSpeed = 2; + this.dollyToCursor = false; + this.dragToOffset = false; + this.verticalDragToForward = false; + this.boundaryFriction = 0; + this.restThreshold = 0.01; + this.colliderMeshes = []; + this.cancel = () => { + }; + this._enabled = true; + this._state = ACTION.NONE; + this._viewport = null; + this._changedDolly = 0; + this._changedZoom = 0; + this._hasRested = true; + this._boundaryEnclosesCamera = false; + this._needsUpdate = true; + this._updatedLastTime = false; + this._elementRect = new DOMRect; + this._isDragging = false; + this._dragNeedsUpdate = true; + this._activePointers = []; + this._lockedPointer = null; + this._interactiveArea = new DOMRect(0, 0, 1, 1); + this._isUserControllingRotate = false; + this._isUserControllingDolly = false; + this._isUserControllingTruck = false; + this._isUserControllingOffset = false; + this._isUserControllingZoom = false; + this._lastDollyDirection = DOLLY_DIRECTION.NONE; + this._thetaVelocity = { value: 0 }; + this._phiVelocity = { value: 0 }; + this._radiusVelocity = { value: 0 }; + this._targetVelocity = new THREE2.Vector3; + this._focalOffsetVelocity = new THREE2.Vector3; + this._zoomVelocity = { value: 0 }; + this._truckInternal = (deltaX, deltaY, dragToOffset) => { + let truckX; + let pedestalY; + if (isPerspectiveCamera(this._camera)) { + const offset = _v3A.copy(this._camera.position).sub(this._target); + const fov2 = this._camera.getEffectiveFOV() * DEG2RAD2; + const targetDistance = offset.length() * Math.tan(fov2 * 0.5); + truckX = this.truckSpeed * deltaX * targetDistance / this._elementRect.height; + pedestalY = this.truckSpeed * deltaY * targetDistance / this._elementRect.height; + } else if (isOrthographicCamera(this._camera)) { + const camera2 = this._camera; + truckX = deltaX * (camera2.right - camera2.left) / camera2.zoom / this._elementRect.width; + pedestalY = deltaY * (camera2.top - camera2.bottom) / camera2.zoom / this._elementRect.height; + } else { + return; + } + if (this.verticalDragToForward) { + dragToOffset ? this.setFocalOffset(this._focalOffsetEnd.x + truckX, this._focalOffsetEnd.y, this._focalOffsetEnd.z, true) : this.truck(truckX, 0, true); + this.forward(-pedestalY, true); + } else { + dragToOffset ? this.setFocalOffset(this._focalOffsetEnd.x + truckX, this._focalOffsetEnd.y + pedestalY, this._focalOffsetEnd.z, true) : this.truck(truckX, pedestalY, true); + } + }; + this._rotateInternal = (deltaX, deltaY) => { + const theta = PI_2 * this.azimuthRotateSpeed * deltaX / this._elementRect.height; + const phi = PI_2 * this.polarRotateSpeed * deltaY / this._elementRect.height; + this.rotate(theta, phi, true); + }; + this._dollyInternal = (delta, x2, y3) => { + const dollyScale = Math.pow(0.95, -delta * this.dollySpeed); + const lastDistance = this._sphericalEnd.radius; + const distance = this._sphericalEnd.radius * dollyScale; + const clampedDistance = clamp3(distance, this.minDistance, this.maxDistance); + const overflowedDistance = clampedDistance - distance; + if (this.infinityDolly && this.dollyToCursor) { + this._dollyToNoClamp(distance, true); + } else if (this.infinityDolly && !this.dollyToCursor) { + this.dollyInFixed(overflowedDistance, true); + this._dollyToNoClamp(clampedDistance, true); + } else { + this._dollyToNoClamp(clampedDistance, true); + } + if (this.dollyToCursor) { + this._changedDolly += (this.infinityDolly ? distance : clampedDistance) - lastDistance; + this._dollyControlCoord.set(x2, y3); + } + this._lastDollyDirection = Math.sign(-delta); + }; + this._zoomInternal = (delta, x2, y3) => { + const zoomScale = Math.pow(0.95, delta * this.dollySpeed); + const lastZoom = this._zoom; + const zoom = this._zoom * zoomScale; + this.zoomTo(zoom, true); + if (this.dollyToCursor) { + this._changedZoom += zoom - lastZoom; + this._dollyControlCoord.set(x2, y3); + } + }; + if (typeof THREE2 === "undefined") { + console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."); + } + this._camera = camera; + this._yAxisUpSpace = new THREE2.Quaternion().setFromUnitVectors(this._camera.up, _AXIS_Y); + this._yAxisUpSpaceInverse = this._yAxisUpSpace.clone().invert(); + this._state = ACTION.NONE; + this._target = new THREE2.Vector3; + this._targetEnd = this._target.clone(); + this._focalOffset = new THREE2.Vector3; + this._focalOffsetEnd = this._focalOffset.clone(); + this._spherical = new THREE2.Spherical().setFromVector3(_v3A.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)); + this._sphericalEnd = this._spherical.clone(); + this._lastDistance = this._spherical.radius; + this._zoom = this._camera.zoom; + this._zoomEnd = this._zoom; + this._lastZoom = this._zoom; + this._nearPlaneCorners = [ + new THREE2.Vector3, + new THREE2.Vector3, + new THREE2.Vector3, + new THREE2.Vector3 + ]; + this._updateNearPlaneCorners(); + this._boundary = new THREE2.Box3(new THREE2.Vector3(-Infinity, -Infinity, -Infinity), new THREE2.Vector3(Infinity, Infinity, Infinity)); + this._cameraUp0 = this._camera.up.clone(); + this._target0 = this._target.clone(); + this._position0 = this._camera.position.clone(); + this._zoom0 = this._zoom; + this._focalOffset0 = this._focalOffset.clone(); + this._dollyControlCoord = new THREE2.Vector2; + this.mouseButtons = { + left: ACTION.ROTATE, + middle: ACTION.DOLLY, + right: ACTION.TRUCK, + wheel: isPerspectiveCamera(this._camera) ? ACTION.DOLLY : isOrthographicCamera(this._camera) ? ACTION.ZOOM : ACTION.NONE + }; + this.touches = { + one: ACTION.TOUCH_ROTATE, + two: isPerspectiveCamera(this._camera) ? ACTION.TOUCH_DOLLY_TRUCK : isOrthographicCamera(this._camera) ? ACTION.TOUCH_ZOOM_TRUCK : ACTION.NONE, + three: ACTION.TOUCH_TRUCK + }; + const dragStartPosition = new THREE2.Vector2; + const lastDragPosition = new THREE2.Vector2; + const dollyStart = new THREE2.Vector2; + const onPointerDown = (event) => { + if (!this._enabled || !this._domElement) + return; + if (this._interactiveArea.left !== 0 || this._interactiveArea.top !== 0 || this._interactiveArea.width !== 1 || this._interactiveArea.height !== 1) { + const elRect = this._domElement.getBoundingClientRect(); + const left = event.clientX / elRect.width; + const top = event.clientY / elRect.height; + if (left < this._interactiveArea.left || left > this._interactiveArea.right || top < this._interactiveArea.top || top > this._interactiveArea.bottom) + return; + } + const mouseButton = event.pointerType !== "mouse" ? null : (event.buttons & MOUSE_BUTTON.LEFT) === MOUSE_BUTTON.LEFT ? MOUSE_BUTTON.LEFT : (event.buttons & MOUSE_BUTTON.MIDDLE) === MOUSE_BUTTON.MIDDLE ? MOUSE_BUTTON.MIDDLE : (event.buttons & MOUSE_BUTTON.RIGHT) === MOUSE_BUTTON.RIGHT ? MOUSE_BUTTON.RIGHT : null; + if (mouseButton !== null) { + const zombiePointer = this._findPointerByMouseButton(mouseButton); + zombiePointer && this._disposePointer(zombiePointer); + } + if ((event.buttons & MOUSE_BUTTON.LEFT) === MOUSE_BUTTON.LEFT && this._lockedPointer) + return; + const pointer = { + pointerId: event.pointerId, + clientX: event.clientX, + clientY: event.clientY, + deltaX: 0, + deltaY: 0, + mouseButton + }; + this._activePointers.push(pointer); + this._domElement.ownerDocument.removeEventListener("pointermove", onPointerMove, { passive: false }); + this._domElement.ownerDocument.removeEventListener("pointerup", onPointerUp); + this._domElement.ownerDocument.addEventListener("pointermove", onPointerMove, { passive: false }); + this._domElement.ownerDocument.addEventListener("pointerup", onPointerUp); + this._isDragging = true; + startDragging(event); + }; + const onPointerMove = (event) => { + if (event.cancelable) + event.preventDefault(); + const pointerId = event.pointerId; + const pointer = this._lockedPointer || this._findPointerById(pointerId); + if (!pointer) + return; + pointer.clientX = event.clientX; + pointer.clientY = event.clientY; + pointer.deltaX = event.movementX; + pointer.deltaY = event.movementY; + this._state = 0; + if (event.pointerType === "touch") { + switch (this._activePointers.length) { + case 1: + this._state = this.touches.one; + break; + case 2: + this._state = this.touches.two; + break; + case 3: + this._state = this.touches.three; + break; + } + } else { + if (!this._isDragging && this._lockedPointer || this._isDragging && (event.buttons & MOUSE_BUTTON.LEFT) === MOUSE_BUTTON.LEFT) { + this._state = this._state | this.mouseButtons.left; + } + if (this._isDragging && (event.buttons & MOUSE_BUTTON.MIDDLE) === MOUSE_BUTTON.MIDDLE) { + this._state = this._state | this.mouseButtons.middle; + } + if (this._isDragging && (event.buttons & MOUSE_BUTTON.RIGHT) === MOUSE_BUTTON.RIGHT) { + this._state = this._state | this.mouseButtons.right; + } + } + dragging(); + }; + const onPointerUp = (event) => { + const pointer = this._findPointerById(event.pointerId); + if (pointer && pointer === this._lockedPointer) + return; + pointer && this._disposePointer(pointer); + if (event.pointerType === "touch") { + switch (this._activePointers.length) { + case 0: + this._state = ACTION.NONE; + break; + case 1: + this._state = this.touches.one; + break; + case 2: + this._state = this.touches.two; + break; + case 3: + this._state = this.touches.three; + break; + } + } else { + this._state = ACTION.NONE; + } + endDragging(); + }; + let lastScrollTimeStamp = -1; + const onMouseWheel = (event) => { + if (!this._domElement) + return; + if (!this._enabled || this.mouseButtons.wheel === ACTION.NONE) + return; + if (this._interactiveArea.left !== 0 || this._interactiveArea.top !== 0 || this._interactiveArea.width !== 1 || this._interactiveArea.height !== 1) { + const elRect = this._domElement.getBoundingClientRect(); + const left = event.clientX / elRect.width; + const top = event.clientY / elRect.height; + if (left < this._interactiveArea.left || left > this._interactiveArea.right || top < this._interactiveArea.top || top > this._interactiveArea.bottom) + return; + } + event.preventDefault(); + if (this.dollyToCursor || this.mouseButtons.wheel === ACTION.ROTATE || this.mouseButtons.wheel === ACTION.TRUCK) { + const now2 = performance.now(); + if (lastScrollTimeStamp - now2 < 1000) + this._getClientRect(this._elementRect); + lastScrollTimeStamp = now2; + } + const deltaYFactor = isMac ? -1 : -3; + const delta = event.deltaMode === 1 ? event.deltaY / deltaYFactor : event.deltaY / (deltaYFactor * 10); + const x2 = this.dollyToCursor ? (event.clientX - this._elementRect.x) / this._elementRect.width * 2 - 1 : 0; + const y3 = this.dollyToCursor ? (event.clientY - this._elementRect.y) / this._elementRect.height * -2 + 1 : 0; + switch (this.mouseButtons.wheel) { + case ACTION.ROTATE: { + this._rotateInternal(event.deltaX, event.deltaY); + this._isUserControllingRotate = true; + break; + } + case ACTION.TRUCK: { + this._truckInternal(event.deltaX, event.deltaY, false); + this._isUserControllingTruck = true; + break; + } + case ACTION.OFFSET: { + this._truckInternal(event.deltaX, event.deltaY, true); + this._isUserControllingOffset = true; + break; + } + case ACTION.DOLLY: { + this._dollyInternal(-delta, x2, y3); + this._isUserControllingDolly = true; + break; + } + case ACTION.ZOOM: { + this._zoomInternal(-delta, x2, y3); + this._isUserControllingZoom = true; + break; + } + } + this.dispatchEvent({ type: "control" }); + }; + const onContextMenu = (event) => { + if (!this._domElement || !this._enabled) + return; + if (this.mouseButtons.right === CameraControls.ACTION.NONE) { + const pointerId = event instanceof PointerEvent ? event.pointerId : 0; + const pointer = this._findPointerById(pointerId); + pointer && this._disposePointer(pointer); + this._domElement.ownerDocument.removeEventListener("pointermove", onPointerMove, { passive: false }); + this._domElement.ownerDocument.removeEventListener("pointerup", onPointerUp); + return; + } + event.preventDefault(); + }; + const startDragging = (event) => { + if (!this._enabled) + return; + extractClientCoordFromEvent(this._activePointers, _v27); + this._getClientRect(this._elementRect); + dragStartPosition.copy(_v27); + lastDragPosition.copy(_v27); + const isMultiTouch = this._activePointers.length >= 2; + if (isMultiTouch) { + const dx = _v27.x - this._activePointers[1].clientX; + const dy2 = _v27.y - this._activePointers[1].clientY; + const distance = Math.sqrt(dx * dx + dy2 * dy2); + dollyStart.set(0, distance); + const x2 = (this._activePointers[0].clientX + this._activePointers[1].clientX) * 0.5; + const y3 = (this._activePointers[0].clientY + this._activePointers[1].clientY) * 0.5; + lastDragPosition.set(x2, y3); + } + this._state = 0; + if (!event) { + if (this._lockedPointer) + this._state = this._state | this.mouseButtons.left; + } else if ("pointerType" in event && event.pointerType === "touch") { + switch (this._activePointers.length) { + case 1: + this._state = this.touches.one; + break; + case 2: + this._state = this.touches.two; + break; + case 3: + this._state = this.touches.three; + break; + } + } else { + if (!this._lockedPointer && (event.buttons & MOUSE_BUTTON.LEFT) === MOUSE_BUTTON.LEFT) { + this._state = this._state | this.mouseButtons.left; + } + if ((event.buttons & MOUSE_BUTTON.MIDDLE) === MOUSE_BUTTON.MIDDLE) { + this._state = this._state | this.mouseButtons.middle; + } + if ((event.buttons & MOUSE_BUTTON.RIGHT) === MOUSE_BUTTON.RIGHT) { + this._state = this._state | this.mouseButtons.right; + } + } + if ((this._state & ACTION.ROTATE) === ACTION.ROTATE || (this._state & ACTION.TOUCH_ROTATE) === ACTION.TOUCH_ROTATE || (this._state & ACTION.TOUCH_DOLLY_ROTATE) === ACTION.TOUCH_DOLLY_ROTATE || (this._state & ACTION.TOUCH_ZOOM_ROTATE) === ACTION.TOUCH_ZOOM_ROTATE) { + this._sphericalEnd.theta = this._spherical.theta; + this._sphericalEnd.phi = this._spherical.phi; + this._thetaVelocity.value = 0; + this._phiVelocity.value = 0; + } + if ((this._state & ACTION.TRUCK) === ACTION.TRUCK || (this._state & ACTION.TOUCH_TRUCK) === ACTION.TOUCH_TRUCK || (this._state & ACTION.TOUCH_DOLLY_TRUCK) === ACTION.TOUCH_DOLLY_TRUCK || (this._state & ACTION.TOUCH_ZOOM_TRUCK) === ACTION.TOUCH_ZOOM_TRUCK) { + this._targetEnd.copy(this._target); + this._targetVelocity.set(0, 0, 0); + } + if ((this._state & ACTION.DOLLY) === ACTION.DOLLY || (this._state & ACTION.TOUCH_DOLLY) === ACTION.TOUCH_DOLLY || (this._state & ACTION.TOUCH_DOLLY_TRUCK) === ACTION.TOUCH_DOLLY_TRUCK || (this._state & ACTION.TOUCH_DOLLY_OFFSET) === ACTION.TOUCH_DOLLY_OFFSET || (this._state & ACTION.TOUCH_DOLLY_ROTATE) === ACTION.TOUCH_DOLLY_ROTATE) { + this._sphericalEnd.radius = this._spherical.radius; + this._radiusVelocity.value = 0; + } + if ((this._state & ACTION.ZOOM) === ACTION.ZOOM || (this._state & ACTION.TOUCH_ZOOM) === ACTION.TOUCH_ZOOM || (this._state & ACTION.TOUCH_ZOOM_TRUCK) === ACTION.TOUCH_ZOOM_TRUCK || (this._state & ACTION.TOUCH_ZOOM_OFFSET) === ACTION.TOUCH_ZOOM_OFFSET || (this._state & ACTION.TOUCH_ZOOM_ROTATE) === ACTION.TOUCH_ZOOM_ROTATE) { + this._zoomEnd = this._zoom; + this._zoomVelocity.value = 0; + } + if ((this._state & ACTION.OFFSET) === ACTION.OFFSET || (this._state & ACTION.TOUCH_OFFSET) === ACTION.TOUCH_OFFSET || (this._state & ACTION.TOUCH_DOLLY_OFFSET) === ACTION.TOUCH_DOLLY_OFFSET || (this._state & ACTION.TOUCH_ZOOM_OFFSET) === ACTION.TOUCH_ZOOM_OFFSET) { + this._focalOffsetEnd.copy(this._focalOffset); + this._focalOffsetVelocity.set(0, 0, 0); + } + this.dispatchEvent({ type: "controlstart" }); + }; + const dragging = () => { + if (!this._enabled || !this._dragNeedsUpdate) + return; + this._dragNeedsUpdate = false; + extractClientCoordFromEvent(this._activePointers, _v27); + const isPointerLockActive = this._domElement && this._domElement.ownerDocument.pointerLockElement === this._domElement; + const lockedPointer = isPointerLockActive ? this._lockedPointer || this._activePointers[0] : null; + const deltaX = lockedPointer ? -lockedPointer.deltaX : lastDragPosition.x - _v27.x; + const deltaY = lockedPointer ? -lockedPointer.deltaY : lastDragPosition.y - _v27.y; + lastDragPosition.copy(_v27); + if ((this._state & ACTION.ROTATE) === ACTION.ROTATE || (this._state & ACTION.TOUCH_ROTATE) === ACTION.TOUCH_ROTATE || (this._state & ACTION.TOUCH_DOLLY_ROTATE) === ACTION.TOUCH_DOLLY_ROTATE || (this._state & ACTION.TOUCH_ZOOM_ROTATE) === ACTION.TOUCH_ZOOM_ROTATE) { + this._rotateInternal(deltaX, deltaY); + this._isUserControllingRotate = true; + } + if ((this._state & ACTION.DOLLY) === ACTION.DOLLY || (this._state & ACTION.ZOOM) === ACTION.ZOOM) { + const dollyX = this.dollyToCursor ? (dragStartPosition.x - this._elementRect.x) / this._elementRect.width * 2 - 1 : 0; + const dollyY = this.dollyToCursor ? (dragStartPosition.y - this._elementRect.y) / this._elementRect.height * -2 + 1 : 0; + const dollyDirection = this.dollyDragInverted ? -1 : 1; + if ((this._state & ACTION.DOLLY) === ACTION.DOLLY) { + this._dollyInternal(dollyDirection * deltaY * TOUCH_DOLLY_FACTOR, dollyX, dollyY); + this._isUserControllingDolly = true; + } else { + this._zoomInternal(dollyDirection * deltaY * TOUCH_DOLLY_FACTOR, dollyX, dollyY); + this._isUserControllingZoom = true; + } + } + if ((this._state & ACTION.TOUCH_DOLLY) === ACTION.TOUCH_DOLLY || (this._state & ACTION.TOUCH_ZOOM) === ACTION.TOUCH_ZOOM || (this._state & ACTION.TOUCH_DOLLY_TRUCK) === ACTION.TOUCH_DOLLY_TRUCK || (this._state & ACTION.TOUCH_ZOOM_TRUCK) === ACTION.TOUCH_ZOOM_TRUCK || (this._state & ACTION.TOUCH_DOLLY_OFFSET) === ACTION.TOUCH_DOLLY_OFFSET || (this._state & ACTION.TOUCH_ZOOM_OFFSET) === ACTION.TOUCH_ZOOM_OFFSET || (this._state & ACTION.TOUCH_DOLLY_ROTATE) === ACTION.TOUCH_DOLLY_ROTATE || (this._state & ACTION.TOUCH_ZOOM_ROTATE) === ACTION.TOUCH_ZOOM_ROTATE) { + const dx = _v27.x - this._activePointers[1].clientX; + const dy2 = _v27.y - this._activePointers[1].clientY; + const distance = Math.sqrt(dx * dx + dy2 * dy2); + const dollyDelta = dollyStart.y - distance; + dollyStart.set(0, distance); + const dollyX = this.dollyToCursor ? (lastDragPosition.x - this._elementRect.x) / this._elementRect.width * 2 - 1 : 0; + const dollyY = this.dollyToCursor ? (lastDragPosition.y - this._elementRect.y) / this._elementRect.height * -2 + 1 : 0; + if ((this._state & ACTION.TOUCH_DOLLY) === ACTION.TOUCH_DOLLY || (this._state & ACTION.TOUCH_DOLLY_ROTATE) === ACTION.TOUCH_DOLLY_ROTATE || (this._state & ACTION.TOUCH_DOLLY_TRUCK) === ACTION.TOUCH_DOLLY_TRUCK || (this._state & ACTION.TOUCH_DOLLY_OFFSET) === ACTION.TOUCH_DOLLY_OFFSET) { + this._dollyInternal(dollyDelta * TOUCH_DOLLY_FACTOR, dollyX, dollyY); + this._isUserControllingDolly = true; + } else { + this._zoomInternal(dollyDelta * TOUCH_DOLLY_FACTOR, dollyX, dollyY); + this._isUserControllingZoom = true; + } + } + if ((this._state & ACTION.TRUCK) === ACTION.TRUCK || (this._state & ACTION.TOUCH_TRUCK) === ACTION.TOUCH_TRUCK || (this._state & ACTION.TOUCH_DOLLY_TRUCK) === ACTION.TOUCH_DOLLY_TRUCK || (this._state & ACTION.TOUCH_ZOOM_TRUCK) === ACTION.TOUCH_ZOOM_TRUCK) { + this._truckInternal(deltaX, deltaY, false); + this._isUserControllingTruck = true; + } + if ((this._state & ACTION.OFFSET) === ACTION.OFFSET || (this._state & ACTION.TOUCH_OFFSET) === ACTION.TOUCH_OFFSET || (this._state & ACTION.TOUCH_DOLLY_OFFSET) === ACTION.TOUCH_DOLLY_OFFSET || (this._state & ACTION.TOUCH_ZOOM_OFFSET) === ACTION.TOUCH_ZOOM_OFFSET) { + this._truckInternal(deltaX, deltaY, true); + this._isUserControllingOffset = true; + } + this.dispatchEvent({ type: "control" }); + }; + const endDragging = () => { + extractClientCoordFromEvent(this._activePointers, _v27); + lastDragPosition.copy(_v27); + this._dragNeedsUpdate = false; + if (this._activePointers.length === 0 || this._activePointers.length === 1 && this._activePointers[0] === this._lockedPointer) { + this._isDragging = false; + } + if (this._activePointers.length === 0 && this._domElement) { + this._domElement.ownerDocument.removeEventListener("pointermove", onPointerMove, { passive: false }); + this._domElement.ownerDocument.removeEventListener("pointerup", onPointerUp); + this.dispatchEvent({ type: "controlend" }); + } + }; + this.lockPointer = () => { + if (!this._enabled || !this._domElement) + return; + this.cancel(); + this._lockedPointer = { + pointerId: -1, + clientX: 0, + clientY: 0, + deltaX: 0, + deltaY: 0, + mouseButton: null + }; + this._activePointers.push(this._lockedPointer); + this._domElement.ownerDocument.removeEventListener("pointermove", onPointerMove, { passive: false }); + this._domElement.ownerDocument.removeEventListener("pointerup", onPointerUp); + this._domElement.requestPointerLock(); + this._domElement.ownerDocument.addEventListener("pointerlockchange", onPointerLockChange); + this._domElement.ownerDocument.addEventListener("pointerlockerror", onPointerLockError); + this._domElement.ownerDocument.addEventListener("pointermove", onPointerMove, { passive: false }); + this._domElement.ownerDocument.addEventListener("pointerup", onPointerUp); + startDragging(); + }; + this.unlockPointer = () => { + var _a4, _b3, _c; + if (this._lockedPointer !== null) { + this._disposePointer(this._lockedPointer); + this._lockedPointer = null; + } + (_a4 = this._domElement) === null || _a4 === undefined || _a4.ownerDocument.exitPointerLock(); + (_b3 = this._domElement) === null || _b3 === undefined || _b3.ownerDocument.removeEventListener("pointerlockchange", onPointerLockChange); + (_c = this._domElement) === null || _c === undefined || _c.ownerDocument.removeEventListener("pointerlockerror", onPointerLockError); + this.cancel(); + }; + const onPointerLockChange = () => { + const isPointerLockActive = this._domElement && this._domElement.ownerDocument.pointerLockElement === this._domElement; + if (!isPointerLockActive) + this.unlockPointer(); + }; + const onPointerLockError = () => { + this.unlockPointer(); + }; + this._addAllEventListeners = (domElement2) => { + this._domElement = domElement2; + this._domElement.style.touchAction = "none"; + this._domElement.style.userSelect = "none"; + this._domElement.style.webkitUserSelect = "none"; + this._domElement.addEventListener("pointerdown", onPointerDown); + this._domElement.addEventListener("pointercancel", onPointerUp); + this._domElement.addEventListener("wheel", onMouseWheel, { passive: false }); + this._domElement.addEventListener("contextmenu", onContextMenu); + }; + this._removeAllEventListeners = () => { + if (!this._domElement) + return; + this._domElement.style.touchAction = ""; + this._domElement.style.userSelect = ""; + this._domElement.style.webkitUserSelect = ""; + this._domElement.removeEventListener("pointerdown", onPointerDown); + this._domElement.removeEventListener("pointercancel", onPointerUp); + this._domElement.removeEventListener("wheel", onMouseWheel, { passive: false }); + this._domElement.removeEventListener("contextmenu", onContextMenu); + this._domElement.ownerDocument.removeEventListener("pointermove", onPointerMove, { passive: false }); + this._domElement.ownerDocument.removeEventListener("pointerup", onPointerUp); + this._domElement.ownerDocument.removeEventListener("pointerlockchange", onPointerLockChange); + this._domElement.ownerDocument.removeEventListener("pointerlockerror", onPointerLockError); + }; + this.cancel = () => { + if (this._state === ACTION.NONE) + return; + this._state = ACTION.NONE; + this._activePointers.length = 0; + endDragging(); + }; + if (domElement) + this.connect(domElement); + this.update(0); + } + get camera() { + return this._camera; + } + set camera(camera) { + this._camera = camera; + this.updateCameraUp(); + this._camera.updateProjectionMatrix(); + this._updateNearPlaneCorners(); + this._needsUpdate = true; + } + get enabled() { + return this._enabled; + } + set enabled(enabled) { + this._enabled = enabled; + if (!this._domElement) + return; + if (enabled) { + this._domElement.style.touchAction = "none"; + this._domElement.style.userSelect = "none"; + this._domElement.style.webkitUserSelect = "none"; + } else { + this.cancel(); + this._domElement.style.touchAction = ""; + this._domElement.style.userSelect = ""; + this._domElement.style.webkitUserSelect = ""; + } + } + get active() { + return !this._hasRested; + } + get currentAction() { + return this._state; + } + get distance() { + return this._spherical.radius; + } + set distance(distance) { + if (this._spherical.radius === distance && this._sphericalEnd.radius === distance) + return; + this._spherical.radius = distance; + this._sphericalEnd.radius = distance; + this._needsUpdate = true; + } + get azimuthAngle() { + return this._spherical.theta; + } + set azimuthAngle(azimuthAngle) { + if (this._spherical.theta === azimuthAngle && this._sphericalEnd.theta === azimuthAngle) + return; + this._spherical.theta = azimuthAngle; + this._sphericalEnd.theta = azimuthAngle; + this._needsUpdate = true; + } + get polarAngle() { + return this._spherical.phi; + } + set polarAngle(polarAngle) { + if (this._spherical.phi === polarAngle && this._sphericalEnd.phi === polarAngle) + return; + this._spherical.phi = polarAngle; + this._sphericalEnd.phi = polarAngle; + this._needsUpdate = true; + } + get boundaryEnclosesCamera() { + return this._boundaryEnclosesCamera; + } + set boundaryEnclosesCamera(boundaryEnclosesCamera) { + this._boundaryEnclosesCamera = boundaryEnclosesCamera; + this._needsUpdate = true; + } + set interactiveArea(interactiveArea) { + this._interactiveArea.width = clamp3(interactiveArea.width, 0, 1); + this._interactiveArea.height = clamp3(interactiveArea.height, 0, 1); + this._interactiveArea.x = clamp3(interactiveArea.x, 0, 1 - this._interactiveArea.width); + this._interactiveArea.y = clamp3(interactiveArea.y, 0, 1 - this._interactiveArea.height); + } + addEventListener(type, listener) { + super.addEventListener(type, listener); + } + removeEventListener(type, listener) { + super.removeEventListener(type, listener); + } + rotate(azimuthAngle, polarAngle, enableTransition = false) { + return this.rotateTo(this._sphericalEnd.theta + azimuthAngle, this._sphericalEnd.phi + polarAngle, enableTransition); + } + rotateAzimuthTo(azimuthAngle, enableTransition = false) { + return this.rotateTo(azimuthAngle, this._sphericalEnd.phi, enableTransition); + } + rotatePolarTo(polarAngle, enableTransition = false) { + return this.rotateTo(this._sphericalEnd.theta, polarAngle, enableTransition); + } + rotateTo(azimuthAngle, polarAngle, enableTransition = false) { + this._isUserControllingRotate = false; + const theta = clamp3(azimuthAngle, this.minAzimuthAngle, this.maxAzimuthAngle); + const phi = clamp3(polarAngle, this.minPolarAngle, this.maxPolarAngle); + this._sphericalEnd.theta = theta; + this._sphericalEnd.phi = phi; + this._sphericalEnd.makeSafe(); + this._needsUpdate = true; + if (!enableTransition) { + this._spherical.theta = this._sphericalEnd.theta; + this._spherical.phi = this._sphericalEnd.phi; + } + const resolveImmediately = !enableTransition || approxEquals(this._spherical.theta, this._sphericalEnd.theta, this.restThreshold) && approxEquals(this._spherical.phi, this._sphericalEnd.phi, this.restThreshold); + return this._createOnRestPromise(resolveImmediately); + } + dolly(distance, enableTransition = false) { + return this.dollyTo(this._sphericalEnd.radius - distance, enableTransition); + } + dollyTo(distance, enableTransition = false) { + this._isUserControllingDolly = false; + this._lastDollyDirection = DOLLY_DIRECTION.NONE; + this._changedDolly = 0; + return this._dollyToNoClamp(clamp3(distance, this.minDistance, this.maxDistance), enableTransition); + } + _dollyToNoClamp(distance, enableTransition = false) { + const lastRadius = this._sphericalEnd.radius; + const hasCollider = this.colliderMeshes.length >= 1; + if (hasCollider) { + const maxDistanceByCollisionTest = this._collisionTest(); + const isCollided = approxEquals(maxDistanceByCollisionTest, this._spherical.radius); + const isDollyIn = lastRadius > distance; + if (!isDollyIn && isCollided) + return Promise.resolve(); + this._sphericalEnd.radius = Math.min(distance, maxDistanceByCollisionTest); + } else { + this._sphericalEnd.radius = distance; + } + this._needsUpdate = true; + if (!enableTransition) { + this._spherical.radius = this._sphericalEnd.radius; + } + const resolveImmediately = !enableTransition || approxEquals(this._spherical.radius, this._sphericalEnd.radius, this.restThreshold); + return this._createOnRestPromise(resolveImmediately); + } + dollyInFixed(distance, enableTransition = false) { + this._targetEnd.add(this._getCameraDirection(_cameraDirection).multiplyScalar(distance)); + if (!enableTransition) { + this._target.copy(this._targetEnd); + } + const resolveImmediately = !enableTransition || approxEquals(this._target.x, this._targetEnd.x, this.restThreshold) && approxEquals(this._target.y, this._targetEnd.y, this.restThreshold) && approxEquals(this._target.z, this._targetEnd.z, this.restThreshold); + return this._createOnRestPromise(resolveImmediately); + } + zoom(zoomStep, enableTransition = false) { + return this.zoomTo(this._zoomEnd + zoomStep, enableTransition); + } + zoomTo(zoom, enableTransition = false) { + this._isUserControllingZoom = false; + this._zoomEnd = clamp3(zoom, this.minZoom, this.maxZoom); + this._needsUpdate = true; + if (!enableTransition) { + this._zoom = this._zoomEnd; + } + const resolveImmediately = !enableTransition || approxEquals(this._zoom, this._zoomEnd, this.restThreshold); + this._changedZoom = 0; + return this._createOnRestPromise(resolveImmediately); + } + pan(x2, y3, enableTransition = false) { + console.warn("`pan` has been renamed to `truck`"); + return this.truck(x2, y3, enableTransition); + } + truck(x2, y3, enableTransition = false) { + this._camera.updateMatrix(); + _xColumn.setFromMatrixColumn(this._camera.matrix, 0); + _yColumn.setFromMatrixColumn(this._camera.matrix, 1); + _xColumn.multiplyScalar(x2); + _yColumn.multiplyScalar(-y3); + const offset = _v3A.copy(_xColumn).add(_yColumn); + const to = _v3B.copy(this._targetEnd).add(offset); + return this.moveTo(to.x, to.y, to.z, enableTransition); + } + forward(distance, enableTransition = false) { + _v3A.setFromMatrixColumn(this._camera.matrix, 0); + _v3A.crossVectors(this._camera.up, _v3A); + _v3A.multiplyScalar(distance); + const to = _v3B.copy(this._targetEnd).add(_v3A); + return this.moveTo(to.x, to.y, to.z, enableTransition); + } + elevate(height2, enableTransition = false) { + _v3A.copy(this._camera.up).multiplyScalar(height2); + return this.moveTo(this._targetEnd.x + _v3A.x, this._targetEnd.y + _v3A.y, this._targetEnd.z + _v3A.z, enableTransition); + } + moveTo(x2, y3, z2, enableTransition = false) { + this._isUserControllingTruck = false; + const offset = _v3A.set(x2, y3, z2).sub(this._targetEnd); + this._encloseToBoundary(this._targetEnd, offset, this.boundaryFriction); + this._needsUpdate = true; + if (!enableTransition) { + this._target.copy(this._targetEnd); + } + const resolveImmediately = !enableTransition || approxEquals(this._target.x, this._targetEnd.x, this.restThreshold) && approxEquals(this._target.y, this._targetEnd.y, this.restThreshold) && approxEquals(this._target.z, this._targetEnd.z, this.restThreshold); + return this._createOnRestPromise(resolveImmediately); + } + lookInDirectionOf(x2, y3, z2, enableTransition = false) { + const point = _v3A.set(x2, y3, z2); + const direction = point.sub(this._targetEnd).normalize(); + const position2 = direction.multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd); + return this.setPosition(position2.x, position2.y, position2.z, enableTransition); + } + fitToBox(box3OrObject, enableTransition, { cover: cover2 = false, paddingLeft = 0, paddingRight = 0, paddingBottom = 0, paddingTop = 0 } = {}) { + const promises = []; + const aabb2 = box3OrObject.isBox3 ? _box3A.copy(box3OrObject) : _box3A.setFromObject(box3OrObject); + if (aabb2.isEmpty()) { + console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"); + Promise.resolve(); + } + const theta = roundToStep(this._sphericalEnd.theta, PI_HALF); + const phi = roundToStep(this._sphericalEnd.phi, PI_HALF); + promises.push(this.rotateTo(theta, phi, enableTransition)); + const normal = _v3A.setFromSpherical(this._sphericalEnd).normalize(); + const rotation2 = _quaternionA.setFromUnitVectors(normal, _AXIS_Z); + const viewFromPolar = approxEquals(Math.abs(normal.y), 1); + if (viewFromPolar) { + rotation2.multiply(_quaternionB.setFromAxisAngle(_AXIS_Y, theta)); + } + rotation2.multiply(this._yAxisUpSpaceInverse); + const bb = _box3B.makeEmpty(); + _v3B.copy(aabb2.min).applyQuaternion(rotation2); + bb.expandByPoint(_v3B); + _v3B.copy(aabb2.min).setX(aabb2.max.x).applyQuaternion(rotation2); + bb.expandByPoint(_v3B); + _v3B.copy(aabb2.min).setY(aabb2.max.y).applyQuaternion(rotation2); + bb.expandByPoint(_v3B); + _v3B.copy(aabb2.max).setZ(aabb2.min.z).applyQuaternion(rotation2); + bb.expandByPoint(_v3B); + _v3B.copy(aabb2.min).setZ(aabb2.max.z).applyQuaternion(rotation2); + bb.expandByPoint(_v3B); + _v3B.copy(aabb2.max).setY(aabb2.min.y).applyQuaternion(rotation2); + bb.expandByPoint(_v3B); + _v3B.copy(aabb2.max).setX(aabb2.min.x).applyQuaternion(rotation2); + bb.expandByPoint(_v3B); + _v3B.copy(aabb2.max).applyQuaternion(rotation2); + bb.expandByPoint(_v3B); + bb.min.x -= paddingLeft; + bb.min.y -= paddingBottom; + bb.max.x += paddingRight; + bb.max.y += paddingTop; + rotation2.setFromUnitVectors(_AXIS_Z, normal); + if (viewFromPolar) { + rotation2.premultiply(_quaternionB.invert()); + } + rotation2.premultiply(this._yAxisUpSpace); + const bbSize = bb.getSize(_v3A); + const center = bb.getCenter(_v3B).applyQuaternion(rotation2); + if (isPerspectiveCamera(this._camera)) { + const distance = this.getDistanceToFitBox(bbSize.x, bbSize.y, bbSize.z, cover2); + promises.push(this.moveTo(center.x, center.y, center.z, enableTransition)); + promises.push(this.dollyTo(distance, enableTransition)); + promises.push(this.setFocalOffset(0, 0, 0, enableTransition)); + } else if (isOrthographicCamera(this._camera)) { + const camera = this._camera; + const width2 = camera.right - camera.left; + const height2 = camera.top - camera.bottom; + const zoom = cover2 ? Math.max(width2 / bbSize.x, height2 / bbSize.y) : Math.min(width2 / bbSize.x, height2 / bbSize.y); + promises.push(this.moveTo(center.x, center.y, center.z, enableTransition)); + promises.push(this.zoomTo(zoom, enableTransition)); + promises.push(this.setFocalOffset(0, 0, 0, enableTransition)); + } + return Promise.all(promises); + } + fitToSphere(sphereOrMesh, enableTransition) { + const promises = []; + const isObject3D = "isObject3D" in sphereOrMesh; + const boundingSphere = isObject3D ? CameraControls.createBoundingSphere(sphereOrMesh, _sphere4) : _sphere4.copy(sphereOrMesh); + promises.push(this.moveTo(boundingSphere.center.x, boundingSphere.center.y, boundingSphere.center.z, enableTransition)); + if (isPerspectiveCamera(this._camera)) { + const distanceToFit = this.getDistanceToFitSphere(boundingSphere.radius); + promises.push(this.dollyTo(distanceToFit, enableTransition)); + } else if (isOrthographicCamera(this._camera)) { + const width2 = this._camera.right - this._camera.left; + const height2 = this._camera.top - this._camera.bottom; + const diameter = 2 * boundingSphere.radius; + const zoom = Math.min(width2 / diameter, height2 / diameter); + promises.push(this.zoomTo(zoom, enableTransition)); + } + promises.push(this.setFocalOffset(0, 0, 0, enableTransition)); + return Promise.all(promises); + } + setLookAt(positionX, positionY, positionZ, targetX, targetY, targetZ, enableTransition = false) { + this._isUserControllingRotate = false; + this._isUserControllingDolly = false; + this._isUserControllingTruck = false; + this._lastDollyDirection = DOLLY_DIRECTION.NONE; + this._changedDolly = 0; + const target = _v3B.set(targetX, targetY, targetZ); + const position2 = _v3A.set(positionX, positionY, positionZ); + this._targetEnd.copy(target); + this._sphericalEnd.setFromVector3(position2.sub(target).applyQuaternion(this._yAxisUpSpace)); + this.normalizeRotations(); + this._needsUpdate = true; + if (!enableTransition) { + this._target.copy(this._targetEnd); + this._spherical.copy(this._sphericalEnd); + } + const resolveImmediately = !enableTransition || approxEquals(this._target.x, this._targetEnd.x, this.restThreshold) && approxEquals(this._target.y, this._targetEnd.y, this.restThreshold) && approxEquals(this._target.z, this._targetEnd.z, this.restThreshold) && approxEquals(this._spherical.theta, this._sphericalEnd.theta, this.restThreshold) && approxEquals(this._spherical.phi, this._sphericalEnd.phi, this.restThreshold) && approxEquals(this._spherical.radius, this._sphericalEnd.radius, this.restThreshold); + return this._createOnRestPromise(resolveImmediately); + } + lerpLookAt(positionAX, positionAY, positionAZ, targetAX, targetAY, targetAZ, positionBX, positionBY, positionBZ, targetBX, targetBY, targetBZ, t4, enableTransition = false) { + this._isUserControllingRotate = false; + this._isUserControllingDolly = false; + this._isUserControllingTruck = false; + this._lastDollyDirection = DOLLY_DIRECTION.NONE; + this._changedDolly = 0; + const targetA = _v3A.set(targetAX, targetAY, targetAZ); + const positionA = _v3B.set(positionAX, positionAY, positionAZ); + _sphericalA.setFromVector3(positionA.sub(targetA).applyQuaternion(this._yAxisUpSpace)); + const targetB = _v3C.set(targetBX, targetBY, targetBZ); + const positionB = _v3B.set(positionBX, positionBY, positionBZ); + _sphericalB.setFromVector3(positionB.sub(targetB).applyQuaternion(this._yAxisUpSpace)); + this._targetEnd.copy(targetA.lerp(targetB, t4)); + const deltaTheta = _sphericalB.theta - _sphericalA.theta; + const deltaPhi = _sphericalB.phi - _sphericalA.phi; + const deltaRadius = _sphericalB.radius - _sphericalA.radius; + this._sphericalEnd.set(_sphericalA.radius + deltaRadius * t4, _sphericalA.phi + deltaPhi * t4, _sphericalA.theta + deltaTheta * t4); + this.normalizeRotations(); + this._needsUpdate = true; + if (!enableTransition) { + this._target.copy(this._targetEnd); + this._spherical.copy(this._sphericalEnd); + } + const resolveImmediately = !enableTransition || approxEquals(this._target.x, this._targetEnd.x, this.restThreshold) && approxEquals(this._target.y, this._targetEnd.y, this.restThreshold) && approxEquals(this._target.z, this._targetEnd.z, this.restThreshold) && approxEquals(this._spherical.theta, this._sphericalEnd.theta, this.restThreshold) && approxEquals(this._spherical.phi, this._sphericalEnd.phi, this.restThreshold) && approxEquals(this._spherical.radius, this._sphericalEnd.radius, this.restThreshold); + return this._createOnRestPromise(resolveImmediately); + } + setPosition(positionX, positionY, positionZ, enableTransition = false) { + return this.setLookAt(positionX, positionY, positionZ, this._targetEnd.x, this._targetEnd.y, this._targetEnd.z, enableTransition); + } + setTarget(targetX, targetY, targetZ, enableTransition = false) { + const pos = this.getPosition(_v3A); + const promise = this.setLookAt(pos.x, pos.y, pos.z, targetX, targetY, targetZ, enableTransition); + this._sphericalEnd.phi = clamp3(this._sphericalEnd.phi, this.minPolarAngle, this.maxPolarAngle); + return promise; + } + setFocalOffset(x2, y3, z2, enableTransition = false) { + this._isUserControllingOffset = false; + this._focalOffsetEnd.set(x2, y3, z2); + this._needsUpdate = true; + if (!enableTransition) + this._focalOffset.copy(this._focalOffsetEnd); + const resolveImmediately = !enableTransition || approxEquals(this._focalOffset.x, this._focalOffsetEnd.x, this.restThreshold) && approxEquals(this._focalOffset.y, this._focalOffsetEnd.y, this.restThreshold) && approxEquals(this._focalOffset.z, this._focalOffsetEnd.z, this.restThreshold); + return this._createOnRestPromise(resolveImmediately); + } + setOrbitPoint(targetX, targetY, targetZ) { + this._camera.updateMatrixWorld(); + _xColumn.setFromMatrixColumn(this._camera.matrixWorldInverse, 0); + _yColumn.setFromMatrixColumn(this._camera.matrixWorldInverse, 1); + _zColumn.setFromMatrixColumn(this._camera.matrixWorldInverse, 2); + const position2 = _v3A.set(targetX, targetY, targetZ); + const distance = position2.distanceTo(this._camera.position); + const cameraToPoint = position2.sub(this._camera.position); + _xColumn.multiplyScalar(cameraToPoint.x); + _yColumn.multiplyScalar(cameraToPoint.y); + _zColumn.multiplyScalar(cameraToPoint.z); + _v3A.copy(_xColumn).add(_yColumn).add(_zColumn); + _v3A.z = _v3A.z + distance; + this.dollyTo(distance, false); + this.setFocalOffset(-_v3A.x, _v3A.y, -_v3A.z, false); + this.moveTo(targetX, targetY, targetZ, false); + } + setBoundary(box3) { + if (!box3) { + this._boundary.min.set(-Infinity, -Infinity, -Infinity); + this._boundary.max.set(Infinity, Infinity, Infinity); + this._needsUpdate = true; + return; + } + this._boundary.copy(box3); + this._boundary.clampPoint(this._targetEnd, this._targetEnd); + this._needsUpdate = true; + } + setViewport(viewportOrX, y3, width2, height2) { + if (viewportOrX === null) { + this._viewport = null; + return; + } + this._viewport = this._viewport || new THREE2.Vector4; + if (typeof viewportOrX === "number") { + this._viewport.set(viewportOrX, y3, width2, height2); + } else { + this._viewport.copy(viewportOrX); + } + } + getDistanceToFitBox(width2, height2, depth, cover2 = false) { + if (notSupportedInOrthographicCamera(this._camera, "getDistanceToFitBox")) + return this._spherical.radius; + const boundingRectAspect = width2 / height2; + const fov2 = this._camera.getEffectiveFOV() * DEG2RAD2; + const aspect2 = this._camera.aspect; + const heightToFit = (cover2 ? boundingRectAspect > aspect2 : boundingRectAspect < aspect2) ? height2 : width2 / aspect2; + return heightToFit * 0.5 / Math.tan(fov2 * 0.5) + depth * 0.5; + } + getDistanceToFitSphere(radius) { + if (notSupportedInOrthographicCamera(this._camera, "getDistanceToFitSphere")) + return this._spherical.radius; + const vFOV = this._camera.getEffectiveFOV() * DEG2RAD2; + const hFOV = Math.atan(Math.tan(vFOV * 0.5) * this._camera.aspect) * 2; + const fov2 = 1 < this._camera.aspect ? vFOV : hFOV; + return radius / Math.sin(fov2 * 0.5); + } + getTarget(out, receiveEndValue = true) { + const _out = !!out && out.isVector3 ? out : new THREE2.Vector3; + return _out.copy(receiveEndValue ? this._targetEnd : this._target); + } + getPosition(out, receiveEndValue = true) { + const _out = !!out && out.isVector3 ? out : new THREE2.Vector3; + return _out.setFromSpherical(receiveEndValue ? this._sphericalEnd : this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(receiveEndValue ? this._targetEnd : this._target); + } + getSpherical(out, receiveEndValue = true) { + const _out = out || new THREE2.Spherical; + return _out.copy(receiveEndValue ? this._sphericalEnd : this._spherical); + } + getFocalOffset(out, receiveEndValue = true) { + const _out = !!out && out.isVector3 ? out : new THREE2.Vector3; + return _out.copy(receiveEndValue ? this._focalOffsetEnd : this._focalOffset); + } + normalizeRotations() { + this._sphericalEnd.theta = this._sphericalEnd.theta % PI_2; + if (this._sphericalEnd.theta < 0) + this._sphericalEnd.theta += PI_2; + this._spherical.theta += PI_2 * Math.round((this._sphericalEnd.theta - this._spherical.theta) / PI_2); + } + stop() { + this._focalOffset.copy(this._focalOffsetEnd); + this._target.copy(this._targetEnd); + this._spherical.copy(this._sphericalEnd); + this._zoom = this._zoomEnd; + } + reset(enableTransition = false) { + if (!approxEquals(this._camera.up.x, this._cameraUp0.x) || !approxEquals(this._camera.up.y, this._cameraUp0.y) || !approxEquals(this._camera.up.z, this._cameraUp0.z)) { + this._camera.up.copy(this._cameraUp0); + const position2 = this.getPosition(_v3A); + this.updateCameraUp(); + this.setPosition(position2.x, position2.y, position2.z); + } + const promises = [ + this.setLookAt(this._position0.x, this._position0.y, this._position0.z, this._target0.x, this._target0.y, this._target0.z, enableTransition), + this.setFocalOffset(this._focalOffset0.x, this._focalOffset0.y, this._focalOffset0.z, enableTransition), + this.zoomTo(this._zoom0, enableTransition) + ]; + return Promise.all(promises); + } + saveState() { + this._cameraUp0.copy(this._camera.up); + this.getTarget(this._target0); + this.getPosition(this._position0); + this._zoom0 = this._zoom; + this._focalOffset0.copy(this._focalOffset); + } + updateCameraUp() { + this._yAxisUpSpace.setFromUnitVectors(this._camera.up, _AXIS_Y); + this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert(); + } + applyCameraUp() { + const cameraDirection = _v3A.subVectors(this._target, this._camera.position).normalize(); + const side = _v3B.crossVectors(cameraDirection, this._camera.up); + this._camera.up.crossVectors(side, cameraDirection).normalize(); + this._camera.updateMatrixWorld(); + const position2 = this.getPosition(_v3A); + this.updateCameraUp(); + this.setPosition(position2.x, position2.y, position2.z); + } + update(delta) { + const deltaTheta = this._sphericalEnd.theta - this._spherical.theta; + const deltaPhi = this._sphericalEnd.phi - this._spherical.phi; + const deltaRadius = this._sphericalEnd.radius - this._spherical.radius; + const deltaTarget = _deltaTarget.subVectors(this._targetEnd, this._target); + const deltaOffset = _deltaOffset.subVectors(this._focalOffsetEnd, this._focalOffset); + const deltaZoom = this._zoomEnd - this._zoom; + if (approxZero(deltaTheta)) { + this._thetaVelocity.value = 0; + this._spherical.theta = this._sphericalEnd.theta; + } else { + const smoothTime = this._isUserControllingRotate ? this.draggingSmoothTime : this.smoothTime; + this._spherical.theta = smoothDamp(this._spherical.theta, this._sphericalEnd.theta, this._thetaVelocity, smoothTime, Infinity, delta); + this._needsUpdate = true; + } + if (approxZero(deltaPhi)) { + this._phiVelocity.value = 0; + this._spherical.phi = this._sphericalEnd.phi; + } else { + const smoothTime = this._isUserControllingRotate ? this.draggingSmoothTime : this.smoothTime; + this._spherical.phi = smoothDamp(this._spherical.phi, this._sphericalEnd.phi, this._phiVelocity, smoothTime, Infinity, delta); + this._needsUpdate = true; + } + if (approxZero(deltaRadius)) { + this._radiusVelocity.value = 0; + this._spherical.radius = this._sphericalEnd.radius; + } else { + const smoothTime = this._isUserControllingDolly ? this.draggingSmoothTime : this.smoothTime; + this._spherical.radius = smoothDamp(this._spherical.radius, this._sphericalEnd.radius, this._radiusVelocity, smoothTime, this.maxSpeed, delta); + this._needsUpdate = true; + } + if (approxZero(deltaTarget.x) && approxZero(deltaTarget.y) && approxZero(deltaTarget.z)) { + this._targetVelocity.set(0, 0, 0); + this._target.copy(this._targetEnd); + } else { + const smoothTime = this._isUserControllingTruck ? this.draggingSmoothTime : this.smoothTime; + smoothDampVec3(this._target, this._targetEnd, this._targetVelocity, smoothTime, this.maxSpeed, delta, this._target); + this._needsUpdate = true; + } + if (approxZero(deltaOffset.x) && approxZero(deltaOffset.y) && approxZero(deltaOffset.z)) { + this._focalOffsetVelocity.set(0, 0, 0); + this._focalOffset.copy(this._focalOffsetEnd); + } else { + const smoothTime = this._isUserControllingOffset ? this.draggingSmoothTime : this.smoothTime; + smoothDampVec3(this._focalOffset, this._focalOffsetEnd, this._focalOffsetVelocity, smoothTime, this.maxSpeed, delta, this._focalOffset); + this._needsUpdate = true; + } + if (approxZero(deltaZoom)) { + this._zoomVelocity.value = 0; + this._zoom = this._zoomEnd; + } else { + const smoothTime = this._isUserControllingZoom ? this.draggingSmoothTime : this.smoothTime; + this._zoom = smoothDamp(this._zoom, this._zoomEnd, this._zoomVelocity, smoothTime, Infinity, delta); + } + if (this.dollyToCursor) { + if (isPerspectiveCamera(this._camera) && this._changedDolly !== 0) { + const dollyControlAmount = this._spherical.radius - this._lastDistance; + const camera = this._camera; + const cameraDirection = this._getCameraDirection(_cameraDirection); + const planeX = _v3A.copy(cameraDirection).cross(camera.up).normalize(); + if (planeX.lengthSq() === 0) + planeX.x = 1; + const planeY = _v3B.crossVectors(planeX, cameraDirection); + const worldToScreen = this._sphericalEnd.radius * Math.tan(camera.getEffectiveFOV() * DEG2RAD2 * 0.5); + const prevRadius = this._sphericalEnd.radius - dollyControlAmount; + const lerpRatio = (prevRadius - this._sphericalEnd.radius) / this._sphericalEnd.radius; + const cursor = _v3C.copy(this._targetEnd).add(planeX.multiplyScalar(this._dollyControlCoord.x * worldToScreen * camera.aspect)).add(planeY.multiplyScalar(this._dollyControlCoord.y * worldToScreen)); + const newTargetEnd = _v3A.copy(this._targetEnd).lerp(cursor, lerpRatio); + const isMin = this._lastDollyDirection === DOLLY_DIRECTION.IN && this._spherical.radius <= this.minDistance; + const isMax = this._lastDollyDirection === DOLLY_DIRECTION.OUT && this.maxDistance <= this._spherical.radius; + if (this.infinityDolly && (isMin || isMax)) { + this._sphericalEnd.radius -= dollyControlAmount; + this._spherical.radius -= dollyControlAmount; + const dollyAmount = _v3B.copy(cameraDirection).multiplyScalar(-dollyControlAmount); + newTargetEnd.add(dollyAmount); + } + this._boundary.clampPoint(newTargetEnd, newTargetEnd); + const targetEndDiff = _v3B.subVectors(newTargetEnd, this._targetEnd); + this._targetEnd.copy(newTargetEnd); + this._target.add(targetEndDiff); + this._changedDolly -= dollyControlAmount; + if (approxZero(this._changedDolly)) + this._changedDolly = 0; + } else if (isOrthographicCamera(this._camera) && this._changedZoom !== 0) { + const dollyControlAmount = this._zoom - this._lastZoom; + const camera = this._camera; + const worldCursorPosition = _v3A.set(this._dollyControlCoord.x, this._dollyControlCoord.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); + const quaternion = _v3B.set(0, 0, -1).applyQuaternion(camera.quaternion); + const cursor = _v3C.copy(worldCursorPosition).add(quaternion.multiplyScalar(-worldCursorPosition.dot(camera.up))); + const prevZoom = this._zoom - dollyControlAmount; + const lerpRatio = -(prevZoom - this._zoom) / this._zoom; + const cameraDirection = this._getCameraDirection(_cameraDirection); + const prevPlaneConstant = this._targetEnd.dot(cameraDirection); + const newTargetEnd = _v3A.copy(this._targetEnd).lerp(cursor, lerpRatio); + const newPlaneConstant = newTargetEnd.dot(cameraDirection); + const pullBack = cameraDirection.multiplyScalar(newPlaneConstant - prevPlaneConstant); + newTargetEnd.sub(pullBack); + this._boundary.clampPoint(newTargetEnd, newTargetEnd); + const targetEndDiff = _v3B.subVectors(newTargetEnd, this._targetEnd); + this._targetEnd.copy(newTargetEnd); + this._target.add(targetEndDiff); + this._changedZoom -= dollyControlAmount; + if (approxZero(this._changedZoom)) + this._changedZoom = 0; + } + } + if (this._camera.zoom !== this._zoom) { + this._camera.zoom = this._zoom; + this._camera.updateProjectionMatrix(); + this._updateNearPlaneCorners(); + this._needsUpdate = true; + } + this._dragNeedsUpdate = true; + const maxDistance = this._collisionTest(); + this._spherical.radius = Math.min(this._spherical.radius, maxDistance); + this._spherical.makeSafe(); + this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target); + this._camera.lookAt(this._target); + const affectOffset = !approxZero(this._focalOffset.x) || !approxZero(this._focalOffset.y) || !approxZero(this._focalOffset.z); + if (affectOffset) { + this._camera.updateMatrixWorld(); + _xColumn.setFromMatrixColumn(this._camera.matrix, 0); + _yColumn.setFromMatrixColumn(this._camera.matrix, 1); + _zColumn.setFromMatrixColumn(this._camera.matrix, 2); + _xColumn.multiplyScalar(this._focalOffset.x); + _yColumn.multiplyScalar(-this._focalOffset.y); + _zColumn.multiplyScalar(this._focalOffset.z); + _v3A.copy(_xColumn).add(_yColumn).add(_zColumn); + this._camera.position.add(_v3A); + } + if (this._boundaryEnclosesCamera) { + this._encloseToBoundary(this._camera.position.copy(this._target), _v3A.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse), 1); + } + const updated = this._needsUpdate; + if (updated && !this._updatedLastTime) { + this._hasRested = false; + this.dispatchEvent({ type: "wake" }); + this.dispatchEvent({ type: "update" }); + } else if (updated) { + this.dispatchEvent({ type: "update" }); + if (approxZero(deltaTheta, this.restThreshold) && approxZero(deltaPhi, this.restThreshold) && approxZero(deltaRadius, this.restThreshold) && approxZero(deltaTarget.x, this.restThreshold) && approxZero(deltaTarget.y, this.restThreshold) && approxZero(deltaTarget.z, this.restThreshold) && approxZero(deltaOffset.x, this.restThreshold) && approxZero(deltaOffset.y, this.restThreshold) && approxZero(deltaOffset.z, this.restThreshold) && approxZero(deltaZoom, this.restThreshold) && !this._hasRested) { + this._hasRested = true; + this.dispatchEvent({ type: "rest" }); + } + } else if (!updated && this._updatedLastTime) { + this.dispatchEvent({ type: "sleep" }); + } + this._lastDistance = this._spherical.radius; + this._lastZoom = this._zoom; + this._updatedLastTime = updated; + this._needsUpdate = false; + return updated; + } + toJSON() { + return JSON.stringify({ + enabled: this._enabled, + minDistance: this.minDistance, + maxDistance: infinityToMaxNumber(this.maxDistance), + minZoom: this.minZoom, + maxZoom: infinityToMaxNumber(this.maxZoom), + minPolarAngle: this.minPolarAngle, + maxPolarAngle: infinityToMaxNumber(this.maxPolarAngle), + minAzimuthAngle: infinityToMaxNumber(this.minAzimuthAngle), + maxAzimuthAngle: infinityToMaxNumber(this.maxAzimuthAngle), + smoothTime: this.smoothTime, + draggingSmoothTime: this.draggingSmoothTime, + dollySpeed: this.dollySpeed, + truckSpeed: this.truckSpeed, + dollyToCursor: this.dollyToCursor, + verticalDragToForward: this.verticalDragToForward, + target: this._targetEnd.toArray(), + position: _v3A.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(), + zoom: this._zoomEnd, + focalOffset: this._focalOffsetEnd.toArray(), + target0: this._target0.toArray(), + position0: this._position0.toArray(), + zoom0: this._zoom0, + focalOffset0: this._focalOffset0.toArray() + }); + } + fromJSON(json, enableTransition = false) { + const obj = JSON.parse(json); + this.enabled = obj.enabled; + this.minDistance = obj.minDistance; + this.maxDistance = maxNumberToInfinity(obj.maxDistance); + this.minZoom = obj.minZoom; + this.maxZoom = maxNumberToInfinity(obj.maxZoom); + this.minPolarAngle = obj.minPolarAngle; + this.maxPolarAngle = maxNumberToInfinity(obj.maxPolarAngle); + this.minAzimuthAngle = maxNumberToInfinity(obj.minAzimuthAngle); + this.maxAzimuthAngle = maxNumberToInfinity(obj.maxAzimuthAngle); + this.smoothTime = obj.smoothTime; + this.draggingSmoothTime = obj.draggingSmoothTime; + this.dollySpeed = obj.dollySpeed; + this.truckSpeed = obj.truckSpeed; + this.dollyToCursor = obj.dollyToCursor; + this.verticalDragToForward = obj.verticalDragToForward; + this._target0.fromArray(obj.target0); + this._position0.fromArray(obj.position0); + this._zoom0 = obj.zoom0; + this._focalOffset0.fromArray(obj.focalOffset0); + this.moveTo(obj.target[0], obj.target[1], obj.target[2], enableTransition); + _sphericalA.setFromVector3(_v3A.fromArray(obj.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)); + this.rotateTo(_sphericalA.theta, _sphericalA.phi, enableTransition); + this.dollyTo(_sphericalA.radius, enableTransition); + this.zoomTo(obj.zoom, enableTransition); + this.setFocalOffset(obj.focalOffset[0], obj.focalOffset[1], obj.focalOffset[2], enableTransition); + this._needsUpdate = true; + } + connect(domElement) { + if (this._domElement) { + console.warn("camera-controls is already connected."); + return; + } + domElement.setAttribute("data-camera-controls-version", VERSION); + this._addAllEventListeners(domElement); + this._getClientRect(this._elementRect); + } + disconnect() { + this.cancel(); + this._removeAllEventListeners(); + if (this._domElement) { + this._domElement.removeAttribute("data-camera-controls-version"); + this._domElement = undefined; + } + } + dispose() { + this.removeAllEventListeners(); + this.disconnect(); + } + _getTargetDirection(out) { + return out.setFromSpherical(this._spherical).divideScalar(this._spherical.radius).applyQuaternion(this._yAxisUpSpaceInverse); + } + _getCameraDirection(out) { + return this._getTargetDirection(out).negate(); + } + _findPointerById(pointerId) { + return this._activePointers.find((activePointer) => activePointer.pointerId === pointerId); + } + _findPointerByMouseButton(mouseButton) { + return this._activePointers.find((activePointer) => activePointer.mouseButton === mouseButton); + } + _disposePointer(pointer) { + this._activePointers.splice(this._activePointers.indexOf(pointer), 1); + } + _encloseToBoundary(position2, offset, friction) { + const offsetLength2 = offset.lengthSq(); + if (offsetLength2 === 0) { + return position2; + } + const newTarget = _v3B.copy(offset).add(position2); + const clampedTarget = this._boundary.clampPoint(newTarget, _v3C); + const deltaClampedTarget = clampedTarget.sub(newTarget); + const deltaClampedTargetLength2 = deltaClampedTarget.lengthSq(); + if (deltaClampedTargetLength2 === 0) { + return position2.add(offset); + } else if (deltaClampedTargetLength2 === offsetLength2) { + return position2; + } else if (friction === 0) { + return position2.add(offset).add(deltaClampedTarget); + } else { + const offsetFactor = 1 + friction * deltaClampedTargetLength2 / offset.dot(deltaClampedTarget); + return position2.add(_v3B.copy(offset).multiplyScalar(offsetFactor)).add(deltaClampedTarget.multiplyScalar(1 - friction)); + } + } + _updateNearPlaneCorners() { + if (isPerspectiveCamera(this._camera)) { + const camera = this._camera; + const near = camera.near; + const fov2 = camera.getEffectiveFOV() * DEG2RAD2; + const heightHalf = Math.tan(fov2 * 0.5) * near; + const widthHalf = heightHalf * camera.aspect; + this._nearPlaneCorners[0].set(-widthHalf, -heightHalf, 0); + this._nearPlaneCorners[1].set(widthHalf, -heightHalf, 0); + this._nearPlaneCorners[2].set(widthHalf, heightHalf, 0); + this._nearPlaneCorners[3].set(-widthHalf, heightHalf, 0); + } else if (isOrthographicCamera(this._camera)) { + const camera = this._camera; + const zoomInv = 1 / camera.zoom; + const left = camera.left * zoomInv; + const right = camera.right * zoomInv; + const top = camera.top * zoomInv; + const bottom = camera.bottom * zoomInv; + this._nearPlaneCorners[0].set(left, top, 0); + this._nearPlaneCorners[1].set(right, top, 0); + this._nearPlaneCorners[2].set(right, bottom, 0); + this._nearPlaneCorners[3].set(left, bottom, 0); + } + } + _collisionTest() { + let distance = Infinity; + const hasCollider = this.colliderMeshes.length >= 1; + if (!hasCollider) + return distance; + if (notSupportedInOrthographicCamera(this._camera, "_collisionTest")) + return distance; + const rayDirection = this._getTargetDirection(_cameraDirection); + _rotationMatrix.lookAt(_ORIGIN, rayDirection, this._camera.up); + for (let i = 0;i < 4; i++) { + const nearPlaneCorner = _v3B.copy(this._nearPlaneCorners[i]); + nearPlaneCorner.applyMatrix4(_rotationMatrix); + const origin = _v3C.addVectors(this._target, nearPlaneCorner); + _raycaster4.set(origin, rayDirection); + _raycaster4.far = this._spherical.radius + 1; + const intersects2 = _raycaster4.intersectObjects(this.colliderMeshes); + if (intersects2.length !== 0 && intersects2[0].distance < distance) { + distance = intersects2[0].distance; + } + } + return distance; + } + _getClientRect(target) { + if (!this._domElement) + return; + const rect = this._domElement.getBoundingClientRect(); + target.x = rect.left; + target.y = rect.top; + if (this._viewport) { + target.x += this._viewport.x; + target.y += rect.height - this._viewport.w - this._viewport.y; + target.width = this._viewport.z; + target.height = this._viewport.w; + } else { + target.width = rect.width; + target.height = rect.height; + } + return target; + } + _createOnRestPromise(resolveImmediately) { + if (resolveImmediately) + return Promise.resolve(); + this._hasRested = false; + this.dispatchEvent({ type: "transitionstart" }); + return new Promise((resolve) => { + const onResolve = () => { + this.removeEventListener("rest", onResolve); + resolve(); + }; + this.addEventListener("rest", onResolve); + }); + } + _addAllEventListeners(_domElement) { + } + _removeAllEventListeners() { + } + get dampingFactor() { + console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."); + return 0; + } + set dampingFactor(_9) { + console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."); + } + get draggingDampingFactor() { + console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."); + return 0; + } + set draggingDampingFactor(_9) { + console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."); + } + static createBoundingSphere(object3d, out = new THREE2.Sphere) { + const boundingSphere = out; + const center = boundingSphere.center; + _box3A.makeEmpty(); + object3d.traverseVisible((object) => { + if (!object.isMesh) + return; + _box3A.expandByObject(object); + }); + _box3A.getCenter(center); + let maxRadiusSq = 0; + object3d.traverseVisible((object) => { + if (!object.isMesh) + return; + const mesh = object; + const geometry = mesh.geometry.clone(); + geometry.applyMatrix4(mesh.matrixWorld); + const bufferGeometry = geometry; + const position2 = bufferGeometry.attributes.position; + for (let i = 0, l2 = position2.count;i < l2; i++) { + _v3A.fromBufferAttribute(position2, i); + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_v3A)); + } + }); + boundingSphere.radius = Math.sqrt(maxRadiusSq); + return boundingSphere; + } +} + +// src/class/3d/effect/SparkleParticle.ts +class SparkleParticle { + scene; + position; + texture; + duration; + particleCount; + timeElapsed; + geometry; + material; + particles; + constructor(scene, position2, texture, duration = 0.2, particleCount = 6) { + this.scene = scene; + this.position = position2; + this.texture = texture; + this.duration = duration; + this.particleCount = particleCount; + this.timeElapsed = 0; + this.initParticles(); + } + initParticles() { + this.geometry = new BufferGeometry; + const positions = []; + const sizes = []; + const minDistance = 1; + for (let i = 0;i < this.particleCount; i++) { + let validPosition = false; + let x2, y3, z2; + while (!validPosition) { + x2 = this.position.x + Math.random() * 5 - 2.5; + y3 = this.position.y + Math.random() * 6.5 - 2.5; + z2 = this.position.z + Math.random() * 5 - 2.5; + validPosition = true; + for (let j2 = 0;j2 < i; j2++) { + const dx = x2 - positions[j2 * 3]; + const dy2 = y3 - positions[j2 * 3 + 1]; + const dz = z2 - positions[j2 * 3 + 2]; + const distance = Math.sqrt(dx * dx + dy2 * dy2 + dz * dz); + if (distance < minDistance) { + validPosition = false; + break; + } + } + } + positions.push(x2, y3, z2); + sizes.push(Math.random() * 5 + 0.1); + } + this.geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + this.geometry.setAttribute("size", new Float32BufferAttribute(sizes, 1)); + this.material = new PointsMaterial({ + size: 4, + map: this.texture, + transparent: true, + blending: AdditiveBlending, + depthWrite: false + }); + this.particles = new Points(this.geometry, this.material); + this.scene.add(this.particles); + } + update(deltaTime) { + this.timeElapsed += deltaTime; + this.material.opacity = 1 - this.timeElapsed / this.duration; + if (this.timeElapsed >= this.duration) { + this.dispose(); + } + return true; + } + dispose() { + this.scene.remove(this.particles); + this.particles.geometry.dispose(); + this.particles.material.dispose(); + return false; + } +} + +// src/util/MiiRendering.ts +var import_FFLShaderMaterial4 = __toESM(require_FFLShaderMaterial(), 1); +async function getHeadModel(mii, rendererRef, modelFlag, texResolution) { + const dataU8 = mii.export("studioData"); + const modelDesc = FFLCharModelDescDefault; + modelDesc.resolution = 512; + modelDesc.allExpressionFlag = new Uint32Array([1, 0, 0]); + if (modelFlag) + modelDesc.modelFlag = FFLModelFlag[modelFlag]; + if (texResolution) + modelDesc.resolution = texResolution; + let currentCharModel; + try { + currentCharModel = createCharModel(dataU8, modelDesc, await getShaderMaterialFromShaderType(), getFFL(), false); + if (mii.eyeSclera === 1 && mii.eyeColor !== 8) { + window.eyeScleraHack = true; + } + currentCharModel._materialTextureClass = import_FFLShaderMaterial4.default; + initCharModelTextures(currentCharModel, rendererRef, import_FFLShaderMaterial4.default); + if (mii.eyeSclera === 1 && mii.eyeColor !== 8) { + window.eyeScleraHack = false; + } + } catch (err) { + currentCharModel = null; + alert(`Error creating/updating CharModel: ${err}`); + console.error("Error creating/updating CharModel:", err); + throw err; + } + const asset = { + extras: { + partsTransform: currentCharModel.partsTransform + } + }; + let scene = new Group; + scene.add(currentCharModel.meshes); + return { + animations: [], + asset, + cameras: [], + parser: {}, + scene, + scenes: [scene], + userData: {}, + CharModel: currentCharModel + }; +} +async function getMaskTex(mii, rendererRef, expressionFlag = new Uint32Array([1, 0, 0])) { + const dataU8 = mii.export("studioData"); + const modelDesc = FFLCharModelDescDefault; + modelDesc.resolution = 1024; + modelDesc.allExpressionFlag = expressionFlag; + let currentCharModel; + var img; + const shaderMaterial = await getShaderMaterialFromShaderType(); + try { + currentCharModel = createCharModel(dataU8, modelDesc, shaderMaterial, getFFL(), false); + img = await new Promise((resolve) => { + if (mii.eyeSclera === 1 && mii.eyeColor !== 8) { + window.eyeScleraHack = true; + } + initCharModelTextures(currentCharModel, rendererRef, import_FFLShaderMaterial4.default); + if (mii.eyeSclera === 1 && mii.eyeColor !== 8) { + window.eyeScleraHack = false; + } + const target = currentCharModel._maskTargets[currentCharModel.expression]; + renderTargetToDataTexture(target, rendererRef).then((r) => { + resolve(r); + }); + }); + } catch (err) { + currentCharModel = null; + alert(`Error creating/updating CharModel: ${err}`); + console.error("Error creating/updating CharModel:", err); + throw err; + } + return { img, model: currentCharModel }; +} + +// src/class/3DScene.ts +var import_jszip3 = __toESM(require_lib(), 1); + +// src/util/scaling.ts +function streetpassHandScaling(body, scaleMul = 1) { + const k4 = 0.2; + var scaleVec = new Vector3; + body.getWorldScale(scaleVec); + const baseHandScaleX = 1 / scaleVec.x; + const baseHandScaleY = 1 / scaleVec.y; + const adjustmentFactor = 1 + k4 * (scaleVec.y - 1); + const adjustedHandScaleY = baseHandScaleY * adjustmentFactor; + body.getObjectByName("handLPs").scale.set(baseHandScaleX, adjustedHandScaleY, baseHandScaleX); + body.getObjectByName("handRPs").scale.set(baseHandScaleX, adjustedHandScaleY, baseHandScaleX); +} + +// src/class/3DScene.ts +class Mii3DScene { + #camera; + #controls; + #textureLoader; + #gltfLoader; + #scene; + #renderer; + #parent; + charModel; + mii; + ready; + headReady; + mixer; + animators; + animations; + setupType; + #initCallback; + type; + cameraPan; + shaderOverride; + bodyModel; + handColor; + shaderType; + simpleShaderLegacyColors; + hatModels; + clothingTextures; + editor; + camSetup; + texResolution; + constructor(mii, parent2, setupType = 0 /* Normal */, initCallback, shaderOverride = false, editor) { + this.animations = new Map; + this.animators = new Map; + this.anim = new Map; + this.#parent = parent2; + this.#scene = new Scene; + this.#camera = new PerspectiveCamera(45, parent2.offsetWidth / parent2.offsetHeight, 0.1, 1000); + this.ready = false; + this.headReady = false; + this.texResolution = 512; + if (initCallback) + this.#initCallback = initCallback; + this.shaderOverride = shaderOverride; + this.editor = editor; + if (setupType === 1 /* Screenshot */) { + this.#renderer = new WebGLRenderer({ + antialias: true, + preserveDrawingBuffer: true, + logarithmicDepthBuffer: true + }); + this.texResolution = 1024; + } else { + this.#renderer = new WebGLRenderer({ antialias: true }); + } + this.#renderer.outputColorSpace = LinearSRGBColorSpace; + this.getRendererElement().classList.add("scene"); + this.setupType = setupType; + getSetting("bodyModel").then((type) => { + this.bodyModel = type; + }); + window.THREE = exports_three_module; + getSetting("shaderType").then((type) => { + this.shaderType = type; + getSetting("simpleShaderLegacyColors").then((val2) => { + this.simpleShaderLegacyColors = val2; + }); + if (type === "lightDisabled" || type.startsWith("wiiu") || type === "switch") { + this.#gltfLoader = new GLTFLoader; + } else { + this.#gltfLoader = new GLTFLoader; + } + if (type === "none") { + const cubeTextureLoader = new CubeTextureLoader; + const environmentMap = cubeTextureLoader.load([ + "./cube_map.png", + "./cube_map.png", + "./cube_map.png", + "./cube_map.png", + "./cube_map.png", + "./cube_map.png" + ]); + this.#scene.environment = environmentMap; + this.#scene.environmentIntensity = 1.25; + const directionalLight = new DirectionalLight(15466239, Math.PI); + directionalLight.position.set(1, 0.1, 1); + this.#scene.add(directionalLight); + const ambientLight = new AmbientLight(6710886, Math.PI / 16); + this.#scene.add(ambientLight); + } else if (type !== "lightDisabled") { + this.#scene.environmentIntensity = 0; + } + this.focusCamera(0 /* MiiHead */, true); + }); + this.#renderer.setSize(512, 512); + this.#renderer.setPixelRatio(window.devicePixelRatio); + CameraControls.install({ THREE: exports_three_module }); + this.#controls = new CameraControls(this.#camera, this.#renderer.domElement); + if (setupType === 0 /* Normal */) { + this.camSetup = async () => { + const canPan = this.cameraPan !== undefined ? this.cameraPan : false; + if (canPan !== true) { + console.log("canPan is not false:", canPan); + this.#controls.mouseButtons.left = CameraControls.ACTION.ROTATE; + this.#controls.mouseButtons.right = CameraControls.ACTION.NONE; + this.#controls.mouseButtons.wheel = CameraControls.ACTION.DOLLY; + this.#controls.touches.one = CameraControls.ACTION.TOUCH_ROTATE; + this.#controls.touches.two = CameraControls.ACTION.TOUCH_DOLLY; + this.#controls.touches.three = CameraControls.ACTION.NONE; + this.#controls.enabled = true; + this.#controls.minDistance = 10; + this.#controls.maxDistance = 35; + this.#controls.minAzimuthAngle = -Math.PI; + this.#controls.maxAzimuthAngle = Math.PI; + this.#controls.zoomTo(1); + this.cameraPan = true; + } else { + console.log("canPan is True:", canPan); + this.#controls.enabled = false; + this.#controls.minDistance = 60; + this.#controls.maxDistance = 140; + this.#controls.minAzimuthAngle = -Math.PI; + this.#controls.maxAzimuthAngle = Math.PI; + this.#controls.dollyTo(380 / 10); + this.#controls.zoomTo(2.5); + this.cameraPan = false; + } + }; + this.camSetup(); + } + if (setupType === 1 /* Screenshot */) { + this.#controls.dollyTo(40); + this.#camera.fov = 30; + this.#controls.minDistance = 8; + this.#controls.maxDistance = 300; + } else { + setTimeout(() => { + this.focusCamera(0 /* MiiHead */, true); + }, 200); + } + this.animators.set("cameraControls", (time2, delta) => { + this.#controls.update(delta); + }); + this.#textureLoader = new TextureLoader; + this.mii = mii; + this.type = this.mii.gender === 0 ? "m" : "f"; + const clock = new Clock; + const animate = (time2) => { + const delta = clock.getDelta(); + try { + this.#renderer.render(this.#scene, this.#camera); + } catch (e) { + console.error(e); + } + this.animators.forEach((f) => f(time2, delta)); + }; + this.#renderer.setClearAlpha(0); + this.#renderer.setAnimationLoop(animate); + this.#camera.aspect = this.#parent.offsetWidth / this.#parent.offsetHeight; + this.#camera.updateProjectionMatrix(); + this.resize(); + } + async#loadZip(path, out, useKeys, type) { + this[out] = []; + const data2 = await fetch(path).then((j2) => j2.blob()); + const zip = await import_jszip3.default.loadAsync(data2); + let promises = []; + const fileList = Object.keys(zip.files); + for (const file of fileList) { + promises.push(zip.files[file].async("blob")); + } + const resolves = await Promise.all(promises); + for (let i = 0;i < fileList.length; i++) { + const url = URL.createObjectURL(resolves[i]); + let result; + if (type === "gltf") { + result = await this.#gltfLoader.loadAsync(url); + } else { + result = await this.#textureLoader.loadAsync(url); + result.flipY = false; + } + if (useKeys) { + const fileName = fileList[i].split("."); + fileName.pop(); + this[out][fileName.join(".")] = result; + } else { + this[out][i] = result; + } + URL.revokeObjectURL(url); + } + } + currentPosition; + focusCamera(part, force = false, transition = true, onlyReturn = false) { + this.#controls.smoothTime = 0.2; + if (this.currentPosition === part && force === false) + return; + this.currentPosition = part; + const pos = new Vector3; + let body = this.#scene.getObjectByName(this.type), head2 = this.#scene.getObjectByName("MiiHead"); + if (part === 1 /* MiiFullBody */) { + if (body !== undefined && head2 !== undefined) { + const box = new Box3().setFromObject(head2); + pos.y = box.max.y / 2; + } + if (onlyReturn === false) { + let minInput = 0, maxInput = 127, minOutput = 38, maxOutput = 40; + this.#controls.moveTo(pos.x, pos.y, pos.z, transition); + this.#controls.rotateTo(0, Math.PI / 2, transition); + if (this.cameraPan === false) { + minOutput = 80; + maxOutput = 96; + } + this.#controls.dollyTo(minOutput + (this.mii.height - minInput) / (maxInput - minInput) * (maxOutput - minOutput), transition); + } + return pos; + } else if (part === 0 /* MiiHead */) { + switch (this.setupType) { + case 0 /* Normal */: + if (body !== undefined) { + const box = new Box3().setFromObject(body); + pos.y = box.max.y - box.min.y; + } + if (onlyReturn === false) { + this.#controls.moveTo(pos.x, pos.y + 2, pos.z, transition); + this.#controls.rotateTo(0, Math.PI / 2, transition); + this.#controls.dollyTo(25, transition); + if (this.cameraPan === false) { + this.#controls.moveTo(pos.x, pos.y + 1.75, pos.z, transition); + this.#controls.dollyTo(65, transition); + } + } + return pos; + case 1 /* Screenshot */: + if (this.getHead() !== undefined) { + const box = new Box3().setFromObject(this.getHead()); + pos.y = box.max.y - box.min.y; + } + this.#controls.moveTo(pos.x, pos.y + 1.75, pos.z, transition); + this.#controls.rotateTo(0, Math.PI / 2, transition); + this.#controls.dollyTo(30, transition); + break; + } + } + } + focusCameraUpdate() { + if (this.ready) + this.camSetup(); + if (this.anim) + switch (this.cameraPan) { + case true: + for (const [_9, anim] of this.anim) { + anim.timeScale = 0.5; + } + break; + case false: + for (const [_9, anim] of this.anim) { + anim.reset(); + anim.timeScale = 0; + } + break; + } + this.focusCamera(this.currentPosition, true, false); + } + playEndingAnimation() { + this.#controls.enabled = false; + this.focusCamera(1 /* MiiFullBody */, true); + let heads = this.#scene.getObjectsByProperty("name", "MiiHead"); + for (const head2 of heads) { + if (Config.renderer.useRendererServer) { + } + this.traverseAddFaceMaterial(head2, `&data=${encodeURIComponent(this.mii.exportHex("studioData"))}&expression=1&width=512`); + } + const type = this.mii.gender == 0 ? "m" : "f"; + this.animators.delete(`animation-${type}`); + this.swapAnimation("Finish"); + getSoundManager().playSound("finish"); + } + resize(width2 = this.#parent.offsetWidth, height2 = this.#parent.offsetHeight) { + this.resizeRendererToDisplaySize(width2, height2); + let zoomValue = 1, widescreen = window.innerWidth > 960, is2DMode = !this.cameraPan; + switch (this.currentPosition) { + case 0 /* MiiHead */: + if (is2DMode) + zoomValue = widescreen ? 2.5 : 3.25; + else + zoomValue = widescreen ? 1 : 1.25; + break; + case 1 /* MiiFullBody */: + if (is2DMode) + zoomValue = widescreen ? 2.5 : 3.25; + else + zoomValue = 1; + break; + } + if (this.setupType !== 1 /* Screenshot */) { + this.#controls.zoomTo(zoomValue, true); + } else + this.#controls.zoomTo(1); + } + resizeRendererToDisplaySize(width2, height2) { + this.#camera.aspect = width2 / height2; + this.#camera.updateProjectionMatrix(); + const canvas = this.#renderer.domElement; + const pixelRatio = window.devicePixelRatio; + const w = Math.floor(canvas.clientWidth * pixelRatio); + const h = Math.floor(canvas.clientHeight * pixelRatio); + this.#renderer.setSize(w, h, false); + } + preparing; + async init() { + if (this.ready) + return; + if (this.preparing) + return; + this.preparing = true; + this.ready = false; + this.getRendererElement().style.opacity = "0"; + await this.#addBody(); + this.updateBody(1 /* ClothingUpdate */); + this.swapAnimation("Wait", true); + await this.#loadZip("./assets/models/hat_models_bundle.zip", "hatModels", false, "gltf"); + await this.#loadZip("./assets/images/mii_clothes_textures_bundle.zip", "clothingTextures", true, "texture"); + this.ready = true; + this.preparing = false; + this.resize(); + this.updateBody(1 /* ClothingUpdate */); + if (this.setupType === 1 /* Screenshot */) { + this.#initCallback && this.#initCallback(this.#renderer); + this.resize(); + requestAnimationFrame(() => { + this.resize(); + }); + setTimeout(() => { + this.resize(); + }, 0); + } else { + this.resize(); + setTimeout(() => { + this.resize(); + this.focusCamera(0 /* MiiHead */, true, false); + }, 500); + } + } + getRendererElement() { + return this.#renderer.domElement; + } + anim; + currentAnim; + initAnimation(mesh, id) { + console.debug("playAnimation() called:", mesh, id); + if (this.mixer === undefined) + this.mixer = new AnimationMixer(this.#scene.getObjectByName("m")); + this.animators.set(id, (_time, delta) => { + try { + this.mixer.update(delta); + } catch (e) { + console.warn(e); + } + }); + } + swapAnimation(newAnim, force = false) { + if (newAnim === this.currentAnim) + return; + console.debug("swapAnimation() called:", newAnim); + if (force !== true) { + for (const [_9, anim] of this.anim) { + anim.fadeOut(0.2); + } + } else { + for (const [_9, anim] of this.anim) { + anim.fadeOut(0).reset().stop(); + } + } + this.currentAnim = newAnim; + let x2 = ["m", "f"]; + for (const key2 of x2) { + let clip; + try { + clip = this.mixer.clipAction(this.animations.get(`${key2}-${newAnim}`), this.#scene.getObjectByName(key2)); + } catch (e) { + return; + } + this.anim.set(key2, clip); + this.anim.get(key2).reset().setEffectiveTimeScale(1).setEffectiveWeight(1); + if (newAnim === "Wait") { + setTimeout(() => { + this.anim.get(key2).timeScale = 0.5; + }, 33.33); + } + if (newAnim === "Finish") { + setTimeout(() => { + this.anim.get(key2).timeScale = 0.8; + }, 33.33); + } + if (force === false) { + this.anim.get(key2).fadeIn(0.2).play(); + } else { + this.anim.get(key2).play(); + } + this.anim.get(key2).timeScale = 1; + } + } + async#addBody() { + console.log("addBody()"); + const setupMiiBody = async (path, type) => { + const glb = await this.#gltfLoader.loadAsync(path); + const clips = glb.animations; + this.mixer = new AnimationMixer(glb.scene.getObjectByName(type)); + for (const anim of clips) { + this.animations.set(`${type}-${anim.name}`, anim); + } + glb.scene.name = `${type}-body-root`; + this.#scene.add(glb.scene); + this.initAnimation(glb.scene.getObjectByName(type), `animation-${type}`); + const gBodyMesh = glb.scene.getObjectByName(`body_${type}`); + gBodyMesh.geometry.userData = { + cullMode: 1, + modulateColor: MiiFavoriteFFLColorLookupTable[this.mii.favoriteColor], + modulateMode: 0, + modulateType: 9 + }; + if (this.shaderOverride) + gBodyMesh.material = new MeshStandardMaterial({ + roughness: 1, + metalness: 1, + color: MiiFavoriteColorLookupTable[this.mii.favoriteColor] + }); + else + traverseMesh(gBodyMesh, this.shaderType); + const gHandsMesh = glb.scene.getObjectByName(`hands_${type}`); + if (gHandsMesh) { + gHandsMesh.geometry.userData = { + cullMode: 1, + modulateColor: MiiFavoriteFFLColorLookupTable[this.mii.favoriteColor], + modulateMode: 0, + modulateType: 9 + }; + if (this.shaderOverride) + gHandsMesh.material = new MeshStandardMaterial({ + roughness: 1, + metalness: 1, + color: MiiFavoriteColorLookupTable[this.mii.favoriteColor] + }); + else { + traverseMesh(gHandsMesh, this.shaderType); + } + } + const gLegsMesh = glb.scene.getObjectByName(`legs_${type}`); + gLegsMesh.geometry.userData = { + cullMode: 1, + modulateColor: cPantsColorGray, + modulateMode: 0, + modulateType: 10 + }; + if (this.shaderOverride) + gLegsMesh.material = new MeshStandardMaterial({ + metalness: 1, + roughness: 1, + color: new Color(this.getPantsColor()[0], this.getPantsColor()[1], this.getPantsColor()[2]) + }); + else + traverseMesh(gLegsMesh, this.shaderType); + if (this.#scene.getObjectByName("m")) + this.#scene.getObjectByName("m").visible = false; + if (this.#scene.getObjectByName("f")) + this.#scene.getObjectByName("f").visible = false; + glb.scene.rotation.set(0, 0, 0); + console.log(`setupBody("${path}", "${type}")`); + }; + const bodyModel = await getSetting("bodyModel"); + const loaders = [ + setupMiiBody(`./assets/models/miiBodyM_${bodyModel}.glb`, "m"), + setupMiiBody(`./assets/models/miiBodyF_${bodyModel}.glb`, "f") + ]; + await Promise.all(loaders); + console.log("READY"); + } + getShirtColor() { + return this.mii.shirtColor !== -1 && this.mii.shirtColor < 100 ? SwitchMiiColorTableSRGB[this.mii.shirtColor] : MiiFavoriteFFLColorLookupTable[this.mii.favoriteColor]; + } + getShoesColor() { + return this.mii.shoesColor !== -1 && this.mii.shoesColor < 100 ? SwitchMiiColorTableSRGB[this.mii.shoesColor] : [1, 1, 1]; + } + getPantsColor() { + if (this.mii.pantsColor !== -1 && this.mii.pantsColor < 100 && !ForbiddenShirtPantColors.includes(this.mii.pantsColor)) { + return SwitchMiiColorTableSRGB[this.mii.pantsColor]; + } + if (this.mii.special) { + return cPantsColorGold; + } + if (this.mii.favorite) { + return cPantsColorRed; + } + if (this.mii.temporary) { + return cPantsColorBlue; + } + return cPantsColorGray; + } + async updateBody(updateType = 0 /* None */) { + if (!this.ready) + return; + this.resize(); + this.type = this.mii.gender === 0 ? "m" : "f"; + const bodyM = this.#scene.getObjectByName("m-body-root"); + const bodyF = this.#scene.getObjectByName("f-body-root"); + if (!bodyM) + return; + if (!bodyF) + return; + const build = this.mii.build; + const height2 = this.mii.height; + let scaleFactors = { x: 0, y: 0, z: 0 }; + switch (Config.mii.scalingMode) { + case "scaleLimit": + let heightFactor = height2 / 128; + scaleFactors.y = heightFactor * 0.55 + 0.6; + scaleFactors.x = heightFactor * 0.3 + 0.6; + scaleFactors.x = (heightFactor * 0.6 + 0.8 - scaleFactors.x) * (build / 128) + scaleFactors.x; + break; + case "scaleLimitClampY": + heightFactor = height2 / 128; + scaleFactors.y = heightFactor * 0.55 + 0.6; + scaleFactors.x = heightFactor * 0.3 + 0.6; + scaleFactors.x = (heightFactor * 0.6 + 0.8 - scaleFactors.x) * (build / 128) + scaleFactors.x; + scaleFactors.y = Math.min(scaleFactors.y, 1); + break; + case "scaleApply": + scaleFactors.x = build * (height2 * 0.003671875 + 0.4) / 128 + height2 * 0.001796875 + 0.4; + scaleFactors.y = height2 * 0.006015625 + 0.5; + break; + } + scaleFactors.z = scaleFactors.x; + window.scaleFactors = scaleFactors; + let body = this.type === "m" ? bodyM : bodyF; + const traverseBones = (object) => { + object.scale.set(scaleFactors.x, scaleFactors.y, scaleFactors.z); + if (this.bodyModel === "streetpass") { + streetpassHandScaling(body); + } + }; + const shaderSetting = await getSetting("shaderType"); + const bodyModel = await getSetting("bodyModel"); + const makeHeadBoneUpdate = (body2) => { + const quaternion = new Quaternion; + const scale2 = new Vector3; + return () => { + let headBone = body2.getObjectByName("head"); + if (headBone === undefined) + headBone = body2.getObjectByName("Head"); + if (!headBone) + return; + headBone.updateMatrixWorld(true); + const position2 = new Vector3; + headBone.matrixWorld.decompose(position2, quaternion, scale2); + if (this.#scene.getObjectByName("MiiHead")) { + this.#scene.getObjectByName("MiiHead").position.copy(position2); + this.#scene.getObjectByName("MiiHead").setRotationFromQuaternion(quaternion); + if (bodyModel === "miitomo") { + this.#scene.getObjectByName("MiiHead").rotation.z -= Math.PI / 2; + } else { + this.#scene.getObjectByName("MiiHead").position.y += 0.1; + } + } + }; + }; + const assignMaterial = async (bodyN, type) => { + const hasShaderApplied = this.shaderOverride === false; + const nBody = bodyN.getObjectByName(type).getObjectByName("body_" + type); + const nLegs = bodyN.getObjectByName(type).getObjectByName("legs_" + type); + const colorHands = await getSetting("bodyModelHands"); + if (updateType === 1 /* ClothingUpdate */) { + if (hasShaderApplied) { + nBody.material.color = new Color(...this.getShirtColor()); + } + if (hasShaderApplied) + nLegs.material.color = new Color(...this.getPantsColor()); + if (this.mii.clothesType !== -1) { + console.log("clothing update"); + let shirtTexture, pantsTexture = null; + const suffix = this.type == "f" ? "F" : ""; + let key2 = `${this.bodyModel}_${ExtClothesList[this.mii.clothesType]}${suffix}`; + let shirtKey = key2; + if (this.bodyModel === "miitomo") { + shirtKey = key2 + "_Top"; + } + switch (ClothesTypeList[this.mii.clothesType]) { + case 0 /* COLOR_MIXED */: { + const colorMixR = new Vector4(...this.getShirtColor(), 1), colorMixG = new Vector4(...this.getShoesColor(), 1), colorMixB = new Vector4(...this.getPantsColor(), 1), colorMixA = this.charModel ? this.charModel.facelineColor : 16711680; + console.log("Shirt Texture Key:", shirtKey); + let tex = await colorMixTexture(this.clothingTextures[shirtKey], colorMixR, colorMixG, colorMixB, colorMixA, this.#renderer); + shirtTexture = await loadBlobTexture(tex); + console.log("loaded shirt texture!"); + break; + } + case 1 /* TEXTURE_COLOR */: { + shirtTexture = this.clothingTextures[shirtKey + suffix]; + break; + } + default: + alert("Something isn't right here"); + throw "???"; + } + this.#renderer.initTexture(shirtTexture); + let nBodyMat = nBody.material; + let nLegsMat = nLegs.material; + nBodyMat.dispose(); + nLegsMat.dispose(); + const params = { + modulateType: 9, + modulateMode: 1, + map: shirtTexture + }; + const newBodyMat = new (await getShaderMaterialFromShaderType())(params); + if (this.bodyModel !== "miitomo") + nBody.material = newBodyMat; + if (this.bodyModel === "miitomo" && pantsTexture !== null) { + const params2 = { + modulateType: 9, + modulateMode: 1, + map: pantsTexture + }; + const newLegsMat = new (await getShaderMaterialFromShaderType())(params2); + nLegs.material = newLegsMat; + } else { + nLegs.material = newBodyMat; + } + console.log("mat changed!", newBodyMat, nBody, nLegs); + } else { + nBody.material = new (await getShaderMaterialFromShaderType())({ + color: new Color(this.getShirtColor()[0], this.getShirtColor()[1], this.getShirtColor()[2]), + modulateMode: 0, + modulateType: 9 + }); + nLegs.material = new (await getShaderMaterialFromShaderType())({ + color: new Color(this.getPantsColor()[0], this.getPantsColor()[1], this.getPantsColor()[2]), + modulateMode: 0, + modulateType: 10 + }); + } + } + const nHands = bodyN.getObjectByName(type).getObjectByName("hands_" + type); + if (nHands) { + if (colorHands === true) { + let desiredColor = [1, 0, 0]; + if (this.mii.facePaintColor !== -1) { + desiredColor = SwitchMiiColorTableSRGB[this.mii.facePaintColor]; + } else { + desiredColor = MiiSwitchSkinColorSRGB[this.mii.facelineColor]; + } + if (hasShaderApplied) { + nHands.material.color = new Color(...desiredColor); + } else if (this.shaderOverride) { + nHands.material.color.set(desiredColor[0], desiredColor[1], desiredColor[2]); + } + this.handColor = desiredColor; + } else { + nHands.material = nBody.material; + } + } + }; + switch (this.mii.gender) { + case 0: + bodyM.getObjectByName("m").visible = true; + bodyF.getObjectByName("f").visible = false; + this.animators.set("head_bone", makeHeadBoneUpdate(bodyM)); + traverseBones(bodyM); + assignMaterial(bodyM, "m"); + break; + case 1: + bodyM.getObjectByName("m").visible = false; + bodyF.getObjectByName("f").visible = true; + this.animators.set("head_bone", makeHeadBoneUpdate(bodyF)); + traverseBones(bodyF); + assignMaterial(bodyF, "f"); + break; + } + if (updateType === 2 /* RepositionCamera */) + requestAnimationFrame(() => { + this.focusCamera(this.currentPosition, true, true, false); + }); + else + requestAnimationFrame(() => { + this.resize(); + }); + } + debugGetScene() { + return this.#scene; + } + fadeIn() { + if (this.setupType === 0 /* Normal */) { + this.getRendererElement().style.opacity = "0"; + setTimeout(() => { + this.getRendererElement().style.opacity = "1"; + }, 500); + } else { + this.getRendererElement().style.opacity = "1"; + } + } + async updateMiiHead(renderPart = 0 /* Head */) { + if (!this.ready) { + console.log("first time loading head"); + } + let head2 = this.#scene.getObjectsByProperty("name", "MiiHead"); + switch (renderPart) { + case 0 /* Head */: + try { + const tmpMii = new Mii(this.mii.export("miic")); + let params = {}; + if (this.mii.hatType !== -1) { + switch (HatTypeList[this.mii.hatType]) { + case 1 /* HAT */: + params["modelType"] = "hat"; + break; + case 2 /* FACE_ONLY */: + params["modelType"] = "face_only"; + break; + case 6 /* BALD */: + tmpMii.hairType = 30; + break; + } + } + params["verifyCharInfo"] = "0"; + let GLB; + if (Config.renderer.useRendererServer) { + GLB = null; + } else { + let modelType = "NORMAL"; + switch (params.modelType) { + case "hat": + modelType = "HAT"; + break; + case "face_only": + modelType = "FACE_ONLY"; + break; + } + GLB = await getHeadModel(tmpMii, this.getRenderer(), modelType, this.texResolution); + } + window.GLB = GLB; + GLB.scene.name = "MiiHead"; + var headScale = 0.14; + GLB.scene.scale.set(headScale, headScale, headScale); + if (head2) { + this.#scene.remove(...head2); + this.#scene.getObjectsByProperty("name", "MiiHead").forEach((obj) => { + obj.parent.remove(obj); + }); + } + console.debug("Adding head to scene"); + this.resize(); + this.#scene.add(GLB.scene); + if (Config.renderer.useRendererServer) + traverseAddShader(GLB.scene, this.shaderType); + let lights = await getSimpleMaterialAddLights(this.shaderType); + cleanupLights(this.#scene); + if (lights) { + lights(this.#scene); + } + console.debug("Traversing shader now"); + const body = this.#scene.getObjectByName(this.type); + let headBone = body.getObjectByName("head"); + if (headBone === undefined) + headBone = body.getObjectByName("Head"); + if (!headBone) + return; + headBone.updateMatrixWorld(true); + const position2 = new Vector3; + const quaternion = new Quaternion; + const scale2 = new Vector3; + headBone.matrixWorld.decompose(position2, quaternion, scale2); + if (GLB.scene) { + GLB.scene.position.copy(position2); + GLB.scene.setRotationFromQuaternion(quaternion); + console.debug("Positioning head to body"); + } + const bodyModelType = this.bodyModel; + if (Config.renderer.useRendererServer === false) { + if (this.charModel) { + if (this.charModel.dispose) { + this.charModel.dispose(); + this.charModel = null; + } + } + this.charModel = GLB.CharModel; + } + if (bodyModelType === "miitomo") { + GLB.scene.rotation.z -= Math.PI / 2; + } + try { + if (this.mii.hatType !== -1) { + let hatModel = this.hatModels[this.mii.hatType].scene.clone(true); + hatModel.name = "HatScene"; + let i = 0; + if (GLB.asset.extras.partsTransform.hatTranslate) { + const vec = GLB.asset.extras.partsTransform.hatTranslate; + hatModel.position.add(vec); + window.hatModel = hatModel; + switch (HatTypeList[this.mii.hatType]) { + case 4 /* SIDE */: + break; + case 3 /* FRONT */: + break; + case 5 /* TOP */: + break; + } + } + let shaderSetting = await getSetting("shaderType"); + hatModel.traverse((o) => { + if (o.name === "HatScene" || o.name === "HatRoot") + return; + if (o.isMesh) { + let m = o; + const mat = m.material; + let tableToPullFrom = MiiFavoriteColorVec3Table; + if (shaderSetting === "none") { + tableToPullFrom = MiiFavoriteColorVec3Table; + if (this.simpleShaderLegacyColors === true) { + tableToPullFrom = MiiFavoriteColorVec3Table; + } + } + m.material = new MeshBasicMaterial({ + color: 16777215, + map: mat.map + }); + m.material.needsUpdate = true; + m.geometry.userData = { + cullMode: 0, + modulateColor: this.mii.hatCommonColor !== -1 && this.mii.hatCommonColor < 100 ? SwitchMiiColorTableSRGB[this.mii.hatCommonColor] : MiiFavoriteColorVec3Table[this.mii.hatFavoriteColor !== -1 ? this.mii.hatFavoriteColor : this.mii.favoriteColor], + modulateMode: 5, + modulateType: 5 + }; + i++; + if (Config.renderer.useRendererServer === false) { + traverseMesh(m, this.shaderType); + } + } + }); + GLB.scene.add(hatModel); + } + } catch (e) { + console.error("Hat type resulted in an error, but we're not going to let that stop the head from rendering!", e); + } + } catch (e) { + console.error(e); + } + break; + case 1 /* Face */: + if (head2.length > 0) { + head2.forEach((h) => { + this.traverseAddFaceMaterial(h, `&data=${encodeURIComponent(this.mii.exportHex("studioData"))}&width=512`); + }); + } + break; + } + if (this.headReady === false) + this.fadeIn(); + this.headReady = true; + this.resize(); + } + particles; + lastSparkleTime; + sparkle() { + if (!this.particles) + this.particles = []; + if (!this.lastSparkleTime) + this.lastSparkleTime = 0; + if (performance.now() - this.lastSparkleTime < 150) { + return; + } + this.lastSparkleTime = performance.now(); + this.#textureLoader.load("./assets/images/star.png", (texture) => { + const pos = new Vector3; + const box = new Box3; + if (this.#scene.getObjectByName("MiiHead") !== undefined) { + this.#scene.getObjectByName("MiiHead").getWorldPosition(pos); + box.setFromObject(this.#scene.getObjectByName("MiiHead")); + } + let particle = new SparkleParticle(this.#scene, new Vector3(0, pos.y + box.min.y / 2, 2), texture); + this.particles.push(particle); + this.animators.set("particle_" + performance.now(), (_t, delta) => particle.update(delta)); + setTimeout(() => { + this.particles.forEach((p, i) => { + p.dispose(); + }); + this.particles = []; + Array.from(this.animators.keys()).filter((p) => p.startsWith("particle_")).forEach((key2) => { + this.animators.delete(key2); + }); + }, 1000); + }); + } + getHead() { + return this.#scene.getObjectByName("MiiHead"); + } + traverseAddFaceMaterial(node, urlParams) { + node.traverse((c2) => { + let child = c2; + if (child.isMesh) { + if (child.geometry.userData) { + const data2 = child.geometry.userData; + if (data2.modulateMode) { + if (data2.modulateType === 6) { + (async () => { + const mat = child.material; + const oldMat = mat; + var loadUrl = Config.renderer.renderFaceURL + urlParams; + let tex; + if (Config.renderer.useRendererServer === false) { + console.log("READY"); + const params = new URLSearchParams(urlParams); + let expressionFlag = new Uint32Array([ + 1, + 0, + 0 + ]); + if (params.has("expression")) { + expressionFlag = makeExpressionFlag(Number(params.get("expression"))); + } + console.log("Expression:", params.get("expression"), expressionFlag); + const { img, model } = await getMaskTex(this.mii, this.getRenderer(), expressionFlag); + console.log("DONE"); + loadUrl = null; + tex = img; + model.dispose(); + } else { + tex = await this.#textureLoader.loadAsync(loadUrl); + } + if (tex) { + tex.flipY = false; + this.#renderer.initTexture(tex); + child.material.map = tex; + child.material.transparent = true; + oldMat.dispose(); + } + })(); + } + } + } + } + }); + } + getCamera() { + return this.#camera; + } + getControls() { + return this.#controls; + } + getScene() { + return this.#scene; + } + getRenderer() { + return this.#renderer; + } + shutdown() { + Array.from(this.animators.keys()).forEach((k4) => { + this.animators.delete(k4); + }); + } +} + +// src/ui/components/MiiPagedFeatureSet.ts +var import_md5 = __toESM(require_md5(), 1); +var playHoverSound = () => playSound("hover"); +function MiiPagedFeatureSet(set) { + let tmpMii; + if (set.mii) + if (set.miiIsNotMii === undefined || set.miiIsNotMii === false) + tmpMii = new Mii(set.mii.export()); + else + tmpMii = set.mii; + else + tmpMii = {}; + let setContainer = new Html("div").class("feature-set-container"); + const tabListInit = []; + for (const key2 in set.entries) { + const entry = set.entries[key2]; + let property2 = key2; + tabListInit.push({ + icon: entry.label, + async select(content2) { + let setList = new Html("div").class("feature-set-group").appendTo(content2); + if (entry.header) { + const header = new Html("div").class("feature-set-header"); + if (entry.headerIsHtml !== undefined) { + header.append(entry.header); + } else { + header.text(entry.header); + } + setList.append(header); + } + if ("items" in entry) { + for (const item of entry.items) { + const id = import_md5.default(String(Math.random() * 21412855)); + let forceRender = true, updateType = 0 /* None */; + if (item.forceRender !== undefined) { + if (item.forceRender === false) { + forceRender = false; + } + } + if (item.bodyUpdateType !== undefined) { + if (item.bodyUpdateType !== 0 /* None */) { + updateType = item.bodyUpdateType; + } + } + const update = () => set.onChange(tmpMii, forceRender, item.part || 0 /* Head */, updateType); + let value2 = tmpMii[property2]; + switch (item.type) { + case 0 /* Icon */: + let iconSelected = false; + if (item.selectedCondition) + if (item.selectedCondition() === true) + iconSelected = true; + else + iconSelected = false; + if (item.property) { + if (Array.isArray(item.property)) { + let tmpValue = tmpMii[item.property[0]]; + if (item.property.map((i) => tmpMii[i]).every((i) => i === tmpValue)) + value2 = tmpValue; + else { + value2 = false; + iconSelected = false; + } + } else + value2 = tmpMii[item.property]; + } + let featureItem = new Html("div").class("feature-item").on("pointerenter", playHoverSound).on("click", async () => { + let value3; + if (MiiEditor2.getCurrentEditor() !== null) { + tmpMii = MiiEditor2.getCurrentEditor().mii; + } + value3 = tmpMii[property2]; + const newValue = item.value; + if (item.selectedCondition) + if (item.selectedCondition() === true) + iconSelected = true; + else + iconSelected = false; + console.log(`condition check: value (${value3}) === newValue (${newValue}), iconSelected (${iconSelected})`); + if (value3 === newValue || iconSelected) + return; + if (item.preSelectCallback) + item.preSelectCallback(tmpMii); + if (item.property) { + if (Array.isArray(item.property)) { + for (const prop of item.property) { + tmpMii[prop] = newValue; + } + } else { + tmpMii[item.property] = newValue; + } + } else { + tmpMii[key2] = newValue; + } + update(); + if (item.sound) + playSound(item.sound); + else if (item.color) + playSound("select_color"); + else if (item.icon) + playSound("select_part"); + setList.qsa(".feature-item").forEach((i) => i.classOff("active")); + featureItem.classOn("active"); + }).appendTo(setList); + if (item.icon) { + featureItem.html(item.icon); + } + if (item.color) { + featureItem.classOn("is-color").style({ "--color": item.color }); + } + if (value2 === item.value || iconSelected) { + if (item.property) { + if (Array.isArray(item.property)) { + if (item.property.map((i) => tmpMii[i]).every((i) => i === value2) === false) { + console.log("FAILED CHECK, skipping"); + debugger; + continue; + } + } + } + featureItem.classOn("active"); + } + break; + case 3 /* Slider */: + if (item.label !== undefined) { + new Html("span").text(item.label).appendTo(setList); + } + let featureSliderItem = new Html("div").class("feature-slider").on("pointerenter", playHoverSound).appendTo(setList); + if (item.iconStart) { + let frontIcon = new Html("span").html(item.iconStart).on("click", () => { + if (MiiEditor2.getCurrentEditor() !== null) { + tmpMii = MiiEditor2.getCurrentEditor().mii; + } + featureSlider.val(Number(featureSlider.getValue()) - 1); + tmpMii[item.property] = Number(featureSlider.getValue()); + if (item.soundStart) + playSound(item.soundStart); + else + playSound("select"); + update(); + }); + featureSliderItem.append(frontIcon); + } + let featureSlider = new Html("input").attr({ + type: "range", + min: item.min, + max: item.max + }).id(id).appendTo(featureSliderItem); + if (item.iconEnd) { + let backIcon = new Html("span").html(item.iconEnd).on("click", () => { + if (MiiEditor2.getCurrentEditor() !== null) { + tmpMii = MiiEditor2.getCurrentEditor().mii; + } + featureSlider.val(Number(featureSlider.getValue()) + 1); + tmpMii[item.property] = Number(featureSlider.getValue()); + if (item.soundEnd) + playSound(item.soundEnd); + else + playSound("select"); + update(); + }); + featureSliderItem.append(backIcon); + } + featureSlider.val(tmpMii[item.property]); + featureSlider.on("input", () => { + if (MiiEditor2.getCurrentEditor() !== null) { + tmpMii = MiiEditor2.getCurrentEditor().mii; + } + playSound("slider_tick"); + tmpMii[item.property] = Number(featureSlider.getValue()); + update(); + }); + break; + case 2 /* Range */: + let featureRangeGroup = new Html("div").class("col").style({ width: "100%", gap: "0", "align-items": "center" }).appendTo(setList); + if (item.label !== undefined) { + new Html("span").text(item.label).appendTo(featureRangeGroup); + } + let featureRangeItem = new Html("div").class("feature-slider").appendTo(featureRangeGroup); + if (item.iconStart) { + let frontIcon = new Html("span").html(item.iconStart).on("click", () => { + if (MiiEditor2.getCurrentEditor() !== null) { + tmpMii = MiiEditor2.getCurrentEditor().mii; + } + featureRange.val(Number(featureRange.getValue()) + (item.inverse ? 1 : -1)); + tmpMii[item.property] = item.inverse ? item.max + item.min - Number(featureRange.getValue()) : Number(featureRange.getValue()); + if (item.soundStart) + playSound(item.soundStart); + else + playSound("select"); + update(); + }); + if (item.inverse) + featureRangeItem.prepend(frontIcon); + else + featureRangeItem.append(frontIcon); + } + let featureRange = new Html("input").attr({ + type: "range", + min: item.min, + max: item.max + }).id(id); + if (item.inverse) + featureRangeItem.prepend(featureRange); + else + featureRangeItem.append(featureRange); + if (item.iconEnd) { + let backIcon = new Html("span").html(item.iconEnd).on("click", () => { + if (MiiEditor2.getCurrentEditor() !== null) { + tmpMii = MiiEditor2.getCurrentEditor().mii; + } + featureRange.val(Number(featureRange.getValue()) + (item.inverse ? -1 : 1)); + tmpMii[item.property] = item.inverse ? item.max + item.min - Number(featureRange.getValue()) : Number(featureRange.getValue()); + if (item.soundEnd) + playSound(item.soundEnd); + else + playSound("select"); + update(); + }); + if (item.inverse) + featureRangeItem.prepend(backIcon); + else + featureRangeItem.append(backIcon); + } + featureRange.val(item.inverse ? item.max - tmpMii[item.property] + item.min : tmpMii[item.property]); + featureRange.on("change", () => { + if (MiiEditor2.getCurrentEditor() !== null) { + tmpMii = MiiEditor2.getCurrentEditor().mii; + } + const newValue = item.inverse ? item.max + item.min - Number(featureRange.getValue()) : Number(featureRange.getValue()); + const current = tmpMii[item.property]; + if (item.soundStart !== undefined && item.soundEnd !== undefined) { + if (newValue < current) { + playSound(item.soundStart); + } else { + playSound(item.soundEnd); + } + } + tmpMii[item.property] = newValue; + update(); + }); + featureRange.on("input", () => { + playSound("slider_tick"); + }); + break; + case 4 /* Switch */: + let featureSwitchItem = new Html("div").class("feature-switch-group").appendTo(setList); + let featureSwitch = new Html("div").class("feature-switch").id(id).appendTo(featureSwitchItem); + let buttonLeft = new Html("button").class("feature-switch-left").html(item.iconOff).appendTo(featureSwitch); + let buttonRight = new Html("button").class("feature-switch-right").html(item.iconOn).appendTo(featureSwitch); + const switchToggle = (value3) => { + if (MiiEditor2.getCurrentEditor() !== null) { + tmpMii = MiiEditor2.getCurrentEditor().mii; + } + let valueToSet = value3; + if (item.isNumber) { + valueToSet = Number(valueToSet); + } + tmpMii[item.property] = valueToSet; + if (value3 === false) { + if (item.soundOff) + playSound(item.soundOff); + else + playSound("select"); + } + if (value3 === true) { + if (item.soundOn) + playSound(item.soundOn); + else + playSound("select"); + } + update(); + }; + buttonLeft.on("click", () => { + switchToggle(false); + buttonLeft.classOn("active"); + buttonRight.classOff("active"); + }); + buttonRight.on("click", () => { + switchToggle(true); + buttonLeft.classOff("active"); + buttonRight.classOn("active"); + }); + buttonLeft.on("pointerenter", playHoverSound); + buttonRight.on("pointerenter", playHoverSound); + if (tmpMii[item.property] == true) { + buttonLeft.classOff("active"); + buttonRight.classOn("active"); + } else { + buttonLeft.classOn("active"); + buttonRight.classOff("active"); + } + break; + case 5 /* Misc */: + let featureMiscItem = item.html.appendTo(setList); + featureMiscItem.on("click", item.select); + break; + } + } + } + window.LazyLoad.update(); + } + }); + } + if (Object.keys(set.entries).length === 1) { + let tabs = TabList(tabListInit, 1 /* NotSquare */); + tabs.list.appendTo(setContainer); + tabs.content.appendTo(setContainer); + } else { + let tabs = TabList(tabListInit, 1 /* NotSquare */); + tabs.list.appendTo(setContainer); + tabs.content.appendTo(setContainer); + } + return setContainer; +} + +// src/constants/MiiFeatureTable.ts +var MiiEyeTable = [ + [2, 4, 0, 8, 39, 17, 1, 26, 16, 15, 27, 20], + [33, 11, 19, 32, 9, 12, 23, 34, 21, 25, 40, 35], + [5, 41, 13, 36, 37, 6, 24, 30, 31, 18, 28, 46], + [7, 44, 38, 42, 45, 29, 3, 43, 22, 10, 14, 47], + [48, 49, 50, 53, 59, 56, 54, 58, 57, 55, 51, 52] +]; +var MiiEyebrowTable = [ + [6, 0, 12, 1, 9, 19, 7, 21, 8, 17, 5, 4], + [11, 10, 2, 3, 14, 20, 15, 13, 22, 18, 16, 23] +]; +var MiiMouthTable = [ + [23, 1, 19, 21, 22, 5, 0, 8, 10, 16, 6, 13], + [7, 9, 2, 17, 3, 4, 15, 11, 20, 18, 14, 12], + [27, 30, 24, 25, 29, 28, 26, 35, 31, 34, 33, 32] +]; +var MiiNoseTable = [ + [1, 10, 2, 3, 6, 0, 5, 4, 8, 9, 7, 11], + [13, 14, 12, 17, 16, 15] +]; +var MiiHairTable = [ + [33, 47, 40, 37, 32, 107, 48, 51, 55, 70, 44, 66], + [52, 50, 38, 49, 43, 31, 56, 68, 62, 115, 76, 119], + [64, 81, 116, 121, 22, 58, 60, 87, 125, 117, 73, 75], + [42, 89, 57, 54, 80, 34, 23, 86, 88, 118, 39, 36], + [45, 67, 59, 65, 41, 30, 12, 16, 10, 82, 128, 129], + [14, 95, 105, 100, 6, 20, 93, 102, 27, 4, 17, 110], + [123, 8, 106, 72, 3, 21, 0, 98, 63, 90, 11, 120], + [5, 74, 108, 94, 124, 25, 99, 69, 35, 13, 122, 113], + [53, 24, 85, 83, 71, 131, 96, 101, 29, 7, 15, 112], + [79, 1, 109, 127, 91, 26, 61, 103, 2, 77, 18, 92], + [84, 9, 19, 130, 97, 104, 46, 78, 28, 114, 126, 111] +]; +var MiiSwitchColorTable = [ + [2, 24, 10, 23, 15, 20, 21, 25, 26, 27], + [28, 29, 30, 31, 32, 33, 34, 35, 36, 37], + [38, 39, 40, 41, 42, 43, 44, 45, 46, 47], + [48, 16, 49, 12, 50, 51, 52, 53, 54, 55], + [56, 57, 58, 59, 13, 60, 61, 62, 63, 64], + [65, 66, 67, 68, 69, 70, 71, 72, 73, 74], + [5, 11, 75, 76, 77, 78, 79, 80, 81, 82], + [14, 83, 6, 17, 7, 84, 85, 86, 87, 88], + [1, 3, 89, 19, 90, 91, 22, 92, 93, 94], + [8, 0, 95, 9, 18, 4, 96, 97, 98, 99] +]; +var MiiSwitchSkinColorTable = [ + [0, 7, 1, 4, 5], + [6, 3, 2, 8, 9] +]; +var MiiEyeRotationGroups = [ + -1, + 0, + 0, + 0, + -1, + 0, + 0, + 0, + -1, + 0, + 0, + 0, + 0, + -1, + -1, + 0, + 0, + 0, + 0, + -1, + 0, + 0, + 0, + -1, + -1, + 0, + -1, + 0, + 0, + -1, + 0, + 0, + 0, + -1, + -1, + -1, + 0, + 0, + -1, + -1, + -1, + 0, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 0, + 0, + -1, + 0, + 0, + -1 +]; +var MiiEyebrowRotationGroups = [ + 0, + 0, + -1, + 1, + 0, + 1, + 0, + 1, + -2, + 1, + 0, + 2, + -1, + -1, + 0, + 0, + 1, + 1, + 0, + 0, + -1, + 0, + 1, + 0 +]; +function rearrangeArray(array, lookupTable, separator = makeSeparatorGapThinDesktop) { + let rearrangedArray = []; + if (Array.isArray(lookupTable) && Array.isArray(lookupTable[0])) { + for (const page of lookupTable) { + let pageItems = page.map((index2) => array[index2]).filter((i) => i !== undefined); + if (rearrangedArray.length > 0 && pageItems.length > 0) { + rearrangedArray.push(separator()); + } + rearrangedArray.push(...pageItems); + } + } else { + for (const realIndex in lookupTable) { + const lookupIndex = lookupTable[realIndex]; + rearrangedArray[parseInt(realIndex)] = array[lookupIndex]; + } + rearrangedArray = rearrangedArray.filter((i) => i !== undefined); + } + return rearrangedArray; +} +var makeSeparatorFSI = () => ({ + type: 5 /* Misc */, + html: new Html("div").class("separator"), + select() { + } +}); +var makeSeparatorGapThinFSI = () => ({ + type: 5 /* Misc */, + html: new Html("div").class("separator-gap-thin"), + select() { + } +}); +var makeSeparatorGapThinDesktop = () => ({ + type: 5 /* Misc */, + html: new Html("div").class("separator-gap-thin-desktop"), + select() { + } +}); +var makeSeparatorGapThinLaptop = () => ({ + type: 5 /* Misc */, + html: new Html("div").class("separator-gap-thin-laptop"), + select() { + } +}); + +// src/ui/tabs/Eye.ts +var __6 = _8(); +function EyeTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: data2.callback, + entries: { + eyeType: { + label: __6("Type"), + items: rearrangeArray(ArrayNum(60).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + icon: data2.icons.eyes[k4], + part: 1 /* Face */, + preSelectCallback(tmpMii) { + tmpMii.eyeRotate += MiiEyeRotationGroups[k4] - MiiEyeRotationGroups[tmpMii.eyeType]; + } + })), MiiEyeTable, makeSeparatorGapThinDesktop) + }, + eyeColor: { + label: data2.useAccessibility ? __6("Color") : EditorIcons_default.color, + items: [ + ...ArrayNum(6).map((k4) => ({ + type: 0 /* Icon */, + value: Ver3EyeColorTable[k4], + color: SwitchMiiColorTable[Ver3EyeColorTable[k4]], + part: 1 /* Face */ + })), + makeSeparatorFSI(), + ...rearrangeArray(ArrayNum(100).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + color: SwitchMiiColorTable[k4], + part: 1 /* Face */ + })), MiiSwitchColorTable, makeSeparatorGapThinLaptop) + ] + }, + eyeSclera: { + label: __6("Sclera"), + items: [ + { + type: 4 /* Switch */, + part: 1 /* Face */, + iconOff: __6("Disabled"), + iconOn: __6("Enabled"), + property: "eyeSclera", + isNumber: true + } + ], + header: __6("%1 is a CUSTOM property, and will not transfer to any other data formats.", __6("Sclera fill")) + }, + eyePosition: { + label: __6("Position"), + items: [ + { + type: 2 /* Range */, + property: "eyeY", + iconStart: EditorIcons_default.positionMoveUp, + iconEnd: EditorIcons_default.positionMoveDown, + soundStart: "position_down", + soundEnd: "position_up", + min: 0, + max: 18, + part: 1 /* Face */, + inverse: true, + label: data2.useAccessibility ? __6("Position") : undefined + }, + { + type: 2 /* Range */, + property: "eyeX", + iconStart: EditorIcons_default.positionPushIn, + iconEnd: EditorIcons_default.positionPushOut, + soundStart: "move_together", + soundEnd: "move_apart", + min: 0, + max: 12, + part: 1 /* Face */, + label: data2.useAccessibility ? __6("Spacing") : undefined + }, + { + type: 2 /* Range */, + property: "eyeRotate", + iconStart: EditorIcons_default.positionRotateCW, + iconEnd: EditorIcons_default.positionRotateCCW, + soundStart: "rotate_cw", + soundEnd: "rotate_ccw", + min: 0, + max: 7, + part: 1 /* Face */, + label: data2.useAccessibility ? __6("Rotation") : undefined + }, + { + type: 2 /* Range */, + property: "eyeScale", + iconStart: EditorIcons_default.positionSizeDown, + iconEnd: EditorIcons_default.positionSizeUp, + soundStart: "scale_down", + soundEnd: "scale_up", + min: 0, + max: 7, + part: 1 /* Face */, + label: data2.useAccessibility ? __6("Scale") : undefined + }, + { + type: 2 /* Range */, + property: "eyeAspect", + iconStart: EditorIcons_default.positionStretchIn, + iconEnd: EditorIcons_default.positionStretchOut, + soundStart: "vert_stretch_down", + soundEnd: "vert_stretch_up", + min: 0, + max: 6, + part: 1 /* Face */, + label: data2.useAccessibility ? __6("Stretch") : undefined + } + ] + } + } + })); +} + +// src/ui/tabs/Head.ts +var __7 = _8(); +function HeadTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: data2.callback, + entries: { + facelineType: { + label: data2.useAccessibility ? __7("Shape") : EditorIcons_default.face, + items: ArrayNum(12).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + icon: data2.icons.face[k4], + part: 0 /* Head */, + bodyUpdateType: 0 /* None */ + })) + }, + facelineMake: { + label: data2.useAccessibility ? __7("Makeup") : EditorIcons_default.face_makeup, + items: ArrayNum(12).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + icon: data2.icons.makeup[k4], + part: 0 /* Head */, + bodyUpdateType: 0 /* None */ + })) + }, + facelineWrinkle: { + label: data2.useAccessibility ? __7("Wrinkles") : EditorIcons_default.face_wrinkles, + items: ArrayNum(12).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + icon: data2.icons.wrinkles[k4], + part: 0 /* Head */, + bodyUpdateType: 0 /* None */ + })) + }, + facelineColor: { + label: data2.useAccessibility ? __7("Color") : EditorIcons_default.color, + items: [ + ...ArrayNum(6).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + color: MiiSkinColorTable[k4], + part: 0 /* Head */, + bodyUpdateType: 1 /* ClothingUpdate */ + })), + makeSeparatorFSI(), + ...rearrangeArray(ArrayNum(10).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + color: MiiSwitchSkinColorList[k4], + part: 0 /* Head */, + bodyUpdateType: 1 /* ClothingUpdate */ + })), MiiSwitchSkinColorTable, makeSeparatorGapThinFSI) + ] + }, + facePaintColor: { + label: data2.useAccessibility ? __7("Face Paint") : EditorIcons_default.face_paint, + header: __7("%1 is a CUSTOM property, and will not transfer to any other data formats.", __7("Face paint")), + items: [ + { + type: 0 /* Icon */, + forceRender: true, + value: -1, + icon: `${__7("Disabled")}`, + part: 0 /* Head */, + bodyUpdateType: 1 /* ClothingUpdate */ + }, + makeSeparatorGapThinFSI(), + ...rearrangeArray(ArrayNum(100).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + color: SwitchMiiColorTable[k4], + part: 0 /* Head */, + bodyUpdateType: 1 /* ClothingUpdate */ + })), MiiSwitchColorTable, makeSeparatorGapThinLaptop) + ] + } + } + })); +} + +// src/ui/components/Input.ts +function Input(label, value2, callback, validate2, editor) { + let id = String(performance.now()); + function checkValidity(value3) { + if (editor) { + editor.dirty = true; + if (validate2) { + const result = validate2(value3); + if (result === true) { + input.classOff("invalid"); + if (editor) + editor.errors.set(label, { + valid: true, + reason: "Valid" + }); + callback(value3); + } else { + input.classOn("invalid"); + if (editor) + editor.errors.set(label, { + valid: false, + reason: String(result) + }); + } + } + } + } + let input = new Html("input").id(id).attr({ type: "text", value: value2 }).on("input", (e) => { + const target = e.target; + checkValidity(target.value); + }); + if (validate2) + validate2(value2); + return new Html("div").class("input-group").appendMany(new Html("label").attr({ for: id }).text(label), input); +} + +// src/ui/tabs/Misc.ts +var __8 = _8(); +function MiscTab(data2) { + let tmpMii = new Mii(data2.mii.export()); + const setProp = (prop, val2) => { + if (MiiEditor2.getCurrentEditor() !== null) { + tmpMii = MiiEditor2.getCurrentEditor().mii; + } + tmpMii[prop] = val2; + data2.callback(tmpMii, false, 0 /* Head */, 0 /* None */); + return true; + }; + data2.container.appendMany(new Html("div").style({ + padding: "1rem", + display: "flex", + "flex-direction": "column", + gap: "1rem" + }).appendMany(Input(__8("Name"), data2.mii.nickname, (name2) => setProp("nickname", name2.trim()), (name2) => { + const nameBuffer = encodeUTF16LE(name2); + let nameStr = decodeUTF16LE(nameBuffer); + if (nameStr.trim() === "") + return __8("Name is empty"); + if (nameBuffer.length > 20) + return __8("Name is too long"); + if (nameBuffer.length === 0) + return __8("Name is too short"); + return true; + }, data2.editor), Input(__8("Creator"), data2.mii.creator, (creator) => setProp("creator", creator.trim()), (name2) => { + const nameBuffer = encodeUTF16LE(name2); + let nameStr = decodeUTF16LE(nameBuffer); + if (nameStr.length === 0) + return true; + if (nameStr.trim() === "") + return __8("Creator name is empty"); + if (nameBuffer.length > 20) + return __8("Creator name is too long"); + return true; + }, data2.editor)), new Html("div").class("input-group").style({ + height: "max-content" + }).appendMany(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: data2.callback, + entries: { + gender: { + label: __8("Gender"), + items: [ + { + type: 4 /* Switch */, + iconOff: data2.useAccessibility ? __8("Male") : EditorIcons_default.genderMale, + iconOn: data2.useAccessibility ? __8("Female") : EditorIcons_default.genderFemale, + property: "gender", + isNumber: true, + forceRender: true, + part: 2 /* Body */, + bodyUpdateType: 1 /* ClothingUpdate */, + soundOff: "select_misc", + soundOn: "select_misc" + } + ] + }, + favorite: { + label: __8("Favorite/Special"), + items: [ + { + type: 4 /* Switch */, + iconOff: __8("Normal"), + iconOn: __8("Favorite"), + property: "favorite", + isNumber: true, + forceRender: false, + part: 2 /* Body */, + bodyUpdateType: 1 /* ClothingUpdate */, + soundOff: "select_color", + soundOn: "select_color" + }, + makeSeparatorGapThinFSI(), + { + type: 4 /* Switch */, + iconOff: __8("Normal"), + iconOn: __8("Special"), + property: "special", + isNumber: true, + forceRender: false, + part: 2 /* Body */, + bodyUpdateType: 1 /* ClothingUpdate */, + soundOff: "select_color", + soundOn: "select_color" + } + ] + } + } + }))); +} + +// src/ui/tabs/Nose.ts +var __9 = _8(); +function NoseTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: data2.callback, + entries: { + noseType: { + label: __9("Type"), + items: rearrangeArray(ArrayNum(18).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + icon: data2.icons.nose[k4], + part: 0 /* Head */ + })), MiiNoseTable, makeSeparatorGapThinDesktop) + }, + nosePosition: { + label: __9("Position"), + items: [ + { + type: 2 /* Range */, + property: "noseY", + iconStart: EditorIcons_default.positionMoveUp, + iconEnd: EditorIcons_default.positionMoveDown, + soundStart: "position_down", + soundEnd: "position_up", + min: 0, + max: 18, + part: 0 /* Head */, + inverse: true, + label: data2.useAccessibility ? __9("Position") : undefined + }, + { + type: 2 /* Range */, + property: "noseScale", + iconStart: EditorIcons_default.positionSizeDown, + iconEnd: EditorIcons_default.positionSizeUp, + soundStart: "scale_down", + soundEnd: "scale_up", + min: 0, + max: 8, + part: 0 /* Head */, + label: data2.useAccessibility ? __9("Scale") : undefined + } + ] + } + } + })); +} + +// src/util/NumberToHexString.ts +var numToHex = (num) => "#" + num.toString(16).padStart(6, "0"); + +// src/ui/tabs/FavoriteColor.ts +var __10 = _8(); +function FavoriteColorTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: data2.callback, + entries: { + favoriteColor: { + label: __10("Favorite Color"), + items: ArrayNum(12).map((k4) => ({ + type: 0 /* Icon */, + forceRender: true, + value: k4, + color: numToHex(MiiFavoriteColorLookupTable[k4]), + part: 0 /* Head */, + bodyUpdateType: 1 /* ClothingUpdate */ + })) + } + } + })); +} + +// src/ui/tabs/Mouth.ts +var __11 = _8(); +function MouthTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: (newMii, forceRender, renderPart, updateType) => { + data2.callback(newMii, forceRender, renderPart, updateType); + }, + entries: { + mouthType: { + label: __11("Type"), + items: rearrangeArray(ArrayNum(36).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + icon: data2.icons.mouth[k4], + part: 1 /* Face */ + })), MiiMouthTable, makeSeparatorGapThinDesktop) + }, + mouthColor: { + label: data2.useAccessibility ? __11("Color") : EditorIcons_default.color, + items: [ + ...ArrayNum(5).map((k4) => ({ + type: 0 /* Icon */, + value: Ver3MouthColorTable[k4], + color: SwitchMiiColorTable[Ver3MouthColorTable[k4]], + part: 1 /* Face */, + property: "mouthColor" + })), + makeSeparatorFSI(), + ...rearrangeArray(ArrayNum(100).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + color: SwitchMiiColorTable[k4], + part: 1 /* Face */, + property: "mouthColor" + })), MiiSwitchColorTable, makeSeparatorGapThinLaptop) + ] + }, + mouthPosition: { + label: __11("Position"), + items: [ + { + type: 2 /* Range */, + property: "mouthY", + iconStart: EditorIcons_default.positionMoveUp, + iconEnd: EditorIcons_default.positionMoveDown, + soundStart: "position_down", + soundEnd: "position_up", + min: 0, + max: 18, + part: 1 /* Face */, + inverse: true, + label: data2.useAccessibility ? __11("Position") : undefined + }, + { + type: 2 /* Range */, + property: "mouthScale", + iconStart: EditorIcons_default.positionSizeDown, + iconEnd: EditorIcons_default.positionSizeUp, + soundStart: "scale_down", + soundEnd: "scale_up", + min: 0, + max: 8, + part: 1 /* Face */, + label: data2.useAccessibility ? __11("Scale") : undefined + }, + { + type: 2 /* Range */, + property: "mouthAspect", + iconStart: EditorIcons_default.positionStretchIn, + iconEnd: EditorIcons_default.positionStretchOut, + soundStart: "vert_stretch_down", + soundEnd: "vert_stretch_up", + min: 0, + max: 6, + part: 1 /* Face */, + label: data2.useAccessibility ? __11("Stretch") : undefined + } + ] + } + } + })); +} + +// src/ui/tabs/Hair.ts +var __12 = _8(); +function HairTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: (newMii, forceRender, renderPart, updateType) => { + data2.callback(newMii, forceRender, renderPart, updateType); + }, + entries: { + hairType: { + label: __12("Type"), + items: rearrangeArray(ArrayNum(132).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + icon: data2.icons.hair[k4], + part: 0 /* Head */ + })), MiiHairTable, makeSeparatorGapThinDesktop) + }, + hairColor: { + label: data2.useAccessibility ? __12("Color") : EditorIcons_default.color, + items: [ + ...ArrayNum(8).map((k4) => ({ + type: 0 /* Icon */, + value: Ver3HairColorTable[k4], + color: SwitchMiiColorTable[Ver3HairColorTable[k4]], + part: 0 /* Head */ + })), + makeSeparatorFSI(), + ...rearrangeArray(ArrayNum(100).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + color: SwitchMiiColorTable[k4], + part: 0 /* Head */ + })), MiiSwitchColorTable, makeSeparatorGapThinLaptop) + ] + }, + hairPosition: { + label: __12("Hair Flip"), + items: [ + { + type: 4 /* Switch */, + iconOff: data2.useAccessibility ? __12("Unflipped") : EditorIcons_default.positionHairFlip, + iconOn: data2.useAccessibility ? __12("Flipped") : EditorIcons_default.positionHairFlipped, + property: "hairFlip", + part: 0 /* Head */ + } + ] + } + } + })); +} + +// src/ui/tabs/Scale.ts +var __13 = _8(); +function ScaleTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: data2.callback, + entries: { + bodySize: { + label: __13("Scale"), + items: [ + { + type: 3 /* Slider */, + property: "height", + iconStart: EditorIcons_default.scaleShort, + iconEnd: EditorIcons_default.scaleTall, + min: 0, + max: 127, + forceRender: false, + part: 2 /* Body */, + bodyUpdateType: 2 /* RepositionCamera */, + soundStart: "vert_stretch_down", + soundEnd: "vert_stretch_up", + label: data2.useAccessibility ? __13("Height") : undefined + }, + { + type: 3 /* Slider */, + property: "build", + iconStart: EditorIcons_default.scaleThin, + iconEnd: EditorIcons_default.scaleFat, + min: 0, + max: 127, + forceRender: false, + part: 2 /* Body */, + bodyUpdateType: 2 /* RepositionCamera */, + soundStart: "vert_stretch_down", + soundEnd: "vert_stretch_up", + label: data2.useAccessibility ? __13("Build") : undefined + } + ] + } + } + })); +} + +// src/ui/tabs/FacialHair.ts +var __14 = _8(); +function FacialHairTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: data2.callback, + entries: { + mustacheType: { + label: __14("Mustache"), + items: ArrayNum(6).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + icon: data2.icons.mustache[k4], + part: 1 /* Face */ + })) + }, + mustachePosition: { + label: __14("Position"), + items: [ + { + type: 2 /* Range */, + property: "mustacheY", + iconStart: EditorIcons_default.positionMoveUp, + iconEnd: EditorIcons_default.positionMoveDown, + soundStart: "position_down", + soundEnd: "position_up", + min: 0, + max: 16, + part: 1 /* Face */, + inverse: true, + label: data2.useAccessibility ? "Position" : undefined + }, + { + type: 2 /* Range */, + property: "mustacheScale", + iconStart: EditorIcons_default.positionSizeDown, + iconEnd: EditorIcons_default.positionSizeUp, + soundStart: "scale_down", + soundEnd: "scale_up", + min: 0, + max: 8, + part: 1 /* Face */, + label: data2.useAccessibility ? "Scale" : undefined + } + ] + }, + beardType: { + label: __14("Beard"), + items: ArrayNum(6).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + icon: data2.icons.goatee[k4], + part: 0 /* Head */ + })) + }, + beardColor: { + label: data2.useAccessibility ? __14("Color") : EditorIcons_default.color, + items: [ + ...ArrayNum(8).map((k4) => ({ + type: 0 /* Icon */, + value: Ver3HairColorTable[k4], + color: SwitchMiiColorTable[Ver3HairColorTable[k4]], + part: 0 /* Head */, + property: "beardColor" + })), + makeSeparatorFSI(), + ...rearrangeArray(ArrayNum(100).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + color: SwitchMiiColorTable[k4], + part: 0 /* Head */, + property: "beardColor" + })), MiiSwitchColorTable, makeSeparatorGapThinLaptop) + ] + } + } + })); +} + +// src/ui/tabs/Mole.ts +var __15 = _8(); +function MoleTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: data2.callback, + entries: { + mole: { + label: __15("Mole"), + items: [ + { + type: 4 /* Switch */, + iconOff: __15("Disable"), + iconOn: __15("Enable"), + property: "moleType", + part: 1 /* Face */, + isNumber: true + }, + { + type: 2 /* Range */, + property: "moleY", + iconStart: EditorIcons_default.positionMoveUp, + iconEnd: EditorIcons_default.positionMoveDown, + soundStart: "position_down", + soundEnd: "position_up", + min: 0, + max: 30, + part: 1 /* Face */, + inverse: true, + label: data2.useAccessibility ? __15("Position") : undefined + }, + { + type: 2 /* Range */, + property: "moleX", + iconStart: EditorIcons_default.positionPushIn, + iconEnd: EditorIcons_default.positionPushOut, + soundStart: "move_together", + soundEnd: "move_apart", + min: 0, + max: 16, + part: 1 /* Face */, + label: data2.useAccessibility ? __15("Spacing") : undefined + }, + { + type: 2 /* Range */, + property: "moleScale", + iconStart: EditorIcons_default.positionSizeDown, + iconEnd: EditorIcons_default.positionSizeUp, + soundStart: "scale_down", + soundEnd: "scale_up", + min: 0, + max: 7, + part: 1 /* Face */, + label: data2.useAccessibility ? __15("Scale") : undefined + } + ] + } + } + })); +} + +// src/ui/tabs/Eyebrow.ts +var __16 = _8(); +function EyebrowTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: data2.callback, + entries: { + eyebrowType: { + label: __16("Type"), + items: rearrangeArray(ArrayNum(24).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + icon: data2.icons.eyebrows[k4], + part: 1 /* Face */, + preSelectCallback(tmpMii) { + tmpMii.eyebrowRotate += MiiEyebrowRotationGroups[k4] - MiiEyebrowRotationGroups[tmpMii.eyebrowType]; + } + })), MiiEyebrowTable, makeSeparatorGapThinDesktop) + }, + eyebrowColor: { + label: data2.useAccessibility ? __16("Color") : EditorIcons_default.color, + items: [ + ...ArrayNum(8).map((k4) => ({ + type: 0 /* Icon */, + value: Ver3HairColorTable[k4], + color: SwitchMiiColorTable[Ver3HairColorTable[k4]], + part: 1 /* Face */ + })), + makeSeparatorFSI(), + ...rearrangeArray(ArrayNum(100).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + color: SwitchMiiColorTable[k4], + part: 1 /* Face */ + })), MiiSwitchColorTable, makeSeparatorGapThinLaptop) + ] + }, + eyebrowPosition: { + label: __16("Position"), + items: [ + { + type: 2 /* Range */, + property: "eyebrowY", + iconStart: EditorIcons_default.positionMoveUp, + iconEnd: EditorIcons_default.positionMoveDown, + soundStart: "position_down", + soundEnd: "position_up", + min: 3, + max: 18, + part: 1 /* Face */, + inverse: true, + label: data2.useAccessibility ? __16("Position") : undefined + }, + { + type: 2 /* Range */, + property: "eyebrowX", + iconStart: EditorIcons_default.positionPushIn, + iconEnd: EditorIcons_default.positionPushOut, + soundStart: "move_together", + soundEnd: "move_apart", + min: 0, + max: 12, + part: 1 /* Face */, + label: data2.useAccessibility ? __16("Spacing") : undefined + }, + { + type: 2 /* Range */, + property: "eyebrowRotate", + iconStart: EditorIcons_default.positionRotateCW, + iconEnd: EditorIcons_default.positionRotateCCW, + soundStart: "rotate_cw", + soundEnd: "rotate_ccw", + min: 0, + max: 11, + part: 1 /* Face */, + label: data2.useAccessibility ? __16("Rotation") : undefined + }, + { + type: 2 /* Range */, + property: "eyebrowScale", + iconStart: EditorIcons_default.positionSizeDown, + iconEnd: EditorIcons_default.positionSizeUp, + soundStart: "scale_down", + soundEnd: "scale_up", + min: 0, + max: 8, + part: 1 /* Face */, + label: data2.useAccessibility ? __16("Scale") : undefined + }, + { + type: 2 /* Range */, + property: "eyebrowAspect", + iconStart: EditorIcons_default.positionStretchIn, + iconEnd: EditorIcons_default.positionStretchOut, + soundStart: "vert_stretch_down", + soundEnd: "vert_stretch_up", + min: 0, + max: 6, + part: 1 /* Face */, + label: data2.useAccessibility ? __16("Stretch") : undefined + } + ] + } + } + })); +} + +// src/ui/tabs/Glasses.ts +var __17 = _8(); +function GlassesTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: (newMii, forceRender, renderPart, updateType) => { + data2.callback(newMii, forceRender, renderPart, updateType); + }, + entries: { + glassType: { + label: __17("Type"), + items: ArrayNum(20).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + icon: data2.icons.glasses[k4], + part: 0 /* Head */ + })) + }, + glassesColor: { + label: data2.useAccessibility ? __17("Color") : EditorIcons_default.color, + items: [ + ...ArrayNum(6).map((k4) => ({ + type: 0 /* Icon */, + value: Ver3GlassColorTable[k4], + color: SwitchMiiColorTable[Ver3GlassColorTable[k4]], + part: 0 /* Head */, + property: "glassColor" + })), + makeSeparatorFSI(), + ...rearrangeArray(ArrayNum(100).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + color: SwitchMiiColorTable[k4], + part: 0 /* Head */, + property: "glassColor" + })), MiiSwitchColorTable, makeSeparatorGapThinLaptop) + ] + }, + glassesPosition: { + label: __17("Position"), + items: [ + { + type: 2 /* Range */, + property: "glassY", + iconStart: EditorIcons_default.positionMoveUp, + iconEnd: EditorIcons_default.positionMoveDown, + soundStart: "position_down", + soundEnd: "position_up", + min: 0, + max: 20, + part: 0 /* Head */, + inverse: true, + label: data2.useAccessibility ? __17("Position") : undefined + }, + { + type: 2 /* Range */, + property: "glassScale", + iconStart: EditorIcons_default.positionSizeDown, + iconEnd: EditorIcons_default.positionSizeUp, + soundStart: "scale_down", + soundEnd: "scale_up", + min: 0, + max: 7, + part: 0 /* Head */, + label: data2.useAccessibility ? __17("Scale") : undefined + } + ] + } + } + })); +} + +// src/ui/tabs/ExtHat.ts +var __18 = _8(); +function ExtHatTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: data2.callback, + entries: { + hatType: { + label: __18("Hat"), + header: __18("%1 is a CUSTOM property, and will not transfer to any other data formats.", __18("Hat type")), + items: [ + { + type: 0 /* Icon */, + forceRender: true, + value: -1, + icon: `${__18("Disabled")}`, + part: 0 /* Head */ + }, + makeSeparatorGapThinFSI(), + ...ArrayNum(10).slice(1).map((k4) => ({ + type: 0 /* Icon */, + forceRender: true, + value: k4 - 1, + icon: data2.icons.hat[k4 - 1], + part: 0 /* Head */ + })) + ] + }, + hatColor: { + label: __18("Hat Color"), + header: __18("%1 is a CUSTOM property, and will not transfer to any other data formats.", __18("Hat color")), + items: [ + { + type: 0 /* Icon */, + forceRender: true, + value: -1, + icon: `${__18("Disabled")}`, + part: 0 /* Head */, + property: ["hatFavoriteColor", "hatCommonColor"], + selectedCondition: () => data2.mii.hatCommonColor === -1 && data2.mii.hatFavoriteColor === -1 + }, + makeSeparatorGapThinFSI(), + ...ArrayNum(12).map((k4) => ({ + type: 0 /* Icon */, + forceRender: true, + value: k4, + color: numToHex(MiiFavoriteColorLookupTable[k4]), + part: 0 /* Head */, + property: "hatFavoriteColor", + preSelectCallback: (mii) => { + mii.hatFavoriteColor = k4; + mii.hatCommonColor = -1; + } + })), + makeSeparatorFSI(), + ...rearrangeArray(ArrayNum(100).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + color: SwitchMiiColorTable[k4], + part: 0 /* Head */, + property: "hatCommonColor", + preSelectCallback: (mii) => { + mii.hatFavoriteColor = -1; + mii.hatCommonColor = k4; + } + })), MiiSwitchColorTable, makeSeparatorGapThinLaptop) + ] + } + } + })); +} + +// src/ui/tabs/ExtClothes.ts +var __19 = _8(); +function ExtClothesTab(data2) { + data2.container.append(MiiPagedFeatureSet({ + mii: data2.mii, + onChange: data2.callback, + entries: { + clothesType: { + label: __19("Clothes"), + header: __19("%1 is a CUSTOM property, and will not transfer to any other data formats.", __19("Clothes type")), + items: [ + { + type: 0 /* Icon */, + forceRender: true, + value: -1, + icon: `${__19("Disabled")}`, + part: 0 /* Head */, + bodyUpdateType: 1 /* ClothingUpdate */ + }, + makeSeparatorGapThinFSI(), + ...ArrayNum(10).slice(1).map((k4) => ({ + type: 0 /* Icon */, + forceRender: true, + bodyUpdateType: 1 /* ClothingUpdate */, + value: k4 - 1, + icon: k4, + part: 0 /* Head */ + })) + ] + }, + shirtColor: { + label: __19("Shirt Color"), + header: __19("%1 is a CUSTOM property, and will not transfer to any other data formats.", __19("Shirt color")), + items: [ + { + type: 0 /* Icon */, + forceRender: true, + value: -1, + icon: `${__19("Disabled")}`, + part: 2 /* Body */, + bodyUpdateType: 1 /* ClothingUpdate */, + property: "shirtColor", + sound: "select_color" + }, + makeSeparatorGapThinFSI(), + ...rearrangeArray(ArrayNum(100).map((k4) => ({ + type: 0 /* Icon */, + forceRender: true, + value: k4, + color: SwitchMiiColorTable[k4], + part: 2 /* Body */, + bodyUpdateType: 1 /* ClothingUpdate */, + property: "shirtColor" + })), MiiSwitchColorTable, makeSeparatorGapThinLaptop).filter((n2) => !ForbiddenShirtPantColors.includes(n2.value)) + ] + }, + pantsColor: { + label: __19("Pants Color"), + header: __19("%1 is a CUSTOM property, and will not transfer to any other data formats.", __19("Pants color")), + items: [ + { + type: 0 /* Icon */, + forceRender: false, + value: -1, + icon: `${__19("Disabled")}`, + part: 2 /* Body */, + bodyUpdateType: 1 /* ClothingUpdate */, + property: "pantsColor", + sound: "select_color" + }, + makeSeparatorGapThinFSI(), + ...rearrangeArray(ArrayNum(100).map((k4) => ({ + type: 0 /* Icon */, + forceRender: false, + value: k4, + color: SwitchMiiColorTable[k4], + part: 2 /* Body */, + bodyUpdateType: 1 /* ClothingUpdate */, + property: "pantsColor" + })), MiiSwitchColorTable, makeSeparatorGapThinLaptop).filter((n2) => !ForbiddenShirtPantColors.includes(n2.value)) + ] + }, + shoesColor: { + label: __19("Shoes Color"), + header: __19("%1 is a CUSTOM property, and will not transfer to any other data formats.", __19("Shoes color")), + items: [ + { + type: 0 /* Icon */, + forceRender: false, + value: -1, + icon: `${__19("Disabled")}`, + part: 2 /* Body */, + bodyUpdateType: 1 /* ClothingUpdate */, + property: "shoesColor", + sound: "select_color" + }, + makeSeparatorGapThinFSI(), + ...rearrangeArray(ArrayNum(100).map((k4) => ({ + type: 0 /* Icon */, + forceRender: false, + value: k4, + color: SwitchMiiColorTable[k4], + part: 2 /* Body */, + bodyUpdateType: 1 /* ClothingUpdate */, + property: "shoesColor" + })), MiiSwitchColorTable, makeSeparatorGapThinLaptop).filter((n2) => !ForbiddenShirtPantColors.includes(n2.value)) + ] + } + } + })); +} + +// src/class/MiiEditor.ts +var activeMii; +var currentEditor = null; +var __20 = _8(); + +class MiiEditor2 { + mii; + icons; + ui; + dirty; + ready; + renderingMode; + onShutdown; + errors; + useAccessibility; + static getCurrentEditor() { + return currentEditor; + } + constructor(gender, onShutdown, init) { + window.editor = this; + currentEditor = this; + document.dispatchEvent(new CustomEvent("editor-launch")); + this.showLoadIndicator(); + this.dirty = false; + this.ready = false; + this.errors = new Map; + let initString = "BAXGigDvV8wSNID/cJl869TJwxYAAAAAAAAAAAAAAAAAAAAAAAAAAE0AaQBpAAAAAAAAAAAAAAAAAAAACAAAAAAAQAMDAQYEBgIKCAQEAgIMAAAAAP8AAAAACAQACgEAIf///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAP//"; + if (gender === 1 /* Female */) { + initString = "BACnywgm6RFTRIDfGZqVDHu5NhQAAAAAAAAAAAAAAAAAAAAAAAAAAE0AaQBpAAAAAAAAAAAAAAAAAAAACAAAAAAAQAMDAQYEAAIKCAMEBAIMAAAAAP8AAAABCAQACgEADP///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAP//"; + } + if (init) + initString = init; + if (onShutdown) { + this.onShutdown = onShutdown; + } + this.mii = new Mii(initString); + activeMii = this.mii; + this.#setupUi(); + } + #loadInterval; + showLoadIndicator() { + const check2 = () => { + if (this.ready) { + this.hideLoadIndicator(); + return; + } else { + if (this.ui) { + if (this.ui.mii) { + if (this.ui.mii.qs(".loader")) + this.ui.mii.qs(".loader").classOn("active"); + } + } + } + playSound("wait"); + }; + check2(); + this.#loadInterval = setInterval(check2, 1000); + } + hideLoadIndicator() { + clearInterval(this.#loadInterval); + if (this.ui.mii.qs(".loader")) { + this.ui.mii.qs(".loader").classOff("active"); + } + } + async#setupUi() { + const editMode = await getSetting("editMode"); + if (editMode === "2d") { + this.renderingMode = 0 /* Canvas2DRenderer */; + } else if (editMode === "3d") { + if (Config.renderer.allow3DMode === true) + this.renderingMode = 1 /* Canvas3DScene */; + else + this.renderingMode = 0 /* Canvas2DRenderer */; + } + const useAccessibility = await getSetting("accessibilityFeature"); + this.useAccessibility = useAccessibility; + this.icons = await fetch("./dist/icons.json?t=" + Date.now()).then((j2) => j2.json()); + this.ui = {}; + this.#setupBase(); + this.#updateCssVars(); + await this.#setupMii(); + this.#setupTabs(); + await this.render(); + this.ready = true; + } + #setupBase() { + this.ui.base = new Html("div").class("ui-base").appendTo("body"); + } + #renderModeText(RM) { + switch (RM) { + case 0 /* Canvas2DRenderer */: + return "2D"; + case 1 /* Canvas3DScene */: + return "3D"; + } + } + async#setupMii() { + this.ui.mii = new Html("div").class("mii-holder").appendTo(this.ui.base); + this.ui.mii.append(new Html("div").html(EditorIcons_default.loading).class("loader", "active")); + let nextRenderMode = 0; + switch (this.renderingMode) { + case 0 /* Canvas2DRenderer */: + if (Config.renderer.useRendererServer === true) + this.#setup2D(); + else { + await this.#setup3D(); + this.ui.scene.cameraPan = true; + this.ui.scene.focusCameraUpdate(); + } + nextRenderMode = 1 /* Canvas3DScene */; + break; + case 1 /* Canvas3DScene */: + this.#setup3D(); + nextRenderMode = 0 /* Canvas2DRenderer */; + break; + } + const renderModeToggle = AddButtonSounds(new Html("button").class("render-mode-toggle").style({ "z-index": "1" }).text(this.#renderModeText(nextRenderMode)).on("click", () => { + if (Config.renderer.allow3DMode === false) + return Modal_default.alert(__20("You can't use this feature"), __20("Sorry, but you can't use this feature because 3D mode is disabled at the moment.")); + renderModeToggle.text(this.#renderModeText(this.renderingMode)); + switch (this.renderingMode) { + case 0 /* Canvas2DRenderer */: + this.renderingMode = 1 /* Canvas3DScene */; + break; + case 1 /* Canvas3DScene */: + this.renderingMode = 0 /* Canvas2DRenderer */; + } + if (this.ui.scene && Config.renderer.useRendererServer === false) { + this.ui.scene.cameraPan = !Boolean(this.renderingMode); + this.ui.scene.focusCameraUpdate(); + console.log("why this Really not work :(", this.renderingMode); + return; + } + this.render(); + }).appendTo(this.ui.mii)); + } + #setup2D() { + new Html("img").attr({ crossorigin: "anonymous" }).appendTo(this.ui.mii); + } + async#setup3D() { + this.ui.scene = new Mii3DScene(this.mii, this.ui.mii.elm, undefined, undefined, undefined, this); + if (this.ui.scene && Config.renderer.useRendererServer === false) { + this.ui.scene.cameraPan = Boolean(this.renderingMode); + this.ui.scene.focusCameraUpdate(); + } + await this.ui.scene.init(); + this.ui.mii.append(this.ui.scene.getRendererElement()); + window.addEventListener("resize", () => { + this.ui.scene.resize(); + }); + this.ui.scene.focusCamera(0 /* MiiHead */); + this.ui.scene.getRendererElement().classList.add("ready"); + this.ui.mii.qs(".loader").classOff("active"); + } + async#updateCssVars() { + let glassesColor = SwitchMiiColorTable[this.mii.glassColor]; + let eyeColor = SwitchMiiColorTable[this.mii.eyeColor]; + let mouthColor = { + top: SwitchMiiColorTableLip[this.mii.mouthColor], + bottom: SwitchMiiColorTable[this.mii.mouthColor] + }; + if (this.useAccessibility) { + this.ui.base.style({ + "--eye-color": "#787880", + "--icon-lip-color-top": "#780c0c", + "--icon-lip-color-bottom": "#f00c08", + "--icon-hair-tie": "#" + MiiFavoriteColorLookupTable[this.mii.favoriteColor].toString(16).padStart(6, "0"), + "--icon-eyebrow-fill": "var(--text)", + "--icon-hair-fill": "var(--text)", + "--icon-facial-hair-fill": "#9b9b9b", + "--icon-hat-fill": MiiFavoriteColorIconTable[0].top, + "--icon-hat-stroke": MiiFavoriteColorIconTable[0].bottom, + "--icon-custom-hat-fill": MiiFavoriteColorIconTable[0].top, + "--icon-custom-hat-stroke": MiiFavoriteColorIconTable[0].bottom, + "--icon-glasses-fill": "#787880", + "--icon-glasses-shade": "#78788077" + }); + } else { + this.ui.base.style({ + "--eye-color": eyeColor, + "--icon-lip-color-top": mouthColor.top, + "--icon-lip-color-bottom": mouthColor.bottom, + "--icon-hair-tie": "#" + MiiFavoriteColorLookupTable[this.mii.favoriteColor].toString(16).padStart(6, "0"), + "--icon-eyebrow-fill": SwitchMiiColorTable[this.mii.eyebrowColor], + "--icon-hair-fill": SwitchMiiColorTable[this.mii.hairColor], + "--icon-facial-hair-fill": SwitchMiiColorTable[this.mii.beardColor], + "--icon-hat-fill": MiiFavoriteColorIconTable[this.mii.favoriteColor].top, + "--icon-hat-stroke": MiiFavoriteColorIconTable[this.mii.favoriteColor].bottom, + "--icon-glasses-fill": glassesColor, + "--icon-glasses-shade": glassesColor + "77" + }); + } + } + #setupTabs() { + const TabInit = (Tab, CameraFocusPart) => { + return async (content2) => { + if (this.ui.scene) + this.ui.scene.focusCamera(CameraFocusPart); + await Tab({ + container: content2, + callback: (mii, forceRender, renderPart, bodyUpdateType) => { + this.mii = mii; + activeMii = mii; + this.render(forceRender, renderPart, bodyUpdateType); + this.#updateCssVars(); + this.dirty = true; + }, + icons: this.icons, + mii: this.mii, + editor: this, + useAccessibility: this.useAccessibility + }); + if (this.ui.scene) + this.ui.scene.resize(); + }; + }; + const tabs = TabList([ + { + icon: EditorIcons_default.head, + select: TabInit(HeadTab, 0 /* MiiHead */) + }, + { + icon: EditorIcons_default.hair, + select: TabInit(HairTab, 0 /* MiiHead */) + }, + { + icon: EditorIcons_default.hat, + select: TabInit(ExtHatTab, 0 /* MiiHead */) + }, + { + icon: EditorIcons_default.eyebrows, + select: TabInit(EyebrowTab, 0 /* MiiHead */) + }, + { + icon: EditorIcons_default.eyes, + select: TabInit(EyeTab, 0 /* MiiHead */) + }, + { + icon: EditorIcons_default.nose, + select: TabInit(NoseTab, 0 /* MiiHead */) + }, + { + icon: EditorIcons_default.mouth, + select: TabInit(MouthTab, 0 /* MiiHead */) + }, + { + icon: EditorIcons_default.facialHair, + select: TabInit(FacialHairTab, 0 /* MiiHead */) + }, + { + icon: EditorIcons_default.mole, + select: TabInit(MoleTab, 0 /* MiiHead */) + }, + { + icon: EditorIcons_default.glasses, + select: TabInit(GlassesTab, 0 /* MiiHead */) + }, + { + icon: EditorIcons_default.scale, + select: TabInit(ScaleTab, 1 /* MiiFullBody */) + }, + { + icon: EditorIcons_default.favoriteColor, + select: TabInit(FavoriteColorTab, 1 /* MiiFullBody */) + }, + { + icon: EditorIcons_default.clothes, + select: TabInit(ExtClothesTab, 1 /* MiiFullBody */) + }, + { + icon: EditorIcons_default.details, + select: TabInit(MiscTab, 1 /* MiiFullBody */) + }, + { + icon: EditorIcons_default.save + "Save", + type: "tab-save", + select: () => { + if (this.dirty === true) + Modal_default.modal("Save Mii", "Would you like to save?", "body", { + text: "Save & Exit", + callback: () => { + this.shutdown(); + } + }, { + text: "Exit without Saving", + callback: () => { + this.shutdown(false); + } + }, { + text: "Cancel" + }); + else + Modal_default.modal("Quitting Editor", "No changes were made. Are you sure you want to exit?", "body", { + text: "Save & Exit", + callback: () => { + this.shutdown(); + } + }, { + text: "Exit without Saving", + callback: () => { + this.shutdown(false); + } + }, { + text: "Cancel" + }); + }, + update: false + } + ]); + this.ui.tabList = tabs.list; + this.ui.tabContent = tabs.content; + this.ui.base.appendMany(tabs.list, tabs.content); + } + async render(forceReloadHead = true, renderPart = 0 /* Head */, bodyUpdateType = 0 /* None */) { + if (Config.renderer.allow3DMode === false) + this.renderingMode = 0 /* Canvas2DRenderer */; + switch (this.renderingMode) { + case 0 /* Canvas2DRenderer */: + if (Config.renderer.useRendererServer === false) { + if (this.ui.mii.qs("canvas.scene") === null) { + await this.#setup3D(); + } + this.ui.mii.qs("canvas.scene")?.style({ display: "block" }); + this.ui.scene.mii = this.mii; + if (renderPart === 2 /* Body */) { + this.ui.scene.updateBody(bodyUpdateType); + this.ui.scene.resize(); + } else if (forceReloadHead) { + if (bodyUpdateType !== 0 /* None */) { + this.ui.scene.updateBody(bodyUpdateType); + } + this.ui.scene.updateMiiHead(renderPart); + this.ui.scene.sparkle(); + this.ui.scene.resize(); + } + return; + } + if (this.ui.mii.qs("img") === null) { + this.#setup2D(); + } + if (this.ui.mii.qs("canvas.scene")) { + this.ui.mii.qs("canvas.scene")?.style({ display: "none" }); + } + this.ui.mii.qs("img")?.style({ display: "block" }); + let pantsColor = "gray"; + if (this.mii.special === 1) { + pantsColor = "gold"; + } + if (this.mii.favorite) { + pantsColor = "red"; + } + this.ui.mii.qs("img")?.style({ display: "block" }).attr({ + src: `${Config.renderer.renderFullBodyURL}&data=${encodeURIComponent(this.mii.exportHex("studioData"))}&${Config.renderer.hatTypeParam}=${this.mii.hatType + Config.renderer.hatTypeAdd}&${Config.renderer.hatColorParam}=${(this.mii.hatFavoriteColor !== -1 ? this.mii.hatFavoriteColor - 1 : -1) + Config.renderer.hatColorAdd}&miic=${encodeURIComponent(dataToBase64(this.mii.export("miic")))}&pantsColor=${pantsColor}` + }); + break; + case 1 /* Canvas3DScene */: + if (this.ui.mii.qs("canvas.scene") === null) { + await this.#setup3D(); + } + if (this.ui.mii.qs("img")) { + this.ui.mii.qs("img")?.style({ display: "none" }); + } + this.ui.mii.qs("canvas.scene")?.style({ display: "block" }); + this.ui.scene.mii = this.mii; + if (renderPart === 2 /* Body */) { + this.ui.scene.updateBody(bodyUpdateType); + } else if (forceReloadHead) { + if (bodyUpdateType !== 0 /* None */) { + this.ui.scene.updateBody(bodyUpdateType); + } + this.ui.scene.updateMiiHead(renderPart); + this.ui.scene.sparkle(); + } + break; + } + } + #disableUI() { + this.ui.mii.qs("button").classOn("disabled"); + this.ui.tabList.classOn("disabled"); + this.ui.tabContent.classOn("disabled"); + } + async shutdown(shouldSave = true) { + if (shouldSave) { + if (Array.from(this.errors.values()).find((i) => i.valid === false)) { + let errorList = []; + for (const value2 of this.errors.values()) { + if (value2.valid === false) + errorList.push(value2.reason); + } + Modal_default.alert("Notice", `You need to fix the following issues before you can save: + +` + errorList.map((e) => `• ${e}`).join(` +`)); + return; + } + if (this.renderingMode === 1 /* Canvas3DScene */) { + await new Promise((resolve, reject2) => { + this.#disableUI(); + this.ui.scene.playEndingAnimation(); + setTimeout(() => { + resolve(null); + }, 1500); + }); + } + await fetch("/api/archive", { + body: JSON.stringify({ + nickname: this.mii.nickname, + creator: this.mii.creator, + ffsd: this.mii.exportBase64("ffsd"), + data: this.mii.exportBase64("miic"), + studio: this.mii.exportBase64("studioData") + }), + method: "POST", + headers: { "content-type": "application/json" } + }).catch(undefined); + } + if (this.#loadInterval) { + clearInterval(this.#loadInterval); + } + this.ui.base.classOn("closing"); + setTimeout(() => { + if (this.ui.scene) { + this.ui.scene.shutdown(); + } + this.ui.base.cleanup(); + if (this.onShutdown) { + this.onShutdown(dataToBase64(this.mii.export("miic")), shouldSave); + } + document.dispatchEvent(new CustomEvent("editor-shutdown")); + window.editor = null; + currentEditor = null; + }, 500); + } +} + +// src/ui/pages/library/importDialog.ts +var import_localforage6 = __toESM(require_localforage(), 1); +async function importMiiConfirmation(mii, source, title = "Mii Import") { + var m2 = Modal_default.modal(title, "", "body", { + text: "Cancel" + }, { + text: "Don't Save" + }, { + text: "Save", + async callback(e) { + const id = await newMiiId(); + await import_localforage6.default.setItem(id, dataToBase64(mii.export())); + await pushToServer(); + _shutdown()(); + Library(id); + } + }); + m2.qs(".modal-content").styleJs({ maxWidth: "100%", maxHeight: "100%" }); + m2.qs(".modal-body span").cleanup(); + m2.qs(".modal-body").style({ "align-items": "center", gap: "1.5rem" }).prependMany(new Html("span").text(`Do you want to save this Mii?`), new Html("small").text(source), new Html("span").style({ "font-size": "20px" }).text(`${mii.nickname} has arrived!`), new Html("img").attr({ + src: await getMiiIcon(mii, "import", "all_body_sugar", 260) + }).style({ + width: "260px", + height: "260px", + "object-fit": "contain" + })); +} + +// src/ui/pages/library/render/customRender.ts +var __21 = _8(); +var expressionTable = [ + { name: "Normal", id: 0 }, + { name: "Smile", id: 1 }, + { name: "Anger", id: 2 }, + { name: "Sorrow", id: 3 }, + { name: "Surprise", id: 4 }, + { name: "Blink", id: 5 }, + { name: "Normal (open mouth)", id: 6 }, + { name: "Smile (open mouth)", id: 7 }, + { name: "Anger (open mouth)", id: 8 }, + { name: "Surprise (open mouth)", id: 9 }, + { name: "Sorrow (open mouth)", id: 10 }, + { name: "Blink (open mouth)", id: 11 }, + { name: "Wink (left eye open)", id: 12 }, + { name: "Wink (right eye open)", id: 13 }, + { name: "Wink (left eye and mouth open)", id: 14 }, + { name: "Wink (right eye and mouth open)", id: 15 }, + { name: "Wink (left eye open and smiling)", id: 16 }, + { name: "Wink (right eye open and smiling)", id: 17 }, + { name: "Frustrated", id: 18 }, + { name: "Bored", id: 19 }, + { name: "Bored open mouth", id: 20 }, + { name: "Sigh mouth straight", id: 21 }, + { name: "Sigh", id: 22 }, + { name: "Disgusted mouth straight", id: 23 }, + { name: "Disgusted", id: 24 }, + { name: "Love", id: 25 }, + { name: "Love mouth open", id: 26 }, + { name: "Determined mouth straight", id: 27 }, + { name: "Determined", id: 28 }, + { name: "Cry mouth straight", id: 29 }, + { name: "Cry", id: 30 }, + { name: "Big smile mouth straight", id: 31 }, + { name: "Big smile", id: 32 }, + { name: "Cheeky", id: 33 }, + { name: "Resolve eyes funny mouth", id: 35 }, + { name: "Resolve eyes funny mouth open", id: 36 }, + { name: "Smug", id: 37 }, + { name: "Smug mouth open", id: 38 }, + { name: "Resolve", id: 39 }, + { name: "Resolve mouth open", id: 40 }, + { name: "Unbelievable", id: 41 }, + { name: "Cunning", id: 43 }, + { name: "Raspberry", id: 45 }, + { name: "Innocent", id: 47 }, + { name: "Cat", id: 49, modifier: 0 /* HideNose */ }, + { name: "Dog", id: 51, modifier: 0 /* HideNose */ }, + { name: "Tasty", id: 53 }, + { name: "Money mouth straight", id: 55 }, + { name: "Money", id: 56 }, + { name: "Confused mouth straight", id: 57 }, + { name: "Confused", id: 58 }, + { name: "Cheerful mouth straight", id: 59 }, + { name: "Cheerful", id: 60 }, + { name: "Blank", id: 61, modifier: 1 /* HideNoseAndMask */ }, + { name: "Grumble mouth straight", id: 63 }, + { name: "Grumble", id: 64 }, + { name: "Moved mouth straight", id: 65 }, + { name: "Moved (aka pleading face)", id: 66 }, + { name: "Singing mouth small", id: 67 }, + { name: "Singing", id: 68 }, + { name: "Stunned", id: 69 } +]; +async function customRender(miiData) { + const modal = Modal_default.modal("Custom Render", "", "body", { + text: "Cancel" + }); + const body = modal.qs(".modal-body").classOn("responsive-row-lg").clear(); + modal.qs(".modal-content").styleJs({ + width: "100%", + height: "100%", + maxWidth: "100%", + maxHeight: "100%", + backgroundColor: "var(--container-solid)" + }); + let parent2 = new Html("div").style({ + display: "flex", + flex: "1", + background: "var(--container-solid)", + "border-radius": "12px", + "flex-shrink": "0", + height: "100%", + overflow: "hidden", + "justify-content": "center", + "align-items": "center" + }).appendTo(body); + let parentBox = new Html("div").style({ "aspect-ratio": "1 / 1", height: "100%" }).appendTo(parent2); + let tabsContent = new Html("div").classOn("tab-content").style({ flex: "1", height: "100%", overflow: "auto", gap: "0.5rem" }).appendTo(body); + let configuration = { + fov: 30, + pose: 0, + expression: "0", + renderWidth: 720, + renderHeight: 720, + animSpeed: 100 + }; + const miiDataHex = miiData.exportHex("studioData"); + let poseListPerBodyModel = { + wii: 4, + wiiu: 14, + switch: 5, + miitomo: 16 + }; + let bodyModelSetting = await getSetting("bodyModel"); + let poseCount = 0; + if (bodyModelSetting in poseListPerBodyModel) { + poseCount = poseListPerBodyModel[bodyModelSetting] + 1; + } + console.log(bodyModelSetting); + let controls, rotationFactor = Math.PI / 8; + const e = { + camera: { + label: __21("Camera"), + header: new Html("span").html(__21(`Use mouse or touch to move the camera around. +Using touch, rotate the camera around with one finger, and drag with two fingers to pan. Pinch with two fingers to zoom. +If you like this site, PLEASE consider sharing it with others by crediting the site when you post your renders! \uD83D\uDE09`)), + headerIsHtml: true, + items: [ + { + type: 3 /* Slider */, + property: "fov", + iconStart: "FOV", + iconEnd: "", + min: 5, + max: 90, + part: 1 /* Face */ + }, + { + type: 5 /* Misc */, + html: new Html("div").class("flex-group", "col").appendMany(new Html("label").text(__21("Position")), new Html("div").class("flex-group").appendMany(new Html("button").text(__21("Center X")).on("click", () => { + const newPosition = scene.focusCamera(1 /* MiiFullBody */, true, false, true); + let target = new Vector3; + controls.getTarget(target); + target.x = newPosition.x; + controls.moveTo(target.x, target.y, target.z); + }), new Html("button").text(__21("Center Y")).on("click", () => { + const newPosition = scene.focusCamera(1 /* MiiFullBody */, true, false, true); + let target = new Vector3; + controls.getTarget(target); + target.y = newPosition.y; + controls.moveTo(target.x, target.y, target.z); + }), new Html("button").text(__21("Center to body")).on("click", () => { + scene.focusCamera(1 /* MiiFullBody */, true, false); + }), new Html("button").text(__21("Center to head")).on("click", () => { + scene.focusCamera(0 /* MiiHead */, true, false); + })), new Html("label").text(__21("Rotate")), new Html("div").class("flex-group").appendMany(new Html("button").text(__21("Up")).on("click", () => { + scene.getControls().rotateTo(controls.azimuthAngle, controls.polarAngle - rotationFactor); + }), new Html("button").text(__21("Down")).on("click", () => { + scene.getControls().rotateTo(controls.azimuthAngle, controls.polarAngle + rotationFactor); + }), new Html("button").text(__21("Left")).on("click", () => { + scene.getControls().rotateTo(controls.azimuthAngle - rotationFactor, controls.polarAngle); + }), new Html("button").text(__21("Right")).on("click", () => { + scene.getControls().rotateTo(controls.azimuthAngle + rotationFactor, controls.polarAngle); + }), new Html("button").text(__21("Reset")).on("click", () => { + controls.rotateTo(0, Math.PI / 2); + }))), + select() { + } + } + ] + }, + pose: { + label: __21("Pose"), + header: new Html("div").appendMany(new Html("span").html(__21("Change the Body Model option in Settings to get many different options of poses!") + "

" + __21('Do you like the Mii that does the poses? His name is "dummy".') + " "), new Html("a").text(__21("Click here")).on("click", (e2) => { + scene.shutdown(); + parent2.cleanup(); + modal.qs("button")?.elm.click(); + const mii = new Mii(parseHexOrB64ToUint8Array("BAUajXYYt5uiVoD/cJkq8RYY+sFNAGkAaQBDAHIAZQBhAHQAbwByAGQAdQBtAG0AeQAAAAAAAAAAAAAACAAAAAAAQAMACAYDBwMLCAMEEgMNAAAJAGMAAAAACAQACgEAHv///0AABAACFAMTAxMMBAAAAQEKX/8A/wEA")); + importMiiConfirmation(mii, __21("Mii Creator (Special Mii)")); + }), new Html("span").html(" " + __21("to obtain him in your library :)"))), + headerIsHtml: true, + items: ArrayNum(poseCount).map((k4) => ({ + type: 0 /* Icon */, + value: k4, + icon: k4 === 0 ? "None" : ``, + part: 0 /* Head */ + })) + }, + expression: { + label: __21("Expression"), + items: [] + }, + animation: { + label: __21("Animation"), + header: __21("Control the animation speed."), + items: [ + { + type: 3 /* Slider */, + property: "animSpeed", + part: 1 /* Face */, + iconStart: "0x", + iconEnd: "2x", + min: 0, + max: 200 + } + ] + } + }; + expressionTable.forEach(async (k4) => { + let iconTag; + if (Config.renderer.useRendererServer) { + iconTag = ``; + } else { + const icon = await getMiiIcon(miiData, "customRender", "fflmakeicon", 128, k4.id, false).catch((e2) => { + console.error("oh noes, Icon didnt Load", e2); + }); + iconTag = ``; + } + const expressionItem = { + type: 0 /* Icon */, + value: String(k4.id), + icon: iconTag, + part: 0 /* Head */ + }; + e["expression"].items.push(expressionItem); + }); + MiiPagedFeatureSet({ + mii: configuration, + miiIsNotMii: true, + entries: e, + onChange(mii, forceRender, part) { + configuration = mii; + updateConfiguration(); + oldConfiguration = Object.assign({}, configuration); + } + }).style({ height: "auto" }).appendTo(tabsContent); + let playing = true; + if (bodyModelSetting === "wiiu") + playing = false; + let pauseButton = AddButtonSounds(new Html("button").text(playing ? __21("Pause Animation") : __21("Pause Animation")).on("click", () => { + if (playing === true) { + playing = false; + } else { + playing = true; + } + scene.anim.forEach((anim) => { + if (playing === true) { + anim.paused = false; + pauseButton.text(__21("Pause Animation")); + } else { + anim.paused = true; + pauseButton.text(__21("Play Animation")); + } + }); + }).appendTo(tabsContent)); + new Html("button").text(__21("Save Render")).on("click", finalizeRender).appendTo(tabsContent); + function resize() { + let { width: width2, height: height2 } = parentBox.elm.getBoundingClientRect(); + if (width2 < 1024) { + width2 = 1024; + } + if (height2 < 1024) { + height2 = 1024; + } + scene.resize(width2, height2); + scene.getRendererElement().style.height = "100%"; + scene.getRendererElement().style.width = "unset"; + } + window.addEventListener("resize", () => { + resize(); + }); + const scene = new Mii3DScene(miiData, parentBox.elm, 1 /* Screenshot */, (renderer2) => { + }); + controls = scene.getControls(); + window.scene = scene; + const useGreenScreen = await getSetting("customRenderGreenScreen"); + if (useGreenScreen !== "off") { + let color = useGreenScreen; + switch (useGreenScreen) { + case "green": + color = "#00ff00"; + break; + case "blue": + color = "#0000ff"; + break; + case "white": + color = "#ffffff"; + break; + case "black": + color = "#000000"; + break; + } + scene.getScene().background = new Color(color); + } + let oldConfiguration = { + fov: 30, + pose: 0, + expression: "0", + renderWidth: 720, + renderHeight: 720, + animSpeed: 1 + }; + function updateConfiguration() { + scene.getCamera().fov = configuration.fov; + scene.getCamera().updateProjectionMatrix(); + if (oldConfiguration.expression !== configuration.expression) { + scene.traverseAddFaceMaterial(scene.getHead(), `&data=${encodeURIComponent(miiDataHex)}&expression=${configuration.expression}&width=896&verifyCharInfo=0`); + } + const expr = expressionTable.find((e2) => e2.id === parseInt(configuration.expression)); + if (expr) { + if (typeof expr.modifier !== "undefined") { + switch (expr.modifier) { + case 0 /* HideNose */: + scene.getHead().traverse((o) => { + if (o.isMesh !== true) + return; + const m = o; + const modulateType = m.geometry.userData.modulateType; + if (modulateType === 2 /* FFL_MODULATE_TYPE_SHAPE_NOSE */ || modulateType === 7 /* FFL_MODULATE_TYPE_SHAPE_NOSELINE */) { + m.visible = false; + } else { + m.visible = true; + } + }); + break; + case 1 /* HideNoseAndMask */: + scene.getHead().traverse((o) => { + if (o.isMesh !== true) + return; + const m = o; + const modulateType = m.geometry.userData.modulateType; + if (modulateType === 6 /* FFL_MODULATE_TYPE_SHAPE_MASK */ || modulateType === 2 /* FFL_MODULATE_TYPE_SHAPE_NOSE */ || modulateType === 7 /* FFL_MODULATE_TYPE_SHAPE_NOSELINE */) { + m.visible = false; + } else { + m.visible = true; + } + }); + break; + } + } else { + scene.getHead().traverse((o) => { + if (o.isMesh !== true) + return; + const m = o; + m.visible = true; + }); + } + } + const pose = "Pose." + String(configuration.pose).padStart(2, "0"); + if (scene.animations.get(`${scene.type}-${pose}`)) { + scene.swapAnimation(pose); + if (playing === false) { + scene.anim.forEach((a2) => a2.paused = true); + } + } else { + scene.swapAnimation("Wait"); + if (playing === false) { + scene.anim.forEach((a2) => a2.paused = true); + } + } + scene.anim.forEach((a2) => { + a2.timeScale = configuration.animSpeed / 100; + }); + scene.anim.get(scene.type).timeScale *= 0.5; + } + window.scene = scene; + scene.init().then(async () => { + await scene.updateMiiHead(); + if (playing === false) { + scene.anim.forEach((anim) => { + if (playing === true) { + anim.paused = false; + pauseButton.text(__21("Pause Animation")); + } else { + anim.paused = true; + pauseButton.text(__21("Play Animation")); + } + }); + } + scene.focusCamera(1 /* MiiFullBody */, true, false); + parentBox.append(scene.getRendererElement()); + scene.resize(); + }); + let shouldClose = await getSetting("autoCloseCustomRender"); + const rendererElm = scene.getRendererElement(); + function finalizeRender() { + rendererElm.toBlob((blob) => { + const image = new Image(rendererElm.width, rendererElm.height); + image.src = URL.createObjectURL(blob); + image.onload = () => { + downloadLink(image.src, __21("%1_custom_render_%2.png", miiData.nickname, new Date().toJSON())); + if (shouldClose) { + scene.shutdown(); + parent2.cleanup(); + modal.qs("button")?.elm.click(); + } + }; + }); + } + async function save3DModel() { + alert("This option doesn't work at the moment, please try again later."); + } +} + +// src/ui/pages/library/render/renderPresets.ts +var __22 = _8(); +var miiRenderPresets = async (mii, miiData) => { + const renderer2 = new WebGLRenderer({ alpha: true }); + const miiRenderInfo = { + data: miiData.export("studioData"), + module: getFFL(), + renderer: renderer2, + characterYRotate: 0, + expression: 0, + modelFlag: 0, + size: 1440, + additionalInfo: { + favorite: miiData.favorite, + hatCommonColor: miiData.hatCommonColor, + hatFavoriteColor: miiData.hatFavoriteColor, + hatType: miiData.hatType, + pantsColor: miiData.pantsColor, + shirtColor: miiData.shirtColor, + special: miiData.special, + temporary: miiData.temporary, + eyeSclera: miiData.eyeSclera, + wigType: miiData.wigType, + clothesType: miiData.clothesType, + shoesColor: miiData.shoesColor + } + }; + Modal_default.modal(__22("Render options: %1", miiData.nickname), __22("Choose a way to render this Mii"), "body", { + text: "Focus on head", + async callback() { + const renderImage = await createMiiRender({ + ...miiRenderInfo, + type: ViewType2.Face, + drawBody: true + }); + saveBlob(renderImage.result, __22("%1_render_headshot_%2.png", miiData.nickname, new Date().toJSON())); + renderer2.dispose(); + } + }, { + text: "Focus on full body", + async callback() { + const renderImage = await createMiiRender({ + ...miiRenderInfo, + type: ViewType2.AllBodySugar, + drawBody: true + }); + saveBlob(renderImage.result, __22("%1_render_body_%2.png", miiData.nickname, new Date().toJSON())); + renderer2.dispose(); + } + }, { + text: "Head only", + async callback() { + const renderImage = await createMiiRender({ + ...miiRenderInfo, + type: ViewType2.MakeIcon, + drawBody: false + }); + saveBlob(renderImage.result, __22("%1_render_head_only_%2.png", miiData.nickname, new Date().toJSON())); + renderer2.dispose(); + } + }, { + text: "Cancel" + }); +}; + +// src/ui/pages/library/render/renderMenu.ts +var __23 = _8(); +var miiRender = (mii, miiData) => { + Modal_default.modal(__23("Render Mii"), __23("What would you like to do?"), "body", { + text: __23("Download 3D head model"), + async callback() { + Modal_default.modal(__23("Warning"), __23(`3D model download has been disabled due to some buggy normals exporting going on at the moment. +In the meantime, you can use Arian's Mii Renderer to get head models. +Sorry about that.`), "body", ...buttonsOkCancel); + } + }, { + text: __23("Render presets"), + async callback() { + miiRenderPresets(mii, miiData); + } + }, { + text: __23("Custom render"), + async callback() { + customRender(miiData); + } + }, { + text: "Cancel" + }); +}; + +// src/ui/pages/library/export.ts +var __24 = _8(); +var miiExportData = async (mii, miiData) => { + Modal_default.modal(__24("Export Mii"), __24("How would you like to save the Mii?"), "body", { + text: "Cancel" + }, { + text: __24("Save Mii Creator data"), + type: "primary", + async callback() { + const blob = new Blob([miiData.export()]); + const url = URL.createObjectURL(blob); + const a2 = document.createElement("a"); + a2.href = url; + a2.target = "_blank"; + a2.download = miiData.nickname + ".miic"; + document.body.appendChild(a2); + a2.click(); + requestAnimationFrame(() => { + a2.remove(); + }); + setTimeout(() => { + URL.revokeObjectURL(url); + }, 2000); + } + }, { + text: __24("Download other file types..."), + callback(e) { + Modal_default.modal(__24("Other download types"), __24("Choose a file type to download"), "body", { + text: "Cancel", + callback(e2) { + miiExportData(mii, miiData); + } + }, { + text: __24("Download .CharInfo (Switch) file"), + async callback() { + const blob = new Blob([miiData.export("switchCharInfo")]); + const url = URL.createObjectURL(blob); + const a2 = document.createElement("a"); + a2.href = url; + a2.target = "_blank"; + a2.download = miiData.nickname + ".charinfo"; + document.body.appendChild(a2); + a2.click(); + requestAnimationFrame(() => { + a2.remove(); + }); + setTimeout(() => { + URL.revokeObjectURL(url); + }, 2000); + } + }, { + text: __24("Download .FFSD (3DS/Wii U)"), + async callback() { + if (!await miiFFSDWarning(miiData)) + return; + const blob = new Blob([miiData.export("ffsd")]); + const url = URL.createObjectURL(blob); + const a2 = document.createElement("a"); + a2.href = url; + a2.target = "_blank"; + a2.download = miiData.nickname + ".ffsd"; + document.body.appendChild(a2); + a2.click(); + requestAnimationFrame(() => { + a2.remove(); + }); + setTimeout(() => { + URL.revokeObjectURL(url); + }, 2000); + } + }, { + text: __24("Download .RSD (Wii)"), + async callback() { + Modal_default.alert(__24("Notice"), __24("Sorry, RSD export isn't available yet.")); + return; + const blob = new Blob([miiData.export("rsd")]); + const url = URL.createObjectURL(blob); + const a2 = document.createElement("a"); + a2.href = url; + a2.target = "_blank"; + a2.download = miiData.nickname + ".rsd"; + document.body.appendChild(a2); + a2.click(); + requestAnimationFrame(() => { + a2.remove(); + }); + setTimeout(() => { + URL.revokeObjectURL(url); + }, 2000); + } + }); + } + }, { + text: __24("Save Mii as QR Code"), + async callback() { + if (!await miiQRConversionWarning(miiData)) + return; + if (!await Modal_default.prompt(__24("Warning"), __24("Mii Creator QR codes won't save all of this Mii's data at the moment. Mii Creator will never be able to scan back these beta version QR codes and retain all the custom colors and other info. Is this OK?"), "body", true)) + return; + const qrCodeImage = await QRCodeCanvas(miiData, miiData.hasExtendedColors()); + downloadLink(qrCodeImage, `${miiData.nickname}_QR.png`); + } + }, { + text: __24("Show other raw data formats"), + async callback() { + const modal = Modal_default.modal(__24("Miscellaneous Output Formats"), __24("Click inside a code block to select it."), "body", ...buttonsOkCancel); + modal.qs(".modal-content").style({ "max-height": "100vh", "max-width": "600px" }); + modal.qs(".modal-body").prependMany(new Html("div").appendMany(new Html("span").class("h4").text("CharInfo (Switch) data (Hex)"), new Html("pre").class("pre-wrap", "mb-0").text(miiData.exportHex("switchCharInfo"))), new Html("div").appendMany(new Html("span").class("h4").text("Mii Creator data (Base64)"), new Html("pre").class("pre-wrap", "mb-0").text(miiData.exportBase64("miic"))), new Html("div").appendMany(new Html("span").class("h4").text("FFSD (Base64)"), new Html("pre").class("pre-wrap", "mb-0").text(miiData.exportBase64("ffsd"))), new Html("div").appendMany(new Html("span").class("h4").text("FFSD (Hex)"), new Html("pre").class("pre-wrap", "mb-0").text(miiData.exportHex("ffsd"))), new Html("div").appendMany(new Html("span").class("h4").text("Mii Studio data"), new Html("pre").class("pre-wrap", "mb-0").text(miiData.exportHex("studioData")))); + } + }); +}; + +// src/ui/pages/library/new/lookalike.ts +var import_localforage11 = __toESM(require_localforage(), 1); + +// src/external/ffl/FFLiCharInfo.ts +function FFLiiGetEyeRotateOffset(type) { + const ROTATE = [ + 3, + 4, + 4, + 4, + 3, + 4, + 4, + 4, + 3, + 4, + 4, + 4, + 4, + 3, + 3, + 4, + 4, + 4, + 3, + 3, + 4, + 3, + 4, + 3, + 3, + 4, + 3, + 4, + 4, + 3, + 4, + 4, + 4, + 3, + 3, + 3, + 4, + 4, + 3, + 3, + 3, + 4, + 4, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 3, + 4, + 4, + 3, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4 + ]; + return 32 - ROTATE[type]; +} + +// src/external/ffl/RandomParts.ts +var RANDOM_PARTS_ARRAY_FACE_TYPE = [ + [ + [ + [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]], + [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]], + [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]] + ], + [ + [12, [0, 0, 1, 2, 2, 3, 4, 5, 6, 7, 10, 11]], + [13, [0, 1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 10, 11]], + [12, [0, 0, 1, 2, 2, 3, 4, 5, 6, 7, 10, 11]] + ], + [ + [12, [0, 0, 1, 2, 2, 3, 4, 5, 6, 7, 10, 11]], + [13, [0, 1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 10, 11]], + [12, [0, 0, 1, 2, 2, 3, 4, 5, 6, 7, 10, 11]] + ] + ], + [ + [ + [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]], + [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]], + [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]] + ], + [ + [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]], + [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]], + [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]] + ], + [ + [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]], + [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]], + [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]] + ] + ] +]; +var RANDOM_PARTS_ARRAY_HAIR_TYPE = [ + [ + [ + [ + 30, + [ + 13, + 23, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 40, + 43, + 44, + 45, + 47, + 48, + 49, + 50, + 51, + 52, + 54, + 56, + 57, + 64, + 66, + 75, + 76, + 86, + 89 + ] + ], + [ + 31, + [ + 13, + 23, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 40, + 43, + 44, + 45, + 47, + 48, + 49, + 50, + 51, + 52, + 54, + 56, + 57, + 64, + 66, + 73, + 75, + 81, + 86, + 87 + ] + ], + [ + 31, + [ + 13, + 23, + 30, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + 38, + 40, + 43, + 44, + 45, + 47, + 48, + 49, + 50, + 51, + 52, + 54, + 56, + 57, + 64, + 66, + 73, + 75, + 81, + 86, + 87 + ] + ] + ], + [ + [ + 38, + [ + 13, + 23, + 30, + 31, + 32, + 33, + 34, + 36, + 37, + 38, + 40, + 42, + 43, + 44, + 45, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 58, + 59, + 60, + 64, + 65, + 66, + 67, + 68, + 70, + 75, + 76, + 86, + 89 + ] + ], + [ + 39, + [ + 13, + 23, + 30, + 31, + 32, + 33, + 34, + 36, + 37, + 38, + 39, + 40, + 43, + 44, + 45, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 58, + 59, + 60, + 64, + 65, + 66, + 67, + 68, + 70, + 73, + 75, + 81, + 86, + 87 + ] + ], + [ + 39, + [ + 13, + 23, + 30, + 31, + 32, + 33, + 34, + 36, + 37, + 38, + 39, + 40, + 43, + 44, + 45, + 47, + 48, + 49, + 50, + 51, + 52, + 53, + 54, + 55, + 56, + 58, + 59, + 60, + 64, + 65, + 66, + 67, + 68, + 70, + 73, + 75, + 81, + 86, + 87 + ] + ] + ], + [ + [ + 18, + [ + 13, + 23, + 30, + 36, + 37, + 41, + 45, + 47, + 51, + 53, + 54, + 55, + 58, + 59, + 65, + 67, + 86, + 88 + ] + ], + [ + 19, + [ + 13, + 23, + 30, + 36, + 37, + 39, + 41, + 45, + 47, + 51, + 53, + 54, + 55, + 58, + 59, + 65, + 67, + 86, + 88 + ] + ], + [ + 19, + [ + 13, + 23, + 30, + 36, + 37, + 39, + 41, + 45, + 47, + 51, + 53, + 54, + 55, + 58, + 59, + 65, + 67, + 86, + 88 + ] + ] + ] + ], + [ + [ + [ + 39, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 24, + 25, + 26, + 28, + 46, + 50, + 61, + 62, + 63, + 64, + 69, + 76, + 77, + 79, + 80, + 83, + 85 + ] + ], + [ + 42, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 24, + 25, + 26, + 28, + 46, + 50, + 61, + 62, + 63, + 64, + 69, + 72, + 74, + 77, + 78, + 82, + 83, + 84, + 85, + 87 + ] + ], + [ + 42, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 24, + 25, + 26, + 28, + 46, + 50, + 61, + 62, + 63, + 64, + 69, + 72, + 74, + 77, + 78, + 82, + 83, + 84, + 85, + 87 + ] + ] + ], + [ + [ + 44, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 24, + 25, + 26, + 27, + 29, + 42, + 50, + 58, + 60, + 62, + 63, + 64, + 69, + 71, + 76, + 79, + 80, + 81, + 82, + 83, + 86 + ] + ], + [ + 44, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 24, + 25, + 26, + 27, + 29, + 50, + 58, + 60, + 62, + 63, + 64, + 69, + 71, + 72, + 74, + 79, + 81, + 82, + 83, + 84, + 85 + ] + ], + [ + 44, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 24, + 25, + 26, + 27, + 29, + 50, + 58, + 60, + 62, + 63, + 64, + 69, + 71, + 72, + 74, + 79, + 81, + 82, + 83, + 84, + 85 + ] + ] + ], + [ + [ + 24, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 10, + 11, + 12, + 13, + 14, + 16, + 17, + 18, + 20, + 21, + 24, + 25, + 58, + 62, + 69, + 76, + 83 + ] + ], + [ + 27, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 10, + 11, + 12, + 13, + 14, + 16, + 17, + 18, + 20, + 21, + 24, + 25, + 58, + 62, + 69, + 74, + 76, + 81, + 83, + 85 + ] + ], + [ + 27, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 10, + 11, + 12, + 13, + 14, + 16, + 17, + 18, + 20, + 21, + 24, + 25, + 58, + 62, + 69, + 74, + 76, + 81, + 83, + 85 + ] + ] + ] + ] +]; +var RANDOM_PARTS_ARRAY_EYE_TYPE = [ + [ + [ + [ + 26, + [ + 2, + 3, + 5, + 7, + 8, + 9, + 11, + 12, + 13, + 15, + 16, + 18, + 27, + 29, + 32, + 34, + 36, + 38, + 39, + 41, + 43, + 47, + 49, + 51, + 53, + 57 + ] + ], + [ + 26, + [ + 2, + 3, + 5, + 7, + 8, + 9, + 11, + 12, + 13, + 15, + 16, + 18, + 27, + 29, + 32, + 34, + 36, + 38, + 39, + 41, + 43, + 47, + 49, + 51, + 53, + 57 + ] + ], + [ + 27, + [ + 2, + 3, + 5, + 7, + 8, + 9, + 11, + 12, + 13, + 15, + 16, + 18, + 26, + 27, + 29, + 32, + 34, + 36, + 38, + 39, + 41, + 43, + 47, + 48, + 49, + 53, + 57 + ] + ] + ], + [ + [ + 35, + [ + 2, + 3, + 5, + 6, + 7, + 8, + 9, + 11, + 12, + 13, + 15, + 16, + 17, + 18, + 21, + 22, + 27, + 29, + 31, + 32, + 34, + 36, + 37, + 38, + 39, + 41, + 43, + 44, + 47, + 49, + 51, + 53, + 55, + 56, + 57 + ] + ], + [ + 35, + [ + 2, + 3, + 5, + 6, + 7, + 8, + 9, + 11, + 12, + 13, + 15, + 16, + 17, + 18, + 21, + 22, + 27, + 29, + 31, + 32, + 34, + 36, + 37, + 38, + 39, + 41, + 43, + 44, + 47, + 49, + 51, + 53, + 55, + 56, + 57 + ] + ], + [ + 35, + [ + 2, + 3, + 5, + 6, + 7, + 8, + 9, + 11, + 12, + 13, + 15, + 16, + 18, + 21, + 22, + 26, + 27, + 29, + 31, + 32, + 34, + 36, + 37, + 38, + 39, + 41, + 43, + 44, + 47, + 48, + 49, + 50, + 53, + 56, + 57 + ] + ] + ], + [ + [ + 30, + [ + 2, + 3, + 5, + 7, + 8, + 9, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 21, + 22, + 31, + 32, + 34, + 36, + 37, + 39, + 41, + 44, + 49, + 51, + 53, + 55, + 56, + 57 + ] + ], + [ + 30, + [ + 2, + 3, + 5, + 7, + 8, + 9, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 21, + 22, + 31, + 32, + 34, + 36, + 37, + 39, + 41, + 44, + 49, + 51, + 53, + 55, + 56, + 57 + ] + ], + [ + 30, + [ + 2, + 3, + 5, + 7, + 8, + 9, + 11, + 12, + 13, + 14, + 15, + 16, + 18, + 21, + 22, + 26, + 31, + 32, + 34, + 36, + 37, + 39, + 41, + 44, + 48, + 49, + 50, + 51, + 53, + 57 + ] + ] + ] + ], + [ + [ + [ + 39, + [ + 0, + 1, + 2, + 4, + 5, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 15, + 16, + 18, + 19, + 23, + 24, + 25, + 27, + 28, + 29, + 32, + 33, + 34, + 35, + 38, + 39, + 40, + 41, + 42, + 45, + 46, + 47, + 48, + 53, + 54, + 57, + 59 + ] + ], + [ + 39, + [ + 0, + 1, + 2, + 4, + 5, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 15, + 16, + 18, + 19, + 23, + 24, + 25, + 27, + 28, + 29, + 32, + 33, + 34, + 35, + 38, + 39, + 40, + 41, + 42, + 45, + 46, + 47, + 48, + 53, + 54, + 57, + 59 + ] + ], + [ + 40, + [ + 0, + 1, + 2, + 4, + 5, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 15, + 16, + 18, + 19, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 32, + 33, + 34, + 35, + 38, + 39, + 40, + 41, + 42, + 45, + 46, + 47, + 48, + 53, + 54, + 57, + 59 + ] + ] + ], + [ + [ + 46, + [ + 0, + 1, + 2, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 23, + 24, + 25, + 27, + 28, + 29, + 30, + 32, + 33, + 34, + 35, + 37, + 38, + 39, + 40, + 41, + 42, + 45, + 46, + 47, + 48, + 53, + 54, + 57, + 58, + 59 + ] + ], + [ + 46, + [ + 0, + 1, + 2, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 23, + 24, + 25, + 27, + 28, + 29, + 30, + 32, + 33, + 34, + 35, + 37, + 38, + 39, + 40, + 41, + 42, + 45, + 46, + 47, + 48, + 53, + 54, + 57, + 58, + 59 + ] + ], + [ + 46, + [ + 0, + 1, + 2, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 15, + 16, + 18, + 19, + 20, + 21, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 32, + 33, + 34, + 35, + 37, + 38, + 39, + 40, + 41, + 42, + 45, + 46, + 47, + 48, + 53, + 54, + 57, + 58, + 59 + ] + ] + ], + [ + [ + 34, + [ + 0, + 1, + 2, + 4, + 5, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 15, + 16, + 18, + 19, + 23, + 24, + 25, + 27, + 28, + 29, + 32, + 33, + 34, + 35, + 38, + 39, + 40, + 41, + 42, + 45, + 46, + 47 + ] + ], + [ + 34, + [ + 0, + 1, + 2, + 4, + 5, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 15, + 16, + 18, + 19, + 23, + 24, + 25, + 27, + 28, + 29, + 32, + 33, + 34, + 35, + 38, + 39, + 40, + 41, + 42, + 45, + 46, + 47 + ] + ], + [ + 35, + [ + 0, + 1, + 2, + 4, + 5, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 15, + 16, + 18, + 19, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 32, + 33, + 34, + 35, + 38, + 39, + 40, + 41, + 42, + 45, + 46, + 47 + ] + ] + ] + ] +]; +var RANDOM_PARTS_ARRAY_EYEBROW_TYPE = [ + [ + [ + [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18, 20]], + [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18, 20]], + [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18, 20]] + ], + [ + [ + 23, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22 + ] + ], + [ + 23, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22 + ] + ], + [ + 23, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22 + ] + ] + ], + [ + [ + 21, + [ + 0, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 22 + ] + ], + [ + 21, + [ + 0, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 22 + ] + ], + [ + 21, + [ + 0, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 20, + 21, + 22 + ] + ] + ] + ], + [ + [ + [9, [0, 1, 3, 7, 8, 9, 10, 11, 13]], + [9, [0, 1, 3, 7, 8, 9, 10, 11, 13]], + [9, [0, 1, 3, 7, 8, 9, 10, 11, 13]] + ], + [ + [11, [0, 1, 3, 7, 8, 9, 10, 11, 13, 15, 19]], + [11, [0, 1, 3, 7, 8, 9, 10, 11, 13, 15, 19]], + [11, [0, 1, 3, 7, 8, 9, 10, 11, 13, 15, 19]] + ], + [ + [9, [0, 3, 7, 8, 9, 10, 11, 13, 15]], + [9, [0, 3, 7, 8, 9, 10, 11, 13, 15]], + [9, [0, 3, 7, 8, 9, 10, 11, 13, 15]] + ] + ] +]; +var RANDOM_PARTS_ARRAY_NOSE_TYPE = [ + [ + [ + [11, [0, 1, 2, 3, 4, 5, 7, 8, 10, 13, 14]], + [11, [0, 1, 2, 3, 4, 5, 7, 8, 10, 13, 14]], + [11, [0, 1, 2, 3, 4, 5, 7, 8, 10, 13, 14]] + ], + [ + [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]], + [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]], + [15, [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16]] + ], + [ + [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]], + [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]], + [15, [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16]] + ] + ], + [ + [ + [8, [0, 1, 3, 4, 8, 10, 13, 14]], + [8, [0, 1, 3, 4, 8, 10, 13, 14]], + [8, [0, 1, 3, 4, 8, 10, 13, 14]] + ], + [ + [12, [0, 1, 3, 4, 6, 8, 9, 10, 11, 13, 14, 15]], + [11, [0, 1, 3, 4, 6, 8, 9, 10, 11, 13, 15]], + [10, [0, 1, 3, 4, 6, 8, 10, 11, 13, 14]] + ], + [ + [12, [0, 1, 3, 4, 6, 8, 9, 10, 11, 13, 14, 15]], + [11, [0, 1, 3, 4, 6, 8, 9, 10, 11, 13, 15]], + [10, [0, 1, 3, 4, 6, 8, 10, 11, 13, 14]] + ] + ] +]; +var RANDOM_PARTS_ARRAY_MOUTH_TYPE = [ + [ + [ + [ + 25, + [ + 0, + 2, + 3, + 6, + 7, + 8, + 9, + 10, + 12, + 14, + 15, + 17, + 18, + 19, + 21, + 22, + 23, + 25, + 26, + 28, + 30, + 32, + 33, + 34, + 35 + ] + ], + [ + 27, + [ + 0, + 2, + 3, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 17, + 18, + 19, + 21, + 22, + 23, + 25, + 26, + 28, + 30, + 32, + 33, + 34, + 35 + ] + ], + [ + 28, + [ + 0, + 2, + 3, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 17, + 18, + 19, + 21, + 22, + 23, + 25, + 26, + 28, + 30, + 31, + 32, + 33, + 34, + 35 + ] + ] + ], + [ + [ + 24, + [ + 0, + 2, + 3, + 6, + 7, + 8, + 9, + 10, + 12, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 30, + 31, + 33, + 34, + 35 + ] + ], + [ + 26, + [ + 0, + 2, + 3, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 30, + 31, + 33, + 34, + 35 + ] + ], + [ + 26, + [ + 0, + 2, + 3, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 30, + 31, + 33, + 34, + 35 + ] + ] + ], + [ + [ + 24, + [ + 0, + 2, + 3, + 6, + 7, + 8, + 9, + 10, + 12, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 30, + 31, + 33, + 34, + 35 + ] + ], + [ + 26, + [ + 0, + 2, + 3, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 30, + 31, + 33, + 34, + 35 + ] + ], + [ + 26, + [ + 0, + 2, + 3, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 30, + 31, + 33, + 34, + 35 + ] + ] + ] + ], + [ + [ + [ + 25, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 12, + 14, + 15, + 17, + 18, + 19, + 21, + 22, + 23, + 25, + 26, + 30, + 33, + 34, + 35 + ] + ], + [ + 26, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 12, + 13, + 14, + 15, + 17, + 18, + 19, + 21, + 22, + 23, + 25, + 26, + 30, + 33, + 34, + 35 + ] + ], + [ + 26, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 12, + 13, + 14, + 15, + 17, + 18, + 19, + 21, + 22, + 23, + 25, + 26, + 30, + 33, + 34, + 35 + ] + ] + ], + [ + [ + 25, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 12, + 14, + 15, + 17, + 18, + 19, + 21, + 22, + 23, + 24, + 26, + 27, + 29, + 33, + 35 + ] + ], + [ + 26, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 12, + 13, + 14, + 15, + 17, + 18, + 19, + 21, + 22, + 23, + 24, + 26, + 27, + 29, + 33, + 35 + ] + ], + [ + 25, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 12, + 13, + 14, + 15, + 17, + 18, + 19, + 21, + 22, + 23, + 24, + 25, + 29, + 33, + 35 + ] + ] + ], + [ + [ + 24, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 12, + 14, + 15, + 16, + 17, + 18, + 19, + 21, + 22, + 23, + 25, + 26, + 29, + 33 + ] + ], + [ + 25, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 21, + 22, + 23, + 25, + 26, + 29, + 33 + ] + ], + [ + 25, + [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 21, + 22, + 23, + 25, + 26, + 29, + 33 + ] + ] + ] + ] +]; +var RANDOM_PARTS_ARRAY_FACE_LINE = [ + [ + [ + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8]] + ], + [ + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] + ], + [ + [ + 20, + [ + 9, + 9, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 11, + 11, + 11, + 11, + 11, + 11, + 11, + 11, + 11 + ] + ], + [ + 20, + [ + 9, + 9, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 11, + 11, + 11, + 11, + 11, + 11, + 11, + 11, + 11 + ] + ], + [ + 20, + [ + 9, + 9, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 11, + 11, + 11, + 11, + 11, + 11, + 11, + 11, + 11 + ] + ] + ] + ], + [ + [ + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]] + ], + [ + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 4, 8, 8]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 4, 8, 8]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 4]] + ], + [ + [ + 20, + [ + 9, + 9, + 9, + 9, + 9, + 9, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 11, + 11, + 11, + 11, + 11 + ] + ], + [ + 20, + [ + 9, + 9, + 9, + 9, + 9, + 9, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 11, + 11, + 11, + 11, + 11 + ] + ], + [ + 20, + [ + 9, + 9, + 9, + 9, + 9, + 9, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 10, + 11, + 11, + 11, + 11, + 11 + ] + ] + ] + ] +]; +var RANDOM_PARTS_ARRAY_FACE_MAKEUP = [ + [ + [ + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9]] + ], + [ + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]] + ], + [ + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]] + ] + ], + [ + [ + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 9, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 9, 9]] + ], + [ + [20, [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9]], + [20, [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]], + [20, [0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9, 9]] + ], + [ + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] + ] + ] +]; +var RANDOM_PARTS_ARRAY_FACELINE_COLOR = [ + [ + [10, [2, 2, 4, 4, 4, 4, 5, 5, 5, 5]], + [10, [0, 0, 0, 0, 1, 1, 2, 3, 3, 3]], + [10, [0, 0, 1, 1, 1, 1, 1, 1, 1, 2]] + ], + [ + [10, [2, 2, 4, 4, 4, 4, 5, 5, 5, 5]], + [10, [0, 0, 0, 0, 0, 0, 0, 0, 1, 3]], + [10, [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]] + ] +]; +var RANDOM_PARTS_ARRAY_HAIR_COLOR = [ + [ + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], + [20, [0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]] + ], + [ + [20, [2, 3, 3, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7]], + [20, [2, 3, 3, 3, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7]], + [20, [2, 3, 3, 4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7]] + ], + [ + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]], + [20, [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3]], + [20, [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]] + ] +]; +var RANDOM_PARTS_ARRAY_EYE_COLOR = [ + [10, [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], + [10, [0, 1, 1, 2, 3, 3, 4, 4, 4, 5]], + [10, [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]] +]; + +// src/external/ffl/FFLTypes.ts +function FFLiiGetEyebrowRotateOffset(type) { + const ROTATE = [ + 6, + 6, + 5, + 7, + 6, + 7, + 6, + 7, + 4, + 7, + 6, + 8, + 5, + 5, + 6, + 6, + 7, + 7, + 6, + 6, + 5, + 6, + 7, + 5, + 6, + 6, + 6, + 6 + ]; + return 32 - ROTATE[type]; +} +var FFL_MOUTH_COLOR_MAX = 5; + +// src/external/ffl/FFLiDatabaseRandom.ts +function DetermineParam(pGender, pAge, pRace) { + let gender = pGender, age = pAge, race = pRace; + if (pGender == 2 /* FFL_GENDER_MAX */) { + const rnd = Math.floor(Math.random() * 2); + gender = rnd == 0 ? 0 /* FFL_GENDER_MALE */ : 1 /* FFL_GENDER_FEMALE */; + } + if (pAge == 3 /* FFL_AGE_MAX */) { + const rnd = Math.floor(Math.random() * 10); + age = rnd < 4 ? 0 /* FFL_AGE_CHILD */ : rnd < 8 ? 1 /* FFL_AGE_ADULT */ : 2 /* FFL_AGE_ELDER */; + } + if (pRace == 3 /* FFL_RACE_MAX */) { + const rnd = Math.floor(Math.random() * 10); + race = rnd < 4 ? 2 /* FFL_RACE_ASIAN */ : rnd < 8 ? 1 /* FFL_RACE_WHITE */ : 0 /* FFL_RACE_BLACK */; + } + return [gender, age, race]; +} +function GetRandomGlassType(age) { + let target = Math.floor(Math.random() * 100); + let type = 0; + while (target >= RANDOM_GLASS_TYPE[age][type]) + type++; + return type; +} +function GetRandomParts(array) { + return array[1][Math.floor(Math.random() * array[0])]; +} +var RANDOM_GLASS_TYPE = [ + [90, 94, 96, 100, 0, 0, 0, 0, 0], + [83, 86, 90, 93, 94, 96, 98, 100, 0], + [78, 83, 0, 93, 0, 0, 98, 100, 0] +]; +var EYE_Y_TO_GLASS_Y = [ + 0, + 0, + 0, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 11, + 12, + 13, + 14, + 15, + 16 +]; +function roll(minPercentage) { + if (Math.floor(Math.random() * 100) >= 100 - minPercentage) { + return true; + } + return false; +} +function FFLiDatabaseRandom_Get(pCharInfo, fixedSettings) { + let [pGender, pAge, pRace] = [ + 2 /* FFL_GENDER_MAX */, + 3 /* FFL_AGE_MAX */, + 3 /* FFL_RACE_MAX */ + ]; + let [gender, age, race] = DetermineParam(pGender, pAge, pRace); + if (fixedSettings.age !== undefined) { + age = fixedSettings.age; + } + if (fixedSettings.gender !== undefined) { + gender = fixedSettings.gender; + } + if (fixedSettings.race !== undefined) { + race = fixedSettings.race; + } + console.log("Gender,age,race", gender, age, race); + pCharInfo.originPlatform = 3 /* FFL_Wii_U */; + let basePositionY = 0; + if (gender == 1 /* FFL_GENDER_FEMALE */ || age == 0 /* FFL_AGE_CHILD */) + basePositionY = Math.floor(Math.random() * 3); + pCharInfo.facelineType = GetRandomParts(RANDOM_PARTS_ARRAY_FACE_TYPE[gender][age][race]); + pCharInfo.facelineColor = GetRandomParts(RANDOM_PARTS_ARRAY_FACELINE_COLOR[gender][race]); + pCharInfo.facelineWrinkle = GetRandomParts(RANDOM_PARTS_ARRAY_FACE_LINE[gender][age][race]); + pCharInfo.facelineMake = GetRandomParts(RANDOM_PARTS_ARRAY_FACE_MAKEUP[gender][age][race]); + pCharInfo.hairType = GetRandomParts(RANDOM_PARTS_ARRAY_HAIR_TYPE[gender][age][race]); + pCharInfo.hairColor = Ver3HairColorTable[GetRandomParts(RANDOM_PARTS_ARRAY_HAIR_COLOR[race][age])]; + if (fixedSettings.hairColor !== undefined) { + pCharInfo.hairColor = Ver3HairColorTable[fixedSettings.hairColor]; + } + pCharInfo.hairFlip = Math.ceil(Math.random() * 2) - 1; + pCharInfo.eyeType = GetRandomParts(RANDOM_PARTS_ARRAY_EYE_TYPE[gender][age][race]); + pCharInfo.eyeColor = Ver3EyeColorTable[GetRandomParts(RANDOM_PARTS_ARRAY_EYE_COLOR[race])]; + if (fixedSettings.eyeColor !== undefined) { + pCharInfo.eyeColor = Ver3EyeColorTable[fixedSettings.eyeColor]; + } + pCharInfo.eyeScale = 4; + pCharInfo.eyeAspect = 3; + let eyeRotateOffsetTarget; + if (gender == 0 /* FFL_GENDER_MALE */) { + pCharInfo.eyeRotate = 4; + eyeRotateOffsetTarget = FFLiiGetEyeRotateOffset(2); + } else { + pCharInfo.eyeRotate = 3; + eyeRotateOffsetTarget = FFLiiGetEyeRotateOffset(4); + } + const eyeRotateOffsetBase = FFLiiGetEyeRotateOffset(pCharInfo.eyeType); + pCharInfo.eyeX = 2; + pCharInfo.eyeY = basePositionY + 12; + pCharInfo.eyeRotate += eyeRotateOffsetTarget - eyeRotateOffsetBase; + pCharInfo.eyebrowType = GetRandomParts(RANDOM_PARTS_ARRAY_EYEBROW_TYPE[gender][age][race]); + pCharInfo.eyebrowColor = pCharInfo.hairColor; + pCharInfo.eyebrowScale = 4; + pCharInfo.eyebrowAspect = 3; + pCharInfo.eyebrowRotate = 6; + pCharInfo.eyebrowX = 2; + let eyebrowRotateOffsetTarget; + if (race == 2 /* FFL_RACE_ASIAN */) { + pCharInfo.eyebrowY = basePositionY + 9; + eyebrowRotateOffsetTarget = FFLiiGetEyebrowRotateOffset(6); + } else { + pCharInfo.eyebrowY = basePositionY + 10; + eyebrowRotateOffsetTarget = FFLiiGetEyebrowRotateOffset(0); + } + const eyebrowRotateOffsetBase = FFLiiGetEyebrowRotateOffset(pCharInfo.eyebrowType); + pCharInfo.eyebrowRotate += eyebrowRotateOffsetTarget - eyebrowRotateOffsetBase; + pCharInfo.noseType = GetRandomParts(RANDOM_PARTS_ARRAY_NOSE_TYPE[gender][age][race]); + pCharInfo.noseScale = gender == 0 /* FFL_GENDER_MALE */ ? 4 : 3; + pCharInfo.noseY = basePositionY + 9; + pCharInfo.mouthType = GetRandomParts(RANDOM_PARTS_ARRAY_MOUTH_TYPE[gender][age][race]); + pCharInfo.mouthColor = Ver3MouthColorTable[gender == 0 /* FFL_GENDER_MALE */ ? 0 : Math.floor(Math.random() * FFL_MOUTH_COLOR_MAX)]; + pCharInfo.mouthScale = 4; + pCharInfo.mouthAspect = 3; + pCharInfo.mouthY = basePositionY + 13; + let mustacheType, beardType, mustachePositionY; + if (gender == 0 /* FFL_GENDER_MALE */ && (age == 1 /* FFL_AGE_ADULT */ || age == 2 /* FFL_AGE_ELDER */) && Math.floor(Math.random() * 10) < 2) { + mustacheType = 0; + let randomBeardType = false; + switch (Math.floor(Math.random() * 3)) { + case 0: + randomBeardType = true; + break; + case 2: + randomBeardType = true; + case 1: + mustacheType = Math.floor(Math.random() * 5) + 1; + break; + } + beardType = randomBeardType ? Math.floor(Math.random() * 5) + 1 : 0; + mustachePositionY = 10; + } else { + mustacheType = 0; + beardType = 0; + mustachePositionY = basePositionY + 10; + } + pCharInfo.mustacheType = mustacheType; + pCharInfo.beardType = beardType; + pCharInfo.beardColor = pCharInfo.hairColor; + pCharInfo.mustacheScale = 4; + pCharInfo.mustacheY = mustachePositionY; + pCharInfo.glassType = GetRandomGlassType(age); + pCharInfo.glassColor = Ver3GlassColorTable[Math.floor(Math.random() * 6)]; + pCharInfo.glassScale = 4; + pCharInfo.glassY = basePositionY + 10; + pCharInfo.moleType = 0; + pCharInfo.moleScale = 4; + pCharInfo.moleX = 2; + pCharInfo.moleY = 20; + pCharInfo.height = 64; + pCharInfo.build = 64; + pCharInfo.nickname = "no name"; + pCharInfo.gender = gender; + pCharInfo.birthMonth = 0; + pCharInfo.birthDay = 0; + pCharInfo.favoriteColor = Math.floor(Math.random() * 12 /* FFL_FAVORITE_COLOR_MAX */); + if (fixedSettings.favoriteColor !== undefined) { + pCharInfo.favoriteColor = fixedSettings.favoriteColor; + } + pCharInfo.favorite = 0; +} +function RandomizeMii(pCharInfo, options) { + let [pGender, pAge, pRace] = [ + 2 /* FFL_GENDER_MAX */, + 3 /* FFL_AGE_MAX */, + 3 /* FFL_RACE_MAX */ + ]; + let [gender, age, race] = DetermineParam(pGender, pAge, pRace); + if (options.age !== undefined) { + age = options.age; + } + if (options.gender !== undefined) { + gender = options.gender; + } + if (options.race !== undefined) { + race = options.race; + } + let basePositionY = 0; + if (gender == 1 /* FFL_GENDER_FEMALE */ || age == 0 /* FFL_AGE_CHILD */) + basePositionY = Math.floor(Math.random() * 3); + if (roll(6)) + pCharInfo.facelineType = GetRandomParts(RANDOM_PARTS_ARRAY_FACE_TYPE[gender][age][race]); + if (roll(5)) + pCharInfo.facelineColor = GetRandomParts(RANDOM_PARTS_ARRAY_FACELINE_COLOR[gender][race]); + if (roll(5)) + pCharInfo.facelineWrinkle = GetRandomParts(RANDOM_PARTS_ARRAY_FACE_LINE[gender][age][race]); + if (roll(5)) + pCharInfo.facelineMake = GetRandomParts(RANDOM_PARTS_ARRAY_FACE_MAKEUP[gender][age][race]); + if (roll(7)) + pCharInfo.hairType = GetRandomParts(RANDOM_PARTS_ARRAY_HAIR_TYPE[gender][age][race]); + if (roll(5)) + pCharInfo.hairColor = Ver3HairColorTable[GetRandomParts(RANDOM_PARTS_ARRAY_HAIR_COLOR[race][age])]; + if (options.hairColor !== undefined) { + pCharInfo.hairColor = Ver3HairColorTable[options.hairColor]; + } + if (roll(15)) + pCharInfo.hairFlip = Math.ceil(Math.random() * 2) - 1; + if (roll(10)) + pCharInfo.eyeType = GetRandomParts(RANDOM_PARTS_ARRAY_EYE_TYPE[gender][age][race]); + if (roll(5)) + pCharInfo.eyeColor = Ver3EyeColorTable[GetRandomParts(RANDOM_PARTS_ARRAY_EYE_COLOR[race])]; + if (options.eyeColor !== undefined) { + pCharInfo.eyeColor = Ver3EyeColorTable[options.eyeColor]; + } + if (options.isOriginalMii !== true) { + pCharInfo.eyeScale = 4; + pCharInfo.eyeAspect = 3; + let eyeRotateOffsetTarget; + if (gender == 0 /* FFL_GENDER_MALE */) { + pCharInfo.eyeRotate = 4; + eyeRotateOffsetTarget = FFLiiGetEyeRotateOffset(2); + } else { + pCharInfo.eyeRotate = 3; + eyeRotateOffsetTarget = FFLiiGetEyeRotateOffset(4); + } + const eyeRotateOffsetBase = FFLiiGetEyeRotateOffset(pCharInfo.eyeType); + pCharInfo.eyeRotate += eyeRotateOffsetTarget - eyeRotateOffsetBase; + } + if (roll(15)) + pCharInfo.eyebrowType = GetRandomParts(RANDOM_PARTS_ARRAY_EYEBROW_TYPE[gender][age][race]); + if (options.isOriginalMii !== true) { + pCharInfo.eyebrowColor = pCharInfo.hairColor; + pCharInfo.eyebrowScale = 4; + pCharInfo.eyebrowAspect = 3; + pCharInfo.eyebrowRotate = 6; + pCharInfo.eyebrowX = 2; + let eyebrowRotateOffsetTarget; + if (race == 2 /* FFL_RACE_ASIAN */) { + pCharInfo.eyebrowY = basePositionY + 9; + eyebrowRotateOffsetTarget = FFLiiGetEyebrowRotateOffset(6); + } else { + pCharInfo.eyebrowY = basePositionY + 10; + eyebrowRotateOffsetTarget = FFLiiGetEyebrowRotateOffset(0); + } + const eyebrowRotateOffsetBase = FFLiiGetEyebrowRotateOffset(pCharInfo.eyebrowType); + pCharInfo.eyebrowRotate += eyebrowRotateOffsetTarget - eyebrowRotateOffsetBase; + } + if (roll(15)) + pCharInfo.noseType = GetRandomParts(RANDOM_PARTS_ARRAY_NOSE_TYPE[gender][age][race]); + if (options.isOriginalMii !== true) { + pCharInfo.noseScale = gender == 0 /* FFL_GENDER_MALE */ ? 4 : 3; + pCharInfo.noseY = basePositionY + 9; + } + pCharInfo.mouthType = GetRandomParts(RANDOM_PARTS_ARRAY_MOUTH_TYPE[gender][age][race]); + if (roll(15)) + pCharInfo.mouthColor = Ver3MouthColorTable[gender == 0 /* FFL_GENDER_MALE */ ? 0 : Math.floor(Math.random() * FFL_MOUTH_COLOR_MAX)]; + if (options.isOriginalMii !== true) { + pCharInfo.mouthScale = 4; + pCharInfo.mouthAspect = 3; + pCharInfo.mouthY = basePositionY + 13; + } + let mustacheType, beardType, mustachePositionY; + if (gender == 0 /* FFL_GENDER_MALE */ && (age == 1 /* FFL_AGE_ADULT */ || age == 2 /* FFL_AGE_ELDER */) && Math.floor(Math.random() * 10) < 2) { + mustacheType = 0; + let randomBeardType = false; + switch (Math.floor(Math.random() * 3)) { + case 0: + randomBeardType = true; + break; + case 2: + randomBeardType = true; + case 1: + if (roll(15)) + mustacheType = Math.floor(Math.random() * 5) + 1; + break; + } + beardType = randomBeardType ? Math.floor(Math.random() * 5) + 1 : 0; + mustachePositionY = 10; + } else { + mustacheType = 0; + beardType = 0; + mustachePositionY = basePositionY + 10; + } + if (roll(20)) + pCharInfo.mustacheType = mustacheType; + if (roll(20)) + pCharInfo.beardType = beardType; + pCharInfo.beardColor = pCharInfo.hairColor; + if (options.isOriginalMii !== true) { + pCharInfo.mustacheScale = 4; + pCharInfo.mustacheY = mustachePositionY; + } else { + if (pCharInfo.glassType === 0) { + pCharInfo.glassY = EYE_Y_TO_GLASS_Y[pCharInfo.eyeY]; + } + } + pCharInfo.glassType = GetRandomGlassType(age); + if (roll(20)) + pCharInfo.glassColor = Ver3GlassColorTable[Math.floor(Math.random() * 6)]; + if (options.isOriginalMii !== true) { + pCharInfo.glassScale = 4; + pCharInfo.glassY = basePositionY + 10; + } +} +window.mii = Mii; +window.FFLiDatabaseRandom_Get = FFLiDatabaseRandom_Get; + +// src/ui/pages/library/new/_dialog.ts +var import_localforage10 = __toESM(require_localforage(), 1); + +// src/ui/pages/library/new/fromScratch.ts +var import_localforage7 = __toESM(require_localforage(), 1); +var __25 = _8(); +var newFromScratch = () => { + function cb(gender) { + return () => { + _shutdown()(); + new MiiEditor2(gender, async (m2, shouldSave) => { + if (shouldSave === true) + await import_localforage7.default.setItem(await newMiiId(), m2); + await pushToServer(); + Library(); + }); + }; + } + var m = Modal_default.modal(__25("Create Mii"), __25("Select the Mii's gender"), "body", { + text: __25("Male"), + callback: cb(0 /* Male */) + }, { + text: __25("Female"), + callback: cb(1 /* Female */) + }, { + text: "Cancel", + callback: () => miiCreateDialog() + }); + const genderMaleButton = m.qs(".modal-body button:nth-child(1)"); + const genderFemaleButton = m.qs(".modal-body button:nth-child(2)"); + if (genderMaleButton) { + genderMaleButton.classOn("gender-select-btn"); + genderMaleButton.prepend(new Html("span").html(EditorIcons_default.genderMaleLg)); + } + if (genderFemaleButton) { + genderFemaleButton.classOn("gender-select-btn"); + genderFemaleButton.prepend(new Html("span").html(EditorIcons_default.genderFemaleLg)); + } +}; + +// src/util/DecodeQRCode.ts +var import_qr_scanner_umd_min = __toESM(require_qr_scanner_umd_min(), 1); +var AES_CCM_KEY_HEX = "59FC817E6446EA6190347B20E9BDCE52"; +var AES_CTR_KEY_HEX = "30819F300D06092A864886F70D010101"; +var AES_CCM_KEY_BITS = sjcl_min_default.codec.hex.toBits(AES_CCM_KEY_HEX); +var crypto2 = window.crypto; +var sc = crypto2.subtle; +function QrScannerError(message) { + if (message === "Camera not found.") { + message += ` +Check your browser settings and make sure it isn't disabled. +If you don't have a camera, you can disable the option in Mii Creator settings.`; + } + var m = Modal_default.modal("QR Scanner Error", message, "body", { + text: "Cancel" + }, { + text: "OK" + }); + m.qs(".modal-content").styleJs({ minWidth: "360px" }); +} +function hexToUint8Array2(hex) { + const bytes = new Uint8Array(hex.length / 2); + for (let i = 0;i < bytes.length; i++) { + bytes[i] = parseInt(hex.substring(i * 2, 2), 16); + } + return bytes; +} +var CRC32_CKSUM_POLYNOMIAL = 79764919; +var crc32CksumTable = new Uint32Array(256); +function generateCrc32CksumTable() { + for (let i = 0;i < 256; i++) { + let crc = i << 24; + for (let j2 = 0;j2 < 8; j2++) { + if (crc & 2147483648) { + crc = crc << 1 ^ CRC32_CKSUM_POLYNOMIAL; + } else { + crc = crc << 1; + } + } + crc32CksumTable[i] = crc >>> 0; + } +} +generateCrc32CksumTable(); +function decryptAesCcm(encryptedData) { + if (encryptedData.length < 112) { + throw new Error("Mii QR codes should be 112 or more bytes long, yours is " + encryptedData.length); + } + const nonce = encryptedData.slice(0, 8); + const encryptedContent = encryptedData.slice(8); + const cipher = new sjcl_min_default.cipher.aes(AES_CCM_KEY_BITS); + const encryptedBits = sjcl_min_default.codec.bytes.toBits(Array.from(encryptedContent)); + const nonceBits = sjcl_min_default.codec.bytes.toBits([...nonce, 0, 0, 0, 0]); + const tlen = 128; + const out = sjcl_min_default.bitArray.clamp(encryptedBits, sjcl_min_default.bitArray.bitLength(encryptedBits) - tlen); + const ctrDecrypt = sjcl_min_default.mode.ccm._ctrMode || sjcl_min_default.mode.ccm.C; + const decryptedBits = ctrDecrypt(cipher, out, nonceBits, [], tlen, 3); + const decryptedBytes = sjcl_min_default.codec.bytes.fromBits(decryptedBits.data); + const decryptedSlice = new Uint8Array(decryptedBytes).slice(0, 88); + return new Uint8Array([ + ...decryptedSlice.slice(0, 12), + ...nonce, + ...decryptedSlice.slice(12) + ]); +} +async function decryptAesCtr(encryptedData, iv) { + const key2 = await sc.importKey("raw", hexToUint8Array2(AES_CTR_KEY_HEX), { name: "AES-CTR" }, false, ["decrypt"]); + const decrypted = await sc.decrypt({ name: "AES-CTR", counter: iv, length: 128 }, key2, encryptedData.buffer); + return new Uint8Array(decrypted); +} +var cameraScanner; +async function startScanner(camList) { + console.log("startScanner()"); + cameraScanner = new import_qr_scanner_umd_min.default(document.getElementById("qr-video"), (result) => handleQrCode(result), { + onDecodeError: (error) => { + if (error === "No QR code found") + return; + console.log("QR scan error:", error); + }, + highlightScanRegion: true, + highlightCodeOutline: true + }); + const allowCam = await getSetting("allowQrCamera"); + if (allowCam) { + cameraScanner.start().then(() => { + const existingCameras = document.getElementsByClassName("device-camera"); + Array.from(existingCameras).forEach((camera) => { + camera.remove(); + }); + import_qr_scanner_umd_min.default.listCameras(true).then((cameras) => cameras.forEach((camera) => { + const option = document.createElement("option"); + option.value = camera.id; + option.text = camera.label; + option.className = "device-camera"; + camList.appendChild(option); + })).catch((e) => { + QrScannerError(e); + console.error(e); + }); + }).catch((e) => { + QrScannerError(e); + console.error(e); + }); + } else { + cameraScanner.start().catch((e) => { + if (e !== "Camera not found.") + QrScannerError(e); + }); + } +} +async function initQrCam(camList, startCamera, stopCamera, fileInput) { + console.log("initQrCam()"); + let allowCam = await getSetting("allowQrCamera"); + const disableCam = () => { + camList.style.display = "none"; + startCamera.style.display = "none"; + stopCamera.style.display = "none"; + }; + if (allowCam) { + import_qr_scanner_umd_min.default.hasCamera().then((hasCamera) => { + if (hasCamera === false) { + disableCam(); + } + }).catch((e) => { + QrScannerError(e); + console.error(e); + }); + } else + disableCam(); + camList.addEventListener("change", (event) => { + cameraScanner.setCamera(event.target.value); + }); + startCamera.addEventListener("click", () => { + try { + cameraScanner = new import_qr_scanner_umd_min.default(document.getElementById("qr-video"), (result) => handleQrCode(result)); + cameraScanner.start().catch((e) => { + QrScannerError(e); + console.error(e); + }); + } catch (e) { + QrScannerError(e); + console.error(e); + } + }); + stopCamera.addEventListener("click", () => { + if (cameraScanner) + cameraScanner.stop(); + }); + fileInput.addEventListener("change", (event) => { + const file = event.target.files[0]; + if (file) { + import_qr_scanner_umd_min.default.scanImage(file, { returnDetailedScanResult: true }).then((result) => handleQrCode(result)); + } + }); +} +var qrCallback; +function setQRCallback(fn) { + qrCallback = fn; +} +function handleQrCode(result) { + if (!result || !result.bytes) + return; + if (result.noQrCode) { + return; + } + cameraScanner.stop(); + const qrData = new Uint8Array(result.bytes); + console.log(dataToHex(qrData)); + const decryptedData = decryptAesCcm(qrData.slice(0, 112)); + const decryptedStoreDataBuf = decryptedData; + console.log("Decrypted QR Store Data:", dataToBase64(decryptedStoreDataBuf)); + if (qrData.length > 112) { + console.log("Has extra data"); + const iv = qrData.slice(112, 128); + const encryptedExtra = qrData.slice(128, -4); + decryptAesCtr(encryptedExtra, iv).then((decryptedExtraData) => { + console.log("Scanned Extra Data:", dataToHex(decryptedExtraData)); + if (decryptedExtraData.length === 240) { + qrCallback(decryptedStoreDataBuf, 1 /* ExtraDataTL */); + } + }).catch((error) => { + console.error("Something went wrong decrypting the QR extra data", error); + console.log("Attempting to load QR extra data anyways:"); + const extDataBuf = new Uint8Array(qrData.slice(112)); + console.log(dataToBase64(extDataBuf)); + if (extDataBuf.length === 10 || extDataBuf.length === 12) { + console.log("This is probably miic data"); + var newArray = new Uint8Array(decryptedStoreDataBuf.length + extDataBuf.length); + newArray.set(decryptedStoreDataBuf); + newArray.set(extDataBuf, decryptedStoreDataBuf.length); + qrCallback(newArray, 2 /* ExtraDataMiiC */); + } + }); + } else { + console.log("No extra data"); + qrCallback(decryptedStoreDataBuf, 0 /* GenericWiiU3ds */); + } +} + +// src/ui/pages/library/new/qrCode.ts +var __26 = _8(); +var newFromQRCode = async () => { + let qrReturnToMenu = true; + const m = Modal_default.modal(__26("Scan QR Code"), "", "body", { + text: "Cancel", + callback: () => { + m.qs("#stop-camera").elm.click(); + if (qrReturnToMenu) + miiCreateDialog(); + } + }); + const mb = m.qs(".modal-body"); + m.qs(".modal-body").qsa("*").forEach((item) => item.cleanup()); + m.qs(".modal-content")?.styleJs({ maxHeight: "100%", maxWidth: "600px" }); + mb.appendMany(new Html("div").classOn("col").appendMany(new Html("span").attr({ for: "cam-list" }).text(__26("Select camera:")), new Html("select").id("cam-list").appendMany(new Html("option").attr({ value: "environment", selected: "yes" }).text(__26("Back Camera (default)")), new Html("option").attr({ value: "user" }).text(__26("User/Front Facing Camera")), new Html("option").attr({ value: "device-camera", disabled: true }).text(__26("(Open the camera for more options)"))), new Html("div").class("flex-group").appendMany(new Html("button").id("start-camera").text(__26("Start camera")), new Html("button").id("stop-camera").text(__26("Stop camera"))), new Html("video").id("qr-video").styleJs({ maxWidth: "100%" }), new Html("span").id("file-upload").text(__26("Or upload an image:")), new Html("input").attr({ + type: "file", + id: "file-input", + accept: "image/*" + }))); + startScanner(mb.qs("#cam-list").elm); + initQrCam(mb.qs("#cam-list").elm, mb.qs("#start-camera").elm, mb.qs("#stop-camera").elm, mb.qs("#file-input").elm); + if (await getSetting("allowQrCamera") === false) { + mb.qsa('span[for="cam-list"], #cam-list, .flex-group, video').forEach((e) => e.style({ display: "none" })); + mb.qs("video").style({ position: "fixed" }); + mb.qs("span#file-upload").text(__26(`Camera is disabled in settings. + +Upload an image:`)); + } + async function qrImportConfirmation(mii, source) { + const shouldClose = await getSetting("autoCloseQrScan"); + if (shouldClose) { + qrReturnToMenu = false; + m.qs(".modal-header button")?.elm.click(); + } + importMiiConfirmation(mii, source, __26("Mii QR Scanned")); + } + setQRCallback((data2, dataType) => { + try { + var mii; + switch (dataType) { + case 0 /* GenericWiiU3ds */: + mii = new Mii(data2); + qrImportConfirmation(mii, __26("3DS/Wii U QR Code")); + break; + case 1 /* ExtraDataTL */: + Modal_default.alert(__26("Notice"), new Html("span").html(__26(`Tomodachi Life QR codes aren't supported yet. Use %1 to scan it.`, __26("Mii Renderer (REAL)")))); + break; + case 2 /* ExtraDataMiiC */: + mii = new Mii(data2); + qrImportConfirmation(mii, __26("Mii Creator QR Code")); + break; + } + } catch (e) { + QrScannerError(__26(`An error occurred when reading the data. +Please check the console for more information.`)); + console.error(e); + } + }); +}; + +// src/ui/pages/library/new/nnidPnid.ts +var import_localforage8 = __toESM(require_localforage(), 1); + +// src/ui/components/Loader.ts +var loader; +var Loader_default = { + show() { + if (loader === undefined) { + loader = new Html("div").class("loader", "active").html(EditorIcons_default.loading).appendTo("body"); + } else { + loader.classOn("active"); + } + }, + hide() { + if (loader) + loader.classOff("active"); + } +}; + +// src/ui/pages/library/new/nnidPnid.ts +var __27 = _8(); +var newFromNNID = async () => { + const input = await Modal_default.input(__27("Nintendo Network ID"), __27("Enter NNID of user.."), __27("Username"), "body", false); + if (input === false) { + return miiCreateDialog(); + } + Loader_default.show(); + let nnid = await fetch(Config.apis.nnidFetchURL(encodeURIComponent(input))); + const result = await nnid.json(); + Loader_default.hide(); + if (result.error !== undefined) { + await Modal_default.alert(__27("Error"), __27("Couldn't get Mii: %1", result.error)); + return; + } + _shutdown()(); + new MiiEditor2(0, async (m, shouldSave) => { + if (shouldSave === true) + await import_localforage8.default.setItem(await newMiiId(), m); + await pushToServer(); + Library(); + }, result.data); +}; +var newFromPNID = async () => { + const input = await Modal_default.input(__27("Pretendo Network ID"), __27("Enter PNID of user.."), __27("Username"), "body", false); + if (input === false) { + return miiCreateDialog(); + } + Loader_default.show(); + let pnid = await fetch(Config.apis.pnidFetchURL(encodeURIComponent(input))); + Loader_default.hide(); + if (!pnid.ok) { + await Modal_default.alert(__27("Error"), __27("Couldn't get Mii: %1", await pnid.text())); + return; + } + _shutdown()(); + new MiiEditor2(0, async (m, shouldSave) => { + if (shouldSave === true) + await import_localforage8.default.setItem(await newMiiId(), m); + await pushToServer(); + Library(); + }, (await pnid.json()).data); +}; + +// src/ui/pages/library/new/randomNnid.ts +var import_localforage9 = __toESM(require_localforage(), 1); +var newFromRandonNNID = async () => { + Loader_default.show(); + let random2 = await fetch(Config.apis.nnidRandomURL).then((j2) => j2.json()); + Loader_default.hide(); + _shutdown()(); + new MiiEditor2(0, async (m, shouldSave) => { + if (shouldSave === true) + await import_localforage9.default.setItem(await newMiiId(), m); + await pushToServer(); + Library(); + }, random2.data); +}; + +// src/ui/pages/library/new/_dialog.ts +var __28 = _8(); +var miiCreateDialog = () => { + const m = Modal_default.modal(__28("Create Mii"), __28("How would you like to create the Mii?"), "body", { + text: __28("From Scratch"), + type: "primary", + callback: () => { + newFromScratch(); + } + }, { + text: __28("QR Code"), + callback: () => { + newFromQRCode(); + } + }, { + text: __28("Mii data file"), + callback: () => { + let id; + let modal = Modal_default.modal(__28("Mii data files import"), "", "body", { + text: "Cancel", + callback: () => { + miiCreateDialog(); + } + }, { + text: "Confirm", + callback() { + Library(id); + } + }); + modal.qsa(".modal-body .flex-group,.modal-body span").forEach((q2) => q2.style({ display: "none" })); + modal.qs(".modal-body").appendMany(new Html("span").text(__28("Import Mii data file(s) here. Supported formats: .ffsd/.cfsd, .miic, .charinfo, .rsd")), new Html("input").attr({ + type: "file", + accept: ".ffsd,.cfsd,.charinfo,.rsd,.rcd," + ".miic,.mii,.miigx,.cfcd,.ufsd,.mnms,.nfcd,", + multiple: "on" + }).style({ margin: "auto" }).on("change", async (e) => { + const target = e.target; + console.log("Files", target.files); + const f = new FileReader; + let processed = 0; + function loadFile(file) { + return new Promise((resolve) => { + f.readAsArrayBuffer(file); + f.onload = async () => { + const miiData = new Uint8Array(f.result); + const mii = new Mii(miiData); + const miiDataToSave = dataToBase64(mii.export("miic")); + id = await newMiiId(); + await import_localforage10.default.setItem(id, miiDataToSave); + await pushToServer(); + processed++; + resolve(); + }; + }); + } + for (const file of Array.from(target.files)) { + try { + await loadFile(file).catch((e2) => { + throw e2; + }); + } catch (e2) { + Modal_default.alert(__28("Error"), __28("Invalid Mii data: %1", e2)); + console.error(e2); + target.value = ""; + continue; + } + } + if (processed > 0) { + _shutdown()(); + modal.qs(".modal-body button").elm.click(); + } + })); + } + }, { + text: __28("Raw Mii data"), + callback: async () => { + const result = await Modal_default.input(__28("Raw Mii data import"), __28("Paste raw Mii data here."), __28("Hex/Base64 data"), "body"); + if (result === false) + return; + const miiData = parseHexOrB64ToUint8Array(result); + const mii = new Mii(miiData); + const miiDataToSave = dataToBase64(mii.export("miic")); + let id = await newMiiId(); + await import_localforage10.default.setItem(id, miiDataToSave); + await pushToServer(); + _shutdown()(); + Library(id); + } + }, { + text: __28("Enter NNID/PNID"), + callback: () => { + Modal_default.modal(__28("Enter NNID/PNID"), __28("Select a service to look up"), "body", { + text: "Cancel" + }, { + text: __28("Enter Nintendo Network ID"), + callback(e) { + newFromNNID(); + } + }, { + text: __28("Enter Pretendo Network ID"), + callback(e) { + newFromPNID(); + } + }); + } + }, { + text: __28("Choose a look-alike"), + callback: () => { + newFromLookalike(); + } + }, { + text: __28("Random NNID"), + callback: () => { + newFromRandonNNID(); + } + }, { + text: "Cancel" + }); + m.qs(".modal-body").styleJs({ maxWidth: "600px" }); +}; + +// src/ui/pages/library/new/lookalike.ts +var __29 = _8(); +var newFromLookalike = async () => { + var lookalikeModal = Modal_default.modal(__29("Choose a look-alike"), "", "body", { + text: "Cancel", + callback(e) { + miiCreateDialog(); + } + }, { + text: __29("Confirm") + }); + lookalikeModal.classOn("random-mii-grid"); + const container = lookalikeModal.qs(".modal-body"); + container.qsa("span,.flex-group *").forEach((e) => e.style({ display: "none" })); + let randomMiiContainer = new Html("div").class("random-mii-container").appendTo(container); + const group = container.qs(".flex-group"); + container.prepend(new Html("span").style({ + width: "100%", + padding: "14px 18px", + background: "var(--hover)", + color: "var(--text)", + border: "1px solid var(--stroke)", + "border-radius": "6px", + "flex-shrink": "0" + }).text(__29("All of the options here are what Nintendo originally programmed in. Please let me know if you want more options added."))); + new Html("button").class("primary").text("Reroll").on("click", () => reroll()).appendTo(group); + let options = {}; + function makeSelect(property2, values2) { + console.log(values2); + return new Html("select").appendMany(...values2).on("input", (e) => { + options[property2] = parseInt(e.target.value); + if (options[property2] === -1) + delete options[property2]; + console.log(options); + }); + } + group.prependMany(makeSelect("race", [ + new Option(__29("Skin tone"), "-1", true, true), + new Option(__29("(Random)"), "-1"), + new Option(__29("Black"), "0"), + new Option(__29("White"), "1"), + new Option(__29("Asian"), "2") + ]), makeSelect("gender", [ + new Option(__29("Gender"), "-1", true, true), + new Option(__29("(Random)"), "-1"), + new Option(__29("Male"), "0"), + new Option(__29("Female"), "1") + ]), makeSelect("hairColor", [ + new Option(__29("Hair color"), "-1", true, true), + new Option(__29("(Random)"), "-1"), + new Option(__29("Black"), "0"), + new Option(__29("Brown"), "1"), + new Option(__29("Auburn"), "2"), + new Option(__29("Hazel"), "3"), + new Option(__29("Gray"), "4"), + new Option(__29("Olive"), "5"), + new Option(__29("Medium-blonde"), "6"), + new Option(__29("Light-blonde"), "7") + ]), makeSelect("favoriteColor", [ + new Option(__29("Favorite color"), "-1", true, true), + new Option(__29("(Random)"), "-1"), + new Option(__29("Red"), "0"), + new Option(__29("Orange"), "1"), + new Option(__29("Yellow"), "2"), + new Option(__29("Lime"), "3"), + new Option(__29("Green"), "4"), + new Option(__29("Blue"), "5"), + new Option(__29("Cyan"), "6"), + new Option(__29("Pink"), "7"), + new Option(__29("Purple"), "8"), + new Option(__29("Brown"), "9"), + new Option(__29("White"), "10"), + new Option(__29("Black"), "11") + ]), makeSelect("eyeColor", [ + new Option(__29("Eye color"), "-1", true, true), + new Option(__29("(Random)"), "-1"), + new Option(__29("Black"), "0"), + new Option(__29("Gray"), "1"), + new Option(__29("Brown"), "2"), + new Option(__29("Hazel"), "3"), + new Option(__29("Blue"), "4"), + new Option(__29("Green"), "5") + ]), makeSelect("age", [ + new Option(__29("Age"), "-1", true, true), + new Option(__29("(Random)"), "-1"), + new Option(__29("Child"), "0"), + new Option(__29("Adult"), "1"), + new Option(__29("Elder"), "2") + ])); + function reroll() { + randomMiiContainer.clear(); + for (let i = 0;i < 24; i++) { + const randomMii = new Mii("AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn"); + FFLiDatabaseRandom_Get(randomMii, options); + let button = new Html("button").append(new Html("img").attr({ src: "" })).appendTo(randomMiiContainer); + getMiiIcon(randomMii, "lookalike").then((icon) => { + playLoadSound(); + button.qs("img")?.attr({ src: icon }); + }); + button.on("click", async () => { + confirmOrReviseMii(randomMii, options, lookalikeModal); + }); + } + } + reroll(); +}; +function confirmOrReviseMii(mii, options, modalRef) { + const miiIcon = new Html("img").style({ + opacity: "0", + width: "210px", + height: "210px", + transition: "opacity 0.35s ease" + }); + getMiiIcon(mii, "lookalike_preview", "all_body_sugar", 210).then((icon) => { + miiIcon.attr({ src: icon }).style({ opacity: "1" }); + }); + Modal_default.modal(__29("Is this OK?"), new Html("div").style({ margin: "0 auto" }).append(miiIcon), "body", { + text: "Cancel" + }, { + text: __29("Close"), + type: "danger" + }, { + text: __29("Revise"), + callback(e) { + let currentMii = mii; + const m = Modal_default.modal("Revise", new Html("div").appendMany(new Html("span").style({ margin: "0 auto" }).text(__29("Click any to reroll")), new Html("div").class("menu").style({ + display: "flex", + "flex-direction": "column", + gap: "0.5rem" + })), "body", { text: "Cancel" }, { + text: __29("Done"), + callback(e2) { + confirmOrReviseMii(currentMii, options, modalRef); + } + }); + m.qs(".modal-content").style({ + height: "max-content", + "max-height": "100vh" + }); + const menuDiv = m.qs(".menu"); + function regenerate() { + menuDiv.clear(); + let rows = []; + for (let i = 0;i < 9; i++) { + const row = Math.floor(i / 3); + const col = i % 3; + if (rows[row] === undefined) { + rows[row] = []; + } + if (i === 4) { + rows[row][col] = currentMii; + } else { + var mii2 = new Mii(currentMii.export()); + console.log("options:", options); + RandomizeMii(mii2, options); + rows[row][col] = mii2; + } + } + for (const row of rows) { + const rowElm = new Html("div").style({ display: "flex", gap: "0.5rem" }).appendTo(menuDiv); + for (const child of row) { + const button = new Html("button").style({ + padding: "0" + }); + const img = new Html("img").style({ + width: "108px", + height: "108px", + opacity: "0", + transition: "opacity 0.2s ease" + }).appendTo(button); + rowElm.append(button); + button.on("click", (e2) => { + e2.preventDefault(); + currentMii = child; + requestAnimationFrame(() => { + regenerate(); + }); + }); + getMiiIcon(child, "lookalike_regenerate", "fflmakeicon", 108).then((icon) => { + playLoadSound(); + img.attr({ src: icon }).style({ opacity: "1" }); + }); + } + } + } + regenerate(); + } + }, { + text: __29("Done"), + type: "primary", + callback(e) { + const randomMiiB64 = dataToBase64(mii.export("miic")); + if (modalRef) + modalRef.qs(".flex-group button")?.elm.click(); + _shutdown()(); + new MiiEditor2(0, async (m, shouldSave) => { + if (shouldSave === true) + await import_localforage11.default.setItem(await newMiiId(), m); + await pushToServer(); + Library(); + }, randomMiiB64); + } + }); +} + +// src/ui/pages/library/select.ts +var __30 = _8(); +var miiSelect = (mii, miiData, isSpecial) => { + return async () => { + const modal = Modal_default.modal(miiData.nickname, __30("What would you like to do?"), "body", { + text: __30("Edit"), + async callback() { + if (isSpecial) { + Modal_default.modal(__30("Notice"), __30("You can't edit Mii Creator-specific Special Miis."), "body", { text: "Cancel" }, { text: __30("OK") }); + } else { + await _shutdown()(); + new MiiEditor2(0, async (m, shouldSave) => { + if (shouldSave === true) + await import_localforage12.default.setItem(mii.id, m); + await pushToServer(); + Library(); + }, mii.mii); + } + } + }, { + text: __30("Revise"), + async callback() { + if (isSpecial) { + return Modal_default.modal(__30("Notice"), __30("You can't edit Mii Creator-specific Special Miis."), "body", { text: "Cancel" }, { text: __30("OK") }); + } + confirmOrReviseMii(miiData, { + gender: miiData.gender, + isOriginalMii: true + }); + } + }, { + text: __30("Delete"), + async callback() { + try { + let destroy = function() { + disableModal(); + scaredMiiImage.classOn("rotateAndCry"); + }, closingCallback2 = function() { + tmpDeleteModal.qs(".modal-body").qsa("*").forEach((a2) => a2.attr({ disabled: true, tabindex: "-1" })); + }, disableModal = function() { + closingCallback2(); + }, closeModal2 = function() { + tmpDeleteModal.class("closing"); + closingCallback2(); + setTimeout(() => { + tmpDeleteModal.cleanup(); + }, 350); + }; + let scaredIcon = await getMiiIcon(miiData, "deletion", "face", 256, 10, false); + let fearfulIcon = await getMiiIcon(miiData, "deletion", "face", 256, 30, false); + let reliefIcon = await getMiiIcon(miiData, "deletion", "face", 256, 1, false); + let tmpDeleteModal = Modal_default.modal(__30("Warning"), __30("Are you sure you want to delete %1?", miiData.nickname), "body"); + tmpDeleteModal.qs(".modal-body").append(new Html("div").class("flex-group").appendMany(new Html("button").class("danger").text(__30("Yes")).on("click", () => { + destroy(); + scaredMiiImage.attr({ + src: fearfulIcon + }); + setTimeout(async () => { + closeModal2(); + await import_localforage12.default.removeItem(mii.id); + await pushToServer(); + await _shutdown()(); + Library(); + }, 1000); + }), new Html("button").text(__30("No")).on("click", () => { + closeModal2(); + }))); + tmpDeleteModal.qs(".modal-body").classOn("flex-group"); + const scaredMiiImage = new Html("img").attr({ src: scaredIcon }).style({ width: "180px", margin: "-18px auto 0 auto" }); + tmpDeleteModal.qs(".modal-body").prepend(scaredMiiImage); + tmpDeleteModal.qsa("button").forEach((item) => { + const yes = item?.elm.classList.contains("danger"); + item.on("pointerenter", () => { + if (yes) { + scaredMiiImage.attr({ + src: fearfulIcon + }); + } else { + scaredMiiImage.attr({ + src: reliefIcon + }); + } + }); + item.on("pointerleave", () => { + scaredMiiImage.attr({ + src: scaredIcon + }); + }); + }); + } catch (e) { + console.log("FALL BACK"); + Modal_default.modal(__30("Warning"), __30("Are you sure you want to delete %1?", miiData.nickname), "body", { + text: __30("Yes"), + type: "danger", + async callback(e2) { + await import_localforage12.default.removeItem(mii.id); + await pushToServer(); + await _shutdown()(); + Library(); + } + }, { text: __30("No") }); + } + } + }, { + text: __30("Export/Download Data"), + async callback() { + miiExportData(mii, miiData); + } + }, { + text: __30("Render"), + async callback() { + miiRender(mii, miiData); + } + }, { + text: "Cancel" + }); + const miiBodyIcon = new Html("img").style({ + "object-fit": "cover", + width: "240px", + height: "240px", + margin: "-18px auto 0 auto", + transition: "opacity 0.3s ease", + opacity: "0" + }); + getMiiIcon(miiData, "preview", "all_body_sugar", 240).then((result) => { + miiBodyIcon.attr({ src: result }).style({ opacity: "1" }); + }); + modal.qs(".modal-body")?.prepend(miiBodyIcon); + }; +}; + +// src/ui/pages/Library.ts +var __31 = _8(); +var savedMiiCount = async () => (await import_localforage13.default.keys()).filter((k4) => k4.startsWith("mii-")).length; +var newMiiId = async () => `mii-${Date.now()}-${await savedMiiCount()}`; +var playLoadSound = () => { + setTimeout(() => { + if (RandomInt(2) !== 0) + return; + playSound(`load${RandomInt(4) + 1}`); + }, RandomInt(200)); +}; +var tmpRenderer; +var canvas = document.createElement("canvas"); +document.body.appendChild(canvas); +tmpRenderer = new WebGLRenderer({ alpha: true, preserveDrawingBuffer: true }); +var getMiiIcon = async (mii, source = "unknown", view = "variableiconbody", size2 = 180, expression = 0, useBlob = true) => { + let m = "", drawBody = true, type = ViewType2.Face; + switch (view) { + case "creditIcon": + type = ViewType2.CreditIcon; + break; + case "face": + case "variableiconbody": + type = ViewType2.Face; + break; + case "fflmakeicon": + type = ViewType2.MakeIcon; + drawBody = false; + break; + case "all_body": + type = ViewType2.AllBody; + break; + case "all_body_sugar": + type = ViewType2.AllBodySugar; + break; + } + console.debug("icon view:", Object.keys(ViewType2)[type]); + if (Config.renderer.useRendererServer === false) { + let dataURL = "undefined", model, data2, miiData; + if (typeof mii === "string") { + data2 = parseHexOrB64ToUint8Array(mii); + miiData = new Mii(data2); + } else { + data2 = mii.export("studioData"); + miiData = mii; + } + if (getFFLWorkerExists()) { + console.debug("Asking worker thread for an icon plz!"); + const icon = await getFFLWorkerMakeIcon({ + data: data2, + type, + expression, + texResolution: 256, + additionalInfo: { + hatCommonColor: miiData.hatCommonColor, + hatFavoriteColor: miiData.hatFavoriteColor, + hatType: miiData.hatType, + pantsColor: miiData.pantsColor, + shirtColor: miiData.shirtColor, + favorite: miiData.favorite, + special: miiData.special, + temporary: miiData.temporary, + eyeSclera: miiData.eyeSclera, + wigType: miiData.wigType, + clothesType: miiData.clothesType, + shoesColor: miiData.shoesColor + }, + drawBody, + size: size2 + }, useBlob); + return icon; + } + try { + alert("Icon rendering is broken in your browser since we aren't using web workers, upgrade your browser and try again"); + } catch (e) { + let name2 = ""; + if (typeof mii !== "string") { + name2 = mii.nickname; + } + console.error(`Library: Could not make icon for ${name2}: ${e}`); + } finally { + model.dispose(); + return dataURL; + } + } + if (typeof mii === "string") + return; + let url = Config.renderer.renderHeadshotURLNoParams; + let params = new URLSearchParams; + params.set("data", mii.exportHex("studioData")); + adjustShaderQuery(params, currentShader); + params.set("bodyType", currentBodyModel); + params.set("type", view); + params.set("width", size2.toString()); + params.set("verifyCharInfo", "0"); + params.set("miic", encodeURIComponent(mii.exportHex("miic"))); + params.set("version", Config.version.string); + params.set("source", source ? "library" : "lookalike"); + params.set("pantsColor", mii.special === 1 ? "gold" : mii.favorite === 1 ? "red" : "gray"); + if (mii.hatType !== -1) { + params.set(Config.renderer.hatTypeParam, String(mii.hatType + 1 + Config.renderer.hatTypeAdd)); + } + if (mii.hatFavoriteColor !== -1) { + params.set(Config.renderer.hatColorParam, String(mii.hatFavoriteColor + Config.renderer.hatColorAdd)); + } + return `${url}?${params.toString()}`; +}; +var currentShader = "wiiu" /* WiiU */; +document.addEventListener("library-shader-update", async () => { + currentShader = await getSetting("shaderType"); +}); +var currentBodyModel = "wiiu" /* WiiU */; +document.addEventListener("library-body-update", async () => { + currentBodyModel = await getSetting("bodyModel"); +}); +var shutdown = () => { + console.log("Shutdown was called but was not set yet!"); +}; +var _shutdown = () => shutdown; +async function pushToServer() { + const miis = await Promise.all((await import_localforage13.default.keys()).filter((k4) => k4.startsWith("mii-")).sort((a2, b3) => Number(a2.split("-")[1]) - Number(b3.split("-")[1])).map(async (k4) => ({ + id: k4, + mii: await import_localforage13.default.getItem(k4) + }))); + await fetch("/api/sync_library", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ miis }) + }).then(async (e) => { + if (!e.ok) { + const text2 = await e.text(); + alert("REQ FAILED - Unable to sync library data: " + text2); + console.error("Failed to sync library data: " + e); + } + }).catch((e) => { + alert("ERROR - Unable to sync library data: " + e); + console.error("Failed to sync library data: " + e); + }); +} +function choosePersonalMii(miiList) { + return new Promise((resolve) => { + const personalMiiChooseModal = Modal_default.modal(__31("Notice"), "", "body", { + text: __31("Confirm") + }); + personalMiiChooseModal.classOn("random-mii-grid"); + const container = personalMiiChooseModal.qs(".modal-body"); + container.qsa("span,.flex-group *").forEach((e) => e.style({ display: "none" })); + container.prepend(new Html("span").style({ + width: "100%", + padding: "14px 18px", + background: "var(--hover)", + color: "var(--text)", + border: "1px solid var(--stroke)", + "border-radius": "6px", + "flex-shrink": "0" + }).text(__31("Choose a Mii to be your Personal Mii, which can be used across apps. This can always be changed later in Settings."))); + let randomMiiContainer = new Html("div").class("random-mii-container").appendTo(container); + let count = 0; + for (const mii of miiList) { + let loadIcon = function() { + getMiiIcon(m, "lookalike").then((icon) => { + playLoadSound(); + button.qs("img")?.attr({ src: icon }); + }); + }; + let button = new Html("button").append(new Html("img").attr({ src: "" })).appendTo(randomMiiContainer); + const m = new Mii(mii.mii); + button.on("click", async () => { + confirmPersonalMii(m, mii, personalMiiChooseModal).then((result) => { + if (result) { + resolve(mii.id); + } + }); + }); + if (window.browserMitigations !== undefined) { + setTimeout(() => { + loadIcon(); + }, count * 100); + } else { + loadIcon(); + } + count++; + } + }); +} +function confirmPersonalMii(mii, miiLocalforage, modalRef) { + return new Promise((resolve) => { + const miiIcon = new Html("img").style({ + opacity: "0", + width: "210px", + height: "210px", + transition: "opacity 0.35s ease" + }); + getMiiIcon(mii, "lookalike_preview", "all_body_sugar", 210).then((icon) => { + miiIcon.attr({ src: icon }).style({ opacity: "1" }); + }); + Modal_default.modal(__31("Is this OK?"), new Html("div").style({ + margin: "0 auto", + display: "flex", + "flex-direction": "column", + "align-items": "center" + }).classOn("col").append(miiIcon).prepend(new Html("span").text("This will be set as your Personal Mii.")), "body", { + text: "Cancel", + callback() { + resolve(false); + } + }, { + text: __31("Close"), + callback() { + resolve(false); + } + }, { + text: __31("Confirm"), + type: "primary", + async callback(e) { + if (modalRef) + modalRef.qs(".flex-group button")?.elm.click(); + await fetch("/api/personal_mii", { + body: JSON.stringify({ + nickname: mii.nickname, + creator: mii.creator, + ffsd: mii.exportBase64("ffsd"), + data: mii.exportBase64("miic"), + studio: mii.exportBase64("studioData"), + store_id: miiLocalforage.id + }), + method: "POST", + headers: { "content-type": "application/json" } + }).catch(undefined); + resolve(true); + } + }); + }); +} +async function Library(highlightMiiId) { + currentShader = await getSetting("shaderType"); + currentBodyModel = await getSetting("bodyModel"); + function shutdownReal() { + return new Promise((resolve) => { + container.class("fadeOut"); + setTimeout(() => { + container.cleanup(); + resolve(); + }, 500); + }); + } + shutdown = shutdownReal; + const container = new Html("div").class("mii-library").appendTo("body"); + const sidebar = new Html("div").class("library-sidebar").appendTo(container); + sidebar.append(new Html("h1").text(__31("Mii Creator"))); + const libraryList = new Html("div").class("library-list").appendTo(container); + let miisJson = await fetch("/api/sync_library", { + headers: { accept: "application/json" } + }).then((j2) => j2.json()); + let miis = []; + if (miisJson === null) { + miisJson = []; + miis = await Promise.all((await import_localforage13.default.keys()).filter((k4) => k4.startsWith("mii-")).sort((a2, b3) => Number(a2.split("-")[1]) - Number(b3.split("-")[1])).map(async (k4) => ({ + id: k4, + mii: await import_localforage13.default.getItem(k4) + }))); + } else { + miis = miisJson; + } + console.log(miisJson); + if (miis.length === 0) { + libraryList.append(new Html("div").style({ position: "absolute", top: "2rem", left: "2rem" }).text(__31("You don't have any Miis. Create one to get started!"))); + } else { + const resp = await fetch("/api/personal_mii"); + if (!resp.ok) { + await choosePersonalMii(miis); + } + } + let miiErrorCount = 0, miiCount = 0; + for (const mii of miis) { + import_localforage13.default.setItem(mii.id, mii.mii); + let miiContainer = new Html("div").class("library-list-mii"); + AddButtonSounds(miiContainer); + let miiData = null; + try { + let loadIcon = function() { + getMiiIcon(miiData, "library", "variableiconbody", 180, 0 /* Normal */).then((r) => { + miiImage.attr({ src: r }).style({ opacity: "1" }); + }).catch((e) => { + Notify_default.show(__31("Notice"), __31("Failed to load %1's icon", miiData.nickname)); + }); + }; + miiData = new Mii(mii.mii); + miiData.validate(); + console.debug("MII DATA GOT:", miiData); + let specialMii = false; + if (miiData.createId[4] === 42 && miiData.createId[5] === 241 && miiData.createId[6] === 22 && miiData.createId[7] === 24 && miiData.createId[8] === 250 && miiData.createId[9] === 191) { + miiContainer.classOn("highlight").style({ "--selection-color": "#ffbf00" }); + specialMii = true; + } + miiContainer.style({ + "--color": MiiFavoriteColorIconTable[miiData.favoriteColor % Object.keys(MiiFavoriteColorIconTable).length].top + }); + let extraData = ""; + if (miiData.hatType !== 0 - 1) { + extraData += `&${Config.renderer.hatTypeParam}=${encodeURIComponent(miiData.hatType + 1 + Config.renderer.hatTypeAdd)}&${Config.renderer.hatColorParam}=${encodeURIComponent(miiData.hatFavoriteColor + Config.renderer.hatColorAdd)}`; + } + let miiImage = new Html("img").attr({}).style({ opacity: "0", transition: "opacity 0.3s ease" }); + if (window.browserMitigations !== undefined) { + setTimeout(() => { + loadIcon(); + }, miiCount * 100); + } else { + loadIcon(); + } + if (miiData.special === 1 || miiData.favorite === 1 || specialMii) { + const star = new Html("i").style({ position: "absolute", top: "-22px", right: "-18px" }).appendTo(miiContainer); + if (miiData.favorite === 1) { + star.html(EditorIcons_default.favorite).style({ color: cPantsColorRedHex }); + } + if (miiData.special === 1 || specialMii) { + star.html(EditorIcons_default.special).style({ color: cPantsColorGoldHex }); + } + } + let miiName = new Html("span").text(miiData.nickname); + let miiEditCallback = miiSelect(mii, miiData, specialMii); + miiContainer.on("click", async () => { + miiEditCallback(); + }); + let hasMiiErrored = false; + miiImage.on("error", () => { + if (hasMiiErrored === true) + return; + miiImage.attr({ + src: "data:image/svg+xml," + encodeURIComponent(EditorIcons_default.error) + }); + hasMiiErrored = true; + }); + miiImage.on("load", () => { + playLoadSound(); + }); + miiContainer.appendMany(miiImage, miiName).appendTo(libraryList); + requestAnimationFrame(() => { + if (highlightMiiId !== undefined) { + if (highlightMiiId === mii.id) { + miiContainer.classOn("highlight"); + setTimeout(() => { + if (specialMii === false) + miiContainer.classOff("highlight"); + }, 2000); + const mc = miiContainer.elm; + mc.closest(".library-list").scroll({ + top: mc.getBoundingClientRect().top + mc.getBoundingClientRect().height, + behavior: "smooth" + }); + } + } + }); + } catch (e) { + console.log("Oops", e); + miiErrorCount++; + let miiImage = new Html("img").attr({ + src: "data:image/svg+xml," + encodeURIComponent(EditorIcons_default.error) + }); + let miiName = new Html("span").text(__31("?")); + if (miiData !== null) { + if (miiData.nickname.trim() !== "") + miiName.text(miiData.nickname); + } + miiContainer.appendMany(miiImage, miiName).appendTo(libraryList); + miiContainer.on("click", async () => { + Modal_default.modal(__31("Warning"), __31("This Mii might be corrupted. Choose an option below."), "body", { + text: "Cancel" + }, { + text: __31("Download a copy"), + callback(e2) { + console.log(mii); + saveArrayBuffer(parseHexOrB64ToUint8Array(mii.mii).buffer, mii.id + ".miic"); + } + }, { + text: __31("Download a copy (Base64 encoded)"), + callback(e2) { + console.log(mii); + saveArrayBuffer(dataToBase64(parseHexOrB64ToUint8Array(mii.mii)), mii.id + ".miic.txt"); + } + }, { + text: __31("Delete"), + callback(e2) { + Modal_default.modal(__31("Warning"), __31("Are you sure you want to delete this Mii?"), "body", { + async callback(e3) { + await import_localforage13.default.removeItem(mii.id); + await pushToServer(); + await shutdown(); + Library(); + }, + text: __31("Yes"), + type: "danger" + }, { + text: __31("No") + }); + } + }); + }); + } + miiCount++; + } + if (miiErrorCount > 0) { + Modal_default.modal(__31("Error"), __31(`It appears that %1 of your Miis have failed to load. Their data may be corrupted. + +If you'd like to try and recover the Mii data, you can select the Miis with errors and choose to either save a copy or delete them.`, miiErrorCount), "body", ...buttonsOkCancel); + } + window.LazyLoad.update(); + sidebar.appendMany(new Html("div").class("sidebar-buttons").appendMany(AddButtonSounds(new Html("button").text(__31("Create Mii")).on("click", async () => { + miiCreateDialog(); + })), AddButtonSounds(new Html("button").text(__31("More Options")).on("click", async () => { + Modal_default.modal(__31("More Options"), __31("Select an option."), "body", { + text: "Cancel" + }, { + text: __31("Settings"), + callback(e) { + Settings(); + } + }, { + text: __31("Credits"), + callback(e) { + var m = Modal_default.modal(__31("Credits"), "", "body", { text: "Cancel" }, { text: "OK" }); + m.qs(".modal-body span").cleanup(); + m.qs(".modal-content").style({ + "max-width": "100%", + "max-height": "100%" + }); + const mb = m.qs(".modal-body"); + m.qs(".modal-content").style({ position: "relative" }); + const container2 = new Html("div").class("col").prependTo(mb); + new Html("span").text(__31("Check out the people behind Mii Creator!")).style({ + "font-size": "20px", + "flex-shrink": "0", + "margin-bottom": "-16px" + }).prependTo(mb); + new Html("a").text(__31("secret?")).style({ + "font-size": "10px", + opacity: "0.3", + cursor: "pointer", + position: "absolute", + bottom: "10px", + right: "10px" + }).on("click", (e2) => { + m.qs("button")?.elm.click(); + const mii = new Mii(parseHexOrB64ToUint8Array("BANtKwIiiUS3tZw1sDcq8RYY+sFjAGgAYQByAGwAaQBuAGUAAAAAAGMAaABhAHIAbABpAG4AZQAAAAAACAALAQAAJgMDAQYEAAIKCwQEGwIMAAkBAP8BAAABCAQACgYAZf///0wABAACFAMTARMNBAAKBAEJEP8A/wEA")); + importMiiConfirmation(mii, __31("Mii Creator (Special Mii)")); + }).appendTo(mb); + createMiiCard(container2, __31("Austin☆²¹ / Kat21"), "datkat21", "https://github.com/datkat21", __31("Lead developer of Mii Creator"), "000040030c040320020c0407050213030a0000000008000804000a07003e5303010a09031303130d04000a030d0a"); + createMiiCard(container2, __31("Arian"), "ariankordi", "https://github.com/ariankordi", __31('Creator of Mii Renderer (REAL), made FFL.js and ported Miitomo shader, and was a big help with debugging many issues'), "080037030d020531020c030105040a0209000001000a011004010b0100662f04000214031603140d04000a020109"); + createMiiCard(container2, __31("obj"), "objecty", "https://x.com/objecty_twitt", __31("Composed the music for Mii Creator"), "00003a030a030407020b030805040902080400010000000804000a0800403e02010311031304130d04000a040109"); + createMiiCard(container2, __31("Timothy"), "Timimimi", "https://github.com/Timiimiimii", __31("Modeled many of the custom hats and helped with debugging"), "00003b0208040206040d0308050206040a0100020003005f03090b0800426d01010e16031403130f04000804070b "); + createMiiCard(container2, __31("David J."), "dwyazzo90", "https://x.com/dwyazzo90", __31("Helped with design, localization, and created the Wii U theme"), "0800450308040402020c0308060406020a0001000006000804000a0800326702010314031304190d04000a040109"); + createMiiCard(container2, __31("raymond"), "raymonable", "https://github.com/raymonable", __31("Helped with initial development for client-side rendering"), "0800400308040402020c0301050400020a0000000000000804000a01004b4004000214031303190d04000a040109"); + createMiiCard(container2, __31("MilkGalaxy"), "milkgalaxy", "https://www.youtube.com/channel/UCUHVT7e1MT0Mpiv0e8WB2fQ", __31("Helped create custom clothing"), "080057033c05030c030d0101060415030c0000010307000804000a1701656204000214011303230d04000a010a0a"); + } + }, { + text: __31("Contact"), + callback(e) { + var m = Modal_default.modal("Contact", "", "body", { text: "Cancel" }, { text: "OK" }); + m.qs(".modal-body span").cleanup(); + m.qs(".modal-content").style({ + "max-width": "100%", + "max-height": "100%" + }); + const mb = m.qs(".modal-body"); + m.qs(".modal-content").style({ position: "relative" }); + const container2 = new Html("div").class("col").style({ gap: "0" }).prependTo(mb); + new Html("span").text(__31("Here's where you can contact the author, Kat21")).style({ + "font-size": "20px", + "flex-shrink": "0", + "margin-bottom": "-16px" + }).prependTo(mb); + new Html("a").text(__31("secret?")).style({ + "font-size": "10px", + opacity: "0.3", + cursor: "pointer", + position: "absolute", + bottom: "10px", + left: "10px" + }).on("click", (e2) => { + m.qs("button")?.elm.click(); + const mii = new Mii(parseHexOrB64ToUint8Array("BAWl18qbeYiSbgD/dXQq8RYY+sFrAGEAdAAyADEAAAAAAAAAAAAAAGIAbwBvAGUAeQAAAAAAAAAAAAAACAAAAAAAbwMECAYEDQMLMwMHEgIMAAAJAGMACgAANgMACmMASf83ARQABAACFAYTAxMKBAAKAAANN/8AYwEA")); + importMiiConfirmation(mii, __31("Mii Creator (Special Mii)")); + }).appendTo(mb); + createIconCard(container2, __31("E-mail (Preferred)"), "mailto:datkat21.yt@gmail.com", "datkat21.yt@gmail.com", EditorIcons_default.contact_email); + createIconCard(container2, __31("Discord"), "", "kat21", EditorIcons_default.contact_discord); + } + }, { + text: __31("Manual"), + callback(e) { + Modal_default.alert(__31("Notice"), __31("The manual isn't finished yet. Please come back later.")); + } + }); + }))), new Html("div").class("sidebar-credits").appendMany(new Html("strong").text(__31("This site is not affiliated with Nintendo.")), new Html("small").html(`Mii Creator ${Config.version.string} by kat21 (${Config.version.name})`).style({ cursor: "pointer" }).on("click", () => { + replayUpdateNotice(); + }), AddButtonSounds(new Html("a").html(`Subscribe to my YouTube channel!`).attr({ href: "https://youtube.com/@ngx3", target: "_blank" }).styleJs({ + gap: "12px", + display: "flex", + alignItems: "center", + cursor: "pointer" + })))); +} +var miiQRConversionWarning = async (miiData) => { + if (miiData.hasExtendedColors() === true) { + let result = await Modal_default.prompt(__31("Warning"), __31("This Mii is using extended Switch colors, but those colors will never show up if you scan this QR Code anywhere outside of this app. Is this OK?"), "body", false); + if (result === false) + return false; + } + return true; +}; +var miiFFSDWarning = async (miiData) => { + if (miiData.hasExtendedColors() === true) { + let result = await Modal_default.prompt(__31("Warning"), __31(`This Mii is using extended Switch colors and/or Mii Creator features, but those features will be lost when converting to FFSD. +Use "Save Mii Creator data" if you want to keep the data. +Is this OK?`), "body", false); + if (result === false) + return false; + } + return true; +}; + +// src/ui/setup.ts +var __32 = _8(); +async function setupUi() { + let mm2 = getMusicManager(); + getSoundManager(); + let shownSessionModal = false; + setInterval(() => { + fetch("/api/session").then((e) => { + if (!e.ok) { + showSessionModal(); + } + }).catch((e) => { + showSessionModal(); + }); + }, 45000); + function showSessionModal() { + if (shownSessionModal) + return; + shownSessionModal = true; + Modal_default.modal(__32("Warning"), __32("Mii Creator has lost connection to the server. Click OK to reload."), "body", { + text: "OK", + callback(e) { + location.reload(); + } + }); + } + updateSettings(true); + await prepareFFL(); + function showBrowserWarning() { + if (navigator.userAgent.includes("Firefox") && sessionStorage.getItem("seen-firefox-notice") === null) { + sessionStorage.setItem("seen-firefox-notice", "yes"); + Modal_default.modal(__32("Warning"), __32("You're using Mii Creator under Firefox. Using the Firefox browser WILL experience slowdowns and lag."), "body", ...buttonsOkCancel); + } + if (navigator.userAgent.indexOf("Safari") != -1 && navigator.userAgent.indexOf("Chrome") == -1) { + Modal_default.modal(__32("Warning"), __32("You're using Mii Creator under Safari. Safari on iOS or iPadOS may experience instability with Mii Creator, causing the page to crash and refresh randomly. Some checks have been enabled to try and prevent the page from crashing right now. You have been warned."), "body", ...buttonsOkCancel); + } + } + if (navigator.userAgent.indexOf("Safari") != -1 && navigator.userAgent.indexOf("Chrome") == -1) { + window.browserMitigations = true; + } else { + } + Modal_default.modal(__32("Warning"), __32(`You're using a BETA version of Mii Creator. Some features in development have been disabled, and bugs/glitches can occur. + +• Special Miis have been changed. +• QR codes made from this version of Mii Creator can't be scanned back in. +• Your Mii library now automatically syncs with the server and across devices.`), "body", { + text: "Cancel", + callback(e) { + showBrowserWarning(); + } + }, { + text: __32("OK"), + callback() { + showBrowserWarning(); + } + }); + let state = "main"; + document.addEventListener("editor-launch", () => { + state = "edit"; + setTimeout(() => { + updateMusicVol(); + }, 100); + }); + document.addEventListener("editor-shutdown", () => { + state = "main"; + setTimeout(() => { + updateMusicVol(); + }, 100); + }); + function updateMusicVol() { + if (mm2.editGainNode === undefined) + return; + if (state === "main") { + mm2.mainGainNode.gain.linearRampToValueAtTime(-0.6, getMusicManager().audioContext.currentTime + 0.5); + mm2.editGainNode.gain.linearRampToValueAtTime(-1, getMusicManager().audioContext.currentTime + 0.5); + } + if (state === "edit") { + mm2.mainGainNode.gain.linearRampToValueAtTime(-1, getMusicManager().audioContext.currentTime + 0.5); + mm2.editGainNode.gain.linearRampToValueAtTime(-0.6, getMusicManager().audioContext.currentTime + 0.5); + } + } + mm2.initMusic(); + if (location.search !== "") { + const searchParams = new URLSearchParams(location.search); + if (searchParams.has("data")) { + new MiiEditor2(0, async (data2, shutdownProperly) => { + if (window.parent !== window.self) { + const miiData = new Mii(data2); + let headshot = null; + let headOnly = null; + let fullBody = null; + if (shutdownProperly === true) { + if (searchParams.has("renderTypes")) { + const renderTypes = searchParams.get("renderTypes").split(","); + } + } + mm2.mainGainNode.gain.linearRampToValueAtTime(-1, mm2.audioContext.currentTime + 0.5); + window.parent.postMessage({ + type: "miic-data-finalize", + properSave: shutdownProperly, + data: data2, + name: miiData.nickname, + creator: miiData.creator, + headshot, + headOnly, + fullBody + }, searchParams.get("origin")); + } else { + Library(); + } + }, searchParams.get("data")); + } else if (searchParams.has("select")) { + alert(__32("Selection library is currently not implemented yet")); + throw new Error(__32("Selection library is currently not implemented yet")); + } else if (searchParams.has("custom-render-preview")) { + } else if (searchParams.has("settings")) { + Settings(); + } else + Library(); + } else + Library(); + getSoundManager().setVolume(0.28); + mm2.setVolume(0.28); + window.addEventListener("blur", () => { + if (mm2.mainGainNode) { + mm2.mainGainNode.gain.linearRampToValueAtTime(-1, getMusicManager().audioContext.currentTime + 0.5); + if (mm2.editGainNode) { + mm2.editGainNode.gain.linearRampToValueAtTime(-1, getMusicManager().audioContext.currentTime + 0.5); + } + } else + getMusicManager().setVolume(0); + getSoundManager().setVolume(0); + }); + window.addEventListener("focus", () => { + if (mm2.mainGainNode) { + if (state === "main") { + mm2.mainGainNode.gain.setValueAtTime(-1, mm2.audioContext.currentTime); + mm2.mainGainNode.gain.linearRampToValueAtTime(-0.6, getMusicManager().audioContext.currentTime + 0.5); + } else if (state === "edit") { + if (mm2.editGainNode) { + mm2.editGainNode.gain.setValueAtTime(-1, mm2.audioContext.currentTime); + mm2.editGainNode.gain.linearRampToValueAtTime(-0.6, getMusicManager().audioContext.currentTime + 0.5); + } else { + mm2.mainGainNode.gain.setValueAtTime(-1, mm2.audioContext.currentTime); + mm2.mainGainNode.gain.linearRampToValueAtTime(-0.6, getMusicManager().audioContext.currentTime + 0.5); + } + } + } else + getMusicManager().setVolume(0); + getSoundManager().setVolume(getSoundManager().previousVolume); + }); + window.MusicManager = getMusicManager(); + window.soundManager = getSoundManager(); + window.localforage = import_localforage14.default; +} + +// src/main.ts +var import_vanilla_lazyload = __toESM(require_lazyload_min(), 1); + +// node_modules/@sentry/core/build/esm/debug-build.js +var DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; + +// node_modules/@sentry/core/build/esm/utils-hoist/version.js +var SDK_VERSION = "8.53.0"; + +// node_modules/@sentry/core/build/esm/utils-hoist/worldwide.js +var GLOBAL_OBJ = globalThis; +function getGlobalSingleton(name2, creator, obj) { + const gbl = obj || GLOBAL_OBJ; + const __SENTRY__ = gbl.__SENTRY__ = gbl.__SENTRY__ || {}; + const versionedCarrier = __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {}; + return versionedCarrier[name2] || (versionedCarrier[name2] = creator()); +} + +// node_modules/@sentry/core/build/esm/utils-hoist/debug-build.js +var DEBUG_BUILD2 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; + +// node_modules/@sentry/core/build/esm/utils-hoist/logger.js +var PREFIX = "Sentry Logger "; +var CONSOLE_LEVELS = [ + "debug", + "info", + "warn", + "error", + "log", + "assert", + "trace" +]; +var originalConsoleMethods = {}; +function consoleSandbox(callback) { + if (!("console" in GLOBAL_OBJ)) { + return callback(); + } + const console2 = GLOBAL_OBJ.console; + const wrappedFuncs = {}; + const wrappedLevels = Object.keys(originalConsoleMethods); + wrappedLevels.forEach((level) => { + const originalConsoleMethod = originalConsoleMethods[level]; + wrappedFuncs[level] = console2[level]; + console2[level] = originalConsoleMethod; + }); + try { + return callback(); + } finally { + wrappedLevels.forEach((level) => { + console2[level] = wrappedFuncs[level]; + }); + } +} +function makeLogger() { + let enabled = false; + const logger = { + enable: () => { + enabled = true; + }, + disable: () => { + enabled = false; + }, + isEnabled: () => enabled + }; + if (DEBUG_BUILD2) { + CONSOLE_LEVELS.forEach((name2) => { + logger[name2] = (...args) => { + if (enabled) { + consoleSandbox(() => { + GLOBAL_OBJ.console[name2](`${PREFIX}[${name2}]:`, ...args); + }); + } + }; + }); + } else { + CONSOLE_LEVELS.forEach((name2) => { + logger[name2] = () => { + return; + }; + }); + } + return logger; +} +var logger = getGlobalSingleton("logger", makeLogger); + +// node_modules/@sentry/core/build/esm/utils-hoist/stacktrace.js +var STACKTRACE_FRAME_LIMIT = 50; +var UNKNOWN_FUNCTION = "?"; +var WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/; +var STRIP_FRAME_REGEXP = /captureMessage|captureException/; +function createStackParser(...parsers) { + const sortedParsers = parsers.sort((a2, b3) => a2[0] - b3[0]).map((p) => p[1]); + return (stack, skipFirstLines = 0, framesToPop = 0) => { + const frames2 = []; + const lines = stack.split(` +`); + for (let i = skipFirstLines;i < lines.length; i++) { + const line2 = lines[i]; + if (line2.length > 1024) { + continue; + } + const cleanedLine = WEBPACK_ERROR_REGEXP.test(line2) ? line2.replace(WEBPACK_ERROR_REGEXP, "$1") : line2; + if (cleanedLine.match(/\S*Error: /)) { + continue; + } + for (const parser of sortedParsers) { + const frame = parser(cleanedLine); + if (frame) { + frames2.push(frame); + break; + } + } + if (frames2.length >= STACKTRACE_FRAME_LIMIT + framesToPop) { + break; + } + } + return stripSentryFramesAndReverse(frames2.slice(framesToPop)); + }; +} +function stackParserFromStackParserOptions(stackParser) { + if (Array.isArray(stackParser)) { + return createStackParser(...stackParser); + } + return stackParser; +} +function stripSentryFramesAndReverse(stack) { + if (!stack.length) { + return []; + } + const localStack = Array.from(stack); + if (/sentryWrapped/.test(getLastStackFrame(localStack).function || "")) { + localStack.pop(); + } + localStack.reverse(); + if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) { + localStack.pop(); + if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || "")) { + localStack.pop(); + } + } + return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({ + ...frame, + filename: frame.filename || getLastStackFrame(localStack).filename, + function: frame.function || UNKNOWN_FUNCTION + })); +} +function getLastStackFrame(arr) { + return arr[arr.length - 1] || {}; +} +var defaultFunctionName = ""; +function getFunctionName(fn) { + try { + if (!fn || typeof fn !== "function") { + return defaultFunctionName; + } + return fn.name || defaultFunctionName; + } catch (e) { + return defaultFunctionName; + } +} +function getFramesFromEvent(event) { + const exception = event.exception; + if (exception) { + const frames2 = []; + try { + exception.values.forEach((value2) => { + if (value2.stacktrace.frames) { + frames2.push(...value2.stacktrace.frames); + } + }); + return frames2; + } catch (_oO) { + return; + } + } + return; +} + +// node_modules/@sentry/core/build/esm/utils-hoist/instrument/handlers.js +var handlers = {}; +var instrumented = {}; +function addHandler(type, handler) { + handlers[type] = handlers[type] || []; + handlers[type].push(handler); +} +function maybeInstrument(type, instrumentFn) { + if (!instrumented[type]) { + instrumented[type] = true; + try { + instrumentFn(); + } catch (e) { + DEBUG_BUILD2 && logger.error(`Error while instrumenting ${type}`, e); + } + } +} +function triggerHandlers(type, data2) { + const typeHandlers = type && handlers[type]; + if (!typeHandlers) { + return; + } + for (const handler of typeHandlers) { + try { + handler(data2); + } catch (e) { + DEBUG_BUILD2 && logger.error(`Error while triggering instrumentation handler. +Type: ${type} +Name: ${getFunctionName(handler)} +Error:`, e); + } + } +} + +// node_modules/@sentry/core/build/esm/utils-hoist/instrument/globalError.js +var _oldOnErrorHandler = null; +function addGlobalErrorInstrumentationHandler(handler) { + const type = "error"; + addHandler(type, handler); + maybeInstrument(type, instrumentError); +} +function instrumentError() { + _oldOnErrorHandler = GLOBAL_OBJ.onerror; + GLOBAL_OBJ.onerror = function(msg, url, line2, column, error) { + const handlerData = { + column, + error, + line: line2, + msg, + url + }; + triggerHandlers("error", handlerData); + if (_oldOnErrorHandler) { + return _oldOnErrorHandler.apply(this, arguments); + } + return false; + }; + GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true; +} + +// node_modules/@sentry/core/build/esm/utils-hoist/instrument/globalUnhandledRejection.js +var _oldOnUnhandledRejectionHandler = null; +function addGlobalUnhandledRejectionInstrumentationHandler(handler) { + const type = "unhandledrejection"; + addHandler(type, handler); + maybeInstrument(type, instrumentUnhandledRejection); +} +function instrumentUnhandledRejection() { + _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection; + GLOBAL_OBJ.onunhandledrejection = function(e) { + const handlerData = e; + triggerHandlers("unhandledrejection", handlerData); + if (_oldOnUnhandledRejectionHandler) { + return _oldOnUnhandledRejectionHandler.apply(this, arguments); + } + return true; + }; + GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true; +} + +// node_modules/@sentry/core/build/esm/carrier.js +function getMainCarrier() { + getSentryCarrier(GLOBAL_OBJ); + return GLOBAL_OBJ; +} +function getSentryCarrier(carrier) { + const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {}; + __SENTRY__.version = __SENTRY__.version || SDK_VERSION; + return __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {}; +} + +// node_modules/@sentry/core/build/esm/utils-hoist/is.js +var objectToString = Object.prototype.toString; +function isError(wat) { + switch (objectToString.call(wat)) { + case "[object Error]": + case "[object Exception]": + case "[object DOMException]": + case "[object WebAssembly.Exception]": + return true; + default: + return isInstanceOf(wat, Error); + } +} +function isBuiltin(wat, className) { + return objectToString.call(wat) === `[object ${className}]`; +} +function isErrorEvent(wat) { + return isBuiltin(wat, "ErrorEvent"); +} +function isDOMError(wat) { + return isBuiltin(wat, "DOMError"); +} +function isDOMException(wat) { + return isBuiltin(wat, "DOMException"); +} +function isString2(wat) { + return isBuiltin(wat, "String"); +} +function isParameterizedString(wat) { + return typeof wat === "object" && wat !== null && "__sentry_template_string__" in wat && "__sentry_template_values__" in wat; +} +function isPrimitive(wat) { + return wat === null || isParameterizedString(wat) || typeof wat !== "object" && typeof wat !== "function"; +} +function isPlainObject(wat) { + return isBuiltin(wat, "Object"); +} +function isEvent(wat) { + return typeof Event !== "undefined" && isInstanceOf(wat, Event); +} +function isElement(wat) { + return typeof Element !== "undefined" && isInstanceOf(wat, Element); +} +function isRegExp2(wat) { + return isBuiltin(wat, "RegExp"); +} +function isThenable(wat) { + return Boolean(wat && wat.then && typeof wat.then === "function"); +} +function isSyntheticEvent(wat) { + return isPlainObject(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat; +} +function isInstanceOf(wat, base) { + try { + return wat instanceof base; + } catch (_e) { + return false; + } +} +function isVueViewModel(wat) { + return !!(typeof wat === "object" && wat !== null && (wat.__isVue || wat._isVue)); +} + +// node_modules/@sentry/core/build/esm/utils-hoist/browser.js +var WINDOW = GLOBAL_OBJ; +var DEFAULT_MAX_STRING_LENGTH = 80; +function htmlTreeAsString(elem2, options = {}) { + if (!elem2) { + return ""; + } + try { + let currentElem = elem2; + const MAX_TRAVERSE_HEIGHT = 5; + const out = []; + let height2 = 0; + let len = 0; + const separator = " > "; + const sepLength = separator.length; + let nextStr; + const keyAttrs = Array.isArray(options) ? options : options.keyAttrs; + const maxStringLength = !Array.isArray(options) && options.maxStringLength || DEFAULT_MAX_STRING_LENGTH; + while (currentElem && height2++ < MAX_TRAVERSE_HEIGHT) { + nextStr = _htmlElementAsString(currentElem, keyAttrs); + if (nextStr === "html" || height2 > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength) { + break; + } + out.push(nextStr); + len += nextStr.length; + currentElem = currentElem.parentNode; + } + return out.reverse().join(separator); + } catch (_oO) { + return ""; + } +} +function _htmlElementAsString(el, keyAttrs) { + const elem2 = el; + const out = []; + if (!elem2 || !elem2.tagName) { + return ""; + } + if (WINDOW.HTMLElement) { + if (elem2 instanceof HTMLElement && elem2.dataset) { + if (elem2.dataset["sentryComponent"]) { + return elem2.dataset["sentryComponent"]; + } + if (elem2.dataset["sentryElement"]) { + return elem2.dataset["sentryElement"]; + } + } + } + out.push(elem2.tagName.toLowerCase()); + const keyAttrPairs = keyAttrs && keyAttrs.length ? keyAttrs.filter((keyAttr) => elem2.getAttribute(keyAttr)).map((keyAttr) => [keyAttr, elem2.getAttribute(keyAttr)]) : null; + if (keyAttrPairs && keyAttrPairs.length) { + keyAttrPairs.forEach((keyAttrPair) => { + out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); + }); + } else { + if (elem2.id) { + out.push(`#${elem2.id}`); + } + const className = elem2.className; + if (className && isString2(className)) { + const classes = className.split(/\s+/); + for (const c2 of classes) { + out.push(`.${c2}`); + } + } + } + const allowedAttrs = ["aria-label", "type", "name", "title", "alt"]; + for (const k4 of allowedAttrs) { + const attr = elem2.getAttribute(k4); + if (attr) { + out.push(`[${k4}="${attr}"]`); + } + } + return out.join(""); +} +function getLocationHref2() { + try { + return WINDOW.document.location.href; + } catch (oO) { + return ""; + } +} +function getComponentName(elem2) { + if (!WINDOW.HTMLElement) { + return null; + } + let currentElem = elem2; + const MAX_TRAVERSE_HEIGHT = 5; + for (let i = 0;i < MAX_TRAVERSE_HEIGHT; i++) { + if (!currentElem) { + return null; + } + if (currentElem instanceof HTMLElement) { + if (currentElem.dataset["sentryComponent"]) { + return currentElem.dataset["sentryComponent"]; + } + if (currentElem.dataset["sentryElement"]) { + return currentElem.dataset["sentryElement"]; + } + } + currentElem = currentElem.parentNode; + } + return null; +} + +// node_modules/@sentry/core/build/esm/utils-hoist/string.js +function truncate(str, max = 0) { + if (typeof str !== "string" || max === 0) { + return str; + } + return str.length <= max ? str : `${str.slice(0, max)}...`; +} +function safeJoin(input, delimiter) { + if (!Array.isArray(input)) { + return ""; + } + const output = []; + for (let i = 0;i < input.length; i++) { + const value2 = input[i]; + try { + if (isVueViewModel(value2)) { + output.push("[VueViewModel]"); + } else { + output.push(String(value2)); + } + } catch (e) { + output.push("[value cannot be serialized]"); + } + } + return output.join(delimiter); +} +function isMatchingPattern(value2, pattern, requireExactStringMatch = false) { + if (!isString2(value2)) { + return false; + } + if (isRegExp2(pattern)) { + return pattern.test(value2); + } + if (isString2(pattern)) { + return requireExactStringMatch ? value2 === pattern : value2.includes(pattern); + } + return false; +} +function stringMatchesSomePattern(testString, patterns = [], requireExactStringMatch = false) { + return patterns.some((pattern) => isMatchingPattern(testString, pattern, requireExactStringMatch)); +} + +// node_modules/@sentry/core/build/esm/utils-hoist/object.js +function fill2(source, name2, replacementFactory) { + if (!(name2 in source)) { + return; + } + const original = source[name2]; + const wrapped = replacementFactory(original); + if (typeof wrapped === "function") { + markFunctionWrapped(wrapped, original); + } + try { + source[name2] = wrapped; + } catch (e) { + DEBUG_BUILD2 && logger.log(`Failed to replace method "${name2}" in object`, source); + } +} +function addNonEnumerableProperty(obj, name2, value2) { + try { + Object.defineProperty(obj, name2, { + value: value2, + writable: true, + configurable: true + }); + } catch (o_O) { + DEBUG_BUILD2 && logger.log(`Failed to add non-enumerable property "${name2}" to object`, obj); + } +} +function markFunctionWrapped(wrapped, original) { + try { + const proto = original.prototype || {}; + wrapped.prototype = original.prototype = proto; + addNonEnumerableProperty(wrapped, "__sentry_original__", original); + } catch (o_O) { + } +} +function getOriginalFunction(func) { + return func.__sentry_original__; +} +function convertToPlainObject(value2) { + if (isError(value2)) { + return { + message: value2.message, + name: value2.name, + stack: value2.stack, + ...getOwnProperties(value2) + }; + } else if (isEvent(value2)) { + const newObj = { + type: value2.type, + target: serializeEventTarget(value2.target), + currentTarget: serializeEventTarget(value2.currentTarget), + ...getOwnProperties(value2) + }; + if (typeof CustomEvent !== "undefined" && isInstanceOf(value2, CustomEvent)) { + newObj.detail = value2.detail; + } + return newObj; + } else { + return value2; + } +} +function serializeEventTarget(target) { + try { + return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target); + } catch (_oO) { + return ""; + } +} +function getOwnProperties(obj) { + if (typeof obj === "object" && obj !== null) { + const extractedProps = {}; + for (const property2 in obj) { + if (Object.prototype.hasOwnProperty.call(obj, property2)) { + extractedProps[property2] = obj[property2]; + } + } + return extractedProps; + } else { + return {}; + } +} +function extractExceptionKeysForMessage(exception, maxLength = 40) { + const keys2 = Object.keys(convertToPlainObject(exception)); + keys2.sort(); + const firstKey = keys2[0]; + if (!firstKey) { + return "[object has no keys]"; + } + if (firstKey.length >= maxLength) { + return truncate(firstKey, maxLength); + } + for (let includedKeys = keys2.length;includedKeys > 0; includedKeys--) { + const serialized = keys2.slice(0, includedKeys).join(", "); + if (serialized.length > maxLength) { + continue; + } + if (includedKeys === keys2.length) { + return serialized; + } + return truncate(serialized, maxLength); + } + return ""; +} +function dropUndefinedKeys(inputValue) { + const memoizationMap = new Map; + return _dropUndefinedKeys(inputValue, memoizationMap); +} +function _dropUndefinedKeys(inputValue, memoizationMap) { + if (isPojo(inputValue)) { + const memoVal = memoizationMap.get(inputValue); + if (memoVal !== undefined) { + return memoVal; + } + const returnValue = {}; + memoizationMap.set(inputValue, returnValue); + for (const key2 of Object.getOwnPropertyNames(inputValue)) { + if (typeof inputValue[key2] !== "undefined") { + returnValue[key2] = _dropUndefinedKeys(inputValue[key2], memoizationMap); + } + } + return returnValue; + } + if (Array.isArray(inputValue)) { + const memoVal = memoizationMap.get(inputValue); + if (memoVal !== undefined) { + return memoVal; + } + const returnValue = []; + memoizationMap.set(inputValue, returnValue); + inputValue.forEach((item) => { + returnValue.push(_dropUndefinedKeys(item, memoizationMap)); + }); + return returnValue; + } + return inputValue; +} +function isPojo(input) { + if (!isPlainObject(input)) { + return false; + } + try { + const name2 = Object.getPrototypeOf(input).constructor.name; + return !name2 || name2 === "Object"; + } catch (e2) { + return true; + } +} + +// node_modules/@sentry/core/build/esm/utils-hoist/time.js +var ONE_SECOND_IN_MS = 1000; +function dateTimestampInSeconds() { + return Date.now() / ONE_SECOND_IN_MS; +} +function createUnixTimestampInSecondsFunc() { + const { performance: performance2 } = GLOBAL_OBJ; + if (!performance2 || !performance2.now) { + return dateTimestampInSeconds; + } + const approxStartingTimeOrigin = Date.now() - performance2.now(); + const timeOrigin = performance2.timeOrigin == undefined ? approxStartingTimeOrigin : performance2.timeOrigin; + return () => { + return (timeOrigin + performance2.now()) / ONE_SECOND_IN_MS; + }; +} +var timestampInSeconds = createUnixTimestampInSecondsFunc(); +var _browserPerformanceTimeOriginMode; +var browserPerformanceTimeOrigin = (() => { + const { performance: performance2 } = GLOBAL_OBJ; + if (!performance2 || !performance2.now) { + _browserPerformanceTimeOriginMode = "none"; + return; + } + const threshold = 3600 * 1000; + const performanceNow = performance2.now(); + const dateNow = Date.now(); + const timeOriginDelta = performance2.timeOrigin ? Math.abs(performance2.timeOrigin + performanceNow - dateNow) : threshold; + const timeOriginIsReliable = timeOriginDelta < threshold; + const navigationStart = performance2.timing && performance2.timing.navigationStart; + const hasNavigationStart = typeof navigationStart === "number"; + const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; + const navigationStartIsReliable = navigationStartDelta < threshold; + if (timeOriginIsReliable || navigationStartIsReliable) { + if (timeOriginDelta <= navigationStartDelta) { + _browserPerformanceTimeOriginMode = "timeOrigin"; + return performance2.timeOrigin; + } else { + _browserPerformanceTimeOriginMode = "navigationStart"; + return navigationStart; + } + } + _browserPerformanceTimeOriginMode = "dateNow"; + return dateNow; +})(); + +// node_modules/@sentry/core/build/esm/utils-hoist/misc.js +function uuid4() { + const gbl = GLOBAL_OBJ; + const crypto3 = gbl.crypto || gbl.msCrypto; + let getRandomByte = () => Math.random() * 16; + try { + if (crypto3 && crypto3.randomUUID) { + return crypto3.randomUUID().replace(/-/g, ""); + } + if (crypto3 && crypto3.getRandomValues) { + getRandomByte = () => { + const typedArray = new Uint8Array(1); + crypto3.getRandomValues(typedArray); + return typedArray[0]; + }; + } + } catch (_9) { + } + return ([1e7] + 1000 + 4000 + 8000 + 100000000000).replace(/[018]/g, (c2) => (c2 ^ (getRandomByte() & 15) >> c2 / 4).toString(16)); +} +function getFirstException(event) { + return event.exception && event.exception.values ? event.exception.values[0] : undefined; +} +function getEventDescription(event) { + const { message, event_id: eventId } = event; + if (message) { + return message; + } + const firstException = getFirstException(event); + if (firstException) { + if (firstException.type && firstException.value) { + return `${firstException.type}: ${firstException.value}`; + } + return firstException.type || firstException.value || eventId || ""; + } + return eventId || ""; +} +function addExceptionTypeValue(event, value2, type) { + const exception = event.exception = event.exception || {}; + const values2 = exception.values = exception.values || []; + const firstException = values2[0] = values2[0] || {}; + if (!firstException.value) { + firstException.value = value2 || ""; + } + if (!firstException.type) { + firstException.type = type || "Error"; + } +} +function addExceptionMechanism(event, newMechanism) { + const firstException = getFirstException(event); + if (!firstException) { + return; + } + const defaultMechanism = { type: "generic", handled: true }; + const currentMechanism = firstException.mechanism; + firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism }; + if (newMechanism && "data" in newMechanism) { + const mergedData = { ...currentMechanism && currentMechanism.data, ...newMechanism.data }; + firstException.mechanism.data = mergedData; + } +} +function checkOrSetAlreadyCaught(exception) { + if (isAlreadyCaptured(exception)) { + return true; + } + try { + addNonEnumerableProperty(exception, "__sentry_captured__", true); + } catch (err) { + } + return false; +} +function isAlreadyCaptured(exception) { + try { + return exception.__sentry_captured__; + } catch (e) { + } +} + +// node_modules/@sentry/core/build/esm/utils-hoist/syncpromise.js +var States; +(function(States2) { + const PENDING = 0; + States2[States2["PENDING"] = PENDING] = "PENDING"; + const RESOLVED = 1; + States2[States2["RESOLVED"] = RESOLVED] = "RESOLVED"; + const REJECTED = 2; + States2[States2["REJECTED"] = REJECTED] = "REJECTED"; +})(States || (States = {})); +function resolvedSyncPromise(value2) { + return new SyncPromise((resolve) => { + resolve(value2); + }); +} +function rejectedSyncPromise(reason) { + return new SyncPromise((_9, reject2) => { + reject2(reason); + }); +} + +class SyncPromise { + constructor(executor) { + SyncPromise.prototype.__init.call(this); + SyncPromise.prototype.__init2.call(this); + SyncPromise.prototype.__init3.call(this); + SyncPromise.prototype.__init4.call(this); + this._state = States.PENDING; + this._handlers = []; + try { + executor(this._resolve, this._reject); + } catch (e) { + this._reject(e); + } + } + then(onfulfilled, onrejected) { + return new SyncPromise((resolve, reject2) => { + this._handlers.push([ + false, + (result) => { + if (!onfulfilled) { + resolve(result); + } else { + try { + resolve(onfulfilled(result)); + } catch (e) { + reject2(e); + } + } + }, + (reason) => { + if (!onrejected) { + reject2(reason); + } else { + try { + resolve(onrejected(reason)); + } catch (e) { + reject2(e); + } + } + } + ]); + this._executeHandlers(); + }); + } + catch(onrejected) { + return this.then((val2) => val2, onrejected); + } + finally(onfinally) { + return new SyncPromise((resolve, reject2) => { + let val2; + let isRejected; + return this.then((value2) => { + isRejected = false; + val2 = value2; + if (onfinally) { + onfinally(); + } + }, (reason) => { + isRejected = true; + val2 = reason; + if (onfinally) { + onfinally(); + } + }).then(() => { + if (isRejected) { + reject2(val2); + return; + } + resolve(val2); + }); + }); + } + __init() { + this._resolve = (value2) => { + this._setResult(States.RESOLVED, value2); + }; + } + __init2() { + this._reject = (reason) => { + this._setResult(States.REJECTED, reason); + }; + } + __init3() { + this._setResult = (state, value2) => { + if (this._state !== States.PENDING) { + return; + } + if (isThenable(value2)) { + value2.then(this._resolve, this._reject); + return; + } + this._state = state; + this._value = value2; + this._executeHandlers(); + }; + } + __init4() { + this._executeHandlers = () => { + if (this._state === States.PENDING) { + return; + } + const cachedHandlers = this._handlers.slice(); + this._handlers = []; + cachedHandlers.forEach((handler) => { + if (handler[0]) { + return; + } + if (this._state === States.RESOLVED) { + handler[1](this._value); + } + if (this._state === States.REJECTED) { + handler[2](this._value); + } + handler[0] = true; + }); + }; + } +} + +// node_modules/@sentry/core/build/esm/session.js +function makeSession(context) { + const startingTime = timestampInSeconds(); + const session = { + sid: uuid4(), + init: true, + timestamp: startingTime, + started: startingTime, + duration: 0, + status: "ok", + errors: 0, + ignoreDuration: false, + toJSON: () => sessionToJSON(session) + }; + if (context) { + updateSession(session, context); + } + return session; +} +function updateSession(session, context = {}) { + if (context.user) { + if (!session.ipAddress && context.user.ip_address) { + session.ipAddress = context.user.ip_address; + } + if (!session.did && !context.did) { + session.did = context.user.id || context.user.email || context.user.username; + } + } + session.timestamp = context.timestamp || timestampInSeconds(); + if (context.abnormal_mechanism) { + session.abnormal_mechanism = context.abnormal_mechanism; + } + if (context.ignoreDuration) { + session.ignoreDuration = context.ignoreDuration; + } + if (context.sid) { + session.sid = context.sid.length === 32 ? context.sid : uuid4(); + } + if (context.init !== undefined) { + session.init = context.init; + } + if (!session.did && context.did) { + session.did = `${context.did}`; + } + if (typeof context.started === "number") { + session.started = context.started; + } + if (session.ignoreDuration) { + session.duration = undefined; + } else if (typeof context.duration === "number") { + session.duration = context.duration; + } else { + const duration = session.timestamp - session.started; + session.duration = duration >= 0 ? duration : 0; + } + if (context.release) { + session.release = context.release; + } + if (context.environment) { + session.environment = context.environment; + } + if (!session.ipAddress && context.ipAddress) { + session.ipAddress = context.ipAddress; + } + if (!session.userAgent && context.userAgent) { + session.userAgent = context.userAgent; + } + if (typeof context.errors === "number") { + session.errors = context.errors; + } + if (context.status) { + session.status = context.status; + } +} +function closeSession(session, status) { + let context = {}; + if (status) { + context = { status }; + } else if (session.status === "ok") { + context = { status: "exited" }; + } + updateSession(session, context); +} +function sessionToJSON(session) { + return dropUndefinedKeys({ + sid: `${session.sid}`, + init: session.init, + started: new Date(session.started * 1000).toISOString(), + timestamp: new Date(session.timestamp * 1000).toISOString(), + status: session.status, + errors: session.errors, + did: typeof session.did === "number" || typeof session.did === "string" ? `${session.did}` : undefined, + duration: session.duration, + abnormal_mechanism: session.abnormal_mechanism, + attrs: { + release: session.release, + environment: session.environment, + ip_address: session.ipAddress, + user_agent: session.userAgent + } + }); +} + +// node_modules/@sentry/core/build/esm/utils-hoist/propagationContext.js +function generateTraceId() { + return uuid4(); +} +function generateSpanId() { + return uuid4().substring(16); +} + +// node_modules/@sentry/core/build/esm/utils/merge.js +function merge2(initialObj, mergeObj, levels = 2) { + if (!mergeObj || typeof mergeObj !== "object" || levels <= 0) { + return mergeObj; + } + if (initialObj && mergeObj && Object.keys(mergeObj).length === 0) { + return initialObj; + } + const output = { ...initialObj }; + for (const key2 in mergeObj) { + if (Object.prototype.hasOwnProperty.call(mergeObj, key2)) { + output[key2] = merge2(output[key2], mergeObj[key2], levels - 1); + } + } + return output; +} + +// node_modules/@sentry/core/build/esm/utils/spanOnScope.js +var SCOPE_SPAN_FIELD = "_sentrySpan"; +function _setSpanForScope(scope, span) { + if (span) { + addNonEnumerableProperty(scope, SCOPE_SPAN_FIELD, span); + } else { + delete scope[SCOPE_SPAN_FIELD]; + } +} +function _getSpanForScope(scope) { + return scope[SCOPE_SPAN_FIELD]; +} + +// node_modules/@sentry/core/build/esm/scope.js +var DEFAULT_MAX_BREADCRUMBS = 100; + +class ScopeClass { + constructor() { + this._notifyingListeners = false; + this._scopeListeners = []; + this._eventProcessors = []; + this._breadcrumbs = []; + this._attachments = []; + this._user = {}; + this._tags = {}; + this._extra = {}; + this._contexts = {}; + this._sdkProcessingMetadata = {}; + this._propagationContext = { + traceId: generateTraceId(), + spanId: generateSpanId() + }; + } + clone() { + const newScope = new ScopeClass; + newScope._breadcrumbs = [...this._breadcrumbs]; + newScope._tags = { ...this._tags }; + newScope._extra = { ...this._extra }; + newScope._contexts = { ...this._contexts }; + if (this._contexts.flags) { + newScope._contexts.flags = { + values: [...this._contexts.flags.values] + }; + } + newScope._user = this._user; + newScope._level = this._level; + newScope._session = this._session; + newScope._transactionName = this._transactionName; + newScope._fingerprint = this._fingerprint; + newScope._eventProcessors = [...this._eventProcessors]; + newScope._requestSession = this._requestSession; + newScope._attachments = [...this._attachments]; + newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata }; + newScope._propagationContext = { ...this._propagationContext }; + newScope._client = this._client; + newScope._lastEventId = this._lastEventId; + _setSpanForScope(newScope, _getSpanForScope(this)); + return newScope; + } + setClient(client) { + this._client = client; + } + setLastEventId(lastEventId) { + this._lastEventId = lastEventId; + } + getClient() { + return this._client; + } + lastEventId() { + return this._lastEventId; + } + addScopeListener(callback) { + this._scopeListeners.push(callback); + } + addEventProcessor(callback) { + this._eventProcessors.push(callback); + return this; + } + setUser(user) { + this._user = user || { + email: undefined, + id: undefined, + ip_address: undefined, + username: undefined + }; + if (this._session) { + updateSession(this._session, { user }); + } + this._notifyScopeListeners(); + return this; + } + getUser() { + return this._user; + } + getRequestSession() { + return this._requestSession; + } + setRequestSession(requestSession) { + this._requestSession = requestSession; + return this; + } + setTags(tags) { + this._tags = { + ...this._tags, + ...tags + }; + this._notifyScopeListeners(); + return this; + } + setTag(key2, value2) { + this._tags = { ...this._tags, [key2]: value2 }; + this._notifyScopeListeners(); + return this; + } + setExtras(extras) { + this._extra = { + ...this._extra, + ...extras + }; + this._notifyScopeListeners(); + return this; + } + setExtra(key2, extra) { + this._extra = { ...this._extra, [key2]: extra }; + this._notifyScopeListeners(); + return this; + } + setFingerprint(fingerprint) { + this._fingerprint = fingerprint; + this._notifyScopeListeners(); + return this; + } + setLevel(level) { + this._level = level; + this._notifyScopeListeners(); + return this; + } + setTransactionName(name2) { + this._transactionName = name2; + this._notifyScopeListeners(); + return this; + } + setContext(key2, context) { + if (context === null) { + delete this._contexts[key2]; + } else { + this._contexts[key2] = context; + } + this._notifyScopeListeners(); + return this; + } + setSession(session) { + if (!session) { + delete this._session; + } else { + this._session = session; + } + this._notifyScopeListeners(); + return this; + } + getSession() { + return this._session; + } + update(captureContext) { + if (!captureContext) { + return this; + } + const scopeToMerge = typeof captureContext === "function" ? captureContext(this) : captureContext; + const [scopeInstance, requestSession] = scopeToMerge instanceof Scope ? [scopeToMerge.getScopeData(), scopeToMerge.getRequestSession()] : isPlainObject(scopeToMerge) ? [captureContext, captureContext.requestSession] : []; + const { tags, extra, user, contexts, level, fingerprint = [], propagationContext } = scopeInstance || {}; + this._tags = { ...this._tags, ...tags }; + this._extra = { ...this._extra, ...extra }; + this._contexts = { ...this._contexts, ...contexts }; + if (user && Object.keys(user).length) { + this._user = user; + } + if (level) { + this._level = level; + } + if (fingerprint.length) { + this._fingerprint = fingerprint; + } + if (propagationContext) { + this._propagationContext = propagationContext; + } + if (requestSession) { + this._requestSession = requestSession; + } + return this; + } + clear() { + this._breadcrumbs = []; + this._tags = {}; + this._extra = {}; + this._user = {}; + this._contexts = {}; + this._level = undefined; + this._transactionName = undefined; + this._fingerprint = undefined; + this._requestSession = undefined; + this._session = undefined; + _setSpanForScope(this, undefined); + this._attachments = []; + this.setPropagationContext({ traceId: generateTraceId() }); + this._notifyScopeListeners(); + return this; + } + addBreadcrumb(breadcrumb, maxBreadcrumbs) { + const maxCrumbs = typeof maxBreadcrumbs === "number" ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS; + if (maxCrumbs <= 0) { + return this; + } + const mergedBreadcrumb = { + timestamp: dateTimestampInSeconds(), + ...breadcrumb + }; + this._breadcrumbs.push(mergedBreadcrumb); + if (this._breadcrumbs.length > maxCrumbs) { + this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs); + if (this._client) { + this._client.recordDroppedEvent("buffer_overflow", "log_item"); + } + } + this._notifyScopeListeners(); + return this; + } + getLastBreadcrumb() { + return this._breadcrumbs[this._breadcrumbs.length - 1]; + } + clearBreadcrumbs() { + this._breadcrumbs = []; + this._notifyScopeListeners(); + return this; + } + addAttachment(attachment) { + this._attachments.push(attachment); + return this; + } + clearAttachments() { + this._attachments = []; + return this; + } + getScopeData() { + return { + breadcrumbs: this._breadcrumbs, + attachments: this._attachments, + contexts: this._contexts, + tags: this._tags, + extra: this._extra, + user: this._user, + level: this._level, + fingerprint: this._fingerprint || [], + eventProcessors: this._eventProcessors, + propagationContext: this._propagationContext, + sdkProcessingMetadata: this._sdkProcessingMetadata, + transactionName: this._transactionName, + span: _getSpanForScope(this) + }; + } + setSDKProcessingMetadata(newData) { + this._sdkProcessingMetadata = merge2(this._sdkProcessingMetadata, newData, 2); + return this; + } + setPropagationContext(context) { + this._propagationContext = { + spanId: generateSpanId(), + ...context + }; + return this; + } + getPropagationContext() { + return this._propagationContext; + } + captureException(exception, hint) { + const eventId = hint && hint.event_id ? hint.event_id : uuid4(); + if (!this._client) { + logger.warn("No client configured on scope - will not capture exception!"); + return eventId; + } + const syntheticException = new Error("Sentry syntheticException"); + this._client.captureException(exception, { + originalException: exception, + syntheticException, + ...hint, + event_id: eventId + }, this); + return eventId; + } + captureMessage(message, level, hint) { + const eventId = hint && hint.event_id ? hint.event_id : uuid4(); + if (!this._client) { + logger.warn("No client configured on scope - will not capture message!"); + return eventId; + } + const syntheticException = new Error(message); + this._client.captureMessage(message, level, { + originalException: message, + syntheticException, + ...hint, + event_id: eventId + }, this); + return eventId; + } + captureEvent(event, hint) { + const eventId = hint && hint.event_id ? hint.event_id : uuid4(); + if (!this._client) { + logger.warn("No client configured on scope - will not capture event!"); + return eventId; + } + this._client.captureEvent(event, { ...hint, event_id: eventId }, this); + return eventId; + } + _notifyScopeListeners() { + if (!this._notifyingListeners) { + this._notifyingListeners = true; + this._scopeListeners.forEach((callback) => { + callback(this); + }); + this._notifyingListeners = false; + } + } +} +var Scope = ScopeClass; + +// node_modules/@sentry/core/build/esm/defaultScopes.js +function getDefaultCurrentScope() { + return getGlobalSingleton("defaultCurrentScope", () => new Scope); +} +function getDefaultIsolationScope() { + return getGlobalSingleton("defaultIsolationScope", () => new Scope); +} + +// node_modules/@sentry/core/build/esm/asyncContext/stackStrategy.js +class AsyncContextStack { + constructor(scope, isolationScope) { + let assignedScope; + if (!scope) { + assignedScope = new Scope; + } else { + assignedScope = scope; + } + let assignedIsolationScope; + if (!isolationScope) { + assignedIsolationScope = new Scope; + } else { + assignedIsolationScope = isolationScope; + } + this._stack = [{ scope: assignedScope }]; + this._isolationScope = assignedIsolationScope; + } + withScope(callback) { + const scope = this._pushScope(); + let maybePromiseResult; + try { + maybePromiseResult = callback(scope); + } catch (e) { + this._popScope(); + throw e; + } + if (isThenable(maybePromiseResult)) { + return maybePromiseResult.then((res) => { + this._popScope(); + return res; + }, (e) => { + this._popScope(); + throw e; + }); + } + this._popScope(); + return maybePromiseResult; + } + getClient() { + return this.getStackTop().client; + } + getScope() { + return this.getStackTop().scope; + } + getIsolationScope() { + return this._isolationScope; + } + getStackTop() { + return this._stack[this._stack.length - 1]; + } + _pushScope() { + const scope = this.getScope().clone(); + this._stack.push({ + client: this.getClient(), + scope + }); + return scope; + } + _popScope() { + if (this._stack.length <= 1) + return false; + return !!this._stack.pop(); + } +} +function getAsyncContextStack() { + const registry = getMainCarrier(); + const sentry = getSentryCarrier(registry); + return sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope()); +} +function withScope(callback) { + return getAsyncContextStack().withScope(callback); +} +function withSetScope(scope, callback) { + const stack = getAsyncContextStack(); + return stack.withScope(() => { + stack.getStackTop().scope = scope; + return callback(scope); + }); +} +function withIsolationScope(callback) { + return getAsyncContextStack().withScope(() => { + return callback(getAsyncContextStack().getIsolationScope()); + }); +} +function getStackAsyncContextStrategy() { + return { + withIsolationScope, + withScope, + withSetScope, + withSetIsolationScope: (_isolationScope, callback) => { + return withIsolationScope(callback); + }, + getCurrentScope: () => getAsyncContextStack().getScope(), + getIsolationScope: () => getAsyncContextStack().getIsolationScope() + }; +} + +// node_modules/@sentry/core/build/esm/asyncContext/index.js +function getAsyncContextStrategy(carrier) { + const sentry = getSentryCarrier(carrier); + if (sentry.acs) { + return sentry.acs; + } + return getStackAsyncContextStrategy(); +} + +// node_modules/@sentry/core/build/esm/currentScopes.js +function getCurrentScope() { + const carrier = getMainCarrier(); + const acs = getAsyncContextStrategy(carrier); + return acs.getCurrentScope(); +} +function getIsolationScope() { + const carrier = getMainCarrier(); + const acs = getAsyncContextStrategy(carrier); + return acs.getIsolationScope(); +} +function getGlobalScope() { + return getGlobalSingleton("globalScope", () => new Scope); +} +function withScope2(...rest) { + const carrier = getMainCarrier(); + const acs = getAsyncContextStrategy(carrier); + if (rest.length === 2) { + const [scope, callback] = rest; + if (!scope) { + return acs.withScope(callback); + } + return acs.withSetScope(scope, callback); + } + return acs.withScope(rest[0]); +} +function getClient() { + return getCurrentScope().getClient(); +} +function getTraceContextFromScope(scope) { + const propagationContext = scope.getPropagationContext(); + const { traceId, spanId, parentSpanId } = propagationContext; + const traceContext = dropUndefinedKeys({ + trace_id: traceId, + span_id: spanId, + parent_span_id: parentSpanId + }); + return traceContext; +} + +// node_modules/@sentry/core/build/esm/metrics/metric-summary.js +var METRICS_SPAN_FIELD = "_sentryMetrics"; +function getMetricSummaryJsonForSpan(span) { + const storage = span[METRICS_SPAN_FIELD]; + if (!storage) { + return; + } + const output = {}; + for (const [, [exportKey, summary]] of storage) { + const arr = output[exportKey] || (output[exportKey] = []); + arr.push(dropUndefinedKeys(summary)); + } + return output; +} + +// node_modules/@sentry/core/build/esm/semanticAttributes.js +var SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = "sentry.source"; +var SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = "sentry.sample_rate"; +var SEMANTIC_ATTRIBUTE_SENTRY_OP = "sentry.op"; +var SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = "sentry.origin"; + +// node_modules/@sentry/core/build/esm/tracing/spanstatus.js +var SPAN_STATUS_UNSET = 0; +var SPAN_STATUS_OK = 1; + +// node_modules/@sentry/core/build/esm/utils-hoist/baggage.js +var SENTRY_BAGGAGE_KEY_PREFIX = "sentry-"; +var SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/; +function baggageHeaderToDynamicSamplingContext(baggageHeader) { + const baggageObject = parseBaggageHeader(baggageHeader); + if (!baggageObject) { + return; + } + const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key2, value2]) => { + if (key2.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) { + const nonPrefixedKey = key2.slice(SENTRY_BAGGAGE_KEY_PREFIX.length); + acc[nonPrefixedKey] = value2; + } + return acc; + }, {}); + if (Object.keys(dynamicSamplingContext).length > 0) { + return dynamicSamplingContext; + } else { + return; + } +} +function parseBaggageHeader(baggageHeader) { + if (!baggageHeader || !isString2(baggageHeader) && !Array.isArray(baggageHeader)) { + return; + } + if (Array.isArray(baggageHeader)) { + return baggageHeader.reduce((acc, curr) => { + const currBaggageObject = baggageHeaderToObject(curr); + Object.entries(currBaggageObject).forEach(([key2, value2]) => { + acc[key2] = value2; + }); + return acc; + }, {}); + } + return baggageHeaderToObject(baggageHeader); +} +function baggageHeaderToObject(baggageHeader) { + return baggageHeader.split(",").map((baggageEntry) => baggageEntry.split("=").map((keyOrValue) => decodeURIComponent(keyOrValue.trim()))).reduce((acc, [key2, value2]) => { + if (key2 && value2) { + acc[key2] = value2; + } + return acc; + }, {}); +} + +// node_modules/@sentry/core/build/esm/utils/spanUtils.js +var TRACE_FLAG_SAMPLED = 1; +var hasShownSpanDropWarning = false; +function spanToTraceContext(span) { + const { spanId, traceId: trace_id, isRemote } = span.spanContext(); + const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id; + const span_id = isRemote ? generateSpanId() : spanId; + return dropUndefinedKeys({ + parent_span_id, + span_id, + trace_id + }); +} +function spanTimeInputToSeconds(input) { + if (typeof input === "number") { + return ensureTimestampInSeconds(input); + } + if (Array.isArray(input)) { + return input[0] + input[1] / 1e9; + } + if (input instanceof Date) { + return ensureTimestampInSeconds(input.getTime()); + } + return timestampInSeconds(); +} +function ensureTimestampInSeconds(timestamp) { + const isMs = timestamp > 9999999999; + return isMs ? timestamp / 1000 : timestamp; +} +function spanToJSON(span) { + if (spanIsSentrySpan(span)) { + return span.getSpanJSON(); + } + try { + const { spanId: span_id, traceId: trace_id } = span.spanContext(); + if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) { + const { attributes, startTime, name: name2, endTime, parentSpanId, status } = span; + return dropUndefinedKeys({ + span_id, + trace_id, + data: attributes, + description: name2, + parent_span_id: parentSpanId, + start_timestamp: spanTimeInputToSeconds(startTime), + timestamp: spanTimeInputToSeconds(endTime) || undefined, + status: getStatusMessage(status), + op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP], + origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN], + _metrics_summary: getMetricSummaryJsonForSpan(span) + }); + } + return { + span_id, + trace_id + }; + } catch (e) { + return {}; + } +} +function spanIsOpenTelemetrySdkTraceBaseSpan(span) { + const castSpan = span; + return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status; +} +function spanIsSentrySpan(span) { + return typeof span.getSpanJSON === "function"; +} +function spanIsSampled(span) { + const { traceFlags } = span.spanContext(); + return traceFlags === TRACE_FLAG_SAMPLED; +} +function getStatusMessage(status) { + if (!status || status.code === SPAN_STATUS_UNSET) { + return; + } + if (status.code === SPAN_STATUS_OK) { + return "ok"; + } + return status.message || "unknown_error"; +} +var ROOT_SPAN_FIELD = "_sentryRootSpan"; +function getRootSpan(span) { + return span[ROOT_SPAN_FIELD] || span; +} +function showSpanDropWarning() { + if (!hasShownSpanDropWarning) { + consoleSandbox(() => { + console.warn("[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly."); + }); + hasShownSpanDropWarning = true; + } +} + +// node_modules/@sentry/core/build/esm/utils/hasTracingEnabled.js +function hasTracingEnabled(maybeOptions) { + if (typeof __SENTRY_TRACING__ === "boolean" && !__SENTRY_TRACING__) { + return false; + } + const client = getClient(); + const options = maybeOptions || client && client.getOptions(); + return !!options && (options.enableTracing || ("tracesSampleRate" in options) || ("tracesSampler" in options)); +} + +// node_modules/@sentry/core/build/esm/constants.js +var DEFAULT_ENVIRONMENT = "production"; + +// node_modules/@sentry/core/build/esm/tracing/dynamicSamplingContext.js +var FROZEN_DSC_FIELD = "_frozenDsc"; +function getDynamicSamplingContextFromClient(trace_id, client) { + const options = client.getOptions(); + const { publicKey: public_key } = client.getDsn() || {}; + const dsc = dropUndefinedKeys({ + environment: options.environment || DEFAULT_ENVIRONMENT, + release: options.release, + public_key, + trace_id + }); + client.emit("createDsc", dsc); + return dsc; +} +function getDynamicSamplingContextFromScope(client, scope) { + const propagationContext = scope.getPropagationContext(); + return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client); +} +function getDynamicSamplingContextFromSpan(span) { + const client = getClient(); + if (!client) { + return {}; + } + const rootSpan = getRootSpan(span); + const frozenDsc = rootSpan[FROZEN_DSC_FIELD]; + if (frozenDsc) { + return frozenDsc; + } + const traceState = rootSpan.spanContext().traceState; + const traceStateDsc = traceState && traceState.get("sentry.dsc"); + const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc); + if (dscOnTraceState) { + return dscOnTraceState; + } + const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client); + const jsonSpan = spanToJSON(rootSpan); + const attributes = jsonSpan.data || {}; + const maybeSampleRate = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]; + if (maybeSampleRate != null) { + dsc.sample_rate = `${maybeSampleRate}`; + } + const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]; + const name2 = jsonSpan.description; + if (source !== "url" && name2) { + dsc.transaction = name2; + } + if (hasTracingEnabled()) { + dsc.sampled = String(spanIsSampled(rootSpan)); + } + client.emit("createDsc", dsc, rootSpan); + return dsc; +} + +// node_modules/@sentry/core/build/esm/utils/parseSampleRate.js +function parseSampleRate(sampleRate) { + if (typeof sampleRate === "boolean") { + return Number(sampleRate); + } + const rate = typeof sampleRate === "string" ? parseFloat(sampleRate) : sampleRate; + if (typeof rate !== "number" || isNaN(rate) || rate < 0 || rate > 1) { + DEBUG_BUILD && logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(sampleRate)} of type ${JSON.stringify(typeof sampleRate)}.`); + return; + } + return rate; +} + +// node_modules/@sentry/core/build/esm/utils-hoist/dsn.js +var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/; +function isValidProtocol(protocol) { + return protocol === "http" || protocol === "https"; +} +function dsnToString(dsn, withPassword = false) { + const { host, path, pass, port, projectId, protocol, publicKey } = dsn; + return `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ""}` + `@${host}${port ? `:${port}` : ""}/${path ? `${path}/` : path}${projectId}`; +} +function dsnFromString(str) { + const match = DSN_REGEX.exec(str); + if (!match) { + consoleSandbox(() => { + console.error(`Invalid Sentry Dsn: ${str}`); + }); + return; + } + const [protocol, publicKey, pass = "", host = "", port = "", lastPath = ""] = match.slice(1); + let path = ""; + let projectId = lastPath; + const split = projectId.split("/"); + if (split.length > 1) { + path = split.slice(0, -1).join("/"); + projectId = split.pop(); + } + if (projectId) { + const projectMatch = projectId.match(/^\d+/); + if (projectMatch) { + projectId = projectMatch[0]; + } + } + return dsnFromComponents({ host, pass, path, projectId, port, protocol, publicKey }); +} +function dsnFromComponents(components) { + return { + protocol: components.protocol, + publicKey: components.publicKey || "", + pass: components.pass || "", + host: components.host, + port: components.port || "", + path: components.path || "", + projectId: components.projectId + }; +} +function validateDsn(dsn) { + if (!DEBUG_BUILD2) { + return true; + } + const { port, projectId, protocol } = dsn; + const requiredComponents = ["protocol", "publicKey", "host", "projectId"]; + const hasMissingRequiredComponent = requiredComponents.find((component) => { + if (!dsn[component]) { + logger.error(`Invalid Sentry Dsn: ${component} missing`); + return true; + } + return false; + }); + if (hasMissingRequiredComponent) { + return false; + } + if (!projectId.match(/^\d+$/)) { + logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`); + return false; + } + if (!isValidProtocol(protocol)) { + logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`); + return false; + } + if (port && isNaN(parseInt(port, 10))) { + logger.error(`Invalid Sentry Dsn: Invalid port ${port}`); + return false; + } + return true; +} +function makeDsn(from) { + const components = typeof from === "string" ? dsnFromString(from) : dsnFromComponents(from); + if (!components || !validateDsn(components)) { + return; + } + return components; +} + +// node_modules/@sentry/core/build/esm/utils-hoist/memo.js +function memoBuilder() { + const hasWeakSet = typeof WeakSet === "function"; + const inner = hasWeakSet ? new WeakSet : []; + function memoize(obj) { + if (hasWeakSet) { + if (inner.has(obj)) { + return true; + } + inner.add(obj); + return false; + } + for (let i = 0;i < inner.length; i++) { + const value2 = inner[i]; + if (value2 === obj) { + return true; + } + } + inner.push(obj); + return false; + } + function unmemoize(obj) { + if (hasWeakSet) { + inner.delete(obj); + } else { + for (let i = 0;i < inner.length; i++) { + if (inner[i] === obj) { + inner.splice(i, 1); + break; + } + } + } + } + return [memoize, unmemoize]; +} + +// node_modules/@sentry/core/build/esm/utils-hoist/normalize.js +function normalize3(input, depth = 100, maxProperties = Infinity) { + try { + return visit("", input, depth, maxProperties); + } catch (err) { + return { ERROR: `**non-serializable** (${err})` }; + } +} +function normalizeToSize(object, depth = 3, maxSize = 100 * 1024) { + const normalized = normalize3(object, depth); + if (jsonSize(normalized) > maxSize) { + return normalizeToSize(object, depth - 1, maxSize); + } + return normalized; +} +function visit(key2, value2, depth = Infinity, maxProperties = Infinity, memo = memoBuilder()) { + const [memoize, unmemoize] = memo; + if (value2 == null || ["boolean", "string"].includes(typeof value2) || typeof value2 === "number" && Number.isFinite(value2)) { + return value2; + } + const stringified = stringifyValue(key2, value2); + if (!stringified.startsWith("[object ")) { + return stringified; + } + if (value2["__sentry_skip_normalization__"]) { + return value2; + } + const remainingDepth = typeof value2["__sentry_override_normalization_depth__"] === "number" ? value2["__sentry_override_normalization_depth__"] : depth; + if (remainingDepth === 0) { + return stringified.replace("object ", ""); + } + if (memoize(value2)) { + return "[Circular ~]"; + } + const valueWithToJSON = value2; + if (valueWithToJSON && typeof valueWithToJSON.toJSON === "function") { + try { + const jsonValue = valueWithToJSON.toJSON(); + return visit("", jsonValue, remainingDepth - 1, maxProperties, memo); + } catch (err) { + } + } + const normalized = Array.isArray(value2) ? [] : {}; + let numAdded = 0; + const visitable = convertToPlainObject(value2); + for (const visitKey in visitable) { + if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) { + continue; + } + if (numAdded >= maxProperties) { + normalized[visitKey] = "[MaxProperties ~]"; + break; + } + const visitValue = visitable[visitKey]; + normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo); + numAdded++; + } + unmemoize(value2); + return normalized; +} +function stringifyValue(key2, value2) { + try { + if (key2 === "domain" && value2 && typeof value2 === "object" && value2._events) { + return "[Domain]"; + } + if (key2 === "domainEmitter") { + return "[DomainEmitter]"; + } + if (typeof global !== "undefined" && value2 === global) { + return "[Global]"; + } + if (typeof window !== "undefined" && value2 === window) { + return "[Window]"; + } + if (typeof document !== "undefined" && value2 === document) { + return "[Document]"; + } + if (isVueViewModel(value2)) { + return "[VueViewModel]"; + } + if (isSyntheticEvent(value2)) { + return "[SyntheticEvent]"; + } + if (typeof value2 === "number" && !Number.isFinite(value2)) { + return `[${value2}]`; + } + if (typeof value2 === "function") { + return `[Function: ${getFunctionName(value2)}]`; + } + if (typeof value2 === "symbol") { + return `[${String(value2)}]`; + } + if (typeof value2 === "bigint") { + return `[BigInt: ${String(value2)}]`; + } + const objName = getConstructorName(value2); + if (/^HTML(\w*)Element$/.test(objName)) { + return `[HTMLElement: ${objName}]`; + } + return `[object ${objName}]`; + } catch (err) { + return `**non-serializable** (${err})`; + } +} +function getConstructorName(value2) { + const prototype = Object.getPrototypeOf(value2); + return prototype ? prototype.constructor.name : "null prototype"; +} +function utf8Length(value2) { + return ~-encodeURI(value2).split(/%..|./).length; +} +function jsonSize(value2) { + return utf8Length(JSON.stringify(value2)); +} + +// node_modules/@sentry/core/build/esm/utils-hoist/envelope.js +function createEnvelope(headers, items = []) { + return [headers, items]; +} +function addItemToEnvelope(envelope, newItem) { + const [headers, items] = envelope; + return [headers, [...items, newItem]]; +} +function forEachEnvelopeItem(envelope, callback) { + const envelopeItems = envelope[1]; + for (const envelopeItem of envelopeItems) { + const envelopeItemType = envelopeItem[0].type; + const result = callback(envelopeItem, envelopeItemType); + if (result) { + return true; + } + } + return false; +} +function encodeUTF8(input) { + return GLOBAL_OBJ.__SENTRY__ && GLOBAL_OBJ.__SENTRY__.encodePolyfill ? GLOBAL_OBJ.__SENTRY__.encodePolyfill(input) : new TextEncoder().encode(input); +} +function serializeEnvelope(envelope) { + const [envHeaders, items] = envelope; + let parts = JSON.stringify(envHeaders); + function append(next) { + if (typeof parts === "string") { + parts = typeof next === "string" ? parts + next : [encodeUTF8(parts), next]; + } else { + parts.push(typeof next === "string" ? encodeUTF8(next) : next); + } + } + for (const item of items) { + const [itemHeaders, payload] = item; + append(` +${JSON.stringify(itemHeaders)} +`); + if (typeof payload === "string" || payload instanceof Uint8Array) { + append(payload); + } else { + let stringifiedPayload; + try { + stringifiedPayload = JSON.stringify(payload); + } catch (e) { + stringifiedPayload = JSON.stringify(normalize3(payload)); + } + append(stringifiedPayload); + } + } + return typeof parts === "string" ? parts : concatBuffers(parts); +} +function concatBuffers(buffers) { + const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0); + const merged = new Uint8Array(totalLength); + let offset = 0; + for (const buffer of buffers) { + merged.set(buffer, offset); + offset += buffer.length; + } + return merged; +} +function createAttachmentEnvelopeItem(attachment) { + const buffer = typeof attachment.data === "string" ? encodeUTF8(attachment.data) : attachment.data; + return [ + dropUndefinedKeys({ + type: "attachment", + length: buffer.length, + filename: attachment.filename, + content_type: attachment.contentType, + attachment_type: attachment.attachmentType + }), + buffer + ]; +} +var ITEM_TYPE_TO_DATA_CATEGORY_MAP = { + session: "session", + sessions: "session", + attachment: "attachment", + transaction: "transaction", + event: "error", + client_report: "internal", + user_report: "default", + profile: "profile", + profile_chunk: "profile", + replay_event: "replay", + replay_recording: "replay", + check_in: "monitor", + feedback: "feedback", + span: "span", + statsd: "metric_bucket", + raw_security: "security" +}; +function envelopeItemTypeToDataCategory(type) { + return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type]; +} +function getSdkMetadataForEnvelopeHeader(metadataOrEvent) { + if (!metadataOrEvent || !metadataOrEvent.sdk) { + return; + } + const { name: name2, version } = metadataOrEvent.sdk; + return { name: name2, version }; +} +function createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn) { + const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext; + return { + event_id: event.event_id, + sent_at: new Date().toISOString(), + ...sdkInfo && { sdk: sdkInfo }, + ...!!tunnel && dsn && { dsn: dsnToString(dsn) }, + ...dynamicSamplingContext && { + trace: dropUndefinedKeys({ ...dynamicSamplingContext }) + } + }; +} + +// node_modules/@sentry/core/build/esm/envelope.js +function enhanceEventWithSdkInfo(event, sdkInfo) { + if (!sdkInfo) { + return event; + } + event.sdk = event.sdk || {}; + event.sdk.name = event.sdk.name || sdkInfo.name; + event.sdk.version = event.sdk.version || sdkInfo.version; + event.sdk.integrations = [...event.sdk.integrations || [], ...sdkInfo.integrations || []]; + event.sdk.packages = [...event.sdk.packages || [], ...sdkInfo.packages || []]; + return event; +} +function createSessionEnvelope(session, dsn, metadata, tunnel) { + const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); + const envelopeHeaders = { + sent_at: new Date().toISOString(), + ...sdkInfo && { sdk: sdkInfo }, + ...!!tunnel && dsn && { dsn: dsnToString(dsn) } + }; + const envelopeItem = "aggregates" in session ? [{ type: "sessions" }, session] : [{ type: "session" }, session.toJSON()]; + return createEnvelope(envelopeHeaders, [envelopeItem]); +} +function createEventEnvelope(event, dsn, metadata, tunnel) { + const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata); + const eventType = event.type && event.type !== "replay_event" ? event.type : "event"; + enhanceEventWithSdkInfo(event, metadata && metadata.sdk); + const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn); + delete event.sdkProcessingMetadata; + const eventItem = [{ type: eventType }, event]; + return createEnvelope(envelopeHeaders, [eventItem]); +} + +// node_modules/@sentry/core/build/esm/eventProcessors.js +function notifyEventProcessors(processors, event, hint, index2 = 0) { + return new SyncPromise((resolve, reject2) => { + const processor = processors[index2]; + if (event === null || typeof processor !== "function") { + resolve(event); + } else { + const result = processor({ ...event }, hint); + DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor "${processor.id}" dropped event`); + if (isThenable(result)) { + result.then((final) => notifyEventProcessors(processors, final, hint, index2 + 1).then(resolve)).then(null, reject2); + } else { + notifyEventProcessors(processors, result, hint, index2 + 1).then(resolve).then(null, reject2); + } + } + }); +} + +// node_modules/@sentry/core/build/esm/utils-hoist/debug-ids.js +var parsedStackResults; +var lastKeysCount; +var cachedFilenameDebugIds; +function getFilenameToDebugIdMap(stackParser) { + const debugIdMap = GLOBAL_OBJ._sentryDebugIds; + if (!debugIdMap) { + return {}; + } + const debugIdKeys = Object.keys(debugIdMap); + if (cachedFilenameDebugIds && debugIdKeys.length === lastKeysCount) { + return cachedFilenameDebugIds; + } + lastKeysCount = debugIdKeys.length; + cachedFilenameDebugIds = debugIdKeys.reduce((acc, stackKey) => { + if (!parsedStackResults) { + parsedStackResults = {}; + } + const result = parsedStackResults[stackKey]; + if (result) { + acc[result[0]] = result[1]; + } else { + const parsedStack = stackParser(stackKey); + for (let i = parsedStack.length - 1;i >= 0; i--) { + const stackFrame = parsedStack[i]; + const filename = stackFrame && stackFrame.filename; + const debugId = debugIdMap[stackKey]; + if (filename && debugId) { + acc[filename] = debugId; + parsedStackResults[stackKey] = [filename, debugId]; + break; + } + } + } + return acc; + }, {}); + return cachedFilenameDebugIds; +} + +// node_modules/@sentry/core/build/esm/utils/applyScopeDataToEvent.js +function applyScopeDataToEvent(event, data2) { + const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data2; + applyDataToEvent(event, data2); + if (span) { + applySpanToEvent(event, span); + } + applyFingerprintToEvent(event, fingerprint); + applyBreadcrumbsToEvent(event, breadcrumbs); + applySdkMetadataToEvent(event, sdkProcessingMetadata); +} +function mergeScopeData(data2, mergeData) { + const { + extra, + tags, + user, + contexts, + level, + sdkProcessingMetadata, + breadcrumbs, + fingerprint, + eventProcessors, + attachments, + propagationContext, + transactionName, + span + } = mergeData; + mergeAndOverwriteScopeData(data2, "extra", extra); + mergeAndOverwriteScopeData(data2, "tags", tags); + mergeAndOverwriteScopeData(data2, "user", user); + mergeAndOverwriteScopeData(data2, "contexts", contexts); + data2.sdkProcessingMetadata = merge2(data2.sdkProcessingMetadata, sdkProcessingMetadata, 2); + if (level) { + data2.level = level; + } + if (transactionName) { + data2.transactionName = transactionName; + } + if (span) { + data2.span = span; + } + if (breadcrumbs.length) { + data2.breadcrumbs = [...data2.breadcrumbs, ...breadcrumbs]; + } + if (fingerprint.length) { + data2.fingerprint = [...data2.fingerprint, ...fingerprint]; + } + if (eventProcessors.length) { + data2.eventProcessors = [...data2.eventProcessors, ...eventProcessors]; + } + if (attachments.length) { + data2.attachments = [...data2.attachments, ...attachments]; + } + data2.propagationContext = { ...data2.propagationContext, ...propagationContext }; +} +function mergeAndOverwriteScopeData(data2, prop, mergeVal) { + data2[prop] = merge2(data2[prop], mergeVal, 1); +} +function applyDataToEvent(event, data2) { + const { extra, tags, user, contexts, level, transactionName } = data2; + const cleanedExtra = dropUndefinedKeys(extra); + if (cleanedExtra && Object.keys(cleanedExtra).length) { + event.extra = { ...cleanedExtra, ...event.extra }; + } + const cleanedTags = dropUndefinedKeys(tags); + if (cleanedTags && Object.keys(cleanedTags).length) { + event.tags = { ...cleanedTags, ...event.tags }; + } + const cleanedUser = dropUndefinedKeys(user); + if (cleanedUser && Object.keys(cleanedUser).length) { + event.user = { ...cleanedUser, ...event.user }; + } + const cleanedContexts = dropUndefinedKeys(contexts); + if (cleanedContexts && Object.keys(cleanedContexts).length) { + event.contexts = { ...cleanedContexts, ...event.contexts }; + } + if (level) { + event.level = level; + } + if (transactionName && event.type !== "transaction") { + event.transaction = transactionName; + } +} +function applyBreadcrumbsToEvent(event, breadcrumbs) { + const mergedBreadcrumbs = [...event.breadcrumbs || [], ...breadcrumbs]; + event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined; +} +function applySdkMetadataToEvent(event, sdkProcessingMetadata) { + event.sdkProcessingMetadata = { + ...event.sdkProcessingMetadata, + ...sdkProcessingMetadata + }; +} +function applySpanToEvent(event, span) { + event.contexts = { + trace: spanToTraceContext(span), + ...event.contexts + }; + event.sdkProcessingMetadata = { + dynamicSamplingContext: getDynamicSamplingContextFromSpan(span), + ...event.sdkProcessingMetadata + }; + const rootSpan = getRootSpan(span); + const transactionName = spanToJSON(rootSpan).description; + if (transactionName && !event.transaction && event.type === "transaction") { + event.transaction = transactionName; + } +} +function applyFingerprintToEvent(event, fingerprint) { + event.fingerprint = event.fingerprint ? Array.isArray(event.fingerprint) ? event.fingerprint : [event.fingerprint] : []; + if (fingerprint) { + event.fingerprint = event.fingerprint.concat(fingerprint); + } + if (event.fingerprint && !event.fingerprint.length) { + delete event.fingerprint; + } +} + +// node_modules/@sentry/core/build/esm/utils/prepareEvent.js +function prepareEvent(options, event, hint, scope, client, isolationScope) { + const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = options; + const prepared = { + ...event, + event_id: event.event_id || hint.event_id || uuid4(), + timestamp: event.timestamp || dateTimestampInSeconds() + }; + const integrations = hint.integrations || options.integrations.map((i) => i.name); + applyClientOptions(prepared, options); + applyIntegrationsMetadata(prepared, integrations); + if (client) { + client.emit("applyFrameMetadata", event); + } + if (event.type === undefined) { + applyDebugIds(prepared, options.stackParser); + } + const finalScope = getFinalScope(scope, hint.captureContext); + if (hint.mechanism) { + addExceptionMechanism(prepared, hint.mechanism); + } + const clientEventProcessors = client ? client.getEventProcessors() : []; + const data2 = getGlobalScope().getScopeData(); + if (isolationScope) { + const isolationData = isolationScope.getScopeData(); + mergeScopeData(data2, isolationData); + } + if (finalScope) { + const finalScopeData = finalScope.getScopeData(); + mergeScopeData(data2, finalScopeData); + } + const attachments = [...hint.attachments || [], ...data2.attachments]; + if (attachments.length) { + hint.attachments = attachments; + } + applyScopeDataToEvent(prepared, data2); + const eventProcessors = [ + ...clientEventProcessors, + ...data2.eventProcessors + ]; + const result = notifyEventProcessors(eventProcessors, prepared, hint); + return result.then((evt) => { + if (evt) { + applyDebugMeta(evt); + } + if (typeof normalizeDepth === "number" && normalizeDepth > 0) { + return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth); + } + return evt; + }); +} +function applyClientOptions(event, options) { + const { environment, release, dist, maxValueLength = 250 } = options; + event.environment = event.environment || environment || DEFAULT_ENVIRONMENT; + if (!event.release && release) { + event.release = release; + } + if (!event.dist && dist) { + event.dist = dist; + } + if (event.message) { + event.message = truncate(event.message, maxValueLength); + } + const exception = event.exception && event.exception.values && event.exception.values[0]; + if (exception && exception.value) { + exception.value = truncate(exception.value, maxValueLength); + } + const request = event.request; + if (request && request.url) { + request.url = truncate(request.url, maxValueLength); + } +} +function applyDebugIds(event, stackParser) { + const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser); + try { + event.exception.values.forEach((exception) => { + exception.stacktrace.frames.forEach((frame) => { + if (filenameDebugIdMap && frame.filename) { + frame.debug_id = filenameDebugIdMap[frame.filename]; + } + }); + }); + } catch (e) { + } +} +function applyDebugMeta(event) { + const filenameDebugIdMap = {}; + try { + event.exception.values.forEach((exception) => { + exception.stacktrace.frames.forEach((frame) => { + if (frame.debug_id) { + if (frame.abs_path) { + filenameDebugIdMap[frame.abs_path] = frame.debug_id; + } else if (frame.filename) { + filenameDebugIdMap[frame.filename] = frame.debug_id; + } + delete frame.debug_id; + } + }); + }); + } catch (e) { + } + if (Object.keys(filenameDebugIdMap).length === 0) { + return; + } + event.debug_meta = event.debug_meta || {}; + event.debug_meta.images = event.debug_meta.images || []; + const images = event.debug_meta.images; + Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => { + images.push({ + type: "sourcemap", + code_file: filename, + debug_id + }); + }); +} +function applyIntegrationsMetadata(event, integrationNames) { + if (integrationNames.length > 0) { + event.sdk = event.sdk || {}; + event.sdk.integrations = [...event.sdk.integrations || [], ...integrationNames]; + } +} +function normalizeEvent(event, depth, maxBreadth) { + if (!event) { + return null; + } + const normalized = { + ...event, + ...event.breadcrumbs && { + breadcrumbs: event.breadcrumbs.map((b3) => ({ + ...b3, + ...b3.data && { + data: normalize3(b3.data, depth, maxBreadth) + } + })) + }, + ...event.user && { + user: normalize3(event.user, depth, maxBreadth) + }, + ...event.contexts && { + contexts: normalize3(event.contexts, depth, maxBreadth) + }, + ...event.extra && { + extra: normalize3(event.extra, depth, maxBreadth) + } + }; + if (event.contexts && event.contexts.trace && normalized.contexts) { + normalized.contexts.trace = event.contexts.trace; + if (event.contexts.trace.data) { + normalized.contexts.trace.data = normalize3(event.contexts.trace.data, depth, maxBreadth); + } + } + if (event.spans) { + normalized.spans = event.spans.map((span) => { + return { + ...span, + ...span.data && { + data: normalize3(span.data, depth, maxBreadth) + } + }; + }); + } + if (event.contexts && event.contexts.flags && normalized.contexts) { + normalized.contexts.flags = normalize3(event.contexts.flags, 3, maxBreadth); + } + return normalized; +} +function getFinalScope(scope, captureContext) { + if (!captureContext) { + return scope; + } + const finalScope = scope ? scope.clone() : new Scope; + finalScope.update(captureContext); + return finalScope; +} +function parseEventHintOrCaptureContext(hint) { + if (!hint) { + return; + } + if (hintIsScopeOrFunction(hint)) { + return { captureContext: hint }; + } + if (hintIsScopeContext(hint)) { + return { + captureContext: hint + }; + } + return hint; +} +function hintIsScopeOrFunction(hint) { + return hint instanceof Scope || typeof hint === "function"; +} +var captureContextKeys = [ + "user", + "level", + "extra", + "contexts", + "tags", + "fingerprint", + "requestSession", + "propagationContext" +]; +function hintIsScopeContext(hint) { + return Object.keys(hint).some((key2) => captureContextKeys.includes(key2)); +} + +// node_modules/@sentry/core/build/esm/exports.js +function captureException(exception, hint) { + return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint)); +} +function captureEvent(event, hint) { + return getCurrentScope().captureEvent(event, hint); +} +function startSession(context) { + const client = getClient(); + const isolationScope = getIsolationScope(); + const currentScope = getCurrentScope(); + const { release, environment = DEFAULT_ENVIRONMENT } = client && client.getOptions() || {}; + const { userAgent } = GLOBAL_OBJ.navigator || {}; + const session = makeSession({ + release, + environment, + user: currentScope.getUser() || isolationScope.getUser(), + ...userAgent && { userAgent }, + ...context + }); + const currentSession = isolationScope.getSession(); + if (currentSession && currentSession.status === "ok") { + updateSession(currentSession, { status: "exited" }); + } + endSession(); + isolationScope.setSession(session); + currentScope.setSession(session); + return session; +} +function endSession() { + const isolationScope = getIsolationScope(); + const currentScope = getCurrentScope(); + const session = currentScope.getSession() || isolationScope.getSession(); + if (session) { + closeSession(session); + } + _sendSessionUpdate(); + isolationScope.setSession(); + currentScope.setSession(); +} +function _sendSessionUpdate() { + const isolationScope = getIsolationScope(); + const currentScope = getCurrentScope(); + const client = getClient(); + const session = currentScope.getSession() || isolationScope.getSession(); + if (session && client) { + client.captureSession(session); + } +} +function captureSession(end = false) { + if (end) { + endSession(); + return; + } + _sendSessionUpdate(); +} +// node_modules/@sentry/core/build/esm/api.js +var SENTRY_API_VERSION = "7"; +function getBaseApiEndpoint(dsn) { + const protocol = dsn.protocol ? `${dsn.protocol}:` : ""; + const port = dsn.port ? `:${dsn.port}` : ""; + return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ""}/api/`; +} +function _getIngestEndpoint(dsn) { + return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`; +} +function _encodedAuth(dsn, sdkInfo) { + const params = { + sentry_version: SENTRY_API_VERSION + }; + if (dsn.publicKey) { + params.sentry_key = dsn.publicKey; + } + if (sdkInfo) { + params.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`; + } + return new URLSearchParams(params).toString(); +} +function getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) { + return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`; +} + +// node_modules/@sentry/core/build/esm/integration.js +var installedIntegrations = []; +function filterDuplicates(integrations) { + const integrationsByName = {}; + integrations.forEach((currentInstance) => { + const { name: name2 } = currentInstance; + const existingInstance = integrationsByName[name2]; + if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) { + return; + } + integrationsByName[name2] = currentInstance; + }); + return Object.values(integrationsByName); +} +function getIntegrationsToSetup(options) { + const defaultIntegrations = options.defaultIntegrations || []; + const userIntegrations = options.integrations; + defaultIntegrations.forEach((integration) => { + integration.isDefaultInstance = true; + }); + let integrations; + if (Array.isArray(userIntegrations)) { + integrations = [...defaultIntegrations, ...userIntegrations]; + } else if (typeof userIntegrations === "function") { + const resolvedUserIntegrations = userIntegrations(defaultIntegrations); + integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations]; + } else { + integrations = defaultIntegrations; + } + const finalIntegrations = filterDuplicates(integrations); + const debugIndex = finalIntegrations.findIndex((integration) => integration.name === "Debug"); + if (debugIndex > -1) { + const [debugInstance] = finalIntegrations.splice(debugIndex, 1); + finalIntegrations.push(debugInstance); + } + return finalIntegrations; +} +function setupIntegrations(client, integrations) { + const integrationIndex = {}; + integrations.forEach((integration) => { + if (integration) { + setupIntegration(client, integration, integrationIndex); + } + }); + return integrationIndex; +} +function afterSetupIntegrations(client, integrations) { + for (const integration of integrations) { + if (integration && integration.afterAllSetup) { + integration.afterAllSetup(client); + } + } +} +function setupIntegration(client, integration, integrationIndex) { + if (integrationIndex[integration.name]) { + DEBUG_BUILD && logger.log(`Integration skipped because it was already installed: ${integration.name}`); + return; + } + integrationIndex[integration.name] = integration; + if (installedIntegrations.indexOf(integration.name) === -1 && typeof integration.setupOnce === "function") { + integration.setupOnce(); + installedIntegrations.push(integration.name); + } + if (integration.setup && typeof integration.setup === "function") { + integration.setup(client); + } + if (typeof integration.preprocessEvent === "function") { + const callback = integration.preprocessEvent.bind(integration); + client.on("preprocessEvent", (event, hint) => callback(event, hint, client)); + } + if (typeof integration.processEvent === "function") { + const callback = integration.processEvent.bind(integration); + const processor = Object.assign((event, hint) => callback(event, hint, client), { + id: integration.name + }); + client.addEventProcessor(processor); + } + DEBUG_BUILD && logger.log(`Integration installed: ${integration.name}`); +} +function defineIntegration(fn) { + return fn; +} + +// node_modules/@sentry/core/build/esm/utils-hoist/clientreport.js +function createClientReportEnvelope(discarded_events, dsn, timestamp) { + const clientReportItem = [ + { type: "client_report" }, + { + timestamp: timestamp || dateTimestampInSeconds(), + discarded_events + } + ]; + return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]); +} + +// node_modules/@sentry/core/build/esm/utils-hoist/error.js +class SentryError extends Error { + constructor(message, logLevel = "warn") { + super(message); + this.message = message; + this.logLevel = logLevel; + } +} + +// node_modules/@sentry/core/build/esm/baseclient.js +var ALREADY_SEEN_ERROR = "Not capturing exception because it's already been captured."; + +class BaseClient { + constructor(options) { + this._options = options; + this._integrations = {}; + this._numProcessing = 0; + this._outcomes = {}; + this._hooks = {}; + this._eventProcessors = []; + if (options.dsn) { + this._dsn = makeDsn(options.dsn); + } else { + DEBUG_BUILD && logger.warn("No DSN provided, client will not send events."); + } + if (this._dsn) { + const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options.tunnel, options._metadata ? options._metadata.sdk : undefined); + this._transport = options.transport({ + tunnel: this._options.tunnel, + recordDroppedEvent: this.recordDroppedEvent.bind(this), + ...options.transportOptions, + url + }); + } + const tracingOptions = ["enableTracing", "tracesSampleRate", "tracesSampler"]; + const undefinedOption = tracingOptions.find((option) => (option in options) && options[option] == undefined); + if (undefinedOption) { + consoleSandbox(() => { + console.warn(`[Sentry] Deprecation warning: \`${undefinedOption}\` is set to undefined, which leads to tracing being enabled. In v9, a value of \`undefined\` will result in tracing being disabled.`); + }); + } + } + captureException(exception, hint, scope) { + const eventId = uuid4(); + if (checkOrSetAlreadyCaught(exception)) { + DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR); + return eventId; + } + const hintWithEventId = { + event_id: eventId, + ...hint + }; + this._process(this.eventFromException(exception, hintWithEventId).then((event) => this._captureEvent(event, hintWithEventId, scope))); + return hintWithEventId.event_id; + } + captureMessage(message, level, hint, currentScope) { + const hintWithEventId = { + event_id: uuid4(), + ...hint + }; + const eventMessage = isParameterizedString(message) ? message : String(message); + const promisedEvent = isPrimitive(message) ? this.eventFromMessage(eventMessage, level, hintWithEventId) : this.eventFromException(message, hintWithEventId); + this._process(promisedEvent.then((event) => this._captureEvent(event, hintWithEventId, currentScope))); + return hintWithEventId.event_id; + } + captureEvent(event, hint, currentScope) { + const eventId = uuid4(); + if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) { + DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR); + return eventId; + } + const hintWithEventId = { + event_id: eventId, + ...hint + }; + const sdkProcessingMetadata = event.sdkProcessingMetadata || {}; + const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope; + this._process(this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope)); + return hintWithEventId.event_id; + } + captureSession(session) { + if (!(typeof session.release === "string")) { + DEBUG_BUILD && logger.warn("Discarded session because of missing or non-string release"); + } else { + this.sendSession(session); + updateSession(session, { init: false }); + } + } + getDsn() { + return this._dsn; + } + getOptions() { + return this._options; + } + getSdkMetadata() { + return this._options._metadata; + } + getTransport() { + return this._transport; + } + flush(timeout) { + const transport = this._transport; + if (transport) { + this.emit("flush"); + return this._isClientDoneProcessing(timeout).then((clientFinished) => { + return transport.flush(timeout).then((transportFlushed) => clientFinished && transportFlushed); + }); + } else { + return resolvedSyncPromise(true); + } + } + close(timeout) { + return this.flush(timeout).then((result) => { + this.getOptions().enabled = false; + this.emit("close"); + return result; + }); + } + getEventProcessors() { + return this._eventProcessors; + } + addEventProcessor(eventProcessor) { + this._eventProcessors.push(eventProcessor); + } + init() { + if (this._isEnabled() || this._options.integrations.some(({ name: name2 }) => name2.startsWith("Spotlight"))) { + this._setupIntegrations(); + } + } + getIntegrationByName(integrationName) { + return this._integrations[integrationName]; + } + addIntegration(integration) { + const isAlreadyInstalled = this._integrations[integration.name]; + setupIntegration(this, integration, this._integrations); + if (!isAlreadyInstalled) { + afterSetupIntegrations(this, [integration]); + } + } + sendEvent(event, hint = {}) { + this.emit("beforeSendEvent", event, hint); + let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel); + for (const attachment of hint.attachments || []) { + env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment)); + } + const promise = this.sendEnvelope(env); + if (promise) { + promise.then((sendResponse) => this.emit("afterSendEvent", event, sendResponse), null); + } + } + sendSession(session) { + const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel); + this.sendEnvelope(env); + } + recordDroppedEvent(reason, category, eventOrCount) { + if (this._options.sendClientReports) { + const count = typeof eventOrCount === "number" ? eventOrCount : 1; + const key2 = `${reason}:${category}`; + DEBUG_BUILD && logger.log(`Recording outcome: "${key2}"${count > 1 ? ` (${count} times)` : ""}`); + this._outcomes[key2] = (this._outcomes[key2] || 0) + count; + } + } + on(hook, callback) { + const hooks = this._hooks[hook] = this._hooks[hook] || []; + hooks.push(callback); + return () => { + const cbIndex = hooks.indexOf(callback); + if (cbIndex > -1) { + hooks.splice(cbIndex, 1); + } + }; + } + emit(hook, ...rest) { + const callbacks = this._hooks[hook]; + if (callbacks) { + callbacks.forEach((callback) => callback(...rest)); + } + } + sendEnvelope(envelope) { + this.emit("beforeEnvelope", envelope); + if (this._isEnabled() && this._transport) { + return this._transport.send(envelope).then(null, (reason) => { + DEBUG_BUILD && logger.error("Error while sending envelope:", reason); + return reason; + }); + } + DEBUG_BUILD && logger.error("Transport disabled"); + return resolvedSyncPromise({}); + } + _setupIntegrations() { + const { integrations } = this._options; + this._integrations = setupIntegrations(this, integrations); + afterSetupIntegrations(this, integrations); + } + _updateSessionFromEvent(session, event) { + let crashed = event.level === "fatal"; + let errored = false; + const exceptions = event.exception && event.exception.values; + if (exceptions) { + errored = true; + for (const ex of exceptions) { + const mechanism = ex.mechanism; + if (mechanism && mechanism.handled === false) { + crashed = true; + break; + } + } + } + const sessionNonTerminal = session.status === "ok"; + const shouldUpdateAndSend = sessionNonTerminal && session.errors === 0 || sessionNonTerminal && crashed; + if (shouldUpdateAndSend) { + updateSession(session, { + ...crashed && { status: "crashed" }, + errors: session.errors || Number(errored || crashed) + }); + this.captureSession(session); + } + } + _isClientDoneProcessing(timeout) { + return new SyncPromise((resolve) => { + let ticked = 0; + const tick = 1; + const interval = setInterval(() => { + if (this._numProcessing == 0) { + clearInterval(interval); + resolve(true); + } else { + ticked += tick; + if (timeout && ticked >= timeout) { + clearInterval(interval); + resolve(false); + } + } + }, tick); + }); + } + _isEnabled() { + return this.getOptions().enabled !== false && this._transport !== undefined; + } + _prepareEvent(event, hint, currentScope = getCurrentScope(), isolationScope = getIsolationScope()) { + const options = this.getOptions(); + const integrations = Object.keys(this._integrations); + if (!hint.integrations && integrations.length > 0) { + hint.integrations = integrations; + } + this.emit("preprocessEvent", event, hint); + if (!event.type) { + isolationScope.setLastEventId(event.event_id || hint.event_id); + } + return prepareEvent(options, event, hint, currentScope, this, isolationScope).then((evt) => { + if (evt === null) { + return evt; + } + evt.contexts = { + trace: getTraceContextFromScope(currentScope), + ...evt.contexts + }; + const dynamicSamplingContext = getDynamicSamplingContextFromScope(this, currentScope); + evt.sdkProcessingMetadata = { + dynamicSamplingContext, + ...evt.sdkProcessingMetadata + }; + return evt; + }); + } + _captureEvent(event, hint = {}, scope) { + return this._processEvent(event, hint, scope).then((finalEvent) => { + return finalEvent.event_id; + }, (reason) => { + if (DEBUG_BUILD) { + if (reason instanceof SentryError && reason.logLevel === "log") { + logger.log(reason.message); + } else { + logger.warn(reason); + } + } + return; + }); + } + _processEvent(event, hint, currentScope) { + const options = this.getOptions(); + const { sampleRate } = options; + const isTransaction = isTransactionEvent(event); + const isError2 = isErrorEvent2(event); + const eventType = event.type || "error"; + const beforeSendLabel = `before send for type \`${eventType}\``; + const parsedSampleRate = typeof sampleRate === "undefined" ? undefined : parseSampleRate(sampleRate); + if (isError2 && typeof parsedSampleRate === "number" && Math.random() > parsedSampleRate) { + this.recordDroppedEvent("sample_rate", "error", event); + return rejectedSyncPromise(new SentryError(`Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`, "log")); + } + const dataCategory = eventType === "replay_event" ? "replay" : eventType; + const sdkProcessingMetadata = event.sdkProcessingMetadata || {}; + const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope; + return this._prepareEvent(event, hint, currentScope, capturedSpanIsolationScope).then((prepared) => { + if (prepared === null) { + this.recordDroppedEvent("event_processor", dataCategory, event); + throw new SentryError("An event processor returned `null`, will not send event.", "log"); + } + const isInternalException = hint.data && hint.data.__sentry__ === true; + if (isInternalException) { + return prepared; + } + const result = processBeforeSend(this, options, prepared, hint); + return _validateBeforeSendResult(result, beforeSendLabel); + }).then((processedEvent) => { + if (processedEvent === null) { + this.recordDroppedEvent("before_send", dataCategory, event); + if (isTransaction) { + const spans = event.spans || []; + const spanCount = 1 + spans.length; + this.recordDroppedEvent("before_send", "span", spanCount); + } + throw new SentryError(`${beforeSendLabel} returned \`null\`, will not send event.`, "log"); + } + const session = currentScope && currentScope.getSession(); + if (!isTransaction && session) { + this._updateSessionFromEvent(session, processedEvent); + } + if (isTransaction) { + const spanCountBefore = processedEvent.sdkProcessingMetadata && processedEvent.sdkProcessingMetadata.spanCountBeforeProcessing || 0; + const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0; + const droppedSpanCount = spanCountBefore - spanCountAfter; + if (droppedSpanCount > 0) { + this.recordDroppedEvent("before_send", "span", droppedSpanCount); + } + } + const transactionInfo = processedEvent.transaction_info; + if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) { + const source = "custom"; + processedEvent.transaction_info = { + ...transactionInfo, + source + }; + } + this.sendEvent(processedEvent, hint); + return processedEvent; + }).then(null, (reason) => { + if (reason instanceof SentryError) { + throw reason; + } + this.captureException(reason, { + data: { + __sentry__: true + }, + originalException: reason + }); + throw new SentryError(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event. +Reason: ${reason}`); + }); + } + _process(promise) { + this._numProcessing++; + promise.then((value2) => { + this._numProcessing--; + return value2; + }, (reason) => { + this._numProcessing--; + return reason; + }); + } + _clearOutcomes() { + const outcomes = this._outcomes; + this._outcomes = {}; + return Object.entries(outcomes).map(([key2, quantity]) => { + const [reason, category] = key2.split(":"); + return { + reason, + category, + quantity + }; + }); + } + _flushOutcomes() { + DEBUG_BUILD && logger.log("Flushing outcomes..."); + const outcomes = this._clearOutcomes(); + if (outcomes.length === 0) { + DEBUG_BUILD && logger.log("No outcomes to send"); + return; + } + if (!this._dsn) { + DEBUG_BUILD && logger.log("No dsn provided, will not send outcomes"); + return; + } + DEBUG_BUILD && logger.log("Sending outcomes:", outcomes); + const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn)); + this.sendEnvelope(envelope); + } +} +function _validateBeforeSendResult(beforeSendResult, beforeSendLabel) { + const invalidValueError = `${beforeSendLabel} must return \`null\` or a valid event.`; + if (isThenable(beforeSendResult)) { + return beforeSendResult.then((event) => { + if (!isPlainObject(event) && event !== null) { + throw new SentryError(invalidValueError); + } + return event; + }, (e) => { + throw new SentryError(`${beforeSendLabel} rejected with ${e}`); + }); + } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) { + throw new SentryError(invalidValueError); + } + return beforeSendResult; +} +function processBeforeSend(client, options, event, hint) { + const { beforeSend, beforeSendTransaction, beforeSendSpan } = options; + if (isErrorEvent2(event) && beforeSend) { + return beforeSend(event, hint); + } + if (isTransactionEvent(event)) { + if (event.spans && beforeSendSpan) { + const processedSpans = []; + for (const span of event.spans) { + const processedSpan = beforeSendSpan(span); + if (processedSpan) { + processedSpans.push(processedSpan); + } else { + showSpanDropWarning(); + client.recordDroppedEvent("before_send", "span"); + } + } + event.spans = processedSpans; + } + if (beforeSendTransaction) { + if (event.spans) { + const spanCountBefore = event.spans.length; + event.sdkProcessingMetadata = { + ...event.sdkProcessingMetadata, + spanCountBeforeProcessing: spanCountBefore + }; + } + return beforeSendTransaction(event, hint); + } + } + return event; +} +function isErrorEvent2(event) { + return event.type === undefined; +} +function isTransactionEvent(event) { + return event.type === "transaction"; +} +// node_modules/@sentry/core/build/esm/sdk.js +function initAndBind(clientClass, options) { + if (options.debug === true) { + if (DEBUG_BUILD) { + logger.enable(); + } else { + consoleSandbox(() => { + console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle."); + }); + } + } + const scope = getCurrentScope(); + scope.update(options.initialScope); + const client = new clientClass(options); + setCurrentClient(client); + client.init(); + return client; +} +function setCurrentClient(client) { + getCurrentScope().setClient(client); +} +// node_modules/@sentry/core/build/esm/utils-hoist/promisebuffer.js +function makePromiseBuffer(limit) { + const buffer = []; + function isReady() { + return limit === undefined || buffer.length < limit; + } + function remove(task) { + return buffer.splice(buffer.indexOf(task), 1)[0] || Promise.resolve(undefined); + } + function add2(taskProducer) { + if (!isReady()) { + return rejectedSyncPromise(new SentryError("Not adding Promise because buffer limit was reached.")); + } + const task = taskProducer(); + if (buffer.indexOf(task) === -1) { + buffer.push(task); + } + task.then(() => remove(task)).then(null, () => remove(task).then(null, () => { + })); + return task; + } + function drain(timeout) { + return new SyncPromise((resolve, reject2) => { + let counter = buffer.length; + if (!counter) { + return resolve(true); + } + const capturedSetTimeout = setTimeout(() => { + if (timeout && timeout > 0) { + resolve(false); + } + }, timeout); + buffer.forEach((item) => { + resolvedSyncPromise(item).then(() => { + if (!--counter) { + clearTimeout(capturedSetTimeout); + resolve(true); + } + }, reject2); + }); + }); + } + return { + $: buffer, + add: add2, + drain + }; +} + +// node_modules/@sentry/core/build/esm/utils-hoist/ratelimit.js +var DEFAULT_RETRY_AFTER = 60 * 1000; +function parseRetryAfterHeader(header, now2 = Date.now()) { + const headerDelay = parseInt(`${header}`, 10); + if (!isNaN(headerDelay)) { + return headerDelay * 1000; + } + const headerDate = Date.parse(`${header}`); + if (!isNaN(headerDate)) { + return headerDate - now2; + } + return DEFAULT_RETRY_AFTER; +} +function disabledUntil(limits, dataCategory) { + return limits[dataCategory] || limits.all || 0; +} +function isRateLimited(limits, dataCategory, now2 = Date.now()) { + return disabledUntil(limits, dataCategory) > now2; +} +function updateRateLimits(limits, { statusCode, headers }, now2 = Date.now()) { + const updatedRateLimits = { + ...limits + }; + const rateLimitHeader = headers && headers["x-sentry-rate-limits"]; + const retryAfterHeader = headers && headers["retry-after"]; + if (rateLimitHeader) { + for (const limit of rateLimitHeader.trim().split(",")) { + const [retryAfter, categories, , , namespaces] = limit.split(":", 5); + const headerDelay = parseInt(retryAfter, 10); + const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; + if (!categories) { + updatedRateLimits.all = now2 + delay; + } else { + for (const category of categories.split(";")) { + if (category === "metric_bucket") { + if (!namespaces || namespaces.split(";").includes("custom")) { + updatedRateLimits[category] = now2 + delay; + } + } else { + updatedRateLimits[category] = now2 + delay; + } + } + } + } + } else if (retryAfterHeader) { + updatedRateLimits.all = now2 + parseRetryAfterHeader(retryAfterHeader, now2); + } else if (statusCode === 429) { + updatedRateLimits.all = now2 + 60 * 1000; + } + return updatedRateLimits; +} + +// node_modules/@sentry/core/build/esm/transports/base.js +var DEFAULT_TRANSPORT_BUFFER_SIZE = 64; +function createTransport(options, makeRequest, buffer = makePromiseBuffer(options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE)) { + let rateLimits = {}; + const flush = (timeout) => buffer.drain(timeout); + function send(envelope) { + const filteredEnvelopeItems = []; + forEachEnvelopeItem(envelope, (item, type) => { + const dataCategory = envelopeItemTypeToDataCategory(type); + if (isRateLimited(rateLimits, dataCategory)) { + const event = getEventForEnvelopeItem(item, type); + options.recordDroppedEvent("ratelimit_backoff", dataCategory, event); + } else { + filteredEnvelopeItems.push(item); + } + }); + if (filteredEnvelopeItems.length === 0) { + return resolvedSyncPromise({}); + } + const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems); + const recordEnvelopeLoss = (reason) => { + forEachEnvelopeItem(filteredEnvelope, (item, type) => { + const event = getEventForEnvelopeItem(item, type); + options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event); + }); + }; + const requestTask = () => makeRequest({ body: serializeEnvelope(filteredEnvelope) }).then((response) => { + if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) { + DEBUG_BUILD && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`); + } + rateLimits = updateRateLimits(rateLimits, response); + return response; + }, (error) => { + recordEnvelopeLoss("network_error"); + throw error; + }); + return buffer.add(requestTask).then((result) => result, (error) => { + if (error instanceof SentryError) { + DEBUG_BUILD && logger.error("Skipped sending event because buffer is full."); + recordEnvelopeLoss("queue_overflow"); + return resolvedSyncPromise({}); + } else { + throw error; + } + }); + } + return { + send, + flush + }; +} +function getEventForEnvelopeItem(item, type) { + if (type !== "event" && type !== "transaction") { + return; + } + return Array.isArray(item) ? item[1] : undefined; +} +// node_modules/@sentry/core/build/esm/utils/sdkMetadata.js +function applySdkMetadata(options, name2, names = [name2], source = "npm") { + const metadata = options._metadata || {}; + if (!metadata.sdk) { + metadata.sdk = { + name: `sentry.javascript.${name2}`, + packages: names.map((name3) => ({ + name: `${source}:@sentry/${name3}`, + version: SDK_VERSION + })), + version: SDK_VERSION + }; + } + options._metadata = metadata; +} +// node_modules/@sentry/core/build/esm/breadcrumbs.js +var DEFAULT_BREADCRUMBS = 100; +function addBreadcrumb(breadcrumb, hint) { + const client = getClient(); + const isolationScope = getIsolationScope(); + if (!client) + return; + const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions(); + if (maxBreadcrumbs <= 0) + return; + const timestamp = dateTimestampInSeconds(); + const mergedBreadcrumb = { timestamp, ...breadcrumb }; + const finalBreadcrumb = beforeBreadcrumb ? consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) : mergedBreadcrumb; + if (finalBreadcrumb === null) + return; + if (client.emit) { + client.emit("beforeAddBreadcrumb", finalBreadcrumb, hint); + } + isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); +} +// node_modules/@sentry/core/build/esm/integrations/functiontostring.js +var originalFunctionToString; +var INTEGRATION_NAME = "FunctionToString"; +var SETUP_CLIENTS = new WeakMap; +var _functionToStringIntegration = () => { + return { + name: INTEGRATION_NAME, + setupOnce() { + originalFunctionToString = Function.prototype.toString; + try { + Function.prototype.toString = function(...args) { + const originalFunction = getOriginalFunction(this); + const context = SETUP_CLIENTS.has(getClient()) && originalFunction !== undefined ? originalFunction : this; + return originalFunctionToString.apply(context, args); + }; + } catch (e) { + } + }, + setup(client) { + SETUP_CLIENTS.set(client, true); + } + }; +}; +var functionToStringIntegration = defineIntegration(_functionToStringIntegration); +// node_modules/@sentry/core/build/esm/integrations/inboundfilters.js +var DEFAULT_IGNORE_ERRORS = [ + /^Script error\.?$/, + /^Javascript error: Script error\.? on line 0$/, + /^ResizeObserver loop completed with undelivered notifications.$/, + /^Cannot redefine property: googletag$/, + "undefined is not an object (evaluating 'a.L')", + `can't redefine non-configurable property "solana"`, + "vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)", + "Can't find variable: _AutofillCallbackHandler", + /^Non-Error promise rejection captured with value: Object Not Found Matching Id:\d+, MethodName:simulateEvent, ParamCount:\d+$/ +]; +var INTEGRATION_NAME2 = "InboundFilters"; +var _inboundFiltersIntegration = (options = {}) => { + return { + name: INTEGRATION_NAME2, + processEvent(event, _hint, client) { + const clientOptions = client.getOptions(); + const mergedOptions = _mergeOptions(options, clientOptions); + return _shouldDropEvent(event, mergedOptions) ? null : event; + } + }; +}; +var inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration); +function _mergeOptions(internalOptions = {}, clientOptions = {}) { + return { + allowUrls: [...internalOptions.allowUrls || [], ...clientOptions.allowUrls || []], + denyUrls: [...internalOptions.denyUrls || [], ...clientOptions.denyUrls || []], + ignoreErrors: [ + ...internalOptions.ignoreErrors || [], + ...clientOptions.ignoreErrors || [], + ...internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS + ], + ignoreTransactions: [...internalOptions.ignoreTransactions || [], ...clientOptions.ignoreTransactions || []], + ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true + }; +} +function _shouldDropEvent(event, options) { + if (options.ignoreInternal && _isSentryError(event)) { + DEBUG_BUILD && logger.warn(`Event dropped due to being internal Sentry Error. +Event: ${getEventDescription(event)}`); + return true; + } + if (_isIgnoredError(event, options.ignoreErrors)) { + DEBUG_BUILD && logger.warn(`Event dropped due to being matched by \`ignoreErrors\` option. +Event: ${getEventDescription(event)}`); + return true; + } + if (_isUselessError(event)) { + DEBUG_BUILD && logger.warn(`Event dropped due to not having an error message, error type or stacktrace. +Event: ${getEventDescription(event)}`); + return true; + } + if (_isIgnoredTransaction(event, options.ignoreTransactions)) { + DEBUG_BUILD && logger.warn(`Event dropped due to being matched by \`ignoreTransactions\` option. +Event: ${getEventDescription(event)}`); + return true; + } + if (_isDeniedUrl(event, options.denyUrls)) { + DEBUG_BUILD && logger.warn(`Event dropped due to being matched by \`denyUrls\` option. +Event: ${getEventDescription(event)}. +Url: ${_getEventFilterUrl(event)}`); + return true; + } + if (!_isAllowedUrl(event, options.allowUrls)) { + DEBUG_BUILD && logger.warn(`Event dropped due to not being matched by \`allowUrls\` option. +Event: ${getEventDescription(event)}. +Url: ${_getEventFilterUrl(event)}`); + return true; + } + return false; +} +function _isIgnoredError(event, ignoreErrors) { + if (event.type || !ignoreErrors || !ignoreErrors.length) { + return false; + } + return _getPossibleEventMessages(event).some((message) => stringMatchesSomePattern(message, ignoreErrors)); +} +function _isIgnoredTransaction(event, ignoreTransactions) { + if (event.type !== "transaction" || !ignoreTransactions || !ignoreTransactions.length) { + return false; + } + const name2 = event.transaction; + return name2 ? stringMatchesSomePattern(name2, ignoreTransactions) : false; +} +function _isDeniedUrl(event, denyUrls) { + if (!denyUrls || !denyUrls.length) { + return false; + } + const url = _getEventFilterUrl(event); + return !url ? false : stringMatchesSomePattern(url, denyUrls); +} +function _isAllowedUrl(event, allowUrls) { + if (!allowUrls || !allowUrls.length) { + return true; + } + const url = _getEventFilterUrl(event); + return !url ? true : stringMatchesSomePattern(url, allowUrls); +} +function _getPossibleEventMessages(event) { + const possibleMessages = []; + if (event.message) { + possibleMessages.push(event.message); + } + let lastException; + try { + lastException = event.exception.values[event.exception.values.length - 1]; + } catch (e) { + } + if (lastException) { + if (lastException.value) { + possibleMessages.push(lastException.value); + if (lastException.type) { + possibleMessages.push(`${lastException.type}: ${lastException.value}`); + } + } + } + return possibleMessages; +} +function _isSentryError(event) { + try { + return event.exception.values[0].type === "SentryError"; + } catch (e) { + } + return false; +} +function _getLastValidUrl(frames2 = []) { + for (let i = frames2.length - 1;i >= 0; i--) { + const frame = frames2[i]; + if (frame && frame.filename !== "" && frame.filename !== "[native code]") { + return frame.filename || null; + } + } + return null; +} +function _getEventFilterUrl(event) { + try { + let frames2; + try { + frames2 = event.exception.values[0].stacktrace.frames; + } catch (e) { + } + return frames2 ? _getLastValidUrl(frames2) : null; + } catch (oO) { + DEBUG_BUILD && logger.error(`Cannot extract url for event ${getEventDescription(event)}`); + return null; + } +} +function _isUselessError(event) { + if (event.type) { + return false; + } + if (!event.exception || !event.exception.values || event.exception.values.length === 0) { + return false; + } + return !event.message && !event.exception.values.some((value2) => value2.stacktrace || value2.type && value2.type !== "Error" || value2.value); +} +// node_modules/@sentry/core/build/esm/utils-hoist/aggregate-errors.js +function applyAggregateErrorsToEvent(exceptionFromErrorImplementation, parser, maxValueLimit = 250, key2, limit, event, hint) { + if (!event.exception || !event.exception.values || !hint || !isInstanceOf(hint.originalException, Error)) { + return; + } + const originalException = event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined; + if (originalException) { + event.exception.values = truncateAggregateExceptions(aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, hint.originalException, key2, event.exception.values, originalException, 0), maxValueLimit); + } +} +function aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, error, key2, prevExceptions, exception, exceptionId) { + if (prevExceptions.length >= limit + 1) { + return prevExceptions; + } + let newExceptions = [...prevExceptions]; + if (isInstanceOf(error[key2], Error)) { + applyExceptionGroupFieldsForParentException(exception, exceptionId); + const newException = exceptionFromErrorImplementation(parser, error[key2]); + const newExceptionId = newExceptions.length; + applyExceptionGroupFieldsForChildException(newException, key2, newExceptionId, exceptionId); + newExceptions = aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, error[key2], key2, [newException, ...newExceptions], newException, newExceptionId); + } + if (Array.isArray(error.errors)) { + error.errors.forEach((childError, i) => { + if (isInstanceOf(childError, Error)) { + applyExceptionGroupFieldsForParentException(exception, exceptionId); + const newException = exceptionFromErrorImplementation(parser, childError); + const newExceptionId = newExceptions.length; + applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId); + newExceptions = aggregateExceptionsFromError(exceptionFromErrorImplementation, parser, limit, childError, key2, [newException, ...newExceptions], newException, newExceptionId); + } + }); + } + return newExceptions; +} +function applyExceptionGroupFieldsForParentException(exception, exceptionId) { + exception.mechanism = exception.mechanism || { type: "generic", handled: true }; + exception.mechanism = { + ...exception.mechanism, + ...exception.type === "AggregateError" && { is_exception_group: true }, + exception_id: exceptionId + }; +} +function applyExceptionGroupFieldsForChildException(exception, source, exceptionId, parentId) { + exception.mechanism = exception.mechanism || { type: "generic", handled: true }; + exception.mechanism = { + ...exception.mechanism, + type: "chained", + source, + exception_id: exceptionId, + parent_id: parentId + }; +} +function truncateAggregateExceptions(exceptions, maxValueLength) { + return exceptions.map((exception) => { + if (exception.value) { + exception.value = truncate(exception.value, maxValueLength); + } + return exception; + }); +} + +// node_modules/@sentry/core/build/esm/utils-hoist/url.js +function parseUrl(url) { + if (!url) { + return {}; + } + const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); + if (!match) { + return {}; + } + const query = match[6] || ""; + const fragment2 = match[8] || ""; + return { + host: match[4], + path: match[5], + protocol: match[2], + search: query, + hash: fragment2, + relative: match[5] + query + fragment2 + }; +} + +// node_modules/@sentry/core/build/esm/utils-hoist/instrument/console.js +function addConsoleInstrumentationHandler(handler) { + const type = "console"; + addHandler(type, handler); + maybeInstrument(type, instrumentConsole); +} +function instrumentConsole() { + if (!("console" in GLOBAL_OBJ)) { + return; + } + CONSOLE_LEVELS.forEach(function(level) { + if (!(level in GLOBAL_OBJ.console)) { + return; + } + fill2(GLOBAL_OBJ.console, level, function(originalConsoleMethod) { + originalConsoleMethods[level] = originalConsoleMethod; + return function(...args) { + const handlerData = { args, level }; + triggerHandlers("console", handlerData); + const log3 = originalConsoleMethods[level]; + log3 && log3.apply(GLOBAL_OBJ.console, args); + }; + }); + }); +} + +// node_modules/@sentry/core/build/esm/utils-hoist/severity.js +function severityLevelFromString(level) { + return level === "warn" ? "warning" : ["fatal", "error", "warning", "log", "info", "debug"].includes(level) ? level : "log"; +} + +// node_modules/@sentry/core/build/esm/integrations/dedupe.js +var INTEGRATION_NAME3 = "Dedupe"; +var _dedupeIntegration = () => { + let previousEvent; + return { + name: INTEGRATION_NAME3, + processEvent(currentEvent) { + if (currentEvent.type) { + return currentEvent; + } + try { + if (_shouldDropEvent2(currentEvent, previousEvent)) { + DEBUG_BUILD && logger.warn("Event dropped due to being a duplicate of previously captured event."); + return null; + } + } catch (_oO) { + } + return previousEvent = currentEvent; + } + }; +}; +var dedupeIntegration = defineIntegration(_dedupeIntegration); +function _shouldDropEvent2(currentEvent, previousEvent) { + if (!previousEvent) { + return false; + } + if (_isSameMessageEvent(currentEvent, previousEvent)) { + return true; + } + if (_isSameExceptionEvent(currentEvent, previousEvent)) { + return true; + } + return false; +} +function _isSameMessageEvent(currentEvent, previousEvent) { + const currentMessage = currentEvent.message; + const previousMessage = previousEvent.message; + if (!currentMessage && !previousMessage) { + return false; + } + if (currentMessage && !previousMessage || !currentMessage && previousMessage) { + return false; + } + if (currentMessage !== previousMessage) { + return false; + } + if (!_isSameFingerprint(currentEvent, previousEvent)) { + return false; + } + if (!_isSameStacktrace(currentEvent, previousEvent)) { + return false; + } + return true; +} +function _isSameExceptionEvent(currentEvent, previousEvent) { + const previousException = _getExceptionFromEvent(previousEvent); + const currentException = _getExceptionFromEvent(currentEvent); + if (!previousException || !currentException) { + return false; + } + if (previousException.type !== currentException.type || previousException.value !== currentException.value) { + return false; + } + if (!_isSameFingerprint(currentEvent, previousEvent)) { + return false; + } + if (!_isSameStacktrace(currentEvent, previousEvent)) { + return false; + } + return true; +} +function _isSameStacktrace(currentEvent, previousEvent) { + let currentFrames = getFramesFromEvent(currentEvent); + let previousFrames = getFramesFromEvent(previousEvent); + if (!currentFrames && !previousFrames) { + return true; + } + if (currentFrames && !previousFrames || !currentFrames && previousFrames) { + return false; + } + currentFrames = currentFrames; + previousFrames = previousFrames; + if (previousFrames.length !== currentFrames.length) { + return false; + } + for (let i = 0;i < previousFrames.length; i++) { + const frameA = previousFrames[i]; + const frameB = currentFrames[i]; + if (frameA.filename !== frameB.filename || frameA.lineno !== frameB.lineno || frameA.colno !== frameB.colno || frameA.function !== frameB.function) { + return false; + } + } + return true; +} +function _isSameFingerprint(currentEvent, previousEvent) { + let currentFingerprint = currentEvent.fingerprint; + let previousFingerprint = previousEvent.fingerprint; + if (!currentFingerprint && !previousFingerprint) { + return true; + } + if (currentFingerprint && !previousFingerprint || !currentFingerprint && previousFingerprint) { + return false; + } + currentFingerprint = currentFingerprint; + previousFingerprint = previousFingerprint; + try { + return !!(currentFingerprint.join("") === previousFingerprint.join("")); + } catch (_oO) { + return false; + } +} +function _getExceptionFromEvent(event) { + return event.exception && event.exception.values && event.exception.values[0]; +} +// node_modules/@sentry/core/build/esm/utils-hoist/breadcrumb-log-level.js +function getBreadcrumbLogLevelFromHttpStatusCode(statusCode) { + if (statusCode === undefined) { + return; + } else if (statusCode >= 400 && statusCode < 500) { + return "warning"; + } else if (statusCode >= 500) { + return "error"; + } else { + return; + } +} +// node_modules/@sentry/core/build/esm/utils-hoist/supports.js +var WINDOW2 = GLOBAL_OBJ; +function supportsFetch() { + if (!("fetch" in WINDOW2)) { + return false; + } + try { + new Headers; + new Request("http://www.example.com"); + new Response; + return true; + } catch (e) { + return false; + } +} +function isNativeFunction(func) { + return func && /^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString()); +} +function supportsNativeFetch() { + if (typeof EdgeRuntime === "string") { + return true; + } + if (!supportsFetch()) { + return false; + } + if (isNativeFunction(WINDOW2.fetch)) { + return true; + } + let result = false; + const doc = WINDOW2.document; + if (doc && typeof doc.createElement === "function") { + try { + const sandbox = doc.createElement("iframe"); + sandbox.hidden = true; + doc.head.appendChild(sandbox); + if (sandbox.contentWindow && sandbox.contentWindow.fetch) { + result = isNativeFunction(sandbox.contentWindow.fetch); + } + doc.head.removeChild(sandbox); + } catch (err) { + DEBUG_BUILD2 && logger.warn("Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ", err); + } + } + return result; +} + +// node_modules/@sentry/core/build/esm/utils-hoist/instrument/fetch.js +function addFetchInstrumentationHandler(handler, skipNativeFetchCheck) { + const type = "fetch"; + addHandler(type, handler); + maybeInstrument(type, () => instrumentFetch(undefined, skipNativeFetchCheck)); +} +function instrumentFetch(onFetchResolved, skipNativeFetchCheck = false) { + if (skipNativeFetchCheck && !supportsNativeFetch()) { + return; + } + fill2(GLOBAL_OBJ, "fetch", function(originalFetch) { + return function(...args) { + const virtualError = new Error; + const { method, url } = parseFetchArgs(args); + const handlerData = { + args, + fetchData: { + method, + url + }, + startTimestamp: timestampInSeconds() * 1000, + virtualError + }; + if (!onFetchResolved) { + triggerHandlers("fetch", { + ...handlerData + }); + } + return originalFetch.apply(GLOBAL_OBJ, args).then(async (response) => { + if (onFetchResolved) { + onFetchResolved(response); + } else { + triggerHandlers("fetch", { + ...handlerData, + endTimestamp: timestampInSeconds() * 1000, + response + }); + } + return response; + }, (error) => { + triggerHandlers("fetch", { + ...handlerData, + endTimestamp: timestampInSeconds() * 1000, + error + }); + if (isError(error) && error.stack === undefined) { + error.stack = virtualError.stack; + addNonEnumerableProperty(error, "framesToPop", 1); + } + throw error; + }); + }; + }); +} +function hasProp(obj, prop) { + return !!obj && typeof obj === "object" && !!obj[prop]; +} +function getUrlFromResource(resource) { + if (typeof resource === "string") { + return resource; + } + if (!resource) { + return ""; + } + if (hasProp(resource, "url")) { + return resource.url; + } + if (resource.toString) { + return resource.toString(); + } + return ""; +} +function parseFetchArgs(fetchArgs) { + if (fetchArgs.length === 0) { + return { method: "GET", url: "" }; + } + if (fetchArgs.length === 2) { + const [url, options] = fetchArgs; + return { + url: getUrlFromResource(url), + method: hasProp(options, "method") ? String(options.method).toUpperCase() : "GET" + }; + } + const arg = fetchArgs[0]; + return { + url: getUrlFromResource(arg), + method: hasProp(arg, "method") ? String(arg.method).toUpperCase() : "GET" + }; +} +// node_modules/@sentry/core/build/esm/utils-hoist/env.js +function getSDKSource() { + return "npm"; +} +// node_modules/@sentry/core/build/esm/utils-hoist/vendor/supportsHistory.js +var WINDOW3 = GLOBAL_OBJ; +function supportsHistory() { + const chromeVar = WINDOW3.chrome; + const isChromePackagedApp = chromeVar && chromeVar.app && chromeVar.app.runtime; + const hasHistoryApi = "history" in WINDOW3 && !!WINDOW3.history.pushState && !!WINDOW3.history.replaceState; + return !isChromePackagedApp && hasHistoryApi; +} +// node_modules/@sentry/browser/build/npm/esm/helpers.js +var WINDOW4 = GLOBAL_OBJ; +var ignoreOnError = 0; +function shouldIgnoreOnError() { + return ignoreOnError > 0; +} +function ignoreNextOnError() { + ignoreOnError++; + setTimeout(() => { + ignoreOnError--; + }); +} +function wrap(fn, options = {}) { + function isFunction2(fn2) { + return typeof fn2 === "function"; + } + if (!isFunction2(fn)) { + return fn; + } + try { + const wrapper = fn.__sentry_wrapped__; + if (wrapper) { + if (typeof wrapper === "function") { + return wrapper; + } else { + return fn; + } + } + if (getOriginalFunction(fn)) { + return fn; + } + } catch (e) { + return fn; + } + const sentryWrapped = function(...args) { + try { + const wrappedArguments = args.map((arg) => wrap(arg, options)); + return fn.apply(this, wrappedArguments); + } catch (ex) { + ignoreNextOnError(); + withScope2((scope) => { + scope.addEventProcessor((event) => { + if (options.mechanism) { + addExceptionTypeValue(event, undefined, undefined); + addExceptionMechanism(event, options.mechanism); + } + event.extra = { + ...event.extra, + arguments: args + }; + return event; + }); + captureException(ex); + }); + throw ex; + } + }; + try { + for (const property2 in fn) { + if (Object.prototype.hasOwnProperty.call(fn, property2)) { + sentryWrapped[property2] = fn[property2]; + } + } + } catch (e2) { + } + markFunctionWrapped(sentryWrapped, fn); + addNonEnumerableProperty(fn, "__sentry_wrapped__", sentryWrapped); + try { + const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, "name"); + if (descriptor.configurable) { + Object.defineProperty(sentryWrapped, "name", { + get() { + return fn.name; + } + }); + } + } catch (e3) { + } + return sentryWrapped; +} + +// node_modules/@sentry/browser/build/npm/esm/debug-build.js +var DEBUG_BUILD3 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; + +// node_modules/@sentry/browser/build/npm/esm/eventbuilder.js +function exceptionFromError(stackParser, ex) { + const frames2 = parseStackFrames(stackParser, ex); + const exception = { + type: extractType(ex), + value: extractMessage(ex) + }; + if (frames2.length) { + exception.stacktrace = { frames: frames2 }; + } + if (exception.type === undefined && exception.value === "") { + exception.value = "Unrecoverable error caught"; + } + return exception; +} +function eventFromPlainObject(stackParser, exception, syntheticException, isUnhandledRejection) { + const client = getClient(); + const normalizeDepth = client && client.getOptions().normalizeDepth; + const errorFromProp = getErrorPropertyFromObject(exception); + const extra = { + __serialized__: normalizeToSize(exception, normalizeDepth) + }; + if (errorFromProp) { + return { + exception: { + values: [exceptionFromError(stackParser, errorFromProp)] + }, + extra + }; + } + const event = { + exception: { + values: [ + { + type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? "UnhandledRejection" : "Error", + value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }) + } + ] + }, + extra + }; + if (syntheticException) { + const frames2 = parseStackFrames(stackParser, syntheticException); + if (frames2.length) { + event.exception.values[0].stacktrace = { frames: frames2 }; + } + } + return event; +} +function eventFromError(stackParser, ex) { + return { + exception: { + values: [exceptionFromError(stackParser, ex)] + } + }; +} +function parseStackFrames(stackParser, ex) { + const stacktrace = ex.stacktrace || ex.stack || ""; + const skipLines = getSkipFirstStackStringLines(ex); + const framesToPop = getPopFirstTopFrames(ex); + try { + return stackParser(stacktrace, skipLines, framesToPop); + } catch (e) { + } + return []; +} +var reactMinifiedRegexp = /Minified React error #\d+;/i; +function getSkipFirstStackStringLines(ex) { + if (ex && reactMinifiedRegexp.test(ex.message)) { + return 1; + } + return 0; +} +function getPopFirstTopFrames(ex) { + if (typeof ex.framesToPop === "number") { + return ex.framesToPop; + } + return 0; +} +function isWebAssemblyException(exception) { + if (typeof WebAssembly !== "undefined" && typeof WebAssembly.Exception !== "undefined") { + return exception instanceof WebAssembly.Exception; + } else { + return false; + } +} +function extractType(ex) { + const name2 = ex && ex.name; + if (!name2 && isWebAssemblyException(ex)) { + const hasTypeInMessage = ex.message && Array.isArray(ex.message) && ex.message.length == 2; + return hasTypeInMessage ? ex.message[0] : "WebAssembly.Exception"; + } + return name2; +} +function extractMessage(ex) { + const message = ex && ex.message; + if (!message) { + return "No error message"; + } + if (message.error && typeof message.error.message === "string") { + return message.error.message; + } + if (isWebAssemblyException(ex) && Array.isArray(ex.message) && ex.message.length == 2) { + return ex.message[1]; + } + return message; +} +function eventFromException(stackParser, exception, hint, attachStacktrace) { + const syntheticException = hint && hint.syntheticException || undefined; + const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace); + addExceptionMechanism(event); + event.level = "error"; + if (hint && hint.event_id) { + event.event_id = hint.event_id; + } + return resolvedSyncPromise(event); +} +function eventFromMessage(stackParser, message, level = "info", hint, attachStacktrace) { + const syntheticException = hint && hint.syntheticException || undefined; + const event = eventFromString(stackParser, message, syntheticException, attachStacktrace); + event.level = level; + if (hint && hint.event_id) { + event.event_id = hint.event_id; + } + return resolvedSyncPromise(event); +} +function eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace, isUnhandledRejection) { + let event; + if (isErrorEvent(exception) && exception.error) { + const errorEvent = exception; + return eventFromError(stackParser, errorEvent.error); + } + if (isDOMError(exception) || isDOMException(exception)) { + const domException = exception; + if ("stack" in exception) { + event = eventFromError(stackParser, exception); + } else { + const name2 = domException.name || (isDOMError(domException) ? "DOMError" : "DOMException"); + const message = domException.message ? `${name2}: ${domException.message}` : name2; + event = eventFromString(stackParser, message, syntheticException, attachStacktrace); + addExceptionTypeValue(event, message); + } + if ("code" in domException) { + event.tags = { ...event.tags, "DOMException.code": `${domException.code}` }; + } + return event; + } + if (isError(exception)) { + return eventFromError(stackParser, exception); + } + if (isPlainObject(exception) || isEvent(exception)) { + const objectException = exception; + event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection); + addExceptionMechanism(event, { + synthetic: true + }); + return event; + } + event = eventFromString(stackParser, exception, syntheticException, attachStacktrace); + addExceptionTypeValue(event, `${exception}`, undefined); + addExceptionMechanism(event, { + synthetic: true + }); + return event; +} +function eventFromString(stackParser, message, syntheticException, attachStacktrace) { + const event = {}; + if (attachStacktrace && syntheticException) { + const frames2 = parseStackFrames(stackParser, syntheticException); + if (frames2.length) { + event.exception = { + values: [{ value: message, stacktrace: { frames: frames2 } }] + }; + } + addExceptionMechanism(event, { synthetic: true }); + } + if (isParameterizedString(message)) { + const { __sentry_template_string__, __sentry_template_values__ } = message; + event.logentry = { + message: __sentry_template_string__, + params: __sentry_template_values__ + }; + return event; + } + event.message = message; + return event; +} +function getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }) { + const keys2 = extractExceptionKeysForMessage(exception); + const captureType = isUnhandledRejection ? "promise rejection" : "exception"; + if (isErrorEvent(exception)) { + return `Event \`ErrorEvent\` captured as ${captureType} with message \`${exception.message}\``; + } + if (isEvent(exception)) { + const className = getObjectClassName(exception); + return `Event \`${className}\` (type=${exception.type}) captured as ${captureType}`; + } + return `Object captured as ${captureType} with keys: ${keys2}`; +} +function getObjectClassName(obj) { + try { + const prototype = Object.getPrototypeOf(obj); + return prototype ? prototype.constructor.name : undefined; + } catch (e) { + } +} +function getErrorPropertyFromObject(obj) { + for (const prop in obj) { + if (Object.prototype.hasOwnProperty.call(obj, prop)) { + const value2 = obj[prop]; + if (value2 instanceof Error) { + return value2; + } + } + } + return; +} + +// node_modules/@sentry/browser/build/npm/esm/userfeedback.js +function createUserFeedbackEnvelope(feedback, { + metadata, + tunnel, + dsn +}) { + const headers = { + event_id: feedback.event_id, + sent_at: new Date().toISOString(), + ...metadata && metadata.sdk && { + sdk: { + name: metadata.sdk.name, + version: metadata.sdk.version + } + }, + ...!!tunnel && !!dsn && { dsn: dsnToString(dsn) } + }; + const item = createUserFeedbackEnvelopeItem(feedback); + return createEnvelope(headers, [item]); +} +function createUserFeedbackEnvelopeItem(feedback) { + const feedbackHeaders = { + type: "user_report" + }; + return [feedbackHeaders, feedback]; +} + +// node_modules/@sentry/browser/build/npm/esm/client.js +class BrowserClient extends BaseClient { + constructor(options) { + const opts = { + parentSpanIsAlwaysRootSpan: true, + ...options + }; + const sdkSource = WINDOW4.SENTRY_SDK_SOURCE || getSDKSource(); + applySdkMetadata(opts, "browser", ["browser"], sdkSource); + super(opts); + if (opts.sendClientReports && WINDOW4.document) { + WINDOW4.document.addEventListener("visibilitychange", () => { + if (WINDOW4.document.visibilityState === "hidden") { + this._flushOutcomes(); + } + }); + } + } + eventFromException(exception, hint) { + return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace); + } + eventFromMessage(message, level = "info", hint) { + return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace); + } + captureUserFeedback(feedback) { + if (!this._isEnabled()) { + DEBUG_BUILD3 && logger.warn("SDK not enabled, will not capture user feedback."); + return; + } + const envelope = createUserFeedbackEnvelope(feedback, { + metadata: this.getSdkMetadata(), + dsn: this.getDsn(), + tunnel: this.getOptions().tunnel + }); + this.sendEnvelope(envelope); + } + _prepareEvent(event, hint, scope) { + event.platform = event.platform || "javascript"; + return super._prepareEvent(event, hint, scope); + } +} + +// node_modules/@sentry-internal/browser-utils/build/esm/debug-build.js +var DEBUG_BUILD4 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__; + +// node_modules/@sentry-internal/browser-utils/build/esm/types.js +var WINDOW5 = GLOBAL_OBJ; + +// node_modules/@sentry-internal/browser-utils/build/esm/instrument/dom.js +var DEBOUNCE_DURATION = 1000; +var debounceTimerID; +var lastCapturedEventType; +var lastCapturedEventTargetId; +function addClickKeypressInstrumentationHandler(handler) { + const type = "dom"; + addHandler(type, handler); + maybeInstrument(type, instrumentDOM); +} +function instrumentDOM() { + if (!WINDOW5.document) { + return; + } + const triggerDOMHandler = triggerHandlers.bind(null, "dom"); + const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true); + WINDOW5.document.addEventListener("click", globalDOMEventHandler, false); + WINDOW5.document.addEventListener("keypress", globalDOMEventHandler, false); + ["EventTarget", "Node"].forEach((target) => { + const globalObject = WINDOW5; + const targetObj = globalObject[target]; + const proto = targetObj && targetObj.prototype; + if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) { + return; + } + fill2(proto, "addEventListener", function(originalAddEventListener) { + return function(type, listener, options) { + if (type === "click" || type == "keypress") { + try { + const handlers2 = this.__sentry_instrumentation_handlers__ = this.__sentry_instrumentation_handlers__ || {}; + const handlerForType = handlers2[type] = handlers2[type] || { refCount: 0 }; + if (!handlerForType.handler) { + const handler = makeDOMEventHandler(triggerDOMHandler); + handlerForType.handler = handler; + originalAddEventListener.call(this, type, handler, options); + } + handlerForType.refCount++; + } catch (e) { + } + } + return originalAddEventListener.call(this, type, listener, options); + }; + }); + fill2(proto, "removeEventListener", function(originalRemoveEventListener) { + return function(type, listener, options) { + if (type === "click" || type == "keypress") { + try { + const handlers2 = this.__sentry_instrumentation_handlers__ || {}; + const handlerForType = handlers2[type]; + if (handlerForType) { + handlerForType.refCount--; + if (handlerForType.refCount <= 0) { + originalRemoveEventListener.call(this, type, handlerForType.handler, options); + handlerForType.handler = undefined; + delete handlers2[type]; + } + if (Object.keys(handlers2).length === 0) { + delete this.__sentry_instrumentation_handlers__; + } + } + } catch (e) { + } + } + return originalRemoveEventListener.call(this, type, listener, options); + }; + }); + }); +} +function isSimilarToLastCapturedEvent(event) { + if (event.type !== lastCapturedEventType) { + return false; + } + try { + if (!event.target || event.target._sentryId !== lastCapturedEventTargetId) { + return false; + } + } catch (e) { + } + return true; +} +function shouldSkipDOMEvent(eventType, target) { + if (eventType !== "keypress") { + return false; + } + if (!target || !target.tagName) { + return true; + } + if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) { + return false; + } + return true; +} +function makeDOMEventHandler(handler, globalListener = false) { + return (event) => { + if (!event || event["_sentryCaptured"]) { + return; + } + const target = getEventTarget(event); + if (shouldSkipDOMEvent(event.type, target)) { + return; + } + addNonEnumerableProperty(event, "_sentryCaptured", true); + if (target && !target._sentryId) { + addNonEnumerableProperty(target, "_sentryId", uuid4()); + } + const name2 = event.type === "keypress" ? "input" : event.type; + if (!isSimilarToLastCapturedEvent(event)) { + const handlerData = { event, name: name2, global: globalListener }; + handler(handlerData); + lastCapturedEventType = event.type; + lastCapturedEventTargetId = target ? target._sentryId : undefined; + } + clearTimeout(debounceTimerID); + debounceTimerID = WINDOW5.setTimeout(() => { + lastCapturedEventTargetId = undefined; + lastCapturedEventType = undefined; + }, DEBOUNCE_DURATION); + }; +} +function getEventTarget(event) { + try { + return event.target; + } catch (e) { + return null; + } +} +// node_modules/@sentry-internal/browser-utils/build/esm/instrument/history.js +var lastHref; +function addHistoryInstrumentationHandler(handler) { + const type = "history"; + addHandler(type, handler); + maybeInstrument(type, instrumentHistory); +} +function instrumentHistory() { + if (!supportsHistory()) { + return; + } + const oldOnPopState = WINDOW5.onpopstate; + WINDOW5.onpopstate = function(...args) { + const to = WINDOW5.location.href; + const from = lastHref; + lastHref = to; + const handlerData = { from, to }; + triggerHandlers("history", handlerData); + if (oldOnPopState) { + try { + return oldOnPopState.apply(this, args); + } catch (_oO) { + } + } + }; + function historyReplacementFunction(originalHistoryFunction) { + return function(...args) { + const url = args.length > 2 ? args[2] : undefined; + if (url) { + const from = lastHref; + const to = String(url); + lastHref = to; + const handlerData = { from, to }; + triggerHandlers("history", handlerData); + } + return originalHistoryFunction.apply(this, args); + }; + } + fill2(WINDOW5.history, "pushState", historyReplacementFunction); + fill2(WINDOW5.history, "replaceState", historyReplacementFunction); +} +// node_modules/@sentry-internal/browser-utils/build/esm/getNativeImplementation.js +var cachedImplementations = {}; +function getNativeImplementation(name2) { + const cached = cachedImplementations[name2]; + if (cached) { + return cached; + } + let impl = WINDOW5[name2]; + if (isNativeFunction(impl)) { + return cachedImplementations[name2] = impl.bind(WINDOW5); + } + const document2 = WINDOW5.document; + if (document2 && typeof document2.createElement === "function") { + try { + const sandbox = document2.createElement("iframe"); + sandbox.hidden = true; + document2.head.appendChild(sandbox); + const contentWindow = sandbox.contentWindow; + if (contentWindow && contentWindow[name2]) { + impl = contentWindow[name2]; + } + document2.head.removeChild(sandbox); + } catch (e) { + DEBUG_BUILD4 && logger.warn(`Could not create sandbox iframe for ${name2} check, bailing to window.${name2}: `, e); + } + } + if (!impl) { + return impl; + } + return cachedImplementations[name2] = impl.bind(WINDOW5); +} +function clearCachedImplementation(name2) { + cachedImplementations[name2] = undefined; +} +// node_modules/@sentry-internal/browser-utils/build/esm/instrument/xhr.js +var SENTRY_XHR_DATA_KEY = "__sentry_xhr_v3__"; +function addXhrInstrumentationHandler(handler) { + const type = "xhr"; + addHandler(type, handler); + maybeInstrument(type, instrumentXHR); +} +function instrumentXHR() { + if (!WINDOW5.XMLHttpRequest) { + return; + } + const xhrproto = XMLHttpRequest.prototype; + xhrproto.open = new Proxy(xhrproto.open, { + apply(originalOpen, xhrOpenThisArg, xhrOpenArgArray) { + const virtualError = new Error; + const startTimestamp = timestampInSeconds() * 1000; + const method = isString2(xhrOpenArgArray[0]) ? xhrOpenArgArray[0].toUpperCase() : undefined; + const url = parseUrl2(xhrOpenArgArray[1]); + if (!method || !url) { + return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray); + } + xhrOpenThisArg[SENTRY_XHR_DATA_KEY] = { + method, + url, + request_headers: {} + }; + if (method === "POST" && url.match(/sentry_key/)) { + xhrOpenThisArg.__sentry_own_request__ = true; + } + const onreadystatechangeHandler = () => { + const xhrInfo = xhrOpenThisArg[SENTRY_XHR_DATA_KEY]; + if (!xhrInfo) { + return; + } + if (xhrOpenThisArg.readyState === 4) { + try { + xhrInfo.status_code = xhrOpenThisArg.status; + } catch (e) { + } + const handlerData = { + endTimestamp: timestampInSeconds() * 1000, + startTimestamp, + xhr: xhrOpenThisArg, + virtualError + }; + triggerHandlers("xhr", handlerData); + } + }; + if ("onreadystatechange" in xhrOpenThisArg && typeof xhrOpenThisArg.onreadystatechange === "function") { + xhrOpenThisArg.onreadystatechange = new Proxy(xhrOpenThisArg.onreadystatechange, { + apply(originalOnreadystatechange, onreadystatechangeThisArg, onreadystatechangeArgArray) { + onreadystatechangeHandler(); + return originalOnreadystatechange.apply(onreadystatechangeThisArg, onreadystatechangeArgArray); + } + }); + } else { + xhrOpenThisArg.addEventListener("readystatechange", onreadystatechangeHandler); + } + xhrOpenThisArg.setRequestHeader = new Proxy(xhrOpenThisArg.setRequestHeader, { + apply(originalSetRequestHeader, setRequestHeaderThisArg, setRequestHeaderArgArray) { + const [header, value2] = setRequestHeaderArgArray; + const xhrInfo = setRequestHeaderThisArg[SENTRY_XHR_DATA_KEY]; + if (xhrInfo && isString2(header) && isString2(value2)) { + xhrInfo.request_headers[header.toLowerCase()] = value2; + } + return originalSetRequestHeader.apply(setRequestHeaderThisArg, setRequestHeaderArgArray); + } + }); + return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray); + } + }); + xhrproto.send = new Proxy(xhrproto.send, { + apply(originalSend, sendThisArg, sendArgArray) { + const sentryXhrData = sendThisArg[SENTRY_XHR_DATA_KEY]; + if (!sentryXhrData) { + return originalSend.apply(sendThisArg, sendArgArray); + } + if (sendArgArray[0] !== undefined) { + sentryXhrData.body = sendArgArray[0]; + } + const handlerData = { + startTimestamp: timestampInSeconds() * 1000, + xhr: sendThisArg + }; + triggerHandlers("xhr", handlerData); + return originalSend.apply(sendThisArg, sendArgArray); + } + }); +} +function parseUrl2(url) { + if (isString2(url)) { + return url; + } + try { + return url.toString(); + } catch (e2) { + } + return; +} +// node_modules/@sentry/browser/build/npm/esm/transports/fetch.js +function makeFetchTransport(options, nativeFetch = getNativeImplementation("fetch")) { + let pendingBodySize = 0; + let pendingCount = 0; + function makeRequest(request) { + const requestSize = request.body.length; + pendingBodySize += requestSize; + pendingCount++; + const requestOptions = { + body: request.body, + method: "POST", + referrerPolicy: "origin", + headers: options.headers, + keepalive: pendingBodySize <= 60000 && pendingCount < 15, + ...options.fetchOptions + }; + if (!nativeFetch) { + clearCachedImplementation("fetch"); + return rejectedSyncPromise("No fetch implementation available"); + } + try { + return nativeFetch(options.url, requestOptions).then((response) => { + pendingBodySize -= requestSize; + pendingCount--; + return { + statusCode: response.status, + headers: { + "x-sentry-rate-limits": response.headers.get("X-Sentry-Rate-Limits"), + "retry-after": response.headers.get("Retry-After") + } + }; + }); + } catch (e) { + clearCachedImplementation("fetch"); + pendingBodySize -= requestSize; + pendingCount--; + return rejectedSyncPromise(e); + } + } + return createTransport(options, makeRequest); +} + +// node_modules/@sentry/browser/build/npm/esm/stack-parsers.js +var CHROME_PRIORITY = 30; +var GECKO_PRIORITY = 50; +function createFrame(filename, func, lineno, colno) { + const frame = { + filename, + function: func === "" ? UNKNOWN_FUNCTION : func, + in_app: true + }; + if (lineno !== undefined) { + frame.lineno = lineno; + } + if (colno !== undefined) { + frame.colno = colno; + } + return frame; +} +var chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i; +var chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i; +var chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/; +var chromeStackParserFn = (line2) => { + const noFnParts = chromeRegexNoFnName.exec(line2); + if (noFnParts) { + const [, filename, line3, col] = noFnParts; + return createFrame(filename, UNKNOWN_FUNCTION, +line3, +col); + } + const parts = chromeRegex.exec(line2); + if (parts) { + const isEval = parts[2] && parts[2].indexOf("eval") === 0; + if (isEval) { + const subMatch = chromeEvalRegex.exec(parts[2]); + if (subMatch) { + parts[2] = subMatch[1]; + parts[3] = subMatch[2]; + parts[4] = subMatch[3]; + } + } + const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]); + return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined); + } + return; +}; +var chromeStackLineParser = [CHROME_PRIORITY, chromeStackParserFn]; +var geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i; +var geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i; +var gecko = (line2) => { + const parts = geckoREgex.exec(line2); + if (parts) { + const isEval = parts[3] && parts[3].indexOf(" > eval") > -1; + if (isEval) { + const subMatch = geckoEvalRegex.exec(parts[3]); + if (subMatch) { + parts[1] = parts[1] || "eval"; + parts[3] = subMatch[1]; + parts[4] = subMatch[2]; + parts[5] = ""; + } + } + let filename = parts[3]; + let func = parts[1] || UNKNOWN_FUNCTION; + [func, filename] = extractSafariExtensionDetails(func, filename); + return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined); + } + return; +}; +var geckoStackLineParser = [GECKO_PRIORITY, gecko]; +var defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser]; +var defaultStackParser = createStackParser(...defaultStackLineParsers); +var extractSafariExtensionDetails = (func, filename) => { + const isSafariExtension = func.indexOf("safari-extension") !== -1; + const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1; + return isSafariExtension || isSafariWebExtension ? [ + func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION, + isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}` + ] : [func, filename]; +}; + +// node_modules/@sentry/browser/build/npm/esm/integrations/breadcrumbs.js +var MAX_ALLOWED_STRING_LENGTH = 1024; +var INTEGRATION_NAME4 = "Breadcrumbs"; +var _breadcrumbsIntegration = (options = {}) => { + const _options = { + console: true, + dom: true, + fetch: true, + history: true, + sentry: true, + xhr: true, + ...options + }; + return { + name: INTEGRATION_NAME4, + setup(client) { + if (_options.console) { + addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client)); + } + if (_options.dom) { + addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom)); + } + if (_options.xhr) { + addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client)); + } + if (_options.fetch) { + addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client)); + } + if (_options.history) { + addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client)); + } + if (_options.sentry) { + client.on("beforeSendEvent", _getSentryBreadcrumbHandler(client)); + } + } + }; +}; +var breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration); +function _getSentryBreadcrumbHandler(client) { + return function addSentryBreadcrumb(event) { + if (getClient() !== client) { + return; + } + addBreadcrumb({ + category: `sentry.${event.type === "transaction" ? "transaction" : "event"}`, + event_id: event.event_id, + level: event.level, + message: getEventDescription(event) + }, { + event + }); + }; +} +function _getDomBreadcrumbHandler(client, dom) { + return function _innerDomBreadcrumb(handlerData) { + if (getClient() !== client) { + return; + } + let target; + let componentName; + let keyAttrs = typeof dom === "object" ? dom.serializeAttribute : undefined; + let maxStringLength = typeof dom === "object" && typeof dom.maxStringLength === "number" ? dom.maxStringLength : undefined; + if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) { + DEBUG_BUILD3 && logger.warn(`\`dom.maxStringLength\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`); + maxStringLength = MAX_ALLOWED_STRING_LENGTH; + } + if (typeof keyAttrs === "string") { + keyAttrs = [keyAttrs]; + } + try { + const event = handlerData.event; + const element = _isEvent(event) ? event.target : event; + target = htmlTreeAsString(element, { keyAttrs, maxStringLength }); + componentName = getComponentName(element); + } catch (e) { + target = ""; + } + if (target.length === 0) { + return; + } + const breadcrumb = { + category: `ui.${handlerData.name}`, + message: target + }; + if (componentName) { + breadcrumb.data = { "ui.component_name": componentName }; + } + addBreadcrumb(breadcrumb, { + event: handlerData.event, + name: handlerData.name, + global: handlerData.global + }); + }; +} +function _getConsoleBreadcrumbHandler(client) { + return function _consoleBreadcrumb(handlerData) { + if (getClient() !== client) { + return; + } + const breadcrumb = { + category: "console", + data: { + arguments: handlerData.args, + logger: "console" + }, + level: severityLevelFromString(handlerData.level), + message: safeJoin(handlerData.args, " ") + }; + if (handlerData.level === "assert") { + if (handlerData.args[0] === false) { + breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), " ") || "console.assert"}`; + breadcrumb.data.arguments = handlerData.args.slice(1); + } else { + return; + } + } + addBreadcrumb(breadcrumb, { + input: handlerData.args, + level: handlerData.level + }); + }; +} +function _getXhrBreadcrumbHandler(client) { + return function _xhrBreadcrumb(handlerData) { + if (getClient() !== client) { + return; + } + const { startTimestamp, endTimestamp } = handlerData; + const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY]; + if (!startTimestamp || !endTimestamp || !sentryXhrData) { + return; + } + const { method, url, status_code, body } = sentryXhrData; + const data2 = { + method, + url, + status_code + }; + const hint = { + xhr: handlerData.xhr, + input: body, + startTimestamp, + endTimestamp + }; + const level = getBreadcrumbLogLevelFromHttpStatusCode(status_code); + addBreadcrumb({ + category: "xhr", + data: data2, + type: "http", + level + }, hint); + }; +} +function _getFetchBreadcrumbHandler(client) { + return function _fetchBreadcrumb(handlerData) { + if (getClient() !== client) { + return; + } + const { startTimestamp, endTimestamp } = handlerData; + if (!endTimestamp) { + return; + } + if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === "POST") { + return; + } + if (handlerData.error) { + const data2 = handlerData.fetchData; + const hint = { + data: handlerData.error, + input: handlerData.args, + startTimestamp, + endTimestamp + }; + addBreadcrumb({ + category: "fetch", + data: data2, + level: "error", + type: "http" + }, hint); + } else { + const response = handlerData.response; + const data2 = { + ...handlerData.fetchData, + status_code: response && response.status + }; + const hint = { + input: handlerData.args, + response, + startTimestamp, + endTimestamp + }; + const level = getBreadcrumbLogLevelFromHttpStatusCode(data2.status_code); + addBreadcrumb({ + category: "fetch", + data: data2, + type: "http", + level + }, hint); + } + }; +} +function _getHistoryBreadcrumbHandler(client) { + return function _historyBreadcrumb(handlerData) { + if (getClient() !== client) { + return; + } + let from = handlerData.from; + let to = handlerData.to; + const parsedLoc = parseUrl(WINDOW4.location.href); + let parsedFrom = from ? parseUrl(from) : undefined; + const parsedTo = parseUrl(to); + if (!parsedFrom || !parsedFrom.path) { + parsedFrom = parsedLoc; + } + if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) { + to = parsedTo.relative; + } + if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) { + from = parsedFrom.relative; + } + addBreadcrumb({ + category: "navigation", + data: { + from, + to + } + }); + }; +} +function _isEvent(event) { + return !!event && !!event.target; +} + +// node_modules/@sentry/browser/build/npm/esm/integrations/browserapierrors.js +var DEFAULT_EVENT_TARGET = [ + "EventTarget", + "Window", + "Node", + "ApplicationCache", + "AudioTrackList", + "BroadcastChannel", + "ChannelMergerNode", + "CryptoOperation", + "EventSource", + "FileReader", + "HTMLUnknownElement", + "IDBDatabase", + "IDBRequest", + "IDBTransaction", + "KeyOperation", + "MediaController", + "MessagePort", + "ModalWindow", + "Notification", + "SVGElementInstance", + "Screen", + "SharedWorker", + "TextTrack", + "TextTrackCue", + "TextTrackList", + "WebSocket", + "WebSocketWorker", + "Worker", + "XMLHttpRequest", + "XMLHttpRequestEventTarget", + "XMLHttpRequestUpload" +]; +var INTEGRATION_NAME5 = "BrowserApiErrors"; +var _browserApiErrorsIntegration = (options = {}) => { + const _options = { + XMLHttpRequest: true, + eventTarget: true, + requestAnimationFrame: true, + setInterval: true, + setTimeout: true, + ...options + }; + return { + name: INTEGRATION_NAME5, + setupOnce() { + if (_options.setTimeout) { + fill2(WINDOW4, "setTimeout", _wrapTimeFunction); + } + if (_options.setInterval) { + fill2(WINDOW4, "setInterval", _wrapTimeFunction); + } + if (_options.requestAnimationFrame) { + fill2(WINDOW4, "requestAnimationFrame", _wrapRAF); + } + if (_options.XMLHttpRequest && "XMLHttpRequest" in WINDOW4) { + fill2(XMLHttpRequest.prototype, "send", _wrapXHR); + } + const eventTargetOption = _options.eventTarget; + if (eventTargetOption) { + const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET; + eventTarget.forEach(_wrapEventTarget); + } + } + }; +}; +var browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration); +function _wrapTimeFunction(original) { + return function(...args) { + const originalCallback = args[0]; + args[0] = wrap(originalCallback, { + mechanism: { + data: { function: getFunctionName(original) }, + handled: false, + type: "instrument" + } + }); + return original.apply(this, args); + }; +} +function _wrapRAF(original) { + return function(callback) { + return original.apply(this, [ + wrap(callback, { + mechanism: { + data: { + function: "requestAnimationFrame", + handler: getFunctionName(original) + }, + handled: false, + type: "instrument" + } + }) + ]); + }; +} +function _wrapXHR(originalSend) { + return function(...args) { + const xhr = this; + const xmlHttpRequestProps = ["onload", "onerror", "onprogress", "onreadystatechange"]; + xmlHttpRequestProps.forEach((prop) => { + if (prop in xhr && typeof xhr[prop] === "function") { + fill2(xhr, prop, function(original) { + const wrapOptions = { + mechanism: { + data: { + function: prop, + handler: getFunctionName(original) + }, + handled: false, + type: "instrument" + } + }; + const originalFunction = getOriginalFunction(original); + if (originalFunction) { + wrapOptions.mechanism.data.handler = getFunctionName(originalFunction); + } + return wrap(original, wrapOptions); + }); + } + }); + return originalSend.apply(this, args); + }; +} +function _wrapEventTarget(target) { + const globalObject = WINDOW4; + const targetObj = globalObject[target]; + const proto = targetObj && targetObj.prototype; + if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty("addEventListener")) { + return; + } + fill2(proto, "addEventListener", function(original) { + return function(eventName, fn, options) { + try { + if (isEventListenerObject(fn)) { + fn.handleEvent = wrap(fn.handleEvent, { + mechanism: { + data: { + function: "handleEvent", + handler: getFunctionName(fn), + target + }, + handled: false, + type: "instrument" + } + }); + } + } catch (e2) { + } + return original.apply(this, [ + eventName, + wrap(fn, { + mechanism: { + data: { + function: "addEventListener", + handler: getFunctionName(fn), + target + }, + handled: false, + type: "instrument" + } + }), + options + ]); + }; + }); + fill2(proto, "removeEventListener", function(originalRemoveEventListener) { + return function(eventName, fn, options) { + try { + const originalEventHandler = fn.__sentry_wrapped__; + if (originalEventHandler) { + originalRemoveEventListener.call(this, eventName, originalEventHandler, options); + } + } catch (e) { + } + return originalRemoveEventListener.call(this, eventName, fn, options); + }; + }); +} +function isEventListenerObject(obj) { + return typeof obj.handleEvent === "function"; +} + +// node_modules/@sentry/browser/build/npm/esm/integrations/browsersession.js +var browserSessionIntegration = defineIntegration(() => { + return { + name: "BrowserSession", + setupOnce() { + if (typeof WINDOW4.document === "undefined") { + DEBUG_BUILD3 && logger.warn("Using the `browserSessionIntegration` in non-browser environments is not supported."); + return; + } + startSession({ ignoreDuration: true }); + captureSession(); + addHistoryInstrumentationHandler(({ from, to }) => { + if (from !== undefined && from !== to) { + startSession({ ignoreDuration: true }); + captureSession(); + } + }); + } + }; +}); + +// node_modules/@sentry/browser/build/npm/esm/integrations/globalhandlers.js +var INTEGRATION_NAME6 = "GlobalHandlers"; +var _globalHandlersIntegration = (options = {}) => { + const _options = { + onerror: true, + onunhandledrejection: true, + ...options + }; + return { + name: INTEGRATION_NAME6, + setupOnce() { + Error.stackTraceLimit = 50; + }, + setup(client) { + if (_options.onerror) { + _installGlobalOnErrorHandler(client); + globalHandlerLog("onerror"); + } + if (_options.onunhandledrejection) { + _installGlobalOnUnhandledRejectionHandler(client); + globalHandlerLog("onunhandledrejection"); + } + } + }; +}; +var globalHandlersIntegration = defineIntegration(_globalHandlersIntegration); +function _installGlobalOnErrorHandler(client) { + addGlobalErrorInstrumentationHandler((data2) => { + const { stackParser, attachStacktrace } = getOptions(); + if (getClient() !== client || shouldIgnoreOnError()) { + return; + } + const { msg, url, line: line2, column, error } = data2; + const event = _enhanceEventWithInitialFrame(eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false), url, line2, column); + event.level = "error"; + captureEvent(event, { + originalException: error, + mechanism: { + handled: false, + type: "onerror" + } + }); + }); +} +function _installGlobalOnUnhandledRejectionHandler(client) { + addGlobalUnhandledRejectionInstrumentationHandler((e) => { + const { stackParser, attachStacktrace } = getOptions(); + if (getClient() !== client || shouldIgnoreOnError()) { + return; + } + const error = _getUnhandledRejectionError(e); + const event = isPrimitive(error) ? _eventFromRejectionWithPrimitive(error) : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true); + event.level = "error"; + captureEvent(event, { + originalException: error, + mechanism: { + handled: false, + type: "onunhandledrejection" + } + }); + }); +} +function _getUnhandledRejectionError(error) { + if (isPrimitive(error)) { + return error; + } + try { + if ("reason" in error) { + return error.reason; + } + if ("detail" in error && "reason" in error.detail) { + return error.detail.reason; + } + } catch (e2) { + } + return error; +} +function _eventFromRejectionWithPrimitive(reason) { + return { + exception: { + values: [ + { + type: "UnhandledRejection", + value: `Non-Error promise rejection captured with value: ${String(reason)}` + } + ] + } + }; +} +function _enhanceEventWithInitialFrame(event, url, line2, column) { + const e = event.exception = event.exception || {}; + const ev = e.values = e.values || []; + const ev0 = ev[0] = ev[0] || {}; + const ev0s = ev0.stacktrace = ev0.stacktrace || {}; + const ev0sf = ev0s.frames = ev0s.frames || []; + const colno = column; + const lineno = line2; + const filename = isString2(url) && url.length > 0 ? url : getLocationHref2(); + if (ev0sf.length === 0) { + ev0sf.push({ + colno, + filename, + function: UNKNOWN_FUNCTION, + in_app: true, + lineno + }); + } + return event; +} +function globalHandlerLog(type) { + DEBUG_BUILD3 && logger.log(`Global Handler attached: ${type}`); +} +function getOptions() { + const client = getClient(); + const options = client && client.getOptions() || { + stackParser: () => [], + attachStacktrace: false + }; + return options; +} + +// node_modules/@sentry/browser/build/npm/esm/integrations/httpcontext.js +var httpContextIntegration = defineIntegration(() => { + return { + name: "HttpContext", + preprocessEvent(event) { + if (!WINDOW4.navigator && !WINDOW4.location && !WINDOW4.document) { + return; + } + const url = event.request && event.request.url || WINDOW4.location && WINDOW4.location.href; + const { referrer } = WINDOW4.document || {}; + const { userAgent } = WINDOW4.navigator || {}; + const headers = { + ...event.request && event.request.headers, + ...referrer && { Referer: referrer }, + ...userAgent && { "User-Agent": userAgent } + }; + const request = { ...event.request, ...url && { url }, headers }; + event.request = request; + } + }; +}); + +// node_modules/@sentry/browser/build/npm/esm/integrations/linkederrors.js +var DEFAULT_KEY = "cause"; +var DEFAULT_LIMIT = 5; +var INTEGRATION_NAME7 = "LinkedErrors"; +var _linkedErrorsIntegration = (options = {}) => { + const limit = options.limit || DEFAULT_LIMIT; + const key2 = options.key || DEFAULT_KEY; + return { + name: INTEGRATION_NAME7, + preprocessEvent(event, hint, client) { + const options2 = client.getOptions(); + applyAggregateErrorsToEvent(exceptionFromError, options2.stackParser, options2.maxValueLength, key2, limit, event, hint); + } + }; +}; +var linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration); + +// node_modules/@sentry/browser/build/npm/esm/sdk.js +function getDefaultIntegrations(options) { + const integrations = [ + inboundFiltersIntegration(), + functionToStringIntegration(), + browserApiErrorsIntegration(), + breadcrumbsIntegration(), + globalHandlersIntegration(), + linkedErrorsIntegration(), + dedupeIntegration(), + httpContextIntegration() + ]; + if (options.autoSessionTracking !== false) { + integrations.push(browserSessionIntegration()); + } + return integrations; +} +function applyDefaultOptions(optionsArg = {}) { + const defaultOptions = { + defaultIntegrations: getDefaultIntegrations(optionsArg), + release: typeof __SENTRY_RELEASE__ === "string" ? __SENTRY_RELEASE__ : WINDOW4.SENTRY_RELEASE && WINDOW4.SENTRY_RELEASE.id ? WINDOW4.SENTRY_RELEASE.id : undefined, + autoSessionTracking: true, + sendClientReports: true + }; + if (optionsArg.defaultIntegrations == null) { + delete optionsArg.defaultIntegrations; + } + return { ...defaultOptions, ...optionsArg }; +} +function shouldShowBrowserExtensionError() { + const windowWithMaybeExtension = typeof WINDOW4.window !== "undefined" && WINDOW4; + if (!windowWithMaybeExtension) { + return false; + } + const extensionKey = windowWithMaybeExtension.chrome ? "chrome" : "browser"; + const extensionObject = windowWithMaybeExtension[extensionKey]; + const runtimeId = extensionObject && extensionObject.runtime && extensionObject.runtime.id; + const href = WINDOW4.location && WINDOW4.location.href || ""; + const extensionProtocols = ["chrome-extension:", "moz-extension:", "ms-browser-extension:", "safari-web-extension:"]; + const isDedicatedExtensionPage = !!runtimeId && WINDOW4 === WINDOW4.top && extensionProtocols.some((protocol) => href.startsWith(`${protocol}//`)); + const isNWjs = typeof windowWithMaybeExtension.nw !== "undefined"; + return !!runtimeId && !isDedicatedExtensionPage && !isNWjs; +} +function init(browserOptions = {}) { + const options = applyDefaultOptions(browserOptions); + if (!options.skipBrowserExtensionCheck && shouldShowBrowserExtensionError()) { + consoleSandbox(() => { + console.error("[Sentry] You cannot run Sentry this way in a browser extension, check: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/"); + }); + return; + } + if (DEBUG_BUILD3) { + if (!supportsFetch()) { + logger.warn("No Fetch API detected. The Sentry SDK requires a Fetch API compatible environment to send events. Please add a Fetch API polyfill."); + } + } + const clientOptions = { + ...options, + stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser), + integrations: getIntegrationsToSetup(options), + transport: options.transport || makeFetchTransport + }; + return initAndBind(BrowserClient, clientOptions); +} +// src/main.ts +var import_localforage15 = __toESM(require_localforage(), 1); +window.LazyLoad = new import_vanilla_lazyload.default; +if (Config.apis.useSentry) { + init({ + dsn: Config.apis.sentryURL, + tracesSampleRate: 0.01 + }); +} +document.documentElement.dataset.theme = "default"; +window.localforage = import_localforage15.default; +if (window[[108, 111, 99, 97, 116, 105, 111, 110].map((n2) => ([] + []).constructor.fromCharCode(n2)).join("")][[104, 111, 115, 116].map((n2) => ([] + []).constructor.fromCharCode(n2)).join("")].includes([109, 105, 105, 46, 110, 120, 119, 46, 112, 119].map((n2) => ([] + []).constructor.fromCharCode(n2)).join(""))) { +} else { +} +setupUi(); diff --git a/public/dist/popup.js b/public/dist/popup.js new file mode 100644 index 0000000..e20e893 --- /dev/null +++ b/public/dist/popup.js @@ -0,0 +1,285 @@ +var __create = Object.create; +var __getProtoOf = Object.getPrototypeOf; +var __defProp = Object.defineProperty; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __toESM = (mod, isNodeMode, target) => { + target = mod != null ? __create(__getProtoOf(mod)) : {}; + const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target; + for (let key of __getOwnPropNames(mod)) + if (!__hasOwnProp.call(to, key)) + __defProp(to, key, { + get: () => mod[key], + enumerable: true + }); + return to; +}; +var __moduleCache = /* @__PURE__ */ new WeakMap; +var __toCommonJS = (from) => { + var entry = __moduleCache.get(from), desc; + if (entry) + return entry; + entry = __defProp({}, "__esModule", { value: true }); + if (from && typeof from === "object" || typeof from === "function") + __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, { + get: () => from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + })); + __moduleCache.set(from, entry); + return entry; +}; +var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { + get: all[name], + enumerable: true, + configurable: true, + set: (newValue) => all[name] = () => newValue + }); +}; +var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res); +var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] +}) : x)(function(x) { + if (typeof require !== "undefined") + return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); +}); + +// node_modules/@datkat21/html/dist/html.js +/*! +Html library by datkat21 on GitHub. Licensed under MIT +https://github.com/datkat21/html +!*/ + +class Html { + elm; + constructor(elm) { + if (elm instanceof HTMLElement) + this.elm = elm; + else + this.elm = document.createElement(elm || "div"); + } + text(val) { + this.elm.innerText = val; + return this; + } + html(val) { + this.elm.innerHTML = val; + return this; + } + cleanup() { + this.elm.remove(); + return this; + } + query(selector) { + return this.elm.querySelector(selector); + } + qs(query) { + if (this.elm.querySelector(query)) + return Html.from(this.elm.querySelector(query)); + else + return null; + } + qsa(query) { + if (this.elm.querySelector(query)) + return Array.from(this.elm.querySelectorAll(query)).map((e) => Html.from(e)); + else + return null; + } + id(val) { + this.elm.id = val; + return this; + } + class(...val) { + for (let i = 0;i < val.length; i++) + this.elm.classList.toggle(val[i]); + return this; + } + classOn(...val) { + for (let i = 0;i < val.length; i++) + this.elm.classList.add(val[i]); + return this; + } + classOff(...val) { + for (let i = 0;i < val.length; i++) + this.elm.classList.remove(val[i]); + return this; + } + style(obj) { + for (const key of Object.keys(obj)) + this.elm.style.setProperty(key, obj[key]); + return this; + } + styleJs(obj) { + for (const key of Object.keys(obj)) + this.elm.style[key] = obj[key]; + return this; + } + on(ev, cb) { + this.elm.addEventListener(ev, cb); + return this; + } + un(ev, cb) { + this.elm.removeEventListener(ev, cb); + return this; + } + getElement(element) { + let p = element instanceof Html ? element.elm : element; + if (typeof element === "string") + p = document.querySelector(element); + if (p instanceof HTMLElement) + return p; + else + throw new Error("Invalid element type."); + } + appendTo(parent) { + let p = this.getElement(parent); + if (p instanceof HTMLElement) + p.appendChild(this.elm); + else + throw new Error("Invalid parent element, exausted 3 checks."); + return this; + } + prependTo(parent) { + let p = this.getElement(parent); + if (p instanceof HTMLElement) + p.prepend(this.elm); + return this; + } + append(elem) { + let e = this.getElement(elem); + if (e instanceof HTMLElement) + this.elm.appendChild(e); + else if (typeof elem === "string") { + const newElem = document.createElement(elem); + this.elm.appendChild(newElem); + return new Html(newElem.tagName); + } + return this; + } + prepend(elem) { + let e = this.getElement(elem); + if (e instanceof HTMLElement) + this.elm.prepend(e); + else if (typeof elem === "string") { + const newElem = document.createElement(elem); + this.elm.prepend(newElem); + return new Html(newElem.tagName); + } + return this; + } + appendMany(...elements) { + for (const elem of elements) + this.append(elem); + return this; + } + prependMany(...elements) { + for (const elem of elements) + this.prepend(elem); + return this; + } + clear() { + this.elm.innerHTML = ""; + return this; + } + attr(obj) { + for (let key in obj) + if (obj[key] !== null && obj[key] !== undefined) + this.elm.setAttribute(key, obj[key]); + else + this.elm.removeAttribute(key); + return this; + } + val(str) { + this.elm.value = str; + return this; + } + getText() { + return this.elm.innerText; + } + getHtml() { + return this.elm.innerHTML; + } + getValue() { + return this.elm.value; + } + swapRef(elm) { + this.elm = elm; + return this; + } + static from(elm) { + const qs = () => Html.qs(elm); + if (typeof elm === "string") + return qs(); + return new Html(elm); + } + static qs(query) { + if (document.querySelector(query)) + return Html.from(document.querySelector(query)); + return null; + } + static qsa(query) { + if (document.querySelector(query)) + return Array.from(document.querySelectorAll(query)).map((e) => Html.from(e)); + return null; + } +} + +// src/popup.ts +(() => { + if (!window.opener) + return document.write(); + else { + let cancel = function() { + window.opener.postMessage({ type: "miic-auth-finalize", canceled: true }, "*"); + close(); + }; + let params = new URLSearchParams(location.search); + const title = params.get("page_title"); + if (title === null) + return; + const req = params.get("type"); + if (req === null) + return; + let permissions = []; + switch (req) { + case "library" /* Library */: + permissions.push("Personal Mii"); + permissions.push("Library"); + break; + case "personal_mii_only" /* PersonalMiiOnly */: + permissions.push("Personal Mii"); + break; + default: + return; + } + async function authorize() { + let infoJson; + switch (req) { + case "library" /* Library */: + infoJson = await fetch("/api/me").then((r) => r.json()); + if (infoJson.personal_mii.error) + infoJson.personal_mii = null; + if (infoJson.library) + infoJson.library = JSON.parse(infoJson.library); + break; + case "personal_mii_only" /* PersonalMiiOnly */: + let personal_mii = await fetch("/api/personal_mii").then((r) => r.json()); + if (personal_mii.error) + personal_mii = null; + infoJson = { personal_mii }; + break; + default: + window.opener.postMessage({ type: "miic-auth-finalize", canceled: true }, "*"); + close(); + return; + } + window.opener.postMessage({ type: "miic-auth-finalize", canceled: false, data: infoJson }, "*"); + close(); + } + new Html("div").class("popup").appendMany(new Html("span").class("header").appendMany(new Html("span").class("title").text(title), new Html("br"), new Html("span").text("would like to access your Mii Creator data")), new Html("ul").class("permissions").appendMany(...permissions.map((n) => new Html("li").text(n))), new Html("span").class("confirmation").text("Is this OK?"), new Html("div").style({ display: "flex", gap: "1rem" }).appendMany(new Html("button").class("button").text("Cancel").on("click", cancel), new Html("button").class("button", "primary").text("Authorize").on("click", authorize))).appendTo("body"); + } +})(); diff --git a/public/dist/worker.js b/public/dist/worker.js index baaec37..d848b3b 100644 --- a/public/dist/worker.js +++ b/public/dist/worker.js @@ -1,10100 +1,145843 @@ -var k$=Object.create;var{getPrototypeOf:S$,defineProperty:b6,getOwnPropertyNames:b7,getOwnPropertyDescriptor:T$}=Object,f7=Object.prototype.hasOwnProperty;var z$=(A,Q,E)=>{E=A!=null?k$(S$(A)):{};let B=Q||!A||!A.__esModule?b6(E,"default",{value:A,enumerable:!0}):E;for(let I of b7(A))if(!f7.call(B,I))b6(B,I,{get:()=>A[I],enumerable:!0});return B},x7=/*@__PURE__*/new WeakMap,gz=(A)=>{var Q=x7.get(A),E;if(Q)return Q;if(Q=b6({},"__esModule",{value:!0}),A&&typeof A==="object"||typeof A==="function")b7(A).map((B)=>!f7.call(Q,B)&&b6(Q,B,{get:()=>A[B],enumerable:!(E=T$(A,B))||E.enumerable}));return x7.set(A,Q),Q},P$=(A,Q)=>()=>(Q||A((Q={exports:{}}).exports,Q),Q.exports);var rU=(A,Q)=>{for(var E in Q)b6(A,E,{get:Q[E],enumerable:!0,configurable:!0,set:(B)=>Q[E]=()=>B})};var V$=(A,Q)=>()=>(A&&(Q=A(A=0)),Q);var xz=/*@__PURE__*/((A)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy(A,{get:(Q,E)=>(typeof require!=="undefined"?require:Q)[E]}):A)(function(A){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+A+'" is not supported')});var uN=P$((mz,BU)=>{/*! - * The following is a version of the struct-fu library - * fork by ariankordi: https://github.com/ariankordi/struct-fu - * with the following changes made for code size: - * Added: _.uintptr, mapping to _.uint32le (with WASM in mind) - * Added (TODO): add JSDoc StructInstance template - * Removed: Polyfills Function.prototype.bind, TextEncoder/TextDecoder - * Removed: bitfield, bitfieldLE... - * Removed: char16be, swapBytesPairs - * Removed: 64-bit types, 16-bit float - * Modified: addField (no bit handling), _.struct (rm "aligned bitfield" message) - */var MQ={};function IU(A){return new Uint8Array(new ArrayBuffer(A))}function UH(A){var Q=Array.prototype.slice.call(arguments,1);return Q.forEach(function(E){Object.keys(E).forEach(function(B){A[B]=E[B]})}),A}function bI(A,Q){return A.bytes+=Q.size,A}function CU(A,Q){var E=typeof Q==="number"?UH({name:A.name,field:A,valueFromBytes:function(B,I){I||(I={bytes:0,bits:0});var C=new Array(Q);for(var K=0,J=C.length;K>8&255}return E}});function tE(A,Q,E){var B="get"+A,I="set"+A;return Q||(Q=+A.match(/\d+/)[0]/8),function(C,K){if(typeof C!=="string")K=C,C=null;return CU({valueFromBytes:function(J,U){U||(U={bytes:0});var Y=J instanceof ArrayBuffer?new Uint8Array(J):J,H=new DataView(Y.buffer,Y.byteOffset,Y.byteLength),R=H[B](U.bytes,E);return bI(U,this),R},bytesFromValue:function(J,U,Y){J||(J=0),U||(U=IU(this.size)),Y||(Y={bytes:0});var H=U instanceof ArrayBuffer?new Uint8Array(U):U,R=new DataView(H.buffer,H.byteOffset,H.byteLength);return R[I](Y.bytes,J,E),bI(Y,this),U},size:Q,name:C},K)}}MQ.uint8=tE("Uint8",1,!1);MQ.uint16=tE("Uint16",2,!1);MQ.uint32=tE("Uint32",4,!1);MQ.uint16le=tE("Uint16",2,!0);MQ.uint32le=tE("Uint32",4,!0);MQ.uintptr=MQ.uint32le;MQ.int8=tE("Int8",1,!1);MQ.int16=tE("Int16",2,!1);MQ.int32=tE("Int32",4,!1);MQ.int16le=tE("Int16",2,!0);MQ.int32le=tE("Int32",4,!0);MQ.float32=tE("Float32",4,!1);MQ.float32le=tE("Float32",4,!0);MQ.derive=function(A,Q,E){return function(B,I){if(typeof B!=="string")I=B,B=null;return CU(UH({valueFromBytes:function(C,K){return E(A.valueFromBytes(C,K))},bytesFromValue:function(C,K,J){return A.bytesFromValue(Q(C),K,J)},name:B},"width"in A?{width:A.width}:{size:A.size}),I)}};if(typeof BU!=="undefined"&&BU.exports)BU.exports=MQ;else window._=MQ});var X$={};rU(X$,{default:()=>hz});function IT(A){if(GA.locateFile)return GA.locateFile(A,qI);return qI+A}function Y$(){var A=nU.buffer;GA.HEAP8=KT=new Int8Array(A),GA.HEAP16=JT=new Int16Array(A),GA.HEAPU8=v7=new Uint8Array(A),GA.HEAPU16=UT=new Uint16Array(A),GA.HEAP32=YT=new Int32Array(A),GA.HEAPU32=OT=new Uint32Array(A),GA.HEAPF32=HT=new Float32Array(A),GA.HEAPF64=ZT=new Float64Array(A)}function NT(){if(GA.preRun){if(typeof GA.preRun=="function")GA.preRun=[GA.preRun];while(GA.preRun.length)XT(GA.preRun.shift())}h7(O$)}function GT(){RT=!0,h7(H$)}function WT(){if(GA.postRun){if(typeof GA.postRun=="function")GA.postRun=[GA.postRun];while(GA.postRun.length)LT(GA.postRun.shift())}h7(Z$)}function XT(A){O$.unshift(A)}function $T(A){H$.unshift(A)}function LT(A){Z$.unshift(A)}function qT(A){B8++,GA.monitorRunDependencies?.(B8)}function FT(A){if(B8--,GA.monitorRunDependencies?.(B8),B8==0){if(j7!==null)clearInterval(j7),j7=null;if(cK){var Q=cK;cK=null,Q()}}}function R$(A){GA.onAbort?.(A),A="Aborted("+A+")",lK(A),U$=!0,CT=1,A+=". Build with -sASSERTIONS for more info.";var Q=new WebAssembly.RuntimeError(A);throw Q}function MT(){var A="/dist/ffl-emscripten.wasm";if(!N$(A))return IT(A);return A}function E$(A){if(A==dU&&dK)return new Uint8Array(dK);if(Q$)return Q$(A);throw"both async and sync fetching of the wasm failed"}function wT(A){if(!dK)return J$(A).then((Q)=>new Uint8Array(Q),()=>E$(A));return Promise.resolve().then(()=>E$(A))}function B$(A,Q,E){return wT(A).then((B)=>WebAssembly.instantiate(B,Q)).then(E,(B)=>{lK(`failed to asynchronously prepare wasm: ${B}`),R$(B)})}function _T(A,Q,E,B){if(!A&&typeof WebAssembly.instantiateStreaming=="function"&&!N$(Q)&&typeof fetch=="function")return fetch(Q,{credentials:"same-origin"}).then((I)=>{var C=WebAssembly.instantiateStreaming(I,E);return C.then(B,function(K){return lK(`wasm streaming compile failed: ${K}`),lK("falling back to ArrayBuffer instantiation"),B$(Q,E,B)})});return B$(Q,E,B)}function kT(){return{a:mT}}function ST(){var A=kT();function Q(B,I){return X0=B.exports,nU=X0.e,Y$(),I8=X0.O,$T(X0.f),FT("wasm-instantiate"),X0}qT("wasm-instantiate");function E(B){Q(B.instance)}if(GA.instantiateWasm)try{return GA.instantiateWasm(A,Q)}catch(B){return lK(`Module.instantiateWasm callback failed with error: ${B}`),!1}if(!dU)dU=MT();return _T(dK,dU,A,E),{}}function W$(){if(B8>0)return;if(NT(),B8>0)return;function A(){if(sU)return;if(sU=!0,GA.calledRun=!0,U$)return;GT(),GA.onRuntimeInitialized?.(),WT()}if(GA.setStatus)GA.setStatus("Running..."),setTimeout(function(){setTimeout(function(){GA.setStatus("")},1),A()},1);else A()}var GA,AT=!0,A$=!1,K$,QT,ET="./this.program",BT=(A,Q)=>{throw Q},qI="",J$,Q$,zr,lK,dK,nU,U$=!1,CT,KT,v7,JT,UT,YT,OT,HT,ZT,O$,H$,Z$,RT=!1,B8=0,j7=null,cK=null,DT="data:application/octet-stream;base64,",N$=(A)=>A.startsWith(DT),dU,h7=(A)=>{while(A.length>0)A.shift()(GA)},Pr,TT=()=>{R$("")},zT=(A,Q,E)=>v7.copyWithin(A,Q,Q+E),PT=()=>Math.random(),VT=()=>2147483648,jT=(A)=>{var Q=nU.buffer,E=(A-Q.byteLength+65535)/65536;try{return nU.grow(E),Y$(),1}catch(B){}},vT=(A)=>{var Q=v7.length;A>>>=0;var E=VT();if(A>E)return!1;var B=(U,Y)=>U+(Y-U%Y)%Y;for(var I=1;I<=4;I*=2){var C=Q*(1+0.2/I);C=Math.min(C,A+100663296);var K=Math.min(E,B(Math.max(A,C),65536)),J=jT(K);if(J)return!0}return!1},G$=(A,Q)=>{if(A<128)Q.push(A);else Q.push(A%128|128,A>>7)},hT=(A)=>{var Q={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},E={parameters:[],results:A[0]=="v"?[]:[Q[A[0]]]};for(var B=1;B{var E=A.slice(0,1),B=A.slice(1),I={i:127,p:127,j:126,f:125,d:124,e:111};Q.push(96),G$(B.length,Q);for(var C=0;C{if(typeof WebAssembly.Function=="function")return new WebAssembly.Function(hT(Q),A);var E=[1];yT(Q,E);var B=[0,97,115,109,1,0,0,0,1];G$(E.length,B),B.push(...E),B.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var I=new WebAssembly.Module(new Uint8Array(B)),C=new WebAssembly.Instance(I,{e:{f:A}}),K=C.exports.f;return K},mK,I8,xT=(A)=>{var Q=mK[A];if(!Q){if(A>=mK.length)mK.length=A+1;mK[A]=Q=I8.get(A)}return Q},bT=(A,Q)=>{if(j6)for(var E=A;E{if(!j6)j6=/*@__PURE__*/new WeakMap,bT(0,I8.length);return j6.get(A)||0},I$,uT=()=>{if(I$.length)return I$.pop();try{I8.grow(1)}catch(A){if(!(A instanceof RangeError))throw A;throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return I8.length-1},C$=(A,Q)=>{I8.set(A,Q),mK[A]=I8.get(A)},pT=(A,Q)=>{var E=fT(A);if(E)return E;var B=uT();try{C$(B,A)}catch(C){if(!(C instanceof TypeError))throw C;var I=gT(A,Q);C$(B,I)}return j6.set(A,B),B},mT,X0,cT,lT,dT,nT,sT,iT,oT,rT,aT,tT,eT,Az,Qz,Ez,Bz,Iz,Cz,Kz,Jz,Uz,Yz,Oz,Hz,Zz,Rz,Nz,Gz,Wz,Xz,$z,Lz,qz,Fz,Dz,Mz,wz,_z,kz,Sz,Tz,zz,Pz,Vz,jz,vz,sU,hz;var $$=V$(()=>{GA=typeof GA!="undefined"?GA:{},K$=Object.assign({},GA),QT=[];if(AT||A$){if(A$)qI=self.location.href;else if(typeof document!="undefined"&&document.currentScript)qI=document.currentScript.src;if(qI.startsWith("blob:"))qI="";else qI=qI.substr(0,qI.replace(/[?#].*/,"").lastIndexOf("/")+1);J$=(A)=>fetch(A,{credentials:"same-origin"}).then((Q)=>{if(Q.ok)return Q.arrayBuffer();return Promise.reject(new Error(Q.status+" : "+Q.url))})}zr=GA.print||console.log.bind(console),lK=GA.printErr||console.error.bind(console);Object.assign(GA,K$);K$=null;if(GA.arguments)QT=GA.arguments;if(GA.thisProgram)ET=GA.thisProgram;if(GA.quit)BT=GA.quit;if(GA.wasmBinary)dK=GA.wasmBinary;O$=[],H$=[],Z$=[];Pr=GA.noExitRuntime||!0,mK=[],I$=[],mT={a:TT,c:zT,d:PT,b:vT},X0=ST(),cT=GA._FFLInitCharModelCPUStepWithCallback=(A,Q,E,B)=>(cT=GA._FFLInitCharModelCPUStepWithCallback=X0.g)(A,Q,E,B),lT=GA._FFLInitCharModelCPUStep=(A,Q,E)=>(lT=GA._FFLInitCharModelCPUStep=X0.h)(A,Q,E),dT=GA._FFLDeleteCharModel=(A)=>(dT=GA._FFLDeleteCharModel=X0.i)(A),nT=GA._FFLGetDrawParamOpaFaceline=(A)=>(nT=GA._FFLGetDrawParamOpaFaceline=X0.j)(A),sT=GA._FFLGetDrawParamOpaBeard=(A)=>(sT=GA._FFLGetDrawParamOpaBeard=X0.k)(A),iT=GA._FFLGetDrawParamOpaNose=(A)=>(iT=GA._FFLGetDrawParamOpaNose=X0.l)(A),oT=GA._FFLGetDrawParamOpaForehead=(A)=>(oT=GA._FFLGetDrawParamOpaForehead=X0.m)(A),rT=GA._FFLGetDrawParamOpaHair=(A)=>(rT=GA._FFLGetDrawParamOpaHair=X0.n)(A),aT=GA._FFLGetDrawParamOpaCap=(A)=>(aT=GA._FFLGetDrawParamOpaCap=X0.o)(A),tT=GA._FFLGetDrawParamXluMask=(A)=>(tT=GA._FFLGetDrawParamXluMask=X0.p)(A),eT=GA._FFLGetDrawParamXluNoseLine=(A)=>(eT=GA._FFLGetDrawParamXluNoseLine=X0.q)(A),Az=GA._FFLGetDrawParamXluGlass=(A)=>(Az=GA._FFLGetDrawParamXluGlass=X0.r)(A),Qz=GA._FFLSetExpression=(A,Q)=>(Qz=GA._FFLSetExpression=X0.s)(A,Q),Ez=GA._FFLGetExpression=(A)=>(Ez=GA._FFLGetExpression=X0.t)(A),Bz=GA._FFLSetViewModelType=(A,Q)=>(Bz=GA._FFLSetViewModelType=X0.u)(A,Q),Iz=GA._FFLGetBoundingBox=(A,Q)=>(Iz=GA._FFLGetBoundingBox=X0.v)(A,Q),Cz=GA._FFLIsAvailableExpression=(A,Q)=>(Cz=GA._FFLIsAvailableExpression=X0.w)(A,Q),Kz=GA._FFLSetCoordinate=(A,Q)=>(Kz=GA._FFLSetCoordinate=X0.x)(A,Q),Jz=GA._FFLSetScale=(A)=>(Jz=GA._FFLSetScale=X0.y)(A),Uz=GA._FFLiGetRandomCharInfo=(A,Q,E,B)=>(Uz=GA._FFLiGetRandomCharInfo=X0.z)(A,Q,E,B),Yz=GA._FFLpGetStoreDataFromCharInfo=(A,Q)=>(Yz=GA._FFLpGetStoreDataFromCharInfo=X0.A)(A,Q),Oz=GA._FFLpGetCharInfoFromStoreData=(A,Q)=>(Oz=GA._FFLpGetCharInfoFromStoreData=X0.B)(A,Q),Hz=GA._FFLGetAdditionalInfo=(A,Q,E,B,I)=>(Hz=GA._FFLGetAdditionalInfo=X0.C)(A,Q,E,B,I),Zz=GA._FFLInitRes=(A,Q)=>(Zz=GA._FFLInitRes=X0.D)(A,Q),Rz=GA._FFLInitResGPUStep=()=>(Rz=GA._FFLInitResGPUStep=X0.E)(),Nz=GA._FFLExit=()=>(Nz=GA._FFLExit=X0.F)(),Gz=GA._FFLIsAvailable=()=>(Gz=GA._FFLIsAvailable=X0.G)(),Wz=GA._FFLGetFavoriteColor=(A,Q)=>(Wz=GA._FFLGetFavoriteColor=X0.H)(A,Q),Xz=GA._FFLSetLinearGammaMode=(A)=>(Xz=GA._FFLSetLinearGammaMode=X0.I)(A),$z=GA._FFLGetFacelineColor=(A,Q)=>($z=GA._FFLGetFacelineColor=X0.J)(A,Q),Lz=GA._FFLSetTextureFlipY=(A)=>(Lz=GA._FFLSetTextureFlipY=X0.K)(A),qz=GA._FFLSetNormalIsSnorm8_8_8_8=(A)=>(qz=GA._FFLSetNormalIsSnorm8_8_8_8=X0.L)(A),Fz=GA._FFLSetFrontCullForFlipX=(A)=>(Fz=GA._FFLSetFrontCullForFlipX=X0.M)(A),Dz=GA._FFLSetTextureCallback=(A)=>(Dz=GA._FFLSetTextureCallback=X0.N)(A),Mz=GA._FFLiDeleteTempObjectMaskTextures=(A,Q,E)=>(Mz=GA._FFLiDeleteTempObjectMaskTextures=X0.P)(A,Q,E),wz=GA._FFLiDeleteTempObjectFacelineTexture=(A,Q,E)=>(wz=GA._FFLiDeleteTempObjectFacelineTexture=X0.Q)(A,Q,E),_z=GA._FFLiDeleteTextureTempObject=(A)=>(_z=GA._FFLiDeleteTextureTempObject=X0.R)(A),kz=GA._FFLiiGetEyeRotateOffset=(A)=>(kz=GA._FFLiiGetEyeRotateOffset=X0.S)(A),Sz=GA._FFLiiGetEyebrowRotateOffset=(A)=>(Sz=GA._FFLiiGetEyebrowRotateOffset=X0.T)(A),Tz=GA._FFLiInvalidateTempObjectFacelineTexture=(A)=>(Tz=GA._FFLiInvalidateTempObjectFacelineTexture=X0.U)(A),zz=GA._FFLiInvalidatePartsTextures=(A)=>(zz=GA._FFLiInvalidatePartsTextures=X0.V)(A),Pz=GA._FFLiInvalidateRawMask=(A)=>(Pz=GA._FFLiInvalidateRawMask=X0.W)(A),Vz=GA._FFLiVerifyCharInfoWithReason=(A,Q)=>(Vz=GA._FFLiVerifyCharInfoWithReason=X0.X)(A,Q),jz=GA._malloc=(A)=>(jz=GA._malloc=X0.Y)(A),vz=GA._free=(A)=>(vz=GA._free=X0.Z)(A);GA.addFunction=pT;cK=function A(){if(!sU)W$();if(!sU)cK=A};if(GA.preInit){if(typeof GA.preInit=="function")GA.preInit=[GA.preInit];while(GA.preInit.length>0)GA.preInit.pop()()}W$();hz={Module:GA}});var QK={};rU(QK,{createCanvasElement:()=>LO,ZeroStencilOp:()=>NR,ZeroSlopeEnding:()=>JR,ZeroFactor:()=>$E,ZeroCurvatureEnding:()=>KR,WrapAroundEnding:()=>UR,WireframeGeometry:()=>r8,WebXRController:()=>m8,WebGPUCoordinateSystem:()=>xR,WebGLUtils:()=>xN,WebGLRenderer:()=>AK,WebGLRenderTarget:()=>Q0,WebGLCubeRenderTarget:()=>DC,WebGLCoordinateSystem:()=>L9,WebGLArrayRenderTarget:()=>qO,WebGL3DRenderTarget:()=>FO,VideoTexture:()=>_9,VideoFrameTexture:()=>kO,VectorKeyframeTrack:()=>YE,Vector4:()=>MA,Vector3:()=>y,Vector2:()=>AA,VSMShadowMap:()=>RB,UnsignedShortType:()=>hB,UnsignedShort5551Type:()=>eJ,UnsignedShort4444Type:()=>tJ,UnsignedIntType:()=>$1,UnsignedInt5999Type:()=>EO,UnsignedInt248Type:()=>VE,UnsignedByteType:()=>x0,UniformsUtils:()=>oA,UniformsLib:()=>vA,UniformsGroup:()=>pO,Uniform:()=>rC,Uint8ClampedBufferAttribute:()=>DO,Uint8BufferAttribute:()=>qC,Uint32BufferAttribute:()=>FC,Uint16BufferAttribute:()=>VI,UVMapping:()=>jB,TubeGeometry:()=>uC,TrianglesDrawMode:()=>W9,TriangleStripDrawMode:()=>x8,TriangleFanDrawMode:()=>z1,Triangle:()=>PQ,TorusKnotGeometry:()=>fC,TorusGeometry:()=>o8,TimestampQuery:()=>bR,TextureUtils:()=>BN,TextureLoader:()=>nQ,Texture:()=>EQ,TetrahedronGeometry:()=>bC,TangentSpaceNormalMap:()=>KO,TOUCH:()=>IC,SubtractiveBlending:()=>uJ,SubtractEquation:()=>uY,StringKeyframeTrack:()=>JI,StreamReadUsage:()=>jR,StreamDrawUsage:()=>zR,StreamCopyUsage:()=>yR,StereoCamera:()=>E6,StaticReadUsage:()=>PR,StaticDrawUsage:()=>TR,StaticCopyUsage:()=>vR,SrcColorFactor:()=>lY,SrcAlphaSaturateFactor:()=>sY,SrcAlphaFactor:()=>EE,SpriteMaterial:()=>y1,Sprite:()=>c8,SpotLightHelper:()=>lO,SpotLight:()=>UI,SplineCurve:()=>VC,SphericalHarmonics3:()=>lC,Spherical:()=>I6,SphereGeometry:()=>FE,Sphere:()=>KQ,Source:()=>OB,SkinnedMesh:()=>jI,SkeletonHelper:()=>i9,Skeleton:()=>gB,ShortType:()=>QO,ShapeUtils:()=>WE,ShapePath:()=>aC,ShapeGeometry:()=>xC,Shape:()=>TB,ShadowMaterial:()=>v9,ShaderMaterial:()=>bA,ShaderLib:()=>CE,ShaderChunk:()=>G0,Scene:()=>yQ,SRGBTransfer:()=>IQ,SRGBColorSpace:()=>N0,SIGNED_RED_RGTC1_Format:()=>R9,SIGNED_RED_GREEN_RGTC2_Format:()=>G9,RingGeometry:()=>gC,ReverseSubtractEquation:()=>pY,ReplaceStencilOp:()=>WR,RepeatWrapping:()=>BQ,RenderTargetArray:()=>uO,RenderTarget3D:()=>fO,RenderTarget:()=>u8,ReinhardToneMapping:()=>dJ,RedIntegerFormat:()=>NC,RedFormat:()=>SQ,RectAreaLight:()=>cC,Raycaster:()=>bE,Ray:()=>qE,RawShaderMaterial:()=>II,RGIntegerFormat:()=>GC,RGFormat:()=>jE,RGDepthPacking:()=>RR,RGB_S3TC_DXT1_Format:()=>j8,RGB_PVRTC_4BPPV1_Format:()=>F1,RGB_PVRTC_2BPPV1_Format:()=>WC,RGB_ETC2_Format:()=>h8,RGB_ETC1_Format:()=>M1,RGB_BPTC_UNSIGNED_Format:()=>S1,RGB_BPTC_SIGNED_Format:()=>$C,RGBIntegerFormat:()=>QR,RGBFormat:()=>IO,RGBDepthPacking:()=>ZR,RGBA_S3TC_DXT5_Format:()=>PI,RGBA_S3TC_DXT3_Format:()=>v8,RGBA_S3TC_DXT1_Format:()=>q1,RGBA_PVRTC_4BPPV1_Format:()=>D1,RGBA_PVRTC_2BPPV1_Format:()=>XC,RGBA_ETC2_EAC_Format:()=>y8,RGBA_BPTC_Format:()=>k1,RGBA_ASTC_8x8_Format:()=>K9,RGBA_ASTC_8x6_Format:()=>C9,RGBA_ASTC_8x5_Format:()=>I9,RGBA_ASTC_6x6_Format:()=>_1,RGBA_ASTC_6x5_Format:()=>B9,RGBA_ASTC_5x5_Format:()=>E9,RGBA_ASTC_5x4_Format:()=>Q9,RGBA_ASTC_4x4_Format:()=>w1,RGBA_ASTC_12x12_Format:()=>Z9,RGBA_ASTC_12x10_Format:()=>H9,RGBA_ASTC_10x8_Format:()=>Y9,RGBA_ASTC_10x6_Format:()=>U9,RGBA_ASTC_10x5_Format:()=>J9,RGBA_ASTC_10x10_Format:()=>O9,RGBAIntegerFormat:()=>A9,RGBAFormat:()=>V0,RGBADepthPacking:()=>b8,REVISION:()=>ZB,RED_RGTC1_Format:()=>CO,RED_GREEN_RGTC2_Format:()=>N9,QuaternionLinearInterpolant:()=>f9,QuaternionKeyframeTrack:()=>ME,Quaternion:()=>J0,QuadraticBezierCurve3:()=>PC,QuadraticBezierCurve:()=>zC,PropertyMixer:()=>d9,PropertyBinding:()=>T0,PositionalAudio:()=>hO,PolyhedronGeometry:()=>BI,PolarGridHelper:()=>sO,PointsMaterial:()=>aE,Points:()=>GB,PointLightHelper:()=>dO,PointLight:()=>WB,PlaneHelper:()=>aO,PlaneGeometry:()=>dQ,Plane:()=>UQ,PerspectiveCamera:()=>v0,Path:()=>TI,PMREMGenerator:()=>QU,PCFSoftShadowMap:()=>fY,PCFShadowMap:()=>fJ,OrthographicCamera:()=>HE,OneMinusSrcColorFactor:()=>dY,OneMinusSrcAlphaFactor:()=>iE,OneMinusDstColorFactor:()=>nY,OneMinusDstAlphaFactor:()=>N1,OneMinusConstantColorFactor:()=>oY,OneMinusConstantAlphaFactor:()=>aY,OneFactor:()=>PE,OctahedronGeometry:()=>x1,ObjectSpaceNormalMap:()=>JO,ObjectLoader:()=>VO,Object3D:()=>I0,NumberKeyframeTrack:()=>zE,NotEqualStencilFunc:()=>_R,NotEqualDepth:()=>HC,NotEqualCompare:()=>NO,NormalBlending:()=>zB,NormalAnimationBlendMode:()=>YR,NoToneMapping:()=>VB,NoColorSpace:()=>YQ,NoBlending:()=>H0,NeverStencilFunc:()=>FR,NeverDepth:()=>CC,NeverCompare:()=>OO,NeutralToneMapping:()=>rJ,NearestMipmapNearestFilter:()=>X1,NearestMipmapLinearFilter:()=>vB,NearestMipMapNearestFilter:()=>tZ,NearestMipMapLinearFilter:()=>eZ,NearestFilter:()=>Z0,MultiplyOperation:()=>mJ,MultiplyBlending:()=>pJ,MixOperation:()=>tY,MirroredRepeatWrapping:()=>OE,MinEquation:()=>mY,MeshToonMaterial:()=>h9,MeshStandardMaterial:()=>aQ,MeshPhysicalMaterial:()=>fQ,MeshPhongMaterial:()=>DE,MeshNormalMaterial:()=>gE,MeshMatcapMaterial:()=>y9,MeshLambertMaterial:()=>CI,MeshDistanceMaterial:()=>pC,MeshDepthMaterial:()=>hI,MeshBasicMaterial:()=>_0,Mesh:()=>xA,MaxEquation:()=>cY,Matrix4:()=>RA,Matrix3:()=>E0,Matrix2:()=>s9,MathUtils:()=>o0,MaterialLoader:()=>dC,Material:()=>$Q,MOUSE:()=>T8,LuminanceFormat:()=>L1,LuminanceAlphaFormat:()=>ZC,LoopRepeat:()=>BR,LoopPingPong:()=>IR,LoopOnce:()=>ER,LoadingManager:()=>t8,LoaderUtils:()=>QE,Loader:()=>C0,LinearTransfer:()=>LC,LinearToneMapping:()=>lJ,LinearSRGBColorSpace:()=>b0,LinearMipmapNearestFilter:()=>AI,LinearMipmapLinearFilter:()=>hQ,LinearMipMapNearestFilter:()=>AR,LinearMipMapLinearFilter:()=>eY,LinearInterpolant:()=>mC,LinearFilter:()=>L0,LineSegments:()=>RQ,LineLoop:()=>l8,LineDashedMaterial:()=>g9,LineCurve3:()=>z9,LineCurve:()=>TC,LineBasicMaterial:()=>p0,Line3:()=>$B,Line:()=>VQ,LightProbe:()=>Q6,Light:()=>uB,LessStencilFunc:()=>DR,LessEqualStencilFunc:()=>MR,LessEqualDepth:()=>z8,LessEqualCompare:()=>X9,LessDepth:()=>JC,LessCompare:()=>HO,Layers:()=>j1,LatheGeometry:()=>n8,LOD:()=>M9,KeyframeTrack:()=>xE,KeepStencilOp:()=>GR,InvertStencilOp:()=>qR,InterpolateSmooth:()=>CR,InterpolateLinear:()=>T1,InterpolateDiscrete:()=>g8,Interpolant:()=>KI,InterleavedBufferAttribute:()=>xQ,InterleavedBuffer:()=>hE,IntType:()=>aJ,Int8BufferAttribute:()=>p8,Int32BufferAttribute:()=>F9,Int16BufferAttribute:()=>MO,InstancedMesh:()=>vI,InstancedInterleavedBuffer:()=>B6,InstancedBufferGeometry:()=>nC,InstancedBufferAttribute:()=>HB,IncrementWrapStencilOp:()=>$R,IncrementStencilOp:()=>UO,ImageUtils:()=>q9,ImageLoader:()=>R1,ImageBitmapLoader:()=>iC,IcosahedronGeometry:()=>yC,HemisphereLightHelper:()=>nO,HemisphereLight:()=>p9,HalfFloatType:()=>sA,Group:()=>i0,GridHelper:()=>o9,GreaterStencilFunc:()=>wR,GreaterEqualStencilFunc:()=>kR,GreaterEqualDepth:()=>YC,GreaterEqualCompare:()=>GO,GreaterDepth:()=>OC,GreaterCompare:()=>RO,GLSL3:()=>$9,GLSL1:()=>gR,GLBufferAttribute:()=>mO,Frustum:()=>xB,FrontSide:()=>jQ,FramebufferTexture:()=>d8,FogExp2:()=>MC,Fog:()=>wC,FloatType:()=>m0,Float32BufferAttribute:()=>PA,Float16BufferAttribute:()=>wO,FileLoader:()=>U0,ExtrudeGeometry:()=>i8,EventDispatcher:()=>rE,Euler:()=>DQ,EquirectangularRefractionMapping:()=>P8,EquirectangularReflectionMapping:()=>W1,EqualStencilFunc:()=>YO,EqualDepth:()=>UC,EqualCompare:()=>ZO,EllipseCurve:()=>g1,EdgesGeometry:()=>V9,DynamicReadUsage:()=>VR,DynamicDrawUsage:()=>f8,DynamicCopyUsage:()=>hR,DstColorFactor:()=>PB,DstAlphaFactor:()=>LE,DoubleSide:()=>y0,DodecahedronGeometry:()=>hC,DiscreteInterpolant:()=>b9,DirectionalLightHelper:()=>iO,DirectionalLight:()=>XB,DetachedBindMode:()=>aZ,DepthTexture:()=>IE,DepthStencilFormat:()=>oE,DepthFormat:()=>RC,DefaultLoadingManager:()=>u9,DecrementWrapStencilOp:()=>LR,DecrementStencilOp:()=>XR,DataUtils:()=>vE,DataTextureLoader:()=>yI,DataTexture:()=>h0,DataArrayTexture:()=>V1,Data3DTexture:()=>NB,Cylindrical:()=>cO,CylinderGeometry:()=>bB,CustomToneMapping:()=>iJ,CustomBlending:()=>vQ,CurvePath:()=>P9,Curve:()=>rQ,CullFaceNone:()=>xY,CullFaceFrontBack:()=>iZ,CullFaceFront:()=>bY,CullFaceBack:()=>bJ,CubicInterpolant:()=>x9,CubicBezierCurve3:()=>T9,CubicBezierCurve:()=>SC,CubeUVReflectionMapping:()=>V8,CubeTextureLoader:()=>PO,CubeTexture:()=>QI,CubeRefractionMapping:()=>zI,CubeReflectionMapping:()=>G1,CubeCamera:()=>D9,Controls:()=>LB,ConstantColorFactor:()=>iY,ConstantAlphaFactor:()=>rY,ConeGeometry:()=>s8,CompressedTextureLoader:()=>e8,CompressedTexture:()=>yE,CompressedCubeTexture:()=>kC,CompressedArrayTexture:()=>_C,ColorManagement:()=>O0,ColorKeyframeTrack:()=>a8,Color:()=>a,Clock:()=>gI,ClampToEdgeWrapping:()=>JQ,CircleGeometry:()=>vC,CineonToneMapping:()=>nJ,CatmullRomCurve3:()=>S9,CapsuleGeometry:()=>jC,CanvasTexture:()=>EI,CameraHelper:()=>oO,Camera:()=>h1,Cache:()=>SB,ByteType:()=>AO,BufferGeometryLoader:()=>sC,BufferGeometry:()=>hA,BufferAttribute:()=>tA,BoxHelper:()=>rO,BoxGeometry:()=>bQ,Box3Helper:()=>r9,Box3:()=>g0,Box2:()=>b1,BooleanKeyframeTrack:()=>fB,Bone:()=>yB,BatchedMesh:()=>w9,BasicShadowMap:()=>oZ,BasicDepthPacking:()=>HR,BackSide:()=>ZQ,AxesHelper:()=>eO,AudioLoader:()=>jO,AudioListener:()=>vO,AudioContext:()=>oC,AudioAnalyser:()=>yO,Audio:()=>l9,AttachedBindMode:()=>rZ,ArrowHelper:()=>tO,ArrayCamera:()=>c9,ArcCurve:()=>k9,AnimationUtils:()=>rR,AnimationObjectGroup:()=>bO,AnimationMixer:()=>xI,AnimationLoader:()=>zO,AnimationClip:()=>oQ,AnimationAction:()=>n9,AmbientLight:()=>A6,AlwaysStencilFunc:()=>SR,AlwaysDepth:()=>KC,AlwaysCompare:()=>WO,AlphaFormat:()=>BO,AgXToneMapping:()=>oJ,AdditiveBlending:()=>XE,AdditiveAnimationBlendMode:()=>OR,AddOperation:()=>cJ,AddEquation:()=>kQ,ACESFilmicToneMapping:()=>sJ});var ZB="173",T8={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},IC={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},xY=0,bJ=1,bY=2,iZ=3,oZ=0,fJ=1,fY=2,RB=3,jQ=0,ZQ=1,y0=2,H0=0,zB=1,XE=2,uJ=3,pJ=4,vQ=5,kQ=100,uY=101,pY=102,mY=103,cY=104,$E=200,PE=201,lY=202,dY=203,EE=204,iE=205,LE=206,N1=207,PB=208,nY=209,sY=210,iY=211,oY=212,rY=213,aY=214,CC=0,KC=1,JC=2,z8=3,UC=4,YC=5,OC=6,HC=7,mJ=0,tY=1,cJ=2,VB=0,lJ=1,dJ=2,nJ=3,sJ=4,iJ=5,oJ=6,rJ=7,rZ="attached",aZ="detached",jB=300,G1=301,zI=302,W1=303,P8=304,V8=306,BQ=1000,JQ=1001,OE=1002,Z0=1003,X1=1004,tZ=1004,vB=1005,eZ=1005,L0=1006,AI=1007,AR=1007,hQ=1008,eY=1008,x0=1009,AO=1010,QO=1011,hB=1012,aJ=1013,$1=1014,m0=1015,sA=1016,tJ=1017,eJ=1018,VE=1020,EO=35902,BO=1021,IO=1022,V0=1023,L1=1024,ZC=1025,RC=1026,oE=1027,SQ=1028,NC=1029,jE=1030,GC=1031,QR=1032,A9=1033,j8=33776,q1=33777,v8=33778,PI=33779,F1=35840,WC=35841,D1=35842,XC=35843,M1=36196,h8=37492,y8=37496,w1=37808,Q9=37809,E9=37810,B9=37811,_1=37812,I9=37813,C9=37814,K9=37815,J9=37816,U9=37817,Y9=37818,O9=37819,H9=37820,Z9=37821,k1=36492,$C=36494,S1=36495,CO=36283,R9=36284,N9=36285,G9=36286,ER=2200,BR=2201,IR=2202,g8=2300,T1=2301,CR=2302,KR=2400,JR=2401,UR=2402,YR=2500,OR=2501,W9=0,x8=1,z1=2,HR=3200,b8=3201,ZR=3202,RR=3203,KO=0,JO=1,YQ="",N0="srgb",b0="srgb-linear",LC="linear",IQ="srgb",NR=0,GR=7680,WR=7681,UO=7682,XR=7683,$R=34055,LR=34056,qR=5386,FR=512,DR=513,YO=514,MR=515,wR=516,_R=517,kR=518,SR=519,OO=512,HO=513,ZO=514,X9=515,RO=516,NO=517,GO=518,WO=519,TR=35044,f8=35048,zR=35040,PR=35045,VR=35049,jR=35041,vR=35046,hR=35050,yR=35042,gR="100",$9="300 es",L9=2000,xR=2001,bR={COMPUTE:"compute",RENDER:"render"};class rE{addEventListener(A,Q){if(this._listeners===void 0)this._listeners={};let E=this._listeners;if(E[A]===void 0)E[A]=[];if(E[A].indexOf(Q)===-1)E[A].push(Q)}hasEventListener(A,Q){let E=this._listeners;if(E===void 0)return!1;return E[A]!==void 0&&E[A].indexOf(Q)!==-1}removeEventListener(A,Q){let E=this._listeners;if(E===void 0)return;let B=E[A];if(B!==void 0){let I=B.indexOf(Q);if(I!==-1)B.splice(I,1)}}dispatchEvent(A){let Q=this._listeners;if(Q===void 0)return;let E=Q[A.type];if(E!==void 0){A.target=this;let B=E.slice(0);for(let I=0,C=B.length;I>8&255]+tQ[A>>16&255]+tQ[A>>24&255]+"-"+tQ[Q&255]+tQ[Q>>8&255]+"-"+tQ[Q>>16&15|64]+tQ[Q>>24&255]+"-"+tQ[E&63|128]+tQ[E>>8&255]+"-"+tQ[E>>16&255]+tQ[E>>24&255]+tQ[B&255]+tQ[B>>8&255]+tQ[B>>16&255]+tQ[B>>24&255]).toLowerCase()}function w0(A,Q,E){return Math.max(Q,Math.min(E,A))}function XO(A,Q){return(A%Q+Q)%Q}function j$(A,Q,E,B,I){return B+(A-Q)*(I-B)/(E-Q)}function v$(A,Q,E){if(A!==Q)return(E-A)/(Q-A);else return 0}function t6(A,Q,E){return(1-E)*A+E*Q}function h$(A,Q,E,B){return t6(A,Q,1-Math.exp(-E*B))}function y$(A,Q=1){return Q-Math.abs(XO(A,Q*2)-Q)}function g$(A,Q,E){if(A<=Q)return 0;if(A>=E)return 1;return A=(A-Q)/(E-Q),A*A*(3-2*A)}function x$(A,Q,E){if(A<=Q)return 0;if(A>=E)return 1;return A=(A-Q)/(E-Q),A*A*A*(A*(A*6-15)+10)}function b$(A,Q){return A+Math.floor(Math.random()*(Q-A+1))}function f$(A,Q){return A+Math.random()*(Q-A)}function u$(A){return A*(0.5-Math.random())}function p$(A){if(A!==void 0)u7=A;let Q=u7+=1831565813;return Q=Math.imul(Q^Q>>>15,Q|1),Q^=Q+Math.imul(Q^Q>>>7,Q|61),((Q^Q>>>14)>>>0)/4294967296}function m$(A){return A*O1}function c$(A){return A*H1}function l$(A){return(A&A-1)===0&&A!==0}function d$(A){return Math.pow(2,Math.ceil(Math.log(A)/Math.LN2))}function n$(A){return Math.pow(2,Math.floor(Math.log(A)/Math.LN2))}function s$(A,Q,E,B,I){let{cos:C,sin:K}=Math,J=C(E/2),U=K(E/2),Y=C((Q+B)/2),H=K((Q+B)/2),R=C((Q-B)/2),O=K((Q-B)/2),N=C((B-Q)/2),$=K((B-Q)/2);switch(I){case"XYX":A.set(J*H,U*R,U*O,J*Y);break;case"YZY":A.set(U*O,J*H,U*R,J*Y);break;case"ZXZ":A.set(U*R,U*O,J*H,J*Y);break;case"XZX":A.set(J*H,U*$,U*N,J*Y);break;case"YXY":A.set(U*N,J*H,U*$,J*Y);break;case"ZYZ":A.set(U*$,U*N,J*H,J*Y);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+I)}}function UE(A,Q){switch(Q.constructor){case Float32Array:return A;case Uint32Array:return A/4294967295;case Uint16Array:return A/65535;case Uint8Array:return A/255;case Int32Array:return Math.max(A/2147483647,-1);case Int16Array:return Math.max(A/32767,-1);case Int8Array:return Math.max(A/127,-1);default:throw new Error("Invalid component type.")}}function S0(A,Q){switch(Q.constructor){case Float32Array:return A;case Uint32Array:return Math.round(A*4294967295);case Uint16Array:return Math.round(A*65535);case Uint8Array:return Math.round(A*255);case Int32Array:return Math.round(A*2147483647);case Int16Array:return Math.round(A*32767);case Int8Array:return Math.round(A*127);default:throw new Error("Invalid component type.")}}var o0={DEG2RAD:O1,RAD2DEG:H1,generateUUID:TE,clamp:w0,euclideanModulo:XO,mapLinear:j$,inverseLerp:v$,lerp:t6,damp:h$,pingpong:y$,smoothstep:g$,smootherstep:x$,randInt:b$,randFloat:f$,randFloatSpread:u$,seededRandom:p$,degToRad:m$,radToDeg:c$,isPowerOfTwo:l$,ceilPowerOfTwo:d$,floorPowerOfTwo:n$,setQuaternionFromProperEuler:s$,normalize:S0,denormalize:UE};class AA{constructor(A=0,Q=0){AA.prototype.isVector2=!0,this.x=A,this.y=Q}get width(){return this.x}set width(A){this.x=A}get height(){return this.y}set height(A){this.y=A}set(A,Q){return this.x=A,this.y=Q,this}setScalar(A){return this.x=A,this.y=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setComponent(A,Q){switch(A){case 0:this.x=Q;break;case 1:this.y=Q;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y)}copy(A){return this.x=A.x,this.y=A.y,this}add(A){return this.x+=A.x,this.y+=A.y,this}addScalar(A){return this.x+=A,this.y+=A,this}addVectors(A,Q){return this.x=A.x+Q.x,this.y=A.y+Q.y,this}addScaledVector(A,Q){return this.x+=A.x*Q,this.y+=A.y*Q,this}sub(A){return this.x-=A.x,this.y-=A.y,this}subScalar(A){return this.x-=A,this.y-=A,this}subVectors(A,Q){return this.x=A.x-Q.x,this.y=A.y-Q.y,this}multiply(A){return this.x*=A.x,this.y*=A.y,this}multiplyScalar(A){return this.x*=A,this.y*=A,this}divide(A){return this.x/=A.x,this.y/=A.y,this}divideScalar(A){return this.multiplyScalar(1/A)}applyMatrix3(A){let Q=this.x,E=this.y,B=A.elements;return this.x=B[0]*Q+B[3]*E+B[6],this.y=B[1]*Q+B[4]*E+B[7],this}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this}clamp(A,Q){return this.x=w0(this.x,A.x,Q.x),this.y=w0(this.y,A.y,Q.y),this}clampScalar(A,Q){return this.x=w0(this.x,A,Q),this.y=w0(this.y,A,Q),this}clampLength(A,Q){let E=this.length();return this.divideScalar(E||1).multiplyScalar(w0(E,A,Q))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(A){return this.x*A.x+this.y*A.y}cross(A){return this.x*A.y-this.y*A.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(A){let Q=Math.sqrt(this.lengthSq()*A.lengthSq());if(Q===0)return Math.PI/2;let E=this.dot(A)/Q;return Math.acos(w0(E,-1,1))}distanceTo(A){return Math.sqrt(this.distanceToSquared(A))}distanceToSquared(A){let Q=this.x-A.x,E=this.y-A.y;return Q*Q+E*E}manhattanDistanceTo(A){return Math.abs(this.x-A.x)+Math.abs(this.y-A.y)}setLength(A){return this.normalize().multiplyScalar(A)}lerp(A,Q){return this.x+=(A.x-this.x)*Q,this.y+=(A.y-this.y)*Q,this}lerpVectors(A,Q,E){return this.x=A.x+(Q.x-A.x)*E,this.y=A.y+(Q.y-A.y)*E,this}equals(A){return A.x===this.x&&A.y===this.y}fromArray(A,Q=0){return this.x=A[Q],this.y=A[Q+1],this}toArray(A=[],Q=0){return A[Q]=this.x,A[Q+1]=this.y,A}fromBufferAttribute(A,Q){return this.x=A.getX(Q),this.y=A.getY(Q),this}rotateAround(A,Q){let E=Math.cos(Q),B=Math.sin(Q),I=this.x-A.x,C=this.y-A.y;return this.x=I*E-C*B+A.x,this.y=I*B+C*E+A.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class E0{constructor(A,Q,E,B,I,C,K,J,U){if(E0.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],A!==void 0)this.set(A,Q,E,B,I,C,K,J,U)}set(A,Q,E,B,I,C,K,J,U){let Y=this.elements;return Y[0]=A,Y[1]=B,Y[2]=K,Y[3]=Q,Y[4]=I,Y[5]=J,Y[6]=E,Y[7]=C,Y[8]=U,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(A){let Q=this.elements,E=A.elements;return Q[0]=E[0],Q[1]=E[1],Q[2]=E[2],Q[3]=E[3],Q[4]=E[4],Q[5]=E[5],Q[6]=E[6],Q[7]=E[7],Q[8]=E[8],this}extractBasis(A,Q,E){return A.setFromMatrix3Column(this,0),Q.setFromMatrix3Column(this,1),E.setFromMatrix3Column(this,2),this}setFromMatrix4(A){let Q=A.elements;return this.set(Q[0],Q[4],Q[8],Q[1],Q[5],Q[9],Q[2],Q[6],Q[10]),this}multiply(A){return this.multiplyMatrices(this,A)}premultiply(A){return this.multiplyMatrices(A,this)}multiplyMatrices(A,Q){let E=A.elements,B=Q.elements,I=this.elements,C=E[0],K=E[3],J=E[6],U=E[1],Y=E[4],H=E[7],R=E[2],O=E[5],N=E[8],$=B[0],L=B[3],W=B[6],Z=B[1],G=B[4],X=B[7],q=B[2],M=B[5],F=B[8];return I[0]=C*$+K*Z+J*q,I[3]=C*L+K*G+J*M,I[6]=C*W+K*X+J*F,I[1]=U*$+Y*Z+H*q,I[4]=U*L+Y*G+H*M,I[7]=U*W+Y*X+H*F,I[2]=R*$+O*Z+N*q,I[5]=R*L+O*G+N*M,I[8]=R*W+O*X+N*F,this}multiplyScalar(A){let Q=this.elements;return Q[0]*=A,Q[3]*=A,Q[6]*=A,Q[1]*=A,Q[4]*=A,Q[7]*=A,Q[2]*=A,Q[5]*=A,Q[8]*=A,this}determinant(){let A=this.elements,Q=A[0],E=A[1],B=A[2],I=A[3],C=A[4],K=A[5],J=A[6],U=A[7],Y=A[8];return Q*C*Y-Q*K*U-E*I*Y+E*K*J+B*I*U-B*C*J}invert(){let A=this.elements,Q=A[0],E=A[1],B=A[2],I=A[3],C=A[4],K=A[5],J=A[6],U=A[7],Y=A[8],H=Y*C-K*U,R=K*J-Y*I,O=U*I-C*J,N=Q*H+E*R+B*O;if(N===0)return this.set(0,0,0,0,0,0,0,0,0);let $=1/N;return A[0]=H*$,A[1]=(B*U-Y*E)*$,A[2]=(K*E-B*C)*$,A[3]=R*$,A[4]=(Y*Q-B*J)*$,A[5]=(B*I-K*Q)*$,A[6]=O*$,A[7]=(E*J-U*Q)*$,A[8]=(C*Q-E*I)*$,this}transpose(){let A,Q=this.elements;return A=Q[1],Q[1]=Q[3],Q[3]=A,A=Q[2],Q[2]=Q[6],Q[6]=A,A=Q[5],Q[5]=Q[7],Q[7]=A,this}getNormalMatrix(A){return this.setFromMatrix4(A).invert().transpose()}transposeIntoArray(A){let Q=this.elements;return A[0]=Q[0],A[1]=Q[3],A[2]=Q[6],A[3]=Q[1],A[4]=Q[4],A[5]=Q[7],A[6]=Q[2],A[7]=Q[5],A[8]=Q[8],this}setUvTransform(A,Q,E,B,I,C,K){let J=Math.cos(I),U=Math.sin(I);return this.set(E*J,E*U,-E*(J*C+U*K)+C+A,-B*U,B*J,-B*(-U*C+J*K)+K+Q,0,0,1),this}scale(A,Q){return this.premultiply(aU.makeScale(A,Q)),this}rotate(A){return this.premultiply(aU.makeRotation(-A)),this}translate(A,Q){return this.premultiply(aU.makeTranslation(A,Q)),this}makeTranslation(A,Q){if(A.isVector2)this.set(1,0,A.x,0,1,A.y,0,0,1);else this.set(1,0,A,0,1,Q,0,0,1);return this}makeRotation(A){let Q=Math.cos(A),E=Math.sin(A);return this.set(Q,-E,0,E,Q,0,0,0,1),this}makeScale(A,Q){return this.set(A,0,0,0,Q,0,0,0,1),this}equals(A){let Q=this.elements,E=A.elements;for(let B=0;B<9;B++)if(Q[B]!==E[B])return!1;return!0}fromArray(A,Q=0){for(let E=0;E<9;E++)this.elements[E]=A[E+Q];return this}toArray(A=[],Q=0){let E=this.elements;return A[Q]=E[0],A[Q+1]=E[1],A[Q+2]=E[2],A[Q+3]=E[3],A[Q+4]=E[4],A[Q+5]=E[5],A[Q+6]=E[6],A[Q+7]=E[7],A[Q+8]=E[8],A}clone(){return new this.constructor().fromArray(this.elements)}}var aU=/*@__PURE__*/new E0;function $O(A){for(let Q=A.length-1;Q>=0;--Q)if(A[Q]>=65535)return!0;return!1}var i$={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function w8(A,Q){return new i$[A](Q)}function S8(A){return document.createElementNS("http://www.w3.org/1999/xhtml",A)}function LO(){let A=S8("canvas");return A.style.display="block",A}var p7={};function P1(A){if(A in p7)return;p7[A]=!0,console.warn(A)}function fR(A,Q,E){return new Promise(function(B,I){function C(){switch(A.clientWaitSync(Q,A.SYNC_FLUSH_COMMANDS_BIT,0)){case A.WAIT_FAILED:I();break;case A.TIMEOUT_EXPIRED:setTimeout(C,E);break;default:B()}}setTimeout(C,E)})}function uR(A){let Q=A.elements;Q[2]=0.5*Q[2]+0.5*Q[3],Q[6]=0.5*Q[6]+0.5*Q[7],Q[10]=0.5*Q[10]+0.5*Q[11],Q[14]=0.5*Q[14]+0.5*Q[15]}function pR(A){let Q=A.elements;if(Q[11]===-1)Q[10]=-Q[10]-1,Q[14]=-Q[14];else Q[10]=-Q[10],Q[14]=-Q[14]+1}var m7=/*@__PURE__*/new E0().set(0.4123908,0.3575843,0.1804808,0.212639,0.7151687,0.0721923,0.0193308,0.1191948,0.9505322),c7=/*@__PURE__*/new E0().set(3.2409699,-1.5373832,-0.4986108,-0.9692436,1.8759675,0.0415551,0.0556301,-0.203977,1.0569715);function o$(){let A={enabled:!0,workingColorSpace:"srgb-linear",spaces:{},convert:function(I,C,K){if(this.enabled===!1||C===K||!C||!K)return I;if(this.spaces[C].transfer==="srgb")I.r=eB(I.r),I.g=eB(I.g),I.b=eB(I.b);if(this.spaces[C].primaries!==this.spaces[K].primaries)I.applyMatrix3(this.spaces[C].toXYZ),I.applyMatrix3(this.spaces[K].fromXYZ);if(this.spaces[K].transfer==="srgb")I.r=k8(I.r),I.g=k8(I.g),I.b=k8(I.b);return I},fromWorkingColorSpace:function(I,C){return this.convert(I,this.workingColorSpace,C)},toWorkingColorSpace:function(I,C){return this.convert(I,C,this.workingColorSpace)},getPrimaries:function(I){return this.spaces[I].primaries},getTransfer:function(I){if(I==="")return"linear";return this.spaces[I].transfer},getLuminanceCoefficients:function(I,C=this.workingColorSpace){return I.fromArray(this.spaces[C].luminanceCoefficients)},define:function(I){Object.assign(this.spaces,I)},_getMatrix:function(I,C,K){return I.copy(this.spaces[C].toXYZ).multiply(this.spaces[K].fromXYZ)},_getDrawingBufferColorSpace:function(I){return this.spaces[I].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(I=this.workingColorSpace){return this.spaces[I].workingColorSpaceConfig.unpackColorSpace}},Q=[0.64,0.33,0.3,0.6,0.15,0.06],E=[0.2126,0.7152,0.0722],B=[0.3127,0.329];return A.define({["srgb-linear"]:{primaries:Q,whitePoint:B,transfer:"linear",toXYZ:m7,fromXYZ:c7,luminanceCoefficients:E,workingColorSpaceConfig:{unpackColorSpace:"srgb"},outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}},["srgb"]:{primaries:Q,whitePoint:B,transfer:"srgb",toXYZ:m7,fromXYZ:c7,luminanceCoefficients:E,outputColorSpaceConfig:{drawingBufferColorSpace:"srgb"}}}),A}var O0=/*@__PURE__*/o$();function eB(A){return A<0.04045?A*0.0773993808:Math.pow(A*0.9478672986+0.0521327014,2.4)}function k8(A){return A<0.0031308?A*12.92:1.055*Math.pow(A,0.41666)-0.055}var J8;class q9{static getDataURL(A){if(/^data:/i.test(A.src))return A.src;if(typeof HTMLCanvasElement==="undefined")return A.src;let Q;if(A instanceof HTMLCanvasElement)Q=A;else{if(J8===void 0)J8=S8("canvas");J8.width=A.width,J8.height=A.height;let E=J8.getContext("2d");if(A instanceof ImageData)E.putImageData(A,0,0);else E.drawImage(A,0,0,A.width,A.height);Q=J8}return Q.toDataURL("image/png")}static sRGBToLinear(A){if(typeof HTMLImageElement!=="undefined"&&A instanceof HTMLImageElement||typeof HTMLCanvasElement!=="undefined"&&A instanceof HTMLCanvasElement||typeof ImageBitmap!=="undefined"&&A instanceof ImageBitmap){let Q=S8("canvas");Q.width=A.width,Q.height=A.height;let E=Q.getContext("2d");E.drawImage(A,0,0,A.width,A.height);let B=E.getImageData(0,0,A.width,A.height),I=B.data;for(let C=0;C0)E.userData=this.userData;if(!Q)A.textures[this.uuid]=E;return E}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(A){if(this.mapping!==300)return A;if(A.applyMatrix3(this.matrix),A.x<0||A.x>1)switch(this.wrapS){case 1000:A.x=A.x-Math.floor(A.x);break;case 1001:A.x=A.x<0?0:1;break;case 1002:if(Math.abs(Math.floor(A.x)%2)===1)A.x=Math.ceil(A.x)-A.x;else A.x=A.x-Math.floor(A.x);break}if(A.y<0||A.y>1)switch(this.wrapT){case 1000:A.y=A.y-Math.floor(A.y);break;case 1001:A.y=A.y<0?0:1;break;case 1002:if(Math.abs(Math.floor(A.y)%2)===1)A.y=Math.ceil(A.y)-A.y;else A.y=A.y-Math.floor(A.y);break}if(this.flipY)A.y=1-A.y;return A}set needsUpdate(A){if(A===!0)this.version++,this.source.needsUpdate=!0}set needsPMREMUpdate(A){if(A===!0)this.pmremVersion++}}EQ.DEFAULT_IMAGE=null;EQ.DEFAULT_MAPPING=300;EQ.DEFAULT_ANISOTROPY=1;class MA{constructor(A=0,Q=0,E=0,B=1){MA.prototype.isVector4=!0,this.x=A,this.y=Q,this.z=E,this.w=B}get width(){return this.z}set width(A){this.z=A}get height(){return this.w}set height(A){this.w=A}set(A,Q,E,B){return this.x=A,this.y=Q,this.z=E,this.w=B,this}setScalar(A){return this.x=A,this.y=A,this.z=A,this.w=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setZ(A){return this.z=A,this}setW(A){return this.w=A,this}setComponent(A,Q){switch(A){case 0:this.x=Q;break;case 1:this.y=Q;break;case 2:this.z=Q;break;case 3:this.w=Q;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(A){return this.x=A.x,this.y=A.y,this.z=A.z,this.w=A.w!==void 0?A.w:1,this}add(A){return this.x+=A.x,this.y+=A.y,this.z+=A.z,this.w+=A.w,this}addScalar(A){return this.x+=A,this.y+=A,this.z+=A,this.w+=A,this}addVectors(A,Q){return this.x=A.x+Q.x,this.y=A.y+Q.y,this.z=A.z+Q.z,this.w=A.w+Q.w,this}addScaledVector(A,Q){return this.x+=A.x*Q,this.y+=A.y*Q,this.z+=A.z*Q,this.w+=A.w*Q,this}sub(A){return this.x-=A.x,this.y-=A.y,this.z-=A.z,this.w-=A.w,this}subScalar(A){return this.x-=A,this.y-=A,this.z-=A,this.w-=A,this}subVectors(A,Q){return this.x=A.x-Q.x,this.y=A.y-Q.y,this.z=A.z-Q.z,this.w=A.w-Q.w,this}multiply(A){return this.x*=A.x,this.y*=A.y,this.z*=A.z,this.w*=A.w,this}multiplyScalar(A){return this.x*=A,this.y*=A,this.z*=A,this.w*=A,this}applyMatrix4(A){let Q=this.x,E=this.y,B=this.z,I=this.w,C=A.elements;return this.x=C[0]*Q+C[4]*E+C[8]*B+C[12]*I,this.y=C[1]*Q+C[5]*E+C[9]*B+C[13]*I,this.z=C[2]*Q+C[6]*E+C[10]*B+C[14]*I,this.w=C[3]*Q+C[7]*E+C[11]*B+C[15]*I,this}divide(A){return this.x/=A.x,this.y/=A.y,this.z/=A.z,this.w/=A.w,this}divideScalar(A){return this.multiplyScalar(1/A)}setAxisAngleFromQuaternion(A){this.w=2*Math.acos(A.w);let Q=Math.sqrt(1-A.w*A.w);if(Q<0.0001)this.x=1,this.y=0,this.z=0;else this.x=A.x/Q,this.y=A.y/Q,this.z=A.z/Q;return this}setAxisAngleFromRotationMatrix(A){let Q,E,B,I,C=0.01,K=0.1,J=A.elements,U=J[0],Y=J[4],H=J[8],R=J[1],O=J[5],N=J[9],$=J[2],L=J[6],W=J[10];if(Math.abs(Y-R)<0.01&&Math.abs(H-$)<0.01&&Math.abs(N-L)<0.01){if(Math.abs(Y+R)<0.1&&Math.abs(H+$)<0.1&&Math.abs(N+L)<0.1&&Math.abs(U+O+W-3)<0.1)return this.set(1,0,0,0),this;Q=Math.PI;let G=(U+1)/2,X=(O+1)/2,q=(W+1)/2,M=(Y+R)/4,F=(H+$)/4,D=(N+L)/4;if(G>X&&G>q)if(G<0.01)E=0,B=0.707106781,I=0.707106781;else E=Math.sqrt(G),B=M/E,I=F/E;else if(X>q)if(X<0.01)E=0.707106781,B=0,I=0.707106781;else B=Math.sqrt(X),E=M/B,I=D/B;else if(q<0.01)E=0.707106781,B=0.707106781,I=0;else I=Math.sqrt(q),E=F/I,B=D/I;return this.set(E,B,I,Q),this}let Z=Math.sqrt((L-N)*(L-N)+(H-$)*(H-$)+(R-Y)*(R-Y));if(Math.abs(Z)<0.001)Z=1;return this.x=(L-N)/Z,this.y=(H-$)/Z,this.z=(R-Y)/Z,this.w=Math.acos((U+O+W-1)/2),this}setFromMatrixPosition(A){let Q=A.elements;return this.x=Q[12],this.y=Q[13],this.z=Q[14],this.w=Q[15],this}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this.z=Math.min(this.z,A.z),this.w=Math.min(this.w,A.w),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this.z=Math.max(this.z,A.z),this.w=Math.max(this.w,A.w),this}clamp(A,Q){return this.x=w0(this.x,A.x,Q.x),this.y=w0(this.y,A.y,Q.y),this.z=w0(this.z,A.z,Q.z),this.w=w0(this.w,A.w,Q.w),this}clampScalar(A,Q){return this.x=w0(this.x,A,Q),this.y=w0(this.y,A,Q),this.z=w0(this.z,A,Q),this.w=w0(this.w,A,Q),this}clampLength(A,Q){let E=this.length();return this.divideScalar(E||1).multiplyScalar(w0(E,A,Q))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(A){return this.x*A.x+this.y*A.y+this.z*A.z+this.w*A.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(A){return this.normalize().multiplyScalar(A)}lerp(A,Q){return this.x+=(A.x-this.x)*Q,this.y+=(A.y-this.y)*Q,this.z+=(A.z-this.z)*Q,this.w+=(A.w-this.w)*Q,this}lerpVectors(A,Q,E){return this.x=A.x+(Q.x-A.x)*E,this.y=A.y+(Q.y-A.y)*E,this.z=A.z+(Q.z-A.z)*E,this.w=A.w+(Q.w-A.w)*E,this}equals(A){return A.x===this.x&&A.y===this.y&&A.z===this.z&&A.w===this.w}fromArray(A,Q=0){return this.x=A[Q],this.y=A[Q+1],this.z=A[Q+2],this.w=A[Q+3],this}toArray(A=[],Q=0){return A[Q]=this.x,A[Q+1]=this.y,A[Q+2]=this.z,A[Q+3]=this.w,A}fromBufferAttribute(A,Q){return this.x=A.getX(Q),this.y=A.getY(Q),this.z=A.getZ(Q),this.w=A.getW(Q),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class u8 extends rE{constructor(A=1,Q=1,E={}){super();this.isRenderTarget=!0,this.width=A,this.height=Q,this.depth=1,this.scissor=new MA(0,0,A,Q),this.scissorTest=!1,this.viewport=new MA(0,0,A,Q);let B={width:A,height:Q,depth:1};E=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:1006,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},E);let I=new EQ(B,E.mapping,E.wrapS,E.wrapT,E.magFilter,E.minFilter,E.format,E.type,E.anisotropy,E.colorSpace);I.flipY=!1,I.generateMipmaps=E.generateMipmaps,I.internalFormat=E.internalFormat,this.textures=[];let C=E.count;for(let K=0;K=0?1:-1,G=1-W*W;if(G>Number.EPSILON){let q=Math.sqrt(G),M=Math.atan2(q,W*Z);L=Math.sin(L*M)/q,K=Math.sin(K*M)/q}let X=K*Z;if(J=J*L+R*X,U=U*L+O*X,Y=Y*L+N*X,H=H*L+$*X,L===1-K){let q=1/Math.sqrt(J*J+U*U+Y*Y+H*H);J*=q,U*=q,Y*=q,H*=q}}A[Q]=J,A[Q+1]=U,A[Q+2]=Y,A[Q+3]=H}static multiplyQuaternionsFlat(A,Q,E,B,I,C){let K=E[B],J=E[B+1],U=E[B+2],Y=E[B+3],H=I[C],R=I[C+1],O=I[C+2],N=I[C+3];return A[Q]=K*N+Y*H+J*O-U*R,A[Q+1]=J*N+Y*R+U*H-K*O,A[Q+2]=U*N+Y*O+K*R-J*H,A[Q+3]=Y*N-K*H-J*R-U*O,A}get x(){return this._x}set x(A){this._x=A,this._onChangeCallback()}get y(){return this._y}set y(A){this._y=A,this._onChangeCallback()}get z(){return this._z}set z(A){this._z=A,this._onChangeCallback()}get w(){return this._w}set w(A){this._w=A,this._onChangeCallback()}set(A,Q,E,B){return this._x=A,this._y=Q,this._z=E,this._w=B,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(A){return this._x=A.x,this._y=A.y,this._z=A.z,this._w=A.w,this._onChangeCallback(),this}setFromEuler(A,Q=!0){let{_x:E,_y:B,_z:I,_order:C}=A,K=Math.cos,J=Math.sin,U=K(E/2),Y=K(B/2),H=K(I/2),R=J(E/2),O=J(B/2),N=J(I/2);switch(C){case"XYZ":this._x=R*Y*H+U*O*N,this._y=U*O*H-R*Y*N,this._z=U*Y*N+R*O*H,this._w=U*Y*H-R*O*N;break;case"YXZ":this._x=R*Y*H+U*O*N,this._y=U*O*H-R*Y*N,this._z=U*Y*N-R*O*H,this._w=U*Y*H+R*O*N;break;case"ZXY":this._x=R*Y*H-U*O*N,this._y=U*O*H+R*Y*N,this._z=U*Y*N+R*O*H,this._w=U*Y*H-R*O*N;break;case"ZYX":this._x=R*Y*H-U*O*N,this._y=U*O*H+R*Y*N,this._z=U*Y*N-R*O*H,this._w=U*Y*H+R*O*N;break;case"YZX":this._x=R*Y*H+U*O*N,this._y=U*O*H+R*Y*N,this._z=U*Y*N-R*O*H,this._w=U*Y*H-R*O*N;break;case"XZY":this._x=R*Y*H-U*O*N,this._y=U*O*H-R*Y*N,this._z=U*Y*N+R*O*H,this._w=U*Y*H+R*O*N;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+C)}if(Q===!0)this._onChangeCallback();return this}setFromAxisAngle(A,Q){let E=Q/2,B=Math.sin(E);return this._x=A.x*B,this._y=A.y*B,this._z=A.z*B,this._w=Math.cos(E),this._onChangeCallback(),this}setFromRotationMatrix(A){let Q=A.elements,E=Q[0],B=Q[4],I=Q[8],C=Q[1],K=Q[5],J=Q[9],U=Q[2],Y=Q[6],H=Q[10],R=E+K+H;if(R>0){let O=0.5/Math.sqrt(R+1);this._w=0.25/O,this._x=(Y-J)*O,this._y=(I-U)*O,this._z=(C-B)*O}else if(E>K&&E>H){let O=2*Math.sqrt(1+E-K-H);this._w=(Y-J)/O,this._x=0.25*O,this._y=(B+C)/O,this._z=(I+U)/O}else if(K>H){let O=2*Math.sqrt(1+K-E-H);this._w=(I-U)/O,this._x=(B+C)/O,this._y=0.25*O,this._z=(J+Y)/O}else{let O=2*Math.sqrt(1+H-E-K);this._w=(C-B)/O,this._x=(I+U)/O,this._y=(J+Y)/O,this._z=0.25*O}return this._onChangeCallback(),this}setFromUnitVectors(A,Q){let E=A.dot(Q)+1;if(EMath.abs(A.z))this._x=-A.y,this._y=A.x,this._z=0,this._w=E;else this._x=0,this._y=-A.z,this._z=A.y,this._w=E;else this._x=A.y*Q.z-A.z*Q.y,this._y=A.z*Q.x-A.x*Q.z,this._z=A.x*Q.y-A.y*Q.x,this._w=E;return this.normalize()}angleTo(A){return 2*Math.acos(Math.abs(w0(this.dot(A),-1,1)))}rotateTowards(A,Q){let E=this.angleTo(A);if(E===0)return this;let B=Math.min(1,Q/E);return this.slerp(A,B),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(A){return this._x*A._x+this._y*A._y+this._z*A._z+this._w*A._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let A=this.length();if(A===0)this._x=0,this._y=0,this._z=0,this._w=1;else A=1/A,this._x=this._x*A,this._y=this._y*A,this._z=this._z*A,this._w=this._w*A;return this._onChangeCallback(),this}multiply(A){return this.multiplyQuaternions(this,A)}premultiply(A){return this.multiplyQuaternions(A,this)}multiplyQuaternions(A,Q){let{_x:E,_y:B,_z:I,_w:C}=A,K=Q._x,J=Q._y,U=Q._z,Y=Q._w;return this._x=E*Y+C*K+B*U-I*J,this._y=B*Y+C*J+I*K-E*U,this._z=I*Y+C*U+E*J-B*K,this._w=C*Y-E*K-B*J-I*U,this._onChangeCallback(),this}slerp(A,Q){if(Q===0)return this;if(Q===1)return this.copy(A);let E=this._x,B=this._y,I=this._z,C=this._w,K=C*A._w+E*A._x+B*A._y+I*A._z;if(K<0)this._w=-A._w,this._x=-A._x,this._y=-A._y,this._z=-A._z,K=-K;else this.copy(A);if(K>=1)return this._w=C,this._x=E,this._y=B,this._z=I,this;let J=1-K*K;if(J<=Number.EPSILON){let O=1-Q;return this._w=O*C+Q*this._w,this._x=O*E+Q*this._x,this._y=O*B+Q*this._y,this._z=O*I+Q*this._z,this.normalize(),this}let U=Math.sqrt(J),Y=Math.atan2(U,K),H=Math.sin((1-Q)*Y)/U,R=Math.sin(Q*Y)/U;return this._w=C*H+this._w*R,this._x=E*H+this._x*R,this._y=B*H+this._y*R,this._z=I*H+this._z*R,this._onChangeCallback(),this}slerpQuaternions(A,Q,E){return this.copy(A).slerp(Q,E)}random(){let A=2*Math.PI*Math.random(),Q=2*Math.PI*Math.random(),E=Math.random(),B=Math.sqrt(1-E),I=Math.sqrt(E);return this.set(B*Math.sin(A),B*Math.cos(A),I*Math.sin(Q),I*Math.cos(Q))}equals(A){return A._x===this._x&&A._y===this._y&&A._z===this._z&&A._w===this._w}fromArray(A,Q=0){return this._x=A[Q],this._y=A[Q+1],this._z=A[Q+2],this._w=A[Q+3],this._onChangeCallback(),this}toArray(A=[],Q=0){return A[Q]=this._x,A[Q+1]=this._y,A[Q+2]=this._z,A[Q+3]=this._w,A}fromBufferAttribute(A,Q){return this._x=A.getX(Q),this._y=A.getY(Q),this._z=A.getZ(Q),this._w=A.getW(Q),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(A){return this._onChangeCallback=A,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class y{constructor(A=0,Q=0,E=0){y.prototype.isVector3=!0,this.x=A,this.y=Q,this.z=E}set(A,Q,E){if(E===void 0)E=this.z;return this.x=A,this.y=Q,this.z=E,this}setScalar(A){return this.x=A,this.y=A,this.z=A,this}setX(A){return this.x=A,this}setY(A){return this.y=A,this}setZ(A){return this.z=A,this}setComponent(A,Q){switch(A){case 0:this.x=Q;break;case 1:this.y=Q;break;case 2:this.z=Q;break;default:throw new Error("index is out of range: "+A)}return this}getComponent(A){switch(A){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+A)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(A){return this.x=A.x,this.y=A.y,this.z=A.z,this}add(A){return this.x+=A.x,this.y+=A.y,this.z+=A.z,this}addScalar(A){return this.x+=A,this.y+=A,this.z+=A,this}addVectors(A,Q){return this.x=A.x+Q.x,this.y=A.y+Q.y,this.z=A.z+Q.z,this}addScaledVector(A,Q){return this.x+=A.x*Q,this.y+=A.y*Q,this.z+=A.z*Q,this}sub(A){return this.x-=A.x,this.y-=A.y,this.z-=A.z,this}subScalar(A){return this.x-=A,this.y-=A,this.z-=A,this}subVectors(A,Q){return this.x=A.x-Q.x,this.y=A.y-Q.y,this.z=A.z-Q.z,this}multiply(A){return this.x*=A.x,this.y*=A.y,this.z*=A.z,this}multiplyScalar(A){return this.x*=A,this.y*=A,this.z*=A,this}multiplyVectors(A,Q){return this.x=A.x*Q.x,this.y=A.y*Q.y,this.z=A.z*Q.z,this}applyEuler(A){return this.applyQuaternion(l7.setFromEuler(A))}applyAxisAngle(A,Q){return this.applyQuaternion(l7.setFromAxisAngle(A,Q))}applyMatrix3(A){let Q=this.x,E=this.y,B=this.z,I=A.elements;return this.x=I[0]*Q+I[3]*E+I[6]*B,this.y=I[1]*Q+I[4]*E+I[7]*B,this.z=I[2]*Q+I[5]*E+I[8]*B,this}applyNormalMatrix(A){return this.applyMatrix3(A).normalize()}applyMatrix4(A){let Q=this.x,E=this.y,B=this.z,I=A.elements,C=1/(I[3]*Q+I[7]*E+I[11]*B+I[15]);return this.x=(I[0]*Q+I[4]*E+I[8]*B+I[12])*C,this.y=(I[1]*Q+I[5]*E+I[9]*B+I[13])*C,this.z=(I[2]*Q+I[6]*E+I[10]*B+I[14])*C,this}applyQuaternion(A){let Q=this.x,E=this.y,B=this.z,I=A.x,C=A.y,K=A.z,J=A.w,U=2*(C*B-K*E),Y=2*(K*Q-I*B),H=2*(I*E-C*Q);return this.x=Q+J*U+C*H-K*Y,this.y=E+J*Y+K*U-I*H,this.z=B+J*H+I*Y-C*U,this}project(A){return this.applyMatrix4(A.matrixWorldInverse).applyMatrix4(A.projectionMatrix)}unproject(A){return this.applyMatrix4(A.projectionMatrixInverse).applyMatrix4(A.matrixWorld)}transformDirection(A){let Q=this.x,E=this.y,B=this.z,I=A.elements;return this.x=I[0]*Q+I[4]*E+I[8]*B,this.y=I[1]*Q+I[5]*E+I[9]*B,this.z=I[2]*Q+I[6]*E+I[10]*B,this.normalize()}divide(A){return this.x/=A.x,this.y/=A.y,this.z/=A.z,this}divideScalar(A){return this.multiplyScalar(1/A)}min(A){return this.x=Math.min(this.x,A.x),this.y=Math.min(this.y,A.y),this.z=Math.min(this.z,A.z),this}max(A){return this.x=Math.max(this.x,A.x),this.y=Math.max(this.y,A.y),this.z=Math.max(this.z,A.z),this}clamp(A,Q){return this.x=w0(this.x,A.x,Q.x),this.y=w0(this.y,A.y,Q.y),this.z=w0(this.z,A.z,Q.z),this}clampScalar(A,Q){return this.x=w0(this.x,A,Q),this.y=w0(this.y,A,Q),this.z=w0(this.z,A,Q),this}clampLength(A,Q){let E=this.length();return this.divideScalar(E||1).multiplyScalar(w0(E,A,Q))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(A){return this.x*A.x+this.y*A.y+this.z*A.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(A){return this.normalize().multiplyScalar(A)}lerp(A,Q){return this.x+=(A.x-this.x)*Q,this.y+=(A.y-this.y)*Q,this.z+=(A.z-this.z)*Q,this}lerpVectors(A,Q,E){return this.x=A.x+(Q.x-A.x)*E,this.y=A.y+(Q.y-A.y)*E,this.z=A.z+(Q.z-A.z)*E,this}cross(A){return this.crossVectors(this,A)}crossVectors(A,Q){let{x:E,y:B,z:I}=A,C=Q.x,K=Q.y,J=Q.z;return this.x=B*J-I*K,this.y=I*C-E*J,this.z=E*K-B*C,this}projectOnVector(A){let Q=A.lengthSq();if(Q===0)return this.set(0,0,0);let E=A.dot(this)/Q;return this.copy(A).multiplyScalar(E)}projectOnPlane(A){return eU.copy(this).projectOnVector(A),this.sub(eU)}reflect(A){return this.sub(eU.copy(A).multiplyScalar(2*this.dot(A)))}angleTo(A){let Q=Math.sqrt(this.lengthSq()*A.lengthSq());if(Q===0)return Math.PI/2;let E=this.dot(A)/Q;return Math.acos(w0(E,-1,1))}distanceTo(A){return Math.sqrt(this.distanceToSquared(A))}distanceToSquared(A){let Q=this.x-A.x,E=this.y-A.y,B=this.z-A.z;return Q*Q+E*E+B*B}manhattanDistanceTo(A){return Math.abs(this.x-A.x)+Math.abs(this.y-A.y)+Math.abs(this.z-A.z)}setFromSpherical(A){return this.setFromSphericalCoords(A.radius,A.phi,A.theta)}setFromSphericalCoords(A,Q,E){let B=Math.sin(Q)*A;return this.x=B*Math.sin(E),this.y=Math.cos(Q)*A,this.z=B*Math.cos(E),this}setFromCylindrical(A){return this.setFromCylindricalCoords(A.radius,A.theta,A.y)}setFromCylindricalCoords(A,Q,E){return this.x=A*Math.sin(Q),this.y=E,this.z=A*Math.cos(Q),this}setFromMatrixPosition(A){let Q=A.elements;return this.x=Q[12],this.y=Q[13],this.z=Q[14],this}setFromMatrixScale(A){let Q=this.setFromMatrixColumn(A,0).length(),E=this.setFromMatrixColumn(A,1).length(),B=this.setFromMatrixColumn(A,2).length();return this.x=Q,this.y=E,this.z=B,this}setFromMatrixColumn(A,Q){return this.fromArray(A.elements,Q*4)}setFromMatrix3Column(A,Q){return this.fromArray(A.elements,Q*3)}setFromEuler(A){return this.x=A._x,this.y=A._y,this.z=A._z,this}setFromColor(A){return this.x=A.r,this.y=A.g,this.z=A.b,this}equals(A){return A.x===this.x&&A.y===this.y&&A.z===this.z}fromArray(A,Q=0){return this.x=A[Q],this.y=A[Q+1],this.z=A[Q+2],this}toArray(A=[],Q=0){return A[Q]=this.x,A[Q+1]=this.y,A[Q+2]=this.z,A}fromBufferAttribute(A,Q){return this.x=A.getX(Q),this.y=A.getY(Q),this.z=A.getZ(Q),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let A=Math.random()*Math.PI*2,Q=Math.random()*2-1,E=Math.sqrt(1-Q*Q);return this.x=E*Math.cos(A),this.y=Q,this.z=E*Math.sin(A),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}var eU=/*@__PURE__*/new y,l7=/*@__PURE__*/new J0;class g0{constructor(A=new y(1/0,1/0,1/0),Q=new y(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=A,this.max=Q}set(A,Q){return this.min.copy(A),this.max.copy(Q),this}setFromArray(A){this.makeEmpty();for(let Q=0,E=A.length;Q=this.min.x&&A.x<=this.max.x&&A.y>=this.min.y&&A.y<=this.max.y&&A.z>=this.min.z&&A.z<=this.max.z}containsBox(A){return this.min.x<=A.min.x&&A.max.x<=this.max.x&&this.min.y<=A.min.y&&A.max.y<=this.max.y&&this.min.z<=A.min.z&&A.max.z<=this.max.z}getParameter(A,Q){return Q.set((A.x-this.min.x)/(this.max.x-this.min.x),(A.y-this.min.y)/(this.max.y-this.min.y),(A.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(A){return A.max.x>=this.min.x&&A.min.x<=this.max.x&&A.max.y>=this.min.y&&A.min.y<=this.max.y&&A.max.z>=this.min.z&&A.min.z<=this.max.z}intersectsSphere(A){return this.clampPoint(A.center,JB),JB.distanceToSquared(A.center)<=A.radius*A.radius}intersectsPlane(A){let Q,E;if(A.normal.x>0)Q=A.normal.x*this.min.x,E=A.normal.x*this.max.x;else Q=A.normal.x*this.max.x,E=A.normal.x*this.min.x;if(A.normal.y>0)Q+=A.normal.y*this.min.y,E+=A.normal.y*this.max.y;else Q+=A.normal.y*this.max.y,E+=A.normal.y*this.min.y;if(A.normal.z>0)Q+=A.normal.z*this.min.z,E+=A.normal.z*this.max.z;else Q+=A.normal.z*this.max.z,E+=A.normal.z*this.min.z;return Q<=-A.constant&&E>=-A.constant}intersectsTriangle(A){if(this.isEmpty())return!1;this.getCenter(f6),iK.subVectors(this.max,f6),U8.subVectors(A.a,f6),Y8.subVectors(A.b,f6),O8.subVectors(A.c,f6),FI.subVectors(Y8,U8),DI.subVectors(O8,Y8),tI.subVectors(U8,O8);let Q=[0,-FI.z,FI.y,0,-DI.z,DI.y,0,-tI.z,tI.y,FI.z,0,-FI.x,DI.z,0,-DI.x,tI.z,0,-tI.x,-FI.y,FI.x,0,-DI.y,DI.x,0,-tI.y,tI.x,0];if(!AY(Q,U8,Y8,O8,iK))return!1;if(Q=[1,0,0,0,1,0,0,0,1],!AY(Q,U8,Y8,O8,iK))return!1;return oK.crossVectors(FI,DI),Q=[oK.x,oK.y,oK.z],AY(Q,U8,Y8,O8,iK)}clampPoint(A,Q){return Q.copy(A).clamp(this.min,this.max)}distanceToPoint(A){return this.clampPoint(A,JB).distanceTo(A)}getBoundingSphere(A){if(this.isEmpty())A.makeEmpty();else this.getCenter(A.center),A.radius=this.getSize(JB).length()*0.5;return A}intersect(A){if(this.min.max(A.min),this.max.min(A.max),this.isEmpty())this.makeEmpty();return this}union(A){return this.min.min(A.min),this.max.max(A.max),this}applyMatrix4(A){if(this.isEmpty())return this;return nB[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(A),nB[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(A),nB[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(A),nB[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(A),nB[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(A),nB[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(A),nB[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(A),nB[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(A),this.setFromPoints(nB),this}translate(A){return this.min.add(A),this.max.add(A),this}equals(A){return A.min.equals(this.min)&&A.max.equals(this.max)}}var nB=[/*@__PURE__*/new y,/*@__PURE__*/new y,/*@__PURE__*/new y,/*@__PURE__*/new y,/*@__PURE__*/new y,/*@__PURE__*/new y,/*@__PURE__*/new y,/*@__PURE__*/new y],JB=/*@__PURE__*/new y,sK=/*@__PURE__*/new g0,U8=/*@__PURE__*/new y,Y8=/*@__PURE__*/new y,O8=/*@__PURE__*/new y,FI=/*@__PURE__*/new y,DI=/*@__PURE__*/new y,tI=/*@__PURE__*/new y,f6=/*@__PURE__*/new y,iK=/*@__PURE__*/new y,oK=/*@__PURE__*/new y,eI=/*@__PURE__*/new y;function AY(A,Q,E,B,I){for(let C=0,K=A.length-3;C<=K;C+=3){eI.fromArray(A,C);let J=I.x*Math.abs(eI.x)+I.y*Math.abs(eI.y)+I.z*Math.abs(eI.z),U=Q.dot(eI),Y=E.dot(eI),H=B.dot(eI);if(Math.max(-Math.max(U,Y,H),Math.min(U,Y,H))>J)return!1}return!0}var t$=/*@__PURE__*/new g0,u6=/*@__PURE__*/new y,QY=/*@__PURE__*/new y;class KQ{constructor(A=new y,Q=-1){this.isSphere=!0,this.center=A,this.radius=Q}set(A,Q){return this.center.copy(A),this.radius=Q,this}setFromPoints(A,Q){let E=this.center;if(Q!==void 0)E.copy(Q);else t$.setFromPoints(A).getCenter(E);let B=0;for(let I=0,C=A.length;Ithis.radius*this.radius)Q.sub(this.center).normalize(),Q.multiplyScalar(this.radius).add(this.center);return Q}getBoundingBox(A){if(this.isEmpty())return A.makeEmpty(),A;return A.set(this.center,this.center),A.expandByScalar(this.radius),A}applyMatrix4(A){return this.center.applyMatrix4(A),this.radius=this.radius*A.getMaxScaleOnAxis(),this}translate(A){return this.center.add(A),this}expandByPoint(A){if(this.isEmpty())return this.center.copy(A),this.radius=0,this;u6.subVectors(A,this.center);let Q=u6.lengthSq();if(Q>this.radius*this.radius){let E=Math.sqrt(Q),B=(E-this.radius)*0.5;this.center.addScaledVector(u6,B/E),this.radius+=B}return this}union(A){if(A.isEmpty())return this;if(this.isEmpty())return this.copy(A),this;if(this.center.equals(A.center)===!0)this.radius=Math.max(this.radius,A.radius);else QY.subVectors(A.center,this.center).setLength(A.radius),this.expandByPoint(u6.copy(A.center).add(QY)),this.expandByPoint(u6.copy(A.center).sub(QY));return this}equals(A){return A.center.equals(this.center)&&A.radius===this.radius}clone(){return new this.constructor().copy(this)}}var sB=/*@__PURE__*/new y,EY=/*@__PURE__*/new y,rK=/*@__PURE__*/new y,MI=/*@__PURE__*/new y,BY=/*@__PURE__*/new y,aK=/*@__PURE__*/new y,IY=/*@__PURE__*/new y;class qE{constructor(A=new y,Q=new y(0,0,-1)){this.origin=A,this.direction=Q}set(A,Q){return this.origin.copy(A),this.direction.copy(Q),this}copy(A){return this.origin.copy(A.origin),this.direction.copy(A.direction),this}at(A,Q){return Q.copy(this.origin).addScaledVector(this.direction,A)}lookAt(A){return this.direction.copy(A).sub(this.origin).normalize(),this}recast(A){return this.origin.copy(this.at(A,sB)),this}closestPointToPoint(A,Q){Q.subVectors(A,this.origin);let E=Q.dot(this.direction);if(E<0)return Q.copy(this.origin);return Q.copy(this.origin).addScaledVector(this.direction,E)}distanceToPoint(A){return Math.sqrt(this.distanceSqToPoint(A))}distanceSqToPoint(A){let Q=sB.subVectors(A,this.origin).dot(this.direction);if(Q<0)return this.origin.distanceToSquared(A);return sB.copy(this.origin).addScaledVector(this.direction,Q),sB.distanceToSquared(A)}distanceSqToSegment(A,Q,E,B){EY.copy(A).add(Q).multiplyScalar(0.5),rK.copy(Q).sub(A).normalize(),MI.copy(this.origin).sub(EY);let I=A.distanceTo(Q)*0.5,C=-this.direction.dot(rK),K=MI.dot(this.direction),J=-MI.dot(rK),U=MI.lengthSq(),Y=Math.abs(1-C*C),H,R,O,N;if(Y>0)if(H=C*J-K,R=C*K-J,N=I*Y,H>=0)if(R>=-N)if(R<=N){let $=1/Y;H*=$,R*=$,O=H*(H+C*R+2*K)+R*(C*H+R+2*J)+U}else R=I,H=Math.max(0,-(C*R+K)),O=-H*H+R*(R+2*J)+U;else R=-I,H=Math.max(0,-(C*R+K)),O=-H*H+R*(R+2*J)+U;else if(R<=-N)H=Math.max(0,-(-C*I+K)),R=H>0?-I:Math.min(Math.max(-I,-J),I),O=-H*H+R*(R+2*J)+U;else if(R<=N)H=0,R=Math.min(Math.max(-I,-J),I),O=R*(R+2*J)+U;else H=Math.max(0,-(C*I+K)),R=H>0?I:Math.min(Math.max(-I,-J),I),O=-H*H+R*(R+2*J)+U;else R=C>0?-I:I,H=Math.max(0,-(C*R+K)),O=-H*H+R*(R+2*J)+U;if(E)E.copy(this.origin).addScaledVector(this.direction,H);if(B)B.copy(EY).addScaledVector(rK,R);return O}intersectSphere(A,Q){sB.subVectors(A.center,this.origin);let E=sB.dot(this.direction),B=sB.dot(sB)-E*E,I=A.radius*A.radius;if(B>I)return null;let C=Math.sqrt(I-B),K=E-C,J=E+C;if(J<0)return null;if(K<0)return this.at(J,Q);return this.at(K,Q)}intersectsSphere(A){return this.distanceSqToPoint(A.center)<=A.radius*A.radius}distanceToPlane(A){let Q=A.normal.dot(this.direction);if(Q===0){if(A.distanceToPoint(this.origin)===0)return 0;return null}let E=-(this.origin.dot(A.normal)+A.constant)/Q;return E>=0?E:null}intersectPlane(A,Q){let E=this.distanceToPlane(A);if(E===null)return null;return this.at(E,Q)}intersectsPlane(A){let Q=A.distanceToPoint(this.origin);if(Q===0)return!0;if(A.normal.dot(this.direction)*Q<0)return!0;return!1}intersectBox(A,Q){let E,B,I,C,K,J,U=1/this.direction.x,Y=1/this.direction.y,H=1/this.direction.z,R=this.origin;if(U>=0)E=(A.min.x-R.x)*U,B=(A.max.x-R.x)*U;else E=(A.max.x-R.x)*U,B=(A.min.x-R.x)*U;if(Y>=0)I=(A.min.y-R.y)*Y,C=(A.max.y-R.y)*Y;else I=(A.max.y-R.y)*Y,C=(A.min.y-R.y)*Y;if(E>C||I>B)return null;if(I>E||isNaN(E))E=I;if(C=0)K=(A.min.z-R.z)*H,J=(A.max.z-R.z)*H;else K=(A.max.z-R.z)*H,J=(A.min.z-R.z)*H;if(E>J||K>B)return null;if(K>E||E!==E)E=K;if(J=0?E:B,Q)}intersectsBox(A){return this.intersectBox(A,sB)!==null}intersectTriangle(A,Q,E,B,I){BY.subVectors(Q,A),aK.subVectors(E,A),IY.crossVectors(BY,aK);let C=this.direction.dot(IY),K;if(C>0){if(B)return null;K=1}else if(C<0)K=-1,C=-C;else return null;MI.subVectors(this.origin,A);let J=K*this.direction.dot(aK.crossVectors(MI,aK));if(J<0)return null;let U=K*this.direction.dot(BY.cross(MI));if(U<0)return null;if(J+U>C)return null;let Y=-K*MI.dot(IY);if(Y<0)return null;return this.at(Y/C,I)}applyMatrix4(A){return this.origin.applyMatrix4(A),this.direction.transformDirection(A),this}equals(A){return A.origin.equals(this.origin)&&A.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class RA{constructor(A,Q,E,B,I,C,K,J,U,Y,H,R,O,N,$,L){if(RA.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],A!==void 0)this.set(A,Q,E,B,I,C,K,J,U,Y,H,R,O,N,$,L)}set(A,Q,E,B,I,C,K,J,U,Y,H,R,O,N,$,L){let W=this.elements;return W[0]=A,W[4]=Q,W[8]=E,W[12]=B,W[1]=I,W[5]=C,W[9]=K,W[13]=J,W[2]=U,W[6]=Y,W[10]=H,W[14]=R,W[3]=O,W[7]=N,W[11]=$,W[15]=L,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new RA().fromArray(this.elements)}copy(A){let Q=this.elements,E=A.elements;return Q[0]=E[0],Q[1]=E[1],Q[2]=E[2],Q[3]=E[3],Q[4]=E[4],Q[5]=E[5],Q[6]=E[6],Q[7]=E[7],Q[8]=E[8],Q[9]=E[9],Q[10]=E[10],Q[11]=E[11],Q[12]=E[12],Q[13]=E[13],Q[14]=E[14],Q[15]=E[15],this}copyPosition(A){let Q=this.elements,E=A.elements;return Q[12]=E[12],Q[13]=E[13],Q[14]=E[14],this}setFromMatrix3(A){let Q=A.elements;return this.set(Q[0],Q[3],Q[6],0,Q[1],Q[4],Q[7],0,Q[2],Q[5],Q[8],0,0,0,0,1),this}extractBasis(A,Q,E){return A.setFromMatrixColumn(this,0),Q.setFromMatrixColumn(this,1),E.setFromMatrixColumn(this,2),this}makeBasis(A,Q,E){return this.set(A.x,Q.x,E.x,0,A.y,Q.y,E.y,0,A.z,Q.z,E.z,0,0,0,0,1),this}extractRotation(A){let Q=this.elements,E=A.elements,B=1/H8.setFromMatrixColumn(A,0).length(),I=1/H8.setFromMatrixColumn(A,1).length(),C=1/H8.setFromMatrixColumn(A,2).length();return Q[0]=E[0]*B,Q[1]=E[1]*B,Q[2]=E[2]*B,Q[3]=0,Q[4]=E[4]*I,Q[5]=E[5]*I,Q[6]=E[6]*I,Q[7]=0,Q[8]=E[8]*C,Q[9]=E[9]*C,Q[10]=E[10]*C,Q[11]=0,Q[12]=0,Q[13]=0,Q[14]=0,Q[15]=1,this}makeRotationFromEuler(A){let Q=this.elements,E=A.x,B=A.y,I=A.z,C=Math.cos(E),K=Math.sin(E),J=Math.cos(B),U=Math.sin(B),Y=Math.cos(I),H=Math.sin(I);if(A.order==="XYZ"){let R=C*Y,O=C*H,N=K*Y,$=K*H;Q[0]=J*Y,Q[4]=-J*H,Q[8]=U,Q[1]=O+N*U,Q[5]=R-$*U,Q[9]=-K*J,Q[2]=$-R*U,Q[6]=N+O*U,Q[10]=C*J}else if(A.order==="YXZ"){let R=J*Y,O=J*H,N=U*Y,$=U*H;Q[0]=R+$*K,Q[4]=N*K-O,Q[8]=C*U,Q[1]=C*H,Q[5]=C*Y,Q[9]=-K,Q[2]=O*K-N,Q[6]=$+R*K,Q[10]=C*J}else if(A.order==="ZXY"){let R=J*Y,O=J*H,N=U*Y,$=U*H;Q[0]=R-$*K,Q[4]=-C*H,Q[8]=N+O*K,Q[1]=O+N*K,Q[5]=C*Y,Q[9]=$-R*K,Q[2]=-C*U,Q[6]=K,Q[10]=C*J}else if(A.order==="ZYX"){let R=C*Y,O=C*H,N=K*Y,$=K*H;Q[0]=J*Y,Q[4]=N*U-O,Q[8]=R*U+$,Q[1]=J*H,Q[5]=$*U+R,Q[9]=O*U-N,Q[2]=-U,Q[6]=K*J,Q[10]=C*J}else if(A.order==="YZX"){let R=C*J,O=C*U,N=K*J,$=K*U;Q[0]=J*Y,Q[4]=$-R*H,Q[8]=N*H+O,Q[1]=H,Q[5]=C*Y,Q[9]=-K*Y,Q[2]=-U*Y,Q[6]=O*H+N,Q[10]=R-$*H}else if(A.order==="XZY"){let R=C*J,O=C*U,N=K*J,$=K*U;Q[0]=J*Y,Q[4]=-H,Q[8]=U*Y,Q[1]=R*H+$,Q[5]=C*Y,Q[9]=O*H-N,Q[2]=N*H-O,Q[6]=K*Y,Q[10]=$*H+R}return Q[3]=0,Q[7]=0,Q[11]=0,Q[12]=0,Q[13]=0,Q[14]=0,Q[15]=1,this}makeRotationFromQuaternion(A){return this.compose(e$,A,AL)}lookAt(A,Q,E){let B=this.elements;if(kE.subVectors(A,Q),kE.lengthSq()===0)kE.z=1;if(kE.normalize(),wI.crossVectors(E,kE),wI.lengthSq()===0){if(Math.abs(E.z)===1)kE.x+=0.0001;else kE.z+=0.0001;kE.normalize(),wI.crossVectors(E,kE)}return wI.normalize(),tK.crossVectors(kE,wI),B[0]=wI.x,B[4]=tK.x,B[8]=kE.x,B[1]=wI.y,B[5]=tK.y,B[9]=kE.y,B[2]=wI.z,B[6]=tK.z,B[10]=kE.z,this}multiply(A){return this.multiplyMatrices(this,A)}premultiply(A){return this.multiplyMatrices(A,this)}multiplyMatrices(A,Q){let E=A.elements,B=Q.elements,I=this.elements,C=E[0],K=E[4],J=E[8],U=E[12],Y=E[1],H=E[5],R=E[9],O=E[13],N=E[2],$=E[6],L=E[10],W=E[14],Z=E[3],G=E[7],X=E[11],q=E[15],M=B[0],F=B[4],D=B[8],_=B[12],w=B[1],k=B[5],T=B[9],z=B[13],j=B[2],v=B[6],g=B[10],P=B[14],V=B[3],S=B[7],h=B[11],x=B[15];return I[0]=C*M+K*w+J*j+U*V,I[4]=C*F+K*k+J*v+U*S,I[8]=C*D+K*T+J*g+U*h,I[12]=C*_+K*z+J*P+U*x,I[1]=Y*M+H*w+R*j+O*V,I[5]=Y*F+H*k+R*v+O*S,I[9]=Y*D+H*T+R*g+O*h,I[13]=Y*_+H*z+R*P+O*x,I[2]=N*M+$*w+L*j+W*V,I[6]=N*F+$*k+L*v+W*S,I[10]=N*D+$*T+L*g+W*h,I[14]=N*_+$*z+L*P+W*x,I[3]=Z*M+G*w+X*j+q*V,I[7]=Z*F+G*k+X*v+q*S,I[11]=Z*D+G*T+X*g+q*h,I[15]=Z*_+G*z+X*P+q*x,this}multiplyScalar(A){let Q=this.elements;return Q[0]*=A,Q[4]*=A,Q[8]*=A,Q[12]*=A,Q[1]*=A,Q[5]*=A,Q[9]*=A,Q[13]*=A,Q[2]*=A,Q[6]*=A,Q[10]*=A,Q[14]*=A,Q[3]*=A,Q[7]*=A,Q[11]*=A,Q[15]*=A,this}determinant(){let A=this.elements,Q=A[0],E=A[4],B=A[8],I=A[12],C=A[1],K=A[5],J=A[9],U=A[13],Y=A[2],H=A[6],R=A[10],O=A[14],N=A[3],$=A[7],L=A[11],W=A[15];return N*(+I*J*H-B*U*H-I*K*R+E*U*R+B*K*O-E*J*O)+$*(+Q*J*O-Q*U*R+I*C*R-B*C*O+B*U*Y-I*J*Y)+L*(+Q*U*H-Q*K*O-I*C*H+E*C*O+I*K*Y-E*U*Y)+W*(-B*K*Y-Q*J*H+Q*K*R+B*C*H-E*C*R+E*J*Y)}transpose(){let A=this.elements,Q;return Q=A[1],A[1]=A[4],A[4]=Q,Q=A[2],A[2]=A[8],A[8]=Q,Q=A[6],A[6]=A[9],A[9]=Q,Q=A[3],A[3]=A[12],A[12]=Q,Q=A[7],A[7]=A[13],A[13]=Q,Q=A[11],A[11]=A[14],A[14]=Q,this}setPosition(A,Q,E){let B=this.elements;if(A.isVector3)B[12]=A.x,B[13]=A.y,B[14]=A.z;else B[12]=A,B[13]=Q,B[14]=E;return this}invert(){let A=this.elements,Q=A[0],E=A[1],B=A[2],I=A[3],C=A[4],K=A[5],J=A[6],U=A[7],Y=A[8],H=A[9],R=A[10],O=A[11],N=A[12],$=A[13],L=A[14],W=A[15],Z=H*L*U-$*R*U+$*J*O-K*L*O-H*J*W+K*R*W,G=N*R*U-Y*L*U-N*J*O+C*L*O+Y*J*W-C*R*W,X=Y*$*U-N*H*U+N*K*O-C*$*O-Y*K*W+C*H*W,q=N*H*J-Y*$*J-N*K*R+C*$*R+Y*K*L-C*H*L,M=Q*Z+E*G+B*X+I*q;if(M===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let F=1/M;return A[0]=Z*F,A[1]=($*R*I-H*L*I-$*B*O+E*L*O+H*B*W-E*R*W)*F,A[2]=(K*L*I-$*J*I+$*B*U-E*L*U-K*B*W+E*J*W)*F,A[3]=(H*J*I-K*R*I-H*B*U+E*R*U+K*B*O-E*J*O)*F,A[4]=G*F,A[5]=(Y*L*I-N*R*I+N*B*O-Q*L*O-Y*B*W+Q*R*W)*F,A[6]=(N*J*I-C*L*I-N*B*U+Q*L*U+C*B*W-Q*J*W)*F,A[7]=(C*R*I-Y*J*I+Y*B*U-Q*R*U-C*B*O+Q*J*O)*F,A[8]=X*F,A[9]=(N*H*I-Y*$*I-N*E*O+Q*$*O+Y*E*W-Q*H*W)*F,A[10]=(C*$*I-N*K*I+N*E*U-Q*$*U-C*E*W+Q*K*W)*F,A[11]=(Y*K*I-C*H*I-Y*E*U+Q*H*U+C*E*O-Q*K*O)*F,A[12]=q*F,A[13]=(Y*$*B-N*H*B+N*E*R-Q*$*R-Y*E*L+Q*H*L)*F,A[14]=(N*K*B-C*$*B-N*E*J+Q*$*J+C*E*L-Q*K*L)*F,A[15]=(C*H*B-Y*K*B+Y*E*J-Q*H*J-C*E*R+Q*K*R)*F,this}scale(A){let Q=this.elements,E=A.x,B=A.y,I=A.z;return Q[0]*=E,Q[4]*=B,Q[8]*=I,Q[1]*=E,Q[5]*=B,Q[9]*=I,Q[2]*=E,Q[6]*=B,Q[10]*=I,Q[3]*=E,Q[7]*=B,Q[11]*=I,this}getMaxScaleOnAxis(){let A=this.elements,Q=A[0]*A[0]+A[1]*A[1]+A[2]*A[2],E=A[4]*A[4]+A[5]*A[5]+A[6]*A[6],B=A[8]*A[8]+A[9]*A[9]+A[10]*A[10];return Math.sqrt(Math.max(Q,E,B))}makeTranslation(A,Q,E){if(A.isVector3)this.set(1,0,0,A.x,0,1,0,A.y,0,0,1,A.z,0,0,0,1);else this.set(1,0,0,A,0,1,0,Q,0,0,1,E,0,0,0,1);return this}makeRotationX(A){let Q=Math.cos(A),E=Math.sin(A);return this.set(1,0,0,0,0,Q,-E,0,0,E,Q,0,0,0,0,1),this}makeRotationY(A){let Q=Math.cos(A),E=Math.sin(A);return this.set(Q,0,E,0,0,1,0,0,-E,0,Q,0,0,0,0,1),this}makeRotationZ(A){let Q=Math.cos(A),E=Math.sin(A);return this.set(Q,-E,0,0,E,Q,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(A,Q){let E=Math.cos(Q),B=Math.sin(Q),I=1-E,C=A.x,K=A.y,J=A.z,U=I*C,Y=I*K;return this.set(U*C+E,U*K-B*J,U*J+B*K,0,U*K+B*J,Y*K+E,Y*J-B*C,0,U*J-B*K,Y*J+B*C,I*J*J+E,0,0,0,0,1),this}makeScale(A,Q,E){return this.set(A,0,0,0,0,Q,0,0,0,0,E,0,0,0,0,1),this}makeShear(A,Q,E,B,I,C){return this.set(1,E,I,0,A,1,C,0,Q,B,1,0,0,0,0,1),this}compose(A,Q,E){let B=this.elements,I=Q._x,C=Q._y,K=Q._z,J=Q._w,U=I+I,Y=C+C,H=K+K,R=I*U,O=I*Y,N=I*H,$=C*Y,L=C*H,W=K*H,Z=J*U,G=J*Y,X=J*H,q=E.x,M=E.y,F=E.z;return B[0]=(1-($+W))*q,B[1]=(O+X)*q,B[2]=(N-G)*q,B[3]=0,B[4]=(O-X)*M,B[5]=(1-(R+W))*M,B[6]=(L+Z)*M,B[7]=0,B[8]=(N+G)*F,B[9]=(L-Z)*F,B[10]=(1-(R+$))*F,B[11]=0,B[12]=A.x,B[13]=A.y,B[14]=A.z,B[15]=1,this}decompose(A,Q,E){let B=this.elements,I=H8.set(B[0],B[1],B[2]).length(),C=H8.set(B[4],B[5],B[6]).length(),K=H8.set(B[8],B[9],B[10]).length();if(this.determinant()<0)I=-I;A.x=B[12],A.y=B[13],A.z=B[14],UB.copy(this);let U=1/I,Y=1/C,H=1/K;return UB.elements[0]*=U,UB.elements[1]*=U,UB.elements[2]*=U,UB.elements[4]*=Y,UB.elements[5]*=Y,UB.elements[6]*=Y,UB.elements[8]*=H,UB.elements[9]*=H,UB.elements[10]*=H,Q.setFromRotationMatrix(UB),E.x=I,E.y=C,E.z=K,this}makePerspective(A,Q,E,B,I,C,K=2000){let J=this.elements,U=2*I/(Q-A),Y=2*I/(E-B),H=(Q+A)/(Q-A),R=(E+B)/(E-B),O,N;if(K===2000)O=-(C+I)/(C-I),N=-2*C*I/(C-I);else if(K===2001)O=-C/(C-I),N=-C*I/(C-I);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+K);return J[0]=U,J[4]=0,J[8]=H,J[12]=0,J[1]=0,J[5]=Y,J[9]=R,J[13]=0,J[2]=0,J[6]=0,J[10]=O,J[14]=N,J[3]=0,J[7]=0,J[11]=-1,J[15]=0,this}makeOrthographic(A,Q,E,B,I,C,K=2000){let J=this.elements,U=1/(Q-A),Y=1/(E-B),H=1/(C-I),R=(Q+A)*U,O=(E+B)*Y,N,$;if(K===2000)N=(C+I)*H,$=-2*H;else if(K===2001)N=I*H,$=-1*H;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+K);return J[0]=2*U,J[4]=0,J[8]=0,J[12]=-R,J[1]=0,J[5]=2*Y,J[9]=0,J[13]=-O,J[2]=0,J[6]=0,J[10]=$,J[14]=-N,J[3]=0,J[7]=0,J[11]=0,J[15]=1,this}equals(A){let Q=this.elements,E=A.elements;for(let B=0;B<16;B++)if(Q[B]!==E[B])return!1;return!0}fromArray(A,Q=0){for(let E=0;E<16;E++)this.elements[E]=A[E+Q];return this}toArray(A=[],Q=0){let E=this.elements;return A[Q]=E[0],A[Q+1]=E[1],A[Q+2]=E[2],A[Q+3]=E[3],A[Q+4]=E[4],A[Q+5]=E[5],A[Q+6]=E[6],A[Q+7]=E[7],A[Q+8]=E[8],A[Q+9]=E[9],A[Q+10]=E[10],A[Q+11]=E[11],A[Q+12]=E[12],A[Q+13]=E[13],A[Q+14]=E[14],A[Q+15]=E[15],A}}var H8=/*@__PURE__*/new y,UB=/*@__PURE__*/new RA,e$=/*@__PURE__*/new y(0,0,0),AL=/*@__PURE__*/new y(1,1,1),wI=/*@__PURE__*/new y,tK=/*@__PURE__*/new y,kE=/*@__PURE__*/new y,d7=/*@__PURE__*/new RA,n7=/*@__PURE__*/new J0;class DQ{constructor(A=0,Q=0,E=0,B=DQ.DEFAULT_ORDER){this.isEuler=!0,this._x=A,this._y=Q,this._z=E,this._order=B}get x(){return this._x}set x(A){this._x=A,this._onChangeCallback()}get y(){return this._y}set y(A){this._y=A,this._onChangeCallback()}get z(){return this._z}set z(A){this._z=A,this._onChangeCallback()}get order(){return this._order}set order(A){this._order=A,this._onChangeCallback()}set(A,Q,E,B=this._order){return this._x=A,this._y=Q,this._z=E,this._order=B,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(A){return this._x=A._x,this._y=A._y,this._z=A._z,this._order=A._order,this._onChangeCallback(),this}setFromRotationMatrix(A,Q=this._order,E=!0){let B=A.elements,I=B[0],C=B[4],K=B[8],J=B[1],U=B[5],Y=B[9],H=B[2],R=B[6],O=B[10];switch(Q){case"XYZ":if(this._y=Math.asin(w0(K,-1,1)),Math.abs(K)<0.9999999)this._x=Math.atan2(-Y,O),this._z=Math.atan2(-C,I);else this._x=Math.atan2(R,U),this._z=0;break;case"YXZ":if(this._x=Math.asin(-w0(Y,-1,1)),Math.abs(Y)<0.9999999)this._y=Math.atan2(K,O),this._z=Math.atan2(J,U);else this._y=Math.atan2(-H,I),this._z=0;break;case"ZXY":if(this._x=Math.asin(w0(R,-1,1)),Math.abs(R)<0.9999999)this._y=Math.atan2(-H,O),this._z=Math.atan2(-C,U);else this._y=0,this._z=Math.atan2(J,I);break;case"ZYX":if(this._y=Math.asin(-w0(H,-1,1)),Math.abs(H)<0.9999999)this._x=Math.atan2(R,O),this._z=Math.atan2(J,I);else this._x=0,this._z=Math.atan2(-C,U);break;case"YZX":if(this._z=Math.asin(w0(J,-1,1)),Math.abs(J)<0.9999999)this._x=Math.atan2(-Y,U),this._y=Math.atan2(-H,I);else this._x=0,this._y=Math.atan2(K,O);break;case"XZY":if(this._z=Math.asin(-w0(C,-1,1)),Math.abs(C)<0.9999999)this._x=Math.atan2(R,U),this._y=Math.atan2(K,I);else this._x=Math.atan2(-Y,O),this._y=0;break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+Q)}if(this._order=Q,E===!0)this._onChangeCallback();return this}setFromQuaternion(A,Q,E){return d7.makeRotationFromQuaternion(A),this.setFromRotationMatrix(d7,Q,E)}setFromVector3(A,Q=this._order){return this.set(A.x,A.y,A.z,Q)}reorder(A){return n7.setFromEuler(this),this.setFromQuaternion(n7,A)}equals(A){return A._x===this._x&&A._y===this._y&&A._z===this._z&&A._order===this._order}fromArray(A){if(this._x=A[0],this._y=A[1],this._z=A[2],A[3]!==void 0)this._order=A[3];return this._onChangeCallback(),this}toArray(A=[],Q=0){return A[Q]=this._x,A[Q+1]=this._y,A[Q+2]=this._z,A[Q+3]=this._order,A}_onChange(A){return this._onChangeCallback=A,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}DQ.DEFAULT_ORDER="XYZ";class j1{constructor(){this.mask=1}set(A){this.mask=(1<>>0}enable(A){this.mask|=1<1){for(let Q=0;Q1){for(let E=0;E0)B.userData=this.userData;if(B.layers=this.layers.mask,B.matrix=this.matrix.toArray(),B.up=this.up.toArray(),this.matrixAutoUpdate===!1)B.matrixAutoUpdate=!1;if(this.isInstancedMesh){if(B.type="InstancedMesh",B.count=this.count,B.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null)B.instanceColor=this.instanceColor.toJSON()}if(this.isBatchedMesh){if(B.type="BatchedMesh",B.perObjectFrustumCulled=this.perObjectFrustumCulled,B.sortObjects=this.sortObjects,B.drawRanges=this._drawRanges,B.reservedRanges=this._reservedRanges,B.visibility=this._visibility,B.active=this._active,B.bounds=this._bounds.map((K)=>({boxInitialized:K.boxInitialized,boxMin:K.box.min.toArray(),boxMax:K.box.max.toArray(),sphereInitialized:K.sphereInitialized,sphereRadius:K.sphere.radius,sphereCenter:K.sphere.center.toArray()})),B.maxInstanceCount=this._maxInstanceCount,B.maxVertexCount=this._maxVertexCount,B.maxIndexCount=this._maxIndexCount,B.geometryInitialized=this._geometryInitialized,B.geometryCount=this._geometryCount,B.matricesTexture=this._matricesTexture.toJSON(A),this._colorsTexture!==null)B.colorsTexture=this._colorsTexture.toJSON(A);if(this.boundingSphere!==null)B.boundingSphere={center:B.boundingSphere.center.toArray(),radius:B.boundingSphere.radius};if(this.boundingBox!==null)B.boundingBox={min:B.boundingBox.min.toArray(),max:B.boundingBox.max.toArray()}}function I(K,J){if(K[J.uuid]===void 0)K[J.uuid]=J.toJSON(A);return J.uuid}if(this.isScene){if(this.background){if(this.background.isColor)B.background=this.background.toJSON();else if(this.background.isTexture)B.background=this.background.toJSON(A).uuid}if(this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0)B.environment=this.environment.toJSON(A).uuid}else if(this.isMesh||this.isLine||this.isPoints){B.geometry=I(A.geometries,this.geometry);let K=this.geometry.parameters;if(K!==void 0&&K.shapes!==void 0){let J=K.shapes;if(Array.isArray(J))for(let U=0,Y=J.length;U0){B.children=[];for(let K=0;K0){B.animations=[];for(let K=0;K0)E.geometries=K;if(J.length>0)E.materials=J;if(U.length>0)E.textures=U;if(Y.length>0)E.images=Y;if(H.length>0)E.shapes=H;if(R.length>0)E.skeletons=R;if(O.length>0)E.animations=O;if(N.length>0)E.nodes=N}return E.object=B,E;function C(K){let J=[];for(let U in K){let Y=K[U];delete Y.metadata,J.push(Y)}return J}}clone(A){return new this.constructor().copy(this,A)}copy(A,Q=!0){if(this.name=A.name,this.up.copy(A.up),this.position.copy(A.position),this.rotation.order=A.rotation.order,this.quaternion.copy(A.quaternion),this.scale.copy(A.scale),this.matrix.copy(A.matrix),this.matrixWorld.copy(A.matrixWorld),this.matrixAutoUpdate=A.matrixAutoUpdate,this.matrixWorldAutoUpdate=A.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=A.matrixWorldNeedsUpdate,this.layers.mask=A.layers.mask,this.visible=A.visible,this.castShadow=A.castShadow,this.receiveShadow=A.receiveShadow,this.frustumCulled=A.frustumCulled,this.renderOrder=A.renderOrder,this.animations=A.animations.slice(),this.userData=JSON.parse(JSON.stringify(A.userData)),Q===!0)for(let E=0;E0)return B.multiplyScalar(1/Math.sqrt(I));return B.set(0,0,0)}static getBarycoord(A,Q,E,B,I){YB.subVectors(B,Q),oB.subVectors(E,Q),KY.subVectors(A,Q);let C=YB.dot(YB),K=YB.dot(oB),J=YB.dot(KY),U=oB.dot(oB),Y=oB.dot(KY),H=C*U-K*K;if(H===0)return I.set(0,0,0),null;let R=1/H,O=(U*J-K*Y)*R,N=(C*Y-K*J)*R;return I.set(1-O-N,N,O)}static containsPoint(A,Q,E,B){if(this.getBarycoord(A,Q,E,B,rB)===null)return!1;return rB.x>=0&&rB.y>=0&&rB.x+rB.y<=1}static getInterpolation(A,Q,E,B,I,C,K,J){if(this.getBarycoord(A,Q,E,B,rB)===null){if(J.x=0,J.y=0,"z"in J)J.z=0;if("w"in J)J.w=0;return null}return J.setScalar(0),J.addScaledVector(I,rB.x),J.addScaledVector(C,rB.y),J.addScaledVector(K,rB.z),J}static getInterpolatedAttribute(A,Q,E,B,I,C){return OY.setScalar(0),HY.setScalar(0),ZY.setScalar(0),OY.fromBufferAttribute(A,Q),HY.fromBufferAttribute(A,E),ZY.fromBufferAttribute(A,B),C.setScalar(0),C.addScaledVector(OY,I.x),C.addScaledVector(HY,I.y),C.addScaledVector(ZY,I.z),C}static isFrontFacing(A,Q,E,B){return YB.subVectors(E,Q),oB.subVectors(A,Q),YB.cross(oB).dot(B)<0?!0:!1}set(A,Q,E){return this.a.copy(A),this.b.copy(Q),this.c.copy(E),this}setFromPointsAndIndices(A,Q,E,B){return this.a.copy(A[Q]),this.b.copy(A[E]),this.c.copy(A[B]),this}setFromAttributeAndIndices(A,Q,E,B){return this.a.fromBufferAttribute(A,Q),this.b.fromBufferAttribute(A,E),this.c.fromBufferAttribute(A,B),this}clone(){return new this.constructor().copy(this)}copy(A){return this.a.copy(A.a),this.b.copy(A.b),this.c.copy(A.c),this}getArea(){return YB.subVectors(this.c,this.b),oB.subVectors(this.a,this.b),YB.cross(oB).length()*0.5}getMidpoint(A){return A.addVectors(this.a,this.b).add(this.c).multiplyScalar(0.3333333333333333)}getNormal(A){return PQ.getNormal(this.a,this.b,this.c,A)}getPlane(A){return A.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(A,Q){return PQ.getBarycoord(A,this.a,this.b,this.c,Q)}getInterpolation(A,Q,E,B,I){return PQ.getInterpolation(A,this.a,this.b,this.c,Q,E,B,I)}containsPoint(A){return PQ.containsPoint(A,this.a,this.b,this.c)}isFrontFacing(A){return PQ.isFrontFacing(this.a,this.b,this.c,A)}intersectsBox(A){return A.intersectsTriangle(this)}closestPointToPoint(A,Q){let E=this.a,B=this.b,I=this.c,C,K;N8.subVectors(B,E),G8.subVectors(I,E),JY.subVectors(A,E);let J=N8.dot(JY),U=G8.dot(JY);if(J<=0&&U<=0)return Q.copy(E);UY.subVectors(A,B);let Y=N8.dot(UY),H=G8.dot(UY);if(Y>=0&&H<=Y)return Q.copy(B);let R=J*H-Y*U;if(R<=0&&J>=0&&Y<=0)return C=J/(J-Y),Q.copy(E).addScaledVector(N8,C);YY.subVectors(A,I);let O=N8.dot(YY),N=G8.dot(YY);if(N>=0&&O<=N)return Q.copy(I);let $=O*U-J*N;if($<=0&&U>=0&&N<=0)return K=U/(U-N),Q.copy(E).addScaledVector(G8,K);let L=Y*N-O*H;if(L<=0&&H-Y>=0&&O-N>=0)return t7.subVectors(I,B),K=(H-Y)/(H-Y+(O-N)),Q.copy(B).addScaledVector(t7,K);let W=1/(L+$+R);return C=$*W,K=R*W,Q.copy(E).addScaledVector(N8,C).addScaledVector(G8,K)}equals(A){return A.a.equals(this.a)&&A.b.equals(this.b)&&A.c.equals(this.c)}}var mR={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},_I={h:0,s:0,l:0},AJ={h:0,s:0,l:0};function RY(A,Q,E){if(E<0)E+=1;if(E>1)E-=1;if(E<0.16666666666666666)return A+(Q-A)*6*E;if(E<0.5)return Q;if(E<0.6666666666666666)return A+(Q-A)*6*(0.6666666666666666-E);return A}class a{constructor(A,Q,E){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(A,Q,E)}set(A,Q,E){if(Q===void 0&&E===void 0){let B=A;if(B&&B.isColor)this.copy(B);else if(typeof B==="number")this.setHex(B);else if(typeof B==="string")this.setStyle(B)}else this.setRGB(A,Q,E);return this}setScalar(A){return this.r=A,this.g=A,this.b=A,this}setHex(A,Q="srgb"){return A=Math.floor(A),this.r=(A>>16&255)/255,this.g=(A>>8&255)/255,this.b=(A&255)/255,O0.toWorkingColorSpace(this,Q),this}setRGB(A,Q,E,B=O0.workingColorSpace){return this.r=A,this.g=Q,this.b=E,O0.toWorkingColorSpace(this,B),this}setHSL(A,Q,E,B=O0.workingColorSpace){if(A=XO(A,1),Q=w0(Q,0,1),E=w0(E,0,1),Q===0)this.r=this.g=this.b=E;else{let I=E<=0.5?E*(1+Q):E+Q-E*Q,C=2*E-I;this.r=RY(C,I,A+0.3333333333333333),this.g=RY(C,I,A),this.b=RY(C,I,A-0.3333333333333333)}return O0.toWorkingColorSpace(this,B),this}setStyle(A,Q="srgb"){function E(I){if(I===void 0)return;if(parseFloat(I)<1)console.warn("THREE.Color: Alpha component of "+A+" will be ignored.")}let B;if(B=/^(\w+)\(([^\)]*)\)/.exec(A)){let I,C=B[1],K=B[2];switch(C){case"rgb":case"rgba":if(I=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(K))return E(I[4]),this.setRGB(Math.min(255,parseInt(I[1],10))/255,Math.min(255,parseInt(I[2],10))/255,Math.min(255,parseInt(I[3],10))/255,Q);if(I=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(K))return E(I[4]),this.setRGB(Math.min(100,parseInt(I[1],10))/100,Math.min(100,parseInt(I[2],10))/100,Math.min(100,parseInt(I[3],10))/100,Q);break;case"hsl":case"hsla":if(I=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(K))return E(I[4]),this.setHSL(parseFloat(I[1])/360,parseFloat(I[2])/100,parseFloat(I[3])/100,Q);break;default:console.warn("THREE.Color: Unknown color model "+A)}}else if(B=/^\#([A-Fa-f\d]+)$/.exec(A)){let I=B[1],C=I.length;if(C===3)return this.setRGB(parseInt(I.charAt(0),16)/15,parseInt(I.charAt(1),16)/15,parseInt(I.charAt(2),16)/15,Q);else if(C===6)return this.setHex(parseInt(I,16),Q);else console.warn("THREE.Color: Invalid hex color "+A)}else if(A&&A.length>0)return this.setColorName(A,Q);return this}setColorName(A,Q="srgb"){let E=mR[A.toLowerCase()];if(E!==void 0)this.setHex(E,Q);else console.warn("THREE.Color: Unknown color "+A);return this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(A){return this.r=A.r,this.g=A.g,this.b=A.b,this}copySRGBToLinear(A){return this.r=eB(A.r),this.g=eB(A.g),this.b=eB(A.b),this}copyLinearToSRGB(A){return this.r=k8(A.r),this.g=k8(A.g),this.b=k8(A.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(A="srgb"){return O0.fromWorkingColorSpace(eQ.copy(this),A),Math.round(w0(eQ.r*255,0,255))*65536+Math.round(w0(eQ.g*255,0,255))*256+Math.round(w0(eQ.b*255,0,255))}getHexString(A="srgb"){return("000000"+this.getHex(A).toString(16)).slice(-6)}getHSL(A,Q=O0.workingColorSpace){O0.fromWorkingColorSpace(eQ.copy(this),Q);let{r:E,g:B,b:I}=eQ,C=Math.max(E,B,I),K=Math.min(E,B,I),J,U,Y=(K+C)/2;if(K===C)J=0,U=0;else{let H=C-K;switch(U=Y<=0.5?H/(C+K):H/(2-C-K),C){case E:J=(B-I)/H+(B0!==A>0)this.version++;this._alphaTest=A}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(A){if(A===void 0)return;for(let Q in A){let E=A[Q];if(E===void 0){console.warn(`THREE.Material: parameter '${Q}' has value of undefined.`);continue}let B=this[Q];if(B===void 0){console.warn(`THREE.Material: '${Q}' is not a property of THREE.${this.type}.`);continue}if(B&&B.isColor)B.set(E);else if(B&&B.isVector3&&(E&&E.isVector3))B.copy(E);else this[Q]=E}}toJSON(A){let Q=A===void 0||typeof A==="string";if(Q)A={textures:{},images:{}};let E={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};if(E.uuid=this.uuid,E.type=this.type,this.name!=="")E.name=this.name;if(this.color&&this.color.isColor)E.color=this.color.getHex();if(this.roughness!==void 0)E.roughness=this.roughness;if(this.metalness!==void 0)E.metalness=this.metalness;if(this.sheen!==void 0)E.sheen=this.sheen;if(this.sheenColor&&this.sheenColor.isColor)E.sheenColor=this.sheenColor.getHex();if(this.sheenRoughness!==void 0)E.sheenRoughness=this.sheenRoughness;if(this.emissive&&this.emissive.isColor)E.emissive=this.emissive.getHex();if(this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1)E.emissiveIntensity=this.emissiveIntensity;if(this.specular&&this.specular.isColor)E.specular=this.specular.getHex();if(this.specularIntensity!==void 0)E.specularIntensity=this.specularIntensity;if(this.specularColor&&this.specularColor.isColor)E.specularColor=this.specularColor.getHex();if(this.shininess!==void 0)E.shininess=this.shininess;if(this.clearcoat!==void 0)E.clearcoat=this.clearcoat;if(this.clearcoatRoughness!==void 0)E.clearcoatRoughness=this.clearcoatRoughness;if(this.clearcoatMap&&this.clearcoatMap.isTexture)E.clearcoatMap=this.clearcoatMap.toJSON(A).uuid;if(this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture)E.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(A).uuid;if(this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture)E.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(A).uuid,E.clearcoatNormalScale=this.clearcoatNormalScale.toArray();if(this.dispersion!==void 0)E.dispersion=this.dispersion;if(this.iridescence!==void 0)E.iridescence=this.iridescence;if(this.iridescenceIOR!==void 0)E.iridescenceIOR=this.iridescenceIOR;if(this.iridescenceThicknessRange!==void 0)E.iridescenceThicknessRange=this.iridescenceThicknessRange;if(this.iridescenceMap&&this.iridescenceMap.isTexture)E.iridescenceMap=this.iridescenceMap.toJSON(A).uuid;if(this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture)E.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(A).uuid;if(this.anisotropy!==void 0)E.anisotropy=this.anisotropy;if(this.anisotropyRotation!==void 0)E.anisotropyRotation=this.anisotropyRotation;if(this.anisotropyMap&&this.anisotropyMap.isTexture)E.anisotropyMap=this.anisotropyMap.toJSON(A).uuid;if(this.map&&this.map.isTexture)E.map=this.map.toJSON(A).uuid;if(this.matcap&&this.matcap.isTexture)E.matcap=this.matcap.toJSON(A).uuid;if(this.alphaMap&&this.alphaMap.isTexture)E.alphaMap=this.alphaMap.toJSON(A).uuid;if(this.lightMap&&this.lightMap.isTexture)E.lightMap=this.lightMap.toJSON(A).uuid,E.lightMapIntensity=this.lightMapIntensity;if(this.aoMap&&this.aoMap.isTexture)E.aoMap=this.aoMap.toJSON(A).uuid,E.aoMapIntensity=this.aoMapIntensity;if(this.bumpMap&&this.bumpMap.isTexture)E.bumpMap=this.bumpMap.toJSON(A).uuid,E.bumpScale=this.bumpScale;if(this.normalMap&&this.normalMap.isTexture)E.normalMap=this.normalMap.toJSON(A).uuid,E.normalMapType=this.normalMapType,E.normalScale=this.normalScale.toArray();if(this.displacementMap&&this.displacementMap.isTexture)E.displacementMap=this.displacementMap.toJSON(A).uuid,E.displacementScale=this.displacementScale,E.displacementBias=this.displacementBias;if(this.roughnessMap&&this.roughnessMap.isTexture)E.roughnessMap=this.roughnessMap.toJSON(A).uuid;if(this.metalnessMap&&this.metalnessMap.isTexture)E.metalnessMap=this.metalnessMap.toJSON(A).uuid;if(this.emissiveMap&&this.emissiveMap.isTexture)E.emissiveMap=this.emissiveMap.toJSON(A).uuid;if(this.specularMap&&this.specularMap.isTexture)E.specularMap=this.specularMap.toJSON(A).uuid;if(this.specularIntensityMap&&this.specularIntensityMap.isTexture)E.specularIntensityMap=this.specularIntensityMap.toJSON(A).uuid;if(this.specularColorMap&&this.specularColorMap.isTexture)E.specularColorMap=this.specularColorMap.toJSON(A).uuid;if(this.envMap&&this.envMap.isTexture){if(E.envMap=this.envMap.toJSON(A).uuid,this.combine!==void 0)E.combine=this.combine}if(this.envMapRotation!==void 0)E.envMapRotation=this.envMapRotation.toArray();if(this.envMapIntensity!==void 0)E.envMapIntensity=this.envMapIntensity;if(this.reflectivity!==void 0)E.reflectivity=this.reflectivity;if(this.refractionRatio!==void 0)E.refractionRatio=this.refractionRatio;if(this.gradientMap&&this.gradientMap.isTexture)E.gradientMap=this.gradientMap.toJSON(A).uuid;if(this.transmission!==void 0)E.transmission=this.transmission;if(this.transmissionMap&&this.transmissionMap.isTexture)E.transmissionMap=this.transmissionMap.toJSON(A).uuid;if(this.thickness!==void 0)E.thickness=this.thickness;if(this.thicknessMap&&this.thicknessMap.isTexture)E.thicknessMap=this.thicknessMap.toJSON(A).uuid;if(this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0)E.attenuationDistance=this.attenuationDistance;if(this.attenuationColor!==void 0)E.attenuationColor=this.attenuationColor.getHex();if(this.size!==void 0)E.size=this.size;if(this.shadowSide!==null)E.shadowSide=this.shadowSide;if(this.sizeAttenuation!==void 0)E.sizeAttenuation=this.sizeAttenuation;if(this.blending!==1)E.blending=this.blending;if(this.side!==0)E.side=this.side;if(this.vertexColors===!0)E.vertexColors=!0;if(this.opacity<1)E.opacity=this.opacity;if(this.transparent===!0)E.transparent=!0;if(this.blendSrc!==204)E.blendSrc=this.blendSrc;if(this.blendDst!==205)E.blendDst=this.blendDst;if(this.blendEquation!==100)E.blendEquation=this.blendEquation;if(this.blendSrcAlpha!==null)E.blendSrcAlpha=this.blendSrcAlpha;if(this.blendDstAlpha!==null)E.blendDstAlpha=this.blendDstAlpha;if(this.blendEquationAlpha!==null)E.blendEquationAlpha=this.blendEquationAlpha;if(this.blendColor&&this.blendColor.isColor)E.blendColor=this.blendColor.getHex();if(this.blendAlpha!==0)E.blendAlpha=this.blendAlpha;if(this.depthFunc!==3)E.depthFunc=this.depthFunc;if(this.depthTest===!1)E.depthTest=this.depthTest;if(this.depthWrite===!1)E.depthWrite=this.depthWrite;if(this.colorWrite===!1)E.colorWrite=this.colorWrite;if(this.stencilWriteMask!==255)E.stencilWriteMask=this.stencilWriteMask;if(this.stencilFunc!==519)E.stencilFunc=this.stencilFunc;if(this.stencilRef!==0)E.stencilRef=this.stencilRef;if(this.stencilFuncMask!==255)E.stencilFuncMask=this.stencilFuncMask;if(this.stencilFail!==7680)E.stencilFail=this.stencilFail;if(this.stencilZFail!==7680)E.stencilZFail=this.stencilZFail;if(this.stencilZPass!==7680)E.stencilZPass=this.stencilZPass;if(this.stencilWrite===!0)E.stencilWrite=this.stencilWrite;if(this.rotation!==void 0&&this.rotation!==0)E.rotation=this.rotation;if(this.polygonOffset===!0)E.polygonOffset=!0;if(this.polygonOffsetFactor!==0)E.polygonOffsetFactor=this.polygonOffsetFactor;if(this.polygonOffsetUnits!==0)E.polygonOffsetUnits=this.polygonOffsetUnits;if(this.linewidth!==void 0&&this.linewidth!==1)E.linewidth=this.linewidth;if(this.dashSize!==void 0)E.dashSize=this.dashSize;if(this.gapSize!==void 0)E.gapSize=this.gapSize;if(this.scale!==void 0)E.scale=this.scale;if(this.dithering===!0)E.dithering=!0;if(this.alphaTest>0)E.alphaTest=this.alphaTest;if(this.alphaHash===!0)E.alphaHash=!0;if(this.alphaToCoverage===!0)E.alphaToCoverage=!0;if(this.premultipliedAlpha===!0)E.premultipliedAlpha=!0;if(this.forceSinglePass===!0)E.forceSinglePass=!0;if(this.wireframe===!0)E.wireframe=!0;if(this.wireframeLinewidth>1)E.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!=="round")E.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!=="round")E.wireframeLinejoin=this.wireframeLinejoin;if(this.flatShading===!0)E.flatShading=!0;if(this.visible===!1)E.visible=!1;if(this.toneMapped===!1)E.toneMapped=!1;if(this.fog===!1)E.fog=!1;if(Object.keys(this.userData).length>0)E.userData=this.userData;function B(I){let C=[];for(let K in I){let J=I[K];delete J.metadata,C.push(J)}return C}if(Q){let I=B(A.textures),C=B(A.images);if(I.length>0)E.textures=I;if(C.length>0)E.images=C}return E}clone(){return new this.constructor().copy(this)}copy(A){this.name=A.name,this.blending=A.blending,this.side=A.side,this.vertexColors=A.vertexColors,this.opacity=A.opacity,this.transparent=A.transparent,this.blendSrc=A.blendSrc,this.blendDst=A.blendDst,this.blendEquation=A.blendEquation,this.blendSrcAlpha=A.blendSrcAlpha,this.blendDstAlpha=A.blendDstAlpha,this.blendEquationAlpha=A.blendEquationAlpha,this.blendColor.copy(A.blendColor),this.blendAlpha=A.blendAlpha,this.depthFunc=A.depthFunc,this.depthTest=A.depthTest,this.depthWrite=A.depthWrite,this.stencilWriteMask=A.stencilWriteMask,this.stencilFunc=A.stencilFunc,this.stencilRef=A.stencilRef,this.stencilFuncMask=A.stencilFuncMask,this.stencilFail=A.stencilFail,this.stencilZFail=A.stencilZFail,this.stencilZPass=A.stencilZPass,this.stencilWrite=A.stencilWrite;let Q=A.clippingPlanes,E=null;if(Q!==null){let B=Q.length;E=new Array(B);for(let I=0;I!==B;++I)E[I]=Q[I].clone()}return this.clippingPlanes=E,this.clipIntersection=A.clipIntersection,this.clipShadows=A.clipShadows,this.shadowSide=A.shadowSide,this.colorWrite=A.colorWrite,this.precision=A.precision,this.polygonOffset=A.polygonOffset,this.polygonOffsetFactor=A.polygonOffsetFactor,this.polygonOffsetUnits=A.polygonOffsetUnits,this.dithering=A.dithering,this.alphaTest=A.alphaTest,this.alphaHash=A.alphaHash,this.alphaToCoverage=A.alphaToCoverage,this.premultipliedAlpha=A.premultipliedAlpha,this.forceSinglePass=A.forceSinglePass,this.visible=A.visible,this.toneMapped=A.toneMapped,this.userData=JSON.parse(JSON.stringify(A.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(A){if(A===!0)this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class _0 extends $Q{constructor(A){super();this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new a(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new DQ,this.combine=0,this.reflectivity=1,this.refractionRatio=0.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.specularMap=A.specularMap,this.alphaMap=A.alphaMap,this.envMap=A.envMap,this.envMapRotation.copy(A.envMapRotation),this.combine=A.combine,this.reflectivity=A.reflectivity,this.refractionRatio=A.refractionRatio,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.fog=A.fog,this}}var tB=/*@__PURE__*/KL();function KL(){let A=new ArrayBuffer(4),Q=new Float32Array(A),E=new Uint32Array(A),B=new Uint32Array(512),I=new Uint32Array(512);for(let U=0;U<256;++U){let Y=U-127;if(Y<-27)B[U]=0,B[U|256]=32768,I[U]=24,I[U|256]=24;else if(Y<-14)B[U]=1024>>-Y-14,B[U|256]=1024>>-Y-14|32768,I[U]=-Y-1,I[U|256]=-Y-1;else if(Y<=15)B[U]=Y+15<<10,B[U|256]=Y+15<<10|32768,I[U]=13,I[U|256]=13;else if(Y<128)B[U]=31744,B[U|256]=64512,I[U]=24,I[U|256]=24;else B[U]=31744,B[U|256]=64512,I[U]=13,I[U|256]=13}let C=new Uint32Array(2048),K=new Uint32Array(64),J=new Uint32Array(64);for(let U=1;U<1024;++U){let Y=U<<13,H=0;while((Y&8388608)===0)Y<<=1,H-=8388608;Y&=-8388609,H+=947912704,C[U]=Y|H}for(let U=1024;U<2048;++U)C[U]=939524096+(U-1024<<13);for(let U=1;U<31;++U)K[U]=U<<23;K[31]=1199570944,K[32]=2147483648;for(let U=33;U<63;++U)K[U]=2147483648+(U-32<<23);K[63]=3347054592;for(let U=1;U<64;++U)if(U!==32)J[U]=1024;return{floatView:Q,uint32View:E,baseTable:B,shiftTable:I,mantissaTable:C,exponentTable:K,offsetTable:J}}function GE(A){if(Math.abs(A)>65504)console.warn("THREE.DataUtils.toHalfFloat(): Value out of range.");A=w0(A,-65504,65504),tB.floatView[0]=A;let Q=tB.uint32View[0],E=Q>>23&511;return tB.baseTable[E]+((Q&8388607)>>tB.shiftTable[E])}function a6(A){let Q=A>>10;return tB.uint32View[0]=tB.mantissaTable[tB.offsetTable[Q]+(A&1023)]+tB.exponentTable[Q],tB.floatView[0]}var vE={toHalfFloat:GE,fromHalfFloat:a6},zQ=/*@__PURE__*/new y,QJ=/*@__PURE__*/new AA,JL=0;class tA{constructor(A,Q,E=!1){if(Array.isArray(A))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:JL++}),this.name="",this.array=A,this.itemSize=Q,this.count=A!==void 0?A.length/Q:0,this.normalized=E,this.usage=35044,this.updateRanges=[],this.gpuType=1015,this.version=0}onUploadCallback(){}set needsUpdate(A){if(A===!0)this.version++}setUsage(A){return this.usage=A,this}addUpdateRange(A,Q){this.updateRanges.push({start:A,count:Q})}clearUpdateRanges(){this.updateRanges.length=0}copy(A){return this.name=A.name,this.array=new A.array.constructor(A.array),this.itemSize=A.itemSize,this.count=A.count,this.normalized=A.normalized,this.usage=A.usage,this.gpuType=A.gpuType,this}copyAt(A,Q,E){A*=this.itemSize,E*=Q.itemSize;for(let B=0,I=this.itemSize;BQ.count)console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.");Q.needsUpdate=!0}return this}computeBoundingBox(){if(this.boundingBox===null)this.boundingBox=new g0;let A=this.attributes.position,Q=this.morphAttributes.position;if(A&&A.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new y(-1/0,-1/0,-1/0),new y(1/0,1/0,1/0));return}if(A!==void 0){if(this.boundingBox.setFromBufferAttribute(A),Q)for(let E=0,B=Q.length;E0)A.userData=this.userData;if(this.parameters!==void 0){let J=this.parameters;for(let U in J)if(J[U]!==void 0)A[U]=J[U];return A}A.data={attributes:{}};let Q=this.index;if(Q!==null)A.data.index={type:Q.array.constructor.name,array:Array.prototype.slice.call(Q.array)};let E=this.attributes;for(let J in E){let U=E[J];A.data.attributes[J]=U.toJSON(A.data)}let B={},I=!1;for(let J in this.morphAttributes){let U=this.morphAttributes[J],Y=[];for(let H=0,R=U.length;H0)B[J]=Y,I=!0}if(I)A.data.morphAttributes=B,A.data.morphTargetsRelative=this.morphTargetsRelative;let C=this.groups;if(C.length>0)A.data.groups=JSON.parse(JSON.stringify(C));let K=this.boundingSphere;if(K!==null)A.data.boundingSphere={center:K.center.toArray(),radius:K.radius};return A}clone(){return new this.constructor().copy(this)}copy(A){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let Q={};this.name=A.name;let E=A.index;if(E!==null)this.setIndex(E.clone(Q));let B=A.attributes;for(let U in B){let Y=B[U];this.setAttribute(U,Y.clone(Q))}let I=A.morphAttributes;for(let U in I){let Y=[],H=I[U];for(let R=0,O=H.length;R0){let B=Q[E[0]];if(B!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let I=0,C=B.length;I(A.far-A.near)**2)return}if(e7.copy(I).invert(),A1.copy(A.ray).applyMatrix4(e7),E.boundingBox!==null){if(A1.intersectsBox(E.boundingBox)===!1)return}this._computeIntersections(A,Q,A1)}_computeIntersections(A,Q,E){let B,I=this.geometry,C=this.material,K=I.index,J=I.attributes.position,U=I.attributes.uv,Y=I.attributes.uv1,H=I.attributes.normal,R=I.groups,O=I.drawRange;if(K!==null)if(Array.isArray(C))for(let N=0,$=R.length;N<$;N++){let L=R[N],W=C[L.materialIndex],Z=Math.max(L.start,O.start),G=Math.min(K.count,Math.min(L.start+L.count,O.start+O.count));for(let X=Z,q=G;XE.far)return null;return{distance:Y,point:JJ.clone(),object:A}}function UJ(A,Q,E,B,I,C,K,J,U,Y){A.getVertexPosition(J,BJ),A.getVertexPosition(U,IJ),A.getVertexPosition(Y,CJ);let H=YL(A,Q,E,B,BJ,IJ,CJ,QZ);if(H){let R=new y;if(PQ.getBarycoord(QZ,BJ,IJ,CJ,R),I)H.uv=PQ.getInterpolatedAttribute(I,J,U,Y,R,new AA);if(C)H.uv1=PQ.getInterpolatedAttribute(C,J,U,Y,R,new AA);if(K){if(H.normal=PQ.getInterpolatedAttribute(K,J,U,Y,R,new y),H.normal.dot(B.direction)>0)H.normal.multiplyScalar(-1)}let O={a:J,b:U,c:Y,normal:new y,materialIndex:0};PQ.getNormal(BJ,IJ,CJ,O.normal),H.face=O,H.barycoord=R}return H}class bQ extends hA{constructor(A=1,Q=1,E=1,B=1,I=1,C=1){super();this.type="BoxGeometry",this.parameters={width:A,height:Q,depth:E,widthSegments:B,heightSegments:I,depthSegments:C};let K=this;B=Math.floor(B),I=Math.floor(I),C=Math.floor(C);let J=[],U=[],Y=[],H=[],R=0,O=0;N("z","y","x",-1,-1,E,Q,A,C,I,0),N("z","y","x",1,-1,E,Q,-A,C,I,1),N("x","z","y",1,1,A,E,Q,B,C,2),N("x","z","y",1,-1,A,E,-Q,B,C,3),N("x","y","z",1,-1,A,Q,E,B,I,4),N("x","y","z",-1,-1,A,Q,-E,B,I,5),this.setIndex(J),this.setAttribute("position",new PA(U,3)),this.setAttribute("normal",new PA(Y,3)),this.setAttribute("uv",new PA(H,2));function N($,L,W,Z,G,X,q,M,F,D,_){let w=X/F,k=q/D,T=X/2,z=q/2,j=M/2,v=F+1,g=D+1,P=0,V=0,S=new y;for(let h=0;h0?1:-1,Y.push(S.x,S.y,S.z),H.push(b/F),H.push(1-h/D),P+=1}}for(let h=0;h0)Q.defines=this.defines;Q.vertexShader=this.vertexShader,Q.fragmentShader=this.fragmentShader,Q.lights=this.lights,Q.clipping=this.clipping;let E={};for(let B in this.extensions)if(this.extensions[B]===!0)E[B]=!0;if(Object.keys(E).length>0)Q.extensions=E;return Q}}class h1 extends I0{constructor(){super();this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new RA,this.projectionMatrix=new RA,this.projectionMatrixInverse=new RA,this.coordinateSystem=2000}copy(A,Q){return super.copy(A,Q),this.matrixWorldInverse.copy(A.matrixWorldInverse),this.projectionMatrix.copy(A.projectionMatrix),this.projectionMatrixInverse.copy(A.projectionMatrixInverse),this.coordinateSystem=A.coordinateSystem,this}getWorldDirection(A){return super.getWorldDirection(A).negate()}updateMatrixWorld(A){super.updateMatrixWorld(A),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(A,Q){super.updateWorldMatrix(A,Q),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}var kI=/*@__PURE__*/new y,EZ=/*@__PURE__*/new AA,BZ=/*@__PURE__*/new AA;class v0 extends h1{constructor(A=50,Q=1,E=0.1,B=2000){super();this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=A,this.zoom=1,this.near=E,this.far=B,this.focus=10,this.aspect=Q,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(A,Q){return super.copy(A,Q),this.fov=A.fov,this.zoom=A.zoom,this.near=A.near,this.far=A.far,this.focus=A.focus,this.aspect=A.aspect,this.view=A.view===null?null:Object.assign({},A.view),this.filmGauge=A.filmGauge,this.filmOffset=A.filmOffset,this}setFocalLength(A){let Q=0.5*this.getFilmHeight()/A;this.fov=H1*2*Math.atan(Q),this.updateProjectionMatrix()}getFocalLength(){let A=Math.tan(O1*0.5*this.fov);return 0.5*this.getFilmHeight()/A}getEffectiveFOV(){return H1*2*Math.atan(Math.tan(O1*0.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(A,Q,E){kI.set(-1,-1,0.5).applyMatrix4(this.projectionMatrixInverse),Q.set(kI.x,kI.y).multiplyScalar(-A/kI.z),kI.set(1,1,0.5).applyMatrix4(this.projectionMatrixInverse),E.set(kI.x,kI.y).multiplyScalar(-A/kI.z)}getViewSize(A,Q){return this.getViewBounds(A,EZ,BZ),Q.subVectors(BZ,EZ)}setViewOffset(A,Q,E,B,I,C){if(this.aspect=A/Q,this.view===null)this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1};this.view.enabled=!0,this.view.fullWidth=A,this.view.fullHeight=Q,this.view.offsetX=E,this.view.offsetY=B,this.view.width=I,this.view.height=C,this.updateProjectionMatrix()}clearViewOffset(){if(this.view!==null)this.view.enabled=!1;this.updateProjectionMatrix()}updateProjectionMatrix(){let A=this.near,Q=A*Math.tan(O1*0.5*this.fov)/this.zoom,E=2*Q,B=this.aspect*E,I=-0.5*B,C=this.view;if(this.view!==null&&this.view.enabled){let{fullWidth:J,fullHeight:U}=C;I+=C.offsetX*B/J,Q-=C.offsetY*E/U,B*=C.width/J,E*=C.height/U}let K=this.filmOffset;if(K!==0)I+=A*K/this.getFilmWidth();this.projectionMatrix.makePerspective(I,I+B,Q,Q-E,A,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(A){let Q=super.toJSON(A);if(Q.object.fov=this.fov,Q.object.zoom=this.zoom,Q.object.near=this.near,Q.object.far=this.far,Q.object.focus=this.focus,Q.object.aspect=this.aspect,this.view!==null)Q.object.view=Object.assign({},this.view);return Q.object.filmGauge=this.filmGauge,Q.object.filmOffset=this.filmOffset,Q}}var X8=-90,$8=1;class D9 extends I0{constructor(A,Q,E){super();this.type="CubeCamera",this.renderTarget=E,this.coordinateSystem=null,this.activeMipmapLevel=0;let B=new v0(X8,$8,A,Q);B.layers=this.layers,this.add(B);let I=new v0(X8,$8,A,Q);I.layers=this.layers,this.add(I);let C=new v0(X8,$8,A,Q);C.layers=this.layers,this.add(C);let K=new v0(X8,$8,A,Q);K.layers=this.layers,this.add(K);let J=new v0(X8,$8,A,Q);J.layers=this.layers,this.add(J);let U=new v0(X8,$8,A,Q);U.layers=this.layers,this.add(U)}updateCoordinateSystem(){let A=this.coordinateSystem,Q=this.children.concat(),[E,B,I,C,K,J]=Q;for(let U of Q)this.remove(U);if(A===2000)E.up.set(0,1,0),E.lookAt(1,0,0),B.up.set(0,1,0),B.lookAt(-1,0,0),I.up.set(0,0,-1),I.lookAt(0,1,0),C.up.set(0,0,1),C.lookAt(0,-1,0),K.up.set(0,1,0),K.lookAt(0,0,1),J.up.set(0,1,0),J.lookAt(0,0,-1);else if(A===2001)E.up.set(0,-1,0),E.lookAt(-1,0,0),B.up.set(0,-1,0),B.lookAt(1,0,0),I.up.set(0,0,1),I.lookAt(0,1,0),C.up.set(0,0,-1),C.lookAt(0,-1,0),K.up.set(0,-1,0),K.lookAt(0,0,1),J.up.set(0,-1,0),J.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+A);for(let U of Q)this.add(U),U.updateMatrixWorld()}update(A,Q){if(this.parent===null)this.updateMatrixWorld();let{renderTarget:E,activeMipmapLevel:B}=this;if(this.coordinateSystem!==A.coordinateSystem)this.coordinateSystem=A.coordinateSystem,this.updateCoordinateSystem();let[I,C,K,J,U,Y]=this.children,H=A.getRenderTarget(),R=A.getActiveCubeFace(),O=A.getActiveMipmapLevel(),N=A.xr.enabled;A.xr.enabled=!1;let $=E.texture.generateMipmaps;E.texture.generateMipmaps=!1,A.setRenderTarget(E,0,B),A.render(Q,I),A.setRenderTarget(E,1,B),A.render(Q,C),A.setRenderTarget(E,2,B),A.render(Q,K),A.setRenderTarget(E,3,B),A.render(Q,J),A.setRenderTarget(E,4,B),A.render(Q,U),E.texture.generateMipmaps=$,A.setRenderTarget(E,5,B),A.render(Q,Y),A.setRenderTarget(H,R,O),A.xr.enabled=N,E.texture.needsPMREMUpdate=!0}}class QI extends EQ{constructor(A,Q,E,B,I,C,K,J,U,Y){A=A!==void 0?A:[],Q=Q!==void 0?Q:301;super(A,Q,E,B,I,C,K,J,U,Y);this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(A){this.image=A}}class DC extends Q0{constructor(A=1,Q={}){super(A,A,Q);this.isWebGLCubeRenderTarget=!0;let E={width:A,height:A,depth:1},B=[E,E,E,E,E,E];this.texture=new QI(B,Q.mapping,Q.wrapS,Q.wrapT,Q.magFilter,Q.minFilter,Q.format,Q.type,Q.anisotropy,Q.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=Q.generateMipmaps!==void 0?Q.generateMipmaps:!1,this.texture.minFilter=Q.minFilter!==void 0?Q.minFilter:1006}fromEquirectangularTexture(A,Q){this.texture.type=Q.type,this.texture.colorSpace=Q.colorSpace,this.texture.generateMipmaps=Q.generateMipmaps,this.texture.minFilter=Q.minFilter,this.texture.magFilter=Q.magFilter;let E={uniforms:{tEquirect:{value:null}},vertexShader:` - - varying vec3 vWorldDirection; - - vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); - - } - - void main() { - - vWorldDirection = transformDirection( position, modelMatrix ); - - #include - #include - - } - `,fragmentShader:` - - uniform sampler2D tEquirect; - - varying vec3 vWorldDirection; - - #include - - void main() { - - vec3 direction = normalize( vWorldDirection ); - - vec2 sampleUV = equirectUv( direction ); - - gl_FragColor = texture2D( tEquirect, sampleUV ); - - } - `},B=new bQ(5,5,5),I=new bA({name:"CubemapFromEquirect",uniforms:v1(E.uniforms),vertexShader:E.vertexShader,fragmentShader:E.fragmentShader,side:1,blending:0});I.uniforms.tEquirect.value=Q;let C=new xA(B,I),K=Q.minFilter;if(Q.minFilter===1008)Q.minFilter=1006;return new D9(1,10,this).update(A,C),Q.minFilter=K,C.geometry.dispose(),C.material.dispose(),this}clear(A,Q,E,B){let I=A.getRenderTarget();for(let C=0;C<6;C++)A.setRenderTarget(this,C),A.clear(Q,E,B);A.setRenderTarget(I)}}class i0 extends I0{constructor(){super();this.isGroup=!0,this.type="Group"}}var RL={type:"move"};class m8{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){if(this._hand===null)this._hand=new i0,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1};return this._hand}getTargetRaySpace(){if(this._targetRay===null)this._targetRay=new i0,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new y,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new y;return this._targetRay}getGripSpace(){if(this._grip===null)this._grip=new i0,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new y,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new y;return this._grip}dispatchEvent(A){if(this._targetRay!==null)this._targetRay.dispatchEvent(A);if(this._grip!==null)this._grip.dispatchEvent(A);if(this._hand!==null)this._hand.dispatchEvent(A);return this}connect(A){if(A&&A.hand){let Q=this._hand;if(Q)for(let E of A.hand.values())this._getHandJoint(Q,E)}return this.dispatchEvent({type:"connected",data:A}),this}disconnect(A){if(this.dispatchEvent({type:"disconnected",data:A}),this._targetRay!==null)this._targetRay.visible=!1;if(this._grip!==null)this._grip.visible=!1;if(this._hand!==null)this._hand.visible=!1;return this}update(A,Q,E){let B=null,I=null,C=null,K=this._targetRay,J=this._grip,U=this._hand;if(A&&Q.session.visibilityState!=="visible-blurred"){if(U&&A.hand){C=!0;for(let $ of A.hand.values()){let L=Q.getJointPose($,E),W=this._getHandJoint(U,$);if(L!==null)W.matrix.fromArray(L.transform.matrix),W.matrix.decompose(W.position,W.rotation,W.scale),W.matrixWorldNeedsUpdate=!0,W.jointRadius=L.radius;W.visible=L!==null}let Y=U.joints["index-finger-tip"],H=U.joints["thumb-tip"],R=Y.position.distanceTo(H.position),O=0.02,N=0.005;if(U.inputState.pinching&&R>O+N)U.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:A.handedness,target:this});else if(!U.inputState.pinching&&R<=O-N)U.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:A.handedness,target:this})}else if(J!==null&&A.gripSpace){if(I=Q.getPose(A.gripSpace,E),I!==null){if(J.matrix.fromArray(I.transform.matrix),J.matrix.decompose(J.position,J.rotation,J.scale),J.matrixWorldNeedsUpdate=!0,I.linearVelocity)J.hasLinearVelocity=!0,J.linearVelocity.copy(I.linearVelocity);else J.hasLinearVelocity=!1;if(I.angularVelocity)J.hasAngularVelocity=!0,J.angularVelocity.copy(I.angularVelocity);else J.hasAngularVelocity=!1}}if(K!==null){if(B=Q.getPose(A.targetRaySpace,E),B===null&&I!==null)B=I;if(B!==null){if(K.matrix.fromArray(B.transform.matrix),K.matrix.decompose(K.position,K.rotation,K.scale),K.matrixWorldNeedsUpdate=!0,B.linearVelocity)K.hasLinearVelocity=!0,K.linearVelocity.copy(B.linearVelocity);else K.hasLinearVelocity=!1;if(B.angularVelocity)K.hasAngularVelocity=!0,K.angularVelocity.copy(B.angularVelocity);else K.hasAngularVelocity=!1;this.dispatchEvent(RL)}}}if(K!==null)K.visible=B!==null;if(J!==null)J.visible=I!==null;if(U!==null)U.visible=C!==null;return this}_getHandJoint(A,Q){if(A.joints[Q.jointName]===void 0){let E=new i0;E.matrixAutoUpdate=!1,E.visible=!1,A.joints[Q.jointName]=E,A.add(E)}return A.joints[Q.jointName]}}class MC{constructor(A,Q=0.00025){this.isFogExp2=!0,this.name="",this.color=new a(A),this.density=Q}clone(){return new MC(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class wC{constructor(A,Q=1,E=1000){this.isFog=!0,this.name="",this.color=new a(A),this.near=Q,this.far=E}clone(){return new wC(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class yQ extends I0{constructor(){super();if(this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new DQ,this.environmentIntensity=1,this.environmentRotation=new DQ,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__!=="undefined")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(A,Q){if(super.copy(A,Q),A.background!==null)this.background=A.background.clone();if(A.environment!==null)this.environment=A.environment.clone();if(A.fog!==null)this.fog=A.fog.clone();if(this.backgroundBlurriness=A.backgroundBlurriness,this.backgroundIntensity=A.backgroundIntensity,this.backgroundRotation.copy(A.backgroundRotation),this.environmentIntensity=A.environmentIntensity,this.environmentRotation.copy(A.environmentRotation),A.overrideMaterial!==null)this.overrideMaterial=A.overrideMaterial.clone();return this.matrixAutoUpdate=A.matrixAutoUpdate,this}toJSON(A){let Q=super.toJSON(A);if(this.fog!==null)Q.object.fog=this.fog.toJSON();if(this.backgroundBlurriness>0)Q.object.backgroundBlurriness=this.backgroundBlurriness;if(this.backgroundIntensity!==1)Q.object.backgroundIntensity=this.backgroundIntensity;if(Q.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1)Q.object.environmentIntensity=this.environmentIntensity;return Q.object.environmentRotation=this.environmentRotation.toArray(),Q}}class hE{constructor(A,Q){this.isInterleavedBuffer=!0,this.array=A,this.stride=Q,this.count=A!==void 0?A.length/Q:0,this.usage=35044,this.updateRanges=[],this.version=0,this.uuid=TE()}onUploadCallback(){}set needsUpdate(A){if(A===!0)this.version++}setUsage(A){return this.usage=A,this}addUpdateRange(A,Q){this.updateRanges.push({start:A,count:Q})}clearUpdateRanges(){this.updateRanges.length=0}copy(A){return this.array=new A.array.constructor(A.array),this.count=A.count,this.stride=A.stride,this.usage=A.usage,this}copyAt(A,Q,E){A*=this.stride,E*=Q.stride;for(let B=0,I=this.stride;BA.far)return;Q.push({distance:J,point:c6.clone(),uv:PQ.getInterpolation(c6,YJ,d6,OJ,IZ,WY,CZ,new AA),face:null,object:this})}copy(A,Q){if(super.copy(A,Q),A.center!==void 0)this.center.copy(A.center);return this.material=A.material,this}}function HJ(A,Q,E,B,I,C){if(D8.subVectors(A,E).addScalar(0.5).multiply(B),I!==void 0)l6.x=C*D8.x-I*D8.y,l6.y=I*D8.x+C*D8.y;else l6.copy(D8);A.copy(Q),A.x+=l6.x,A.y+=l6.y,A.applyMatrix4(cR)}var ZJ=/*@__PURE__*/new y,KZ=/*@__PURE__*/new y;class M9 extends I0{constructor(){super();this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(A){super.copy(A,!1);let Q=A.levels;for(let E=0,B=Q.length;E0){let E,B;for(E=1,B=Q.length;E0){ZJ.setFromMatrixPosition(this.matrixWorld);let B=A.ray.origin.distanceTo(ZJ);this.getObjectForDistance(B).raycast(A,Q)}}update(A){let Q=this.levels;if(Q.length>1){ZJ.setFromMatrixPosition(A.matrixWorld),KZ.setFromMatrixPosition(this.matrixWorld);let E=ZJ.distanceTo(KZ)/A.zoom;Q[0].object.visible=!0;let B,I;for(B=1,I=Q.length;B=C)Q[B-1].object.visible=!1,Q[B].object.visible=!0;else break}this._currentLevel=B-1;for(;B1)return null;return Q.copy(A.start).addScaledVector(E,I)}intersectsLine(A){let Q=this.distanceToPoint(A.start),E=this.distanceToPoint(A.end);return Q<0&&E>0||E<0&&Q>0}intersectsBox(A){return A.intersectsPlane(this)}intersectsSphere(A){return A.intersectsPlane(this)}coplanarPoint(A){return A.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(A,Q){let E=Q||$L.getNormalMatrix(A),B=this.coplanarPoint(LY).applyMatrix4(A),I=this.normal.applyMatrix3(E).normalize();return this.constant=-B.dot(I),this}translate(A){return this.constant-=A.dot(this.normal),this}equals(A){return A.normal.equals(this.normal)&&A.constant===this.constant}clone(){return new this.constructor().copy(this)}}var Q1=/*@__PURE__*/new KQ,GJ=/*@__PURE__*/new y;class xB{constructor(A=new UQ,Q=new UQ,E=new UQ,B=new UQ,I=new UQ,C=new UQ){this.planes=[A,Q,E,B,I,C]}set(A,Q,E,B,I,C){let K=this.planes;return K[0].copy(A),K[1].copy(Q),K[2].copy(E),K[3].copy(B),K[4].copy(I),K[5].copy(C),this}copy(A){let Q=this.planes;for(let E=0;E<6;E++)Q[E].copy(A.planes[E]);return this}setFromProjectionMatrix(A,Q=2000){let E=this.planes,B=A.elements,I=B[0],C=B[1],K=B[2],J=B[3],U=B[4],Y=B[5],H=B[6],R=B[7],O=B[8],N=B[9],$=B[10],L=B[11],W=B[12],Z=B[13],G=B[14],X=B[15];if(E[0].setComponents(J-I,R-U,L-O,X-W).normalize(),E[1].setComponents(J+I,R+U,L+O,X+W).normalize(),E[2].setComponents(J+C,R+Y,L+N,X+Z).normalize(),E[3].setComponents(J-C,R-Y,L-N,X-Z).normalize(),E[4].setComponents(J-K,R-H,L-$,X-G).normalize(),Q===2000)E[5].setComponents(J+K,R+H,L+$,X+G).normalize();else if(Q===2001)E[5].setComponents(K,H,$,G).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+Q);return this}intersectsObject(A){if(A.boundingSphere!==void 0){if(A.boundingSphere===null)A.computeBoundingSphere();Q1.copy(A.boundingSphere).applyMatrix4(A.matrixWorld)}else{let Q=A.geometry;if(Q.boundingSphere===null)Q.computeBoundingSphere();Q1.copy(Q.boundingSphere).applyMatrix4(A.matrixWorld)}return this.intersectsSphere(Q1)}intersectsSprite(A){return Q1.center.set(0,0,0),Q1.radius=0.7071067811865476,Q1.applyMatrix4(A.matrixWorld),this.intersectsSphere(Q1)}intersectsSphere(A){let Q=this.planes,E=A.center,B=-A.radius;for(let I=0;I<6;I++)if(Q[I].distanceToPoint(E)0?A.max.x:A.min.x,GJ.y=B.normal.y>0?A.max.y:A.min.y,GJ.z=B.normal.z>0?A.max.z:A.min.z,B.distanceToPoint(GJ)<0)return!1}return!0}containsPoint(A){let Q=this.planes;for(let E=0;E<6;E++)if(Q[E].distanceToPoint(A)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}function qY(A,Q){return A-Q}function LL(A,Q){return A.z-Q.z}function qL(A,Q){return Q.z-A.z}class lR{constructor(){this.index=0,this.pool=[],this.list=[]}push(A,Q,E,B){let I=this.pool,C=this.list;if(this.index>=I.length)I.push({start:-1,count:-1,z:-1,index:-1});let K=I[this.index];C.push(K),this.index++,K.start=A,K.count=Q,K.z=E,K.index=B}reset(){this.list.length=0,this.index=0}}var NE=/*@__PURE__*/new RA,FL=/*@__PURE__*/new a(1,1,1),FY=/*@__PURE__*/new xB,WJ=/*@__PURE__*/new g0,E1=/*@__PURE__*/new KQ,i6=/*@__PURE__*/new y,GZ=/*@__PURE__*/new y,DL=/*@__PURE__*/new y,DY=/*@__PURE__*/new lR,AE=/*@__PURE__*/new xA,XJ=[];function ML(A,Q,E=0){let B=Q.itemSize;if(A.isInterleavedBufferAttribute||A.array.constructor!==Q.array.constructor){let I=A.count;for(let C=0;C65535?new Uint32Array(B):new Uint16Array(B);Q.setIndex(new tA(I,1))}this._geometryInitialized=!0}}_validateGeometry(A){let Q=this.geometry;if(Boolean(A.getIndex())!==Boolean(Q.getIndex()))throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(let E in Q.attributes){if(!A.hasAttribute(E))throw new Error(`THREE.BatchedMesh: Added geometry missing "${E}". All geometries must have consistent attributes.`);let B=A.getAttribute(E),I=Q.getAttribute(E);if(B.itemSize!==I.itemSize||B.normalized!==I.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(A){let Q=this._instanceInfo;if(A<0||A>=Q.length||Q[A].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${A}. Instance is either out of range or has been deleted.`)}validateGeometryId(A){let Q=this._geometryInfo;if(A<0||A>=Q.length||Q[A].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${A}. Geometry is either out of range or has been deleted.`)}setCustomSort(A){return this.customSort=A,this}computeBoundingBox(){if(this.boundingBox===null)this.boundingBox=new g0;let A=this.boundingBox,Q=this._instanceInfo;A.makeEmpty();for(let E=0,B=Q.length;E=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");let E={visible:!0,active:!0,geometryIndex:A},B=null;if(this._availableInstanceIds.length>0)this._availableInstanceIds.sort(qY),B=this._availableInstanceIds.shift(),this._instanceInfo[B]=E;else B=this._instanceInfo.length,this._instanceInfo.push(E);let I=this._matricesTexture;NE.identity().toArray(I.image.data,B*16),I.needsUpdate=!0;let C=this._colorsTexture;if(C)FL.toArray(C.image.data,B*4),C.needsUpdate=!0;return this._visibilityChanged=!0,B}addGeometry(A,Q=-1,E=-1){this._initializeGeometry(A),this._validateGeometry(A);let B={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},I=this._geometryInfo;B.vertexStart=this._nextVertexStart,B.reservedVertexCount=Q===-1?A.getAttribute("position").count:Q;let C=A.getIndex();if(C!==null)B.indexStart=this._nextIndexStart,B.reservedIndexCount=E===-1?C.count:E;if(B.indexStart!==-1&&B.indexStart+B.reservedIndexCount>this._maxIndexCount||B.vertexStart+B.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let J;if(this._availableGeometryIds.length>0)this._availableGeometryIds.sort(qY),J=this._availableGeometryIds.shift(),I[J]=B;else J=this._geometryCount,this._geometryCount++,I.push(B);return this.setGeometryAt(J,A),this._nextIndexStart=B.indexStart+B.reservedIndexCount,this._nextVertexStart=B.vertexStart+B.reservedVertexCount,J}setGeometryAt(A,Q){if(A>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(Q);let E=this.geometry,B=E.getIndex()!==null,I=E.getIndex(),C=Q.getIndex(),K=this._geometryInfo[A];if(B&&C.count>K.reservedIndexCount||Q.attributes.position.count>K.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");let{vertexStart:J,reservedVertexCount:U}=K;K.vertexCount=Q.getAttribute("position").count;for(let Y in E.attributes){let H=Q.getAttribute(Y),R=E.getAttribute(Y);ML(H,R,J);let O=H.itemSize;for(let N=H.count,$=U;N<$;N++){let L=J+N;for(let W=0;W=Q.length||Q[A].active===!1)return this;let E=this._instanceInfo;for(let B=0,I=E.length;BK).sort((C,K)=>{return E[C].vertexStart-E[K].vertexStart}),I=this.geometry;for(let C=0,K=E.length;C=this._geometryCount)return null;let E=this.geometry,B=this._geometryInfo[A];if(B.boundingBox===null){let I=new g0,C=E.index,K=E.attributes.position;for(let J=B.start,U=B.start+B.count;J=this._geometryCount)return null;let E=this.geometry,B=this._geometryInfo[A];if(B.boundingSphere===null){let I=new KQ;this.getBoundingBoxAt(A,WJ),WJ.getCenter(I.center);let C=E.index,K=E.attributes.position,J=0;for(let U=B.start,Y=B.start+B.count;UK.active);if(Math.max(...E.map((K)=>K.vertexStart+K.reservedVertexCount))>A)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${Q}. Cannot shrink further.`);if(this.geometry.index){if(Math.max(...E.map((J)=>J.indexStart+J.reservedIndexCount))>Q)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${Q}. Cannot shrink further.`)}let I=this.geometry;if(I.dispose(),this._maxVertexCount=A,this._maxIndexCount=Q,this._geometryInitialized)this._geometryInitialized=!1,this.geometry=new hA,this._initializeGeometry(I);let C=this.geometry;if(I.index)B1(I.index.array,C.index.array);for(let K in I.attributes)B1(I.attributes[K].array,C.attributes[K].array)}raycast(A,Q){let E=this._instanceInfo,B=this._geometryInfo,I=this.matrixWorld,C=this.geometry;if(AE.material=this.material,AE.geometry.index=C.index,AE.geometry.attributes=C.attributes,AE.geometry.boundingBox===null)AE.geometry.boundingBox=new g0;if(AE.geometry.boundingSphere===null)AE.geometry.boundingSphere=new KQ;for(let K=0,J=E.length;K({...Q,boundingBox:Q.boundingBox!==null?Q.boundingBox.clone():null,boundingSphere:Q.boundingSphere!==null?Q.boundingSphere.clone():null})),this._instanceInfo=A._instanceInfo.map((Q)=>({...Q})),this._maxInstanceCount=A._maxInstanceCount,this._maxVertexCount=A._maxVertexCount,this._maxIndexCount=A._maxIndexCount,this._geometryInitialized=A._geometryInitialized,this._geometryCount=A._geometryCount,this._multiDrawCounts=A._multiDrawCounts.slice(),this._multiDrawStarts=A._multiDrawStarts.slice(),this._matricesTexture=A._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null)this._colorsTexture=A._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice();return this}dispose(){if(this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null)this._colorsTexture.dispose(),this._colorsTexture=null;return this}onBeforeRender(A,Q,E,B,I){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;let C=B.getIndex(),K=C===null?1:C.array.BYTES_PER_ELEMENT,J=this._instanceInfo,U=this._multiDrawStarts,Y=this._multiDrawCounts,H=this._geometryInfo,R=this.perObjectFrustumCulled,O=this._indirectTexture,N=O.image.data;if(R)NE.multiplyMatrices(E.projectionMatrix,E.matrixWorldInverse).multiply(this.matrixWorld),FY.setFromProjectionMatrix(NE,A.coordinateSystem);let $=0;if(this.sortObjects){NE.copy(this.matrixWorld).invert(),i6.setFromMatrixPosition(E.matrixWorld).applyMatrix4(NE),GZ.set(0,0,-1).transformDirection(E.matrixWorld).transformDirection(NE);for(let Z=0,G=J.length;Z0){let B=Q[E[0]];if(B!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let I=0,C=B.length;IB)return;MY.applyMatrix4(A.matrixWorld);let Y=Q.ray.origin.distanceTo(MY);if(YQ.far)return;return{distance:Y,point:XZ.clone().applyMatrix4(A.matrixWorld),index:K,face:null,faceIndex:null,barycoord:null,object:A}}var $Z=/*@__PURE__*/new y,LZ=/*@__PURE__*/new y;class RQ extends VQ{constructor(A,Q){super(A,Q);this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let A=this.geometry;if(A.index===null){let Q=A.attributes.position,E=[];for(let B=0,I=Q.count;B0){let B=Q[E[0]];if(B!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let I=0,C=B.length;II.far)return;C.push({distance:Y,distanceToRay:Math.sqrt(J),point:U,index:Q,face:null,faceIndex:null,barycoord:null,object:K})}}class _9 extends EQ{constructor(A,Q,E,B,I,C,K,J,U){super(A,Q,E,B,I,C,K,J,U);this.isVideoTexture=!0,this.minFilter=C!==void 0?C:1006,this.magFilter=I!==void 0?I:1006,this.generateMipmaps=!1;let Y=this;function H(){Y.needsUpdate=!0,A.requestVideoFrameCallback(H)}if("requestVideoFrameCallback"in A)A.requestVideoFrameCallback(H)}clone(){return new this.constructor(this.image).copy(this)}update(){let A=this.image;if("requestVideoFrameCallback"in A===!1&&A.readyState>=A.HAVE_CURRENT_DATA)this.needsUpdate=!0}}class kO extends _9{constructor(A,Q,E,B,I,C,K,J){super({},A,Q,E,B,I,C,K,J);this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(A){this.image=A,this.needsUpdate=!0}}class d8 extends EQ{constructor(A,Q){super({width:A,height:Q});this.isFramebufferTexture=!0,this.magFilter=1003,this.minFilter=1003,this.generateMipmaps=!1,this.needsUpdate=!0}}class yE extends EQ{constructor(A,Q,E,B,I,C,K,J,U,Y,H,R){super(null,C,K,J,U,Y,B,I,H,R);this.isCompressedTexture=!0,this.image={width:Q,height:E},this.mipmaps=A,this.flipY=!1,this.generateMipmaps=!1}}class _C extends yE{constructor(A,Q,E,B,I,C){super(A,Q,E,I,C);this.isCompressedArrayTexture=!0,this.image.depth=B,this.wrapR=1001,this.layerUpdates=/*@__PURE__*/new Set}addLayerUpdate(A){this.layerUpdates.add(A)}clearLayerUpdates(){this.layerUpdates.clear()}}class kC extends yE{constructor(A,Q,E){super(void 0,A[0].width,A[0].height,Q,E,301);this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=A}}class EI extends EQ{constructor(A,Q,E,B,I,C,K,J,U){super(A,Q,E,B,I,C,K,J,U);this.isCanvasTexture=!0,this.needsUpdate=!0}}class IE extends EQ{constructor(A,Q,E,B,I,C,K,J,U,Y=1026){if(Y!==1026&&Y!==1027)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");if(E===void 0&&Y===1026)E=1014;if(E===void 0&&Y===1027)E=1020;super(null,B,I,C,K,J,Y,E,U);this.isDepthTexture=!0,this.image={width:A,height:Q},this.magFilter=K!==void 0?K:1003,this.minFilter=J!==void 0?J:1003,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(A){return super.copy(A),this.compareFunction=A.compareFunction,this}toJSON(A){let Q=super.toJSON(A);if(this.compareFunction!==null)Q.compareFunction=this.compareFunction;return Q}}class rQ{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(A,Q){let E=this.getUtoTmapping(A);return this.getPoint(E,Q)}getPoints(A=5){let Q=[];for(let E=0;E<=A;E++)Q.push(this.getPoint(E/A));return Q}getSpacedPoints(A=5){let Q=[];for(let E=0;E<=A;E++)Q.push(this.getPointAt(E/A));return Q}getLength(){let A=this.getLengths();return A[A.length-1]}getLengths(A=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===A+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;let Q=[],E,B=this.getPoint(0),I=0;Q.push(0);for(let C=1;C<=A;C++)E=this.getPoint(C/A),I+=E.distanceTo(B),Q.push(I),B=E;return this.cacheArcLengths=Q,Q}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(A,Q){let E=this.getLengths(),B=0,I=E.length,C;if(Q)C=Q;else C=A*E[I-1];let K=0,J=I-1,U;while(K<=J)if(B=Math.floor(K+(J-K)/2),U=E[B]-C,U<0)K=B+1;else if(U>0)J=B-1;else{J=B;break}if(B=J,E[B]===C)return B/(I-1);let Y=E[B],R=E[B+1]-Y,O=(C-Y)/R;return(B+O)/(I-1)}getTangent(A,Q){let B=A-0.0001,I=A+0.0001;if(B<0)B=0;if(I>1)I=1;let C=this.getPoint(B),K=this.getPoint(I),J=Q||(C.isVector2?new AA:new y);return J.copy(K).sub(C).normalize(),J}getTangentAt(A,Q){let E=this.getUtoTmapping(A);return this.getTangent(E,Q)}computeFrenetFrames(A,Q){let E=new y,B=[],I=[],C=[],K=new y,J=new RA;for(let O=0;O<=A;O++){let N=O/A;B[O]=this.getTangentAt(N,new y)}I[0]=new y,C[0]=new y;let U=Number.MAX_VALUE,Y=Math.abs(B[0].x),H=Math.abs(B[0].y),R=Math.abs(B[0].z);if(Y<=U)U=Y,E.set(1,0,0);if(H<=U)U=H,E.set(0,1,0);if(R<=U)E.set(0,0,1);K.crossVectors(B[0],E).normalize(),I[0].crossVectors(B[0],K),C[0].crossVectors(B[0],I[0]);for(let O=1;O<=A;O++){if(I[O]=I[O-1].clone(),C[O]=C[O-1].clone(),K.crossVectors(B[O-1],B[O]),K.length()>Number.EPSILON){K.normalize();let N=Math.acos(w0(B[O-1].dot(B[O]),-1,1));I[O].applyMatrix4(J.makeRotationAxis(K,N))}C[O].crossVectors(B[O],I[O])}if(Q===!0){let O=Math.acos(w0(I[0].dot(I[A]),-1,1));if(O/=A,B[0].dot(K.crossVectors(I[0],I[A]))>0)O=-O;for(let N=1;N<=A;N++)I[N].applyMatrix4(J.makeRotationAxis(B[N],O*N)),C[N].crossVectors(B[N],I[N])}return{tangents:B,normals:I,binormals:C}}clone(){return new this.constructor().copy(this)}copy(A){return this.arcLengthDivisions=A.arcLengthDivisions,this}toJSON(){let A={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return A.arcLengthDivisions=this.arcLengthDivisions,A.type=this.type,A}fromJSON(A){return this.arcLengthDivisions=A.arcLengthDivisions,this}}class g1 extends rQ{constructor(A=0,Q=0,E=1,B=1,I=0,C=Math.PI*2,K=!1,J=0){super();this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=A,this.aY=Q,this.xRadius=E,this.yRadius=B,this.aStartAngle=I,this.aEndAngle=C,this.aClockwise=K,this.aRotation=J}getPoint(A,Q=new AA){let E=Q,B=Math.PI*2,I=this.aEndAngle-this.aStartAngle,C=Math.abs(I)B)I-=B;if(I0?0:(Math.floor(Math.abs(K)/I)+1)*I;else if(J===0&&K===I-1)K=I-2,J=1;let U,Y;if(this.closed||K>0)U=B[(K-1)%I];else DJ.subVectors(B[0],B[1]).add(B[0]),U=DJ;let H=B[K%I],R=B[(K+1)%I];if(this.closed||K+2B.length-2?B.length-1:C+1],H=B[C>B.length-3?B.length-1:C+2];return E.set(DZ(K,J.x,U.x,Y.x,H.x),DZ(K,J.y,U.y,Y.y,H.y)),E}copy(A){super.copy(A),this.points=[];for(let Q=0,E=A.points.length;Q=E){let C=B[I]-E,K=this.curves[I],J=K.getLength(),U=J===0?0:1-C/J;return K.getPointAt(U,Q)}I++}return null}getLength(){let A=this.getCurveLengths();return A[A.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;let A=[],Q=0;for(let E=0,B=this.curves.length;E1&&!Q[Q.length-1].equals(Q[0]))Q.push(Q[0]);return Q}copy(A){super.copy(A),this.curves=[];for(let Q=0,E=A.curves.length;Q0){let H=U.getPoint(0);if(!H.equals(this.currentPoint))this.lineTo(H.x,H.y)}this.curves.push(U);let Y=U.getPoint(1);return this.currentPoint.copy(Y),this}copy(A){return super.copy(A),this.currentPoint.copy(A.currentPoint),this}toJSON(){let A=super.toJSON();return A.currentPoint=this.currentPoint.toArray(),A}fromJSON(A){return super.fromJSON(A),this.currentPoint.fromArray(A.currentPoint),this}}class n8 extends hA{constructor(A=[new AA(0,-0.5),new AA(0.5,0),new AA(0,0.5)],Q=12,E=0,B=Math.PI*2){super();this.type="LatheGeometry",this.parameters={points:A,segments:Q,phiStart:E,phiLength:B},Q=Math.floor(Q),B=w0(B,0,Math.PI*2);let I=[],C=[],K=[],J=[],U=[],Y=1/Q,H=new y,R=new AA,O=new y,N=new y,$=new y,L=0,W=0;for(let Z=0;Z<=A.length-1;Z++)switch(Z){case 0:L=A[Z+1].x-A[Z].x,W=A[Z+1].y-A[Z].y,O.x=W*1,O.y=-L,O.z=W*0,$.copy(O),O.normalize(),J.push(O.x,O.y,O.z);break;case A.length-1:J.push($.x,$.y,$.z);break;default:L=A[Z+1].x-A[Z].x,W=A[Z+1].y-A[Z].y,O.x=W*1,O.y=-L,O.z=W*0,N.copy(O),O.x+=$.x,O.y+=$.y,O.z+=$.z,O.normalize(),J.push(O.x,O.y,O.z),$.copy(N)}for(let Z=0;Z<=Q;Z++){let G=E+Z*Y*B,X=Math.sin(G),q=Math.cos(G);for(let M=0;M<=A.length-1;M++){H.x=A[M].x*X,H.y=A[M].y,H.z=A[M].x*q,C.push(H.x,H.y,H.z),R.x=Z/Q,R.y=M/(A.length-1),K.push(R.x,R.y);let F=J[3*M+0]*X,D=J[3*M+1],_=J[3*M+0]*q;U.push(F,D,_)}}for(let Z=0;Z0)G(!0);if(Q>0)G(!1)}this.setIndex(Y),this.setAttribute("position",new PA(H,3)),this.setAttribute("normal",new PA(R,3)),this.setAttribute("uv",new PA(O,2));function Z(){let X=new y,q=new y,M=0,F=(Q-A)/E;for(let D=0;D<=I;D++){let _=[],w=D/I,k=w*(Q-A)+A;for(let T=0;T<=B;T++){let z=T/B,j=z*J+K,v=Math.sin(j),g=Math.cos(j);q.x=k*v,q.y=-w*E+L,q.z=k*g,H.push(q.x,q.y,q.z),X.set(v,F,g).normalize(),R.push(X.x,X.y,X.z),O.push(z,1-w),_.push(N++)}$.push(_)}for(let D=0;D0||_!==0)Y.push(w,k,z),M+=3;if(Q>0||_!==I-1)Y.push(k,T,z),M+=3}U.addGroup(W,M,0),W+=M}function G(X){let q=N,M=new AA,F=new y,D=0,_=X===!0?A:Q,w=X===!0?1:-1;for(let T=1;T<=B;T++)H.push(0,L*w,0),R.push(0,w,0),O.push(0.5,0.5),N++;let k=N;for(let T=0;T<=B;T++){let j=T/B*J+K,v=Math.cos(j),g=Math.sin(j);F.x=_*g,F.y=L*w,F.z=_*v,H.push(F.x,F.y,F.z),R.push(0,w,0),M.x=v*0.5+0.5,M.y=g*0.5*w+0.5,O.push(M.x,M.y),N++}for(let T=0;T0.9&&F<0.1){if(G<0.2)C[Z+0]+=1;if(X<0.2)C[Z+2]+=1;if(q<0.2)C[Z+4]+=1}}}function R(Z){I.push(Z.x,Z.y,Z.z)}function O(Z,G){let X=Z*3;G.x=A[X+0],G.y=A[X+1],G.z=A[X+2]}function N(){let Z=new y,G=new y,X=new y,q=new y,M=new AA,F=new AA,D=new AA;for(let _=0,w=0;_80*E){J=Y=A[0],U=H=A[1];for(let $=E;$Y)Y=R;if(O>H)H=O}N=Math.max(Y-J,H-U),N=N!==0?32767/N:0}return QC(C,K,E,J,U,N,0),K}};function dR(A,Q,E,B,I){let C,K;if(I===sL(A,Q,E,B)>0)for(C=Q;C=Q;C-=B)K=MZ(C,A[C],A[C+1],K);if(K&&j9(K,K.next))BC(K),K=K.next;return K}function Z1(A,Q){if(!A)return A;if(!Q)Q=A;let E=A,B;do if(B=!1,!E.steiner&&(j9(E,E.next)||XQ(E.prev,E,E.next)===0)){if(BC(E),E=Q=E.prev,E===E.next)break;B=!0}else E=E.next;while(B||E!==Q);return Q}function QC(A,Q,E,B,I,C,K){if(!A)return;if(!K&&C)pL(A,B,I,C);let J=A,U,Y;while(A.prev!==A.next){if(U=A.prev,Y=A.next,C?vL(A,B,I,C):jL(A)){Q.push(U.i/E|0),Q.push(A.i/E|0),Q.push(Y.i/E|0),BC(A),A=Y.next,J=Y.next;continue}if(A=Y,A===J){if(!K)QC(Z1(A),Q,E,B,I,C,1);else if(K===1)A=hL(Z1(A),Q,E),QC(A,Q,E,B,I,C,2);else if(K===2)yL(A,Q,E,B,I,C);break}}}function jL(A){let Q=A.prev,E=A,B=A.next;if(XQ(Q,E,B)>=0)return!1;let I=Q.x,C=E.x,K=B.x,J=Q.y,U=E.y,Y=B.y,H=IC?I>K?I:K:C>K?C:K,N=J>U?J>Y?J:Y:U>Y?U:Y,$=B.next;while($!==Q){if($.x>=H&&$.x<=O&&$.y>=R&&$.y<=N&&_8(I,J,C,U,K,Y,$.x,$.y)&&XQ($.prev,$,$.next)>=0)return!1;$=$.next}return!0}function vL(A,Q,E,B){let I=A.prev,C=A,K=A.next;if(XQ(I,C,K)>=0)return!1;let J=I.x,U=C.x,Y=K.x,H=I.y,R=C.y,O=K.y,N=JU?J>Y?J:Y:U>Y?U:Y,W=H>R?H>O?H:O:R>O?R:O,Z=vY(N,$,Q,E,B),G=vY(L,W,Q,E,B),X=A.prevZ,q=A.nextZ;while(X&&X.z>=Z&&q&&q.z<=G){if(X.x>=N&&X.x<=L&&X.y>=$&&X.y<=W&&X!==I&&X!==K&&_8(J,H,U,R,Y,O,X.x,X.y)&&XQ(X.prev,X,X.next)>=0)return!1;if(X=X.prevZ,q.x>=N&&q.x<=L&&q.y>=$&&q.y<=W&&q!==I&&q!==K&&_8(J,H,U,R,Y,O,q.x,q.y)&&XQ(q.prev,q,q.next)>=0)return!1;q=q.nextZ}while(X&&X.z>=Z){if(X.x>=N&&X.x<=L&&X.y>=$&&X.y<=W&&X!==I&&X!==K&&_8(J,H,U,R,Y,O,X.x,X.y)&&XQ(X.prev,X,X.next)>=0)return!1;X=X.prevZ}while(q&&q.z<=G){if(q.x>=N&&q.x<=L&&q.y>=$&&q.y<=W&&q!==I&&q!==K&&_8(J,H,U,R,Y,O,q.x,q.y)&&XQ(q.prev,q,q.next)>=0)return!1;q=q.nextZ}return!0}function hL(A,Q,E){let B=A;do{let I=B.prev,C=B.next.next;if(!j9(I,C)&&nR(I,B,B.next,C)&&EC(I,C)&&EC(C,I))Q.push(I.i/E|0),Q.push(B.i/E|0),Q.push(C.i/E|0),BC(B),BC(B.next),B=A=C;B=B.next}while(B!==A);return Z1(B)}function yL(A,Q,E,B,I,C){let K=A;do{let J=K.next.next;while(J!==K.prev){if(K.i!==J.i&&lL(K,J)){let U=sR(K,J);K=Z1(K,K.next),U=Z1(U,U.next),QC(K,Q,E,B,I,C,0),QC(U,Q,E,B,I,C,0);return}J=J.next}K=K.next}while(K!==A)}function gL(A,Q,E,B){let I=[],C,K,J,U,Y;for(C=0,K=Q.length;C=E.next.y&&E.next.y!==E.y){let O=E.x+(K-E.y)*(E.next.x-E.x)/(E.next.y-E.y);if(O<=C&&O>B){if(B=O,I=E.x=E.x&&E.x>=U&&C!==E.x&&_8(KI.x||E.x===I.x&&uL(I,E))))I=E,H=R}E=E.next}while(E!==J);return I}function uL(A,Q){return XQ(A.prev,A,Q.prev)<0&&XQ(Q.next,A,A.next)<0}function pL(A,Q,E,B){let I=A;do{if(I.z===0)I.z=vY(I.x,I.y,Q,E,B);I.prevZ=I.prev,I.nextZ=I.next,I=I.next}while(I!==A);I.prevZ.nextZ=null,I.prevZ=null,mL(I)}function mL(A){let Q,E,B,I,C,K,J,U,Y=1;do{E=A,A=null,C=null,K=0;while(E){K++,B=E,J=0;for(Q=0;Q0||U>0&&B){if(J!==0&&(U===0||!B||E.z<=B.z))I=E,E=E.nextZ,J--;else I=B,B=B.nextZ,U--;if(C)C.nextZ=I;else A=I;I.prevZ=C,C=I}E=B}C.nextZ=null,Y*=2}while(K>1);return A}function vY(A,Q,E,B,I){return A=(A-E)*I|0,Q=(Q-B)*I|0,A=(A|A<<8)&16711935,A=(A|A<<4)&252645135,A=(A|A<<2)&858993459,A=(A|A<<1)&1431655765,Q=(Q|Q<<8)&16711935,Q=(Q|Q<<4)&252645135,Q=(Q|Q<<2)&858993459,Q=(Q|Q<<1)&1431655765,A|Q<<1}function cL(A){let Q=A,E=A;do{if(Q.x=(A-K)*(C-J)&&(A-K)*(B-J)>=(E-K)*(Q-J)&&(E-K)*(C-J)>=(I-K)*(B-J)}function lL(A,Q){return A.next.i!==Q.i&&A.prev.i!==Q.i&&!dL(A,Q)&&(EC(A,Q)&&EC(Q,A)&&nL(A,Q)&&(XQ(A.prev,A,Q.prev)||XQ(A,Q.prev,Q))||j9(A,Q)&&XQ(A.prev,A,A.next)>0&&XQ(Q.prev,Q,Q.next)>0)}function XQ(A,Q,E){return(Q.y-A.y)*(E.x-Q.x)-(Q.x-A.x)*(E.y-Q.y)}function j9(A,Q){return A.x===Q.x&&A.y===Q.y}function nR(A,Q,E,B){let I=SJ(XQ(A,Q,E)),C=SJ(XQ(A,Q,B)),K=SJ(XQ(E,B,A)),J=SJ(XQ(E,B,Q));if(I!==C&&K!==J)return!0;if(I===0&&kJ(A,E,Q))return!0;if(C===0&&kJ(A,B,Q))return!0;if(K===0&&kJ(E,A,B))return!0;if(J===0&&kJ(E,Q,B))return!0;return!1}function kJ(A,Q,E){return Q.x<=Math.max(A.x,E.x)&&Q.x>=Math.min(A.x,E.x)&&Q.y<=Math.max(A.y,E.y)&&Q.y>=Math.min(A.y,E.y)}function SJ(A){return A>0?1:A<0?-1:0}function dL(A,Q){let E=A;do{if(E.i!==A.i&&E.next.i!==A.i&&E.i!==Q.i&&E.next.i!==Q.i&&nR(E,E.next,A,Q))return!0;E=E.next}while(E!==A);return!1}function EC(A,Q){return XQ(A.prev,A,A.next)<0?XQ(A,Q,A.next)>=0&&XQ(A,A.prev,Q)>=0:XQ(A,Q,A.prev)<0||XQ(A,A.next,Q)<0}function nL(A,Q){let E=A,B=!1,I=(A.x+Q.x)/2,C=(A.y+Q.y)/2;do{if(E.y>C!==E.next.y>C&&E.next.y!==E.y&&I<(E.next.x-E.x)*(C-E.y)/(E.next.y-E.y)+E.x)B=!B;E=E.next}while(E!==A);return B}function sR(A,Q){let E=new hY(A.i,A.x,A.y),B=new hY(Q.i,Q.x,Q.y),I=A.next,C=Q.prev;return A.next=Q,Q.prev=A,E.next=I,I.prev=E,B.next=E,E.prev=B,C.next=B,B.prev=C,B}function MZ(A,Q,E,B){let I=new hY(A,Q,E);if(!B)I.prev=I,I.next=I;else I.next=B.next,I.prev=B,B.next.prev=I,B.next=I;return I}function BC(A){if(A.next.prev=A.prev,A.prev.next=A.next,A.prevZ)A.prevZ.nextZ=A.nextZ;if(A.nextZ)A.nextZ.prevZ=A.prevZ}function hY(A,Q,E){this.i=A,this.x=Q,this.y=E,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function sL(A,Q,E,B){let I=0;for(let C=Q,K=E-B;C2&&A[Q-1].equals(A[0]))A.pop()}function _Z(A,Q){for(let E=0;ENumber.EPSILON){let QA=Math.sqrt(d),t=Math.sqrt(wA*wA+VA*VA),KA=CA.x-jA/QA,HA=CA.y+ZA/QA,fA=f.x-VA/t,zA=f.y+wA/t,yA=((fA-KA)*VA-(zA-HA)*wA)/(ZA*VA-jA*wA);NA=KA+ZA*yA-EA.x,YA=HA+jA*yA-EA.y;let qA=NA*NA+YA*YA;if(qA<=2)return new AA(NA,YA);else FA=Math.sqrt(qA/2)}else{let QA=!1;if(ZA>Number.EPSILON){if(wA>Number.EPSILON)QA=!0}else if(ZA<-Number.EPSILON){if(wA<-Number.EPSILON)QA=!0}else if(Math.sign(jA)===Math.sign(VA))QA=!0;if(QA)NA=-jA,YA=ZA,FA=Math.sqrt(d);else NA=ZA,YA=jA,FA=Math.sqrt(d/2)}return new AA(NA/FA,YA/FA)}let S=[];for(let EA=0,CA=j.length,f=CA-1,NA=EA+1;EA=0;EA--){let CA=EA/L,f=O*Math.cos(CA*Math.PI/2),NA=N*Math.sin(CA*Math.PI/2)+$;for(let YA=0,FA=j.length;YA=0){let NA=f,YA=f-1;if(YA<0)YA=EA.length-1;for(let FA=0,ZA=Y+L*2;FA0)O.push(G,X,M);if(W!==E-1||J0!==A>0)this.version++;this._anisotropy=A}get clearcoat(){return this._clearcoat}set clearcoat(A){if(this._clearcoat>0!==A>0)this.version++;this._clearcoat=A}get iridescence(){return this._iridescence}set iridescence(A){if(this._iridescence>0!==A>0)this.version++;this._iridescence=A}get dispersion(){return this._dispersion}set dispersion(A){if(this._dispersion>0!==A>0)this.version++;this._dispersion=A}get sheen(){return this._sheen}set sheen(A){if(this._sheen>0!==A>0)this.version++;this._sheen=A}get transmission(){return this._transmission}set transmission(A){if(this._transmission>0!==A>0)this.version++;this._transmission=A}copy(A){return super.copy(A),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=A.anisotropy,this.anisotropyRotation=A.anisotropyRotation,this.anisotropyMap=A.anisotropyMap,this.clearcoat=A.clearcoat,this.clearcoatMap=A.clearcoatMap,this.clearcoatRoughness=A.clearcoatRoughness,this.clearcoatRoughnessMap=A.clearcoatRoughnessMap,this.clearcoatNormalMap=A.clearcoatNormalMap,this.clearcoatNormalScale.copy(A.clearcoatNormalScale),this.dispersion=A.dispersion,this.ior=A.ior,this.iridescence=A.iridescence,this.iridescenceMap=A.iridescenceMap,this.iridescenceIOR=A.iridescenceIOR,this.iridescenceThicknessRange=[...A.iridescenceThicknessRange],this.iridescenceThicknessMap=A.iridescenceThicknessMap,this.sheen=A.sheen,this.sheenColor.copy(A.sheenColor),this.sheenColorMap=A.sheenColorMap,this.sheenRoughness=A.sheenRoughness,this.sheenRoughnessMap=A.sheenRoughnessMap,this.transmission=A.transmission,this.transmissionMap=A.transmissionMap,this.thickness=A.thickness,this.thicknessMap=A.thicknessMap,this.attenuationDistance=A.attenuationDistance,this.attenuationColor.copy(A.attenuationColor),this.specularIntensity=A.specularIntensity,this.specularIntensityMap=A.specularIntensityMap,this.specularColor.copy(A.specularColor),this.specularColorMap=A.specularColorMap,this}}class DE extends $Q{constructor(A){super();this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new a(16777215),this.specular=new a(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new a(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new AA(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new DQ,this.combine=0,this.reflectivity=1,this.refractionRatio=0.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.specular.copy(A.specular),this.shininess=A.shininess,this.map=A.map,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.emissive.copy(A.emissive),this.emissiveMap=A.emissiveMap,this.emissiveIntensity=A.emissiveIntensity,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.specularMap=A.specularMap,this.alphaMap=A.alphaMap,this.envMap=A.envMap,this.envMapRotation.copy(A.envMapRotation),this.combine=A.combine,this.reflectivity=A.reflectivity,this.refractionRatio=A.refractionRatio,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.flatShading=A.flatShading,this.fog=A.fog,this}}class h9 extends $Q{constructor(A){super();this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new a(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new a(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new AA(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.gradientMap=A.gradientMap,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.emissive.copy(A.emissive),this.emissiveMap=A.emissiveMap,this.emissiveIntensity=A.emissiveIntensity,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.alphaMap=A.alphaMap,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.fog=A.fog,this}}class gE extends $Q{constructor(A){super();this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new AA(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(A)}copy(A){return super.copy(A),this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.flatShading=A.flatShading,this}}class CI extends $Q{constructor(A){super();this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new a(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new a(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new AA(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new DQ,this.combine=0,this.reflectivity=1,this.refractionRatio=0.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.color.copy(A.color),this.map=A.map,this.lightMap=A.lightMap,this.lightMapIntensity=A.lightMapIntensity,this.aoMap=A.aoMap,this.aoMapIntensity=A.aoMapIntensity,this.emissive.copy(A.emissive),this.emissiveMap=A.emissiveMap,this.emissiveIntensity=A.emissiveIntensity,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.specularMap=A.specularMap,this.alphaMap=A.alphaMap,this.envMap=A.envMap,this.envMapRotation.copy(A.envMapRotation),this.combine=A.combine,this.reflectivity=A.reflectivity,this.refractionRatio=A.refractionRatio,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this.wireframeLinecap=A.wireframeLinecap,this.wireframeLinejoin=A.wireframeLinejoin,this.flatShading=A.flatShading,this.fog=A.fog,this}}class hI extends $Q{constructor(A){super();this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(A)}copy(A){return super.copy(A),this.depthPacking=A.depthPacking,this.map=A.map,this.alphaMap=A.alphaMap,this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.wireframe=A.wireframe,this.wireframeLinewidth=A.wireframeLinewidth,this}}class pC extends $Q{constructor(A){super();this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(A)}copy(A){return super.copy(A),this.map=A.map,this.alphaMap=A.alphaMap,this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this}}class y9 extends $Q{constructor(A){super();this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new a(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new AA(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(A)}copy(A){return super.copy(A),this.defines={MATCAP:""},this.color.copy(A.color),this.matcap=A.matcap,this.map=A.map,this.bumpMap=A.bumpMap,this.bumpScale=A.bumpScale,this.normalMap=A.normalMap,this.normalMapType=A.normalMapType,this.normalScale.copy(A.normalScale),this.displacementMap=A.displacementMap,this.displacementScale=A.displacementScale,this.displacementBias=A.displacementBias,this.alphaMap=A.alphaMap,this.flatShading=A.flatShading,this.fog=A.fog,this}}class g9 extends p0{constructor(A){super();this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(A)}copy(A){return super.copy(A),this.scale=A.scale,this.dashSize=A.dashSize,this.gapSize=A.gapSize,this}}function Y1(A,Q,E){if(!A||!E&&A.constructor===Q)return A;if(typeof Q.BYTES_PER_ELEMENT==="number")return new Q(A);return Array.prototype.slice.call(A)}function iR(A){return ArrayBuffer.isView(A)&&!(A instanceof DataView)}function oR(A){function Q(I,C){return A[I]-A[C]}let E=A.length,B=new Array(E);for(let I=0;I!==E;++I)B[I]=I;return B.sort(Q),B}function yY(A,Q,E){let B=A.length,I=new A.constructor(B);for(let C=0,K=0;K!==B;++C){let J=E[C]*Q;for(let U=0;U!==Q;++U)I[K++]=A[J+U]}return I}function TO(A,Q,E,B){let I=1,C=A[0];while(C!==void 0&&C[B]===void 0)C=A[I++];if(C===void 0)return;let K=C[B];if(K===void 0)return;if(Array.isArray(K))do{if(K=C[B],K!==void 0)Q.push(C.time),E.push.apply(E,K);C=A[I++]}while(C!==void 0);else if(K.toArray!==void 0)do{if(K=C[B],K!==void 0)Q.push(C.time),K.toArray(E,E.length);C=A[I++]}while(C!==void 0);else do{if(K=C[B],K!==void 0)Q.push(C.time),E.push(K);C=A[I++]}while(C!==void 0)}function aL(A,Q,E,B,I=30){let C=A.clone();C.name=Q;let K=[];for(let U=0;U=B)continue;R.push(Y.times[N]);for(let L=0;LC.tracks[U].times[0])J=C.tracks[U].times[0];for(let U=0;U=J.times[$]){let Z=$*R+H,G=Z+R-H;L=J.values.slice(Z,G)}else{let Z=J.createInterpolant(),G=H,X=R-H;Z.evaluate(C),L=Z.resultBuffer.slice(G,X)}if(U==="quaternion")new J0().fromArray(L).normalize().conjugate().toArray(L);let W=Y.times.length;for(let Z=0;Z=I)){let K=Q[1];if(A=I)break Q}C=E,E=0;break E}break A}while(E>>1;if(AQ)--C;if(++C,I!==0||C!==B){if(I>=C)C=Math.max(C,1),I=C-1;let K=this.getValueSize();this.times=E.slice(I,C),this.values=this.values.slice(I*K,C*K)}return this}validate(){let A=!0,Q=this.getValueSize();if(Q-Math.floor(Q)!==0)console.error("THREE.KeyframeTrack: Invalid value size in track.",this),A=!1;let E=this.times,B=this.values,I=E.length;if(I===0)console.error("THREE.KeyframeTrack: Track is empty.",this),A=!1;let C=null;for(let K=0;K!==I;K++){let J=E[K];if(typeof J==="number"&&isNaN(J)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,K,J),A=!1;break}if(C!==null&&C>J){console.error("THREE.KeyframeTrack: Out of order keys.",this,K,J,C),A=!1;break}C=J}if(B!==void 0){if(iR(B))for(let K=0,J=B.length;K!==J;++K){let U=B[K];if(isNaN(U)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,K,U),A=!1;break}}}return A}optimize(){let A=this.times.slice(),Q=this.values.slice(),E=this.getValueSize(),B=this.getInterpolation()===2302,I=A.length-1,C=1;for(let K=1;K0){A[C]=A[I];for(let K=I*E,J=C*E,U=0;U!==E;++U)Q[J+U]=Q[K+U];++C}if(C!==A.length)this.times=A.slice(0,C),this.values=Q.slice(0,C*E);else this.times=A,this.values=Q;return this}clone(){let A=this.times.slice(),Q=this.values.slice(),B=new this.constructor(this.name,A,Q);return B.createInterpolant=this.createInterpolant,B}}xE.prototype.TimeBufferType=Float32Array;xE.prototype.ValueBufferType=Float32Array;xE.prototype.DefaultInterpolation=2301;class fB extends xE{constructor(A,Q,E){super(A,Q,E)}}fB.prototype.ValueTypeName="bool";fB.prototype.ValueBufferType=Array;fB.prototype.DefaultInterpolation=2300;fB.prototype.InterpolantFactoryMethodLinear=void 0;fB.prototype.InterpolantFactoryMethodSmooth=void 0;class a8 extends xE{}a8.prototype.ValueTypeName="color";class zE extends xE{}zE.prototype.ValueTypeName="number";class f9 extends KI{constructor(A,Q,E,B){super(A,Q,E,B)}interpolate_(A,Q,E,B){let I=this.resultBuffer,C=this.sampleValues,K=this.valueSize,J=(E-Q)/(B-Q),U=A*K;for(let Y=U+K;U!==Y;U+=4)J0.slerpFlat(I,0,C,U-K,C,U,J);return I}}class ME extends xE{InterpolantFactoryMethodLinear(A){return new f9(this.times,this.values,this.getValueSize(),A)}}ME.prototype.ValueTypeName="quaternion";ME.prototype.InterpolantFactoryMethodSmooth=void 0;class JI extends xE{constructor(A,Q,E){super(A,Q,E)}}JI.prototype.ValueTypeName="string";JI.prototype.ValueBufferType=Array;JI.prototype.DefaultInterpolation=2300;JI.prototype.InterpolantFactoryMethodLinear=void 0;JI.prototype.InterpolantFactoryMethodSmooth=void 0;class YE extends xE{}YE.prototype.ValueTypeName="vector";class oQ{constructor(A="",Q=-1,E=[],B=2500){if(this.name=A,this.tracks=E,this.duration=Q,this.blendMode=B,this.uuid=TE(),this.duration<0)this.resetDuration()}static parse(A){let Q=[],E=A.tracks,B=1/(A.fps||1);for(let C=0,K=E.length;C!==K;++C)Q.push(A5(E[C]).scale(B));let I=new this(A.name,A.duration,Q,A.blendMode);return I.uuid=A.uuid,I}static toJSON(A){let Q=[],E=A.tracks,B={name:A.name,duration:A.duration,tracks:Q,uuid:A.uuid,blendMode:A.blendMode};for(let I=0,C=E.length;I!==C;++I)Q.push(xE.toJSON(E[I]));return B}static CreateFromMorphTargetSequence(A,Q,E,B){let I=Q.length,C=[];for(let K=0;K1){let H=Y[1],R=B[H];if(!R)B[H]=R=[];R.push(U)}}let C=[];for(let K in B)C.push(this.CreateFromMorphTargetSequence(K,B[K],Q,E));return C}static parseAnimation(A,Q){if(!A)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;let E=function(H,R,O,N,$){if(O.length!==0){let L=[],W=[];if(TO(O,L,W,N),L.length!==0)$.push(new H(R,L,W))}},B=[],I=A.name||"default",C=A.fps||30,K=A.blendMode,J=A.length||-1,U=A.hierarchy||[];for(let H=0;H{if(Q)Q(I);this.manager.itemEnd(A)},0),I;if(aB[A]!==void 0){aB[A].push({onLoad:Q,onProgress:E,onError:B});return}aB[A]=[],aB[A].push({onLoad:Q,onProgress:E,onError:B});let C=new Request(A,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),K=this.mimeType,J=this.responseType;fetch(C).then((U)=>{if(U.status===200||U.status===0){if(U.status===0)console.warn("THREE.FileLoader: HTTP Status 0 received.");if(typeof ReadableStream==="undefined"||U.body===void 0||U.body.getReader===void 0)return U;let Y=aB[A],H=U.body.getReader(),R=U.headers.get("X-File-Size")||U.headers.get("Content-Length"),O=R?parseInt(R):0,N=O!==0,$=0,L=new ReadableStream({start(W){Z();function Z(){H.read().then(({done:G,value:X})=>{if(G)W.close();else{$+=X.byteLength;let q=new ProgressEvent("progress",{lengthComputable:N,loaded:$,total:O});for(let M=0,F=Y.length;M{W.error(G)})}}});return new Response(L)}else throw new aR(`fetch for "${U.url}" responded with ${U.status}: ${U.statusText}`,U)}).then((U)=>{switch(J){case"arraybuffer":return U.arrayBuffer();case"blob":return U.blob();case"document":return U.text().then((Y)=>{return new DOMParser().parseFromString(Y,K)});case"json":return U.json();default:if(K===void 0)return U.text();else{let H=/charset="?([^;"\s]*)"?/i.exec(K),R=H&&H[1]?H[1].toLowerCase():void 0,O=new TextDecoder(R);return U.arrayBuffer().then((N)=>O.decode(N))}}}).then((U)=>{SB.add(A,U);let Y=aB[A];delete aB[A];for(let H=0,R=Y.length;H{let Y=aB[A];if(Y===void 0)throw this.manager.itemError(A),U;delete aB[A];for(let H=0,R=Y.length;H{this.manager.itemEnd(A)}),this.manager.itemStart(A)}setResponseType(A){return this.responseType=A,this}setMimeType(A){return this.mimeType=A,this}}class zO extends C0{constructor(A){super(A)}load(A,Q,E,B){let I=this,C=new U0(this.manager);C.setPath(this.path),C.setRequestHeader(this.requestHeader),C.setWithCredentials(this.withCredentials),C.load(A,function(K){try{Q(I.parse(JSON.parse(K)))}catch(J){if(B)B(J);else console.error(J);I.manager.itemError(A)}},E,B)}parse(A){let Q=[];for(let E=0;E0?!0:!1;else B.vertexColors=A.vertexColors;if(A.uniforms!==void 0)for(let I in A.uniforms){let C=A.uniforms[I];switch(B.uniforms[I]={},C.type){case"t":B.uniforms[I].value=E(C.value);break;case"c":B.uniforms[I].value=new a().setHex(C.value);break;case"v2":B.uniforms[I].value=new AA().fromArray(C.value);break;case"v3":B.uniforms[I].value=new y().fromArray(C.value);break;case"v4":B.uniforms[I].value=new MA().fromArray(C.value);break;case"m3":B.uniforms[I].value=new E0().fromArray(C.value);break;case"m4":B.uniforms[I].value=new RA().fromArray(C.value);break;default:B.uniforms[I].value=C.value}}if(A.defines!==void 0)B.defines=A.defines;if(A.vertexShader!==void 0)B.vertexShader=A.vertexShader;if(A.fragmentShader!==void 0)B.fragmentShader=A.fragmentShader;if(A.glslVersion!==void 0)B.glslVersion=A.glslVersion;if(A.extensions!==void 0)for(let I in A.extensions)B.extensions[I]=A.extensions[I];if(A.lights!==void 0)B.lights=A.lights;if(A.clipping!==void 0)B.clipping=A.clipping;if(A.size!==void 0)B.size=A.size;if(A.sizeAttenuation!==void 0)B.sizeAttenuation=A.sizeAttenuation;if(A.map!==void 0)B.map=E(A.map);if(A.matcap!==void 0)B.matcap=E(A.matcap);if(A.alphaMap!==void 0)B.alphaMap=E(A.alphaMap);if(A.bumpMap!==void 0)B.bumpMap=E(A.bumpMap);if(A.bumpScale!==void 0)B.bumpScale=A.bumpScale;if(A.normalMap!==void 0)B.normalMap=E(A.normalMap);if(A.normalMapType!==void 0)B.normalMapType=A.normalMapType;if(A.normalScale!==void 0){let I=A.normalScale;if(Array.isArray(I)===!1)I=[I,I];B.normalScale=new AA().fromArray(I)}if(A.displacementMap!==void 0)B.displacementMap=E(A.displacementMap);if(A.displacementScale!==void 0)B.displacementScale=A.displacementScale;if(A.displacementBias!==void 0)B.displacementBias=A.displacementBias;if(A.roughnessMap!==void 0)B.roughnessMap=E(A.roughnessMap);if(A.metalnessMap!==void 0)B.metalnessMap=E(A.metalnessMap);if(A.emissiveMap!==void 0)B.emissiveMap=E(A.emissiveMap);if(A.emissiveIntensity!==void 0)B.emissiveIntensity=A.emissiveIntensity;if(A.specularMap!==void 0)B.specularMap=E(A.specularMap);if(A.specularIntensityMap!==void 0)B.specularIntensityMap=E(A.specularIntensityMap);if(A.specularColorMap!==void 0)B.specularColorMap=E(A.specularColorMap);if(A.envMap!==void 0)B.envMap=E(A.envMap);if(A.envMapRotation!==void 0)B.envMapRotation.fromArray(A.envMapRotation);if(A.envMapIntensity!==void 0)B.envMapIntensity=A.envMapIntensity;if(A.reflectivity!==void 0)B.reflectivity=A.reflectivity;if(A.refractionRatio!==void 0)B.refractionRatio=A.refractionRatio;if(A.lightMap!==void 0)B.lightMap=E(A.lightMap);if(A.lightMapIntensity!==void 0)B.lightMapIntensity=A.lightMapIntensity;if(A.aoMap!==void 0)B.aoMap=E(A.aoMap);if(A.aoMapIntensity!==void 0)B.aoMapIntensity=A.aoMapIntensity;if(A.gradientMap!==void 0)B.gradientMap=E(A.gradientMap);if(A.clearcoatMap!==void 0)B.clearcoatMap=E(A.clearcoatMap);if(A.clearcoatRoughnessMap!==void 0)B.clearcoatRoughnessMap=E(A.clearcoatRoughnessMap);if(A.clearcoatNormalMap!==void 0)B.clearcoatNormalMap=E(A.clearcoatNormalMap);if(A.clearcoatNormalScale!==void 0)B.clearcoatNormalScale=new AA().fromArray(A.clearcoatNormalScale);if(A.iridescenceMap!==void 0)B.iridescenceMap=E(A.iridescenceMap);if(A.iridescenceThicknessMap!==void 0)B.iridescenceThicknessMap=E(A.iridescenceThicknessMap);if(A.transmissionMap!==void 0)B.transmissionMap=E(A.transmissionMap);if(A.thicknessMap!==void 0)B.thicknessMap=E(A.thicknessMap);if(A.anisotropyMap!==void 0)B.anisotropyMap=E(A.anisotropyMap);if(A.sheenColorMap!==void 0)B.sheenColorMap=E(A.sheenColorMap);if(A.sheenRoughnessMap!==void 0)B.sheenRoughnessMap=E(A.sheenRoughnessMap);return B}setTextures(A){return this.textures=A,this}createMaterialFromType(A){return dC.createMaterialFromType(A)}static createMaterialFromType(A){return new{ShadowMaterial:v9,SpriteMaterial:y1,RawShaderMaterial:II,ShaderMaterial:bA,PointsMaterial:aE,MeshPhysicalMaterial:fQ,MeshStandardMaterial:aQ,MeshPhongMaterial:DE,MeshToonMaterial:h9,MeshNormalMaterial:gE,MeshLambertMaterial:CI,MeshDepthMaterial:hI,MeshDistanceMaterial:pC,MeshBasicMaterial:_0,MeshMatcapMaterial:y9,LineDashedMaterial:g9,LineBasicMaterial:p0,Material:$Q}[A]}}class QE{static decodeText(A){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),typeof TextDecoder!=="undefined")return(/*@__PURE__*/new TextDecoder()).decode(A);let Q="";for(let E=0,B=A.length;E0){let J=new t8(Q);I=new R1(J),I.setCrossOrigin(this.crossOrigin);for(let U=0,Y=A.length;U0){B=new R1(this.manager),B.setCrossOrigin(this.crossOrigin);for(let C=0,K=A.length;C{let L=new g0;L.min.fromArray($.boxMin),L.max.fromArray($.boxMax);let W=new KQ;return W.radius=$.sphereRadius,W.center.fromArray($.sphereCenter),{boxInitialized:$.boxInitialized,box:L,sphereInitialized:$.sphereInitialized,sphere:W}}),C._maxInstanceCount=A.maxInstanceCount,C._maxVertexCount=A.maxVertexCount,C._maxIndexCount=A.maxIndexCount,C._geometryInitialized=A.geometryInitialized,C._geometryCount=A.geometryCount,C._matricesTexture=U(A.matricesTexture.uuid),A.colorsTexture!==void 0)C._colorsTexture=U(A.colorsTexture.uuid);break;case"LOD":C=new M9;break;case"Line":C=new VQ(K(A.geometry),J(A.material));break;case"LineLoop":C=new l8(K(A.geometry),J(A.material));break;case"LineSegments":C=new RQ(K(A.geometry),J(A.material));break;case"PointCloud":case"Points":C=new GB(K(A.geometry),J(A.material));break;case"Sprite":C=new c8(J(A.material));break;case"Group":C=new i0;break;case"Bone":C=new yB;break;default:C=new I0}if(C.uuid=A.uuid,A.name!==void 0)C.name=A.name;if(A.matrix!==void 0){if(C.matrix.fromArray(A.matrix),A.matrixAutoUpdate!==void 0)C.matrixAutoUpdate=A.matrixAutoUpdate;if(C.matrixAutoUpdate)C.matrix.decompose(C.position,C.quaternion,C.scale)}else{if(A.position!==void 0)C.position.fromArray(A.position);if(A.rotation!==void 0)C.rotation.fromArray(A.rotation);if(A.quaternion!==void 0)C.quaternion.fromArray(A.quaternion);if(A.scale!==void 0)C.scale.fromArray(A.scale)}if(A.up!==void 0)C.up.fromArray(A.up);if(A.castShadow!==void 0)C.castShadow=A.castShadow;if(A.receiveShadow!==void 0)C.receiveShadow=A.receiveShadow;if(A.shadow){if(A.shadow.intensity!==void 0)C.shadow.intensity=A.shadow.intensity;if(A.shadow.bias!==void 0)C.shadow.bias=A.shadow.bias;if(A.shadow.normalBias!==void 0)C.shadow.normalBias=A.shadow.normalBias;if(A.shadow.radius!==void 0)C.shadow.radius=A.shadow.radius;if(A.shadow.mapSize!==void 0)C.shadow.mapSize.fromArray(A.shadow.mapSize);if(A.shadow.camera!==void 0)C.shadow.camera=this.parseObject(A.shadow.camera)}if(A.visible!==void 0)C.visible=A.visible;if(A.frustumCulled!==void 0)C.frustumCulled=A.frustumCulled;if(A.renderOrder!==void 0)C.renderOrder=A.renderOrder;if(A.userData!==void 0)C.userData=A.userData;if(A.layers!==void 0)C.layers.mask=A.layers;if(A.children!==void 0){let R=A.children;for(let O=0;O{if(Q)Q(U);I.manager.itemEnd(A)}).catch((U)=>{if(B)B(U)});return}return setTimeout(function(){if(Q)Q(C);I.manager.itemEnd(A)},0),C}let K={};K.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",K.headers=this.requestHeader;let J=fetch(A,K).then(function(U){return U.blob()}).then(function(U){return createImageBitmap(U,Object.assign(I.options,{colorSpaceConversion:"none"}))}).then(function(U){if(SB.add(A,U),Q)Q(U);return I.manager.itemEnd(A),U}).catch(function(U){if(B)B(U);SB.remove(A),I.manager.itemError(A),I.manager.itemEnd(A)});SB.add(A,J),I.manager.itemStart(A)}}var TJ;class oC{static getContext(){if(TJ===void 0)TJ=new(window.AudioContext||window.webkitAudioContext);return TJ}static setContext(A){TJ=A}}class jO extends C0{constructor(A){super(A)}load(A,Q,E,B){let I=this,C=new U0(this.manager);C.setResponseType("arraybuffer"),C.setPath(this.path),C.setRequestHeader(this.requestHeader),C.setWithCredentials(this.withCredentials),C.load(A,function(J){try{let U=J.slice(0);oC.getContext().decodeAudioData(U,function(H){Q(H)}).catch(K)}catch(U){K(U)}},E,B);function K(J){if(B)B(J);else console.error(J);I.manager.itemError(A)}}}var vZ=/*@__PURE__*/new RA,hZ=/*@__PURE__*/new RA,I1=/*@__PURE__*/new RA;class E6{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=0.064,this.cameraL=new v0,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new v0,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(A){let Q=this._cache;if(Q.focus!==A.focus||Q.fov!==A.fov||Q.aspect!==A.aspect*this.aspect||Q.near!==A.near||Q.far!==A.far||Q.zoom!==A.zoom||Q.eyeSep!==this.eyeSep){Q.focus=A.focus,Q.fov=A.fov,Q.aspect=A.aspect*this.aspect,Q.near=A.near,Q.far=A.far,Q.zoom=A.zoom,Q.eyeSep=this.eyeSep,I1.copy(A.projectionMatrix);let B=Q.eyeSep/2,I=B*Q.near/Q.focus,C=Q.near*Math.tan(O1*Q.fov*0.5)/Q.zoom,K,J;hZ.elements[12]=-B,vZ.elements[12]=B,K=-C*Q.aspect+I,J=C*Q.aspect+I,I1.elements[0]=2*Q.near/(J-K),I1.elements[8]=(J+K)/(J-K),this.cameraL.projectionMatrix.copy(I1),K=-C*Q.aspect-I,J=C*Q.aspect-I,I1.elements[0]=2*Q.near/(J-K),I1.elements[8]=(J+K)/(J-K),this.cameraR.projectionMatrix.copy(I1)}this.cameraL.matrixWorld.copy(A.matrixWorld).multiply(hZ),this.cameraR.matrixWorld.copy(A.matrixWorld).multiply(vZ)}}class c9 extends v0{constructor(A=[]){super();this.isArrayCamera=!0,this.cameras=A,this.index=0}}class gI{constructor(A=!0){this.autoStart=A,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=yZ(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let A=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){let Q=yZ();A=(Q-this.oldTime)/1000,this.oldTime=Q,this.elapsedTime+=A}return A}}function yZ(){return performance.now()}var C1=/*@__PURE__*/new y,gZ=/*@__PURE__*/new J0,E5=/*@__PURE__*/new y,K1=/*@__PURE__*/new y;class vO extends I0{constructor(){super();this.type="AudioListener",this.context=oC.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new gI}getInput(){return this.gain}removeFilter(){if(this.filter!==null)this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null;return this}getFilter(){return this.filter}setFilter(A){if(this.filter!==null)this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination);else this.gain.disconnect(this.context.destination);return this.filter=A,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(A){return this.gain.gain.setTargetAtTime(A,this.context.currentTime,0.01),this}updateMatrixWorld(A){super.updateMatrixWorld(A);let Q=this.context.listener,E=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(C1,gZ,E5),K1.set(0,0,-1).applyQuaternion(gZ),Q.positionX){let B=this.context.currentTime+this.timeDelta;Q.positionX.linearRampToValueAtTime(C1.x,B),Q.positionY.linearRampToValueAtTime(C1.y,B),Q.positionZ.linearRampToValueAtTime(C1.z,B),Q.forwardX.linearRampToValueAtTime(K1.x,B),Q.forwardY.linearRampToValueAtTime(K1.y,B),Q.forwardZ.linearRampToValueAtTime(K1.z,B),Q.upX.linearRampToValueAtTime(E.x,B),Q.upY.linearRampToValueAtTime(E.y,B),Q.upZ.linearRampToValueAtTime(E.z,B)}else Q.setPosition(C1.x,C1.y,C1.z),Q.setOrientation(K1.x,K1.y,K1.z,E.x,E.y,E.z)}}class l9 extends I0{constructor(A){super();this.type="Audio",this.listener=A,this.context=A.context,this.gain=this.context.createGain(),this.gain.connect(A.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(A){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=A,this.connect(),this}setMediaElementSource(A){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(A),this.connect(),this}setMediaStreamSource(A){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(A),this.connect(),this}setBuffer(A){if(this.buffer=A,this.sourceType="buffer",this.autoplay)this.play();return this}play(A=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+A;let Q=this.context.createBufferSource();return Q.buffer=this.buffer,Q.loop=this.loop,Q.loopStart=this.loopStart,Q.loopEnd=this.loopEnd,Q.onended=this.onEnded.bind(this),Q.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=Q,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}if(this.isPlaying===!0){if(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0)this._progress=this._progress%(this.duration||this.buffer.duration);this.source.stop(),this.source.onended=null,this.isPlaying=!1}return this}stop(A=0){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}if(this._progress=0,this.source!==null)this.source.stop(this.context.currentTime+A),this.source.onended=null;return this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let A=1,Q=this.filters.length;A0){this.source.disconnect(this.filters[0]);for(let A=1,Q=this.filters.length;A0)this._mixBufferRegionAdditive(E,B,this._addIndex*Q,1,Q);for(let J=Q,U=Q+Q;J!==U;++J)if(E[J]!==E[J+Q]){K.setValue(E,B);break}}saveOriginalState(){let A=this.binding,Q=this.buffer,E=this.valueSize,B=E*this._origIndex;A.getValue(Q,B);for(let I=E,C=B;I!==C;++I)Q[I]=Q[B+I%E];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let A=this.valueSize*3;this.binding.setValue(this.buffer,A)}_setAdditiveIdentityNumeric(){let A=this._addIndex*this.valueSize,Q=A+this.valueSize;for(let E=A;E=0.5)for(let C=0;C!==I;++C)A[Q+C]=A[E+C]}_slerp(A,Q,E,B){J0.slerpFlat(A,Q,A,Q,A,E,B)}_slerpAdditive(A,Q,E,B,I){let C=this._workIndex*I;J0.multiplyQuaternionsFlat(A,C,A,Q,A,E),J0.slerpFlat(A,Q,A,Q,A,C,B)}_lerp(A,Q,E,B,I){let C=1-B;for(let K=0;K!==I;++K){let J=Q+K;A[J]=A[J]*C+A[E+K]*B}}_lerpAdditive(A,Q,E,B,I){for(let C=0;C!==I;++C){let K=Q+C;A[K]=A[K]+A[E+C]*B}}}var gO="\\[\\]\\.:\\/",I5=new RegExp("["+gO+"]","g"),xO="[^"+gO+"]",C5="[^"+gO.replace("\\.","")+"]",K5=/*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace("WC",xO),J5=/*@__PURE__*/ /(WCOD+)?/.source.replace("WCOD",C5),U5=/*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",xO),Y5=/*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC",xO),O5=new RegExp("^"+K5+J5+U5+Y5+"$"),H5=["material","materials","bones","map"];class QN{constructor(A,Q,E){let B=E||T0.parseTrackName(Q);this._targetGroup=A,this._bindings=A.subscribe_(Q,B)}getValue(A,Q){this.bind();let E=this._targetGroup.nCachedObjects_,B=this._bindings[E];if(B!==void 0)B.getValue(A,Q)}setValue(A,Q){let E=this._bindings;for(let B=this._targetGroup.nCachedObjects_,I=E.length;B!==I;++B)E[B].setValue(A,Q)}bind(){let A=this._bindings;for(let Q=this._targetGroup.nCachedObjects_,E=A.length;Q!==E;++Q)A[Q].bind()}unbind(){let A=this._bindings;for(let Q=this._targetGroup.nCachedObjects_,E=A.length;Q!==E;++Q)A[Q].unbind()}}class T0{constructor(A,Q,E){this.path=Q,this.parsedPath=E||T0.parseTrackName(Q),this.node=T0.findNode(A,this.parsedPath.nodeName),this.rootNode=A,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(A,Q,E){if(!(A&&A.isAnimationObjectGroup))return new T0(A,Q,E);else return new T0.Composite(A,Q,E)}static sanitizeNodeName(A){return A.replace(/\s/g,"_").replace(I5,"")}static parseTrackName(A){let Q=O5.exec(A);if(Q===null)throw new Error("PropertyBinding: Cannot parse trackName: "+A);let E={nodeName:Q[2],objectName:Q[3],objectIndex:Q[4],propertyName:Q[5],propertyIndex:Q[6]},B=E.nodeName&&E.nodeName.lastIndexOf(".");if(B!==void 0&&B!==-1){let I=E.nodeName.substring(B+1);if(H5.indexOf(I)!==-1)E.nodeName=E.nodeName.substring(0,B),E.objectName=I}if(E.propertyName===null||E.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+A);return E}static findNode(A,Q){if(Q===void 0||Q===""||Q==="."||Q===-1||Q===A.name||Q===A.uuid)return A;if(A.skeleton){let E=A.skeleton.getBoneByName(Q);if(E!==void 0)return E}if(A.children){let E=function(I){for(let C=0;C=I){let H=I++,R=A[H];Q[R.uuid]=Y,A[Y]=R,Q[U]=H,A[H]=J;for(let O=0,N=B;O!==N;++O){let $=E[O],L=$[H],W=$[Y];$[Y]=L,$[H]=W}}}this.nCachedObjects_=I}uncache(){let A=this._objects,Q=this._indicesByUUID,E=this._bindings,B=E.length,I=this.nCachedObjects_,C=A.length;for(let K=0,J=arguments.length;K!==J;++K){let U=arguments[K],Y=U.uuid,H=Q[Y];if(H!==void 0)if(delete Q[Y],H0)Q[O.uuid]=H;A[H]=O,A.pop();for(let N=0,$=B;N!==$;++N){let L=E[N];L[H]=L[R],L.pop()}}}this.nCachedObjects_=I}subscribe_(A,Q){let E=this._bindingsIndicesByPath,B=E[A],I=this._bindings;if(B!==void 0)return I[B];let C=this._paths,K=this._parsedPaths,J=this._objects,U=J.length,Y=this.nCachedObjects_,H=new Array(U);B=I.length,E[A]=B,C.push(A),K.push(Q),I.push(H);for(let R=Y,O=J.length;R!==O;++R){let N=J[R];H[R]=new T0(N,A,Q)}return H}unsubscribe_(A){let Q=this._bindingsIndicesByPath,E=Q[A];if(E!==void 0){let B=this._paths,I=this._parsedPaths,C=this._bindings,K=C.length-1,J=C[K],U=A[K];Q[U]=E,C[E]=J,C.pop(),I[E]=I[K],I.pop(),B[E]=B[K],B.pop()}}}class n9{constructor(A,Q,E=null,B=Q.blendMode){this._mixer=A,this._clip=Q,this._localRoot=E,this.blendMode=B;let I=Q.tracks,C=I.length,K=new Array(C),J={endingStart:2400,endingEnd:2400};for(let U=0;U!==C;++U){let Y=I[U].createInterpolant(null);K[U]=Y,Y.settings=J}this._interpolantSettings=J,this._interpolants=K,this._propertyBindings=new Array(C),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(A){return this._startTime=A,this}setLoop(A,Q){return this.loop=A,this.repetitions=Q,this}setEffectiveWeight(A){return this.weight=A,this._effectiveWeight=this.enabled?A:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(A){return this._scheduleFading(A,0,1)}fadeOut(A){return this._scheduleFading(A,1,0)}crossFadeFrom(A,Q,E){if(A.fadeOut(Q),this.fadeIn(Q),E){let B=this._clip.duration,I=A._clip.duration,C=I/B,K=B/I;A.warp(1,C,Q),this.warp(K,1,Q)}return this}crossFadeTo(A,Q,E){return A.crossFadeFrom(this,Q,E)}stopFading(){let A=this._weightInterpolant;if(A!==null)this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(A);return this}setEffectiveTimeScale(A){return this.timeScale=A,this._effectiveTimeScale=this.paused?0:A,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(A){return this.timeScale=this._clip.duration/A,this.stopWarping()}syncWith(A){return this.time=A.time,this.timeScale=A.timeScale,this.stopWarping()}halt(A){return this.warp(this._effectiveTimeScale,0,A)}warp(A,Q,E){let B=this._mixer,I=B.time,C=this.timeScale,K=this._timeScaleInterpolant;if(K===null)K=B._lendControlInterpolant(),this._timeScaleInterpolant=K;let{parameterPositions:J,sampleValues:U}=K;return J[0]=I,J[1]=I+E,U[0]=A/C,U[1]=Q/C,this}stopWarping(){let A=this._timeScaleInterpolant;if(A!==null)this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(A);return this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(A,Q,E,B){if(!this.enabled){this._updateWeight(A);return}let I=this._startTime;if(I!==null){let J=(A-I)*E;if(J<0||E===0)Q=0;else this._startTime=null,Q=E*J}Q*=this._updateTimeScale(A);let C=this._updateTime(Q),K=this._updateWeight(A);if(K>0){let J=this._interpolants,U=this._propertyBindings;switch(this.blendMode){case 2501:for(let Y=0,H=J.length;Y!==H;++Y)J[Y].evaluate(C),U[Y].accumulateAdditive(K);break;case 2500:default:for(let Y=0,H=J.length;Y!==H;++Y)J[Y].evaluate(C),U[Y].accumulate(B,K)}}}_updateWeight(A){let Q=0;if(this.enabled){Q=this.weight;let E=this._weightInterpolant;if(E!==null){let B=E.evaluate(A)[0];if(Q*=B,A>E.parameterPositions[1]){if(this.stopFading(),B===0)this.enabled=!1}}}return this._effectiveWeight=Q,Q}_updateTimeScale(A){let Q=0;if(!this.paused){Q=this.timeScale;let E=this._timeScaleInterpolant;if(E!==null){let B=E.evaluate(A)[0];if(Q*=B,A>E.parameterPositions[1])if(this.stopWarping(),Q===0)this.paused=!0;else this.timeScale=Q}}return this._effectiveTimeScale=Q,Q}_updateTime(A){let Q=this._clip.duration,E=this.loop,B=this.time+A,I=this._loopCount,C=E===2202;if(A===0){if(I===-1)return B;return C&&(I&1)===1?Q-B:B}if(E===2200){if(I===-1)this._loopCount=0,this._setEndings(!0,!0,!1);A:{if(B>=Q)B=Q;else if(B<0)B=0;else{this.time=B;break A}if(this.clampWhenFinished)this.paused=!0;else this.enabled=!1;this.time=B,this._mixer.dispatchEvent({type:"finished",action:this,direction:A<0?-1:1})}}else{if(I===-1)if(A>=0)I=0,this._setEndings(!0,this.repetitions===0,C);else this._setEndings(this.repetitions===0,!0,C);if(B>=Q||B<0){let K=Math.floor(B/Q);B-=Q*K,I+=Math.abs(K);let J=this.repetitions-I;if(J<=0){if(this.clampWhenFinished)this.paused=!0;else this.enabled=!1;B=A>0?Q:0,this.time=B,this._mixer.dispatchEvent({type:"finished",action:this,direction:A>0?1:-1})}else{if(J===1){let U=A<0;this._setEndings(U,!U,C)}else this._setEndings(!1,!1,C);this._loopCount=I,this.time=B,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:K})}}else this.time=B;if(C&&(I&1)===1)return Q-B}return B}_setEndings(A,Q,E){let B=this._interpolantSettings;if(E)B.endingStart=2401,B.endingEnd=2401;else{if(A)B.endingStart=this.zeroSlopeAtStart?2401:2400;else B.endingStart=2402;if(Q)B.endingEnd=this.zeroSlopeAtEnd?2401:2400;else B.endingEnd=2402}}_scheduleFading(A,Q,E){let B=this._mixer,I=B.time,C=this._weightInterpolant;if(C===null)C=B._lendControlInterpolant(),this._weightInterpolant=C;let{parameterPositions:K,sampleValues:J}=C;return K[0]=I,J[0]=Q,K[1]=I+A,J[1]=E,this}}var Z5=new Float32Array(1);class xI extends rE{constructor(A){super();this._root=A,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(A,Q){let E=A._localRoot||this._root,B=A._clip.tracks,I=B.length,C=A._propertyBindings,K=A._interpolants,J=E.uuid,U=this._bindingsByRootAndName,Y=U[J];if(Y===void 0)Y={},U[J]=Y;for(let H=0;H!==I;++H){let R=B[H],O=R.name,N=Y[O];if(N!==void 0)++N.referenceCount,C[H]=N;else{if(N=C[H],N!==void 0){if(N._cacheIndex===null)++N.referenceCount,this._addInactiveBinding(N,J,O);continue}let $=Q&&Q._propertyBindings[H].binding.parsedPath;N=new d9(T0.create(E,O,$),R.ValueTypeName,R.getValueSize()),++N.referenceCount,this._addInactiveBinding(N,J,O),C[H]=N}K[H].resultBuffer=N.buffer}}_activateAction(A){if(!this._isActiveAction(A)){if(A._cacheIndex===null){let E=(A._localRoot||this._root).uuid,B=A._clip.uuid,I=this._actionsByClip[B];this._bindAction(A,I&&I.knownActions[0]),this._addInactiveAction(A,B,E)}let Q=A._propertyBindings;for(let E=0,B=Q.length;E!==B;++E){let I=Q[E];if(I.useCount++===0)this._lendBinding(I),I.saveOriginalState()}this._lendAction(A)}}_deactivateAction(A){if(this._isActiveAction(A)){let Q=A._propertyBindings;for(let E=0,B=Q.length;E!==B;++E){let I=Q[E];if(--I.useCount===0)I.restoreOriginalState(),this._takeBackBinding(I)}this._takeBackAction(A)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let A=this;this.stats={actions:{get total(){return A._actions.length},get inUse(){return A._nActiveActions}},bindings:{get total(){return A._bindings.length},get inUse(){return A._nActiveBindings}},controlInterpolants:{get total(){return A._controlInterpolants.length},get inUse(){return A._nActiveControlInterpolants}}}}_isActiveAction(A){let Q=A._cacheIndex;return Q!==null&&Q=0;--E)A[E].stop();return this}update(A){A*=this.timeScale;let Q=this._actions,E=this._nActiveActions,B=this.time+=A,I=Math.sign(A),C=this._accuIndex^=1;for(let U=0;U!==E;++U)Q[U]._update(B,A,I,C);let K=this._bindings,J=this._nActiveBindings;for(let U=0;U!==J;++U)K[U].apply(C);return this}setTime(A){this.time=0;for(let Q=0;Q=this.min.x&&A.x<=this.max.x&&A.y>=this.min.y&&A.y<=this.max.y}containsBox(A){return this.min.x<=A.min.x&&A.max.x<=this.max.x&&this.min.y<=A.min.y&&A.max.y<=this.max.y}getParameter(A,Q){return Q.set((A.x-this.min.x)/(this.max.x-this.min.x),(A.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(A){return A.max.x>=this.min.x&&A.min.x<=this.max.x&&A.max.y>=this.min.y&&A.min.y<=this.max.y}clampPoint(A,Q){return Q.copy(A).clamp(this.min,this.max)}distanceToPoint(A){return this.clampPoint(A,uZ).distanceTo(A)}intersect(A){if(this.min.max(A.min),this.max.min(A.max),this.isEmpty())this.makeEmpty();return this}union(A){return this.min.min(A.min),this.max.max(A.max),this}translate(A){return this.min.add(A),this.max.add(A),this}equals(A){return A.min.equals(this.min)&&A.max.equals(this.max)}}var pZ=/*@__PURE__*/new y,zJ=/*@__PURE__*/new y;class $B{constructor(A=new y,Q=new y){this.start=A,this.end=Q}set(A,Q){return this.start.copy(A),this.end.copy(Q),this}copy(A){return this.start.copy(A.start),this.end.copy(A.end),this}getCenter(A){return A.addVectors(this.start,this.end).multiplyScalar(0.5)}delta(A){return A.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(A,Q){return this.delta(Q).multiplyScalar(A).add(this.start)}closestPointToPointParameter(A,Q){pZ.subVectors(A,this.start),zJ.subVectors(this.end,this.start);let E=zJ.dot(zJ),I=zJ.dot(pZ)/E;if(Q)I=w0(I,0,1);return I}closestPointToPoint(A,Q,E){let B=this.closestPointToPointParameter(A,Q);return this.delta(E).multiplyScalar(B).add(this.start)}applyMatrix4(A){return this.start.applyMatrix4(A),this.end.applyMatrix4(A),this}equals(A){return A.start.equals(this.start)&&A.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}var mZ=/*@__PURE__*/new y;class lO extends I0{constructor(A,Q){super();this.light=A,this.matrixAutoUpdate=!1,this.color=Q,this.type="SpotLightHelper";let E=new hA,B=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let C=0,K=1,J=32;C1)for(let H=0;H0.99999)this.quaternion.set(0,0,0,1);else if(A.y<-0.99999)this.quaternion.set(1,0,0,0);else{sZ.set(A.z,0,-A.x).normalize();let Q=Math.acos(A.y);this.quaternion.setFromAxisAngle(sZ,Q)}}setLength(A,Q=A*0.2,E=Q*0.2){this.line.scale.set(1,Math.max(0.0001,A-Q),1),this.line.updateMatrix(),this.cone.scale.set(E,Q,E),this.cone.position.y=A,this.cone.updateMatrix()}setColor(A){this.line.material.color.set(A),this.cone.material.color.set(A)}copy(A){return super.copy(A,!1),this.line.copy(A.line),this.cone.copy(A.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class eO extends RQ{constructor(A=1){let Q=[0,0,0,A,0,0,0,0,0,0,A,0,0,0,0,0,0,A],E=[1,0,0,1,0.6,0,0,1,0,0.6,1,0,0,0,1,0,0.6,1],B=new hA;B.setAttribute("position",new PA(Q,3)),B.setAttribute("color",new PA(E,3));let I=new p0({vertexColors:!0,toneMapped:!1});super(B,I);this.type="AxesHelper"}setColors(A,Q,E){let B=new a,I=this.geometry.attributes.color.array;return B.set(A),B.toArray(I,0),B.toArray(I,3),B.set(Q),B.toArray(I,6),B.toArray(I,9),B.set(E),B.toArray(I,12),B.toArray(I,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class aC{constructor(){this.type="ShapePath",this.color=new a,this.subPaths=[],this.currentPath=null}moveTo(A,Q){return this.currentPath=new TI,this.subPaths.push(this.currentPath),this.currentPath.moveTo(A,Q),this}lineTo(A,Q){return this.currentPath.lineTo(A,Q),this}quadraticCurveTo(A,Q,E,B){return this.currentPath.quadraticCurveTo(A,Q,E,B),this}bezierCurveTo(A,Q,E,B,I,C){return this.currentPath.bezierCurveTo(A,Q,E,B,I,C),this}splineThru(A){return this.currentPath.splineThru(A),this}toShapes(A){function Q(W){let Z=[];for(let G=0,X=W.length;GNumber.EPSILON){if(w<0)F=Z[M],_=-_,D=Z[q],w=-w;if(W.yD.y)continue;if(W.y===F.y){if(W.x===F.x)return!0}else{let k=w*(W.x-F.x)-_*(W.y-F.y);if(k===0)return!0;if(k<0)continue;X=!X}}else{if(W.y!==F.y)continue;if(D.x<=W.x&&W.x<=F.x||F.x<=W.x&&W.x<=D.x)return!0}}return X}let B=WE.isClockWise,I=this.subPaths;if(I.length===0)return[];let C,K,J,U=[];if(I.length===1)return K=I[0],J=new TB,J.curves=K.curves,U.push(J),U;let Y=!B(I[0].getPoints());Y=A?!Y:Y;let H=[],R=[],O=[],N=0,$;R[N]=void 0,O[N]=[];for(let W=0,Z=I.length;W1){let W=!1,Z=0;for(let G=0,X=R.length;G0&&W===!1)O=H}let L;for(let W=0,Z=R.length;WQ)A.repeat.x=1,A.repeat.y=E/Q,A.offset.x=0,A.offset.y=(1-A.repeat.y)/2;else A.repeat.x=Q/E,A.repeat.y=1,A.offset.x=(1-A.repeat.x)/2,A.offset.y=0;return A}function W5(A,Q){let E=A.image&&A.image.width?A.image.width/A.image.height:1;if(E>Q)A.repeat.x=Q/E,A.repeat.y=1,A.offset.x=(1-A.repeat.x)/2,A.offset.y=0;else A.repeat.x=1,A.repeat.y=E/Q,A.offset.x=0,A.offset.y=(1-A.repeat.y)/2;return A}function X5(A){return A.repeat.x=1,A.repeat.y=1,A.offset.x=0,A.offset.y=0,A}function a9(A,Q,E,B){let I=$5(B);switch(E){case 1021:return A*Q;case 1024:return A*Q;case 1025:return A*Q*2;case 1028:return A*Q/I.components*I.byteLength;case 1029:return A*Q/I.components*I.byteLength;case 1030:return A*Q*2/I.components*I.byteLength;case 1031:return A*Q*2/I.components*I.byteLength;case 1022:return A*Q*3/I.components*I.byteLength;case 1023:return A*Q*4/I.components*I.byteLength;case 1033:return A*Q*4/I.components*I.byteLength;case 33776:case 33777:return Math.floor((A+3)/4)*Math.floor((Q+3)/4)*8;case 33778:case 33779:return Math.floor((A+3)/4)*Math.floor((Q+3)/4)*16;case 35841:case 35843:return Math.max(A,16)*Math.max(Q,8)/4;case 35840:case 35842:return Math.max(A,8)*Math.max(Q,8)/2;case 36196:case 37492:return Math.floor((A+3)/4)*Math.floor((Q+3)/4)*8;case 37496:return Math.floor((A+3)/4)*Math.floor((Q+3)/4)*16;case 37808:return Math.floor((A+3)/4)*Math.floor((Q+3)/4)*16;case 37809:return Math.floor((A+4)/5)*Math.floor((Q+3)/4)*16;case 37810:return Math.floor((A+4)/5)*Math.floor((Q+4)/5)*16;case 37811:return Math.floor((A+5)/6)*Math.floor((Q+4)/5)*16;case 37812:return Math.floor((A+5)/6)*Math.floor((Q+5)/6)*16;case 37813:return Math.floor((A+7)/8)*Math.floor((Q+4)/5)*16;case 37814:return Math.floor((A+7)/8)*Math.floor((Q+5)/6)*16;case 37815:return Math.floor((A+7)/8)*Math.floor((Q+7)/8)*16;case 37816:return Math.floor((A+9)/10)*Math.floor((Q+4)/5)*16;case 37817:return Math.floor((A+9)/10)*Math.floor((Q+5)/6)*16;case 37818:return Math.floor((A+9)/10)*Math.floor((Q+7)/8)*16;case 37819:return Math.floor((A+9)/10)*Math.floor((Q+9)/10)*16;case 37820:return Math.floor((A+11)/12)*Math.floor((Q+9)/10)*16;case 37821:return Math.floor((A+11)/12)*Math.floor((Q+11)/12)*16;case 36492:case 36494:case 36495:return Math.ceil(A/4)*Math.ceil(Q/4)*16;case 36283:case 36284:return Math.ceil(A/4)*Math.ceil(Q/4)*8;case 36285:case 36286:return Math.ceil(A/4)*Math.ceil(Q/4)*16}throw new Error(`Unable to determine texture byte length for ${E} format.`)}function $5(A){switch(A){case 1009:case 1010:return{byteLength:1,components:1};case 1012:case 1011:case 1016:return{byteLength:2,components:1};case 1017:case 1018:return{byteLength:2,components:4};case 1014:case 1013:case 1015:return{byteLength:4,components:1};case 35902:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${A}.`)}var BN={contain:G5,cover:W5,fill:X5,getByteLength:a9};if(typeof __THREE_DEVTOOLS__!=="undefined")__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"173"}}));if(typeof window!=="undefined")if(window.__THREE__)console.warn("WARNING: Multiple instances of Three.js being imported.");else window.__THREE__="173";function SN(){let A=null,Q=!1,E=null,B=null;function I(C,K){E(C,K),B=A.requestAnimationFrame(I)}return{start:function(){if(Q===!0)return;if(E===null)return;B=A.requestAnimationFrame(I),Q=!0},stop:function(){A.cancelAnimationFrame(B),Q=!1},setAnimationLoop:function(C){E=C},setContext:function(C){A=C}}}function L5(A){let Q=/*@__PURE__*/new WeakMap;function E(J,U){let{array:Y,usage:H}=J,R=Y.byteLength,O=A.createBuffer();A.bindBuffer(U,O),A.bufferData(U,Y,H),J.onUploadCallback();let N;if(Y instanceof Float32Array)N=A.FLOAT;else if(Y instanceof Uint16Array)if(J.isFloat16BufferAttribute)N=A.HALF_FLOAT;else N=A.UNSIGNED_SHORT;else if(Y instanceof Int16Array)N=A.SHORT;else if(Y instanceof Uint32Array)N=A.UNSIGNED_INT;else if(Y instanceof Int32Array)N=A.INT;else if(Y instanceof Int8Array)N=A.BYTE;else if(Y instanceof Uint8Array)N=A.UNSIGNED_BYTE;else if(Y instanceof Uint8ClampedArray)N=A.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+Y);return{buffer:O,type:N,bytesPerElement:Y.BYTES_PER_ELEMENT,version:J.version,size:R}}function B(J,U,Y){let{array:H,updateRanges:R}=U;if(A.bindBuffer(Y,J),R.length===0)A.bufferSubData(Y,0,H);else{R.sort((N,$)=>N.start-$.start);let O=0;for(let N=1;N 0 - vec4 plane; - #ifdef ALPHA_TO_COVERAGE - float distanceToPlane, distanceGradient; - float clipOpacity = 1.0; - #pragma unroll_loop_start - for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; - distanceGradient = fwidth( distanceToPlane ) / 2.0; - clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); - if ( clipOpacity == 0.0 ) discard; - } - #pragma unroll_loop_end - #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES - float unionClipOpacity = 1.0; - #pragma unroll_loop_start - for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; - distanceGradient = fwidth( distanceToPlane ) / 2.0; - unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); - } - #pragma unroll_loop_end - clipOpacity *= 1.0 - unionClipOpacity; - #endif - diffuseColor.a *= clipOpacity; - if ( diffuseColor.a == 0.0 ) discard; - #else - #pragma unroll_loop_start - for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; - } - #pragma unroll_loop_end - #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES - bool clipped = true; - #pragma unroll_loop_start - for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { - plane = clippingPlanes[ i ]; - clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; - } - #pragma unroll_loop_end - if ( clipped ) discard; - #endif - #endif -#endif`,g5=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; - uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; -#endif`,x5=`#if NUM_CLIPPING_PLANES > 0 - varying vec3 vClipPosition; -#endif`,b5=`#if NUM_CLIPPING_PLANES > 0 - vClipPosition = - mvPosition.xyz; -#endif`,f5=`#if defined( USE_COLOR_ALPHA ) - diffuseColor *= vColor; -#elif defined( USE_COLOR ) - diffuseColor.rgb *= vColor; -#endif`,u5=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) - varying vec3 vColor; -#endif`,p5=`#if defined( USE_COLOR_ALPHA ) - varying vec4 vColor; -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - varying vec3 vColor; -#endif`,m5=`#if defined( USE_COLOR_ALPHA ) - vColor = vec4( 1.0 ); -#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) - vColor = vec3( 1.0 ); -#endif -#ifdef USE_COLOR - vColor *= color; -#endif -#ifdef USE_INSTANCING_COLOR - vColor.xyz *= instanceColor.xyz; -#endif -#ifdef USE_BATCHING_COLOR - vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); - vColor.xyz *= batchingColor.xyz; -#endif`,c5=`#define PI 3.141592653589793 -#define PI2 6.283185307179586 -#define PI_HALF 1.5707963267948966 -#define RECIPROCAL_PI 0.3183098861837907 -#define RECIPROCAL_PI2 0.15915494309189535 -#define EPSILON 1e-6 -#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -#define whiteComplement( a ) ( 1.0 - saturate( a ) ) -float pow2( const in float x ) { return x*x; } -vec3 pow2( const in vec3 x ) { return x*x; } -float pow3( const in float x ) { return x*x*x; } -float pow4( const in float x ) { float x2 = x*x; return x2*x2; } -float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } -float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } -highp float rand( const in vec2 uv ) { - const highp float a = 12.9898, b = 78.233, c = 43758.5453; - highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); - return fract( sin( sn ) * c ); -} -#ifdef HIGH_PRECISION - float precisionSafeLength( vec3 v ) { return length( v ); } -#else - float precisionSafeLength( vec3 v ) { - float maxComponent = max3( abs( v ) ); - return length( v / maxComponent ) * maxComponent; - } -#endif -struct IncidentLight { - vec3 color; - vec3 direction; - bool visible; -}; -struct ReflectedLight { - vec3 directDiffuse; - vec3 directSpecular; - vec3 indirectDiffuse; - vec3 indirectSpecular; -}; -#ifdef USE_ALPHAHASH - varying vec3 vPosition; -#endif -vec3 transformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); -} -vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { - return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); -} -mat3 transposeMat3( const in mat3 m ) { - mat3 tmp; - tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); - tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); - tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); - return tmp; -} -bool isPerspectiveMatrix( mat4 m ) { - return m[ 2 ][ 3 ] == - 1.0; -} -vec2 equirectUv( in vec3 dir ) { - float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; - float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; - return vec2( u, v ); -} -vec3 BRDF_Lambert( const in vec3 diffuseColor ) { - return RECIPROCAL_PI * diffuseColor; -} -vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} -float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { - float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); - return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); -} // validated`,l5=`#ifdef ENVMAP_TYPE_CUBE_UV - #define cubeUV_minMipLevel 4.0 - #define cubeUV_minTileSize 16.0 - float getFace( vec3 direction ) { - vec3 absDirection = abs( direction ); - float face = - 1.0; - if ( absDirection.x > absDirection.z ) { - if ( absDirection.x > absDirection.y ) - face = direction.x > 0.0 ? 0.0 : 3.0; - else - face = direction.y > 0.0 ? 1.0 : 4.0; - } else { - if ( absDirection.z > absDirection.y ) - face = direction.z > 0.0 ? 2.0 : 5.0; - else - face = direction.y > 0.0 ? 1.0 : 4.0; - } - return face; - } - vec2 getUV( vec3 direction, float face ) { - vec2 uv; - if ( face == 0.0 ) { - uv = vec2( direction.z, direction.y ) / abs( direction.x ); - } else if ( face == 1.0 ) { - uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); - } else if ( face == 2.0 ) { - uv = vec2( - direction.x, direction.y ) / abs( direction.z ); - } else if ( face == 3.0 ) { - uv = vec2( - direction.z, direction.y ) / abs( direction.x ); - } else if ( face == 4.0 ) { - uv = vec2( - direction.x, direction.z ) / abs( direction.y ); - } else { - uv = vec2( direction.x, direction.y ) / abs( direction.z ); - } - return 0.5 * ( uv + 1.0 ); - } - vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { - float face = getFace( direction ); - float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); - mipInt = max( mipInt, cubeUV_minMipLevel ); - float faceSize = exp2( mipInt ); - highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; - if ( face > 2.0 ) { - uv.y += faceSize; - face -= 3.0; - } - uv.x += face * faceSize; - uv.x += filterInt * 3.0 * cubeUV_minTileSize; - uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); - uv.x *= CUBEUV_TEXEL_WIDTH; - uv.y *= CUBEUV_TEXEL_HEIGHT; - #ifdef texture2DGradEXT - return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; - #else - return texture2D( envMap, uv ).rgb; - #endif - } - #define cubeUV_r0 1.0 - #define cubeUV_m0 - 2.0 - #define cubeUV_r1 0.8 - #define cubeUV_m1 - 1.0 - #define cubeUV_r4 0.4 - #define cubeUV_m4 2.0 - #define cubeUV_r5 0.305 - #define cubeUV_m5 3.0 - #define cubeUV_r6 0.21 - #define cubeUV_m6 4.0 - float roughnessToMip( float roughness ) { - float mip = 0.0; - if ( roughness >= cubeUV_r1 ) { - mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; - } else if ( roughness >= cubeUV_r4 ) { - mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; - } else if ( roughness >= cubeUV_r5 ) { - mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; - } else if ( roughness >= cubeUV_r6 ) { - mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; - } else { - mip = - 2.0 * log2( 1.16 * roughness ); } - return mip; - } - vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { - float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); - float mipF = fract( mip ); - float mipInt = floor( mip ); - vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); - if ( mipF == 0.0 ) { - return vec4( color0, 1.0 ); - } else { - vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); - return vec4( mix( color0, color1, mipF ), 1.0 ); - } - } -#endif`,d5=`vec3 transformedNormal = objectNormal; -#ifdef USE_TANGENT - vec3 transformedTangent = objectTangent; -#endif -#ifdef USE_BATCHING - mat3 bm = mat3( batchingMatrix ); - transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); - transformedNormal = bm * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = bm * transformedTangent; - #endif -#endif -#ifdef USE_INSTANCING - mat3 im = mat3( instanceMatrix ); - transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); - transformedNormal = im * transformedNormal; - #ifdef USE_TANGENT - transformedTangent = im * transformedTangent; - #endif -#endif -transformedNormal = normalMatrix * transformedNormal; -#ifdef FLIP_SIDED - transformedNormal = - transformedNormal; -#endif -#ifdef USE_TANGENT - transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; - #ifdef FLIP_SIDED - transformedTangent = - transformedTangent; - #endif -#endif`,n5=`#ifdef USE_DISPLACEMENTMAP - uniform sampler2D displacementMap; - uniform float displacementScale; - uniform float displacementBias; -#endif`,s5=`#ifdef USE_DISPLACEMENTMAP - transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); -#endif`,i5=`#ifdef USE_EMISSIVEMAP - vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); - #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE - emissiveColor = sRGBTransferEOTF( emissiveColor ); - #endif - totalEmissiveRadiance *= emissiveColor.rgb; -#endif`,o5=`#ifdef USE_EMISSIVEMAP - uniform sampler2D emissiveMap; -#endif`,r5="gl_FragColor = linearToOutputTexel( gl_FragColor );",a5=`vec4 LinearTransferOETF( in vec4 value ) { - return value; -} -vec4 sRGBTransferEOTF( in vec4 value ) { - return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); -} -vec4 sRGBTransferOETF( in vec4 value ) { - return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); -}`,t5=`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vec3 cameraToFrag; - if ( isOrthographic ) { - cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToFrag = normalize( vWorldPosition - cameraPosition ); - } - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vec3 reflectVec = reflect( cameraToFrag, worldNormal ); - #else - vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); - #endif - #else - vec3 reflectVec = vReflect; - #endif - #ifdef ENVMAP_TYPE_CUBE - vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); - #else - vec4 envColor = vec4( 0.0 ); - #endif - #ifdef ENVMAP_BLENDING_MULTIPLY - outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_MIX ) - outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); - #elif defined( ENVMAP_BLENDING_ADD ) - outgoingLight += envColor.xyz * specularStrength * reflectivity; - #endif -#endif`,e5=`#ifdef USE_ENVMAP - uniform float envMapIntensity; - uniform float flipEnvMap; - uniform mat3 envMapRotation; - #ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; - #else - uniform sampler2D envMap; - #endif - -#endif`,Aq=`#ifdef USE_ENVMAP - uniform float reflectivity; - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) - #define ENV_WORLDPOS - #endif - #ifdef ENV_WORLDPOS - varying vec3 vWorldPosition; - uniform float refractionRatio; - #else - varying vec3 vReflect; - #endif -#endif`,Qq=`#ifdef USE_ENVMAP - #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) - #define ENV_WORLDPOS - #endif - #ifdef ENV_WORLDPOS - - varying vec3 vWorldPosition; - #else - varying vec3 vReflect; - uniform float refractionRatio; - #endif -#endif`,Eq=`#ifdef USE_ENVMAP - #ifdef ENV_WORLDPOS - vWorldPosition = worldPosition.xyz; - #else - vec3 cameraToVertex; - if ( isOrthographic ) { - cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); - } else { - cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); - } - vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - #ifdef ENVMAP_MODE_REFLECTION - vReflect = reflect( cameraToVertex, worldNormal ); - #else - vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); - #endif - #endif -#endif`,Bq=`#ifdef USE_FOG - vFogDepth = - mvPosition.z; -#endif`,Iq=`#ifdef USE_FOG - varying float vFogDepth; -#endif`,Cq=`#ifdef USE_FOG - #ifdef FOG_EXP2 - float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); - #else - float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); - #endif - gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); -#endif`,Kq=`#ifdef USE_FOG - uniform vec3 fogColor; - varying float vFogDepth; - #ifdef FOG_EXP2 - uniform float fogDensity; - #else - uniform float fogNear; - uniform float fogFar; - #endif -#endif`,Jq=`#ifdef USE_GRADIENTMAP - uniform sampler2D gradientMap; -#endif -vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { - float dotNL = dot( normal, lightDirection ); - vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); - #ifdef USE_GRADIENTMAP - return vec3( texture2D( gradientMap, coord ).r ); - #else - vec2 fw = fwidth( coord ) * 0.5; - return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); - #endif -}`,Uq=`#ifdef USE_LIGHTMAP - uniform sampler2D lightMap; - uniform float lightMapIntensity; -#endif`,Yq=`LambertMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularStrength = specularStrength;`,Oq=`varying vec3 vViewPosition; -struct LambertMaterial { - vec3 diffuseColor; - float specularStrength; -}; -void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_Lambert -#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,Hq=`uniform bool receiveShadow; -uniform vec3 ambientLightColor; -#if defined( USE_LIGHT_PROBES ) - uniform vec3 lightProbe[ 9 ]; -#endif -vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { - float x = normal.x, y = normal.y, z = normal.z; - vec3 result = shCoefficients[ 0 ] * 0.886227; - result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; - result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; - result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; - result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; - result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; - result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); - result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; - result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); - return result; -} -vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); - return irradiance; -} -vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { - vec3 irradiance = ambientLightColor; - return irradiance; -} -float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { - float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); - if ( cutoffDistance > 0.0 ) { - distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); - } - return distanceFalloff; -} -float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { - return smoothstep( coneCosine, penumbraCosine, angleCosine ); -} -#if NUM_DIR_LIGHTS > 0 - struct DirectionalLight { - vec3 direction; - vec3 color; - }; - uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; - void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { - light.color = directionalLight.color; - light.direction = directionalLight.direction; - light.visible = true; - } -#endif -#if NUM_POINT_LIGHTS > 0 - struct PointLight { - vec3 position; - vec3 color; - float distance; - float decay; - }; - uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; - void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = pointLight.position - geometryPosition; - light.direction = normalize( lVector ); - float lightDistance = length( lVector ); - light.color = pointLight.color; - light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } -#endif -#if NUM_SPOT_LIGHTS > 0 - struct SpotLight { - vec3 position; - vec3 direction; - vec3 color; - float distance; - float decay; - float coneCos; - float penumbraCos; - }; - uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; - void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { - vec3 lVector = spotLight.position - geometryPosition; - light.direction = normalize( lVector ); - float angleCos = dot( light.direction, spotLight.direction ); - float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); - if ( spotAttenuation > 0.0 ) { - float lightDistance = length( lVector ); - light.color = spotLight.color * spotAttenuation; - light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); - light.visible = ( light.color != vec3( 0.0 ) ); - } else { - light.color = vec3( 0.0 ); - light.visible = false; - } - } -#endif -#if NUM_RECT_AREA_LIGHTS > 0 - struct RectAreaLight { - vec3 color; - vec3 position; - vec3 halfWidth; - vec3 halfHeight; - }; - uniform sampler2D ltc_1; uniform sampler2D ltc_2; - uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; -#endif -#if NUM_HEMI_LIGHTS > 0 - struct HemisphereLight { - vec3 direction; - vec3 skyColor; - vec3 groundColor; - }; - uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; - vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { - float dotNL = dot( normal, hemiLight.direction ); - float hemiDiffuseWeight = 0.5 * dotNL + 0.5; - vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); - return irradiance; - } -#endif`,Zq=`#ifdef USE_ENVMAP - vec3 getIBLIrradiance( const in vec3 normal ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); - return PI * envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 reflectVec = reflect( - viewDir, normal ); - reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); - reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); - vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); - return envMapColor.rgb * envMapIntensity; - #else - return vec3( 0.0 ); - #endif - } - #ifdef USE_ANISOTROPY - vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { - #ifdef ENVMAP_TYPE_CUBE_UV - vec3 bentNormal = cross( bitangent, viewDir ); - bentNormal = normalize( cross( bentNormal, bitangent ) ); - bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); - return getIBLRadiance( viewDir, bentNormal, roughness ); - #else - return vec3( 0.0 ); - #endif - } - #endif -#endif`,Rq=`ToonMaterial material; -material.diffuseColor = diffuseColor.rgb;`,Nq=`varying vec3 vViewPosition; -struct ToonMaterial { - vec3 diffuseColor; -}; -void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { - vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_Toon -#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,Gq=`BlinnPhongMaterial material; -material.diffuseColor = diffuseColor.rgb; -material.specularColor = specular; -material.specularShininess = shininess; -material.specularStrength = specularStrength;`,Wq=`varying vec3 vViewPosition; -struct BlinnPhongMaterial { - vec3 diffuseColor; - vec3 specularColor; - float specularShininess; - float specularStrength; -}; -void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); - reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; -} -void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -#define RE_Direct RE_Direct_BlinnPhong -#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,Xq=`PhysicalMaterial material; -material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); -vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); -float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); -material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; -material.roughness = min( material.roughness, 1.0 ); -#ifdef IOR - material.ior = ior; - #ifdef USE_SPECULAR - float specularIntensityFactor = specularIntensity; - vec3 specularColorFactor = specularColor; - #ifdef USE_SPECULAR_COLORMAP - specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; - #endif - material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); - #else - float specularIntensityFactor = 1.0; - vec3 specularColorFactor = vec3( 1.0 ); - material.specularF90 = 1.0; - #endif - material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); -#else - material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); - material.specularF90 = 1.0; -#endif -#ifdef USE_CLEARCOAT - material.clearcoat = clearcoat; - material.clearcoatRoughness = clearcoatRoughness; - material.clearcoatF0 = vec3( 0.04 ); - material.clearcoatF90 = 1.0; - #ifdef USE_CLEARCOATMAP - material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; - #endif - #ifdef USE_CLEARCOAT_ROUGHNESSMAP - material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; - #endif - material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); - material.clearcoatRoughness += geometryRoughness; - material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); -#endif -#ifdef USE_DISPERSION - material.dispersion = dispersion; -#endif -#ifdef USE_IRIDESCENCE - material.iridescence = iridescence; - material.iridescenceIOR = iridescenceIOR; - #ifdef USE_IRIDESCENCEMAP - material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; - #endif - #ifdef USE_IRIDESCENCE_THICKNESSMAP - material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; - #else - material.iridescenceThickness = iridescenceThicknessMaximum; - #endif -#endif -#ifdef USE_SHEEN - material.sheenColor = sheenColor; - #ifdef USE_SHEEN_COLORMAP - material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; - #endif - material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); - #ifdef USE_SHEEN_ROUGHNESSMAP - material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; - #endif -#endif -#ifdef USE_ANISOTROPY - #ifdef USE_ANISOTROPYMAP - mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); - vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; - vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; - #else - vec2 anisotropyV = anisotropyVector; - #endif - material.anisotropy = length( anisotropyV ); - if( material.anisotropy == 0.0 ) { - anisotropyV = vec2( 1.0, 0.0 ); - } else { - anisotropyV /= material.anisotropy; - material.anisotropy = saturate( material.anisotropy ); - } - material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); - material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; - material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; -#endif`,$q=`struct PhysicalMaterial { - vec3 diffuseColor; - float roughness; - vec3 specularColor; - float specularF90; - float dispersion; - #ifdef USE_CLEARCOAT - float clearcoat; - float clearcoatRoughness; - vec3 clearcoatF0; - float clearcoatF90; - #endif - #ifdef USE_IRIDESCENCE - float iridescence; - float iridescenceIOR; - float iridescenceThickness; - vec3 iridescenceFresnel; - vec3 iridescenceF0; - #endif - #ifdef USE_SHEEN - vec3 sheenColor; - float sheenRoughness; - #endif - #ifdef IOR - float ior; - #endif - #ifdef USE_TRANSMISSION - float transmission; - float transmissionAlpha; - float thickness; - float attenuationDistance; - vec3 attenuationColor; - #endif - #ifdef USE_ANISOTROPY - float anisotropy; - float alphaT; - vec3 anisotropyT; - vec3 anisotropyB; - #endif -}; -vec3 clearcoatSpecularDirect = vec3( 0.0 ); -vec3 clearcoatSpecularIndirect = vec3( 0.0 ); -vec3 sheenSpecularDirect = vec3( 0.0 ); -vec3 sheenSpecularIndirect = vec3(0.0 ); -vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { - float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); - float x2 = x * x; - float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); - return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); -} -float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { - float a2 = pow2( alpha ); - float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); - float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); - return 0.5 / max( gv + gl, EPSILON ); -} -float D_GGX( const in float alpha, const in float dotNH ) { - float a2 = pow2( alpha ); - float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; - return RECIPROCAL_PI * a2 / pow2( denom ); -} -#ifdef USE_ANISOTROPY - float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { - float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); - float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); - float v = 0.5 / ( gv + gl ); - return saturate(v); - } - float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { - float a2 = alphaT * alphaB; - highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); - highp float v2 = dot( v, v ); - float w2 = a2 / v2; - return RECIPROCAL_PI * a2 * pow2 ( w2 ); - } -#endif -#ifdef USE_CLEARCOAT - vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { - vec3 f0 = material.clearcoatF0; - float f90 = material.clearcoatF90; - float roughness = material.clearcoatRoughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - return F * ( V * D ); - } -#endif -vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { - vec3 f0 = material.specularColor; - float f90 = material.specularF90; - float roughness = material.roughness; - float alpha = pow2( roughness ); - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float dotVH = saturate( dot( viewDir, halfDir ) ); - vec3 F = F_Schlick( f0, f90, dotVH ); - #ifdef USE_IRIDESCENCE - F = mix( F, material.iridescenceFresnel, material.iridescence ); - #endif - #ifdef USE_ANISOTROPY - float dotTL = dot( material.anisotropyT, lightDir ); - float dotTV = dot( material.anisotropyT, viewDir ); - float dotTH = dot( material.anisotropyT, halfDir ); - float dotBL = dot( material.anisotropyB, lightDir ); - float dotBV = dot( material.anisotropyB, viewDir ); - float dotBH = dot( material.anisotropyB, halfDir ); - float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); - float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); - #else - float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); - float D = D_GGX( alpha, dotNH ); - #endif - return F * ( V * D ); -} -vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { - const float LUT_SIZE = 64.0; - const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; - const float LUT_BIAS = 0.5 / LUT_SIZE; - float dotNV = saturate( dot( N, V ) ); - vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); - uv = uv * LUT_SCALE + LUT_BIAS; - return uv; -} -float LTC_ClippedSphereFormFactor( const in vec3 f ) { - float l = length( f ); - return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); -} -vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { - float x = dot( v1, v2 ); - float y = abs( x ); - float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; - float b = 3.4175940 + ( 4.1616724 + y ) * y; - float v = a / b; - float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; - return cross( v1, v2 ) * theta_sintheta; -} -vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { - vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; - vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; - vec3 lightNormal = cross( v1, v2 ); - if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); - vec3 T1, T2; - T1 = normalize( V - N * dot( V, N ) ); - T2 = - cross( N, T1 ); - mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); - vec3 coords[ 4 ]; - coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); - coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); - coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); - coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); - coords[ 0 ] = normalize( coords[ 0 ] ); - coords[ 1 ] = normalize( coords[ 1 ] ); - coords[ 2 ] = normalize( coords[ 2 ] ); - coords[ 3 ] = normalize( coords[ 3 ] ); - vec3 vectorFormFactor = vec3( 0.0 ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); - vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); - float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); - return vec3( result ); -} -#if defined( USE_SHEEN ) -float D_Charlie( float roughness, float dotNH ) { - float alpha = pow2( roughness ); - float invAlpha = 1.0 / alpha; - float cos2h = dotNH * dotNH; - float sin2h = max( 1.0 - cos2h, 0.0078125 ); - return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); -} -float V_Neubelt( float dotNV, float dotNL ) { - return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); -} -vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { - vec3 halfDir = normalize( lightDir + viewDir ); - float dotNL = saturate( dot( normal, lightDir ) ); - float dotNV = saturate( dot( normal, viewDir ) ); - float dotNH = saturate( dot( normal, halfDir ) ); - float D = D_Charlie( sheenRoughness, dotNH ); - float V = V_Neubelt( dotNV, dotNL ); - return sheenColor * ( D * V ); -} -#endif -float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - float r2 = roughness * roughness; - float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; - float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; - float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); - return saturate( DG * RECIPROCAL_PI ); -} -vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { - float dotNV = saturate( dot( normal, viewDir ) ); - const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); - const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); - vec4 r = roughness * c0 + c1; - float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; - vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; - return fab; -} -vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { - vec2 fab = DFGApprox( normal, viewDir, roughness ); - return specularColor * fab.x + specularF90 * fab.y; -} -#ifdef USE_IRIDESCENCE -void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#else -void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { -#endif - vec2 fab = DFGApprox( normal, viewDir, roughness ); - #ifdef USE_IRIDESCENCE - vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); - #else - vec3 Fr = specularColor; - #endif - vec3 FssEss = Fr * fab.x + specularF90 * fab.y; - float Ess = fab.x + fab.y; - float Ems = 1.0 - Ess; - vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); - singleScatter += FssEss; - multiScatter += Fms * Ems; -} -#if NUM_RECT_AREA_LIGHTS > 0 - void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - vec3 normal = geometryNormal; - vec3 viewDir = geometryViewDir; - vec3 position = geometryPosition; - vec3 lightPos = rectAreaLight.position; - vec3 halfWidth = rectAreaLight.halfWidth; - vec3 halfHeight = rectAreaLight.halfHeight; - vec3 lightColor = rectAreaLight.color; - float roughness = material.roughness; - vec3 rectCoords[ 4 ]; - rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; - rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; - rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; - vec2 uv = LTC_Uv( normal, viewDir, roughness ); - vec4 t1 = texture2D( ltc_1, uv ); - vec4 t2 = texture2D( ltc_2, uv ); - mat3 mInv = mat3( - vec3( t1.x, 0, t1.y ), - vec3( 0, 1, 0 ), - vec3( t1.z, 0, t1.w ) - ); - vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); - reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); - reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); - } -#endif -void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); - vec3 irradiance = dotNL * directLight.color; - #ifdef USE_CLEARCOAT - float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); - vec3 ccIrradiance = dotNLcc * directLight.color; - clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); - #endif - #ifdef USE_SHEEN - sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); - #endif - reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); - reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { - reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); -} -void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { - #ifdef USE_CLEARCOAT - clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); - #endif - #ifdef USE_SHEEN - sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); - #endif - vec3 singleScattering = vec3( 0.0 ); - vec3 multiScattering = vec3( 0.0 ); - vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; - #ifdef USE_IRIDESCENCE - computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); - #else - computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); - #endif - vec3 totalScattering = singleScattering + multiScattering; - vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); - reflectedLight.indirectSpecular += radiance * singleScattering; - reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; - reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; -} -#define RE_Direct RE_Direct_Physical -#define RE_Direct_RectArea RE_Direct_RectArea_Physical -#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical -#define RE_IndirectSpecular RE_IndirectSpecular_Physical -float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { - return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); -}`,Lq=` -vec3 geometryPosition = - vViewPosition; -vec3 geometryNormal = normal; -vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); -vec3 geometryClearcoatNormal = vec3( 0.0 ); -#ifdef USE_CLEARCOAT - geometryClearcoatNormal = clearcoatNormal; -#endif -#ifdef USE_IRIDESCENCE - float dotNVi = saturate( dot( normal, geometryViewDir ) ); - if ( material.iridescenceThickness == 0.0 ) { - material.iridescence = 0.0; - } else { - material.iridescence = saturate( material.iridescence ); - } - if ( material.iridescence > 0.0 ) { - material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); - material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); - } -#endif -IncidentLight directLight; -#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) - PointLight pointLight; - #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - pointLight = pointLights[ i ]; - getPointLightInfo( pointLight, geometryPosition, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) - pointLightShadow = pointLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) - SpotLight spotLight; - vec4 spotColor; - vec3 spotLightCoord; - bool inSpotLightMap; - #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - spotLight = spotLights[ i ]; - getSpotLightInfo( spotLight, geometryPosition, directLight ); - #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX - #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS - #else - #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #endif - #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) - spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; - inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); - spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); - directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; - #endif - #undef SPOT_LIGHT_MAP_INDEX - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - spotLightShadow = spotLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) - DirectionalLight directionalLight; - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, directLight ); - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) - RectAreaLight rectAreaLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { - rectAreaLight = rectAreaLights[ i ]; - RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - } - #pragma unroll_loop_end -#endif -#if defined( RE_IndirectDiffuse ) - vec3 iblIrradiance = vec3( 0.0 ); - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); - #if defined( USE_LIGHT_PROBES ) - irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); - #endif - #if ( NUM_HEMI_LIGHTS > 0 ) - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); - } - #pragma unroll_loop_end - #endif -#endif -#if defined( RE_IndirectSpecular ) - vec3 radiance = vec3( 0.0 ); - vec3 clearcoatRadiance = vec3( 0.0 ); -#endif`,qq=`#if defined( RE_IndirectDiffuse ) - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; - irradiance += lightMapIrradiance; - #endif - #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) - iblIrradiance += getIBLIrradiance( geometryNormal ); - #endif -#endif -#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) - #ifdef USE_ANISOTROPY - radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); - #else - radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); - #endif - #ifdef USE_CLEARCOAT - clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); - #endif -#endif`,Fq=`#if defined( RE_IndirectDiffuse ) - RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif -#if defined( RE_IndirectSpecular ) - RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); -#endif`,Dq=`#if defined( USE_LOGDEPTHBUF ) - gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; -#endif`,Mq=`#if defined( USE_LOGDEPTHBUF ) - uniform float logDepthBufFC; - varying float vFragDepth; - varying float vIsPerspective; -#endif`,wq=`#ifdef USE_LOGDEPTHBUF - varying float vFragDepth; - varying float vIsPerspective; -#endif`,_q=`#ifdef USE_LOGDEPTHBUF - vFragDepth = 1.0 + gl_Position.w; - vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); -#endif`,kq=`#ifdef USE_MAP - vec4 sampledDiffuseColor = texture2D( map, vMapUv ); - #ifdef DECODE_VIDEO_TEXTURE - sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); - #endif - diffuseColor *= sampledDiffuseColor; -#endif`,Sq=`#ifdef USE_MAP - uniform sampler2D map; -#endif`,Tq=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) - #if defined( USE_POINTS_UV ) - vec2 uv = vUv; - #else - vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; - #endif -#endif -#ifdef USE_MAP - diffuseColor *= texture2D( map, uv ); -#endif -#ifdef USE_ALPHAMAP - diffuseColor.a *= texture2D( alphaMap, uv ).g; -#endif`,zq=`#if defined( USE_POINTS_UV ) - varying vec2 vUv; -#else - #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) - uniform mat3 uvTransform; - #endif -#endif -#ifdef USE_MAP - uniform sampler2D map; -#endif -#ifdef USE_ALPHAMAP - uniform sampler2D alphaMap; -#endif`,Pq=`float metalnessFactor = metalness; -#ifdef USE_METALNESSMAP - vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); - metalnessFactor *= texelMetalness.b; -#endif`,Vq=`#ifdef USE_METALNESSMAP - uniform sampler2D metalnessMap; -#endif`,jq=`#ifdef USE_INSTANCING_MORPH - float morphTargetInfluences[ MORPHTARGETS_COUNT ]; - float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; - } -#endif`,vq=`#if defined( USE_MORPHCOLORS ) - vColor *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - #if defined( USE_COLOR_ALPHA ) - if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; - #elif defined( USE_COLOR ) - if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; - #endif - } -#endif`,hq=`#ifdef USE_MORPHNORMALS - objectNormal *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; - } -#endif`,yq=`#ifdef USE_MORPHTARGETS - #ifndef USE_INSTANCING_MORPH - uniform float morphTargetBaseInfluence; - uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; - #endif - uniform sampler2DArray morphTargetsTexture; - uniform ivec2 morphTargetsTextureSize; - vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { - int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; - int y = texelIndex / morphTargetsTextureSize.x; - int x = texelIndex - y * morphTargetsTextureSize.x; - ivec3 morphUV = ivec3( x, y, morphTargetIndex ); - return texelFetch( morphTargetsTexture, morphUV, 0 ); - } -#endif`,gq=`#ifdef USE_MORPHTARGETS - transformed *= morphTargetBaseInfluence; - for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { - if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; - } -#endif`,xq=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; -#ifdef FLAT_SHADED - vec3 fdx = dFdx( vViewPosition ); - vec3 fdy = dFdy( vViewPosition ); - vec3 normal = normalize( cross( fdx, fdy ) ); -#else - vec3 normal = normalize( vNormal ); - #ifdef DOUBLE_SIDED - normal *= faceDirection; - #endif -#endif -#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) - #ifdef USE_TANGENT - mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn = getTangentFrame( - vViewPosition, normal, - #if defined( USE_NORMALMAP ) - vNormalMapUv - #elif defined( USE_CLEARCOAT_NORMALMAP ) - vClearcoatNormalMapUv - #else - vUv - #endif - ); - #endif - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - tbn[0] *= faceDirection; - tbn[1] *= faceDirection; - #endif -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - #ifdef USE_TANGENT - mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); - #else - mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); - #endif - #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) - tbn2[0] *= faceDirection; - tbn2[1] *= faceDirection; - #endif -#endif -vec3 nonPerturbedNormal = normal;`,bq=`#ifdef USE_NORMALMAP_OBJECTSPACE - normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - #ifdef FLIP_SIDED - normal = - normal; - #endif - #ifdef DOUBLE_SIDED - normal = normal * faceDirection; - #endif - normal = normalize( normalMatrix * normal ); -#elif defined( USE_NORMALMAP_TANGENTSPACE ) - vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; - mapN.xy *= normalScale; - normal = normalize( tbn * mapN ); -#elif defined( USE_BUMPMAP ) - normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); -#endif`,fq=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,uq=`#ifndef FLAT_SHADED - varying vec3 vNormal; - #ifdef USE_TANGENT - varying vec3 vTangent; - varying vec3 vBitangent; - #endif -#endif`,pq=`#ifndef FLAT_SHADED - vNormal = normalize( transformedNormal ); - #ifdef USE_TANGENT - vTangent = normalize( transformedTangent ); - vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); - #endif -#endif`,mq=`#ifdef USE_NORMALMAP - uniform sampler2D normalMap; - uniform vec2 normalScale; -#endif -#ifdef USE_NORMALMAP_OBJECTSPACE - uniform mat3 normalMatrix; -#endif -#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) - mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { - vec3 q0 = dFdx( eye_pos.xyz ); - vec3 q1 = dFdy( eye_pos.xyz ); - vec2 st0 = dFdx( uv.st ); - vec2 st1 = dFdy( uv.st ); - vec3 N = surf_norm; - vec3 q1perp = cross( q1, N ); - vec3 q0perp = cross( N, q0 ); - vec3 T = q1perp * st0.x + q0perp * st1.x; - vec3 B = q1perp * st0.y + q0perp * st1.y; - float det = max( dot( T, T ), dot( B, B ) ); - float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); - return mat3( T * scale, B * scale, N ); - } -#endif`,cq=`#ifdef USE_CLEARCOAT - vec3 clearcoatNormal = nonPerturbedNormal; -#endif`,lq=`#ifdef USE_CLEARCOAT_NORMALMAP - vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; - clearcoatMapN.xy *= clearcoatNormalScale; - clearcoatNormal = normalize( tbn2 * clearcoatMapN ); -#endif`,dq=`#ifdef USE_CLEARCOATMAP - uniform sampler2D clearcoatMap; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - uniform sampler2D clearcoatNormalMap; - uniform vec2 clearcoatNormalScale; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - uniform sampler2D clearcoatRoughnessMap; -#endif`,nq=`#ifdef USE_IRIDESCENCEMAP - uniform sampler2D iridescenceMap; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform sampler2D iridescenceThicknessMap; -#endif`,sq=`#ifdef OPAQUE -diffuseColor.a = 1.0; -#endif -#ifdef USE_TRANSMISSION -diffuseColor.a *= material.transmissionAlpha; -#endif -gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,iq=`vec3 packNormalToRGB( const in vec3 normal ) { - return normalize( normal ) * 0.5 + 0.5; -} -vec3 unpackRGBToNormal( const in vec3 rgb ) { - return 2.0 * rgb.xyz - 1.0; -} -const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; -const float Inv255 = 1. / 255.; -const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); -const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); -const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); -const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); -vec4 packDepthToRGBA( const in float v ) { - if( v <= 0.0 ) - return vec4( 0., 0., 0., 0. ); - if( v >= 1.0 ) - return vec4( 1., 1., 1., 1. ); - float vuf; - float af = modf( v * PackFactors.a, vuf ); - float bf = modf( vuf * ShiftRight8, vuf ); - float gf = modf( vuf * ShiftRight8, vuf ); - return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); -} -vec3 packDepthToRGB( const in float v ) { - if( v <= 0.0 ) - return vec3( 0., 0., 0. ); - if( v >= 1.0 ) - return vec3( 1., 1., 1. ); - float vuf; - float bf = modf( v * PackFactors.b, vuf ); - float gf = modf( vuf * ShiftRight8, vuf ); - return vec3( vuf * Inv255, gf * PackUpscale, bf ); -} -vec2 packDepthToRG( const in float v ) { - if( v <= 0.0 ) - return vec2( 0., 0. ); - if( v >= 1.0 ) - return vec2( 1., 1. ); - float vuf; - float gf = modf( v * 256., vuf ); - return vec2( vuf * Inv255, gf ); -} -float unpackRGBAToDepth( const in vec4 v ) { - return dot( v, UnpackFactors4 ); -} -float unpackRGBToDepth( const in vec3 v ) { - return dot( v, UnpackFactors3 ); -} -float unpackRGToDepth( const in vec2 v ) { - return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; -} -vec4 pack2HalfToRGBA( const in vec2 v ) { - vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); - return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); -} -vec2 unpackRGBATo2Half( const in vec4 v ) { - return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); -} -float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { - return ( viewZ + near ) / ( near - far ); -} -float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { - return depth * ( near - far ) - near; -} -float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { - return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); -} -float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { - return ( near * far ) / ( ( far - near ) * depth - far ); -}`,oq=`#ifdef PREMULTIPLIED_ALPHA - gl_FragColor.rgb *= gl_FragColor.a; -#endif`,rq=`vec4 mvPosition = vec4( transformed, 1.0 ); -#ifdef USE_BATCHING - mvPosition = batchingMatrix * mvPosition; -#endif -#ifdef USE_INSTANCING - mvPosition = instanceMatrix * mvPosition; -#endif -mvPosition = modelViewMatrix * mvPosition; -gl_Position = projectionMatrix * mvPosition;`,aq=`#ifdef DITHERING - gl_FragColor.rgb = dithering( gl_FragColor.rgb ); -#endif`,tq=`#ifdef DITHERING - vec3 dithering( vec3 color ) { - float grid_position = rand( gl_FragCoord.xy ); - vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); - dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); - return color + dither_shift_RGB; - } -#endif`,eq=`float roughnessFactor = roughness; -#ifdef USE_ROUGHNESSMAP - vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); - roughnessFactor *= texelRoughness.g; -#endif`,AF=`#ifdef USE_ROUGHNESSMAP - uniform sampler2D roughnessMap; -#endif`,QF=`#if NUM_SPOT_LIGHT_COORDS > 0 - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#if NUM_SPOT_LIGHT_MAPS > 0 - uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; -#endif -#ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; - struct DirectionalLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; - struct SpotLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; - struct PointLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - float shadowCameraNear; - float shadowCameraFar; - }; - uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; - #endif - float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { - return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); - } - vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { - return unpackRGBATo2Half( texture2D( shadow, uv ) ); - } - float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ - float occlusion = 1.0; - vec2 distribution = texture2DDistribution( shadow, uv ); - float hard_shadow = step( compare , distribution.x ); - if (hard_shadow != 1.0 ) { - float distance = compare - distribution.x ; - float variance = max( 0.00000, distribution.y * distribution.y ); - float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); - } - return occlusion; - } - float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { - float shadow = 1.0; - shadowCoord.xyz /= shadowCoord.w; - shadowCoord.z += shadowBias; - bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; - bool frustumTest = inFrustum && shadowCoord.z <= 1.0; - if ( frustumTest ) { - #if defined( SHADOWMAP_TYPE_PCF ) - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - float dx0 = - texelSize.x * shadowRadius; - float dy0 = - texelSize.y * shadowRadius; - float dx1 = + texelSize.x * shadowRadius; - float dy1 = + texelSize.y * shadowRadius; - float dx2 = dx0 / 2.0; - float dy2 = dy0 / 2.0; - float dx3 = dx1 / 2.0; - float dy3 = dy1 / 2.0; - shadow = ( - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + - texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) - ) * ( 1.0 / 17.0 ); - #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) - vec2 texelSize = vec2( 1.0 ) / shadowMapSize; - float dx = texelSize.x; - float dy = texelSize.y; - vec2 uv = shadowCoord.xy; - vec2 f = fract( uv * shadowMapSize + 0.5 ); - uv -= f * texelSize; - shadow = ( - texture2DCompare( shadowMap, uv, shadowCoord.z ) + - texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + - texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + - texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + - mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), - f.x ) + - mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), - f.x ) + - mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), - f.y ) + - mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), - f.y ) + - mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), - f.x ), - mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), - texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), - f.x ), - f.y ) - ) * ( 1.0 / 9.0 ); - #elif defined( SHADOWMAP_TYPE_VSM ) - shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); - #else - shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); - #endif - } - return mix( 1.0, shadow, shadowIntensity ); - } - vec2 cubeToUV( vec3 v, float texelSizeY ) { - vec3 absV = abs( v ); - float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); - absV *= scaleToCube; - v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); - vec2 planar = v.xy; - float almostATexel = 1.5 * texelSizeY; - float almostOne = 1.0 - almostATexel; - if ( absV.z >= almostOne ) { - if ( v.z > 0.0 ) - planar.x = 4.0 - v.x; - } else if ( absV.x >= almostOne ) { - float signX = sign( v.x ); - planar.x = v.z * signX + 2.0 * signX; - } else if ( absV.y >= almostOne ) { - float signY = sign( v.y ); - planar.x = v.x + 2.0 * signY + 2.0; - planar.y = v.z * signY - 2.0; - } - return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); - } - float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { - float shadow = 1.0; - vec3 lightToPosition = shadowCoord.xyz; - - float lightToPositionLength = length( lightToPosition ); - if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { - float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; - vec3 bd3D = normalize( lightToPosition ); - vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); - #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) - vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; - shadow = ( - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + - texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) - ) * ( 1.0 / 9.0 ); - #else - shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); - #endif - } - return mix( 1.0, shadow, shadowIntensity ); - } -#endif`,EF=`#if NUM_SPOT_LIGHT_COORDS > 0 - uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; - varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; -#endif -#ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; - varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; - struct DirectionalLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - struct SpotLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - }; - uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; - varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; - struct PointLightShadow { - float shadowIntensity; - float shadowBias; - float shadowNormalBias; - float shadowRadius; - vec2 shadowMapSize; - float shadowCameraNear; - float shadowCameraFar; - }; - uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; - #endif -#endif`,BF=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) - vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); - vec4 shadowWorldPosition; -#endif -#if defined( USE_SHADOWMAP ) - #if NUM_DIR_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); - vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); - vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end - #endif -#endif -#if NUM_SPOT_LIGHT_COORDS > 0 - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { - shadowWorldPosition = worldPosition; - #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; - #endif - vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; - } - #pragma unroll_loop_end -#endif`,IF=`float getShadowMask() { - float shadow = 1.0; - #ifdef USE_SHADOWMAP - #if NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { - directionalLight = directionalLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { - spotLight = spotLightShadows[ i ]; - shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - } - #pragma unroll_loop_end - #endif - #if NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLight; - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { - pointLight = pointLightShadows[ i ]; - shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; - } - #pragma unroll_loop_end - #endif - #endif - return shadow; -}`,CF=`#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); -#endif`,KF=`#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif`,JF=`#ifdef USE_SKINNING - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif`,UF=`#ifdef USE_SKINNING - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; - #ifdef USE_TANGENT - objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; - #endif -#endif`,YF=`float specularStrength; -#ifdef USE_SPECULARMAP - vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); - specularStrength = texelSpecular.r; -#else - specularStrength = 1.0; -#endif`,OF=`#ifdef USE_SPECULARMAP - uniform sampler2D specularMap; -#endif`,HF=`#if defined( TONE_MAPPING ) - gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); -#endif`,ZF=`#ifndef saturate -#define saturate( a ) clamp( a, 0.0, 1.0 ) -#endif -uniform float toneMappingExposure; -vec3 LinearToneMapping( vec3 color ) { - return saturate( toneMappingExposure * color ); -} -vec3 ReinhardToneMapping( vec3 color ) { - color *= toneMappingExposure; - return saturate( color / ( vec3( 1.0 ) + color ) ); -} -vec3 CineonToneMapping( vec3 color ) { - color *= toneMappingExposure; - color = max( vec3( 0.0 ), color - 0.004 ); - return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); -} -vec3 RRTAndODTFit( vec3 v ) { - vec3 a = v * ( v + 0.0245786 ) - 0.000090537; - vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; - return a / b; -} -vec3 ACESFilmicToneMapping( vec3 color ) { - const mat3 ACESInputMat = mat3( - vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), - vec3( 0.04823, 0.01566, 0.83777 ) - ); - const mat3 ACESOutputMat = mat3( - vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), - vec3( -0.07367, -0.00605, 1.07602 ) - ); - color *= toneMappingExposure / 0.6; - color = ACESInputMat * color; - color = RRTAndODTFit( color ); - color = ACESOutputMat * color; - return saturate( color ); -} -const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( - vec3( 1.6605, - 0.1246, - 0.0182 ), - vec3( - 0.5876, 1.1329, - 0.1006 ), - vec3( - 0.0728, - 0.0083, 1.1187 ) -); -const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( - vec3( 0.6274, 0.0691, 0.0164 ), - vec3( 0.3293, 0.9195, 0.0880 ), - vec3( 0.0433, 0.0113, 0.8956 ) -); -vec3 agxDefaultContrastApprox( vec3 x ) { - vec3 x2 = x * x; - vec3 x4 = x2 * x2; - return + 15.5 * x4 * x2 - - 40.14 * x4 * x - + 31.96 * x4 - - 6.868 * x2 * x - + 0.4298 * x2 - + 0.1191 * x - - 0.00232; -} -vec3 AgXToneMapping( vec3 color ) { - const mat3 AgXInsetMatrix = mat3( - vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), - vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), - vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) - ); - const mat3 AgXOutsetMatrix = mat3( - vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), - vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), - vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) - ); - const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; - color *= toneMappingExposure; - color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; - color = AgXInsetMatrix * color; - color = max( color, 1e-10 ); color = log2( color ); - color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); - color = clamp( color, 0.0, 1.0 ); - color = agxDefaultContrastApprox( color ); - color = AgXOutsetMatrix * color; - color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); - color = LINEAR_REC2020_TO_LINEAR_SRGB * color; - color = clamp( color, 0.0, 1.0 ); - return color; -} -vec3 NeutralToneMapping( vec3 color ) { - const float StartCompression = 0.8 - 0.04; - const float Desaturation = 0.15; - color *= toneMappingExposure; - float x = min( color.r, min( color.g, color.b ) ); - float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; - color -= offset; - float peak = max( color.r, max( color.g, color.b ) ); - if ( peak < StartCompression ) return color; - float d = 1. - StartCompression; - float newPeak = 1. - d * d / ( peak + d - StartCompression ); - color *= newPeak / peak; - float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); - return mix( color, vec3( newPeak ), g ); -} -vec3 CustomToneMapping( vec3 color ) { return color; }`,RF=`#ifdef USE_TRANSMISSION - material.transmission = transmission; - material.transmissionAlpha = 1.0; - material.thickness = thickness; - material.attenuationDistance = attenuationDistance; - material.attenuationColor = attenuationColor; - #ifdef USE_TRANSMISSIONMAP - material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; - #endif - #ifdef USE_THICKNESSMAP - material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; - #endif - vec3 pos = vWorldPosition; - vec3 v = normalize( cameraPosition - pos ); - vec3 n = inverseTransformDirection( normal, viewMatrix ); - vec4 transmitted = getIBLVolumeRefraction( - n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, - pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, - material.attenuationColor, material.attenuationDistance ); - material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); - totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); -#endif`,NF=`#ifdef USE_TRANSMISSION - uniform float transmission; - uniform float thickness; - uniform float attenuationDistance; - uniform vec3 attenuationColor; - #ifdef USE_TRANSMISSIONMAP - uniform sampler2D transmissionMap; - #endif - #ifdef USE_THICKNESSMAP - uniform sampler2D thicknessMap; - #endif - uniform vec2 transmissionSamplerSize; - uniform sampler2D transmissionSamplerMap; - uniform mat4 modelMatrix; - uniform mat4 projectionMatrix; - varying vec3 vWorldPosition; - float w0( float a ) { - return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); - } - float w1( float a ) { - return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); - } - float w2( float a ){ - return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); - } - float w3( float a ) { - return ( 1.0 / 6.0 ) * ( a * a * a ); - } - float g0( float a ) { - return w0( a ) + w1( a ); - } - float g1( float a ) { - return w2( a ) + w3( a ); - } - float h0( float a ) { - return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); - } - float h1( float a ) { - return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); - } - vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { - uv = uv * texelSize.zw + 0.5; - vec2 iuv = floor( uv ); - vec2 fuv = fract( uv ); - float g0x = g0( fuv.x ); - float g1x = g1( fuv.x ); - float h0x = h0( fuv.x ); - float h1x = h1( fuv.x ); - float h0y = h0( fuv.y ); - float h1y = h1( fuv.y ); - vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; - vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; - vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; - vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; - return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + - g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); - } - vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { - vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); - vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); - vec2 fLodSizeInv = 1.0 / fLodSize; - vec2 cLodSizeInv = 1.0 / cLodSize; - vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); - vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); - return mix( fSample, cSample, fract( lod ) ); - } - vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { - vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); - vec3 modelScale; - modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); - modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); - modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); - return normalize( refractionVector ) * thickness * modelScale; - } - float applyIorToRoughness( const in float roughness, const in float ior ) { - return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); - } - vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { - float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); - return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); - } - vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { - if ( isinf( attenuationDistance ) ) { - return vec3( 1.0 ); - } else { - vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; - vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; - } - } - vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, - const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, - const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, - const in vec3 attenuationColor, const in float attenuationDistance ) { - vec4 transmittedLight; - vec3 transmittance; - #ifdef USE_DISPERSION - float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; - vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); - for ( int i = 0; i < 3; i ++ ) { - vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); - vec3 refractedRayExit = position + transmissionRay; - vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); - vec2 refractionCoords = ndcPos.xy / ndcPos.w; - refractionCoords += 1.0; - refractionCoords /= 2.0; - vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); - transmittedLight[ i ] = transmissionSample[ i ]; - transmittedLight.a += transmissionSample.a; - transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; - } - transmittedLight.a /= 3.0; - #else - vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); - vec3 refractedRayExit = position + transmissionRay; - vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); - vec2 refractionCoords = ndcPos.xy / ndcPos.w; - refractionCoords += 1.0; - refractionCoords /= 2.0; - transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); - transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); - #endif - vec3 attenuatedColor = transmittance * transmittedLight.rgb; - vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); - float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; - return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); - } -#endif`,GF=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - varying vec2 vUv; -#endif -#ifdef USE_MAP - varying vec2 vMapUv; -#endif -#ifdef USE_ALPHAMAP - varying vec2 vAlphaMapUv; -#endif -#ifdef USE_LIGHTMAP - varying vec2 vLightMapUv; -#endif -#ifdef USE_AOMAP - varying vec2 vAoMapUv; -#endif -#ifdef USE_BUMPMAP - varying vec2 vBumpMapUv; -#endif -#ifdef USE_NORMALMAP - varying vec2 vNormalMapUv; -#endif -#ifdef USE_EMISSIVEMAP - varying vec2 vEmissiveMapUv; -#endif -#ifdef USE_METALNESSMAP - varying vec2 vMetalnessMapUv; -#endif -#ifdef USE_ROUGHNESSMAP - varying vec2 vRoughnessMapUv; -#endif -#ifdef USE_ANISOTROPYMAP - varying vec2 vAnisotropyMapUv; -#endif -#ifdef USE_CLEARCOATMAP - varying vec2 vClearcoatMapUv; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - varying vec2 vClearcoatNormalMapUv; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - varying vec2 vClearcoatRoughnessMapUv; -#endif -#ifdef USE_IRIDESCENCEMAP - varying vec2 vIridescenceMapUv; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - varying vec2 vIridescenceThicknessMapUv; -#endif -#ifdef USE_SHEEN_COLORMAP - varying vec2 vSheenColorMapUv; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - varying vec2 vSheenRoughnessMapUv; -#endif -#ifdef USE_SPECULARMAP - varying vec2 vSpecularMapUv; -#endif -#ifdef USE_SPECULAR_COLORMAP - varying vec2 vSpecularColorMapUv; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - varying vec2 vSpecularIntensityMapUv; -#endif -#ifdef USE_TRANSMISSIONMAP - uniform mat3 transmissionMapTransform; - varying vec2 vTransmissionMapUv; -#endif -#ifdef USE_THICKNESSMAP - uniform mat3 thicknessMapTransform; - varying vec2 vThicknessMapUv; -#endif`,WF=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - varying vec2 vUv; -#endif -#ifdef USE_MAP - uniform mat3 mapTransform; - varying vec2 vMapUv; -#endif -#ifdef USE_ALPHAMAP - uniform mat3 alphaMapTransform; - varying vec2 vAlphaMapUv; -#endif -#ifdef USE_LIGHTMAP - uniform mat3 lightMapTransform; - varying vec2 vLightMapUv; -#endif -#ifdef USE_AOMAP - uniform mat3 aoMapTransform; - varying vec2 vAoMapUv; -#endif -#ifdef USE_BUMPMAP - uniform mat3 bumpMapTransform; - varying vec2 vBumpMapUv; -#endif -#ifdef USE_NORMALMAP - uniform mat3 normalMapTransform; - varying vec2 vNormalMapUv; -#endif -#ifdef USE_DISPLACEMENTMAP - uniform mat3 displacementMapTransform; - varying vec2 vDisplacementMapUv; -#endif -#ifdef USE_EMISSIVEMAP - uniform mat3 emissiveMapTransform; - varying vec2 vEmissiveMapUv; -#endif -#ifdef USE_METALNESSMAP - uniform mat3 metalnessMapTransform; - varying vec2 vMetalnessMapUv; -#endif -#ifdef USE_ROUGHNESSMAP - uniform mat3 roughnessMapTransform; - varying vec2 vRoughnessMapUv; -#endif -#ifdef USE_ANISOTROPYMAP - uniform mat3 anisotropyMapTransform; - varying vec2 vAnisotropyMapUv; -#endif -#ifdef USE_CLEARCOATMAP - uniform mat3 clearcoatMapTransform; - varying vec2 vClearcoatMapUv; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - uniform mat3 clearcoatNormalMapTransform; - varying vec2 vClearcoatNormalMapUv; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - uniform mat3 clearcoatRoughnessMapTransform; - varying vec2 vClearcoatRoughnessMapUv; -#endif -#ifdef USE_SHEEN_COLORMAP - uniform mat3 sheenColorMapTransform; - varying vec2 vSheenColorMapUv; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - uniform mat3 sheenRoughnessMapTransform; - varying vec2 vSheenRoughnessMapUv; -#endif -#ifdef USE_IRIDESCENCEMAP - uniform mat3 iridescenceMapTransform; - varying vec2 vIridescenceMapUv; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - uniform mat3 iridescenceThicknessMapTransform; - varying vec2 vIridescenceThicknessMapUv; -#endif -#ifdef USE_SPECULARMAP - uniform mat3 specularMapTransform; - varying vec2 vSpecularMapUv; -#endif -#ifdef USE_SPECULAR_COLORMAP - uniform mat3 specularColorMapTransform; - varying vec2 vSpecularColorMapUv; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - uniform mat3 specularIntensityMapTransform; - varying vec2 vSpecularIntensityMapUv; -#endif -#ifdef USE_TRANSMISSIONMAP - uniform mat3 transmissionMapTransform; - varying vec2 vTransmissionMapUv; -#endif -#ifdef USE_THICKNESSMAP - uniform mat3 thicknessMapTransform; - varying vec2 vThicknessMapUv; -#endif`,XF=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) - vUv = vec3( uv, 1 ).xy; -#endif -#ifdef USE_MAP - vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ALPHAMAP - vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_LIGHTMAP - vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_AOMAP - vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_BUMPMAP - vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_NORMALMAP - vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_DISPLACEMENTMAP - vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_EMISSIVEMAP - vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_METALNESSMAP - vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ROUGHNESSMAP - vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_ANISOTROPYMAP - vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOATMAP - vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOAT_NORMALMAP - vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_CLEARCOAT_ROUGHNESSMAP - vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_IRIDESCENCEMAP - vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_IRIDESCENCE_THICKNESSMAP - vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SHEEN_COLORMAP - vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SHEEN_ROUGHNESSMAP - vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULARMAP - vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULAR_COLORMAP - vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_SPECULAR_INTENSITYMAP - vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_TRANSMISSIONMAP - vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; -#endif -#ifdef USE_THICKNESSMAP - vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; -#endif`,$F=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 - vec4 worldPosition = vec4( transformed, 1.0 ); - #ifdef USE_BATCHING - worldPosition = batchingMatrix * worldPosition; - #endif - #ifdef USE_INSTANCING - worldPosition = instanceMatrix * worldPosition; - #endif - worldPosition = modelMatrix * worldPosition; -#endif`,LF=`varying vec2 vUv; -uniform mat3 uvTransform; -void main() { - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - gl_Position = vec4( position.xy, 1.0, 1.0 ); -}`,qF=`uniform sampler2D t2D; -uniform float backgroundIntensity; -varying vec2 vUv; -void main() { - vec4 texColor = texture2D( t2D, vUv ); - #ifdef DECODE_VIDEO_TEXTURE - texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,FF=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,DF=`#ifdef ENVMAP_TYPE_CUBE - uniform samplerCube envMap; -#elif defined( ENVMAP_TYPE_CUBE_UV ) - uniform sampler2D envMap; -#endif -uniform float flipEnvMap; -uniform float backgroundBlurriness; -uniform float backgroundIntensity; -uniform mat3 backgroundRotation; -varying vec3 vWorldDirection; -#include -void main() { - #ifdef ENVMAP_TYPE_CUBE - vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); - #elif defined( ENVMAP_TYPE_CUBE_UV ) - vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); - #else - vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - #endif - texColor.rgb *= backgroundIntensity; - gl_FragColor = texColor; - #include - #include -}`,MF=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include - gl_Position.z = gl_Position.w; -}`,wF=`uniform samplerCube tCube; -uniform float tFlip; -uniform float opacity; -varying vec3 vWorldDirection; -void main() { - vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); - gl_FragColor = texColor; - gl_FragColor.a *= opacity; - #include - #include -}`,_F=`#include -#include -#include -#include -#include -#include -#include -#include -varying vec2 vHighPrecisionZW; -void main() { - #include - #include - #include - #include - #ifdef USE_DISPLACEMENTMAP - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - vHighPrecisionZW = gl_Position.zw; -}`,kF=`#if DEPTH_PACKING == 3200 - uniform float opacity; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -varying vec2 vHighPrecisionZW; -void main() { - vec4 diffuseColor = vec4( 1.0 ); - #include - #if DEPTH_PACKING == 3200 - diffuseColor.a = opacity; - #endif - #include - #include - #include - #include - #include - float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; - #if DEPTH_PACKING == 3200 - gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); - #elif DEPTH_PACKING == 3201 - gl_FragColor = packDepthToRGBA( fragCoordZ ); - #elif DEPTH_PACKING == 3202 - gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); - #elif DEPTH_PACKING == 3203 - gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); - #endif -}`,SF=`#define DISTANCE -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #ifdef USE_DISPLACEMENTMAP - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - vWorldPosition = worldPosition.xyz; -}`,TF=`#define DISTANCE -uniform vec3 referencePosition; -uniform float nearDistance; -uniform float farDistance; -varying vec3 vWorldPosition; -#include -#include -#include -#include -#include -#include -#include -#include -void main () { - vec4 diffuseColor = vec4( 1.0 ); - #include - #include - #include - #include - #include - float dist = length( vWorldPosition - referencePosition ); - dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); - dist = saturate( dist ); - gl_FragColor = packDepthToRGBA( dist ); -}`,zF=`varying vec3 vWorldDirection; -#include -void main() { - vWorldDirection = transformDirection( position, modelMatrix ); - #include - #include -}`,PF=`uniform sampler2D tEquirect; -varying vec3 vWorldDirection; -#include -void main() { - vec3 direction = normalize( vWorldDirection ); - vec2 sampleUV = equirectUv( direction ); - gl_FragColor = texture2D( tEquirect, sampleUV ); - #include - #include -}`,VF=`uniform float scale; -attribute float lineDistance; -varying float vLineDistance; -#include -#include -#include -#include -#include -#include -#include -void main() { - vLineDistance = scale * lineDistance; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,jF=`uniform vec3 diffuse; -uniform float opacity; -uniform float dashSize; -uniform float totalSize; -varying float vLineDistance; -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - if ( mod( vLineDistance, totalSize ) > dashSize ) { - discard; - } - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include - #include -}`,vF=`#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) - #include - #include - #include - #include - #include - #endif - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,hF=`uniform vec3 diffuse; -uniform float opacity; -#ifndef FLAT_SHADED - varying vec3 vNormal; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - #include - #include - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - #ifdef USE_LIGHTMAP - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; - #else - reflectedLight.indirectDiffuse += vec3( 1.0 ); - #endif - #include - reflectedLight.indirectDiffuse *= diffuseColor.rgb; - vec3 outgoingLight = reflectedLight.indirectDiffuse; - #include - #include - #include - #include - #include - #include - #include -}`,yF=`#define LAMBERT -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include - #include -}`,gF=`#define LAMBERT -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,xF=`#define MATCAP -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; -}`,bF=`#define MATCAP -uniform vec3 diffuse; -uniform float opacity; -uniform sampler2D matcap; -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 viewDir = normalize( vViewPosition ); - vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); - vec3 y = cross( viewDir, x ); - vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; - #ifdef USE_MATCAP - vec4 matcapColor = texture2D( matcap, uv ); - #else - vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); - #endif - vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; - #include - #include - #include - #include - #include - #include -}`,fF=`#define NORMAL -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - vViewPosition = - mvPosition.xyz; -#endif -}`,uF=`#define NORMAL -uniform float opacity; -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - varying vec3 vViewPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); - #include - #include - #include - #include - gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); - #ifdef OPAQUE - gl_FragColor.a = 1.0; - #endif -}`,pF=`#define PHONG -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include - #include -}`,mF=`#define PHONG -uniform vec3 diffuse; -uniform vec3 emissive; -uniform vec3 specular; -uniform float shininess; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include - #include -}`,cF=`#define STANDARD -varying vec3 vViewPosition; -#ifdef USE_TRANSMISSION - varying vec3 vWorldPosition; -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include -#ifdef USE_TRANSMISSION - vWorldPosition = worldPosition.xyz; -#endif -}`,lF=`#define STANDARD -#ifdef PHYSICAL - #define IOR - #define USE_SPECULAR -#endif -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float roughness; -uniform float metalness; -uniform float opacity; -#ifdef IOR - uniform float ior; -#endif -#ifdef USE_SPECULAR - uniform float specularIntensity; - uniform vec3 specularColor; - #ifdef USE_SPECULAR_COLORMAP - uniform sampler2D specularColorMap; - #endif - #ifdef USE_SPECULAR_INTENSITYMAP - uniform sampler2D specularIntensityMap; - #endif -#endif -#ifdef USE_CLEARCOAT - uniform float clearcoat; - uniform float clearcoatRoughness; -#endif -#ifdef USE_DISPERSION - uniform float dispersion; -#endif -#ifdef USE_IRIDESCENCE - uniform float iridescence; - uniform float iridescenceIOR; - uniform float iridescenceThicknessMinimum; - uniform float iridescenceThicknessMaximum; -#endif -#ifdef USE_SHEEN - uniform vec3 sheenColor; - uniform float sheenRoughness; - #ifdef USE_SHEEN_COLORMAP - uniform sampler2D sheenColorMap; - #endif - #ifdef USE_SHEEN_ROUGHNESSMAP - uniform sampler2D sheenRoughnessMap; - #endif -#endif -#ifdef USE_ANISOTROPY - uniform vec2 anisotropyVector; - #ifdef USE_ANISOTROPYMAP - uniform sampler2D anisotropyMap; - #endif -#endif -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; - vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; - #include - vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; - #ifdef USE_SHEEN - float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); - outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; - #endif - #ifdef USE_CLEARCOAT - float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); - vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); - outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; - #endif - #include - #include - #include - #include - #include - #include -}`,dF=`#define TOON -varying vec3 vViewPosition; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vViewPosition = - mvPosition.xyz; - #include - #include - #include -}`,nF=`#define TOON -uniform vec3 diffuse; -uniform vec3 emissive; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - #include - #include - #include - #include - #include - #include -}`,sF=`uniform float size; -uniform float scale; -#include -#include -#include -#include -#include -#include -#ifdef USE_POINTS_UV - varying vec2 vUv; - uniform mat3 uvTransform; -#endif -void main() { - #ifdef USE_POINTS_UV - vUv = ( uvTransform * vec3( uv, 1 ) ).xy; - #endif - #include - #include - #include - #include - #include - #include - gl_PointSize = size; - #ifdef USE_SIZEATTENUATION - bool isPerspective = isPerspectiveMatrix( projectionMatrix ); - if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); - #endif - #include - #include - #include - #include -}`,iF=`uniform vec3 diffuse; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include - #include -}`,oF=`#include -#include -#include -#include -#include -#include -#include -void main() { - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -}`,rF=`uniform vec3 color; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - #include - gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); - #include - #include - #include -}`,aF=`uniform float rotation; -uniform vec2 center; -#include -#include -#include -#include -#include -void main() { - #include - vec4 mvPosition = modelViewMatrix[ 3 ]; - vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); - #ifndef USE_SIZEATTENUATION - bool isPerspective = isPerspectiveMatrix( projectionMatrix ); - if ( isPerspective ) scale *= - mvPosition.z; - #endif - vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; - vec2 rotatedPosition; - rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; - rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; - mvPosition.xy += rotatedPosition; - gl_Position = projectionMatrix * mvPosition; - #include - #include - #include -}`,tF=`uniform vec3 diffuse; -uniform float opacity; -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main() { - vec4 diffuseColor = vec4( diffuse, opacity ); - #include - vec3 outgoingLight = vec3( 0.0 ); - #include - #include - #include - #include - #include - outgoingLight = diffuseColor.rgb; - #include - #include - #include - #include -}`,G0={alphahash_fragment:q5,alphahash_pars_fragment:F5,alphamap_fragment:D5,alphamap_pars_fragment:M5,alphatest_fragment:w5,alphatest_pars_fragment:_5,aomap_fragment:k5,aomap_pars_fragment:S5,batching_pars_vertex:T5,batching_vertex:z5,begin_vertex:P5,beginnormal_vertex:V5,bsdfs:j5,iridescence_fragment:v5,bumpmap_pars_fragment:h5,clipping_planes_fragment:y5,clipping_planes_pars_fragment:g5,clipping_planes_pars_vertex:x5,clipping_planes_vertex:b5,color_fragment:f5,color_pars_fragment:u5,color_pars_vertex:p5,color_vertex:m5,common:c5,cube_uv_reflection_fragment:l5,defaultnormal_vertex:d5,displacementmap_pars_vertex:n5,displacementmap_vertex:s5,emissivemap_fragment:i5,emissivemap_pars_fragment:o5,colorspace_fragment:r5,colorspace_pars_fragment:a5,envmap_fragment:t5,envmap_common_pars_fragment:e5,envmap_pars_fragment:Aq,envmap_pars_vertex:Qq,envmap_physical_pars_fragment:Zq,envmap_vertex:Eq,fog_vertex:Bq,fog_pars_vertex:Iq,fog_fragment:Cq,fog_pars_fragment:Kq,gradientmap_pars_fragment:Jq,lightmap_pars_fragment:Uq,lights_lambert_fragment:Yq,lights_lambert_pars_fragment:Oq,lights_pars_begin:Hq,lights_toon_fragment:Rq,lights_toon_pars_fragment:Nq,lights_phong_fragment:Gq,lights_phong_pars_fragment:Wq,lights_physical_fragment:Xq,lights_physical_pars_fragment:$q,lights_fragment_begin:Lq,lights_fragment_maps:qq,lights_fragment_end:Fq,logdepthbuf_fragment:Dq,logdepthbuf_pars_fragment:Mq,logdepthbuf_pars_vertex:wq,logdepthbuf_vertex:_q,map_fragment:kq,map_pars_fragment:Sq,map_particle_fragment:Tq,map_particle_pars_fragment:zq,metalnessmap_fragment:Pq,metalnessmap_pars_fragment:Vq,morphinstance_vertex:jq,morphcolor_vertex:vq,morphnormal_vertex:hq,morphtarget_pars_vertex:yq,morphtarget_vertex:gq,normal_fragment_begin:xq,normal_fragment_maps:bq,normal_pars_fragment:fq,normal_pars_vertex:uq,normal_vertex:pq,normalmap_pars_fragment:mq,clearcoat_normal_fragment_begin:cq,clearcoat_normal_fragment_maps:lq,clearcoat_pars_fragment:dq,iridescence_pars_fragment:nq,opaque_fragment:sq,packing:iq,premultiplied_alpha_fragment:oq,project_vertex:rq,dithering_fragment:aq,dithering_pars_fragment:tq,roughnessmap_fragment:eq,roughnessmap_pars_fragment:AF,shadowmap_pars_fragment:QF,shadowmap_pars_vertex:EF,shadowmap_vertex:BF,shadowmask_pars_fragment:IF,skinbase_vertex:CF,skinning_pars_vertex:KF,skinning_vertex:JF,skinnormal_vertex:UF,specularmap_fragment:YF,specularmap_pars_fragment:OF,tonemapping_fragment:HF,tonemapping_pars_fragment:ZF,transmission_fragment:RF,transmission_pars_fragment:NF,uv_pars_fragment:GF,uv_pars_vertex:WF,uv_vertex:XF,worldpos_vertex:$F,background_vert:LF,background_frag:qF,backgroundCube_vert:FF,backgroundCube_frag:DF,cube_vert:MF,cube_frag:wF,depth_vert:_F,depth_frag:kF,distanceRGBA_vert:SF,distanceRGBA_frag:TF,equirect_vert:zF,equirect_frag:PF,linedashed_vert:VF,linedashed_frag:jF,meshbasic_vert:vF,meshbasic_frag:hF,meshlambert_vert:yF,meshlambert_frag:gF,meshmatcap_vert:xF,meshmatcap_frag:bF,meshnormal_vert:fF,meshnormal_frag:uF,meshphong_vert:pF,meshphong_frag:mF,meshphysical_vert:cF,meshphysical_frag:lF,meshtoon_vert:dF,meshtoon_frag:nF,points_vert:sF,points_frag:iF,shadow_vert:oF,shadow_frag:rF,sprite_vert:aF,sprite_frag:tF},vA={common:{diffuse:{value:/*@__PURE__*/new a(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:/*@__PURE__*/new E0},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/new E0},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:/*@__PURE__*/new E0}},envmap:{envMap:{value:null},envMapRotation:{value:/*@__PURE__*/new E0},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:0.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:/*@__PURE__*/new E0}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:/*@__PURE__*/new E0}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:/*@__PURE__*/new E0},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:/*@__PURE__*/new E0},normalScale:{value:/*@__PURE__*/new AA(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:/*@__PURE__*/new E0},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:/*@__PURE__*/new E0}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:/*@__PURE__*/new E0}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:/*@__PURE__*/new E0}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:0.00025},fogNear:{value:1},fogFar:{value:2000},fogColor:{value:/*@__PURE__*/new a(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:/*@__PURE__*/new a(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/new E0},alphaTest:{value:0},uvTransform:{value:/*@__PURE__*/new E0}},sprite:{diffuse:{value:/*@__PURE__*/new a(16777215)},opacity:{value:1},center:{value:/*@__PURE__*/new AA(0.5,0.5)},rotation:{value:0},map:{value:null},mapTransform:{value:/*@__PURE__*/new E0},alphaMap:{value:null},alphaMapTransform:{value:/*@__PURE__*/new E0},alphaTest:{value:0}}},CE={basic:{uniforms:/*@__PURE__*/BE([vA.common,vA.specularmap,vA.envmap,vA.aomap,vA.lightmap,vA.fog]),vertexShader:G0.meshbasic_vert,fragmentShader:G0.meshbasic_frag},lambert:{uniforms:/*@__PURE__*/BE([vA.common,vA.specularmap,vA.envmap,vA.aomap,vA.lightmap,vA.emissivemap,vA.bumpmap,vA.normalmap,vA.displacementmap,vA.fog,vA.lights,{emissive:{value:/*@__PURE__*/new a(0)}}]),vertexShader:G0.meshlambert_vert,fragmentShader:G0.meshlambert_frag},phong:{uniforms:/*@__PURE__*/BE([vA.common,vA.specularmap,vA.envmap,vA.aomap,vA.lightmap,vA.emissivemap,vA.bumpmap,vA.normalmap,vA.displacementmap,vA.fog,vA.lights,{emissive:{value:/*@__PURE__*/new a(0)},specular:{value:/*@__PURE__*/new a(1118481)},shininess:{value:30}}]),vertexShader:G0.meshphong_vert,fragmentShader:G0.meshphong_frag},standard:{uniforms:/*@__PURE__*/BE([vA.common,vA.envmap,vA.aomap,vA.lightmap,vA.emissivemap,vA.bumpmap,vA.normalmap,vA.displacementmap,vA.roughnessmap,vA.metalnessmap,vA.fog,vA.lights,{emissive:{value:/*@__PURE__*/new a(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:G0.meshphysical_vert,fragmentShader:G0.meshphysical_frag},toon:{uniforms:/*@__PURE__*/BE([vA.common,vA.aomap,vA.lightmap,vA.emissivemap,vA.bumpmap,vA.normalmap,vA.displacementmap,vA.gradientmap,vA.fog,vA.lights,{emissive:{value:/*@__PURE__*/new a(0)}}]),vertexShader:G0.meshtoon_vert,fragmentShader:G0.meshtoon_frag},matcap:{uniforms:/*@__PURE__*/BE([vA.common,vA.bumpmap,vA.normalmap,vA.displacementmap,vA.fog,{matcap:{value:null}}]),vertexShader:G0.meshmatcap_vert,fragmentShader:G0.meshmatcap_frag},points:{uniforms:/*@__PURE__*/BE([vA.points,vA.fog]),vertexShader:G0.points_vert,fragmentShader:G0.points_frag},dashed:{uniforms:/*@__PURE__*/BE([vA.common,vA.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:G0.linedashed_vert,fragmentShader:G0.linedashed_frag},depth:{uniforms:/*@__PURE__*/BE([vA.common,vA.displacementmap]),vertexShader:G0.depth_vert,fragmentShader:G0.depth_frag},normal:{uniforms:/*@__PURE__*/BE([vA.common,vA.bumpmap,vA.normalmap,vA.displacementmap,{opacity:{value:1}}]),vertexShader:G0.meshnormal_vert,fragmentShader:G0.meshnormal_frag},sprite:{uniforms:/*@__PURE__*/BE([vA.sprite,vA.fog]),vertexShader:G0.sprite_vert,fragmentShader:G0.sprite_frag},background:{uniforms:{uvTransform:{value:/*@__PURE__*/new E0},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:G0.background_vert,fragmentShader:G0.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:/*@__PURE__*/new E0}},vertexShader:G0.backgroundCube_vert,fragmentShader:G0.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:G0.cube_vert,fragmentShader:G0.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:G0.equirect_vert,fragmentShader:G0.equirect_frag},distanceRGBA:{uniforms:/*@__PURE__*/BE([vA.common,vA.displacementmap,{referencePosition:{value:/*@__PURE__*/new y},nearDistance:{value:1},farDistance:{value:1000}}]),vertexShader:G0.distanceRGBA_vert,fragmentShader:G0.distanceRGBA_frag},shadow:{uniforms:/*@__PURE__*/BE([vA.lights,vA.fog,{color:{value:/*@__PURE__*/new a(0)},opacity:{value:1}}]),vertexShader:G0.shadow_vert,fragmentShader:G0.shadow_frag}};CE.physical={uniforms:/*@__PURE__*/BE([CE.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:/*@__PURE__*/new E0},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:/*@__PURE__*/new E0},clearcoatNormalScale:{value:/*@__PURE__*/new AA(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:/*@__PURE__*/new E0},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:/*@__PURE__*/new E0},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:/*@__PURE__*/new E0},sheen:{value:0},sheenColor:{value:/*@__PURE__*/new a(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:/*@__PURE__*/new E0},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:/*@__PURE__*/new E0},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:/*@__PURE__*/new E0},transmissionSamplerSize:{value:/*@__PURE__*/new AA},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:/*@__PURE__*/new E0},attenuationDistance:{value:0},attenuationColor:{value:/*@__PURE__*/new a(0)},specularColor:{value:/*@__PURE__*/new a(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:/*@__PURE__*/new E0},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:/*@__PURE__*/new E0},anisotropyVector:{value:/*@__PURE__*/new AA},anisotropyMap:{value:null},anisotropyMapTransform:{value:/*@__PURE__*/new E0}}]),vertexShader:G0.meshphysical_vert,fragmentShader:G0.meshphysical_frag};var t9={r:0,b:0,g:0},f1=/*@__PURE__*/new DQ,eF=/*@__PURE__*/new RA;function AD(A,Q,E,B,I,C,K){let J=new a(0),U=C===!0?0:1,Y,H,R=null,O=0,N=null;function $(X){let q=X.isScene===!0?X.background:null;if(q&&q.isTexture)q=(X.backgroundBlurriness>0?E:Q).get(q);return q}function L(X){let q=!1,M=$(X);if(M===null)Z(J,U);else if(M&&M.isColor)Z(M,1),q=!0;let F=A.xr.getEnvironmentBlendMode();if(F==="additive")B.buffers.color.setClear(0,0,0,1,K);else if(F==="alpha-blend")B.buffers.color.setClear(0,0,0,0,K);if(A.autoClear||q)B.buffers.depth.setTest(!0),B.buffers.depth.setMask(!0),B.buffers.color.setMask(!0),A.clear(A.autoClearColor,A.autoClearDepth,A.autoClearStencil)}function W(X,q){let M=$(q);if(M&&(M.isCubeTexture||M.mapping===V8)){if(H===void 0)H=new xA(new bQ(1,1,1),new bA({name:"BackgroundCubeMaterial",uniforms:v1(CE.backgroundCube.uniforms),vertexShader:CE.backgroundCube.vertexShader,fragmentShader:CE.backgroundCube.fragmentShader,side:ZQ,depthTest:!1,depthWrite:!1,fog:!1})),H.geometry.deleteAttribute("normal"),H.geometry.deleteAttribute("uv"),H.onBeforeRender=function(F,D,_){this.matrixWorld.copyPosition(_.matrixWorld)},Object.defineProperty(H.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),I.update(H);if(f1.copy(q.backgroundRotation),f1.x*=-1,f1.y*=-1,f1.z*=-1,M.isCubeTexture&&M.isRenderTargetTexture===!1)f1.y*=-1,f1.z*=-1;if(H.material.uniforms.envMap.value=M,H.material.uniforms.flipEnvMap.value=M.isCubeTexture&&M.isRenderTargetTexture===!1?-1:1,H.material.uniforms.backgroundBlurriness.value=q.backgroundBlurriness,H.material.uniforms.backgroundIntensity.value=q.backgroundIntensity,H.material.uniforms.backgroundRotation.value.setFromMatrix4(eF.makeRotationFromEuler(f1)),H.material.toneMapped=O0.getTransfer(M.colorSpace)!==IQ,R!==M||O!==M.version||N!==A.toneMapping)H.material.needsUpdate=!0,R=M,O=M.version,N=A.toneMapping;H.layers.enableAll(),X.unshift(H,H.geometry,H.material,0,0,null)}else if(M&&M.isTexture){if(Y===void 0)Y=new xA(new dQ(2,2),new bA({name:"BackgroundMaterial",uniforms:v1(CE.background.uniforms),vertexShader:CE.background.vertexShader,fragmentShader:CE.background.fragmentShader,side:jQ,depthTest:!1,depthWrite:!1,fog:!1})),Y.geometry.deleteAttribute("normal"),Object.defineProperty(Y.material,"map",{get:function(){return this.uniforms.t2D.value}}),I.update(Y);if(Y.material.uniforms.t2D.value=M,Y.material.uniforms.backgroundIntensity.value=q.backgroundIntensity,Y.material.toneMapped=O0.getTransfer(M.colorSpace)!==IQ,M.matrixAutoUpdate===!0)M.updateMatrix();if(Y.material.uniforms.uvTransform.value.copy(M.matrix),R!==M||O!==M.version||N!==A.toneMapping)Y.material.needsUpdate=!0,R=M,O=M.version,N=A.toneMapping;Y.layers.enableAll(),X.unshift(Y,Y.geometry,Y.material,0,0,null)}}function Z(X,q){X.getRGB(t9,_O(A)),B.buffers.color.setClear(t9.r,t9.g,t9.b,q,K)}function G(){if(H!==void 0)H.geometry.dispose(),H.material.dispose(),H=void 0;if(Y!==void 0)Y.geometry.dispose(),Y.material.dispose(),Y=void 0}return{getClearColor:function(){return J},setClearColor:function(X,q=1){J.set(X),U=q,Z(J,U)},getClearAlpha:function(){return U},setClearAlpha:function(X){U=X,Z(J,U)},render:L,addToRenderList:W,dispose:G}}function QD(A,Q){let E=A.getParameter(A.MAX_VERTEX_ATTRIBS),B={},I=O(null),C=I,K=!1;function J(k,T,z,j,v){let g=!1,P=R(j,z,T);if(C!==P)C=P,Y(C.object);if(g=N(k,j,z,v),g)$(k,j,z,v);if(v!==null)Q.update(v,A.ELEMENT_ARRAY_BUFFER);if(g||K){if(K=!1,q(k,T,z,j),v!==null)A.bindBuffer(A.ELEMENT_ARRAY_BUFFER,Q.get(v).buffer)}}function U(){return A.createVertexArray()}function Y(k){return A.bindVertexArray(k)}function H(k){return A.deleteVertexArray(k)}function R(k,T,z){let j=z.wireframe===!0,v=B[k.id];if(v===void 0)v={},B[k.id]=v;let g=v[T.id];if(g===void 0)g={},v[T.id]=g;let P=g[j];if(P===void 0)P=O(U()),g[j]=P;return P}function O(k){let T=[],z=[],j=[];for(let v=0;v=0){let x=v[S],b=g[S];if(b===void 0){if(S==="instanceMatrix"&&k.instanceMatrix)b=k.instanceMatrix;if(S==="instanceColor"&&k.instanceColor)b=k.instanceColor}if(x===void 0)return!0;if(x.attribute!==b)return!0;if(b&&x.data!==b.data)return!0;P++}if(C.attributesNum!==P)return!0;if(C.index!==j)return!0;return!1}function $(k,T,z,j){let v={},g=T.attributes,P=0,V=z.getAttributes();for(let S in V)if(V[S].location>=0){let x=g[S];if(x===void 0){if(S==="instanceMatrix"&&k.instanceMatrix)x=k.instanceMatrix;if(S==="instanceColor"&&k.instanceColor)x=k.instanceColor}let b={};if(b.attribute=x,x&&x.data)b.data=x.data;v[S]=b,P++}C.attributes=v,C.attributesNum=P,C.index=j}function L(){let k=C.newAttributes;for(let T=0,z=k.length;T=0){let h=v[V];if(h===void 0){if(V==="instanceMatrix"&&k.instanceMatrix)h=k.instanceMatrix;if(V==="instanceColor"&&k.instanceColor)h=k.instanceColor}if(h!==void 0){let{normalized:x,itemSize:b}=h,m=Q.get(h);if(m===void 0)continue;let{buffer:s,type:i,bytesPerElement:n}=m,l=i===A.INT||i===A.UNSIGNED_INT||h.gpuType===aJ;if(h.isInterleavedBufferAttribute){let c=h.data,o=c.stride,e=h.offset;if(c.isInstancedInterleavedBuffer){for(let BA=0;BA0&&A.getShaderPrecisionFormat(A.FRAGMENT_SHADER,A.HIGH_FLOAT).precision>0)return"highp";D="mediump"}if(D==="mediump"){if(A.getShaderPrecisionFormat(A.VERTEX_SHADER,A.MEDIUM_FLOAT).precision>0&&A.getShaderPrecisionFormat(A.FRAGMENT_SHADER,A.MEDIUM_FLOAT).precision>0)return"mediump"}return"lowp"}let Y=E.precision!==void 0?E.precision:"highp",H=U(Y);if(H!==Y)console.warn("THREE.WebGLRenderer:",Y,"not supported, using",H,"instead."),Y=H;let R=E.logarithmicDepthBuffer===!0,O=E.reverseDepthBuffer===!0&&Q.has("EXT_clip_control"),N=A.getParameter(A.MAX_TEXTURE_IMAGE_UNITS),$=A.getParameter(A.MAX_VERTEX_TEXTURE_IMAGE_UNITS),L=A.getParameter(A.MAX_TEXTURE_SIZE),W=A.getParameter(A.MAX_CUBE_MAP_TEXTURE_SIZE),Z=A.getParameter(A.MAX_VERTEX_ATTRIBS),G=A.getParameter(A.MAX_VERTEX_UNIFORM_VECTORS),X=A.getParameter(A.MAX_VARYING_VECTORS),q=A.getParameter(A.MAX_FRAGMENT_UNIFORM_VECTORS),M=$>0,F=A.getParameter(A.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:C,getMaxPrecision:U,textureFormatReadable:K,textureTypeReadable:J,precision:Y,logarithmicDepthBuffer:R,reverseDepthBuffer:O,maxTextures:N,maxVertexTextures:$,maxTextureSize:L,maxCubemapSize:W,maxAttributes:Z,maxVertexUniforms:G,maxVaryings:X,maxFragmentUniforms:q,vertexTextures:M,maxSamples:F}}function ID(A){let Q=this,E=null,B=0,I=!1,C=!1,K=new UQ,J=new E0,U={value:null,needsUpdate:!1};this.uniform=U,this.numPlanes=0,this.numIntersection=0,this.init=function(R,O){let N=R.length!==0||O||B!==0||I;return I=O,B=R.length,N},this.beginShadows=function(){C=!0,H(null)},this.endShadows=function(){C=!1},this.setGlobalState=function(R,O){E=H(R,O,0)},this.setState=function(R,O,N){let{clippingPlanes:$,clipIntersection:L,clipShadows:W}=R,Z=A.get(R);if(!I||$===null||$.length===0||C&&!W)if(C)H(null);else Y();else{let G=C?0:B,X=G*4,q=Z.clippingState||null;U.value=q,q=H($,O,X,N);for(let M=0;M!==X;++M)q[M]=E[M];Z.clippingState=q,this.numIntersection=L?this.numPlanes:0,this.numPlanes+=G}};function Y(){if(U.value!==E)U.value=E,U.needsUpdate=B>0;Q.numPlanes=B,Q.numIntersection=0}function H(R,O,N,$){let L=R!==null?R.length:0,W=null;if(L!==0){if(W=U.value,$!==!0||W===null){let Z=N+L*4,G=O.matrixWorldInverse;if(J.getNormalMatrix(G),W===null||W.length0){let Y=new DC(U.height);return Y.fromEquirectangularTexture(A,K),Q.set(K,Y),K.addEventListener("dispose",I),E(Y.texture,K.mapping)}else return null}}return K}function I(K){let J=K.target;J.removeEventListener("dispose",I);let U=Q.get(J);if(U!==void 0)Q.delete(J),U.dispose()}function C(){Q=/*@__PURE__*/new WeakMap}return{get:B,dispose:C}}var K6=4,IN=[0.125,0.215,0.35,0.446,0.526,0.582],m1=20,AH=/*@__PURE__*/new HE,CN=/*@__PURE__*/new a,QH=null,EH=0,BH=0,IH=!1,p1=(1+Math.sqrt(5))/2,C6=1/p1,KN=[/*@__PURE__*/new y(-p1,C6,0),/*@__PURE__*/new y(p1,C6,0),/*@__PURE__*/new y(-C6,0,p1),/*@__PURE__*/new y(C6,0,p1),/*@__PURE__*/new y(0,p1,-C6),/*@__PURE__*/new y(0,p1,C6),/*@__PURE__*/new y(-1,1,-1),/*@__PURE__*/new y(1,1,-1),/*@__PURE__*/new y(-1,1,1),/*@__PURE__*/new y(1,1,1)];class QU{constructor(A){this._renderer=A,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(A,Q=0,E=0.1,B=100){QH=this._renderer.getRenderTarget(),EH=this._renderer.getActiveCubeFace(),BH=this._renderer.getActiveMipmapLevel(),IH=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);let I=this._allocateTargets();if(I.depthBuffer=!0,this._sceneToCubeUV(A,E,B,I),Q>0)this._blur(I,0,0,Q);return this._applyPMREM(I),this._cleanup(I),I}fromEquirectangular(A,Q=null){return this._fromTexture(A,Q)}fromCubemap(A,Q=null){return this._fromTexture(A,Q)}compileCubemapShader(){if(this._cubemapMaterial===null)this._cubemapMaterial=YN(),this._compileMaterial(this._cubemapMaterial)}compileEquirectangularShader(){if(this._equirectMaterial===null)this._equirectMaterial=UN(),this._compileMaterial(this._equirectMaterial)}dispose(){if(this._dispose(),this._cubemapMaterial!==null)this._cubemapMaterial.dispose();if(this._equirectMaterial!==null)this._equirectMaterial.dispose()}_setSize(A){this._lodMax=Math.floor(Math.log2(A)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){if(this._blurMaterial!==null)this._blurMaterial.dispose();if(this._pingPongRenderTarget!==null)this._pingPongRenderTarget.dispose();for(let A=0;A2?G:0,G,G),Y.setRenderTarget(B),$)Y.render(N,K);Y.render(A,K)}N.geometry.dispose(),N.material.dispose(),Y.toneMapping=R,Y.autoClear=H,A.background=L}_textureToCubeUV(A,Q){let E=this._renderer,B=A.mapping===G1||A.mapping===zI;if(B){if(this._cubemapMaterial===null)this._cubemapMaterial=YN();this._cubemapMaterial.uniforms.flipEnvMap.value=A.isRenderTargetTexture===!1?-1:1}else if(this._equirectMaterial===null)this._equirectMaterial=UN();let I=B?this._cubemapMaterial:this._equirectMaterial,C=new xA(this._lodPlanes[0],I),K=I.uniforms;K.envMap.value=A;let J=this._cubeSize;e9(Q,0,0,3*J,2*J),E.setRenderTarget(Q),E.render(C,AH)}_applyPMREM(A){let Q=this._renderer,E=Q.autoClear;Q.autoClear=!1;let B=this._lodPlanes.length;for(let I=1;Im1)console.warn(`sigmaRadians, ${I}, is too large and will clip, as it requested ${L} samples when the maximum is set to ${m1}`);let W=[],Z=0;for(let F=0;FG-K6?B-G+K6:0),M=4*(this._cubeSize-X);e9(Q,q,M,3*X,2*X),J.setRenderTarget(Q),J.render(H,AH)}}function KD(A){let Q=[],E=[],B=[],I=A,C=A-K6+1+IN.length;for(let K=0;KA-K6)U=IN[K-A+K6-1];else if(K===0)U=0;B.push(U);let Y=1/(J-2),H=-Y,R=1+Y,O=[H,H,R,H,R,R,H,H,R,R,H,R],N=6,$=6,L=3,W=2,Z=1,G=new Float32Array(L*$*N),X=new Float32Array(W*$*N),q=new Float32Array(Z*$*N);for(let F=0;F2?0:-1,w=[D,_,0,D+0.6666666666666666,_,0,D+0.6666666666666666,_+1,0,D,_,0,D+0.6666666666666666,_+1,0,D,_+1,0];G.set(w,L*$*F),X.set(O,W*$*F);let k=[F,F,F,F,F,F];q.set(k,Z*$*F)}let M=new hA;if(M.setAttribute("position",new tA(G,L)),M.setAttribute("uv",new tA(X,W)),M.setAttribute("faceIndex",new tA(q,Z)),Q.push(M),I>K6)I--}return{lodPlanes:Q,sizeLods:E,sigmas:B}}function JN(A,Q,E){let B=new Q0(A,Q,E);return B.texture.mapping=V8,B.texture.name="PMREM.cubeUv",B.scissorTest=!0,B}function e9(A,Q,E,B,I){A.viewport.set(Q,E,B,I),A.scissor.set(Q,E,B,I)}function JD(A,Q,E){let B=new Float32Array(m1),I=new y(0,1,0);return new bA({name:"SphericalGaussianBlur",defines:{n:m1,CUBEUV_TEXEL_WIDTH:1/Q,CUBEUV_TEXEL_HEIGHT:1/E,CUBEUV_MAX_MIP:`${A}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:B},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:I}},vertexShader:JH(),fragmentShader:` - - precision mediump float; - precision mediump int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - uniform int samples; - uniform float weights[ n ]; - uniform bool latitudinal; - uniform float dTheta; - uniform float mipInt; - uniform vec3 poleAxis; - - #define ENVMAP_TYPE_CUBE_UV - #include - - vec3 getSample( float theta, vec3 axis ) { - - float cosTheta = cos( theta ); - // Rodrigues' axis-angle rotation - vec3 sampleDirection = vOutputDirection * cosTheta - + cross( axis, vOutputDirection ) * sin( theta ) - + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); - - return bilinearCubeUV( envMap, sampleDirection, mipInt ); - - } - - void main() { - - vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); - - if ( all( equal( axis, vec3( 0.0 ) ) ) ) { - - axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); - - } - - axis = normalize( axis ); - - gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); - gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); - - for ( int i = 1; i < n; i++ ) { - - if ( i >= samples ) { - - break; - - } - - float theta = dTheta * float( i ); - gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); - gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); - - } - - } - `,blending:H0,depthTest:!1,depthWrite:!1})}function UN(){return new bA({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:JH(),fragmentShader:` - - precision mediump float; - precision mediump int; - - varying vec3 vOutputDirection; - - uniform sampler2D envMap; - - #include - - void main() { - - vec3 outputDirection = normalize( vOutputDirection ); - vec2 uv = equirectUv( outputDirection ); - - gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); - - } - `,blending:H0,depthTest:!1,depthWrite:!1})}function YN(){return new bA({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:JH(),fragmentShader:` - - precision mediump float; - precision mediump int; - - uniform float flipEnvMap; - - varying vec3 vOutputDirection; - - uniform samplerCube envMap; - - void main() { - - gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); - - } - `,blending:H0,depthTest:!1,depthWrite:!1})}function JH(){return` - - precision mediump float; - precision mediump int; - - attribute float faceIndex; - - varying vec3 vOutputDirection; - - // RH coordinate system; PMREM face-indexing convention - vec3 getDirection( vec2 uv, float face ) { - - uv = 2.0 * uv - 1.0; - - vec3 direction = vec3( uv, 1.0 ); - - if ( face == 0.0 ) { - - direction = direction.zyx; // ( 1, v, u ) pos x - - } else if ( face == 1.0 ) { - - direction = direction.xzy; - direction.xz *= -1.0; // ( -u, 1, -v ) pos y - - } else if ( face == 2.0 ) { - - direction.x *= -1.0; // ( -u, v, 1 ) pos z - - } else if ( face == 3.0 ) { - - direction = direction.zyx; - direction.xz *= -1.0; // ( -1, v, -u ) neg x - - } else if ( face == 4.0 ) { - - direction = direction.xzy; - direction.xy *= -1.0; // ( -u, -1, v ) neg y - - } else if ( face == 5.0 ) { - - direction.z *= -1.0; // ( u, v, -1 ) neg z - - } - - return direction; - - } - - void main() { - - vOutputDirection = getDirection( uv, faceIndex ); - gl_Position = vec4( position, 1.0 ); - - } - `}function UD(A){let Q=/*@__PURE__*/new WeakMap,E=null;function B(J){if(J&&J.isTexture){let U=J.mapping,Y=U===W1||U===P8,H=U===G1||U===zI;if(Y||H){let R=Q.get(J),O=R!==void 0?R.texture.pmremVersion:0;if(J.isRenderTargetTexture&&J.pmremVersion!==O){if(E===null)E=new QU(A);return R=Y?E.fromEquirectangular(J,R):E.fromCubemap(J,R),R.texture.pmremVersion=J.pmremVersion,Q.set(J,R),R.texture}else if(R!==void 0)return R.texture;else{let N=J.image;if(Y&&N&&N.height>0||H&&N&&I(N)){if(E===null)E=new QU(A);return R=Y?E.fromEquirectangular(J):E.fromCubemap(J),R.texture.pmremVersion=J.pmremVersion,Q.set(J,R),J.addEventListener("dispose",C),R.texture}else return null}}}return J}function I(J){let U=0,Y=6;for(let H=0;HQ.maxTextureSize)M=Math.ceil(q/Q.maxTextureSize),q=Q.maxTextureSize;let F=new Float32Array(q*M*4*R),D=new V1(F,q,M,R);D.type=m0,D.needsUpdate=!0;let _=X*4;for(let k=0;k0)return A;let I=Q*E,C=HN[I];if(C===void 0)C=new Float32Array(I),HN[I]=C;if(Q!==0){B.toArray(C,0);for(let K=1,J=0;K!==Q;++K)J+=E,A[K].toArray(C,J)}return C}function uQ(A,Q){if(A.length!==Q.length)return!1;for(let E=0,B=A.length;E":" "} ${J}: ${E[K]}`)}return B.join(` -`)}var $N=/*@__PURE__*/new E0;function CM(A){O0._getMatrix($N,O0.workingColorSpace,A);let Q=`mat3( ${$N.elements.map((E)=>E.toFixed(4))} )`;switch(O0.getTransfer(A)){case LC:return[Q,"LinearTransferOETF"];case IQ:return[Q,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",A),[Q,"LinearTransferOETF"]}}function LN(A,Q,E){let B=A.getShaderParameter(Q,A.COMPILE_STATUS),I=A.getShaderInfoLog(Q).trim();if(B&&I==="")return"";let C=/ERROR: 0:(\d+)/.exec(I);if(C){let K=parseInt(C[1]);return E.toUpperCase()+` - -`+I+` - -`+IM(A.getShaderSource(Q),K)}else return I}function KM(A,Q){let E=CM(Q);return[`vec4 ${A}( vec4 value ) {`,` return ${E[1]}( vec4( value.rgb * ${E[0]}, value.a ) );`,"}"].join(` -`)}function JM(A,Q){let E;switch(Q){case lJ:E="Linear";break;case dJ:E="Reinhard";break;case nJ:E="Cineon";break;case sJ:E="ACESFilmic";break;case oJ:E="AgX";break;case rJ:E="Neutral";break;case iJ:E="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",Q),E="Linear"}return"vec3 "+A+"( vec3 color ) { return "+E+"ToneMapping( color ); }"}var AU=/*@__PURE__*/new y;function UM(){O0.getLuminanceCoefficients(AU);let A=AU.x.toFixed(4),Q=AU.y.toFixed(4),E=AU.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${A}, ${Q}, ${E} );`,"\treturn dot( weights, rgb );","}"].join(` -`)}function YM(A){return[A.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",A.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(tC).join(` -`)}function OM(A){let Q=[];for(let E in A){let B=A[E];if(B===!1)continue;Q.push("#define "+E+" "+B)}return Q.join(` -`)}function HM(A,Q){let E={},B=A.getProgramParameter(Q,A.ACTIVE_ATTRIBUTES);for(let I=0;I/gm;function KH(A){return A.replace(ZM,NM)}var RM=/*@__PURE__*/new Map;function NM(A,Q){let E=G0[Q];if(E===void 0){let B=RM.get(Q);if(B!==void 0)E=G0[B],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',Q,B);else throw new Error("Can not resolve #include <"+Q+">")}return KH(E)}var GM=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function DN(A){return A.replace(GM,WM)}function WM(A,Q,E,B){let I="";for(let C=parseInt(Q);C0)W+=` -`;if(Z=["#define SHADER_TYPE "+E.shaderType,"#define SHADER_NAME "+E.shaderName,$].filter(tC).join(` -`),Z.length>0)Z+=` -`}else W=[MN(E),"#define SHADER_TYPE "+E.shaderType,"#define SHADER_NAME "+E.shaderName,$,E.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",E.batching?"#define USE_BATCHING":"",E.batchingColor?"#define USE_BATCHING_COLOR":"",E.instancing?"#define USE_INSTANCING":"",E.instancingColor?"#define USE_INSTANCING_COLOR":"",E.instancingMorph?"#define USE_INSTANCING_MORPH":"",E.useFog&&E.fog?"#define USE_FOG":"",E.useFog&&E.fogExp2?"#define FOG_EXP2":"",E.map?"#define USE_MAP":"",E.envMap?"#define USE_ENVMAP":"",E.envMap?"#define "+H:"",E.lightMap?"#define USE_LIGHTMAP":"",E.aoMap?"#define USE_AOMAP":"",E.bumpMap?"#define USE_BUMPMAP":"",E.normalMap?"#define USE_NORMALMAP":"",E.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",E.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",E.displacementMap?"#define USE_DISPLACEMENTMAP":"",E.emissiveMap?"#define USE_EMISSIVEMAP":"",E.anisotropy?"#define USE_ANISOTROPY":"",E.anisotropyMap?"#define USE_ANISOTROPYMAP":"",E.clearcoatMap?"#define USE_CLEARCOATMAP":"",E.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",E.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",E.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",E.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",E.specularMap?"#define USE_SPECULARMAP":"",E.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",E.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",E.roughnessMap?"#define USE_ROUGHNESSMAP":"",E.metalnessMap?"#define USE_METALNESSMAP":"",E.alphaMap?"#define USE_ALPHAMAP":"",E.alphaHash?"#define USE_ALPHAHASH":"",E.transmission?"#define USE_TRANSMISSION":"",E.transmissionMap?"#define USE_TRANSMISSIONMAP":"",E.thicknessMap?"#define USE_THICKNESSMAP":"",E.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",E.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",E.mapUv?"#define MAP_UV "+E.mapUv:"",E.alphaMapUv?"#define ALPHAMAP_UV "+E.alphaMapUv:"",E.lightMapUv?"#define LIGHTMAP_UV "+E.lightMapUv:"",E.aoMapUv?"#define AOMAP_UV "+E.aoMapUv:"",E.emissiveMapUv?"#define EMISSIVEMAP_UV "+E.emissiveMapUv:"",E.bumpMapUv?"#define BUMPMAP_UV "+E.bumpMapUv:"",E.normalMapUv?"#define NORMALMAP_UV "+E.normalMapUv:"",E.displacementMapUv?"#define DISPLACEMENTMAP_UV "+E.displacementMapUv:"",E.metalnessMapUv?"#define METALNESSMAP_UV "+E.metalnessMapUv:"",E.roughnessMapUv?"#define ROUGHNESSMAP_UV "+E.roughnessMapUv:"",E.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+E.anisotropyMapUv:"",E.clearcoatMapUv?"#define CLEARCOATMAP_UV "+E.clearcoatMapUv:"",E.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+E.clearcoatNormalMapUv:"",E.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+E.clearcoatRoughnessMapUv:"",E.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+E.iridescenceMapUv:"",E.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+E.iridescenceThicknessMapUv:"",E.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+E.sheenColorMapUv:"",E.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+E.sheenRoughnessMapUv:"",E.specularMapUv?"#define SPECULARMAP_UV "+E.specularMapUv:"",E.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+E.specularColorMapUv:"",E.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+E.specularIntensityMapUv:"",E.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+E.transmissionMapUv:"",E.thicknessMapUv?"#define THICKNESSMAP_UV "+E.thicknessMapUv:"",E.vertexTangents&&E.flatShading===!1?"#define USE_TANGENT":"",E.vertexColors?"#define USE_COLOR":"",E.vertexAlphas?"#define USE_COLOR_ALPHA":"",E.vertexUv1s?"#define USE_UV1":"",E.vertexUv2s?"#define USE_UV2":"",E.vertexUv3s?"#define USE_UV3":"",E.pointsUvs?"#define USE_POINTS_UV":"",E.flatShading?"#define FLAT_SHADED":"",E.skinning?"#define USE_SKINNING":"",E.morphTargets?"#define USE_MORPHTARGETS":"",E.morphNormals&&E.flatShading===!1?"#define USE_MORPHNORMALS":"",E.morphColors?"#define USE_MORPHCOLORS":"",E.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+E.morphTextureStride:"",E.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+E.morphTargetsCount:"",E.doubleSided?"#define DOUBLE_SIDED":"",E.flipSided?"#define FLIP_SIDED":"",E.shadowMapEnabled?"#define USE_SHADOWMAP":"",E.shadowMapEnabled?"#define "+U:"",E.sizeAttenuation?"#define USE_SIZEATTENUATION":"",E.numLightProbes>0?"#define USE_LIGHT_PROBES":"",E.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",E.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif",` -`].filter(tC).join(` -`),Z=[MN(E),"#define SHADER_TYPE "+E.shaderType,"#define SHADER_NAME "+E.shaderName,$,E.useFog&&E.fog?"#define USE_FOG":"",E.useFog&&E.fogExp2?"#define FOG_EXP2":"",E.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",E.map?"#define USE_MAP":"",E.matcap?"#define USE_MATCAP":"",E.envMap?"#define USE_ENVMAP":"",E.envMap?"#define "+Y:"",E.envMap?"#define "+H:"",E.envMap?"#define "+R:"",O?"#define CUBEUV_TEXEL_WIDTH "+O.texelWidth:"",O?"#define CUBEUV_TEXEL_HEIGHT "+O.texelHeight:"",O?"#define CUBEUV_MAX_MIP "+O.maxMip+".0":"",E.lightMap?"#define USE_LIGHTMAP":"",E.aoMap?"#define USE_AOMAP":"",E.bumpMap?"#define USE_BUMPMAP":"",E.normalMap?"#define USE_NORMALMAP":"",E.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",E.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",E.emissiveMap?"#define USE_EMISSIVEMAP":"",E.anisotropy?"#define USE_ANISOTROPY":"",E.anisotropyMap?"#define USE_ANISOTROPYMAP":"",E.clearcoat?"#define USE_CLEARCOAT":"",E.clearcoatMap?"#define USE_CLEARCOATMAP":"",E.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",E.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",E.dispersion?"#define USE_DISPERSION":"",E.iridescence?"#define USE_IRIDESCENCE":"",E.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",E.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",E.specularMap?"#define USE_SPECULARMAP":"",E.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",E.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",E.roughnessMap?"#define USE_ROUGHNESSMAP":"",E.metalnessMap?"#define USE_METALNESSMAP":"",E.alphaMap?"#define USE_ALPHAMAP":"",E.alphaTest?"#define USE_ALPHATEST":"",E.alphaHash?"#define USE_ALPHAHASH":"",E.sheen?"#define USE_SHEEN":"",E.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",E.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",E.transmission?"#define USE_TRANSMISSION":"",E.transmissionMap?"#define USE_TRANSMISSIONMAP":"",E.thicknessMap?"#define USE_THICKNESSMAP":"",E.vertexTangents&&E.flatShading===!1?"#define USE_TANGENT":"",E.vertexColors||E.instancingColor||E.batchingColor?"#define USE_COLOR":"",E.vertexAlphas?"#define USE_COLOR_ALPHA":"",E.vertexUv1s?"#define USE_UV1":"",E.vertexUv2s?"#define USE_UV2":"",E.vertexUv3s?"#define USE_UV3":"",E.pointsUvs?"#define USE_POINTS_UV":"",E.gradientMap?"#define USE_GRADIENTMAP":"",E.flatShading?"#define FLAT_SHADED":"",E.doubleSided?"#define DOUBLE_SIDED":"",E.flipSided?"#define FLIP_SIDED":"",E.shadowMapEnabled?"#define USE_SHADOWMAP":"",E.shadowMapEnabled?"#define "+U:"",E.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",E.numLightProbes>0?"#define USE_LIGHT_PROBES":"",E.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",E.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",E.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",E.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",E.toneMapping!==VB?"#define TONE_MAPPING":"",E.toneMapping!==VB?G0.tonemapping_pars_fragment:"",E.toneMapping!==VB?JM("toneMapping",E.toneMapping):"",E.dithering?"#define DITHERING":"",E.opaque?"#define OPAQUE":"",G0.colorspace_pars_fragment,KM("linearToOutputTexel",E.outputColorSpace),UM(),E.useDepthPacking?"#define DEPTH_PACKING "+E.depthPacking:"",` -`].filter(tC).join(` -`);if(K=KH(K),K=qN(K,E),K=FN(K,E),J=KH(J),J=qN(J,E),J=FN(J,E),K=DN(K),J=DN(J),E.isRawShaderMaterial!==!0)G=`#version 300 es -`,W=[N,"#define attribute in","#define varying out","#define texture2D texture"].join(` -`)+` -`+W,Z=["#define varying in",E.glslVersion===$9?"":"layout(location = 0) out highp vec4 pc_fragColor;",E.glslVersion===$9?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(` -`)+` -`+Z;let X=G+W+K,q=G+Z+J,M=XN(I,I.VERTEX_SHADER,X),F=XN(I,I.FRAGMENT_SHADER,q);if(I.attachShader(L,M),I.attachShader(L,F),E.index0AttributeName!==void 0)I.bindAttribLocation(L,0,E.index0AttributeName);else if(E.morphTargets===!0)I.bindAttribLocation(L,0,"position");I.linkProgram(L);function D(T){if(A.debug.checkShaderErrors){let z=I.getProgramInfoLog(L).trim(),j=I.getShaderInfoLog(M).trim(),v=I.getShaderInfoLog(F).trim(),g=!0,P=!0;if(I.getProgramParameter(L,I.LINK_STATUS)===!1)if(g=!1,typeof A.debug.onShaderError==="function")A.debug.onShaderError(I,L,M,F);else{let V=LN(I,M,"vertex"),S=LN(I,F,"fragment");console.error("THREE.WebGLProgram: Shader Error "+I.getError()+" - VALIDATE_STATUS "+I.getProgramParameter(L,I.VALIDATE_STATUS)+` - -Material Name: `+T.name+` -Material Type: `+T.type+` - -Program Info Log: `+z+` -`+V+` -`+S)}else if(z!=="")console.warn("THREE.WebGLProgram: Program Info Log:",z);else if(j===""||v==="")P=!1;if(P)T.diagnostics={runnable:g,programLog:z,vertexShader:{log:j,prefix:W},fragmentShader:{log:v,prefix:Z}}}I.deleteShader(M),I.deleteShader(F),_=new eC(I,L),w=HM(I,L)}let _;this.getUniforms=function(){if(_===void 0)D(this);return _};let w;this.getAttributes=function(){if(w===void 0)D(this);return w};let k=E.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){if(k===!1)k=I.getProgramParameter(L,EM);return k},this.destroy=function(){B.releaseStatesOfProgram(this),I.deleteProgram(L),this.program=void 0},this.type=E.shaderType,this.name=E.shaderName,this.id=BM++,this.cacheKey=Q,this.usedTimes=1,this.program=L,this.vertexShader=M,this.fragmentShader=F,this}var MM=0;class yN{constructor(){this.shaderCache=/*@__PURE__*/new Map,this.materialCache=/*@__PURE__*/new Map}update(A){let{vertexShader:Q,fragmentShader:E}=A,B=this._getShaderStage(Q),I=this._getShaderStage(E),C=this._getShaderCacheForMaterial(A);if(C.has(B)===!1)C.add(B),B.usedTimes++;if(C.has(I)===!1)C.add(I),I.usedTimes++;return this}remove(A){let Q=this.materialCache.get(A);for(let E of Q)if(E.usedTimes--,E.usedTimes===0)this.shaderCache.delete(E.code);return this.materialCache.delete(A),this}getVertexShaderID(A){return this._getShaderStage(A.vertexShader).id}getFragmentShaderID(A){return this._getShaderStage(A.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(A){let Q=this.materialCache,E=Q.get(A);if(E===void 0)E=/*@__PURE__*/new Set,Q.set(A,E);return E}_getShaderStage(A){let Q=this.shaderCache,E=Q.get(A);if(E===void 0)E=new gN(A),Q.set(A,E);return E}}class gN{constructor(A){this.id=MM++,this.code=A,this.usedTimes=0}}function wM(A,Q,E,B,I,C,K){let J=new j1,U=new yN,Y=/*@__PURE__*/new Set,H=[],R=I.logarithmicDepthBuffer,O=I.vertexTextures,N=I.precision,$={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function L(w){if(Y.add(w),w===0)return"uv";return`uv${w}`}function W(w,k,T,z,j){let v=z.fog,g=j.geometry,P=w.isMeshStandardMaterial?z.environment:null,V=(w.isMeshStandardMaterial?E:Q).get(w.envMap||P),S=!!V&&V.mapping===V8?V.image.height:null,h=$[w.type];if(w.precision!==null){if(N=I.getMaxPrecision(w.precision),N!==w.precision)console.warn("THREE.WebGLProgram.getParameters:",w.precision,"not supported, using",N,"instead.")}let x=g.morphAttributes.position||g.morphAttributes.normal||g.morphAttributes.color,b=x!==void 0?x.length:0,m=0;if(g.morphAttributes.position!==void 0)m=1;if(g.morphAttributes.normal!==void 0)m=2;if(g.morphAttributes.color!==void 0)m=3;let s,i,n,l;if(h){let d0=CE[h];s=d0.vertexShader,i=d0.fragmentShader}else s=w.vertexShader,i=w.fragmentShader,U.update(w),n=U.getVertexShaderID(w),l=U.getFragmentShaderID(w);let c=A.getRenderTarget(),o=A.state.buffers.depth.getReversed(),e=j.isInstancedMesh===!0,BA=j.isBatchedMesh===!0,EA=!!w.map,CA=!!w.matcap,f=!!V,NA=!!w.aoMap,YA=!!w.lightMap,FA=!!w.bumpMap,ZA=!!w.normalMap,jA=!!w.displacementMap,wA=!!w.emissiveMap,VA=!!w.metalnessMap,d=!!w.roughnessMap,u=w.anisotropy>0,QA=w.clearcoat>0,t=w.dispersion>0,KA=w.iridescence>0,HA=w.sheen>0,fA=w.transmission>0,zA=u&&!!w.anisotropyMap,yA=QA&&!!w.clearcoatMap,qA=QA&&!!w.clearcoatNormalMap,LA=QA&&!!w.clearcoatRoughnessMap,_A=KA&&!!w.iridescenceMap,B0=KA&&!!w.iridescenceThicknessMap,cA=HA&&!!w.sheenColorMap,uA=HA&&!!w.sheenRoughnessMap,pA=!!w.specularMap,iA=!!w.specularColorMap,$0=!!w.specularIntensityMap,IA=fA&&!!w.transmissionMap,TA=fA&&!!w.thicknessMap,DA=!!w.gradientMap,kA=!!w.alphaMap,lA=w.alphaTest>0,dA=!!w.alphaHash,F0=!!w.extensions,HQ=VB;if(w.toneMapped){if(c===null||c.isXRRenderTarget===!0)HQ=A.toneMapping}let gQ={shaderID:h,shaderType:w.type,shaderName:w.name,vertexShader:s,fragmentShader:i,defines:w.defines,customVertexShaderID:n,customFragmentShaderID:l,isRawShaderMaterial:w.isRawShaderMaterial===!0,glslVersion:w.glslVersion,precision:N,batching:BA,batchingColor:BA&&j._colorsTexture!==null,instancing:e,instancingColor:e&&j.instanceColor!==null,instancingMorph:e&&j.morphTexture!==null,supportsVertexTextures:O,outputColorSpace:c===null?A.outputColorSpace:c.isXRRenderTarget===!0?c.texture.colorSpace:b0,alphaToCoverage:!!w.alphaToCoverage,map:EA,matcap:CA,envMap:f,envMapMode:f&&V.mapping,envMapCubeUVHeight:S,aoMap:NA,lightMap:YA,bumpMap:FA,normalMap:ZA,displacementMap:O&&jA,emissiveMap:wA,normalMapObjectSpace:ZA&&w.normalMapType===JO,normalMapTangentSpace:ZA&&w.normalMapType===KO,metalnessMap:VA,roughnessMap:d,anisotropy:u,anisotropyMap:zA,clearcoat:QA,clearcoatMap:yA,clearcoatNormalMap:qA,clearcoatRoughnessMap:LA,dispersion:t,iridescence:KA,iridescenceMap:_A,iridescenceThicknessMap:B0,sheen:HA,sheenColorMap:cA,sheenRoughnessMap:uA,specularMap:pA,specularColorMap:iA,specularIntensityMap:$0,transmission:fA,transmissionMap:IA,thicknessMap:TA,gradientMap:DA,opaque:w.transparent===!1&&w.blending===zB&&w.alphaToCoverage===!1,alphaMap:kA,alphaTest:lA,alphaHash:dA,combine:w.combine,mapUv:EA&&L(w.map.channel),aoMapUv:NA&&L(w.aoMap.channel),lightMapUv:YA&&L(w.lightMap.channel),bumpMapUv:FA&&L(w.bumpMap.channel),normalMapUv:ZA&&L(w.normalMap.channel),displacementMapUv:jA&&L(w.displacementMap.channel),emissiveMapUv:wA&&L(w.emissiveMap.channel),metalnessMapUv:VA&&L(w.metalnessMap.channel),roughnessMapUv:d&&L(w.roughnessMap.channel),anisotropyMapUv:zA&&L(w.anisotropyMap.channel),clearcoatMapUv:yA&&L(w.clearcoatMap.channel),clearcoatNormalMapUv:qA&&L(w.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:LA&&L(w.clearcoatRoughnessMap.channel),iridescenceMapUv:_A&&L(w.iridescenceMap.channel),iridescenceThicknessMapUv:B0&&L(w.iridescenceThicknessMap.channel),sheenColorMapUv:cA&&L(w.sheenColorMap.channel),sheenRoughnessMapUv:uA&&L(w.sheenRoughnessMap.channel),specularMapUv:pA&&L(w.specularMap.channel),specularColorMapUv:iA&&L(w.specularColorMap.channel),specularIntensityMapUv:$0&&L(w.specularIntensityMap.channel),transmissionMapUv:IA&&L(w.transmissionMap.channel),thicknessMapUv:TA&&L(w.thicknessMap.channel),alphaMapUv:kA&&L(w.alphaMap.channel),vertexTangents:!!g.attributes.tangent&&(ZA||u),vertexColors:w.vertexColors,vertexAlphas:w.vertexColors===!0&&!!g.attributes.color&&g.attributes.color.itemSize===4,pointsUvs:j.isPoints===!0&&!!g.attributes.uv&&(EA||kA),fog:!!v,useFog:w.fog===!0,fogExp2:!!v&&v.isFogExp2,flatShading:w.flatShading===!0,sizeAttenuation:w.sizeAttenuation===!0,logarithmicDepthBuffer:R,reverseDepthBuffer:o,skinning:j.isSkinnedMesh===!0,morphTargets:g.morphAttributes.position!==void 0,morphNormals:g.morphAttributes.normal!==void 0,morphColors:g.morphAttributes.color!==void 0,morphTargetsCount:b,morphTextureStride:m,numDirLights:k.directional.length,numPointLights:k.point.length,numSpotLights:k.spot.length,numSpotLightMaps:k.spotLightMap.length,numRectAreaLights:k.rectArea.length,numHemiLights:k.hemi.length,numDirLightShadows:k.directionalShadowMap.length,numPointLightShadows:k.pointShadowMap.length,numSpotLightShadows:k.spotShadowMap.length,numSpotLightShadowsWithMaps:k.numSpotLightShadowsWithMaps,numLightProbes:k.numLightProbes,numClippingPlanes:K.numPlanes,numClipIntersection:K.numIntersection,dithering:w.dithering,shadowMapEnabled:A.shadowMap.enabled&&T.length>0,shadowMapType:A.shadowMap.type,toneMapping:HQ,decodeVideoTexture:EA&&w.map.isVideoTexture===!0&&O0.getTransfer(w.map.colorSpace)===IQ,decodeVideoTextureEmissive:wA&&w.emissiveMap.isVideoTexture===!0&&O0.getTransfer(w.emissiveMap.colorSpace)===IQ,premultipliedAlpha:w.premultipliedAlpha,doubleSided:w.side===y0,flipSided:w.side===ZQ,useDepthPacking:w.depthPacking>=0,depthPacking:w.depthPacking||0,index0AttributeName:w.index0AttributeName,extensionClipCullDistance:F0&&w.extensions.clipCullDistance===!0&&B.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(F0&&w.extensions.multiDraw===!0||BA)&&B.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:B.has("KHR_parallel_shader_compile"),customProgramCacheKey:w.customProgramCacheKey()};return gQ.vertexUv1s=Y.has(1),gQ.vertexUv2s=Y.has(2),gQ.vertexUv3s=Y.has(3),Y.clear(),gQ}function Z(w){let k=[];if(w.shaderID)k.push(w.shaderID);else k.push(w.customVertexShaderID),k.push(w.customFragmentShaderID);if(w.defines!==void 0)for(let T in w.defines)k.push(T),k.push(w.defines[T]);if(w.isRawShaderMaterial===!1)G(k,w),X(k,w),k.push(A.outputColorSpace);return k.push(w.customProgramCacheKey),k.join()}function G(w,k){w.push(k.precision),w.push(k.outputColorSpace),w.push(k.envMapMode),w.push(k.envMapCubeUVHeight),w.push(k.mapUv),w.push(k.alphaMapUv),w.push(k.lightMapUv),w.push(k.aoMapUv),w.push(k.bumpMapUv),w.push(k.normalMapUv),w.push(k.displacementMapUv),w.push(k.emissiveMapUv),w.push(k.metalnessMapUv),w.push(k.roughnessMapUv),w.push(k.anisotropyMapUv),w.push(k.clearcoatMapUv),w.push(k.clearcoatNormalMapUv),w.push(k.clearcoatRoughnessMapUv),w.push(k.iridescenceMapUv),w.push(k.iridescenceThicknessMapUv),w.push(k.sheenColorMapUv),w.push(k.sheenRoughnessMapUv),w.push(k.specularMapUv),w.push(k.specularColorMapUv),w.push(k.specularIntensityMapUv),w.push(k.transmissionMapUv),w.push(k.thicknessMapUv),w.push(k.combine),w.push(k.fogExp2),w.push(k.sizeAttenuation),w.push(k.morphTargetsCount),w.push(k.morphAttributeCount),w.push(k.numDirLights),w.push(k.numPointLights),w.push(k.numSpotLights),w.push(k.numSpotLightMaps),w.push(k.numHemiLights),w.push(k.numRectAreaLights),w.push(k.numDirLightShadows),w.push(k.numPointLightShadows),w.push(k.numSpotLightShadows),w.push(k.numSpotLightShadowsWithMaps),w.push(k.numLightProbes),w.push(k.shadowMapType),w.push(k.toneMapping),w.push(k.numClippingPlanes),w.push(k.numClipIntersection),w.push(k.depthPacking)}function X(w,k){if(J.disableAll(),k.supportsVertexTextures)J.enable(0);if(k.instancing)J.enable(1);if(k.instancingColor)J.enable(2);if(k.instancingMorph)J.enable(3);if(k.matcap)J.enable(4);if(k.envMap)J.enable(5);if(k.normalMapObjectSpace)J.enable(6);if(k.normalMapTangentSpace)J.enable(7);if(k.clearcoat)J.enable(8);if(k.iridescence)J.enable(9);if(k.alphaTest)J.enable(10);if(k.vertexColors)J.enable(11);if(k.vertexAlphas)J.enable(12);if(k.vertexUv1s)J.enable(13);if(k.vertexUv2s)J.enable(14);if(k.vertexUv3s)J.enable(15);if(k.vertexTangents)J.enable(16);if(k.anisotropy)J.enable(17);if(k.alphaHash)J.enable(18);if(k.batching)J.enable(19);if(k.dispersion)J.enable(20);if(k.batchingColor)J.enable(21);if(w.push(J.mask),J.disableAll(),k.fog)J.enable(0);if(k.useFog)J.enable(1);if(k.flatShading)J.enable(2);if(k.logarithmicDepthBuffer)J.enable(3);if(k.reverseDepthBuffer)J.enable(4);if(k.skinning)J.enable(5);if(k.morphTargets)J.enable(6);if(k.morphNormals)J.enable(7);if(k.morphColors)J.enable(8);if(k.premultipliedAlpha)J.enable(9);if(k.shadowMapEnabled)J.enable(10);if(k.doubleSided)J.enable(11);if(k.flipSided)J.enable(12);if(k.useDepthPacking)J.enable(13);if(k.dithering)J.enable(14);if(k.transmission)J.enable(15);if(k.sheen)J.enable(16);if(k.opaque)J.enable(17);if(k.pointsUvs)J.enable(18);if(k.decodeVideoTexture)J.enable(19);if(k.decodeVideoTextureEmissive)J.enable(20);if(k.alphaToCoverage)J.enable(21);w.push(J.mask)}function q(w){let k=$[w.type],T;if(k){let z=CE[k];T=oA.clone(z.uniforms)}else T=w.uniforms;return T}function M(w,k){let T;for(let z=0,j=H.length;z0)B.push(Z);else if(N.transparent===!0)I.push(Z);else E.push(Z)}function U(R,O,N,$,L,W){let Z=K(R,O,N,$,L,W);if(N.transmission>0)B.unshift(Z);else if(N.transparent===!0)I.unshift(Z);else E.unshift(Z)}function Y(R,O){if(E.length>1)E.sort(R||kM);if(B.length>1)B.sort(O||wN);if(I.length>1)I.sort(O||wN)}function H(){for(let R=Q,O=A.length;R=C.length)K=new _N,C.push(K);else K=C[I];return K}function E(){A=/*@__PURE__*/new WeakMap}return{get:Q,dispose:E}}function TM(){let A={};return{get:function(Q){if(A[Q.id]!==void 0)return A[Q.id];let E;switch(Q.type){case"DirectionalLight":E={direction:new y,color:new a};break;case"SpotLight":E={position:new y,direction:new y,color:new a,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":E={position:new y,color:new a,distance:0,decay:0};break;case"HemisphereLight":E={direction:new y,skyColor:new a,groundColor:new a};break;case"RectAreaLight":E={color:new a,position:new y,halfWidth:new y,halfHeight:new y};break}return A[Q.id]=E,E}}}function zM(){let A={};return{get:function(Q){if(A[Q.id]!==void 0)return A[Q.id];let E;switch(Q.type){case"DirectionalLight":E={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new AA};break;case"SpotLight":E={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new AA};break;case"PointLight":E={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new AA,shadowCameraNear:1,shadowCameraFar:1000};break}return A[Q.id]=E,E}}}var PM=0;function VM(A,Q){return(Q.castShadow?2:0)-(A.castShadow?2:0)+(Q.map?1:0)-(A.map?1:0)}function jM(A){let Q=new TM,E=zM(),B={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let Y=0;Y<9;Y++)B.probe.push(new y);let I=new y,C=new RA,K=new RA;function J(Y){let H=0,R=0,O=0;for(let w=0;w<9;w++)B.probe[w].set(0,0,0);let N=0,$=0,L=0,W=0,Z=0,G=0,X=0,q=0,M=0,F=0,D=0;Y.sort(VM);for(let w=0,k=Y.length;w0)if(A.has("OES_texture_float_linear")===!0)B.rectAreaLTC1=vA.LTC_FLOAT_1,B.rectAreaLTC2=vA.LTC_FLOAT_2;else B.rectAreaLTC1=vA.LTC_HALF_1,B.rectAreaLTC2=vA.LTC_HALF_2;B.ambient[0]=H,B.ambient[1]=R,B.ambient[2]=O;let _=B.hash;if(_.directionalLength!==N||_.pointLength!==$||_.spotLength!==L||_.rectAreaLength!==W||_.hemiLength!==Z||_.numDirectionalShadows!==G||_.numPointShadows!==X||_.numSpotShadows!==q||_.numSpotMaps!==M||_.numLightProbes!==D)B.directional.length=N,B.spot.length=L,B.rectArea.length=W,B.point.length=$,B.hemi.length=Z,B.directionalShadow.length=G,B.directionalShadowMap.length=G,B.pointShadow.length=X,B.pointShadowMap.length=X,B.spotShadow.length=q,B.spotShadowMap.length=q,B.directionalShadowMatrix.length=G,B.pointShadowMatrix.length=X,B.spotLightMatrix.length=q+M-F,B.spotLightMap.length=M,B.numSpotLightShadowsWithMaps=F,B.numLightProbes=D,_.directionalLength=N,_.pointLength=$,_.spotLength=L,_.rectAreaLength=W,_.hemiLength=Z,_.numDirectionalShadows=G,_.numPointShadows=X,_.numSpotShadows=q,_.numSpotMaps=M,_.numLightProbes=D,B.version=PM++}function U(Y,H){let R=0,O=0,N=0,$=0,L=0,W=H.matrixWorldInverse;for(let Z=0,G=Y.length;Z=K.length)J=new kN(A),K.push(J);else J=K[C];return J}function B(){Q=/*@__PURE__*/new WeakMap}return{get:E,dispose:B}}var hM=`void main() { - gl_Position = vec4( position, 1.0 ); -}`,yM=`uniform sampler2D shadow_pass; -uniform vec2 resolution; -uniform float radius; -#include -void main() { - const float samples = float( VSM_SAMPLES ); - float mean = 0.0; - float squared_mean = 0.0; - float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); - float uvStart = samples <= 1.0 ? 0.0 : - 1.0; - for ( float i = 0.0; i < samples; i ++ ) { - float uvOffset = uvStart + i * uvStride; - #ifdef HORIZONTAL_PASS - vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); - mean += distribution.x; - squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; - #else - float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); - mean += depth; - squared_mean += depth * depth; - #endif - } - mean = mean / samples; - squared_mean = squared_mean / samples; - float std_dev = sqrt( squared_mean - mean * mean ); - gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); -}`;function gM(A,Q,E){let B=new xB,I=new AA,C=new AA,K=new MA,J=new hI({depthPacking:b8}),U=new pC,Y={},H=E.maxTextureSize,R={[jQ]:ZQ,[ZQ]:jQ,[y0]:y0},O=new bA({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new AA},radius:{value:4}},vertexShader:hM,fragmentShader:yM}),N=O.clone();N.defines.HORIZONTAL_PASS=1;let $=new hA;$.setAttribute("position",new tA(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));let L=new xA($,O),W=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=fJ;let Z=this.type;this.render=function(F,D,_){if(W.enabled===!1)return;if(W.autoUpdate===!1&&W.needsUpdate===!1)return;if(F.length===0)return;let w=A.getRenderTarget(),k=A.getActiveCubeFace(),T=A.getActiveMipmapLevel(),z=A.state;z.setBlending(H0),z.buffers.color.setClear(1,1,1,1),z.buffers.depth.setTest(!0),z.setScissorTest(!1);let j=Z!==RB&&this.type===RB,v=Z===RB&&this.type!==RB;for(let g=0,P=F.length;gH||I.y>H){if(I.x>H)C.x=Math.floor(H/h.x),I.x=C.x*h.x,S.mapSize.x=C.x;if(I.y>H)C.y=Math.floor(H/h.y),I.y=C.y*h.y,S.mapSize.y=C.y}if(S.map===null||j===!0||v===!0){let b=this.type!==RB?{minFilter:Z0,magFilter:Z0}:{};if(S.map!==null)S.map.dispose();S.map=new Q0(I.x,I.y,b),S.map.texture.name=V.name+".shadowMap",S.camera.updateProjectionMatrix()}A.setRenderTarget(S.map),A.clear();let x=S.getViewportCount();for(let b=0;b0||D.map&&D.alphaTest>0){let z=k.uuid,j=D.uuid,v=Y[z];if(v===void 0)v={},Y[z]=v;let g=v[j];if(g===void 0)g=k.clone(),v[j]=g,D.addEventListener("dispose",M);k=g}if(k.visible=D.visible,k.wireframe=D.wireframe,w===RB)k.side=D.shadowSide!==null?D.shadowSide:D.side;else k.side=D.shadowSide!==null?D.shadowSide:R[D.side];if(k.alphaMap=D.alphaMap,k.alphaTest=D.alphaTest,k.map=D.map,k.clipShadows=D.clipShadows,k.clippingPlanes=D.clippingPlanes,k.clipIntersection=D.clipIntersection,k.displacementMap=D.displacementMap,k.displacementScale=D.displacementScale,k.displacementBias=D.displacementBias,k.wireframeLinewidth=D.wireframeLinewidth,k.linewidth=D.linewidth,_.isPointLight===!0&&k.isMeshDistanceMaterial===!0){let z=A.properties.get(k);z.light=_}return k}function q(F,D,_,w,k){if(F.visible===!1)return;if(F.layers.test(D.layers)&&(F.isMesh||F.isLine||F.isPoints)){if((F.castShadow||F.receiveShadow&&k===RB)&&(!F.frustumCulled||B.intersectsObject(F))){F.modelViewMatrix.multiplyMatrices(_.matrixWorldInverse,F.matrixWorld);let j=Q.update(F),v=F.material;if(Array.isArray(v)){let g=j.groups;for(let P=0,V=g.length;P=1;else if(S.indexOf("OpenGL ES")!==-1)V=parseFloat(/^OpenGL ES (\d)/.exec(S)[1]),P=V>=2;let h=null,x={},b=A.getParameter(A.SCISSOR_BOX),m=A.getParameter(A.VIEWPORT),s=new MA().fromArray(b),i=new MA().fromArray(m);function n(IA,TA,DA,kA){let lA=new Uint8Array(4),dA=A.createTexture();A.bindTexture(IA,dA),A.texParameteri(IA,A.TEXTURE_MIN_FILTER,A.NEAREST),A.texParameteri(IA,A.TEXTURE_MAG_FILTER,A.NEAREST);for(let F0=0;F0QA||KA.height>QA)t=QA/Math.max(KA.width,KA.height);if(t<1)if(typeof HTMLImageElement!=="undefined"&&d instanceof HTMLImageElement||typeof HTMLCanvasElement!=="undefined"&&d instanceof HTMLCanvasElement||typeof ImageBitmap!=="undefined"&&d instanceof ImageBitmap||typeof VideoFrame!=="undefined"&&d instanceof VideoFrame){let HA=Math.floor(t*KA.width),fA=Math.floor(t*KA.height);if(R===void 0)R=$(HA,fA);let zA=u?$(HA,fA):R;return zA.width=HA,zA.height=fA,zA.getContext("2d").drawImage(d,0,0,HA,fA),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+KA.width+"x"+KA.height+") to ("+HA+"x"+fA+")."),zA}else{if("data"in d)console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+KA.width+"x"+KA.height+").");return d}return d}function W(d){return d.generateMipmaps}function Z(d){A.generateMipmap(d)}function G(d){if(d.isWebGLCubeRenderTarget)return A.TEXTURE_CUBE_MAP;if(d.isWebGL3DRenderTarget)return A.TEXTURE_3D;if(d.isWebGLArrayRenderTarget||d.isCompressedArrayTexture)return A.TEXTURE_2D_ARRAY;return A.TEXTURE_2D}function X(d,u,QA,t,KA=!1){if(d!==null){if(A[d]!==void 0)return A[d];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+d+"'")}let HA=u;if(u===A.RED){if(QA===A.FLOAT)HA=A.R32F;if(QA===A.HALF_FLOAT)HA=A.R16F;if(QA===A.UNSIGNED_BYTE)HA=A.R8}if(u===A.RED_INTEGER){if(QA===A.UNSIGNED_BYTE)HA=A.R8UI;if(QA===A.UNSIGNED_SHORT)HA=A.R16UI;if(QA===A.UNSIGNED_INT)HA=A.R32UI;if(QA===A.BYTE)HA=A.R8I;if(QA===A.SHORT)HA=A.R16I;if(QA===A.INT)HA=A.R32I}if(u===A.RG){if(QA===A.FLOAT)HA=A.RG32F;if(QA===A.HALF_FLOAT)HA=A.RG16F;if(QA===A.UNSIGNED_BYTE)HA=A.RG8}if(u===A.RG_INTEGER){if(QA===A.UNSIGNED_BYTE)HA=A.RG8UI;if(QA===A.UNSIGNED_SHORT)HA=A.RG16UI;if(QA===A.UNSIGNED_INT)HA=A.RG32UI;if(QA===A.BYTE)HA=A.RG8I;if(QA===A.SHORT)HA=A.RG16I;if(QA===A.INT)HA=A.RG32I}if(u===A.RGB_INTEGER){if(QA===A.UNSIGNED_BYTE)HA=A.RGB8UI;if(QA===A.UNSIGNED_SHORT)HA=A.RGB16UI;if(QA===A.UNSIGNED_INT)HA=A.RGB32UI;if(QA===A.BYTE)HA=A.RGB8I;if(QA===A.SHORT)HA=A.RGB16I;if(QA===A.INT)HA=A.RGB32I}if(u===A.RGBA_INTEGER){if(QA===A.UNSIGNED_BYTE)HA=A.RGBA8UI;if(QA===A.UNSIGNED_SHORT)HA=A.RGBA16UI;if(QA===A.UNSIGNED_INT)HA=A.RGBA32UI;if(QA===A.BYTE)HA=A.RGBA8I;if(QA===A.SHORT)HA=A.RGBA16I;if(QA===A.INT)HA=A.RGBA32I}if(u===A.RGB){if(QA===A.UNSIGNED_INT_5_9_9_9_REV)HA=A.RGB9_E5}if(u===A.RGBA){let fA=KA?LC:O0.getTransfer(t);if(QA===A.FLOAT)HA=A.RGBA32F;if(QA===A.HALF_FLOAT)HA=A.RGBA16F;if(QA===A.UNSIGNED_BYTE)HA=fA===IQ?A.SRGB8_ALPHA8:A.RGBA8;if(QA===A.UNSIGNED_SHORT_4_4_4_4)HA=A.RGBA4;if(QA===A.UNSIGNED_SHORT_5_5_5_1)HA=A.RGB5_A1}if(HA===A.R16F||HA===A.R32F||HA===A.RG16F||HA===A.RG32F||HA===A.RGBA16F||HA===A.RGBA32F)Q.get("EXT_color_buffer_float");return HA}function q(d,u){let QA;if(d){if(u===null||u===$1||u===VE)QA=A.DEPTH24_STENCIL8;else if(u===m0)QA=A.DEPTH32F_STENCIL8;else if(u===hB)QA=A.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")}else if(u===null||u===$1||u===VE)QA=A.DEPTH_COMPONENT24;else if(u===m0)QA=A.DEPTH_COMPONENT32F;else if(u===hB)QA=A.DEPTH_COMPONENT16;return QA}function M(d,u){if(W(d)===!0||d.isFramebufferTexture&&d.minFilter!==Z0&&d.minFilter!==L0)return Math.log2(Math.max(u.width,u.height))+1;else if(d.mipmaps!==void 0&&d.mipmaps.length>0)return d.mipmaps.length;else if(d.isCompressedTexture&&Array.isArray(d.image))return u.mipmaps.length;else return 1}function F(d){let u=d.target;if(u.removeEventListener("dispose",F),_(u),u.isVideoTexture)H.delete(u)}function D(d){let u=d.target;u.removeEventListener("dispose",D),k(u)}function _(d){let u=B.get(d);if(u.__webglInit===void 0)return;let QA=d.source,t=O.get(QA);if(t){let KA=t[u.__cacheKey];if(KA.usedTimes--,KA.usedTimes===0)w(d);if(Object.keys(t).length===0)O.delete(QA)}B.remove(d)}function w(d){let u=B.get(d);A.deleteTexture(u.__webglTexture);let QA=d.source,t=O.get(QA);delete t[u.__cacheKey],K.memory.textures--}function k(d){let u=B.get(d);if(d.depthTexture)d.depthTexture.dispose(),B.remove(d.depthTexture);if(d.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(u.__webglFramebuffer[t]))for(let KA=0;KA=I.maxTextures)console.warn("THREE.WebGLTextures: Trying to use "+d+" texture units while this GPU supports only "+I.maxTextures);return T+=1,d}function v(d){let u=[];return u.push(d.wrapS),u.push(d.wrapT),u.push(d.wrapR||0),u.push(d.magFilter),u.push(d.minFilter),u.push(d.anisotropy),u.push(d.internalFormat),u.push(d.format),u.push(d.type),u.push(d.generateMipmaps),u.push(d.premultiplyAlpha),u.push(d.flipY),u.push(d.unpackAlignment),u.push(d.colorSpace),u.join()}function g(d,u){let QA=B.get(d);if(d.isVideoTexture)jA(d);if(d.isRenderTargetTexture===!1&&d.version>0&&QA.__version!==d.version){let t=d.image;if(t===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(t.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{i(QA,d,u);return}}E.bindTexture(A.TEXTURE_2D,QA.__webglTexture,A.TEXTURE0+u)}function P(d,u){let QA=B.get(d);if(d.version>0&&QA.__version!==d.version){i(QA,d,u);return}E.bindTexture(A.TEXTURE_2D_ARRAY,QA.__webglTexture,A.TEXTURE0+u)}function V(d,u){let QA=B.get(d);if(d.version>0&&QA.__version!==d.version){i(QA,d,u);return}E.bindTexture(A.TEXTURE_3D,QA.__webglTexture,A.TEXTURE0+u)}function S(d,u){let QA=B.get(d);if(d.version>0&&QA.__version!==d.version){n(QA,d,u);return}E.bindTexture(A.TEXTURE_CUBE_MAP,QA.__webglTexture,A.TEXTURE0+u)}let h={[BQ]:A.REPEAT,[JQ]:A.CLAMP_TO_EDGE,[OE]:A.MIRRORED_REPEAT},x={[Z0]:A.NEAREST,[X1]:A.NEAREST_MIPMAP_NEAREST,[vB]:A.NEAREST_MIPMAP_LINEAR,[L0]:A.LINEAR,[AI]:A.LINEAR_MIPMAP_NEAREST,[hQ]:A.LINEAR_MIPMAP_LINEAR},b={[OO]:A.NEVER,[WO]:A.ALWAYS,[HO]:A.LESS,[X9]:A.LEQUAL,[ZO]:A.EQUAL,[GO]:A.GEQUAL,[RO]:A.GREATER,[NO]:A.NOTEQUAL};function m(d,u){if(u.type===m0&&Q.has("OES_texture_float_linear")===!1&&(u.magFilter===L0||u.magFilter===AI||u.magFilter===vB||u.magFilter===hQ||u.minFilter===L0||u.minFilter===AI||u.minFilter===vB||u.minFilter===hQ))console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.");if(A.texParameteri(d,A.TEXTURE_WRAP_S,h[u.wrapS]),A.texParameteri(d,A.TEXTURE_WRAP_T,h[u.wrapT]),d===A.TEXTURE_3D||d===A.TEXTURE_2D_ARRAY)A.texParameteri(d,A.TEXTURE_WRAP_R,h[u.wrapR]);if(A.texParameteri(d,A.TEXTURE_MAG_FILTER,x[u.magFilter]),A.texParameteri(d,A.TEXTURE_MIN_FILTER,x[u.minFilter]),u.compareFunction)A.texParameteri(d,A.TEXTURE_COMPARE_MODE,A.COMPARE_REF_TO_TEXTURE),A.texParameteri(d,A.TEXTURE_COMPARE_FUNC,b[u.compareFunction]);if(Q.has("EXT_texture_filter_anisotropic")===!0){if(u.magFilter===Z0)return;if(u.minFilter!==vB&&u.minFilter!==hQ)return;if(u.type===m0&&Q.has("OES_texture_float_linear")===!1)return;if(u.anisotropy>1||B.get(u).__currentAnisotropy){let QA=Q.get("EXT_texture_filter_anisotropic");A.texParameterf(d,QA.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(u.anisotropy,I.getMaxAnisotropy())),B.get(u).__currentAnisotropy=u.anisotropy}}}function s(d,u){let QA=!1;if(d.__webglInit===void 0)d.__webglInit=!0,u.addEventListener("dispose",F);let t=u.source,KA=O.get(t);if(KA===void 0)KA={},O.set(t,KA);let HA=v(u);if(HA!==d.__cacheKey){if(KA[HA]===void 0)KA[HA]={texture:A.createTexture(),usedTimes:0},K.memory.textures++,QA=!0;KA[HA].usedTimes++;let fA=KA[d.__cacheKey];if(fA!==void 0){if(KA[d.__cacheKey].usedTimes--,fA.usedTimes===0)w(u)}d.__cacheKey=HA,d.__webglTexture=KA[HA].texture}return QA}function i(d,u,QA){let t=A.TEXTURE_2D;if(u.isDataArrayTexture||u.isCompressedArrayTexture)t=A.TEXTURE_2D_ARRAY;if(u.isData3DTexture)t=A.TEXTURE_3D;let KA=s(d,u),HA=u.source;E.bindTexture(t,d.__webglTexture,A.TEXTURE0+QA);let fA=B.get(HA);if(HA.version!==fA.__version||KA===!0){E.activeTexture(A.TEXTURE0+QA);let zA=O0.getPrimaries(O0.workingColorSpace),yA=u.colorSpace===YQ?null:O0.getPrimaries(u.colorSpace),qA=u.colorSpace===YQ||zA===yA?A.NONE:A.BROWSER_DEFAULT_WEBGL;A.pixelStorei(A.UNPACK_FLIP_Y_WEBGL,u.flipY),A.pixelStorei(A.UNPACK_PREMULTIPLY_ALPHA_WEBGL,u.premultiplyAlpha),A.pixelStorei(A.UNPACK_ALIGNMENT,u.unpackAlignment),A.pixelStorei(A.UNPACK_COLORSPACE_CONVERSION_WEBGL,qA);let LA=L(u.image,!1,I.maxTextureSize);LA=wA(u,LA);let _A=C.convert(u.format,u.colorSpace),B0=C.convert(u.type),cA=X(u.internalFormat,_A,B0,u.colorSpace,u.isVideoTexture);m(t,u);let uA,pA=u.mipmaps,iA=u.isVideoTexture!==!0,$0=fA.__version===void 0||KA===!0,IA=HA.dataReady,TA=M(u,LA);if(u.isDepthTexture){if(cA=q(u.format===oE,u.type),$0)if(iA)E.texStorage2D(A.TEXTURE_2D,1,cA,LA.width,LA.height);else E.texImage2D(A.TEXTURE_2D,0,cA,LA.width,LA.height,0,_A,B0,null)}else if(u.isDataTexture)if(pA.length>0){if(iA&&$0)E.texStorage2D(A.TEXTURE_2D,TA,cA,pA[0].width,pA[0].height);for(let DA=0,kA=pA.length;DA0){let lA=a9(uA.width,uA.height,u.format,u.type);for(let dA of u.layerUpdates){let F0=uA.data.subarray(dA*lA/uA.data.BYTES_PER_ELEMENT,(dA+1)*lA/uA.data.BYTES_PER_ELEMENT);E.compressedTexSubImage3D(A.TEXTURE_2D_ARRAY,DA,0,0,dA,uA.width,uA.height,1,_A,F0)}u.clearLayerUpdates()}else E.compressedTexSubImage3D(A.TEXTURE_2D_ARRAY,DA,0,0,0,uA.width,uA.height,LA.depth,_A,uA.data)}else E.compressedTexImage3D(A.TEXTURE_2D_ARRAY,DA,cA,uA.width,uA.height,LA.depth,0,uA.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else if(iA){if(IA)E.texSubImage3D(A.TEXTURE_2D_ARRAY,DA,0,0,0,uA.width,uA.height,LA.depth,_A,B0,uA.data)}else E.texImage3D(A.TEXTURE_2D_ARRAY,DA,cA,uA.width,uA.height,LA.depth,0,_A,B0,uA.data)}else{if(iA&&$0)E.texStorage2D(A.TEXTURE_2D,TA,cA,pA[0].width,pA[0].height);for(let DA=0,kA=pA.length;DA0){let DA=a9(LA.width,LA.height,u.format,u.type);for(let kA of u.layerUpdates){let lA=LA.data.subarray(kA*DA/LA.data.BYTES_PER_ELEMENT,(kA+1)*DA/LA.data.BYTES_PER_ELEMENT);E.texSubImage3D(A.TEXTURE_2D_ARRAY,0,0,0,kA,LA.width,LA.height,1,_A,B0,lA)}u.clearLayerUpdates()}else E.texSubImage3D(A.TEXTURE_2D_ARRAY,0,0,0,0,LA.width,LA.height,LA.depth,_A,B0,LA.data)}else E.texImage3D(A.TEXTURE_2D_ARRAY,0,cA,LA.width,LA.height,LA.depth,0,_A,B0,LA.data);else if(u.isData3DTexture)if(iA){if($0)E.texStorage3D(A.TEXTURE_3D,TA,cA,LA.width,LA.height,LA.depth);if(IA)E.texSubImage3D(A.TEXTURE_3D,0,0,0,0,LA.width,LA.height,LA.depth,_A,B0,LA.data)}else E.texImage3D(A.TEXTURE_3D,0,cA,LA.width,LA.height,LA.depth,0,_A,B0,LA.data);else if(u.isFramebufferTexture){if($0)if(iA)E.texStorage2D(A.TEXTURE_2D,TA,cA,LA.width,LA.height);else{let{width:DA,height:kA}=LA;for(let lA=0;lA>=1,kA>>=1}}else if(pA.length>0){if(iA&&$0){let DA=VA(pA[0]);E.texStorage2D(A.TEXTURE_2D,TA,cA,DA.width,DA.height)}for(let DA=0,kA=pA.length;DA0)TA++;let kA=VA(_A[0]);E.texStorage2D(A.TEXTURE_CUBE_MAP,TA,pA,kA.width,kA.height)}for(let kA=0;kA<6;kA++)if(LA){if(iA){if(IA)E.texSubImage2D(A.TEXTURE_CUBE_MAP_POSITIVE_X+kA,0,0,0,_A[kA].width,_A[kA].height,cA,uA,_A[kA].data)}else E.texImage2D(A.TEXTURE_CUBE_MAP_POSITIVE_X+kA,0,pA,_A[kA].width,_A[kA].height,0,cA,uA,_A[kA].data);for(let lA=0;lA>HA),B0=Math.max(1,u.height>>HA);if(KA===A.TEXTURE_3D||KA===A.TEXTURE_2D_ARRAY)E.texImage3D(KA,HA,yA,_A,B0,u.depth,0,fA,zA,null);else E.texImage2D(KA,HA,yA,_A,B0,0,fA,zA,null)}if(E.bindFramebuffer(A.FRAMEBUFFER,d),ZA(u))J.framebufferTexture2DMultisampleEXT(A.FRAMEBUFFER,t,KA,LA.__webglTexture,0,FA(u));else if(KA===A.TEXTURE_2D||KA>=A.TEXTURE_CUBE_MAP_POSITIVE_X&&KA<=A.TEXTURE_CUBE_MAP_NEGATIVE_Z)A.framebufferTexture2D(A.FRAMEBUFFER,t,KA,LA.__webglTexture,HA);E.bindFramebuffer(A.FRAMEBUFFER,null)}function c(d,u,QA){if(A.bindRenderbuffer(A.RENDERBUFFER,d),u.depthBuffer){let t=u.depthTexture,KA=t&&t.isDepthTexture?t.type:null,HA=q(u.stencilBuffer,KA),fA=u.stencilBuffer?A.DEPTH_STENCIL_ATTACHMENT:A.DEPTH_ATTACHMENT,zA=FA(u);if(ZA(u))J.renderbufferStorageMultisampleEXT(A.RENDERBUFFER,zA,HA,u.width,u.height);else if(QA)A.renderbufferStorageMultisample(A.RENDERBUFFER,zA,HA,u.width,u.height);else A.renderbufferStorage(A.RENDERBUFFER,HA,u.width,u.height);A.framebufferRenderbuffer(A.FRAMEBUFFER,fA,A.RENDERBUFFER,d)}else{let t=u.textures;for(let KA=0;KA{delete u.__boundDepthTexture,delete u.__depthDisposeCallback,t.removeEventListener("dispose",KA)};t.addEventListener("dispose",KA),u.__depthDisposeCallback=KA}u.__boundDepthTexture=t}if(d.depthTexture&&!u.__autoAllocateDepthBuffer){if(QA)throw new Error("target.depthTexture not supported in Cube render targets");o(u.__webglFramebuffer,d)}else if(QA){u.__webglDepthbuffer=[];for(let t=0;t<6;t++)if(E.bindFramebuffer(A.FRAMEBUFFER,u.__webglFramebuffer[t]),u.__webglDepthbuffer[t]===void 0)u.__webglDepthbuffer[t]=A.createRenderbuffer(),c(u.__webglDepthbuffer[t],d,!1);else{let KA=d.stencilBuffer?A.DEPTH_STENCIL_ATTACHMENT:A.DEPTH_ATTACHMENT,HA=u.__webglDepthbuffer[t];A.bindRenderbuffer(A.RENDERBUFFER,HA),A.framebufferRenderbuffer(A.FRAMEBUFFER,KA,A.RENDERBUFFER,HA)}}else if(E.bindFramebuffer(A.FRAMEBUFFER,u.__webglFramebuffer),u.__webglDepthbuffer===void 0)u.__webglDepthbuffer=A.createRenderbuffer(),c(u.__webglDepthbuffer,d,!1);else{let t=d.stencilBuffer?A.DEPTH_STENCIL_ATTACHMENT:A.DEPTH_ATTACHMENT,KA=u.__webglDepthbuffer;A.bindRenderbuffer(A.RENDERBUFFER,KA),A.framebufferRenderbuffer(A.FRAMEBUFFER,t,A.RENDERBUFFER,KA)}E.bindFramebuffer(A.FRAMEBUFFER,null)}function BA(d,u,QA){let t=B.get(d);if(u!==void 0)l(t.__webglFramebuffer,d,d.texture,A.COLOR_ATTACHMENT0,A.TEXTURE_2D,0);if(QA!==void 0)e(d)}function EA(d){let u=d.texture,QA=B.get(d),t=B.get(u);d.addEventListener("dispose",D);let KA=d.textures,HA=d.isWebGLCubeRenderTarget===!0,fA=KA.length>1;if(!fA){if(t.__webglTexture===void 0)t.__webglTexture=A.createTexture();t.__version=u.version,K.memory.textures++}if(HA){QA.__webglFramebuffer=[];for(let zA=0;zA<6;zA++)if(u.mipmaps&&u.mipmaps.length>0){QA.__webglFramebuffer[zA]=[];for(let yA=0;yA0){QA.__webglFramebuffer=[];for(let zA=0;zA0&&ZA(d)===!1){QA.__webglMultisampledFramebuffer=A.createFramebuffer(),QA.__webglColorRenderbuffer=[],E.bindFramebuffer(A.FRAMEBUFFER,QA.__webglMultisampledFramebuffer);for(let zA=0;zA0)for(let yA=0;yA0)for(let yA=0;yA0){if(ZA(d)===!1){let{textures:u,width:QA,height:t}=d,KA=A.COLOR_BUFFER_BIT,HA=d.stencilBuffer?A.DEPTH_STENCIL_ATTACHMENT:A.DEPTH_ATTACHMENT,fA=B.get(d),zA=u.length>1;if(zA)for(let yA=0;yA0&&Q.has("WEBGL_multisampled_render_to_texture")===!0&&u.__useRenderToTexture!==!1}function jA(d){let u=K.render.frame;if(H.get(d)!==u)H.set(d,u),d.update()}function wA(d,u){let{colorSpace:QA,format:t,type:KA}=d;if(d.isCompressedTexture===!0||d.isVideoTexture===!0)return u;if(QA!==b0&&QA!==YQ)if(O0.getTransfer(QA)===IQ){if(t!==V0||KA!==x0)console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.")}else console.error("THREE.WebGLTextures: Unsupported texture color space:",QA);return u}function VA(d){if(typeof HTMLImageElement!=="undefined"&&d instanceof HTMLImageElement)Y.width=d.naturalWidth||d.width,Y.height=d.naturalHeight||d.height;else if(typeof VideoFrame!=="undefined"&&d instanceof VideoFrame)Y.width=d.displayWidth,Y.height=d.displayHeight;else Y.width=d.width,Y.height=d.height;return Y}this.allocateTextureUnit=j,this.resetTextureUnits=z,this.setTexture2D=g,this.setTexture2DArray=P,this.setTexture3D=V,this.setTextureCube=S,this.rebindTextures=BA,this.setupRenderTarget=EA,this.updateRenderTargetMipmap=CA,this.updateMultisampleRenderTarget=YA,this.setupDepthRenderbuffer=e,this.setupFrameBufferTexture=l,this.useMultisampledRTT=ZA}function xN(A,Q){function E(B,I=YQ){let C,K=O0.getTransfer(I);if(B===x0)return A.UNSIGNED_BYTE;if(B===tJ)return A.UNSIGNED_SHORT_4_4_4_4;if(B===eJ)return A.UNSIGNED_SHORT_5_5_5_1;if(B===EO)return A.UNSIGNED_INT_5_9_9_9_REV;if(B===AO)return A.BYTE;if(B===QO)return A.SHORT;if(B===hB)return A.UNSIGNED_SHORT;if(B===aJ)return A.INT;if(B===$1)return A.UNSIGNED_INT;if(B===m0)return A.FLOAT;if(B===sA)return A.HALF_FLOAT;if(B===BO)return A.ALPHA;if(B===IO)return A.RGB;if(B===V0)return A.RGBA;if(B===L1)return A.LUMINANCE;if(B===ZC)return A.LUMINANCE_ALPHA;if(B===RC)return A.DEPTH_COMPONENT;if(B===oE)return A.DEPTH_STENCIL;if(B===SQ)return A.RED;if(B===NC)return A.RED_INTEGER;if(B===jE)return A.RG;if(B===GC)return A.RG_INTEGER;if(B===A9)return A.RGBA_INTEGER;if(B===j8||B===q1||B===v8||B===PI)if(K===IQ)if(C=Q.get("WEBGL_compressed_texture_s3tc_srgb"),C!==null){if(B===j8)return C.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(B===q1)return C.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(B===v8)return C.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(B===PI)return C.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(C=Q.get("WEBGL_compressed_texture_s3tc"),C!==null){if(B===j8)return C.COMPRESSED_RGB_S3TC_DXT1_EXT;if(B===q1)return C.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(B===v8)return C.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(B===PI)return C.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(B===F1||B===WC||B===D1||B===XC)if(C=Q.get("WEBGL_compressed_texture_pvrtc"),C!==null){if(B===F1)return C.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(B===WC)return C.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(B===D1)return C.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(B===XC)return C.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(B===M1||B===h8||B===y8)if(C=Q.get("WEBGL_compressed_texture_etc"),C!==null){if(B===M1||B===h8)return K===IQ?C.COMPRESSED_SRGB8_ETC2:C.COMPRESSED_RGB8_ETC2;if(B===y8)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:C.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(B===w1||B===Q9||B===E9||B===B9||B===_1||B===I9||B===C9||B===K9||B===J9||B===U9||B===Y9||B===O9||B===H9||B===Z9)if(C=Q.get("WEBGL_compressed_texture_astc"),C!==null){if(B===w1)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:C.COMPRESSED_RGBA_ASTC_4x4_KHR;if(B===Q9)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:C.COMPRESSED_RGBA_ASTC_5x4_KHR;if(B===E9)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:C.COMPRESSED_RGBA_ASTC_5x5_KHR;if(B===B9)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:C.COMPRESSED_RGBA_ASTC_6x5_KHR;if(B===_1)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:C.COMPRESSED_RGBA_ASTC_6x6_KHR;if(B===I9)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:C.COMPRESSED_RGBA_ASTC_8x5_KHR;if(B===C9)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:C.COMPRESSED_RGBA_ASTC_8x6_KHR;if(B===K9)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:C.COMPRESSED_RGBA_ASTC_8x8_KHR;if(B===J9)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:C.COMPRESSED_RGBA_ASTC_10x5_KHR;if(B===U9)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:C.COMPRESSED_RGBA_ASTC_10x6_KHR;if(B===Y9)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:C.COMPRESSED_RGBA_ASTC_10x8_KHR;if(B===O9)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:C.COMPRESSED_RGBA_ASTC_10x10_KHR;if(B===H9)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:C.COMPRESSED_RGBA_ASTC_12x10_KHR;if(B===Z9)return K===IQ?C.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:C.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(B===k1||B===$C||B===S1)if(C=Q.get("EXT_texture_compression_bptc"),C!==null){if(B===k1)return K===IQ?C.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:C.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(B===$C)return C.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(B===S1)return C.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(B===CO||B===R9||B===N9||B===G9)if(C=Q.get("EXT_texture_compression_rgtc"),C!==null){if(B===k1)return C.COMPRESSED_RED_RGTC1_EXT;if(B===R9)return C.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(B===N9)return C.COMPRESSED_RED_GREEN_RGTC2_EXT;if(B===G9)return C.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;if(B===VE)return A.UNSIGNED_INT_24_8;return A[B]!==void 0?A[B]:null}return{convert:E}}var uM=` -void main() { - - gl_Position = vec4( position, 1.0 ); - -}`,pM=` -uniform sampler2DArray depthColor; -uniform float depthWidth; -uniform float depthHeight; - -void main() { - - vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); - - if ( coord.x >= 1.0 ) { - - gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; - - } else { - - gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; - - } - -}`;class bN{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(A,Q,E){if(this.texture===null){let B=new EQ,I=A.properties.get(B);if(I.__webglTexture=Q.texture,Q.depthNear!==E.depthNear||Q.depthFar!==E.depthFar)this.depthNear=Q.depthNear,this.depthFar=Q.depthFar;this.texture=B}}getMesh(A){if(this.texture!==null){if(this.mesh===null){let Q=A.cameras[0].viewport,E=new bA({vertexShader:uM,fragmentShader:pM,uniforms:{depthColor:{value:this.texture},depthWidth:{value:Q.z},depthHeight:{value:Q.w}}});this.mesh=new xA(new dQ(20,20),E)}}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class fN extends rE{constructor(A,Q){super();let E=this,B=null,I=1,C=null,K="local-floor",J=1,U=null,Y=null,H=null,R=null,O=null,N=null,$=new bN,L=Q.getContextAttributes(),W=null,Z=null,G=[],X=[],q=new AA,M=null,F=new v0;F.viewport=new MA;let D=new v0;D.viewport=new MA;let _=[F,D],w=new c9,k=null,T=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(s){let i=G[s];if(i===void 0)i=new m8,G[s]=i;return i.getTargetRaySpace()},this.getControllerGrip=function(s){let i=G[s];if(i===void 0)i=new m8,G[s]=i;return i.getGripSpace()},this.getHand=function(s){let i=G[s];if(i===void 0)i=new m8,G[s]=i;return i.getHandSpace()};function z(s){let i=X.indexOf(s.inputSource);if(i===-1)return;let n=G[i];if(n!==void 0)n.update(s.inputSource,s.frame,U||C),n.dispatchEvent({type:s.type,data:s.inputSource})}function j(){B.removeEventListener("select",z),B.removeEventListener("selectstart",z),B.removeEventListener("selectend",z),B.removeEventListener("squeeze",z),B.removeEventListener("squeezestart",z),B.removeEventListener("squeezeend",z),B.removeEventListener("end",j),B.removeEventListener("inputsourceschange",v);for(let s=0;s=0)X[l]=null,G[l].disconnect(n)}for(let i=0;i=X.length){X.push(n),l=o;break}else if(X[o]===null){X[o]=n,l=o;break}if(l===-1)break}let c=G[l];if(c)c.connect(n)}}let g=new y,P=new y;function V(s,i,n){g.setFromMatrixPosition(i.matrixWorld),P.setFromMatrixPosition(n.matrixWorld);let l=g.distanceTo(P),c=i.projectionMatrix.elements,o=n.projectionMatrix.elements,e=c[14]/(c[10]-1),BA=c[14]/(c[10]+1),EA=(c[9]+1)/c[5],CA=(c[9]-1)/c[5],f=(c[8]-1)/c[0],NA=(o[8]+1)/o[0],YA=e*f,FA=e*NA,ZA=l/(-f+NA),jA=ZA*-f;if(i.matrixWorld.decompose(s.position,s.quaternion,s.scale),s.translateX(jA),s.translateZ(ZA),s.matrixWorld.compose(s.position,s.quaternion,s.scale),s.matrixWorldInverse.copy(s.matrixWorld).invert(),c[10]===-1)s.projectionMatrix.copy(i.projectionMatrix),s.projectionMatrixInverse.copy(i.projectionMatrixInverse);else{let wA=e+ZA,VA=BA+ZA,d=YA-jA,u=FA+(l-jA),QA=EA*BA/VA*wA,t=CA*BA/VA*wA;s.projectionMatrix.makePerspective(d,u,QA,t,wA,VA),s.projectionMatrixInverse.copy(s.projectionMatrix).invert()}}function S(s,i){if(i===null)s.matrixWorld.copy(s.matrix);else s.matrixWorld.multiplyMatrices(i.matrixWorld,s.matrix);s.matrixWorldInverse.copy(s.matrixWorld).invert()}this.updateCamera=function(s){if(B===null)return;let{near:i,far:n}=s;if($.texture!==null){if($.depthNear>0)i=$.depthNear;if($.depthFar>0)n=$.depthFar}if(w.near=D.near=F.near=i,w.far=D.far=F.far=n,k!==w.near||T!==w.far)B.updateRenderState({depthNear:w.near,depthFar:w.far}),k=w.near,T=w.far;F.layers.mask=s.layers.mask|2,D.layers.mask=s.layers.mask|4,w.layers.mask=F.layers.mask|D.layers.mask;let l=s.parent,c=w.cameras;S(w,l);for(let o=0;o0)W.alphaTest.value=Z.alphaTest;let G=Q.get(Z),X=G.envMap,q=G.envMapRotation;if(X){if(W.envMap.value=X,u1.copy(q),u1.x*=-1,u1.y*=-1,u1.z*=-1,X.isCubeTexture&&X.isRenderTargetTexture===!1)u1.y*=-1,u1.z*=-1;W.envMapRotation.value.setFromMatrix4(mM.makeRotationFromEuler(u1)),W.flipEnvMap.value=X.isCubeTexture&&X.isRenderTargetTexture===!1?-1:1,W.reflectivity.value=Z.reflectivity,W.ior.value=Z.ior,W.refractionRatio.value=Z.refractionRatio}if(Z.lightMap)W.lightMap.value=Z.lightMap,W.lightMapIntensity.value=Z.lightMapIntensity,E(Z.lightMap,W.lightMapTransform);if(Z.aoMap)W.aoMap.value=Z.aoMap,W.aoMapIntensity.value=Z.aoMapIntensity,E(Z.aoMap,W.aoMapTransform)}function K(W,Z){if(W.diffuse.value.copy(Z.color),W.opacity.value=Z.opacity,Z.map)W.map.value=Z.map,E(Z.map,W.mapTransform)}function J(W,Z){W.dashSize.value=Z.dashSize,W.totalSize.value=Z.dashSize+Z.gapSize,W.scale.value=Z.scale}function U(W,Z,G,X){if(W.diffuse.value.copy(Z.color),W.opacity.value=Z.opacity,W.size.value=Z.size*G,W.scale.value=X*0.5,Z.map)W.map.value=Z.map,E(Z.map,W.uvTransform);if(Z.alphaMap)W.alphaMap.value=Z.alphaMap,E(Z.alphaMap,W.alphaMapTransform);if(Z.alphaTest>0)W.alphaTest.value=Z.alphaTest}function Y(W,Z){if(W.diffuse.value.copy(Z.color),W.opacity.value=Z.opacity,W.rotation.value=Z.rotation,Z.map)W.map.value=Z.map,E(Z.map,W.mapTransform);if(Z.alphaMap)W.alphaMap.value=Z.alphaMap,E(Z.alphaMap,W.alphaMapTransform);if(Z.alphaTest>0)W.alphaTest.value=Z.alphaTest}function H(W,Z){W.specular.value.copy(Z.specular),W.shininess.value=Math.max(Z.shininess,0.0001)}function R(W,Z){if(Z.gradientMap)W.gradientMap.value=Z.gradientMap}function O(W,Z){if(W.metalness.value=Z.metalness,Z.metalnessMap)W.metalnessMap.value=Z.metalnessMap,E(Z.metalnessMap,W.metalnessMapTransform);if(W.roughness.value=Z.roughness,Z.roughnessMap)W.roughnessMap.value=Z.roughnessMap,E(Z.roughnessMap,W.roughnessMapTransform);if(Z.envMap)W.envMapIntensity.value=Z.envMapIntensity}function N(W,Z,G){if(W.ior.value=Z.ior,Z.sheen>0){if(W.sheenColor.value.copy(Z.sheenColor).multiplyScalar(Z.sheen),W.sheenRoughness.value=Z.sheenRoughness,Z.sheenColorMap)W.sheenColorMap.value=Z.sheenColorMap,E(Z.sheenColorMap,W.sheenColorMapTransform);if(Z.sheenRoughnessMap)W.sheenRoughnessMap.value=Z.sheenRoughnessMap,E(Z.sheenRoughnessMap,W.sheenRoughnessMapTransform)}if(Z.clearcoat>0){if(W.clearcoat.value=Z.clearcoat,W.clearcoatRoughness.value=Z.clearcoatRoughness,Z.clearcoatMap)W.clearcoatMap.value=Z.clearcoatMap,E(Z.clearcoatMap,W.clearcoatMapTransform);if(Z.clearcoatRoughnessMap)W.clearcoatRoughnessMap.value=Z.clearcoatRoughnessMap,E(Z.clearcoatRoughnessMap,W.clearcoatRoughnessMapTransform);if(Z.clearcoatNormalMap){if(W.clearcoatNormalMap.value=Z.clearcoatNormalMap,E(Z.clearcoatNormalMap,W.clearcoatNormalMapTransform),W.clearcoatNormalScale.value.copy(Z.clearcoatNormalScale),Z.side===ZQ)W.clearcoatNormalScale.value.negate()}}if(Z.dispersion>0)W.dispersion.value=Z.dispersion;if(Z.iridescence>0){if(W.iridescence.value=Z.iridescence,W.iridescenceIOR.value=Z.iridescenceIOR,W.iridescenceThicknessMinimum.value=Z.iridescenceThicknessRange[0],W.iridescenceThicknessMaximum.value=Z.iridescenceThicknessRange[1],Z.iridescenceMap)W.iridescenceMap.value=Z.iridescenceMap,E(Z.iridescenceMap,W.iridescenceMapTransform);if(Z.iridescenceThicknessMap)W.iridescenceThicknessMap.value=Z.iridescenceThicknessMap,E(Z.iridescenceThicknessMap,W.iridescenceThicknessMapTransform)}if(Z.transmission>0){if(W.transmission.value=Z.transmission,W.transmissionSamplerMap.value=G.texture,W.transmissionSamplerSize.value.set(G.width,G.height),Z.transmissionMap)W.transmissionMap.value=Z.transmissionMap,E(Z.transmissionMap,W.transmissionMapTransform);if(W.thickness.value=Z.thickness,Z.thicknessMap)W.thicknessMap.value=Z.thicknessMap,E(Z.thicknessMap,W.thicknessMapTransform);W.attenuationDistance.value=Z.attenuationDistance,W.attenuationColor.value.copy(Z.attenuationColor)}if(Z.anisotropy>0){if(W.anisotropyVector.value.set(Z.anisotropy*Math.cos(Z.anisotropyRotation),Z.anisotropy*Math.sin(Z.anisotropyRotation)),Z.anisotropyMap)W.anisotropyMap.value=Z.anisotropyMap,E(Z.anisotropyMap,W.anisotropyMapTransform)}if(W.specularIntensity.value=Z.specularIntensity,W.specularColor.value.copy(Z.specularColor),Z.specularColorMap)W.specularColorMap.value=Z.specularColorMap,E(Z.specularColorMap,W.specularColorMapTransform);if(Z.specularIntensityMap)W.specularIntensityMap.value=Z.specularIntensityMap,E(Z.specularIntensityMap,W.specularIntensityMapTransform)}function $(W,Z){if(Z.matcap)W.matcap.value=Z.matcap}function L(W,Z){let G=Q.get(Z).light;W.referencePosition.value.setFromMatrixPosition(G.matrixWorld),W.nearDistance.value=G.shadow.camera.near,W.farDistance.value=G.shadow.camera.far}return{refreshFogUniforms:B,refreshMaterialUniforms:I}}function lM(A,Q,E,B){let I={},C={},K=[],J=A.getParameter(A.MAX_UNIFORM_BUFFER_BINDINGS);function U(G,X){let q=X.program;B.uniformBlockBinding(G,q)}function Y(G,X){let q=I[G.id];if(q===void 0)$(G),q=H(G),I[G.id]=q,G.addEventListener("dispose",W);let M=X.program;B.updateUBOMapping(G,M);let F=Q.render.frame;if(C[G.id]!==F)O(G),C[G.id]=F}function H(G){let X=R();G.__bindingPointIndex=X;let q=A.createBuffer(),M=G.__size,F=G.usage;return A.bindBuffer(A.UNIFORM_BUFFER,q),A.bufferData(A.UNIFORM_BUFFER,M,F),A.bindBuffer(A.UNIFORM_BUFFER,null),A.bindBufferBase(A.UNIFORM_BUFFER,X,q),q}function R(){for(let G=0;G0)q+=M-F;return G.__size=q,G.__cache={},this}function L(G){let X={boundary:0,storage:0};if(typeof G==="number"||typeof G==="boolean")X.boundary=4,X.storage=4;else if(G.isVector2)X.boundary=8,X.storage=8;else if(G.isVector3||G.isColor)X.boundary=16,X.storage=12;else if(G.isVector4)X.boundary=16,X.storage=16;else if(G.isMatrix3)X.boundary=48,X.storage=48;else if(G.isMatrix4)X.boundary=64,X.storage=64;else if(G.isTexture)console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.");else console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",G);return X}function W(G){let X=G.target;X.removeEventListener("dispose",W);let q=K.indexOf(X.__bindingPointIndex);K.splice(q,1),A.deleteBuffer(I[X.id]),delete I[X.id],delete C[X.id]}function Z(){for(let G in I)A.deleteBuffer(I[G]);K=[],I={},C={}}return{bind:U,update:Y,dispose:Z}}class AK{constructor(A={}){let{canvas:Q=LO(),context:E=null,depth:B=!0,stencil:I=!1,alpha:C=!1,antialias:K=!1,premultipliedAlpha:J=!0,preserveDrawingBuffer:U=!1,powerPreference:Y="default",failIfMajorPerformanceCaveat:H=!1,reverseDepthBuffer:R=!1}=A;this.isWebGLRenderer=!0;let O;if(E!==null){if(typeof WebGLRenderingContext!=="undefined"&&E instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");O=E.getContextAttributes().alpha}else O=C;let N=new Uint32Array(4),$=new Int32Array(4),L=null,W=null,Z=[],G=[];this.domElement=Q,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=N0,this.toneMapping=VB,this.toneMappingExposure=1;let X=this,q=!1,M=0,F=0,D=null,_=-1,w=null,k=new MA,T=new MA,z=null,j=new a(0),v=0,g=Q.width,P=Q.height,V=1,S=null,h=null,x=new MA(0,0,g,P),b=new MA(0,0,g,P),m=!1,s=new xB,i=!1,n=!1;this.transmissionResolutionScale=1;let l=new RA,c=new RA,o=new y,e=new MA,BA={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},EA=!1;function CA(){return D===null?V:1}let f=E;function NA(p,JA){return Q.getContext(p,JA)}try{let p={alpha:!0,depth:B,stencil:I,antialias:K,premultipliedAlpha:J,preserveDrawingBuffer:U,powerPreference:Y,failIfMajorPerformanceCaveat:H};if("setAttribute"in Q)Q.setAttribute("data-engine",`three.js r${ZB}`);if(Q.addEventListener("webglcontextlost",DA,!1),Q.addEventListener("webglcontextrestored",kA,!1),Q.addEventListener("webglcontextcreationerror",lA,!1),f===null){if(f=NA("webgl2",p),f===null)if(NA("webgl2"))throw new Error("Error creating WebGL context with your selected attributes.");else throw new Error("Error creating WebGL context.")}}catch(p){throw console.error("THREE.WebGLRenderer: "+p.message),p}let YA,FA,ZA,jA,wA,VA,d,u,QA,t,KA,HA,fA,zA,yA,qA,LA,_A,B0,cA,uA,pA,iA,$0;function IA(){if(YA=new YD(f),YA.init(),pA=new xN(f,YA),FA=new BD(f,YA,A,pA),ZA=new bM(f,YA),FA.reverseDepthBuffer&&R)ZA.buffers.depth.setReversed(!0);jA=new ZD(f),wA=new _M,VA=new fM(f,YA,ZA,wA,FA,pA,jA),d=new CD(X),u=new UD(X),QA=new L5(f),iA=new QD(f,QA),t=new OD(f,QA,jA,iA),KA=new ND(f,t,QA,jA),B0=new RD(f,FA,VA),qA=new ID(wA),HA=new wM(X,d,u,YA,FA,iA,qA),fA=new cM(X,wA),zA=new SM,yA=new vM(YA),_A=new AD(X,d,u,ZA,KA,O,J),LA=new gM(X,KA,FA),$0=new lM(f,jA,FA,ZA),cA=new ED(f,YA,jA),uA=new HD(f,YA,jA),jA.programs=HA.programs,X.capabilities=FA,X.extensions=YA,X.properties=wA,X.renderLists=zA,X.shadowMap=LA,X.state=ZA,X.info=jA}IA();let TA=new fN(X,f);this.xr=TA,this.getContext=function(){return f},this.getContextAttributes=function(){return f.getContextAttributes()},this.forceContextLoss=function(){let p=YA.get("WEBGL_lose_context");if(p)p.loseContext()},this.forceContextRestore=function(){let p=YA.get("WEBGL_lose_context");if(p)p.restoreContext()},this.getPixelRatio=function(){return V},this.setPixelRatio=function(p){if(p===void 0)return;V=p,this.setSize(g,P,!1)},this.getSize=function(p){return p.set(g,P)},this.setSize=function(p,JA,WA=!0){if(TA.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}if(g=p,P=JA,Q.width=Math.floor(p*V),Q.height=Math.floor(JA*V),WA===!0)Q.style.width=p+"px",Q.style.height=JA+"px";this.setViewport(0,0,p,JA)},this.getDrawingBufferSize=function(p){return p.set(g*V,P*V).floor()},this.setDrawingBufferSize=function(p,JA,WA){g=p,P=JA,V=WA,Q.width=Math.floor(p*WA),Q.height=Math.floor(JA*WA),this.setViewport(0,0,p,JA)},this.getCurrentViewport=function(p){return p.copy(k)},this.getViewport=function(p){return p.copy(x)},this.setViewport=function(p,JA,WA,XA){if(p.isVector4)x.set(p.x,p.y,p.z,p.w);else x.set(p,JA,WA,XA);ZA.viewport(k.copy(x).multiplyScalar(V).round())},this.getScissor=function(p){return p.copy(b)},this.setScissor=function(p,JA,WA,XA){if(p.isVector4)b.set(p.x,p.y,p.z,p.w);else b.set(p,JA,WA,XA);ZA.scissor(T.copy(b).multiplyScalar(V).round())},this.getScissorTest=function(){return m},this.setScissorTest=function(p){ZA.setScissorTest(m=p)},this.setOpaqueSort=function(p){S=p},this.setTransparentSort=function(p){h=p},this.getClearColor=function(p){return p.copy(_A.getClearColor())},this.setClearColor=function(){_A.setClearColor.apply(_A,arguments)},this.getClearAlpha=function(){return _A.getClearAlpha()},this.setClearAlpha=function(){_A.setClearAlpha.apply(_A,arguments)},this.clear=function(p=!0,JA=!0,WA=!0){let XA=0;if(p){let UA=!1;if(D!==null){let gA=D.texture.format;UA=gA===A9||gA===GC||gA===NC}if(UA){let gA=D.texture.type,nA=gA===x0||gA===$1||gA===hB||gA===VE||gA===tJ||gA===eJ,rA=_A.getClearColor(),A0=_A.getClearAlpha(),D0=rA.r,M0=rA.g,Y0=rA.b;if(nA)N[0]=D0,N[1]=M0,N[2]=Y0,N[3]=A0,f.clearBufferuiv(f.COLOR,0,N);else $[0]=D0,$[1]=M0,$[2]=Y0,$[3]=A0,f.clearBufferiv(f.COLOR,0,$)}else XA|=f.COLOR_BUFFER_BIT}if(JA)XA|=f.DEPTH_BUFFER_BIT;if(WA)XA|=f.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295);f.clear(XA)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){Q.removeEventListener("webglcontextlost",DA,!1),Q.removeEventListener("webglcontextrestored",kA,!1),Q.removeEventListener("webglcontextcreationerror",lA,!1),_A.dispose(),zA.dispose(),yA.dispose(),wA.dispose(),d.dispose(),u.dispose(),KA.dispose(),iA.dispose(),$0.dispose(),HA.dispose(),TA.dispose(),TA.removeEventListener("sessionstart",cE),TA.removeEventListener("sessionend",CB),lE.stop()};function DA(p){p.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),q=!0}function kA(){console.log("THREE.WebGLRenderer: Context Restored."),q=!1;let p=jA.autoReset,JA=LA.enabled,WA=LA.autoUpdate,XA=LA.needsUpdate,UA=LA.type;IA(),jA.autoReset=p,LA.enabled=JA,LA.autoUpdate=WA,LA.needsUpdate=XA,LA.type=UA}function lA(p){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",p.statusMessage)}function dA(p){let JA=p.target;JA.removeEventListener("dispose",dA),F0(JA)}function F0(p){HQ(p),wA.remove(p)}function HQ(p){let JA=wA.get(p).programs;if(JA!==void 0){if(JA.forEach(function(WA){HA.releaseProgram(WA)}),p.isShaderMaterial)HA.releaseShaderCache(p)}}this.renderBufferDirect=function(p,JA,WA,XA,UA,gA){if(JA===null)JA=BA;let nA=UA.isMesh&&UA.matrixWorld.determinant()<0,rA=q$(p,JA,WA,XA,UA);ZA.setMaterial(XA,nA);let A0=WA.index,D0=1;if(XA.wireframe===!0){if(A0=t.getWireframeAttribute(WA),A0===void 0)return;D0=2}let M0=WA.drawRange,Y0=WA.attributes.position,l0=M0.start*D0,AQ=(M0.start+M0.count)*D0;if(gA!==null)l0=Math.max(l0,gA.start*D0),AQ=Math.min(AQ,(gA.start+gA.count)*D0);if(A0!==null)l0=Math.max(l0,0),AQ=Math.min(AQ,A0.count);else if(Y0!==void 0&&Y0!==null)l0=Math.max(l0,0),AQ=Math.min(AQ,Y0.count);let TQ=AQ-l0;if(TQ<0||TQ===1/0)return;iA.setup(UA,XA,rA,WA,A0);let qQ,n0=cA;if(A0!==null)qQ=QA.get(A0),n0=uA,n0.setIndex(qQ);if(UA.isMesh)if(XA.wireframe===!0)ZA.setLineWidth(XA.wireframeLinewidth*CA()),n0.setMode(f.LINES);else n0.setMode(f.TRIANGLES);else if(UA.isLine){let R0=XA.linewidth;if(R0===void 0)R0=1;if(ZA.setLineWidth(R0*CA()),UA.isLineSegments)n0.setMode(f.LINES);else if(UA.isLineLoop)n0.setMode(f.LINE_LOOP);else n0.setMode(f.LINE_STRIP)}else if(UA.isPoints)n0.setMode(f.POINTS);else if(UA.isSprite)n0.setMode(f.TRIANGLES);if(UA.isBatchedMesh)if(UA._multiDrawInstances!==null)n0.renderMultiDrawInstances(UA._multiDrawStarts,UA._multiDrawCounts,UA._multiDrawCount,UA._multiDrawInstances);else if(!YA.get("WEBGL_multi_draw")){let{_multiDrawStarts:R0,_multiDrawCounts:iQ,_multiDrawCount:QQ}=UA,KB=A0?QA.get(A0).bytesPerElement:1,K8=wA.get(XA).currentProgram.getUniforms();for(let _E=0;_E{function gA(){if(XA.forEach(function(nA){if(wA.get(nA).currentProgram.isReady())XA.delete(nA)}),XA.size===0){UA(p);return}setTimeout(gA,10)}if(YA.get("KHR_parallel_shader_compile")!==null)gA();else setTimeout(gA,10)})};let d0=null;function IB(p){if(d0)d0(p)}function cE(){lE.stop()}function CB(){lE.start()}let lE=new SN;if(lE.setAnimationLoop(IB),typeof self!=="undefined")lE.setContext(self);this.setAnimationLoop=function(p){d0=p,TA.setAnimationLoop(p),p===null?lE.stop():lE.start()},TA.addEventListener("sessionstart",cE),TA.addEventListener("sessionend",CB),this.render=function(p,JA){if(JA!==void 0&&JA.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(q===!0)return;if(p.matrixWorldAutoUpdate===!0)p.updateMatrixWorld();if(JA.parent===null&&JA.matrixWorldAutoUpdate===!0)JA.updateMatrixWorld();if(TA.enabled===!0&&TA.isPresenting===!0){if(TA.cameraAutoUpdate===!0)TA.updateCamera(JA);JA=TA.getCamera()}if(p.isScene===!0)p.onBeforeRender(X,p,JA,D);if(W=yA.get(p,G.length),W.init(JA),G.push(W),c.multiplyMatrices(JA.projectionMatrix,JA.matrixWorldInverse),s.setFromProjectionMatrix(c),n=this.localClippingEnabled,i=qA.init(this.clippingPlanes,n),L=zA.get(p,Z.length),L.init(),Z.push(L),TA.enabled===!0&&TA.isPresenting===!0){let gA=X.xr.getDepthSensingMesh();if(gA!==null)v6(gA,JA,-1/0,X.sortObjects)}if(v6(p,JA,0,X.sortObjects),L.finish(),X.sortObjects===!0)L.sort(S,h);if(EA=TA.enabled===!1||TA.isPresenting===!1||TA.hasDepthSensing()===!1,EA)_A.addToRenderList(L,p);if(this.info.render.frame++,i===!0)qA.beginShadows();let WA=W.state.shadowsArray;if(LA.render(WA,p,JA),i===!0)qA.endShadows();if(this.info.autoReset===!0)this.info.reset();let{opaque:XA,transmissive:UA}=L;if(W.setupLights(),JA.isArrayCamera){let gA=JA.cameras;if(UA.length>0)for(let nA=0,rA=gA.length;nA0)h6(XA,UA,p,JA);if(EA)_A.render(p);nK(L,p,JA)}if(D!==null&&F===0)VA.updateMultisampleRenderTarget(D),VA.updateRenderTargetMipmap(D);if(p.isScene===!0)p.onAfterRender(X,p,JA);if(iA.resetDefaultState(),_=-1,w=null,G.pop(),G.length>0){if(W=G[G.length-1],i===!0)qA.setGlobalState(X.clippingPlanes,W.state.camera)}else W=null;if(Z.pop(),Z.length>0)L=Z[Z.length-1];else L=null};function v6(p,JA,WA,XA){if(p.visible===!1)return;if(p.layers.test(JA.layers)){if(p.isGroup)WA=p.renderOrder;else if(p.isLOD){if(p.autoUpdate===!0)p.update(JA)}else if(p.isLight){if(W.pushLight(p),p.castShadow)W.pushShadow(p)}else if(p.isSprite){if(!p.frustumCulled||s.intersectsSprite(p)){if(XA)e.setFromMatrixPosition(p.matrixWorld).applyMatrix4(c);let nA=KA.update(p),rA=p.material;if(rA.visible)L.push(p,nA,rA,WA,e.z,null)}}else if(p.isMesh||p.isLine||p.isPoints){if(!p.frustumCulled||s.intersectsObject(p)){let nA=KA.update(p),rA=p.material;if(XA){if(p.boundingSphere!==void 0){if(p.boundingSphere===null)p.computeBoundingSphere();e.copy(p.boundingSphere.center)}else{if(nA.boundingSphere===null)nA.computeBoundingSphere();e.copy(nA.boundingSphere.center)}e.applyMatrix4(p.matrixWorld).applyMatrix4(c)}if(Array.isArray(rA)){let A0=nA.groups;for(let D0=0,M0=A0.length;D00)oI(UA,JA,WA);if(gA.length>0)oI(gA,JA,WA);if(nA.length>0)oI(nA,JA,WA);ZA.buffers.depth.setTest(!0),ZA.buffers.depth.setMask(!0),ZA.buffers.color.setMask(!0),ZA.setPolygonOffset(!1)}function h6(p,JA,WA,XA){if((WA.isScene===!0?WA.overrideMaterial:null)!==null)return;if(W.state.transmissionRenderTarget[XA.id]===void 0)W.state.transmissionRenderTarget[XA.id]=new Q0(1,1,{generateMipmaps:!0,type:YA.has("EXT_color_buffer_half_float")||YA.has("EXT_color_buffer_float")?sA:x0,minFilter:hQ,samples:4,stencilBuffer:I,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:O0.workingColorSpace});let gA=W.state.transmissionRenderTarget[XA.id],nA=XA.viewport||k;gA.setSize(nA.z*X.transmissionResolutionScale,nA.w*X.transmissionResolutionScale);let rA=X.getRenderTarget();if(X.setRenderTarget(gA),X.getClearColor(j),v=X.getClearAlpha(),v<1)X.setClearColor(16777215,0.5);if(X.clear(),EA)_A.render(WA);let A0=X.toneMapping;X.toneMapping=VB;let D0=XA.viewport;if(XA.viewport!==void 0)XA.viewport=void 0;if(W.setupLightsView(XA),i===!0)qA.setGlobalState(X.clippingPlanes,XA);if(oI(p,WA,XA),VA.updateMultisampleRenderTarget(gA),VA.updateRenderTargetMipmap(gA),YA.has("WEBGL_multisampled_render_to_texture")===!1){let M0=!1;for(let Y0=0,l0=JA.length;Y00),Y0=!!WA.morphAttributes.position,l0=!!WA.morphAttributes.normal,AQ=!!WA.morphAttributes.color,TQ=VB;if(XA.toneMapped){if(D===null||D.isXRRenderTarget===!0)TQ=X.toneMapping}let qQ=WA.morphAttributes.position||WA.morphAttributes.normal||WA.morphAttributes.color,n0=qQ!==void 0?qQ.length:0,R0=wA.get(XA),iQ=W.state.lights;if(i===!0){if(n===!0||p!==w){let KE=p===w&&XA.id===_;qA.setState(XA,p,KE)}}let QQ=!1;if(XA.version===R0.__version){if(R0.needsLights&&R0.lightsStateVersion!==iQ.state.version)QQ=!0;else if(R0.outputColorSpace!==rA)QQ=!0;else if(UA.isBatchedMesh&&R0.batching===!1)QQ=!0;else if(!UA.isBatchedMesh&&R0.batching===!0)QQ=!0;else if(UA.isBatchedMesh&&R0.batchingColor===!0&&UA.colorTexture===null)QQ=!0;else if(UA.isBatchedMesh&&R0.batchingColor===!1&&UA.colorTexture!==null)QQ=!0;else if(UA.isInstancedMesh&&R0.instancing===!1)QQ=!0;else if(!UA.isInstancedMesh&&R0.instancing===!0)QQ=!0;else if(UA.isSkinnedMesh&&R0.skinning===!1)QQ=!0;else if(!UA.isSkinnedMesh&&R0.skinning===!0)QQ=!0;else if(UA.isInstancedMesh&&R0.instancingColor===!0&&UA.instanceColor===null)QQ=!0;else if(UA.isInstancedMesh&&R0.instancingColor===!1&&UA.instanceColor!==null)QQ=!0;else if(UA.isInstancedMesh&&R0.instancingMorph===!0&&UA.morphTexture===null)QQ=!0;else if(UA.isInstancedMesh&&R0.instancingMorph===!1&&UA.morphTexture!==null)QQ=!0;else if(R0.envMap!==A0)QQ=!0;else if(XA.fog===!0&&R0.fog!==gA)QQ=!0;else if(R0.numClippingPlanes!==void 0&&(R0.numClippingPlanes!==qA.numPlanes||R0.numIntersection!==qA.numIntersection))QQ=!0;else if(R0.vertexAlphas!==D0)QQ=!0;else if(R0.vertexTangents!==M0)QQ=!0;else if(R0.morphTargets!==Y0)QQ=!0;else if(R0.morphNormals!==l0)QQ=!0;else if(R0.morphColors!==AQ)QQ=!0;else if(R0.toneMapping!==TQ)QQ=!0;else if(R0.morphTargetsCount!==n0)QQ=!0}else QQ=!0,R0.__version=XA.version;let KB=R0.currentProgram;if(QQ===!0)KB=rI(XA,JA,UA);let K8=!1,_E=!1,x6=!1,WQ=KB.getUniforms(),dE=R0.uniforms;if(ZA.useProgram(KB.program))K8=!0,_E=!0,x6=!0;if(XA.id!==_)_=XA.id,_E=!0;if(K8||w!==p){if(ZA.buffers.depth.getReversed())l.copy(p.projectionMatrix),uR(l),pR(l),WQ.setValue(f,"projectionMatrix",l);else WQ.setValue(f,"projectionMatrix",p.projectionMatrix);WQ.setValue(f,"viewMatrix",p.matrixWorldInverse);let RE=WQ.map.cameraPosition;if(RE!==void 0)RE.setValue(f,o.setFromMatrixPosition(p.matrixWorld));if(FA.logarithmicDepthBuffer)WQ.setValue(f,"logDepthBufFC",2/(Math.log(p.far+1)/Math.LN2));if(XA.isMeshPhongMaterial||XA.isMeshToonMaterial||XA.isMeshLambertMaterial||XA.isMeshBasicMaterial||XA.isMeshStandardMaterial||XA.isShaderMaterial)WQ.setValue(f,"isOrthographic",p.isOrthographicCamera===!0);if(w!==p)w=p,_E=!0,x6=!0}if(UA.isSkinnedMesh){WQ.setOptional(f,UA,"bindMatrix"),WQ.setOptional(f,UA,"bindMatrixInverse");let KE=UA.skeleton;if(KE){if(KE.boneTexture===null)KE.computeBoneTexture();WQ.setValue(f,"boneTexture",KE.boneTexture,VA)}}if(UA.isBatchedMesh){if(WQ.setOptional(f,UA,"batchingTexture"),WQ.setValue(f,"batchingTexture",UA._matricesTexture,VA),WQ.setOptional(f,UA,"batchingIdTexture"),WQ.setValue(f,"batchingIdTexture",UA._indirectTexture,VA),WQ.setOptional(f,UA,"batchingColorTexture"),UA._colorsTexture!==null)WQ.setValue(f,"batchingColorTexture",UA._colorsTexture,VA)}let nE=WA.morphAttributes;if(nE.position!==void 0||nE.normal!==void 0||nE.color!==void 0)B0.update(UA,WA,KB);if(_E||R0.receiveShadow!==UA.receiveShadow)R0.receiveShadow=UA.receiveShadow,WQ.setValue(f,"receiveShadow",UA.receiveShadow);if(XA.isMeshGouraudMaterial&&XA.envMap!==null)dE.envMap.value=A0,dE.flipEnvMap.value=A0.isCubeTexture&&A0.isRenderTargetTexture===!1?-1:1;if(XA.isMeshStandardMaterial&&XA.envMap===null&&JA.environment!==null)dE.envMapIntensity.value=JA.environmentIntensity;if(_E){if(WQ.setValue(f,"toneMappingExposure",X.toneMappingExposure),R0.needsLights)F$(dE,x6);if(gA&&XA.fog===!0)fA.refreshFogUniforms(dE,gA);fA.refreshMaterialUniforms(dE,XA,V,P,W.state.transmissionRenderTarget[p.id]),eC.upload(f,g6(R0),dE,VA)}if(XA.isShaderMaterial&&XA.uniformsNeedUpdate===!0)eC.upload(f,g6(R0),dE,VA),XA.uniformsNeedUpdate=!1;if(XA.isSpriteMaterial)WQ.setValue(f,"center",UA.center);if(WQ.setValue(f,"modelViewMatrix",UA.modelViewMatrix),WQ.setValue(f,"normalMatrix",UA.normalMatrix),WQ.setValue(f,"modelMatrix",UA.matrixWorld),XA.isShaderMaterial||XA.isRawShaderMaterial){let KE=XA.uniformsGroups;for(let RE=0,oU=KE.length;RE0&&VA.useMultisampledRTT(p)===!1)UA=wA.get(p).__webglMultisampledFramebuffer;else if(Array.isArray(M0))UA=M0[WA];else UA=M0;k.copy(p.viewport),T.copy(p.scissor),z=p.scissorTest}else k.copy(x).multiplyScalar(V).floor(),T.copy(b).multiplyScalar(V).floor(),z=m;if(WA!==0)UA=M$;if(ZA.bindFramebuffer(f.FRAMEBUFFER,UA)&&XA)ZA.drawBuffers(p,UA);if(ZA.viewport(k),ZA.scissor(T),ZA.setScissorTest(z),gA){let A0=wA.get(p.texture);f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_CUBE_MAP_POSITIVE_X+JA,A0.__webglTexture,WA)}else if(nA){let A0=wA.get(p.texture),D0=JA;f.framebufferTextureLayer(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,A0.__webglTexture,WA,D0)}else if(p!==null&&WA!==0){let A0=wA.get(p.texture);f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,A0.__webglTexture,WA)}_=-1},this.readRenderTargetPixels=function(p,JA,WA,XA,UA,gA,nA){if(!(p&&p.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let rA=wA.get(p).__webglFramebuffer;if(p.isWebGLCubeRenderTarget&&nA!==void 0)rA=rA[nA];if(rA){ZA.bindFramebuffer(f.FRAMEBUFFER,rA);try{let A0=p.texture,D0=A0.format,M0=A0.type;if(!FA.textureFormatReadable(D0)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!FA.textureTypeReadable(M0)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}if(JA>=0&&JA<=p.width-XA&&(WA>=0&&WA<=p.height-UA))f.readPixels(JA,WA,XA,UA,pA.convert(D0),pA.convert(M0),gA)}finally{let A0=D!==null?wA.get(D).__webglFramebuffer:null;ZA.bindFramebuffer(f.FRAMEBUFFER,A0)}}},this.readRenderTargetPixelsAsync=async function(p,JA,WA,XA,UA,gA,nA){if(!(p&&p.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let rA=wA.get(p).__webglFramebuffer;if(p.isWebGLCubeRenderTarget&&nA!==void 0)rA=rA[nA];if(rA){let A0=p.texture,D0=A0.format,M0=A0.type;if(!FA.textureFormatReadable(D0))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!FA.textureTypeReadable(M0))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(JA>=0&&JA<=p.width-XA&&(WA>=0&&WA<=p.height-UA)){ZA.bindFramebuffer(f.FRAMEBUFFER,rA);let Y0=f.createBuffer();f.bindBuffer(f.PIXEL_PACK_BUFFER,Y0),f.bufferData(f.PIXEL_PACK_BUFFER,gA.byteLength,f.STREAM_READ),f.readPixels(JA,WA,XA,UA,pA.convert(D0),pA.convert(M0),0);let l0=D!==null?wA.get(D).__webglFramebuffer:null;ZA.bindFramebuffer(f.FRAMEBUFFER,l0);let AQ=f.fenceSync(f.SYNC_GPU_COMMANDS_COMPLETE,0);return f.flush(),await fR(f,AQ,4),f.bindBuffer(f.PIXEL_PACK_BUFFER,Y0),f.getBufferSubData(f.PIXEL_PACK_BUFFER,0,gA),f.deleteBuffer(Y0),f.deleteSync(AQ),gA}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(p,JA=null,WA=0){if(p.isTexture!==!0)P1("WebGLRenderer: copyFramebufferToTexture function signature has changed."),JA=arguments[0]||null,p=arguments[1];let XA=Math.pow(2,-WA),UA=Math.floor(p.image.width*XA),gA=Math.floor(p.image.height*XA),nA=JA!==null?JA.x:0,rA=JA!==null?JA.y:0;VA.setTexture2D(p,0),f.copyTexSubImage2D(f.TEXTURE_2D,WA,0,0,nA,rA,UA,gA),ZA.unbindTexture()};let w$=f.createFramebuffer(),_$=f.createFramebuffer();if(this.copyTextureToTexture=function(p,JA,WA=null,XA=null,UA=0,gA=null){if(p.isTexture!==!0)P1("WebGLRenderer: copyTextureToTexture function signature has changed."),XA=arguments[0]||null,p=arguments[1],JA=arguments[2],gA=arguments[3]||0,WA=null;if(gA===null)if(UA!==0)P1("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),gA=UA,UA=0;else gA=0;let nA,rA,A0,D0,M0,Y0,l0,AQ,TQ,qQ=p.isCompressedTexture?p.mipmaps[gA]:p.image;if(WA!==null)nA=WA.max.x-WA.min.x,rA=WA.max.y-WA.min.y,A0=WA.isBox3?WA.max.z-WA.min.z:1,D0=WA.min.x,M0=WA.min.y,Y0=WA.isBox3?WA.min.z:0;else{let nE=Math.pow(2,-UA);if(nA=Math.floor(qQ.width*nE),rA=Math.floor(qQ.height*nE),p.isDataArrayTexture)A0=qQ.depth;else if(p.isData3DTexture)A0=Math.floor(qQ.depth*nE);else A0=1;D0=0,M0=0,Y0=0}if(XA!==null)l0=XA.x,AQ=XA.y,TQ=XA.z;else l0=0,AQ=0,TQ=0;let n0=pA.convert(JA.format),R0=pA.convert(JA.type),iQ;if(JA.isData3DTexture)VA.setTexture3D(JA,0),iQ=f.TEXTURE_3D;else if(JA.isDataArrayTexture||JA.isCompressedArrayTexture)VA.setTexture2DArray(JA,0),iQ=f.TEXTURE_2D_ARRAY;else VA.setTexture2D(JA,0),iQ=f.TEXTURE_2D;f.pixelStorei(f.UNPACK_FLIP_Y_WEBGL,JA.flipY),f.pixelStorei(f.UNPACK_PREMULTIPLY_ALPHA_WEBGL,JA.premultiplyAlpha),f.pixelStorei(f.UNPACK_ALIGNMENT,JA.unpackAlignment);let QQ=f.getParameter(f.UNPACK_ROW_LENGTH),KB=f.getParameter(f.UNPACK_IMAGE_HEIGHT),K8=f.getParameter(f.UNPACK_SKIP_PIXELS),_E=f.getParameter(f.UNPACK_SKIP_ROWS),x6=f.getParameter(f.UNPACK_SKIP_IMAGES);f.pixelStorei(f.UNPACK_ROW_LENGTH,qQ.width),f.pixelStorei(f.UNPACK_IMAGE_HEIGHT,qQ.height),f.pixelStorei(f.UNPACK_SKIP_PIXELS,D0),f.pixelStorei(f.UNPACK_SKIP_ROWS,M0),f.pixelStorei(f.UNPACK_SKIP_IMAGES,Y0);let WQ=p.isDataArrayTexture||p.isData3DTexture,dE=JA.isDataArrayTexture||JA.isData3DTexture;if(p.isDepthTexture){let nE=wA.get(p),KE=wA.get(JA),RE=wA.get(nE.__renderTarget),oU=wA.get(KE.__renderTarget);ZA.bindFramebuffer(f.READ_FRAMEBUFFER,RE.__webglFramebuffer),ZA.bindFramebuffer(f.DRAW_FRAMEBUFFER,oU.__webglFramebuffer);for(let aI=0;aIQ.length)Q.push(new KU);Q.length=A.length;for(let E=0;E 0.0 ) { - material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); - // Iridescence F0 approximation - material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); - } -#endif - -IncidentLight directLight; - -#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) - - PointLight pointLight; - #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 - PointLightShadow pointLightShadow; - #endif - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - - pointLight = pointLights[ i ]; - - getPointLightInfo( pointLight, geometryPosition, directLight ); - - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) - pointLightShadow = pointLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; - #endif - - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - } - #pragma unroll_loop_end - -#endif - -#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) - - SpotLight spotLight; - vec4 spotColor; - vec3 spotLightCoord; - bool inSpotLightMap; - - #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 - SpotLightShadow spotLightShadow; - #endif - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - - spotLight = spotLights[ i ]; - - getSpotLightInfo( spotLight, geometryPosition, directLight ); - - // spot lights are ordered [shadows with maps, shadows without maps, maps without shadows, none] - #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX - #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS - #else - #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) - #endif - #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) - spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; - inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); - spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); - directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; - #endif - #undef SPOT_LIGHT_MAP_INDEX - - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) - spotLightShadow = spotLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; - - #endif - - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - } - #pragma unroll_loop_end - -#endif - -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES ) - - DirectionalLight directionalLight; - float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear); - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - - #if defined( USE_SHADOWMAP ) && defined( CSM_FADE ) - vec2 cascade; - float cascadeCenter; - float closestEdge; - float margin; - float csmx; - float csmy; - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, directLight ); - - #if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - // NOTE: Depth gets larger away from the camera. - // cascade.x is closer, cascade.y is further - cascade = CSM_cascades[ i ]; - cascadeCenter = ( cascade.x + cascade.y ) / 2.0; - closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y; - margin = 0.25 * pow( closestEdge, 2.0 ); - csmx = cascade.x - margin / 2.0; - csmy = cascade.y + margin / 2.0; - if( linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) { - - float dist = min( linearDepth - csmx, csmy - linearDepth ); - float ratio = clamp( dist / margin, 0.0, 1.0 ); - - vec3 prevColor = directLight.color; - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - - bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter; - directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 ); - - ReflectedLight prevLight = reflectedLight; - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter; - float blendRatio = shouldBlend ? ratio : 1.0; - - reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio ); - reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio ); - reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio ); - reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio ); - - } - #endif - - } - #pragma unroll_loop_end - #elif defined (USE_SHADOWMAP) - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - directionalLight = directionalLights[ i ]; - getDirectionalLightInfo( directionalLight, directLight ); - - #if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - - directionalLightShadow = directionalLightShadows[ i ]; - if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - - if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - #endif - - } - #pragma unroll_loop_end - - #elif ( NUM_DIR_LIGHT_SHADOWS > 0 ) - // note: no loop here - all CSM lights are in fact one light only - getDirectionalLightInfo( directionalLights[0], directLight ); - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - #endif - - #if ( NUM_DIR_LIGHTS > NUM_DIR_LIGHT_SHADOWS) - // compute the lights not casting shadows (if any) - - #pragma unroll_loop_start - for ( int i = NUM_DIR_LIGHT_SHADOWS; i < NUM_DIR_LIGHTS; i ++ ) { - - directionalLight = directionalLights[ i ]; - - getDirectionalLightInfo( directionalLight, directLight ); - - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - } - #pragma unroll_loop_end - - #endif - -#endif - - -#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !defined( USE_CSM ) && !defined( CSM_CASCADES ) - - DirectionalLight directionalLight; - #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 - DirectionalLightShadow directionalLightShadow; - #endif - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - directionalLight = directionalLights[ i ]; - - getDirectionalLightInfo( directionalLight, directLight ); - - #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) - directionalLightShadow = directionalLightShadows[ i ]; - directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; - #endif - - RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - } - #pragma unroll_loop_end - -#endif - -#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) - - RectAreaLight rectAreaLight; - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { - - rectAreaLight = rectAreaLights[ i ]; - RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); - - } - #pragma unroll_loop_end - -#endif - -#if defined( RE_IndirectDiffuse ) - - vec3 iblIrradiance = vec3( 0.0 ); - - vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); - - #if defined( USE_LIGHT_PROBES ) - - irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); - - #endif - - #if ( NUM_HEMI_LIGHTS > 0 ) - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - - irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); - - } - #pragma unroll_loop_end - - #endif - -#endif - -#if defined( RE_IndirectSpecular ) - - vec3 radiance = vec3( 0.0 ); - vec3 clearcoatRadiance = vec3( 0.0 ); - -#endif -`,lights_pars_begin:` -#if defined( USE_CSM ) && defined( CSM_CASCADES ) -uniform vec2 CSM_cascades[CSM_CASCADES]; -uniform float cameraNear; -uniform float shadowFar; -#endif - `+G0.lights_pars_begin};var bP=new RA,fP=new KU({webGL:!0}),uP=new y,pP=new g0;var mP=new RA,cP=new RA,lP=new y(0,1,0);class s0{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}var sM=new HE(-1,1,1,-1,0,1);class pN extends hA{constructor(){super();this.setAttribute("position",new PA([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new PA([0,2,0,0,2,0],2))}}var iM=new pN;class r0{constructor(A){this._mesh=new xA(iM,A)}dispose(){this._mesh.geometry.dispose()}render(A){A.render(this._mesh,sM)}get material(){return this._mesh.material}set material(A){this._mesh.material=A}}class eE{parse(A,Q={}){if(Q=Object.assign({decodeSpeed:5,encodeSpeed:5,encoderMethod:eE.MESH_EDGEBREAKER_ENCODING,quantization:[16,8,8,8,8],exportUvs:!0,exportNormals:!0,exportColor:!1},Q),DracoEncoderModule===void 0)throw new Error("THREE.DRACOExporter: required the draco_encoder to work.");let E=A.geometry,B=DracoEncoderModule(),I=new B.Encoder,C,K;if(A.isMesh===!0){C=new B.MeshBuilder,K=new B.Mesh;let O=E.getAttribute("position");C.AddFloatAttributeToMesh(K,B.POSITION,O.count,O.itemSize,O.array);let N=E.getIndex();if(N!==null)C.AddFacesToMesh(K,N.count/3,N.array);else{let $=new(O.count>65535?Uint32Array:Uint16Array)(O.count);for(let L=0;L<$.length;L++)$[L]=L;C.AddFacesToMesh(K,O.count,$)}if(Q.exportNormals===!0){let $=E.getAttribute("normal");if($!==void 0)C.AddFloatAttributeToMesh(K,B.NORMAL,$.count,$.itemSize,$.array)}if(Q.exportUvs===!0){let $=E.getAttribute("uv");if($!==void 0)C.AddFloatAttributeToMesh(K,B.TEX_COORD,$.count,$.itemSize,$.array)}if(Q.exportColor===!0){let $=E.getAttribute("color");if($!==void 0){let L=mN($);C.AddFloatAttributeToMesh(K,B.COLOR,$.count,$.itemSize,L)}}}else if(A.isPoints===!0){C=new B.PointCloudBuilder,K=new B.PointCloud;let O=E.getAttribute("position");if(C.AddFloatAttribute(K,B.POSITION,O.count,O.itemSize,O.array),Q.exportColor===!0){let N=E.getAttribute("color");if(N!==void 0){let $=mN(N);C.AddFloatAttribute(K,B.COLOR,N.count,N.itemSize,$)}}}else throw new Error("DRACOExporter: Unsupported object type.");let J=new B.DracoInt8Array,U=Q.encodeSpeed!==void 0?Q.encodeSpeed:5,Y=Q.decodeSpeed!==void 0?Q.decodeSpeed:5;if(I.SetSpeedOptions(U,Y),Q.encoderMethod!==void 0)I.SetEncodingMethod(Q.encoderMethod);if(Q.quantization!==void 0){for(let O=0;O<5;O++)if(Q.quantization[O]!==void 0)I.SetAttributeQuantization(O,Q.quantization[O])}let H;if(A.isMesh===!0)H=I.EncodeMeshToDracoBuffer(K,J);else H=I.EncodePointCloudToDracoBuffer(K,!0,J);if(B.destroy(K),H===0)throw new Error("THREE.DRACOExporter: Draco encoding failed.");let R=new Int8Array(new ArrayBuffer(H));for(let O=0;O -Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE -version 0.8.2 -*/var U6=Uint8Array,cN=Uint16Array,oM=Int32Array,rM=new U6([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,0,0,0]),aM=new U6([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,0,0]),SV=new U6([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),lN=function(A,Q){var E=new cN(31);for(var B=0;B<31;++B)E[B]=Q+=1<>1|(a0&21845)<<1,YI=(YI&52428)>>2|(YI&13107)<<2,YI=(YI&61680)>>4|(YI&3855)<<4,Aw[a0]=((YI&65280)>>8|(YI&255)<<8)>>1;var YI,a0;var UU=new U6(288);for(a0=0;a0<144;++a0)UU[a0]=8;var a0;for(a0=144;a0<256;++a0)UU[a0]=9;var a0;for(a0=256;a0<280;++a0)UU[a0]=7;var a0;for(a0=280;a0<288;++a0)UU[a0]=8;var a0,Qw=new U6(32);for(a0=0;a0<32;++a0)Qw[a0]=5;var a0;var Ew=/*@__PURE__*/new U6(0);var Bw=typeof TextDecoder!="undefined"&&/*@__PURE__*/new TextDecoder,Iw=0;try{Bw.decode(Ew,{stream:!0}),Iw=1}catch(A){}var sN={POSITION:["byte","byte normalized","unsigned byte","unsigned byte normalized","short","short normalized","unsigned short","unsigned short normalized"],NORMAL:["byte normalized","short normalized"],TANGENT:["byte normalized","short normalized"],TEXCOORD:["byte","byte normalized","unsigned byte","short","short normalized","unsigned short"]};class YU{constructor(){this.textureUtils=null,this.pluginCallbacks=[],this.register(function(A){return new QG(A)}),this.register(function(A){return new EG(A)}),this.register(function(A){return new KG(A)}),this.register(function(A){return new JG(A)}),this.register(function(A){return new UG(A)}),this.register(function(A){return new YG(A)}),this.register(function(A){return new BG(A)}),this.register(function(A){return new IG(A)}),this.register(function(A){return new CG(A)}),this.register(function(A){return new OG(A)}),this.register(function(A){return new HG(A)}),this.register(function(A){return new ZG(A)}),this.register(function(A){return new RG(A)}),this.register(function(A){return new NG(A)})}register(A){if(this.pluginCallbacks.indexOf(A)===-1)this.pluginCallbacks.push(A);return this}unregister(A){if(this.pluginCallbacks.indexOf(A)!==-1)this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(A),1);return this}setTextureUtils(A){return this.textureUtils=A,this}parse(A,Q,E,B){let I=new AG,C=[];for(let K=0,J=this.pluginCallbacks.length;K4)K=A.array[I*A.itemSize+C];else{if(C===0)K=A.getX(I);else if(C===1)K=A.getY(I);else if(C===2)K=A.getZ(I);else if(C===3)K=A.getW(I);if(A.normalized===!0)K=o0.normalize(K,A.array)}B.min[C]=Math.min(B.min[C],K),B.max[C]=Math.max(B.max[C],K)}return B}function eN(A){return Math.ceil(A/4)*4}function ZH(A,Q=0){let E=eN(A.byteLength);if(E!==A.byteLength){let B=new Uint8Array(E);if(B.set(new Uint8Array(A)),Q!==0)for(let I=A.byteLength;IA.toBlob(B,Q));let E;if(Q==="image/jpeg")E=0.92;else if(Q==="image/webp")E=0.8;return A.convertToBlob({type:Q,quality:E})}class AG{constructor(){this.plugins=[],this.options={},this.pending=[],this.buffers=[],this.byteOffset=0,this.buffers=[],this.nodeMap=/*@__PURE__*/new Map,this.skins=[],this.extensionsUsed={},this.extensionsRequired={},this.uids=/*@__PURE__*/new Map,this.uid=0,this.json={asset:{version:"2.0",generator:"THREE.GLTFExporter r"+ZB}},this.cache={meshes:/*@__PURE__*/new Map,attributes:/*@__PURE__*/new Map,attributesNormalized:/*@__PURE__*/new Map,materials:/*@__PURE__*/new Map,textures:/*@__PURE__*/new Map,images:/*@__PURE__*/new Map},this.textureUtils=null}setPlugins(A){this.plugins=A}setTextureUtils(A){this.textureUtils=A}async writeAsync(A,Q,E={}){if(this.options=Object.assign({binary:!1,trs:!1,onlyVisible:!0,maxTextureSize:1/0,animations:[],includeCustomExtensions:!1},E),this.options.animations.length>0)this.options.trs=!0;await this.processInputAsync(A),await Promise.all(this.pending);let B=this,I=B.buffers,C=B.json;E=B.options;let{extensionsUsed:K,extensionsRequired:J}=B,U=new Blob(I,{type:"application/octet-stream"}),Y=Object.keys(K),H=Object.keys(J);if(Y.length>0)C.extensionsUsed=Y;if(H.length>0)C.extensionsRequired=H;if(C.buffers&&C.buffers.length>0)C.buffers[0].byteLength=U.size;if(E.binary===!0){let R=new FileReader;R.readAsArrayBuffer(U),R.onloadend=function(){let O=ZH(R.result),N=new DataView(new ArrayBuffer(rN));N.setUint32(0,O.byteLength,!0),N.setUint32(4,Yw,!0);let $=ZH(Ow(JSON.stringify(C)),32),L=new DataView(new ArrayBuffer(rN));L.setUint32(0,$.byteLength,!0),L.setUint32(4,Uw,!0);let W=new ArrayBuffer(oN),Z=new DataView(W);Z.setUint32(0,Kw,!0),Z.setUint32(4,Jw,!0);let G=oN+L.byteLength+$.byteLength+N.byteLength+O.byteLength;Z.setUint32(8,G,!0);let X=new Blob([W,L,$,N,O],{type:"application/octet-stream"}),q=new FileReader;q.readAsArrayBuffer(X),q.onloadend=function(){Q(q.result)}}}else if(C.buffers&&C.buffers.length>0){let R=new FileReader;R.readAsDataURL(U),R.onloadend=function(){let O=R.result;C.buffers[0].uri=O,Q(C)}}else Q(C)}serializeUserData(A,Q){if(Object.keys(A.userData).length===0)return;let E=this.options,B=this.extensionsUsed;try{let I=JSON.parse(JSON.stringify(A.userData));if(E.includeCustomExtensions&&I.gltfExtensions){if(Q.extensions===void 0)Q.extensions={};for(let C in I.gltfExtensions)Q.extensions[C]=I.gltfExtensions[C],B[C]=!0;delete I.gltfExtensions}if(Object.keys(I).length>0)Q.extras=I}catch(I){console.warn("THREE.GLTFExporter: userData of '"+A.name+"' won't be serialized because of JSON.stringify error - "+I.message)}}getUID(A,Q=!1){if(this.uids.has(A)===!1){let B=/*@__PURE__*/new Map;B.set(!0,this.uid++),B.set(!1,this.uid++),this.uids.set(A,B)}return this.uids.get(A).get(Q)}isNormalizedNormalAttribute(A){if(this.cache.attributesNormalized.has(A))return!1;let E=new y;for(let B=0,I=A.count;B0.0005)return!1;return!0}createNormalizedNormalAttribute(A){let Q=this.cache;if(Q.attributesNormalized.has(A))return Q.attributesNormalized.get(A);let E=A.clone(),B=new y;for(let I=0,C=E.count;I4)L=A.array[N*A.itemSize+$];else{if($===0)L=A.getX(N);else if($===1)L=A.getY(N);else if($===2)L=A.getZ(N);else if($===3)L=A.getW(N);if(A.normalized===!0)L=o0.normalize(L,A.array)}if(Q===f0.FLOAT)Y.setFloat32(H,L,!0);else if(Q===f0.INT)Y.setInt32(H,L,!0);else if(Q===f0.UNSIGNED_INT)Y.setUint32(H,L,!0);else if(Q===f0.SHORT)Y.setInt16(H,L,!0);else if(Q===f0.UNSIGNED_SHORT)Y.setUint16(H,L,!0);else if(Q===f0.BYTE)Y.setInt8(H,L);else if(Q===f0.UNSIGNED_BYTE)Y.setUint8(H,L);H+=K}if(H%J!==0)H+=J-H%J}let R={buffer:this.processBuffer(Y.buffer),byteOffset:this.byteOffset,byteLength:U};if(I!==void 0)R.target=I;if(I===f0.ARRAY_BUFFER)R.byteStride=J;return this.byteOffset+=U,C.bufferViews.push(R),{id:C.bufferViews.length-1,byteLength:0}}processBufferViewImage(A){let Q=this,E=Q.json;if(!E.bufferViews)E.bufferViews=[];return new Promise(function(B){let I=new FileReader;I.readAsArrayBuffer(A),I.onloadend=function(){let C=ZH(I.result),K={buffer:Q.processBuffer(C),byteOffset:Q.byteOffset,byteLength:C.byteLength};Q.byteOffset+=C.byteLength,B(E.bufferViews.push(K)-1)}})}processAccessor(A,Q,E,B){let I=this.json,C={1:"SCALAR",2:"VEC2",3:"VEC3",4:"VEC4",9:"MAT3",16:"MAT4"},K;if(A.array.constructor===Float32Array)K=f0.FLOAT;else if(A.array.constructor===Int32Array)K=f0.INT;else if(A.array.constructor===Uint32Array)K=f0.UNSIGNED_INT;else if(A.array.constructor===Int16Array)K=f0.SHORT;else if(A.array.constructor===Uint16Array)K=f0.UNSIGNED_SHORT;else if(A.array.constructor===Int8Array)K=f0.BYTE;else if(A.array.constructor===Uint8Array)K=f0.UNSIGNED_BYTE;else throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: "+A.array.constructor.name);if(E===void 0)E=0;if(B===void 0||B===1/0)B=A.count;if(B===0)return null;let J=Zw(A,E,B),U;if(Q!==void 0)U=A===Q.index?f0.ELEMENT_ARRAY_BUFFER:f0.ARRAY_BUFFER;let Y=this.processBufferView(A,K,E,B,U),H={bufferView:Y.id,byteOffset:Y.byteOffset,componentType:K,count:B,max:J.max,min:J.min,type:C[A.itemSize]};if(A.normalized===!0)H.normalized=!0;if(!I.accessors)I.accessors=[];return I.accessors.push(H)-1}processImage(A,Q,E,B="image/png"){if(A!==null){let I=this,C=I.cache,K=I.json,J=I.options,U=I.pending;if(!C.images.has(A))C.images.set(A,{});let Y=C.images.get(A),H=B+":flipY/"+E.toString();if(Y[H]!==void 0)return Y[H];if(!K.images)K.images=[];let R={mimeType:B},O=aN();O.width=Math.min(A.width,J.maxTextureSize),O.height=Math.min(A.height,J.maxTextureSize);let N=O.getContext("2d",{willReadFrequently:!0});if(E===!0)N.translate(0,O.height),N.scale(1,-1);if(A.data!==void 0){if(Q!==V0)console.error("GLTFExporter: Only RGBAFormat is supported.",Q);if(A.width>J.maxTextureSize||A.height>J.maxTextureSize)console.warn("GLTFExporter: Image size is bigger than maxTextureSize",A);let L=new Uint8ClampedArray(A.height*A.width*4);for(let W=0;WI.processBufferViewImage(L)).then((L)=>{R.bufferView=L}));else if(O.toDataURL!==void 0)R.uri=O.toDataURL(B);else U.push(tN(O,B).then((L)=>new FileReader().readAsDataURL(L)).then((L)=>{R.uri=L}));let $=K.images.push(R)-1;return Y[H]=$,$}else throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture.")}processSampler(A){let Q=this.json;if(!Q.samplers)Q.samplers=[];let E={magFilter:fE[A.magFilter],minFilter:fE[A.minFilter],wrapS:fE[A.wrapS],wrapT:fE[A.wrapT]};return Q.samplers.push(E)-1}async processTextureAsync(A){let E=this.options,B=this.cache,I=this.json;if(B.textures.has(A))return B.textures.get(A);if(!I.textures)I.textures=[];if(A instanceof yE)A=await this.decompressTextureAsync(A,E.maxTextureSize);let C=A.userData.mimeType;if(C==="image/webp")C="image/png";let K={sampler:this.processSampler(A),source:this.processImage(A.image,A.format,A.flipY,C)};if(A.name)K.name=A.name;await this._invokeAllAsync(async function(U){U.writeTexture&&await U.writeTexture(A,K)});let J=I.textures.push(K)-1;return B.textures.set(A,J),J}async processMaterialAsync(A){let Q=this.cache,E=this.json;if(Q.materials.has(A))return Q.materials.get(A);if(A.isShaderMaterial)return console.warn("GLTFExporter: THREE.ShaderMaterial not supported."),null;if(!E.materials)E.materials=[];let B={pbrMetallicRoughness:{}};if(A.isMeshStandardMaterial!==!0&&A.isMeshBasicMaterial!==!0)console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.");let I=A.color.toArray().concat([A.opacity]);if(!EK(I,[1,1,1,1]))B.pbrMetallicRoughness.baseColorFactor=I;if(A.isMeshStandardMaterial)B.pbrMetallicRoughness.metallicFactor=A.metalness,B.pbrMetallicRoughness.roughnessFactor=A.roughness;else B.pbrMetallicRoughness.metallicFactor=0,B.pbrMetallicRoughness.roughnessFactor=1;if(A.metalnessMap||A.roughnessMap){let K=await this.buildMetalRoughTextureAsync(A.metalnessMap,A.roughnessMap),J={index:await this.processTextureAsync(K),texCoord:K.channel};this.applyTextureTransform(J,K),B.pbrMetallicRoughness.metallicRoughnessTexture=J}if(A.map){let K={index:await this.processTextureAsync(A.map),texCoord:A.map.channel};this.applyTextureTransform(K,A.map),B.pbrMetallicRoughness.baseColorTexture=K}if(A.emissive){let K=A.emissive;if(Math.max(K.r,K.g,K.b)>0)B.emissiveFactor=A.emissive.toArray();if(A.emissiveMap){let U={index:await this.processTextureAsync(A.emissiveMap),texCoord:A.emissiveMap.channel};this.applyTextureTransform(U,A.emissiveMap),B.emissiveTexture=U}}if(A.normalMap){let K={index:await this.processTextureAsync(A.normalMap),texCoord:A.normalMap.channel};if(A.normalScale&&A.normalScale.x!==1)K.scale=A.normalScale.x;this.applyTextureTransform(K,A.normalMap),B.normalTexture=K}if(A.aoMap){let K={index:await this.processTextureAsync(A.aoMap),texCoord:A.aoMap.channel};if(A.aoMapIntensity!==1)K.strength=A.aoMapIntensity;this.applyTextureTransform(K,A.aoMap),B.occlusionTexture=K}if(A.transparent)B.alphaMode="BLEND";else if(A.alphaTest>0)B.alphaMode="MASK",B.alphaCutoff=A.alphaTest;if(A.side===y0)B.doubleSided=!0;if(A.name!=="")B.name=A.name;this.serializeUserData(A,B),await this._invokeAllAsync(async function(K){K.writeMaterialAsync&&await K.writeMaterialAsync(A,B)});let C=E.materials.push(B)-1;return Q.materials.set(A,C),C}async processMeshAsync(A){let Q=this.cache,E=this.json,B=[A.geometry.uuid];if(Array.isArray(A.material))for(let X=0,q=A.material.length;X0){let X=[],q=[],M={};if(A.morphTargetDictionary!==void 0)for(let F in A.morphTargetDictionary)M[A.morphTargetDictionary[F]]=F;for(let F=0;F0)J.extras={},J.extras.targetNames=q}let $=Array.isArray(A.material);if($&&C.groups.length===0)return null;let L=!1;if($&&C.index===null){let X=[];for(let q=0,M=C.attributes.position.count;q0)M.targets=H;if(C.index!==null){let D=this.getUID(C.index);if(Z[X].start!==void 0||Z[X].count!==void 0)D+=":"+Z[X].start+":"+Z[X].count;if(Q.attributes.has(D))M.indices=Q.attributes.get(D);else M.indices=this.processAccessor(C.index,C,Z[X].start,Z[X].count),Q.attributes.set(D,M.indices);if(M.indices===null)delete M.indices}let F=await this.processMaterialAsync(W[Z[X].materialIndex]);if(F!==null)M.material=F;Y.push(M)}if(L===!0)C.setIndex(null);if(J.primitives=Y,!E.meshes)E.meshes=[];await this._invokeAllAsync(function(X){X.writeMesh&&X.writeMesh(A,J)});let G=E.meshes.push(J)-1;return Q.meshes.set(I,G),G}detectMeshQuantization(A,Q){if(this.extensionsUsed[HH])return;let E=void 0;switch(Q.array.constructor){case Int8Array:E="byte";break;case Uint8Array:E="unsigned byte";break;case Int16Array:E="short";break;case Uint16Array:E="unsigned short";break;default:return}if(Q.normalized)E+=" normalized";let B=A.split("_",1)[0];if(sN[B]&&sN[B].includes(E))this.extensionsUsed[HH]=!0,this.extensionsRequired[HH]=!0}processCamera(A){let Q=this.json;if(!Q.cameras)Q.cameras=[];let E=A.isOrthographicCamera,B={type:E?"orthographic":"perspective"};if(E)B.orthographic={xmag:A.right*2,ymag:A.top*2,zfar:A.far<=0?0.001:A.far,znear:A.near<0?0:A.near};else B.perspective={aspectRatio:A.aspect,yfov:o0.degToRad(A.fov),zfar:A.far<=0?0.001:A.far,znear:A.near<0?0:A.near};if(A.name!=="")B.name=A.type;return Q.cameras.push(B)-1}processAnimation(A,Q){let E=this.json,B=this.nodeMap;if(!E.animations)E.animations=[];A=YU.Utils.mergeMorphTargetTracks(A.clone(),Q);let I=A.tracks,C=[],K=[];for(let J=0;J0){let K=[];for(let J=0,U=A.children.length;J0)I.children=K}await this._invokeAllAsync(function(K){K.writeNode&&K.writeNode(A,I)});let C=Q.nodes.push(I)-1;return B.set(A,C),C}async processSceneAsync(A){let Q=this.json,E=this.options;if(!Q.scenes)Q.scenes=[],Q.scene=0;let B={};if(A.name!=="")B.name=A.name;Q.scenes.push(B);let I=[];for(let C=0,K=A.children.length;C0)B.nodes=I;this.serializeUserData(A,B)}async processObjectsAsync(A){let Q=new yQ;Q.name="AuxScene";for(let E=0;E0)await this.processObjectsAsync(E);for(let B=0;B0)C.range=A.distance}else if(A.isSpotLight){if(C.type="spot",A.distance>0)C.range=A.distance;C.spot={},C.spot.innerConeAngle=(1-A.penumbra)*A.angle,C.spot.outerConeAngle=A.angle}if(A.decay!==void 0&&A.decay!==2)console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2.");if(A.target&&(A.target.parent!==A||A.target.position.x!==0||A.target.position.y!==0||A.target.position.z!==-1))console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, make light.target a child of the light with position 0,0,-1.");if(!I[this.name])B.extensions=B.extensions||{},B.extensions[this.name]={lights:[]},I[this.name]=!0;let K=B.extensions[this.name].lights;K.push(C),Q.extensions=Q.extensions||{},Q.extensions[this.name]={light:K.length-1}}}class EG{constructor(A){this.writer=A,this.name="KHR_materials_unlit"}async writeMaterialAsync(A,Q){if(!A.isMeshBasicMaterial)return;let B=this.writer.extensionsUsed;Q.extensions=Q.extensions||{},Q.extensions[this.name]={},B[this.name]=!0,Q.pbrMetallicRoughness.metallicFactor=0,Q.pbrMetallicRoughness.roughnessFactor=0.9}}class BG{constructor(A){this.writer=A,this.name="KHR_materials_clearcoat"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.clearcoat===0)return;let E=this.writer,B=E.extensionsUsed,I={};if(I.clearcoatFactor=A.clearcoat,A.clearcoatMap){let C={index:await E.processTextureAsync(A.clearcoatMap),texCoord:A.clearcoatMap.channel};E.applyTextureTransform(C,A.clearcoatMap),I.clearcoatTexture=C}if(I.clearcoatRoughnessFactor=A.clearcoatRoughness,A.clearcoatRoughnessMap){let C={index:await E.processTextureAsync(A.clearcoatRoughnessMap),texCoord:A.clearcoatRoughnessMap.channel};E.applyTextureTransform(C,A.clearcoatRoughnessMap),I.clearcoatRoughnessTexture=C}if(A.clearcoatNormalMap){let C={index:await E.processTextureAsync(A.clearcoatNormalMap),texCoord:A.clearcoatNormalMap.channel};if(A.clearcoatNormalScale.x!==1)C.scale=A.clearcoatNormalScale.x;E.applyTextureTransform(C,A.clearcoatNormalMap),I.clearcoatNormalTexture=C}Q.extensions=Q.extensions||{},Q.extensions[this.name]=I,B[this.name]=!0}}class IG{constructor(A){this.writer=A,this.name="KHR_materials_dispersion"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.dispersion===0)return;let B=this.writer.extensionsUsed,I={};I.dispersion=A.dispersion,Q.extensions=Q.extensions||{},Q.extensions[this.name]=I,B[this.name]=!0}}class CG{constructor(A){this.writer=A,this.name="KHR_materials_iridescence"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.iridescence===0)return;let E=this.writer,B=E.extensionsUsed,I={};if(I.iridescenceFactor=A.iridescence,A.iridescenceMap){let C={index:await E.processTextureAsync(A.iridescenceMap),texCoord:A.iridescenceMap.channel};E.applyTextureTransform(C,A.iridescenceMap),I.iridescenceTexture=C}if(I.iridescenceIor=A.iridescenceIOR,I.iridescenceThicknessMinimum=A.iridescenceThicknessRange[0],I.iridescenceThicknessMaximum=A.iridescenceThicknessRange[1],A.iridescenceThicknessMap){let C={index:await E.processTextureAsync(A.iridescenceThicknessMap),texCoord:A.iridescenceThicknessMap.channel};E.applyTextureTransform(C,A.iridescenceThicknessMap),I.iridescenceThicknessTexture=C}Q.extensions=Q.extensions||{},Q.extensions[this.name]=I,B[this.name]=!0}}class KG{constructor(A){this.writer=A,this.name="KHR_materials_transmission"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.transmission===0)return;let E=this.writer,B=E.extensionsUsed,I={};if(I.transmissionFactor=A.transmission,A.transmissionMap){let C={index:await E.processTextureAsync(A.transmissionMap),texCoord:A.transmissionMap.channel};E.applyTextureTransform(C,A.transmissionMap),I.transmissionTexture=C}Q.extensions=Q.extensions||{},Q.extensions[this.name]=I,B[this.name]=!0}}class JG{constructor(A){this.writer=A,this.name="KHR_materials_volume"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.transmission===0)return;let E=this.writer,B=E.extensionsUsed,I={};if(I.thicknessFactor=A.thickness,A.thicknessMap){let C={index:await E.processTextureAsync(A.thicknessMap),texCoord:A.thicknessMap.channel};E.applyTextureTransform(C,A.thicknessMap),I.thicknessTexture=C}if(A.attenuationDistance!==1/0)I.attenuationDistance=A.attenuationDistance;I.attenuationColor=A.attenuationColor.toArray(),Q.extensions=Q.extensions||{},Q.extensions[this.name]=I,B[this.name]=!0}}class UG{constructor(A){this.writer=A,this.name="KHR_materials_ior"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.ior===1.5)return;let B=this.writer.extensionsUsed,I={};I.ior=A.ior,Q.extensions=Q.extensions||{},Q.extensions[this.name]=I,B[this.name]=!0}}class YG{constructor(A){this.writer=A,this.name="KHR_materials_specular"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.specularIntensity===1&&A.specularColor.equals(Cw)&&!A.specularIntensityMap&&!A.specularColorMap)return;let E=this.writer,B=E.extensionsUsed,I={};if(A.specularIntensityMap){let C={index:await E.processTextureAsync(A.specularIntensityMap),texCoord:A.specularIntensityMap.channel};E.applyTextureTransform(C,A.specularIntensityMap),I.specularTexture=C}if(A.specularColorMap){let C={index:await E.processTextureAsync(A.specularColorMap),texCoord:A.specularColorMap.channel};E.applyTextureTransform(C,A.specularColorMap),I.specularColorTexture=C}I.specularFactor=A.specularIntensity,I.specularColorFactor=A.specularColor.toArray(),Q.extensions=Q.extensions||{},Q.extensions[this.name]=I,B[this.name]=!0}}class OG{constructor(A){this.writer=A,this.name="KHR_materials_sheen"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.sheen==0)return;let E=this.writer,B=E.extensionsUsed,I={};if(A.sheenRoughnessMap){let C={index:await E.processTextureAsync(A.sheenRoughnessMap),texCoord:A.sheenRoughnessMap.channel};E.applyTextureTransform(C,A.sheenRoughnessMap),I.sheenRoughnessTexture=C}if(A.sheenColorMap){let C={index:await E.processTextureAsync(A.sheenColorMap),texCoord:A.sheenColorMap.channel};E.applyTextureTransform(C,A.sheenColorMap),I.sheenColorTexture=C}I.sheenRoughnessFactor=A.sheenRoughness,I.sheenColorFactor=A.sheenColor.toArray(),Q.extensions=Q.extensions||{},Q.extensions[this.name]=I,B[this.name]=!0}}class HG{constructor(A){this.writer=A,this.name="KHR_materials_anisotropy"}async writeMaterialAsync(A,Q){if(!A.isMeshPhysicalMaterial||A.anisotropy==0)return;let E=this.writer,B=E.extensionsUsed,I={};if(A.anisotropyMap){let C={index:await E.processTextureAsync(A.anisotropyMap)};E.applyTextureTransform(C,A.anisotropyMap),I.anisotropyTexture=C}I.anisotropyStrength=A.anisotropy,I.anisotropyRotation=A.anisotropyRotation,Q.extensions=Q.extensions||{},Q.extensions[this.name]=I,B[this.name]=!0}}class ZG{constructor(A){this.writer=A,this.name="KHR_materials_emissive_strength"}async writeMaterialAsync(A,Q){if(!A.isMeshStandardMaterial||A.emissiveIntensity===1)return;let B=this.writer.extensionsUsed,I={};I.emissiveStrength=A.emissiveIntensity,Q.extensions=Q.extensions||{},Q.extensions[this.name]=I,B[this.name]=!0}}class RG{constructor(A){this.writer=A,this.name="EXT_materials_bump"}async writeMaterialAsync(A,Q){if(!A.isMeshStandardMaterial||A.bumpScale===1&&!A.bumpMap)return;let E=this.writer,B=E.extensionsUsed,I={};if(A.bumpMap){let C={index:await E.processTextureAsync(A.bumpMap),texCoord:A.bumpMap.channel};E.applyTextureTransform(C,A.bumpMap),I.bumpTexture=C}I.bumpFactor=A.bumpScale,Q.extensions=Q.extensions||{},Q.extensions[this.name]=I,B[this.name]=!0}}class NG{constructor(A){this.writer=A,this.name="EXT_mesh_gpu_instancing"}writeNode(A,Q){if(!A.isInstancedMesh)return;let E=this.writer,B=A,I=new Float32Array(B.count*3),C=new Float32Array(B.count*4),K=new Float32Array(B.count*3),J=new RA,U=new y,Y=new J0,H=new y;for(let O=0;OA.times[A.times.length-1]){if(Math.abs(A.times[A.times.length-1]-Q)<0.001)return A.times.length-1;I[I.length-1]=Q,I.set(A.times,0),C.set(A.values,0),C.set(K.evaluate(Q),A.values.length),J=I.length-1}else for(let U=0;UQ){I.set(A.times.slice(0,U+1),0),I[U+1]=Q,I.set(A.times.slice(U+1),U+2),C.set(A.values.slice(0,(U+1)*B),0),C.set(K.evaluate(Q),(U+1)*B),C.set(A.values.slice((U+1)*B),(U+2)*B),J=U+1;break}}return A.times=I,A.values=C,J},mergeMorphTargetTracks:function(A,Q){let E=[],B={},I=A.tracks;for(let C=0;CC.set(B,I,Math.cos(B)*Math.sin(I)),Q=8,E=8){super();this.type="ParametricGeometry",this.parameters={func:A,slices:Q,stacks:E};let B=[],I=[],C=[],K=[],J=0.00001,U=new y,Y=new y,H=new y,R=new y,O=new y,N=Q+1;for(let $=0;$<=E;$++){let L=$/E;for(let W=0;W<=Q;W++){let Z=W/Q;if(A(Z,L,Y),I.push(Y.x,Y.y,Y.z),Z-J>=0)A(Z-J,L,H),R.subVectors(Y,H);else A(Z+J,L,H),R.subVectors(H,Y);if(L-J>=0)A(Z,L-J,H),O.subVectors(Y,H);else A(Z,L+J,H),O.subVectors(H,Y);U.crossVectors(R,O).normalize(),C.push(U.x,U.y,U.z),K.push(Z,L)}}for(let $=0;$ - #include - #include - #include - #include - - uniform float linewidth; - uniform vec2 resolution; - - attribute vec3 instanceStart; - attribute vec3 instanceEnd; - - attribute vec3 instanceColorStart; - attribute vec3 instanceColorEnd; - - #ifdef WORLD_UNITS - - varying vec4 worldPos; - varying vec3 worldStart; - varying vec3 worldEnd; - - #ifdef USE_DASH - - varying vec2 vUv; - - #endif - - #else - - varying vec2 vUv; - - #endif - - #ifdef USE_DASH - - uniform float dashScale; - attribute float instanceDistanceStart; - attribute float instanceDistanceEnd; - varying float vLineDistance; - - #endif - - void trimSegment( const in vec4 start, inout vec4 end ) { - - // trim end segment so it terminates between the camera plane and the near plane - - // conservative estimate of the near plane - float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column - float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column - float nearEstimate = - 0.5 * b / a; - - float alpha = ( nearEstimate - start.z ) / ( end.z - start.z ); - - end.xyz = mix( start.xyz, end.xyz, alpha ); - - } - - void main() { - - #ifdef USE_COLOR - - vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd; - - #endif - - #ifdef USE_DASH - - vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd; - vUv = uv; - - #endif - - float aspect = resolution.x / resolution.y; - - // camera space - vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 ); - vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 ); - - #ifdef WORLD_UNITS - - worldStart = start.xyz; - worldEnd = end.xyz; - - #else - - vUv = uv; - - #endif - - // special case for perspective projection, and segments that terminate either in, or behind, the camera plane - // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space - // but we need to perform ndc-space calculations in the shader, so we must address this issue directly - // perhaps there is a more elegant solution -- WestLangley - - bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column - - if ( perspective ) { - - if ( start.z < 0.0 && end.z >= 0.0 ) { - - trimSegment( start, end ); - - } else if ( end.z < 0.0 && start.z >= 0.0 ) { - - trimSegment( end, start ); - - } - - } - - // clip space - vec4 clipStart = projectionMatrix * start; - vec4 clipEnd = projectionMatrix * end; - - // ndc space - vec3 ndcStart = clipStart.xyz / clipStart.w; - vec3 ndcEnd = clipEnd.xyz / clipEnd.w; - - // direction - vec2 dir = ndcEnd.xy - ndcStart.xy; - - // account for clip-space aspect ratio - dir.x *= aspect; - dir = normalize( dir ); - - #ifdef WORLD_UNITS - - vec3 worldDir = normalize( end.xyz - start.xyz ); - vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) ); - vec3 worldUp = normalize( cross( worldDir, tmpFwd ) ); - vec3 worldFwd = cross( worldDir, worldUp ); - worldPos = position.y < 0.5 ? start: end; - - // height offset - float hw = linewidth * 0.5; - worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp; - - // don't extend the line if we're rendering dashes because we - // won't be rendering the endcaps - #ifndef USE_DASH - - // cap extension - worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir; - - // add width to the box - worldPos.xyz += worldFwd * hw; - - // endcaps - if ( position.y > 1.0 || position.y < 0.0 ) { - - worldPos.xyz -= worldFwd * 2.0 * hw; - - } - - #endif - - // project the worldpos - vec4 clip = projectionMatrix * worldPos; - - // shift the depth of the projected points so the line - // segments overlap neatly - vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd; - clip.z = clipPose.z * clip.w; - - #else - - vec2 offset = vec2( dir.y, - dir.x ); - // undo aspect ratio adjustment - dir.x /= aspect; - offset.x /= aspect; - - // sign flip - if ( position.x < 0.0 ) offset *= - 1.0; - - // endcaps - if ( position.y < 0.0 ) { - - offset += - dir; - - } else if ( position.y > 1.0 ) { - - offset += dir; - - } - - // adjust for linewidth - offset *= linewidth; - - // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ... - offset /= resolution.y; - - // select end - vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd; - - // back to clip space - offset *= clip.w; - - clip.xy += offset; - - #endif - - gl_Position = clip; - - vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation - - #include - #include - #include - - } - `,fragmentShader:` - uniform vec3 diffuse; - uniform float opacity; - uniform float linewidth; - - #ifdef USE_DASH - - uniform float dashOffset; - uniform float dashSize; - uniform float gapSize; - - #endif - - varying float vLineDistance; - - #ifdef WORLD_UNITS - - varying vec4 worldPos; - varying vec3 worldStart; - varying vec3 worldEnd; - - #ifdef USE_DASH - - varying vec2 vUv; - - #endif - - #else - - varying vec2 vUv; - - #endif - - #include - #include - #include - #include - #include - - vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) { - - float mua; - float mub; - - vec3 p13 = p1 - p3; - vec3 p43 = p4 - p3; - - vec3 p21 = p2 - p1; - - float d1343 = dot( p13, p43 ); - float d4321 = dot( p43, p21 ); - float d1321 = dot( p13, p21 ); - float d4343 = dot( p43, p43 ); - float d2121 = dot( p21, p21 ); - - float denom = d2121 * d4343 - d4321 * d4321; - - float numer = d1343 * d4321 - d1321 * d4343; - - mua = numer / denom; - mua = clamp( mua, 0.0, 1.0 ); - mub = ( d1343 + d4321 * ( mua ) ) / d4343; - mub = clamp( mub, 0.0, 1.0 ); - - return vec2( mua, mub ); - - } - - void main() { - - #include - - #ifdef USE_DASH - - if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps - - if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX - - #endif - - float alpha = opacity; - - #ifdef WORLD_UNITS - - // Find the closest points on the view ray and the line segment - vec3 rayEnd = normalize( worldPos.xyz ) * 1e5; - vec3 lineDir = worldEnd - worldStart; - vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd ); - - vec3 p1 = worldStart + lineDir * params.x; - vec3 p2 = rayEnd * params.y; - vec3 delta = p1 - p2; - float len = length( delta ); - float norm = len / linewidth; - - #ifndef USE_DASH - - #ifdef USE_ALPHA_TO_COVERAGE - - float dnorm = fwidth( norm ); - alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm ); - - #else - - if ( norm > 0.5 ) { - - discard; - - } - - #endif - - #endif - - #else - - #ifdef USE_ALPHA_TO_COVERAGE - - // artifacts appear on some hardware if a derivative is taken within a conditional - float a = vUv.x; - float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; - float len2 = a * a + b * b; - float dlen = fwidth( len2 ); - - if ( abs( vUv.y ) > 1.0 ) { - - alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 ); - - } - - #else - - if ( abs( vUv.y ) > 1.0 ) { - - float a = vUv.x; - float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; - float len2 = a * a + b * b; - - if ( len2 > 1.0 ) discard; - - } - - #endif - - #endif - - vec4 diffuseColor = vec4( diffuse, alpha ); - - #include - #include - - gl_FragColor = vec4( diffuseColor.rgb, alpha ); - - #include - #include - #include - #include - - } - `};var ov=new MA,rv=new y,av=new y,tv=new MA,ev=new MA,Ah=new MA,Qh=new y,Eh=new RA,Bh=new $B,Ih=new y,Ch=new g0,Kh=new KQ,Jh=new MA;var qh=new y,Fh=new y,Dh=new MA;var th=new DQ,eh=new y;class YK extends C0{constructor(A){super(A);this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(Q){return new PG(Q)}),this.register(function(Q){return new VG(Q)}),this.register(function(Q){return new uG(Q)}),this.register(function(Q){return new pG(Q)}),this.register(function(Q){return new mG(Q)}),this.register(function(Q){return new vG(Q)}),this.register(function(Q){return new hG(Q)}),this.register(function(Q){return new yG(Q)}),this.register(function(Q){return new gG(Q)}),this.register(function(Q){return new zG(Q)}),this.register(function(Q){return new xG(Q)}),this.register(function(Q){return new jG(Q)}),this.register(function(Q){return new fG(Q)}),this.register(function(Q){return new bG(Q)}),this.register(function(Q){return new SG(Q)}),this.register(function(Q){return new cG(Q)}),this.register(function(Q){return new lG(Q)})}load(A,Q,E,B){let I=this,C;if(this.resourcePath!=="")C=this.resourcePath;else if(this.path!==""){let U=QE.extractUrlBase(A);C=QE.resolveURL(U,this.path)}else C=QE.extractUrlBase(A);this.manager.itemStart(A);let K=function(U){if(B)B(U);else console.error(U);I.manager.itemError(A),I.manager.itemEnd(A)},J=new U0(this.manager);J.setPath(this.path),J.setResponseType("arraybuffer"),J.setRequestHeader(this.requestHeader),J.setWithCredentials(this.withCredentials),J.load(A,function(U){try{I.parse(U,C,function(Y){Q(Y),I.manager.itemEnd(A)},K)}catch(Y){K(Y)}},E,K)}setDRACOLoader(A){return this.dracoLoader=A,this}setKTX2Loader(A){return this.ktx2Loader=A,this}setMeshoptDecoder(A){return this.meshoptDecoder=A,this}register(A){if(this.pluginCallbacks.indexOf(A)===-1)this.pluginCallbacks.push(A);return this}unregister(A){if(this.pluginCallbacks.indexOf(A)!==-1)this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(A),1);return this}parse(A,Q,E,B){let I,C={},K={},J=/*@__PURE__*/new TextDecoder;if(typeof A==="string")I=JSON.parse(A);else if(A instanceof ArrayBuffer)if(J.decode(new Uint8Array(A,0,4))===dG){try{C[u0.KHR_BINARY_GLTF]=new nG(A)}catch(H){if(B)B(H);return}I=JSON.parse(C[u0.KHR_BINARY_GLTF].content)}else I=JSON.parse(J.decode(A));else I=A;if(I.asset===void 0||I.asset.version[0]<2){if(B)B(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let U=new aG(I,{path:Q||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});U.fileLoader.setRequestHeader(this.requestHeader);for(let Y=0;Y=0&&K[H]===void 0)console.warn('THREE.GLTFLoader: Unknown extension "'+H+'".')}}U.setExtensions(C),U.setPlugins(K),U.parse(E,B)}parseAsync(A,Q){let E=this;return new Promise(function(B,I){E.parse(A,Q,B,I)})}}function Nw(){let A={};return{get:function(Q){return A[Q]},add:function(Q,E){A[Q]=E},remove:function(Q){delete A[Q]},removeAll:function(){A={}}}}var u0={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class SG{constructor(A){this.parser=A,this.name=u0.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let A=this.parser,Q=this.parser.json.nodes||[];for(let E=0,B=Q.length;E=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");else return null;return Q.loadTextureImage(A,I.source,C)}}class pG{constructor(A){this.parser=A,this.name=u0.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(A){let Q=this.name,E=this.parser,B=E.json,I=B.textures[A];if(!I.extensions||!I.extensions[Q])return null;let C=I.extensions[Q],K=B.images[C.source],J=E.textureLoader;if(K.uri){let U=E.options.manager.getHandler(K.uri);if(U!==null)J=U}return this.detectSupport().then(function(U){if(U)return E.loadTextureImage(A,C.source,J);if(B.extensionsRequired&&B.extensionsRequired.indexOf(Q)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return E.loadTexture(A)})}detectSupport(){if(!this.isSupported)this.isSupported=new Promise(function(A){let Q=new Image;Q.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",Q.onload=Q.onerror=function(){A(Q.height===1)}});return this.isSupported}}class mG{constructor(A){this.parser=A,this.name=u0.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(A){let Q=this.name,E=this.parser,B=E.json,I=B.textures[A];if(!I.extensions||!I.extensions[Q])return null;let C=I.extensions[Q],K=B.images[C.source],J=E.textureLoader;if(K.uri){let U=E.options.manager.getHandler(K.uri);if(U!==null)J=U}return this.detectSupport().then(function(U){if(U)return E.loadTextureImage(A,C.source,J);if(B.extensionsRequired&&B.extensionsRequired.indexOf(Q)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return E.loadTexture(A)})}detectSupport(){if(!this.isSupported)this.isSupported=new Promise(function(A){let Q=new Image;Q.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",Q.onload=Q.onerror=function(){A(Q.height===1)}});return this.isSupported}}class cG{constructor(A){this.name=u0.EXT_MESHOPT_COMPRESSION,this.parser=A}loadBufferView(A){let Q=this.parser.json,E=Q.bufferViews[A];if(E.extensions&&E.extensions[this.name]){let B=E.extensions[this.name],I=this.parser.getDependency("buffer",B.buffer),C=this.parser.options.meshoptDecoder;if(!C||!C.supported)if(Q.extensionsRequired&&Q.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");else return null;return I.then(function(K){let J=B.byteOffset||0,U=B.byteLength||0,Y=B.count,H=B.byteStride,R=new Uint8Array(K,J,U);if(C.decodeGltfBufferAsync)return C.decodeGltfBufferAsync(Y,H,R,B.mode,B.filter).then(function(O){return O.buffer});else return C.ready.then(function(){let O=new ArrayBuffer(Y*H);return C.decodeGltfBuffer(new Uint8Array(O),Y,H,R,B.mode,B.filter),O})})}else return null}}class lG{constructor(A){this.name=u0.EXT_MESH_GPU_INSTANCING,this.parser=A}createNodeMesh(A){let Q=this.parser.json,E=Q.nodes[A];if(!E.extensions||!E.extensions[this.name]||E.mesh===void 0)return null;let B=Q.meshes[E.mesh];for(let U of B.primitives)if(U.mode!==AB.TRIANGLES&&U.mode!==AB.TRIANGLE_STRIP&&U.mode!==AB.TRIANGLE_FAN&&U.mode!==void 0)return null;let C=E.extensions[this.name].attributes,K=[],J={};for(let U in C)K.push(this.parser.getDependency("accessor",C[U]).then((Y)=>{return J[U]=Y,J[U]}));if(K.length<1)return null;return K.push(this.parser.createNodeMesh(A)),Promise.all(K).then((U)=>{let Y=U.pop(),H=Y.isGroup?Y.children:[Y],R=U[0].count,O=[];for(let N of H){let $=new RA,L=new y,W=new J0,Z=new y(1,1,1),G=new vI(N.geometry,N.material,R);for(let X=0;X0||A.search(/^data\:image\/jpeg/)===0)return"image/jpeg";if(A.search(/\.webp($|\?)/i)>0||A.search(/^data\:image\/webp/)===0)return"image/webp";if(A.search(/\.ktx2($|\?)/i)>0||A.search(/^data\:image\/ktx2/)===0)return"image/ktx2";return"image/png"}var Dw=new RA;class aG{constructor(A={},Q={}){this.json=A,this.extensions={},this.plugins={},this.options=Q,this.cache=new Nw,this.associations=/*@__PURE__*/new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let E=!1,B=-1,I=!1,C=-1;if(typeof navigator!=="undefined"){let K=navigator.userAgent;E=/^((?!chrome|android).)*safari/i.test(K)===!0;let J=K.match(/Version\/(\d+)/);B=E&&J?parseInt(J[1],10):-1,I=K.indexOf("Firefox")>-1,C=I?K.match(/Firefox\/([0-9]+)\./)[1]:-1}if(typeof createImageBitmap==="undefined"||E&&B<17||I&&C<98)this.textureLoader=new nQ(this.options.manager);else this.textureLoader=new iC(this.options.manager);if(this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new U0(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials")this.fileLoader.setWithCredentials(!0)}setExtensions(A){this.extensions=A}setPlugins(A){this.plugins=A}parse(A,Q){let E=this,B=this.json,I=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(C){return C._markDefs&&C._markDefs()}),Promise.all(this._invokeAll(function(C){return C.beforeRoot&&C.beforeRoot()})).then(function(){return Promise.all([E.getDependencies("scene"),E.getDependencies("animation"),E.getDependencies("camera")])}).then(function(C){let K={scene:C[0][B.scene||0],scenes:C[0],animations:C[1],cameras:C[2],asset:B.asset,parser:E,userData:{}};return c1(I,K,B),HI(K,B),Promise.all(E._invokeAll(function(J){return J.afterRoot&&J.afterRoot(K)})).then(function(){for(let J of K.scenes)J.updateMatrixWorld();A(K)})}).catch(Q)}_markDefs(){let A=this.json.nodes||[],Q=this.json.skins||[],E=this.json.meshes||[];for(let B=0,I=Q.length;B{let J=this.associations.get(C);if(J!=null)this.associations.set(K,J);for(let[U,Y]of C.children.entries())I(Y,K.children[U])};return I(E,B),B.name+="_instance_"+A.uses[Q]++,B}_invokeOne(A){let Q=Object.values(this.plugins);Q.push(this);for(let E=0;E=2)L.setY(_,M[F*J+1]);if(J>=3)L.setZ(_,M[F*J+2]);if(J>=4)L.setW(_,M[F*J+3]);if(J>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}L.normalized=N}return L})}loadTexture(A){let Q=this.json,E=this.options,I=Q.textures[A].source,C=Q.images[I],K=this.textureLoader;if(C.uri){let J=E.manager.getHandler(C.uri);if(J!==null)K=J}return this.loadTextureImage(A,I,K)}loadTextureImage(A,Q,E){let B=this,I=this.json,C=I.textures[A],K=I.images[Q],J=(K.uri||K.bufferView)+":"+C.sampler;if(this.textureCache[J])return this.textureCache[J];let U=this.loadImageSource(Q,E).then(function(Y){if(Y.flipY=!1,Y.name=C.name||K.name||"",Y.name===""&&typeof K.uri==="string"&&K.uri.startsWith("data:image/")===!1)Y.name=K.uri;let R=(I.samplers||{})[C.sampler]||{};return Y.magFilter=wG[R.magFilter]||L0,Y.minFilter=wG[R.minFilter]||hQ,Y.wrapS=_G[R.wrapS]||BQ,Y.wrapT=_G[R.wrapT]||BQ,Y.generateMipmaps=!Y.isCompressedTexture&&Y.minFilter!==Z0&&Y.minFilter!==L0,B.associations.set(Y,{textures:A}),Y}).catch(function(){return null});return this.textureCache[J]=U,U}loadImageSource(A,Q){let E=this,B=this.json,I=this.options;if(this.sourceCache[A]!==void 0)return this.sourceCache[A].then((H)=>H.clone());let C=B.images[A],K=self.URL||self.webkitURL,J=C.uri||"",U=!1;if(C.bufferView!==void 0)J=E.getDependency("bufferView",C.bufferView).then(function(H){U=!0;let R=new Blob([H],{type:C.mimeType});return J=K.createObjectURL(R),J});else if(C.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+A+" is missing URI and bufferView");let Y=Promise.resolve(J).then(function(H){return new Promise(function(R,O){let N=R;if(Q.isImageBitmapLoader===!0)N=function($){let L=new EQ($);L.needsUpdate=!0,R(L)};Q.load(QE.resolveURL(H,I.path),N,void 0,O)})}).then(function(H){if(U===!0)K.revokeObjectURL(J);return HI(H,C),H.userData.mimeType=C.mimeType||Fw(C.uri),H}).catch(function(H){throw console.error("THREE.GLTFLoader: Couldn't load texture",J),H});return this.sourceCache[A]=Y,Y}assignTexture(A,Q,E,B){let I=this;return this.getDependency("texture",E.index).then(function(C){if(!C)return null;if(E.texCoord!==void 0&&E.texCoord>0)C=C.clone(),C.channel=E.texCoord;if(I.extensions[u0.KHR_TEXTURE_TRANSFORM]){let K=E.extensions!==void 0?E.extensions[u0.KHR_TEXTURE_TRANSFORM]:void 0;if(K){let J=I.associations.get(C);C=I.extensions[u0.KHR_TEXTURE_TRANSFORM].extendTexture(C,K),I.associations.set(C,J)}}if(B!==void 0)C.colorSpace=B;return A[Q]=C,C})}assignFinalMaterial(A){let{geometry:Q,material:E}=A,B=Q.attributes.tangent===void 0,I=Q.attributes.color!==void 0,C=Q.attributes.normal===void 0;if(A.isPoints){let K="PointsMaterial:"+E.uuid,J=this.cache.get(K);if(!J)J=new aE,$Q.prototype.copy.call(J,E),J.color.copy(E.color),J.map=E.map,J.sizeAttenuation=!1,this.cache.add(K,J);E=J}else if(A.isLine){let K="LineBasicMaterial:"+E.uuid,J=this.cache.get(K);if(!J)J=new p0,$Q.prototype.copy.call(J,E),J.color.copy(E.color),J.map=E.map,this.cache.add(K,J);E=J}if(B||I||C){let K="ClonedMaterial:"+E.uuid+":";if(B)K+="derivative-tangents:";if(I)K+="vertex-colors:";if(C)K+="flat-shading:";let J=this.cache.get(K);if(!J){if(J=E.clone(),I)J.vertexColors=!0;if(C)J.flatShading=!0;if(B){if(J.normalScale)J.normalScale.y*=-1;if(J.clearcoatNormalScale)J.clearcoatNormalScale.y*=-1}this.cache.add(K,J),this.associations.set(J,this.associations.get(E))}E=J}A.material=E}getMaterialType(){return aQ}loadMaterial(A){let Q=this,E=this.json,B=this.extensions,I=E.materials[A],C,K={},J=I.extensions||{},U=[];if(J[u0.KHR_MATERIALS_UNLIT]){let H=B[u0.KHR_MATERIALS_UNLIT];C=H.getMaterialType(),U.push(H.extendParams(K,I,Q))}else{let H=I.pbrMetallicRoughness||{};if(K.color=new a(1,1,1),K.opacity=1,Array.isArray(H.baseColorFactor)){let R=H.baseColorFactor;K.color.setRGB(R[0],R[1],R[2],b0),K.opacity=R[3]}if(H.baseColorTexture!==void 0)U.push(Q.assignTexture(K,"map",H.baseColorTexture,N0));if(K.metalness=H.metallicFactor!==void 0?H.metallicFactor:1,K.roughness=H.roughnessFactor!==void 0?H.roughnessFactor:1,H.metallicRoughnessTexture!==void 0)U.push(Q.assignTexture(K,"metalnessMap",H.metallicRoughnessTexture)),U.push(Q.assignTexture(K,"roughnessMap",H.metallicRoughnessTexture));C=this._invokeOne(function(R){return R.getMaterialType&&R.getMaterialType(A)}),U.push(Promise.all(this._invokeAll(function(R){return R.extendMaterialParams&&R.extendMaterialParams(A,K)})))}if(I.doubleSided===!0)K.side=y0;let Y=I.alphaMode||wH.OPAQUE;if(Y===wH.BLEND)K.transparent=!0,K.depthWrite=!1;else if(K.transparent=!1,Y===wH.MASK)K.alphaTest=I.alphaCutoff!==void 0?I.alphaCutoff:0.5;if(I.normalTexture!==void 0&&C!==_0){if(U.push(Q.assignTexture(K,"normalMap",I.normalTexture)),K.normalScale=new AA(1,1),I.normalTexture.scale!==void 0){let H=I.normalTexture.scale;K.normalScale.set(H,H)}}if(I.occlusionTexture!==void 0&&C!==_0){if(U.push(Q.assignTexture(K,"aoMap",I.occlusionTexture)),I.occlusionTexture.strength!==void 0)K.aoMapIntensity=I.occlusionTexture.strength}if(I.emissiveFactor!==void 0&&C!==_0){let H=I.emissiveFactor;K.emissive=new a().setRGB(H[0],H[1],H[2],b0)}if(I.emissiveTexture!==void 0&&C!==_0)U.push(Q.assignTexture(K,"emissiveMap",I.emissiveTexture,N0));return Promise.all(U).then(function(){let H=new C(K);if(I.name)H.name=I.name;if(HI(H,I),Q.associations.set(H,{materials:A}),I.extensions)c1(B,H,I);return H})}createUniqueName(A){let Q=T0.sanitizeNodeName(A||"");if(Q in this.nodeNamesUsed)return Q+"_"+ ++this.nodeNamesUsed[Q];else return this.nodeNamesUsed[Q]=0,Q}loadGeometries(A){let Q=this,E=this.extensions,B=this.primitiveCache;function I(K){return E[u0.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(K,Q).then(function(J){return kG(J,K,Q)})}let C=[];for(let K=0,J=A.length;K0)Lw(W,I);if(W.name=Q.createUniqueName(I.name||"mesh_"+A),HI(W,I),L.extensions)c1(B,W,L);Q.assignFinalMaterial(W),H.push(W)}for(let O=0,N=H.length;O1)Y=new i0;else if(U.length===1)Y=U[0];else Y=new I0;if(Y!==U[0])for(let H=0,R=U.length;H{let H=/*@__PURE__*/new Map;for(let[R,O]of B.associations)if(R instanceof $Q||R instanceof EQ)H.set(R,O);return Y.traverse((R)=>{let O=B.associations.get(R);if(O!=null)H.set(R,O)}),H};return B.associations=U(I),I})}_createAnimationTracks(A,Q,E,B,I){let C=[],K=A.name?A.name:A.uuid,J=[];if(fI[I.path]===fI.weights)A.traverse(function(R){if(R.morphTargetInfluences)J.push(R.name?R.name:R.uuid)});else J.push(K);let U;switch(fI[I.path]){case fI.weights:U=zE;break;case fI.rotation:U=ME;break;case fI.position:case fI.scale:U=YE;break;default:switch(E.itemSize){case 1:U=zE;break;case 2:case 3:default:U=YE;break}break}let Y=B.interpolation!==void 0?Ww[B.interpolation]:T1,H=this._getArrayFromAccessor(E);for(let R=0,O=J.length;R{let B=this._getIdleWorker();if(B!==-1)this._initWorker(B),this.workerStatus|=1<A.terminate()),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}var PH,ZI,jH,VH={env:{emscripten_notify_memory_growth:function(A){jH=new Uint8Array(ZI.exports.memory.buffer)}}};class vH{init(){return PH||(PH=typeof fetch!="undefined"?fetch("data:application/wasm;base64,"+tG).then((A)=>A.arrayBuffer()).then((A)=>WebAssembly.instantiate(A,VH)).then(this._init):WebAssembly.instantiate(Buffer.from(tG,"base64"),VH).then(this._init),PH)}_init(A){ZI=A.instance,VH.env.emscripten_notify_memory_growth(0)}decode(A,Q=0){if(!ZI)throw new Error("ZSTDDecoder: Await .init() before decoding.");let E=A.byteLength,B=ZI.exports.malloc(E);jH.set(A,B),Q=Q||Number(ZI.exports.ZSTD_findDecompressedSize(B,E));let I=ZI.exports.malloc(Q),C=ZI.exports.ZSTD_decompress(I,Q,B,E),K=jH.slice(I,I+C);return ZI.exports.free(B),ZI.exports.free(I),K}}var tG="AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDBgEACQkHBgICAAYGAgQUBwYGAwIGAAMCAQgBBwUGCgoEEQAEBAEIAwgDBQgDEA8IAAcABAUBcAECAgUEAQCAAgYJAX8BQaCgwAILB2AHBm1lbW9yeQIABm1hbGxvYwAoBGZyZWUAJgxaU1REX2lzRXJyb3IAaBlaU1REX2ZpbmREZWNvbXByZXNzZWRTaXplAFQPWlNURF9kZWNvbXByZXNzAEoGX3N0YXJ0ACQJBwEAQQELASQKussBaA8AIAAgACgCBCABajYCBAsZACAAKAIAIAAoAgRBH3F0QQAgAWtBH3F2CwgAIABBiH9LC34BBH9BAyEBIAAoAgQiA0EgTQRAIAAoAggiASAAKAIQTwRAIAAQDQ8LIAAoAgwiAiABRgRAQQFBAiADQSBJGw8LIAAgASABIAJrIANBA3YiBCABIARrIAJJIgEbIgJrIgQ2AgggACADIAJBA3RrNgIEIAAgBCgAADYCAAsgAQsUAQF/IAAgARACIQIgACABEAEgAgv3AQECfyACRQRAIABCADcCACAAQQA2AhAgAEIANwIIQbh/DwsgACABNgIMIAAgAUEEajYCECACQQRPBEAgACABIAJqIgFBfGoiAzYCCCAAIAMoAAA2AgAgAUF/ai0AACIBBEAgAEEIIAEQFGs2AgQgAg8LIABBADYCBEF/DwsgACABNgIIIAAgAS0AACIDNgIAIAJBfmoiBEEBTQRAIARBAWtFBEAgACABLQACQRB0IANyIgM2AgALIAAgAS0AAUEIdCADajYCAAsgASACakF/ai0AACIBRQRAIABBADYCBEFsDwsgAEEoIAEQFCACQQN0ams2AgQgAgsWACAAIAEpAAA3AAAgACABKQAINwAICy8BAX8gAUECdEGgHWooAgAgACgCAEEgIAEgACgCBGprQR9xdnEhAiAAIAEQASACCyEAIAFCz9bTvtLHq9lCfiAAfEIfiUKHla+vmLbem55/fgsdAQF/IAAoAgggACgCDEYEfyAAKAIEQSBGBUEACwuCBAEDfyACQYDAAE8EQCAAIAEgAhBnIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAsMACAAIAEpAAA3AAALQQECfyAAKAIIIgEgACgCEEkEQEEDDwsgACAAKAIEIgJBB3E2AgQgACABIAJBA3ZrIgE2AgggACABKAAANgIAQQALDAAgACABKAIANgAAC/cCAQJ/AkAgACABRg0AAkAgASACaiAASwRAIAAgAmoiBCABSw0BCyAAIAEgAhALDwsgACABc0EDcSEDAkACQCAAIAFJBEAgAwRAIAAhAwwDCyAAQQNxRQRAIAAhAwwCCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigCACACaiAAQQZ2IgFBAnRBsB5qKAIAaiAAQSBxIgBFaiABRSAAQQV2cWoFQbh/CwsdACAAKAKQ4gEQWiAAQQA2AqDiASAAQgA3A5DiAQu1AwEFfyMAQZACayIKJABBuH8hBgJAIAVFDQAgBCwAACIIQf8BcSEHAkAgCEF/TARAIAdBgn9qQQF2IgggBU8NAkFsIQYgB0GBf2oiBUGAAk8NAiAEQQFqIQdBACEGA0AgBiAFTwRAIAUhBiAIIQcMAwUgACAGaiAHIAZBAXZqIgQtAABBBHY6AAAgACAGQQFyaiAELQAAQQ9xOgAAIAZBAmohBgwBCwAACwALIAcgBU8NASAAIARBAWogByAKEFMiBhADDQELIAYhBEEAIQYgAUEAQTQQECEJQQAhBQNAIAQgBkcEQCAAIAZqIggtAAAiAUELSwRAQWwhBgwDBSAJIAFBAnRqIgEgASgCAEEBajYCACAGQQFqIQZBASAILQAAdEEBdSAFaiEFDAILAAsLQWwhBiAFRQ0AIAUQFEEBaiIBQQxLDQAgAyABNgIAQQFBASABdCAFayIDEBQiAXQgA0cNACAAIARqIAFBAWoiADoAACAJIABBAnRqIgAgACgCAEEBajYCACAJKAIEIgBBAkkgAEEBcXINACACIARBAWo2AgAgB0EBaiEGCyAKQZACaiQAIAYLxhEBDH8jAEHwAGsiBSQAQWwhCwJAIANBCkkNACACLwAAIQogAi8AAiEJIAIvAAQhByAFQQhqIAQQDgJAIAMgByAJIApqakEGaiIMSQ0AIAUtAAohCCAFQdgAaiACQQZqIgIgChAGIgsQAw0BIAVBQGsgAiAKaiICIAkQBiILEAMNASAFQShqIAIgCWoiAiAHEAYiCxADDQEgBUEQaiACIAdqIAMgDGsQBiILEAMNASAAIAFqIg9BfWohECAEQQRqIQZBASELIAAgAUEDakECdiIDaiIMIANqIgIgA2oiDiEDIAIhBCAMIQcDQCALIAMgEElxBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgCS0AAyELIAcgBiAFQUBrIAgQAkECdGoiCS8BADsAACAFQUBrIAktAAIQASAJLQADIQogBCAGIAVBKGogCBACQQJ0aiIJLwEAOwAAIAVBKGogCS0AAhABIAktAAMhCSADIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgDS0AAyENIAAgC2oiCyAGIAVB2ABqIAgQAkECdGoiAC8BADsAACAFQdgAaiAALQACEAEgAC0AAyEAIAcgCmoiCiAGIAVBQGsgCBACQQJ0aiIHLwEAOwAAIAVBQGsgBy0AAhABIActAAMhByAEIAlqIgkgBiAFQShqIAgQAkECdGoiBC8BADsAACAFQShqIAQtAAIQASAELQADIQQgAyANaiIDIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgACALaiEAIAcgCmohByAEIAlqIQQgAyANLQADaiEDIAVB2ABqEA0gBUFAaxANciAFQShqEA1yIAVBEGoQDXJFIQsMAQsLIAQgDksgByACS3INAEFsIQsgACAMSw0BIAxBfWohCQNAQQAgACAJSSAFQdgAahAEGwRAIAAgBiAFQdgAaiAIEAJBAnRqIgovAQA7AAAgBUHYAGogCi0AAhABIAAgCi0AA2oiACAGIAVB2ABqIAgQAkECdGoiCi8BADsAACAFQdgAaiAKLQACEAEgACAKLQADaiEADAEFIAxBfmohCgNAIAVB2ABqEAQgACAKS3JFBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgACAJLQADaiEADAELCwNAIAAgCk0EQCAAIAYgBUHYAGogCBACQQJ0aiIJLwEAOwAAIAVB2ABqIAktAAIQASAAIAktAANqIQAMAQsLAkAgACAMTw0AIAAgBiAFQdgAaiAIEAIiAEECdGoiDC0AADoAACAMLQADQQFGBEAgBUHYAGogDC0AAhABDAELIAUoAlxBH0sNACAFQdgAaiAGIABBAnRqLQACEAEgBSgCXEEhSQ0AIAVBIDYCXAsgAkF9aiEMA0BBACAHIAxJIAVBQGsQBBsEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiIAIAYgBUFAayAIEAJBAnRqIgcvAQA7AAAgBUFAayAHLQACEAEgACAHLQADaiEHDAEFIAJBfmohDANAIAVBQGsQBCAHIAxLckUEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwNAIAcgDE0EQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwJAIAcgAk8NACAHIAYgBUFAayAIEAIiAEECdGoiAi0AADoAACACLQADQQFGBEAgBUFAayACLQACEAEMAQsgBSgCREEfSw0AIAVBQGsgBiAAQQJ0ai0AAhABIAUoAkRBIUkNACAFQSA2AkQLIA5BfWohAgNAQQAgBCACSSAFQShqEAQbBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2oiACAGIAVBKGogCBACQQJ0aiIELwEAOwAAIAVBKGogBC0AAhABIAAgBC0AA2ohBAwBBSAOQX5qIQIDQCAFQShqEAQgBCACS3JFBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsDQCAEIAJNBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsCQCAEIA5PDQAgBCAGIAVBKGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBKGogAi0AAhABDAELIAUoAixBH0sNACAFQShqIAYgAEECdGotAAIQASAFKAIsQSFJDQAgBUEgNgIsCwNAQQAgAyAQSSAFQRBqEAQbBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2oiACAGIAVBEGogCBACQQJ0aiICLwEAOwAAIAVBEGogAi0AAhABIAAgAi0AA2ohAwwBBSAPQX5qIQIDQCAFQRBqEAQgAyACS3JFBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsDQCADIAJNBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsCQCADIA9PDQAgAyAGIAVBEGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBEGogAi0AAhABDAELIAUoAhRBH0sNACAFQRBqIAYgAEECdGotAAIQASAFKAIUQSFJDQAgBUEgNgIUCyABQWwgBUHYAGoQCiAFQUBrEApxIAVBKGoQCnEgBUEQahAKcRshCwwJCwAACwALAAALAAsAAAsACwAACwALQWwhCwsgBUHwAGokACALC7UEAQ5/IwBBEGsiBiQAIAZBBGogABAOQVQhBQJAIARB3AtJDQAgBi0ABCEHIANB8ARqQQBB7AAQECEIIAdBDEsNACADQdwJaiIJIAggBkEIaiAGQQxqIAEgAhAxIhAQA0UEQCAGKAIMIgQgB0sNASADQdwFaiEPIANBpAVqIREgAEEEaiESIANBqAVqIQEgBCEFA0AgBSICQX9qIQUgCCACQQJ0aigCAEUNAAsgAkEBaiEOQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgASALaiAKNgIAIAVBAWohBSAKIAxqIQoMAQsLIAEgCjYCAEEAIQUgBigCCCELA0AgBSALRkUEQCABIAUgCWotAAAiDEECdGoiDSANKAIAIg1BAWo2AgAgDyANQQF0aiINIAw6AAEgDSAFOgAAIAVBAWohBQwBCwtBACEBIANBADYCqAUgBEF/cyAHaiEJQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgAyALaiABNgIAIAwgBSAJanQgAWohASAFQQFqIQUMAQsLIAcgBEEBaiIBIAJrIgRrQQFqIQgDQEEBIQUgBCAIT0UEQANAIAUgDk9FBEAgBUECdCIJIAMgBEE0bGpqIAMgCWooAgAgBHY2AgAgBUEBaiEFDAELCyAEQQFqIQQMAQsLIBIgByAPIAogESADIAIgARBkIAZBAToABSAGIAc6AAYgACAGKAIENgIACyAQIQULIAZBEGokACAFC8ENAQt/IwBB8ABrIgUkAEFsIQkCQCADQQpJDQAgAi8AACEKIAIvAAIhDCACLwAEIQYgBUEIaiAEEA4CQCADIAYgCiAMampBBmoiDUkNACAFLQAKIQcgBUHYAGogAkEGaiICIAoQBiIJEAMNASAFQUBrIAIgCmoiAiAMEAYiCRADDQEgBUEoaiACIAxqIgIgBhAGIgkQAw0BIAVBEGogAiAGaiADIA1rEAYiCRADDQEgACABaiIOQX1qIQ8gBEEEaiEGQQEhCSAAIAFBA2pBAnYiAmoiCiACaiIMIAJqIg0hAyAMIQQgCiECA0AgCSADIA9JcQRAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAACAGIAVBQGsgBxACQQF0aiIILQAAIQsgBUFAayAILQABEAEgAiALOgAAIAYgBUEoaiAHEAJBAXRqIggtAAAhCyAFQShqIAgtAAEQASAEIAs6AAAgBiAFQRBqIAcQAkEBdGoiCC0AACELIAVBEGogCC0AARABIAMgCzoAACAGIAVB2ABqIAcQAkEBdGoiCC0AACELIAVB2ABqIAgtAAEQASAAIAs6AAEgBiAFQUBrIAcQAkEBdGoiCC0AACELIAVBQGsgCC0AARABIAIgCzoAASAGIAVBKGogBxACQQF0aiIILQAAIQsgBUEoaiAILQABEAEgBCALOgABIAYgBUEQaiAHEAJBAXRqIggtAAAhCyAFQRBqIAgtAAEQASADIAs6AAEgA0ECaiEDIARBAmohBCACQQJqIQIgAEECaiEAIAkgBUHYAGoQDUVxIAVBQGsQDUVxIAVBKGoQDUVxIAVBEGoQDUVxIQkMAQsLIAQgDUsgAiAMS3INAEFsIQkgACAKSw0BIApBfWohCQNAIAVB2ABqEAQgACAJT3JFBEAgBiAFQdgAaiAHEAJBAXRqIggtAAAhCyAFQdgAaiAILQABEAEgACALOgAAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAASAAQQJqIQAMAQsLA0AgBUHYAGoQBCAAIApPckUEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCwNAIAAgCkkEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCyAMQX1qIQADQCAFQUBrEAQgAiAAT3JFBEAgBiAFQUBrIAcQAkEBdGoiCi0AACEJIAVBQGsgCi0AARABIAIgCToAACAGIAVBQGsgBxACQQF0aiIKLQAAIQkgBUFAayAKLQABEAEgAiAJOgABIAJBAmohAgwBCwsDQCAFQUBrEAQgAiAMT3JFBEAgBiAFQUBrIAcQAkEBdGoiAC0AACEKIAVBQGsgAC0AARABIAIgCjoAACACQQFqIQIMAQsLA0AgAiAMSQRAIAYgBUFAayAHEAJBAXRqIgAtAAAhCiAFQUBrIAAtAAEQASACIAo6AAAgAkEBaiECDAELCyANQX1qIQADQCAFQShqEAQgBCAAT3JFBEAgBiAFQShqIAcQAkEBdGoiAi0AACEKIAVBKGogAi0AARABIAQgCjoAACAGIAVBKGogBxACQQF0aiICLQAAIQogBUEoaiACLQABEAEgBCAKOgABIARBAmohBAwBCwsDQCAFQShqEAQgBCANT3JFBEAgBiAFQShqIAcQAkEBdGoiAC0AACECIAVBKGogAC0AARABIAQgAjoAACAEQQFqIQQMAQsLA0AgBCANSQRAIAYgBUEoaiAHEAJBAXRqIgAtAAAhAiAFQShqIAAtAAEQASAEIAI6AAAgBEEBaiEEDAELCwNAIAVBEGoQBCADIA9PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIAYgBUEQaiAHEAJBAXRqIgAtAAAhAiAFQRBqIAAtAAEQASADIAI6AAEgA0ECaiEDDAELCwNAIAVBEGoQBCADIA5PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIANBAWohAwwBCwsDQCADIA5JBEAgBiAFQRBqIAcQAkEBdGoiAC0AACECIAVBEGogAC0AARABIAMgAjoAACADQQFqIQMMAQsLIAFBbCAFQdgAahAKIAVBQGsQCnEgBUEoahAKcSAFQRBqEApxGyEJDAELQWwhCQsgBUHwAGokACAJC8oCAQR/IwBBIGsiBSQAIAUgBBAOIAUtAAIhByAFQQhqIAIgAxAGIgIQA0UEQCAEQQRqIQIgACABaiIDQX1qIQQDQCAFQQhqEAQgACAET3JFBEAgAiAFQQhqIAcQAkEBdGoiBi0AACEIIAVBCGogBi0AARABIAAgCDoAACACIAVBCGogBxACQQF0aiIGLQAAIQggBUEIaiAGLQABEAEgACAIOgABIABBAmohAAwBCwsDQCAFQQhqEAQgACADT3JFBEAgAiAFQQhqIAcQAkEBdGoiBC0AACEGIAVBCGogBC0AARABIAAgBjoAACAAQQFqIQAMAQsLA0AgACADT0UEQCACIAVBCGogBxACQQF0aiIELQAAIQYgBUEIaiAELQABEAEgACAGOgAAIABBAWohAAwBCwsgAUFsIAVBCGoQChshAgsgBUEgaiQAIAILtgMBCX8jAEEQayIGJAAgBkEANgIMIAZBADYCCEFUIQQCQAJAIANBQGsiDCADIAZBCGogBkEMaiABIAIQMSICEAMNACAGQQRqIAAQDiAGKAIMIgcgBi0ABEEBaksNASAAQQRqIQogBkEAOgAFIAYgBzoABiAAIAYoAgQ2AgAgB0EBaiEJQQEhBANAIAQgCUkEQCADIARBAnRqIgEoAgAhACABIAU2AgAgACAEQX9qdCAFaiEFIARBAWohBAwBCwsgB0EBaiEHQQAhBSAGKAIIIQkDQCAFIAlGDQEgAyAFIAxqLQAAIgRBAnRqIgBBASAEdEEBdSILIAAoAgAiAWoiADYCACAHIARrIQhBACEEAkAgC0EDTQRAA0AgBCALRg0CIAogASAEakEBdGoiACAIOgABIAAgBToAACAEQQFqIQQMAAALAAsDQCABIABPDQEgCiABQQF0aiIEIAg6AAEgBCAFOgAAIAQgCDoAAyAEIAU6AAIgBCAIOgAFIAQgBToABCAEIAg6AAcgBCAFOgAGIAFBBGohAQwAAAsACyAFQQFqIQUMAAALAAsgAiEECyAGQRBqJAAgBAutAQECfwJAQYQgKAIAIABHIAAoAgBBAXYiAyABa0F4aiICQXhxQQhHcgR/IAIFIAMQJ0UNASACQQhqC0EQSQ0AIAAgACgCACICQQFxIAAgAWpBD2pBeHEiASAAa0EBdHI2AgAgASAANgIEIAEgASgCAEEBcSAAIAJBAXZqIAFrIgJBAXRyNgIAQYQgIAEgAkH/////B3FqQQRqQYQgKAIAIABGGyABNgIAIAEQJQsLygIBBX8CQAJAAkAgAEEIIABBCEsbZ0EfcyAAaUEBR2oiAUEESSAAIAF2cg0AIAFBAnRB/B5qKAIAIgJFDQADQCACQXhqIgMoAgBBAXZBeGoiBSAATwRAIAIgBUEIIAVBCEsbZ0Efc0ECdEGAH2oiASgCAEYEQCABIAIoAgQ2AgALDAMLIARBHksNASAEQQFqIQQgAigCBCICDQALC0EAIQMgAUEgTw0BA0AgAUECdEGAH2ooAgAiAkUEQCABQR5LIQIgAUEBaiEBIAJFDQEMAwsLIAIgAkF4aiIDKAIAQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgBGBEAgASACKAIENgIACwsgAigCACIBBEAgASACKAIENgIECyACKAIEIgEEQCABIAIoAgA2AgALIAMgAygCAEEBcjYCACADIAAQNwsgAwvhCwINfwV+IwBB8ABrIgckACAHIAAoAvDhASIINgJcIAEgAmohDSAIIAAoAoDiAWohDwJAAkAgBUUEQCABIQQMAQsgACgCxOABIRAgACgCwOABIREgACgCvOABIQ4gAEEBNgKM4QFBACEIA0AgCEEDRwRAIAcgCEECdCICaiAAIAJqQazQAWooAgA2AkQgCEEBaiEIDAELC0FsIQwgB0EYaiADIAQQBhADDQEgB0EsaiAHQRhqIAAoAgAQEyAHQTRqIAdBGGogACgCCBATIAdBPGogB0EYaiAAKAIEEBMgDUFgaiESIAEhBEEAIQwDQCAHKAIwIAcoAixBA3RqKQIAIhRCEIinQf8BcSEIIAcoAkAgBygCPEEDdGopAgAiFUIQiKdB/wFxIQsgBygCOCAHKAI0QQN0aikCACIWQiCIpyEJIBVCIIghFyAUQiCIpyECAkAgFkIQiKdB/wFxIgNBAk8EQAJAIAZFIANBGUlyRQRAIAkgB0EYaiADQSAgBygCHGsiCiAKIANLGyIKEAUgAyAKayIDdGohCSAHQRhqEAQaIANFDQEgB0EYaiADEAUgCWohCQwBCyAHQRhqIAMQBSAJaiEJIAdBGGoQBBoLIAcpAkQhGCAHIAk2AkQgByAYNwNIDAELAkAgA0UEQCACBEAgBygCRCEJDAMLIAcoAkghCQwBCwJAAkAgB0EYakEBEAUgCSACRWpqIgNBA0YEQCAHKAJEQX9qIgMgA0VqIQkMAQsgA0ECdCAHaigCRCIJIAlFaiEJIANBAUYNAQsgByAHKAJINgJMCwsgByAHKAJENgJIIAcgCTYCRAsgF6chAyALBEAgB0EYaiALEAUgA2ohAwsgCCALakEUTwRAIAdBGGoQBBoLIAgEQCAHQRhqIAgQBSACaiECCyAHQRhqEAQaIAcgB0EYaiAUQhiIp0H/AXEQCCAUp0H//wNxajYCLCAHIAdBGGogFUIYiKdB/wFxEAggFadB//8DcWo2AjwgB0EYahAEGiAHIAdBGGogFkIYiKdB/wFxEAggFqdB//8DcWo2AjQgByACNgJgIAcoAlwhCiAHIAk2AmggByADNgJkAkACQAJAIAQgAiADaiILaiASSw0AIAIgCmoiEyAPSw0AIA0gBGsgC0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ";var eG="display-p3",AW="display-p3-linear";var hH=/*@__PURE__*/new WeakMap,yH=0,gH;class qB extends C0{constructor(A){super(A);if(this.transcoderPath="",this.transcoderBinary=null,this.transcoderPending=null,this.workerPool=new zH,this.workerSourceURL="",this.workerConfig=null,typeof MSC_TRANSCODER!=="undefined")console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.')}setTranscoderPath(A){return this.transcoderPath=A,this}setWorkerLimit(A){return this.workerPool.setWorkerLimit(A),this}async detectSupportAsync(A){return this.workerConfig={astcSupported:await A.hasFeatureAsync("texture-compression-astc"),astcHDRSupported:!1,etc1Supported:await A.hasFeatureAsync("texture-compression-etc1"),etc2Supported:await A.hasFeatureAsync("texture-compression-etc2"),dxtSupported:await A.hasFeatureAsync("texture-compression-bc"),bptcSupported:await A.hasFeatureAsync("texture-compression-bptc"),pvrtcSupported:await A.hasFeatureAsync("texture-compression-pvrtc")},this}detectSupport(A){if(A.isWebGPURenderer===!0)this.workerConfig={astcSupported:A.hasFeature("texture-compression-astc"),astcHDRSupported:!1,etc1Supported:A.hasFeature("texture-compression-etc1"),etc2Supported:A.hasFeature("texture-compression-etc2"),dxtSupported:A.hasFeature("texture-compression-bc"),bptcSupported:A.hasFeature("texture-compression-bptc"),pvrtcSupported:A.hasFeature("texture-compression-pvrtc")};else this.workerConfig={astcSupported:A.extensions.has("WEBGL_compressed_texture_astc"),astcHDRSupported:A.extensions.has("WEBGL_compressed_texture_astc")&&A.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"),etc1Supported:A.extensions.has("WEBGL_compressed_texture_etc1"),etc2Supported:A.extensions.has("WEBGL_compressed_texture_etc"),dxtSupported:A.extensions.has("WEBGL_compressed_texture_s3tc"),bptcSupported:A.extensions.has("EXT_texture_compression_bptc"),pvrtcSupported:A.extensions.has("WEBGL_compressed_texture_pvrtc")||A.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc")};return this}init(){if(!this.transcoderPending){let A=new U0(this.manager);A.setPath(this.transcoderPath),A.setWithCredentials(this.withCredentials);let Q=A.loadAsync("basis_transcoder.js"),E=new U0(this.manager);E.setPath(this.transcoderPath),E.setResponseType("arraybuffer"),E.setWithCredentials(this.withCredentials);let B=E.loadAsync("basis_transcoder.wasm");if(this.transcoderPending=Promise.all([Q,B]).then(([I,C])=>{let K=qB.BasisWorker.toString(),J=["/* constants */","let _EngineFormat = "+JSON.stringify(qB.EngineFormat),"let _EngineType = "+JSON.stringify(qB.EngineType),"let _TranscoderFormat = "+JSON.stringify(qB.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(qB.BasisFormat),"/* basis_transcoder.js */",I,"/* worker */",K.substring(K.indexOf("{")+1,K.lastIndexOf("}"))].join(` -`);this.workerSourceURL=URL.createObjectURL(new Blob([J])),this.transcoderBinary=C,this.workerPool.setWorkerCreator(()=>{let U=new Worker(this.workerSourceURL),Y=this.transcoderBinary.slice(0);return U.postMessage({type:"init",config:this.workerConfig,transcoderBinary:Y},[Y]),U})}),yH>0)console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances.");yH++}return this.transcoderPending}load(A,Q,E,B){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");let I=new U0(this.manager);I.setResponseType("arraybuffer"),I.setWithCredentials(this.withCredentials),I.load(A,(C)=>{this.parse(C,Q,B)},E,B)}parse(A,Q,E){if(this.workerConfig===null)throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.");if(hH.has(A))return hH.get(A).promise.then(Q).catch(E);this._createTexture(A).then((B)=>Q?Q(B):null).catch(E)}_createTextureFrom(A,Q){let{type:E,error:B,data:{faces:I,width:C,height:K,format:J,type:U,dfdFlags:Y}}=A;if(E==="error")return Promise.reject(B);let H;if(Q.faceCount===6)H=new kC(I,J,U);else{let R=I[0].mipmaps;H=Q.layerCount>1?new _C(R,C,K,Q.layerCount,J,U):new yE(R,C,K,J,U)}return H.minFilter=I[0].mipmaps.length===1?L0:hQ,H.magFilter=L0,H.generateMipmaps=!1,H.needsUpdate=!0,H.colorSpace=QW(Q),H.premultiplyAlpha=!!(Y&XG),H}async _createTexture(A,Q={}){let E=qG(new Uint8Array(A)),B=E.vkFormat===HU&&E.dataFormatDescriptor[0].colorModel===167;if(!(E.vkFormat===LG||B&&!this.workerConfig.astcHDRSupported))return kw(E);let C=Q,K=this.init().then(()=>{return this.workerPool.postMessage({type:"transcode",buffer:A,taskConfig:C},[A])}).then((J)=>this._createTextureFrom(J.data,E));return hH.set(A,{promise:K}),K}dispose(){if(this.workerPool.dispose(),this.workerSourceURL)URL.revokeObjectURL(this.workerSourceURL);return yH--,this}}qB.BasisFormat={ETC1S:0,UASTC:1,UASTC_HDR:2};qB.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16,BC6H:22,RGB_HALF:24,RGBA_HALF:25};qB.EngineFormat={RGBAFormat:V0,RGBA_ASTC_4x4_Format:w1,RGB_BPTC_UNSIGNED_Format:S1,RGBA_BPTC_Format:k1,RGBA_ETC2_EAC_Format:y8,RGBA_PVRTC_4BPPV1_Format:D1,RGBA_S3TC_DXT5_Format:PI,RGB_ETC1_Format:M1,RGB_ETC2_Format:h8,RGB_PVRTC_4BPPV1_Format:F1,RGBA_S3TC_DXT1_Format:q1};qB.EngineType={UnsignedByteType:x0,HalfFloatType:sA,FloatType:m0};qB.BasisWorker=function(){let A,Q,E,B=_EngineFormat,I=_EngineType,C=_TranscoderFormat,K=_BasisFormat;self.addEventListener("message",function($){let L=$.data;switch(L.type){case"init":A=L.config,J(L.transcoderBinary);break;case"transcode":Q.then(()=>{try{let{faces:W,buffers:Z,width:G,height:X,hasAlpha:q,format:M,type:F,dfdFlags:D}=U(L.buffer);self.postMessage({type:"transcode",id:L.id,data:{faces:W,width:G,height:X,hasAlpha:q,format:M,type:F,dfdFlags:D}},Z)}catch(W){console.error(W),self.postMessage({type:"error",id:L.id,error:W.message})}});break}});function J($){Q=new Promise((L)=>{E={wasmBinary:$,onRuntimeInitialized:L},BASIS(E)}).then(()=>{if(E.initializeBasis(),E.KTX2File===void 0)console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder.")})}function U($){let L=new E.KTX2File(new Uint8Array($));function W(){L.close(),L.delete()}if(!L.isValid())throw W(),new Error("THREE.KTX2Loader:\tInvalid or unsupported .ktx2 file");let Z;if(L.isUASTC())Z=K.UASTC;else if(L.isETC1S())Z=K.ETC1S;else if(L.isHDR())Z=K.UASTC_HDR;else throw new Error("THREE.KTX2Loader: Unknown Basis encoding");let G=L.getWidth(),X=L.getHeight(),q=L.getLayers()||1,M=L.getLevels(),F=L.getFaces(),D=L.getHasAlpha(),_=L.getDFDFlags(),{transcoderFormat:w,engineFormat:k,engineType:T}=R(Z,G,X,D);if(!G||!X||!M)throw W(),new Error("THREE.KTX2Loader:\tInvalid texture");if(!L.startTranscoding())throw W(),new Error("THREE.KTX2Loader: .startTranscoding failed");let z=[],j=[];for(let v=0;v1)S=m.origWidth,h=m.origHeight;else S=m.width,h=m.height;let s=new Uint8Array(L.getImageTranscodedSizeInBytes(P,b,0,w)),i=L.transcodeImage(s,P,b,v,w,0,-1,-1);if(T===I.HalfFloatType)s=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/Uint16Array.BYTES_PER_ELEMENT);if(!i)throw W(),new Error("THREE.KTX2Loader: .transcodeImage failed.");V.push(s)}let x=N(V);g.push({data:x,width:S,height:h}),j.push(x.buffer)}z.push({mipmaps:g,width:G,height:X,format:k,type:T})}return W(),{faces:z,buffers:j,width:G,height:X,hasAlpha:D,dfdFlags:_,format:k,type:T}}let Y=[{if:"astcSupported",basisFormat:[K.UASTC],transcoderFormat:[C.ASTC_4x4,C.ASTC_4x4],engineFormat:[B.RGBA_ASTC_4x4_Format,B.RGBA_ASTC_4x4_Format],engineType:[I.UnsignedByteType],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[K.ETC1S,K.UASTC],transcoderFormat:[C.BC7_M5,C.BC7_M5],engineFormat:[B.RGBA_BPTC_Format,B.RGBA_BPTC_Format],engineType:[I.UnsignedByteType],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[K.ETC1S,K.UASTC],transcoderFormat:[C.BC1,C.BC3],engineFormat:[B.RGBA_S3TC_DXT1_Format,B.RGBA_S3TC_DXT5_Format],engineType:[I.UnsignedByteType],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[K.ETC1S,K.UASTC],transcoderFormat:[C.ETC1,C.ETC2],engineFormat:[B.RGB_ETC2_Format,B.RGBA_ETC2_EAC_Format],engineType:[I.UnsignedByteType],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[K.ETC1S,K.UASTC],transcoderFormat:[C.ETC1],engineFormat:[B.RGB_ETC1_Format],engineType:[I.UnsignedByteType],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[K.ETC1S,K.UASTC],transcoderFormat:[C.PVRTC1_4_RGB,C.PVRTC1_4_RGBA],engineFormat:[B.RGB_PVRTC_4BPPV1_Format,B.RGBA_PVRTC_4BPPV1_Format],engineType:[I.UnsignedByteType],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0},{if:"bptcSupported",basisFormat:[K.UASTC_HDR],transcoderFormat:[C.BC6H],engineFormat:[B.RGB_BPTC_UNSIGNED_Format],engineType:[I.HalfFloatType],priorityHDR:1,needsPowerOfTwo:!1},{basisFormat:[K.ETC1S,K.UASTC],transcoderFormat:[C.RGBA32,C.RGBA32],engineFormat:[B.RGBAFormat,B.RGBAFormat],engineType:[I.UnsignedByteType,I.UnsignedByteType],priorityETC1S:100,priorityUASTC:100,needsPowerOfTwo:!1},{basisFormat:[K.UASTC_HDR],transcoderFormat:[C.RGBA_HALF],engineFormat:[B.RGBAFormat],engineType:[I.HalfFloatType],priorityHDR:100,needsPowerOfTwo:!1}],H={[K.ETC1S]:Y.filter(($)=>$.basisFormat.includes(K.ETC1S)).sort(($,L)=>$.priorityUASTC-L.priorityUASTC),[K.UASTC]:Y.filter(($)=>$.basisFormat.includes(K.UASTC)).sort(($,L)=>$.priorityUASTC-L.priorityUASTC),[K.UASTC_HDR]:Y.filter(($)=>$.basisFormat.includes(K.UASTC_HDR)).sort(($,L)=>$.priorityHDR-L.priorityHDR)};function R($,L,W,Z){let G=H[$];for(let X=0;X{let K=new vH;await K.init(),C(K)});E=await gH}let B=[];for(let C=0;C>C),J=Math.max(1,A.pixelHeight>>C),U=A.pixelDepth?Math.max(1,A.pixelDepth>>C):0,Y=A.levels[C],H;if(A.supercompressionScheme===WG)H=Y.levelData;else if(A.supercompressionScheme===RH)H=E.decode(Y.levelData,Y.uncompressedByteLength);else throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme.");let R;if(bH[Q]===m0)R=new Float32Array(H.buffer,H.byteOffset,H.byteLength/Float32Array.BYTES_PER_ELEMENT);else if(bH[Q]===sA)R=new Uint16Array(H.buffer,H.byteOffset,H.byteLength/Uint16Array.BYTES_PER_ELEMENT);else R=H;B.push({data:R,width:K,height:J,depth:U})}let I;if(_w.has(xH[Q]))I=A.pixelDepth===0?new h0(B[0].data,A.pixelWidth,A.pixelHeight):new NB(B[0].data,A.pixelWidth,A.pixelHeight,A.pixelDepth);else{if(A.pixelDepth>0)throw new Error("THREE.KTX2Loader: Unsupported pixelDepth.");I=new yE(B,A.pixelWidth,A.pixelHeight),I.minFilter=B.length===1?L0:hQ,I.magFilter=L0}return I.mipmaps=B,I.type=bH[Q],I.format=xH[Q],I.colorSpace=QW(A),I.needsUpdate=!0,Promise.resolve(I)}function QW(A){let Q=A.dataFormatDescriptor[0];if(Q.colorPrimaries===GH)return Q.transferFunction===OU?N0:b0;else if(Q.colorPrimaries===$G)return Q.transferFunction===OU?eG:AW;else if(Q.colorPrimaries===NH)return YQ;else return console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${Q.colorPrimaries}"`),YQ}var vy=new y,hy=new y;var yy=new qE;var BW={};rU(BW,{default:()=>CQ});var CQ={};if(typeof document!=="undefined"){function createTag(A){return document.createElement(A)}function extendPrototype(A,Q){var E,B=A.length,I;for(E=0;E1)E[1]=1;else if(E[1]<=0)E[1]=0;return HSVtoRGB(E[0],E[1],E[2])}function addBrightnessToRGB(A,Q){var E=RGBtoHSV(A[0]*255,A[1]*255,A[2]*255);if(E[2]+=Q,E[2]>1)E[2]=1;else if(E[2]<0)E[2]=0;return HSVtoRGB(E[0],E[1],E[2])}function addHueToRGB(A,Q){var E=RGBtoHSV(A[0]*255,A[1]*255,A[2]*255);if(E[0]+=Q/360,E[0]>1)E[0]-=1;else if(E[0]<0)E[0]+=1;return HSVtoRGB(E[0],E[1],E[2])}function createNS(A){return document.createElementNS("http://www.w3.org/2000/svg",A)}function BaseEvent(){}function getRenderer(A){return renderers[A]}function bezFunction(){var A=Math;function Q(O,N,$,L,W,Z){var G=O*L+N*W+$*Z-W*L-Z*O-$*N;return G>-0.001&&G<0.001}function E(O,N,$,L,W,Z,G,X,q){if($===0&&Z===0&&q===0)return Q(O,N,L,W,G,X);var M=A.sqrt(A.pow(L-O,2)+A.pow(W-N,2)+A.pow(Z-$,2)),F=A.sqrt(A.pow(G-O,2)+A.pow(X-N,2)+A.pow(q-$,2)),D=A.sqrt(A.pow(G-L,2)+A.pow(X-W,2)+A.pow(q-Z,2)),_;if(M>F)if(M>D)_=M-F-D;else _=D-F-M;else if(D>F)_=D-F-M;else _=F-M-D;return _>-0.0001&&_<0.0001}var B=function(){return function(O,N,$,L){var W=getDefaultCurveSegments(),Z,G,X,q,M,F=0,D,_=[],w=[],k=bezierLengthPool.newElement();X=$.length;for(Z=0;ZG?-1:1,M=!0;while(M){if(L[Z]<=G&&L[Z+1]>G)X=(G-L[Z])/(L[Z+1]-L[Z]),M=!1;else Z+=q;if(Z<0||Z>=W-1){if(Z===W-1)return $[Z];M=!1}}return $[Z]+($[Z+1]-$[Z])*X}function Y(O,N,$,L,W,Z){var G=U(W,Z),X=1-G,q=A.round((X*X*X*O[0]+(G*X*X+X*G*X+X*X*G)*$[0]+(G*G*X+X*G*G+G*X*G)*L[0]+G*G*G*N[0])*1000)/1000,M=A.round((X*X*X*O[1]+(G*X*X+X*G*X+X*X*G)*$[1]+(G*G*X+X*G*G+G*X*G)*L[1]+G*G*G*N[1])*1000)/1000;return[q,M]}var H=createTypedArray("float32",8);function R(O,N,$,L,W,Z,G){if(W<0)W=0;else if(W>1)W=1;var X=U(W,G);Z=Z>1?1:Z;var q=U(Z,G),M,F=O.length,D=1-X,_=1-q,w=D*D*D,k=X*D*D*3,T=X*X*D*3,z=X*X*X,j=D*D*_,v=X*D*_+D*X*_+D*D*q,g=X*X*_+D*X*q+X*D*q,P=X*X*q,V=D*_*_,S=X*_*_+D*q*_+D*_*q,h=X*q*_+D*q*q+X*_*q,x=X*q*q,b=_*_*_,m=q*_*_+_*q*_+_*_*q,s=q*q*_+_*q*q+q*_*q,i=q*q*q;for(M=0;M1)setDefaultCurveSegments(A);if(getDefaultCurveSegments()>=50)roundValues(!1);else roundValues(!0)}function inBrowser(){return typeof navigator!=="undefined"}function installPlugin(A,Q){if(A==="expressions")setExpressionsPlugin(Q)}function getFactory(A){switch(A){case"propertyFactory":return PropertyFactory;case"shapePropertyFactory":return ShapePropertyFactory;case"matrix":return Matrix;default:return null}}function checkReady(){if(document.readyState==="complete")clearInterval(readyStateCheckInterval),searchAnimations()}function getQueryVariable(A){var Q=queryString.split("&");for(var E=0;E0)this.maskElement.setAttribute("id",O),this.element.maskedElement.setAttribute(G,"url("+getLocationHref()+"#"+O+")"),B.appendChild(this.maskElement);if(this.viewData.length)this.element.addRenderableComponent(this)}function SVGEffects(A){var Q,E="SourceGraphic",B=A.data.ef?A.data.ef.length:0,I=createElementID(),C=filtersFactory.createFilter(I,!0),K=0;this.filters=[];var J;for(Q=0;Q=Y)k/=2,T/=2,z>>>=1;return(k+z)/T};return w.int32=function(){return _.g(4)|0},w.quick=function(){return _.g(4)/4294967296},w.double=w,W(G(_.S),A),(q.pass||M||function(k,T,z,j){if(j){if(j.S)$(j,_);k.state=function(){return $(_,{})}}if(z)return Q[K]=k,T;else return k})(w,D,"global"in q?q.global:this==Q,q.state)}Q["seed"+K]=O;function N(X){var q,M=X.length,F=this,D=0,_=F.i=F.j=0,w=F.S=[];if(!M)X=[M++];while(DW.length-1)N=W.length-1;X=W[W.length-1-N].t,G=Z-X}else{if(!N)G=Math.max(0,Z-this.elem.data.ip);else G=Math.abs(Z-this.elem.comp.globalData.frameRate*N);X=Z-G}var q,M,F;if(O==="pingpong"){var D=Math.floor((L-X)/G);if(D%2!==0)return this.getValueAtTime((G-(L-X)%G+X)/this.comp.globalData.frameRate,0)}else if(O==="offset"){var _=this.getValueAtTime(X/this.comp.globalData.frameRate,0),w=this.getValueAtTime(Z/this.comp.globalData.frameRate,0),k=this.getValueAtTime(((L-X)%G+X)/this.comp.globalData.frameRate,0),T=Math.floor((L-X)/G);if(this.pv.length){F=new Array(_.length),M=F.length;for(q=0;q=Z)return this.pv;var G,X;if(!$){if(!N||N>W.length-1)N=W.length-1;X=W[N].t,G=X-Z}else{if(!N)G=Math.max(0,this.elem.data.op-Z);else G=Math.abs(this.elem.comp.globalData.frameRate*N);X=Z+G}var q,M,F;if(O==="pingpong"){var D=Math.floor((Z-L)/G);if(D%2===0)return this.getValueAtTime(((Z-L)%G+Z)/this.comp.globalData.frameRate,0)}else if(O==="offset"){var _=this.getValueAtTime(Z/this.comp.globalData.frameRate,0),w=this.getValueAtTime(X/this.comp.globalData.frameRate,0),k=this.getValueAtTime((G-(Z-L)%G+Z)/this.comp.globalData.frameRate,0),T=Math.floor((Z-L)/G)+1;if(this.pv.length){F=new Array(_.length),M=F.length;for(q=0;q1?(W-L)/(N-1):1,G=0,X=0,q;if(this.pv.length)q=createTypedArray("float32",this.pv.length);else q=0;var M;while(GZ){var F=G,D=$.c&&G===X-1?0:G+1,_=(Z-q)/W[G].addedLength;M=bez.getPointInSegment($.v[F],$.v[D],$.o[F],$.i[D],_,W[G]);break}else q+=W[G].addedLength;G+=1}if(!M)M=$.c?[$.v[0][0],$.v[0][1]]:[$.v[$._length-1][0],$.v[$._length-1][1]];return M},vectorOnPath:function(O,N,$){if(O==1)O=this.v.c;else if(O==0)O=0.999;var L=this.pointOnPath(O,N),W=this.pointOnPath(O+0.001,N),Z=W[0]-L[0],G=W[1]-L[1],X=Math.sqrt(Math.pow(Z,2)+Math.pow(G,2));if(X===0)return[0,0];var q=$==="tangent"?[Z/X,G/X]:[-G/X,Z/X];return q},tangentOnPath:function(O,N){return this.vectorOnPath(O,N,"tangent")},normalOnPath:function(O,N){return this.vectorOnPath(O,N,"normal")},setGroupProperty:expressionHelpers.setGroupProperty,getValueAtTime:expressionHelpers.getStaticValueAtTime},extendPrototype([H],U),extendPrototype([H],Y),Y.prototype.getValueAtTime=J,Y.prototype.initiateExpression=ExpressionManager.initiateExpression;var R=ShapePropertyFactory.getShapeProp;ShapePropertyFactory.getShapeProp=function(O,N,$,L,W){var Z=R(O,N,$,L,W);if(Z.propertyIndex=N.ix,Z.lock=!1,$===3)expressionHelpers.searchExpressions(O,N.pt,Z);else if($===4)expressionHelpers.searchExpressions(O,N.ks,Z);if(Z.k)O.addDynamicProperty(Z);return Z}}function initialize$1(){addPropertyDecorator()}function addDecorator(){function A(){if(this.data.d.x)return this.calculateExpression=ExpressionManager.initiateExpression.bind(this)(this.elem,this.data.d,this),this.addEffect(this.getExpressionValue.bind(this)),!0;return null}TextProperty.prototype.getExpressionValue=function(Q,E){var B=this.calculateExpression(E);if(Q.t!==B){var I={};return this.copyData(I,Q),I.t=B.toString(),I.__complete=!1,I}return Q},TextProperty.prototype.searchProperty=function(){var Q=this.searchKeyframes(),E=this.searchExpressions();return this.kf=Q||E,this.kf},TextProperty.prototype.searchExpressions=A}function initialize(){addDecorator()}let svgNS="http://www.w3.org/2000/svg",locationHref="",_useWebWorker=!1,initialDefaultFrame=-999999,setWebWorker=(A)=>{_useWebWorker=!!A},getWebWorker=()=>_useWebWorker,setLocationHref=(A)=>{locationHref=A},getLocationHref=()=>locationHref,audioControllerFactory=function(){function A(Q){this.audios=[],this.audioFactory=Q,this._volume=1,this._isMuted=!1}return A.prototype={addAudio:function(Q){this.audios.push(Q)},pause:function(){var Q,E=this.audios.length;for(Q=0;Q{subframeEnabled=!!A},getSubframeEnabled=()=>subframeEnabled,setExpressionsPlugin=(A)=>{expressionsPlugin=A},getExpressionsPlugin=()=>expressionsPlugin,setDefaultCurveSegments=(A)=>{defaultCurveSegments=A},getDefaultCurveSegments=()=>defaultCurveSegments,setIdPrefix=(A)=>{idPrefix$1=A},getIdPrefix=()=>idPrefix$1,dataManager=function(){var A=1,Q=[],E,B,I={onmessage:function(){},postMessage:function(O){E({data:O})}},C={postMessage:function(O){I.onmessage({data:O})}};function K(O){if(window.Worker&&window.Blob&&getWebWorker()){var N=new Blob(["var _workerSelf = self; self.onmessage = ",O.toString()],{type:"text/javascript"}),$=URL.createObjectURL(N);return new Worker($)}return E=O,I}function J(){if(!B)B=K(function O(N){function $(){function W(g,P){var V,S,h=g.length,x,b,m,s;for(S=0;S=0;P-=1)if(g[P].ty==="sh")if(g[P].ks.k.i)M(g[P].ks.k);else{h=g[P].ks.k.length;for(S=0;SV[0])return!0;if(V[0]>g[0])return!1;if(g[1]>V[1])return!0;if(V[1]>g[1])return!1;if(g[2]>V[2])return!0;if(V[2]>g[2])return!1;return null}var D=function(){var g=[4,4,14];function P(S){var h=S.t.d;S.t.d={k:[{s:h,t:0}]}}function V(S){var h,x=S.length;for(h=0;h=0;h-=1)if(S[h].ty==="sh")if(S[h].ks.k.i)S[h].ks.k.c=S[h].closed;else{m=S[h].ks.k.length;for(b=0;b500)this._imageLoaded(),clearInterval(X);G+=1}.bind(this),50)}function C(Z){var G=B(Z,this.assetsPath,this.path),X=createNS("image");if(isSafari)this.testImageLoaded(X);else X.addEventListener("load",this._imageLoaded,!1);if(X.addEventListener("error",function(){q.img=A,this._imageLoaded()}.bind(this),!1),X.setAttributeNS("http://www.w3.org/1999/xlink","href",G),this._elementHelper.append)this._elementHelper.append(X);else this._elementHelper.appendChild(X);var q={img:X,assetData:Z};return q}function K(Z){var G=B(Z,this.assetsPath,this.path),X=createTag("img");X.crossOrigin="anonymous",X.addEventListener("load",this._imageLoaded,!1),X.addEventListener("error",function(){q.img=A,this._imageLoaded()}.bind(this),!1),X.src=G;var q={img:X,assetData:Z};return q}function J(Z){var G={assetData:Z},X=B(Z,this.assetsPath,this.path);return dataManager.loadData(X,function(q){G.img=q,this._footageLoaded()}.bind(this),function(){G.img={},this._footageLoaded()}.bind(this)),G}function U(Z,G){this.imagesLoadedCb=G;var X,q=Z.length;for(X=0;X{renderers[A]=Q},AnimationItem=function(){this._cbs=[],this.name="",this.path="",this.isLoaded=!1,this.currentFrame=0,this.currentRawFrame=0,this.firstFrame=0,this.totalFrames=0,this.frameRate=0,this.frameMult=0,this.playSpeed=1,this.playDirection=1,this.playCount=0,this.animationData={},this.assets=[],this.isPaused=!0,this.autoplay=!1,this.loop=!0,this.renderer=null,this.animationID=createElementID(),this.assetsPath="",this.timeCompleted=0,this.segmentPos=0,this.isSubframeEnabled=getSubframeEnabled(),this.segments=[],this._idle=!0,this._completedLoop=!1,this.projectInterface=ProjectInterface(),this.imagePreloader=new ImagePreloader,this.audioController=audioControllerFactory(),this.markers=[],this.configAnimation=this.configAnimation.bind(this),this.onSetupError=this.onSetupError.bind(this),this.onSegmentComplete=this.onSegmentComplete.bind(this),this.drawnFrameEvent=new BMEnterFrameEvent("drawnFrame",0,0,0)};extendPrototype([BaseEvent],AnimationItem),AnimationItem.prototype.setParams=function(A){if(A.wrapper||A.container)this.wrapper=A.wrapper||A.container;var Q="svg";if(A.animType)Q=A.animType;else if(A.renderer)Q=A.renderer;let E=getRenderer(Q);if(this.renderer=new E(this,A.rendererSettings),this.imagePreloader.setCacheType(Q,this.renderer.globalData.defs),this.renderer.setProjectInterface(this.projectInterface),this.animType=Q,A.loop===""||A.loop===null||A.loop===void 0||A.loop===!0)this.loop=!0;else if(A.loop===!1)this.loop=!1;else this.loop=parseInt(A.loop,10);if(this.autoplay="autoplay"in A?A.autoplay:!0,this.name=A.name?A.name:"",this.autoloadSegments=Object.prototype.hasOwnProperty.call(A,"autoloadSegments")?A.autoloadSegments:!0,this.assetsPath=A.assetsPath,this.initialSegment=A.initialSegment,A.audioFactory)this.audioController.setAudioFactory(A.audioFactory);if(A.animationData)this.setupAnimation(A.animationData);else if(A.path){if(A.path.lastIndexOf("\\")!==-1)this.path=A.path.substr(0,A.path.lastIndexOf("\\")+1);else this.path=A.path.substr(0,A.path.lastIndexOf("/")+1);this.fileName=A.path.substr(A.path.lastIndexOf("/")+1),this.fileName=this.fileName.substr(0,this.fileName.lastIndexOf(".json")),dataManager.loadAnimation(A.path,this.configAnimation,this.onSetupError)}},AnimationItem.prototype.onSetupError=function(){this.trigger("data_failed")},AnimationItem.prototype.setupAnimation=function(A){dataManager.completeAnimation(A,this.configAnimation)},AnimationItem.prototype.setData=function(A,Q){if(Q){if(typeof Q!=="object")Q=JSON.parse(Q)}var E={wrapper:A,animationData:Q},B=A.attributes;E.path=B.getNamedItem("data-animation-path")?B.getNamedItem("data-animation-path").value:B.getNamedItem("data-bm-path")?B.getNamedItem("data-bm-path").value:B.getNamedItem("bm-path")?B.getNamedItem("bm-path").value:"",E.animType=B.getNamedItem("data-anim-type")?B.getNamedItem("data-anim-type").value:B.getNamedItem("data-bm-type")?B.getNamedItem("data-bm-type").value:B.getNamedItem("bm-type")?B.getNamedItem("bm-type").value:B.getNamedItem("data-bm-renderer")?B.getNamedItem("data-bm-renderer").value:B.getNamedItem("bm-renderer")?B.getNamedItem("bm-renderer").value:"canvas";var I=B.getNamedItem("data-anim-loop")?B.getNamedItem("data-anim-loop").value:B.getNamedItem("data-bm-loop")?B.getNamedItem("data-bm-loop").value:B.getNamedItem("bm-loop")?B.getNamedItem("bm-loop").value:"";if(I==="false")E.loop=!1;else if(I==="true")E.loop=!0;else if(I!=="")E.loop=parseInt(I,10);var C=B.getNamedItem("data-anim-autoplay")?B.getNamedItem("data-anim-autoplay").value:B.getNamedItem("data-bm-autoplay")?B.getNamedItem("data-bm-autoplay").value:B.getNamedItem("bm-autoplay")?B.getNamedItem("bm-autoplay").value:!0;E.autoplay=C!=="false",E.name=B.getNamedItem("data-name")?B.getNamedItem("data-name").value:B.getNamedItem("data-bm-name")?B.getNamedItem("data-bm-name").value:B.getNamedItem("bm-name")?B.getNamedItem("bm-name").value:"";var K=B.getNamedItem("data-anim-prerender")?B.getNamedItem("data-anim-prerender").value:B.getNamedItem("data-bm-prerender")?B.getNamedItem("data-bm-prerender").value:B.getNamedItem("bm-prerender")?B.getNamedItem("bm-prerender").value:"";if(K==="false")E.prerender=!1;this.setParams(E)},AnimationItem.prototype.includeLayers=function(A){if(A.op>this.animationData.op)this.animationData.op=A.op,this.totalFrames=Math.floor(A.op-this.animationData.ip);var Q=this.animationData.layers,E,B=Q.length,I=A.layers,C,K=I.length;for(C=0;Cthis.timeCompleted)this.currentFrame=this.timeCompleted;this.trigger("enterFrame"),this.renderFrame(),this.trigger("drawnFrame")},AnimationItem.prototype.renderFrame=function(){if(this.isLoaded===!1||!this.renderer)return;try{this.renderer.renderFrame(this.currentFrame+this.firstFrame)}catch(A){this.triggerRenderFrameError(A)}},AnimationItem.prototype.play=function(A){if(A&&this.name!==A)return;if(this.isPaused===!0){if(this.isPaused=!1,this.trigger("_pause"),this.audioController.resume(),this._idle)this._idle=!1,this.trigger("_active")}},AnimationItem.prototype.pause=function(A){if(A&&this.name!==A)return;if(this.isPaused===!1)this.isPaused=!0,this.trigger("_play"),this._idle=!0,this.trigger("_idle"),this.audioController.pause()},AnimationItem.prototype.togglePause=function(A){if(A&&this.name!==A)return;if(this.isPaused===!0)this.play();else this.pause()},AnimationItem.prototype.stop=function(A){if(A&&this.name!==A)return;this.pause(),this.playCount=0,this._completedLoop=!1,this.setCurrentRawFrameValue(0)},AnimationItem.prototype.getMarkerData=function(A){var Q;for(var E=0;E=this.totalFrames-1&&this.frameModifier>0)if(!this.loop||this.playCount===this.loop){if(!this.checkSegments(Q>this.totalFrames?Q%this.totalFrames:0))E=!0,Q=this.totalFrames-1}else if(Q>=this.totalFrames){if(this.playCount+=1,!this.checkSegments(Q%this.totalFrames))this.setCurrentRawFrameValue(Q%this.totalFrames),this._completedLoop=!0,this.trigger("loopComplete")}else this.setCurrentRawFrameValue(Q);else if(Q<0){if(!this.checkSegments(Q%this.totalFrames))if(this.loop&&!(this.playCount--<=0&&this.loop!==!0))if(this.setCurrentRawFrameValue(this.totalFrames+Q%this.totalFrames),!this._completedLoop)this._completedLoop=!0;else this.trigger("loopComplete");else E=!0,Q=0}else this.setCurrentRawFrameValue(Q);if(E)this.setCurrentRawFrameValue(Q),this.pause(),this.trigger("complete")},AnimationItem.prototype.adjustSegment=function(A,Q){if(this.playCount=0,A[1]0)if(this.playSpeed<0)this.setSpeed(-this.playSpeed);else this.setDirection(-1);this.totalFrames=A[0]-A[1],this.timeCompleted=this.totalFrames,this.firstFrame=A[1],this.setCurrentRawFrameValue(this.totalFrames-0.001-Q)}else if(A[1]>A[0]){if(this.frameModifier<0)if(this.playSpeed<0)this.setSpeed(-this.playSpeed);else this.setDirection(1);this.totalFrames=A[1]-A[0],this.timeCompleted=this.totalFrames,this.firstFrame=A[0],this.setCurrentRawFrameValue(0.001+Q)}this.trigger("segmentStart")},AnimationItem.prototype.setSegment=function(A,Q){var E=-1;if(this.isPaused){if(this.currentRawFrame+this.firstFrameQ)E=Q-A}if(this.firstFrame=A,this.totalFrames=Q-A,this.timeCompleted=this.totalFrames,E!==-1)this.goToAndStop(E,!0)},AnimationItem.prototype.playSegments=function(A,Q){if(Q)this.segments.length=0;if(typeof A[0]==="object"){var E,B=A.length;for(E=0;E=0;V-=1)Q[V].animation.destroy(P)}function _(P,V,S){var h=[].concat([].slice.call(document.getElementsByClassName("lottie")),[].slice.call(document.getElementsByClassName("bodymovin"))),x,b=h.length;for(x=0;x0)q=_;else X=_;while(Math.abs(D)>C&&++w=I)return W(G,k,X,q);if(T===0)return k;return L(G,F,F+U,X,q)}},A}(),pooling=function(){function A(Q){return Q.concat(createSizedArray(Q.length))}return{double:A}}(),poolFactory=function(){return function(A,Q,E){var B=0,I=A,C=createSizedArray(I),K={newElement:J,release:U};function J(){var Y;if(B)B-=1,Y=C[B];else Y=Q();return Y}function U(Y){if(B===I)C=pooling.double(C),I*=2;if(E)E(Y);C[B]=Y,B+=1}return K}}(),bezierLengthPool=function(){function A(){return{addedLength:0,percents:createTypedArray("float32",getDefaultCurveSegments()),lengths:createTypedArray("float32",getDefaultCurveSegments())}}return poolFactory(8,A)}(),segmentsLengthPool=function(){function A(){return{lengths:[],totalLength:0}}function Q(E){var B,I=E.lengths.length;for(B=0;B=w.t-G){if(_.h)_=w;q=0;break}if(w.t-G>W){q=M;break}if(M=V||W=V?x.points.length-1:0;z=x.points[b].point.length;for(T=0;T=i&&m=V)X[0]=h[0],X[1]=h[1],X[2]=h[2];else if(W<=S)X[0]=_.s[0],X[1]=_.s[1],X[2]=_.s[2];else{var BA=C(_.s),EA=C(h),CA=(W-S)/(V-S);I(X,B(BA,EA,CA))}else for(M=0;M=V)j=1;else if(W0.000001)z=Math.acos(j),v=Math.sin(z),g=Math.sin((1-G)*z)/v,P=Math.sin(G*z)/v;else g=1-G,P=G;return X[0]=g*q+P*_,X[1]=g*M+P*w,X[2]=g*F+P*k,X[3]=g*D+P*T,X}function I(W,Z){var G=Z[0],X=Z[1],q=Z[2],M=Z[3],F=Math.atan2(2*X*M-2*G*q,1-2*X*X-2*q*q),D=Math.asin(2*G*X+2*q*M),_=Math.atan2(2*G*M-2*X*q,1-2*G*G-2*q*q);W[0]=F/degToRads,W[1]=D/degToRads,W[2]=_/degToRads}function C(W){var Z=W[0]*degToRads,G=W[1]*degToRads,X=W[2]*degToRads,q=Math.cos(Z/2),M=Math.cos(G/2),F=Math.cos(X/2),D=Math.sin(Z/2),_=Math.sin(G/2),w=Math.sin(X/2),k=q*M*F-D*_*w,T=D*_*F+q*M*w,z=D*M*F+q*_*w,j=q*_*F-D*M*w;return[T,z,j,k]}function K(){var W=this.comp.renderedFrame-this.offsetTime,Z=this.keyframes[0].t-this.offsetTime,G=this.keyframes[this.keyframes.length-1].t-this.offsetTime;if(!(W===this._caching.lastFrame||this._caching.lastFrame!==A&&(this._caching.lastFrame>=G&&W>=G||this._caching.lastFrame=W)this._caching._lastKeyframeIndex=-1,this._caching.lastIndex=0;var X=this.interpolateValue(W,this._caching);this.pv=X}return this._caching.lastFrame=W,this.pv}function J(W){var Z;if(this.propType==="unidimensional"){if(Z=W*this.mult,Q(this.v-Z)>0.00001)this.v=Z,this._mdf=!0}else{var G=0,X=this.v.length;while(G0.00001)this.v[G]=Z,this._mdf=!0;G+=1}}}function U(){if(this.elem.globalData.frameId===this.frameId||!this.effectsSequence.length)return;if(this.lock){this.setVValue(this.pv);return}this.lock=!0,this._mdf=this._isFirstFrame;var W,Z=this.effectsSequence.length,G=this.kf?this.pv:this.data.k;for(W=0;W=this._maxLength)this.doubleArrayLength();switch(E){case"v":C=this.v;break;case"i":C=this.i;break;case"o":C=this.o;break;default:C=[];break}if(!C[B]||C[B]&&!I)C[B]=pointPool.newElement();C[B][0]=A,C[B][1]=Q},ShapePath.prototype.setTripleAt=function(A,Q,E,B,I,C,K,J){this.setXYAt(A,Q,"v",K,J),this.setXYAt(E,B,"o",K,J),this.setXYAt(I,C,"i",K,J)},ShapePath.prototype.reverse=function(){var A=new ShapePath;A.setPathData(this.c,this._length);var Q=this.v,E=this.o,B=this.i,I=0;if(this.c)A.setTripleAt(Q[0][0],Q[0][1],B[0][0],B[0][1],E[0][0],E[0][1],0,!1),I=1;var C=this._length-1,K=this._length,J;for(J=I;J=v[v.length-1].t-this.offsetTime)M=v[v.length-1].s?v[v.length-1].s[0]:v[v.length-2].e[0],D=!0;else{var g=q,P=v.length-1,V=!0,S,h,x;while(V){if(S=v[g],h=v[g+1],h.t-this.offsetTime>Z)break;if(g=h.t-this.offsetTime)z=1;else if(ZX&&Z>X)))this._caching.lastIndex=q0||V>-0.000001&&V<0)return B(V*S)/S;return V}function P(){var V=this.props,S=g(V[0]),h=g(V[1]),x=g(V[4]),b=g(V[5]),m=g(V[12]),s=g(V[13]);return"matrix("+S+","+h+","+x+","+b+","+m+","+s+")"}return function(){this.reset=I,this.rotate=C,this.rotateX=K,this.rotateY=J,this.rotateZ=U,this.skew=H,this.skewFromAxis=R,this.shear=Y,this.scale=O,this.setTransform=N,this.translate=$,this.transform=L,this.applyToPoint=q,this.applyToX=M,this.applyToY=F,this.applyToZ=D,this.applyToPointArray=z,this.applyToTriplePoints=T,this.applyToPointStringified=j,this.toCSS=v,this.to2dCSS=P,this.clone=G,this.cloneFromProps=X,this.equals=Z,this.inversePoints=k,this.inversePoint=w,this.getInverseMatrix=_,this._t=this.transform,this.isIdentity=W,this._identity=!0,this._identityCalculated=!1,this.props=createTypedArray("float32",16),this.reset()}}();if(standalone="__[STANDALONE]__",animationData="__[ANIMATIONDATA]__",renderer="",CQ.play=animationManager.play,CQ.pause=animationManager.pause,CQ.setLocationHref=setLocation,CQ.togglePause=animationManager.togglePause,CQ.setSpeed=animationManager.setSpeed,CQ.setDirection=animationManager.setDirection,CQ.stop=animationManager.stop,CQ.searchAnimations=searchAnimations,CQ.registerAnimation=animationManager.registerAnimation,CQ.loadAnimation=loadAnimation,CQ.setSubframeRendering=setSubframeRendering,CQ.resize=animationManager.resize,CQ.goToAndStop=animationManager.goToAndStop,CQ.destroy=animationManager.destroy,CQ.setQuality=setQuality,CQ.inBrowser=inBrowser,CQ.installPlugin=installPlugin,CQ.freeze=animationManager.freeze,CQ.unfreeze=animationManager.unfreeze,CQ.setVolume=animationManager.setVolume,CQ.mute=animationManager.mute,CQ.unmute=animationManager.unmute,CQ.getRegisteredAnimations=animationManager.getRegisteredAnimations,CQ.useWebWorker=setWebWorker,CQ.setIDPrefix=setPrefix,CQ.__getFactory=getFactory,CQ.version="[[BM_VERSION]]",queryString="",standalone)fH=document.getElementsByTagName("script"),EW=fH.length-1,uH=fH[EW]||{src:""},queryString=uH.src?uH.src.replace(/^[^\?]+\??/,""):"",renderer=getQueryVariable("renderer");readyStateCheckInterval=setInterval(checkReady,100);try{if(!(typeof BW==="object"&&typeof Sw!=="undefined")&&!(typeof define==="function"&&define.amd))window.bodymovin=CQ}catch(A){}let ShapeModifiers=function(){var A={},Q={};A.registerModifier=E,A.getModifier=B;function E(I,C){if(!Q[I])Q[I]=C}function B(I,C,K){return new Q[I](C,K)}return A}();ShapeModifier.prototype.initModifierProperties=function(){},ShapeModifier.prototype.addShapeToModifier=function(){},ShapeModifier.prototype.addShape=function(A){if(!this.closed){A.sh.container.addDynamicProperty(A.sh);var Q={shape:A.sh,data:A,localShapeCollection:shapeCollectionPool.newShapeCollection()};if(this.shapes.push(Q),this.addShapeToModifier(Q),this._isAnimated)A.setAsAnimated()}},ShapeModifier.prototype.init=function(A,Q){if(this.shapes=[],this.elem=A,this.initDynamicPropertyContainer(A),this.initModifierProperties(A,Q),this.frameId=initialDefaultFrame,this.closed=!1,this.k=!1,this.dynamicProperties.length)this.k=!0;else this.getValue(!0)},ShapeModifier.prototype.processKeys=function(){if(this.elem.globalData.frameId===this.frameId)return;this.frameId=this.elem.globalData.frameId,this.iterateDynamicProperties()},extendPrototype([DynamicPropertyContainer],ShapeModifier),extendPrototype([ShapeModifier],TrimModifier),TrimModifier.prototype.initModifierProperties=function(A,Q){this.s=PropertyFactory.getProp(A,Q.s,0,0.01,this),this.e=PropertyFactory.getProp(A,Q.e,0,0.01,this),this.o=PropertyFactory.getProp(A,Q.o,0,0,this),this.sValue=0,this.eValue=0,this.getValue=this.processKeys,this.m=Q.m,this._isAnimated=!!this.s.effectsSequence.length||!!this.e.effectsSequence.length||!!this.o.effectsSequence.length},TrimModifier.prototype.addShapeToModifier=function(A){A.pathsData=[]},TrimModifier.prototype.calculateShapeEdges=function(A,Q,E,B,I){var C=[];if(Q<=1)C.push({s:A,e:Q});else if(A>=1)C.push({s:A-1,e:Q-1});else C.push({s:A,e:1}),C.push({s:0,e:Q-1});var K=[],J,U=C.length,Y;for(J=0;JB+E)){var H,R;if(Y.s*I<=B)H=0;else H=(Y.s*I-B)/E;if(Y.e*I>=B+E)R=1;else R=(Y.e*I-B)/E;K.push([H,R])}if(!K.length)K.push([0,0]);return K},TrimModifier.prototype.releasePathsData=function(A){var Q,E=A.length;for(Q=0;Q1)Q=1+B;else if(this.s.v<0)Q=0+B;else Q=this.s.v+B;if(this.e.v>1)E=1+B;else if(this.e.v<0)E=0+B;else E=this.e.v+B;if(Q>E){var I=Q;Q=E,E=I}Q=Math.round(Q*1e4)*0.0001,E=Math.round(E*1e4)*0.0001,this.sValue=Q,this.eValue=E}else Q=this.sValue,E=this.eValue;var C,K,J=this.shapes.length,U,Y,H,R,O,N=0;if(E===Q){for(K=0;K=0;K-=1)if(L=this.shapes[K],L.shape._mdf){if(W=L.localShapeCollection,W.releaseShapes(),this.m===2&&J>1)q=this.calculateShapeEdges(Q,E,L.totalShapeLength,X,N),X+=L.totalShapeLength;else q=[[Z,G]];Y=q.length;for(U=0;U=1)$.push({s:L.totalShapeLength*(Z-1),e:L.totalShapeLength*(G-1)});else $.push({s:L.totalShapeLength*Z,e:L.totalShapeLength}),$.push({s:0,e:L.totalShapeLength*(G-1)});var M=this.addShapes(L,$[0]);if($[0].s!==$[0].e){if($.length>1){var F=L.shape.paths.shapes[L.shape.paths._length-1];if(F.c){var D=M.pop();this.addPaths(M,W),M=this.addShapes(L,$[1],D)}else this.addPaths(M,W),M=this.addShapes(L,$[1])}this.addPaths(M,W)}}L.shape.paths=W}}else if(this._mdf)for(K=0;KQ.e){E.c=!1;break}else{if(Q.s<=Y&&Q.e>=Y+H.addedLength)this.addSegment(I[C].v[J-1],I[C].o[J-1],I[C].i[J],I[C].v[J],E,R,W),W=!1;else N=bez.getNewSegment(I[C].v[J-1],I[C].v[J],I[C].o[J-1],I[C].i[J],(Q.s-Y)/H.addedLength,(Q.e-Y)/H.addedLength,O[J-1]),this.addSegmentFromArray(N,E,R,W),W=!1,E.c=!1;Y+=H.addedLength,R+=1}if(I[C].c&&O.length){if(H=O[J-1],Y<=Q.e){var Z=O[J-1].addedLength;if(Q.s<=Y&&Q.e>=Y+Z)this.addSegment(I[C].v[J-1],I[C].o[J-1],I[C].i[0],I[C].v[0],E,R,W),W=!1;else N=bez.getNewSegment(I[C].v[J-1],I[C].v[0],I[C].o[J-1],I[C].i[0],(Q.s-Y)/Z,(Q.e-Y)/Z,O[J-1]),this.addSegmentFromArray(N,E,R,W),W=!1,E.c=!1}else E.c=!1;Y+=H.addedLength,R+=1}if(E._length)E.setXYAt(E.v[L][0],E.v[L][1],"i",L),E.setXYAt(E.v[E._length-1][0],E.v[E._length-1][1],"o",E._length-1);if(Y>Q.e)break;if(C=this.p.keyframes[this.p.keyframes.length-1].t)H=this.p.getValueAtTime(this.p.keyframes[this.p.keyframes.length-1].t/Y,0),R=this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length-1].t-0.05)/Y,0);else H=this.p.pv,R=this.p.getValueAtTime((this.p._caching.lastFrame+this.p.offsetTime-0.01)/Y,this.p.offsetTime);else if(this.px&&this.px.keyframes&&this.py.keyframes&&this.px.getValueAtTime&&this.py.getValueAtTime){H=[],R=[];var O=this.px,N=this.py;if(O._caching.lastFrame+O.offsetTime<=O.keyframes[0].t)H[0]=O.getValueAtTime((O.keyframes[0].t+0.01)/Y,0),H[1]=N.getValueAtTime((N.keyframes[0].t+0.01)/Y,0),R[0]=O.getValueAtTime(O.keyframes[0].t/Y,0),R[1]=N.getValueAtTime(N.keyframes[0].t/Y,0);else if(O._caching.lastFrame+O.offsetTime>=O.keyframes[O.keyframes.length-1].t)H[0]=O.getValueAtTime(O.keyframes[O.keyframes.length-1].t/Y,0),H[1]=N.getValueAtTime(N.keyframes[N.keyframes.length-1].t/Y,0),R[0]=O.getValueAtTime((O.keyframes[O.keyframes.length-1].t-0.01)/Y,0),R[1]=N.getValueAtTime((N.keyframes[N.keyframes.length-1].t-0.01)/Y,0);else H=[O.pv,N.pv],R[0]=O.getValueAtTime((O._caching.lastFrame+O.offsetTime-0.01)/Y,O.offsetTime),R[1]=N.getValueAtTime((N._caching.lastFrame+N.offsetTime-0.01)/Y,N.offsetTime)}else R=A,H=R;this.v.rotate(-Math.atan2(H[1]-R[1],H[0]-R[0]))}if(this.data.p&&this.data.p.s)if(this.data.p.z)this.v.translate(this.px.v,this.py.v,-this.pz.v);else this.v.translate(this.px.v,this.py.v,0);else this.v.translate(this.p.v[0],this.p.v[1],-this.p.v[2])}this.frameId=this.elem.globalData.frameId}function B(){if(!this.a.k)this.pre.translate(-this.a.v[0],-this.a.v[1],this.a.v[2]),this.appliedTransformations=1;else return;if(!this.s.effectsSequence.length)this.pre.scale(this.s.v[0],this.s.v[1],this.s.v[2]),this.appliedTransformations=2;else return;if(this.sk)if(!this.sk.effectsSequence.length&&!this.sa.effectsSequence.length)this.pre.skewFromAxis(-this.sk.v,this.sa.v),this.appliedTransformations=3;else return;if(this.r){if(!this.r.effectsSequence.length)this.pre.rotate(-this.r.v),this.appliedTransformations=4}else if(!this.rz.effectsSequence.length&&!this.ry.effectsSequence.length&&!this.rx.effectsSequence.length&&!this.or.effectsSequence.length)this.pre.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]),this.appliedTransformations=4}function I(){}function C(U){this._addDynamicProperty(U),this.elem.addDynamicProperty(U),this._isDirty=!0}function K(U,Y,H){if(this.elem=U,this.frameId=-1,this.propType="transform",this.data=Y,this.v=new Matrix,this.pre=new Matrix,this.appliedTransformations=0,this.initDynamicPropertyContainer(H||U),Y.p&&Y.p.s){if(this.px=PropertyFactory.getProp(U,Y.p.x,0,0,this),this.py=PropertyFactory.getProp(U,Y.p.y,0,0,this),Y.p.z)this.pz=PropertyFactory.getProp(U,Y.p.z,0,0,this)}else this.p=PropertyFactory.getProp(U,Y.p||{k:[0,0,0]},1,0,this);if(Y.rx){if(this.rx=PropertyFactory.getProp(U,Y.rx,0,degToRads,this),this.ry=PropertyFactory.getProp(U,Y.ry,0,degToRads,this),this.rz=PropertyFactory.getProp(U,Y.rz,0,degToRads,this),Y.or.k[0].ti){var R,O=Y.or.k.length;for(R=0;R0)E-=1,this._elements.unshift(Q[E]);if(this.dynamicProperties.length)this.k=!0;else this.getValue(!0)},RepeaterModifier.prototype.resetElements=function(A){var Q,E=A.length;for(Q=0;Q0?Math.floor(O):Math.ceil(O),L=this.pMatrix.props,W=this.rMatrix.props,Z=this.sMatrix.props;this.pMatrix.reset(),this.rMatrix.reset(),this.sMatrix.reset(),this.tMatrix.reset(),this.matrix.reset();var G=0;if(O>0){while(G<$)this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,1,!1),G+=1;if(N)this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,N,!1),G+=N}else if(O<0){while(G>$)this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,1,!0),G-=1;if(N)this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,-N,!0),G-=N}B=this.data.m===1?0:this._currentCopies-1,I=this.data.m===1?1:-1,C=this._currentCopies;var X,q;while(C){if(Q=this.elemsData[B].it,E=Q[Q.length-1].transform.mProps.v.props,q=E.length,Q[Q.length-1].transform.mProps._mdf=!0,Q[Q.length-1].transform.op._mdf=!0,Q[Q.length-1].transform.op.v=this._currentCopies===1?this.so.v:this.so.v+(this.eo.v-this.so.v)*(B/(this._currentCopies-1)),G!==0){if(B!==0&&I===1||B!==this._currentCopies-1&&I===-1)this.applyTransforms(this.pMatrix,this.rMatrix,this.sMatrix,this.tr,1,!1);this.matrix.transform(W[0],W[1],W[2],W[3],W[4],W[5],W[6],W[7],W[8],W[9],W[10],W[11],W[12],W[13],W[14],W[15]),this.matrix.transform(Z[0],Z[1],Z[2],Z[3],Z[4],Z[5],Z[6],Z[7],Z[8],Z[9],Z[10],Z[11],Z[12],Z[13],Z[14],Z[15]),this.matrix.transform(L[0],L[1],L[2],L[3],L[4],L[5],L[6],L[7],L[8],L[9],L[10],L[11],L[12],L[13],L[14],L[15]);for(X=0;X{P.helper=U(P),P.cache={}}),this.fonts=q.list;return}var F=q.list,D,_=F.length,w=_;for(D=0;D<_;D+=1){var k=!0,T,z;if(F[D].loaded=!1,F[D].monoCase=K(F[D].fFamily,"monospace"),F[D].sansCase=K(F[D].fFamily,"sans-serif"),!F[D].fPath)F[D].loaded=!0,w-=1;else if(F[D].fOrigin==="p"||F[D].origin===3){if(T=document.querySelectorAll('style[f-forigin="p"][f-family="'+F[D].fFamily+'"], style[f-origin="3"][f-family="'+F[D].fFamily+'"]'),T.length>0)k=!1;if(k){var j=createTag("style");j.setAttribute("f-forigin",F[D].fOrigin),j.setAttribute("f-origin",F[D].origin),j.setAttribute("f-family",F[D].fFamily),j.type="text/css",j.innerText="@font-face {font-family: "+F[D].fFamily+"; font-style: normal; src: url('"+F[D].fPath+"');}",M.appendChild(j)}}else if(F[D].fOrigin==="g"||F[D].origin===1){T=document.querySelectorAll('link[f-forigin="g"], link[f-origin="1"]');for(z=0;zA){if(this.isInRange!==!0)this.globalData._mdf=!0,this._mdf=!0,this.isInRange=!0,this.show()}else if(this.isInRange!==!1)this.globalData._mdf=!0,this.isInRange=!1,this.hide()},renderRenderable:function(){var A,Q=this.renderableComponents.length;for(A=0;A0.1)this.audio.seek(this._currentTime/this.globalData.frameRate)}},AudioElement.prototype.show=function(){},AudioElement.prototype.hide=function(){this.audio.pause(),this._isPlaying=!1},AudioElement.prototype.pause=function(){this.audio.pause(),this._isPlaying=!1,this._canPlay=!1},AudioElement.prototype.resume=function(){this._canPlay=!0},AudioElement.prototype.setRate=function(A){this.audio.rate(A)},AudioElement.prototype.volume=function(A){this._volumeMultiplier=A,this._previousVolume=A*this._volume,this.audio.volume(this._previousVolume)},AudioElement.prototype.getBaseElement=function(){return null},AudioElement.prototype.destroy=function(){},AudioElement.prototype.sourceRectAtTime=function(){},AudioElement.prototype.initExpressions=function(){},BaseRenderer.prototype.checkLayers=function(A){var Q,E=this.layers.length,B;this.completeLayers=!0;for(Q=E-1;Q>=0;Q-=1){if(!this.elements[Q]){if(B=this.layers[Q],B.ip-B.st<=A-this.layers[Q].st&&B.op-B.st>A-this.layers[Q].st)this.buildItem(Q)}this.completeLayers=this.elements[Q]?this.completeLayers:!1}this.checkPendingElements()},BaseRenderer.prototype.createItem=function(A){switch(A.ty){case 2:return this.createImage(A);case 0:return this.createComp(A);case 1:return this.createSolid(A);case 3:return this.createNull(A);case 4:return this.createShape(A);case 5:return this.createText(A);case 6:return this.createAudio(A);case 13:return this.createCamera(A);case 15:return this.createFootage(A);default:return this.createNull(A)}},BaseRenderer.prototype.createCamera=function(){throw new Error("You're using a 3d camera. Try the html renderer.")},BaseRenderer.prototype.createAudio=function(A){return new AudioElement(A,this.globalData,this)},BaseRenderer.prototype.createFootage=function(A){return new FootageElement(A,this.globalData,this)},BaseRenderer.prototype.buildAllItems=function(){var A,Q=this.layers.length;for(A=0;A1)B+=" C"+Q.o[I-1][0]+","+Q.o[I-1][1]+" "+Q.i[0][0]+","+Q.i[0][1]+" "+Q.v[0][0]+","+Q.v[0][1];if(E.lastPath!==B){var K="";if(E.elem){if(Q.c)K=A.inv?this.solidPath+B:B;E.elem.setAttribute("d",K)}E.lastPath=B}},MaskElement.prototype.destroy=function(){this.element=null,this.globalData=null,this.maskElement=null,this.data=null,this.masksProperties=null};let filtersFactory=function(){var A={};A.createFilter=Q,A.createAlphaToLuminanceFilter=E;function Q(B,I){var C=createNS("filter");if(C.setAttribute("id",B),I!==!0)C.setAttribute("filterUnits","objectBoundingBox"),C.setAttribute("x","0%"),C.setAttribute("y","0%"),C.setAttribute("width","100%"),C.setAttribute("height","100%");return C}function E(){var B=createNS("feColorMatrix");return B.setAttribute("type","matrix"),B.setAttribute("color-interpolation-filters","sRGB"),B.setAttribute("values","0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1"),B}return A}(),featureSupport=function(){var A={maskType:!0};if(/MSIE 10/i.test(navigator.userAgent)||/MSIE 9/i.test(navigator.userAgent)||/rv:11.0/i.test(navigator.userAgent)||/Edge\/\d./i.test(navigator.userAgent))A.maskType=!1;return A}();registeredEffects={},idPrefix="filter_result_",SVGEffects.prototype.renderFrame=function(A){var Q,E=this.filters.length;for(Q=0;Q=0;A-=1)if(E=this.shapeModifiers[A].processShapes(this._isFirstFrame),E)break},searchProcessedElement:function(A){var Q=this.processedElements,E=0,B=Q.length;while(E0.01)return!1;E+=1}return!0},GradientProperty.prototype.checkCollapsable=function(){if(this.o.length/2!==this.c.length/4)return!1;if(this.data.k.k[0].s){var A=0,Q=this.data.k.k.length;while(A0)Z=O.transformers[k].mProps._mdf||Z,w-=1,k-=1;if(Z){w=M-O.styles[X].lvl,k=O.transformers.length-1;while(w>0)_=O.transformers[k].mProps.v.props,D.transform(_[0],_[1],_[2],_[3],_[4],_[5],_[6],_[7],_[8],_[9],_[10],_[11],_[12],_[13],_[14],_[15]),w-=1,k-=1}}else D=A;if(F=O.sh.paths,L=F._length,Z){W="";for($=0;$=1)j=0.99;else if(j<=-1)j=-0.99;var v=T*j,g=Math.cos(z+O.a.v)*v+W[0],P=Math.sin(z+O.a.v)*v+W[1];if($.setAttribute("fx",g),$.setAttribute("fy",P),L&&!O.g._collapsable)O.of.setAttribute("fx",g),O.of.setAttribute("fy",P)}}}function H(R,O,N){var{style:$,d:L}=O;if(L&&(L._mdf||N)&&L.dashStr)$.pElem.setAttribute("stroke-dasharray",L.dashStr),$.pElem.setAttribute("stroke-dashoffset",L.dashoffset[0]);if(O.c&&(O.c._mdf||N))$.pElem.setAttribute("stroke","rgb("+bmFloor(O.c.v[0])+","+bmFloor(O.c.v[1])+","+bmFloor(O.c.v[2])+")");if(O.o._mdf||N)$.pElem.setAttribute("stroke-opacity",O.o.v);if(O.w._mdf||N){if($.pElem.setAttribute("stroke-width",O.w.v),$.msElem)$.msElem.setAttribute("stroke-width",O.w.v)}}return E}();extendPrototype([BaseElement,TransformElement,SVGBaseElement,IShapeElement,HierarchyElement,FrameElement,RenderableDOMElement],SVGShapeElement),SVGShapeElement.prototype.initSecondaryElement=function(){},SVGShapeElement.prototype.identityMatrix=new Matrix,SVGShapeElement.prototype.buildExpressionInterface=function(){},SVGShapeElement.prototype.createContent=function(){this.searchShapes(this.shapesData,this.itemsData,this.prevViewData,this.layerElement,0,[],!0),this.filterUniqueShapes()},SVGShapeElement.prototype.filterUniqueShapes=function(){var A,Q=this.shapes.length,E,B,I=this.stylesList.length,C,K=[],J=!1;for(B=0;B1&&J)this.setShapesAsAnimated(K)}},SVGShapeElement.prototype.setShapesAsAnimated=function(A){var Q,E=A.length;for(Q=0;Q=0;U-=1){if(W=this.searchProcessedElement(A[U]),!W)A[U]._render=K;else Q[U]=E[W-1];if(A[U].ty==="fl"||A[U].ty==="st"||A[U].ty==="gf"||A[U].ty==="gs"||A[U].ty==="no"){if(!W)Q[U]=this.createStyleElement(A[U],I);else Q[U].style.closed=!1;if(A[U]._render){if(Q[U].style.pElem.parentNode!==B)B.appendChild(Q[U].style.pElem)}O.push(Q[U].style)}else if(A[U].ty==="gr"){if(!W)Q[U]=this.createGroupElement(A[U]);else{R=Q[U].it.length;for(H=0;H1,this.kf)this.addEffect(this.getKeyframeValue.bind(this));return this.kf},TextProperty.prototype.addEffect=function(A){this.effectsSequence.push(A),this.elem.addDynamicProperty(this)},TextProperty.prototype.getValue=function(A){if((this.elem.globalData.frameId===this.frameId||!this.effectsSequence.length)&&!A)return;this.currentData.t=this.data.d.k[this.keysIndex].s.t;var Q=this.currentData,E=this.keysIndex;if(this.lock){this.setCurrentData(this.currentData);return}this.lock=!0,this._mdf=!1;var B,I=this.effectsSequence.length,C=A||this.data.d.k[this.keysIndex].s;for(B=0;BQ)break;E+=1}if(this.keysIndex!==E)this.keysIndex=E;return this.data.d.k[this.keysIndex].s},TextProperty.prototype.buildFinalText=function(A){var Q=[],E=0,B=A.length,I,C,K=!1;while(E=55296&&I<=56319)if(C=A.charCodeAt(E+1),C>=56320&&C<=57343){if(K||FontManager.isModifier(I,C))Q[Q.length-1]+=A.substr(E,2),K=!1;else Q.push(A.substr(E,2));E+=1}else Q.push(A.charAt(E));else if(I>56319)if(C=A.charCodeAt(E+1),FontManager.isZeroWidthJoiner(I,C))K=!0,Q[Q.length-1]+=A.substr(E,2),E+=1;else Q.push(A.charAt(E));else if(FontManager.isZeroWidthJoiner(I))Q[Q.length-1]+=A.charAt(E),K=!0;else Q.push(A.charAt(E));E+=1}return Q},TextProperty.prototype.completeTextData=function(A){A.__complete=!0;var Q=this.elem.globalData.fontManager,E=this.data,B=[],I,C,K,J=0,U,Y=E.m.g,H=0,R=0,O=0,N=[],$=0,L=0,W,Z,G=Q.getFontByName(A.f),X,q=0,M=getFontProperties(G);A.fWeight=M.weight,A.fStyle=M.style,A.finalSize=A.s,A.finalText=this.buildFinalText(A.t),C=A.finalText.length,A.finalLineHeight=A.lh;var F=A.tr/1000*A.finalSize,D;if(A.sz){var _=!0,w=A.sz[0],k=A.sz[1],T,z;while(_){z=this.buildFinalText(A.t),T=0,$=0,C=z.length,F=A.tr/1000*A.finalSize;var j=-1;for(I=0;Iw&&z[I]!==" "){if(j===-1)C+=1;else I=j;T+=A.finalLineHeight||A.finalSize*1.2,z.splice(I,j===I?1:0,"\r"),j=-1,$=0}else $+=q,$+=F}if(T+=G.ascent*A.finalSize/100,this.canResize&&A.finalSize>this.minimumFontSize&&kL?$:L,$=-2*F,U="",K=!0,O+=1;else U=g;if(Q.chars)X=Q.getCharData(g,G.fStyle,Q.getFontByName(A.f).fFamily),q=K?0:X.w*A.finalSize/100;else q=Q.measureText(U,A.f,A.finalSize);if(g===" ")v+=q+F;else $+=q+F+v,v=0;if(B.push({l:q,an:q,add:H,n:K,anIndexes:[],val:U,line:O,animatorJustifyOffset:0}),Y==2){if(H+=q,U===""||U===" "||I===C-1){if(U===""||U===" ")H-=q;while(R<=I)B[R].an=H,B[R].ind=J,B[R].extra=q,R+=1;J+=1,H=0}}else if(Y==3){if(H+=q,U===""||I===C-1){if(U==="")H-=q;while(R<=I)B[R].an=H,B[R].ind=J,B[R].extra=q,R+=1;H=0,J+=1}}else B[J].ind=J,B[J].extra=0,J+=1}if(A.l=B,L=$>L?$:L,N.push($),A.sz)A.boxWidth=A.sz[0],A.justifyOffset=0;else switch(A.boxWidth=L,A.j){case 1:A.justifyOffset=-A.boxWidth;break;case 2:A.justifyOffset=-A.boxWidth/2;break;default:A.justifyOffset=0}A.lineWidths=N;var P=E.a,V,S;Z=P.length;var h,x,b=[];for(W=0;W0)K=this.ne.v/100;else J=-this.ne.v/100;if(this.xe.v>0)U=1-this.xe.v/100;else Y=1+this.xe.v/100;var H=BezierFactory.getBezierEasing(K,J,U,Y).get,R=0,O=this.finalS,N=this.finalE,$=this.data.sh;if($===2){if(N===O)R=C>=N?1:0;else R=A(0,Q(0.5/(N-O)+(C-O)/(N-O),1));R=H(R)}else if($===3){if(N===O)R=C>=N?0:1;else R=1-A(0,Q(0.5/(N-O)+(C-O)/(N-O),1));R=H(R)}else if($===4){if(N===O)R=0;else if(R=A(0,Q(0.5/(N-O)+(C-O)/(N-O),1)),R<0.5)R*=2;else R=1-2*(R-0.5);R=H(R)}else if($===5){if(N===O)R=0;else{var L=N-O;C=Q(A(0,C+0.5-O),N-O);var W=-L/2+C,Z=L/2;R=Math.sqrt(1-W*W/(Z*Z))}R=H(R)}else if($===6){if(N===O)R=0;else C=Q(A(0,C+0.5-O),N-O),R=(1+Math.cos(Math.PI+Math.PI*2*C/(N-O)))/2;R=H(R)}else{if(C>=E(O))if(C-O<0)R=A(0,Q(Q(N,1)-(O-C),1));else R=A(0,Q(N-C,1));R=H(R)}if(this.sm.v!==100){var G=this.sm.v*0.01;if(G===0)G=0.00000001;var X=0.5-G*0.5;if(R1)R=1}return R*this.a.v},getValue:function(C){if(this.iterateDynamicProperties(),this._mdf=C||this._mdf,this._currentTextLength=this.elem.textProperty.currentData.l.length||0,C&&this.data.r===2)this.e.v=this._currentTextLength;var K=this.data.r===2?1:100/this.data.totalChars,J=this.o.v/K,U=this.s.v/K+J,Y=this.e.v/K+J;if(U>Y){var H=U;U=Y,Y=H}this.finalS=U,this.finalE=Y}},extendPrototype([DynamicPropertyContainer],B);function I(C,K,J){return new B(C,K,J)}return{getTextSelectorProp:I}}();TextAnimatorProperty.prototype.searchProperties=function(){var A,Q=this._textData.a.length,E,B=PropertyFactory.getProp;for(A=0;A=$+HA||!M)w=($+HA-W)/L.partialLength,i=q.point[0]+(L.point[0]-q.point[0])*w,n=q.point[1]+(L.point[1]-q.point[1])*w,C.translate(-E[0]*O[H].an*0.005,-(E[1]*v)*0.01),Z=!1;else if(M){if(W+=L.partialLength,G+=1,G>=M.length)if(G=0,X+=1,!F[X])if(T.v.c)G=0,X=0,M=F[X].points;else W-=L.partialLength,M=null;else M=F[X].points;if(M)q=L,L=M[G],D=L.partialLength}s=O[H].an/2-O[H].add,C.translate(-s,0,0)}else s=O[H].an/2-O[H].add,C.translate(-s,0,0),C.translate(-E[0]*O[H].an*0.005,-E[1]*v*0.01,0);for(S=0;SA?this.textSpans[A].span:createNS(J?"g":"text"),X<=A){if(U.setAttribute("stroke-linecap","butt"),U.setAttribute("stroke-linejoin","round"),U.setAttribute("stroke-miterlimit","4"),this.textSpans[A].span=U,J){var M=createNS("g");U.appendChild(M),this.textSpans[A].childSpan=M}this.textSpans[A].span=U,this.layerElement.appendChild(U)}U.style.display="inherit"}if(Y.reset(),R){if(K[A].n)O=-L,N+=E.yOffset,N+=$?1:0,$=!1;this.applyTextPropertiesToMatrix(E,Y,K[A].line,O,N),O+=K[A].l||0,O+=L}if(J){q=this.globalData.fontManager.getCharData(E.finalText[A],B.fStyle,this.globalData.fontManager.getFontByName(E.f).fFamily);var F;if(q.t===1)F=new SVGCompElement(q.data,this.globalData,this);else{var D=emptyShapeData;if(q.data&&q.data.shapes)D=this.buildShapeData(q.data,E.finalSize);F=new SVGShapeElement(D,this.globalData,this)}if(this.textSpans[A].glyph){var _=this.textSpans[A].glyph;this.textSpans[A].childSpan.removeChild(_.layerElement),_.destroy()}if(this.textSpans[A].glyph=F,F._debug=!0,F.prepareFrame(0),F.renderFrame(),this.textSpans[A].childSpan.appendChild(F.layerElement),q.t===1)this.textSpans[A].childSpan.setAttribute("transform","scale("+E.finalSize/100+","+E.finalSize/100+")")}else{if(R)U.setAttribute("transform","translate("+Y.props[12]+","+Y.props[13]+")");U.textContent=K[A].val,U.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve")}}if(R&&U)U.setAttribute("d",H)}while(A=0;Q-=1)if(this.completeLayers||this.elements[Q])this.elements[Q].prepareFrame(A-this.layers[Q].st);if(this.globalData._mdf){for(Q=0;Q=0;E-=1)if(this.completeLayers||this.elements[E]){if(this.elements[E].prepareFrame(this.renderedFrame-this.layers[E].st),this.elements[E]._mdf)this._mdf=!0}},ICompElement.prototype.renderInnerContent=function(){var A,Q=this.layers.length;for(A=0;A=0;E-=1)C=A.transforms[E].transform.mProps.v.props,A.finalTransform.transform(C[0],C[1],C[2],C[3],C[4],C[5],C[6],C[7],C[8],C[9],C[10],C[11],C[12],C[13],C[14],C[15])}A._mdf=I},processSequences:function(A){var Q,E=this.sequenceList.length;for(Q=0;Q=0;C-=1){if(R=this.searchProcessedElement(A[C]),!R)A[C]._shouldRender=B;else Q[C]=E[R-1];if(A[C].ty==="fl"||A[C].ty==="st"||A[C].ty==="gf"||A[C].ty==="gs"){if(!R)Q[C]=this.createStyleElement(A[C],$);else Q[C].style.closed=!1;Y.push(Q[C].style)}else if(A[C].ty==="gr"){if(!R)Q[C]=this.createGroupElement(A[C]);else{U=Q[C].it.length;for(J=0;J=0;I-=1)if(Q[I].ty==="tr")K=E[I].transform,this.renderShapeTransform(A,K);else if(Q[I].ty==="sh"||Q[I].ty==="el"||Q[I].ty==="rc"||Q[I].ty==="sr")this.renderPath(Q[I],E[I]);else if(Q[I].ty==="fl")this.renderFill(Q[I],E[I],K);else if(Q[I].ty==="st")this.renderStroke(Q[I],E[I],K);else if(Q[I].ty==="gf"||Q[I].ty==="gs")this.renderGradientFill(Q[I],E[I],K);else if(Q[I].ty==="gr")this.renderShape(K,Q[I].it,E[I].it);else if(Q[I].ty==="tm");if(B)this.drawLayer()},CVShapeElement.prototype.renderStyledShape=function(A,Q){if(this._isFirstFrame||Q._mdf||A.transforms._mdf){var E=A.trNodes,B=Q.paths,I,C,K,J=B._length;E.length=0;var U=A.transforms.finalTransform;for(K=0;K=1)H=0.99;else if(H<=-1)H=-0.99;var R=U*H,O=Math.cos(Y+Q.a.v)*R+K[0],N=Math.sin(Y+Q.a.v)*R+K[1];I=C.createRadialGradient(O,N,0,K[0],K[1],U)}var $,L=A.g.p,W=Q.g.c,Z=1;for($=0;$C&&U==="xMidYMid slice"||IE&&C==="meet"||BE&&C==="slice"))this.transformCanvas.tx=(A-this.transformCanvas.w*(Q/this.transformCanvas.h))/2*this.renderConfig.dpr;else if(J==="xMax"&&(BE&&C==="slice"))this.transformCanvas.tx=(A-this.transformCanvas.w*(Q/this.transformCanvas.h))*this.renderConfig.dpr;else this.transformCanvas.tx=0;if(U==="YMid"&&(B>E&&C==="meet"||BE&&C==="meet"||B=0;A-=1)if(this.elements[A])this.elements[A].destroy();this.elements.length=0,this.globalData.canvasContext=null,this.animationItem.container=null,this.destroyed=!0},CanvasRendererBase.prototype.renderFrame=function(A,Q){if(this.renderedFrame===A&&this.renderConfig.clearCanvas===!0&&!Q||this.destroyed||A===-1)return;this.renderedFrame=A,this.globalData.frameNum=A-this.animationItem._isFirstFrame,this.globalData.frameId+=1,this.globalData._mdf=!this.renderConfig.clearCanvas||Q,this.globalData.projectInterface.currentFrame=A;var E,B=this.layers.length;if(!this.completeLayers)this.checkLayers(A);for(E=0;E=0;E-=1)if(this.completeLayers||this.elements[E])this.elements[E].renderFrame();if(this.renderConfig.clearCanvas!==!0)this.restore()}},CanvasRendererBase.prototype.buildItem=function(A){var Q=this.elements;if(Q[A]||this.layers[A].ty===99)return;var E=this.createItem(this.layers[A],this,this.globalData);Q[A]=E,E.initExpressions()},CanvasRendererBase.prototype.checkPendingElements=function(){while(this.pendingElements.length){var A=this.pendingElements.pop();A.checkParenting()}},CanvasRendererBase.prototype.hide=function(){this.animationItem.container.style.display="none"},CanvasRendererBase.prototype.show=function(){this.animationItem.container.style.display="block"},extendPrototype([CanvasRendererBase,ICompElement,CVBaseElement],CVCompElement),CVCompElement.prototype.renderInnerContent=function(){var A=this.canvasContext;A.beginPath(),A.moveTo(0,0),A.lineTo(this.data.w,0),A.lineTo(this.data.w,this.data.h),A.lineTo(0,this.data.h),A.lineTo(0,0),A.clip();var Q,E=this.layers.length;for(Q=E-1;Q>=0;Q-=1)if(this.completeLayers||this.elements[Q])this.elements[Q].renderFrame()},CVCompElement.prototype.destroy=function(){var A,Q=this.layers.length;for(A=Q-1;A>=0;A-=1)if(this.elements[A])this.elements[A].destroy();this.layers=null,this.elements=null},CVCompElement.prototype.createComp=function(A){return new CVCompElement(A,this.globalData,this)},extendPrototype([CanvasRendererBase],CanvasRenderer),CanvasRenderer.prototype.createComp=function(A){return new CVCompElement(A,this.globalData,this)},registerRenderer("canvas",CanvasRenderer),ShapeModifiers.registerModifier("tm",TrimModifier),ShapeModifiers.registerModifier("pb",PuckerAndBloatModifier),ShapeModifiers.registerModifier("rp",RepeaterModifier),ShapeModifiers.registerModifier("rd",RoundCornersModifier);let Expressions=function(){var A={};A.initExpressions=Q;function Q(E){var B=0,I=[];function C(){B+=1}function K(){if(B-=1,B===0)U()}function J(Y){if(I.indexOf(Y)===-1)I.push(Y)}function U(){var Y,H=I.length;for(Y=0;YE){var B=E;E=Q,Q=B}return Math.min(Math.max(A,Q),E)}function radiansToDegrees(A){return A/degToRads}var radians_to_degrees=radiansToDegrees;function degreesToRadians(A){return A*degToRads}var degrees_to_radians=radiansToDegrees,helperLengthArray=[0,0,0,0,0,0];function length(A,Q){if(typeof A==="number"||A instanceof Number)return Q=Q||0,Math.abs(A-Q);if(!Q)Q=helperLengthArray;var E,B=Math.min(A.length,Q.length),I=0;for(E=0;E0.5?Y/(2-I-C):Y/(I+C),I){case Q:K=(E-B)/Y+(E1)E-=1;if(E<0.16666666666666666)return A+(Q-A)*6*E;if(E<0.5)return Q;if(E<0.6666666666666666)return A+(Q-A)*(0.6666666666666666-E)*6;return A}function hslToRgb(A){var Q=A[0],E=A[1],B=A[2],I,C,K;if(E===0)I=B,K=B,C=B;else{var J=B<0.5?B*(1+E):B+E-B*E,U=2*B-J;I=hue2rgb(U,J,Q+0.3333333333333333),C=hue2rgb(U,J,Q),K=hue2rgb(U,J,Q-0.3333333333333333)}return[I,C,K,A[3]]}function linear(A,Q,E,B,I){if(B===void 0||I===void 0)B=Q,I=E,Q=0,E=1;if(E=E)return I;var K=E===Q?0:(A-Q)/(E-Q);if(!B.length)return B+(I-B)*K;var J,U=B.length,Y=createTypedArray("float32",U);for(J=0;J1){for(I=0;I1)Q=1;else if(Q<0)Q=0;var K=A(Q);if($bm_isInstanceOfArray(I)){var J,U=I.length,Y=createTypedArray("float32",U);for(J=0;Jdata.k[Q].t&&Adata.k[Q+1].t-A)B=Q+2,I=data.k[Q+1].t;else B=Q+1,I=data.k[Q].t;break}if(B===-1)B=Q+1,I=data.k[Q].t}var C={};return C.index=B,C.time=I/elem.comp.globalData.frameRate,C}function key(A){var Q,E,B;if(!data.k.length||typeof data.k[0]==="number")throw new Error("The property has no keyframe at index "+A);A-=1,Q={time:data.k[A].t/elem.comp.globalData.frameRate,value:[]};var I=Object.prototype.hasOwnProperty.call(data.k[A],"s")?data.k[A].s:data.k[A-1].e;B=I.length;for(E=0;EMath.pow(Q/255*0.9478672986+0.0521327014,2.4));var j0={};j0.toRGBA8=function(A){var{width:Q,height:E}=A;if(A.tabs.acTL==null)return[j0.toRGBA8.decodeImage(A.data,Q,E,A).buffer];var B=[];if(A.frames[0].data==null)A.frames[0].data=A.data;var I=Q*E*4,C=new Uint8Array(I),K=new Uint8Array(I),J=new Uint8Array(I);for(var U=0;U>3)]>>7-((N&7)<<0)&1,T=3*k;J[X]=q[T],J[X+1]=q[T+1],J[X+2]=q[T+2],J[X+3]=k>2)]>>6-((N&3)<<1)&3,T=3*k;J[X]=q[T],J[X+1]=q[T+1],J[X+2]=q[T+2],J[X+3]=k>1)]>>4-((N&1)<<2)&15,T=3*k;J[X]=q[T],J[X+1]=q[T+1],J[X+2]=q[T+2],J[X+3]=k>>3)]>>>7-(P&7)&1),V=j==W*255?0:255;U[g+P]=V<<24|j<<16|j<<8|j}else if(H==2)for(var P=0;P>>2)]>>>6-((P&3)<<1)&3),V=j==W*85?0:255;U[g+P]=V<<24|j<<16|j<<8|j}else if(H==4)for(var P=0;P>>1)]>>>4-((P&1)<<2)&15),V=j==W*17?0:255;U[g+P]=V<<24|j<<16|j<<8|j}else if(H==8)for(var P=0;P>>2<<5);while(I==0){if(I=W(Q,O,1),C=W(Q,O+1,2),O+=3,C==0){if((O&7)!=0)O+=8-(O&7);var _=(O>>>3)+4,w=Q[_-4]|Q[_-3]<<8;if(D)E=A.H.W(E,R+w);E.set(new B(Q.buffer,Q.byteOffset+_,w),R),O=_+w<<3,R+=w;continue}if(D)E=A.H.W(E,R+131072);if(C==1)N=F.J,$=F.h,Y=511,H=31;if(C==2){K=Z(Q,O,5)+257,J=Z(Q,O+5,5)+1,U=Z(Q,O+10,4)+4,O+=14;var k=1;for(var T=0;T<38;T+=2)F.Q[T]=0,F.Q[T+1]=0;for(var T=0;Tk)k=z}O+=3*U,X(F.Q,k),q(F.Q,k,F.u),N=F.w,$=F.d,O=G(F.u,(1<>>4;if(P>>>8==0)E[R++]=P;else if(P==256)break;else{var V=R+P-254;if(P>264){var S=F.q[P-257];V=R+(S>>>3)+Z(Q,O,S&7),O+=S&7}var h=$[M(Q,O)&H];O+=h&15;var x=h>>>4,b=F.c[x],m=(b>>>4)+W(Q,O,b&15);O+=b&15;while(R>>4;if(R<=15)K[Y]=R,Y++;else{var O=0,N=0;if(R==16)N=3+J(I,C,2),C+=2,O=K[Y-1];else if(R==17)N=3+J(I,C,3),C+=3;else if(R==18)N=11+J(I,C,7),C+=7;var $=Y+N;while(Y<$)K[Y]=O,Y++}}return C},A.H.V=function(Q,E,B,I){var C=0,K=0,J=I.length>>>1;while(KC)C=U;K++}while(K>1,Y=Q[J+1],H=U<<4|Y,R=E-Y,O=Q[J]<>>15-E;B[$]=H,O++}}},A.H.l=function(Q,E){var B=A.H.m.r,I=15-E;for(var C=0;C>>I}},A.H.M=function(Q,E,B){B=B<<(E&7);var I=E>>>3;Q[I]|=B,Q[I+1]|=B>>>8},A.H.I=function(Q,E,B){B=B<<(E&7);var I=E>>>3;Q[I]|=B,Q[I+1]|=B>>>8,Q[I+2]|=B>>>16},A.H.e=function(Q,E,B){return(Q[E>>>3]|Q[(E>>>3)+1]<<8)>>>(E&7)&(1<>>3]|Q[(E>>>3)+1]<<8|Q[(E>>>3)+2]<<16)>>>(E&7)&(1<>>3]|Q[(E>>>3)+1]<<8|Q[(E>>>3)+2]<<16)>>>(E&7)},A.H.i=function(Q,E){return(Q[E>>>3]|Q[(E>>>3)+1]<<8|Q[(E>>>3)+2]<<16|Q[(E>>>3)+3]<<24)>>>(E&7)},A.H.m=function(){var Q=Uint16Array,E=Uint32Array;return{K:new Q(16),j:new Q(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[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,999,999,999],T:[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,0,0,0],q:new Q(32),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,65535,65535],z:[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,0,0],c:new E(32),J:new Q(512),_:[],h:new Q(32),$:[],w:new Q(32768),C:[],v:[],d:new Q(32768),D:[],u:new Q(512),Q:[],r:new Q(32768),s:new E(286),Y:new E(30),a:new E(19),t:new E(15000),k:new Q(65536),g:new Q(32768)}}(),function(){var Q=A.H.m,E=32768;for(var B=0;B>>1|(I&1431655765)<<1,I=(I&3435973836)>>>2|(I&858993459)<<2,I=(I&4042322160)>>>4|(I&252645135)<<4,I=(I&4278255360)>>>8|(I&16711935)<<8,Q.r[B]=(I>>>16|I<<16)>>>17}function C(K,J,U){while(J--!=0)K.push(0,U)}for(var B=0;B<32;B++)Q.q[B]=Q.S[B]<<3|Q.T[B],Q.c[B]=Q.p[B]<<4|Q.z[B];C(Q._,144,8),C(Q._,112,9),C(Q._,24,7),C(Q._,8,8),A.H.n(Q._,9),A.H.A(Q._,9,Q.J),A.H.l(Q._,9),C(Q.$,32,5),A.H.n(Q.$,5),A.H.A(Q.$,5,Q.h),A.H.l(Q.$,5),C(Q.Q,19,0),C(Q.C,286,0),C(Q.D,30,0),C(Q.v,320,0)}(),A.H.N}();j0.decode._readInterlace=function(A,Q){var{width:E,height:B}=Q,I=j0.decode._getBPP(Q),C=I>>3,K=Math.ceil(E*I/8),J=new Uint8Array(B*K),U=0,Y=[0,0,4,0,2,0,1],H=[0,4,0,2,0,1,0],R=[8,8,8,4,4,2,2],O=[8,8,4,4,2,2,1],N=0;while(N<7){var $=R[N],L=O[N],W=0,Z=0,G=Y[N];while(G>3],D=D>>7-(w&7)&1,J[F*K+(_>>3)]|=D<<7-((_&7)<<0);if(I==2)D=A[w>>3],D=D>>6-(w&7)&3,J[F*K+(_>>2)]|=D<<6-((_&3)<<1);if(I==4)D=A[w>>3],D=D>>4-(w&7)&15,J[F*K+(_>>1)]|=D<<4-((_&1)<<2);if(I>=8){var k=F*K+_*C;for(var T=0;T>3)+T]}w+=I,_+=L}M++,F+=$}if(W*Z!=0)U+=Z*(1+q);N=N+1}return J};j0.decode._getBPP=function(A){var Q=[1,null,3,1,2,null,4][A.ctype];return Q*A.depth};j0.decode._filterZero=function(A,Q,E,B,I){var C=j0.decode._getBPP(Q),K=Math.ceil(B*C/8),J=j0.decode._paeth;C=Math.ceil(C/8);var U,Y,H=A[E],R=0;if(H>1)A[E]=[0,0,1][H-2];if(H==3)for(R=C;R>>1)&255;for(var O=0;O>>1);for(;R>>1)}else{for(;R>8&255,A[Q+1]=E&255},readUint:function(A,Q){return A[Q]*16777216+(A[Q+1]<<16|A[Q+2]<<8|A[Q+3])},writeUint:function(A,Q,E){A[Q]=E>>24&255,A[Q+1]=E>>16&255,A[Q+2]=E>>8&255,A[Q+3]=E&255},readASCII:function(A,Q,E){var B="";for(var I=0;I=0&&J>=0)R=N*Q+$<<2,O=(J+N)*I+K+$<<2;else R=(-J+N)*Q-K+$<<2,O=N*I+$<<2;if(U==0)B[O]=A[R],B[O+1]=A[R+1],B[O+2]=A[R+2],B[O+3]=A[R+3];else if(U==1){var L=A[R+3]*0.00392156862745098,W=A[R]*L,Z=A[R+1]*L,G=A[R+2]*L,X=B[O+3]*0.00392156862745098,q=B[O]*X,M=B[O+1]*X,F=B[O+2]*X,D=1-L,_=L+X*D,w=_==0?0:1/_;B[O+3]=255*_,B[O+0]=(W+q*D)*w,B[O+1]=(Z+M*D)*w,B[O+2]=(G+F*D)*w}else if(U==2){var L=A[R+3],W=A[R],Z=A[R+1],G=A[R+2],X=B[O+3],q=B[O],M=B[O+1],F=B[O+2];if(L==X&&W==q&&Z==M&&G==F)B[O]=0,B[O+1]=0,B[O+2]=0,B[O+3]=0;else B[O]=W,B[O+1]=Z,B[O+2]=G,B[O+3]=L}else if(U==3){var L=A[R+3],W=A[R],Z=A[R+1],G=A[R+2],X=B[O+3],q=B[O],M=B[O+1],F=B[O+2];if(L==X&&W==q&&Z==M&&G==F)continue;if(L<220&&X>20)return!1}}return!0};var OA={};(function(){var A=function C(){function K(J){this.message="JPEG error: "+J}return K.prototype=new Error,K.prototype.name="JpegError",K.constructor=K,K}(),Q=function C(){var K=new Uint8Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),J=4017,U=799,Y=3406,H=2276,R=1567,O=3784,N=5793,$=2896;function L(F){if(F==null)F={};if(F.w==null)F.w=-1;this.V=F.n,this.N=F.w}function W(F,D){var _=0,w=[],k,T,z=16,j;while(z>0&&!F[z-1])z--;w.push({children:[],index:0});var v=w[0];for(k=0;k0)v=w.pop();v.index++,w.push(v);while(w.length<=k)w.push(j={children:[],index:0}),v.children[v.index]=j.children,v=j;_++}if(k+10)return x--,h>>x&1;if(h=F[D++],h===255){var qA=F[D++];if(qA){if(qA===220&&g){D+=2;var LA=B(F,D);if(D+=2,LA>0&&LA!==_.s)throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data",LA)}else if(qA===217){if(g){var _A=i*8;if(_A>0&&_A<_.s/10)throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, possibly caused by incorrect `scanLines` parameter",_A)}throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data")}throw new A("unexpected marker")}}return x=7,h>>>7}function ZA(qA){var LA=qA;while(!0){switch(LA=LA[FA()],typeof LA){case"number":return LA;case"object":continue}throw new A("invalid huffman sequence")}}function jA(qA){var LA=0;while(qA>0)LA=LA<<1|FA(),qA--;return LA}function wA(qA){if(qA===1)return FA()===1?1:-1;var LA=jA(qA);if(LA>=1<>4;if(pA===0){if(iA<15)break;cA+=16;continue}cA+=iA;var $0=K[cA];qA.D[LA+$0]=wA(pA),cA++}}function d(qA,LA){var _A=ZA(qA.J),B0=_A===0?0:wA(_A)<0){b--;return}var _A=T,B0=z;while(_A<=B0){var cA=ZA(qA.i),uA=cA&15,pA=cA>>4;if(uA===0){if(pA<15){b=jA(pA)+(1<>4,uA===0)if(cA<15)b=jA(cA)+(1<0){for(l=0;l0?"unexpected":"excessive";D=CA.offset}if(CA.M>=65488&&CA.M<=65495)D+=2;else break}return D-S}function X(F,D,_){var{$:w,D:k}=F,T,z,j,v,g,P,V,S,h,x,b,m,s,i,n,l,c;if(!w)throw new A("missing required Quantization Table.");for(var o=0;o<64;o+=8){if(h=k[D+o],x=k[D+o+1],b=k[D+o+2],m=k[D+o+3],s=k[D+o+4],i=k[D+o+5],n=k[D+o+6],l=k[D+o+7],h*=w[o],(x|b|m|s|i|n|l)===0){c=N*h+512>>10,_[o]=c,_[o+1]=c,_[o+2]=c,_[o+3]=c,_[o+4]=c,_[o+5]=c,_[o+6]=c,_[o+7]=c;continue}x*=w[o+1],b*=w[o+2],m*=w[o+3],s*=w[o+4],i*=w[o+5],n*=w[o+6],l*=w[o+7],T=N*h+128>>8,z=N*s+128>>8,j=b,v=n,g=$*(x-l)+128>>8,S=$*(x+l)+128>>8,P=m<<4,V=i<<4,T=T+z+1>>1,z=T-z,c=j*O+v*R+128>>8,j=j*R-v*O+128>>8,v=c,g=g+V+1>>1,V=g-V,S=S+P+1>>1,P=S-P,T=T+v+1>>1,v=T-v,z=z+j+1>>1,j=z-j,c=g*H+S*Y+2048>>12,g=g*Y-S*H+2048>>12,S=c,c=P*U+V*J+2048>>12,P=P*J-V*U+2048>>12,V=c,_[o]=T+S,_[o+7]=T-S,_[o+1]=z+V,_[o+6]=z-V,_[o+2]=j+P,_[o+5]=j-P,_[o+3]=v+g,_[o+4]=v-g}for(var e=0;e<8;++e){if(h=_[e],x=_[e+8],b=_[e+16],m=_[e+24],s=_[e+32],i=_[e+40],n=_[e+48],l=_[e+56],(x|b|m|s|i|n|l)===0){if(c=N*h+8192>>14,c<-2040)c=0;else if(c>=2024)c=255;else c=c+2056>>4;k[D+e]=c,k[D+e+8]=c,k[D+e+16]=c,k[D+e+24]=c,k[D+e+32]=c,k[D+e+40]=c,k[D+e+48]=c,k[D+e+56]=c;continue}if(T=N*h+2048>>12,z=N*s+2048>>12,j=b,v=n,g=$*(x-l)+2048>>12,S=$*(x+l)+2048>>12,P=m,V=i,T=(T+z+1>>1)+4112,z=T-z,c=j*O+v*R+2048>>12,j=j*R-v*O+2048>>12,v=c,g=g+V+1>>1,V=g-V,S=S+P+1>>1,P=S-P,T=T+v+1>>1,v=T-v,z=z+j+1>>1,j=z-j,c=g*H+S*Y+2048>>12,g=g*Y-S*H+2048>>12,S=c,c=P*U+V*J+2048>>12,P=P*J-V*U+2048>>12,V=c,h=T+S,l=T-S,x=z+V,n=z-V,b=j+P,i=j-P,m=v+g,s=v-g,h<16)h=0;else if(h>=4080)h=255;else h>>=4;if(x<16)x=0;else if(x>=4080)x=255;else x>>=4;if(b<16)b=0;else if(b>=4080)b=255;else b>>=4;if(m<16)m=0;else if(m>=4080)m=255;else m>>=4;if(s<16)s=0;else if(s>=4080)s=255;else s>>=4;if(i<16)i=0;else if(i>=4080)i=255;else i>>=4;if(n<16)n=0;else if(n>=4080)n=255;else n>>=4;if(l<16)l=0;else if(l>=4080)l=255;else l>>=4;k[D+e]=h,k[D+e+8]=x,k[D+e+16]=b,k[D+e+24]=m,k[D+e+32]=s,k[D+e+40]=i,k[D+e+48]=n,k[D+e+56]=l}}function q(F,D){var{P:_,c:w}=D,k=new Int16Array(64);for(var T=0;T=w)return null;var T=B(F,D);if(T>=65472&&T<=65534)return{u:null,M:T,offset:D};var z=B(F,k);while(!(z>=65472&&z<=65534)){if(++k>=w)return null;z=B(F,k)}return{u:T.toString(16),M:z,offset:k}}return L.prototype={parse(F,D){if(D==null)D={};var _=D.F,w=0,k=null,T=null,z,j,v=0;function g(){var pA=B(F,w);w+=2;var iA=w+pA-2,$0=M(F,iA,w);if($0&&$0.u)iA=$0.offset;var IA=F.subarray(w,iA);return w+=IA.length,IA}function P(pA){var iA=Math.ceil(pA.o/8/pA.X),$0=Math.ceil(pA.s/8/pA.B);for(var IA=0;IA>4===0)for(m=0;m<64;m++)l=K[m],e[l]=F[w++];else if(o>>4===1)for(m=0;m<64;m++)l=K[m],e[l]=B(F,w),w+=2;else throw new A("DQT - invalid table spec");V[o&15]=e}break;case 65472:case 65473:case 65474:if(z)throw new A("Only single frame JPEGs supported");w+=2,z={},z.G=x===65473,z.Z=x===65474,z.precision=F[w++];var BA=B(F,w),EA,CA=0,f=0;w+=2,z.s=_||BA,z.o=B(F,w),w+=2,z.W=[],z._={};var NA=F[w++];for(b=0;b>4,FA=F[w+1]&15;if(CA>4===0?h:S)[wA&15]=W(VA,u)}break;case 65501:w+=2,j=B(F,w),w+=2;break;case 65498:var QA=++v===1&&!_,t;w+=2;var KA=F[w++],HA=[];for(b=0;b>4],t.i=S[yA&15],HA.push(t)}var qA=F[w++],LA=F[w++],_A=F[w++];try{var B0=G(F,w,z,HA,j,qA,LA,_A>>4,_A&15,QA);w+=B0}catch(pA){if(pA instanceof DNLMarkerError)return this.parse(F,{F:pA.s});else if(pA instanceof EOIMarkerError)break A;throw pA}break;case 65500:w+=4;break;case 65535:if(F[w]!==255)w--;break;default:var cA=M(F,w-2,w-3);if(cA&&cA.u){w=cA.offset;break}if(w>=F.length-1)break A;throw new A("JpegImage.parse - unknown marker: "+x.toString(16))}x=B(F,w),w+=2}this.width=z.o,this.height=z.s,this.g=k,this.b=T,this.W=[];for(b=0;b>8)+e[h+1];return n},get f(){if(this.b)return!!this.b.a;if(this.p===3){if(this.N===0)return!1;else if(this.W[0].index===82&&this.W[1].index===71&&this.W[2].index===66)return!1;return!0}if(this.N===1)return!0;return!1},z:function F(D){var _,w,k;for(var T=0,z=D.length;T4)throw new A("Unsupported color mode");var T=this.Y(D,_,k);if(this.p===1&&w){var z=T.length,j=new Uint8ClampedArray(z*3),v=0;for(var g=0;g>24}function B(C,K){return C[K]<<8|C[K+1]}function I(C,K){return(C[K]<<24|C[K+1]<<16|C[K+2]<<8|C[K+3])>>>0}OA.JpegDecoder=Q})();OA.encodeImage=function(A,Q,E,B){var I={t256:[Q],t257:[E],t258:[8,8,8,8],t259:[1],t262:[2],t273:[1000],t277:[4],t278:[E],t279:[Q*E*4],t282:[[72,1]],t283:[[72,1]],t284:[1],t286:[[0,1]],t287:[[0,1]],t296:[1],t305:["Photopea (UTIF.js)"],t338:[1]};if(B)for(var C in B)I[C]=B[C];var K=new Uint8Array(OA.encode([I])),J=new Uint8Array(A),U=new Uint8Array(1000+Q*E*4);for(var C=0;C3)Q.t258=Q.t258.slice(0,3);var J=Q.t277?Q.t277[0]:1,U=Q.t258?Q.t258[0]:1,Y=U*J;if(C==1&&Q.t279!=null&&Q.t278&&Q.t262[0]==32803)Y=Math.round(Q.t279[0]*8/(Q.width*Q.t278[0]));if(Q.t50885&&Q.t50885[0]==4)Y=Q.t258[0]*3;var H=Math.ceil(Q.width*Y/8)*8,R=Q.t273;if(R==null||Q.t322)R=Q.t324;var O=Q.t279;if(C==1&&R.length==1)O=[Q.height*(H>>>3)];if(O==null||Q.t322)O=Q.t325;var N=new Uint8Array(Q.height*(H>>>3)),$=0;if(Q.t322!=null){var L=Q.t322[0],W=Q.t323[0],Z=Math.floor((Q.width+L-1)/L),G=Math.floor((Q.height+W-1)/W),X=new Uint8Array(Math.ceil(L*W*Y/8)|0);console.log("====",Z,G);for(var q=0;q>>3,Z=Math.ceil($*L*Y/8);if($==16&&!A.isLE&&A.t33422==null)for(var G=0;G>>8&255}else if(L==3)for(var R=3;R>3^16368,(j[$]|j[$+1]<<8)>>(N&7)&~(-1<>2,Z[1]=((P(1)&3)<<12|P(2)<<4|P(3)>>4)&16383,Z[2]=P(3)>>2&3,Z[3]=(P(3)&3)<<8|P(4),Z[4]=P(5)<<2|P(6)>>6,Z[5]=(P(6)&63)<<4|P(7)>>4,Z[6]=P(7)>>2&3,Z[7]=(P(7)&3)<<8|P(8),Z[8]=P(9)<<2&1020|P(10)>>6,Z[9]=(P(10)<<4|P(11)>>4)&1023,Z[10]=P(11)>>2&3,Z[11]=(P(11)&3)<<8|P(12),Z[12]=(P(13)<<2&1020|P(14)>>6)&1023,Z[13]=(P(14)<<4|P(15)>>4)&1023,N+=16,$=0}function S(){Z[0]=P(0)<<4|P(1)>>4,Z[1]=((P(1)&15)<<8|P(2))&4095,Z[2]=P(3)>>6&3,Z[3]=(P(3)&63)<<2|P(4)>>6,Z[4]=(P(4)&63)<<2|P(5)>>6,Z[5]=(P(5)&63)<<2|P(6)>>6,Z[6]=P(6)>>4&3,Z[7]=(P(6)&15)<<4|P(7)>>4,Z[8]=(P(7)&15)<<4|P(8)>>4,Z[9]=(P(8)&15)<<4|P(9)>>4,Z[10]=P(9)>>2&3,Z[11]=(P(9)&3)<<6|P(10)>>2,Z[12]=(P(10)&3)<<6|P(11)>>2,Z[13]=(P(11)&3)<<6|P(12)>>2,Z[14]=P(12)&3,Z[15]=P(13),Z[16]=P(14),Z[17]=P(15),N+=16,$=0}function h(){M[0]=0,M[1]=0,F[0]=0,F[1]=0}if(H==7)throw H;else if(H==6){var x=Y==12,b=x?S:V,m=x?14:11,s=x?128:512,i=x?2048:8192,n=x?16383:65535,l=x?4095:16383,c=J/m,o=c*16,e=x?18:14;for(k=0;kw)NA+=F[D]-w;F[D]=NA}else if(M[D]=NA,NA)F[D]=NA;else NA=F[D];v[_+T++]=NA-15<=n?NA-15&n:NA+2147483633>>31&l}}}}}else if(H==5){var YA=Y==12?10:9;for(k=0;k>4),v[_++]=((Z[4]&15)<<8)+Z[3],v[_++]=16*Z[5]+(Z[4]>>4),v[_++]=((Z[7]&15)<<8)+Z[6],v[_++]=16*Z[8]+(Z[7]>>4),v[_++]=((Z[10]&15)<<8)+Z[9],v[_++]=16*Z[11]+(Z[10]>>4),v[_++]=((Z[13]&15)<<8)+Z[12],v[_++]=16*Z[14]+(Z[13]>>4);else if(Y==14)v[_++]=Z[0]+((Z[1]&63)<<8),v[_++]=(Z[1]>>6)+4*Z[2]+((Z[3]&15)<<10),v[_++]=(Z[3]>>4)+16*Z[4]+((Z[5]&3)<<12),v[_++]=((Z[5]&252)>>2)+(Z[6]<<6),v[_++]=Z[7]+((Z[8]&63)<<8),v[_++]=(Z[8]>>6)+4*Z[9]+((Z[10]&15)<<10),v[_++]=(Z[10]>>4)+16*Z[11]+((Z[12]&3)<<12),v[_++]=((Z[12]&252)>>2)+(Z[13]<<6),v[_++]=Z[14]+((Z[15]&63)<<8)}else if(H==4)for(k=0;k>3-g(2);if(F[D]){if(X=g(8),X!=0){if(M[D]-=128<11)M[D]=F[D]<<4|g(4);v[_++]=M[T&1]}else throw H};OA.decode._decodeVC5=function(){var A=[1,0,1,0,2,2,1,1,3,7,1,2,5,25,1,3,6,48,1,4,6,54,1,5,7,111,1,8,7,99,1,6,7,105,12,0,7,107,1,7,8,209,20,0,8,212,1,9,8,220,1,10,9,393,1,11,9,394,32,0,9,416,1,12,9,427,1,13,10,887,1,18,10,784,1,14,10,790,1,15,10,835,60,0,10,852,1,16,10,885,1,17,11,1571,1,19,11,1668,1,20,11,1669,100,0,11,1707,1,21,11,1772,1,22,12,3547,1,29,12,3164,1,24,12,3166,1,25,12,3140,1,23,12,3413,1,26,12,3537,1,27,12,3539,1,28,13,7093,1,35,13,6283,1,30,13,6331,1,31,13,6335,180,0,13,6824,1,32,13,7072,1,33,13,7077,320,0,13,7076,1,34,14,12565,1,36,14,12661,1,37,14,12669,1,38,14,13651,1,39,14,14184,1,40,15,28295,1,46,15,28371,1,47,15,25320,1,42,15,25336,1,43,15,25128,1,41,15,27300,1,44,15,28293,1,45,16,50259,1,48,16,50643,1,49,16,50675,1,50,16,56740,1,53,16,56584,1,51,16,56588,1,52,17,113483,1,61,17,113482,1,60,17,101285,1,55,17,101349,1,56,17,109205,1,57,17,109207,1,58,17,100516,1,54,17,113171,1,59,18,202568,1,62,18,202696,1,63,18,218408,1,64,18,218412,1,65,18,226340,1,66,18,226356,1,67,18,226358,1,68,19,402068,1,69,19,405138,1,70,19,405394,1,71,19,436818,1,72,19,436826,1,73,19,452714,1,75,19,452718,1,76,19,452682,1,74,20,804138,1,77,20,810279,1,78,20,810790,1,79,20,873638,1,80,20,873654,1,81,20,905366,1,82,20,905430,1,83,20,905438,1,84,21,1608278,1,85,21,1620557,1,86,21,1621582,1,87,21,1621583,1,88,21,1747310,1,89,21,1810734,1,90,21,1810735,1,91,21,1810863,1,92,21,1810879,1,93,22,3621725,1,99,22,3621757,1,100,22,3241112,1,94,22,3494556,1,95,22,3494557,1,96,22,3494622,1,97,22,3494623,1,98,23,6482227,1,102,23,6433117,1,101,23,6989117,1,103,23,6989119,1,105,23,6989118,1,104,23,7243449,1,106,23,7243512,1,107,24,13978233,1,111,24,12964453,1,109,24,12866232,1,108,24,14486897,1,113,24,13978232,1,110,24,14486896,1,112,24,14487026,1,114,24,14487027,1,115,25,25732598,1,225,25,25732597,1,189,25,25732596,1,188,25,25732595,1,203,25,25732594,1,202,25,25732593,1,197,25,25732592,1,207,25,25732591,1,169,25,25732590,1,223,25,25732589,1,159,25,25732522,1,235,25,25732579,1,152,25,25732575,1,192,25,25732489,1,179,25,25732573,1,201,25,25732472,1,172,25,25732576,1,149,25,25732488,1,178,25,25732566,1,120,25,25732571,1,219,25,25732577,1,150,25,25732487,1,127,25,25732506,1,211,25,25732548,1,125,25,25732588,1,158,25,25732486,1,247,25,25732467,1,238,25,25732508,1,163,25,25732552,1,228,25,25732603,1,183,25,25732513,1,217,25,25732587,1,168,25,25732520,1,122,25,25732484,1,128,25,25732562,1,249,25,25732505,1,187,25,25732504,1,186,25,25732483,1,136,25,25928905,1,181,25,25732560,1,255,25,25732500,1,230,25,25732482,1,135,25,25732555,1,233,25,25732568,1,222,25,25732583,1,145,25,25732481,1,134,25,25732586,1,167,25,25732521,1,248,25,25732518,1,209,25,25732480,1,243,25,25732512,1,216,25,25732509,1,164,25,25732547,1,140,25,25732479,1,157,25,25732544,1,239,25,25732574,1,191,25,25732564,1,251,25,25732478,1,156,25,25732546,1,139,25,25732498,1,242,25,25732557,1,133,25,25732477,1,162,25,25732515,1,213,25,25732584,1,165,25,25732514,1,212,25,25732476,1,227,25,25732494,1,198,25,25732531,1,236,25,25732530,1,234,25,25732529,1,117,25,25732528,1,215,25,25732527,1,124,25,25732526,1,123,25,25732525,1,254,25,25732524,1,253,25,25732523,1,148,25,25732570,1,218,25,25732580,1,146,25,25732581,1,147,25,25732569,1,224,25,25732533,1,143,25,25732540,1,184,25,25732541,1,185,25,25732585,1,166,25,25732556,1,132,25,25732485,1,129,25,25732563,1,250,25,25732578,1,151,25,25732501,1,119,25,25732502,1,193,25,25732536,1,176,25,25732496,1,245,25,25732553,1,229,25,25732516,1,206,25,25732582,1,144,25,25732517,1,208,25,25732558,1,137,25,25732543,1,241,25,25732466,1,237,25,25732507,1,190,25,25732542,1,240,25,25732551,1,131,25,25732554,1,232,25,25732565,1,252,25,25732475,1,171,25,25732493,1,205,25,25732492,1,204,25,25732491,1,118,25,25732490,1,214,25,25928904,1,180,25,25732549,1,126,25,25732602,1,182,25,25732539,1,175,25,25732545,1,141,25,25732559,1,138,25,25732537,1,177,25,25732534,1,153,25,25732503,1,194,25,25732606,1,160,25,25732567,1,121,25,25732538,1,174,25,25732497,1,246,25,25732550,1,130,25,25732572,1,200,25,25732474,1,170,25,25732511,1,221,25,25732601,1,196,25,25732532,1,142,25,25732519,1,210,25,25732495,1,199,25,25732605,1,155,25,25732535,1,154,25,25732499,1,244,25,25732510,1,220,25,25732600,1,195,25,25732607,1,161,25,25732604,1,231,25,25732473,1,173,25,25732599,1,226,26,51465122,1,116,26,51465123,0,1],Q,E,B,I=[3,3,3,3,2,2,2,1,1,1],C=24576,K=16384,J=8192,U=K|J;function Y(G){var X=G[1],q=G[0][X>>>3]>>>7-(X&7)&1;return G[1]++,q}function H(G,X){if(Q==null){Q={};for(var q=0;q>>1}return G}function O(G,X){return G>>X}function N(G,X,q,M,F,D){X[q]=O(O(11*G[F]-4*G[F+D]+G[F+D+D]+4,3)+G[M],1),X[q+D]=O(O(5*G[F]+4*G[F+D]-G[F+D+D]+4,3)-G[M],1)}function $(G,X,q,M,F,D){var _=G[F-D]-G[F+D],w=G[F],k=G[M];X[q]=O(O(_+4,3)+w+k,1),X[q+D]=O(O(-_+4,3)+w-k,1)}function L(G,X,q,M,F,D){X[q]=O(O(5*G[F]+4*G[F-D]-G[F-D-D]+4,3)+G[M],1),X[q+D]=O(O(11*G[F]-4*G[F-D]+G[F-D-D]+4,3)-G[M],1)}function W(G){return G=G<0?0:G>4095?4095:G,G=B[G]>>>2,G}function Z(G,X,q,M,F,D){M=new Uint16Array(M.buffer);var _=Date.now(),w=OA._binBE,k=X+q,T,z,j,v,g,P,V,S,h,x,b,m,s,i,n,l,c,o;X+=4;var e=D[0]==1;while(X>>1)*(j>>>1));o=new Int16Array((z>>>1)*(j>>>1)),E=new Int16Array(1024);for(var YA=0;YA<1024;YA++){var FA=YA-512,ZA=Math.abs(FA),T=Math.floor(768*ZA*ZA*ZA/16581375)+ZA;E[YA]=Math.sign(FA)*T}B=new Uint16Array(4096);var jA=65535;for(var YA=0;YA<4096;YA++){var wA=YA,VA=jA*(Math.pow(113,wA/4095)-1)/112;B[YA]=Math.min(VA,jA)}}var d=c[V],u=R(z,1+I[v]),QA=R(j,1+I[v]);if(v==0)for(var t=0;t>>1)+KA]=G[HA]<<8|G[HA+1]}else{var fA=[G,X*8],zA=[],yA=0,qA=u*QA,LA=[0,0],_A=0,EA=0;while(yA0)zA[yA++]=EA,_A--}var B0=(v-1)%3,cA=B0!=1?u:0,uA=B0!=0?QA:0;for(var t=0;t>>1)+cA,iA=t*u;for(var KA=0;KA>>1,$0=u*2,IA=QA*2;for(var t=0;t>14-F0*2&3;var HQ=lA[dA];if(HQ!=0)for(var t=0;t>>1)*(z>>>1)+(KA>>>1),lE=gQ[HA],v6=d0[HA]-2048,nK=IB[HA]-2048,h6=cE[HA]-2048,oI=(v6<<1)+lE,y6=(nK<<1)+lE,rI=lE+h6,g6=lE-h6;if(e)M[CB]=W(rI),M[CB+1]=W(y6),M[CB+z]=W(oI),M[CB+z+1]=W(g6);else M[CB]=W(oI),M[CB+1]=W(rI),M[CB+z]=W(g6),M[CB+z+1]=W(y6)}}X+=NA*4}else if(CA==16388)X+=NA*4;else if(f==8192||f==8448||f==9216);else throw CA.toString(16)}}console.log(Date.now()-_)}return Z}();OA.decode._decodeLogLuv32=function(A,Q,E,B,I,C){var K=A.width,J=K*4,U=0,Y=new Uint8Array(J);while(U>>(N[V]>>>8);for(var $=0;$>>4,I[C+V+1]=q<<4|F>>>4,I[C+V+2]=F<<4|M>>>4}return}var D=new Uint16Array(16),_,w,k,T,z,j,v,g,P,V,S,h=new Uint8Array(K+1);for(_=0;_>>11,j=15&k>>>22,v=15&k>>>26;for(g=0;g<4&&128<>3))>>>(P&7)&127)<2047)D[V]=2047;P+=7}for(V=0;V<16;V++,w+=2){var X=D[V]<<1;OA.decode._putsF(I,(_*K+w)*U,X<<16-U)}w-=w&1?1:31}}};OA.decode._decodeNikon=function(A,Q,E,B,I,C,K){var J=[[0,0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,5,4,3,6,2,7,1,0,8,9,11,10,12],[0,0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0,57,90,56,39,22,5,4,3,2,1,0,11,12,12],[0,0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,5,4,6,3,7,2,8,1,9,0,10,11,12],[0,0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0,5,6,4,7,8,3,9,2,1,0,10,11,12,13,14],[0,0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0,8,92,75,58,41,7,6,5,4,3,2,1,0,13,14],[0,0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0,7,6,8,5,9,4,10,3,11,12,2,0,1,13,14]],U=A.t256[0],Y=A.t257[0],H=A.t258[0],R=0,O=0,N=OA.decode._make_decoder,$=OA.decode._getbithuff,L=Q[0].exifIFD.makerNote,W=L.t150?L.t150:L.t140,Z=0,G=W[Z++],X=W[Z++];if(G==73||X==88)Z+=2110;if(G==70)R=2;if(H==14)R+=3;var q=[[0,0],[0,0]],M=A.isLE?OA._binLE:OA._binBE;for(var k=0;k<2;k++)for(var F=0;F<2;F++)q[k][F]=M.readShort(W,Z),Z+=2;var D=1<1)_=Math.floor(D/(w-1));if(G==68&&X==32&&_>0)O=M.readShort(W,562);var k,T,z,j,v,g,P=0,V=[0,0],S=N(J[R]),h=[B,0,0,0];for(P=T=0;T>>4,g=($(E,h,j-v,0)<<1)+1<>>1,(g&1<>>3;A[B]|=E>>>16,A[B+1]|=E>>>8,A[B+2]|=E};OA.decode._getbithuff=function(A,Q,E,B){var I=0,C=OA.decode._get_byte,K,J=Q[0],U=Q[1],Y=Q[2],H=Q[3];if(E==0||Y<0)return 0;while(!H&&Y>>32-E,B)Y-=B[K+1]>>>8,K=B[K+1]&255;else Y-=E;if(Y<0)throw"e";return Q[0]=J,Q[1]=U,Q[2]=Y,Q[3]=H,K};OA.decode._make_decoder=function(A){var Q,E,B,I,C,K=[];for(Q=16;Q!=0&&!A[Q];Q--);var J=17;K[0]=Q;for(B=E=1;E<=Q;E++)for(I=0;I>>8;else for(var O=0;O>>8,I[C+(O<<1)+1]=W[O]&255;else if(L==14||L==12||L==10){var G=16-L;for(var O=0;O1;if(!L){if(Q[E]==255&&Q[E+1]==I)return{jpegOffset:E};if(X!=null){if(Q[E+q]==255&&Q[E+q+1]==I)R=E+q;else log("JPEGInterchangeFormat does not point to SOI");if(M==null)log("JPEGInterchangeFormatLength field is missing");else if(q>=O||q+F<=O)log("JPEGInterchangeFormatLength field value is invalid");if(R!=null)return{jpegOffset:R}}}if(_!=null)w=_[0],k=_[1];if(X!=null){if(M!=null)if(F>=2&&q+F<=O){if(Q[E+q+F-2]==255&&Q[E+q+F-1]==I)N=new Uint8Array(F-2);else N=new Uint8Array(F);for(W=0;W offset to first strip or tile")}if(N==null){var j=0,v=[];v[j++]=255,v[j++]=I;var g=A.t519;if(g==null)throw new Error("JPEGQTables tag is missing");for(W=0;W>>8,v[j++]=V&255,v[j++]=W|G<<4;for(Z=0;Z<16;Z++)v[j++]=Q[E+P[W]+Z];for(Z=0;Z>>8&255,v[j++]=A.height&255,v[j++]=A.width>>>8&255,v[j++]=A.width&255,v[j++]=T,T==1)v[j++]=1,v[j++]=17,v[j++]=0;else for(W=0;W<3;W++)v[j++]=W+1,v[j++]=W!=0?17:(w&15)<<4|k&15,v[j++]=W;if(z!=null&&z[0]!=0)v[j++]=255,v[j++]=U,v[j++]=0,v[j++]=4,v[j++]=z[0]>>>8&255,v[j++]=z[0]&255;N=new Uint8Array(v)}var S=-1;W=0;while(W>>8&255,N[x++]=A.height&255,N[x++]=A.width>>>8&255,N[x++]=A.width&255,N[x++]=T,T==1)N[x++]=1,N[x++]=17,N[x++]=0;else for(W=0;W<3;W++)N[x++]=W+1,N[x++]=W!=0?17:(w&15)<<4|k&15,N[x++]=W}if(Q[O]==255&&Q[O+1]==H){var b=Q[O+2]<<8|Q[O+3];$=new Uint8Array(b+2),$[0]=Q[O],$[1]=Q[O+1],$[2]=Q[O+2],$[3]=Q[O+3];for(W=0;W>>8&255,Y[R.sofPosition+6]=A.height&255,Y[R.sofPosition+7]=A.width>>>8&255,Y[R.sofPosition+8]=A.width&255,Q[E]!=255||Q[E+1]!=SOS)Y.set(R.sosMarker,H),H+=sosMarker.length;for(K=0;K=0&&U<128)for(var Y=0;Y=-127&&U<0){for(var Y=0;Y<-U+1;Y++)K[I]=C[Q],I++;Q++}}return I};OA.decode._decodeThunder=function(A,Q,E,B,I){var C=[0,1,0,-1],K=[0,1,2,3,0,-3,-2,-1],J=Q+E,U=I*2,Y=0;while(Q>>6,O=H&63;if(Q++,R==3)Y=O&15,B[U>>>1]|=Y<<4*(1-U&1),U++;if(R==0)for(var N=0;N>>1]|=Y<<4*(1-U&1),U++;if(R==2)for(var N=0;N<2;N++){var $=O>>>3*(1-N)&7;if($!=4)Y+=K[$],B[U>>>1]|=Y<<4*(1-U&1),U++}if(R==1)for(var N=0;N<3;N++){var $=O>>>2*(2-N)&3;if($!=2)Y+=C[$],B[U>>>1]|=Y<<4*(1-U&1),U++}}};OA.decode._dmap={"1":0,"011":1,"000011":2,"0000011":3,"010":-1,"000010":-2,"0000010":-3};OA.decode._lens=function(){var A=function(U,Y,H,R){for(var O=0;O>>3>>3]>>>7-(U&7)&1;if(K==2)_=A[U>>>3]>>>(U&7)&1;if(U++,H+=_,M=="H"){if(J._lens[X][H]!=null){var w=J._lens[X][H];if(H="",Y+=w,w<64){if(J._addNtimes(R,Y,X),$+=Y,X=1-X,Y=0,F--,F==0)M=""}}}else{if(H=="0001")H="",J._addNtimes(R,G-$,X),$=G;if(H=="001")H="",M="H",F=2;if(J._dmap[H]!=null)L=Z+J._dmap[H],J._addNtimes(R,L-$,X),$=L,H="",X=1-X}if(R.length==C&&M=="")J._writeBits(R,B,I*8+q*D),X=0,q++,$=0,O=J._makeDiff(R),R=[]}};OA.decode._findDiff=function(A,Q,E){for(var B=0;B=Q&&A[B+1]==E)return A[B]};OA.decode._makeDiff=function(A){var Q=[];if(A[0]==1)Q.push(0,1);for(var E=1;E>>3>>3]>>>7-(U&7)&1;if(K==2)L=A[U>>>3]>>>(U&7)&1;if(U++,H+=L,Y=J._lens[O][H],Y!=null){if(J._addNtimes(R,Y,O),H="",Y<64)O=1-O;if(R.length==C){if(J._writeBits(R,B,I*8+N*$),R=[],N++,O=0,(U&7)!=0)U+=8-(U&7);if(Y>=64)U+=8}}}};OA.decode._decodeG3=function(A,Q,E,B,I,C,K,J){var U=OA.decode,Y=Q<<3,H=0,R="",O=[],N=[];for(var $=0;$>>3>>3]>>>7-(Y&7)&1;if(K==2)k=A[Y>>>3]>>>(Y&7)&1;if(Y++,R+=k,_){if(U._lens[q][R]!=null){var T=U._lens[q][R];if(R="",H+=T,T<64)U._addNtimes(O,H,q),q=1-q,H=0}}else if(F=="H"){if(U._lens[q][R]!=null){var T=U._lens[q][R];if(R="",H+=T,T<64){if(U._addNtimes(O,H,q),L+=H,q=1-q,H=0,D--,D==0)F=""}}}else{if(R=="0001")R="",U._addNtimes(O,X-L,q),L=X;if(R=="001")R="",F="H",D=2;if(U._dmap[R]!=null)W=G+U._dmap[R],U._addNtimes(O,W-L,q),L=W,R="",q=1-q}if(R.endsWith("000000000001")){if(M>=0)U._writeBits(O,B,I*8+M*w);if(J){if(K==1)_=(A[Y>>>3]>>>7-(Y&7)&1)==1;if(K==2)_=(A[Y>>>3]>>>(Y&7)&1)==1;Y++}R="",q=0,M++,L=0,N=U._makeDiff(O),O=[]}}if(O.length==C)U._writeBits(O,B,I*8+M*w)};OA.decode._addNtimes=function(A,Q,E){for(var B=0;B>>3]|=A[B]<<7-(E+B&7)};OA.decode._decodeLZW=OA.decode._decodeLZW=function(){var A,Q,E,B,I=0,C=0,K=0,J=0,U=function(){var W=A>>>3,Z=Q[W]<<16|Q[W+1]<<8|Q[W+2],G=Z>>>24-(A&7)-C&(1<>>----------------");for(var U=0;UQ.buffer.byteLength)R=Q.buffer.byteLength-$;N=new Uint8Array(Q.buffer,$,R)}if(H==2){var L=R<5?E-4:O,W=Q[L],Z=Math.max(0,Math.min(R-1,Q.length-L));if(W<128||Z==0)N.push(A.readASCII(Q,L,Z));else N=new Uint8Array(Q.buffer,L,Z)}if(H==3)for(var G=0;G4)A.writeUint(E,B,J),W=J;if(R==1||R==7)for(var Z=0;Z<$;Z++)E[W+Z]=O[Z];else if(R==2)A.writeASCII(E,W,O);else if(R==3)for(var Z=0;Z<$;Z++)A.writeUshort(E,W+2*Z,O[Z]);else if(R==4)for(var Z=0;Z<$;Z++)A.writeUint(E,W+4*Z,O[Z]);else if(R==5||R==10){var G=R==5?A.writeUint:A.writeInt;for(var Z=0;Z<$;Z++){var X=O[Z],q=X[0],M=X[1];if(q==null)throw"e";G(E,W+8*Z,q),G(E,W+8*Z+4,M)}}else if(R==9)for(var Z=0;Z<$;Z++)A.writeInt(E,W+4*Z,O[Z]);else if(R==12)for(var Z=0;Z<$;Z++)A.writeDouble(E,W+8*Z,O[Z]);else throw R;if(L>4)L+=L&1,J+=L;B+=4}return[B,J]};OA.toRGBA8=function(A,Q){function E(d){return d<0.0031308?12.92*d:1.055*Math.pow(d,0.4166666666666667)-0.055}var{width:B,height:I}=A,C=B*I,K=C*4,J=A.data,U=new Uint8Array(C*4),Y=A.t262?A.t262[0]:2,H=A.t258?Math.min(32,A.t258[0]):1;if(A.t262==null&&H==1)Y=0;var R=A.t277?A.t277[0]:A.t258?A.t258.length:[1,1,3,1,1,4,3][Y],O=A.t339?A.t339[0]:null;if(Y==1&&H==32&&O!=3)throw"e";var N=Math.ceil(R*H*B/8);if(Y==0){Q=0.00390625;for(var $=0;$>3)]>>7-(Z&7)&1;U[G]=U[G+1]=U[G+2]=(1-X)*255,U[G+3]=255}if(H==4)for(var Z=0;Z>1)]>>4-4*(Z&1)&15;U[G]=U[G+1]=U[G+2]=(15-X)*17,U[G+3]=255}if(H==8)for(var Z=0;Z>3)]>>7-(Z&7)&1;U[G]=U[G+1]=U[G+2]=X*255,U[G+3]=255}if(H==2)for(var Z=0;Z>2)]>>6-2*(Z&3)&3;U[G]=U[G+1]=U[G+2]=X*85,U[G+3]=255}if(H==8)for(var Z=0;Z>>2)+Z,X=M[q];U[G]=U[G+1]=U[G+2]=~~(0.5+255*X),U[G+3]=255}}}else if(Y==2)if(H==8){if(R==1)for(var Z=0;Z=4)for(var Z=0;Z1&&A.t338&&A.t338[0]!=0;for(var $=0;$>>3)]>>>7-(g&7)&1;else if(H==2)P=J[V+(g>>>2)]>>>6-2*(g&3)&3;else if(H==4)P=J[V+(g>>>1)]>>>4-4*(g&1)&15;else if(H==8)P=J[V+g*R];else throw H;U[G]=z[P]>>8,U[G+1]=z[j+P]>>8,U[G+2]=z[j+j+P]>>8,U[G+3]=v?J[V+g*R+1]:255}}else if(Y==5){var S=R>4?1:0;for(var Z=0;Z>>1),m=J[h+(c&1)],o=J[h+2]-128,e=J[h+3]-128,BA=m+((e>>2)+(e>>3)+(e>>5)),EA=m-((o>>2)+(o>>4)+(o>>5))-((e>>1)+(e>>3)+(e>>4)+(e>>5)),CA=m+(o+(o>>1)+(o>>2)+(o>>6));U[G]=Math.max(0,Math.min(255,BA)),U[G+1]=Math.max(0,Math.min(255,EA)),U[G+2]=Math.max(0,Math.min(255,CA)),U[G+3]=255}}}else if(Y==32845)for(var $=0;$B)B=J,I=K}OA.decodeImage(A,I,Q);var U=OA.toRGBA8(I),Y=I.width,H=I.height,R=document.createElement("canvas");R.width=Y,R.height=H;var O=R.getContext("2d"),N=new ImageData(new Uint8ClampedArray(U.buffer),Y,H);return O.putImageData(N,0,0),R.toDataURL()};OA._binBE={nextZero:function(A,Q){while(A[Q]!=0)Q++;return Q},readUshort:function(A,Q){return A[Q]<<8|A[Q+1]},readShort:function(A,Q){var E=OA._binBE.ui8;return E[0]=A[Q+1],E[1]=A[Q+0],OA._binBE.i16[0]},readInt:function(A,Q){var E=OA._binBE.ui8;return E[0]=A[Q+3],E[1]=A[Q+2],E[2]=A[Q+1],E[3]=A[Q+0],OA._binBE.i32[0]},readUint:function(A,Q){var E=OA._binBE.ui8;return E[0]=A[Q+3],E[1]=A[Q+2],E[2]=A[Q+1],E[3]=A[Q+0],OA._binBE.ui32[0]},readASCII:function(A,Q,E){var B="";for(var I=0;I>8&255,A[Q+1]=E&255},writeInt:function(A,Q,E){var B=OA._binBE.ui8;OA._binBE.i32[0]=E,A[Q+3]=B[0],A[Q+2]=B[1],A[Q+1]=B[2],A[Q+0]=B[3]},writeUint:function(A,Q,E){A[Q]=E>>24&255,A[Q+1]=E>>16&255,A[Q+2]=E>>8&255,A[Q+3]=E>>0&255},writeASCII:function(A,Q,E){for(var B=0;B>8&255},writeInt:function(A,Q,E){var B=OA._binBE.ui8;OA._binBE.i32[0]=E,A[Q+0]=B[0],A[Q+1]=B[1],A[Q+2]=B[2],A[Q+3]=B[3]},writeUint:function(A,Q,E){A[Q]=E>>>0&255,A[Q+1]=E>>>8&255,A[Q+2]=E>>>16&255,A[Q+3]=E>>>24&255},writeASCII:OA._binBE.writeASCII};OA._copyTile=function(A,Q,E,B,I,C,K,J){var U=Math.min(Q,I-K),Y=Math.min(E,C-J);for(var H=0;H>>2<<5);while(I==0){if(I=W(Q,O,1),C=W(Q,O+1,2),O+=3,C==0){if((O&7)!=0)O+=8-(O&7);var _=(O>>>3)+4,w=Q[_-4]|Q[_-3]<<8;if(D)E=A.H.W(E,R+w);E.set(new B(Q.buffer,Q.byteOffset+_,w),R),O=_+w<<3,R+=w;continue}if(D)E=A.H.W(E,R+131072);if(C==1)N=F.J,$=F.h,Y=511,H=31;if(C==2){K=Z(Q,O,5)+257,J=Z(Q,O+5,5)+1,U=Z(Q,O+10,4)+4,O+=14;var k=O,T=1;for(var z=0;z<38;z+=2)F.Q[z]=0,F.Q[z+1]=0;for(var z=0;zT)T=j}O+=3*U,X(F.Q,T),q(F.Q,T,F.u),N=F.w,$=F.d,O=G(F.u,(1<>>4;if(V>>>8==0)E[R++]=V;else if(V==256)break;else{var S=R+V-254;if(V>264){var h=F.q[V-257];S=R+(h>>>3)+Z(Q,O,h&7),O+=h&7}var x=$[M(Q,O)&H];O+=x&15;var b=x>>>4,m=F.c[b],s=(m>>>4)+W(Q,O,m&15);O+=m&15;while(R>>4;if(R<=15)K[Y]=R,Y++;else{var O=0,N=0;if(R==16)N=3+J(I,C,2),C+=2,O=K[Y-1];else if(R==17)N=3+J(I,C,3),C+=3;else if(R==18)N=11+J(I,C,7),C+=7;var $=Y+N;while(Y<$)K[Y]=O,Y++}}return C},A.H.V=function(Q,E,B,I){var C=0,K=0,J=I.length>>>1;while(KC)C=U;K++}while(K>1,Y=Q[J+1],H=U<<4|Y,R=E-Y,O=Q[J]<>>15-E;B[$]=H,O++}}},A.H.l=function(Q,E){var B=A.H.m.r,I=15-E;for(var C=0;C>>I}},A.H.M=function(Q,E,B){B=B<<(E&7);var I=E>>>3;Q[I]|=B,Q[I+1]|=B>>>8},A.H.I=function(Q,E,B){B=B<<(E&7);var I=E>>>3;Q[I]|=B,Q[I+1]|=B>>>8,Q[I+2]|=B>>>16},A.H.e=function(Q,E,B){return(Q[E>>>3]|Q[(E>>>3)+1]<<8)>>>(E&7)&(1<>>3]|Q[(E>>>3)+1]<<8|Q[(E>>>3)+2]<<16)>>>(E&7)&(1<>>3]|Q[(E>>>3)+1]<<8|Q[(E>>>3)+2]<<16)>>>(E&7)},A.H.i=function(Q,E){return(Q[E>>>3]|Q[(E>>>3)+1]<<8|Q[(E>>>3)+2]<<16|Q[(E>>>3)+3]<<24)>>>(E&7)},A.H.m=function(){var Q=Uint16Array,E=Uint32Array;return{K:new Q(16),j:new Q(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[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,999,999,999],T:[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,0,0,0],q:new Q(32),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,65535,65535],z:[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,0,0],c:new E(32),J:new Q(512),_:[],h:new Q(32),$:[],w:new Q(32768),C:[],v:[],d:new Q(32768),D:[],u:new Q(512),Q:[],r:new Q(32768),s:new E(286),Y:new E(30),a:new E(19),t:new E(15000),k:new Q(65536),g:new Q(32768)}}(),function(){var Q=A.H.m,E=32768;for(var B=0;B>>1|(I&1431655765)<<1,I=(I&3435973836)>>>2|(I&858993459)<<2,I=(I&4042322160)>>>4|(I&252645135)<<4,I=(I&4278255360)>>>8|(I&16711935)<<8,Q.r[B]=(I>>>16|I<<16)>>>17}function C(K,J,U){while(J--!=0)K.push(0,U)}for(var B=0;B<32;B++)Q.q[B]=Q.S[B]<<3|Q.T[B],Q.c[B]=Q.p[B]<<4|Q.z[B];C(Q._,144,8),C(Q._,112,9),C(Q._,24,7),C(Q._,8,8),A.H.n(Q._,9),A.H.A(Q._,9,Q.J),A.H.l(Q._,9),C(Q.$,32,5),A.H.n(Q.$,5),A.H.A(Q.$,5,Q.h),A.H.l(Q.$,5),C(Q.Q,19,0),C(Q.C,286,0),C(Q.D,30,0),C(Q.v,320,0)}(),A.H.N}();OA.LosslessJpegDecode=function(){var A,Q;function E(){return A[Q++]}function B(){return A[Q++]<<8|A[Q++]}function I(W){var Z=E(),G=[0,0,0,255],X=[],q=8;for(var M=0;M<16;M++)X[M]=E();for(var M=0;M<16;M++)for(var F=0;F>--w&1,T=G[T+z];_[M]=T}}function C(W,Z,G,X){if(W[Z+3]!=255)return 0;if(G==0)return Z;for(var q=0;q<2;q++){if(W[Z+q]==0)W[Z+q]=W.length,W.push(0,0,X,255);var M=C(W,W[Z+q],G-1,X+1);if(M!=0)return M}return 0}function K(W){var{b:Z,f:G}=W;while(Z<25&&W.a>(Z.b-=W)&65535>>16-W}function U(W,Z){var G=W[0],X=0,q=255,M=0;if(Z.b<16)K(Z);var F=Z.f>>Z.b-8&255;X=W[1][F],q=G[X+3],Z.b-=G[X+2];while(q==255)M=Z.f>>--Z.b&1,X=G[X+M],q=G[X+3];return q}function Y(W,Z){if(W<32768>>16-Z)W+=-(1<>4,g&15]}}else if(T==65476){var V=Q+z-2;while(Q>>4],M[h[0]]=h.slice(1)}G=E(),Q+=2;break}else if(T==65501)q=B();else Q+=z-2}var x=X>8?Uint16Array:Uint8Array,b=new x(w*k*_),m={b:0,f:0,c:G==8,a:Q,data:A,d:A.length,e:q};if(m.c)N(b,k*_,m,D[0],w);else{var s=[],i=0,n=0;for(var j=0;j<_;j++){var l=M[j],c=l[0],o=l[1];if(c>i)i=c;if(o>n)n=o;s.push(c*o)}if(i!=1||n!=1){if(_!=3||s[1]!=1||s[2]!=1)throw"e";if(i!=2||n!=1&&n!=2)throw"e";var e=[],BA=0;for(var j=0;j<_;j++){for(var EA=0;EA>>1)*CA+(c>>>1))*BA,wA=(o&1)*2+(c&1);b[ZA]=FA[jA+wA],b[ZA+1]=FA[jA+4],b[ZA+2]=FA[jA+5]}else for(var c=0;c>>1))*BA,wA=c&1;b[ZA]=FA[jA+wA],b[ZA+1]=FA[jA+2],b[ZA+2]=FA[jA+3]}}else if(R(b,k*_,m,D,_,w),q==0)L(b,G,k,w,0,_,_,X);else{var VA=Math.floor(q/k);for(var o=0;o>>1);else if(Z==6)P=W[v]+(g-W[v-F]>>>1);else if(Z==7)P=g+W[v]>>>1;else throw Z;W[j]+=P}}}return $}();(function(){var A=0,Q=1,E=2,B=3,I=4,C=5,K=6,J=7,U=8,Y=9,H=10,R=11,O=12,N=13,$=14,L=15,W=16,Z=17,G=18;function X(S){var h=OA._binBE.readUshort,x={b:h(S,0),i:S[2],C:S[3],u:S[4],q:h(S,5),k:h(S,7),e:h(S,9),l:h(S,11),s:S[13],d:h(S,14)};if(x.b!=18771||x.i>1||x.q<6||x.q%6||x.e<768||x.e%24||x.l!=768||x.k=x.l||x.s>16||x.s!=x.k/x.l||x.s!=Math.ceil(x.e/x.l)||x.d!=x.q/6||x.u!=12&&x.u!=14&&x.u!=16||x.C!=16&&x.C!=0)throw"Invalid data";if(x.i==0)throw"Not implemented. We need this file!";return x.h=x.C==16,x.m=(x.h?x.l*2/3:x.l>>>1)|0,x.A=x.m+2,x.f=64,x.g=(1<>>6);for(var b=0;b<3;b++)for(var m=0;m<41;m++)h[b][m]=[x,1];return h}function w(S){for(var h=-1,x=0;!x;h++)if(x=S[S.j]>>>7-S.a&1,S.a++,S.a&=7,!S.a)S.j++;return h}function k(S,h){var x=0,b=8-S.a,m=S.j,s=S.a;if(h){if(h>=b)do x<<=b,h-=b,x|=S[S.j]&(1<=8);if(h)x<<=h,b-=h,x|=S[S.j]>>>b&(1<t&&QA>>2,n){f[l]=KA;return}EA=h.t*h.c[S.g+ZA-YA]+h.c[S.g+FA-ZA]}else KA=ZA>FA&&ZA>jA||ZA>>2:wA+VA>>>1,EA=h.t*h.c[S.g+ZA-FA]+h.c[S.g+FA-wA];CA=d(EA);var HA=w(x);if(HA>>1):BA>>>1,i[CA][0]+=d(BA),i[CA][1]==S.f)i[CA][0]>>>=1,i[CA][1]>>>=1;if(i[CA][1]++,KA=EA<0?KA-BA:KA+BA,S.i){if(KA<0)KA+=h.w;else if(KA>S.g)KA-=h.w}f[l]=KA>=0?Math.min(KA,S.g):0}function j(S,h,x){var b=S[0].length;for(var m=h;m<=x;m++)S[m][0]=S[m-1][1],S[m][b-1]=S[m-1][b-2]}function v(S){j(S,J,O),j(S,E,I),j(S,L,Z)}function g(S,h,x,b,m,s,i,n,l,c,o,e,BA){var EA=0,CA=1,f=mI;while(CA8)z(S,h,x,b,m,CA,n[l]),z(S,h,x,b,s,CA,n[l]),CA+=2}v(b)}function P(S,h,x,b,m,s){g(S,h,x,b,E,J,m,s,0,0,1,0,8),g(S,h,x,b,U,L,m,s,1,0,1,0,8),g(S,h,x,b,B,Y,m,s,2,1,0,3,0),g(S,h,x,b,H,W,m,s,0,0,0,3,2),g(S,h,x,b,I,R,m,s,1,0,0,3,2),g(S,h,x,b,O,Z,m,s,2,1,0,3,0)}function V(S,h,x,b,m,s){var i=s.length,n=S.l;if(m+1==S.s)n=S.e-m*S.l;var l=6*S.e*b+m*S.l;for(var c=0;c<6;c++){for(var o=0;o>>1);else if(e==2)BA=L+(c>>>1);else BA=J+c;var EA=S.h?(o*2/3&2147483646|o%3&1)+(o%3>>>1):o>>>1;h[l+o]=x[BA][EA+1]}l+=S.e}}OA._decompressRAF=function(S,h){var x=X(S),b=q(S,x),m=D(x),s=new Int16Array(x.e*x.q);if(h==null)h=x.h?[[1,1,0,1,1,2],[1,1,2,1,1,0],[2,0,1,0,2,1],[1,1,2,1,1,0],[1,1,0,1,1,2],[0,2,1,2,0,1]]:[[0,1],[3,2]];var i=[[A,B],[Q,I],[C,R],[K,O],[N,W],[$,Z]],n=[];for(var l=0;l=I)return;var K=B.charCodeAt(C),J;if(K>=55296&&K<=56319&&I>C+1){if(J=B.charCodeAt(C+1),J>=56320&&J<=57343)return(K-55296)*1024+J-56320+65536}return K};if(A)A(String.prototype,"codePointAt",{value:Q,configurable:!0,writable:!0});else String.prototype.codePointAt=Q})();function E7(){this.table=new Uint16Array(16),this.trans=new Uint16Array(288)}var Tw=new E7,zw=new E7,uW=new Uint8Array(30),pW=new Uint16Array(30),Pw=new Uint8Array(30),Vw=new Uint16Array(30),ag=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),tg=new E7,eg=new Uint8Array(320);function mW(A,Q,E,B){var I,C;for(I=0;Ithis.x2)this.x2=A}if(typeof Q==="number"){if(isNaN(this.y1)||isNaN(this.y2))this.y1=Q,this.y2=Q;if(Qthis.y2)this.y2=Q}};nI.prototype.addX=function(A){this.addPoint(A,null)};nI.prototype.addY=function(A){this.addPoint(null,A)};nI.prototype.addBezier=function(A,Q,E,B,I,C,K,J){var U=[A,Q],Y=[E,B],H=[I,C],R=[K,J];this.addPoint(A,Q),this.addPoint(K,J);for(var O=0;O<=1;O++){var N=6*U[O]-12*Y[O]+6*H[O],$=-3*U[O]+9*Y[O]-9*H[O]+3*R[O],L=3*Y[O]-3*U[O];if($===0){if(N===0)continue;var W=-L/N;if(0=0&&U>0)J+=" ";J+=Q(Y)}return J}var B="";for(var I=0;I=0&&A<=255,"Byte value should be between 0 and 255."),[A]};q0.BYTE=MB(1);mA.CHAR=function(A){return[A.charCodeAt(0)]};q0.CHAR=MB(1);mA.CHARARRAY=function(A){if(typeof A==="undefined")A="",console.warn("Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name.");var Q=[];for(var E=0;E>8&255,A&255]};q0.USHORT=MB(2);mA.SHORT=function(A){if(A>=CW)A=-(2*CW-A);return[A>>8&255,A&255]};q0.SHORT=MB(2);mA.UINT24=function(A){return[A>>16&255,A>>8&255,A&255]};q0.UINT24=MB(3);mA.ULONG=function(A){return[A>>24&255,A>>16&255,A>>8&255,A&255]};q0.ULONG=MB(4);mA.LONG=function(A){if(A>=KW)A=-(2*KW-A);return[A>>24&255,A>>16&255,A>>8&255,A&255]};q0.LONG=MB(4);mA.FIXED=mA.ULONG;q0.FIXED=q0.ULONG;mA.FWORD=mA.SHORT;q0.FWORD=q0.SHORT;mA.UFWORD=mA.USHORT;q0.UFWORD=q0.USHORT;mA.LONGDATETIME=function(A){return[0,0,0,0,A>>24&255,A>>16&255,A>>8&255,A&255]};q0.LONGDATETIME=MB(8);mA.TAG=function(A){return W0.argument(A.length===4,"Tag should be exactly 4 ASCII characters."),[A.charCodeAt(0),A.charCodeAt(1),A.charCodeAt(2),A.charCodeAt(3)]};q0.TAG=MB(4);mA.Card8=mA.BYTE;q0.Card8=q0.BYTE;mA.Card16=mA.USHORT;q0.Card16=q0.USHORT;mA.OffSize=mA.BYTE;q0.OffSize=q0.BYTE;mA.SID=mA.USHORT;q0.SID=q0.USHORT;mA.NUMBER=function(A){if(A>=-107&&A<=107)return[A+139];else if(A>=108&&A<=1131)return A=A-108,[(A>>8)+247,A&255];else if(A>=-1131&&A<=-108)return A=-A-108,[(A>>8)+251,A&255];else if(A>=-32768&&A<=32767)return mA.NUMBER16(A);else return mA.NUMBER32(A)};q0.NUMBER=function(A){return mA.NUMBER(A).length};mA.NUMBER16=function(A){return[28,A>>8&255,A&255]};q0.NUMBER16=MB(3);mA.NUMBER32=function(A){return[29,A>>24&255,A>>16&255,A>>8&255,A&255]};q0.NUMBER32=MB(5);mA.REAL=function(A){var Q=A.toString(),E=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(Q);if(E){var B=parseFloat("1e"+((E[2]?+E[2]:0)+E[1].length));Q=(Math.round(A*B)/B).toString()}var I="";for(var C=0,K=Q.length;C>8&255,Q[Q.length]=B&255}return Q};q0.UTF16=function(A){return A.length*2};var oH={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø"+"¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ"+"јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø"+"ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ"+"άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ"+"ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ"+"ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};M6.MACSTRING=function(A,Q,E,B){var I=oH[B];if(I===void 0)return;var C="";for(var K=0;K=128){if(C=E[C],C===void 0)return}B[I]=C}return B};q0.MACSTRING=function(A,Q){var E=mA.MACSTRING(A,Q);if(E!==void 0)return E.length;else return 0};function rH(A){return A>=-128&&A<=127}function hw(A,Q,E){var B=0,I=A.length;while(Q>8&255,U+256&255)}return C}mA.VARDELTAS=function(A){var Q=0,E=[];while(Q=-128&&B<=127)Q=yw(A,Q,E);else Q=gw(A,Q,E)}return E};mA.INDEX=function(A){var Q=1,E=[Q],B=[];for(var I=0;I>8,Q[R+1]=O&255,Q=Q.concat(B[H])}return Q};q0.TABLE=function(A){var Q=0,E=A.fields.length;for(var B=0;B0)return new $A(this.data,this.offset+Q).parseStruct(A);return};$A.prototype.parsePointer32=function(A){var Q=this.parseOffset32();if(Q>0)return new $A(this.data,this.offset+Q).parseStruct(A);return};$A.prototype.parseListOfLists=function(A){var Q=this.parseOffset16List(),E=Q.length,B=this.relativeOffset,I=new Array(E);for(var C=0;C>1,Q.skip("uShort",3),A.glyphIndexMap={};var K=new z0.Parser(E,B+I+14),J=new z0.Parser(E,B+I+16+C*2),U=new z0.Parser(E,B+I+16+C*4),Y=new z0.Parser(E,B+I+16+C*6),H=B+I+16+C*8;for(var R=0;R=0;I-=1){var C=z0.getUShort(A,Q+4+I*8),K=z0.getUShort(A,Q+4+I*8+2);if(C===3&&(K===0||K===1||K===10)||C===0&&(K===0||K===1||K===2||K===3||K===4)){B=z0.getULong(A,Q+4+I*8+4);break}}if(B===-1)throw new Error("No valid cmap sub-tables found.");var J=new z0.Parser(A,Q+B);if(E.format=J.parseUShort(),E.format===12)cw(E,J);else if(E.format===4)lw(E,J,A,Q,B);else throw new Error("Only format 4 and 12 cmap tables are supported (found format "+E.format+").");return E}function nw(A,Q,E){A.segments.push({end:Q,start:Q,delta:-(Q-E),offset:0,glyphIndex:E})}function sw(A){A.segments.push({end:65535,start:65535,delta:1,offset:0})}function iw(A){var Q=!0,E;for(E=A.length-1;E>0;E-=1){var B=A.get(E);if(B.unicode>65535){console.log("Adding CMAP format 12 (needed!)"),Q=!1;break}}var I=[{name:"version",type:"USHORT",value:0},{name:"numTables",type:"USHORT",value:Q?1:2},{name:"platformID",type:"USHORT",value:3},{name:"encodingID",type:"USHORT",value:1},{name:"offset",type:"ULONG",value:Q?12:20}];if(!Q)I=I.concat([{name:"cmap12PlatformID",type:"USHORT",value:3},{name:"cmap12EncodingID",type:"USHORT",value:10},{name:"cmap12Offset",type:"ULONG",value:0}]);I=I.concat([{name:"format",type:"USHORT",value:4},{name:"cmap4Length",type:"USHORT",value:0},{name:"language",type:"USHORT",value:0},{name:"segCountX2",type:"USHORT",value:0},{name:"searchRange",type:"USHORT",value:0},{name:"entrySelector",type:"USHORT",value:0},{name:"rangeShift",type:"USHORT",value:0}]);var C=new aA.Table("cmap",I);C.segments=[];for(E=0;E>4,K=I&15;if(C===E)break;if(Q+=B[C],K===E)break;Q+=B[K]}return parseFloat(Q)}function J_(A,Q){var E,B,I,C;if(Q===28)return E=A.parseByte(),B=A.parseByte(),E<<8|B;if(Q===29)return E=A.parseByte(),B=A.parseByte(),I=A.parseByte(),C=A.parseByte(),E<<24|B<<16|I<<8|C;if(Q===30)return K_(A);if(Q>=32&&Q<=246)return Q-139;if(Q>=247&&Q<=250)return E=A.parseByte(),(Q-247)*256+E+108;if(Q>=251&&Q<=254)return E=A.parseByte(),-(Q-251)*256-E-108;throw new Error("Invalid b0 "+Q)}function U_(A){var Q={};for(var E=0;E>1,U.length=0,H=!0}function D(_){var w,k,T,z,j,v,g,P,V,S,h,x,b=0;while(b<_.length){var m=_[b];switch(b+=1,m){case 1:F();break;case 3:F();break;case 4:if(U.length>1&&!H)q=U.shift()+Z,H=!0;N+=U.pop(),M(O,N);break;case 5:while(U.length>0)O+=U.shift(),N+=U.shift(),J.lineTo(O,N);break;case 6:while(U.length>0){if(O+=U.shift(),J.lineTo(O,N),U.length===0)break;N+=U.shift(),J.lineTo(O,N)}break;case 7:while(U.length>0){if(N+=U.shift(),J.lineTo(O,N),U.length===0)break;O+=U.shift(),J.lineTo(O,N)}break;case 8:while(U.length>0)B=O+U.shift(),I=N+U.shift(),C=B+U.shift(),K=I+U.shift(),O=C+U.shift(),N=K+U.shift(),J.curveTo(B,I,C,K,O,N);break;case 10:if(j=U.pop()+L,v=$[j],v)D(v);break;case 11:return;case 12:switch(m=_[b],b+=1,m){case 35:B=O+U.shift(),I=N+U.shift(),C=B+U.shift(),K=I+U.shift(),g=C+U.shift(),P=K+U.shift(),V=g+U.shift(),S=P+U.shift(),h=V+U.shift(),x=S+U.shift(),O=h+U.shift(),N=x+U.shift(),U.shift(),J.curveTo(B,I,C,K,g,P),J.curveTo(V,S,h,x,O,N);break;case 34:B=O+U.shift(),I=N,C=B+U.shift(),K=I+U.shift(),g=C+U.shift(),P=K,V=g+U.shift(),S=K,h=V+U.shift(),x=N,O=h+U.shift(),J.curveTo(B,I,C,K,g,P),J.curveTo(V,S,h,x,O,N);break;case 36:B=O+U.shift(),I=N+U.shift(),C=B+U.shift(),K=I+U.shift(),g=C+U.shift(),P=K,V=g+U.shift(),S=K,h=V+U.shift(),x=S+U.shift(),O=h+U.shift(),J.curveTo(B,I,C,K,g,P),J.curveTo(V,S,h,x,O,N);break;case 37:if(B=O+U.shift(),I=N+U.shift(),C=B+U.shift(),K=I+U.shift(),g=C+U.shift(),P=K+U.shift(),V=g+U.shift(),S=P+U.shift(),h=V+U.shift(),x=S+U.shift(),Math.abs(h-O)>Math.abs(x-N))O=h+U.shift();else N=x+U.shift();J.curveTo(B,I,C,K,g,P),J.curveTo(V,S,h,x,O,N);break;default:console.log("Glyph "+Q.index+": unknown operator 1200"+m),U.length=0}break;case 14:if(U.length>0&&!H)q=U.shift()+Z,H=!0;if(R)J.closePath(),R=!1;break;case 18:F();break;case 19:case 20:F(),b+=Y+7>>3;break;case 21:if(U.length>2&&!H)q=U.shift()+Z,H=!0;N+=U.pop(),O+=U.pop(),M(O,N);break;case 22:if(U.length>1&&!H)q=U.shift()+Z,H=!0;O+=U.pop(),M(O,N);break;case 23:F();break;case 24:while(U.length>2)B=O+U.shift(),I=N+U.shift(),C=B+U.shift(),K=I+U.shift(),O=C+U.shift(),N=K+U.shift(),J.curveTo(B,I,C,K,O,N);O+=U.shift(),N+=U.shift(),J.lineTo(O,N);break;case 25:while(U.length>6)O+=U.shift(),N+=U.shift(),J.lineTo(O,N);B=O+U.shift(),I=N+U.shift(),C=B+U.shift(),K=I+U.shift(),O=C+U.shift(),N=K+U.shift(),J.curveTo(B,I,C,K,O,N);break;case 26:if(U.length%2)O+=U.shift();while(U.length>0)B=O,I=N+U.shift(),C=B+U.shift(),K=I+U.shift(),O=C,N=K+U.shift(),J.curveTo(B,I,C,K,O,N);break;case 27:if(U.length%2)N+=U.shift();while(U.length>0)B=O+U.shift(),I=N,C=B+U.shift(),K=I+U.shift(),O=C+U.shift(),N=K,J.curveTo(B,I,C,K,O,N);break;case 28:w=_[b],k=_[b+1],U.push((w<<24|k<<16)>>16),b+=2;break;case 29:if(j=U.pop()+A.gsubrsBias,v=A.gsubrs[j],v)D(v);break;case 30:while(U.length>0){if(B=O,I=N+U.shift(),C=B+U.shift(),K=I+U.shift(),O=C+U.shift(),N=K+(U.length===1?U.shift():0),J.curveTo(B,I,C,K,O,N),U.length===0)break;B=O+U.shift(),I=N,C=B+U.shift(),K=I+U.shift(),N=K+U.shift(),O=C+(U.length===1?U.shift():0),J.curveTo(B,I,C,K,O,N)}break;case 31:while(U.length>0){if(B=O+U.shift(),I=N,C=B+U.shift(),K=I+U.shift(),N=K+U.shift(),O=C+(U.length===1?U.shift():0),J.curveTo(B,I,C,K,O,N),U.length===0)break;B=O,I=N+U.shift(),C=B+U.shift(),K=I+U.shift(),O=C+U.shift(),N=K+(U.length===1?U.shift():0),J.curveTo(B,I,C,K,O,N)}break;default:if(m<32)console.log("Glyph "+Q.index+": unknown operator "+m);else if(m<247)U.push(m-139);else if(m<251)w=_[b],b+=1,U.push((m-247)*256+w+108);else if(m<255)w=_[b],b+=1,U.push(-(m-251)*256-w-108);else w=_[b],k=_[b+1],T=_[b+2],z=_[b+3],b+=4,U.push((w<<24|k<<16|T<<8|z)/65536)}}}return D(E),Q.advanceWidth=q,J}function R_(A,Q,E,B){var I=[],C,K=new z0.Parser(A,Q),J=K.parseCard8();if(J===0)for(var U=0;U=B)throw new Error("CFF table CID Font FDSelect has bad FD index value "+C+" (FD count "+B+")");I.push(C)}else if(J===3){var Y=K.parseCard16(),H=K.parseCard16();if(H!==0)throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID "+H);var R;for(var O=0;O=B)throw new Error("CFF table CID Font FDSelect has bad FD index value "+C+" (FD count "+B+")");if(R>E)throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID "+R);for(;H=0)E=B;if(B=Q.indexOf(A),B>=0)E=B+XU.length;else E=XU.length+Q.length,Q.push(A);return E}function G_(){return new aA.Record("Header",[{name:"major",type:"Card8",value:1},{name:"minor",type:"Card8",value:0},{name:"hdrSize",type:"Card8",value:4},{name:"major",type:"Card8",value:1}])}function W_(A){var Q=new aA.Record("Name INDEX",[{name:"names",type:"INDEX",value:[]}]);Q.names=[];for(var E=0;E=E.begin&&A=1)E.ulCodePageRange1=B.parseULong(),E.ulCodePageRange2=B.parseULong();if(E.version>=2)E.sxHeight=B.parseShort(),E.sCapHeight=B.parseShort(),E.usDefaultChar=B.parseUShort(),E.usBreakChar=B.parseUShort(),E.usMaxContent=B.parseUShort();return E}function t_(A){return new aA.Table("OS/2",[{name:"version",type:"USHORT",value:3},{name:"xAvgCharWidth",type:"SHORT",value:0},{name:"usWeightClass",type:"USHORT",value:0},{name:"usWidthClass",type:"USHORT",value:0},{name:"fsType",type:"USHORT",value:0},{name:"ySubscriptXSize",type:"SHORT",value:650},{name:"ySubscriptYSize",type:"SHORT",value:699},{name:"ySubscriptXOffset",type:"SHORT",value:0},{name:"ySubscriptYOffset",type:"SHORT",value:140},{name:"ySuperscriptXSize",type:"SHORT",value:650},{name:"ySuperscriptYSize",type:"SHORT",value:699},{name:"ySuperscriptXOffset",type:"SHORT",value:0},{name:"ySuperscriptYOffset",type:"SHORT",value:479},{name:"yStrikeoutSize",type:"SHORT",value:49},{name:"yStrikeoutPosition",type:"SHORT",value:258},{name:"sFamilyClass",type:"SHORT",value:0},{name:"bFamilyType",type:"BYTE",value:0},{name:"bSerifStyle",type:"BYTE",value:0},{name:"bWeight",type:"BYTE",value:0},{name:"bProportion",type:"BYTE",value:0},{name:"bContrast",type:"BYTE",value:0},{name:"bStrokeVariation",type:"BYTE",value:0},{name:"bArmStyle",type:"BYTE",value:0},{name:"bLetterform",type:"BYTE",value:0},{name:"bMidline",type:"BYTE",value:0},{name:"bXHeight",type:"BYTE",value:0},{name:"ulUnicodeRange1",type:"ULONG",value:0},{name:"ulUnicodeRange2",type:"ULONG",value:0},{name:"ulUnicodeRange3",type:"ULONG",value:0},{name:"ulUnicodeRange4",type:"ULONG",value:0},{name:"achVendID",type:"CHARARRAY",value:"XXXX"},{name:"fsSelection",type:"USHORT",value:0},{name:"usFirstCharIndex",type:"USHORT",value:0},{name:"usLastCharIndex",type:"USHORT",value:0},{name:"sTypoAscender",type:"SHORT",value:0},{name:"sTypoDescender",type:"SHORT",value:0},{name:"sTypoLineGap",type:"SHORT",value:0},{name:"usWinAscent",type:"USHORT",value:0},{name:"usWinDescent",type:"USHORT",value:0},{name:"ulCodePageRange1",type:"ULONG",value:0},{name:"ulCodePageRange2",type:"ULONG",value:0},{name:"sxHeight",type:"SHORT",value:0},{name:"sCapHeight",type:"SHORT",value:0},{name:"usDefaultChar",type:"USHORT",value:0},{name:"usBreakChar",type:"USHORT",value:0},{name:"usMaxContext",type:"USHORT",value:0}],A)}var GW={parse:a_,make:t_,unicodeRanges:A7,getUnicodeRange:r_};function e_(A,Q){var E={},B=new z0.Parser(A,Q);switch(E.version=B.parseVersion(),E.italicAngle=B.parseFixed(),E.underlinePosition=B.parseShort(),E.underlineThickness=B.parseShort(),E.isFixedPitch=B.parseULong(),E.minMemType42=B.parseULong(),E.maxMemType42=B.parseULong(),E.minMemType1=B.parseULong(),E.maxMemType1=B.parseULong(),E.version){case 1:E.names=d1.slice();break;case 2:E.numberOfGlyphs=B.parseUShort(),E.glyphNameIndex=new Array(E.numberOfGlyphs);for(var I=0;I=d1.length){var K=B.parseChar();E.names.push(B.parseString(K))}break;case 2.5:E.numberOfGlyphs=B.parseUShort(),E.offset=new Array(E.numberOfGlyphs);for(var J=0;JR.value.tag)return 1;else return-1}),Q.fields=Q.fields.concat(B),Q.fields=Q.fields.concat(I),Q}function $W(A,Q,E){for(var B=0;B0){var C=A.glyphs.get(I);return C.getMetrics()}}return E}function N2(A){var Q=0;for(var E=0;EW||U===void 0){if(W>0)U=W}if(Y 123 are reserved for internal usage");if(L.name===".notdef")continue;var G=L.getMetrics();Q.push(G.xMin),E.push(G.yMin),B.push(G.xMax),I.push(G.yMax),K.push(G.leftSideBearing),J.push(G.rightSideBearing),C.push(L.advanceWidth)}var X={xMin:Math.min.apply(null,Q),yMin:Math.min.apply(null,E),xMax:Math.max.apply(null,B),yMax:Math.max.apply(null,I),advanceWidthMax:Math.max.apply(null,C),advanceWidthAvg:N2(C),minLeftSideBearing:Math.min.apply(null,K),maxLeftSideBearing:Math.max.apply(null,K),minRightSideBearing:Math.min.apply(null,J)};X.ascender=A.ascender,X.descender=A.descender;var q=S_.make({flags:3,unitsPerEm:A.unitsPerEm,xMin:X.xMin,yMin:X.yMin,xMax:X.xMax,yMax:X.yMax,lowestRecPPEM:3,createdTimestamp:A.createdTimestamp}),M=P_.make({ascender:X.ascender,descender:X.descender,advanceWidthMax:X.advanceWidthMax,minLeftSideBearing:X.minLeftSideBearing,minRightSideBearing:X.minRightSideBearing,xMaxExtent:X.maxLeftSideBearing+(X.xMax-X.xMin),numberOfHMetrics:A.glyphs.length}),F=p_.make(A.glyphs.length),D=GW.make(Object.assign({xAvgCharWidth:Math.round(X.advanceWidthAvg),usFirstCharIndex:U,usLastCharIndex:Y,ulUnicodeRange1:H,ulUnicodeRange2:R,ulUnicodeRange3:O,ulUnicodeRange4:N,sTypoAscender:X.ascender,sTypoDescender:X.descender,sTypoLineGap:0,usWinAscent:X.yMax,usWinDescent:Math.abs(X.yMin),ulCodePageRange1:1,sxHeight:$W(A,"xyvw",{yMax:Math.round(X.ascender/2)}).yMax,sCapHeight:$W(A,"HIKLEFJMNTZBDPRAGOQSUVWXY",X).yMax,usDefaultChar:A.hasChar(" ")?32:0,usBreakChar:A.hasChar(" ")?32:0},A.tables.os2)),_=y_.make(A.glyphs),w=ow.make(A.glyphs),k=A.getEnglishName("fontFamily"),T=A.getEnglishName("fontSubfamily"),z=k+" "+T,j=A.getEnglishName("postScriptName");if(!j)j=k.replace(/\s/g,"")+"-"+T;var v={};for(var g in A.names)v[g]=A.names[g];if(!v.uniqueID)v.uniqueID={en:A.getEnglishName("manufacturer")+":"+z};if(!v.postScriptName)v.postScriptName={en:j};if(!v.preferredFamily)v.preferredFamily=A.names.fontFamily;if(!v.preferredSubfamily)v.preferredSubfamily=A.names.fontSubfamily;var P=[],V=o_.make(v,P),S=P.length>0?b_.make(P):void 0,h=Q2.make(),x=w_.make(A.glyphs,{version:A.getEnglishName("version"),fullName:z,familyName:k,weightName:T,postScriptName:j,unitsPerEm:A.unitsPerEm,fontBBox:[0,X.yMin,X.ascender,X.advanceWidthMax]}),b=A.metas&&Object.keys(A.metas).length>0?J2.make(A.metas):void 0,m=[q,M,F,D,V,w,h,x,_];if(S)m.push(S);if(A.tables.gsub)m.push(I2.make(A.tables.gsub));if(A.tables.cpal)m.push(R2.make(A.tables.cpal));if(A.tables.colr)m.push(O2.make(A.tables.colr));if(b)m.push(b);var s=CX(m),i=s.encode(),n=C7(i),l=s.fields,c=!1;for(var o=0;o>>1,C=A[I].tag;if(C===Q)return I;else if(C>>1,C=A[I];if(C===Q)return I;else if(C>>1;E=A[C];var K=E.start;if(K===Q)return E;else if(K0){if(E=A[B-1],Q>E.end)return 0;return E}}function GK(A,Q){this.font=A,this.tableName=Q}GK.prototype={searchTag:mH,binSearch:LW,getTable:function(A){var Q=this.font.tables[this.tableName];if(!Q&&A)Q=this.font.tables[this.tableName]=this.createDefaultTable();return Q},getScriptNames:function(){var A=this.getTable();if(!A)return[];return A.scripts.map(function(Q){return Q.tag})},getDefaultScriptName:function(){var A=this.getTable();if(!A)return;var Q=!1;for(var E=0;E=0)return B[I].script;else if(Q){var C={tag:A,script:{defaultLangSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]},langSysRecords:[]}};return B.splice(-1-I,0,C),C.script}}},getLangSysTable:function(A,Q,E){var B=this.getScriptTable(A,E);if(B){if(!Q||Q==="dflt"||Q==="DFLT")return B.defaultLangSys;var I=mH(B.langSysRecords,Q);if(I>=0)return B.langSysRecords[I].langSys;else if(E){var C={tag:Q,langSys:{reserved:0,reqFeatureIndex:65535,featureIndexes:[]}};return B.langSysRecords.splice(-1-I,0,C),C.langSys}}},getFeatureTable:function(A,Q,E,B){var I=this.getLangSysTable(A,Q,B);if(I){var C,K=I.featureIndexes,J=this.font.tables[this.tableName].features;for(var U=0;U=J[Y-1].tag,"Features must be added in alphabetical order."),C={tag:E,feature:{params:0,lookupListIndexes:[]}},J.push(C),K.push(Y),C.feature}}},getLookupTables:function(A,Q,E,B,I){var C=this.getFeatureTable(A,Q,E,I),K=[];if(C){var J,U=C.lookupListIndexes,Y=this.font.tables[this.tableName].lookups;for(var H=0;H=0?E:-1;case 2:var B=qW(A.ranges,Q);return B?B.index+Q-B.start:-1}},expandCoverage:function(A){if(A.format===1)return A.glyphs;else{var Q=[],E=A.ranges;for(var B=0;B1,'Multiple: "by" must be an array of two or more ids');var I=this.getLookupTables(E,B,A,2,!0)[0],C=K7(I,1,{substFormat:1,coverage:{format:1,glyphs:[]},sequences:[]});W0.assert(C.coverage.format===1,"Multiple: unable to modify coverage table format "+C.coverage.format);var K=Q.sub,J=this.binSearch(C.coverage.glyphs,K);if(J<0)J=-1-J,C.coverage.glyphs.splice(J,0,K),C.sequences.splice(J,0,0);C.sequences[J]=Q.by};uE.prototype.addAlternate=function(A,Q,E,B){var I=this.getLookupTables(E,B,A,3,!0)[0],C=K7(I,1,{substFormat:1,coverage:{format:1,glyphs:[]},alternateSets:[]});W0.assert(C.coverage.format===1,"Alternate: unable to modify coverage table format "+C.coverage.format);var K=Q.sub,J=this.binSearch(C.coverage.glyphs,K);if(J<0)J=-1-J,C.coverage.glyphs.splice(J,0,K),C.alternateSets.splice(J,0,0);C.alternateSets[J]=Q.by};uE.prototype.addLigature=function(A,Q,E,B){var I=this.getLookupTables(E,B,A,4,!0)[0],C=I.subtables[0];if(!C)C={substFormat:1,coverage:{format:1,glyphs:[]},ligatureSets:[]},I.subtables[0]=C;W0.assert(C.coverage.format===1,"Ligature: unable to modify coverage table format "+C.coverage.format);var K=Q.sub[0],J=Q.sub.slice(1),U={ligGlyph:Q.by,components:J},Y=this.binSearch(C.coverage.glyphs,K);if(Y>=0){var H=C.ligatureSets[Y];for(var R=0;R0){if(C=A.parseByte(),(Q&I)===0)C=-C;C=E+C}else if((Q&I)>0)C=E;else C=E+A.parseShort();return C}function KX(A,Q,E){var B=new z0.Parser(Q,E);A.numberOfContours=B.parseShort(),A._xMin=B.parseShort(),A._yMin=B.parseShort(),A._xMax=B.parseShort(),A._yMax=B.parseShort();var I,C;if(A.numberOfContours>0){var K=A.endPointIndices=[];for(var J=0;J0){var R=B.parseByte();for(var O=0;O0){var N=[],$;if(Y>0){for(var L=0;L=0,N.push($);var W=0;for(var Z=0;Z0)if((I&2)>0)M.dx=B.parseShort(),M.dy=B.parseShort();else M.matchedPoints=[B.parseUShort(),B.parseUShort()];else if((I&2)>0)M.dx=B.parseChar(),M.dy=B.parseChar();else M.matchedPoints=[B.parseByte(),B.parseByte()];if((I&8)>0)M.xScale=M.yScale=B.parseF2Dot14();else if((I&64)>0)M.xScale=B.parseF2Dot14(),M.yScale=B.parseF2Dot14();else if((I&128)>0)M.xScale=B.parseF2Dot14(),M.scale01=B.parseF2Dot14(),M.scale10=B.parseF2Dot14(),M.yScale=B.parseF2Dot14();A.components.push(M),q=!!(I&32)}if(I&256){A.instructionLength=B.parseUShort(),A.instructions=[];for(var F=0;FQ.points.length-1||B.matchedPoints[1]>I.points.length-1)throw Error("Matched points out of range in "+Q.name);var K=Q.points[B.matchedPoints[0]],J=I.points[B.matchedPoints[1]],U={xScale:B.xScale,scale01:B.scale01,scale10:B.scale10,yScale:B.yScale,dx:0,dy:0};J=cH([J],U)[0],U.dx=K.x-J.x,U.dy=K.y-J.y,C=cH(I.points,U)}Q.points=Q.points.concat(C)}}return JX(Q.points)}function L2(A,Q,E,B){var I=new mB.GlyphSet(B);for(var C=0;C2)return;var E=this.font,B=this._prepState;if(!B||B.ppem!==Q){var I=this._fpgmState;if(!I){if(cI.prototype=T2,I=this._fpgmState=new cI("fpgm",E.tables.fpgm),I.funcs=[],I.font=E,Ex.DEBUG)console.log("---EXEC FPGM---"),I.step=-1;try{s1(I)}catch(Y){console.log("Hinting error in FPGM:"+Y),this._errorState=3;return}}cI.prototype=I,B=this._prepState=new cI("prep",E.tables.prep),B.ppem=Q;var C=E.tables.cvt;if(C){var K=B.cvt=new Array(C.length),J=Q/E.unitsPerEm;for(var U=0;U1)return;try{return OX(A,B)}catch(Y){if(this._errorState<1)console.log("Hinting error:"+Y),console.log("Note: further hinting errors are silenced");this._errorState=1;return}};OX=function(A,Q){var E=Q.ppem/Q.font.unitsPerEm,B=E,I=A.components,C,K,J;if(cI.prototype=Q,!I){if(J=new cI("glyf",A.instructions),Ex.DEBUG)console.log("---EXEC GLYPH---"),J.step=-1;Q7(A,J,E,B),K=J.gZone}else{var U=Q.font;K=[],C=[];for(var Y=0;Y=176&&C<=183)B+=C-176+1;else if(C>=184&&C<=191)B+=(C-184+1)*2;else if(Q&&I===1&&C===27)break;while(I>0);A.ip=B}function DW(A,Q){if(Ex.DEBUG)console.log(Q.step,"SVTCA["+A.axis+"]");Q.fv=Q.pv=Q.dpv=A}function MW(A,Q){if(Ex.DEBUG)console.log(Q.step,"SPVTCA["+A.axis+"]");Q.pv=Q.dpv=A}function wW(A,Q){if(Ex.DEBUG)console.log(Q.step,"SFVTCA["+A.axis+"]");Q.fv=A}function _W(A,Q){var E=Q.stack,B=E.pop(),I=E.pop(),C=Q.z2[B],K=Q.z1[I];if(Ex.DEBUG)console.log("SPVTL["+A+"]",B,I);var J,U;if(!A)J=K.x-C.x,U=K.y-C.y;else J=C.y-K.y,U=K.x-C.x;Q.pv=Q.dpv=$K(J,U)}function kW(A,Q){var E=Q.stack,B=E.pop(),I=E.pop(),C=Q.z2[B],K=Q.z1[I];if(Ex.DEBUG)console.log("SFVTL["+A+"]",B,I);var J,U;if(!A)J=K.x-C.x,U=K.y-C.y;else J=C.y-K.y,U=K.x-C.x;Q.fv=$K(J,U)}function z2(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"SPVFS[]",E,B);A.pv=A.dpv=$K(B,E)}function P2(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"SPVFS[]",E,B);A.fv=$K(B,E)}function V2(A){var{stack:Q,pv:E}=A;if(Ex.DEBUG)console.log(A.step,"GPV[]");Q.push(E.x*16384),Q.push(E.y*16384)}function j2(A){var{stack:Q,fv:E}=A;if(Ex.DEBUG)console.log(A.step,"GFV[]");Q.push(E.x*16384),Q.push(E.y*16384)}function v2(A){if(A.fv=A.pv,Ex.DEBUG)console.log(A.step,"SFVTPV[]")}function h2(A){var Q=A.stack,E=Q.pop(),B=Q.pop(),I=Q.pop(),C=Q.pop(),K=Q.pop(),J=A.z0,U=A.z1,Y=J[E],H=J[B],R=U[I],O=U[C],N=A.z2[K];if(Ex.DEBUG)console.log("ISECT[], ",E,B,I,C,K);var{x:$,y:L}=Y,W=H.x,Z=H.y,G=R.x,X=R.y,q=O.x,M=O.y,F=($-W)*(X-M)-(L-Z)*(G-q),D=$*Z-L*W,_=G*M-X*q;N.x=(D*(G-q)-_*($-W))/F,N.y=(D*(X-M)-_*(L-Z))/F}function y2(A){if(A.rp0=A.stack.pop(),Ex.DEBUG)console.log(A.step,"SRP0[]",A.rp0)}function g2(A){if(A.rp1=A.stack.pop(),Ex.DEBUG)console.log(A.step,"SRP1[]",A.rp1)}function x2(A){if(A.rp2=A.stack.pop(),Ex.DEBUG)console.log(A.step,"SRP2[]",A.rp2)}function b2(A){var Q=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"SZP0[]",Q);switch(A.zp0=Q,Q){case 0:if(!A.tZone)_U(A);A.z0=A.tZone;break;case 1:A.z0=A.gZone;break;default:throw new Error("Invalid zone pointer")}}function f2(A){var Q=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"SZP1[]",Q);switch(A.zp1=Q,Q){case 0:if(!A.tZone)_U(A);A.z1=A.tZone;break;case 1:A.z1=A.gZone;break;default:throw new Error("Invalid zone pointer")}}function u2(A){var Q=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"SZP2[]",Q);switch(A.zp2=Q,Q){case 0:if(!A.tZone)_U(A);A.z2=A.tZone;break;case 1:A.z2=A.gZone;break;default:throw new Error("Invalid zone pointer")}}function p2(A){var Q=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"SZPS[]",Q);switch(A.zp0=A.zp1=A.zp2=Q,Q){case 0:if(!A.tZone)_U(A);A.z0=A.z1=A.z2=A.tZone;break;case 1:A.z0=A.z1=A.z2=A.gZone;break;default:throw new Error("Invalid zone pointer")}}function m2(A){if(A.loop=A.stack.pop(),Ex.DEBUG)console.log(A.step,"SLOOP[]",A.loop)}function c2(A){if(Ex.DEBUG)console.log(A.step,"RTG[]");A.round=ZX}function l2(A){if(Ex.DEBUG)console.log(A.step,"RTHG[]");A.round=_2}function d2(A){var Q=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"SMD[]",Q);A.minDis=Q/64}function n2(A){if(Ex.DEBUG)console.log(A.step,"ELSE[]");NX(A,!1)}function s2(A){var Q=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"JMPR[]",Q);A.ip+=Q-1}function i2(A){var Q=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"SCVTCI[]",Q);A.cvCutIn=Q/64}function o2(A){var Q=A.stack;if(Ex.DEBUG)console.log(A.step,"DUP[]");Q.push(Q[Q.length-1])}function lH(A){if(Ex.DEBUG)console.log(A.step,"POP[]");A.stack.pop()}function r2(A){if(Ex.DEBUG)console.log(A.step,"CLEAR[]");A.stack.length=0}function a2(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"SWAP[]");Q.push(E),Q.push(B)}function t2(A){var Q=A.stack;if(Ex.DEBUG)console.log(A.step,"DEPTH[]");Q.push(Q.length)}function e2(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"LOOPCALL[]",E,B);var{ip:I,prog:C}=A;A.prog=A.funcs[E];for(var K=0;K1?"loop "+(Q.loop-J)+": ":"")+"SHP["+(A?"rp1":"rp2")+"]",Y)}Q.loop=1}function PW(A,Q){var E=Q.stack,B=A?Q.rp1:Q.rp2,I=(A?Q.z0:Q.z1)[B],C=Q.fv,K=Q.pv,J=E.pop(),U=Q.z2[Q.contours[J]],Y=U;if(Ex.DEBUG)console.log(Q.step,"SHC["+A+"]",J);var H=K.distance(I,I,!1,!0);do{if(Y!==I)C.setRelative(Y,Y,H,K);Y=Y.nextPointOnContour}while(Y!==U)}function VW(A,Q){var E=Q.stack,B=A?Q.rp1:Q.rp2,I=(A?Q.z0:Q.z1)[B],C=Q.fv,K=Q.pv,J=E.pop();if(Ex.DEBUG)console.log(Q.step,"SHZ["+A+"]",J);var U;switch(J){case 0:U=Q.tZone;break;case 1:U=Q.gZone;break;default:throw new Error("Invalid zone")}var Y,H=K.distance(I,I,!1,!0),R=U.length-2;for(var O=0;O1?"loop "+(A.loop-E)+": ":"")+"SHPIX[]",K,I);B.setRelative(J,J,I),B.touch(J)}A.loop=1}function C4(A){var{stack:Q,rp1:E,rp2:B,loop:I}=A,C=A.z0[E],K=A.z1[B],J=A.fv,U=A.dpv,Y=A.z2;while(I--){var H=Q.pop(),R=Y[H];if(Ex.DEBUG)console.log(A.step,(A.loop>1?"loop "+(A.loop-I)+": ":"")+"IP[]",H,E,"<->",B);J.interpolate(R,C,K,U),J.touch(R)}A.loop=1}function jW(A,Q){var E=Q.stack,B=E.pop()/64,I=E.pop(),C=Q.z1[I],K=Q.z0[Q.rp0],J=Q.fv,U=Q.pv;if(J.setRelative(C,K,B,U),J.touch(C),Ex.DEBUG)console.log(Q.step,"MSIRP["+A+"]",B,I);if(Q.rp1=Q.rp0,Q.rp2=I,A)Q.rp0=I}function K4(A){var{stack:Q,rp0:E}=A,B=A.z0[E],I=A.loop,C=A.fv,K=A.pv,J=A.z1;while(I--){var U=Q.pop(),Y=J[U];if(Ex.DEBUG)console.log(A.step,(A.loop>1?"loop "+(A.loop-I)+": ":"")+"ALIGNRP[]",U);C.setRelative(Y,B,0,K),C.touch(Y)}A.loop=1}function J4(A){if(Ex.DEBUG)console.log(A.step,"RTDG[]");A.round=w2}function vW(A,Q){var E=Q.stack,B=E.pop(),I=E.pop(),C=Q.z0[I],K=Q.fv,J=Q.pv,U=Q.cvt[B];if(Ex.DEBUG)console.log(Q.step,"MIAP["+A+"]",B,"(",U,")",I);var Y=J.distance(C,NK);if(A){if(Math.abs(Y-U)",J);Q.stack.push(Math.round(J*64))}function N4(A){if(Ex.DEBUG)console.log(A.step,"MPPEM[]");A.stack.push(A.ppem)}function G4(A){if(Ex.DEBUG)console.log(A.step,"FLIPON[]");A.autoFlip=!0}function W4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"LT[]",E,B);Q.push(BE?1:0)}function L4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"GTEQ[]",E,B);Q.push(B>=E?1:0)}function q4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"EQ[]",E,B);Q.push(E===B?1:0)}function F4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"NEQ[]",E,B);Q.push(E!==B?1:0)}function D4(A){var Q=A.stack,E=Q.pop();if(Ex.DEBUG)console.log(A.step,"ODD[]",E);Q.push(Math.trunc(E)%2?1:0)}function M4(A){var Q=A.stack,E=Q.pop();if(Ex.DEBUG)console.log(A.step,"EVEN[]",E);Q.push(Math.trunc(E)%2?0:1)}function w4(A){var Q=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"IF[]",Q);if(!Q){if(NX(A,!0),Ex.DEBUG)console.log(A.step,"EIF[]")}}function _4(A){if(Ex.DEBUG)console.log(A.step,"EIF[]")}function k4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"AND[]",E,B);Q.push(E&&B?1:0)}function S4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"OR[]",E,B);Q.push(E||B?1:0)}function T4(A){var Q=A.stack,E=Q.pop();if(Ex.DEBUG)console.log(A.step,"NOT[]",E);Q.push(E?0:1)}function dH(A,Q){var E=Q.stack,B=E.pop(),I=Q.fv,C=Q.pv,K=Q.ppem,J=Q.deltaBase+(A-1)*16,U=Q.deltaShift,Y=Q.z0;if(Ex.DEBUG)console.log(Q.step,"DELTAP["+A+"]",B,E);for(var H=0;H>4);if(N!==K)continue;var $=(O&15)-8;if($>=0)$++;if(Ex.DEBUG)console.log(Q.step,"DELTAPFIX",R,"by",$*U);var L=Y[R];I.setRelative(L,L,$*U,C)}}function z4(A){var Q=A.stack,E=Q.pop();if(Ex.DEBUG)console.log(A.step,"SDB[]",E);A.deltaBase=E}function P4(A){var Q=A.stack,E=Q.pop();if(Ex.DEBUG)console.log(A.step,"SDS[]",E);A.deltaShift=Math.pow(0.5,E)}function V4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"ADD[]",E,B);Q.push(B+E)}function j4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"SUB[]",E,B);Q.push(B-E)}function v4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"DIV[]",E,B);Q.push(B*64/E)}function h4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"MUL[]",E,B);Q.push(B*E/64)}function y4(A){var Q=A.stack,E=Q.pop();if(Ex.DEBUG)console.log(A.step,"ABS[]",E);Q.push(Math.abs(E))}function g4(A){var Q=A.stack,E=Q.pop();if(Ex.DEBUG)console.log(A.step,"NEG[]",E);Q.push(-E)}function x4(A){var Q=A.stack,E=Q.pop();if(Ex.DEBUG)console.log(A.step,"FLOOR[]",E);Q.push(Math.floor(E/64)*64)}function b4(A){var Q=A.stack,E=Q.pop();if(Ex.DEBUG)console.log(A.step,"CEILING[]",E);Q.push(Math.ceil(E/64)*64)}function WU(A,Q){var E=Q.stack,B=E.pop();if(Ex.DEBUG)console.log(Q.step,"ROUND[]");E.push(Q.round(B/64)*64)}function f4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"WCVTF[]",E,B);A.cvt[B]=E*A.ppem/A.font.unitsPerEm}function nH(A,Q){var E=Q.stack,B=E.pop(),I=Q.ppem,C=Q.deltaBase+(A-1)*16,K=Q.deltaShift;if(Ex.DEBUG)console.log(Q.step,"DELTAC["+A+"]",B,E);for(var J=0;J>4);if(H!==I)continue;var R=(Y&15)-8;if(R>=0)R++;var O=R*K;if(Ex.DEBUG)console.log(Q.step,"DELTACFIX",U,"by",O);Q.cvt[U]+=O}}function u4(A){var Q=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"SROUND[]",Q);A.round=RX;var E;switch(Q&192){case 0:E=0.5;break;case 64:E=1;break;case 128:E=2;break;default:throw new Error("invalid SROUND value")}switch(A.srPeriod=E,Q&48){case 0:A.srPhase=0;break;case 16:A.srPhase=0.25*E;break;case 32:A.srPhase=0.5*E;break;case 48:A.srPhase=0.75*E;break;default:throw new Error("invalid SROUND value")}if(Q&=15,Q===0)A.srThreshold=0;else A.srThreshold=(Q/8-0.5)*E}function p4(A){var Q=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"S45ROUND[]",Q);A.round=RX;var E;switch(Q&192){case 0:E=Math.sqrt(2)/2;break;case 64:E=Math.sqrt(2);break;case 128:E=2*Math.sqrt(2);break;default:throw new Error("invalid S45ROUND value")}switch(A.srPeriod=E,Q&48){case 0:A.srPhase=0;break;case 16:A.srPhase=0.25*E;break;case 32:A.srPhase=0.5*E;break;case 48:A.srPhase=0.75*E;break;default:throw new Error("invalid S45ROUND value")}if(Q&=15,Q===0)A.srThreshold=0;else A.srThreshold=(Q/8-0.5)*E}function m4(A){if(Ex.DEBUG)console.log(A.step,"ROFF[]");A.round=M2}function c4(A){if(Ex.DEBUG)console.log(A.step,"RUTG[]");A.round=k2}function l4(A){if(Ex.DEBUG)console.log(A.step,"RDTG[]");A.round=S2}function d4(A){var Q=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"SCANCTRL[]",Q)}function gW(A,Q){var E=Q.stack,B=E.pop(),I=E.pop(),C=Q.z2[B],K=Q.z1[I];if(Ex.DEBUG)console.log(Q.step,"SDPVTL["+A+"]",B,I);var J,U;if(!A)J=K.x-C.x,U=K.y-C.y;else J=C.y-K.y,U=K.x-C.x;Q.dpv=$K(J,U)}function n4(A){var Q=A.stack,E=Q.pop(),B=0;if(Ex.DEBUG)console.log(A.step,"GETINFO[]",E);if(E&1)B=35;if(E&32)B|=4096;Q.push(B)}function s4(A){var Q=A.stack,E=Q.pop(),B=Q.pop(),I=Q.pop();if(Ex.DEBUG)console.log(A.step,"ROLL[]");Q.push(B),Q.push(E),Q.push(I)}function i4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"MAX[]",E,B);Q.push(Math.max(B,E))}function o4(A){var Q=A.stack,E=Q.pop(),B=Q.pop();if(Ex.DEBUG)console.log(A.step,"MIN[]",E,B);Q.push(Math.min(B,E))}function r4(A){var Q=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"SCANTYPE[]",Q)}function a4(A){var Q=A.stack.pop(),E=A.stack.pop();if(Ex.DEBUG)console.log(A.step,"INSTCTRL[]",Q,E);switch(Q){case 1:A.inhibitGridFit=!!E;return;case 2:A.ignoreCvt=!!E;return;default:throw new Error("invalid INSTCTRL[] selector")}}function uI(A,Q){var{stack:E,prog:B,ip:I}=Q;if(Ex.DEBUG)console.log(Q.step,"PUSHB["+A+"]");for(var C=0;C=0?1:-1,W=Math.abs(W),A){if(G=C.cvt[J],B&&Math.abs(W-G)":"_")+(B?"R":"_")+(I===0?"Gr":I===1?"Bl":I===2?"Wh":"")+"]",A?J+"("+C.cvt[J]+","+G+")":"",U,"(d =",L,"->",Z*W,")");if(C.rp1=C.rp0,C.rp2=U,Q)C.rp0=U}YX=[DW.bind(void 0,RI),DW.bind(void 0,pB),MW.bind(void 0,RI),MW.bind(void 0,pB),wW.bind(void 0,RI),wW.bind(void 0,pB),_W.bind(void 0,0),_W.bind(void 0,1),kW.bind(void 0,0),kW.bind(void 0,1),z2,P2,V2,j2,v2,h2,y2,g2,x2,b2,f2,u2,p2,m2,c2,l2,d2,n2,s2,i2,void 0,void 0,o2,lH,r2,a2,t2,Q4,E4,void 0,void 0,void 0,e2,A4,B4,void 0,SW.bind(void 0,0),SW.bind(void 0,1),TW.bind(void 0,RI),TW.bind(void 0,pB),zW.bind(void 0,0),zW.bind(void 0,1),PW.bind(void 0,0),PW.bind(void 0,1),VW.bind(void 0,0),VW.bind(void 0,1),I4,C4,jW.bind(void 0,0),jW.bind(void 0,1),K4,J4,vW.bind(void 0,0),vW.bind(void 0,1),U4,Y4,O4,H4,Z4,R4,hW.bind(void 0,0),hW.bind(void 0,1),void 0,yW.bind(void 0,0),yW.bind(void 0,1),N4,void 0,G4,void 0,void 0,W4,X4,$4,L4,q4,F4,D4,M4,w4,_4,k4,S4,T4,dH.bind(void 0,1),z4,P4,V4,j4,v4,h4,y4,g4,x4,b4,WU.bind(void 0,0),WU.bind(void 0,1),WU.bind(void 0,2),WU.bind(void 0,3),void 0,void 0,void 0,void 0,f4,dH.bind(void 0,2),dH.bind(void 0,3),nH.bind(void 0,1),nH.bind(void 0,2),nH.bind(void 0,3),u4,p4,void 0,void 0,m4,void 0,c4,l4,lH,lH,void 0,void 0,void 0,void 0,void 0,d4,gW.bind(void 0,0),gW.bind(void 0,1),n4,void 0,s4,i4,o4,r4,a4,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,uI.bind(void 0,1),uI.bind(void 0,2),uI.bind(void 0,3),uI.bind(void 0,4),uI.bind(void 0,5),uI.bind(void 0,6),uI.bind(void 0,7),uI.bind(void 0,8),pI.bind(void 0,1),pI.bind(void 0,2),pI.bind(void 0,3),pI.bind(void 0,4),pI.bind(void 0,5),pI.bind(void 0,6),pI.bind(void 0,7),pI.bind(void 0,8),eA.bind(void 0,0,0,0,0,0),eA.bind(void 0,0,0,0,0,1),eA.bind(void 0,0,0,0,0,2),eA.bind(void 0,0,0,0,0,3),eA.bind(void 0,0,0,0,1,0),eA.bind(void 0,0,0,0,1,1),eA.bind(void 0,0,0,0,1,2),eA.bind(void 0,0,0,0,1,3),eA.bind(void 0,0,0,1,0,0),eA.bind(void 0,0,0,1,0,1),eA.bind(void 0,0,0,1,0,2),eA.bind(void 0,0,0,1,0,3),eA.bind(void 0,0,0,1,1,0),eA.bind(void 0,0,0,1,1,1),eA.bind(void 0,0,0,1,1,2),eA.bind(void 0,0,0,1,1,3),eA.bind(void 0,0,1,0,0,0),eA.bind(void 0,0,1,0,0,1),eA.bind(void 0,0,1,0,0,2),eA.bind(void 0,0,1,0,0,3),eA.bind(void 0,0,1,0,1,0),eA.bind(void 0,0,1,0,1,1),eA.bind(void 0,0,1,0,1,2),eA.bind(void 0,0,1,0,1,3),eA.bind(void 0,0,1,1,0,0),eA.bind(void 0,0,1,1,0,1),eA.bind(void 0,0,1,1,0,2),eA.bind(void 0,0,1,1,0,3),eA.bind(void 0,0,1,1,1,0),eA.bind(void 0,0,1,1,1,1),eA.bind(void 0,0,1,1,1,2),eA.bind(void 0,0,1,1,1,3),eA.bind(void 0,1,0,0,0,0),eA.bind(void 0,1,0,0,0,1),eA.bind(void 0,1,0,0,0,2),eA.bind(void 0,1,0,0,0,3),eA.bind(void 0,1,0,0,1,0),eA.bind(void 0,1,0,0,1,1),eA.bind(void 0,1,0,0,1,2),eA.bind(void 0,1,0,0,1,3),eA.bind(void 0,1,0,1,0,0),eA.bind(void 0,1,0,1,0,1),eA.bind(void 0,1,0,1,0,2),eA.bind(void 0,1,0,1,0,3),eA.bind(void 0,1,0,1,1,0),eA.bind(void 0,1,0,1,1,1),eA.bind(void 0,1,0,1,1,2),eA.bind(void 0,1,0,1,1,3),eA.bind(void 0,1,1,0,0,0),eA.bind(void 0,1,1,0,0,1),eA.bind(void 0,1,1,0,0,2),eA.bind(void 0,1,1,0,0,3),eA.bind(void 0,1,1,0,1,0),eA.bind(void 0,1,1,0,1,1),eA.bind(void 0,1,1,0,1,2),eA.bind(void 0,1,1,0,1,3),eA.bind(void 0,1,1,1,0,0),eA.bind(void 0,1,1,1,0,1),eA.bind(void 0,1,1,1,0,2),eA.bind(void 0,1,1,1,0,3),eA.bind(void 0,1,1,1,1,0),eA.bind(void 0,1,1,1,1,1),eA.bind(void 0,1,1,1,1,2),eA.bind(void 0,1,1,1,1,3)];function _6(A){this.char=A,this.state={},this.activeState=null}function J7(A,Q,E){this.contextName=E,this.startIndex=A,this.endOffset=Q}function t4(A,Q,E){this.contextName=A,this.openRange=null,this.ranges=[],this.checkStart=Q,this.checkEnd=E}function DB(A,Q){this.context=A,this.index=Q,this.length=A.length,this.current=A[Q],this.backtrack=A.slice(0,Q),this.lookahead=A.slice(Q+1)}function kU(A){this.eventId=A,this.subscribers=[]}function e4(A){var Q=this,E=["start","end","next","newToken","contextStart","contextEnd","insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD","updateContextsRanges"];if(E.forEach(function(I){Object.defineProperty(Q.events,I,{value:new kU(I)})}),A)E.forEach(function(I){var C=A[I];if(typeof C==="function")Q.events[I].subscribe(C)});var B=["insertToken","removeToken","removeRange","replaceToken","replaceRange","composeRUD"];B.forEach(function(I){Q.events[I].subscribe(Q.updateContextsRanges)})}function wQ(A){this.tokens=[],this.registeredContexts={},this.contextCheckers=[],this.events={},this.registeredModifiers=[],e4.call(this,A)}_6.prototype.setState=function(A,Q){return this.state[A]=Q,this.activeState={key:A,value:this.state[A]},this.activeState};_6.prototype.getState=function(A){return this.state[A]||null};wQ.prototype.inboundIndex=function(A){return A>=0&&A0&&A<=this.lookahead.length):return this.lookahead[A-1];default:return null}};wQ.prototype.rangeToText=function(A){if(A instanceof J7)return this.getRangeTokens(A).map(function(Q){return Q.char}).join("")};wQ.prototype.getText=function(){return this.tokens.map(function(A){return A.char}).join("")};wQ.prototype.getContext=function(A){var Q=this.registeredContexts[A];return Q?Q:null};wQ.prototype.on=function(A,Q){var E=this.events[A];if(E)return E.subscribe(Q);else return null};wQ.prototype.dispatch=function(A,Q){var E=this,B=this.events[A];if(B instanceof kU)B.subscribers.forEach(function(I){I.apply(E,Q||[])})};wQ.prototype.registerContextChecker=function(A,Q,E){if(this.getContext(A))return{FAIL:"context name '"+A+"' is already registered."};if(typeof Q!=="function")return{FAIL:"missing context start check."};if(typeof E!=="function")return{FAIL:"missing context end check."};var B=new t4(A,Q,E);return this.registeredContexts[A]=B,this.contextCheckers.push(B),B};wQ.prototype.getRangeTokens=function(A){var Q=A.startIndex+A.endOffset;return[].concat(this.tokens.slice(A.startIndex,Q))};wQ.prototype.getContextRanges=function(A){var Q=this.getContext(A);if(Q)return Q.ranges;else return{FAIL:"context checker '"+A+"' is not registered."}};wQ.prototype.resetContextsRanges=function(){var A=this.registeredContexts;for(var Q in A)if(A.hasOwnProperty(Q)){var E=A[Q];E.ranges=[]}};wQ.prototype.updateContextsRanges=function(){this.resetContextsRanges();var A=this.tokens.map(function(B){return B.char});for(var Q=0;Q=I.start&&A<=I.end){var C=A-I.start;return I.index+C}}break;default:return-1}return-1}function Qk(A,Q){var E=LK(A,Q.coverage);if(E===-1)return null;return A+Q.deltaGlyphId}function Ek(A,Q){var E=LK(A,Q.coverage);if(E===-1)return null;return Q.substitute[E]}function sH(A,Q){var E=[];for(var B=0;B=0;E--){var B=Q[E],I=GX(B),C=dI(B);if(!I&&!C)return!0;if(I)return!1}return!1}function Xk(A){if(GX(A.current))return!1;for(var Q=0;Q0)}E("fontFamily"),E("weightName"),E("manufacturer"),E("copyright"),E("version"),Q(this.unitsPerEm>0)};OQ.prototype.toTables=function(){return W2.fontToTable(this)};OQ.prototype.toBuffer=function(){return console.warn("Font.toBuffer is deprecated. Use Font.toArrayBuffer instead."),this.toArrayBuffer()};OQ.prototype.toArrayBuffer=function(){var A=this.toTables(),Q=A.encode(),E=new ArrayBuffer(Q.length),B=new Uint8Array(E);for(var I=0;I()=>(Q||(Q={exports:{}},A(Q.exports,Q)),Q.exports),WX=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.VERSION=void 0,A.VERSION="9.0.1"}),t0=P0((exports,module)=>{var __spreadArray=exports&&exports.__spreadArray||function(A,Q){for(var E=0,B=Q.length,I=A.length;E{(function(E,B){typeof define=="function"&&define.amd?define([],B):typeof Q=="object"&&Q.exports?Q.exports=B():E.regexpToAst=B()})(typeof self!="undefined"?self:A,function(){function E(){}E.prototype.saveState=function(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}},E.prototype.restoreState=function(W){this.idx=W.idx,this.input=W.input,this.groupIdx=W.groupIdx},E.prototype.pattern=function(W){this.idx=0,this.input=W,this.groupIdx=0,this.consumeChar("/");var Z=this.disjunction();this.consumeChar("/");for(var G={type:"Flags",loc:{begin:this.idx,end:W.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};this.isRegExpFlag();)switch(this.popChar()){case"g":U(G,"global");break;case"i":U(G,"ignoreCase");break;case"m":U(G,"multiLine");break;case"u":U(G,"unicode");break;case"y":U(G,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:G,value:Z,loc:this.loc(0)}},E.prototype.disjunction=function(){var W=[],Z=this.idx;for(W.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),W.push(this.alternative());return{type:"Disjunction",value:W,loc:this.loc(Z)}},E.prototype.alternative=function(){for(var W=[],Z=this.idx;this.isTerm();)W.push(this.term());return{type:"Alternative",value:W,loc:this.loc(Z)}},E.prototype.term=function(){return this.isAssertion()?this.assertion():this.atom()},E.prototype.assertion=function(){var W=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(W)};case"$":return{type:"EndAnchor",loc:this.loc(W)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(W)};case"B":return{type:"NonWordBoundary",loc:this.loc(W)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");var Z;switch(this.popChar()){case"=":Z="Lookahead";break;case"!":Z="NegativeLookahead";break}Y(Z);var G=this.disjunction();return this.consumeChar(")"),{type:Z,value:G,loc:this.loc(W)}}H()},E.prototype.quantifier=function(W){var Z,G=this.idx;switch(this.popChar()){case"*":Z={atLeast:0,atMost:1/0};break;case"+":Z={atLeast:1,atMost:1/0};break;case"?":Z={atLeast:0,atMost:1};break;case"{":var X=this.integerIncludingZero();switch(this.popChar()){case"}":Z={atLeast:X,atMost:X};break;case",":var q;this.isDigit()?(q=this.integerIncludingZero(),Z={atLeast:X,atMost:q}):Z={atLeast:X,atMost:1/0},this.consumeChar("}");break}if(W===!0&&Z===void 0)return;Y(Z);break}if(!(W===!0&&Z===void 0))return Y(Z),this.peekChar(0)==="?"?(this.consumeChar("?"),Z.greedy=!1):Z.greedy=!0,Z.type="Quantifier",Z.loc=this.loc(G),Z},E.prototype.atom=function(){var W,Z=this.idx;switch(this.peekChar()){case".":W=this.dotAll();break;case"\\":W=this.atomEscape();break;case"[":W=this.characterClass();break;case"(":W=this.group();break}return W===void 0&&this.isPatternCharacter()&&(W=this.patternCharacter()),Y(W),W.loc=this.loc(Z),this.isQuantifier()&&(W.quantifier=this.quantifier()),W},E.prototype.dotAll=function(){return this.consumeChar("."),{type:"Set",complement:!0,value:[K(` -`),K("\r"),K("\u2028"),K("\u2029")]}},E.prototype.atomEscape=function(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}},E.prototype.decimalEscapeAtom=function(){var W=this.positiveInteger();return{type:"GroupBackReference",value:W}},E.prototype.characterClassEscape=function(){var W,Z=!1;switch(this.popChar()){case"d":W=O;break;case"D":W=O,Z=!0;break;case"s":W=$;break;case"S":W=$,Z=!0;break;case"w":W=N;break;case"W":W=N,Z=!0;break}return Y(W),{type:"Set",value:W,complement:Z}},E.prototype.controlEscapeAtom=function(){var W;switch(this.popChar()){case"f":W=K("\f");break;case"n":W=K(` -`);break;case"r":W=K("\r");break;case"t":W=K("\t");break;case"v":W=K("\v");break}return Y(W),{type:"Character",value:W}},E.prototype.controlLetterEscapeAtom=function(){this.consumeChar("c");var W=this.popChar();if(/[a-zA-Z]/.test(W)===!1)throw Error("Invalid ");var Z=W.toUpperCase().charCodeAt(0)-64;return{type:"Character",value:Z}},E.prototype.nulCharacterAtom=function(){return this.consumeChar("0"),{type:"Character",value:K("\x00")}},E.prototype.hexEscapeSequenceAtom=function(){return this.consumeChar("x"),this.parseHexDigits(2)},E.prototype.regExpUnicodeEscapeSequenceAtom=function(){return this.consumeChar("u"),this.parseHexDigits(4)},E.prototype.identityEscapeAtom=function(){var W=this.popChar();return{type:"Character",value:K(W)}},E.prototype.classPatternCharacterAtom=function(){switch(this.peekChar()){case` -`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:var W=this.popChar();return{type:"Character",value:K(W)}}},E.prototype.characterClass=function(){var W=[],Z=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),Z=!0);this.isClassAtom();){var G=this.classAtom(),X=G.type==="Character";if(X&&this.isRangeDash()){this.consumeChar("-");var q=this.classAtom(),M=q.type==="Character";if(M){if(q.value=this.input.length)throw Error("Unexpected end of input");this.idx++},E.prototype.loc=function(W){return{begin:W,end:this.idx}};var B=/[0-9a-fA-F]/,I=/[0-9]/,C=/[1-9]/;function K(W){return W.charCodeAt(0)}function J(W,Z){W.length!==void 0?W.forEach(function(G){Z.push(G)}):Z.push(W)}function U(W,Z){if(W[Z]===!0)throw"duplicate flag "+Z;W[Z]=!0}function Y(W){if(W===void 0)throw Error("Internal Error - Should never get here!")}function H(){throw Error("Internal Error - Should never get here!")}var R,O=[];for(R=K("0");R<=K("9");R++)O.push(R);var N=[K("_")].concat(O);for(R=K("a");R<=K("z");R++)N.push(R);for(R=K("A");R<=K("Z");R++)N.push(R);var $=[K(" "),K("\f"),K(` -`),K("\r"),K("\t"),K("\v"),K("\t"),K(" "),K(" "),K(" "),K(" "),K(" "),K(" "),K(" "),K(" "),K(" "),K(" "),K(" "),K(" "),K(" "),K("\u2028"),K("\u2029"),K(" "),K(" "),K(" "),K("\uFEFF")];function L(){}return L.prototype.visitChildren=function(W){for(var Z in W){var G=W[Z];W.hasOwnProperty(Z)&&(G.type!==void 0?this.visit(G):Array.isArray(G)&&G.forEach(function(X){this.visit(X)},this))}},L.prototype.visit=function(W){switch(W.type){case"Pattern":this.visitPattern(W);break;case"Flags":this.visitFlags(W);break;case"Disjunction":this.visitDisjunction(W);break;case"Alternative":this.visitAlternative(W);break;case"StartAnchor":this.visitStartAnchor(W);break;case"EndAnchor":this.visitEndAnchor(W);break;case"WordBoundary":this.visitWordBoundary(W);break;case"NonWordBoundary":this.visitNonWordBoundary(W);break;case"Lookahead":this.visitLookahead(W);break;case"NegativeLookahead":this.visitNegativeLookahead(W);break;case"Character":this.visitCharacter(W);break;case"Set":this.visitSet(W);break;case"Group":this.visitGroup(W);break;case"GroupBackReference":this.visitGroupBackReference(W);break;case"Quantifier":this.visitQuantifier(W);break}this.visitChildren(W)},L.prototype.visitPattern=function(W){},L.prototype.visitFlags=function(W){},L.prototype.visitDisjunction=function(W){},L.prototype.visitAlternative=function(W){},L.prototype.visitStartAnchor=function(W){},L.prototype.visitEndAnchor=function(W){},L.prototype.visitWordBoundary=function(W){},L.prototype.visitNonWordBoundary=function(W){},L.prototype.visitLookahead=function(W){},L.prototype.visitNegativeLookahead=function(W){},L.prototype.visitCharacter=function(W){},L.prototype.visitSet=function(W){},L.prototype.visitGroup=function(W){},L.prototype.visitGroupBackReference=function(W){},L.prototype.visitQuantifier=function(W){},{RegExpParser:E,BaseRegExpVisitor:L,VERSION:"0.5.0"}})}),H7=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.clearRegExpParserCache=A.getRegExpAst=void 0;var Q=O7(),E={},B=new Q.RegExpParser;function I(K){var J=K.toString();if(E.hasOwnProperty(J))return E[J];var U=B.pattern(J);return E[J]=U,U}A.getRegExpAst=I;function C(){E={}}A.clearRegExpParserCache=C}),zk=P0((A)=>{var Q=A&&A.__extends||function(){var L=function(W,Z){return L=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(G,X){G.__proto__=X}||function(G,X){for(var q in X)Object.prototype.hasOwnProperty.call(X,q)&&(G[q]=X[q])},L(W,Z)};return function(W,Z){if(typeof Z!="function"&&Z!==null)throw new TypeError("Class extends value "+String(Z)+" is not a constructor or null");L(W,Z);function G(){this.constructor=W}W.prototype=Z===null?Object.create(Z):(G.prototype=Z.prototype,new G)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.canMatchCharCode=A.firstCharOptimizedIndices=A.getOptimizedStartCodesIndices=A.failedOptimizationPrefixMsg=void 0;var E=O7(),B=t0(),I=H7(),C=XX(),K="Complement Sets are not supported for first char optimization";A.failedOptimizationPrefixMsg=`Unable to use "first char" lexer optimizations: -`;function J(L,W){W===void 0&&(W=!1);try{var Z=I.getRegExpAst(L),G=U(Z.value,{},Z.flags.ignoreCase);return G}catch(q){if(q.message===K)W&&B.PRINT_WARNING(""+A.failedOptimizationPrefixMsg+("\tUnable to optimize: < "+L.toString()+` > -`)+` Complement Sets cannot be automatically optimized. - This will disable the lexer's first char optimizations. - See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{var X="";W&&(X=` - This will disable the lexer's first char optimizations. - See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),B.PRINT_ERROR(A.failedOptimizationPrefixMsg+` -`+("\tFailed parsing: < "+L.toString()+` > -`)+("\tUsing the regexp-to-ast library version: "+E.VERSION+` -`)+"\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues"+X)}}return[]}A.getOptimizedStartCodesIndices=J;function U(L,W,Z){switch(L.type){case"Disjunction":for(var G=0;G=C.minOptimizationVal)for(var T=w.from>=C.minOptimizationVal?w.from:C.minOptimizationVal,z=w.to,j=C.charCodeToOptimizedIndex(T),v=C.charCodeToOptimizedIndex(z),g=j;g<=v;g++)W[g]=g}}});break;case"Group":U(M.value,W,Z);break;default:throw Error("Non Exhaustive Match")}var F=M.quantifier!==void 0&&M.quantifier.atLeast===0;if(M.type==="Group"&&O(M)===!1||M.type!=="Group"&&F===!1)break}break;default:throw Error("non exhaustive match!")}return B.values(W)}A.firstCharOptimizedIndices=U;function Y(L,W,Z){var G=C.charCodeToOptimizedIndex(L);W[G]=G,Z===!0&&H(L,W)}function H(L,W){var Z=String.fromCharCode(L),G=Z.toUpperCase();if(G!==Z){var X=C.charCodeToOptimizedIndex(G.charCodeAt(0));W[X]=X}else{var q=Z.toLowerCase();if(q!==Z){var X=C.charCodeToOptimizedIndex(q.charCodeAt(0));W[X]=X}}}function R(L,W){return B.find(L.value,function(Z){if(typeof Z=="number")return B.contains(W,Z);var G=Z;return B.find(W,function(X){return G.from<=X&&X<=G.to})!==void 0})}function O(L){return L.quantifier&&L.quantifier.atLeast===0?!0:L.value?B.isArray(L.value)?B.every(L.value,O):O(L.value):!1}var N=function(L){Q(W,L);function W(Z){var G=L.call(this)||this;return G.targetCharCodes=Z,G.found=!1,G}return W.prototype.visitChildren=function(Z){if(this.found!==!0){switch(Z.type){case"Lookahead":this.visitLookahead(Z);return;case"NegativeLookahead":this.visitNegativeLookahead(Z);return}L.prototype.visitChildren.call(this,Z)}},W.prototype.visitCharacter=function(Z){B.contains(this.targetCharCodes,Z.value)&&(this.found=!0)},W.prototype.visitSet=function(Z){Z.complement?R(Z,this.targetCharCodes)===void 0&&(this.found=!0):R(Z,this.targetCharCodes)!==void 0&&(this.found=!0)},W}(E.BaseRegExpVisitor);function $(L,W){if(W instanceof RegExp){var Z=I.getRegExpAst(W),G=new N(L);return G.visit(Z),G.found}else return B.find(W,function(X){return B.contains(L,X.charCodeAt(0))})!==void 0}A.canMatchCharCode=$}),XX=P0((A)=>{var Q=A&&A.__extends||function(){var n=function(l,c){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(o,e){o.__proto__=e}||function(o,e){for(var BA in e)Object.prototype.hasOwnProperty.call(e,BA)&&(o[BA]=e[BA])},n(l,c)};return function(l,c){if(typeof c!="function"&&c!==null)throw new TypeError("Class extends value "+String(c)+" is not a constructor or null");n(l,c);function o(){this.constructor=l}l.prototype=c===null?Object.create(c):(o.prototype=c.prototype,new o)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.charCodeToOptimizedIndex=A.minOptimizationVal=A.buildLineBreakIssueMessage=A.LineTerminatorOptimizedTester=A.isShortPattern=A.isCustomPattern=A.cloneEmptyGroups=A.performWarningRuntimeChecks=A.performRuntimeChecks=A.addStickyFlag=A.addStartOfInput=A.findUnreachablePatterns=A.findModesThatDoNotExist=A.findInvalidGroupType=A.findDuplicatePatterns=A.findUnsupportedFlags=A.findStartOfInputAnchor=A.findEmptyMatchRegExps=A.findEndOfInputAnchor=A.findInvalidPatterns=A.findMissingPatterns=A.validatePatterns=A.analyzeTokenTypes=A.enableSticky=A.disableSticky=A.SUPPORT_STICKY=A.MODES=A.DEFAULT_MODE=void 0;var E=O7(),B=SU(),I=t0(),C=zk(),K=H7(),J="PATTERN";A.DEFAULT_MODE="defaultMode",A.MODES="modes",A.SUPPORT_STICKY=typeof new RegExp("(?:)").sticky=="boolean";function U(){A.SUPPORT_STICKY=!1}A.disableSticky=U;function Y(){A.SUPPORT_STICKY=!0}A.enableSticky=Y;function H(n,l){l=I.defaults(l,{useSticky:A.SUPPORT_STICKY,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` -`],tracer:function(QA,t){return t()}});var c=l.tracer;c("initCharCodeToOptimizedIndexMap",function(){i()});var o;c("Reject Lexer.NA",function(){o=I.reject(n,function(QA){return QA[J]===B.Lexer.NA})});var e=!1,BA;c("Transform Patterns",function(){e=!1,BA=I.map(o,function(QA){var t=QA[J];if(I.isRegExp(t)){var KA=t.source;return KA.length===1&&KA!=="^"&&KA!=="$"&&KA!=="."&&!t.ignoreCase?KA:KA.length===2&&KA[0]==="\\"&&!I.contains(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],KA[1])?KA[1]:l.useSticky?z(t):T(t)}else{if(I.isFunction(t))return e=!0,{exec:t};if(I.has(t,"exec"))return e=!0,t;if(typeof t=="string"){if(t.length===1)return t;var HA=t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),fA=new RegExp(HA);return l.useSticky?z(fA):T(fA)}else throw Error("non exhaustive match")}})});var EA,CA,f,NA,YA;c("misc mapping",function(){EA=I.map(o,function(QA){return QA.tokenTypeIdx}),CA=I.map(o,function(QA){var t=QA.GROUP;if(t!==B.Lexer.SKIPPED){if(I.isString(t))return t;if(I.isUndefined(t))return!1;throw Error("non exhaustive match")}}),f=I.map(o,function(QA){var t=QA.LONGER_ALT;if(t){var KA=I.indexOf(o,t);return KA}}),NA=I.map(o,function(QA){return QA.PUSH_MODE}),YA=I.map(o,function(QA){return I.has(QA,"POP_MODE")})});var FA;c("Line Terminator Handling",function(){var QA=x(l.lineTerminatorCharacters);FA=I.map(o,function(t){return!1}),l.positionTracking!=="onlyOffset"&&(FA=I.map(o,function(t){if(I.has(t,"LINE_BREAKS"))return t.LINE_BREAKS;if(S(t,QA)===!1)return C.canMatchCharCode(QA,t.PATTERN)}))});var ZA,jA,wA,VA;c("Misc Mapping #2",function(){ZA=I.map(o,P),jA=I.map(BA,V),wA=I.reduce(o,function(QA,t){var KA=t.GROUP;return I.isString(KA)&&KA!==B.Lexer.SKIPPED&&(QA[KA]=[]),QA},{}),VA=I.map(BA,function(QA,t){return{pattern:BA[t],longerAlt:f[t],canLineTerminator:FA[t],isCustom:ZA[t],short:jA[t],group:CA[t],push:NA[t],pop:YA[t],tokenTypeIdx:EA[t],tokenType:o[t]}})});var d=!0,u=[];return l.safeMode||c("First Char Optimization",function(){u=I.reduce(o,function(QA,t,KA){if(typeof t.PATTERN=="string"){var HA=t.PATTERN.charCodeAt(0),fA=s(HA);b(QA,fA,VA[KA])}else if(I.isArray(t.START_CHARS_HINT)){var zA;I.forEach(t.START_CHARS_HINT,function(qA){var LA=typeof qA=="string"?qA.charCodeAt(0):qA,_A=s(LA);zA!==_A&&(zA=_A,b(QA,_A,VA[KA]))})}else if(I.isRegExp(t.PATTERN))if(t.PATTERN.unicode)d=!1,l.ensureOptimizations&&I.PRINT_ERROR(""+C.failedOptimizationPrefixMsg+("\tUnable to analyze < "+t.PATTERN.toString()+` > pattern. -`)+` The regexp unicode flag is not currently supported by the regexp-to-ast library. - This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{var yA=C.getOptimizedStartCodesIndices(t.PATTERN,l.ensureOptimizations);I.isEmpty(yA)&&(d=!1),I.forEach(yA,function(qA){b(QA,qA,VA[KA])})}else l.ensureOptimizations&&I.PRINT_ERROR(""+C.failedOptimizationPrefixMsg+("\tTokenType: <"+t.name+`> is using a custom token pattern without providing parameter. -`)+` This will disable the lexer's first char optimizations. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),d=!1;return QA},[])}),c("ArrayPacking",function(){u=I.packArray(u)}),{emptyGroups:wA,patternIdxToConfig:VA,charCodeToPatternIdxToConfig:u,hasCustom:e,canBeOptimized:d}}A.analyzeTokenTypes=H;function R(n,l){var c=[],o=N(n);c=c.concat(o.errors);var e=$(o.valid),BA=e.valid;return c=c.concat(e.errors),c=c.concat(O(BA)),c=c.concat(F(BA)),c=c.concat(D(BA,l)),c=c.concat(_(BA)),c}A.validatePatterns=R;function O(n){var l=[],c=I.filter(n,function(o){return I.isRegExp(o[J])});return l=l.concat(W(c)),l=l.concat(X(c)),l=l.concat(q(c)),l=l.concat(M(c)),l=l.concat(Z(c)),l}function N(n){var l=I.filter(n,function(e){return!I.has(e,J)}),c=I.map(l,function(e){return{message:"Token Type: ->"+e.name+"<- missing static 'PATTERN' property",type:B.LexerDefinitionErrorType.MISSING_PATTERN,tokenTypes:[e]}}),o=I.difference(n,l);return{errors:c,valid:o}}A.findMissingPatterns=N;function $(n){var l=I.filter(n,function(e){var BA=e[J];return!I.isRegExp(BA)&&!I.isFunction(BA)&&!I.has(BA,"exec")&&!I.isString(BA)}),c=I.map(l,function(e){return{message:"Token Type: ->"+e.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:B.LexerDefinitionErrorType.INVALID_PATTERN,tokenTypes:[e]}}),o=I.difference(n,l);return{errors:c,valid:o}}A.findInvalidPatterns=$;var L=/[^\\][\$]/;function W(n){var l=function(e){Q(BA,e);function BA(){var EA=e!==null&&e.apply(this,arguments)||this;return EA.found=!1,EA}return BA.prototype.visitEndAnchor=function(EA){this.found=!0},BA}(E.BaseRegExpVisitor),c=I.filter(n,function(e){var BA=e[J];try{var EA=K.getRegExpAst(BA),CA=new l;return CA.visit(EA),CA.found}catch(f){return L.test(BA.source)}}),o=I.map(c,function(e){return{message:`Unexpected RegExp Anchor Error: - Token Type: ->`+e.name+`<- static 'PATTERN' cannot contain end of input anchor '$' - See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:B.LexerDefinitionErrorType.EOI_ANCHOR_FOUND,tokenTypes:[e]}});return o}A.findEndOfInputAnchor=W;function Z(n){var l=I.filter(n,function(o){var e=o[J];return e.test("")}),c=I.map(l,function(o){return{message:"Token Type: ->"+o.name+"<- static 'PATTERN' must not match an empty string",type:B.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,tokenTypes:[o]}});return c}A.findEmptyMatchRegExps=Z;var G=/[^\\[][\^]|^\^/;function X(n){var l=function(e){Q(BA,e);function BA(){var EA=e!==null&&e.apply(this,arguments)||this;return EA.found=!1,EA}return BA.prototype.visitStartAnchor=function(EA){this.found=!0},BA}(E.BaseRegExpVisitor),c=I.filter(n,function(e){var BA=e[J];try{var EA=K.getRegExpAst(BA),CA=new l;return CA.visit(EA),CA.found}catch(f){return G.test(BA.source)}}),o=I.map(c,function(e){return{message:`Unexpected RegExp Anchor Error: - Token Type: ->`+e.name+`<- static 'PATTERN' cannot contain start of input anchor '^' - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:B.LexerDefinitionErrorType.SOI_ANCHOR_FOUND,tokenTypes:[e]}});return o}A.findStartOfInputAnchor=X;function q(n){var l=I.filter(n,function(o){var e=o[J];return e instanceof RegExp&&(e.multiline||e.global)}),c=I.map(l,function(o){return{message:"Token Type: ->"+o.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:B.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[o]}});return c}A.findUnsupportedFlags=q;function M(n){var l=[],c=I.map(n,function(BA){return I.reduce(n,function(EA,CA){return BA.PATTERN.source===CA.PATTERN.source&&!I.contains(l,CA)&&CA.PATTERN!==B.Lexer.NA&&(l.push(CA),EA.push(CA)),EA},[])});c=I.compact(c);var o=I.filter(c,function(BA){return BA.length>1}),e=I.map(o,function(BA){var EA=I.map(BA,function(f){return f.name}),CA=I.first(BA).PATTERN;return{message:"The same RegExp pattern ->"+CA+"<-"+("has been used in all of the following Token Types: "+EA.join(", ")+" <-"),type:B.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,tokenTypes:BA}});return e}A.findDuplicatePatterns=M;function F(n){var l=I.filter(n,function(o){if(!I.has(o,"GROUP"))return!1;var e=o.GROUP;return e!==B.Lexer.SKIPPED&&e!==B.Lexer.NA&&!I.isString(e)}),c=I.map(l,function(o){return{message:"Token Type: ->"+o.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:B.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,tokenTypes:[o]}});return c}A.findInvalidGroupType=F;function D(n,l){var c=I.filter(n,function(e){return e.PUSH_MODE!==void 0&&!I.contains(l,e.PUSH_MODE)}),o=I.map(c,function(e){var BA="Token Type: ->"+e.name+"<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->"+e.PUSH_MODE+"<-which does not exist";return{message:BA,type:B.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[e]}});return o}A.findModesThatDoNotExist=D;function _(n){var l=[],c=I.reduce(n,function(o,e,BA){var EA=e.PATTERN;return EA===B.Lexer.NA||(I.isString(EA)?o.push({str:EA,idx:BA,tokenType:e}):I.isRegExp(EA)&&k(EA)&&o.push({str:EA.source,idx:BA,tokenType:e})),o},[]);return I.forEach(n,function(o,e){I.forEach(c,function(BA){var{str:EA,idx:CA,tokenType:f}=BA;if(e"+o.name+"<-")+`in the lexer's definition. -See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;l.push({message:NA,type:B.LexerDefinitionErrorType.UNREACHABLE_PATTERN,tokenTypes:[o,f]})}})}),l}A.findUnreachablePatterns=_;function w(n,l){if(I.isRegExp(l)){var c=l.exec(n);return c!==null&&c.index===0}else{if(I.isFunction(l))return l(n,0,[],{});if(I.has(l,"exec"))return l.exec(n,0,[],{});if(typeof l=="string")return l===n;throw Error("non exhaustive match")}}function k(n){var l=[".","\\","[","]","|","^","$","(",")","?","*","+","{"];return I.find(l,function(c){return n.source.indexOf(c)!==-1})===void 0}function T(n){var l=n.ignoreCase?"i":"";return new RegExp("^(?:"+n.source+")",l)}A.addStartOfInput=T;function z(n){var l=n.ignoreCase?"iy":"y";return new RegExp(""+n.source,l)}A.addStickyFlag=z;function j(n,l,c){var o=[];return I.has(n,A.DEFAULT_MODE)||o.push({message:"A MultiMode Lexer cannot be initialized without a <"+A.DEFAULT_MODE+`> property in its definition -`,type:B.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),I.has(n,A.MODES)||o.push({message:"A MultiMode Lexer cannot be initialized without a <"+A.MODES+`> property in its definition -`,type:B.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),I.has(n,A.MODES)&&I.has(n,A.DEFAULT_MODE)&&!I.has(n.modes,n.defaultMode)&&o.push({message:"A MultiMode Lexer cannot be initialized with a "+A.DEFAULT_MODE+": <"+n.defaultMode+`>which does not exist -`,type:B.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),I.has(n,A.MODES)&&I.forEach(n.modes,function(e,BA){I.forEach(e,function(EA,CA){I.isUndefined(EA)&&o.push({message:"A Lexer cannot be initialized using an undefined Token Type. Mode:"+("<"+BA+"> at index: <"+CA+`> -`),type:B.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED})})}),o}A.performRuntimeChecks=j;function v(n,l,c){var o=[],e=!1,BA=I.compact(I.flatten(I.mapValues(n.modes,function(f){return f}))),EA=I.reject(BA,function(f){return f[J]===B.Lexer.NA}),CA=x(c);return l&&I.forEach(EA,function(f){var NA=S(f,CA);if(NA!==!1){var YA=h(f,NA),FA={message:YA,type:NA.issue,tokenType:f};o.push(FA)}else I.has(f,"LINE_BREAKS")?f.LINE_BREAKS===!0&&(e=!0):C.canMatchCharCode(CA,f.PATTERN)&&(e=!0)}),l&&!e&&o.push({message:`Warning: No LINE_BREAKS Found. - This Lexer has been defined to track line and column information, - But none of the Token Types can be identified as matching a line terminator. - See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS - for details.`,type:B.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS}),o}A.performWarningRuntimeChecks=v;function g(n){var l={},c=I.keys(n);return I.forEach(c,function(o){var e=n[o];if(I.isArray(e))l[o]=[];else throw Error("non exhaustive match")}),l}A.cloneEmptyGroups=g;function P(n){var l=n.PATTERN;if(I.isRegExp(l))return!1;if(I.isFunction(l))return!0;if(I.has(l,"exec"))return!0;if(I.isString(l))return!1;throw Error("non exhaustive match")}A.isCustomPattern=P;function V(n){return I.isString(n)&&n.length===1?n.charCodeAt(0):!1}A.isShortPattern=V,A.LineTerminatorOptimizedTester={test:function(n){for(var l=n.length,c=this.lastIndex;c Token Type -`)+("\t Root cause: "+l.errMsg+`. -`)+"\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR";if(l.issue===B.LexerDefinitionErrorType.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. -`+("\tThe problem is in the <"+n.name+`> Token Type -`)+"\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK";throw Error("non exhaustive match")}A.buildLineBreakIssueMessage=h;function x(n){var l=I.map(n,function(c){return I.isString(c)&&c.length>0?c.charCodeAt(0):c});return l}function b(n,l,c){n[l]===void 0?n[l]=[c]:n[l].push(c)}A.minOptimizationVal=256;var m=[];function s(n){return n255?255+~~(n/255):n}}}),qK=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.isTokenType=A.hasExtendingTokensTypesMapProperty=A.hasExtendingTokensTypesProperty=A.hasCategoriesProperty=A.hasShortKeyProperty=A.singleAssignCategoriesToksMap=A.assignCategoriesMapProp=A.assignCategoriesTokensProp=A.assignTokenDefaultProps=A.expandCategories=A.augmentTokenTypes=A.tokenIdxToClass=A.tokenShortNameIdx=A.tokenStructuredMatcherNoCategories=A.tokenStructuredMatcher=void 0;var Q=t0();function E(L,W){var Z=L.tokenTypeIdx;return Z===W.tokenTypeIdx?!0:W.isParent===!0&&W.categoryMatchesMap[Z]===!0}A.tokenStructuredMatcher=E;function B(L,W){return L.tokenTypeIdx===W.tokenTypeIdx}A.tokenStructuredMatcherNoCategories=B,A.tokenShortNameIdx=1,A.tokenIdxToClass={};function I(L){var W=C(L);K(W),U(W),J(W),Q.forEach(W,function(Z){Z.isParent=Z.categoryMatches.length>0})}A.augmentTokenTypes=I;function C(L){for(var W=Q.cloneArr(L),Z=L,G=!0;G;){Z=Q.compact(Q.flatten(Q.map(Z,function(q){return q.CATEGORIES})));var X=Q.difference(Z,W);W=W.concat(X),Q.isEmpty(X)?G=!1:Z=X}return W}A.expandCategories=C;function K(L){Q.forEach(L,function(W){H(W)||(A.tokenIdxToClass[A.tokenShortNameIdx]=W,W.tokenTypeIdx=A.tokenShortNameIdx++),R(W)&&!Q.isArray(W.CATEGORIES)&&(W.CATEGORIES=[W.CATEGORIES]),R(W)||(W.CATEGORIES=[]),O(W)||(W.categoryMatches=[]),N(W)||(W.categoryMatchesMap={})})}A.assignTokenDefaultProps=K;function J(L){Q.forEach(L,function(W){W.categoryMatches=[],Q.forEach(W.categoryMatchesMap,function(Z,G){W.categoryMatches.push(A.tokenIdxToClass[G].tokenTypeIdx)})})}A.assignCategoriesTokensProp=J;function U(L){Q.forEach(L,function(W){Y([],W)})}A.assignCategoriesMapProp=U;function Y(L,W){Q.forEach(L,function(Z){W.categoryMatchesMap[Z.tokenTypeIdx]=!0}),Q.forEach(W.CATEGORIES,function(Z){var G=L.concat(W);Q.contains(G,Z)||Y(G,Z)})}A.singleAssignCategoriesToksMap=Y;function H(L){return Q.has(L,"tokenTypeIdx")}A.hasShortKeyProperty=H;function R(L){return Q.has(L,"CATEGORIES")}A.hasCategoriesProperty=R;function O(L){return Q.has(L,"categoryMatches")}A.hasExtendingTokensTypesProperty=O;function N(L){return Q.has(L,"categoryMatchesMap")}A.hasExtendingTokensTypesMapProperty=N;function $(L){return Q.has(L,"tokenTypeIdx")}A.isTokenType=$}),$X=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.defaultLexerErrorProvider=void 0,A.defaultLexerErrorProvider={buildUnableToPopLexerModeMessage:function(Q){return"Unable to pop Lexer Mode after encountering Token ->"+Q.image+"<- The Mode Stack is empty"},buildUnexpectedCharactersMessage:function(Q,E,B,I,C){return"unexpected character: ->"+Q.charAt(E)+"<- at offset: "+E+","+(" skipped "+B+" characters.")}}}),SU=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.Lexer=A.LexerDefinitionErrorType=void 0;var Q=XX(),E=t0(),B=qK(),I=$X(),C=H7(),K;(function(Y){Y[Y.MISSING_PATTERN=0]="MISSING_PATTERN",Y[Y.INVALID_PATTERN=1]="INVALID_PATTERN",Y[Y.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",Y[Y.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",Y[Y.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",Y[Y.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",Y[Y.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",Y[Y.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",Y[Y.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",Y[Y.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",Y[Y.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",Y[Y.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",Y[Y.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",Y[Y.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",Y[Y.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",Y[Y.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",Y[Y.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK"})(K=A.LexerDefinitionErrorType||(A.LexerDefinitionErrorType={}));var J={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` -`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:I.defaultLexerErrorProvider,traceInitPerf:!1,skipValidations:!1};Object.freeze(J);var U=function(){function Y(H,R){var O=this;if(R===void 0&&(R=J),this.lexerDefinition=H,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.config=void 0,this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},typeof R=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. -a boolean 2nd argument is no longer supported`);this.config=E.merge(J,R);var N=this.config.traceInitPerf;N===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof N=="number"&&(this.traceInitMaxIdent=N,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",function(){var $,L=!0;O.TRACE_INIT("Lexer Config handling",function(){if(O.config.lineTerminatorsPattern===J.lineTerminatorsPattern)O.config.lineTerminatorsPattern=Q.LineTerminatorOptimizedTester;else if(O.config.lineTerminatorCharacters===J.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. - For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(R.safeMode&&R.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');O.trackStartLines=/full|onlyStart/i.test(O.config.positionTracking),O.trackEndLines=/full/i.test(O.config.positionTracking),E.isArray(H)?($={modes:{}},$.modes[Q.DEFAULT_MODE]=E.cloneArr(H),$[Q.DEFAULT_MODE]=Q.DEFAULT_MODE):(L=!1,$=E.cloneObj(H))}),O.config.skipValidations===!1&&(O.TRACE_INIT("performRuntimeChecks",function(){O.lexerDefinitionErrors=O.lexerDefinitionErrors.concat(Q.performRuntimeChecks($,O.trackStartLines,O.config.lineTerminatorCharacters))}),O.TRACE_INIT("performWarningRuntimeChecks",function(){O.lexerDefinitionWarning=O.lexerDefinitionWarning.concat(Q.performWarningRuntimeChecks($,O.trackStartLines,O.config.lineTerminatorCharacters))})),$.modes=$.modes?$.modes:{},E.forEach($.modes,function(X,q){$.modes[q]=E.reject(X,function(M){return E.isUndefined(M)})});var W=E.keys($.modes);if(E.forEach($.modes,function(X,q){O.TRACE_INIT("Mode: <"+q+"> processing",function(){if(O.modes.push(q),O.config.skipValidations===!1&&O.TRACE_INIT("validatePatterns",function(){O.lexerDefinitionErrors=O.lexerDefinitionErrors.concat(Q.validatePatterns(X,W))}),E.isEmpty(O.lexerDefinitionErrors)){B.augmentTokenTypes(X);var M;O.TRACE_INIT("analyzeTokenTypes",function(){M=Q.analyzeTokenTypes(X,{lineTerminatorCharacters:O.config.lineTerminatorCharacters,positionTracking:R.positionTracking,ensureOptimizations:R.ensureOptimizations,safeMode:R.safeMode,tracer:O.TRACE_INIT.bind(O)})}),O.patternIdxToConfig[q]=M.patternIdxToConfig,O.charCodeToPatternIdxToConfig[q]=M.charCodeToPatternIdxToConfig,O.emptyGroups=E.merge(O.emptyGroups,M.emptyGroups),O.hasCustom=M.hasCustom||O.hasCustom,O.canModeBeOptimized[q]=M.canBeOptimized}})}),O.defaultMode=$.defaultMode,!E.isEmpty(O.lexerDefinitionErrors)&&!O.config.deferDefinitionErrorsHandling){var Z=E.map(O.lexerDefinitionErrors,function(X){return X.message}),G=Z.join(`----------------------- -`);throw new Error(`Errors detected in definition of Lexer: -`+G)}E.forEach(O.lexerDefinitionWarning,function(X){E.PRINT_WARNING(X.message)}),O.TRACE_INIT("Choosing sub-methods implementations",function(){if(Q.SUPPORT_STICKY?(O.chopInput=E.IDENTITY,O.match=O.matchWithTest):(O.updateLastIndex=E.NOOP,O.match=O.matchWithExec),L&&(O.handleModes=E.NOOP),O.trackStartLines===!1&&(O.computeNewColumn=E.IDENTITY),O.trackEndLines===!1&&(O.updateTokenEndLineColumnLocation=E.NOOP),/full/i.test(O.config.positionTracking))O.createTokenInstance=O.createFullToken;else if(/onlyStart/i.test(O.config.positionTracking))O.createTokenInstance=O.createStartOnlyToken;else if(/onlyOffset/i.test(O.config.positionTracking))O.createTokenInstance=O.createOffsetOnlyToken;else throw Error('Invalid config option: "'+O.config.positionTracking+'"');O.hasCustom?(O.addToken=O.addTokenUsingPush,O.handlePayload=O.handlePayloadWithCustom):(O.addToken=O.addTokenUsingMemberAccess,O.handlePayload=O.handlePayloadNoCustom)}),O.TRACE_INIT("Failed Optimization Warnings",function(){var X=E.reduce(O.canModeBeOptimized,function(q,M,F){return M===!1&&q.push(F),q},[]);if(R.ensureOptimizations&&!E.isEmpty(X))throw Error("Lexer Modes: < "+X.join(", ")+` > cannot be optimized. - Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. - Or inspect the console log for details on how to resolve these issues.`)}),O.TRACE_INIT("clearRegExpParserCache",function(){C.clearRegExpParserCache()}),O.TRACE_INIT("toFastProperties",function(){E.toFastProperties(O)})})}return Y.prototype.tokenize=function(H,R){if(R===void 0&&(R=this.defaultMode),!E.isEmpty(this.lexerDefinitionErrors)){var O=E.map(this.lexerDefinitionErrors,function(L){return L.message}),N=O.join(`----------------------- -`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: -`+N)}var $=this.tokenizeInternal(H,R);return $},Y.prototype.tokenizeInternal=function(H,R){var O=this,N,$,L,W,Z,G,X,q,M,F,D,_,w,k,T,z=H,j=z.length,v=0,g=0,P=this.hasCustom?0:Math.floor(H.length/10),V=new Array(P),S=[],h=this.trackStartLines?1:void 0,x=this.trackStartLines?1:void 0,b=Q.cloneEmptyGroups(this.emptyGroups),m=this.trackStartLines,s=this.config.lineTerminatorsPattern,i=0,n=[],l=[],c=[],o=[];Object.freeze(o);var e=void 0;function BA(){return n}function EA(qA){var LA=Q.charCodeToOptimizedIndex(qA),_A=l[LA];return _A===void 0?o:_A}var CA=function(qA){if(c.length===1&&qA.tokenType.PUSH_MODE===void 0){var LA=O.config.errorMessageProvider.buildUnableToPopLexerModeMessage(qA);S.push({offset:qA.startOffset,line:qA.startLine!==void 0?qA.startLine:void 0,column:qA.startColumn!==void 0?qA.startColumn:void 0,length:qA.image.length,message:LA})}else{c.pop();var _A=E.last(c);n=O.patternIdxToConfig[_A],l=O.charCodeToPatternIdxToConfig[_A],i=n.length;var B0=O.canModeBeOptimized[_A]&&O.config.safeMode===!1;l&&B0?e=EA:e=BA}};function f(qA){c.push(qA),l=this.charCodeToPatternIdxToConfig[qA],n=this.patternIdxToConfig[qA],i=n.length,i=n.length;var LA=this.canModeBeOptimized[qA]&&this.config.safeMode===!1;l&&LA?e=EA:e=BA}f.call(this,R);for(var NA;vZ.length&&(Z=L,G=X,NA=VA)}break}}if(Z!==null){if(q=Z.length,M=NA.group,M!==void 0&&(F=NA.tokenTypeIdx,D=this.createTokenInstance(Z,v,F,NA.tokenType,h,x,q),this.handlePayload(D,G),M===!1?g=this.addToken(V,g,D):b[M].push(D)),H=this.chopInput(H,q),v=v+q,x=this.computeNewColumn(x,q),m===!0&&NA.canLineTerminator===!0){var u=0,QA=void 0,t=void 0;s.lastIndex=0;do QA=s.test(Z),QA===!0&&(t=s.lastIndex-1,u++);while(QA===!0);u!==0&&(h=h+u,x=q-t,this.updateTokenEndLineColumnLocation(D,M,t,u,h,x,q))}this.handleModes(NA,CA,f,D)}else{for(var KA=v,HA=h,fA=x,zA=!1;!zA&&v <"+H+">");var N=E.timer(R),$=N.time,L=N.value,W=$>10?console.warn:console.log;return this.traceInitIndent time: "+$+"ms"),this.traceInitIndent--,L}else return R()},Y.SKIPPED="This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.",Y.NA=/NOT_APPLICABLE/,Y}();A.Lexer=U}),i1=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.tokenMatcher=A.createTokenInstance=A.EOF=A.createToken=A.hasTokenLabel=A.tokenName=A.tokenLabel=void 0;var Q=t0(),E=SU(),B=qK();function I(q){return K(q)?q.LABEL:q.name}A.tokenLabel=I;function C(q){return q.name}A.tokenName=C;function K(q){return Q.isString(q.LABEL)&&q.LABEL!==""}A.hasTokenLabel=K;var J="parent",U="categories",Y="label",H="group",R="push_mode",O="pop_mode",N="longer_alt",$="line_breaks",L="start_chars_hint";function W(q){return Z(q)}A.createToken=W;function Z(q){var M=q.pattern,F={};if(F.name=q.name,Q.isUndefined(M)||(F.PATTERN=M),Q.has(q,J))throw`The parent property is no longer supported. -See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.`;return Q.has(q,U)&&(F.CATEGORIES=q[U]),B.augmentTokenTypes([F]),Q.has(q,Y)&&(F.LABEL=q[Y]),Q.has(q,H)&&(F.GROUP=q[H]),Q.has(q,O)&&(F.POP_MODE=q[O]),Q.has(q,R)&&(F.PUSH_MODE=q[R]),Q.has(q,N)&&(F.LONGER_ALT=q[N]),Q.has(q,$)&&(F.LINE_BREAKS=q[$]),Q.has(q,L)&&(F.START_CHARS_HINT=q[L]),F}A.EOF=W({name:"EOF",pattern:E.Lexer.NA}),B.augmentTokenTypes([A.EOF]);function G(q,M,F,D,_,w,k,T){return{image:M,startOffset:F,endOffset:D,startLine:_,endLine:w,startColumn:k,endColumn:T,tokenTypeIdx:q.tokenTypeIdx,tokenType:q}}A.createTokenInstance=G;function X(q,M){return B.tokenStructuredMatcher(q,M)}A.tokenMatcher=X}),mE=P0((A)=>{var Q=A&&A.__extends||function(){var Z=function(G,X){return Z=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(q,M){q.__proto__=M}||function(q,M){for(var F in M)Object.prototype.hasOwnProperty.call(M,F)&&(q[F]=M[F])},Z(G,X)};return function(G,X){if(typeof X!="function"&&X!==null)throw new TypeError("Class extends value "+String(X)+" is not a constructor or null");Z(G,X);function q(){this.constructor=G}G.prototype=X===null?Object.create(X):(q.prototype=X.prototype,new q)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.serializeProduction=A.serializeGrammar=A.Terminal=A.Alternation=A.RepetitionWithSeparator=A.Repetition=A.RepetitionMandatoryWithSeparator=A.RepetitionMandatory=A.Option=A.Alternative=A.Rule=A.NonTerminal=A.AbstractProduction=void 0;var E=t0(),B=i1(),I=function(){function Z(G){this._definition=G}return Object.defineProperty(Z.prototype,"definition",{get:function(){return this._definition},set:function(G){this._definition=G},enumerable:!1,configurable:!0}),Z.prototype.accept=function(G){G.visit(this),E.forEach(this.definition,function(X){X.accept(G)})},Z}();A.AbstractProduction=I;var C=function(Z){Q(G,Z);function G(X){var q=Z.call(this,[])||this;return q.idx=1,E.assign(q,E.pick(X,function(M){return M!==void 0})),q}return Object.defineProperty(G.prototype,"definition",{get:function(){return this.referencedRule!==void 0?this.referencedRule.definition:[]},set:function(X){},enumerable:!1,configurable:!0}),G.prototype.accept=function(X){X.visit(this)},G}(I);A.NonTerminal=C;var K=function(Z){Q(G,Z);function G(X){var q=Z.call(this,X.definition)||this;return q.orgText="",E.assign(q,E.pick(X,function(M){return M!==void 0})),q}return G}(I);A.Rule=K;var J=function(Z){Q(G,Z);function G(X){var q=Z.call(this,X.definition)||this;return q.ignoreAmbiguities=!1,E.assign(q,E.pick(X,function(M){return M!==void 0})),q}return G}(I);A.Alternative=J;var U=function(Z){Q(G,Z);function G(X){var q=Z.call(this,X.definition)||this;return q.idx=1,E.assign(q,E.pick(X,function(M){return M!==void 0})),q}return G}(I);A.Option=U;var Y=function(Z){Q(G,Z);function G(X){var q=Z.call(this,X.definition)||this;return q.idx=1,E.assign(q,E.pick(X,function(M){return M!==void 0})),q}return G}(I);A.RepetitionMandatory=Y;var H=function(Z){Q(G,Z);function G(X){var q=Z.call(this,X.definition)||this;return q.idx=1,E.assign(q,E.pick(X,function(M){return M!==void 0})),q}return G}(I);A.RepetitionMandatoryWithSeparator=H;var R=function(Z){Q(G,Z);function G(X){var q=Z.call(this,X.definition)||this;return q.idx=1,E.assign(q,E.pick(X,function(M){return M!==void 0})),q}return G}(I);A.Repetition=R;var O=function(Z){Q(G,Z);function G(X){var q=Z.call(this,X.definition)||this;return q.idx=1,E.assign(q,E.pick(X,function(M){return M!==void 0})),q}return G}(I);A.RepetitionWithSeparator=O;var N=function(Z){Q(G,Z);function G(X){var q=Z.call(this,X.definition)||this;return q.idx=1,q.ignoreAmbiguities=!1,q.hasPredicates=!1,E.assign(q,E.pick(X,function(M){return M!==void 0})),q}return Object.defineProperty(G.prototype,"definition",{get:function(){return this._definition},set:function(X){this._definition=X},enumerable:!1,configurable:!0}),G}(I);A.Alternation=N;var $=function(){function Z(G){this.idx=1,E.assign(this,E.pick(G,function(X){return X!==void 0}))}return Z.prototype.accept=function(G){G.visit(this)},Z}();A.Terminal=$;function L(Z){return E.map(Z,W)}A.serializeGrammar=L;function W(Z){function G(M){return E.map(M,W)}if(Z instanceof C)return{type:"NonTerminal",name:Z.nonTerminalName,idx:Z.idx};if(Z instanceof J)return{type:"Alternative",definition:G(Z.definition)};if(Z instanceof U)return{type:"Option",idx:Z.idx,definition:G(Z.definition)};if(Z instanceof Y)return{type:"RepetitionMandatory",idx:Z.idx,definition:G(Z.definition)};if(Z instanceof H)return{type:"RepetitionMandatoryWithSeparator",idx:Z.idx,separator:W(new $({terminalType:Z.separator})),definition:G(Z.definition)};if(Z instanceof O)return{type:"RepetitionWithSeparator",idx:Z.idx,separator:W(new $({terminalType:Z.separator})),definition:G(Z.definition)};if(Z instanceof R)return{type:"Repetition",idx:Z.idx,definition:G(Z.definition)};if(Z instanceof N)return{type:"Alternation",idx:Z.idx,definition:G(Z.definition)};if(Z instanceof $){var X={type:"Terminal",name:Z.terminalType.name,label:B.tokenLabel(Z.terminalType),idx:Z.idx},q=Z.terminalType.PATTERN;return Z.terminalType.PATTERN&&(X.pattern=E.isRegExp(q)?q.source:q),X}else{if(Z instanceof K)return{type:"Rule",name:Z.name,orgText:Z.orgText,definition:G(Z.definition)};throw Error("non exhaustive match")}}A.serializeProduction=W}),Z7=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.RestWalker=void 0;var Q=t0(),E=mE(),B=function(){function C(){}return C.prototype.walk=function(K,J){var U=this;J===void 0&&(J=[]),Q.forEach(K.definition,function(Y,H){var R=Q.drop(K.definition,H+1);if(Y instanceof E.NonTerminal)U.walkProdRef(Y,R,J);else if(Y instanceof E.Terminal)U.walkTerminal(Y,R,J);else if(Y instanceof E.Alternative)U.walkFlat(Y,R,J);else if(Y instanceof E.Option)U.walkOption(Y,R,J);else if(Y instanceof E.RepetitionMandatory)U.walkAtLeastOne(Y,R,J);else if(Y instanceof E.RepetitionMandatoryWithSeparator)U.walkAtLeastOneSep(Y,R,J);else if(Y instanceof E.RepetitionWithSeparator)U.walkManySep(Y,R,J);else if(Y instanceof E.Repetition)U.walkMany(Y,R,J);else if(Y instanceof E.Alternation)U.walkOr(Y,R,J);else throw Error("non exhaustive match")})},C.prototype.walkTerminal=function(K,J,U){},C.prototype.walkProdRef=function(K,J,U){},C.prototype.walkFlat=function(K,J,U){var Y=J.concat(U);this.walk(K,Y)},C.prototype.walkOption=function(K,J,U){var Y=J.concat(U);this.walk(K,Y)},C.prototype.walkAtLeastOne=function(K,J,U){var Y=[new E.Option({definition:K.definition})].concat(J,U);this.walk(K,Y)},C.prototype.walkAtLeastOneSep=function(K,J,U){var Y=I(K,J,U);this.walk(K,Y)},C.prototype.walkMany=function(K,J,U){var Y=[new E.Option({definition:K.definition})].concat(J,U);this.walk(K,Y)},C.prototype.walkManySep=function(K,J,U){var Y=I(K,J,U);this.walk(K,Y)},C.prototype.walkOr=function(K,J,U){var Y=this,H=J.concat(U);Q.forEach(K.definition,function(R){var O=new E.Alternative({definition:[R]});Y.walk(O,H)})},C}();A.RestWalker=B;function I(C,K,J){var U=[new E.Option({definition:[new E.Terminal({terminalType:C.separator})].concat(C.definition)})],Y=U.concat(K,J);return Y}}),FK=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.GAstVisitor=void 0;var Q=mE(),E=function(){function B(){}return B.prototype.visit=function(I){var C=I;switch(C.constructor){case Q.NonTerminal:return this.visitNonTerminal(C);case Q.Alternative:return this.visitAlternative(C);case Q.Option:return this.visitOption(C);case Q.RepetitionMandatory:return this.visitRepetitionMandatory(C);case Q.RepetitionMandatoryWithSeparator:return this.visitRepetitionMandatoryWithSeparator(C);case Q.RepetitionWithSeparator:return this.visitRepetitionWithSeparator(C);case Q.Repetition:return this.visitRepetition(C);case Q.Alternation:return this.visitAlternation(C);case Q.Terminal:return this.visitTerminal(C);case Q.Rule:return this.visitRule(C);default:throw Error("non exhaustive match")}},B.prototype.visitNonTerminal=function(I){},B.prototype.visitAlternative=function(I){},B.prototype.visitOption=function(I){},B.prototype.visitRepetition=function(I){},B.prototype.visitRepetitionMandatory=function(I){},B.prototype.visitRepetitionMandatoryWithSeparator=function(I){},B.prototype.visitRepetitionWithSeparator=function(I){},B.prototype.visitAlternation=function(I){},B.prototype.visitTerminal=function(I){},B.prototype.visitRule=function(I){},B}();A.GAstVisitor=E}),TU=P0((A)=>{var Q=A&&A.__extends||function(){var O=function(N,$){return O=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(L,W){L.__proto__=W}||function(L,W){for(var Z in W)Object.prototype.hasOwnProperty.call(W,Z)&&(L[Z]=W[Z])},O(N,$)};return function(N,$){if(typeof $!="function"&&$!==null)throw new TypeError("Class extends value "+String($)+" is not a constructor or null");O(N,$);function L(){this.constructor=N}N.prototype=$===null?Object.create($):(L.prototype=$.prototype,new L)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.collectMethods=A.DslMethodsCollectorVisitor=A.getProductionDslName=A.isBranchingProd=A.isOptionalProd=A.isSequenceProd=void 0;var E=t0(),B=mE(),I=FK();function C(O){return O instanceof B.Alternative||O instanceof B.Option||O instanceof B.Repetition||O instanceof B.RepetitionMandatory||O instanceof B.RepetitionMandatoryWithSeparator||O instanceof B.RepetitionWithSeparator||O instanceof B.Terminal||O instanceof B.Rule}A.isSequenceProd=C;function K(O,N){N===void 0&&(N=[]);var $=O instanceof B.Option||O instanceof B.Repetition||O instanceof B.RepetitionWithSeparator;return $?!0:O instanceof B.Alternation?E.some(O.definition,function(L){return K(L,N)}):O instanceof B.NonTerminal&&E.contains(N,O)?!1:O instanceof B.AbstractProduction?(O instanceof B.NonTerminal&&N.push(O),E.every(O.definition,function(L){return K(L,N)})):!1}A.isOptionalProd=K;function J(O){return O instanceof B.Alternation}A.isBranchingProd=J;function U(O){if(O instanceof B.NonTerminal)return"SUBRULE";if(O instanceof B.Option)return"OPTION";if(O instanceof B.Alternation)return"OR";if(O instanceof B.RepetitionMandatory)return"AT_LEAST_ONE";if(O instanceof B.RepetitionMandatoryWithSeparator)return"AT_LEAST_ONE_SEP";if(O instanceof B.RepetitionWithSeparator)return"MANY_SEP";if(O instanceof B.Repetition)return"MANY";if(O instanceof B.Terminal)return"CONSUME";throw Error("non exhaustive match")}A.getProductionDslName=U;var Y=function(O){Q(N,O);function N(){var $=O!==null&&O.apply(this,arguments)||this;return $.separator="-",$.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]},$}return N.prototype.reset=function(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}},N.prototype.visitTerminal=function($){var L=$.terminalType.name+this.separator+"Terminal";E.has(this.dslMethods,L)||(this.dslMethods[L]=[]),this.dslMethods[L].push($)},N.prototype.visitNonTerminal=function($){var L=$.nonTerminalName+this.separator+"Terminal";E.has(this.dslMethods,L)||(this.dslMethods[L]=[]),this.dslMethods[L].push($)},N.prototype.visitOption=function($){this.dslMethods.option.push($)},N.prototype.visitRepetitionWithSeparator=function($){this.dslMethods.repetitionWithSeparator.push($)},N.prototype.visitRepetitionMandatory=function($){this.dslMethods.repetitionMandatory.push($)},N.prototype.visitRepetitionMandatoryWithSeparator=function($){this.dslMethods.repetitionMandatoryWithSeparator.push($)},N.prototype.visitRepetition=function($){this.dslMethods.repetition.push($)},N.prototype.visitAlternation=function($){this.dslMethods.alternation.push($)},N}(I.GAstVisitor);A.DslMethodsCollectorVisitor=Y;var H=new Y;function R(O){H.reset(),O.accept(H);var N=H.dslMethods;return H.reset(),N}A.collectMethods=R}),LX=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.firstForTerminal=A.firstForBranching=A.firstForSequence=A.first=void 0;var Q=t0(),E=mE(),B=TU();function I(U){if(U instanceof E.NonTerminal)return I(U.referencedRule);if(U instanceof E.Terminal)return J(U);if(B.isSequenceProd(U))return C(U);if(B.isBranchingProd(U))return K(U);throw Error("non exhaustive match")}A.first=I;function C(U){for(var Y=[],H=U.definition,R=0,O=H.length>R,N,$=!0;O&&$;)N=H[R],$=B.isOptionalProd(N),Y=Y.concat(I(N)),R=R+1,O=H.length>R;return Q.uniq(Y)}A.firstForSequence=C;function K(U){var Y=Q.map(U.definition,function(H){return I(H)});return Q.uniq(Q.flatten(Y))}A.firstForBranching=K;function J(U){return[U.terminalType]}A.firstForTerminal=J}),qX=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.IN=void 0,A.IN="_~IN~_"}),Pk=P0((A)=>{var Q=A&&A.__extends||function(){var R=function(O,N){return R=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function($,L){$.__proto__=L}||function($,L){for(var W in L)Object.prototype.hasOwnProperty.call(L,W)&&($[W]=L[W])},R(O,N)};return function(O,N){if(typeof N!="function"&&N!==null)throw new TypeError("Class extends value "+String(N)+" is not a constructor or null");R(O,N);function $(){this.constructor=O}O.prototype=N===null?Object.create(N):($.prototype=N.prototype,new $)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.buildInProdFollowPrefix=A.buildBetweenProdsFollowPrefix=A.computeAllProdsFollows=A.ResyncFollowsWalker=void 0;var E=Z7(),B=LX(),I=t0(),C=qX(),K=mE(),J=function(R){Q(O,R);function O(N){var $=R.call(this)||this;return $.topProd=N,$.follows={},$}return O.prototype.startWalking=function(){return this.walk(this.topProd),this.follows},O.prototype.walkTerminal=function(N,$,L){},O.prototype.walkProdRef=function(N,$,L){var W=Y(N.referencedRule,N.idx)+this.topProd.name,Z=$.concat(L),G=new K.Alternative({definition:Z}),X=B.first(G);this.follows[W]=X},O}(E.RestWalker);A.ResyncFollowsWalker=J;function U(R){var O={};return I.forEach(R,function(N){var $=new J(N).startWalking();I.assign(O,$)}),O}A.computeAllProdsFollows=U;function Y(R,O){return R.name+O+C.IN}A.buildBetweenProdsFollowPrefix=Y;function H(R){var O=R.terminalType.name;return O+R.idx+C.IN}A.buildInProdFollowPrefix=H}),zU=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.defaultGrammarValidatorErrorProvider=A.defaultGrammarResolverErrorProvider=A.defaultParserErrorProvider=void 0;var Q=i1(),E=t0(),B=t0(),I=mE(),C=TU();A.defaultParserErrorProvider={buildMismatchTokenMessage:function(K){var{expected:J,actual:U,previous:Y,ruleName:H}=K,R=Q.hasTokenLabel(J),O=R?"--> "+Q.tokenLabel(J)+" <--":"token of type --> "+J.name+" <--",N="Expecting "+O+" but found --> '"+U.image+"' <--";return N},buildNotAllInputParsedMessage:function(K){var{firstRedundant:J,ruleName:U}=K;return"Redundant input, expecting EOF but found: "+J.image},buildNoViableAltMessage:function(K){var{expectedPathsPerAlt:J,actual:U,previous:Y,customUserDescription:H,ruleName:R}=K,O="Expecting: ",N=B.first(U).image,$=` -but found: '`+N+"'";if(H)return O+H+$;var L=B.reduce(J,function(X,q){return X.concat(q)},[]),W=B.map(L,function(X){return"["+B.map(X,function(q){return Q.tokenLabel(q)}).join(", ")+"]"}),Z=B.map(W,function(X,q){return" "+(q+1)+". "+X}),G=`one of these possible Token sequences: -`+Z.join(` -`);return O+G+$},buildEarlyExitMessage:function(K){var{expectedIterationPaths:J,actual:U,customUserDescription:Y,ruleName:H}=K,R="Expecting: ",O=B.first(U).image,N=` -but found: '`+O+"'";if(Y)return R+Y+N;var $=B.map(J,function(W){return"["+B.map(W,function(Z){return Q.tokenLabel(Z)}).join(",")+"]"}),L=`expecting at least one iteration which starts with one of these possible Token sequences:: - `+("<"+$.join(" ,")+">");return R+L+N}},Object.freeze(A.defaultParserErrorProvider),A.defaultGrammarResolverErrorProvider={buildRuleNotFoundError:function(K,J){var U="Invalid grammar, reference to a rule which is not defined: ->"+J.nonTerminalName+`<- -inside top level rule: ->`+K.name+"<-";return U}},A.defaultGrammarValidatorErrorProvider={buildDuplicateFoundError:function(K,J){function U(W){return W instanceof I.Terminal?W.terminalType.name:W instanceof I.NonTerminal?W.nonTerminalName:""}var Y=K.name,H=B.first(J),R=H.idx,O=C.getProductionDslName(H),N=U(H),$=R>0,L="->"+O+($?R:"")+"<- "+(N?"with argument: ->"+N+"<-":"")+` - appears more than once (`+J.length+" times) in the top level rule: ->"+Y+`<-. - For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES - `;return L=L.replace(/[ \t]+/g," "),L=L.replace(/\s\s+/g,` -`),L},buildNamespaceConflictError:function(K){var J=`Namespace conflict found in grammar. -`+("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <"+K.name+`>. -`)+`To resolve this make sure each Terminal and Non-Terminal names are unique -This is easy to accomplish by using the convention that Terminal names start with an uppercase letter -and Non-Terminal names start with a lower case letter.`;return J},buildAlternationPrefixAmbiguityError:function(K){var J=B.map(K.prefixPath,function(H){return Q.tokenLabel(H)}).join(", "),U=K.alternation.idx===0?"":K.alternation.idx,Y="Ambiguous alternatives: <"+K.ambiguityIndices.join(" ,")+`> due to common lookahead prefix -`+("in inside <"+K.topLevelRule.name+`> Rule, -`)+("<"+J+`> may appears as a prefix path in all these alternatives. -`)+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX -For Further details.`;return Y},buildAlternationAmbiguityError:function(K){var J=B.map(K.prefixPath,function(H){return Q.tokenLabel(H)}).join(", "),U=K.alternation.idx===0?"":K.alternation.idx,Y="Ambiguous Alternatives Detected: <"+K.ambiguityIndices.join(" ,")+"> in "+(" inside <"+K.topLevelRule.name+`> Rule, -`)+("<"+J+`> may appears as a prefix path in all these alternatives. -`);return Y=Y+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES -For Further details.`,Y},buildEmptyRepetitionError:function(K){var J=C.getProductionDslName(K.repetition);K.repetition.idx!==0&&(J+=K.repetition.idx);var U="The repetition <"+J+"> within Rule <"+K.topLevelRule.name+`> can never consume any tokens. -This could lead to an infinite loop.`;return U},buildTokenNameError:function(K){return"deprecated"},buildEmptyAlternationError:function(K){var J="Ambiguous empty alternative: <"+(K.emptyChoiceIdx+1)+">"+(" in inside <"+K.topLevelRule.name+`> Rule. -`)+"Only the last alternative may be an empty alternative.";return J},buildTooManyAlternativesError:function(K){var J=`An Alternation cannot have more than 256 alternatives: -`+(" inside <"+K.topLevelRule.name+`> Rule. - has `+(K.alternation.definition.length+1)+" alternatives.");return J},buildLeftRecursionError:function(K){var J=K.topLevelRule.name,U=E.map(K.leftRecursionPath,function(R){return R.name}),Y=J+" --> "+U.concat([J]).join(" --> "),H=`Left Recursion found in grammar. -`+("rule: <"+J+`> can be invoked from itself (directly or indirectly) -`)+(`without consuming any Tokens. The grammar path that causes this is: - `+Y+` -`)+` To fix this refactor your grammar to remove the left recursion. -see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring.`;return H},buildInvalidRuleNameError:function(K){return"deprecated"},buildDuplicateRuleNameError:function(K){var J;K.topLevelRule instanceof I.Rule?J=K.topLevelRule.name:J=K.topLevelRule;var U="Duplicate definition, rule: ->"+J+"<- is already defined in the grammar: ->"+K.grammarName+"<-";return U}}}),Vk=P0((A)=>{var Q=A&&A.__extends||function(){var J=function(U,Y){return J=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,R){H.__proto__=R}||function(H,R){for(var O in R)Object.prototype.hasOwnProperty.call(R,O)&&(H[O]=R[O])},J(U,Y)};return function(U,Y){if(typeof Y!="function"&&Y!==null)throw new TypeError("Class extends value "+String(Y)+" is not a constructor or null");J(U,Y);function H(){this.constructor=U}U.prototype=Y===null?Object.create(Y):(H.prototype=Y.prototype,new H)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.GastRefResolverVisitor=A.resolveGrammar=void 0;var E=EB(),B=t0(),I=FK();function C(J,U){var Y=new K(J,U);return Y.resolveRefs(),Y.errors}A.resolveGrammar=C;var K=function(J){Q(U,J);function U(Y,H){var R=J.call(this)||this;return R.nameToTopRule=Y,R.errMsgProvider=H,R.errors=[],R}return U.prototype.resolveRefs=function(){var Y=this;B.forEach(B.values(this.nameToTopRule),function(H){Y.currTopLevel=H,H.accept(Y)})},U.prototype.visitNonTerminal=function(Y){var H=this.nameToTopRule[Y.nonTerminalName];if(H)Y.referencedRule=H;else{var R=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,Y);this.errors.push({message:R,type:E.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:Y.nonTerminalName})}},U}(I.GAstVisitor);A.GastRefResolverVisitor=K}),PU=P0((A)=>{var Q=A&&A.__extends||function(){var W=function(Z,G){return W=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(X,q){X.__proto__=q}||function(X,q){for(var M in q)Object.prototype.hasOwnProperty.call(q,M)&&(X[M]=q[M])},W(Z,G)};return function(Z,G){if(typeof G!="function"&&G!==null)throw new TypeError("Class extends value "+String(G)+" is not a constructor or null");W(Z,G);function X(){this.constructor=Z}Z.prototype=G===null?Object.create(G):(X.prototype=G.prototype,new X)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.nextPossibleTokensAfter=A.possiblePathsFrom=A.NextTerminalAfterAtLeastOneSepWalker=A.NextTerminalAfterAtLeastOneWalker=A.NextTerminalAfterManySepWalker=A.NextTerminalAfterManyWalker=A.AbstractNextTerminalAfterProductionWalker=A.NextAfterTokenWalker=A.AbstractNextPossibleTokensWalker=void 0;var E=Z7(),B=t0(),I=LX(),C=mE(),K=function(W){Q(Z,W);function Z(G,X){var q=W.call(this)||this;return q.topProd=G,q.path=X,q.possibleTokTypes=[],q.nextProductionName="",q.nextProductionOccurrence=0,q.found=!1,q.isAtEndOfPath=!1,q}return Z.prototype.startWalking=function(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=B.cloneArr(this.path.ruleStack).reverse(),this.occurrenceStack=B.cloneArr(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes},Z.prototype.walk=function(G,X){X===void 0&&(X=[]),this.found||W.prototype.walk.call(this,G,X)},Z.prototype.walkProdRef=function(G,X,q){if(G.referencedRule.name===this.nextProductionName&&G.idx===this.nextProductionOccurrence){var M=X.concat(q);this.updateExpectedNext(),this.walk(G.referencedRule,M)}},Z.prototype.updateExpectedNext=function(){B.isEmpty(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())},Z}(E.RestWalker);A.AbstractNextPossibleTokensWalker=K;var J=function(W){Q(Z,W);function Z(G,X){var q=W.call(this,G,X)||this;return q.path=X,q.nextTerminalName="",q.nextTerminalOccurrence=0,q.nextTerminalName=q.path.lastTok.name,q.nextTerminalOccurrence=q.path.lastTokOccurrence,q}return Z.prototype.walkTerminal=function(G,X,q){if(this.isAtEndOfPath&&G.terminalType.name===this.nextTerminalName&&G.idx===this.nextTerminalOccurrence&&!this.found){var M=X.concat(q),F=new C.Alternative({definition:M});this.possibleTokTypes=I.first(F),this.found=!0}},Z}(K);A.NextAfterTokenWalker=J;var U=function(W){Q(Z,W);function Z(G,X){var q=W.call(this)||this;return q.topRule=G,q.occurrence=X,q.result={token:void 0,occurrence:void 0,isEndOfRule:void 0},q}return Z.prototype.startWalking=function(){return this.walk(this.topRule),this.result},Z}(E.RestWalker);A.AbstractNextTerminalAfterProductionWalker=U;var Y=function(W){Q(Z,W);function Z(){return W!==null&&W.apply(this,arguments)||this}return Z.prototype.walkMany=function(G,X,q){if(G.idx===this.occurrence){var M=B.first(X.concat(q));this.result.isEndOfRule=M===void 0,M instanceof C.Terminal&&(this.result.token=M.terminalType,this.result.occurrence=M.idx)}else W.prototype.walkMany.call(this,G,X,q)},Z}(U);A.NextTerminalAfterManyWalker=Y;var H=function(W){Q(Z,W);function Z(){return W!==null&&W.apply(this,arguments)||this}return Z.prototype.walkManySep=function(G,X,q){if(G.idx===this.occurrence){var M=B.first(X.concat(q));this.result.isEndOfRule=M===void 0,M instanceof C.Terminal&&(this.result.token=M.terminalType,this.result.occurrence=M.idx)}else W.prototype.walkManySep.call(this,G,X,q)},Z}(U);A.NextTerminalAfterManySepWalker=H;var R=function(W){Q(Z,W);function Z(){return W!==null&&W.apply(this,arguments)||this}return Z.prototype.walkAtLeastOne=function(G,X,q){if(G.idx===this.occurrence){var M=B.first(X.concat(q));this.result.isEndOfRule=M===void 0,M instanceof C.Terminal&&(this.result.token=M.terminalType,this.result.occurrence=M.idx)}else W.prototype.walkAtLeastOne.call(this,G,X,q)},Z}(U);A.NextTerminalAfterAtLeastOneWalker=R;var O=function(W){Q(Z,W);function Z(){return W!==null&&W.apply(this,arguments)||this}return Z.prototype.walkAtLeastOneSep=function(G,X,q){if(G.idx===this.occurrence){var M=B.first(X.concat(q));this.result.isEndOfRule=M===void 0,M instanceof C.Terminal&&(this.result.token=M.terminalType,this.result.occurrence=M.idx)}else W.prototype.walkAtLeastOneSep.call(this,G,X,q)},Z}(U);A.NextTerminalAfterAtLeastOneSepWalker=O;function N(W,Z,G){G===void 0&&(G=[]),G=B.cloneArr(G);var X=[],q=0;function M(w){return w.concat(B.drop(W,q+1))}function F(w){var k=N(M(w),Z,G);return X.concat(k)}for(;G.length=0;e--){var BA=V.definition[e],EA={idx:v,def:BA.definition.concat(B.drop(j)),ruleStack:g,occurrenceStack:P};T.push(EA),T.push(F)}else if(V instanceof C.Alternative)T.push({idx:v,def:V.definition.concat(B.drop(j)),ruleStack:g,occurrenceStack:P});else if(V instanceof C.Rule)T.push(L(V,v,g,P));else throw Error("non exhaustive match")}}return k}A.nextPossibleTokensAfter=$;function L(W,Z,G,X){var q=B.cloneArr(G);q.push(W.name);var M=B.cloneArr(X);return M.push(1),{idx:Z,def:W.definition,ruleStack:q,occurrenceStack:M}}}),VU=P0((A)=>{var Q=A&&A.__extends||function(){var w=function(k,T){return w=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(z,j){z.__proto__=j}||function(z,j){for(var v in j)Object.prototype.hasOwnProperty.call(j,v)&&(z[v]=j[v])},w(k,T)};return function(k,T){if(typeof T!="function"&&T!==null)throw new TypeError("Class extends value "+String(T)+" is not a constructor or null");w(k,T);function z(){this.constructor=k}k.prototype=T===null?Object.create(T):(z.prototype=T.prototype,new z)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.areTokenCategoriesNotUsed=A.isStrictPrefixOfPath=A.containsPath=A.getLookaheadPathsForOptionalProd=A.getLookaheadPathsForOr=A.lookAheadSequenceFromAlternatives=A.buildSingleAlternativeLookaheadFunction=A.buildAlternativesLookAheadFunc=A.buildLookaheadFuncForOptionalProd=A.buildLookaheadFuncForOr=A.getProdType=A.PROD_TYPE=void 0;var E=t0(),B=PU(),I=Z7(),C=qK(),K=mE(),J=FK(),U;(function(w){w[w.OPTION=0]="OPTION",w[w.REPETITION=1]="REPETITION",w[w.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",w[w.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",w[w.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",w[w.ALTERNATION=5]="ALTERNATION"})(U=A.PROD_TYPE||(A.PROD_TYPE={}));function Y(w){if(w instanceof K.Option)return U.OPTION;if(w instanceof K.Repetition)return U.REPETITION;if(w instanceof K.RepetitionMandatory)return U.REPETITION_MANDATORY;if(w instanceof K.RepetitionMandatoryWithSeparator)return U.REPETITION_MANDATORY_WITH_SEPARATOR;if(w instanceof K.RepetitionWithSeparator)return U.REPETITION_WITH_SEPARATOR;if(w instanceof K.Alternation)return U.ALTERNATION;throw Error("non exhaustive match")}A.getProdType=Y;function H(w,k,T,z,j,v){var g=q(w,k,T),P=_(g)?C.tokenStructuredMatcherNoCategories:C.tokenStructuredMatcher;return v(g,z,P,j)}A.buildLookaheadFuncForOr=H;function R(w,k,T,z,j,v){var g=M(w,k,j,T),P=_(g)?C.tokenStructuredMatcherNoCategories:C.tokenStructuredMatcher;return v(g[0],P,z)}A.buildLookaheadFuncForOptionalProd=R;function O(w,k,T,z){var j=w.length,v=E.every(w,function(V){return E.every(V,function(S){return S.length===1})});if(k)return function(V){for(var S=E.map(V,function(o){return o.GATE}),h=0;h{var Q=A&&A.__extends||function(){var z=function(j,v){return z=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,P){g.__proto__=P}||function(g,P){for(var V in P)Object.prototype.hasOwnProperty.call(P,V)&&(g[V]=P[V])},z(j,v)};return function(j,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");z(j,v);function g(){this.constructor=j}j.prototype=v===null?Object.create(v):(g.prototype=v.prototype,new g)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.checkPrefixAlternativesAmbiguities=A.validateSomeNonEmptyLookaheadPath=A.validateTooManyAlts=A.RepetionCollector=A.validateAmbiguousAlternationAlternatives=A.validateEmptyOrAlternative=A.getFirstNoneTerminal=A.validateNoLeftRecursion=A.validateRuleIsOverridden=A.validateRuleDoesNotAlreadyExist=A.OccurrenceValidationCollector=A.identifyProductionForDuplicates=A.validateGrammar=void 0;var E=t0(),B=t0(),I=EB(),C=TU(),K=VU(),J=PU(),U=mE(),Y=FK();function H(z,j,v,g,P){var V=E.map(z,function(n){return R(n,g)}),S=E.map(z,function(n){return Z(n,n,g)}),h=[],x=[],b=[];B.every(S,B.isEmpty)&&(h=B.map(z,function(n){return q(n,g)}),x=B.map(z,function(n){return M(n,j,g)}),b=_(z,j,g));var m=T(z,v,g),s=B.map(z,function(n){return D(n,g)}),i=B.map(z,function(n){return L(n,z,P,g)});return E.flatten(V.concat(b,S,h,x,m,s,i))}A.validateGrammar=H;function R(z,j){var v=new $;z.accept(v);var g=v.allProductions,P=E.groupBy(g,O),V=E.pick(P,function(h){return h.length>1}),S=E.map(E.values(V),function(h){var x=E.first(h),b=j.buildDuplicateFoundError(z,h),m=C.getProductionDslName(x),s={message:b,type:I.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,ruleName:z.name,dslName:m,occurrence:x.idx},i=N(x);return i&&(s.parameter=i),s});return S}function O(z){return C.getProductionDslName(z)+"_#_"+z.idx+"_#_"+N(z)}A.identifyProductionForDuplicates=O;function N(z){return z instanceof U.Terminal?z.terminalType.name:z instanceof U.NonTerminal?z.nonTerminalName:""}var $=function(z){Q(j,z);function j(){var v=z!==null&&z.apply(this,arguments)||this;return v.allProductions=[],v}return j.prototype.visitNonTerminal=function(v){this.allProductions.push(v)},j.prototype.visitOption=function(v){this.allProductions.push(v)},j.prototype.visitRepetitionWithSeparator=function(v){this.allProductions.push(v)},j.prototype.visitRepetitionMandatory=function(v){this.allProductions.push(v)},j.prototype.visitRepetitionMandatoryWithSeparator=function(v){this.allProductions.push(v)},j.prototype.visitRepetition=function(v){this.allProductions.push(v)},j.prototype.visitAlternation=function(v){this.allProductions.push(v)},j.prototype.visitTerminal=function(v){this.allProductions.push(v)},j}(Y.GAstVisitor);A.OccurrenceValidationCollector=$;function L(z,j,v,g){var P=[],V=B.reduce(j,function(h,x){return x.name===z.name?h+1:h},0);if(V>1){var S=g.buildDuplicateRuleNameError({topLevelRule:z,grammarName:v});P.push({message:S,type:I.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:z.name})}return P}A.validateRuleDoesNotAlreadyExist=L;function W(z,j,v){var g=[],P;return E.contains(j,z)||(P="Invalid rule override, rule: ->"+z+"<- cannot be overridden in the grammar: ->"+v+"<-as it is not defined in any of the super grammars ",g.push({message:P,type:I.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,ruleName:z})),g}A.validateRuleIsOverridden=W;function Z(z,j,v,g){g===void 0&&(g=[]);var P=[],V=G(j.definition);if(E.isEmpty(V))return[];var S=z.name,h=E.contains(V,z);h&&P.push({message:v.buildLeftRecursionError({topLevelRule:z,leftRecursionPath:g}),type:I.ParserDefinitionErrorType.LEFT_RECURSION,ruleName:S});var x=E.difference(V,g.concat([z])),b=E.map(x,function(m){var s=E.cloneArr(g);return s.push(m),Z(z,m,v,s)});return P.concat(E.flatten(b))}A.validateNoLeftRecursion=Z;function G(z){var j=[];if(E.isEmpty(z))return j;var v=E.first(z);if(v instanceof U.NonTerminal)j.push(v.referencedRule);else if(v instanceof U.Alternative||v instanceof U.Option||v instanceof U.RepetitionMandatory||v instanceof U.RepetitionMandatoryWithSeparator||v instanceof U.RepetitionWithSeparator||v instanceof U.Repetition)j=j.concat(G(v.definition));else if(v instanceof U.Alternation)j=E.flatten(E.map(v.definition,function(S){return G(S.definition)}));else if(!(v instanceof U.Terminal))throw Error("non exhaustive match");var g=C.isOptionalProd(v),P=z.length>1;if(g&&P){var V=E.drop(z);return j.concat(G(V))}else return j}A.getFirstNoneTerminal=G;var X=function(z){Q(j,z);function j(){var v=z!==null&&z.apply(this,arguments)||this;return v.alternations=[],v}return j.prototype.visitAlternation=function(v){this.alternations.push(v)},j}(Y.GAstVisitor);function q(z,j){var v=new X;z.accept(v);var g=v.alternations,P=E.reduce(g,function(V,S){var h=E.dropRight(S.definition),x=E.map(h,function(b,m){var s=J.nextPossibleTokensAfter([b],[],null,1);return E.isEmpty(s)?{message:j.buildEmptyAlternationError({topLevelRule:z,alternation:S,emptyChoiceIdx:m}),type:I.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,ruleName:z.name,occurrence:S.idx,alternative:m+1}:null});return V.concat(E.compact(x))},[]);return P}A.validateEmptyOrAlternative=q;function M(z,j,v){var g=new X;z.accept(g);var P=g.alternations;P=B.reject(P,function(S){return S.ignoreAmbiguities===!0});var V=E.reduce(P,function(S,h){var x=h.idx,b=h.maxLookahead||j,m=K.getLookaheadPathsForOr(x,z,b,h),s=w(m,h,z,v),i=k(m,h,z,v);return S.concat(s,i)},[]);return V}A.validateAmbiguousAlternationAlternatives=M;var F=function(z){Q(j,z);function j(){var v=z!==null&&z.apply(this,arguments)||this;return v.allProductions=[],v}return j.prototype.visitRepetitionWithSeparator=function(v){this.allProductions.push(v)},j.prototype.visitRepetitionMandatory=function(v){this.allProductions.push(v)},j.prototype.visitRepetitionMandatoryWithSeparator=function(v){this.allProductions.push(v)},j.prototype.visitRepetition=function(v){this.allProductions.push(v)},j}(Y.GAstVisitor);A.RepetionCollector=F;function D(z,j){var v=new X;z.accept(v);var g=v.alternations,P=E.reduce(g,function(V,S){return S.definition.length>255&&V.push({message:j.buildTooManyAlternativesError({topLevelRule:z,alternation:S}),type:I.ParserDefinitionErrorType.TOO_MANY_ALTS,ruleName:z.name,occurrence:S.idx}),V},[]);return P}A.validateTooManyAlts=D;function _(z,j,v){var g=[];return B.forEach(z,function(P){var V=new F;P.accept(V);var S=V.allProductions;B.forEach(S,function(h){var x=K.getProdType(h),b=h.maxLookahead||j,m=h.idx,s=K.getLookaheadPathsForOptionalProd(m,P,x,b),i=s[0];if(B.isEmpty(B.flatten(i))){var n=v.buildEmptyRepetitionError({topLevelRule:P,repetition:h});g.push({message:n,type:I.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,ruleName:P.name})}})}),g}A.validateSomeNonEmptyLookaheadPath=_;function w(z,j,v,g){var P=[],V=B.reduce(z,function(h,x,b){return j.definition[b].ignoreAmbiguities===!0||B.forEach(x,function(m){var s=[b];B.forEach(z,function(i,n){b!==n&&K.containsPath(i,m)&&j.definition[n].ignoreAmbiguities!==!0&&s.push(n)}),s.length>1&&!K.containsPath(P,m)&&(P.push(m),h.push({alts:s,path:m}))}),h},[]),S=E.map(V,function(h){var x=B.map(h.alts,function(m){return m+1}),b=g.buildAlternationAmbiguityError({topLevelRule:v,alternation:j,ambiguityIndices:x,prefixPath:h.path});return{message:b,type:I.ParserDefinitionErrorType.AMBIGUOUS_ALTS,ruleName:v.name,occurrence:j.idx,alternatives:[h.alts]}});return S}function k(z,j,v,g){var P=[],V=B.reduce(z,function(S,h,x){var b=B.map(h,function(m){return{idx:x,path:m}});return S.concat(b)},[]);return B.forEach(V,function(S){var h=j.definition[S.idx];if(h.ignoreAmbiguities!==!0){var{idx:x,path:b}=S,m=B.findAll(V,function(i){return j.definition[i.idx].ignoreAmbiguities!==!0&&i.idx{Object.defineProperty(A,"__esModule",{value:!0}),A.validateGrammar=A.resolveGrammar=void 0;var Q=t0(),E=Vk(),B=FX(),I=zU();function C(J){J=Q.defaults(J,{errMsgProvider:I.defaultGrammarResolverErrorProvider});var U={};return Q.forEach(J.rules,function(Y){U[Y.name]=Y}),E.resolveGrammar(U,J.errMsgProvider)}A.resolveGrammar=C;function K(J){return J=Q.defaults(J,{errMsgProvider:I.defaultGrammarValidatorErrorProvider}),B.validateGrammar(J.rules,J.maxLookahead,J.tokenTypes,J.errMsgProvider,J.grammarName)}A.validateGrammar=K}),DK=P0((A)=>{var Q=A&&A.__extends||function(){var $=function(L,W){return $=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(Z,G){Z.__proto__=G}||function(Z,G){for(var X in G)Object.prototype.hasOwnProperty.call(G,X)&&(Z[X]=G[X])},$(L,W)};return function(L,W){if(typeof W!="function"&&W!==null)throw new TypeError("Class extends value "+String(W)+" is not a constructor or null");$(L,W);function Z(){this.constructor=L}L.prototype=W===null?Object.create(W):(Z.prototype=W.prototype,new Z)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.EarlyExitException=A.NotAllInputParsedException=A.NoViableAltException=A.MismatchedTokenException=A.isRecognitionException=void 0;var E=t0(),B="MismatchedTokenException",I="NoViableAltException",C="EarlyExitException",K="NotAllInputParsedException",J=[B,I,C,K];Object.freeze(J);function U($){return E.contains(J,$.name)}A.isRecognitionException=U;var Y=function($){Q(L,$);function L(W,Z){var G=this.constructor,X=$.call(this,W)||this;return X.token=Z,X.resyncedTokens=[],Object.setPrototypeOf(X,G.prototype),Error.captureStackTrace&&Error.captureStackTrace(X,X.constructor),X}return L}(Error),H=function($){Q(L,$);function L(W,Z,G){var X=$.call(this,W,Z)||this;return X.previousToken=G,X.name=B,X}return L}(Y);A.MismatchedTokenException=H;var R=function($){Q(L,$);function L(W,Z,G){var X=$.call(this,W,Z)||this;return X.previousToken=G,X.name=I,X}return L}(Y);A.NoViableAltException=R;var O=function($){Q(L,$);function L(W,Z){var G=$.call(this,W,Z)||this;return G.name=K,G}return L}(Y);A.NotAllInputParsedException=O;var N=function($){Q(L,$);function L(W,Z,G){var X=$.call(this,W,Z)||this;return X.previousToken=G,X.name=C,X}return L}(Y);A.EarlyExitException=N}),DX=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.attemptInRepetitionRecovery=A.Recoverable=A.InRuleRecoveryException=A.IN_RULE_RECOVERY_EXCEPTION=A.EOF_FOLLOW_KEY=void 0;var Q=i1(),E=t0(),B=DK(),I=qX(),C=EB();A.EOF_FOLLOW_KEY={},A.IN_RULE_RECOVERY_EXCEPTION="InRuleRecoveryException";function K(Y){this.name=A.IN_RULE_RECOVERY_EXCEPTION,this.message=Y}A.InRuleRecoveryException=K,K.prototype=Error.prototype;var J=function(){function Y(){}return Y.prototype.initRecoverable=function(H){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=E.has(H,"recoveryEnabled")?H.recoveryEnabled:C.DEFAULT_PARSER_CONFIG.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=U)},Y.prototype.getTokenToInsert=function(H){var R=Q.createTokenInstance(H,"",NaN,NaN,NaN,NaN,NaN,NaN);return R.isInsertedInRecovery=!0,R},Y.prototype.canTokenTypeBeInsertedInRecovery=function(H){return!0},Y.prototype.tryInRepetitionRecovery=function(H,R,O,N){for(var $=this,L=this.findReSyncTokenType(),W=this.exportLexerState(),Z=[],G=!1,X=this.LA(1),q=this.LA(1),M=function(){var F=$.LA(0),D=$.errorMessageProvider.buildMismatchTokenMessage({expected:N,actual:X,previous:F,ruleName:$.getCurrRuleFullName()}),_=new B.MismatchedTokenException(D,X,$.LA(0));_.resyncedTokens=E.dropRight(Z),$.SAVE_ERROR(_)};!G;)if(this.tokenMatcher(q,N)){M();return}else if(O.call(this)){M(),H.apply(this,R);return}else this.tokenMatcher(q,L)?G=!0:(q=this.SKIP_TOKEN(),this.addToResyncTokens(q,Z));this.importLexerState(W)},Y.prototype.shouldInRepetitionRecoveryBeTried=function(H,R,O){return!(O===!1||H===void 0||R===void 0||this.tokenMatcher(this.LA(1),H)||this.isBackTracking()||this.canPerformInRuleRecovery(H,this.getFollowsForInRuleRecovery(H,R)))},Y.prototype.getFollowsForInRuleRecovery=function(H,R){var O=this.getCurrentGrammarPath(H,R),N=this.getNextPossibleTokenTypes(O);return N},Y.prototype.tryInRuleRecovery=function(H,R){if(this.canRecoverWithSingleTokenInsertion(H,R)){var O=this.getTokenToInsert(H);return O}if(this.canRecoverWithSingleTokenDeletion(H)){var N=this.SKIP_TOKEN();return this.consumeToken(),N}throw new K("sad sad panda")},Y.prototype.canPerformInRuleRecovery=function(H,R){return this.canRecoverWithSingleTokenInsertion(H,R)||this.canRecoverWithSingleTokenDeletion(H)},Y.prototype.canRecoverWithSingleTokenInsertion=function(H,R){var O=this;if(!this.canTokenTypeBeInsertedInRecovery(H)||E.isEmpty(R))return!1;var N=this.LA(1),$=E.find(R,function(L){return O.tokenMatcher(N,L)})!==void 0;return $},Y.prototype.canRecoverWithSingleTokenDeletion=function(H){var R=this.tokenMatcher(this.LA(2),H);return R},Y.prototype.isInCurrentRuleReSyncSet=function(H){var R=this.getCurrFollowKey(),O=this.getFollowSetFromFollowKey(R);return E.contains(O,H)},Y.prototype.findReSyncTokenType=function(){for(var H=this.flattenFollowSet(),R=this.LA(1),O=2;;){var N=R.tokenType;if(E.contains(H,N))return N;R=this.LA(O),O++}},Y.prototype.getCurrFollowKey=function(){if(this.RULE_STACK.length===1)return A.EOF_FOLLOW_KEY;var H=this.getLastExplicitRuleShortName(),R=this.getLastExplicitRuleOccurrenceIndex(),O=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(H),idxInCallingRule:R,inRule:this.shortRuleNameToFullName(O)}},Y.prototype.buildFullFollowKeyStack=function(){var H=this,R=this.RULE_STACK,O=this.RULE_OCCURRENCE_STACK;return E.map(R,function(N,$){return $===0?A.EOF_FOLLOW_KEY:{ruleName:H.shortRuleNameToFullName(N),idxInCallingRule:O[$],inRule:H.shortRuleNameToFullName(R[$-1])}})},Y.prototype.flattenFollowSet=function(){var H=this,R=E.map(this.buildFullFollowKeyStack(),function(O){return H.getFollowSetFromFollowKey(O)});return E.flatten(R)},Y.prototype.getFollowSetFromFollowKey=function(H){if(H===A.EOF_FOLLOW_KEY)return[Q.EOF];var R=H.ruleName+H.idxInCallingRule+I.IN+H.inRule;return this.resyncFollows[R]},Y.prototype.addToResyncTokens=function(H,R){return this.tokenMatcher(H,Q.EOF)||R.push(H),R},Y.prototype.reSyncTo=function(H){for(var R=[],O=this.LA(1);this.tokenMatcher(O,H)===!1;)O=this.SKIP_TOKEN(),this.addToResyncTokens(O,R);return E.dropRight(R)},Y.prototype.attemptInRepetitionRecovery=function(H,R,O,N,$,L,W){},Y.prototype.getCurrentGrammarPath=function(H,R){var O=this.getHumanReadableRuleStack(),N=E.cloneArr(this.RULE_OCCURRENCE_STACK),$={ruleStack:O,occurrenceStack:N,lastTok:H,lastTokOccurrence:R};return $},Y.prototype.getHumanReadableRuleStack=function(){var H=this;return E.map(this.RULE_STACK,function(R){return H.shortRuleNameToFullName(R)})},Y}();A.Recoverable=J;function U(Y,H,R,O,N,$,L){var W=this.getKeyForAutomaticLookahead(O,N),Z=this.firstAfterRepMap[W];if(Z===void 0){var G=this.getCurrRuleFullName(),X=this.getGAstProductions()[G],q=new $(X,N);Z=q.startWalking(),this.firstAfterRepMap[W]=Z}var{token:M,occurrence:F,isEndOfRule:D}=Z;this.RULE_STACK.length===1&&D&&M===void 0&&(M=Q.EOF,F=1),this.shouldInRepetitionRecoveryBeTried(M,F,L)&&this.tryInRepetitionRecovery(Y,H,R,M)}A.attemptInRepetitionRecovery=U}),R7=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.getKeyForAutomaticLookahead=A.AT_LEAST_ONE_SEP_IDX=A.MANY_SEP_IDX=A.AT_LEAST_ONE_IDX=A.MANY_IDX=A.OPTION_IDX=A.OR_IDX=A.BITS_FOR_ALT_IDX=A.BITS_FOR_RULE_IDX=A.BITS_FOR_OCCURRENCE_IDX=A.BITS_FOR_METHOD_TYPE=void 0,A.BITS_FOR_METHOD_TYPE=4,A.BITS_FOR_OCCURRENCE_IDX=8,A.BITS_FOR_RULE_IDX=12,A.BITS_FOR_ALT_IDX=8,A.OR_IDX=1<{Object.defineProperty(A,"__esModule",{value:!0}),A.LooksAhead=void 0;var Q=VU(),E=t0(),B=EB(),I=R7(),C=TU(),K=function(){function J(){}return J.prototype.initLooksAhead=function(U){this.dynamicTokensEnabled=E.has(U,"dynamicTokensEnabled")?U.dynamicTokensEnabled:B.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled,this.maxLookahead=E.has(U,"maxLookahead")?U.maxLookahead:B.DEFAULT_PARSER_CONFIG.maxLookahead,this.lookAheadFuncsCache=E.isES2015MapSupported()?/*@__PURE__*/new Map:[],E.isES2015MapSupported()?(this.getLaFuncFromCache=this.getLaFuncFromMap,this.setLaFuncCache=this.setLaFuncCacheUsingMap):(this.getLaFuncFromCache=this.getLaFuncFromObj,this.setLaFuncCache=this.setLaFuncUsingObj)},J.prototype.preComputeLookaheadFunctions=function(U){var Y=this;E.forEach(U,function(H){Y.TRACE_INIT(H.name+" Rule Lookahead",function(){var R=C.collectMethods(H),O=R.alternation,N=R.repetition,$=R.option,L=R.repetitionMandatory,W=R.repetitionMandatoryWithSeparator,Z=R.repetitionWithSeparator;E.forEach(O,function(G){var X=G.idx===0?"":G.idx;Y.TRACE_INIT(""+C.getProductionDslName(G)+X,function(){var q=Q.buildLookaheadFuncForOr(G.idx,H,G.maxLookahead||Y.maxLookahead,G.hasPredicates,Y.dynamicTokensEnabled,Y.lookAheadBuilderForAlternatives),M=I.getKeyForAutomaticLookahead(Y.fullRuleNameToShort[H.name],I.OR_IDX,G.idx);Y.setLaFuncCache(M,q)})}),E.forEach(N,function(G){Y.computeLookaheadFunc(H,G.idx,I.MANY_IDX,Q.PROD_TYPE.REPETITION,G.maxLookahead,C.getProductionDslName(G))}),E.forEach($,function(G){Y.computeLookaheadFunc(H,G.idx,I.OPTION_IDX,Q.PROD_TYPE.OPTION,G.maxLookahead,C.getProductionDslName(G))}),E.forEach(L,function(G){Y.computeLookaheadFunc(H,G.idx,I.AT_LEAST_ONE_IDX,Q.PROD_TYPE.REPETITION_MANDATORY,G.maxLookahead,C.getProductionDslName(G))}),E.forEach(W,function(G){Y.computeLookaheadFunc(H,G.idx,I.AT_LEAST_ONE_SEP_IDX,Q.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,G.maxLookahead,C.getProductionDslName(G))}),E.forEach(Z,function(G){Y.computeLookaheadFunc(H,G.idx,I.MANY_SEP_IDX,Q.PROD_TYPE.REPETITION_WITH_SEPARATOR,G.maxLookahead,C.getProductionDslName(G))})})})},J.prototype.computeLookaheadFunc=function(U,Y,H,R,O,N){var $=this;this.TRACE_INIT(""+N+(Y===0?"":Y),function(){var L=Q.buildLookaheadFuncForOptionalProd(Y,U,O||$.maxLookahead,$.dynamicTokensEnabled,R,$.lookAheadBuilderForOptional),W=I.getKeyForAutomaticLookahead($.fullRuleNameToShort[U.name],H,Y);$.setLaFuncCache(W,L)})},J.prototype.lookAheadBuilderForOptional=function(U,Y,H){return Q.buildSingleAlternativeLookaheadFunction(U,Y,H)},J.prototype.lookAheadBuilderForAlternatives=function(U,Y,H,R){return Q.buildAlternativesLookAheadFunc(U,Y,H,R)},J.prototype.getKeyForAutomaticLookahead=function(U,Y){var H=this.getLastExplicitRuleShortName();return I.getKeyForAutomaticLookahead(H,U,Y)},J.prototype.getLaFuncFromCache=function(U){},J.prototype.getLaFuncFromMap=function(U){return this.lookAheadFuncsCache.get(U)},J.prototype.getLaFuncFromObj=function(U){return this.lookAheadFuncsCache[U]},J.prototype.setLaFuncCache=function(U,Y){},J.prototype.setLaFuncCacheUsingMap=function(U,Y){this.lookAheadFuncsCache.set(U,Y)},J.prototype.setLaFuncUsingObj=function(U,Y){this.lookAheadFuncsCache[U]=Y},J}();A.LooksAhead=K}),hk=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.addNoneTerminalToCst=A.addTerminalToCst=A.setNodeLocationFull=A.setNodeLocationOnlyOffset=void 0;function Q(C,K){isNaN(C.startOffset)===!0?(C.startOffset=K.startOffset,C.endOffset=K.endOffset):C.endOffset{Object.defineProperty(A,"__esModule",{value:!0}),A.defineNameProp=A.functionName=A.classNameFromInstance=void 0;var Q=t0();function E(K){return I(K.constructor)}A.classNameFromInstance=E;var B="name";function I(K){var J=K.name;return J||"anonymous"}A.functionName=I;function C(K,J){var U=Object.getOwnPropertyDescriptor(K,B);return Q.isUndefined(U)||U.configurable?(Object.defineProperty(K,B,{enumerable:!1,configurable:!0,writable:!1,value:J}),!0):!1}A.defineNameProp=C}),yk=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.validateRedundantMethods=A.validateMissingCstMethods=A.validateVisitor=A.CstVisitorDefinitionError=A.createBaseVisitorConstructorWithDefaults=A.createBaseSemanticVisitorConstructor=A.defaultVisit=void 0;var Q=t0(),E=MX();function B(R,O){for(var N=Q.keys(R),$=N.length,L=0;L<$;L++)for(var W=N[L],Z=R[W],G=Z.length,X=0;X: - `+(""+W.join(` - -`).replace(/\n/g,` - `)))}}};return N.prototype=$,N.prototype.constructor=N,N._RULE_NAMES=O,N}A.createBaseSemanticVisitorConstructor=I;function C(R,O,N){var $=function(){};E.defineNameProp($,R+"BaseSemanticsWithDefaults");var L=Object.create(N.prototype);return Q.forEach(O,function(W){L[W]=B}),$.prototype=L,$.prototype.constructor=$,$}A.createBaseVisitorConstructorWithDefaults=C;var K;(function(R){R[R.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",R[R.MISSING_METHOD=1]="MISSING_METHOD"})(K=A.CstVisitorDefinitionError||(A.CstVisitorDefinitionError={}));function J(R,O){var N=U(R,O),$=H(R,O);return N.concat($)}A.validateVisitor=J;function U(R,O){var N=Q.map(O,function($){if(!Q.isFunction(R[$]))return{msg:"Missing visitor method: <"+$+"> on "+E.functionName(R.constructor)+" CST Visitor.",type:K.MISSING_METHOD,methodName:$}});return Q.compact(N)}A.validateMissingCstMethods=U;var Y=["constructor","visit","validateVisitor"];function H(R,O){var N=[];for(var $ in R)Q.isFunction(R[$])&&!Q.contains(Y,$)&&!Q.contains(O,$)&&N.push({msg:"Redundant visitor method: <"+$+"> on "+E.functionName(R.constructor)+` CST Visitor -There is no Grammar Rule corresponding to this method's name. -`,type:K.REDUNDANT_METHOD,methodName:$});return N}A.validateRedundantMethods=H}),gk=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.TreeBuilder=void 0;var Q=hk(),E=t0(),B=yk(),I=EB(),C=function(){function K(){}return K.prototype.initTreeBuilder=function(J){if(this.CST_STACK=[],this.outputCst=J.outputCst,this.nodeLocationTracking=E.has(J,"nodeLocationTracking")?J.nodeLocationTracking:I.DEFAULT_PARSER_CONFIG.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=E.NOOP,this.cstFinallyStateUpdate=E.NOOP,this.cstPostTerminal=E.NOOP,this.cstPostNonTerminal=E.NOOP,this.cstPostRule=E.NOOP;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Q.setNodeLocationFull,this.setNodeLocationFromNode=Q.setNodeLocationFull,this.cstPostRule=E.NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=E.NOOP,this.setNodeLocationFromNode=E.NOOP,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Q.setNodeLocationOnlyOffset,this.setNodeLocationFromNode=Q.setNodeLocationOnlyOffset,this.cstPostRule=E.NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=E.NOOP,this.setNodeLocationFromNode=E.NOOP,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=E.NOOP,this.setNodeLocationFromNode=E.NOOP,this.cstPostRule=E.NOOP,this.setInitialNodeLocation=E.NOOP;else throw Error('Invalid config option: "'+J.nodeLocationTracking+'"')},K.prototype.setInitialNodeLocationOnlyOffsetRecovery=function(J){J.location={startOffset:NaN,endOffset:NaN}},K.prototype.setInitialNodeLocationOnlyOffsetRegular=function(J){J.location={startOffset:this.LA(1).startOffset,endOffset:NaN}},K.prototype.setInitialNodeLocationFullRecovery=function(J){J.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}},K.prototype.setInitialNodeLocationFullRegular=function(J){var U=this.LA(1);J.location={startOffset:U.startOffset,startLine:U.startLine,startColumn:U.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}},K.prototype.cstInvocationStateUpdate=function(J,U){var Y={name:J,children:{}};this.setInitialNodeLocation(Y),this.CST_STACK.push(Y)},K.prototype.cstFinallyStateUpdate=function(){this.CST_STACK.pop()},K.prototype.cstPostRuleFull=function(J){var U=this.LA(0),Y=J.location;Y.startOffset<=U.startOffset?(Y.endOffset=U.endOffset,Y.endLine=U.endLine,Y.endColumn=U.endColumn):(Y.startOffset=NaN,Y.startLine=NaN,Y.startColumn=NaN)},K.prototype.cstPostRuleOnlyOffset=function(J){var U=this.LA(0),Y=J.location;Y.startOffset<=U.startOffset?Y.endOffset=U.endOffset:Y.startOffset=NaN},K.prototype.cstPostTerminal=function(J,U){var Y=this.CST_STACK[this.CST_STACK.length-1];Q.addTerminalToCst(Y,U,J),this.setNodeLocationFromToken(Y.location,U)},K.prototype.cstPostNonTerminal=function(J,U){var Y=this.CST_STACK[this.CST_STACK.length-1];Q.addNoneTerminalToCst(Y,U,J),this.setNodeLocationFromNode(Y.location,J.location)},K.prototype.getBaseCstVisitorConstructor=function(){if(E.isUndefined(this.baseCstVisitorConstructor)){var J=B.createBaseSemanticVisitorConstructor(this.className,E.keys(this.gastProductionsCache));return this.baseCstVisitorConstructor=J,J}return this.baseCstVisitorConstructor},K.prototype.getBaseCstVisitorConstructorWithDefaults=function(){if(E.isUndefined(this.baseCstVisitorWithDefaultsConstructor)){var J=B.createBaseVisitorConstructorWithDefaults(this.className,E.keys(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=J,J}return this.baseCstVisitorWithDefaultsConstructor},K.prototype.getLastExplicitRuleShortName=function(){var J=this.RULE_STACK;return J[J.length-1]},K.prototype.getPreviousExplicitRuleShortName=function(){var J=this.RULE_STACK;return J[J.length-2]},K.prototype.getLastExplicitRuleOccurrenceIndex=function(){var J=this.RULE_OCCURRENCE_STACK;return J[J.length-1]},K}();A.TreeBuilder=C}),xk=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.LexerAdapter=void 0;var Q=EB(),E=function(){function B(){}return B.prototype.initLexerAdapter=function(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1},Object.defineProperty(B.prototype,"input",{get:function(){return this.tokVector},set:function(I){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=I,this.tokVectorLength=I.length},enumerable:!1,configurable:!0}),B.prototype.SKIP_TOKEN=function(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):Q.END_OF_FILE},B.prototype.LA=function(I){var C=this.currIdx+I;return C<0||this.tokVectorLength<=C?Q.END_OF_FILE:this.tokVector[C]},B.prototype.consumeToken=function(){this.currIdx++},B.prototype.exportLexerState=function(){return this.currIdx},B.prototype.importLexerState=function(I){this.currIdx=I},B.prototype.resetLexerState=function(){this.currIdx=-1},B.prototype.moveToTerminatedState=function(){this.currIdx=this.tokVector.length-1},B.prototype.getLexerPosition=function(){return this.exportLexerState()},B}();A.LexerAdapter=E}),bk=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.RecognizerApi=void 0;var Q=t0(),E=DK(),B=EB(),I=zU(),C=FX(),K=mE(),J=function(){function U(){}return U.prototype.ACTION=function(Y){return Y.call(this)},U.prototype.consume=function(Y,H,R){return this.consumeInternal(H,Y,R)},U.prototype.subrule=function(Y,H,R){return this.subruleInternal(H,Y,R)},U.prototype.option=function(Y,H){return this.optionInternal(H,Y)},U.prototype.or=function(Y,H){return this.orInternal(H,Y)},U.prototype.many=function(Y,H){return this.manyInternal(Y,H)},U.prototype.atLeastOne=function(Y,H){return this.atLeastOneInternal(Y,H)},U.prototype.CONSUME=function(Y,H){return this.consumeInternal(Y,0,H)},U.prototype.CONSUME1=function(Y,H){return this.consumeInternal(Y,1,H)},U.prototype.CONSUME2=function(Y,H){return this.consumeInternal(Y,2,H)},U.prototype.CONSUME3=function(Y,H){return this.consumeInternal(Y,3,H)},U.prototype.CONSUME4=function(Y,H){return this.consumeInternal(Y,4,H)},U.prototype.CONSUME5=function(Y,H){return this.consumeInternal(Y,5,H)},U.prototype.CONSUME6=function(Y,H){return this.consumeInternal(Y,6,H)},U.prototype.CONSUME7=function(Y,H){return this.consumeInternal(Y,7,H)},U.prototype.CONSUME8=function(Y,H){return this.consumeInternal(Y,8,H)},U.prototype.CONSUME9=function(Y,H){return this.consumeInternal(Y,9,H)},U.prototype.SUBRULE=function(Y,H){return this.subruleInternal(Y,0,H)},U.prototype.SUBRULE1=function(Y,H){return this.subruleInternal(Y,1,H)},U.prototype.SUBRULE2=function(Y,H){return this.subruleInternal(Y,2,H)},U.prototype.SUBRULE3=function(Y,H){return this.subruleInternal(Y,3,H)},U.prototype.SUBRULE4=function(Y,H){return this.subruleInternal(Y,4,H)},U.prototype.SUBRULE5=function(Y,H){return this.subruleInternal(Y,5,H)},U.prototype.SUBRULE6=function(Y,H){return this.subruleInternal(Y,6,H)},U.prototype.SUBRULE7=function(Y,H){return this.subruleInternal(Y,7,H)},U.prototype.SUBRULE8=function(Y,H){return this.subruleInternal(Y,8,H)},U.prototype.SUBRULE9=function(Y,H){return this.subruleInternal(Y,9,H)},U.prototype.OPTION=function(Y){return this.optionInternal(Y,0)},U.prototype.OPTION1=function(Y){return this.optionInternal(Y,1)},U.prototype.OPTION2=function(Y){return this.optionInternal(Y,2)},U.prototype.OPTION3=function(Y){return this.optionInternal(Y,3)},U.prototype.OPTION4=function(Y){return this.optionInternal(Y,4)},U.prototype.OPTION5=function(Y){return this.optionInternal(Y,5)},U.prototype.OPTION6=function(Y){return this.optionInternal(Y,6)},U.prototype.OPTION7=function(Y){return this.optionInternal(Y,7)},U.prototype.OPTION8=function(Y){return this.optionInternal(Y,8)},U.prototype.OPTION9=function(Y){return this.optionInternal(Y,9)},U.prototype.OR=function(Y){return this.orInternal(Y,0)},U.prototype.OR1=function(Y){return this.orInternal(Y,1)},U.prototype.OR2=function(Y){return this.orInternal(Y,2)},U.prototype.OR3=function(Y){return this.orInternal(Y,3)},U.prototype.OR4=function(Y){return this.orInternal(Y,4)},U.prototype.OR5=function(Y){return this.orInternal(Y,5)},U.prototype.OR6=function(Y){return this.orInternal(Y,6)},U.prototype.OR7=function(Y){return this.orInternal(Y,7)},U.prototype.OR8=function(Y){return this.orInternal(Y,8)},U.prototype.OR9=function(Y){return this.orInternal(Y,9)},U.prototype.MANY=function(Y){this.manyInternal(0,Y)},U.prototype.MANY1=function(Y){this.manyInternal(1,Y)},U.prototype.MANY2=function(Y){this.manyInternal(2,Y)},U.prototype.MANY3=function(Y){this.manyInternal(3,Y)},U.prototype.MANY4=function(Y){this.manyInternal(4,Y)},U.prototype.MANY5=function(Y){this.manyInternal(5,Y)},U.prototype.MANY6=function(Y){this.manyInternal(6,Y)},U.prototype.MANY7=function(Y){this.manyInternal(7,Y)},U.prototype.MANY8=function(Y){this.manyInternal(8,Y)},U.prototype.MANY9=function(Y){this.manyInternal(9,Y)},U.prototype.MANY_SEP=function(Y){this.manySepFirstInternal(0,Y)},U.prototype.MANY_SEP1=function(Y){this.manySepFirstInternal(1,Y)},U.prototype.MANY_SEP2=function(Y){this.manySepFirstInternal(2,Y)},U.prototype.MANY_SEP3=function(Y){this.manySepFirstInternal(3,Y)},U.prototype.MANY_SEP4=function(Y){this.manySepFirstInternal(4,Y)},U.prototype.MANY_SEP5=function(Y){this.manySepFirstInternal(5,Y)},U.prototype.MANY_SEP6=function(Y){this.manySepFirstInternal(6,Y)},U.prototype.MANY_SEP7=function(Y){this.manySepFirstInternal(7,Y)},U.prototype.MANY_SEP8=function(Y){this.manySepFirstInternal(8,Y)},U.prototype.MANY_SEP9=function(Y){this.manySepFirstInternal(9,Y)},U.prototype.AT_LEAST_ONE=function(Y){this.atLeastOneInternal(0,Y)},U.prototype.AT_LEAST_ONE1=function(Y){return this.atLeastOneInternal(1,Y)},U.prototype.AT_LEAST_ONE2=function(Y){this.atLeastOneInternal(2,Y)},U.prototype.AT_LEAST_ONE3=function(Y){this.atLeastOneInternal(3,Y)},U.prototype.AT_LEAST_ONE4=function(Y){this.atLeastOneInternal(4,Y)},U.prototype.AT_LEAST_ONE5=function(Y){this.atLeastOneInternal(5,Y)},U.prototype.AT_LEAST_ONE6=function(Y){this.atLeastOneInternal(6,Y)},U.prototype.AT_LEAST_ONE7=function(Y){this.atLeastOneInternal(7,Y)},U.prototype.AT_LEAST_ONE8=function(Y){this.atLeastOneInternal(8,Y)},U.prototype.AT_LEAST_ONE9=function(Y){this.atLeastOneInternal(9,Y)},U.prototype.AT_LEAST_ONE_SEP=function(Y){this.atLeastOneSepFirstInternal(0,Y)},U.prototype.AT_LEAST_ONE_SEP1=function(Y){this.atLeastOneSepFirstInternal(1,Y)},U.prototype.AT_LEAST_ONE_SEP2=function(Y){this.atLeastOneSepFirstInternal(2,Y)},U.prototype.AT_LEAST_ONE_SEP3=function(Y){this.atLeastOneSepFirstInternal(3,Y)},U.prototype.AT_LEAST_ONE_SEP4=function(Y){this.atLeastOneSepFirstInternal(4,Y)},U.prototype.AT_LEAST_ONE_SEP5=function(Y){this.atLeastOneSepFirstInternal(5,Y)},U.prototype.AT_LEAST_ONE_SEP6=function(Y){this.atLeastOneSepFirstInternal(6,Y)},U.prototype.AT_LEAST_ONE_SEP7=function(Y){this.atLeastOneSepFirstInternal(7,Y)},U.prototype.AT_LEAST_ONE_SEP8=function(Y){this.atLeastOneSepFirstInternal(8,Y)},U.prototype.AT_LEAST_ONE_SEP9=function(Y){this.atLeastOneSepFirstInternal(9,Y)},U.prototype.RULE=function(Y,H,R){if(R===void 0&&(R=B.DEFAULT_RULE_CONFIG),Q.contains(this.definedRulesNames,Y)){var O=I.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({topLevelRule:Y,grammarName:this.className}),N={message:O,type:B.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:Y};this.definitionErrors.push(N)}this.definedRulesNames.push(Y);var $=this.defineRule(Y,H,R);return this[Y]=$,$},U.prototype.OVERRIDE_RULE=function(Y,H,R){R===void 0&&(R=B.DEFAULT_RULE_CONFIG);var O=[];O=O.concat(C.validateRuleIsOverridden(Y,this.definedRulesNames,this.className)),this.definitionErrors=this.definitionErrors.concat(O);var N=this.defineRule(Y,H,R);return this[Y]=N,N},U.prototype.BACKTRACK=function(Y,H){return function(){this.isBackTrackingStack.push(1);var R=this.saveRecogState();try{return Y.apply(this,H),!0}catch(O){if(E.isRecognitionException(O))return!1;throw O}finally{this.reloadRecogState(R),this.isBackTrackingStack.pop()}}},U.prototype.getGAstProductions=function(){return this.gastProductionsCache},U.prototype.getSerializedGastProductions=function(){return K.serializeGrammar(Q.values(this.gastProductionsCache))},U}();A.RecognizerApi=J}),fk=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.RecognizerEngine=void 0;var Q=t0(),E=R7(),B=DK(),I=VU(),C=PU(),K=EB(),J=DX(),U=i1(),Y=qK(),H=MX(),R=function(){function O(){}return O.prototype.initRecognizerEngine=function(N,$){if(this.className=H.classNameFromInstance(this),this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=Y.tokenStructuredMatcherNoCategories,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},Q.has($,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. - See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 - For Further details.`);if(Q.isArray(N)){if(Q.isEmpty(N))throw Error(`A Token Vocabulary cannot be empty. - Note that the first argument for the parser constructor - is no longer a Token vector (since v4.0).`);if(typeof N[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. - See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 - For Further details.`)}if(Q.isArray(N))this.tokensMap=Q.reduce(N,function(G,X){return G[X.name]=X,G},{});else if(Q.has(N,"modes")&&Q.every(Q.flatten(Q.values(N.modes)),Y.isTokenType)){var L=Q.flatten(Q.values(N.modes)),W=Q.uniq(L);this.tokensMap=Q.reduce(W,function(G,X){return G[X.name]=X,G},{})}else if(Q.isObject(N))this.tokensMap=Q.cloneObj(N);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=U.EOF;var Z=Q.every(Q.values(N),function(G){return Q.isEmpty(G.categoryMatches)});this.tokenMatcher=Z?Y.tokenStructuredMatcherNoCategories:Y.tokenStructuredMatcher,Y.augmentTokenTypes(Q.values(this.tokensMap))},O.prototype.defineRule=function(N,$,L){if(this.selfAnalysisDone)throw Error("Grammar rule <"+N+`> may not be defined after the 'performSelfAnalysis' method has been called' -Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);var W=Q.has(L,"resyncEnabled")?L.resyncEnabled:K.DEFAULT_RULE_CONFIG.resyncEnabled,Z=Q.has(L,"recoveryValueFunc")?L.recoveryValueFunc:K.DEFAULT_RULE_CONFIG.recoveryValueFunc,G=this.ruleShortNameIdx<$},O.prototype.orInternal=function(N,$){var L=this.getKeyForAutomaticLookahead(E.OR_IDX,$),W=Q.isArray(N)?N:N.DEF,Z=this.getLaFuncFromCache(L),G=Z.call(this,W);if(G!==void 0){var X=W[G];return X.ALT.call(this)}this.raiseNoAltException($,N.ERR_MSG)},O.prototype.ruleFinallyStateUpdate=function(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){var N=this.LA(1),$=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:N,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new B.NotAllInputParsedException($,N))}},O.prototype.subruleInternal=function(N,$,L){var W;try{var Z=L!==void 0?L.ARGS:void 0;return W=N.call(this,$,Z),this.cstPostNonTerminal(W,L!==void 0&&L.LABEL!==void 0?L.LABEL:N.ruleName),W}catch(G){this.subruleInternalError(G,L,N.ruleName)}},O.prototype.subruleInternalError=function(N,$,L){throw B.isRecognitionException(N)&&N.partialCstResult!==void 0&&(this.cstPostNonTerminal(N.partialCstResult,$!==void 0&&$.LABEL!==void 0?$.LABEL:L),delete N.partialCstResult),N},O.prototype.consumeInternal=function(N,$,L){var W;try{var Z=this.LA(1);this.tokenMatcher(Z,N)===!0?(this.consumeToken(),W=Z):this.consumeInternalError(N,Z,L)}catch(G){W=this.consumeInternalRecovery(N,$,G)}return this.cstPostTerminal(L!==void 0&&L.LABEL!==void 0?L.LABEL:N.name,W),W},O.prototype.consumeInternalError=function(N,$,L){var W,Z=this.LA(0);throw L!==void 0&&L.ERR_MSG?W=L.ERR_MSG:W=this.errorMessageProvider.buildMismatchTokenMessage({expected:N,actual:$,previous:Z,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new B.MismatchedTokenException(W,$,Z))},O.prototype.consumeInternalRecovery=function(N,$,L){if(this.recoveryEnabled&&L.name==="MismatchedTokenException"&&!this.isBackTracking()){var W=this.getFollowsForInRuleRecovery(N,$);try{return this.tryInRuleRecovery(N,W)}catch(Z){throw Z.name===J.IN_RULE_RECOVERY_EXCEPTION?L:Z}}else throw L},O.prototype.saveRecogState=function(){var N=this.errors,$=Q.cloneArr(this.RULE_STACK);return{errors:N,lexerState:this.exportLexerState(),RULE_STACK:$,CST_STACK:this.CST_STACK}},O.prototype.reloadRecogState=function(N){this.errors=N.errors,this.importLexerState(N.lexerState),this.RULE_STACK=N.RULE_STACK},O.prototype.ruleInvocationStateUpdate=function(N,$,L){this.RULE_OCCURRENCE_STACK.push(L),this.RULE_STACK.push(N),this.cstInvocationStateUpdate($,N)},O.prototype.isBackTracking=function(){return this.isBackTrackingStack.length!==0},O.prototype.getCurrRuleFullName=function(){var N=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[N]},O.prototype.shortRuleNameToFullName=function(N){return this.shortRuleNameToFull[N]},O.prototype.isAtEndOfInput=function(){return this.tokenMatcher(this.LA(1),U.EOF)},O.prototype.reset=function(){this.resetLexerState(),this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]},O}();A.RecognizerEngine=R}),uk=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.ErrorHandler=void 0;var Q=DK(),E=t0(),B=VU(),I=EB(),C=function(){function K(){}return K.prototype.initErrorHandler=function(J){this._errors=[],this.errorMessageProvider=E.has(J,"errorMessageProvider")?J.errorMessageProvider:I.DEFAULT_PARSER_CONFIG.errorMessageProvider},K.prototype.SAVE_ERROR=function(J){if(Q.isRecognitionException(J))return J.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:E.cloneArr(this.RULE_OCCURRENCE_STACK)},this._errors.push(J),J;throw Error("Trying to save an Error which is not a RecognitionException")},Object.defineProperty(K.prototype,"errors",{get:function(){return E.cloneArr(this._errors)},set:function(J){this._errors=J},enumerable:!1,configurable:!0}),K.prototype.raiseEarlyExitException=function(J,U,Y){for(var H=this.getCurrRuleFullName(),R=this.getGAstProductions()[H],O=B.getLookaheadPathsForOptionalProd(J,R,U,this.maxLookahead),N=O[0],$=[],L=1;L<=this.maxLookahead;L++)$.push(this.LA(L));var W=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:N,actual:$,previous:this.LA(0),customUserDescription:Y,ruleName:H});throw this.SAVE_ERROR(new Q.EarlyExitException(W,this.LA(1),this.LA(0)))},K.prototype.raiseNoAltException=function(J,U){for(var Y=this.getCurrRuleFullName(),H=this.getGAstProductions()[Y],R=B.getLookaheadPathsForOr(J,H,this.maxLookahead),O=[],N=1;N<=this.maxLookahead;N++)O.push(this.LA(N));var $=this.LA(0),L=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:R,actual:O,previous:$,customUserDescription:U,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new Q.NoViableAltException(L,this.LA(1),$))},K}();A.ErrorHandler=C}),pk=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.ContentAssist=void 0;var Q=PU(),E=t0(),B=function(){function I(){}return I.prototype.initContentAssist=function(){},I.prototype.computeContentAssist=function(C,K){var J=this.gastProductionsCache[C];if(E.isUndefined(J))throw Error("Rule ->"+C+"<- does not exist in this grammar.");return Q.nextPossibleTokensAfter([J],K,this.tokenMatcher,this.maxLookahead)},I.prototype.getNextPossibleTokenTypes=function(C){var K=E.first(C.ruleStack),J=this.getGAstProductions(),U=J[K],Y=new Q.NextAfterTokenWalker(U,C).startWalking();return Y},I}();A.ContentAssist=B}),mk=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.GastRecorder=void 0;var Q=t0(),E=mE(),B=SU(),I=qK(),C=i1(),K=EB(),J=R7(),U={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(U);var Y=!0,H=Math.pow(2,J.BITS_FOR_OCCURRENCE_IDX)-1,R=C.createToken({name:"RECORDING_PHASE_TOKEN",pattern:B.Lexer.NA});I.augmentTokenTypes([R]);var O=C.createTokenInstance(R,`This IToken indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(O);var N={name:`This CSTNode indicates the Parser is in Recording Phase - See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}},$=function(){function X(){}return X.prototype.initGastRecorder=function(q){this.recordingProdStack=[],this.RECORDING_PHASE=!1},X.prototype.enableRecording=function(){var q=this;this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",function(){for(var M=function(D){var _=D>0?D:"";q["CONSUME"+_]=function(w,k){return this.consumeInternalRecord(w,D,k)},q["SUBRULE"+_]=function(w,k){return this.subruleInternalRecord(w,D,k)},q["OPTION"+_]=function(w){return this.optionInternalRecord(w,D)},q["OR"+_]=function(w){return this.orInternalRecord(w,D)},q["MANY"+_]=function(w){this.manyInternalRecord(D,w)},q["MANY_SEP"+_]=function(w){this.manySepFirstInternalRecord(D,w)},q["AT_LEAST_ONE"+_]=function(w){this.atLeastOneInternalRecord(D,w)},q["AT_LEAST_ONE_SEP"+_]=function(w){this.atLeastOneSepFirstInternalRecord(D,w)}},F=0;F<10;F++)M(F);q.consume=function(D,_,w){return this.consumeInternalRecord(_,D,w)},q.subrule=function(D,_,w){return this.subruleInternalRecord(_,D,w)},q.option=function(D,_){return this.optionInternalRecord(_,D)},q.or=function(D,_){return this.orInternalRecord(_,D)},q.many=function(D,_){this.manyInternalRecord(D,_)},q.atLeastOne=function(D,_){this.atLeastOneInternalRecord(D,_)},q.ACTION=q.ACTION_RECORD,q.BACKTRACK=q.BACKTRACK_RECORD,q.LA=q.LA_RECORD})},X.prototype.disableRecording=function(){var q=this;this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",function(){for(var M=0;M<10;M++){var F=M>0?M:"";delete q["CONSUME"+F],delete q["SUBRULE"+F],delete q["OPTION"+F],delete q["OR"+F],delete q["MANY"+F],delete q["MANY_SEP"+F],delete q["AT_LEAST_ONE"+F],delete q["AT_LEAST_ONE_SEP"+F]}delete q.consume,delete q.subrule,delete q.option,delete q.or,delete q.many,delete q.atLeastOne,delete q.ACTION,delete q.BACKTRACK,delete q.LA})},X.prototype.ACTION_RECORD=function(q){},X.prototype.BACKTRACK_RECORD=function(q,M){return function(){return!0}},X.prototype.LA_RECORD=function(q){return K.END_OF_FILE},X.prototype.topLevelRuleRecord=function(q,M){try{var F=new E.Rule({definition:[],name:q});return F.name=q,this.recordingProdStack.push(F),M.call(this),this.recordingProdStack.pop(),F}catch(D){if(D.KNOWN_RECORDER_ERROR!==!0)try{D.message=D.message+` - This error was thrown during the "grammar recording phase" For more info see: - https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch(_){throw D}throw D}},X.prototype.optionInternalRecord=function(q,M){return L.call(this,E.Option,q,M)},X.prototype.atLeastOneInternalRecord=function(q,M){L.call(this,E.RepetitionMandatory,M,q)},X.prototype.atLeastOneSepFirstInternalRecord=function(q,M){L.call(this,E.RepetitionMandatoryWithSeparator,M,q,Y)},X.prototype.manyInternalRecord=function(q,M){L.call(this,E.Repetition,M,q)},X.prototype.manySepFirstInternalRecord=function(q,M){L.call(this,E.RepetitionWithSeparator,M,q,Y)},X.prototype.orInternalRecord=function(q,M){return W.call(this,q,M)},X.prototype.subruleInternalRecord=function(q,M,F){if(G(M),!q||Q.has(q,"ruleName")===!1){var D=new Error(" argument is invalid"+(" expecting a Parser method reference but got: <"+JSON.stringify(q)+">")+(` - inside top level rule: <`+this.recordingProdStack[0].name+">"));throw D.KNOWN_RECORDER_ERROR=!0,D}var _=Q.peek(this.recordingProdStack),w=q.ruleName,k=new E.NonTerminal({idx:M,nonTerminalName:w,referencedRule:void 0});return _.definition.push(k),this.outputCst?N:U},X.prototype.consumeInternalRecord=function(q,M,F){if(G(M),!I.hasShortKeyProperty(q)){var D=new Error(" argument is invalid"+(" expecting a TokenType reference but got: <"+JSON.stringify(q)+">")+(` - inside top level rule: <`+this.recordingProdStack[0].name+">"));throw D.KNOWN_RECORDER_ERROR=!0,D}var _=Q.peek(this.recordingProdStack),w=new E.Terminal({idx:M,terminalType:q});return _.definition.push(w),O},X}();A.GastRecorder=$;function L(X,q,M,F){F===void 0&&(F=!1),G(M);var D=Q.peek(this.recordingProdStack),_=Q.isFunction(q)?q:q.DEF,w=new X({definition:[],idx:M});return F&&(w.separator=q.SEP),Q.has(q,"MAX_LOOKAHEAD")&&(w.maxLookahead=q.MAX_LOOKAHEAD),this.recordingProdStack.push(w),_.call(this),D.definition.push(w),this.recordingProdStack.pop(),U}function W(X,q){var M=this;G(q);var F=Q.peek(this.recordingProdStack),D=Q.isArray(X)===!1,_=D===!1?X:X.DEF,w=new E.Alternation({definition:[],idx:q,ignoreAmbiguities:D&&X.IGNORE_AMBIGUITIES===!0});Q.has(X,"MAX_LOOKAHEAD")&&(w.maxLookahead=X.MAX_LOOKAHEAD);var k=Q.some(_,function(T){return Q.isFunction(T.GATE)});return w.hasPredicates=k,F.definition.push(w),Q.forEach(_,function(T){var z=new E.Alternative({definition:[]});w.definition.push(z),Q.has(T,"IGNORE_AMBIGUITIES")?z.ignoreAmbiguities=T.IGNORE_AMBIGUITIES:Q.has(T,"GATE")&&(z.ignoreAmbiguities=!0),M.recordingProdStack.push(z),T.ALT.call(M),M.recordingProdStack.pop()}),U}function Z(X){return X===0?"":""+X}function G(X){if(X<0||X>H){var q=new Error("Invalid DSL Method idx value: <"+X+`> - `+("Idx value must be a none negative value smaller than "+(H+1)));throw q.KNOWN_RECORDER_ERROR=!0,q}}}),ck=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.PerformanceTracer=void 0;var Q=t0(),E=EB(),B=function(){function I(){}return I.prototype.initPerformanceTracer=function(C){if(Q.has(C,"traceInitPerf")){var K=C.traceInitPerf,J=typeof K=="number";this.traceInitMaxIdent=J?K:1/0,this.traceInitPerf=J?K>0:K}else this.traceInitMaxIdent=0,this.traceInitPerf=E.DEFAULT_PARSER_CONFIG.traceInitPerf;this.traceInitIndent=-1},I.prototype.TRACE_INIT=function(C,K){if(this.traceInitPerf===!0){this.traceInitIndent++;var J=new Array(this.traceInitIndent+1).join("\t");this.traceInitIndent <"+C+">");var U=Q.timer(K),Y=U.time,H=U.value,R=Y>10?console.warn:console.log;return this.traceInitIndent time: "+Y+"ms"),this.traceInitIndent--,H}else return K()},I}();A.PerformanceTracer=B}),lk=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.applyMixins=void 0;function Q(E,B){B.forEach(function(I){var C=I.prototype;Object.getOwnPropertyNames(C).forEach(function(K){if(K!=="constructor"){var J=Object.getOwnPropertyDescriptor(C,K);J&&(J.get||J.set)?Object.defineProperty(E.prototype,K,J):E.prototype[K]=I.prototype[K]}})})}A.applyMixins=Q}),EB=P0((A)=>{var Q=A&&A.__extends||function(){var D=function(_,w){return D=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(k,T){k.__proto__=T}||function(k,T){for(var z in T)Object.prototype.hasOwnProperty.call(T,z)&&(k[z]=T[z])},D(_,w)};return function(_,w){if(typeof w!="function"&&w!==null)throw new TypeError("Class extends value "+String(w)+" is not a constructor or null");D(_,w);function k(){this.constructor=_}_.prototype=w===null?Object.create(w):(k.prototype=w.prototype,new k)}}();Object.defineProperty(A,"__esModule",{value:!0}),A.EmbeddedActionsParser=A.CstParser=A.Parser=A.EMPTY_ALT=A.ParserDefinitionErrorType=A.DEFAULT_RULE_CONFIG=A.DEFAULT_PARSER_CONFIG=A.END_OF_FILE=void 0;var E=t0(),B=Pk(),I=i1(),C=zU(),K=jk(),J=DX(),U=vk(),Y=gk(),H=xk(),R=bk(),O=fk(),N=uk(),$=pk(),L=mk(),W=ck(),Z=lk();A.END_OF_FILE=I.createTokenInstance(I.EOF,"",NaN,NaN,NaN,NaN,NaN,NaN),Object.freeze(A.END_OF_FILE),A.DEFAULT_PARSER_CONFIG=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:C.defaultParserErrorProvider,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),A.DEFAULT_RULE_CONFIG=Object.freeze({recoveryValueFunc:function(){},resyncEnabled:!0});var G;(function(D){D[D.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",D[D.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",D[D.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",D[D.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",D[D.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",D[D.LEFT_RECURSION=5]="LEFT_RECURSION",D[D.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",D[D.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",D[D.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",D[D.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",D[D.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",D[D.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",D[D.TOO_MANY_ALTS=12]="TOO_MANY_ALTS"})(G=A.ParserDefinitionErrorType||(A.ParserDefinitionErrorType={}));function X(D){return D===void 0&&(D=void 0),function(){return D}}A.EMPTY_ALT=X;var q=function(){function D(_,w){this.definitionErrors=[],this.selfAnalysisDone=!1;var k=this;if(k.initErrorHandler(w),k.initLexerAdapter(),k.initLooksAhead(w),k.initRecognizerEngine(_,w),k.initRecoverable(w),k.initTreeBuilder(w),k.initContentAssist(),k.initGastRecorder(w),k.initPerformanceTracer(w),E.has(w,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. - Please use the flag on the relevant DSL method instead. - See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES - For further details.`);this.skipValidations=E.has(w,"skipValidations")?w.skipValidations:A.DEFAULT_PARSER_CONFIG.skipValidations}return D.performSelfAnalysis=function(_){throw Error("The **static** `performSelfAnalysis` method has been deprecated.\t\nUse the **instance** method with the same name instead.")},D.prototype.performSelfAnalysis=function(){var _=this;this.TRACE_INIT("performSelfAnalysis",function(){var w;_.selfAnalysisDone=!0;var k=_.className;_.TRACE_INIT("toFastProps",function(){E.toFastProperties(_)}),_.TRACE_INIT("Grammar Recording",function(){try{_.enableRecording(),E.forEach(_.definedRulesNames,function(z){var j=_[z],v=j.originalGrammarAction,g=void 0;_.TRACE_INIT(z+" Rule",function(){g=_.topLevelRuleRecord(z,v)}),_.gastProductionsCache[z]=g})}finally{_.disableRecording()}});var T=[];if(_.TRACE_INIT("Grammar Resolving",function(){T=K.resolveGrammar({rules:E.values(_.gastProductionsCache)}),_.definitionErrors=_.definitionErrors.concat(T)}),_.TRACE_INIT("Grammar Validations",function(){if(E.isEmpty(T)&&_.skipValidations===!1){var z=K.validateGrammar({rules:E.values(_.gastProductionsCache),maxLookahead:_.maxLookahead,tokenTypes:E.values(_.tokensMap),errMsgProvider:C.defaultGrammarValidatorErrorProvider,grammarName:k});_.definitionErrors=_.definitionErrors.concat(z)}}),E.isEmpty(_.definitionErrors)&&(_.recoveryEnabled&&_.TRACE_INIT("computeAllProdsFollows",function(){var z=B.computeAllProdsFollows(E.values(_.gastProductionsCache));_.resyncFollows=z}),_.TRACE_INIT("ComputeLookaheadFunctions",function(){_.preComputeLookaheadFunctions(E.values(_.gastProductionsCache))})),!D.DEFER_DEFINITION_ERRORS_HANDLING&&!E.isEmpty(_.definitionErrors))throw w=E.map(_.definitionErrors,function(z){return z.message}),new Error(`Parser Definition Errors detected: - `+w.join(` -------------------------------- -`))})},D.DEFER_DEFINITION_ERRORS_HANDLING=!1,D}();A.Parser=q,Z.applyMixins(q,[J.Recoverable,U.LooksAhead,Y.TreeBuilder,H.LexerAdapter,O.RecognizerEngine,R.RecognizerApi,N.ErrorHandler,$.ContentAssist,L.GastRecorder,W.PerformanceTracer]);var M=function(D){Q(_,D);function _(w,k){k===void 0&&(k=A.DEFAULT_PARSER_CONFIG);var T=this,z=E.cloneObj(k);return z.outputCst=!0,T=D.call(this,w,z)||this,T}return _}(q);A.CstParser=M;var F=function(D){Q(_,D);function _(w,k){k===void 0&&(k=A.DEFAULT_PARSER_CONFIG);var T=this,z=E.cloneObj(k);return z.outputCst=!1,T=D.call(this,w,z)||this,T}return _}(q);A.EmbeddedActionsParser=F}),dk=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.createSyntaxDiagramsCode=void 0;var Q=WX();function E(B,I){var C=I===void 0?{}:I,K=C.resourceBase,J=K===void 0?"https://unpkg.com/chevrotain@"+Q.VERSION+"/diagrams/":K,U=C.css,Y=U===void 0?"https://unpkg.com/chevrotain@"+Q.VERSION+"/diagrams/diagrams.css":U,H=` - - - - - -`,R=` - -`,O=` - - - - -`,N=` -
-`,$=` - -`,L=` - -`;return H+R+O+N+$+L}A.createSyntaxDiagramsCode=E}),nk=P0((A)=>{Object.defineProperty(A,"__esModule",{value:!0}),A.Parser=A.createSyntaxDiagramsCode=A.clearCache=A.GAstVisitor=A.serializeProduction=A.serializeGrammar=A.Terminal=A.Rule=A.RepetitionWithSeparator=A.RepetitionMandatoryWithSeparator=A.RepetitionMandatory=A.Repetition=A.Option=A.NonTerminal=A.Alternative=A.Alternation=A.defaultLexerErrorProvider=A.NoViableAltException=A.NotAllInputParsedException=A.MismatchedTokenException=A.isRecognitionException=A.EarlyExitException=A.defaultParserErrorProvider=A.tokenName=A.tokenMatcher=A.tokenLabel=A.EOF=A.createTokenInstance=A.createToken=A.LexerDefinitionErrorType=A.Lexer=A.EMPTY_ALT=A.ParserDefinitionErrorType=A.EmbeddedActionsParser=A.CstParser=A.VERSION=void 0;var Q=WX();Object.defineProperty(A,"VERSION",{enumerable:!0,get:function(){return Q.VERSION}});var E=EB();Object.defineProperty(A,"CstParser",{enumerable:!0,get:function(){return E.CstParser}}),Object.defineProperty(A,"EmbeddedActionsParser",{enumerable:!0,get:function(){return E.EmbeddedActionsParser}}),Object.defineProperty(A,"ParserDefinitionErrorType",{enumerable:!0,get:function(){return E.ParserDefinitionErrorType}}),Object.defineProperty(A,"EMPTY_ALT",{enumerable:!0,get:function(){return E.EMPTY_ALT}});var B=SU();Object.defineProperty(A,"Lexer",{enumerable:!0,get:function(){return B.Lexer}}),Object.defineProperty(A,"LexerDefinitionErrorType",{enumerable:!0,get:function(){return B.LexerDefinitionErrorType}});var I=i1();Object.defineProperty(A,"createToken",{enumerable:!0,get:function(){return I.createToken}}),Object.defineProperty(A,"createTokenInstance",{enumerable:!0,get:function(){return I.createTokenInstance}}),Object.defineProperty(A,"EOF",{enumerable:!0,get:function(){return I.EOF}}),Object.defineProperty(A,"tokenLabel",{enumerable:!0,get:function(){return I.tokenLabel}}),Object.defineProperty(A,"tokenMatcher",{enumerable:!0,get:function(){return I.tokenMatcher}}),Object.defineProperty(A,"tokenName",{enumerable:!0,get:function(){return I.tokenName}});var C=zU();Object.defineProperty(A,"defaultParserErrorProvider",{enumerable:!0,get:function(){return C.defaultParserErrorProvider}});var K=DK();Object.defineProperty(A,"EarlyExitException",{enumerable:!0,get:function(){return K.EarlyExitException}}),Object.defineProperty(A,"isRecognitionException",{enumerable:!0,get:function(){return K.isRecognitionException}}),Object.defineProperty(A,"MismatchedTokenException",{enumerable:!0,get:function(){return K.MismatchedTokenException}}),Object.defineProperty(A,"NotAllInputParsedException",{enumerable:!0,get:function(){return K.NotAllInputParsedException}}),Object.defineProperty(A,"NoViableAltException",{enumerable:!0,get:function(){return K.NoViableAltException}});var J=$X();Object.defineProperty(A,"defaultLexerErrorProvider",{enumerable:!0,get:function(){return J.defaultLexerErrorProvider}});var U=mE();Object.defineProperty(A,"Alternation",{enumerable:!0,get:function(){return U.Alternation}}),Object.defineProperty(A,"Alternative",{enumerable:!0,get:function(){return U.Alternative}}),Object.defineProperty(A,"NonTerminal",{enumerable:!0,get:function(){return U.NonTerminal}}),Object.defineProperty(A,"Option",{enumerable:!0,get:function(){return U.Option}}),Object.defineProperty(A,"Repetition",{enumerable:!0,get:function(){return U.Repetition}}),Object.defineProperty(A,"RepetitionMandatory",{enumerable:!0,get:function(){return U.RepetitionMandatory}}),Object.defineProperty(A,"RepetitionMandatoryWithSeparator",{enumerable:!0,get:function(){return U.RepetitionMandatoryWithSeparator}}),Object.defineProperty(A,"RepetitionWithSeparator",{enumerable:!0,get:function(){return U.RepetitionWithSeparator}}),Object.defineProperty(A,"Rule",{enumerable:!0,get:function(){return U.Rule}}),Object.defineProperty(A,"Terminal",{enumerable:!0,get:function(){return U.Terminal}});var Y=mE();Object.defineProperty(A,"serializeGrammar",{enumerable:!0,get:function(){return Y.serializeGrammar}}),Object.defineProperty(A,"serializeProduction",{enumerable:!0,get:function(){return Y.serializeProduction}});var H=FK();Object.defineProperty(A,"GAstVisitor",{enumerable:!0,get:function(){return H.GAstVisitor}});function R(){console.warn(`The clearCache function was 'soft' removed from the Chevrotain API. - It performs no action other than printing this message. - Please avoid using it as it will be completely removed in the future`)}A.clearCache=R;var O=dk();Object.defineProperty(A,"createSyntaxDiagramsCode",{enumerable:!0,get:function(){return O.createSyntaxDiagramsCode}});var N=function(){function $(){throw new Error(`The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead. -See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_7-0-0`)}return $}();A.Parser=N}),wX=nk();var Nx=wX.CstParser;var Fx={name:"GouraudShader",uniforms:oA.merge([vA.common,vA.specularmap,vA.envmap,vA.aomap,vA.lightmap,vA.emissivemap,vA.fog,vA.lights,{emissive:{value:new a(0)}}]),vertexShader:` - - #define GOURAUD - - varying vec3 vLightFront; - varying vec3 vIndirectFront; - - #ifdef DOUBLE_SIDED - varying vec3 vLightBack; - varying vec3 vIndirectBack; - #endif - - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - - void main() { - - #include - #include - #include - - #include - #include - #include - #include - #include - - #include - #include - #include - #include - #include - #include - - #include - #include - - // inlining legacy - - vec3 diffuse = vec3( 1.0 ); - - vec3 geometryPosition = mvPosition.xyz; - vec3 geometryNormal = normalize( transformedNormal ); - vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz ); - - vec3 backGeometryNormal = - geometryNormal; - - vLightFront = vec3( 0.0 ); - vIndirectFront = vec3( 0.0 ); - #ifdef DOUBLE_SIDED - vLightBack = vec3( 0.0 ); - vIndirectBack = vec3( 0.0 ); - #endif - - IncidentLight directLight; - float dotNL; - vec3 directLightColor_Diffuse; - - vIndirectFront += getAmbientLightIrradiance( ambientLightColor ); - - #if defined( USE_LIGHT_PROBES ) - - vIndirectFront += getLightProbeIrradiance( lightProbe, geometryNormal ); - - #endif - - #ifdef DOUBLE_SIDED - - vIndirectBack += getAmbientLightIrradiance( ambientLightColor ); - - #if defined( USE_LIGHT_PROBES ) - - vIndirectBack += getLightProbeIrradiance( lightProbe, backGeometryNormal ); - - #endif - - #endif - - #if NUM_POINT_LIGHTS > 0 - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { - - getPointLightInfo( pointLights[ i ], geometryPosition, directLight ); - - dotNL = dot( geometryNormal, directLight.direction ); - directLightColor_Diffuse = directLight.color; - - vLightFront += saturate( dotNL ) * directLightColor_Diffuse; - - #ifdef DOUBLE_SIDED - - vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; - - #endif - - } - #pragma unroll_loop_end - - #endif - - #if NUM_SPOT_LIGHTS > 0 - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { - - getSpotLightInfo( spotLights[ i ], geometryPosition, directLight ); - - dotNL = dot( geometryNormal, directLight.direction ); - directLightColor_Diffuse = directLight.color; - - vLightFront += saturate( dotNL ) * directLightColor_Diffuse; - - #ifdef DOUBLE_SIDED - - vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; - - #endif - } - #pragma unroll_loop_end - - #endif - - #if NUM_DIR_LIGHTS > 0 - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { - - getDirectionalLightInfo( directionalLights[ i ], directLight ); - - dotNL = dot( geometryNormal, directLight.direction ); - directLightColor_Diffuse = directLight.color; - - vLightFront += saturate( dotNL ) * directLightColor_Diffuse; - - #ifdef DOUBLE_SIDED - - vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; - - #endif - - } - #pragma unroll_loop_end - - #endif - - #if NUM_HEMI_LIGHTS > 0 - - #pragma unroll_loop_start - for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { - - vIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); - - #ifdef DOUBLE_SIDED - - vIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometryNormal ); - - #endif - - } - #pragma unroll_loop_end - - #endif - - #include - #include - - }`,fragmentShader:` - - #define GOURAUD - - uniform vec3 diffuse; - uniform vec3 emissive; - uniform float opacity; - - varying vec3 vLightFront; - varying vec3 vIndirectFront; - - #ifdef DOUBLE_SIDED - varying vec3 vLightBack; - varying vec3 vIndirectBack; - #endif - - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - - void main() { - - #include - - vec4 diffuseColor = vec4( diffuse, opacity ); - ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); - vec3 totalEmissiveRadiance = emissive; - - #include - #include - #include - #include - #include - #include - #include - - // accumulation - - #ifdef DOUBLE_SIDED - - reflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack; - - #else - - reflectedLight.indirectDiffuse += vIndirectFront; - - #endif - - #ifdef USE_LIGHTMAP - - vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); - vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; - reflectedLight.indirectDiffuse += lightMapIrradiance; - - #endif - - reflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb ); - - #ifdef DOUBLE_SIDED - - reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack; - - #else - - reflectedLight.directDiffuse = vLightFront; - - #endif - - reflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask(); - - // modulation - - #include - - vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; - - #include - - #include - #include - #include - #include - #include - #include - - }`};class jU{constructor(A=new y(0,0,0),Q=new y(0,1,0),E=1){this.start=A,this.end=Q,this.radius=E}clone(){return new jU(this.start.clone(),this.end.clone(),this.radius)}set(A,Q,E){this.start.copy(A),this.end.copy(Q),this.radius=E}copy(A){this.start.copy(A.start),this.end.copy(A.end),this.radius=A.radius}getCenter(A){return A.copy(this.end).add(this.start).multiplyScalar(0.5)}translate(A){this.start.add(A),this.end.add(A)}checkAABBAxis(A,Q,E,B,I,C,K,J,U){return(I-AE+B)return!1;for(let I=0;I<3;I++)if(E=c0.e[0]*k0[0][I]+c0.e[1]*k0[1][I]+c0.e[2]*k0[2][I],B=e0.e[I],Math.abs(NQ[0]*LQ[0][I]+NQ[1]*LQ[1][I]+NQ[2]*LQ[2][I])>E+B)return!1;if(E=c0.e[1]*k0[2][0]+c0.e[2]*k0[1][0],B=e0.e[1]*k0[0][2]+e0.e[2]*k0[0][1],Math.abs(NQ[2]*LQ[1][0]-NQ[1]*LQ[2][0])>E+B)return!1;if(E=c0.e[1]*k0[2][1]+c0.e[2]*k0[1][1],B=e0.e[0]*k0[0][2]+e0.e[2]*k0[0][0],Math.abs(NQ[2]*LQ[1][1]-NQ[1]*LQ[2][1])>E+B)return!1;if(E=c0.e[1]*k0[2][2]+c0.e[2]*k0[1][2],B=e0.e[0]*k0[0][1]+e0.e[1]*k0[0][0],Math.abs(NQ[2]*LQ[1][2]-NQ[1]*LQ[2][2])>E+B)return!1;if(E=c0.e[0]*k0[2][0]+c0.e[2]*k0[0][0],B=e0.e[1]*k0[1][2]+e0.e[2]*k0[1][1],Math.abs(NQ[0]*LQ[2][0]-NQ[2]*LQ[0][0])>E+B)return!1;if(E=c0.e[0]*k0[2][1]+c0.e[2]*k0[0][1],B=e0.e[0]*k0[1][2]+e0.e[2]*k0[1][0],Math.abs(NQ[0]*LQ[2][1]-NQ[2]*LQ[0][1])>E+B)return!1;if(E=c0.e[0]*k0[2][2]+c0.e[2]*k0[0][2],B=e0.e[0]*k0[1][1]+e0.e[1]*k0[1][0],Math.abs(NQ[0]*LQ[2][2]-NQ[2]*LQ[0][2])>E+B)return!1;if(E=c0.e[0]*k0[1][0]+c0.e[1]*k0[0][0],B=e0.e[1]*k0[2][2]+e0.e[2]*k0[2][1],Math.abs(NQ[1]*LQ[0][0]-NQ[0]*LQ[1][0])>E+B)return!1;if(E=c0.e[0]*k0[1][1]+c0.e[1]*k0[0][1],B=e0.e[0]*k0[2][2]+e0.e[2]*k0[2][0],Math.abs(NQ[1]*LQ[0][1]-NQ[0]*LQ[1][1])>E+B)return!1;if(E=c0.e[0]*k0[1][2]+c0.e[1]*k0[0][2],B=e0.e[0]*k0[2][1]+e0.e[1]*k0[2][0],Math.abs(NQ[1]*LQ[0][2]-NQ[0]*LQ[1][2])>E+B)return!1;return!0}intersectsPlane(A){this.rotation.extractBasis(o1,r1,a1);let Q=this.halfSize.x*Math.abs(A.normal.dot(o1))+this.halfSize.y*Math.abs(A.normal.dot(r1))+this.halfSize.z*Math.abs(A.normal.dot(a1)),E=A.normal.dot(this.center)-A.constant;return Math.abs(E)<=Q}intersectRay(A,Q){if(this.getSize(kX),TX.setFromCenterAndSize(cQ.set(0,0,0),kX),vU.setFromMatrix3(this.rotation),vU.setPosition(this.center),zX.copy(vU).invert(),PX.copy(A).applyMatrix4(zX),PX.intersectBox(TX,Q))return Q.applyMatrix4(vU);else return null}intersectsRay(A){return this.intersectRay(A,cQ)!==null}fromBox3(A){return A.getCenter(this.center),A.getSize(this.halfSize).multiplyScalar(0.5),this.rotation.identity(),this}equals(A){return A.center.equals(this.center)&&A.halfSize.equals(this.halfSize)&&A.rotation.equals(this.rotation)}applyMatrix4(A){let Q=A.elements,E=cQ.set(Q[0],Q[1],Q[2]).length(),B=cQ.set(Q[4],Q[5],Q[6]).length(),I=cQ.set(Q[8],Q[9],Q[10]).length();if(A.determinant()<0)E=-E;_B.setFromMatrix4(A);let K=1/E,J=1/B,U=1/I;return _B.elements[0]*=K,_B.elements[1]*=K,_B.elements[2]*=K,_B.elements[3]*=J,_B.elements[4]*=J,_B.elements[5]*=J,_B.elements[6]*=U,_B.elements[7]*=U,_B.elements[8]*=U,this.rotation.multiply(_B),this.halfSize.x*=E,this.halfSize.y*=B,this.halfSize.z*=I,cQ.setFromMatrixPosition(A),this.center.add(cQ),this}}var sk=new VX;var dx=new y,nx=new y,sx=new y,ix=new y,ox=new UQ,rx=new $B,ax=new $B,tx=new KQ,ex=new jU,Ab=new y,Qb=new y,Eb=new y;class MK{constructor(A=Math){this.grad3=[[1,1,0],[-1,1,0],[1,-1,0],[-1,-1,0],[1,0,1],[-1,0,1],[1,0,-1],[-1,0,-1],[0,1,1],[0,-1,1],[0,1,-1],[0,-1,-1]],this.grad4=[[0,1,1,1],[0,1,1,-1],[0,1,-1,1],[0,1,-1,-1],[0,-1,1,1],[0,-1,1,-1],[0,-1,-1,1],[0,-1,-1,-1],[1,0,1,1],[1,0,1,-1],[1,0,-1,1],[1,0,-1,-1],[-1,0,1,1],[-1,0,1,-1],[-1,0,-1,1],[-1,0,-1,-1],[1,1,0,1],[1,1,0,-1],[1,-1,0,1],[1,-1,0,-1],[-1,1,0,1],[-1,1,0,-1],[-1,-1,0,1],[-1,-1,0,-1],[1,1,1,0],[1,1,-1,0],[1,-1,1,0],[1,-1,-1,0],[-1,1,1,0],[-1,1,-1,0],[-1,-1,1,0],[-1,-1,-1,0]],this.p=[];for(let Q=0;Q<256;Q++)this.p[Q]=Math.floor(A.random()*256);this.perm=[];for(let Q=0;Q<512;Q++)this.perm[Q]=this.p[Q&255];this.simplex=[[0,1,2,3],[0,1,3,2],[0,0,0,0],[0,2,3,1],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,2,3,0],[0,2,1,3],[0,0,0,0],[0,3,1,2],[0,3,2,1],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,3,2,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,2,0,3],[0,0,0,0],[1,3,0,2],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,3,0,1],[2,3,1,0],[1,0,2,3],[1,0,3,2],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,0,3,1],[0,0,0,0],[2,1,3,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,0,1,3],[0,0,0,0],[0,0,0,0],[0,0,0,0],[3,0,1,2],[3,0,2,1],[0,0,0,0],[3,1,2,0],[2,1,0,3],[0,0,0,0],[0,0,0,0],[0,0,0,0],[3,1,0,2],[0,0,0,0],[3,2,0,1],[3,2,1,0]]}dot(A,Q,E){return A[0]*Q+A[1]*E}dot3(A,Q,E,B){return A[0]*Q+A[1]*E+A[2]*B}dot4(A,Q,E,B,I){return A[0]*Q+A[1]*E+A[2]*B+A[3]*I}noise(A,Q){let E,B,I,C=0.5*(Math.sqrt(3)-1),K=(A+Q)*C,J=Math.floor(A+K),U=Math.floor(Q+K),Y=(3-Math.sqrt(3))/6,H=(J+U)*Y,R=J-H,O=U-H,N=A-R,$=Q-O,L,W;if(N>$)L=1,W=0;else L=0,W=1;let Z=N-L+Y,G=$-W+Y,X=N-1+2*Y,q=$-1+2*Y,M=J&255,F=U&255,D=this.perm[M+this.perm[F]]%12,_=this.perm[M+L+this.perm[F+W]]%12,w=this.perm[M+1+this.perm[F+1]]%12,k=0.5-N*N-$*$;if(k<0)E=0;else k*=k,E=k*k*this.dot(this.grad3[D],N,$);let T=0.5-Z*Z-G*G;if(T<0)B=0;else T*=T,B=T*T*this.dot(this.grad3[_],Z,G);let z=0.5-X*X-q*q;if(z<0)I=0;else z*=z,I=z*z*this.dot(this.grad3[w],X,q);return 70*(E+B+I)}noise3d(A,Q,E){let B,I,C,K,J=0.3333333333333333,U=(A+Q+E)*0.3333333333333333,Y=Math.floor(A+U),H=Math.floor(Q+U),R=Math.floor(E+U),O=0.16666666666666666,N=(Y+H+R)*0.16666666666666666,$=Y-N,L=H-N,W=R-N,Z=A-$,G=Q-L,X=E-W,q,M,F,D,_,w;if(Z>=G)if(G>=X)q=1,M=0,F=0,D=1,_=1,w=0;else if(Z>=X)q=1,M=0,F=0,D=1,_=0,w=1;else q=0,M=0,F=1,D=1,_=0,w=1;else if(Gw?32:0,j=_>k?16:0,v=w>k?8:0,g=_>T?4:0,P=w>T?2:0,V=k>T?1:0,S=z+j+v+g+P+V,h=C[S][0]>=3?1:0,x=C[S][1]>=3?1:0,b=C[S][2]>=3?1:0,m=C[S][3]>=3?1:0,s=C[S][0]>=2?1:0,i=C[S][1]>=2?1:0,n=C[S][2]>=2?1:0,l=C[S][3]>=2?1:0,c=C[S][0]>=1?1:0,o=C[S][1]>=1?1:0,e=C[S][2]>=1?1:0,BA=C[S][3]>=1?1:0,EA=_-h+U,CA=w-x+U,f=k-b+U,NA=T-m+U,YA=_-s+2*U,FA=w-i+2*U,ZA=k-n+2*U,jA=T-l+2*U,wA=_-c+3*U,VA=w-o+3*U,d=k-e+3*U,u=T-BA+3*U,QA=_-1+4*U,t=w-1+4*U,KA=k-1+4*U,HA=T-1+4*U,fA=L&255,zA=W&255,yA=Z&255,qA=G&255,LA=K[fA+K[zA+K[yA+K[qA]]]]%32,_A=K[fA+h+K[zA+x+K[yA+b+K[qA+m]]]]%32,B0=K[fA+s+K[zA+i+K[yA+n+K[qA+l]]]]%32,cA=K[fA+c+K[zA+o+K[yA+e+K[qA+BA]]]]%32,uA=K[fA+1+K[zA+1+K[yA+1+K[qA+1]]]]%32,pA=0.6-_*_-w*w-k*k-T*T;if(pA<0)Y=0;else pA*=pA,Y=pA*pA*this.dot4(I[LA],_,w,k,T);let iA=0.6-EA*EA-CA*CA-f*f-NA*NA;if(iA<0)H=0;else iA*=iA,H=iA*iA*this.dot4(I[_A],EA,CA,f,NA);let $0=0.6-YA*YA-FA*FA-ZA*ZA-jA*jA;if($0<0)R=0;else $0*=$0,R=$0*$0*this.dot4(I[B0],YA,FA,ZA,jA);let IA=0.6-wA*wA-VA*VA-d*d-u*u;if(IA<0)O=0;else IA*=IA,O=IA*IA*this.dot4(I[cA],wA,VA,d,u);let TA=0.6-QA*QA-t*t-KA*KA-HA*HA;if(TA<0)N=0;else TA*=TA,N=TA*TA*this.dot4(I[uA],QA,t,KA,HA);return 27*(Y+H+R+O+N)}}var Ub=new y;var Nb=new y,Gb=new J0,Wb=new y,Xb=new y,$b=new J0,Lb=new y;var lb=new RA;var sb=new y,ib=new y,rb=new y;var eb=new y,Af=new y;class hU extends xA{constructor(){super(hU.Geometry,new _0({opacity:0,transparent:!0}));this.isLensflare=!0,this.type="Lensflare",this.frustumCulled=!1,this.renderOrder=1/0;let A=new y,Q=new y,E=new d8(16,16),B=new d8(16,16),I=x0,C=hU.Geometry,K=new II({uniforms:{scale:{value:null},screenPosition:{value:null}},vertexShader:` - - precision highp float; - - uniform vec3 screenPosition; - uniform vec2 scale; - - attribute vec3 position; - - void main() { - - gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); - - }`,fragmentShader:` - - precision highp float; - - void main() { - - gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 ); - - }`,depthTest:!0,depthWrite:!1,transparent:!1}),J=new II({uniforms:{map:{value:E},scale:{value:null},screenPosition:{value:null}},vertexShader:` - - precision highp float; - - uniform vec3 screenPosition; - uniform vec2 scale; - - attribute vec3 position; - attribute vec2 uv; - - varying vec2 vUV; - - void main() { - - vUV = uv; - - gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); - - }`,fragmentShader:` - - precision highp float; - - uniform sampler2D map; - - varying vec2 vUV; - - void main() { - - gl_FragColor = texture2D( map, vUV ); - - }`,depthTest:!1,depthWrite:!1,transparent:!1}),U=new xA(C,K),Y=[],H=N7.Shader,R=new II({name:H.name,uniforms:{map:{value:null},occlusionMap:{value:B},color:{value:new a(16777215)},scale:{value:new AA},screenPosition:{value:new y}},vertexShader:H.vertexShader,fragmentShader:H.fragmentShader,blending:XE,transparent:!0,depthWrite:!1}),O=new xA(C,R);this.addElement=function(Z){Y.push(Z)};let N=new AA,$=new AA,L=new b1,W=new MA;this.onBeforeRender=function(Z,G,X){Z.getCurrentViewport(W);let q=Z.getRenderTarget(),M=q!==null?q.texture.type:x0;if(I!==M)E.dispose(),B.dispose(),E.type=B.type=M,I=M;let F=W.w/W.z,D=W.z/2,_=W.w/2,w=16/W.w;if(N.set(w*F,w),L.min.set(W.x,W.y),L.max.set(W.x+(W.z-16),W.y+(W.w-16)),Q.setFromMatrixPosition(this.matrixWorld),Q.applyMatrix4(X.matrixWorldInverse),Q.z>0)return;if(A.copy(Q).applyMatrix4(X.projectionMatrix),$.x=W.x+A.x*D+D-8,$.y=W.y+A.y*_+_-8,L.containsPoint($)){Z.copyFramebufferToTexture(E,$);let k=K.uniforms;k.scale.value=N,k.screenPosition.value=A,Z.renderBufferDirect(X,null,C,K,U,null),Z.copyFramebufferToTexture(B,$),k=J.uniforms,k.scale.value=N,k.screenPosition.value=A,Z.renderBufferDirect(X,null,C,J,U,null);let T=-A.x*2,z=-A.y*2;for(let j=0,v=Y.length;j0)return;W.reflect(H).negate(),W.add(R),N.extractRotation(w.matrixWorld),$.set(0,0,-1),$.applyMatrix4(N),$.add(O),Z.subVectors(R,$),Z.reflect(H).negate(),Z.add(R),q.position.copy(W),q.up.set(0,1,0),q.up.applyMatrix4(N),q.up.reflect(H),q.lookAt(Z),q.far=w.far,q.updateMatrixWorld(),q.projectionMatrix.copy(w.projectionMatrix),X.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1),X.multiply(q.projectionMatrix),X.multiply(q.matrixWorldInverse),X.multiply(E.matrixWorld),Y.setFromNormalAndCoplanarPoint(H,R),Y.applyMatrix4(q.matrixWorldInverse),L.set(Y.normal.x,Y.normal.y,Y.normal.z,Y.constant);let k=q.projectionMatrix;G.x=(Math.sign(L.x)+k.elements[8])/k.elements[0],G.y=(Math.sign(L.y)+k.elements[9])/k.elements[5],G.z=-1,G.w=(1+k.elements[10])/k.elements[14],L.multiplyScalar(2/L.dot(G)),k.elements[2]=L.x,k.elements[6]=L.y,k.elements[10]=L.z+1-K,k.elements[14]=L.w,E.visible=!1;let T=D.getRenderTarget(),z=D.xr.enabled,j=D.shadowMap.autoUpdate;if(D.xr.enabled=!1,D.shadowMap.autoUpdate=!1,D.setRenderTarget(M),D.state.buffers.depth.setMask(!0),D.autoClear===!1)D.clear();D.render(_,q),D.xr.enabled=z,D.shadowMap.autoUpdate=j,D.setRenderTarget(T);let v=w.viewport;if(v!==void 0)D.state.viewport(v);E.visible=!0},this.getRenderTarget=function(){return M},this.dispose=function(){M.dispose(),E.material.dispose()}}}k6.ReflectorShader={name:"ReflectorShader",uniforms:{color:{value:null},tDiffuse:{value:null},textureMatrix:{value:null}},vertexShader:` - uniform mat4 textureMatrix; - varying vec4 vUv; - - #include - #include - - void main() { - - vUv = textureMatrix * vec4( position, 1.0 ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - #include - - }`,fragmentShader:` - uniform vec3 color; - uniform sampler2D tDiffuse; - varying vec4 vUv; - - #include - - float blendOverlay( float base, float blend ) { - - return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); - - } - - vec3 blendOverlay( vec3 base, vec3 blend ) { - - return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); - - } - - void main() { - - #include - - vec4 base = texture2DProj( tDiffuse, vUv ); - gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); - - #include - #include - - }`};class sI extends xA{constructor(A,Q={}){super(A);this.isReflectorForSSRPass=!0,this.type="ReflectorForSSRPass";let E=this,B=Q.color!==void 0?new a(Q.color):new a(8355711),I=Q.textureWidth||512,C=Q.textureHeight||512,K=Q.clipBias||0,J=Q.shader||sI.ReflectorShader,U=Q.useDepthTexture===!0,Y=new y(0,1,0),H=new y,R=new y;E.needsUpdate=!1,E.maxDistance=sI.ReflectorShader.uniforms.maxDistance.value,E.opacity=sI.ReflectorShader.uniforms.opacity.value,E.color=B,E.resolution=Q.resolution||new AA(window.innerWidth,window.innerHeight),E._distanceAttenuation=sI.ReflectorShader.defines.DISTANCE_ATTENUATION,Object.defineProperty(E,"distanceAttenuation",{get(){return E._distanceAttenuation},set(T){if(E._distanceAttenuation===T)return;E._distanceAttenuation=T,E.material.defines.DISTANCE_ATTENUATION=T,E.material.needsUpdate=!0}}),E._fresnel=sI.ReflectorShader.defines.FRESNEL,Object.defineProperty(E,"fresnel",{get(){return E._fresnel},set(T){if(E._fresnel===T)return;E._fresnel=T,E.material.defines.FRESNEL=T,E.material.needsUpdate=!0}});let O=new y,N=new y,$=new y,L=new RA,W=new y(0,0,-1),Z=new y,G=new y,X=new RA,q=new v0,M;if(U)M=new IE,M.type=hB,M.minFilter=Z0,M.magFilter=Z0;let D=new Q0(I,C,{depthTexture:U?M:null,type:sA}),_=new bA({name:J.name!==void 0?J.name:"unspecified",transparent:U,defines:Object.assign({},sI.ReflectorShader.defines,{useDepthTexture:U}),uniforms:oA.clone(J.uniforms),fragmentShader:J.fragmentShader,vertexShader:J.vertexShader});if(_.uniforms.tDiffuse.value=D.texture,_.uniforms.color.value=E.color,_.uniforms.textureMatrix.value=X,U)_.uniforms.tDepth.value=D.depthTexture;this.material=_;let k=[new UQ(new y(0,1,0),K)];this.doRender=function(T,z,j){if(_.uniforms.maxDistance.value=E.maxDistance,_.uniforms.color.value=E.color,_.uniforms.opacity.value=E.opacity,H.copy(j.position).normalize(),R.copy(H).reflect(Y),_.uniforms.fresnelCoe.value=(H.dot(R)+1)/2,N.setFromMatrixPosition(E.matrixWorld),$.setFromMatrixPosition(j.matrixWorld),L.extractRotation(E.matrixWorld),O.set(0,0,1),O.applyMatrix4(L),Z.subVectors(N,$),Z.dot(O)>0)return;Z.reflect(O).negate(),Z.add(N),L.extractRotation(j.matrixWorld),W.set(0,0,-1),W.applyMatrix4(L),W.add($),G.subVectors(N,W),G.reflect(O).negate(),G.add(N),q.position.copy(Z),q.up.set(0,1,0),q.up.applyMatrix4(L),q.up.reflect(O),q.lookAt(G),q.far=j.far,q.updateMatrixWorld(),q.projectionMatrix.copy(j.projectionMatrix),_.uniforms.virtualCameraNear.value=j.near,_.uniforms.virtualCameraFar.value=j.far,_.uniforms.virtualCameraMatrixWorld.value=q.matrixWorld,_.uniforms.virtualCameraProjectionMatrix.value=j.projectionMatrix,_.uniforms.virtualCameraProjectionMatrixInverse.value=j.projectionMatrixInverse,_.uniforms.resolution.value=E.resolution,X.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1),X.multiply(q.projectionMatrix),X.multiply(q.matrixWorldInverse),X.multiply(E.matrixWorld);let v=T.getRenderTarget(),g=T.xr.enabled,P=T.shadowMap.autoUpdate,V=T.clippingPlanes;if(T.xr.enabled=!1,T.shadowMap.autoUpdate=!1,T.clippingPlanes=k,T.setRenderTarget(D),T.state.buffers.depth.setMask(!0),T.autoClear===!1)T.clear();T.render(z,q),T.xr.enabled=g,T.shadowMap.autoUpdate=P,T.clippingPlanes=V,T.setRenderTarget(v);let S=j.viewport;if(S!==void 0)T.state.viewport(S)},this.getRenderTarget=function(){return D}}}sI.ReflectorShader={name:"ReflectorShader",defines:{DISTANCE_ATTENUATION:!0,FRESNEL:!0},uniforms:{color:{value:null},tDiffuse:{value:null},tDepth:{value:null},textureMatrix:{value:new RA},maxDistance:{value:180},opacity:{value:0.5},fresnelCoe:{value:null},virtualCameraNear:{value:null},virtualCameraFar:{value:null},virtualCameraProjectionMatrix:{value:new RA},virtualCameraMatrixWorld:{value:new RA},virtualCameraProjectionMatrixInverse:{value:new RA},resolution:{value:new AA}},vertexShader:` - uniform mat4 textureMatrix; - varying vec4 vUv; - - void main() { - - vUv = textureMatrix * vec4( position, 1.0 ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - uniform vec3 color; - uniform sampler2D tDiffuse; - uniform sampler2D tDepth; - uniform float maxDistance; - uniform float opacity; - uniform float fresnelCoe; - uniform float virtualCameraNear; - uniform float virtualCameraFar; - uniform mat4 virtualCameraProjectionMatrix; - uniform mat4 virtualCameraProjectionMatrixInverse; - uniform mat4 virtualCameraMatrixWorld; - uniform vec2 resolution; - varying vec4 vUv; - #include - float blendOverlay( float base, float blend ) { - return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); - } - vec3 blendOverlay( vec3 base, vec3 blend ) { - return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); - } - float getDepth( const in vec2 uv ) { - return texture2D( tDepth, uv ).x; - } - float getViewZ( const in float depth ) { - return perspectiveDepthToViewZ( depth, virtualCameraNear, virtualCameraFar ); - } - vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { - vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc - clipPosition *= clipW; //clip - return ( virtualCameraProjectionMatrixInverse * clipPosition ).xyz;//view - } - void main() { - vec4 base = texture2DProj( tDiffuse, vUv ); - #ifdef useDepthTexture - vec2 uv=(gl_FragCoord.xy-.5)/resolution.xy; - uv.x=1.-uv.x; - float depth = texture2DProj( tDepth, vUv ).r; - float viewZ = getViewZ( depth ); - float clipW = virtualCameraProjectionMatrix[2][3] * viewZ+virtualCameraProjectionMatrix[3][3]; - vec3 viewPosition=getViewPosition( uv, depth, clipW ); - vec3 worldPosition=(virtualCameraMatrixWorld*vec4(viewPosition,1)).xyz; - if(worldPosition.y>maxDistance) discard; - float op=opacity; - #ifdef DISTANCE_ATTENUATION - float ratio=1.-(worldPosition.y/maxDistance); - float attenuation=ratio*ratio; - op=opacity*attenuation; - #endif - #ifdef FRESNEL - op*=fresnelCoe; - #endif - gl_FragColor = vec4( blendOverlay( base.rgb, color ), op ); - #else - gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); - #endif - } - `};class S6 extends xA{constructor(A,Q={}){super(A);this.isRefractor=!0,this.type="Refractor",this.camera=new v0;let E=this,B=Q.color!==void 0?new a(Q.color):new a(8355711),I=Q.textureWidth||512,C=Q.textureHeight||512,K=Q.clipBias||0,J=Q.shader||S6.RefractorShader,U=Q.multisample!==void 0?Q.multisample:4,Y=this.camera;Y.matrixAutoUpdate=!1,Y.userData.refractor=!0;let H=new UQ,R=new RA,O=new Q0(I,C,{samples:U,type:sA});this.material=new bA({name:J.name!==void 0?J.name:"unspecified",uniforms:oA.clone(J.uniforms),vertexShader:J.vertexShader,fragmentShader:J.fragmentShader,transparent:!0}),this.material.uniforms.color.value=B,this.material.uniforms.tDiffuse.value=O.texture,this.material.uniforms.textureMatrix.value=R;let N=function(){let G=new y,X=new y,q=new RA,M=new y,F=new y;return function D(_){return G.setFromMatrixPosition(E.matrixWorld),X.setFromMatrixPosition(_.matrixWorld),M.subVectors(G,X),q.extractRotation(E.matrixWorld),F.set(0,0,1),F.applyMatrix4(q),M.dot(F)<0}}(),$=function(){let G=new y,X=new y,q=new J0,M=new y;return function F(){E.matrixWorld.decompose(X,q,M),G.set(0,0,1).applyQuaternion(q).normalize(),G.negate(),H.setFromNormalAndCoplanarPoint(G,X)}}(),L=function(){let G=new UQ,X=new MA,q=new MA;return function M(F){Y.matrixWorld.copy(F.matrixWorld),Y.matrixWorldInverse.copy(Y.matrixWorld).invert(),Y.projectionMatrix.copy(F.projectionMatrix),Y.far=F.far,G.copy(H),G.applyMatrix4(Y.matrixWorldInverse),X.set(G.normal.x,G.normal.y,G.normal.z,G.constant);let D=Y.projectionMatrix;q.x=(Math.sign(X.x)+D.elements[8])/D.elements[0],q.y=(Math.sign(X.y)+D.elements[9])/D.elements[5],q.z=-1,q.w=(1+D.elements[10])/D.elements[14],X.multiplyScalar(2/X.dot(q)),D.elements[2]=X.x,D.elements[6]=X.y,D.elements[10]=X.z+1-K,D.elements[14]=X.w}}();function W(G){R.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1),R.multiply(G.projectionMatrix),R.multiply(G.matrixWorldInverse),R.multiply(E.matrixWorld)}function Z(G,X,q){E.visible=!1;let M=G.getRenderTarget(),F=G.xr.enabled,D=G.shadowMap.autoUpdate;if(G.xr.enabled=!1,G.shadowMap.autoUpdate=!1,G.setRenderTarget(O),G.autoClear===!1)G.clear();G.render(X,Y),G.xr.enabled=F,G.shadowMap.autoUpdate=D,G.setRenderTarget(M);let _=q.viewport;if(_!==void 0)G.state.viewport(_);E.visible=!0}this.onBeforeRender=function(G,X,q){if(q.userData.refractor===!0)return;if(!N(q)===!0)return;$(),W(q),L(q),Z(G,X,q)},this.getRenderTarget=function(){return O},this.dispose=function(){O.dispose(),E.material.dispose()}}}S6.RefractorShader={name:"RefractorShader",uniforms:{color:{value:null},tDiffuse:{value:null},textureMatrix:{value:null}},vertexShader:` - - uniform mat4 textureMatrix; - - varying vec4 vUv; - - void main() { - - vUv = textureMatrix * vec4( position, 1.0 ); - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform vec3 color; - uniform sampler2D tDiffuse; - - varying vec4 vUv; - - float blendOverlay( float base, float blend ) { - - return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); - - } - - vec3 blendOverlay( vec3 base, vec3 blend ) { - - return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); - - } - - void main() { - - vec4 base = texture2DProj( tDiffuse, vUv ); - gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); - - #include - #include - - }`};var Lf=new RA;class G7 extends xA{constructor(){let A=G7.SkyShader,Q=new bA({name:A.name,uniforms:oA.clone(A.uniforms),vertexShader:A.vertexShader,fragmentShader:A.fragmentShader,side:ZQ,depthWrite:!1});super(new bQ(1,1,1),Q);this.isSky=!0}}G7.SkyShader={name:"SkyShader",uniforms:{turbidity:{value:2},rayleigh:{value:1},mieCoefficient:{value:0.005},mieDirectionalG:{value:0.8},sunPosition:{value:new y},up:{value:new y(0,1,0)}},vertexShader:` - uniform vec3 sunPosition; - uniform float rayleigh; - uniform float turbidity; - uniform float mieCoefficient; - uniform vec3 up; - - varying vec3 vWorldPosition; - varying vec3 vSunDirection; - varying float vSunfade; - varying vec3 vBetaR; - varying vec3 vBetaM; - varying float vSunE; - - // constants for atmospheric scattering - const float e = 2.71828182845904523536028747135266249775724709369995957; - const float pi = 3.141592653589793238462643383279502884197169; - - // wavelength of used primaries, according to preetham - const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 ); - // this pre-calculation replaces older TotalRayleigh(vec3 lambda) function: - // (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn)) - const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 ); - - // mie stuff - // K coefficient for the primaries - const float v = 4.0; - const vec3 K = vec3( 0.686, 0.678, 0.666 ); - // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K - const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 ); - - // earth shadow hack - // cutoffAngle = pi / 1.95; - const float cutoffAngle = 1.6110731556870734; - const float steepness = 1.5; - const float EE = 1000.0; - - float sunIntensity( float zenithAngleCos ) { - zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 ); - return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) ); - } - - vec3 totalMie( float T ) { - float c = ( 0.2 * T ) * 10E-18; - return 0.434 * c * MieConst; - } - - void main() { - - vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); - vWorldPosition = worldPosition.xyz; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - gl_Position.z = gl_Position.w; // set z to camera.far - - vSunDirection = normalize( sunPosition ); - - vSunE = sunIntensity( dot( vSunDirection, up ) ); - - vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 ); - - float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) ); - - // extinction (absorption + out scattering) - // rayleigh coefficients - vBetaR = totalRayleigh * rayleighCoefficient; - - // mie coefficients - vBetaM = totalMie( turbidity ) * mieCoefficient; - - }`,fragmentShader:` - varying vec3 vWorldPosition; - varying vec3 vSunDirection; - varying float vSunfade; - varying vec3 vBetaR; - varying vec3 vBetaM; - varying float vSunE; - - uniform float mieDirectionalG; - uniform vec3 up; - - // constants for atmospheric scattering - const float pi = 3.141592653589793238462643383279502884197169; - - const float n = 1.0003; // refractive index of air - const float N = 2.545E25; // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius) - - // optical length at zenith for molecules - const float rayleighZenithLength = 8.4E3; - const float mieZenithLength = 1.25E3; - // 66 arc seconds -> degrees, and the cosine of that - const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324; - - // 3.0 / ( 16.0 * pi ) - const float THREE_OVER_SIXTEENPI = 0.05968310365946075; - // 1.0 / ( 4.0 * pi ) - const float ONE_OVER_FOURPI = 0.07957747154594767; - - float rayleighPhase( float cosTheta ) { - return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) ); - } - - float hgPhase( float cosTheta, float g ) { - float g2 = pow( g, 2.0 ); - float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 ); - return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse ); - } - - void main() { - - vec3 direction = normalize( vWorldPosition - cameraPosition ); - - // optical length - // cutoff angle at 90 to avoid singularity in next formula. - float zenithAngle = acos( max( 0.0, dot( up, direction ) ) ); - float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) ); - float sR = rayleighZenithLength * inverse; - float sM = mieZenithLength * inverse; - - // combined extinction factor - vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) ); - - // in scattering - float cosTheta = dot( direction, vSunDirection ); - - float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 ); - vec3 betaRTheta = vBetaR * rPhase; - - float mPhase = hgPhase( cosTheta, mieDirectionalG ); - vec3 betaMTheta = vBetaM * mPhase; - - vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) ); - Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) ); - - // nightsky - float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2] - float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2] - vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 ); - vec3 L0 = vec3( 0.1 ) * Fex; - - // composition + solar disc - float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta ); - L0 += ( vSunE * 19000.0 * Fex ) * sundisk; - - vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 ); - - vec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) ); - - gl_FragColor = vec4( retColor, 1.0 ); - - #include - #include - - }`};class yU extends xA{constructor(A,Q={}){super(A);this.isWater=!0,this.type="Water";let E=this,B=Q.color!==void 0?new a(Q.color):new a(16777215),I=Q.textureWidth!==void 0?Q.textureWidth:512,C=Q.textureHeight!==void 0?Q.textureHeight:512,K=Q.clipBias!==void 0?Q.clipBias:0,J=Q.flowDirection!==void 0?Q.flowDirection:new AA(1,0),U=Q.flowSpeed!==void 0?Q.flowSpeed:0.03,Y=Q.reflectivity!==void 0?Q.reflectivity:0.02,H=Q.scale!==void 0?Q.scale:1,R=Q.shader!==void 0?Q.shader:yU.WaterShader,O=new nQ,N=Q.flowMap||void 0,$=Q.normalMap0||O.load("textures/water/Water_1_M_Normal.jpg"),L=Q.normalMap1||O.load("textures/water/Water_2_M_Normal.jpg"),W=0.15,Z=W*0.5,G=new RA,X=new gI;if(k6===void 0){console.error("THREE.Water: Required component Reflector not found.");return}if(S6===void 0){console.error("THREE.Water: Required component Refractor not found.");return}let q=new k6(A,{textureWidth:I,textureHeight:C,clipBias:K}),M=new S6(A,{textureWidth:I,textureHeight:C,clipBias:K});if(q.matrixAutoUpdate=!1,M.matrixAutoUpdate=!1,this.material=new bA({name:R.name,uniforms:oA.merge([vA.fog,R.uniforms]),vertexShader:R.vertexShader,fragmentShader:R.fragmentShader,transparent:!0,fog:!0}),N!==void 0)this.material.defines.USE_FLOWMAP="",this.material.uniforms.tFlowMap={type:"t",value:N};else this.material.uniforms.flowDirection={type:"v2",value:J};$.wrapS=$.wrapT=BQ,L.wrapS=L.wrapT=BQ,this.material.uniforms.tReflectionMap.value=q.getRenderTarget().texture,this.material.uniforms.tRefractionMap.value=M.getRenderTarget().texture,this.material.uniforms.tNormalMap0.value=$,this.material.uniforms.tNormalMap1.value=L,this.material.uniforms.color.value=B,this.material.uniforms.reflectivity.value=Y,this.material.uniforms.textureMatrix.value=G,this.material.uniforms.config.value.x=0,this.material.uniforms.config.value.y=Z,this.material.uniforms.config.value.z=Z,this.material.uniforms.config.value.w=H;function F(_){G.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1),G.multiply(_.projectionMatrix),G.multiply(_.matrixWorldInverse),G.multiply(E.matrixWorld)}function D(){let _=X.getDelta(),w=E.material.uniforms.config;if(w.value.x+=U*_,w.value.y=w.value.x+Z,w.value.x>=W)w.value.x=0,w.value.y=Z;else if(w.value.y>=W)w.value.y=w.value.y-W}this.onBeforeRender=function(_,w,k){F(k),D(),E.visible=!1,q.matrixWorld.copy(E.matrixWorld),M.matrixWorld.copy(E.matrixWorld),q.onBeforeRender(_,w,k),M.onBeforeRender(_,w,k),E.visible=!0}}}yU.WaterShader={name:"WaterShader",uniforms:{color:{type:"c",value:null},reflectivity:{type:"f",value:0},tReflectionMap:{type:"t",value:null},tRefractionMap:{type:"t",value:null},tNormalMap0:{type:"t",value:null},tNormalMap1:{type:"t",value:null},textureMatrix:{type:"m4",value:null},config:{type:"v4",value:new MA}},vertexShader:` - - #include - #include - #include - - uniform mat4 textureMatrix; - - varying vec4 vCoord; - varying vec2 vUv; - varying vec3 vToEye; - - void main() { - - vUv = uv; - vCoord = textureMatrix * vec4( position, 1.0 ); - - vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); - vToEye = cameraPosition - worldPosition.xyz; - - vec4 mvPosition = viewMatrix * worldPosition; // used in fog_vertex - gl_Position = projectionMatrix * mvPosition; - - #include - #include - - }`,fragmentShader:` - - #include - #include - #include - - uniform sampler2D tReflectionMap; - uniform sampler2D tRefractionMap; - uniform sampler2D tNormalMap0; - uniform sampler2D tNormalMap1; - - #ifdef USE_FLOWMAP - uniform sampler2D tFlowMap; - #else - uniform vec2 flowDirection; - #endif - - uniform vec3 color; - uniform float reflectivity; - uniform vec4 config; - - varying vec4 vCoord; - varying vec2 vUv; - varying vec3 vToEye; - - void main() { - - #include - - float flowMapOffset0 = config.x; - float flowMapOffset1 = config.y; - float halfCycle = config.z; - float scale = config.w; - - vec3 toEye = normalize( vToEye ); - - // determine flow direction - vec2 flow; - #ifdef USE_FLOWMAP - flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0; - #else - flow = flowDirection; - #endif - flow.x *= - 1.0; - - // sample normal maps (distort uvs with flowdata) - vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 ); - vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 ); - - // linear interpolate to get the final normal color - float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle; - vec4 normalColor = mix( normalColor0, normalColor1, flowLerp ); - - // calculate normal vector - vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) ); - - // calculate the fresnel term to blend reflection and refraction maps - float theta = max( dot( toEye, normal ), 0.0 ); - float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 ); - - // calculate final uv coords - vec3 coord = vCoord.xyz / vCoord.w; - vec2 uv = coord.xy + coord.z * normal.xz * 0.05; - - vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) ); - vec4 refractColor = texture2D( tRefractionMap, uv ); - - // multiply water color with the mix of both textures - gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance ); - - #include - #include - #include - - }`};var Vf=new y(1,1,1),jf=new y;var GQ={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform float opacity; - - uniform sampler2D tDiffuse; - - varying vec2 vUv; - - void main() { - - vec4 texel = texture2D( tDiffuse, vUv ); - gl_FragColor = opacity * texel; - - - }`};var W7={name:"ConvolutionShader",defines:{KERNEL_SIZE_FLOAT:"25.0",KERNEL_SIZE_INT:"25"},uniforms:{tDiffuse:{value:null},uImageIncrement:{value:new AA(0.001953125,0)},cKernel:{value:[]}},vertexShader:` - - uniform vec2 uImageIncrement; - - varying vec2 vUv; - - void main() { - - vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform float cKernel[ KERNEL_SIZE_INT ]; - - uniform sampler2D tDiffuse; - uniform vec2 uImageIncrement; - - varying vec2 vUv; - - void main() { - - vec2 imageCoord = vUv; - vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 ); - - for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) { - - sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ]; - imageCoord += uImageIncrement; - - } - - gl_FragColor = sum; - - }`,buildKernel:function(A){let E=2*Math.ceil(A*3)+1;if(E>25)E=25;let B=(E-1)*0.5,I=new Array(E),C=0;for(let K=0;K - #include - - #ifndef FRAGMENT_OUTPUT - #define FRAGMENT_OUTPUT vec4(vec3(ao), 1.) - #endif - - vec3 getViewPosition(const in vec2 screenPosition, const in float depth) { - vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); - vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; - return viewSpacePosition.xyz / viewSpacePosition.w; - } - - float getDepth(const vec2 uv) { - return textureLod(tDepth, uv.xy, 0.0).DEPTH_SWIZZLING; - } - - float fetchDepth(const ivec2 uv) { - return texelFetch(tDepth, uv.xy, 0).DEPTH_SWIZZLING; - } - - float getViewZ(const in float depth) { - #if PERSPECTIVE_CAMERA == 1 - return perspectiveDepthToViewZ(depth, cameraNear, cameraFar); - #else - return orthographicDepthToViewZ(depth, cameraNear, cameraFar); - #endif - } - - vec3 computeNormalFromDepth(const vec2 uv) { - vec2 size = vec2(textureSize(tDepth, 0)); - ivec2 p = ivec2(uv * size); - float c0 = fetchDepth(p); - float l2 = fetchDepth(p - ivec2(2, 0)); - float l1 = fetchDepth(p - ivec2(1, 0)); - float r1 = fetchDepth(p + ivec2(1, 0)); - float r2 = fetchDepth(p + ivec2(2, 0)); - float b2 = fetchDepth(p - ivec2(0, 2)); - float b1 = fetchDepth(p - ivec2(0, 1)); - float t1 = fetchDepth(p + ivec2(0, 1)); - float t2 = fetchDepth(p + ivec2(0, 2)); - float dl = abs((2.0 * l1 - l2) - c0); - float dr = abs((2.0 * r1 - r2) - c0); - float db = abs((2.0 * b1 - b2) - c0); - float dt = abs((2.0 * t1 - t2) - c0); - vec3 ce = getViewPosition(uv, c0).xyz; - vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; - vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; - return normalize(cross(dpdx, dpdy)); - } - - vec3 getViewNormal(const vec2 uv) { - #if NORMAL_VECTOR_TYPE == 2 - return normalize(textureLod(tNormal, uv, 0.).rgb); - #elif NORMAL_VECTOR_TYPE == 1 - return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); - #else - return computeNormalFromDepth(uv); - #endif - } - - vec3 getSceneUvAndDepth(vec3 sampleViewPos) { - vec4 sampleClipPos = cameraProjectionMatrix * vec4(sampleViewPos, 1.); - vec2 sampleUv = sampleClipPos.xy / sampleClipPos.w * 0.5 + 0.5; - float sampleSceneDepth = getDepth(sampleUv); - return vec3(sampleUv, sampleSceneDepth); - } - - void main() { - float depth = getDepth(vUv.xy); - if (depth >= 1.0) { - discard; - return; - } - vec3 viewPos = getViewPosition(vUv, depth); - vec3 viewNormal = getViewNormal(vUv); - - float radiusToUse = radius; - float distanceFalloffToUse = thickness; - #if SCREEN_SPACE_RADIUS == 1 - float radiusScale = getViewPosition(vec2(0.5 + float(SCREEN_SPACE_RADIUS_SCALE) / resolution.x, 0.0), depth).x; - radiusToUse *= radiusScale; - distanceFalloffToUse *= radiusScale; - #endif - - #if SCENE_CLIP_BOX == 1 - vec3 worldPos = (cameraWorldMatrix * vec4(viewPos, 1.0)).xyz; - float boxDistance = length(max(vec3(0.0), max(sceneBoxMin - worldPos, worldPos - sceneBoxMax))); - if (boxDistance > radiusToUse) { - discard; - return; - } - #endif - - vec2 noiseResolution = vec2(textureSize(tNoise, 0)); - vec2 noiseUv = vUv * resolution / noiseResolution; - vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); - vec3 randomVec = noiseTexel.xyz * 2.0 - 1.0; - vec3 tangent = normalize(vec3(randomVec.xy, 0.)); - vec3 bitangent = vec3(-tangent.y, tangent.x, 0.); - mat3 kernelMatrix = mat3(tangent, bitangent, vec3(0., 0., 1.)); - - const int DIRECTIONS = SAMPLES < 30 ? 3 : 5; - const int STEPS = (SAMPLES + DIRECTIONS - 1) / DIRECTIONS; - float ao = 0.0; - for (int i = 0; i < DIRECTIONS; ++i) { - - float angle = float(i) / float(DIRECTIONS) * PI; - vec4 sampleDir = vec4(cos(angle), sin(angle), 0., 0.5 + 0.5 * noiseTexel.w); - sampleDir.xyz = normalize(kernelMatrix * sampleDir.xyz); - - vec3 viewDir = normalize(-viewPos.xyz); - vec3 sliceBitangent = normalize(cross(sampleDir.xyz, viewDir)); - vec3 sliceTangent = cross(sliceBitangent, viewDir); - vec3 normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent)); - - vec3 tangentToNormalInSlice = cross(normalInSlice, sliceBitangent); - vec2 cosHorizons = vec2(dot(viewDir, tangentToNormalInSlice), dot(viewDir, -tangentToNormalInSlice)); - - for (int j = 0; j < STEPS; ++j) { - vec3 sampleViewOffset = sampleDir.xyz * radiusToUse * sampleDir.w * pow(float(j + 1) / float(STEPS), distanceExponent); - - vec3 sampleSceneUvDepth = getSceneUvAndDepth(viewPos + sampleViewOffset); - vec3 sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); - vec3 viewDelta = sampleSceneViewPos - viewPos; - if (abs(viewDelta.z) < thickness) { - float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); - cosHorizons.x += max(0., (sampleCosHorizon - cosHorizons.x) * mix(1., 2. / float(j + 2), distanceFallOff)); - } - - sampleSceneUvDepth = getSceneUvAndDepth(viewPos - sampleViewOffset); - sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); - viewDelta = sampleSceneViewPos - viewPos; - if (abs(viewDelta.z) < thickness) { - float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); - cosHorizons.y += max(0., (sampleCosHorizon - cosHorizons.y) * mix(1., 2. / float(j + 2), distanceFallOff)); - } - } - - vec2 sinHorizons = sqrt(1. - cosHorizons * cosHorizons); - float nx = dot(normalInSlice, sliceTangent); - float ny = dot(normalInSlice, viewDir); - float nxb = 1. / 2. * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y); - float nyb = 1. / 2. * (2. - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y); - float occlusion = nx * nxb + ny * nyb; - ao += occlusion; - } - - ao = clamp(ao / float(DIRECTIONS), 0., 1.); - #if SCENE_CLIP_BOX == 1 - ao = mix(ao, 1., smoothstep(0., radiusToUse, boxDistance)); - #endif - ao = pow(ao, scale); - - gl_FragColor = FRAGMENT_OUTPUT; - }`},_K={name:"GTAODepthShader",defines:{PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null}},vertexShader:` - varying vec2 vUv; - - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:` - uniform sampler2D tDepth; - uniform float cameraNear; - uniform float cameraFar; - varying vec2 vUv; - - #include - - float getLinearDepth( const in vec2 screenPosition ) { - #if PERSPECTIVE_CAMERA == 1 - float fragCoordZ = texture2D( tDepth, screenPosition ).x; - float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); - return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); - #else - return texture2D( tDepth, screenPosition ).x; - #endif - } - - void main() { - float depth = getLinearDepth( vUv ); - gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); - - }`},xU={name:"GTAOBlendShader",uniforms:{tDiffuse:{value:null},intensity:{value:1}},vertexShader:` - varying vec2 vUv; - - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:` - uniform float intensity; - uniform sampler2D tDiffuse; - varying vec2 vUv; - - void main() { - vec4 texel = texture2D( tDiffuse, vUv ); - gl_FragColor = vec4(mix(vec3(1.), texel.rgb, intensity), texel.a); - }`};function jX(A=5){let Q=Math.floor(A)%2===0?Math.floor(A)+1:Math.floor(A),E=ek(Q),B=E.length,I=new Uint8Array(B*4);for(let K=0;K - #include - - #ifndef SAMPLE_LUMINANCE - #define SAMPLE_LUMINANCE dot(vec3(0.2125, 0.7154, 0.0721), a) - #endif - - #ifndef FRAGMENT_OUTPUT - #define FRAGMENT_OUTPUT vec4(denoised, 1.) - #endif - - float getLuminance(const in vec3 a) { - return SAMPLE_LUMINANCE; - } - - const vec3 poissonDisk[SAMPLES] = SAMPLE_VECTORS; - - vec3 getViewPosition(const in vec2 screenPosition, const in float depth) { - vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); - vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; - return viewSpacePosition.xyz / viewSpacePosition.w; - } - - float getDepth(const vec2 uv) { - #if DEPTH_VALUE_SOURCE == 1 - return textureLod(tDepth, uv.xy, 0.0).a; - #else - return textureLod(tDepth, uv.xy, 0.0).r; - #endif - } - - float fetchDepth(const ivec2 uv) { - #if DEPTH_VALUE_SOURCE == 1 - return texelFetch(tDepth, uv.xy, 0).a; - #else - return texelFetch(tDepth, uv.xy, 0).r; - #endif - } - - vec3 computeNormalFromDepth(const vec2 uv) { - vec2 size = vec2(textureSize(tDepth, 0)); - ivec2 p = ivec2(uv * size); - float c0 = fetchDepth(p); - float l2 = fetchDepth(p - ivec2(2, 0)); - float l1 = fetchDepth(p - ivec2(1, 0)); - float r1 = fetchDepth(p + ivec2(1, 0)); - float r2 = fetchDepth(p + ivec2(2, 0)); - float b2 = fetchDepth(p - ivec2(0, 2)); - float b1 = fetchDepth(p - ivec2(0, 1)); - float t1 = fetchDepth(p + ivec2(0, 1)); - float t2 = fetchDepth(p + ivec2(0, 2)); - float dl = abs((2.0 * l1 - l2) - c0); - float dr = abs((2.0 * r1 - r2) - c0); - float db = abs((2.0 * b1 - b2) - c0); - float dt = abs((2.0 * t1 - t2) - c0); - vec3 ce = getViewPosition(uv, c0).xyz; - vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz - : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; - vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz - : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; - return normalize(cross(dpdx, dpdy)); - } - - vec3 getViewNormal(const vec2 uv) { - #if NORMAL_VECTOR_TYPE == 2 - return normalize(textureLod(tNormal, uv, 0.).rgb); - #elif NORMAL_VECTOR_TYPE == 1 - return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); - #else - return computeNormalFromDepth(uv); - #endif - } - - void denoiseSample(in vec3 center, in vec3 viewNormal, in vec3 viewPos, in vec2 sampleUv, inout vec3 denoised, inout float totalWeight) { - vec4 sampleTexel = textureLod(tDiffuse, sampleUv, 0.0); - float sampleDepth = getDepth(sampleUv); - vec3 sampleNormal = getViewNormal(sampleUv); - vec3 neighborColor = sampleTexel.rgb; - vec3 viewPosSample = getViewPosition(sampleUv, sampleDepth); - - float normalDiff = dot(viewNormal, sampleNormal); - float normalSimilarity = pow(max(normalDiff, 0.), normalPhi); - float lumaDiff = abs(getLuminance(neighborColor) - getLuminance(center)); - float lumaSimilarity = max(1.0 - lumaDiff / lumaPhi, 0.0); - float depthDiff = abs(dot(viewPos - viewPosSample, viewNormal)); - float depthSimilarity = max(1. - depthDiff / depthPhi, 0.); - float w = lumaSimilarity * depthSimilarity * normalSimilarity; - - denoised += w * neighborColor; - totalWeight += w; - } - - void main() { - float depth = getDepth(vUv.xy); - vec3 viewNormal = getViewNormal(vUv); - if (depth == 1. || dot(viewNormal, viewNormal) == 0.) { - discard; - return; - } - vec4 texel = textureLod(tDiffuse, vUv, 0.0); - vec3 center = texel.rgb; - vec3 viewPos = getViewPosition(vUv, depth); - - vec2 noiseResolution = vec2(textureSize(tNoise, 0)); - vec2 noiseUv = vUv * resolution / noiseResolution; - vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); - vec2 noiseVec = vec2(sin(noiseTexel[index % 4] * 2. * PI), cos(noiseTexel[index % 4] * 2. * PI)); - mat2 rotationMatrix = mat2(noiseVec.x, -noiseVec.y, noiseVec.x, noiseVec.y); - - float totalWeight = 1.0; - vec3 denoised = texel.rgb; - for (int i = 0; i < SAMPLES; i++) { - vec3 sampleDir = poissonDisk[i]; - vec2 offset = rotationMatrix * (sampleDir.xy * (1. + sampleDir.z * (radius - 1.)) / resolution); - vec2 sampleUv = vUv + offset; - denoiseSample(center, viewNormal, viewPos, sampleUv, denoised, totalWeight); - } - - if (totalWeight > 0.) { - denoised /= totalWeight; - } - gl_FragColor = FRAGMENT_OUTPUT; - }`};function X7(A,Q,E){let B=AS(A,Q,E),I="vec3[SAMPLES](";for(let C=0;C cos_t ) ? rad - sin_t * rad : rad - cos_t * rad ) ); - - } - - return rad - dist; - - } - - struct Cell { - - // grid sample positions - vec2 normal; - vec2 p1; - vec2 p2; - vec2 p3; - vec2 p4; - float samp2; - float samp1; - float samp3; - float samp4; - - }; - - vec4 getSample( vec2 point ) { - - // multi-sampled point - vec4 tex = texture2D( tDiffuse, vec2( point.x / width, point.y / height ) ); - float base = rand( vec2( floor( point.x ), floor( point.y ) ) ) * PI2; - float step = PI2 / float( samples ); - float dist = radius * 0.66; - - for ( int i = 0; i < samples; ++i ) { - - float r = base + step * float( i ); - vec2 coord = point + vec2( cos( r ) * dist, sin( r ) * dist ); - tex += texture2D( tDiffuse, vec2( coord.x / width, coord.y / height ) ); - - } - - tex /= float( samples ) + 1.0; - return tex; - - } - - float getDotColour( Cell c, vec2 p, int channel, float angle, float aa ) { - - // get colour for given point - float dist_c_1, dist_c_2, dist_c_3, dist_c_4, res; - - if ( channel == 0 ) { - - c.samp1 = getSample( c.p1 ).r; - c.samp2 = getSample( c.p2 ).r; - c.samp3 = getSample( c.p3 ).r; - c.samp4 = getSample( c.p4 ).r; - - } else if (channel == 1) { - - c.samp1 = getSample( c.p1 ).g; - c.samp2 = getSample( c.p2 ).g; - c.samp3 = getSample( c.p3 ).g; - c.samp4 = getSample( c.p4 ).g; - - } else { - - c.samp1 = getSample( c.p1 ).b; - c.samp3 = getSample( c.p3 ).b; - c.samp2 = getSample( c.p2 ).b; - c.samp4 = getSample( c.p4 ).b; - - } - - dist_c_1 = distanceToDotRadius( c.samp1, c.p1, c.normal, p, angle, radius ); - dist_c_2 = distanceToDotRadius( c.samp2, c.p2, c.normal, p, angle, radius ); - dist_c_3 = distanceToDotRadius( c.samp3, c.p3, c.normal, p, angle, radius ); - dist_c_4 = distanceToDotRadius( c.samp4, c.p4, c.normal, p, angle, radius ); - res = ( dist_c_1 > 0.0 ) ? clamp( dist_c_1 / aa, 0.0, 1.0 ) : 0.0; - res += ( dist_c_2 > 0.0 ) ? clamp( dist_c_2 / aa, 0.0, 1.0 ) : 0.0; - res += ( dist_c_3 > 0.0 ) ? clamp( dist_c_3 / aa, 0.0, 1.0 ) : 0.0; - res += ( dist_c_4 > 0.0 ) ? clamp( dist_c_4 / aa, 0.0, 1.0 ) : 0.0; - res = clamp( res, 0.0, 1.0 ); - - return res; - - } - - Cell getReferenceCell( vec2 p, vec2 origin, float grid_angle, float step ) { - - // get containing cell - Cell c; - - // calc grid - vec2 n = vec2( cos( grid_angle ), sin( grid_angle ) ); - float threshold = step * 0.5; - float dot_normal = n.x * ( p.x - origin.x ) + n.y * ( p.y - origin.y ); - float dot_line = -n.y * ( p.x - origin.x ) + n.x * ( p.y - origin.y ); - vec2 offset = vec2( n.x * dot_normal, n.y * dot_normal ); - float offset_normal = mod( hypot( offset.x, offset.y ), step ); - float normal_dir = ( dot_normal < 0.0 ) ? 1.0 : -1.0; - float normal_scale = ( ( offset_normal < threshold ) ? -offset_normal : step - offset_normal ) * normal_dir; - float offset_line = mod( hypot( ( p.x - offset.x ) - origin.x, ( p.y - offset.y ) - origin.y ), step ); - float line_dir = ( dot_line < 0.0 ) ? 1.0 : -1.0; - float line_scale = ( ( offset_line < threshold ) ? -offset_line : step - offset_line ) * line_dir; - - // get closest corner - c.normal = n; - c.p1.x = p.x - n.x * normal_scale + n.y * line_scale; - c.p1.y = p.y - n.y * normal_scale - n.x * line_scale; - - // scatter - if ( scatter != 0.0 ) { - - float off_mag = scatter * threshold * 0.5; - float off_angle = rand( vec2( floor( c.p1.x ), floor( c.p1.y ) ) ) * PI2; - c.p1.x += cos( off_angle ) * off_mag; - c.p1.y += sin( off_angle ) * off_mag; - - } - - // find corners - float normal_step = normal_dir * ( ( offset_normal < threshold ) ? step : -step ); - float line_step = line_dir * ( ( offset_line < threshold ) ? step : -step ); - c.p2.x = c.p1.x - n.x * normal_step; - c.p2.y = c.p1.y - n.y * normal_step; - c.p3.x = c.p1.x + n.y * line_step; - c.p3.y = c.p1.y - n.x * line_step; - c.p4.x = c.p1.x - n.x * normal_step + n.y * line_step; - c.p4.y = c.p1.y - n.y * normal_step - n.x * line_step; - - return c; - - } - - float blendColour( float a, float b, float t ) { - - // blend colours - if ( blendingMode == BLENDING_LINEAR ) { - return blend( a, b, 1.0 - t ); - } else if ( blendingMode == BLENDING_ADD ) { - return blend( a, min( 1.0, a + b ), t ); - } else if ( blendingMode == BLENDING_MULTIPLY ) { - return blend( a, max( 0.0, a * b ), t ); - } else if ( blendingMode == BLENDING_LIGHTER ) { - return blend( a, max( a, b ), t ); - } else if ( blendingMode == BLENDING_DARKER ) { - return blend( a, min( a, b ), t ); - } else { - return blend( a, b, 1.0 - t ); - } - - } - - void main() { - - if ( ! disable ) { - - // setup - vec2 p = vec2( vUV.x * width, vUV.y * height ); - vec2 origin = vec2( 0, 0 ); - float aa = ( radius < 2.5 ) ? radius * 0.5 : 1.25; - - // get channel samples - Cell cell_r = getReferenceCell( p, origin, rotateR, radius ); - Cell cell_g = getReferenceCell( p, origin, rotateG, radius ); - Cell cell_b = getReferenceCell( p, origin, rotateB, radius ); - float r = getDotColour( cell_r, p, 0, rotateR, aa ); - float g = getDotColour( cell_g, p, 1, rotateG, aa ); - float b = getDotColour( cell_b, p, 2, rotateB, aa ); - - // blend with original - vec4 colour = texture2D( tDiffuse, vUV ); - r = blendColour( r, colour.r, blending ); - g = blendColour( g, colour.g, blending ); - b = blendColour( b, colour.b, blending ); - - if ( greyscale ) { - r = g = b = (r + b + g) / 3.0; - } - - gl_FragColor = vec4( r, g, b, 1.0 ); - - } else { - - gl_FragColor = texture2D( tDiffuse, vUV ); - - } - - }`};class t1 extends s0{constructor(A,Q,E,B){super();this.renderScene=Q,this.renderCamera=E,this.selectedObjects=B!==void 0?B:[],this.visibleEdgeColor=new a(1,1,1),this.hiddenEdgeColor=new a(0.1,0.04,0.02),this.edgeGlow=0,this.usePatternTexture=!1,this.edgeThickness=1,this.edgeStrength=3,this.downSampleRatio=2,this.pulsePeriod=0,this._visibilityCache=/*@__PURE__*/new Map,this._selectionCache=/*@__PURE__*/new Set,this.resolution=A!==void 0?new AA(A.x,A.y):new AA(256,256);let I=Math.round(this.resolution.x/this.downSampleRatio),C=Math.round(this.resolution.y/this.downSampleRatio);this.renderTargetMaskBuffer=new Q0(this.resolution.x,this.resolution.y),this.renderTargetMaskBuffer.texture.name="OutlinePass.mask",this.renderTargetMaskBuffer.texture.generateMipmaps=!1,this.depthMaterial=new hI,this.depthMaterial.side=y0,this.depthMaterial.depthPacking=b8,this.depthMaterial.blending=H0,this.prepareMaskMaterial=this.getPrepareMaskMaterial(),this.prepareMaskMaterial.side=y0,this.prepareMaskMaterial.fragmentShader=Y(this.prepareMaskMaterial.fragmentShader,this.renderCamera),this.renderTargetDepthBuffer=new Q0(this.resolution.x,this.resolution.y,{type:sA}),this.renderTargetDepthBuffer.texture.name="OutlinePass.depth",this.renderTargetDepthBuffer.texture.generateMipmaps=!1,this.renderTargetMaskDownSampleBuffer=new Q0(I,C,{type:sA}),this.renderTargetMaskDownSampleBuffer.texture.name="OutlinePass.depthDownSample",this.renderTargetMaskDownSampleBuffer.texture.generateMipmaps=!1,this.renderTargetBlurBuffer1=new Q0(I,C,{type:sA}),this.renderTargetBlurBuffer1.texture.name="OutlinePass.blur1",this.renderTargetBlurBuffer1.texture.generateMipmaps=!1,this.renderTargetBlurBuffer2=new Q0(Math.round(I/2),Math.round(C/2),{type:sA}),this.renderTargetBlurBuffer2.texture.name="OutlinePass.blur2",this.renderTargetBlurBuffer2.texture.generateMipmaps=!1,this.edgeDetectionMaterial=this.getEdgeDetectionMaterial(),this.renderTargetEdgeBuffer1=new Q0(I,C,{type:sA}),this.renderTargetEdgeBuffer1.texture.name="OutlinePass.edge1",this.renderTargetEdgeBuffer1.texture.generateMipmaps=!1,this.renderTargetEdgeBuffer2=new Q0(Math.round(I/2),Math.round(C/2),{type:sA}),this.renderTargetEdgeBuffer2.texture.name="OutlinePass.edge2",this.renderTargetEdgeBuffer2.texture.generateMipmaps=!1;let K=4,J=4;this.separableBlurMaterial1=this.getSeparableBlurMaterial(K),this.separableBlurMaterial1.uniforms.texSize.value.set(I,C),this.separableBlurMaterial1.uniforms.kernelRadius.value=1,this.separableBlurMaterial2=this.getSeparableBlurMaterial(J),this.separableBlurMaterial2.uniforms.texSize.value.set(Math.round(I/2),Math.round(C/2)),this.separableBlurMaterial2.uniforms.kernelRadius.value=J,this.overlayMaterial=this.getOverlayMaterial();let U=GQ;this.copyUniforms=oA.clone(U.uniforms),this.materialCopy=new bA({uniforms:this.copyUniforms,vertexShader:U.vertexShader,fragmentShader:U.fragmentShader,blending:H0,depthTest:!1,depthWrite:!1}),this.enabled=!0,this.needsSwap=!1,this._oldClearColor=new a,this.oldClearAlpha=1,this.fsQuad=new r0(null),this.tempPulseColor1=new a,this.tempPulseColor2=new a,this.textureMatrix=new RA;function Y(H,R){let O=R.isPerspectiveCamera?"perspective":"orthographic";return H.replace(/DEPTH_TO_VIEW_Z/g,O+"DepthToViewZ")}}dispose(){this.renderTargetMaskBuffer.dispose(),this.renderTargetDepthBuffer.dispose(),this.renderTargetMaskDownSampleBuffer.dispose(),this.renderTargetBlurBuffer1.dispose(),this.renderTargetBlurBuffer2.dispose(),this.renderTargetEdgeBuffer1.dispose(),this.renderTargetEdgeBuffer2.dispose(),this.depthMaterial.dispose(),this.prepareMaskMaterial.dispose(),this.edgeDetectionMaterial.dispose(),this.separableBlurMaterial1.dispose(),this.separableBlurMaterial2.dispose(),this.overlayMaterial.dispose(),this.materialCopy.dispose(),this.fsQuad.dispose()}setSize(A,Q){this.renderTargetMaskBuffer.setSize(A,Q),this.renderTargetDepthBuffer.setSize(A,Q);let E=Math.round(A/this.downSampleRatio),B=Math.round(Q/this.downSampleRatio);this.renderTargetMaskDownSampleBuffer.setSize(E,B),this.renderTargetBlurBuffer1.setSize(E,B),this.renderTargetEdgeBuffer1.setSize(E,B),this.separableBlurMaterial1.uniforms.texSize.value.set(E,B),E=Math.round(E/2),B=Math.round(B/2),this.renderTargetBlurBuffer2.setSize(E,B),this.renderTargetEdgeBuffer2.setSize(E,B),this.separableBlurMaterial2.uniforms.texSize.value.set(E,B)}updateSelectionCache(){let A=this._selectionCache;function Q(E){if(E.isMesh)A.add(E)}A.clear();for(let E=0;E0){A.getClearColor(this._oldClearColor),this.oldClearAlpha=A.getClearAlpha();let C=A.autoClear;if(A.autoClear=!1,I)A.state.buffers.stencil.setTest(!1);A.setClearColor(16777215,1),this.updateSelectionCache(),this.changeVisibilityOfSelectedObjects(!1);let K=this.renderScene.background;if(this.renderScene.background=null,this.renderScene.overrideMaterial=this.depthMaterial,A.setRenderTarget(this.renderTargetDepthBuffer),A.clear(),A.render(this.renderScene,this.renderCamera),this.changeVisibilityOfSelectedObjects(!0),this._visibilityCache.clear(),this.updateTextureMatrix(),this.changeVisibilityOfNonSelectedObjects(!1),this.renderScene.overrideMaterial=this.prepareMaskMaterial,this.prepareMaskMaterial.uniforms.cameraNearFar.value.set(this.renderCamera.near,this.renderCamera.far),this.prepareMaskMaterial.uniforms.depthTexture.value=this.renderTargetDepthBuffer.texture,this.prepareMaskMaterial.uniforms.textureMatrix.value=this.textureMatrix,A.setRenderTarget(this.renderTargetMaskBuffer),A.clear(),A.render(this.renderScene,this.renderCamera),this.renderScene.overrideMaterial=null,this.changeVisibilityOfNonSelectedObjects(!0),this._visibilityCache.clear(),this._selectionCache.clear(),this.renderScene.background=K,this.fsQuad.material=this.materialCopy,this.copyUniforms.tDiffuse.value=this.renderTargetMaskBuffer.texture,A.setRenderTarget(this.renderTargetMaskDownSampleBuffer),A.clear(),this.fsQuad.render(A),this.tempPulseColor1.copy(this.visibleEdgeColor),this.tempPulseColor2.copy(this.hiddenEdgeColor),this.pulsePeriod>0){let J=0.625+Math.cos(performance.now()*0.01/this.pulsePeriod)*0.75/2;this.tempPulseColor1.multiplyScalar(J),this.tempPulseColor2.multiplyScalar(J)}if(this.fsQuad.material=this.edgeDetectionMaterial,this.edgeDetectionMaterial.uniforms.maskTexture.value=this.renderTargetMaskDownSampleBuffer.texture,this.edgeDetectionMaterial.uniforms.texSize.value.set(this.renderTargetMaskDownSampleBuffer.width,this.renderTargetMaskDownSampleBuffer.height),this.edgeDetectionMaterial.uniforms.visibleEdgeColor.value=this.tempPulseColor1,this.edgeDetectionMaterial.uniforms.hiddenEdgeColor.value=this.tempPulseColor2,A.setRenderTarget(this.renderTargetEdgeBuffer1),A.clear(),this.fsQuad.render(A),this.fsQuad.material=this.separableBlurMaterial1,this.separableBlurMaterial1.uniforms.colorTexture.value=this.renderTargetEdgeBuffer1.texture,this.separableBlurMaterial1.uniforms.direction.value=t1.BlurDirectionX,this.separableBlurMaterial1.uniforms.kernelRadius.value=this.edgeThickness,A.setRenderTarget(this.renderTargetBlurBuffer1),A.clear(),this.fsQuad.render(A),this.separableBlurMaterial1.uniforms.colorTexture.value=this.renderTargetBlurBuffer1.texture,this.separableBlurMaterial1.uniforms.direction.value=t1.BlurDirectionY,A.setRenderTarget(this.renderTargetEdgeBuffer1),A.clear(),this.fsQuad.render(A),this.fsQuad.material=this.separableBlurMaterial2,this.separableBlurMaterial2.uniforms.colorTexture.value=this.renderTargetEdgeBuffer1.texture,this.separableBlurMaterial2.uniforms.direction.value=t1.BlurDirectionX,A.setRenderTarget(this.renderTargetBlurBuffer2),A.clear(),this.fsQuad.render(A),this.separableBlurMaterial2.uniforms.colorTexture.value=this.renderTargetBlurBuffer2.texture,this.separableBlurMaterial2.uniforms.direction.value=t1.BlurDirectionY,A.setRenderTarget(this.renderTargetEdgeBuffer2),A.clear(),this.fsQuad.render(A),this.fsQuad.material=this.overlayMaterial,this.overlayMaterial.uniforms.maskTexture.value=this.renderTargetMaskBuffer.texture,this.overlayMaterial.uniforms.edgeTexture1.value=this.renderTargetEdgeBuffer1.texture,this.overlayMaterial.uniforms.edgeTexture2.value=this.renderTargetEdgeBuffer2.texture,this.overlayMaterial.uniforms.patternTexture.value=this.patternTexture,this.overlayMaterial.uniforms.edgeStrength.value=this.edgeStrength,this.overlayMaterial.uniforms.edgeGlow.value=this.edgeGlow,this.overlayMaterial.uniforms.usePatternTexture.value=this.usePatternTexture,I)A.state.buffers.stencil.setTest(!0);A.setRenderTarget(E),this.fsQuad.render(A),A.setClearColor(this._oldClearColor,this.oldClearAlpha),A.autoClear=C}if(this.renderToScreen)this.fsQuad.material=this.materialCopy,this.copyUniforms.tDiffuse.value=E.texture,A.setRenderTarget(null),this.fsQuad.render(A)}getPrepareMaskMaterial(){return new bA({uniforms:{depthTexture:{value:null},cameraNearFar:{value:new AA(0.5,0.5)},textureMatrix:{value:null}},vertexShader:`#include - #include - - varying vec4 projTexCoord; - varying vec4 vPosition; - uniform mat4 textureMatrix; - - void main() { - - #include - #include - #include - #include - #include - - vPosition = mvPosition; - - vec4 worldPosition = vec4( transformed, 1.0 ); - - #ifdef USE_INSTANCING - - worldPosition = instanceMatrix * worldPosition; - - #endif - - worldPosition = modelMatrix * worldPosition; - - projTexCoord = textureMatrix * worldPosition; - - }`,fragmentShader:`#include - varying vec4 vPosition; - varying vec4 projTexCoord; - uniform sampler2D depthTexture; - uniform vec2 cameraNearFar; - - void main() { - - float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord )); - float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y ); - float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0; - gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0); - - }`})}getEdgeDetectionMaterial(){return new bA({uniforms:{maskTexture:{value:null},texSize:{value:new AA(0.5,0.5)},visibleEdgeColor:{value:new y(1,1,1)},hiddenEdgeColor:{value:new y(1,1,1)}},vertexShader:`varying vec2 vUv; - - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:`varying vec2 vUv; - - uniform sampler2D maskTexture; - uniform vec2 texSize; - uniform vec3 visibleEdgeColor; - uniform vec3 hiddenEdgeColor; - - void main() { - vec2 invSize = 1.0 / texSize; - vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize); - vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy); - vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy); - vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw); - vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw); - float diff1 = (c1.r - c2.r)*0.5; - float diff2 = (c3.r - c4.r)*0.5; - float d = length( vec2(diff1, diff2) ); - float a1 = min(c1.g, c2.g); - float a2 = min(c3.g, c4.g); - float visibilityFactor = min(a1, a2); - vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor; - gl_FragColor = vec4(edgeColor, 1.0) * vec4(d); - }`})}getSeparableBlurMaterial(A){return new bA({defines:{MAX_RADIUS:A},uniforms:{colorTexture:{value:null},texSize:{value:new AA(0.5,0.5)},direction:{value:new AA(0.5,0.5)},kernelRadius:{value:1}},vertexShader:`varying vec2 vUv; - - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:`#include - varying vec2 vUv; - uniform sampler2D colorTexture; - uniform vec2 texSize; - uniform vec2 direction; - uniform float kernelRadius; - - float gaussianPdf(in float x, in float sigma) { - return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma; - } - - void main() { - vec2 invSize = 1.0 / texSize; - float sigma = kernelRadius/2.0; - float weightSum = gaussianPdf(0.0, sigma); - vec4 diffuseSum = texture2D( colorTexture, vUv) * weightSum; - vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS); - vec2 uvOffset = delta; - for( int i = 1; i <= MAX_RADIUS; i ++ ) { - float x = kernelRadius * float(i) / float(MAX_RADIUS); - float w = gaussianPdf(x, sigma); - vec4 sample1 = texture2D( colorTexture, vUv + uvOffset); - vec4 sample2 = texture2D( colorTexture, vUv - uvOffset); - diffuseSum += ((sample1 + sample2) * w); - weightSum += (2.0 * w); - uvOffset += delta; - } - gl_FragColor = diffuseSum/weightSum; - }`})}getOverlayMaterial(){return new bA({uniforms:{maskTexture:{value:null},edgeTexture1:{value:null},edgeTexture2:{value:null},patternTexture:{value:null},edgeStrength:{value:1},edgeGlow:{value:1},usePatternTexture:{value:0}},vertexShader:`varying vec2 vUv; - - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:`varying vec2 vUv; - - uniform sampler2D maskTexture; - uniform sampler2D edgeTexture1; - uniform sampler2D edgeTexture2; - uniform sampler2D patternTexture; - uniform float edgeStrength; - uniform float edgeGlow; - uniform bool usePatternTexture; - - void main() { - vec4 edgeValue1 = texture2D(edgeTexture1, vUv); - vec4 edgeValue2 = texture2D(edgeTexture2, vUv); - vec4 maskColor = texture2D(maskTexture, vUv); - vec4 patternColor = texture2D(patternTexture, 6.0 * vUv); - float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5; - vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow; - vec4 finalColor = edgeStrength * maskColor.r * edgeValue; - if(usePatternTexture) - finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r); - gl_FragColor = finalColor; - }`,blending:XE,depthTest:!1,depthWrite:!1,transparent:!0})}}t1.BlurDirectionX=new AA(1,0);t1.BlurDirectionY=new AA(0,1);var SK={name:"SAOShader",defines:{NUM_SAMPLES:7,NUM_RINGS:4,DIFFUSE_TEXTURE:0,PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},tDiffuse:{value:null},tNormal:{value:null},size:{value:new AA(512,512)},cameraNear:{value:1},cameraFar:{value:100},cameraProjectionMatrix:{value:new RA},cameraInverseProjectionMatrix:{value:new RA},scale:{value:1},intensity:{value:0.1},bias:{value:0.5},minResolution:{value:0},kernelRadius:{value:100},randomSeed:{value:0}},vertexShader:` - - varying vec2 vUv; - - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:` - #include - - varying vec2 vUv; - - #if DIFFUSE_TEXTURE == 1 - uniform sampler2D tDiffuse; - #endif - - uniform highp sampler2D tDepth; - uniform highp sampler2D tNormal; - - uniform float cameraNear; - uniform float cameraFar; - uniform mat4 cameraProjectionMatrix; - uniform mat4 cameraInverseProjectionMatrix; - - uniform float scale; - uniform float intensity; - uniform float bias; - uniform float kernelRadius; - uniform float minResolution; - uniform vec2 size; - uniform float randomSeed; - - // RGBA depth - - #include - - vec4 getDefaultColor( const in vec2 screenPosition ) { - #if DIFFUSE_TEXTURE == 1 - return texture2D( tDiffuse, vUv ); - #else - return vec4( 1.0 ); - #endif - } - - float getDepth( const in vec2 screenPosition ) { - return texture2D( tDepth, screenPosition ).x; - } - - float getViewZ( const in float depth ) { - #if PERSPECTIVE_CAMERA == 1 - return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); - #else - return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); - #endif - } - - vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) { - float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3]; - vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 ); - clipPosition *= clipW; // unprojection. - - return ( cameraInverseProjectionMatrix * clipPosition ).xyz; - } - - vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPosition ) { - return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); - } - - float scaleDividedByCameraFar; - float minResolutionMultipliedByCameraFar; - - float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) { - vec3 viewDelta = sampleViewPosition - centerViewPosition; - float viewDistance = length( viewDelta ); - float scaledScreenDistance = scaleDividedByCameraFar * viewDistance; - - return max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - bias) / (1.0 + pow2( scaledScreenDistance ) ); - } - - // moving costly divides into consts - const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES ); - const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES ); - - float getAmbientOcclusion( const in vec3 centerViewPosition ) { - // precompute some variables require in getOcclusion. - scaleDividedByCameraFar = scale / cameraFar; - minResolutionMultipliedByCameraFar = minResolution * cameraFar; - vec3 centerViewNormal = getViewNormal( centerViewPosition, vUv ); - - // jsfiddle that shows sample pattern: https://jsfiddle.net/a16ff1p7/ - float angle = rand( vUv + randomSeed ) * PI2; - vec2 radius = vec2( kernelRadius * INV_NUM_SAMPLES ) / size; - vec2 radiusStep = radius; - - float occlusionSum = 0.0; - float weightSum = 0.0; - - for( int i = 0; i < NUM_SAMPLES; i ++ ) { - vec2 sampleUv = vUv + vec2( cos( angle ), sin( angle ) ) * radius; - radius += radiusStep; - angle += ANGLE_STEP; - - float sampleDepth = getDepth( sampleUv ); - if( sampleDepth >= ( 1.0 - EPSILON ) ) { - continue; - } - - float sampleViewZ = getViewZ( sampleDepth ); - vec3 sampleViewPosition = getViewPosition( sampleUv, sampleDepth, sampleViewZ ); - occlusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition ); - weightSum += 1.0; - } - - if( weightSum == 0.0 ) discard; - - return occlusionSum * ( intensity / weightSum ); - } - - void main() { - float centerDepth = getDepth( vUv ); - if( centerDepth >= ( 1.0 - EPSILON ) ) { - discard; - } - - float centerViewZ = getViewZ( centerDepth ); - vec3 viewPosition = getViewPosition( vUv, centerDepth, centerViewZ ); - - float ambientOcclusion = getAmbientOcclusion( viewPosition ); - - gl_FragColor = getDefaultColor( vUv ); - gl_FragColor.xyz *= 1.0 - ambientOcclusion; - }`};var XI={name:"DepthLimitedBlurShader",defines:{KERNEL_RADIUS:4,DEPTH_PACKING:1,PERSPECTIVE_CAMERA:1},uniforms:{tDiffuse:{value:null},size:{value:new AA(512,512)},sampleUvOffsets:{value:[new AA(0,0)]},sampleWeights:{value:[1]},tDepth:{value:null},cameraNear:{value:10},cameraFar:{value:1000},depthCutoff:{value:10}},vertexShader:` - - #include - - uniform vec2 size; - - varying vec2 vUv; - varying vec2 vInvSize; - - void main() { - vUv = uv; - vInvSize = 1.0 / size; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:` - - #include - #include - - uniform sampler2D tDiffuse; - uniform sampler2D tDepth; - - uniform float cameraNear; - uniform float cameraFar; - uniform float depthCutoff; - - uniform vec2 sampleUvOffsets[ KERNEL_RADIUS + 1 ]; - uniform float sampleWeights[ KERNEL_RADIUS + 1 ]; - - varying vec2 vUv; - varying vec2 vInvSize; - - float getDepth( const in vec2 screenPosition ) { - #if DEPTH_PACKING == 1 - return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) ); - #else - return texture2D( tDepth, screenPosition ).x; - #endif - } - - float getViewZ( const in float depth ) { - #if PERSPECTIVE_CAMERA == 1 - return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); - #else - return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); - #endif - } - - void main() { - float depth = getDepth( vUv ); - if( depth >= ( 1.0 - EPSILON ) ) { - discard; - } - - float centerViewZ = -getViewZ( depth ); - bool rBreak = false, lBreak = false; - - float weightSum = sampleWeights[0]; - vec4 diffuseSum = texture2D( tDiffuse, vUv ) * weightSum; - - for( int i = 1; i <= KERNEL_RADIUS; i ++ ) { - - float sampleWeight = sampleWeights[i]; - vec2 sampleUvOffset = sampleUvOffsets[i] * vInvSize; - - vec2 sampleUv = vUv + sampleUvOffset; - float viewZ = -getViewZ( getDepth( sampleUv ) ); - - if( abs( viewZ - centerViewZ ) > depthCutoff ) rBreak = true; - - if( ! rBreak ) { - diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight; - weightSum += sampleWeight; - } - - sampleUv = vUv - sampleUvOffset; - viewZ = -getViewZ( getDepth( sampleUv ) ); - - if( abs( viewZ - centerViewZ ) > depthCutoff ) lBreak = true; - - if( ! lBreak ) { - diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight; - weightSum += sampleWeight; - } - - } - - gl_FragColor = diffuseSum / weightSum; - }`},TK={createSampleWeights:function(A,Q){let E=[];for(let B=0;B<=A;B++)E.push(ES(B,Q));return E},createSampleOffsets:function(A,Q){let E=[];for(let B=0;B<=A;B++)E.push(Q.clone().multiplyScalar(B));return E},configure:function(A,Q,E,B){A.defines.KERNEL_RADIUS=Q,A.uniforms.sampleUvOffsets.value=TK.createSampleOffsets(Q,B),A.uniforms.sampleWeights.value=TK.createSampleWeights(Q,E),A.needsUpdate=!0}};function ES(A,Q){return Math.exp(-(A*A)/(2*(Q*Q)))/(Math.sqrt(2*Math.PI)*Q)}class bU extends s0{constructor(A,Q,E=new AA(256,256)){super();this.scene=A,this.camera=Q,this.clear=!0,this.needsSwap=!1,this.originalClearColor=new a,this._oldClearColor=new a,this.oldClearAlpha=1,this.params={output:0,saoBias:0.5,saoIntensity:0.18,saoScale:1,saoKernelRadius:100,saoMinResolution:0,saoBlur:!0,saoBlurRadius:8,saoBlurStdDev:4,saoBlurDepthCutoff:0.01},this.resolution=new AA(E.x,E.y),this.saoRenderTarget=new Q0(this.resolution.x,this.resolution.y,{type:sA}),this.blurIntermediateRenderTarget=this.saoRenderTarget.clone();let B=new IE;B.format=oE,B.type=VE,this.normalRenderTarget=new Q0(this.resolution.x,this.resolution.y,{minFilter:Z0,magFilter:Z0,type:sA,depthTexture:B}),this.normalMaterial=new gE,this.normalMaterial.blending=H0,this.saoMaterial=new bA({defines:Object.assign({},SK.defines),fragmentShader:SK.fragmentShader,vertexShader:SK.vertexShader,uniforms:oA.clone(SK.uniforms)}),this.saoMaterial.defines.PERSPECTIVE_CAMERA=this.camera.isPerspectiveCamera?1:0,this.saoMaterial.uniforms.tDepth.value=B,this.saoMaterial.uniforms.tNormal.value=this.normalRenderTarget.texture,this.saoMaterial.uniforms.size.value.set(this.resolution.x,this.resolution.y),this.saoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.saoMaterial.uniforms.cameraProjectionMatrix.value=this.camera.projectionMatrix,this.saoMaterial.blending=H0,this.vBlurMaterial=new bA({uniforms:oA.clone(XI.uniforms),defines:Object.assign({},XI.defines),vertexShader:XI.vertexShader,fragmentShader:XI.fragmentShader}),this.vBlurMaterial.defines.DEPTH_PACKING=0,this.vBlurMaterial.defines.PERSPECTIVE_CAMERA=this.camera.isPerspectiveCamera?1:0,this.vBlurMaterial.uniforms.tDiffuse.value=this.saoRenderTarget.texture,this.vBlurMaterial.uniforms.tDepth.value=B,this.vBlurMaterial.uniforms.size.value.set(this.resolution.x,this.resolution.y),this.vBlurMaterial.blending=H0,this.hBlurMaterial=new bA({uniforms:oA.clone(XI.uniforms),defines:Object.assign({},XI.defines),vertexShader:XI.vertexShader,fragmentShader:XI.fragmentShader}),this.hBlurMaterial.defines.DEPTH_PACKING=0,this.hBlurMaterial.defines.PERSPECTIVE_CAMERA=this.camera.isPerspectiveCamera?1:0,this.hBlurMaterial.uniforms.tDiffuse.value=this.blurIntermediateRenderTarget.texture,this.hBlurMaterial.uniforms.tDepth.value=B,this.hBlurMaterial.uniforms.size.value.set(this.resolution.x,this.resolution.y),this.hBlurMaterial.blending=H0,this.materialCopy=new bA({uniforms:oA.clone(GQ.uniforms),vertexShader:GQ.vertexShader,fragmentShader:GQ.fragmentShader,blending:H0}),this.materialCopy.transparent=!0,this.materialCopy.depthTest=!1,this.materialCopy.depthWrite=!1,this.materialCopy.blending=vQ,this.materialCopy.blendSrc=PB,this.materialCopy.blendDst=$E,this.materialCopy.blendEquation=kQ,this.materialCopy.blendSrcAlpha=LE,this.materialCopy.blendDstAlpha=$E,this.materialCopy.blendEquationAlpha=kQ,this.fsQuad=new r0(null)}render(A,Q,E){if(this.renderToScreen)this.materialCopy.blending=H0,this.materialCopy.uniforms.tDiffuse.value=E.texture,this.materialCopy.needsUpdate=!0,this.renderPass(A,this.materialCopy,null);A.getClearColor(this._oldClearColor),this.oldClearAlpha=A.getClearAlpha();let B=A.autoClear;A.autoClear=!1,this.saoMaterial.uniforms.bias.value=this.params.saoBias,this.saoMaterial.uniforms.intensity.value=this.params.saoIntensity,this.saoMaterial.uniforms.scale.value=this.params.saoScale,this.saoMaterial.uniforms.kernelRadius.value=this.params.saoKernelRadius,this.saoMaterial.uniforms.minResolution.value=this.params.saoMinResolution,this.saoMaterial.uniforms.cameraNear.value=this.camera.near,this.saoMaterial.uniforms.cameraFar.value=this.camera.far;let I=this.params.saoBlurDepthCutoff*(this.camera.far-this.camera.near);if(this.vBlurMaterial.uniforms.depthCutoff.value=I,this.hBlurMaterial.uniforms.depthCutoff.value=I,this.vBlurMaterial.uniforms.cameraNear.value=this.camera.near,this.vBlurMaterial.uniforms.cameraFar.value=this.camera.far,this.hBlurMaterial.uniforms.cameraNear.value=this.camera.near,this.hBlurMaterial.uniforms.cameraFar.value=this.camera.far,this.params.saoBlurRadius=Math.floor(this.params.saoBlurRadius),this.prevStdDev!==this.params.saoBlurStdDev||this.prevNumSamples!==this.params.saoBlurRadius)TK.configure(this.vBlurMaterial,this.params.saoBlurRadius,this.params.saoBlurStdDev,new AA(0,1)),TK.configure(this.hBlurMaterial,this.params.saoBlurRadius,this.params.saoBlurStdDev,new AA(1,0)),this.prevStdDev=this.params.saoBlurStdDev,this.prevNumSamples=this.params.saoBlurRadius;if(this.renderOverride(A,this.normalMaterial,this.normalRenderTarget,7829503,1),this.renderPass(A,this.saoMaterial,this.saoRenderTarget,16777215,1),this.params.saoBlur)this.renderPass(A,this.vBlurMaterial,this.blurIntermediateRenderTarget,16777215,1),this.renderPass(A,this.hBlurMaterial,this.saoRenderTarget,16777215,1);let C=this.materialCopy;if(this.params.output===bU.OUTPUT.Normal)this.materialCopy.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.materialCopy.needsUpdate=!0;else this.materialCopy.uniforms.tDiffuse.value=this.saoRenderTarget.texture,this.materialCopy.needsUpdate=!0;if(this.params.output===bU.OUTPUT.Default)C.blending=vQ;else C.blending=H0;this.renderPass(A,C,this.renderToScreen?null:E),A.setClearColor(this._oldClearColor,this.oldClearAlpha),A.autoClear=B}renderPass(A,Q,E,B,I){A.getClearColor(this.originalClearColor);let C=A.getClearAlpha(),K=A.autoClear;if(A.setRenderTarget(E),A.autoClear=!1,B!==void 0&&B!==null)A.setClearColor(B),A.setClearAlpha(I||0),A.clear();this.fsQuad.material=Q,this.fsQuad.render(A),A.autoClear=K,A.setClearColor(this.originalClearColor),A.setClearAlpha(C)}renderOverride(A,Q,E,B,I){A.getClearColor(this.originalClearColor);let C=A.getClearAlpha(),K=A.autoClear;if(A.setRenderTarget(E),A.autoClear=!1,B=Q.clearColor||B,I=Q.clearAlpha||I,B!==void 0&&B!==null)A.setClearColor(B),A.setClearAlpha(I||0),A.clear();this.scene.overrideMaterial=Q,A.render(this.scene,this.camera),this.scene.overrideMaterial=null,A.autoClear=K,A.setClearColor(this.originalClearColor),A.setClearAlpha(C)}setSize(A,Q){this.saoRenderTarget.setSize(A,Q),this.blurIntermediateRenderTarget.setSize(A,Q),this.normalRenderTarget.setSize(A,Q),this.saoMaterial.uniforms.size.value.set(A,Q),this.saoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.saoMaterial.uniforms.cameraProjectionMatrix.value=this.camera.projectionMatrix,this.saoMaterial.needsUpdate=!0,this.vBlurMaterial.uniforms.size.value.set(A,Q),this.vBlurMaterial.needsUpdate=!0,this.hBlurMaterial.uniforms.size.value.set(A,Q),this.hBlurMaterial.needsUpdate=!0}dispose(){this.saoRenderTarget.dispose(),this.blurIntermediateRenderTarget.dispose(),this.normalRenderTarget.dispose(),this.normalMaterial.dispose(),this.saoMaterial.dispose(),this.vBlurMaterial.dispose(),this.hBlurMaterial.dispose(),this.materialCopy.dispose(),this.fsQuad.dispose()}}bU.OUTPUT={Default:0,SAO:1,Normal:2};var BS={name:"SMAAEdgesShader",defines:{SMAA_THRESHOLD:"0.1"},uniforms:{tDiffuse:{value:null},resolution:{value:new AA(0.0009765625,0.001953125)}},vertexShader:` - - uniform vec2 resolution; - - varying vec2 vUv; - varying vec4 vOffset[ 3 ]; - - void SMAAEdgeDetectionVS( vec2 texcoord ) { - vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component - vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component - vOffset[ 2 ] = texcoord.xyxy + resolution.xyxy * vec4( -2.0, 0.0, 0.0, 2.0 ); // WebGL port note: Changed sign in W component - } - - void main() { - - vUv = uv; - - SMAAEdgeDetectionVS( vUv ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform sampler2D tDiffuse; - - varying vec2 vUv; - varying vec4 vOffset[ 3 ]; - - vec4 SMAAColorEdgeDetectionPS( vec2 texcoord, vec4 offset[3], sampler2D colorTex ) { - vec2 threshold = vec2( SMAA_THRESHOLD, SMAA_THRESHOLD ); - - // Calculate color deltas: - vec4 delta; - vec3 C = texture2D( colorTex, texcoord ).rgb; - - vec3 Cleft = texture2D( colorTex, offset[0].xy ).rgb; - vec3 t = abs( C - Cleft ); - delta.x = max( max( t.r, t.g ), t.b ); - - vec3 Ctop = texture2D( colorTex, offset[0].zw ).rgb; - t = abs( C - Ctop ); - delta.y = max( max( t.r, t.g ), t.b ); - - // We do the usual threshold: - vec2 edges = step( threshold, delta.xy ); - - // Then discard if there is no edge: - if ( dot( edges, vec2( 1.0, 1.0 ) ) == 0.0 ) - discard; - - // Calculate right and bottom deltas: - vec3 Cright = texture2D( colorTex, offset[1].xy ).rgb; - t = abs( C - Cright ); - delta.z = max( max( t.r, t.g ), t.b ); - - vec3 Cbottom = texture2D( colorTex, offset[1].zw ).rgb; - t = abs( C - Cbottom ); - delta.w = max( max( t.r, t.g ), t.b ); - - // Calculate the maximum delta in the direct neighborhood: - float maxDelta = max( max( max( delta.x, delta.y ), delta.z ), delta.w ); - - // Calculate left-left and top-top deltas: - vec3 Cleftleft = texture2D( colorTex, offset[2].xy ).rgb; - t = abs( C - Cleftleft ); - delta.z = max( max( t.r, t.g ), t.b ); - - vec3 Ctoptop = texture2D( colorTex, offset[2].zw ).rgb; - t = abs( C - Ctoptop ); - delta.w = max( max( t.r, t.g ), t.b ); - - // Calculate the final maximum delta: - maxDelta = max( max( maxDelta, delta.z ), delta.w ); - - // Local contrast adaptation in action: - edges.xy *= step( 0.5 * maxDelta, delta.xy ); - - return vec4( edges, 0.0, 0.0 ); - } - - void main() { - - gl_FragColor = SMAAColorEdgeDetectionPS( vUv, vOffset, tDiffuse ); - - }`},IS={name:"SMAAWeightsShader",defines:{SMAA_MAX_SEARCH_STEPS:"8",SMAA_AREATEX_MAX_DISTANCE:"16",SMAA_AREATEX_PIXEL_SIZE:"( 1.0 / vec2( 160.0, 560.0 ) )",SMAA_AREATEX_SUBTEX_SIZE:"( 1.0 / 7.0 )"},uniforms:{tDiffuse:{value:null},tArea:{value:null},tSearch:{value:null},resolution:{value:new AA(0.0009765625,0.001953125)}},vertexShader:` - - uniform vec2 resolution; - - varying vec2 vUv; - varying vec4 vOffset[ 3 ]; - varying vec2 vPixcoord; - - void SMAABlendingWeightCalculationVS( vec2 texcoord ) { - vPixcoord = texcoord / resolution; - - // We will use these offsets for the searches later on (see @PSEUDO_GATHER4): - vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.25, 0.125, 1.25, 0.125 ); // WebGL port note: Changed sign in Y and W components - vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.125, 0.25, -0.125, -1.25 ); // WebGL port note: Changed sign in Y and W components - - // And these for the searches, they indicate the ends of the loops: - vOffset[ 2 ] = vec4( vOffset[ 0 ].xz, vOffset[ 1 ].yw ) + vec4( -2.0, 2.0, -2.0, 2.0 ) * resolution.xxyy * float( SMAA_MAX_SEARCH_STEPS ); - - } - - void main() { - - vUv = uv; - - SMAABlendingWeightCalculationVS( vUv ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - #define SMAASampleLevelZeroOffset( tex, coord, offset ) texture2D( tex, coord + float( offset ) * resolution, 0.0 ) - - uniform sampler2D tDiffuse; - uniform sampler2D tArea; - uniform sampler2D tSearch; - uniform vec2 resolution; - - varying vec2 vUv; - varying vec4 vOffset[3]; - varying vec2 vPixcoord; - - #if __VERSION__ == 100 - vec2 round( vec2 x ) { - return sign( x ) * floor( abs( x ) + 0.5 ); - } - #endif - - float SMAASearchLength( sampler2D searchTex, vec2 e, float bias, float scale ) { - // Not required if searchTex accesses are set to point: - // float2 SEARCH_TEX_PIXEL_SIZE = 1.0 / float2(66.0, 33.0); - // e = float2(bias, 0.0) + 0.5 * SEARCH_TEX_PIXEL_SIZE + - // e * float2(scale, 1.0) * float2(64.0, 32.0) * SEARCH_TEX_PIXEL_SIZE; - e.r = bias + e.r * scale; - return 255.0 * texture2D( searchTex, e, 0.0 ).r; - } - - float SMAASearchXLeft( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { - /** - * @PSEUDO_GATHER4 - * This texcoord has been offset by (-0.25, -0.125) in the vertex shader to - * sample between edge, thus fetching four edges in a row. - * Sampling with different offsets in each direction allows to disambiguate - * which edges are active from the four fetched ones. - */ - vec2 e = vec2( 0.0, 1.0 ); - - for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for - e = texture2D( edgesTex, texcoord, 0.0 ).rg; - texcoord -= vec2( 2.0, 0.0 ) * resolution; - if ( ! ( texcoord.x > end && e.g > 0.8281 && e.r == 0.0 ) ) break; - } - - // We correct the previous (-0.25, -0.125) offset we applied: - texcoord.x += 0.25 * resolution.x; - - // The searches are bias by 1, so adjust the coords accordingly: - texcoord.x += resolution.x; - - // Disambiguate the length added by the last step: - texcoord.x += 2.0 * resolution.x; // Undo last step - texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5); - - return texcoord.x; - } - - float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { - vec2 e = vec2( 0.0, 1.0 ); - - for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for - e = texture2D( edgesTex, texcoord, 0.0 ).rg; - texcoord += vec2( 2.0, 0.0 ) * resolution; - if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break; - } - - texcoord.x -= 0.25 * resolution.x; - texcoord.x -= resolution.x; - texcoord.x -= 2.0 * resolution.x; - texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 ); - - return texcoord.x; - } - - float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { - vec2 e = vec2( 1.0, 0.0 ); - - for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for - e = texture2D( edgesTex, texcoord, 0.0 ).rg; - texcoord += vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign - if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break; - } - - texcoord.y -= 0.25 * resolution.y; // WebGL port note: Changed sign - texcoord.y -= resolution.y; // WebGL port note: Changed sign - texcoord.y -= 2.0 * resolution.y; // WebGL port note: Changed sign - texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 ); // WebGL port note: Changed sign - - return texcoord.y; - } - - float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { - vec2 e = vec2( 1.0, 0.0 ); - - for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for - e = texture2D( edgesTex, texcoord, 0.0 ).rg; - texcoord -= vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign - if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break; - } - - texcoord.y += 0.25 * resolution.y; // WebGL port note: Changed sign - texcoord.y += resolution.y; // WebGL port note: Changed sign - texcoord.y += 2.0 * resolution.y; // WebGL port note: Changed sign - texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 ); // WebGL port note: Changed sign - - return texcoord.y; - } - - vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) { - // Rounding prevents precision errors of bilinear filtering: - vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist; - - // We do a scale and bias for mapping to texel space: - texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE ); - - // Move to proper place, according to the subpixel offset: - texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset; - - return texture2D( areaTex, texcoord, 0.0 ).rg; - } - - vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) { - vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 ); - - vec2 e = texture2D( edgesTex, texcoord ).rg; - - if ( e.g > 0.0 ) { // Edge at north - vec2 d; - - // Find the distance to the left: - vec2 coords; - coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x ); - coords.y = offset[ 1 ].y; // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET) - d.x = coords.x; - - // Now fetch the left crossing edges, two at a time using bilinear - // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to - // discern what value each edge has: - float e1 = texture2D( edgesTex, coords, 0.0 ).r; - - // Find the distance to the right: - coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y ); - d.y = coords.x; - - // We want the distances to be in pixel units (doing this here allow to - // better interleave arithmetic and memory accesses): - d = d / resolution.x - pixcoord.x; - - // SMAAArea below needs a sqrt, as the areas texture is compressed - // quadratically: - vec2 sqrt_d = sqrt( abs( d ) ); - - // Fetch the right crossing edges: - coords.y -= 1.0 * resolution.y; // WebGL port note: Added - float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r; - - // Ok, we know how this pattern looks like, now it is time for getting - // the actual area: - weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) ); - } - - if ( e.r > 0.0 ) { // Edge at west - vec2 d; - - // Find the distance to the top: - vec2 coords; - - coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z ); - coords.x = offset[ 0 ].x; // offset[1].x = texcoord.x - 0.25 * resolution.x; - d.x = coords.y; - - // Fetch the top crossing edges: - float e1 = texture2D( edgesTex, coords, 0.0 ).g; - - // Find the distance to the bottom: - coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w ); - d.y = coords.y; - - // We want the distances to be in pixel units: - d = d / resolution.y - pixcoord.y; - - // SMAAArea below needs a sqrt, as the areas texture is compressed - // quadratically: - vec2 sqrt_d = sqrt( abs( d ) ); - - // Fetch the bottom crossing edges: - coords.y -= 1.0 * resolution.y; // WebGL port note: Added - float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g; - - // Get the area for this direction: - weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) ); - } - - return weights; - } - - void main() { - - gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) ); - - }`},CS={name:"SMAABlendShader",uniforms:{tDiffuse:{value:null},tColor:{value:null},resolution:{value:new AA(0.0009765625,0.001953125)}},vertexShader:` - - uniform vec2 resolution; - - varying vec2 vUv; - varying vec4 vOffset[ 2 ]; - - void SMAANeighborhoodBlendingVS( vec2 texcoord ) { - vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component - vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component - } - - void main() { - - vUv = uv; - - SMAANeighborhoodBlendingVS( vUv ); - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform sampler2D tDiffuse; - uniform sampler2D tColor; - uniform vec2 resolution; - - varying vec2 vUv; - varying vec4 vOffset[ 2 ]; - - vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) { - // Fetch the blending weights for current pixel: - vec4 a; - a.xz = texture2D( blendTex, texcoord ).xz; - a.y = texture2D( blendTex, offset[ 1 ].zw ).g; - a.w = texture2D( blendTex, offset[ 1 ].xy ).a; - - // Is there any blending weight with a value greater than 0.0? - if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) { - return texture2D( colorTex, texcoord, 0.0 ); - } else { - // Up to 4 lines can be crossing a pixel (one through each edge). We - // favor blending by choosing the line with the maximum weight for each - // direction: - vec2 offset; - offset.x = a.a > a.b ? a.a : -a.b; // left vs. right - offset.y = a.g > a.r ? -a.g : a.r; // top vs. bottom // WebGL port note: Changed signs - - // Then we go in the direction that has the maximum weight: - if ( abs( offset.x ) > abs( offset.y )) { // horizontal vs. vertical - offset.y = 0.0; - } else { - offset.x = 0.0; - } - - // Fetch the opposite color and lerp by hand: - vec4 C = texture2D( colorTex, texcoord, 0.0 ); - texcoord += sign( offset ) * resolution; - vec4 Cop = texture2D( colorTex, texcoord, 0.0 ); - float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y ); - - // WebGL port note: Added gamma correction - C.xyz = pow(C.xyz, vec3(2.2)); - Cop.xyz = pow(Cop.xyz, vec3(2.2)); - vec4 mixed = mix(C, Cop, s); - mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2)); - - return mixed; - } - } - - void main() { - - gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse ); - - }`};var zK={name:"SSAOShader",defines:{PERSPECTIVE_CAMERA:1,KERNEL_SIZE:32},uniforms:{tNormal:{value:null},tDepth:{value:null},tNoise:{value:null},kernel:{value:null},cameraNear:{value:null},cameraFar:{value:null},resolution:{value:new AA},cameraProjectionMatrix:{value:new RA},cameraInverseProjectionMatrix:{value:new RA},kernelRadius:{value:8},minDistance:{value:0.005},maxDistance:{value:0.05}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - uniform highp sampler2D tNormal; - uniform highp sampler2D tDepth; - uniform sampler2D tNoise; - - uniform vec3 kernel[ KERNEL_SIZE ]; - - uniform vec2 resolution; - - uniform float cameraNear; - uniform float cameraFar; - uniform mat4 cameraProjectionMatrix; - uniform mat4 cameraInverseProjectionMatrix; - - uniform float kernelRadius; - uniform float minDistance; // avoid artifacts caused by neighbour fragments with minimal depth difference - uniform float maxDistance; // avoid the influence of fragments which are too far away - - varying vec2 vUv; - - #include - - float getDepth( const in vec2 screenPosition ) { - - return texture2D( tDepth, screenPosition ).x; - - } - - float getLinearDepth( const in vec2 screenPosition ) { - - #if PERSPECTIVE_CAMERA == 1 - - float fragCoordZ = texture2D( tDepth, screenPosition ).x; - float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); - return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); - - #else - - return texture2D( tDepth, screenPosition ).x; - - #endif - - } - - float getViewZ( const in float depth ) { - - #if PERSPECTIVE_CAMERA == 1 - - return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); - - #else - - return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); - - #endif - - } - - vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) { - - float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3]; - - vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 ); - - clipPosition *= clipW; // unprojection. - - return ( cameraInverseProjectionMatrix * clipPosition ).xyz; - - } - - vec3 getViewNormal( const in vec2 screenPosition ) { - - return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); - - } - - void main() { - - float depth = getDepth( vUv ); - - if ( depth == 1.0 ) { - - gl_FragColor = vec4( 1.0 ); // don't influence background - - } else { - - float viewZ = getViewZ( depth ); - - vec3 viewPosition = getViewPosition( vUv, depth, viewZ ); - vec3 viewNormal = getViewNormal( vUv ); - - vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 ); - vec3 random = vec3( texture2D( tNoise, vUv * noiseScale ).r ); - - // compute matrix used to reorient a kernel vector - - vec3 tangent = normalize( random - viewNormal * dot( random, viewNormal ) ); - vec3 bitangent = cross( viewNormal, tangent ); - mat3 kernelMatrix = mat3( tangent, bitangent, viewNormal ); - - float occlusion = 0.0; - - for ( int i = 0; i < KERNEL_SIZE; i ++ ) { - - vec3 sampleVector = kernelMatrix * kernel[ i ]; // reorient sample vector in view space - vec3 samplePoint = viewPosition + ( sampleVector * kernelRadius ); // calculate sample point - - vec4 samplePointNDC = cameraProjectionMatrix * vec4( samplePoint, 1.0 ); // project point and calculate NDC - samplePointNDC /= samplePointNDC.w; - - vec2 samplePointUv = samplePointNDC.xy * 0.5 + 0.5; // compute uv coordinates - - float realDepth = getLinearDepth( samplePointUv ); // get linear depth from depth texture - float sampleDepth = viewZToOrthographicDepth( samplePoint.z, cameraNear, cameraFar ); // compute linear depth of the sample view Z value - float delta = sampleDepth - realDepth; - - if ( delta > minDistance && delta < maxDistance ) { // if fragment is before sample point, increase occlusion - - occlusion += 1.0; - - } - - } - - occlusion = clamp( occlusion / float( KERNEL_SIZE ), 0.0, 1.0 ); - - gl_FragColor = vec4( vec3( 1.0 - occlusion ), 1.0 ); - - } - - }`},PK={name:"SSAODepthShader",defines:{PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null}},vertexShader:`varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:`uniform sampler2D tDepth; - - uniform float cameraNear; - uniform float cameraFar; - - varying vec2 vUv; - - #include - - float getLinearDepth( const in vec2 screenPosition ) { - - #if PERSPECTIVE_CAMERA == 1 - - float fragCoordZ = texture2D( tDepth, screenPosition ).x; - float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); - return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); - - #else - - return texture2D( tDepth, screenPosition ).x; - - #endif - - } - - void main() { - - float depth = getLinearDepth( vUv ); - gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); - - }`},VK={name:"SSAOBlurShader",uniforms:{tDiffuse:{value:null},resolution:{value:new AA}},vertexShader:`varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:`uniform sampler2D tDiffuse; - - uniform vec2 resolution; - - varying vec2 vUv; - - void main() { - - vec2 texelSize = ( 1.0 / resolution ); - float result = 0.0; - - for ( int i = - 2; i <= 2; i ++ ) { - - for ( int j = - 2; j <= 2; j ++ ) { - - vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize; - result += texture2D( tDiffuse, vUv + offset ).r; - - } - - } - - gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 ); - - }`};class e1 extends s0{constructor(A,Q,E,B,I=32){super();this.width=E!==void 0?E:512,this.height=B!==void 0?B:512,this.clear=!0,this.needsSwap=!1,this.camera=Q,this.scene=A,this.kernelRadius=8,this.kernel=[],this.noiseTexture=null,this.output=0,this.minDistance=0.005,this.maxDistance=0.1,this._visibilityCache=/*@__PURE__*/new Map,this.generateSampleKernel(I),this.generateRandomKernelRotations();let C=new IE;C.format=oE,C.type=VE,this.normalRenderTarget=new Q0(this.width,this.height,{minFilter:Z0,magFilter:Z0,type:sA,depthTexture:C}),this.ssaoRenderTarget=new Q0(this.width,this.height,{type:sA}),this.blurRenderTarget=this.ssaoRenderTarget.clone(),this.ssaoMaterial=new bA({defines:Object.assign({},zK.defines),uniforms:oA.clone(zK.uniforms),vertexShader:zK.vertexShader,fragmentShader:zK.fragmentShader,blending:H0}),this.ssaoMaterial.defines.KERNEL_SIZE=I,this.ssaoMaterial.uniforms.tNormal.value=this.normalRenderTarget.texture,this.ssaoMaterial.uniforms.tDepth.value=this.normalRenderTarget.depthTexture,this.ssaoMaterial.uniforms.tNoise.value=this.noiseTexture,this.ssaoMaterial.uniforms.kernel.value=this.kernel,this.ssaoMaterial.uniforms.cameraNear.value=this.camera.near,this.ssaoMaterial.uniforms.cameraFar.value=this.camera.far,this.ssaoMaterial.uniforms.resolution.value.set(this.width,this.height),this.ssaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssaoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.normalMaterial=new gE,this.normalMaterial.blending=H0,this.blurMaterial=new bA({defines:Object.assign({},VK.defines),uniforms:oA.clone(VK.uniforms),vertexShader:VK.vertexShader,fragmentShader:VK.fragmentShader}),this.blurMaterial.uniforms.tDiffuse.value=this.ssaoRenderTarget.texture,this.blurMaterial.uniforms.resolution.value.set(this.width,this.height),this.depthRenderMaterial=new bA({defines:Object.assign({},PK.defines),uniforms:oA.clone(PK.uniforms),vertexShader:PK.vertexShader,fragmentShader:PK.fragmentShader,blending:H0}),this.depthRenderMaterial.uniforms.tDepth.value=this.normalRenderTarget.depthTexture,this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this.copyMaterial=new bA({uniforms:oA.clone(GQ.uniforms),vertexShader:GQ.vertexShader,fragmentShader:GQ.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blendSrc:PB,blendDst:$E,blendEquation:kQ,blendSrcAlpha:LE,blendDstAlpha:$E,blendEquationAlpha:kQ}),this.fsQuad=new r0(null),this.originalClearColor=new a}dispose(){this.normalRenderTarget.dispose(),this.ssaoRenderTarget.dispose(),this.blurRenderTarget.dispose(),this.normalMaterial.dispose(),this.blurMaterial.dispose(),this.copyMaterial.dispose(),this.depthRenderMaterial.dispose(),this.fsQuad.dispose()}render(A,Q,E){switch(this.overrideVisibility(),this.renderOverride(A,this.normalMaterial,this.normalRenderTarget,7829503,1),this.restoreVisibility(),this.ssaoMaterial.uniforms.kernelRadius.value=this.kernelRadius,this.ssaoMaterial.uniforms.minDistance.value=this.minDistance,this.ssaoMaterial.uniforms.maxDistance.value=this.maxDistance,this.renderPass(A,this.ssaoMaterial,this.ssaoRenderTarget),this.renderPass(A,this.blurMaterial,this.blurRenderTarget),this.output){case e1.OUTPUT.SSAO:this.copyMaterial.uniforms.tDiffuse.value=this.ssaoRenderTarget.texture,this.copyMaterial.blending=H0,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:E);break;case e1.OUTPUT.Blur:this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget.texture,this.copyMaterial.blending=H0,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:E);break;case e1.OUTPUT.Depth:this.renderPass(A,this.depthRenderMaterial,this.renderToScreen?null:E);break;case e1.OUTPUT.Normal:this.copyMaterial.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.copyMaterial.blending=H0,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:E);break;case e1.OUTPUT.Default:this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget.texture,this.copyMaterial.blending=vQ,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:E);break;default:console.warn("THREE.SSAOPass: Unknown output type.")}}renderPass(A,Q,E,B,I){A.getClearColor(this.originalClearColor);let C=A.getClearAlpha(),K=A.autoClear;if(A.setRenderTarget(E),A.autoClear=!1,B!==void 0&&B!==null)A.setClearColor(B),A.setClearAlpha(I||0),A.clear();this.fsQuad.material=Q,this.fsQuad.render(A),A.autoClear=K,A.setClearColor(this.originalClearColor),A.setClearAlpha(C)}renderOverride(A,Q,E,B,I){A.getClearColor(this.originalClearColor);let C=A.getClearAlpha(),K=A.autoClear;if(A.setRenderTarget(E),A.autoClear=!1,B=Q.clearColor||B,I=Q.clearAlpha||I,B!==void 0&&B!==null)A.setClearColor(B),A.setClearAlpha(I||0),A.clear();this.scene.overrideMaterial=Q,A.render(this.scene,this.camera),this.scene.overrideMaterial=null,A.autoClear=K,A.setClearColor(this.originalClearColor),A.setClearAlpha(C)}setSize(A,Q){this.width=A,this.height=Q,this.ssaoRenderTarget.setSize(A,Q),this.normalRenderTarget.setSize(A,Q),this.blurRenderTarget.setSize(A,Q),this.ssaoMaterial.uniforms.resolution.value.set(A,Q),this.ssaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssaoMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.blurMaterial.uniforms.resolution.value.set(A,Q)}generateSampleKernel(A){let Q=this.kernel;for(let E=0;E - float pointToLineDistance(vec3 x0, vec3 x1, vec3 x2) { - //x0: point, x1: linePointA, x2: linePointB - //https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html - return length(cross(x0-x1,x0-x2))/length(x2-x1); - } - float pointPlaneDistance(vec3 point,vec3 planePoint,vec3 planeNormal){ - // https://mathworld.wolfram.com/Point-PlaneDistance.html - //// https://en.wikipedia.org/wiki/Plane_(geometry) - //// http://paulbourke.net/geometry/pointlineplane/ - float a=planeNormal.x,b=planeNormal.y,c=planeNormal.z; - float x0=point.x,y0=point.y,z0=point.z; - float x=planePoint.x,y=planePoint.y,z=planePoint.z; - float d=-(a*x+b*y+c*z); - float distance=(a*x0+b*y0+c*z0+d)/sqrt(a*a+b*b+c*c); - return distance; - } - float getDepth( const in vec2 uv ) { - return texture2D( tDepth, uv ).x; - } - float getViewZ( const in float depth ) { - #ifdef PERSPECTIVE_CAMERA - return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); - #else - return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); - #endif - } - vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { - vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc - clipPosition *= clipW; //clip - return ( cameraInverseProjectionMatrix * clipPosition ).xyz;//view - } - vec3 getViewNormal( const in vec2 uv ) { - return unpackRGBToNormal( texture2D( tNormal, uv ).xyz ); - } - vec2 viewPositionToXY(vec3 viewPosition){ - vec2 xy; - vec4 clip=cameraProjectionMatrix*vec4(viewPosition,1); - xy=clip.xy;//clip - float clipW=clip.w; - xy/=clipW;//NDC - xy=(xy+1.)/2.;//uv - xy*=resolution;//screen - return xy; - } - void main(){ - #ifdef SELECTIVE - float metalness=texture2D(tMetalness,vUv).r; - if(metalness==0.) return; - #endif - - float depth = getDepth( vUv ); - float viewZ = getViewZ( depth ); - if(-viewZ>=cameraFar) return; - - float clipW = cameraProjectionMatrix[2][3] * viewZ+cameraProjectionMatrix[3][3]; - vec3 viewPosition=getViewPosition( vUv, depth, clipW ); - - vec2 d0=gl_FragCoord.xy; - vec2 d1; - - vec3 viewNormal=getViewNormal( vUv ); - - #ifdef PERSPECTIVE_CAMERA - vec3 viewIncidentDir=normalize(viewPosition); - vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal); - #else - vec3 viewIncidentDir=vec3(0,0,-1); - vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal); - #endif - - float maxReflectRayLen=maxDistance/dot(-viewIncidentDir,viewNormal); - // dot(a,b)==length(a)*length(b)*cos(theta) // https://www.mathsisfun.com/algebra/vectors-dot-product.html - // if(a.isNormalized&&b.isNormalized) dot(a,b)==cos(theta) - // maxDistance/maxReflectRayLen=cos(theta) - // maxDistance/maxReflectRayLen==dot(a,b) - // maxReflectRayLen==maxDistance/dot(a,b) - - vec3 d1viewPosition=viewPosition+viewReflectDir*maxReflectRayLen; - #ifdef PERSPECTIVE_CAMERA - if(d1viewPosition.z>-cameraNear){ - //https://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx - float t=(-cameraNear-viewPosition.z)/viewReflectDir.z; - d1viewPosition=viewPosition+viewReflectDir*t; - } - #endif - d1=viewPositionToXY(d1viewPosition); - - float totalLen=length(d1-d0); - float xLen=d1.x-d0.x; - float yLen=d1.y-d0.y; - float totalStep=max(abs(xLen),abs(yLen)); - float xSpan=xLen/totalStep; - float ySpan=yLen/totalStep; - for(float i=0.;i=totalStep) break; - vec2 xy=vec2(d0.x+i*xSpan,d0.y+i*ySpan); - if(xy.x<0.||xy.x>resolution.x||xy.y<0.||xy.y>resolution.y) break; - float s=length(xy-d0)/totalLen; - vec2 uv=xy/resolution; - - float d = getDepth(uv); - float vZ = getViewZ( d ); - if(-vZ>=cameraFar) continue; - float cW = cameraProjectionMatrix[2][3] * vZ+cameraProjectionMatrix[3][3]; - vec3 vP=getViewPosition( uv, d, cW ); - - #ifdef PERSPECTIVE_CAMERA - // https://comp.nus.edu.sg/~lowkl/publications/lowk_persp_interp_techrep.pdf - float recipVPZ=1./viewPosition.z; - float viewReflectRayZ=1./(recipVPZ+s*(1./d1viewPosition.z-recipVPZ)); - #else - float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z); - #endif - - // if(viewReflectRayZ>vZ) continue; // will cause "npm run make-screenshot webgl_postprocessing_ssr" high probability hang. - // https://github.com/mrdoob/three.js/pull/21539#issuecomment-821061164 - if(viewReflectRayZ<=vZ){ - - bool hit; - #ifdef INFINITE_THICK - hit=true; - #else - float away=pointToLineDistance(vP,viewPosition,d1viewPosition); - - float minThickness; - vec2 xyNeighbor=xy; - xyNeighbor.x+=1.; - vec2 uvNeighbor=xyNeighbor/resolution; - vec3 vPNeighbor=getViewPosition(uvNeighbor,d,cW); - minThickness=vPNeighbor.x-vP.x; - minThickness*=3.; - float tk=max(minThickness,thickness); - - hit=away<=tk; - #endif - - if(hit){ - vec3 vN=getViewNormal( uv ); - if(dot(viewReflectDir,vN)>=0.) continue; - float distance=pointPlaneDistance(vP,viewPosition,viewNormal); - if(distance>maxDistance) break; - float op=opacity; - #ifdef DISTANCE_ATTENUATION - float ratio=1.-(distance/maxDistance); - float attenuation=ratio*ratio; - op=opacity*attenuation; - #endif - #ifdef FRESNEL - float fresnelCoe=(dot(viewIncidentDir,viewReflectDir)+1.)/2.; - op*=fresnelCoe; - #endif - vec4 reflectColor=texture2D(tDiffuse,uv); - gl_FragColor.xyz=reflectColor.xyz; - gl_FragColor.a=op; - break; - } - } - } - } - `},jK={name:"SSRDepthShader",defines:{PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - } - - `,fragmentShader:` - - uniform sampler2D tDepth; - - uniform float cameraNear; - uniform float cameraFar; - - varying vec2 vUv; - - #include - - float getLinearDepth( const in vec2 uv ) { - - #if PERSPECTIVE_CAMERA == 1 - - float fragCoordZ = texture2D( tDepth, uv ).x; - float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); - return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); - - #else - - return texture2D( tDepth, uv ).x; - - #endif - - } - - void main() { - - float depth = getLinearDepth( vUv ); - float d = 1.0 - depth; - // d=(d-.999)*1000.; - gl_FragColor = vec4( vec3( d ), 1.0 ); - - } - - `},$I={name:"SSRBlurShader",uniforms:{tDiffuse:{value:null},resolution:{value:new AA},opacity:{value:0.5}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - } - - `,fragmentShader:` - - uniform sampler2D tDiffuse; - uniform vec2 resolution; - varying vec2 vUv; - void main() { - //reverse engineering from PhotoShop blur filter, then change coefficient - - vec2 texelSize = ( 1.0 / resolution ); - - vec4 c=texture2D(tDiffuse,vUv); - - vec2 offset; - - offset=(vec2(-1,0))*texelSize; - vec4 cl=texture2D(tDiffuse,vUv+offset); - - offset=(vec2(1,0))*texelSize; - vec4 cr=texture2D(tDiffuse,vUv+offset); - - offset=(vec2(0,-1))*texelSize; - vec4 cb=texture2D(tDiffuse,vUv+offset); - - offset=(vec2(0,1))*texelSize; - vec4 ct=texture2D(tDiffuse,vUv+offset); - - // float coeCenter=.5; - // float coeSide=.125; - float coeCenter=.2; - float coeSide=.2; - float a=c.a*coeCenter+cl.a*coeSide+cr.a*coeSide+cb.a*coeSide+ct.a*coeSide; - vec3 rgb=(c.rgb*c.a*coeCenter+cl.rgb*cl.a*coeSide+cr.rgb*cr.a*coeSide+cb.rgb*cb.a*coeSide+ct.rgb*ct.a*coeSide)/a; - gl_FragColor=vec4(rgb,a); - - } - `};class iI extends s0{constructor({renderer:A,scene:Q,camera:E,width:B,height:I,selects:C,bouncing:K=!1,groundReflector:J}){super();this.width=B!==void 0?B:512,this.height=I!==void 0?I:512,this.clear=!0,this.renderer=A,this.scene=Q,this.camera=E,this.groundReflector=J,this.opacity=kB.uniforms.opacity.value,this.output=0,this.maxDistance=kB.uniforms.maxDistance.value,this.thickness=kB.uniforms.thickness.value,this.tempColor=new a,this._selects=C,this.selective=Array.isArray(this._selects),Object.defineProperty(this,"selects",{get(){return this._selects},set(Y){if(this._selects===Y)return;if(this._selects=Y,Array.isArray(Y))this.selective=!0,this.ssrMaterial.defines.SELECTIVE=!0,this.ssrMaterial.needsUpdate=!0;else this.selective=!1,this.ssrMaterial.defines.SELECTIVE=!1,this.ssrMaterial.needsUpdate=!0}}),this._bouncing=K,Object.defineProperty(this,"bouncing",{get(){return this._bouncing},set(Y){if(this._bouncing===Y)return;if(this._bouncing=Y,Y)this.ssrMaterial.uniforms.tDiffuse.value=this.prevRenderTarget.texture;else this.ssrMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture}}),this.blur=!0,this._distanceAttenuation=kB.defines.DISTANCE_ATTENUATION,Object.defineProperty(this,"distanceAttenuation",{get(){return this._distanceAttenuation},set(Y){if(this._distanceAttenuation===Y)return;this._distanceAttenuation=Y,this.ssrMaterial.defines.DISTANCE_ATTENUATION=Y,this.ssrMaterial.needsUpdate=!0}}),this._fresnel=kB.defines.FRESNEL,Object.defineProperty(this,"fresnel",{get(){return this._fresnel},set(Y){if(this._fresnel===Y)return;this._fresnel=Y,this.ssrMaterial.defines.FRESNEL=Y,this.ssrMaterial.needsUpdate=!0}}),this._infiniteThick=kB.defines.INFINITE_THICK,Object.defineProperty(this,"infiniteThick",{get(){return this._infiniteThick},set(Y){if(this._infiniteThick===Y)return;this._infiniteThick=Y,this.ssrMaterial.defines.INFINITE_THICK=Y,this.ssrMaterial.needsUpdate=!0}});let U=new IE;U.type=hB,U.minFilter=Z0,U.magFilter=Z0,this.beautyRenderTarget=new Q0(this.width,this.height,{minFilter:Z0,magFilter:Z0,type:sA,depthTexture:U,depthBuffer:!0}),this.prevRenderTarget=new Q0(this.width,this.height,{minFilter:Z0,magFilter:Z0}),this.normalRenderTarget=new Q0(this.width,this.height,{minFilter:Z0,magFilter:Z0,type:sA}),this.metalnessRenderTarget=new Q0(this.width,this.height,{minFilter:Z0,magFilter:Z0,type:sA}),this.ssrRenderTarget=new Q0(this.width,this.height,{minFilter:Z0,magFilter:Z0}),this.blurRenderTarget=this.ssrRenderTarget.clone(),this.blurRenderTarget2=this.ssrRenderTarget.clone(),this.ssrMaterial=new bA({defines:Object.assign({},kB.defines,{MAX_STEP:Math.sqrt(this.width*this.width+this.height*this.height)}),uniforms:oA.clone(kB.uniforms),vertexShader:kB.vertexShader,fragmentShader:kB.fragmentShader,blending:H0}),this.ssrMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.ssrMaterial.uniforms.tNormal.value=this.normalRenderTarget.texture,this.ssrMaterial.defines.SELECTIVE=this.selective,this.ssrMaterial.needsUpdate=!0,this.ssrMaterial.uniforms.tMetalness.value=this.metalnessRenderTarget.texture,this.ssrMaterial.uniforms.tDepth.value=this.beautyRenderTarget.depthTexture,this.ssrMaterial.uniforms.cameraNear.value=this.camera.near,this.ssrMaterial.uniforms.cameraFar.value=this.camera.far,this.ssrMaterial.uniforms.thickness.value=this.thickness,this.ssrMaterial.uniforms.resolution.value.set(this.width,this.height),this.ssrMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssrMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.normalMaterial=new gE,this.normalMaterial.blending=H0,this.metalnessOnMaterial=new _0({color:"white"}),this.metalnessOffMaterial=new _0({color:"black"}),this.blurMaterial=new bA({defines:Object.assign({},$I.defines),uniforms:oA.clone($I.uniforms),vertexShader:$I.vertexShader,fragmentShader:$I.fragmentShader}),this.blurMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture,this.blurMaterial.uniforms.resolution.value.set(this.width,this.height),this.blurMaterial2=new bA({defines:Object.assign({},$I.defines),uniforms:oA.clone($I.uniforms),vertexShader:$I.vertexShader,fragmentShader:$I.fragmentShader}),this.blurMaterial2.uniforms.tDiffuse.value=this.blurRenderTarget.texture,this.blurMaterial2.uniforms.resolution.value.set(this.width,this.height),this.depthRenderMaterial=new bA({defines:Object.assign({},jK.defines),uniforms:oA.clone(jK.uniforms),vertexShader:jK.vertexShader,fragmentShader:jK.fragmentShader,blending:H0}),this.depthRenderMaterial.uniforms.tDepth.value=this.beautyRenderTarget.depthTexture,this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this.copyMaterial=new bA({uniforms:oA.clone(GQ.uniforms),vertexShader:GQ.vertexShader,fragmentShader:GQ.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blendSrc:EE,blendDst:iE,blendEquation:kQ,blendSrcAlpha:EE,blendDstAlpha:iE,blendEquationAlpha:kQ}),this.fsQuad=new r0(null),this.originalClearColor=new a}dispose(){this.beautyRenderTarget.dispose(),this.prevRenderTarget.dispose(),this.normalRenderTarget.dispose(),this.metalnessRenderTarget.dispose(),this.ssrRenderTarget.dispose(),this.blurRenderTarget.dispose(),this.blurRenderTarget2.dispose(),this.normalMaterial.dispose(),this.metalnessOnMaterial.dispose(),this.metalnessOffMaterial.dispose(),this.blurMaterial.dispose(),this.blurMaterial2.dispose(),this.copyMaterial.dispose(),this.depthRenderMaterial.dispose(),this.fsQuad.dispose()}render(A,Q){if(A.setRenderTarget(this.beautyRenderTarget),A.clear(),this.groundReflector)this.groundReflector.visible=!1,this.groundReflector.doRender(this.renderer,this.scene,this.camera),this.groundReflector.visible=!0;if(A.render(this.scene,this.camera),this.groundReflector)this.groundReflector.visible=!1;if(this.renderOverride(A,this.normalMaterial,this.normalRenderTarget,0,0),this.selective)this.renderMetalness(A,this.metalnessOnMaterial,this.metalnessRenderTarget,0,0);if(this.ssrMaterial.uniforms.opacity.value=this.opacity,this.ssrMaterial.uniforms.maxDistance.value=this.maxDistance,this.ssrMaterial.uniforms.thickness.value=this.thickness,this.renderPass(A,this.ssrMaterial,this.ssrRenderTarget),this.blur)this.renderPass(A,this.blurMaterial,this.blurRenderTarget),this.renderPass(A,this.blurMaterial2,this.blurRenderTarget2);switch(this.output){case iI.OUTPUT.Default:if(this.bouncing){if(this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.copyMaterial.blending=H0,this.renderPass(A,this.copyMaterial,this.prevRenderTarget),this.blur)this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget2.texture;else this.copyMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture;this.copyMaterial.blending=zB,this.renderPass(A,this.copyMaterial,this.prevRenderTarget),this.copyMaterial.uniforms.tDiffuse.value=this.prevRenderTarget.texture,this.copyMaterial.blending=H0,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q)}else{if(this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.copyMaterial.blending=H0,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q),this.blur)this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget2.texture;else this.copyMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture;this.copyMaterial.blending=zB,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q)}break;case iI.OUTPUT.SSR:if(this.blur)this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget2.texture;else this.copyMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture;if(this.copyMaterial.blending=H0,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q),this.bouncing){if(this.blur)this.copyMaterial.uniforms.tDiffuse.value=this.blurRenderTarget2.texture;else this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture;this.copyMaterial.blending=H0,this.renderPass(A,this.copyMaterial,this.prevRenderTarget),this.copyMaterial.uniforms.tDiffuse.value=this.ssrRenderTarget.texture,this.copyMaterial.blending=zB,this.renderPass(A,this.copyMaterial,this.prevRenderTarget)}break;case iI.OUTPUT.Beauty:this.copyMaterial.uniforms.tDiffuse.value=this.beautyRenderTarget.texture,this.copyMaterial.blending=H0,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q);break;case iI.OUTPUT.Depth:this.renderPass(A,this.depthRenderMaterial,this.renderToScreen?null:Q);break;case iI.OUTPUT.Normal:this.copyMaterial.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.copyMaterial.blending=H0,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q);break;case iI.OUTPUT.Metalness:this.copyMaterial.uniforms.tDiffuse.value=this.metalnessRenderTarget.texture,this.copyMaterial.blending=H0,this.renderPass(A,this.copyMaterial,this.renderToScreen?null:Q);break;default:console.warn("THREE.SSRPass: Unknown output type.")}}renderPass(A,Q,E,B,I){this.originalClearColor.copy(A.getClearColor(this.tempColor));let C=A.getClearAlpha(this.tempColor),K=A.autoClear;if(A.setRenderTarget(E),A.autoClear=!1,B!==void 0&&B!==null)A.setClearColor(B),A.setClearAlpha(I||0),A.clear();this.fsQuad.material=Q,this.fsQuad.render(A),A.autoClear=K,A.setClearColor(this.originalClearColor),A.setClearAlpha(C)}renderOverride(A,Q,E,B,I){this.originalClearColor.copy(A.getClearColor(this.tempColor));let C=A.getClearAlpha(this.tempColor),K=A.autoClear;if(A.setRenderTarget(E),A.autoClear=!1,B=Q.clearColor||B,I=Q.clearAlpha||I,B!==void 0&&B!==null)A.setClearColor(B),A.setClearAlpha(I||0),A.clear();this.scene.overrideMaterial=Q,A.render(this.scene,this.camera),this.scene.overrideMaterial=null,A.autoClear=K,A.setClearColor(this.originalClearColor),A.setClearAlpha(C)}renderMetalness(A,Q,E,B,I){this.originalClearColor.copy(A.getClearColor(this.tempColor));let C=A.getClearAlpha(this.tempColor),K=A.autoClear,J=this.scene.background,U=this.scene.fog;if(A.setRenderTarget(E),A.autoClear=!1,this.scene.background=null,this.scene.fog=null,B=Q.clearColor||B,I=Q.clearAlpha||I,B!==void 0&&B!==null)A.setClearColor(B),A.setClearAlpha(I||0),A.clear();this.scene.traverseVisible((Y)=>{if(Y._SSRPassBackupMaterial=Y.material,this._selects.includes(Y))Y.material=this.metalnessOnMaterial;else Y.material=this.metalnessOffMaterial}),A.render(this.scene,this.camera),this.scene.traverseVisible((Y)=>{Y.material=Y._SSRPassBackupMaterial}),A.autoClear=K,A.setClearColor(this.originalClearColor),A.setClearAlpha(C),this.scene.background=J,this.scene.fog=U}setSize(A,Q){this.width=A,this.height=Q,this.ssrMaterial.defines.MAX_STEP=Math.sqrt(A*A+Q*Q),this.ssrMaterial.needsUpdate=!0,this.beautyRenderTarget.setSize(A,Q),this.prevRenderTarget.setSize(A,Q),this.ssrRenderTarget.setSize(A,Q),this.normalRenderTarget.setSize(A,Q),this.metalnessRenderTarget.setSize(A,Q),this.blurRenderTarget.setSize(A,Q),this.blurRenderTarget2.setSize(A,Q),this.ssrMaterial.uniforms.resolution.value.set(A,Q),this.ssrMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.ssrMaterial.uniforms.cameraInverseProjectionMatrix.value.copy(this.camera.projectionMatrixInverse),this.blurMaterial.uniforms.resolution.value.set(A,Q),this.blurMaterial2.uniforms.resolution.value.set(A,Q)}}iI.OUTPUT={Default:0,SSR:1,Beauty:3,Depth:4,Normal:5,Metalness:7};var vX={name:"LuminosityHighPassShader",shaderID:"luminosityHighPass",uniforms:{tDiffuse:{value:null},luminosityThreshold:{value:1},smoothWidth:{value:1},defaultColor:{value:new a(0)},defaultOpacity:{value:0}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform sampler2D tDiffuse; - uniform vec3 defaultColor; - uniform float defaultOpacity; - uniform float luminosityThreshold; - uniform float smoothWidth; - - varying vec2 vUv; - - void main() { - - vec4 texel = texture2D( tDiffuse, vUv ); - - float v = luminance( texel.xyz ); - - vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity ); - - float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v ); - - gl_FragColor = mix( outputColor, texel, alpha ); - - }`};class vK extends s0{constructor(A,Q,E,B){super();this.strength=Q!==void 0?Q:1,this.radius=E,this.threshold=B,this.resolution=A!==void 0?new AA(A.x,A.y):new AA(256,256),this.clearColor=new a(0,0,0),this.renderTargetsHorizontal=[],this.renderTargetsVertical=[],this.nMips=5;let I=Math.round(this.resolution.x/2),C=Math.round(this.resolution.y/2);this.renderTargetBright=new Q0(I,C,{type:sA}),this.renderTargetBright.texture.name="UnrealBloomPass.bright",this.renderTargetBright.texture.generateMipmaps=!1;for(let H=0;H - varying vec2 vUv; - uniform sampler2D colorTexture; - uniform vec2 invSize; - uniform vec2 direction; - uniform float gaussianCoefficients[KERNEL_RADIUS]; - - void main() { - float weightSum = gaussianCoefficients[0]; - vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum; - for( int i = 1; i < KERNEL_RADIUS; i ++ ) { - float x = float(i); - float w = gaussianCoefficients[i]; - vec2 uvOffset = direction * invSize * x; - vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb; - vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb; - diffuseSum += (sample1 + sample2) * w; - weightSum += 2.0 * w; - } - gl_FragColor = vec4(diffuseSum/weightSum, 1.0); - }`})}getCompositeMaterial(A){return new bA({defines:{NUM_MIPS:A},uniforms:{blurTexture1:{value:null},blurTexture2:{value:null},blurTexture3:{value:null},blurTexture4:{value:null},blurTexture5:{value:null},bloomStrength:{value:1},bloomFactors:{value:null},bloomTintColors:{value:null},bloomRadius:{value:0}},vertexShader:`varying vec2 vUv; - void main() { - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - }`,fragmentShader:`varying vec2 vUv; - uniform sampler2D blurTexture1; - uniform sampler2D blurTexture2; - uniform sampler2D blurTexture3; - uniform sampler2D blurTexture4; - uniform sampler2D blurTexture5; - uniform float bloomStrength; - uniform float bloomRadius; - uniform float bloomFactors[NUM_MIPS]; - uniform vec3 bloomTintColors[NUM_MIPS]; - - float lerpBloomFactor(const in float factor) { - float mirrorFactor = 1.2 - factor; - return mix(factor, mirrorFactor, bloomRadius); - } - - void main() { - gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + - lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + - lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + - lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + - lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) ); - }`})}}vK.BlurDirectionX=new AA(1,0);vK.BlurDirectionY=new AA(0,1);var $m=new y,Lm=new RA,qm=new RA,Fm=new y,Dm=new y;var _m=new y,km=new J0,Sm=new y;var Tm=new RA,zm=new RA;var KS={name:"BokehShader",uniforms:{textureWidth:{value:1},textureHeight:{value:1},focalDepth:{value:1},focalLength:{value:24},fstop:{value:0.9},tColor:{value:null},tDepth:{value:null},maxblur:{value:1},showFocus:{value:0},manualdof:{value:0},vignetting:{value:0},depthblur:{value:0},threshold:{value:0.5},gain:{value:2},bias:{value:0.5},fringe:{value:0.7},znear:{value:0.1},zfar:{value:100},noise:{value:1},dithering:{value:0.0001},pentagon:{value:0},shaderFocus:{value:1},focusCoords:{value:new AA}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - #include - - varying vec2 vUv; - - uniform sampler2D tColor; - uniform sampler2D tDepth; - uniform float textureWidth; - uniform float textureHeight; - - uniform float focalDepth; //focal distance value in meters, but you may use autofocus option below - uniform float focalLength; //focal length in mm - uniform float fstop; //f-stop value - uniform bool showFocus; //show debug focus point and focal range (red = focal point, green = focal range) - - /* - make sure that these two values are the same for your camera, otherwise distances will be wrong. - */ - - uniform float znear; // camera clipping start - uniform float zfar; // camera clipping end - - //------------------------------------------ - //user variables - - const int samples = SAMPLES; //samples on the first ring - const int rings = RINGS; //ring count - - const int maxringsamples = rings * samples; - - uniform bool manualdof; // manual dof calculation - float ndofstart = 1.0; // near dof blur start - float ndofdist = 2.0; // near dof blur falloff distance - float fdofstart = 1.0; // far dof blur start - float fdofdist = 3.0; // far dof blur falloff distance - - float CoC = 0.03; //circle of confusion size in mm (35mm film = 0.03mm) - - uniform bool vignetting; // use optical lens vignetting - - float vignout = 1.3; // vignetting outer border - float vignin = 0.0; // vignetting inner border - float vignfade = 22.0; // f-stops till vignette fades - - uniform bool shaderFocus; - // disable if you use external focalDepth value - - uniform vec2 focusCoords; - // autofocus point on screen (0.0,0.0 - left lower corner, 1.0,1.0 - upper right) - // if center of screen use vec2(0.5, 0.5); - - uniform float maxblur; - //clamp value of max blur (0.0 = no blur, 1.0 default) - - uniform float threshold; // highlight threshold; - uniform float gain; // highlight gain; - - uniform float bias; // bokeh edge bias - uniform float fringe; // bokeh chromatic aberration / fringing - - uniform bool noise; //use noise instead of pattern for sample dithering - - uniform float dithering; - - uniform bool depthblur; // blur the depth buffer - float dbsize = 1.25; // depth blur size - - /* - next part is experimental - not looking good with small sample and ring count - looks okay starting from samples = 4, rings = 4 - */ - - uniform bool pentagon; //use pentagon as bokeh shape? - float feather = 0.4; //pentagon shape feather - - //------------------------------------------ - - float penta(vec2 coords) { - //pentagonal shape - float scale = float(rings) - 1.3; - vec4 HS0 = vec4( 1.0, 0.0, 0.0, 1.0); - vec4 HS1 = vec4( 0.309016994, 0.951056516, 0.0, 1.0); - vec4 HS2 = vec4(-0.809016994, 0.587785252, 0.0, 1.0); - vec4 HS3 = vec4(-0.809016994,-0.587785252, 0.0, 1.0); - vec4 HS4 = vec4( 0.309016994,-0.951056516, 0.0, 1.0); - vec4 HS5 = vec4( 0.0 ,0.0 , 1.0, 1.0); - - vec4 one = vec4( 1.0 ); - - vec4 P = vec4((coords),vec2(scale, scale)); - - vec4 dist = vec4(0.0); - float inorout = -4.0; - - dist.x = dot( P, HS0 ); - dist.y = dot( P, HS1 ); - dist.z = dot( P, HS2 ); - dist.w = dot( P, HS3 ); - - dist = smoothstep( -feather, feather, dist ); - - inorout += dot( dist, one ); - - dist.x = dot( P, HS4 ); - dist.y = HS5.w - abs( P.z ); - - dist = smoothstep( -feather, feather, dist ); - inorout += dist.x; - - return clamp( inorout, 0.0, 1.0 ); - } - - float bdepth(vec2 coords) { - // Depth buffer blur - float d = 0.0; - float kernel[9]; - vec2 offset[9]; - - vec2 wh = vec2(1.0/textureWidth,1.0/textureHeight) * dbsize; - - offset[0] = vec2(-wh.x,-wh.y); - offset[1] = vec2( 0.0, -wh.y); - offset[2] = vec2( wh.x -wh.y); - - offset[3] = vec2(-wh.x, 0.0); - offset[4] = vec2( 0.0, 0.0); - offset[5] = vec2( wh.x, 0.0); - - offset[6] = vec2(-wh.x, wh.y); - offset[7] = vec2( 0.0, wh.y); - offset[8] = vec2( wh.x, wh.y); - - kernel[0] = 1.0/16.0; kernel[1] = 2.0/16.0; kernel[2] = 1.0/16.0; - kernel[3] = 2.0/16.0; kernel[4] = 4.0/16.0; kernel[5] = 2.0/16.0; - kernel[6] = 1.0/16.0; kernel[7] = 2.0/16.0; kernel[8] = 1.0/16.0; - - - for( int i=0; i<9; i++ ) { - float tmp = texture2D(tDepth, coords + offset[i]).r; - d += tmp * kernel[i]; - } - - return d; - } - - - vec3 color(vec2 coords,float blur) { - //processing the sample - - vec3 col = vec3(0.0); - vec2 texel = vec2(1.0/textureWidth,1.0/textureHeight); - - col.r = texture2D(tColor,coords + vec2(0.0,1.0)*texel*fringe*blur).r; - col.g = texture2D(tColor,coords + vec2(-0.866,-0.5)*texel*fringe*blur).g; - col.b = texture2D(tColor,coords + vec2(0.866,-0.5)*texel*fringe*blur).b; - - vec3 lumcoeff = vec3(0.299,0.587,0.114); - float lum = dot(col.rgb, lumcoeff); - float thresh = max((lum-threshold)*gain, 0.0); - return col+mix(vec3(0.0),col,thresh*blur); - } - - vec3 debugFocus(vec3 col, float blur, float depth) { - float edge = 0.002*depth; //distance based edge smoothing - float m = clamp(smoothstep(0.0,edge,blur),0.0,1.0); - float e = clamp(smoothstep(1.0-edge,1.0,blur),0.0,1.0); - - col = mix(col,vec3(1.0,0.5,0.0),(1.0-m)*0.6); - col = mix(col,vec3(0.0,0.5,1.0),((1.0-e)-(1.0-m))*0.2); - - return col; - } - - float linearize(float depth) { - return -zfar * znear / (depth * (zfar - znear) - zfar); - } - - float vignette() { - float dist = distance(vUv.xy, vec2(0.5,0.5)); - dist = smoothstep(vignout+(fstop/vignfade), vignin+(fstop/vignfade), dist); - return clamp(dist,0.0,1.0); - } - - float gather(float i, float j, int ringsamples, inout vec3 col, float w, float h, float blur) { - float rings2 = float(rings); - float step = PI*2.0 / float(ringsamples); - float pw = cos(j*step)*i; - float ph = sin(j*step)*i; - float p = 1.0; - if (pentagon) { - p = penta(vec2(pw,ph)); - } - col += color(vUv.xy + vec2(pw*w,ph*h), blur) * mix(1.0, i/rings2, bias) * p; - return 1.0 * mix(1.0, i /rings2, bias) * p; - } - - void main() { - //scene depth calculation - - float depth = linearize(texture2D(tDepth,vUv.xy).x); - - // Blur depth? - if ( depthblur ) { - depth = linearize(bdepth(vUv.xy)); - } - - //focal plane calculation - - float fDepth = focalDepth; - - if (shaderFocus) { - - fDepth = linearize(texture2D(tDepth,focusCoords).x); - - } - - // dof blur factor calculation - - float blur = 0.0; - - if (manualdof) { - float a = depth-fDepth; // Focal plane - float b = (a-fdofstart)/fdofdist; // Far DoF - float c = (-a-ndofstart)/ndofdist; // Near Dof - blur = (a>0.0) ? b : c; - } else { - float f = focalLength; // focal length in mm - float d = fDepth*1000.0; // focal plane in mm - float o = depth*1000.0; // depth in mm - - float a = (o*f)/(o-f); - float b = (d*f)/(d-f); - float c = (d-f)/(d*fstop*CoC); - - blur = abs(a-b)*c; - } - - blur = clamp(blur,0.0,1.0); - - // calculation of pattern for dithering - - vec2 noise = vec2(rand(vUv.xy), rand( vUv.xy + vec2( 0.4, 0.6 ) ) )*dithering*blur; - - // getting blur x and y step factor - - float w = (1.0/textureWidth)*blur*maxblur+noise.x; - float h = (1.0/textureHeight)*blur*maxblur+noise.y; - - // calculation of final color - - vec3 col = vec3(0.0); - - if(blur < 0.05) { - //some optimization thingy - col = texture2D(tColor, vUv.xy).rgb; - } else { - col = texture2D(tColor, vUv.xy).rgb; - float s = 1.0; - int ringsamples; - - for (int i = 1; i <= rings; i++) { - /*unboxstart*/ - ringsamples = i * samples; - - for (int j = 0 ; j < maxringsamples ; j++) { - if (j >= ringsamples) break; - s += gather(float(i), float(j), ringsamples, col, w, h, blur); - } - /*unboxend*/ - } - - col /= s; //divide by sample count - } - - if (showFocus) { - col = debugFocus(col, blur, depth); - } - - if (vignetting) { - col *= vignette(); - } - - gl_FragColor.rgb = col; - gl_FragColor.a = 1.0; - - #include - #include - }`};var im={name:"ColorCorrectionShader",uniforms:{tDiffuse:{value:null},powRGB:{value:new y(2,2,2)},mulRGB:{value:new y(1,1,1)},addRGB:{value:new y(0,0,0)}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform sampler2D tDiffuse; - uniform vec3 powRGB; - uniform vec3 mulRGB; - uniform vec3 addRGB; - - varying vec2 vUv; - - void main() { - - gl_FragColor = texture2D( tDiffuse, vUv ); - gl_FragColor.rgb = mulRGB * pow( ( gl_FragColor.rgb + addRGB ), powRGB ); - - }`};var am={name:"ColorifyShader",uniforms:{tDiffuse:{value:null},color:{value:new a(16777215)}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform vec3 color; - uniform sampler2D tDiffuse; - - varying vec2 vUv; - - void main() { - - vec4 texel = texture2D( tDiffuse, vUv ); - - float v = luminance( texel.xyz ); - - gl_FragColor = vec4( v * color, texel.w ); - - }`};var Ec={name:"FXAAShader",uniforms:{tDiffuse:{value:null},resolution:{value:new AA(0.0009765625,0.001953125)}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - // FXAA algorithm from NVIDIA, C# implementation by Jasper Flick, GLSL port by Dave Hoskins - // http://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf - // https://catlikecoding.com/unity/tutorials/advanced-rendering/fxaa/ - - uniform sampler2D tDiffuse; - uniform vec2 resolution; - varying vec2 vUv; - - #define EDGE_STEP_COUNT 6 - #define EDGE_GUESS 8.0 - #define EDGE_STEPS 1.0, 1.5, 2.0, 2.0, 2.0, 4.0 - const float edgeSteps[EDGE_STEP_COUNT] = float[EDGE_STEP_COUNT]( EDGE_STEPS ); - - float _ContrastThreshold = 0.0312; - float _RelativeThreshold = 0.063; - float _SubpixelBlending = 1.0; - - vec4 Sample( sampler2D tex2D, vec2 uv ) { - - return texture( tex2D, uv ); - - } - - float SampleLuminance( sampler2D tex2D, vec2 uv ) { - - return dot( Sample( tex2D, uv ).rgb, vec3( 0.3, 0.59, 0.11 ) ); - - } - - float SampleLuminance( sampler2D tex2D, vec2 texSize, vec2 uv, float uOffset, float vOffset ) { - - uv += texSize * vec2(uOffset, vOffset); - return SampleLuminance(tex2D, uv); - - } - - struct LuminanceData { - - float m, n, e, s, w; - float ne, nw, se, sw; - float highest, lowest, contrast; - - }; - - LuminanceData SampleLuminanceNeighborhood( sampler2D tex2D, vec2 texSize, vec2 uv ) { - - LuminanceData l; - l.m = SampleLuminance( tex2D, uv ); - l.n = SampleLuminance( tex2D, texSize, uv, 0.0, 1.0 ); - l.e = SampleLuminance( tex2D, texSize, uv, 1.0, 0.0 ); - l.s = SampleLuminance( tex2D, texSize, uv, 0.0, -1.0 ); - l.w = SampleLuminance( tex2D, texSize, uv, -1.0, 0.0 ); - - l.ne = SampleLuminance( tex2D, texSize, uv, 1.0, 1.0 ); - l.nw = SampleLuminance( tex2D, texSize, uv, -1.0, 1.0 ); - l.se = SampleLuminance( tex2D, texSize, uv, 1.0, -1.0 ); - l.sw = SampleLuminance( tex2D, texSize, uv, -1.0, -1.0 ); - - l.highest = max( max( max( max( l.n, l.e ), l.s ), l.w ), l.m ); - l.lowest = min( min( min( min( l.n, l.e ), l.s ), l.w ), l.m ); - l.contrast = l.highest - l.lowest; - return l; - - } - - bool ShouldSkipPixel( LuminanceData l ) { - - float threshold = max( _ContrastThreshold, _RelativeThreshold * l.highest ); - return l.contrast < threshold; - - } - - float DeterminePixelBlendFactor( LuminanceData l ) { - - float f = 2.0 * ( l.n + l.e + l.s + l.w ); - f += l.ne + l.nw + l.se + l.sw; - f *= 1.0 / 12.0; - f = abs( f - l.m ); - f = clamp( f / l.contrast, 0.0, 1.0 ); - - float blendFactor = smoothstep( 0.0, 1.0, f ); - return blendFactor * blendFactor * _SubpixelBlending; - - } - - struct EdgeData { - - bool isHorizontal; - float pixelStep; - float oppositeLuminance, gradient; - - }; - - EdgeData DetermineEdge( vec2 texSize, LuminanceData l ) { - - EdgeData e; - float horizontal = - abs( l.n + l.s - 2.0 * l.m ) * 2.0 + - abs( l.ne + l.se - 2.0 * l.e ) + - abs( l.nw + l.sw - 2.0 * l.w ); - float vertical = - abs( l.e + l.w - 2.0 * l.m ) * 2.0 + - abs( l.ne + l.nw - 2.0 * l.n ) + - abs( l.se + l.sw - 2.0 * l.s ); - e.isHorizontal = horizontal >= vertical; - - float pLuminance = e.isHorizontal ? l.n : l.e; - float nLuminance = e.isHorizontal ? l.s : l.w; - float pGradient = abs( pLuminance - l.m ); - float nGradient = abs( nLuminance - l.m ); - - e.pixelStep = e.isHorizontal ? texSize.y : texSize.x; - - if (pGradient < nGradient) { - - e.pixelStep = -e.pixelStep; - e.oppositeLuminance = nLuminance; - e.gradient = nGradient; - - } else { - - e.oppositeLuminance = pLuminance; - e.gradient = pGradient; - - } - - return e; - - } - - float DetermineEdgeBlendFactor( sampler2D tex2D, vec2 texSize, LuminanceData l, EdgeData e, vec2 uv ) { - - vec2 uvEdge = uv; - vec2 edgeStep; - if (e.isHorizontal) { - - uvEdge.y += e.pixelStep * 0.5; - edgeStep = vec2( texSize.x, 0.0 ); - - } else { - - uvEdge.x += e.pixelStep * 0.5; - edgeStep = vec2( 0.0, texSize.y ); - - } - - float edgeLuminance = ( l.m + e.oppositeLuminance ) * 0.5; - float gradientThreshold = e.gradient * 0.25; - - vec2 puv = uvEdge + edgeStep * edgeSteps[0]; - float pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; - bool pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; - - for ( int i = 1; i < EDGE_STEP_COUNT && !pAtEnd; i++ ) { - - puv += edgeStep * edgeSteps[i]; - pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; - pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; - - } - - if ( !pAtEnd ) { - - puv += edgeStep * EDGE_GUESS; - - } - - vec2 nuv = uvEdge - edgeStep * edgeSteps[0]; - float nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; - bool nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; - - for ( int i = 1; i < EDGE_STEP_COUNT && !nAtEnd; i++ ) { - - nuv -= edgeStep * edgeSteps[i]; - nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; - nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; - - } - - if ( !nAtEnd ) { - - nuv -= edgeStep * EDGE_GUESS; - - } - - float pDistance, nDistance; - if ( e.isHorizontal ) { - - pDistance = puv.x - uv.x; - nDistance = uv.x - nuv.x; - - } else { - - pDistance = puv.y - uv.y; - nDistance = uv.y - nuv.y; - - } - - float shortestDistance; - bool deltaSign; - if ( pDistance <= nDistance ) { - - shortestDistance = pDistance; - deltaSign = pLuminanceDelta >= 0.0; - - } else { - - shortestDistance = nDistance; - deltaSign = nLuminanceDelta >= 0.0; - - } - - if ( deltaSign == ( l.m - edgeLuminance >= 0.0 ) ) { - - return 0.0; - - } - - return 0.5 - shortestDistance / ( pDistance + nDistance ); - - } - - vec4 ApplyFXAA( sampler2D tex2D, vec2 texSize, vec2 uv ) { - - LuminanceData luminance = SampleLuminanceNeighborhood( tex2D, texSize, uv ); - if ( ShouldSkipPixel( luminance ) ) { - - return Sample( tex2D, uv ); - - } - - float pixelBlend = DeterminePixelBlendFactor( luminance ); - EdgeData edge = DetermineEdge( texSize, luminance ); - float edgeBlend = DetermineEdgeBlendFactor( tex2D, texSize, luminance, edge, uv ); - float finalBlend = max( pixelBlend, edgeBlend ); - - if (edge.isHorizontal) { - - uv.y += edge.pixelStep * finalBlend; - - } else { - - uv.x += edge.pixelStep * finalBlend; - - } - - return Sample( tex2D, uv ); - - } - - void main() { - - gl_FragColor = ApplyFXAA( tDiffuse, resolution.xy, vUv ); - - }`};var Kc={name:"FreiChenShader",uniforms:{tDiffuse:{value:null},aspect:{value:new AA(512,512)}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform sampler2D tDiffuse; - varying vec2 vUv; - - uniform vec2 aspect; - - vec2 texel = vec2( 1.0 / aspect.x, 1.0 / aspect.y ); - - - mat3 G[9]; - - // hard coded matrix values!!!! as suggested in https://github.com/neilmendoza/ofxPostProcessing/blob/master/src/EdgePass.cpp#L45 - - const mat3 g0 = mat3( 0.3535533845424652, 0, -0.3535533845424652, 0.5, 0, -0.5, 0.3535533845424652, 0, -0.3535533845424652 ); - const mat3 g1 = mat3( 0.3535533845424652, 0.5, 0.3535533845424652, 0, 0, 0, -0.3535533845424652, -0.5, -0.3535533845424652 ); - const mat3 g2 = mat3( 0, 0.3535533845424652, -0.5, -0.3535533845424652, 0, 0.3535533845424652, 0.5, -0.3535533845424652, 0 ); - const mat3 g3 = mat3( 0.5, -0.3535533845424652, 0, -0.3535533845424652, 0, 0.3535533845424652, 0, 0.3535533845424652, -0.5 ); - const mat3 g4 = mat3( 0, -0.5, 0, 0.5, 0, 0.5, 0, -0.5, 0 ); - const mat3 g5 = mat3( -0.5, 0, 0.5, 0, 0, 0, 0.5, 0, -0.5 ); - const mat3 g6 = mat3( 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.6666666865348816, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204 ); - const mat3 g7 = mat3( -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, 0.6666666865348816, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408 ); - const mat3 g8 = mat3( 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408 ); - - void main(void) - { - - G[0] = g0, - G[1] = g1, - G[2] = g2, - G[3] = g3, - G[4] = g4, - G[5] = g5, - G[6] = g6, - G[7] = g7, - G[8] = g8; - - mat3 I; - float cnv[9]; - vec3 sample; - - /* fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */ - for (float i=0.0; i<3.0; i++) { - for (float j=0.0; j<3.0; j++) { - sample = texture2D(tDiffuse, vUv + texel * vec2(i-1.0,j-1.0) ).rgb; - I[int(i)][int(j)] = length(sample); - } - } - - /* calculate the convolution values for all the masks */ - for (int i=0; i<9; i++) { - float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]); - cnv[i] = dp3 * dp3; - } - - float M = (cnv[0] + cnv[1]) + (cnv[2] + cnv[3]); - float S = (cnv[4] + cnv[5]) + (cnv[6] + cnv[7]) + (cnv[8] + M); - - gl_FragColor = vec4(vec3(sqrt(M/S)), 1.0); - }`};var Oc={name:"GodRaysGenerateShader",uniforms:{tInput:{value:null},fStepSize:{value:1},vSunPositionScreenSpace:{value:new y}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - #define TAPS_PER_PASS 6.0 - - varying vec2 vUv; - - uniform sampler2D tInput; - - uniform vec3 vSunPositionScreenSpace; - uniform float fStepSize; // filter step size - - void main() { - - // delta from current pixel to "sun" position - - vec2 delta = vSunPositionScreenSpace.xy - vUv; - float dist = length( delta ); - - // Step vector (uv space) - - vec2 stepv = fStepSize * delta / dist; - - // Number of iterations between pixel and sun - - float iters = dist/fStepSize; - - vec2 uv = vUv.xy; - float col = 0.0; - - // This breaks ANGLE in Chrome 22 - // - see http://code.google.com/p/chromium/issues/detail?id=153105 - - /* - // Unrolling didn't do much on my hardware (ATI Mobility Radeon 3450), - // so i've just left the loop - - "for ( float i = 0.0; i < TAPS_PER_PASS; i += 1.0 ) {", - - // Accumulate samples, making sure we don't walk past the light source. - - // The check for uv.y < 1 would not be necessary with "border" UV wrap - // mode, with a black border color. I don't think this is currently - // exposed by three.js. As a result there might be artifacts when the - // sun is to the left, right or bottom of screen as these cases are - // not specifically handled. - - " col += ( i <= iters && uv.y < 1.0 ? texture2D( tInput, uv ).r : 0.0 );", - " uv += stepv;", - - "}", - */ - - // Unrolling loop manually makes it work in ANGLE - - float f = min( 1.0, max( vSunPositionScreenSpace.z / 1000.0, 0.0 ) ); // used to fade out godrays - - if ( 0.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; - uv += stepv; - - if ( 1.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; - uv += stepv; - - if ( 2.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; - uv += stepv; - - if ( 3.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; - uv += stepv; - - if ( 4.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; - uv += stepv; - - if ( 5.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; - uv += stepv; - - // Should technically be dividing by 'iters but 'TAPS_PER_PASS' smooths out - // objectionable artifacts, in particular near the sun position. The side - // effect is that the result is darker than it should be around the sun, as - // TAPS_PER_PASS is greater than the number of samples actually accumulated. - // When the result is inverted (in the shader 'godrays_combine this produces - // a slight bright spot at the position of the sun, even when it is occluded. - - gl_FragColor = vec4( col/TAPS_PER_PASS ); - gl_FragColor.a = 1.0; - - }`};var Hc={name:"GodRaysFakeSunShader",uniforms:{vSunPositionScreenSpace:{value:new y},fAspect:{value:1},sunColor:{value:new a(16772608)},bgColor:{value:new a(0)}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - varying vec2 vUv; - - uniform vec3 vSunPositionScreenSpace; - uniform float fAspect; - - uniform vec3 sunColor; - uniform vec3 bgColor; - - void main() { - - vec2 diff = vUv - vSunPositionScreenSpace.xy; - - // Correct for aspect ratio - - diff.x *= fAspect; - - float prop = clamp( length( diff ) / 0.5, 0.0, 1.0 ); - prop = 0.35 * pow( 1.0 - prop, 3.0 ); - - gl_FragColor.xyz = ( vSunPositionScreenSpace.z > 0.0 ) ? mix( sunColor, bgColor, 1.0 - prop ) : bgColor; - gl_FragColor.w = 1.0; - - }`};var qc={name:"NormalMapShader",uniforms:{heightMap:{value:null},resolution:{value:new AA(512,512)},scale:{value:new AA(1,1)},height:{value:0.05}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform float height; - uniform vec2 resolution; - uniform sampler2D heightMap; - - varying vec2 vUv; - - void main() { - - float val = texture2D( heightMap, vUv ).x; - - float valU = texture2D( heightMap, vUv + vec2( 1.0 / resolution.x, 0.0 ) ).x; - float valV = texture2D( heightMap, vUv + vec2( 0.0, 1.0 / resolution.y ) ).x; - - gl_FragColor = vec4( ( 0.5 * normalize( vec3( val - valU, val - valV, height ) ) + 0.5 ), 1.0 ); - - }`};var _c={name:"SobelOperatorShader",uniforms:{tDiffuse:{value:null},resolution:{value:new AA}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - uniform sampler2D tDiffuse; - uniform vec2 resolution; - varying vec2 vUv; - - void main() { - - vec2 texel = vec2( 1.0 / resolution.x, 1.0 / resolution.y ); - - // kernel definition (in glsl matrices are filled in column-major order) - - const mat3 Gx = mat3( -1, -2, -1, 0, 0, 0, 1, 2, 1 ); // x direction kernel - const mat3 Gy = mat3( -1, 0, 1, -2, 0, 2, -1, 0, 1 ); // y direction kernel - - // fetch the 3x3 neighbourhood of a fragment - - // first column - - float tx0y0 = texture2D( tDiffuse, vUv + texel * vec2( -1, -1 ) ).r; - float tx0y1 = texture2D( tDiffuse, vUv + texel * vec2( -1, 0 ) ).r; - float tx0y2 = texture2D( tDiffuse, vUv + texel * vec2( -1, 1 ) ).r; - - // second column - - float tx1y0 = texture2D( tDiffuse, vUv + texel * vec2( 0, -1 ) ).r; - float tx1y1 = texture2D( tDiffuse, vUv + texel * vec2( 0, 0 ) ).r; - float tx1y2 = texture2D( tDiffuse, vUv + texel * vec2( 0, 1 ) ).r; - - // third column - - float tx2y0 = texture2D( tDiffuse, vUv + texel * vec2( 1, -1 ) ).r; - float tx2y1 = texture2D( tDiffuse, vUv + texel * vec2( 1, 0 ) ).r; - float tx2y2 = texture2D( tDiffuse, vUv + texel * vec2( 1, 1 ) ).r; - - // gradient value in x direction - - float valueGx = Gx[0][0] * tx0y0 + Gx[1][0] * tx1y0 + Gx[2][0] * tx2y0 + - Gx[0][1] * tx0y1 + Gx[1][1] * tx1y1 + Gx[2][1] * tx2y1 + - Gx[0][2] * tx0y2 + Gx[1][2] * tx1y2 + Gx[2][2] * tx2y2; - - // gradient value in y direction - - float valueGy = Gy[0][0] * tx0y0 + Gy[1][0] * tx1y0 + Gy[2][0] * tx2y0 + - Gy[0][1] * tx0y1 + Gy[1][1] * tx1y1 + Gy[2][1] * tx2y1 + - Gy[0][2] * tx0y2 + Gy[1][2] * tx1y2 + Gy[2][2] * tx2y2; - - // magnitude of the total gradient - - float G = sqrt( ( valueGx * valueGx ) + ( valueGy * valueGy ) ); - - gl_FragColor = vec4( vec3( G ), 1 ); - - }`};function JS(A,Q,E){return A.split(Q).join(E)}var US=G0.meshphong_frag.slice(0,G0.meshphong_frag.indexOf("void main() {")),YS=G0.meshphong_frag.slice(G0.meshphong_frag.indexOf("void main() {")),Tc={name:"SubsurfaceScatteringShader",uniforms:oA.merge([CE.phong.uniforms,{thicknessMap:{value:null},thicknessColor:{value:new a(16777215)},thicknessDistortion:{value:0.1},thicknessAmbient:{value:0},thicknessAttenuation:{value:0.1},thicknessPower:{value:2},thicknessScale:{value:10}}]),vertexShader:["#define USE_UV",G0.meshphong_vert].join(` -`),fragmentShader:["#define USE_UV","#define SUBSURFACE",US,"uniform sampler2D thicknessMap;","uniform float thicknessPower;","uniform float thicknessScale;","uniform float thicknessDistortion;","uniform float thicknessAmbient;","uniform float thicknessAttenuation;","uniform vec3 thicknessColor;","void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, inout ReflectedLight reflectedLight) {","\tvec3 thickness = thicknessColor * texture2D(thicknessMap, uv).r;","\tvec3 scatteringHalf = normalize(directLight.direction + (geometryNormal * thicknessDistortion));","\tfloat scatteringDot = pow(saturate(dot(geometryViewDir, -scatteringHalf)), thicknessPower) * thicknessScale;","\tvec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;","\treflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;","}",YS.replace("#include ",JS(G0.lights_fragment_begin,"RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );",["RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );","#if defined( SUBSURFACE ) && defined( USE_UV )"," RE_Direct_Scattering(directLight, vUv, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, reflectedLight);","#endif"].join(` -`)))].join(` -`)};var jc={uniforms:{uDirLightPos:{value:new y},uDirLightColor:{value:new a(15658734)},uAmbientLightColor:{value:new a(328965)},uBaseColor:{value:new a(16777215)}},vertexShader:` - - varying vec3 vNormal; - varying vec3 vRefract; - - void main() { - - vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); - vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); - vec3 worldNormal = normalize ( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal ); - - vNormal = normalize( normalMatrix * normal ); - - vec3 I = worldPosition.xyz - cameraPosition; - vRefract = refract( normalize( I ), worldNormal, 1.02 ); - - gl_Position = projectionMatrix * mvPosition; - - }`,fragmentShader:` - - uniform vec3 uBaseColor; - - uniform vec3 uDirLightPos; - uniform vec3 uDirLightColor; - - uniform vec3 uAmbientLightColor; - - varying vec3 vNormal; - - varying vec3 vRefract; - - void main() { - - float directionalLightWeighting = max( dot( normalize( vNormal ), uDirLightPos ), 0.0); - vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; - - float intensity = smoothstep( - 0.5, 1.0, pow( length(lightWeighting), 20.0 ) ); - intensity += length(lightWeighting) * 0.2; - - float cameraWeighting = dot( normalize( vNormal ), vRefract ); - intensity += pow( 1.0 - length( cameraWeighting ), 6.0 ); - intensity = intensity * 0.2 + 0.3; - - if ( intensity < 0.50 ) { - - gl_FragColor = vec4( 2.0 * intensity * uBaseColor, 1.0 ); - - } else { - - gl_FragColor = vec4( 1.0 - 2.0 * ( 1.0 - intensity ) * ( 1.0 - uBaseColor ), 1.0 ); - - } - - #include - - }`},vc={uniforms:{uDirLightPos:{value:new y},uDirLightColor:{value:new a(15658734)},uAmbientLightColor:{value:new a(328965)},uBaseColor:{value:new a(15658734)},uLineColor1:{value:new a(8421504)},uLineColor2:{value:new a(0)},uLineColor3:{value:new a(0)},uLineColor4:{value:new a(0)}},vertexShader:` - - varying vec3 vNormal; - - void main() { - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - vNormal = normalize( normalMatrix * normal ); - - }`,fragmentShader:` - - uniform vec3 uBaseColor; - uniform vec3 uLineColor1; - uniform vec3 uLineColor2; - uniform vec3 uLineColor3; - uniform vec3 uLineColor4; - - uniform vec3 uDirLightPos; - uniform vec3 uDirLightColor; - - uniform vec3 uAmbientLightColor; - - varying vec3 vNormal; - - void main() { - - float camera = max( dot( normalize( vNormal ), vec3( 0.0, 0.0, 1.0 ) ), 0.4); - float light = max( dot( normalize( vNormal ), uDirLightPos ), 0.0); - - gl_FragColor = vec4( uBaseColor, 1.0 ); - - if ( length(uAmbientLightColor + uDirLightColor * light) < 1.00 ) { - - gl_FragColor *= vec4( uLineColor1, 1.0 ); - - } - - if ( length(uAmbientLightColor + uDirLightColor * camera) < 0.50 ) { - - gl_FragColor *= vec4( uLineColor2, 1.0 ); - - } - - #include - - }`},hc={uniforms:{uDirLightPos:{value:new y},uDirLightColor:{value:new a(15658734)},uAmbientLightColor:{value:new a(328965)},uBaseColor:{value:new a(16777215)},uLineColor1:{value:new a(0)},uLineColor2:{value:new a(0)},uLineColor3:{value:new a(0)},uLineColor4:{value:new a(0)}},vertexShader:` - - varying vec3 vNormal; - - void main() { - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - vNormal = normalize( normalMatrix * normal ); - - }`,fragmentShader:` - - uniform vec3 uBaseColor; - uniform vec3 uLineColor1; - uniform vec3 uLineColor2; - uniform vec3 uLineColor3; - uniform vec3 uLineColor4; - - uniform vec3 uDirLightPos; - uniform vec3 uDirLightColor; - - uniform vec3 uAmbientLightColor; - - varying vec3 vNormal; - - void main() { - - float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0); - vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; - - gl_FragColor = vec4( uBaseColor, 1.0 ); - - if ( length(lightWeighting) < 1.00 ) { - - if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) { - - gl_FragColor = vec4( uLineColor1, 1.0 ); - - } - - } - - if ( length(lightWeighting) < 0.75 ) { - - if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) { - - gl_FragColor = vec4( uLineColor2, 1.0 ); - - } - - } - - if ( length(lightWeighting) < 0.50 ) { - - if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) { - - gl_FragColor = vec4( uLineColor3, 1.0 ); - - } - - } - - if ( length(lightWeighting) < 0.3465 ) { - - if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) { - - gl_FragColor = vec4( uLineColor4, 1.0 ); - - } - - } - - #include - - }`},yc={uniforms:{uDirLightPos:{value:new y},uDirLightColor:{value:new a(15658734)},uAmbientLightColor:{value:new a(328965)},uBaseColor:{value:new a(16777215)},uLineColor1:{value:new a(0)}},vertexShader:` - - varying vec3 vNormal; - - void main() { - - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - vNormal = normalize( normalMatrix * normal ); - - }`,fragmentShader:` - - uniform vec3 uBaseColor; - uniform vec3 uLineColor1; - uniform vec3 uLineColor2; - uniform vec3 uLineColor3; - uniform vec3 uLineColor4; - - uniform vec3 uDirLightPos; - uniform vec3 uDirLightColor; - - uniform vec3 uAmbientLightColor; - - varying vec3 vNormal; - - void main() { - - float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0); - vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; - - gl_FragColor = vec4( uBaseColor, 1.0 ); - - if ( length(lightWeighting) < 1.00 ) { - - if ( ( mod(gl_FragCoord.x, 4.001) + mod(gl_FragCoord.y, 4.0) ) > 6.00 ) { - - gl_FragColor = vec4( uLineColor1, 1.0 ); - - } - - } - - if ( length(lightWeighting) < 0.50 ) { - - if ( ( mod(gl_FragCoord.x + 2.0, 4.001) + mod(gl_FragCoord.y + 2.0, 4.0) ) > 6.00 ) { - - gl_FragColor = vec4( uLineColor1, 1.0 ); - - } - - } - - #include - - }`};var bc={name:"TriangleBlurShader",uniforms:{texture:{value:null},delta:{value:new AA(1,1)}},vertexShader:` - - varying vec2 vUv; - - void main() { - - vUv = uv; - gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); - - }`,fragmentShader:` - - #include - - #define ITERATIONS 10.0 - - uniform sampler2D texture; - uniform vec2 delta; - - varying vec2 vUv; - - void main() { - - vec4 color = vec4( 0.0 ); - - float total = 0.0; - - // randomize the lookup values to hide the fixed number of samples - - float offset = rand( vUv ); - - for ( float t = -ITERATIONS; t <= ITERATIONS; t ++ ) { - - float percent = ( t + offset - 0.5 ) / ITERATIONS; - float weight = 1.0 - abs( percent ); - - color += texture2D( texture, vUv + delta * percent ) * weight; - total += weight; - - } - - gl_FragColor = color / total; - - }`};var mc={name:"VelocityShader",uniforms:oA.merge([vA.common,vA.displacementmap,{modelMatrixPrev:{value:new RA},currentProjectionViewMatrix:{value:new RA},previousProjectionViewMatrix:{value:new RA}}]),vertexShader:` -#define NORMAL - -#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) - - varying vec3 vViewPosition; - -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -uniform mat4 previousProjectionViewMatrix; -uniform mat4 currentProjectionViewMatrix; - -uniform mat4 modelMatrixPrev; - -varying vec4 clipPositionCurrent; -varying vec4 clipPositionPrevious; - -void main() { - - - #include - - #include - #include - #include - #include - #include - #include - - #include - #include - #include - #include - #include - -#ifdef USE_SKINNING - - vec4 mvPosition = modelViewMatrix * skinned; - clipPositionCurrent = currentProjectionViewMatrix * modelMatrix * skinned; - clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * skinned; - -#else - - vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 ); - clipPositionCurrent = currentProjectionViewMatrix * modelMatrix * vec4( transformed, 1.0 ); - clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * vec4( transformed, 1.0 ); - -#endif - - gl_Position = projectionMatrix * mvPosition; - - #include - #include -} -`,fragmentShader:` -#define NORMAL - -uniform float opacity; - -#include -#include -#include -#include -#include -#include -#include - -varying vec4 clipPositionCurrent; -varying vec4 clipPositionPrevious; - -void main() { - - vec4 diffuseColor = vec4( 1.0 ); - diffuseColor.a = opacity; - - #include - #include - #include - - vec2 ndcPositionCurrent = clipPositionCurrent.xy/clipPositionCurrent.w; - vec2 ndcPositionPrevious = clipPositionPrevious.xy/clipPositionPrevious.w; - vec2 vel = ( ndcPositionCurrent - ndcPositionPrevious ) * 0.5; - vel = vel * 0.5 + 0.5; - vec2 v1 = packDepthToRG(vel.x); - vec2 v2 = packDepthToRG(vel.y); - gl_FragColor = vec4(v1.x, v1.y, v2.x, v2.y); - - #include - -} - -`};var ic={uniforms:{u_size:{value:new y(1,1,1)},u_renderstyle:{value:0},u_renderthreshold:{value:0.5},u_clim:{value:new AA(1,1)},u_data:{value:null},u_cmdata:{value:null}},vertexShader:` - - varying vec4 v_nearpos; - varying vec4 v_farpos; - varying vec3 v_position; - - void main() { - // Prepare transforms to map to "camera view". See also: - // https://threejs.org/docs/#api/renderers/webgl/WebGLProgram - mat4 viewtransformf = modelViewMatrix; - mat4 viewtransformi = inverse(modelViewMatrix); - - // Project local vertex coordinate to camera position. Then do a step - // backward (in cam coords) to the near clipping plane, and project back. Do - // the same for the far clipping plane. This gives us all the information we - // need to calculate the ray and truncate it to the viewing cone. - vec4 position4 = vec4(position, 1.0); - vec4 pos_in_cam = viewtransformf * position4; - - // Intersection of ray and near clipping plane (z = -1 in clip coords) - pos_in_cam.z = -pos_in_cam.w; - v_nearpos = viewtransformi * pos_in_cam; - - // Intersection of ray and far clipping plane (z = +1 in clip coords) - pos_in_cam.z = pos_in_cam.w; - v_farpos = viewtransformi * pos_in_cam; - - // Set varyings and output pos - v_position = position; - gl_Position = projectionMatrix * viewMatrix * modelMatrix * position4; - }`,fragmentShader:` - - precision highp float; - precision mediump sampler3D; - - uniform vec3 u_size; - uniform int u_renderstyle; - uniform float u_renderthreshold; - uniform vec2 u_clim; - - uniform sampler3D u_data; - uniform sampler2D u_cmdata; - - varying vec3 v_position; - varying vec4 v_nearpos; - varying vec4 v_farpos; - - // The maximum distance through our rendering volume is sqrt(3). - const int MAX_STEPS = 887; // 887 for 512^3, 1774 for 1024^3 - const int REFINEMENT_STEPS = 4; - const float relative_step_size = 1.0; - const vec4 ambient_color = vec4(0.2, 0.4, 0.2, 1.0); - const vec4 diffuse_color = vec4(0.8, 0.2, 0.2, 1.0); - const vec4 specular_color = vec4(1.0, 1.0, 1.0, 1.0); - const float shininess = 40.0; - - void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray); - void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray); - - float sample1(vec3 texcoords); - vec4 apply_colormap(float val); - vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray); - - - void main() { - // Normalize clipping plane info - vec3 farpos = v_farpos.xyz / v_farpos.w; - vec3 nearpos = v_nearpos.xyz / v_nearpos.w; - - // Calculate unit vector pointing in the view direction through this fragment. - vec3 view_ray = normalize(nearpos.xyz - farpos.xyz); - - // Compute the (negative) distance to the front surface or near clipping plane. - // v_position is the back face of the cuboid, so the initial distance calculated in the dot - // product below is the distance from near clip plane to the back of the cuboid - float distance = dot(nearpos - v_position, view_ray); - distance = max(distance, min((-0.5 - v_position.x) / view_ray.x, - (u_size.x - 0.5 - v_position.x) / view_ray.x)); - distance = max(distance, min((-0.5 - v_position.y) / view_ray.y, - (u_size.y - 0.5 - v_position.y) / view_ray.y)); - distance = max(distance, min((-0.5 - v_position.z) / view_ray.z, - (u_size.z - 0.5 - v_position.z) / view_ray.z)); - - // Now we have the starting position on the front surface - vec3 front = v_position + view_ray * distance; - - // Decide how many steps to take - int nsteps = int(-distance / relative_step_size + 0.5); - if ( nsteps < 1 ) - discard; - - // Get starting location and step vector in texture coordinates - vec3 step = ((v_position - front) / u_size) / float(nsteps); - vec3 start_loc = front / u_size; - - // For testing: show the number of steps. This helps to establish - // whether the rays are correctly oriented - //'gl_FragColor = vec4(0.0, float(nsteps) / 1.0 / u_size.x, 1.0, 1.0); - //'return; - - if (u_renderstyle == 0) - cast_mip(start_loc, step, nsteps, view_ray); - else if (u_renderstyle == 1) - cast_iso(start_loc, step, nsteps, view_ray); - - if (gl_FragColor.a < 0.05) - discard; - } - - - float sample1(vec3 texcoords) { - /* Sample float value from a 3D texture. Assumes intensity data. */ - return texture(u_data, texcoords.xyz).r; - } - - - vec4 apply_colormap(float val) { - val = (val - u_clim[0]) / (u_clim[1] - u_clim[0]); - return texture2D(u_cmdata, vec2(val, 0.5)); - } - - - void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) { - - float max_val = -1e6; - int max_i = 100; - vec3 loc = start_loc; - - // Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with - // non-constant expression. So we use a hard-coded max, and an additional condition - // inside the loop. - for (int iter=0; iter= nsteps) - break; - // Sample from the 3D texture - float val = sample1(loc); - // Apply MIP operation - if (val > max_val) { - max_val = val; - max_i = iter; - } - // Advance location deeper into the volume - loc += step; - } - - // Refine location, gives crispier images - vec3 iloc = start_loc + step * (float(max_i) - 0.5); - vec3 istep = step / float(REFINEMENT_STEPS); - for (int i=0; i= nsteps) - break; - - // Sample from the 3D texture - float val = sample1(loc); - - if (val > low_threshold) { - // Take the last interval in smaller steps - vec3 iloc = loc - 0.5 * step; - vec3 istep = step / float(REFINEMENT_STEPS); - for (int i=0; i u_renderthreshold) { - gl_FragColor = add_lighting(val, iloc, dstep, view_ray); - return; - } - iloc += istep; - } - } - - // Advance location deeper into the volume - loc += step; - } - } - - - vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray) - { - // Calculate color by incorporating lighting - - // View direction - vec3 V = normalize(view_ray); - - // calculate normal vector from gradient - vec3 N; - float val1, val2; - val1 = sample1(loc + vec3(-step[0], 0.0, 0.0)); - val2 = sample1(loc + vec3(+step[0], 0.0, 0.0)); - N[0] = val1 - val2; - val = max(max(val1, val2), val); - val1 = sample1(loc + vec3(0.0, -step[1], 0.0)); - val2 = sample1(loc + vec3(0.0, +step[1], 0.0)); - N[1] = val1 - val2; - val = max(max(val1, val2), val); - val1 = sample1(loc + vec3(0.0, 0.0, -step[2])); - val2 = sample1(loc + vec3(0.0, 0.0, +step[2])); - N[2] = val1 - val2; - val = max(max(val1, val2), val); - - float gm = length(N); // gradient magnitude - N = normalize(N); - - // Flip normal so it points towards viewer - float Nselect = float(dot(N, V) > 0.0); - N = (2.0 * Nselect - 1.0) * N; // == Nselect * N - (1.0-Nselect)*N; - - // Init colors - vec4 ambient_color = vec4(0.0, 0.0, 0.0, 0.0); - vec4 diffuse_color = vec4(0.0, 0.0, 0.0, 0.0); - vec4 specular_color = vec4(0.0, 0.0, 0.0, 0.0); - - // note: could allow multiple lights - for (int i=0; i<1; i++) - { - // Get light direction (make sure to prevent zero devision) - vec3 L = normalize(view_ray); //lightDirs[i]; - float lightEnabled = float( length(L) > 0.0 ); - L = normalize(L + (1.0 - lightEnabled)); - - // Calculate lighting properties - float lambertTerm = clamp(dot(N, L), 0.0, 1.0); - vec3 H = normalize(L+V); // Halfway vector - float specularTerm = pow(max(dot(H, N), 0.0), shininess); - - // Calculate mask - float mask1 = lightEnabled; - - // Calculate colors - ambient_color += mask1 * ambient_color; // * gl_LightSource[i].ambient; - diffuse_color += mask1 * lambertTerm; - specular_color += mask1 * specularTerm * specular_color; - } - - // Calculate final color by componing different components - vec4 final_color; - vec4 color = apply_colormap(val); - final_color = color * (ambient_color + diffuse_color) + specular_color; - final_color.a = color.a; - return final_color; - }`};var GS=new Array(4),WS=new ArrayBuffer(5120),hX=0;for(let A=0;A<5;A++)GS[A]=new Uint32Array(WS,hX,256),hX+=1024;class hK{static createButton(A,Q={}){let E=document.createElement("button");function B(){let U=null;async function Y(O){O.addEventListener("end",H),await A.xr.setSession(O),E.textContent="EXIT VR",U=O}function H(){U.removeEventListener("end",H),E.textContent="ENTER VR",U=null}E.style.display="",E.style.cursor="pointer",E.style.left="calc(50% - 50px)",E.style.width="100px",E.textContent="ENTER VR";let R={...Q,optionalFeatures:["local-floor","bounded-floor","layers",...Q.optionalFeatures||[]]};if(E.onmouseenter=function(){E.style.opacity="1.0"},E.onmouseleave=function(){E.style.opacity="0.5"},E.onclick=function(){if(U===null)navigator.xr.requestSession("immersive-vr",R).then(Y);else if(U.end(),navigator.xr.offerSession!==void 0)navigator.xr.offerSession("immersive-vr",R).then(Y).catch((O)=>{console.warn(O)})},navigator.xr.offerSession!==void 0)navigator.xr.offerSession("immersive-vr",R).then(Y).catch((O)=>{console.warn(O)})}function I(){E.style.display="",E.style.cursor="auto",E.style.left="calc(50% - 75px)",E.style.width="150px",E.onmouseenter=null,E.onmouseleave=null,E.onclick=null}function C(){I(),E.textContent="VR NOT SUPPORTED"}function K(U){I(),console.warn("Exception when trying to call xr.isSessionSupported",U),E.textContent="VR NOT ALLOWED"}function J(U){U.style.position="absolute",U.style.bottom="20px",U.style.padding="12px 6px",U.style.border="1px solid #fff",U.style.borderRadius="4px",U.style.background="rgba(0,0,0,0.1)",U.style.color="#fff",U.style.font="normal 13px sans-serif",U.style.textAlign="center",U.style.opacity="0.5",U.style.outline="none",U.style.zIndex="999"}if("xr"in navigator)return E.id="VRButton",E.style.display="none",J(E),navigator.xr.isSessionSupported("immersive-vr").then(function(U){if(U?B():C(),U&&hK.xrSessionIsGranted)E.click()}).catch(K),E;else{let U=document.createElement("a");if(window.isSecureContext===!1)U.href=document.location.href.replace(/^http:/,"https:"),U.innerHTML="WEBXR NEEDS HTTPS";else U.href="https://immersiveweb.dev/",U.innerHTML="WEBXR NOT AVAILABLE";return U.style.left="calc(50% - 90px)",U.style.width="180px",U.style.textDecoration="none",J(U),U}}static registerSessionGrantedListener(){if(typeof navigator!=="undefined"&&"xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent))return;navigator.xr.addEventListener("sessiongranted",()=>{hK.xrSessionIsGranted=!0})}}}hK.xrSessionIsGranted=!1;hK.registerSessionGrantedListener();var yX={Handedness:Object.freeze({NONE:"none",LEFT:"left",RIGHT:"right"}),ComponentState:Object.freeze({DEFAULT:"default",TOUCHED:"touched",PRESSED:"pressed"}),ComponentProperty:Object.freeze({BUTTON:"button",X_AXIS:"xAxis",Y_AXIS:"yAxis",STATE:"state"}),ComponentType:Object.freeze({TRIGGER:"trigger",SQUEEZE:"squeeze",TOUCHPAD:"touchpad",THUMBSTICK:"thumbstick",BUTTON:"button"}),ButtonTouchThreshold:0.05,AxisTouchThreshold:0.1,VisualResponseProperty:Object.freeze({TRANSFORM:"transform",VISIBILITY:"visibility"})};var zl={xAxis:0,yAxis:0,button:0,state:yX.ComponentState.DEFAULT};var ul=new RA,pl=new y;var LS=` -// 頂点シェーダーに入力される attribute 変数 -//attribute vec4 position; //!< 入力: 位置情報 -//attribute vec2 uv; //!< 入力: テクスチャー座標 -//attribute vec3 normal; //!< 入力: 法線ベクトル -// All provided by three.js ^^ - -// vertex color is not actually the color of the shape, as such -// it is a custom attribute _COLOR in the glTF - -attribute vec4 _color; //!< 入力: 頂点の色 -attribute vec3 tangent; //!< 入力: 異方位 - -// フラグメントシェーダーへの入力 -varying vec4 v_color; //!< 出力: 頂点の色 -varying vec4 v_position; //!< 出力: 位置情報 -varying vec3 v_normal; //!< 出力: 法線ベクトル -varying vec3 v_tangent; //!< 出力: 異方位 -varying vec2 v_texCoord; //!< 出力: テクスチャー座標 - -// ユニフォーム -//uniform mat3 normalMatrix; //!< ユニフォーム: モデルの法線用行列 -//uniform mat4 modelViewMatrix; //!< ユニフォーム: プロジェクション行列 -//uniform mat4 projectionMatrix; //!< ユニフォーム: モデル行列 -// All provided by three.js ^^ - -// skinning_pars_vertex.glsl.js -#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif - -void main() -{ - - // begin_vertex.glsl.js - vec3 transformed = vec3( position ); -// skinbase_vertex.glsl.js -#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); - // skinning_vertex.glsl.js - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif - -//#ifdef FFL_COORDINATE_MODE_NORMAL - // 頂点座標を変換 - v_position = modelViewMatrix * vec4(transformed, 1.0); - gl_Position = projectionMatrix * v_position; - - vec3 objectNormal = normal; - vec3 objectTangent = tangent.xyz; -// skinnormal_vertex.glsl.js -#ifdef USE_SKINNING - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - - objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; - objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; - -#endif - - // 法線も変換 - //v_normal = mat3(inverse(u_mv)) * a_normal; - v_normal = normalize(normalMatrix * objectNormal); -//#elif defined(FFL_COORDINATE_MODE_NONE) -// // 頂点座標を変換 -// gl_Position = vec4(a_position.x, a_position.y * -1.0, a_position.z, a_position.w); -// v_position = a_position; -// -// v_normal = a_normal; -//#endif - - // その他の情報も書き出す - v_texCoord = uv; - // safe normalize - if (tangent != vec3(0.0, 0.0, 0.0)) - { - v_tangent = normalize(normalMatrix * objectTangent); - } - else - { - v_tangent = vec3(0.0, 0.0, 0.0); - } - - v_color = _color; -} -`,qS=` -// -// sample.flg -// Fragment shader -// Copyright (c) 2014 Nintendo Co., Ltd. All rights reserved. -// -// - -#ifdef GL_ES -precision mediump float; -#else -# define lowp -# define mediump -# define highp -#endif - - -// -// 定数定義ファイル -// - -/// シェーダーモード -#define FFL_SHADER_MODE_UR 0 -#define FFL_SHADER_MODE_UB 1 - -/// 変調処理のマクロ -#define FFL_MODULATE_MODE_CONSTANT 0 -#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 -#define FFL_MODULATE_MODE_RGB_LAYERED 2 -#define FFL_MODULATE_MODE_ALPHA 3 -#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 -#define FFL_MODULATE_MODE_ALPHA_OPA 5 - -/// スペキュラのモード -#define FFL_SPECULAR_MODE_BLINN 0 -#define FFL_SPECULAR_MODE_ANISO 1 - -/// ライトのON/OFF -#define FFL_LIGHT_MODE_DISABLE 0 -#define FFL_LIGHT_MODE_ENABLE 1 - -/// フラグメントのディスカードモード -#define FFL_DISCARD_FRAGMENT_DISABLE 0 -#define FFL_DISCARD_FRAGMENT_ENABLE 1 - -/// 座標変換モード -#define FFL_COORDINATE_MODE_NONE 0 -#define FFL_COORDINATE_MODE_NORMAL 1 - -// -// 関数の定義ファイル -// - -/** - * @brief 異方性反射の反射率を計算します。 - * @param[in] light ライトの向き - * @param[in] tangent 接線 - * @param[in] eye 視線の向き - * @param[in] power 鋭さ - */ -mediump float calculateAnisotropicSpecular(mediump vec3 light, mediump vec3 tangent, mediump vec3 eye, mediump float power ) -{ - mediump float dotLT = dot(light, tangent); - mediump float dotVT = dot(eye, tangent); - mediump float dotLN = sqrt(1.0 - dotLT * dotLT); - mediump float dotVR = dotLN*sqrt(1.0 - dotVT * dotVT) - dotLT * dotVT; - - return pow(max(0.0, dotVR), power); -} - -/** - * @brief 異方性反射の反射率を計算します。 - * @param[in] light ライトの向き - * @param[in] normal 法線 - * @param[in] eye 視線の向き - * @param[in] power 鋭さ - */ -mediump float calculateBlinnSpecular(mediump vec3 light, mediump vec3 normal, mediump vec3 eye, mediump float power) -{ - return pow(max(dot(reflect(-light, normal), eye), 0.0), power); -} - -/** - * @brief 異方性反射、ブリン反射をブレンドします。 - * @param[in] blend ブレンド率 - * @param[in] blinn ブリンの値 - * @param[in] aniso 異方性の値 - */ -mediump float calculateSpecularBlend(mediump float blend, mediump float blinn, mediump float aniso) -{ - return mix(aniso, blinn, blend); -} - -/** - * @brief アンビエントを計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - */ -mediump vec3 calculateAmbientColor(mediump vec3 light, mediump vec3 material) -{ - return light * material; -} - -/** - * @brief 拡散を計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - * @param[in] ln ライトと法線の内積 - */ -mediump vec3 calculateDiffuseColor(mediump vec3 light, mediump vec3 material, mediump float ln) -{ - return light * material * ln; -} - -/** - * @brief 鏡面反射を計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - * @param[in] reflection 反射率 - * @param[in] strength 幅 - */ -mediump vec3 calculateSpecularColor(mediump vec3 light, mediump vec3 material, mediump float reflection, mediump float strength) -{ - return light * material * reflection * strength; -} - -/** - * @brief リムを計算します。 - * @param[in] color リム色 - * @param[in] normalZ 法線のZ方向 - * @param[in] width リム幅 - * @param[in] power リムの鋭さ - */ -mediump vec3 calculateRimColor(mediump vec3 color, mediump float normalZ, mediump float width, mediump float power) -{ - return color * pow(width * (1.0 - abs(normalZ)), power); -} - -/** - * @brief ライト方向と法線の内積を求める - * @note 特殊な実装になっています。 - */ -mediump float calculateDot(mediump vec3 light, mediump vec3 normal) -{ - return max(dot(light, normal), 0.1); -} - -// フラグメントシェーダーに入力される varying 変数 -varying mediump vec4 v_color; //!< 出力: 頂点の色 -varying highp vec4 v_position; //!< 出力: 位置情報 -varying highp vec3 v_normal; //!< 出力: 法線ベクトル -// NOTE: ^^ Those two need to be highp to avoid weird black dot issue on Android -varying mediump vec3 v_tangent; //!< 出力: 異方位 -varying mediump vec2 v_texCoord; //!< 出力: テクスチャー座標 - -/// constカラー -uniform mediump vec4 u_const1; ///< constカラー1 -uniform mediump vec4 u_const2; ///< constカラー2 -uniform mediump vec4 u_const3; ///< constカラー3 - -/// ライト設定 -uniform mediump vec3 u_light_ambient; ///< カメラ空間のライト方向 -uniform mediump vec3 u_light_diffuse; ///< 拡散光用ライト -uniform mediump vec3 u_light_dir; -uniform bool u_light_enable; -uniform mediump vec3 u_light_specular; ///< 鏡面反射用ライト強度 - -/// マテリアル設定 -uniform mediump vec3 u_material_ambient; ///< 環境光用マテリアル設定 -uniform mediump vec3 u_material_diffuse; ///< 拡散光用マテリアル設定 -uniform mediump vec3 u_material_specular; ///< 鏡面反射用マテリアル設定 -uniform int u_material_specular_mode; ///< スペキュラの反射モード(CharModelに依存する設定のためub_modulateにしている) -uniform mediump float u_material_specular_power; ///< スペキュラの鋭さ(0.0を指定すると頂点カラーの設定が利用される) - -/// 変調設定 -uniform int u_mode; ///< 描画モード - -/// リム設定 -uniform mediump vec3 u_rim_color; -uniform mediump float u_rim_power; - -// サンプラー -uniform sampler2D s_texture; - - -// ------------------------------------------------------- -// メイン文 -void main() -{ - mediump vec4 color; - - mediump float specularPower = u_material_specular_power; - mediump float rimWidth = v_color.a; - -//#ifdef FFL_MODULATE_MODE_CONSTANT - if(u_mode == FFL_MODULATE_MODE_CONSTANT) - { - color = u_const1; - } -//#elif defined(FFL_MODULATE_MODE_TEXTURE_DIRECT) - else if(u_mode == FFL_MODULATE_MODE_TEXTURE_DIRECT) - { - color = texture2D(s_texture, v_texCoord); - } -//#elif defined(FFL_MODULATE_MODE_RGB_LAYERED) - else if(u_mode == FFL_MODULATE_MODE_RGB_LAYERED) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.r * u_const1.rgb + color.g * u_const2.rgb + color.b * u_const3.rgb, color.a); - } -//#elif defined(FFL_MODULATE_MODE_ALPHA) - else if(u_mode == FFL_MODULATE_MODE_ALPHA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(u_const1.rgb, color.r); - } -//#elif defined(FFL_MODULATE_MODE_LUMINANCE_ALPHA) - else if(u_mode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.g * u_const1.rgb, color.r); - } -//#elif defined(FFL_MODULATE_MODE_ALPHA_OPA) - else if(u_mode == FFL_MODULATE_MODE_ALPHA_OPA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.r * u_const1.rgb, 1.0); - } -//#endif - - // avoids little outline around mask elements - if(u_mode != FFL_MODULATE_MODE_CONSTANT && color.a == 0.0) - { - discard; - } - -//#ifdef FFL_LIGHT_MODE_ENABLE - if(u_light_enable) - { - /// 環境光の計算 - mediump vec3 ambient = calculateAmbientColor(u_light_ambient.xyz, u_material_ambient.xyz); - - /// 法線ベクトルの正規化 - mediump vec3 norm = normalize(v_normal); - - /// 視線ベクトル - mediump vec3 eye = normalize(-v_position.xyz); - - // ライトの向き - mediump float fDot = calculateDot(u_light_dir, norm); - - /// Diffuse計算 - mediump vec3 diffuse = calculateDiffuseColor(u_light_diffuse.xyz, u_material_diffuse.xyz, fDot); - - /// Specular計算 - mediump float specularBlinn = calculateBlinnSpecular(u_light_dir, norm, eye, u_material_specular_power); - - /// Specularの値を確保する変数を宣言 - mediump float reflection; - mediump float strength = v_color.g; - if(u_material_specular_mode == 0) - { - /// Blinnモデルの場合 - strength = 1.0; - reflection = specularBlinn; - } - else - { - /// Aisoモデルの場合 - mediump float specularAniso = calculateAnisotropicSpecular(u_light_dir, v_tangent, eye, u_material_specular_power); - reflection = calculateSpecularBlend(v_color.r, specularBlinn, specularAniso); - } - /// Specularの色を取得 - mediump vec3 specular = calculateSpecularColor(u_light_specular.xyz, u_material_specular.xyz, reflection, strength); - - // リムの色を計算 - mediump vec3 rimColor = calculateRimColor(u_rim_color.rgb, norm.z, rimWidth, u_rim_power); - - // カラーの計算 - color.rgb = (ambient + diffuse) * color.rgb + specular + rimColor; - } -//#endif - - gl_FragColor = color; -} -`;class BB extends bA{static defaultLightAmbient=new a(0.73,0.73,0.73);static defaultLightDiffuse=new a(0.6,0.6,0.6);static defaultLightSpecular=new a(0.7,0.7,0.7);static defaultLightDir=new y(-0.4531539381,0.4226179123,0.7848858833);static defaultRimColor=new a(0.3,0.3,0.3);static defaultRimPower=2;static defaultLightDirection=this.defaultLightDir;static materialParams=[{ambient:new a(0.85,0.75,0.75),diffuse:new a(0.75,0.75,0.75),specular:new a(0.3,0.3,0.3),specularPower:1.2,specularMode:0},{ambient:new a(1,1,1),diffuse:new a(0.7,0.7,0.7),specular:new a(0,0,0),specularPower:40,specularMode:1},{ambient:new a(0.9,0.85,0.85),diffuse:new a(0.75,0.75,0.75),specular:new a(0.22,0.22,0.22),specularPower:1.5,specularMode:0},{ambient:new a(0.85,0.75,0.75),diffuse:new a(0.75,0.75,0.75),specular:new a(0.3,0.3,0.3),specularPower:1.2,specularMode:0},{ambient:new a(1,1,1),diffuse:new a(0.7,0.7,0.7),specular:new a(0.35,0.35,0.35),specularPower:10,specularMode:1},{ambient:new a(0.75,0.75,0.75),diffuse:new a(0.72,0.72,0.72),specular:new a(0.3,0.3,0.3),specularPower:1.5,specularMode:0},{ambient:new a(1,1,1),diffuse:new a(0.7,0.7,0.7),specular:new a(0,0,0),specularPower:40,specularMode:1},{ambient:new a(1,1,1),diffuse:new a(0.7,0.7,0.7),specular:new a(0,0,0),specularPower:40,specularMode:1},{ambient:new a(1,1,1),diffuse:new a(0.7,0.7,0.7),specular:new a(0,0,0),specularPower:40,specularMode:1},{ambient:new a(0.95622,0.95622,0.95622),diffuse:new a(0.49673,0.49673,0.49673),specular:new a(0.24099,0.24099,0.24099),specularPower:3,specularMode:0},{ambient:new a(0.95622,0.95622,0.95622),diffuse:new a(1.08497,1.08497,1.08497),specular:new a(0.2409,0.2409,0.2409),specularPower:3,specularMode:0}];static getBlendOptionsFromModulateType(A){if(A>=0&&A<=5)return{blending:vQ,blendSrcAlpha:EE,blendDstAlpha:PE};else if(A>=6&&A<=8)return{blending:vQ,blendSrc:EE,blendDst:iE,blendDstAlpha:PE};else if(A>=9&&A<=13)return{blending:vQ,blendSrc:N1,blendSrcAlpha:EE,blendDst:LE};else if(A>=14&&A<=17)return{blending:vQ,blendSrc:EE,blendDst:iE,blendSrcAlpha:PE,blendDstAlpha:PE};else return console.error("Unknown modulate type:",A),{}}modulateMode;modulateType;modulateColor;lightEnable;constructor(A={}){let Q=A.modulateMode??0,E=A.modulateType??0,B=A.lightEnable??!0,I=A.lightDirection??BB.defaultLightDir.clone(),C=A.map||null,K=A.customMaterial||null,J={};if(Array.isArray(A.modulateColor)&&A.modulateColor.length===3)J={u_const1:{value:A.modulateColor[0]},u_const2:{value:A.modulateColor[1]},u_const3:{value:A.modulateColor[2]}};else J={u_const1:{value:A.modulateColor||new MA(1,1,1,1)}};let U=BB.materialParams[E]||BB.materialParams[0];if(K)U=K;let Y=Object.assign({},J,{u_light_ambient:{value:A.lightAmbient||BB.defaultLightAmbient},u_light_diffuse:{value:A.lightDiffuse||BB.defaultLightDiffuse},u_light_specular:{value:A.lightSpecular||BB.defaultLightSpecular},u_light_dir:{value:I},u_light_enable:{value:B},u_material_ambient:{value:U.ambient},u_material_diffuse:{value:U.diffuse},u_material_specular:{value:U.specular},u_material_specular_mode:{value:U.specularMode},u_material_specular_power:{value:U.specularPower},u_mode:{value:Q},u_rim_color:{value:BB.defaultRimColor},u_rim_power:{value:BB.defaultRimPower},s_texture:{value:C}});super({vertexShader:A.vertexShader||LS,fragmentShader:A.fragmentShader||qS,uniforms:Y,side:A.side||jQ,...Q!==0?BB.getBlendOptionsFromModulateType(E):{}});this.modulateMode=Q,this.modulateType=E,this.modulateColor=A.modulateColor,this.lightEnable=B}get map(){return this.uniforms.s_texture.value}set map(A){this.uniforms.s_texture.value=A}get lightDirection(){return this.uniforms.u_light_dir.value}set lightDirection(A){this.uniforms.u_light_dir.value=A}}var FS=` -#define AGX_FEATURE_ALBEDO_TEXTURE -/** - * @file LUT.vsh - * @brief LUT - * @since 2014/10/02 - * - * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. - */ - -// シェーダーの種類毎に設定されるマクロリスト -// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 -// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 -// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 -// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 -// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 -// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 -// AGX_FEATURE_SKIN_MASK 肌マスクが有効(u_const1) -// AGX_FEATURE_HAIR_MASK 髪マスクが有効(u_const2) -// AGX_FEATURE_ALPHA_TEST アルファテストが有効 -// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(u_const3) -// AGX_FEATURE_DISABLE_LIGHT ライトが無効 -// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 -// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 -// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 -// AGX_FEATURE_MII Miiを描画する -// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant -// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct -// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered -// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha -// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha -// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa -// -// AGX_BONE_MAX ボーンの最大数 - -#ifdef GL_ES -precision highp float; -#else -# define lowp -# define mediump -# define highp -#endif - -//#ifndef AGX_BONE_MAX -//# define AGX_BONE_MAX 15 -//#endif -#ifndef AGX_DIR_LIGHT_MAX -# define AGX_DIR_LIGHT_MAX 2 -#endif - -// ---------------------------------------- -// 頂点シェーダーに入力される attribute 変数 -//attribute highp vec3 position; //!< 入力:[ 1 : 1 ] 位置情報 -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) -//attribute mediump vec2 uv; //!< 入力:[ 1 : 5 ] テクスチャー座標 -#endif -//attribute mediump vec3 normal; //!< 入力:[ 1 : 2 ] 法線ベクトル -//attribute mediump vec4 aBoneIndex; //!< 入力:[ 1 : 3 ] ボーンのインデックス(最大4つ) -//attribute mediump vec4 aBoneWeight; //!< 入力:[ 1 : 4 ] ボーンの影響度(最大4つ) -#if defined(AGX_FEATURE_VERTEX_COLOR) -//attribute lowp vec4 _color; //!< 入力:[ 1 : 6 ] 頂点カラー -#endif -#if defined(AGX_FEATURE_BUMP_TEXTURE) -//attribute mediump vec3 tangent; //!< 入力:[ 1 : 7 ] 接線ベクトル -#endif - -// ^^ Commented attributes are provided by three.js. - -// ---------------------------------------- -// 頂点シェーダーに入力される uniform 変数 -//uniform highp mat4 modelViewMatrix; //!< 入力:[ 4 / 4 : 4 ] モデルの合成行列 -//uniform mat4 projectionMatrix; -//uniform highp mat4 viewMatrix; //!< 入力:[ 4 / 4 : 8 ] モデルのビュー行列 -//uniform mediump mat3 normalMatrix; //!< 入力:[ 3 / 3 : 11 ] モデルの法線用行列 -//uniform highp mat4 modelMatrix; //!< 入力:[ 4 / 4 : 15 ] モデルのワールド変換行列 -//uniform lowp int uBoneCount; //!< 入力:[ 1 / 1 : 16 ] ボーンの個数 -//uniform highp mat4 uBoneMatrices[AGX_BONE_MAX]; //!< 入力:[ 4 x 15 / 60 : 76 ] ボーンの行列配列 -//uniform mediump mat3 uBoneNormalMatrices[AGX_BONE_MAX]; //!< 入力:[ 3 x 15 / 45 : 121 ] ボーンの法線行列配列 -// ^^ Unused in favor of three.js skinning. -uniform lowp int uDirLightCount; //!< 入力:[ 1 / 1 : 122 ] 方向ライトの数 -uniform mediump vec4 uDirLightDirAndType0;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 -uniform mediump vec4 uDirLightDirAndType1;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 -uniform mediump vec3 uDirLightColor0; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー -uniform mediump vec3 uDirLightColor1; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー -uniform mediump vec3 uHSLightSkyColor; //!< 入力:[ 1 / 1 : 127 ] 半球ライトのスカイカラー -uniform mediump vec3 uHSLightGroundColor; //!< 入力:[ 1 / 1 : 128 ] 半球ライトのグラウンドカラー -//uniform mediump vec3 cameraPosition; //!< 入力:[ 1 / 1 : 129 ] カメラの位置 -// ^^ previously uEyePt -uniform mediump float uAlpha; //!< 入力:[ 1 / 1 : 130 ] アルファ値 - -// ^^ Commented uniforms are provided by three.js. - -// ---------------------------------------- -// フラグメントシェーダーに渡される varying 変数 -varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 -#if !defined(AGX_FEATURE_BUMP_TEXTURE) -varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 -#endif -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) -varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV -#endif -// camera -varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル -#if !defined(AGX_FEATURE_DISABLE_LIGHT) -// punctual light -varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 -varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル -// GI -varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー -// Lighting Result -varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 -#endif -// Reflect -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) -varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル -#endif - -// skinning_pars_vertex.glsl.js -#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif - -// ------------------------------------------------------------ -// 頂点シェーダーのエントリーポイント -// ------------------------------------------------------------ -void main() -{ - // ------------------------------------------------------------ - // 頂点変換用の処理 - // ------------------------------------------------------------ - highp vec4 position_; //!< 最終的な頂点 - mediump vec3 normal_; //!< 最終的な法線 - mediump vec3 tangent_; //!< 最終的な接線 - highp vec4 positionWorld; //!< ワールド空間上での頂点 - - - // begin_vertex.glsl.js - vec3 transformed = vec3( position ); -// skinbase_vertex.glsl.js -#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); - // skinning_vertex.glsl.js - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif - - // ---------------------------------------- - // ボーンが存在しない場合は位置と法線に手を加えない - position_ = vec4(transformed.xyz, 1.0); - - - - normal_ = normal; -#if defined(AGX_FEATURE_BUMP_TEXTURE) - tangent_ = tangent.xyz; -#endif - // skinnormal_vertex.glsl.js -#ifdef USE_SKINNING - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - - normal_ = vec4( skinMatrix * vec4( normal_, 0.0 ) ).xyz; -#if defined(AGX_FEATURE_BUMP_TEXTURE) - tangent_ = vec4( skinMatrix * vec4( tangent_, 0.0 ) ).xyz; -#endif // defined(AGX_FEATURE_BUMP_TEXTURE) -#endif // USE_SKINNING - - // ---------------------------------------- - // ワールド上での位置を求める - positionWorld = modelMatrix * position_; - // 最終結果を行う - position_ = projectionMatrix * modelViewMatrix * position_; - normal_ = normalize(normalMatrix * normal_); -#if defined(AGX_FEATURE_BUMP_TEXTURE) - tangent = normalize(normalMatrix * tangent_); -#endif - - // ---------------------------------------- - // 計算結果を保持させる - gl_Position = position_; -#if !defined(AGX_FEATURE_BUMP_TEXTURE) - vNormal = normal_; -#endif -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) - // テクスチャー座標を設定する - vTexcoord0 = uv; -#endif - // モデルの色を指定する -#if defined(AGX_FEATURE_VERTEX_COLOR) - lowp vec4 modelColor = aColor; - -#else - lowp vec4 modelColor = vec4(1.0, 1.0, 1.0, 1.0); -#endif - - // プリマルチプライドアルファ -#if defined(AGX_FEATURE_PREMULTIPLY_ALPHA) - modelColor *= uAlpha; -#else - modelColor.a *= uAlpha; -#endif - - - // ------------------------------------------------------------ - // ライト用の処理 - // ------------------------------------------------------------ - mediump vec3 eyeVecWorld; //!< ワールド状態での視線ベクトル - mediump vec3 eyeVec; //!< 最終的にフラグメントシェーダーに渡す視線ベクトル(バンプの有無によって、ワールド座標系になったり、タンジェント座標系になったりする) - - vec4 eye = modelViewMatrix * position_; - - // 視線ベクトルを取得する - //eyeVecWorld = normalize(cameraPosition - positionWorld.xyz); - eyeVecWorld = normalize(-(eye.xyz) - positionWorld.xyz);//normalize(cameraPosition - positionWorld.xyz); - eyeVec = eyeVecWorld; - - lowp vec3 diffuseColor = vec3(0.0); // バーテックスシェーダーで計算できるディフューズの色をここに格納する - -# if defined(AGX_FEATURE_BUMP_TEXTURE) - // Normal, Binormal, Tangent を取得する - mediump vec3 n = normal; - mediump vec3 t = tangent; - mediump vec3 b = cross(n, t); - // 接空間からローカルへ変換する行列を設定する(mat3(N, T, B)の逆行列) - mediump mat3 tangentMatrix = mat3(t.x, b.x, n.x, t.y, b.y, n.y, t.z, b.z, n.z); - // 視線ベクトルを接空間へ - vEyeVecWorldOrTangent.xyz = tangentMatrix * eyeVec; -#else - vEyeVecWorldOrTangent.xyz = eyeVec; -#endif - -#if !defined(AGX_FEATURE_DISABLE_LIGHT) - // punctual lightの設定 - if (uDirLightCount > 0) - { - mediump vec3 lightDir; - - // 方向ライト - if (uDirLightDirAndType0.w < 0.0) { lightDir = uDirLightDirAndType0.xyz; } - // 点光源ライト - else { lightDir = uDirLightDirAndType0.xyz - positionWorld.xyz; } - lightDir = normalize(lightDir); - -# if defined(AGX_FEATURE_BUMP_TEXTURE) - // ライトを接空間へ - vPunctualLightDirWorldOrTangent.xyz = tangentMatrix * lightDir; -# else - vPunctualLightDirWorldOrTangent.xyz = lightDir; -# endif - - // Halfベクトルを求める - vPunctualLightHalfVecWorldOrTangent.xyz = normalize(vPunctualLightDirWorldOrTangent.xyz + vEyeVecWorldOrTangent.xyz); - - // Diffuse計算 - diffuseColor += (uDirLightColor0.rgb * clamp(dot(lightDir, normal), 0.0, 1.0)); - } - if (uDirLightCount > 1) - { - mediump vec3 lightDir; - - // 方向ライト - if (uDirLightDirAndType1.w < 0.0) { lightDir = uDirLightDirAndType1.xyz; } - // 点光源ライト - else { lightDir = uDirLightDirAndType1.xyz - positionWorld.xyz; } - lightDir = normalize(lightDir); - - diffuseColor += max(dot(lightDir, normal), 0.0) * uDirLightColor1; - } - // ライトは1.0を超えないように - diffuseColor = min(diffuseColor, 1.0); -#endif - -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) - { - // キューブ環境マップ用の反射ベクトルを求める -// vReflectDir = reflect(normalize(positionWorld.xyz - cameraPosition), normal); - - // スフィア環境マップ用の反射ベクトルを求める -// vReflectDir = normalize((uViewMatrix * vec4(normal, 0.0)).xyz) * 0.5 + 0.5; - - // ビュー座標系での位置と法線を取得 - mediump vec3 viewNormal = normalize(mat3(uViewMatrix) * normal); - mediump vec4 viewPosition = uViewMatrix * positionWorld; - viewPosition = viewPosition / viewPosition.w; - // ビュー座標系での頂点ベクトルを取得 - viewPosition.z = 1.0 - viewPosition.z; - mediump vec3 viewPositionVec = normalize(viewPosition.xyz); - // ビュー座標系での反射ベクトルを求める - mediump vec3 viewReflect = viewPositionVec - 2.0 * dot(viewPositionVec, viewNormal) * viewNormal; - // 両面スフィア環境マップではないので、反射ベクトルを調整 - viewReflect = normalize(viewReflect - vec3(0.0, 0.0, 1.5)); - // 反射ベクトルをテクスチャー座標系へ - vReflectDir = viewReflect * 0.5 + 0.5; - - // 公式 -// mediump vec3 viewPositionVec = normalize(vec3(uViewMatrix * positionWorld)); -// mediump vec3 viewReflectVec = viewPositionVec - 2.0 * dot(viewPositionVec, normal) * normal; -// mediump float m = 2.0 * sqrt(viewReflectVec.x * viewReflectVec.x + -// viewReflectVec.y * viewReflectVec.y + -// (viewReflectVec.z + 1.0) * (viewReflectVec.z * 1.0)); -// vReflectDir = viewReflectVec / m + 0.5; - - // 別版 -// mediump vec3 posW = positionWorld.xyz; -// mediump vec3 dir = normalize(mat3(uViewMatrix) * normal); -// -// mediump float radius = 75.0; -// mediump vec3 posWDir = dot(dir, posW) * dir; -// mediump vec3 posWDirV = posW - posWDir; -// mediump float lengthDir = sqrt(radius * radius - dot(posWDirV, posWDirV)) - length(posWDir); -// vReflectDir = normalize(posW + dir * lengthDir) * 0.5 + 0.5; - } -#endif - -#if !defined(AGX_FEATURE_DISABLE_LIGHT) - // GIの計算 - { - mediump vec3 hemiColor; - mediump vec3 sky = uHSLightSkyColor; - mediump vec3 ground = uHSLightGroundColor; - - { - mediump float skyRatio = (normal.y + 1.0) * 0.5; - hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); - diffuseColor += hemiColor; - } - - { -// mediump vec3 reflectDir = -reflect(normal, eyeVecWorld); // おそらくコレで良いはず - mediump vec3 reflectDir = 2.0 * dot(eyeVecWorld, normal) * normal - eyeVecWorld; // 多少冗長でも、正しい計算で行なう - - mediump float skyRatio = (reflectDir.y + 1.0) * 0.5; - hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); - vGISpecularLightColor.rgb = hemiColor; - } - } -#endif - - // モデルの色を設定 - vModelColor = modelColor; -#if !defined(AGX_FEATURE_DISABLE_LIGHT) - vDiffuseColor.rgb = diffuseColor; -#endif -} -`,DS=` -#define AGX_FEATURE_ALBEDO_TEXTURE -#define AGX_FEATURE_MII -/** - * @file LUT.fsh - * @brief LUT - * @since 2014/10/02 - * - * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. - */ - -// シェーダーの種類毎に設定されるマクロリスト -// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 -// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 -// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 -// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 -// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 -// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 -// AGX_FEATURE_SKIN_MASK 肌マスクが有効(u_const1) -// AGX_FEATURE_HAIR_MASK 髪マスクが有効(u_const2) -// AGX_FEATURE_ALPHA_TEST アルファテストが有効 -// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(u_const3) -// AGX_FEATURE_DISABLE_LIGHT ライトが無効 -// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 -// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 -// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 -// AGX_FEATURE_MII Miiを描画する -// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant -// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct -// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered -// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha -// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha -// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa - -#ifdef GL_ES -precision mediump float; -#else -# define lowp -# define mediump -# define highp -#endif - -/// 変調処理のマクロ -#define FFL_MODULATE_MODE_CONSTANT 0 -#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 -#define FFL_MODULATE_MODE_RGB_LAYERED 2 -#define FFL_MODULATE_MODE_ALPHA 3 -#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 -#define FFL_MODULATE_MODE_ALPHA_OPA 5 - -// ---------------------------------------- -// フラグメントシェーダーに入力される uniform 変数 -uniform int uMode; ///< 描画モード -uniform bool uAlphaTest; -uniform bool uLightEnable; -uniform mediump vec4 u_const1; //!< 入力:[ 1 : 1 ] カラー0 (OR 肌カラー) -uniform mediump vec4 u_const2; //!< 入力:[ 1 : 2 ] カラー1 (OR 髪カラー) -uniform mediump vec4 u_const3; //!< 入力:[ 1 : 3 ] カラー2 (OR フェードアウトカラー) -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -uniform mediump vec3 uLightColor; //!< 入力:[ 1 : 4 ] ライトの色 -//#endif - -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) -uniform sampler2D uAlbedoTexture; //!< 入力: テクスチャー -#endif -#if defined(AGX_FEATURE_BUMP_TEXTURE) -uniform sampler2D uNormalTexture; //!< 入力: ノーマルマップ -#endif -#if defined(AGX_FEATURE_MASK_TEXTURE) -uniform sampler2D uMaskTexture; //!< 入力:マスクテクスチャー -#endif -#if defined(AGX_FEATURE_ALPHA_TEXTURE) -uniform sampler2D uAlphaTexture; //!< 入力:アルファテクスチャー -#endif -uniform sampler2D uLUTSpecTexture; //!< 入力: スペキュラーLUT -uniform sampler2D uLUTFresTexture; //!< 入力: フレネルLUT -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) -uniform sampler2D uSphereMapTexture; //!< 入力: スフィア環境マップ -#endif - -// ---------------------------------------- -// フラグメントシェーダーに渡される varying 変数 -varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 -#if !defined(AGX_FEATURE_BUMP_TEXTURE) -varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 -#endif -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) -varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV -#endif -// camera -varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -// punctual light -varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 -varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル -// GI -varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー -// Lighting Result -varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 -//#endif -// Reflect -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) -varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル -#endif - -// ------------------------------------------------------------ -// フラグメントシェーダーのエントリーポイント -// ------------------------------------------------------------ -void main() -{ - - // ディフューズカラーを取得 - lowp vec4 albedoColor = vec4(1.0, 1.0, 1.0, 1.0); - - // ============================================================ - // Mii - // ============================================================ -#if defined(AGX_FEATURE_MII) - - //#if defined(AGX_FEATURE_MII_CONSTANT) - if(uMode == FFL_MODULATE_MODE_CONSTANT) - { - albedoColor = vec4(u_const1.rgb, 1.0); - } - //#elif defined(AGX_FEATURE_MII_TEXTURE_DIRECT) - else if(uMode == FFL_MODULATE_MODE_TEXTURE_DIRECT) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - } - //#elif defined(AGX_FEATURE_MII_RGB_LAYERED) - else if(uMode == FFL_MODULATE_MODE_RGB_LAYERED) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(albedoColor.r * u_const1.rgb + albedoColor.g * u_const2.rgb + albedoColor.b * u_const3.rgb, - albedoColor.a); - } - //#elif defined(AGX_FEATURE_MII_ALPHA) - else if(uMode == FFL_MODULATE_MODE_ALPHA) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(u_const1.rgb, albedoColor.r); - } - //#elif defined(AGX_FEATURE_MII_LUMINANCE_ALPHA) - else if(uMode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(albedoColor.g * u_const1.rgb, albedoColor.r); - } - //#elif defined(AGX_FEATURE_MII_ALPHA_OPA) - else if(uMode == FFL_MODULATE_MODE_ALPHA_OPA) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(albedoColor.r * u_const1.rgb, 1.0); - } -//#endif - - albedoColor = albedoColor * vModelColor; -#endif - - // ============================================================ - // Albedo Texture - // ============================================================ -#if !defined(AGX_FEATURE_MII) && defined(AGX_FEATURE_ALBEDO_TEXTURE) - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); -#endif -#if defined(AGX_FEATURE_ALPHA_TEXTURE) - albedoColor.a = texture2D(uAlphaTexture, vTexcoord0).r; -#endif - - // ============================================================ - // Color Mask - // ============================================================ - // ---------------------------------------- - // Deprecated -#if defined(AGX_FEATURE_ALPHA_COLOR_FILTER) - // 一部の場所にColor0を反映する - albedoColor.rgb = (albedoColor.rgb * albedoColor.a + u_const1.rgb * (1.0 - albedoColor.a)); - albedoColor.a = 1.0; -#elif defined(AGX_FEATURE_MASK_TEXTURE) - lowp vec3 maskTextureColor = texture2D(uMaskTexture, vTexcoord0).rgb; - -# if defined(AGX_FEATURE_SKIN_MASK) && defined(AGX_FEATURE_HAIR_MASK) - // 肌と髪両方マスクが存在する - lowp float maskColorValue = maskTextureColor.g + maskTextureColor.b; - lowp vec3 maskColor = maskTextureColor.g * u_const1.rgb + maskTextureColor.b * u_const2.rgb; - albedoColor.rgb = (albedoColor.rgb * (1.0 - maskColorValue) + maskColor); - -# elif defined(AGX_FEATURE_SKIN_MASK) - // 肌しかマスクが存在しない - albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.g) + maskTextureColor.g * u_const1.rgb); - -# elif defined(AGX_FEATURE_HAIR_MASK) - // 髪しかマスクが存在しない - albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.b) + maskTextureColor.b * u_const2.rgb); - -# endif -#endif - - // アルベドに頂点カラーを掛ける - albedoColor *= vModelColor; - - // ============================================================ - // Alpha test - // ============================================================ -//#if defined(AGX_FEATURE_ALPHA_TEST) - if (uAlphaTest && albedoColor.a < 0.5) { discard; } -//#endif - - // ============================================================ - // Bumpmap - // ============================================================ - // 頂点からの情報 - lowp vec3 normalWorldOrTangent; -#if defined(AGX_FEATURE_BUMP_TEXTURE) - // バンプマップから法線を取得する - mediump vec3 bumpNormal = texture2D(uNormalTexture, vTexcoord0).rgb; - - // 法線の正規化は処理が重いのでいったん正規化しない様に... -// normalWorldOrTangent = normalize(bumpNormal * 2.0 - 1.0); - normalWorldOrTangent = bumpNormal * 2.0 - 1.0; - -#else - // 法線を正規化して取得する - normalWorldOrTangent = normalize(vNormal); -#endif - - // ============================================================ - // Lighting - // ============================================================ - // 最終的なカラー情報 - lowp vec4 colorOut = vec4(0.0, 0.0, 0.0, albedoColor.a); // 最終的に出力される色 - lowp vec3 fresnel = vec3(0.0, 0.0, 0.0); // フレネル - lowp vec3 specular = vec3(0.0, 0.0, 0.0); // スペキュラー - -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -if (uLightEnable) { - - // BRDFの計算を行う(バンプマッピングの場合は接空間) - lowp vec3 N = normalWorldOrTangent; - lowp vec3 V = vEyeVecWorldOrTangent.xyz;//normalize(vEyeVecWorldOrTangent.xyz); - lowp vec3 I = vPunctualLightDirWorldOrTangent.xyz;//normalize(vPunctualLightDirWorldOrTangent.xyz); - lowp vec3 H = vPunctualLightHalfVecWorldOrTangent.xyz;//normalize(vPunctualLightHalfVecWorldOrTangent.xyz); - - - // ---------------------------------------- - // punctual light - // 平行光源や点光源などの厳密なライティング計算を行なうもの - { - lowp float fSpecular = dot(N, H); - - lowp float specularIntensity = texture2D(uLUTSpecTexture, vec2(fSpecular)).r; - specular = (specularIntensity * uLightColor.rgb); - } - - // ---------------------------------------- - // GI - // 半球ライトやIBL、SHのように法線方向に半球積分された結果でライティング計算を行なうもの - { - lowp float fFresnel = dot(N, V); - lowp float fresnelIntensity = texture2D(uLUTFresTexture, vec2(fFresnel)).r; - - fresnel = (fresnelIntensity * vGISpecularLightColor.rgb); - } -} -//#endif - -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) - // スフィア環境マップ - specular += texture2D(uSphereMapTexture, vReflectDir.xy).rgb; -#endif - - // ============================================================ - // Specular Mask - // ============================================================ -#if !defined(AGX_FEATURE_ALPHA_COLOR_FILTER) && defined(AGX_FEATURE_MASK_TEXTURE) - // スペキュラーマスク - specular = specular * maskTextureColor.r + fresnel; -#else - specular += fresnel; -#endif - - // ============================================================ - // Output - // ============================================================ -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -if (uLightEnable) - colorOut.rgb = vDiffuseColor.rgb * albedoColor.rgb + specular; -//#else -else - colorOut.rgb = albedoColor.rgb; -//#endif - - // フェードアウトを実装する -#if defined(AGX_FEATURE_FADE_OUT_COLOR) - colorOut.rgb = (colorOut.rgb * (1.0 - u_const3.a)) + (u_const3.rgb * u_const3.a); -#endif - - // 色を反映させる - gl_FragColor = colorOut; - - //#include - //#include -} -`;class A8{keys;constructor(A){this.keys=A.sort((Q,E)=>Q.x-E.x)}interpolate(A,Q,E,B,I){let C=2*A*A*A-3*A*A+1,K=A*A*A-2*A*A+A,J=-2*A*A*A+3*A*A,U=A*A*A-A*A;return C*Q+K*B+J*E+U*I}clamp(A,Q,E){return Math.min(Math.max(A,Q),E)}generateLUT(A=512){let Q=new Uint8Array(A),E=0;for(let B=0;Bthis.keys[E+1].x)E++;let C=this.keys[E],K=this.keys[E+1],J=(I-C.x)/(K.x-C.x);J=isNaN(J)?0:J;let U=this.interpolate(J,C.y,K.y,C.dx*(K.x-C.x),K.dx*(K.x-C.x));Q[B]=Math.round(this.clamp(U,0,1)*255)}return Q}}class K0 extends bA{static LUTSpecularTextureType={NONE:0,DEFAULT_02:1,SKIN_01:2,MAX:3};static LUTFresnelTextureType={NONE:0,DEFAULT_02:1,SKIN_01:2,MAX:3};static lutDefinitions={specular:{[K0.LUTSpecularTextureType.NONE]:new A8([{x:0,y:0,dx:0,dy:0},{x:1,y:0,dx:0,dy:0}]),[K0.LUTSpecularTextureType.DEFAULT_02]:new A8([{x:0,y:0,dx:0,dy:0},{x:0.05,y:0,dx:0,dy:0},{x:0.8,y:0.038,dx:0.157894736842105,dy:0.157894736842105},{x:1,y:0.11,dx:0,dy:0}]),[K0.LUTSpecularTextureType.SKIN_01]:new A8([{x:0,y:0.03,dx:-0.105263157894737,dy:-0.105263157894737},{x:1,y:0,dx:0,dy:0}])},fresnel:{[K0.LUTFresnelTextureType.NONE]:new A8([{x:0,y:0,dx:0,dy:0},{x:1,y:0,dx:0,dy:0}]),[K0.LUTFresnelTextureType.DEFAULT_02]:new A8([{x:0,y:0.3,dx:-0.105263157894734,dy:-0.105263157894734},{x:0.175,y:0.23,dx:-0.626315789473681,dy:-0.626315789473681},{x:0.6,y:0.05,dx:-0.210526315789474,dy:-0.210526315789474},{x:1,y:0,dx:-0.105263157894737,dy:-0.105263157894737}]),[K0.LUTFresnelTextureType.SKIN_01]:new A8([{x:0.005,y:0.35,dx:-0.105263157894734,dy:-0.105263157894734},{x:0.173,y:0.319,dx:-0.205263157894734,dy:-0.205263157894734},{x:0.552,y:0.051,dx:-0.210526315789474,dy:-0.210526315789474},{x:1,y:0.001,dx:0,dy:0}])}};static modulateToLUTSpecular=[K0.LUTSpecularTextureType.SKIN_01,K0.LUTSpecularTextureType.DEFAULT_02,K0.LUTSpecularTextureType.SKIN_01,K0.LUTSpecularTextureType.SKIN_01,K0.LUTSpecularTextureType.DEFAULT_02,K0.LUTSpecularTextureType.DEFAULT_02,K0.LUTSpecularTextureType.DEFAULT_02,K0.LUTSpecularTextureType.NONE,K0.LUTSpecularTextureType.NONE,K0.LUTSpecularTextureType.DEFAULT_02,K0.LUTSpecularTextureType.DEFAULT_02];static modulateToLUTFresnel=[K0.LUTFresnelTextureType.SKIN_01,K0.LUTFresnelTextureType.DEFAULT_02,K0.LUTFresnelTextureType.SKIN_01,K0.LUTFresnelTextureType.SKIN_01,K0.LUTFresnelTextureType.DEFAULT_02,K0.LUTFresnelTextureType.DEFAULT_02,K0.LUTFresnelTextureType.DEFAULT_02,K0.LUTFresnelTextureType.NONE,K0.LUTFresnelTextureType.NONE,K0.LUTFresnelTextureType.DEFAULT_02,K0.LUTFresnelTextureType.DEFAULT_02];static _lutTextures=null;static getLUTTextures(A=512){if(!K0._lutTextures){let Q={specular:{},fresnel:{}},E=Number(ZB)<137?L1:SQ;for(let[B,I]of Object.entries(K0.lutDefinitions.specular)){let C=I.generateLUT(A),K=new h0(C,A,1,E,x0);K.needsUpdate=!0,Q.specular[B]=K}for(let[B,I]of Object.entries(K0.lutDefinitions.fresnel)){let C=I.generateLUT(A),K=new h0(C,A,1,E,x0);K.needsUpdate=!0,Q.fresnel[B]=K}K0._lutTextures=Q}return K0._lutTextures}static defaultHSLightGroundColor=new a(0.87843,0.72157,0.5898);static defaultHSLightSkyColor=new a(0.87843,0.83451,0.80314);static defaultDirLightColor0=new a(0.35137,0.32392,0.32392);static defaultDirLightColor1=new a(0.10039,0.09255,0.09255);static defaultDirLightCount=2;static defaultDirLightDirAndType0=new MA(-0.2,0.5,0.8,-1);static defaultDirLightDirAndType1=new MA(0,-0.19612,0.98058,-1);static defaultLightColor=new a(0.35137,0.32392,0.32392);static defaultLightDirection=this.defaultDirLightDirAndType0;static getBlendOptionsFromModulateType(A){if(A>=0&&A<=5)return{blending:vQ,blendSrcAlpha:EE,blendDstAlpha:PE};else if(A>=6&&A<=8)return{blending:vQ,blendSrc:EE,blendDst:iE,blendDstAlpha:PE};else if(A>=9&&A<=13)return{blending:vQ,blendSrc:N1,blendSrcAlpha:EE,blendDst:LE};else if(A>=14&&A<=17)return{blending:vQ,blendSrc:EE,blendDst:iE,blendSrcAlpha:PE,blendDstAlpha:PE};else return console.error(`Unknown modulate type: ${A}.`),{}}modulateMode;modulateType;modulateColor;lightEnable;_side;constructor(A={}){let Q=A.modulateMode??0,E=A.modulateType??0,B=A.lightEnable??!0,I=A.map||null,C=E>=6&&E<=8?!0:A.alphaTest,K=E===6?y0:A.side||jQ,J={};if(Array.isArray(A.modulateColor)&&A.modulateColor.length===3)J={u_const1:{value:A.modulateColor[0]},u_const2:{value:A.modulateColor[1]},u_const3:{value:A.modulateColor[2]}};else J={u_const1:{value:A.modulateColor||new MA(1,1,1,1)}};let U=K0.getLUTTextures(),Y=K0.modulateToLUTSpecular[E]??K0.LUTSpecularTextureType.NONE,H=K0.modulateToLUTFresnel[E]??K0.LUTFresnelTextureType.NONE,R=U.specular[Y],O=U.fresnel[H],N=Object.assign({},J,{uBoneCount:{value:0},uAlpha:{value:1},uHSLightGroundColor:{value:A.hslightGroundColor||K0.defaultHSLightGroundColor},uHSLightSkyColor:{value:A.hslightSkyColor||K0.defaultHSLightSkyColor},uDirLightColor0:{value:A.dirLightColor0||K0.defaultDirLightColor0},uDirLightColor1:{value:A.dirLightColor1||K0.defaultDirLightColor1},uDirLightCount:{value:A.dirLightCount||K0.defaultDirLightCount},uDirLightDirAndType0:{value:A.dirLightDirAndType0||K0.defaultDirLightDirAndType0.clone()},uDirLightDirAndType1:{value:A.dirLightDirAndType1||K0.defaultDirLightDirAndType1.clone()},uLightEnable:{value:B},uLightColor:{value:A.lightColor||K0.defaultLightColor},uMode:{value:Q},uAlphaTest:{value:C},uAlbedoTexture:{value:I},uLUTSpecTexture:{value:R},uLUTFresTexture:{value:O}});super({vertexShader:A.vertexShader||FS,fragmentShader:A.fragmentShader||DS,uniforms:N,side:K,...Q!==0?K0.getBlendOptionsFromModulateType(E):{}});this.modulateMode=Q,this.modulateType=E,this.modulateColor=A.modulateColor,this.lightEnable=B,this._side=A.side}get map(){return this.uniforms.uAlbedoTexture.value}set map(A){this.uniforms.uAlbedoTexture.value=A}get lightDirection(){return this.uniforms.uDirLightDirAndType0.value}set lightDirection(A){this.uniforms.uDirLightDirAndType0.value=A,this.uniforms.uDirLightDirAndType0.value.w=-1}}var bo={specularMode:0},fo={ambient:new MA(0.8,0.8,0.8,1),diffuse:new MA(0.8,0.8,0.8,1),specular:new MA(0.1,0.1,0.1,1),specularPower:0.01,specularMode:0},uo=[{ambient:new MA(0.85,0.75,0.75,1),diffuse:new MA(0.75,0.75,0.75,1),specular:new MA(0.3,0.3,0.3,1),specularPower:1.2,specularMode:0},{ambient:new MA(1,1,1,1),diffuse:new MA(0.7,0.7,0.7,1),specular:new MA(0,0,0,1),specularPower:40,specularMode:1},{ambient:new MA(0.9,0.85,0.85,1),diffuse:new MA(0.75,0.75,0.75,1),specular:new MA(0.22,0.22,0.22,1),specularPower:1.5,specularMode:0},{ambient:new MA(0.85,0.75,0.75,1),diffuse:new MA(0.75,0.75,0.75,1),specular:new MA(0.3,0.3,0.3,1),specularPower:1.2,specularMode:0},{ambient:new MA(1,1,1,1),diffuse:new MA(0.7,0.7,0.7,1),specular:new MA(0.35,0.35,0.35,1),specularPower:10,specularMode:1},{ambient:new MA(0.75,0.75,0.75,1),diffuse:new MA(0.72,0.72,0.72,1),specular:new MA(0.3,0.3,0.3,1),specularPower:1.5,specularMode:0},{ambient:new MA(1,1,1,1),diffuse:new MA(0.7,0.7,0.7,1),specular:new MA(0,0,0,1),specularPower:40,specularMode:1},{ambient:new MA(1,1,1,1),diffuse:new MA(0.7,0.7,0.7,1),specular:new MA(0,0,0,1),specularPower:40,specularMode:1},{ambient:new MA(1,1,1,1),diffuse:new MA(0.7,0.7,0.7,1),specular:new MA(0,0,0,1),specularPower:40,specularMode:1},{ambient:new MA(0.95622,0.95622,0.95622,1),diffuse:new MA(0.49673,0.49673,0.49673,1),specular:new MA(0.24099,0.24099,0.24099,1),specularPower:3,specularMode:0},{ambient:new MA(0.95622,0.95622,0.95622,1),diffuse:new MA(1.08497,1.08497,1.08497,1),specular:new MA(0.2409,0.2409,0.2409,1),specularPower:3,specularMode:0}],po=new MA(0.73,0.73,0.73,1),mo=new MA(0.6,0.6,0.6,1),co=new MA(0.7,0.7,0.7,1),lo=new MA(0.5,0.5,0.5,1),no=new MA(0.9,0.9,0.9,1),so=new MA(1,1,1,1),io=new y(-0.4531539381,0.4226179123,0.7848858833),oo=new y(-0.35,1,0.8),ro=new y(-0.5,0.366,0.785),ao=new MA(0.3,0.3,0.3,1),to=2,eo=[0.25098,0.27451,0.30588],Ar=[0.43922,0.12549,0.06275];var Qr=[0.75294,0.62745,0.18824],Er=[0.05126930067255049,0.061246141699984984,0.07618418934386001],Br=[0.1620327698875954,0.014443805936996105,0.0051820344376627735];var Ir=[0.5271132835871205,0.3515313874944194,0.02955820686563641];var Cr="#902010";var Kr="#c0a030",Jr={0:[0.824,0.118,0.078],1:[1,0.431,0.098],2:[1,0.847,0.125],3:[0.471,0.824,0.125],4:[0,0.471,0.188],5:[0.039,0.282,0.706],6:[0.235,0.667,0.871],7:[0.961,0.353,0.49],8:[0.451,0.157,0.678],9:[0.282,0.22,0.094],10:[0.878,0.878,0.878],11:[0.094,0.094,0.078]};var wE;if(typeof window==="undefined")wE=self;else wE=window;wE.FFLShaderMaterial=BB;wE.LUTShaderMaterial=K0;var fK={WiiU:{m:null,f:null},Switch:{m:null,f:null},Miitomo:{m:null,f:null}},MS=new YK;//! NOTE: THIS ASSUMES THE ROOT IS THE PUBLIC FOLDER -function gX(A,Q){return`/assets/models/miiBody${A}_${Q}.glb`}async function xX(A){let Q=await MS.loadAsync(A);var E=new xI(Q.scene);let B=Q.scene,I=Q.animations[0];E.clipAction(I,B).stop();let K=Q.animations.find((U)=>U.name==="Wait"),J=E.clipAction(K,B);return J.play(),J.timeScale=0,E.update(),B}async function lX(){fK.Miitomo.m=await xX(gX("M","miitomo")),fK.Miitomo.f=await xX(gX("F","miitomo"))}wE.bodyModels=fK;function bX(A,Q="GeneratedType",E=0){if(E>5)return"";let B=" ".repeat(E),I=`${B}/** -${B} * @typedef {Object} ${Q} -`;Object.keys(A).forEach((C)=>{if(C.startsWith("_"))return;let K=A[C],J=typeof K,U;if(K===null)U="null";else if(Array.isArray(K)){let Y=K.length>0?typeof K[0]:"any";if(typeof K[0]==="object"&&K[0]!==null)Y=bX(K[0],`${Q}_${C}_Item`,E+1);U=`Array<${Y}>`}else if(J==="object")U=bX(K,`${Q}_${C}`,E+1)||"Object";else U=J;I+=`${B} * @property {${U}} ${C} -`}),I+=`${B} */ -`,console.log(I)}function Nr(typeName){if(typeof typeName!=="string")throw new Error;eval(` - const empty = new Uint8Array(${typeName}.size); - generateJSDoc(${typeName}.unpack(empty), typeName); - `)}if(r.default===void 0){let A=wE._}var gK={OPA_BEARD:0,OPA_FACELINE:1,OPA_HAIR_NORMAL:2,OPA_FOREHEAD_NORMAL:3,XLU_MASK:4,XLU_NOSELINE:5,OPA_NOSE:6,OPA_HAT_NORMAL:7,XLU_GLASS:8,OPA_HAIR_CAP:9,OPA_FOREHEAD_CAP:10,OPA_HAT_CAP:11,MAX:12},Q8={POSITION:0,TEXCOORD:1,NORMAL:2,TANGENT:3,COLOR:4,MAX:5},fU={NONE:0,BACK:1,FRONT:2,MAX:3},wS={CONSTANT:0,TEXTURE_DIRECT:1,RGB_LAYERED:2,ALPHA:3,LUMINANCE_ALPHA:4,ALPHA_OPA:5},V6={SHAPE_FACELINE:0,SHAPE_BEARD:1,SHAPE_NOSE:2,SHAPE_FOREHEAD:3,SHAPE_HAIR:4,SHAPE_CAP:5,SHAPE_MASK:6,SHAPE_NOSELINE:7,SHAPE_GLASS:8,MUSTACHE:9,MOUTH:10,EYEBROW:11,EYE:12,MOLE:13,FACE_MAKE:14,FACE_LINE:15,FACE_BEARD:16,FILL:17,SHAPE_MAX:9},uK={MIDDLE:0,HIGH:1,MAX:2},pK={NORMAL:0,MAX:70},dX={NORMAL:1,HAT:2,FACE_ONLY:4,FLATTEN_NOSE:8,NEW_EXPRESSIONS:16,NEW_MASK_ONLY:32},_S=r.default.struct([r.default.uint32le("size"),r.default.uint32le("stride"),r.default.uintptr("ptr")]),kS=r.default.struct([r.default.struct("attributeBuffers",[_S],5)]),SS=r.default.struct([r.default.uint32le("primitiveType"),r.default.uint32le("indexCount"),r.default.uint32le("_8"),r.default.uintptr("pIndexBuffer")]),q7=r.default.struct([r.default.float32le("r"),r.default.float32le("g"),r.default.float32le("b"),r.default.float32le("a")]),cB=r.default.struct([r.default.float32le("x"),r.default.float32le("y"),r.default.float32le("z")]),TS=r.default.struct([r.default.uint32le("mode"),r.default.uint32le("type"),r.default.uintptr("pColorR"),r.default.uintptr("pColorG"),r.default.uintptr("pColorB"),r.default.uintptr("pTexture2D")]),lB=r.default.struct([r.default.struct("attributeBufferParam",[kS]),r.default.struct("modulateParam",[TS]),r.default.uint32le("cullMode"),r.default.struct("primitiveParam",[SS])]),nX=r.default.struct([r.default.uint8("data",10)]),dB=r.default.struct([r.default.int32le("miiVersion"),r.default.struct("faceline",[r.default.int32le("type"),r.default.int32le("color"),r.default.int32le("texture"),r.default.int32le("make")]),r.default.struct("hair",[r.default.int32le("type"),r.default.int32le("color"),r.default.int32le("flip")]),r.default.struct("eye",[r.default.int32le("type"),r.default.int32le("color"),r.default.int32le("scale"),r.default.int32le("aspect"),r.default.int32le("rotate"),r.default.int32le("x"),r.default.int32le("y")]),r.default.struct("eyebrow",[r.default.int32le("type"),r.default.int32le("color"),r.default.int32le("scale"),r.default.int32le("aspect"),r.default.int32le("rotate"),r.default.int32le("x"),r.default.int32le("y")]),r.default.struct("nose",[r.default.int32le("type"),r.default.int32le("scale"),r.default.int32le("y")]),r.default.struct("mouth",[r.default.int32le("type"),r.default.int32le("color"),r.default.int32le("scale"),r.default.int32le("aspect"),r.default.int32le("y")]),r.default.struct("beard",[r.default.int32le("mustache"),r.default.int32le("type"),r.default.int32le("color"),r.default.int32le("scale"),r.default.int32le("y")]),r.default.struct("glass",[r.default.int32le("type"),r.default.int32le("color"),r.default.int32le("scale"),r.default.int32le("y")]),r.default.struct("mole",[r.default.int32le("type"),r.default.int32le("scale"),r.default.int32le("x"),r.default.int32le("y")]),r.default.struct("body",[r.default.int32le("height"),r.default.int32le("build")]),r.default.struct("personal",[r.default.char16le("name",22),r.default.char16le("creator",22),r.default.int32le("gender"),r.default.int32le("birthMonth"),r.default.int32le("birthDay"),r.default.int32le("favoriteColor"),r.default.uint8("favorite"),r.default.uint8("copyable"),r.default.uint8("ngWord"),r.default.uint8("localonly"),r.default.int32le("regionMove"),r.default.int32le("fontRegion"),r.default.int32le("roomIndex"),r.default.int32le("positionInRoom"),r.default.int32le("birthPlatform")]),r.default.struct("createID",[nX]),r.default.uint16le("padding_0"),r.default.int32le("authorType"),r.default.uint8("authorID",8)]),cU=96,F7=-2147483648,z6=(A)=>A|F7,P6=(A)=>A&~F7===0?A:A&~F7,$7=r.default.struct([r.default.char16le("name",22),r.default.char16le("creator",22),r.default.struct("createID",[nX]),r.default.byte("_padding0",2),r.default.struct("skinColor",[q7]),r.default.uint32le("flags"),r.default.uint8("facelineType"),r.default.uint8("hairType"),r.default.byte("_padding1",2)]),zS=r.default.struct([r.default.uintptr("pTexture2DRenderBufferColorTargetDepthTarget",4)]),PS=r.default.struct([r.default.uintptr("pTextureFaceLine"),r.default.struct("drawParamFaceLine",[lB]),r.default.uintptr("pTextureFaceMake"),r.default.struct("drawParamFaceMake",[lB]),r.default.uintptr("pTextureFaceBeard"),r.default.struct("drawParamFaceBeard",[lB]),r.default.uintptr("pRenderTextureCompressorParam",2)]),fX=r.default.struct([r.default.struct("drawParamRawMaskPartsEye",[lB],2),r.default.struct("drawParamRawMaskPartsEyebrow",[lB],2),r.default.struct("drawParamRawMaskPartsMouth",[lB]),r.default.struct("drawParamRawMaskPartsMustache",[lB],2),r.default.struct("drawParamRawMaskPartsMole",[lB]),r.default.struct("drawParamRawMaskPartsFill",[lB])]),sX=r.default.struct([r.default.uint8("partsTextures",340),r.default.uintptr("pRawMaskDrawParam",pK.MAX),r.default.byte("_remaining",284)]),yK=r.default.struct([r.default.struct("maskTextures",[sX]),r.default.struct("facelineTexture",[PS])]),VS=r.default.struct([r.default.uintptr("pRenderTextures",pK.MAX)]),jS=1073741823,E8=r.default.struct([r.default.uint32le("resolution"),r.default.uint32le("allExpressionFlag",3),r.default.uint32le("modelFlag"),r.default.uint32le("resourceType")]);E8.default={resolution:512,allExpressionFlag:new Uint32Array([1,0,0]),modelFlag:dX.NORMAL,resourceType:uK.HIGH};var Gr=E8.default,vS=r.default.struct([r.default.struct("min",[cB]),r.default.struct("max",[cB])]),hS=r.default.struct([r.default.struct("hatTranslate",[cB]),r.default.struct("headFrontRotate",[cB]),r.default.struct("headFrontTranslate",[cB]),r.default.struct("headSideRotate",[cB]),r.default.struct("headSideTranslate",[cB]),r.default.struct("headTopRotate",[cB]),r.default.struct("headTopTranslate",[cB])]),lU=r.default.struct([r.default.struct("charInfo",[dB]),r.default.struct("charModelDesc",[E8]),r.default.uint32le("expression"),r.default.uintptr("pTextureTempObject"),r.default.struct("drawParam",[lB],gK.MAX),r.default.uintptr("pShapeData",gK.MAX),r.default.struct("facelineRenderTexture",[zS]),r.default.uintptr("pCapGlassNoselineTextures",3),r.default.struct("maskTextures",[VS]),r.default.struct("beardHairFaceCenterPos",[cB],3),r.default.struct("partsTransform",[hS]),r.default.uint32le("modelType"),r.default.struct("boundingBox",[vS],3)]),iX={OFFICIAL:0,DEFAULT:1,MIDDLE_DB:2,STORE_DATA_OFFICIAL:3,STORE_DATA:4,BUFFER:5,DIRECT_POINTER:6},uX=r.default.struct([r.default.uint32le("dataSource"),r.default.uintptr("pBuffer"),r.default.uint16le("index")]),Wr={MALE:0,FEMALE:1,ALL:2},Xr={CHILD:0,ADULT:1,ELDER:2,ALL:3},$r={BLACK:0,WHITE:1,ASIAN:2,ALL:3},pX=r.default.struct([r.default.uintptr("pData",uK.MAX),r.default.uint32le("size",uK.MAX)]),L7={R8_UNORM:0,R8_G8_UNORM:1,R8_G8_B8_A8_UNORM:2,MAX:3},mX=r.default.struct([r.default.uint16le("width"),r.default.uint16le("height"),r.default.uint8("mipCount"),r.default.uint8("format"),r.default.uint8("isGX2Tiled"),r.default.byte("_padding",1),r.default.uint32le("imageSize"),r.default.uintptr("imagePtr"),r.default.uint32le("mipSize"),r.default.uintptr("mipPtr"),r.default.uint32le("mipLevelOffset",13)]),cX=r.default.struct([r.default.uintptr("pObj"),r.default.uint8("useOriginalTileMode"),r.default.byte("_padding",3),r.default.uintptr("pCreateFunc"),r.default.uintptr("pDeleteFunc")]);class oX{constructor(A=wE.Module){this.module=A,this.textures=/*@__PURE__*/new Map,this.textureCallbackPtr=null,this._setupTextureCallbacks()}_setupTextureCallbacks(){let A=this.module;this.createCallback=A.addFunction(this._textureCreateFunc.bind(this),"vppp"),this.deleteCallback=A.addFunction(this._textureDeleteFunc.bind(this),"vpp");let Q={pObj:0,useOriginalTileMode:!1,_padding:[0,0,0],pCreateFunc:this.createCallback,pDeleteFunc:this.deleteCallback},E=cX.pack(Q);this.textureCallbackPtr=A._malloc(cX.size),A.HEAPU8.set(new Uint8Array(E),this.textureCallbackPtr),A._FFLSetTextureCallback(this.textureCallbackPtr)}_getTextureFormat(A){let Q=Number(ZB)<137,E=Q?L1:SQ,B=Q?ZC:jE,C={[L7.R8_UNORM]:E,[L7.R8_G8_UNORM]:B,[L7.R8_G8_B8_A8_UNORM]:V0}[A];if(C===void 0)throw new Error(`_textureCreateFunc: Unexpected FFLTextureFormat value: ${A}`);return C}_textureCreateFunc(A,Q,E){let B=this.module.HEAPU8.subarray(Q,Q+mX.size),I=mX.unpack(B),C=this._getTextureFormat(I.format),K=this.module.HEAPU8.slice(I.imagePtr,I.imagePtr+I.imageSize),J=new h0(K,I.width,I.height,C,x0);if(J.magFilter=L0,J.minFilter=L0,Number(ZB)>=138)J.minFilter=hQ,J.generateMipmaps=!1,this._addMipmaps(J,I);J.needsUpdate=!0,this.set(J.id,J),this.module.HEAPU32[E/4]=J.id}_addMipmaps(A,Q){if(Q.mipPtr===0||Q.mipCount<2)return;let E=[1,2,4][Q.format];if(!E)throw new Error(`_addMipmaps: Unexpected FFLTextureFormat value: ${Q.format}`);for(let B=1;B>B),K=Math.max(1,Q.height>>B),J=C*K*E,U=Q.mipPtr+I,Y=this.module.HEAPU8.slice(U,U+J);A.mipmaps.push({data:Y,width:C,height:K})}}_textureDeleteFunc(A,Q){let E=this.module.HEAPU32[Q/4],B=this.textures.get(E)}get(A){let Q=this.textures.get(A);if(!Q)console.error("Unknown texture",A);return Q}set(A,Q){Q._dispose=Q.dispose.bind(Q),Q.dispose=()=>{this.delete(A)},this.textures.set(A,Q)}delete(A){let Q=this.textures.get(A);if(Q)Q._dispose(),Q.source=null,this.textures.delete(A)}}function w7(A,Q){let E;if(typeof Q!=="number")E=`Unexpected type for FFLResult from ${A}: ${typeof Q}`;else if(Q!==0)E=`${A} failed with FFLResult: ${Q}`;if(E)throw new Error(E)}async function yS(A,Q){let E,B;try{if(A instanceof ArrayBuffer)A=new Uint8Array(A);if(A instanceof Uint8Array)console.warn("initializeFFL -> _loadDataIntoHeap: resource was passed as Uint8Array/ArrayBuffer. Please pass in a fetch Response instance for improved efficiency."),E=A.length,B=Q._malloc(E),console.debug(`loadDataIntoHeap: Loading from Uint8Array. Size: ${E}, pointer: ${B}`),Q.HEAPU8.set(A,B);else if(A instanceof Response){if(!A.body)throw new Error("Fetch response is not streamable.");let I=A.headers.get("Content-Length");if(!I)throw new Error("Fetch response missing Content-Length.");E=parseInt(I,10),B=Q._malloc(E),console.debug(`loadDataIntoHeap: Streaming ${E} bytes from fetch response. URL: ${A.url}, pointer: ${B}`);let C=A.body.getReader(),K=B;while(!0){let{done:J,value:U}=await C.read();if(J)break;Q.HEAPU8.set(U,K),K+=U.length}}else throw new Error("loadDataIntoHeap: type is not Uint8Array or Response");return{pointer:B,size:E}}catch(I){if(B)Q._free(B);throw I}}var pU;async function gS(A,Q=wE.Module){console.debug("initializeFFL: Entrypoint, waiting for module to be ready.");let E;return new Promise((B)=>{if(!Q.calledRun&&!Q.onRuntimeInitialized)Q.onRuntimeInitialized=()=>{console.debug("initializeFFL: Emscripten runtime initialized, resolving."),B()},console.debug(`initializeFFL: module.calledRun: ${Q.calledRun}, module.onRuntimeInitialized: ${Q.onRuntimeInitialized} / << assigned and waiting.`);else console.debug("initializeFFL: Assuming module is ready."),B()}).then(async()=>{if(A instanceof Promise)A=await A}).then(()=>{return yS(A,Q)}).then(({pointer:B,size:I})=>{console.debug(`initializeFFL: Resource loaded into heap. Pointer: ${B}, Size: ${I}`);let C={pData:[0,0],size:[0,0]};C.pData[uK.HIGH]=B,C.size[uK.HIGH]=I,pU=C;let K=pX.pack(C);E=Q._malloc(pX.size),Q.HEAPU8.set(K,E);let J=Q._FFLInitRes(0,E);w7("FFLInitRes",J),Q._FFLInitResGPUStep(),Q._FFLSetNormalIsSnorm8_8_8_8(!0),Q._FFLSetTextureFlipY(!0)}).catch((B)=>{throw Q._free(),console.error("initializeFFL failed:",B),B}).finally(()=>{if(E)Q._free(E)})}async function rX(A=null,Q=wE.Module){if(!A&&typeof document!=="undefined"){let B=document.querySelector("meta[itemprop=ffl-js-resource-fetch-path]");if(!B||!B.getAttribute("content"))throw new Error('initializeFFLWithResource: Element not found or does not have "content" attribute with path to FFL resource: meta[itemprop=ffl-js-resource-fetch-path]');A=B.getAttribute("content")}if(!A)throw new Error("initializeFFLWithResource: resourcePath must be a string");try{let B=await fetch(A);await gS(B,Q),wE.FFLTextures=new oX(Q),console.debug("initializeFFLWithResource: FFLiManager and TextureManager initialized, exiting")}catch(B){throw alert(`Error initializing FFL with resource: ${B}`),B}}function Lr(A){if(!pU){console.warn("exitFFL was called when FFL is not initialized.");return}console.debug("exitFFL called, _resourceDesc:",pU),A._FFLExit(),pU.pData.forEach((Q)=>{if(Q)A._free(_fflResourcePtr)})}class xK{constructor(A,Q=wE.Module,E=wE.FFLShaderMaterial){this._module=Q,this._materialClass=E,this._ptr=A,this.__ptr=A;let B=this._module.HEAPU8.subarray(A,A+lU.size);this._model=lU.unpack(B),this._facelineTarget=null,this._maskTargets=new Array(pK.MAX).fill(null),this.meshes=new i0,this._addCharModelMeshes(Q)}_addCharModelMeshes(A){for(let Q=0;Q{if(!A)return;A.dispose(),this._maskTargets[Q]=null})}dispose(){this._finalizeCharModel(),P7(this.meshes),this.meshes=null,this._disposeTextures()}getStoreData(){let A=this._getCharInfoUint8Array(),Q=this._module,E=Q._malloc(dB.size),B=Q._malloc(cU);Q.HEAPU8.set(A,E);let I=Q._FFLpGetStoreDataFromCharInfo(B,E),C=Q.HEAPU8.slice(B,B+cU);if(Q._free(E),Q._free(B),!I)throw new Error("getStoreData: call to FFLpGetStoreDataFromCharInfo returned false, CharInfo verification probably failed");return C}setExpression(A){this._model.expression=A;let Q=this._maskTargets[A];if(!Q||!Q.texture)throw new Error(`setExpression: this._maskTargets[${A}].texture is not a valid texture`);let E=this.meshes.getObjectById(this._maskID);if(!E)throw new Error("setExpression: this.meshes[FFLiShapeType.XLU_MASK] does not exist, cannot set expression on the mask");E.material.map=Q.texture,E.material.needsUpdate=!0}get expression(){return this._model.expression}set expression(A){throw new Error("nope you cannot do this, try setExpression instead")}get facelineColor(){if(!this._facelineColor)this._facelineColor=this._getFacelineColor();return this._facelineColor}get favoriteColor(){if(!this._favoriteColor)this._favoriteColor=this._getFavoriteColor();return this._favoriteColor}get partsTransform(){if(!this._partsTransform)this._partsTransform=this._getPartsTransform();return this._partsTransform}get boundingBox(){if(!this._boundingBox)this._boundingBox=this._getBoundingBox();return this._boundingBox}static BodyScaleMode={Apply:0,Limit:1};getBodyScale(A=xK.BodyScaleMode.Apply){let Q=this._model.charInfo.body.build,E=this._model.charInfo.body.height,B=new y;switch(A){case xK.BodyScaleMode.Apply:{B.x=Q*(E*0.003671875+0.4)/128+E*0.001796875+0.4,B.y=E*0.006015625+0.5;break}case xK.BodyScaleMode.Limit:{let I=E/128;B.y=I*0.55+0.6,B.x=I*0.3+0.6,B.x=(I*0.6+0.8-B.x)*(Q/128)+B.x;break}default:throw new Error(`getBodyScale: Unexpected value for scaleMode: ${A}`)}return B.z=B.x,B}}var uU={GrayNormal:0,BluePresent:1,RedRegular:2,GoldSpecial:3},qr={[uU.GrayNormal]:new a(4212558),[uU.BluePresent]:new a(2637946),[uU.RedRegular]:new a(7348245),[uU.GoldSpecial]:new a(12623920)};function xS(A,Q){let E=Q._malloc(dB.size),B={dataSource:iX.DIRECT_POINTER,pBuffer:E,index:0};if(!(A instanceof Uint8Array))try{if(typeof A!=="object")throw new Error("_allocateModelSource: data passed in is not FFLiCharInfo object or Uint8Array");A=dB.pack(A)}catch(I){throw Q._free(E),I}switch(A.length){case cU:{let I=Q._malloc(cU);Q.HEAPU8.set(A,I);let C=Q._FFLpGetCharInfoFromStoreData(E,I);if(Q._free(I),!C)throw Q._free(E),new Error("_allocateModelSource: call to FFLpGetCharInfoFromStoreData returned false, CharInfo verification probably failed");break}case dB.size:Q.HEAPU8.set(A,E);break;case mU.size+1:A=oS(A);case mU.size:{let I=mU.unpack(A),C=iS(I);A=dB.pack(C),Q.HEAPU8.set(A,E);break}default:throw Q._free(E),new Error(`_allocateModelSource: Unknown data length: ${A.length}`)}return B}function bS(A,Q,E=!1){let B=0,I=!1;if(typeof A==="number")B=A,I=!1;else I=!0,B=Q._malloc(dB.size),Q.HEAPU8.set(A,B);let C=Q._FFLiVerifyCharInfoWithReason(B,E);if(I)Q._free(B);if(C!==0)throw new Error(`FFLiVerifyCharInfoWithReason failed with result: ${C}`)}function Fr(A,Q,E,B){let I=A._malloc(dB.size);A._FFLiGetRandomCharInfo(I,Q,E,B);let C=A.HEAPU8.slice(I,I+dB.size);return A._free(I),C}function fS(A){function Q(B){if(B>=pK.MAX)throw new Error(`makeExpressionFlag: input out of range: got ${B}, max: ${pK.MAX}`)}let E=new Uint32Array([0,0,0]);if(typeof A==="number")A=[A];else if(!Array.isArray(A))throw new Error("makeExpressionFlag: expected array or single number");for(let B of A){Q(B);let I=Math.floor(B/32),C=B%32;E[I]|=1<{let R=parseInt(Y);if(H.size===0&&R!==Q8.POSITION)return;switch(R){case Q8.POSITION:{let O=H.ptr/4,N=Q.HEAPF32.subarray(O,O+I*4),$=new hE(N,4);C.setAttribute("position",new xQ($,3,0));break}case Q8.NORMAL:{let O=Q.HEAP8.subarray(H.ptr,H.ptr+H.size);C.setAttribute("normal",new p8(O,H.stride,!0));break}case Q8.TANGENT:{let O=Q.HEAP8.subarray(H.ptr,H.ptr+H.size);C.setAttribute("tangent",new p8(O,H.stride,!0));break}case Q8.TEXCOORD:{let O=H.ptr/4,N=Q.HEAPF32.subarray(O,O+I*2);C.setAttribute("uv",new PA(N,H.stride/4));break}case Q8.COLOR:{if(H.stride===0)break;let O=Q.HEAPU8.subarray(H.ptr,H.ptr+H.size);C.setAttribute("_color",new qC(O,H.stride,!0));break}}}),C}function pS(A,Q=wE.FFLTextures){if(!A.pTexture2D||A.type===V6.SHAPE_FACELINE||A.type===V6.SHAPE_MASK)return null;let E=A.pTexture2D,B=Q.get(E);if(!B)throw new Error(`_getTextureFromModulateParam: Texture not found for ${E}.`);if([V6.SHAPE_FACELINE,V6.SHAPE_CAP,V6.SHAPE_GLASS].includes(A.type))B.wrapS=OE,B.wrapT=OE,B.needsUpdate=!0;return B}function mS(A,Q){let E=new MA(0,0,0,0);if(A.pColorR!==0){let I=A.pColorR/4,C=Q.HEAPF32.subarray(I,I+4);E=new MA(C[0],C[1],C[2],C[3])}if(A.pColorG!==0&&A.pColorB!==0)E=[bK(A.pColorR,Q),bK(A.pColorG,Q),bK(A.pColorB,Q)];let B=!(A.mode!==wS.CONSTANT&&A.type>=V6.SHAPE_MAX);return{modulateMode:A.mode,modulateType:A.type,modulateColor:E,lightEnable:B}}function bK(A,Q){if(!A)return console.error("getVector4FromFFLColorPtr: Received null pointer"),new MA(0,0,0,0);let E=Q.HEAPF32.subarray(A/4,A/4+4);return new MA(E[0],E[1],E[2],E[3])}var k7=!1;function S7(A,Q){let E=A._module,B=A._getTextureTempObject();if(cS(A,B,Q,E),lS(A,B,Q,E),!k7)A._finalizeCharModel();A.setExpression(A.expression)}var D7=()=>null,M7=()=>null;function Mr(A){D7=async(Q,E)=>{let B=await V7(Q,E,!0);A(B),D7=()=>null}}function wr(A){M7=async(Q,E)=>{let B=await V7(Q,E,!0);A(B),M7=()=>null}}function cS(A,Q,E,B){let I=A._getFacelineTempObjectPtr();B._FFLiInvalidateTempObjectFacelineTexture(I);let C=[Q.facelineTexture.drawParamFaceLine,Q.facelineTexture.drawParamFaceBeard,Q.facelineTexture.drawParamFaceMake].filter((O)=>O&&O.modulateParam.pTexture2D!==0);if(C.length===0)return;let K=A.facelineColor,{scene:J}=tX(C,K,A._materialClass,A._module,E),U=A._getResolution()/2,Y=A._getResolution(),H={depthBuffer:!1,stencilBuffer:!1,wrapS:OE,wrapT:OE},R=z7(J,T7(),E,U,Y,H);if(D7(R,E),nS(A,R),!k7)B._FFLiDeleteTempObjectFacelineTexture(I,A._ptr,A._model.charModelDesc.resourceType);P7(J)}function lS(A,Q,E,B){let I=A._getMaskTempObjectPtr(),C=A._ptr+lU.fields.charModelDesc.offset+E8.fields.allExpressionFlag.offset,K=[];for(let J=0;J{P7(J)}),!k7)B._FFLiDeleteTempObjectMaskTextures(I,C,A._model.charModelDesc.resourceType),B._FFLiDeleteTextureTempObject(A._ptr)}function dS(A,Q,E,B){let I=[Q.drawParamRawMaskPartsMustache[0],Q.drawParamRawMaskPartsMustache[1],Q.drawParamRawMaskPartsMouth,Q.drawParamRawMaskPartsEyebrow[0],Q.drawParamRawMaskPartsEyebrow[1],Q.drawParamRawMaskPartsEye[0],Q.drawParamRawMaskPartsEye[1],Q.drawParamRawMaskPartsMole].filter((Y)=>Y&&Y.primitiveParam.indexCount!==0);if(I.length===0)return console.error("No mask drawParams found"),null;let C={depthBuffer:!1,stencilBuffer:!1},{scene:K}=tX(I,null,A._materialClass,B),J=A._getResolution(),U=z7(K,T7(),E,J,J,C);return M7(U,E),{target:U,scene:K}}function nS(A,Q){if(!Q||!Q.texture)throw new Error("setFaceline: passed in RenderTarget is invalid");A._facelineTarget=Q;let E=A.meshes.getObjectById(A._facelineID);if(!E)throw new Error("setFaceline: charModel.meshes[FFLiShapeType.OPA_FACELINE] does not exist");E.material.map=Q.texture,E.material.needsUpdate=!0}function tX(A,Q=null,E,B){let I=new yQ;I.background=Q||null;let C=[];return A.forEach((K)=>{let J=aX(K,E,B);if(J)I.add(J),C.push(J)}),{scene:I,meshes:C}}function T7(A=!1){let Q=new HE(-1,1,A?-1:1,A?1:-1,0.1,10);return Q.position.z=1,Q}function z7(A,Q,E,B,I,C={}){let K={minFilter:L0,magFilter:L0,...C},J=new Q0(B,I,K),U=E.getRenderTarget();return E.setRenderTarget(J),E.render(A,Q),E.setRenderTarget(U),J}function P7(A,Q){if(A.traverse((E)=>{if(!E.isMesh)return;if(E.geometry)E.geometry.dispose();if(E.material){if(E.material.map)E.material.map.dispose();E.material.dispose()}}),Q&&Q instanceof yQ)Q.remove(A);A.children=[]}function V7(A,Q,E=!1){return new Promise((B)=>{let I=new yQ;I.background=null;let C=new _0({side:y0,map:A.texture,transparent:!0}),K=new dQ(2,2),J=new xA(K,C);I.add(J);let U=T7(E),Y=Q.getRenderTarget(),H=Q.outputColorSpace,R=new AA;Q.getSize(R),Q.setRenderTarget(null),Q.outputColorSpace=O0?O0.workingColorSpace:null,Q.setSize(A.width,A.height,!1),Q.render(I,U);function O(){C.dispose(),K.dispose(),I.remove(J),Q.outputColorSpace=H,Q.setSize(R.x,R.y,!1),Q.setRenderTarget(Y)}if(typeof window==="undefined")Q.domElement.convertToBlob({type:"image/png"}).then((N)=>{B({type:"blob",result:N}),O()});else{let N=Q.domElement.toDataURL("image/png");B({type:"dataURL",result:N}),O()}})}function _r(A,Q){if(!Q)console.warn(`appendImageFromDataUrl: you did not specify "container" so we will use document.body, don't be surprised if your image ends up in brazil`),Q=document.body;let E=new Image;E.src=A,Q.appendChild(E)}var LI={Face:0,MakeIcon:1,IconFovy45:2,AllBody:3};function sS(A,Q=1,E=1){let B=Q/E;switch(A){case LI.Face:{let C=new v0(15,B,0.1,1000);return C.position.set(0,34.5,380),C.lookAt(0,34.3,0),C}case LI.MakeIcon:{let C=new v0(10,B,500,1000);return C.position.set(0,34.5,600),C.lookAt(0,34.5,0),C}case LI.IconFovy45:{let I=new v0(45,B,50,1000);return I.position.set(0,34,110),I.lookAt(0,34,0),I}case LI.AllBody:{let C=new v0(15,B,50,1500);return C.position.set(0,50,900),C.lookAt(0,105,0),C}default:throw new Error("getCameraForViewType: not implemented")}}function eX(A,Q,E=LI.MakeIcon,B=256,I=256,C=!1){return new Promise((K)=>{let J=new yQ;J.background=null;let U=A._getGender();if(C){let L,W,Z,G;var Y=A.getBodyScale();switch(U){case 0:{L=fK.Miitomo.m,W=L.getObjectByName("body_m"),Z=L.getObjectByName("hands_m"),G=L.getObjectByName("legs_m");break}case 1:{L=fK.Miitomo.f,W=L.getObjectByName("body_f"),Z=L.getObjectByName("hands_f"),G=L.getObjectByName("legs_f");break}}L.scale.set(1,Y.y*10,1);var H=new g0().setFromObject(L);console.log("pos y:",H.max.y),L.position.set(0,-H.max.y,0),J.add(L);var R=A._getFavoriteColor(!0);W.material=new K0({modulateType:9,modulateMode:0,modulateColor:new MA(R.r,R.g,R.b,1)}),G.material=new K0({modulateType:10,modulateMode:0,modulateColor:new MA(0.3,0.3,0.3,1)})}J.add(A.meshes.clone());let O=sS(E),N=z7(J,O,Q,B,I),$=V7(N,Q);N.dispose(),K($)})}var mU=r.default.struct([r.default.uint8("beardColor"),r.default.uint8("beardType"),r.default.uint8("build"),r.default.uint8("eyeAspect"),r.default.uint8("eyeColor"),r.default.uint8("eyeRotate"),r.default.uint8("eyeScale"),r.default.uint8("eyeType"),r.default.uint8("eyeX"),r.default.uint8("eyeY"),r.default.uint8("eyebrowAspect"),r.default.uint8("eyebrowColor"),r.default.uint8("eyebrowRotate"),r.default.uint8("eyebrowScale"),r.default.uint8("eyebrowType"),r.default.uint8("eyebrowX"),r.default.uint8("eyebrowY"),r.default.uint8("facelineColor"),r.default.uint8("facelineMake"),r.default.uint8("facelineType"),r.default.uint8("facelineWrinkle"),r.default.uint8("favoriteColor"),r.default.uint8("gender"),r.default.uint8("glassColor"),r.default.uint8("glassScale"),r.default.uint8("glassType"),r.default.uint8("glassY"),r.default.uint8("hairColor"),r.default.uint8("hairFlip"),r.default.uint8("hairType"),r.default.uint8("height"),r.default.uint8("moleScale"),r.default.uint8("moleType"),r.default.uint8("moleX"),r.default.uint8("moleY"),r.default.uint8("mouthAspect"),r.default.uint8("mouthColor"),r.default.uint8("mouthScale"),r.default.uint8("mouthType"),r.default.uint8("mouthY"),r.default.uint8("mustacheScale"),r.default.uint8("mustacheType"),r.default.uint8("mustacheY"),r.default.uint8("noseScale"),r.default.uint8("noseType"),r.default.uint8("noseY")]);function iS(A){return{miiVersion:0,faceline:{type:A.facelineType,color:A.facelineColor,texture:A.facelineWrinkle,make:A.facelineMake},hair:{type:A.hairType,color:z6(A.hairColor),flip:A.hairFlip},eye:{type:A.eyeType,color:z6(A.eyeColor),scale:A.eyeScale,aspect:A.eyeAspect,rotate:A.eyeRotate,x:A.eyeX,y:A.eyeY},eyebrow:{type:A.eyebrowType,color:z6(A.eyebrowColor),scale:A.eyebrowScale,aspect:A.eyebrowAspect,rotate:A.eyebrowRotate,x:A.eyebrowX,y:A.eyebrowY},nose:{type:A.noseType,scale:A.noseScale,y:A.noseY},mouth:{type:A.mouthType,color:z6(A.mouthColor),scale:A.mouthScale,aspect:A.mouthAspect,y:A.mouthY},beard:{mustache:A.mustacheType,type:A.beardType,color:z6(A.beardColor),scale:A.mustacheScale,y:A.mustacheY},glass:{type:A.glassType,color:z6(A.glassColor),scale:A.glassScale,y:A.glassY},mole:{type:A.moleType,scale:A.moleScale,x:A.moleX,y:A.moleY},body:{height:A.height,build:A.build},personal:{name:"",creator:"",gender:A.gender,birthMonth:0,birthDay:0,favoriteColor:A.favoriteColor,favorite:0,copyable:0,ngWord:0,localonly:0,regionMove:0,fontRegion:0,roomIndex:0,positionInRoom:0,birthPlatform:3},createID:{data:new Array(10).fill(0)},padding_0:0,authorType:0,authorID:new Array(8).fill(0)}}function oS(A){let Q=new Uint8Array(A),B=Q[0];for(let I=1;I<48;I++){let C=Q[I],K=(C-7+256)%256;Q[I-1]=K^B,B=C}return Q.slice(0,mU.size)}function kr(A){return{beardColor:P6(A.beard.color),beardType:A.beard.type,build:A.body.build,eyeAspect:A.eye.aspect,eyeColor:P6(A.eye.color),eyeRotate:A.eye.rotate,eyeScale:A.eye.scale,eyeType:A.eye.type,eyeX:A.eye.x,eyeY:A.eye.y,eyebrowAspect:A.eyebrow.aspect,eyebrowColor:P6(A.eyebrow.color),eyebrowRotate:A.eyebrow.rotate,eyebrowScale:A.eyebrow.scale,eyebrowType:A.eyebrow.type,eyebrowX:A.eyebrow.x,eyebrowY:A.eyebrow.y,facelineColor:A.faceline.color,facelineMake:A.faceline.make,facelineType:A.faceline.type,facelineWrinkle:A.faceline.texture,favoriteColor:A.personal.favoriteColor,gender:A.personal.gender,glassColor:P6(A.glass.color),glassScale:A.glass.scale,glassType:A.glass.type,glassY:A.glass.y,hairColor:P6(A.hair.color),hairFlip:A.hair.flip,hairType:A.hair.type,height:A.body.height,moleScale:A.mole.scale,moleType:A.mole.type,moleX:A.mole.x,moleY:A.mole.y,mouthAspect:A.mouth.aspect,mouthColor:P6(A.mouth.color),mouthScale:A.mouth.scale,mouthType:A.mouth.type,mouthY:A.mouth.y,mustacheScale:A.beard.scale,mustacheType:A.beard.mustache,mustacheY:A.beard.y,noseScale:A.nose.scale,noseType:A.nose.type,noseY:A.nose.y}}var rS=(A)=>A.replace(/\s+/g,""),aS=(A)=>new Uint8Array(A.match(/.{1,2}/g).map((Q)=>parseInt(Q,16)));function tS(A){let Q=A.replace(/-/g,"+").replace(/_/g,"/"),E=Q.padEnd(Q.length+(4-Q.length%4)%4,"=");return Uint8Array.from(atob(E),(B)=>B.charCodeAt(0))}var Sr=(A)=>btoa(String.fromCharCode.apply(null,A));function Tr(A){let Q,E=rS(A);if(/^[0-9a-fA-F]+$/.test(E))Q=aS(E);else Q=tS(E);return Q}var iU,L$,y7;function C8(...A){console.log("[FFLWorker]",...A)}function yz(){y7=new AK({antialias:!0,alpha:!0,canvas:L$})}self.onmessage=async(A)=>{C8("Message received from main script",A);let Q=A.data;switch(Q.type){case"Init":{C8("Loading FFL Module"),iU=(await Promise.resolve().then(() => ($$(),X$))).default.Module,C8("Initialized Module!",iU),C8("Loading FFL Resource..."),await lX(),await rX(Q.resourcePath,iU),C8("Loaded FFL Resource!"),L$=Q.offscreenCanvas,yz(),postMessage({ready:!0});break}case"MakeIcon":{C8("Call MakeIcon");var E=performance.now();let C={type:"dataURL",result:""},K;try{let J=Q.data;K=_7(J,void 0,K0,iU,!1),S7(K,y7);let U=LI.MakeIcon;switch(Q.view){case"face":case"variableiconbody":U=LI.MakeIcon;break;case"all_body_sugar":U=LI.MakeIcon;break}C=await eX(K,y7,U,512,512)}catch(J){console.error("Library error: Could not make icon",J)}finally{K.dispose();var B=performance.now();C8(`Got it in ${(B-E).toFixed(0)}ms! Sending to main thread.`);var I=void 0;if(C.type==="blob")I=URL.createObjectURL(C.result),setTimeout(()=>{URL.revokeObjectURL(I)},500);postMessage({id:Q.id,result:I||C.result})}}}}; +var __create = Object.create; +var __getProtoOf = Object.getPrototypeOf; +var __defProp = Object.defineProperty; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __toESM = (mod2, isNodeMode, target) => { + target = mod2 != null ? __create(__getProtoOf(mod2)) : {}; + const to = isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target; + for (let key2 of __getOwnPropNames(mod2)) + if (!__hasOwnProp.call(to, key2)) + __defProp(to, key2, { + get: () => mod2[key2], + enumerable: true + }); + return to; +}; +var __moduleCache = /* @__PURE__ */ new WeakMap; +var __toCommonJS = (from) => { + var entry = __moduleCache.get(from), desc; + if (entry) + return entry; + entry = __defProp({}, "__esModule", { value: true }); + if (from && typeof from === "object" || typeof from === "function") + __getOwnPropNames(from).map((key2) => !__hasOwnProp.call(entry, key2) && __defProp(entry, key2, { + get: () => from[key2], + enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable + })); + __moduleCache.set(from, entry); + return entry; +}; +var __commonJS = (cb, mod2) => () => (mod2 || cb((mod2 = { exports: {} }).exports, mod2), mod2.exports); +var __export = (target, all) => { + for (var name2 in all) + __defProp(target, name2, { + get: all[name2], + enumerable: true, + configurable: true, + set: (newValue) => all[name2] = () => newValue + }); +}; +var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res); +var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b) => (typeof require !== "undefined" ? require : a)[b] +}) : x)(function(x) { + if (typeof require !== "undefined") + return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); +}); + +// src/external/ffl.js/struct-fu.js +var require_struct_fu = __commonJS((exports2, module2) => { + /*! + * struct-fu library: https://github.com/natevw/struct-fu + * forked by ariankordi: https://github.com/ariankordi/struct-fu + * @author Nathan Vander Wilt + * @license Apache-2.0 + * @license BSD-2-Clause + */ + (function(root, factory) { + if (typeof define === "function" && define.amd) { + define([], factory); + } else if (typeof module2 === "object" && module2.exports) { + module2.exports = factory(globalThis.TextEncoder, globalThis.TextDecoder); + } else { + root._ = factory(root.TextEncoder, root.TextDecoder); + } + })(typeof self !== "undefined" ? self : exports2, function(_TextEncoder, _TextDecoder) { + var _ = {}; + if (!("bind" in Function.prototype)) { + Function.prototype.bind = function(owner) { + var that = this; + if (arguments.length <= 1) { + return function() { + return that.apply(owner, arguments); + }; + } + var args = Array.prototype.slice.call(arguments, 1); + return function() { + return that.apply(owner, arguments.length === 0 ? args : args.concat(Array.prototype.slice.call(arguments))); + }; + }; + } + function newBuffer(size) { + return new Uint8Array(new ArrayBuffer(size)); + } + function extend(obj) { + var args = Array.prototype.slice.call(arguments, 1); + args.forEach(function(ext) { + Object.keys(ext).forEach(function(key2) { + obj[key2] = ext[key2]; + }); + }); + return obj; + } + function addField(ctr, f) { + if ("width" in f && typeof f.width === "number") { + ctr.bits = (ctr.bits || 0) + f.width; + while ((ctr.bits || 0) > 7) { + ctr.bytes += 1; + ctr.bits -= 8; + } + } else if (!ctr.bits) { + ctr.bytes += f.size || 0; + } else { + throw Error("Improperly aligned bitfield before field: " + (f.name || "")); + } + return ctr; + } + function arrayizeField(f, count) { + var field = typeof count === "number" ? extend({ + name: f.name, + field: f, + unpack: function(buf, off) { + off || (off = { bytes: 0, bits: 0 }); + var arr = new Array(count); + for (var idx = 0, len = arr.length;idx < len; idx += 1) { + arr[idx] = f.unpack(buf, off); + } + return arr; + }, + pack: function(arr, buf, off) { + arr || (arr = new Array(count)); + buf || (buf = newBuffer(this.size)); + off || (off = { bytes: 0, bits: 0 }); + for (var idx = 0, len = Math.min(arr.length, count);idx < len; idx += 1) { + f.pack(arr[idx], buf, off); + } + while (idx++ < count) + addField(off, f); + return buf; + } + }, f.width !== undefined ? { width: f.width * count } : { size: f.size * count }) : f; + return field; + } + _.struct = function(name2, fields, count) { + var structName; + var fieldDefs; + if (typeof name2 !== "string") { + count = fields; + fieldDefs = name2; + } else { + structName = name2; + fieldDefs = fields; + } + var _size = { bytes: 0, bits: 0 }; + var _padsById = Object.create(null); + function reduceFunc(obj, f) { + if ("_padTo" in f) { + var padField = f; + if (!padField._id) { + padField._id = "id" + Math.random().toFixed(20).slice(2); + } + var neededPadBytes = padField._padTo - _size.bytes; + if (_size.bits) { + var bitsNeeded = 8 * neededPadBytes - _size.bits; + if (bitsNeeded < 0) { + throw Error("Invalid .padTo(" + padField._padTo + ") field, struct is already " + _size.bytes + " byte(s) and " + _size.bits + " bits!"); + } + _padsById[padField._id] = { width: bitsNeeded }; + f.width = bitsNeeded; + } else { + if (neededPadBytes < 0) { + throw Error("Invalid .padTo(" + padField._padTo + ") field, struct is already " + _size.bytes + " bytes!"); + } + _padsById[padField._id] = { size: neededPadBytes }; + f.size = neededPadBytes; + } + } + if (f._hoistFields) { + var hoistFields = f._hoistFields; + Object.keys(hoistFields).forEach(function(subName) { + var _f = Object.create(hoistFields[subName]); + if ("width" in _f && typeof _f.width === "number") { + _f.offset = { bytes: _f.offset.bytes + _size.bytes, bits: _f.offset.bits }; + } else { + _f.offset = _f.offset + _size.bytes; + } + obj[subName] = _f; + }); + } else if (f.name) { + var localCopy = Object.create(f); + if ("width" in localCopy && typeof localCopy.width === "number") { + localCopy.offset = { bytes: _size.bytes, bits: _size.bits }; + } else { + localCopy.offset = _size.bytes; + } + obj[f.name] = localCopy; + } + addField(_size, f); + return obj; + } + var fieldsObj = fieldDefs.reduce(reduceFunc, {}); + if (_size.bits) { + throw Error("Improperly aligned bitfield at end of struct: " + (structName || "")); + } + var structField = { + unpack: function(buf, off) { + off = off || { bytes: 0, bits: 0 }; + var obj = {}; + fieldDefs.forEach(function(f) { + if ("_padTo" in f && f._id !== undefined) { + addField(off, _padsById[f._id]); + return; + } + var value2 = f.unpack(buf, off); + if (f.name) { + obj[f.name] = value2; + } else if (typeof value2 === "object") { + extend(obj, value2); + } + }); + return obj; + }, + pack: function(obj, buf, off) { + obj = obj || {}; + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0, bits: 0 }; + fieldDefs.forEach(function(f) { + if ("_padTo" in f && f._id !== undefined) { + addField(off, _padsById[f._id]); + return; + } + var value2 = f.name ? obj[f.name] : obj; + f.pack(value2, buf, off); + }); + return buf; + }, + _hoistFields: structName ? null : fieldsObj, + fields: fieldsObj, + size: _size.bytes, + name: structName + }; + return arrayizeField(structField, count); + }; + function truncatedReadUInt32(buffer, offset, littleEndian) { + var bytes = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : buffer; + var availableBytes = bytes.length - offset; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + if (availableBytes >= 4) { + return view.getUint32(offset, littleEndian); + } else if (availableBytes === 3) { + var first2 = view.getUint16(offset, littleEndian); + var second = view.getUint8(offset + 2); + return littleEndian ? (second << 16) + first2 >>> 0 : (first2 << 8) + second << 8 >>> 0; + } else if (availableBytes === 2) { + return view.getUint16(offset, littleEndian) << (littleEndian ? 0 : 16) >>> 0; + } else if (availableBytes === 1) { + return view.getUint8(offset) << (littleEndian ? 0 : 24) >>> 0; + } + return 0; + } + function truncatedWriteUInt32(buffer, offset, data2, littleEndian) { + var bytes = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : buffer; + var availableBytes = bytes.length - offset; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + if (availableBytes >= 4) { + view.setUint32(offset, data2, littleEndian); + } else if (availableBytes === 3) { + if (littleEndian) { + view.setUint8(offset, data2 & 255); + view.setUint16(offset + 1, data2 >>> 8, littleEndian); + } else { + view.setUint16(offset, data2 >>> 16, littleEndian); + view.setUint8(offset + 2, data2 >>> 8 & 255); + } + } else if (availableBytes === 2) { + view.setUint16(offset, littleEndian ? data2 & 65535 : data2 >>> 16, littleEndian); + } else if (availableBytes === 1) { + view.setUint8(offset, littleEndian ? data2 & 255 : data2 >>> 24); + } + } + _.padTo = function(off) { + var field = { + _padTo: off, + size: 0, + unpack: function() { + return null; + }, + pack: function() { + return newBuffer(0); + } + }; + return field; + }; + var FULL = 4294967295; + function bitfield(name2, width2, count) { + if (width2 === undefined) { + width2 = 1; + } + if (width2 > 24) { + throw Error("Bitfields support a maximum width of 24 bits."); + } + var mask2 = FULL >>> 32 - width2; + var littleEndian = this.littleEndian; + if (littleEndian) { + mask2 >>>= 0; + } + var impl = this; + return arrayizeField({ + unpack: function(buf, off) { + off = off || { bytes: 0, bits: 0 }; + var over; + var end; + var word; + if (littleEndian) { + end = off.bits || 0; + word = truncatedReadUInt32(buf, off.bytes, true) >>> 0; + over = word >>> end; + } else { + end = (off.bits || 0) + width2; + word = truncatedReadUInt32(buf, off.bytes, false) || 0; + over = word >>> 32 - end; + } + addField(off, this); + return impl.b2v.call(this, over & mask2); + }, + pack: function(val2, buf, off) { + val2 = impl.v2b.call(this, val2 || 0); + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0, bits: 0 }; + var word; + var zero; + var over; + if (littleEndian) { + word = truncatedReadUInt32(buf, off.bytes, true) >>> 0; + var shift = off.bits || 0; + zero = mask2 << shift >>> 0; + word &= ~zero; + over = (val2 & mask2) << shift; + word = (word | over) >>> 0; + truncatedWriteUInt32(buf, off.bytes, word, true); + } else { + var end = (off.bits || 0) + width2; + word = truncatedReadUInt32(buf, off.bytes, false) || 0; + zero = mask2 << 32 - end; + over = (val2 & mask2) << 32 - end; + word &= ~zero; + word = (word | over) >>> 0; + truncatedWriteUInt32(buf, off.bytes, word, false); + } + addField(off, this); + return new Uint8Array(buf); + }, + width: width2, + size: 0, + name: name2 + }, count); + } + _.bool = function(name2, count) { + return bitfield.call({ + b2v: function(b) { + return Boolean(b); + }, + v2b: function(v) { + return v ? FULL : 0; + } + }, name2, 1, count); + }; + _.ubit = bitfield.bind({ + b2v: function(b) { + return b; + }, + v2b: function(v) { + return Number(v); + } + }); + _.ubitLE = bitfield.bind({ + b2v: function(b) { + return b; + }, + v2b: function(v) { + return Number(v); + }, + littleEndian: true + }); + _.sbit = bitfield.bind({ + b2v: function(b) { + var m = 1 << (this.width || 1) - 1; + var s = b & m; + return s ? -(b &= ~m) : b; + }, + v2b: function(v) { + v = Number(v); + var m = 1 << (this.width || 1) - 1; + var s = v < 0; + return s ? -v | m : v; + } + }); + function bytefield(name2, size, count) { + var fieldName; + var fieldSize = 1; + if (typeof name2 === "string") { + fieldName = name2; + if (typeof size === "number") { + fieldSize = size; + } + } else { + fieldSize = name2; + count = size; + } + var impl = this; + return arrayizeField({ + name: fieldName, + size: fieldSize, + unpack: function(buf, off) { + off = off || { bytes: 0, bits: 0 }; + var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; + var val2 = bytes.subarray(off.bytes, off.bytes + this.size); + addField(off, this); + return impl.b2v.call(this, val2); + }, + pack: function(val2, buf, off) { + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0, bits: 0 }; + var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; + var blk = bytes.subarray(off.bytes, off.bytes + this.size); + impl.vTb.call(this, val2, blk); + addField(off, this); + return buf; + }, + b2v: function(b) { + return b; + }, + vTb: function(v, b) { + if (!v) + return 0; + var src = new Uint8Array(v); + b.set(src.subarray(0, b.length)); + return b.length; + } + }, count); + } + function swapBytesPairs(fromBuffer, toBuffer) { + toBuffer = toBuffer || fromBuffer; + var l = fromBuffer.length; + for (var i = 1;i < l; i += 2) { + var a = fromBuffer[i - 1]; + toBuffer[i - 1] = fromBuffer[i]; + toBuffer[i] = a; + } + return toBuffer; + } + _.byte = bytefield.bind({ + b2v: function(b) { + return new Uint8Array(b); + }, + vTb: function(v, b) { + if (!v) + return 0; + b.set(new Uint8Array(v)); + return v.byteLength; + } + }); + _.char = bytefield.bind({ + b2v: function(b) { + var decoder; + if (typeof _TextDecoder !== "undefined" && _TextDecoder) { + decoder = new _TextDecoder("utf-8"); + } else { + decoder = { + decode: function(buf) { + var bytes = new Uint8Array(buf); + var str = ""; + for (var i = 0;i < bytes.length; i++) { + str += String.fromCharCode(bytes[i]); + } + return str; + } + }; + } + var v = decoder.decode(b); + var z = v.indexOf("\x00"); + return ~z ? v.slice(0, z) : v; + }, + vTb: function(v, b) { + v || (v = ""); + var encoder; + if (typeof _TextEncoder !== "undefined" && _TextEncoder) { + encoder = new _TextEncoder; + } else { + encoder = { + encode: function(str) { + var arr = new Uint8Array(str.length); + for (var i2 = 0;i2 < str.length; i2++) { + arr[i2] = str.charCodeAt(i2) & 255; + } + return arr; + } + }; + } + var encoded = encoder.encode(v); + for (var i = 0;i < encoded.length && i < b.length; i++) { + b[i] = encoded[i]; + } + return encoded.length; + } + }); + _.char16le = bytefield.bind({ + b2v: function(b) { + var decoder; + if (typeof _TextDecoder !== "undefined" && _TextDecoder) { + decoder = new _TextDecoder("utf-16le"); + } else { + decoder = { + decode: function(buf) { + var bytes = new Uint8Array(buf); + var str = ""; + for (var i = 0;i < bytes.length; i += 2) { + var charCode = bytes[i] | bytes[i + 1] << 8; + str += String.fromCharCode(charCode); + } + return str; + } + }; + } + var v = decoder.decode(b); + var z = v.indexOf("\x00"); + return ~z ? v.slice(0, z) : v; + }, + vTb: function(v, b) { + v || (v = ""); + var bytesWritten = 0; + for (var i = 0;i < v.length && bytesWritten + 1 < b.length; i++) { + var charCode = v.charCodeAt(i); + b[bytesWritten++] = charCode & 255; + b[bytesWritten++] = charCode >> 8 & 255; + } + return bytesWritten; + } + }); + _.char16be = bytefield.bind({ + b2v: function(b) { + var temp = new Uint8Array(b); + swapBytesPairs(temp); + var decoder; + if (typeof _TextDecoder !== "undefined" && _TextDecoder) { + decoder = new _TextDecoder("utf-16le"); + } else { + decoder = { + decode: function(buf) { + var bytes = new Uint8Array(buf); + var str = ""; + for (var i = 0;i < bytes.length; i += 2) { + var charCode = bytes[i] | bytes[i + 1] << 8; + str += String.fromCharCode(charCode); + } + return str; + } + }; + } + var v = decoder.decode(temp.buffer); + var z = v.indexOf("\x00"); + return ~z ? v.slice(0, z) : v; + }, + vTb: function(v, b) { + v || (v = ""); + var temp = new Uint8Array(b.length); + var bytesWritten = 0; + for (var i = 0;i < v.length && bytesWritten + 1 < temp.length; i++) { + var charCode = v.charCodeAt(i); + temp[bytesWritten++] = charCode & 255; + temp[bytesWritten++] = charCode >> 8 & 255; + } + swapBytesPairs(temp, b); + return bytesWritten; + } + }); + function dataViewField(getFn, setFn, size, littleEndian) { + var func = function(name2, count) { + var fieldName; + if (typeof name2 === "string") { + fieldName = name2; + } else { + count = name2; + } + return arrayizeField({ + name: fieldName, + size, + unpack: function(buf, off) { + off = off || { bytes: 0 }; + var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + var val2 = getFn.call(view, off.bytes, littleEndian); + addField(off, this); + return val2; + }, + pack: function(val2, buf, off) { + if (val2 === undefined || val2 === null) { + val2 = 0; + } + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0 }; + var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + setFn.call(view, off.bytes, val2, littleEndian); + addField(off, this); + return new Uint8Array(buf); + } + }, count); + }; + return func; + } + var DV = DataView.prototype; + _.uint8 = dataViewField(DV.getUint8, DV.setUint8, 1, false); + _.uint16 = dataViewField(DV.getUint16, DV.setUint16, 2, false); + _.uint32 = dataViewField(DV.getUint32, DV.setUint32, 4, false); + _.uint16le = dataViewField(DV.getUint16, DV.setUint16, 2, true); + _.uint32le = dataViewField(DV.getUint32, DV.setUint32, 4, true); + _.int8 = dataViewField(DV.getInt8, DV.setInt8, 1, false); + _.int16 = dataViewField(DV.getInt16, DV.setInt16, 2, false); + _.int32 = dataViewField(DV.getInt32, DV.setInt32, 4, false); + _.int16le = dataViewField(DV.getInt16, DV.setInt16, 2, true); + _.int32le = dataViewField(DV.getInt32, DV.setInt32, 4, true); + _.float32 = dataViewField(DV.getFloat32, DV.setFloat32, 4, false); + _.float64 = dataViewField(DV.getFloat64, DV.setFloat64, 8, false); + _.float32le = dataViewField(DV.getFloat32, DV.setFloat32, 4, true); + _.float64le = dataViewField(DV.getFloat64, DV.setFloat64, 8, true); + _.derive = function(orig, pack, unpack) { + var func = function(name2, count) { + var fieldName = null; + if (typeof name2 === "string") { + fieldName = name2; + } else { + count = name2; + } + var derived = extend({ + unpack: function(buf, off) { + var rawVal = orig.unpack(buf, off); + return unpack(rawVal); + }, + pack: function(val2, buf, off) { + var packed = pack(val2); + return orig.pack(packed, buf, off); + }, + name: fieldName + }, "width" in orig ? { width: orig.width } : { size: orig.size }); + return arrayizeField(derived, count); + }; + return func; + }; + return _; + }); +}); + +// node:stream +var exports_stream = {}; +__export(exports_stream, { + default: () => Uc +}); +var al, tt, cl, dl, hl, pl, yl = (e, t) => () => (e && (t = e(e = 0)), t), E = (e, t) => () => (t || e((t = { exports: {} }).exports, t), t.exports), Qr = (e, t) => { + for (var r in t) + tt(e, r, { get: t[r], enumerable: true }); +}, et = (e, t, r, n) => { + if (t && typeof t == "object" || typeof t == "function") + for (let i of dl(t)) + !pl.call(e, i) && i !== r && tt(e, i, { get: () => t[i], enumerable: !(n = cl(t, i)) || n.enumerable }); + return e; +}, ue = (e, t, r) => (et(e, t, "default"), r && et(r, t, "default")), rt = (e, t, r) => (r = e != null ? al(hl(e)) : {}, et(t || !e || !e.__esModule ? tt(r, "default", { value: e, enumerable: true }) : r, e)), pe = (e) => et(tt({}, "__esModule", { value: true }), e), tn, rn, te, I, V, ut, C, He, ir, k, Gu, se, ae, ce, di, Se, Et, xt, At, Pi, Tt, Wi, Gi, Er, Ke, Cr, Mo, J, qr, $r, Ut, Jo, Kr, fl, Jr, Ze, Uc; +var init_stream = __esm(() => { + al = Object.create; + tt = Object.defineProperty; + cl = Object.getOwnPropertyDescriptor; + dl = Object.getOwnPropertyNames; + hl = Object.getPrototypeOf; + pl = Object.prototype.hasOwnProperty; + tn = E((nt) => { + nt.byteLength = bl; + nt.toByteArray = _l; + nt.fromByteArray = ml; + var G = [], P = [], wl = typeof Uint8Array < "u" ? Uint8Array : Array, Wt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (ye = 0, Zr = Wt.length;ye < Zr; ++ye) + G[ye] = Wt[ye], P[Wt.charCodeAt(ye)] = ye; + var ye, Zr; + P[45] = 62; + P[95] = 63; + function en(e) { + var t = e.length; + if (t % 4 > 0) + throw new Error("Invalid string. Length must be a multiple of 4"); + var r = e.indexOf("="); + r === -1 && (r = t); + var n = r === t ? 0 : 4 - r % 4; + return [r, n]; + } + function bl(e) { + var t = en(e), r = t[0], n = t[1]; + return (r + n) * 3 / 4 - n; + } + function gl(e, t, r) { + return (t + r) * 3 / 4 - r; + } + function _l(e) { + var t, r = en(e), n = r[0], i = r[1], o = new wl(gl(e, n, i)), l = 0, u = i > 0 ? n - 4 : n, f; + for (f = 0;f < u; f += 4) + t = P[e.charCodeAt(f)] << 18 | P[e.charCodeAt(f + 1)] << 12 | P[e.charCodeAt(f + 2)] << 6 | P[e.charCodeAt(f + 3)], o[l++] = t >> 16 & 255, o[l++] = t >> 8 & 255, o[l++] = t & 255; + return i === 2 && (t = P[e.charCodeAt(f)] << 2 | P[e.charCodeAt(f + 1)] >> 4, o[l++] = t & 255), i === 1 && (t = P[e.charCodeAt(f)] << 10 | P[e.charCodeAt(f + 1)] << 4 | P[e.charCodeAt(f + 2)] >> 2, o[l++] = t >> 8 & 255, o[l++] = t & 255), o; + } + function El(e) { + return G[e >> 18 & 63] + G[e >> 12 & 63] + G[e >> 6 & 63] + G[e & 63]; + } + function Sl(e, t, r) { + for (var n, i = [], o = t;o < r; o += 3) + n = (e[o] << 16 & 16711680) + (e[o + 1] << 8 & 65280) + (e[o + 2] & 255), i.push(El(n)); + return i.join(""); + } + function ml(e) { + for (var t, r = e.length, n = r % 3, i = [], o = 16383, l = 0, u = r - n;l < u; l += o) + i.push(Sl(e, l, l + o > u ? u : l + o)); + return n === 1 ? (t = e[r - 1], i.push(G[t >> 2] + G[t << 4 & 63] + "==")) : n === 2 && (t = (e[r - 2] << 8) + e[r - 1], i.push(G[t >> 10] + G[t >> 4 & 63] + G[t << 2 & 63] + "=")), i.join(""); + } + }); + rn = E(($t) => { + $t.read = function(e, t, r, n, i) { + var o, l, u = i * 8 - n - 1, f = (1 << u) - 1, s = f >> 1, d = -7, c = r ? i - 1 : 0, y = r ? -1 : 1, h = e[t + c]; + for (c += y, o = h & (1 << -d) - 1, h >>= -d, d += u;d > 0; o = o * 256 + e[t + c], c += y, d -= 8) + ; + for (l = o & (1 << -d) - 1, o >>= -d, d += n;d > 0; l = l * 256 + e[t + c], c += y, d -= 8) + ; + if (o === 0) + o = 1 - s; + else { + if (o === f) + return l ? NaN : (h ? -1 : 1) * (1 / 0); + l = l + Math.pow(2, n), o = o - s; + } + return (h ? -1 : 1) * l * Math.pow(2, o - n); + }; + $t.write = function(e, t, r, n, i, o) { + var l, u, f, s = o * 8 - i - 1, d = (1 << s) - 1, c = d >> 1, y = i === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, h = n ? 0 : o - 1, p = n ? 1 : -1, B = t < 0 || t === 0 && 1 / t < 0 ? 1 : 0; + for (t = Math.abs(t), isNaN(t) || t === 1 / 0 ? (u = isNaN(t) ? 1 : 0, l = d) : (l = Math.floor(Math.log(t) / Math.LN2), t * (f = Math.pow(2, -l)) < 1 && (l--, f *= 2), l + c >= 1 ? t += y / f : t += y * Math.pow(2, 1 - c), t * f >= 2 && (l++, f /= 2), l + c >= d ? (u = 0, l = d) : l + c >= 1 ? (u = (t * f - 1) * Math.pow(2, i), l = l + c) : (u = t * Math.pow(2, c - 1) * Math.pow(2, i), l = 0));i >= 8; e[r + h] = u & 255, h += p, u /= 256, i -= 8) + ; + for (l = l << i | u, s += i;s > 0; e[r + h] = l & 255, h += p, l /= 256, s -= 8) + ; + e[r + h - p] |= B * 128; + }; + }); + te = E((Fe) => { + var jt = tn(), Le = rn(), nn = typeof Symbol == "function" && typeof Symbol.for == "function" ? Symbol.for("nodejs.util.inspect.custom") : null; + Fe.Buffer = a; + Fe.SlowBuffer = Bl; + Fe.INSPECT_MAX_BYTES = 50; + var it = 2147483647; + Fe.kMaxLength = it; + a.TYPED_ARRAY_SUPPORT = xl(); + !a.TYPED_ARRAY_SUPPORT && typeof console < "u" && typeof console.error == "function" && console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."); + function xl() { + try { + let e = new Uint8Array(1), t = { foo: function() { + return 42; + } }; + return Object.setPrototypeOf(t, Uint8Array.prototype), Object.setPrototypeOf(e, t), e.foo() === 42; + } catch { + return false; + } + } + Object.defineProperty(a.prototype, "parent", { enumerable: true, get: function() { + if (!!a.isBuffer(this)) + return this.buffer; + } }); + Object.defineProperty(a.prototype, "offset", { enumerable: true, get: function() { + if (!!a.isBuffer(this)) + return this.byteOffset; + } }); + function ee(e) { + if (e > it) + throw new RangeError('The value "' + e + '" is invalid for option "size"'); + let t = new Uint8Array(e); + return Object.setPrototypeOf(t, a.prototype), t; + } + function a(e, t, r) { + if (typeof e == "number") { + if (typeof t == "string") + throw new TypeError('The "string" argument must be of type string. Received type number'); + return Yt(e); + } + return fn(e, t, r); + } + a.poolSize = 8192; + function fn(e, t, r) { + if (typeof e == "string") + return Al(e, t); + if (ArrayBuffer.isView(e)) + return Il(e); + if (e == null) + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e); + if (H(e, ArrayBuffer) || e && H(e.buffer, ArrayBuffer) || typeof SharedArrayBuffer < "u" && (H(e, SharedArrayBuffer) || e && H(e.buffer, SharedArrayBuffer))) + return Ht(e, t, r); + if (typeof e == "number") + throw new TypeError('The "value" argument must not be of type number. Received type number'); + let n = e.valueOf && e.valueOf(); + if (n != null && n !== e) + return a.from(n, t, r); + let i = Tl(e); + if (i) + return i; + if (typeof Symbol < "u" && Symbol.toPrimitive != null && typeof e[Symbol.toPrimitive] == "function") + return a.from(e[Symbol.toPrimitive]("string"), t, r); + throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e); + } + a.from = function(e, t, r) { + return fn(e, t, r); + }; + Object.setPrototypeOf(a.prototype, Uint8Array.prototype); + Object.setPrototypeOf(a, Uint8Array); + function sn(e) { + if (typeof e != "number") + throw new TypeError('"size" argument must be of type number'); + if (e < 0) + throw new RangeError('The value "' + e + '" is invalid for option "size"'); + } + function Rl(e, t, r) { + return sn(e), e <= 0 ? ee(e) : t !== undefined ? typeof r == "string" ? ee(e).fill(t, r) : ee(e).fill(t) : ee(e); + } + a.alloc = function(e, t, r) { + return Rl(e, t, r); + }; + function Yt(e) { + return sn(e), ee(e < 0 ? 0 : Kt(e) | 0); + } + a.allocUnsafe = function(e) { + return Yt(e); + }; + a.allocUnsafeSlow = function(e) { + return Yt(e); + }; + function Al(e, t) { + if ((typeof t != "string" || t === "") && (t = "utf8"), !a.isEncoding(t)) + throw new TypeError("Unknown encoding: " + t); + let r = an(e, t) | 0, n = ee(r), i = n.write(e, t); + return i !== r && (n = n.slice(0, i)), n; + } + function Gt(e) { + let t = e.length < 0 ? 0 : Kt(e.length) | 0, r = ee(t); + for (let n = 0;n < t; n += 1) + r[n] = e[n] & 255; + return r; + } + function Il(e) { + if (H(e, Uint8Array)) { + let t = new Uint8Array(e); + return Ht(t.buffer, t.byteOffset, t.byteLength); + } + return Gt(e); + } + function Ht(e, t, r) { + if (t < 0 || e.byteLength < t) + throw new RangeError('"offset" is outside of buffer bounds'); + if (e.byteLength < t + (r || 0)) + throw new RangeError('"length" is outside of buffer bounds'); + let n; + return t === undefined && r === undefined ? n = new Uint8Array(e) : r === undefined ? n = new Uint8Array(e, t) : n = new Uint8Array(e, t, r), Object.setPrototypeOf(n, a.prototype), n; + } + function Tl(e) { + if (a.isBuffer(e)) { + let t = Kt(e.length) | 0, r = ee(t); + return r.length === 0 || e.copy(r, 0, 0, t), r; + } + if (e.length !== undefined) + return typeof e.length != "number" || Xt(e.length) ? ee(0) : Gt(e); + if (e.type === "Buffer" && Array.isArray(e.data)) + return Gt(e.data); + } + function Kt(e) { + if (e >= it) + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + it.toString(16) + " bytes"); + return e | 0; + } + function Bl(e) { + return +e != e && (e = 0), a.alloc(+e); + } + a.isBuffer = function(t) { + return t != null && t._isBuffer === true && t !== a.prototype; + }; + a.compare = function(t, r) { + if (H(t, Uint8Array) && (t = a.from(t, t.offset, t.byteLength)), H(r, Uint8Array) && (r = a.from(r, r.offset, r.byteLength)), !a.isBuffer(t) || !a.isBuffer(r)) + throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'); + if (t === r) + return 0; + let n = t.length, i = r.length; + for (let o = 0, l = Math.min(n, i);o < l; ++o) + if (t[o] !== r[o]) { + n = t[o], i = r[o]; + break; + } + return n < i ? -1 : i < n ? 1 : 0; + }; + a.isEncoding = function(t) { + switch (String(t).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } + }; + a.concat = function(t, r) { + if (!Array.isArray(t)) + throw new TypeError('"list" argument must be an Array of Buffers'); + if (t.length === 0) + return a.alloc(0); + let n; + if (r === undefined) + for (r = 0, n = 0;n < t.length; ++n) + r += t[n].length; + let i = a.allocUnsafe(r), o = 0; + for (n = 0;n < t.length; ++n) { + let l = t[n]; + if (H(l, Uint8Array)) + o + l.length > i.length ? (a.isBuffer(l) || (l = a.from(l)), l.copy(i, o)) : Uint8Array.prototype.set.call(i, l, o); + else if (a.isBuffer(l)) + l.copy(i, o); + else + throw new TypeError('"list" argument must be an Array of Buffers'); + o += l.length; + } + return i; + }; + function an(e, t) { + if (a.isBuffer(e)) + return e.length; + if (ArrayBuffer.isView(e) || H(e, ArrayBuffer)) + return e.byteLength; + if (typeof e != "string") + throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof e); + let r = e.length, n = arguments.length > 2 && arguments[2] === true; + if (!n && r === 0) + return 0; + let i = false; + for (;; ) + switch (t) { + case "ascii": + case "latin1": + case "binary": + return r; + case "utf8": + case "utf-8": + return Vt(e).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return r * 2; + case "hex": + return r >>> 1; + case "base64": + return _n(e).length; + default: + if (i) + return n ? -1 : Vt(e).length; + t = ("" + t).toLowerCase(), i = true; + } + } + a.byteLength = an; + function Ll(e, t, r) { + let n = false; + if ((t === undefined || t < 0) && (t = 0), t > this.length || ((r === undefined || r > this.length) && (r = this.length), r <= 0) || (r >>>= 0, t >>>= 0, r <= t)) + return ""; + for (e || (e = "utf8");; ) + switch (e) { + case "hex": + return vl(this, t, r); + case "utf8": + case "utf-8": + return dn(this, t, r); + case "ascii": + return kl(this, t, r); + case "latin1": + case "binary": + return Ul(this, t, r); + case "base64": + return Dl(this, t, r); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ql(this, t, r); + default: + if (n) + throw new TypeError("Unknown encoding: " + e); + e = (e + "").toLowerCase(), n = true; + } + } + a.prototype._isBuffer = true; + function we(e, t, r) { + let n = e[t]; + e[t] = e[r], e[r] = n; + } + a.prototype.swap16 = function() { + let t = this.length; + if (t % 2 !== 0) + throw new RangeError("Buffer size must be a multiple of 16-bits"); + for (let r = 0;r < t; r += 2) + we(this, r, r + 1); + return this; + }; + a.prototype.swap32 = function() { + let t = this.length; + if (t % 4 !== 0) + throw new RangeError("Buffer size must be a multiple of 32-bits"); + for (let r = 0;r < t; r += 4) + we(this, r, r + 3), we(this, r + 1, r + 2); + return this; + }; + a.prototype.swap64 = function() { + let t = this.length; + if (t % 8 !== 0) + throw new RangeError("Buffer size must be a multiple of 64-bits"); + for (let r = 0;r < t; r += 8) + we(this, r, r + 7), we(this, r + 1, r + 6), we(this, r + 2, r + 5), we(this, r + 3, r + 4); + return this; + }; + a.prototype.toString = function() { + let t = this.length; + return t === 0 ? "" : arguments.length === 0 ? dn(this, 0, t) : Ll.apply(this, arguments); + }; + a.prototype.toLocaleString = a.prototype.toString; + a.prototype.equals = function(t) { + if (!a.isBuffer(t)) + throw new TypeError("Argument must be a Buffer"); + return this === t ? true : a.compare(this, t) === 0; + }; + a.prototype.inspect = function() { + let t = "", r = Fe.INSPECT_MAX_BYTES; + return t = this.toString("hex", 0, r).replace(/(.{2})/g, "$1 ").trim(), this.length > r && (t += " ... "), ""; + }; + nn && (a.prototype[nn] = a.prototype.inspect); + a.prototype.compare = function(t, r, n, i, o) { + if (H(t, Uint8Array) && (t = a.from(t, t.offset, t.byteLength)), !a.isBuffer(t)) + throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof t); + if (r === undefined && (r = 0), n === undefined && (n = t ? t.length : 0), i === undefined && (i = 0), o === undefined && (o = this.length), r < 0 || n > t.length || i < 0 || o > this.length) + throw new RangeError("out of range index"); + if (i >= o && r >= n) + return 0; + if (i >= o) + return -1; + if (r >= n) + return 1; + if (r >>>= 0, n >>>= 0, i >>>= 0, o >>>= 0, this === t) + return 0; + let l = o - i, u = n - r, f = Math.min(l, u), s = this.slice(i, o), d = t.slice(r, n); + for (let c = 0;c < f; ++c) + if (s[c] !== d[c]) { + l = s[c], u = d[c]; + break; + } + return l < u ? -1 : u < l ? 1 : 0; + }; + function cn(e, t, r, n, i) { + if (e.length === 0) + return -1; + if (typeof r == "string" ? (n = r, r = 0) : r > 2147483647 ? r = 2147483647 : r < -2147483648 && (r = -2147483648), r = +r, Xt(r) && (r = i ? 0 : e.length - 1), r < 0 && (r = e.length + r), r >= e.length) { + if (i) + return -1; + r = e.length - 1; + } else if (r < 0) + if (i) + r = 0; + else + return -1; + if (typeof t == "string" && (t = a.from(t, n)), a.isBuffer(t)) + return t.length === 0 ? -1 : on(e, t, r, n, i); + if (typeof t == "number") + return t = t & 255, typeof Uint8Array.prototype.indexOf == "function" ? i ? Uint8Array.prototype.indexOf.call(e, t, r) : Uint8Array.prototype.lastIndexOf.call(e, t, r) : on(e, [t], r, n, i); + throw new TypeError("val must be string, number or Buffer"); + } + function on(e, t, r, n, i) { + let o = 1, l = e.length, u = t.length; + if (n !== undefined && (n = String(n).toLowerCase(), n === "ucs2" || n === "ucs-2" || n === "utf16le" || n === "utf-16le")) { + if (e.length < 2 || t.length < 2) + return -1; + o = 2, l /= 2, u /= 2, r /= 2; + } + function f(d, c) { + return o === 1 ? d[c] : d.readUInt16BE(c * o); + } + let s; + if (i) { + let d = -1; + for (s = r;s < l; s++) + if (f(e, s) === f(t, d === -1 ? 0 : s - d)) { + if (d === -1 && (d = s), s - d + 1 === u) + return d * o; + } else + d !== -1 && (s -= s - d), d = -1; + } else + for (r + u > l && (r = l - u), s = r;s >= 0; s--) { + let d = true; + for (let c = 0;c < u; c++) + if (f(e, s + c) !== f(t, c)) { + d = false; + break; + } + if (d) + return s; + } + return -1; + } + a.prototype.includes = function(t, r, n) { + return this.indexOf(t, r, n) !== -1; + }; + a.prototype.indexOf = function(t, r, n) { + return cn(this, t, r, n, true); + }; + a.prototype.lastIndexOf = function(t, r, n) { + return cn(this, t, r, n, false); + }; + function Nl(e, t, r, n) { + r = Number(r) || 0; + let i = e.length - r; + n ? (n = Number(n), n > i && (n = i)) : n = i; + let o = t.length; + n > o / 2 && (n = o / 2); + let l; + for (l = 0;l < n; ++l) { + let u = parseInt(t.substr(l * 2, 2), 16); + if (Xt(u)) + return l; + e[r + l] = u; + } + return l; + } + function Fl(e, t, r, n) { + return ot(Vt(t, e.length - r), e, r, n); + } + function Ml(e, t, r, n) { + return ot(Gl(t), e, r, n); + } + function Cl(e, t, r, n) { + return ot(_n(t), e, r, n); + } + function Ol(e, t, r, n) { + return ot(Hl(t, e.length - r), e, r, n); + } + a.prototype.write = function(t, r, n, i) { + if (r === undefined) + i = "utf8", n = this.length, r = 0; + else if (n === undefined && typeof r == "string") + i = r, n = this.length, r = 0; + else if (isFinite(r)) + r = r >>> 0, isFinite(n) ? (n = n >>> 0, i === undefined && (i = "utf8")) : (i = n, n = undefined); + else + throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported"); + let o = this.length - r; + if ((n === undefined || n > o) && (n = o), t.length > 0 && (n < 0 || r < 0) || r > this.length) + throw new RangeError("Attempt to write outside buffer bounds"); + i || (i = "utf8"); + let l = false; + for (;; ) + switch (i) { + case "hex": + return Nl(this, t, r, n); + case "utf8": + case "utf-8": + return Fl(this, t, r, n); + case "ascii": + case "latin1": + case "binary": + return Ml(this, t, r, n); + case "base64": + return Cl(this, t, r, n); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return Ol(this, t, r, n); + default: + if (l) + throw new TypeError("Unknown encoding: " + i); + i = ("" + i).toLowerCase(), l = true; + } + }; + a.prototype.toJSON = function() { + return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) }; + }; + function Dl(e, t, r) { + return t === 0 && r === e.length ? jt.fromByteArray(e) : jt.fromByteArray(e.slice(t, r)); + } + function dn(e, t, r) { + r = Math.min(e.length, r); + let n = [], i = t; + for (;i < r; ) { + let o = e[i], l = null, u = o > 239 ? 4 : o > 223 ? 3 : o > 191 ? 2 : 1; + if (i + u <= r) { + let f, s, d, c; + switch (u) { + case 1: + o < 128 && (l = o); + break; + case 2: + f = e[i + 1], (f & 192) === 128 && (c = (o & 31) << 6 | f & 63, c > 127 && (l = c)); + break; + case 3: + f = e[i + 1], s = e[i + 2], (f & 192) === 128 && (s & 192) === 128 && (c = (o & 15) << 12 | (f & 63) << 6 | s & 63, c > 2047 && (c < 55296 || c > 57343) && (l = c)); + break; + case 4: + f = e[i + 1], s = e[i + 2], d = e[i + 3], (f & 192) === 128 && (s & 192) === 128 && (d & 192) === 128 && (c = (o & 15) << 18 | (f & 63) << 12 | (s & 63) << 6 | d & 63, c > 65535 && c < 1114112 && (l = c)); + } + } + l === null ? (l = 65533, u = 1) : l > 65535 && (l -= 65536, n.push(l >>> 10 & 1023 | 55296), l = 56320 | l & 1023), n.push(l), i += u; + } + return Pl(n); + } + var ln = 4096; + function Pl(e) { + let t = e.length; + if (t <= ln) + return String.fromCharCode.apply(String, e); + let r = "", n = 0; + for (;n < t; ) + r += String.fromCharCode.apply(String, e.slice(n, n += ln)); + return r; + } + function kl(e, t, r) { + let n = ""; + r = Math.min(e.length, r); + for (let i = t;i < r; ++i) + n += String.fromCharCode(e[i] & 127); + return n; + } + function Ul(e, t, r) { + let n = ""; + r = Math.min(e.length, r); + for (let i = t;i < r; ++i) + n += String.fromCharCode(e[i]); + return n; + } + function vl(e, t, r) { + let n = e.length; + (!t || t < 0) && (t = 0), (!r || r < 0 || r > n) && (r = n); + let i = ""; + for (let o = t;o < r; ++o) + i += Vl[e[o]]; + return i; + } + function ql(e, t, r) { + let n = e.slice(t, r), i = ""; + for (let o = 0;o < n.length - 1; o += 2) + i += String.fromCharCode(n[o] + n[o + 1] * 256); + return i; + } + a.prototype.slice = function(t, r) { + let n = this.length; + t = ~~t, r = r === undefined ? n : ~~r, t < 0 ? (t += n, t < 0 && (t = 0)) : t > n && (t = n), r < 0 ? (r += n, r < 0 && (r = 0)) : r > n && (r = n), r < t && (r = t); + let i = this.subarray(t, r); + return Object.setPrototypeOf(i, a.prototype), i; + }; + function F(e, t, r) { + if (e % 1 !== 0 || e < 0) + throw new RangeError("offset is not uint"); + if (e + t > r) + throw new RangeError("Trying to access beyond buffer length"); + } + a.prototype.readUintLE = a.prototype.readUIntLE = function(t, r, n) { + t = t >>> 0, r = r >>> 0, n || F(t, r, this.length); + let i = this[t], o = 1, l = 0; + for (;++l < r && (o *= 256); ) + i += this[t + l] * o; + return i; + }; + a.prototype.readUintBE = a.prototype.readUIntBE = function(t, r, n) { + t = t >>> 0, r = r >>> 0, n || F(t, r, this.length); + let i = this[t + --r], o = 1; + for (;r > 0 && (o *= 256); ) + i += this[t + --r] * o; + return i; + }; + a.prototype.readUint8 = a.prototype.readUInt8 = function(t, r) { + return t = t >>> 0, r || F(t, 1, this.length), this[t]; + }; + a.prototype.readUint16LE = a.prototype.readUInt16LE = function(t, r) { + return t = t >>> 0, r || F(t, 2, this.length), this[t] | this[t + 1] << 8; + }; + a.prototype.readUint16BE = a.prototype.readUInt16BE = function(t, r) { + return t = t >>> 0, r || F(t, 2, this.length), this[t] << 8 | this[t + 1]; + }; + a.prototype.readUint32LE = a.prototype.readUInt32LE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), (this[t] | this[t + 1] << 8 | this[t + 2] << 16) + this[t + 3] * 16777216; + }; + a.prototype.readUint32BE = a.prototype.readUInt32BE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), this[t] * 16777216 + (this[t + 1] << 16 | this[t + 2] << 8 | this[t + 3]); + }; + a.prototype.readBigUInt64LE = fe(function(t) { + t = t >>> 0, Ne(t, "offset"); + let r = this[t], n = this[t + 7]; + (r === undefined || n === undefined) && Ge(t, this.length - 8); + let i = r + this[++t] * 2 ** 8 + this[++t] * 2 ** 16 + this[++t] * 2 ** 24, o = this[++t] + this[++t] * 2 ** 8 + this[++t] * 2 ** 16 + n * 2 ** 24; + return BigInt(i) + (BigInt(o) << BigInt(32)); + }); + a.prototype.readBigUInt64BE = fe(function(t) { + t = t >>> 0, Ne(t, "offset"); + let r = this[t], n = this[t + 7]; + (r === undefined || n === undefined) && Ge(t, this.length - 8); + let i = r * 2 ** 24 + this[++t] * 2 ** 16 + this[++t] * 2 ** 8 + this[++t], o = this[++t] * 2 ** 24 + this[++t] * 2 ** 16 + this[++t] * 2 ** 8 + n; + return (BigInt(i) << BigInt(32)) + BigInt(o); + }); + a.prototype.readIntLE = function(t, r, n) { + t = t >>> 0, r = r >>> 0, n || F(t, r, this.length); + let i = this[t], o = 1, l = 0; + for (;++l < r && (o *= 256); ) + i += this[t + l] * o; + return o *= 128, i >= o && (i -= Math.pow(2, 8 * r)), i; + }; + a.prototype.readIntBE = function(t, r, n) { + t = t >>> 0, r = r >>> 0, n || F(t, r, this.length); + let i = r, o = 1, l = this[t + --i]; + for (;i > 0 && (o *= 256); ) + l += this[t + --i] * o; + return o *= 128, l >= o && (l -= Math.pow(2, 8 * r)), l; + }; + a.prototype.readInt8 = function(t, r) { + return t = t >>> 0, r || F(t, 1, this.length), this[t] & 128 ? (255 - this[t] + 1) * -1 : this[t]; + }; + a.prototype.readInt16LE = function(t, r) { + t = t >>> 0, r || F(t, 2, this.length); + let n = this[t] | this[t + 1] << 8; + return n & 32768 ? n | 4294901760 : n; + }; + a.prototype.readInt16BE = function(t, r) { + t = t >>> 0, r || F(t, 2, this.length); + let n = this[t + 1] | this[t] << 8; + return n & 32768 ? n | 4294901760 : n; + }; + a.prototype.readInt32LE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), this[t] | this[t + 1] << 8 | this[t + 2] << 16 | this[t + 3] << 24; + }; + a.prototype.readInt32BE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), this[t] << 24 | this[t + 1] << 16 | this[t + 2] << 8 | this[t + 3]; + }; + a.prototype.readBigInt64LE = fe(function(t) { + t = t >>> 0, Ne(t, "offset"); + let r = this[t], n = this[t + 7]; + (r === undefined || n === undefined) && Ge(t, this.length - 8); + let i = this[t + 4] + this[t + 5] * 2 ** 8 + this[t + 6] * 2 ** 16 + (n << 24); + return (BigInt(i) << BigInt(32)) + BigInt(r + this[++t] * 2 ** 8 + this[++t] * 2 ** 16 + this[++t] * 2 ** 24); + }); + a.prototype.readBigInt64BE = fe(function(t) { + t = t >>> 0, Ne(t, "offset"); + let r = this[t], n = this[t + 7]; + (r === undefined || n === undefined) && Ge(t, this.length - 8); + let i = (r << 24) + this[++t] * 2 ** 16 + this[++t] * 2 ** 8 + this[++t]; + return (BigInt(i) << BigInt(32)) + BigInt(this[++t] * 2 ** 24 + this[++t] * 2 ** 16 + this[++t] * 2 ** 8 + n); + }); + a.prototype.readFloatLE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), Le.read(this, t, true, 23, 4); + }; + a.prototype.readFloatBE = function(t, r) { + return t = t >>> 0, r || F(t, 4, this.length), Le.read(this, t, false, 23, 4); + }; + a.prototype.readDoubleLE = function(t, r) { + return t = t >>> 0, r || F(t, 8, this.length), Le.read(this, t, true, 52, 8); + }; + a.prototype.readDoubleBE = function(t, r) { + return t = t >>> 0, r || F(t, 8, this.length), Le.read(this, t, false, 52, 8); + }; + function O(e, t, r, n, i, o) { + if (!a.isBuffer(e)) + throw new TypeError('"buffer" argument must be a Buffer instance'); + if (t > i || t < o) + throw new RangeError('"value" argument is out of bounds'); + if (r + n > e.length) + throw new RangeError("Index out of range"); + } + a.prototype.writeUintLE = a.prototype.writeUIntLE = function(t, r, n, i) { + if (t = +t, r = r >>> 0, n = n >>> 0, !i) { + let u = Math.pow(2, 8 * n) - 1; + O(this, t, r, n, u, 0); + } + let o = 1, l = 0; + for (this[r] = t & 255;++l < n && (o *= 256); ) + this[r + l] = t / o & 255; + return r + n; + }; + a.prototype.writeUintBE = a.prototype.writeUIntBE = function(t, r, n, i) { + if (t = +t, r = r >>> 0, n = n >>> 0, !i) { + let u = Math.pow(2, 8 * n) - 1; + O(this, t, r, n, u, 0); + } + let o = n - 1, l = 1; + for (this[r + o] = t & 255;--o >= 0 && (l *= 256); ) + this[r + o] = t / l & 255; + return r + n; + }; + a.prototype.writeUint8 = a.prototype.writeUInt8 = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 1, 255, 0), this[r] = t & 255, r + 1; + }; + a.prototype.writeUint16LE = a.prototype.writeUInt16LE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 2, 65535, 0), this[r] = t & 255, this[r + 1] = t >>> 8, r + 2; + }; + a.prototype.writeUint16BE = a.prototype.writeUInt16BE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 2, 65535, 0), this[r] = t >>> 8, this[r + 1] = t & 255, r + 2; + }; + a.prototype.writeUint32LE = a.prototype.writeUInt32LE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 4, 4294967295, 0), this[r + 3] = t >>> 24, this[r + 2] = t >>> 16, this[r + 1] = t >>> 8, this[r] = t & 255, r + 4; + }; + a.prototype.writeUint32BE = a.prototype.writeUInt32BE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 4, 4294967295, 0), this[r] = t >>> 24, this[r + 1] = t >>> 16, this[r + 2] = t >>> 8, this[r + 3] = t & 255, r + 4; + }; + function hn(e, t, r, n, i) { + gn(t, n, i, e, r, 7); + let o = Number(t & BigInt(4294967295)); + e[r++] = o, o = o >> 8, e[r++] = o, o = o >> 8, e[r++] = o, o = o >> 8, e[r++] = o; + let l = Number(t >> BigInt(32) & BigInt(4294967295)); + return e[r++] = l, l = l >> 8, e[r++] = l, l = l >> 8, e[r++] = l, l = l >> 8, e[r++] = l, r; + } + function pn(e, t, r, n, i) { + gn(t, n, i, e, r, 7); + let o = Number(t & BigInt(4294967295)); + e[r + 7] = o, o = o >> 8, e[r + 6] = o, o = o >> 8, e[r + 5] = o, o = o >> 8, e[r + 4] = o; + let l = Number(t >> BigInt(32) & BigInt(4294967295)); + return e[r + 3] = l, l = l >> 8, e[r + 2] = l, l = l >> 8, e[r + 1] = l, l = l >> 8, e[r] = l, r + 8; + } + a.prototype.writeBigUInt64LE = fe(function(t, r = 0) { + return hn(this, t, r, BigInt(0), BigInt("0xffffffffffffffff")); + }); + a.prototype.writeBigUInt64BE = fe(function(t, r = 0) { + return pn(this, t, r, BigInt(0), BigInt("0xffffffffffffffff")); + }); + a.prototype.writeIntLE = function(t, r, n, i) { + if (t = +t, r = r >>> 0, !i) { + let f = Math.pow(2, 8 * n - 1); + O(this, t, r, n, f - 1, -f); + } + let o = 0, l = 1, u = 0; + for (this[r] = t & 255;++o < n && (l *= 256); ) + t < 0 && u === 0 && this[r + o - 1] !== 0 && (u = 1), this[r + o] = (t / l >> 0) - u & 255; + return r + n; + }; + a.prototype.writeIntBE = function(t, r, n, i) { + if (t = +t, r = r >>> 0, !i) { + let f = Math.pow(2, 8 * n - 1); + O(this, t, r, n, f - 1, -f); + } + let o = n - 1, l = 1, u = 0; + for (this[r + o] = t & 255;--o >= 0 && (l *= 256); ) + t < 0 && u === 0 && this[r + o + 1] !== 0 && (u = 1), this[r + o] = (t / l >> 0) - u & 255; + return r + n; + }; + a.prototype.writeInt8 = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 1, 127, -128), t < 0 && (t = 255 + t + 1), this[r] = t & 255, r + 1; + }; + a.prototype.writeInt16LE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 2, 32767, -32768), this[r] = t & 255, this[r + 1] = t >>> 8, r + 2; + }; + a.prototype.writeInt16BE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 2, 32767, -32768), this[r] = t >>> 8, this[r + 1] = t & 255, r + 2; + }; + a.prototype.writeInt32LE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 4, 2147483647, -2147483648), this[r] = t & 255, this[r + 1] = t >>> 8, this[r + 2] = t >>> 16, this[r + 3] = t >>> 24, r + 4; + }; + a.prototype.writeInt32BE = function(t, r, n) { + return t = +t, r = r >>> 0, n || O(this, t, r, 4, 2147483647, -2147483648), t < 0 && (t = 4294967295 + t + 1), this[r] = t >>> 24, this[r + 1] = t >>> 16, this[r + 2] = t >>> 8, this[r + 3] = t & 255, r + 4; + }; + a.prototype.writeBigInt64LE = fe(function(t, r = 0) { + return hn(this, t, r, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + a.prototype.writeBigInt64BE = fe(function(t, r = 0) { + return pn(this, t, r, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + function yn(e, t, r, n, i, o) { + if (r + n > e.length) + throw new RangeError("Index out of range"); + if (r < 0) + throw new RangeError("Index out of range"); + } + function wn(e, t, r, n, i) { + return t = +t, r = r >>> 0, i || yn(e, t, r, 4, 340282346638528860000000000000000000000, -340282346638528860000000000000000000000), Le.write(e, t, r, n, 23, 4), r + 4; + } + a.prototype.writeFloatLE = function(t, r, n) { + return wn(this, t, r, true, n); + }; + a.prototype.writeFloatBE = function(t, r, n) { + return wn(this, t, r, false, n); + }; + function bn(e, t, r, n, i) { + return t = +t, r = r >>> 0, i || yn(e, t, r, 8, 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, -179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000), Le.write(e, t, r, n, 52, 8), r + 8; + } + a.prototype.writeDoubleLE = function(t, r, n) { + return bn(this, t, r, true, n); + }; + a.prototype.writeDoubleBE = function(t, r, n) { + return bn(this, t, r, false, n); + }; + a.prototype.copy = function(t, r, n, i) { + if (!a.isBuffer(t)) + throw new TypeError("argument should be a Buffer"); + if (n || (n = 0), !i && i !== 0 && (i = this.length), r >= t.length && (r = t.length), r || (r = 0), i > 0 && i < n && (i = n), i === n || t.length === 0 || this.length === 0) + return 0; + if (r < 0) + throw new RangeError("targetStart out of bounds"); + if (n < 0 || n >= this.length) + throw new RangeError("Index out of range"); + if (i < 0) + throw new RangeError("sourceEnd out of bounds"); + i > this.length && (i = this.length), t.length - r < i - n && (i = t.length - r + n); + let o = i - n; + return this === t && typeof Uint8Array.prototype.copyWithin == "function" ? this.copyWithin(r, n, i) : Uint8Array.prototype.set.call(t, this.subarray(n, i), r), o; + }; + a.prototype.fill = function(t, r, n, i) { + if (typeof t == "string") { + if (typeof r == "string" ? (i = r, r = 0, n = this.length) : typeof n == "string" && (i = n, n = this.length), i !== undefined && typeof i != "string") + throw new TypeError("encoding must be a string"); + if (typeof i == "string" && !a.isEncoding(i)) + throw new TypeError("Unknown encoding: " + i); + if (t.length === 1) { + let l = t.charCodeAt(0); + (i === "utf8" && l < 128 || i === "latin1") && (t = l); + } + } else + typeof t == "number" ? t = t & 255 : typeof t == "boolean" && (t = Number(t)); + if (r < 0 || this.length < r || this.length < n) + throw new RangeError("Out of range index"); + if (n <= r) + return this; + r = r >>> 0, n = n === undefined ? this.length : n >>> 0, t || (t = 0); + let o; + if (typeof t == "number") + for (o = r;o < n; ++o) + this[o] = t; + else { + let l = a.isBuffer(t) ? t : a.from(t, i), u = l.length; + if (u === 0) + throw new TypeError('The value "' + t + '" is invalid for argument "value"'); + for (o = 0;o < n - r; ++o) + this[o + r] = l[o % u]; + } + return this; + }; + var Be = {}; + function zt(e, t, r) { + Be[e] = class extends r { + constructor() { + super(), Object.defineProperty(this, "message", { value: t.apply(this, arguments), writable: true, configurable: true }), this.name = `${this.name} [${e}]`, this.stack, delete this.name; + } + get code() { + return e; + } + set code(i) { + Object.defineProperty(this, "code", { configurable: true, enumerable: true, value: i, writable: true }); + } + toString() { + return `${this.name} [${e}]: ${this.message}`; + } + }; + } + zt("ERR_BUFFER_OUT_OF_BOUNDS", function(e) { + return e ? `${e} is outside of buffer bounds` : "Attempt to access memory outside buffer bounds"; + }, RangeError); + zt("ERR_INVALID_ARG_TYPE", function(e, t) { + return `The "${e}" argument must be of type number. Received type ${typeof t}`; + }, TypeError); + zt("ERR_OUT_OF_RANGE", function(e, t, r) { + let n = `The value of "${e}" is out of range.`, i = r; + return Number.isInteger(r) && Math.abs(r) > 2 ** 32 ? i = un(String(r)) : typeof r == "bigint" && (i = String(r), (r > BigInt(2) ** BigInt(32) || r < -(BigInt(2) ** BigInt(32))) && (i = un(i)), i += "n"), n += ` It must be ${t}. Received ${i}`, n; + }, RangeError); + function un(e) { + let t = "", r = e.length, n = e[0] === "-" ? 1 : 0; + for (;r >= n + 4; r -= 3) + t = `_${e.slice(r - 3, r)}${t}`; + return `${e.slice(0, r)}${t}`; + } + function Wl(e, t, r) { + Ne(t, "offset"), (e[t] === undefined || e[t + r] === undefined) && Ge(t, e.length - (r + 1)); + } + function gn(e, t, r, n, i, o) { + if (e > r || e < t) { + let l = typeof t == "bigint" ? "n" : "", u; + throw o > 3 ? t === 0 || t === BigInt(0) ? u = `>= 0${l} and < 2${l} ** ${(o + 1) * 8}${l}` : u = `>= -(2${l} ** ${(o + 1) * 8 - 1}${l}) and < 2 ** ${(o + 1) * 8 - 1}${l}` : u = `>= ${t}${l} and <= ${r}${l}`, new Be.ERR_OUT_OF_RANGE("value", u, e); + } + Wl(n, i, o); + } + function Ne(e, t) { + if (typeof e != "number") + throw new Be.ERR_INVALID_ARG_TYPE(t, "number", e); + } + function Ge(e, t, r) { + throw Math.floor(e) !== e ? (Ne(e, r), new Be.ERR_OUT_OF_RANGE(r || "offset", "an integer", e)) : t < 0 ? new Be.ERR_BUFFER_OUT_OF_BOUNDS : new Be.ERR_OUT_OF_RANGE(r || "offset", `>= ${r ? 1 : 0} and <= ${t}`, e); + } + var $l = /[^+/0-9A-Za-z-_]/g; + function jl(e) { + if (e = e.split("=")[0], e = e.trim().replace($l, ""), e.length < 2) + return ""; + for (;e.length % 4 !== 0; ) + e = e + "="; + return e; + } + function Vt(e, t) { + t = t || 1 / 0; + let r, n = e.length, i = null, o = []; + for (let l = 0;l < n; ++l) { + if (r = e.charCodeAt(l), r > 55295 && r < 57344) { + if (!i) { + if (r > 56319) { + (t -= 3) > -1 && o.push(239, 191, 189); + continue; + } else if (l + 1 === n) { + (t -= 3) > -1 && o.push(239, 191, 189); + continue; + } + i = r; + continue; + } + if (r < 56320) { + (t -= 3) > -1 && o.push(239, 191, 189), i = r; + continue; + } + r = (i - 55296 << 10 | r - 56320) + 65536; + } else + i && (t -= 3) > -1 && o.push(239, 191, 189); + if (i = null, r < 128) { + if ((t -= 1) < 0) + break; + o.push(r); + } else if (r < 2048) { + if ((t -= 2) < 0) + break; + o.push(r >> 6 | 192, r & 63 | 128); + } else if (r < 65536) { + if ((t -= 3) < 0) + break; + o.push(r >> 12 | 224, r >> 6 & 63 | 128, r & 63 | 128); + } else if (r < 1114112) { + if ((t -= 4) < 0) + break; + o.push(r >> 18 | 240, r >> 12 & 63 | 128, r >> 6 & 63 | 128, r & 63 | 128); + } else + throw new Error("Invalid code point"); + } + return o; + } + function Gl(e) { + let t = []; + for (let r = 0;r < e.length; ++r) + t.push(e.charCodeAt(r) & 255); + return t; + } + function Hl(e, t) { + let r, n, i, o = []; + for (let l = 0;l < e.length && !((t -= 2) < 0); ++l) + r = e.charCodeAt(l), n = r >> 8, i = r % 256, o.push(i), o.push(n); + return o; + } + function _n(e) { + return jt.toByteArray(jl(e)); + } + function ot(e, t, r, n) { + let i; + for (i = 0;i < n && !(i + r >= t.length || i >= e.length); ++i) + t[i + r] = e[i]; + return i; + } + function H(e, t) { + return e instanceof t || e != null && e.constructor != null && e.constructor.name != null && e.constructor.name === t.name; + } + function Xt(e) { + return e !== e; + } + var Vl = function() { + let e = "0123456789abcdef", t = new Array(256); + for (let r = 0;r < 16; ++r) { + let n = r * 16; + for (let i = 0;i < 16; ++i) + t[n + i] = e[r] + e[i]; + } + return t; + }(); + function fe(e) { + return typeof BigInt > "u" ? Yl : e; + } + function Yl() { + throw new Error("BigInt not supported"); + } + }); + I = E((Gc, En) => { + En.exports = { ArrayIsArray(e) { + return Array.isArray(e); + }, ArrayPrototypeIncludes(e, t) { + return e.includes(t); + }, ArrayPrototypeIndexOf(e, t) { + return e.indexOf(t); + }, ArrayPrototypeJoin(e, t) { + return e.join(t); + }, ArrayPrototypeMap(e, t) { + return e.map(t); + }, ArrayPrototypePop(e, t) { + return e.pop(t); + }, ArrayPrototypePush(e, t) { + return e.push(t); + }, ArrayPrototypeSlice(e, t, r) { + return e.slice(t, r); + }, Error, FunctionPrototypeCall(e, t, ...r) { + return e.call(t, ...r); + }, FunctionPrototypeSymbolHasInstance(e, t) { + return Function.prototype[Symbol.hasInstance].call(e, t); + }, MathFloor: Math.floor, Number, NumberIsInteger: Number.isInteger, NumberIsNaN: Number.isNaN, NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, NumberParseInt: Number.parseInt, ObjectDefineProperties(e, t) { + return Object.defineProperties(e, t); + }, ObjectDefineProperty(e, t, r) { + return Object.defineProperty(e, t, r); + }, ObjectGetOwnPropertyDescriptor(e, t) { + return Object.getOwnPropertyDescriptor(e, t); + }, ObjectKeys(e) { + return Object.keys(e); + }, ObjectSetPrototypeOf(e, t) { + return Object.setPrototypeOf(e, t); + }, Promise, PromisePrototypeCatch(e, t) { + return e.catch(t); + }, PromisePrototypeThen(e, t, r) { + return e.then(t, r); + }, PromiseReject(e) { + return Promise.reject(e); + }, ReflectApply: Reflect.apply, RegExpPrototypeTest(e, t) { + return e.test(t); + }, SafeSet: Set, String, StringPrototypeSlice(e, t, r) { + return e.slice(t, r); + }, StringPrototypeToLowerCase(e) { + return e.toLowerCase(); + }, StringPrototypeToUpperCase(e) { + return e.toUpperCase(); + }, StringPrototypeTrim(e) { + return e.trim(); + }, Symbol, SymbolAsyncIterator: Symbol.asyncIterator, SymbolHasInstance: Symbol.hasInstance, SymbolIterator: Symbol.iterator, TypedArrayPrototypeSet(e, t, r) { + return e.set(t, r); + }, Uint8Array }; + }); + V = E((Hc, Qt) => { + var Kl = te(), zl = Object.getPrototypeOf(async function() { + }).constructor, Sn = globalThis.Blob || Kl.Blob, Xl = typeof Sn < "u" ? function(t) { + return t instanceof Sn; + } : function(t) { + return false; + }, Jt = class extends Error { + constructor(t) { + if (!Array.isArray(t)) + throw new TypeError(`Expected input to be an Array, got ${typeof t}`); + let r = ""; + for (let n = 0;n < t.length; n++) + r += ` ${t[n].stack} +`; + super(r), this.name = "AggregateError", this.errors = t; + } + }; + Qt.exports = { AggregateError: Jt, kEmptyObject: Object.freeze({}), once(e) { + let t = false; + return function(...r) { + t || (t = true, e.apply(this, r)); + }; + }, createDeferredPromise: function() { + let e, t; + return { promise: new Promise((n, i) => { + e = n, t = i; + }), resolve: e, reject: t }; + }, promisify(e) { + return new Promise((t, r) => { + e((n, ...i) => n ? r(n) : t(...i)); + }); + }, debuglog() { + return function() { + }; + }, format(e, ...t) { + return e.replace(/%([sdifj])/g, function(...[r, n]) { + let i = t.shift(); + return n === "f" ? i.toFixed(6) : n === "j" ? JSON.stringify(i) : n === "s" && typeof i == "object" ? `${i.constructor !== Object ? i.constructor.name : ""} {}`.trim() : i.toString(); + }); + }, inspect(e) { + switch (typeof e) { + case "string": + if (e.includes("'")) + if (e.includes('"')) { + if (!e.includes("`") && !e.includes("${")) + return `\`${e}\``; + } else + return `"${e}"`; + return `'${e}'`; + case "number": + return isNaN(e) ? "NaN" : Object.is(e, -0) ? String(e) : e; + case "bigint": + return `${String(e)}n`; + case "boolean": + case "undefined": + return String(e); + case "object": + return "{}"; + } + }, types: { isAsyncFunction(e) { + return e instanceof zl; + }, isArrayBufferView(e) { + return ArrayBuffer.isView(e); + } }, isBlob: Xl }; + Qt.exports.promisify.custom = Symbol.for("nodejs.util.promisify.custom"); + }); + ut = E((Vc, lt) => { + var { AbortController: mn, AbortSignal: Jl } = typeof self < "u" ? self : typeof window < "u" ? window : undefined; + lt.exports = mn; + lt.exports.AbortSignal = Jl; + lt.exports.default = mn; + }); + C = E((Yc, An) => { + var { format: Ql, inspect: ft, AggregateError: Zl } = V(), eu = globalThis.AggregateError || Zl, tu = Symbol("kIsNodeError"), ru = ["string", "function", "number", "object", "Function", "Object", "boolean", "bigint", "symbol"], nu = /^([A-Z][a-z0-9]*)+$/, iu = "__node_internal_", st = {}; + function be(e, t) { + if (!e) + throw new st.ERR_INTERNAL_ASSERTION(t); + } + function xn(e) { + let t = "", r = e.length, n = e[0] === "-" ? 1 : 0; + for (;r >= n + 4; r -= 3) + t = `_${e.slice(r - 3, r)}${t}`; + return `${e.slice(0, r)}${t}`; + } + function ou(e, t, r) { + if (typeof t == "function") + return be(t.length <= r.length, `Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`), t(...r); + let n = (t.match(/%[dfijoOs]/g) || []).length; + return be(n === r.length, `Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${n}).`), r.length === 0 ? t : Ql(t, ...r); + } + function M(e, t, r) { + r || (r = Error); + + class n extends r { + constructor(...o) { + super(ou(e, t, o)); + } + toString() { + return `${this.name} [${e}]: ${this.message}`; + } + } + Object.defineProperties(n.prototype, { name: { value: r.name, writable: true, enumerable: false, configurable: true }, toString: { value() { + return `${this.name} [${e}]: ${this.message}`; + }, writable: true, enumerable: false, configurable: true } }), n.prototype.code = e, n.prototype[tu] = true, st[e] = n; + } + function Rn(e) { + let t = iu + e.name; + return Object.defineProperty(e, "name", { value: t }), e; + } + function lu(e, t) { + if (e && t && e !== t) { + if (Array.isArray(t.errors)) + return t.errors.push(e), t; + let r = new eu([t, e], t.message); + return r.code = t.code, r; + } + return e || t; + } + var Zt = class extends Error { + constructor(t = "The operation was aborted", r = undefined) { + if (r !== undefined && typeof r != "object") + throw new st.ERR_INVALID_ARG_TYPE("options", "Object", r); + super(t, r), this.code = "ABORT_ERR", this.name = "AbortError"; + } + }; + M("ERR_ASSERTION", "%s", Error); + M("ERR_INVALID_ARG_TYPE", (e, t, r) => { + be(typeof e == "string", "'name' must be a string"), Array.isArray(t) || (t = [t]); + let n = "The "; + e.endsWith(" argument") ? n += `${e} ` : n += `"${e}" ${e.includes(".") ? "property" : "argument"} `, n += "must be "; + let i = [], o = [], l = []; + for (let f of t) + be(typeof f == "string", "All expected entries have to be of type string"), ru.includes(f) ? i.push(f.toLowerCase()) : nu.test(f) ? o.push(f) : (be(f !== "object", 'The value "object" should be written as "Object"'), l.push(f)); + if (o.length > 0) { + let f = i.indexOf("object"); + f !== -1 && (i.splice(i, f, 1), o.push("Object")); + } + if (i.length > 0) { + switch (i.length) { + case 1: + n += `of type ${i[0]}`; + break; + case 2: + n += `one of type ${i[0]} or ${i[1]}`; + break; + default: { + let f = i.pop(); + n += `one of type ${i.join(", ")}, or ${f}`; + } + } + (o.length > 0 || l.length > 0) && (n += " or "); + } + if (o.length > 0) { + switch (o.length) { + case 1: + n += `an instance of ${o[0]}`; + break; + case 2: + n += `an instance of ${o[0]} or ${o[1]}`; + break; + default: { + let f = o.pop(); + n += `an instance of ${o.join(", ")}, or ${f}`; + } + } + l.length > 0 && (n += " or "); + } + switch (l.length) { + case 0: + break; + case 1: + l[0].toLowerCase() !== l[0] && (n += "an "), n += `${l[0]}`; + break; + case 2: + n += `one of ${l[0]} or ${l[1]}`; + break; + default: { + let f = l.pop(); + n += `one of ${l.join(", ")}, or ${f}`; + } + } + if (r == null) + n += `. Received ${r}`; + else if (typeof r == "function" && r.name) + n += `. Received function ${r.name}`; + else if (typeof r == "object") { + var u; + (u = r.constructor) !== null && u !== undefined && u.name ? n += `. Received an instance of ${r.constructor.name}` : n += `. Received ${ft(r, { depth: -1 })}`; + } else { + let f = ft(r, { colors: false }); + f.length > 25 && (f = `${f.slice(0, 25)}...`), n += `. Received type ${typeof r} (${f})`; + } + return n; + }, TypeError); + M("ERR_INVALID_ARG_VALUE", (e, t, r = "is invalid") => { + let n = ft(t); + return n.length > 128 && (n = n.slice(0, 128) + "..."), `The ${e.includes(".") ? "property" : "argument"} '${e}' ${r}. Received ${n}`; + }, TypeError); + M("ERR_INVALID_RETURN_VALUE", (e, t, r) => { + var n; + let i = r != null && (n = r.constructor) !== null && n !== undefined && n.name ? `instance of ${r.constructor.name}` : `type ${typeof r}`; + return `Expected ${e} to be returned from the "${t}" function but got ${i}.`; + }, TypeError); + M("ERR_MISSING_ARGS", (...e) => { + be(e.length > 0, "At least one arg needs to be specified"); + let t, r = e.length; + switch (e = (Array.isArray(e) ? e : [e]).map((n) => `"${n}"`).join(" or "), r) { + case 1: + t += `The ${e[0]} argument`; + break; + case 2: + t += `The ${e[0]} and ${e[1]} arguments`; + break; + default: + { + let n = e.pop(); + t += `The ${e.join(", ")}, and ${n} arguments`; + } + break; + } + return `${t} must be specified`; + }, TypeError); + M("ERR_OUT_OF_RANGE", (e, t, r) => { + be(t, 'Missing "range" argument'); + let n; + return Number.isInteger(r) && Math.abs(r) > 2 ** 32 ? n = xn(String(r)) : typeof r == "bigint" ? (n = String(r), (r > 2n ** 32n || r < -(2n ** 32n)) && (n = xn(n)), n += "n") : n = ft(r), `The value of "${e}" is out of range. It must be ${t}. Received ${n}`; + }, RangeError); + M("ERR_MULTIPLE_CALLBACK", "Callback called multiple times", Error); + M("ERR_METHOD_NOT_IMPLEMENTED", "The %s method is not implemented", Error); + M("ERR_STREAM_ALREADY_FINISHED", "Cannot call %s after a stream was finished", Error); + M("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable", Error); + M("ERR_STREAM_DESTROYED", "Cannot call %s after a stream was destroyed", Error); + M("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError); + M("ERR_STREAM_PREMATURE_CLOSE", "Premature close", Error); + M("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF", Error); + M("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event", Error); + M("ERR_STREAM_WRITE_AFTER_END", "write after end", Error); + M("ERR_UNKNOWN_ENCODING", "Unknown encoding: %s", TypeError); + An.exports = { AbortError: Zt, aggregateTwoErrors: Rn(lu), hideStackFrames: Rn, codes: st }; + }); + He = E((Kc, Cn) => { + var { ArrayIsArray: Bn, ArrayPrototypeIncludes: Ln, ArrayPrototypeJoin: Nn, ArrayPrototypeMap: uu, NumberIsInteger: tr, NumberIsNaN: fu, NumberMAX_SAFE_INTEGER: su, NumberMIN_SAFE_INTEGER: au, NumberParseInt: cu, ObjectPrototypeHasOwnProperty: du, RegExpPrototypeExec: hu, String: pu, StringPrototypeToUpperCase: yu, StringPrototypeTrim: wu } = I(), { hideStackFrames: W, codes: { ERR_SOCKET_BAD_PORT: bu, ERR_INVALID_ARG_TYPE: D, ERR_INVALID_ARG_VALUE: at, ERR_OUT_OF_RANGE: ge, ERR_UNKNOWN_SIGNAL: In } } = C(), { normalizeEncoding: gu } = V(), { isAsyncFunction: _u, isArrayBufferView: Eu } = V().types, Tn = {}; + function Su(e) { + return e === (e | 0); + } + function mu(e) { + return e === e >>> 0; + } + var xu = /^[0-7]+$/, Ru = "must be a 32-bit unsigned integer or an octal string"; + function Au(e, t, r) { + if (typeof e > "u" && (e = r), typeof e == "string") { + if (hu(xu, e) === null) + throw new at(t, e, Ru); + e = cu(e, 8); + } + return Fn(e, t), e; + } + var Iu = W((e, t, r = au, n = su) => { + if (typeof e != "number") + throw new D(t, "number", e); + if (!tr(e)) + throw new ge(t, "an integer", e); + if (e < r || e > n) + throw new ge(t, `>= ${r} && <= ${n}`, e); + }), Tu = W((e, t, r = -2147483648, n = 2147483647) => { + if (typeof e != "number") + throw new D(t, "number", e); + if (!tr(e)) + throw new ge(t, "an integer", e); + if (e < r || e > n) + throw new ge(t, `>= ${r} && <= ${n}`, e); + }), Fn = W((e, t, r = false) => { + if (typeof e != "number") + throw new D(t, "number", e); + if (!tr(e)) + throw new ge(t, "an integer", e); + let n = r ? 1 : 0, i = 4294967295; + if (e < n || e > i) + throw new ge(t, `>= ${n} && <= ${i}`, e); + }); + function Mn(e, t) { + if (typeof e != "string") + throw new D(t, "string", e); + } + function Bu(e, t, r = undefined, n) { + if (typeof e != "number") + throw new D(t, "number", e); + if (r != null && e < r || n != null && e > n || (r != null || n != null) && fu(e)) + throw new ge(t, `${r != null ? `>= ${r}` : ""}${r != null && n != null ? " && " : ""}${n != null ? `<= ${n}` : ""}`, e); + } + var Lu = W((e, t, r) => { + if (!Ln(r, e)) { + let n = Nn(uu(r, (o) => typeof o == "string" ? `'${o}'` : pu(o)), ", "), i = "must be one of: " + n; + throw new at(t, e, i); + } + }); + function Nu(e, t) { + if (typeof e != "boolean") + throw new D(t, "boolean", e); + } + function er(e, t, r) { + return e == null || !du(e, t) ? r : e[t]; + } + var Fu = W((e, t, r = null) => { + let n = er(r, "allowArray", false), i = er(r, "allowFunction", false); + if (!er(r, "nullable", false) && e === null || !n && Bn(e) || typeof e != "object" && (!i || typeof e != "function")) + throw new D(t, "Object", e); + }), Mu = W((e, t, r = 0) => { + if (!Bn(e)) + throw new D(t, "Array", e); + if (e.length < r) { + let n = `must be longer than ${r}`; + throw new at(t, e, n); + } + }); + function Cu(e, t = "signal") { + if (Mn(e, t), Tn[e] === undefined) + throw Tn[yu(e)] !== undefined ? new In(e + " (signals must use all capital letters)") : new In(e); + } + var Ou = W((e, t = "buffer") => { + if (!Eu(e)) + throw new D(t, ["Buffer", "TypedArray", "DataView"], e); + }); + function Du(e, t) { + let r = gu(t), n = e.length; + if (r === "hex" && n % 2 !== 0) + throw new at("encoding", t, `is invalid for data of length ${n}`); + } + function Pu(e, t = "Port", r = true) { + if (typeof e != "number" && typeof e != "string" || typeof e == "string" && wu(e).length === 0 || +e !== +e >>> 0 || e > 65535 || e === 0 && !r) + throw new bu(t, e, r); + return e | 0; + } + var ku = W((e, t) => { + if (e !== undefined && (e === null || typeof e != "object" || !("aborted" in e))) + throw new D(t, "AbortSignal", e); + }), Uu = W((e, t) => { + if (typeof e != "function") + throw new D(t, "Function", e); + }), vu = W((e, t) => { + if (typeof e != "function" || _u(e)) + throw new D(t, "Function", e); + }), qu = W((e, t) => { + if (e !== undefined) + throw new D(t, "undefined", e); + }); + function Wu(e, t, r) { + if (!Ln(r, e)) + throw new D(t, `('${Nn(r, "|")}')`, e); + } + Cn.exports = { isInt32: Su, isUint32: mu, parseFileMode: Au, validateArray: Mu, validateBoolean: Nu, validateBuffer: Ou, validateEncoding: Du, validateFunction: Uu, validateInt32: Tu, validateInteger: Iu, validateNumber: Bu, validateObject: Fu, validateOneOf: Lu, validatePlainFunction: vu, validatePort: Pu, validateSignalName: Cu, validateString: Mn, validateUint32: Fn, validateUndefined: qu, validateUnion: Wu, validateAbortSignal: ku }; + }); + ir = E((zc, kn) => { + var x = kn.exports = {}, Y, K; + function rr() { + throw new Error("setTimeout has not been defined"); + } + function nr() { + throw new Error("clearTimeout has not been defined"); + } + (function() { + try { + typeof setTimeout == "function" ? Y = setTimeout : Y = rr; + } catch { + Y = rr; + } + try { + typeof clearTimeout == "function" ? K = clearTimeout : K = nr; + } catch { + K = nr; + } + })(); + function On(e) { + if (Y === setTimeout) + return setTimeout(e, 0); + if ((Y === rr || !Y) && setTimeout) + return Y = setTimeout, setTimeout(e, 0); + try { + return Y(e, 0); + } catch { + try { + return Y.call(null, e, 0); + } catch { + return Y.call(this, e, 0); + } + } + } + function $u(e) { + if (K === clearTimeout) + return clearTimeout(e); + if ((K === nr || !K) && clearTimeout) + return K = clearTimeout, clearTimeout(e); + try { + return K(e); + } catch { + try { + return K.call(null, e); + } catch { + return K.call(this, e); + } + } + } + var re = [], Me = false, _e, ct = -1; + function ju() { + !Me || !_e || (Me = false, _e.length ? re = _e.concat(re) : ct = -1, re.length && Dn()); + } + function Dn() { + if (!Me) { + var e = On(ju); + Me = true; + for (var t = re.length;t; ) { + for (_e = re, re = [];++ct < t; ) + _e && _e[ct].run(); + ct = -1, t = re.length; + } + _e = null, Me = false, $u(e); + } + } + x.nextTick = function(e) { + var t = new Array(arguments.length - 1); + if (arguments.length > 1) + for (var r = 1;r < arguments.length; r++) + t[r - 1] = arguments[r]; + re.push(new Pn(e, t)), re.length === 1 && !Me && On(Dn); + }; + function Pn(e, t) { + this.fun = e, this.array = t; + } + Pn.prototype.run = function() { + this.fun.apply(null, this.array); + }; + x.title = "browser"; + x.browser = true; + x.env = {}; + x.argv = []; + x.version = ""; + x.versions = {}; + function ne() { + } + x.on = ne; + x.addListener = ne; + x.once = ne; + x.off = ne; + x.removeListener = ne; + x.removeAllListeners = ne; + x.emit = ne; + x.prependListener = ne; + x.prependOnceListener = ne; + x.listeners = function(e) { + return []; + }; + x.binding = function(e) { + throw new Error("process.binding is not supported"); + }; + x.cwd = function() { + return "/"; + }; + x.chdir = function(e) { + throw new Error("process.chdir is not supported"); + }; + x.umask = function() { + return 0; + }; + }); + k = {}; + Qr(k, { default: () => Gu }); + se = yl(() => { + ue(k, rt(ir())); + Gu = rt(ir()); + }); + ae = E((Jc, zn) => { + var { Symbol: dt, SymbolAsyncIterator: Un, SymbolIterator: vn } = I(), qn = dt("kDestroyed"), Wn = dt("kIsErrored"), or = dt("kIsReadable"), $n = dt("kIsDisturbed"); + function ht(e, t = false) { + var r; + return !!(e && typeof e.pipe == "function" && typeof e.on == "function" && (!t || typeof e.pause == "function" && typeof e.resume == "function") && (!e._writableState || ((r = e._readableState) === null || r === undefined ? undefined : r.readable) !== false) && (!e._writableState || e._readableState)); + } + function pt(e) { + var t; + return !!(e && typeof e.write == "function" && typeof e.on == "function" && (!e._readableState || ((t = e._writableState) === null || t === undefined ? undefined : t.writable) !== false)); + } + function Hu(e) { + return !!(e && typeof e.pipe == "function" && e._readableState && typeof e.on == "function" && typeof e.write == "function"); + } + function Ee(e) { + return e && (e._readableState || e._writableState || typeof e.write == "function" && typeof e.on == "function" || typeof e.pipe == "function" && typeof e.on == "function"); + } + function Vu(e, t) { + return e == null ? false : t === true ? typeof e[Un] == "function" : t === false ? typeof e[vn] == "function" : typeof e[Un] == "function" || typeof e[vn] == "function"; + } + function yt(e) { + if (!Ee(e)) + return null; + let { _writableState: t, _readableState: r } = e, n = t || r; + return !!(e.destroyed || e[qn] || n != null && n.destroyed); + } + function jn(e) { + if (!pt(e)) + return null; + if (e.writableEnded === true) + return true; + let t = e._writableState; + return t != null && t.errored ? false : typeof t?.ended != "boolean" ? null : t.ended; + } + function Yu(e, t) { + if (!pt(e)) + return null; + if (e.writableFinished === true) + return true; + let r = e._writableState; + return r != null && r.errored ? false : typeof r?.finished != "boolean" ? null : !!(r.finished || t === false && r.ended === true && r.length === 0); + } + function Ku(e) { + if (!ht(e)) + return null; + if (e.readableEnded === true) + return true; + let t = e._readableState; + return !t || t.errored ? false : typeof t?.ended != "boolean" ? null : t.ended; + } + function Gn(e, t) { + if (!ht(e)) + return null; + let r = e._readableState; + return r != null && r.errored ? false : typeof r?.endEmitted != "boolean" ? null : !!(r.endEmitted || t === false && r.ended === true && r.length === 0); + } + function Hn(e) { + return e && e[or] != null ? e[or] : typeof e?.readable != "boolean" ? null : yt(e) ? false : ht(e) && e.readable && !Gn(e); + } + function Vn(e) { + return typeof e?.writable != "boolean" ? null : yt(e) ? false : pt(e) && e.writable && !jn(e); + } + function zu(e, t) { + return Ee(e) ? yt(e) ? true : !(t?.readable !== false && Hn(e) || t?.writable !== false && Vn(e)) : null; + } + function Xu(e) { + var t, r; + return Ee(e) ? e.writableErrored ? e.writableErrored : (t = (r = e._writableState) === null || r === undefined ? undefined : r.errored) !== null && t !== undefined ? t : null : null; + } + function Ju(e) { + var t, r; + return Ee(e) ? e.readableErrored ? e.readableErrored : (t = (r = e._readableState) === null || r === undefined ? undefined : r.errored) !== null && t !== undefined ? t : null : null; + } + function Qu(e) { + if (!Ee(e)) + return null; + if (typeof e.closed == "boolean") + return e.closed; + let { _writableState: t, _readableState: r } = e; + return typeof t?.closed == "boolean" || typeof r?.closed == "boolean" ? t?.closed || r?.closed : typeof e._closed == "boolean" && Yn(e) ? e._closed : null; + } + function Yn(e) { + return typeof e._closed == "boolean" && typeof e._defaultKeepAlive == "boolean" && typeof e._removedConnection == "boolean" && typeof e._removedContLen == "boolean"; + } + function Kn(e) { + return typeof e._sent100 == "boolean" && Yn(e); + } + function Zu(e) { + var t; + return typeof e._consuming == "boolean" && typeof e._dumped == "boolean" && ((t = e.req) === null || t === undefined ? undefined : t.upgradeOrConnect) === undefined; + } + function ef(e) { + if (!Ee(e)) + return null; + let { _writableState: t, _readableState: r } = e, n = t || r; + return !n && Kn(e) || !!(n && n.autoDestroy && n.emitClose && n.closed === false); + } + function tf(e) { + var t; + return !!(e && ((t = e[$n]) !== null && t !== undefined ? t : e.readableDidRead || e.readableAborted)); + } + function rf(e) { + var t, r, n, i, o, l, u, f, s, d; + return !!(e && ((t = (r = (n = (i = (o = (l = e[Wn]) !== null && l !== undefined ? l : e.readableErrored) !== null && o !== undefined ? o : e.writableErrored) !== null && i !== undefined ? i : (u = e._readableState) === null || u === undefined ? undefined : u.errorEmitted) !== null && n !== undefined ? n : (f = e._writableState) === null || f === undefined ? undefined : f.errorEmitted) !== null && r !== undefined ? r : (s = e._readableState) === null || s === undefined ? undefined : s.errored) !== null && t !== undefined ? t : (d = e._writableState) === null || d === undefined ? undefined : d.errored)); + } + zn.exports = { kDestroyed: qn, isDisturbed: tf, kIsDisturbed: $n, isErrored: rf, kIsErrored: Wn, isReadable: Hn, kIsReadable: or, isClosed: Qu, isDestroyed: yt, isDuplexNodeStream: Hu, isFinished: zu, isIterable: Vu, isReadableNodeStream: ht, isReadableEnded: Ku, isReadableFinished: Gn, isReadableErrored: Ju, isNodeStream: Ee, isWritable: Vn, isWritableNodeStream: pt, isWritableEnded: jn, isWritableFinished: Yu, isWritableErrored: Xu, isServerRequest: Zu, isServerResponse: Kn, willEmitClose: ef }; + }); + ce = E((Qc, ur) => { + var Ce = (se(), pe(k)), { AbortError: nf, codes: of } = C(), { ERR_INVALID_ARG_TYPE: lf, ERR_STREAM_PREMATURE_CLOSE: Xn } = of, { kEmptyObject: Jn, once: Qn } = V(), { validateAbortSignal: uf, validateFunction: ff, validateObject: sf } = He(), { Promise: af } = I(), { isClosed: cf, isReadable: Zn, isReadableNodeStream: lr, isReadableFinished: ei, isReadableErrored: df, isWritable: ti, isWritableNodeStream: ri, isWritableFinished: ni, isWritableErrored: hf, isNodeStream: pf, willEmitClose: yf } = ae(); + function wf(e) { + return e.setHeader && typeof e.abort == "function"; + } + var bf = () => { + }; + function ii(e, t, r) { + var n, i; + arguments.length === 2 ? (r = t, t = Jn) : t == null ? t = Jn : sf(t, "options"), ff(r, "callback"), uf(t.signal, "options.signal"), r = Qn(r); + let o = (n = t.readable) !== null && n !== undefined ? n : lr(e), l = (i = t.writable) !== null && i !== undefined ? i : ri(e); + if (!pf(e)) + throw new lf("stream", "Stream", e); + let { _writableState: u, _readableState: f } = e, s = () => { + e.writable || y(); + }, d = yf(e) && lr(e) === o && ri(e) === l, c = ni(e, false), y = () => { + c = true, e.destroyed && (d = false), !(d && (!e.readable || o)) && (!o || h) && r.call(e); + }, h = ei(e, false), p = () => { + h = true, e.destroyed && (d = false), !(d && (!e.writable || l)) && (!l || c) && r.call(e); + }, B = (N) => { + r.call(e, N); + }, v = cf(e), w = () => { + v = true; + let N = hf(e) || df(e); + if (N && typeof N != "boolean") + return r.call(e, N); + if (o && !h && lr(e, true) && !ei(e, false)) + return r.call(e, new Xn); + if (l && !c && !ni(e, false)) + return r.call(e, new Xn); + r.call(e); + }, b = () => { + e.req.on("finish", y); + }; + wf(e) ? (e.on("complete", y), d || e.on("abort", w), e.req ? b() : e.on("request", b)) : l && !u && (e.on("end", s), e.on("close", s)), !d && typeof e.aborted == "boolean" && e.on("aborted", w), e.on("end", p), e.on("finish", y), t.error !== false && e.on("error", B), e.on("close", w), v ? Ce.nextTick(w) : u != null && u.errorEmitted || f != null && f.errorEmitted ? d || Ce.nextTick(w) : (!o && (!d || Zn(e)) && (c || ti(e) === false) || !l && (!d || ti(e)) && (h || Zn(e) === false) || f && e.req && e.aborted) && Ce.nextTick(w); + let L = () => { + r = bf, e.removeListener("aborted", w), e.removeListener("complete", y), e.removeListener("abort", w), e.removeListener("request", b), e.req && e.req.removeListener("finish", y), e.removeListener("end", s), e.removeListener("close", s), e.removeListener("finish", y), e.removeListener("end", p), e.removeListener("error", B), e.removeListener("close", w); + }; + if (t.signal && !v) { + let N = () => { + let Q = r; + L(), Q.call(e, new nf(undefined, { cause: t.signal.reason })); + }; + if (t.signal.aborted) + Ce.nextTick(N); + else { + let Q = r; + r = Qn((...Ie) => { + t.signal.removeEventListener("abort", N), Q.apply(e, Ie); + }), t.signal.addEventListener("abort", N); + } + } + return L; + } + function gf(e, t) { + return new af((r, n) => { + ii(e, t, (i) => { + i ? n(i) : r(); + }); + }); + } + ur.exports = ii; + ur.exports.finished = gf; + }); + di = E((Zc, ar) => { + var fi = globalThis.AbortController || ut().AbortController, { codes: { ERR_INVALID_ARG_TYPE: Ve, ERR_MISSING_ARGS: _f, ERR_OUT_OF_RANGE: Ef }, AbortError: z } = C(), { validateAbortSignal: Oe, validateInteger: Sf, validateObject: De } = He(), mf = I().Symbol("kWeak"), { finished: xf } = ce(), { ArrayPrototypePush: Rf, MathFloor: Af, Number: If, NumberIsNaN: Tf, Promise: oi, PromiseReject: li, PromisePrototypeThen: Bf, Symbol: si } = I(), wt = si("kEmpty"), ui = si("kEof"); + function bt(e, t) { + if (typeof e != "function") + throw new Ve("fn", ["Function", "AsyncFunction"], e); + t != null && De(t, "options"), t?.signal != null && Oe(t.signal, "options.signal"); + let r = 1; + return t?.concurrency != null && (r = Af(t.concurrency)), Sf(r, "concurrency", 1), async function* () { + var i, o; + let l = new fi, u = this, f = [], s = l.signal, d = { signal: s }, c = () => l.abort(); + t != null && (i = t.signal) !== null && i !== undefined && i.aborted && c(), t == null || (o = t.signal) === null || o === undefined || o.addEventListener("abort", c); + let y, h, p = false; + function B() { + p = true; + } + async function v() { + try { + for await (let L of u) { + var w; + if (p) + return; + if (s.aborted) + throw new z; + try { + L = e(L, d); + } catch (N) { + L = li(N); + } + L !== wt && (typeof ((w = L) === null || w === undefined ? undefined : w.catch) == "function" && L.catch(B), f.push(L), y && (y(), y = null), !p && f.length && f.length >= r && await new oi((N) => { + h = N; + })); + } + f.push(ui); + } catch (L) { + let N = li(L); + Bf(N, undefined, B), f.push(N); + } finally { + var b; + p = true, y && (y(), y = null), t == null || (b = t.signal) === null || b === undefined || b.removeEventListener("abort", c); + } + } + v(); + try { + for (;; ) { + for (;f.length > 0; ) { + let w = await f[0]; + if (w === ui) + return; + if (s.aborted) + throw new z; + w !== wt && (yield w), f.shift(), h && (h(), h = null); + } + await new oi((w) => { + y = w; + }); + } + } finally { + l.abort(), p = true, h && (h(), h = null); + } + }.call(this); + } + function Lf(e = undefined) { + return e != null && De(e, "options"), e?.signal != null && Oe(e.signal, "options.signal"), async function* () { + let r = 0; + for await (let i of this) { + var n; + if (e != null && (n = e.signal) !== null && n !== undefined && n.aborted) + throw new z({ cause: e.signal.reason }); + yield [r++, i]; + } + }.call(this); + } + async function ai(e, t = undefined) { + for await (let r of sr.call(this, e, t)) + return true; + return false; + } + async function Nf(e, t = undefined) { + if (typeof e != "function") + throw new Ve("fn", ["Function", "AsyncFunction"], e); + return !await ai.call(this, async (...r) => !await e(...r), t); + } + async function Ff(e, t) { + for await (let r of sr.call(this, e, t)) + return r; + } + async function Mf(e, t) { + if (typeof e != "function") + throw new Ve("fn", ["Function", "AsyncFunction"], e); + async function r(n, i) { + return await e(n, i), wt; + } + for await (let n of bt.call(this, r, t)) + ; + } + function sr(e, t) { + if (typeof e != "function") + throw new Ve("fn", ["Function", "AsyncFunction"], e); + async function r(n, i) { + return await e(n, i) ? n : wt; + } + return bt.call(this, r, t); + } + var fr = class extends _f { + constructor() { + super("reduce"), this.message = "Reduce of an empty stream requires an initial value"; + } + }; + async function Cf(e, t, r) { + var n; + if (typeof e != "function") + throw new Ve("reducer", ["Function", "AsyncFunction"], e); + r != null && De(r, "options"), r?.signal != null && Oe(r.signal, "options.signal"); + let i = arguments.length > 1; + if (r != null && (n = r.signal) !== null && n !== undefined && n.aborted) { + let s = new z(undefined, { cause: r.signal.reason }); + throw this.once("error", () => { + }), await xf(this.destroy(s)), s; + } + let o = new fi, l = o.signal; + if (r != null && r.signal) { + let s = { once: true, [mf]: this }; + r.signal.addEventListener("abort", () => o.abort(), s); + } + let u = false; + try { + for await (let s of this) { + var f; + if (u = true, r != null && (f = r.signal) !== null && f !== undefined && f.aborted) + throw new z; + i ? t = await e(t, s, { signal: l }) : (t = s, i = true); + } + if (!u && !i) + throw new fr; + } finally { + o.abort(); + } + return t; + } + async function Of(e) { + e != null && De(e, "options"), e?.signal != null && Oe(e.signal, "options.signal"); + let t = []; + for await (let n of this) { + var r; + if (e != null && (r = e.signal) !== null && r !== undefined && r.aborted) + throw new z(undefined, { cause: e.signal.reason }); + Rf(t, n); + } + return t; + } + function Df(e, t) { + let r = bt.call(this, e, t); + return async function* () { + for await (let i of r) + yield* i; + }.call(this); + } + function ci(e) { + if (e = If(e), Tf(e)) + return 0; + if (e < 0) + throw new Ef("number", ">= 0", e); + return e; + } + function Pf(e, t = undefined) { + return t != null && De(t, "options"), t?.signal != null && Oe(t.signal, "options.signal"), e = ci(e), async function* () { + var n; + if (t != null && (n = t.signal) !== null && n !== undefined && n.aborted) + throw new z; + for await (let o of this) { + var i; + if (t != null && (i = t.signal) !== null && i !== undefined && i.aborted) + throw new z; + e-- <= 0 && (yield o); + } + }.call(this); + } + function kf(e, t = undefined) { + return t != null && De(t, "options"), t?.signal != null && Oe(t.signal, "options.signal"), e = ci(e), async function* () { + var n; + if (t != null && (n = t.signal) !== null && n !== undefined && n.aborted) + throw new z; + for await (let o of this) { + var i; + if (t != null && (i = t.signal) !== null && i !== undefined && i.aborted) + throw new z; + if (e-- > 0) + yield o; + else + return; + } + }.call(this); + } + ar.exports.streamReturningOperators = { asIndexedPairs: Lf, drop: Pf, filter: sr, flatMap: Df, map: bt, take: kf }; + ar.exports.promiseReturningOperators = { every: Nf, forEach: Mf, reduce: Cf, toArray: Of, some: ai, find: Ff }; + }); + Se = E((ed, Ei) => { + var de = (se(), pe(k)), { aggregateTwoErrors: Uf, codes: { ERR_MULTIPLE_CALLBACK: vf }, AbortError: qf } = C(), { Symbol: yi } = I(), { kDestroyed: Wf, isDestroyed: $f, isFinished: jf, isServerRequest: Gf } = ae(), wi = yi("kDestroy"), cr = yi("kConstruct"); + function bi(e, t, r) { + e && (e.stack, t && !t.errored && (t.errored = e), r && !r.errored && (r.errored = e)); + } + function Hf(e, t) { + let r = this._readableState, n = this._writableState, i = n || r; + return n && n.destroyed || r && r.destroyed ? (typeof t == "function" && t(), this) : (bi(e, n, r), n && (n.destroyed = true), r && (r.destroyed = true), i.constructed ? hi(this, e, t) : this.once(wi, function(o) { + hi(this, Uf(o, e), t); + }), this); + } + function hi(e, t, r) { + let n = false; + function i(o) { + if (n) + return; + n = true; + let { _readableState: l, _writableState: u } = e; + bi(o, u, l), u && (u.closed = true), l && (l.closed = true), typeof r == "function" && r(o), o ? de.nextTick(Vf, e, o) : de.nextTick(gi, e); + } + try { + e._destroy(t || null, i); + } catch (o) { + i(o); + } + } + function Vf(e, t) { + dr(e, t), gi(e); + } + function gi(e) { + let { _readableState: t, _writableState: r } = e; + r && (r.closeEmitted = true), t && (t.closeEmitted = true), (r && r.emitClose || t && t.emitClose) && e.emit("close"); + } + function dr(e, t) { + let { _readableState: r, _writableState: n } = e; + n && n.errorEmitted || r && r.errorEmitted || (n && (n.errorEmitted = true), r && (r.errorEmitted = true), e.emit("error", t)); + } + function Yf() { + let e = this._readableState, t = this._writableState; + e && (e.constructed = true, e.closed = false, e.closeEmitted = false, e.destroyed = false, e.errored = null, e.errorEmitted = false, e.reading = false, e.ended = e.readable === false, e.endEmitted = e.readable === false), t && (t.constructed = true, t.destroyed = false, t.closed = false, t.closeEmitted = false, t.errored = null, t.errorEmitted = false, t.finalCalled = false, t.prefinished = false, t.ended = t.writable === false, t.ending = t.writable === false, t.finished = t.writable === false); + } + function hr(e, t, r) { + let { _readableState: n, _writableState: i } = e; + if (i && i.destroyed || n && n.destroyed) + return this; + n && n.autoDestroy || i && i.autoDestroy ? e.destroy(t) : t && (t.stack, i && !i.errored && (i.errored = t), n && !n.errored && (n.errored = t), r ? de.nextTick(dr, e, t) : dr(e, t)); + } + function Kf(e, t) { + if (typeof e._construct != "function") + return; + let { _readableState: r, _writableState: n } = e; + r && (r.constructed = false), n && (n.constructed = false), e.once(cr, t), !(e.listenerCount(cr) > 1) && de.nextTick(zf, e); + } + function zf(e) { + let t = false; + function r(n) { + if (t) { + hr(e, n ?? new vf); + return; + } + t = true; + let { _readableState: i, _writableState: o } = e, l = o || i; + i && (i.constructed = true), o && (o.constructed = true), l.destroyed ? e.emit(wi, n) : n ? hr(e, n, true) : de.nextTick(Xf, e); + } + try { + e._construct(r); + } catch (n) { + r(n); + } + } + function Xf(e) { + e.emit(cr); + } + function pi(e) { + return e && e.setHeader && typeof e.abort == "function"; + } + function _i(e) { + e.emit("close"); + } + function Jf(e, t) { + e.emit("error", t), de.nextTick(_i, e); + } + function Qf(e, t) { + !e || $f(e) || (!t && !jf(e) && (t = new qf), Gf(e) ? (e.socket = null, e.destroy(t)) : pi(e) ? e.abort() : pi(e.req) ? e.req.abort() : typeof e.destroy == "function" ? e.destroy(t) : typeof e.close == "function" ? e.close() : t ? de.nextTick(Jf, e, t) : de.nextTick(_i, e), e.destroyed || (e[Wf] = true)); + } + Ei.exports = { construct: Kf, destroyer: Qf, destroy: Hf, undestroy: Yf, errorOrDestroy: hr }; + }); + Et = E((td, pr) => { + var Pe = typeof Reflect == "object" ? Reflect : null, Si = Pe && typeof Pe.apply == "function" ? Pe.apply : function(t, r, n) { + return Function.prototype.apply.call(t, r, n); + }, gt; + Pe && typeof Pe.ownKeys == "function" ? gt = Pe.ownKeys : Object.getOwnPropertySymbols ? gt = function(t) { + return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t)); + } : gt = function(t) { + return Object.getOwnPropertyNames(t); + }; + function Zf(e) { + console && console.warn && console.warn(e); + } + var xi = Number.isNaN || function(t) { + return t !== t; + }; + function S() { + S.init.call(this); + } + pr.exports = S; + pr.exports.once = ns; + S.EventEmitter = S; + S.prototype._events = undefined; + S.prototype._eventsCount = 0; + S.prototype._maxListeners = undefined; + var mi = 10; + function _t(e) { + if (typeof e != "function") + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof e); + } + Object.defineProperty(S, "defaultMaxListeners", { enumerable: true, get: function() { + return mi; + }, set: function(e) { + if (typeof e != "number" || e < 0 || xi(e)) + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + e + "."); + mi = e; + } }); + S.init = function() { + (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) && (this._events = Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || undefined; + }; + S.prototype.setMaxListeners = function(t) { + if (typeof t != "number" || t < 0 || xi(t)) + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + t + "."); + return this._maxListeners = t, this; + }; + function Ri(e) { + return e._maxListeners === undefined ? S.defaultMaxListeners : e._maxListeners; + } + S.prototype.getMaxListeners = function() { + return Ri(this); + }; + S.prototype.emit = function(t) { + for (var r = [], n = 1;n < arguments.length; n++) + r.push(arguments[n]); + var i = t === "error", o = this._events; + if (o !== undefined) + i = i && o.error === undefined; + else if (!i) + return false; + if (i) { + var l; + if (r.length > 0 && (l = r[0]), l instanceof Error) + throw l; + var u = new Error("Unhandled error." + (l ? " (" + l.message + ")" : "")); + throw u.context = l, u; + } + var f = o[t]; + if (f === undefined) + return false; + if (typeof f == "function") + Si(f, this, r); + else + for (var s = f.length, d = Li(f, s), n = 0;n < s; ++n) + Si(d[n], this, r); + return true; + }; + function Ai(e, t, r, n) { + var i, o, l; + if (_t(r), o = e._events, o === undefined ? (o = e._events = Object.create(null), e._eventsCount = 0) : (o.newListener !== undefined && (e.emit("newListener", t, r.listener ? r.listener : r), o = e._events), l = o[t]), l === undefined) + l = o[t] = r, ++e._eventsCount; + else if (typeof l == "function" ? l = o[t] = n ? [r, l] : [l, r] : n ? l.unshift(r) : l.push(r), i = Ri(e), i > 0 && l.length > i && !l.warned) { + l.warned = true; + var u = new Error("Possible EventEmitter memory leak detected. " + l.length + " " + String(t) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + u.name = "MaxListenersExceededWarning", u.emitter = e, u.type = t, u.count = l.length, Zf(u); + } + return e; + } + S.prototype.addListener = function(t, r) { + return Ai(this, t, r, false); + }; + S.prototype.on = S.prototype.addListener; + S.prototype.prependListener = function(t, r) { + return Ai(this, t, r, true); + }; + function es() { + if (!this.fired) + return this.target.removeListener(this.type, this.wrapFn), this.fired = true, arguments.length === 0 ? this.listener.call(this.target) : this.listener.apply(this.target, arguments); + } + function Ii(e, t, r) { + var n = { fired: false, wrapFn: undefined, target: e, type: t, listener: r }, i = es.bind(n); + return i.listener = r, n.wrapFn = i, i; + } + S.prototype.once = function(t, r) { + return _t(r), this.on(t, Ii(this, t, r)), this; + }; + S.prototype.prependOnceListener = function(t, r) { + return _t(r), this.prependListener(t, Ii(this, t, r)), this; + }; + S.prototype.removeListener = function(t, r) { + var n, i, o, l, u; + if (_t(r), i = this._events, i === undefined) + return this; + if (n = i[t], n === undefined) + return this; + if (n === r || n.listener === r) + --this._eventsCount === 0 ? this._events = Object.create(null) : (delete i[t], i.removeListener && this.emit("removeListener", t, n.listener || r)); + else if (typeof n != "function") { + for (o = -1, l = n.length - 1;l >= 0; l--) + if (n[l] === r || n[l].listener === r) { + u = n[l].listener, o = l; + break; + } + if (o < 0) + return this; + o === 0 ? n.shift() : ts(n, o), n.length === 1 && (i[t] = n[0]), i.removeListener !== undefined && this.emit("removeListener", t, u || r); + } + return this; + }; + S.prototype.off = S.prototype.removeListener; + S.prototype.removeAllListeners = function(t) { + var r, n, i; + if (n = this._events, n === undefined) + return this; + if (n.removeListener === undefined) + return arguments.length === 0 ? (this._events = Object.create(null), this._eventsCount = 0) : n[t] !== undefined && (--this._eventsCount === 0 ? this._events = Object.create(null) : delete n[t]), this; + if (arguments.length === 0) { + var o = Object.keys(n), l; + for (i = 0;i < o.length; ++i) + l = o[i], l !== "removeListener" && this.removeAllListeners(l); + return this.removeAllListeners("removeListener"), this._events = Object.create(null), this._eventsCount = 0, this; + } + if (r = n[t], typeof r == "function") + this.removeListener(t, r); + else if (r !== undefined) + for (i = r.length - 1;i >= 0; i--) + this.removeListener(t, r[i]); + return this; + }; + function Ti(e, t, r) { + var n = e._events; + if (n === undefined) + return []; + var i = n[t]; + return i === undefined ? [] : typeof i == "function" ? r ? [i.listener || i] : [i] : r ? rs(i) : Li(i, i.length); + } + S.prototype.listeners = function(t) { + return Ti(this, t, true); + }; + S.prototype.rawListeners = function(t) { + return Ti(this, t, false); + }; + S.listenerCount = function(e, t) { + return typeof e.listenerCount == "function" ? e.listenerCount(t) : Bi.call(e, t); + }; + S.prototype.listenerCount = Bi; + function Bi(e) { + var t = this._events; + if (t !== undefined) { + var r = t[e]; + if (typeof r == "function") + return 1; + if (r !== undefined) + return r.length; + } + return 0; + } + S.prototype.eventNames = function() { + return this._eventsCount > 0 ? gt(this._events) : []; + }; + function Li(e, t) { + for (var r = new Array(t), n = 0;n < t; ++n) + r[n] = e[n]; + return r; + } + function ts(e, t) { + for (;t + 1 < e.length; t++) + e[t] = e[t + 1]; + e.pop(); + } + function rs(e) { + for (var t = new Array(e.length), r = 0;r < t.length; ++r) + t[r] = e[r].listener || e[r]; + return t; + } + function ns(e, t) { + return new Promise(function(r, n) { + function i(l) { + e.removeListener(t, o), n(l); + } + function o() { + typeof e.removeListener == "function" && e.removeListener("error", i), r([].slice.call(arguments)); + } + Ni(e, t, o, { once: true }), t !== "error" && is(e, i, { once: true }); + }); + } + function is(e, t, r) { + typeof e.on == "function" && Ni(e, "error", t, r); + } + function Ni(e, t, r, n) { + if (typeof e.on == "function") + n.once ? e.once(t, r) : e.on(t, r); + else if (typeof e.addEventListener == "function") + e.addEventListener(t, function i(o) { + n.once && e.removeEventListener(t, i), r(o); + }); + else + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof e); + } + }); + xt = E((rd, Mi) => { + var { ArrayIsArray: os, ObjectSetPrototypeOf: Fi } = I(), { EventEmitter: St } = Et(); + function mt(e) { + St.call(this, e); + } + Fi(mt.prototype, St.prototype); + Fi(mt, St); + mt.prototype.pipe = function(e, t) { + let r = this; + function n(d) { + e.writable && e.write(d) === false && r.pause && r.pause(); + } + r.on("data", n); + function i() { + r.readable && r.resume && r.resume(); + } + e.on("drain", i), !e._isStdio && (!t || t.end !== false) && (r.on("end", l), r.on("close", u)); + let o = false; + function l() { + o || (o = true, e.end()); + } + function u() { + o || (o = true, typeof e.destroy == "function" && e.destroy()); + } + function f(d) { + s(), St.listenerCount(this, "error") === 0 && this.emit("error", d); + } + yr(r, "error", f), yr(e, "error", f); + function s() { + r.removeListener("data", n), e.removeListener("drain", i), r.removeListener("end", l), r.removeListener("close", u), r.removeListener("error", f), e.removeListener("error", f), r.removeListener("end", s), r.removeListener("close", s), e.removeListener("close", s); + } + return r.on("end", s), r.on("close", s), e.on("close", s), e.emit("pipe", r), e; + }; + function yr(e, t, r) { + if (typeof e.prependListener == "function") + return e.prependListener(t, r); + !e._events || !e._events[t] ? e.on(t, r) : os(e._events[t]) ? e._events[t].unshift(r) : e._events[t] = [r, e._events[t]]; + } + Mi.exports = { Stream: mt, prependListener: yr }; + }); + At = E((nd, Rt) => { + var { AbortError: ls, codes: us } = C(), fs = ce(), { ERR_INVALID_ARG_TYPE: Ci } = us, ss = (e, t) => { + if (typeof e != "object" || !("aborted" in e)) + throw new Ci(t, "AbortSignal", e); + }; + function as(e) { + return !!(e && typeof e.pipe == "function"); + } + Rt.exports.addAbortSignal = function(t, r) { + if (ss(t, "signal"), !as(r)) + throw new Ci("stream", "stream.Stream", r); + return Rt.exports.addAbortSignalNoValidate(t, r); + }; + Rt.exports.addAbortSignalNoValidate = function(e, t) { + if (typeof e != "object" || !("aborted" in e)) + return t; + let r = () => { + t.destroy(new ls(undefined, { cause: e.reason })); + }; + return e.aborted ? r() : (e.addEventListener("abort", r), fs(t, () => e.removeEventListener("abort", r))), t; + }; + }); + Pi = E((od, Di) => { + var { StringPrototypeSlice: Oi, SymbolIterator: cs, TypedArrayPrototypeSet: It, Uint8Array: ds } = I(), { Buffer: wr } = te(), { inspect: hs } = V(); + Di.exports = class { + constructor() { + this.head = null, this.tail = null, this.length = 0; + } + push(t) { + let r = { data: t, next: null }; + this.length > 0 ? this.tail.next = r : this.head = r, this.tail = r, ++this.length; + } + unshift(t) { + let r = { data: t, next: this.head }; + this.length === 0 && (this.tail = r), this.head = r, ++this.length; + } + shift() { + if (this.length === 0) + return; + let t = this.head.data; + return this.length === 1 ? this.head = this.tail = null : this.head = this.head.next, --this.length, t; + } + clear() { + this.head = this.tail = null, this.length = 0; + } + join(t) { + if (this.length === 0) + return ""; + let r = this.head, n = "" + r.data; + for (;(r = r.next) !== null; ) + n += t + r.data; + return n; + } + concat(t) { + if (this.length === 0) + return wr.alloc(0); + let r = wr.allocUnsafe(t >>> 0), n = this.head, i = 0; + for (;n; ) + It(r, n.data, i), i += n.data.length, n = n.next; + return r; + } + consume(t, r) { + let n = this.head.data; + if (t < n.length) { + let i = n.slice(0, t); + return this.head.data = n.slice(t), i; + } + return t === n.length ? this.shift() : r ? this._getString(t) : this._getBuffer(t); + } + first() { + return this.head.data; + } + *[cs]() { + for (let t = this.head;t; t = t.next) + yield t.data; + } + _getString(t) { + let r = "", n = this.head, i = 0; + do { + let o = n.data; + if (t > o.length) + r += o, t -= o.length; + else { + t === o.length ? (r += o, ++i, n.next ? this.head = n.next : this.head = this.tail = null) : (r += Oi(o, 0, t), this.head = n, n.data = Oi(o, t)); + break; + } + ++i; + } while ((n = n.next) !== null); + return this.length -= i, r; + } + _getBuffer(t) { + let r = wr.allocUnsafe(t), n = t, i = this.head, o = 0; + do { + let l = i.data; + if (t > l.length) + It(r, l, n - t), t -= l.length; + else { + t === l.length ? (It(r, l, n - t), ++o, i.next ? this.head = i.next : this.head = this.tail = null) : (It(r, new ds(l.buffer, l.byteOffset, t), n - t), this.head = i, i.data = l.slice(t)); + break; + } + ++o; + } while ((i = i.next) !== null); + return this.length -= o, r; + } + [Symbol.for("nodejs.util.inspect.custom")](t, r) { + return hs(this, { ...r, depth: 0, customInspect: false }); + } + }; + }); + Tt = E((ld, Ui) => { + var { MathFloor: ps, NumberIsInteger: ys } = I(), { ERR_INVALID_ARG_VALUE: ws } = C().codes; + function bs(e, t, r) { + return e.highWaterMark != null ? e.highWaterMark : t ? e[r] : null; + } + function ki(e) { + return e ? 16 : 16 * 1024; + } + function gs(e, t, r, n) { + let i = bs(t, n, r); + if (i != null) { + if (!ys(i) || i < 0) { + let o = n ? `options.${r}` : "options.highWaterMark"; + throw new ws(o, i); + } + return ps(i); + } + return ki(e.objectMode); + } + Ui.exports = { getHighWaterMark: gs, getDefaultHighWaterMark: ki }; + }); + Wi = E((br, qi) => { + var Bt = te(), X = Bt.Buffer; + function vi(e, t) { + for (var r in e) + t[r] = e[r]; + } + X.from && X.alloc && X.allocUnsafe && X.allocUnsafeSlow ? qi.exports = Bt : (vi(Bt, br), br.Buffer = me); + function me(e, t, r) { + return X(e, t, r); + } + me.prototype = Object.create(X.prototype); + vi(X, me); + me.from = function(e, t, r) { + if (typeof e == "number") + throw new TypeError("Argument must not be a number"); + return X(e, t, r); + }; + me.alloc = function(e, t, r) { + if (typeof e != "number") + throw new TypeError("Argument must be a number"); + var n = X(e); + return t !== undefined ? typeof r == "string" ? n.fill(t, r) : n.fill(t) : n.fill(0), n; + }; + me.allocUnsafe = function(e) { + if (typeof e != "number") + throw new TypeError("Argument must be a number"); + return X(e); + }; + me.allocUnsafeSlow = function(e) { + if (typeof e != "number") + throw new TypeError("Argument must be a number"); + return Bt.SlowBuffer(e); + }; + }); + Gi = E((ji) => { + var _r = Wi().Buffer, $i = _r.isEncoding || function(e) { + switch (e = "" + e, e && e.toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + case "raw": + return true; + default: + return false; + } + }; + function _s(e) { + if (!e) + return "utf8"; + for (var t;; ) + switch (e) { + case "utf8": + case "utf-8": + return "utf8"; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return "utf16le"; + case "latin1": + case "binary": + return "latin1"; + case "base64": + case "ascii": + case "hex": + return e; + default: + if (t) + return; + e = ("" + e).toLowerCase(), t = true; + } + } + function Es(e) { + var t = _s(e); + if (typeof t != "string" && (_r.isEncoding === $i || !$i(e))) + throw new Error("Unknown encoding: " + e); + return t || e; + } + ji.StringDecoder = Ye; + function Ye(e) { + this.encoding = Es(e); + var t; + switch (this.encoding) { + case "utf16le": + this.text = Is, this.end = Ts, t = 4; + break; + case "utf8": + this.fillLast = xs, t = 4; + break; + case "base64": + this.text = Bs, this.end = Ls, t = 3; + break; + default: + this.write = Ns, this.end = Fs; + return; + } + this.lastNeed = 0, this.lastTotal = 0, this.lastChar = _r.allocUnsafe(t); + } + Ye.prototype.write = function(e) { + if (e.length === 0) + return ""; + var t, r; + if (this.lastNeed) { + if (t = this.fillLast(e), t === undefined) + return ""; + r = this.lastNeed, this.lastNeed = 0; + } else + r = 0; + return r < e.length ? t ? t + this.text(e, r) : this.text(e, r) : t || ""; + }; + Ye.prototype.end = As; + Ye.prototype.text = Rs; + Ye.prototype.fillLast = function(e) { + if (this.lastNeed <= e.length) + return e.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal); + e.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, e.length), this.lastNeed -= e.length; + }; + function gr(e) { + return e <= 127 ? 0 : e >> 5 === 6 ? 2 : e >> 4 === 14 ? 3 : e >> 3 === 30 ? 4 : e >> 6 === 2 ? -1 : -2; + } + function Ss(e, t, r) { + var n = t.length - 1; + if (n < r) + return 0; + var i = gr(t[n]); + return i >= 0 ? (i > 0 && (e.lastNeed = i - 1), i) : --n < r || i === -2 ? 0 : (i = gr(t[n]), i >= 0 ? (i > 0 && (e.lastNeed = i - 2), i) : --n < r || i === -2 ? 0 : (i = gr(t[n]), i >= 0 ? (i > 0 && (i === 2 ? i = 0 : e.lastNeed = i - 3), i) : 0)); + } + function ms(e, t, r) { + if ((t[0] & 192) !== 128) + return e.lastNeed = 0, "�"; + if (e.lastNeed > 1 && t.length > 1) { + if ((t[1] & 192) !== 128) + return e.lastNeed = 1, "�"; + if (e.lastNeed > 2 && t.length > 2 && (t[2] & 192) !== 128) + return e.lastNeed = 2, "�"; + } + } + function xs(e) { + var t = this.lastTotal - this.lastNeed, r = ms(this, e, t); + if (r !== undefined) + return r; + if (this.lastNeed <= e.length) + return e.copy(this.lastChar, t, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal); + e.copy(this.lastChar, t, 0, e.length), this.lastNeed -= e.length; + } + function Rs(e, t) { + var r = Ss(this, e, t); + if (!this.lastNeed) + return e.toString("utf8", t); + this.lastTotal = r; + var n = e.length - (r - this.lastNeed); + return e.copy(this.lastChar, 0, n), e.toString("utf8", t, n); + } + function As(e) { + var t = e && e.length ? this.write(e) : ""; + return this.lastNeed ? t + "�" : t; + } + function Is(e, t) { + if ((e.length - t) % 2 === 0) { + var r = e.toString("utf16le", t); + if (r) { + var n = r.charCodeAt(r.length - 1); + if (n >= 55296 && n <= 56319) + return this.lastNeed = 2, this.lastTotal = 4, this.lastChar[0] = e[e.length - 2], this.lastChar[1] = e[e.length - 1], r.slice(0, -1); + } + return r; + } + return this.lastNeed = 1, this.lastTotal = 2, this.lastChar[0] = e[e.length - 1], e.toString("utf16le", t, e.length - 1); + } + function Ts(e) { + var t = e && e.length ? this.write(e) : ""; + if (this.lastNeed) { + var r = this.lastTotal - this.lastNeed; + return t + this.lastChar.toString("utf16le", 0, r); + } + return t; + } + function Bs(e, t) { + var r = (e.length - t) % 3; + return r === 0 ? e.toString("base64", t) : (this.lastNeed = 3 - r, this.lastTotal = 3, r === 1 ? this.lastChar[0] = e[e.length - 1] : (this.lastChar[0] = e[e.length - 2], this.lastChar[1] = e[e.length - 1]), e.toString("base64", t, e.length - r)); + } + function Ls(e) { + var t = e && e.length ? this.write(e) : ""; + return this.lastNeed ? t + this.lastChar.toString("base64", 0, 3 - this.lastNeed) : t; + } + function Ns(e) { + return e.toString(this.encoding); + } + function Fs(e) { + return e && e.length ? this.write(e) : ""; + } + }); + Er = E((fd, Ki) => { + var Hi = (se(), pe(k)), { PromisePrototypeThen: Ms, SymbolAsyncIterator: Vi, SymbolIterator: Yi } = I(), { Buffer: Cs } = te(), { ERR_INVALID_ARG_TYPE: Os, ERR_STREAM_NULL_VALUES: Ds } = C().codes; + function Ps(e, t, r) { + let n; + if (typeof t == "string" || t instanceof Cs) + return new e({ objectMode: true, ...r, read() { + this.push(t), this.push(null); + } }); + let i; + if (t && t[Vi]) + i = true, n = t[Vi](); + else if (t && t[Yi]) + i = false, n = t[Yi](); + else + throw new Os("iterable", ["Iterable"], t); + let o = new e({ objectMode: true, highWaterMark: 1, ...r }), l = false; + o._read = function() { + l || (l = true, f()); + }, o._destroy = function(s, d) { + Ms(u(s), () => Hi.nextTick(d, s), (c) => Hi.nextTick(d, c || s)); + }; + async function u(s) { + let d = s != null, c = typeof n.throw == "function"; + if (d && c) { + let { value: y, done: h } = await n.throw(s); + if (await y, h) + return; + } + if (typeof n.return == "function") { + let { value: y } = await n.return(); + await y; + } + } + async function f() { + for (;; ) { + try { + let { value: s, done: d } = i ? await n.next() : n.next(); + if (d) + o.push(null); + else { + let c = s && typeof s.then == "function" ? await s : s; + if (c === null) + throw l = false, new Ds; + if (o.push(c)) + continue; + l = false; + } + } catch (s) { + o.destroy(s); + } + break; + } + } + return o; + } + Ki.exports = Ps; + }); + Ke = E((sd, uo) => { + var $ = (se(), pe(k)), { ArrayPrototypeIndexOf: ks, NumberIsInteger: Us, NumberIsNaN: vs, NumberParseInt: qs, ObjectDefineProperties: Ji, ObjectKeys: Ws, ObjectSetPrototypeOf: Qi, Promise: $s, SafeSet: js, SymbolAsyncIterator: Gs, Symbol: Hs } = I(); + uo.exports = g; + g.ReadableState = Ir; + var { EventEmitter: Vs } = Et(), { Stream: he, prependListener: Ys } = xt(), { Buffer: Sr } = te(), { addAbortSignal: Ks } = At(), zs = ce(), _2 = V().debuglog("stream", (e) => { + _2 = e; + }), Xs = Pi(), Ue = Se(), { getHighWaterMark: Js, getDefaultHighWaterMark: Qs } = Tt(), { aggregateTwoErrors: zi, codes: { ERR_INVALID_ARG_TYPE: Zs, ERR_METHOD_NOT_IMPLEMENTED: ea, ERR_OUT_OF_RANGE: ta, ERR_STREAM_PUSH_AFTER_EOF: ra, ERR_STREAM_UNSHIFT_AFTER_END_EVENT: na } } = C(), { validateObject: ia } = He(), xe = Hs("kPaused"), { StringDecoder: Zi } = Gi(), oa = Er(); + Qi(g.prototype, he.prototype); + Qi(g, he); + var mr = () => { + }, { errorOrDestroy: ke } = Ue; + function Ir(e, t, r) { + typeof r != "boolean" && (r = t instanceof J()), this.objectMode = !!(e && e.objectMode), r && (this.objectMode = this.objectMode || !!(e && e.readableObjectMode)), this.highWaterMark = e ? Js(this, e, "readableHighWaterMark", r) : Qs(false), this.buffer = new Xs, this.length = 0, this.pipes = [], this.flowing = null, this.ended = false, this.endEmitted = false, this.reading = false, this.constructed = true, this.sync = true, this.needReadable = false, this.emittedReadable = false, this.readableListening = false, this.resumeScheduled = false, this[xe] = null, this.errorEmitted = false, this.emitClose = !e || e.emitClose !== false, this.autoDestroy = !e || e.autoDestroy !== false, this.destroyed = false, this.errored = null, this.closed = false, this.closeEmitted = false, this.defaultEncoding = e && e.defaultEncoding || "utf8", this.awaitDrainWriters = null, this.multiAwaitDrain = false, this.readingMore = false, this.dataEmitted = false, this.decoder = null, this.encoding = null, e && e.encoding && (this.decoder = new Zi(e.encoding), this.encoding = e.encoding); + } + function g(e) { + if (!(this instanceof g)) + return new g(e); + let t = this instanceof J(); + this._readableState = new Ir(e, this, t), e && (typeof e.read == "function" && (this._read = e.read), typeof e.destroy == "function" && (this._destroy = e.destroy), typeof e.construct == "function" && (this._construct = e.construct), e.signal && !t && Ks(e.signal, this)), he.call(this, e), Ue.construct(this, () => { + this._readableState.needReadable && Lt(this, this._readableState); + }); + } + g.prototype.destroy = Ue.destroy; + g.prototype._undestroy = Ue.undestroy; + g.prototype._destroy = function(e, t) { + t(e); + }; + g.prototype[Vs.captureRejectionSymbol] = function(e) { + this.destroy(e); + }; + g.prototype.push = function(e, t) { + return eo(this, e, t, false); + }; + g.prototype.unshift = function(e, t) { + return eo(this, e, t, true); + }; + function eo(e, t, r, n) { + _2("readableAddChunk", t); + let i = e._readableState, o; + if (i.objectMode || (typeof t == "string" ? (r = r || i.defaultEncoding, i.encoding !== r && (n && i.encoding ? t = Sr.from(t, r).toString(i.encoding) : (t = Sr.from(t, r), r = ""))) : t instanceof Sr ? r = "" : he._isUint8Array(t) ? (t = he._uint8ArrayToBuffer(t), r = "") : t != null && (o = new Zs("chunk", ["string", "Buffer", "Uint8Array"], t))), o) + ke(e, o); + else if (t === null) + i.reading = false, fa(e, i); + else if (i.objectMode || t && t.length > 0) + if (n) + if (i.endEmitted) + ke(e, new na); + else { + if (i.destroyed || i.errored) + return false; + xr(e, i, t, true); + } + else if (i.ended) + ke(e, new ra); + else { + if (i.destroyed || i.errored) + return false; + i.reading = false, i.decoder && !r ? (t = i.decoder.write(t), i.objectMode || t.length !== 0 ? xr(e, i, t, false) : Lt(e, i)) : xr(e, i, t, false); + } + else + n || (i.reading = false, Lt(e, i)); + return !i.ended && (i.length < i.highWaterMark || i.length === 0); + } + function xr(e, t, r, n) { + t.flowing && t.length === 0 && !t.sync && e.listenerCount("data") > 0 ? (t.multiAwaitDrain ? t.awaitDrainWriters.clear() : t.awaitDrainWriters = null, t.dataEmitted = true, e.emit("data", r)) : (t.length += t.objectMode ? 1 : r.length, n ? t.buffer.unshift(r) : t.buffer.push(r), t.needReadable && Nt(e)), Lt(e, t); + } + g.prototype.isPaused = function() { + let e = this._readableState; + return e[xe] === true || e.flowing === false; + }; + g.prototype.setEncoding = function(e) { + let t = new Zi(e); + this._readableState.decoder = t, this._readableState.encoding = this._readableState.decoder.encoding; + let r = this._readableState.buffer, n = ""; + for (let i of r) + n += t.write(i); + return r.clear(), n !== "" && r.push(n), this._readableState.length = n.length, this; + }; + var la = 1073741824; + function ua(e) { + if (e > la) + throw new ta("size", "<= 1GiB", e); + return e--, e |= e >>> 1, e |= e >>> 2, e |= e >>> 4, e |= e >>> 8, e |= e >>> 16, e++, e; + } + function Xi(e, t) { + return e <= 0 || t.length === 0 && t.ended ? 0 : t.objectMode ? 1 : vs(e) ? t.flowing && t.length ? t.buffer.first().length : t.length : e <= t.length ? e : t.ended ? t.length : 0; + } + g.prototype.read = function(e) { + _2("read", e), e === undefined ? e = NaN : Us(e) || (e = qs(e, 10)); + let t = this._readableState, r = e; + if (e > t.highWaterMark && (t.highWaterMark = ua(e)), e !== 0 && (t.emittedReadable = false), e === 0 && t.needReadable && ((t.highWaterMark !== 0 ? t.length >= t.highWaterMark : t.length > 0) || t.ended)) + return _2("read: emitReadable", t.length, t.ended), t.length === 0 && t.ended ? Rr(this) : Nt(this), null; + if (e = Xi(e, t), e === 0 && t.ended) + return t.length === 0 && Rr(this), null; + let n = t.needReadable; + if (_2("need readable", n), (t.length === 0 || t.length - e < t.highWaterMark) && (n = true, _2("length less than watermark", n)), t.ended || t.reading || t.destroyed || t.errored || !t.constructed) + n = false, _2("reading, ended or constructing", n); + else if (n) { + _2("do read"), t.reading = true, t.sync = true, t.length === 0 && (t.needReadable = true); + try { + this._read(t.highWaterMark); + } catch (o) { + ke(this, o); + } + t.sync = false, t.reading || (e = Xi(r, t)); + } + let i; + return e > 0 ? i = oo(e, t) : i = null, i === null ? (t.needReadable = t.length <= t.highWaterMark, e = 0) : (t.length -= e, t.multiAwaitDrain ? t.awaitDrainWriters.clear() : t.awaitDrainWriters = null), t.length === 0 && (t.ended || (t.needReadable = true), r !== e && t.ended && Rr(this)), i !== null && !t.errorEmitted && !t.closeEmitted && (t.dataEmitted = true, this.emit("data", i)), i; + }; + function fa(e, t) { + if (_2("onEofChunk"), !t.ended) { + if (t.decoder) { + let r = t.decoder.end(); + r && r.length && (t.buffer.push(r), t.length += t.objectMode ? 1 : r.length); + } + t.ended = true, t.sync ? Nt(e) : (t.needReadable = false, t.emittedReadable = true, to(e)); + } + } + function Nt(e) { + let t = e._readableState; + _2("emitReadable", t.needReadable, t.emittedReadable), t.needReadable = false, t.emittedReadable || (_2("emitReadable", t.flowing), t.emittedReadable = true, $.nextTick(to, e)); + } + function to(e) { + let t = e._readableState; + _2("emitReadable_", t.destroyed, t.length, t.ended), !t.destroyed && !t.errored && (t.length || t.ended) && (e.emit("readable"), t.emittedReadable = false), t.needReadable = !t.flowing && !t.ended && t.length <= t.highWaterMark, no(e); + } + function Lt(e, t) { + !t.readingMore && t.constructed && (t.readingMore = true, $.nextTick(sa, e, t)); + } + function sa(e, t) { + for (;!t.reading && !t.ended && (t.length < t.highWaterMark || t.flowing && t.length === 0); ) { + let r = t.length; + if (_2("maybeReadMore read 0"), e.read(0), r === t.length) + break; + } + t.readingMore = false; + } + g.prototype._read = function(e) { + throw new ea("_read()"); + }; + g.prototype.pipe = function(e, t) { + let r = this, n = this._readableState; + n.pipes.length === 1 && (n.multiAwaitDrain || (n.multiAwaitDrain = true, n.awaitDrainWriters = new js(n.awaitDrainWriters ? [n.awaitDrainWriters] : []))), n.pipes.push(e), _2("pipe count=%d opts=%j", n.pipes.length, t); + let o = (!t || t.end !== false) && e !== $.stdout && e !== $.stderr ? u : v; + n.endEmitted ? $.nextTick(o) : r.once("end", o), e.on("unpipe", l); + function l(w, b) { + _2("onunpipe"), w === r && b && b.hasUnpiped === false && (b.hasUnpiped = true, d()); + } + function u() { + _2("onend"), e.end(); + } + let f, s = false; + function d() { + _2("cleanup"), e.removeListener("close", p), e.removeListener("finish", B), f && e.removeListener("drain", f), e.removeListener("error", h), e.removeListener("unpipe", l), r.removeListener("end", u), r.removeListener("end", v), r.removeListener("data", y), s = true, f && n.awaitDrainWriters && (!e._writableState || e._writableState.needDrain) && f(); + } + function c() { + s || (n.pipes.length === 1 && n.pipes[0] === e ? (_2("false write response, pause", 0), n.awaitDrainWriters = e, n.multiAwaitDrain = false) : n.pipes.length > 1 && n.pipes.includes(e) && (_2("false write response, pause", n.awaitDrainWriters.size), n.awaitDrainWriters.add(e)), r.pause()), f || (f = aa(r, e), e.on("drain", f)); + } + r.on("data", y); + function y(w) { + _2("ondata"); + let b = e.write(w); + _2("dest.write", b), b === false && c(); + } + function h(w) { + if (_2("onerror", w), v(), e.removeListener("error", h), e.listenerCount("error") === 0) { + let b = e._writableState || e._readableState; + b && !b.errorEmitted ? ke(e, w) : e.emit("error", w); + } + } + Ys(e, "error", h); + function p() { + e.removeListener("finish", B), v(); + } + e.once("close", p); + function B() { + _2("onfinish"), e.removeListener("close", p), v(); + } + e.once("finish", B); + function v() { + _2("unpipe"), r.unpipe(e); + } + return e.emit("pipe", r), e.writableNeedDrain === true ? n.flowing && c() : n.flowing || (_2("pipe resume"), r.resume()), e; + }; + function aa(e, t) { + return function() { + let n = e._readableState; + n.awaitDrainWriters === t ? (_2("pipeOnDrain", 1), n.awaitDrainWriters = null) : n.multiAwaitDrain && (_2("pipeOnDrain", n.awaitDrainWriters.size), n.awaitDrainWriters.delete(t)), (!n.awaitDrainWriters || n.awaitDrainWriters.size === 0) && e.listenerCount("data") && e.resume(); + }; + } + g.prototype.unpipe = function(e) { + let t = this._readableState, r = { hasUnpiped: false }; + if (t.pipes.length === 0) + return this; + if (!e) { + let i = t.pipes; + t.pipes = [], this.pause(); + for (let o = 0;o < i.length; o++) + i[o].emit("unpipe", this, { hasUnpiped: false }); + return this; + } + let n = ks(t.pipes, e); + return n === -1 ? this : (t.pipes.splice(n, 1), t.pipes.length === 0 && this.pause(), e.emit("unpipe", this, r), this); + }; + g.prototype.on = function(e, t) { + let r = he.prototype.on.call(this, e, t), n = this._readableState; + return e === "data" ? (n.readableListening = this.listenerCount("readable") > 0, n.flowing !== false && this.resume()) : e === "readable" && !n.endEmitted && !n.readableListening && (n.readableListening = n.needReadable = true, n.flowing = false, n.emittedReadable = false, _2("on readable", n.length, n.reading), n.length ? Nt(this) : n.reading || $.nextTick(ca, this)), r; + }; + g.prototype.addListener = g.prototype.on; + g.prototype.removeListener = function(e, t) { + let r = he.prototype.removeListener.call(this, e, t); + return e === "readable" && $.nextTick(ro, this), r; + }; + g.prototype.off = g.prototype.removeListener; + g.prototype.removeAllListeners = function(e) { + let t = he.prototype.removeAllListeners.apply(this, arguments); + return (e === "readable" || e === undefined) && $.nextTick(ro, this), t; + }; + function ro(e) { + let t = e._readableState; + t.readableListening = e.listenerCount("readable") > 0, t.resumeScheduled && t[xe] === false ? t.flowing = true : e.listenerCount("data") > 0 ? e.resume() : t.readableListening || (t.flowing = null); + } + function ca(e) { + _2("readable nexttick read 0"), e.read(0); + } + g.prototype.resume = function() { + let e = this._readableState; + return e.flowing || (_2("resume"), e.flowing = !e.readableListening, da(this, e)), e[xe] = false, this; + }; + function da(e, t) { + t.resumeScheduled || (t.resumeScheduled = true, $.nextTick(ha, e, t)); + } + function ha(e, t) { + _2("resume", t.reading), t.reading || e.read(0), t.resumeScheduled = false, e.emit("resume"), no(e), t.flowing && !t.reading && e.read(0); + } + g.prototype.pause = function() { + return _2("call pause flowing=%j", this._readableState.flowing), this._readableState.flowing !== false && (_2("pause"), this._readableState.flowing = false, this.emit("pause")), this._readableState[xe] = true, this; + }; + function no(e) { + let t = e._readableState; + for (_2("flow", t.flowing);t.flowing && e.read() !== null; ) + ; + } + g.prototype.wrap = function(e) { + let t = false; + e.on("data", (n) => { + !this.push(n) && e.pause && (t = true, e.pause()); + }), e.on("end", () => { + this.push(null); + }), e.on("error", (n) => { + ke(this, n); + }), e.on("close", () => { + this.destroy(); + }), e.on("destroy", () => { + this.destroy(); + }), this._read = () => { + t && e.resume && (t = false, e.resume()); + }; + let r = Ws(e); + for (let n = 1;n < r.length; n++) { + let i = r[n]; + this[i] === undefined && typeof e[i] == "function" && (this[i] = e[i].bind(e)); + } + return this; + }; + g.prototype[Gs] = function() { + return io(this); + }; + g.prototype.iterator = function(e) { + return e !== undefined && ia(e, "options"), io(this, e); + }; + function io(e, t) { + typeof e.read != "function" && (e = g.wrap(e, { objectMode: true })); + let r = pa(e, t); + return r.stream = e, r; + } + async function* pa(e, t) { + let r = mr; + function n(l) { + this === e ? (r(), r = mr) : r = l; + } + e.on("readable", n); + let i, o = zs(e, { writable: false }, (l) => { + i = l ? zi(i, l) : null, r(), r = mr; + }); + try { + for (;; ) { + let l = e.destroyed ? null : e.read(); + if (l !== null) + yield l; + else { + if (i) + throw i; + if (i === null) + return; + await new $s(n); + } + } + } catch (l) { + throw i = zi(i, l), i; + } finally { + (i || t?.destroyOnReturn !== false) && (i === undefined || e._readableState.autoDestroy) ? Ue.destroyer(e, null) : (e.off("readable", n), o()); + } + } + Ji(g.prototype, { readable: { __proto__: null, get() { + let e = this._readableState; + return !!e && e.readable !== false && !e.destroyed && !e.errorEmitted && !e.endEmitted; + }, set(e) { + this._readableState && (this._readableState.readable = !!e); + } }, readableDidRead: { __proto__: null, enumerable: false, get: function() { + return this._readableState.dataEmitted; + } }, readableAborted: { __proto__: null, enumerable: false, get: function() { + return !!(this._readableState.readable !== false && (this._readableState.destroyed || this._readableState.errored) && !this._readableState.endEmitted); + } }, readableHighWaterMark: { __proto__: null, enumerable: false, get: function() { + return this._readableState.highWaterMark; + } }, readableBuffer: { __proto__: null, enumerable: false, get: function() { + return this._readableState && this._readableState.buffer; + } }, readableFlowing: { __proto__: null, enumerable: false, get: function() { + return this._readableState.flowing; + }, set: function(e) { + this._readableState && (this._readableState.flowing = e); + } }, readableLength: { __proto__: null, enumerable: false, get() { + return this._readableState.length; + } }, readableObjectMode: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.objectMode : false; + } }, readableEncoding: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.encoding : null; + } }, errored: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.errored : null; + } }, closed: { __proto__: null, get() { + return this._readableState ? this._readableState.closed : false; + } }, destroyed: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.destroyed : false; + }, set(e) { + !this._readableState || (this._readableState.destroyed = e); + } }, readableEnded: { __proto__: null, enumerable: false, get() { + return this._readableState ? this._readableState.endEmitted : false; + } } }); + Ji(Ir.prototype, { pipesCount: { __proto__: null, get() { + return this.pipes.length; + } }, paused: { __proto__: null, get() { + return this[xe] !== false; + }, set(e) { + this[xe] = !!e; + } } }); + g._fromList = oo; + function oo(e, t) { + if (t.length === 0) + return null; + let r; + return t.objectMode ? r = t.buffer.shift() : !e || e >= t.length ? (t.decoder ? r = t.buffer.join("") : t.buffer.length === 1 ? r = t.buffer.first() : r = t.buffer.concat(t.length), t.buffer.clear()) : r = t.buffer.consume(e, t.decoder), r; + } + function Rr(e) { + let t = e._readableState; + _2("endReadable", t.endEmitted), t.endEmitted || (t.ended = true, $.nextTick(ya, t, e)); + } + function ya(e, t) { + if (_2("endReadableNT", e.endEmitted, e.length), !e.errored && !e.closeEmitted && !e.endEmitted && e.length === 0) { + if (e.endEmitted = true, t.emit("end"), t.writable && t.allowHalfOpen === false) + $.nextTick(wa, t); + else if (e.autoDestroy) { + let r = t._writableState; + (!r || r.autoDestroy && (r.finished || r.writable === false)) && t.destroy(); + } + } + } + function wa(e) { + e.writable && !e.writableEnded && !e.destroyed && e.end(); + } + g.from = function(e, t) { + return oa(g, e, t); + }; + var Ar; + function lo() { + return Ar === undefined && (Ar = {}), Ar; + } + g.fromWeb = function(e, t) { + return lo().newStreamReadableFromReadableStream(e, t); + }; + g.toWeb = function(e, t) { + return lo().newReadableStreamFromStreamReadable(e, t); + }; + g.wrap = function(e, t) { + var r, n; + return new g({ objectMode: (r = (n = e.readableObjectMode) !== null && n !== undefined ? n : e.objectMode) !== null && r !== undefined ? r : true, ...t, destroy(i, o) { + Ue.destroyer(e, i), o(i); + } }).wrap(e); + }; + }); + Cr = E((ad, Eo) => { + var Re = (se(), pe(k)), { ArrayPrototypeSlice: ao, Error: ba, FunctionPrototypeSymbolHasInstance: co, ObjectDefineProperty: ho, ObjectDefineProperties: ga, ObjectSetPrototypeOf: po, StringPrototypeToLowerCase: _a, Symbol: Ea, SymbolHasInstance: Sa } = I(); + Eo.exports = m; + m.WritableState = Je; + var { EventEmitter: ma } = Et(), ze = xt().Stream, { Buffer: Ft } = te(), Ot = Se(), { addAbortSignal: xa } = At(), { getHighWaterMark: Ra, getDefaultHighWaterMark: Aa } = Tt(), { ERR_INVALID_ARG_TYPE: Ia, ERR_METHOD_NOT_IMPLEMENTED: Ta, ERR_MULTIPLE_CALLBACK: yo, ERR_STREAM_CANNOT_PIPE: Ba, ERR_STREAM_DESTROYED: Xe, ERR_STREAM_ALREADY_FINISHED: La, ERR_STREAM_NULL_VALUES: Na, ERR_STREAM_WRITE_AFTER_END: Fa, ERR_UNKNOWN_ENCODING: wo } = C().codes, { errorOrDestroy: ve } = Ot; + po(m.prototype, ze.prototype); + po(m, ze); + function Lr() { + } + var qe = Ea("kOnFinished"); + function Je(e, t, r) { + typeof r != "boolean" && (r = t instanceof J()), this.objectMode = !!(e && e.objectMode), r && (this.objectMode = this.objectMode || !!(e && e.writableObjectMode)), this.highWaterMark = e ? Ra(this, e, "writableHighWaterMark", r) : Aa(false), this.finalCalled = false, this.needDrain = false, this.ending = false, this.ended = false, this.finished = false, this.destroyed = false; + let n = !!(e && e.decodeStrings === false); + this.decodeStrings = !n, this.defaultEncoding = e && e.defaultEncoding || "utf8", this.length = 0, this.writing = false, this.corked = 0, this.sync = true, this.bufferProcessing = false, this.onwrite = Ca.bind(undefined, t), this.writecb = null, this.writelen = 0, this.afterWriteTickInfo = null, Ct(this), this.pendingcb = 0, this.constructed = true, this.prefinished = false, this.errorEmitted = false, this.emitClose = !e || e.emitClose !== false, this.autoDestroy = !e || e.autoDestroy !== false, this.errored = null, this.closed = false, this.closeEmitted = false, this[qe] = []; + } + function Ct(e) { + e.buffered = [], e.bufferedIndex = 0, e.allBuffers = true, e.allNoop = true; + } + Je.prototype.getBuffer = function() { + return ao(this.buffered, this.bufferedIndex); + }; + ho(Je.prototype, "bufferedRequestCount", { __proto__: null, get() { + return this.buffered.length - this.bufferedIndex; + } }); + function m(e) { + let t = this instanceof J(); + if (!t && !co(m, this)) + return new m(e); + this._writableState = new Je(e, this, t), e && (typeof e.write == "function" && (this._write = e.write), typeof e.writev == "function" && (this._writev = e.writev), typeof e.destroy == "function" && (this._destroy = e.destroy), typeof e.final == "function" && (this._final = e.final), typeof e.construct == "function" && (this._construct = e.construct), e.signal && xa(e.signal, this)), ze.call(this, e), Ot.construct(this, () => { + let r = this._writableState; + r.writing || Fr(this, r), Mr(this, r); + }); + } + ho(m, Sa, { __proto__: null, value: function(e) { + return co(this, e) ? true : this !== m ? false : e && e._writableState instanceof Je; + } }); + m.prototype.pipe = function() { + ve(this, new Ba); + }; + function bo(e, t, r, n) { + let i = e._writableState; + if (typeof r == "function") + n = r, r = i.defaultEncoding; + else { + if (!r) + r = i.defaultEncoding; + else if (r !== "buffer" && !Ft.isEncoding(r)) + throw new wo(r); + typeof n != "function" && (n = Lr); + } + if (t === null) + throw new Na; + if (!i.objectMode) + if (typeof t == "string") + i.decodeStrings !== false && (t = Ft.from(t, r), r = "buffer"); + else if (t instanceof Ft) + r = "buffer"; + else if (ze._isUint8Array(t)) + t = ze._uint8ArrayToBuffer(t), r = "buffer"; + else + throw new Ia("chunk", ["string", "Buffer", "Uint8Array"], t); + let o; + return i.ending ? o = new Fa : i.destroyed && (o = new Xe("write")), o ? (Re.nextTick(n, o), ve(e, o, true), o) : (i.pendingcb++, Ma(e, i, t, r, n)); + } + m.prototype.write = function(e, t, r) { + return bo(this, e, t, r) === true; + }; + m.prototype.cork = function() { + this._writableState.corked++; + }; + m.prototype.uncork = function() { + let e = this._writableState; + e.corked && (e.corked--, e.writing || Fr(this, e)); + }; + m.prototype.setDefaultEncoding = function(t) { + if (typeof t == "string" && (t = _a(t)), !Ft.isEncoding(t)) + throw new wo(t); + return this._writableState.defaultEncoding = t, this; + }; + function Ma(e, t, r, n, i) { + let o = t.objectMode ? 1 : r.length; + t.length += o; + let l = t.length < t.highWaterMark; + return l || (t.needDrain = true), t.writing || t.corked || t.errored || !t.constructed ? (t.buffered.push({ chunk: r, encoding: n, callback: i }), t.allBuffers && n !== "buffer" && (t.allBuffers = false), t.allNoop && i !== Lr && (t.allNoop = false)) : (t.writelen = o, t.writecb = i, t.writing = true, t.sync = true, e._write(r, n, t.onwrite), t.sync = false), l && !t.errored && !t.destroyed; + } + function fo(e, t, r, n, i, o, l) { + t.writelen = n, t.writecb = l, t.writing = true, t.sync = true, t.destroyed ? t.onwrite(new Xe("write")) : r ? e._writev(i, t.onwrite) : e._write(i, o, t.onwrite), t.sync = false; + } + function so(e, t, r, n) { + --t.pendingcb, n(r), Nr(t), ve(e, r); + } + function Ca(e, t) { + let r = e._writableState, n = r.sync, i = r.writecb; + if (typeof i != "function") { + ve(e, new yo); + return; + } + r.writing = false, r.writecb = null, r.length -= r.writelen, r.writelen = 0, t ? (t.stack, r.errored || (r.errored = t), e._readableState && !e._readableState.errored && (e._readableState.errored = t), n ? Re.nextTick(so, e, r, t, i) : so(e, r, t, i)) : (r.buffered.length > r.bufferedIndex && Fr(e, r), n ? r.afterWriteTickInfo !== null && r.afterWriteTickInfo.cb === i ? r.afterWriteTickInfo.count++ : (r.afterWriteTickInfo = { count: 1, cb: i, stream: e, state: r }, Re.nextTick(Oa, r.afterWriteTickInfo)) : go(e, r, 1, i)); + } + function Oa({ stream: e, state: t, count: r, cb: n }) { + return t.afterWriteTickInfo = null, go(e, t, r, n); + } + function go(e, t, r, n) { + for (!t.ending && !e.destroyed && t.length === 0 && t.needDrain && (t.needDrain = false, e.emit("drain"));r-- > 0; ) + t.pendingcb--, n(); + t.destroyed && Nr(t), Mr(e, t); + } + function Nr(e) { + if (e.writing) + return; + for (let i = e.bufferedIndex;i < e.buffered.length; ++i) { + var t; + let { chunk: o, callback: l } = e.buffered[i], u = e.objectMode ? 1 : o.length; + e.length -= u, l((t = e.errored) !== null && t !== undefined ? t : new Xe("write")); + } + let r = e[qe].splice(0); + for (let i = 0;i < r.length; i++) { + var n; + r[i]((n = e.errored) !== null && n !== undefined ? n : new Xe("end")); + } + Ct(e); + } + function Fr(e, t) { + if (t.corked || t.bufferProcessing || t.destroyed || !t.constructed) + return; + let { buffered: r, bufferedIndex: n, objectMode: i } = t, o = r.length - n; + if (!o) + return; + let l = n; + if (t.bufferProcessing = true, o > 1 && e._writev) { + t.pendingcb -= o - 1; + let u = t.allNoop ? Lr : (s) => { + for (let d = l;d < r.length; ++d) + r[d].callback(s); + }, f = t.allNoop && l === 0 ? r : ao(r, l); + f.allBuffers = t.allBuffers, fo(e, t, true, t.length, f, "", u), Ct(t); + } else { + do { + let { chunk: u, encoding: f, callback: s } = r[l]; + r[l++] = null; + let d = i ? 1 : u.length; + fo(e, t, false, d, u, f, s); + } while (l < r.length && !t.writing); + l === r.length ? Ct(t) : l > 256 ? (r.splice(0, l), t.bufferedIndex = 0) : t.bufferedIndex = l; + } + t.bufferProcessing = false; + } + m.prototype._write = function(e, t, r) { + if (this._writev) + this._writev([{ chunk: e, encoding: t }], r); + else + throw new Ta("_write()"); + }; + m.prototype._writev = null; + m.prototype.end = function(e, t, r) { + let n = this._writableState; + typeof e == "function" ? (r = e, e = null, t = null) : typeof t == "function" && (r = t, t = null); + let i; + if (e != null) { + let o = bo(this, e, t); + o instanceof ba && (i = o); + } + return n.corked && (n.corked = 1, this.uncork()), i || (!n.errored && !n.ending ? (n.ending = true, Mr(this, n, true), n.ended = true) : n.finished ? i = new La("end") : n.destroyed && (i = new Xe("end"))), typeof r == "function" && (i || n.finished ? Re.nextTick(r, i) : n[qe].push(r)), this; + }; + function Mt(e) { + return e.ending && !e.destroyed && e.constructed && e.length === 0 && !e.errored && e.buffered.length === 0 && !e.finished && !e.writing && !e.errorEmitted && !e.closeEmitted; + } + function Da(e, t) { + let r = false; + function n(i) { + if (r) { + ve(e, i ?? yo()); + return; + } + if (r = true, t.pendingcb--, i) { + let o = t[qe].splice(0); + for (let l = 0;l < o.length; l++) + o[l](i); + ve(e, i, t.sync); + } else + Mt(t) && (t.prefinished = true, e.emit("prefinish"), t.pendingcb++, Re.nextTick(Br, e, t)); + } + t.sync = true, t.pendingcb++; + try { + e._final(n); + } catch (i) { + n(i); + } + t.sync = false; + } + function Pa(e, t) { + !t.prefinished && !t.finalCalled && (typeof e._final == "function" && !t.destroyed ? (t.finalCalled = true, Da(e, t)) : (t.prefinished = true, e.emit("prefinish"))); + } + function Mr(e, t, r) { + Mt(t) && (Pa(e, t), t.pendingcb === 0 && (r ? (t.pendingcb++, Re.nextTick((n, i) => { + Mt(i) ? Br(n, i) : i.pendingcb--; + }, e, t)) : Mt(t) && (t.pendingcb++, Br(e, t)))); + } + function Br(e, t) { + t.pendingcb--, t.finished = true; + let r = t[qe].splice(0); + for (let n = 0;n < r.length; n++) + r[n](); + if (e.emit("finish"), t.autoDestroy) { + let n = e._readableState; + (!n || n.autoDestroy && (n.endEmitted || n.readable === false)) && e.destroy(); + } + } + ga(m.prototype, { closed: { __proto__: null, get() { + return this._writableState ? this._writableState.closed : false; + } }, destroyed: { __proto__: null, get() { + return this._writableState ? this._writableState.destroyed : false; + }, set(e) { + this._writableState && (this._writableState.destroyed = e); + } }, writable: { __proto__: null, get() { + let e = this._writableState; + return !!e && e.writable !== false && !e.destroyed && !e.errored && !e.ending && !e.ended; + }, set(e) { + this._writableState && (this._writableState.writable = !!e); + } }, writableFinished: { __proto__: null, get() { + return this._writableState ? this._writableState.finished : false; + } }, writableObjectMode: { __proto__: null, get() { + return this._writableState ? this._writableState.objectMode : false; + } }, writableBuffer: { __proto__: null, get() { + return this._writableState && this._writableState.getBuffer(); + } }, writableEnded: { __proto__: null, get() { + return this._writableState ? this._writableState.ending : false; + } }, writableNeedDrain: { __proto__: null, get() { + let e = this._writableState; + return e ? !e.destroyed && !e.ending && e.needDrain : false; + } }, writableHighWaterMark: { __proto__: null, get() { + return this._writableState && this._writableState.highWaterMark; + } }, writableCorked: { __proto__: null, get() { + return this._writableState ? this._writableState.corked : 0; + } }, writableLength: { __proto__: null, get() { + return this._writableState && this._writableState.length; + } }, errored: { __proto__: null, enumerable: false, get() { + return this._writableState ? this._writableState.errored : null; + } }, writableAborted: { __proto__: null, enumerable: false, get: function() { + return !!(this._writableState.writable !== false && (this._writableState.destroyed || this._writableState.errored) && !this._writableState.finished); + } } }); + var ka = Ot.destroy; + m.prototype.destroy = function(e, t) { + let r = this._writableState; + return !r.destroyed && (r.bufferedIndex < r.buffered.length || r[qe].length) && Re.nextTick(Nr, r), ka.call(this, e, t), this; + }; + m.prototype._undestroy = Ot.undestroy; + m.prototype._destroy = function(e, t) { + t(e); + }; + m.prototype[ma.captureRejectionSymbol] = function(e) { + this.destroy(e); + }; + var Tr; + function _o() { + return Tr === undefined && (Tr = {}), Tr; + } + m.fromWeb = function(e, t) { + return _o().newStreamWritableFromWritableStream(e, t); + }; + m.toWeb = function(e) { + return _o().newWritableStreamFromStreamWritable(e); + }; + }); + Mo = E((cd, Fo) => { + var Or = (se(), pe(k)), Ua = te(), { isReadable: va, isWritable: qa, isIterable: So, isNodeStream: Wa, isReadableNodeStream: mo, isWritableNodeStream: xo, isDuplexNodeStream: $a } = ae(), Ro = ce(), { AbortError: No, codes: { ERR_INVALID_ARG_TYPE: ja, ERR_INVALID_RETURN_VALUE: Ao } } = C(), { destroyer: We } = Se(), Ga = J(), Ha = Ke(), { createDeferredPromise: Io } = V(), To = Er(), Bo = globalThis.Blob || Ua.Blob, Va = typeof Bo < "u" ? function(t) { + return t instanceof Bo; + } : function(t) { + return false; + }, Ya = globalThis.AbortController || ut().AbortController, { FunctionPrototypeCall: Lo } = I(), Ae = class extends Ga { + constructor(t) { + super(t), t?.readable === false && (this._readableState.readable = false, this._readableState.ended = true, this._readableState.endEmitted = true), t?.writable === false && (this._writableState.writable = false, this._writableState.ending = true, this._writableState.ended = true, this._writableState.finished = true); + } + }; + Fo.exports = function e(t, r) { + if ($a(t)) + return t; + if (mo(t)) + return Dt({ readable: t }); + if (xo(t)) + return Dt({ writable: t }); + if (Wa(t)) + return Dt({ writable: false, readable: false }); + if (typeof t == "function") { + let { value: i, write: o, final: l, destroy: u } = Ka(t); + if (So(i)) + return To(Ae, i, { objectMode: true, write: o, final: l, destroy: u }); + let f = i?.then; + if (typeof f == "function") { + let s, d = Lo(f, i, (c) => { + if (c != null) + throw new Ao("nully", "body", c); + }, (c) => { + We(s, c); + }); + return s = new Ae({ objectMode: true, readable: false, write: o, final(c) { + l(async () => { + try { + await d, Or.nextTick(c, null); + } catch (y) { + Or.nextTick(c, y); + } + }); + }, destroy: u }); + } + throw new Ao("Iterable, AsyncIterable or AsyncFunction", r, i); + } + if (Va(t)) + return e(t.arrayBuffer()); + if (So(t)) + return To(Ae, t, { objectMode: true, writable: false }); + if (typeof t?.writable == "object" || typeof t?.readable == "object") { + let i = t != null && t.readable ? mo(t?.readable) ? t?.readable : e(t.readable) : undefined, o = t != null && t.writable ? xo(t?.writable) ? t?.writable : e(t.writable) : undefined; + return Dt({ readable: i, writable: o }); + } + let n = t?.then; + if (typeof n == "function") { + let i; + return Lo(n, t, (o) => { + o != null && i.push(o), i.push(null); + }, (o) => { + We(i, o); + }), i = new Ae({ objectMode: true, writable: false, read() { + } }); + } + throw new ja(r, ["Blob", "ReadableStream", "WritableStream", "Stream", "Iterable", "AsyncIterable", "Function", "{ readable, writable } pair", "Promise"], t); + }; + function Ka(e) { + let { promise: t, resolve: r } = Io(), n = new Ya, i = n.signal; + return { value: e(async function* () { + for (;; ) { + let l = t; + t = null; + let { chunk: u, done: f, cb: s } = await l; + if (Or.nextTick(s), f) + return; + if (i.aborted) + throw new No(undefined, { cause: i.reason }); + ({ promise: t, resolve: r } = Io()), yield u; + } + }(), { signal: i }), write(l, u, f) { + let s = r; + r = null, s({ chunk: l, done: false, cb: f }); + }, final(l) { + let u = r; + r = null, u({ done: true, cb: l }); + }, destroy(l, u) { + n.abort(), u(l); + } }; + } + function Dt(e) { + let t = e.readable && typeof e.readable.read != "function" ? Ha.wrap(e.readable) : e.readable, r = e.writable, n = !!va(t), i = !!qa(r), o, l, u, f, s; + function d(c) { + let y = f; + f = null, y ? y(c) : c ? s.destroy(c) : !n && !i && s.destroy(); + } + return s = new Ae({ readableObjectMode: !!(t != null && t.readableObjectMode), writableObjectMode: !!(r != null && r.writableObjectMode), readable: n, writable: i }), i && (Ro(r, (c) => { + i = false, c && We(t, c), d(c); + }), s._write = function(c, y, h) { + r.write(c, y) ? h() : o = h; + }, s._final = function(c) { + r.end(), l = c; + }, r.on("drain", function() { + if (o) { + let c = o; + o = null, c(); + } + }), r.on("finish", function() { + if (l) { + let c = l; + l = null, c(); + } + })), n && (Ro(t, (c) => { + n = false, c && We(t, c), d(c); + }), t.on("readable", function() { + if (u) { + let c = u; + u = null, c(); + } + }), t.on("end", function() { + s.push(null); + }), s._read = function() { + for (;; ) { + let c = t.read(); + if (c === null) { + u = s._read; + return; + } + if (!s.push(c)) + return; + } + }), s._destroy = function(c, y) { + !c && f !== null && (c = new No), u = null, o = null, l = null, f === null ? y(c) : (f = y, We(r, c), We(t, c)); + }, s; + } + }); + J = E((dd, Do) => { + var { ObjectDefineProperties: za, ObjectGetOwnPropertyDescriptor: ie, ObjectKeys: Xa, ObjectSetPrototypeOf: Co } = I(); + Do.exports = j; + var kr = Ke(), U = Cr(); + Co(j.prototype, kr.prototype); + Co(j, kr); + { + let e = Xa(U.prototype); + for (let t = 0;t < e.length; t++) { + let r = e[t]; + j.prototype[r] || (j.prototype[r] = U.prototype[r]); + } + } + function j(e) { + if (!(this instanceof j)) + return new j(e); + kr.call(this, e), U.call(this, e), e ? (this.allowHalfOpen = e.allowHalfOpen !== false, e.readable === false && (this._readableState.readable = false, this._readableState.ended = true, this._readableState.endEmitted = true), e.writable === false && (this._writableState.writable = false, this._writableState.ending = true, this._writableState.ended = true, this._writableState.finished = true)) : this.allowHalfOpen = true; + } + za(j.prototype, { writable: { __proto__: null, ...ie(U.prototype, "writable") }, writableHighWaterMark: { __proto__: null, ...ie(U.prototype, "writableHighWaterMark") }, writableObjectMode: { __proto__: null, ...ie(U.prototype, "writableObjectMode") }, writableBuffer: { __proto__: null, ...ie(U.prototype, "writableBuffer") }, writableLength: { __proto__: null, ...ie(U.prototype, "writableLength") }, writableFinished: { __proto__: null, ...ie(U.prototype, "writableFinished") }, writableCorked: { __proto__: null, ...ie(U.prototype, "writableCorked") }, writableEnded: { __proto__: null, ...ie(U.prototype, "writableEnded") }, writableNeedDrain: { __proto__: null, ...ie(U.prototype, "writableNeedDrain") }, destroyed: { __proto__: null, get() { + return this._readableState === undefined || this._writableState === undefined ? false : this._readableState.destroyed && this._writableState.destroyed; + }, set(e) { + this._readableState && this._writableState && (this._readableState.destroyed = e, this._writableState.destroyed = e); + } } }); + var Dr; + function Oo() { + return Dr === undefined && (Dr = {}), Dr; + } + j.fromWeb = function(e, t) { + return Oo().newStreamDuplexFromReadableWritablePair(e, t); + }; + j.toWeb = function(e) { + return Oo().newReadableWritablePairFromDuplex(e); + }; + var Pr; + j.from = function(e) { + return Pr || (Pr = Mo()), Pr(e, "body"); + }; + }); + qr = E((hd, ko) => { + var { ObjectSetPrototypeOf: Po, Symbol: Ja } = I(); + ko.exports = oe; + var { ERR_METHOD_NOT_IMPLEMENTED: Qa } = C().codes, vr = J(), { getHighWaterMark: Za } = Tt(); + Po(oe.prototype, vr.prototype); + Po(oe, vr); + var Qe = Ja("kCallback"); + function oe(e) { + if (!(this instanceof oe)) + return new oe(e); + let t = e ? Za(this, e, "readableHighWaterMark", true) : null; + t === 0 && (e = { ...e, highWaterMark: null, readableHighWaterMark: t, writableHighWaterMark: e.writableHighWaterMark || 0 }), vr.call(this, e), this._readableState.sync = false, this[Qe] = null, e && (typeof e.transform == "function" && (this._transform = e.transform), typeof e.flush == "function" && (this._flush = e.flush)), this.on("prefinish", ec); + } + function Ur(e) { + typeof this._flush == "function" && !this.destroyed ? this._flush((t, r) => { + if (t) { + e ? e(t) : this.destroy(t); + return; + } + r != null && this.push(r), this.push(null), e && e(); + }) : (this.push(null), e && e()); + } + function ec() { + this._final !== Ur && Ur.call(this); + } + oe.prototype._final = Ur; + oe.prototype._transform = function(e, t, r) { + throw new Qa("_transform()"); + }; + oe.prototype._write = function(e, t, r) { + let n = this._readableState, i = this._writableState, o = n.length; + this._transform(e, t, (l, u) => { + if (l) { + r(l); + return; + } + u != null && this.push(u), i.ended || o === n.length || n.length < n.highWaterMark ? r() : this[Qe] = r; + }); + }; + oe.prototype._read = function() { + if (this[Qe]) { + let e = this[Qe]; + this[Qe] = null, e(); + } + }; + }); + $r = E((pd, vo) => { + var { ObjectSetPrototypeOf: Uo } = I(); + vo.exports = $e; + var Wr = qr(); + Uo($e.prototype, Wr.prototype); + Uo($e, Wr); + function $e(e) { + if (!(this instanceof $e)) + return new $e(e); + Wr.call(this, e); + } + $e.prototype._transform = function(e, t, r) { + r(null, e); + }; + }); + Ut = E((yd, Vo) => { + var Pt = (se(), pe(k)), { ArrayIsArray: tc, Promise: rc, SymbolAsyncIterator: nc } = I(), kt = ce(), { once: ic } = V(), oc = Se(), qo = J(), { aggregateTwoErrors: lc, codes: { ERR_INVALID_ARG_TYPE: Go, ERR_INVALID_RETURN_VALUE: jr, ERR_MISSING_ARGS: uc, ERR_STREAM_DESTROYED: fc, ERR_STREAM_PREMATURE_CLOSE: sc }, AbortError: ac } = C(), { validateFunction: cc, validateAbortSignal: dc } = He(), { isIterable: je, isReadable: Gr, isReadableNodeStream: Yr, isNodeStream: Wo } = ae(), hc = globalThis.AbortController || ut().AbortController, Hr, Vr; + function $o(e, t, r) { + let n = false; + e.on("close", () => { + n = true; + }); + let i = kt(e, { readable: t, writable: r }, (o) => { + n = !o; + }); + return { destroy: (o) => { + n || (n = true, oc.destroyer(e, o || new fc("pipe"))); + }, cleanup: i }; + } + function pc(e) { + return cc(e[e.length - 1], "streams[stream.length - 1]"), e.pop(); + } + function yc(e) { + if (je(e)) + return e; + if (Yr(e)) + return wc(e); + throw new Go("val", ["Readable", "Iterable", "AsyncIterable"], e); + } + async function* wc(e) { + Vr || (Vr = Ke()), yield* Vr.prototype[nc].call(e); + } + async function jo(e, t, r, { end: n }) { + let i, o = null, l = (s) => { + if (s && (i = s), o) { + let d = o; + o = null, d(); + } + }, u = () => new rc((s, d) => { + i ? d(i) : o = () => { + i ? d(i) : s(); + }; + }); + t.on("drain", l); + let f = kt(t, { readable: false }, l); + try { + t.writableNeedDrain && await u(); + for await (let s of e) + t.write(s) || await u(); + n && t.end(), await u(), r(); + } catch (s) { + r(i !== s ? lc(i, s) : s); + } finally { + f(), t.off("drain", l); + } + } + function bc(...e) { + return Ho(e, ic(pc(e))); + } + function Ho(e, t, r) { + if (e.length === 1 && tc(e[0]) && (e = e[0]), e.length < 2) + throw new uc("streams"); + let n = new hc, i = n.signal, o = r?.signal, l = []; + dc(o, "options.signal"); + function u() { + h(new ac); + } + o?.addEventListener("abort", u); + let f, s, d = [], c = 0; + function y(w) { + h(w, --c === 0); + } + function h(w, b) { + if (w && (!f || f.code === "ERR_STREAM_PREMATURE_CLOSE") && (f = w), !(!f && !b)) { + for (;d.length; ) + d.shift()(f); + o?.removeEventListener("abort", u), n.abort(), b && (f || l.forEach((L) => L()), Pt.nextTick(t, f, s)); + } + } + let p; + for (let w = 0;w < e.length; w++) { + let b = e[w], L = w < e.length - 1, N = w > 0, Q = L || r?.end !== false, Ie = w === e.length - 1; + if (Wo(b)) { + let q = function(Z) { + Z && Z.name !== "AbortError" && Z.code !== "ERR_STREAM_PREMATURE_CLOSE" && y(Z); + }; + var v = q; + if (Q) { + let { destroy: Z, cleanup: qt } = $o(b, L, N); + d.push(Z), Gr(b) && Ie && l.push(qt); + } + b.on("error", q), Gr(b) && Ie && l.push(() => { + b.removeListener("error", q); + }); + } + if (w === 0) + if (typeof b == "function") { + if (p = b({ signal: i }), !je(p)) + throw new jr("Iterable, AsyncIterable or Stream", "source", p); + } else + je(b) || Yr(b) ? p = b : p = qo.from(b); + else if (typeof b == "function") + if (p = yc(p), p = b(p, { signal: i }), L) { + if (!je(p, true)) + throw new jr("AsyncIterable", `transform[${w - 1}]`, p); + } else { + var B; + Hr || (Hr = $r()); + let q = new Hr({ objectMode: true }), Z = (B = p) === null || B === undefined ? undefined : B.then; + if (typeof Z == "function") + c++, Z.call(p, (Te) => { + s = Te, Te != null && q.write(Te), Q && q.end(), Pt.nextTick(y); + }, (Te) => { + q.destroy(Te), Pt.nextTick(y, Te); + }); + else if (je(p, true)) + c++, jo(p, q, y, { end: Q }); + else + throw new jr("AsyncIterable or Promise", "destination", p); + p = q; + let { destroy: qt, cleanup: sl } = $o(p, false, true); + d.push(qt), Ie && l.push(sl); + } + else if (Wo(b)) { + if (Yr(p)) { + c += 2; + let q = gc(p, b, y, { end: Q }); + Gr(b) && Ie && l.push(q); + } else if (je(p)) + c++, jo(p, b, y, { end: Q }); + else + throw new Go("val", ["Readable", "Iterable", "AsyncIterable"], p); + p = b; + } else + p = qo.from(b); + } + return (i != null && i.aborted || o != null && o.aborted) && Pt.nextTick(u), p; + } + function gc(e, t, r, { end: n }) { + let i = false; + return t.on("close", () => { + i || r(new sc); + }), e.pipe(t, { end: n }), n ? e.once("end", () => { + i = true, t.end(); + }) : r(), kt(e, { readable: true, writable: false }, (o) => { + let l = e._readableState; + o && o.code === "ERR_STREAM_PREMATURE_CLOSE" && l && l.ended && !l.errored && !l.errorEmitted ? e.once("end", r).once("error", r) : r(o); + }), kt(t, { readable: false, writable: true }, r); + } + Vo.exports = { pipelineImpl: Ho, pipeline: bc }; + }); + Jo = E((wd, Xo) => { + var { pipeline: _c } = Ut(), vt = J(), { destroyer: Ec } = Se(), { isNodeStream: Sc, isReadable: Yo, isWritable: Ko } = ae(), { AbortError: mc, codes: { ERR_INVALID_ARG_VALUE: zo, ERR_MISSING_ARGS: xc } } = C(); + Xo.exports = function(...t) { + if (t.length === 0) + throw new xc("streams"); + if (t.length === 1) + return vt.from(t[0]); + let r = [...t]; + if (typeof t[0] == "function" && (t[0] = vt.from(t[0])), typeof t[t.length - 1] == "function") { + let h = t.length - 1; + t[h] = vt.from(t[h]); + } + for (let h = 0;h < t.length; ++h) + if (!!Sc(t[h])) { + if (h < t.length - 1 && !Yo(t[h])) + throw new zo(`streams[${h}]`, r[h], "must be readable"); + if (h > 0 && !Ko(t[h])) + throw new zo(`streams[${h}]`, r[h], "must be writable"); + } + let n, i, o, l, u; + function f(h) { + let p = l; + l = null, p ? p(h) : h ? u.destroy(h) : !y && !c && u.destroy(); + } + let s = t[0], d = _c(t, f), c = !!Ko(s), y = !!Yo(d); + return u = new vt({ writableObjectMode: !!(s != null && s.writableObjectMode), readableObjectMode: !!(d != null && d.writableObjectMode), writable: c, readable: y }), c && (u._write = function(h, p, B) { + s.write(h, p) ? B() : n = B; + }, u._final = function(h) { + s.end(), i = h; + }, s.on("drain", function() { + if (n) { + let h = n; + n = null, h(); + } + }), d.on("finish", function() { + if (i) { + let h = i; + i = null, h(); + } + })), y && (d.on("readable", function() { + if (o) { + let h = o; + o = null, h(); + } + }), d.on("end", function() { + u.push(null); + }), u._read = function() { + for (;; ) { + let h = d.read(); + if (h === null) { + o = u._read; + return; + } + if (!u.push(h)) + return; + } + }), u._destroy = function(h, p) { + !h && l !== null && (h = new mc), o = null, n = null, i = null, l === null ? p(h) : (l = p, Ec(d, h)); + }, u; + }; + }); + Kr = E((bd, Qo) => { + var { ArrayPrototypePop: Rc, Promise: Ac } = I(), { isIterable: Ic, isNodeStream: Tc } = ae(), { pipelineImpl: Bc } = Ut(), { finished: Lc } = ce(); + function Nc(...e) { + return new Ac((t, r) => { + let n, i, o = e[e.length - 1]; + if (o && typeof o == "object" && !Tc(o) && !Ic(o)) { + let l = Rc(e); + n = l.signal, i = l.end; + } + Bc(e, (l, u) => { + l ? r(l) : t(u); + }, { signal: n, end: i }); + }); + } + Qo.exports = { finished: Lc, pipeline: Nc }; + }); + fl = E((gd, ul) => { + var { Buffer: Fc } = te(), { ObjectDefineProperty: le, ObjectKeys: tl, ReflectApply: rl } = I(), { promisify: { custom: nl } } = V(), { streamReturningOperators: Zo, promiseReturningOperators: el } = di(), { codes: { ERR_ILLEGAL_CONSTRUCTOR: il } } = C(), Mc = Jo(), { pipeline: ol } = Ut(), { destroyer: Cc } = Se(), ll = ce(), zr = Kr(), Xr = ae(), R = ul.exports = xt().Stream; + R.isDisturbed = Xr.isDisturbed; + R.isErrored = Xr.isErrored; + R.isReadable = Xr.isReadable; + R.Readable = Ke(); + for (let e of tl(Zo)) { + let r = function(...n) { + if (new.target) + throw il(); + return R.Readable.from(rl(t, this, n)); + }; + Dc = r; + let t = Zo[e]; + le(r, "name", { __proto__: null, value: t.name }), le(r, "length", { __proto__: null, value: t.length }), le(R.Readable.prototype, e, { __proto__: null, value: r, enumerable: false, configurable: true, writable: true }); + } + var Dc; + for (let e of tl(el)) { + let r = function(...i) { + if (new.target) + throw il(); + return rl(t, this, i); + }; + Dc = r; + let t = el[e]; + le(r, "name", { __proto__: null, value: t.name }), le(r, "length", { __proto__: null, value: t.length }), le(R.Readable.prototype, e, { __proto__: null, value: r, enumerable: false, configurable: true, writable: true }); + } + var Dc; + R.Writable = Cr(); + R.Duplex = J(); + R.Transform = qr(); + R.PassThrough = $r(); + R.pipeline = ol; + var { addAbortSignal: Oc } = At(); + R.addAbortSignal = Oc; + R.finished = ll; + R.destroy = Cc; + R.compose = Mc; + le(R, "promises", { __proto__: null, configurable: true, enumerable: true, get() { + return zr; + } }); + le(ol, nl, { __proto__: null, enumerable: true, get() { + return zr.pipeline; + } }); + le(ll, nl, { __proto__: null, enumerable: true, get() { + return zr.finished; + } }); + R.Stream = R; + R._isUint8Array = function(t) { + return t instanceof Uint8Array; + }; + R._uint8ArrayToBuffer = function(t) { + return Fc.from(t.buffer, t.byteOffset, t.byteLength); + }; + }); + Jr = E((_d, A) => { + var T = fl(), Pc = Kr(), kc = T.Readable.destroy; + A.exports = T.Readable; + A.exports._uint8ArrayToBuffer = T._uint8ArrayToBuffer; + A.exports._isUint8Array = T._isUint8Array; + A.exports.isDisturbed = T.isDisturbed; + A.exports.isErrored = T.isErrored; + A.exports.isReadable = T.isReadable; + A.exports.Readable = T.Readable; + A.exports.Writable = T.Writable; + A.exports.Duplex = T.Duplex; + A.exports.Transform = T.Transform; + A.exports.PassThrough = T.PassThrough; + A.exports.addAbortSignal = T.addAbortSignal; + A.exports.finished = T.finished; + A.exports.destroy = T.destroy; + A.exports.destroy = kc; + A.exports.pipeline = T.pipeline; + A.exports.compose = T.compose; + Object.defineProperty(T, "promises", { configurable: true, enumerable: true, get() { + return Pc; + } }); + A.exports.Stream = T.Stream; + A.exports.default = A.exports; + }); + Ze = {}; + Qr(Ze, { default: () => Uc }); + ue(Ze, rt(Jr())); + Uc = rt(Jr()); + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + /*! safe-buffer. MIT License. Feross Aboukhadijeh */ +}); + +// node_modules/jszip/lib/support.js +var require_support = __commonJS((exports2) => { + exports2.base64 = true; + exports2.array = true; + exports2.string = true; + exports2.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"; + exports2.nodebuffer = typeof Buffer !== "undefined"; + exports2.uint8array = typeof Uint8Array !== "undefined"; + if (typeof ArrayBuffer === "undefined") { + exports2.blob = false; + } else { + buffer = new ArrayBuffer(0); + try { + exports2.blob = new Blob([buffer], { + type: "application/zip" + }).size === 0; + } catch (e) { + try { + Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; + builder = new Builder; + builder.append(buffer); + exports2.blob = builder.getBlob("application/zip").size === 0; + } catch (e2) { + exports2.blob = false; + } + } + } + var buffer; + var Builder; + var builder; + try { + exports2.nodestream = !!(init_stream(), __toCommonJS(exports_stream)).Readable; + } catch (e) { + exports2.nodestream = false; + } +}); + +// node_modules/jszip/lib/base64.js +var require_base64 = __commonJS((exports2) => { + var utils = require_utils(); + var support = require_support(); + var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; + exports2.encode = function(input) { + var output = []; + var chr1, chr2, chr3, enc1, enc2, enc3, enc4; + var i = 0, len = input.length, remainingBytes = len; + var isArray2 = utils.getTypeOf(input) !== "string"; + while (i < input.length) { + remainingBytes = len - i; + if (!isArray2) { + chr1 = input.charCodeAt(i++); + chr2 = i < len ? input.charCodeAt(i++) : 0; + chr3 = i < len ? input.charCodeAt(i++) : 0; + } else { + chr1 = input[i++]; + chr2 = i < len ? input[i++] : 0; + chr3 = i < len ? input[i++] : 0; + } + enc1 = chr1 >> 2; + enc2 = (chr1 & 3) << 4 | chr2 >> 4; + enc3 = remainingBytes > 1 ? (chr2 & 15) << 2 | chr3 >> 6 : 64; + enc4 = remainingBytes > 2 ? chr3 & 63 : 64; + output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4)); + } + return output.join(""); + }; + exports2.decode = function(input) { + var chr1, chr2, chr3; + var enc1, enc2, enc3, enc4; + var i = 0, resultIndex = 0; + var dataUrlPrefix = "data:"; + if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) { + throw new Error("Invalid base64 input, it looks like a data url."); + } + input = input.replace(/[^A-Za-z0-9+/=]/g, ""); + var totalLength = input.length * 3 / 4; + if (input.charAt(input.length - 1) === _keyStr.charAt(64)) { + totalLength--; + } + if (input.charAt(input.length - 2) === _keyStr.charAt(64)) { + totalLength--; + } + if (totalLength % 1 !== 0) { + throw new Error("Invalid base64 input, bad content length."); + } + var output; + if (support.uint8array) { + output = new Uint8Array(totalLength | 0); + } else { + output = new Array(totalLength | 0); + } + while (i < input.length) { + enc1 = _keyStr.indexOf(input.charAt(i++)); + enc2 = _keyStr.indexOf(input.charAt(i++)); + enc3 = _keyStr.indexOf(input.charAt(i++)); + enc4 = _keyStr.indexOf(input.charAt(i++)); + chr1 = enc1 << 2 | enc2 >> 4; + chr2 = (enc2 & 15) << 4 | enc3 >> 2; + chr3 = (enc3 & 3) << 6 | enc4; + output[resultIndex++] = chr1; + if (enc3 !== 64) { + output[resultIndex++] = chr2; + } + if (enc4 !== 64) { + output[resultIndex++] = chr3; + } + } + return output; + }; +}); + +// node_modules/jszip/lib/nodejsUtils.js +var require_nodejsUtils = __commonJS((exports2, module2) => { + module2.exports = { + isNode: typeof Buffer !== "undefined", + newBufferFrom: function(data2, encoding) { + if (Buffer.from && Buffer.from !== Uint8Array.from) { + return Buffer.from(data2, encoding); + } else { + if (typeof data2 === "number") { + throw new Error('The "data" argument must not be a number'); + } + return new Buffer(data2, encoding); + } + }, + allocBuffer: function(size) { + if (Buffer.alloc) { + return Buffer.alloc(size); + } else { + var buf = new Buffer(size); + buf.fill(0); + return buf; + } + }, + isBuffer: function(b) { + return Buffer.isBuffer(b); + }, + isStream: function(obj) { + return obj && typeof obj.on === "function" && typeof obj.pause === "function" && typeof obj.resume === "function"; + } + }; +}); + +// node_modules/immediate/lib/browser.js +var require_browser = __commonJS((exports2, module2) => { + var Mutation = global.MutationObserver || global.WebKitMutationObserver; + var scheduleDrain; + { + if (Mutation) { + called = 0; + observer = new Mutation(nextTick); + element = global.document.createTextNode(""); + observer.observe(element, { + characterData: true + }); + scheduleDrain = function() { + element.data = called = ++called % 2; + }; + } else if (!global.setImmediate && typeof global.MessageChannel !== "undefined") { + channel = new global.MessageChannel; + channel.port1.onmessage = nextTick; + scheduleDrain = function() { + channel.port2.postMessage(0); + }; + } else if ("document" in global && "onreadystatechange" in global.document.createElement("script")) { + scheduleDrain = function() { + var scriptEl = global.document.createElement("script"); + scriptEl.onreadystatechange = function() { + nextTick(); + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + global.document.documentElement.appendChild(scriptEl); + }; + } else { + scheduleDrain = function() { + setTimeout(nextTick, 0); + }; + } + } + var called; + var observer; + var element; + var channel; + var draining; + var queue = []; + function nextTick() { + draining = true; + var i, oldQueue; + var len = queue.length; + while (len) { + oldQueue = queue; + queue = []; + i = -1; + while (++i < len) { + oldQueue[i](); + } + len = queue.length; + } + draining = false; + } + module2.exports = immediate; + function immediate(task) { + if (queue.push(task) === 1 && !draining) { + scheduleDrain(); + } + } +}); + +// node_modules/lie/lib/browser.js +var require_browser2 = __commonJS((exports2, module2) => { + var immediate = require_browser(); + function INTERNAL() { + } + var handlers = {}; + var REJECTED = ["REJECTED"]; + var FULFILLED = ["FULFILLED"]; + var PENDING = ["PENDING"]; + module2.exports = Promise2; + function Promise2(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("resolver must be a function"); + } + this.state = PENDING; + this.queue = []; + this.outcome = undefined; + if (resolver !== INTERNAL) { + safelyResolveThenable(this, resolver); + } + } + Promise2.prototype["finally"] = function(callback) { + if (typeof callback !== "function") { + return this; + } + var p = this.constructor; + return this.then(resolve2, reject3); + function resolve2(value2) { + function yes() { + return value2; + } + return p.resolve(callback()).then(yes); + } + function reject3(reason) { + function no() { + throw reason; + } + return p.resolve(callback()).then(no); + } + }; + Promise2.prototype["catch"] = function(onRejected) { + return this.then(null, onRejected); + }; + Promise2.prototype.then = function(onFulfilled, onRejected) { + if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) { + return this; + } + var promise = new this.constructor(INTERNAL); + if (this.state !== PENDING) { + var resolver = this.state === FULFILLED ? onFulfilled : onRejected; + unwrap(promise, resolver, this.outcome); + } else { + this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); + } + return promise; + }; + function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === "function") { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === "function") { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } + } + QueueItem.prototype.callFulfilled = function(value2) { + handlers.resolve(this.promise, value2); + }; + QueueItem.prototype.otherCallFulfilled = function(value2) { + unwrap(this.promise, this.onFulfilled, value2); + }; + QueueItem.prototype.callRejected = function(value2) { + handlers.reject(this.promise, value2); + }; + QueueItem.prototype.otherCallRejected = function(value2) { + unwrap(this.promise, this.onRejected, value2); + }; + function unwrap(promise, func, value2) { + immediate(function() { + var returnValue; + try { + returnValue = func(value2); + } catch (e) { + return handlers.reject(promise, e); + } + if (returnValue === promise) { + handlers.reject(promise, new TypeError("Cannot resolve promise with itself")); + } else { + handlers.resolve(promise, returnValue); + } + }); + } + handlers.resolve = function(self2, value2) { + var result = tryCatch(getThen, value2); + if (result.status === "error") { + return handlers.reject(self2, result.value); + } + var thenable = result.value; + if (thenable) { + safelyResolveThenable(self2, thenable); + } else { + self2.state = FULFILLED; + self2.outcome = value2; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callFulfilled(value2); + } + } + return self2; + }; + handlers.reject = function(self2, error) { + self2.state = REJECTED; + self2.outcome = error; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callRejected(error); + } + return self2; + }; + function getThen(obj) { + var then = obj && obj.then; + if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") { + return function appyThen() { + then.apply(obj, arguments); + }; + } + } + function safelyResolveThenable(self2, thenable) { + var called = false; + function onError(value2) { + if (called) { + return; + } + called = true; + handlers.reject(self2, value2); + } + function onSuccess(value2) { + if (called) { + return; + } + called = true; + handlers.resolve(self2, value2); + } + function tryToUnwrap() { + thenable(onSuccess, onError); + } + var result = tryCatch(tryToUnwrap); + if (result.status === "error") { + onError(result.value); + } + } + function tryCatch(func, value2) { + var out = {}; + try { + out.value = func(value2); + out.status = "success"; + } catch (e) { + out.status = "error"; + out.value = e; + } + return out; + } + Promise2.resolve = resolve; + function resolve(value2) { + if (value2 instanceof this) { + return value2; + } + return handlers.resolve(new this(INTERNAL), value2); + } + Promise2.reject = reject2; + function reject2(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); + } + Promise2.all = all; + function all(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var values2 = new Array(len); + var resolved = 0; + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + allResolver(iterable[i], i); + } + return promise; + function allResolver(value2, i2) { + self2.resolve(value2).then(resolveFromAll, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values2[i2] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values2); + } + } + } + } + Promise2.race = race; + function race(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + resolver(iterable[i]); + } + return promise; + function resolver(value2) { + self2.resolve(value2).then(function(response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } + } +}); + +// node_modules/jszip/lib/external.js +var require_external = __commonJS((exports2, module2) => { + var ES6Promise = null; + if (typeof Promise !== "undefined") { + ES6Promise = Promise; + } else { + ES6Promise = require_browser2(); + } + module2.exports = { + Promise: ES6Promise + }; +}); + +// node_modules/setimmediate/setImmediate.js +var require_setImmediate = __commonJS((exports2) => { + (function(global2, undefined2) { + if (global2.setImmediate) { + return; + } + var nextHandle = 1; + var tasksByHandle = {}; + var currentlyRunningATask = false; + var doc = global2.document; + var registerImmediate; + function setImmediate2(callback) { + if (typeof callback !== "function") { + callback = new Function("" + callback); + } + var args = new Array(arguments.length - 1); + for (var i = 0;i < args.length; i++) { + args[i] = arguments[i + 1]; + } + var task = { callback, args }; + tasksByHandle[nextHandle] = task; + registerImmediate(nextHandle); + return nextHandle++; + } + function clearImmediate(handle) { + delete tasksByHandle[handle]; + } + function run(task) { + var callback = task.callback; + var args = task.args; + switch (args.length) { + case 0: + callback(); + break; + case 1: + callback(args[0]); + break; + case 2: + callback(args[0], args[1]); + break; + case 3: + callback(args[0], args[1], args[2]); + break; + default: + callback.apply(undefined2, args); + break; + } + } + function runIfPresent(handle) { + if (currentlyRunningATask) { + setTimeout(runIfPresent, 0, handle); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunningATask = true; + try { + run(task); + } finally { + clearImmediate(handle); + currentlyRunningATask = false; + } + } + } + } + function installNextTickImplementation() { + registerImmediate = function(handle) { + process.nextTick(function() { + runIfPresent(handle); + }); + }; + } + function canUsePostMessage() { + if (global2.postMessage && !global2.importScripts) { + var postMessageIsAsynchronous = true; + var oldOnMessage = global2.onmessage; + global2.onmessage = function() { + postMessageIsAsynchronous = false; + }; + global2.postMessage("", "*"); + global2.onmessage = oldOnMessage; + return postMessageIsAsynchronous; + } + } + function installPostMessageImplementation() { + var messagePrefix = "setImmediate$" + Math.random() + "$"; + var onGlobalMessage = function(event) { + if (event.source === global2 && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) { + runIfPresent(+event.data.slice(messagePrefix.length)); + } + }; + if (global2.addEventListener) { + global2.addEventListener("message", onGlobalMessage, false); + } else { + global2.attachEvent("onmessage", onGlobalMessage); + } + registerImmediate = function(handle) { + global2.postMessage(messagePrefix + handle, "*"); + }; + } + function installMessageChannelImplementation() { + var channel = new MessageChannel; + channel.port1.onmessage = function(event) { + var handle = event.data; + runIfPresent(handle); + }; + registerImmediate = function(handle) { + channel.port2.postMessage(handle); + }; + } + function installReadyStateChangeImplementation() { + var html = doc.documentElement; + registerImmediate = function(handle) { + var script = doc.createElement("script"); + script.onreadystatechange = function() { + runIfPresent(handle); + script.onreadystatechange = null; + html.removeChild(script); + script = null; + }; + html.appendChild(script); + }; + } + function installSetTimeoutImplementation() { + registerImmediate = function(handle) { + setTimeout(runIfPresent, 0, handle); + }; + } + var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global2); + attachTo = attachTo && attachTo.setTimeout ? attachTo : global2; + if ({}.toString.call(global2.process) === "[object process]") { + installNextTickImplementation(); + } else if (canUsePostMessage()) { + installPostMessageImplementation(); + } else if (global2.MessageChannel) { + installMessageChannelImplementation(); + } else if (doc && "onreadystatechange" in doc.createElement("script")) { + installReadyStateChangeImplementation(); + } else { + installSetTimeoutImplementation(); + } + attachTo.setImmediate = setImmediate2; + attachTo.clearImmediate = clearImmediate; + })(typeof self === "undefined" ? typeof global === "undefined" ? exports2 : global : self); +}); + +// node_modules/jszip/lib/utils.js +var require_utils = __commonJS((exports2) => { + var support = require_support(); + var base64 = require_base64(); + var nodejsUtils = require_nodejsUtils(); + var external = require_external(); + require_setImmediate(); + function string2binary(str) { + var result = null; + if (support.uint8array) { + result = new Uint8Array(str.length); + } else { + result = new Array(str.length); + } + return stringToArrayLike(str, result); + } + exports2.newBlob = function(part, type) { + exports2.checkSupport("blob"); + try { + return new Blob([part], { + type + }); + } catch (e) { + try { + var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; + var builder = new Builder; + builder.append(part); + return builder.getBlob(type); + } catch (e2) { + throw new Error("Bug : can't construct the Blob."); + } + } + }; + function identity(input) { + return input; + } + function stringToArrayLike(str, array) { + for (var i = 0;i < str.length; ++i) { + array[i] = str.charCodeAt(i) & 255; + } + return array; + } + var arrayToStringHelper = { + stringifyByChunk: function(array, type, chunk) { + var result = [], k2 = 0, len = array.length; + if (len <= chunk) { + return String.fromCharCode.apply(null, array); + } + while (k2 < len) { + if (type === "array" || type === "nodebuffer") { + result.push(String.fromCharCode.apply(null, array.slice(k2, Math.min(k2 + chunk, len)))); + } else { + result.push(String.fromCharCode.apply(null, array.subarray(k2, Math.min(k2 + chunk, len)))); + } + k2 += chunk; + } + return result.join(""); + }, + stringifyByChar: function(array) { + var resultStr = ""; + for (var i = 0;i < array.length; i++) { + resultStr += String.fromCharCode(array[i]); + } + return resultStr; + }, + applyCanBeUsed: { + uint8array: function() { + try { + return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1; + } catch (e) { + return false; + } + }(), + nodebuffer: function() { + try { + return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1; + } catch (e) { + return false; + } + }() + } + }; + function arrayLikeToString(array) { + var chunk = 65536, type = exports2.getTypeOf(array), canUseApply = true; + if (type === "uint8array") { + canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array; + } else if (type === "nodebuffer") { + canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer; + } + if (canUseApply) { + while (chunk > 1) { + try { + return arrayToStringHelper.stringifyByChunk(array, type, chunk); + } catch (e) { + chunk = Math.floor(chunk / 2); + } + } + } + return arrayToStringHelper.stringifyByChar(array); + } + exports2.applyFromCharCode = arrayLikeToString; + function arrayLikeToArrayLike(arrayFrom, arrayTo) { + for (var i = 0;i < arrayFrom.length; i++) { + arrayTo[i] = arrayFrom[i]; + } + return arrayTo; + } + var transform2 = {}; + transform2["string"] = { + string: identity, + array: function(input) { + return stringToArrayLike(input, new Array(input.length)); + }, + arraybuffer: function(input) { + return transform2["string"]["uint8array"](input).buffer; + }, + uint8array: function(input) { + return stringToArrayLike(input, new Uint8Array(input.length)); + }, + nodebuffer: function(input) { + return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length)); + } + }; + transform2["array"] = { + string: arrayLikeToString, + array: identity, + arraybuffer: function(input) { + return new Uint8Array(input).buffer; + }, + uint8array: function(input) { + return new Uint8Array(input); + }, + nodebuffer: function(input) { + return nodejsUtils.newBufferFrom(input); + } + }; + transform2["arraybuffer"] = { + string: function(input) { + return arrayLikeToString(new Uint8Array(input)); + }, + array: function(input) { + return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); + }, + arraybuffer: identity, + uint8array: function(input) { + return new Uint8Array(input); + }, + nodebuffer: function(input) { + return nodejsUtils.newBufferFrom(new Uint8Array(input)); + } + }; + transform2["uint8array"] = { + string: arrayLikeToString, + array: function(input) { + return arrayLikeToArrayLike(input, new Array(input.length)); + }, + arraybuffer: function(input) { + return input.buffer; + }, + uint8array: identity, + nodebuffer: function(input) { + return nodejsUtils.newBufferFrom(input); + } + }; + transform2["nodebuffer"] = { + string: arrayLikeToString, + array: function(input) { + return arrayLikeToArrayLike(input, new Array(input.length)); + }, + arraybuffer: function(input) { + return transform2["nodebuffer"]["uint8array"](input).buffer; + }, + uint8array: function(input) { + return arrayLikeToArrayLike(input, new Uint8Array(input.length)); + }, + nodebuffer: identity + }; + exports2.transformTo = function(outputType, input) { + if (!input) { + input = ""; + } + if (!outputType) { + return input; + } + exports2.checkSupport(outputType); + var inputType = exports2.getTypeOf(input); + var result = transform2[inputType][outputType](input); + return result; + }; + exports2.resolve = function(path) { + var parts = path.split("/"); + var result = []; + for (var index2 = 0;index2 < parts.length; index2++) { + var part = parts[index2]; + if (part === "." || part === "" && index2 !== 0 && index2 !== parts.length - 1) { + continue; + } else if (part === "..") { + result.pop(); + } else { + result.push(part); + } + } + return result.join("/"); + }; + exports2.getTypeOf = function(input) { + if (typeof input === "string") { + return "string"; + } + if (Object.prototype.toString.call(input) === "[object Array]") { + return "array"; + } + if (support.nodebuffer && nodejsUtils.isBuffer(input)) { + return "nodebuffer"; + } + if (support.uint8array && input instanceof Uint8Array) { + return "uint8array"; + } + if (support.arraybuffer && input instanceof ArrayBuffer) { + return "arraybuffer"; + } + }; + exports2.checkSupport = function(type) { + var supported = support[type.toLowerCase()]; + if (!supported) { + throw new Error(type + " is not supported by this platform"); + } + }; + exports2.MAX_VALUE_16BITS = 65535; + exports2.MAX_VALUE_32BITS = -1; + exports2.pretty = function(str) { + var res = "", code, i; + for (i = 0;i < (str || "").length; i++) { + code = str.charCodeAt(i); + res += "\\x" + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); + } + return res; + }; + exports2.delay = function(callback, args, self2) { + setImmediate(function() { + callback.apply(self2 || null, args || []); + }); + }; + exports2.inherits = function(ctor, superCtor) { + var Obj = function() { + }; + Obj.prototype = superCtor.prototype; + ctor.prototype = new Obj; + }; + exports2.extend = function() { + var result = {}, i, attr; + for (i = 0;i < arguments.length; i++) { + for (attr in arguments[i]) { + if (Object.prototype.hasOwnProperty.call(arguments[i], attr) && typeof result[attr] === "undefined") { + result[attr] = arguments[i][attr]; + } + } + } + return result; + }; + exports2.prepareContent = function(name2, inputData, isBinary, isOptimizedBinaryString, isBase64) { + var promise = external.Promise.resolve(inputData).then(function(data2) { + var isBlob = support.blob && (data2 instanceof Blob || ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(data2)) !== -1); + if (isBlob && typeof FileReader !== "undefined") { + return new external.Promise(function(resolve, reject2) { + var reader = new FileReader; + reader.onload = function(e) { + resolve(e.target.result); + }; + reader.onerror = function(e) { + reject2(e.target.error); + }; + reader.readAsArrayBuffer(data2); + }); + } else { + return data2; + } + }); + return promise.then(function(data2) { + var dataType = exports2.getTypeOf(data2); + if (!dataType) { + return external.Promise.reject(new Error("Can't read the data of '" + name2 + "'. Is it " + "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")); + } + if (dataType === "arraybuffer") { + data2 = exports2.transformTo("uint8array", data2); + } else if (dataType === "string") { + if (isBase64) { + data2 = base64.decode(data2); + } else if (isBinary) { + if (isOptimizedBinaryString !== true) { + data2 = string2binary(data2); + } + } + } + return data2; + }); + }; +}); + +// node_modules/jszip/lib/stream/GenericWorker.js +var require_GenericWorker = __commonJS((exports2, module2) => { + function GenericWorker(name2) { + this.name = name2 || "default"; + this.streamInfo = {}; + this.generatedError = null; + this.extraStreamInfo = {}; + this.isPaused = true; + this.isFinished = false; + this.isLocked = false; + this._listeners = { + data: [], + end: [], + error: [] + }; + this.previous = null; + } + GenericWorker.prototype = { + push: function(chunk) { + this.emit("data", chunk); + }, + end: function() { + if (this.isFinished) { + return false; + } + this.flush(); + try { + this.emit("end"); + this.cleanUp(); + this.isFinished = true; + } catch (e) { + this.emit("error", e); + } + return true; + }, + error: function(e) { + if (this.isFinished) { + return false; + } + if (this.isPaused) { + this.generatedError = e; + } else { + this.isFinished = true; + this.emit("error", e); + if (this.previous) { + this.previous.error(e); + } + this.cleanUp(); + } + return true; + }, + on: function(name2, listener) { + this._listeners[name2].push(listener); + return this; + }, + cleanUp: function() { + this.streamInfo = this.generatedError = this.extraStreamInfo = null; + this._listeners = []; + }, + emit: function(name2, arg) { + if (this._listeners[name2]) { + for (var i = 0;i < this._listeners[name2].length; i++) { + this._listeners[name2][i].call(this, arg); + } + } + }, + pipe: function(next) { + return next.registerPrevious(this); + }, + registerPrevious: function(previous) { + if (this.isLocked) { + throw new Error("The stream '" + this + "' has already been used."); + } + this.streamInfo = previous.streamInfo; + this.mergeStreamInfo(); + this.previous = previous; + var self2 = this; + previous.on("data", function(chunk) { + self2.processChunk(chunk); + }); + previous.on("end", function() { + self2.end(); + }); + previous.on("error", function(e) { + self2.error(e); + }); + return this; + }, + pause: function() { + if (this.isPaused || this.isFinished) { + return false; + } + this.isPaused = true; + if (this.previous) { + this.previous.pause(); + } + return true; + }, + resume: function() { + if (!this.isPaused || this.isFinished) { + return false; + } + this.isPaused = false; + var withError = false; + if (this.generatedError) { + this.error(this.generatedError); + withError = true; + } + if (this.previous) { + this.previous.resume(); + } + return !withError; + }, + flush: function() { + }, + processChunk: function(chunk) { + this.push(chunk); + }, + withStreamInfo: function(key2, value2) { + this.extraStreamInfo[key2] = value2; + this.mergeStreamInfo(); + return this; + }, + mergeStreamInfo: function() { + for (var key2 in this.extraStreamInfo) { + if (!Object.prototype.hasOwnProperty.call(this.extraStreamInfo, key2)) { + continue; + } + this.streamInfo[key2] = this.extraStreamInfo[key2]; + } + }, + lock: function() { + if (this.isLocked) { + throw new Error("The stream '" + this + "' has already been used."); + } + this.isLocked = true; + if (this.previous) { + this.previous.lock(); + } + }, + toString: function() { + var me = "Worker " + this.name; + if (this.previous) { + return this.previous + " -> " + me; + } else { + return me; + } + } + }; + module2.exports = GenericWorker; +}); + +// node_modules/jszip/lib/utf8.js +var require_utf8 = __commonJS((exports2) => { + var utils = require_utils(); + var support = require_support(); + var nodejsUtils = require_nodejsUtils(); + var GenericWorker = require_GenericWorker(); + var _utf8len = new Array(256); + for (i = 0;i < 256; i++) { + _utf8len[i] = i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1; + } + var i; + _utf8len[254] = _utf8len[254] = 1; + var string2buf = function(str) { + var buf, c, c2, m_pos, i2, str_len = str.length, buf_len = 0; + for (m_pos = 0;m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4; + } + if (support.uint8array) { + buf = new Uint8Array(buf_len); + } else { + buf = new Array(buf_len); + } + for (i2 = 0, m_pos = 0;i2 < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + if (c < 128) { + buf[i2++] = c; + } else if (c < 2048) { + buf[i2++] = 192 | c >>> 6; + buf[i2++] = 128 | c & 63; + } else if (c < 65536) { + buf[i2++] = 224 | c >>> 12; + buf[i2++] = 128 | c >>> 6 & 63; + buf[i2++] = 128 | c & 63; + } else { + buf[i2++] = 240 | c >>> 18; + buf[i2++] = 128 | c >>> 12 & 63; + buf[i2++] = 128 | c >>> 6 & 63; + buf[i2++] = 128 | c & 63; + } + } + return buf; + }; + var utf8border = function(buf, max) { + var pos; + max = max || buf.length; + if (max > buf.length) { + max = buf.length; + } + pos = max - 1; + while (pos >= 0 && (buf[pos] & 192) === 128) { + pos--; + } + if (pos < 0) { + return max; + } + if (pos === 0) { + return max; + } + return pos + _utf8len[buf[pos]] > max ? pos : max; + }; + var buf2string = function(buf) { + var i2, out, c, c_len; + var len = buf.length; + var utf16buf = new Array(len * 2); + for (out = 0, i2 = 0;i2 < len; ) { + c = buf[i2++]; + if (c < 128) { + utf16buf[out++] = c; + continue; + } + c_len = _utf8len[c]; + if (c_len > 4) { + utf16buf[out++] = 65533; + i2 += c_len - 1; + continue; + } + c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7; + while (c_len > 1 && i2 < len) { + c = c << 6 | buf[i2++] & 63; + c_len--; + } + if (c_len > 1) { + utf16buf[out++] = 65533; + continue; + } + if (c < 65536) { + utf16buf[out++] = c; + } else { + c -= 65536; + utf16buf[out++] = 55296 | c >> 10 & 1023; + utf16buf[out++] = 56320 | c & 1023; + } + } + if (utf16buf.length !== out) { + if (utf16buf.subarray) { + utf16buf = utf16buf.subarray(0, out); + } else { + utf16buf.length = out; + } + } + return utils.applyFromCharCode(utf16buf); + }; + exports2.utf8encode = function utf8encode(str) { + if (support.nodebuffer) { + return nodejsUtils.newBufferFrom(str, "utf-8"); + } + return string2buf(str); + }; + exports2.utf8decode = function utf8decode(buf) { + if (support.nodebuffer) { + return utils.transformTo("nodebuffer", buf).toString("utf-8"); + } + buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf); + return buf2string(buf); + }; + function Utf8DecodeWorker() { + GenericWorker.call(this, "utf-8 decode"); + this.leftOver = null; + } + utils.inherits(Utf8DecodeWorker, GenericWorker); + Utf8DecodeWorker.prototype.processChunk = function(chunk) { + var data2 = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data); + if (this.leftOver && this.leftOver.length) { + if (support.uint8array) { + var previousData = data2; + data2 = new Uint8Array(previousData.length + this.leftOver.length); + data2.set(this.leftOver, 0); + data2.set(previousData, this.leftOver.length); + } else { + data2 = this.leftOver.concat(data2); + } + this.leftOver = null; + } + var nextBoundary = utf8border(data2); + var usableData = data2; + if (nextBoundary !== data2.length) { + if (support.uint8array) { + usableData = data2.subarray(0, nextBoundary); + this.leftOver = data2.subarray(nextBoundary, data2.length); + } else { + usableData = data2.slice(0, nextBoundary); + this.leftOver = data2.slice(nextBoundary, data2.length); + } + } + this.push({ + data: exports2.utf8decode(usableData), + meta: chunk.meta + }); + }; + Utf8DecodeWorker.prototype.flush = function() { + if (this.leftOver && this.leftOver.length) { + this.push({ + data: exports2.utf8decode(this.leftOver), + meta: {} + }); + this.leftOver = null; + } + }; + exports2.Utf8DecodeWorker = Utf8DecodeWorker; + function Utf8EncodeWorker() { + GenericWorker.call(this, "utf-8 encode"); + } + utils.inherits(Utf8EncodeWorker, GenericWorker); + Utf8EncodeWorker.prototype.processChunk = function(chunk) { + this.push({ + data: exports2.utf8encode(chunk.data), + meta: chunk.meta + }); + }; + exports2.Utf8EncodeWorker = Utf8EncodeWorker; +}); + +// node_modules/jszip/lib/stream/ConvertWorker.js +var require_ConvertWorker = __commonJS((exports2, module2) => { + var GenericWorker = require_GenericWorker(); + var utils = require_utils(); + function ConvertWorker(destType) { + GenericWorker.call(this, "ConvertWorker to " + destType); + this.destType = destType; + } + utils.inherits(ConvertWorker, GenericWorker); + ConvertWorker.prototype.processChunk = function(chunk) { + this.push({ + data: utils.transformTo(this.destType, chunk.data), + meta: chunk.meta + }); + }; + module2.exports = ConvertWorker; +}); + +// node_modules/jszip/lib/nodejs/NodejsStreamOutputAdapter.js +var require_NodejsStreamOutputAdapter = __commonJS((exports2, module2) => { + var Readable = (init_stream(), __toCommonJS(exports_stream)).Readable; + var utils = require_utils(); + utils.inherits(NodejsStreamOutputAdapter, Readable); + function NodejsStreamOutputAdapter(helper, options, updateCb) { + Readable.call(this, options); + this._helper = helper; + var self2 = this; + helper.on("data", function(data2, meta) { + if (!self2.push(data2)) { + self2._helper.pause(); + } + if (updateCb) { + updateCb(meta); + } + }).on("error", function(e) { + self2.emit("error", e); + }).on("end", function() { + self2.push(null); + }); + } + NodejsStreamOutputAdapter.prototype._read = function() { + this._helper.resume(); + }; + module2.exports = NodejsStreamOutputAdapter; +}); + +// node_modules/jszip/lib/stream/StreamHelper.js +var require_StreamHelper = __commonJS((exports2, module2) => { + var utils = require_utils(); + var ConvertWorker = require_ConvertWorker(); + var GenericWorker = require_GenericWorker(); + var base64 = require_base64(); + var support = require_support(); + var external = require_external(); + var NodejsStreamOutputAdapter = null; + if (support.nodestream) { + try { + NodejsStreamOutputAdapter = require_NodejsStreamOutputAdapter(); + } catch (e) { + } + } + function transformZipOutput(type, content2, mimeType) { + switch (type) { + case "blob": + return utils.newBlob(utils.transformTo("arraybuffer", content2), mimeType); + case "base64": + return base64.encode(content2); + default: + return utils.transformTo(type, content2); + } + } + function concat(type, dataArray) { + var i, index2 = 0, res = null, totalLength = 0; + for (i = 0;i < dataArray.length; i++) { + totalLength += dataArray[i].length; + } + switch (type) { + case "string": + return dataArray.join(""); + case "array": + return Array.prototype.concat.apply([], dataArray); + case "uint8array": + res = new Uint8Array(totalLength); + for (i = 0;i < dataArray.length; i++) { + res.set(dataArray[i], index2); + index2 += dataArray[i].length; + } + return res; + case "nodebuffer": + return Buffer.concat(dataArray); + default: + throw new Error("concat : unsupported type '" + type + "'"); + } + } + function accumulate(helper, updateCallback) { + return new external.Promise(function(resolve, reject2) { + var dataArray = []; + var { _internalType: chunkType, _outputType: resultType, _mimeType: mimeType } = helper; + helper.on("data", function(data2, meta) { + dataArray.push(data2); + if (updateCallback) { + updateCallback(meta); + } + }).on("error", function(err) { + dataArray = []; + reject2(err); + }).on("end", function() { + try { + var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType); + resolve(result); + } catch (e) { + reject2(e); + } + dataArray = []; + }).resume(); + }); + } + function StreamHelper(worker, outputType, mimeType) { + var internalType = outputType; + switch (outputType) { + case "blob": + case "arraybuffer": + internalType = "uint8array"; + break; + case "base64": + internalType = "string"; + break; + } + try { + this._internalType = internalType; + this._outputType = outputType; + this._mimeType = mimeType; + utils.checkSupport(internalType); + this._worker = worker.pipe(new ConvertWorker(internalType)); + worker.lock(); + } catch (e) { + this._worker = new GenericWorker("error"); + this._worker.error(e); + } + } + StreamHelper.prototype = { + accumulate: function(updateCb) { + return accumulate(this, updateCb); + }, + on: function(evt, fn) { + var self2 = this; + if (evt === "data") { + this._worker.on(evt, function(chunk) { + fn.call(self2, chunk.data, chunk.meta); + }); + } else { + this._worker.on(evt, function() { + utils.delay(fn, arguments, self2); + }); + } + return this; + }, + resume: function() { + utils.delay(this._worker.resume, [], this._worker); + return this; + }, + pause: function() { + this._worker.pause(); + return this; + }, + toNodejsStream: function(updateCb) { + utils.checkSupport("nodestream"); + if (this._outputType !== "nodebuffer") { + throw new Error(this._outputType + " is not supported by this method"); + } + return new NodejsStreamOutputAdapter(this, { + objectMode: this._outputType !== "nodebuffer" + }, updateCb); + } + }; + module2.exports = StreamHelper; +}); + +// node_modules/jszip/lib/defaults.js +var require_defaults = __commonJS((exports2) => { + exports2.base64 = false; + exports2.binary = false; + exports2.dir = false; + exports2.createFolders = true; + exports2.date = null; + exports2.compression = null; + exports2.compressionOptions = null; + exports2.comment = null; + exports2.unixPermissions = null; + exports2.dosPermissions = null; +}); + +// node_modules/jszip/lib/stream/DataWorker.js +var require_DataWorker = __commonJS((exports2, module2) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var DEFAULT_BLOCK_SIZE = 16 * 1024; + function DataWorker(dataP) { + GenericWorker.call(this, "DataWorker"); + var self2 = this; + this.dataIsReady = false; + this.index = 0; + this.max = 0; + this.data = null; + this.type = ""; + this._tickScheduled = false; + dataP.then(function(data2) { + self2.dataIsReady = true; + self2.data = data2; + self2.max = data2 && data2.length || 0; + self2.type = utils.getTypeOf(data2); + if (!self2.isPaused) { + self2._tickAndRepeat(); + } + }, function(e) { + self2.error(e); + }); + } + utils.inherits(DataWorker, GenericWorker); + DataWorker.prototype.cleanUp = function() { + GenericWorker.prototype.cleanUp.call(this); + this.data = null; + }; + DataWorker.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) { + return false; + } + if (!this._tickScheduled && this.dataIsReady) { + this._tickScheduled = true; + utils.delay(this._tickAndRepeat, [], this); + } + return true; + }; + DataWorker.prototype._tickAndRepeat = function() { + this._tickScheduled = false; + if (this.isPaused || this.isFinished) { + return; + } + this._tick(); + if (!this.isFinished) { + utils.delay(this._tickAndRepeat, [], this); + this._tickScheduled = true; + } + }; + DataWorker.prototype._tick = function() { + if (this.isPaused || this.isFinished) { + return false; + } + var size = DEFAULT_BLOCK_SIZE; + var data2 = null, nextIndex = Math.min(this.max, this.index + size); + if (this.index >= this.max) { + return this.end(); + } else { + switch (this.type) { + case "string": + data2 = this.data.substring(this.index, nextIndex); + break; + case "uint8array": + data2 = this.data.subarray(this.index, nextIndex); + break; + case "array": + case "nodebuffer": + data2 = this.data.slice(this.index, nextIndex); + break; + } + this.index = nextIndex; + return this.push({ + data: data2, + meta: { + percent: this.max ? this.index / this.max * 100 : 0 + } + }); + } + }; + module2.exports = DataWorker; +}); + +// node_modules/jszip/lib/crc32.js +var require_crc32 = __commonJS((exports2, module2) => { + var utils = require_utils(); + function makeTable() { + var c, table = []; + for (var n = 0;n < 256; n++) { + c = n; + for (var k2 = 0;k2 < 8; k2++) { + c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; + } + table[n] = c; + } + return table; + } + var crcTable = makeTable(); + function crc32(crc, buf, len, pos) { + var t = crcTable, end = pos + len; + crc = crc ^ -1; + for (var i = pos;i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255]; + } + return crc ^ -1; + } + function crc32str(crc, str, len, pos) { + var t = crcTable, end = pos + len; + crc = crc ^ -1; + for (var i = pos;i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ str.charCodeAt(i)) & 255]; + } + return crc ^ -1; + } + module2.exports = function crc32wrapper(input, crc) { + if (typeof input === "undefined" || !input.length) { + return 0; + } + var isArray2 = utils.getTypeOf(input) !== "string"; + if (isArray2) { + return crc32(crc | 0, input, input.length, 0); + } else { + return crc32str(crc | 0, input, input.length, 0); + } + }; +}); + +// node_modules/jszip/lib/stream/Crc32Probe.js +var require_Crc32Probe = __commonJS((exports2, module2) => { + var GenericWorker = require_GenericWorker(); + var crc32 = require_crc32(); + var utils = require_utils(); + function Crc32Probe() { + GenericWorker.call(this, "Crc32Probe"); + this.withStreamInfo("crc32", 0); + } + utils.inherits(Crc32Probe, GenericWorker); + Crc32Probe.prototype.processChunk = function(chunk) { + this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0); + this.push(chunk); + }; + module2.exports = Crc32Probe; +}); + +// node_modules/jszip/lib/stream/DataLengthProbe.js +var require_DataLengthProbe = __commonJS((exports2, module2) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + function DataLengthProbe(propName) { + GenericWorker.call(this, "DataLengthProbe for " + propName); + this.propName = propName; + this.withStreamInfo(propName, 0); + } + utils.inherits(DataLengthProbe, GenericWorker); + DataLengthProbe.prototype.processChunk = function(chunk) { + if (chunk) { + var length2 = this.streamInfo[this.propName] || 0; + this.streamInfo[this.propName] = length2 + chunk.data.length; + } + GenericWorker.prototype.processChunk.call(this, chunk); + }; + module2.exports = DataLengthProbe; +}); + +// node_modules/jszip/lib/compressedObject.js +var require_compressedObject = __commonJS((exports2, module2) => { + var external = require_external(); + var DataWorker = require_DataWorker(); + var Crc32Probe = require_Crc32Probe(); + var DataLengthProbe = require_DataLengthProbe(); + function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data2) { + this.compressedSize = compressedSize; + this.uncompressedSize = uncompressedSize; + this.crc32 = crc32; + this.compression = compression; + this.compressedContent = data2; + } + CompressedObject.prototype = { + getContentWorker: function() { + var worker = new DataWorker(external.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new DataLengthProbe("data_length")); + var that = this; + worker.on("end", function() { + if (this.streamInfo["data_length"] !== that.uncompressedSize) { + throw new Error("Bug : uncompressed data size mismatch"); + } + }); + return worker; + }, + getCompressedWorker: function() { + return new DataWorker(external.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize", this.compressedSize).withStreamInfo("uncompressedSize", this.uncompressedSize).withStreamInfo("crc32", this.crc32).withStreamInfo("compression", this.compression); + } + }; + CompressedObject.createWorkerFrom = function(uncompressedWorker, compression, compressionOptions) { + return uncompressedWorker.pipe(new Crc32Probe).pipe(new DataLengthProbe("uncompressedSize")).pipe(compression.compressWorker(compressionOptions)).pipe(new DataLengthProbe("compressedSize")).withStreamInfo("compression", compression); + }; + module2.exports = CompressedObject; +}); + +// node_modules/jszip/lib/zipObject.js +var require_zipObject = __commonJS((exports2, module2) => { + var StreamHelper = require_StreamHelper(); + var DataWorker = require_DataWorker(); + var utf8 = require_utf8(); + var CompressedObject = require_compressedObject(); + var GenericWorker = require_GenericWorker(); + var ZipObject = function(name2, data2, options) { + this.name = name2; + this.dir = options.dir; + this.date = options.date; + this.comment = options.comment; + this.unixPermissions = options.unixPermissions; + this.dosPermissions = options.dosPermissions; + this._data = data2; + this._dataBinary = options.binary; + this.options = { + compression: options.compression, + compressionOptions: options.compressionOptions + }; + }; + ZipObject.prototype = { + internalStream: function(type) { + var result = null, outputType = "string"; + try { + if (!type) { + throw new Error("No output type specified."); + } + outputType = type.toLowerCase(); + var askUnicodeString = outputType === "string" || outputType === "text"; + if (outputType === "binarystring" || outputType === "text") { + outputType = "string"; + } + result = this._decompressWorker(); + var isUnicodeString = !this._dataBinary; + if (isUnicodeString && !askUnicodeString) { + result = result.pipe(new utf8.Utf8EncodeWorker); + } + if (!isUnicodeString && askUnicodeString) { + result = result.pipe(new utf8.Utf8DecodeWorker); + } + } catch (e) { + result = new GenericWorker("error"); + result.error(e); + } + return new StreamHelper(result, outputType, ""); + }, + async: function(type, onUpdate) { + return this.internalStream(type).accumulate(onUpdate); + }, + nodeStream: function(type, onUpdate) { + return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate); + }, + _compressWorker: function(compression, compressionOptions) { + if (this._data instanceof CompressedObject && this._data.compression.magic === compression.magic) { + return this._data.getCompressedWorker(); + } else { + var result = this._decompressWorker(); + if (!this._dataBinary) { + result = result.pipe(new utf8.Utf8EncodeWorker); + } + return CompressedObject.createWorkerFrom(result, compression, compressionOptions); + } + }, + _decompressWorker: function() { + if (this._data instanceof CompressedObject) { + return this._data.getContentWorker(); + } else if (this._data instanceof GenericWorker) { + return this._data; + } else { + return new DataWorker(this._data); + } + } + }; + var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"]; + var removedFn = function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }; + for (i = 0;i < removedMethods.length; i++) { + ZipObject.prototype[removedMethods[i]] = removedFn; + } + var i; + module2.exports = ZipObject; +}); + +// node_modules/pako/lib/utils/common.js +var require_common = __commonJS((exports2) => { + var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined"; + function _has(obj, key2) { + return Object.prototype.hasOwnProperty.call(obj, key2); + } + exports2.assign = function(obj) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { + continue; + } + if (typeof source !== "object") { + throw new TypeError(source + "must be non-object"); + } + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + return obj; + }; + exports2.shrinkBuf = function(buf, size) { + if (buf.length === size) { + return buf; + } + if (buf.subarray) { + return buf.subarray(0, size); + } + buf.length = size; + return buf; + }; + var fnTyped = { + arraySet: function(dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + for (var i = 0;i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + flattenChunks: function(chunks) { + var i, l, len, pos, chunk, result; + len = 0; + for (i = 0, l = chunks.length;i < l; i++) { + len += chunks[i].length; + } + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length;i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + return result; + } + }; + var fnUntyped = { + arraySet: function(dest, src, src_offs, len, dest_offs) { + for (var i = 0;i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + flattenChunks: function(chunks) { + return [].concat.apply([], chunks); + } + }; + exports2.setTyped = function(on) { + if (on) { + exports2.Buf8 = Uint8Array; + exports2.Buf16 = Uint16Array; + exports2.Buf32 = Int32Array; + exports2.assign(exports2, fnTyped); + } else { + exports2.Buf8 = Array; + exports2.Buf16 = Array; + exports2.Buf32 = Array; + exports2.assign(exports2, fnUntyped); + } + }; + exports2.setTyped(TYPED_OK); +}); + +// node_modules/pako/lib/zlib/trees.js +var require_trees = __commonJS((exports2) => { + var utils = require_common(); + var Z_FIXED = 4; + var Z_BINARY = 0; + var Z_TEXT = 1; + var Z_UNKNOWN = 2; + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + var STORED_BLOCK = 0; + var STATIC_TREES = 1; + var DYN_TREES = 2; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var Buf_size = 16; + var MAX_BL_BITS = 7; + var END_BLOCK = 256; + var REP_3_6 = 16; + var REPZ_3_10 = 17; + var REPZ_11_138 = 18; + var 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]; + var 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]; + var extra_blbits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]; + var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + var DIST_CODE_LEN = 512; + var static_ltree = new Array((L_CODES + 2) * 2); + zero(static_ltree); + var static_dtree = new Array(D_CODES * 2); + zero(static_dtree); + var _dist_code = new Array(DIST_CODE_LEN); + zero(_dist_code); + var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); + zero(_length_code); + var base_length = new Array(LENGTH_CODES); + zero(base_length); + var base_dist = new Array(D_CODES); + zero(base_dist); + function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + this.static_tree = static_tree; + this.extra_bits = extra_bits; + this.extra_base = extra_base; + this.elems = elems; + this.max_length = max_length; + this.has_stree = static_tree && static_tree.length; + } + var static_l_desc; + var static_d_desc; + var static_bl_desc; + function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; + this.max_code = 0; + this.stat_desc = stat_desc; + } + function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; + } + function put_short(s, w) { + s.pending_buf[s.pending++] = w & 255; + s.pending_buf[s.pending++] = w >>> 8 & 255; + } + function send_bits(s, value2, length2) { + if (s.bi_valid > Buf_size - length2) { + s.bi_buf |= value2 << s.bi_valid & 65535; + put_short(s, s.bi_buf); + s.bi_buf = value2 >> Buf_size - s.bi_valid; + s.bi_valid += length2 - Buf_size; + } else { + s.bi_buf |= value2 << s.bi_valid & 65535; + s.bi_valid += length2; + } + } + function send_code(s, c, tree) { + send_bits(s, tree[c * 2], tree[c * 2 + 1]); + } + function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; + } + function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 255; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } + } + function gen_bitlen(s, desc) { + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; + var n, m; + var bits; + var xbits; + var f; + var overflow = 0; + for (bits = 0;bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + tree[s.heap[s.heap_max] * 2 + 1] = 0; + for (h = s.heap_max + 1;h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1] = bits; + if (n > max_code) { + continue; + } + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1] + xbits); + } + } + if (overflow === 0) { + return; + } + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { + bits--; + } + s.bl_count[bits]--; + s.bl_count[bits + 1] += 2; + s.bl_count[max_length]--; + overflow -= 2; + } while (overflow > 0); + for (bits = max_length;bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { + continue; + } + if (tree[m * 2 + 1] !== bits) { + s.opt_len += (bits - tree[m * 2 + 1]) * tree[m * 2]; + tree[m * 2 + 1] = bits; + } + n--; + } + } + } + function gen_codes(tree, max_code, bl_count) { + var next_code = new Array(MAX_BITS + 1); + var code = 0; + var bits; + var n; + for (bits = 1;bits <= MAX_BITS; bits++) { + next_code[bits] = code = code + bl_count[bits - 1] << 1; + } + for (n = 0;n <= max_code; n++) { + var len = tree[n * 2 + 1]; + if (len === 0) { + continue; + } + tree[n * 2] = bi_reverse(next_code[len]++, len); + } + } + function tr_static_init() { + var n; + var bits; + var length2; + var code; + var dist; + var bl_count = new Array(MAX_BITS + 1); + length2 = 0; + for (code = 0;code < LENGTH_CODES - 1; code++) { + base_length[code] = length2; + for (n = 0;n < 1 << extra_lbits[code]; n++) { + _length_code[length2++] = code; + } + } + _length_code[length2 - 1] = code; + dist = 0; + for (code = 0;code < 16; code++) { + base_dist[code] = dist; + for (n = 0;n < 1 << extra_dbits[code]; n++) { + _dist_code[dist++] = code; + } + } + dist >>= 7; + for (;code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0;n < 1 << extra_dbits[code] - 7; n++) { + _dist_code[256 + dist++] = code; + } + } + for (bits = 0;bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1] = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1] = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1] = 8; + n++; + bl_count[8]++; + } + gen_codes(static_ltree, L_CODES + 1, bl_count); + for (n = 0;n < D_CODES; n++) { + static_dtree[n * 2 + 1] = 5; + static_dtree[n * 2] = bi_reverse(n, 5); + } + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + } + function init_block(s) { + var n; + for (n = 0;n < L_CODES; n++) { + s.dyn_ltree[n * 2] = 0; + } + for (n = 0;n < D_CODES; n++) { + s.dyn_dtree[n * 2] = 0; + } + for (n = 0;n < BL_CODES; n++) { + s.bl_tree[n * 2] = 0; + } + s.dyn_ltree[END_BLOCK * 2] = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; + } + function bi_windup(s) { + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; + } + function copy_block(s, buf, len, header) { + bi_windup(s); + if (header) { + put_short(s, len); + put_short(s, ~len); + } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; + } + function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return tree[_n2] < tree[_m2] || tree[_n2] === tree[_m2] && depth[n] <= depth[m]; + } + function pqdownheap(s, tree, k2) { + var v = s.heap[k2]; + var j = k2 << 1; + while (j <= s.heap_len) { + if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + if (smaller(tree, v, s.heap[j], s.depth)) { + break; + } + s.heap[k2] = s.heap[j]; + k2 = j; + j <<= 1; + } + s.heap[k2] = v; + } + function compress_block(s, ltree, dtree) { + var dist; + var lc; + var lx = 0; + var code; + var extra; + if (s.last_lit !== 0) { + do { + dist = s.pending_buf[s.d_buf + lx * 2] << 8 | s.pending_buf[s.d_buf + lx * 2 + 1]; + lc = s.pending_buf[s.l_buf + lx]; + lx++; + if (dist === 0) { + send_code(s, lc, ltree); + } else { + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); + } + dist--; + code = d_code(dist); + send_code(s, code, dtree); + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); + } + } + } while (lx < s.last_lit); + } + send_code(s, END_BLOCK, ltree); + } + function build_tree(s, desc) { + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; + var max_code = -1; + var node; + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + for (n = 0;n < elems; n++) { + if (tree[n * 2] !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + } else { + tree[n * 2 + 1] = 0; + } + } + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = max_code < 2 ? ++max_code : 0; + tree[node * 2] = 1; + s.depth[node] = 0; + s.opt_len--; + if (has_stree) { + s.static_len -= stree[node * 2 + 1]; + } + } + desc.max_code = max_code; + for (n = s.heap_len >> 1;n >= 1; n--) { + pqdownheap(s, tree, n); + } + node = elems; + do { + n = s.heap[1]; + s.heap[1] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1); + m = s.heap[1]; + s.heap[--s.heap_max] = n; + s.heap[--s.heap_max] = m; + tree[node * 2] = tree[n * 2] + tree[m * 2]; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1] = tree[m * 2 + 1] = node; + s.heap[1] = node++; + pqdownheap(s, tree, 1); + } while (s.heap_len >= 2); + s.heap[--s.heap_max] = s.heap[1]; + gen_bitlen(s, desc); + gen_codes(tree, max_code, s.bl_count); + } + function scan_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[0 * 2 + 1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1] = 65535; + for (n = 0;n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) { + continue; + } else if (count < min_count) { + s.bl_tree[curlen * 2] += count; + } else if (curlen !== 0) { + if (curlen !== prevlen) { + s.bl_tree[curlen * 2]++; + } + s.bl_tree[REP_3_6 * 2]++; + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]++; + } else { + s.bl_tree[REPZ_11_138 * 2]++; + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function send_tree(s, tree, max_code) { + var n; + var prevlen = -1; + var curlen; + var nextlen = tree[0 * 2 + 1]; + var count = 0; + var max_count = 7; + var min_count = 4; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + for (n = 0;n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]; + if (++count < max_count && curlen === nextlen) { + continue; + } else if (count < min_count) { + do { + send_code(s, curlen, s.bl_tree); + } while (--count !== 0); + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + } else { + max_count = 7; + min_count = 4; + } + } + } + function build_bl_tree(s) { + var max_blindex; + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + build_tree(s, s.bl_desc); + for (max_blindex = BL_CODES - 1;max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1] !== 0) { + break; + } + } + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + return max_blindex; + } + function send_all_trees(s, lcodes, dcodes, blcodes) { + var rank; + send_bits(s, lcodes - 257, 5); + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); + for (rank = 0;rank < blcodes; rank++) { + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1], 3); + } + send_tree(s, s.dyn_ltree, lcodes - 1); + send_tree(s, s.dyn_dtree, dcodes - 1); + } + function detect_data_type(s) { + var black_mask = 4093624447; + var n; + for (n = 0;n <= 31; n++, black_mask >>>= 1) { + if (black_mask & 1 && s.dyn_ltree[n * 2] !== 0) { + return Z_BINARY; + } + } + if (s.dyn_ltree[9 * 2] !== 0 || s.dyn_ltree[10 * 2] !== 0 || s.dyn_ltree[13 * 2] !== 0) { + return Z_TEXT; + } + for (n = 32;n < LITERALS; n++) { + if (s.dyn_ltree[n * 2] !== 0) { + return Z_TEXT; + } + } + return Z_BINARY; + } + var static_init_done = false; + function _tr_init(s) { + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + s.bi_buf = 0; + s.bi_valid = 0; + init_block(s); + } + function _tr_stored_block(s, buf, stored_len, last2) { + send_bits(s, (STORED_BLOCK << 1) + (last2 ? 1 : 0), 3); + copy_block(s, buf, stored_len, true); + } + function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); + } + function _tr_flush_block(s, buf, stored_len, last2) { + var opt_lenb, static_lenb; + var max_blindex = 0; + if (s.level > 0) { + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + build_tree(s, s.l_desc); + build_tree(s, s.d_desc); + max_blindex = build_bl_tree(s); + opt_lenb = s.opt_len + 3 + 7 >>> 3; + static_lenb = s.static_len + 3 + 7 >>> 3; + if (static_lenb <= opt_lenb) { + opt_lenb = static_lenb; + } + } else { + opt_lenb = static_lenb = stored_len + 5; + } + if (stored_len + 4 <= opt_lenb && buf !== -1) { + _tr_stored_block(s, buf, stored_len, last2); + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + send_bits(s, (STATIC_TREES << 1) + (last2 ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + } else { + send_bits(s, (DYN_TREES << 1) + (last2 ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + init_block(s); + if (last2) { + bi_windup(s); + } + } + function _tr_tally(s, dist, lc) { + s.pending_buf[s.d_buf + s.last_lit * 2] = dist >>> 8 & 255; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 255; + s.pending_buf[s.l_buf + s.last_lit] = lc & 255; + s.last_lit++; + if (dist === 0) { + s.dyn_ltree[lc * 2]++; + } else { + s.matches++; + dist--; + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]++; + s.dyn_dtree[d_code(dist) * 2]++; + } + return s.last_lit === s.lit_bufsize - 1; + } + exports2._tr_init = _tr_init; + exports2._tr_stored_block = _tr_stored_block; + exports2._tr_flush_block = _tr_flush_block; + exports2._tr_tally = _tr_tally; + exports2._tr_align = _tr_align; +}); + +// node_modules/pako/lib/zlib/adler32.js +var require_adler32 = __commonJS((exports2, module2) => { + function adler32(adler, buf, len, pos) { + var s1 = adler & 65535 | 0, s2 = adler >>> 16 & 65535 | 0, n = 0; + while (len !== 0) { + n = len > 2000 ? 2000 : len; + len -= n; + do { + s1 = s1 + buf[pos++] | 0; + s2 = s2 + s1 | 0; + } while (--n); + s1 %= 65521; + s2 %= 65521; + } + return s1 | s2 << 16 | 0; + } + module2.exports = adler32; +}); + +// node_modules/pako/lib/zlib/crc32.js +var require_crc322 = __commonJS((exports2, module2) => { + function makeTable() { + var c, table = []; + for (var n = 0;n < 256; n++) { + c = n; + for (var k2 = 0;k2 < 8; k2++) { + c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1; + } + table[n] = c; + } + return table; + } + var crcTable = makeTable(); + function crc32(crc, buf, len, pos) { + var t = crcTable, end = pos + len; + crc ^= -1; + for (var i = pos;i < end; i++) { + crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 255]; + } + return crc ^ -1; + } + module2.exports = crc32; +}); + +// node_modules/pako/lib/zlib/messages.js +var require_messages = __commonJS((exports2, module2) => { + module2.exports = { + 2: "need dictionary", + 1: "stream end", + 0: "", + "-1": "file error", + "-2": "stream error", + "-3": "data error", + "-4": "insufficient memory", + "-5": "buffer error", + "-6": "incompatible version" + }; +}); + +// node_modules/pako/lib/zlib/deflate.js +var require_deflate = __commonJS((exports2) => { + var utils = require_common(); + var trees = require_trees(); + var adler32 = require_adler32(); + var crc32 = require_crc322(); + var msg = require_messages(); + var Z_NO_FLUSH = 0; + var Z_PARTIAL_FLUSH = 1; + var Z_FULL_FLUSH = 3; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_BUF_ERROR = -5; + var Z_DEFAULT_COMPRESSION = -1; + var Z_FILTERED = 1; + var Z_HUFFMAN_ONLY = 2; + var Z_RLE = 3; + var Z_FIXED = 4; + var Z_DEFAULT_STRATEGY = 0; + var Z_UNKNOWN = 2; + var Z_DEFLATED = 8; + var MAX_MEM_LEVEL = 9; + var MAX_WBITS = 15; + var DEF_MEM_LEVEL = 8; + var LENGTH_CODES = 29; + var LITERALS = 256; + var L_CODES = LITERALS + 1 + LENGTH_CODES; + var D_CODES = 30; + var BL_CODES = 19; + var HEAP_SIZE = 2 * L_CODES + 1; + var MAX_BITS = 15; + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1; + var PRESET_DICT = 32; + var INIT_STATE = 42; + var EXTRA_STATE = 69; + var NAME_STATE = 73; + var COMMENT_STATE = 91; + var HCRC_STATE = 103; + var BUSY_STATE = 113; + var FINISH_STATE = 666; + var BS_NEED_MORE = 1; + var BS_BLOCK_DONE = 2; + var BS_FINISH_STARTED = 3; + var BS_FINISH_DONE = 4; + var OS_CODE = 3; + function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; + } + function rank(f) { + return (f << 1) - (f > 4 ? 9 : 0); + } + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + function flush_pending(strm) { + var s = strm.state; + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { + return; + } + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } + } + function flush_block_only(s, last2) { + trees._tr_flush_block(s, s.block_start >= 0 ? s.block_start : -1, s.strstart - s.block_start, last2); + s.block_start = s.strstart; + flush_pending(s.strm); + } + function put_byte(s, b) { + s.pending_buf[s.pending++] = b; + } + function putShortMSB(s, b) { + s.pending_buf[s.pending++] = b >>> 8 & 255; + s.pending_buf[s.pending++] = b & 255; + } + function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + if (len > size) { + len = size; + } + if (len === 0) { + return 0; + } + strm.avail_in -= len; + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + strm.next_in += len; + strm.total_in += len; + return len; + } + function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; + var scan = s.strstart; + var match; + var len; + var best_len = s.prev_length; + var nice_match = s.nice_match; + var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0; + var _win = s.window; + var wmask = s.w_mask; + var prev = s.prev; + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + if (nice_match > s.lookahead) { + nice_match = s.lookahead; + } + do { + match = cur_match; + if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { + continue; + } + scan += 2; + match++; + do { + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; + } + function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + do { + more = s.window_size - s.lookahead - s.strstart; + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + s.block_start -= _w_size; + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = m >= _w_size ? m - _w_size : 0; + } while (--n); + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + 1]) & s.hash_mask; + while (s.insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + } + function deflate_stored(s, flush) { + var max_block_size = 65535; + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + for (;; ) { + if (s.lookahead <= 1) { + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + s.strstart += s.lookahead; + s.lookahead = 0; + var max_start = s.block_start + max_block_size; + if (s.strstart === 0 || s.strstart >= max_start) { + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + if (s.strstart - s.block_start >= s.w_size - MIN_LOOKAHEAD) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.strstart > s.block_start) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_NEED_MORE; + } + function deflate_fast(s, flush) { + var hash_head; + var bflush; + for (;; ) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + if (hash_head !== 0 && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + } + if (s.match_length >= MIN_MATCH) { + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + if (s.match_length <= s.max_lazy_match && s.lookahead >= MIN_MATCH) { + s.match_length--; + do { + s.strstart++; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } while (--s.match_length !== 0); + s.strstart++; + } else { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + 1]) & s.hash_mask; + } + } else { + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_slow(s, flush) { + var hash_head; + var bflush; + var max_insert; + for (;; ) { + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + hash_head = 0; + if (s.lookahead >= MIN_MATCH) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + if (hash_head !== 0 && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= s.w_size - MIN_LOOKAHEAD) { + s.match_length = longest_match(s, hash_head); + if (s.match_length <= 5 && (s.strategy === Z_FILTERED || s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096)) { + s.match_length = MIN_MATCH - 1; + } + } + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } else if (s.match_available) { + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + if (bflush) { + flush_block_only(s, false); + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + if (s.match_available) { + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_rle(s, flush) { + var bflush; + var prev; + var scan, strend; + var _win = s.window; + for (;; ) { + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } + } + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + } + if (s.match_length >= MIN_MATCH) { + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + } + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function deflate_huff(s, flush) { + var bflush; + for (;; ) { + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; + } + } + s.match_length = 0; + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + } + s.insert = 0; + if (flush === Z_FINISH) { + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + return BS_FINISH_DONE; + } + if (s.last_lit) { + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } + return BS_BLOCK_DONE; + } + function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; + } + var configuration_table; + configuration_table = [ + new Config(0, 0, 0, 0, deflate_stored), + new Config(4, 4, 8, 4, deflate_fast), + new Config(4, 5, 16, 8, deflate_fast), + new Config(4, 6, 32, 32, deflate_fast), + new Config(4, 4, 16, 16, deflate_slow), + new Config(8, 16, 32, 32, deflate_slow), + new Config(8, 16, 128, 128, deflate_slow), + new Config(8, 32, 128, 256, deflate_slow), + new Config(32, 128, 258, 1024, deflate_slow), + new Config(32, 258, 258, 4096, deflate_slow) + ]; + function lm_init(s) { + s.window_size = 2 * s.w_size; + zero(s.head); + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; + } + function DeflateState() { + this.strm = null; + this.status = 0; + this.pending_buf = null; + this.pending_buf_size = 0; + this.pending_out = 0; + this.pending = 0; + this.wrap = 0; + this.gzhead = null; + this.gzindex = 0; + this.method = Z_DEFLATED; + this.last_flush = -1; + this.w_size = 0; + this.w_bits = 0; + this.w_mask = 0; + this.window = null; + this.window_size = 0; + this.prev = null; + this.head = null; + this.ins_h = 0; + this.hash_size = 0; + this.hash_bits = 0; + this.hash_mask = 0; + this.hash_shift = 0; + this.block_start = 0; + this.match_length = 0; + this.prev_match = 0; + this.match_available = 0; + this.strstart = 0; + this.match_start = 0; + this.lookahead = 0; + this.prev_length = 0; + this.max_chain_length = 0; + this.max_lazy_match = 0; + this.level = 0; + this.strategy = 0; + this.good_match = 0; + this.nice_match = 0; + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + this.l_desc = null; + this.d_desc = null; + this.bl_desc = null; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + this.heap = new utils.Buf16(2 * L_CODES + 1); + zero(this.heap); + this.heap_len = 0; + this.heap_max = 0; + this.depth = new utils.Buf16(2 * L_CODES + 1); + zero(this.depth); + this.l_buf = 0; + this.lit_bufsize = 0; + this.last_lit = 0; + this.d_buf = 0; + this.opt_len = 0; + this.static_len = 0; + this.matches = 0; + this.insert = 0; + this.bi_buf = 0; + this.bi_valid = 0; + } + function deflateResetKeep(strm) { + var s; + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + s = strm.state; + s.pending = 0; + s.pending_out = 0; + if (s.wrap < 0) { + s.wrap = -s.wrap; + } + s.status = s.wrap ? INIT_STATE : BUSY_STATE; + strm.adler = s.wrap === 2 ? 0 : 1; + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; + } + function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; + } + function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + if (strm.state.wrap !== 2) { + return Z_STREAM_ERROR; + } + strm.state.gzhead = head; + return Z_OK; + } + function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { + return Z_STREAM_ERROR; + } + var wrap = 1; + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else if (windowBits > 15) { + wrap = 2; + windowBits -= 16; + } + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + if (windowBits === 8) { + windowBits = 9; + } + var s = new DeflateState; + strm.state = s; + s.strm = strm; + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + s.lit_bufsize = 1 << memLevel + 6; + s.pending_buf_size = s.lit_bufsize * 4; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + s.d_buf = 1 * s.lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + s.level = level; + s.strategy = strategy; + s.method = method; + return deflateReset(strm); + } + function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); + } + function deflate(strm, flush) { + var old_flush, s; + var beg, val2; + if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + s = strm.state; + if (!strm.output || !strm.input && strm.avail_in !== 0 || s.status === FINISH_STATE && flush !== Z_FINISH) { + return err(strm, strm.avail_out === 0 ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + s.strm = strm; + old_flush = s.last_flush; + s.last_flush = flush; + if (s.status === INIT_STATE) { + if (s.wrap === 2) { + strm.adler = 0; + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } else { + put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16)); + put_byte(s, s.gzhead.time & 255); + put_byte(s, s.gzhead.time >> 8 & 255); + put_byte(s, s.gzhead.time >> 16 & 255); + put_byte(s, s.gzhead.time >> 24 & 255); + put_byte(s, s.level === 9 ? 2 : s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0); + put_byte(s, s.gzhead.os & 255); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 255); + put_byte(s, s.gzhead.extra.length >> 8 & 255); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } else { + var header = Z_DEFLATED + (s.w_bits - 8 << 4) << 8; + var level_flags = -1; + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= level_flags << 6; + if (s.strstart !== 0) { + header |= PRESET_DICT; + } + header += 31 - header % 31; + s.status = BUSY_STATE; + putShortMSB(s, header); + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + strm.adler = 1; + } + } + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra) { + beg = s.pending; + while (s.gzindex < (s.gzhead.extra.length & 65535)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 255); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val2 = 1; + break; + } + } + if (s.gzindex < s.gzhead.name.length) { + val2 = s.gzhead.name.charCodeAt(s.gzindex++) & 255; + } else { + val2 = 0; + } + put_byte(s, val2); + } while (val2 !== 0); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val2 === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment) { + beg = s.pending; + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val2 = 1; + break; + } + } + if (s.gzindex < s.gzhead.comment.length) { + val2 = s.gzhead.comment.charCodeAt(s.gzindex++) & 255; + } else { + val2 = 0; + } + put_byte(s, val2); + } while (val2 !== 0); + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val2 === 0) { + s.status = HCRC_STATE; + } + } else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + strm.adler = 0; + s.status = BUSY_STATE; + } + } else { + s.status = BUSY_STATE; + } + } + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + if (strm.avail_in !== 0 || s.lookahead !== 0 || flush !== Z_NO_FLUSH && s.status !== FINISH_STATE) { + var bstate = s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush); + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + } + return Z_OK; + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } else if (flush !== Z_BLOCK) { + trees._tr_stored_block(s, 0, 0, false); + if (flush === Z_FULL_FLUSH) { + zero(s.head); + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; + return Z_OK; + } + } + } + if (flush !== Z_FINISH) { + return Z_OK; + } + if (s.wrap <= 0) { + return Z_STREAM_END; + } + if (s.wrap === 2) { + put_byte(s, strm.adler & 255); + put_byte(s, strm.adler >> 8 & 255); + put_byte(s, strm.adler >> 16 & 255); + put_byte(s, strm.adler >> 24 & 255); + put_byte(s, strm.total_in & 255); + put_byte(s, strm.total_in >> 8 & 255); + put_byte(s, strm.total_in >> 16 & 255); + put_byte(s, strm.total_in >> 24 & 255); + } else { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 65535); + } + flush_pending(strm); + if (s.wrap > 0) { + s.wrap = -s.wrap; + } + return s.pending !== 0 ? Z_OK : Z_STREAM_END; + } + function deflateEnd(strm) { + var status; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + status = strm.state.status; + if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE) { + return err(strm, Z_STREAM_ERROR); + } + strm.state = null; + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; + } + function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + s = strm.state; + wrap = s.wrap; + if (wrap === 2 || wrap === 1 && s.status !== INIT_STATE || s.lookahead) { + return Z_STREAM_ERROR; + } + if (wrap === 1) { + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + s.wrap = 0; + if (dictLength >= s.w_size) { + if (wrap === 0) { + zero(s.head); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + s.ins_h = (s.ins_h << s.hash_shift ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; + } + exports2.deflateInit = deflateInit; + exports2.deflateInit2 = deflateInit2; + exports2.deflateReset = deflateReset; + exports2.deflateResetKeep = deflateResetKeep; + exports2.deflateSetHeader = deflateSetHeader; + exports2.deflate = deflate; + exports2.deflateEnd = deflateEnd; + exports2.deflateSetDictionary = deflateSetDictionary; + exports2.deflateInfo = "pako deflate (from Nodeca project)"; +}); + +// node_modules/pako/lib/utils/strings.js +var require_strings = __commonJS((exports2) => { + var utils = require_common(); + var STR_APPLY_OK = true; + var STR_APPLY_UIA_OK = true; + try { + String.fromCharCode.apply(null, [0]); + } catch (__) { + STR_APPLY_OK = false; + } + try { + String.fromCharCode.apply(null, new Uint8Array(1)); + } catch (__) { + STR_APPLY_UIA_OK = false; + } + var _utf8len = new utils.Buf8(256); + for (q = 0;q < 256; q++) { + _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1; + } + var q; + _utf8len[254] = _utf8len[254] = 1; + exports2.string2buf = function(str) { + var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; + for (m_pos = 0;m_pos < str_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + buf_len += c < 128 ? 1 : c < 2048 ? 2 : c < 65536 ? 3 : 4; + } + buf = new utils.Buf8(buf_len); + for (i = 0, m_pos = 0;i < buf_len; m_pos++) { + c = str.charCodeAt(m_pos); + if ((c & 64512) === 55296 && m_pos + 1 < str_len) { + c2 = str.charCodeAt(m_pos + 1); + if ((c2 & 64512) === 56320) { + c = 65536 + (c - 55296 << 10) + (c2 - 56320); + m_pos++; + } + } + if (c < 128) { + buf[i++] = c; + } else if (c < 2048) { + buf[i++] = 192 | c >>> 6; + buf[i++] = 128 | c & 63; + } else if (c < 65536) { + buf[i++] = 224 | c >>> 12; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } else { + buf[i++] = 240 | c >>> 18; + buf[i++] = 128 | c >>> 12 & 63; + buf[i++] = 128 | c >>> 6 & 63; + buf[i++] = 128 | c & 63; + } + } + return buf; + }; + function buf2binstring(buf, len) { + if (len < 65534) { + if (buf.subarray && STR_APPLY_UIA_OK || !buf.subarray && STR_APPLY_OK) { + return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); + } + } + var result = ""; + for (var i = 0;i < len; i++) { + result += String.fromCharCode(buf[i]); + } + return result; + } + exports2.buf2binstring = function(buf) { + return buf2binstring(buf, buf.length); + }; + exports2.binstring2buf = function(str) { + var buf = new utils.Buf8(str.length); + for (var i = 0, len = buf.length;i < len; i++) { + buf[i] = str.charCodeAt(i); + } + return buf; + }; + exports2.buf2string = function(buf, max) { + var i, out, c, c_len; + var len = max || buf.length; + var utf16buf = new Array(len * 2); + for (out = 0, i = 0;i < len; ) { + c = buf[i++]; + if (c < 128) { + utf16buf[out++] = c; + continue; + } + c_len = _utf8len[c]; + if (c_len > 4) { + utf16buf[out++] = 65533; + i += c_len - 1; + continue; + } + c &= c_len === 2 ? 31 : c_len === 3 ? 15 : 7; + while (c_len > 1 && i < len) { + c = c << 6 | buf[i++] & 63; + c_len--; + } + if (c_len > 1) { + utf16buf[out++] = 65533; + continue; + } + if (c < 65536) { + utf16buf[out++] = c; + } else { + c -= 65536; + utf16buf[out++] = 55296 | c >> 10 & 1023; + utf16buf[out++] = 56320 | c & 1023; + } + } + return buf2binstring(utf16buf, out); + }; + exports2.utf8border = function(buf, max) { + var pos; + max = max || buf.length; + if (max > buf.length) { + max = buf.length; + } + pos = max - 1; + while (pos >= 0 && (buf[pos] & 192) === 128) { + pos--; + } + if (pos < 0) { + return max; + } + if (pos === 0) { + return max; + } + return pos + _utf8len[buf[pos]] > max ? pos : max; + }; +}); + +// node_modules/pako/lib/zlib/zstream.js +var require_zstream = __commonJS((exports2, module2) => { + function ZStream() { + this.input = null; + this.next_in = 0; + this.avail_in = 0; + this.total_in = 0; + this.output = null; + this.next_out = 0; + this.avail_out = 0; + this.total_out = 0; + this.msg = ""; + this.state = null; + this.data_type = 2; + this.adler = 0; + } + module2.exports = ZStream; +}); + +// node_modules/pako/lib/deflate.js +var require_deflate2 = __commonJS((exports2) => { + var zlib_deflate = require_deflate(); + var utils = require_common(); + var strings = require_strings(); + var msg = require_messages(); + var ZStream = require_zstream(); + var toString2 = Object.prototype.toString; + var Z_NO_FLUSH = 0; + var Z_FINISH = 4; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_SYNC_FLUSH = 2; + var Z_DEFAULT_COMPRESSION = -1; + var Z_DEFAULT_STRATEGY = 0; + var Z_DEFLATED = 8; + function Deflate(options) { + if (!(this instanceof Deflate)) + return new Deflate(options); + this.options = utils.assign({ + level: Z_DEFAULT_COMPRESSION, + method: Z_DEFLATED, + chunkSize: 16384, + windowBits: 15, + memLevel: 8, + strategy: Z_DEFAULT_STRATEGY, + to: "" + }, options || {}); + var opt = this.options; + if (opt.raw && opt.windowBits > 0) { + opt.windowBits = -opt.windowBits; + } else if (opt.gzip && opt.windowBits > 0 && opt.windowBits < 16) { + opt.windowBits += 16; + } + this.err = 0; + this.msg = ""; + this.ended = false; + this.chunks = []; + this.strm = new ZStream; + this.strm.avail_out = 0; + var status = zlib_deflate.deflateInit2(this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy); + if (status !== Z_OK) { + throw new Error(msg[status]); + } + if (opt.header) { + zlib_deflate.deflateSetHeader(this.strm, opt.header); + } + if (opt.dictionary) { + var dict; + if (typeof opt.dictionary === "string") { + dict = strings.string2buf(opt.dictionary); + } else if (toString2.call(opt.dictionary) === "[object ArrayBuffer]") { + dict = new Uint8Array(opt.dictionary); + } else { + dict = opt.dictionary; + } + status = zlib_deflate.deflateSetDictionary(this.strm, dict); + if (status !== Z_OK) { + throw new Error(msg[status]); + } + this._dict_set = true; + } + } + Deflate.prototype.push = function(data2, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var status, _mode; + if (this.ended) { + return false; + } + _mode = mode === ~~mode ? mode : mode === true ? Z_FINISH : Z_NO_FLUSH; + if (typeof data2 === "string") { + strm.input = strings.string2buf(data2); + } else if (toString2.call(data2) === "[object ArrayBuffer]") { + strm.input = new Uint8Array(data2); + } else { + strm.input = data2; + } + strm.next_in = 0; + strm.avail_in = strm.input.length; + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_deflate.deflate(strm, _mode); + if (status !== Z_STREAM_END && status !== Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.avail_out === 0 || strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH)) { + if (this.options.to === "string") { + this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); + if (_mode === Z_FINISH) { + status = zlib_deflate.deflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === Z_OK; + } + if (_mode === Z_SYNC_FLUSH) { + this.onEnd(Z_OK); + strm.avail_out = 0; + return true; + } + return true; + }; + Deflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); + }; + Deflate.prototype.onEnd = function(status) { + if (status === Z_OK) { + if (this.options.to === "string") { + this.result = this.chunks.join(""); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; + function deflate(input, options) { + var deflator = new Deflate(options); + deflator.push(input, true); + if (deflator.err) { + throw deflator.msg || msg[deflator.err]; + } + return deflator.result; + } + function deflateRaw(input, options) { + options = options || {}; + options.raw = true; + return deflate(input, options); + } + function gzip(input, options) { + options = options || {}; + options.gzip = true; + return deflate(input, options); + } + exports2.Deflate = Deflate; + exports2.deflate = deflate; + exports2.deflateRaw = deflateRaw; + exports2.gzip = gzip; +}); + +// node_modules/pako/lib/zlib/inffast.js +var require_inffast = __commonJS((exports2, module2) => { + var BAD = 30; + var TYPE = 12; + module2.exports = function inflate_fast(strm, start) { + var state; + var _in; + var last2; + var _out; + var beg; + var end; + var dmax; + var wsize; + var whave; + var wnext; + var s_window; + var hold; + var bits; + var lcode; + var dcode; + var lmask; + var dmask; + var here; + var op; + var len; + var dist; + var from; + var from_source; + var input, output; + state = strm.state; + _in = strm.next_in; + input = strm.input; + last2 = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); + dmax = state.dmax; + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + for (;; ) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op === 0) { + output[_out++] = here & 65535; + } else if (op & 16) { + len = here & 65535; + op &= 15; + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & (1 << op) - 1; + hold >>>= op; + bits -= op; + } + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + for (;; ) { + op = here >>> 24; + hold >>>= op; + bits -= op; + op = here >>> 16 & 255; + if (op & 16) { + dist = here & 65535; + op &= 15; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & (1 << op) - 1; + if (dist > dmax) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break top; + } + hold >>>= op; + bits -= op; + op = _out - beg; + if (dist > op) { + op = dist - op; + if (op > whave) { + if (state.sane) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break top; + } + } + from = 0; + from_source = s_window; + if (wnext === 0) { + from += wsize - op; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } else if (wnext < op) { + from += wsize + wnext - op; + op -= wnext; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } + } else { + from += wnext - op; + if (op < len) { + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } else { + from = _out - dist; + do { + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } else if ((op & 64) === 0) { + here = dcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dodist; + } else { + strm.msg = "invalid distance code"; + state.mode = BAD; + break top; + } + break; + } + } else if ((op & 64) === 0) { + here = lcode[(here & 65535) + (hold & (1 << op) - 1)]; + continue dolen; + } else if (op & 32) { + state.mode = TYPE; + break top; + } else { + strm.msg = "invalid literal/length code"; + state.mode = BAD; + break top; + } + break; + } + } while (_in < last2 && _out < end); + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = _in < last2 ? 5 + (last2 - _in) : 5 - (_in - last2); + strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); + state.hold = hold; + state.bits = bits; + return; + }; +}); + +// node_modules/pako/lib/zlib/inftrees.js +var require_inftrees = __commonJS((exports2, module2) => { + var utils = require_common(); + var MAXBITS = 15; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var lbase = [ + 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 + ]; + var lext = [ + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 16, + 17, + 17, + 17, + 17, + 18, + 18, + 18, + 18, + 19, + 19, + 19, + 19, + 20, + 20, + 20, + 20, + 21, + 21, + 21, + 21, + 16, + 72, + 78 + ]; + var dbase = [ + 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, + 0, + 0 + ]; + var dext = [ + 16, + 16, + 16, + 16, + 17, + 17, + 18, + 18, + 19, + 19, + 20, + 20, + 21, + 21, + 22, + 22, + 23, + 23, + 24, + 24, + 25, + 25, + 26, + 26, + 27, + 27, + 28, + 28, + 29, + 29, + 64, + 64 + ]; + module2.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { + var bits = opts.bits; + var len = 0; + var sym = 0; + var min = 0, max = 0; + var root = 0; + var curr = 0; + var drop2 = 0; + var left = 0; + var used = 0; + var huff = 0; + var incr; + var fill2; + var low; + var mask2; + var next; + var base = null; + var base_index = 0; + var end; + var count = new utils.Buf16(MAXBITS + 1); + var offs = new utils.Buf16(MAXBITS + 1); + var extra = null; + var extra_index = 0; + var here_bits, here_op, here_val; + for (len = 0;len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0;sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + root = bits; + for (max = MAXBITS;max >= 1; max--) { + if (count[max] !== 0) { + break; + } + } + if (root > max) { + root = max; + } + if (max === 0) { + table[table_index++] = 1 << 24 | 64 << 16 | 0; + table[table_index++] = 1 << 24 | 64 << 16 | 0; + opts.bits = 1; + return 0; + } + for (min = 1;min < max; min++) { + if (count[min] !== 0) { + break; + } + } + if (root < min) { + root = min; + } + left = 1; + for (len = 1;len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; + } + offs[1] = 0; + for (len = 1;len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + for (sym = 0;sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + if (type === CODES) { + base = extra = work; + end = 19; + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + } else { + base = dbase; + extra = dext; + end = -1; + } + huff = 0; + sym = 0; + len = min; + next = table_index; + curr = root; + drop2 = 0; + low = -1; + used = 1 << root; + mask2 = used - 1; + if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) { + return 1; + } + for (;; ) { + here_bits = len - drop2; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } else { + here_op = 32 + 64; + here_val = 0; + } + incr = 1 << len - drop2; + fill2 = 1 << curr; + min = fill2; + do { + fill2 -= incr; + table[next + (huff >> drop2) + fill2] = here_bits << 24 | here_op << 16 | here_val | 0; + } while (fill2 !== 0); + incr = 1 << len - 1; + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + sym++; + if (--count[len] === 0) { + if (len === max) { + break; + } + len = lens[lens_index + work[sym]]; + } + if (len > root && (huff & mask2) !== low) { + if (drop2 === 0) { + drop2 = root; + } + next += min; + curr = len - drop2; + left = 1 << curr; + while (curr + drop2 < max) { + left -= count[curr + drop2]; + if (left <= 0) { + break; + } + curr++; + left <<= 1; + } + used += 1 << curr; + if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) { + return 1; + } + low = huff & mask2; + table[low] = root << 24 | curr << 16 | next - table_index | 0; + } + } + if (huff !== 0) { + table[next + huff] = len - drop2 << 24 | 64 << 16 | 0; + } + opts.bits = root; + return 0; + }; +}); + +// node_modules/pako/lib/zlib/inflate.js +var require_inflate = __commonJS((exports2) => { + var utils = require_common(); + var adler32 = require_adler32(); + var crc32 = require_crc322(); + var inflate_fast = require_inffast(); + var inflate_table = require_inftrees(); + var CODES = 0; + var LENS = 1; + var DISTS = 2; + var Z_FINISH = 4; + var Z_BLOCK = 5; + var Z_TREES = 6; + var Z_OK = 0; + var Z_STREAM_END = 1; + var Z_NEED_DICT = 2; + var Z_STREAM_ERROR = -2; + var Z_DATA_ERROR = -3; + var Z_MEM_ERROR = -4; + var Z_BUF_ERROR = -5; + var Z_DEFLATED = 8; + var HEAD = 1; + var FLAGS = 2; + var TIME = 3; + var OS = 4; + var EXLEN = 5; + var EXTRA = 6; + var NAME = 7; + var COMMENT = 8; + var HCRC = 9; + var DICTID = 10; + var DICT = 11; + var TYPE = 12; + var TYPEDO = 13; + var STORED = 14; + var COPY_ = 15; + var COPY = 16; + var TABLE = 17; + var LENLENS = 18; + var CODELENS = 19; + var LEN_ = 20; + var LEN = 21; + var LENEXT = 22; + var DIST = 23; + var DISTEXT = 24; + var MATCH = 25; + var LIT = 26; + var CHECK = 27; + var LENGTH = 28; + var DONE = 29; + var BAD = 30; + var MEM = 31; + var SYNC = 32; + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + var MAX_WBITS = 15; + var DEF_WBITS = MAX_WBITS; + function zswap32(q) { + return (q >>> 24 & 255) + (q >>> 8 & 65280) + ((q & 65280) << 8) + ((q & 255) << 24); + } + function InflateState() { + this.mode = 0; + this.last = false; + this.wrap = 0; + this.havedict = false; + this.flags = 0; + this.dmax = 0; + this.check = 0; + this.total = 0; + this.head = null; + this.wbits = 0; + this.wsize = 0; + this.whave = 0; + this.wnext = 0; + this.window = null; + this.hold = 0; + this.bits = 0; + this.length = 0; + this.offset = 0; + this.extra = 0; + this.lencode = null; + this.distcode = null; + this.lenbits = 0; + this.distbits = 0; + this.ncode = 0; + this.nlen = 0; + this.ndist = 0; + this.have = 0; + this.next = null; + this.lens = new utils.Buf16(320); + this.work = new utils.Buf16(288); + this.lendyn = null; + this.distdyn = null; + this.sane = 0; + this.back = 0; + this.was = 0; + } + function inflateResetKeep(strm) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ""; + if (state.wrap) { + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null; + state.hold = 0; + state.bits = 0; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + state.sane = 1; + state.back = -1; + return Z_OK; + } + function inflateReset(strm) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + } + function inflateReset2(strm, windowBits) { + var wrap; + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); + } + function inflateInit2(strm, windowBits) { + var ret; + var state; + if (!strm) { + return Z_STREAM_ERROR; + } + state = new InflateState; + strm.state = state; + state.window = null; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null; + } + return ret; + } + function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); + } + var virgin = true; + var lenfix; + var distfix; + function fixedtables(state) { + if (virgin) { + var sym; + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + sym = 0; + while (sym < 144) { + state.lens[sym++] = 8; + } + while (sym < 256) { + state.lens[sym++] = 9; + } + while (sym < 280) { + state.lens[sym++] = 7; + } + while (sym < 288) { + state.lens[sym++] = 8; + } + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + sym = 0; + while (sym < 32) { + state.lens[sym++] = 5; + } + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + virgin = false; + } + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; + } + function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + state.window = new utils.Buf8(state.wsize); + } + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } else { + state.wnext += dist; + if (state.wnext === state.wsize) { + state.wnext = 0; + } + if (state.whave < state.wsize) { + state.whave += dist; + } + } + } + return 0; + } + function inflate(strm, flush) { + var state; + var input, output; + var next; + var put; + var have, left; + var hold; + var bits; + var _in, _out; + var copy; + var from; + var from_source; + var here = 0; + var here_bits, here_op, here_val; + var last_bits, last_op, last_val; + var len; + var ret; + var hbuf = new utils.Buf8(4); + var opts; + var n; + var order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (state.mode === TYPE) { + state.mode = TYPEDO; + } + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + _in = have; + _out = left; + ret = Z_OK; + inf_leave: + for (;; ) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.wrap & 2 && hold === 35615) { + state.check = 0; + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + hold = 0; + bits = 0; + state.mode = FLAGS; + break; + } + state.flags = 0; + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || (((hold & 255) << 8) + (hold >> 8)) % 31) { + strm.msg = "incorrect header check"; + state.mode = BAD; + break; + } + if ((hold & 15) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state.mode = BAD; + break; + } + hold >>>= 4; + bits -= 4; + len = (hold & 15) + 8; + if (state.wbits === 0) { + state.wbits = len; + } else if (len > state.wbits) { + strm.msg = "invalid window size"; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + strm.adler = state.check = 1; + state.mode = hold & 512 ? DICTID : TYPE; + hold = 0; + bits = 0; + break; + case FLAGS: + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.flags = hold; + if ((state.flags & 255) !== Z_DEFLATED) { + strm.msg = "unknown compression method"; + state.mode = BAD; + break; + } + if (state.flags & 57344) { + strm.msg = "unknown header flags set"; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = hold >> 8 & 1; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state.mode = TIME; + case TIME: + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.head) { + state.head.time = hold; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + hbuf[2] = hold >>> 16 & 255; + hbuf[3] = hold >>> 24 & 255; + state.check = crc32(state.check, hbuf, 4, 0); + } + hold = 0; + bits = 0; + state.mode = OS; + case OS: + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (state.head) { + state.head.xflags = hold & 255; + state.head.os = hold >> 8; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + state.mode = EXLEN; + case EXLEN: + if (state.flags & 1024) { + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 512) { + hbuf[0] = hold & 255; + hbuf[1] = hold >>> 8 & 255; + state.check = crc32(state.check, hbuf, 2, 0); + } + hold = 0; + bits = 0; + } else if (state.head) { + state.head.extra = null; + } + state.mode = EXTRA; + case EXTRA: + if (state.flags & 1024) { + copy = state.length; + if (copy > have) { + copy = have; + } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet(state.head.extra, input, next, copy, len); + } + if (state.flags & 512) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { + break inf_leave; + } + } + state.length = 0; + state.mode = NAME; + case NAME: + if (state.flags & 2048) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + len = input[next + copy++]; + if (state.head && len && state.length < 65536) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 512) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + case COMMENT: + if (state.flags & 4096) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + len = input[next + copy++]; + if (state.head && len && state.length < 65536) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 512) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + case HCRC: + if (state.flags & 512) { + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state.check & 65535)) { + strm.msg = "header crc mismatch"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + if (state.head) { + state.head.hcrc = state.flags >> 9 & 1; + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + strm.adler = state.check = zswap32(hold); + hold = 0; + bits = 0; + state.mode = DICT; + case DICT: + if (state.havedict === 0) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + return Z_NEED_DICT; + } + strm.adler = state.check = 1; + state.mode = TYPE; + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { + break inf_leave; + } + case TYPEDO: + if (state.last) { + hold >>>= bits & 7; + bits -= bits & 7; + state.mode = CHECK; + break; + } + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.last = hold & 1; + hold >>>= 1; + bits -= 1; + switch (hold & 3) { + case 0: + state.mode = STORED; + break; + case 1: + fixedtables(state); + state.mode = LEN_; + if (flush === Z_TREES) { + hold >>>= 2; + bits -= 2; + break inf_leave; + } + break; + case 2: + state.mode = TABLE; + break; + case 3: + strm.msg = "invalid block type"; + state.mode = BAD; + } + hold >>>= 2; + bits -= 2; + break; + case STORED: + hold >>>= bits & 7; + bits -= bits & 7; + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((hold & 65535) !== (hold >>> 16 ^ 65535)) { + strm.msg = "invalid stored block lengths"; + state.mode = BAD; + break; + } + state.length = hold & 65535; + hold = 0; + bits = 0; + state.mode = COPY_; + if (flush === Z_TREES) { + break inf_leave; + } + case COPY_: + state.mode = COPY; + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { + copy = have; + } + if (copy > left) { + copy = left; + } + if (copy === 0) { + break inf_leave; + } + utils.arraySet(output, input, next, copy, put); + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + state.mode = TYPE; + break; + case TABLE: + while (bits < 14) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.nlen = (hold & 31) + 257; + hold >>>= 5; + bits -= 5; + state.ndist = (hold & 31) + 1; + hold >>>= 5; + bits -= 5; + state.ncode = (hold & 15) + 4; + hold >>>= 4; + bits -= 4; + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = "too many length or distance symbols"; + state.mode = BAD; + break; + } + state.have = 0; + state.mode = LENLENS; + case LENLENS: + while (state.have < state.ncode) { + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.lens[order[state.have++]] = hold & 7; + hold >>>= 3; + bits -= 3; + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + state.lencode = state.lendyn; + state.lenbits = 7; + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid code lengths set"; + state.mode = BAD; + break; + } + state.have = 0; + state.mode = CODELENS; + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;; ) { + here = state.lencode[hold & (1 << state.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_val < 16) { + hold >>>= here_bits; + bits -= here_bits; + state.lens[state.have++] = here_val; + } else { + if (here_val === 16) { + n = here_bits + 2; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + if (state.have === 0) { + strm.msg = "invalid bit length repeat"; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 3); + hold >>>= 2; + bits -= 2; + } else if (here_val === 17) { + n = here_bits + 3; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy = 3 + (hold & 7); + hold >>>= 3; + bits -= 3; + } else { + n = here_bits + 7; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= here_bits; + bits -= here_bits; + len = 0; + copy = 11 + (hold & 127); + hold >>>= 7; + bits -= 7; + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = "invalid bit length repeat"; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + if (state.mode === BAD) { + break; + } + if (state.lens[256] === 0) { + strm.msg = "invalid code -- missing end-of-block"; + state.mode = BAD; + break; + } + state.lenbits = 9; + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + if (ret) { + strm.msg = "invalid literal/lengths set"; + state.mode = BAD; + break; + } + state.distbits = 6; + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + state.distbits = opts.bits; + if (ret) { + strm.msg = "invalid distances set"; + state.mode = BAD; + break; + } + state.mode = LEN_; + if (flush === Z_TREES) { + break inf_leave; + } + case LEN_: + state.mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + inflate_fast(strm, _out); + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;; ) { + here = state.lencode[hold & (1 << state.lenbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (here_op && (here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;; ) { + here = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + state.mode = LIT; + break; + } + if (here_op & 32) { + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = "invalid literal/length code"; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + case LENEXT: + if (state.extra) { + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.length += hold & (1 << state.extra) - 1; + hold >>>= state.extra; + bits -= state.extra; + state.back += state.extra; + } + state.was = state.length; + state.mode = DIST; + case DIST: + for (;; ) { + here = state.distcode[hold & (1 << state.distbits) - 1]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if ((here_op & 240) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;; ) { + here = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> last_bits)]; + here_bits = here >>> 24; + here_op = here >>> 16 & 255; + here_val = here & 65535; + if (last_bits + here_bits <= bits) { + break; + } + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + hold >>>= last_bits; + bits -= last_bits; + state.back += last_bits; + } + hold >>>= here_bits; + bits -= here_bits; + state.back += here_bits; + if (here_op & 64) { + strm.msg = "invalid distance code"; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = here_op & 15; + state.mode = DISTEXT; + case DISTEXT: + if (state.extra) { + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + state.offset += hold & (1 << state.extra) - 1; + hold >>>= state.extra; + bits -= state.extra; + state.back += state.extra; + } + if (state.offset > state.dmax) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break; + } + state.mode = MATCH; + case MATCH: + if (left === 0) { + break inf_leave; + } + copy = _out - left; + if (state.offset > copy) { + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = "invalid distance too far back"; + state.mode = BAD; + break; + } + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } else { + from = state.wnext - copy; + } + if (copy > state.length) { + copy = state.length; + } + from_source = state.window; + } else { + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { + copy = left; + } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { + state.mode = LEN; + } + break; + case LIT: + if (left === 0) { + break inf_leave; + } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold |= input[next++] << bits; + bits += 8; + } + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out); + } + _out = left; + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = "incorrect data check"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state.mode = LENGTH; + case LENGTH: + if (state.wrap && state.flags) { + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + if (hold !== (state.total & 4294967295)) { + strm.msg = "incorrect length check"; + state.mode = BAD; + break; + } + hold = 0; + bits = 0; + } + state.mode = DONE; + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + } + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + if (state.wsize || _out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH)) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if ((_in === 0 && _out === 0 || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; + } + function inflateEnd(strm) { + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; + } + function inflateGetHeader(strm, head) { + var state; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if ((state.wrap & 2) === 0) { + return Z_STREAM_ERROR; + } + state.head = head; + head.done = false; + return Z_OK; + } + function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + var state; + var dictid; + var ret; + if (!strm || !strm.state) { + return Z_STREAM_ERROR; + } + state = strm.state; + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + if (state.mode === DICT) { + dictid = 1; + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + return Z_OK; + } + exports2.inflateReset = inflateReset; + exports2.inflateReset2 = inflateReset2; + exports2.inflateResetKeep = inflateResetKeep; + exports2.inflateInit = inflateInit; + exports2.inflateInit2 = inflateInit2; + exports2.inflate = inflate; + exports2.inflateEnd = inflateEnd; + exports2.inflateGetHeader = inflateGetHeader; + exports2.inflateSetDictionary = inflateSetDictionary; + exports2.inflateInfo = "pako inflate (from Nodeca project)"; +}); + +// node_modules/pako/lib/zlib/constants.js +var require_constants = __commonJS((exports2, module2) => { + module2.exports = { + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + Z_BUF_ERROR: -5, + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + Z_BINARY: 0, + Z_TEXT: 1, + Z_UNKNOWN: 2, + Z_DEFLATED: 8 + }; +}); + +// node_modules/pako/lib/zlib/gzheader.js +var require_gzheader = __commonJS((exports2, module2) => { + function GZheader() { + this.text = 0; + this.time = 0; + this.xflags = 0; + this.os = 0; + this.extra = null; + this.extra_len = 0; + this.name = ""; + this.comment = ""; + this.hcrc = 0; + this.done = false; + } + module2.exports = GZheader; +}); + +// node_modules/pako/lib/inflate.js +var require_inflate2 = __commonJS((exports2) => { + var zlib_inflate = require_inflate(); + var utils = require_common(); + var strings = require_strings(); + var c = require_constants(); + var msg = require_messages(); + var ZStream = require_zstream(); + var GZheader = require_gzheader(); + var toString2 = Object.prototype.toString; + function Inflate(options) { + if (!(this instanceof Inflate)) + return new Inflate(options); + this.options = utils.assign({ + chunkSize: 16384, + windowBits: 0, + to: "" + }, options || {}); + var opt = this.options; + if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) { + opt.windowBits = -opt.windowBits; + if (opt.windowBits === 0) { + opt.windowBits = -15; + } + } + if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) { + opt.windowBits += 32; + } + if (opt.windowBits > 15 && opt.windowBits < 48) { + if ((opt.windowBits & 15) === 0) { + opt.windowBits |= 15; + } + } + this.err = 0; + this.msg = ""; + this.ended = false; + this.chunks = []; + this.strm = new ZStream; + this.strm.avail_out = 0; + var status = zlib_inflate.inflateInit2(this.strm, opt.windowBits); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + this.header = new GZheader; + zlib_inflate.inflateGetHeader(this.strm, this.header); + if (opt.dictionary) { + if (typeof opt.dictionary === "string") { + opt.dictionary = strings.string2buf(opt.dictionary); + } else if (toString2.call(opt.dictionary) === "[object ArrayBuffer]") { + opt.dictionary = new Uint8Array(opt.dictionary); + } + if (opt.raw) { + status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); + if (status !== c.Z_OK) { + throw new Error(msg[status]); + } + } + } + } + Inflate.prototype.push = function(data2, mode) { + var strm = this.strm; + var chunkSize = this.options.chunkSize; + var dictionary = this.options.dictionary; + var status, _mode; + var next_out_utf8, tail, utf8str; + var allowBufError = false; + if (this.ended) { + return false; + } + _mode = mode === ~~mode ? mode : mode === true ? c.Z_FINISH : c.Z_NO_FLUSH; + if (typeof data2 === "string") { + strm.input = strings.binstring2buf(data2); + } else if (toString2.call(data2) === "[object ArrayBuffer]") { + strm.input = new Uint8Array(data2); + } else { + strm.input = data2; + } + strm.next_in = 0; + strm.avail_in = strm.input.length; + do { + if (strm.avail_out === 0) { + strm.output = new utils.Buf8(chunkSize); + strm.next_out = 0; + strm.avail_out = chunkSize; + } + status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); + if (status === c.Z_NEED_DICT && dictionary) { + status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); + } + if (status === c.Z_BUF_ERROR && allowBufError === true) { + status = c.Z_OK; + allowBufError = false; + } + if (status !== c.Z_STREAM_END && status !== c.Z_OK) { + this.onEnd(status); + this.ended = true; + return false; + } + if (strm.next_out) { + if (strm.avail_out === 0 || status === c.Z_STREAM_END || strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH)) { + if (this.options.to === "string") { + next_out_utf8 = strings.utf8border(strm.output, strm.next_out); + tail = strm.next_out - next_out_utf8; + utf8str = strings.buf2string(strm.output, next_out_utf8); + strm.next_out = tail; + strm.avail_out = chunkSize - tail; + if (tail) { + utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); + } + this.onData(utf8str); + } else { + this.onData(utils.shrinkBuf(strm.output, strm.next_out)); + } + } + } + if (strm.avail_in === 0 && strm.avail_out === 0) { + allowBufError = true; + } + } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); + if (status === c.Z_STREAM_END) { + _mode = c.Z_FINISH; + } + if (_mode === c.Z_FINISH) { + status = zlib_inflate.inflateEnd(this.strm); + this.onEnd(status); + this.ended = true; + return status === c.Z_OK; + } + if (_mode === c.Z_SYNC_FLUSH) { + this.onEnd(c.Z_OK); + strm.avail_out = 0; + return true; + } + return true; + }; + Inflate.prototype.onData = function(chunk) { + this.chunks.push(chunk); + }; + Inflate.prototype.onEnd = function(status) { + if (status === c.Z_OK) { + if (this.options.to === "string") { + this.result = this.chunks.join(""); + } else { + this.result = utils.flattenChunks(this.chunks); + } + } + this.chunks = []; + this.err = status; + this.msg = this.strm.msg; + }; + function inflate(input, options) { + var inflator = new Inflate(options); + inflator.push(input, true); + if (inflator.err) { + throw inflator.msg || msg[inflator.err]; + } + return inflator.result; + } + function inflateRaw(input, options) { + options = options || {}; + options.raw = true; + return inflate(input, options); + } + exports2.Inflate = Inflate; + exports2.inflate = inflate; + exports2.inflateRaw = inflateRaw; + exports2.ungzip = inflate; +}); + +// node_modules/pako/index.js +var require_pako = __commonJS((exports2, module2) => { + var assign2 = require_common().assign; + var deflate = require_deflate2(); + var inflate = require_inflate2(); + var constants = require_constants(); + var pako = {}; + assign2(pako, deflate, inflate, constants); + module2.exports = pako; +}); + +// node_modules/jszip/lib/flate.js +var require_flate = __commonJS((exports2) => { + var USE_TYPEDARRAY = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Uint32Array !== "undefined"; + var pako = require_pako(); + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array"; + exports2.magic = "\b\x00"; + function FlateWorker(action, options) { + GenericWorker.call(this, "FlateWorker/" + action); + this._pako = null; + this._pakoAction = action; + this._pakoOptions = options; + this.meta = {}; + } + utils.inherits(FlateWorker, GenericWorker); + FlateWorker.prototype.processChunk = function(chunk) { + this.meta = chunk.meta; + if (this._pako === null) { + this._createPako(); + } + this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false); + }; + FlateWorker.prototype.flush = function() { + GenericWorker.prototype.flush.call(this); + if (this._pako === null) { + this._createPako(); + } + this._pako.push([], true); + }; + FlateWorker.prototype.cleanUp = function() { + GenericWorker.prototype.cleanUp.call(this); + this._pako = null; + }; + FlateWorker.prototype._createPako = function() { + this._pako = new pako[this._pakoAction]({ + raw: true, + level: this._pakoOptions.level || -1 + }); + var self2 = this; + this._pako.onData = function(data2) { + self2.push({ + data: data2, + meta: self2.meta + }); + }; + }; + exports2.compressWorker = function(compressionOptions) { + return new FlateWorker("Deflate", compressionOptions); + }; + exports2.uncompressWorker = function() { + return new FlateWorker("Inflate", {}); + }; +}); + +// node_modules/jszip/lib/compressions.js +var require_compressions = __commonJS((exports2) => { + var GenericWorker = require_GenericWorker(); + exports2.STORE = { + magic: "\x00\x00", + compressWorker: function() { + return new GenericWorker("STORE compression"); + }, + uncompressWorker: function() { + return new GenericWorker("STORE decompression"); + } + }; + exports2.DEFLATE = require_flate(); +}); + +// node_modules/jszip/lib/signature.js +var require_signature = __commonJS((exports2) => { + exports2.LOCAL_FILE_HEADER = "PK\x03\x04"; + exports2.CENTRAL_FILE_HEADER = "PK\x01\x02"; + exports2.CENTRAL_DIRECTORY_END = "PK\x05\x06"; + exports2.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07"; + exports2.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06"; + exports2.DATA_DESCRIPTOR = "PK\x07\b"; +}); + +// node_modules/jszip/lib/generate/ZipFileWorker.js +var require_ZipFileWorker = __commonJS((exports2, module2) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var utf8 = require_utf8(); + var crc32 = require_crc32(); + var signature = require_signature(); + var decToHex = function(dec, bytes) { + var hex = "", i; + for (i = 0;i < bytes; i++) { + hex += String.fromCharCode(dec & 255); + dec = dec >>> 8; + } + return hex; + }; + var generateUnixExternalFileAttr = function(unixPermissions, isDir) { + var result = unixPermissions; + if (!unixPermissions) { + result = isDir ? 16893 : 33204; + } + return (result & 65535) << 16; + }; + var generateDosExternalFileAttr = function(dosPermissions) { + return (dosPermissions || 0) & 63; + }; + var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) { + var file = streamInfo["file"], compression = streamInfo["compression"], useCustomEncoding = encodeFileName !== utf8.utf8encode, encodedFileName = utils.transformTo("string", encodeFileName(file.name)), utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), comment = file.comment, encodedComment = utils.transformTo("string", encodeFileName(comment)), utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, useUTF8ForComment = utfEncodedComment.length !== comment.length, dosTime, dosDate, extraFields = "", unicodePathExtraField = "", unicodeCommentExtraField = "", dir = file.dir, date = file.date; + var dataInfo = { + crc32: 0, + compressedSize: 0, + uncompressedSize: 0 + }; + if (!streamedContent || streamingEnded) { + dataInfo.crc32 = streamInfo["crc32"]; + dataInfo.compressedSize = streamInfo["compressedSize"]; + dataInfo.uncompressedSize = streamInfo["uncompressedSize"]; + } + var bitflag = 0; + if (streamedContent) { + bitflag |= 8; + } + if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) { + bitflag |= 2048; + } + var extFileAttr = 0; + var versionMadeBy = 0; + if (dir) { + extFileAttr |= 16; + } + if (platform === "UNIX") { + versionMadeBy = 798; + extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir); + } else { + versionMadeBy = 20; + extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir); + } + dosTime = date.getUTCHours(); + dosTime = dosTime << 6; + dosTime = dosTime | date.getUTCMinutes(); + dosTime = dosTime << 5; + dosTime = dosTime | date.getUTCSeconds() / 2; + dosDate = date.getUTCFullYear() - 1980; + dosDate = dosDate << 4; + dosDate = dosDate | date.getUTCMonth() + 1; + dosDate = dosDate << 5; + dosDate = dosDate | date.getUTCDate(); + if (useUTF8ForFileName) { + unicodePathExtraField = decToHex(1, 1) + decToHex(crc32(encodedFileName), 4) + utfEncodedFileName; + extraFields += "up" + decToHex(unicodePathExtraField.length, 2) + unicodePathExtraField; + } + if (useUTF8ForComment) { + unicodeCommentExtraField = decToHex(1, 1) + decToHex(crc32(encodedComment), 4) + utfEncodedComment; + extraFields += "uc" + decToHex(unicodeCommentExtraField.length, 2) + unicodeCommentExtraField; + } + var header = ""; + header += ` +\x00`; + header += decToHex(bitflag, 2); + header += compression.magic; + header += decToHex(dosTime, 2); + header += decToHex(dosDate, 2); + header += decToHex(dataInfo.crc32, 4); + header += decToHex(dataInfo.compressedSize, 4); + header += decToHex(dataInfo.uncompressedSize, 4); + header += decToHex(encodedFileName.length, 2); + header += decToHex(extraFields.length, 2); + var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields; + var dirRecord = signature.CENTRAL_FILE_HEADER + decToHex(versionMadeBy, 2) + header + decToHex(encodedComment.length, 2) + "\x00\x00" + "\x00\x00" + decToHex(extFileAttr, 4) + decToHex(offset, 4) + encodedFileName + extraFields + encodedComment; + return { + fileRecord, + dirRecord + }; + }; + var generateCentralDirectoryEnd = function(entriesCount, centralDirLength, localDirLength, comment, encodeFileName) { + var dirEnd = ""; + var encodedComment = utils.transformTo("string", encodeFileName(comment)); + dirEnd = signature.CENTRAL_DIRECTORY_END + "\x00\x00" + "\x00\x00" + decToHex(entriesCount, 2) + decToHex(entriesCount, 2) + decToHex(centralDirLength, 4) + decToHex(localDirLength, 4) + decToHex(encodedComment.length, 2) + encodedComment; + return dirEnd; + }; + var generateDataDescriptors = function(streamInfo) { + var descriptor = ""; + descriptor = signature.DATA_DESCRIPTOR + decToHex(streamInfo["crc32"], 4) + decToHex(streamInfo["compressedSize"], 4) + decToHex(streamInfo["uncompressedSize"], 4); + return descriptor; + }; + function ZipFileWorker(streamFiles, comment, platform, encodeFileName) { + GenericWorker.call(this, "ZipFileWorker"); + this.bytesWritten = 0; + this.zipComment = comment; + this.zipPlatform = platform; + this.encodeFileName = encodeFileName; + this.streamFiles = streamFiles; + this.accumulate = false; + this.contentBuffer = []; + this.dirRecords = []; + this.currentSourceOffset = 0; + this.entriesCount = 0; + this.currentFile = null; + this._sources = []; + } + utils.inherits(ZipFileWorker, GenericWorker); + ZipFileWorker.prototype.push = function(chunk) { + var currentFilePercent = chunk.meta.percent || 0; + var entriesCount = this.entriesCount; + var remainingFiles = this._sources.length; + if (this.accumulate) { + this.contentBuffer.push(chunk); + } else { + this.bytesWritten += chunk.data.length; + GenericWorker.prototype.push.call(this, { + data: chunk.data, + meta: { + currentFile: this.currentFile, + percent: entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100 + } + }); + } + }; + ZipFileWorker.prototype.openedSource = function(streamInfo) { + this.currentSourceOffset = this.bytesWritten; + this.currentFile = streamInfo["file"].name; + var streamedContent = this.streamFiles && !streamInfo["file"].dir; + if (streamedContent) { + var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.push({ + data: record.fileRecord, + meta: { percent: 0 } + }); + } else { + this.accumulate = true; + } + }; + ZipFileWorker.prototype.closedSource = function(streamInfo) { + this.accumulate = false; + var streamedContent = this.streamFiles && !streamInfo["file"].dir; + var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); + this.dirRecords.push(record.dirRecord); + if (streamedContent) { + this.push({ + data: generateDataDescriptors(streamInfo), + meta: { percent: 100 } + }); + } else { + this.push({ + data: record.fileRecord, + meta: { percent: 0 } + }); + while (this.contentBuffer.length) { + this.push(this.contentBuffer.shift()); + } + } + this.currentFile = null; + }; + ZipFileWorker.prototype.flush = function() { + var localDirLength = this.bytesWritten; + for (var i = 0;i < this.dirRecords.length; i++) { + this.push({ + data: this.dirRecords[i], + meta: { percent: 100 } + }); + } + var centralDirLength = this.bytesWritten - localDirLength; + var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName); + this.push({ + data: dirEnd, + meta: { percent: 100 } + }); + }; + ZipFileWorker.prototype.prepareNextSource = function() { + this.previous = this._sources.shift(); + this.openedSource(this.previous.streamInfo); + if (this.isPaused) { + this.previous.pause(); + } else { + this.previous.resume(); + } + }; + ZipFileWorker.prototype.registerPrevious = function(previous) { + this._sources.push(previous); + var self2 = this; + previous.on("data", function(chunk) { + self2.processChunk(chunk); + }); + previous.on("end", function() { + self2.closedSource(self2.previous.streamInfo); + if (self2._sources.length) { + self2.prepareNextSource(); + } else { + self2.end(); + } + }); + previous.on("error", function(e) { + self2.error(e); + }); + return this; + }; + ZipFileWorker.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) { + return false; + } + if (!this.previous && this._sources.length) { + this.prepareNextSource(); + return true; + } + if (!this.previous && !this._sources.length && !this.generatedError) { + this.end(); + return true; + } + }; + ZipFileWorker.prototype.error = function(e) { + var sources = this._sources; + if (!GenericWorker.prototype.error.call(this, e)) { + return false; + } + for (var i = 0;i < sources.length; i++) { + try { + sources[i].error(e); + } catch (e2) { + } + } + return true; + }; + ZipFileWorker.prototype.lock = function() { + GenericWorker.prototype.lock.call(this); + var sources = this._sources; + for (var i = 0;i < sources.length; i++) { + sources[i].lock(); + } + }; + module2.exports = ZipFileWorker; +}); + +// node_modules/jszip/lib/generate/index.js +var require_generate = __commonJS((exports2) => { + var compressions = require_compressions(); + var ZipFileWorker = require_ZipFileWorker(); + var getCompression = function(fileCompression, zipCompression) { + var compressionName = fileCompression || zipCompression; + var compression = compressions[compressionName]; + if (!compression) { + throw new Error(compressionName + " is not a valid compression method !"); + } + return compression; + }; + exports2.generateWorker = function(zip, options, comment) { + var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName); + var entriesCount = 0; + try { + zip.forEach(function(relativePath, file) { + entriesCount++; + var compression = getCompression(file.options.compression, options.compression); + var compressionOptions = file.options.compressionOptions || options.compressionOptions || {}; + var { dir, date } = file; + file._compressWorker(compression, compressionOptions).withStreamInfo("file", { + name: relativePath, + dir, + date, + comment: file.comment || "", + unixPermissions: file.unixPermissions, + dosPermissions: file.dosPermissions + }).pipe(zipFileWorker); + }); + zipFileWorker.entriesCount = entriesCount; + } catch (e) { + zipFileWorker.error(e); + } + return zipFileWorker; + }; +}); + +// node_modules/jszip/lib/nodejs/NodejsStreamInputAdapter.js +var require_NodejsStreamInputAdapter = __commonJS((exports2, module2) => { + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + function NodejsStreamInputAdapter(filename, stream) { + GenericWorker.call(this, "Nodejs stream input adapter for " + filename); + this._upstreamEnded = false; + this._bindStream(stream); + } + utils.inherits(NodejsStreamInputAdapter, GenericWorker); + NodejsStreamInputAdapter.prototype._bindStream = function(stream) { + var self2 = this; + this._stream = stream; + stream.pause(); + stream.on("data", function(chunk) { + self2.push({ + data: chunk, + meta: { + percent: 0 + } + }); + }).on("error", function(e) { + if (self2.isPaused) { + this.generatedError = e; + } else { + self2.error(e); + } + }).on("end", function() { + if (self2.isPaused) { + self2._upstreamEnded = true; + } else { + self2.end(); + } + }); + }; + NodejsStreamInputAdapter.prototype.pause = function() { + if (!GenericWorker.prototype.pause.call(this)) { + return false; + } + this._stream.pause(); + return true; + }; + NodejsStreamInputAdapter.prototype.resume = function() { + if (!GenericWorker.prototype.resume.call(this)) { + return false; + } + if (this._upstreamEnded) { + this.end(); + } else { + this._stream.resume(); + } + return true; + }; + module2.exports = NodejsStreamInputAdapter; +}); + +// node_modules/jszip/lib/object.js +var require_object = __commonJS((exports2, module2) => { + var utf8 = require_utf8(); + var utils = require_utils(); + var GenericWorker = require_GenericWorker(); + var StreamHelper = require_StreamHelper(); + var defaults2 = require_defaults(); + var CompressedObject = require_compressedObject(); + var ZipObject = require_zipObject(); + var generate = require_generate(); + var nodejsUtils = require_nodejsUtils(); + var NodejsStreamInputAdapter = require_NodejsStreamInputAdapter(); + var fileAdd = function(name2, data2, originalOptions) { + var dataType = utils.getTypeOf(data2), parent2; + var o = utils.extend(originalOptions || {}, defaults2); + o.date = o.date || new Date; + if (o.compression !== null) { + o.compression = o.compression.toUpperCase(); + } + if (typeof o.unixPermissions === "string") { + o.unixPermissions = parseInt(o.unixPermissions, 8); + } + if (o.unixPermissions && o.unixPermissions & 16384) { + o.dir = true; + } + if (o.dosPermissions && o.dosPermissions & 16) { + o.dir = true; + } + if (o.dir) { + name2 = forceTrailingSlash(name2); + } + if (o.createFolders && (parent2 = parentFolder(name2))) { + folderAdd.call(this, parent2, true); + } + var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false; + if (!originalOptions || typeof originalOptions.binary === "undefined") { + o.binary = !isUnicodeString; + } + var isCompressedEmpty = data2 instanceof CompressedObject && data2.uncompressedSize === 0; + if (isCompressedEmpty || o.dir || !data2 || data2.length === 0) { + o.base64 = false; + o.binary = true; + data2 = ""; + o.compression = "STORE"; + dataType = "string"; + } + var zipObjectContent = null; + if (data2 instanceof CompressedObject || data2 instanceof GenericWorker) { + zipObjectContent = data2; + } else if (nodejsUtils.isNode && nodejsUtils.isStream(data2)) { + zipObjectContent = new NodejsStreamInputAdapter(name2, data2); + } else { + zipObjectContent = utils.prepareContent(name2, data2, o.binary, o.optimizedBinaryString, o.base64); + } + var object = new ZipObject(name2, zipObjectContent, o); + this.files[name2] = object; + }; + var parentFolder = function(path) { + if (path.slice(-1) === "/") { + path = path.substring(0, path.length - 1); + } + var lastSlash = path.lastIndexOf("/"); + return lastSlash > 0 ? path.substring(0, lastSlash) : ""; + }; + var forceTrailingSlash = function(path) { + if (path.slice(-1) !== "/") { + path += "/"; + } + return path; + }; + var folderAdd = function(name2, createFolders) { + createFolders = typeof createFolders !== "undefined" ? createFolders : defaults2.createFolders; + name2 = forceTrailingSlash(name2); + if (!this.files[name2]) { + fileAdd.call(this, name2, null, { + dir: true, + createFolders + }); + } + return this.files[name2]; + }; + function isRegExp2(object) { + return Object.prototype.toString.call(object) === "[object RegExp]"; + } + var out = { + load: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, + forEach: function(cb) { + var filename, relativePath, file; + for (filename in this.files) { + file = this.files[filename]; + relativePath = filename.slice(this.root.length, filename.length); + if (relativePath && filename.slice(0, this.root.length) === this.root) { + cb(relativePath, file); + } + } + }, + filter: function(search) { + var result = []; + this.forEach(function(relativePath, entry) { + if (search(relativePath, entry)) { + result.push(entry); + } + }); + return result; + }, + file: function(name2, data2, o) { + if (arguments.length === 1) { + if (isRegExp2(name2)) { + var regexp = name2; + return this.filter(function(relativePath, file) { + return !file.dir && regexp.test(relativePath); + }); + } else { + var obj = this.files[this.root + name2]; + if (obj && !obj.dir) { + return obj; + } else { + return null; + } + } + } else { + name2 = this.root + name2; + fileAdd.call(this, name2, data2, o); + } + return this; + }, + folder: function(arg) { + if (!arg) { + return this; + } + if (isRegExp2(arg)) { + return this.filter(function(relativePath, file) { + return file.dir && arg.test(relativePath); + }); + } + var name2 = this.root + arg; + var newFolder = folderAdd.call(this, name2); + var ret = this.clone(); + ret.root = newFolder.name; + return ret; + }, + remove: function(name2) { + name2 = this.root + name2; + var file = this.files[name2]; + if (!file) { + if (name2.slice(-1) !== "/") { + name2 += "/"; + } + file = this.files[name2]; + } + if (file && !file.dir) { + delete this.files[name2]; + } else { + var kids = this.filter(function(relativePath, file2) { + return file2.name.slice(0, name2.length) === name2; + }); + for (var i = 0;i < kids.length; i++) { + delete this.files[kids[i].name]; + } + } + return this; + }, + generate: function() { + throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); + }, + generateInternalStream: function(options) { + var worker, opts = {}; + try { + opts = utils.extend(options || {}, { + streamFiles: false, + compression: "STORE", + compressionOptions: null, + type: "", + platform: "DOS", + comment: null, + mimeType: "application/zip", + encodeFileName: utf8.utf8encode + }); + opts.type = opts.type.toLowerCase(); + opts.compression = opts.compression.toUpperCase(); + if (opts.type === "binarystring") { + opts.type = "string"; + } + if (!opts.type) { + throw new Error("No output type specified."); + } + utils.checkSupport(opts.type); + if (opts.platform === "darwin" || opts.platform === "freebsd" || opts.platform === "linux" || opts.platform === "sunos") { + opts.platform = "UNIX"; + } + if (opts.platform === "win32") { + opts.platform = "DOS"; + } + var comment = opts.comment || this.comment || ""; + worker = generate.generateWorker(this, opts, comment); + } catch (e) { + worker = new GenericWorker("error"); + worker.error(e); + } + return new StreamHelper(worker, opts.type || "string", opts.mimeType); + }, + generateAsync: function(options, onUpdate) { + return this.generateInternalStream(options).accumulate(onUpdate); + }, + generateNodeStream: function(options, onUpdate) { + options = options || {}; + if (!options.type) { + options.type = "nodebuffer"; + } + return this.generateInternalStream(options).toNodejsStream(onUpdate); + } + }; + module2.exports = out; +}); + +// node_modules/jszip/lib/reader/DataReader.js +var require_DataReader = __commonJS((exports2, module2) => { + var utils = require_utils(); + function DataReader(data2) { + this.data = data2; + this.length = data2.length; + this.index = 0; + this.zero = 0; + } + DataReader.prototype = { + checkOffset: function(offset) { + this.checkIndex(this.index + offset); + }, + checkIndex: function(newIndex) { + if (this.length < this.zero + newIndex || newIndex < 0) { + throw new Error("End of data reached (data length = " + this.length + ", asked index = " + newIndex + "). Corrupted zip ?"); + } + }, + setIndex: function(newIndex) { + this.checkIndex(newIndex); + this.index = newIndex; + }, + skip: function(n) { + this.setIndex(this.index + n); + }, + byteAt: function() { + }, + readInt: function(size) { + var result = 0, i; + this.checkOffset(size); + for (i = this.index + size - 1;i >= this.index; i--) { + result = (result << 8) + this.byteAt(i); + } + this.index += size; + return result; + }, + readString: function(size) { + return utils.transformTo("string", this.readData(size)); + }, + readData: function() { + }, + lastIndexOfSignature: function() { + }, + readAndCheckSignature: function() { + }, + readDate: function() { + var dostime = this.readInt(4); + return new Date(Date.UTC((dostime >> 25 & 127) + 1980, (dostime >> 21 & 15) - 1, dostime >> 16 & 31, dostime >> 11 & 31, dostime >> 5 & 63, (dostime & 31) << 1)); + } + }; + module2.exports = DataReader; +}); + +// node_modules/jszip/lib/reader/ArrayReader.js +var require_ArrayReader = __commonJS((exports2, module2) => { + var DataReader = require_DataReader(); + var utils = require_utils(); + function ArrayReader(data2) { + DataReader.call(this, data2); + for (var i = 0;i < this.data.length; i++) { + data2[i] = data2[i] & 255; + } + } + utils.inherits(ArrayReader, DataReader); + ArrayReader.prototype.byteAt = function(i) { + return this.data[this.zero + i]; + }; + ArrayReader.prototype.lastIndexOfSignature = function(sig) { + var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3); + for (var i = this.length - 4;i >= 0; --i) { + if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) { + return i - this.zero; + } + } + return -1; + }; + ArrayReader.prototype.readAndCheckSignature = function(sig) { + var sig0 = sig.charCodeAt(0), sig1 = sig.charCodeAt(1), sig2 = sig.charCodeAt(2), sig3 = sig.charCodeAt(3), data2 = this.readData(4); + return sig0 === data2[0] && sig1 === data2[1] && sig2 === data2[2] && sig3 === data2[3]; + }; + ArrayReader.prototype.readData = function(size) { + this.checkOffset(size); + if (size === 0) { + return []; + } + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module2.exports = ArrayReader; +}); + +// node_modules/jszip/lib/reader/StringReader.js +var require_StringReader = __commonJS((exports2, module2) => { + var DataReader = require_DataReader(); + var utils = require_utils(); + function StringReader(data2) { + DataReader.call(this, data2); + } + utils.inherits(StringReader, DataReader); + StringReader.prototype.byteAt = function(i) { + return this.data.charCodeAt(this.zero + i); + }; + StringReader.prototype.lastIndexOfSignature = function(sig) { + return this.data.lastIndexOf(sig) - this.zero; + }; + StringReader.prototype.readAndCheckSignature = function(sig) { + var data2 = this.readData(4); + return sig === data2; + }; + StringReader.prototype.readData = function(size) { + this.checkOffset(size); + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module2.exports = StringReader; +}); + +// node_modules/jszip/lib/reader/Uint8ArrayReader.js +var require_Uint8ArrayReader = __commonJS((exports2, module2) => { + var ArrayReader = require_ArrayReader(); + var utils = require_utils(); + function Uint8ArrayReader(data2) { + ArrayReader.call(this, data2); + } + utils.inherits(Uint8ArrayReader, ArrayReader); + Uint8ArrayReader.prototype.readData = function(size) { + this.checkOffset(size); + if (size === 0) { + return new Uint8Array(0); + } + var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module2.exports = Uint8ArrayReader; +}); + +// node_modules/jszip/lib/reader/NodeBufferReader.js +var require_NodeBufferReader = __commonJS((exports2, module2) => { + var Uint8ArrayReader = require_Uint8ArrayReader(); + var utils = require_utils(); + function NodeBufferReader(data2) { + Uint8ArrayReader.call(this, data2); + } + utils.inherits(NodeBufferReader, Uint8ArrayReader); + NodeBufferReader.prototype.readData = function(size) { + this.checkOffset(size); + var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); + this.index += size; + return result; + }; + module2.exports = NodeBufferReader; +}); + +// node_modules/jszip/lib/reader/readerFor.js +var require_readerFor = __commonJS((exports2, module2) => { + var utils = require_utils(); + var support = require_support(); + var ArrayReader = require_ArrayReader(); + var StringReader = require_StringReader(); + var NodeBufferReader = require_NodeBufferReader(); + var Uint8ArrayReader = require_Uint8ArrayReader(); + module2.exports = function(data2) { + var type = utils.getTypeOf(data2); + utils.checkSupport(type); + if (type === "string" && !support.uint8array) { + return new StringReader(data2); + } + if (type === "nodebuffer") { + return new NodeBufferReader(data2); + } + if (support.uint8array) { + return new Uint8ArrayReader(utils.transformTo("uint8array", data2)); + } + return new ArrayReader(utils.transformTo("array", data2)); + }; +}); + +// node_modules/jszip/lib/zipEntry.js +var require_zipEntry = __commonJS((exports2, module2) => { + var readerFor = require_readerFor(); + var utils = require_utils(); + var CompressedObject = require_compressedObject(); + var crc32fn = require_crc32(); + var utf8 = require_utf8(); + var compressions = require_compressions(); + var support = require_support(); + var MADE_BY_DOS = 0; + var MADE_BY_UNIX = 3; + var findCompression = function(compressionMethod) { + for (var method in compressions) { + if (!Object.prototype.hasOwnProperty.call(compressions, method)) { + continue; + } + if (compressions[method].magic === compressionMethod) { + return compressions[method]; + } + } + return null; + }; + function ZipEntry(options, loadOptions) { + this.options = options; + this.loadOptions = loadOptions; + } + ZipEntry.prototype = { + isEncrypted: function() { + return (this.bitFlag & 1) === 1; + }, + useUTF8: function() { + return (this.bitFlag & 2048) === 2048; + }, + readLocalPart: function(reader) { + var compression, localExtraFieldsLength; + reader.skip(22); + this.fileNameLength = reader.readInt(2); + localExtraFieldsLength = reader.readInt(2); + this.fileName = reader.readData(this.fileNameLength); + reader.skip(localExtraFieldsLength); + if (this.compressedSize === -1 || this.uncompressedSize === -1) { + throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)"); + } + compression = findCompression(this.compressionMethod); + if (compression === null) { + throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")"); + } + this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize)); + }, + readCentralPart: function(reader) { + this.versionMadeBy = reader.readInt(2); + reader.skip(2); + this.bitFlag = reader.readInt(2); + this.compressionMethod = reader.readString(2); + this.date = reader.readDate(); + this.crc32 = reader.readInt(4); + this.compressedSize = reader.readInt(4); + this.uncompressedSize = reader.readInt(4); + var fileNameLength = reader.readInt(2); + this.extraFieldsLength = reader.readInt(2); + this.fileCommentLength = reader.readInt(2); + this.diskNumberStart = reader.readInt(2); + this.internalFileAttributes = reader.readInt(2); + this.externalFileAttributes = reader.readInt(4); + this.localHeaderOffset = reader.readInt(4); + if (this.isEncrypted()) { + throw new Error("Encrypted zip are not supported"); + } + reader.skip(fileNameLength); + this.readExtraFields(reader); + this.parseZIP64ExtraField(reader); + this.fileComment = reader.readData(this.fileCommentLength); + }, + processAttributes: function() { + this.unixPermissions = null; + this.dosPermissions = null; + var madeBy = this.versionMadeBy >> 8; + this.dir = this.externalFileAttributes & 16 ? true : false; + if (madeBy === MADE_BY_DOS) { + this.dosPermissions = this.externalFileAttributes & 63; + } + if (madeBy === MADE_BY_UNIX) { + this.unixPermissions = this.externalFileAttributes >> 16 & 65535; + } + if (!this.dir && this.fileNameStr.slice(-1) === "/") { + this.dir = true; + } + }, + parseZIP64ExtraField: function() { + if (!this.extraFields[1]) { + return; + } + var extraReader = readerFor(this.extraFields[1].value); + if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { + this.uncompressedSize = extraReader.readInt(8); + } + if (this.compressedSize === utils.MAX_VALUE_32BITS) { + this.compressedSize = extraReader.readInt(8); + } + if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { + this.localHeaderOffset = extraReader.readInt(8); + } + if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { + this.diskNumberStart = extraReader.readInt(4); + } + }, + readExtraFields: function(reader) { + var end = reader.index + this.extraFieldsLength, extraFieldId, extraFieldLength, extraFieldValue; + if (!this.extraFields) { + this.extraFields = {}; + } + while (reader.index + 4 < end) { + extraFieldId = reader.readInt(2); + extraFieldLength = reader.readInt(2); + extraFieldValue = reader.readData(extraFieldLength); + this.extraFields[extraFieldId] = { + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue + }; + } + reader.setIndex(end); + }, + handleUTF8: function() { + var decodeParamType = support.uint8array ? "uint8array" : "array"; + if (this.useUTF8()) { + this.fileNameStr = utf8.utf8decode(this.fileName); + this.fileCommentStr = utf8.utf8decode(this.fileComment); + } else { + var upath = this.findExtraFieldUnicodePath(); + if (upath !== null) { + this.fileNameStr = upath; + } else { + var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName); + this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray); + } + var ucomment = this.findExtraFieldUnicodeComment(); + if (ucomment !== null) { + this.fileCommentStr = ucomment; + } else { + var commentByteArray = utils.transformTo(decodeParamType, this.fileComment); + this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray); + } + } + }, + findExtraFieldUnicodePath: function() { + var upathField = this.extraFields[28789]; + if (upathField) { + var extraReader = readerFor(upathField.value); + if (extraReader.readInt(1) !== 1) { + return null; + } + if (crc32fn(this.fileName) !== extraReader.readInt(4)) { + return null; + } + return utf8.utf8decode(extraReader.readData(upathField.length - 5)); + } + return null; + }, + findExtraFieldUnicodeComment: function() { + var ucommentField = this.extraFields[25461]; + if (ucommentField) { + var extraReader = readerFor(ucommentField.value); + if (extraReader.readInt(1) !== 1) { + return null; + } + if (crc32fn(this.fileComment) !== extraReader.readInt(4)) { + return null; + } + return utf8.utf8decode(extraReader.readData(ucommentField.length - 5)); + } + return null; + } + }; + module2.exports = ZipEntry; +}); + +// node_modules/jszip/lib/zipEntries.js +var require_zipEntries = __commonJS((exports2, module2) => { + var readerFor = require_readerFor(); + var utils = require_utils(); + var sig = require_signature(); + var ZipEntry = require_zipEntry(); + var support = require_support(); + function ZipEntries(loadOptions) { + this.files = []; + this.loadOptions = loadOptions; + } + ZipEntries.prototype = { + checkSignature: function(expectedSignature) { + if (!this.reader.readAndCheckSignature(expectedSignature)) { + this.reader.index -= 4; + var signature = this.reader.readString(4); + throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); + } + }, + isSignature: function(askedIndex, expectedSignature) { + var currentIndex = this.reader.index; + this.reader.setIndex(askedIndex); + var signature = this.reader.readString(4); + var result = signature === expectedSignature; + this.reader.setIndex(currentIndex); + return result; + }, + readBlockEndOfCentral: function() { + this.diskNumber = this.reader.readInt(2); + this.diskWithCentralDirStart = this.reader.readInt(2); + this.centralDirRecordsOnThisDisk = this.reader.readInt(2); + this.centralDirRecords = this.reader.readInt(2); + this.centralDirSize = this.reader.readInt(4); + this.centralDirOffset = this.reader.readInt(4); + this.zipCommentLength = this.reader.readInt(2); + var zipComment = this.reader.readData(this.zipCommentLength); + var decodeParamType = support.uint8array ? "uint8array" : "array"; + var decodeContent = utils.transformTo(decodeParamType, zipComment); + this.zipComment = this.loadOptions.decodeFileName(decodeContent); + }, + readBlockZip64EndOfCentral: function() { + this.zip64EndOfCentralSize = this.reader.readInt(8); + this.reader.skip(4); + this.diskNumber = this.reader.readInt(4); + this.diskWithCentralDirStart = this.reader.readInt(4); + this.centralDirRecordsOnThisDisk = this.reader.readInt(8); + this.centralDirRecords = this.reader.readInt(8); + this.centralDirSize = this.reader.readInt(8); + this.centralDirOffset = this.reader.readInt(8); + this.zip64ExtensibleData = {}; + var extraDataSize = this.zip64EndOfCentralSize - 44, index2 = 0, extraFieldId, extraFieldLength, extraFieldValue; + while (index2 < extraDataSize) { + extraFieldId = this.reader.readInt(2); + extraFieldLength = this.reader.readInt(4); + extraFieldValue = this.reader.readData(extraFieldLength); + this.zip64ExtensibleData[extraFieldId] = { + id: extraFieldId, + length: extraFieldLength, + value: extraFieldValue + }; + } + }, + readBlockZip64EndOfCentralLocator: function() { + this.diskWithZip64CentralDirStart = this.reader.readInt(4); + this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); + this.disksCount = this.reader.readInt(4); + if (this.disksCount > 1) { + throw new Error("Multi-volumes zip are not supported"); + } + }, + readLocalFiles: function() { + var i, file; + for (i = 0;i < this.files.length; i++) { + file = this.files[i]; + this.reader.setIndex(file.localHeaderOffset); + this.checkSignature(sig.LOCAL_FILE_HEADER); + file.readLocalPart(this.reader); + file.handleUTF8(); + file.processAttributes(); + } + }, + readCentralDir: function() { + var file; + this.reader.setIndex(this.centralDirOffset); + while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) { + file = new ZipEntry({ + zip64: this.zip64 + }, this.loadOptions); + file.readCentralPart(this.reader); + this.files.push(file); + } + if (this.centralDirRecords !== this.files.length) { + if (this.centralDirRecords !== 0 && this.files.length === 0) { + throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); + } else { + } + } + }, + readEndOfCentral: function() { + var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); + if (offset < 0) { + var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER); + if (isGarbage) { + throw new Error("Can't find end of central directory : is this a zip file ? " + "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"); + } else { + throw new Error("Corrupted zip: can't find end of central directory"); + } + } + this.reader.setIndex(offset); + var endOfCentralDirOffset = offset; + this.checkSignature(sig.CENTRAL_DIRECTORY_END); + this.readBlockEndOfCentral(); + if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { + this.zip64 = true; + offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); + if (offset < 0) { + throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); + } + this.reader.setIndex(offset); + this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); + this.readBlockZip64EndOfCentralLocator(); + if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) { + this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + if (this.relativeOffsetEndOfZip64CentralDir < 0) { + throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); + } + } + this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); + this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); + this.readBlockZip64EndOfCentral(); + } + var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize; + if (this.zip64) { + expectedEndOfCentralDirOffset += 20; + expectedEndOfCentralDirOffset += 12 + this.zip64EndOfCentralSize; + } + var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset; + if (extraBytes > 0) { + if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) { + } else { + this.reader.zero = extraBytes; + } + } else if (extraBytes < 0) { + throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes."); + } + }, + prepareReader: function(data2) { + this.reader = readerFor(data2); + }, + load: function(data2) { + this.prepareReader(data2); + this.readEndOfCentral(); + this.readCentralDir(); + this.readLocalFiles(); + } + }; + module2.exports = ZipEntries; +}); + +// node_modules/jszip/lib/load.js +var require_load = __commonJS((exports2, module2) => { + var utils = require_utils(); + var external = require_external(); + var utf8 = require_utf8(); + var ZipEntries = require_zipEntries(); + var Crc32Probe = require_Crc32Probe(); + var nodejsUtils = require_nodejsUtils(); + function checkEntryCRC32(zipEntry) { + return new external.Promise(function(resolve, reject2) { + var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe); + worker.on("error", function(e) { + reject2(e); + }).on("end", function() { + if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) { + reject2(new Error("Corrupted zip : CRC32 mismatch")); + } else { + resolve(); + } + }).resume(); + }); + } + module2.exports = function(data2, options) { + var zip = this; + options = utils.extend(options || {}, { + base64: false, + checkCRC32: false, + optimizedBinaryString: false, + createFolders: false, + decodeFileName: utf8.utf8decode + }); + if (nodejsUtils.isNode && nodejsUtils.isStream(data2)) { + return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")); + } + return utils.prepareContent("the loaded zip file", data2, true, options.optimizedBinaryString, options.base64).then(function(data3) { + var zipEntries = new ZipEntries(options); + zipEntries.load(data3); + return zipEntries; + }).then(function checkCRC32(zipEntries) { + var promises = [external.Promise.resolve(zipEntries)]; + var files = zipEntries.files; + if (options.checkCRC32) { + for (var i = 0;i < files.length; i++) { + promises.push(checkEntryCRC32(files[i])); + } + } + return external.Promise.all(promises); + }).then(function addFiles(results) { + var zipEntries = results.shift(); + var files = zipEntries.files; + for (var i = 0;i < files.length; i++) { + var input = files[i]; + var unsafeName = input.fileNameStr; + var safeName = utils.resolve(input.fileNameStr); + zip.file(safeName, input.decompressed, { + binary: true, + optimizedBinaryString: true, + date: input.date, + dir: input.dir, + comment: input.fileCommentStr.length ? input.fileCommentStr : null, + unixPermissions: input.unixPermissions, + dosPermissions: input.dosPermissions, + createFolders: options.createFolders + }); + if (!input.dir) { + zip.file(safeName).unsafeOriginalName = unsafeName; + } + } + if (zipEntries.zipComment.length) { + zip.comment = zipEntries.zipComment; + } + return zip; + }); + }; +}); + +// node_modules/jszip/lib/index.js +var require_lib = __commonJS((exports2, module2) => { + function JSZip() { + if (!(this instanceof JSZip)) { + return new JSZip; + } + if (arguments.length) { + throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide."); + } + this.files = Object.create(null); + this.comment = null; + this.root = ""; + this.clone = function() { + var newObj = new JSZip; + for (var i in this) { + if (typeof this[i] !== "function") { + newObj[i] = this[i]; + } + } + return newObj; + }; + } + JSZip.prototype = require_object(); + JSZip.prototype.loadAsync = require_load(); + JSZip.support = require_support(); + JSZip.defaults = require_defaults(); + JSZip.version = "3.10.1"; + JSZip.loadAsync = function(content2, options) { + return new JSZip().loadAsync(content2, options); + }; + JSZip.external = require_external(); + module2.exports = JSZip; +}); + +// node_modules/localforage/dist/localforage.js +var require_localforage = __commonJS((exports2, module2) => { + /*! + localForage -- Offline Storage, Improved + Version 1.10.0 + https://localforage.github.io/localForage + (c) 2013-2017 Mozilla, Apache License 2.0 + */ + (function(f) { + if (typeof exports2 === "object" && typeof module2 !== "undefined") { + module2.exports = f(); + } else if (typeof define === "function" && define.amd) { + define([], f); + } else { + var g; + if (typeof window !== "undefined") { + g = window; + } else if (typeof global !== "undefined") { + g = global; + } else if (typeof self !== "undefined") { + g = self; + } else { + g = this; + } + g.localforage = f(); + } + })(function() { + var define2, module3, exports3; + return function e(t, n, r) { + function s(o2, u) { + if (!n[o2]) { + if (!t[o2]) { + var a = __require; + if (!u && a) + return a(o2, true); + if (i) + return i(o2, true); + var f = new Error("Cannot find module '" + o2 + "'"); + throw f.code = "MODULE_NOT_FOUND", f; + } + var l = n[o2] = { exports: {} }; + t[o2][0].call(l.exports, function(e) { + var n2 = t[o2][1][e]; + return s(n2 ? n2 : e); + }, l, l.exports, e, t, n, r); + } + return n[o2].exports; + } + var i = __require; + for (var o = 0;o < r.length; o++) + s(r[o]); + return s; + }({ 1: [function(_dereq_, module4, exports4) { + (function(global2) { + var Mutation = global2.MutationObserver || global2.WebKitMutationObserver; + var scheduleDrain; + { + if (Mutation) { + var called = 0; + var observer = new Mutation(nextTick); + var element = global2.document.createTextNode(""); + observer.observe(element, { + characterData: true + }); + scheduleDrain = function() { + element.data = called = ++called % 2; + }; + } else if (!global2.setImmediate && typeof global2.MessageChannel !== "undefined") { + var channel = new global2.MessageChannel; + channel.port1.onmessage = nextTick; + scheduleDrain = function() { + channel.port2.postMessage(0); + }; + } else if ("document" in global2 && "onreadystatechange" in global2.document.createElement("script")) { + scheduleDrain = function() { + var scriptEl = global2.document.createElement("script"); + scriptEl.onreadystatechange = function() { + nextTick(); + scriptEl.onreadystatechange = null; + scriptEl.parentNode.removeChild(scriptEl); + scriptEl = null; + }; + global2.document.documentElement.appendChild(scriptEl); + }; + } else { + scheduleDrain = function() { + setTimeout(nextTick, 0); + }; + } + } + var draining; + var queue = []; + function nextTick() { + draining = true; + var i, oldQueue; + var len = queue.length; + while (len) { + oldQueue = queue; + queue = []; + i = -1; + while (++i < len) { + oldQueue[i](); + } + len = queue.length; + } + draining = false; + } + module4.exports = immediate; + function immediate(task) { + if (queue.push(task) === 1 && !draining) { + scheduleDrain(); + } + } + }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); + }, {}], 2: [function(_dereq_, module4, exports4) { + var immediate = _dereq_(1); + function INTERNAL() { + } + var handlers = {}; + var REJECTED = ["REJECTED"]; + var FULFILLED = ["FULFILLED"]; + var PENDING = ["PENDING"]; + module4.exports = Promise2; + function Promise2(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("resolver must be a function"); + } + this.state = PENDING; + this.queue = []; + this.outcome = undefined; + if (resolver !== INTERNAL) { + safelyResolveThenable(this, resolver); + } + } + Promise2.prototype["catch"] = function(onRejected) { + return this.then(null, onRejected); + }; + Promise2.prototype.then = function(onFulfilled, onRejected) { + if (typeof onFulfilled !== "function" && this.state === FULFILLED || typeof onRejected !== "function" && this.state === REJECTED) { + return this; + } + var promise = new this.constructor(INTERNAL); + if (this.state !== PENDING) { + var resolver = this.state === FULFILLED ? onFulfilled : onRejected; + unwrap(promise, resolver, this.outcome); + } else { + this.queue.push(new QueueItem(promise, onFulfilled, onRejected)); + } + return promise; + }; + function QueueItem(promise, onFulfilled, onRejected) { + this.promise = promise; + if (typeof onFulfilled === "function") { + this.onFulfilled = onFulfilled; + this.callFulfilled = this.otherCallFulfilled; + } + if (typeof onRejected === "function") { + this.onRejected = onRejected; + this.callRejected = this.otherCallRejected; + } + } + QueueItem.prototype.callFulfilled = function(value2) { + handlers.resolve(this.promise, value2); + }; + QueueItem.prototype.otherCallFulfilled = function(value2) { + unwrap(this.promise, this.onFulfilled, value2); + }; + QueueItem.prototype.callRejected = function(value2) { + handlers.reject(this.promise, value2); + }; + QueueItem.prototype.otherCallRejected = function(value2) { + unwrap(this.promise, this.onRejected, value2); + }; + function unwrap(promise, func, value2) { + immediate(function() { + var returnValue; + try { + returnValue = func(value2); + } catch (e) { + return handlers.reject(promise, e); + } + if (returnValue === promise) { + handlers.reject(promise, new TypeError("Cannot resolve promise with itself")); + } else { + handlers.resolve(promise, returnValue); + } + }); + } + handlers.resolve = function(self2, value2) { + var result = tryCatch(getThen, value2); + if (result.status === "error") { + return handlers.reject(self2, result.value); + } + var thenable = result.value; + if (thenable) { + safelyResolveThenable(self2, thenable); + } else { + self2.state = FULFILLED; + self2.outcome = value2; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callFulfilled(value2); + } + } + return self2; + }; + handlers.reject = function(self2, error) { + self2.state = REJECTED; + self2.outcome = error; + var i = -1; + var len = self2.queue.length; + while (++i < len) { + self2.queue[i].callRejected(error); + } + return self2; + }; + function getThen(obj) { + var then = obj && obj.then; + if (obj && (typeof obj === "object" || typeof obj === "function") && typeof then === "function") { + return function appyThen() { + then.apply(obj, arguments); + }; + } + } + function safelyResolveThenable(self2, thenable) { + var called = false; + function onError(value2) { + if (called) { + return; + } + called = true; + handlers.reject(self2, value2); + } + function onSuccess(value2) { + if (called) { + return; + } + called = true; + handlers.resolve(self2, value2); + } + function tryToUnwrap() { + thenable(onSuccess, onError); + } + var result = tryCatch(tryToUnwrap); + if (result.status === "error") { + onError(result.value); + } + } + function tryCatch(func, value2) { + var out = {}; + try { + out.value = func(value2); + out.status = "success"; + } catch (e) { + out.status = "error"; + out.value = e; + } + return out; + } + Promise2.resolve = resolve; + function resolve(value2) { + if (value2 instanceof this) { + return value2; + } + return handlers.resolve(new this(INTERNAL), value2); + } + Promise2.reject = reject2; + function reject2(reason) { + var promise = new this(INTERNAL); + return handlers.reject(promise, reason); + } + Promise2.all = all; + function all(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var values2 = new Array(len); + var resolved = 0; + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + allResolver(iterable[i], i); + } + return promise; + function allResolver(value2, i2) { + self2.resolve(value2).then(resolveFromAll, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + function resolveFromAll(outValue) { + values2[i2] = outValue; + if (++resolved === len && !called) { + called = true; + handlers.resolve(promise, values2); + } + } + } + } + Promise2.race = race; + function race(iterable) { + var self2 = this; + if (Object.prototype.toString.call(iterable) !== "[object Array]") { + return this.reject(new TypeError("must be an array")); + } + var len = iterable.length; + var called = false; + if (!len) { + return this.resolve([]); + } + var i = -1; + var promise = new this(INTERNAL); + while (++i < len) { + resolver(iterable[i]); + } + return promise; + function resolver(value2) { + self2.resolve(value2).then(function(response) { + if (!called) { + called = true; + handlers.resolve(promise, response); + } + }, function(error) { + if (!called) { + called = true; + handlers.reject(promise, error); + } + }); + } + } + }, { "1": 1 }], 3: [function(_dereq_, module4, exports4) { + (function(global2) { + if (typeof global2.Promise !== "function") { + global2.Promise = _dereq_(2); + } + }).call(this, typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); + }, { "2": 2 }], 4: [function(_dereq_, module4, exports4) { + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) { + return typeof obj; + } : function(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function getIDB() { + try { + if (typeof indexedDB !== "undefined") { + return indexedDB; + } + if (typeof webkitIndexedDB !== "undefined") { + return webkitIndexedDB; + } + if (typeof mozIndexedDB !== "undefined") { + return mozIndexedDB; + } + if (typeof OIndexedDB !== "undefined") { + return OIndexedDB; + } + if (typeof msIndexedDB !== "undefined") { + return msIndexedDB; + } + } catch (e) { + return; + } + } + var idb = getIDB(); + function isIndexedDBValid() { + try { + if (!idb || !idb.open) { + return false; + } + var isSafari2 = typeof openDatabase !== "undefined" && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform); + var hasFetch = typeof fetch === "function" && fetch.toString().indexOf("[native code") !== -1; + return (!isSafari2 || hasFetch) && typeof indexedDB !== "undefined" && typeof IDBKeyRange !== "undefined"; + } catch (e) { + return false; + } + } + function createBlob(parts, properties) { + parts = parts || []; + properties = properties || {}; + try { + return new Blob(parts, properties); + } catch (e) { + if (e.name !== "TypeError") { + throw e; + } + var Builder = typeof BlobBuilder !== "undefined" ? BlobBuilder : typeof MSBlobBuilder !== "undefined" ? MSBlobBuilder : typeof MozBlobBuilder !== "undefined" ? MozBlobBuilder : WebKitBlobBuilder; + var builder = new Builder; + for (var i = 0;i < parts.length; i += 1) { + builder.append(parts[i]); + } + return builder.getBlob(properties.type); + } + } + if (typeof Promise === "undefined") { + _dereq_(3); + } + var Promise$1 = Promise; + function executeCallback(promise, callback) { + if (callback) { + promise.then(function(result) { + callback(null, result); + }, function(error) { + callback(error); + }); + } + } + function executeTwoCallbacks(promise, callback, errorCallback) { + if (typeof callback === "function") { + promise.then(callback); + } + if (typeof errorCallback === "function") { + promise["catch"](errorCallback); + } + } + function normalizeKey(key3) { + if (typeof key3 !== "string") { + console.warn(key3 + " used as a key, but it is not a string."); + key3 = String(key3); + } + return key3; + } + function getCallback() { + if (arguments.length && typeof arguments[arguments.length - 1] === "function") { + return arguments[arguments.length - 1]; + } + } + var DETECT_BLOB_SUPPORT_STORE = "local-forage-detect-blob-support"; + var supportsBlobs = undefined; + var dbContexts = {}; + var toString2 = Object.prototype.toString; + var READ_ONLY = "readonly"; + var READ_WRITE = "readwrite"; + function _binStringToArrayBuffer(bin) { + var length3 = bin.length; + var buf = new ArrayBuffer(length3); + var arr = new Uint8Array(buf); + for (var i = 0;i < length3; i++) { + arr[i] = bin.charCodeAt(i); + } + return buf; + } + function _checkBlobSupportWithoutCaching(idb2) { + return new Promise$1(function(resolve) { + var txn = idb2.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE); + var blob = createBlob([""]); + txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, "key"); + txn.onabort = function(e) { + e.preventDefault(); + e.stopPropagation(); + resolve(false); + }; + txn.oncomplete = function() { + var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/); + var matchedEdge = navigator.userAgent.match(/Edge\//); + resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43); + }; + })["catch"](function() { + return false; + }); + } + function _checkBlobSupport(idb2) { + if (typeof supportsBlobs === "boolean") { + return Promise$1.resolve(supportsBlobs); + } + return _checkBlobSupportWithoutCaching(idb2).then(function(value2) { + supportsBlobs = value2; + return supportsBlobs; + }); + } + function _deferReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + var deferredOperation = {}; + deferredOperation.promise = new Promise$1(function(resolve, reject2) { + deferredOperation.resolve = resolve; + deferredOperation.reject = reject2; + }); + dbContext.deferredOperations.push(deferredOperation); + if (!dbContext.dbReady) { + dbContext.dbReady = deferredOperation.promise; + } else { + dbContext.dbReady = dbContext.dbReady.then(function() { + return deferredOperation.promise; + }); + } + } + function _advanceReadiness(dbInfo) { + var dbContext = dbContexts[dbInfo.name]; + var deferredOperation = dbContext.deferredOperations.pop(); + if (deferredOperation) { + deferredOperation.resolve(); + return deferredOperation.promise; + } + } + function _rejectReadiness(dbInfo, err) { + var dbContext = dbContexts[dbInfo.name]; + var deferredOperation = dbContext.deferredOperations.pop(); + if (deferredOperation) { + deferredOperation.reject(err); + return deferredOperation.promise; + } + } + function _getConnection(dbInfo, upgradeNeeded) { + return new Promise$1(function(resolve, reject2) { + dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext(); + if (dbInfo.db) { + if (upgradeNeeded) { + _deferReadiness(dbInfo); + dbInfo.db.close(); + } else { + return resolve(dbInfo.db); + } + } + var dbArgs = [dbInfo.name]; + if (upgradeNeeded) { + dbArgs.push(dbInfo.version); + } + var openreq = idb.open.apply(idb, dbArgs); + if (upgradeNeeded) { + openreq.onupgradeneeded = function(e) { + var db = openreq.result; + try { + db.createObjectStore(dbInfo.storeName); + if (e.oldVersion <= 1) { + db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); + } + } catch (ex) { + if (ex.name === "ConstraintError") { + console.warn('The database "' + dbInfo.name + '"' + " has been upgraded from version " + e.oldVersion + " to version " + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); + } else { + throw ex; + } + } + }; + } + openreq.onerror = function(e) { + e.preventDefault(); + reject2(openreq.error); + }; + openreq.onsuccess = function() { + var db = openreq.result; + db.onversionchange = function(e) { + e.target.close(); + }; + resolve(db); + _advanceReadiness(dbInfo); + }; + }); + } + function _getOriginalConnection(dbInfo) { + return _getConnection(dbInfo, false); + } + function _getUpgradedConnection(dbInfo) { + return _getConnection(dbInfo, true); + } + function _isUpgradeNeeded(dbInfo, defaultVersion) { + if (!dbInfo.db) { + return true; + } + var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); + var isDowngrade = dbInfo.version < dbInfo.db.version; + var isUpgrade = dbInfo.version > dbInfo.db.version; + if (isDowngrade) { + if (dbInfo.version !== defaultVersion) { + console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + " to version " + dbInfo.version + "."); + } + dbInfo.version = dbInfo.db.version; + } + if (isUpgrade || isNewStore) { + if (isNewStore) { + var incVersion = dbInfo.db.version + 1; + if (incVersion > dbInfo.version) { + dbInfo.version = incVersion; + } + } + return true; + } + return false; + } + function _encodeBlob(blob) { + return new Promise$1(function(resolve, reject2) { + var reader = new FileReader; + reader.onerror = reject2; + reader.onloadend = function(e) { + var base64 = btoa(e.target.result || ""); + resolve({ + __local_forage_encoded_blob: true, + data: base64, + type: blob.type + }); + }; + reader.readAsBinaryString(blob); + }); + } + function _decodeBlob(encodedBlob) { + var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); + return createBlob([arrayBuff], { type: encodedBlob.type }); + } + function _isEncodedBlob(value2) { + return value2 && value2.__local_forage_encoded_blob; + } + function _fullyReady(callback) { + var self2 = this; + var promise = self2._initReady().then(function() { + var dbContext = dbContexts[self2._dbInfo.name]; + if (dbContext && dbContext.dbReady) { + return dbContext.dbReady; + } + }); + executeTwoCallbacks(promise, callback, callback); + return promise; + } + function _tryReconnect(dbInfo) { + _deferReadiness(dbInfo); + var dbContext = dbContexts[dbInfo.name]; + var forages = dbContext.forages; + for (var i = 0;i < forages.length; i++) { + var forage = forages[i]; + if (forage._dbInfo.db) { + forage._dbInfo.db.close(); + forage._dbInfo.db = null; + } + } + dbInfo.db = null; + return _getOriginalConnection(dbInfo).then(function(db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo)) { + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function(db) { + dbInfo.db = dbContext.db = db; + for (var i2 = 0;i2 < forages.length; i2++) { + forages[i2]._dbInfo.db = db; + } + })["catch"](function(err) { + _rejectReadiness(dbInfo, err); + throw err; + }); + } + function createTransaction(dbInfo, mode, callback, retries) { + if (retries === undefined) { + retries = 1; + } + try { + var tx = dbInfo.db.transaction(dbInfo.storeName, mode); + callback(null, tx); + } catch (err) { + if (retries > 0 && (!dbInfo.db || err.name === "InvalidStateError" || err.name === "NotFoundError")) { + return Promise$1.resolve().then(function() { + if (!dbInfo.db || err.name === "NotFoundError" && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) { + if (dbInfo.db) { + dbInfo.version = dbInfo.db.version + 1; + } + return _getUpgradedConnection(dbInfo); + } + }).then(function() { + return _tryReconnect(dbInfo).then(function() { + createTransaction(dbInfo, mode, callback, retries - 1); + }); + })["catch"](callback); + } + callback(err); + } + } + function createDbContext() { + return { + forages: [], + db: null, + dbReady: null, + deferredOperations: [] + }; + } + function _initStorage(options) { + var self2 = this; + var dbInfo = { + db: null + }; + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + var dbContext = dbContexts[dbInfo.name]; + if (!dbContext) { + dbContext = createDbContext(); + dbContexts[dbInfo.name] = dbContext; + } + dbContext.forages.push(self2); + if (!self2._initReady) { + self2._initReady = self2.ready; + self2.ready = _fullyReady; + } + var initPromises = []; + function ignoreErrors() { + return Promise$1.resolve(); + } + for (var j = 0;j < dbContext.forages.length; j++) { + var forage = dbContext.forages[j]; + if (forage !== self2) { + initPromises.push(forage._initReady()["catch"](ignoreErrors)); + } + } + var forages = dbContext.forages.slice(0); + return Promise$1.all(initPromises).then(function() { + dbInfo.db = dbContext.db; + return _getOriginalConnection(dbInfo); + }).then(function(db) { + dbInfo.db = db; + if (_isUpgradeNeeded(dbInfo, self2._defaultConfig.version)) { + return _getUpgradedConnection(dbInfo); + } + return db; + }).then(function(db) { + dbInfo.db = dbContext.db = db; + self2._dbInfo = dbInfo; + for (var k2 = 0;k2 < forages.length; k2++) { + var forage2 = forages[k2]; + if (forage2 !== self2) { + forage2._dbInfo.db = dbInfo.db; + forage2._dbInfo.version = dbInfo.version; + } + } + }); + } + function getItem(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.get(key3); + req.onsuccess = function() { + var value2 = req.result; + if (value2 === undefined) { + value2 = null; + } + if (_isEncodedBlob(value2)) { + value2 = _decodeBlob(value2); + } + resolve(value2); + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function iterate(iterator, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.openCursor(); + var iterationNumber = 1; + req.onsuccess = function() { + var cursor = req.result; + if (cursor) { + var value2 = cursor.value; + if (_isEncodedBlob(value2)) { + value2 = _decodeBlob(value2); + } + var result = iterator(value2, cursor.key, iterationNumber++); + if (result !== undefined) { + resolve(result); + } else { + cursor["continue"](); + } + } else { + resolve(); + } + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function setItem(key3, value2, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + var dbInfo; + self2.ready().then(function() { + dbInfo = self2._dbInfo; + if (toString2.call(value2) === "[object Blob]") { + return _checkBlobSupport(dbInfo.db).then(function(blobSupport) { + if (blobSupport) { + return value2; + } + return _encodeBlob(value2); + }); + } + return value2; + }).then(function(value3) { + createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + if (value3 === null) { + value3 = undefined; + } + var req = store.put(value3, key3); + transaction.oncomplete = function() { + if (value3 === undefined) { + value3 = null; + } + resolve(value3); + }; + transaction.onabort = transaction.onerror = function() { + var err2 = req.error ? req.error : req.transaction.error; + reject2(err2); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function removeItem(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store["delete"](key3); + transaction.oncomplete = function() { + resolve(); + }; + transaction.onerror = function() { + reject2(req.error); + }; + transaction.onabort = function() { + var err2 = req.error ? req.error : req.transaction.error; + reject2(err2); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function clear(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_WRITE, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.clear(); + transaction.oncomplete = function() { + resolve(); + }; + transaction.onabort = transaction.onerror = function() { + var err2 = req.error ? req.error : req.transaction.error; + reject2(err2); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function length2(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.count(); + req.onsuccess = function() { + resolve(req.result); + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function key2(n, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + if (n < 0) { + resolve(null); + return; + } + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var advanced = false; + var req = store.openKeyCursor(); + req.onsuccess = function() { + var cursor = req.result; + if (!cursor) { + resolve(null); + return; + } + if (n === 0) { + resolve(cursor.key); + } else { + if (!advanced) { + advanced = true; + cursor.advance(n); + } else { + resolve(cursor.key); + } + } + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function keys2(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + createTransaction(self2._dbInfo, READ_ONLY, function(err, transaction) { + if (err) { + return reject2(err); + } + try { + var store = transaction.objectStore(self2._dbInfo.storeName); + var req = store.openKeyCursor(); + var keys3 = []; + req.onsuccess = function() { + var cursor = req.result; + if (!cursor) { + resolve(keys3); + return; + } + keys3.push(cursor.key); + cursor["continue"](); + }; + req.onerror = function() { + reject2(req.error); + }; + } catch (e) { + reject2(e); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function dropInstance(options, callback) { + callback = getCallback.apply(this, arguments); + var currentConfig = this.config(); + options = typeof options !== "function" && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + var self2 = this; + var promise; + if (!options.name) { + promise = Promise$1.reject("Invalid arguments"); + } else { + var isCurrentDb = options.name === currentConfig.name && self2._dbInfo.db; + var dbPromise = isCurrentDb ? Promise$1.resolve(self2._dbInfo.db) : _getOriginalConnection(options).then(function(db) { + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + dbContext.db = db; + for (var i = 0;i < forages.length; i++) { + forages[i]._dbInfo.db = db; + } + return db; + }); + if (!options.storeName) { + promise = dbPromise.then(function(db) { + _deferReadiness(options); + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + db.close(); + for (var i = 0;i < forages.length; i++) { + var forage = forages[i]; + forage._dbInfo.db = null; + } + var dropDBPromise = new Promise$1(function(resolve, reject2) { + var req = idb.deleteDatabase(options.name); + req.onerror = function() { + var db2 = req.result; + if (db2) { + db2.close(); + } + reject2(req.error); + }; + req.onblocked = function() { + console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed'); + }; + req.onsuccess = function() { + var db2 = req.result; + if (db2) { + db2.close(); + } + resolve(db2); + }; + }); + return dropDBPromise.then(function(db2) { + dbContext.db = db2; + for (var i2 = 0;i2 < forages.length; i2++) { + var _forage = forages[i2]; + _advanceReadiness(_forage._dbInfo); + } + })["catch"](function(err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() { + }); + throw err; + }); + }); + } else { + promise = dbPromise.then(function(db) { + if (!db.objectStoreNames.contains(options.storeName)) { + return; + } + var newVersion = db.version + 1; + _deferReadiness(options); + var dbContext = dbContexts[options.name]; + var forages = dbContext.forages; + db.close(); + for (var i = 0;i < forages.length; i++) { + var forage = forages[i]; + forage._dbInfo.db = null; + forage._dbInfo.version = newVersion; + } + var dropObjectPromise = new Promise$1(function(resolve, reject2) { + var req = idb.open(options.name, newVersion); + req.onerror = function(err) { + var db2 = req.result; + db2.close(); + reject2(err); + }; + req.onupgradeneeded = function() { + var db2 = req.result; + db2.deleteObjectStore(options.storeName); + }; + req.onsuccess = function() { + var db2 = req.result; + db2.close(); + resolve(db2); + }; + }); + return dropObjectPromise.then(function(db2) { + dbContext.db = db2; + for (var j = 0;j < forages.length; j++) { + var _forage2 = forages[j]; + _forage2._dbInfo.db = db2; + _advanceReadiness(_forage2._dbInfo); + } + })["catch"](function(err) { + (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function() { + }); + throw err; + }); + }); + } + } + executeCallback(promise, callback); + return promise; + } + var asyncStorage = { + _driver: "asyncStorage", + _initStorage, + _support: isIndexedDBValid(), + iterate, + getItem, + setItem, + removeItem, + clear, + length: length2, + key: key2, + keys: keys2, + dropInstance + }; + function isWebSQLValid() { + return typeof openDatabase === "function"; + } + var BASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var BLOB_TYPE_PREFIX = "~~local_forage_type~"; + var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; + var SERIALIZED_MARKER = "__lfsc__:"; + var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; + var TYPE_ARRAYBUFFER = "arbf"; + var TYPE_BLOB = "blob"; + var TYPE_INT8ARRAY = "si08"; + var TYPE_UINT8ARRAY = "ui08"; + var TYPE_UINT8CLAMPEDARRAY = "uic8"; + var TYPE_INT16ARRAY = "si16"; + var TYPE_INT32ARRAY = "si32"; + var TYPE_UINT16ARRAY = "ur16"; + var TYPE_UINT32ARRAY = "ui32"; + var TYPE_FLOAT32ARRAY = "fl32"; + var TYPE_FLOAT64ARRAY = "fl64"; + var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; + var toString$1 = Object.prototype.toString; + function stringToBuffer(serializedString) { + var bufferLength = serializedString.length * 0.75; + var len = serializedString.length; + var i; + var p = 0; + var encoded1, encoded2, encoded3, encoded4; + if (serializedString[serializedString.length - 1] === "=") { + bufferLength--; + if (serializedString[serializedString.length - 2] === "=") { + bufferLength--; + } + } + var buffer = new ArrayBuffer(bufferLength); + var bytes = new Uint8Array(buffer); + for (i = 0;i < len; i += 4) { + encoded1 = BASE_CHARS.indexOf(serializedString[i]); + encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); + encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); + encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + return buffer; + } + function bufferToString(buffer) { + var bytes = new Uint8Array(buffer); + var base64String = ""; + var i; + for (i = 0;i < bytes.length; i += 3) { + base64String += BASE_CHARS[bytes[i] >> 2]; + base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; + base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; + base64String += BASE_CHARS[bytes[i + 2] & 63]; + } + if (bytes.length % 3 === 2) { + base64String = base64String.substring(0, base64String.length - 1) + "="; + } else if (bytes.length % 3 === 1) { + base64String = base64String.substring(0, base64String.length - 2) + "=="; + } + return base64String; + } + function serialize(value2, callback) { + var valueType = ""; + if (value2) { + valueType = toString$1.call(value2); + } + if (value2 && (valueType === "[object ArrayBuffer]" || value2.buffer && toString$1.call(value2.buffer) === "[object ArrayBuffer]")) { + var buffer; + var marker = SERIALIZED_MARKER; + if (value2 instanceof ArrayBuffer) { + buffer = value2; + marker += TYPE_ARRAYBUFFER; + } else { + buffer = value2.buffer; + if (valueType === "[object Int8Array]") { + marker += TYPE_INT8ARRAY; + } else if (valueType === "[object Uint8Array]") { + marker += TYPE_UINT8ARRAY; + } else if (valueType === "[object Uint8ClampedArray]") { + marker += TYPE_UINT8CLAMPEDARRAY; + } else if (valueType === "[object Int16Array]") { + marker += TYPE_INT16ARRAY; + } else if (valueType === "[object Uint16Array]") { + marker += TYPE_UINT16ARRAY; + } else if (valueType === "[object Int32Array]") { + marker += TYPE_INT32ARRAY; + } else if (valueType === "[object Uint32Array]") { + marker += TYPE_UINT32ARRAY; + } else if (valueType === "[object Float32Array]") { + marker += TYPE_FLOAT32ARRAY; + } else if (valueType === "[object Float64Array]") { + marker += TYPE_FLOAT64ARRAY; + } else { + callback(new Error("Failed to get type for BinaryArray")); + } + } + callback(marker + bufferToString(buffer)); + } else if (valueType === "[object Blob]") { + var fileReader = new FileReader; + fileReader.onload = function() { + var str = BLOB_TYPE_PREFIX + value2.type + "~" + bufferToString(this.result); + callback(SERIALIZED_MARKER + TYPE_BLOB + str); + }; + fileReader.readAsArrayBuffer(value2); + } else { + try { + callback(JSON.stringify(value2)); + } catch (e) { + console.error("Couldn't convert value into a JSON string: ", value2); + callback(null, e); + } + } + } + function deserialize(value2) { + if (value2.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { + return JSON.parse(value2); + } + var serializedString = value2.substring(TYPE_SERIALIZED_MARKER_LENGTH); + var type = value2.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); + var blobType; + if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { + var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); + blobType = matcher[1]; + serializedString = serializedString.substring(matcher[0].length); + } + var buffer = stringToBuffer(serializedString); + switch (type) { + case TYPE_ARRAYBUFFER: + return buffer; + case TYPE_BLOB: + return createBlob([buffer], { type: blobType }); + case TYPE_INT8ARRAY: + return new Int8Array(buffer); + case TYPE_UINT8ARRAY: + return new Uint8Array(buffer); + case TYPE_UINT8CLAMPEDARRAY: + return new Uint8ClampedArray(buffer); + case TYPE_INT16ARRAY: + return new Int16Array(buffer); + case TYPE_UINT16ARRAY: + return new Uint16Array(buffer); + case TYPE_INT32ARRAY: + return new Int32Array(buffer); + case TYPE_UINT32ARRAY: + return new Uint32Array(buffer); + case TYPE_FLOAT32ARRAY: + return new Float32Array(buffer); + case TYPE_FLOAT64ARRAY: + return new Float64Array(buffer); + default: + throw new Error("Unkown type: " + type); + } + } + var localforageSerializer = { + serialize, + deserialize, + stringToBuffer, + bufferToString + }; + function createDbTable(t, dbInfo, callback, errorCallback) { + t.executeSql("CREATE TABLE IF NOT EXISTS " + dbInfo.storeName + " " + "(id INTEGER PRIMARY KEY, key unique, value)", [], callback, errorCallback); + } + function _initStorage$1(options) { + var self2 = this; + var dbInfo = { + db: null + }; + if (options) { + for (var i in options) { + dbInfo[i] = typeof options[i] !== "string" ? options[i].toString() : options[i]; + } + } + var dbInfoPromise = new Promise$1(function(resolve, reject2) { + try { + dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); + } catch (e) { + return reject2(e); + } + dbInfo.db.transaction(function(t) { + createDbTable(t, dbInfo, function() { + self2._dbInfo = dbInfo; + resolve(); + }, function(t2, error) { + reject2(error); + }); + }, reject2); + }); + dbInfo.serializer = localforageSerializer; + return dbInfoPromise; + } + function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) { + t.executeSql(sqlStatement, args, callback, function(t2, error) { + if (error.code === error.SYNTAX_ERR) { + t2.executeSql("SELECT name FROM sqlite_master " + "WHERE type='table' AND name = ?", [dbInfo.storeName], function(t3, results) { + if (!results.rows.length) { + createDbTable(t3, dbInfo, function() { + t3.executeSql(sqlStatement, args, callback, errorCallback); + }, errorCallback); + } else { + errorCallback(t3, error); + } + }, errorCallback); + } else { + errorCallback(t2, error); + } + }, errorCallback); + } + function getItem$1(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT * FROM " + dbInfo.storeName + " WHERE key = ? LIMIT 1", [key3], function(t2, results) { + var result = results.rows.length ? results.rows.item(0).value : null; + if (result) { + result = dbInfo.serializer.deserialize(result); + } + resolve(result); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function iterate$1(iterator, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT * FROM " + dbInfo.storeName, [], function(t2, results) { + var rows = results.rows; + var length3 = rows.length; + for (var i = 0;i < length3; i++) { + var item = rows.item(i); + var result = item.value; + if (result) { + result = dbInfo.serializer.deserialize(result); + } + result = iterator(result, item.key, i + 1); + if (result !== undefined) { + resolve(result); + return; + } + } + resolve(); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function _setItem(key3, value2, callback, retriesLeft) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + if (value2 === undefined) { + value2 = null; + } + var originalValue = value2; + var dbInfo = self2._dbInfo; + dbInfo.serializer.serialize(value2, function(value3, error) { + if (error) { + reject2(error); + } else { + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "INSERT OR REPLACE INTO " + dbInfo.storeName + " " + "(key, value) VALUES (?, ?)", [key3, value3], function() { + resolve(originalValue); + }, function(t2, error2) { + reject2(error2); + }); + }, function(sqlError) { + if (sqlError.code === sqlError.QUOTA_ERR) { + if (retriesLeft > 0) { + resolve(_setItem.apply(self2, [key3, originalValue, callback, retriesLeft - 1])); + return; + } + reject2(sqlError); + } + }); + } + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function setItem$1(key3, value2, callback) { + return _setItem.apply(this, [key3, value2, callback, 1]); + } + function removeItem$1(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "DELETE FROM " + dbInfo.storeName + " WHERE key = ?", [key3], function() { + resolve(); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function clear$1(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "DELETE FROM " + dbInfo.storeName, [], function() { + resolve(); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function length$1(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT COUNT(key) as c FROM " + dbInfo.storeName, [], function(t2, results) { + var result = results.rows.item(0).c; + resolve(result); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function key$1(n, callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT key FROM " + dbInfo.storeName + " WHERE id = ? LIMIT 1", [n + 1], function(t2, results) { + var result = results.rows.length ? results.rows.item(0).key : null; + resolve(result); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function keys$1(callback) { + var self2 = this; + var promise = new Promise$1(function(resolve, reject2) { + self2.ready().then(function() { + var dbInfo = self2._dbInfo; + dbInfo.db.transaction(function(t) { + tryExecuteSql(t, dbInfo, "SELECT key FROM " + dbInfo.storeName, [], function(t2, results) { + var keys3 = []; + for (var i = 0;i < results.rows.length; i++) { + keys3.push(results.rows.item(i).key); + } + resolve(keys3); + }, function(t2, error) { + reject2(error); + }); + }); + })["catch"](reject2); + }); + executeCallback(promise, callback); + return promise; + } + function getAllStoreNames(db) { + return new Promise$1(function(resolve, reject2) { + db.transaction(function(t) { + t.executeSql("SELECT name FROM sqlite_master " + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function(t2, results) { + var storeNames = []; + for (var i = 0;i < results.rows.length; i++) { + storeNames.push(results.rows.item(i).name); + } + resolve({ + db, + storeNames + }); + }, function(t2, error) { + reject2(error); + }); + }, function(sqlError) { + reject2(sqlError); + }); + }); + } + function dropInstance$1(options, callback) { + callback = getCallback.apply(this, arguments); + var currentConfig = this.config(); + options = typeof options !== "function" && options || {}; + if (!options.name) { + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + var self2 = this; + var promise; + if (!options.name) { + promise = Promise$1.reject("Invalid arguments"); + } else { + promise = new Promise$1(function(resolve) { + var db; + if (options.name === currentConfig.name) { + db = self2._dbInfo.db; + } else { + db = openDatabase(options.name, "", "", 0); + } + if (!options.storeName) { + resolve(getAllStoreNames(db)); + } else { + resolve({ + db, + storeNames: [options.storeName] + }); + } + }).then(function(operationInfo) { + return new Promise$1(function(resolve, reject2) { + operationInfo.db.transaction(function(t) { + function dropTable(storeName) { + return new Promise$1(function(resolve2, reject3) { + t.executeSql("DROP TABLE IF EXISTS " + storeName, [], function() { + resolve2(); + }, function(t2, error) { + reject3(error); + }); + }); + } + var operations = []; + for (var i = 0, len = operationInfo.storeNames.length;i < len; i++) { + operations.push(dropTable(operationInfo.storeNames[i])); + } + Promise$1.all(operations).then(function() { + resolve(); + })["catch"](function(e) { + reject2(e); + }); + }, function(sqlError) { + reject2(sqlError); + }); + }); + }); + } + executeCallback(promise, callback); + return promise; + } + var webSQLStorage = { + _driver: "webSQLStorage", + _initStorage: _initStorage$1, + _support: isWebSQLValid(), + iterate: iterate$1, + getItem: getItem$1, + setItem: setItem$1, + removeItem: removeItem$1, + clear: clear$1, + length: length$1, + key: key$1, + keys: keys$1, + dropInstance: dropInstance$1 + }; + function isLocalStorageValid() { + try { + return typeof localStorage !== "undefined" && "setItem" in localStorage && !!localStorage.setItem; + } catch (e) { + return false; + } + } + function _getKeyPrefix(options, defaultConfig) { + var keyPrefix = options.name + "/"; + if (options.storeName !== defaultConfig.storeName) { + keyPrefix += options.storeName + "/"; + } + return keyPrefix; + } + function checkIfLocalStorageThrows() { + var localStorageTestKey = "_localforage_support_test"; + try { + localStorage.setItem(localStorageTestKey, true); + localStorage.removeItem(localStorageTestKey); + return false; + } catch (e) { + return true; + } + } + function _isLocalStorageUsable() { + return !checkIfLocalStorageThrows() || localStorage.length > 0; + } + function _initStorage$2(options) { + var self2 = this; + var dbInfo = {}; + if (options) { + for (var i in options) { + dbInfo[i] = options[i]; + } + } + dbInfo.keyPrefix = _getKeyPrefix(options, self2._defaultConfig); + if (!_isLocalStorageUsable()) { + return Promise$1.reject(); + } + self2._dbInfo = dbInfo; + dbInfo.serializer = localforageSerializer; + return Promise$1.resolve(); + } + function clear$2(callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var keyPrefix = self2._dbInfo.keyPrefix; + for (var i = localStorage.length - 1;i >= 0; i--) { + var key3 = localStorage.key(i); + if (key3.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key3); + } + } + }); + executeCallback(promise, callback); + return promise; + } + function getItem$2(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var result = localStorage.getItem(dbInfo.keyPrefix + key3); + if (result) { + result = dbInfo.serializer.deserialize(result); + } + return result; + }); + executeCallback(promise, callback); + return promise; + } + function iterate$2(iterator, callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var keyPrefix = dbInfo.keyPrefix; + var keyPrefixLength = keyPrefix.length; + var length3 = localStorage.length; + var iterationNumber = 1; + for (var i = 0;i < length3; i++) { + var key3 = localStorage.key(i); + if (key3.indexOf(keyPrefix) !== 0) { + continue; + } + var value2 = localStorage.getItem(key3); + if (value2) { + value2 = dbInfo.serializer.deserialize(value2); + } + value2 = iterator(value2, key3.substring(keyPrefixLength), iterationNumber++); + if (value2 !== undefined) { + return value2; + } + } + }); + executeCallback(promise, callback); + return promise; + } + function key$2(n, callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var result; + try { + result = localStorage.key(n); + } catch (error) { + result = null; + } + if (result) { + result = result.substring(dbInfo.keyPrefix.length); + } + return result; + }); + executeCallback(promise, callback); + return promise; + } + function keys$2(callback) { + var self2 = this; + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + var length3 = localStorage.length; + var keys3 = []; + for (var i = 0;i < length3; i++) { + var itemKey = localStorage.key(i); + if (itemKey.indexOf(dbInfo.keyPrefix) === 0) { + keys3.push(itemKey.substring(dbInfo.keyPrefix.length)); + } + } + return keys3; + }); + executeCallback(promise, callback); + return promise; + } + function length$2(callback) { + var self2 = this; + var promise = self2.keys().then(function(keys3) { + return keys3.length; + }); + executeCallback(promise, callback); + return promise; + } + function removeItem$2(key3, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = self2.ready().then(function() { + var dbInfo = self2._dbInfo; + localStorage.removeItem(dbInfo.keyPrefix + key3); + }); + executeCallback(promise, callback); + return promise; + } + function setItem$2(key3, value2, callback) { + var self2 = this; + key3 = normalizeKey(key3); + var promise = self2.ready().then(function() { + if (value2 === undefined) { + value2 = null; + } + var originalValue = value2; + return new Promise$1(function(resolve, reject2) { + var dbInfo = self2._dbInfo; + dbInfo.serializer.serialize(value2, function(value3, error) { + if (error) { + reject2(error); + } else { + try { + localStorage.setItem(dbInfo.keyPrefix + key3, value3); + resolve(originalValue); + } catch (e) { + if (e.name === "QuotaExceededError" || e.name === "NS_ERROR_DOM_QUOTA_REACHED") { + reject2(e); + } + reject2(e); + } + } + }); + }); + }); + executeCallback(promise, callback); + return promise; + } + function dropInstance$2(options, callback) { + callback = getCallback.apply(this, arguments); + options = typeof options !== "function" && options || {}; + if (!options.name) { + var currentConfig = this.config(); + options.name = options.name || currentConfig.name; + options.storeName = options.storeName || currentConfig.storeName; + } + var self2 = this; + var promise; + if (!options.name) { + promise = Promise$1.reject("Invalid arguments"); + } else { + promise = new Promise$1(function(resolve) { + if (!options.storeName) { + resolve(options.name + "/"); + } else { + resolve(_getKeyPrefix(options, self2._defaultConfig)); + } + }).then(function(keyPrefix) { + for (var i = localStorage.length - 1;i >= 0; i--) { + var key3 = localStorage.key(i); + if (key3.indexOf(keyPrefix) === 0) { + localStorage.removeItem(key3); + } + } + }); + } + executeCallback(promise, callback); + return promise; + } + var localStorageWrapper = { + _driver: "localStorageWrapper", + _initStorage: _initStorage$2, + _support: isLocalStorageValid(), + iterate: iterate$2, + getItem: getItem$2, + setItem: setItem$2, + removeItem: removeItem$2, + clear: clear$2, + length: length$2, + key: key$2, + keys: keys$2, + dropInstance: dropInstance$2 + }; + var sameValue = function sameValue(x, y) { + return x === y || typeof x === "number" && typeof y === "number" && isNaN(x) && isNaN(y); + }; + var includes = function includes(array, searchElement) { + var len = array.length; + var i = 0; + while (i < len) { + if (sameValue(array[i], searchElement)) { + return true; + } + i++; + } + return false; + }; + var isArray2 = Array.isArray || function(arg) { + return Object.prototype.toString.call(arg) === "[object Array]"; + }; + var DefinedDrivers = {}; + var DriverSupport = {}; + var DefaultDrivers = { + INDEXEDDB: asyncStorage, + WEBSQL: webSQLStorage, + LOCALSTORAGE: localStorageWrapper + }; + var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver]; + var OptionalDriverMethods = ["dropInstance"]; + var LibraryMethods = ["clear", "getItem", "iterate", "key", "keys", "length", "removeItem", "setItem"].concat(OptionalDriverMethods); + var DefaultConfig = { + description: "", + driver: DefaultDriverOrder.slice(), + name: "localforage", + size: 4980736, + storeName: "keyvaluepairs", + version: 1 + }; + function callWhenReady(localForageInstance, libraryMethod) { + localForageInstance[libraryMethod] = function() { + var _args = arguments; + return localForageInstance.ready().then(function() { + return localForageInstance[libraryMethod].apply(localForageInstance, _args); + }); + }; + } + function extend() { + for (var i = 1;i < arguments.length; i++) { + var arg = arguments[i]; + if (arg) { + for (var _key in arg) { + if (arg.hasOwnProperty(_key)) { + if (isArray2(arg[_key])) { + arguments[0][_key] = arg[_key].slice(); + } else { + arguments[0][_key] = arg[_key]; + } + } + } + } + } + return arguments[0]; + } + var LocalForage = function() { + function LocalForage2(options) { + _classCallCheck(this, LocalForage2); + for (var driverTypeKey in DefaultDrivers) { + if (DefaultDrivers.hasOwnProperty(driverTypeKey)) { + var driver = DefaultDrivers[driverTypeKey]; + var driverName = driver._driver; + this[driverTypeKey] = driverName; + if (!DefinedDrivers[driverName]) { + this.defineDriver(driver); + } + } + } + this._defaultConfig = extend({}, DefaultConfig); + this._config = extend({}, this._defaultConfig, options); + this._driverSet = null; + this._initDriver = null; + this._ready = false; + this._dbInfo = null; + this._wrapLibraryMethodsWithReady(); + this.setDriver(this._config.driver)["catch"](function() { + }); + } + LocalForage2.prototype.config = function config(options) { + if ((typeof options === "undefined" ? "undefined" : _typeof(options)) === "object") { + if (this._ready) { + return new Error("Can't call config() after localforage " + "has been used."); + } + for (var i in options) { + if (i === "storeName") { + options[i] = options[i].replace(/\W/g, "_"); + } + if (i === "version" && typeof options[i] !== "number") { + return new Error("Database version must be a number."); + } + this._config[i] = options[i]; + } + if ("driver" in options && options.driver) { + return this.setDriver(this._config.driver); + } + return true; + } else if (typeof options === "string") { + return this._config[options]; + } else { + return this._config; + } + }; + LocalForage2.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { + var promise = new Promise$1(function(resolve, reject2) { + try { + var driverName = driverObject._driver; + var complianceError = new Error("Custom driver not compliant; see " + "https://mozilla.github.io/localForage/#definedriver"); + if (!driverObject._driver) { + reject2(complianceError); + return; + } + var driverMethods = LibraryMethods.concat("_initStorage"); + for (var i = 0, len = driverMethods.length;i < len; i++) { + var driverMethodName = driverMethods[i]; + var isRequired = !includes(OptionalDriverMethods, driverMethodName); + if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== "function") { + reject2(complianceError); + return; + } + } + var configureMissingMethods = function configureMissingMethods() { + var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) { + return function() { + var error = new Error("Method " + methodName + " is not implemented by the current driver"); + var promise2 = Promise$1.reject(error); + executeCallback(promise2, arguments[arguments.length - 1]); + return promise2; + }; + }; + for (var _i = 0, _len = OptionalDriverMethods.length;_i < _len; _i++) { + var optionalDriverMethod = OptionalDriverMethods[_i]; + if (!driverObject[optionalDriverMethod]) { + driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod); + } + } + }; + configureMissingMethods(); + var setDriverSupport = function setDriverSupport(support) { + if (DefinedDrivers[driverName]) { + console.info("Redefining LocalForage driver: " + driverName); + } + DefinedDrivers[driverName] = driverObject; + DriverSupport[driverName] = support; + resolve(); + }; + if ("_support" in driverObject) { + if (driverObject._support && typeof driverObject._support === "function") { + driverObject._support().then(setDriverSupport, reject2); + } else { + setDriverSupport(!!driverObject._support); + } + } else { + setDriverSupport(true); + } + } catch (e) { + reject2(e); + } + }); + executeTwoCallbacks(promise, callback, errorCallback); + return promise; + }; + LocalForage2.prototype.driver = function driver() { + return this._driver || null; + }; + LocalForage2.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { + var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error("Driver not found.")); + executeTwoCallbacks(getDriverPromise, callback, errorCallback); + return getDriverPromise; + }; + LocalForage2.prototype.getSerializer = function getSerializer(callback) { + var serializerPromise = Promise$1.resolve(localforageSerializer); + executeTwoCallbacks(serializerPromise, callback); + return serializerPromise; + }; + LocalForage2.prototype.ready = function ready(callback) { + var self2 = this; + var promise = self2._driverSet.then(function() { + if (self2._ready === null) { + self2._ready = self2._initDriver(); + } + return self2._ready; + }); + executeTwoCallbacks(promise, callback, callback); + return promise; + }; + LocalForage2.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { + var self2 = this; + if (!isArray2(drivers)) { + drivers = [drivers]; + } + var supportedDrivers = this._getSupportedDrivers(drivers); + function setDriverToConfig() { + self2._config.driver = self2.driver(); + } + function extendSelfWithDriver(driver) { + self2._extend(driver); + setDriverToConfig(); + self2._ready = self2._initStorage(self2._config); + return self2._ready; + } + function initDriver(supportedDrivers2) { + return function() { + var currentDriverIndex = 0; + function driverPromiseLoop() { + while (currentDriverIndex < supportedDrivers2.length) { + var driverName = supportedDrivers2[currentDriverIndex]; + currentDriverIndex++; + self2._dbInfo = null; + self2._ready = null; + return self2.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop); + } + setDriverToConfig(); + var error = new Error("No available storage method found."); + self2._driverSet = Promise$1.reject(error); + return self2._driverSet; + } + return driverPromiseLoop(); + }; + } + var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function() { + return Promise$1.resolve(); + }) : Promise$1.resolve(); + this._driverSet = oldDriverSetDone.then(function() { + var driverName = supportedDrivers[0]; + self2._dbInfo = null; + self2._ready = null; + return self2.getDriver(driverName).then(function(driver) { + self2._driver = driver._driver; + setDriverToConfig(); + self2._wrapLibraryMethodsWithReady(); + self2._initDriver = initDriver(supportedDrivers); + }); + })["catch"](function() { + setDriverToConfig(); + var error = new Error("No available storage method found."); + self2._driverSet = Promise$1.reject(error); + return self2._driverSet; + }); + executeTwoCallbacks(this._driverSet, callback, errorCallback); + return this._driverSet; + }; + LocalForage2.prototype.supports = function supports(driverName) { + return !!DriverSupport[driverName]; + }; + LocalForage2.prototype._extend = function _extend(libraryMethodsAndProperties) { + extend(this, libraryMethodsAndProperties); + }; + LocalForage2.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { + var supportedDrivers = []; + for (var i = 0, len = drivers.length;i < len; i++) { + var driverName = drivers[i]; + if (this.supports(driverName)) { + supportedDrivers.push(driverName); + } + } + return supportedDrivers; + }; + LocalForage2.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { + for (var i = 0, len = LibraryMethods.length;i < len; i++) { + callWhenReady(this, LibraryMethods[i]); + } + }; + LocalForage2.prototype.createInstance = function createInstance(options) { + return new LocalForage2(options); + }; + return LocalForage2; + }(); + var localforage_js = new LocalForage; + module4.exports = localforage_js; + }, { "3": 3 }] }, {}, [4])(4); + }); +}); + +// node_modules/three/build/three.cjs +var require_three = __commonJS((exports2) => { + var REVISION2 = "173"; + var MOUSE2 = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; + var TOUCH2 = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; + var CullFaceNone2 = 0; + var CullFaceBack2 = 1; + var CullFaceFront2 = 2; + var CullFaceFrontBack2 = 3; + var BasicShadowMap2 = 0; + var PCFShadowMap2 = 1; + var PCFSoftShadowMap2 = 2; + var VSMShadowMap2 = 3; + var FrontSide2 = 0; + var BackSide2 = 1; + var DoubleSide2 = 2; + var NoBlending2 = 0; + var NormalBlending2 = 1; + var AdditiveBlending2 = 2; + var SubtractiveBlending2 = 3; + var MultiplyBlending2 = 4; + var CustomBlending2 = 5; + var AddEquation2 = 100; + var SubtractEquation2 = 101; + var ReverseSubtractEquation2 = 102; + var MinEquation2 = 103; + var MaxEquation2 = 104; + var ZeroFactor2 = 200; + var OneFactor2 = 201; + var SrcColorFactor2 = 202; + var OneMinusSrcColorFactor2 = 203; + var SrcAlphaFactor2 = 204; + var OneMinusSrcAlphaFactor2 = 205; + var DstAlphaFactor2 = 206; + var OneMinusDstAlphaFactor2 = 207; + var DstColorFactor2 = 208; + var OneMinusDstColorFactor2 = 209; + var SrcAlphaSaturateFactor2 = 210; + var ConstantColorFactor2 = 211; + var OneMinusConstantColorFactor2 = 212; + var ConstantAlphaFactor2 = 213; + var OneMinusConstantAlphaFactor2 = 214; + var NeverDepth2 = 0; + var AlwaysDepth2 = 1; + var LessDepth2 = 2; + var LessEqualDepth2 = 3; + var EqualDepth2 = 4; + var GreaterEqualDepth2 = 5; + var GreaterDepth2 = 6; + var NotEqualDepth2 = 7; + var MultiplyOperation2 = 0; + var MixOperation2 = 1; + var AddOperation2 = 2; + var NoToneMapping2 = 0; + var LinearToneMapping2 = 1; + var ReinhardToneMapping2 = 2; + var CineonToneMapping2 = 3; + var ACESFilmicToneMapping2 = 4; + var CustomToneMapping2 = 5; + var AgXToneMapping2 = 6; + var NeutralToneMapping2 = 7; + var AttachedBindMode2 = "attached"; + var DetachedBindMode2 = "detached"; + var UVMapping2 = 300; + var CubeReflectionMapping2 = 301; + var CubeRefractionMapping2 = 302; + var EquirectangularReflectionMapping2 = 303; + var EquirectangularRefractionMapping2 = 304; + var CubeUVReflectionMapping2 = 306; + var RepeatWrapping2 = 1000; + var ClampToEdgeWrapping2 = 1001; + var MirroredRepeatWrapping2 = 1002; + var NearestFilter2 = 1003; + var NearestMipmapNearestFilter2 = 1004; + var NearestMipMapNearestFilter2 = 1004; + var NearestMipmapLinearFilter2 = 1005; + var NearestMipMapLinearFilter2 = 1005; + var LinearFilter2 = 1006; + var LinearMipmapNearestFilter2 = 1007; + var LinearMipMapNearestFilter2 = 1007; + var LinearMipmapLinearFilter2 = 1008; + var LinearMipMapLinearFilter2 = 1008; + var UnsignedByteType2 = 1009; + var ByteType2 = 1010; + var ShortType2 = 1011; + var UnsignedShortType2 = 1012; + var IntType2 = 1013; + var UnsignedIntType2 = 1014; + var FloatType2 = 1015; + var HalfFloatType2 = 1016; + var UnsignedShort4444Type2 = 1017; + var UnsignedShort5551Type2 = 1018; + var UnsignedInt248Type2 = 1020; + var UnsignedInt5999Type2 = 35902; + var AlphaFormat2 = 1021; + var RGBFormat2 = 1022; + var RGBAFormat2 = 1023; + var LuminanceFormat2 = 1024; + var LuminanceAlphaFormat2 = 1025; + var DepthFormat2 = 1026; + var DepthStencilFormat2 = 1027; + var RedFormat2 = 1028; + var RedIntegerFormat2 = 1029; + var RGFormat2 = 1030; + var RGIntegerFormat2 = 1031; + var RGBIntegerFormat2 = 1032; + var RGBAIntegerFormat2 = 1033; + var RGB_S3TC_DXT1_Format2 = 33776; + var RGBA_S3TC_DXT1_Format2 = 33777; + var RGBA_S3TC_DXT3_Format2 = 33778; + var RGBA_S3TC_DXT5_Format2 = 33779; + var RGB_PVRTC_4BPPV1_Format2 = 35840; + var RGB_PVRTC_2BPPV1_Format2 = 35841; + var RGBA_PVRTC_4BPPV1_Format2 = 35842; + var RGBA_PVRTC_2BPPV1_Format2 = 35843; + var RGB_ETC1_Format2 = 36196; + var RGB_ETC2_Format2 = 37492; + var RGBA_ETC2_EAC_Format2 = 37496; + var RGBA_ASTC_4x4_Format2 = 37808; + var RGBA_ASTC_5x4_Format2 = 37809; + var RGBA_ASTC_5x5_Format2 = 37810; + var RGBA_ASTC_6x5_Format2 = 37811; + var RGBA_ASTC_6x6_Format2 = 37812; + var RGBA_ASTC_8x5_Format2 = 37813; + var RGBA_ASTC_8x6_Format2 = 37814; + var RGBA_ASTC_8x8_Format2 = 37815; + var RGBA_ASTC_10x5_Format2 = 37816; + var RGBA_ASTC_10x6_Format2 = 37817; + var RGBA_ASTC_10x8_Format2 = 37818; + var RGBA_ASTC_10x10_Format2 = 37819; + var RGBA_ASTC_12x10_Format2 = 37820; + var RGBA_ASTC_12x12_Format2 = 37821; + var RGBA_BPTC_Format2 = 36492; + var RGB_BPTC_SIGNED_Format2 = 36494; + var RGB_BPTC_UNSIGNED_Format2 = 36495; + var RED_RGTC1_Format2 = 36283; + var SIGNED_RED_RGTC1_Format2 = 36284; + var RED_GREEN_RGTC2_Format2 = 36285; + var SIGNED_RED_GREEN_RGTC2_Format2 = 36286; + var LoopOnce2 = 2200; + var LoopRepeat2 = 2201; + var LoopPingPong2 = 2202; + var InterpolateDiscrete2 = 2300; + var InterpolateLinear2 = 2301; + var InterpolateSmooth2 = 2302; + var ZeroCurvatureEnding2 = 2400; + var ZeroSlopeEnding2 = 2401; + var WrapAroundEnding2 = 2402; + var NormalAnimationBlendMode2 = 2500; + var AdditiveAnimationBlendMode2 = 2501; + var TrianglesDrawMode2 = 0; + var TriangleStripDrawMode2 = 1; + var TriangleFanDrawMode2 = 2; + var BasicDepthPacking2 = 3200; + var RGBADepthPacking2 = 3201; + var RGBDepthPacking2 = 3202; + var RGDepthPacking2 = 3203; + var TangentSpaceNormalMap2 = 0; + var ObjectSpaceNormalMap2 = 1; + var NoColorSpace2 = ""; + var SRGBColorSpace2 = "srgb"; + var LinearSRGBColorSpace2 = "srgb-linear"; + var LinearTransfer2 = "linear"; + var SRGBTransfer2 = "srgb"; + var ZeroStencilOp2 = 0; + var KeepStencilOp2 = 7680; + var ReplaceStencilOp2 = 7681; + var IncrementStencilOp2 = 7682; + var DecrementStencilOp2 = 7683; + var IncrementWrapStencilOp2 = 34055; + var DecrementWrapStencilOp2 = 34056; + var InvertStencilOp2 = 5386; + var NeverStencilFunc2 = 512; + var LessStencilFunc2 = 513; + var EqualStencilFunc2 = 514; + var LessEqualStencilFunc2 = 515; + var GreaterStencilFunc2 = 516; + var NotEqualStencilFunc2 = 517; + var GreaterEqualStencilFunc2 = 518; + var AlwaysStencilFunc2 = 519; + var NeverCompare2 = 512; + var LessCompare2 = 513; + var EqualCompare2 = 514; + var LessEqualCompare2 = 515; + var GreaterCompare2 = 516; + var NotEqualCompare2 = 517; + var GreaterEqualCompare2 = 518; + var AlwaysCompare2 = 519; + var StaticDrawUsage2 = 35044; + var DynamicDrawUsage2 = 35048; + var StreamDrawUsage2 = 35040; + var StaticReadUsage2 = 35045; + var DynamicReadUsage2 = 35049; + var StreamReadUsage2 = 35041; + var StaticCopyUsage2 = 35046; + var DynamicCopyUsage2 = 35050; + var StreamCopyUsage2 = 35042; + var GLSL12 = "100"; + var GLSL32 = "300 es"; + var WebGLCoordinateSystem2 = 2000; + var WebGPUCoordinateSystem2 = 2001; + var TimestampQuery2 = { + COMPUTE: "compute", + RENDER: "render" + }; + + class EventDispatcher2 { + addEventListener(type, listener) { + if (this._listeners === undefined) + this._listeners = {}; + const listeners = this._listeners; + if (listeners[type] === undefined) { + listeners[type] = []; + } + if (listeners[type].indexOf(listener) === -1) { + listeners[type].push(listener); + } + } + hasEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === undefined) + return false; + return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1; + } + removeEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === undefined) + return; + const listenerArray = listeners[type]; + if (listenerArray !== undefined) { + const index2 = listenerArray.indexOf(listener); + if (index2 !== -1) { + listenerArray.splice(index2, 1); + } + } + } + dispatchEvent(event) { + const listeners = this._listeners; + if (listeners === undefined) + return; + const listenerArray = listeners[event.type]; + if (listenerArray !== undefined) { + event.target = this; + const array = listenerArray.slice(0); + for (let i = 0, l2 = array.length;i < l2; i++) { + array[i].call(this, event); + } + event.target = null; + } + } + } + var _lut2 = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"]; + var _seed2 = 1234567; + var DEG2RAD2 = Math.PI / 180; + var RAD2DEG2 = 180 / Math.PI; + function generateUUID2() { + const d0 = Math.random() * 4294967295 | 0; + const d1 = Math.random() * 4294967295 | 0; + const d2 = Math.random() * 4294967295 | 0; + const d3 = Math.random() * 4294967295 | 0; + const uuid = _lut2[d0 & 255] + _lut2[d0 >> 8 & 255] + _lut2[d0 >> 16 & 255] + _lut2[d0 >> 24 & 255] + "-" + _lut2[d1 & 255] + _lut2[d1 >> 8 & 255] + "-" + _lut2[d1 >> 16 & 15 | 64] + _lut2[d1 >> 24 & 255] + "-" + _lut2[d2 & 63 | 128] + _lut2[d2 >> 8 & 255] + "-" + _lut2[d2 >> 16 & 255] + _lut2[d2 >> 24 & 255] + _lut2[d3 & 255] + _lut2[d3 >> 8 & 255] + _lut2[d3 >> 16 & 255] + _lut2[d3 >> 24 & 255]; + return uuid.toLowerCase(); + } + function clamp3(value2, min, max) { + return Math.max(min, Math.min(max, value2)); + } + function euclideanModulo2(n2, m) { + return (n2 % m + m) % m; + } + function mapLinear2(x2, a1, a2, b1, b2) { + return b1 + (x2 - a1) * (b2 - b1) / (a2 - a1); + } + function inverseLerp2(x2, y, value2) { + if (x2 !== y) { + return (value2 - x2) / (y - x2); + } else { + return 0; + } + } + function lerp2(x2, y, t3) { + return (1 - t3) * x2 + t3 * y; + } + function damp2(x2, y, lambda, dt) { + return lerp2(x2, y, 1 - Math.exp(-lambda * dt)); + } + function pingpong2(x2, length2 = 1) { + return length2 - Math.abs(euclideanModulo2(x2, length2 * 2) - length2); + } + function smoothstep2(x2, min, max) { + if (x2 <= min) + return 0; + if (x2 >= max) + return 1; + x2 = (x2 - min) / (max - min); + return x2 * x2 * (3 - 2 * x2); + } + function smootherstep2(x2, min, max) { + if (x2 <= min) + return 0; + if (x2 >= max) + return 1; + x2 = (x2 - min) / (max - min); + return x2 * x2 * x2 * (x2 * (x2 * 6 - 15) + 10); + } + function randInt2(low, high) { + return low + Math.floor(Math.random() * (high - low + 1)); + } + function randFloat2(low, high) { + return low + Math.random() * (high - low); + } + function randFloatSpread2(range) { + return range * (0.5 - Math.random()); + } + function seededRandom2(s) { + if (s !== undefined) + _seed2 = s; + let t3 = _seed2 += 1831565813; + t3 = Math.imul(t3 ^ t3 >>> 15, t3 | 1); + t3 ^= t3 + Math.imul(t3 ^ t3 >>> 7, t3 | 61); + return ((t3 ^ t3 >>> 14) >>> 0) / 4294967296; + } + function degToRad2(degrees) { + return degrees * DEG2RAD2; + } + function radToDeg2(radians) { + return radians * RAD2DEG2; + } + function isPowerOfTwo2(value2) { + return (value2 & value2 - 1) === 0 && value2 !== 0; + } + function ceilPowerOfTwo2(value2) { + return Math.pow(2, Math.ceil(Math.log(value2) / Math.LN2)); + } + function floorPowerOfTwo2(value2) { + return Math.pow(2, Math.floor(Math.log(value2) / Math.LN2)); + } + function setQuaternionFromProperEuler2(q2, a2, b2, c2, order) { + const cos = Math.cos; + const sin = Math.sin; + const c22 = cos(b2 / 2); + const s2 = sin(b2 / 2); + const c13 = cos((a2 + c2) / 2); + const s13 = sin((a2 + c2) / 2); + const c1_3 = cos((a2 - c2) / 2); + const s1_3 = sin((a2 - c2) / 2); + const c3_1 = cos((c2 - a2) / 2); + const s3_1 = sin((c2 - a2) / 2); + switch (order) { + case "XYX": + q2.set(c22 * s13, s2 * c1_3, s2 * s1_3, c22 * c13); + break; + case "YZY": + q2.set(s2 * s1_3, c22 * s13, s2 * c1_3, c22 * c13); + break; + case "ZXZ": + q2.set(s2 * c1_3, s2 * s1_3, c22 * s13, c22 * c13); + break; + case "XZX": + q2.set(c22 * s13, s2 * s3_1, s2 * c3_1, c22 * c13); + break; + case "YXY": + q2.set(s2 * c3_1, c22 * s13, s2 * s3_1, c22 * c13); + break; + case "ZYZ": + q2.set(s2 * s3_1, s2 * c3_1, c22 * s13, c22 * c13); + break; + default: + console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + order); + } + } + function denormalize2(value2, array) { + switch (array.constructor) { + case Float32Array: + return value2; + case Uint32Array: + return value2 / 4294967295; + case Uint16Array: + return value2 / 65535; + case Uint8Array: + return value2 / 255; + case Int32Array: + return Math.max(value2 / 2147483647, -1); + case Int16Array: + return Math.max(value2 / 32767, -1); + case Int8Array: + return Math.max(value2 / 127, -1); + default: + throw new Error("Invalid component type."); + } + } + function normalize3(value2, array) { + switch (array.constructor) { + case Float32Array: + return value2; + case Uint32Array: + return Math.round(value2 * 4294967295); + case Uint16Array: + return Math.round(value2 * 65535); + case Uint8Array: + return Math.round(value2 * 255); + case Int32Array: + return Math.round(value2 * 2147483647); + case Int16Array: + return Math.round(value2 * 32767); + case Int8Array: + return Math.round(value2 * 127); + default: + throw new Error("Invalid component type."); + } + } + var MathUtils2 = { + DEG2RAD: DEG2RAD2, + RAD2DEG: RAD2DEG2, + generateUUID: generateUUID2, + clamp: clamp3, + euclideanModulo: euclideanModulo2, + mapLinear: mapLinear2, + inverseLerp: inverseLerp2, + lerp: lerp2, + damp: damp2, + pingpong: pingpong2, + smoothstep: smoothstep2, + smootherstep: smootherstep2, + randInt: randInt2, + randFloat: randFloat2, + randFloatSpread: randFloatSpread2, + seededRandom: seededRandom2, + degToRad: degToRad2, + radToDeg: radToDeg2, + isPowerOfTwo: isPowerOfTwo2, + ceilPowerOfTwo: ceilPowerOfTwo2, + floorPowerOfTwo: floorPowerOfTwo2, + setQuaternionFromProperEuler: setQuaternionFromProperEuler2, + normalize: normalize3, + denormalize: denormalize2 + }; + + class Vector22 { + constructor(x2 = 0, y = 0) { + Vector22.prototype.isVector2 = true; + this.x = x2; + this.y = y; + } + get width() { + return this.x; + } + set width(value2) { + this.x = value2; + } + get height() { + return this.y; + } + set height(value2) { + this.y = value2; + } + set(x2, y) { + this.x = x2; + this.y = y; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + return this; + } + setX(x2) { + this.x = x2; + return this; + } + setY(y) { + this.y = y; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y); + } + copy(v) { + this.x = v.x; + this.y = v.y; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + return this; + } + addVectors(a2, b2) { + this.x = a2.x + b2.x; + this.y = a2.y + b2.y; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + return this; + } + subVectors(a2, b2) { + this.x = a2.x - b2.x; + this.y = a2.y - b2.y; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + applyMatrix3(m) { + const x2 = this.x, y = this.y; + const e = m.elements; + this.x = e[0] * x2 + e[3] * y + e[6]; + this.y = e[1] * x2 + e[4] * y + e[7]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + return this; + } + clamp(min, max) { + this.x = clamp3(this.x, min.x, max.x); + this.y = clamp3(this.y, min.y, max.y); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp3(this.x, minVal, maxVal); + this.y = clamp3(this.y, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp3(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y; + } + cross(v) { + return this.x * v.y - this.y * v.x; + } + lengthSq() { + return this.x * this.x + this.y * this.y; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + angle() { + const angle = Math.atan2(-this.y, -this.x) + Math.PI; + return angle; + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) + return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp3(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + return this; + } + lerpVectors(v12, v2, alpha) { + this.x = v12.x + (v2.x - v12.x) * alpha; + this.y = v12.y + (v2.y - v12.y) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + return this; + } + rotateAround(center, angle) { + const c2 = Math.cos(angle), s = Math.sin(angle); + const x2 = this.x - center.x; + const y = this.y - center.y; + this.x = x2 * c2 - y * s + center.x; + this.y = x2 * s + y * c2 + center.y; + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + } + } + + class Matrix32 { + constructor(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + Matrix32.prototype.isMatrix3 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n13, n21, n22, n23, n31, n32, n33); + } + } + set(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + const te3 = this.elements; + te3[0] = n11; + te3[1] = n21; + te3[2] = n31; + te3[3] = n12; + te3[4] = n22; + te3[5] = n32; + te3[6] = n13; + te3[7] = n23; + te3[8] = n33; + return this; + } + identity() { + this.set(1, 0, 0, 0, 1, 0, 0, 0, 1); + return this; + } + copy(m) { + const te3 = this.elements; + const me = m.elements; + te3[0] = me[0]; + te3[1] = me[1]; + te3[2] = me[2]; + te3[3] = me[3]; + te3[4] = me[4]; + te3[5] = me[5]; + te3[6] = me[6]; + te3[7] = me[7]; + te3[8] = me[8]; + return this; + } + extractBasis(xAxis2, yAxis2, zAxis2) { + xAxis2.setFromMatrix3Column(this, 0); + yAxis2.setFromMatrix3Column(this, 1); + zAxis2.setFromMatrix3Column(this, 2); + return this; + } + setFromMatrix4(m) { + const me = m.elements; + this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]); + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a2, b2) { + const ae3 = a2.elements; + const be = b2.elements; + const te3 = this.elements; + const a11 = ae3[0], a12 = ae3[3], a13 = ae3[6]; + const a21 = ae3[1], a22 = ae3[4], a23 = ae3[7]; + const a31 = ae3[2], a32 = ae3[5], a33 = ae3[8]; + const b11 = be[0], b12 = be[3], b13 = be[6]; + const b21 = be[1], b22 = be[4], b23 = be[7]; + const b31 = be[2], b32 = be[5], b33 = be[8]; + te3[0] = a11 * b11 + a12 * b21 + a13 * b31; + te3[3] = a11 * b12 + a12 * b22 + a13 * b32; + te3[6] = a11 * b13 + a12 * b23 + a13 * b33; + te3[1] = a21 * b11 + a22 * b21 + a23 * b31; + te3[4] = a21 * b12 + a22 * b22 + a23 * b32; + te3[7] = a21 * b13 + a22 * b23 + a23 * b33; + te3[2] = a31 * b11 + a32 * b21 + a33 * b31; + te3[5] = a31 * b12 + a32 * b22 + a33 * b32; + te3[8] = a31 * b13 + a32 * b23 + a33 * b33; + return this; + } + multiplyScalar(s) { + const te3 = this.elements; + te3[0] *= s; + te3[3] *= s; + te3[6] *= s; + te3[1] *= s; + te3[4] *= s; + te3[7] *= s; + te3[2] *= s; + te3[5] *= s; + te3[8] *= s; + return this; + } + determinant() { + const te3 = this.elements; + const a2 = te3[0], b2 = te3[1], c2 = te3[2], d = te3[3], e = te3[4], f = te3[5], g3 = te3[6], h = te3[7], i = te3[8]; + return a2 * e * i - a2 * f * h - b2 * d * i + b2 * f * g3 + c2 * d * h - c2 * e * g3; + } + invert() { + const te3 = this.elements, n11 = te3[0], n21 = te3[1], n31 = te3[2], n12 = te3[3], n22 = te3[4], n32 = te3[5], n13 = te3[6], n23 = te3[7], n33 = te3[8], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13; + if (det === 0) + return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te3[0] = t11 * detInv; + te3[1] = (n31 * n23 - n33 * n21) * detInv; + te3[2] = (n32 * n21 - n31 * n22) * detInv; + te3[3] = t12 * detInv; + te3[4] = (n33 * n11 - n31 * n13) * detInv; + te3[5] = (n31 * n12 - n32 * n11) * detInv; + te3[6] = t13 * detInv; + te3[7] = (n21 * n13 - n23 * n11) * detInv; + te3[8] = (n22 * n11 - n21 * n12) * detInv; + return this; + } + transpose() { + let tmp3; + const m = this.elements; + tmp3 = m[1]; + m[1] = m[3]; + m[3] = tmp3; + tmp3 = m[2]; + m[2] = m[6]; + m[6] = tmp3; + tmp3 = m[5]; + m[5] = m[7]; + m[7] = tmp3; + return this; + } + getNormalMatrix(matrix4) { + return this.setFromMatrix4(matrix4).invert().transpose(); + } + transposeIntoArray(r) { + const m = this.elements; + r[0] = m[0]; + r[1] = m[3]; + r[2] = m[6]; + r[3] = m[1]; + r[4] = m[4]; + r[5] = m[7]; + r[6] = m[2]; + r[7] = m[5]; + r[8] = m[8]; + return this; + } + setUvTransform(tx, ty, sx, sy, rotation2, cx, cy) { + const c2 = Math.cos(rotation2); + const s = Math.sin(rotation2); + this.set(sx * c2, sx * s, -sx * (c2 * cx + s * cy) + cx + tx, -sy * s, sy * c2, -sy * (-s * cx + c2 * cy) + cy + ty, 0, 0, 1); + return this; + } + scale(sx, sy) { + this.premultiply(_m32.makeScale(sx, sy)); + return this; + } + rotate(theta) { + this.premultiply(_m32.makeRotation(-theta)); + return this; + } + translate(tx, ty) { + this.premultiply(_m32.makeTranslation(tx, ty)); + return this; + } + makeTranslation(x2, y) { + if (x2.isVector2) { + this.set(1, 0, x2.x, 0, 1, x2.y, 0, 0, 1); + } else { + this.set(1, 0, x2, 0, 1, y, 0, 0, 1); + } + return this; + } + makeRotation(theta) { + const c2 = Math.cos(theta); + const s = Math.sin(theta); + this.set(c2, -s, 0, s, c2, 0, 0, 0, 1); + return this; + } + makeScale(x2, y) { + this.set(x2, 0, 0, 0, y, 0, 0, 0, 1); + return this; + } + equals(matrix3) { + const te3 = this.elements; + const me = matrix3.elements; + for (let i = 0;i < 9; i++) { + if (te3[i] !== me[i]) + return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 9; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te3 = this.elements; + array[offset] = te3[0]; + array[offset + 1] = te3[1]; + array[offset + 2] = te3[2]; + array[offset + 3] = te3[3]; + array[offset + 4] = te3[4]; + array[offset + 5] = te3[5]; + array[offset + 6] = te3[6]; + array[offset + 7] = te3[7]; + array[offset + 8] = te3[8]; + return array; + } + clone() { + return new this.constructor().fromArray(this.elements); + } + } + var _m32 = /* @__PURE__ */ new Matrix32; + function arrayNeedsUint322(array) { + for (let i = array.length - 1;i >= 0; --i) { + if (array[i] >= 65535) + return true; + } + return false; + } + var TYPED_ARRAYS2 = { + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array + }; + function getTypedArray2(type, buffer) { + return new TYPED_ARRAYS2[type](buffer); + } + function createElementNS2(name2) { + return document.createElementNS("http://www.w3.org/1999/xhtml", name2); + } + function createCanvasElement2() { + const canvas = createElementNS2("canvas"); + canvas.style.display = "block"; + return canvas; + } + var _cache2 = {}; + function warnOnce2(message) { + if (message in _cache2) + return; + _cache2[message] = true; + console.warn(message); + } + function probeAsync2(gl, sync, interval) { + return new Promise(function(resolve, reject2) { + function probe() { + switch (gl.clientWaitSync(sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0)) { + case gl.WAIT_FAILED: + reject2(); + break; + case gl.TIMEOUT_EXPIRED: + setTimeout(probe, interval); + break; + default: + resolve(); + } + } + setTimeout(probe, interval); + }); + } + function toNormalizedProjectionMatrix2(projectionMatrix) { + const m = projectionMatrix.elements; + m[2] = 0.5 * m[2] + 0.5 * m[3]; + m[6] = 0.5 * m[6] + 0.5 * m[7]; + m[10] = 0.5 * m[10] + 0.5 * m[11]; + m[14] = 0.5 * m[14] + 0.5 * m[15]; + } + function toReversedProjectionMatrix2(projectionMatrix) { + const m = projectionMatrix.elements; + const isPerspectiveMatrix = m[11] === -1; + if (isPerspectiveMatrix) { + m[10] = -m[10] - 1; + m[14] = -m[14]; + } else { + m[10] = -m[10]; + m[14] = -m[14] + 1; + } + } + var LINEAR_REC709_TO_XYZ2 = /* @__PURE__ */ new Matrix32().set(0.4123908, 0.3575843, 0.1804808, 0.212639, 0.7151687, 0.0721923, 0.0193308, 0.1191948, 0.9505322); + var XYZ_TO_LINEAR_REC7092 = /* @__PURE__ */ new Matrix32().set(3.2409699, -1.5373832, -0.4986108, -0.9692436, 1.8759675, 0.0415551, 0.0556301, -0.203977, 1.0569715); + function createColorManagement2() { + const ColorManagement3 = { + enabled: true, + workingColorSpace: LinearSRGBColorSpace2, + spaces: {}, + convert: function(color, sourceColorSpace, targetColorSpace) { + if (this.enabled === false || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) { + return color; + } + if (this.spaces[sourceColorSpace].transfer === SRGBTransfer2) { + color.r = SRGBToLinear2(color.r); + color.g = SRGBToLinear2(color.g); + color.b = SRGBToLinear2(color.b); + } + if (this.spaces[sourceColorSpace].primaries !== this.spaces[targetColorSpace].primaries) { + color.applyMatrix3(this.spaces[sourceColorSpace].toXYZ); + color.applyMatrix3(this.spaces[targetColorSpace].fromXYZ); + } + if (this.spaces[targetColorSpace].transfer === SRGBTransfer2) { + color.r = LinearToSRGB2(color.r); + color.g = LinearToSRGB2(color.g); + color.b = LinearToSRGB2(color.b); + } + return color; + }, + fromWorkingColorSpace: function(color, targetColorSpace) { + return this.convert(color, this.workingColorSpace, targetColorSpace); + }, + toWorkingColorSpace: function(color, sourceColorSpace) { + return this.convert(color, sourceColorSpace, this.workingColorSpace); + }, + getPrimaries: function(colorSpace) { + return this.spaces[colorSpace].primaries; + }, + getTransfer: function(colorSpace) { + if (colorSpace === NoColorSpace2) + return LinearTransfer2; + return this.spaces[colorSpace].transfer; + }, + getLuminanceCoefficients: function(target, colorSpace = this.workingColorSpace) { + return target.fromArray(this.spaces[colorSpace].luminanceCoefficients); + }, + define: function(colorSpaces) { + Object.assign(this.spaces, colorSpaces); + }, + _getMatrix: function(targetMatrix, sourceColorSpace, targetColorSpace) { + return targetMatrix.copy(this.spaces[sourceColorSpace].toXYZ).multiply(this.spaces[targetColorSpace].fromXYZ); + }, + _getDrawingBufferColorSpace: function(colorSpace) { + return this.spaces[colorSpace].outputColorSpaceConfig.drawingBufferColorSpace; + }, + _getUnpackColorSpace: function(colorSpace = this.workingColorSpace) { + return this.spaces[colorSpace].workingColorSpaceConfig.unpackColorSpace; + } + }; + const REC709_PRIMARIES = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06]; + const REC709_LUMINANCE_COEFFICIENTS = [0.2126, 0.7152, 0.0722]; + const D65 = [0.3127, 0.329]; + ColorManagement3.define({ + [LinearSRGBColorSpace2]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: LinearTransfer2, + toXYZ: LINEAR_REC709_TO_XYZ2, + fromXYZ: XYZ_TO_LINEAR_REC7092, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace2 }, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace2 } + }, + [SRGBColorSpace2]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: SRGBTransfer2, + toXYZ: LINEAR_REC709_TO_XYZ2, + fromXYZ: XYZ_TO_LINEAR_REC7092, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace2 } + } + }); + return ColorManagement3; + } + var ColorManagement2 = /* @__PURE__ */ createColorManagement2(); + function SRGBToLinear2(c2) { + return c2 < 0.04045 ? c2 * 0.0773993808 : Math.pow(c2 * 0.9478672986 + 0.0521327014, 2.4); + } + function LinearToSRGB2(c2) { + return c2 < 0.0031308 ? c2 * 12.92 : 1.055 * Math.pow(c2, 0.41666) - 0.055; + } + var _canvas2; + + class ImageUtils2 { + static getDataURL(image) { + if (/^data:/i.test(image.src)) { + return image.src; + } + if (typeof HTMLCanvasElement === "undefined") { + return image.src; + } + let canvas; + if (image instanceof HTMLCanvasElement) { + canvas = image; + } else { + if (_canvas2 === undefined) + _canvas2 = createElementNS2("canvas"); + _canvas2.width = image.width; + _canvas2.height = image.height; + const context = _canvas2.getContext("2d"); + if (image instanceof ImageData) { + context.putImageData(image, 0, 0); + } else { + context.drawImage(image, 0, 0, image.width, image.height); + } + canvas = _canvas2; + } + return canvas.toDataURL("image/png"); + } + static sRGBToLinear(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + const canvas = createElementNS2("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, image.width, image.height); + const imageData = context.getImageData(0, 0, image.width, image.height); + const data2 = imageData.data; + for (let i = 0;i < data2.length; i++) { + data2[i] = SRGBToLinear2(data2[i] / 255) * 255; + } + context.putImageData(imageData, 0, 0); + return canvas; + } else if (image.data) { + const data2 = image.data.slice(0); + for (let i = 0;i < data2.length; i++) { + if (data2 instanceof Uint8Array || data2 instanceof Uint8ClampedArray) { + data2[i] = Math.floor(SRGBToLinear2(data2[i] / 255) * 255); + } else { + data2[i] = SRGBToLinear2(data2[i]); + } + } + return { + data: data2, + width: image.width, + height: image.height + }; + } else { + console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."); + return image; + } + } + } + var _sourceId2 = 0; + + class Source2 { + constructor(data2 = null) { + this.isSource = true; + Object.defineProperty(this, "id", { value: _sourceId2++ }); + this.uuid = generateUUID2(); + this.data = data2; + this.dataReady = true; + this.version = 0; + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + toJSON(meta2) { + const isRootObject = meta2 === undefined || typeof meta2 === "string"; + if (!isRootObject && meta2.images[this.uuid] !== undefined) { + return meta2.images[this.uuid]; + } + const output = { + uuid: this.uuid, + url: "" + }; + const data2 = this.data; + if (data2 !== null) { + let url; + if (Array.isArray(data2)) { + url = []; + for (let i = 0, l2 = data2.length;i < l2; i++) { + if (data2[i].isDataTexture) { + url.push(serializeImage2(data2[i].image)); + } else { + url.push(serializeImage2(data2[i])); + } + } + } else { + url = serializeImage2(data2); + } + output.url = url; + } + if (!isRootObject) { + meta2.images[this.uuid] = output; + } + return output; + } + } + function serializeImage2(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + return ImageUtils2.getDataURL(image); + } else { + if (image.data) { + return { + data: Array.from(image.data), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; + } else { + console.warn("THREE.Texture: Unable to serialize Texture."); + return {}; + } + } + } + var _textureId2 = 0; + + class Texture2 extends EventDispatcher2 { + constructor(image = Texture2.DEFAULT_IMAGE, mapping = Texture2.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping2, wrapT = ClampToEdgeWrapping2, magFilter = LinearFilter2, minFilter = LinearMipmapLinearFilter2, format = RGBAFormat2, type = UnsignedByteType2, anisotropy = Texture2.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace2) { + super(); + this.isTexture = true; + Object.defineProperty(this, "id", { value: _textureId2++ }); + this.uuid = generateUUID2(); + this.name = ""; + this.source = new Source2(image); + this.mipmaps = []; + this.mapping = mapping; + this.channel = 0; + this.wrapS = wrapS; + this.wrapT = wrapT; + this.magFilter = magFilter; + this.minFilter = minFilter; + this.anisotropy = anisotropy; + this.format = format; + this.internalFormat = null; + this.type = type; + this.offset = new Vector22(0, 0); + this.repeat = new Vector22(1, 1); + this.center = new Vector22(0, 0); + this.rotation = 0; + this.matrixAutoUpdate = true; + this.matrix = new Matrix32; + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; + this.colorSpace = colorSpace; + this.userData = {}; + this.version = 0; + this.onUpdate = null; + this.renderTarget = null; + this.isRenderTargetTexture = false; + this.pmremVersion = 0; + } + get image() { + return this.source.data; + } + set image(value2 = null) { + this.source.data = value2; + } + updateMatrix() { + this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.source = source.source; + this.mipmaps = source.mipmaps.slice(0); + this.mapping = source.mapping; + this.channel = source.channel; + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + this.anisotropy = source.anisotropy; + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + this.offset.copy(source.offset); + this.repeat.copy(source.repeat); + this.center.copy(source.center); + this.rotation = source.rotation; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy(source.matrix); + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.colorSpace = source.colorSpace; + this.renderTarget = source.renderTarget; + this.isRenderTargetTexture = source.isRenderTargetTexture; + this.userData = JSON.parse(JSON.stringify(source.userData)); + this.needsUpdate = true; + return this; + } + toJSON(meta2) { + const isRootObject = meta2 === undefined || typeof meta2 === "string"; + if (!isRootObject && meta2.textures[this.uuid] !== undefined) { + return meta2.textures[this.uuid]; + } + const output = { + metadata: { + version: 4.6, + type: "Texture", + generator: "Texture.toJSON" + }, + uuid: this.uuid, + name: this.name, + image: this.source.toJSON(meta2).uuid, + mapping: this.mapping, + channel: this.channel, + repeat: [this.repeat.x, this.repeat.y], + offset: [this.offset.x, this.offset.y], + center: [this.center.x, this.center.y], + rotation: this.rotation, + wrap: [this.wrapS, this.wrapT], + format: this.format, + internalFormat: this.internalFormat, + type: this.type, + colorSpace: this.colorSpace, + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + flipY: this.flipY, + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + }; + if (Object.keys(this.userData).length > 0) + output.userData = this.userData; + if (!isRootObject) { + meta2.textures[this.uuid] = output; + } + return output; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + transformUv(uv) { + if (this.mapping !== UVMapping2) + return uv; + uv.applyMatrix3(this.matrix); + if (uv.x < 0 || uv.x > 1) { + switch (this.wrapS) { + case RepeatWrapping2: + uv.x = uv.x - Math.floor(uv.x); + break; + case ClampToEdgeWrapping2: + uv.x = uv.x < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping2: + if (Math.abs(Math.floor(uv.x) % 2) === 1) { + uv.x = Math.ceil(uv.x) - uv.x; + } else { + uv.x = uv.x - Math.floor(uv.x); + } + break; + } + } + if (uv.y < 0 || uv.y > 1) { + switch (this.wrapT) { + case RepeatWrapping2: + uv.y = uv.y - Math.floor(uv.y); + break; + case ClampToEdgeWrapping2: + uv.y = uv.y < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping2: + if (Math.abs(Math.floor(uv.y) % 2) === 1) { + uv.y = Math.ceil(uv.y) - uv.y; + } else { + uv.y = uv.y - Math.floor(uv.y); + } + break; + } + } + if (this.flipY) { + uv.y = 1 - uv.y; + } + return uv; + } + set needsUpdate(value2) { + if (value2 === true) { + this.version++; + this.source.needsUpdate = true; + } + } + set needsPMREMUpdate(value2) { + if (value2 === true) { + this.pmremVersion++; + } + } + } + Texture2.DEFAULT_IMAGE = null; + Texture2.DEFAULT_MAPPING = UVMapping2; + Texture2.DEFAULT_ANISOTROPY = 1; + + class Vector42 { + constructor(x2 = 0, y = 0, z = 0, w = 1) { + Vector42.prototype.isVector4 = true; + this.x = x2; + this.y = y; + this.z = z; + this.w = w; + } + get width() { + return this.z; + } + set width(value2) { + this.z = value2; + } + get height() { + return this.w; + } + set height(value2) { + this.w = value2; + } + set(x2, y, z, w) { + this.x = x2; + this.y = y; + this.z = z; + this.w = w; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + return this; + } + setX(x2) { + this.x = x2; + return this; + } + setY(y) { + this.y = y; + return this; + } + setZ(z) { + this.z = z; + return this; + } + setW(w) { + this.w = w; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + case 2: + this.z = value2; + break; + case 3: + this.w = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + case 3: + return this.w; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z, this.w); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = v.w !== undefined ? v.w : 1; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + this.w += s; + return this; + } + addVectors(a2, b2) { + this.x = a2.x + b2.x; + this.y = a2.y + b2.y; + this.z = a2.z + b2.z; + this.w = a2.w + b2.w; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; + return this; + } + subVectors(a2, b2) { + this.x = a2.x - b2.x; + this.y = a2.y - b2.y; + this.z = a2.z - b2.z; + this.w = a2.w - b2.w; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + return this; + } + applyMatrix4(m) { + const x2 = this.x, y = this.y, z = this.z, w = this.w; + const e = m.elements; + this.x = e[0] * x2 + e[4] * y + e[8] * z + e[12] * w; + this.y = e[1] * x2 + e[5] * y + e[9] * z + e[13] * w; + this.z = e[2] * x2 + e[6] * y + e[10] * z + e[14] * w; + this.w = e[3] * x2 + e[7] * y + e[11] * z + e[15] * w; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + this.w /= v.w; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + setAxisAngleFromQuaternion(q2) { + this.w = 2 * Math.acos(q2.w); + const s = Math.sqrt(1 - q2.w * q2.w); + if (s < 0.0001) { + this.x = 1; + this.y = 0; + this.z = 0; + } else { + this.x = q2.x / s; + this.y = q2.y / s; + this.z = q2.z / s; + } + return this; + } + setAxisAngleFromRotationMatrix(m) { + let angle, x2, y, z; + const epsilon = 0.01, epsilon2 = 0.1, te3 = m.elements, m11 = te3[0], m12 = te3[4], m13 = te3[8], m21 = te3[1], m22 = te3[5], m23 = te3[9], m31 = te3[2], m32 = te3[6], m33 = te3[10]; + if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) { + if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) { + this.set(1, 0, 0, 0); + return this; + } + angle = Math.PI; + const xx = (m11 + 1) / 2; + const yy = (m22 + 1) / 2; + const zz = (m33 + 1) / 2; + const xy = (m12 + m21) / 4; + const xz = (m13 + m31) / 4; + const yz = (m23 + m32) / 4; + if (xx > yy && xx > zz) { + if (xx < epsilon) { + x2 = 0; + y = 0.707106781; + z = 0.707106781; + } else { + x2 = Math.sqrt(xx); + y = xy / x2; + z = xz / x2; + } + } else if (yy > zz) { + if (yy < epsilon) { + x2 = 0.707106781; + y = 0; + z = 0.707106781; + } else { + y = Math.sqrt(yy); + x2 = xy / y; + z = yz / y; + } + } else { + if (zz < epsilon) { + x2 = 0.707106781; + y = 0.707106781; + z = 0; + } else { + z = Math.sqrt(zz); + x2 = xz / z; + y = yz / z; + } + } + this.set(x2, y, z, angle); + return this; + } + let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); + if (Math.abs(s) < 0.001) + s = 1; + this.x = (m32 - m23) / s; + this.y = (m13 - m31) / s; + this.z = (m21 - m12) / s; + this.w = Math.acos((m11 + m22 + m33 - 1) / 2); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + this.w = e[15]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + this.w = Math.min(this.w, v.w); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + this.w = Math.max(this.w, v.w); + return this; + } + clamp(min, max) { + this.x = clamp3(this.x, min.x, max.x); + this.y = clamp3(this.y, min.y, max.y); + this.z = clamp3(this.z, min.z, max.z); + this.w = clamp3(this.w, min.w, max.w); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp3(this.x, minVal, maxVal); + this.y = clamp3(this.y, minVal, maxVal); + this.z = clamp3(this.z, minVal, maxVal); + this.w = clamp3(this.w, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp3(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + this.w = Math.floor(this.w); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + this.w = Math.ceil(this.w); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + this.w = Math.round(this.w); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + this.w = Math.trunc(this.w); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + this.w += (v.w - this.w) * alpha; + return this; + } + lerpVectors(v12, v2, alpha) { + this.x = v12.x + (v2.x - v12.x) * alpha; + this.y = v12.y + (v2.y - v12.y) * alpha; + this.z = v12.z + (v2.z - v12.z) * alpha; + this.w = v12.w + (v2.w - v12.w) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + this.w = array[offset + 3]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + array[offset + 3] = this.w; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + this.z = attribute.getZ(index2); + this.w = attribute.getW(index2); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + yield this.w; + } + } + + class RenderTarget2 extends EventDispatcher2 { + constructor(width2 = 1, height2 = 1, options = {}) { + super(); + this.isRenderTarget = true; + this.width = width2; + this.height = height2; + this.depth = 1; + this.scissor = new Vector42(0, 0, width2, height2); + this.scissorTest = false; + this.viewport = new Vector42(0, 0, width2, height2); + const image = { width: width2, height: height2, depth: 1 }; + options = Object.assign({ + generateMipmaps: false, + internalFormat: null, + minFilter: LinearFilter2, + depthBuffer: true, + stencilBuffer: false, + resolveDepthBuffer: true, + resolveStencilBuffer: true, + depthTexture: null, + samples: 0, + count: 1 + }, options); + const texture = new Texture2(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + texture.flipY = false; + texture.generateMipmaps = options.generateMipmaps; + texture.internalFormat = options.internalFormat; + this.textures = []; + const count = options.count; + for (let i = 0;i < count; i++) { + this.textures[i] = texture.clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + } + this.depthBuffer = options.depthBuffer; + this.stencilBuffer = options.stencilBuffer; + this.resolveDepthBuffer = options.resolveDepthBuffer; + this.resolveStencilBuffer = options.resolveStencilBuffer; + this._depthTexture = null; + this.depthTexture = options.depthTexture; + this.samples = options.samples; + } + get texture() { + return this.textures[0]; + } + set texture(value2) { + this.textures[0] = value2; + } + set depthTexture(current) { + if (this._depthTexture !== null) + this._depthTexture.renderTarget = null; + if (current !== null) + current.renderTarget = this; + this._depthTexture = current; + } + get depthTexture() { + return this._depthTexture; + } + setSize(width2, height2, depth = 1) { + if (this.width !== width2 || this.height !== height2 || this.depth !== depth) { + this.width = width2; + this.height = height2; + this.depth = depth; + for (let i = 0, il = this.textures.length;i < il; i++) { + this.textures[i].image.width = width2; + this.textures[i].image.height = height2; + this.textures[i].image.depth = depth; + } + this.dispose(); + } + this.viewport.set(0, 0, width2, height2); + this.scissor.set(0, 0, width2, height2); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + this.scissor.copy(source.scissor); + this.scissorTest = source.scissorTest; + this.viewport.copy(source.viewport); + this.textures.length = 0; + for (let i = 0, il = source.textures.length;i < il; i++) { + this.textures[i] = source.textures[i].clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + } + const image = Object.assign({}, source.texture.image); + this.texture.source = new Source2(image); + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.resolveDepthBuffer = source.resolveDepthBuffer; + this.resolveStencilBuffer = source.resolveStencilBuffer; + if (source.depthTexture !== null) + this.depthTexture = source.depthTexture.clone(); + this.samples = source.samples; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + } + + class WebGLRenderTarget2 extends RenderTarget2 { + constructor(width2 = 1, height2 = 1, options = {}) { + super(width2, height2, options); + this.isWebGLRenderTarget = true; + } + } + + class DataArrayTexture2 extends Texture2 { + constructor(data2 = null, width2 = 1, height2 = 1, depth = 1) { + super(null); + this.isDataArrayTexture = true; + this.image = { data: data2, width: width2, height: height2, depth }; + this.magFilter = NearestFilter2; + this.minFilter = NearestFilter2; + this.wrapR = ClampToEdgeWrapping2; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + this.layerUpdates = new Set; + } + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + clearLayerUpdates() { + this.layerUpdates.clear(); + } + } + + class WebGLArrayRenderTarget2 extends WebGLRenderTarget2 { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isWebGLArrayRenderTarget = true; + this.depth = depth; + this.texture = new DataArrayTexture2(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } + } + + class Data3DTexture2 extends Texture2 { + constructor(data2 = null, width2 = 1, height2 = 1, depth = 1) { + super(null); + this.isData3DTexture = true; + this.image = { data: data2, width: width2, height: height2, depth }; + this.magFilter = NearestFilter2; + this.minFilter = NearestFilter2; + this.wrapR = ClampToEdgeWrapping2; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } + } + + class WebGL3DRenderTarget2 extends WebGLRenderTarget2 { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isWebGL3DRenderTarget = true; + this.depth = depth; + this.texture = new Data3DTexture2(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } + } + + class Quaternion2 { + constructor(x2 = 0, y = 0, z = 0, w = 1) { + this.isQuaternion = true; + this._x = x2; + this._y = y; + this._z = z; + this._w = w; + } + static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t3) { + let x0 = src0[srcOffset0 + 0], y0 = src0[srcOffset0 + 1], z0 = src0[srcOffset0 + 2], w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1 + 0], y1 = src1[srcOffset1 + 1], z1 = src1[srcOffset1 + 2], w1 = src1[srcOffset1 + 3]; + if (t3 === 0) { + dst[dstOffset + 0] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + return; + } + if (t3 === 1) { + dst[dstOffset + 0] = x1; + dst[dstOffset + 1] = y1; + dst[dstOffset + 2] = z1; + dst[dstOffset + 3] = w1; + return; + } + if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) { + let s = 1 - t3; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, dir = cos >= 0 ? 1 : -1, sqrSin = 1 - cos * cos; + if (sqrSin > Number.EPSILON) { + const sin = Math.sqrt(sqrSin), len = Math.atan2(sin, cos * dir); + s = Math.sin(s * len) / sin; + t3 = Math.sin(t3 * len) / sin; + } + const tDir = t3 * dir; + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; + if (s === 1 - t3) { + const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0); + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; + } + } + dst[dstOffset] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + } + static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) { + const x0 = src0[srcOffset0]; + const y0 = src0[srcOffset0 + 1]; + const z0 = src0[srcOffset0 + 2]; + const w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1]; + const y1 = src1[srcOffset1 + 1]; + const z1 = src1[srcOffset1 + 2]; + const w1 = src1[srcOffset1 + 3]; + dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + return dst; + } + get x() { + return this._x; + } + set x(value2) { + this._x = value2; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value2) { + this._y = value2; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value2) { + this._z = value2; + this._onChangeCallback(); + } + get w() { + return this._w; + } + set w(value2) { + this._w = value2; + this._onChangeCallback(); + } + set(x2, y, z, w) { + this._x = x2; + this._y = y; + this._z = z; + this._w = w; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._w); + } + copy(quaternion) { + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + this._onChangeCallback(); + return this; + } + setFromEuler(euler, update = true) { + const { _x: x2, _y: y, _z: z, _order: order } = euler; + const cos = Math.cos; + const sin = Math.sin; + const c1 = cos(x2 / 2); + const c2 = cos(y / 2); + const c3 = cos(z / 2); + const s1 = sin(x2 / 2); + const s2 = sin(y / 2); + const s3 = sin(z / 2); + switch (order) { + case "XYZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "YXZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "ZXY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "ZYX": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "YZX": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "XZY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + default: + console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + order); + } + if (update === true) + this._onChangeCallback(); + return this; + } + setFromAxisAngle(axis, angle) { + const halfAngle = angle / 2, s = Math.sin(halfAngle); + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos(halfAngle); + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m) { + const te3 = m.elements, m11 = te3[0], m12 = te3[4], m13 = te3[8], m21 = te3[1], m22 = te3[5], m23 = te3[9], m31 = te3[2], m32 = te3[6], m33 = te3[10], trace = m11 + m22 + m33; + if (trace > 0) { + const s = 0.5 / Math.sqrt(trace + 1); + this._w = 0.25 / s; + this._x = (m32 - m23) * s; + this._y = (m13 - m31) * s; + this._z = (m21 - m12) * s; + } else if (m11 > m22 && m11 > m33) { + const s = 2 * Math.sqrt(1 + m11 - m22 - m33); + this._w = (m32 - m23) / s; + this._x = 0.25 * s; + this._y = (m12 + m21) / s; + this._z = (m13 + m31) / s; + } else if (m22 > m33) { + const s = 2 * Math.sqrt(1 + m22 - m11 - m33); + this._w = (m13 - m31) / s; + this._x = (m12 + m21) / s; + this._y = 0.25 * s; + this._z = (m23 + m32) / s; + } else { + const s = 2 * Math.sqrt(1 + m33 - m11 - m22); + this._w = (m21 - m12) / s; + this._x = (m13 + m31) / s; + this._y = (m23 + m32) / s; + this._z = 0.25 * s; + } + this._onChangeCallback(); + return this; + } + setFromUnitVectors(vFrom, vTo) { + let r = vFrom.dot(vTo) + 1; + if (r < Number.EPSILON) { + r = 0; + if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) { + this._x = -vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + } else { + this._x = 0; + this._y = -vFrom.z; + this._z = vFrom.y; + this._w = r; + } + } else { + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + } + return this.normalize(); + } + angleTo(q2) { + return 2 * Math.acos(Math.abs(clamp3(this.dot(q2), -1, 1))); + } + rotateTowards(q2, step) { + const angle = this.angleTo(q2); + if (angle === 0) + return this; + const t3 = Math.min(1, step / angle); + this.slerp(q2, t3); + return this; + } + identity() { + return this.set(0, 0, 0, 1); + } + invert() { + return this.conjugate(); + } + conjugate() { + this._x *= -1; + this._y *= -1; + this._z *= -1; + this._onChangeCallback(); + return this; + } + dot(v) { + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + } + lengthSq() { + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + } + length() { + return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); + } + normalize() { + let l2 = this.length(); + if (l2 === 0) { + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + } else { + l2 = 1 / l2; + this._x = this._x * l2; + this._y = this._y * l2; + this._z = this._z * l2; + this._w = this._w * l2; + } + this._onChangeCallback(); + return this; + } + multiply(q2) { + return this.multiplyQuaternions(this, q2); + } + premultiply(q2) { + return this.multiplyQuaternions(q2, this); + } + multiplyQuaternions(a2, b2) { + const { _x: qax, _y: qay, _z: qaz, _w: qaw } = a2; + const { _x: qbx, _y: qby, _z: qbz, _w: qbw } = b2; + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + this._onChangeCallback(); + return this; + } + slerp(qb, t3) { + if (t3 === 0) + return this; + if (t3 === 1) + return this.copy(qb); + const x2 = this._x, y = this._y, z = this._z, w = this._w; + let cosHalfTheta = w * qb._w + x2 * qb._x + y * qb._y + z * qb._z; + if (cosHalfTheta < 0) { + this._w = -qb._w; + this._x = -qb._x; + this._y = -qb._y; + this._z = -qb._z; + cosHalfTheta = -cosHalfTheta; + } else { + this.copy(qb); + } + if (cosHalfTheta >= 1) { + this._w = w; + this._x = x2; + this._y = y; + this._z = z; + return this; + } + const sqrSinHalfTheta = 1 - cosHalfTheta * cosHalfTheta; + if (sqrSinHalfTheta <= Number.EPSILON) { + const s = 1 - t3; + this._w = s * w + t3 * this._w; + this._x = s * x2 + t3 * this._x; + this._y = s * y + t3 * this._y; + this._z = s * z + t3 * this._z; + this.normalize(); + return this; + } + const sinHalfTheta = Math.sqrt(sqrSinHalfTheta); + const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta); + const ratioA = Math.sin((1 - t3) * halfTheta) / sinHalfTheta, ratioB = Math.sin(t3 * halfTheta) / sinHalfTheta; + this._w = w * ratioA + this._w * ratioB; + this._x = x2 * ratioA + this._x * ratioB; + this._y = y * ratioA + this._y * ratioB; + this._z = z * ratioA + this._z * ratioB; + this._onChangeCallback(); + return this; + } + slerpQuaternions(qa, qb, t3) { + return this.copy(qa).slerp(qb, t3); + } + random() { + const theta1 = 2 * Math.PI * Math.random(); + const theta2 = 2 * Math.PI * Math.random(); + const x0 = Math.random(); + const r1 = Math.sqrt(1 - x0); + const r2 = Math.sqrt(x0); + return this.set(r1 * Math.sin(theta1), r1 * Math.cos(theta1), r2 * Math.sin(theta2), r2 * Math.cos(theta2)); + } + equals(quaternion) { + return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w; + } + fromArray(array, offset = 0) { + this._x = array[offset]; + this._y = array[offset + 1]; + this._z = array[offset + 2]; + this._w = array[offset + 3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._w; + return array; + } + fromBufferAttribute(attribute, index2) { + this._x = attribute.getX(index2); + this._y = attribute.getY(index2); + this._z = attribute.getZ(index2); + this._w = attribute.getW(index2); + this._onChangeCallback(); + return this; + } + toJSON() { + return this.toArray(); + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._w; + } + } + + class Vector32 { + constructor(x2 = 0, y = 0, z = 0) { + Vector32.prototype.isVector3 = true; + this.x = x2; + this.y = y; + this.z = z; + } + set(x2, y, z) { + if (z === undefined) + z = this.z; + this.x = x2; + this.y = y; + this.z = z; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + return this; + } + setX(x2) { + this.x = x2; + return this; + } + setY(y) { + this.y = y; + return this; + } + setZ(z) { + this.z = z; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + case 2: + this.z = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + return this; + } + addVectors(a2, b2) { + this.x = a2.x + b2.x; + this.y = a2.y + b2.y; + this.z = a2.z + b2.z; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + return this; + } + subVectors(a2, b2) { + this.x = a2.x - b2.x; + this.y = a2.y - b2.y; + this.z = a2.z - b2.z; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + return this; + } + multiplyVectors(a2, b2) { + this.x = a2.x * b2.x; + this.y = a2.y * b2.y; + this.z = a2.z * b2.z; + return this; + } + applyEuler(euler) { + return this.applyQuaternion(_quaternion$42.setFromEuler(euler)); + } + applyAxisAngle(axis, angle) { + return this.applyQuaternion(_quaternion$42.setFromAxisAngle(axis, angle)); + } + applyMatrix3(m) { + const x2 = this.x, y = this.y, z = this.z; + const e = m.elements; + this.x = e[0] * x2 + e[3] * y + e[6] * z; + this.y = e[1] * x2 + e[4] * y + e[7] * z; + this.z = e[2] * x2 + e[5] * y + e[8] * z; + return this; + } + applyNormalMatrix(m) { + return this.applyMatrix3(m).normalize(); + } + applyMatrix4(m) { + const x2 = this.x, y = this.y, z = this.z; + const e = m.elements; + const w = 1 / (e[3] * x2 + e[7] * y + e[11] * z + e[15]); + this.x = (e[0] * x2 + e[4] * y + e[8] * z + e[12]) * w; + this.y = (e[1] * x2 + e[5] * y + e[9] * z + e[13]) * w; + this.z = (e[2] * x2 + e[6] * y + e[10] * z + e[14]) * w; + return this; + } + applyQuaternion(q2) { + const vx = this.x, vy = this.y, vz = this.z; + const { x: qx, y: qy, z: qz, w: qw } = q2; + const tx = 2 * (qy * vz - qz * vy); + const ty = 2 * (qz * vx - qx * vz); + const tz = 2 * (qx * vy - qy * vx); + this.x = vx + qw * tx + qy * tz - qz * ty; + this.y = vy + qw * ty + qz * tx - qx * tz; + this.z = vz + qw * tz + qx * ty - qy * tx; + return this; + } + project(camera) { + return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix); + } + unproject(camera) { + return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld); + } + transformDirection(m) { + const x2 = this.x, y = this.y, z = this.z; + const e = m.elements; + this.x = e[0] * x2 + e[4] * y + e[8] * z; + this.y = e[1] * x2 + e[5] * y + e[9] * z; + this.z = e[2] * x2 + e[6] * y + e[10] * z; + return this.normalize(); + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + return this; + } + clamp(min, max) { + this.x = clamp3(this.x, min.x, max.x); + this.y = clamp3(this.y, min.y, max.y); + this.z = clamp3(this.z, min.z, max.z); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp3(this.x, minVal, maxVal); + this.y = clamp3(this.y, minVal, maxVal); + this.z = clamp3(this.z, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp3(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + return this; + } + lerpVectors(v12, v2, alpha) { + this.x = v12.x + (v2.x - v12.x) * alpha; + this.y = v12.y + (v2.y - v12.y) * alpha; + this.z = v12.z + (v2.z - v12.z) * alpha; + return this; + } + cross(v) { + return this.crossVectors(this, v); + } + crossVectors(a2, b2) { + const { x: ax, y: ay, z: az } = a2; + const { x: bx, y: by, z: bz } = b2; + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + return this; + } + projectOnVector(v) { + const denominator = v.lengthSq(); + if (denominator === 0) + return this.set(0, 0, 0); + const scalar = v.dot(this) / denominator; + return this.copy(v).multiplyScalar(scalar); + } + projectOnPlane(planeNormal) { + _vector$c2.copy(this).projectOnVector(planeNormal); + return this.sub(_vector$c2); + } + reflect(normal) { + return this.sub(_vector$c2.copy(normal).multiplyScalar(2 * this.dot(normal))); + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) + return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp3(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + return dx * dx + dy * dy + dz * dz; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z); + } + setFromSpherical(s) { + return this.setFromSphericalCoords(s.radius, s.phi, s.theta); + } + setFromSphericalCoords(radius, phi, theta) { + const sinPhiRadius = Math.sin(phi) * radius; + this.x = sinPhiRadius * Math.sin(theta); + this.y = Math.cos(phi) * radius; + this.z = sinPhiRadius * Math.cos(theta); + return this; + } + setFromCylindrical(c2) { + return this.setFromCylindricalCoords(c2.radius, c2.theta, c2.y); + } + setFromCylindricalCoords(radius, theta, y) { + this.x = radius * Math.sin(theta); + this.y = y; + this.z = radius * Math.cos(theta); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + return this; + } + setFromMatrixScale(m) { + const sx = this.setFromMatrixColumn(m, 0).length(); + const sy = this.setFromMatrixColumn(m, 1).length(); + const sz = this.setFromMatrixColumn(m, 2).length(); + this.x = sx; + this.y = sy; + this.z = sz; + return this; + } + setFromMatrixColumn(m, index2) { + return this.fromArray(m.elements, index2 * 4); + } + setFromMatrix3Column(m, index2) { + return this.fromArray(m.elements, index2 * 3); + } + setFromEuler(e) { + this.x = e._x; + this.y = e._y; + this.z = e._z; + return this; + } + setFromColor(c2) { + this.x = c2.r; + this.y = c2.g; + this.z = c2.b; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + this.z = attribute.getZ(index2); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + return this; + } + randomDirection() { + const theta = Math.random() * Math.PI * 2; + const u2 = Math.random() * 2 - 1; + const c2 = Math.sqrt(1 - u2 * u2); + this.x = c2 * Math.cos(theta); + this.y = u2; + this.z = c2 * Math.sin(theta); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + } + } + var _vector$c2 = /* @__PURE__ */ new Vector32; + var _quaternion$42 = /* @__PURE__ */ new Quaternion2; + + class Box32 { + constructor(min = new Vector32(Infinity, Infinity, Infinity), max = new Vector32(-Infinity, -Infinity, -Infinity)) { + this.isBox3 = true; + this.min = min; + this.max = max; + } + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + setFromArray(array) { + this.makeEmpty(); + for (let i = 0, il = array.length;i < il; i += 3) { + this.expandByPoint(_vector$b2.fromArray(array, i)); + } + return this; + } + setFromBufferAttribute(attribute) { + this.makeEmpty(); + for (let i = 0, il = attribute.count;i < il; i++) { + this.expandByPoint(_vector$b2.fromBufferAttribute(attribute, i)); + } + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length;i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size2) { + const halfSize = _vector$b2.copy(size2).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + setFromObject(object, precise = false) { + this.makeEmpty(); + return this.expandByObject(object, precise); + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = this.min.z = Infinity; + this.max.x = this.max.y = this.max.z = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + expandByObject(object, precise = false) { + object.updateWorldMatrix(false, false); + const geometry = object.geometry; + if (geometry !== undefined) { + const positionAttribute = geometry.getAttribute("position"); + if (precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true) { + for (let i = 0, l2 = positionAttribute.count;i < l2; i++) { + if (object.isMesh === true) { + object.getVertexPosition(i, _vector$b2); + } else { + _vector$b2.fromBufferAttribute(positionAttribute, i); + } + _vector$b2.applyMatrix4(object.matrixWorld); + this.expandByPoint(_vector$b2); + } + } else { + if (object.boundingBox !== undefined) { + if (object.boundingBox === null) { + object.computeBoundingBox(); + } + _box$42.copy(object.boundingBox); + } else { + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + _box$42.copy(geometry.boundingBox); + } + _box$42.applyMatrix4(object.matrixWorld); + this.union(_box$42); + } + } + const children = object.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + this.expandByObject(children[i], precise); + } + return this; + } + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y && point.z >= this.min.z && point.z <= this.max.z; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z; + } + getParameter(point, target) { + return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z)); + } + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y && box.max.z >= this.min.z && box.min.z <= this.max.z; + } + intersectsSphere(sphere) { + this.clampPoint(sphere.center, _vector$b2); + return _vector$b2.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; + } + intersectsPlane(plane) { + let min, max; + if (plane.normal.x > 0) { + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + } else { + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + } + if (plane.normal.y > 0) { + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + } else { + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + } + if (plane.normal.z > 0) { + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + } else { + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + } + return min <= -plane.constant && max >= -plane.constant; + } + intersectsTriangle(triangle) { + if (this.isEmpty()) { + return false; + } + this.getCenter(_center4); + _extents2.subVectors(this.max, _center4); + _v0$3.subVectors(triangle.a, _center4); + _v1$72.subVectors(triangle.b, _center4); + _v2$42.subVectors(triangle.c, _center4); + _f02.subVectors(_v1$72, _v0$3); + _f12.subVectors(_v2$42, _v1$72); + _f22.subVectors(_v0$3, _v2$42); + let axes = [ + 0, + -_f02.z, + _f02.y, + 0, + -_f12.z, + _f12.y, + 0, + -_f22.z, + _f22.y, + _f02.z, + 0, + -_f02.x, + _f12.z, + 0, + -_f12.x, + _f22.z, + 0, + -_f22.x, + -_f02.y, + _f02.x, + 0, + -_f12.y, + _f12.x, + 0, + -_f22.y, + _f22.x, + 0 + ]; + if (!satForAxes2(axes, _v0$3, _v1$72, _v2$42, _extents2)) { + return false; + } + axes = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + if (!satForAxes2(axes, _v0$3, _v1$72, _v2$42, _extents2)) { + return false; + } + _triangleNormal2.crossVectors(_f02, _f12); + axes = [_triangleNormal2.x, _triangleNormal2.y, _triangleNormal2.z]; + return satForAxes2(axes, _v0$3, _v1$72, _v2$42, _extents2); + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$b2).distanceTo(point); + } + getBoundingSphere(target) { + if (this.isEmpty()) { + target.makeEmpty(); + } else { + this.getCenter(target.center); + target.radius = this.getSize(_vector$b2).length() * 0.5; + } + return target; + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) + this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + applyMatrix4(matrix3) { + if (this.isEmpty()) + return this; + _points2[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix3); + _points2[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix3); + _points2[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix3); + _points2[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix3); + _points2[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix3); + _points2[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix3); + _points2[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix3); + _points2[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix3); + this.setFromPoints(_points2); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } + } + var _points2 = [ + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32, + /* @__PURE__ */ new Vector32 + ]; + var _vector$b2 = /* @__PURE__ */ new Vector32; + var _box$42 = /* @__PURE__ */ new Box32; + var _v0$3 = /* @__PURE__ */ new Vector32; + var _v1$72 = /* @__PURE__ */ new Vector32; + var _v2$42 = /* @__PURE__ */ new Vector32; + var _f02 = /* @__PURE__ */ new Vector32; + var _f12 = /* @__PURE__ */ new Vector32; + var _f22 = /* @__PURE__ */ new Vector32; + var _center4 = /* @__PURE__ */ new Vector32; + var _extents2 = /* @__PURE__ */ new Vector32; + var _triangleNormal2 = /* @__PURE__ */ new Vector32; + var _testAxis2 = /* @__PURE__ */ new Vector32; + function satForAxes2(axes, v0, v12, v2, extents) { + for (let i = 0, j2 = axes.length - 3;i <= j2; i += 3) { + _testAxis2.fromArray(axes, i); + const r = extents.x * Math.abs(_testAxis2.x) + extents.y * Math.abs(_testAxis2.y) + extents.z * Math.abs(_testAxis2.z); + const p0 = v0.dot(_testAxis2); + const p1 = v12.dot(_testAxis2); + const p2 = v2.dot(_testAxis2); + if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) { + return false; + } + } + return true; + } + var _box$32 = /* @__PURE__ */ new Box32; + var _v1$62 = /* @__PURE__ */ new Vector32; + var _v2$32 = /* @__PURE__ */ new Vector32; + + class Sphere2 { + constructor(center = new Vector32, radius = -1) { + this.isSphere = true; + this.center = center; + this.radius = radius; + } + set(center, radius) { + this.center.copy(center); + this.radius = radius; + return this; + } + setFromPoints(points, optionalCenter) { + const center = this.center; + if (optionalCenter !== undefined) { + center.copy(optionalCenter); + } else { + _box$32.setFromPoints(points).getCenter(center); + } + let maxRadiusSq = 0; + for (let i = 0, il = points.length;i < il; i++) { + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i])); + } + this.radius = Math.sqrt(maxRadiusSq); + return this; + } + copy(sphere) { + this.center.copy(sphere.center); + this.radius = sphere.radius; + return this; + } + isEmpty() { + return this.radius < 0; + } + makeEmpty() { + this.center.set(0, 0, 0); + this.radius = -1; + return this; + } + containsPoint(point) { + return point.distanceToSquared(this.center) <= this.radius * this.radius; + } + distanceToPoint(point) { + return point.distanceTo(this.center) - this.radius; + } + intersectsSphere(sphere) { + const radiusSum = this.radius + sphere.radius; + return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum; + } + intersectsBox(box) { + return box.intersectsSphere(this); + } + intersectsPlane(plane) { + return Math.abs(plane.distanceToPoint(this.center)) <= this.radius; + } + clampPoint(point, target) { + const deltaLengthSq = this.center.distanceToSquared(point); + target.copy(point); + if (deltaLengthSq > this.radius * this.radius) { + target.sub(this.center).normalize(); + target.multiplyScalar(this.radius).add(this.center); + } + return target; + } + getBoundingBox(target) { + if (this.isEmpty()) { + target.makeEmpty(); + return target; + } + target.set(this.center, this.center); + target.expandByScalar(this.radius); + return target; + } + applyMatrix4(matrix3) { + this.center.applyMatrix4(matrix3); + this.radius = this.radius * matrix3.getMaxScaleOnAxis(); + return this; + } + translate(offset) { + this.center.add(offset); + return this; + } + expandByPoint(point) { + if (this.isEmpty()) { + this.center.copy(point); + this.radius = 0; + return this; + } + _v1$62.subVectors(point, this.center); + const lengthSq = _v1$62.lengthSq(); + if (lengthSq > this.radius * this.radius) { + const length2 = Math.sqrt(lengthSq); + const delta = (length2 - this.radius) * 0.5; + this.center.addScaledVector(_v1$62, delta / length2); + this.radius += delta; + } + return this; + } + union(sphere) { + if (sphere.isEmpty()) { + return this; + } + if (this.isEmpty()) { + this.copy(sphere); + return this; + } + if (this.center.equals(sphere.center) === true) { + this.radius = Math.max(this.radius, sphere.radius); + } else { + _v2$32.subVectors(sphere.center, this.center).setLength(sphere.radius); + this.expandByPoint(_v1$62.copy(sphere.center).add(_v2$32)); + this.expandByPoint(_v1$62.copy(sphere.center).sub(_v2$32)); + } + return this; + } + equals(sphere) { + return sphere.center.equals(this.center) && sphere.radius === this.radius; + } + clone() { + return new this.constructor().copy(this); + } + } + var _vector$a2 = /* @__PURE__ */ new Vector32; + var _segCenter2 = /* @__PURE__ */ new Vector32; + var _segDir2 = /* @__PURE__ */ new Vector32; + var _diff3 = /* @__PURE__ */ new Vector32; + var _edge12 = /* @__PURE__ */ new Vector32; + var _edge22 = /* @__PURE__ */ new Vector32; + var _normal$12 = /* @__PURE__ */ new Vector32; + + class Ray2 { + constructor(origin = new Vector32, direction = new Vector32(0, 0, -1)) { + this.origin = origin; + this.direction = direction; + } + set(origin, direction) { + this.origin.copy(origin); + this.direction.copy(direction); + return this; + } + copy(ray) { + this.origin.copy(ray.origin); + this.direction.copy(ray.direction); + return this; + } + at(t3, target) { + return target.copy(this.origin).addScaledVector(this.direction, t3); + } + lookAt(v) { + this.direction.copy(v).sub(this.origin).normalize(); + return this; + } + recast(t3) { + this.origin.copy(this.at(t3, _vector$a2)); + return this; + } + closestPointToPoint(point, target) { + target.subVectors(point, this.origin); + const directionDistance = target.dot(this.direction); + if (directionDistance < 0) { + return target.copy(this.origin); + } + return target.copy(this.origin).addScaledVector(this.direction, directionDistance); + } + distanceToPoint(point) { + return Math.sqrt(this.distanceSqToPoint(point)); + } + distanceSqToPoint(point) { + const directionDistance = _vector$a2.subVectors(point, this.origin).dot(this.direction); + if (directionDistance < 0) { + return this.origin.distanceToSquared(point); + } + _vector$a2.copy(this.origin).addScaledVector(this.direction, directionDistance); + return _vector$a2.distanceToSquared(point); + } + distanceSqToSegment(v0, v12, optionalPointOnRay, optionalPointOnSegment) { + _segCenter2.copy(v0).add(v12).multiplyScalar(0.5); + _segDir2.copy(v12).sub(v0).normalize(); + _diff3.copy(this.origin).sub(_segCenter2); + const segExtent = v0.distanceTo(v12) * 0.5; + const a01 = -this.direction.dot(_segDir2); + const b0 = _diff3.dot(this.direction); + const b1 = -_diff3.dot(_segDir2); + const c2 = _diff3.lengthSq(); + const det = Math.abs(1 - a01 * a01); + let s0, s1, sqrDist, extDet; + if (det > 0) { + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + if (s0 >= 0) { + if (s1 >= -extDet) { + if (s1 <= extDet) { + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c2; + } else { + s1 = segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2; + } + } else { + s1 = -segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2; + } + } else { + if (s1 <= -extDet) { + s0 = Math.max(0, -(-a01 * segExtent + b0)); + s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2; + } else if (s1 <= extDet) { + s0 = 0; + s1 = Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = s1 * (s1 + 2 * b1) + c2; + } else { + s0 = Math.max(0, -(a01 * segExtent + b0)); + s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2; + } + } + } else { + s1 = a01 > 0 ? -segExtent : segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c2; + } + if (optionalPointOnRay) { + optionalPointOnRay.copy(this.origin).addScaledVector(this.direction, s0); + } + if (optionalPointOnSegment) { + optionalPointOnSegment.copy(_segCenter2).addScaledVector(_segDir2, s1); + } + return sqrDist; + } + intersectSphere(sphere, target) { + _vector$a2.subVectors(sphere.center, this.origin); + const tca = _vector$a2.dot(this.direction); + const d2 = _vector$a2.dot(_vector$a2) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + if (d2 > radius2) + return null; + const thc = Math.sqrt(radius2 - d2); + const t0 = tca - thc; + const t1 = tca + thc; + if (t1 < 0) + return null; + if (t0 < 0) + return this.at(t1, target); + return this.at(t0, target); + } + intersectsSphere(sphere) { + return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius; + } + distanceToPlane(plane) { + const denominator = plane.normal.dot(this.direction); + if (denominator === 0) { + if (plane.distanceToPoint(this.origin) === 0) { + return 0; + } + return null; + } + const t3 = -(this.origin.dot(plane.normal) + plane.constant) / denominator; + return t3 >= 0 ? t3 : null; + } + intersectPlane(plane, target) { + const t3 = this.distanceToPlane(plane); + if (t3 === null) { + return null; + } + return this.at(t3, target); + } + intersectsPlane(plane) { + const distToPoint = plane.distanceToPoint(this.origin); + if (distToPoint === 0) { + return true; + } + const denominator = plane.normal.dot(this.direction); + if (denominator * distToPoint < 0) { + return true; + } + return false; + } + intersectBox(box, target) { + let tmin, tmax, tymin, tymax, tzmin, tzmax; + const invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z; + const origin = this.origin; + if (invdirx >= 0) { + tmin = (box.min.x - origin.x) * invdirx; + tmax = (box.max.x - origin.x) * invdirx; + } else { + tmin = (box.max.x - origin.x) * invdirx; + tmax = (box.min.x - origin.x) * invdirx; + } + if (invdiry >= 0) { + tymin = (box.min.y - origin.y) * invdiry; + tymax = (box.max.y - origin.y) * invdiry; + } else { + tymin = (box.max.y - origin.y) * invdiry; + tymax = (box.min.y - origin.y) * invdiry; + } + if (tmin > tymax || tymin > tmax) + return null; + if (tymin > tmin || isNaN(tmin)) + tmin = tymin; + if (tymax < tmax || isNaN(tmax)) + tmax = tymax; + if (invdirz >= 0) { + tzmin = (box.min.z - origin.z) * invdirz; + tzmax = (box.max.z - origin.z) * invdirz; + } else { + tzmin = (box.max.z - origin.z) * invdirz; + tzmax = (box.min.z - origin.z) * invdirz; + } + if (tmin > tzmax || tzmin > tmax) + return null; + if (tzmin > tmin || tmin !== tmin) + tmin = tzmin; + if (tzmax < tmax || tmax !== tmax) + tmax = tzmax; + if (tmax < 0) + return null; + return this.at(tmin >= 0 ? tmin : tmax, target); + } + intersectsBox(box) { + return this.intersectBox(box, _vector$a2) !== null; + } + intersectTriangle(a2, b2, c2, backfaceCulling, target) { + _edge12.subVectors(b2, a2); + _edge22.subVectors(c2, a2); + _normal$12.crossVectors(_edge12, _edge22); + let DdN = this.direction.dot(_normal$12); + let sign3; + if (DdN > 0) { + if (backfaceCulling) + return null; + sign3 = 1; + } else if (DdN < 0) { + sign3 = -1; + DdN = -DdN; + } else { + return null; + } + _diff3.subVectors(this.origin, a2); + const DdQxE2 = sign3 * this.direction.dot(_edge22.crossVectors(_diff3, _edge22)); + if (DdQxE2 < 0) { + return null; + } + const DdE1xQ = sign3 * this.direction.dot(_edge12.cross(_diff3)); + if (DdE1xQ < 0) { + return null; + } + if (DdQxE2 + DdE1xQ > DdN) { + return null; + } + const QdN = -sign3 * _diff3.dot(_normal$12); + if (QdN < 0) { + return null; + } + return this.at(QdN / DdN, target); + } + applyMatrix4(matrix4) { + this.origin.applyMatrix4(matrix4); + this.direction.transformDirection(matrix4); + return this; + } + equals(ray) { + return ray.origin.equals(this.origin) && ray.direction.equals(this.direction); + } + clone() { + return new this.constructor().copy(this); + } + } + + class Matrix42 { + constructor(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + Matrix42.prototype.isMatrix4 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44); + } + } + set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + const te3 = this.elements; + te3[0] = n11; + te3[4] = n12; + te3[8] = n13; + te3[12] = n14; + te3[1] = n21; + te3[5] = n22; + te3[9] = n23; + te3[13] = n24; + te3[2] = n31; + te3[6] = n32; + te3[10] = n33; + te3[14] = n34; + te3[3] = n41; + te3[7] = n42; + te3[11] = n43; + te3[15] = n44; + return this; + } + identity() { + this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return this; + } + clone() { + return new Matrix42().fromArray(this.elements); + } + copy(m) { + const te3 = this.elements; + const me = m.elements; + te3[0] = me[0]; + te3[1] = me[1]; + te3[2] = me[2]; + te3[3] = me[3]; + te3[4] = me[4]; + te3[5] = me[5]; + te3[6] = me[6]; + te3[7] = me[7]; + te3[8] = me[8]; + te3[9] = me[9]; + te3[10] = me[10]; + te3[11] = me[11]; + te3[12] = me[12]; + te3[13] = me[13]; + te3[14] = me[14]; + te3[15] = me[15]; + return this; + } + copyPosition(m) { + const te3 = this.elements, me = m.elements; + te3[12] = me[12]; + te3[13] = me[13]; + te3[14] = me[14]; + return this; + } + setFromMatrix3(m) { + const me = m.elements; + this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1); + return this; + } + extractBasis(xAxis2, yAxis2, zAxis2) { + xAxis2.setFromMatrixColumn(this, 0); + yAxis2.setFromMatrixColumn(this, 1); + zAxis2.setFromMatrixColumn(this, 2); + return this; + } + makeBasis(xAxis2, yAxis2, zAxis2) { + this.set(xAxis2.x, yAxis2.x, zAxis2.x, 0, xAxis2.y, yAxis2.y, zAxis2.y, 0, xAxis2.z, yAxis2.z, zAxis2.z, 0, 0, 0, 0, 1); + return this; + } + extractRotation(m) { + const te3 = this.elements; + const me = m.elements; + const scaleX = 1 / _v1$52.setFromMatrixColumn(m, 0).length(); + const scaleY = 1 / _v1$52.setFromMatrixColumn(m, 1).length(); + const scaleZ = 1 / _v1$52.setFromMatrixColumn(m, 2).length(); + te3[0] = me[0] * scaleX; + te3[1] = me[1] * scaleX; + te3[2] = me[2] * scaleX; + te3[3] = 0; + te3[4] = me[4] * scaleY; + te3[5] = me[5] * scaleY; + te3[6] = me[6] * scaleY; + te3[7] = 0; + te3[8] = me[8] * scaleZ; + te3[9] = me[9] * scaleZ; + te3[10] = me[10] * scaleZ; + te3[11] = 0; + te3[12] = 0; + te3[13] = 0; + te3[14] = 0; + te3[15] = 1; + return this; + } + makeRotationFromEuler(euler) { + const te3 = this.elements; + const { x: x2, y, z } = euler; + const a2 = Math.cos(x2), b2 = Math.sin(x2); + const c2 = Math.cos(y), d = Math.sin(y); + const e = Math.cos(z), f = Math.sin(z); + if (euler.order === "XYZ") { + const ae3 = a2 * e, af = a2 * f, be = b2 * e, bf = b2 * f; + te3[0] = c2 * e; + te3[4] = -c2 * f; + te3[8] = d; + te3[1] = af + be * d; + te3[5] = ae3 - bf * d; + te3[9] = -b2 * c2; + te3[2] = bf - ae3 * d; + te3[6] = be + af * d; + te3[10] = a2 * c2; + } else if (euler.order === "YXZ") { + const ce3 = c2 * e, cf = c2 * f, de = d * e, df = d * f; + te3[0] = ce3 + df * b2; + te3[4] = de * b2 - cf; + te3[8] = a2 * d; + te3[1] = a2 * f; + te3[5] = a2 * e; + te3[9] = -b2; + te3[2] = cf * b2 - de; + te3[6] = df + ce3 * b2; + te3[10] = a2 * c2; + } else if (euler.order === "ZXY") { + const ce3 = c2 * e, cf = c2 * f, de = d * e, df = d * f; + te3[0] = ce3 - df * b2; + te3[4] = -a2 * f; + te3[8] = de + cf * b2; + te3[1] = cf + de * b2; + te3[5] = a2 * e; + te3[9] = df - ce3 * b2; + te3[2] = -a2 * d; + te3[6] = b2; + te3[10] = a2 * c2; + } else if (euler.order === "ZYX") { + const ae3 = a2 * e, af = a2 * f, be = b2 * e, bf = b2 * f; + te3[0] = c2 * e; + te3[4] = be * d - af; + te3[8] = ae3 * d + bf; + te3[1] = c2 * f; + te3[5] = bf * d + ae3; + te3[9] = af * d - be; + te3[2] = -d; + te3[6] = b2 * c2; + te3[10] = a2 * c2; + } else if (euler.order === "YZX") { + const ac = a2 * c2, ad = a2 * d, bc = b2 * c2, bd = b2 * d; + te3[0] = c2 * e; + te3[4] = bd - ac * f; + te3[8] = bc * f + ad; + te3[1] = f; + te3[5] = a2 * e; + te3[9] = -b2 * e; + te3[2] = -d * e; + te3[6] = ad * f + bc; + te3[10] = ac - bd * f; + } else if (euler.order === "XZY") { + const ac = a2 * c2, ad = a2 * d, bc = b2 * c2, bd = b2 * d; + te3[0] = c2 * e; + te3[4] = -f; + te3[8] = d * e; + te3[1] = ac * f + bd; + te3[5] = a2 * e; + te3[9] = ad * f - bc; + te3[2] = bc * f - ad; + te3[6] = b2 * e; + te3[10] = bd * f + ac; + } + te3[3] = 0; + te3[7] = 0; + te3[11] = 0; + te3[12] = 0; + te3[13] = 0; + te3[14] = 0; + te3[15] = 1; + return this; + } + makeRotationFromQuaternion(q2) { + return this.compose(_zero2, q2, _one2); + } + lookAt(eye, target, up) { + const te3 = this.elements; + _z2.subVectors(eye, target); + if (_z2.lengthSq() === 0) { + _z2.z = 1; + } + _z2.normalize(); + _x2.crossVectors(up, _z2); + if (_x2.lengthSq() === 0) { + if (Math.abs(up.z) === 1) { + _z2.x += 0.0001; + } else { + _z2.z += 0.0001; + } + _z2.normalize(); + _x2.crossVectors(up, _z2); + } + _x2.normalize(); + _y2.crossVectors(_z2, _x2); + te3[0] = _x2.x; + te3[4] = _y2.x; + te3[8] = _z2.x; + te3[1] = _x2.y; + te3[5] = _y2.y; + te3[9] = _z2.y; + te3[2] = _x2.z; + te3[6] = _y2.z; + te3[10] = _z2.z; + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a2, b2) { + const ae3 = a2.elements; + const be = b2.elements; + const te3 = this.elements; + const a11 = ae3[0], a12 = ae3[4], a13 = ae3[8], a14 = ae3[12]; + const a21 = ae3[1], a22 = ae3[5], a23 = ae3[9], a24 = ae3[13]; + const a31 = ae3[2], a32 = ae3[6], a33 = ae3[10], a34 = ae3[14]; + const a41 = ae3[3], a42 = ae3[7], a43 = ae3[11], a44 = ae3[15]; + const b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; + const b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; + const b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; + const b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; + te3[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te3[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te3[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te3[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + te3[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te3[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te3[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te3[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + te3[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te3[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te3[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te3[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + te3[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te3[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te3[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te3[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + return this; + } + multiplyScalar(s) { + const te3 = this.elements; + te3[0] *= s; + te3[4] *= s; + te3[8] *= s; + te3[12] *= s; + te3[1] *= s; + te3[5] *= s; + te3[9] *= s; + te3[13] *= s; + te3[2] *= s; + te3[6] *= s; + te3[10] *= s; + te3[14] *= s; + te3[3] *= s; + te3[7] *= s; + te3[11] *= s; + te3[15] *= s; + return this; + } + determinant() { + const te3 = this.elements; + const n11 = te3[0], n12 = te3[4], n13 = te3[8], n14 = te3[12]; + const n21 = te3[1], n22 = te3[5], n23 = te3[9], n24 = te3[13]; + const n31 = te3[2], n32 = te3[6], n33 = te3[10], n34 = te3[14]; + const n41 = te3[3], n42 = te3[7], n43 = te3[11], n44 = te3[15]; + return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31); + } + transpose() { + const te3 = this.elements; + let tmp3; + tmp3 = te3[1]; + te3[1] = te3[4]; + te3[4] = tmp3; + tmp3 = te3[2]; + te3[2] = te3[8]; + te3[8] = tmp3; + tmp3 = te3[6]; + te3[6] = te3[9]; + te3[9] = tmp3; + tmp3 = te3[3]; + te3[3] = te3[12]; + te3[12] = tmp3; + tmp3 = te3[7]; + te3[7] = te3[13]; + te3[13] = tmp3; + tmp3 = te3[11]; + te3[11] = te3[14]; + te3[14] = tmp3; + return this; + } + setPosition(x2, y, z) { + const te3 = this.elements; + if (x2.isVector3) { + te3[12] = x2.x; + te3[13] = x2.y; + te3[14] = x2.z; + } else { + te3[12] = x2; + te3[13] = y; + te3[14] = z; + } + return this; + } + invert() { + const te3 = this.elements, n11 = te3[0], n21 = te3[1], n31 = te3[2], n41 = te3[3], n12 = te3[4], n22 = te3[5], n32 = te3[6], n42 = te3[7], n13 = te3[8], n23 = te3[9], n33 = te3[10], n43 = te3[11], n14 = te3[12], n24 = te3[13], n34 = te3[14], n44 = te3[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + if (det === 0) + return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te3[0] = t11 * detInv; + te3[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; + te3[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; + te3[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; + te3[4] = t12 * detInv; + te3[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; + te3[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; + te3[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; + te3[8] = t13 * detInv; + te3[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; + te3[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; + te3[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; + te3[12] = t14 * detInv; + te3[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; + te3[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; + te3[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; + return this; + } + scale(v) { + const te3 = this.elements; + const { x: x2, y, z } = v; + te3[0] *= x2; + te3[4] *= y; + te3[8] *= z; + te3[1] *= x2; + te3[5] *= y; + te3[9] *= z; + te3[2] *= x2; + te3[6] *= y; + te3[10] *= z; + te3[3] *= x2; + te3[7] *= y; + te3[11] *= z; + return this; + } + getMaxScaleOnAxis() { + const te3 = this.elements; + const scaleXSq = te3[0] * te3[0] + te3[1] * te3[1] + te3[2] * te3[2]; + const scaleYSq = te3[4] * te3[4] + te3[5] * te3[5] + te3[6] * te3[6]; + const scaleZSq = te3[8] * te3[8] + te3[9] * te3[9] + te3[10] * te3[10]; + return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); + } + makeTranslation(x2, y, z) { + if (x2.isVector3) { + this.set(1, 0, 0, x2.x, 0, 1, 0, x2.y, 0, 0, 1, x2.z, 0, 0, 0, 1); + } else { + this.set(1, 0, 0, x2, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1); + } + return this; + } + makeRotationX(theta) { + const c2 = Math.cos(theta), s = Math.sin(theta); + this.set(1, 0, 0, 0, 0, c2, -s, 0, 0, s, c2, 0, 0, 0, 0, 1); + return this; + } + makeRotationY(theta) { + const c2 = Math.cos(theta), s = Math.sin(theta); + this.set(c2, 0, s, 0, 0, 1, 0, 0, -s, 0, c2, 0, 0, 0, 0, 1); + return this; + } + makeRotationZ(theta) { + const c2 = Math.cos(theta), s = Math.sin(theta); + this.set(c2, -s, 0, 0, s, c2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return this; + } + makeRotationAxis(axis, angle) { + const c2 = Math.cos(angle); + const s = Math.sin(angle); + const t3 = 1 - c2; + const { x: x2, y, z } = axis; + const tx = t3 * x2, ty = t3 * y; + this.set(tx * x2 + c2, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c2, ty * z - s * x2, 0, tx * z - s * y, ty * z + s * x2, t3 * z * z + c2, 0, 0, 0, 0, 1); + return this; + } + makeScale(x2, y, z) { + this.set(x2, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); + return this; + } + makeShear(xy, xz, yx, yz, zx, zy) { + this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1); + return this; + } + compose(position2, quaternion, scale2) { + const te3 = this.elements; + const { _x: x2, _y: y, _z: z, _w: w } = quaternion; + const x22 = x2 + x2, y2 = y + y, z2 = z + z; + const xx = x2 * x22, xy = x2 * y2, xz = x2 * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x22, wy = w * y2, wz = w * z2; + const { x: sx, y: sy, z: sz } = scale2; + te3[0] = (1 - (yy + zz)) * sx; + te3[1] = (xy + wz) * sx; + te3[2] = (xz - wy) * sx; + te3[3] = 0; + te3[4] = (xy - wz) * sy; + te3[5] = (1 - (xx + zz)) * sy; + te3[6] = (yz + wx) * sy; + te3[7] = 0; + te3[8] = (xz + wy) * sz; + te3[9] = (yz - wx) * sz; + te3[10] = (1 - (xx + yy)) * sz; + te3[11] = 0; + te3[12] = position2.x; + te3[13] = position2.y; + te3[14] = position2.z; + te3[15] = 1; + return this; + } + decompose(position2, quaternion, scale2) { + const te3 = this.elements; + let sx = _v1$52.set(te3[0], te3[1], te3[2]).length(); + const sy = _v1$52.set(te3[4], te3[5], te3[6]).length(); + const sz = _v1$52.set(te3[8], te3[9], te3[10]).length(); + const det = this.determinant(); + if (det < 0) + sx = -sx; + position2.x = te3[12]; + position2.y = te3[13]; + position2.z = te3[14]; + _m1$4.copy(this); + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + _m1$4.elements[0] *= invSX; + _m1$4.elements[1] *= invSX; + _m1$4.elements[2] *= invSX; + _m1$4.elements[4] *= invSY; + _m1$4.elements[5] *= invSY; + _m1$4.elements[6] *= invSY; + _m1$4.elements[8] *= invSZ; + _m1$4.elements[9] *= invSZ; + _m1$4.elements[10] *= invSZ; + quaternion.setFromRotationMatrix(_m1$4); + scale2.x = sx; + scale2.y = sy; + scale2.z = sz; + return this; + } + makePerspective(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem2) { + const te3 = this.elements; + const x2 = 2 * near / (right - left); + const y = 2 * near / (top - bottom); + const a2 = (right + left) / (right - left); + const b2 = (top + bottom) / (top - bottom); + let c2, d; + if (coordinateSystem === WebGLCoordinateSystem2) { + c2 = -(far + near) / (far - near); + d = -2 * far * near / (far - near); + } else if (coordinateSystem === WebGPUCoordinateSystem2) { + c2 = -far / (far - near); + d = -far * near / (far - near); + } else { + throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + coordinateSystem); + } + te3[0] = x2; + te3[4] = 0; + te3[8] = a2; + te3[12] = 0; + te3[1] = 0; + te3[5] = y; + te3[9] = b2; + te3[13] = 0; + te3[2] = 0; + te3[6] = 0; + te3[10] = c2; + te3[14] = d; + te3[3] = 0; + te3[7] = 0; + te3[11] = -1; + te3[15] = 0; + return this; + } + makeOrthographic(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem2) { + const te3 = this.elements; + const w = 1 / (right - left); + const h = 1 / (top - bottom); + const p = 1 / (far - near); + const x2 = (right + left) * w; + const y = (top + bottom) * h; + let z, zInv; + if (coordinateSystem === WebGLCoordinateSystem2) { + z = (far + near) * p; + zInv = -2 * p; + } else if (coordinateSystem === WebGPUCoordinateSystem2) { + z = near * p; + zInv = -1 * p; + } else { + throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + coordinateSystem); + } + te3[0] = 2 * w; + te3[4] = 0; + te3[8] = 0; + te3[12] = -x2; + te3[1] = 0; + te3[5] = 2 * h; + te3[9] = 0; + te3[13] = -y; + te3[2] = 0; + te3[6] = 0; + te3[10] = zInv; + te3[14] = -z; + te3[3] = 0; + te3[7] = 0; + te3[11] = 0; + te3[15] = 1; + return this; + } + equals(matrix3) { + const te3 = this.elements; + const me = matrix3.elements; + for (let i = 0;i < 16; i++) { + if (te3[i] !== me[i]) + return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 16; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te3 = this.elements; + array[offset] = te3[0]; + array[offset + 1] = te3[1]; + array[offset + 2] = te3[2]; + array[offset + 3] = te3[3]; + array[offset + 4] = te3[4]; + array[offset + 5] = te3[5]; + array[offset + 6] = te3[6]; + array[offset + 7] = te3[7]; + array[offset + 8] = te3[8]; + array[offset + 9] = te3[9]; + array[offset + 10] = te3[10]; + array[offset + 11] = te3[11]; + array[offset + 12] = te3[12]; + array[offset + 13] = te3[13]; + array[offset + 14] = te3[14]; + array[offset + 15] = te3[15]; + return array; + } + } + var _v1$52 = /* @__PURE__ */ new Vector32; + var _m1$4 = /* @__PURE__ */ new Matrix42; + var _zero2 = /* @__PURE__ */ new Vector32(0, 0, 0); + var _one2 = /* @__PURE__ */ new Vector32(1, 1, 1); + var _x2 = /* @__PURE__ */ new Vector32; + var _y2 = /* @__PURE__ */ new Vector32; + var _z2 = /* @__PURE__ */ new Vector32; + var _matrix$22 = /* @__PURE__ */ new Matrix42; + var _quaternion$32 = /* @__PURE__ */ new Quaternion2; + + class Euler2 { + constructor(x2 = 0, y = 0, z = 0, order = Euler2.DEFAULT_ORDER) { + this.isEuler = true; + this._x = x2; + this._y = y; + this._z = z; + this._order = order; + } + get x() { + return this._x; + } + set x(value2) { + this._x = value2; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value2) { + this._y = value2; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value2) { + this._z = value2; + this._onChangeCallback(); + } + get order() { + return this._order; + } + set order(value2) { + this._order = value2; + this._onChangeCallback(); + } + set(x2, y, z, order = this._order) { + this._x = x2; + this._y = y; + this._z = z; + this._order = order; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._order); + } + copy(euler) { + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m, order = this._order, update = true) { + const te3 = m.elements; + const m11 = te3[0], m12 = te3[4], m13 = te3[8]; + const m21 = te3[1], m22 = te3[5], m23 = te3[9]; + const m31 = te3[2], m32 = te3[6], m33 = te3[10]; + switch (order) { + case "XYZ": + this._y = Math.asin(clamp3(m13, -1, 1)); + if (Math.abs(m13) < 0.9999999) { + this._x = Math.atan2(-m23, m33); + this._z = Math.atan2(-m12, m11); + } else { + this._x = Math.atan2(m32, m22); + this._z = 0; + } + break; + case "YXZ": + this._x = Math.asin(-clamp3(m23, -1, 1)); + if (Math.abs(m23) < 0.9999999) { + this._y = Math.atan2(m13, m33); + this._z = Math.atan2(m21, m22); + } else { + this._y = Math.atan2(-m31, m11); + this._z = 0; + } + break; + case "ZXY": + this._x = Math.asin(clamp3(m32, -1, 1)); + if (Math.abs(m32) < 0.9999999) { + this._y = Math.atan2(-m31, m33); + this._z = Math.atan2(-m12, m22); + } else { + this._y = 0; + this._z = Math.atan2(m21, m11); + } + break; + case "ZYX": + this._y = Math.asin(-clamp3(m31, -1, 1)); + if (Math.abs(m31) < 0.9999999) { + this._x = Math.atan2(m32, m33); + this._z = Math.atan2(m21, m11); + } else { + this._x = 0; + this._z = Math.atan2(-m12, m22); + } + break; + case "YZX": + this._z = Math.asin(clamp3(m21, -1, 1)); + if (Math.abs(m21) < 0.9999999) { + this._x = Math.atan2(-m23, m22); + this._y = Math.atan2(-m31, m11); + } else { + this._x = 0; + this._y = Math.atan2(m13, m33); + } + break; + case "XZY": + this._z = Math.asin(-clamp3(m12, -1, 1)); + if (Math.abs(m12) < 0.9999999) { + this._x = Math.atan2(m32, m22); + this._y = Math.atan2(m13, m11); + } else { + this._x = Math.atan2(-m23, m33); + this._y = 0; + } + break; + default: + console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + order); + } + this._order = order; + if (update === true) + this._onChangeCallback(); + return this; + } + setFromQuaternion(q2, order, update) { + _matrix$22.makeRotationFromQuaternion(q2); + return this.setFromRotationMatrix(_matrix$22, order, update); + } + setFromVector3(v, order = this._order) { + return this.set(v.x, v.y, v.z, order); + } + reorder(newOrder) { + _quaternion$32.setFromEuler(this); + return this.setFromQuaternion(_quaternion$32, newOrder); + } + equals(euler) { + return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order; + } + fromArray(array) { + this._x = array[0]; + this._y = array[1]; + this._z = array[2]; + if (array[3] !== undefined) + this._order = array[3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._order; + return array; + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._order; + } + } + Euler2.DEFAULT_ORDER = "XYZ"; + + class Layers2 { + constructor() { + this.mask = 1 | 0; + } + set(channel) { + this.mask = (1 << channel | 0) >>> 0; + } + enable(channel) { + this.mask |= 1 << channel | 0; + } + enableAll() { + this.mask = 4294967295 | 0; + } + toggle(channel) { + this.mask ^= 1 << channel | 0; + } + disable(channel) { + this.mask &= ~(1 << channel | 0); + } + disableAll() { + this.mask = 0; + } + test(layers) { + return (this.mask & layers.mask) !== 0; + } + isEnabled(channel) { + return (this.mask & (1 << channel | 0)) !== 0; + } + } + var _object3DId2 = 0; + var _v1$42 = /* @__PURE__ */ new Vector32; + var _q12 = /* @__PURE__ */ new Quaternion2; + var _m1$3 = /* @__PURE__ */ new Matrix42; + var _target3 = /* @__PURE__ */ new Vector32; + var _position$32 = /* @__PURE__ */ new Vector32; + var _scale$22 = /* @__PURE__ */ new Vector32; + var _quaternion$22 = /* @__PURE__ */ new Quaternion2; + var _xAxis2 = /* @__PURE__ */ new Vector32(1, 0, 0); + var _yAxis2 = /* @__PURE__ */ new Vector32(0, 1, 0); + var _zAxis2 = /* @__PURE__ */ new Vector32(0, 0, 1); + var _addedEvent2 = { type: "added" }; + var _removedEvent2 = { type: "removed" }; + var _childaddedEvent2 = { type: "childadded", child: null }; + var _childremovedEvent2 = { type: "childremoved", child: null }; + + class Object3D2 extends EventDispatcher2 { + constructor() { + super(); + this.isObject3D = true; + Object.defineProperty(this, "id", { value: _object3DId2++ }); + this.uuid = generateUUID2(); + this.name = ""; + this.type = "Object3D"; + this.parent = null; + this.children = []; + this.up = Object3D2.DEFAULT_UP.clone(); + const position2 = new Vector32; + const rotation2 = new Euler2; + const quaternion = new Quaternion2; + const scale2 = new Vector32(1, 1, 1); + function onRotationChange() { + quaternion.setFromEuler(rotation2, false); + } + function onQuaternionChange() { + rotation2.setFromQuaternion(quaternion, undefined, false); + } + rotation2._onChange(onRotationChange); + quaternion._onChange(onQuaternionChange); + Object.defineProperties(this, { + position: { + configurable: true, + enumerable: true, + value: position2 + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation2 + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale2 + }, + modelViewMatrix: { + value: new Matrix42 + }, + normalMatrix: { + value: new Matrix32 + } + }); + this.matrix = new Matrix42; + this.matrixWorld = new Matrix42; + this.matrixAutoUpdate = Object3D2.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldAutoUpdate = Object3D2.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + this.layers = new Layers2; + this.visible = true; + this.castShadow = false; + this.receiveShadow = false; + this.frustumCulled = true; + this.renderOrder = 0; + this.animations = []; + this.userData = {}; + } + onBeforeShadow() { + } + onAfterShadow() { + } + onBeforeRender() { + } + onAfterRender() { + } + applyMatrix4(matrix3) { + if (this.matrixAutoUpdate) + this.updateMatrix(); + this.matrix.premultiply(matrix3); + this.matrix.decompose(this.position, this.quaternion, this.scale); + } + applyQuaternion(q2) { + this.quaternion.premultiply(q2); + return this; + } + setRotationFromAxisAngle(axis, angle) { + this.quaternion.setFromAxisAngle(axis, angle); + } + setRotationFromEuler(euler) { + this.quaternion.setFromEuler(euler, true); + } + setRotationFromMatrix(m) { + this.quaternion.setFromRotationMatrix(m); + } + setRotationFromQuaternion(q2) { + this.quaternion.copy(q2); + } + rotateOnAxis(axis, angle) { + _q12.setFromAxisAngle(axis, angle); + this.quaternion.multiply(_q12); + return this; + } + rotateOnWorldAxis(axis, angle) { + _q12.setFromAxisAngle(axis, angle); + this.quaternion.premultiply(_q12); + return this; + } + rotateX(angle) { + return this.rotateOnAxis(_xAxis2, angle); + } + rotateY(angle) { + return this.rotateOnAxis(_yAxis2, angle); + } + rotateZ(angle) { + return this.rotateOnAxis(_zAxis2, angle); + } + translateOnAxis(axis, distance) { + _v1$42.copy(axis).applyQuaternion(this.quaternion); + this.position.add(_v1$42.multiplyScalar(distance)); + return this; + } + translateX(distance) { + return this.translateOnAxis(_xAxis2, distance); + } + translateY(distance) { + return this.translateOnAxis(_yAxis2, distance); + } + translateZ(distance) { + return this.translateOnAxis(_zAxis2, distance); + } + localToWorld(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(this.matrixWorld); + } + worldToLocal(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(_m1$3.copy(this.matrixWorld).invert()); + } + lookAt(x2, y, z) { + if (x2.isVector3) { + _target3.copy(x2); + } else { + _target3.set(x2, y, z); + } + const parent2 = this.parent; + this.updateWorldMatrix(true, false); + _position$32.setFromMatrixPosition(this.matrixWorld); + if (this.isCamera || this.isLight) { + _m1$3.lookAt(_position$32, _target3, this.up); + } else { + _m1$3.lookAt(_target3, _position$32, this.up); + } + this.quaternion.setFromRotationMatrix(_m1$3); + if (parent2) { + _m1$3.extractRotation(parent2.matrixWorld); + _q12.setFromRotationMatrix(_m1$3); + this.quaternion.premultiply(_q12.invert()); + } + } + add(object) { + if (arguments.length > 1) { + for (let i = 0;i < arguments.length; i++) { + this.add(arguments[i]); + } + return this; + } + if (object === this) { + console.error("THREE.Object3D.add: object can't be added as a child of itself.", object); + return this; + } + if (object && object.isObject3D) { + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.dispatchEvent(_addedEvent2); + _childaddedEvent2.child = object; + this.dispatchEvent(_childaddedEvent2); + _childaddedEvent2.child = null; + } else { + console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object); + } + return this; + } + remove(object) { + if (arguments.length > 1) { + for (let i = 0;i < arguments.length; i++) { + this.remove(arguments[i]); + } + return this; + } + const index2 = this.children.indexOf(object); + if (index2 !== -1) { + object.parent = null; + this.children.splice(index2, 1); + object.dispatchEvent(_removedEvent2); + _childremovedEvent2.child = object; + this.dispatchEvent(_childremovedEvent2); + _childremovedEvent2.child = null; + } + return this; + } + removeFromParent() { + const parent2 = this.parent; + if (parent2 !== null) { + parent2.remove(this); + } + return this; + } + clear() { + return this.remove(...this.children); + } + attach(object) { + this.updateWorldMatrix(true, false); + _m1$3.copy(this.matrixWorld).invert(); + if (object.parent !== null) { + object.parent.updateWorldMatrix(true, false); + _m1$3.multiply(object.parent.matrixWorld); + } + object.applyMatrix4(_m1$3); + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.updateWorldMatrix(false, true); + object.dispatchEvent(_addedEvent2); + _childaddedEvent2.child = object; + this.dispatchEvent(_childaddedEvent2); + _childaddedEvent2.child = null; + return this; + } + getObjectById(id) { + return this.getObjectByProperty("id", id); + } + getObjectByName(name2) { + return this.getObjectByProperty("name", name2); + } + getObjectByProperty(name2, value2) { + if (this[name2] === value2) + return this; + for (let i = 0, l2 = this.children.length;i < l2; i++) { + const child = this.children[i]; + const object = child.getObjectByProperty(name2, value2); + if (object !== undefined) { + return object; + } + } + return; + } + getObjectsByProperty(name2, value2, result = []) { + if (this[name2] === value2) + result.push(this); + const children = this.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + children[i].getObjectsByProperty(name2, value2, result); + } + return result; + } + getWorldPosition(target) { + this.updateWorldMatrix(true, false); + return target.setFromMatrixPosition(this.matrixWorld); + } + getWorldQuaternion(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$32, target, _scale$22); + return target; + } + getWorldScale(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$32, _quaternion$22, target); + return target; + } + getWorldDirection(target) { + this.updateWorldMatrix(true, false); + const e = this.matrixWorld.elements; + return target.set(e[8], e[9], e[10]).normalize(); + } + raycast() { + } + traverse(callback) { + callback(this); + const children = this.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + children[i].traverse(callback); + } + } + traverseVisible(callback) { + if (this.visible === false) + return; + callback(this); + const children = this.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + children[i].traverseVisible(callback); + } + } + traverseAncestors(callback) { + const parent2 = this.parent; + if (parent2 !== null) { + callback(parent2); + parent2.traverseAncestors(callback); + } + } + updateMatrix() { + this.matrix.compose(this.position, this.quaternion, this.scale); + this.matrixWorldNeedsUpdate = true; + } + updateMatrixWorld(force) { + if (this.matrixAutoUpdate) + this.updateMatrix(); + if (this.matrixWorldNeedsUpdate || force) { + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + this.matrixWorldNeedsUpdate = false; + force = true; + } + const children = this.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + const child = children[i]; + child.updateMatrixWorld(force); + } + } + updateWorldMatrix(updateParents, updateChildren) { + const parent2 = this.parent; + if (updateParents === true && parent2 !== null) { + parent2.updateWorldMatrix(true, false); + } + if (this.matrixAutoUpdate) + this.updateMatrix(); + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + if (updateChildren === true) { + const children = this.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + const child = children[i]; + child.updateWorldMatrix(false, true); + } + } + } + toJSON(meta2) { + const isRootObject = meta2 === undefined || typeof meta2 === "string"; + const output = {}; + if (isRootObject) { + meta2 = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + output.metadata = { + version: 4.6, + type: "Object", + generator: "Object3D.toJSON" + }; + } + const object = {}; + object.uuid = this.uuid; + object.type = this.type; + if (this.name !== "") + object.name = this.name; + if (this.castShadow === true) + object.castShadow = true; + if (this.receiveShadow === true) + object.receiveShadow = true; + if (this.visible === false) + object.visible = false; + if (this.frustumCulled === false) + object.frustumCulled = false; + if (this.renderOrder !== 0) + object.renderOrder = this.renderOrder; + if (Object.keys(this.userData).length > 0) + object.userData = this.userData; + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + object.up = this.up.toArray(); + if (this.matrixAutoUpdate === false) + object.matrixAutoUpdate = false; + if (this.isInstancedMesh) { + object.type = "InstancedMesh"; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if (this.instanceColor !== null) + object.instanceColor = this.instanceColor.toJSON(); + } + if (this.isBatchedMesh) { + object.type = "BatchedMesh"; + object.perObjectFrustumCulled = this.perObjectFrustumCulled; + object.sortObjects = this.sortObjects; + object.drawRanges = this._drawRanges; + object.reservedRanges = this._reservedRanges; + object.visibility = this._visibility; + object.active = this._active; + object.bounds = this._bounds.map((bound) => ({ + boxInitialized: bound.boxInitialized, + boxMin: bound.box.min.toArray(), + boxMax: bound.box.max.toArray(), + sphereInitialized: bound.sphereInitialized, + sphereRadius: bound.sphere.radius, + sphereCenter: bound.sphere.center.toArray() + })); + object.maxInstanceCount = this._maxInstanceCount; + object.maxVertexCount = this._maxVertexCount; + object.maxIndexCount = this._maxIndexCount; + object.geometryInitialized = this._geometryInitialized; + object.geometryCount = this._geometryCount; + object.matricesTexture = this._matricesTexture.toJSON(meta2); + if (this._colorsTexture !== null) + object.colorsTexture = this._colorsTexture.toJSON(meta2); + if (this.boundingSphere !== null) { + object.boundingSphere = { + center: object.boundingSphere.center.toArray(), + radius: object.boundingSphere.radius + }; + } + if (this.boundingBox !== null) { + object.boundingBox = { + min: object.boundingBox.min.toArray(), + max: object.boundingBox.max.toArray() + }; + } + } + function serialize(library, element) { + if (library[element.uuid] === undefined) { + library[element.uuid] = element.toJSON(meta2); + } + return element.uuid; + } + if (this.isScene) { + if (this.background) { + if (this.background.isColor) { + object.background = this.background.toJSON(); + } else if (this.background.isTexture) { + object.background = this.background.toJSON(meta2).uuid; + } + } + if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) { + object.environment = this.environment.toJSON(meta2).uuid; + } + } else if (this.isMesh || this.isLine || this.isPoints) { + object.geometry = serialize(meta2.geometries, this.geometry); + const parameters = this.geometry.parameters; + if (parameters !== undefined && parameters.shapes !== undefined) { + const shapes = parameters.shapes; + if (Array.isArray(shapes)) { + for (let i = 0, l2 = shapes.length;i < l2; i++) { + const shape = shapes[i]; + serialize(meta2.shapes, shape); + } + } else { + serialize(meta2.shapes, shapes); + } + } + } + if (this.isSkinnedMesh) { + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + if (this.skeleton !== undefined) { + serialize(meta2.skeletons, this.skeleton); + object.skeleton = this.skeleton.uuid; + } + } + if (this.material !== undefined) { + if (Array.isArray(this.material)) { + const uuids = []; + for (let i = 0, l2 = this.material.length;i < l2; i++) { + uuids.push(serialize(meta2.materials, this.material[i])); + } + object.material = uuids; + } else { + object.material = serialize(meta2.materials, this.material); + } + } + if (this.children.length > 0) { + object.children = []; + for (let i = 0;i < this.children.length; i++) { + object.children.push(this.children[i].toJSON(meta2).object); + } + } + if (this.animations.length > 0) { + object.animations = []; + for (let i = 0;i < this.animations.length; i++) { + const animation = this.animations[i]; + object.animations.push(serialize(meta2.animations, animation)); + } + } + if (isRootObject) { + const geometries = extractFromCache(meta2.geometries); + const materials = extractFromCache(meta2.materials); + const textures = extractFromCache(meta2.textures); + const images = extractFromCache(meta2.images); + const shapes = extractFromCache(meta2.shapes); + const skeletons = extractFromCache(meta2.skeletons); + const animations = extractFromCache(meta2.animations); + const nodes = extractFromCache(meta2.nodes); + if (geometries.length > 0) + output.geometries = geometries; + if (materials.length > 0) + output.materials = materials; + if (textures.length > 0) + output.textures = textures; + if (images.length > 0) + output.images = images; + if (shapes.length > 0) + output.shapes = shapes; + if (skeletons.length > 0) + output.skeletons = skeletons; + if (animations.length > 0) + output.animations = animations; + if (nodes.length > 0) + output.nodes = nodes; + } + output.object = object; + return output; + function extractFromCache(cache) { + const values2 = []; + for (const key2 in cache) { + const data2 = cache[key2]; + delete data2.metadata; + values2.push(data2); + } + return values2; + } + } + clone(recursive) { + return new this.constructor().copy(this, recursive); + } + copy(source, recursive = true) { + this.name = source.name; + this.up.copy(source.up); + this.position.copy(source.position); + this.rotation.order = source.rotation.order; + this.quaternion.copy(source.quaternion); + this.scale.copy(source.scale); + this.matrix.copy(source.matrix); + this.matrixWorld.copy(source.matrixWorld); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + this.layers.mask = source.layers.mask; + this.visible = source.visible; + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + this.animations = source.animations.slice(); + this.userData = JSON.parse(JSON.stringify(source.userData)); + if (recursive === true) { + for (let i = 0;i < source.children.length; i++) { + const child = source.children[i]; + this.add(child.clone()); + } + } + return this; + } + } + Object3D2.DEFAULT_UP = /* @__PURE__ */ new Vector32(0, 1, 0); + Object3D2.DEFAULT_MATRIX_AUTO_UPDATE = true; + Object3D2.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; + var _v0$22 = /* @__PURE__ */ new Vector32; + var _v1$32 = /* @__PURE__ */ new Vector32; + var _v2$22 = /* @__PURE__ */ new Vector32; + var _v3$22 = /* @__PURE__ */ new Vector32; + var _vab2 = /* @__PURE__ */ new Vector32; + var _vac2 = /* @__PURE__ */ new Vector32; + var _vbc2 = /* @__PURE__ */ new Vector32; + var _vap2 = /* @__PURE__ */ new Vector32; + var _vbp2 = /* @__PURE__ */ new Vector32; + var _vcp2 = /* @__PURE__ */ new Vector32; + var _v402 = /* @__PURE__ */ new Vector42; + var _v412 = /* @__PURE__ */ new Vector42; + var _v422 = /* @__PURE__ */ new Vector42; + + class Triangle2 { + constructor(a2 = new Vector32, b2 = new Vector32, c2 = new Vector32) { + this.a = a2; + this.b = b2; + this.c = c2; + } + static getNormal(a2, b2, c2, target) { + target.subVectors(c2, b2); + _v0$22.subVectors(a2, b2); + target.cross(_v0$22); + const targetLengthSq = target.lengthSq(); + if (targetLengthSq > 0) { + return target.multiplyScalar(1 / Math.sqrt(targetLengthSq)); + } + return target.set(0, 0, 0); + } + static getBarycoord(point, a2, b2, c2, target) { + _v0$22.subVectors(c2, a2); + _v1$32.subVectors(b2, a2); + _v2$22.subVectors(point, a2); + const dot00 = _v0$22.dot(_v0$22); + const dot01 = _v0$22.dot(_v1$32); + const dot02 = _v0$22.dot(_v2$22); + const dot11 = _v1$32.dot(_v1$32); + const dot12 = _v1$32.dot(_v2$22); + const denom = dot00 * dot11 - dot01 * dot01; + if (denom === 0) { + target.set(0, 0, 0); + return null; + } + const invDenom = 1 / denom; + const u2 = (dot11 * dot02 - dot01 * dot12) * invDenom; + const v = (dot00 * dot12 - dot01 * dot02) * invDenom; + return target.set(1 - u2 - v, v, u2); + } + static containsPoint(point, a2, b2, c2) { + if (this.getBarycoord(point, a2, b2, c2, _v3$22) === null) { + return false; + } + return _v3$22.x >= 0 && _v3$22.y >= 0 && _v3$22.x + _v3$22.y <= 1; + } + static getInterpolation(point, p1, p2, p3, v12, v2, v3, target) { + if (this.getBarycoord(point, p1, p2, p3, _v3$22) === null) { + target.x = 0; + target.y = 0; + if ("z" in target) + target.z = 0; + if ("w" in target) + target.w = 0; + return null; + } + target.setScalar(0); + target.addScaledVector(v12, _v3$22.x); + target.addScaledVector(v2, _v3$22.y); + target.addScaledVector(v3, _v3$22.z); + return target; + } + static getInterpolatedAttribute(attr, i1, i2, i3, barycoord, target) { + _v402.setScalar(0); + _v412.setScalar(0); + _v422.setScalar(0); + _v402.fromBufferAttribute(attr, i1); + _v412.fromBufferAttribute(attr, i2); + _v422.fromBufferAttribute(attr, i3); + target.setScalar(0); + target.addScaledVector(_v402, barycoord.x); + target.addScaledVector(_v412, barycoord.y); + target.addScaledVector(_v422, barycoord.z); + return target; + } + static isFrontFacing(a2, b2, c2, direction) { + _v0$22.subVectors(c2, b2); + _v1$32.subVectors(a2, b2); + return _v0$22.cross(_v1$32).dot(direction) < 0 ? true : false; + } + set(a2, b2, c2) { + this.a.copy(a2); + this.b.copy(b2); + this.c.copy(c2); + return this; + } + setFromPointsAndIndices(points, i0, i1, i2) { + this.a.copy(points[i0]); + this.b.copy(points[i1]); + this.c.copy(points[i2]); + return this; + } + setFromAttributeAndIndices(attribute, i0, i1, i2) { + this.a.fromBufferAttribute(attribute, i0); + this.b.fromBufferAttribute(attribute, i1); + this.c.fromBufferAttribute(attribute, i2); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(triangle) { + this.a.copy(triangle.a); + this.b.copy(triangle.b); + this.c.copy(triangle.c); + return this; + } + getArea() { + _v0$22.subVectors(this.c, this.b); + _v1$32.subVectors(this.a, this.b); + return _v0$22.cross(_v1$32).length() * 0.5; + } + getMidpoint(target) { + return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); + } + getNormal(target) { + return Triangle2.getNormal(this.a, this.b, this.c, target); + } + getPlane(target) { + return target.setFromCoplanarPoints(this.a, this.b, this.c); + } + getBarycoord(point, target) { + return Triangle2.getBarycoord(point, this.a, this.b, this.c, target); + } + getInterpolation(point, v12, v2, v3, target) { + return Triangle2.getInterpolation(point, this.a, this.b, this.c, v12, v2, v3, target); + } + containsPoint(point) { + return Triangle2.containsPoint(point, this.a, this.b, this.c); + } + isFrontFacing(direction) { + return Triangle2.isFrontFacing(this.a, this.b, this.c, direction); + } + intersectsBox(box) { + return box.intersectsTriangle(this); + } + closestPointToPoint(p, target) { + const a2 = this.a, b2 = this.b, c2 = this.c; + let v, w; + _vab2.subVectors(b2, a2); + _vac2.subVectors(c2, a2); + _vap2.subVectors(p, a2); + const d1 = _vab2.dot(_vap2); + const d2 = _vac2.dot(_vap2); + if (d1 <= 0 && d2 <= 0) { + return target.copy(a2); + } + _vbp2.subVectors(p, b2); + const d3 = _vab2.dot(_vbp2); + const d4 = _vac2.dot(_vbp2); + if (d3 >= 0 && d4 <= d3) { + return target.copy(b2); + } + const vc = d1 * d4 - d3 * d2; + if (vc <= 0 && d1 >= 0 && d3 <= 0) { + v = d1 / (d1 - d3); + return target.copy(a2).addScaledVector(_vab2, v); + } + _vcp2.subVectors(p, c2); + const d5 = _vab2.dot(_vcp2); + const d6 = _vac2.dot(_vcp2); + if (d6 >= 0 && d5 <= d6) { + return target.copy(c2); + } + const vb = d5 * d2 - d1 * d6; + if (vb <= 0 && d2 >= 0 && d6 <= 0) { + w = d2 / (d2 - d6); + return target.copy(a2).addScaledVector(_vac2, w); + } + const va2 = d3 * d6 - d5 * d4; + if (va2 <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { + _vbc2.subVectors(c2, b2); + w = (d4 - d3) / (d4 - d3 + (d5 - d6)); + return target.copy(b2).addScaledVector(_vbc2, w); + } + const denom = 1 / (va2 + vb + vc); + v = vb * denom; + w = vc * denom; + return target.copy(a2).addScaledVector(_vab2, v).addScaledVector(_vac2, w); + } + equals(triangle) { + return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c); + } + } + var _colorKeywords2 = { + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + rebeccapurple: 6697881, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 + }; + var _hslA2 = { h: 0, s: 0, l: 0 }; + var _hslB2 = { h: 0, s: 0, l: 0 }; + function hue2rgb3(p, q2, t3) { + if (t3 < 0) + t3 += 1; + if (t3 > 1) + t3 -= 1; + if (t3 < 1 / 6) + return p + (q2 - p) * 6 * t3; + if (t3 < 1 / 2) + return q2; + if (t3 < 2 / 3) + return p + (q2 - p) * 6 * (2 / 3 - t3); + return p; + } + + class Color2 { + constructor(r, g3, b2) { + this.isColor = true; + this.r = 1; + this.g = 1; + this.b = 1; + return this.set(r, g3, b2); + } + set(r, g3, b2) { + if (g3 === undefined && b2 === undefined) { + const value2 = r; + if (value2 && value2.isColor) { + this.copy(value2); + } else if (typeof value2 === "number") { + this.setHex(value2); + } else if (typeof value2 === "string") { + this.setStyle(value2); + } + } else { + this.setRGB(r, g3, b2); + } + return this; + } + setScalar(scalar) { + this.r = scalar; + this.g = scalar; + this.b = scalar; + return this; + } + setHex(hex, colorSpace = SRGBColorSpace2) { + hex = Math.floor(hex); + this.r = (hex >> 16 & 255) / 255; + this.g = (hex >> 8 & 255) / 255; + this.b = (hex & 255) / 255; + ColorManagement2.toWorkingColorSpace(this, colorSpace); + return this; + } + setRGB(r, g3, b2, colorSpace = ColorManagement2.workingColorSpace) { + this.r = r; + this.g = g3; + this.b = b2; + ColorManagement2.toWorkingColorSpace(this, colorSpace); + return this; + } + setHSL(h, s, l2, colorSpace = ColorManagement2.workingColorSpace) { + h = euclideanModulo2(h, 1); + s = clamp3(s, 0, 1); + l2 = clamp3(l2, 0, 1); + if (s === 0) { + this.r = this.g = this.b = l2; + } else { + const p = l2 <= 0.5 ? l2 * (1 + s) : l2 + s - l2 * s; + const q2 = 2 * l2 - p; + this.r = hue2rgb3(q2, p, h + 1 / 3); + this.g = hue2rgb3(q2, p, h); + this.b = hue2rgb3(q2, p, h - 1 / 3); + } + ColorManagement2.toWorkingColorSpace(this, colorSpace); + return this; + } + setStyle(style, colorSpace = SRGBColorSpace2) { + function handleAlpha(string) { + if (string === undefined) + return; + if (parseFloat(string) < 1) { + console.warn("THREE.Color: Alpha component of " + style + " will be ignored."); + } + } + let m; + if (m = /^(\w+)\(([^\)]*)\)/.exec(style)) { + let color; + const name2 = m[1]; + const components = m[2]; + switch (name2) { + case "rgb": + case "rgba": + if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB(Math.min(255, parseInt(color[1], 10)) / 255, Math.min(255, parseInt(color[2], 10)) / 255, Math.min(255, parseInt(color[3], 10)) / 255, colorSpace); + } + if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB(Math.min(100, parseInt(color[1], 10)) / 100, Math.min(100, parseInt(color[2], 10)) / 100, Math.min(100, parseInt(color[3], 10)) / 100, colorSpace); + } + break; + case "hsl": + case "hsla": + if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setHSL(parseFloat(color[1]) / 360, parseFloat(color[2]) / 100, parseFloat(color[3]) / 100, colorSpace); + } + break; + default: + console.warn("THREE.Color: Unknown color model " + style); + } + } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) { + const hex = m[1]; + const size2 = hex.length; + if (size2 === 3) { + return this.setRGB(parseInt(hex.charAt(0), 16) / 15, parseInt(hex.charAt(1), 16) / 15, parseInt(hex.charAt(2), 16) / 15, colorSpace); + } else if (size2 === 6) { + return this.setHex(parseInt(hex, 16), colorSpace); + } else { + console.warn("THREE.Color: Invalid hex color " + style); + } + } else if (style && style.length > 0) { + return this.setColorName(style, colorSpace); + } + return this; + } + setColorName(style, colorSpace = SRGBColorSpace2) { + const hex = _colorKeywords2[style.toLowerCase()]; + if (hex !== undefined) { + this.setHex(hex, colorSpace); + } else { + console.warn("THREE.Color: Unknown color " + style); + } + return this; + } + clone() { + return new this.constructor(this.r, this.g, this.b); + } + copy(color) { + this.r = color.r; + this.g = color.g; + this.b = color.b; + return this; + } + copySRGBToLinear(color) { + this.r = SRGBToLinear2(color.r); + this.g = SRGBToLinear2(color.g); + this.b = SRGBToLinear2(color.b); + return this; + } + copyLinearToSRGB(color) { + this.r = LinearToSRGB2(color.r); + this.g = LinearToSRGB2(color.g); + this.b = LinearToSRGB2(color.b); + return this; + } + convertSRGBToLinear() { + this.copySRGBToLinear(this); + return this; + } + convertLinearToSRGB() { + this.copyLinearToSRGB(this); + return this; + } + getHex(colorSpace = SRGBColorSpace2) { + ColorManagement2.fromWorkingColorSpace(_color4.copy(this), colorSpace); + return Math.round(clamp3(_color4.r * 255, 0, 255)) * 65536 + Math.round(clamp3(_color4.g * 255, 0, 255)) * 256 + Math.round(clamp3(_color4.b * 255, 0, 255)); + } + getHexString(colorSpace = SRGBColorSpace2) { + return ("000000" + this.getHex(colorSpace).toString(16)).slice(-6); + } + getHSL(target, colorSpace = ColorManagement2.workingColorSpace) { + ColorManagement2.fromWorkingColorSpace(_color4.copy(this), colorSpace); + const { r, g: g3, b: b2 } = _color4; + const max = Math.max(r, g3, b2); + const min = Math.min(r, g3, b2); + let hue, saturation; + const lightness = (min + max) / 2; + if (min === max) { + hue = 0; + saturation = 0; + } else { + const delta = max - min; + saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min); + switch (max) { + case r: + hue = (g3 - b2) / delta + (g3 < b2 ? 6 : 0); + break; + case g3: + hue = (b2 - r) / delta + 2; + break; + case b2: + hue = (r - g3) / delta + 4; + break; + } + hue /= 6; + } + target.h = hue; + target.s = saturation; + target.l = lightness; + return target; + } + getRGB(target, colorSpace = ColorManagement2.workingColorSpace) { + ColorManagement2.fromWorkingColorSpace(_color4.copy(this), colorSpace); + target.r = _color4.r; + target.g = _color4.g; + target.b = _color4.b; + return target; + } + getStyle(colorSpace = SRGBColorSpace2) { + ColorManagement2.fromWorkingColorSpace(_color4.copy(this), colorSpace); + const { r, g: g3, b: b2 } = _color4; + if (colorSpace !== SRGBColorSpace2) { + return `color(${colorSpace} ${r.toFixed(3)} ${g3.toFixed(3)} ${b2.toFixed(3)})`; + } + return `rgb(${Math.round(r * 255)},${Math.round(g3 * 255)},${Math.round(b2 * 255)})`; + } + offsetHSL(h, s, l2) { + this.getHSL(_hslA2); + return this.setHSL(_hslA2.h + h, _hslA2.s + s, _hslA2.l + l2); + } + add(color) { + this.r += color.r; + this.g += color.g; + this.b += color.b; + return this; + } + addColors(color1, color2) { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + return this; + } + addScalar(s) { + this.r += s; + this.g += s; + this.b += s; + return this; + } + sub(color) { + this.r = Math.max(0, this.r - color.r); + this.g = Math.max(0, this.g - color.g); + this.b = Math.max(0, this.b - color.b); + return this; + } + multiply(color) { + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + return this; + } + multiplyScalar(s) { + this.r *= s; + this.g *= s; + this.b *= s; + return this; + } + lerp(color, alpha) { + this.r += (color.r - this.r) * alpha; + this.g += (color.g - this.g) * alpha; + this.b += (color.b - this.b) * alpha; + return this; + } + lerpColors(color1, color2, alpha) { + this.r = color1.r + (color2.r - color1.r) * alpha; + this.g = color1.g + (color2.g - color1.g) * alpha; + this.b = color1.b + (color2.b - color1.b) * alpha; + return this; + } + lerpHSL(color, alpha) { + this.getHSL(_hslA2); + color.getHSL(_hslB2); + const h = lerp2(_hslA2.h, _hslB2.h, alpha); + const s = lerp2(_hslA2.s, _hslB2.s, alpha); + const l2 = lerp2(_hslA2.l, _hslB2.l, alpha); + this.setHSL(h, s, l2); + return this; + } + setFromVector3(v) { + this.r = v.x; + this.g = v.y; + this.b = v.z; + return this; + } + applyMatrix3(m) { + const r = this.r, g3 = this.g, b2 = this.b; + const e = m.elements; + this.r = e[0] * r + e[3] * g3 + e[6] * b2; + this.g = e[1] * r + e[4] * g3 + e[7] * b2; + this.b = e[2] * r + e[5] * g3 + e[8] * b2; + return this; + } + equals(c2) { + return c2.r === this.r && c2.g === this.g && c2.b === this.b; + } + fromArray(array, offset = 0) { + this.r = array[offset]; + this.g = array[offset + 1]; + this.b = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.r; + array[offset + 1] = this.g; + array[offset + 2] = this.b; + return array; + } + fromBufferAttribute(attribute, index2) { + this.r = attribute.getX(index2); + this.g = attribute.getY(index2); + this.b = attribute.getZ(index2); + return this; + } + toJSON() { + return this.getHex(); + } + *[Symbol.iterator]() { + yield this.r; + yield this.g; + yield this.b; + } + } + var _color4 = /* @__PURE__ */ new Color2; + Color2.NAMES = _colorKeywords2; + var _materialId2 = 0; + + class Material2 extends EventDispatcher2 { + constructor() { + super(); + this.isMaterial = true; + Object.defineProperty(this, "id", { value: _materialId2++ }); + this.uuid = generateUUID2(); + this.name = ""; + this.type = "Material"; + this.blending = NormalBlending2; + this.side = FrontSide2; + this.vertexColors = false; + this.opacity = 1; + this.transparent = false; + this.alphaHash = false; + this.blendSrc = SrcAlphaFactor2; + this.blendDst = OneMinusSrcAlphaFactor2; + this.blendEquation = AddEquation2; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; + this.blendColor = new Color2(0, 0, 0); + this.blendAlpha = 0; + this.depthFunc = LessEqualDepth2; + this.depthTest = true; + this.depthWrite = true; + this.stencilWriteMask = 255; + this.stencilFunc = AlwaysStencilFunc2; + this.stencilRef = 0; + this.stencilFuncMask = 255; + this.stencilFail = KeepStencilOp2; + this.stencilZFail = KeepStencilOp2; + this.stencilZPass = KeepStencilOp2; + this.stencilWrite = false; + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + this.shadowSide = null; + this.colorWrite = true; + this.precision = null; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + this.dithering = false; + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + this.forceSinglePass = false; + this.visible = true; + this.toneMapped = true; + this.userData = {}; + this.version = 0; + this._alphaTest = 0; + } + get alphaTest() { + return this._alphaTest; + } + set alphaTest(value2) { + if (this._alphaTest > 0 !== value2 > 0) { + this.version++; + } + this._alphaTest = value2; + } + onBeforeRender() { + } + onBeforeCompile() { + } + customProgramCacheKey() { + return this.onBeforeCompile.toString(); + } + setValues(values2) { + if (values2 === undefined) + return; + for (const key2 in values2) { + const newValue = values2[key2]; + if (newValue === undefined) { + console.warn(`THREE.Material: parameter '${key2}' has value of undefined.`); + continue; + } + const currentValue = this[key2]; + if (currentValue === undefined) { + console.warn(`THREE.Material: '${key2}' is not a property of THREE.${this.type}.`); + continue; + } + if (currentValue && currentValue.isColor) { + currentValue.set(newValue); + } else if (currentValue && currentValue.isVector3 && (newValue && newValue.isVector3)) { + currentValue.copy(newValue); + } else { + this[key2] = newValue; + } + } + } + toJSON(meta2) { + const isRootObject = meta2 === undefined || typeof meta2 === "string"; + if (isRootObject) { + meta2 = { + textures: {}, + images: {} + }; + } + const data2 = { + metadata: { + version: 4.6, + type: "Material", + generator: "Material.toJSON" + } + }; + data2.uuid = this.uuid; + data2.type = this.type; + if (this.name !== "") + data2.name = this.name; + if (this.color && this.color.isColor) + data2.color = this.color.getHex(); + if (this.roughness !== undefined) + data2.roughness = this.roughness; + if (this.metalness !== undefined) + data2.metalness = this.metalness; + if (this.sheen !== undefined) + data2.sheen = this.sheen; + if (this.sheenColor && this.sheenColor.isColor) + data2.sheenColor = this.sheenColor.getHex(); + if (this.sheenRoughness !== undefined) + data2.sheenRoughness = this.sheenRoughness; + if (this.emissive && this.emissive.isColor) + data2.emissive = this.emissive.getHex(); + if (this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1) + data2.emissiveIntensity = this.emissiveIntensity; + if (this.specular && this.specular.isColor) + data2.specular = this.specular.getHex(); + if (this.specularIntensity !== undefined) + data2.specularIntensity = this.specularIntensity; + if (this.specularColor && this.specularColor.isColor) + data2.specularColor = this.specularColor.getHex(); + if (this.shininess !== undefined) + data2.shininess = this.shininess; + if (this.clearcoat !== undefined) + data2.clearcoat = this.clearcoat; + if (this.clearcoatRoughness !== undefined) + data2.clearcoatRoughness = this.clearcoatRoughness; + if (this.clearcoatMap && this.clearcoatMap.isTexture) { + data2.clearcoatMap = this.clearcoatMap.toJSON(meta2).uuid; + } + if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) { + data2.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta2).uuid; + } + if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) { + data2.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta2).uuid; + data2.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + } + if (this.dispersion !== undefined) + data2.dispersion = this.dispersion; + if (this.iridescence !== undefined) + data2.iridescence = this.iridescence; + if (this.iridescenceIOR !== undefined) + data2.iridescenceIOR = this.iridescenceIOR; + if (this.iridescenceThicknessRange !== undefined) + data2.iridescenceThicknessRange = this.iridescenceThicknessRange; + if (this.iridescenceMap && this.iridescenceMap.isTexture) { + data2.iridescenceMap = this.iridescenceMap.toJSON(meta2).uuid; + } + if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) { + data2.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta2).uuid; + } + if (this.anisotropy !== undefined) + data2.anisotropy = this.anisotropy; + if (this.anisotropyRotation !== undefined) + data2.anisotropyRotation = this.anisotropyRotation; + if (this.anisotropyMap && this.anisotropyMap.isTexture) { + data2.anisotropyMap = this.anisotropyMap.toJSON(meta2).uuid; + } + if (this.map && this.map.isTexture) + data2.map = this.map.toJSON(meta2).uuid; + if (this.matcap && this.matcap.isTexture) + data2.matcap = this.matcap.toJSON(meta2).uuid; + if (this.alphaMap && this.alphaMap.isTexture) + data2.alphaMap = this.alphaMap.toJSON(meta2).uuid; + if (this.lightMap && this.lightMap.isTexture) { + data2.lightMap = this.lightMap.toJSON(meta2).uuid; + data2.lightMapIntensity = this.lightMapIntensity; + } + if (this.aoMap && this.aoMap.isTexture) { + data2.aoMap = this.aoMap.toJSON(meta2).uuid; + data2.aoMapIntensity = this.aoMapIntensity; + } + if (this.bumpMap && this.bumpMap.isTexture) { + data2.bumpMap = this.bumpMap.toJSON(meta2).uuid; + data2.bumpScale = this.bumpScale; + } + if (this.normalMap && this.normalMap.isTexture) { + data2.normalMap = this.normalMap.toJSON(meta2).uuid; + data2.normalMapType = this.normalMapType; + data2.normalScale = this.normalScale.toArray(); + } + if (this.displacementMap && this.displacementMap.isTexture) { + data2.displacementMap = this.displacementMap.toJSON(meta2).uuid; + data2.displacementScale = this.displacementScale; + data2.displacementBias = this.displacementBias; + } + if (this.roughnessMap && this.roughnessMap.isTexture) + data2.roughnessMap = this.roughnessMap.toJSON(meta2).uuid; + if (this.metalnessMap && this.metalnessMap.isTexture) + data2.metalnessMap = this.metalnessMap.toJSON(meta2).uuid; + if (this.emissiveMap && this.emissiveMap.isTexture) + data2.emissiveMap = this.emissiveMap.toJSON(meta2).uuid; + if (this.specularMap && this.specularMap.isTexture) + data2.specularMap = this.specularMap.toJSON(meta2).uuid; + if (this.specularIntensityMap && this.specularIntensityMap.isTexture) + data2.specularIntensityMap = this.specularIntensityMap.toJSON(meta2).uuid; + if (this.specularColorMap && this.specularColorMap.isTexture) + data2.specularColorMap = this.specularColorMap.toJSON(meta2).uuid; + if (this.envMap && this.envMap.isTexture) { + data2.envMap = this.envMap.toJSON(meta2).uuid; + if (this.combine !== undefined) + data2.combine = this.combine; + } + if (this.envMapRotation !== undefined) + data2.envMapRotation = this.envMapRotation.toArray(); + if (this.envMapIntensity !== undefined) + data2.envMapIntensity = this.envMapIntensity; + if (this.reflectivity !== undefined) + data2.reflectivity = this.reflectivity; + if (this.refractionRatio !== undefined) + data2.refractionRatio = this.refractionRatio; + if (this.gradientMap && this.gradientMap.isTexture) { + data2.gradientMap = this.gradientMap.toJSON(meta2).uuid; + } + if (this.transmission !== undefined) + data2.transmission = this.transmission; + if (this.transmissionMap && this.transmissionMap.isTexture) + data2.transmissionMap = this.transmissionMap.toJSON(meta2).uuid; + if (this.thickness !== undefined) + data2.thickness = this.thickness; + if (this.thicknessMap && this.thicknessMap.isTexture) + data2.thicknessMap = this.thicknessMap.toJSON(meta2).uuid; + if (this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity) + data2.attenuationDistance = this.attenuationDistance; + if (this.attenuationColor !== undefined) + data2.attenuationColor = this.attenuationColor.getHex(); + if (this.size !== undefined) + data2.size = this.size; + if (this.shadowSide !== null) + data2.shadowSide = this.shadowSide; + if (this.sizeAttenuation !== undefined) + data2.sizeAttenuation = this.sizeAttenuation; + if (this.blending !== NormalBlending2) + data2.blending = this.blending; + if (this.side !== FrontSide2) + data2.side = this.side; + if (this.vertexColors === true) + data2.vertexColors = true; + if (this.opacity < 1) + data2.opacity = this.opacity; + if (this.transparent === true) + data2.transparent = true; + if (this.blendSrc !== SrcAlphaFactor2) + data2.blendSrc = this.blendSrc; + if (this.blendDst !== OneMinusSrcAlphaFactor2) + data2.blendDst = this.blendDst; + if (this.blendEquation !== AddEquation2) + data2.blendEquation = this.blendEquation; + if (this.blendSrcAlpha !== null) + data2.blendSrcAlpha = this.blendSrcAlpha; + if (this.blendDstAlpha !== null) + data2.blendDstAlpha = this.blendDstAlpha; + if (this.blendEquationAlpha !== null) + data2.blendEquationAlpha = this.blendEquationAlpha; + if (this.blendColor && this.blendColor.isColor) + data2.blendColor = this.blendColor.getHex(); + if (this.blendAlpha !== 0) + data2.blendAlpha = this.blendAlpha; + if (this.depthFunc !== LessEqualDepth2) + data2.depthFunc = this.depthFunc; + if (this.depthTest === false) + data2.depthTest = this.depthTest; + if (this.depthWrite === false) + data2.depthWrite = this.depthWrite; + if (this.colorWrite === false) + data2.colorWrite = this.colorWrite; + if (this.stencilWriteMask !== 255) + data2.stencilWriteMask = this.stencilWriteMask; + if (this.stencilFunc !== AlwaysStencilFunc2) + data2.stencilFunc = this.stencilFunc; + if (this.stencilRef !== 0) + data2.stencilRef = this.stencilRef; + if (this.stencilFuncMask !== 255) + data2.stencilFuncMask = this.stencilFuncMask; + if (this.stencilFail !== KeepStencilOp2) + data2.stencilFail = this.stencilFail; + if (this.stencilZFail !== KeepStencilOp2) + data2.stencilZFail = this.stencilZFail; + if (this.stencilZPass !== KeepStencilOp2) + data2.stencilZPass = this.stencilZPass; + if (this.stencilWrite === true) + data2.stencilWrite = this.stencilWrite; + if (this.rotation !== undefined && this.rotation !== 0) + data2.rotation = this.rotation; + if (this.polygonOffset === true) + data2.polygonOffset = true; + if (this.polygonOffsetFactor !== 0) + data2.polygonOffsetFactor = this.polygonOffsetFactor; + if (this.polygonOffsetUnits !== 0) + data2.polygonOffsetUnits = this.polygonOffsetUnits; + if (this.linewidth !== undefined && this.linewidth !== 1) + data2.linewidth = this.linewidth; + if (this.dashSize !== undefined) + data2.dashSize = this.dashSize; + if (this.gapSize !== undefined) + data2.gapSize = this.gapSize; + if (this.scale !== undefined) + data2.scale = this.scale; + if (this.dithering === true) + data2.dithering = true; + if (this.alphaTest > 0) + data2.alphaTest = this.alphaTest; + if (this.alphaHash === true) + data2.alphaHash = true; + if (this.alphaToCoverage === true) + data2.alphaToCoverage = true; + if (this.premultipliedAlpha === true) + data2.premultipliedAlpha = true; + if (this.forceSinglePass === true) + data2.forceSinglePass = true; + if (this.wireframe === true) + data2.wireframe = true; + if (this.wireframeLinewidth > 1) + data2.wireframeLinewidth = this.wireframeLinewidth; + if (this.wireframeLinecap !== "round") + data2.wireframeLinecap = this.wireframeLinecap; + if (this.wireframeLinejoin !== "round") + data2.wireframeLinejoin = this.wireframeLinejoin; + if (this.flatShading === true) + data2.flatShading = true; + if (this.visible === false) + data2.visible = false; + if (this.toneMapped === false) + data2.toneMapped = false; + if (this.fog === false) + data2.fog = false; + if (Object.keys(this.userData).length > 0) + data2.userData = this.userData; + function extractFromCache(cache) { + const values2 = []; + for (const key2 in cache) { + const data3 = cache[key2]; + delete data3.metadata; + values2.push(data3); + } + return values2; + } + if (isRootObject) { + const textures = extractFromCache(meta2.textures); + const images = extractFromCache(meta2.images); + if (textures.length > 0) + data2.textures = textures; + if (images.length > 0) + data2.images = images; + } + return data2; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + this.opacity = source.opacity; + this.transparent = source.transparent; + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + this.blendColor.copy(source.blendColor); + this.blendAlpha = source.blendAlpha; + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + if (srcPlanes !== null) { + const n2 = srcPlanes.length; + dstPlanes = new Array(n2); + for (let i = 0;i !== n2; ++i) { + dstPlanes[i] = srcPlanes[i].clone(); + } + } + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + this.shadowSide = source.shadowSide; + this.colorWrite = source.colorWrite; + this.precision = source.precision; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + this.dithering = source.dithering; + this.alphaTest = source.alphaTest; + this.alphaHash = source.alphaHash; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + this.forceSinglePass = source.forceSinglePass; + this.visible = source.visible; + this.toneMapped = source.toneMapped; + this.userData = JSON.parse(JSON.stringify(source.userData)); + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + onBuild() { + console.warn("Material: onBuild() has been removed."); + } + } + + class MeshBasicMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshBasicMaterial = true; + this.type = "MeshBasicMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler2; + this.combine = MultiplyOperation2; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } + } + var _tables2 = /* @__PURE__ */ _generateTables2(); + function _generateTables2() { + const buffer = new ArrayBuffer(4); + const floatView = new Float32Array(buffer); + const uint32View = new Uint32Array(buffer); + const baseTable = new Uint32Array(512); + const shiftTable = new Uint32Array(512); + for (let i = 0;i < 256; ++i) { + const e = i - 127; + if (e < -27) { + baseTable[i] = 0; + baseTable[i | 256] = 32768; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else if (e < -14) { + baseTable[i] = 1024 >> -e - 14; + baseTable[i | 256] = 1024 >> -e - 14 | 32768; + shiftTable[i] = -e - 1; + shiftTable[i | 256] = -e - 1; + } else if (e <= 15) { + baseTable[i] = e + 15 << 10; + baseTable[i | 256] = e + 15 << 10 | 32768; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } else if (e < 128) { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } + } + const mantissaTable = new Uint32Array(2048); + const exponentTable = new Uint32Array(64); + const offsetTable = new Uint32Array(64); + for (let i = 1;i < 1024; ++i) { + let m = i << 13; + let e = 0; + while ((m & 8388608) === 0) { + m <<= 1; + e -= 8388608; + } + m &= ~8388608; + e += 947912704; + mantissaTable[i] = m | e; + } + for (let i = 1024;i < 2048; ++i) { + mantissaTable[i] = 939524096 + (i - 1024 << 13); + } + for (let i = 1;i < 31; ++i) { + exponentTable[i] = i << 23; + } + exponentTable[31] = 1199570944; + exponentTable[32] = 2147483648; + for (let i = 33;i < 63; ++i) { + exponentTable[i] = 2147483648 + (i - 32 << 23); + } + exponentTable[63] = 3347054592; + for (let i = 1;i < 64; ++i) { + if (i !== 32) { + offsetTable[i] = 1024; + } + } + return { + floatView, + uint32View, + baseTable, + shiftTable, + mantissaTable, + exponentTable, + offsetTable + }; + } + function toHalfFloat2(val2) { + if (Math.abs(val2) > 65504) + console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."); + val2 = clamp3(val2, -65504, 65504); + _tables2.floatView[0] = val2; + const f = _tables2.uint32View[0]; + const e = f >> 23 & 511; + return _tables2.baseTable[e] + ((f & 8388607) >> _tables2.shiftTable[e]); + } + function fromHalfFloat2(val2) { + const m = val2 >> 10; + _tables2.uint32View[0] = _tables2.mantissaTable[_tables2.offsetTable[m] + (val2 & 1023)] + _tables2.exponentTable[m]; + return _tables2.floatView[0]; + } + var DataUtils2 = { + toHalfFloat: toHalfFloat2, + fromHalfFloat: fromHalfFloat2 + }; + var _vector$92 = /* @__PURE__ */ new Vector32; + var _vector2$12 = /* @__PURE__ */ new Vector22; + var _id$3 = 0; + + class BufferAttribute2 { + constructor(array, itemSize, normalized = false) { + if (Array.isArray(array)) { + throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); + } + this.isBufferAttribute = true; + Object.defineProperty(this, "id", { value: _id$3++ }); + this.name = ""; + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized; + this.usage = StaticDrawUsage2; + this.updateRanges = []; + this.gpuType = FloatType2; + this.version = 0; + } + onUploadCallback() { + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setUsage(value2) { + this.usage = value2; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.name = source.name; + this.array = new source.array.constructor(source.array); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + this.usage = source.usage; + this.gpuType = source.gpuType; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.itemSize; + index2 *= attribute.itemSize; + for (let i = 0, l2 = this.itemSize;i < l2; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + copyArray(array) { + this.array.set(array); + return this; + } + applyMatrix3(m) { + if (this.itemSize === 2) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector2$12.fromBufferAttribute(this, i); + _vector2$12.applyMatrix3(m); + this.setXY(i, _vector2$12.x, _vector2$12.y); + } + } else if (this.itemSize === 3) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector$92.fromBufferAttribute(this, i); + _vector$92.applyMatrix3(m); + this.setXYZ(i, _vector$92.x, _vector$92.y, _vector$92.z); + } + } + return this; + } + applyMatrix4(m) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector$92.fromBufferAttribute(this, i); + _vector$92.applyMatrix4(m); + this.setXYZ(i, _vector$92.x, _vector$92.y, _vector$92.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector$92.fromBufferAttribute(this, i); + _vector$92.applyNormalMatrix(m); + this.setXYZ(i, _vector$92.x, _vector$92.y, _vector$92.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector$92.fromBufferAttribute(this, i); + _vector$92.transformDirection(m); + this.setXYZ(i, _vector$92.x, _vector$92.y, _vector$92.z); + } + return this; + } + set(value2, offset = 0) { + this.array.set(value2, offset); + return this; + } + getComponent(index2, component) { + let value2 = this.array[index2 * this.itemSize + component]; + if (this.normalized) + value2 = denormalize2(value2, this.array); + return value2; + } + setComponent(index2, component, value2) { + if (this.normalized) + value2 = normalize3(value2, this.array); + this.array[index2 * this.itemSize + component] = value2; + return this; + } + getX(index2) { + let x2 = this.array[index2 * this.itemSize]; + if (this.normalized) + x2 = denormalize2(x2, this.array); + return x2; + } + setX(index2, x2) { + if (this.normalized) + x2 = normalize3(x2, this.array); + this.array[index2 * this.itemSize] = x2; + return this; + } + getY(index2) { + let y = this.array[index2 * this.itemSize + 1]; + if (this.normalized) + y = denormalize2(y, this.array); + return y; + } + setY(index2, y) { + if (this.normalized) + y = normalize3(y, this.array); + this.array[index2 * this.itemSize + 1] = y; + return this; + } + getZ(index2) { + let z = this.array[index2 * this.itemSize + 2]; + if (this.normalized) + z = denormalize2(z, this.array); + return z; + } + setZ(index2, z) { + if (this.normalized) + z = normalize3(z, this.array); + this.array[index2 * this.itemSize + 2] = z; + return this; + } + getW(index2) { + let w = this.array[index2 * this.itemSize + 3]; + if (this.normalized) + w = denormalize2(w, this.array); + return w; + } + setW(index2, w) { + if (this.normalized) + w = normalize3(w, this.array); + this.array[index2 * this.itemSize + 3] = w; + return this; + } + setXY(index2, x2, y) { + index2 *= this.itemSize; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y = normalize3(y, this.array); + } + this.array[index2 + 0] = x2; + this.array[index2 + 1] = y; + return this; + } + setXYZ(index2, x2, y, z) { + index2 *= this.itemSize; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y = normalize3(y, this.array); + z = normalize3(z, this.array); + } + this.array[index2 + 0] = x2; + this.array[index2 + 1] = y; + this.array[index2 + 2] = z; + return this; + } + setXYZW(index2, x2, y, z, w) { + index2 *= this.itemSize; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y = normalize3(y, this.array); + z = normalize3(z, this.array); + w = normalize3(w, this.array); + } + this.array[index2 + 0] = x2; + this.array[index2 + 1] = y; + this.array[index2 + 2] = z; + this.array[index2 + 3] = w; + return this; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + clone() { + return new this.constructor(this.array, this.itemSize).copy(this); + } + toJSON() { + const data2 = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from(this.array), + normalized: this.normalized + }; + if (this.name !== "") + data2.name = this.name; + if (this.usage !== StaticDrawUsage2) + data2.usage = this.usage; + return data2; + } + } + + class Int8BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Int8Array(array), itemSize, normalized); + } + } + + class Uint8BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint8Array(array), itemSize, normalized); + } + } + + class Uint8ClampedBufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint8ClampedArray(array), itemSize, normalized); + } + } + + class Int16BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Int16Array(array), itemSize, normalized); + } + } + + class Uint16BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + } + } + + class Int32BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Int32Array(array), itemSize, normalized); + } + } + + class Uint32BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint32Array(array), itemSize, normalized); + } + } + + class Float16BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + this.isFloat16BufferAttribute = true; + } + getX(index2) { + let x2 = fromHalfFloat2(this.array[index2 * this.itemSize]); + if (this.normalized) + x2 = denormalize2(x2, this.array); + return x2; + } + setX(index2, x2) { + if (this.normalized) + x2 = normalize3(x2, this.array); + this.array[index2 * this.itemSize] = toHalfFloat2(x2); + return this; + } + getY(index2) { + let y = fromHalfFloat2(this.array[index2 * this.itemSize + 1]); + if (this.normalized) + y = denormalize2(y, this.array); + return y; + } + setY(index2, y) { + if (this.normalized) + y = normalize3(y, this.array); + this.array[index2 * this.itemSize + 1] = toHalfFloat2(y); + return this; + } + getZ(index2) { + let z = fromHalfFloat2(this.array[index2 * this.itemSize + 2]); + if (this.normalized) + z = denormalize2(z, this.array); + return z; + } + setZ(index2, z) { + if (this.normalized) + z = normalize3(z, this.array); + this.array[index2 * this.itemSize + 2] = toHalfFloat2(z); + return this; + } + getW(index2) { + let w = fromHalfFloat2(this.array[index2 * this.itemSize + 3]); + if (this.normalized) + w = denormalize2(w, this.array); + return w; + } + setW(index2, w) { + if (this.normalized) + w = normalize3(w, this.array); + this.array[index2 * this.itemSize + 3] = toHalfFloat2(w); + return this; + } + setXY(index2, x2, y) { + index2 *= this.itemSize; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y = normalize3(y, this.array); + } + this.array[index2 + 0] = toHalfFloat2(x2); + this.array[index2 + 1] = toHalfFloat2(y); + return this; + } + setXYZ(index2, x2, y, z) { + index2 *= this.itemSize; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y = normalize3(y, this.array); + z = normalize3(z, this.array); + } + this.array[index2 + 0] = toHalfFloat2(x2); + this.array[index2 + 1] = toHalfFloat2(y); + this.array[index2 + 2] = toHalfFloat2(z); + return this; + } + setXYZW(index2, x2, y, z, w) { + index2 *= this.itemSize; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y = normalize3(y, this.array); + z = normalize3(z, this.array); + w = normalize3(w, this.array); + } + this.array[index2 + 0] = toHalfFloat2(x2); + this.array[index2 + 1] = toHalfFloat2(y); + this.array[index2 + 2] = toHalfFloat2(z); + this.array[index2 + 3] = toHalfFloat2(w); + return this; + } + } + + class Float32BufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized) { + super(new Float32Array(array), itemSize, normalized); + } + } + var _id$22 = 0; + var _m1$22 = /* @__PURE__ */ new Matrix42; + var _obj2 = /* @__PURE__ */ new Object3D2; + var _offset4 = /* @__PURE__ */ new Vector32; + var _box$22 = /* @__PURE__ */ new Box32; + var _boxMorphTargets2 = /* @__PURE__ */ new Box32; + var _vector$82 = /* @__PURE__ */ new Vector32; + + class BufferGeometry2 extends EventDispatcher2 { + constructor() { + super(); + this.isBufferGeometry = true; + Object.defineProperty(this, "id", { value: _id$22++ }); + this.uuid = generateUUID2(); + this.name = ""; + this.type = "BufferGeometry"; + this.index = null; + this.indirect = null; + this.attributes = {}; + this.morphAttributes = {}; + this.morphTargetsRelative = false; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + this.drawRange = { start: 0, count: Infinity }; + this.userData = {}; + } + getIndex() { + return this.index; + } + setIndex(index2) { + if (Array.isArray(index2)) { + this.index = new ((arrayNeedsUint322(index2)) ? Uint32BufferAttribute2 : Uint16BufferAttribute2)(index2, 1); + } else { + this.index = index2; + } + return this; + } + setIndirect(indirect) { + this.indirect = indirect; + return this; + } + getIndirect() { + return this.indirect; + } + getAttribute(name2) { + return this.attributes[name2]; + } + setAttribute(name2, attribute) { + this.attributes[name2] = attribute; + return this; + } + deleteAttribute(name2) { + delete this.attributes[name2]; + return this; + } + hasAttribute(name2) { + return this.attributes[name2] !== undefined; + } + addGroup(start, count, materialIndex = 0) { + this.groups.push({ + start, + count, + materialIndex + }); + } + clearGroups() { + this.groups = []; + } + setDrawRange(start, count) { + this.drawRange.start = start; + this.drawRange.count = count; + } + applyMatrix4(matrix3) { + const position2 = this.attributes.position; + if (position2 !== undefined) { + position2.applyMatrix4(matrix3); + position2.needsUpdate = true; + } + const normal = this.attributes.normal; + if (normal !== undefined) { + const normalMatrix = new Matrix32().getNormalMatrix(matrix3); + normal.applyNormalMatrix(normalMatrix); + normal.needsUpdate = true; + } + const tangent = this.attributes.tangent; + if (tangent !== undefined) { + tangent.transformDirection(matrix3); + tangent.needsUpdate = true; + } + if (this.boundingBox !== null) { + this.computeBoundingBox(); + } + if (this.boundingSphere !== null) { + this.computeBoundingSphere(); + } + return this; + } + applyQuaternion(q2) { + _m1$22.makeRotationFromQuaternion(q2); + this.applyMatrix4(_m1$22); + return this; + } + rotateX(angle) { + _m1$22.makeRotationX(angle); + this.applyMatrix4(_m1$22); + return this; + } + rotateY(angle) { + _m1$22.makeRotationY(angle); + this.applyMatrix4(_m1$22); + return this; + } + rotateZ(angle) { + _m1$22.makeRotationZ(angle); + this.applyMatrix4(_m1$22); + return this; + } + translate(x2, y, z) { + _m1$22.makeTranslation(x2, y, z); + this.applyMatrix4(_m1$22); + return this; + } + scale(x2, y, z) { + _m1$22.makeScale(x2, y, z); + this.applyMatrix4(_m1$22); + return this; + } + lookAt(vector) { + _obj2.lookAt(vector); + _obj2.updateMatrix(); + this.applyMatrix4(_obj2.matrix); + return this; + } + center() { + this.computeBoundingBox(); + this.boundingBox.getCenter(_offset4).negate(); + this.translate(_offset4.x, _offset4.y, _offset4.z); + return this; + } + setFromPoints(points) { + const positionAttribute = this.getAttribute("position"); + if (positionAttribute === undefined) { + const position2 = []; + for (let i = 0, l2 = points.length;i < l2; i++) { + const point = points[i]; + position2.push(point.x, point.y, point.z || 0); + } + this.setAttribute("position", new Float32BufferAttribute2(position2, 3)); + } else { + const l2 = Math.min(points.length, positionAttribute.count); + for (let i = 0;i < l2; i++) { + const point = points[i]; + positionAttribute.setXYZ(i, point.x, point.y, point.z || 0); + } + if (points.length > positionAttribute.count) { + console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."); + } + positionAttribute.needsUpdate = true; + } + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box32; + } + const position2 = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position2 && position2.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this); + this.boundingBox.set(new Vector32(-Infinity, -Infinity, -Infinity), new Vector32(Infinity, Infinity, Infinity)); + return; + } + if (position2 !== undefined) { + this.boundingBox.setFromBufferAttribute(position2); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _box$22.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$82.addVectors(this.boundingBox.min, _box$22.min); + this.boundingBox.expandByPoint(_vector$82); + _vector$82.addVectors(this.boundingBox.max, _box$22.max); + this.boundingBox.expandByPoint(_vector$82); + } else { + this.boundingBox.expandByPoint(_box$22.min); + this.boundingBox.expandByPoint(_box$22.max); + } + } + } + } else { + this.boundingBox.makeEmpty(); + } + if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) { + console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere2; + } + const position2 = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position2 && position2.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this); + this.boundingSphere.set(new Vector32, Infinity); + return; + } + if (position2) { + const center = this.boundingSphere.center; + _box$22.setFromBufferAttribute(position2); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _boxMorphTargets2.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$82.addVectors(_box$22.min, _boxMorphTargets2.min); + _box$22.expandByPoint(_vector$82); + _vector$82.addVectors(_box$22.max, _boxMorphTargets2.max); + _box$22.expandByPoint(_vector$82); + } else { + _box$22.expandByPoint(_boxMorphTargets2.min); + _box$22.expandByPoint(_boxMorphTargets2.max); + } + } + } + _box$22.getCenter(center); + let maxRadiusSq = 0; + for (let i = 0, il = position2.count;i < il; i++) { + _vector$82.fromBufferAttribute(position2, i); + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$82)); + } + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + const morphTargetsRelative = this.morphTargetsRelative; + for (let j2 = 0, jl = morphAttribute.count;j2 < jl; j2++) { + _vector$82.fromBufferAttribute(morphAttribute, j2); + if (morphTargetsRelative) { + _offset4.fromBufferAttribute(position2, j2); + _vector$82.add(_offset4); + } + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$82)); + } + } + } + this.boundingSphere.radius = Math.sqrt(maxRadiusSq); + if (isNaN(this.boundingSphere.radius)) { + console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); + } + } + } + computeTangents() { + const index2 = this.index; + const attributes = this.attributes; + if (index2 === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) { + console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); + return; + } + const positionAttribute = attributes.position; + const normalAttribute = attributes.normal; + const uvAttribute = attributes.uv; + if (this.hasAttribute("tangent") === false) { + this.setAttribute("tangent", new BufferAttribute2(new Float32Array(4 * positionAttribute.count), 4)); + } + const tangentAttribute = this.getAttribute("tangent"); + const tan1 = [], tan2 = []; + for (let i = 0;i < positionAttribute.count; i++) { + tan1[i] = new Vector32; + tan2[i] = new Vector32; + } + const vA = new Vector32, vB = new Vector32, vC = new Vector32, uvA = new Vector22, uvB = new Vector22, uvC = new Vector22, sdir = new Vector32, tdir = new Vector32; + function handleTriangle(a2, b2, c2) { + vA.fromBufferAttribute(positionAttribute, a2); + vB.fromBufferAttribute(positionAttribute, b2); + vC.fromBufferAttribute(positionAttribute, c2); + uvA.fromBufferAttribute(uvAttribute, a2); + uvB.fromBufferAttribute(uvAttribute, b2); + uvC.fromBufferAttribute(uvAttribute, c2); + vB.sub(vA); + vC.sub(vA); + uvB.sub(uvA); + uvC.sub(uvA); + const r = 1 / (uvB.x * uvC.y - uvC.x * uvB.y); + if (!isFinite(r)) + return; + sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r); + tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r); + tan1[a2].add(sdir); + tan1[b2].add(sdir); + tan1[c2].add(sdir); + tan2[a2].add(tdir); + tan2[b2].add(tdir); + tan2[c2].add(tdir); + } + let groups = this.groups; + if (groups.length === 0) { + groups = [{ + start: 0, + count: index2.count + }]; + } + for (let i = 0, il = groups.length;i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j2 = start, jl = start + count;j2 < jl; j2 += 3) { + handleTriangle(index2.getX(j2 + 0), index2.getX(j2 + 1), index2.getX(j2 + 2)); + } + } + const tmp3 = new Vector32, tmp22 = new Vector32; + const n2 = new Vector32, n22 = new Vector32; + function handleVertex(v) { + n2.fromBufferAttribute(normalAttribute, v); + n22.copy(n2); + const t3 = tan1[v]; + tmp3.copy(t3); + tmp3.sub(n2.multiplyScalar(n2.dot(t3))).normalize(); + tmp22.crossVectors(n22, t3); + const test = tmp22.dot(tan2[v]); + const w = test < 0 ? -1 : 1; + tangentAttribute.setXYZW(v, tmp3.x, tmp3.y, tmp3.z, w); + } + for (let i = 0, il = groups.length;i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j2 = start, jl = start + count;j2 < jl; j2 += 3) { + handleVertex(index2.getX(j2 + 0)); + handleVertex(index2.getX(j2 + 1)); + handleVertex(index2.getX(j2 + 2)); + } + } + } + computeVertexNormals() { + const index2 = this.index; + const positionAttribute = this.getAttribute("position"); + if (positionAttribute !== undefined) { + let normalAttribute = this.getAttribute("normal"); + if (normalAttribute === undefined) { + normalAttribute = new BufferAttribute2(new Float32Array(positionAttribute.count * 3), 3); + this.setAttribute("normal", normalAttribute); + } else { + for (let i = 0, il = normalAttribute.count;i < il; i++) { + normalAttribute.setXYZ(i, 0, 0, 0); + } + } + const pA = new Vector32, pB = new Vector32, pC = new Vector32; + const nA = new Vector32, nB = new Vector32, nC = new Vector32; + const cb = new Vector32, ab = new Vector32; + if (index2) { + for (let i = 0, il = index2.count;i < il; i += 3) { + const vA = index2.getX(i + 0); + const vB = index2.getX(i + 1); + const vC = index2.getX(i + 2); + pA.fromBufferAttribute(positionAttribute, vA); + pB.fromBufferAttribute(positionAttribute, vB); + pC.fromBufferAttribute(positionAttribute, vC); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + nA.fromBufferAttribute(normalAttribute, vA); + nB.fromBufferAttribute(normalAttribute, vB); + nC.fromBufferAttribute(normalAttribute, vC); + nA.add(cb); + nB.add(cb); + nC.add(cb); + normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z); + normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z); + normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z); + } + } else { + for (let i = 0, il = positionAttribute.count;i < il; i += 3) { + pA.fromBufferAttribute(positionAttribute, i + 0); + pB.fromBufferAttribute(positionAttribute, i + 1); + pC.fromBufferAttribute(positionAttribute, i + 2); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z); + } + } + this.normalizeNormals(); + normalAttribute.needsUpdate = true; + } + } + normalizeNormals() { + const normals = this.attributes.normal; + for (let i = 0, il = normals.count;i < il; i++) { + _vector$82.fromBufferAttribute(normals, i); + _vector$82.normalize(); + normals.setXYZ(i, _vector$82.x, _vector$82.y, _vector$82.z); + } + } + toNonIndexed() { + function convertBufferAttribute(attribute, indices2) { + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + const array2 = new array.constructor(indices2.length * itemSize); + let index2 = 0, index22 = 0; + for (let i = 0, l2 = indices2.length;i < l2; i++) { + if (attribute.isInterleavedBufferAttribute) { + index2 = indices2[i] * attribute.data.stride + attribute.offset; + } else { + index2 = indices2[i] * itemSize; + } + for (let j2 = 0;j2 < itemSize; j2++) { + array2[index22++] = array[index2++]; + } + } + return new BufferAttribute2(array2, itemSize, normalized); + } + if (this.index === null) { + console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."); + return this; + } + const geometry2 = new BufferGeometry2; + const indices = this.index.array; + const attributes = this.attributes; + for (const name2 in attributes) { + const attribute = attributes[name2]; + const newAttribute = convertBufferAttribute(attribute, indices); + geometry2.setAttribute(name2, newAttribute); + } + const morphAttributes = this.morphAttributes; + for (const name2 in morphAttributes) { + const morphArray = []; + const morphAttribute = morphAttributes[name2]; + for (let i = 0, il = morphAttribute.length;i < il; i++) { + const attribute = morphAttribute[i]; + const newAttribute = convertBufferAttribute(attribute, indices); + morphArray.push(newAttribute); + } + geometry2.morphAttributes[name2] = morphArray; + } + geometry2.morphTargetsRelative = this.morphTargetsRelative; + const groups = this.groups; + for (let i = 0, l2 = groups.length;i < l2; i++) { + const group = groups[i]; + geometry2.addGroup(group.start, group.count, group.materialIndex); + } + return geometry2; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "BufferGeometry", + generator: "BufferGeometry.toJSON" + } + }; + data2.uuid = this.uuid; + data2.type = this.type; + if (this.name !== "") + data2.name = this.name; + if (Object.keys(this.userData).length > 0) + data2.userData = this.userData; + if (this.parameters !== undefined) { + const parameters = this.parameters; + for (const key2 in parameters) { + if (parameters[key2] !== undefined) + data2[key2] = parameters[key2]; + } + return data2; + } + data2.data = { attributes: {} }; + const index2 = this.index; + if (index2 !== null) { + data2.data.index = { + type: index2.array.constructor.name, + array: Array.prototype.slice.call(index2.array) + }; + } + const attributes = this.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + data2.data.attributes[key2] = attribute.toJSON(data2.data); + } + const morphAttributes = {}; + let hasMorphAttributes = false; + for (const key2 in this.morphAttributes) { + const attributeArray = this.morphAttributes[key2]; + const array = []; + for (let i = 0, il = attributeArray.length;i < il; i++) { + const attribute = attributeArray[i]; + array.push(attribute.toJSON(data2.data)); + } + if (array.length > 0) { + morphAttributes[key2] = array; + hasMorphAttributes = true; + } + } + if (hasMorphAttributes) { + data2.data.morphAttributes = morphAttributes; + data2.data.morphTargetsRelative = this.morphTargetsRelative; + } + const groups = this.groups; + if (groups.length > 0) { + data2.data.groups = JSON.parse(JSON.stringify(groups)); + } + const boundingSphere = this.boundingSphere; + if (boundingSphere !== null) { + data2.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; + } + return data2; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + const data2 = {}; + this.name = source.name; + const index2 = source.index; + if (index2 !== null) { + this.setIndex(index2.clone(data2)); + } + const attributes = source.attributes; + for (const name2 in attributes) { + const attribute = attributes[name2]; + this.setAttribute(name2, attribute.clone(data2)); + } + const morphAttributes = source.morphAttributes; + for (const name2 in morphAttributes) { + const array = []; + const morphAttribute = morphAttributes[name2]; + for (let i = 0, l2 = morphAttribute.length;i < l2; i++) { + array.push(morphAttribute[i].clone(data2)); + } + this.morphAttributes[name2] = array; + } + this.morphTargetsRelative = source.morphTargetsRelative; + const groups = source.groups; + for (let i = 0, l2 = groups.length;i < l2; i++) { + const group = groups[i]; + this.addGroup(group.start, group.count, group.materialIndex); + } + const boundingBox = source.boundingBox; + if (boundingBox !== null) { + this.boundingBox = boundingBox.clone(); + } + const boundingSphere = source.boundingSphere; + if (boundingSphere !== null) { + this.boundingSphere = boundingSphere.clone(); + } + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + this.userData = source.userData; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + } + var _inverseMatrix$32 = /* @__PURE__ */ new Matrix42; + var _ray$32 = /* @__PURE__ */ new Ray2; + var _sphere$62 = /* @__PURE__ */ new Sphere2; + var _sphereHitAt2 = /* @__PURE__ */ new Vector32; + var _vA$12 = /* @__PURE__ */ new Vector32; + var _vB$12 = /* @__PURE__ */ new Vector32; + var _vC$12 = /* @__PURE__ */ new Vector32; + var _tempA2 = /* @__PURE__ */ new Vector32; + var _morphA2 = /* @__PURE__ */ new Vector32; + var _intersectionPoint2 = /* @__PURE__ */ new Vector32; + var _intersectionPointWorld2 = /* @__PURE__ */ new Vector32; + + class Mesh2 extends Object3D2 { + constructor(geometry = new BufferGeometry2, material = new MeshBasicMaterial2) { + super(); + this.isMesh = true; + this.type = "Mesh"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.morphTargetInfluences !== undefined) { + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + } + if (source.morphTargetDictionary !== undefined) { + this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary); + } + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } + getVertexPosition(index2, target) { + const geometry = this.geometry; + const position2 = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + target.fromBufferAttribute(position2, index2); + const morphInfluences = this.morphTargetInfluences; + if (morphPosition && morphInfluences) { + _morphA2.set(0, 0, 0); + for (let i = 0, il = morphPosition.length;i < il; i++) { + const influence = morphInfluences[i]; + const morphAttribute = morphPosition[i]; + if (influence === 0) + continue; + _tempA2.fromBufferAttribute(morphAttribute, index2); + if (morphTargetsRelative) { + _morphA2.addScaledVector(_tempA2, influence); + } else { + _morphA2.addScaledVector(_tempA2.sub(target), influence); + } + } + target.add(_morphA2); + } + return target; + } + raycast(raycaster, intersects3) { + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === undefined) + return; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$62.copy(geometry.boundingSphere); + _sphere$62.applyMatrix4(matrixWorld); + _ray$32.copy(raycaster.ray).recast(raycaster.near); + if (_sphere$62.containsPoint(_ray$32.origin) === false) { + if (_ray$32.intersectSphere(_sphere$62, _sphereHitAt2) === null) + return; + if (_ray$32.origin.distanceToSquared(_sphereHitAt2) > (raycaster.far - raycaster.near) ** 2) + return; + } + _inverseMatrix$32.copy(matrixWorld).invert(); + _ray$32.copy(raycaster.ray).applyMatrix4(_inverseMatrix$32); + if (geometry.boundingBox !== null) { + if (_ray$32.intersectsBox(geometry.boundingBox) === false) + return; + } + this._computeIntersections(raycaster, intersects3, _ray$32); + } + _computeIntersections(raycaster, intersects3, rayLocalSpace) { + let intersection; + const geometry = this.geometry; + const material = this.material; + const index2 = geometry.index; + const position2 = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv1 = geometry.attributes.uv1; + const normal = geometry.attributes.normal; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + if (index2 !== null) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length;i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(index2.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j2 = start, jl = end;j2 < jl; j2 += 3) { + const a2 = index2.getX(j2); + const b2 = index2.getX(j2 + 1); + const c2 = index2.getX(j2 + 2); + intersection = checkGeometryIntersection2(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a2, b2, c2); + if (intersection) { + intersection.faceIndex = Math.floor(j2 / 3); + intersection.face.materialIndex = group.materialIndex; + intersects3.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i += 3) { + const a2 = index2.getX(i); + const b2 = index2.getX(i + 1); + const c2 = index2.getX(i + 2); + intersection = checkGeometryIntersection2(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a2, b2, c2); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects3.push(intersection); + } + } + } + } else if (position2 !== undefined) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length;i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(position2.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j2 = start, jl = end;j2 < jl; j2 += 3) { + const a2 = j2; + const b2 = j2 + 1; + const c2 = j2 + 2; + intersection = checkGeometryIntersection2(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a2, b2, c2); + if (intersection) { + intersection.faceIndex = Math.floor(j2 / 3); + intersection.face.materialIndex = group.materialIndex; + intersects3.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(position2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i += 3) { + const a2 = i; + const b2 = i + 1; + const c2 = i + 2; + intersection = checkGeometryIntersection2(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a2, b2, c2); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects3.push(intersection); + } + } + } + } + } + } + function checkIntersection$12(object, material, raycaster, ray, pA, pB, pC, point) { + let intersect3; + if (material.side === BackSide2) { + intersect3 = ray.intersectTriangle(pC, pB, pA, true, point); + } else { + intersect3 = ray.intersectTriangle(pA, pB, pC, material.side === FrontSide2, point); + } + if (intersect3 === null) + return null; + _intersectionPointWorld2.copy(point); + _intersectionPointWorld2.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld2); + if (distance < raycaster.near || distance > raycaster.far) + return null; + return { + distance, + point: _intersectionPointWorld2.clone(), + object + }; + } + function checkGeometryIntersection2(object, material, raycaster, ray, uv, uv1, normal, a2, b2, c2) { + object.getVertexPosition(a2, _vA$12); + object.getVertexPosition(b2, _vB$12); + object.getVertexPosition(c2, _vC$12); + const intersection = checkIntersection$12(object, material, raycaster, ray, _vA$12, _vB$12, _vC$12, _intersectionPoint2); + if (intersection) { + const barycoord = new Vector32; + Triangle2.getBarycoord(_intersectionPoint2, _vA$12, _vB$12, _vC$12, barycoord); + if (uv) { + intersection.uv = Triangle2.getInterpolatedAttribute(uv, a2, b2, c2, barycoord, new Vector22); + } + if (uv1) { + intersection.uv1 = Triangle2.getInterpolatedAttribute(uv1, a2, b2, c2, barycoord, new Vector22); + } + if (normal) { + intersection.normal = Triangle2.getInterpolatedAttribute(normal, a2, b2, c2, barycoord, new Vector32); + if (intersection.normal.dot(ray.direction) > 0) { + intersection.normal.multiplyScalar(-1); + } + } + const face = { + a: a2, + b: b2, + c: c2, + normal: new Vector32, + materialIndex: 0 + }; + Triangle2.getNormal(_vA$12, _vB$12, _vC$12, face.normal); + intersection.face = face; + intersection.barycoord = barycoord; + } + return intersection; + } + + class BoxGeometry2 extends BufferGeometry2 { + constructor(width2 = 1, height2 = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) { + super(); + this.type = "BoxGeometry"; + this.parameters = { + width: width2, + height: height2, + depth, + widthSegments, + heightSegments, + depthSegments + }; + const scope = this; + widthSegments = Math.floor(widthSegments); + heightSegments = Math.floor(heightSegments); + depthSegments = Math.floor(depthSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let numberOfVertices = 0; + let groupStart = 0; + buildPlane("z", "y", "x", -1, -1, depth, height2, width2, depthSegments, heightSegments, 0); + buildPlane("z", "y", "x", 1, -1, depth, height2, -width2, depthSegments, heightSegments, 1); + buildPlane("x", "z", "y", 1, 1, width2, depth, height2, widthSegments, depthSegments, 2); + buildPlane("x", "z", "y", 1, -1, width2, depth, -height2, widthSegments, depthSegments, 3); + buildPlane("x", "y", "z", 1, -1, width2, height2, depth, widthSegments, heightSegments, 4); + buildPlane("x", "y", "z", -1, -1, width2, height2, -depth, widthSegments, heightSegments, 5); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function buildPlane(u2, v, w, udir, vdir, width3, height3, depth2, gridX, gridY, materialIndex) { + const segmentWidth = width3 / gridX; + const segmentHeight = height3 / gridY; + const widthHalf = width3 / 2; + const heightHalf = height3 / 2; + const depthHalf = depth2 / 2; + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + let vertexCounter = 0; + let groupCount = 0; + const vector = new Vector32; + for (let iy = 0;iy < gridY1; iy++) { + const y = iy * segmentHeight - heightHalf; + for (let ix = 0;ix < gridX1; ix++) { + const x2 = ix * segmentWidth - widthHalf; + vector[u2] = x2 * udir; + vector[v] = y * vdir; + vector[w] = depthHalf; + vertices.push(vector.x, vector.y, vector.z); + vector[u2] = 0; + vector[v] = 0; + vector[w] = depth2 > 0 ? 1 : -1; + normals.push(vector.x, vector.y, vector.z); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + vertexCounter += 1; + } + } + for (let iy = 0;iy < gridY; iy++) { + for (let ix = 0;ix < gridX; ix++) { + const a2 = numberOfVertices + ix + gridX1 * iy; + const b2 = numberOfVertices + ix + gridX1 * (iy + 1); + const c2 = numberOfVertices + (ix + 1) + gridX1 * (iy + 1); + const d = numberOfVertices + (ix + 1) + gridX1 * iy; + indices.push(a2, b2, d); + indices.push(b2, c2, d); + groupCount += 6; + } + } + scope.addGroup(groupStart, groupCount, materialIndex); + groupStart += groupCount; + numberOfVertices += vertexCounter; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new BoxGeometry2(data2.width, data2.height, data2.depth, data2.widthSegments, data2.heightSegments, data2.depthSegments); + } + } + function cloneUniforms2(src) { + const dst = {}; + for (const u2 in src) { + dst[u2] = {}; + for (const p in src[u2]) { + const property2 = src[u2][p]; + if (property2 && (property2.isColor || property2.isMatrix3 || property2.isMatrix4 || property2.isVector2 || property2.isVector3 || property2.isVector4 || property2.isTexture || property2.isQuaternion)) { + if (property2.isRenderTargetTexture) { + console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."); + dst[u2][p] = null; + } else { + dst[u2][p] = property2.clone(); + } + } else if (Array.isArray(property2)) { + dst[u2][p] = property2.slice(); + } else { + dst[u2][p] = property2; + } + } + } + return dst; + } + function mergeUniforms2(uniforms) { + const merged = {}; + for (let u2 = 0;u2 < uniforms.length; u2++) { + const tmp3 = cloneUniforms2(uniforms[u2]); + for (const p in tmp3) { + merged[p] = tmp3[p]; + } + } + return merged; + } + function cloneUniformsGroups2(src) { + const dst = []; + for (let u2 = 0;u2 < src.length; u2++) { + dst.push(src[u2].clone()); + } + return dst; + } + function getUnlitUniformColorSpace2(renderer2) { + const currentRenderTarget = renderer2.getRenderTarget(); + if (currentRenderTarget === null) { + return renderer2.outputColorSpace; + } + if (currentRenderTarget.isXRRenderTarget === true) { + return currentRenderTarget.texture.colorSpace; + } + return ColorManagement2.workingColorSpace; + } + var UniformsUtils2 = { clone: cloneUniforms2, merge: mergeUniforms2 }; + var default_vertex2 = `void main() { + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); +}`; + var default_fragment2 = `void main() { + gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); +}`; + + class ShaderMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isShaderMaterial = true; + this.type = "ShaderMaterial"; + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + this.vertexShader = default_vertex2; + this.fragmentShader = default_fragment2; + this.linewidth = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.fog = false; + this.lights = false; + this.clipping = false; + this.forceSinglePass = true; + this.extensions = { + clipCullDistance: false, + multiDraw: false + }; + this.defaultAttributeValues = { + color: [1, 1, 1], + uv: [0, 0], + uv1: [0, 0] + }; + this.index0AttributeName = undefined; + this.uniformsNeedUpdate = false; + this.glslVersion = null; + if (parameters !== undefined) { + this.setValues(parameters); + } + } + copy(source) { + super.copy(source); + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + this.uniforms = cloneUniforms2(source.uniforms); + this.uniformsGroups = cloneUniformsGroups2(source.uniformsGroups); + this.defines = Object.assign({}, source.defines); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + this.extensions = Object.assign({}, source.extensions); + this.glslVersion = source.glslVersion; + return this; + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + data2.glslVersion = this.glslVersion; + data2.uniforms = {}; + for (const name2 in this.uniforms) { + const uniform = this.uniforms[name2]; + const value2 = uniform.value; + if (value2 && value2.isTexture) { + data2.uniforms[name2] = { + type: "t", + value: value2.toJSON(meta2).uuid + }; + } else if (value2 && value2.isColor) { + data2.uniforms[name2] = { + type: "c", + value: value2.getHex() + }; + } else if (value2 && value2.isVector2) { + data2.uniforms[name2] = { + type: "v2", + value: value2.toArray() + }; + } else if (value2 && value2.isVector3) { + data2.uniforms[name2] = { + type: "v3", + value: value2.toArray() + }; + } else if (value2 && value2.isVector4) { + data2.uniforms[name2] = { + type: "v4", + value: value2.toArray() + }; + } else if (value2 && value2.isMatrix3) { + data2.uniforms[name2] = { + type: "m3", + value: value2.toArray() + }; + } else if (value2 && value2.isMatrix4) { + data2.uniforms[name2] = { + type: "m4", + value: value2.toArray() + }; + } else { + data2.uniforms[name2] = { + value: value2 + }; + } + } + if (Object.keys(this.defines).length > 0) + data2.defines = this.defines; + data2.vertexShader = this.vertexShader; + data2.fragmentShader = this.fragmentShader; + data2.lights = this.lights; + data2.clipping = this.clipping; + const extensions = {}; + for (const key2 in this.extensions) { + if (this.extensions[key2] === true) + extensions[key2] = true; + } + if (Object.keys(extensions).length > 0) + data2.extensions = extensions; + return data2; + } + } + + class Camera2 extends Object3D2 { + constructor() { + super(); + this.isCamera = true; + this.type = "Camera"; + this.matrixWorldInverse = new Matrix42; + this.projectionMatrix = new Matrix42; + this.projectionMatrixInverse = new Matrix42; + this.coordinateSystem = WebGLCoordinateSystem2; + } + copy(source, recursive) { + super.copy(source, recursive); + this.matrixWorldInverse.copy(source.matrixWorldInverse); + this.projectionMatrix.copy(source.projectionMatrix); + this.projectionMatrixInverse.copy(source.projectionMatrixInverse); + this.coordinateSystem = source.coordinateSystem; + return this; + } + getWorldDirection(target) { + return super.getWorldDirection(target).negate(); + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + updateWorldMatrix(updateParents, updateChildren) { + super.updateWorldMatrix(updateParents, updateChildren); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + clone() { + return new this.constructor().copy(this); + } + } + var _v3$12 = /* @__PURE__ */ new Vector32; + var _minTarget2 = /* @__PURE__ */ new Vector22; + var _maxTarget2 = /* @__PURE__ */ new Vector22; + + class PerspectiveCamera2 extends Camera2 { + constructor(fov3 = 50, aspect3 = 1, near = 0.1, far = 2000) { + super(); + this.isPerspectiveCamera = true; + this.type = "PerspectiveCamera"; + this.fov = fov3; + this.zoom = 1; + this.near = near; + this.far = far; + this.focus = 10; + this.aspect = aspect3; + this.view = null; + this.filmGauge = 35; + this.filmOffset = 0; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.fov = source.fov; + this.zoom = source.zoom; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign({}, source.view); + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + return this; + } + setFocalLength(focalLength) { + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + this.fov = RAD2DEG2 * 2 * Math.atan(vExtentSlope); + this.updateProjectionMatrix(); + } + getFocalLength() { + const vExtentSlope = Math.tan(DEG2RAD2 * 0.5 * this.fov); + return 0.5 * this.getFilmHeight() / vExtentSlope; + } + getEffectiveFOV() { + return RAD2DEG2 * 2 * Math.atan(Math.tan(DEG2RAD2 * 0.5 * this.fov) / this.zoom); + } + getFilmWidth() { + return this.filmGauge * Math.min(this.aspect, 1); + } + getFilmHeight() { + return this.filmGauge / Math.max(this.aspect, 1); + } + getViewBounds(distance, minTarget, maxTarget) { + _v3$12.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse); + minTarget.set(_v3$12.x, _v3$12.y).multiplyScalar(-distance / _v3$12.z); + _v3$12.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse); + maxTarget.set(_v3$12.x, _v3$12.y).multiplyScalar(-distance / _v3$12.z); + } + getViewSize(distance, target) { + this.getViewBounds(distance, _minTarget2, _maxTarget2); + return target.subVectors(_maxTarget2, _minTarget2); + } + setViewOffset(fullWidth, fullHeight, x2, y, width2, height2) { + this.aspect = fullWidth / fullHeight; + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x2; + this.view.offsetY = y; + this.view.width = width2; + this.view.height = height2; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const near = this.near; + let top = near * Math.tan(DEG2RAD2 * 0.5 * this.fov) / this.zoom; + let height2 = 2 * top; + let width2 = this.aspect * height2; + let left = -0.5 * width2; + const view = this.view; + if (this.view !== null && this.view.enabled) { + const { fullWidth, fullHeight } = view; + left += view.offsetX * width2 / fullWidth; + top -= view.offsetY * height2 / fullHeight; + width2 *= view.width / fullWidth; + height2 *= view.height / fullHeight; + } + const skew = this.filmOffset; + if (skew !== 0) + left += near * skew / this.getFilmWidth(); + this.projectionMatrix.makePerspective(left, left + width2, top, top - height2, near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + data2.object.fov = this.fov; + data2.object.zoom = this.zoom; + data2.object.near = this.near; + data2.object.far = this.far; + data2.object.focus = this.focus; + data2.object.aspect = this.aspect; + if (this.view !== null) + data2.object.view = Object.assign({}, this.view); + data2.object.filmGauge = this.filmGauge; + data2.object.filmOffset = this.filmOffset; + return data2; + } + } + var fov2 = -90; + var aspect2 = 1; + + class CubeCamera2 extends Object3D2 { + constructor(near, far, renderTarget) { + super(); + this.type = "CubeCamera"; + this.renderTarget = renderTarget; + this.coordinateSystem = null; + this.activeMipmapLevel = 0; + const cameraPX = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraPX.layers = this.layers; + this.add(cameraPX); + const cameraNX = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraNX.layers = this.layers; + this.add(cameraNX); + const cameraPY = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraPY.layers = this.layers; + this.add(cameraPY); + const cameraNY = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraNY.layers = this.layers; + this.add(cameraNY); + const cameraPZ = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraPZ.layers = this.layers; + this.add(cameraPZ); + const cameraNZ = new PerspectiveCamera2(fov2, aspect2, near, far); + cameraNZ.layers = this.layers; + this.add(cameraNZ); + } + updateCoordinateSystem() { + const coordinateSystem = this.coordinateSystem; + const cameras = this.children.concat(); + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = cameras; + for (const camera of cameras) + this.remove(camera); + if (coordinateSystem === WebGLCoordinateSystem2) { + cameraPX.up.set(0, 1, 0); + cameraPX.lookAt(1, 0, 0); + cameraNX.up.set(0, 1, 0); + cameraNX.lookAt(-1, 0, 0); + cameraPY.up.set(0, 0, -1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, 1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, 1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, 1, 0); + cameraNZ.lookAt(0, 0, -1); + } else if (coordinateSystem === WebGPUCoordinateSystem2) { + cameraPX.up.set(0, -1, 0); + cameraPX.lookAt(-1, 0, 0); + cameraNX.up.set(0, -1, 0); + cameraNX.lookAt(1, 0, 0); + cameraPY.up.set(0, 0, 1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, -1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, -1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, -1, 0); + cameraNZ.lookAt(0, 0, -1); + } else { + throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + coordinateSystem); + } + for (const camera of cameras) { + this.add(camera); + camera.updateMatrixWorld(); + } + } + update(renderer2, scene) { + if (this.parent === null) + this.updateMatrixWorld(); + const { renderTarget, activeMipmapLevel } = this; + if (this.coordinateSystem !== renderer2.coordinateSystem) { + this.coordinateSystem = renderer2.coordinateSystem; + this.updateCoordinateSystem(); + } + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children; + const currentRenderTarget = renderer2.getRenderTarget(); + const currentActiveCubeFace = renderer2.getActiveCubeFace(); + const currentActiveMipmapLevel = renderer2.getActiveMipmapLevel(); + const currentXrEnabled = renderer2.xr.enabled; + renderer2.xr.enabled = false; + const generateMipmaps = renderTarget.texture.generateMipmaps; + renderTarget.texture.generateMipmaps = false; + renderer2.setRenderTarget(renderTarget, 0, activeMipmapLevel); + renderer2.render(scene, cameraPX); + renderer2.setRenderTarget(renderTarget, 1, activeMipmapLevel); + renderer2.render(scene, cameraNX); + renderer2.setRenderTarget(renderTarget, 2, activeMipmapLevel); + renderer2.render(scene, cameraPY); + renderer2.setRenderTarget(renderTarget, 3, activeMipmapLevel); + renderer2.render(scene, cameraNY); + renderer2.setRenderTarget(renderTarget, 4, activeMipmapLevel); + renderer2.render(scene, cameraPZ); + renderTarget.texture.generateMipmaps = generateMipmaps; + renderer2.setRenderTarget(renderTarget, 5, activeMipmapLevel); + renderer2.render(scene, cameraNZ); + renderer2.setRenderTarget(currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel); + renderer2.xr.enabled = currentXrEnabled; + renderTarget.texture.needsPMREMUpdate = true; + } + } + + class CubeTexture2 extends Texture2 { + constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace) { + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping2; + super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCubeTexture = true; + this.flipY = false; + } + get images() { + return this.image; + } + set images(value2) { + this.image = value2; + } + } + + class WebGLCubeRenderTarget2 extends WebGLRenderTarget2 { + constructor(size2 = 1, options = {}) { + super(size2, size2, options); + this.isWebGLCubeRenderTarget = true; + const image = { width: size2, height: size2, depth: 1 }; + const images = [image, image, image, image, image, image]; + this.texture = new CubeTexture2(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + this.texture.isRenderTargetTexture = true; + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter2; + } + fromEquirectangularTexture(renderer2, texture) { + this.texture.type = texture.type; + this.texture.colorSpace = texture.colorSpace; + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + const shader = { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `, + fragmentShader: ` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + }; + const geometry = new BoxGeometry2(5, 5, 5); + const material = new ShaderMaterial2({ + name: "CubemapFromEquirect", + uniforms: cloneUniforms2(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide2, + blending: NoBlending2 + }); + material.uniforms.tEquirect.value = texture; + const mesh = new Mesh2(geometry, material); + const currentMinFilter = texture.minFilter; + if (texture.minFilter === LinearMipmapLinearFilter2) + texture.minFilter = LinearFilter2; + const camera = new CubeCamera2(1, 10, this); + camera.update(renderer2, mesh); + texture.minFilter = currentMinFilter; + mesh.geometry.dispose(); + mesh.material.dispose(); + return this; + } + clear(renderer2, color, depth, stencil) { + const currentRenderTarget = renderer2.getRenderTarget(); + for (let i = 0;i < 6; i++) { + renderer2.setRenderTarget(this, i); + renderer2.clear(color, depth, stencil); + } + renderer2.setRenderTarget(currentRenderTarget); + } + } + + class Group2 extends Object3D2 { + constructor() { + super(); + this.isGroup = true; + this.type = "Group"; + } + } + var _moveEvent2 = { type: "move" }; + + class WebXRController2 { + constructor() { + this._targetRay = null; + this._grip = null; + this._hand = null; + } + getHandSpace() { + if (this._hand === null) { + this._hand = new Group2; + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + } + return this._hand; + } + getTargetRaySpace() { + if (this._targetRay === null) { + this._targetRay = new Group2; + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector32; + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector32; + } + return this._targetRay; + } + getGripSpace() { + if (this._grip === null) { + this._grip = new Group2; + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector32; + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector32; + } + return this._grip; + } + dispatchEvent(event) { + if (this._targetRay !== null) { + this._targetRay.dispatchEvent(event); + } + if (this._grip !== null) { + this._grip.dispatchEvent(event); + } + if (this._hand !== null) { + this._hand.dispatchEvent(event); + } + return this; + } + connect(inputSource) { + if (inputSource && inputSource.hand) { + const hand = this._hand; + if (hand) { + for (const inputjoint of inputSource.hand.values()) { + this._getHandJoint(hand, inputjoint); + } + } + } + this.dispatchEvent({ type: "connected", data: inputSource }); + return this; + } + disconnect(inputSource) { + this.dispatchEvent({ type: "disconnected", data: inputSource }); + if (this._targetRay !== null) { + this._targetRay.visible = false; + } + if (this._grip !== null) { + this._grip.visible = false; + } + if (this._hand !== null) { + this._hand.visible = false; + } + return this; + } + update(inputSource, frame, referenceSpace) { + let inputPose = null; + let gripPose = null; + let handPose = null; + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + if (inputSource && frame.session.visibilityState !== "visible-blurred") { + if (hand && inputSource.hand) { + handPose = true; + for (const inputjoint of inputSource.hand.values()) { + const jointPose = frame.getJointPose(inputjoint, referenceSpace); + const joint = this._getHandJoint(hand, inputjoint); + if (jointPose !== null) { + joint.matrix.fromArray(jointPose.transform.matrix); + joint.matrix.decompose(joint.position, joint.rotation, joint.scale); + joint.matrixWorldNeedsUpdate = true; + joint.jointRadius = jointPose.radius; + } + joint.visible = jointPose !== null; + } + const indexTip = hand.joints["index-finger-tip"]; + const thumbTip = hand.joints["thumb-tip"]; + const distance = indexTip.position.distanceTo(thumbTip.position); + const distanceToPinch = 0.02; + const threshold = 0.005; + if (hand.inputState.pinching && distance > distanceToPinch + threshold) { + hand.inputState.pinching = false; + this.dispatchEvent({ + type: "pinchend", + handedness: inputSource.handedness, + target: this + }); + } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) { + hand.inputState.pinching = true; + this.dispatchEvent({ + type: "pinchstart", + handedness: inputSource.handedness, + target: this + }); + } + } else { + if (grip !== null && inputSource.gripSpace) { + gripPose = frame.getPose(inputSource.gripSpace, referenceSpace); + if (gripPose !== null) { + grip.matrix.fromArray(gripPose.transform.matrix); + grip.matrix.decompose(grip.position, grip.rotation, grip.scale); + grip.matrixWorldNeedsUpdate = true; + if (gripPose.linearVelocity) { + grip.hasLinearVelocity = true; + grip.linearVelocity.copy(gripPose.linearVelocity); + } else { + grip.hasLinearVelocity = false; + } + if (gripPose.angularVelocity) { + grip.hasAngularVelocity = true; + grip.angularVelocity.copy(gripPose.angularVelocity); + } else { + grip.hasAngularVelocity = false; + } + } + } + } + if (targetRay !== null) { + inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); + if (inputPose === null && gripPose !== null) { + inputPose = gripPose; + } + if (inputPose !== null) { + targetRay.matrix.fromArray(inputPose.transform.matrix); + targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale); + targetRay.matrixWorldNeedsUpdate = true; + if (inputPose.linearVelocity) { + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy(inputPose.linearVelocity); + } else { + targetRay.hasLinearVelocity = false; + } + if (inputPose.angularVelocity) { + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy(inputPose.angularVelocity); + } else { + targetRay.hasAngularVelocity = false; + } + this.dispatchEvent(_moveEvent2); + } + } + } + if (targetRay !== null) { + targetRay.visible = inputPose !== null; + } + if (grip !== null) { + grip.visible = gripPose !== null; + } + if (hand !== null) { + hand.visible = handPose !== null; + } + return this; + } + _getHandJoint(hand, inputjoint) { + if (hand.joints[inputjoint.jointName] === undefined) { + const joint = new Group2; + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[inputjoint.jointName] = joint; + hand.add(joint); + } + return hand.joints[inputjoint.jointName]; + } + } + + class FogExp22 { + constructor(color, density = 0.00025) { + this.isFogExp2 = true; + this.name = ""; + this.color = new Color2(color); + this.density = density; + } + clone() { + return new FogExp22(this.color, this.density); + } + toJSON() { + return { + type: "FogExp2", + name: this.name, + color: this.color.getHex(), + density: this.density + }; + } + } + + class Fog2 { + constructor(color, near = 1, far = 1000) { + this.isFog = true; + this.name = ""; + this.color = new Color2(color); + this.near = near; + this.far = far; + } + clone() { + return new Fog2(this.color, this.near, this.far); + } + toJSON() { + return { + type: "Fog", + name: this.name, + color: this.color.getHex(), + near: this.near, + far: this.far + }; + } + } + + class Scene2 extends Object3D2 { + constructor() { + super(); + this.isScene = true; + this.type = "Scene"; + this.background = null; + this.environment = null; + this.fog = null; + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + this.backgroundRotation = new Euler2; + this.environmentIntensity = 1; + this.environmentRotation = new Euler2; + this.overrideMaterial = null; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.background !== null) + this.background = source.background.clone(); + if (source.environment !== null) + this.environment = source.environment.clone(); + if (source.fog !== null) + this.fog = source.fog.clone(); + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + this.backgroundRotation.copy(source.backgroundRotation); + this.environmentIntensity = source.environmentIntensity; + this.environmentRotation.copy(source.environmentRotation); + if (source.overrideMaterial !== null) + this.overrideMaterial = source.overrideMaterial.clone(); + this.matrixAutoUpdate = source.matrixAutoUpdate; + return this; + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + if (this.fog !== null) + data2.object.fog = this.fog.toJSON(); + if (this.backgroundBlurriness > 0) + data2.object.backgroundBlurriness = this.backgroundBlurriness; + if (this.backgroundIntensity !== 1) + data2.object.backgroundIntensity = this.backgroundIntensity; + data2.object.backgroundRotation = this.backgroundRotation.toArray(); + if (this.environmentIntensity !== 1) + data2.object.environmentIntensity = this.environmentIntensity; + data2.object.environmentRotation = this.environmentRotation.toArray(); + return data2; + } + } + + class InterleavedBuffer2 { + constructor(array, stride) { + this.isInterleavedBuffer = true; + this.array = array; + this.stride = stride; + this.count = array !== undefined ? array.length / stride : 0; + this.usage = StaticDrawUsage2; + this.updateRanges = []; + this.version = 0; + this.uuid = generateUUID2(); + } + onUploadCallback() { + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setUsage(value2) { + this.usage = value2; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.array = new source.array.constructor(source.array); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.stride; + index2 *= attribute.stride; + for (let i = 0, l2 = this.stride;i < l2; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + set(value2, offset = 0) { + this.array.set(value2, offset); + return this; + } + clone(data2) { + if (data2.arrayBuffers === undefined) { + data2.arrayBuffers = {}; + } + if (this.array.buffer._uuid === undefined) { + this.array.buffer._uuid = generateUUID2(); + } + if (data2.arrayBuffers[this.array.buffer._uuid] === undefined) { + data2.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer; + } + const array = new this.array.constructor(data2.arrayBuffers[this.array.buffer._uuid]); + const ib = new this.constructor(array, this.stride); + ib.setUsage(this.usage); + return ib; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + toJSON(data2) { + if (data2.arrayBuffers === undefined) { + data2.arrayBuffers = {}; + } + if (this.array.buffer._uuid === undefined) { + this.array.buffer._uuid = generateUUID2(); + } + if (data2.arrayBuffers[this.array.buffer._uuid] === undefined) { + data2.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer)); + } + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; + } + } + var _vector$72 = /* @__PURE__ */ new Vector32; + + class InterleavedBufferAttribute2 { + constructor(interleavedBuffer, itemSize, offset, normalized = false) { + this.isInterleavedBufferAttribute = true; + this.name = ""; + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; + this.normalized = normalized; + } + get count() { + return this.data.count; + } + get array() { + return this.data.array; + } + set needsUpdate(value2) { + this.data.needsUpdate = value2; + } + applyMatrix4(m) { + for (let i = 0, l2 = this.data.count;i < l2; i++) { + _vector$72.fromBufferAttribute(this, i); + _vector$72.applyMatrix4(m); + this.setXYZ(i, _vector$72.x, _vector$72.y, _vector$72.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector$72.fromBufferAttribute(this, i); + _vector$72.applyNormalMatrix(m); + this.setXYZ(i, _vector$72.x, _vector$72.y, _vector$72.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l2 = this.count;i < l2; i++) { + _vector$72.fromBufferAttribute(this, i); + _vector$72.transformDirection(m); + this.setXYZ(i, _vector$72.x, _vector$72.y, _vector$72.z); + } + return this; + } + getComponent(index2, component) { + let value2 = this.array[index2 * this.data.stride + this.offset + component]; + if (this.normalized) + value2 = denormalize2(value2, this.array); + return value2; + } + setComponent(index2, component, value2) { + if (this.normalized) + value2 = normalize3(value2, this.array); + this.data.array[index2 * this.data.stride + this.offset + component] = value2; + return this; + } + setX(index2, x2) { + if (this.normalized) + x2 = normalize3(x2, this.array); + this.data.array[index2 * this.data.stride + this.offset] = x2; + return this; + } + setY(index2, y) { + if (this.normalized) + y = normalize3(y, this.array); + this.data.array[index2 * this.data.stride + this.offset + 1] = y; + return this; + } + setZ(index2, z) { + if (this.normalized) + z = normalize3(z, this.array); + this.data.array[index2 * this.data.stride + this.offset + 2] = z; + return this; + } + setW(index2, w) { + if (this.normalized) + w = normalize3(w, this.array); + this.data.array[index2 * this.data.stride + this.offset + 3] = w; + return this; + } + getX(index2) { + let x2 = this.data.array[index2 * this.data.stride + this.offset]; + if (this.normalized) + x2 = denormalize2(x2, this.array); + return x2; + } + getY(index2) { + let y = this.data.array[index2 * this.data.stride + this.offset + 1]; + if (this.normalized) + y = denormalize2(y, this.array); + return y; + } + getZ(index2) { + let z = this.data.array[index2 * this.data.stride + this.offset + 2]; + if (this.normalized) + z = denormalize2(z, this.array); + return z; + } + getW(index2) { + let w = this.data.array[index2 * this.data.stride + this.offset + 3]; + if (this.normalized) + w = denormalize2(w, this.array); + return w; + } + setXY(index2, x2, y) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y = normalize3(y, this.array); + } + this.data.array[index2 + 0] = x2; + this.data.array[index2 + 1] = y; + return this; + } + setXYZ(index2, x2, y, z) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y = normalize3(y, this.array); + z = normalize3(z, this.array); + } + this.data.array[index2 + 0] = x2; + this.data.array[index2 + 1] = y; + this.data.array[index2 + 2] = z; + return this; + } + setXYZW(index2, x2, y, z, w) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x2 = normalize3(x2, this.array); + y = normalize3(y, this.array); + z = normalize3(z, this.array); + w = normalize3(w, this.array); + } + this.data.array[index2 + 0] = x2; + this.data.array[index2 + 1] = y; + this.data.array[index2 + 2] = z; + this.data.array[index2 + 3] = w; + return this; + } + clone(data2) { + if (data2 === undefined) { + console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0;i < this.count; i++) { + const index2 = i * this.data.stride + this.offset; + for (let j2 = 0;j2 < this.itemSize; j2++) { + array.push(this.data.array[index2 + j2]); + } + } + return new BufferAttribute2(new this.array.constructor(array), this.itemSize, this.normalized); + } else { + if (data2.interleavedBuffers === undefined) { + data2.interleavedBuffers = {}; + } + if (data2.interleavedBuffers[this.data.uuid] === undefined) { + data2.interleavedBuffers[this.data.uuid] = this.data.clone(data2); + } + return new InterleavedBufferAttribute2(data2.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized); + } + } + toJSON(data2) { + if (data2 === undefined) { + console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0;i < this.count; i++) { + const index2 = i * this.data.stride + this.offset; + for (let j2 = 0;j2 < this.itemSize; j2++) { + array.push(this.data.array[index2 + j2]); + } + } + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array, + normalized: this.normalized + }; + } else { + if (data2.interleavedBuffers === undefined) { + data2.interleavedBuffers = {}; + } + if (data2.interleavedBuffers[this.data.uuid] === undefined) { + data2.interleavedBuffers[this.data.uuid] = this.data.toJSON(data2); + } + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + } + } + } + + class SpriteMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isSpriteMaterial = true; + this.type = "SpriteMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.alphaMap = null; + this.rotation = 0; + this.sizeAttenuation = true; + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.rotation = source.rotation; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } + } + var _geometry3; + var _intersectPoint2 = /* @__PURE__ */ new Vector32; + var _worldScale2 = /* @__PURE__ */ new Vector32; + var _mvPosition2 = /* @__PURE__ */ new Vector32; + var _alignedPosition2 = /* @__PURE__ */ new Vector22; + var _rotatedPosition2 = /* @__PURE__ */ new Vector22; + var _viewWorldMatrix2 = /* @__PURE__ */ new Matrix42; + var _vA3 = /* @__PURE__ */ new Vector32; + var _vB3 = /* @__PURE__ */ new Vector32; + var _vC3 = /* @__PURE__ */ new Vector32; + var _uvA2 = /* @__PURE__ */ new Vector22; + var _uvB2 = /* @__PURE__ */ new Vector22; + var _uvC2 = /* @__PURE__ */ new Vector22; + + class Sprite2 extends Object3D2 { + constructor(material = new SpriteMaterial2) { + super(); + this.isSprite = true; + this.type = "Sprite"; + if (_geometry3 === undefined) { + _geometry3 = new BufferGeometry2; + const float32Array = new Float32Array([ + -0.5, + -0.5, + 0, + 0, + 0, + 0.5, + -0.5, + 0, + 1, + 0, + 0.5, + 0.5, + 0, + 1, + 1, + -0.5, + 0.5, + 0, + 0, + 1 + ]); + const interleavedBuffer = new InterleavedBuffer2(float32Array, 5); + _geometry3.setIndex([0, 1, 2, 0, 2, 3]); + _geometry3.setAttribute("position", new InterleavedBufferAttribute2(interleavedBuffer, 3, 0, false)); + _geometry3.setAttribute("uv", new InterleavedBufferAttribute2(interleavedBuffer, 2, 3, false)); + } + this.geometry = _geometry3; + this.material = material; + this.center = new Vector22(0.5, 0.5); + } + raycast(raycaster, intersects3) { + if (raycaster.camera === null) { + console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'); + } + _worldScale2.setFromMatrixScale(this.matrixWorld); + _viewWorldMatrix2.copy(raycaster.camera.matrixWorld); + this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld); + _mvPosition2.setFromMatrixPosition(this.modelViewMatrix); + if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) { + _worldScale2.multiplyScalar(-_mvPosition2.z); + } + const rotation2 = this.material.rotation; + let sin, cos; + if (rotation2 !== 0) { + cos = Math.cos(rotation2); + sin = Math.sin(rotation2); + } + const center = this.center; + transformVertex2(_vA3.set(-0.5, -0.5, 0), _mvPosition2, center, _worldScale2, sin, cos); + transformVertex2(_vB3.set(0.5, -0.5, 0), _mvPosition2, center, _worldScale2, sin, cos); + transformVertex2(_vC3.set(0.5, 0.5, 0), _mvPosition2, center, _worldScale2, sin, cos); + _uvA2.set(0, 0); + _uvB2.set(1, 0); + _uvC2.set(1, 1); + let intersect3 = raycaster.ray.intersectTriangle(_vA3, _vB3, _vC3, false, _intersectPoint2); + if (intersect3 === null) { + transformVertex2(_vB3.set(-0.5, 0.5, 0), _mvPosition2, center, _worldScale2, sin, cos); + _uvB2.set(0, 1); + intersect3 = raycaster.ray.intersectTriangle(_vA3, _vC3, _vB3, false, _intersectPoint2); + if (intersect3 === null) { + return; + } + } + const distance = raycaster.ray.origin.distanceTo(_intersectPoint2); + if (distance < raycaster.near || distance > raycaster.far) + return; + intersects3.push({ + distance, + point: _intersectPoint2.clone(), + uv: Triangle2.getInterpolation(_intersectPoint2, _vA3, _vB3, _vC3, _uvA2, _uvB2, _uvC2, new Vector22), + face: null, + object: this + }); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.center !== undefined) + this.center.copy(source.center); + this.material = source.material; + return this; + } + } + function transformVertex2(vertexPosition, mvPosition, center, scale2, sin, cos) { + _alignedPosition2.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale2); + if (sin !== undefined) { + _rotatedPosition2.x = cos * _alignedPosition2.x - sin * _alignedPosition2.y; + _rotatedPosition2.y = sin * _alignedPosition2.x + cos * _alignedPosition2.y; + } else { + _rotatedPosition2.copy(_alignedPosition2); + } + vertexPosition.copy(mvPosition); + vertexPosition.x += _rotatedPosition2.x; + vertexPosition.y += _rotatedPosition2.y; + vertexPosition.applyMatrix4(_viewWorldMatrix2); + } + var _v1$22 = /* @__PURE__ */ new Vector32; + var _v2$12 = /* @__PURE__ */ new Vector32; + + class LOD2 extends Object3D2 { + constructor() { + super(); + this._currentLevel = 0; + this.type = "LOD"; + Object.defineProperties(this, { + levels: { + enumerable: true, + value: [] + }, + isLOD: { + value: true + } + }); + this.autoUpdate = true; + } + copy(source) { + super.copy(source, false); + const levels = source.levels; + for (let i = 0, l2 = levels.length;i < l2; i++) { + const level = levels[i]; + this.addLevel(level.object.clone(), level.distance, level.hysteresis); + } + this.autoUpdate = source.autoUpdate; + return this; + } + addLevel(object, distance = 0, hysteresis = 0) { + distance = Math.abs(distance); + const levels = this.levels; + let l2; + for (l2 = 0;l2 < levels.length; l2++) { + if (distance < levels[l2].distance) { + break; + } + } + levels.splice(l2, 0, { distance, hysteresis, object }); + this.add(object); + return this; + } + removeLevel(distance) { + const levels = this.levels; + for (let i = 0;i < levels.length; i++) { + if (levels[i].distance === distance) { + const removedElements = levels.splice(i, 1); + this.remove(removedElements[0].object); + return true; + } + } + return false; + } + getCurrentLevel() { + return this._currentLevel; + } + getObjectForDistance(distance) { + const levels = this.levels; + if (levels.length > 0) { + let i, l2; + for (i = 1, l2 = levels.length;i < l2; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance < levelDistance) { + break; + } + } + return levels[i - 1].object; + } + return null; + } + raycast(raycaster, intersects3) { + const levels = this.levels; + if (levels.length > 0) { + _v1$22.setFromMatrixPosition(this.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_v1$22); + this.getObjectForDistance(distance).raycast(raycaster, intersects3); + } + } + update(camera) { + const levels = this.levels; + if (levels.length > 1) { + _v1$22.setFromMatrixPosition(camera.matrixWorld); + _v2$12.setFromMatrixPosition(this.matrixWorld); + const distance = _v1$22.distanceTo(_v2$12) / camera.zoom; + levels[0].object.visible = true; + let i, l2; + for (i = 1, l2 = levels.length;i < l2; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance >= levelDistance) { + levels[i - 1].object.visible = false; + levels[i].object.visible = true; + } else { + break; + } + } + this._currentLevel = i - 1; + for (;i < l2; i++) { + levels[i].object.visible = false; + } + } + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + if (this.autoUpdate === false) + data2.object.autoUpdate = false; + data2.object.levels = []; + const levels = this.levels; + for (let i = 0, l2 = levels.length;i < l2; i++) { + const level = levels[i]; + data2.object.levels.push({ + object: level.object.uuid, + distance: level.distance, + hysteresis: level.hysteresis + }); + } + return data2; + } + } + var _basePosition2 = /* @__PURE__ */ new Vector32; + var _skinIndex2 = /* @__PURE__ */ new Vector42; + var _skinWeight2 = /* @__PURE__ */ new Vector42; + var _vector32 = /* @__PURE__ */ new Vector32; + var _matrix42 = /* @__PURE__ */ new Matrix42; + var _vertex2 = /* @__PURE__ */ new Vector32; + var _sphere$52 = /* @__PURE__ */ new Sphere2; + var _inverseMatrix$22 = /* @__PURE__ */ new Matrix42; + var _ray$22 = /* @__PURE__ */ new Ray2; + + class SkinnedMesh2 extends Mesh2 { + constructor(geometry, material) { + super(geometry, material); + this.isSkinnedMesh = true; + this.type = "SkinnedMesh"; + this.bindMode = AttachedBindMode2; + this.bindMatrix = new Matrix42; + this.bindMatrixInverse = new Matrix42; + this.boundingBox = null; + this.boundingSphere = null; + } + computeBoundingBox() { + const geometry = this.geometry; + if (this.boundingBox === null) { + this.boundingBox = new Box32; + } + this.boundingBox.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0;i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex2); + this.boundingBox.expandByPoint(_vertex2); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere2; + } + this.boundingSphere.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0;i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex2); + this.boundingSphere.expandByPoint(_vertex2); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.bindMode = source.bindMode; + this.bindMatrix.copy(source.bindMatrix); + this.bindMatrixInverse.copy(source.bindMatrixInverse); + this.skeleton = source.skeleton; + if (source.boundingBox !== null) + this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) + this.boundingSphere = source.boundingSphere.clone(); + return this; + } + raycast(raycaster, intersects3) { + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === undefined) + return; + if (this.boundingSphere === null) + this.computeBoundingSphere(); + _sphere$52.copy(this.boundingSphere); + _sphere$52.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$52) === false) + return; + _inverseMatrix$22.copy(matrixWorld).invert(); + _ray$22.copy(raycaster.ray).applyMatrix4(_inverseMatrix$22); + if (this.boundingBox !== null) { + if (_ray$22.intersectsBox(this.boundingBox) === false) + return; + } + this._computeIntersections(raycaster, intersects3, _ray$22); + } + getVertexPosition(index2, target) { + super.getVertexPosition(index2, target); + this.applyBoneTransform(index2, target); + return target; + } + bind(skeleton, bindMatrix) { + this.skeleton = skeleton; + if (bindMatrix === undefined) { + this.updateMatrixWorld(true); + this.skeleton.calculateInverses(); + bindMatrix = this.matrixWorld; + } + this.bindMatrix.copy(bindMatrix); + this.bindMatrixInverse.copy(bindMatrix).invert(); + } + pose() { + this.skeleton.pose(); + } + normalizeSkinWeights() { + const vector = new Vector42; + const skinWeight = this.geometry.attributes.skinWeight; + for (let i = 0, l2 = skinWeight.count;i < l2; i++) { + vector.fromBufferAttribute(skinWeight, i); + const scale2 = 1 / vector.manhattanLength(); + if (scale2 !== Infinity) { + vector.multiplyScalar(scale2); + } else { + vector.set(1, 0, 0, 0); + } + skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w); + } + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.bindMode === AttachedBindMode2) { + this.bindMatrixInverse.copy(this.matrixWorld).invert(); + } else if (this.bindMode === DetachedBindMode2) { + this.bindMatrixInverse.copy(this.bindMatrix).invert(); + } else { + console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode); + } + } + applyBoneTransform(index2, vector) { + const skeleton = this.skeleton; + const geometry = this.geometry; + _skinIndex2.fromBufferAttribute(geometry.attributes.skinIndex, index2); + _skinWeight2.fromBufferAttribute(geometry.attributes.skinWeight, index2); + _basePosition2.copy(vector).applyMatrix4(this.bindMatrix); + vector.set(0, 0, 0); + for (let i = 0;i < 4; i++) { + const weight = _skinWeight2.getComponent(i); + if (weight !== 0) { + const boneIndex = _skinIndex2.getComponent(i); + _matrix42.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]); + vector.addScaledVector(_vector32.copy(_basePosition2).applyMatrix4(_matrix42), weight); + } + } + return vector.applyMatrix4(this.bindMatrixInverse); + } + } + + class Bone2 extends Object3D2 { + constructor() { + super(); + this.isBone = true; + this.type = "Bone"; + } + } + + class DataTexture2 extends Texture2 { + constructor(data2 = null, width2 = 1, height2 = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter2, minFilter = NearestFilter2, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isDataTexture = true; + this.image = { data: data2, width: width2, height: height2 }; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } + } + var _offsetMatrix2 = /* @__PURE__ */ new Matrix42; + var _identityMatrix3 = /* @__PURE__ */ new Matrix42; + + class Skeleton2 { + constructor(bones = [], boneInverses = []) { + this.uuid = generateUUID2(); + this.bones = bones.slice(0); + this.boneInverses = boneInverses; + this.boneMatrices = null; + this.boneTexture = null; + this.init(); + } + init() { + const bones = this.bones; + const boneInverses = this.boneInverses; + this.boneMatrices = new Float32Array(bones.length * 16); + if (boneInverses.length === 0) { + this.calculateInverses(); + } else { + if (bones.length !== boneInverses.length) { + console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."); + this.boneInverses = []; + for (let i = 0, il = this.bones.length;i < il; i++) { + this.boneInverses.push(new Matrix42); + } + } + } + } + calculateInverses() { + this.boneInverses.length = 0; + for (let i = 0, il = this.bones.length;i < il; i++) { + const inverse2 = new Matrix42; + if (this.bones[i]) { + inverse2.copy(this.bones[i].matrixWorld).invert(); + } + this.boneInverses.push(inverse2); + } + } + pose() { + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone) { + bone.matrixWorld.copy(this.boneInverses[i]).invert(); + } + } + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone) { + if (bone.parent && bone.parent.isBone) { + bone.matrix.copy(bone.parent.matrixWorld).invert(); + bone.matrix.multiply(bone.matrixWorld); + } else { + bone.matrix.copy(bone.matrixWorld); + } + bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); + } + } + } + update() { + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; + for (let i = 0, il = bones.length;i < il; i++) { + const matrix3 = bones[i] ? bones[i].matrixWorld : _identityMatrix3; + _offsetMatrix2.multiplyMatrices(matrix3, boneInverses[i]); + _offsetMatrix2.toArray(boneMatrices, i * 16); + } + if (boneTexture !== null) { + boneTexture.needsUpdate = true; + } + } + clone() { + return new Skeleton2(this.bones, this.boneInverses); + } + computeBoneTexture() { + let size2 = Math.sqrt(this.bones.length * 4); + size2 = Math.ceil(size2 / 4) * 4; + size2 = Math.max(size2, 4); + const boneMatrices = new Float32Array(size2 * size2 * 4); + boneMatrices.set(this.boneMatrices); + const boneTexture = new DataTexture2(boneMatrices, size2, size2, RGBAFormat2, FloatType2); + boneTexture.needsUpdate = true; + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + return this; + } + getBoneByName(name2) { + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone.name === name2) { + return bone; + } + } + return; + } + dispose() { + if (this.boneTexture !== null) { + this.boneTexture.dispose(); + this.boneTexture = null; + } + } + fromJSON(json, bones) { + this.uuid = json.uuid; + for (let i = 0, l2 = json.bones.length;i < l2; i++) { + const uuid = json.bones[i]; + let bone = bones[uuid]; + if (bone === undefined) { + console.warn("THREE.Skeleton: No bone found with UUID:", uuid); + bone = new Bone2; + } + this.bones.push(bone); + this.boneInverses.push(new Matrix42().fromArray(json.boneInverses[i])); + } + this.init(); + return this; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "Skeleton", + generator: "Skeleton.toJSON" + }, + bones: [], + boneInverses: [] + }; + data2.uuid = this.uuid; + const bones = this.bones; + const boneInverses = this.boneInverses; + for (let i = 0, l2 = bones.length;i < l2; i++) { + const bone = bones[i]; + data2.bones.push(bone.uuid); + const boneInverse = boneInverses[i]; + data2.boneInverses.push(boneInverse.toArray()); + } + return data2; + } + } + + class InstancedBufferAttribute2 extends BufferAttribute2 { + constructor(array, itemSize, normalized, meshPerAttribute = 1) { + super(array, itemSize, normalized); + this.isInstancedBufferAttribute = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.meshPerAttribute = this.meshPerAttribute; + data2.isInstancedBufferAttribute = true; + return data2; + } + } + var _instanceLocalMatrix2 = /* @__PURE__ */ new Matrix42; + var _instanceWorldMatrix2 = /* @__PURE__ */ new Matrix42; + var _instanceIntersects2 = []; + var _box32 = /* @__PURE__ */ new Box32; + var _identity2 = /* @__PURE__ */ new Matrix42; + var _mesh$12 = /* @__PURE__ */ new Mesh2; + var _sphere$42 = /* @__PURE__ */ new Sphere2; + + class InstancedMesh2 extends Mesh2 { + constructor(geometry, material, count) { + super(geometry, material); + this.isInstancedMesh = true; + this.instanceMatrix = new InstancedBufferAttribute2(new Float32Array(count * 16), 16); + this.instanceColor = null; + this.morphTexture = null; + this.count = count; + this.boundingBox = null; + this.boundingSphere = null; + for (let i = 0;i < count; i++) { + this.setMatrixAt(i, _identity2); + } + } + computeBoundingBox() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingBox === null) { + this.boundingBox = new Box32; + } + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + this.boundingBox.makeEmpty(); + for (let i = 0;i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix2); + _box32.copy(geometry.boundingBox).applyMatrix4(_instanceLocalMatrix2); + this.boundingBox.union(_box32); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere2; + } + if (geometry.boundingSphere === null) { + geometry.computeBoundingSphere(); + } + this.boundingSphere.makeEmpty(); + for (let i = 0;i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix2); + _sphere$42.copy(geometry.boundingSphere).applyMatrix4(_instanceLocalMatrix2); + this.boundingSphere.union(_sphere$42); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.instanceMatrix.copy(source.instanceMatrix); + if (source.morphTexture !== null) + this.morphTexture = source.morphTexture.clone(); + if (source.instanceColor !== null) + this.instanceColor = source.instanceColor.clone(); + this.count = source.count; + if (source.boundingBox !== null) + this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) + this.boundingSphere = source.boundingSphere.clone(); + return this; + } + getColorAt(index2, color) { + color.fromArray(this.instanceColor.array, index2 * 3); + } + getMatrixAt(index2, matrix3) { + matrix3.fromArray(this.instanceMatrix.array, index2 * 16); + } + getMorphAt(index2, object) { + const objectInfluences = object.morphTargetInfluences; + const array = this.morphTexture.source.data.data; + const len = objectInfluences.length + 1; + const dataIndex = index2 * len + 1; + for (let i = 0;i < objectInfluences.length; i++) { + objectInfluences[i] = array[dataIndex + i]; + } + } + raycast(raycaster, intersects3) { + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + _mesh$12.geometry = this.geometry; + _mesh$12.material = this.material; + if (_mesh$12.material === undefined) + return; + if (this.boundingSphere === null) + this.computeBoundingSphere(); + _sphere$42.copy(this.boundingSphere); + _sphere$42.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$42) === false) + return; + for (let instanceId = 0;instanceId < raycastTimes; instanceId++) { + this.getMatrixAt(instanceId, _instanceLocalMatrix2); + _instanceWorldMatrix2.multiplyMatrices(matrixWorld, _instanceLocalMatrix2); + _mesh$12.matrixWorld = _instanceWorldMatrix2; + _mesh$12.raycast(raycaster, _instanceIntersects2); + for (let i = 0, l2 = _instanceIntersects2.length;i < l2; i++) { + const intersect3 = _instanceIntersects2[i]; + intersect3.instanceId = instanceId; + intersect3.object = this; + intersects3.push(intersect3); + } + _instanceIntersects2.length = 0; + } + } + setColorAt(index2, color) { + if (this.instanceColor === null) { + this.instanceColor = new InstancedBufferAttribute2(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3); + } + color.toArray(this.instanceColor.array, index2 * 3); + } + setMatrixAt(index2, matrix3) { + matrix3.toArray(this.instanceMatrix.array, index2 * 16); + } + setMorphAt(index2, object) { + const objectInfluences = object.morphTargetInfluences; + const len = objectInfluences.length + 1; + if (this.morphTexture === null) { + this.morphTexture = new DataTexture2(new Float32Array(len * this.count), len, this.count, RedFormat2, FloatType2); + } + const array = this.morphTexture.source.data.data; + let morphInfluencesSum = 0; + for (let i = 0;i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + const dataIndex = len * index2; + array[dataIndex] = morphBaseInfluence; + array.set(objectInfluences, dataIndex + 1); + } + updateMorphTargets() { + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + if (this.morphTexture !== null) { + this.morphTexture.dispose(); + this.morphTexture = null; + } + return this; + } + } + var _vector12 = /* @__PURE__ */ new Vector32; + var _vector22 = /* @__PURE__ */ new Vector32; + var _normalMatrix3 = /* @__PURE__ */ new Matrix32; + + class Plane2 { + constructor(normal = new Vector32(1, 0, 0), constant2 = 0) { + this.isPlane = true; + this.normal = normal; + this.constant = constant2; + } + set(normal, constant2) { + this.normal.copy(normal); + this.constant = constant2; + return this; + } + setComponents(x2, y, z, w) { + this.normal.set(x2, y, z); + this.constant = w; + return this; + } + setFromNormalAndCoplanarPoint(normal, point) { + this.normal.copy(normal); + this.constant = -point.dot(this.normal); + return this; + } + setFromCoplanarPoints(a2, b2, c2) { + const normal = _vector12.subVectors(c2, b2).cross(_vector22.subVectors(a2, b2)).normalize(); + this.setFromNormalAndCoplanarPoint(normal, a2); + return this; + } + copy(plane) { + this.normal.copy(plane.normal); + this.constant = plane.constant; + return this; + } + normalize() { + const inverseNormalLength = 1 / this.normal.length(); + this.normal.multiplyScalar(inverseNormalLength); + this.constant *= inverseNormalLength; + return this; + } + negate() { + this.constant *= -1; + this.normal.negate(); + return this; + } + distanceToPoint(point) { + return this.normal.dot(point) + this.constant; + } + distanceToSphere(sphere) { + return this.distanceToPoint(sphere.center) - sphere.radius; + } + projectPoint(point, target) { + return target.copy(point).addScaledVector(this.normal, -this.distanceToPoint(point)); + } + intersectLine(line2, target) { + const direction = line2.delta(_vector12); + const denominator = this.normal.dot(direction); + if (denominator === 0) { + if (this.distanceToPoint(line2.start) === 0) { + return target.copy(line2.start); + } + return null; + } + const t3 = -(line2.start.dot(this.normal) + this.constant) / denominator; + if (t3 < 0 || t3 > 1) { + return null; + } + return target.copy(line2.start).addScaledVector(direction, t3); + } + intersectsLine(line2) { + const startSign = this.distanceToPoint(line2.start); + const endSign = this.distanceToPoint(line2.end); + return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0; + } + intersectsBox(box) { + return box.intersectsPlane(this); + } + intersectsSphere(sphere) { + return sphere.intersectsPlane(this); + } + coplanarPoint(target) { + return target.copy(this.normal).multiplyScalar(-this.constant); + } + applyMatrix4(matrix3, optionalNormalMatrix) { + const normalMatrix = optionalNormalMatrix || _normalMatrix3.getNormalMatrix(matrix3); + const referencePoint = this.coplanarPoint(_vector12).applyMatrix4(matrix3); + const normal = this.normal.applyMatrix3(normalMatrix).normalize(); + this.constant = -referencePoint.dot(normal); + return this; + } + translate(offset) { + this.constant -= offset.dot(this.normal); + return this; + } + equals(plane) { + return plane.normal.equals(this.normal) && plane.constant === this.constant; + } + clone() { + return new this.constructor().copy(this); + } + } + var _sphere$32 = /* @__PURE__ */ new Sphere2; + var _vector$62 = /* @__PURE__ */ new Vector32; + + class Frustum2 { + constructor(p0 = new Plane2, p1 = new Plane2, p2 = new Plane2, p3 = new Plane2, p4 = new Plane2, p5 = new Plane2) { + this.planes = [p0, p1, p2, p3, p4, p5]; + } + set(p0, p1, p2, p3, p4, p5) { + const planes = this.planes; + planes[0].copy(p0); + planes[1].copy(p1); + planes[2].copy(p2); + planes[3].copy(p3); + planes[4].copy(p4); + planes[5].copy(p5); + return this; + } + copy(frustum) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + planes[i].copy(frustum.planes[i]); + } + return this; + } + setFromProjectionMatrix(m, coordinateSystem = WebGLCoordinateSystem2) { + const planes = this.planes; + const me = m.elements; + const me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3]; + const me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7]; + const me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11]; + const me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15]; + planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize(); + planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize(); + planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize(); + planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize(); + planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); + if (coordinateSystem === WebGLCoordinateSystem2) { + planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize(); + } else if (coordinateSystem === WebGPUCoordinateSystem2) { + planes[5].setComponents(me2, me6, me10, me14).normalize(); + } else { + throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + coordinateSystem); + } + return this; + } + intersectsObject(object) { + if (object.boundingSphere !== undefined) { + if (object.boundingSphere === null) + object.computeBoundingSphere(); + _sphere$32.copy(object.boundingSphere).applyMatrix4(object.matrixWorld); + } else { + const geometry = object.geometry; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$32.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld); + } + return this.intersectsSphere(_sphere$32); + } + intersectsSprite(sprite) { + _sphere$32.center.set(0, 0, 0); + _sphere$32.radius = 0.7071067811865476; + _sphere$32.applyMatrix4(sprite.matrixWorld); + return this.intersectsSphere(_sphere$32); + } + intersectsSphere(sphere) { + const planes = this.planes; + const center = sphere.center; + const negRadius = -sphere.radius; + for (let i = 0;i < 6; i++) { + const distance = planes[i].distanceToPoint(center); + if (distance < negRadius) { + return false; + } + } + return true; + } + intersectsBox(box) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + const plane = planes[i]; + _vector$62.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$62.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$62.z = plane.normal.z > 0 ? box.max.z : box.min.z; + if (plane.distanceToPoint(_vector$62) < 0) { + return false; + } + } + return true; + } + containsPoint(point) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + if (planes[i].distanceToPoint(point) < 0) { + return false; + } + } + return true; + } + clone() { + return new this.constructor().copy(this); + } + } + function ascIdSort2(a2, b2) { + return a2 - b2; + } + function sortOpaque2(a2, b2) { + return a2.z - b2.z; + } + function sortTransparent2(a2, b2) { + return b2.z - a2.z; + } + + class MultiDrawRenderList2 { + constructor() { + this.index = 0; + this.pool = []; + this.list = []; + } + push(start, count, z, index2) { + const pool = this.pool; + const list = this.list; + if (this.index >= pool.length) { + pool.push({ + start: -1, + count: -1, + z: -1, + index: -1 + }); + } + const item = pool[this.index]; + list.push(item); + this.index++; + item.start = start; + item.count = count; + item.z = z; + item.index = index2; + } + reset() { + this.list.length = 0; + this.index = 0; + } + } + var _matrix$12 = /* @__PURE__ */ new Matrix42; + var _whiteColor2 = /* @__PURE__ */ new Color2(1, 1, 1); + var _frustum3 = /* @__PURE__ */ new Frustum2; + var _box$12 = /* @__PURE__ */ new Box32; + var _sphere$22 = /* @__PURE__ */ new Sphere2; + var _vector$52 = /* @__PURE__ */ new Vector32; + var _forward2 = /* @__PURE__ */ new Vector32; + var _temp4 = /* @__PURE__ */ new Vector32; + var _renderList2 = /* @__PURE__ */ new MultiDrawRenderList2; + var _mesh2 = /* @__PURE__ */ new Mesh2; + var _batchIntersects2 = []; + function copyAttributeData2(src, target, targetOffset = 0) { + const itemSize = target.itemSize; + if (src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor) { + const vertexCount = src.count; + for (let i = 0;i < vertexCount; i++) { + for (let c2 = 0;c2 < itemSize; c2++) { + target.setComponent(i + targetOffset, c2, src.getComponent(i, c2)); + } + } + } else { + target.array.set(src.array, targetOffset * itemSize); + } + target.needsUpdate = true; + } + function copyArrayContents2(src, target) { + if (src.constructor !== target.constructor) { + const len = Math.min(src.length, target.length); + for (let i = 0;i < len; i++) { + target[i] = src[i]; + } + } else { + const len = Math.min(src.length, target.length); + target.set(new src.constructor(src.buffer, 0, len)); + } + } + + class BatchedMesh2 extends Mesh2 { + get maxInstanceCount() { + return this._maxInstanceCount; + } + get instanceCount() { + return this._instanceInfo.length - this._availableInstanceIds.length; + } + get unusedVertexCount() { + return this._maxVertexCount - this._nextVertexStart; + } + get unusedIndexCount() { + return this._maxIndexCount - this._nextIndexStart; + } + constructor(maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material) { + super(new BufferGeometry2, material); + this.isBatchedMesh = true; + this.perObjectFrustumCulled = true; + this.sortObjects = true; + this.boundingBox = null; + this.boundingSphere = null; + this.customSort = null; + this._instanceInfo = []; + this._geometryInfo = []; + this._availableInstanceIds = []; + this._availableGeometryIds = []; + this._nextIndexStart = 0; + this._nextVertexStart = 0; + this._geometryCount = 0; + this._visibilityChanged = true; + this._geometryInitialized = false; + this._maxInstanceCount = maxInstanceCount; + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + this._multiDrawCounts = new Int32Array(maxInstanceCount); + this._multiDrawStarts = new Int32Array(maxInstanceCount); + this._multiDrawCount = 0; + this._multiDrawInstances = null; + this._matricesTexture = null; + this._indirectTexture = null; + this._colorsTexture = null; + this._initMatricesTexture(); + this._initIndirectTexture(); + } + _initMatricesTexture() { + let size2 = Math.sqrt(this._maxInstanceCount * 4); + size2 = Math.ceil(size2 / 4) * 4; + size2 = Math.max(size2, 4); + const matricesArray = new Float32Array(size2 * size2 * 4); + const matricesTexture = new DataTexture2(matricesArray, size2, size2, RGBAFormat2, FloatType2); + this._matricesTexture = matricesTexture; + } + _initIndirectTexture() { + let size2 = Math.sqrt(this._maxInstanceCount); + size2 = Math.ceil(size2); + const indirectArray = new Uint32Array(size2 * size2); + const indirectTexture = new DataTexture2(indirectArray, size2, size2, RedIntegerFormat2, UnsignedIntType2); + this._indirectTexture = indirectTexture; + } + _initColorsTexture() { + let size2 = Math.sqrt(this._maxInstanceCount); + size2 = Math.ceil(size2); + const colorsArray = new Float32Array(size2 * size2 * 4).fill(1); + const colorsTexture = new DataTexture2(colorsArray, size2, size2, RGBAFormat2, FloatType2); + colorsTexture.colorSpace = ColorManagement2.workingColorSpace; + this._colorsTexture = colorsTexture; + } + _initializeGeometry(reference) { + const geometry = this.geometry; + const maxVertexCount = this._maxVertexCount; + const maxIndexCount = this._maxIndexCount; + if (this._geometryInitialized === false) { + for (const attributeName in reference.attributes) { + const srcAttribute = reference.getAttribute(attributeName); + const { array, itemSize, normalized } = srcAttribute; + const dstArray = new array.constructor(maxVertexCount * itemSize); + const dstAttribute = new BufferAttribute2(dstArray, itemSize, normalized); + geometry.setAttribute(attributeName, dstAttribute); + } + if (reference.getIndex() !== null) { + const indexArray = maxVertexCount > 65535 ? new Uint32Array(maxIndexCount) : new Uint16Array(maxIndexCount); + geometry.setIndex(new BufferAttribute2(indexArray, 1)); + } + this._geometryInitialized = true; + } + } + _validateGeometry(geometry) { + const batchGeometry = this.geometry; + if (Boolean(geometry.getIndex()) !== Boolean(batchGeometry.getIndex())) { + throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".'); + } + for (const attributeName in batchGeometry.attributes) { + if (!geometry.hasAttribute(attributeName)) { + throw new Error(`THREE.BatchedMesh: Added geometry missing "${attributeName}". All geometries must have consistent attributes.`); + } + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + if (srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized) { + throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value."); + } + } + } + validateInstanceId(instanceId) { + const instanceInfo = this._instanceInfo; + if (instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[instanceId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.`); + } + } + validateGeometryId(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.`); + } + } + setCustomSort(func) { + this.customSort = func; + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box32; + } + const boundingBox = this.boundingBox; + const instanceInfo = this._instanceInfo; + boundingBox.makeEmpty(); + for (let i = 0, l2 = instanceInfo.length;i < l2; i++) { + if (instanceInfo[i].active === false) + continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$12); + this.getBoundingBoxAt(geometryId, _box$12).applyMatrix4(_matrix$12); + boundingBox.union(_box$12); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere2; + } + const boundingSphere = this.boundingSphere; + const instanceInfo = this._instanceInfo; + boundingSphere.makeEmpty(); + for (let i = 0, l2 = instanceInfo.length;i < l2; i++) { + if (instanceInfo[i].active === false) + continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$12); + this.getBoundingSphereAt(geometryId, _sphere$22).applyMatrix4(_matrix$12); + boundingSphere.union(_sphere$22); + } + } + addInstance(geometryId) { + const atCapacity = this._instanceInfo.length >= this.maxInstanceCount; + if (atCapacity && this._availableInstanceIds.length === 0) { + throw new Error("THREE.BatchedMesh: Maximum item count reached."); + } + const instanceInfo = { + visible: true, + active: true, + geometryIndex: geometryId + }; + let drawId = null; + if (this._availableInstanceIds.length > 0) { + this._availableInstanceIds.sort(ascIdSort2); + drawId = this._availableInstanceIds.shift(); + this._instanceInfo[drawId] = instanceInfo; + } else { + drawId = this._instanceInfo.length; + this._instanceInfo.push(instanceInfo); + } + const matricesTexture = this._matricesTexture; + _matrix$12.identity().toArray(matricesTexture.image.data, drawId * 16); + matricesTexture.needsUpdate = true; + const colorsTexture = this._colorsTexture; + if (colorsTexture) { + _whiteColor2.toArray(colorsTexture.image.data, drawId * 4); + colorsTexture.needsUpdate = true; + } + this._visibilityChanged = true; + return drawId; + } + addGeometry(geometry, reservedVertexCount = -1, reservedIndexCount = -1) { + this._initializeGeometry(geometry); + this._validateGeometry(geometry); + const geometryInfo = { + vertexStart: -1, + vertexCount: -1, + reservedVertexCount: -1, + indexStart: -1, + indexCount: -1, + reservedIndexCount: -1, + start: -1, + count: -1, + boundingBox: null, + boundingSphere: null, + active: true + }; + const geometryInfoList = this._geometryInfo; + geometryInfo.vertexStart = this._nextVertexStart; + geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute("position").count : reservedVertexCount; + const index2 = geometry.getIndex(); + const hasIndex = index2 !== null; + if (hasIndex) { + geometryInfo.indexStart = this._nextIndexStart; + geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index2.count : reservedIndexCount; + } + if (geometryInfo.indexStart !== -1 && geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount || geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size."); + } + let geometryId; + if (this._availableGeometryIds.length > 0) { + this._availableGeometryIds.sort(ascIdSort2); + geometryId = this._availableGeometryIds.shift(); + geometryInfoList[geometryId] = geometryInfo; + } else { + geometryId = this._geometryCount; + this._geometryCount++; + geometryInfoList.push(geometryInfo); + } + this.setGeometryAt(geometryId, geometry); + this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + return geometryId; + } + setGeometryAt(geometryId, geometry) { + if (geometryId >= this._geometryCount) { + throw new Error("THREE.BatchedMesh: Maximum geometry count reached."); + } + this._validateGeometry(geometry); + const batchGeometry = this.geometry; + const hasIndex = batchGeometry.getIndex() !== null; + const dstIndex = batchGeometry.getIndex(); + const srcIndex = geometry.getIndex(); + const geometryInfo = this._geometryInfo[geometryId]; + if (hasIndex && srcIndex.count > geometryInfo.reservedIndexCount || geometry.attributes.position.count > geometryInfo.reservedVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry."); + } + const vertexStart = geometryInfo.vertexStart; + const reservedVertexCount = geometryInfo.reservedVertexCount; + geometryInfo.vertexCount = geometry.getAttribute("position").count; + for (const attributeName in batchGeometry.attributes) { + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + copyAttributeData2(srcAttribute, dstAttribute, vertexStart); + const itemSize = srcAttribute.itemSize; + for (let i = srcAttribute.count, l2 = reservedVertexCount;i < l2; i++) { + const index2 = vertexStart + i; + for (let c2 = 0;c2 < itemSize; c2++) { + dstAttribute.setComponent(index2, c2, 0); + } + } + dstAttribute.needsUpdate = true; + dstAttribute.addUpdateRange(vertexStart * itemSize, reservedVertexCount * itemSize); + } + if (hasIndex) { + const indexStart = geometryInfo.indexStart; + const reservedIndexCount = geometryInfo.reservedIndexCount; + geometryInfo.indexCount = geometry.getIndex().count; + for (let i = 0;i < srcIndex.count; i++) { + dstIndex.setX(indexStart + i, vertexStart + srcIndex.getX(i)); + } + for (let i = srcIndex.count, l2 = reservedIndexCount;i < l2; i++) { + dstIndex.setX(indexStart + i, vertexStart); + } + dstIndex.needsUpdate = true; + dstIndex.addUpdateRange(indexStart, geometryInfo.reservedIndexCount); + } + geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart; + geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount; + geometryInfo.boundingBox = null; + if (geometry.boundingBox !== null) { + geometryInfo.boundingBox = geometry.boundingBox.clone(); + } + geometryInfo.boundingSphere = null; + if (geometry.boundingSphere !== null) { + geometryInfo.boundingSphere = geometry.boundingSphere.clone(); + } + this._visibilityChanged = true; + return geometryId; + } + deleteGeometry(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + return this; + } + const instanceInfo = this._instanceInfo; + for (let i = 0, l2 = instanceInfo.length;i < l2; i++) { + if (instanceInfo[i].active && instanceInfo[i].geometryIndex === geometryId) { + this.deleteInstance(i); + } + } + geometryInfoList[geometryId].active = false; + this._availableGeometryIds.push(geometryId); + this._visibilityChanged = true; + return this; + } + deleteInstance(instanceId) { + this.validateInstanceId(instanceId); + this._instanceInfo[instanceId].active = false; + this._availableInstanceIds.push(instanceId); + this._visibilityChanged = true; + return this; + } + optimize() { + let nextVertexStart = 0; + let nextIndexStart = 0; + const geometryInfoList = this._geometryInfo; + const indices = geometryInfoList.map((e, i) => i).sort((a2, b2) => { + return geometryInfoList[a2].vertexStart - geometryInfoList[b2].vertexStart; + }); + const geometry = this.geometry; + for (let i = 0, l2 = geometryInfoList.length;i < l2; i++) { + const index2 = indices[i]; + const geometryInfo = geometryInfoList[index2]; + if (geometryInfo.active === false) { + continue; + } + if (geometry.index !== null) { + if (geometryInfo.indexStart !== nextIndexStart) { + const { indexStart, vertexStart, reservedIndexCount } = geometryInfo; + const index3 = geometry.index; + const array = index3.array; + const elementDelta = nextVertexStart - vertexStart; + for (let j2 = indexStart;j2 < indexStart + reservedIndexCount; j2++) { + array[j2] = array[j2] + elementDelta; + } + index3.array.copyWithin(nextIndexStart, indexStart, indexStart + reservedIndexCount); + index3.addUpdateRange(nextIndexStart, reservedIndexCount); + geometryInfo.indexStart = nextIndexStart; + } + nextIndexStart += geometryInfo.reservedIndexCount; + } + if (geometryInfo.vertexStart !== nextVertexStart) { + const { vertexStart, reservedVertexCount } = geometryInfo; + const attributes = geometry.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + const { array, itemSize } = attribute; + array.copyWithin(nextVertexStart * itemSize, vertexStart * itemSize, (vertexStart + reservedVertexCount) * itemSize); + attribute.addUpdateRange(nextVertexStart * itemSize, reservedVertexCount * itemSize); + } + geometryInfo.vertexStart = nextVertexStart; + } + nextVertexStart += geometryInfo.reservedVertexCount; + geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart; + this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + } + return this; + } + getBoundingBoxAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingBox === null) { + const box = new Box32; + const index2 = geometry.index; + const position2 = geometry.attributes.position; + for (let i = geometryInfo.start, l2 = geometryInfo.start + geometryInfo.count;i < l2; i++) { + let iv = i; + if (index2) { + iv = index2.getX(iv); + } + box.expandByPoint(_vector$52.fromBufferAttribute(position2, iv)); + } + geometryInfo.boundingBox = box; + } + target.copy(geometryInfo.boundingBox); + return target; + } + getBoundingSphereAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingSphere === null) { + const sphere = new Sphere2; + this.getBoundingBoxAt(geometryId, _box$12); + _box$12.getCenter(sphere.center); + const index2 = geometry.index; + const position2 = geometry.attributes.position; + let maxRadiusSq = 0; + for (let i = geometryInfo.start, l2 = geometryInfo.start + geometryInfo.count;i < l2; i++) { + let iv = i; + if (index2) { + iv = index2.getX(iv); + } + _vector$52.fromBufferAttribute(position2, iv); + maxRadiusSq = Math.max(maxRadiusSq, sphere.center.distanceToSquared(_vector$52)); + } + sphere.radius = Math.sqrt(maxRadiusSq); + geometryInfo.boundingSphere = sphere; + } + target.copy(geometryInfo.boundingSphere); + return target; + } + setMatrixAt(instanceId, matrix3) { + this.validateInstanceId(instanceId); + const matricesTexture = this._matricesTexture; + const matricesArray = this._matricesTexture.image.data; + matrix3.toArray(matricesArray, instanceId * 16); + matricesTexture.needsUpdate = true; + return this; + } + getMatrixAt(instanceId, matrix3) { + this.validateInstanceId(instanceId); + return matrix3.fromArray(this._matricesTexture.image.data, instanceId * 16); + } + setColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + if (this._colorsTexture === null) { + this._initColorsTexture(); + } + color.toArray(this._colorsTexture.image.data, instanceId * 4); + this._colorsTexture.needsUpdate = true; + return this; + } + getColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + return color.fromArray(this._colorsTexture.image.data, instanceId * 4); + } + setVisibleAt(instanceId, value2) { + this.validateInstanceId(instanceId); + if (this._instanceInfo[instanceId].visible === value2) { + return this; + } + this._instanceInfo[instanceId].visible = value2; + this._visibilityChanged = true; + return this; + } + getVisibleAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].visible; + } + setGeometryIdAt(instanceId, geometryId) { + this.validateInstanceId(instanceId); + this.validateGeometryId(geometryId); + this._instanceInfo[instanceId].geometryIndex = geometryId; + return this; + } + getGeometryIdAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].geometryIndex; + } + getGeometryRangeAt(geometryId, target = {}) { + this.validateGeometryId(geometryId); + const geometryInfo = this._geometryInfo[geometryId]; + target.vertexStart = geometryInfo.vertexStart; + target.vertexCount = geometryInfo.vertexCount; + target.reservedVertexCount = geometryInfo.reservedVertexCount; + target.indexStart = geometryInfo.indexStart; + target.indexCount = geometryInfo.indexCount; + target.reservedIndexCount = geometryInfo.reservedIndexCount; + target.start = geometryInfo.start; + target.count = geometryInfo.count; + return target; + } + setInstanceCount(maxInstanceCount) { + const availableInstanceIds = this._availableInstanceIds; + const instanceInfo = this._instanceInfo; + availableInstanceIds.sort(ascIdSort2); + while (availableInstanceIds[availableInstanceIds.length - 1] === instanceInfo.length) { + instanceInfo.pop(); + availableInstanceIds.pop(); + } + if (maxInstanceCount < instanceInfo.length) { + throw new Error(`BatchedMesh: Instance ids outside the range ${maxInstanceCount} are being used. Cannot shrink instance count.`); + } + const multiDrawCounts = new Int32Array(maxInstanceCount); + const multiDrawStarts = new Int32Array(maxInstanceCount); + copyArrayContents2(this._multiDrawCounts, multiDrawCounts); + copyArrayContents2(this._multiDrawStarts, multiDrawStarts); + this._multiDrawCounts = multiDrawCounts; + this._multiDrawStarts = multiDrawStarts; + this._maxInstanceCount = maxInstanceCount; + const indirectTexture = this._indirectTexture; + const matricesTexture = this._matricesTexture; + const colorsTexture = this._colorsTexture; + indirectTexture.dispose(); + this._initIndirectTexture(); + copyArrayContents2(indirectTexture.image.data, this._indirectTexture.image.data); + matricesTexture.dispose(); + this._initMatricesTexture(); + copyArrayContents2(matricesTexture.image.data, this._matricesTexture.image.data); + if (colorsTexture) { + colorsTexture.dispose(); + this._initColorsTexture(); + copyArrayContents2(colorsTexture.image.data, this._colorsTexture.image.data); + } + } + setGeometrySize(maxVertexCount, maxIndexCount) { + const validRanges = [...this._geometryInfo].filter((info) => info.active); + const requiredVertexLength = Math.max(...validRanges.map((range) => range.vertexStart + range.reservedVertexCount)); + if (requiredVertexLength > maxVertexCount) { + throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + if (this.geometry.index) { + const requiredIndexLength = Math.max(...validRanges.map((range) => range.indexStart + range.reservedIndexCount)); + if (requiredIndexLength > maxIndexCount) { + throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + } + const oldGeometry = this.geometry; + oldGeometry.dispose(); + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + if (this._geometryInitialized) { + this._geometryInitialized = false; + this.geometry = new BufferGeometry2; + this._initializeGeometry(oldGeometry); + } + const geometry = this.geometry; + if (oldGeometry.index) { + copyArrayContents2(oldGeometry.index.array, geometry.index.array); + } + for (const key2 in oldGeometry.attributes) { + copyArrayContents2(oldGeometry.attributes[key2].array, geometry.attributes[key2].array); + } + } + raycast(raycaster, intersects3) { + const instanceInfo = this._instanceInfo; + const geometryInfoList = this._geometryInfo; + const matrixWorld = this.matrixWorld; + const batchGeometry = this.geometry; + _mesh2.material = this.material; + _mesh2.geometry.index = batchGeometry.index; + _mesh2.geometry.attributes = batchGeometry.attributes; + if (_mesh2.geometry.boundingBox === null) { + _mesh2.geometry.boundingBox = new Box32; + } + if (_mesh2.geometry.boundingSphere === null) { + _mesh2.geometry.boundingSphere = new Sphere2; + } + for (let i = 0, l2 = instanceInfo.length;i < l2; i++) { + if (!instanceInfo[i].visible || !instanceInfo[i].active) { + continue; + } + const geometryId = instanceInfo[i].geometryIndex; + const geometryInfo = geometryInfoList[geometryId]; + _mesh2.geometry.setDrawRange(geometryInfo.start, geometryInfo.count); + this.getMatrixAt(i, _mesh2.matrixWorld).premultiply(matrixWorld); + this.getBoundingBoxAt(geometryId, _mesh2.geometry.boundingBox); + this.getBoundingSphereAt(geometryId, _mesh2.geometry.boundingSphere); + _mesh2.raycast(raycaster, _batchIntersects2); + for (let j2 = 0, l3 = _batchIntersects2.length;j2 < l3; j2++) { + const intersect3 = _batchIntersects2[j2]; + intersect3.object = this; + intersect3.batchId = i; + intersects3.push(intersect3); + } + _batchIntersects2.length = 0; + } + _mesh2.material = null; + _mesh2.geometry.index = null; + _mesh2.geometry.attributes = {}; + _mesh2.geometry.setDrawRange(0, Infinity); + } + copy(source) { + super.copy(source); + this.geometry = source.geometry.clone(); + this.perObjectFrustumCulled = source.perObjectFrustumCulled; + this.sortObjects = source.sortObjects; + this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null; + this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null; + this._geometryInfo = source._geometryInfo.map((info) => ({ + ...info, + boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null, + boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null + })); + this._instanceInfo = source._instanceInfo.map((info) => ({ ...info })); + this._maxInstanceCount = source._maxInstanceCount; + this._maxVertexCount = source._maxVertexCount; + this._maxIndexCount = source._maxIndexCount; + this._geometryInitialized = source._geometryInitialized; + this._geometryCount = source._geometryCount; + this._multiDrawCounts = source._multiDrawCounts.slice(); + this._multiDrawStarts = source._multiDrawStarts.slice(); + this._matricesTexture = source._matricesTexture.clone(); + this._matricesTexture.image.data = this._matricesTexture.image.data.slice(); + if (this._colorsTexture !== null) { + this._colorsTexture = source._colorsTexture.clone(); + this._colorsTexture.image.data = this._colorsTexture.image.data.slice(); + } + return this; + } + dispose() { + this.geometry.dispose(); + this._matricesTexture.dispose(); + this._matricesTexture = null; + this._indirectTexture.dispose(); + this._indirectTexture = null; + if (this._colorsTexture !== null) { + this._colorsTexture.dispose(); + this._colorsTexture = null; + } + return this; + } + onBeforeRender(renderer2, scene, camera, geometry, material) { + if (!this._visibilityChanged && !this.perObjectFrustumCulled && !this.sortObjects) { + return; + } + const index2 = geometry.getIndex(); + const bytesPerElement = index2 === null ? 1 : index2.array.BYTES_PER_ELEMENT; + const instanceInfo = this._instanceInfo; + const multiDrawStarts = this._multiDrawStarts; + const multiDrawCounts = this._multiDrawCounts; + const geometryInfoList = this._geometryInfo; + const perObjectFrustumCulled = this.perObjectFrustumCulled; + const indirectTexture = this._indirectTexture; + const indirectArray = indirectTexture.image.data; + if (perObjectFrustumCulled) { + _matrix$12.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).multiply(this.matrixWorld); + _frustum3.setFromProjectionMatrix(_matrix$12, renderer2.coordinateSystem); + } + let multiDrawCount = 0; + if (this.sortObjects) { + _matrix$12.copy(this.matrixWorld).invert(); + _vector$52.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(_matrix$12); + _forward2.set(0, 0, -1).transformDirection(camera.matrixWorld).transformDirection(_matrix$12); + for (let i = 0, l2 = instanceInfo.length;i < l2; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$12); + this.getBoundingSphereAt(geometryId, _sphere$22).applyMatrix4(_matrix$12); + let culled = false; + if (perObjectFrustumCulled) { + culled = !_frustum3.intersectsSphere(_sphere$22); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + const z = _temp4.subVectors(_sphere$22.center, _vector$52).dot(_forward2); + _renderList2.push(geometryInfo.start, geometryInfo.count, z, i); + } + } + } + const list = _renderList2.list; + const customSort = this.customSort; + if (customSort === null) { + list.sort(material.transparent ? sortTransparent2 : sortOpaque2); + } else { + customSort.call(this, list, camera); + } + for (let i = 0, l2 = list.length;i < l2; i++) { + const item = list[i]; + multiDrawStarts[multiDrawCount] = item.start * bytesPerElement; + multiDrawCounts[multiDrawCount] = item.count; + indirectArray[multiDrawCount] = item.index; + multiDrawCount++; + } + _renderList2.reset(); + } else { + for (let i = 0, l2 = instanceInfo.length;i < l2; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + let culled = false; + if (perObjectFrustumCulled) { + this.getMatrixAt(i, _matrix$12); + this.getBoundingSphereAt(geometryId, _sphere$22).applyMatrix4(_matrix$12); + culled = !_frustum3.intersectsSphere(_sphere$22); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + multiDrawStarts[multiDrawCount] = geometryInfo.start * bytesPerElement; + multiDrawCounts[multiDrawCount] = geometryInfo.count; + indirectArray[multiDrawCount] = i; + multiDrawCount++; + } + } + } + } + indirectTexture.needsUpdate = true; + this._multiDrawCount = multiDrawCount; + this._visibilityChanged = false; + } + onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial) { + this.onBeforeRender(renderer2, null, shadowCamera, geometry, depthMaterial); + } + } + + class LineBasicMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isLineBasicMaterial = true; + this.type = "LineBasicMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.linewidth = 1; + this.linecap = "round"; + this.linejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + this.fog = source.fog; + return this; + } + } + var _vStart2 = /* @__PURE__ */ new Vector32; + var _vEnd2 = /* @__PURE__ */ new Vector32; + var _inverseMatrix$12 = /* @__PURE__ */ new Matrix42; + var _ray$12 = /* @__PURE__ */ new Ray2; + var _sphere$12 = /* @__PURE__ */ new Sphere2; + var _intersectPointOnRay2 = /* @__PURE__ */ new Vector32; + var _intersectPointOnSegment2 = /* @__PURE__ */ new Vector32; + + class Line4 extends Object3D2 { + constructor(geometry = new BufferGeometry2, material = new LineBasicMaterial2) { + super(); + this.isLine = true; + this.type = "Line"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = [0]; + for (let i = 1, l2 = positionAttribute.count;i < l2; i++) { + _vStart2.fromBufferAttribute(positionAttribute, i - 1); + _vEnd2.fromBufferAttribute(positionAttribute, i); + lineDistances[i] = lineDistances[i - 1]; + lineDistances[i] += _vStart2.distanceTo(_vEnd2); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute2(lineDistances, 1)); + } else { + console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + raycast(raycaster, intersects3) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$12.copy(geometry.boundingSphere); + _sphere$12.applyMatrix4(matrixWorld); + _sphere$12.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere$12) === false) + return; + _inverseMatrix$12.copy(matrixWorld).invert(); + _ray$12.copy(raycaster.ray).applyMatrix4(_inverseMatrix$12); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const step = this.isLineSegments ? 2 : 1; + const index2 = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index2 !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, l2 = end - 1;i < l2; i += step) { + const a2 = index2.getX(i); + const b2 = index2.getX(i + 1); + const intersect3 = checkIntersection2(this, raycaster, _ray$12, localThresholdSq, a2, b2, i); + if (intersect3) { + intersects3.push(intersect3); + } + } + if (this.isLineLoop) { + const a2 = index2.getX(end - 1); + const b2 = index2.getX(start); + const intersect3 = checkIntersection2(this, raycaster, _ray$12, localThresholdSq, a2, b2, end - 1); + if (intersect3) { + intersects3.push(intersect3); + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l2 = end - 1;i < l2; i += step) { + const intersect3 = checkIntersection2(this, raycaster, _ray$12, localThresholdSq, i, i + 1, i); + if (intersect3) { + intersects3.push(intersect3); + } + } + if (this.isLineLoop) { + const intersect3 = checkIntersection2(this, raycaster, _ray$12, localThresholdSq, end - 1, start, end - 1); + if (intersect3) { + intersects3.push(intersect3); + } + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } + } + function checkIntersection2(object, raycaster, ray, thresholdSq, a2, b2, i) { + const positionAttribute = object.geometry.attributes.position; + _vStart2.fromBufferAttribute(positionAttribute, a2); + _vEnd2.fromBufferAttribute(positionAttribute, b2); + const distSq = ray.distanceSqToSegment(_vStart2, _vEnd2, _intersectPointOnRay2, _intersectPointOnSegment2); + if (distSq > thresholdSq) + return; + _intersectPointOnRay2.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectPointOnRay2); + if (distance < raycaster.near || distance > raycaster.far) + return; + return { + distance, + point: _intersectPointOnSegment2.clone().applyMatrix4(object.matrixWorld), + index: i, + face: null, + faceIndex: null, + barycoord: null, + object + }; + } + var _start5 = /* @__PURE__ */ new Vector32; + var _end5 = /* @__PURE__ */ new Vector32; + + class LineSegments3 extends Line4 { + constructor(geometry, material) { + super(geometry, material); + this.isLineSegments = true; + this.type = "LineSegments"; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + for (let i = 0, l2 = positionAttribute.count;i < l2; i += 2) { + _start5.fromBufferAttribute(positionAttribute, i); + _end5.fromBufferAttribute(positionAttribute, i + 1); + lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1]; + lineDistances[i + 1] = lineDistances[i] + _start5.distanceTo(_end5); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute2(lineDistances, 1)); + } else { + console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + } + + class LineLoop2 extends Line4 { + constructor(geometry, material) { + super(geometry, material); + this.isLineLoop = true; + this.type = "LineLoop"; + } + } + + class PointsMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isPointsMaterial = true; + this.type = "PointsMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.alphaMap = null; + this.size = 1; + this.sizeAttenuation = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } + } + var _inverseMatrix3 = /* @__PURE__ */ new Matrix42; + var _ray4 = /* @__PURE__ */ new Ray2; + var _sphere4 = /* @__PURE__ */ new Sphere2; + var _position$22 = /* @__PURE__ */ new Vector32; + + class Points2 extends Object3D2 { + constructor(geometry = new BufferGeometry2, material = new PointsMaterial2) { + super(); + this.isPoints = true; + this.type = "Points"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + raycast(raycaster, intersects3) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere4.copy(geometry.boundingSphere); + _sphere4.applyMatrix4(matrixWorld); + _sphere4.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere4) === false) + return; + _inverseMatrix3.copy(matrixWorld).invert(); + _ray4.copy(raycaster.ray).applyMatrix4(_inverseMatrix3); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const index2 = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index2 !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i++) { + const a2 = index2.getX(i); + _position$22.fromBufferAttribute(positionAttribute, a2); + testPoint2(_position$22, a2, localThresholdSq, matrixWorld, raycaster, intersects3, this); + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l2 = end;i < l2; i++) { + _position$22.fromBufferAttribute(positionAttribute, i); + testPoint2(_position$22, i, localThresholdSq, matrixWorld, raycaster, intersects3, this); + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } + } + function testPoint2(point, index2, localThresholdSq, matrixWorld, raycaster, intersects3, object) { + const rayPointDistanceSq = _ray4.distanceSqToPoint(point); + if (rayPointDistanceSq < localThresholdSq) { + const intersectPoint = new Vector32; + _ray4.closestPointToPoint(point, intersectPoint); + intersectPoint.applyMatrix4(matrixWorld); + const distance = raycaster.ray.origin.distanceTo(intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) + return; + intersects3.push({ + distance, + distanceToRay: Math.sqrt(rayPointDistanceSq), + point: intersectPoint, + index: index2, + face: null, + faceIndex: null, + barycoord: null, + object + }); + } + } + + class VideoTexture2 extends Texture2 { + constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoTexture = true; + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter2; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter2; + this.generateMipmaps = false; + const scope = this; + function updateVideo() { + scope.needsUpdate = true; + video.requestVideoFrameCallback(updateVideo); + } + if ("requestVideoFrameCallback" in video) { + video.requestVideoFrameCallback(updateVideo); + } + } + clone() { + return new this.constructor(this.image).copy(this); + } + update() { + const video = this.image; + const hasVideoFrameCallback = "requestVideoFrameCallback" in video; + if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) { + this.needsUpdate = true; + } + } + } + + class VideoFrameTexture2 extends VideoTexture2 { + constructor(mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super({}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoFrameTexture = true; + } + update() { + } + clone() { + return new this.constructor().copy(this); + } + setFrame(frame) { + this.image = frame; + this.needsUpdate = true; + } + } + + class FramebufferTexture2 extends Texture2 { + constructor(width2, height2) { + super({ width: width2, height: height2 }); + this.isFramebufferTexture = true; + this.magFilter = NearestFilter2; + this.minFilter = NearestFilter2; + this.generateMipmaps = false; + this.needsUpdate = true; + } + } + + class CompressedTexture2 extends Texture2 { + constructor(mipmaps, width2, height2, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCompressedTexture = true; + this.image = { width: width2, height: height2 }; + this.mipmaps = mipmaps; + this.flipY = false; + this.generateMipmaps = false; + } + } + + class CompressedArrayTexture2 extends CompressedTexture2 { + constructor(mipmaps, width2, height2, depth, format, type) { + super(mipmaps, width2, height2, format, type); + this.isCompressedArrayTexture = true; + this.image.depth = depth; + this.wrapR = ClampToEdgeWrapping2; + this.layerUpdates = new Set; + } + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + clearLayerUpdates() { + this.layerUpdates.clear(); + } + } + + class CompressedCubeTexture2 extends CompressedTexture2 { + constructor(images, format, type) { + super(undefined, images[0].width, images[0].height, format, type, CubeReflectionMapping2); + this.isCompressedCubeTexture = true; + this.isCubeTexture = true; + this.image = images; + } + } + + class CanvasTexture2 extends Texture2 { + constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isCanvasTexture = true; + this.needsUpdate = true; + } + } + + class DepthTexture2 extends Texture2 { + constructor(width2, height2, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat2) { + if (format !== DepthFormat2 && format !== DepthStencilFormat2) { + throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); + } + if (type === undefined && format === DepthFormat2) + type = UnsignedIntType2; + if (type === undefined && format === DepthStencilFormat2) + type = UnsignedInt248Type2; + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isDepthTexture = true; + this.image = { width: width2, height: height2 }; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter2; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter2; + this.flipY = false; + this.generateMipmaps = false; + this.compareFunction = null; + } + copy(source) { + super.copy(source); + this.compareFunction = source.compareFunction; + return this; + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + if (this.compareFunction !== null) + data2.compareFunction = this.compareFunction; + return data2; + } + } + + class Curve2 { + constructor() { + this.type = "Curve"; + this.arcLengthDivisions = 200; + } + getPoint() { + console.warn("THREE.Curve: .getPoint() not implemented."); + return null; + } + getPointAt(u2, optionalTarget) { + const t3 = this.getUtoTmapping(u2); + return this.getPoint(t3, optionalTarget); + } + getPoints(divisions = 5) { + const points = []; + for (let d = 0;d <= divisions; d++) { + points.push(this.getPoint(d / divisions)); + } + return points; + } + getSpacedPoints(divisions = 5) { + const points = []; + for (let d = 0;d <= divisions; d++) { + points.push(this.getPointAt(d / divisions)); + } + return points; + } + getLength() { + const lengths2 = this.getLengths(); + return lengths2[lengths2.length - 1]; + } + getLengths(divisions = this.arcLengthDivisions) { + if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) { + return this.cacheArcLengths; + } + this.needsUpdate = false; + const cache = []; + let current, last2 = this.getPoint(0); + let sum2 = 0; + cache.push(0); + for (let p = 1;p <= divisions; p++) { + current = this.getPoint(p / divisions); + sum2 += current.distanceTo(last2); + cache.push(sum2); + last2 = current; + } + this.cacheArcLengths = cache; + return cache; + } + updateArcLengths() { + this.needsUpdate = true; + this.getLengths(); + } + getUtoTmapping(u2, distance) { + const arcLengths = this.getLengths(); + let i = 0; + const il = arcLengths.length; + let targetArcLength; + if (distance) { + targetArcLength = distance; + } else { + targetArcLength = u2 * arcLengths[il - 1]; + } + let low = 0, high = il - 1, comparison; + while (low <= high) { + i = Math.floor(low + (high - low) / 2); + comparison = arcLengths[i] - targetArcLength; + if (comparison < 0) { + low = i + 1; + } else if (comparison > 0) { + high = i - 1; + } else { + high = i; + break; + } + } + i = high; + if (arcLengths[i] === targetArcLength) { + return i / (il - 1); + } + const lengthBefore = arcLengths[i]; + const lengthAfter = arcLengths[i + 1]; + const segmentLength = lengthAfter - lengthBefore; + const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; + const t3 = (i + segmentFraction) / (il - 1); + return t3; + } + getTangent(t3, optionalTarget) { + const delta = 0.0001; + let t1 = t3 - delta; + let t22 = t3 + delta; + if (t1 < 0) + t1 = 0; + if (t22 > 1) + t22 = 1; + const pt1 = this.getPoint(t1); + const pt2 = this.getPoint(t22); + const tangent = optionalTarget || (pt1.isVector2 ? new Vector22 : new Vector32); + tangent.copy(pt2).sub(pt1).normalize(); + return tangent; + } + getTangentAt(u2, optionalTarget) { + const t3 = this.getUtoTmapping(u2); + return this.getTangent(t3, optionalTarget); + } + computeFrenetFrames(segments, closed) { + const normal = new Vector32; + const tangents = []; + const normals = []; + const binormals = []; + const vec = new Vector32; + const mat = new Matrix42; + for (let i = 0;i <= segments; i++) { + const u2 = i / segments; + tangents[i] = this.getTangentAt(u2, new Vector32); + } + normals[0] = new Vector32; + binormals[0] = new Vector32; + let min = Number.MAX_VALUE; + const tx = Math.abs(tangents[0].x); + const ty = Math.abs(tangents[0].y); + const tz = Math.abs(tangents[0].z); + if (tx <= min) { + min = tx; + normal.set(1, 0, 0); + } + if (ty <= min) { + min = ty; + normal.set(0, 1, 0); + } + if (tz <= min) { + normal.set(0, 0, 1); + } + vec.crossVectors(tangents[0], normal).normalize(); + normals[0].crossVectors(tangents[0], vec); + binormals[0].crossVectors(tangents[0], normals[0]); + for (let i = 1;i <= segments; i++) { + normals[i] = normals[i - 1].clone(); + binormals[i] = binormals[i - 1].clone(); + vec.crossVectors(tangents[i - 1], tangents[i]); + if (vec.length() > Number.EPSILON) { + vec.normalize(); + const theta = Math.acos(clamp3(tangents[i - 1].dot(tangents[i]), -1, 1)); + normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta)); + } + binormals[i].crossVectors(tangents[i], normals[i]); + } + if (closed === true) { + let theta = Math.acos(clamp3(normals[0].dot(normals[segments]), -1, 1)); + theta /= segments; + if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) { + theta = -theta; + } + for (let i = 1;i <= segments; i++) { + normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i)); + binormals[i].crossVectors(tangents[i], normals[i]); + } + } + return { + tangents, + normals, + binormals + }; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.arcLengthDivisions = source.arcLengthDivisions; + return this; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "Curve", + generator: "Curve.toJSON" + } + }; + data2.arcLengthDivisions = this.arcLengthDivisions; + data2.type = this.type; + return data2; + } + fromJSON(json) { + this.arcLengthDivisions = json.arcLengthDivisions; + return this; + } + } + + class EllipseCurve2 extends Curve2 { + constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) { + super(); + this.isEllipseCurve = true; + this.type = "EllipseCurve"; + this.aX = aX; + this.aY = aY; + this.xRadius = xRadius; + this.yRadius = yRadius; + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; + this.aClockwise = aClockwise; + this.aRotation = aRotation; + } + getPoint(t3, optionalTarget = new Vector22) { + const point = optionalTarget; + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs(deltaAngle) < Number.EPSILON; + while (deltaAngle < 0) + deltaAngle += twoPi; + while (deltaAngle > twoPi) + deltaAngle -= twoPi; + if (deltaAngle < Number.EPSILON) { + if (samePoints) { + deltaAngle = 0; + } else { + deltaAngle = twoPi; + } + } + if (this.aClockwise === true && !samePoints) { + if (deltaAngle === twoPi) { + deltaAngle = -twoPi; + } else { + deltaAngle = deltaAngle - twoPi; + } + } + const angle = this.aStartAngle + t3 * deltaAngle; + let x2 = this.aX + this.xRadius * Math.cos(angle); + let y = this.aY + this.yRadius * Math.sin(angle); + if (this.aRotation !== 0) { + const cos = Math.cos(this.aRotation); + const sin = Math.sin(this.aRotation); + const tx = x2 - this.aX; + const ty = y - this.aY; + x2 = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; + } + return point.set(x2, y); + } + copy(source) { + super.copy(source); + this.aX = source.aX; + this.aY = source.aY; + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + this.aClockwise = source.aClockwise; + this.aRotation = source.aRotation; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.aX = this.aX; + data2.aY = this.aY; + data2.xRadius = this.xRadius; + data2.yRadius = this.yRadius; + data2.aStartAngle = this.aStartAngle; + data2.aEndAngle = this.aEndAngle; + data2.aClockwise = this.aClockwise; + data2.aRotation = this.aRotation; + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.aX = json.aX; + this.aY = json.aY; + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + this.aClockwise = json.aClockwise; + this.aRotation = json.aRotation; + return this; + } + } + + class ArcCurve2 extends EllipseCurve2 { + constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + this.isArcCurve = true; + this.type = "ArcCurve"; + } + } + function CubicPoly2() { + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + function init(x0, x1, t0, t1) { + c0 = x0; + c1 = t0; + c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + } + return { + initCatmullRom: function(x0, x1, x2, x3, tension) { + init(x1, x2, tension * (x2 - x0), tension * (x3 - x1)); + }, + initNonuniformCatmullRom: function(x0, x1, x2, x3, dt0, dt1, dt2) { + let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1; + let t22 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; + t1 *= dt1; + t22 *= dt1; + init(x1, x2, t1, t22); + }, + calc: function(t3) { + const t22 = t3 * t3; + const t32 = t22 * t3; + return c0 + c1 * t3 + c2 * t22 + c3 * t32; + } + }; + } + var tmp2 = /* @__PURE__ */ new Vector32; + var px2 = /* @__PURE__ */ new CubicPoly2; + var py2 = /* @__PURE__ */ new CubicPoly2; + var pz2 = /* @__PURE__ */ new CubicPoly2; + + class CatmullRomCurve32 extends Curve2 { + constructor(points = [], closed = false, curveType = "centripetal", tension = 0.5) { + super(); + this.isCatmullRomCurve3 = true; + this.type = "CatmullRomCurve3"; + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + } + getPoint(t3, optionalTarget = new Vector32) { + const point = optionalTarget; + const points = this.points; + const l2 = points.length; + const p = (l2 - (this.closed ? 0 : 1)) * t3; + let intPoint = Math.floor(p); + let weight = p - intPoint; + if (this.closed) { + intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l2) + 1) * l2; + } else if (weight === 0 && intPoint === l2 - 1) { + intPoint = l2 - 2; + weight = 1; + } + let p0, p3; + if (this.closed || intPoint > 0) { + p0 = points[(intPoint - 1) % l2]; + } else { + tmp2.subVectors(points[0], points[1]).add(points[0]); + p0 = tmp2; + } + const p1 = points[intPoint % l2]; + const p2 = points[(intPoint + 1) % l2]; + if (this.closed || intPoint + 2 < l2) { + p3 = points[(intPoint + 2) % l2]; + } else { + tmp2.subVectors(points[l2 - 1], points[l2 - 2]).add(points[l2 - 1]); + p3 = tmp2; + } + if (this.curveType === "centripetal" || this.curveType === "chordal") { + const pow = this.curveType === "chordal" ? 0.5 : 0.25; + let dt0 = Math.pow(p0.distanceToSquared(p1), pow); + let dt1 = Math.pow(p1.distanceToSquared(p2), pow); + let dt2 = Math.pow(p2.distanceToSquared(p3), pow); + if (dt1 < 0.0001) + dt1 = 1; + if (dt0 < 0.0001) + dt0 = dt1; + if (dt2 < 0.0001) + dt2 = dt1; + px2.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2); + py2.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2); + pz2.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2); + } else if (this.curveType === "catmullrom") { + px2.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension); + py2.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension); + pz2.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension); + } + point.set(px2.calc(weight), py2.calc(weight), pz2.calc(weight)); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l2 = source.points.length;i < l2; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.points = []; + for (let i = 0, l2 = this.points.length;i < l2; i++) { + const point = this.points[i]; + data2.points.push(point.toArray()); + } + data2.closed = this.closed; + data2.curveType = this.curveType; + data2.tension = this.tension; + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l2 = json.points.length;i < l2; i++) { + const point = json.points[i]; + this.points.push(new Vector32().fromArray(point)); + } + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + return this; + } + } + function CatmullRom2(t3, p0, p1, p2, p3) { + const v0 = (p2 - p0) * 0.5; + const v12 = (p3 - p1) * 0.5; + const t22 = t3 * t3; + const t32 = t3 * t22; + return (2 * p1 - 2 * p2 + v0 + v12) * t32 + (-3 * p1 + 3 * p2 - 2 * v0 - v12) * t22 + v0 * t3 + p1; + } + function QuadraticBezierP02(t3, p) { + const k3 = 1 - t3; + return k3 * k3 * p; + } + function QuadraticBezierP12(t3, p) { + return 2 * (1 - t3) * t3 * p; + } + function QuadraticBezierP22(t3, p) { + return t3 * t3 * p; + } + function QuadraticBezier2(t3, p0, p1, p2) { + return QuadraticBezierP02(t3, p0) + QuadraticBezierP12(t3, p1) + QuadraticBezierP22(t3, p2); + } + function CubicBezierP02(t3, p) { + const k3 = 1 - t3; + return k3 * k3 * k3 * p; + } + function CubicBezierP12(t3, p) { + const k3 = 1 - t3; + return 3 * k3 * k3 * t3 * p; + } + function CubicBezierP22(t3, p) { + return 3 * (1 - t3) * t3 * t3 * p; + } + function CubicBezierP32(t3, p) { + return t3 * t3 * t3 * p; + } + function CubicBezier2(t3, p0, p1, p2, p3) { + return CubicBezierP02(t3, p0) + CubicBezierP12(t3, p1) + CubicBezierP22(t3, p2) + CubicBezierP32(t3, p3); + } + + class CubicBezierCurve2 extends Curve2 { + constructor(v0 = new Vector22, v12 = new Vector22, v2 = new Vector22, v3 = new Vector22) { + super(); + this.isCubicBezierCurve = true; + this.type = "CubicBezierCurve"; + this.v0 = v0; + this.v1 = v12; + this.v2 = v2; + this.v3 = v3; + } + getPoint(t3, optionalTarget = new Vector22) { + const point = optionalTarget; + const v0 = this.v0, v12 = this.v1, v2 = this.v2, v3 = this.v3; + point.set(CubicBezier2(t3, v0.x, v12.x, v2.x, v3.x), CubicBezier2(t3, v0.y, v12.y, v2.y, v3.y)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + data2.v3 = this.v3.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } + } + + class CubicBezierCurve32 extends Curve2 { + constructor(v0 = new Vector32, v12 = new Vector32, v2 = new Vector32, v3 = new Vector32) { + super(); + this.isCubicBezierCurve3 = true; + this.type = "CubicBezierCurve3"; + this.v0 = v0; + this.v1 = v12; + this.v2 = v2; + this.v3 = v3; + } + getPoint(t3, optionalTarget = new Vector32) { + const point = optionalTarget; + const v0 = this.v0, v12 = this.v1, v2 = this.v2, v3 = this.v3; + point.set(CubicBezier2(t3, v0.x, v12.x, v2.x, v3.x), CubicBezier2(t3, v0.y, v12.y, v2.y, v3.y), CubicBezier2(t3, v0.z, v12.z, v2.z, v3.z)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + data2.v3 = this.v3.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } + } + + class LineCurve2 extends Curve2 { + constructor(v12 = new Vector22, v2 = new Vector22) { + super(); + this.isLineCurve = true; + this.type = "LineCurve"; + this.v1 = v12; + this.v2 = v2; + } + getPoint(t3, optionalTarget = new Vector22) { + const point = optionalTarget; + if (t3 === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t3).add(this.v1); + } + return point; + } + getPointAt(u2, optionalTarget) { + return this.getPoint(u2, optionalTarget); + } + getTangent(t3, optionalTarget = new Vector22) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u2, optionalTarget) { + return this.getTangent(u2, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + + class LineCurve32 extends Curve2 { + constructor(v12 = new Vector32, v2 = new Vector32) { + super(); + this.isLineCurve3 = true; + this.type = "LineCurve3"; + this.v1 = v12; + this.v2 = v2; + } + getPoint(t3, optionalTarget = new Vector32) { + const point = optionalTarget; + if (t3 === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t3).add(this.v1); + } + return point; + } + getPointAt(u2, optionalTarget) { + return this.getPoint(u2, optionalTarget); + } + getTangent(t3, optionalTarget = new Vector32) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u2, optionalTarget) { + return this.getTangent(u2, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + + class QuadraticBezierCurve2 extends Curve2 { + constructor(v0 = new Vector22, v12 = new Vector22, v2 = new Vector22) { + super(); + this.isQuadraticBezierCurve = true; + this.type = "QuadraticBezierCurve"; + this.v0 = v0; + this.v1 = v12; + this.v2 = v2; + } + getPoint(t3, optionalTarget = new Vector22) { + const point = optionalTarget; + const v0 = this.v0, v12 = this.v1, v2 = this.v2; + point.set(QuadraticBezier2(t3, v0.x, v12.x, v2.x), QuadraticBezier2(t3, v0.y, v12.y, v2.y)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + + class QuadraticBezierCurve32 extends Curve2 { + constructor(v0 = new Vector32, v12 = new Vector32, v2 = new Vector32) { + super(); + this.isQuadraticBezierCurve3 = true; + this.type = "QuadraticBezierCurve3"; + this.v0 = v0; + this.v1 = v12; + this.v2 = v2; + } + getPoint(t3, optionalTarget = new Vector32) { + const point = optionalTarget; + const v0 = this.v0, v12 = this.v1, v2 = this.v2; + point.set(QuadraticBezier2(t3, v0.x, v12.x, v2.x), QuadraticBezier2(t3, v0.y, v12.y, v2.y), QuadraticBezier2(t3, v0.z, v12.z, v2.z)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } + } + + class SplineCurve2 extends Curve2 { + constructor(points = []) { + super(); + this.isSplineCurve = true; + this.type = "SplineCurve"; + this.points = points; + } + getPoint(t3, optionalTarget = new Vector22) { + const point = optionalTarget; + const points = this.points; + const p = (points.length - 1) * t3; + const intPoint = Math.floor(p); + const weight = p - intPoint; + const p0 = points[intPoint === 0 ? intPoint : intPoint - 1]; + const p1 = points[intPoint]; + const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1]; + const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2]; + point.set(CatmullRom2(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom2(weight, p0.y, p1.y, p2.y, p3.y)); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l2 = source.points.length;i < l2; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.points = []; + for (let i = 0, l2 = this.points.length;i < l2; i++) { + const point = this.points[i]; + data2.points.push(point.toArray()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l2 = json.points.length;i < l2; i++) { + const point = json.points[i]; + this.points.push(new Vector22().fromArray(point)); + } + return this; + } + } + var Curves2 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ArcCurve: ArcCurve2, + CatmullRomCurve3: CatmullRomCurve32, + CubicBezierCurve: CubicBezierCurve2, + CubicBezierCurve3: CubicBezierCurve32, + EllipseCurve: EllipseCurve2, + LineCurve: LineCurve2, + LineCurve3: LineCurve32, + QuadraticBezierCurve: QuadraticBezierCurve2, + QuadraticBezierCurve3: QuadraticBezierCurve32, + SplineCurve: SplineCurve2 + }); + + class CurvePath2 extends Curve2 { + constructor() { + super(); + this.type = "CurvePath"; + this.curves = []; + this.autoClose = false; + } + add(curve) { + this.curves.push(curve); + } + closePath() { + const startPoint = this.curves[0].getPoint(0); + const endPoint = this.curves[this.curves.length - 1].getPoint(1); + if (!startPoint.equals(endPoint)) { + const lineType = startPoint.isVector2 === true ? "LineCurve" : "LineCurve3"; + this.curves.push(new Curves2[lineType](endPoint, startPoint)); + } + return this; + } + getPoint(t3, optionalTarget) { + const d = t3 * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + while (i < curveLengths.length) { + if (curveLengths[i] >= d) { + const diff = curveLengths[i] - d; + const curve = this.curves[i]; + const segmentLength = curve.getLength(); + const u2 = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + return curve.getPointAt(u2, optionalTarget); + } + i++; + } + return null; + } + getLength() { + const lens = this.getCurveLengths(); + return lens[lens.length - 1]; + } + updateArcLengths() { + this.needsUpdate = true; + this.cacheLengths = null; + this.getCurveLengths(); + } + getCurveLengths() { + if (this.cacheLengths && this.cacheLengths.length === this.curves.length) { + return this.cacheLengths; + } + const lengths2 = []; + let sums = 0; + for (let i = 0, l2 = this.curves.length;i < l2; i++) { + sums += this.curves[i].getLength(); + lengths2.push(sums); + } + this.cacheLengths = lengths2; + return lengths2; + } + getSpacedPoints(divisions = 40) { + const points = []; + for (let i = 0;i <= divisions; i++) { + points.push(this.getPoint(i / divisions)); + } + if (this.autoClose) { + points.push(points[0]); + } + return points; + } + getPoints(divisions = 12) { + const points = []; + let last2; + for (let i = 0, curves = this.curves;i < curves.length; i++) { + const curve = curves[i]; + const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions; + const pts = curve.getPoints(resolution); + for (let j2 = 0;j2 < pts.length; j2++) { + const point = pts[j2]; + if (last2 && last2.equals(point)) + continue; + points.push(point); + last2 = point; + } + } + if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) { + points.push(points[0]); + } + return points; + } + copy(source) { + super.copy(source); + this.curves = []; + for (let i = 0, l2 = source.curves.length;i < l2; i++) { + const curve = source.curves[i]; + this.curves.push(curve.clone()); + } + this.autoClose = source.autoClose; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.autoClose = this.autoClose; + data2.curves = []; + for (let i = 0, l2 = this.curves.length;i < l2; i++) { + const curve = this.curves[i]; + data2.curves.push(curve.toJSON()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.autoClose = json.autoClose; + this.curves = []; + for (let i = 0, l2 = json.curves.length;i < l2; i++) { + const curve = json.curves[i]; + this.curves.push(new Curves2[curve.type]().fromJSON(curve)); + } + return this; + } + } + + class Path3 extends CurvePath2 { + constructor(points) { + super(); + this.type = "Path"; + this.currentPoint = new Vector22; + if (points) { + this.setFromPoints(points); + } + } + setFromPoints(points) { + this.moveTo(points[0].x, points[0].y); + for (let i = 1, l2 = points.length;i < l2; i++) { + this.lineTo(points[i].x, points[i].y); + } + return this; + } + moveTo(x2, y) { + this.currentPoint.set(x2, y); + return this; + } + lineTo(x2, y) { + const curve = new LineCurve2(this.currentPoint.clone(), new Vector22(x2, y)); + this.curves.push(curve); + this.currentPoint.set(x2, y); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + const curve = new QuadraticBezierCurve2(this.currentPoint.clone(), new Vector22(aCPx, aCPy), new Vector22(aX, aY)); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + const curve = new CubicBezierCurve2(this.currentPoint.clone(), new Vector22(aCP1x, aCP1y), new Vector22(aCP2x, aCP2y), new Vector22(aX, aY)); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + splineThru(pts) { + const npts = [this.currentPoint.clone()].concat(pts); + const curve = new SplineCurve2(npts); + this.curves.push(curve); + this.currentPoint.copy(pts[pts.length - 1]); + return this; + } + arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + return this; + } + absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const curve = new EllipseCurve2(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + if (this.curves.length > 0) { + const firstPoint = curve.getPoint(0); + if (!firstPoint.equals(this.currentPoint)) { + this.lineTo(firstPoint.x, firstPoint.y); + } + } + this.curves.push(curve); + const lastPoint = curve.getPoint(1); + this.currentPoint.copy(lastPoint); + return this; + } + copy(source) { + super.copy(source); + this.currentPoint.copy(source.currentPoint); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.currentPoint = this.currentPoint.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.currentPoint.fromArray(json.currentPoint); + return this; + } + } + + class LatheGeometry2 extends BufferGeometry2 { + constructor(points = [new Vector22(0, -0.5), new Vector22(0.5, 0), new Vector22(0, 0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) { + super(); + this.type = "LatheGeometry"; + this.parameters = { + points, + segments, + phiStart, + phiLength + }; + segments = Math.floor(segments); + phiLength = clamp3(phiLength, 0, Math.PI * 2); + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; + const inverseSegments = 1 / segments; + const vertex3 = new Vector32; + const uv = new Vector22; + const normal = new Vector32; + const curNormal = new Vector32; + const prevNormal = new Vector32; + let dx = 0; + let dy = 0; + for (let j2 = 0;j2 <= points.length - 1; j2++) { + switch (j2) { + case 0: + dx = points[j2 + 1].x - points[j2].x; + dy = points[j2 + 1].y - points[j2].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + prevNormal.copy(normal); + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + break; + case points.length - 1: + initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z); + break; + default: + dx = points[j2 + 1].x - points[j2].x; + dy = points[j2 + 1].y - points[j2].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + curNormal.copy(normal); + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + prevNormal.copy(curNormal); + } + } + for (let i = 0;i <= segments; i++) { + const phi = phiStart + i * inverseSegments * phiLength; + const sin = Math.sin(phi); + const cos = Math.cos(phi); + for (let j2 = 0;j2 <= points.length - 1; j2++) { + vertex3.x = points[j2].x * sin; + vertex3.y = points[j2].y; + vertex3.z = points[j2].x * cos; + vertices.push(vertex3.x, vertex3.y, vertex3.z); + uv.x = i / segments; + uv.y = j2 / (points.length - 1); + uvs.push(uv.x, uv.y); + const x2 = initNormals[3 * j2 + 0] * sin; + const y = initNormals[3 * j2 + 1]; + const z = initNormals[3 * j2 + 0] * cos; + normals.push(x2, y, z); + } + } + for (let i = 0;i < segments; i++) { + for (let j2 = 0;j2 < points.length - 1; j2++) { + const base = j2 + i * points.length; + const a2 = base; + const b2 = base + points.length; + const c2 = base + points.length + 1; + const d = base + 1; + indices.push(a2, b2, d); + indices.push(c2, d, b2); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new LatheGeometry2(data2.points, data2.segments, data2.phiStart, data2.phiLength); + } + } + + class CapsuleGeometry2 extends LatheGeometry2 { + constructor(radius = 1, length2 = 1, capSegments = 4, radialSegments = 8) { + const path = new Path3; + path.absarc(0, -length2 / 2, radius, Math.PI * 1.5, 0); + path.absarc(0, length2 / 2, radius, 0, Math.PI * 0.5); + super(path.getPoints(capSegments), radialSegments); + this.type = "CapsuleGeometry"; + this.parameters = { + radius, + length: length2, + capSegments, + radialSegments + }; + } + static fromJSON(data2) { + return new CapsuleGeometry2(data2.radius, data2.length, data2.capSegments, data2.radialSegments); + } + } + + class CircleGeometry2 extends BufferGeometry2 { + constructor(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CircleGeometry"; + this.parameters = { + radius, + segments, + thetaStart, + thetaLength + }; + segments = Math.max(3, segments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex3 = new Vector32; + const uv = new Vector22; + vertices.push(0, 0, 0); + normals.push(0, 0, 1); + uvs.push(0.5, 0.5); + for (let s = 0, i = 3;s <= segments; s++, i += 3) { + const segment = thetaStart + s / segments * thetaLength; + vertex3.x = radius * Math.cos(segment); + vertex3.y = radius * Math.sin(segment); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normals.push(0, 0, 1); + uv.x = (vertices[i] / radius + 1) / 2; + uv.y = (vertices[i + 1] / radius + 1) / 2; + uvs.push(uv.x, uv.y); + } + for (let i = 1;i <= segments; i++) { + indices.push(i, i + 1, 0); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new CircleGeometry2(data2.radius, data2.segments, data2.thetaStart, data2.thetaLength); + } + } + + class CylinderGeometry2 extends BufferGeometry2 { + constructor(radiusTop = 1, radiusBottom = 1, height2 = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CylinderGeometry"; + this.parameters = { + radiusTop, + radiusBottom, + height: height2, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + const scope = this; + radialSegments = Math.floor(radialSegments); + heightSegments = Math.floor(heightSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let index2 = 0; + const indexArray = []; + const halfHeight = height2 / 2; + let groupStart = 0; + generateTorso(); + if (openEnded === false) { + if (radiusTop > 0) + generateCap(true); + if (radiusBottom > 0) + generateCap(false); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function generateTorso() { + const normal = new Vector32; + const vertex3 = new Vector32; + let groupCount = 0; + const slope = (radiusBottom - radiusTop) / height2; + for (let y = 0;y <= heightSegments; y++) { + const indexRow = []; + const v = y / heightSegments; + const radius = v * (radiusBottom - radiusTop) + radiusTop; + for (let x2 = 0;x2 <= radialSegments; x2++) { + const u2 = x2 / radialSegments; + const theta = u2 * thetaLength + thetaStart; + const sinTheta = Math.sin(theta); + const cosTheta = Math.cos(theta); + vertex3.x = radius * sinTheta; + vertex3.y = -v * height2 + halfHeight; + vertex3.z = radius * cosTheta; + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normal.set(sinTheta, slope, cosTheta).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u2, 1 - v); + indexRow.push(index2++); + } + indexArray.push(indexRow); + } + for (let x2 = 0;x2 < radialSegments; x2++) { + for (let y = 0;y < heightSegments; y++) { + const a2 = indexArray[y][x2]; + const b2 = indexArray[y + 1][x2]; + const c2 = indexArray[y + 1][x2 + 1]; + const d = indexArray[y][x2 + 1]; + if (radiusTop > 0 || y !== 0) { + indices.push(a2, b2, d); + groupCount += 3; + } + if (radiusBottom > 0 || y !== heightSegments - 1) { + indices.push(b2, c2, d); + groupCount += 3; + } + } + } + scope.addGroup(groupStart, groupCount, 0); + groupStart += groupCount; + } + function generateCap(top) { + const centerIndexStart = index2; + const uv = new Vector22; + const vertex3 = new Vector32; + let groupCount = 0; + const radius = top === true ? radiusTop : radiusBottom; + const sign3 = top === true ? 1 : -1; + for (let x2 = 1;x2 <= radialSegments; x2++) { + vertices.push(0, halfHeight * sign3, 0); + normals.push(0, sign3, 0); + uvs.push(0.5, 0.5); + index2++; + } + const centerIndexEnd = index2; + for (let x2 = 0;x2 <= radialSegments; x2++) { + const u2 = x2 / radialSegments; + const theta = u2 * thetaLength + thetaStart; + const cosTheta = Math.cos(theta); + const sinTheta = Math.sin(theta); + vertex3.x = radius * sinTheta; + vertex3.y = halfHeight * sign3; + vertex3.z = radius * cosTheta; + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normals.push(0, sign3, 0); + uv.x = cosTheta * 0.5 + 0.5; + uv.y = sinTheta * 0.5 * sign3 + 0.5; + uvs.push(uv.x, uv.y); + index2++; + } + for (let x2 = 0;x2 < radialSegments; x2++) { + const c2 = centerIndexStart + x2; + const i = centerIndexEnd + x2; + if (top === true) { + indices.push(i, i + 1, c2); + } else { + indices.push(i + 1, i, c2); + } + groupCount += 3; + } + scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); + groupStart += groupCount; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new CylinderGeometry2(data2.radiusTop, data2.radiusBottom, data2.height, data2.radialSegments, data2.heightSegments, data2.openEnded, data2.thetaStart, data2.thetaLength); + } + } + + class ConeGeometry2 extends CylinderGeometry2 { + constructor(radius = 1, height2 = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(0, radius, height2, radialSegments, heightSegments, openEnded, thetaStart, thetaLength); + this.type = "ConeGeometry"; + this.parameters = { + radius, + height: height2, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + } + static fromJSON(data2) { + return new ConeGeometry2(data2.radius, data2.height, data2.radialSegments, data2.heightSegments, data2.openEnded, data2.thetaStart, data2.thetaLength); + } + } + + class PolyhedronGeometry2 extends BufferGeometry2 { + constructor(vertices = [], indices = [], radius = 1, detail = 0) { + super(); + this.type = "PolyhedronGeometry"; + this.parameters = { + vertices, + indices, + radius, + detail + }; + const vertexBuffer = []; + const uvBuffer = []; + subdivide(detail); + applyRadius(radius); + generateUVs(); + this.setAttribute("position", new Float32BufferAttribute2(vertexBuffer, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(vertexBuffer.slice(), 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvBuffer, 2)); + if (detail === 0) { + this.computeVertexNormals(); + } else { + this.normalizeNormals(); + } + function subdivide(detail2) { + const a2 = new Vector32; + const b2 = new Vector32; + const c2 = new Vector32; + for (let i = 0;i < indices.length; i += 3) { + getVertexByIndex(indices[i + 0], a2); + getVertexByIndex(indices[i + 1], b2); + getVertexByIndex(indices[i + 2], c2); + subdivideFace(a2, b2, c2, detail2); + } + } + function subdivideFace(a2, b2, c2, detail2) { + const cols = detail2 + 1; + const v = []; + for (let i = 0;i <= cols; i++) { + v[i] = []; + const aj = a2.clone().lerp(c2, i / cols); + const bj = b2.clone().lerp(c2, i / cols); + const rows = cols - i; + for (let j2 = 0;j2 <= rows; j2++) { + if (j2 === 0 && i === cols) { + v[i][j2] = aj; + } else { + v[i][j2] = aj.clone().lerp(bj, j2 / rows); + } + } + } + for (let i = 0;i < cols; i++) { + for (let j2 = 0;j2 < 2 * (cols - i) - 1; j2++) { + const k3 = Math.floor(j2 / 2); + if (j2 % 2 === 0) { + pushVertex(v[i][k3 + 1]); + pushVertex(v[i + 1][k3]); + pushVertex(v[i][k3]); + } else { + pushVertex(v[i][k3 + 1]); + pushVertex(v[i + 1][k3 + 1]); + pushVertex(v[i + 1][k3]); + } + } + } + } + function applyRadius(radius2) { + const vertex3 = new Vector32; + for (let i = 0;i < vertexBuffer.length; i += 3) { + vertex3.x = vertexBuffer[i + 0]; + vertex3.y = vertexBuffer[i + 1]; + vertex3.z = vertexBuffer[i + 2]; + vertex3.normalize().multiplyScalar(radius2); + vertexBuffer[i + 0] = vertex3.x; + vertexBuffer[i + 1] = vertex3.y; + vertexBuffer[i + 2] = vertex3.z; + } + } + function generateUVs() { + const vertex3 = new Vector32; + for (let i = 0;i < vertexBuffer.length; i += 3) { + vertex3.x = vertexBuffer[i + 0]; + vertex3.y = vertexBuffer[i + 1]; + vertex3.z = vertexBuffer[i + 2]; + const u2 = azimuth(vertex3) / 2 / Math.PI + 0.5; + const v = inclination(vertex3) / Math.PI + 0.5; + uvBuffer.push(u2, 1 - v); + } + correctUVs(); + correctSeam(); + } + function correctSeam() { + for (let i = 0;i < uvBuffer.length; i += 6) { + const x0 = uvBuffer[i + 0]; + const x1 = uvBuffer[i + 2]; + const x2 = uvBuffer[i + 4]; + const max = Math.max(x0, x1, x2); + const min = Math.min(x0, x1, x2); + if (max > 0.9 && min < 0.1) { + if (x0 < 0.2) + uvBuffer[i + 0] += 1; + if (x1 < 0.2) + uvBuffer[i + 2] += 1; + if (x2 < 0.2) + uvBuffer[i + 4] += 1; + } + } + } + function pushVertex(vertex3) { + vertexBuffer.push(vertex3.x, vertex3.y, vertex3.z); + } + function getVertexByIndex(index2, vertex3) { + const stride = index2 * 3; + vertex3.x = vertices[stride + 0]; + vertex3.y = vertices[stride + 1]; + vertex3.z = vertices[stride + 2]; + } + function correctUVs() { + const a2 = new Vector32; + const b2 = new Vector32; + const c2 = new Vector32; + const centroid = new Vector32; + const uvA = new Vector22; + const uvB = new Vector22; + const uvC = new Vector22; + for (let i = 0, j2 = 0;i < vertexBuffer.length; i += 9, j2 += 6) { + a2.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]); + b2.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]); + c2.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]); + uvA.set(uvBuffer[j2 + 0], uvBuffer[j2 + 1]); + uvB.set(uvBuffer[j2 + 2], uvBuffer[j2 + 3]); + uvC.set(uvBuffer[j2 + 4], uvBuffer[j2 + 5]); + centroid.copy(a2).add(b2).add(c2).divideScalar(3); + const azi = azimuth(centroid); + correctUV(uvA, j2 + 0, a2, azi); + correctUV(uvB, j2 + 2, b2, azi); + correctUV(uvC, j2 + 4, c2, azi); + } + } + function correctUV(uv, stride, vector, azimuth2) { + if (azimuth2 < 0 && uv.x === 1) { + uvBuffer[stride] = uv.x - 1; + } + if (vector.x === 0 && vector.z === 0) { + uvBuffer[stride] = azimuth2 / 2 / Math.PI + 0.5; + } + } + function azimuth(vector) { + return Math.atan2(vector.z, -vector.x); + } + function inclination(vector) { + return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new PolyhedronGeometry2(data2.vertices, data2.indices, data2.radius, data2.details); + } + } + + class DodecahedronGeometry2 extends PolyhedronGeometry2 { + constructor(radius = 1, detail = 0) { + const t3 = (1 + Math.sqrt(5)) / 2; + const r = 1 / t3; + const vertices = [ + -1, + -1, + -1, + -1, + -1, + 1, + -1, + 1, + -1, + -1, + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + 1, + 1, + -1, + 1, + 1, + 1, + 0, + -r, + -t3, + 0, + -r, + t3, + 0, + r, + -t3, + 0, + r, + t3, + -r, + -t3, + 0, + -r, + t3, + 0, + r, + -t3, + 0, + r, + t3, + 0, + -t3, + 0, + -r, + t3, + 0, + -r, + -t3, + 0, + r, + t3, + 0, + r + ]; + const indices = [ + 3, + 11, + 7, + 3, + 7, + 15, + 3, + 15, + 13, + 7, + 19, + 17, + 7, + 17, + 6, + 7, + 6, + 15, + 17, + 4, + 8, + 17, + 8, + 10, + 17, + 10, + 6, + 8, + 0, + 16, + 8, + 16, + 2, + 8, + 2, + 10, + 0, + 12, + 1, + 0, + 1, + 18, + 0, + 18, + 16, + 6, + 10, + 2, + 6, + 2, + 13, + 6, + 13, + 15, + 2, + 16, + 18, + 2, + 18, + 3, + 2, + 3, + 13, + 18, + 1, + 9, + 18, + 9, + 11, + 18, + 11, + 3, + 4, + 14, + 12, + 4, + 12, + 0, + 4, + 0, + 8, + 11, + 9, + 5, + 11, + 5, + 19, + 11, + 19, + 7, + 19, + 5, + 14, + 19, + 14, + 4, + 19, + 4, + 17, + 1, + 12, + 14, + 1, + 14, + 5, + 1, + 5, + 9 + ]; + super(vertices, indices, radius, detail); + this.type = "DodecahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new DodecahedronGeometry2(data2.radius, data2.detail); + } + } + var _v0$12 = /* @__PURE__ */ new Vector32; + var _v1$12 = /* @__PURE__ */ new Vector32; + var _normal2 = /* @__PURE__ */ new Vector32; + var _triangle3 = /* @__PURE__ */ new Triangle2; + + class EdgesGeometry2 extends BufferGeometry2 { + constructor(geometry = null, thresholdAngle = 1) { + super(); + this.type = "EdgesGeometry"; + this.parameters = { + geometry, + thresholdAngle + }; + if (geometry !== null) { + const precisionPoints = 4; + const precision = Math.pow(10, precisionPoints); + const thresholdDot = Math.cos(DEG2RAD2 * thresholdAngle); + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute("position"); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + const indexArr = [0, 0, 0]; + const vertKeys = ["a", "b", "c"]; + const hashes = new Array(3); + const edgeData = {}; + const vertices = []; + for (let i = 0;i < indexCount; i += 3) { + if (indexAttr) { + indexArr[0] = indexAttr.getX(i); + indexArr[1] = indexAttr.getX(i + 1); + indexArr[2] = indexAttr.getX(i + 2); + } else { + indexArr[0] = i; + indexArr[1] = i + 1; + indexArr[2] = i + 2; + } + const { a: a2, b: b2, c: c2 } = _triangle3; + a2.fromBufferAttribute(positionAttr, indexArr[0]); + b2.fromBufferAttribute(positionAttr, indexArr[1]); + c2.fromBufferAttribute(positionAttr, indexArr[2]); + _triangle3.getNormal(_normal2); + hashes[0] = `${Math.round(a2.x * precision)},${Math.round(a2.y * precision)},${Math.round(a2.z * precision)}`; + hashes[1] = `${Math.round(b2.x * precision)},${Math.round(b2.y * precision)},${Math.round(b2.z * precision)}`; + hashes[2] = `${Math.round(c2.x * precision)},${Math.round(c2.y * precision)},${Math.round(c2.z * precision)}`; + if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) { + continue; + } + for (let j2 = 0;j2 < 3; j2++) { + const jNext = (j2 + 1) % 3; + const vecHash0 = hashes[j2]; + const vecHash1 = hashes[jNext]; + const v0 = _triangle3[vertKeys[j2]]; + const v12 = _triangle3[vertKeys[jNext]]; + const hash = `${vecHash0}_${vecHash1}`; + const reverseHash = `${vecHash1}_${vecHash0}`; + if (reverseHash in edgeData && edgeData[reverseHash]) { + if (_normal2.dot(edgeData[reverseHash].normal) <= thresholdDot) { + vertices.push(v0.x, v0.y, v0.z); + vertices.push(v12.x, v12.y, v12.z); + } + edgeData[reverseHash] = null; + } else if (!(hash in edgeData)) { + edgeData[hash] = { + index0: indexArr[j2], + index1: indexArr[jNext], + normal: _normal2.clone() + }; + } + } + } + for (const key2 in edgeData) { + if (edgeData[key2]) { + const { index0, index1 } = edgeData[key2]; + _v0$12.fromBufferAttribute(positionAttr, index0); + _v1$12.fromBufferAttribute(positionAttr, index1); + vertices.push(_v0$12.x, _v0$12.y, _v0$12.z); + vertices.push(_v1$12.x, _v1$12.y, _v1$12.z); + } + } + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + } + + class Shape2 extends Path3 { + constructor(points) { + super(points); + this.uuid = generateUUID2(); + this.type = "Shape"; + this.holes = []; + } + getPointsHoles(divisions) { + const holesPts = []; + for (let i = 0, l2 = this.holes.length;i < l2; i++) { + holesPts[i] = this.holes[i].getPoints(divisions); + } + return holesPts; + } + extractPoints(divisions) { + return { + shape: this.getPoints(divisions), + holes: this.getPointsHoles(divisions) + }; + } + copy(source) { + super.copy(source); + this.holes = []; + for (let i = 0, l2 = source.holes.length;i < l2; i++) { + const hole = source.holes[i]; + this.holes.push(hole.clone()); + } + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.uuid = this.uuid; + data2.holes = []; + for (let i = 0, l2 = this.holes.length;i < l2; i++) { + const hole = this.holes[i]; + data2.holes.push(hole.toJSON()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.uuid = json.uuid; + this.holes = []; + for (let i = 0, l2 = json.holes.length;i < l2; i++) { + const hole = json.holes[i]; + this.holes.push(new Path3().fromJSON(hole)); + } + return this; + } + } + var Earcut2 = { + triangulate: function(data2, holeIndices, dim = 2) { + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data2.length; + let outerNode = linkedList2(data2, 0, outerLen, dim, true); + const triangles = []; + if (!outerNode || outerNode.next === outerNode.prev) + return triangles; + let minX, minY, maxX, maxY, x2, y, invSize; + if (hasHoles) + outerNode = eliminateHoles2(data2, holeIndices, outerNode, dim); + if (data2.length > 80 * dim) { + minX = maxX = data2[0]; + minY = maxY = data2[1]; + for (let i = dim;i < outerLen; i += dim) { + x2 = data2[i]; + y = data2[i + 1]; + if (x2 < minX) + minX = x2; + if (y < minY) + minY = y; + if (x2 > maxX) + maxX = x2; + if (y > maxY) + maxY = y; + } + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + earcutLinked2(outerNode, triangles, dim, minX, minY, invSize, 0); + return triangles; + } + }; + function linkedList2(data2, start, end, dim, clockwise) { + let i, last2; + if (clockwise === signedArea2(data2, start, end, dim) > 0) { + for (i = start;i < end; i += dim) + last2 = insertNode2(i, data2[i], data2[i + 1], last2); + } else { + for (i = end - dim;i >= start; i -= dim) + last2 = insertNode2(i, data2[i], data2[i + 1], last2); + } + if (last2 && equals3(last2, last2.next)) { + removeNode2(last2); + last2 = last2.next; + } + return last2; + } + function filterPoints2(start, end) { + if (!start) + return start; + if (!end) + end = start; + let p = start, again; + do { + again = false; + if (!p.steiner && (equals3(p, p.next) || area2(p.prev, p, p.next) === 0)) { + removeNode2(p); + p = end = p.prev; + if (p === p.next) + break; + again = true; + } else { + p = p.next; + } + } while (again || p !== end); + return end; + } + function earcutLinked2(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) + return; + if (!pass && invSize) + indexCurve2(ear, minX, minY, invSize); + let stop = ear, prev, next; + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + if (invSize ? isEarHashed2(ear, minX, minY, invSize) : isEar2(ear)) { + triangles.push(prev.i / dim | 0); + triangles.push(ear.i / dim | 0); + triangles.push(next.i / dim | 0); + removeNode2(ear); + ear = next.next; + stop = next.next; + continue; + } + ear = next; + if (ear === stop) { + if (!pass) { + earcutLinked2(filterPoints2(ear), triangles, dim, minX, minY, invSize, 1); + } else if (pass === 1) { + ear = cureLocalIntersections2(filterPoints2(ear), triangles, dim); + earcutLinked2(ear, triangles, dim, minX, minY, invSize, 2); + } else if (pass === 2) { + splitEarcut2(ear, triangles, dim, minX, minY, invSize); + } + break; + } + } + } + function isEar2(ear) { + const a2 = ear.prev, b2 = ear, c2 = ear.next; + if (area2(a2, b2, c2) >= 0) + return false; + const ax = a2.x, bx = b2.x, cx = c2.x, ay = a2.y, by = b2.y, cy = c2.y; + const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + let p = c2.next; + while (p !== a2) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle2(ax, ay, bx, by, cx, cy, p.x, p.y) && area2(p.prev, p, p.next) >= 0) + return false; + p = p.next; + } + return true; + } + function isEarHashed2(ear, minX, minY, invSize) { + const a2 = ear.prev, b2 = ear, c2 = ear.next; + if (area2(a2, b2, c2) >= 0) + return false; + const ax = a2.x, bx = b2.x, cx = c2.x, ay = a2.y, by = b2.y, cy = c2.y; + const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + const minZ = zOrder2(x0, y0, minX, minY, invSize), maxZ = zOrder2(x1, y1, minX, minY, invSize); + let { prevZ: p, nextZ: n2 } = ear; + while (p && p.z >= minZ && n2 && n2.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a2 && p !== c2 && pointInTriangle2(ax, ay, bx, by, cx, cy, p.x, p.y) && area2(p.prev, p, p.next) >= 0) + return false; + p = p.prevZ; + if (n2.x >= x0 && n2.x <= x1 && n2.y >= y0 && n2.y <= y1 && n2 !== a2 && n2 !== c2 && pointInTriangle2(ax, ay, bx, by, cx, cy, n2.x, n2.y) && area2(n2.prev, n2, n2.next) >= 0) + return false; + n2 = n2.nextZ; + } + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a2 && p !== c2 && pointInTriangle2(ax, ay, bx, by, cx, cy, p.x, p.y) && area2(p.prev, p, p.next) >= 0) + return false; + p = p.prevZ; + } + while (n2 && n2.z <= maxZ) { + if (n2.x >= x0 && n2.x <= x1 && n2.y >= y0 && n2.y <= y1 && n2 !== a2 && n2 !== c2 && pointInTriangle2(ax, ay, bx, by, cx, cy, n2.x, n2.y) && area2(n2.prev, n2, n2.next) >= 0) + return false; + n2 = n2.nextZ; + } + return true; + } + function cureLocalIntersections2(start, triangles, dim) { + let p = start; + do { + const a2 = p.prev, b2 = p.next.next; + if (!equals3(a2, b2) && intersects2(a2, p, p.next, b2) && locallyInside2(a2, b2) && locallyInside2(b2, a2)) { + triangles.push(a2.i / dim | 0); + triangles.push(p.i / dim | 0); + triangles.push(b2.i / dim | 0); + removeNode2(p); + removeNode2(p.next); + p = start = b2; + } + p = p.next; + } while (p !== start); + return filterPoints2(p); + } + function splitEarcut2(start, triangles, dim, minX, minY, invSize) { + let a2 = start; + do { + let b2 = a2.next.next; + while (b2 !== a2.prev) { + if (a2.i !== b2.i && isValidDiagonal2(a2, b2)) { + let c2 = splitPolygon2(a2, b2); + a2 = filterPoints2(a2, a2.next); + c2 = filterPoints2(c2, c2.next); + earcutLinked2(a2, triangles, dim, minX, minY, invSize, 0); + earcutLinked2(c2, triangles, dim, minX, minY, invSize, 0); + return; + } + b2 = b2.next; + } + a2 = a2.next; + } while (a2 !== start); + } + function eliminateHoles2(data2, holeIndices, outerNode, dim) { + const queue = []; + let i, len, start, end, list; + for (i = 0, len = holeIndices.length;i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data2.length; + list = linkedList2(data2, start, end, dim, false); + if (list === list.next) + list.steiner = true; + queue.push(getLeftmost2(list)); + } + queue.sort(compareX2); + for (i = 0;i < queue.length; i++) { + outerNode = eliminateHole2(queue[i], outerNode); + } + return outerNode; + } + function compareX2(a2, b2) { + return a2.x - b2.x; + } + function eliminateHole2(hole, outerNode) { + const bridge = findHoleBridge2(hole, outerNode); + if (!bridge) { + return outerNode; + } + const bridgeReverse = splitPolygon2(bridge, hole); + filterPoints2(bridgeReverse, bridgeReverse.next); + return filterPoints2(bridge, bridge.next); + } + function findHoleBridge2(hole, outerNode) { + let p = outerNode, qx = -Infinity, m; + const { x: hx, y: hy } = hole; + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x2 = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x2 <= hx && x2 > qx) { + qx = x2; + m = p.x < p.next.x ? p : p.next; + if (x2 === hx) + return m; + } + } + p = p.next; + } while (p !== outerNode); + if (!m) + return null; + const stop = m, mx = m.x, my = m.y; + let tanMin = Infinity, tan; + p = m; + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle2(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + tan = Math.abs(hy - p.y) / (hx - p.x); + if (locallyInside2(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector2(m, p)))) { + m = p; + tanMin = tan; + } + } + p = p.next; + } while (p !== stop); + return m; + } + function sectorContainsSector2(m, p) { + return area2(m.prev, m, p.prev) < 0 && area2(p.next, m, m.next) < 0; + } + function indexCurve2(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) + p.z = zOrder2(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + p.prevZ.nextZ = null; + p.prevZ = null; + sortLinked2(p); + } + function sortLinked2(list) { + let i, p, q2, e, tail, numMerges, pSize, qSize, inSize = 1; + do { + p = list; + list = null; + tail = null; + numMerges = 0; + while (p) { + numMerges++; + q2 = p; + pSize = 0; + for (i = 0;i < inSize; i++) { + pSize++; + q2 = q2.nextZ; + if (!q2) + break; + } + qSize = inSize; + while (pSize > 0 || qSize > 0 && q2) { + if (pSize !== 0 && (qSize === 0 || !q2 || p.z <= q2.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q2; + q2 = q2.nextZ; + qSize--; + } + if (tail) + tail.nextZ = e; + else + list = e; + e.prevZ = tail; + tail = e; + } + p = q2; + } + tail.nextZ = null; + inSize *= 2; + } while (numMerges > 1); + return list; + } + function zOrder2(x2, y, minX, minY, invSize) { + x2 = (x2 - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + x2 = (x2 | x2 << 8) & 16711935; + x2 = (x2 | x2 << 4) & 252645135; + x2 = (x2 | x2 << 2) & 858993459; + x2 = (x2 | x2 << 1) & 1431655765; + y = (y | y << 8) & 16711935; + y = (y | y << 4) & 252645135; + y = (y | y << 2) & 858993459; + y = (y | y << 1) & 1431655765; + return x2 | y << 1; + } + function getLeftmost2(start) { + let p = start, leftmost = start; + do { + if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) + leftmost = p; + p = p.next; + } while (p !== start); + return leftmost; + } + function pointInTriangle2(ax, ay, bx, by, cx, cy, px3, py3) { + return (cx - px3) * (ay - py3) >= (ax - px3) * (cy - py3) && (ax - px3) * (by - py3) >= (bx - px3) * (ay - py3) && (bx - px3) * (cy - py3) >= (cx - px3) * (by - py3); + } + function isValidDiagonal2(a2, b2) { + return a2.next.i !== b2.i && a2.prev.i !== b2.i && !intersectsPolygon2(a2, b2) && (locallyInside2(a2, b2) && locallyInside2(b2, a2) && middleInside2(a2, b2) && (area2(a2.prev, a2, b2.prev) || area2(a2, b2.prev, b2)) || equals3(a2, b2) && area2(a2.prev, a2, a2.next) > 0 && area2(b2.prev, b2, b2.next) > 0); + } + function area2(p, q2, r) { + return (q2.y - p.y) * (r.x - q2.x) - (q2.x - p.x) * (r.y - q2.y); + } + function equals3(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; + } + function intersects2(p1, q1, p2, q2) { + const o1 = sign2(area2(p1, q1, p2)); + const o2 = sign2(area2(p1, q1, q2)); + const o3 = sign2(area2(p2, q2, p1)); + const o4 = sign2(area2(p2, q2, q1)); + if (o1 !== o2 && o3 !== o4) + return true; + if (o1 === 0 && onSegment2(p1, p2, q1)) + return true; + if (o2 === 0 && onSegment2(p1, q2, q1)) + return true; + if (o3 === 0 && onSegment2(p2, p1, q2)) + return true; + if (o4 === 0 && onSegment2(p2, q1, q2)) + return true; + return false; + } + function onSegment2(p, q2, r) { + return q2.x <= Math.max(p.x, r.x) && q2.x >= Math.min(p.x, r.x) && q2.y <= Math.max(p.y, r.y) && q2.y >= Math.min(p.y, r.y); + } + function sign2(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; + } + function intersectsPolygon2(a2, b2) { + let p = a2; + do { + if (p.i !== a2.i && p.next.i !== a2.i && p.i !== b2.i && p.next.i !== b2.i && intersects2(p, p.next, a2, b2)) + return true; + p = p.next; + } while (p !== a2); + return false; + } + function locallyInside2(a2, b2) { + return area2(a2.prev, a2, a2.next) < 0 ? area2(a2, b2, a2.next) >= 0 && area2(a2, a2.prev, b2) >= 0 : area2(a2, b2, a2.prev) < 0 || area2(a2, a2.next, b2) < 0; + } + function middleInside2(a2, b2) { + let p = a2, inside = false; + const px3 = (a2.x + b2.x) / 2, py3 = (a2.y + b2.y) / 2; + do { + if (p.y > py3 !== p.next.y > py3 && p.next.y !== p.y && px3 < (p.next.x - p.x) * (py3 - p.y) / (p.next.y - p.y) + p.x) + inside = !inside; + p = p.next; + } while (p !== a2); + return inside; + } + function splitPolygon2(a2, b2) { + const a22 = new Node3(a2.i, a2.x, a2.y), b22 = new Node3(b2.i, b2.x, b2.y), an = a2.next, bp = b2.prev; + a2.next = b2; + b2.prev = a2; + a22.next = an; + an.prev = a22; + b22.next = a22; + a22.prev = b22; + bp.next = b22; + b22.prev = bp; + return b22; + } + function insertNode2(i, x2, y, last2) { + const p = new Node3(i, x2, y); + if (!last2) { + p.prev = p; + p.next = p; + } else { + p.next = last2.next; + p.prev = last2; + last2.next.prev = p; + last2.next = p; + } + return p; + } + function removeNode2(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + if (p.prevZ) + p.prevZ.nextZ = p.nextZ; + if (p.nextZ) + p.nextZ.prevZ = p.prevZ; + } + function Node3(i, x2, y) { + this.i = i; + this.x = x2; + this.y = y; + this.prev = null; + this.next = null; + this.z = 0; + this.prevZ = null; + this.nextZ = null; + this.steiner = false; + } + function signedArea2(data2, start, end, dim) { + let sum2 = 0; + for (let i = start, j2 = end - dim;i < end; i += dim) { + sum2 += (data2[j2] - data2[i]) * (data2[i + 1] + data2[j2 + 1]); + j2 = i; + } + return sum2; + } + + class ShapeUtils2 { + static area(contour) { + const n2 = contour.length; + let a2 = 0; + for (let p = n2 - 1, q2 = 0;q2 < n2; p = q2++) { + a2 += contour[p].x * contour[q2].y - contour[q2].x * contour[p].y; + } + return a2 * 0.5; + } + static isClockWise(pts) { + return ShapeUtils2.area(pts) < 0; + } + static triangulateShape(contour, holes) { + const vertices = []; + const holeIndices = []; + const faces = []; + removeDupEndPts2(contour); + addContour2(vertices, contour); + let holeIndex = contour.length; + holes.forEach(removeDupEndPts2); + for (let i = 0;i < holes.length; i++) { + holeIndices.push(holeIndex); + holeIndex += holes[i].length; + addContour2(vertices, holes[i]); + } + const triangles = Earcut2.triangulate(vertices, holeIndices); + for (let i = 0;i < triangles.length; i += 3) { + faces.push(triangles.slice(i, i + 3)); + } + return faces; + } + } + function removeDupEndPts2(points) { + const l2 = points.length; + if (l2 > 2 && points[l2 - 1].equals(points[0])) { + points.pop(); + } + } + function addContour2(vertices, contour) { + for (let i = 0;i < contour.length; i++) { + vertices.push(contour[i].x); + vertices.push(contour[i].y); + } + } + + class ExtrudeGeometry2 extends BufferGeometry2 { + constructor(shapes = new Shape2([new Vector22(0.5, 0.5), new Vector22(-0.5, 0.5), new Vector22(-0.5, -0.5), new Vector22(0.5, -0.5)]), options = {}) { + super(); + this.type = "ExtrudeGeometry"; + this.parameters = { + shapes, + options + }; + shapes = Array.isArray(shapes) ? shapes : [shapes]; + const scope = this; + const verticesArray = []; + const uvArray = []; + for (let i = 0, l2 = shapes.length;i < l2; i++) { + const shape = shapes[i]; + addShape(shape); + } + this.setAttribute("position", new Float32BufferAttribute2(verticesArray, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvArray, 2)); + this.computeVertexNormals(); + function addShape(shape) { + const placeholder = []; + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + const extrudePath = options.extrudePath; + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator2; + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + if (extrudePath) { + extrudePts = extrudePath.getSpacedPoints(steps); + extrudeByPath = true; + bevelEnabled = false; + splineTube = extrudePath.computeFrenetFrames(steps, false); + binormal = new Vector32; + normal = new Vector32; + position2 = new Vector32; + } + if (!bevelEnabled) { + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + } + const shapePoints = shape.extractPoints(curveSegments); + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + const reverse = !ShapeUtils2.isClockWise(vertices); + if (reverse) { + vertices = vertices.reverse(); + for (let h = 0, hl2 = holes.length;h < hl2; h++) { + const ahole = holes[h]; + if (ShapeUtils2.isClockWise(ahole)) { + holes[h] = ahole.reverse(); + } + } + } + const faces = ShapeUtils2.triangulateShape(vertices, holes); + const contour = vertices; + for (let h = 0, hl2 = holes.length;h < hl2; h++) { + const ahole = holes[h]; + vertices = vertices.concat(ahole); + } + function scalePt2(pt, vec, size2) { + if (!vec) + console.error("THREE.ExtrudeGeometry: vec does not exist"); + return pt.clone().addScaledVector(vec, size2); + } + const vlen = vertices.length, flen = faces.length; + function getBevelVec(inPt, inPrev, inNext) { + let v_trans_x, v_trans_y, shrink_by; + const v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; + const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; + const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x; + if (Math.abs(collinear0) > Number.EPSILON) { + const v_prev_len = Math.sqrt(v_prev_lensq); + const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); + const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len; + const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len; + const ptNextShift_x = inNext.x - v_next_y / v_next_len; + const ptNextShift_y = inNext.y + v_next_x / v_next_len; + const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); + v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x; + v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; + const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y; + if (v_trans_lensq <= 2) { + return new Vector22(v_trans_x, v_trans_y); + } else { + shrink_by = Math.sqrt(v_trans_lensq / 2); + } + } else { + let direction_eq = false; + if (v_prev_x > Number.EPSILON) { + if (v_next_x > Number.EPSILON) { + direction_eq = true; + } + } else { + if (v_prev_x < -Number.EPSILON) { + if (v_next_x < -Number.EPSILON) { + direction_eq = true; + } + } else { + if (Math.sign(v_prev_y) === Math.sign(v_next_y)) { + direction_eq = true; + } + } + } + if (direction_eq) { + v_trans_x = -v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt(v_prev_lensq); + } else { + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt(v_prev_lensq / 2); + } + } + return new Vector22(v_trans_x / shrink_by, v_trans_y / shrink_by); + } + const contourMovements = []; + for (let i = 0, il = contour.length, j2 = il - 1, k3 = i + 1;i < il; i++, j2++, k3++) { + if (j2 === il) + j2 = 0; + if (k3 === il) + k3 = 0; + contourMovements[i] = getBevelVec(contour[i], contour[j2], contour[k3]); + } + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + for (let h = 0, hl2 = holes.length;h < hl2; h++) { + const ahole = holes[h]; + oneHoleMovements = []; + for (let i = 0, il = ahole.length, j2 = il - 1, k3 = i + 1;i < il; i++, j2++, k3++) { + if (j2 === il) + j2 = 0; + if (k3 === il) + k3 = 0; + oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j2], ahole[k3]); + } + holesMovements.push(oneHoleMovements); + verticesMovements = verticesMovements.concat(oneHoleMovements); + } + for (let b2 = 0;b2 < bevelSegments; b2++) { + const t3 = b2 / bevelSegments; + const z = bevelThickness * Math.cos(t3 * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t3 * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length;i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, -z); + } + for (let h = 0, hl2 = holes.length;h < hl2; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length;i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + v(vert.x, vert.y, -z); + } + } + } + const bs = bevelSize + bevelOffset; + for (let i = 0;i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, 0); + } else { + normal.copy(splineTube.normals[0]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y); + position2.copy(extrudePts[0]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + for (let s = 1;s <= steps; s++) { + for (let i = 0;i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, depth / steps * s); + } else { + normal.copy(splineTube.normals[s]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y); + position2.copy(extrudePts[s]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + } + for (let b2 = bevelSegments - 1;b2 >= 0; b2--) { + const t3 = b2 / bevelSegments; + const z = bevelThickness * Math.cos(t3 * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t3 * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length;i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, depth + z); + } + for (let h = 0, hl2 = holes.length;h < hl2; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length;i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + if (!extrudeByPath) { + v(vert.x, vert.y, depth + z); + } else { + v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z); + } + } + } + } + buildLidFaces(); + buildSideFaces(); + function buildLidFaces() { + const start = verticesArray.length / 3; + if (bevelEnabled) { + let layer = 0; + let offset = vlen * layer; + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[2] + offset, face[1] + offset, face[0] + offset); + } + layer = steps + bevelSegments * 2; + offset = vlen * layer; + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[0] + offset, face[1] + offset, face[2] + offset); + } + } else { + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[2], face[1], face[0]); + } + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps); + } + } + scope.addGroup(start, verticesArray.length / 3 - start, 0); + } + function buildSideFaces() { + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls(contour, layeroffset); + layeroffset += contour.length; + for (let h = 0, hl2 = holes.length;h < hl2; h++) { + const ahole = holes[h]; + sidewalls(ahole, layeroffset); + layeroffset += ahole.length; + } + scope.addGroup(start, verticesArray.length / 3 - start, 1); + } + function sidewalls(contour2, layeroffset) { + let i = contour2.length; + while (--i >= 0) { + const j2 = i; + let k3 = i - 1; + if (k3 < 0) + k3 = contour2.length - 1; + for (let s = 0, sl = steps + bevelSegments * 2;s < sl; s++) { + const slen1 = vlen * s; + const slen2 = vlen * (s + 1); + const a2 = layeroffset + j2 + slen1, b2 = layeroffset + k3 + slen1, c2 = layeroffset + k3 + slen2, d = layeroffset + j2 + slen2; + f4(a2, b2, c2, d); + } + } + } + function v(x2, y, z) { + placeholder.push(x2); + placeholder.push(y); + placeholder.push(z); + } + function f3(a2, b2, c2) { + addVertex(a2); + addVertex(b2); + addVertex(c2); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[2]); + } + function f4(a2, b2, c2, d) { + addVertex(a2); + addVertex(b2); + addVertex(d); + addVertex(b2); + addVertex(c2); + addVertex(d); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[3]); + addUV(uvs[1]); + addUV(uvs[2]); + addUV(uvs[3]); + } + function addVertex(index2) { + verticesArray.push(placeholder[index2 * 3 + 0]); + verticesArray.push(placeholder[index2 * 3 + 1]); + verticesArray.push(placeholder[index2 * 3 + 2]); + } + function addUV(vector2) { + uvArray.push(vector2.x); + uvArray.push(vector2.y); + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + const shapes = this.parameters.shapes; + const options = this.parameters.options; + return toJSON$12(shapes, options, data2); + } + static fromJSON(data2, shapes) { + const geometryShapes = []; + for (let j2 = 0, jl = data2.shapes.length;j2 < jl; j2++) { + const shape = shapes[data2.shapes[j2]]; + geometryShapes.push(shape); + } + const extrudePath = data2.options.extrudePath; + if (extrudePath !== undefined) { + data2.options.extrudePath = new Curves2[extrudePath.type]().fromJSON(extrudePath); + } + return new ExtrudeGeometry2(geometryShapes, data2.options); + } + } + var WorldUVGenerator2 = { + generateTopUV: function(geometry, vertices, indexA, indexB, indexC) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + return [ + new Vector22(a_x, a_y), + new Vector22(b_x, b_y), + new Vector22(c_x, c_y) + ]; + }, + generateSideWallUV: function(geometry, vertices, indexA, indexB, indexC, indexD) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const a_z = vertices[indexA * 3 + 2]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const b_z = vertices[indexB * 3 + 2]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + const c_z = vertices[indexC * 3 + 2]; + const d_x = vertices[indexD * 3]; + const d_y = vertices[indexD * 3 + 1]; + const d_z = vertices[indexD * 3 + 2]; + if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) { + return [ + new Vector22(a_x, 1 - a_z), + new Vector22(b_x, 1 - b_z), + new Vector22(c_x, 1 - c_z), + new Vector22(d_x, 1 - d_z) + ]; + } else { + return [ + new Vector22(a_y, 1 - a_z), + new Vector22(b_y, 1 - b_z), + new Vector22(c_y, 1 - c_z), + new Vector22(d_y, 1 - d_z) + ]; + } + } + }; + function toJSON$12(shapes, options, data2) { + data2.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l2 = shapes.length;i < l2; i++) { + const shape = shapes[i]; + data2.shapes.push(shape.uuid); + } + } else { + data2.shapes.push(shapes.uuid); + } + data2.options = Object.assign({}, options); + if (options.extrudePath !== undefined) + data2.options.extrudePath = options.extrudePath.toJSON(); + return data2; + } + + class IcosahedronGeometry2 extends PolyhedronGeometry2 { + constructor(radius = 1, detail = 0) { + const t3 = (1 + Math.sqrt(5)) / 2; + const vertices = [ + -1, + t3, + 0, + 1, + t3, + 0, + -1, + -t3, + 0, + 1, + -t3, + 0, + 0, + -1, + t3, + 0, + 1, + t3, + 0, + -1, + -t3, + 0, + 1, + -t3, + t3, + 0, + -1, + t3, + 0, + 1, + -t3, + 0, + -1, + -t3, + 0, + 1 + ]; + const indices = [ + 0, + 11, + 5, + 0, + 5, + 1, + 0, + 1, + 7, + 0, + 7, + 10, + 0, + 10, + 11, + 1, + 5, + 9, + 5, + 11, + 4, + 11, + 10, + 2, + 10, + 7, + 6, + 7, + 1, + 8, + 3, + 9, + 4, + 3, + 4, + 2, + 3, + 2, + 6, + 3, + 6, + 8, + 3, + 8, + 9, + 4, + 9, + 5, + 2, + 4, + 11, + 6, + 2, + 10, + 8, + 6, + 7, + 9, + 8, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "IcosahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new IcosahedronGeometry2(data2.radius, data2.detail); + } + } + + class OctahedronGeometry2 extends PolyhedronGeometry2 { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1 + ]; + const indices = [ + 0, + 2, + 4, + 0, + 4, + 3, + 0, + 3, + 5, + 0, + 5, + 2, + 1, + 2, + 5, + 1, + 5, + 3, + 1, + 3, + 4, + 1, + 4, + 2 + ]; + super(vertices, indices, radius, detail); + this.type = "OctahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new OctahedronGeometry2(data2.radius, data2.detail); + } + } + + class PlaneGeometry3 extends BufferGeometry2 { + constructor(width2 = 1, height2 = 1, widthSegments = 1, heightSegments = 1) { + super(); + this.type = "PlaneGeometry"; + this.parameters = { + width: width2, + height: height2, + widthSegments, + heightSegments + }; + const width_half = width2 / 2; + const height_half = height2 / 2; + const gridX = Math.floor(widthSegments); + const gridY = Math.floor(heightSegments); + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + const segment_width = width2 / gridX; + const segment_height = height2 / gridY; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0;iy < gridY1; iy++) { + const y = iy * segment_height - height_half; + for (let ix = 0;ix < gridX1; ix++) { + const x2 = ix * segment_width - width_half; + vertices.push(x2, -y, 0); + normals.push(0, 0, 1); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + } + } + for (let iy = 0;iy < gridY; iy++) { + for (let ix = 0;ix < gridX; ix++) { + const a2 = ix + gridX1 * iy; + const b2 = ix + gridX1 * (iy + 1); + const c2 = ix + 1 + gridX1 * (iy + 1); + const d = ix + 1 + gridX1 * iy; + indices.push(a2, b2, d); + indices.push(b2, c2, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new PlaneGeometry3(data2.width, data2.height, data2.widthSegments, data2.heightSegments); + } + } + + class RingGeometry2 extends BufferGeometry2 { + constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "RingGeometry"; + this.parameters = { + innerRadius, + outerRadius, + thetaSegments, + phiSegments, + thetaStart, + thetaLength + }; + thetaSegments = Math.max(3, thetaSegments); + phiSegments = Math.max(1, phiSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let radius = innerRadius; + const radiusStep = (outerRadius - innerRadius) / phiSegments; + const vertex3 = new Vector32; + const uv = new Vector22; + for (let j2 = 0;j2 <= phiSegments; j2++) { + for (let i = 0;i <= thetaSegments; i++) { + const segment = thetaStart + i / thetaSegments * thetaLength; + vertex3.x = radius * Math.cos(segment); + vertex3.y = radius * Math.sin(segment); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normals.push(0, 0, 1); + uv.x = (vertex3.x / outerRadius + 1) / 2; + uv.y = (vertex3.y / outerRadius + 1) / 2; + uvs.push(uv.x, uv.y); + } + radius += radiusStep; + } + for (let j2 = 0;j2 < phiSegments; j2++) { + const thetaSegmentLevel = j2 * (thetaSegments + 1); + for (let i = 0;i < thetaSegments; i++) { + const segment = i + thetaSegmentLevel; + const a2 = segment; + const b2 = segment + thetaSegments + 1; + const c2 = segment + thetaSegments + 2; + const d = segment + 1; + indices.push(a2, b2, d); + indices.push(b2, c2, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new RingGeometry2(data2.innerRadius, data2.outerRadius, data2.thetaSegments, data2.phiSegments, data2.thetaStart, data2.thetaLength); + } + } + + class ShapeGeometry2 extends BufferGeometry2 { + constructor(shapes = new Shape2([new Vector22(0, 0.5), new Vector22(-0.5, -0.5), new Vector22(0.5, -0.5)]), curveSegments = 12) { + super(); + this.type = "ShapeGeometry"; + this.parameters = { + shapes, + curveSegments + }; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let groupStart = 0; + let groupCount = 0; + if (Array.isArray(shapes) === false) { + addShape(shapes); + } else { + for (let i = 0;i < shapes.length; i++) { + addShape(shapes[i]); + this.addGroup(groupStart, groupCount, i); + groupStart += groupCount; + groupCount = 0; + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function addShape(shape) { + const indexOffset = vertices.length / 3; + const points = shape.extractPoints(curveSegments); + let shapeVertices = points.shape; + const shapeHoles = points.holes; + if (ShapeUtils2.isClockWise(shapeVertices) === false) { + shapeVertices = shapeVertices.reverse(); + } + for (let i = 0, l2 = shapeHoles.length;i < l2; i++) { + const shapeHole = shapeHoles[i]; + if (ShapeUtils2.isClockWise(shapeHole) === true) { + shapeHoles[i] = shapeHole.reverse(); + } + } + const faces = ShapeUtils2.triangulateShape(shapeVertices, shapeHoles); + for (let i = 0, l2 = shapeHoles.length;i < l2; i++) { + const shapeHole = shapeHoles[i]; + shapeVertices = shapeVertices.concat(shapeHole); + } + for (let i = 0, l2 = shapeVertices.length;i < l2; i++) { + const vertex3 = shapeVertices[i]; + vertices.push(vertex3.x, vertex3.y, 0); + normals.push(0, 0, 1); + uvs.push(vertex3.x, vertex3.y); + } + for (let i = 0, l2 = faces.length;i < l2; i++) { + const face = faces[i]; + const a2 = face[0] + indexOffset; + const b2 = face[1] + indexOffset; + const c2 = face[2] + indexOffset; + indices.push(a2, b2, c2); + groupCount += 3; + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + const shapes = this.parameters.shapes; + return toJSON2(shapes, data2); + } + static fromJSON(data2, shapes) { + const geometryShapes = []; + for (let j2 = 0, jl = data2.shapes.length;j2 < jl; j2++) { + const shape = shapes[data2.shapes[j2]]; + geometryShapes.push(shape); + } + return new ShapeGeometry2(geometryShapes, data2.curveSegments); + } + } + function toJSON2(shapes, data2) { + data2.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l2 = shapes.length;i < l2; i++) { + const shape = shapes[i]; + data2.shapes.push(shape.uuid); + } + } else { + data2.shapes.push(shapes.uuid); + } + return data2; + } + + class SphereGeometry3 extends BufferGeometry2 { + constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) { + super(); + this.type = "SphereGeometry"; + this.parameters = { + radius, + widthSegments, + heightSegments, + phiStart, + phiLength, + thetaStart, + thetaLength + }; + widthSegments = Math.max(3, Math.floor(widthSegments)); + heightSegments = Math.max(2, Math.floor(heightSegments)); + const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI); + let index2 = 0; + const grid = []; + const vertex3 = new Vector32; + const normal = new Vector32; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0;iy <= heightSegments; iy++) { + const verticesRow = []; + const v = iy / heightSegments; + let uOffset = 0; + if (iy === 0 && thetaStart === 0) { + uOffset = 0.5 / widthSegments; + } else if (iy === heightSegments && thetaEnd === Math.PI) { + uOffset = -0.5 / widthSegments; + } + for (let ix = 0;ix <= widthSegments; ix++) { + const u2 = ix / widthSegments; + vertex3.x = -radius * Math.cos(phiStart + u2 * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertex3.y = radius * Math.cos(thetaStart + v * thetaLength); + vertex3.z = radius * Math.sin(phiStart + u2 * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normal.copy(vertex3).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u2 + uOffset, 1 - v); + verticesRow.push(index2++); + } + grid.push(verticesRow); + } + for (let iy = 0;iy < heightSegments; iy++) { + for (let ix = 0;ix < widthSegments; ix++) { + const a2 = grid[iy][ix + 1]; + const b2 = grid[iy][ix]; + const c2 = grid[iy + 1][ix]; + const d = grid[iy + 1][ix + 1]; + if (iy !== 0 || thetaStart > 0) + indices.push(a2, b2, d); + if (iy !== heightSegments - 1 || thetaEnd < Math.PI) + indices.push(b2, c2, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new SphereGeometry3(data2.radius, data2.widthSegments, data2.heightSegments, data2.phiStart, data2.phiLength, data2.thetaStart, data2.thetaLength); + } + } + + class TetrahedronGeometry2 extends PolyhedronGeometry2 { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + -1, + 1, + -1, + -1 + ]; + const indices = [ + 2, + 1, + 0, + 0, + 3, + 2, + 1, + 3, + 0, + 2, + 3, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "TetrahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new TetrahedronGeometry2(data2.radius, data2.detail); + } + } + + class TorusGeometry2 extends BufferGeometry2 { + constructor(radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2) { + super(); + this.type = "TorusGeometry"; + this.parameters = { + radius, + tube, + radialSegments, + tubularSegments, + arc + }; + radialSegments = Math.floor(radialSegments); + tubularSegments = Math.floor(tubularSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const center = new Vector32; + const vertex3 = new Vector32; + const normal = new Vector32; + for (let j2 = 0;j2 <= radialSegments; j2++) { + for (let i = 0;i <= tubularSegments; i++) { + const u2 = i / tubularSegments * arc; + const v = j2 / radialSegments * Math.PI * 2; + vertex3.x = (radius + tube * Math.cos(v)) * Math.cos(u2); + vertex3.y = (radius + tube * Math.cos(v)) * Math.sin(u2); + vertex3.z = tube * Math.sin(v); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + center.x = radius * Math.cos(u2); + center.y = radius * Math.sin(u2); + normal.subVectors(vertex3, center).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j2 / radialSegments); + } + } + for (let j2 = 1;j2 <= radialSegments; j2++) { + for (let i = 1;i <= tubularSegments; i++) { + const a2 = (tubularSegments + 1) * j2 + i - 1; + const b2 = (tubularSegments + 1) * (j2 - 1) + i - 1; + const c2 = (tubularSegments + 1) * (j2 - 1) + i; + const d = (tubularSegments + 1) * j2 + i; + indices.push(a2, b2, d); + indices.push(b2, c2, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new TorusGeometry2(data2.radius, data2.tube, data2.radialSegments, data2.tubularSegments, data2.arc); + } + } + + class TorusKnotGeometry3 extends BufferGeometry2 { + constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q2 = 3) { + super(); + this.type = "TorusKnotGeometry"; + this.parameters = { + radius, + tube, + tubularSegments, + radialSegments, + p, + q: q2 + }; + tubularSegments = Math.floor(tubularSegments); + radialSegments = Math.floor(radialSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex3 = new Vector32; + const normal = new Vector32; + const P1 = new Vector32; + const P2 = new Vector32; + const B2 = new Vector32; + const T2 = new Vector32; + const N = new Vector32; + for (let i = 0;i <= tubularSegments; ++i) { + const u2 = i / tubularSegments * p * Math.PI * 2; + calculatePositionOnCurve(u2, p, q2, radius, P1); + calculatePositionOnCurve(u2 + 0.01, p, q2, radius, P2); + T2.subVectors(P2, P1); + N.addVectors(P2, P1); + B2.crossVectors(T2, N); + N.crossVectors(B2, T2); + B2.normalize(); + N.normalize(); + for (let j2 = 0;j2 <= radialSegments; ++j2) { + const v = j2 / radialSegments * Math.PI * 2; + const cx = -tube * Math.cos(v); + const cy = tube * Math.sin(v); + vertex3.x = P1.x + (cx * N.x + cy * B2.x); + vertex3.y = P1.y + (cx * N.y + cy * B2.y); + vertex3.z = P1.z + (cx * N.z + cy * B2.z); + vertices.push(vertex3.x, vertex3.y, vertex3.z); + normal.subVectors(vertex3, P1).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j2 / radialSegments); + } + } + for (let j2 = 1;j2 <= tubularSegments; j2++) { + for (let i = 1;i <= radialSegments; i++) { + const a2 = (radialSegments + 1) * (j2 - 1) + (i - 1); + const b2 = (radialSegments + 1) * j2 + (i - 1); + const c2 = (radialSegments + 1) * j2 + i; + const d = (radialSegments + 1) * (j2 - 1) + i; + indices.push(a2, b2, d); + indices.push(b2, c2, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function calculatePositionOnCurve(u2, p2, q3, radius2, position2) { + const cu = Math.cos(u2); + const su = Math.sin(u2); + const quOverP = q3 / p2 * u2; + const cs = Math.cos(quOverP); + position2.x = radius2 * (2 + cs) * 0.5 * cu; + position2.y = radius2 * (2 + cs) * su * 0.5; + position2.z = radius2 * Math.sin(quOverP) * 0.5; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new TorusKnotGeometry3(data2.radius, data2.tube, data2.tubularSegments, data2.radialSegments, data2.p, data2.q); + } + } + + class TubeGeometry3 extends BufferGeometry2 { + constructor(path = new QuadraticBezierCurve32(new Vector32(-1, -1, 0), new Vector32(-1, 1, 0), new Vector32(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) { + super(); + this.type = "TubeGeometry"; + this.parameters = { + path, + tubularSegments, + radius, + radialSegments, + closed + }; + const frames2 = path.computeFrenetFrames(tubularSegments, closed); + this.tangents = frames2.tangents; + this.normals = frames2.normals; + this.binormals = frames2.binormals; + const vertex3 = new Vector32; + const normal = new Vector32; + const uv = new Vector22; + let P = new Vector32; + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; + generateBufferData(); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute2(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute2(uvs, 2)); + function generateBufferData() { + for (let i = 0;i < tubularSegments; i++) { + generateSegment(i); + } + generateSegment(closed === false ? tubularSegments : 0); + generateUVs(); + generateIndices(); + } + function generateSegment(i) { + P = path.getPointAt(i / tubularSegments, P); + const N = frames2.normals[i]; + const B2 = frames2.binormals[i]; + for (let j2 = 0;j2 <= radialSegments; j2++) { + const v = j2 / radialSegments * Math.PI * 2; + const sin = Math.sin(v); + const cos = -Math.cos(v); + normal.x = cos * N.x + sin * B2.x; + normal.y = cos * N.y + sin * B2.y; + normal.z = cos * N.z + sin * B2.z; + normal.normalize(); + normals.push(normal.x, normal.y, normal.z); + vertex3.x = P.x + radius * normal.x; + vertex3.y = P.y + radius * normal.y; + vertex3.z = P.z + radius * normal.z; + vertices.push(vertex3.x, vertex3.y, vertex3.z); + } + } + function generateIndices() { + for (let j2 = 1;j2 <= tubularSegments; j2++) { + for (let i = 1;i <= radialSegments; i++) { + const a2 = (radialSegments + 1) * (j2 - 1) + (i - 1); + const b2 = (radialSegments + 1) * j2 + (i - 1); + const c2 = (radialSegments + 1) * j2 + i; + const d = (radialSegments + 1) * (j2 - 1) + i; + indices.push(a2, b2, d); + indices.push(b2, c2, d); + } + } + } + function generateUVs() { + for (let i = 0;i <= tubularSegments; i++) { + for (let j2 = 0;j2 <= radialSegments; j2++) { + uv.x = i / tubularSegments; + uv.y = j2 / radialSegments; + uvs.push(uv.x, uv.y); + } + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.path = this.parameters.path.toJSON(); + return data2; + } + static fromJSON(data2) { + return new TubeGeometry3(new Curves2[data2.path.type]().fromJSON(data2.path), data2.tubularSegments, data2.radius, data2.radialSegments, data2.closed); + } + } + + class WireframeGeometry3 extends BufferGeometry2 { + constructor(geometry = null) { + super(); + this.type = "WireframeGeometry"; + this.parameters = { + geometry + }; + if (geometry !== null) { + const vertices = []; + const edges = new Set; + const start = new Vector32; + const end = new Vector32; + if (geometry.index !== null) { + const position2 = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; + if (groups.length === 0) { + groups = [{ start: 0, count: indices.count, materialIndex: 0 }]; + } + for (let o = 0, ol = groups.length;o < ol; ++o) { + const group = groups[o]; + const groupStart = group.start; + const groupCount = group.count; + for (let i = groupStart, l2 = groupStart + groupCount;i < l2; i += 3) { + for (let j2 = 0;j2 < 3; j2++) { + const index1 = indices.getX(i + j2); + const index2 = indices.getX(i + (j2 + 1) % 3); + start.fromBufferAttribute(position2, index1); + end.fromBufferAttribute(position2, index2); + if (isUniqueEdge2(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + } else { + const position2 = geometry.attributes.position; + for (let i = 0, l2 = position2.count / 3;i < l2; i++) { + for (let j2 = 0;j2 < 3; j2++) { + const index1 = 3 * i + j2; + const index2 = 3 * i + (j2 + 1) % 3; + start.fromBufferAttribute(position2, index1); + end.fromBufferAttribute(position2, index2); + if (isUniqueEdge2(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + this.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + } + function isUniqueEdge2(start, end, edges) { + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; + if (edges.has(hash1) === true || edges.has(hash2) === true) { + return false; + } else { + edges.add(hash1); + edges.add(hash2); + return true; + } + } + var Geometries2 = /* @__PURE__ */ Object.freeze({ + __proto__: null, + BoxGeometry: BoxGeometry2, + CapsuleGeometry: CapsuleGeometry2, + CircleGeometry: CircleGeometry2, + ConeGeometry: ConeGeometry2, + CylinderGeometry: CylinderGeometry2, + DodecahedronGeometry: DodecahedronGeometry2, + EdgesGeometry: EdgesGeometry2, + ExtrudeGeometry: ExtrudeGeometry2, + IcosahedronGeometry: IcosahedronGeometry2, + LatheGeometry: LatheGeometry2, + OctahedronGeometry: OctahedronGeometry2, + PlaneGeometry: PlaneGeometry3, + PolyhedronGeometry: PolyhedronGeometry2, + RingGeometry: RingGeometry2, + ShapeGeometry: ShapeGeometry2, + SphereGeometry: SphereGeometry3, + TetrahedronGeometry: TetrahedronGeometry2, + TorusGeometry: TorusGeometry2, + TorusKnotGeometry: TorusKnotGeometry3, + TubeGeometry: TubeGeometry3, + WireframeGeometry: WireframeGeometry3 + }); + + class ShadowMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isShadowMaterial = true; + this.type = "ShadowMaterial"; + this.color = new Color2(0); + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.fog = source.fog; + return this; + } + } + + class RawShaderMaterial2 extends ShaderMaterial2 { + constructor(parameters) { + super(parameters); + this.isRawShaderMaterial = true; + this.type = "RawShaderMaterial"; + } + } + + class MeshStandardMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshStandardMaterial = true; + this.type = "MeshStandardMaterial"; + this.defines = { STANDARD: "" }; + this.color = new Color2(16777215); + this.roughness = 1; + this.metalness = 0; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color2(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.roughnessMap = null; + this.metalnessMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler2; + this.envMapIntensity = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { STANDARD: "" }; + this.color.copy(source.color); + this.roughness = source.roughness; + this.metalness = source.metalness; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.roughnessMap = source.roughnessMap; + this.metalnessMap = source.metalnessMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.envMapIntensity = source.envMapIntensity; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + + class MeshPhysicalMaterial2 extends MeshStandardMaterial2 { + constructor(parameters) { + super(); + this.isMeshPhysicalMaterial = true; + this.defines = { + STANDARD: "", + PHYSICAL: "" + }; + this.type = "MeshPhysicalMaterial"; + this.anisotropyRotation = 0; + this.anisotropyMap = null; + this.clearcoatMap = null; + this.clearcoatRoughness = 0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector22(1, 1); + this.clearcoatNormalMap = null; + this.ior = 1.5; + Object.defineProperty(this, "reflectivity", { + get: function() { + return clamp3(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1); + }, + set: function(reflectivity) { + this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity); + } + }); + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [100, 400]; + this.iridescenceThicknessMap = null; + this.sheenColor = new Color2(0); + this.sheenColorMap = null; + this.sheenRoughness = 1; + this.sheenRoughnessMap = null; + this.transmissionMap = null; + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = Infinity; + this.attenuationColor = new Color2(1, 1, 1); + this.specularIntensity = 1; + this.specularIntensityMap = null; + this.specularColor = new Color2(1, 1, 1); + this.specularColorMap = null; + this._anisotropy = 0; + this._clearcoat = 0; + this._dispersion = 0; + this._iridescence = 0; + this._sheen = 0; + this._transmission = 0; + this.setValues(parameters); + } + get anisotropy() { + return this._anisotropy; + } + set anisotropy(value2) { + if (this._anisotropy > 0 !== value2 > 0) { + this.version++; + } + this._anisotropy = value2; + } + get clearcoat() { + return this._clearcoat; + } + set clearcoat(value2) { + if (this._clearcoat > 0 !== value2 > 0) { + this.version++; + } + this._clearcoat = value2; + } + get iridescence() { + return this._iridescence; + } + set iridescence(value2) { + if (this._iridescence > 0 !== value2 > 0) { + this.version++; + } + this._iridescence = value2; + } + get dispersion() { + return this._dispersion; + } + set dispersion(value2) { + if (this._dispersion > 0 !== value2 > 0) { + this.version++; + } + this._dispersion = value2; + } + get sheen() { + return this._sheen; + } + set sheen(value2) { + if (this._sheen > 0 !== value2 > 0) { + this.version++; + } + this._sheen = value2; + } + get transmission() { + return this._transmission; + } + set transmission(value2) { + if (this._transmission > 0 !== value2 > 0) { + this.version++; + } + this._transmission = value2; + } + copy(source) { + super.copy(source); + this.defines = { + STANDARD: "", + PHYSICAL: "" + }; + this.anisotropy = source.anisotropy; + this.anisotropyRotation = source.anisotropyRotation; + this.anisotropyMap = source.anisotropyMap; + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy(source.clearcoatNormalScale); + this.dispersion = source.dispersion; + this.ior = source.ior; + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [...source.iridescenceThicknessRange]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + this.sheen = source.sheen; + this.sheenColor.copy(source.sheenColor); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy(source.attenuationColor); + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy(source.specularColor); + this.specularColorMap = source.specularColorMap; + return this; + } + } + + class MeshPhongMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshPhongMaterial = true; + this.type = "MeshPhongMaterial"; + this.color = new Color2(16777215); + this.specular = new Color2(1118481); + this.shininess = 30; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color2(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler2; + this.combine = MultiplyOperation2; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.specular.copy(source.specular); + this.shininess = source.shininess; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + + class MeshToonMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshToonMaterial = true; + this.defines = { TOON: "" }; + this.type = "MeshToonMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.gradientMap = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color2(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.gradientMap = source.gradientMap; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } + } + + class MeshNormalMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshNormalMaterial = true; + this.type = "MeshNormalMaterial"; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.flatShading = false; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.flatShading = source.flatShading; + return this; + } + } + + class MeshLambertMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshLambertMaterial = true; + this.type = "MeshLambertMaterial"; + this.color = new Color2(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color2(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler2; + this.combine = MultiplyOperation2; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + + class MeshDepthMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshDepthMaterial = true; + this.type = "MeshDepthMaterial"; + this.depthPacking = BasicDepthPacking2; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.depthPacking = source.depthPacking; + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + return this; + } + } + + class MeshDistanceMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshDistanceMaterial = true; + this.type = "MeshDistanceMaterial"; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + return this; + } + } + + class MeshMatcapMaterial2 extends Material2 { + constructor(parameters) { + super(); + this.isMeshMatcapMaterial = true; + this.defines = { MATCAP: "" }; + this.type = "MeshMatcapMaterial"; + this.color = new Color2(16777215); + this.matcap = null; + this.map = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap2; + this.normalScale = new Vector22(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { MATCAP: "" }; + this.color.copy(source.color); + this.matcap = source.matcap; + this.map = source.map; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } + } + + class LineDashedMaterial2 extends LineBasicMaterial2 { + constructor(parameters) { + super(); + this.isLineDashedMaterial = true; + this.type = "LineDashedMaterial"; + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + return this; + } + } + function convertArray2(array, type, forceClone) { + if (!array || !forceClone && array.constructor === type) + return array; + if (typeof type.BYTES_PER_ELEMENT === "number") { + return new type(array); + } + return Array.prototype.slice.call(array); + } + function isTypedArray2(object) { + return ArrayBuffer.isView(object) && !(object instanceof DataView); + } + function getKeyframeOrder2(times) { + function compareTime(i, j2) { + return times[i] - times[j2]; + } + const n2 = times.length; + const result = new Array(n2); + for (let i = 0;i !== n2; ++i) + result[i] = i; + result.sort(compareTime); + return result; + } + function sortedArray2(values2, stride, order) { + const nValues = values2.length; + const result = new values2.constructor(nValues); + for (let i = 0, dstOffset = 0;dstOffset !== nValues; ++i) { + const srcOffset = order[i] * stride; + for (let j2 = 0;j2 !== stride; ++j2) { + result[dstOffset++] = values2[srcOffset + j2]; + } + } + return result; + } + function flattenJSON2(jsonKeys, times, values2, valuePropertyName) { + let i = 1, key2 = jsonKeys[0]; + while (key2 !== undefined && key2[valuePropertyName] === undefined) { + key2 = jsonKeys[i++]; + } + if (key2 === undefined) + return; + let value2 = key2[valuePropertyName]; + if (value2 === undefined) + return; + if (Array.isArray(value2)) { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + values2.push.apply(values2, value2); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } else if (value2.toArray !== undefined) { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + value2.toArray(values2, values2.length); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } else { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + values2.push(value2); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } + } + function subclip2(sourceClip, name2, startFrame, endFrame, fps = 30) { + const clip = sourceClip.clone(); + clip.name = name2; + const tracks = []; + for (let i = 0;i < clip.tracks.length; ++i) { + const track = clip.tracks[i]; + const valueSize = track.getValueSize(); + const times = []; + const values2 = []; + for (let j2 = 0;j2 < track.times.length; ++j2) { + const frame = track.times[j2] * fps; + if (frame < startFrame || frame >= endFrame) + continue; + times.push(track.times[j2]); + for (let k3 = 0;k3 < valueSize; ++k3) { + values2.push(track.values[j2 * valueSize + k3]); + } + } + if (times.length === 0) + continue; + track.times = convertArray2(times, track.times.constructor); + track.values = convertArray2(values2, track.values.constructor); + tracks.push(track); + } + clip.tracks = tracks; + let minStartTime = Infinity; + for (let i = 0;i < clip.tracks.length; ++i) { + if (minStartTime > clip.tracks[i].times[0]) { + minStartTime = clip.tracks[i].times[0]; + } + } + for (let i = 0;i < clip.tracks.length; ++i) { + clip.tracks[i].shift(-1 * minStartTime); + } + clip.resetDuration(); + return clip; + } + function makeClipAdditive2(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) { + if (fps <= 0) + fps = 30; + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; + for (let i = 0;i < numTracks; ++i) { + const referenceTrack = referenceClip.tracks[i]; + const referenceTrackType = referenceTrack.ValueTypeName; + if (referenceTrackType === "bool" || referenceTrackType === "string") + continue; + const targetTrack = targetClip.tracks.find(function(track) { + return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType; + }); + if (targetTrack === undefined) + continue; + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); + if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + referenceOffset = referenceValueSize / 3; + } + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); + if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + targetOffset = targetValueSize / 3; + } + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; + if (referenceTime <= referenceTrack.times[0]) { + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else if (referenceTime >= referenceTrack.times[lastIndex]) { + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else { + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate(referenceTime); + referenceValue = interpolant.resultBuffer.slice(startIndex, endIndex); + } + if (referenceTrackType === "quaternion") { + const referenceQuat = new Quaternion2().fromArray(referenceValue).normalize().conjugate(); + referenceQuat.toArray(referenceValue); + } + const numTimes = targetTrack.times.length; + for (let j2 = 0;j2 < numTimes; ++j2) { + const valueStart = j2 * targetValueSize + targetOffset; + if (referenceTrackType === "quaternion") { + Quaternion2.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart); + } else { + const valueEnd = targetValueSize - targetOffset * 2; + for (let k3 = 0;k3 < valueEnd; ++k3) { + targetTrack.values[valueStart + k3] -= referenceValue[k3]; + } + } + } + } + targetClip.blendMode = AdditiveAnimationBlendMode2; + return targetClip; + } + var AnimationUtils2 = { + convertArray: convertArray2, + isTypedArray: isTypedArray2, + getKeyframeOrder: getKeyframeOrder2, + sortedArray: sortedArray2, + flattenJSON: flattenJSON2, + subclip: subclip2, + makeClipAdditive: makeClipAdditive2 + }; + + class Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; + this.settings = null; + this.DefaultSettings_ = {}; + } + evaluate(t3) { + const pp = this.parameterPositions; + let i1 = this._cachedIndex, t1 = pp[i1], t0 = pp[i1 - 1]; + validate_interval: { + seek: { + let right; + linear_scan: { + forward_scan: + if (!(t3 < t1)) { + for (let giveUpAt = i1 + 2;; ) { + if (t1 === undefined) { + if (t3 < t0) + break forward_scan; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + if (i1 === giveUpAt) + break; + t0 = t1; + t1 = pp[++i1]; + if (t3 < t1) { + break seek; + } + } + right = pp.length; + break linear_scan; + } + if (!(t3 >= t0)) { + const t1global = pp[1]; + if (t3 < t1global) { + i1 = 2; + t0 = t1global; + } + for (let giveUpAt = i1 - 2;; ) { + if (t0 === undefined) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (i1 === giveUpAt) + break; + t1 = t0; + t0 = pp[--i1 - 1]; + if (t3 >= t0) { + break seek; + } + } + right = i1; + i1 = 0; + break linear_scan; + } + break validate_interval; + } + while (i1 < right) { + const mid = i1 + right >>> 1; + if (t3 < pp[mid]) { + right = mid; + } else { + i1 = mid + 1; + } + } + t1 = pp[i1]; + t0 = pp[i1 - 1]; + if (t0 === undefined) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (t1 === undefined) { + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + } + this._cachedIndex = i1; + this.intervalChanged_(i1, t0, t1); + } + return this.interpolate_(i1, t0, t3, t1); + } + getSettings_() { + return this.settings || this.DefaultSettings_; + } + copySampleValue_(index2) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, offset = index2 * stride; + for (let i = 0;i !== stride; ++i) { + result[i] = values2[offset + i]; + } + return result; + } + interpolate_() { + throw new Error("call to abstract method"); + } + intervalChanged_() { + } + } + + class CubicInterpolant2 extends Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; + this.DefaultSettings_ = { + endingStart: ZeroCurvatureEnding2, + endingEnd: ZeroCurvatureEnding2 + }; + } + intervalChanged_(i1, t0, t1) { + const pp = this.parameterPositions; + let iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[iPrev], tNext = pp[iNext]; + if (tPrev === undefined) { + switch (this.getSettings_().endingStart) { + case ZeroSlopeEnding2: + iPrev = i1; + tPrev = 2 * t0 - t1; + break; + case WrapAroundEnding2: + iPrev = pp.length - 2; + tPrev = t0 + pp[iPrev] - pp[iPrev + 1]; + break; + default: + iPrev = i1; + tPrev = t1; + } + } + if (tNext === undefined) { + switch (this.getSettings_().endingEnd) { + case ZeroSlopeEnding2: + iNext = i1; + tNext = 2 * t1 - t0; + break; + case WrapAroundEnding2: + iNext = 1; + tNext = t1 + pp[1] - pp[0]; + break; + default: + iNext = i1 - 1; + tNext = t0; + } + } + const halfDt = (t1 - t0) * 0.5, stride = this.valueSize; + this._weightPrev = halfDt / (t0 - tPrev); + this._weightNext = halfDt / (tNext - t1); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + } + interpolate_(i1, t0, t3, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o0 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p = (t3 - t0) / (t1 - t0), pp = p * p, ppp = pp * p; + const sP = -wP * ppp + 2 * wP * pp - wP * p; + const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1; + const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; + for (let i = 0;i !== stride; ++i) { + result[i] = sP * values2[oP + i] + s0 * values2[o0 + i] + s1 * values2[o1 + i] + sN * values2[oN + i]; + } + return result; + } + } + + class LinearInterpolant2 extends Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t3, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = (t3 - t0) / (t1 - t0), weight0 = 1 - weight1; + for (let i = 0;i !== stride; ++i) { + result[i] = values2[offset0 + i] * weight0 + values2[offset1 + i] * weight1; + } + return result; + } + } + + class DiscreteInterpolant2 extends Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1) { + return this.copySampleValue_(i1 - 1); + } + } + + class KeyframeTrack2 { + constructor(name2, times, values2, interpolation) { + if (name2 === undefined) + throw new Error("THREE.KeyframeTrack: track name is undefined"); + if (times === undefined || times.length === 0) + throw new Error("THREE.KeyframeTrack: no keyframes in track named " + name2); + this.name = name2; + this.times = convertArray2(times, this.TimeBufferType); + this.values = convertArray2(values2, this.ValueBufferType); + this.setInterpolation(interpolation || this.DefaultInterpolation); + } + static toJSON(track) { + const trackType = track.constructor; + let json; + if (trackType.toJSON !== this.toJSON) { + json = trackType.toJSON(track); + } else { + json = { + name: track.name, + times: convertArray2(track.times, Array), + values: convertArray2(track.values, Array) + }; + const interpolation = track.getInterpolation(); + if (interpolation !== track.DefaultInterpolation) { + json.interpolation = interpolation; + } + } + json.type = track.ValueTypeName; + return json; + } + InterpolantFactoryMethodDiscrete(result) { + return new DiscreteInterpolant2(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodLinear(result) { + return new LinearInterpolant2(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodSmooth(result) { + return new CubicInterpolant2(this.times, this.values, this.getValueSize(), result); + } + setInterpolation(interpolation) { + let factoryMethod; + switch (interpolation) { + case InterpolateDiscrete2: + factoryMethod = this.InterpolantFactoryMethodDiscrete; + break; + case InterpolateLinear2: + factoryMethod = this.InterpolantFactoryMethodLinear; + break; + case InterpolateSmooth2: + factoryMethod = this.InterpolantFactoryMethodSmooth; + break; + } + if (factoryMethod === undefined) { + const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; + if (this.createInterpolant === undefined) { + if (interpolation !== this.DefaultInterpolation) { + this.setInterpolation(this.DefaultInterpolation); + } else { + throw new Error(message); + } + } + console.warn("THREE.KeyframeTrack:", message); + return this; + } + this.createInterpolant = factoryMethod; + return this; + } + getInterpolation() { + switch (this.createInterpolant) { + case this.InterpolantFactoryMethodDiscrete: + return InterpolateDiscrete2; + case this.InterpolantFactoryMethodLinear: + return InterpolateLinear2; + case this.InterpolantFactoryMethodSmooth: + return InterpolateSmooth2; + } + } + getValueSize() { + return this.values.length / this.times.length; + } + shift(timeOffset) { + if (timeOffset !== 0) { + const times = this.times; + for (let i = 0, n2 = times.length;i !== n2; ++i) { + times[i] += timeOffset; + } + } + return this; + } + scale(timeScale) { + if (timeScale !== 1) { + const times = this.times; + for (let i = 0, n2 = times.length;i !== n2; ++i) { + times[i] *= timeScale; + } + } + return this; + } + trim(startTime, endTime) { + const times = this.times, nKeys = times.length; + let from = 0, to = nKeys - 1; + while (from !== nKeys && times[from] < startTime) { + ++from; + } + while (to !== -1 && times[to] > endTime) { + --to; + } + ++to; + if (from !== 0 || to !== nKeys) { + if (from >= to) { + to = Math.max(to, 1); + from = to - 1; + } + const stride = this.getValueSize(); + this.times = times.slice(from, to); + this.values = this.values.slice(from * stride, to * stride); + } + return this; + } + validate() { + let valid = true; + const valueSize = this.getValueSize(); + if (valueSize - Math.floor(valueSize) !== 0) { + console.error("THREE.KeyframeTrack: Invalid value size in track.", this); + valid = false; + } + const times = this.times, values2 = this.values, nKeys = times.length; + if (nKeys === 0) { + console.error("THREE.KeyframeTrack: Track is empty.", this); + valid = false; + } + let prevTime = null; + for (let i = 0;i !== nKeys; i++) { + const currTime = times[i]; + if (typeof currTime === "number" && isNaN(currTime)) { + console.error("THREE.KeyframeTrack: Time is not a valid number.", this, i, currTime); + valid = false; + break; + } + if (prevTime !== null && prevTime > currTime) { + console.error("THREE.KeyframeTrack: Out of order keys.", this, i, currTime, prevTime); + valid = false; + break; + } + prevTime = currTime; + } + if (values2 !== undefined) { + if (isTypedArray2(values2)) { + for (let i = 0, n2 = values2.length;i !== n2; ++i) { + const value2 = values2[i]; + if (isNaN(value2)) { + console.error("THREE.KeyframeTrack: Value is not a valid number.", this, i, value2); + valid = false; + break; + } + } + } + } + return valid; + } + optimize() { + const times = this.times.slice(), values2 = this.values.slice(), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth2, lastIndex = times.length - 1; + let writeIndex = 1; + for (let i = 1;i < lastIndex; ++i) { + let keep = false; + const time2 = times[i]; + const timeNext = times[i + 1]; + if (time2 !== timeNext && (i !== 1 || time2 !== times[0])) { + if (!smoothInterpolation) { + const offset = i * stride, offsetP = offset - stride, offsetN = offset + stride; + for (let j2 = 0;j2 !== stride; ++j2) { + const value2 = values2[offset + j2]; + if (value2 !== values2[offsetP + j2] || value2 !== values2[offsetN + j2]) { + keep = true; + break; + } + } + } else { + keep = true; + } + } + if (keep) { + if (i !== writeIndex) { + times[writeIndex] = times[i]; + const readOffset = i * stride, writeOffset = writeIndex * stride; + for (let j2 = 0;j2 !== stride; ++j2) { + values2[writeOffset + j2] = values2[readOffset + j2]; + } + } + ++writeIndex; + } + } + if (lastIndex > 0) { + times[writeIndex] = times[lastIndex]; + for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j2 = 0;j2 !== stride; ++j2) { + values2[writeOffset + j2] = values2[readOffset + j2]; + } + ++writeIndex; + } + if (writeIndex !== times.length) { + this.times = times.slice(0, writeIndex); + this.values = values2.slice(0, writeIndex * stride); + } else { + this.times = times; + this.values = values2; + } + return this; + } + clone() { + const times = this.times.slice(); + const values2 = this.values.slice(); + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack(this.name, times, values2); + track.createInterpolant = this.createInterpolant; + return track; + } + } + KeyframeTrack2.prototype.TimeBufferType = Float32Array; + KeyframeTrack2.prototype.ValueBufferType = Float32Array; + KeyframeTrack2.prototype.DefaultInterpolation = InterpolateLinear2; + + class BooleanKeyframeTrack2 extends KeyframeTrack2 { + constructor(name2, times, values2) { + super(name2, times, values2); + } + } + BooleanKeyframeTrack2.prototype.ValueTypeName = "bool"; + BooleanKeyframeTrack2.prototype.ValueBufferType = Array; + BooleanKeyframeTrack2.prototype.DefaultInterpolation = InterpolateDiscrete2; + BooleanKeyframeTrack2.prototype.InterpolantFactoryMethodLinear = undefined; + BooleanKeyframeTrack2.prototype.InterpolantFactoryMethodSmooth = undefined; + + class ColorKeyframeTrack2 extends KeyframeTrack2 { + } + ColorKeyframeTrack2.prototype.ValueTypeName = "color"; + + class NumberKeyframeTrack2 extends KeyframeTrack2 { + } + NumberKeyframeTrack2.prototype.ValueTypeName = "number"; + + class QuaternionLinearInterpolant2 extends Interpolant2 { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t3, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, alpha = (t3 - t0) / (t1 - t0); + let offset = i1 * stride; + for (let end = offset + stride;offset !== end; offset += 4) { + Quaternion2.slerpFlat(result, 0, values2, offset - stride, values2, offset, alpha); + } + return result; + } + } + + class QuaternionKeyframeTrack2 extends KeyframeTrack2 { + InterpolantFactoryMethodLinear(result) { + return new QuaternionLinearInterpolant2(this.times, this.values, this.getValueSize(), result); + } + } + QuaternionKeyframeTrack2.prototype.ValueTypeName = "quaternion"; + QuaternionKeyframeTrack2.prototype.InterpolantFactoryMethodSmooth = undefined; + + class StringKeyframeTrack2 extends KeyframeTrack2 { + constructor(name2, times, values2) { + super(name2, times, values2); + } + } + StringKeyframeTrack2.prototype.ValueTypeName = "string"; + StringKeyframeTrack2.prototype.ValueBufferType = Array; + StringKeyframeTrack2.prototype.DefaultInterpolation = InterpolateDiscrete2; + StringKeyframeTrack2.prototype.InterpolantFactoryMethodLinear = undefined; + StringKeyframeTrack2.prototype.InterpolantFactoryMethodSmooth = undefined; + + class VectorKeyframeTrack2 extends KeyframeTrack2 { + } + VectorKeyframeTrack2.prototype.ValueTypeName = "vector"; + + class AnimationClip2 { + constructor(name2 = "", duration = -1, tracks = [], blendMode = NormalAnimationBlendMode2) { + this.name = name2; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; + this.uuid = generateUUID2(); + if (this.duration < 0) { + this.resetDuration(); + } + } + static parse(json) { + const tracks = [], jsonTracks = json.tracks, frameTime = 1 / (json.fps || 1); + for (let i = 0, n2 = jsonTracks.length;i !== n2; ++i) { + tracks.push(parseKeyframeTrack2(jsonTracks[i]).scale(frameTime)); + } + const clip = new this(json.name, json.duration, tracks, json.blendMode); + clip.uuid = json.uuid; + return clip; + } + static toJSON(clip) { + const tracks = [], clipTracks = clip.tracks; + const json = { + name: clip.name, + duration: clip.duration, + tracks, + uuid: clip.uuid, + blendMode: clip.blendMode + }; + for (let i = 0, n2 = clipTracks.length;i !== n2; ++i) { + tracks.push(KeyframeTrack2.toJSON(clipTracks[i])); + } + return json; + } + static CreateFromMorphTargetSequence(name2, morphTargetSequence, fps, noLoop) { + const numMorphTargets = morphTargetSequence.length; + const tracks = []; + for (let i = 0;i < numMorphTargets; i++) { + let times = []; + let values2 = []; + times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets); + values2.push(0, 1, 0); + const order = getKeyframeOrder2(times); + times = sortedArray2(times, 1, order); + values2 = sortedArray2(values2, 1, order); + if (!noLoop && times[0] === 0) { + times.push(numMorphTargets); + values2.push(values2[0]); + } + tracks.push(new NumberKeyframeTrack2(".morphTargetInfluences[" + morphTargetSequence[i].name + "]", times, values2).scale(1 / fps)); + } + return new this(name2, -1, tracks); + } + static findByName(objectOrClipArray, name2) { + let clipArray = objectOrClipArray; + if (!Array.isArray(objectOrClipArray)) { + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; + } + for (let i = 0;i < clipArray.length; i++) { + if (clipArray[i].name === name2) { + return clipArray[i]; + } + } + return null; + } + static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) { + const animationToMorphTargets = {}; + const pattern = /^([\w-]*?)([\d]+)$/; + for (let i = 0, il = morphTargets.length;i < il; i++) { + const morphTarget = morphTargets[i]; + const parts = morphTarget.name.match(pattern); + if (parts && parts.length > 1) { + const name2 = parts[1]; + let animationMorphTargets = animationToMorphTargets[name2]; + if (!animationMorphTargets) { + animationToMorphTargets[name2] = animationMorphTargets = []; + } + animationMorphTargets.push(morphTarget); + } + } + const clips = []; + for (const name2 in animationToMorphTargets) { + clips.push(this.CreateFromMorphTargetSequence(name2, animationToMorphTargets[name2], fps, noLoop)); + } + return clips; + } + static parseAnimation(animation, bones) { + if (!animation) { + console.error("THREE.AnimationClip: No animation in JSONLoader data."); + return null; + } + const addNonemptyTrack = function(trackType, trackName, animationKeys, propertyName, destTracks) { + if (animationKeys.length !== 0) { + const times = []; + const values2 = []; + flattenJSON2(animationKeys, times, values2, propertyName); + if (times.length !== 0) { + destTracks.push(new trackType(trackName, times, values2)); + } + } + }; + const tracks = []; + const clipName = animation.name || "default"; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; + let duration = animation.length || -1; + const hierarchyTracks = animation.hierarchy || []; + for (let h = 0;h < hierarchyTracks.length; h++) { + const animationKeys = hierarchyTracks[h].keys; + if (!animationKeys || animationKeys.length === 0) + continue; + if (animationKeys[0].morphTargets) { + const morphTargetNames = {}; + let k3; + for (k3 = 0;k3 < animationKeys.length; k3++) { + if (animationKeys[k3].morphTargets) { + for (let m = 0;m < animationKeys[k3].morphTargets.length; m++) { + morphTargetNames[animationKeys[k3].morphTargets[m]] = -1; + } + } + } + for (const morphTargetName in morphTargetNames) { + const times = []; + const values2 = []; + for (let m = 0;m !== animationKeys[k3].morphTargets.length; ++m) { + const animationKey = animationKeys[k3]; + times.push(animationKey.time); + values2.push(animationKey.morphTarget === morphTargetName ? 1 : 0); + } + tracks.push(new NumberKeyframeTrack2(".morphTargetInfluence[" + morphTargetName + "]", times, values2)); + } + duration = morphTargetNames.length * fps; + } else { + const boneName = ".bones[" + bones[h].name + "]"; + addNonemptyTrack(VectorKeyframeTrack2, boneName + ".position", animationKeys, "pos", tracks); + addNonemptyTrack(QuaternionKeyframeTrack2, boneName + ".quaternion", animationKeys, "rot", tracks); + addNonemptyTrack(VectorKeyframeTrack2, boneName + ".scale", animationKeys, "scl", tracks); + } + } + if (tracks.length === 0) { + return null; + } + const clip = new this(clipName, duration, tracks, blendMode); + return clip; + } + resetDuration() { + const tracks = this.tracks; + let duration = 0; + for (let i = 0, n2 = tracks.length;i !== n2; ++i) { + const track = this.tracks[i]; + duration = Math.max(duration, track.times[track.times.length - 1]); + } + this.duration = duration; + return this; + } + trim() { + for (let i = 0;i < this.tracks.length; i++) { + this.tracks[i].trim(0, this.duration); + } + return this; + } + validate() { + let valid = true; + for (let i = 0;i < this.tracks.length; i++) { + valid = valid && this.tracks[i].validate(); + } + return valid; + } + optimize() { + for (let i = 0;i < this.tracks.length; i++) { + this.tracks[i].optimize(); + } + return this; + } + clone() { + const tracks = []; + for (let i = 0;i < this.tracks.length; i++) { + tracks.push(this.tracks[i].clone()); + } + return new this.constructor(this.name, this.duration, tracks, this.blendMode); + } + toJSON() { + return this.constructor.toJSON(this); + } + } + function getTrackTypeForValueTypeName2(typeName) { + switch (typeName.toLowerCase()) { + case "scalar": + case "double": + case "float": + case "number": + case "integer": + return NumberKeyframeTrack2; + case "vector": + case "vector2": + case "vector3": + case "vector4": + return VectorKeyframeTrack2; + case "color": + return ColorKeyframeTrack2; + case "quaternion": + return QuaternionKeyframeTrack2; + case "bool": + case "boolean": + return BooleanKeyframeTrack2; + case "string": + return StringKeyframeTrack2; + } + throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + typeName); + } + function parseKeyframeTrack2(json) { + if (json.type === undefined) { + throw new Error("THREE.KeyframeTrack: track type undefined, can not parse"); + } + const trackType = getTrackTypeForValueTypeName2(json.type); + if (json.times === undefined) { + const times = [], values2 = []; + flattenJSON2(json.keys, times, values2, "value"); + json.times = times; + json.values = values2; + } + if (trackType.parse !== undefined) { + return trackType.parse(json); + } else { + return new trackType(json.name, json.times, json.values, json.interpolation); + } + } + var Cache2 = { + enabled: false, + files: {}, + add: function(key2, file) { + if (this.enabled === false) + return; + this.files[key2] = file; + }, + get: function(key2) { + if (this.enabled === false) + return; + return this.files[key2]; + }, + remove: function(key2) { + delete this.files[key2]; + }, + clear: function() { + this.files = {}; + } + }; + + class LoadingManager2 { + constructor(onLoad, onProgress, onError) { + const scope = this; + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + this.itemStart = function(url) { + itemsTotal++; + if (isLoading === false) { + if (scope.onStart !== undefined) { + scope.onStart(url, itemsLoaded, itemsTotal); + } + } + isLoading = true; + }; + this.itemEnd = function(url) { + itemsLoaded++; + if (scope.onProgress !== undefined) { + scope.onProgress(url, itemsLoaded, itemsTotal); + } + if (itemsLoaded === itemsTotal) { + isLoading = false; + if (scope.onLoad !== undefined) { + scope.onLoad(); + } + } + }; + this.itemError = function(url) { + if (scope.onError !== undefined) { + scope.onError(url); + } + }; + this.resolveURL = function(url) { + if (urlModifier) { + return urlModifier(url); + } + return url; + }; + this.setURLModifier = function(transform2) { + urlModifier = transform2; + return this; + }; + this.addHandler = function(regex, loader) { + handlers.push(regex, loader); + return this; + }; + this.removeHandler = function(regex) { + const index2 = handlers.indexOf(regex); + if (index2 !== -1) { + handlers.splice(index2, 2); + } + return this; + }; + this.getHandler = function(file) { + for (let i = 0, l2 = handlers.length;i < l2; i += 2) { + const regex = handlers[i]; + const loader = handlers[i + 1]; + if (regex.global) + regex.lastIndex = 0; + if (regex.test(file)) { + return loader; + } + } + return null; + }; + } + } + var DefaultLoadingManager2 = /* @__PURE__ */ new LoadingManager2; + + class Loader2 { + constructor(manager) { + this.manager = manager !== undefined ? manager : DefaultLoadingManager2; + this.crossOrigin = "anonymous"; + this.withCredentials = false; + this.path = ""; + this.resourcePath = ""; + this.requestHeader = {}; + } + load() { + } + loadAsync(url, onProgress) { + const scope = this; + return new Promise(function(resolve, reject2) { + scope.load(url, resolve, onProgress, reject2); + }); + } + parse() { + } + setCrossOrigin(crossOrigin) { + this.crossOrigin = crossOrigin; + return this; + } + setWithCredentials(value2) { + this.withCredentials = value2; + return this; + } + setPath(path) { + this.path = path; + return this; + } + setResourcePath(resourcePath) { + this.resourcePath = resourcePath; + return this; + } + setRequestHeader(requestHeader) { + this.requestHeader = requestHeader; + return this; + } + } + Loader2.DEFAULT_MATERIAL_NAME = "__DEFAULT"; + var loading2 = {}; + + class HttpError2 extends Error { + constructor(message, response) { + super(message); + this.response = response; + } + } + + class FileLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (url === undefined) + url = ""; + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const cached = Cache2.get(url); + if (cached !== undefined) { + this.manager.itemStart(url); + setTimeout(() => { + if (onLoad) + onLoad(cached); + this.manager.itemEnd(url); + }, 0); + return cached; + } + if (loading2[url] !== undefined) { + loading2[url].push({ + onLoad, + onProgress, + onError + }); + return; + } + loading2[url] = []; + loading2[url].push({ + onLoad, + onProgress, + onError + }); + const req = new Request(url, { + headers: new Headers(this.requestHeader), + credentials: this.withCredentials ? "include" : "same-origin" + }); + const mimeType = this.mimeType; + const responseType = this.responseType; + fetch(req).then((response) => { + if (response.status === 200 || response.status === 0) { + if (response.status === 0) { + console.warn("THREE.FileLoader: HTTP Status 0 received."); + } + if (typeof ReadableStream === "undefined" || response.body === undefined || response.body.getReader === undefined) { + return response; + } + const callbacks = loading2[url]; + const reader = response.body.getReader(); + const contentLength = response.headers.get("X-File-Size") || response.headers.get("Content-Length"); + const total = contentLength ? parseInt(contentLength) : 0; + const lengthComputable = total !== 0; + let loaded = 0; + const stream = new ReadableStream({ + start(controller) { + readData(); + function readData() { + reader.read().then(({ done, value: value2 }) => { + if (done) { + controller.close(); + } else { + loaded += value2.byteLength; + const event = new ProgressEvent("progress", { lengthComputable, loaded, total }); + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onProgress) + callback.onProgress(event); + } + controller.enqueue(value2); + readData(); + } + }, (e) => { + controller.error(e); + }); + } + } + }); + return new Response(stream); + } else { + throw new HttpError2(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response); + } + }).then((response) => { + switch (responseType) { + case "arraybuffer": + return response.arrayBuffer(); + case "blob": + return response.blob(); + case "document": + return response.text().then((text2) => { + const parser = new DOMParser; + return parser.parseFromString(text2, mimeType); + }); + case "json": + return response.json(); + default: + if (mimeType === undefined) { + return response.text(); + } else { + const re = /charset="?([^;"\s]*)"?/i; + const exec2 = re.exec(mimeType); + const label = exec2 && exec2[1] ? exec2[1].toLowerCase() : undefined; + const decoder = new TextDecoder(label); + return response.arrayBuffer().then((ab) => decoder.decode(ab)); + } + } + }).then((data2) => { + Cache2.add(url, data2); + const callbacks = loading2[url]; + delete loading2[url]; + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onLoad) + callback.onLoad(data2); + } + }).catch((err) => { + const callbacks = loading2[url]; + if (callbacks === undefined) { + this.manager.itemError(url); + throw err; + } + delete loading2[url]; + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onError) + callback.onError(err); + } + this.manager.itemError(url); + }).finally(() => { + this.manager.itemEnd(url); + }); + this.manager.itemStart(url); + } + setResponseType(value2) { + this.responseType = value2; + return this; + } + setMimeType(value2) { + this.mimeType = value2; + return this; + } + } + + class AnimationLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader2(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const animations = []; + for (let i = 0;i < json.length; i++) { + const clip = AnimationClip2.parse(json[i]); + animations.push(clip); + } + return animations; + } + } + + class CompressedTextureLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const images = []; + const texture = new CompressedTexture2; + const loader = new FileLoader2(this.manager); + loader.setPath(this.path); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(scope.withCredentials); + let loaded = 0; + function loadTexture(i) { + loader.load(url[i], function(buffer) { + const texDatas = scope.parse(buffer, true); + images[i] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + loaded += 1; + if (loaded === 6) { + if (texDatas.mipmapCount === 1) + texture.minFilter = LinearFilter2; + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + } + }, onProgress, onError); + } + if (Array.isArray(url)) { + for (let i = 0, il = url.length;i < il; ++i) { + loadTexture(i); + } + } else { + loader.load(url, function(buffer) { + const texDatas = scope.parse(buffer, true); + if (texDatas.isCubemap) { + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + for (let f = 0;f < faces; f++) { + images[f] = { mipmaps: [] }; + for (let i = 0;i < texDatas.mipmapCount; i++) { + images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]); + images[f].format = texDatas.format; + images[f].width = texDatas.width; + images[f].height = texDatas.height; + } + } + texture.image = images; + } else { + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + } + if (texDatas.mipmapCount === 1) { + texture.minFilter = LinearFilter2; + } + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + }, onProgress, onError); + } + return texture; + } + } + + class ImageLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache2.get(url); + if (cached !== undefined) { + scope.manager.itemStart(url); + setTimeout(function() { + if (onLoad) + onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const image = createElementNS2("img"); + function onImageLoad() { + removeEventListeners(); + Cache2.add(url, this); + if (onLoad) + onLoad(this); + scope.manager.itemEnd(url); + } + function onImageError(event) { + removeEventListeners(); + if (onError) + onError(event); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + } + function removeEventListeners() { + image.removeEventListener("load", onImageLoad, false); + image.removeEventListener("error", onImageError, false); + } + image.addEventListener("load", onImageLoad, false); + image.addEventListener("error", onImageError, false); + if (url.slice(0, 5) !== "data:") { + if (this.crossOrigin !== undefined) + image.crossOrigin = this.crossOrigin; + } + scope.manager.itemStart(url); + image.src = url; + return image; + } + } + + class CubeTextureLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(urls, onLoad, onProgress, onError) { + const texture = new CubeTexture2; + texture.colorSpace = SRGBColorSpace2; + const loader = new ImageLoader2(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + let loaded = 0; + function loadTexture(i) { + loader.load(urls[i], function(image) { + texture.images[i] = image; + loaded++; + if (loaded === 6) { + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + } + }, undefined, onError); + } + for (let i = 0;i < urls.length; ++i) { + loadTexture(i); + } + return texture; + } + } + + class DataTextureLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const texture = new DataTexture2; + const loader = new FileLoader2(this.manager); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setPath(this.path); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(buffer) { + let texData; + try { + texData = scope.parse(buffer); + } catch (error) { + if (onError !== undefined) { + onError(error); + } else { + console.error(error); + return; + } + } + if (texData.image !== undefined) { + texture.image = texData.image; + } else if (texData.data !== undefined) { + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; + } + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping2; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping2; + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter2; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter2; + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + if (texData.colorSpace !== undefined) { + texture.colorSpace = texData.colorSpace; + } + if (texData.flipY !== undefined) { + texture.flipY = texData.flipY; + } + if (texData.format !== undefined) { + texture.format = texData.format; + } + if (texData.type !== undefined) { + texture.type = texData.type; + } + if (texData.mipmaps !== undefined) { + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter2; + } + if (texData.mipmapCount === 1) { + texture.minFilter = LinearFilter2; + } + if (texData.generateMipmaps !== undefined) { + texture.generateMipmaps = texData.generateMipmaps; + } + texture.needsUpdate = true; + if (onLoad) + onLoad(texture, texData); + }, onProgress, onError); + return texture; + } + } + + class TextureLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const texture = new Texture2; + const loader = new ImageLoader2(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + loader.load(url, function(image) { + texture.image = image; + texture.needsUpdate = true; + if (onLoad !== undefined) { + onLoad(texture); + } + }, onProgress, onError); + return texture; + } + } + + class Light2 extends Object3D2 { + constructor(color, intensity = 1) { + super(); + this.isLight = true; + this.type = "Light"; + this.color = new Color2(color); + this.intensity = intensity; + } + dispose() { + } + copy(source, recursive) { + super.copy(source, recursive); + this.color.copy(source.color); + this.intensity = source.intensity; + return this; + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + data2.object.color = this.color.getHex(); + data2.object.intensity = this.intensity; + if (this.groundColor !== undefined) + data2.object.groundColor = this.groundColor.getHex(); + if (this.distance !== undefined) + data2.object.distance = this.distance; + if (this.angle !== undefined) + data2.object.angle = this.angle; + if (this.decay !== undefined) + data2.object.decay = this.decay; + if (this.penumbra !== undefined) + data2.object.penumbra = this.penumbra; + if (this.shadow !== undefined) + data2.object.shadow = this.shadow.toJSON(); + if (this.target !== undefined) + data2.object.target = this.target.uuid; + return data2; + } + } + + class HemisphereLight2 extends Light2 { + constructor(skyColor, groundColor, intensity) { + super(skyColor, intensity); + this.isHemisphereLight = true; + this.type = "HemisphereLight"; + this.position.copy(Object3D2.DEFAULT_UP); + this.updateMatrix(); + this.groundColor = new Color2(groundColor); + } + copy(source, recursive) { + super.copy(source, recursive); + this.groundColor.copy(source.groundColor); + return this; + } + } + var _projScreenMatrix$12 = /* @__PURE__ */ new Matrix42; + var _lightPositionWorld$12 = /* @__PURE__ */ new Vector32; + var _lookTarget$12 = /* @__PURE__ */ new Vector32; + + class LightShadow2 { + constructor(camera) { + this.camera = camera; + this.intensity = 1; + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; + this.mapSize = new Vector22(512, 512); + this.map = null; + this.mapPass = null; + this.matrix = new Matrix42; + this.autoUpdate = true; + this.needsUpdate = false; + this._frustum = new Frustum2; + this._frameExtents = new Vector22(1, 1); + this._viewportCount = 1; + this._viewports = [ + new Vector42(0, 0, 1, 1) + ]; + } + getViewportCount() { + return this._viewportCount; + } + getFrustum() { + return this._frustum; + } + updateMatrices(light) { + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; + _lightPositionWorld$12.setFromMatrixPosition(light.matrixWorld); + shadowCamera.position.copy(_lightPositionWorld$12); + _lookTarget$12.setFromMatrixPosition(light.target.matrixWorld); + shadowCamera.lookAt(_lookTarget$12); + shadowCamera.updateMatrixWorld(); + _projScreenMatrix$12.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix$12); + shadowMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + shadowMatrix.multiply(_projScreenMatrix$12); + } + getViewport(viewportIndex) { + return this._viewports[viewportIndex]; + } + getFrameExtents() { + return this._frameExtents; + } + dispose() { + if (this.map) { + this.map.dispose(); + } + if (this.mapPass) { + this.mapPass.dispose(); + } + } + copy(source) { + this.camera = source.camera.clone(); + this.intensity = source.intensity; + this.bias = source.bias; + this.radius = source.radius; + this.mapSize.copy(source.mapSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + toJSON() { + const object = {}; + if (this.intensity !== 1) + object.intensity = this.intensity; + if (this.bias !== 0) + object.bias = this.bias; + if (this.normalBias !== 0) + object.normalBias = this.normalBias; + if (this.radius !== 1) + object.radius = this.radius; + if (this.mapSize.x !== 512 || this.mapSize.y !== 512) + object.mapSize = this.mapSize.toArray(); + object.camera = this.camera.toJSON(false).object; + delete object.camera.matrix; + return object; + } + } + + class SpotLightShadow2 extends LightShadow2 { + constructor() { + super(new PerspectiveCamera2(50, 1, 0.5, 500)); + this.isSpotLightShadow = true; + this.focus = 1; + } + updateMatrices(light) { + const camera = this.camera; + const fov3 = RAD2DEG2 * 2 * light.angle * this.focus; + const aspect3 = this.mapSize.width / this.mapSize.height; + const far = light.distance || camera.far; + if (fov3 !== camera.fov || aspect3 !== camera.aspect || far !== camera.far) { + camera.fov = fov3; + camera.aspect = aspect3; + camera.far = far; + camera.updateProjectionMatrix(); + } + super.updateMatrices(light); + } + copy(source) { + super.copy(source); + this.focus = source.focus; + return this; + } + } + + class SpotLight2 extends Light2 { + constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2) { + super(color, intensity); + this.isSpotLight = true; + this.type = "SpotLight"; + this.position.copy(Object3D2.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D2; + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; + this.map = null; + this.shadow = new SpotLightShadow2; + } + get power() { + return this.intensity * Math.PI; + } + set power(power) { + this.intensity = power / Math.PI; + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } + } + var _projScreenMatrix2 = /* @__PURE__ */ new Matrix42; + var _lightPositionWorld2 = /* @__PURE__ */ new Vector32; + var _lookTarget2 = /* @__PURE__ */ new Vector32; + + class PointLightShadow2 extends LightShadow2 { + constructor() { + super(new PerspectiveCamera2(90, 1, 0.5, 500)); + this.isPointLightShadow = true; + this._frameExtents = new Vector22(4, 2); + this._viewportCount = 6; + this._viewports = [ + new Vector42(2, 1, 1, 1), + new Vector42(0, 1, 1, 1), + new Vector42(3, 1, 1, 1), + new Vector42(1, 1, 1, 1), + new Vector42(3, 0, 1, 1), + new Vector42(1, 0, 1, 1) + ]; + this._cubeDirections = [ + new Vector32(1, 0, 0), + new Vector32(-1, 0, 0), + new Vector32(0, 0, 1), + new Vector32(0, 0, -1), + new Vector32(0, 1, 0), + new Vector32(0, -1, 0) + ]; + this._cubeUps = [ + new Vector32(0, 1, 0), + new Vector32(0, 1, 0), + new Vector32(0, 1, 0), + new Vector32(0, 1, 0), + new Vector32(0, 0, 1), + new Vector32(0, 0, -1) + ]; + } + updateMatrices(light, viewportIndex = 0) { + const camera = this.camera; + const shadowMatrix = this.matrix; + const far = light.distance || camera.far; + if (far !== camera.far) { + camera.far = far; + camera.updateProjectionMatrix(); + } + _lightPositionWorld2.setFromMatrixPosition(light.matrixWorld); + camera.position.copy(_lightPositionWorld2); + _lookTarget2.copy(camera.position); + _lookTarget2.add(this._cubeDirections[viewportIndex]); + camera.up.copy(this._cubeUps[viewportIndex]); + camera.lookAt(_lookTarget2); + camera.updateMatrixWorld(); + shadowMatrix.makeTranslation(-_lightPositionWorld2.x, -_lightPositionWorld2.y, -_lightPositionWorld2.z); + _projScreenMatrix2.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix2); + } + } + + class PointLight2 extends Light2 { + constructor(color, intensity, distance = 0, decay = 2) { + super(color, intensity); + this.isPointLight = true; + this.type = "PointLight"; + this.distance = distance; + this.decay = decay; + this.shadow = new PointLightShadow2; + } + get power() { + return this.intensity * 4 * Math.PI; + } + set power(power) { + this.intensity = power / (4 * Math.PI); + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.decay = source.decay; + this.shadow = source.shadow.clone(); + return this; + } + } + + class OrthographicCamera2 extends Camera2 { + constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) { + super(); + this.isOrthographicCamera = true; + this.type = "OrthographicCamera"; + this.zoom = 1; + this.view = null; + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + this.near = near; + this.far = far; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign({}, source.view); + return this; + } + setViewOffset(fullWidth, fullHeight, x2, y, width2, height2) { + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x2; + this.view.offsetY = y; + this.view.width = width2; + this.view.height = height2; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const dx = (this.right - this.left) / (2 * this.zoom); + const dy = (this.top - this.bottom) / (2 * this.zoom); + const cx = (this.right + this.left) / 2; + const cy = (this.top + this.bottom) / 2; + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + if (this.view !== null && this.view.enabled) { + const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom; + const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom; + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + } + this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + data2.object.zoom = this.zoom; + data2.object.left = this.left; + data2.object.right = this.right; + data2.object.top = this.top; + data2.object.bottom = this.bottom; + data2.object.near = this.near; + data2.object.far = this.far; + if (this.view !== null) + data2.object.view = Object.assign({}, this.view); + return data2; + } + } + + class DirectionalLightShadow2 extends LightShadow2 { + constructor() { + super(new OrthographicCamera2(-5, 5, 5, -5, 0.5, 500)); + this.isDirectionalLightShadow = true; + } + } + + class DirectionalLight2 extends Light2 { + constructor(color, intensity) { + super(color, intensity); + this.isDirectionalLight = true; + this.type = "DirectionalLight"; + this.position.copy(Object3D2.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D2; + this.shadow = new DirectionalLightShadow2; + } + dispose() { + this.shadow.dispose(); + } + copy(source) { + super.copy(source); + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } + } + + class AmbientLight2 extends Light2 { + constructor(color, intensity) { + super(color, intensity); + this.isAmbientLight = true; + this.type = "AmbientLight"; + } + } + + class RectAreaLight2 extends Light2 { + constructor(color, intensity, width2 = 10, height2 = 10) { + super(color, intensity); + this.isRectAreaLight = true; + this.type = "RectAreaLight"; + this.width = width2; + this.height = height2; + } + get power() { + return this.intensity * this.width * this.height * Math.PI; + } + set power(power) { + this.intensity = power / (this.width * this.height * Math.PI); + } + copy(source) { + super.copy(source); + this.width = source.width; + this.height = source.height; + return this; + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + data2.object.width = this.width; + data2.object.height = this.height; + return data2; + } + } + + class SphericalHarmonics32 { + constructor() { + this.isSphericalHarmonics3 = true; + this.coefficients = []; + for (let i = 0;i < 9; i++) { + this.coefficients.push(new Vector32); + } + } + set(coefficients) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].copy(coefficients[i]); + } + return this; + } + zero() { + for (let i = 0;i < 9; i++) { + this.coefficients[i].set(0, 0, 0); + } + return this; + } + getAt(normal, target) { + const { x: x2, y, z } = normal; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.282095); + target.addScaledVector(coeff[1], 0.488603 * y); + target.addScaledVector(coeff[2], 0.488603 * z); + target.addScaledVector(coeff[3], 0.488603 * x2); + target.addScaledVector(coeff[4], 1.092548 * (x2 * y)); + target.addScaledVector(coeff[5], 1.092548 * (y * z)); + target.addScaledVector(coeff[6], 0.315392 * (3 * z * z - 1)); + target.addScaledVector(coeff[7], 1.092548 * (x2 * z)); + target.addScaledVector(coeff[8], 0.546274 * (x2 * x2 - y * y)); + return target; + } + getIrradianceAt(normal, target) { + const { x: x2, y, z } = normal; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.886227); + target.addScaledVector(coeff[1], 2 * 0.511664 * y); + target.addScaledVector(coeff[2], 2 * 0.511664 * z); + target.addScaledVector(coeff[3], 2 * 0.511664 * x2); + target.addScaledVector(coeff[4], 2 * 0.429043 * x2 * y); + target.addScaledVector(coeff[5], 2 * 0.429043 * y * z); + target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); + target.addScaledVector(coeff[7], 2 * 0.429043 * x2 * z); + target.addScaledVector(coeff[8], 0.429043 * (x2 * x2 - y * y)); + return target; + } + add(sh) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].add(sh.coefficients[i]); + } + return this; + } + addScaledSH(sh, s) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].addScaledVector(sh.coefficients[i], s); + } + return this; + } + scale(s) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].multiplyScalar(s); + } + return this; + } + lerp(sh, alpha) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].lerp(sh.coefficients[i], alpha); + } + return this; + } + equals(sh) { + for (let i = 0;i < 9; i++) { + if (!this.coefficients[i].equals(sh.coefficients[i])) { + return false; + } + } + return true; + } + copy(sh) { + return this.set(sh.coefficients); + } + clone() { + return new this.constructor().copy(this); + } + fromArray(array, offset = 0) { + const coefficients = this.coefficients; + for (let i = 0;i < 9; i++) { + coefficients[i].fromArray(array, offset + i * 3); + } + return this; + } + toArray(array = [], offset = 0) { + const coefficients = this.coefficients; + for (let i = 0;i < 9; i++) { + coefficients[i].toArray(array, offset + i * 3); + } + return array; + } + static getBasisAt(normal, shBasis) { + const { x: x2, y, z } = normal; + shBasis[0] = 0.282095; + shBasis[1] = 0.488603 * y; + shBasis[2] = 0.488603 * z; + shBasis[3] = 0.488603 * x2; + shBasis[4] = 1.092548 * x2 * y; + shBasis[5] = 1.092548 * y * z; + shBasis[6] = 0.315392 * (3 * z * z - 1); + shBasis[7] = 1.092548 * x2 * z; + shBasis[8] = 0.546274 * (x2 * x2 - y * y); + } + } + + class LightProbe2 extends Light2 { + constructor(sh = new SphericalHarmonics32, intensity = 1) { + super(undefined, intensity); + this.isLightProbe = true; + this.sh = sh; + } + copy(source) { + super.copy(source); + this.sh.copy(source.sh); + return this; + } + fromJSON(json) { + this.intensity = json.intensity; + this.sh.fromArray(json.sh); + return this; + } + toJSON(meta2) { + const data2 = super.toJSON(meta2); + data2.object.sh = this.sh.toArray(); + return data2; + } + } + + class MaterialLoader2 extends Loader2 { + constructor(manager) { + super(manager); + this.textures = {}; + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader2(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const textures = this.textures; + function getTexture(name2) { + if (textures[name2] === undefined) { + console.warn("THREE.MaterialLoader: Undefined texture", name2); + } + return textures[name2]; + } + const material = this.createMaterialFromType(json.type); + if (json.uuid !== undefined) + material.uuid = json.uuid; + if (json.name !== undefined) + material.name = json.name; + if (json.color !== undefined && material.color !== undefined) + material.color.setHex(json.color); + if (json.roughness !== undefined) + material.roughness = json.roughness; + if (json.metalness !== undefined) + material.metalness = json.metalness; + if (json.sheen !== undefined) + material.sheen = json.sheen; + if (json.sheenColor !== undefined) + material.sheenColor = new Color2().setHex(json.sheenColor); + if (json.sheenRoughness !== undefined) + material.sheenRoughness = json.sheenRoughness; + if (json.emissive !== undefined && material.emissive !== undefined) + material.emissive.setHex(json.emissive); + if (json.specular !== undefined && material.specular !== undefined) + material.specular.setHex(json.specular); + if (json.specularIntensity !== undefined) + material.specularIntensity = json.specularIntensity; + if (json.specularColor !== undefined && material.specularColor !== undefined) + material.specularColor.setHex(json.specularColor); + if (json.shininess !== undefined) + material.shininess = json.shininess; + if (json.clearcoat !== undefined) + material.clearcoat = json.clearcoat; + if (json.clearcoatRoughness !== undefined) + material.clearcoatRoughness = json.clearcoatRoughness; + if (json.dispersion !== undefined) + material.dispersion = json.dispersion; + if (json.iridescence !== undefined) + material.iridescence = json.iridescence; + if (json.iridescenceIOR !== undefined) + material.iridescenceIOR = json.iridescenceIOR; + if (json.iridescenceThicknessRange !== undefined) + material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if (json.transmission !== undefined) + material.transmission = json.transmission; + if (json.thickness !== undefined) + material.thickness = json.thickness; + if (json.attenuationDistance !== undefined) + material.attenuationDistance = json.attenuationDistance; + if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) + material.attenuationColor.setHex(json.attenuationColor); + if (json.anisotropy !== undefined) + material.anisotropy = json.anisotropy; + if (json.anisotropyRotation !== undefined) + material.anisotropyRotation = json.anisotropyRotation; + if (json.fog !== undefined) + material.fog = json.fog; + if (json.flatShading !== undefined) + material.flatShading = json.flatShading; + if (json.blending !== undefined) + material.blending = json.blending; + if (json.combine !== undefined) + material.combine = json.combine; + if (json.side !== undefined) + material.side = json.side; + if (json.shadowSide !== undefined) + material.shadowSide = json.shadowSide; + if (json.opacity !== undefined) + material.opacity = json.opacity; + if (json.transparent !== undefined) + material.transparent = json.transparent; + if (json.alphaTest !== undefined) + material.alphaTest = json.alphaTest; + if (json.alphaHash !== undefined) + material.alphaHash = json.alphaHash; + if (json.depthFunc !== undefined) + material.depthFunc = json.depthFunc; + if (json.depthTest !== undefined) + material.depthTest = json.depthTest; + if (json.depthWrite !== undefined) + material.depthWrite = json.depthWrite; + if (json.colorWrite !== undefined) + material.colorWrite = json.colorWrite; + if (json.blendSrc !== undefined) + material.blendSrc = json.blendSrc; + if (json.blendDst !== undefined) + material.blendDst = json.blendDst; + if (json.blendEquation !== undefined) + material.blendEquation = json.blendEquation; + if (json.blendSrcAlpha !== undefined) + material.blendSrcAlpha = json.blendSrcAlpha; + if (json.blendDstAlpha !== undefined) + material.blendDstAlpha = json.blendDstAlpha; + if (json.blendEquationAlpha !== undefined) + material.blendEquationAlpha = json.blendEquationAlpha; + if (json.blendColor !== undefined && material.blendColor !== undefined) + material.blendColor.setHex(json.blendColor); + if (json.blendAlpha !== undefined) + material.blendAlpha = json.blendAlpha; + if (json.stencilWriteMask !== undefined) + material.stencilWriteMask = json.stencilWriteMask; + if (json.stencilFunc !== undefined) + material.stencilFunc = json.stencilFunc; + if (json.stencilRef !== undefined) + material.stencilRef = json.stencilRef; + if (json.stencilFuncMask !== undefined) + material.stencilFuncMask = json.stencilFuncMask; + if (json.stencilFail !== undefined) + material.stencilFail = json.stencilFail; + if (json.stencilZFail !== undefined) + material.stencilZFail = json.stencilZFail; + if (json.stencilZPass !== undefined) + material.stencilZPass = json.stencilZPass; + if (json.stencilWrite !== undefined) + material.stencilWrite = json.stencilWrite; + if (json.wireframe !== undefined) + material.wireframe = json.wireframe; + if (json.wireframeLinewidth !== undefined) + material.wireframeLinewidth = json.wireframeLinewidth; + if (json.wireframeLinecap !== undefined) + material.wireframeLinecap = json.wireframeLinecap; + if (json.wireframeLinejoin !== undefined) + material.wireframeLinejoin = json.wireframeLinejoin; + if (json.rotation !== undefined) + material.rotation = json.rotation; + if (json.linewidth !== undefined) + material.linewidth = json.linewidth; + if (json.dashSize !== undefined) + material.dashSize = json.dashSize; + if (json.gapSize !== undefined) + material.gapSize = json.gapSize; + if (json.scale !== undefined) + material.scale = json.scale; + if (json.polygonOffset !== undefined) + material.polygonOffset = json.polygonOffset; + if (json.polygonOffsetFactor !== undefined) + material.polygonOffsetFactor = json.polygonOffsetFactor; + if (json.polygonOffsetUnits !== undefined) + material.polygonOffsetUnits = json.polygonOffsetUnits; + if (json.dithering !== undefined) + material.dithering = json.dithering; + if (json.alphaToCoverage !== undefined) + material.alphaToCoverage = json.alphaToCoverage; + if (json.premultipliedAlpha !== undefined) + material.premultipliedAlpha = json.premultipliedAlpha; + if (json.forceSinglePass !== undefined) + material.forceSinglePass = json.forceSinglePass; + if (json.visible !== undefined) + material.visible = json.visible; + if (json.toneMapped !== undefined) + material.toneMapped = json.toneMapped; + if (json.userData !== undefined) + material.userData = json.userData; + if (json.vertexColors !== undefined) { + if (typeof json.vertexColors === "number") { + material.vertexColors = json.vertexColors > 0 ? true : false; + } else { + material.vertexColors = json.vertexColors; + } + } + if (json.uniforms !== undefined) { + for (const name2 in json.uniforms) { + const uniform = json.uniforms[name2]; + material.uniforms[name2] = {}; + switch (uniform.type) { + case "t": + material.uniforms[name2].value = getTexture(uniform.value); + break; + case "c": + material.uniforms[name2].value = new Color2().setHex(uniform.value); + break; + case "v2": + material.uniforms[name2].value = new Vector22().fromArray(uniform.value); + break; + case "v3": + material.uniforms[name2].value = new Vector32().fromArray(uniform.value); + break; + case "v4": + material.uniforms[name2].value = new Vector42().fromArray(uniform.value); + break; + case "m3": + material.uniforms[name2].value = new Matrix32().fromArray(uniform.value); + break; + case "m4": + material.uniforms[name2].value = new Matrix42().fromArray(uniform.value); + break; + default: + material.uniforms[name2].value = uniform.value; + } + } + } + if (json.defines !== undefined) + material.defines = json.defines; + if (json.vertexShader !== undefined) + material.vertexShader = json.vertexShader; + if (json.fragmentShader !== undefined) + material.fragmentShader = json.fragmentShader; + if (json.glslVersion !== undefined) + material.glslVersion = json.glslVersion; + if (json.extensions !== undefined) { + for (const key2 in json.extensions) { + material.extensions[key2] = json.extensions[key2]; + } + } + if (json.lights !== undefined) + material.lights = json.lights; + if (json.clipping !== undefined) + material.clipping = json.clipping; + if (json.size !== undefined) + material.size = json.size; + if (json.sizeAttenuation !== undefined) + material.sizeAttenuation = json.sizeAttenuation; + if (json.map !== undefined) + material.map = getTexture(json.map); + if (json.matcap !== undefined) + material.matcap = getTexture(json.matcap); + if (json.alphaMap !== undefined) + material.alphaMap = getTexture(json.alphaMap); + if (json.bumpMap !== undefined) + material.bumpMap = getTexture(json.bumpMap); + if (json.bumpScale !== undefined) + material.bumpScale = json.bumpScale; + if (json.normalMap !== undefined) + material.normalMap = getTexture(json.normalMap); + if (json.normalMapType !== undefined) + material.normalMapType = json.normalMapType; + if (json.normalScale !== undefined) { + let normalScale = json.normalScale; + if (Array.isArray(normalScale) === false) { + normalScale = [normalScale, normalScale]; + } + material.normalScale = new Vector22().fromArray(normalScale); + } + if (json.displacementMap !== undefined) + material.displacementMap = getTexture(json.displacementMap); + if (json.displacementScale !== undefined) + material.displacementScale = json.displacementScale; + if (json.displacementBias !== undefined) + material.displacementBias = json.displacementBias; + if (json.roughnessMap !== undefined) + material.roughnessMap = getTexture(json.roughnessMap); + if (json.metalnessMap !== undefined) + material.metalnessMap = getTexture(json.metalnessMap); + if (json.emissiveMap !== undefined) + material.emissiveMap = getTexture(json.emissiveMap); + if (json.emissiveIntensity !== undefined) + material.emissiveIntensity = json.emissiveIntensity; + if (json.specularMap !== undefined) + material.specularMap = getTexture(json.specularMap); + if (json.specularIntensityMap !== undefined) + material.specularIntensityMap = getTexture(json.specularIntensityMap); + if (json.specularColorMap !== undefined) + material.specularColorMap = getTexture(json.specularColorMap); + if (json.envMap !== undefined) + material.envMap = getTexture(json.envMap); + if (json.envMapRotation !== undefined) + material.envMapRotation.fromArray(json.envMapRotation); + if (json.envMapIntensity !== undefined) + material.envMapIntensity = json.envMapIntensity; + if (json.reflectivity !== undefined) + material.reflectivity = json.reflectivity; + if (json.refractionRatio !== undefined) + material.refractionRatio = json.refractionRatio; + if (json.lightMap !== undefined) + material.lightMap = getTexture(json.lightMap); + if (json.lightMapIntensity !== undefined) + material.lightMapIntensity = json.lightMapIntensity; + if (json.aoMap !== undefined) + material.aoMap = getTexture(json.aoMap); + if (json.aoMapIntensity !== undefined) + material.aoMapIntensity = json.aoMapIntensity; + if (json.gradientMap !== undefined) + material.gradientMap = getTexture(json.gradientMap); + if (json.clearcoatMap !== undefined) + material.clearcoatMap = getTexture(json.clearcoatMap); + if (json.clearcoatRoughnessMap !== undefined) + material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap); + if (json.clearcoatNormalMap !== undefined) + material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap); + if (json.clearcoatNormalScale !== undefined) + material.clearcoatNormalScale = new Vector22().fromArray(json.clearcoatNormalScale); + if (json.iridescenceMap !== undefined) + material.iridescenceMap = getTexture(json.iridescenceMap); + if (json.iridescenceThicknessMap !== undefined) + material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap); + if (json.transmissionMap !== undefined) + material.transmissionMap = getTexture(json.transmissionMap); + if (json.thicknessMap !== undefined) + material.thicknessMap = getTexture(json.thicknessMap); + if (json.anisotropyMap !== undefined) + material.anisotropyMap = getTexture(json.anisotropyMap); + if (json.sheenColorMap !== undefined) + material.sheenColorMap = getTexture(json.sheenColorMap); + if (json.sheenRoughnessMap !== undefined) + material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap); + return material; + } + setTextures(value2) { + this.textures = value2; + return this; + } + createMaterialFromType(type) { + return MaterialLoader2.createMaterialFromType(type); + } + static createMaterialFromType(type) { + const materialLib = { + ShadowMaterial: ShadowMaterial2, + SpriteMaterial: SpriteMaterial2, + RawShaderMaterial: RawShaderMaterial2, + ShaderMaterial: ShaderMaterial2, + PointsMaterial: PointsMaterial2, + MeshPhysicalMaterial: MeshPhysicalMaterial2, + MeshStandardMaterial: MeshStandardMaterial2, + MeshPhongMaterial: MeshPhongMaterial2, + MeshToonMaterial: MeshToonMaterial2, + MeshNormalMaterial: MeshNormalMaterial2, + MeshLambertMaterial: MeshLambertMaterial2, + MeshDepthMaterial: MeshDepthMaterial2, + MeshDistanceMaterial: MeshDistanceMaterial2, + MeshBasicMaterial: MeshBasicMaterial2, + MeshMatcapMaterial: MeshMatcapMaterial2, + LineDashedMaterial: LineDashedMaterial2, + LineBasicMaterial: LineBasicMaterial2, + Material: Material2 + }; + return new materialLib[type]; + } + } + + class LoaderUtils2 { + static decodeText(array) { + console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."); + if (typeof TextDecoder !== "undefined") { + return new TextDecoder().decode(array); + } + let s = ""; + for (let i = 0, il = array.length;i < il; i++) { + s += String.fromCharCode(array[i]); + } + try { + return decodeURIComponent(escape(s)); + } catch (e) { + return s; + } + } + static extractUrlBase(url) { + const index2 = url.lastIndexOf("/"); + if (index2 === -1) + return "./"; + return url.slice(0, index2 + 1); + } + static resolveURL(url, path) { + if (typeof url !== "string" || url === "") + return ""; + if (/^https?:\/\//i.test(path) && /^\//.test(url)) { + path = path.replace(/(^https?:\/\/[^\/]+).*/i, "$1"); + } + if (/^(https?:)?\/\//i.test(url)) + return url; + if (/^data:.*,.*$/i.test(url)) + return url; + if (/^blob:.*$/i.test(url)) + return url; + return path + url; + } + } + + class InstancedBufferGeometry2 extends BufferGeometry2 { + constructor() { + super(); + this.isInstancedBufferGeometry = true; + this.type = "InstancedBufferGeometry"; + this.instanceCount = Infinity; + } + copy(source) { + super.copy(source); + this.instanceCount = source.instanceCount; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.instanceCount = this.instanceCount; + data2.isInstancedBufferGeometry = true; + return data2; + } + } + + class BufferGeometryLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader2(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const interleavedBufferMap = {}; + const arrayBufferMap = {}; + function getInterleavedBuffer(json2, uuid) { + if (interleavedBufferMap[uuid] !== undefined) + return interleavedBufferMap[uuid]; + const interleavedBuffers = json2.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[uuid]; + const buffer = getArrayBuffer(json2, interleavedBuffer.buffer); + const array = getTypedArray2(interleavedBuffer.type, buffer); + const ib = new InterleavedBuffer2(array, interleavedBuffer.stride); + ib.uuid = interleavedBuffer.uuid; + interleavedBufferMap[uuid] = ib; + return ib; + } + function getArrayBuffer(json2, uuid) { + if (arrayBufferMap[uuid] !== undefined) + return arrayBufferMap[uuid]; + const arrayBuffers = json2.arrayBuffers; + const arrayBuffer = arrayBuffers[uuid]; + const ab = new Uint32Array(arrayBuffer).buffer; + arrayBufferMap[uuid] = ab; + return ab; + } + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry2 : new BufferGeometry2; + const index2 = json.data.index; + if (index2 !== undefined) { + const typedArray = getTypedArray2(index2.type, index2.array); + geometry.setIndex(new BufferAttribute2(typedArray, 1)); + } + const attributes = json.data.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute2(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray2(attribute.type, attribute.array); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute2 : BufferAttribute2; + bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== undefined) + bufferAttribute.name = attribute.name; + if (attribute.usage !== undefined) + bufferAttribute.setUsage(attribute.usage); + geometry.setAttribute(key2, bufferAttribute); + } + const morphAttributes = json.data.morphAttributes; + if (morphAttributes) { + for (const key2 in morphAttributes) { + const attributeArray = morphAttributes[key2]; + const array = []; + for (let i = 0, il = attributeArray.length;i < il; i++) { + const attribute = attributeArray[i]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute2(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray2(attribute.type, attribute.array); + bufferAttribute = new BufferAttribute2(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== undefined) + bufferAttribute.name = attribute.name; + array.push(bufferAttribute); + } + geometry.morphAttributes[key2] = array; + } + } + const morphTargetsRelative = json.data.morphTargetsRelative; + if (morphTargetsRelative) { + geometry.morphTargetsRelative = true; + } + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + if (groups !== undefined) { + for (let i = 0, n2 = groups.length;i !== n2; ++i) { + const group = groups[i]; + geometry.addGroup(group.start, group.count, group.materialIndex); + } + } + const boundingSphere = json.data.boundingSphere; + if (boundingSphere !== undefined) { + const center = new Vector32; + if (boundingSphere.center !== undefined) { + center.fromArray(boundingSphere.center); + } + geometry.boundingSphere = new Sphere2(center, boundingSphere.radius); + } + if (json.name) + geometry.name = json.name; + if (json.userData) + geometry.userData = json.userData; + return geometry; + } + } + + class ObjectLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const path = this.path === "" ? LoaderUtils2.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader2(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text2) { + let json = null; + try { + json = JSON.parse(text2); + } catch (error) { + if (onError !== undefined) + onError(error); + console.error("THREE:ObjectLoader: Can't parse " + url + ".", error.message); + return; + } + const metadata = json.metadata; + if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === "geometry") { + if (onError !== undefined) + onError(new Error("THREE.ObjectLoader: Can't load " + url)); + console.error("THREE.ObjectLoader: Can't load " + url); + return; + } + scope.parse(json, onLoad); + }, onProgress, onError); + } + async loadAsync(url, onProgress) { + const scope = this; + const path = this.path === "" ? LoaderUtils2.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader2(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + const text2 = await loader.loadAsync(url, onProgress); + const json = JSON.parse(text2); + const metadata = json.metadata; + if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === "geometry") { + throw new Error("THREE.ObjectLoader: Can't load " + url); + } + return await scope.parseAsync(json); + } + parse(json, onLoad) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = this.parseImages(json.images, function() { + if (onLoad !== undefined) + onLoad(object); + }); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + if (onLoad !== undefined) { + let hasImages = false; + for (const uuid in images) { + if (images[uuid].data instanceof HTMLImageElement) { + hasImages = true; + break; + } + } + if (hasImages === false) + onLoad(object); + } + return object; + } + async parseAsync(json) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = await this.parseImagesAsync(json.images); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + return object; + } + parseShapes(json) { + const shapes = {}; + if (json !== undefined) { + for (let i = 0, l2 = json.length;i < l2; i++) { + const shape = new Shape2().fromJSON(json[i]); + shapes[shape.uuid] = shape; + } + } + return shapes; + } + parseSkeletons(json, object) { + const skeletons = {}; + const bones = {}; + object.traverse(function(child) { + if (child.isBone) + bones[child.uuid] = child; + }); + if (json !== undefined) { + for (let i = 0, l2 = json.length;i < l2; i++) { + const skeleton = new Skeleton2().fromJSON(json[i], bones); + skeletons[skeleton.uuid] = skeleton; + } + } + return skeletons; + } + parseGeometries(json, shapes) { + const geometries = {}; + if (json !== undefined) { + const bufferGeometryLoader = new BufferGeometryLoader2; + for (let i = 0, l2 = json.length;i < l2; i++) { + let geometry; + const data2 = json[i]; + switch (data2.type) { + case "BufferGeometry": + case "InstancedBufferGeometry": + geometry = bufferGeometryLoader.parse(data2); + break; + default: + if (data2.type in Geometries2) { + geometry = Geometries2[data2.type].fromJSON(data2, shapes); + } else { + console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data2.type}"`); + } + } + geometry.uuid = data2.uuid; + if (data2.name !== undefined) + geometry.name = data2.name; + if (data2.userData !== undefined) + geometry.userData = data2.userData; + geometries[data2.uuid] = geometry; + } + } + return geometries; + } + parseMaterials(json, textures) { + const cache = {}; + const materials = {}; + if (json !== undefined) { + const loader = new MaterialLoader2; + loader.setTextures(textures); + for (let i = 0, l2 = json.length;i < l2; i++) { + const data2 = json[i]; + if (cache[data2.uuid] === undefined) { + cache[data2.uuid] = loader.parse(data2); + } + materials[data2.uuid] = cache[data2.uuid]; + } + } + return materials; + } + parseAnimations(json) { + const animations = {}; + if (json !== undefined) { + for (let i = 0;i < json.length; i++) { + const data2 = json[i]; + const clip = AnimationClip2.parse(data2); + animations[clip.uuid] = clip; + } + } + return animations; + } + parseImages(json, onLoad) { + const scope = this; + const images = {}; + let loader; + function loadImage(url) { + scope.manager.itemStart(url); + return loader.load(url, function() { + scope.manager.itemEnd(url); + }, undefined, function() { + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + } + function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return loadImage(path); + } else { + if (image.data) { + return { + data: getTypedArray2(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== undefined && json.length > 0) { + const manager = new LoadingManager2(onLoad); + loader = new ImageLoader2(manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length;i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j2 = 0, jl = url.length;j2 < jl; j2++) { + const currentUrl = url[j2]; + const deserializedImage = deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture2(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source2(imageArray); + } else { + const deserializedImage = deserializeImage(image.url); + images[image.uuid] = new Source2(deserializedImage); + } + } + } + return images; + } + async parseImagesAsync(json) { + const scope = this; + const images = {}; + let loader; + async function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return await loader.loadAsync(path); + } else { + if (image.data) { + return { + data: getTypedArray2(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== undefined && json.length > 0) { + loader = new ImageLoader2(this.manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length;i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j2 = 0, jl = url.length;j2 < jl; j2++) { + const currentUrl = url[j2]; + const deserializedImage = await deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture2(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source2(imageArray); + } else { + const deserializedImage = await deserializeImage(image.url); + images[image.uuid] = new Source2(deserializedImage); + } + } + } + return images; + } + parseTextures(json, images) { + function parseConstant(value2, type) { + if (typeof value2 === "number") + return value2; + console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.", value2); + return type[value2]; + } + const textures = {}; + if (json !== undefined) { + for (let i = 0, l2 = json.length;i < l2; i++) { + const data2 = json[i]; + if (data2.image === undefined) { + console.warn('THREE.ObjectLoader: No "image" specified for', data2.uuid); + } + if (images[data2.image] === undefined) { + console.warn("THREE.ObjectLoader: Undefined image", data2.image); + } + const source = images[data2.image]; + const image = source.data; + let texture; + if (Array.isArray(image)) { + texture = new CubeTexture2; + if (image.length === 6) + texture.needsUpdate = true; + } else { + if (image && image.data) { + texture = new DataTexture2; + } else { + texture = new Texture2; + } + if (image) + texture.needsUpdate = true; + } + texture.source = source; + texture.uuid = data2.uuid; + if (data2.name !== undefined) + texture.name = data2.name; + if (data2.mapping !== undefined) + texture.mapping = parseConstant(data2.mapping, TEXTURE_MAPPING2); + if (data2.channel !== undefined) + texture.channel = data2.channel; + if (data2.offset !== undefined) + texture.offset.fromArray(data2.offset); + if (data2.repeat !== undefined) + texture.repeat.fromArray(data2.repeat); + if (data2.center !== undefined) + texture.center.fromArray(data2.center); + if (data2.rotation !== undefined) + texture.rotation = data2.rotation; + if (data2.wrap !== undefined) { + texture.wrapS = parseConstant(data2.wrap[0], TEXTURE_WRAPPING2); + texture.wrapT = parseConstant(data2.wrap[1], TEXTURE_WRAPPING2); + } + if (data2.format !== undefined) + texture.format = data2.format; + if (data2.internalFormat !== undefined) + texture.internalFormat = data2.internalFormat; + if (data2.type !== undefined) + texture.type = data2.type; + if (data2.colorSpace !== undefined) + texture.colorSpace = data2.colorSpace; + if (data2.minFilter !== undefined) + texture.minFilter = parseConstant(data2.minFilter, TEXTURE_FILTER2); + if (data2.magFilter !== undefined) + texture.magFilter = parseConstant(data2.magFilter, TEXTURE_FILTER2); + if (data2.anisotropy !== undefined) + texture.anisotropy = data2.anisotropy; + if (data2.flipY !== undefined) + texture.flipY = data2.flipY; + if (data2.generateMipmaps !== undefined) + texture.generateMipmaps = data2.generateMipmaps; + if (data2.premultiplyAlpha !== undefined) + texture.premultiplyAlpha = data2.premultiplyAlpha; + if (data2.unpackAlignment !== undefined) + texture.unpackAlignment = data2.unpackAlignment; + if (data2.compareFunction !== undefined) + texture.compareFunction = data2.compareFunction; + if (data2.userData !== undefined) + texture.userData = data2.userData; + textures[data2.uuid] = texture; + } + } + return textures; + } + parseObject(data2, geometries, materials, textures, animations) { + let object; + function getGeometry(name2) { + if (geometries[name2] === undefined) { + console.warn("THREE.ObjectLoader: Undefined geometry", name2); + } + return geometries[name2]; + } + function getMaterial(name2) { + if (name2 === undefined) + return; + if (Array.isArray(name2)) { + const array = []; + for (let i = 0, l2 = name2.length;i < l2; i++) { + const uuid = name2[i]; + if (materials[uuid] === undefined) { + console.warn("THREE.ObjectLoader: Undefined material", uuid); + } + array.push(materials[uuid]); + } + return array; + } + if (materials[name2] === undefined) { + console.warn("THREE.ObjectLoader: Undefined material", name2); + } + return materials[name2]; + } + function getTexture(uuid) { + if (textures[uuid] === undefined) { + console.warn("THREE.ObjectLoader: Undefined texture", uuid); + } + return textures[uuid]; + } + let geometry, material; + switch (data2.type) { + case "Scene": + object = new Scene2; + if (data2.background !== undefined) { + if (Number.isInteger(data2.background)) { + object.background = new Color2(data2.background); + } else { + object.background = getTexture(data2.background); + } + } + if (data2.environment !== undefined) { + object.environment = getTexture(data2.environment); + } + if (data2.fog !== undefined) { + if (data2.fog.type === "Fog") { + object.fog = new Fog2(data2.fog.color, data2.fog.near, data2.fog.far); + } else if (data2.fog.type === "FogExp2") { + object.fog = new FogExp22(data2.fog.color, data2.fog.density); + } + if (data2.fog.name !== "") { + object.fog.name = data2.fog.name; + } + } + if (data2.backgroundBlurriness !== undefined) + object.backgroundBlurriness = data2.backgroundBlurriness; + if (data2.backgroundIntensity !== undefined) + object.backgroundIntensity = data2.backgroundIntensity; + if (data2.backgroundRotation !== undefined) + object.backgroundRotation.fromArray(data2.backgroundRotation); + if (data2.environmentIntensity !== undefined) + object.environmentIntensity = data2.environmentIntensity; + if (data2.environmentRotation !== undefined) + object.environmentRotation.fromArray(data2.environmentRotation); + break; + case "PerspectiveCamera": + object = new PerspectiveCamera2(data2.fov, data2.aspect, data2.near, data2.far); + if (data2.focus !== undefined) + object.focus = data2.focus; + if (data2.zoom !== undefined) + object.zoom = data2.zoom; + if (data2.filmGauge !== undefined) + object.filmGauge = data2.filmGauge; + if (data2.filmOffset !== undefined) + object.filmOffset = data2.filmOffset; + if (data2.view !== undefined) + object.view = Object.assign({}, data2.view); + break; + case "OrthographicCamera": + object = new OrthographicCamera2(data2.left, data2.right, data2.top, data2.bottom, data2.near, data2.far); + if (data2.zoom !== undefined) + object.zoom = data2.zoom; + if (data2.view !== undefined) + object.view = Object.assign({}, data2.view); + break; + case "AmbientLight": + object = new AmbientLight2(data2.color, data2.intensity); + break; + case "DirectionalLight": + object = new DirectionalLight2(data2.color, data2.intensity); + object.target = data2.target || ""; + break; + case "PointLight": + object = new PointLight2(data2.color, data2.intensity, data2.distance, data2.decay); + break; + case "RectAreaLight": + object = new RectAreaLight2(data2.color, data2.intensity, data2.width, data2.height); + break; + case "SpotLight": + object = new SpotLight2(data2.color, data2.intensity, data2.distance, data2.angle, data2.penumbra, data2.decay); + object.target = data2.target || ""; + break; + case "HemisphereLight": + object = new HemisphereLight2(data2.color, data2.groundColor, data2.intensity); + break; + case "LightProbe": + object = new LightProbe2().fromJSON(data2); + break; + case "SkinnedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new SkinnedMesh2(geometry, material); + if (data2.bindMode !== undefined) + object.bindMode = data2.bindMode; + if (data2.bindMatrix !== undefined) + object.bindMatrix.fromArray(data2.bindMatrix); + if (data2.skeleton !== undefined) + object.skeleton = data2.skeleton; + break; + case "Mesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new Mesh2(geometry, material); + break; + case "InstancedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + const count = data2.count; + const instanceMatrix = data2.instanceMatrix; + const instanceColor = data2.instanceColor; + object = new InstancedMesh2(geometry, material, count); + object.instanceMatrix = new InstancedBufferAttribute2(new Float32Array(instanceMatrix.array), 16); + if (instanceColor !== undefined) + object.instanceColor = new InstancedBufferAttribute2(new Float32Array(instanceColor.array), instanceColor.itemSize); + break; + case "BatchedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new BatchedMesh2(data2.maxInstanceCount, data2.maxVertexCount, data2.maxIndexCount, material); + object.geometry = geometry; + object.perObjectFrustumCulled = data2.perObjectFrustumCulled; + object.sortObjects = data2.sortObjects; + object._drawRanges = data2.drawRanges; + object._reservedRanges = data2.reservedRanges; + object._visibility = data2.visibility; + object._active = data2.active; + object._bounds = data2.bounds.map((bound) => { + const box = new Box32; + box.min.fromArray(bound.boxMin); + box.max.fromArray(bound.boxMax); + const sphere = new Sphere2; + sphere.radius = bound.sphereRadius; + sphere.center.fromArray(bound.sphereCenter); + return { + boxInitialized: bound.boxInitialized, + box, + sphereInitialized: bound.sphereInitialized, + sphere + }; + }); + object._maxInstanceCount = data2.maxInstanceCount; + object._maxVertexCount = data2.maxVertexCount; + object._maxIndexCount = data2.maxIndexCount; + object._geometryInitialized = data2.geometryInitialized; + object._geometryCount = data2.geometryCount; + object._matricesTexture = getTexture(data2.matricesTexture.uuid); + if (data2.colorsTexture !== undefined) + object._colorsTexture = getTexture(data2.colorsTexture.uuid); + break; + case "LOD": + object = new LOD2; + break; + case "Line": + object = new Line4(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "LineLoop": + object = new LineLoop2(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "LineSegments": + object = new LineSegments3(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "PointCloud": + case "Points": + object = new Points2(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "Sprite": + object = new Sprite2(getMaterial(data2.material)); + break; + case "Group": + object = new Group2; + break; + case "Bone": + object = new Bone2; + break; + default: + object = new Object3D2; + } + object.uuid = data2.uuid; + if (data2.name !== undefined) + object.name = data2.name; + if (data2.matrix !== undefined) { + object.matrix.fromArray(data2.matrix); + if (data2.matrixAutoUpdate !== undefined) + object.matrixAutoUpdate = data2.matrixAutoUpdate; + if (object.matrixAutoUpdate) + object.matrix.decompose(object.position, object.quaternion, object.scale); + } else { + if (data2.position !== undefined) + object.position.fromArray(data2.position); + if (data2.rotation !== undefined) + object.rotation.fromArray(data2.rotation); + if (data2.quaternion !== undefined) + object.quaternion.fromArray(data2.quaternion); + if (data2.scale !== undefined) + object.scale.fromArray(data2.scale); + } + if (data2.up !== undefined) + object.up.fromArray(data2.up); + if (data2.castShadow !== undefined) + object.castShadow = data2.castShadow; + if (data2.receiveShadow !== undefined) + object.receiveShadow = data2.receiveShadow; + if (data2.shadow) { + if (data2.shadow.intensity !== undefined) + object.shadow.intensity = data2.shadow.intensity; + if (data2.shadow.bias !== undefined) + object.shadow.bias = data2.shadow.bias; + if (data2.shadow.normalBias !== undefined) + object.shadow.normalBias = data2.shadow.normalBias; + if (data2.shadow.radius !== undefined) + object.shadow.radius = data2.shadow.radius; + if (data2.shadow.mapSize !== undefined) + object.shadow.mapSize.fromArray(data2.shadow.mapSize); + if (data2.shadow.camera !== undefined) + object.shadow.camera = this.parseObject(data2.shadow.camera); + } + if (data2.visible !== undefined) + object.visible = data2.visible; + if (data2.frustumCulled !== undefined) + object.frustumCulled = data2.frustumCulled; + if (data2.renderOrder !== undefined) + object.renderOrder = data2.renderOrder; + if (data2.userData !== undefined) + object.userData = data2.userData; + if (data2.layers !== undefined) + object.layers.mask = data2.layers; + if (data2.children !== undefined) { + const children = data2.children; + for (let i = 0;i < children.length; i++) { + object.add(this.parseObject(children[i], geometries, materials, textures, animations)); + } + } + if (data2.animations !== undefined) { + const objectAnimations = data2.animations; + for (let i = 0;i < objectAnimations.length; i++) { + const uuid = objectAnimations[i]; + object.animations.push(animations[uuid]); + } + } + if (data2.type === "LOD") { + if (data2.autoUpdate !== undefined) + object.autoUpdate = data2.autoUpdate; + const levels = data2.levels; + for (let l2 = 0;l2 < levels.length; l2++) { + const level = levels[l2]; + const child = object.getObjectByProperty("uuid", level.object); + if (child !== undefined) { + object.addLevel(child, level.distance, level.hysteresis); + } + } + } + return object; + } + bindSkeletons(object, skeletons) { + if (Object.keys(skeletons).length === 0) + return; + object.traverse(function(child) { + if (child.isSkinnedMesh === true && child.skeleton !== undefined) { + const skeleton = skeletons[child.skeleton]; + if (skeleton === undefined) { + console.warn("THREE.ObjectLoader: No skeleton found with UUID:", child.skeleton); + } else { + child.bind(skeleton, child.bindMatrix); + } + } + }); + } + bindLightTargets(object) { + object.traverse(function(child) { + if (child.isDirectionalLight || child.isSpotLight) { + const uuid = child.target; + const target = object.getObjectByProperty("uuid", uuid); + if (target !== undefined) { + child.target = target; + } else { + child.target = new Object3D2; + } + } + }); + } + } + var TEXTURE_MAPPING2 = { + UVMapping: UVMapping2, + CubeReflectionMapping: CubeReflectionMapping2, + CubeRefractionMapping: CubeRefractionMapping2, + EquirectangularReflectionMapping: EquirectangularReflectionMapping2, + EquirectangularRefractionMapping: EquirectangularRefractionMapping2, + CubeUVReflectionMapping: CubeUVReflectionMapping2 + }; + var TEXTURE_WRAPPING2 = { + RepeatWrapping: RepeatWrapping2, + ClampToEdgeWrapping: ClampToEdgeWrapping2, + MirroredRepeatWrapping: MirroredRepeatWrapping2 + }; + var TEXTURE_FILTER2 = { + NearestFilter: NearestFilter2, + NearestMipmapNearestFilter: NearestMipmapNearestFilter2, + NearestMipmapLinearFilter: NearestMipmapLinearFilter2, + LinearFilter: LinearFilter2, + LinearMipmapNearestFilter: LinearMipmapNearestFilter2, + LinearMipmapLinearFilter: LinearMipmapLinearFilter2 + }; + + class ImageBitmapLoader2 extends Loader2 { + constructor(manager) { + super(manager); + this.isImageBitmapLoader = true; + if (typeof createImageBitmap === "undefined") { + console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."); + } + if (typeof fetch === "undefined") { + console.warn("THREE.ImageBitmapLoader: fetch() not supported."); + } + this.options = { premultiplyAlpha: "none" }; + } + setOptions(options) { + this.options = options; + return this; + } + load(url, onLoad, onProgress, onError) { + if (url === undefined) + url = ""; + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache2.get(url); + if (cached !== undefined) { + scope.manager.itemStart(url); + if (cached.then) { + cached.then((imageBitmap) => { + if (onLoad) + onLoad(imageBitmap); + scope.manager.itemEnd(url); + }).catch((e) => { + if (onError) + onError(e); + }); + return; + } + setTimeout(function() { + if (onLoad) + onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const fetchOptions = {}; + fetchOptions.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include"; + fetchOptions.headers = this.requestHeader; + const promise = fetch(url, fetchOptions).then(function(res) { + return res.blob(); + }).then(function(blob) { + return createImageBitmap(blob, Object.assign(scope.options, { colorSpaceConversion: "none" })); + }).then(function(imageBitmap) { + Cache2.add(url, imageBitmap); + if (onLoad) + onLoad(imageBitmap); + scope.manager.itemEnd(url); + return imageBitmap; + }).catch(function(e) { + if (onError) + onError(e); + Cache2.remove(url); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + Cache2.add(url, promise); + scope.manager.itemStart(url); + } + } + var _context2; + + class AudioContext2 { + static getContext() { + if (_context2 === undefined) { + _context2 = new (window.AudioContext || window.webkitAudioContext); + } + return _context2; + } + static setContext(value2) { + _context2 = value2; + } + } + + class AudioLoader2 extends Loader2 { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader2(this.manager); + loader.setResponseType("arraybuffer"); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(buffer) { + try { + const bufferCopy = buffer.slice(0); + const context = AudioContext2.getContext(); + context.decodeAudioData(bufferCopy, function(audioBuffer) { + onLoad(audioBuffer); + }).catch(handleError); + } catch (e) { + handleError(e); + } + }, onProgress, onError); + function handleError(e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + } + } + var _eyeRight2 = /* @__PURE__ */ new Matrix42; + var _eyeLeft2 = /* @__PURE__ */ new Matrix42; + var _projectionMatrix2 = /* @__PURE__ */ new Matrix42; + + class StereoCamera2 { + constructor() { + this.type = "StereoCamera"; + this.aspect = 1; + this.eyeSep = 0.064; + this.cameraL = new PerspectiveCamera2; + this.cameraL.layers.enable(1); + this.cameraL.matrixAutoUpdate = false; + this.cameraR = new PerspectiveCamera2; + this.cameraR.layers.enable(2); + this.cameraR.matrixAutoUpdate = false; + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; + } + update(camera) { + const cache = this._cache; + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + if (needsUpdate) { + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; + _projectionMatrix2.copy(camera.projectionMatrix); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = cache.near * Math.tan(DEG2RAD2 * cache.fov * 0.5) / cache.zoom; + let xmin, xmax; + _eyeLeft2.elements[12] = -eyeSepHalf; + _eyeRight2.elements[12] = eyeSepHalf; + xmin = -ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; + _projectionMatrix2.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix2.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraL.projectionMatrix.copy(_projectionMatrix2); + xmin = -ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + _projectionMatrix2.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix2.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraR.projectionMatrix.copy(_projectionMatrix2); + } + this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft2); + this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight2); + } + } + + class ArrayCamera2 extends PerspectiveCamera2 { + constructor(array = []) { + super(); + this.isArrayCamera = true; + this.cameras = array; + this.index = 0; + } + } + + class Clock2 { + constructor(autoStart = true) { + this.autoStart = autoStart; + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; + this.running = false; + } + start() { + this.startTime = now2(); + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + } + stop() { + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + } + getElapsedTime() { + this.getDelta(); + return this.elapsedTime; + } + getDelta() { + let diff = 0; + if (this.autoStart && !this.running) { + this.start(); + return 0; + } + if (this.running) { + const newTime = now2(); + diff = (newTime - this.oldTime) / 1000; + this.oldTime = newTime; + this.elapsedTime += diff; + } + return diff; + } + } + function now2() { + return performance.now(); + } + var _position$12 = /* @__PURE__ */ new Vector32; + var _quaternion$12 = /* @__PURE__ */ new Quaternion2; + var _scale$12 = /* @__PURE__ */ new Vector32; + var _orientation$12 = /* @__PURE__ */ new Vector32; + + class AudioListener2 extends Object3D2 { + constructor() { + super(); + this.type = "AudioListener"; + this.context = AudioContext2.getContext(); + this.gain = this.context.createGain(); + this.gain.connect(this.context.destination); + this.filter = null; + this.timeDelta = 0; + this._clock = new Clock2; + } + getInput() { + return this.gain; + } + removeFilter() { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + this.gain.connect(this.context.destination); + this.filter = null; + } + return this; + } + getFilter() { + return this.filter; + } + setFilter(value2) { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + } else { + this.gain.disconnect(this.context.destination); + } + this.filter = value2; + this.gain.connect(this.filter); + this.filter.connect(this.context.destination); + return this; + } + getMasterVolume() { + return this.gain.gain.value; + } + setMasterVolume(value2) { + this.gain.gain.setTargetAtTime(value2, this.context.currentTime, 0.01); + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + const listener = this.context.listener; + const up = this.up; + this.timeDelta = this._clock.getDelta(); + this.matrixWorld.decompose(_position$12, _quaternion$12, _scale$12); + _orientation$12.set(0, 0, -1).applyQuaternion(_quaternion$12); + if (listener.positionX) { + const endTime = this.context.currentTime + this.timeDelta; + listener.positionX.linearRampToValueAtTime(_position$12.x, endTime); + listener.positionY.linearRampToValueAtTime(_position$12.y, endTime); + listener.positionZ.linearRampToValueAtTime(_position$12.z, endTime); + listener.forwardX.linearRampToValueAtTime(_orientation$12.x, endTime); + listener.forwardY.linearRampToValueAtTime(_orientation$12.y, endTime); + listener.forwardZ.linearRampToValueAtTime(_orientation$12.z, endTime); + listener.upX.linearRampToValueAtTime(up.x, endTime); + listener.upY.linearRampToValueAtTime(up.y, endTime); + listener.upZ.linearRampToValueAtTime(up.z, endTime); + } else { + listener.setPosition(_position$12.x, _position$12.y, _position$12.z); + listener.setOrientation(_orientation$12.x, _orientation$12.y, _orientation$12.z, up.x, up.y, up.z); + } + } + } + + class Audio2 extends Object3D2 { + constructor(listener) { + super(); + this.type = "Audio"; + this.listener = listener; + this.context = listener.context; + this.gain = this.context.createGain(); + this.gain.connect(listener.getInput()); + this.autoplay = false; + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = undefined; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = "empty"; + this._startedAt = 0; + this._progress = 0; + this._connected = false; + this.filters = []; + } + getOutput() { + return this.gain; + } + setNodeSource(audioNode) { + this.hasPlaybackControl = false; + this.sourceType = "audioNode"; + this.source = audioNode; + this.connect(); + return this; + } + setMediaElementSource(mediaElement) { + this.hasPlaybackControl = false; + this.sourceType = "mediaNode"; + this.source = this.context.createMediaElementSource(mediaElement); + this.connect(); + return this; + } + setMediaStreamSource(mediaStream) { + this.hasPlaybackControl = false; + this.sourceType = "mediaStreamNode"; + this.source = this.context.createMediaStreamSource(mediaStream); + this.connect(); + return this; + } + setBuffer(audioBuffer) { + this.buffer = audioBuffer; + this.sourceType = "buffer"; + if (this.autoplay) + this.play(); + return this; + } + play(delay = 0) { + if (this.isPlaying === true) { + console.warn("THREE.Audio: Audio is already playing."); + return; + } + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._startedAt = this.context.currentTime + delay; + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind(this); + source.start(this._startedAt, this._progress + this.offset, this.duration); + this.isPlaying = true; + this.source = source; + this.setDetune(this.detune); + this.setPlaybackRate(this.playbackRate); + return this.connect(); + } + pause() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + if (this.isPlaying === true) { + this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate; + if (this.loop === true) { + this._progress = this._progress % (this.duration || this.buffer.duration); + } + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; + } + return this; + } + stop(delay = 0) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._progress = 0; + if (this.source !== null) { + this.source.stop(this.context.currentTime + delay); + this.source.onended = null; + } + this.isPlaying = false; + return this; + } + connect() { + if (this.filters.length > 0) { + this.source.connect(this.filters[0]); + for (let i = 1, l2 = this.filters.length;i < l2; i++) { + this.filters[i - 1].connect(this.filters[i]); + } + this.filters[this.filters.length - 1].connect(this.getOutput()); + } else { + this.source.connect(this.getOutput()); + } + this._connected = true; + return this; + } + disconnect() { + if (this._connected === false) { + return; + } + if (this.filters.length > 0) { + this.source.disconnect(this.filters[0]); + for (let i = 1, l2 = this.filters.length;i < l2; i++) { + this.filters[i - 1].disconnect(this.filters[i]); + } + this.filters[this.filters.length - 1].disconnect(this.getOutput()); + } else { + this.source.disconnect(this.getOutput()); + } + this._connected = false; + return this; + } + getFilters() { + return this.filters; + } + setFilters(value2) { + if (!value2) + value2 = []; + if (this._connected === true) { + this.disconnect(); + this.filters = value2.slice(); + this.connect(); + } else { + this.filters = value2.slice(); + } + return this; + } + setDetune(value2) { + this.detune = value2; + if (this.isPlaying === true && this.source.detune !== undefined) { + this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01); + } + return this; + } + getDetune() { + return this.detune; + } + getFilter() { + return this.getFilters()[0]; + } + setFilter(filter2) { + return this.setFilters(filter2 ? [filter2] : []); + } + setPlaybackRate(value2) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.playbackRate = value2; + if (this.isPlaying === true) { + this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01); + } + return this; + } + getPlaybackRate() { + return this.playbackRate; + } + onEnded() { + this.isPlaying = false; + this._progress = 0; + } + getLoop() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return false; + } + return this.loop; + } + setLoop(value2) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.loop = value2; + if (this.isPlaying === true) { + this.source.loop = this.loop; + } + return this; + } + setLoopStart(value2) { + this.loopStart = value2; + return this; + } + setLoopEnd(value2) { + this.loopEnd = value2; + return this; + } + getVolume() { + return this.gain.gain.value; + } + setVolume(value2) { + this.gain.gain.setTargetAtTime(value2, this.context.currentTime, 0.01); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.sourceType !== "buffer") { + console.warn("THREE.Audio: Audio source type cannot be copied."); + return this; + } + this.autoplay = source.autoplay; + this.buffer = source.buffer; + this.detune = source.detune; + this.loop = source.loop; + this.loopStart = source.loopStart; + this.loopEnd = source.loopEnd; + this.offset = source.offset; + this.duration = source.duration; + this.playbackRate = source.playbackRate; + this.hasPlaybackControl = source.hasPlaybackControl; + this.sourceType = source.sourceType; + this.filters = source.filters.slice(); + return this; + } + clone(recursive) { + return new this.constructor(this.listener).copy(this, recursive); + } + } + var _position3 = /* @__PURE__ */ new Vector32; + var _quaternion5 = /* @__PURE__ */ new Quaternion2; + var _scale5 = /* @__PURE__ */ new Vector32; + var _orientation2 = /* @__PURE__ */ new Vector32; + + class PositionalAudio2 extends Audio2 { + constructor(listener) { + super(listener); + this.panner = this.context.createPanner(); + this.panner.panningModel = "HRTF"; + this.panner.connect(this.gain); + } + connect() { + super.connect(); + this.panner.connect(this.gain); + } + disconnect() { + super.disconnect(); + this.panner.disconnect(this.gain); + } + getOutput() { + return this.panner; + } + getRefDistance() { + return this.panner.refDistance; + } + setRefDistance(value2) { + this.panner.refDistance = value2; + return this; + } + getRolloffFactor() { + return this.panner.rolloffFactor; + } + setRolloffFactor(value2) { + this.panner.rolloffFactor = value2; + return this; + } + getDistanceModel() { + return this.panner.distanceModel; + } + setDistanceModel(value2) { + this.panner.distanceModel = value2; + return this; + } + getMaxDistance() { + return this.panner.maxDistance; + } + setMaxDistance(value2) { + this.panner.maxDistance = value2; + return this; + } + setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) { + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.hasPlaybackControl === true && this.isPlaying === false) + return; + this.matrixWorld.decompose(_position3, _quaternion5, _scale5); + _orientation2.set(0, 0, 1).applyQuaternion(_quaternion5); + const panner = this.panner; + if (panner.positionX) { + const endTime = this.context.currentTime + this.listener.timeDelta; + panner.positionX.linearRampToValueAtTime(_position3.x, endTime); + panner.positionY.linearRampToValueAtTime(_position3.y, endTime); + panner.positionZ.linearRampToValueAtTime(_position3.z, endTime); + panner.orientationX.linearRampToValueAtTime(_orientation2.x, endTime); + panner.orientationY.linearRampToValueAtTime(_orientation2.y, endTime); + panner.orientationZ.linearRampToValueAtTime(_orientation2.z, endTime); + } else { + panner.setPosition(_position3.x, _position3.y, _position3.z); + panner.setOrientation(_orientation2.x, _orientation2.y, _orientation2.z); + } + } + } + + class AudioAnalyser2 { + constructor(audio, fftSize = 2048) { + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; + this.data = new Uint8Array(this.analyser.frequencyBinCount); + audio.getOutput().connect(this.analyser); + } + getFrequencyData() { + this.analyser.getByteFrequencyData(this.data); + return this.data; + } + getAverageFrequency() { + let value2 = 0; + const data2 = this.getFrequencyData(); + for (let i = 0;i < data2.length; i++) { + value2 += data2[i]; + } + return value2 / data2.length; + } + } + + class PropertyMixer2 { + constructor(binding, typeName, valueSize) { + this.binding = binding; + this.valueSize = valueSize; + let mixFunction, mixFunctionAdditive, setIdentity; + switch (typeName) { + case "quaternion": + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; + this.buffer = new Float64Array(valueSize * 6); + this._workIndex = 5; + break; + case "string": + case "bool": + mixFunction = this._select; + mixFunctionAdditive = this._select; + setIdentity = this._setAdditiveIdentityOther; + this.buffer = new Array(valueSize * 5); + break; + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; + this.buffer = new Float64Array(valueSize * 5); + } + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + this.useCount = 0; + this.referenceCount = 0; + } + accumulate(accuIndex, weight) { + const buffer = this.buffer, stride = this.valueSize, offset = accuIndex * stride + stride; + let currentWeight = this.cumulativeWeight; + if (currentWeight === 0) { + for (let i = 0;i !== stride; ++i) { + buffer[offset + i] = buffer[i]; + } + currentWeight = weight; + } else { + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion(buffer, offset, 0, mix, stride); + } + this.cumulativeWeight = currentWeight; + } + accumulateAdditive(weight) { + const buffer = this.buffer, stride = this.valueSize, offset = stride * this._addIndex; + if (this.cumulativeWeightAdditive === 0) { + this._setIdentity(); + } + this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride); + this.cumulativeWeightAdditive += weight; + } + apply(accuIndex) { + const stride = this.valueSize, buffer = this.buffer, offset = accuIndex * stride + stride, weight = this.cumulativeWeight, weightAdditive = this.cumulativeWeightAdditive, binding = this.binding; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + if (weight < 1) { + const originalValueOffset = stride * this._origIndex; + this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride); + } + if (weightAdditive > 0) { + this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride); + } + for (let i = stride, e = stride + stride;i !== e; ++i) { + if (buffer[i] !== buffer[i + stride]) { + binding.setValue(buffer, offset); + break; + } + } + } + saveOriginalState() { + const binding = this.binding; + const buffer = this.buffer, stride = this.valueSize, originalValueOffset = stride * this._origIndex; + binding.getValue(buffer, originalValueOffset); + for (let i = stride, e = originalValueOffset;i !== e; ++i) { + buffer[i] = buffer[originalValueOffset + i % stride]; + } + this._setIdentity(); + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + } + restoreOriginalState() { + const originalValueOffset = this.valueSize * 3; + this.binding.setValue(this.buffer, originalValueOffset); + } + _setAdditiveIdentityNumeric() { + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; + for (let i = startIndex;i < endIndex; i++) { + this.buffer[i] = 0; + } + } + _setAdditiveIdentityQuaternion() { + this._setAdditiveIdentityNumeric(); + this.buffer[this._addIndex * this.valueSize + 3] = 1; + } + _setAdditiveIdentityOther() { + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; + for (let i = 0;i < this.valueSize; i++) { + this.buffer[targetIndex + i] = this.buffer[startIndex + i]; + } + } + _select(buffer, dstOffset, srcOffset, t3, stride) { + if (t3 >= 0.5) { + for (let i = 0;i !== stride; ++i) { + buffer[dstOffset + i] = buffer[srcOffset + i]; + } + } + } + _slerp(buffer, dstOffset, srcOffset, t3) { + Quaternion2.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t3); + } + _slerpAdditive(buffer, dstOffset, srcOffset, t3, stride) { + const workOffset = this._workIndex * stride; + Quaternion2.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); + Quaternion2.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t3); + } + _lerp(buffer, dstOffset, srcOffset, t3, stride) { + const s = 1 - t3; + for (let i = 0;i !== stride; ++i) { + const j2 = dstOffset + i; + buffer[j2] = buffer[j2] * s + buffer[srcOffset + i] * t3; + } + } + _lerpAdditive(buffer, dstOffset, srcOffset, t3, stride) { + for (let i = 0;i !== stride; ++i) { + const j2 = dstOffset + i; + buffer[j2] = buffer[j2] + buffer[srcOffset + i] * t3; + } + } + } + var _RESERVED_CHARS_RE2 = "\\[\\]\\.:\\/"; + var _reservedRe2 = new RegExp("[" + _RESERVED_CHARS_RE2 + "]", "g"); + var _wordChar2 = "[^" + _RESERVED_CHARS_RE2 + "]"; + var _wordCharOrDot2 = "[^" + _RESERVED_CHARS_RE2.replace("\\.", "") + "]"; + var _directoryRe2 = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", _wordChar2); + var _nodeRe2 = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", _wordCharOrDot2); + var _objectRe2 = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", _wordChar2); + var _propertyRe2 = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", _wordChar2); + var _trackRe2 = new RegExp("" + "^" + _directoryRe2 + _nodeRe2 + _objectRe2 + _propertyRe2 + "$"); + var _supportedObjectNames2 = ["material", "materials", "bones", "map"]; + + class Composite2 { + constructor(targetGroup, path, optionalParsedPath) { + const parsedPath = optionalParsedPath || PropertyBinding2.parseTrackName(path); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_(path, parsedPath); + } + getValue(array, offset) { + this.bind(); + const firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[firstValidIndex]; + if (binding !== undefined) + binding.getValue(array, offset); + } + setValue(array, offset) { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n2 = bindings.length;i !== n2; ++i) { + bindings[i].setValue(array, offset); + } + } + bind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n2 = bindings.length;i !== n2; ++i) { + bindings[i].bind(); + } + } + unbind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n2 = bindings.length;i !== n2; ++i) { + bindings[i].unbind(); + } + } + } + + class PropertyBinding2 { + constructor(rootNode, path, parsedPath) { + this.path = path; + this.parsedPath = parsedPath || PropertyBinding2.parseTrackName(path); + this.node = PropertyBinding2.findNode(rootNode, this.parsedPath.nodeName); + this.rootNode = rootNode; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + static create(root2, path, parsedPath) { + if (!(root2 && root2.isAnimationObjectGroup)) { + return new PropertyBinding2(root2, path, parsedPath); + } else { + return new PropertyBinding2.Composite(root2, path, parsedPath); + } + } + static sanitizeNodeName(name2) { + return name2.replace(/\s/g, "_").replace(_reservedRe2, ""); + } + static parseTrackName(trackName) { + const matches = _trackRe2.exec(trackName); + if (matches === null) { + throw new Error("PropertyBinding: Cannot parse trackName: " + trackName); + } + const results = { + nodeName: matches[2], + objectName: matches[3], + objectIndex: matches[4], + propertyName: matches[5], + propertyIndex: matches[6] + }; + const lastDot = results.nodeName && results.nodeName.lastIndexOf("."); + if (lastDot !== undefined && lastDot !== -1) { + const objectName = results.nodeName.substring(lastDot + 1); + if (_supportedObjectNames2.indexOf(objectName) !== -1) { + results.nodeName = results.nodeName.substring(0, lastDot); + results.objectName = objectName; + } + } + if (results.propertyName === null || results.propertyName.length === 0) { + throw new Error("PropertyBinding: can not parse propertyName from trackName: " + trackName); + } + return results; + } + static findNode(root2, nodeName) { + if (nodeName === undefined || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root2.name || nodeName === root2.uuid) { + return root2; + } + if (root2.skeleton) { + const bone = root2.skeleton.getBoneByName(nodeName); + if (bone !== undefined) { + return bone; + } + } + if (root2.children) { + const searchNodeSubtree = function(children) { + for (let i = 0;i < children.length; i++) { + const childNode = children[i]; + if (childNode.name === nodeName || childNode.uuid === nodeName) { + return childNode; + } + const result = searchNodeSubtree(childNode.children); + if (result) + return result; + } + return null; + }; + const subTreeNode = searchNodeSubtree(root2.children); + if (subTreeNode) { + return subTreeNode; + } + } + return null; + } + _getValue_unavailable() { + } + _setValue_unavailable() { + } + _getValue_direct(buffer, offset) { + buffer[offset] = this.targetObject[this.propertyName]; + } + _getValue_array(buffer, offset) { + const source = this.resolvedProperty; + for (let i = 0, n2 = source.length;i !== n2; ++i) { + buffer[offset++] = source[i]; + } + } + _getValue_arrayElement(buffer, offset) { + buffer[offset] = this.resolvedProperty[this.propertyIndex]; + } + _getValue_toArray(buffer, offset) { + this.resolvedProperty.toArray(buffer, offset); + } + _setValue_direct(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + } + _setValue_direct_setNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_array(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n2 = dest.length;i !== n2; ++i) { + dest[i] = buffer[offset++]; + } + } + _setValue_array_setNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n2 = dest.length;i !== n2; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.needsUpdate = true; + } + _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n2 = dest.length;i !== n2; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_arrayElement(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + } + _setValue_arrayElement_setNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_fromArray(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + } + _setValue_fromArray_setNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.needsUpdate = true; + } + _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.matrixWorldNeedsUpdate = true; + } + _getValue_unbound(targetArray, offset) { + this.bind(); + this.getValue(targetArray, offset); + } + _setValue_unbound(sourceArray, offset) { + this.bind(); + this.setValue(sourceArray, offset); + } + bind() { + let targetObject = this.node; + const parsedPath = this.parsedPath; + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + if (!targetObject) { + targetObject = PropertyBinding2.findNode(this.rootNode, parsedPath.nodeName); + this.node = targetObject; + } + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; + if (!targetObject) { + console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + "."); + return; + } + if (objectName) { + let objectIndex = parsedPath.objectIndex; + switch (objectName) { + case "materials": + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.materials) { + console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this); + return; + } + targetObject = targetObject.material.materials; + break; + case "bones": + if (!targetObject.skeleton) { + console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this); + return; + } + targetObject = targetObject.skeleton.bones; + for (let i = 0;i < targetObject.length; i++) { + if (targetObject[i].name === objectIndex) { + objectIndex = i; + break; + } + } + break; + case "map": + if ("map" in targetObject) { + targetObject = targetObject.map; + break; + } + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.map) { + console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this); + return; + } + targetObject = targetObject.material.map; + break; + default: + if (targetObject[objectName] === undefined) { + console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this); + return; + } + targetObject = targetObject[objectName]; + } + if (objectIndex !== undefined) { + if (targetObject[objectIndex] === undefined) { + console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, targetObject); + return; + } + targetObject = targetObject[objectIndex]; + } + } + const nodeProperty = targetObject[propertyName]; + if (nodeProperty === undefined) { + const nodeName = parsedPath.nodeName; + console.error("THREE.PropertyBinding: Trying to update property for track: " + nodeName + "." + propertyName + " but it wasn't found.", targetObject); + return; + } + let versioning = this.Versioning.None; + this.targetObject = targetObject; + if (targetObject.isMaterial === true) { + versioning = this.Versioning.NeedsUpdate; + } else if (targetObject.isObject3D === true) { + versioning = this.Versioning.MatrixWorldNeedsUpdate; + } + let bindingType = this.BindingType.Direct; + if (propertyIndex !== undefined) { + if (propertyName === "morphTargetInfluences") { + if (!targetObject.geometry) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this); + return; + } + if (!targetObject.geometry.morphAttributes) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this); + return; + } + if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) { + propertyIndex = targetObject.morphTargetDictionary[propertyIndex]; + } + } + bindingType = this.BindingType.ArrayElement; + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) { + bindingType = this.BindingType.HasFromToArray; + this.resolvedProperty = nodeProperty; + } else if (Array.isArray(nodeProperty)) { + bindingType = this.BindingType.EntireArray; + this.resolvedProperty = nodeProperty; + } else { + this.propertyName = propertyName; + } + this.getValue = this.GetterByBindingType[bindingType]; + this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning]; + } + unbind() { + this.node = null; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + } + PropertyBinding2.Composite = Composite2; + PropertyBinding2.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 + }; + PropertyBinding2.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 + }; + PropertyBinding2.prototype.GetterByBindingType = [ + PropertyBinding2.prototype._getValue_direct, + PropertyBinding2.prototype._getValue_array, + PropertyBinding2.prototype._getValue_arrayElement, + PropertyBinding2.prototype._getValue_toArray + ]; + PropertyBinding2.prototype.SetterByBindingTypeAndVersioning = [ + [ + PropertyBinding2.prototype._setValue_direct, + PropertyBinding2.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding2.prototype._setValue_direct_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding2.prototype._setValue_array, + PropertyBinding2.prototype._setValue_array_setNeedsUpdate, + PropertyBinding2.prototype._setValue_array_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding2.prototype._setValue_arrayElement, + PropertyBinding2.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding2.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding2.prototype._setValue_fromArray, + PropertyBinding2.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding2.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate + ] + ]; + + class AnimationObjectGroup2 { + constructor() { + this.isAnimationObjectGroup = true; + this.uuid = generateUUID2(); + this._objects = Array.prototype.slice.call(arguments); + this.nCachedObjects_ = 0; + const indices = {}; + this._indicesByUUID = indices; + for (let i = 0, n2 = arguments.length;i !== n2; ++i) { + indices[arguments[i].uuid] = i; + } + this._paths = []; + this._parsedPaths = []; + this._bindings = []; + this._bindingsIndicesByPath = {}; + const scope = this; + this.stats = { + objects: { + get total() { + return scope._objects.length; + }, + get inUse() { + return this.total - scope.nCachedObjects_; + } + }, + get bindingsPerObject() { + return scope._bindings.length; + } + }; + } + add() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, nBindings = bindings.length; + let knownObject = undefined, nObjects = objects.length, nCachedObjects = this.nCachedObjects_; + for (let i = 0, n2 = arguments.length;i !== n2; ++i) { + const object = arguments[i], uuid = object.uuid; + let index2 = indicesByUUID[uuid]; + if (index2 === undefined) { + index2 = nObjects++; + indicesByUUID[uuid] = index2; + objects.push(object); + for (let j2 = 0, m = nBindings;j2 !== m; ++j2) { + bindings[j2].push(new PropertyBinding2(object, paths[j2], parsedPaths[j2])); + } + } else if (index2 < nCachedObjects) { + knownObject = objects[index2]; + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex]; + indicesByUUID[lastCachedObject.uuid] = index2; + objects[index2] = lastCachedObject; + indicesByUUID[uuid] = firstActiveIndex; + objects[firstActiveIndex] = object; + for (let j2 = 0, m = nBindings;j2 !== m; ++j2) { + const bindingsForPath = bindings[j2], lastCached = bindingsForPath[firstActiveIndex]; + let binding = bindingsForPath[index2]; + bindingsForPath[index2] = lastCached; + if (binding === undefined) { + binding = new PropertyBinding2(object, paths[j2], parsedPaths[j2]); + } + bindingsForPath[firstActiveIndex] = binding; + } + } else if (objects[index2] !== knownObject) { + console.error("THREE.AnimationObjectGroup: Different objects with the same UUID " + "detected. Clean the caches or recreate your infrastructure when reloading scenes."); + } + } + this.nCachedObjects_ = nCachedObjects; + } + remove() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_; + for (let i = 0, n2 = arguments.length;i !== n2; ++i) { + const object = arguments[i], uuid = object.uuid, index2 = indicesByUUID[uuid]; + if (index2 !== undefined && index2 >= nCachedObjects) { + const lastCachedIndex = nCachedObjects++, firstActiveObject = objects[lastCachedIndex]; + indicesByUUID[firstActiveObject.uuid] = index2; + objects[index2] = firstActiveObject; + indicesByUUID[uuid] = lastCachedIndex; + objects[lastCachedIndex] = object; + for (let j2 = 0, m = nBindings;j2 !== m; ++j2) { + const bindingsForPath = bindings[j2], firstActive = bindingsForPath[lastCachedIndex], binding = bindingsForPath[index2]; + bindingsForPath[index2] = firstActive; + bindingsForPath[lastCachedIndex] = binding; + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + uncache() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_, nObjects = objects.length; + for (let i = 0, n2 = arguments.length;i !== n2; ++i) { + const object = arguments[i], uuid = object.uuid, index2 = indicesByUUID[uuid]; + if (index2 !== undefined) { + delete indicesByUUID[uuid]; + if (index2 < nCachedObjects) { + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex], lastIndex = --nObjects, lastObject = objects[lastIndex]; + indicesByUUID[lastCachedObject.uuid] = index2; + objects[index2] = lastCachedObject; + indicesByUUID[lastObject.uuid] = firstActiveIndex; + objects[firstActiveIndex] = lastObject; + objects.pop(); + for (let j2 = 0, m = nBindings;j2 !== m; ++j2) { + const bindingsForPath = bindings[j2], lastCached = bindingsForPath[firstActiveIndex], last2 = bindingsForPath[lastIndex]; + bindingsForPath[index2] = lastCached; + bindingsForPath[firstActiveIndex] = last2; + bindingsForPath.pop(); + } + } else { + const lastIndex = --nObjects, lastObject = objects[lastIndex]; + if (lastIndex > 0) { + indicesByUUID[lastObject.uuid] = index2; + } + objects[index2] = lastObject; + objects.pop(); + for (let j2 = 0, m = nBindings;j2 !== m; ++j2) { + const bindingsForPath = bindings[j2]; + bindingsForPath[index2] = bindingsForPath[lastIndex]; + bindingsForPath.pop(); + } + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + subscribe_(path, parsedPath) { + const indicesByPath = this._bindingsIndicesByPath; + let index2 = indicesByPath[path]; + const bindings = this._bindings; + if (index2 !== undefined) + return bindings[index2]; + const paths = this._paths, parsedPaths = this._parsedPaths, objects = this._objects, nObjects = objects.length, nCachedObjects = this.nCachedObjects_, bindingsForPath = new Array(nObjects); + index2 = bindings.length; + indicesByPath[path] = index2; + paths.push(path); + parsedPaths.push(parsedPath); + bindings.push(bindingsForPath); + for (let i = nCachedObjects, n2 = objects.length;i !== n2; ++i) { + const object = objects[i]; + bindingsForPath[i] = new PropertyBinding2(object, path, parsedPath); + } + return bindingsForPath; + } + unsubscribe_(path) { + const indicesByPath = this._bindingsIndicesByPath, index2 = indicesByPath[path]; + if (index2 !== undefined) { + const paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, lastBindingsIndex = bindings.length - 1, lastBindings = bindings[lastBindingsIndex], lastBindingsPath = path[lastBindingsIndex]; + indicesByPath[lastBindingsPath] = index2; + bindings[index2] = lastBindings; + bindings.pop(); + parsedPaths[index2] = parsedPaths[lastBindingsIndex]; + parsedPaths.pop(); + paths[index2] = paths[lastBindingsIndex]; + paths.pop(); + } + } + } + + class AnimationAction2 { + constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) { + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; + const tracks = clip.tracks, nTracks = tracks.length, interpolants = new Array(nTracks); + const interpolantSettings = { + endingStart: ZeroCurvatureEnding2, + endingEnd: ZeroCurvatureEnding2 + }; + for (let i = 0;i !== nTracks; ++i) { + const interpolant = tracks[i].createInterpolant(null); + interpolants[i] = interpolant; + interpolant.settings = interpolantSettings; + } + this._interpolantSettings = interpolantSettings; + this._interpolants = interpolants; + this._propertyBindings = new Array(nTracks); + this._cacheIndex = null; + this._byClipCacheIndex = null; + this._timeScaleInterpolant = null; + this._weightInterpolant = null; + this.loop = LoopRepeat2; + this._loopCount = -1; + this._startTime = null; + this.time = 0; + this.timeScale = 1; + this._effectiveTimeScale = 1; + this.weight = 1; + this._effectiveWeight = 1; + this.repetitions = Infinity; + this.paused = false; + this.enabled = true; + this.clampWhenFinished = false; + this.zeroSlopeAtStart = true; + this.zeroSlopeAtEnd = true; + } + play() { + this._mixer._activateAction(this); + return this; + } + stop() { + this._mixer._deactivateAction(this); + return this.reset(); + } + reset() { + this.paused = false; + this.enabled = true; + this.time = 0; + this._loopCount = -1; + this._startTime = null; + return this.stopFading().stopWarping(); + } + isRunning() { + return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this); + } + isScheduled() { + return this._mixer._isActiveAction(this); + } + startAt(time2) { + this._startTime = time2; + return this; + } + setLoop(mode, repetitions) { + this.loop = mode; + this.repetitions = repetitions; + return this; + } + setEffectiveWeight(weight) { + this.weight = weight; + this._effectiveWeight = this.enabled ? weight : 0; + return this.stopFading(); + } + getEffectiveWeight() { + return this._effectiveWeight; + } + fadeIn(duration) { + return this._scheduleFading(duration, 0, 1); + } + fadeOut(duration) { + return this._scheduleFading(duration, 1, 0); + } + crossFadeFrom(fadeOutAction, duration, warp) { + fadeOutAction.fadeOut(duration); + this.fadeIn(duration); + if (warp) { + const fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, startEndRatio = fadeOutDuration / fadeInDuration, endStartRatio = fadeInDuration / fadeOutDuration; + fadeOutAction.warp(1, startEndRatio, duration); + this.warp(endStartRatio, 1, duration); + } + return this; + } + crossFadeTo(fadeInAction, duration, warp) { + return fadeInAction.crossFadeFrom(this, duration, warp); + } + stopFading() { + const weightInterpolant = this._weightInterpolant; + if (weightInterpolant !== null) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant(weightInterpolant); + } + return this; + } + setEffectiveTimeScale(timeScale) { + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; + return this.stopWarping(); + } + getEffectiveTimeScale() { + return this._effectiveTimeScale; + } + setDuration(duration) { + this.timeScale = this._clip.duration / duration; + return this.stopWarping(); + } + syncWith(action) { + this.time = action.time; + this.timeScale = action.timeScale; + return this.stopWarping(); + } + halt(duration) { + return this.warp(this._effectiveTimeScale, 0, duration); + } + warp(startTimeScale, endTimeScale, duration) { + const mixer = this._mixer, now3 = mixer.time, timeScale = this.timeScale; + let interpolant = this._timeScaleInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; + } + const { parameterPositions: times, sampleValues: values2 } = interpolant; + times[0] = now3; + times[1] = now3 + duration; + values2[0] = startTimeScale / timeScale; + values2[1] = endTimeScale / timeScale; + return this; + } + stopWarping() { + const timeScaleInterpolant = this._timeScaleInterpolant; + if (timeScaleInterpolant !== null) { + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant(timeScaleInterpolant); + } + return this; + } + getMixer() { + return this._mixer; + } + getClip() { + return this._clip; + } + getRoot() { + return this._localRoot || this._mixer._root; + } + _update(time2, deltaTime, timeDirection, accuIndex) { + if (!this.enabled) { + this._updateWeight(time2); + return; + } + const startTime = this._startTime; + if (startTime !== null) { + const timeRunning = (time2 - startTime) * timeDirection; + if (timeRunning < 0 || timeDirection === 0) { + deltaTime = 0; + } else { + this._startTime = null; + deltaTime = timeDirection * timeRunning; + } + } + deltaTime *= this._updateTimeScale(time2); + const clipTime = this._updateTime(deltaTime); + const weight = this._updateWeight(time2); + if (weight > 0) { + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; + switch (this.blendMode) { + case AdditiveAnimationBlendMode2: + for (let j2 = 0, m = interpolants.length;j2 !== m; ++j2) { + interpolants[j2].evaluate(clipTime); + propertyMixers[j2].accumulateAdditive(weight); + } + break; + case NormalAnimationBlendMode2: + default: + for (let j2 = 0, m = interpolants.length;j2 !== m; ++j2) { + interpolants[j2].evaluate(clipTime); + propertyMixers[j2].accumulate(accuIndex, weight); + } + } + } + } + _updateWeight(time2) { + let weight = 0; + if (this.enabled) { + weight = this.weight; + const interpolant = this._weightInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time2)[0]; + weight *= interpolantValue; + if (time2 > interpolant.parameterPositions[1]) { + this.stopFading(); + if (interpolantValue === 0) { + this.enabled = false; + } + } + } + } + this._effectiveWeight = weight; + return weight; + } + _updateTimeScale(time2) { + let timeScale = 0; + if (!this.paused) { + timeScale = this.timeScale; + const interpolant = this._timeScaleInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time2)[0]; + timeScale *= interpolantValue; + if (time2 > interpolant.parameterPositions[1]) { + this.stopWarping(); + if (timeScale === 0) { + this.paused = true; + } else { + this.timeScale = timeScale; + } + } + } + } + this._effectiveTimeScale = timeScale; + return timeScale; + } + _updateTime(deltaTime) { + const duration = this._clip.duration; + const loop = this.loop; + let time2 = this.time + deltaTime; + let loopCount = this._loopCount; + const pingPong = loop === LoopPingPong2; + if (deltaTime === 0) { + if (loopCount === -1) + return time2; + return pingPong && (loopCount & 1) === 1 ? duration - time2 : time2; + } + if (loop === LoopOnce2) { + if (loopCount === -1) { + this._loopCount = 0; + this._setEndings(true, true, false); + } + handle_stop: { + if (time2 >= duration) { + time2 = duration; + } else if (time2 < 0) { + time2 = 0; + } else { + this.time = time2; + break handle_stop; + } + if (this.clampWhenFinished) + this.paused = true; + else + this.enabled = false; + this.time = time2; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime < 0 ? -1 : 1 + }); + } + } else { + if (loopCount === -1) { + if (deltaTime >= 0) { + loopCount = 0; + this._setEndings(true, this.repetitions === 0, pingPong); + } else { + this._setEndings(this.repetitions === 0, true, pingPong); + } + } + if (time2 >= duration || time2 < 0) { + const loopDelta = Math.floor(time2 / duration); + time2 -= duration * loopDelta; + loopCount += Math.abs(loopDelta); + const pending = this.repetitions - loopCount; + if (pending <= 0) { + if (this.clampWhenFinished) + this.paused = true; + else + this.enabled = false; + time2 = deltaTime > 0 ? duration : 0; + this.time = time2; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime > 0 ? 1 : -1 + }); + } else { + if (pending === 1) { + const atStart = deltaTime < 0; + this._setEndings(atStart, !atStart, pingPong); + } else { + this._setEndings(false, false, pingPong); + } + this._loopCount = loopCount; + this.time = time2; + this._mixer.dispatchEvent({ + type: "loop", + action: this, + loopDelta + }); + } + } else { + this.time = time2; + } + if (pingPong && (loopCount & 1) === 1) { + return duration - time2; + } + } + return time2; + } + _setEndings(atStart, atEnd, pingPong) { + const settings = this._interpolantSettings; + if (pingPong) { + settings.endingStart = ZeroSlopeEnding2; + settings.endingEnd = ZeroSlopeEnding2; + } else { + if (atStart) { + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding2 : ZeroCurvatureEnding2; + } else { + settings.endingStart = WrapAroundEnding2; + } + if (atEnd) { + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding2 : ZeroCurvatureEnding2; + } else { + settings.endingEnd = WrapAroundEnding2; + } + } + } + _scheduleFading(duration, weightNow, weightThen) { + const mixer = this._mixer, now3 = mixer.time; + let interpolant = this._weightInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; + } + const { parameterPositions: times, sampleValues: values2 } = interpolant; + times[0] = now3; + values2[0] = weightNow; + times[1] = now3 + duration; + values2[1] = weightThen; + return this; + } + } + var _controlInterpolantsResultBuffer2 = new Float32Array(1); + + class AnimationMixer2 extends EventDispatcher2 { + constructor(root2) { + super(); + this._root = root2; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1; + } + _bindAction(action, prototypeAction) { + const root2 = action._localRoot || this._root, tracks = action._clip.tracks, nTracks = tracks.length, bindings = action._propertyBindings, interpolants = action._interpolants, rootUuid = root2.uuid, bindingsByRoot = this._bindingsByRootAndName; + let bindingsByName = bindingsByRoot[rootUuid]; + if (bindingsByName === undefined) { + bindingsByName = {}; + bindingsByRoot[rootUuid] = bindingsByName; + } + for (let i = 0;i !== nTracks; ++i) { + const track = tracks[i], trackName = track.name; + let binding = bindingsByName[trackName]; + if (binding !== undefined) { + ++binding.referenceCount; + bindings[i] = binding; + } else { + binding = bindings[i]; + if (binding !== undefined) { + if (binding._cacheIndex === null) { + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + } + continue; + } + const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath; + binding = new PropertyMixer2(PropertyBinding2.create(root2, trackName, path), track.ValueTypeName, track.getValueSize()); + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + bindings[i] = binding; + } + interpolants[i].resultBuffer = binding.buffer; + } + } + _activateAction(action) { + if (!this._isActiveAction(action)) { + if (action._cacheIndex === null) { + const rootUuid = (action._localRoot || this._root).uuid, clipUuid = action._clip.uuid, actionsForClip = this._actionsByClip[clipUuid]; + this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]); + this._addInactiveAction(action, clipUuid, rootUuid); + } + const bindings = action._propertyBindings; + for (let i = 0, n2 = bindings.length;i !== n2; ++i) { + const binding = bindings[i]; + if (binding.useCount++ === 0) { + this._lendBinding(binding); + binding.saveOriginalState(); + } + } + this._lendAction(action); + } + } + _deactivateAction(action) { + if (this._isActiveAction(action)) { + const bindings = action._propertyBindings; + for (let i = 0, n2 = bindings.length;i !== n2; ++i) { + const binding = bindings[i]; + if (--binding.useCount === 0) { + binding.restoreOriginalState(); + this._takeBackBinding(binding); + } + } + this._takeBackAction(action); + } + } + _initMemoryManager() { + this._actions = []; + this._nActiveActions = 0; + this._actionsByClip = {}; + this._bindings = []; + this._nActiveBindings = 0; + this._bindingsByRootAndName = {}; + this._controlInterpolants = []; + this._nActiveControlInterpolants = 0; + const scope = this; + this.stats = { + actions: { + get total() { + return scope._actions.length; + }, + get inUse() { + return scope._nActiveActions; + } + }, + bindings: { + get total() { + return scope._bindings.length; + }, + get inUse() { + return scope._nActiveBindings; + } + }, + controlInterpolants: { + get total() { + return scope._controlInterpolants.length; + }, + get inUse() { + return scope._nActiveControlInterpolants; + } + } + }; + } + _isActiveAction(action) { + const index2 = action._cacheIndex; + return index2 !== null && index2 < this._nActiveActions; + } + _addInactiveAction(action, clipUuid, rootUuid) { + const actions = this._actions, actionsByClip = this._actionsByClip; + let actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip === undefined) { + actionsForClip = { + knownActions: [action], + actionByRoot: {} + }; + action._byClipCacheIndex = 0; + actionsByClip[clipUuid] = actionsForClip; + } else { + const knownActions = actionsForClip.knownActions; + action._byClipCacheIndex = knownActions.length; + knownActions.push(action); + } + action._cacheIndex = actions.length; + actions.push(action); + actionsForClip.actionByRoot[rootUuid] = action; + } + _removeInactiveAction(action) { + const actions = this._actions, lastInactiveAction = actions[actions.length - 1], cacheIndex = action._cacheIndex; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + action._cacheIndex = null; + const clipUuid = action._clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid], knownActionsForClip = actionsForClip.knownActions, lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1], byClipCacheIndex = action._byClipCacheIndex; + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[byClipCacheIndex] = lastKnownAction; + knownActionsForClip.pop(); + action._byClipCacheIndex = null; + const actionByRoot = actionsForClip.actionByRoot, rootUuid = (action._localRoot || this._root).uuid; + delete actionByRoot[rootUuid]; + if (knownActionsForClip.length === 0) { + delete actionsByClip[clipUuid]; + } + this._removeInactiveBindingsForAction(action); + } + _removeInactiveBindingsForAction(action) { + const bindings = action._propertyBindings; + for (let i = 0, n2 = bindings.length;i !== n2; ++i) { + const binding = bindings[i]; + if (--binding.referenceCount === 0) { + this._removeInactiveBinding(binding); + } + } + } + _lendAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, lastActiveIndex = this._nActiveActions++, firstInactiveAction = actions[lastActiveIndex]; + action._cacheIndex = lastActiveIndex; + actions[lastActiveIndex] = action; + firstInactiveAction._cacheIndex = prevIndex; + actions[prevIndex] = firstInactiveAction; + } + _takeBackAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, firstInactiveIndex = --this._nActiveActions, lastActiveAction = actions[firstInactiveIndex]; + action._cacheIndex = firstInactiveIndex; + actions[firstInactiveIndex] = action; + lastActiveAction._cacheIndex = prevIndex; + actions[prevIndex] = lastActiveAction; + } + _addInactiveBinding(binding, rootUuid, trackName) { + const bindingsByRoot = this._bindingsByRootAndName, bindings = this._bindings; + let bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName === undefined) { + bindingByName = {}; + bindingsByRoot[rootUuid] = bindingByName; + } + bindingByName[trackName] = binding; + binding._cacheIndex = bindings.length; + bindings.push(binding); + } + _removeInactiveBinding(binding) { + const bindings = this._bindings, propBinding = binding.binding, rootUuid = propBinding.rootNode.uuid, trackName = propBinding.path, bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid], lastInactiveBinding = bindings[bindings.length - 1], cacheIndex = binding._cacheIndex; + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[cacheIndex] = lastInactiveBinding; + bindings.pop(); + delete bindingByName[trackName]; + if (Object.keys(bindingByName).length === 0) { + delete bindingsByRoot[rootUuid]; + } + } + _lendBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, lastActiveIndex = this._nActiveBindings++, firstInactiveBinding = bindings[lastActiveIndex]; + binding._cacheIndex = lastActiveIndex; + bindings[lastActiveIndex] = binding; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = firstInactiveBinding; + } + _takeBackBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, firstInactiveIndex = --this._nActiveBindings, lastActiveBinding = bindings[firstInactiveIndex]; + binding._cacheIndex = firstInactiveIndex; + bindings[firstInactiveIndex] = binding; + lastActiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = lastActiveBinding; + } + _lendControlInterpolant() { + const interpolants = this._controlInterpolants, lastActiveIndex = this._nActiveControlInterpolants++; + let interpolant = interpolants[lastActiveIndex]; + if (interpolant === undefined) { + interpolant = new LinearInterpolant2(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer2); + interpolant.__cacheIndex = lastActiveIndex; + interpolants[lastActiveIndex] = interpolant; + } + return interpolant; + } + _takeBackControlInterpolant(interpolant) { + const interpolants = this._controlInterpolants, prevIndex = interpolant.__cacheIndex, firstInactiveIndex = --this._nActiveControlInterpolants, lastActiveInterpolant = interpolants[firstInactiveIndex]; + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[firstInactiveIndex] = interpolant; + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[prevIndex] = lastActiveInterpolant; + } + clipAction(clip, optionalRoot, blendMode) { + const root2 = optionalRoot || this._root, rootUuid = root2.uuid; + let clipObject = typeof clip === "string" ? AnimationClip2.findByName(root2, clip) : clip; + const clipUuid = clipObject !== null ? clipObject.uuid : clip; + const actionsForClip = this._actionsByClip[clipUuid]; + let prototypeAction = null; + if (blendMode === undefined) { + if (clipObject !== null) { + blendMode = clipObject.blendMode; + } else { + blendMode = NormalAnimationBlendMode2; + } + } + if (actionsForClip !== undefined) { + const existingAction = actionsForClip.actionByRoot[rootUuid]; + if (existingAction !== undefined && existingAction.blendMode === blendMode) { + return existingAction; + } + prototypeAction = actionsForClip.knownActions[0]; + if (clipObject === null) + clipObject = prototypeAction._clip; + } + if (clipObject === null) + return null; + const newAction = new AnimationAction2(this, clipObject, optionalRoot, blendMode); + this._bindAction(newAction, prototypeAction); + this._addInactiveAction(newAction, clipUuid, rootUuid); + return newAction; + } + existingAction(clip, optionalRoot) { + const root2 = optionalRoot || this._root, rootUuid = root2.uuid, clipObject = typeof clip === "string" ? AnimationClip2.findByName(root2, clip) : clip, clipUuid = clipObject ? clipObject.uuid : clip, actionsForClip = this._actionsByClip[clipUuid]; + if (actionsForClip !== undefined) { + return actionsForClip.actionByRoot[rootUuid] || null; + } + return null; + } + stopAllAction() { + const actions = this._actions, nActions = this._nActiveActions; + for (let i = nActions - 1;i >= 0; --i) { + actions[i].stop(); + } + return this; + } + update(deltaTime) { + deltaTime *= this.timeScale; + const actions = this._actions, nActions = this._nActiveActions, time2 = this.time += deltaTime, timeDirection = Math.sign(deltaTime), accuIndex = this._accuIndex ^= 1; + for (let i = 0;i !== nActions; ++i) { + const action = actions[i]; + action._update(time2, deltaTime, timeDirection, accuIndex); + } + const bindings = this._bindings, nBindings = this._nActiveBindings; + for (let i = 0;i !== nBindings; ++i) { + bindings[i].apply(accuIndex); + } + return this; + } + setTime(timeInSeconds) { + this.time = 0; + for (let i = 0;i < this._actions.length; i++) { + this._actions[i].time = 0; + } + return this.update(timeInSeconds); + } + getRoot() { + return this._root; + } + uncacheClip(clip) { + const actions = this._actions, clipUuid = clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip !== undefined) { + const actionsToRemove = actionsForClip.knownActions; + for (let i = 0, n2 = actionsToRemove.length;i !== n2; ++i) { + const action = actionsToRemove[i]; + this._deactivateAction(action); + const cacheIndex = action._cacheIndex, lastInactiveAction = actions[actions.length - 1]; + action._cacheIndex = null; + action._byClipCacheIndex = null; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + this._removeInactiveBindingsForAction(action); + } + delete actionsByClip[clipUuid]; + } + } + uncacheRoot(root2) { + const rootUuid = root2.uuid, actionsByClip = this._actionsByClip; + for (const clipUuid in actionsByClip) { + const actionByRoot = actionsByClip[clipUuid].actionByRoot, action = actionByRoot[rootUuid]; + if (action !== undefined) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + const bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName !== undefined) { + for (const trackName in bindingByName) { + const binding = bindingByName[trackName]; + binding.restoreOriginalState(); + this._removeInactiveBinding(binding); + } + } + } + uncacheAction(clip, optionalRoot) { + const action = this.existingAction(clip, optionalRoot); + if (action !== null) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + } + + class RenderTarget3D2 extends RenderTarget2 { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isRenderTarget3D = true; + this.depth = depth; + this.texture = new Data3DTexture2(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } + } + + class RenderTargetArray2 extends RenderTarget2 { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isRenderTargetArray = true; + this.depth = depth; + this.texture = new DataArrayTexture2(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } + } + + class Uniform2 { + constructor(value2) { + this.value = value2; + } + clone() { + return new Uniform2(this.value.clone === undefined ? this.value : this.value.clone()); + } + } + var _id$12 = 0; + + class UniformsGroup2 extends EventDispatcher2 { + constructor() { + super(); + this.isUniformsGroup = true; + Object.defineProperty(this, "id", { value: _id$12++ }); + this.name = ""; + this.usage = StaticDrawUsage2; + this.uniforms = []; + } + add(uniform) { + this.uniforms.push(uniform); + return this; + } + remove(uniform) { + const index2 = this.uniforms.indexOf(uniform); + if (index2 !== -1) + this.uniforms.splice(index2, 1); + return this; + } + setName(name2) { + this.name = name2; + return this; + } + setUsage(value2) { + this.usage = value2; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + return this; + } + copy(source) { + this.name = source.name; + this.usage = source.usage; + const uniformsSource = source.uniforms; + this.uniforms.length = 0; + for (let i = 0, l2 = uniformsSource.length;i < l2; i++) { + const uniforms = Array.isArray(uniformsSource[i]) ? uniformsSource[i] : [uniformsSource[i]]; + for (let j2 = 0;j2 < uniforms.length; j2++) { + this.uniforms.push(uniforms[j2].clone()); + } + } + return this; + } + clone() { + return new this.constructor().copy(this); + } + } + + class InstancedInterleavedBuffer2 extends InterleavedBuffer2 { + constructor(array, stride, meshPerAttribute = 1) { + super(array, stride); + this.isInstancedInterleavedBuffer = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + clone(data2) { + const ib = super.clone(data2); + ib.meshPerAttribute = this.meshPerAttribute; + return ib; + } + toJSON(data2) { + const json = super.toJSON(data2); + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; + return json; + } + } + + class GLBufferAttribute2 { + constructor(buffer, type, itemSize, elementSize, count) { + this.isGLBufferAttribute = true; + this.name = ""; + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; + this.version = 0; + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setBuffer(buffer) { + this.buffer = buffer; + return this; + } + setType(type, elementSize) { + this.type = type; + this.elementSize = elementSize; + return this; + } + setItemSize(itemSize) { + this.itemSize = itemSize; + return this; + } + setCount(count) { + this.count = count; + return this; + } + } + var _matrix6 = /* @__PURE__ */ new Matrix42; + + class Raycaster2 { + constructor(origin, direction, near = 0, far = Infinity) { + this.ray = new Ray2(origin, direction); + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers2; + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + } + set(origin, direction) { + this.ray.set(origin, direction); + } + setFromCamera(coords, camera) { + if (camera.isPerspectiveCamera) { + this.ray.origin.setFromMatrixPosition(camera.matrixWorld); + this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize(); + this.camera = camera; + } else if (camera.isOrthographicCamera) { + this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); + this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld); + this.camera = camera; + } else { + console.error("THREE.Raycaster: Unsupported camera type: " + camera.type); + } + } + setFromXRController(controller) { + _matrix6.identity().extractRotation(controller.matrixWorld); + this.ray.origin.setFromMatrixPosition(controller.matrixWorld); + this.ray.direction.set(0, 0, -1).applyMatrix4(_matrix6); + return this; + } + intersectObject(object, recursive = true, intersects3 = []) { + intersect2(object, this, intersects3, recursive); + intersects3.sort(ascSort2); + return intersects3; + } + intersectObjects(objects, recursive = true, intersects3 = []) { + for (let i = 0, l2 = objects.length;i < l2; i++) { + intersect2(objects[i], this, intersects3, recursive); + } + intersects3.sort(ascSort2); + return intersects3; + } + } + function ascSort2(a2, b2) { + return a2.distance - b2.distance; + } + function intersect2(object, raycaster, intersects3, recursive) { + let propagate = true; + if (object.layers.test(raycaster.layers)) { + const result = object.raycast(raycaster, intersects3); + if (result === false) + propagate = false; + } + if (propagate === true && recursive === true) { + const children = object.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + intersect2(children[i], raycaster, intersects3, true); + } + } + } + + class Spherical2 { + constructor(radius = 1, phi = 0, theta = 0) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + set(radius, phi, theta) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + copy(other) { + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + return this; + } + makeSafe() { + const EPS = 0.000001; + this.phi = clamp3(this.phi, EPS, Math.PI - EPS); + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x2, y, z) { + this.radius = Math.sqrt(x2 * x2 + y * y + z * z); + if (this.radius === 0) { + this.theta = 0; + this.phi = 0; + } else { + this.theta = Math.atan2(x2, z); + this.phi = Math.acos(clamp3(y / this.radius, -1, 1)); + } + return this; + } + clone() { + return new this.constructor().copy(this); + } + } + + class Cylindrical2 { + constructor(radius = 1, theta = 0, y = 0) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + set(radius, theta, y) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + copy(other) { + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x2, y, z) { + this.radius = Math.sqrt(x2 * x2 + z * z); + this.theta = Math.atan2(x2, z); + this.y = y; + return this; + } + clone() { + return new this.constructor().copy(this); + } + } + + class Matrix22 { + constructor(n11, n12, n21, n22) { + Matrix22.prototype.isMatrix2 = true; + this.elements = [ + 1, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n21, n22); + } + } + identity() { + this.set(1, 0, 0, 1); + return this; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 4; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + set(n11, n12, n21, n22) { + const te3 = this.elements; + te3[0] = n11; + te3[2] = n12; + te3[1] = n21; + te3[3] = n22; + return this; + } + } + var _vector$42 = /* @__PURE__ */ new Vector22; + + class Box22 { + constructor(min = new Vector22(Infinity, Infinity), max = new Vector22(-Infinity, -Infinity)) { + this.isBox2 = true; + this.min = min; + this.max = max; + } + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length;i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size2) { + const halfSize = _vector$42.copy(size2).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = Infinity; + this.max.x = this.max.y = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y; + } + getParameter(point, target) { + return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y)); + } + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y; + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$42).distanceTo(point); + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) + this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } + } + var _startP2 = /* @__PURE__ */ new Vector32; + var _startEnd2 = /* @__PURE__ */ new Vector32; + + class Line32 { + constructor(start = new Vector32, end = new Vector32) { + this.start = start; + this.end = end; + } + set(start, end) { + this.start.copy(start); + this.end.copy(end); + return this; + } + copy(line2) { + this.start.copy(line2.start); + this.end.copy(line2.end); + return this; + } + getCenter(target) { + return target.addVectors(this.start, this.end).multiplyScalar(0.5); + } + delta(target) { + return target.subVectors(this.end, this.start); + } + distanceSq() { + return this.start.distanceToSquared(this.end); + } + distance() { + return this.start.distanceTo(this.end); + } + at(t3, target) { + return this.delta(target).multiplyScalar(t3).add(this.start); + } + closestPointToPointParameter(point, clampToLine) { + _startP2.subVectors(point, this.start); + _startEnd2.subVectors(this.end, this.start); + const startEnd2 = _startEnd2.dot(_startEnd2); + const startEnd_startP = _startEnd2.dot(_startP2); + let t3 = startEnd_startP / startEnd2; + if (clampToLine) { + t3 = clamp3(t3, 0, 1); + } + return t3; + } + closestPointToPoint(point, clampToLine, target) { + const t3 = this.closestPointToPointParameter(point, clampToLine); + return this.delta(target).multiplyScalar(t3).add(this.start); + } + applyMatrix4(matrix3) { + this.start.applyMatrix4(matrix3); + this.end.applyMatrix4(matrix3); + return this; + } + equals(line2) { + return line2.start.equals(this.start) && line2.end.equals(this.end); + } + clone() { + return new this.constructor().copy(this); + } + } + var _vector$32 = /* @__PURE__ */ new Vector32; + + class SpotLightHelper2 extends Object3D2 { + constructor(light, color) { + super(); + this.light = light; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "SpotLightHelper"; + const geometry = new BufferGeometry2; + const positions = [ + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + -1, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + -1, + 1 + ]; + for (let i = 0, j2 = 1, l2 = 32;i < l2; i++, j2++) { + const p1 = i / l2 * Math.PI * 2; + const p2 = j2 / l2 * Math.PI * 2; + positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1); + } + geometry.setAttribute("position", new Float32BufferAttribute2(positions, 3)); + const material = new LineBasicMaterial2({ fog: false, toneMapped: false }); + this.cone = new LineSegments3(geometry, material); + this.add(this.cone); + this.update(); + } + dispose() { + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + if (this.parent) { + this.parent.updateWorldMatrix(true); + this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld); + } else { + this.matrix.copy(this.light.matrixWorld); + } + this.matrixWorld.copy(this.light.matrixWorld); + const coneLength = this.light.distance ? this.light.distance : 1000; + const coneWidth = coneLength * Math.tan(this.light.angle); + this.cone.scale.set(coneWidth, coneWidth, coneLength); + _vector$32.setFromMatrixPosition(this.light.target.matrixWorld); + this.cone.lookAt(_vector$32); + if (this.color !== undefined) { + this.cone.material.color.set(this.color); + } else { + this.cone.material.color.copy(this.light.color); + } + } + } + var _vector$22 = /* @__PURE__ */ new Vector32; + var _boneMatrix2 = /* @__PURE__ */ new Matrix42; + var _matrixWorldInv2 = /* @__PURE__ */ new Matrix42; + + class SkeletonHelper2 extends LineSegments3 { + constructor(object) { + const bones = getBoneList2(object); + const geometry = new BufferGeometry2; + const vertices = []; + const colors = []; + const color1 = new Color2(0, 0, 1); + const color2 = new Color2(0, 1, 0); + for (let i = 0;i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + vertices.push(0, 0, 0); + vertices.push(0, 0, 0); + colors.push(color1.r, color1.g, color1.b); + colors.push(color2.r, color2.g, color2.b); + } + } + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + const material = new LineBasicMaterial2({ vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true }); + super(geometry, material); + this.isSkeletonHelper = true; + this.type = "SkeletonHelper"; + this.root = object; + this.bones = bones; + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + } + updateMatrixWorld(force) { + const bones = this.bones; + const geometry = this.geometry; + const position2 = geometry.getAttribute("position"); + _matrixWorldInv2.copy(this.root.matrixWorld).invert(); + for (let i = 0, j2 = 0;i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + _boneMatrix2.multiplyMatrices(_matrixWorldInv2, bone.matrixWorld); + _vector$22.setFromMatrixPosition(_boneMatrix2); + position2.setXYZ(j2, _vector$22.x, _vector$22.y, _vector$22.z); + _boneMatrix2.multiplyMatrices(_matrixWorldInv2, bone.parent.matrixWorld); + _vector$22.setFromMatrixPosition(_boneMatrix2); + position2.setXYZ(j2 + 1, _vector$22.x, _vector$22.y, _vector$22.z); + j2 += 2; + } + } + geometry.getAttribute("position").needsUpdate = true; + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + function getBoneList2(object) { + const boneList = []; + if (object.isBone === true) { + boneList.push(object); + } + for (let i = 0;i < object.children.length; i++) { + boneList.push.apply(boneList, getBoneList2(object.children[i])); + } + return boneList; + } + + class PointLightHelper2 extends Mesh2 { + constructor(light, sphereSize, color) { + const geometry = new SphereGeometry3(sphereSize, 4, 2); + const material = new MeshBasicMaterial2({ wireframe: true, fog: false, toneMapped: false }); + super(geometry, material); + this.light = light; + this.color = color; + this.type = "PointLightHelper"; + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; + this.update(); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + if (this.color !== undefined) { + this.material.color.set(this.color); + } else { + this.material.color.copy(this.light.color); + } + } + } + var _vector$12 = /* @__PURE__ */ new Vector32; + var _color12 = /* @__PURE__ */ new Color2; + var _color22 = /* @__PURE__ */ new Color2; + + class HemisphereLightHelper2 extends Object3D2 { + constructor(light, size2, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "HemisphereLightHelper"; + const geometry = new OctahedronGeometry2(size2); + geometry.rotateY(Math.PI * 0.5); + this.material = new MeshBasicMaterial2({ wireframe: true, fog: false, toneMapped: false }); + if (this.color === undefined) + this.material.vertexColors = true; + const position2 = geometry.getAttribute("position"); + const colors = new Float32Array(position2.count * 3); + geometry.setAttribute("color", new BufferAttribute2(colors, 3)); + this.add(new Mesh2(geometry, this.material)); + this.update(); + } + dispose() { + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + update() { + const mesh = this.children[0]; + if (this.color !== undefined) { + this.material.color.set(this.color); + } else { + const colors = mesh.geometry.getAttribute("color"); + _color12.copy(this.light.color); + _color22.copy(this.light.groundColor); + for (let i = 0, l2 = colors.count;i < l2; i++) { + const color = i < l2 / 2 ? _color12 : _color22; + colors.setXYZ(i, color.r, color.g, color.b); + } + colors.needsUpdate = true; + } + this.light.updateWorldMatrix(true, false); + mesh.lookAt(_vector$12.setFromMatrixPosition(this.light.matrixWorld).negate()); + } + } + + class GridHelper2 extends LineSegments3 { + constructor(size2 = 10, divisions = 10, color1 = 4473924, color2 = 8947848) { + color1 = new Color2(color1); + color2 = new Color2(color2); + const center = divisions / 2; + const step = size2 / divisions; + const halfSize = size2 / 2; + const vertices = [], colors = []; + for (let i = 0, j2 = 0, k3 = -halfSize;i <= divisions; i++, k3 += step) { + vertices.push(-halfSize, 0, k3, halfSize, 0, k3); + vertices.push(k3, 0, -halfSize, k3, 0, halfSize); + const color = i === center ? color1 : color2; + color.toArray(colors, j2); + j2 += 3; + color.toArray(colors, j2); + j2 += 3; + color.toArray(colors, j2); + j2 += 3; + color.toArray(colors, j2); + j2 += 3; + } + const geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + const material = new LineBasicMaterial2({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "GridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + + class PolarGridHelper2 extends LineSegments3 { + constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 4473924, color2 = 8947848) { + color1 = new Color2(color1); + color2 = new Color2(color2); + const vertices = []; + const colors = []; + if (sectors > 1) { + for (let i = 0;i < sectors; i++) { + const v = i / sectors * (Math.PI * 2); + const x2 = Math.sin(v) * radius; + const z = Math.cos(v) * radius; + vertices.push(0, 0, 0); + vertices.push(x2, 0, z); + const color = i & 1 ? color1 : color2; + colors.push(color.r, color.g, color.b); + colors.push(color.r, color.g, color.b); + } + } + for (let i = 0;i < rings; i++) { + const color = i & 1 ? color1 : color2; + const r = radius - radius / rings * i; + for (let j2 = 0;j2 < divisions; j2++) { + let v = j2 / divisions * (Math.PI * 2); + let x2 = Math.sin(v) * r; + let z = Math.cos(v) * r; + vertices.push(x2, 0, z); + colors.push(color.r, color.g, color.b); + v = (j2 + 1) / divisions * (Math.PI * 2); + x2 = Math.sin(v) * r; + z = Math.cos(v) * r; + vertices.push(x2, 0, z); + colors.push(color.r, color.g, color.b); + } + } + const geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + const material = new LineBasicMaterial2({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "PolarGridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + var _v18 = /* @__PURE__ */ new Vector32; + var _v27 = /* @__PURE__ */ new Vector32; + var _v33 = /* @__PURE__ */ new Vector32; + + class DirectionalLightHelper2 extends Object3D2 { + constructor(light, size2, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "DirectionalLightHelper"; + if (size2 === undefined) + size2 = 1; + let geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2([ + -size2, + size2, + 0, + size2, + size2, + 0, + size2, + -size2, + 0, + -size2, + -size2, + 0, + -size2, + size2, + 0 + ], 3)); + const material = new LineBasicMaterial2({ fog: false, toneMapped: false }); + this.lightPlane = new Line4(geometry, material); + this.add(this.lightPlane); + geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2([0, 0, 0, 0, 0, 1], 3)); + this.targetLine = new Line4(geometry, material); + this.add(this.targetLine); + this.update(); + } + dispose() { + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + _v18.setFromMatrixPosition(this.light.matrixWorld); + _v27.setFromMatrixPosition(this.light.target.matrixWorld); + _v33.subVectors(_v27, _v18); + this.lightPlane.lookAt(_v27); + if (this.color !== undefined) { + this.lightPlane.material.color.set(this.color); + this.targetLine.material.color.set(this.color); + } else { + this.lightPlane.material.color.copy(this.light.color); + this.targetLine.material.color.copy(this.light.color); + } + this.targetLine.lookAt(_v27); + this.targetLine.scale.z = _v33.length(); + } + } + var _vector5 = /* @__PURE__ */ new Vector32; + var _camera3 = /* @__PURE__ */ new Camera2; + + class CameraHelper2 extends LineSegments3 { + constructor(camera) { + const geometry = new BufferGeometry2; + const material = new LineBasicMaterial2({ color: 16777215, vertexColors: true, toneMapped: false }); + const vertices = []; + const colors = []; + const pointMap = {}; + addLine("n1", "n2"); + addLine("n2", "n4"); + addLine("n4", "n3"); + addLine("n3", "n1"); + addLine("f1", "f2"); + addLine("f2", "f4"); + addLine("f4", "f3"); + addLine("f3", "f1"); + addLine("n1", "f1"); + addLine("n2", "f2"); + addLine("n3", "f3"); + addLine("n4", "f4"); + addLine("p", "n1"); + addLine("p", "n2"); + addLine("p", "n3"); + addLine("p", "n4"); + addLine("u1", "u2"); + addLine("u2", "u3"); + addLine("u3", "u1"); + addLine("c", "t"); + addLine("p", "c"); + addLine("cn1", "cn2"); + addLine("cn3", "cn4"); + addLine("cf1", "cf2"); + addLine("cf3", "cf4"); + function addLine(a2, b2) { + addPoint(a2); + addPoint(b2); + } + function addPoint(id) { + vertices.push(0, 0, 0); + colors.push(0, 0, 0); + if (pointMap[id] === undefined) { + pointMap[id] = []; + } + pointMap[id].push(vertices.length / 3 - 1); + } + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + super(geometry, material); + this.type = "CameraHelper"; + this.camera = camera; + if (this.camera.updateProjectionMatrix) + this.camera.updateProjectionMatrix(); + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; + this.pointMap = pointMap; + this.update(); + const colorFrustum = new Color2(16755200); + const colorCone = new Color2(16711680); + const colorUp = new Color2(43775); + const colorTarget = new Color2(16777215); + const colorCross = new Color2(3355443); + this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross); + } + setColors(frustum, cone, up, target, cross) { + const geometry = this.geometry; + const colorAttribute = geometry.getAttribute("color"); + colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(24, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(26, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(28, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(30, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(32, up.r, up.g, up.b); + colorAttribute.setXYZ(33, up.r, up.g, up.b); + colorAttribute.setXYZ(34, up.r, up.g, up.b); + colorAttribute.setXYZ(35, up.r, up.g, up.b); + colorAttribute.setXYZ(36, up.r, up.g, up.b); + colorAttribute.setXYZ(37, up.r, up.g, up.b); + colorAttribute.setXYZ(38, target.r, target.g, target.b); + colorAttribute.setXYZ(39, target.r, target.g, target.b); + colorAttribute.setXYZ(40, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(42, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(44, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(46, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(48, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); + colorAttribute.needsUpdate = true; + } + update() { + const geometry = this.geometry; + const pointMap = this.pointMap; + const w = 1, h = 1; + _camera3.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); + const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem2 ? -1 : 0; + setPoint2("c", pointMap, geometry, _camera3, 0, 0, nearZ); + setPoint2("t", pointMap, geometry, _camera3, 0, 0, 1); + setPoint2("n1", pointMap, geometry, _camera3, -w, -h, nearZ); + setPoint2("n2", pointMap, geometry, _camera3, w, -h, nearZ); + setPoint2("n3", pointMap, geometry, _camera3, -w, h, nearZ); + setPoint2("n4", pointMap, geometry, _camera3, w, h, nearZ); + setPoint2("f1", pointMap, geometry, _camera3, -w, -h, 1); + setPoint2("f2", pointMap, geometry, _camera3, w, -h, 1); + setPoint2("f3", pointMap, geometry, _camera3, -w, h, 1); + setPoint2("f4", pointMap, geometry, _camera3, w, h, 1); + setPoint2("u1", pointMap, geometry, _camera3, w * 0.7, h * 1.1, nearZ); + setPoint2("u2", pointMap, geometry, _camera3, -w * 0.7, h * 1.1, nearZ); + setPoint2("u3", pointMap, geometry, _camera3, 0, h * 2, nearZ); + setPoint2("cf1", pointMap, geometry, _camera3, -w, 0, 1); + setPoint2("cf2", pointMap, geometry, _camera3, w, 0, 1); + setPoint2("cf3", pointMap, geometry, _camera3, 0, -h, 1); + setPoint2("cf4", pointMap, geometry, _camera3, 0, h, 1); + setPoint2("cn1", pointMap, geometry, _camera3, -w, 0, nearZ); + setPoint2("cn2", pointMap, geometry, _camera3, w, 0, nearZ); + setPoint2("cn3", pointMap, geometry, _camera3, 0, -h, nearZ); + setPoint2("cn4", pointMap, geometry, _camera3, 0, h, nearZ); + geometry.getAttribute("position").needsUpdate = true; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + function setPoint2(point, pointMap, geometry, camera, x2, y, z) { + _vector5.set(x2, y, z).unproject(camera); + const points = pointMap[point]; + if (points !== undefined) { + const position2 = geometry.getAttribute("position"); + for (let i = 0, l2 = points.length;i < l2; i++) { + position2.setXYZ(points[i], _vector5.x, _vector5.y, _vector5.z); + } + } + } + var _box5 = /* @__PURE__ */ new Box32; + + class BoxHelper2 extends LineSegments3 { + constructor(object, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = new Float32Array(8 * 3); + const geometry = new BufferGeometry2; + geometry.setIndex(new BufferAttribute2(indices, 1)); + geometry.setAttribute("position", new BufferAttribute2(positions, 3)); + super(geometry, new LineBasicMaterial2({ color, toneMapped: false })); + this.object = object; + this.type = "BoxHelper"; + this.matrixAutoUpdate = false; + this.update(); + } + update(object) { + if (object !== undefined) { + console.warn("THREE.BoxHelper: .update() has no longer arguments."); + } + if (this.object !== undefined) { + _box5.setFromObject(this.object); + } + if (_box5.isEmpty()) + return; + const min = _box5.min; + const max = _box5.max; + const position2 = this.geometry.attributes.position; + const array = position2.array; + array[0] = max.x; + array[1] = max.y; + array[2] = max.z; + array[3] = min.x; + array[4] = max.y; + array[5] = max.z; + array[6] = min.x; + array[7] = min.y; + array[8] = max.z; + array[9] = max.x; + array[10] = min.y; + array[11] = max.z; + array[12] = max.x; + array[13] = max.y; + array[14] = min.z; + array[15] = min.x; + array[16] = max.y; + array[17] = min.z; + array[18] = min.x; + array[19] = min.y; + array[20] = min.z; + array[21] = max.x; + array[22] = min.y; + array[23] = min.z; + position2.needsUpdate = true; + this.geometry.computeBoundingSphere(); + } + setFromObject(object) { + this.object = object; + this.update(); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + this.object = source.object; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + + class Box3Helper2 extends LineSegments3 { + constructor(box, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1]; + const geometry = new BufferGeometry2; + geometry.setIndex(new BufferAttribute2(indices, 1)); + geometry.setAttribute("position", new Float32BufferAttribute2(positions, 3)); + super(geometry, new LineBasicMaterial2({ color, toneMapped: false })); + this.box = box; + this.type = "Box3Helper"; + this.geometry.computeBoundingSphere(); + } + updateMatrixWorld(force) { + const box = this.box; + if (box.isEmpty()) + return; + box.getCenter(this.position); + box.getSize(this.scale); + this.scale.multiplyScalar(0.5); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + + class PlaneHelper2 extends Line4 { + constructor(plane, size2 = 1, hex = 16776960) { + const color = hex; + const positions = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0]; + const geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2(positions, 3)); + geometry.computeBoundingSphere(); + super(geometry, new LineBasicMaterial2({ color, toneMapped: false })); + this.type = "PlaneHelper"; + this.plane = plane; + this.size = size2; + const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0]; + const geometry2 = new BufferGeometry2; + geometry2.setAttribute("position", new Float32BufferAttribute2(positions2, 3)); + geometry2.computeBoundingSphere(); + this.add(new Mesh2(geometry2, new MeshBasicMaterial2({ color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false }))); + } + updateMatrixWorld(force) { + this.position.set(0, 0, 0); + this.scale.set(0.5 * this.size, 0.5 * this.size, 1); + this.lookAt(this.plane.normal); + this.translateZ(-this.plane.constant); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + } + var _axis4 = /* @__PURE__ */ new Vector32; + var _lineGeometry2; + var _coneGeometry2; + + class ArrowHelper2 extends Object3D2 { + constructor(dir = new Vector32(0, 0, 1), origin = new Vector32(0, 0, 0), length2 = 1, color = 16776960, headLength = length2 * 0.2, headWidth = headLength * 0.2) { + super(); + this.type = "ArrowHelper"; + if (_lineGeometry2 === undefined) { + _lineGeometry2 = new BufferGeometry2; + _lineGeometry2.setAttribute("position", new Float32BufferAttribute2([0, 0, 0, 0, 1, 0], 3)); + _coneGeometry2 = new CylinderGeometry2(0, 0.5, 1, 5, 1); + _coneGeometry2.translate(0, -0.5, 0); + } + this.position.copy(origin); + this.line = new Line4(_lineGeometry2, new LineBasicMaterial2({ color, toneMapped: false })); + this.line.matrixAutoUpdate = false; + this.add(this.line); + this.cone = new Mesh2(_coneGeometry2, new MeshBasicMaterial2({ color, toneMapped: false })); + this.cone.matrixAutoUpdate = false; + this.add(this.cone); + this.setDirection(dir); + this.setLength(length2, headLength, headWidth); + } + setDirection(dir) { + if (dir.y > 0.99999) { + this.quaternion.set(0, 0, 0, 1); + } else if (dir.y < -0.99999) { + this.quaternion.set(1, 0, 0, 0); + } else { + _axis4.set(dir.z, 0, -dir.x).normalize(); + const radians = Math.acos(dir.y); + this.quaternion.setFromAxisAngle(_axis4, radians); + } + } + setLength(length2, headLength = length2 * 0.2, headWidth = headLength * 0.2) { + this.line.scale.set(1, Math.max(0.0001, length2 - headLength), 1); + this.line.updateMatrix(); + this.cone.scale.set(headWidth, headLength, headWidth); + this.cone.position.y = length2; + this.cone.updateMatrix(); + } + setColor(color) { + this.line.material.color.set(color); + this.cone.material.color.set(color); + } + copy(source) { + super.copy(source, false); + this.line.copy(source.line); + this.cone.copy(source.cone); + return this; + } + dispose() { + this.line.geometry.dispose(); + this.line.material.dispose(); + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + } + + class AxesHelper2 extends LineSegments3 { + constructor(size2 = 1) { + const vertices = [ + 0, + 0, + 0, + size2, + 0, + 0, + 0, + 0, + 0, + 0, + size2, + 0, + 0, + 0, + 0, + 0, + 0, + size2 + ]; + const colors = [ + 1, + 0, + 0, + 1, + 0.6, + 0, + 0, + 1, + 0, + 0.6, + 1, + 0, + 0, + 0, + 1, + 0, + 0.6, + 1 + ]; + const geometry = new BufferGeometry2; + geometry.setAttribute("position", new Float32BufferAttribute2(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute2(colors, 3)); + const material = new LineBasicMaterial2({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "AxesHelper"; + } + setColors(xAxisColor, yAxisColor, zAxisColor) { + const color = new Color2; + const array = this.geometry.attributes.color.array; + color.set(xAxisColor); + color.toArray(array, 0); + color.toArray(array, 3); + color.set(yAxisColor); + color.toArray(array, 6); + color.toArray(array, 9); + color.set(zAxisColor); + color.toArray(array, 12); + color.toArray(array, 15); + this.geometry.attributes.color.needsUpdate = true; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + } + + class ShapePath3 { + constructor() { + this.type = "ShapePath"; + this.color = new Color2; + this.subPaths = []; + this.currentPath = null; + } + moveTo(x2, y) { + this.currentPath = new Path3; + this.subPaths.push(this.currentPath); + this.currentPath.moveTo(x2, y); + return this; + } + lineTo(x2, y) { + this.currentPath.lineTo(x2, y); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY); + return this; + } + splineThru(pts) { + this.currentPath.splineThru(pts); + return this; + } + toShapes(isCCW) { + function toShapesNoHoles(inSubpaths) { + const shapes2 = []; + for (let i = 0, l2 = inSubpaths.length;i < l2; i++) { + const tmpPath2 = inSubpaths[i]; + const tmpShape2 = new Shape2; + tmpShape2.curves = tmpPath2.curves; + shapes2.push(tmpShape2); + } + return shapes2; + } + function isPointInsidePolygon(inPt, inPolygon) { + const polyLen = inPolygon.length; + let inside = false; + for (let p = polyLen - 1, q2 = 0;q2 < polyLen; p = q2++) { + let edgeLowPt = inPolygon[p]; + let edgeHighPt = inPolygon[q2]; + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; + if (Math.abs(edgeDy) > Number.EPSILON) { + if (edgeDy < 0) { + edgeLowPt = inPolygon[q2]; + edgeDx = -edgeDx; + edgeHighPt = inPolygon[p]; + edgeDy = -edgeDy; + } + if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) + continue; + if (inPt.y === edgeLowPt.y) { + if (inPt.x === edgeLowPt.x) + return true; + } else { + const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); + if (perpEdge === 0) + return true; + if (perpEdge < 0) + continue; + inside = !inside; + } + } else { + if (inPt.y !== edgeLowPt.y) + continue; + if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) + return true; + } + } + return inside; + } + const isClockWise = ShapeUtils2.isClockWise; + const subPaths = this.subPaths; + if (subPaths.length === 0) + return []; + let solid, tmpPath, tmpShape; + const shapes = []; + if (subPaths.length === 1) { + tmpPath = subPaths[0]; + tmpShape = new Shape2; + tmpShape.curves = tmpPath.curves; + shapes.push(tmpShape); + return shapes; + } + let holesFirst = !isClockWise(subPaths[0].getPoints()); + holesFirst = isCCW ? !holesFirst : holesFirst; + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; + newShapes[mainIdx] = undefined; + newShapeHoles[mainIdx] = []; + for (let i = 0, l2 = subPaths.length;i < l2; i++) { + tmpPath = subPaths[i]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise(tmpPoints); + solid = isCCW ? !solid : solid; + if (solid) { + if (!holesFirst && newShapes[mainIdx]) + mainIdx++; + newShapes[mainIdx] = { s: new Shape2, p: tmpPoints }; + newShapes[mainIdx].s.curves = tmpPath.curves; + if (holesFirst) + mainIdx++; + newShapeHoles[mainIdx] = []; + } else { + newShapeHoles[mainIdx].push({ h: tmpPath, p: tmpPoints[0] }); + } + } + if (!newShapes[0]) + return toShapesNoHoles(subPaths); + if (newShapes.length > 1) { + let ambiguous = false; + let toChange = 0; + for (let sIdx = 0, sLen = newShapes.length;sIdx < sLen; sIdx++) { + betterShapeHoles[sIdx] = []; + } + for (let sIdx = 0, sLen = newShapes.length;sIdx < sLen; sIdx++) { + const sho = newShapeHoles[sIdx]; + for (let hIdx = 0;hIdx < sho.length; hIdx++) { + const ho = sho[hIdx]; + let hole_unassigned = true; + for (let s2Idx = 0;s2Idx < newShapes.length; s2Idx++) { + if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) { + if (sIdx !== s2Idx) + toChange++; + if (hole_unassigned) { + hole_unassigned = false; + betterShapeHoles[s2Idx].push(ho); + } else { + ambiguous = true; + } + } + } + if (hole_unassigned) { + betterShapeHoles[sIdx].push(ho); + } + } + } + if (toChange > 0 && ambiguous === false) { + newShapeHoles = betterShapeHoles; + } + } + let tmpHoles; + for (let i = 0, il = newShapes.length;i < il; i++) { + tmpShape = newShapes[i].s; + shapes.push(tmpShape); + tmpHoles = newShapeHoles[i]; + for (let j2 = 0, jl = tmpHoles.length;j2 < jl; j2++) { + tmpShape.holes.push(tmpHoles[j2].h); + } + } + return shapes; + } + } + + class Controls2 extends EventDispatcher2 { + constructor(object, domElement = null) { + super(); + this.object = object; + this.domElement = domElement; + this.enabled = true; + this.state = -1; + this.keys = {}; + this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null }; + this.touches = { ONE: null, TWO: null }; + } + connect() { + } + disconnect() { + } + dispose() { + } + update() { + } + } + function contain2(texture, aspect3) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect3) { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect3; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } else { + texture.repeat.x = aspect3 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } + return texture; + } + function cover2(texture, aspect3) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect3) { + texture.repeat.x = aspect3 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } else { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect3; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } + return texture; + } + function fill2(texture) { + texture.repeat.x = 1; + texture.repeat.y = 1; + texture.offset.x = 0; + texture.offset.y = 0; + return texture; + } + function getByteLength2(width2, height2, format, type) { + const typeByteLength = getTextureTypeByteLength2(type); + switch (format) { + case AlphaFormat2: + return width2 * height2; + case LuminanceFormat2: + return width2 * height2; + case LuminanceAlphaFormat2: + return width2 * height2 * 2; + case RedFormat2: + return width2 * height2 / typeByteLength.components * typeByteLength.byteLength; + case RedIntegerFormat2: + return width2 * height2 / typeByteLength.components * typeByteLength.byteLength; + case RGFormat2: + return width2 * height2 * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGIntegerFormat2: + return width2 * height2 * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGBFormat2: + return width2 * height2 * 3 / typeByteLength.components * typeByteLength.byteLength; + case RGBAFormat2: + return width2 * height2 * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGBAIntegerFormat2: + return width2 * height2 * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGB_S3TC_DXT1_Format2: + case RGBA_S3TC_DXT1_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 8; + case RGBA_S3TC_DXT3_Format2: + case RGBA_S3TC_DXT5_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGB_PVRTC_2BPPV1_Format2: + case RGBA_PVRTC_2BPPV1_Format2: + return Math.max(width2, 16) * Math.max(height2, 8) / 4; + case RGB_PVRTC_4BPPV1_Format2: + case RGBA_PVRTC_4BPPV1_Format2: + return Math.max(width2, 8) * Math.max(height2, 8) / 2; + case RGB_ETC1_Format2: + case RGB_ETC2_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 8; + case RGBA_ETC2_EAC_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_4x4_Format2: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_5x4_Format2: + return Math.floor((width2 + 4) / 5) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_5x5_Format2: + return Math.floor((width2 + 4) / 5) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_6x5_Format2: + return Math.floor((width2 + 5) / 6) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_6x6_Format2: + return Math.floor((width2 + 5) / 6) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_8x5_Format2: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_8x6_Format2: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_8x8_Format2: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 7) / 8) * 16; + case RGBA_ASTC_10x5_Format2: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_10x6_Format2: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_10x8_Format2: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 7) / 8) * 16; + case RGBA_ASTC_10x10_Format2: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 9) / 10) * 16; + case RGBA_ASTC_12x10_Format2: + return Math.floor((width2 + 11) / 12) * Math.floor((height2 + 9) / 10) * 16; + case RGBA_ASTC_12x12_Format2: + return Math.floor((width2 + 11) / 12) * Math.floor((height2 + 11) / 12) * 16; + case RGBA_BPTC_Format2: + case RGB_BPTC_SIGNED_Format2: + case RGB_BPTC_UNSIGNED_Format2: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 16; + case RED_RGTC1_Format2: + case SIGNED_RED_RGTC1_Format2: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 8; + case RED_GREEN_RGTC2_Format2: + case SIGNED_RED_GREEN_RGTC2_Format2: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 16; + } + throw new Error(`Unable to determine texture byte length for ${format} format.`); + } + function getTextureTypeByteLength2(type) { + switch (type) { + case UnsignedByteType2: + case ByteType2: + return { byteLength: 1, components: 1 }; + case UnsignedShortType2: + case ShortType2: + case HalfFloatType2: + return { byteLength: 2, components: 1 }; + case UnsignedShort4444Type2: + case UnsignedShort5551Type2: + return { byteLength: 2, components: 4 }; + case UnsignedIntType2: + case IntType2: + case FloatType2: + return { byteLength: 4, components: 1 }; + case UnsignedInt5999Type2: + return { byteLength: 4, components: 3 }; + } + throw new Error(`Unknown texture type ${type}.`); + } + var TextureUtils2 = { + contain: contain2, + cover: cover2, + fill: fill2, + getByteLength: getByteLength2 + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { + revision: REVISION2 + } })); + } + if (typeof window !== "undefined") { + if (window.__THREE__) { + console.warn("WARNING: Multiple instances of Three.js being imported."); + } else { + window.__THREE__ = REVISION2; + } + } + function WebGLAnimation2() { + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + function onAnimationFrame(time2, frame) { + animationLoop(time2, frame); + requestId = context.requestAnimationFrame(onAnimationFrame); + } + return { + start: function() { + if (isAnimating === true) + return; + if (animationLoop === null) + return; + requestId = context.requestAnimationFrame(onAnimationFrame); + isAnimating = true; + }, + stop: function() { + context.cancelAnimationFrame(requestId); + isAnimating = false; + }, + setAnimationLoop: function(callback) { + animationLoop = callback; + }, + setContext: function(value2) { + context = value2; + } + }; + } + function WebGLAttributes2(gl) { + const buffers = new WeakMap; + function createBuffer(attribute, bufferType) { + const array = attribute.array; + const usage = attribute.usage; + const size2 = array.byteLength; + const buffer = gl.createBuffer(); + gl.bindBuffer(bufferType, buffer); + gl.bufferData(bufferType, array, usage); + attribute.onUploadCallback(); + let type; + if (array instanceof Float32Array) { + type = gl.FLOAT; + } else if (array instanceof Uint16Array) { + if (attribute.isFloat16BufferAttribute) { + type = gl.HALF_FLOAT; + } else { + type = gl.UNSIGNED_SHORT; + } + } else if (array instanceof Int16Array) { + type = gl.SHORT; + } else if (array instanceof Uint32Array) { + type = gl.UNSIGNED_INT; + } else if (array instanceof Int32Array) { + type = gl.INT; + } else if (array instanceof Int8Array) { + type = gl.BYTE; + } else if (array instanceof Uint8Array) { + type = gl.UNSIGNED_BYTE; + } else if (array instanceof Uint8ClampedArray) { + type = gl.UNSIGNED_BYTE; + } else { + throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + array); + } + return { + buffer, + type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version, + size: size2 + }; + } + function updateBuffer(buffer, attribute, bufferType) { + const array = attribute.array; + const updateRanges = attribute.updateRanges; + gl.bindBuffer(bufferType, buffer); + if (updateRanges.length === 0) { + gl.bufferSubData(bufferType, 0, array); + } else { + updateRanges.sort((a2, b2) => a2.start - b2.start); + let mergeIndex = 0; + for (let i = 1;i < updateRanges.length; i++) { + const previousRange = updateRanges[mergeIndex]; + const range = updateRanges[i]; + if (range.start <= previousRange.start + previousRange.count + 1) { + previousRange.count = Math.max(previousRange.count, range.start + range.count - previousRange.start); + } else { + ++mergeIndex; + updateRanges[mergeIndex] = range; + } + } + updateRanges.length = mergeIndex + 1; + for (let i = 0, l2 = updateRanges.length;i < l2; i++) { + const range = updateRanges[i]; + gl.bufferSubData(bufferType, range.start * array.BYTES_PER_ELEMENT, array, range.start, range.count); + } + attribute.clearUpdateRanges(); + } + attribute.onUploadCallback(); + } + function get(attribute) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + return buffers.get(attribute); + } + function remove(attribute) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + const data2 = buffers.get(attribute); + if (data2) { + gl.deleteBuffer(data2.buffer); + buffers.delete(attribute); + } + } + function update(attribute, bufferType) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + if (attribute.isGLBufferAttribute) { + const cached = buffers.get(attribute); + if (!cached || cached.version < attribute.version) { + buffers.set(attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + }); + } + return; + } + const data2 = buffers.get(attribute); + if (data2 === undefined) { + buffers.set(attribute, createBuffer(attribute, bufferType)); + } else if (data2.version < attribute.version) { + if (data2.size !== attribute.array.byteLength) { + throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported."); + } + updateBuffer(data2.buffer, attribute, bufferType); + data2.version = attribute.version; + } + } + return { + get, + remove, + update + }; + } + var alphahash_fragment2 = `#ifdef USE_ALPHAHASH + if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard; +#endif`; + var alphahash_pars_fragment2 = `#ifdef USE_ALPHAHASH + const float ALPHA_HASH_SCALE = 0.05; + float hash2D( vec2 value ) { + return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) ); + } + float hash3D( vec3 value ) { + return hash2D( vec2( hash2D( value.xy ), value.z ) ); + } + float getAlphaHashThreshold( vec3 position ) { + float maxDeriv = max( + length( dFdx( position.xyz ) ), + length( dFdy( position.xyz ) ) + ); + float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv ); + vec2 pixScales = vec2( + exp2( floor( log2( pixScale ) ) ), + exp2( ceil( log2( pixScale ) ) ) + ); + vec2 alpha = vec2( + hash3D( floor( pixScales.x * position.xyz ) ), + hash3D( floor( pixScales.y * position.xyz ) ) + ); + float lerpFactor = fract( log2( pixScale ) ); + float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y; + float a = min( lerpFactor, 1.0 - lerpFactor ); + vec3 cases = vec3( + x * x / ( 2.0 * a * ( 1.0 - a ) ), + ( x - 0.5 * a ) / ( 1.0 - a ), + 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) ) + ); + float threshold = ( x < ( 1.0 - a ) ) + ? ( ( x < a ) ? cases.x : cases.y ) + : cases.z; + return clamp( threshold , 1.0e-6, 1.0 ); + } +#endif`; + var alphamap_fragment2 = `#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g; +#endif`; + var alphamap_pars_fragment2 = `#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`; + var alphatest_fragment2 = `#ifdef USE_ALPHATEST + #ifdef ALPHA_TO_COVERAGE + diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a ); + if ( diffuseColor.a == 0.0 ) discard; + #else + if ( diffuseColor.a < alphaTest ) discard; + #endif +#endif`; + var alphatest_pars_fragment2 = `#ifdef USE_ALPHATEST + uniform float alphaTest; +#endif`; + var aomap_fragment2 = `#ifdef USE_AOMAP + float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0; + reflectedLight.indirectDiffuse *= ambientOcclusion; + #if defined( USE_CLEARCOAT ) + clearcoatSpecularIndirect *= ambientOcclusion; + #endif + #if defined( USE_SHEEN ) + sheenSpecularIndirect *= ambientOcclusion; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) + float dotNV = saturate( dot( geometryNormal, geometryViewDir ) ); + reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness ); + #endif +#endif`; + var aomap_pars_fragment2 = `#ifdef USE_AOMAP + uniform sampler2D aoMap; + uniform float aoMapIntensity; +#endif`; + var batching_pars_vertex2 = `#ifdef USE_BATCHING + #if ! defined( GL_ANGLE_multi_draw ) + #define gl_DrawID _gl_DrawID + uniform int _gl_DrawID; + #endif + uniform highp sampler2D batchingTexture; + uniform highp usampler2D batchingIdTexture; + mat4 getBatchingMatrix( const in float i ) { + int size = textureSize( batchingTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } + float getIndirectIndex( const in int i ) { + int size = textureSize( batchingIdTexture, 0 ).x; + int x = i % size; + int y = i / size; + return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r ); + } +#endif +#ifdef USE_BATCHING_COLOR + uniform sampler2D batchingColorTexture; + vec3 getBatchingColor( const in float i ) { + int size = textureSize( batchingColorTexture, 0 ).x; + int j = int( i ); + int x = j % size; + int y = j / size; + return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb; + } +#endif`; + var batching_vertex2 = `#ifdef USE_BATCHING + mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) ); +#endif`; + var begin_vertex2 = `vec3 transformed = vec3( position ); +#ifdef USE_ALPHAHASH + vPosition = vec3( position ); +#endif`; + var beginnormal_vertex2 = `vec3 objectNormal = vec3( normal ); +#ifdef USE_TANGENT + vec3 objectTangent = vec3( tangent.xyz ); +#endif`; + var bsdfs2 = `float G_BlinnPhong_Implicit( ) { + return 0.25; +} +float D_BlinnPhong( const in float shininess, const in float dotNH ) { + return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess ); +} +vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( specularColor, 1.0, dotVH ); + float G = G_BlinnPhong_Implicit( ); + float D = D_BlinnPhong( shininess, dotNH ); + return F * ( G * D ); +} // validated`; + var iridescence_fragment2 = `#ifdef USE_IRIDESCENCE + const mat3 XYZ_TO_REC709 = mat3( + 3.2404542, -0.9692660, 0.0556434, + -1.5371385, 1.8760108, -0.2040259, + -0.4985314, 0.0415560, 1.0572252 + ); + vec3 Fresnel0ToIor( vec3 fresnel0 ) { + vec3 sqrtF0 = sqrt( fresnel0 ); + return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 ); + } + vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) { + return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) ); + } + float IorToFresnel0( float transmittedIor, float incidentIor ) { + return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor )); + } + vec3 evalSensitivity( float OPD, vec3 shift ) { + float phase = 2.0 * PI * OPD * 1.0e-9; + vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 ); + vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 ); + vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 ); + vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var ); + xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) ); + xyz /= 1.0685e-7; + vec3 rgb = XYZ_TO_REC709 * xyz; + return rgb; + } + vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) { + vec3 I; + float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) ); + float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) ); + float cosTheta2Sq = 1.0 - sinTheta2Sq; + if ( cosTheta2Sq < 0.0 ) { + return vec3( 1.0 ); + } + float cosTheta2 = sqrt( cosTheta2Sq ); + float R0 = IorToFresnel0( iridescenceIOR, outsideIOR ); + float R12 = F_Schlick( R0, 1.0, cosTheta1 ); + float T121 = 1.0 - R12; + float phi12 = 0.0; + if ( iridescenceIOR < outsideIOR ) phi12 = PI; + float phi21 = PI - phi12; + vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR ); + vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 ); + vec3 phi23 = vec3( 0.0 ); + if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI; + if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI; + if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI; + float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2; + vec3 phi = vec3( phi21 ) + phi23; + vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 ); + vec3 r123 = sqrt( R123 ); + vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 ); + vec3 C0 = R12 + Rs; + I = C0; + vec3 Cm = Rs - T121; + for ( int m = 1; m <= 2; ++ m ) { + Cm *= r123; + vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi ); + I += Cm * Sm; + } + return max( I, vec3( 0.0 ) ); + } +#endif`; + var bumpmap_pars_fragment2 = `#ifdef USE_BUMPMAP + uniform sampler2D bumpMap; + uniform float bumpScale; + vec2 dHdxy_fwd() { + vec2 dSTdx = dFdx( vBumpMapUv ); + vec2 dSTdy = dFdy( vBumpMapUv ); + float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x; + float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll; + float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll; + return vec2( dBx, dBy ); + } + vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) { + vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) ); + vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) ); + vec3 vN = surf_norm; + vec3 R1 = cross( vSigmaY, vN ); + vec3 R2 = cross( vN, vSigmaX ); + float fDet = dot( vSigmaX, R1 ) * faceDirection; + vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 ); + return normalize( abs( fDet ) * surf_norm - vGrad ); + } +#endif`; + var clipping_planes_fragment2 = `#if NUM_CLIPPING_PLANES > 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`; + var clipping_planes_pars_fragment2 = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`; + var clipping_planes_pars_vertex2 = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`; + var clipping_planes_vertex2 = `#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`; + var color_fragment2 = `#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`; + var color_pars_fragment2 = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`; + var color_pars_vertex2 = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`; + var color_vertex2 = `#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`; + var common2 = `#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`; + var cube_uv_reflection_fragment2 = `#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`; + var defaultnormal_vertex2 = `vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`; + var displacementmap_pars_vertex2 = `#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`; + var displacementmap_vertex2 = `#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`; + var emissivemap_fragment2 = `#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`; + var emissivemap_pars_fragment2 = `#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`; + var colorspace_fragment2 = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; + var colorspace_pars_fragment2 = `vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`; + var envmap_fragment2 = `#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`; + var envmap_common_pars_fragment2 = `#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`; + var envmap_pars_fragment2 = `#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`; + var envmap_pars_vertex2 = `#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`; + var envmap_vertex2 = `#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`; + var fog_vertex2 = `#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`; + var fog_pars_vertex2 = `#ifdef USE_FOG + varying float vFogDepth; +#endif`; + var fog_fragment2 = `#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`; + var fog_pars_fragment2 = `#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`; + var gradientmap_pars_fragment2 = `#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`; + var lightmap_pars_fragment2 = `#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`; + var lights_lambert_fragment2 = `LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`; + var lights_lambert_pars_fragment2 = `varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`; + var lights_pars_begin2 = `uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`; + var envmap_physical_pars_fragment2 = `#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`; + var lights_toon_fragment2 = `ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`; + var lights_toon_pars_fragment2 = `varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`; + var lights_phong_fragment2 = `BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`; + var lights_phong_pars_fragment2 = `varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`; + var lights_physical_fragment2 = `PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`; + var lights_physical_pars_fragment2 = `struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`; + var lights_fragment_begin2 = ` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`; + var lights_fragment_maps2 = `#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`; + var lights_fragment_end2 = `#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`; + var logdepthbuf_fragment2 = `#if defined( USE_LOGDEPTHBUF ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`; + var logdepthbuf_pars_fragment2 = `#if defined( USE_LOGDEPTHBUF ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`; + var logdepthbuf_pars_vertex2 = `#ifdef USE_LOGDEPTHBUF + varying float vFragDepth; + varying float vIsPerspective; +#endif`; + var logdepthbuf_vertex2 = `#ifdef USE_LOGDEPTHBUF + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`; + var map_fragment2 = `#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`; + var map_pars_fragment2 = `#ifdef USE_MAP + uniform sampler2D map; +#endif`; + var map_particle_fragment2 = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`; + var map_particle_pars_fragment2 = `#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`; + var metalnessmap_fragment2 = `float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`; + var metalnessmap_pars_fragment2 = `#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`; + var morphinstance_vertex2 = `#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`; + var morphcolor_vertex2 = `#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`; + var morphnormal_vertex2 = `#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`; + var morphtarget_pars_vertex2 = `#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`; + var morphtarget_vertex2 = `#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`; + var normal_fragment_begin2 = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`; + var normal_fragment_maps2 = `#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`; + var normal_pars_fragment2 = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`; + var normal_pars_vertex2 = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`; + var normal_vertex2 = `#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`; + var normalmap_pars_fragment2 = `#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`; + var clearcoat_normal_fragment_begin2 = `#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`; + var clearcoat_normal_fragment_maps2 = `#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`; + var clearcoat_pars_fragment2 = `#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`; + var iridescence_pars_fragment2 = `#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`; + var opaque_fragment2 = `#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`; + var packing2 = `vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`; + var premultiplied_alpha_fragment2 = `#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`; + var project_vertex2 = `vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`; + var dithering_fragment2 = `#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`; + var dithering_pars_fragment2 = `#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`; + var roughnessmap_fragment2 = `float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`; + var roughnessmap_pars_fragment2 = `#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`; + var shadowmap_pars_fragment2 = `#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`; + var shadowmap_pars_vertex2 = `#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`; + var shadowmap_vertex2 = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`; + var shadowmask_pars_fragment2 = `float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`; + var skinbase_vertex2 = `#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`; + var skinning_pars_vertex2 = `#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`; + var skinning_vertex2 = `#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`; + var skinnormal_vertex2 = `#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`; + var specularmap_fragment2 = `float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`; + var specularmap_pars_fragment2 = `#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`; + var tonemapping_fragment2 = `#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`; + var tonemapping_pars_fragment2 = `#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`; + var transmission_fragment2 = `#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`; + var transmission_pars_fragment2 = `#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`; + var uv_pars_fragment2 = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`; + var uv_pars_vertex2 = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`; + var uv_vertex2 = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`; + var worldpos_vertex2 = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`; + var vertex$h2 = `varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`; + var fragment$h2 = `uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`; + var vertex$g2 = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`; + var fragment$g2 = `#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`; + var vertex$f2 = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`; + var fragment$f2 = `uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`; + var vertex$e2 = `#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`; + var fragment$e2 = `#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`; + var vertex$d2 = `#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`; + var fragment$d2 = `#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`; + var vertex$c2 = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`; + var fragment$c2 = `uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`; + var vertex$b2 = `uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; + var fragment$b2 = `uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`; + var vertex$a2 = `#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; + var fragment$a2 = `uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`; + var vertex$92 = `#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`; + var fragment$92 = `#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`; + var vertex$82 = `#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`; + var fragment$82 = `#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`; + var vertex$72 = `#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`; + var fragment$72 = `#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`; + var vertex$62 = `#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`; + var fragment$62 = `#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`; + var vertex$52 = `#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`; + var fragment$52 = `#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`; + var vertex$42 = `#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`; + var fragment$42 = `#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`; + var vertex$32 = `uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`; + var fragment$32 = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`; + var vertex$22 = `#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; + var fragment$22 = `uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`; + var vertex$12 = `uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`; + var fragment$12 = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`; + var ShaderChunk2 = { + alphahash_fragment: alphahash_fragment2, + alphahash_pars_fragment: alphahash_pars_fragment2, + alphamap_fragment: alphamap_fragment2, + alphamap_pars_fragment: alphamap_pars_fragment2, + alphatest_fragment: alphatest_fragment2, + alphatest_pars_fragment: alphatest_pars_fragment2, + aomap_fragment: aomap_fragment2, + aomap_pars_fragment: aomap_pars_fragment2, + batching_pars_vertex: batching_pars_vertex2, + batching_vertex: batching_vertex2, + begin_vertex: begin_vertex2, + beginnormal_vertex: beginnormal_vertex2, + bsdfs: bsdfs2, + iridescence_fragment: iridescence_fragment2, + bumpmap_pars_fragment: bumpmap_pars_fragment2, + clipping_planes_fragment: clipping_planes_fragment2, + clipping_planes_pars_fragment: clipping_planes_pars_fragment2, + clipping_planes_pars_vertex: clipping_planes_pars_vertex2, + clipping_planes_vertex: clipping_planes_vertex2, + color_fragment: color_fragment2, + color_pars_fragment: color_pars_fragment2, + color_pars_vertex: color_pars_vertex2, + color_vertex: color_vertex2, + common: common2, + cube_uv_reflection_fragment: cube_uv_reflection_fragment2, + defaultnormal_vertex: defaultnormal_vertex2, + displacementmap_pars_vertex: displacementmap_pars_vertex2, + displacementmap_vertex: displacementmap_vertex2, + emissivemap_fragment: emissivemap_fragment2, + emissivemap_pars_fragment: emissivemap_pars_fragment2, + colorspace_fragment: colorspace_fragment2, + colorspace_pars_fragment: colorspace_pars_fragment2, + envmap_fragment: envmap_fragment2, + envmap_common_pars_fragment: envmap_common_pars_fragment2, + envmap_pars_fragment: envmap_pars_fragment2, + envmap_pars_vertex: envmap_pars_vertex2, + envmap_physical_pars_fragment: envmap_physical_pars_fragment2, + envmap_vertex: envmap_vertex2, + fog_vertex: fog_vertex2, + fog_pars_vertex: fog_pars_vertex2, + fog_fragment: fog_fragment2, + fog_pars_fragment: fog_pars_fragment2, + gradientmap_pars_fragment: gradientmap_pars_fragment2, + lightmap_pars_fragment: lightmap_pars_fragment2, + lights_lambert_fragment: lights_lambert_fragment2, + lights_lambert_pars_fragment: lights_lambert_pars_fragment2, + lights_pars_begin: lights_pars_begin2, + lights_toon_fragment: lights_toon_fragment2, + lights_toon_pars_fragment: lights_toon_pars_fragment2, + lights_phong_fragment: lights_phong_fragment2, + lights_phong_pars_fragment: lights_phong_pars_fragment2, + lights_physical_fragment: lights_physical_fragment2, + lights_physical_pars_fragment: lights_physical_pars_fragment2, + lights_fragment_begin: lights_fragment_begin2, + lights_fragment_maps: lights_fragment_maps2, + lights_fragment_end: lights_fragment_end2, + logdepthbuf_fragment: logdepthbuf_fragment2, + logdepthbuf_pars_fragment: logdepthbuf_pars_fragment2, + logdepthbuf_pars_vertex: logdepthbuf_pars_vertex2, + logdepthbuf_vertex: logdepthbuf_vertex2, + map_fragment: map_fragment2, + map_pars_fragment: map_pars_fragment2, + map_particle_fragment: map_particle_fragment2, + map_particle_pars_fragment: map_particle_pars_fragment2, + metalnessmap_fragment: metalnessmap_fragment2, + metalnessmap_pars_fragment: metalnessmap_pars_fragment2, + morphinstance_vertex: morphinstance_vertex2, + morphcolor_vertex: morphcolor_vertex2, + morphnormal_vertex: morphnormal_vertex2, + morphtarget_pars_vertex: morphtarget_pars_vertex2, + morphtarget_vertex: morphtarget_vertex2, + normal_fragment_begin: normal_fragment_begin2, + normal_fragment_maps: normal_fragment_maps2, + normal_pars_fragment: normal_pars_fragment2, + normal_pars_vertex: normal_pars_vertex2, + normal_vertex: normal_vertex2, + normalmap_pars_fragment: normalmap_pars_fragment2, + clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin2, + clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps2, + clearcoat_pars_fragment: clearcoat_pars_fragment2, + iridescence_pars_fragment: iridescence_pars_fragment2, + opaque_fragment: opaque_fragment2, + packing: packing2, + premultiplied_alpha_fragment: premultiplied_alpha_fragment2, + project_vertex: project_vertex2, + dithering_fragment: dithering_fragment2, + dithering_pars_fragment: dithering_pars_fragment2, + roughnessmap_fragment: roughnessmap_fragment2, + roughnessmap_pars_fragment: roughnessmap_pars_fragment2, + shadowmap_pars_fragment: shadowmap_pars_fragment2, + shadowmap_pars_vertex: shadowmap_pars_vertex2, + shadowmap_vertex: shadowmap_vertex2, + shadowmask_pars_fragment: shadowmask_pars_fragment2, + skinbase_vertex: skinbase_vertex2, + skinning_pars_vertex: skinning_pars_vertex2, + skinning_vertex: skinning_vertex2, + skinnormal_vertex: skinnormal_vertex2, + specularmap_fragment: specularmap_fragment2, + specularmap_pars_fragment: specularmap_pars_fragment2, + tonemapping_fragment: tonemapping_fragment2, + tonemapping_pars_fragment: tonemapping_pars_fragment2, + transmission_fragment: transmission_fragment2, + transmission_pars_fragment: transmission_pars_fragment2, + uv_pars_fragment: uv_pars_fragment2, + uv_pars_vertex: uv_pars_vertex2, + uv_vertex: uv_vertex2, + worldpos_vertex: worldpos_vertex2, + background_vert: vertex$h2, + background_frag: fragment$h2, + backgroundCube_vert: vertex$g2, + backgroundCube_frag: fragment$g2, + cube_vert: vertex$f2, + cube_frag: fragment$f2, + depth_vert: vertex$e2, + depth_frag: fragment$e2, + distanceRGBA_vert: vertex$d2, + distanceRGBA_frag: fragment$d2, + equirect_vert: vertex$c2, + equirect_frag: fragment$c2, + linedashed_vert: vertex$b2, + linedashed_frag: fragment$b2, + meshbasic_vert: vertex$a2, + meshbasic_frag: fragment$a2, + meshlambert_vert: vertex$92, + meshlambert_frag: fragment$92, + meshmatcap_vert: vertex$82, + meshmatcap_frag: fragment$82, + meshnormal_vert: vertex$72, + meshnormal_frag: fragment$72, + meshphong_vert: vertex$62, + meshphong_frag: fragment$62, + meshphysical_vert: vertex$52, + meshphysical_frag: fragment$52, + meshtoon_vert: vertex$42, + meshtoon_frag: fragment$42, + points_vert: vertex$32, + points_frag: fragment$32, + shadow_vert: vertex$22, + shadow_frag: fragment$22, + sprite_vert: vertex$12, + sprite_frag: fragment$12 + }; + var UniformsLib2 = { + common: { + diffuse: { value: /* @__PURE__ */ new Color2(16777215) }, + opacity: { value: 1 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaTest: { value: 0 } + }, + specularmap: { + specularMap: { value: null }, + specularMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + envmap: { + envMap: { value: null }, + envMapRotation: { value: /* @__PURE__ */ new Matrix32 }, + flipEnvMap: { value: -1 }, + reflectivity: { value: 1 }, + ior: { value: 1.5 }, + refractionRatio: { value: 0.98 } + }, + aomap: { + aoMap: { value: null }, + aoMapIntensity: { value: 1 }, + aoMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + lightmap: { + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + bumpmap: { + bumpMap: { value: null }, + bumpMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + bumpScale: { value: 1 } + }, + normalmap: { + normalMap: { value: null }, + normalMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + normalScale: { value: /* @__PURE__ */ new Vector22(1, 1) } + }, + displacementmap: { + displacementMap: { value: null }, + displacementMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + }, + emissivemap: { + emissiveMap: { value: null }, + emissiveMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + metalnessmap: { + metalnessMap: { value: null }, + metalnessMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + roughnessmap: { + roughnessMap: { value: null }, + roughnessMapTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + gradientmap: { + gradientMap: { value: null } + }, + fog: { + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: /* @__PURE__ */ new Color2(16777215) } + }, + lights: { + ambientLightColor: { value: [] }, + lightProbe: { value: [] }, + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + directionalLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + spotLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + pointLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + ltc_1: { value: null }, + ltc_2: { value: null } + }, + points: { + diffuse: { value: /* @__PURE__ */ new Color2(16777215) }, + opacity: { value: 1 }, + size: { value: 1 }, + scale: { value: 1 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaTest: { value: 0 }, + uvTransform: { value: /* @__PURE__ */ new Matrix32 } + }, + sprite: { + diffuse: { value: /* @__PURE__ */ new Color2(16777215) }, + opacity: { value: 1 }, + center: { value: /* @__PURE__ */ new Vector22(0.5, 0.5) }, + rotation: { value: 0 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + alphaTest: { value: 0 } + } + }; + var ShaderLib2 = { + basic: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.specularmap, + UniformsLib2.envmap, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.fog + ]), + vertexShader: ShaderChunk2.meshbasic_vert, + fragmentShader: ShaderChunk2.meshbasic_frag + }, + lambert: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.specularmap, + UniformsLib2.envmap, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.emissivemap, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.fog, + UniformsLib2.lights, + { + emissive: { value: /* @__PURE__ */ new Color2(0) } + } + ]), + vertexShader: ShaderChunk2.meshlambert_vert, + fragmentShader: ShaderChunk2.meshlambert_frag + }, + phong: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.specularmap, + UniformsLib2.envmap, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.emissivemap, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.fog, + UniformsLib2.lights, + { + emissive: { value: /* @__PURE__ */ new Color2(0) }, + specular: { value: /* @__PURE__ */ new Color2(1118481) }, + shininess: { value: 30 } + } + ]), + vertexShader: ShaderChunk2.meshphong_vert, + fragmentShader: ShaderChunk2.meshphong_frag + }, + standard: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.envmap, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.emissivemap, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.roughnessmap, + UniformsLib2.metalnessmap, + UniformsLib2.fog, + UniformsLib2.lights, + { + emissive: { value: /* @__PURE__ */ new Color2(0) }, + roughness: { value: 1 }, + metalness: { value: 0 }, + envMapIntensity: { value: 1 } + } + ]), + vertexShader: ShaderChunk2.meshphysical_vert, + fragmentShader: ShaderChunk2.meshphysical_frag + }, + toon: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.aomap, + UniformsLib2.lightmap, + UniformsLib2.emissivemap, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.gradientmap, + UniformsLib2.fog, + UniformsLib2.lights, + { + emissive: { value: /* @__PURE__ */ new Color2(0) } + } + ]), + vertexShader: ShaderChunk2.meshtoon_vert, + fragmentShader: ShaderChunk2.meshtoon_frag + }, + matcap: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + UniformsLib2.fog, + { + matcap: { value: null } + } + ]), + vertexShader: ShaderChunk2.meshmatcap_vert, + fragmentShader: ShaderChunk2.meshmatcap_frag + }, + points: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.points, + UniformsLib2.fog + ]), + vertexShader: ShaderChunk2.points_vert, + fragmentShader: ShaderChunk2.points_frag + }, + dashed: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ]), + vertexShader: ShaderChunk2.linedashed_vert, + fragmentShader: ShaderChunk2.linedashed_frag + }, + depth: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.displacementmap + ]), + vertexShader: ShaderChunk2.depth_vert, + fragmentShader: ShaderChunk2.depth_frag + }, + normal: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.bumpmap, + UniformsLib2.normalmap, + UniformsLib2.displacementmap, + { + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk2.meshnormal_vert, + fragmentShader: ShaderChunk2.meshnormal_frag + }, + sprite: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.sprite, + UniformsLib2.fog + ]), + vertexShader: ShaderChunk2.sprite_vert, + fragmentShader: ShaderChunk2.sprite_frag + }, + background: { + uniforms: { + uvTransform: { value: /* @__PURE__ */ new Matrix32 }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + vertexShader: ShaderChunk2.background_vert, + fragmentShader: ShaderChunk2.background_frag + }, + backgroundCube: { + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /* @__PURE__ */ new Matrix32 } + }, + vertexShader: ShaderChunk2.backgroundCube_vert, + fragmentShader: ShaderChunk2.backgroundCube_frag + }, + cube: { + uniforms: { + tCube: { value: null }, + tFlip: { value: -1 }, + opacity: { value: 1 } + }, + vertexShader: ShaderChunk2.cube_vert, + fragmentShader: ShaderChunk2.cube_frag + }, + equirect: { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ShaderChunk2.equirect_vert, + fragmentShader: ShaderChunk2.equirect_frag + }, + distanceRGBA: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.common, + UniformsLib2.displacementmap, + { + referencePosition: { value: /* @__PURE__ */ new Vector32 }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ]), + vertexShader: ShaderChunk2.distanceRGBA_vert, + fragmentShader: ShaderChunk2.distanceRGBA_frag + }, + shadow: { + uniforms: /* @__PURE__ */ mergeUniforms2([ + UniformsLib2.lights, + UniformsLib2.fog, + { + color: { value: /* @__PURE__ */ new Color2(0) }, + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk2.shadow_vert, + fragmentShader: ShaderChunk2.shadow_frag + } + }; + ShaderLib2.physical = { + uniforms: /* @__PURE__ */ mergeUniforms2([ + ShaderLib2.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + clearcoatNormalScale: { value: /* @__PURE__ */ new Vector22(1, 1) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + dispersion: { value: 0 }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + sheen: { value: 0 }, + sheenColor: { value: /* @__PURE__ */ new Color2(0) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + transmissionSamplerSize: { value: /* @__PURE__ */ new Vector22 }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /* @__PURE__ */ new Color2(0) }, + specularColor: { value: /* @__PURE__ */ new Color2(1, 1, 1) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /* @__PURE__ */ new Matrix32 }, + anisotropyVector: { value: /* @__PURE__ */ new Vector22 }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /* @__PURE__ */ new Matrix32 } + } + ]), + vertexShader: ShaderChunk2.meshphysical_vert, + fragmentShader: ShaderChunk2.meshphysical_frag + }; + var _rgb2 = { r: 0, b: 0, g: 0 }; + var _e1$12 = /* @__PURE__ */ new Euler2; + var _m1$13 = /* @__PURE__ */ new Matrix42; + function WebGLBackground2(renderer2, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) { + const clearColor = new Color2(0); + let clearAlpha = alpha === true ? 0 : 1; + let planeMesh; + let boxMesh; + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + function getBackground(scene) { + let background = scene.isScene === true ? scene.background : null; + if (background && background.isTexture) { + const usePMREM = scene.backgroundBlurriness > 0; + background = (usePMREM ? cubeuvmaps : cubemaps).get(background); + } + return background; + } + function render(scene) { + let forceClear = false; + const background = getBackground(scene); + if (background === null) { + setClear(clearColor, clearAlpha); + } else if (background && background.isColor) { + setClear(background, 1); + forceClear = true; + } + const environmentBlendMode = renderer2.xr.getEnvironmentBlendMode(); + if (environmentBlendMode === "additive") { + state.buffers.color.setClear(0, 0, 0, 1, premultipliedAlpha); + } else if (environmentBlendMode === "alpha-blend") { + state.buffers.color.setClear(0, 0, 0, 0, premultipliedAlpha); + } + if (renderer2.autoClear || forceClear) { + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + renderer2.clear(renderer2.autoClearColor, renderer2.autoClearDepth, renderer2.autoClearStencil); + } + } + function addToRenderList(renderList, scene) { + const background = getBackground(scene); + if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping2)) { + if (boxMesh === undefined) { + boxMesh = new Mesh2(new BoxGeometry2(1, 1, 1), new ShaderMaterial2({ + name: "BackgroundCubeMaterial", + uniforms: cloneUniforms2(ShaderLib2.backgroundCube.uniforms), + vertexShader: ShaderLib2.backgroundCube.vertexShader, + fragmentShader: ShaderLib2.backgroundCube.fragmentShader, + side: BackSide2, + depthTest: false, + depthWrite: false, + fog: false + })); + boxMesh.geometry.deleteAttribute("normal"); + boxMesh.geometry.deleteAttribute("uv"); + boxMesh.onBeforeRender = function(renderer3, scene2, camera) { + this.matrixWorld.copyPosition(camera.matrixWorld); + }; + Object.defineProperty(boxMesh.material, "envMap", { + get: function() { + return this.uniforms.envMap.value; + } + }); + objects.update(boxMesh); + } + _e1$12.copy(scene.backgroundRotation); + _e1$12.x *= -1; + _e1$12.y *= -1; + _e1$12.z *= -1; + if (background.isCubeTexture && background.isRenderTargetTexture === false) { + _e1$12.y *= -1; + _e1$12.z *= -1; + } + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4(_m1$13.makeRotationFromEuler(_e1$12)); + boxMesh.material.toneMapped = ColorManagement2.getTransfer(background.colorSpace) !== SRGBTransfer2; + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer2.toneMapping) { + boxMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer2.toneMapping; + } + boxMesh.layers.enableAll(); + renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null); + } else if (background && background.isTexture) { + if (planeMesh === undefined) { + planeMesh = new Mesh2(new PlaneGeometry3(2, 2), new ShaderMaterial2({ + name: "BackgroundMaterial", + uniforms: cloneUniforms2(ShaderLib2.background.uniforms), + vertexShader: ShaderLib2.background.vertexShader, + fragmentShader: ShaderLib2.background.fragmentShader, + side: FrontSide2, + depthTest: false, + depthWrite: false, + fog: false + })); + planeMesh.geometry.deleteAttribute("normal"); + Object.defineProperty(planeMesh.material, "map", { + get: function() { + return this.uniforms.t2D.value; + } + }); + objects.update(planeMesh); + } + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ColorManagement2.getTransfer(background.colorSpace) !== SRGBTransfer2; + if (background.matrixAutoUpdate === true) { + background.updateMatrix(); + } + planeMesh.material.uniforms.uvTransform.value.copy(background.matrix); + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer2.toneMapping) { + planeMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer2.toneMapping; + } + planeMesh.layers.enableAll(); + renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null); + } + } + function setClear(color, alpha2) { + color.getRGB(_rgb2, getUnlitUniformColorSpace2(renderer2)); + state.buffers.color.setClear(_rgb2.r, _rgb2.g, _rgb2.b, alpha2, premultipliedAlpha); + } + function dispose() { + if (boxMesh !== undefined) { + boxMesh.geometry.dispose(); + boxMesh.material.dispose(); + boxMesh = undefined; + } + if (planeMesh !== undefined) { + planeMesh.geometry.dispose(); + planeMesh.material.dispose(); + planeMesh = undefined; + } + } + return { + getClearColor: function() { + return clearColor; + }, + setClearColor: function(color, alpha2 = 1) { + clearColor.set(color); + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + getClearAlpha: function() { + return clearAlpha; + }, + setClearAlpha: function(alpha2) { + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + render, + addToRenderList, + dispose + }; + } + function WebGLBindingStates2(gl, attributes) { + const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const bindingStates = {}; + const defaultState2 = createBindingState(null); + let currentState = defaultState2; + let forceUpdate = false; + function setup(object, material, program, geometry, index2) { + let updateBuffers = false; + const state = getBindingState(geometry, program, material); + if (currentState !== state) { + currentState = state; + bindVertexArrayObject(currentState.object); + } + updateBuffers = needsUpdate(object, geometry, program, index2); + if (updateBuffers) + saveCache(object, geometry, program, index2); + if (index2 !== null) { + attributes.update(index2, gl.ELEMENT_ARRAY_BUFFER); + } + if (updateBuffers || forceUpdate) { + forceUpdate = false; + setupVertexAttributes(object, material, program, geometry); + if (index2 !== null) { + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index2).buffer); + } + } + } + function createVertexArrayObject() { + return gl.createVertexArray(); + } + function bindVertexArrayObject(vao) { + return gl.bindVertexArray(vao); + } + function deleteVertexArrayObject(vao) { + return gl.deleteVertexArray(vao); + } + function getBindingState(geometry, program, material) { + const wireframe = material.wireframe === true; + let programMap = bindingStates[geometry.id]; + if (programMap === undefined) { + programMap = {}; + bindingStates[geometry.id] = programMap; + } + let stateMap = programMap[program.id]; + if (stateMap === undefined) { + stateMap = {}; + programMap[program.id] = stateMap; + } + let state = stateMap[wireframe]; + if (state === undefined) { + state = createBindingState(createVertexArrayObject()); + stateMap[wireframe] = state; + } + return state; + } + function createBindingState(vao) { + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + for (let i = 0;i < maxVertexAttributes; i++) { + newAttributes[i] = 0; + enabledAttributes[i] = 0; + attributeDivisors[i] = 0; + } + return { + geometry: null, + program: null, + wireframe: false, + newAttributes, + enabledAttributes, + attributeDivisors, + object: vao, + attributes: {}, + index: null + }; + } + function needsUpdate(object, geometry, program, index2) { + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + const cachedAttribute = cachedAttributes[name2]; + let geometryAttribute = geometryAttributes[name2]; + if (geometryAttribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + geometryAttribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + geometryAttribute = object.instanceColor; + } + if (cachedAttribute === undefined) + return true; + if (cachedAttribute.attribute !== geometryAttribute) + return true; + if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) + return true; + attributesNum++; + } + } + if (currentState.attributesNum !== attributesNum) + return true; + if (currentState.index !== index2) + return true; + return false; + } + function saveCache(object, geometry, program, index2) { + const cache = {}; + const attributes2 = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + let attribute = attributes2[name2]; + if (attribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + attribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + attribute = object.instanceColor; + } + const data2 = {}; + data2.attribute = attribute; + if (attribute && attribute.data) { + data2.data = attribute.data; + } + cache[name2] = data2; + attributesNum++; + } + } + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + currentState.index = index2; + } + function initAttributes() { + const newAttributes = currentState.newAttributes; + for (let i = 0, il = newAttributes.length;i < il; i++) { + newAttributes[i] = 0; + } + } + function enableAttribute(attribute) { + enableAttributeAndDivisor(attribute, 0); + } + function enableAttributeAndDivisor(attribute, meshPerAttribute) { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + newAttributes[attribute] = 1; + if (enabledAttributes[attribute] === 0) { + gl.enableVertexAttribArray(attribute); + enabledAttributes[attribute] = 1; + } + if (attributeDivisors[attribute] !== meshPerAttribute) { + gl.vertexAttribDivisor(attribute, meshPerAttribute); + attributeDivisors[attribute] = meshPerAttribute; + } + } + function disableUnusedAttributes() { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + for (let i = 0, il = enabledAttributes.length;i < il; i++) { + if (enabledAttributes[i] !== newAttributes[i]) { + gl.disableVertexAttribArray(i); + enabledAttributes[i] = 0; + } + } + } + function vertexAttribPointer(index2, size2, type, normalized, stride, offset, integer) { + if (integer === true) { + gl.vertexAttribIPointer(index2, size2, type, stride, offset); + } else { + gl.vertexAttribPointer(index2, size2, type, normalized, stride, offset); + } + } + function setupVertexAttributes(object, material, program, geometry) { + initAttributes(); + const geometryAttributes = geometry.attributes; + const programAttributes = program.getAttributes(); + const materialDefaultAttributeValues = material.defaultAttributeValues; + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + let geometryAttribute = geometryAttributes[name2]; + if (geometryAttribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + geometryAttribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + geometryAttribute = object.instanceColor; + } + if (geometryAttribute !== undefined) { + const normalized = geometryAttribute.normalized; + const size2 = geometryAttribute.itemSize; + const attribute = attributes.get(geometryAttribute); + if (attribute === undefined) + continue; + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + const integer = type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType2; + if (geometryAttribute.isInterleavedBufferAttribute) { + const data2 = geometryAttribute.data; + const stride = data2.stride; + const offset = geometryAttribute.offset; + if (data2.isInstancedInterleavedBuffer) { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, data2.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { + geometry._maxInstanceCount = data2.meshPerAttribute * data2.count; + } + } else { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0;i < programAttribute.locationSize; i++) { + vertexAttribPointer(programAttribute.location + i, size2 / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size2 / programAttribute.locationSize * i) * bytesPerElement, integer); + } + } else { + if (geometryAttribute.isInstancedBufferAttribute) { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } + } else { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0;i < programAttribute.locationSize; i++) { + vertexAttribPointer(programAttribute.location + i, size2 / programAttribute.locationSize, type, normalized, size2 * bytesPerElement, size2 / programAttribute.locationSize * i * bytesPerElement, integer); + } + } + } else if (materialDefaultAttributeValues !== undefined) { + const value2 = materialDefaultAttributeValues[name2]; + if (value2 !== undefined) { + switch (value2.length) { + case 2: + gl.vertexAttrib2fv(programAttribute.location, value2); + break; + case 3: + gl.vertexAttrib3fv(programAttribute.location, value2); + break; + case 4: + gl.vertexAttrib4fv(programAttribute.location, value2); + break; + default: + gl.vertexAttrib1fv(programAttribute.location, value2); + } + } + } + } + } + disableUnusedAttributes(); + } + function dispose() { + reset(); + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometryId]; + } + } + function releaseStatesOfGeometry(geometry) { + if (bindingStates[geometry.id] === undefined) + return; + const programMap = bindingStates[geometry.id]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometry.id]; + } + function releaseStatesOfProgram(program) { + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + if (programMap[program.id] === undefined) + continue; + const stateMap = programMap[program.id]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[program.id]; + } + } + function reset() { + resetDefaultState(); + forceUpdate = true; + if (currentState === defaultState2) + return; + currentState = defaultState2; + bindVertexArrayObject(currentState.object); + } + function resetDefaultState() { + defaultState2.geometry = null; + defaultState2.program = null; + defaultState2.wireframe = false; + } + return { + setup, + reset, + resetDefaultState, + dispose, + releaseStatesOfGeometry, + releaseStatesOfProgram, + initAttributes, + enableAttribute, + disableUnusedAttributes + }; + } + function WebGLBufferRenderer2(gl, extensions, info) { + let mode; + function setMode(value2) { + mode = value2; + } + function render(start, count) { + gl.drawArrays(mode, start, count); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) + return; + gl.drawArraysInstanced(mode, start, count, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawArraysWEBGL(mode, starts, 0, counts, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0;i < starts.length; i++) { + renderInstances(starts[i], counts[i], primcount[i]); + } + } else { + extension.multiDrawArraysInstancedWEBGL(mode, starts, 0, counts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i] * primcount[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; + } + function WebGLCapabilities2(gl, extensions, parameters, utils) { + let maxAnisotropy; + function getMaxAnisotropy() { + if (maxAnisotropy !== undefined) + return maxAnisotropy; + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } else { + maxAnisotropy = 0; + } + return maxAnisotropy; + } + function textureFormatReadable(textureFormat) { + if (textureFormat !== RGBAFormat2 && utils.convert(textureFormat) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT)) { + return false; + } + return true; + } + function textureTypeReadable(textureType) { + const halfFloatSupportedByExt = textureType === HalfFloatType2 && (extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float")); + if (textureType !== UnsignedByteType2 && utils.convert(textureType) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE) && textureType !== FloatType2 && !halfFloatSupportedByExt) { + return false; + } + return true; + } + function getMaxPrecision(precision2) { + if (precision2 === "highp") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) { + return "highp"; + } + precision2 = "mediump"; + } + if (precision2 === "mediump") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) { + return "mediump"; + } + } + return "lowp"; + } + let precision = parameters.precision !== undefined ? parameters.precision : "highp"; + const maxPrecision = getMaxPrecision(precision); + if (maxPrecision !== precision) { + console.warn("THREE.WebGLRenderer:", precision, "not supported, using", maxPrecision, "instead."); + precision = maxPrecision; + } + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has("EXT_clip_control"); + const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); + const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); + const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); + const vertexTextures = maxVertexTextures > 0; + const maxSamples = gl.getParameter(gl.MAX_SAMPLES); + return { + isWebGL2: true, + getMaxAnisotropy, + getMaxPrecision, + textureFormatReadable, + textureTypeReadable, + precision, + logarithmicDepthBuffer, + reverseDepthBuffer, + maxTextures, + maxVertexTextures, + maxTextureSize, + maxCubemapSize, + maxAttributes, + maxVertexUniforms, + maxVaryings, + maxFragmentUniforms, + vertexTextures, + maxSamples + }; + } + function WebGLClipping2(properties) { + const scope = this; + let globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false; + const plane = new Plane2, viewNormalMatrix = new Matrix32, uniform = { value: null, needsUpdate: false }; + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + this.init = function(planes, enableLocalClipping) { + const enabled = planes.length !== 0 || enableLocalClipping || numGlobalPlanes !== 0 || localClippingEnabled; + localClippingEnabled = enableLocalClipping; + numGlobalPlanes = planes.length; + return enabled; + }; + this.beginShadows = function() { + renderingShadows = true; + projectPlanes(null); + }; + this.endShadows = function() { + renderingShadows = false; + }; + this.setGlobalState = function(planes, camera) { + globalState = projectPlanes(planes, camera, 0); + }; + this.setState = function(material, camera, useCache) { + const { clippingPlanes: planes, clipIntersection, clipShadows } = material; + const materialProperties = properties.get(material); + if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) { + if (renderingShadows) { + projectPlanes(null); + } else { + resetGlobalState(); + } + } else { + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4; + let dstArray = materialProperties.clippingState || null; + uniform.value = dstArray; + dstArray = projectPlanes(planes, camera, lGlobal, useCache); + for (let i = 0;i !== lGlobal; ++i) { + dstArray[i] = globalState[i]; + } + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + } + }; + function resetGlobalState() { + if (uniform.value !== globalState) { + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + } + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + } + function projectPlanes(planes, camera, dstOffset, skipTransform) { + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + if (nPlanes !== 0) { + dstArray = uniform.value; + if (skipTransform !== true || dstArray === null) { + const flatSize = dstOffset + nPlanes * 4, viewMatrix = camera.matrixWorldInverse; + viewNormalMatrix.getNormalMatrix(viewMatrix); + if (dstArray === null || dstArray.length < flatSize) { + dstArray = new Float32Array(flatSize); + } + for (let i = 0, i4 = dstOffset;i !== nPlanes; ++i, i4 += 4) { + plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix); + plane.normal.toArray(dstArray, i4); + dstArray[i4 + 3] = plane.constant; + } + } + uniform.value = dstArray; + uniform.needsUpdate = true; + } + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + return dstArray; + } + } + function WebGLCubeMaps2(renderer2) { + let cubemaps = new WeakMap; + function mapTextureMapping(texture, mapping) { + if (mapping === EquirectangularReflectionMapping2) { + texture.mapping = CubeReflectionMapping2; + } else if (mapping === EquirectangularRefractionMapping2) { + texture.mapping = CubeRefractionMapping2; + } + return texture; + } + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + if (mapping === EquirectangularReflectionMapping2 || mapping === EquirectangularRefractionMapping2) { + if (cubemaps.has(texture)) { + const cubemap = cubemaps.get(texture).texture; + return mapTextureMapping(cubemap, texture.mapping); + } else { + const image = texture.image; + if (image && image.height > 0) { + const renderTarget = new WebGLCubeRenderTarget2(image.height); + renderTarget.fromEquirectangularTexture(renderer2, texture); + cubemaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return mapTextureMapping(renderTarget.texture, texture.mapping); + } else { + return null; + } + } + } + } + return texture; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemap = cubemaps.get(texture); + if (cubemap !== undefined) { + cubemaps.delete(texture); + cubemap.dispose(); + } + } + function dispose() { + cubemaps = new WeakMap; + } + return { + get, + dispose + }; + } + var LOD_MIN2 = 4; + var EXTRA_LOD_SIGMA2 = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; + var MAX_SAMPLES2 = 20; + var _flatCamera2 = /* @__PURE__ */ new OrthographicCamera2; + var _clearColor2 = /* @__PURE__ */ new Color2; + var _oldTarget2 = null; + var _oldActiveCubeFace2 = 0; + var _oldActiveMipmapLevel2 = 0; + var _oldXrEnabled2 = false; + var PHI2 = (1 + Math.sqrt(5)) / 2; + var INV_PHI2 = 1 / PHI2; + var _axisDirections2 = [ + /* @__PURE__ */ new Vector32(-PHI2, INV_PHI2, 0), + /* @__PURE__ */ new Vector32(PHI2, INV_PHI2, 0), + /* @__PURE__ */ new Vector32(-INV_PHI2, 0, PHI2), + /* @__PURE__ */ new Vector32(INV_PHI2, 0, PHI2), + /* @__PURE__ */ new Vector32(0, PHI2, -INV_PHI2), + /* @__PURE__ */ new Vector32(0, PHI2, INV_PHI2), + /* @__PURE__ */ new Vector32(-1, 1, -1), + /* @__PURE__ */ new Vector32(1, 1, -1), + /* @__PURE__ */ new Vector32(-1, 1, 1), + /* @__PURE__ */ new Vector32(1, 1, 1) + ]; + + class PMREMGenerator2 { + constructor(renderer2) { + this._renderer = renderer2; + this._pingPongRenderTarget = null; + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + this._compileMaterial(this._blurMaterial); + } + fromScene(scene, sigma = 0, near = 0.1, far = 100) { + _oldTarget2 = this._renderer.getRenderTarget(); + _oldActiveCubeFace2 = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel2 = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled2 = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + this._setSize(256); + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget); + if (sigma > 0) { + this._blur(cubeUVRenderTarget, 0, 0, sigma); + } + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + fromEquirectangular(equirectangular, renderTarget = null) { + return this._fromTexture(equirectangular, renderTarget); + } + fromCubemap(cubemap, renderTarget = null) { + return this._fromTexture(cubemap, renderTarget); + } + compileCubemapShader() { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial2(); + this._compileMaterial(this._cubemapMaterial); + } + } + compileEquirectangularShader() { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial2(); + this._compileMaterial(this._equirectMaterial); + } + } + dispose() { + this._dispose(); + if (this._cubemapMaterial !== null) + this._cubemapMaterial.dispose(); + if (this._equirectMaterial !== null) + this._equirectMaterial.dispose(); + } + _setSize(cubeSize) { + this._lodMax = Math.floor(Math.log2(cubeSize)); + this._cubeSize = Math.pow(2, this._lodMax); + } + _dispose() { + if (this._blurMaterial !== null) + this._blurMaterial.dispose(); + if (this._pingPongRenderTarget !== null) + this._pingPongRenderTarget.dispose(); + for (let i = 0;i < this._lodPlanes.length; i++) { + this._lodPlanes[i].dispose(); + } + } + _cleanup(outputTarget) { + this._renderer.setRenderTarget(_oldTarget2, _oldActiveCubeFace2, _oldActiveMipmapLevel2); + this._renderer.xr.enabled = _oldXrEnabled2; + outputTarget.scissorTest = false; + _setViewport2(outputTarget, 0, 0, outputTarget.width, outputTarget.height); + } + _fromTexture(texture, renderTarget) { + if (texture.mapping === CubeReflectionMapping2 || texture.mapping === CubeRefractionMapping2) { + this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width); + } else { + this._setSize(texture.image.width / 4); + } + _oldTarget2 = this._renderer.getRenderTarget(); + _oldActiveCubeFace2 = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel2 = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled2 = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV(texture, cubeUVRenderTarget); + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + _allocateTargets() { + const width2 = 3 * Math.max(this._cubeSize, 16 * 7); + const height2 = 4 * this._cubeSize; + const params = { + magFilter: LinearFilter2, + minFilter: LinearFilter2, + generateMipmaps: false, + type: HalfFloatType2, + format: RGBAFormat2, + colorSpace: LinearSRGBColorSpace2, + depthBuffer: false + }; + const cubeUVRenderTarget = _createRenderTarget2(width2, height2, params); + if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width2 || this._pingPongRenderTarget.height !== height2) { + if (this._pingPongRenderTarget !== null) { + this._dispose(); + } + this._pingPongRenderTarget = _createRenderTarget2(width2, height2, params); + const { _lodMax } = this; + ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes2(_lodMax)); + this._blurMaterial = _getBlurShader2(_lodMax, width2, height2); + } + return cubeUVRenderTarget; + } + _compileMaterial(material) { + const tmpMesh = new Mesh2(this._lodPlanes[0], material); + this._renderer.compile(tmpMesh, _flatCamera2); + } + _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) { + const fov3 = 90; + const aspect3 = 1; + const cubeCamera = new PerspectiveCamera2(fov3, aspect3, near, far); + const upSign = [1, -1, 1, 1, 1, 1]; + const forwardSign = [1, 1, 1, -1, -1, -1]; + const renderer2 = this._renderer; + const originalAutoClear = renderer2.autoClear; + const toneMapping = renderer2.toneMapping; + renderer2.getClearColor(_clearColor2); + renderer2.toneMapping = NoToneMapping2; + renderer2.autoClear = false; + const backgroundMaterial = new MeshBasicMaterial2({ + name: "PMREM.Background", + side: BackSide2, + depthWrite: false, + depthTest: false + }); + const backgroundBox = new Mesh2(new BoxGeometry2, backgroundMaterial); + let useSolidColor = false; + const background = scene.background; + if (background) { + if (background.isColor) { + backgroundMaterial.color.copy(background); + scene.background = null; + useSolidColor = true; + } + } else { + backgroundMaterial.color.copy(_clearColor2); + useSolidColor = true; + } + for (let i = 0;i < 6; i++) { + const col = i % 3; + if (col === 0) { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(forwardSign[i], 0, 0); + } else if (col === 1) { + cubeCamera.up.set(0, 0, upSign[i]); + cubeCamera.lookAt(0, forwardSign[i], 0); + } else { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(0, 0, forwardSign[i]); + } + const size2 = this._cubeSize; + _setViewport2(cubeUVRenderTarget, col * size2, i > 2 ? size2 : 0, size2, size2); + renderer2.setRenderTarget(cubeUVRenderTarget); + if (useSolidColor) { + renderer2.render(backgroundBox, cubeCamera); + } + renderer2.render(scene, cubeCamera); + } + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + renderer2.toneMapping = toneMapping; + renderer2.autoClear = originalAutoClear; + scene.background = background; + } + _textureToCubeUV(texture, cubeUVRenderTarget) { + const renderer2 = this._renderer; + const isCubeTexture = texture.mapping === CubeReflectionMapping2 || texture.mapping === CubeRefractionMapping2; + if (isCubeTexture) { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial2(); + } + this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1; + } else { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial2(); + } + } + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh2(this._lodPlanes[0], material); + const uniforms = material.uniforms; + uniforms["envMap"].value = texture; + const size2 = this._cubeSize; + _setViewport2(cubeUVRenderTarget, 0, 0, 3 * size2, 2 * size2); + renderer2.setRenderTarget(cubeUVRenderTarget); + renderer2.render(mesh, _flatCamera2); + } + _applyPMREM(cubeUVRenderTarget) { + const renderer2 = this._renderer; + const autoClear = renderer2.autoClear; + renderer2.autoClear = false; + const n2 = this._lodPlanes.length; + for (let i = 1;i < n2; i++) { + const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]); + const poleAxis = _axisDirections2[(n2 - i - 1) % _axisDirections2.length]; + this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis); + } + renderer2.autoClear = autoClear; + } + _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) { + const pingPongRenderTarget = this._pingPongRenderTarget; + this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, "latitudinal", poleAxis); + this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, "longitudinal", poleAxis); + } + _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) { + const renderer2 = this._renderer; + const blurMaterial = this._blurMaterial; + if (direction !== "latitudinal" && direction !== "longitudinal") { + console.error("blur direction must be either latitudinal or longitudinal!"); + } + const STANDARD_DEVIATIONS = 3; + const blurMesh = new Mesh2(this._lodPlanes[lodOut], blurMaterial); + const blurUniforms = blurMaterial.uniforms; + const pixels = this._sizeLods[lodIn] - 1; + const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES2 - 1); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES2; + if (samples > MAX_SAMPLES2) { + console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES2}`); + } + const weights = []; + let sum2 = 0; + for (let i = 0;i < MAX_SAMPLES2; ++i) { + const x3 = i / sigmaPixels; + const weight = Math.exp(-x3 * x3 / 2); + weights.push(weight); + if (i === 0) { + sum2 += weight; + } else if (i < samples) { + sum2 += 2 * weight; + } + } + for (let i = 0;i < weights.length; i++) { + weights[i] = weights[i] / sum2; + } + blurUniforms["envMap"].value = targetIn.texture; + blurUniforms["samples"].value = samples; + blurUniforms["weights"].value = weights; + blurUniforms["latitudinal"].value = direction === "latitudinal"; + if (poleAxis) { + blurUniforms["poleAxis"].value = poleAxis; + } + const { _lodMax } = this; + blurUniforms["dTheta"].value = radiansPerPixel; + blurUniforms["mipInt"].value = _lodMax - lodIn; + const outputSize = this._sizeLods[lodOut]; + const x2 = 3 * outputSize * (lodOut > _lodMax - LOD_MIN2 ? lodOut - _lodMax + LOD_MIN2 : 0); + const y = 4 * (this._cubeSize - outputSize); + _setViewport2(targetOut, x2, y, 3 * outputSize, 2 * outputSize); + renderer2.setRenderTarget(targetOut); + renderer2.render(blurMesh, _flatCamera2); + } + } + function _createPlanes2(lodMax) { + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + let lod = lodMax; + const totalLods = lodMax - LOD_MIN2 + 1 + EXTRA_LOD_SIGMA2.length; + for (let i = 0;i < totalLods; i++) { + const sizeLod = Math.pow(2, lod); + sizeLods.push(sizeLod); + let sigma = 1 / sizeLod; + if (i > lodMax - LOD_MIN2) { + sigma = EXTRA_LOD_SIGMA2[i - lodMax + LOD_MIN2 - 1]; + } else if (i === 0) { + sigma = 0; + } + sigmas.push(sigma); + const texelSize = 1 / (sizeLod - 2); + const min = -texelSize; + const max = 1 + texelSize; + const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max]; + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + const position2 = new Float32Array(positionSize * vertices * cubeFaces); + const uv = new Float32Array(uvSize * vertices * cubeFaces); + const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces); + for (let face = 0;face < cubeFaces; face++) { + const x2 = face % 3 * 2 / 3 - 1; + const y = face > 2 ? 0 : -1; + const coordinates = [ + x2, + y, + 0, + x2 + 2 / 3, + y, + 0, + x2 + 2 / 3, + y + 1, + 0, + x2, + y, + 0, + x2 + 2 / 3, + y + 1, + 0, + x2, + y + 1, + 0 + ]; + position2.set(coordinates, positionSize * vertices * face); + uv.set(uv1, uvSize * vertices * face); + const fill3 = [face, face, face, face, face, face]; + faceIndex.set(fill3, faceIndexSize * vertices * face); + } + const planes = new BufferGeometry2; + planes.setAttribute("position", new BufferAttribute2(position2, positionSize)); + planes.setAttribute("uv", new BufferAttribute2(uv, uvSize)); + planes.setAttribute("faceIndex", new BufferAttribute2(faceIndex, faceIndexSize)); + lodPlanes.push(planes); + if (lod > LOD_MIN2) { + lod--; + } + } + return { lodPlanes, sizeLods, sigmas }; + } + function _createRenderTarget2(width2, height2, params) { + const cubeUVRenderTarget = new WebGLRenderTarget2(width2, height2, params); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping2; + cubeUVRenderTarget.texture.name = "PMREM.cubeUv"; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; + } + function _setViewport2(target, x2, y, width2, height2) { + target.viewport.set(x2, y, width2, height2); + target.scissor.set(x2, y, width2, height2); + } + function _getBlurShader2(lodMax, width2, height2) { + const weights = new Float32Array(MAX_SAMPLES2); + const poleAxis = new Vector32(0, 1, 0); + const shaderMaterial = new ShaderMaterial2({ + name: "SphericalGaussianBlur", + defines: { + n: MAX_SAMPLES2, + CUBEUV_TEXEL_WIDTH: 1 / width2, + CUBEUV_TEXEL_HEIGHT: 1 / height2, + CUBEUV_MAX_MIP: `${lodMax}.0` + }, + uniforms: { + envMap: { value: null }, + samples: { value: 1 }, + weights: { value: weights }, + latitudinal: { value: false }, + dTheta: { value: 0 }, + mipInt: { value: 0 }, + poleAxis: { value: poleAxis } + }, + vertexShader: _getCommonVertexShader2(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `, + blending: NoBlending2, + depthTest: false, + depthWrite: false + }); + return shaderMaterial; + } + function _getEquirectMaterial2() { + return new ShaderMaterial2({ + name: "EquirectangularToCubeUV", + uniforms: { + envMap: { value: null } + }, + vertexShader: _getCommonVertexShader2(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `, + blending: NoBlending2, + depthTest: false, + depthWrite: false + }); + } + function _getCubemapMaterial2() { + return new ShaderMaterial2({ + name: "CubemapToCubeUV", + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 } + }, + vertexShader: _getCommonVertexShader2(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `, + blending: NoBlending2, + depthTest: false, + depthWrite: false + }); + } + function _getCommonVertexShader2() { + return ` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `; + } + function WebGLCubeUVMaps2(renderer2) { + let cubeUVmaps = new WeakMap; + let pmremGenerator = null; + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + const isEquirectMap = mapping === EquirectangularReflectionMapping2 || mapping === EquirectangularRefractionMapping2; + const isCubeMap = mapping === CubeReflectionMapping2 || mapping === CubeRefractionMapping2; + if (isEquirectMap || isCubeMap) { + let renderTarget = cubeUVmaps.get(texture); + const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0; + if (texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion) { + if (pmremGenerator === null) + pmremGenerator = new PMREMGenerator2(renderer2); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + return renderTarget.texture; + } else { + if (renderTarget !== undefined) { + return renderTarget.texture; + } else { + const image = texture.image; + if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) { + if (pmremGenerator === null) + pmremGenerator = new PMREMGenerator2(renderer2); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return renderTarget.texture; + } else { + return null; + } + } + } + } + } + return texture; + } + function isCubeTextureComplete(image) { + let count = 0; + const length2 = 6; + for (let i = 0;i < length2; i++) { + if (image[i] !== undefined) + count++; + } + return count === length2; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemapUV = cubeUVmaps.get(texture); + if (cubemapUV !== undefined) { + cubeUVmaps.delete(texture); + cubemapUV.dispose(); + } + } + function dispose() { + cubeUVmaps = new WeakMap; + if (pmremGenerator !== null) { + pmremGenerator.dispose(); + pmremGenerator = null; + } + } + return { + get, + dispose + }; + } + function WebGLExtensions2(gl) { + const extensions = {}; + function getExtension(name2) { + if (extensions[name2] !== undefined) { + return extensions[name2]; + } + let extension; + switch (name2) { + case "WEBGL_depth_texture": + extension = gl.getExtension("WEBGL_depth_texture") || gl.getExtension("MOZ_WEBGL_depth_texture") || gl.getExtension("WEBKIT_WEBGL_depth_texture"); + break; + case "EXT_texture_filter_anisotropic": + extension = gl.getExtension("EXT_texture_filter_anisotropic") || gl.getExtension("MOZ_EXT_texture_filter_anisotropic") || gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic"); + break; + case "WEBGL_compressed_texture_s3tc": + extension = gl.getExtension("WEBGL_compressed_texture_s3tc") || gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"); + break; + case "WEBGL_compressed_texture_pvrtc": + extension = gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"); + break; + default: + extension = gl.getExtension(name2); + } + extensions[name2] = extension; + return extension; + } + return { + has: function(name2) { + return getExtension(name2) !== null; + }, + init: function() { + getExtension("EXT_color_buffer_float"); + getExtension("WEBGL_clip_cull_distance"); + getExtension("OES_texture_float_linear"); + getExtension("EXT_color_buffer_half_float"); + getExtension("WEBGL_multisampled_render_to_texture"); + getExtension("WEBGL_render_shared_exponent"); + }, + get: function(name2) { + const extension = getExtension(name2); + if (extension === null) { + warnOnce2("THREE.WebGLRenderer: " + name2 + " extension not supported."); + } + return extension; + } + }; + } + function WebGLGeometries2(gl, attributes, info, bindingStates) { + const geometries = {}; + const wireframeAttributes = new WeakMap; + function onGeometryDispose(event) { + const geometry = event.target; + if (geometry.index !== null) { + attributes.remove(geometry.index); + } + for (const name2 in geometry.attributes) { + attributes.remove(geometry.attributes[name2]); + } + geometry.removeEventListener("dispose", onGeometryDispose); + delete geometries[geometry.id]; + const attribute = wireframeAttributes.get(geometry); + if (attribute) { + attributes.remove(attribute); + wireframeAttributes.delete(geometry); + } + bindingStates.releaseStatesOfGeometry(geometry); + if (geometry.isInstancedBufferGeometry === true) { + delete geometry._maxInstanceCount; + } + info.memory.geometries--; + } + function get(object, geometry) { + if (geometries[geometry.id] === true) + return geometry; + geometry.addEventListener("dispose", onGeometryDispose); + geometries[geometry.id] = true; + info.memory.geometries++; + return geometry; + } + function update(geometry) { + const geometryAttributes = geometry.attributes; + for (const name2 in geometryAttributes) { + attributes.update(geometryAttributes[name2], gl.ARRAY_BUFFER); + } + } + function updateWireframeAttribute(geometry) { + const indices = []; + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + if (geometryIndex !== null) { + const array = geometryIndex.array; + version = geometryIndex.version; + for (let i = 0, l2 = array.length;i < l2; i += 3) { + const a2 = array[i + 0]; + const b2 = array[i + 1]; + const c2 = array[i + 2]; + indices.push(a2, b2, b2, c2, c2, a2); + } + } else if (geometryPosition !== undefined) { + const array = geometryPosition.array; + version = geometryPosition.version; + for (let i = 0, l2 = array.length / 3 - 1;i < l2; i += 3) { + const a2 = i + 0; + const b2 = i + 1; + const c2 = i + 2; + indices.push(a2, b2, b2, c2, c2, a2); + } + } else { + return; + } + const attribute = new ((arrayNeedsUint322(indices)) ? Uint32BufferAttribute2 : Uint16BufferAttribute2)(indices, 1); + attribute.version = version; + const previousAttribute = wireframeAttributes.get(geometry); + if (previousAttribute) + attributes.remove(previousAttribute); + wireframeAttributes.set(geometry, attribute); + } + function getWireframeAttribute(geometry) { + const currentAttribute = wireframeAttributes.get(geometry); + if (currentAttribute) { + const geometryIndex = geometry.index; + if (geometryIndex !== null) { + if (currentAttribute.version < geometryIndex.version) { + updateWireframeAttribute(geometry); + } + } + } else { + updateWireframeAttribute(geometry); + } + return wireframeAttributes.get(geometry); + } + return { + get, + update, + getWireframeAttribute + }; + } + function WebGLIndexedBufferRenderer2(gl, extensions, info) { + let mode; + function setMode(value2) { + mode = value2; + } + let type, bytesPerElement; + function setIndex(value2) { + type = value2.type; + bytesPerElement = value2.bytesPerElement; + } + function render(start, count) { + gl.drawElements(mode, count, type, start * bytesPerElement); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) + return; + gl.drawElementsInstanced(mode, count, type, start * bytesPerElement, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawElementsWEBGL(mode, counts, 0, type, starts, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0;i < starts.length; i++) { + renderInstances(starts[i] / bytesPerElement, counts[i], primcount[i]); + } + } else { + extension.multiDrawElementsInstancedWEBGL(mode, counts, 0, type, starts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i] * primcount[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; + } + function WebGLInfo2(gl) { + const memory = { + geometries: 0, + textures: 0 + }; + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + function update(count, mode, instanceCount) { + render.calls++; + switch (mode) { + case gl.TRIANGLES: + render.triangles += instanceCount * (count / 3); + break; + case gl.LINES: + render.lines += instanceCount * (count / 2); + break; + case gl.LINE_STRIP: + render.lines += instanceCount * (count - 1); + break; + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + case gl.POINTS: + render.points += instanceCount * count; + break; + default: + console.error("THREE.WebGLInfo: Unknown draw mode:", mode); + break; + } + } + function reset() { + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + } + return { + memory, + render, + programs: null, + autoReset: true, + reset, + update + }; + } + function WebGLMorphtargets2(gl, capabilities, textures) { + const morphTextures = new WeakMap; + const morph = new Vector42; + function update(object, geometry, program) { + const objectInfluences = object.morphTargetInfluences; + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + let entry = morphTextures.get(geometry); + if (entry === undefined || entry.count !== morphTargetsCount) { + let disposeTexture = function() { + texture.dispose(); + morphTextures.delete(geometry); + geometry.removeEventListener("dispose", disposeTexture); + }; + if (entry !== undefined) + entry.texture.dispose(); + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + let vertexDataCount = 0; + if (hasMorphPosition === true) + vertexDataCount = 1; + if (hasMorphNormals === true) + vertexDataCount = 2; + if (hasMorphColors === true) + vertexDataCount = 3; + let width2 = geometry.attributes.position.count * vertexDataCount; + let height2 = 1; + if (width2 > capabilities.maxTextureSize) { + height2 = Math.ceil(width2 / capabilities.maxTextureSize); + width2 = capabilities.maxTextureSize; + } + const buffer = new Float32Array(width2 * height2 * 4 * morphTargetsCount); + const texture = new DataArrayTexture2(buffer, width2, height2, morphTargetsCount); + texture.type = FloatType2; + texture.needsUpdate = true; + const vertexDataStride = vertexDataCount * 4; + for (let i = 0;i < morphTargetsCount; i++) { + const morphTarget = morphTargets[i]; + const morphNormal = morphNormals[i]; + const morphColor = morphColors[i]; + const offset = width2 * height2 * 4 * i; + for (let j2 = 0;j2 < morphTarget.count; j2++) { + const stride = j2 * vertexDataStride; + if (hasMorphPosition === true) { + morph.fromBufferAttribute(morphTarget, j2); + buffer[offset + stride + 0] = morph.x; + buffer[offset + stride + 1] = morph.y; + buffer[offset + stride + 2] = morph.z; + buffer[offset + stride + 3] = 0; + } + if (hasMorphNormals === true) { + morph.fromBufferAttribute(morphNormal, j2); + buffer[offset + stride + 4] = morph.x; + buffer[offset + stride + 5] = morph.y; + buffer[offset + stride + 6] = morph.z; + buffer[offset + stride + 7] = 0; + } + if (hasMorphColors === true) { + morph.fromBufferAttribute(morphColor, j2); + buffer[offset + stride + 8] = morph.x; + buffer[offset + stride + 9] = morph.y; + buffer[offset + stride + 10] = morph.z; + buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1; + } + } + } + entry = { + count: morphTargetsCount, + texture, + size: new Vector22(width2, height2) + }; + morphTextures.set(geometry, entry); + geometry.addEventListener("dispose", disposeTexture); + } + if (object.isInstancedMesh === true && object.morphTexture !== null) { + program.getUniforms().setValue(gl, "morphTexture", object.morphTexture, textures); + } else { + let morphInfluencesSum = 0; + for (let i = 0;i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence); + program.getUniforms().setValue(gl, "morphTargetInfluences", objectInfluences); + } + program.getUniforms().setValue(gl, "morphTargetsTexture", entry.texture, textures); + program.getUniforms().setValue(gl, "morphTargetsTextureSize", entry.size); + } + return { + update + }; + } + function WebGLObjects2(gl, geometries, attributes, info) { + let updateMap = new WeakMap; + function update(object) { + const frame = info.render.frame; + const geometry = object.geometry; + const buffergeometry = geometries.get(object, geometry); + if (updateMap.get(buffergeometry) !== frame) { + geometries.update(buffergeometry); + updateMap.set(buffergeometry, frame); + } + if (object.isInstancedMesh) { + if (object.hasEventListener("dispose", onInstancedMeshDispose) === false) { + object.addEventListener("dispose", onInstancedMeshDispose); + } + if (updateMap.get(object) !== frame) { + attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER); + if (object.instanceColor !== null) { + attributes.update(object.instanceColor, gl.ARRAY_BUFFER); + } + updateMap.set(object, frame); + } + } + if (object.isSkinnedMesh) { + const skeleton = object.skeleton; + if (updateMap.get(skeleton) !== frame) { + skeleton.update(); + updateMap.set(skeleton, frame); + } + } + return buffergeometry; + } + function dispose() { + updateMap = new WeakMap; + } + function onInstancedMeshDispose(event) { + const instancedMesh = event.target; + instancedMesh.removeEventListener("dispose", onInstancedMeshDispose); + attributes.remove(instancedMesh.instanceMatrix); + if (instancedMesh.instanceColor !== null) + attributes.remove(instancedMesh.instanceColor); + } + return { + update, + dispose + }; + } + var emptyTexture2 = /* @__PURE__ */ new Texture2; + var emptyShadowTexture2 = /* @__PURE__ */ new DepthTexture2(1, 1); + var emptyArrayTexture2 = /* @__PURE__ */ new DataArrayTexture2; + var empty3dTexture2 = /* @__PURE__ */ new Data3DTexture2; + var emptyCubeTexture2 = /* @__PURE__ */ new CubeTexture2; + var arrayCacheF322 = []; + var arrayCacheI322 = []; + var mat4array2 = new Float32Array(16); + var mat3array2 = new Float32Array(9); + var mat2array2 = new Float32Array(4); + function flatten3(array, nBlocks, blockSize) { + const firstElem = array[0]; + if (firstElem <= 0 || firstElem > 0) + return array; + const n2 = nBlocks * blockSize; + let r = arrayCacheF322[n2]; + if (r === undefined) { + r = new Float32Array(n2); + arrayCacheF322[n2] = r; + } + if (nBlocks !== 0) { + firstElem.toArray(r, 0); + for (let i = 1, offset = 0;i !== nBlocks; ++i) { + offset += blockSize; + array[i].toArray(r, offset); + } + } + return r; + } + function arraysEqual3(a2, b2) { + if (a2.length !== b2.length) + return false; + for (let i = 0, l2 = a2.length;i < l2; i++) { + if (a2[i] !== b2[i]) + return false; + } + return true; + } + function copyArray2(a2, b2) { + for (let i = 0, l2 = b2.length;i < l2; i++) { + a2[i] = b2[i]; + } + } + function allocTexUnits2(textures, n2) { + let r = arrayCacheI322[n2]; + if (r === undefined) { + r = new Int32Array(n2); + arrayCacheI322[n2] = r; + } + for (let i = 0;i !== n2; ++i) { + r[i] = textures.allocateTextureUnit(); + } + return r; + } + function setValueV1f2(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1f(this.addr, v); + cache[0] = v; + } + function setValueV2f2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2f(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform2fv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV3f2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3f(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else if (v.r !== undefined) { + if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) { + gl.uniform3f(this.addr, v.r, v.g, v.b); + cache[0] = v.r; + cache[1] = v.g; + cache[2] = v.b; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform3fv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV4f2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4f(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform4fv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueM22(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual3(cache, v)) + return; + gl.uniformMatrix2fv(this.addr, false, v); + copyArray2(cache, v); + } else { + if (arraysEqual3(cache, elements)) + return; + mat2array2.set(elements); + gl.uniformMatrix2fv(this.addr, false, mat2array2); + copyArray2(cache, elements); + } + } + function setValueM32(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual3(cache, v)) + return; + gl.uniformMatrix3fv(this.addr, false, v); + copyArray2(cache, v); + } else { + if (arraysEqual3(cache, elements)) + return; + mat3array2.set(elements); + gl.uniformMatrix3fv(this.addr, false, mat3array2); + copyArray2(cache, elements); + } + } + function setValueM42(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual3(cache, v)) + return; + gl.uniformMatrix4fv(this.addr, false, v); + copyArray2(cache, v); + } else { + if (arraysEqual3(cache, elements)) + return; + mat4array2.set(elements); + gl.uniformMatrix4fv(this.addr, false, mat4array2); + copyArray2(cache, elements); + } + } + function setValueV1i2(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1i(this.addr, v); + cache[0] = v; + } + function setValueV2i2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2i(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform2iv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV3i2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3i(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform3iv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV4i2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4i(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform4iv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV1ui2(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1ui(this.addr, v); + cache[0] = v; + } + function setValueV2ui2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2ui(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform2uiv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV3ui2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3ui(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform3uiv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueV4ui2(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4ui(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual3(cache, v)) + return; + gl.uniform4uiv(this.addr, v); + copyArray2(cache, v); + } + } + function setValueT12(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + let emptyTexture2D; + if (this.type === gl.SAMPLER_2D_SHADOW) { + emptyShadowTexture2.compareFunction = LessEqualCompare2; + emptyTexture2D = emptyShadowTexture2; + } else { + emptyTexture2D = emptyTexture2; + } + textures.setTexture2D(v || emptyTexture2D, unit); + } + function setValueT3D12(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture3D(v || empty3dTexture2, unit); + } + function setValueT62(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTextureCube(v || emptyCubeTexture2, unit); + } + function setValueT2DArray12(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture2DArray(v || emptyArrayTexture2, unit); + } + function getSingularSetter2(type) { + switch (type) { + case 5126: + return setValueV1f2; + case 35664: + return setValueV2f2; + case 35665: + return setValueV3f2; + case 35666: + return setValueV4f2; + case 35674: + return setValueM22; + case 35675: + return setValueM32; + case 35676: + return setValueM42; + case 5124: + case 35670: + return setValueV1i2; + case 35667: + case 35671: + return setValueV2i2; + case 35668: + case 35672: + return setValueV3i2; + case 35669: + case 35673: + return setValueV4i2; + case 5125: + return setValueV1ui2; + case 36294: + return setValueV2ui2; + case 36295: + return setValueV3ui2; + case 36296: + return setValueV4ui2; + case 35678: + case 36198: + case 36298: + case 36306: + case 35682: + return setValueT12; + case 35679: + case 36299: + case 36307: + return setValueT3D12; + case 35680: + case 36300: + case 36308: + case 36293: + return setValueT62; + case 36289: + case 36303: + case 36311: + case 36292: + return setValueT2DArray12; + } + } + function setValueV1fArray2(gl, v) { + gl.uniform1fv(this.addr, v); + } + function setValueV2fArray2(gl, v) { + const data2 = flatten3(v, this.size, 2); + gl.uniform2fv(this.addr, data2); + } + function setValueV3fArray2(gl, v) { + const data2 = flatten3(v, this.size, 3); + gl.uniform3fv(this.addr, data2); + } + function setValueV4fArray2(gl, v) { + const data2 = flatten3(v, this.size, 4); + gl.uniform4fv(this.addr, data2); + } + function setValueM2Array2(gl, v) { + const data2 = flatten3(v, this.size, 4); + gl.uniformMatrix2fv(this.addr, false, data2); + } + function setValueM3Array2(gl, v) { + const data2 = flatten3(v, this.size, 9); + gl.uniformMatrix3fv(this.addr, false, data2); + } + function setValueM4Array2(gl, v) { + const data2 = flatten3(v, this.size, 16); + gl.uniformMatrix4fv(this.addr, false, data2); + } + function setValueV1iArray2(gl, v) { + gl.uniform1iv(this.addr, v); + } + function setValueV2iArray2(gl, v) { + gl.uniform2iv(this.addr, v); + } + function setValueV3iArray2(gl, v) { + gl.uniform3iv(this.addr, v); + } + function setValueV4iArray2(gl, v) { + gl.uniform4iv(this.addr, v); + } + function setValueV1uiArray2(gl, v) { + gl.uniform1uiv(this.addr, v); + } + function setValueV2uiArray2(gl, v) { + gl.uniform2uiv(this.addr, v); + } + function setValueV3uiArray2(gl, v) { + gl.uniform3uiv(this.addr, v); + } + function setValueV4uiArray2(gl, v) { + gl.uniform4uiv(this.addr, v); + } + function setValueT1Array2(gl, v, textures) { + const cache = this.cache; + const n2 = v.length; + const units = allocTexUnits2(textures, n2); + if (!arraysEqual3(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray2(cache, units); + } + for (let i = 0;i !== n2; ++i) { + textures.setTexture2D(v[i] || emptyTexture2, units[i]); + } + } + function setValueT3DArray2(gl, v, textures) { + const cache = this.cache; + const n2 = v.length; + const units = allocTexUnits2(textures, n2); + if (!arraysEqual3(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray2(cache, units); + } + for (let i = 0;i !== n2; ++i) { + textures.setTexture3D(v[i] || empty3dTexture2, units[i]); + } + } + function setValueT6Array2(gl, v, textures) { + const cache = this.cache; + const n2 = v.length; + const units = allocTexUnits2(textures, n2); + if (!arraysEqual3(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray2(cache, units); + } + for (let i = 0;i !== n2; ++i) { + textures.setTextureCube(v[i] || emptyCubeTexture2, units[i]); + } + } + function setValueT2DArrayArray2(gl, v, textures) { + const cache = this.cache; + const n2 = v.length; + const units = allocTexUnits2(textures, n2); + if (!arraysEqual3(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray2(cache, units); + } + for (let i = 0;i !== n2; ++i) { + textures.setTexture2DArray(v[i] || emptyArrayTexture2, units[i]); + } + } + function getPureArraySetter2(type) { + switch (type) { + case 5126: + return setValueV1fArray2; + case 35664: + return setValueV2fArray2; + case 35665: + return setValueV3fArray2; + case 35666: + return setValueV4fArray2; + case 35674: + return setValueM2Array2; + case 35675: + return setValueM3Array2; + case 35676: + return setValueM4Array2; + case 5124: + case 35670: + return setValueV1iArray2; + case 35667: + case 35671: + return setValueV2iArray2; + case 35668: + case 35672: + return setValueV3iArray2; + case 35669: + case 35673: + return setValueV4iArray2; + case 5125: + return setValueV1uiArray2; + case 36294: + return setValueV2uiArray2; + case 36295: + return setValueV3uiArray2; + case 36296: + return setValueV4uiArray2; + case 35678: + case 36198: + case 36298: + case 36306: + case 35682: + return setValueT1Array2; + case 35679: + case 36299: + case 36307: + return setValueT3DArray2; + case 35680: + case 36300: + case 36308: + case 36293: + return setValueT6Array2; + case 36289: + case 36303: + case 36311: + case 36292: + return setValueT2DArrayArray2; + } + } + + class SingleUniform2 { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.setValue = getSingularSetter2(activeInfo.type); + } + } + + class PureArrayUniform2 { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.size = activeInfo.size; + this.setValue = getPureArraySetter2(activeInfo.type); + } + } + + class StructuredUniform2 { + constructor(id) { + this.id = id; + this.seq = []; + this.map = {}; + } + setValue(gl, value2, textures) { + const seq = this.seq; + for (let i = 0, n2 = seq.length;i !== n2; ++i) { + const u2 = seq[i]; + u2.setValue(gl, value2[u2.id], textures); + } + } + } + var RePathPart2 = /(\w+)(\])?(\[|\.)?/g; + function addUniform2(container, uniformObject) { + container.seq.push(uniformObject); + container.map[uniformObject.id] = uniformObject; + } + function parseUniform2(activeInfo, addr, container) { + const path = activeInfo.name, pathLength = path.length; + RePathPart2.lastIndex = 0; + while (true) { + const match = RePathPart2.exec(path), matchEnd = RePathPart2.lastIndex; + let id = match[1]; + const idIsIndex = match[2] === "]", subscript = match[3]; + if (idIsIndex) + id = id | 0; + if (subscript === undefined || subscript === "[" && matchEnd + 2 === pathLength) { + addUniform2(container, subscript === undefined ? new SingleUniform2(id, activeInfo, addr) : new PureArrayUniform2(id, activeInfo, addr)); + break; + } else { + const map2 = container.map; + let next = map2[id]; + if (next === undefined) { + next = new StructuredUniform2(id); + addUniform2(container, next); + } + container = next; + } + } + } + + class WebGLUniforms2 { + constructor(gl, program) { + this.seq = []; + this.map = {}; + const n2 = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (let i = 0;i < n2; ++i) { + const info = gl.getActiveUniform(program, i), addr = gl.getUniformLocation(program, info.name); + parseUniform2(info, addr, this); + } + } + setValue(gl, name2, value2, textures) { + const u2 = this.map[name2]; + if (u2 !== undefined) + u2.setValue(gl, value2, textures); + } + setOptional(gl, object, name2) { + const v = object[name2]; + if (v !== undefined) + this.setValue(gl, name2, v); + } + static upload(gl, seq, values2, textures) { + for (let i = 0, n2 = seq.length;i !== n2; ++i) { + const u2 = seq[i], v = values2[u2.id]; + if (v.needsUpdate !== false) { + u2.setValue(gl, v.value, textures); + } + } + } + static seqWithValue(seq, values2) { + const r = []; + for (let i = 0, n2 = seq.length;i !== n2; ++i) { + const u2 = seq[i]; + if (u2.id in values2) + r.push(u2); + } + return r; + } + } + function WebGLShader2(gl, type, string) { + const shader = gl.createShader(type); + gl.shaderSource(shader, string); + gl.compileShader(shader); + return shader; + } + var COMPLETION_STATUS_KHR2 = 37297; + var programIdCount2 = 0; + function handleSource2(string, errorLine) { + const lines = string.split(` +`); + const lines2 = []; + const from = Math.max(errorLine - 6, 0); + const to = Math.min(errorLine + 6, lines.length); + for (let i = from;i < to; i++) { + const line2 = i + 1; + lines2.push(`${line2 === errorLine ? ">" : " "} ${line2}: ${lines[i]}`); + } + return lines2.join(` +`); + } + var _m02 = /* @__PURE__ */ new Matrix32; + function getEncodingComponents2(colorSpace) { + ColorManagement2._getMatrix(_m02, ColorManagement2.workingColorSpace, colorSpace); + const encodingMatrix = `mat3( ${_m02.elements.map((v) => v.toFixed(4))} )`; + switch (ColorManagement2.getTransfer(colorSpace)) { + case LinearTransfer2: + return [encodingMatrix, "LinearTransferOETF"]; + case SRGBTransfer2: + return [encodingMatrix, "sRGBTransferOETF"]; + default: + console.warn("THREE.WebGLProgram: Unsupported color space: ", colorSpace); + return [encodingMatrix, "LinearTransferOETF"]; + } + } + function getShaderErrors2(gl, shader, type) { + const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS); + const errors = gl.getShaderInfoLog(shader).trim(); + if (status && errors === "") + return ""; + const errorMatches = /ERROR: 0:(\d+)/.exec(errors); + if (errorMatches) { + const errorLine = parseInt(errorMatches[1]); + return type.toUpperCase() + ` + +` + errors + ` + +` + handleSource2(gl.getShaderSource(shader), errorLine); + } else { + return errors; + } + } + function getTexelEncodingFunction2(functionName, colorSpace) { + const components = getEncodingComponents2(colorSpace); + return [ + `vec4 ${functionName}( vec4 value ) {`, + ` return ${components[1]}( vec4( value.rgb * ${components[0]}, value.a ) );`, + "}" + ].join(` +`); + } + function getToneMappingFunction2(functionName, toneMapping) { + let toneMappingName; + switch (toneMapping) { + case LinearToneMapping2: + toneMappingName = "Linear"; + break; + case ReinhardToneMapping2: + toneMappingName = "Reinhard"; + break; + case CineonToneMapping2: + toneMappingName = "Cineon"; + break; + case ACESFilmicToneMapping2: + toneMappingName = "ACESFilmic"; + break; + case AgXToneMapping2: + toneMappingName = "AgX"; + break; + case NeutralToneMapping2: + toneMappingName = "Neutral"; + break; + case CustomToneMapping2: + toneMappingName = "Custom"; + break; + default: + console.warn("THREE.WebGLProgram: Unsupported toneMapping:", toneMapping); + toneMappingName = "Linear"; + } + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; + } + var _v03 = /* @__PURE__ */ new Vector32; + function getLuminanceFunction2() { + ColorManagement2.getLuminanceCoefficients(_v03); + const r = _v03.x.toFixed(4); + const g3 = _v03.y.toFixed(4); + const b2 = _v03.z.toFixed(4); + return [ + "float luminance( const in vec3 rgb ) {", + ` const vec3 weights = vec3( ${r}, ${g3}, ${b2} );`, + "\treturn dot( weights, rgb );", + "}" + ].join(` +`); + } + function generateVertexExtensions2(parameters) { + const chunks = [ + parameters.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "", + parameters.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : "" + ]; + return chunks.filter(filterEmptyLine2).join(` +`); + } + function generateDefines2(defines) { + const chunks = []; + for (const name2 in defines) { + const value2 = defines[name2]; + if (value2 === false) + continue; + chunks.push("#define " + name2 + " " + value2); + } + return chunks.join(` +`); + } + function fetchAttributeLocations2(gl, program) { + const attributes = {}; + const n2 = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (let i = 0;i < n2; i++) { + const info = gl.getActiveAttrib(program, i); + const name2 = info.name; + let locationSize = 1; + if (info.type === gl.FLOAT_MAT2) + locationSize = 2; + if (info.type === gl.FLOAT_MAT3) + locationSize = 3; + if (info.type === gl.FLOAT_MAT4) + locationSize = 4; + attributes[name2] = { + type: info.type, + location: gl.getAttribLocation(program, name2), + locationSize + }; + } + return attributes; + } + function filterEmptyLine2(string) { + return string !== ""; + } + function replaceLightNums2(string, parameters) { + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows); + } + function replaceClippingPlaneNums2(string, parameters) { + return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection); + } + var includePattern2 = /^[ \t]*#include +<([\w\d./]+)>/gm; + function resolveIncludes2(string) { + return string.replace(includePattern2, includeReplacer2); + } + var shaderChunkMap2 = new Map; + function includeReplacer2(match, include) { + let string = ShaderChunk2[include]; + if (string === undefined) { + const newInclude = shaderChunkMap2.get(include); + if (newInclude !== undefined) { + string = ShaderChunk2[newInclude]; + console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude); + } else { + throw new Error("Can not resolve #include <" + include + ">"); + } + } + return resolveIncludes2(string); + } + var unrollLoopPattern2 = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; + function unrollLoops2(string) { + return string.replace(unrollLoopPattern2, loopReplacer2); + } + function loopReplacer2(match, start, end, snippet) { + let string = ""; + for (let i = parseInt(start);i < parseInt(end); i++) { + string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i + " ]").replace(/UNROLLED_LOOP_INDEX/g, i); + } + return string; + } + function generatePrecision2(parameters) { + let precisionstring = `precision ${parameters.precision} float; + precision ${parameters.precision} int; + precision ${parameters.precision} sampler2D; + precision ${parameters.precision} samplerCube; + precision ${parameters.precision} sampler3D; + precision ${parameters.precision} sampler2DArray; + precision ${parameters.precision} sampler2DShadow; + precision ${parameters.precision} samplerCubeShadow; + precision ${parameters.precision} sampler2DArrayShadow; + precision ${parameters.precision} isampler2D; + precision ${parameters.precision} isampler3D; + precision ${parameters.precision} isamplerCube; + precision ${parameters.precision} isampler2DArray; + precision ${parameters.precision} usampler2D; + precision ${parameters.precision} usampler3D; + precision ${parameters.precision} usamplerCube; + precision ${parameters.precision} usampler2DArray; + `; + if (parameters.precision === "highp") { + precisionstring += ` +#define HIGH_PRECISION`; + } else if (parameters.precision === "mediump") { + precisionstring += ` +#define MEDIUM_PRECISION`; + } else if (parameters.precision === "lowp") { + precisionstring += ` +#define LOW_PRECISION`; + } + return precisionstring; + } + function generateShadowMapTypeDefine2(parameters) { + let shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; + if (parameters.shadowMapType === PCFShadowMap2) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; + } else if (parameters.shadowMapType === PCFSoftShadowMap2) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; + } else if (parameters.shadowMapType === VSMShadowMap2) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_VSM"; + } + return shadowMapTypeDefine; + } + function generateEnvMapTypeDefine2(parameters) { + let envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeReflectionMapping2: + case CubeRefractionMapping2: + envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + break; + case CubeUVReflectionMapping2: + envMapTypeDefine = "ENVMAP_TYPE_CUBE_UV"; + break; + } + } + return envMapTypeDefine; + } + function generateEnvMapModeDefine2(parameters) { + let envMapModeDefine = "ENVMAP_MODE_REFLECTION"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeRefractionMapping2: + envMapModeDefine = "ENVMAP_MODE_REFRACTION"; + break; + } + } + return envMapModeDefine; + } + function generateEnvMapBlendingDefine2(parameters) { + let envMapBlendingDefine = "ENVMAP_BLENDING_NONE"; + if (parameters.envMap) { + switch (parameters.combine) { + case MultiplyOperation2: + envMapBlendingDefine = "ENVMAP_BLENDING_MULTIPLY"; + break; + case MixOperation2: + envMapBlendingDefine = "ENVMAP_BLENDING_MIX"; + break; + case AddOperation2: + envMapBlendingDefine = "ENVMAP_BLENDING_ADD"; + break; + } + } + return envMapBlendingDefine; + } + function generateCubeUVSize2(parameters) { + const imageHeight = parameters.envMapCubeUVHeight; + if (imageHeight === null) + return null; + const maxMip = Math.log2(imageHeight) - 2; + const texelHeight = 1 / imageHeight; + const texelWidth = 1 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16)); + return { texelWidth, texelHeight, maxMip }; + } + function WebGLProgram2(renderer2, cacheKey, parameters, bindingStates) { + const gl = renderer2.getContext(); + const defines = parameters.defines; + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + const shadowMapTypeDefine = generateShadowMapTypeDefine2(parameters); + const envMapTypeDefine = generateEnvMapTypeDefine2(parameters); + const envMapModeDefine = generateEnvMapModeDefine2(parameters); + const envMapBlendingDefine = generateEnvMapBlendingDefine2(parameters); + const envMapCubeUVSize = generateCubeUVSize2(parameters); + const customVertexExtensions = generateVertexExtensions2(parameters); + const customDefines = generateDefines2(defines); + const program = gl.createProgram(); + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? "#version " + parameters.glslVersion + ` +` : ""; + if (parameters.isRawShaderMaterial) { + prefixVertex = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine2).join(` +`); + if (prefixVertex.length > 0) { + prefixVertex += ` +`; + } + prefixFragment = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine2).join(` +`); + if (prefixFragment.length > 0) { + prefixFragment += ` +`; + } + } else { + prefixVertex = [ + generatePrecision2(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "", + parameters.batching ? "#define USE_BATCHING" : "", + parameters.batchingColor ? "#define USE_BATCHING_COLOR" : "", + parameters.instancing ? "#define USE_INSTANCING" : "", + parameters.instancingColor ? "#define USE_INSTANCING_COLOR" : "", + parameters.instancingMorph ? "#define USE_INSTANCING_MORPH" : "", + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.displacementMap ? "#define USE_DISPLACEMENTMAP" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.mapUv ? "#define MAP_UV " + parameters.mapUv : "", + parameters.alphaMapUv ? "#define ALPHAMAP_UV " + parameters.alphaMapUv : "", + parameters.lightMapUv ? "#define LIGHTMAP_UV " + parameters.lightMapUv : "", + parameters.aoMapUv ? "#define AOMAP_UV " + parameters.aoMapUv : "", + parameters.emissiveMapUv ? "#define EMISSIVEMAP_UV " + parameters.emissiveMapUv : "", + parameters.bumpMapUv ? "#define BUMPMAP_UV " + parameters.bumpMapUv : "", + parameters.normalMapUv ? "#define NORMALMAP_UV " + parameters.normalMapUv : "", + parameters.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + parameters.displacementMapUv : "", + parameters.metalnessMapUv ? "#define METALNESSMAP_UV " + parameters.metalnessMapUv : "", + parameters.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + parameters.roughnessMapUv : "", + parameters.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + parameters.anisotropyMapUv : "", + parameters.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + parameters.clearcoatMapUv : "", + parameters.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + parameters.clearcoatNormalMapUv : "", + parameters.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + parameters.clearcoatRoughnessMapUv : "", + parameters.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + parameters.iridescenceMapUv : "", + parameters.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + parameters.iridescenceThicknessMapUv : "", + parameters.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + parameters.sheenColorMapUv : "", + parameters.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + parameters.sheenRoughnessMapUv : "", + parameters.specularMapUv ? "#define SPECULARMAP_UV " + parameters.specularMapUv : "", + parameters.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + parameters.specularColorMapUv : "", + parameters.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + parameters.specularIntensityMapUv : "", + parameters.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + parameters.transmissionMapUv : "", + parameters.thicknessMapUv ? "#define THICKNESSMAP_UV " + parameters.thicknessMapUv : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.skinning ? "#define USE_SKINNING" : "", + parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", + parameters.morphNormals && parameters.flatShading === false ? "#define USE_MORPHNORMALS" : "", + parameters.morphColors ? "#define USE_MORPHCOLORS" : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + parameters.morphTextureStride : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + parameters.morphTargetsCount : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "", + "uniform mat4 modelMatrix;", + "uniform mat4 modelViewMatrix;", + "uniform mat4 projectionMatrix;", + "uniform mat4 viewMatrix;", + "uniform mat3 normalMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + "#ifdef USE_INSTANCING", + "\tattribute mat4 instanceMatrix;", + "#endif", + "#ifdef USE_INSTANCING_COLOR", + "\tattribute vec3 instanceColor;", + "#endif", + "#ifdef USE_INSTANCING_MORPH", + "\tuniform sampler2D morphTexture;", + "#endif", + "attribute vec3 position;", + "attribute vec3 normal;", + "attribute vec2 uv;", + "#ifdef USE_UV1", + "\tattribute vec2 uv1;", + "#endif", + "#ifdef USE_UV2", + "\tattribute vec2 uv2;", + "#endif", + "#ifdef USE_UV3", + "\tattribute vec2 uv3;", + "#endif", + "#ifdef USE_TANGENT", + "\tattribute vec4 tangent;", + "#endif", + "#if defined( USE_COLOR_ALPHA )", + "\tattribute vec4 color;", + "#elif defined( USE_COLOR )", + "\tattribute vec3 color;", + "#endif", + "#ifdef USE_SKINNING", + "\tattribute vec4 skinIndex;", + "\tattribute vec4 skinWeight;", + "#endif", + ` +` + ].filter(filterEmptyLine2).join(` +`); + prefixFragment = [ + generatePrecision2(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.matcap ? "#define USE_MATCAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapTypeDefine : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.envMap ? "#define " + envMapBlendingDefine : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_WIDTH " + envMapCubeUVSize.texelWidth : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_HEIGHT " + envMapCubeUVSize.texelHeight : "", + envMapCubeUVSize ? "#define CUBEUV_MAX_MIP " + envMapCubeUVSize.maxMip + ".0" : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoat ? "#define USE_CLEARCOAT" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.dispersion ? "#define USE_DISPERSION" : "", + parameters.iridescence ? "#define USE_IRIDESCENCE" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaTest ? "#define USE_ALPHATEST" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.sheen ? "#define USE_SHEEN" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.gradientMap ? "#define USE_GRADIENTMAP" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", + parameters.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "", + "uniform mat4 viewMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + parameters.toneMapping !== NoToneMapping2 ? "#define TONE_MAPPING" : "", + parameters.toneMapping !== NoToneMapping2 ? ShaderChunk2["tonemapping_pars_fragment"] : "", + parameters.toneMapping !== NoToneMapping2 ? getToneMappingFunction2("toneMapping", parameters.toneMapping) : "", + parameters.dithering ? "#define DITHERING" : "", + parameters.opaque ? "#define OPAQUE" : "", + ShaderChunk2["colorspace_pars_fragment"], + getTexelEncodingFunction2("linearToOutputTexel", parameters.outputColorSpace), + getLuminanceFunction2(), + parameters.useDepthPacking ? "#define DEPTH_PACKING " + parameters.depthPacking : "", + ` +` + ].filter(filterEmptyLine2).join(` +`); + } + vertexShader = resolveIncludes2(vertexShader); + vertexShader = replaceLightNums2(vertexShader, parameters); + vertexShader = replaceClippingPlaneNums2(vertexShader, parameters); + fragmentShader = resolveIncludes2(fragmentShader); + fragmentShader = replaceLightNums2(fragmentShader, parameters); + fragmentShader = replaceClippingPlaneNums2(fragmentShader, parameters); + vertexShader = unrollLoops2(vertexShader); + fragmentShader = unrollLoops2(fragmentShader); + if (parameters.isRawShaderMaterial !== true) { + versionString = `#version 300 es +`; + prefixVertex = [ + customVertexExtensions, + "#define attribute in", + "#define varying out", + "#define texture2D texture" + ].join(` +`) + ` +` + prefixVertex; + prefixFragment = [ + "#define varying in", + parameters.glslVersion === GLSL32 ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", + parameters.glslVersion === GLSL32 ? "" : "#define gl_FragColor pc_fragColor", + "#define gl_FragDepthEXT gl_FragDepth", + "#define texture2D texture", + "#define textureCube texture", + "#define texture2DProj textureProj", + "#define texture2DLodEXT textureLod", + "#define texture2DProjLodEXT textureProjLod", + "#define textureCubeLodEXT textureLod", + "#define texture2DGradEXT textureGrad", + "#define texture2DProjGradEXT textureProjGrad", + "#define textureCubeGradEXT textureGrad" + ].join(` +`) + ` +` + prefixFragment; + } + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + const glVertexShader = WebGLShader2(gl, gl.VERTEX_SHADER, vertexGlsl); + const glFragmentShader = WebGLShader2(gl, gl.FRAGMENT_SHADER, fragmentGlsl); + gl.attachShader(program, glVertexShader); + gl.attachShader(program, glFragmentShader); + if (parameters.index0AttributeName !== undefined) { + gl.bindAttribLocation(program, 0, parameters.index0AttributeName); + } else if (parameters.morphTargets === true) { + gl.bindAttribLocation(program, 0, "position"); + } + gl.linkProgram(program); + function onFirstUse(self2) { + if (renderer2.debug.checkShaderErrors) { + const programLog = gl.getProgramInfoLog(program).trim(); + const vertexLog = gl.getShaderInfoLog(glVertexShader).trim(); + const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim(); + let runnable = true; + let haveDiagnostics = true; + if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) { + runnable = false; + if (typeof renderer2.debug.onShaderError === "function") { + renderer2.debug.onShaderError(gl, program, glVertexShader, glFragmentShader); + } else { + const vertexErrors = getShaderErrors2(gl, glVertexShader, "vertex"); + const fragmentErrors = getShaderErrors2(gl, glFragmentShader, "fragment"); + console.error("THREE.WebGLProgram: Shader Error " + gl.getError() + " - " + "VALIDATE_STATUS " + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + ` + +` + "Material Name: " + self2.name + ` +` + "Material Type: " + self2.type + ` + +` + "Program Info Log: " + programLog + ` +` + vertexErrors + ` +` + fragmentErrors); + } + } else if (programLog !== "") { + console.warn("THREE.WebGLProgram: Program Info Log:", programLog); + } else if (vertexLog === "" || fragmentLog === "") { + haveDiagnostics = false; + } + if (haveDiagnostics) { + self2.diagnostics = { + runnable, + programLog, + vertexShader: { + log: vertexLog, + prefix: prefixVertex + }, + fragmentShader: { + log: fragmentLog, + prefix: prefixFragment + } + }; + } + } + gl.deleteShader(glVertexShader); + gl.deleteShader(glFragmentShader); + cachedUniforms = new WebGLUniforms2(gl, program); + cachedAttributes = fetchAttributeLocations2(gl, program); + } + let cachedUniforms; + this.getUniforms = function() { + if (cachedUniforms === undefined) { + onFirstUse(this); + } + return cachedUniforms; + }; + let cachedAttributes; + this.getAttributes = function() { + if (cachedAttributes === undefined) { + onFirstUse(this); + } + return cachedAttributes; + }; + let programReady = parameters.rendererExtensionParallelShaderCompile === false; + this.isReady = function() { + if (programReady === false) { + programReady = gl.getProgramParameter(program, COMPLETION_STATUS_KHR2); + } + return programReady; + }; + this.destroy = function() { + bindingStates.releaseStatesOfProgram(this); + gl.deleteProgram(program); + this.program = undefined; + }; + this.type = parameters.shaderType; + this.name = parameters.shaderName; + this.id = programIdCount2++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + return this; + } + var _id3 = 0; + + class WebGLShaderCache2 { + constructor() { + this.shaderCache = new Map; + this.materialCache = new Map; + } + update(material) { + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + const vertexShaderStage = this._getShaderStage(vertexShader); + const fragmentShaderStage = this._getShaderStage(fragmentShader); + const materialShaders = this._getShaderCacheForMaterial(material); + if (materialShaders.has(vertexShaderStage) === false) { + materialShaders.add(vertexShaderStage); + vertexShaderStage.usedTimes++; + } + if (materialShaders.has(fragmentShaderStage) === false) { + materialShaders.add(fragmentShaderStage); + fragmentShaderStage.usedTimes++; + } + return this; + } + remove(material) { + const materialShaders = this.materialCache.get(material); + for (const shaderStage of materialShaders) { + shaderStage.usedTimes--; + if (shaderStage.usedTimes === 0) + this.shaderCache.delete(shaderStage.code); + } + this.materialCache.delete(material); + return this; + } + getVertexShaderID(material) { + return this._getShaderStage(material.vertexShader).id; + } + getFragmentShaderID(material) { + return this._getShaderStage(material.fragmentShader).id; + } + dispose() { + this.shaderCache.clear(); + this.materialCache.clear(); + } + _getShaderCacheForMaterial(material) { + const cache = this.materialCache; + let set = cache.get(material); + if (set === undefined) { + set = new Set; + cache.set(material, set); + } + return set; + } + _getShaderStage(code) { + const cache = this.shaderCache; + let stage = cache.get(code); + if (stage === undefined) { + stage = new WebGLShaderStage2(code); + cache.set(code, stage); + } + return stage; + } + } + + class WebGLShaderStage2 { + constructor(code) { + this.id = _id3++; + this.code = code; + this.usedTimes = 0; + } + } + function WebGLPrograms2(renderer2, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) { + const _programLayers = new Layers2; + const _customShaders = new WebGLShaderCache2; + const _activeChannels = new Set; + const programs = []; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures; + let precision = capabilities.precision; + const shaderIDs = { + MeshDepthMaterial: "depth", + MeshDistanceMaterial: "distanceRGBA", + MeshNormalMaterial: "normal", + MeshBasicMaterial: "basic", + MeshLambertMaterial: "lambert", + MeshPhongMaterial: "phong", + MeshToonMaterial: "toon", + MeshStandardMaterial: "physical", + MeshPhysicalMaterial: "physical", + MeshMatcapMaterial: "matcap", + LineBasicMaterial: "basic", + LineDashedMaterial: "dashed", + PointsMaterial: "points", + ShadowMaterial: "shadow", + SpriteMaterial: "sprite" + }; + function getChannel(value2) { + _activeChannels.add(value2); + if (value2 === 0) + return "uv"; + return `uv${value2}`; + } + function getParameters(material, lights, shadows, scene, object) { + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping2 ? envMap.image.height : null; + const shaderID = shaderIDs[material.type]; + if (material.precision !== null) { + precision = capabilities.getMaxPrecision(material.precision); + if (precision !== material.precision) { + console.warn("THREE.WebGLProgram.getParameters:", material.precision, "not supported, using", precision, "instead."); + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + let morphTextureStride = 0; + if (geometry.morphAttributes.position !== undefined) + morphTextureStride = 1; + if (geometry.morphAttributes.normal !== undefined) + morphTextureStride = 2; + if (geometry.morphAttributes.color !== undefined) + morphTextureStride = 3; + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + if (shaderID) { + const shader = ShaderLib2[shaderID]; + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + } else { + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + _customShaders.update(material); + customVertexShaderID = _customShaders.getVertexShaderID(material); + customFragmentShaderID = _customShaders.getFragmentShaderID(material); + } + const currentRenderTarget = renderer2.getRenderTarget(); + const reverseDepthBuffer = renderer2.state.buffers.depth.getReversed(); + const IS_INSTANCEDMESH = object.isInstancedMesh === true; + const IS_BATCHEDMESH = object.isBatchedMesh === true; + const HAS_MAP = !!material.map; + const HAS_MATCAP = !!material.matcap; + const HAS_ENVMAP = !!envMap; + const HAS_AOMAP = !!material.aoMap; + const HAS_LIGHTMAP = !!material.lightMap; + const HAS_BUMPMAP = !!material.bumpMap; + const HAS_NORMALMAP = !!material.normalMap; + const HAS_DISPLACEMENTMAP = !!material.displacementMap; + const HAS_EMISSIVEMAP = !!material.emissiveMap; + const HAS_METALNESSMAP = !!material.metalnessMap; + const HAS_ROUGHNESSMAP = !!material.roughnessMap; + const HAS_ANISOTROPY = material.anisotropy > 0; + const HAS_CLEARCOAT = material.clearcoat > 0; + const HAS_DISPERSION = material.dispersion > 0; + const HAS_IRIDESCENCE = material.iridescence > 0; + const HAS_SHEEN = material.sheen > 0; + const HAS_TRANSMISSION = material.transmission > 0; + const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !!material.anisotropyMap; + const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !!material.clearcoatMap; + const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !!material.clearcoatNormalMap; + const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !!material.clearcoatRoughnessMap; + const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !!material.iridescenceMap; + const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !!material.iridescenceThicknessMap; + const HAS_SHEEN_COLORMAP = HAS_SHEEN && !!material.sheenColorMap; + const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !!material.sheenRoughnessMap; + const HAS_SPECULARMAP = !!material.specularMap; + const HAS_SPECULAR_COLORMAP = !!material.specularColorMap; + const HAS_SPECULAR_INTENSITYMAP = !!material.specularIntensityMap; + const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !!material.transmissionMap; + const HAS_THICKNESSMAP = HAS_TRANSMISSION && !!material.thicknessMap; + const HAS_GRADIENTMAP = !!material.gradientMap; + const HAS_ALPHAMAP = !!material.alphaMap; + const HAS_ALPHATEST = material.alphaTest > 0; + const HAS_ALPHAHASH = !!material.alphaHash; + const HAS_EXTENSIONS = !!material.extensions; + let toneMapping = NoToneMapping2; + if (material.toneMapped) { + if (currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true) { + toneMapping = renderer2.toneMapping; + } + } + const parameters = { + shaderID, + shaderType: material.type, + shaderName: material.name, + vertexShader, + fragmentShader, + defines: material.defines, + customVertexShaderID, + customFragmentShaderID, + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + precision, + batching: IS_BATCHEDMESH, + batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null, + instancing: IS_INSTANCEDMESH, + instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, + supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, + outputColorSpace: currentRenderTarget === null ? renderer2.outputColorSpace : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace2, + alphaToCoverage: !!material.alphaToCoverage, + map: HAS_MAP, + matcap: HAS_MATCAP, + envMap: HAS_ENVMAP, + envMapMode: HAS_ENVMAP && envMap.mapping, + envMapCubeUVHeight, + aoMap: HAS_AOMAP, + lightMap: HAS_LIGHTMAP, + bumpMap: HAS_BUMPMAP, + normalMap: HAS_NORMALMAP, + displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP, + emissiveMap: HAS_EMISSIVEMAP, + normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap2, + normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap2, + metalnessMap: HAS_METALNESSMAP, + roughnessMap: HAS_ROUGHNESSMAP, + anisotropy: HAS_ANISOTROPY, + anisotropyMap: HAS_ANISOTROPYMAP, + clearcoat: HAS_CLEARCOAT, + clearcoatMap: HAS_CLEARCOATMAP, + clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP, + clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP, + dispersion: HAS_DISPERSION, + iridescence: HAS_IRIDESCENCE, + iridescenceMap: HAS_IRIDESCENCEMAP, + iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP, + sheen: HAS_SHEEN, + sheenColorMap: HAS_SHEEN_COLORMAP, + sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP, + specularMap: HAS_SPECULARMAP, + specularColorMap: HAS_SPECULAR_COLORMAP, + specularIntensityMap: HAS_SPECULAR_INTENSITYMAP, + transmission: HAS_TRANSMISSION, + transmissionMap: HAS_TRANSMISSIONMAP, + thicknessMap: HAS_THICKNESSMAP, + gradientMap: HAS_GRADIENTMAP, + opaque: material.transparent === false && material.blending === NormalBlending2 && material.alphaToCoverage === false, + alphaMap: HAS_ALPHAMAP, + alphaTest: HAS_ALPHATEST, + alphaHash: HAS_ALPHAHASH, + combine: material.combine, + mapUv: HAS_MAP && getChannel(material.map.channel), + aoMapUv: HAS_AOMAP && getChannel(material.aoMap.channel), + lightMapUv: HAS_LIGHTMAP && getChannel(material.lightMap.channel), + bumpMapUv: HAS_BUMPMAP && getChannel(material.bumpMap.channel), + normalMapUv: HAS_NORMALMAP && getChannel(material.normalMap.channel), + displacementMapUv: HAS_DISPLACEMENTMAP && getChannel(material.displacementMap.channel), + emissiveMapUv: HAS_EMISSIVEMAP && getChannel(material.emissiveMap.channel), + metalnessMapUv: HAS_METALNESSMAP && getChannel(material.metalnessMap.channel), + roughnessMapUv: HAS_ROUGHNESSMAP && getChannel(material.roughnessMap.channel), + anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel(material.anisotropyMap.channel), + clearcoatMapUv: HAS_CLEARCOATMAP && getChannel(material.clearcoatMap.channel), + clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel(material.clearcoatNormalMap.channel), + clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel(material.clearcoatRoughnessMap.channel), + iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel(material.iridescenceMap.channel), + iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel(material.iridescenceThicknessMap.channel), + sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel(material.sheenColorMap.channel), + sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel(material.sheenRoughnessMap.channel), + specularMapUv: HAS_SPECULARMAP && getChannel(material.specularMap.channel), + specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel(material.specularColorMap.channel), + specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel(material.specularIntensityMap.channel), + transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel(material.transmissionMap.channel), + thicknessMapUv: HAS_THICKNESSMAP && getChannel(material.thicknessMap.channel), + alphaMapUv: HAS_ALPHAMAP && getChannel(material.alphaMap.channel), + vertexTangents: !!geometry.attributes.tangent && (HAS_NORMALMAP || HAS_ANISOTROPY), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4, + pointsUvs: object.isPoints === true && !!geometry.attributes.uv && (HAS_MAP || HAS_ALPHAMAP), + fog: !!fog, + useFog: material.fog === true, + fogExp2: !!fog && fog.isFogExp2, + flatShading: material.flatShading === true, + sizeAttenuation: material.sizeAttenuation === true, + logarithmicDepthBuffer, + reverseDepthBuffer, + skinning: object.isSkinnedMesh === true, + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount, + morphTextureStride, + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + numLightProbes: lights.numLightProbes, + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + dithering: material.dithering, + shadowMapEnabled: renderer2.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer2.shadowMap.type, + toneMapping, + decodeVideoTexture: HAS_MAP && material.map.isVideoTexture === true && ColorManagement2.getTransfer(material.map.colorSpace) === SRGBTransfer2, + decodeVideoTextureEmissive: HAS_EMISSIVEMAP && material.emissiveMap.isVideoTexture === true && ColorManagement2.getTransfer(material.emissiveMap.colorSpace) === SRGBTransfer2, + premultipliedAlpha: material.premultipliedAlpha, + doubleSided: material.side === DoubleSide2, + flipSided: material.side === BackSide2, + useDepthPacking: material.depthPacking >= 0, + depthPacking: material.depthPacking || 0, + index0AttributeName: material.index0AttributeName, + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has("WEBGL_clip_cull_distance"), + extensionMultiDraw: (HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH) && extensions.has("WEBGL_multi_draw"), + rendererExtensionParallelShaderCompile: extensions.has("KHR_parallel_shader_compile"), + customProgramCacheKey: material.customProgramCacheKey() + }; + parameters.vertexUv1s = _activeChannels.has(1); + parameters.vertexUv2s = _activeChannels.has(2); + parameters.vertexUv3s = _activeChannels.has(3); + _activeChannels.clear(); + return parameters; + } + function getProgramCacheKey(parameters) { + const array = []; + if (parameters.shaderID) { + array.push(parameters.shaderID); + } else { + array.push(parameters.customVertexShaderID); + array.push(parameters.customFragmentShaderID); + } + if (parameters.defines !== undefined) { + for (const name2 in parameters.defines) { + array.push(name2); + array.push(parameters.defines[name2]); + } + } + if (parameters.isRawShaderMaterial === false) { + getProgramCacheKeyParameters(array, parameters); + getProgramCacheKeyBooleans(array, parameters); + array.push(renderer2.outputColorSpace); + } + array.push(parameters.customProgramCacheKey); + return array.join(); + } + function getProgramCacheKeyParameters(array, parameters) { + array.push(parameters.precision); + array.push(parameters.outputColorSpace); + array.push(parameters.envMapMode); + array.push(parameters.envMapCubeUVHeight); + array.push(parameters.mapUv); + array.push(parameters.alphaMapUv); + array.push(parameters.lightMapUv); + array.push(parameters.aoMapUv); + array.push(parameters.bumpMapUv); + array.push(parameters.normalMapUv); + array.push(parameters.displacementMapUv); + array.push(parameters.emissiveMapUv); + array.push(parameters.metalnessMapUv); + array.push(parameters.roughnessMapUv); + array.push(parameters.anisotropyMapUv); + array.push(parameters.clearcoatMapUv); + array.push(parameters.clearcoatNormalMapUv); + array.push(parameters.clearcoatRoughnessMapUv); + array.push(parameters.iridescenceMapUv); + array.push(parameters.iridescenceThicknessMapUv); + array.push(parameters.sheenColorMapUv); + array.push(parameters.sheenRoughnessMapUv); + array.push(parameters.specularMapUv); + array.push(parameters.specularColorMapUv); + array.push(parameters.specularIntensityMapUv); + array.push(parameters.transmissionMapUv); + array.push(parameters.thicknessMapUv); + array.push(parameters.combine); + array.push(parameters.fogExp2); + array.push(parameters.sizeAttenuation); + array.push(parameters.morphTargetsCount); + array.push(parameters.morphAttributeCount); + array.push(parameters.numDirLights); + array.push(parameters.numPointLights); + array.push(parameters.numSpotLights); + array.push(parameters.numSpotLightMaps); + array.push(parameters.numHemiLights); + array.push(parameters.numRectAreaLights); + array.push(parameters.numDirLightShadows); + array.push(parameters.numPointLightShadows); + array.push(parameters.numSpotLightShadows); + array.push(parameters.numSpotLightShadowsWithMaps); + array.push(parameters.numLightProbes); + array.push(parameters.shadowMapType); + array.push(parameters.toneMapping); + array.push(parameters.numClippingPlanes); + array.push(parameters.numClipIntersection); + array.push(parameters.depthPacking); + } + function getProgramCacheKeyBooleans(array, parameters) { + _programLayers.disableAll(); + if (parameters.supportsVertexTextures) + _programLayers.enable(0); + if (parameters.instancing) + _programLayers.enable(1); + if (parameters.instancingColor) + _programLayers.enable(2); + if (parameters.instancingMorph) + _programLayers.enable(3); + if (parameters.matcap) + _programLayers.enable(4); + if (parameters.envMap) + _programLayers.enable(5); + if (parameters.normalMapObjectSpace) + _programLayers.enable(6); + if (parameters.normalMapTangentSpace) + _programLayers.enable(7); + if (parameters.clearcoat) + _programLayers.enable(8); + if (parameters.iridescence) + _programLayers.enable(9); + if (parameters.alphaTest) + _programLayers.enable(10); + if (parameters.vertexColors) + _programLayers.enable(11); + if (parameters.vertexAlphas) + _programLayers.enable(12); + if (parameters.vertexUv1s) + _programLayers.enable(13); + if (parameters.vertexUv2s) + _programLayers.enable(14); + if (parameters.vertexUv3s) + _programLayers.enable(15); + if (parameters.vertexTangents) + _programLayers.enable(16); + if (parameters.anisotropy) + _programLayers.enable(17); + if (parameters.alphaHash) + _programLayers.enable(18); + if (parameters.batching) + _programLayers.enable(19); + if (parameters.dispersion) + _programLayers.enable(20); + if (parameters.batchingColor) + _programLayers.enable(21); + array.push(_programLayers.mask); + _programLayers.disableAll(); + if (parameters.fog) + _programLayers.enable(0); + if (parameters.useFog) + _programLayers.enable(1); + if (parameters.flatShading) + _programLayers.enable(2); + if (parameters.logarithmicDepthBuffer) + _programLayers.enable(3); + if (parameters.reverseDepthBuffer) + _programLayers.enable(4); + if (parameters.skinning) + _programLayers.enable(5); + if (parameters.morphTargets) + _programLayers.enable(6); + if (parameters.morphNormals) + _programLayers.enable(7); + if (parameters.morphColors) + _programLayers.enable(8); + if (parameters.premultipliedAlpha) + _programLayers.enable(9); + if (parameters.shadowMapEnabled) + _programLayers.enable(10); + if (parameters.doubleSided) + _programLayers.enable(11); + if (parameters.flipSided) + _programLayers.enable(12); + if (parameters.useDepthPacking) + _programLayers.enable(13); + if (parameters.dithering) + _programLayers.enable(14); + if (parameters.transmission) + _programLayers.enable(15); + if (parameters.sheen) + _programLayers.enable(16); + if (parameters.opaque) + _programLayers.enable(17); + if (parameters.pointsUvs) + _programLayers.enable(18); + if (parameters.decodeVideoTexture) + _programLayers.enable(19); + if (parameters.decodeVideoTextureEmissive) + _programLayers.enable(20); + if (parameters.alphaToCoverage) + _programLayers.enable(21); + array.push(_programLayers.mask); + } + function getUniforms(material) { + const shaderID = shaderIDs[material.type]; + let uniforms; + if (shaderID) { + const shader = ShaderLib2[shaderID]; + uniforms = UniformsUtils2.clone(shader.uniforms); + } else { + uniforms = material.uniforms; + } + return uniforms; + } + function acquireProgram(parameters, cacheKey) { + let program; + for (let p = 0, pl2 = programs.length;p < pl2; p++) { + const preexistingProgram = programs[p]; + if (preexistingProgram.cacheKey === cacheKey) { + program = preexistingProgram; + ++program.usedTimes; + break; + } + } + if (program === undefined) { + program = new WebGLProgram2(renderer2, cacheKey, parameters, bindingStates); + programs.push(program); + } + return program; + } + function releaseProgram(program) { + if (--program.usedTimes === 0) { + const i = programs.indexOf(program); + programs[i] = programs[programs.length - 1]; + programs.pop(); + program.destroy(); + } + } + function releaseShaderCache(material) { + _customShaders.remove(material); + } + function dispose() { + _customShaders.dispose(); + } + return { + getParameters, + getProgramCacheKey, + getUniforms, + acquireProgram, + releaseProgram, + releaseShaderCache, + programs, + dispose + }; + } + function WebGLProperties2() { + let properties = new WeakMap; + function has2(object) { + return properties.has(object); + } + function get(object) { + let map2 = properties.get(object); + if (map2 === undefined) { + map2 = {}; + properties.set(object, map2); + } + return map2; + } + function remove(object) { + properties.delete(object); + } + function update(object, key2, value2) { + properties.get(object)[key2] = value2; + } + function dispose() { + properties = new WeakMap; + } + return { + has: has2, + get, + remove, + update, + dispose + }; + } + function painterSortStable2(a2, b2) { + if (a2.groupOrder !== b2.groupOrder) { + return a2.groupOrder - b2.groupOrder; + } else if (a2.renderOrder !== b2.renderOrder) { + return a2.renderOrder - b2.renderOrder; + } else if (a2.material.id !== b2.material.id) { + return a2.material.id - b2.material.id; + } else if (a2.z !== b2.z) { + return a2.z - b2.z; + } else { + return a2.id - b2.id; + } + } + function reversePainterSortStable2(a2, b2) { + if (a2.groupOrder !== b2.groupOrder) { + return a2.groupOrder - b2.groupOrder; + } else if (a2.renderOrder !== b2.renderOrder) { + return a2.renderOrder - b2.renderOrder; + } else if (a2.z !== b2.z) { + return b2.z - a2.z; + } else { + return a2.id - b2.id; + } + } + function WebGLRenderList2() { + const renderItems = []; + let renderItemsIndex = 0; + const opaque = []; + const transmissive = []; + const transparent = []; + function init() { + renderItemsIndex = 0; + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + } + function getNextRenderItem(object, geometry, material, groupOrder, z, group) { + let renderItem = renderItems[renderItemsIndex]; + if (renderItem === undefined) { + renderItem = { + id: object.id, + object, + geometry, + material, + groupOrder, + renderOrder: object.renderOrder, + z, + group + }; + renderItems[renderItemsIndex] = renderItem; + } else { + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + } + renderItemsIndex++; + return renderItem; + } + function push(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.push(renderItem); + } else if (material.transparent === true) { + transparent.push(renderItem); + } else { + opaque.push(renderItem); + } + } + function unshift(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.unshift(renderItem); + } else if (material.transparent === true) { + transparent.unshift(renderItem); + } else { + opaque.unshift(renderItem); + } + } + function sort(customOpaqueSort, customTransparentSort) { + if (opaque.length > 1) + opaque.sort(customOpaqueSort || painterSortStable2); + if (transmissive.length > 1) + transmissive.sort(customTransparentSort || reversePainterSortStable2); + if (transparent.length > 1) + transparent.sort(customTransparentSort || reversePainterSortStable2); + } + function finish() { + for (let i = renderItemsIndex, il = renderItems.length;i < il; i++) { + const renderItem = renderItems[i]; + if (renderItem.id === null) + break; + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + } + } + return { + opaque, + transmissive, + transparent, + init, + push, + unshift, + finish, + sort + }; + } + function WebGLRenderLists2() { + let lists = new WeakMap; + function get(scene, renderCallDepth) { + const listArray = lists.get(scene); + let list; + if (listArray === undefined) { + list = new WebGLRenderList2; + lists.set(scene, [list]); + } else { + if (renderCallDepth >= listArray.length) { + list = new WebGLRenderList2; + listArray.push(list); + } else { + list = listArray[renderCallDepth]; + } + } + return list; + } + function dispose() { + lists = new WeakMap; + } + return { + get, + dispose + }; + } + function UniformsCache2() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== undefined) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + direction: new Vector32, + color: new Color2 + }; + break; + case "SpotLight": + uniforms = { + position: new Vector32, + direction: new Vector32, + color: new Color2, + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + case "PointLight": + uniforms = { + position: new Vector32, + color: new Color2, + distance: 0, + decay: 0 + }; + break; + case "HemisphereLight": + uniforms = { + direction: new Vector32, + skyColor: new Color2, + groundColor: new Color2 + }; + break; + case "RectAreaLight": + uniforms = { + color: new Color2, + position: new Vector32, + halfWidth: new Vector32, + halfHeight: new Vector32 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; + } + function ShadowUniformsCache2() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== undefined) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector22 + }; + break; + case "SpotLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector22 + }; + break; + case "PointLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector22, + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; + } + var nextVersion2 = 0; + function shadowCastingAndTexturingLightsFirst2(lightA, lightB) { + return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0); + } + function WebGLLights2(extensions) { + const cache = new UniformsCache2; + const shadowCache = ShadowUniformsCache2(); + const state = { + version: 0, + hash: { + directionalLength: -1, + pointLength: -1, + spotLength: -1, + rectAreaLength: -1, + hemiLength: -1, + numDirectionalShadows: -1, + numPointShadows: -1, + numSpotShadows: -1, + numSpotMaps: -1, + numLightProbes: -1 + }, + ambient: [0, 0, 0], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0, + numLightProbes: 0 + }; + for (let i = 0;i < 9; i++) + state.probe.push(new Vector32); + const vector3 = new Vector32; + const matrix4 = new Matrix42; + const matrix42 = new Matrix42; + function setup(lights) { + let r = 0, g3 = 0, b2 = 0; + for (let i = 0;i < 9; i++) + state.probe[i].set(0, 0, 0); + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + let numLightProbes = 0; + lights.sort(shadowCastingAndTexturingLightsFirst2); + for (let i = 0, l2 = lights.length;i < l2; i++) { + const light = lights[i]; + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null; + if (light.isAmbientLight) { + r += color.r * intensity; + g3 += color.g * intensity; + b2 += color.b * intensity; + } else if (light.isLightProbe) { + for (let j2 = 0;j2 < 9; j2++) { + state.probe[j2].addScaledVector(light.sh.coefficients[j2], intensity); + } + numLightProbes++; + } else if (light.isDirectionalLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.directionalShadow[directionalLength] = shadowUniforms; + state.directionalShadowMap[directionalLength] = shadowMap; + state.directionalShadowMatrix[directionalLength] = light.shadow.matrix; + numDirectionalShadows++; + } + state.directional[directionalLength] = uniforms; + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = cache.get(light); + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.distance = distance; + uniforms.coneCos = Math.cos(light.angle); + uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra)); + uniforms.decay = light.decay; + state.spot[spotLength] = uniforms; + const shadow = light.shadow; + if (light.map) { + state.spotLightMap[numSpotMaps] = light.map; + numSpotMaps++; + shadow.updateMatrices(light); + if (light.castShadow) + numSpotShadowsWithMaps++; + } + state.spotLightMatrix[spotLength] = shadow.matrix; + if (light.castShadow) { + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.spotShadow[spotLength] = shadowUniforms; + state.spotShadowMap[spotLength] = shadowMap; + numSpotShadows++; + } + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = cache.get(light); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + state.rectArea[rectAreaLength] = uniforms; + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + state.pointShadow[pointLength] = shadowUniforms; + state.pointShadowMap[pointLength] = shadowMap; + state.pointShadowMatrix[pointLength] = light.shadow.matrix; + numPointShadows++; + } + state.point[pointLength] = uniforms; + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = cache.get(light); + uniforms.skyColor.copy(light.color).multiplyScalar(intensity); + uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity); + state.hemi[hemiLength] = uniforms; + hemiLength++; + } + } + if (rectAreaLength > 0) { + if (extensions.has("OES_texture_float_linear") === true) { + state.rectAreaLTC1 = UniformsLib2.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib2.LTC_FLOAT_2; + } else { + state.rectAreaLTC1 = UniformsLib2.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib2.LTC_HALF_2; + } + } + state.ambient[0] = r; + state.ambient[1] = g3; + state.ambient[2] = b2; + const hash = state.hash; + if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps || hash.numLightProbes !== numLightProbes) { + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + state.numLightProbes = numLightProbes; + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + hash.numLightProbes = numLightProbes; + state.version = nextVersion2++; + } + } + function setupView(lights, camera) { + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + const viewMatrix = camera.matrixWorldInverse; + for (let i = 0, l2 = lights.length;i < l2; i++) { + const light = lights[i]; + if (light.isDirectionalLight) { + const uniforms = state.directional[directionalLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = state.spot[spotLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = state.rectArea[rectAreaLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + matrix42.identity(); + matrix4.copy(light.matrixWorld); + matrix4.premultiply(viewMatrix); + matrix42.extractRotation(matrix4); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + uniforms.halfWidth.applyMatrix4(matrix42); + uniforms.halfHeight.applyMatrix4(matrix42); + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = state.point[pointLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = state.hemi[hemiLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + uniforms.direction.transformDirection(viewMatrix); + hemiLength++; + } + } + } + return { + setup, + setupView, + state + }; + } + function WebGLRenderState2(extensions) { + const lights = new WebGLLights2(extensions); + const lightsArray = []; + const shadowsArray = []; + function init(camera) { + state.camera = camera; + lightsArray.length = 0; + shadowsArray.length = 0; + } + function pushLight(light) { + lightsArray.push(light); + } + function pushShadow(shadowLight) { + shadowsArray.push(shadowLight); + } + function setupLights() { + lights.setup(lightsArray); + } + function setupLightsView(camera) { + lights.setupView(lightsArray, camera); + } + const state = { + lightsArray, + shadowsArray, + camera: null, + lights, + transmissionRenderTarget: {} + }; + return { + init, + state, + setupLights, + setupLightsView, + pushLight, + pushShadow + }; + } + function WebGLRenderStates2(extensions) { + let renderStates = new WeakMap; + function get(scene, renderCallDepth = 0) { + const renderStateArray = renderStates.get(scene); + let renderState; + if (renderStateArray === undefined) { + renderState = new WebGLRenderState2(extensions); + renderStates.set(scene, [renderState]); + } else { + if (renderCallDepth >= renderStateArray.length) { + renderState = new WebGLRenderState2(extensions); + renderStateArray.push(renderState); + } else { + renderState = renderStateArray[renderCallDepth]; + } + } + return renderState; + } + function dispose() { + renderStates = new WeakMap; + } + return { + get, + dispose + }; + } + var vertex2 = `void main() { + gl_Position = vec4( position, 1.0 ); +}`; + var fragment2 = `uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`; + function WebGLShadowMap2(renderer2, objects, capabilities) { + let _frustum4 = new Frustum2; + const _shadowMapSize = new Vector22, _viewportSize = new Vector22, _viewport3 = new Vector42, _depthMaterial = new MeshDepthMaterial2({ depthPacking: RGBADepthPacking2 }), _distanceMaterial = new MeshDistanceMaterial2, _materialCache = {}, _maxTextureSize = capabilities.maxTextureSize; + const shadowSide = { [FrontSide2]: BackSide2, [BackSide2]: FrontSide2, [DoubleSide2]: DoubleSide2 }; + const shadowMaterialVertical = new ShaderMaterial2({ + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector22 }, + radius: { value: 4 } + }, + vertexShader: vertex2, + fragmentShader: fragment2 + }); + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + const fullScreenTri = new BufferGeometry2; + fullScreenTri.setAttribute("position", new BufferAttribute2(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3)); + const fullScreenMesh = new Mesh2(fullScreenTri, shadowMaterialVertical); + const scope = this; + this.enabled = false; + this.autoUpdate = true; + this.needsUpdate = false; + this.type = PCFShadowMap2; + let _previousType = this.type; + this.render = function(lights, scene, camera) { + if (scope.enabled === false) + return; + if (scope.autoUpdate === false && scope.needsUpdate === false) + return; + if (lights.length === 0) + return; + const currentRenderTarget = renderer2.getRenderTarget(); + const activeCubeFace = renderer2.getActiveCubeFace(); + const activeMipmapLevel = renderer2.getActiveMipmapLevel(); + const _state = renderer2.state; + _state.setBlending(NoBlending2); + _state.buffers.color.setClear(1, 1, 1, 1); + _state.buffers.depth.setTest(true); + _state.setScissorTest(false); + const toVSM = _previousType !== VSMShadowMap2 && this.type === VSMShadowMap2; + const fromVSM = _previousType === VSMShadowMap2 && this.type !== VSMShadowMap2; + for (let i = 0, il = lights.length;i < il; i++) { + const light = lights[i]; + const shadow = light.shadow; + if (shadow === undefined) { + console.warn("THREE.WebGLShadowMap:", light, "has no shadow."); + continue; + } + if (shadow.autoUpdate === false && shadow.needsUpdate === false) + continue; + _shadowMapSize.copy(shadow.mapSize); + const shadowFrameExtents = shadow.getFrameExtents(); + _shadowMapSize.multiply(shadowFrameExtents); + _viewportSize.copy(shadow.mapSize); + if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) { + if (_shadowMapSize.x > _maxTextureSize) { + _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + } + if (_shadowMapSize.y > _maxTextureSize) { + _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + } + } + if (shadow.map === null || toVSM === true || fromVSM === true) { + const pars = this.type !== VSMShadowMap2 ? { minFilter: NearestFilter2, magFilter: NearestFilter2 } : {}; + if (shadow.map !== null) { + shadow.map.dispose(); + } + shadow.map = new WebGLRenderTarget2(_shadowMapSize.x, _shadowMapSize.y, pars); + shadow.map.texture.name = light.name + ".shadowMap"; + shadow.camera.updateProjectionMatrix(); + } + renderer2.setRenderTarget(shadow.map); + renderer2.clear(); + const viewportCount = shadow.getViewportCount(); + for (let vp = 0;vp < viewportCount; vp++) { + const viewport = shadow.getViewport(vp); + _viewport3.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w); + _state.viewport(_viewport3); + shadow.updateMatrices(light, vp); + _frustum4 = shadow.getFrustum(); + renderObject(scene, camera, shadow.camera, light, this.type); + } + if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap2) { + VSMPass(shadow, camera); + } + shadow.needsUpdate = false; + } + _previousType = this.type; + scope.needsUpdate = false; + renderer2.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel); + }; + function VSMPass(shadow, camera) { + const geometry = objects.update(fullScreenMesh); + if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) { + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + } + if (shadow.mapPass === null) { + shadow.mapPass = new WebGLRenderTarget2(_shadowMapSize.x, _shadowMapSize.y); + } + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + renderer2.setRenderTarget(shadow.mapPass); + renderer2.clear(); + renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + renderer2.setRenderTarget(shadow.map); + renderer2.clear(); + renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null); + } + function getDepthMaterial(object, material, light, type) { + let result = null; + const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial; + if (customMaterial !== undefined) { + result = customMaterial; + } else { + result = light.isPointLight === true ? _distanceMaterial : _depthMaterial; + if (renderer2.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0 || material.map && material.alphaTest > 0) { + const keyA = result.uuid, keyB = material.uuid; + let materialsForVariant = _materialCache[keyA]; + if (materialsForVariant === undefined) { + materialsForVariant = {}; + _materialCache[keyA] = materialsForVariant; + } + let cachedMaterial = materialsForVariant[keyB]; + if (cachedMaterial === undefined) { + cachedMaterial = result.clone(); + materialsForVariant[keyB] = cachedMaterial; + material.addEventListener("dispose", onMaterialDispose); + } + result = cachedMaterial; + } + } + result.visible = material.visible; + result.wireframe = material.wireframe; + if (type === VSMShadowMap2) { + result.side = material.shadowSide !== null ? material.shadowSide : material.side; + } else { + result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side]; + } + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.map = material.map; + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + if (light.isPointLight === true && result.isMeshDistanceMaterial === true) { + const materialProperties = renderer2.properties.get(result); + materialProperties.light = light; + } + return result; + } + function renderObject(object, camera, shadowCamera, light, type) { + if (object.visible === false) + return; + const visible = object.layers.test(camera.layers); + if (visible && (object.isMesh || object.isLine || object.isPoints)) { + if ((object.castShadow || object.receiveShadow && type === VSMShadowMap2) && (!object.frustumCulled || _frustum4.intersectsObject(object))) { + object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld); + const geometry = objects.update(object); + const material = object.material; + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let k3 = 0, kl = groups.length;k3 < kl; k3++) { + const group = groups[k3]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + const depthMaterial = getDepthMaterial(object, groupMaterial, light, type); + object.onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group); + object.onAfterShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + } + } + } else if (material.visible) { + const depthMaterial = getDepthMaterial(object, material, light, type); + object.onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null); + object.onAfterShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + } + } + } + const children = object.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + renderObject(children[i], camera, shadowCamera, light, type); + } + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + for (const id in _materialCache) { + const cache = _materialCache[id]; + const uuid = event.target.uuid; + if (uuid in cache) { + const shadowMaterial = cache[uuid]; + shadowMaterial.dispose(); + delete cache[uuid]; + } + } + } + } + var reversedFuncs2 = { + [NeverDepth2]: AlwaysDepth2, + [LessDepth2]: GreaterDepth2, + [EqualDepth2]: NotEqualDepth2, + [LessEqualDepth2]: GreaterEqualDepth2, + [AlwaysDepth2]: NeverDepth2, + [GreaterDepth2]: LessDepth2, + [NotEqualDepth2]: EqualDepth2, + [GreaterEqualDepth2]: LessEqualDepth2 + }; + function WebGLState2(gl, extensions) { + function ColorBuffer() { + let locked = false; + const color = new Vector42; + let currentColorMask = null; + const currentColorClear = new Vector42(0, 0, 0, 0); + return { + setMask: function(colorMask) { + if (currentColorMask !== colorMask && !locked) { + gl.colorMask(colorMask, colorMask, colorMask, colorMask); + currentColorMask = colorMask; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(r, g3, b2, a2, premultipliedAlpha) { + if (premultipliedAlpha === true) { + r *= a2; + g3 *= a2; + b2 *= a2; + } + color.set(r, g3, b2, a2); + if (currentColorClear.equals(color) === false) { + gl.clearColor(r, g3, b2, a2); + currentColorClear.copy(color); + } + }, + reset: function() { + locked = false; + currentColorMask = null; + currentColorClear.set(-1, 0, 0, 0); + } + }; + } + function DepthBuffer() { + let locked = false; + let reversed = false; + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + return { + setReversed: function(value2) { + if (reversed !== value2) { + const ext = extensions.get("EXT_clip_control"); + if (reversed) { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT); + } else { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT); + } + const oldDepth = currentDepthClear; + currentDepthClear = null; + this.setClear(oldDepth); + } + reversed = value2; + }, + getReversed: function() { + return reversed; + }, + setTest: function(depthTest) { + if (depthTest) { + enable(gl.DEPTH_TEST); + } else { + disable(gl.DEPTH_TEST); + } + }, + setMask: function(depthMask) { + if (currentDepthMask !== depthMask && !locked) { + gl.depthMask(depthMask); + currentDepthMask = depthMask; + } + }, + setFunc: function(depthFunc) { + if (reversed) + depthFunc = reversedFuncs2[depthFunc]; + if (currentDepthFunc !== depthFunc) { + switch (depthFunc) { + case NeverDepth2: + gl.depthFunc(gl.NEVER); + break; + case AlwaysDepth2: + gl.depthFunc(gl.ALWAYS); + break; + case LessDepth2: + gl.depthFunc(gl.LESS); + break; + case LessEqualDepth2: + gl.depthFunc(gl.LEQUAL); + break; + case EqualDepth2: + gl.depthFunc(gl.EQUAL); + break; + case GreaterEqualDepth2: + gl.depthFunc(gl.GEQUAL); + break; + case GreaterDepth2: + gl.depthFunc(gl.GREATER); + break; + case NotEqualDepth2: + gl.depthFunc(gl.NOTEQUAL); + break; + default: + gl.depthFunc(gl.LEQUAL); + } + currentDepthFunc = depthFunc; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(depth) { + if (currentDepthClear !== depth) { + if (reversed) { + depth = 1 - depth; + } + gl.clearDepth(depth); + currentDepthClear = depth; + } + }, + reset: function() { + locked = false; + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + reversed = false; + } + }; + } + function StencilBuffer() { + let locked = false; + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + return { + setTest: function(stencilTest) { + if (!locked) { + if (stencilTest) { + enable(gl.STENCIL_TEST); + } else { + disable(gl.STENCIL_TEST); + } + } + }, + setMask: function(stencilMask) { + if (currentStencilMask !== stencilMask && !locked) { + gl.stencilMask(stencilMask); + currentStencilMask = stencilMask; + } + }, + setFunc: function(stencilFunc, stencilRef, stencilMask) { + if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) { + gl.stencilFunc(stencilFunc, stencilRef, stencilMask); + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + } + }, + setOp: function(stencilFail, stencilZFail, stencilZPass) { + if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) { + gl.stencilOp(stencilFail, stencilZFail, stencilZPass); + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(stencil) { + if (currentStencilClear !== stencil) { + gl.clearStencil(stencil); + currentStencilClear = stencil; + } + }, + reset: function() { + locked = false; + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + } + }; + } + const colorBuffer = new ColorBuffer; + const depthBuffer = new DepthBuffer; + const stencilBuffer = new StencilBuffer; + const uboBindings = new WeakMap; + const uboProgramMap = new WeakMap; + let enabledCapabilities = {}; + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap; + let defaultDrawbuffers = []; + let currentProgram = null; + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentBlendColor = new Color2(0, 0, 0); + let currentBlendAlpha = 0; + let currentPremultipledAlpha = false; + let currentFlipSided = null; + let currentCullFace = null; + let currentLineWidth = null; + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter(gl.VERSION); + if (glVersion.indexOf("WebGL") !== -1) { + version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 1; + } else if (glVersion.indexOf("OpenGL ES") !== -1) { + version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 2; + } + let currentTextureSlot = null; + let currentBoundTextures = {}; + const scissorParam = gl.getParameter(gl.SCISSOR_BOX); + const viewportParam = gl.getParameter(gl.VIEWPORT); + const currentScissor = new Vector42().fromArray(scissorParam); + const currentViewport = new Vector42().fromArray(viewportParam); + function createTexture(type, target, count, dimensions) { + const data2 = new Uint8Array(4); + const texture = gl.createTexture(); + gl.bindTexture(type, texture); + gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + for (let i = 0;i < count; i++) { + if (type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY) { + gl.texImage3D(target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data2); + } else { + gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data2); + } + } + return texture; + } + const emptyTextures = {}; + emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1); + emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); + emptyTextures[gl.TEXTURE_2D_ARRAY] = createTexture(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1); + emptyTextures[gl.TEXTURE_3D] = createTexture(gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1); + colorBuffer.setClear(0, 0, 0, 1); + depthBuffer.setClear(1); + stencilBuffer.setClear(0); + enable(gl.DEPTH_TEST); + depthBuffer.setFunc(LessEqualDepth2); + setFlipSided(false); + setCullFace(CullFaceBack2); + enable(gl.CULL_FACE); + setBlending(NoBlending2); + function enable(id) { + if (enabledCapabilities[id] !== true) { + gl.enable(id); + enabledCapabilities[id] = true; + } + } + function disable(id) { + if (enabledCapabilities[id] !== false) { + gl.disable(id); + enabledCapabilities[id] = false; + } + } + function bindFramebuffer(target, framebuffer) { + if (currentBoundFramebuffers[target] !== framebuffer) { + gl.bindFramebuffer(target, framebuffer); + currentBoundFramebuffers[target] = framebuffer; + if (target === gl.DRAW_FRAMEBUFFER) { + currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer; + } + if (target === gl.FRAMEBUFFER) { + currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer; + } + return true; + } + return false; + } + function drawBuffers(renderTarget, framebuffer) { + let drawBuffers2 = defaultDrawbuffers; + let needsUpdate = false; + if (renderTarget) { + drawBuffers2 = currentDrawbuffers.get(framebuffer); + if (drawBuffers2 === undefined) { + drawBuffers2 = []; + currentDrawbuffers.set(framebuffer, drawBuffers2); + } + const textures = renderTarget.textures; + if (drawBuffers2.length !== textures.length || drawBuffers2[0] !== gl.COLOR_ATTACHMENT0) { + for (let i = 0, il = textures.length;i < il; i++) { + drawBuffers2[i] = gl.COLOR_ATTACHMENT0 + i; + } + drawBuffers2.length = textures.length; + needsUpdate = true; + } + } else { + if (drawBuffers2[0] !== gl.BACK) { + drawBuffers2[0] = gl.BACK; + needsUpdate = true; + } + } + if (needsUpdate) { + gl.drawBuffers(drawBuffers2); + } + } + function useProgram(program) { + if (currentProgram !== program) { + gl.useProgram(program); + currentProgram = program; + return true; + } + return false; + } + const equationToGL = { + [AddEquation2]: gl.FUNC_ADD, + [SubtractEquation2]: gl.FUNC_SUBTRACT, + [ReverseSubtractEquation2]: gl.FUNC_REVERSE_SUBTRACT + }; + equationToGL[MinEquation2] = gl.MIN; + equationToGL[MaxEquation2] = gl.MAX; + const factorToGL = { + [ZeroFactor2]: gl.ZERO, + [OneFactor2]: gl.ONE, + [SrcColorFactor2]: gl.SRC_COLOR, + [SrcAlphaFactor2]: gl.SRC_ALPHA, + [SrcAlphaSaturateFactor2]: gl.SRC_ALPHA_SATURATE, + [DstColorFactor2]: gl.DST_COLOR, + [DstAlphaFactor2]: gl.DST_ALPHA, + [OneMinusSrcColorFactor2]: gl.ONE_MINUS_SRC_COLOR, + [OneMinusSrcAlphaFactor2]: gl.ONE_MINUS_SRC_ALPHA, + [OneMinusDstColorFactor2]: gl.ONE_MINUS_DST_COLOR, + [OneMinusDstAlphaFactor2]: gl.ONE_MINUS_DST_ALPHA, + [ConstantColorFactor2]: gl.CONSTANT_COLOR, + [OneMinusConstantColorFactor2]: gl.ONE_MINUS_CONSTANT_COLOR, + [ConstantAlphaFactor2]: gl.CONSTANT_ALPHA, + [OneMinusConstantAlphaFactor2]: gl.ONE_MINUS_CONSTANT_ALPHA + }; + function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha) { + if (blending === NoBlending2) { + if (currentBlendingEnabled === true) { + disable(gl.BLEND); + currentBlendingEnabled = false; + } + return; + } + if (currentBlendingEnabled === false) { + enable(gl.BLEND); + currentBlendingEnabled = true; + } + if (blending !== CustomBlending2) { + if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) { + if (currentBlendEquation !== AddEquation2 || currentBlendEquationAlpha !== AddEquation2) { + gl.blendEquation(gl.FUNC_ADD); + currentBlendEquation = AddEquation2; + currentBlendEquationAlpha = AddEquation2; + } + if (premultipliedAlpha) { + switch (blending) { + case NormalBlending2: + gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending2: + gl.blendFunc(gl.ONE, gl.ONE); + break; + case SubtractiveBlending2: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending2: + gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } else { + switch (blending) { + case NormalBlending2: + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending2: + gl.blendFunc(gl.SRC_ALPHA, gl.ONE); + break; + case SubtractiveBlending2: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending2: + gl.blendFunc(gl.ZERO, gl.SRC_COLOR); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor.set(0, 0, 0); + currentBlendAlpha = 0; + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + } + return; + } + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) { + gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]); + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + } + if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) { + gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]); + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + } + if (blendColor.equals(currentBlendColor) === false || blendAlpha !== currentBlendAlpha) { + gl.blendColor(blendColor.r, blendColor.g, blendColor.b, blendAlpha); + currentBlendColor.copy(blendColor); + currentBlendAlpha = blendAlpha; + } + currentBlending = blending; + currentPremultipledAlpha = false; + } + function setMaterial(material, frontFaceCW) { + material.side === DoubleSide2 ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE); + let flipSided = material.side === BackSide2; + if (frontFaceCW) + flipSided = !flipSided; + setFlipSided(flipSided); + material.blending === NormalBlending2 && material.transparent === false ? setBlending(NoBlending2) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha); + depthBuffer.setFunc(material.depthFunc); + depthBuffer.setTest(material.depthTest); + depthBuffer.setMask(material.depthWrite); + colorBuffer.setMask(material.colorWrite); + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest(stencilWrite); + if (stencilWrite) { + stencilBuffer.setMask(material.stencilWriteMask); + stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask); + stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass); + } + setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits); + material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + } + function setFlipSided(flipSided) { + if (currentFlipSided !== flipSided) { + if (flipSided) { + gl.frontFace(gl.CW); + } else { + gl.frontFace(gl.CCW); + } + currentFlipSided = flipSided; + } + } + function setCullFace(cullFace) { + if (cullFace !== CullFaceNone2) { + enable(gl.CULL_FACE); + if (cullFace !== currentCullFace) { + if (cullFace === CullFaceBack2) { + gl.cullFace(gl.BACK); + } else if (cullFace === CullFaceFront2) { + gl.cullFace(gl.FRONT); + } else { + gl.cullFace(gl.FRONT_AND_BACK); + } + } + } else { + disable(gl.CULL_FACE); + } + currentCullFace = cullFace; + } + function setLineWidth(width2) { + if (width2 !== currentLineWidth) { + if (lineWidthAvailable) + gl.lineWidth(width2); + currentLineWidth = width2; + } + } + function setPolygonOffset(polygonOffset, factor, units) { + if (polygonOffset) { + enable(gl.POLYGON_OFFSET_FILL); + if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) { + gl.polygonOffset(factor, units); + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + } + } else { + disable(gl.POLYGON_OFFSET_FILL); + } + } + function setScissorTest(scissorTest) { + if (scissorTest) { + enable(gl.SCISSOR_TEST); + } else { + disable(gl.SCISSOR_TEST); + } + } + function activeTexture(webglSlot) { + if (webglSlot === undefined) + webglSlot = gl.TEXTURE0 + maxTextures - 1; + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + } + function bindTexture(webglType, webglTexture, webglSlot) { + if (webglSlot === undefined) { + if (currentTextureSlot === null) { + webglSlot = gl.TEXTURE0 + maxTextures - 1; + } else { + webglSlot = currentTextureSlot; + } + } + let boundTexture = currentBoundTextures[webglSlot]; + if (boundTexture === undefined) { + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[webglSlot] = boundTexture; + } + if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) { + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]); + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + } + } + function unbindTexture() { + const boundTexture = currentBoundTextures[currentTextureSlot]; + if (boundTexture !== undefined && boundTexture.type !== undefined) { + gl.bindTexture(boundTexture.type, null); + boundTexture.type = undefined; + boundTexture.texture = undefined; + } + } + function compressedTexImage2D() { + try { + gl.compressedTexImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexImage3D() { + try { + gl.compressedTexImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage2D() { + try { + gl.texSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage3D() { + try { + gl.texSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage2D() { + try { + gl.compressedTexSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage3D() { + try { + gl.compressedTexSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage2D() { + try { + gl.texStorage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage3D() { + try { + gl.texStorage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage2D() { + try { + gl.texImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage3D() { + try { + gl.texImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function scissor(scissor2) { + if (currentScissor.equals(scissor2) === false) { + gl.scissor(scissor2.x, scissor2.y, scissor2.z, scissor2.w); + currentScissor.copy(scissor2); + } + } + function viewport(viewport2) { + if (currentViewport.equals(viewport2) === false) { + gl.viewport(viewport2.x, viewport2.y, viewport2.z, viewport2.w); + currentViewport.copy(viewport2); + } + } + function updateUBOMapping(uniformsGroup, program) { + let mapping = uboProgramMap.get(program); + if (mapping === undefined) { + mapping = new WeakMap; + uboProgramMap.set(program, mapping); + } + let blockIndex = mapping.get(uniformsGroup); + if (blockIndex === undefined) { + blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name); + mapping.set(uniformsGroup, blockIndex); + } + } + function uniformBlockBinding(uniformsGroup, program) { + const mapping = uboProgramMap.get(program); + const blockIndex = mapping.get(uniformsGroup); + if (uboBindings.get(program) !== blockIndex) { + gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex); + uboBindings.set(program, blockIndex); + } + } + function reset() { + gl.disable(gl.BLEND); + gl.disable(gl.CULL_FACE); + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.POLYGON_OFFSET_FILL); + gl.disable(gl.SCISSOR_TEST); + gl.disable(gl.STENCIL_TEST); + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ZERO); + gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO); + gl.blendColor(0, 0, 0, 0); + gl.colorMask(true, true, true, true); + gl.clearColor(0, 0, 0, 0); + gl.depthMask(true); + gl.depthFunc(gl.LESS); + depthBuffer.setReversed(false); + gl.clearDepth(1); + gl.stencilMask(4294967295); + gl.stencilFunc(gl.ALWAYS, 0, 4294967295); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + gl.clearStencil(0); + gl.cullFace(gl.BACK); + gl.frontFace(gl.CCW); + gl.polygonOffset(0, 0); + gl.activeTexture(gl.TEXTURE0); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); + gl.useProgram(null); + gl.lineWidth(1); + gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); + gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); + enabledCapabilities = {}; + currentTextureSlot = null; + currentBoundTextures = {}; + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap; + defaultDrawbuffers = []; + currentProgram = null; + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor = new Color2(0, 0, 0); + currentBlendAlpha = 0; + currentPremultipledAlpha = false; + currentFlipSided = null; + currentCullFace = null; + currentLineWidth = null; + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height); + currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height); + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + } + return { + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + enable, + disable, + bindFramebuffer, + drawBuffers, + useProgram, + setBlending, + setMaterial, + setFlipSided, + setCullFace, + setLineWidth, + setPolygonOffset, + setScissorTest, + activeTexture, + bindTexture, + unbindTexture, + compressedTexImage2D, + compressedTexImage3D, + texImage2D, + texImage3D, + updateUBOMapping, + uniformBlockBinding, + texStorage2D, + texStorage3D, + texSubImage2D, + texSubImage3D, + compressedTexSubImage2D, + compressedTexSubImage3D, + scissor, + viewport, + reset + }; + } + function WebGLTextures2(_gl, extensions, state, properties, capabilities, utils, info) { + const multisampledRTTExt = extensions.has("WEBGL_multisampled_render_to_texture") ? extensions.get("WEBGL_multisampled_render_to_texture") : null; + const supportsInvalidateFramebuffer = typeof navigator === "undefined" ? false : /OculusBrowser/g.test(navigator.userAgent); + const _imageDimensions = new Vector22; + const _videoTextures = new WeakMap; + let _canvas3; + const _sources = new WeakMap; + let useOffscreenCanvas = false; + try { + useOffscreenCanvas = typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null; + } catch (err) { + } + function createCanvas(width2, height2) { + return useOffscreenCanvas ? new OffscreenCanvas(width2, height2) : createElementNS2("canvas"); + } + function resizeImage(image, needsNewCanvas, maxSize) { + let scale2 = 1; + const dimensions = getDimensions(image); + if (dimensions.width > maxSize || dimensions.height > maxSize) { + scale2 = maxSize / Math.max(dimensions.width, dimensions.height); + } + if (scale2 < 1) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + const width2 = Math.floor(scale2 * dimensions.width); + const height2 = Math.floor(scale2 * dimensions.height); + if (_canvas3 === undefined) + _canvas3 = createCanvas(width2, height2); + const canvas = needsNewCanvas ? createCanvas(width2, height2) : _canvas3; + canvas.width = width2; + canvas.height = height2; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, width2, height2); + console.warn("THREE.WebGLRenderer: Texture has been resized from (" + dimensions.width + "x" + dimensions.height + ") to (" + width2 + "x" + height2 + ")."); + return canvas; + } else { + if ("data" in image) { + console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + dimensions.width + "x" + dimensions.height + ")."); + } + return image; + } + } + return image; + } + function textureNeedsGenerateMipmaps(texture) { + return texture.generateMipmaps; + } + function generateMipmap(target) { + _gl.generateMipmap(target); + } + function getTargetType(texture) { + if (texture.isWebGLCubeRenderTarget) + return _gl.TEXTURE_CUBE_MAP; + if (texture.isWebGL3DRenderTarget) + return _gl.TEXTURE_3D; + if (texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture) + return _gl.TEXTURE_2D_ARRAY; + return _gl.TEXTURE_2D; + } + function getInternalFormat(internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false) { + if (internalFormatName !== null) { + if (_gl[internalFormatName] !== undefined) + return _gl[internalFormatName]; + console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + internalFormatName + "'"); + } + let internalFormat = glFormat; + if (glFormat === _gl.RED) { + if (glType === _gl.FLOAT) + internalFormat = _gl.R32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.R16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.R8; + } + if (glFormat === _gl.RED_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.R8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.R16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.R32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.R8I; + if (glType === _gl.SHORT) + internalFormat = _gl.R16I; + if (glType === _gl.INT) + internalFormat = _gl.R32I; + } + if (glFormat === _gl.RG) { + if (glType === _gl.FLOAT) + internalFormat = _gl.RG32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.RG16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RG8; + } + if (glFormat === _gl.RG_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RG8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RG16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RG32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RG8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RG16I; + if (glType === _gl.INT) + internalFormat = _gl.RG32I; + } + if (glFormat === _gl.RGB_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RGB8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RGB16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RGB32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RGB8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RGB16I; + if (glType === _gl.INT) + internalFormat = _gl.RGB32I; + } + if (glFormat === _gl.RGBA_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RGBA8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RGBA16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RGBA32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RGBA8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RGBA16I; + if (glType === _gl.INT) + internalFormat = _gl.RGBA32I; + } + if (glFormat === _gl.RGB) { + if (glType === _gl.UNSIGNED_INT_5_9_9_9_REV) + internalFormat = _gl.RGB9_E5; + } + if (glFormat === _gl.RGBA) { + const transfer = forceLinearTransfer ? LinearTransfer2 : ColorManagement2.getTransfer(colorSpace); + if (glType === _gl.FLOAT) + internalFormat = _gl.RGBA32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.RGBA16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = transfer === SRGBTransfer2 ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) + internalFormat = _gl.RGBA4; + if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) + internalFormat = _gl.RGB5_A1; + } + if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) { + extensions.get("EXT_color_buffer_float"); + } + return internalFormat; + } + function getInternalDepthFormat(useStencil, depthType) { + let glInternalFormat; + if (useStencil) { + if (depthType === null || depthType === UnsignedIntType2 || depthType === UnsignedInt248Type2) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + } else if (depthType === FloatType2) { + glInternalFormat = _gl.DEPTH32F_STENCIL8; + } else if (depthType === UnsignedShortType2) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment."); + } + } else { + if (depthType === null || depthType === UnsignedIntType2 || depthType === UnsignedInt248Type2) { + glInternalFormat = _gl.DEPTH_COMPONENT24; + } else if (depthType === FloatType2) { + glInternalFormat = _gl.DEPTH_COMPONENT32F; + } else if (depthType === UnsignedShortType2) { + glInternalFormat = _gl.DEPTH_COMPONENT16; + } + } + return glInternalFormat; + } + function getMipLevels(texture, image) { + if (textureNeedsGenerateMipmaps(texture) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter2 && texture.minFilter !== LinearFilter2) { + return Math.log2(Math.max(image.width, image.height)) + 1; + } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) { + return texture.mipmaps.length; + } else if (texture.isCompressedTexture && Array.isArray(texture.image)) { + return image.mipmaps.length; + } else { + return 1; + } + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + deallocateTexture(texture); + if (texture.isVideoTexture) { + _videoTextures.delete(texture); + } + } + function onRenderTargetDispose(event) { + const renderTarget = event.target; + renderTarget.removeEventListener("dispose", onRenderTargetDispose); + deallocateRenderTarget(renderTarget); + } + function deallocateTexture(texture) { + const textureProperties = properties.get(texture); + if (textureProperties.__webglInit === undefined) + return; + const source = texture.source; + const webglTextures = _sources.get(source); + if (webglTextures) { + const webglTexture = webglTextures[textureProperties.__cacheKey]; + webglTexture.usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + if (Object.keys(webglTextures).length === 0) { + _sources.delete(source); + } + } + properties.remove(texture); + } + function deleteTexture(texture) { + const textureProperties = properties.get(texture); + _gl.deleteTexture(textureProperties.__webglTexture); + const source = texture.source; + const webglTextures = _sources.get(source); + delete webglTextures[textureProperties.__cacheKey]; + info.memory.textures--; + } + function deallocateRenderTarget(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTarget.depthTexture) { + renderTarget.depthTexture.dispose(); + properties.remove(renderTarget.depthTexture); + } + if (renderTarget.isWebGLCubeRenderTarget) { + for (let i = 0;i < 6; i++) { + if (Array.isArray(renderTargetProperties.__webglFramebuffer[i])) { + for (let level = 0;level < renderTargetProperties.__webglFramebuffer[i].length; level++) + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i][level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]); + } + if (renderTargetProperties.__webglDepthbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]); + } + } else { + if (Array.isArray(renderTargetProperties.__webglFramebuffer)) { + for (let level = 0;level < renderTargetProperties.__webglFramebuffer.length; level++) + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer); + } + if (renderTargetProperties.__webglDepthbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer); + if (renderTargetProperties.__webglMultisampledFramebuffer) + _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer); + if (renderTargetProperties.__webglColorRenderbuffer) { + for (let i = 0;i < renderTargetProperties.__webglColorRenderbuffer.length; i++) { + if (renderTargetProperties.__webglColorRenderbuffer[i]) + _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]); + } + } + if (renderTargetProperties.__webglDepthRenderbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer); + } + const textures = renderTarget.textures; + for (let i = 0, il = textures.length;i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture) { + _gl.deleteTexture(attachmentProperties.__webglTexture); + info.memory.textures--; + } + properties.remove(textures[i]); + } + properties.remove(renderTarget); + } + let textureUnits = 0; + function resetTextureUnits() { + textureUnits = 0; + } + function allocateTextureUnit() { + const textureUnit = textureUnits; + if (textureUnit >= capabilities.maxTextures) { + console.warn("THREE.WebGLTextures: Trying to use " + textureUnit + " texture units while this GPU supports only " + capabilities.maxTextures); + } + textureUnits += 1; + return textureUnit; + } + function getTextureCacheKey(texture) { + const array = []; + array.push(texture.wrapS); + array.push(texture.wrapT); + array.push(texture.wrapR || 0); + array.push(texture.magFilter); + array.push(texture.minFilter); + array.push(texture.anisotropy); + array.push(texture.internalFormat); + array.push(texture.format); + array.push(texture.type); + array.push(texture.generateMipmaps); + array.push(texture.premultiplyAlpha); + array.push(texture.flipY); + array.push(texture.unpackAlignment); + array.push(texture.colorSpace); + return array.join(); + } + function setTexture2D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isVideoTexture) + updateVideoTexture(texture); + if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { + const image = texture.image; + if (image === null) { + console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found."); + } else if (image.complete === false) { + console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete"); + } else { + uploadTexture(textureProperties, texture, slot); + return; + } + } + state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture2DArray(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture3D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTextureCube(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadCubeTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + const wrappingToGL = { + [RepeatWrapping2]: _gl.REPEAT, + [ClampToEdgeWrapping2]: _gl.CLAMP_TO_EDGE, + [MirroredRepeatWrapping2]: _gl.MIRRORED_REPEAT + }; + const filterToGL = { + [NearestFilter2]: _gl.NEAREST, + [NearestMipmapNearestFilter2]: _gl.NEAREST_MIPMAP_NEAREST, + [NearestMipmapLinearFilter2]: _gl.NEAREST_MIPMAP_LINEAR, + [LinearFilter2]: _gl.LINEAR, + [LinearMipmapNearestFilter2]: _gl.LINEAR_MIPMAP_NEAREST, + [LinearMipmapLinearFilter2]: _gl.LINEAR_MIPMAP_LINEAR + }; + const compareToGL = { + [NeverCompare2]: _gl.NEVER, + [AlwaysCompare2]: _gl.ALWAYS, + [LessCompare2]: _gl.LESS, + [LessEqualCompare2]: _gl.LEQUAL, + [EqualCompare2]: _gl.EQUAL, + [GreaterEqualCompare2]: _gl.GEQUAL, + [GreaterCompare2]: _gl.GREATER, + [NotEqualCompare2]: _gl.NOTEQUAL + }; + function setTextureParameters(textureType, texture) { + if (texture.type === FloatType2 && extensions.has("OES_texture_float_linear") === false && (texture.magFilter === LinearFilter2 || texture.magFilter === LinearMipmapNearestFilter2 || texture.magFilter === NearestMipmapLinearFilter2 || texture.magFilter === LinearMipmapLinearFilter2 || texture.minFilter === LinearFilter2 || texture.minFilter === LinearMipmapNearestFilter2 || texture.minFilter === NearestMipmapLinearFilter2 || texture.minFilter === LinearMipmapLinearFilter2)) { + console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."); + } + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]); + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]); + if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) { + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]); + } + _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]); + _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]); + if (texture.compareFunction) { + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE); + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[texture.compareFunction]); + } + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + if (texture.magFilter === NearestFilter2) + return; + if (texture.minFilter !== NearestMipmapLinearFilter2 && texture.minFilter !== LinearMipmapLinearFilter2) + return; + if (texture.type === FloatType2 && extensions.has("OES_texture_float_linear") === false) + return; + if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy())); + properties.get(texture).__currentAnisotropy = texture.anisotropy; + } + } + } + function initTexture(textureProperties, texture) { + let forceUpload = false; + if (textureProperties.__webglInit === undefined) { + textureProperties.__webglInit = true; + texture.addEventListener("dispose", onTextureDispose); + } + const source = texture.source; + let webglTextures = _sources.get(source); + if (webglTextures === undefined) { + webglTextures = {}; + _sources.set(source, webglTextures); + } + const textureCacheKey = getTextureCacheKey(texture); + if (textureCacheKey !== textureProperties.__cacheKey) { + if (webglTextures[textureCacheKey] === undefined) { + webglTextures[textureCacheKey] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + info.memory.textures++; + forceUpload = true; + } + webglTextures[textureCacheKey].usedTimes++; + const webglTexture = webglTextures[textureProperties.__cacheKey]; + if (webglTexture !== undefined) { + webglTextures[textureProperties.__cacheKey].usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + } + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[textureCacheKey].texture; + } + return forceUpload; + } + function uploadTexture(textureProperties, texture, slot) { + let textureType = _gl.TEXTURE_2D; + if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) + textureType = _gl.TEXTURE_2D_ARRAY; + if (texture.isData3DTexture) + textureType = _gl.TEXTURE_3D; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement2.getPrimaries(ColorManagement2.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace2 ? null : ColorManagement2.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace2 || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + let image = resizeImage(texture.image, false, capabilities.maxTextureSize); + image = verifyColorSpace(texture, image); + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + let glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture); + setTextureParameters(textureType, texture); + let mipmap; + const mipmaps = texture.mipmaps; + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; + const dataReady = source.dataReady; + const levels = getMipLevels(texture, image); + if (texture.isDepthTexture) { + glInternalFormat = getInternalDepthFormat(texture.format === DepthStencilFormat2, texture.type); + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height); + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null); + } + } + } else if (texture.isDataTexture) { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data); + } + } + } else if (texture.isCompressedTexture) { + if (texture.isCompressedArrayTexture) { + if (useTexStorage && allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat2) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength2(mipmap.width, mipmap.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = mipmap.data.subarray(layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT, (layerIndex + 1) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT); + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData); + } + texture.clearLayerUpdates(); + } else { + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data); + } + } + } else { + state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data); + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data); + } + } + } + } else { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat2) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else if (texture.isDataArrayTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength2(image.width, image.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = image.data.subarray(layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT, (layerIndex + 1) * layerByteLength / image.data.BYTES_PER_ELEMENT); + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData); + } + texture.clearLayerUpdates(); + } else { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isData3DTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } else { + state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isFramebufferTexture) { + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } else { + let { width: width2, height: height2 } = image; + for (let i = 0;i < levels; i++) { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width2, height2, 0, glFormat, glType, null); + width2 >>= 1; + height2 >>= 1; + } + } + } + } else { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + const dimensions = getDimensions(mipmaps[0]); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + const dimensions = getDimensions(image); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image); + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(textureType); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) + texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function uploadCubeTexture(textureProperties, texture, slot) { + if (texture.image.length !== 6) + return; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement2.getPrimaries(ColorManagement2.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace2 ? null : ColorManagement2.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace2 || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture; + const isDataTexture = texture.image[0] && texture.image[0].isDataTexture; + const cubeImage = []; + for (let i = 0;i < 6; i++) { + if (!isCompressed && !isDataTexture) { + cubeImage[i] = resizeImage(texture.image[i], true, capabilities.maxCubemapSize); + } else { + cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i]; + } + cubeImage[i] = verifyColorSpace(texture, cubeImage[i]); + } + const image = cubeImage[0], glFormat = utils.convert(texture.format, texture.colorSpace), glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; + const dataReady = source.dataReady; + let levels = getMipLevels(texture, image); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + let mipmaps; + if (isCompressed) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height); + } + for (let i = 0;i < 6; i++) { + mipmaps = cubeImage[i].mipmaps; + for (let j2 = 0;j2 < mipmaps.length; j2++) { + const mipmap = mipmaps[j2]; + if (texture.format !== RGBAFormat2) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else { + mipmaps = texture.mipmaps; + if (useTexStorage && allocateMemory) { + if (mipmaps.length > 0) + levels++; + const dimensions = getDimensions(cubeImage[0]); + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0;i < 6; i++) { + if (isDataTexture) { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data); + } + for (let j2 = 0;j2 < mipmaps.length; j2++) { + const mipmap = mipmaps[j2]; + const mipmapImage = mipmap.image[i].image; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2 + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2 + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data); + } + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]); + } + for (let j2 = 0;j2 < mipmaps.length; j2++) { + const mipmap = mipmaps[j2]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2 + 1, 0, 0, glFormat, glType, mipmap.image[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j2 + 1, glInternalFormat, glFormat, glType, mipmap.image[i]); + } + } + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) + texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget, level) { + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + textureProperties.__renderTarget = renderTarget; + if (!renderTargetProperties.__hasExternalTextures) { + const width2 = Math.max(1, renderTarget.width >> level); + const height2 = Math.max(1, renderTarget.height >> level); + if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) { + state.texImage3D(textureTarget, level, glInternalFormat, width2, height2, renderTarget.depth, 0, glFormat, glType, null); + } else { + state.texImage2D(textureTarget, level, glInternalFormat, width2, height2, 0, glFormat, glType, null); + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples(renderTarget)); + } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) { + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null; + const glInternalFormat = getInternalDepthFormat(renderTarget.stencilBuffer, depthType); + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const samples = getRenderTargetSamples(renderTarget); + const isUseMultisampledRTT = useMultisampledRTT(renderTarget); + if (isUseMultisampledRTT) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (isMultisample) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } else { + const textures = renderTarget.textures; + for (let i = 0;i < textures.length; i++) { + const texture = textures[i]; + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const samples = getRenderTargetSamples(renderTarget); + if (isMultisample && useMultisampledRTT(renderTarget) === false) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + } + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + } + function setupDepthTexture(framebuffer, renderTarget) { + const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget; + if (isCube) + throw new Error("Depth Texture with cube render targets is not supported"); + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) { + throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); + } + const textureProperties = properties.get(renderTarget.depthTexture); + textureProperties.__renderTarget = renderTarget; + if (!textureProperties.__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) { + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + } + setTexture2D(renderTarget.depthTexture, 0); + const webglDepthTexture = textureProperties.__webglTexture; + const samples = getRenderTargetSamples(renderTarget); + if (renderTarget.depthTexture.format === DepthFormat2) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else if (renderTarget.depthTexture.format === DepthStencilFormat2) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else { + throw new Error("Unknown depthTexture format"); + } + } + function setupDepthRenderbuffer(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + if (renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__depthDisposeCallback) { + renderTargetProperties.__depthDisposeCallback(); + } + if (depthTexture) { + const disposeEvent = () => { + delete renderTargetProperties.__boundDepthTexture; + delete renderTargetProperties.__depthDisposeCallback; + depthTexture.removeEventListener("dispose", disposeEvent); + }; + depthTexture.addEventListener("dispose", disposeEvent); + renderTargetProperties.__depthDisposeCallback = disposeEvent; + } + renderTargetProperties.__boundDepthTexture = depthTexture; + } + if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) { + if (isCube) + throw new Error("target.depthTexture not supported in Cube render targets"); + setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget); + } else { + if (isCube) { + renderTargetProperties.__webglDepthbuffer = []; + for (let i = 0;i < 6; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]); + if (renderTargetProperties.__webglDepthbuffer[i] === undefined) { + renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer[i]; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } else { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + if (renderTargetProperties.__webglDepthbuffer === undefined) { + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function rebindTextures(renderTarget, colorTexture, depthTexture) { + const renderTargetProperties = properties.get(renderTarget); + if (colorTexture !== undefined) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0); + } + if (depthTexture !== undefined) { + setupDepthRenderbuffer(renderTarget); + } + } + function setupRenderTarget(renderTarget) { + const texture = renderTarget.texture; + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + renderTarget.addEventListener("dispose", onRenderTargetDispose); + const textures = renderTarget.textures; + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + const isMultipleRenderTargets = textures.length > 1; + if (!isMultipleRenderTargets) { + if (textureProperties.__webglTexture === undefined) { + textureProperties.__webglTexture = _gl.createTexture(); + } + textureProperties.__version = texture.version; + info.memory.textures++; + } + if (isCube) { + renderTargetProperties.__webglFramebuffer = []; + for (let i = 0;i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer[i] = []; + for (let level = 0;level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[i][level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer(); + } + } + } else { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer = []; + for (let level = 0;level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + } + if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length;i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture === undefined) { + attachmentProperties.__webglTexture = _gl.createTexture(); + info.memory.textures++; + } + } + } + if (renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + for (let i = 0;i < textures.length; i++) { + const texture2 = textures[i]; + renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer(); + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const glFormat = utils.convert(texture2.format, texture2.colorSpace); + const glType = utils.convert(texture2.type); + const glInternalFormat = getInternalFormat(texture2.internalFormat, glFormat, glType, texture2.colorSpace, renderTarget.isXRRenderTarget === true); + const samples = getRenderTargetSamples(renderTarget); + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + if (renderTarget.depthBuffer) { + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + } + if (isCube) { + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + for (let i = 0;i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0;level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i][level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0); + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + state.unbindTexture(); + } else if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length;i < il; i++) { + const attachment = textures[i]; + const attachmentProperties = properties.get(attachment); + state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_2D, attachment); + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0); + if (textureNeedsGenerateMipmaps(attachment)) { + generateMipmap(_gl.TEXTURE_2D); + } + } + state.unbindTexture(); + } else { + let glTextureType = _gl.TEXTURE_2D; + if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + } + state.bindTexture(glTextureType, textureProperties.__webglTexture); + setTextureParameters(glTextureType, texture); + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0;level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0); + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(glTextureType); + } + state.unbindTexture(); + } + if (renderTarget.depthBuffer) { + setupDepthRenderbuffer(renderTarget); + } + } + function updateRenderTargetMipmap(renderTarget) { + const textures = renderTarget.textures; + for (let i = 0, il = textures.length;i < il; i++) { + const texture = textures[i]; + if (textureNeedsGenerateMipmaps(texture)) { + const targetType = getTargetType(renderTarget); + const webglTexture = properties.get(texture).__webglTexture; + state.bindTexture(targetType, webglTexture); + generateMipmap(targetType); + state.unbindTexture(); + } + } + } + const invalidationArrayRead = []; + const invalidationArrayDraw = []; + function updateMultisampleRenderTarget(renderTarget) { + if (renderTarget.samples > 0) { + if (useMultisampledRTT(renderTarget) === false) { + const textures = renderTarget.textures; + const width2 = renderTarget.width; + const height2 = renderTarget.height; + let mask2 = _gl.COLOR_BUFFER_BIT; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get(renderTarget); + const isMultipleRenderTargets = textures.length > 1; + if (isMultipleRenderTargets) { + for (let i = 0;i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null); + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + for (let i = 0;i < textures.length; i++) { + if (renderTarget.resolveDepthBuffer) { + if (renderTarget.depthBuffer) + mask2 |= _gl.DEPTH_BUFFER_BIT; + if (renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer) + mask2 |= _gl.STENCIL_BUFFER_BIT; + } + if (isMultipleRenderTargets) { + _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0); + } + _gl.blitFramebuffer(0, 0, width2, height2, 0, 0, width2, height2, mask2, _gl.NEAREST); + if (supportsInvalidateFramebuffer === true) { + invalidationArrayRead.length = 0; + invalidationArrayDraw.length = 0; + invalidationArrayRead.push(_gl.COLOR_ATTACHMENT0 + i); + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false) { + invalidationArrayRead.push(depthStyle); + invalidationArrayDraw.push(depthStyle); + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, invalidationArrayDraw); + } + _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArrayRead); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + if (isMultipleRenderTargets) { + for (let i = 0;i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0); + } + } + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + } else { + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer) { + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]); + } + } + } + } + function getRenderTargetSamples(renderTarget) { + return Math.min(capabilities.maxSamples, renderTarget.samples); + } + function useMultisampledRTT(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + return renderTarget.samples > 0 && extensions.has("WEBGL_multisampled_render_to_texture") === true && renderTargetProperties.__useRenderToTexture !== false; + } + function updateVideoTexture(texture) { + const frame = info.render.frame; + if (_videoTextures.get(texture) !== frame) { + _videoTextures.set(texture, frame); + texture.update(); + } + } + function verifyColorSpace(texture, image) { + const colorSpace = texture.colorSpace; + const format = texture.format; + const type = texture.type; + if (texture.isCompressedTexture === true || texture.isVideoTexture === true) + return image; + if (colorSpace !== LinearSRGBColorSpace2 && colorSpace !== NoColorSpace2) { + if (ColorManagement2.getTransfer(colorSpace) === SRGBTransfer2) { + if (format !== RGBAFormat2 || type !== UnsignedByteType2) { + console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."); + } + } else { + console.error("THREE.WebGLTextures: Unsupported texture color space:", colorSpace); + } + } + return image; + } + function getDimensions(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement) { + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + } else if (typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + } else { + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + } + return _imageDimensions; + } + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; + } + function WebGLUtils2(gl, extensions) { + function convert(p, colorSpace = NoColorSpace2) { + let extension; + const transfer = ColorManagement2.getTransfer(colorSpace); + if (p === UnsignedByteType2) + return gl.UNSIGNED_BYTE; + if (p === UnsignedShort4444Type2) + return gl.UNSIGNED_SHORT_4_4_4_4; + if (p === UnsignedShort5551Type2) + return gl.UNSIGNED_SHORT_5_5_5_1; + if (p === UnsignedInt5999Type2) + return gl.UNSIGNED_INT_5_9_9_9_REV; + if (p === ByteType2) + return gl.BYTE; + if (p === ShortType2) + return gl.SHORT; + if (p === UnsignedShortType2) + return gl.UNSIGNED_SHORT; + if (p === IntType2) + return gl.INT; + if (p === UnsignedIntType2) + return gl.UNSIGNED_INT; + if (p === FloatType2) + return gl.FLOAT; + if (p === HalfFloatType2) + return gl.HALF_FLOAT; + if (p === AlphaFormat2) + return gl.ALPHA; + if (p === RGBFormat2) + return gl.RGB; + if (p === RGBAFormat2) + return gl.RGBA; + if (p === LuminanceFormat2) + return gl.LUMINANCE; + if (p === LuminanceAlphaFormat2) + return gl.LUMINANCE_ALPHA; + if (p === DepthFormat2) + return gl.DEPTH_COMPONENT; + if (p === DepthStencilFormat2) + return gl.DEPTH_STENCIL; + if (p === RedFormat2) + return gl.RED; + if (p === RedIntegerFormat2) + return gl.RED_INTEGER; + if (p === RGFormat2) + return gl.RG; + if (p === RGIntegerFormat2) + return gl.RG_INTEGER; + if (p === RGBAIntegerFormat2) + return gl.RGBA_INTEGER; + if (p === RGB_S3TC_DXT1_Format2 || p === RGBA_S3TC_DXT1_Format2 || p === RGBA_S3TC_DXT3_Format2 || p === RGBA_S3TC_DXT5_Format2) { + if (transfer === SRGBTransfer2) { + extension = extensions.get("WEBGL_compressed_texture_s3tc_srgb"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format2) + return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format2) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format2) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format2) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + } else { + return null; + } + } else { + extension = extensions.get("WEBGL_compressed_texture_s3tc"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format2) + return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format2) + return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format2) + return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format2) + return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + } else { + return null; + } + } + } + if (p === RGB_PVRTC_4BPPV1_Format2 || p === RGB_PVRTC_2BPPV1_Format2 || p === RGBA_PVRTC_4BPPV1_Format2 || p === RGBA_PVRTC_2BPPV1_Format2) { + extension = extensions.get("WEBGL_compressed_texture_pvrtc"); + if (extension !== null) { + if (p === RGB_PVRTC_4BPPV1_Format2) + return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if (p === RGB_PVRTC_2BPPV1_Format2) + return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if (p === RGBA_PVRTC_4BPPV1_Format2) + return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if (p === RGBA_PVRTC_2BPPV1_Format2) + return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + } else { + return null; + } + } + if (p === RGB_ETC1_Format2 || p === RGB_ETC2_Format2 || p === RGBA_ETC2_EAC_Format2) { + extension = extensions.get("WEBGL_compressed_texture_etc"); + if (extension !== null) { + if (p === RGB_ETC1_Format2 || p === RGB_ETC2_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if (p === RGBA_ETC2_EAC_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + } else { + return null; + } + } + if (p === RGBA_ASTC_4x4_Format2 || p === RGBA_ASTC_5x4_Format2 || p === RGBA_ASTC_5x5_Format2 || p === RGBA_ASTC_6x5_Format2 || p === RGBA_ASTC_6x6_Format2 || p === RGBA_ASTC_8x5_Format2 || p === RGBA_ASTC_8x6_Format2 || p === RGBA_ASTC_8x8_Format2 || p === RGBA_ASTC_10x5_Format2 || p === RGBA_ASTC_10x6_Format2 || p === RGBA_ASTC_10x8_Format2 || p === RGBA_ASTC_10x10_Format2 || p === RGBA_ASTC_12x10_Format2 || p === RGBA_ASTC_12x12_Format2) { + extension = extensions.get("WEBGL_compressed_texture_astc"); + if (extension !== null) { + if (p === RGBA_ASTC_4x4_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if (p === RGBA_ASTC_5x4_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if (p === RGBA_ASTC_5x5_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if (p === RGBA_ASTC_6x5_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if (p === RGBA_ASTC_6x6_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if (p === RGBA_ASTC_8x5_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if (p === RGBA_ASTC_8x6_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if (p === RGBA_ASTC_8x8_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if (p === RGBA_ASTC_10x5_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if (p === RGBA_ASTC_10x6_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if (p === RGBA_ASTC_10x8_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if (p === RGBA_ASTC_10x10_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if (p === RGBA_ASTC_12x10_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if (p === RGBA_ASTC_12x12_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + } else { + return null; + } + } + if (p === RGBA_BPTC_Format2 || p === RGB_BPTC_SIGNED_Format2 || p === RGB_BPTC_UNSIGNED_Format2) { + extension = extensions.get("EXT_texture_compression_bptc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format2) + return transfer === SRGBTransfer2 ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + if (p === RGB_BPTC_SIGNED_Format2) + return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; + if (p === RGB_BPTC_UNSIGNED_Format2) + return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; + } else { + return null; + } + } + if (p === RED_RGTC1_Format2 || p === SIGNED_RED_RGTC1_Format2 || p === RED_GREEN_RGTC2_Format2 || p === SIGNED_RED_GREEN_RGTC2_Format2) { + extension = extensions.get("EXT_texture_compression_rgtc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format2) + return extension.COMPRESSED_RED_RGTC1_EXT; + if (p === SIGNED_RED_RGTC1_Format2) + return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if (p === RED_GREEN_RGTC2_Format2) + return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if (p === SIGNED_RED_GREEN_RGTC2_Format2) + return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + } else { + return null; + } + } + if (p === UnsignedInt248Type2) + return gl.UNSIGNED_INT_24_8; + return gl[p] !== undefined ? gl[p] : null; + } + return { convert }; + } + var _occlusion_vertex2 = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; + var _occlusion_fragment2 = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; + + class WebXRDepthSensing2 { + constructor() { + this.texture = null; + this.mesh = null; + this.depthNear = 0; + this.depthFar = 0; + } + init(renderer2, depthData, renderState) { + if (this.texture === null) { + const texture = new Texture2; + const texProps = renderer2.properties.get(texture); + texProps.__webglTexture = depthData.texture; + if (depthData.depthNear !== renderState.depthNear || depthData.depthFar !== renderState.depthFar) { + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + } + this.texture = texture; + } + } + getMesh(cameraXR) { + if (this.texture !== null) { + if (this.mesh === null) { + const viewport = cameraXR.cameras[0].viewport; + const material = new ShaderMaterial2({ + vertexShader: _occlusion_vertex2, + fragmentShader: _occlusion_fragment2, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + }); + this.mesh = new Mesh2(new PlaneGeometry3(20, 20), material); + } + } + return this.mesh; + } + reset() { + this.texture = null; + this.mesh = null; + } + getDepthTexture() { + return this.texture; + } + } + + class WebXRManager2 extends EventDispatcher2 { + constructor(renderer2, gl) { + super(); + const scope = this; + let session = null; + let framebufferScaleFactor = 1; + let referenceSpace = null; + let referenceSpaceType = "local-floor"; + let foveation = 1; + let customReferenceSpace = null; + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const depthSensing = new WebXRDepthSensing2; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + const controllers = []; + const controllerInputSources = []; + const currentSize = new Vector22; + let currentPixelRatio = null; + const cameraL = new PerspectiveCamera2; + cameraL.viewport = new Vector42; + const cameraR = new PerspectiveCamera2; + cameraR.viewport = new Vector42; + const cameras = [cameraL, cameraR]; + const cameraXR = new ArrayCamera2; + let _currentDepthNear = null; + let _currentDepthFar = null; + this.cameraAutoUpdate = true; + this.enabled = false; + this.isPresenting = false; + this.getController = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController2; + controllers[index2] = controller; + } + return controller.getTargetRaySpace(); + }; + this.getControllerGrip = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController2; + controllers[index2] = controller; + } + return controller.getGripSpace(); + }; + this.getHand = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController2; + controllers[index2] = controller; + } + return controller.getHandSpace(); + }; + function onSessionEvent(event) { + const controllerIndex = controllerInputSources.indexOf(event.inputSource); + if (controllerIndex === -1) { + return; + } + const controller = controllers[controllerIndex]; + if (controller !== undefined) { + controller.update(event.inputSource, event.frame, customReferenceSpace || referenceSpace); + controller.dispatchEvent({ type: event.type, data: event.inputSource }); + } + } + function onSessionEnd() { + session.removeEventListener("select", onSessionEvent); + session.removeEventListener("selectstart", onSessionEvent); + session.removeEventListener("selectend", onSessionEvent); + session.removeEventListener("squeeze", onSessionEvent); + session.removeEventListener("squeezestart", onSessionEvent); + session.removeEventListener("squeezeend", onSessionEvent); + session.removeEventListener("end", onSessionEnd); + session.removeEventListener("inputsourceschange", onInputSourcesChange); + for (let i = 0;i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + if (inputSource === null) + continue; + controllerInputSources[i] = null; + controllers[i].disconnect(inputSource); + } + _currentDepthNear = null; + _currentDepthFar = null; + depthSensing.reset(); + renderer2.setRenderTarget(initialRenderTarget); + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + animation.stop(); + scope.isPresenting = false; + renderer2.setPixelRatio(currentPixelRatio); + renderer2.setSize(currentSize.width, currentSize.height, false); + scope.dispatchEvent({ type: "sessionend" }); + } + this.setFramebufferScaleFactor = function(value2) { + framebufferScaleFactor = value2; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting."); + } + }; + this.setReferenceSpaceType = function(value2) { + referenceSpaceType = value2; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change reference space type while presenting."); + } + }; + this.getReferenceSpace = function() { + return customReferenceSpace || referenceSpace; + }; + this.setReferenceSpace = function(space) { + customReferenceSpace = space; + }; + this.getBaseLayer = function() { + return glProjLayer !== null ? glProjLayer : glBaseLayer; + }; + this.getBinding = function() { + return glBinding; + }; + this.getFrame = function() { + return xrFrame; + }; + this.getSession = function() { + return session; + }; + this.setSession = async function(value2) { + session = value2; + if (session !== null) { + initialRenderTarget = renderer2.getRenderTarget(); + session.addEventListener("select", onSessionEvent); + session.addEventListener("selectstart", onSessionEvent); + session.addEventListener("selectend", onSessionEvent); + session.addEventListener("squeeze", onSessionEvent); + session.addEventListener("squeezestart", onSessionEvent); + session.addEventListener("squeezeend", onSessionEvent); + session.addEventListener("end", onSessionEnd); + session.addEventListener("inputsourceschange", onInputSourcesChange); + if (attributes.xrCompatible !== true) { + await gl.makeXRCompatible(); + } + currentPixelRatio = renderer2.getPixelRatio(); + renderer2.getSize(currentSize); + const useLayers = typeof XRWebGLBinding !== "undefined" && "createProjectionLayer" in XRWebGLBinding.prototype; + if (!useLayers) { + const layerInit = { + antialias: attributes.antialias, + alpha: true, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor + }; + glBaseLayer = new XRWebGLLayer(session, gl, layerInit); + session.updateRenderState({ baseLayer: glBaseLayer }); + renderer2.setPixelRatio(1); + renderer2.setSize(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false); + newRenderTarget = new WebGLRenderTarget2(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, { + format: RGBAFormat2, + type: UnsignedByteType2, + colorSpace: renderer2.outputColorSpace, + stencilBuffer: attributes.stencil + }); + } else { + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + if (attributes.depth) { + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat2 : DepthFormat2; + depthType = attributes.stencil ? UnsignedInt248Type2 : UnsignedIntType2; + } + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + glBinding = new XRWebGLBinding(session, gl); + glProjLayer = glBinding.createProjectionLayer(projectionlayerInit); + session.updateRenderState({ layers: [glProjLayer] }); + renderer2.setPixelRatio(1); + renderer2.setSize(glProjLayer.textureWidth, glProjLayer.textureHeight, false); + newRenderTarget = new WebGLRenderTarget2(glProjLayer.textureWidth, glProjLayer.textureHeight, { + format: RGBAFormat2, + type: UnsignedByteType2, + depthTexture: new DepthTexture2(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat), + stencilBuffer: attributes.stencil, + colorSpace: renderer2.outputColorSpace, + samples: attributes.antialias ? 4 : 0, + resolveDepthBuffer: glProjLayer.ignoreDepthValues === false + }); + } + newRenderTarget.isXRRenderTarget = true; + this.setFoveation(foveation); + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace(referenceSpaceType); + animation.setContext(session); + animation.start(); + scope.isPresenting = true; + scope.dispatchEvent({ type: "sessionstart" }); + } + }; + this.getEnvironmentBlendMode = function() { + if (session !== null) { + return session.environmentBlendMode; + } + }; + this.getDepthTexture = function() { + return depthSensing.getDepthTexture(); + }; + function onInputSourcesChange(event) { + for (let i = 0;i < event.removed.length; i++) { + const inputSource = event.removed[i]; + const index2 = controllerInputSources.indexOf(inputSource); + if (index2 >= 0) { + controllerInputSources[index2] = null; + controllers[index2].disconnect(inputSource); + } + } + for (let i = 0;i < event.added.length; i++) { + const inputSource = event.added[i]; + let controllerIndex = controllerInputSources.indexOf(inputSource); + if (controllerIndex === -1) { + for (let i2 = 0;i2 < controllers.length; i2++) { + if (i2 >= controllerInputSources.length) { + controllerInputSources.push(inputSource); + controllerIndex = i2; + break; + } else if (controllerInputSources[i2] === null) { + controllerInputSources[i2] = inputSource; + controllerIndex = i2; + break; + } + } + if (controllerIndex === -1) + break; + } + const controller = controllers[controllerIndex]; + if (controller) { + controller.connect(inputSource); + } + } + } + const cameraLPos = new Vector32; + const cameraRPos = new Vector32; + function setProjectionFromUnion(camera, cameraL2, cameraR2) { + cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld); + cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld); + const ipd = cameraLPos.distanceTo(cameraRPos); + const projL = cameraL2.projectionMatrix.elements; + const projR = cameraR2.projectionMatrix.elements; + const near = projL[14] / (projL[10] - 1); + const far = projL[14] / (projL[10] + 1); + const topFov = (projL[9] + 1) / projL[5]; + const bottomFov = (projL[9] - 1) / projL[5]; + const leftFov = (projL[8] - 1) / projL[0]; + const rightFov = (projR[8] + 1) / projR[0]; + const left = near * leftFov; + const right = near * rightFov; + const zOffset = ipd / (-leftFov + rightFov); + const xOffset = zOffset * -leftFov; + cameraL2.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale); + camera.translateX(xOffset); + camera.translateZ(zOffset); + camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale); + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + if (projL[10] === -1) { + camera.projectionMatrix.copy(cameraL2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraL2.projectionMatrixInverse); + } else { + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + (ipd - xOffset); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + } + } + function updateCamera(camera, parent2) { + if (parent2 === null) { + camera.matrixWorld.copy(camera.matrix); + } else { + camera.matrixWorld.multiplyMatrices(parent2.matrixWorld, camera.matrix); + } + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + } + this.updateCamera = function(camera) { + if (session === null) + return; + let depthNear = camera.near; + let depthFar = camera.far; + if (depthSensing.texture !== null) { + if (depthSensing.depthNear > 0) + depthNear = depthSensing.depthNear; + if (depthSensing.depthFar > 0) + depthFar = depthSensing.depthFar; + } + cameraXR.near = cameraR.near = cameraL.near = depthNear; + cameraXR.far = cameraR.far = cameraL.far = depthFar; + if (_currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far) { + session.updateRenderState({ + depthNear: cameraXR.near, + depthFar: cameraXR.far + }); + _currentDepthNear = cameraXR.near; + _currentDepthFar = cameraXR.far; + } + cameraL.layers.mask = camera.layers.mask | 2; + cameraR.layers.mask = camera.layers.mask | 4; + cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask; + const parent2 = camera.parent; + const cameras2 = cameraXR.cameras; + updateCamera(cameraXR, parent2); + for (let i = 0;i < cameras2.length; i++) { + updateCamera(cameras2[i], parent2); + } + if (cameras2.length === 2) { + setProjectionFromUnion(cameraXR, cameraL, cameraR); + } else { + cameraXR.projectionMatrix.copy(cameraL.projectionMatrix); + } + updateUserCamera(camera, cameraXR, parent2); + }; + function updateUserCamera(camera, cameraXR2, parent2) { + if (parent2 === null) { + camera.matrix.copy(cameraXR2.matrixWorld); + } else { + camera.matrix.copy(parent2.matrixWorld); + camera.matrix.invert(); + camera.matrix.multiply(cameraXR2.matrixWorld); + } + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.updateMatrixWorld(true); + camera.projectionMatrix.copy(cameraXR2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraXR2.projectionMatrixInverse); + if (camera.isPerspectiveCamera) { + camera.fov = RAD2DEG2 * 2 * Math.atan(1 / camera.projectionMatrix.elements[5]); + camera.zoom = 1; + } + } + this.getCamera = function() { + return cameraXR; + }; + this.getFoveation = function() { + if (glProjLayer === null && glBaseLayer === null) { + return; + } + return foveation; + }; + this.setFoveation = function(value2) { + foveation = value2; + if (glProjLayer !== null) { + glProjLayer.fixedFoveation = value2; + } + if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) { + glBaseLayer.fixedFoveation = value2; + } + }; + this.hasDepthSensing = function() { + return depthSensing.texture !== null; + }; + this.getDepthSensingMesh = function() { + return depthSensing.getMesh(cameraXR); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time2, frame) { + pose = frame.getViewerPose(customReferenceSpace || referenceSpace); + xrFrame = frame; + if (pose !== null) { + const views = pose.views; + if (glBaseLayer !== null) { + renderer2.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer); + renderer2.setRenderTarget(newRenderTarget); + } + let cameraXRNeedsUpdate = false; + if (views.length !== cameraXR.cameras.length) { + cameraXR.cameras.length = 0; + cameraXRNeedsUpdate = true; + } + for (let i = 0;i < views.length; i++) { + const view = views[i]; + let viewport = null; + if (glBaseLayer !== null) { + viewport = glBaseLayer.getViewport(view); + } else { + const glSubImage = glBinding.getViewSubImage(glProjLayer, view); + viewport = glSubImage.viewport; + if (i === 0) { + renderer2.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture); + renderer2.setRenderTarget(newRenderTarget); + } + } + let camera = cameras[i]; + if (camera === undefined) { + camera = new PerspectiveCamera2; + camera.layers.enable(i); + camera.viewport = new Vector42; + cameras[i] = camera; + } + camera.matrix.fromArray(view.transform.matrix); + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.projectionMatrix.fromArray(view.projectionMatrix); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height); + if (i === 0) { + cameraXR.matrix.copy(camera.matrix); + cameraXR.matrix.decompose(cameraXR.position, cameraXR.quaternion, cameraXR.scale); + } + if (cameraXRNeedsUpdate === true) { + cameraXR.cameras.push(camera); + } + } + const enabledFeatures = session.enabledFeatures; + const gpuDepthSensingEnabled = enabledFeatures && enabledFeatures.includes("depth-sensing") && session.depthUsage == "gpu-optimized"; + if (gpuDepthSensingEnabled && glBinding) { + const depthData = glBinding.getDepthInformation(views[0]); + if (depthData && depthData.isValid && depthData.texture) { + depthSensing.init(renderer2, depthData, session.renderState); + } + } + } + for (let i = 0;i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + const controller = controllers[i]; + if (inputSource !== null && controller !== undefined) { + controller.update(inputSource, frame, customReferenceSpace || referenceSpace); + } + } + if (onAnimationFrameCallback) + onAnimationFrameCallback(time2, frame); + if (frame.detectedPlanes) { + scope.dispatchEvent({ type: "planesdetected", data: frame }); + } + xrFrame = null; + } + const animation = new WebGLAnimation2; + animation.setAnimationLoop(onAnimationFrame); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + }; + this.dispose = function() { + }; + } + } + var _e12 = /* @__PURE__ */ new Euler2; + var _m13 = /* @__PURE__ */ new Matrix42; + function WebGLMaterials2(renderer2, properties) { + function refreshTransformUniform(map2, uniform) { + if (map2.matrixAutoUpdate === true) { + map2.updateMatrix(); + } + uniform.value.copy(map2.matrix); + } + function refreshFogUniforms(uniforms, fog) { + fog.color.getRGB(uniforms.fogColor.value, getUnlitUniformColorSpace2(renderer2)); + if (fog.isFog) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + } else if (fog.isFogExp2) { + uniforms.fogDensity.value = fog.density; + } + } + function refreshMaterialUniforms(uniforms, material, pixelRatio, height2, transmissionRenderTarget) { + if (material.isMeshBasicMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshLambertMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshToonMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsToon(uniforms, material); + } else if (material.isMeshPhongMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsPhong(uniforms, material); + } else if (material.isMeshStandardMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsStandard(uniforms, material); + if (material.isMeshPhysicalMaterial) { + refreshUniformsPhysical(uniforms, material, transmissionRenderTarget); + } + } else if (material.isMeshMatcapMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsMatcap(uniforms, material); + } else if (material.isMeshDepthMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshDistanceMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsDistance(uniforms, material); + } else if (material.isMeshNormalMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isLineBasicMaterial) { + refreshUniformsLine(uniforms, material); + if (material.isLineDashedMaterial) { + refreshUniformsDash(uniforms, material); + } + } else if (material.isPointsMaterial) { + refreshUniformsPoints(uniforms, material, pixelRatio, height2); + } else if (material.isSpriteMaterial) { + refreshUniformsSprites(uniforms, material); + } else if (material.isShadowMaterial) { + uniforms.color.value.copy(material.color); + uniforms.opacity.value = material.opacity; + } else if (material.isShaderMaterial) { + material.uniformsNeedUpdate = false; + } + } + function refreshUniformsCommon(uniforms, material) { + uniforms.opacity.value = material.opacity; + if (material.color) { + uniforms.diffuse.value.copy(material.color); + } + if (material.emissive) { + uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity); + } + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.bumpMap) { + uniforms.bumpMap.value = material.bumpMap; + refreshTransformUniform(material.bumpMap, uniforms.bumpMapTransform); + uniforms.bumpScale.value = material.bumpScale; + if (material.side === BackSide2) { + uniforms.bumpScale.value *= -1; + } + } + if (material.normalMap) { + uniforms.normalMap.value = material.normalMap; + refreshTransformUniform(material.normalMap, uniforms.normalMapTransform); + uniforms.normalScale.value.copy(material.normalScale); + if (material.side === BackSide2) { + uniforms.normalScale.value.negate(); + } + } + if (material.displacementMap) { + uniforms.displacementMap.value = material.displacementMap; + refreshTransformUniform(material.displacementMap, uniforms.displacementMapTransform); + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + } + if (material.emissiveMap) { + uniforms.emissiveMap.value = material.emissiveMap; + refreshTransformUniform(material.emissiveMap, uniforms.emissiveMapTransform); + } + if (material.specularMap) { + uniforms.specularMap.value = material.specularMap; + refreshTransformUniform(material.specularMap, uniforms.specularMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + const materialProperties = properties.get(material); + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; + if (envMap) { + uniforms.envMap.value = envMap; + _e12.copy(envMapRotation); + _e12.x *= -1; + _e12.y *= -1; + _e12.z *= -1; + if (envMap.isCubeTexture && envMap.isRenderTargetTexture === false) { + _e12.y *= -1; + _e12.z *= -1; + } + uniforms.envMapRotation.value.setFromMatrix4(_m13.makeRotationFromEuler(_e12)); + uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + } + if (material.lightMap) { + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; + refreshTransformUniform(material.lightMap, uniforms.lightMapTransform); + } + if (material.aoMap) { + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + refreshTransformUniform(material.aoMap, uniforms.aoMapTransform); + } + } + function refreshUniformsLine(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + } + function refreshUniformsDash(uniforms, material) { + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + } + function refreshUniformsPoints(uniforms, material, pixelRatio, height2) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height2 * 0.5; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.uvTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsSprites(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsPhong(uniforms, material) { + uniforms.specular.value.copy(material.specular); + uniforms.shininess.value = Math.max(material.shininess, 0.0001); + } + function refreshUniformsToon(uniforms, material) { + if (material.gradientMap) { + uniforms.gradientMap.value = material.gradientMap; + } + } + function refreshUniformsStandard(uniforms, material) { + uniforms.metalness.value = material.metalness; + if (material.metalnessMap) { + uniforms.metalnessMap.value = material.metalnessMap; + refreshTransformUniform(material.metalnessMap, uniforms.metalnessMapTransform); + } + uniforms.roughness.value = material.roughness; + if (material.roughnessMap) { + uniforms.roughnessMap.value = material.roughnessMap; + refreshTransformUniform(material.roughnessMap, uniforms.roughnessMapTransform); + } + if (material.envMap) { + uniforms.envMapIntensity.value = material.envMapIntensity; + } + } + function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) { + uniforms.ior.value = material.ior; + if (material.sheen > 0) { + uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen); + uniforms.sheenRoughness.value = material.sheenRoughness; + if (material.sheenColorMap) { + uniforms.sheenColorMap.value = material.sheenColorMap; + refreshTransformUniform(material.sheenColorMap, uniforms.sheenColorMapTransform); + } + if (material.sheenRoughnessMap) { + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + refreshTransformUniform(material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform); + } + } + if (material.clearcoat > 0) { + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + if (material.clearcoatMap) { + uniforms.clearcoatMap.value = material.clearcoatMap; + refreshTransformUniform(material.clearcoatMap, uniforms.clearcoatMapTransform); + } + if (material.clearcoatRoughnessMap) { + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + refreshTransformUniform(material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform); + } + if (material.clearcoatNormalMap) { + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + refreshTransformUniform(material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform); + uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale); + if (material.side === BackSide2) { + uniforms.clearcoatNormalScale.value.negate(); + } + } + } + if (material.dispersion > 0) { + uniforms.dispersion.value = material.dispersion; + } + if (material.iridescence > 0) { + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1]; + if (material.iridescenceMap) { + uniforms.iridescenceMap.value = material.iridescenceMap; + refreshTransformUniform(material.iridescenceMap, uniforms.iridescenceMapTransform); + } + if (material.iridescenceThicknessMap) { + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + refreshTransformUniform(material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform); + } + } + if (material.transmission > 0) { + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height); + if (material.transmissionMap) { + uniforms.transmissionMap.value = material.transmissionMap; + refreshTransformUniform(material.transmissionMap, uniforms.transmissionMapTransform); + } + uniforms.thickness.value = material.thickness; + if (material.thicknessMap) { + uniforms.thicknessMap.value = material.thicknessMap; + refreshTransformUniform(material.thicknessMap, uniforms.thicknessMapTransform); + } + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy(material.attenuationColor); + } + if (material.anisotropy > 0) { + uniforms.anisotropyVector.value.set(material.anisotropy * Math.cos(material.anisotropyRotation), material.anisotropy * Math.sin(material.anisotropyRotation)); + if (material.anisotropyMap) { + uniforms.anisotropyMap.value = material.anisotropyMap; + refreshTransformUniform(material.anisotropyMap, uniforms.anisotropyMapTransform); + } + } + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy(material.specularColor); + if (material.specularColorMap) { + uniforms.specularColorMap.value = material.specularColorMap; + refreshTransformUniform(material.specularColorMap, uniforms.specularColorMapTransform); + } + if (material.specularIntensityMap) { + uniforms.specularIntensityMap.value = material.specularIntensityMap; + refreshTransformUniform(material.specularIntensityMap, uniforms.specularIntensityMapTransform); + } + } + function refreshUniformsMatcap(uniforms, material) { + if (material.matcap) { + uniforms.matcap.value = material.matcap; + } + } + function refreshUniformsDistance(uniforms, material) { + const light = properties.get(material).light; + uniforms.referencePosition.value.setFromMatrixPosition(light.matrixWorld); + uniforms.nearDistance.value = light.shadow.camera.near; + uniforms.farDistance.value = light.shadow.camera.far; + } + return { + refreshFogUniforms, + refreshMaterialUniforms + }; + } + function WebGLUniformsGroups2(gl, info, capabilities, state) { + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + const maxBindingPoints = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS); + function bind(uniformsGroup, program) { + const webglProgram = program.program; + state.uniformBlockBinding(uniformsGroup, webglProgram); + } + function update(uniformsGroup, program) { + let buffer = buffers[uniformsGroup.id]; + if (buffer === undefined) { + prepareUniformsGroup(uniformsGroup); + buffer = createBuffer(uniformsGroup); + buffers[uniformsGroup.id] = buffer; + uniformsGroup.addEventListener("dispose", onUniformsGroupsDispose); + } + const webglProgram = program.program; + state.updateUBOMapping(uniformsGroup, webglProgram); + const frame = info.render.frame; + if (updateList[uniformsGroup.id] !== frame) { + updateBufferData(uniformsGroup); + updateList[uniformsGroup.id] = frame; + } + } + function createBuffer(uniformsGroup) { + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + const buffer = gl.createBuffer(); + const size2 = uniformsGroup.__size; + const usage = uniformsGroup.usage; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + gl.bufferData(gl.UNIFORM_BUFFER, size2, usage); + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer); + return buffer; + } + function allocateBindingPointIndex() { + for (let i = 0;i < maxBindingPoints; i++) { + if (allocatedBindingPoints.indexOf(i) === -1) { + allocatedBindingPoints.push(i); + return i; + } + } + console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."); + return 0; + } + function updateBufferData(uniformsGroup) { + const buffer = buffers[uniformsGroup.id]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + for (let i = 0, il = uniforms.length;i < il; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j2 = 0, jl = uniformArray.length;j2 < jl; j2++) { + const uniform = uniformArray[j2]; + if (hasUniformChanged(uniform, i, j2, cache) === true) { + const offset = uniform.__offset; + const values2 = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + let arrayOffset = 0; + for (let k3 = 0;k3 < values2.length; k3++) { + const value2 = values2[k3]; + const info2 = getUniformSize(value2); + if (typeof value2 === "number" || typeof value2 === "boolean") { + uniform.__data[0] = value2; + gl.bufferSubData(gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data); + } else if (value2.isMatrix3) { + uniform.__data[0] = value2.elements[0]; + uniform.__data[1] = value2.elements[1]; + uniform.__data[2] = value2.elements[2]; + uniform.__data[3] = 0; + uniform.__data[4] = value2.elements[3]; + uniform.__data[5] = value2.elements[4]; + uniform.__data[6] = value2.elements[5]; + uniform.__data[7] = 0; + uniform.__data[8] = value2.elements[6]; + uniform.__data[9] = value2.elements[7]; + uniform.__data[10] = value2.elements[8]; + uniform.__data[11] = 0; + } else { + value2.toArray(uniform.__data, arrayOffset); + arrayOffset += info2.storage / Float32Array.BYTES_PER_ELEMENT; + } + } + gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data); + } + } + } + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + } + function hasUniformChanged(uniform, index2, indexArray, cache) { + const value2 = uniform.value; + const indexString = index2 + "_" + indexArray; + if (cache[indexString] === undefined) { + if (typeof value2 === "number" || typeof value2 === "boolean") { + cache[indexString] = value2; + } else { + cache[indexString] = value2.clone(); + } + return true; + } else { + const cachedObject = cache[indexString]; + if (typeof value2 === "number" || typeof value2 === "boolean") { + if (cachedObject !== value2) { + cache[indexString] = value2; + return true; + } + } else { + if (cachedObject.equals(value2) === false) { + cachedObject.copy(value2); + return true; + } + } + } + return false; + } + function prepareUniformsGroup(uniformsGroup) { + const uniforms = uniformsGroup.uniforms; + let offset = 0; + const chunkSize = 16; + for (let i = 0, l2 = uniforms.length;i < l2; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j2 = 0, jl = uniformArray.length;j2 < jl; j2++) { + const uniform = uniformArray[j2]; + const values2 = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + for (let k3 = 0, kl = values2.length;k3 < kl; k3++) { + const value2 = values2[k3]; + const info2 = getUniformSize(value2); + const chunkOffset2 = offset % chunkSize; + const chunkPadding = chunkOffset2 % info2.boundary; + const chunkStart = chunkOffset2 + chunkPadding; + offset += chunkPadding; + if (chunkStart !== 0 && chunkSize - chunkStart < info2.storage) { + offset += chunkSize - chunkStart; + } + uniform.__data = new Float32Array(info2.storage / Float32Array.BYTES_PER_ELEMENT); + uniform.__offset = offset; + offset += info2.storage; + } + } + } + const chunkOffset = offset % chunkSize; + if (chunkOffset > 0) + offset += chunkSize - chunkOffset; + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + return this; + } + function getUniformSize(value2) { + const info2 = { + boundary: 0, + storage: 0 + }; + if (typeof value2 === "number" || typeof value2 === "boolean") { + info2.boundary = 4; + info2.storage = 4; + } else if (value2.isVector2) { + info2.boundary = 8; + info2.storage = 8; + } else if (value2.isVector3 || value2.isColor) { + info2.boundary = 16; + info2.storage = 12; + } else if (value2.isVector4) { + info2.boundary = 16; + info2.storage = 16; + } else if (value2.isMatrix3) { + info2.boundary = 48; + info2.storage = 48; + } else if (value2.isMatrix4) { + info2.boundary = 64; + info2.storage = 64; + } else if (value2.isTexture) { + console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."); + } else { + console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", value2); + } + return info2; + } + function onUniformsGroupsDispose(event) { + const uniformsGroup = event.target; + uniformsGroup.removeEventListener("dispose", onUniformsGroupsDispose); + const index2 = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex); + allocatedBindingPoints.splice(index2, 1); + gl.deleteBuffer(buffers[uniformsGroup.id]); + delete buffers[uniformsGroup.id]; + delete updateList[uniformsGroup.id]; + } + function dispose() { + for (const id in buffers) { + gl.deleteBuffer(buffers[id]); + } + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + } + return { + bind, + update, + dispose + }; + } + + class WebGLRenderer2 { + constructor(parameters = {}) { + const { + canvas = createCanvasElement2(), + context = null, + depth = true, + stencil = false, + alpha = false, + antialias = false, + premultipliedAlpha = true, + preserveDrawingBuffer = false, + powerPreference = "default", + failIfMajorPerformanceCaveat = false, + reverseDepthBuffer = false + } = parameters; + this.isWebGLRenderer = true; + let _alpha; + if (context !== null) { + if (typeof WebGLRenderingContext !== "undefined" && context instanceof WebGLRenderingContext) { + throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163."); + } + _alpha = context.getContextAttributes().alpha; + } else { + _alpha = alpha; + } + const uintClearColor = new Uint32Array(4); + const intClearColor = new Int32Array(4); + let currentRenderList = null; + let currentRenderState = null; + const renderListStack = []; + const renderStateStack = []; + this.domElement = canvas; + this.debug = { + checkShaderErrors: true, + onShaderError: null + }; + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + this.sortObjects = true; + this.clippingPlanes = []; + this.localClippingEnabled = false; + this._outputColorSpace = SRGBColorSpace2; + this.toneMapping = NoToneMapping2; + this.toneMappingExposure = 1; + const _this = this; + let _isContextLost = false; + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = -1; + let _currentCamera = null; + const _currentViewport = new Vector42; + const _currentScissor = new Vector42; + let _currentScissorTest = null; + const _currentClearColor = new Color2(0); + let _currentClearAlpha = 0; + let _width = canvas.width; + let _height = canvas.height; + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + const _viewport3 = new Vector42(0, 0, _width, _height); + const _scissor = new Vector42(0, 0, _width, _height); + let _scissorTest = false; + const _frustum4 = new Frustum2; + let _clippingEnabled = false; + let _localClippingEnabled = false; + this.transmissionResolutionScale = 1; + const _currentProjectionMatrix = new Matrix42; + const _projScreenMatrix3 = new Matrix42; + const _vector33 = new Vector32; + const _vector42 = new Vector42; + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + let _renderBackground = false; + function getTargetPixelRatio() { + return _currentRenderTarget === null ? _pixelRatio : 1; + } + let _gl = context; + function getContext(contextName, contextAttributes) { + return canvas.getContext(contextName, contextAttributes); + } + try { + const contextAttributes = { + alpha: true, + depth, + stencil, + antialias, + premultipliedAlpha, + preserveDrawingBuffer, + powerPreference, + failIfMajorPerformanceCaveat + }; + if ("setAttribute" in canvas) + canvas.setAttribute("data-engine", `three.js r${REVISION2}`); + canvas.addEventListener("webglcontextlost", onContextLost, false); + canvas.addEventListener("webglcontextrestored", onContextRestore, false); + canvas.addEventListener("webglcontextcreationerror", onContextCreationError, false); + if (_gl === null) { + const contextName = "webgl2"; + _gl = getContext(contextName, contextAttributes); + if (_gl === null) { + if (getContext(contextName)) { + throw new Error("Error creating WebGL context with your selected attributes."); + } else { + throw new Error("Error creating WebGL context."); + } + } + } + } catch (error) { + console.error("THREE.WebGLRenderer: " + error.message); + throw error; + } + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + let utils, bindingStates, uniformsGroups; + function initGLContext() { + extensions = new WebGLExtensions2(_gl); + extensions.init(); + utils = new WebGLUtils2(_gl, extensions); + capabilities = new WebGLCapabilities2(_gl, extensions, parameters, utils); + state = new WebGLState2(_gl, extensions); + if (capabilities.reverseDepthBuffer && reverseDepthBuffer) { + state.buffers.depth.setReversed(true); + } + info = new WebGLInfo2(_gl); + properties = new WebGLProperties2; + textures = new WebGLTextures2(_gl, extensions, state, properties, capabilities, utils, info); + cubemaps = new WebGLCubeMaps2(_this); + cubeuvmaps = new WebGLCubeUVMaps2(_this); + attributes = new WebGLAttributes2(_gl); + bindingStates = new WebGLBindingStates2(_gl, attributes); + geometries = new WebGLGeometries2(_gl, attributes, info, bindingStates); + objects = new WebGLObjects2(_gl, geometries, attributes, info); + morphtargets = new WebGLMorphtargets2(_gl, capabilities, textures); + clipping = new WebGLClipping2(properties); + programCache = new WebGLPrograms2(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping); + materials = new WebGLMaterials2(_this, properties); + renderLists = new WebGLRenderLists2; + renderStates = new WebGLRenderStates2(extensions); + background = new WebGLBackground2(_this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha); + shadowMap = new WebGLShadowMap2(_this, objects, capabilities); + uniformsGroups = new WebGLUniformsGroups2(_gl, info, capabilities, state); + bufferRenderer = new WebGLBufferRenderer2(_gl, extensions, info); + indexedBufferRenderer = new WebGLIndexedBufferRenderer2(_gl, extensions, info); + info.programs = programCache.programs; + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; + } + initGLContext(); + const xr = new WebXRManager2(_this, _gl); + this.xr = xr; + this.getContext = function() { + return _gl; + }; + this.getContextAttributes = function() { + return _gl.getContextAttributes(); + }; + this.forceContextLoss = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) + extension.loseContext(); + }; + this.forceContextRestore = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) + extension.restoreContext(); + }; + this.getPixelRatio = function() { + return _pixelRatio; + }; + this.setPixelRatio = function(value2) { + if (value2 === undefined) + return; + _pixelRatio = value2; + this.setSize(_width, _height, false); + }; + this.getSize = function(target) { + return target.set(_width, _height); + }; + this.setSize = function(width2, height2, updateStyle = true) { + if (xr.isPresenting) { + console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."); + return; + } + _width = width2; + _height = height2; + canvas.width = Math.floor(width2 * _pixelRatio); + canvas.height = Math.floor(height2 * _pixelRatio); + if (updateStyle === true) { + canvas.style.width = width2 + "px"; + canvas.style.height = height2 + "px"; + } + this.setViewport(0, 0, width2, height2); + }; + this.getDrawingBufferSize = function(target) { + return target.set(_width * _pixelRatio, _height * _pixelRatio).floor(); + }; + this.setDrawingBufferSize = function(width2, height2, pixelRatio) { + _width = width2; + _height = height2; + _pixelRatio = pixelRatio; + canvas.width = Math.floor(width2 * pixelRatio); + canvas.height = Math.floor(height2 * pixelRatio); + this.setViewport(0, 0, width2, height2); + }; + this.getCurrentViewport = function(target) { + return target.copy(_currentViewport); + }; + this.getViewport = function(target) { + return target.copy(_viewport3); + }; + this.setViewport = function(x2, y, width2, height2) { + if (x2.isVector4) { + _viewport3.set(x2.x, x2.y, x2.z, x2.w); + } else { + _viewport3.set(x2, y, width2, height2); + } + state.viewport(_currentViewport.copy(_viewport3).multiplyScalar(_pixelRatio).round()); + }; + this.getScissor = function(target) { + return target.copy(_scissor); + }; + this.setScissor = function(x2, y, width2, height2) { + if (x2.isVector4) { + _scissor.set(x2.x, x2.y, x2.z, x2.w); + } else { + _scissor.set(x2, y, width2, height2); + } + state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).round()); + }; + this.getScissorTest = function() { + return _scissorTest; + }; + this.setScissorTest = function(boolean) { + state.setScissorTest(_scissorTest = boolean); + }; + this.setOpaqueSort = function(method) { + _opaqueSort = method; + }; + this.setTransparentSort = function(method) { + _transparentSort = method; + }; + this.getClearColor = function(target) { + return target.copy(background.getClearColor()); + }; + this.setClearColor = function() { + background.setClearColor.apply(background, arguments); + }; + this.getClearAlpha = function() { + return background.getClearAlpha(); + }; + this.setClearAlpha = function() { + background.setClearAlpha.apply(background, arguments); + }; + this.clear = function(color = true, depth2 = true, stencil2 = true) { + let bits = 0; + if (color) { + let isIntegerFormat = false; + if (_currentRenderTarget !== null) { + const targetFormat = _currentRenderTarget.texture.format; + isIntegerFormat = targetFormat === RGBAIntegerFormat2 || targetFormat === RGIntegerFormat2 || targetFormat === RedIntegerFormat2; + } + if (isIntegerFormat) { + const targetType = _currentRenderTarget.texture.type; + const isUnsignedType = targetType === UnsignedByteType2 || targetType === UnsignedIntType2 || targetType === UnsignedShortType2 || targetType === UnsignedInt248Type2 || targetType === UnsignedShort4444Type2 || targetType === UnsignedShort5551Type2; + const clearColor = background.getClearColor(); + const a2 = background.getClearAlpha(); + const r = clearColor.r; + const g3 = clearColor.g; + const b2 = clearColor.b; + if (isUnsignedType) { + uintClearColor[0] = r; + uintClearColor[1] = g3; + uintClearColor[2] = b2; + uintClearColor[3] = a2; + _gl.clearBufferuiv(_gl.COLOR, 0, uintClearColor); + } else { + intClearColor[0] = r; + intClearColor[1] = g3; + intClearColor[2] = b2; + intClearColor[3] = a2; + _gl.clearBufferiv(_gl.COLOR, 0, intClearColor); + } + } else { + bits |= _gl.COLOR_BUFFER_BIT; + } + } + if (depth2) { + bits |= _gl.DEPTH_BUFFER_BIT; + } + if (stencil2) { + bits |= _gl.STENCIL_BUFFER_BIT; + this.state.buffers.stencil.setMask(4294967295); + } + _gl.clear(bits); + }; + this.clearColor = function() { + this.clear(true, false, false); + }; + this.clearDepth = function() { + this.clear(false, true, false); + }; + this.clearStencil = function() { + this.clear(false, false, true); + }; + this.dispose = function() { + canvas.removeEventListener("webglcontextlost", onContextLost, false); + canvas.removeEventListener("webglcontextrestored", onContextRestore, false); + canvas.removeEventListener("webglcontextcreationerror", onContextCreationError, false); + background.dispose(); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + xr.dispose(); + xr.removeEventListener("sessionstart", onXRSessionStart); + xr.removeEventListener("sessionend", onXRSessionEnd); + animation.stop(); + }; + function onContextLost(event) { + event.preventDefault(); + console.log("THREE.WebGLRenderer: Context Lost."); + _isContextLost = true; + } + function onContextRestore() { + console.log("THREE.WebGLRenderer: Context Restored."); + _isContextLost = false; + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + initGLContext(); + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + } + function onContextCreationError(event) { + console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", event.statusMessage); + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + deallocateMaterial(material); + } + function deallocateMaterial(material) { + releaseMaterialProgramReferences(material); + properties.remove(material); + } + function releaseMaterialProgramReferences(material) { + const programs = properties.get(material).programs; + if (programs !== undefined) { + programs.forEach(function(program) { + programCache.releaseProgram(program); + }); + if (material.isShaderMaterial) { + programCache.releaseShaderCache(material); + } + } + } + this.renderBufferDirect = function(camera, scene, geometry, material, object, group) { + if (scene === null) + scene = _emptyScene; + const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0; + const program = setProgram(camera, scene, geometry, material, object); + state.setMaterial(material, frontFaceCW); + let index2 = geometry.index; + let rangeFactor = 1; + if (material.wireframe === true) { + index2 = geometries.getWireframeAttribute(geometry); + if (index2 === undefined) + return; + rangeFactor = 2; + } + const drawRange = geometry.drawRange; + const position2 = geometry.attributes.position; + let drawStart = drawRange.start * rangeFactor; + let drawEnd = (drawRange.start + drawRange.count) * rangeFactor; + if (group !== null) { + drawStart = Math.max(drawStart, group.start * rangeFactor); + drawEnd = Math.min(drawEnd, (group.start + group.count) * rangeFactor); + } + if (index2 !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, index2.count); + } else if (position2 !== undefined && position2 !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, position2.count); + } + const drawCount = drawEnd - drawStart; + if (drawCount < 0 || drawCount === Infinity) + return; + bindingStates.setup(object, material, program, geometry, index2); + let attribute; + let renderer2 = bufferRenderer; + if (index2 !== null) { + attribute = attributes.get(index2); + renderer2 = indexedBufferRenderer; + renderer2.setIndex(attribute); + } + if (object.isMesh) { + if (material.wireframe === true) { + state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio()); + renderer2.setMode(_gl.LINES); + } else { + renderer2.setMode(_gl.TRIANGLES); + } + } else if (object.isLine) { + let lineWidth = material.linewidth; + if (lineWidth === undefined) + lineWidth = 1; + state.setLineWidth(lineWidth * getTargetPixelRatio()); + if (object.isLineSegments) { + renderer2.setMode(_gl.LINES); + } else if (object.isLineLoop) { + renderer2.setMode(_gl.LINE_LOOP); + } else { + renderer2.setMode(_gl.LINE_STRIP); + } + } else if (object.isPoints) { + renderer2.setMode(_gl.POINTS); + } else if (object.isSprite) { + renderer2.setMode(_gl.TRIANGLES); + } + if (object.isBatchedMesh) { + if (object._multiDrawInstances !== null) { + renderer2.renderMultiDrawInstances(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances); + } else { + if (!extensions.get("WEBGL_multi_draw")) { + const starts = object._multiDrawStarts; + const counts = object._multiDrawCounts; + const drawCount2 = object._multiDrawCount; + const bytesPerElement = index2 ? attributes.get(index2).bytesPerElement : 1; + const uniforms = properties.get(material).currentProgram.getUniforms(); + for (let i = 0;i < drawCount2; i++) { + uniforms.setValue(_gl, "_gl_DrawID", i); + renderer2.render(starts[i] / bytesPerElement, counts[i]); + } + } else { + renderer2.renderMultiDraw(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount); + } + } + } else if (object.isInstancedMesh) { + renderer2.renderInstances(drawStart, drawCount, object.count); + } else if (geometry.isInstancedBufferGeometry) { + const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min(geometry.instanceCount, maxInstanceCount); + renderer2.renderInstances(drawStart, drawCount, instanceCount); + } else { + renderer2.render(drawStart, drawCount); + } + }; + function prepareMaterial(material, scene, object) { + if (material.transparent === true && material.side === DoubleSide2 && material.forceSinglePass === false) { + material.side = BackSide2; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = FrontSide2; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = DoubleSide2; + } else { + getProgram(material, scene, object); + } + } + this.compile = function(scene, camera, targetScene = null) { + if (targetScene === null) + targetScene = scene; + currentRenderState = renderStates.get(targetScene); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + targetScene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + if (scene !== targetScene) { + scene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + } + currentRenderState.setupLights(); + const materials2 = new Set; + scene.traverse(function(object) { + if (!(object.isMesh || object.isPoints || object.isLine || object.isSprite)) { + return; + } + const material = object.material; + if (material) { + if (Array.isArray(material)) { + for (let i = 0;i < material.length; i++) { + const material2 = material[i]; + prepareMaterial(material2, targetScene, object); + materials2.add(material2); + } + } else { + prepareMaterial(material, targetScene, object); + materials2.add(material); + } + } + }); + renderStateStack.pop(); + currentRenderState = null; + return materials2; + }; + this.compileAsync = function(scene, camera, targetScene = null) { + const materials2 = this.compile(scene, camera, targetScene); + return new Promise((resolve) => { + function checkMaterialsReady() { + materials2.forEach(function(material) { + const materialProperties = properties.get(material); + const program = materialProperties.currentProgram; + if (program.isReady()) { + materials2.delete(material); + } + }); + if (materials2.size === 0) { + resolve(scene); + return; + } + setTimeout(checkMaterialsReady, 10); + } + if (extensions.get("KHR_parallel_shader_compile") !== null) { + checkMaterialsReady(); + } else { + setTimeout(checkMaterialsReady, 10); + } + }); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time2) { + if (onAnimationFrameCallback) + onAnimationFrameCallback(time2); + } + function onXRSessionStart() { + animation.stop(); + } + function onXRSessionEnd() { + animation.start(); + } + const animation = new WebGLAnimation2; + animation.setAnimationLoop(onAnimationFrame); + if (typeof self !== "undefined") + animation.setContext(self); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + xr.setAnimationLoop(callback); + callback === null ? animation.stop() : animation.start(); + }; + xr.addEventListener("sessionstart", onXRSessionStart); + xr.addEventListener("sessionend", onXRSessionEnd); + this.render = function(scene, camera) { + if (camera !== undefined && camera.isCamera !== true) { + console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera."); + return; + } + if (_isContextLost === true) + return; + if (scene.matrixWorldAutoUpdate === true) + scene.updateMatrixWorld(); + if (camera.parent === null && camera.matrixWorldAutoUpdate === true) + camera.updateMatrixWorld(); + if (xr.enabled === true && xr.isPresenting === true) { + if (xr.cameraAutoUpdate === true) + xr.updateCamera(camera); + camera = xr.getCamera(); + } + if (scene.isScene === true) + scene.onBeforeRender(_this, scene, camera, _currentRenderTarget); + currentRenderState = renderStates.get(scene, renderStateStack.length); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + _projScreenMatrix3.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + _frustum4.setFromProjectionMatrix(_projScreenMatrix3); + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled); + currentRenderList = renderLists.get(scene, renderListStack.length); + currentRenderList.init(); + renderListStack.push(currentRenderList); + if (xr.enabled === true && xr.isPresenting === true) { + const depthSensingMesh = _this.xr.getDepthSensingMesh(); + if (depthSensingMesh !== null) { + projectObject(depthSensingMesh, camera, -Infinity, _this.sortObjects); + } + } + projectObject(scene, camera, 0, _this.sortObjects); + currentRenderList.finish(); + if (_this.sortObjects === true) { + currentRenderList.sort(_opaqueSort, _transparentSort); + } + _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false; + if (_renderBackground) { + background.addToRenderList(currentRenderList, scene); + } + this.info.render.frame++; + if (_clippingEnabled === true) + clipping.beginShadows(); + const shadowsArray = currentRenderState.state.shadowsArray; + shadowMap.render(shadowsArray, scene, camera); + if (_clippingEnabled === true) + clipping.endShadows(); + if (this.info.autoReset === true) + this.info.reset(); + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + currentRenderState.setupLights(); + if (camera.isArrayCamera) { + const cameras = camera.cameras; + if (transmissiveObjects.length > 0) { + for (let i = 0, l2 = cameras.length;i < l2; i++) { + const camera2 = cameras[i]; + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera2); + } + } + if (_renderBackground) + background.render(scene); + for (let i = 0, l2 = cameras.length;i < l2; i++) { + const camera2 = cameras[i]; + renderScene(currentRenderList, scene, camera2, camera2.viewport); + } + } else { + if (transmissiveObjects.length > 0) + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera); + if (_renderBackground) + background.render(scene); + renderScene(currentRenderList, scene, camera); + } + if (_currentRenderTarget !== null && _currentActiveMipmapLevel === 0) { + textures.updateMultisampleRenderTarget(_currentRenderTarget); + textures.updateRenderTargetMipmap(_currentRenderTarget); + } + if (scene.isScene === true) + scene.onAfterRender(_this, scene, camera); + bindingStates.resetDefaultState(); + _currentMaterialId = -1; + _currentCamera = null; + renderStateStack.pop(); + if (renderStateStack.length > 0) { + currentRenderState = renderStateStack[renderStateStack.length - 1]; + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, currentRenderState.state.camera); + } else { + currentRenderState = null; + } + renderListStack.pop(); + if (renderListStack.length > 0) { + currentRenderList = renderListStack[renderListStack.length - 1]; + } else { + currentRenderList = null; + } + }; + function projectObject(object, camera, groupOrder, sortObjects) { + if (object.visible === false) + return; + const visible = object.layers.test(camera.layers); + if (visible) { + if (object.isGroup) { + groupOrder = object.renderOrder; + } else if (object.isLOD) { + if (object.autoUpdate === true) + object.update(camera); + } else if (object.isLight) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } else if (object.isSprite) { + if (!object.frustumCulled || _frustum4.intersectsSprite(object)) { + if (sortObjects) { + _vector42.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix3); + } + const geometry = objects.update(object); + const material = object.material; + if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector42.z, null); + } + } + } else if (object.isMesh || object.isLine || object.isPoints) { + if (!object.frustumCulled || _frustum4.intersectsObject(object)) { + const geometry = objects.update(object); + const material = object.material; + if (sortObjects) { + if (object.boundingSphere !== undefined) { + if (object.boundingSphere === null) + object.computeBoundingSphere(); + _vector42.copy(object.boundingSphere.center); + } else { + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _vector42.copy(geometry.boundingSphere.center); + } + _vector42.applyMatrix4(object.matrixWorld).applyMatrix4(_projScreenMatrix3); + } + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let i = 0, l2 = groups.length;i < l2; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector42.z, group); + } + } + } else if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector42.z, null); + } + } + } + } + const children = object.children; + for (let i = 0, l2 = children.length;i < l2; i++) { + projectObject(children[i], camera, groupOrder, sortObjects); + } + } + function renderScene(currentRenderList2, scene, camera, viewport) { + const opaqueObjects = currentRenderList2.opaque; + const transmissiveObjects = currentRenderList2.transmissive; + const transparentObjects = currentRenderList2.transparent; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, camera); + if (viewport) + state.viewport(_currentViewport.copy(viewport)); + if (opaqueObjects.length > 0) + renderObjects(opaqueObjects, scene, camera); + if (transmissiveObjects.length > 0) + renderObjects(transmissiveObjects, scene, camera); + if (transparentObjects.length > 0) + renderObjects(transparentObjects, scene, camera); + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + state.setPolygonOffset(false); + } + function renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + if (overrideMaterial !== null) { + return; + } + if (currentRenderState.state.transmissionRenderTarget[camera.id] === undefined) { + currentRenderState.state.transmissionRenderTarget[camera.id] = new WebGLRenderTarget2(1, 1, { + generateMipmaps: true, + type: extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float") ? HalfFloatType2 : UnsignedByteType2, + minFilter: LinearMipmapLinearFilter2, + samples: 4, + stencilBuffer: stencil, + resolveDepthBuffer: false, + resolveStencilBuffer: false, + colorSpace: ColorManagement2.workingColorSpace + }); + } + const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[camera.id]; + const activeViewport = camera.viewport || _currentViewport; + transmissionRenderTarget.setSize(activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale); + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget(transmissionRenderTarget); + _this.getClearColor(_currentClearColor); + _currentClearAlpha = _this.getClearAlpha(); + if (_currentClearAlpha < 1) + _this.setClearColor(16777215, 0.5); + _this.clear(); + if (_renderBackground) + background.render(scene); + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping2; + const currentCameraViewport = camera.viewport; + if (camera.viewport !== undefined) + camera.viewport = undefined; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, camera); + renderObjects(opaqueObjects, scene, camera); + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + if (extensions.has("WEBGL_multisampled_render_to_texture") === false) { + let renderTargetNeedsUpdate = false; + for (let i = 0, l2 = transmissiveObjects.length;i < l2; i++) { + const renderItem = transmissiveObjects[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = renderItem.material; + const group = renderItem.group; + if (material.side === DoubleSide2 && object.layers.test(camera.layers)) { + const currentSide = material.side; + material.side = BackSide2; + material.needsUpdate = true; + renderObject(object, scene, camera, geometry, material, group); + material.side = currentSide; + material.needsUpdate = true; + renderTargetNeedsUpdate = true; + } + } + if (renderTargetNeedsUpdate === true) { + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + } + } + _this.setRenderTarget(currentRenderTarget); + _this.setClearColor(_currentClearColor, _currentClearAlpha); + if (currentCameraViewport !== undefined) + camera.viewport = currentCameraViewport; + _this.toneMapping = currentToneMapping; + } + function renderObjects(renderList, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + for (let i = 0, l2 = renderList.length;i < l2; i++) { + const renderItem = renderList[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; + if (object.layers.test(camera.layers)) { + renderObject(object, scene, camera, geometry, material, group); + } + } + } + function renderObject(object, scene, camera, geometry, material, group) { + object.onBeforeRender(_this, scene, camera, geometry, material, group); + object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld); + object.normalMatrix.getNormalMatrix(object.modelViewMatrix); + material.onBeforeRender(_this, scene, camera, geometry, object, group); + if (material.transparent === true && material.side === DoubleSide2 && material.forceSinglePass === false) { + material.side = BackSide2; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = FrontSide2; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = DoubleSide2; + } else { + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + } + object.onAfterRender(_this, scene, camera, geometry, material, group); + } + function getProgram(material, scene, object) { + if (scene.isScene !== true) + scene = _emptyScene; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + const lightsStateVersion = lights.state.version; + const parameters2 = programCache.getParameters(material, lights.state, shadowsArray, scene, object); + const programCacheKey = programCache.getProgramCacheKey(parameters2); + let programs = materialProperties.programs; + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment); + materialProperties.envMapRotation = materialProperties.environment !== null && material.envMap === null ? scene.environmentRotation : material.envMapRotation; + if (programs === undefined) { + material.addEventListener("dispose", onMaterialDispose); + programs = new Map; + materialProperties.programs = programs; + } + let program = programs.get(programCacheKey); + if (program !== undefined) { + if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) { + updateCommonMaterialProperties(material, parameters2); + return program; + } + } else { + parameters2.uniforms = programCache.getUniforms(material); + material.onBeforeCompile(parameters2, _this); + program = programCache.acquireProgram(parameters2, programCacheKey); + programs.set(programCacheKey, program); + materialProperties.uniforms = parameters2.uniforms; + } + const uniforms = materialProperties.uniforms; + if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) { + uniforms.clippingPlanes = clipping.uniform; + } + updateCommonMaterialProperties(material, parameters2); + materialProperties.needsLights = materialNeedsLights(material); + materialProperties.lightsStateVersion = lightsStateVersion; + if (materialProperties.needsLights) { + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + } + materialProperties.currentProgram = program; + materialProperties.uniformsList = null; + return program; + } + function getUniformList(materialProperties) { + if (materialProperties.uniformsList === null) { + const progUniforms = materialProperties.currentProgram.getUniforms(); + materialProperties.uniformsList = WebGLUniforms2.seqWithValue(progUniforms.seq, materialProperties.uniforms); + } + return materialProperties.uniformsList; + } + function updateCommonMaterialProperties(material, parameters2) { + const materialProperties = properties.get(material); + materialProperties.outputColorSpace = parameters2.outputColorSpace; + materialProperties.batching = parameters2.batching; + materialProperties.batchingColor = parameters2.batchingColor; + materialProperties.instancing = parameters2.instancing; + materialProperties.instancingColor = parameters2.instancingColor; + materialProperties.instancingMorph = parameters2.instancingMorph; + materialProperties.skinning = parameters2.skinning; + materialProperties.morphTargets = parameters2.morphTargets; + materialProperties.morphNormals = parameters2.morphNormals; + materialProperties.morphColors = parameters2.morphColors; + materialProperties.morphTargetsCount = parameters2.morphTargetsCount; + materialProperties.numClippingPlanes = parameters2.numClippingPlanes; + materialProperties.numIntersection = parameters2.numClipIntersection; + materialProperties.vertexAlphas = parameters2.vertexAlphas; + materialProperties.vertexTangents = parameters2.vertexTangents; + materialProperties.toneMapping = parameters2.toneMapping; + } + function setProgram(camera, scene, geometry, material, object) { + if (scene.isScene !== true) + scene = _emptyScene; + textures.resetTextureUnits(); + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const colorSpace = _currentRenderTarget === null ? _this.outputColorSpace : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace2; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !!geometry.attributes.tangent && (!!material.normalMap || material.anisotropy > 0); + const morphTargets = !!geometry.morphAttributes.position; + const morphNormals = !!geometry.morphAttributes.normal; + const morphColors = !!geometry.morphAttributes.color; + let toneMapping = NoToneMapping2; + if (material.toneMapped) { + if (_currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true) { + toneMapping = _this.toneMapping; + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + if (_clippingEnabled === true) { + if (_localClippingEnabled === true || camera !== _currentCamera) { + const useCache = camera === _currentCamera && material.id === _currentMaterialId; + clipping.setState(material, camera, useCache); + } + } + let needsProgramChange = false; + if (material.version === materialProperties.__version) { + if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) { + needsProgramChange = true; + } else if (materialProperties.outputColorSpace !== colorSpace) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batching === false) { + needsProgramChange = true; + } else if (!object.isBatchedMesh && materialProperties.batching === true) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancing === false) { + needsProgramChange = true; + } else if (!object.isInstancedMesh && materialProperties.instancing === true) { + needsProgramChange = true; + } else if (object.isSkinnedMesh && materialProperties.skinning === false) { + needsProgramChange = true; + } else if (!object.isSkinnedMesh && materialProperties.skinning === true) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null) { + needsProgramChange = true; + } else if (materialProperties.envMap !== envMap) { + needsProgramChange = true; + } else if (material.fog === true && materialProperties.fog !== fog) { + needsProgramChange = true; + } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) { + needsProgramChange = true; + } else if (materialProperties.vertexAlphas !== vertexAlphas) { + needsProgramChange = true; + } else if (materialProperties.vertexTangents !== vertexTangents) { + needsProgramChange = true; + } else if (materialProperties.morphTargets !== morphTargets) { + needsProgramChange = true; + } else if (materialProperties.morphNormals !== morphNormals) { + needsProgramChange = true; + } else if (materialProperties.morphColors !== morphColors) { + needsProgramChange = true; + } else if (materialProperties.toneMapping !== toneMapping) { + needsProgramChange = true; + } else if (materialProperties.morphTargetsCount !== morphTargetsCount) { + needsProgramChange = true; + } + } else { + needsProgramChange = true; + materialProperties.__version = material.version; + } + let program = materialProperties.currentProgram; + if (needsProgramChange === true) { + program = getProgram(material, scene, object); + } + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + const p_uniforms = program.getUniforms(), m_uniforms = materialProperties.uniforms; + if (state.useProgram(program.program)) { + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + } + if (material.id !== _currentMaterialId) { + _currentMaterialId = material.id; + refreshMaterial = true; + } + if (refreshProgram || _currentCamera !== camera) { + const reverseDepthBuffer2 = state.buffers.depth.getReversed(); + if (reverseDepthBuffer2) { + _currentProjectionMatrix.copy(camera.projectionMatrix); + toNormalizedProjectionMatrix2(_currentProjectionMatrix); + toReversedProjectionMatrix2(_currentProjectionMatrix); + p_uniforms.setValue(_gl, "projectionMatrix", _currentProjectionMatrix); + } else { + p_uniforms.setValue(_gl, "projectionMatrix", camera.projectionMatrix); + } + p_uniforms.setValue(_gl, "viewMatrix", camera.matrixWorldInverse); + const uCamPos = p_uniforms.map.cameraPosition; + if (uCamPos !== undefined) { + uCamPos.setValue(_gl, _vector33.setFromMatrixPosition(camera.matrixWorld)); + } + if (capabilities.logarithmicDepthBuffer) { + p_uniforms.setValue(_gl, "logDepthBufFC", 2 / (Math.log(camera.far + 1) / Math.LN2)); + } + if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) { + p_uniforms.setValue(_gl, "isOrthographic", camera.isOrthographicCamera === true); + } + if (_currentCamera !== camera) { + _currentCamera = camera; + refreshMaterial = true; + refreshLights = true; + } + } + if (object.isSkinnedMesh) { + p_uniforms.setOptional(_gl, object, "bindMatrix"); + p_uniforms.setOptional(_gl, object, "bindMatrixInverse"); + const skeleton = object.skeleton; + if (skeleton) { + if (skeleton.boneTexture === null) + skeleton.computeBoneTexture(); + p_uniforms.setValue(_gl, "boneTexture", skeleton.boneTexture, textures); + } + } + if (object.isBatchedMesh) { + p_uniforms.setOptional(_gl, object, "batchingTexture"); + p_uniforms.setValue(_gl, "batchingTexture", object._matricesTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingIdTexture"); + p_uniforms.setValue(_gl, "batchingIdTexture", object._indirectTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingColorTexture"); + if (object._colorsTexture !== null) { + p_uniforms.setValue(_gl, "batchingColorTexture", object._colorsTexture, textures); + } + } + const morphAttributes = geometry.morphAttributes; + if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined) { + morphtargets.update(object, geometry, program); + } + if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) { + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue(_gl, "receiveShadow", object.receiveShadow); + } + if (material.isMeshGouraudMaterial && material.envMap !== null) { + m_uniforms.envMap.value = envMap; + m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + } + if (material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null) { + m_uniforms.envMapIntensity.value = scene.environmentIntensity; + } + if (refreshMaterial) { + p_uniforms.setValue(_gl, "toneMappingExposure", _this.toneMappingExposure); + if (materialProperties.needsLights) { + markUniformsLightsNeedsUpdate(m_uniforms, refreshLights); + } + if (fog && material.fog === true) { + materials.refreshFogUniforms(m_uniforms, fog); + } + materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[camera.id]); + WebGLUniforms2.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + } + if (material.isShaderMaterial && material.uniformsNeedUpdate === true) { + WebGLUniforms2.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + material.uniformsNeedUpdate = false; + } + if (material.isSpriteMaterial) { + p_uniforms.setValue(_gl, "center", object.center); + } + p_uniforms.setValue(_gl, "modelViewMatrix", object.modelViewMatrix); + p_uniforms.setValue(_gl, "normalMatrix", object.normalMatrix); + p_uniforms.setValue(_gl, "modelMatrix", object.matrixWorld); + if (material.isShaderMaterial || material.isRawShaderMaterial) { + const groups = material.uniformsGroups; + for (let i = 0, l2 = groups.length;i < l2; i++) { + const group = groups[i]; + uniformsGroups.update(group, program); + uniformsGroups.bind(group, program); + } + } + return program; + } + function markUniformsLightsNeedsUpdate(uniforms, value2) { + uniforms.ambientLightColor.needsUpdate = value2; + uniforms.lightProbe.needsUpdate = value2; + uniforms.directionalLights.needsUpdate = value2; + uniforms.directionalLightShadows.needsUpdate = value2; + uniforms.pointLights.needsUpdate = value2; + uniforms.pointLightShadows.needsUpdate = value2; + uniforms.spotLights.needsUpdate = value2; + uniforms.spotLightShadows.needsUpdate = value2; + uniforms.rectAreaLights.needsUpdate = value2; + uniforms.hemisphereLights.needsUpdate = value2; + } + function materialNeedsLights(material) { + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true; + } + this.getActiveCubeFace = function() { + return _currentActiveCubeFace; + }; + this.getActiveMipmapLevel = function() { + return _currentActiveMipmapLevel; + }; + this.getRenderTarget = function() { + return _currentRenderTarget; + }; + this.setRenderTargetTextures = function(renderTarget, colorTexture, depthTexture) { + properties.get(renderTarget.texture).__webglTexture = colorTexture; + properties.get(renderTarget.depthTexture).__webglTexture = depthTexture; + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__hasExternalTextures = true; + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; + if (!renderTargetProperties.__autoAllocateDepthBuffer) { + if (extensions.has("WEBGL_multisampled_render_to_texture") === true) { + console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"); + renderTargetProperties.__useRenderToTexture = false; + } + } + }; + this.setRenderTargetFramebuffer = function(renderTarget, defaultFramebuffer) { + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; + }; + const _scratchFrameBuffer = _gl.createFramebuffer(); + this.setRenderTarget = function(renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) { + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + if (renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTargetProperties.__useDefaultFramebuffer !== undefined) { + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + useDefaultFramebuffer = false; + } else if (renderTargetProperties.__webglFramebuffer === undefined) { + textures.setupRenderTarget(renderTarget); + } else if (renderTargetProperties.__hasExternalTextures) { + textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture); + } else if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__boundDepthTexture !== depthTexture) { + if (depthTexture !== null && properties.has(depthTexture) && (renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height)) { + throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size."); + } + textures.setupDepthRenderbuffer(renderTarget); + } + } + const texture = renderTarget.texture; + if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + isRenderTarget3D = true; + } + const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget) { + if (Array.isArray(__webglFramebuffer[activeCubeFace])) { + framebuffer = __webglFramebuffer[activeCubeFace][activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer[activeCubeFace]; + } + isCube = true; + } else if (renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) { + framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer; + } else { + if (Array.isArray(__webglFramebuffer)) { + framebuffer = __webglFramebuffer[activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer; + } + } + _currentViewport.copy(renderTarget.viewport); + _currentScissor.copy(renderTarget.scissor); + _currentScissorTest = renderTarget.scissorTest; + } else { + _currentViewport.copy(_viewport3).multiplyScalar(_pixelRatio).floor(); + _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(); + _currentScissorTest = _scissorTest; + } + if (activeMipmapLevel !== 0) { + framebuffer = _scratchFrameBuffer; + } + const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (framebufferBound && useDefaultFramebuffer) { + state.drawBuffers(renderTarget, framebuffer); + } + state.viewport(_currentViewport); + state.scissor(_currentScissor); + state.setScissorTest(_currentScissorTest); + if (isCube) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel); + } else if (isRenderTarget3D) { + const textureProperties = properties.get(renderTarget.texture); + const layer = activeCubeFace; + _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer); + } else if (renderTarget !== null && activeMipmapLevel !== 0) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel); + } + _currentMaterialId = -1; + }; + this.readRenderTargetPixels = function(renderTarget, x2, y, width2, height2, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + return; + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + try { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); + return; + } + if (!capabilities.textureTypeReadable(textureType)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); + return; + } + if (x2 >= 0 && x2 <= renderTarget.width - width2 && (y >= 0 && y <= renderTarget.height - height2)) { + _gl.readPixels(x2, y, width2, height2, utils.convert(textureFormat), utils.convert(textureType), buffer); + } + } finally { + const framebuffer2 = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer2); + } + } + }; + this.readRenderTargetPixelsAsync = async function(renderTarget, x2, y, width2, height2, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format."); + } + if (!capabilities.textureTypeReadable(textureType)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type."); + } + if (x2 >= 0 && x2 <= renderTarget.width - width2 && (y >= 0 && y <= renderTarget.height - height2)) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + const glBuffer = _gl.createBuffer(); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.bufferData(_gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ); + _gl.readPixels(x2, y, width2, height2, utils.convert(textureFormat), utils.convert(textureType), 0); + const currFramebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, currFramebuffer); + const sync = _gl.fenceSync(_gl.SYNC_GPU_COMMANDS_COMPLETE, 0); + _gl.flush(); + await probeAsync2(_gl, sync, 4); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.getBufferSubData(_gl.PIXEL_PACK_BUFFER, 0, buffer); + _gl.deleteBuffer(glBuffer); + _gl.deleteSync(sync); + return buffer; + } else { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range."); + } + } + }; + this.copyFramebufferToTexture = function(texture, position2 = null, level = 0) { + if (texture.isTexture !== true) { + warnOnce2("WebGLRenderer: copyFramebufferToTexture function signature has changed."); + position2 = arguments[0] || null; + texture = arguments[1]; + } + const levelScale = Math.pow(2, -level); + const width2 = Math.floor(texture.image.width * levelScale); + const height2 = Math.floor(texture.image.height * levelScale); + const x2 = position2 !== null ? position2.x : 0; + const y = position2 !== null ? position2.y : 0; + textures.setTexture2D(texture, 0); + _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, x2, y, width2, height2); + state.unbindTexture(); + }; + const _srcFramebuffer = _gl.createFramebuffer(); + const _dstFramebuffer = _gl.createFramebuffer(); + this.copyTextureToTexture = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null) { + if (srcTexture.isTexture !== true) { + warnOnce2("WebGLRenderer: copyTextureToTexture function signature has changed."); + dstPosition = arguments[0] || null; + srcTexture = arguments[1]; + dstTexture = arguments[2]; + dstLevel = arguments[3] || 0; + srcRegion = null; + } + if (dstLevel === null) { + if (srcLevel !== 0) { + warnOnce2("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."); + dstLevel = srcLevel; + srcLevel = 0; + } else { + dstLevel = 0; + } + } + let width2, height2, depth2, minX, minY, minZ; + let dstX, dstY, dstZ; + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[dstLevel] : srcTexture.image; + if (srcRegion !== null) { + width2 = srcRegion.max.x - srcRegion.min.x; + height2 = srcRegion.max.y - srcRegion.min.y; + depth2 = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1; + minX = srcRegion.min.x; + minY = srcRegion.min.y; + minZ = srcRegion.isBox3 ? srcRegion.min.z : 0; + } else { + const levelScale = Math.pow(2, -srcLevel); + width2 = Math.floor(image.width * levelScale); + height2 = Math.floor(image.height * levelScale); + if (srcTexture.isDataArrayTexture) { + depth2 = image.depth; + } else if (srcTexture.isData3DTexture) { + depth2 = Math.floor(image.depth * levelScale); + } else { + depth2 = 1; + } + minX = 0; + minY = 0; + minZ = 0; + } + if (dstPosition !== null) { + dstX = dstPosition.x; + dstY = dstPosition.y; + dstZ = dstPosition.z; + } else { + dstX = 0; + dstY = 0; + dstZ = 0; + } + const glFormat = utils.convert(dstTexture.format); + const glType = utils.convert(dstTexture.type); + let glTarget; + if (dstTexture.isData3DTexture) { + textures.setTexture3D(dstTexture, 0); + glTarget = _gl.TEXTURE_3D; + } else if (dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture) { + textures.setTexture2DArray(dstTexture, 0); + glTarget = _gl.TEXTURE_2D_ARRAY; + } else { + textures.setTexture2D(dstTexture, 0); + glTarget = _gl.TEXTURE_2D; + } + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment); + const currentUnpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH); + const currentUnpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT); + const currentUnpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS); + const currentUnpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS); + const currentUnpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES); + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, minX); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, minY); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, minZ); + const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture; + const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture; + if (srcTexture.isDepthTexture) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + const srcRenderTargetProperties = properties.get(srcTextureProperties.__renderTarget); + const dstRenderTargetProperties = properties.get(dstTextureProperties.__renderTarget); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer); + for (let i = 0;i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(srcTexture).__webglTexture, srcLevel, minZ + i); + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(dstTexture).__webglTexture, dstLevel, dstZ + i); + } + _gl.blitFramebuffer(minX, minY, width2, height2, dstX, dstY, width2, height2, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST); + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else if (srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has(srcTexture)) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, _srcFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, _dstFramebuffer); + for (let i = 0;i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i); + } else { + _gl.framebufferTexture2D(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel); + } + if (isDst3D) { + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i); + } else { + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel); + } + if (srcLevel !== 0) { + _gl.blitFramebuffer(minX, minY, width2, height2, dstX, dstY, width2, height2, _gl.COLOR_BUFFER_BIT, _gl.NEAREST); + } else if (isDst3D) { + _gl.copyTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width2, height2); + } else { + _gl.copyTexSubImage2D(glTarget, dstLevel, dstX, dstY, minX, minY, width2, height2); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else { + if (isDst3D) { + if (srcTexture.isDataTexture || srcTexture.isData3DTexture) { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, glType, image.data); + } else if (dstTexture.isCompressedArrayTexture) { + _gl.compressedTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, image.data); + } else { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, glType, image); + } + } else { + if (srcTexture.isDataTexture) { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width2, height2, glFormat, glType, image.data); + } else if (srcTexture.isCompressedTexture) { + _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data); + } else { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width2, height2, glFormat, glType, image); + } + } + } + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, currentUnpackRowLen); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages); + if (dstLevel === 0 && dstTexture.generateMipmaps) { + _gl.generateMipmap(glTarget); + } + state.unbindTexture(); + }; + this.copyTextureToTexture3D = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0) { + if (srcTexture.isTexture !== true) { + warnOnce2("WebGLRenderer: copyTextureToTexture3D function signature has changed."); + srcRegion = arguments[0] || null; + dstPosition = arguments[1] || null; + srcTexture = arguments[2]; + dstTexture = arguments[3]; + level = arguments[4] || 0; + } + warnOnce2('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'); + return this.copyTextureToTexture(srcTexture, dstTexture, srcRegion, dstPosition, level); + }; + this.initRenderTarget = function(target) { + if (properties.get(target).__webglFramebuffer === undefined) { + textures.setupRenderTarget(target); + } + }; + this.initTexture = function(texture) { + if (texture.isCubeTexture) { + textures.setTextureCube(texture, 0); + } else if (texture.isData3DTexture) { + textures.setTexture3D(texture, 0); + } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + textures.setTexture2DArray(texture, 0); + } else { + textures.setTexture2D(texture, 0); + } + state.unbindTexture(); + }; + this.resetState = function() { + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + state.reset(); + bindingStates.reset(); + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + get coordinateSystem() { + return WebGLCoordinateSystem2; + } + get outputColorSpace() { + return this._outputColorSpace; + } + set outputColorSpace(colorSpace) { + this._outputColorSpace = colorSpace; + const gl = this.getContext(); + gl.drawingBufferColorspace = ColorManagement2._getDrawingBufferColorSpace(colorSpace); + gl.unpackColorSpace = ColorManagement2._getUnpackColorSpace(); + } + } + exports2.ACESFilmicToneMapping = ACESFilmicToneMapping2; + exports2.AddEquation = AddEquation2; + exports2.AddOperation = AddOperation2; + exports2.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode2; + exports2.AdditiveBlending = AdditiveBlending2; + exports2.AgXToneMapping = AgXToneMapping2; + exports2.AlphaFormat = AlphaFormat2; + exports2.AlwaysCompare = AlwaysCompare2; + exports2.AlwaysDepth = AlwaysDepth2; + exports2.AlwaysStencilFunc = AlwaysStencilFunc2; + exports2.AmbientLight = AmbientLight2; + exports2.AnimationAction = AnimationAction2; + exports2.AnimationClip = AnimationClip2; + exports2.AnimationLoader = AnimationLoader2; + exports2.AnimationMixer = AnimationMixer2; + exports2.AnimationObjectGroup = AnimationObjectGroup2; + exports2.AnimationUtils = AnimationUtils2; + exports2.ArcCurve = ArcCurve2; + exports2.ArrayCamera = ArrayCamera2; + exports2.ArrowHelper = ArrowHelper2; + exports2.AttachedBindMode = AttachedBindMode2; + exports2.Audio = Audio2; + exports2.AudioAnalyser = AudioAnalyser2; + exports2.AudioContext = AudioContext2; + exports2.AudioListener = AudioListener2; + exports2.AudioLoader = AudioLoader2; + exports2.AxesHelper = AxesHelper2; + exports2.BackSide = BackSide2; + exports2.BasicDepthPacking = BasicDepthPacking2; + exports2.BasicShadowMap = BasicShadowMap2; + exports2.BatchedMesh = BatchedMesh2; + exports2.Bone = Bone2; + exports2.BooleanKeyframeTrack = BooleanKeyframeTrack2; + exports2.Box2 = Box22; + exports2.Box3 = Box32; + exports2.Box3Helper = Box3Helper2; + exports2.BoxGeometry = BoxGeometry2; + exports2.BoxHelper = BoxHelper2; + exports2.BufferAttribute = BufferAttribute2; + exports2.BufferGeometry = BufferGeometry2; + exports2.BufferGeometryLoader = BufferGeometryLoader2; + exports2.ByteType = ByteType2; + exports2.Cache = Cache2; + exports2.Camera = Camera2; + exports2.CameraHelper = CameraHelper2; + exports2.CanvasTexture = CanvasTexture2; + exports2.CapsuleGeometry = CapsuleGeometry2; + exports2.CatmullRomCurve3 = CatmullRomCurve32; + exports2.CineonToneMapping = CineonToneMapping2; + exports2.CircleGeometry = CircleGeometry2; + exports2.ClampToEdgeWrapping = ClampToEdgeWrapping2; + exports2.Clock = Clock2; + exports2.Color = Color2; + exports2.ColorKeyframeTrack = ColorKeyframeTrack2; + exports2.ColorManagement = ColorManagement2; + exports2.CompressedArrayTexture = CompressedArrayTexture2; + exports2.CompressedCubeTexture = CompressedCubeTexture2; + exports2.CompressedTexture = CompressedTexture2; + exports2.CompressedTextureLoader = CompressedTextureLoader2; + exports2.ConeGeometry = ConeGeometry2; + exports2.ConstantAlphaFactor = ConstantAlphaFactor2; + exports2.ConstantColorFactor = ConstantColorFactor2; + exports2.Controls = Controls2; + exports2.CubeCamera = CubeCamera2; + exports2.CubeReflectionMapping = CubeReflectionMapping2; + exports2.CubeRefractionMapping = CubeRefractionMapping2; + exports2.CubeTexture = CubeTexture2; + exports2.CubeTextureLoader = CubeTextureLoader2; + exports2.CubeUVReflectionMapping = CubeUVReflectionMapping2; + exports2.CubicBezierCurve = CubicBezierCurve2; + exports2.CubicBezierCurve3 = CubicBezierCurve32; + exports2.CubicInterpolant = CubicInterpolant2; + exports2.CullFaceBack = CullFaceBack2; + exports2.CullFaceFront = CullFaceFront2; + exports2.CullFaceFrontBack = CullFaceFrontBack2; + exports2.CullFaceNone = CullFaceNone2; + exports2.Curve = Curve2; + exports2.CurvePath = CurvePath2; + exports2.CustomBlending = CustomBlending2; + exports2.CustomToneMapping = CustomToneMapping2; + exports2.CylinderGeometry = CylinderGeometry2; + exports2.Cylindrical = Cylindrical2; + exports2.Data3DTexture = Data3DTexture2; + exports2.DataArrayTexture = DataArrayTexture2; + exports2.DataTexture = DataTexture2; + exports2.DataTextureLoader = DataTextureLoader2; + exports2.DataUtils = DataUtils2; + exports2.DecrementStencilOp = DecrementStencilOp2; + exports2.DecrementWrapStencilOp = DecrementWrapStencilOp2; + exports2.DefaultLoadingManager = DefaultLoadingManager2; + exports2.DepthFormat = DepthFormat2; + exports2.DepthStencilFormat = DepthStencilFormat2; + exports2.DepthTexture = DepthTexture2; + exports2.DetachedBindMode = DetachedBindMode2; + exports2.DirectionalLight = DirectionalLight2; + exports2.DirectionalLightHelper = DirectionalLightHelper2; + exports2.DiscreteInterpolant = DiscreteInterpolant2; + exports2.DodecahedronGeometry = DodecahedronGeometry2; + exports2.DoubleSide = DoubleSide2; + exports2.DstAlphaFactor = DstAlphaFactor2; + exports2.DstColorFactor = DstColorFactor2; + exports2.DynamicCopyUsage = DynamicCopyUsage2; + exports2.DynamicDrawUsage = DynamicDrawUsage2; + exports2.DynamicReadUsage = DynamicReadUsage2; + exports2.EdgesGeometry = EdgesGeometry2; + exports2.EllipseCurve = EllipseCurve2; + exports2.EqualCompare = EqualCompare2; + exports2.EqualDepth = EqualDepth2; + exports2.EqualStencilFunc = EqualStencilFunc2; + exports2.EquirectangularReflectionMapping = EquirectangularReflectionMapping2; + exports2.EquirectangularRefractionMapping = EquirectangularRefractionMapping2; + exports2.Euler = Euler2; + exports2.EventDispatcher = EventDispatcher2; + exports2.ExtrudeGeometry = ExtrudeGeometry2; + exports2.FileLoader = FileLoader2; + exports2.Float16BufferAttribute = Float16BufferAttribute2; + exports2.Float32BufferAttribute = Float32BufferAttribute2; + exports2.FloatType = FloatType2; + exports2.Fog = Fog2; + exports2.FogExp2 = FogExp22; + exports2.FramebufferTexture = FramebufferTexture2; + exports2.FrontSide = FrontSide2; + exports2.Frustum = Frustum2; + exports2.GLBufferAttribute = GLBufferAttribute2; + exports2.GLSL1 = GLSL12; + exports2.GLSL3 = GLSL32; + exports2.GreaterCompare = GreaterCompare2; + exports2.GreaterDepth = GreaterDepth2; + exports2.GreaterEqualCompare = GreaterEqualCompare2; + exports2.GreaterEqualDepth = GreaterEqualDepth2; + exports2.GreaterEqualStencilFunc = GreaterEqualStencilFunc2; + exports2.GreaterStencilFunc = GreaterStencilFunc2; + exports2.GridHelper = GridHelper2; + exports2.Group = Group2; + exports2.HalfFloatType = HalfFloatType2; + exports2.HemisphereLight = HemisphereLight2; + exports2.HemisphereLightHelper = HemisphereLightHelper2; + exports2.IcosahedronGeometry = IcosahedronGeometry2; + exports2.ImageBitmapLoader = ImageBitmapLoader2; + exports2.ImageLoader = ImageLoader2; + exports2.ImageUtils = ImageUtils2; + exports2.IncrementStencilOp = IncrementStencilOp2; + exports2.IncrementWrapStencilOp = IncrementWrapStencilOp2; + exports2.InstancedBufferAttribute = InstancedBufferAttribute2; + exports2.InstancedBufferGeometry = InstancedBufferGeometry2; + exports2.InstancedInterleavedBuffer = InstancedInterleavedBuffer2; + exports2.InstancedMesh = InstancedMesh2; + exports2.Int16BufferAttribute = Int16BufferAttribute2; + exports2.Int32BufferAttribute = Int32BufferAttribute2; + exports2.Int8BufferAttribute = Int8BufferAttribute2; + exports2.IntType = IntType2; + exports2.InterleavedBuffer = InterleavedBuffer2; + exports2.InterleavedBufferAttribute = InterleavedBufferAttribute2; + exports2.Interpolant = Interpolant2; + exports2.InterpolateDiscrete = InterpolateDiscrete2; + exports2.InterpolateLinear = InterpolateLinear2; + exports2.InterpolateSmooth = InterpolateSmooth2; + exports2.InvertStencilOp = InvertStencilOp2; + exports2.KeepStencilOp = KeepStencilOp2; + exports2.KeyframeTrack = KeyframeTrack2; + exports2.LOD = LOD2; + exports2.LatheGeometry = LatheGeometry2; + exports2.Layers = Layers2; + exports2.LessCompare = LessCompare2; + exports2.LessDepth = LessDepth2; + exports2.LessEqualCompare = LessEqualCompare2; + exports2.LessEqualDepth = LessEqualDepth2; + exports2.LessEqualStencilFunc = LessEqualStencilFunc2; + exports2.LessStencilFunc = LessStencilFunc2; + exports2.Light = Light2; + exports2.LightProbe = LightProbe2; + exports2.Line = Line4; + exports2.Line3 = Line32; + exports2.LineBasicMaterial = LineBasicMaterial2; + exports2.LineCurve = LineCurve2; + exports2.LineCurve3 = LineCurve32; + exports2.LineDashedMaterial = LineDashedMaterial2; + exports2.LineLoop = LineLoop2; + exports2.LineSegments = LineSegments3; + exports2.LinearFilter = LinearFilter2; + exports2.LinearInterpolant = LinearInterpolant2; + exports2.LinearMipMapLinearFilter = LinearMipMapLinearFilter2; + exports2.LinearMipMapNearestFilter = LinearMipMapNearestFilter2; + exports2.LinearMipmapLinearFilter = LinearMipmapLinearFilter2; + exports2.LinearMipmapNearestFilter = LinearMipmapNearestFilter2; + exports2.LinearSRGBColorSpace = LinearSRGBColorSpace2; + exports2.LinearToneMapping = LinearToneMapping2; + exports2.LinearTransfer = LinearTransfer2; + exports2.Loader = Loader2; + exports2.LoaderUtils = LoaderUtils2; + exports2.LoadingManager = LoadingManager2; + exports2.LoopOnce = LoopOnce2; + exports2.LoopPingPong = LoopPingPong2; + exports2.LoopRepeat = LoopRepeat2; + exports2.LuminanceAlphaFormat = LuminanceAlphaFormat2; + exports2.LuminanceFormat = LuminanceFormat2; + exports2.MOUSE = MOUSE2; + exports2.Material = Material2; + exports2.MaterialLoader = MaterialLoader2; + exports2.MathUtils = MathUtils2; + exports2.Matrix2 = Matrix22; + exports2.Matrix3 = Matrix32; + exports2.Matrix4 = Matrix42; + exports2.MaxEquation = MaxEquation2; + exports2.Mesh = Mesh2; + exports2.MeshBasicMaterial = MeshBasicMaterial2; + exports2.MeshDepthMaterial = MeshDepthMaterial2; + exports2.MeshDistanceMaterial = MeshDistanceMaterial2; + exports2.MeshLambertMaterial = MeshLambertMaterial2; + exports2.MeshMatcapMaterial = MeshMatcapMaterial2; + exports2.MeshNormalMaterial = MeshNormalMaterial2; + exports2.MeshPhongMaterial = MeshPhongMaterial2; + exports2.MeshPhysicalMaterial = MeshPhysicalMaterial2; + exports2.MeshStandardMaterial = MeshStandardMaterial2; + exports2.MeshToonMaterial = MeshToonMaterial2; + exports2.MinEquation = MinEquation2; + exports2.MirroredRepeatWrapping = MirroredRepeatWrapping2; + exports2.MixOperation = MixOperation2; + exports2.MultiplyBlending = MultiplyBlending2; + exports2.MultiplyOperation = MultiplyOperation2; + exports2.NearestFilter = NearestFilter2; + exports2.NearestMipMapLinearFilter = NearestMipMapLinearFilter2; + exports2.NearestMipMapNearestFilter = NearestMipMapNearestFilter2; + exports2.NearestMipmapLinearFilter = NearestMipmapLinearFilter2; + exports2.NearestMipmapNearestFilter = NearestMipmapNearestFilter2; + exports2.NeutralToneMapping = NeutralToneMapping2; + exports2.NeverCompare = NeverCompare2; + exports2.NeverDepth = NeverDepth2; + exports2.NeverStencilFunc = NeverStencilFunc2; + exports2.NoBlending = NoBlending2; + exports2.NoColorSpace = NoColorSpace2; + exports2.NoToneMapping = NoToneMapping2; + exports2.NormalAnimationBlendMode = NormalAnimationBlendMode2; + exports2.NormalBlending = NormalBlending2; + exports2.NotEqualCompare = NotEqualCompare2; + exports2.NotEqualDepth = NotEqualDepth2; + exports2.NotEqualStencilFunc = NotEqualStencilFunc2; + exports2.NumberKeyframeTrack = NumberKeyframeTrack2; + exports2.Object3D = Object3D2; + exports2.ObjectLoader = ObjectLoader2; + exports2.ObjectSpaceNormalMap = ObjectSpaceNormalMap2; + exports2.OctahedronGeometry = OctahedronGeometry2; + exports2.OneFactor = OneFactor2; + exports2.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor2; + exports2.OneMinusConstantColorFactor = OneMinusConstantColorFactor2; + exports2.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor2; + exports2.OneMinusDstColorFactor = OneMinusDstColorFactor2; + exports2.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor2; + exports2.OneMinusSrcColorFactor = OneMinusSrcColorFactor2; + exports2.OrthographicCamera = OrthographicCamera2; + exports2.PCFShadowMap = PCFShadowMap2; + exports2.PCFSoftShadowMap = PCFSoftShadowMap2; + exports2.PMREMGenerator = PMREMGenerator2; + exports2.Path = Path3; + exports2.PerspectiveCamera = PerspectiveCamera2; + exports2.Plane = Plane2; + exports2.PlaneGeometry = PlaneGeometry3; + exports2.PlaneHelper = PlaneHelper2; + exports2.PointLight = PointLight2; + exports2.PointLightHelper = PointLightHelper2; + exports2.Points = Points2; + exports2.PointsMaterial = PointsMaterial2; + exports2.PolarGridHelper = PolarGridHelper2; + exports2.PolyhedronGeometry = PolyhedronGeometry2; + exports2.PositionalAudio = PositionalAudio2; + exports2.PropertyBinding = PropertyBinding2; + exports2.PropertyMixer = PropertyMixer2; + exports2.QuadraticBezierCurve = QuadraticBezierCurve2; + exports2.QuadraticBezierCurve3 = QuadraticBezierCurve32; + exports2.Quaternion = Quaternion2; + exports2.QuaternionKeyframeTrack = QuaternionKeyframeTrack2; + exports2.QuaternionLinearInterpolant = QuaternionLinearInterpolant2; + exports2.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format2; + exports2.RED_RGTC1_Format = RED_RGTC1_Format2; + exports2.REVISION = REVISION2; + exports2.RGBADepthPacking = RGBADepthPacking2; + exports2.RGBAFormat = RGBAFormat2; + exports2.RGBAIntegerFormat = RGBAIntegerFormat2; + exports2.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format2; + exports2.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format2; + exports2.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format2; + exports2.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format2; + exports2.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format2; + exports2.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format2; + exports2.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format2; + exports2.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format2; + exports2.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format2; + exports2.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format2; + exports2.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format2; + exports2.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format2; + exports2.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format2; + exports2.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format2; + exports2.RGBA_BPTC_Format = RGBA_BPTC_Format2; + exports2.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format2; + exports2.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format2; + exports2.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format2; + exports2.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format2; + exports2.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format2; + exports2.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format2; + exports2.RGBDepthPacking = RGBDepthPacking2; + exports2.RGBFormat = RGBFormat2; + exports2.RGBIntegerFormat = RGBIntegerFormat2; + exports2.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format2; + exports2.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format2; + exports2.RGB_ETC1_Format = RGB_ETC1_Format2; + exports2.RGB_ETC2_Format = RGB_ETC2_Format2; + exports2.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format2; + exports2.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format2; + exports2.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format2; + exports2.RGDepthPacking = RGDepthPacking2; + exports2.RGFormat = RGFormat2; + exports2.RGIntegerFormat = RGIntegerFormat2; + exports2.RawShaderMaterial = RawShaderMaterial2; + exports2.Ray = Ray2; + exports2.Raycaster = Raycaster2; + exports2.RectAreaLight = RectAreaLight2; + exports2.RedFormat = RedFormat2; + exports2.RedIntegerFormat = RedIntegerFormat2; + exports2.ReinhardToneMapping = ReinhardToneMapping2; + exports2.RenderTarget = RenderTarget2; + exports2.RenderTarget3D = RenderTarget3D2; + exports2.RenderTargetArray = RenderTargetArray2; + exports2.RepeatWrapping = RepeatWrapping2; + exports2.ReplaceStencilOp = ReplaceStencilOp2; + exports2.ReverseSubtractEquation = ReverseSubtractEquation2; + exports2.RingGeometry = RingGeometry2; + exports2.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format2; + exports2.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format2; + exports2.SRGBColorSpace = SRGBColorSpace2; + exports2.SRGBTransfer = SRGBTransfer2; + exports2.Scene = Scene2; + exports2.ShaderChunk = ShaderChunk2; + exports2.ShaderLib = ShaderLib2; + exports2.ShaderMaterial = ShaderMaterial2; + exports2.ShadowMaterial = ShadowMaterial2; + exports2.Shape = Shape2; + exports2.ShapeGeometry = ShapeGeometry2; + exports2.ShapePath = ShapePath3; + exports2.ShapeUtils = ShapeUtils2; + exports2.ShortType = ShortType2; + exports2.Skeleton = Skeleton2; + exports2.SkeletonHelper = SkeletonHelper2; + exports2.SkinnedMesh = SkinnedMesh2; + exports2.Source = Source2; + exports2.Sphere = Sphere2; + exports2.SphereGeometry = SphereGeometry3; + exports2.Spherical = Spherical2; + exports2.SphericalHarmonics3 = SphericalHarmonics32; + exports2.SplineCurve = SplineCurve2; + exports2.SpotLight = SpotLight2; + exports2.SpotLightHelper = SpotLightHelper2; + exports2.Sprite = Sprite2; + exports2.SpriteMaterial = SpriteMaterial2; + exports2.SrcAlphaFactor = SrcAlphaFactor2; + exports2.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor2; + exports2.SrcColorFactor = SrcColorFactor2; + exports2.StaticCopyUsage = StaticCopyUsage2; + exports2.StaticDrawUsage = StaticDrawUsage2; + exports2.StaticReadUsage = StaticReadUsage2; + exports2.StereoCamera = StereoCamera2; + exports2.StreamCopyUsage = StreamCopyUsage2; + exports2.StreamDrawUsage = StreamDrawUsage2; + exports2.StreamReadUsage = StreamReadUsage2; + exports2.StringKeyframeTrack = StringKeyframeTrack2; + exports2.SubtractEquation = SubtractEquation2; + exports2.SubtractiveBlending = SubtractiveBlending2; + exports2.TOUCH = TOUCH2; + exports2.TangentSpaceNormalMap = TangentSpaceNormalMap2; + exports2.TetrahedronGeometry = TetrahedronGeometry2; + exports2.Texture = Texture2; + exports2.TextureLoader = TextureLoader2; + exports2.TextureUtils = TextureUtils2; + exports2.TimestampQuery = TimestampQuery2; + exports2.TorusGeometry = TorusGeometry2; + exports2.TorusKnotGeometry = TorusKnotGeometry3; + exports2.Triangle = Triangle2; + exports2.TriangleFanDrawMode = TriangleFanDrawMode2; + exports2.TriangleStripDrawMode = TriangleStripDrawMode2; + exports2.TrianglesDrawMode = TrianglesDrawMode2; + exports2.TubeGeometry = TubeGeometry3; + exports2.UVMapping = UVMapping2; + exports2.Uint16BufferAttribute = Uint16BufferAttribute2; + exports2.Uint32BufferAttribute = Uint32BufferAttribute2; + exports2.Uint8BufferAttribute = Uint8BufferAttribute2; + exports2.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute2; + exports2.Uniform = Uniform2; + exports2.UniformsGroup = UniformsGroup2; + exports2.UniformsLib = UniformsLib2; + exports2.UniformsUtils = UniformsUtils2; + exports2.UnsignedByteType = UnsignedByteType2; + exports2.UnsignedInt248Type = UnsignedInt248Type2; + exports2.UnsignedInt5999Type = UnsignedInt5999Type2; + exports2.UnsignedIntType = UnsignedIntType2; + exports2.UnsignedShort4444Type = UnsignedShort4444Type2; + exports2.UnsignedShort5551Type = UnsignedShort5551Type2; + exports2.UnsignedShortType = UnsignedShortType2; + exports2.VSMShadowMap = VSMShadowMap2; + exports2.Vector2 = Vector22; + exports2.Vector3 = Vector32; + exports2.Vector4 = Vector42; + exports2.VectorKeyframeTrack = VectorKeyframeTrack2; + exports2.VideoFrameTexture = VideoFrameTexture2; + exports2.VideoTexture = VideoTexture2; + exports2.WebGL3DRenderTarget = WebGL3DRenderTarget2; + exports2.WebGLArrayRenderTarget = WebGLArrayRenderTarget2; + exports2.WebGLCoordinateSystem = WebGLCoordinateSystem2; + exports2.WebGLCubeRenderTarget = WebGLCubeRenderTarget2; + exports2.WebGLRenderTarget = WebGLRenderTarget2; + exports2.WebGLRenderer = WebGLRenderer2; + exports2.WebGLUtils = WebGLUtils2; + exports2.WebGPUCoordinateSystem = WebGPUCoordinateSystem2; + exports2.WebXRController = WebXRController2; + exports2.WireframeGeometry = WireframeGeometry3; + exports2.WrapAroundEnding = WrapAroundEnding2; + exports2.ZeroCurvatureEnding = ZeroCurvatureEnding2; + exports2.ZeroFactor = ZeroFactor2; + exports2.ZeroSlopeEnding = ZeroSlopeEnding2; + exports2.ZeroStencilOp = ZeroStencilOp2; + exports2.createCanvasElement = createCanvasElement2; +}); + +// src/external/ffl.js/FFLShaderMaterial.js +var require_FFLShaderMaterial = __commonJS((exports2, module2) => { + (function(root2, factory) { + if (typeof define === "function" && define.amd) { + define(["three"], factory); + } else if (typeof module2 === "object" && module2.exports) { + module2.exports = factory(require_three()); + } else { + root2.FFLShaderMaterial = factory(root2.THREE); + } + })(typeof self !== "undefined" ? self : exports2, function(THREE2) { + const _FFLShader_vert = ` +// 頂点シェーダーに入力される attribute 変数 +//attribute vec4 position; //!< 入力: 位置情報 +//attribute vec2 uv; //!< 入力: テクスチャー座標 +//attribute vec3 normal; //!< 入力: 法線ベクトル +// All provided by three.js ^^ + +// vertex color is not actually the color of the shape, as such +// it is a custom attribute _COLOR in the glTF + +attribute vec4 _color; //!< 入力: 頂点の色 +attribute vec3 tangent; //!< 入力: 異方位 + +// フラグメントシェーダーへの入力 +varying vec4 v_color; //!< 出力: 頂点の色 +varying vec4 v_position; //!< 出力: 位置情報 +varying vec3 v_normal; //!< 出力: 法線ベクトル +varying vec3 v_tangent; //!< 出力: 異方位 +varying vec2 v_texCoord; //!< 出力: テクスチャー座標 + +// ユニフォーム +//uniform mat3 normalMatrix; //!< ユニフォーム: モデルの法線用行列 +//uniform mat4 modelViewMatrix; //!< ユニフォーム: プロジェクション行列 +//uniform mat4 projectionMatrix; //!< ユニフォーム: モデル行列 +// All provided by three.js ^^ + +// skinning_pars_vertex.glsl.js +#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif + +void main() +{ + + // begin_vertex.glsl.js + vec3 transformed = vec3( position ); +// skinbase_vertex.glsl.js +#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); + // skinning_vertex.glsl.js + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif + +//#ifdef FFL_COORDINATE_MODE_NORMAL + // 頂点座標を変換 + v_position = modelViewMatrix * vec4(transformed, 1.0); + gl_Position = projectionMatrix * v_position; + + vec3 objectNormal = normal; + vec3 objectTangent = tangent.xyz; +// skinnormal_vertex.glsl.js +#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + +#endif + + // 法線も変換 + //v_normal = mat3(inverse(u_mv)) * a_normal; + v_normal = normalize(normalMatrix * objectNormal); +//#elif defined(FFL_COORDINATE_MODE_NONE) +// // 頂点座標を変換 +// gl_Position = vec4(a_position.x, a_position.y * -1.0, a_position.z, a_position.w); +// v_position = a_position; +// +// v_normal = a_normal; +//#endif + + // その他の情報も書き出す + v_texCoord = uv; + // safe normalize + if (tangent != vec3(0.0, 0.0, 0.0)) + { + v_tangent = normalize(normalMatrix * objectTangent); + } + else + { + v_tangent = vec3(0.0, 0.0, 0.0); + } + + v_color = _color; +} +`; + const _FFLShader_frag = ` +// +// sample.flg +// Fragment shader +// Copyright (c) 2014 Nintendo Co., Ltd. All rights reserved. +// +// + +#ifdef GL_ES +precision mediump float; +#else +# define lowp +# define mediump +# define highp +#endif + + +// +// 定数定義ファイル +// + +/// シェーダーモード +#define FFL_SHADER_MODE_UR 0 +#define FFL_SHADER_MODE_UB 1 + +/// 変調処理のマクロ +#define FFL_MODULATE_MODE_CONSTANT 0 +#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 +#define FFL_MODULATE_MODE_RGB_LAYERED 2 +#define FFL_MODULATE_MODE_ALPHA 3 +#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 +#define FFL_MODULATE_MODE_ALPHA_OPA 5 + +/// スペキュラのモード +#define FFL_SPECULAR_MODE_BLINN 0 +#define FFL_SPECULAR_MODE_ANISO 1 + +/// ライトのON/OFF +#define FFL_LIGHT_MODE_DISABLE 0 +#define FFL_LIGHT_MODE_ENABLE 1 + +/// フラグメントのディスカードモード +#define FFL_DISCARD_FRAGMENT_DISABLE 0 +#define FFL_DISCARD_FRAGMENT_ENABLE 1 + +/// 座標変換モード +#define FFL_COORDINATE_MODE_NONE 0 +#define FFL_COORDINATE_MODE_NORMAL 1 + +// +// 関数の定義ファイル +// + +/** + * @brief 異方性反射の反射率を計算します。 + * @param[in] light ライトの向き + * @param[in] tangent 接線 + * @param[in] eye 視線の向き + * @param[in] power 鋭さ + */ +mediump float calculateAnisotropicSpecular(mediump vec3 light, mediump vec3 tangent, mediump vec3 eye, mediump float power ) +{ + mediump float dotLT = dot(light, tangent); + mediump float dotVT = dot(eye, tangent); + mediump float dotLN = sqrt(1.0 - dotLT * dotLT); + mediump float dotVR = dotLN*sqrt(1.0 - dotVT * dotVT) - dotLT * dotVT; + + return pow(max(0.0, dotVR), power); +} + +/** + * @brief 異方性反射の反射率を計算します。 + * @param[in] light ライトの向き + * @param[in] normal 法線 + * @param[in] eye 視線の向き + * @param[in] power 鋭さ + */ +mediump float calculateBlinnSpecular(mediump vec3 light, mediump vec3 normal, mediump vec3 eye, mediump float power) +{ + return pow(max(dot(reflect(-light, normal), eye), 0.0), power); +} + +/** + * @brief 異方性反射、ブリン反射をブレンドします。 + * @param[in] blend ブレンド率 + * @param[in] blinn ブリンの値 + * @param[in] aniso 異方性の値 + */ +mediump float calculateSpecularBlend(mediump float blend, mediump float blinn, mediump float aniso) +{ + return mix(aniso, blinn, blend); +} + +/** + * @brief アンビエントを計算します。 + * @param[in] light ライト + * @param[in] material マテリアル + */ +mediump vec3 calculateAmbientColor(mediump vec3 light, mediump vec3 material) +{ + return light * material; +} + +/** + * @brief 拡散を計算します。 + * @param[in] light ライト + * @param[in] material マテリアル + * @param[in] ln ライトと法線の内積 + */ +mediump vec3 calculateDiffuseColor(mediump vec3 light, mediump vec3 material, mediump float ln) +{ + return light * material * ln; +} + +/** + * @brief 鏡面反射を計算します。 + * @param[in] light ライト + * @param[in] material マテリアル + * @param[in] reflection 反射率 + * @param[in] strength 幅 + */ +mediump vec3 calculateSpecularColor(mediump vec3 light, mediump vec3 material, mediump float reflection, mediump float strength) +{ + return light * material * reflection * strength; +} + +/** + * @brief リムを計算します。 + * @param[in] color リム色 + * @param[in] normalZ 法線のZ方向 + * @param[in] width リム幅 + * @param[in] power リムの鋭さ + */ +mediump vec3 calculateRimColor(mediump vec3 color, mediump float normalZ, mediump float width, mediump float power) +{ + return color * pow(width * (1.0 - abs(normalZ)), power); +} + +/** + * @brief ライト方向と法線の内積を求める + * @note 特殊な実装になっています。 + */ +mediump float calculateDot(mediump vec3 light, mediump vec3 normal) +{ + return max(dot(light, normal), 0.1); +} + +// フラグメントシェーダーに入力される varying 変数 +varying mediump vec4 v_color; //!< 出力: 頂点の色 +varying highp vec4 v_position; //!< 出力: 位置情報 +varying highp vec3 v_normal; //!< 出力: 法線ベクトル +// NOTE: ^^ Those two need to be highp to avoid weird black dot issue on Android +varying mediump vec3 v_tangent; //!< 出力: 異方位 +varying mediump vec2 v_texCoord; //!< 出力: テクスチャー座標 + +/// constカラー +uniform mediump vec4 u_const1; ///< constカラー1 +uniform mediump vec4 u_const2; ///< constカラー2 +uniform mediump vec4 u_const3; ///< constカラー3 + +/// ライト設定 +uniform mediump vec3 u_light_ambient; ///< カメラ空間のライト方向 +uniform mediump vec3 u_light_diffuse; ///< 拡散光用ライト +uniform mediump vec3 u_light_dir; +uniform bool u_light_enable; +uniform mediump vec3 u_light_specular; ///< 鏡面反射用ライト強度 + +/// マテリアル設定 +uniform mediump vec3 u_material_ambient; ///< 環境光用マテリアル設定 +uniform mediump vec3 u_material_diffuse; ///< 拡散光用マテリアル設定 +uniform mediump vec3 u_material_specular; ///< 鏡面反射用マテリアル設定 +uniform int u_material_specular_mode; ///< スペキュラの反射モード(CharModelに依存する設定のためub_modulateにしている) +uniform mediump float u_material_specular_power; ///< スペキュラの鋭さ(0.0を指定すると頂点カラーの設定が利用される) + +/// 変調設定 +uniform int u_mode; ///< 描画モード + +/// リム設定 +uniform mediump vec3 u_rim_color; +uniform mediump float u_rim_power; + +// サンプラー +uniform sampler2D s_texture; + + +// ------------------------------------------------------- +// メイン文 +void main() +{ + mediump vec4 color; + + mediump float specularPower = u_material_specular_power; + mediump float rimWidth = v_color.a; + +//#ifdef FFL_MODULATE_MODE_CONSTANT + if(u_mode == FFL_MODULATE_MODE_CONSTANT) + { + color = u_const1; + } + // modified to handle u_const1 alpha: +//#elif defined(FFL_MODULATE_MODE_TEXTURE_DIRECT) + else if(u_mode == FFL_MODULATE_MODE_TEXTURE_DIRECT) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.rgb, u_const1.a * texel.a); + } +//#elif defined(FFL_MODULATE_MODE_RGB_LAYERED) + else if(u_mode == FFL_MODULATE_MODE_RGB_LAYERED) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.r * u_const1.rgb + texel.g * u_const2.rgb + texel.b * u_const3.rgb, u_const1.a * texel.a); + } +//#elif defined(FFL_MODULATE_MODE_ALPHA) + else if(u_mode == FFL_MODULATE_MODE_ALPHA) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(u_const1.rgb, u_const1.a * texel.r); + } +//#elif defined(FFL_MODULATE_MODE_LUMINANCE_ALPHA) + else if(u_mode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.g * u_const1.rgb, u_const1.a * texel.r); + } +//#elif defined(FFL_MODULATE_MODE_ALPHA_OPA) + else if(u_mode == FFL_MODULATE_MODE_ALPHA_OPA) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.r * u_const1.rgb, u_const1.a); + } +//#endif + + // avoids little outline around mask elements + if(u_mode != FFL_MODULATE_MODE_CONSTANT && color.a == 0.0) + { + discard; + } + +//#ifdef FFL_LIGHT_MODE_ENABLE + if(u_light_enable) + { + /// 環境光の計算 + mediump vec3 ambient = calculateAmbientColor(u_light_ambient.xyz, u_material_ambient.xyz); + + /// 法線ベクトルの正規化 + mediump vec3 norm = normalize(v_normal); + + /// 視線ベクトル + mediump vec3 eye = normalize(-v_position.xyz); + + // ライトの向き + mediump float fDot = calculateDot(u_light_dir, norm); + + /// Diffuse計算 + mediump vec3 diffuse = calculateDiffuseColor(u_light_diffuse.xyz, u_material_diffuse.xyz, fDot); + + /// Specular計算 + mediump float specularBlinn = calculateBlinnSpecular(u_light_dir, norm, eye, u_material_specular_power); + + /// Specularの値を確保する変数を宣言 + mediump float reflection; + mediump float strength = v_color.g; + if(u_material_specular_mode == 0) + { + /// Blinnモデルの場合 + strength = 1.0; + reflection = specularBlinn; + } + else + { + /// Aisoモデルの場合 + mediump float specularAniso = calculateAnisotropicSpecular(u_light_dir, v_tangent, eye, u_material_specular_power); + reflection = calculateSpecularBlend(v_color.r, specularBlinn, specularAniso); + } + /// Specularの色を取得 + mediump vec3 specular = calculateSpecularColor(u_light_specular.xyz, u_material_specular.xyz, reflection, strength); + + // リムの色を計算 + mediump vec3 rimColor = calculateRimColor(u_rim_color.rgb, norm.z, rimWidth, u_rim_power); + + // カラーの計算 + color.rgb = (ambient + diffuse) * color.rgb + specular + rimColor; + } +//#endif + + gl_FragColor = color; +} +`; + + class FFLShaderMaterial extends THREE2.ShaderMaterial { + static defaultLightAmbient = new THREE2.Color(0.73, 0.73, 0.73); + static defaultLightDiffuse = new THREE2.Color(0.6, 0.6, 0.6); + static defaultLightSpecular = new THREE2.Color(0.7, 0.7, 0.7); + static defaultLightDir = new THREE2.Vector3(-0.4531539381, 0.4226179123, 0.7848858833); + static defaultRimColor = new THREE2.Color(0.3, 0.3, 0.3); + static defaultRimPower = 2; + static defaultLightDirection = this.defaultLightDir; + static materialParams = [ + { + ambient: new THREE2.Color(0.85, 0.75, 0.75), + diffuse: new THREE2.Color(0.75, 0.75, 0.75), + specular: new THREE2.Color(0.3, 0.3, 0.3), + specularPower: 1.2, + specularMode: 0 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0, 0, 0), + specularPower: 40, + specularMode: 1 + }, + { + ambient: new THREE2.Color(0.9, 0.85, 0.85), + diffuse: new THREE2.Color(0.75, 0.75, 0.75), + specular: new THREE2.Color(0.22, 0.22, 0.22), + specularPower: 1.5, + specularMode: 0 + }, + { + ambient: new THREE2.Color(0.85, 0.75, 0.75), + diffuse: new THREE2.Color(0.75, 0.75, 0.75), + specular: new THREE2.Color(0.3, 0.3, 0.3), + specularPower: 1.2, + specularMode: 0 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0.35, 0.35, 0.35), + specularPower: 10, + specularMode: 1 + }, + { + ambient: new THREE2.Color(0.75, 0.75, 0.75), + diffuse: new THREE2.Color(0.72, 0.72, 0.72), + specular: new THREE2.Color(0.3, 0.3, 0.3), + specularPower: 1.5, + specularMode: 0 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0, 0, 0), + specularPower: 40, + specularMode: 1 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0, 0, 0), + specularPower: 40, + specularMode: 1 + }, + { + ambient: new THREE2.Color(1, 1, 1), + diffuse: new THREE2.Color(0.7, 0.7, 0.7), + specular: new THREE2.Color(0, 0, 0), + specularPower: 40, + specularMode: 1 + }, + { + ambient: new THREE2.Color(0.95622, 0.95622, 0.95622), + diffuse: new THREE2.Color(0.49673, 0.49673, 0.49673), + specular: new THREE2.Color(0.24099, 0.24099, 0.24099), + specularPower: 3, + specularMode: 0 + }, + { + ambient: new THREE2.Color(0.95622, 0.95622, 0.95622), + diffuse: new THREE2.Color(1.08497, 1.08497, 1.08497), + specular: new THREE2.Color(0.2409, 0.2409, 0.2409), + specularPower: 3, + specularMode: 0 + } + ]; + constructor(options = {}) { + const uniforms = { + u_light_ambient: { + value: FFLShaderMaterial.defaultLightAmbient + }, + u_light_diffuse: { + value: FFLShaderMaterial.defaultLightDiffuse + }, + u_light_specular: { + value: FFLShaderMaterial.defaultLightSpecular + }, + u_light_dir: { value: FFLShaderMaterial.defaultLightDir.clone() }, + u_light_enable: { value: true }, + u_rim_color: { value: FFLShaderMaterial.defaultRimColor }, + u_rim_power: { value: FFLShaderMaterial.defaultRimPower } + }; + super({ + vertexShader: _FFLShader_vert, + fragmentShader: _FFLShader_frag, + uniforms + }); + this._modulateType = 0; + this.useSpecularModeBlinn = false; + this.setValues(options); + } + get color() { + if (!this.uniforms.u_const1) { + return null; + } else if (this._color3) { + return this._color3; + } + const color4 = this.uniforms.u_const1.value; + const color3 = new THREE2.Color(color4.x, color4.y, color4.z); + this._color3 = color3; + return color3; + } + set color(value2) { + function toColor4(color, opacity2 = 1) { + return new THREE2.Vector4(color.r, color.g, color.b, opacity2); + } + if (Array.isArray(value2)) { + this.uniforms.u_const1 = { value: toColor4(value2[0]) }; + this.uniforms.u_const2 = { value: toColor4(value2[1]) }; + this.uniforms.u_const3 = { value: toColor4(value2[2]) }; + return; + } + const color3 = value2 ? value2 : new THREE2.Color(1, 1, 1); + this._color3 = color3; + const opacity = this.opacity; + if (this._opacity) { + delete this._opacity; + } + this.uniforms.u_const1 = { value: toColor4(color3, opacity) }; + } + get opacity() { + if (!this.uniforms.u_const1) { + return this._opacity ? this._opacity : 1; + } + return this.uniforms.u_const1.value.w; + } + set opacity(value2) { + if (!this.uniforms || !this.uniforms.u_const1) { + this._opacity = 1; + return; + } + this.uniforms.u_const1.value.w = value2; + } + get modulateMode() { + return this.uniforms.u_mode ? this.uniforms.u_mode.value : null; + } + set modulateMode(value2) { + this.uniforms.u_mode = { value: value2 }; + } + get lightEnable() { + return this.uniforms.u_light_enable ? this.uniforms.u_light_enable.value : null; + } + set lightEnable(value2) { + this.uniforms.u_light_enable = { value: value2 }; + } + set useSpecularModeBlinn(value2) { + this._useSpecularModeBlinn = value2; + if (this._modulateType !== undefined) { + this.modulateType = this._modulateType; + } + } + get useSpecularModeBlinn() { + return this._useSpecularModeBlinn; + } + get modulateType() { + return this._modulateType; + } + set modulateType(value2) { + const matParam = FFLShaderMaterial.materialParams[value2]; + if (!matParam) { + return; + } + this._modulateType = value2; + this.uniforms.u_material_ambient = { value: matParam.ambient }; + this.uniforms.u_material_diffuse = { value: matParam.diffuse }; + this.uniforms.u_material_specular = { value: matParam.specular }; + this.uniforms.u_material_specular_mode = { + value: this._useSpecularModeBlinn ? 0 : matParam.specularMode + }; + this.uniforms.u_material_specular_power = { value: matParam.specularPower }; + } + get map() { + return this.uniforms.s_texture ? this.uniforms.s_texture.value : null; + } + set map(value2) { + this.uniforms.s_texture = { value: value2 }; + } + get lightDirection() { + return this.uniforms.u_light_dir.value; + } + set lightDirection(value2) { + this.uniforms.u_light_dir = { value: value2 }; + } + } + return FFLShaderMaterial; + }); +}); + +// src/external/ffl.js/LUTShaderMaterial.js +var require_LUTShaderMaterial = __commonJS((exports2, module2) => { + (function(root2, factory) { + if (typeof define === "function" && define.amd) { + define(["three"], factory); + } else if (typeof module2 === "object" && module2.exports) { + module2.exports = factory(require_three()); + } else { + root2.LUTShaderMaterial = factory(root2.THREE); + } + })(typeof self !== "undefined" ? self : exports2, function(THREE2) { + const _LUTShader_vert = ` +#define AGX_FEATURE_ALBEDO_TEXTURE +/** + * @file LUT.vsh + * @brief LUT + * @since 2014/10/02 + * + * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. + */ + +// シェーダーの種類毎に設定されるマクロリスト +// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 +// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 +// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 +// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 +// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 +// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 +// AGX_FEATURE_SKIN_MASK 肌マスクが有効(uColor0) +// AGX_FEATURE_HAIR_MASK 髪マスクが有効(uColor1) +// AGX_FEATURE_ALPHA_TEST アルファテストが有効 +// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(uColor2) +// AGX_FEATURE_DISABLE_LIGHT ライトが無効 +// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 +// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 +// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 +// AGX_FEATURE_MII Miiを描画する +// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant +// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct +// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered +// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha +// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha +// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa +// +// AGX_BONE_MAX ボーンの最大数 + +#ifdef GL_ES +precision highp float; +#else +# define lowp +# define mediump +# define highp +#endif + +//#ifndef AGX_BONE_MAX +//# define AGX_BONE_MAX 15 +//#endif +#ifndef AGX_DIR_LIGHT_MAX +# define AGX_DIR_LIGHT_MAX 2 +#endif + +// ---------------------------------------- +// 頂点シェーダーに入力される attribute 変数 +//attribute highp vec3 position; //!< 入力:[ 1 : 1 ] 位置情報 +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) +//attribute mediump vec2 uv; //!< 入力:[ 1 : 5 ] テクスチャー座標 +#endif +//attribute mediump vec3 normal; //!< 入力:[ 1 : 2 ] 法線ベクトル +//attribute mediump vec4 aBoneIndex; //!< 入力:[ 1 : 3 ] ボーンのインデックス(最大4つ) +//attribute mediump vec4 aBoneWeight; //!< 入力:[ 1 : 4 ] ボーンの影響度(最大4つ) +#if defined(AGX_FEATURE_VERTEX_COLOR) +//attribute lowp vec4 _color; //!< 入力:[ 1 : 6 ] 頂点カラー +#endif +#if defined(AGX_FEATURE_BUMP_TEXTURE) +//attribute mediump vec3 tangent; //!< 入力:[ 1 : 7 ] 接線ベクトル +#endif + +// ^^ Commented attributes are provided by three.js. + +// ---------------------------------------- +// 頂点シェーダーに入力される uniform 変数 +//uniform highp mat4 modelViewMatrix; //!< 入力:[ 4 / 4 : 4 ] モデルの合成行列 +//uniform mat4 projectionMatrix; +//uniform highp mat4 viewMatrix; //!< 入力:[ 4 / 4 : 8 ] モデルのビュー行列 +//uniform mediump mat3 normalMatrix; //!< 入力:[ 3 / 3 : 11 ] モデルの法線用行列 +//uniform highp mat4 modelMatrix; //!< 入力:[ 4 / 4 : 15 ] モデルのワールド変換行列 +//uniform lowp int uBoneCount; //!< 入力:[ 1 / 1 : 16 ] ボーンの個数 +//uniform highp mat4 uBoneMatrices[AGX_BONE_MAX]; //!< 入力:[ 4 x 15 / 60 : 76 ] ボーンの行列配列 +//uniform mediump mat3 uBoneNormalMatrices[AGX_BONE_MAX]; //!< 入力:[ 3 x 15 / 45 : 121 ] ボーンの法線行列配列 +// ^^ Unused in favor of three.js skinning. +uniform lowp int uDirLightCount; //!< 入力:[ 1 / 1 : 122 ] 方向ライトの数 +uniform mediump vec4 uDirLightDirAndType0;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 +uniform mediump vec4 uDirLightDirAndType1;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 +uniform mediump vec3 uDirLightColor0; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー +uniform mediump vec3 uDirLightColor1; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー +uniform mediump vec3 uHSLightSkyColor; //!< 入力:[ 1 / 1 : 127 ] 半球ライトのスカイカラー +uniform mediump vec3 uHSLightGroundColor; //!< 入力:[ 1 / 1 : 128 ] 半球ライトのグラウンドカラー +//uniform mediump vec3 cameraPosition; //!< 入力:[ 1 / 1 : 129 ] カメラの位置 +// ^^ previously uEyePt +uniform mediump float uAlpha; //!< 入力:[ 1 / 1 : 130 ] アルファ値 + +// ^^ Commented uniforms are provided by three.js. + +// ---------------------------------------- +// フラグメントシェーダーに渡される varying 変数 +varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 +#if !defined(AGX_FEATURE_BUMP_TEXTURE) +varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 +#endif +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) +varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV +#endif +// camera +varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル +#if !defined(AGX_FEATURE_DISABLE_LIGHT) +// punctual light +varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 +varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル +// GI +varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー +// Lighting Result +varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 +#endif +// Reflect +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) +varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル +#endif + +// skinning_pars_vertex.glsl.js +#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif + +// ------------------------------------------------------------ +// 頂点シェーダーのエントリーポイント +// ------------------------------------------------------------ +void main() +{ + // ------------------------------------------------------------ + // 頂点変換用の処理 + // ------------------------------------------------------------ + highp vec4 position_; //!< 最終的な頂点 + mediump vec3 normal_; //!< 最終的な法線 + mediump vec3 tangent_; //!< 最終的な接線 + highp vec4 positionWorld; //!< ワールド空間上での頂点 + + + // begin_vertex.glsl.js + vec3 transformed = vec3( position ); +// skinbase_vertex.glsl.js +#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); + // skinning_vertex.glsl.js + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif + + // ---------------------------------------- + // ボーンが存在しない場合は位置と法線に手を加えない + position_ = vec4(transformed.xyz, 1.0); + + + + normal_ = normal; +#if defined(AGX_FEATURE_BUMP_TEXTURE) + tangent_ = tangent.xyz; +#endif + // skinnormal_vertex.glsl.js +#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + + normal_ = vec4( skinMatrix * vec4( normal_, 0.0 ) ).xyz; +#if defined(AGX_FEATURE_BUMP_TEXTURE) + tangent_ = vec4( skinMatrix * vec4( tangent_, 0.0 ) ).xyz; +#endif // defined(AGX_FEATURE_BUMP_TEXTURE) +#endif // USE_SKINNING + + // ---------------------------------------- + // ワールド上での位置を求める + positionWorld = modelMatrix * position_; + // 最終結果を行う + position_ = projectionMatrix * modelViewMatrix * position_; + normal_ = normalize(normalMatrix * normal_); +#if defined(AGX_FEATURE_BUMP_TEXTURE) + tangent = normalize(normalMatrix * tangent_); +#endif + + // ---------------------------------------- + // 計算結果を保持させる + gl_Position = position_; +#if !defined(AGX_FEATURE_BUMP_TEXTURE) + vNormal = normal_; +#endif +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) + // テクスチャー座標を設定する + vTexcoord0 = uv; +#endif + // モデルの色を指定する +#if defined(AGX_FEATURE_VERTEX_COLOR) + lowp vec4 modelColor = aColor; + +#else + lowp vec4 modelColor = vec4(1.0, 1.0, 1.0, 1.0); +#endif + + // プリマルチプライドアルファ +#if defined(AGX_FEATURE_PREMULTIPLY_ALPHA) + modelColor *= uAlpha; +#else + modelColor.a *= uAlpha; +#endif + + + // ------------------------------------------------------------ + // ライト用の処理 + // ------------------------------------------------------------ + mediump vec3 eyeVecWorld; //!< ワールド状態での視線ベクトル + mediump vec3 eyeVec; //!< 最終的にフラグメントシェーダーに渡す視線ベクトル(バンプの有無によって、ワールド座標系になったり、タンジェント座標系になったりする) + + vec4 eye = modelViewMatrix * position_; + + // 視線ベクトルを取得する + //eyeVecWorld = normalize(cameraPosition - positionWorld.xyz); + eyeVecWorld = normalize(-(eye.xyz) - positionWorld.xyz);//normalize(cameraPosition - positionWorld.xyz); + eyeVec = eyeVecWorld; + + lowp vec3 diffuseColor = vec3(0.0); // バーテックスシェーダーで計算できるディフューズの色をここに格納する + +# if defined(AGX_FEATURE_BUMP_TEXTURE) + // Normal, Binormal, Tangent を取得する + mediump vec3 n = normal; + mediump vec3 t = tangent; + mediump vec3 b = cross(n, t); + // 接空間からローカルへ変換する行列を設定する(mat3(N, T, B)の逆行列) + mediump mat3 tangentMatrix = mat3(t.x, b.x, n.x, t.y, b.y, n.y, t.z, b.z, n.z); + // 視線ベクトルを接空間へ + vEyeVecWorldOrTangent.xyz = tangentMatrix * eyeVec; +#else + vEyeVecWorldOrTangent.xyz = eyeVec; +#endif + +#if !defined(AGX_FEATURE_DISABLE_LIGHT) + // punctual lightの設定 + if (uDirLightCount > 0) + { + mediump vec3 lightDir; + + // 方向ライト + if (uDirLightDirAndType0.w < 0.0) { lightDir = uDirLightDirAndType0.xyz; } + // 点光源ライト + else { lightDir = uDirLightDirAndType0.xyz - positionWorld.xyz; } + lightDir = normalize(lightDir); + +# if defined(AGX_FEATURE_BUMP_TEXTURE) + // ライトを接空間へ + vPunctualLightDirWorldOrTangent.xyz = tangentMatrix * lightDir; +# else + vPunctualLightDirWorldOrTangent.xyz = lightDir; +# endif + + // Halfベクトルを求める + vPunctualLightHalfVecWorldOrTangent.xyz = normalize(vPunctualLightDirWorldOrTangent.xyz + vEyeVecWorldOrTangent.xyz); + + // Diffuse計算 + diffuseColor += (uDirLightColor0.rgb * clamp(dot(lightDir, normal_), 0.0, 1.0)); + } + if (uDirLightCount > 1) + { + mediump vec3 lightDir; + + // 方向ライト + if (uDirLightDirAndType1.w < 0.0) { lightDir = uDirLightDirAndType1.xyz; } + // 点光源ライト + else { lightDir = uDirLightDirAndType1.xyz - positionWorld.xyz; } + lightDir = normalize(lightDir); + + diffuseColor += max(dot(lightDir, normal_), 0.0) * uDirLightColor1; + } + // ライトは1.0を超えないように + diffuseColor = min(diffuseColor, 1.0); +#endif + +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) + { + // キューブ環境マップ用の反射ベクトルを求める +// vReflectDir = reflect(normalize(positionWorld.xyz - cameraPosition), normal_); + + // スフィア環境マップ用の反射ベクトルを求める +// vReflectDir = normalize((uViewMatrix * vec4(normal_, 0.0)).xyz) * 0.5 + 0.5; + + // ビュー座標系での位置と法線を取得 + mediump vec3 viewNormal = normalize(mat3(uViewMatrix) * normal_); + mediump vec4 viewPosition = uViewMatrix * positionWorld; + viewPosition = viewPosition / viewPosition.w; + // ビュー座標系での頂点ベクトルを取得 + viewPosition.z = 1.0 - viewPosition.z; + mediump vec3 viewPositionVec = normalize(viewPosition.xyz); + // ビュー座標系での反射ベクトルを求める + mediump vec3 viewReflect = viewPositionVec - 2.0 * dot(viewPositionVec, viewNormal) * viewNormal; + // 両面スフィア環境マップではないので、反射ベクトルを調整 + viewReflect = normalize(viewReflect - vec3(0.0, 0.0, 1.5)); + // 反射ベクトルをテクスチャー座標系へ + vReflectDir = viewReflect * 0.5 + 0.5; + + // 公式 +// mediump vec3 viewPositionVec = normalize(vec3(uViewMatrix * positionWorld)); +// mediump vec3 viewReflectVec = viewPositionVec - 2.0 * dot(viewPositionVec, normal_) * normal; +// mediump float m = 2.0 * sqrt(viewReflectVec.x * viewReflectVec.x + +// viewReflectVec.y * viewReflectVec.y + +// (viewReflectVec.z + 1.0) * (viewReflectVec.z * 1.0)); +// vReflectDir = viewReflectVec / m + 0.5; + + // 別版 +// mediump vec3 posW = positionWorld.xyz; +// mediump vec3 dir = normalize(mat3(uViewMatrix) * normal); +// +// mediump float radius = 75.0; +// mediump vec3 posWDir = dot(dir, posW) * dir; +// mediump vec3 posWDirV = posW - posWDir; +// mediump float lengthDir = sqrt(radius * radius - dot(posWDirV, posWDirV)) - length(posWDir); +// vReflectDir = normalize(posW + dir * lengthDir) * 0.5 + 0.5; + } +#endif + +#if !defined(AGX_FEATURE_DISABLE_LIGHT) + // GIの計算 + { + mediump vec3 hemiColor; + mediump vec3 sky = uHSLightSkyColor; + mediump vec3 ground = uHSLightGroundColor; + + { + mediump float skyRatio = (normal_.y + 1.0) * 0.5; + hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); + diffuseColor += hemiColor; + } + + { +// mediump vec3 reflectDir = -reflect(normal_, eyeVecWorld); // おそらくコレで良いはず + mediump vec3 reflectDir = 2.0 * dot(eyeVecWorld, normal_) * normal_ - eyeVecWorld; // 多少冗長でも、正しい計算で行なう + + mediump float skyRatio = (reflectDir.y + 1.0) * 0.5; + hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); + vGISpecularLightColor.rgb = hemiColor; + } + } +#endif + + // モデルの色を設定 + vModelColor = modelColor; +#if !defined(AGX_FEATURE_DISABLE_LIGHT) + vDiffuseColor.rgb = diffuseColor; +#endif +} +`; + const _LUTShader_frag = ` +#define AGX_FEATURE_ALBEDO_TEXTURE +#define AGX_FEATURE_MII +/** + * @file LUT.fsh + * @brief LUT + * @since 2014/10/02 + * + * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. + */ + +// シェーダーの種類毎に設定されるマクロリスト +// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 +// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 +// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 +// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 +// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 +// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 +// AGX_FEATURE_SKIN_MASK 肌マスクが有効(uColor0) +// AGX_FEATURE_HAIR_MASK 髪マスクが有効(uColor1) +// AGX_FEATURE_ALPHA_TEST アルファテストが有効 +// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(uColor2) +// AGX_FEATURE_DISABLE_LIGHT ライトが無効 +// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 +// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 +// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 +// AGX_FEATURE_MII Miiを描画する +// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant +// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct +// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered +// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha +// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha +// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa + +#ifdef GL_ES +precision mediump float; +#else +# define lowp +# define mediump +# define highp +#endif + +/// 変調処理のマクロ +#define FFL_MODULATE_MODE_CONSTANT 0 +#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 +#define FFL_MODULATE_MODE_RGB_LAYERED 2 +#define FFL_MODULATE_MODE_ALPHA 3 +#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 +#define FFL_MODULATE_MODE_ALPHA_OPA 5 + +// ---------------------------------------- +// フラグメントシェーダーに入力される uniform 変数 +uniform int uMode; ///< 描画モード +uniform bool uAlphaTest; +uniform bool uLightEnable; +uniform mediump vec4 uColor0; //!< 入力:[ 1 : 1 ] カラー0 (OR 肌カラー) +uniform mediump vec4 uColor1; //!< 入力:[ 1 : 2 ] カラー1 (OR 髪カラー) +uniform mediump vec4 uColor2; //!< 入力:[ 1 : 3 ] カラー2 (OR フェードアウトカラー) +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +uniform mediump vec3 uLightColor; //!< 入力:[ 1 : 4 ] ライトの色 +//#endif + +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) +uniform sampler2D uAlbedoTexture; //!< 入力: テクスチャー +#endif +#if defined(AGX_FEATURE_BUMP_TEXTURE) +uniform sampler2D uNormalTexture; //!< 入力: ノーマルマップ +#endif +#if defined(AGX_FEATURE_MASK_TEXTURE) +uniform sampler2D uMaskTexture; //!< 入力:マスクテクスチャー +#endif +#if defined(AGX_FEATURE_ALPHA_TEXTURE) +uniform sampler2D uAlphaTexture; //!< 入力:アルファテクスチャー +#endif +uniform sampler2D uLUTSpecTexture; //!< 入力: スペキュラーLUT +uniform sampler2D uLUTFresTexture; //!< 入力: フレネルLUT +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) +uniform sampler2D uSphereMapTexture; //!< 入力: スフィア環境マップ +#endif + +// ---------------------------------------- +// フラグメントシェーダーに渡される varying 変数 +varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 +#if !defined(AGX_FEATURE_BUMP_TEXTURE) +varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 +#endif +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) +varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV +#endif +// camera +varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +// punctual light +varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 +varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル +// GI +varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー +// Lighting Result +varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 +//#endif +// Reflect +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) +varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル +#endif + +// ------------------------------------------------------------ +// フラグメントシェーダーのエントリーポイント +// ------------------------------------------------------------ +void main() +{ + + // ディフューズカラーを取得 + lowp vec4 albedoColor = vec4(1.0, 1.0, 1.0, 1.0); + + // ============================================================ + // Mii + // ============================================================ +#if defined(AGX_FEATURE_MII) + + //#if defined(AGX_FEATURE_MII_CONSTANT) + if(uMode == FFL_MODULATE_MODE_CONSTANT) + { + albedoColor = uColor0; + } + //#elif defined(AGX_FEATURE_MII_TEXTURE_DIRECT) + else if(uMode == FFL_MODULATE_MODE_TEXTURE_DIRECT) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + } + //#elif defined(AGX_FEATURE_MII_RGB_LAYERED) + else if(uMode == FFL_MODULATE_MODE_RGB_LAYERED) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(albedoColor.r * uColor0.rgb + albedoColor.g * uColor1.rgb + albedoColor.b * uColor2.rgb, + uColor0.a * albedoColor.a); + } + //#elif defined(AGX_FEATURE_MII_ALPHA) + else if(uMode == FFL_MODULATE_MODE_ALPHA) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(uColor0.rgb, uColor0.a * albedoColor.r); + } + //#elif defined(AGX_FEATURE_MII_LUMINANCE_ALPHA) + else if(uMode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(albedoColor.g * uColor0.rgb, uColor0.a * albedoColor.r); + } + //#elif defined(AGX_FEATURE_MII_ALPHA_OPA) + else if(uMode == FFL_MODULATE_MODE_ALPHA_OPA) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(albedoColor.r * uColor0.rgb, uColor0.a); + } +//#endif + + albedoColor = albedoColor * vModelColor; +#endif + + // ============================================================ + // Albedo Texture + // ============================================================ +#if !defined(AGX_FEATURE_MII) && defined(AGX_FEATURE_ALBEDO_TEXTURE) + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); +#endif +#if defined(AGX_FEATURE_ALPHA_TEXTURE) + albedoColor.a = texture2D(uAlphaTexture, vTexcoord0).r; +#endif + + // ============================================================ + // Color Mask + // ============================================================ + // ---------------------------------------- + // Deprecated +#if defined(AGX_FEATURE_ALPHA_COLOR_FILTER) + // 一部の場所にColor0を反映する + albedoColor.rgb = (albedoColor.rgb * albedoColor.a + uColor0.rgb * (1.0 - albedoColor.a)); + albedoColor.a = 1.0; +#elif defined(AGX_FEATURE_MASK_TEXTURE) + lowp vec3 maskTextureColor = texture2D(uMaskTexture, vTexcoord0).rgb; + +# if defined(AGX_FEATURE_SKIN_MASK) && defined(AGX_FEATURE_HAIR_MASK) + // 肌と髪両方マスクが存在する + lowp float maskColorValue = maskTextureColor.g + maskTextureColor.b; + lowp vec3 maskColor = maskTextureColor.g * uColor0.rgb + maskTextureColor.b * uColor1.rgb; + albedoColor.rgb = (albedoColor.rgb * (1.0 - maskColorValue) + maskColor); + +# elif defined(AGX_FEATURE_SKIN_MASK) + // 肌しかマスクが存在しない + albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.g) + maskTextureColor.g * uColor0.rgb); + +# elif defined(AGX_FEATURE_HAIR_MASK) + // 髪しかマスクが存在しない + albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.b) + maskTextureColor.b * uColor1.rgb); + +# endif +#endif + + // アルベドに頂点カラーを掛ける + albedoColor *= vModelColor; + + // ============================================================ + // Alpha test + // ============================================================ +//#if defined(AGX_FEATURE_ALPHA_TEST) + if (uAlphaTest && albedoColor.a < 0.5) { discard; } +//#endif + + // ============================================================ + // Bumpmap + // ============================================================ + // 頂点からの情報 + lowp vec3 normalWorldOrTangent; +#if defined(AGX_FEATURE_BUMP_TEXTURE) + // バンプマップから法線を取得する + mediump vec3 bumpNormal = texture2D(uNormalTexture, vTexcoord0).rgb; + + // 法線の正規化は処理が重いのでいったん正規化しない様に... +// normalWorldOrTangent = normalize(bumpNormal * 2.0 - 1.0); + normalWorldOrTangent = bumpNormal * 2.0 - 1.0; + +#else + // 法線を正規化して取得する + normalWorldOrTangent = normalize(vNormal); +#endif + + // ============================================================ + // Lighting + // ============================================================ + // 最終的なカラー情報 + lowp vec4 colorOut = vec4(0.0, 0.0, 0.0, albedoColor.a); // 最終的に出力される色 + lowp vec3 fresnel = vec3(0.0, 0.0, 0.0); // フレネル + lowp vec3 specular = vec3(0.0, 0.0, 0.0); // スペキュラー + +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +if (uLightEnable) { + + // BRDFの計算を行う(バンプマッピングの場合は接空間) + lowp vec3 N = normalWorldOrTangent; + lowp vec3 V = vEyeVecWorldOrTangent.xyz;//normalize(vEyeVecWorldOrTangent.xyz); + lowp vec3 I = vPunctualLightDirWorldOrTangent.xyz;//normalize(vPunctualLightDirWorldOrTangent.xyz); + lowp vec3 H = vPunctualLightHalfVecWorldOrTangent.xyz;//normalize(vPunctualLightHalfVecWorldOrTangent.xyz); + + + // ---------------------------------------- + // punctual light + // 平行光源や点光源などの厳密なライティング計算を行なうもの + { + lowp float fSpecular = dot(N, H); + + lowp float specularIntensity = texture2D(uLUTSpecTexture, vec2(fSpecular)).r; + specular = (specularIntensity * uLightColor.rgb); + } + + // ---------------------------------------- + // GI + // 半球ライトやIBL、SHのように法線方向に半球積分された結果でライティング計算を行なうもの + { + lowp float fFresnel = dot(N, V); + lowp float fresnelIntensity = texture2D(uLUTFresTexture, vec2(fFresnel)).r; + + fresnel = (fresnelIntensity * vGISpecularLightColor.rgb); + } +} +//#endif + +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) + // スフィア環境マップ + specular += texture2D(uSphereMapTexture, vReflectDir.xy).rgb; +#endif + + // ============================================================ + // Specular Mask + // ============================================================ +#if !defined(AGX_FEATURE_ALPHA_COLOR_FILTER) && defined(AGX_FEATURE_MASK_TEXTURE) + // スペキュラーマスク + specular = specular * maskTextureColor.r + fresnel; +#else + specular += fresnel; +#endif + + // ============================================================ + // Output + // ============================================================ +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +if (uLightEnable) + colorOut.rgb = vDiffuseColor.rgb * albedoColor.rgb + specular; +//#else +else + colorOut.rgb = albedoColor.rgb; +//#endif + + // フェードアウトを実装する +#if defined(AGX_FEATURE_FADE_OUT_COLOR) + colorOut.rgb = (colorOut.rgb * (1.0 - uColor2.a)) + (uColor2.rgb * uColor2.a); +#endif + + // 色を反映させる + gl_FragColor = colorOut; + + //#include + //#include +} +`; + + class HermitianCurve { + constructor(keys2) { + this.keys = keys2.sort((a2, b2) => a2.x - b2.x); + } + interpolate(t3, p0, p1, m0, m1) { + const h00 = 2 * t3 * t3 * t3 - 3 * t3 * t3 + 1; + const h10 = t3 * t3 * t3 - 2 * t3 * t3 + t3; + const h01 = -2 * t3 * t3 * t3 + 3 * t3 * t3; + const h11 = t3 * t3 * t3 - t3 * t3; + return h00 * p0 + h10 * m0 + h01 * p1 + h11 * m1; + } + clamp(value2, min, max) { + return Math.min(Math.max(value2, min), max); + } + generateLUT(lutSize = 512) { + const lut = new Uint8Array(lutSize); + let keyIdx = 0; + for (let i = 0;i < lutSize; i++) { + const pos = i / (lutSize - 1); + while (keyIdx < this.keys.length - 2 && pos > this.keys[keyIdx + 1].x) { + keyIdx++; + } + const p0 = this.keys[keyIdx]; + const p1 = this.keys[keyIdx + 1]; + let t3 = (pos - p0.x) / (p1.x - p0.x); + t3 = isNaN(t3) ? 0 : t3; + const y = this.interpolate(t3, p0.y, p1.y, p0.dx * (p1.x - p0.x), p1.dx * (p1.x - p0.x)); + lut[i] = Math.round(this.clamp(y, 0, 1) * 255); + } + return lut; + } + } + + class LUTShaderMaterial extends THREE2.ShaderMaterial { + static LUTSpecularTextureType = { + NONE: 0, + DEFAULT_02: 1, + SKIN_01: 2, + MAX: 3 + }; + static LUTFresnelTextureType = { + NONE: 0, + DEFAULT_02: 1, + SKIN_01: 2, + MAX: 3 + }; + static lutDefinitions = { + specular: { + [LUTShaderMaterial.LUTSpecularTextureType.NONE]: new HermitianCurve([ + { x: 0, y: 0, dx: 0, dy: 0 }, + { x: 1, y: 0, dx: 0, dy: 0 } + ]), + [LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02]: new HermitianCurve([ + { x: 0, y: 0, dx: 0, dy: 0 }, + { x: 0.05, y: 0, dx: 0, dy: 0 }, + { + x: 0.8, + y: 0.038, + dx: 0.157894736842105, + dy: 0.157894736842105 + }, + { x: 1, y: 0.11, dx: 0, dy: 0 } + ]), + [LUTShaderMaterial.LUTSpecularTextureType.SKIN_01]: new HermitianCurve([ + { + x: 0, + y: 0.03, + dx: -0.105263157894737, + dy: -0.105263157894737 + }, + { x: 1, y: 0, dx: 0, dy: 0 } + ]) + }, + fresnel: { + [LUTShaderMaterial.LUTFresnelTextureType.NONE]: new HermitianCurve([ + { x: 0, y: 0, dx: 0, dy: 0 }, + { x: 1, y: 0, dx: 0, dy: 0 } + ]), + [LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02]: new HermitianCurve([ + { + x: 0, + y: 0.3, + dx: -0.105263157894734, + dy: -0.105263157894734 + }, + { + x: 0.175, + y: 0.23, + dx: -0.626315789473681, + dy: -0.626315789473681 + }, + { + x: 0.6, + y: 0.05, + dx: -0.210526315789474, + dy: -0.210526315789474 + }, + { + x: 1, + y: 0, + dx: -0.105263157894737, + dy: -0.105263157894737 + } + ]), + [LUTShaderMaterial.LUTFresnelTextureType.SKIN_01]: new HermitianCurve([ + { + x: 0.005, + y: 0.35, + dx: -0.105263157894734, + dy: -0.105263157894734 + }, + { + x: 0.173, + y: 0.319, + dx: -0.205263157894734, + dy: -0.205263157894734 + }, + { + x: 0.552, + y: 0.051, + dx: -0.210526315789474, + dy: -0.210526315789474 + }, + { x: 1, y: 0.001, dx: 0, dy: 0 } + ]) + } + }; + static modulateTypeToLUTSpecular = [ + LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, + LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.NONE, + LUTShaderMaterial.LUTSpecularTextureType.NONE, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02 + ]; + static modulateTypeToLUTFresnel = [ + LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, + LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.NONE, + LUTShaderMaterial.LUTFresnelTextureType.NONE, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02 + ]; + static _lutTextures = null; + static getLUTTextures(lutSize = 512) { + if (LUTShaderMaterial._lutTextures) { + return LUTShaderMaterial._lutTextures; + } + const textures = { specular: {}, fresnel: {} }; + const r8 = Number(THREE2.REVISION) <= 136 ? THREE2.LuminanceFormat : THREE2.RedFormat; + function generateLUTTextures(lutType, target) { + for (const key2 in lutType) { + const lutData = lutType[key2].generateLUT(lutSize); + target[Number(key2)] = Object.assign(new THREE2.DataTexture(lutData, lutSize, 1, r8, THREE2.UnsignedByteType), { + colorSpace: THREE2.LinearSRGBColorSpace, + needsUpdate: true + }); + } + } + generateLUTTextures(LUTShaderMaterial.lutDefinitions.specular, textures.specular); + generateLUTTextures(LUTShaderMaterial.lutDefinitions.fresnel, textures.fresnel); + LUTShaderMaterial._lutTextures = textures; + return textures; + } + static defaultHSLightGroundColor = new THREE2.Color(0.87843, 0.72157, 0.5898); + static defaultHSLightSkyColor = new THREE2.Color(0.87843, 0.83451, 0.80314); + static defaultDirLightColor0 = new THREE2.Color(0.35137, 0.32392, 0.32392); + static defaultDirLightColor1 = new THREE2.Color(0.10039, 0.09255, 0.09255); + static defaultDirLightCount = 2; + static defaultDirLightDirAndType0 = new THREE2.Vector4(-0.2, 0.5, 0.8, -1); + static defaultDirLightDirAndType1 = new THREE2.Vector4(0, -0.19612, 0.98058, -1); + static defaultLightColor = new THREE2.Color(0.35137, 0.32392, 0.32392); + static defaultLightDirection = this.defaultDirLightDirAndType0; + static multiplyColorIfNeeded(color, modulateType, modulateMode) { + if (modulateType === 1 || modulateType === 4 || modulateMode === 0 && modulateType === 9) { + const mul2 = 0.9019608; + color.r *= mul2; + color.g *= mul2; + color.b *= mul2; + } + return color; + } + constructor(options = {}) { + const uniforms = { + uBoneCount: { value: 0 }, + uAlpha: { value: 1 }, + uHSLightGroundColor: { + value: LUTShaderMaterial.defaultHSLightGroundColor + }, + uHSLightSkyColor: { + value: LUTShaderMaterial.defaultHSLightSkyColor + }, + uDirLightColor0: { + value: LUTShaderMaterial.defaultDirLightColor0 + }, + uDirLightColor1: { + value: LUTShaderMaterial.defaultDirLightColor1 + }, + uDirLightCount: { + value: LUTShaderMaterial.defaultDirLightCount + }, + uDirLightDirAndType0: { + value: LUTShaderMaterial.defaultDirLightDirAndType0.clone() + }, + uDirLightDirAndType1: { + value: LUTShaderMaterial.defaultDirLightDirAndType1.clone() + }, + uLightEnable: { value: true }, + uLightColor: { value: LUTShaderMaterial.defaultLightColor } + }; + super({ + vertexShader: _LUTShader_vert, + fragmentShader: _LUTShader_frag, + uniforms + }); + this._modulateType = 0; + this.setValues(options); + } + get color() { + if (!this.uniforms.uColor0) { + return null; + } else if (this._color3) { + return this._color3; + } + const color4 = this.uniforms.uColor0.value; + const color3 = new THREE2.Color(color4.x, color4.y, color4.z); + this._color3 = color3; + return color3; + } + set color(value2) { + function toColor4(color, opacity2 = 1) { + return new THREE2.Vector4(color.r, color.g, color.b, opacity2); + } + if (Array.isArray(value2)) { + this.uniforms.uColor0 = { value: toColor4(value2[0]) }; + this.uniforms.uColor1 = { value: toColor4(value2[1]) }; + this.uniforms.uColor2 = { value: toColor4(value2[2]) }; + return; + } + const color3 = value2 ? value2 : new THREE2.Color(1, 1, 1); + this._color3 = color3.clone(); + if (this.modulateType !== undefined && typeof this.modulateMode === "number") { + LUTShaderMaterial.multiplyColorIfNeeded(color3, this.modulateType, this.modulateMode); + } + const opacity = this.opacity; + if (this._opacity) { + delete this._opacity; + } + this.uniforms.uColor0 = { value: toColor4(color3, opacity) }; + } + get opacity() { + if (!this.uniforms.uColor0) { + return this._opacity ? this._opacity : 1; + } + return this.uniforms.uColor0.value.w; + } + set opacity(value2) { + if (!this.uniforms || !this.uniforms.uColor0) { + this._opacity = 1; + return; + } + this.uniforms.uColor0.value.w = value2; + } + get modulateMode() { + return this.uniforms.uMode ? this.uniforms.uMode.value : null; + } + set modulateMode(value2) { + this.uniforms.uMode = { value: value2 }; + } + get lightEnable() { + return this.uniforms.uLightEnable ? this.uniforms.uLightEnable.value : null; + } + set lightEnable(value2) { + this.uniforms.uLightEnable = { value: value2 }; + } + get modulateType() { + return this._modulateType; + } + set modulateType(value2) { + const lutTextures = LUTShaderMaterial.getLUTTextures(); + const specType = LUTShaderMaterial.modulateTypeToLUTSpecular[value2]; + const fresType = LUTShaderMaterial.modulateTypeToLUTFresnel[value2]; + if (specType === undefined || fresType === undefined) { + return; + } + this._modulateType = value2; + const lutSpecTexture = lutTextures.specular[specType]; + const lutFresTexture = lutTextures.fresnel[fresType]; + this.uniforms.uLUTSpecTexture = { value: lutSpecTexture }; + this.uniforms.uLUTFresTexture = { value: lutFresTexture }; + this.uniforms.uAlphaTest = { + value: value2 >= 6 && value2 <= 8 + }; + this._side = this.side; + this.side = value2 === 6 ? THREE2.DoubleSide : this.side; + } + get map() { + return this.uniforms.uAlbedoTexture ? this.uniforms.uAlbedoTexture.value : null; + } + set map(value2) { + this.uniforms.uAlbedoTexture = { value: value2 }; + } + get lightDirection() { + return this.uniforms.uDirLightDirAndType0.value; + } + set lightDirection(value2) { + this.uniforms.uDirLightDirAndType0 = { value: value2 }; + this.uniforms.uDirLightDirAndType0.value.w = -1; + } + } + return LUTShaderMaterial; + }); +}); + +// src/external/ffl.js/ffl-emscripten.js +var require_ffl_emscripten = __commonJS((exports2, module2) => { + var ModuleFFL = (() => { + var _scriptName = typeof document != "undefined" ? document.currentScript?.src : undefined; + return async function(moduleArg = {}) { + var moduleRtn; + var Module = moduleArg; + var readyPromiseResolve, readyPromiseReject; + var readyPromise = new Promise((resolve, reject2) => { + readyPromiseResolve = resolve; + readyPromiseReject = reject2; + }); + var ENVIRONMENT_IS_WEB = true; + var ENVIRONMENT_IS_WORKER = false; + var moduleOverrides = { ...Module }; + var scriptDirectory = ""; + function locateFile(path) { + if (Module["locateFile"]) { + return Module["locateFile"](path, scriptDirectory); + } + return scriptDirectory + path; + } + var readAsync, readBinary; + if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { + if (ENVIRONMENT_IS_WORKER) { + scriptDirectory = self.location.href; + } else if (typeof document != "undefined" && document.currentScript) { + scriptDirectory = document.currentScript.src; + } + if (_scriptName) { + scriptDirectory = _scriptName; + } + if (scriptDirectory.startsWith("blob:")) { + scriptDirectory = ""; + } else { + scriptDirectory = scriptDirectory.slice(0, scriptDirectory.replace(/[?#].*/, "").lastIndexOf("/") + 1); + } + { + readAsync = async (url) => { + var response = await fetch(url, { credentials: "same-origin" }); + if (response.ok) { + return response.arrayBuffer(); + } + throw new Error(response.status + " : " + response.url); + }; + } + } else { + } + var out = console.log.bind(console); + var err = console.error.bind(console); + Object.assign(Module, moduleOverrides); + moduleOverrides = null; + var wasmBinary; + var wasmMemory; + var ABORT = false; + var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAP64, HEAPU64, HEAPF64; + var runtimeInitialized = false; + function updateMemoryViews() { + var b2 = wasmMemory.buffer; + Module["HEAP8"] = HEAP8 = new Int8Array(b2); + HEAP16 = new Int16Array(b2); + Module["HEAPU8"] = HEAPU8 = new Uint8Array(b2); + Module["HEAPU16"] = HEAPU16 = new Uint16Array(b2); + Module["HEAP32"] = HEAP32 = new Int32Array(b2); + Module["HEAPU32"] = HEAPU32 = new Uint32Array(b2); + Module["HEAPF32"] = HEAPF32 = new Float32Array(b2); + HEAPF64 = new Float64Array(b2); + HEAP64 = new BigInt64Array(b2); + HEAPU64 = new BigUint64Array(b2); + } + function preRun() { + } + function initRuntime() { + runtimeInitialized = true; + wasmExports["e"](); + } + function postRun() { + } + var runDependencies = 0; + var dependenciesFulfilled = null; + function addRunDependency(id) { + runDependencies++; + } + function removeRunDependency(id) { + runDependencies--; + if (runDependencies == 0) { + if (dependenciesFulfilled) { + var callback = dependenciesFulfilled; + dependenciesFulfilled = null; + callback(); + } + } + } + function abort(what) { + what = "Aborted(" + what + ")"; + err(what); + ABORT = true; + what += ". Build with -sASSERTIONS for more info."; + var e = new WebAssembly.RuntimeError(what); + readyPromiseReject(e); + throw e; + } + var wasmBinaryFile; + function findWasmBinary() { + return locateFile("ffl-emscripten.wasm"); + } + function getBinarySync(file) { + if (file == wasmBinaryFile && wasmBinary) { + return new Uint8Array(wasmBinary); + } + if (readBinary) { + return readBinary(file); + } + throw "both async and sync fetching of the wasm failed"; + } + async function getWasmBinary(binaryFile) { + if (!wasmBinary) { + try { + var response = await readAsync(binaryFile); + return new Uint8Array(response); + } catch { + } + } + return getBinarySync(binaryFile); + } + async function instantiateArrayBuffer(binaryFile, imports) { + try { + var binary = await getWasmBinary(binaryFile); + var instance = await WebAssembly.instantiate(binary, imports); + return instance; + } catch (reason) { + err(`failed to asynchronously prepare wasm: ${reason}`); + abort(reason); + } + } + async function instantiateAsync(binary, binaryFile, imports) { + if (!binary && typeof WebAssembly.instantiateStreaming == "function") { + try { + var response = fetch(binaryFile, { credentials: "same-origin" }); + var instantiationResult = await WebAssembly.instantiateStreaming(response, imports); + return instantiationResult; + } catch (reason) { + err(`wasm streaming compile failed: ${reason}`); + err("falling back to ArrayBuffer instantiation"); + } + } + return instantiateArrayBuffer(binaryFile, imports); + } + function getWasmImports() { + return { a: wasmImports }; + } + async function createWasm() { + function receiveInstance(instance, module3) { + wasmExports = instance.exports; + wasmMemory = wasmExports["d"]; + updateMemoryViews(); + wasmTable = wasmExports["O"]; + removeRunDependency("wasm-instantiate"); + return wasmExports; + } + addRunDependency("wasm-instantiate"); + function receiveInstantiationResult(result2) { + return receiveInstance(result2["instance"]); + } + var info = getWasmImports(); + wasmBinaryFile ??= findWasmBinary(); + try { + var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info); + var exports3 = receiveInstantiationResult(result); + return exports3; + } catch (e) { + readyPromiseReject(e); + return Promise.reject(e); + } + } + + class ExitStatus { + name = "ExitStatus"; + constructor(status) { + this.message = `Program terminated with exit(${status})`; + this.status = status; + } + } + function stackTrace() { + abort("missing function: $stackTrace"); + } + stackTrace.stub = true; + var __abort_js = () => abort(""); + var _emscripten_random = () => Math.random(); + var getHeapMax = () => 2147483648; + var alignMemory = (size2, alignment) => Math.ceil(size2 / alignment) * alignment; + var growMemory = (size2) => { + var b2 = wasmMemory.buffer; + var pages = (size2 - b2.byteLength + 65535) / 65536 | 0; + try { + wasmMemory.grow(pages); + updateMemoryViews(); + return 1; + } catch (e) { + } + }; + var _emscripten_resize_heap = (requestedSize) => { + var oldSize = HEAPU8.length; + requestedSize >>>= 0; + var maxHeapSize = getHeapMax(); + if (requestedSize > maxHeapSize) { + return false; + } + for (var cutDown = 1;cutDown <= 4; cutDown *= 2) { + var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown); + overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296); + var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536)); + var replacement = growMemory(newSize); + if (replacement) { + return true; + } + } + return false; + }; + var uleb128Encode = (n2, target) => { + if (n2 < 128) { + target.push(n2); + } else { + target.push(n2 % 128 | 128, n2 >> 7); + } + }; + var sigToWasmTypes = (sig) => { + var typeNames = { i: "i32", j: "i64", f: "f32", d: "f64", e: "externref", p: "i32" }; + var type = { parameters: [], results: sig[0] == "v" ? [] : [typeNames[sig[0]]] }; + for (var i = 1;i < sig.length; ++i) { + type.parameters.push(typeNames[sig[i]]); + } + return type; + }; + var generateFuncType = (sig, target) => { + var sigRet = sig.slice(0, 1); + var sigParam = sig.slice(1); + var typeCodes = { i: 127, p: 127, j: 126, f: 125, d: 124, e: 111 }; + target.push(96); + uleb128Encode(sigParam.length, target); + for (var paramType of sigParam) { + target.push(typeCodes[paramType]); + } + if (sigRet == "v") { + target.push(0); + } else { + target.push(1, typeCodes[sigRet]); + } + }; + var convertJsFunctionToWasm = (func, sig) => { + if (typeof WebAssembly.Function == "function") { + return new WebAssembly.Function(sigToWasmTypes(sig), func); + } + var typeSectionBody = [1]; + generateFuncType(sig, typeSectionBody); + var bytes = [0, 97, 115, 109, 1, 0, 0, 0, 1]; + uleb128Encode(typeSectionBody.length, bytes); + bytes.push(...typeSectionBody); + bytes.push(2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0); + var module3 = new WebAssembly.Module(new Uint8Array(bytes)); + var instance = new WebAssembly.Instance(module3, { e: { f: func } }); + var wrappedFunc = instance.exports["f"]; + return wrappedFunc; + }; + var wasmTableMirror = []; + var wasmTable; + var getWasmTableEntry = (funcPtr) => { + var func = wasmTableMirror[funcPtr]; + if (!func) { + wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr); + } + return func; + }; + var updateTableMap = (offset, count) => { + if (functionsInTableMap) { + for (var i = offset;i < offset + count; i++) { + var item = getWasmTableEntry(i); + if (item) { + functionsInTableMap.set(item, i); + } + } + } + }; + var functionsInTableMap; + var getFunctionAddress = (func) => { + if (!functionsInTableMap) { + functionsInTableMap = new WeakMap; + updateTableMap(0, wasmTable.length); + } + return functionsInTableMap.get(func) || 0; + }; + var freeTableIndexes = []; + var getEmptyTableSlot = () => { + if (freeTableIndexes.length) { + return freeTableIndexes.pop(); + } + try { + wasmTable.grow(1); + } catch (err2) { + if (!(err2 instanceof RangeError)) { + throw err2; + } + throw "Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."; + } + return wasmTable.length - 1; + }; + var setWasmTableEntry = (idx, func) => { + wasmTable.set(idx, func); + wasmTableMirror[idx] = wasmTable.get(idx); + }; + var addFunction = (func, sig) => { + var rtn = getFunctionAddress(func); + if (rtn) { + return rtn; + } + var ret = getEmptyTableSlot(); + try { + setWasmTableEntry(ret, func); + } catch (err2) { + if (!(err2 instanceof TypeError)) { + throw err2; + } + var wrapped = convertJsFunctionToWasm(func, sig); + setWasmTableEntry(ret, wrapped); + } + functionsInTableMap.set(func, ret); + return ret; + }; + var removeFunction = (index2) => { + functionsInTableMap.delete(getWasmTableEntry(index2)); + setWasmTableEntry(index2, null); + freeTableIndexes.push(index2); + }; + var wasmImports = { a: __abort_js, c: _emscripten_random, b: _emscripten_resize_heap }; + var wasmExports = await createWasm(); + var ___wasm_call_ctors = wasmExports["e"]; + var _FFLInitCharModelCPUStepWithCallback = Module["_FFLInitCharModelCPUStepWithCallback"] = wasmExports["f"]; + var _FFLInitCharModelCPUStep = Module["_FFLInitCharModelCPUStep"] = wasmExports["g"]; + var _FFLDeleteCharModel = Module["_FFLDeleteCharModel"] = wasmExports["h"]; + var _FFLGetDrawParamOpaFaceline = Module["_FFLGetDrawParamOpaFaceline"] = wasmExports["i"]; + var _FFLGetDrawParamOpaBeard = Module["_FFLGetDrawParamOpaBeard"] = wasmExports["j"]; + var _FFLGetDrawParamOpaNose = Module["_FFLGetDrawParamOpaNose"] = wasmExports["k"]; + var _FFLGetDrawParamOpaForehead = Module["_FFLGetDrawParamOpaForehead"] = wasmExports["l"]; + var _FFLGetDrawParamOpaHair = Module["_FFLGetDrawParamOpaHair"] = wasmExports["m"]; + var _FFLGetDrawParamOpaCap = Module["_FFLGetDrawParamOpaCap"] = wasmExports["n"]; + var _FFLGetDrawParamXluMask = Module["_FFLGetDrawParamXluMask"] = wasmExports["o"]; + var _FFLGetDrawParamXluNoseLine = Module["_FFLGetDrawParamXluNoseLine"] = wasmExports["p"]; + var _FFLGetDrawParamXluGlass = Module["_FFLGetDrawParamXluGlass"] = wasmExports["q"]; + var _FFLSetExpression = Module["_FFLSetExpression"] = wasmExports["r"]; + var _FFLGetExpression = Module["_FFLGetExpression"] = wasmExports["s"]; + var _FFLSetViewModelType = Module["_FFLSetViewModelType"] = wasmExports["t"]; + var _FFLGetBoundingBox = Module["_FFLGetBoundingBox"] = wasmExports["u"]; + var _FFLIsAvailableExpression = Module["_FFLIsAvailableExpression"] = wasmExports["v"]; + var _FFLSetCoordinate = Module["_FFLSetCoordinate"] = wasmExports["w"]; + var _FFLSetScale = Module["_FFLSetScale"] = wasmExports["x"]; + var _FFLiGetRandomCharInfo = Module["_FFLiGetRandomCharInfo"] = wasmExports["y"]; + var _FFLpGetStoreDataFromCharInfo = Module["_FFLpGetStoreDataFromCharInfo"] = wasmExports["z"]; + var _FFLpGetCharInfoFromStoreData = Module["_FFLpGetCharInfoFromStoreData"] = wasmExports["A"]; + var _FFLpGetCharInfoFromMiiDataOfficialRFL = Module["_FFLpGetCharInfoFromMiiDataOfficialRFL"] = wasmExports["B"]; + var _FFLGetAdditionalInfo = Module["_FFLGetAdditionalInfo"] = wasmExports["C"]; + var _FFLInitRes = Module["_FFLInitRes"] = wasmExports["D"]; + var _FFLInitResGPUStep = Module["_FFLInitResGPUStep"] = wasmExports["E"]; + var _FFLExit = Module["_FFLExit"] = wasmExports["F"]; + var _FFLIsAvailable = Module["_FFLIsAvailable"] = wasmExports["G"]; + var _FFLGetFavoriteColor = Module["_FFLGetFavoriteColor"] = wasmExports["H"]; + var _FFLSetLinearGammaMode = Module["_FFLSetLinearGammaMode"] = wasmExports["I"]; + var _FFLGetFacelineColor = Module["_FFLGetFacelineColor"] = wasmExports["J"]; + var _FFLSetTextureFlipY = Module["_FFLSetTextureFlipY"] = wasmExports["K"]; + var _FFLSetNormalIsSnorm8_8_8_8 = Module["_FFLSetNormalIsSnorm8_8_8_8"] = wasmExports["L"]; + var _FFLSetFrontCullForFlipX = Module["_FFLSetFrontCullForFlipX"] = wasmExports["M"]; + var _FFLSetTextureCallback = Module["_FFLSetTextureCallback"] = wasmExports["N"]; + var _FFLiDeleteTempObjectMaskTextures = Module["_FFLiDeleteTempObjectMaskTextures"] = wasmExports["P"]; + var _FFLiDeleteTempObjectFacelineTexture = Module["_FFLiDeleteTempObjectFacelineTexture"] = wasmExports["Q"]; + var _FFLiDeleteTextureTempObject = Module["_FFLiDeleteTextureTempObject"] = wasmExports["R"]; + var _FFLiiGetEyeRotateOffset = Module["_FFLiiGetEyeRotateOffset"] = wasmExports["S"]; + var _FFLiiGetEyebrowRotateOffset = Module["_FFLiiGetEyebrowRotateOffset"] = wasmExports["T"]; + var _FFLiInvalidateTempObjectFacelineTexture = Module["_FFLiInvalidateTempObjectFacelineTexture"] = wasmExports["U"]; + var _FFLiInvalidatePartsTextures = Module["_FFLiInvalidatePartsTextures"] = wasmExports["V"]; + var _FFLiInvalidateRawMask = Module["_FFLiInvalidateRawMask"] = wasmExports["W"]; + var _GX2CalcSurfaceSizeAndAlignment = Module["_GX2CalcSurfaceSizeAndAlignment"] = wasmExports["X"]; + var _GX2CopySurface = Module["_GX2CopySurface"] = wasmExports["Y"]; + var _FFLiVerifyCharInfoWithReason = Module["_FFLiVerifyCharInfoWithReason"] = wasmExports["Z"]; + var _malloc = Module["_malloc"] = wasmExports["_"]; + var _free = Module["_free"] = wasmExports["$"]; + Module["addFunction"] = addFunction; + Module["removeFunction"] = removeFunction; + function run() { + if (runDependencies > 0) { + dependenciesFulfilled = run; + return; + } + preRun(); + if (runDependencies > 0) { + dependenciesFulfilled = run; + return; + } + function doRun() { + Module["calledRun"] = true; + if (ABORT) + return; + initRuntime(); + readyPromiseResolve(Module); + Module["onRuntimeInitialized"]?.(); + postRun(); + } + { + doRun(); + } + } + run(); + moduleRtn = readyPromise; + return moduleRtn; + }; + })(); + if (typeof exports2 === "object" && typeof module2 === "object") { + module2.exports = ModuleFFL; + module2.exports.default = ModuleFFL; + } else if (typeof define === "function" && define["amd"]) + define([], () => ModuleFFL); +}); + +// node_modules/three/build/three.module.js +var exports_three_module = {}; +__export(exports_three_module, { + createCanvasElement: () => createCanvasElement, + ZeroStencilOp: () => ZeroStencilOp, + ZeroSlopeEnding: () => ZeroSlopeEnding, + ZeroFactor: () => ZeroFactor, + ZeroCurvatureEnding: () => ZeroCurvatureEnding, + WrapAroundEnding: () => WrapAroundEnding, + WireframeGeometry: () => WireframeGeometry, + WebXRController: () => WebXRController, + WebGPUCoordinateSystem: () => WebGPUCoordinateSystem, + WebGLUtils: () => WebGLUtils, + WebGLRenderer: () => WebGLRenderer, + WebGLRenderTarget: () => WebGLRenderTarget, + WebGLCubeRenderTarget: () => WebGLCubeRenderTarget, + WebGLCoordinateSystem: () => WebGLCoordinateSystem, + WebGLArrayRenderTarget: () => WebGLArrayRenderTarget, + WebGL3DRenderTarget: () => WebGL3DRenderTarget, + VideoTexture: () => VideoTexture, + VideoFrameTexture: () => VideoFrameTexture, + VectorKeyframeTrack: () => VectorKeyframeTrack, + Vector4: () => Vector4, + Vector3: () => Vector3, + Vector2: () => Vector2, + VSMShadowMap: () => VSMShadowMap, + UnsignedShortType: () => UnsignedShortType, + UnsignedShort5551Type: () => UnsignedShort5551Type, + UnsignedShort4444Type: () => UnsignedShort4444Type, + UnsignedIntType: () => UnsignedIntType, + UnsignedInt5999Type: () => UnsignedInt5999Type, + UnsignedInt248Type: () => UnsignedInt248Type, + UnsignedByteType: () => UnsignedByteType, + UniformsUtils: () => UniformsUtils, + UniformsLib: () => UniformsLib, + UniformsGroup: () => UniformsGroup, + Uniform: () => Uniform, + Uint8ClampedBufferAttribute: () => Uint8ClampedBufferAttribute, + Uint8BufferAttribute: () => Uint8BufferAttribute, + Uint32BufferAttribute: () => Uint32BufferAttribute, + Uint16BufferAttribute: () => Uint16BufferAttribute, + UVMapping: () => UVMapping, + TubeGeometry: () => TubeGeometry, + TrianglesDrawMode: () => TrianglesDrawMode, + TriangleStripDrawMode: () => TriangleStripDrawMode, + TriangleFanDrawMode: () => TriangleFanDrawMode, + Triangle: () => Triangle, + TorusKnotGeometry: () => TorusKnotGeometry, + TorusGeometry: () => TorusGeometry, + TimestampQuery: () => TimestampQuery, + TextureUtils: () => TextureUtils, + TextureLoader: () => TextureLoader, + Texture: () => Texture, + TetrahedronGeometry: () => TetrahedronGeometry, + TangentSpaceNormalMap: () => TangentSpaceNormalMap, + TOUCH: () => TOUCH, + SubtractiveBlending: () => SubtractiveBlending, + SubtractEquation: () => SubtractEquation, + StringKeyframeTrack: () => StringKeyframeTrack, + StreamReadUsage: () => StreamReadUsage, + StreamDrawUsage: () => StreamDrawUsage, + StreamCopyUsage: () => StreamCopyUsage, + StereoCamera: () => StereoCamera, + StaticReadUsage: () => StaticReadUsage, + StaticDrawUsage: () => StaticDrawUsage, + StaticCopyUsage: () => StaticCopyUsage, + SrcColorFactor: () => SrcColorFactor, + SrcAlphaSaturateFactor: () => SrcAlphaSaturateFactor, + SrcAlphaFactor: () => SrcAlphaFactor, + SpriteMaterial: () => SpriteMaterial, + Sprite: () => Sprite, + SpotLightHelper: () => SpotLightHelper, + SpotLight: () => SpotLight, + SplineCurve: () => SplineCurve, + SphericalHarmonics3: () => SphericalHarmonics3, + Spherical: () => Spherical, + SphereGeometry: () => SphereGeometry, + Sphere: () => Sphere, + Source: () => Source, + SkinnedMesh: () => SkinnedMesh, + SkeletonHelper: () => SkeletonHelper, + Skeleton: () => Skeleton, + ShortType: () => ShortType, + ShapeUtils: () => ShapeUtils, + ShapePath: () => ShapePath2, + ShapeGeometry: () => ShapeGeometry, + Shape: () => Shape, + ShadowMaterial: () => ShadowMaterial, + ShaderMaterial: () => ShaderMaterial, + ShaderLib: () => ShaderLib, + ShaderChunk: () => ShaderChunk, + Scene: () => Scene, + SRGBTransfer: () => SRGBTransfer, + SRGBColorSpace: () => SRGBColorSpace, + SIGNED_RED_RGTC1_Format: () => SIGNED_RED_RGTC1_Format, + SIGNED_RED_GREEN_RGTC2_Format: () => SIGNED_RED_GREEN_RGTC2_Format, + RingGeometry: () => RingGeometry, + ReverseSubtractEquation: () => ReverseSubtractEquation, + ReplaceStencilOp: () => ReplaceStencilOp, + RepeatWrapping: () => RepeatWrapping, + RenderTargetArray: () => RenderTargetArray, + RenderTarget3D: () => RenderTarget3D, + RenderTarget: () => RenderTarget, + ReinhardToneMapping: () => ReinhardToneMapping, + RedIntegerFormat: () => RedIntegerFormat, + RedFormat: () => RedFormat, + RectAreaLight: () => RectAreaLight, + Raycaster: () => Raycaster, + Ray: () => Ray, + RawShaderMaterial: () => RawShaderMaterial, + RGIntegerFormat: () => RGIntegerFormat, + RGFormat: () => RGFormat, + RGDepthPacking: () => RGDepthPacking, + RGB_S3TC_DXT1_Format: () => RGB_S3TC_DXT1_Format, + RGB_PVRTC_4BPPV1_Format: () => RGB_PVRTC_4BPPV1_Format, + RGB_PVRTC_2BPPV1_Format: () => RGB_PVRTC_2BPPV1_Format, + RGB_ETC2_Format: () => RGB_ETC2_Format, + RGB_ETC1_Format: () => RGB_ETC1_Format, + RGB_BPTC_UNSIGNED_Format: () => RGB_BPTC_UNSIGNED_Format, + RGB_BPTC_SIGNED_Format: () => RGB_BPTC_SIGNED_Format, + RGBIntegerFormat: () => RGBIntegerFormat, + RGBFormat: () => RGBFormat, + RGBDepthPacking: () => RGBDepthPacking, + RGBA_S3TC_DXT5_Format: () => RGBA_S3TC_DXT5_Format, + RGBA_S3TC_DXT3_Format: () => RGBA_S3TC_DXT3_Format, + RGBA_S3TC_DXT1_Format: () => RGBA_S3TC_DXT1_Format, + RGBA_PVRTC_4BPPV1_Format: () => RGBA_PVRTC_4BPPV1_Format, + RGBA_PVRTC_2BPPV1_Format: () => RGBA_PVRTC_2BPPV1_Format, + RGBA_ETC2_EAC_Format: () => RGBA_ETC2_EAC_Format, + RGBA_BPTC_Format: () => RGBA_BPTC_Format, + RGBA_ASTC_8x8_Format: () => RGBA_ASTC_8x8_Format, + RGBA_ASTC_8x6_Format: () => RGBA_ASTC_8x6_Format, + RGBA_ASTC_8x5_Format: () => RGBA_ASTC_8x5_Format, + RGBA_ASTC_6x6_Format: () => RGBA_ASTC_6x6_Format, + RGBA_ASTC_6x5_Format: () => RGBA_ASTC_6x5_Format, + RGBA_ASTC_5x5_Format: () => RGBA_ASTC_5x5_Format, + RGBA_ASTC_5x4_Format: () => RGBA_ASTC_5x4_Format, + RGBA_ASTC_4x4_Format: () => RGBA_ASTC_4x4_Format, + RGBA_ASTC_12x12_Format: () => RGBA_ASTC_12x12_Format, + RGBA_ASTC_12x10_Format: () => RGBA_ASTC_12x10_Format, + RGBA_ASTC_10x8_Format: () => RGBA_ASTC_10x8_Format, + RGBA_ASTC_10x6_Format: () => RGBA_ASTC_10x6_Format, + RGBA_ASTC_10x5_Format: () => RGBA_ASTC_10x5_Format, + RGBA_ASTC_10x10_Format: () => RGBA_ASTC_10x10_Format, + RGBAIntegerFormat: () => RGBAIntegerFormat, + RGBAFormat: () => RGBAFormat, + RGBADepthPacking: () => RGBADepthPacking, + REVISION: () => REVISION, + RED_RGTC1_Format: () => RED_RGTC1_Format, + RED_GREEN_RGTC2_Format: () => RED_GREEN_RGTC2_Format, + QuaternionLinearInterpolant: () => QuaternionLinearInterpolant, + QuaternionKeyframeTrack: () => QuaternionKeyframeTrack, + Quaternion: () => Quaternion, + QuadraticBezierCurve3: () => QuadraticBezierCurve3, + QuadraticBezierCurve: () => QuadraticBezierCurve, + PropertyMixer: () => PropertyMixer, + PropertyBinding: () => PropertyBinding, + PositionalAudio: () => PositionalAudio, + PolyhedronGeometry: () => PolyhedronGeometry, + PolarGridHelper: () => PolarGridHelper, + PointsMaterial: () => PointsMaterial, + Points: () => Points, + PointLightHelper: () => PointLightHelper, + PointLight: () => PointLight, + PlaneHelper: () => PlaneHelper, + PlaneGeometry: () => PlaneGeometry, + Plane: () => Plane, + PerspectiveCamera: () => PerspectiveCamera, + Path: () => Path, + PMREMGenerator: () => PMREMGenerator, + PCFSoftShadowMap: () => PCFSoftShadowMap, + PCFShadowMap: () => PCFShadowMap, + OrthographicCamera: () => OrthographicCamera, + OneMinusSrcColorFactor: () => OneMinusSrcColorFactor, + OneMinusSrcAlphaFactor: () => OneMinusSrcAlphaFactor, + OneMinusDstColorFactor: () => OneMinusDstColorFactor, + OneMinusDstAlphaFactor: () => OneMinusDstAlphaFactor, + OneMinusConstantColorFactor: () => OneMinusConstantColorFactor, + OneMinusConstantAlphaFactor: () => OneMinusConstantAlphaFactor, + OneFactor: () => OneFactor, + OctahedronGeometry: () => OctahedronGeometry, + ObjectSpaceNormalMap: () => ObjectSpaceNormalMap, + ObjectLoader: () => ObjectLoader, + Object3D: () => Object3D, + NumberKeyframeTrack: () => NumberKeyframeTrack, + NotEqualStencilFunc: () => NotEqualStencilFunc, + NotEqualDepth: () => NotEqualDepth, + NotEqualCompare: () => NotEqualCompare, + NormalBlending: () => NormalBlending, + NormalAnimationBlendMode: () => NormalAnimationBlendMode, + NoToneMapping: () => NoToneMapping, + NoColorSpace: () => NoColorSpace, + NoBlending: () => NoBlending, + NeverStencilFunc: () => NeverStencilFunc, + NeverDepth: () => NeverDepth, + NeverCompare: () => NeverCompare, + NeutralToneMapping: () => NeutralToneMapping, + NearestMipmapNearestFilter: () => NearestMipmapNearestFilter, + NearestMipmapLinearFilter: () => NearestMipmapLinearFilter, + NearestMipMapNearestFilter: () => NearestMipMapNearestFilter, + NearestMipMapLinearFilter: () => NearestMipMapLinearFilter, + NearestFilter: () => NearestFilter, + MultiplyOperation: () => MultiplyOperation, + MultiplyBlending: () => MultiplyBlending, + MixOperation: () => MixOperation, + MirroredRepeatWrapping: () => MirroredRepeatWrapping, + MinEquation: () => MinEquation, + MeshToonMaterial: () => MeshToonMaterial, + MeshStandardMaterial: () => MeshStandardMaterial, + MeshPhysicalMaterial: () => MeshPhysicalMaterial, + MeshPhongMaterial: () => MeshPhongMaterial, + MeshNormalMaterial: () => MeshNormalMaterial, + MeshMatcapMaterial: () => MeshMatcapMaterial, + MeshLambertMaterial: () => MeshLambertMaterial, + MeshDistanceMaterial: () => MeshDistanceMaterial, + MeshDepthMaterial: () => MeshDepthMaterial, + MeshBasicMaterial: () => MeshBasicMaterial, + Mesh: () => Mesh, + MaxEquation: () => MaxEquation, + Matrix4: () => Matrix4, + Matrix3: () => Matrix3, + Matrix2: () => Matrix2, + MathUtils: () => MathUtils, + MaterialLoader: () => MaterialLoader, + Material: () => Material, + MOUSE: () => MOUSE, + LuminanceFormat: () => LuminanceFormat, + LuminanceAlphaFormat: () => LuminanceAlphaFormat, + LoopRepeat: () => LoopRepeat, + LoopPingPong: () => LoopPingPong, + LoopOnce: () => LoopOnce, + LoadingManager: () => LoadingManager, + LoaderUtils: () => LoaderUtils, + Loader: () => Loader, + LinearTransfer: () => LinearTransfer, + LinearToneMapping: () => LinearToneMapping, + LinearSRGBColorSpace: () => LinearSRGBColorSpace, + LinearMipmapNearestFilter: () => LinearMipmapNearestFilter, + LinearMipmapLinearFilter: () => LinearMipmapLinearFilter, + LinearMipMapNearestFilter: () => LinearMipMapNearestFilter, + LinearMipMapLinearFilter: () => LinearMipMapLinearFilter, + LinearInterpolant: () => LinearInterpolant, + LinearFilter: () => LinearFilter, + LineSegments: () => LineSegments, + LineLoop: () => LineLoop, + LineDashedMaterial: () => LineDashedMaterial, + LineCurve3: () => LineCurve3, + LineCurve: () => LineCurve, + LineBasicMaterial: () => LineBasicMaterial, + Line3: () => Line3, + Line: () => Line, + LightProbe: () => LightProbe, + Light: () => Light, + LessStencilFunc: () => LessStencilFunc, + LessEqualStencilFunc: () => LessEqualStencilFunc, + LessEqualDepth: () => LessEqualDepth, + LessEqualCompare: () => LessEqualCompare, + LessDepth: () => LessDepth, + LessCompare: () => LessCompare, + Layers: () => Layers, + LatheGeometry: () => LatheGeometry, + LOD: () => LOD, + KeyframeTrack: () => KeyframeTrack, + KeepStencilOp: () => KeepStencilOp, + InvertStencilOp: () => InvertStencilOp, + InterpolateSmooth: () => InterpolateSmooth, + InterpolateLinear: () => InterpolateLinear, + InterpolateDiscrete: () => InterpolateDiscrete, + Interpolant: () => Interpolant, + InterleavedBufferAttribute: () => InterleavedBufferAttribute, + InterleavedBuffer: () => InterleavedBuffer, + IntType: () => IntType, + Int8BufferAttribute: () => Int8BufferAttribute, + Int32BufferAttribute: () => Int32BufferAttribute, + Int16BufferAttribute: () => Int16BufferAttribute, + InstancedMesh: () => InstancedMesh, + InstancedInterleavedBuffer: () => InstancedInterleavedBuffer, + InstancedBufferGeometry: () => InstancedBufferGeometry, + InstancedBufferAttribute: () => InstancedBufferAttribute, + IncrementWrapStencilOp: () => IncrementWrapStencilOp, + IncrementStencilOp: () => IncrementStencilOp, + ImageUtils: () => ImageUtils, + ImageLoader: () => ImageLoader, + ImageBitmapLoader: () => ImageBitmapLoader, + IcosahedronGeometry: () => IcosahedronGeometry, + HemisphereLightHelper: () => HemisphereLightHelper, + HemisphereLight: () => HemisphereLight, + HalfFloatType: () => HalfFloatType, + Group: () => Group, + GridHelper: () => GridHelper, + GreaterStencilFunc: () => GreaterStencilFunc, + GreaterEqualStencilFunc: () => GreaterEqualStencilFunc, + GreaterEqualDepth: () => GreaterEqualDepth, + GreaterEqualCompare: () => GreaterEqualCompare, + GreaterDepth: () => GreaterDepth, + GreaterCompare: () => GreaterCompare, + GLSL3: () => GLSL3, + GLSL1: () => GLSL1, + GLBufferAttribute: () => GLBufferAttribute, + Frustum: () => Frustum, + FrontSide: () => FrontSide, + FramebufferTexture: () => FramebufferTexture, + FogExp2: () => FogExp2, + Fog: () => Fog, + FloatType: () => FloatType, + Float32BufferAttribute: () => Float32BufferAttribute, + Float16BufferAttribute: () => Float16BufferAttribute, + FileLoader: () => FileLoader, + ExtrudeGeometry: () => ExtrudeGeometry, + EventDispatcher: () => EventDispatcher, + Euler: () => Euler, + EquirectangularRefractionMapping: () => EquirectangularRefractionMapping, + EquirectangularReflectionMapping: () => EquirectangularReflectionMapping, + EqualStencilFunc: () => EqualStencilFunc, + EqualDepth: () => EqualDepth, + EqualCompare: () => EqualCompare, + EllipseCurve: () => EllipseCurve, + EdgesGeometry: () => EdgesGeometry, + DynamicReadUsage: () => DynamicReadUsage, + DynamicDrawUsage: () => DynamicDrawUsage, + DynamicCopyUsage: () => DynamicCopyUsage, + DstColorFactor: () => DstColorFactor, + DstAlphaFactor: () => DstAlphaFactor, + DoubleSide: () => DoubleSide, + DodecahedronGeometry: () => DodecahedronGeometry, + DiscreteInterpolant: () => DiscreteInterpolant, + DirectionalLightHelper: () => DirectionalLightHelper, + DirectionalLight: () => DirectionalLight, + DetachedBindMode: () => DetachedBindMode, + DepthTexture: () => DepthTexture, + DepthStencilFormat: () => DepthStencilFormat, + DepthFormat: () => DepthFormat, + DefaultLoadingManager: () => DefaultLoadingManager, + DecrementWrapStencilOp: () => DecrementWrapStencilOp, + DecrementStencilOp: () => DecrementStencilOp, + DataUtils: () => DataUtils, + DataTextureLoader: () => DataTextureLoader, + DataTexture: () => DataTexture, + DataArrayTexture: () => DataArrayTexture, + Data3DTexture: () => Data3DTexture, + Cylindrical: () => Cylindrical, + CylinderGeometry: () => CylinderGeometry, + CustomToneMapping: () => CustomToneMapping, + CustomBlending: () => CustomBlending, + CurvePath: () => CurvePath, + Curve: () => Curve, + CullFaceNone: () => CullFaceNone, + CullFaceFrontBack: () => CullFaceFrontBack, + CullFaceFront: () => CullFaceFront, + CullFaceBack: () => CullFaceBack, + CubicInterpolant: () => CubicInterpolant, + CubicBezierCurve3: () => CubicBezierCurve3, + CubicBezierCurve: () => CubicBezierCurve, + CubeUVReflectionMapping: () => CubeUVReflectionMapping, + CubeTextureLoader: () => CubeTextureLoader, + CubeTexture: () => CubeTexture, + CubeRefractionMapping: () => CubeRefractionMapping, + CubeReflectionMapping: () => CubeReflectionMapping, + CubeCamera: () => CubeCamera, + Controls: () => Controls, + ConstantColorFactor: () => ConstantColorFactor, + ConstantAlphaFactor: () => ConstantAlphaFactor, + ConeGeometry: () => ConeGeometry, + CompressedTextureLoader: () => CompressedTextureLoader, + CompressedTexture: () => CompressedTexture, + CompressedCubeTexture: () => CompressedCubeTexture, + CompressedArrayTexture: () => CompressedArrayTexture, + ColorManagement: () => ColorManagement, + ColorKeyframeTrack: () => ColorKeyframeTrack, + Color: () => Color, + Clock: () => Clock, + ClampToEdgeWrapping: () => ClampToEdgeWrapping, + CircleGeometry: () => CircleGeometry, + CineonToneMapping: () => CineonToneMapping, + CatmullRomCurve3: () => CatmullRomCurve3, + CapsuleGeometry: () => CapsuleGeometry, + CanvasTexture: () => CanvasTexture, + CameraHelper: () => CameraHelper, + Camera: () => Camera, + Cache: () => Cache, + ByteType: () => ByteType, + BufferGeometryLoader: () => BufferGeometryLoader, + BufferGeometry: () => BufferGeometry, + BufferAttribute: () => BufferAttribute, + BoxHelper: () => BoxHelper, + BoxGeometry: () => BoxGeometry, + Box3Helper: () => Box3Helper, + Box3: () => Box3, + Box2: () => Box2, + BooleanKeyframeTrack: () => BooleanKeyframeTrack, + Bone: () => Bone, + BatchedMesh: () => BatchedMesh, + BasicShadowMap: () => BasicShadowMap, + BasicDepthPacking: () => BasicDepthPacking, + BackSide: () => BackSide, + AxesHelper: () => AxesHelper, + AudioLoader: () => AudioLoader, + AudioListener: () => AudioListener, + AudioContext: () => AudioContext, + AudioAnalyser: () => AudioAnalyser, + Audio: () => Audio, + AttachedBindMode: () => AttachedBindMode, + ArrowHelper: () => ArrowHelper, + ArrayCamera: () => ArrayCamera, + ArcCurve: () => ArcCurve, + AnimationUtils: () => AnimationUtils, + AnimationObjectGroup: () => AnimationObjectGroup, + AnimationMixer: () => AnimationMixer, + AnimationLoader: () => AnimationLoader, + AnimationClip: () => AnimationClip, + AnimationAction: () => AnimationAction, + AmbientLight: () => AmbientLight, + AlwaysStencilFunc: () => AlwaysStencilFunc, + AlwaysDepth: () => AlwaysDepth, + AlwaysCompare: () => AlwaysCompare, + AlphaFormat: () => AlphaFormat, + AgXToneMapping: () => AgXToneMapping, + AdditiveBlending: () => AdditiveBlending, + AdditiveAnimationBlendMode: () => AdditiveAnimationBlendMode, + AddOperation: () => AddOperation, + AddEquation: () => AddEquation, + ACESFilmicToneMapping: () => ACESFilmicToneMapping +}); + +// node_modules/three/build/three.core.js +var REVISION = "173"; +var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 }; +var TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 }; +var CullFaceNone = 0; +var CullFaceBack = 1; +var CullFaceFront = 2; +var CullFaceFrontBack = 3; +var BasicShadowMap = 0; +var PCFShadowMap = 1; +var PCFSoftShadowMap = 2; +var VSMShadowMap = 3; +var FrontSide = 0; +var BackSide = 1; +var DoubleSide = 2; +var NoBlending = 0; +var NormalBlending = 1; +var AdditiveBlending = 2; +var SubtractiveBlending = 3; +var MultiplyBlending = 4; +var CustomBlending = 5; +var AddEquation = 100; +var SubtractEquation = 101; +var ReverseSubtractEquation = 102; +var MinEquation = 103; +var MaxEquation = 104; +var ZeroFactor = 200; +var OneFactor = 201; +var SrcColorFactor = 202; +var OneMinusSrcColorFactor = 203; +var SrcAlphaFactor = 204; +var OneMinusSrcAlphaFactor = 205; +var DstAlphaFactor = 206; +var OneMinusDstAlphaFactor = 207; +var DstColorFactor = 208; +var OneMinusDstColorFactor = 209; +var SrcAlphaSaturateFactor = 210; +var ConstantColorFactor = 211; +var OneMinusConstantColorFactor = 212; +var ConstantAlphaFactor = 213; +var OneMinusConstantAlphaFactor = 214; +var NeverDepth = 0; +var AlwaysDepth = 1; +var LessDepth = 2; +var LessEqualDepth = 3; +var EqualDepth = 4; +var GreaterEqualDepth = 5; +var GreaterDepth = 6; +var NotEqualDepth = 7; +var MultiplyOperation = 0; +var MixOperation = 1; +var AddOperation = 2; +var NoToneMapping = 0; +var LinearToneMapping = 1; +var ReinhardToneMapping = 2; +var CineonToneMapping = 3; +var ACESFilmicToneMapping = 4; +var CustomToneMapping = 5; +var AgXToneMapping = 6; +var NeutralToneMapping = 7; +var AttachedBindMode = "attached"; +var DetachedBindMode = "detached"; +var UVMapping = 300; +var CubeReflectionMapping = 301; +var CubeRefractionMapping = 302; +var EquirectangularReflectionMapping = 303; +var EquirectangularRefractionMapping = 304; +var CubeUVReflectionMapping = 306; +var RepeatWrapping = 1000; +var ClampToEdgeWrapping = 1001; +var MirroredRepeatWrapping = 1002; +var NearestFilter = 1003; +var NearestMipmapNearestFilter = 1004; +var NearestMipMapNearestFilter = 1004; +var NearestMipmapLinearFilter = 1005; +var NearestMipMapLinearFilter = 1005; +var LinearFilter = 1006; +var LinearMipmapNearestFilter = 1007; +var LinearMipMapNearestFilter = 1007; +var LinearMipmapLinearFilter = 1008; +var LinearMipMapLinearFilter = 1008; +var UnsignedByteType = 1009; +var ByteType = 1010; +var ShortType = 1011; +var UnsignedShortType = 1012; +var IntType = 1013; +var UnsignedIntType = 1014; +var FloatType = 1015; +var HalfFloatType = 1016; +var UnsignedShort4444Type = 1017; +var UnsignedShort5551Type = 1018; +var UnsignedInt248Type = 1020; +var UnsignedInt5999Type = 35902; +var AlphaFormat = 1021; +var RGBFormat = 1022; +var RGBAFormat = 1023; +var LuminanceFormat = 1024; +var LuminanceAlphaFormat = 1025; +var DepthFormat = 1026; +var DepthStencilFormat = 1027; +var RedFormat = 1028; +var RedIntegerFormat = 1029; +var RGFormat = 1030; +var RGIntegerFormat = 1031; +var RGBIntegerFormat = 1032; +var RGBAIntegerFormat = 1033; +var RGB_S3TC_DXT1_Format = 33776; +var RGBA_S3TC_DXT1_Format = 33777; +var RGBA_S3TC_DXT3_Format = 33778; +var RGBA_S3TC_DXT5_Format = 33779; +var RGB_PVRTC_4BPPV1_Format = 35840; +var RGB_PVRTC_2BPPV1_Format = 35841; +var RGBA_PVRTC_4BPPV1_Format = 35842; +var RGBA_PVRTC_2BPPV1_Format = 35843; +var RGB_ETC1_Format = 36196; +var RGB_ETC2_Format = 37492; +var RGBA_ETC2_EAC_Format = 37496; +var RGBA_ASTC_4x4_Format = 37808; +var RGBA_ASTC_5x4_Format = 37809; +var RGBA_ASTC_5x5_Format = 37810; +var RGBA_ASTC_6x5_Format = 37811; +var RGBA_ASTC_6x6_Format = 37812; +var RGBA_ASTC_8x5_Format = 37813; +var RGBA_ASTC_8x6_Format = 37814; +var RGBA_ASTC_8x8_Format = 37815; +var RGBA_ASTC_10x5_Format = 37816; +var RGBA_ASTC_10x6_Format = 37817; +var RGBA_ASTC_10x8_Format = 37818; +var RGBA_ASTC_10x10_Format = 37819; +var RGBA_ASTC_12x10_Format = 37820; +var RGBA_ASTC_12x12_Format = 37821; +var RGBA_BPTC_Format = 36492; +var RGB_BPTC_SIGNED_Format = 36494; +var RGB_BPTC_UNSIGNED_Format = 36495; +var RED_RGTC1_Format = 36283; +var SIGNED_RED_RGTC1_Format = 36284; +var RED_GREEN_RGTC2_Format = 36285; +var SIGNED_RED_GREEN_RGTC2_Format = 36286; +var LoopOnce = 2200; +var LoopRepeat = 2201; +var LoopPingPong = 2202; +var InterpolateDiscrete = 2300; +var InterpolateLinear = 2301; +var InterpolateSmooth = 2302; +var ZeroCurvatureEnding = 2400; +var ZeroSlopeEnding = 2401; +var WrapAroundEnding = 2402; +var NormalAnimationBlendMode = 2500; +var AdditiveAnimationBlendMode = 2501; +var TrianglesDrawMode = 0; +var TriangleStripDrawMode = 1; +var TriangleFanDrawMode = 2; +var BasicDepthPacking = 3200; +var RGBADepthPacking = 3201; +var RGBDepthPacking = 3202; +var RGDepthPacking = 3203; +var TangentSpaceNormalMap = 0; +var ObjectSpaceNormalMap = 1; +var NoColorSpace = ""; +var SRGBColorSpace = "srgb"; +var LinearSRGBColorSpace = "srgb-linear"; +var LinearTransfer = "linear"; +var SRGBTransfer = "srgb"; +var ZeroStencilOp = 0; +var KeepStencilOp = 7680; +var ReplaceStencilOp = 7681; +var IncrementStencilOp = 7682; +var DecrementStencilOp = 7683; +var IncrementWrapStencilOp = 34055; +var DecrementWrapStencilOp = 34056; +var InvertStencilOp = 5386; +var NeverStencilFunc = 512; +var LessStencilFunc = 513; +var EqualStencilFunc = 514; +var LessEqualStencilFunc = 515; +var GreaterStencilFunc = 516; +var NotEqualStencilFunc = 517; +var GreaterEqualStencilFunc = 518; +var AlwaysStencilFunc = 519; +var NeverCompare = 512; +var LessCompare = 513; +var EqualCompare = 514; +var LessEqualCompare = 515; +var GreaterCompare = 516; +var NotEqualCompare = 517; +var GreaterEqualCompare = 518; +var AlwaysCompare = 519; +var StaticDrawUsage = 35044; +var DynamicDrawUsage = 35048; +var StreamDrawUsage = 35040; +var StaticReadUsage = 35045; +var DynamicReadUsage = 35049; +var StreamReadUsage = 35041; +var StaticCopyUsage = 35046; +var DynamicCopyUsage = 35050; +var StreamCopyUsage = 35042; +var GLSL1 = "100"; +var GLSL3 = "300 es"; +var WebGLCoordinateSystem = 2000; +var WebGPUCoordinateSystem = 2001; +var TimestampQuery = { + COMPUTE: "compute", + RENDER: "render" +}; + +class EventDispatcher { + addEventListener(type, listener) { + if (this._listeners === undefined) + this._listeners = {}; + const listeners = this._listeners; + if (listeners[type] === undefined) { + listeners[type] = []; + } + if (listeners[type].indexOf(listener) === -1) { + listeners[type].push(listener); + } + } + hasEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === undefined) + return false; + return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1; + } + removeEventListener(type, listener) { + const listeners = this._listeners; + if (listeners === undefined) + return; + const listenerArray = listeners[type]; + if (listenerArray !== undefined) { + const index2 = listenerArray.indexOf(listener); + if (index2 !== -1) { + listenerArray.splice(index2, 1); + } + } + } + dispatchEvent(event) { + const listeners = this._listeners; + if (listeners === undefined) + return; + const listenerArray = listeners[event.type]; + if (listenerArray !== undefined) { + event.target = this; + const array = listenerArray.slice(0); + for (let i = 0, l = array.length;i < l; i++) { + array[i].call(this, event); + } + event.target = null; + } + } +} +var _lut = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"]; +var _seed = 1234567; +var DEG2RAD = Math.PI / 180; +var RAD2DEG = 180 / Math.PI; +function generateUUID() { + const d0 = Math.random() * 4294967295 | 0; + const d1 = Math.random() * 4294967295 | 0; + const d2 = Math.random() * 4294967295 | 0; + const d3 = Math.random() * 4294967295 | 0; + const uuid = _lut[d0 & 255] + _lut[d0 >> 8 & 255] + _lut[d0 >> 16 & 255] + _lut[d0 >> 24 & 255] + "-" + _lut[d1 & 255] + _lut[d1 >> 8 & 255] + "-" + _lut[d1 >> 16 & 15 | 64] + _lut[d1 >> 24 & 255] + "-" + _lut[d2 & 63 | 128] + _lut[d2 >> 8 & 255] + "-" + _lut[d2 >> 16 & 255] + _lut[d2 >> 24 & 255] + _lut[d3 & 255] + _lut[d3 >> 8 & 255] + _lut[d3 >> 16 & 255] + _lut[d3 >> 24 & 255]; + return uuid.toLowerCase(); +} +function clamp2(value2, min, max) { + return Math.max(min, Math.min(max, value2)); +} +function euclideanModulo(n, m) { + return (n % m + m) % m; +} +function mapLinear(x, a1, a2, b1, b2) { + return b1 + (x - a1) * (b2 - b1) / (a2 - a1); +} +function inverseLerp(x, y, value2) { + if (x !== y) { + return (value2 - x) / (y - x); + } else { + return 0; + } +} +function lerp(x, y, t) { + return (1 - t) * x + t * y; +} +function damp(x, y, lambda, dt) { + return lerp(x, y, 1 - Math.exp(-lambda * dt)); +} +function pingpong(x, length2 = 1) { + return length2 - Math.abs(euclideanModulo(x, length2 * 2) - length2); +} +function smoothstep(x, min, max) { + if (x <= min) + return 0; + if (x >= max) + return 1; + x = (x - min) / (max - min); + return x * x * (3 - 2 * x); +} +function smootherstep(x, min, max) { + if (x <= min) + return 0; + if (x >= max) + return 1; + x = (x - min) / (max - min); + return x * x * x * (x * (x * 6 - 15) + 10); +} +function randInt(low, high) { + return low + Math.floor(Math.random() * (high - low + 1)); +} +function randFloat(low, high) { + return low + Math.random() * (high - low); +} +function randFloatSpread(range) { + return range * (0.5 - Math.random()); +} +function seededRandom(s) { + if (s !== undefined) + _seed = s; + let t = _seed += 1831565813; + t = Math.imul(t ^ t >>> 15, t | 1); + t ^= t + Math.imul(t ^ t >>> 7, t | 61); + return ((t ^ t >>> 14) >>> 0) / 4294967296; +} +function degToRad(degrees) { + return degrees * DEG2RAD; +} +function radToDeg(radians) { + return radians * RAD2DEG; +} +function isPowerOfTwo(value2) { + return (value2 & value2 - 1) === 0 && value2 !== 0; +} +function ceilPowerOfTwo(value2) { + return Math.pow(2, Math.ceil(Math.log(value2) / Math.LN2)); +} +function floorPowerOfTwo(value2) { + return Math.pow(2, Math.floor(Math.log(value2) / Math.LN2)); +} +function setQuaternionFromProperEuler(q, a, b, c, order) { + const cos = Math.cos; + const sin = Math.sin; + const c2 = cos(b / 2); + const s2 = sin(b / 2); + const c13 = cos((a + c) / 2); + const s13 = sin((a + c) / 2); + const c1_3 = cos((a - c) / 2); + const s1_3 = sin((a - c) / 2); + const c3_1 = cos((c - a) / 2); + const s3_1 = sin((c - a) / 2); + switch (order) { + case "XYX": + q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13); + break; + case "YZY": + q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13); + break; + case "ZXZ": + q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13); + break; + case "XZX": + q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13); + break; + case "YXY": + q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13); + break; + case "ZYZ": + q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13); + break; + default: + console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + order); + } +} +function denormalize(value2, array) { + switch (array.constructor) { + case Float32Array: + return value2; + case Uint32Array: + return value2 / 4294967295; + case Uint16Array: + return value2 / 65535; + case Uint8Array: + return value2 / 255; + case Int32Array: + return Math.max(value2 / 2147483647, -1); + case Int16Array: + return Math.max(value2 / 32767, -1); + case Int8Array: + return Math.max(value2 / 127, -1); + default: + throw new Error("Invalid component type."); + } +} +function normalize2(value2, array) { + switch (array.constructor) { + case Float32Array: + return value2; + case Uint32Array: + return Math.round(value2 * 4294967295); + case Uint16Array: + return Math.round(value2 * 65535); + case Uint8Array: + return Math.round(value2 * 255); + case Int32Array: + return Math.round(value2 * 2147483647); + case Int16Array: + return Math.round(value2 * 32767); + case Int8Array: + return Math.round(value2 * 127); + default: + throw new Error("Invalid component type."); + } +} +var MathUtils = { + DEG2RAD, + RAD2DEG, + generateUUID, + clamp: clamp2, + euclideanModulo, + mapLinear, + inverseLerp, + lerp, + damp, + pingpong, + smoothstep, + smootherstep, + randInt, + randFloat, + randFloatSpread, + seededRandom, + degToRad, + radToDeg, + isPowerOfTwo, + ceilPowerOfTwo, + floorPowerOfTwo, + setQuaternionFromProperEuler, + normalize: normalize2, + denormalize +}; + +class Vector2 { + constructor(x = 0, y = 0) { + Vector2.prototype.isVector2 = true; + this.x = x; + this.y = y; + } + get width() { + return this.x; + } + set width(value2) { + this.x = value2; + } + get height() { + return this.y; + } + set height(value2) { + this.y = value2; + } + set(x, y) { + this.x = x; + this.y = y; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y); + } + copy(v) { + this.x = v.x; + this.y = v.y; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + applyMatrix3(m) { + const x = this.x, y = this.y; + const e = m.elements; + this.x = e[0] * x + e[3] * y + e[6]; + this.y = e[1] * x + e[4] * y + e[7]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + return this; + } + clamp(min, max) { + this.x = clamp2(this.x, min.x, max.x); + this.y = clamp2(this.y, min.y, max.y); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp2(this.x, minVal, maxVal); + this.y = clamp2(this.y, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp2(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y; + } + cross(v) { + return this.x * v.y - this.y * v.x; + } + lengthSq() { + return this.x * this.x + this.y * this.y; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + angle() { + const angle = Math.atan2(-this.y, -this.x) + Math.PI; + return angle; + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) + return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp2(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y; + return dx * dx + dy * dy; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + return this; + } + rotateAround(center, angle) { + const c = Math.cos(angle), s = Math.sin(angle); + const x = this.x - center.x; + const y = this.y - center.y; + this.x = x * c - y * s + center.x; + this.y = x * s + y * c + center.y; + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + } +} + +class Matrix3 { + constructor(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + Matrix3.prototype.isMatrix3 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n13, n21, n22, n23, n31, n32, n33); + } + } + set(n11, n12, n13, n21, n22, n23, n31, n32, n33) { + const te = this.elements; + te[0] = n11; + te[1] = n21; + te[2] = n31; + te[3] = n12; + te[4] = n22; + te[5] = n32; + te[6] = n13; + te[7] = n23; + te[8] = n33; + return this; + } + identity() { + this.set(1, 0, 0, 0, 1, 0, 0, 0, 1); + return this; + } + copy(m) { + const te = this.elements; + const me = m.elements; + te[0] = me[0]; + te[1] = me[1]; + te[2] = me[2]; + te[3] = me[3]; + te[4] = me[4]; + te[5] = me[5]; + te[6] = me[6]; + te[7] = me[7]; + te[8] = me[8]; + return this; + } + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrix3Column(this, 0); + yAxis.setFromMatrix3Column(this, 1); + zAxis.setFromMatrix3Column(this, 2); + return this; + } + setFromMatrix4(m) { + const me = m.elements; + this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]); + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a, b) { + const ae = a.elements; + const be = b.elements; + const te = this.elements; + const a11 = ae[0], a12 = ae[3], a13 = ae[6]; + const a21 = ae[1], a22 = ae[4], a23 = ae[7]; + const a31 = ae[2], a32 = ae[5], a33 = ae[8]; + const b11 = be[0], b12 = be[3], b13 = be[6]; + const b21 = be[1], b22 = be[4], b23 = be[7]; + const b31 = be[2], b32 = be[5], b33 = be[8]; + te[0] = a11 * b11 + a12 * b21 + a13 * b31; + te[3] = a11 * b12 + a12 * b22 + a13 * b32; + te[6] = a11 * b13 + a12 * b23 + a13 * b33; + te[1] = a21 * b11 + a22 * b21 + a23 * b31; + te[4] = a21 * b12 + a22 * b22 + a23 * b32; + te[7] = a21 * b13 + a22 * b23 + a23 * b33; + te[2] = a31 * b11 + a32 * b21 + a33 * b31; + te[5] = a31 * b12 + a32 * b22 + a33 * b32; + te[8] = a31 * b13 + a32 * b23 + a33 * b33; + return this; + } + multiplyScalar(s) { + const te = this.elements; + te[0] *= s; + te[3] *= s; + te[6] *= s; + te[1] *= s; + te[4] *= s; + te[7] *= s; + te[2] *= s; + te[5] *= s; + te[8] *= s; + return this; + } + determinant() { + const te = this.elements; + const a = te[0], b = te[1], c = te[2], d = te[3], e = te[4], f = te[5], g = te[6], h = te[7], i = te[8]; + return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g; + } + invert() { + const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n12 = te[3], n22 = te[4], n32 = te[5], n13 = te[6], n23 = te[7], n33 = te[8], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13; + if (det === 0) + return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te[0] = t11 * detInv; + te[1] = (n31 * n23 - n33 * n21) * detInv; + te[2] = (n32 * n21 - n31 * n22) * detInv; + te[3] = t12 * detInv; + te[4] = (n33 * n11 - n31 * n13) * detInv; + te[5] = (n31 * n12 - n32 * n11) * detInv; + te[6] = t13 * detInv; + te[7] = (n21 * n13 - n23 * n11) * detInv; + te[8] = (n22 * n11 - n21 * n12) * detInv; + return this; + } + transpose() { + let tmp; + const m = this.elements; + tmp = m[1]; + m[1] = m[3]; + m[3] = tmp; + tmp = m[2]; + m[2] = m[6]; + m[6] = tmp; + tmp = m[5]; + m[5] = m[7]; + m[7] = tmp; + return this; + } + getNormalMatrix(matrix4) { + return this.setFromMatrix4(matrix4).invert().transpose(); + } + transposeIntoArray(r) { + const m = this.elements; + r[0] = m[0]; + r[1] = m[3]; + r[2] = m[6]; + r[3] = m[1]; + r[4] = m[4]; + r[5] = m[7]; + r[6] = m[2]; + r[7] = m[5]; + r[8] = m[8]; + return this; + } + setUvTransform(tx, ty, sx, sy, rotation2, cx, cy) { + const c = Math.cos(rotation2); + const s = Math.sin(rotation2); + this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1); + return this; + } + scale(sx, sy) { + this.premultiply(_m3.makeScale(sx, sy)); + return this; + } + rotate(theta) { + this.premultiply(_m3.makeRotation(-theta)); + return this; + } + translate(tx, ty) { + this.premultiply(_m3.makeTranslation(tx, ty)); + return this; + } + makeTranslation(x, y) { + if (x.isVector2) { + this.set(1, 0, x.x, 0, 1, x.y, 0, 0, 1); + } else { + this.set(1, 0, x, 0, 1, y, 0, 0, 1); + } + return this; + } + makeRotation(theta) { + const c = Math.cos(theta); + const s = Math.sin(theta); + this.set(c, -s, 0, s, c, 0, 0, 0, 1); + return this; + } + makeScale(x, y) { + this.set(x, 0, 0, 0, y, 0, 0, 0, 1); + return this; + } + equals(matrix) { + const te = this.elements; + const me = matrix.elements; + for (let i = 0;i < 9; i++) { + if (te[i] !== me[i]) + return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 9; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te = this.elements; + array[offset] = te[0]; + array[offset + 1] = te[1]; + array[offset + 2] = te[2]; + array[offset + 3] = te[3]; + array[offset + 4] = te[4]; + array[offset + 5] = te[5]; + array[offset + 6] = te[6]; + array[offset + 7] = te[7]; + array[offset + 8] = te[8]; + return array; + } + clone() { + return new this.constructor().fromArray(this.elements); + } +} +var _m3 = /* @__PURE__ */ new Matrix3; +function arrayNeedsUint32(array) { + for (let i = array.length - 1;i >= 0; --i) { + if (array[i] >= 65535) + return true; + } + return false; +} +var TYPED_ARRAYS = { + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array +}; +function getTypedArray(type, buffer) { + return new TYPED_ARRAYS[type](buffer); +} +function createElementNS(name2) { + return document.createElementNS("http://www.w3.org/1999/xhtml", name2); +} +function createCanvasElement() { + const canvas = createElementNS("canvas"); + canvas.style.display = "block"; + return canvas; +} +var _cache = {}; +function warnOnce(message) { + if (message in _cache) + return; + _cache[message] = true; + console.warn(message); +} +function probeAsync(gl, sync, interval) { + return new Promise(function(resolve, reject2) { + function probe() { + switch (gl.clientWaitSync(sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0)) { + case gl.WAIT_FAILED: + reject2(); + break; + case gl.TIMEOUT_EXPIRED: + setTimeout(probe, interval); + break; + default: + resolve(); + } + } + setTimeout(probe, interval); + }); +} +function toNormalizedProjectionMatrix(projectionMatrix) { + const m = projectionMatrix.elements; + m[2] = 0.5 * m[2] + 0.5 * m[3]; + m[6] = 0.5 * m[6] + 0.5 * m[7]; + m[10] = 0.5 * m[10] + 0.5 * m[11]; + m[14] = 0.5 * m[14] + 0.5 * m[15]; +} +function toReversedProjectionMatrix(projectionMatrix) { + const m = projectionMatrix.elements; + const isPerspectiveMatrix = m[11] === -1; + if (isPerspectiveMatrix) { + m[10] = -m[10] - 1; + m[14] = -m[14]; + } else { + m[10] = -m[10]; + m[14] = -m[14] + 1; + } +} +var LINEAR_REC709_TO_XYZ = /* @__PURE__ */ new Matrix3().set(0.4123908, 0.3575843, 0.1804808, 0.212639, 0.7151687, 0.0721923, 0.0193308, 0.1191948, 0.9505322); +var XYZ_TO_LINEAR_REC709 = /* @__PURE__ */ new Matrix3().set(3.2409699, -1.5373832, -0.4986108, -0.9692436, 1.8759675, 0.0415551, 0.0556301, -0.203977, 1.0569715); +function createColorManagement() { + const ColorManagement = { + enabled: true, + workingColorSpace: LinearSRGBColorSpace, + spaces: {}, + convert: function(color, sourceColorSpace, targetColorSpace) { + if (this.enabled === false || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) { + return color; + } + if (this.spaces[sourceColorSpace].transfer === SRGBTransfer) { + color.r = SRGBToLinear(color.r); + color.g = SRGBToLinear(color.g); + color.b = SRGBToLinear(color.b); + } + if (this.spaces[sourceColorSpace].primaries !== this.spaces[targetColorSpace].primaries) { + color.applyMatrix3(this.spaces[sourceColorSpace].toXYZ); + color.applyMatrix3(this.spaces[targetColorSpace].fromXYZ); + } + if (this.spaces[targetColorSpace].transfer === SRGBTransfer) { + color.r = LinearToSRGB(color.r); + color.g = LinearToSRGB(color.g); + color.b = LinearToSRGB(color.b); + } + return color; + }, + fromWorkingColorSpace: function(color, targetColorSpace) { + return this.convert(color, this.workingColorSpace, targetColorSpace); + }, + toWorkingColorSpace: function(color, sourceColorSpace) { + return this.convert(color, sourceColorSpace, this.workingColorSpace); + }, + getPrimaries: function(colorSpace) { + return this.spaces[colorSpace].primaries; + }, + getTransfer: function(colorSpace) { + if (colorSpace === NoColorSpace) + return LinearTransfer; + return this.spaces[colorSpace].transfer; + }, + getLuminanceCoefficients: function(target, colorSpace = this.workingColorSpace) { + return target.fromArray(this.spaces[colorSpace].luminanceCoefficients); + }, + define: function(colorSpaces) { + Object.assign(this.spaces, colorSpaces); + }, + _getMatrix: function(targetMatrix, sourceColorSpace, targetColorSpace) { + return targetMatrix.copy(this.spaces[sourceColorSpace].toXYZ).multiply(this.spaces[targetColorSpace].fromXYZ); + }, + _getDrawingBufferColorSpace: function(colorSpace) { + return this.spaces[colorSpace].outputColorSpaceConfig.drawingBufferColorSpace; + }, + _getUnpackColorSpace: function(colorSpace = this.workingColorSpace) { + return this.spaces[colorSpace].workingColorSpaceConfig.unpackColorSpace; + } + }; + const REC709_PRIMARIES = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06]; + const REC709_LUMINANCE_COEFFICIENTS = [0.2126, 0.7152, 0.0722]; + const D65 = [0.3127, 0.329]; + ColorManagement.define({ + [LinearSRGBColorSpace]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: LinearTransfer, + toXYZ: LINEAR_REC709_TO_XYZ, + fromXYZ: XYZ_TO_LINEAR_REC709, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace }, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace } + }, + [SRGBColorSpace]: { + primaries: REC709_PRIMARIES, + whitePoint: D65, + transfer: SRGBTransfer, + toXYZ: LINEAR_REC709_TO_XYZ, + fromXYZ: XYZ_TO_LINEAR_REC709, + luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS, + outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace } + } + }); + return ColorManagement; +} +var ColorManagement = /* @__PURE__ */ createColorManagement(); +function SRGBToLinear(c) { + return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); +} +function LinearToSRGB(c) { + return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055; +} +var _canvas; + +class ImageUtils { + static getDataURL(image) { + if (/^data:/i.test(image.src)) { + return image.src; + } + if (typeof HTMLCanvasElement === "undefined") { + return image.src; + } + let canvas; + if (image instanceof HTMLCanvasElement) { + canvas = image; + } else { + if (_canvas === undefined) + _canvas = createElementNS("canvas"); + _canvas.width = image.width; + _canvas.height = image.height; + const context = _canvas.getContext("2d"); + if (image instanceof ImageData) { + context.putImageData(image, 0, 0); + } else { + context.drawImage(image, 0, 0, image.width, image.height); + } + canvas = _canvas; + } + return canvas.toDataURL("image/png"); + } + static sRGBToLinear(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + const canvas = createElementNS("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, image.width, image.height); + const imageData = context.getImageData(0, 0, image.width, image.height); + const data2 = imageData.data; + for (let i = 0;i < data2.length; i++) { + data2[i] = SRGBToLinear(data2[i] / 255) * 255; + } + context.putImageData(imageData, 0, 0); + return canvas; + } else if (image.data) { + const data2 = image.data.slice(0); + for (let i = 0;i < data2.length; i++) { + if (data2 instanceof Uint8Array || data2 instanceof Uint8ClampedArray) { + data2[i] = Math.floor(SRGBToLinear(data2[i] / 255) * 255); + } else { + data2[i] = SRGBToLinear(data2[i]); + } + } + return { + data: data2, + width: image.width, + height: image.height + }; + } else { + console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."); + return image; + } + } +} +var _sourceId = 0; + +class Source { + constructor(data2 = null) { + this.isSource = true; + Object.defineProperty(this, "id", { value: _sourceId++ }); + this.uuid = generateUUID(); + this.data = data2; + this.dataReady = true; + this.version = 0; + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + if (!isRootObject && meta.images[this.uuid] !== undefined) { + return meta.images[this.uuid]; + } + const output = { + uuid: this.uuid, + url: "" + }; + const data2 = this.data; + if (data2 !== null) { + let url; + if (Array.isArray(data2)) { + url = []; + for (let i = 0, l = data2.length;i < l; i++) { + if (data2[i].isDataTexture) { + url.push(serializeImage(data2[i].image)); + } else { + url.push(serializeImage(data2[i])); + } + } + } else { + url = serializeImage(data2); + } + output.url = url; + } + if (!isRootObject) { + meta.images[this.uuid] = output; + } + return output; + } +} +function serializeImage(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { + return ImageUtils.getDataURL(image); + } else { + if (image.data) { + return { + data: Array.from(image.data), + width: image.width, + height: image.height, + type: image.data.constructor.name + }; + } else { + console.warn("THREE.Texture: Unable to serialize Texture."); + return {}; + } + } +} +var _textureId = 0; + +class Texture extends EventDispatcher { + constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace) { + super(); + this.isTexture = true; + Object.defineProperty(this, "id", { value: _textureId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.source = new Source(image); + this.mipmaps = []; + this.mapping = mapping; + this.channel = 0; + this.wrapS = wrapS; + this.wrapT = wrapT; + this.magFilter = magFilter; + this.minFilter = minFilter; + this.anisotropy = anisotropy; + this.format = format; + this.internalFormat = null; + this.type = type; + this.offset = new Vector2(0, 0); + this.repeat = new Vector2(1, 1); + this.center = new Vector2(0, 0); + this.rotation = 0; + this.matrixAutoUpdate = true; + this.matrix = new Matrix3; + this.generateMipmaps = true; + this.premultiplyAlpha = false; + this.flipY = true; + this.unpackAlignment = 4; + this.colorSpace = colorSpace; + this.userData = {}; + this.version = 0; + this.onUpdate = null; + this.renderTarget = null; + this.isRenderTargetTexture = false; + this.pmremVersion = 0; + } + get image() { + return this.source.data; + } + set image(value2 = null) { + this.source.data = value2; + } + updateMatrix() { + this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.source = source.source; + this.mipmaps = source.mipmaps.slice(0); + this.mapping = source.mapping; + this.channel = source.channel; + this.wrapS = source.wrapS; + this.wrapT = source.wrapT; + this.magFilter = source.magFilter; + this.minFilter = source.minFilter; + this.anisotropy = source.anisotropy; + this.format = source.format; + this.internalFormat = source.internalFormat; + this.type = source.type; + this.offset.copy(source.offset); + this.repeat.copy(source.repeat); + this.center.copy(source.center); + this.rotation = source.rotation; + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrix.copy(source.matrix); + this.generateMipmaps = source.generateMipmaps; + this.premultiplyAlpha = source.premultiplyAlpha; + this.flipY = source.flipY; + this.unpackAlignment = source.unpackAlignment; + this.colorSpace = source.colorSpace; + this.renderTarget = source.renderTarget; + this.isRenderTargetTexture = source.isRenderTargetTexture; + this.userData = JSON.parse(JSON.stringify(source.userData)); + this.needsUpdate = true; + return this; + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + if (!isRootObject && meta.textures[this.uuid] !== undefined) { + return meta.textures[this.uuid]; + } + const output = { + metadata: { + version: 4.6, + type: "Texture", + generator: "Texture.toJSON" + }, + uuid: this.uuid, + name: this.name, + image: this.source.toJSON(meta).uuid, + mapping: this.mapping, + channel: this.channel, + repeat: [this.repeat.x, this.repeat.y], + offset: [this.offset.x, this.offset.y], + center: [this.center.x, this.center.y], + rotation: this.rotation, + wrap: [this.wrapS, this.wrapT], + format: this.format, + internalFormat: this.internalFormat, + type: this.type, + colorSpace: this.colorSpace, + minFilter: this.minFilter, + magFilter: this.magFilter, + anisotropy: this.anisotropy, + flipY: this.flipY, + generateMipmaps: this.generateMipmaps, + premultiplyAlpha: this.premultiplyAlpha, + unpackAlignment: this.unpackAlignment + }; + if (Object.keys(this.userData).length > 0) + output.userData = this.userData; + if (!isRootObject) { + meta.textures[this.uuid] = output; + } + return output; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + transformUv(uv) { + if (this.mapping !== UVMapping) + return uv; + uv.applyMatrix3(this.matrix); + if (uv.x < 0 || uv.x > 1) { + switch (this.wrapS) { + case RepeatWrapping: + uv.x = uv.x - Math.floor(uv.x); + break; + case ClampToEdgeWrapping: + uv.x = uv.x < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping: + if (Math.abs(Math.floor(uv.x) % 2) === 1) { + uv.x = Math.ceil(uv.x) - uv.x; + } else { + uv.x = uv.x - Math.floor(uv.x); + } + break; + } + } + if (uv.y < 0 || uv.y > 1) { + switch (this.wrapT) { + case RepeatWrapping: + uv.y = uv.y - Math.floor(uv.y); + break; + case ClampToEdgeWrapping: + uv.y = uv.y < 0 ? 0 : 1; + break; + case MirroredRepeatWrapping: + if (Math.abs(Math.floor(uv.y) % 2) === 1) { + uv.y = Math.ceil(uv.y) - uv.y; + } else { + uv.y = uv.y - Math.floor(uv.y); + } + break; + } + } + if (this.flipY) { + uv.y = 1 - uv.y; + } + return uv; + } + set needsUpdate(value2) { + if (value2 === true) { + this.version++; + this.source.needsUpdate = true; + } + } + set needsPMREMUpdate(value2) { + if (value2 === true) { + this.pmremVersion++; + } + } +} +Texture.DEFAULT_IMAGE = null; +Texture.DEFAULT_MAPPING = UVMapping; +Texture.DEFAULT_ANISOTROPY = 1; + +class Vector4 { + constructor(x = 0, y = 0, z = 0, w = 1) { + Vector4.prototype.isVector4 = true; + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + get width() { + return this.z; + } + set width(value2) { + this.z = value2; + } + get height() { + return this.w; + } + set height(value2) { + this.w = value2; + } + set(x, y, z, w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + this.w = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setZ(z) { + this.z = z; + return this; + } + setW(w) { + this.w = w; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + case 2: + this.z = value2; + break; + case 3: + this.w = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + case 3: + return this.w; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z, this.w); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + this.w = v.w !== undefined ? v.w : 1; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + this.w += v.w; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + this.w += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + this.w = a.w + b.w; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + this.w += v.w * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + this.w -= v.w; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + this.w -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + this.w = a.w - b.w; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + this.w *= v.w; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + this.w *= scalar; + return this; + } + applyMatrix4(m) { + const x = this.x, y = this.y, z = this.z, w = this.w; + const e = m.elements; + this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w; + this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w; + this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w; + this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w; + return this; + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + this.w /= v.w; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + setAxisAngleFromQuaternion(q) { + this.w = 2 * Math.acos(q.w); + const s = Math.sqrt(1 - q.w * q.w); + if (s < 0.0001) { + this.x = 1; + this.y = 0; + this.z = 0; + } else { + this.x = q.x / s; + this.y = q.y / s; + this.z = q.z / s; + } + return this; + } + setAxisAngleFromRotationMatrix(m) { + let angle, x, y, z; + const epsilon = 0.01, epsilon2 = 0.1, te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10]; + if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) { + if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) { + this.set(1, 0, 0, 0); + return this; + } + angle = Math.PI; + const xx = (m11 + 1) / 2; + const yy = (m22 + 1) / 2; + const zz = (m33 + 1) / 2; + const xy = (m12 + m21) / 4; + const xz = (m13 + m31) / 4; + const yz = (m23 + m32) / 4; + if (xx > yy && xx > zz) { + if (xx < epsilon) { + x = 0; + y = 0.707106781; + z = 0.707106781; + } else { + x = Math.sqrt(xx); + y = xy / x; + z = xz / x; + } + } else if (yy > zz) { + if (yy < epsilon) { + x = 0.707106781; + y = 0; + z = 0.707106781; + } else { + y = Math.sqrt(yy); + x = xy / y; + z = yz / y; + } + } else { + if (zz < epsilon) { + x = 0.707106781; + y = 0.707106781; + z = 0; + } else { + z = Math.sqrt(zz); + x = xz / z; + y = yz / z; + } + } + this.set(x, y, z, angle); + return this; + } + let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); + if (Math.abs(s) < 0.001) + s = 1; + this.x = (m32 - m23) / s; + this.y = (m13 - m31) / s; + this.z = (m21 - m12) / s; + this.w = Math.acos((m11 + m22 + m33 - 1) / 2); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + this.w = e[15]; + return this; + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + this.w = Math.min(this.w, v.w); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + this.w = Math.max(this.w, v.w); + return this; + } + clamp(min, max) { + this.x = clamp2(this.x, min.x, max.x); + this.y = clamp2(this.y, min.y, max.y); + this.z = clamp2(this.z, min.z, max.z); + this.w = clamp2(this.w, min.w, max.w); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp2(this.x, minVal, maxVal); + this.y = clamp2(this.y, minVal, maxVal); + this.z = clamp2(this.z, minVal, maxVal); + this.w = clamp2(this.w, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp2(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + this.w = Math.floor(this.w); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + this.w = Math.ceil(this.w); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + this.w = Math.round(this.w); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + this.w = Math.trunc(this.w); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + this.w += (v.w - this.w) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + this.w = v1.w + (v2.w - v1.w) * alpha; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + this.w = array[offset + 3]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + array[offset + 3] = this.w; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + this.z = attribute.getZ(index2); + this.w = attribute.getW(index2); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + this.w = Math.random(); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + yield this.w; + } +} + +class RenderTarget extends EventDispatcher { + constructor(width2 = 1, height2 = 1, options = {}) { + super(); + this.isRenderTarget = true; + this.width = width2; + this.height = height2; + this.depth = 1; + this.scissor = new Vector4(0, 0, width2, height2); + this.scissorTest = false; + this.viewport = new Vector4(0, 0, width2, height2); + const image = { width: width2, height: height2, depth: 1 }; + options = Object.assign({ + generateMipmaps: false, + internalFormat: null, + minFilter: LinearFilter, + depthBuffer: true, + stencilBuffer: false, + resolveDepthBuffer: true, + resolveStencilBuffer: true, + depthTexture: null, + samples: 0, + count: 1 + }, options); + const texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + texture.flipY = false; + texture.generateMipmaps = options.generateMipmaps; + texture.internalFormat = options.internalFormat; + this.textures = []; + const count = options.count; + for (let i = 0;i < count; i++) { + this.textures[i] = texture.clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + } + this.depthBuffer = options.depthBuffer; + this.stencilBuffer = options.stencilBuffer; + this.resolveDepthBuffer = options.resolveDepthBuffer; + this.resolveStencilBuffer = options.resolveStencilBuffer; + this._depthTexture = null; + this.depthTexture = options.depthTexture; + this.samples = options.samples; + } + get texture() { + return this.textures[0]; + } + set texture(value2) { + this.textures[0] = value2; + } + set depthTexture(current) { + if (this._depthTexture !== null) + this._depthTexture.renderTarget = null; + if (current !== null) + current.renderTarget = this; + this._depthTexture = current; + } + get depthTexture() { + return this._depthTexture; + } + setSize(width2, height2, depth = 1) { + if (this.width !== width2 || this.height !== height2 || this.depth !== depth) { + this.width = width2; + this.height = height2; + this.depth = depth; + for (let i = 0, il = this.textures.length;i < il; i++) { + this.textures[i].image.width = width2; + this.textures[i].image.height = height2; + this.textures[i].image.depth = depth; + } + this.dispose(); + } + this.viewport.set(0, 0, width2, height2); + this.scissor.set(0, 0, width2, height2); + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.width = source.width; + this.height = source.height; + this.depth = source.depth; + this.scissor.copy(source.scissor); + this.scissorTest = source.scissorTest; + this.viewport.copy(source.viewport); + this.textures.length = 0; + for (let i = 0, il = source.textures.length;i < il; i++) { + this.textures[i] = source.textures[i].clone(); + this.textures[i].isRenderTargetTexture = true; + this.textures[i].renderTarget = this; + } + const image = Object.assign({}, source.texture.image); + this.texture.source = new Source(image); + this.depthBuffer = source.depthBuffer; + this.stencilBuffer = source.stencilBuffer; + this.resolveDepthBuffer = source.resolveDepthBuffer; + this.resolveStencilBuffer = source.resolveStencilBuffer; + if (source.depthTexture !== null) + this.depthTexture = source.depthTexture.clone(); + this.samples = source.samples; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } +} + +class WebGLRenderTarget extends RenderTarget { + constructor(width2 = 1, height2 = 1, options = {}) { + super(width2, height2, options); + this.isWebGLRenderTarget = true; + } +} + +class DataArrayTexture extends Texture { + constructor(data2 = null, width2 = 1, height2 = 1, depth = 1) { + super(null); + this.isDataArrayTexture = true; + this.image = { data: data2, width: width2, height: height2, depth }; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.wrapR = ClampToEdgeWrapping; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + this.layerUpdates = new Set; + } + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + clearLayerUpdates() { + this.layerUpdates.clear(); + } +} + +class WebGLArrayRenderTarget extends WebGLRenderTarget { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isWebGLArrayRenderTarget = true; + this.depth = depth; + this.texture = new DataArrayTexture(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } +} + +class Data3DTexture extends Texture { + constructor(data2 = null, width2 = 1, height2 = 1, depth = 1) { + super(null); + this.isData3DTexture = true; + this.image = { data: data2, width: width2, height: height2, depth }; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.wrapR = ClampToEdgeWrapping; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } +} + +class WebGL3DRenderTarget extends WebGLRenderTarget { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isWebGL3DRenderTarget = true; + this.depth = depth; + this.texture = new Data3DTexture(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } +} + +class Quaternion { + constructor(x = 0, y = 0, z = 0, w = 1) { + this.isQuaternion = true; + this._x = x; + this._y = y; + this._z = z; + this._w = w; + } + static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) { + let x0 = src0[srcOffset0 + 0], y0 = src0[srcOffset0 + 1], z0 = src0[srcOffset0 + 2], w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1 + 0], y1 = src1[srcOffset1 + 1], z1 = src1[srcOffset1 + 2], w1 = src1[srcOffset1 + 3]; + if (t === 0) { + dst[dstOffset + 0] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + return; + } + if (t === 1) { + dst[dstOffset + 0] = x1; + dst[dstOffset + 1] = y1; + dst[dstOffset + 2] = z1; + dst[dstOffset + 3] = w1; + return; + } + if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) { + let s = 1 - t; + const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, dir = cos >= 0 ? 1 : -1, sqrSin = 1 - cos * cos; + if (sqrSin > Number.EPSILON) { + const sin = Math.sqrt(sqrSin), len = Math.atan2(sin, cos * dir); + s = Math.sin(s * len) / sin; + t = Math.sin(t * len) / sin; + } + const tDir = t * dir; + x0 = x0 * s + x1 * tDir; + y0 = y0 * s + y1 * tDir; + z0 = z0 * s + z1 * tDir; + w0 = w0 * s + w1 * tDir; + if (s === 1 - t) { + const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0); + x0 *= f; + y0 *= f; + z0 *= f; + w0 *= f; + } + } + dst[dstOffset] = x0; + dst[dstOffset + 1] = y0; + dst[dstOffset + 2] = z0; + dst[dstOffset + 3] = w0; + } + static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) { + const x0 = src0[srcOffset0]; + const y0 = src0[srcOffset0 + 1]; + const z0 = src0[srcOffset0 + 2]; + const w0 = src0[srcOffset0 + 3]; + const x1 = src1[srcOffset1]; + const y1 = src1[srcOffset1 + 1]; + const z1 = src1[srcOffset1 + 2]; + const w1 = src1[srcOffset1 + 3]; + dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; + dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; + dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; + dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; + return dst; + } + get x() { + return this._x; + } + set x(value2) { + this._x = value2; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value2) { + this._y = value2; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value2) { + this._z = value2; + this._onChangeCallback(); + } + get w() { + return this._w; + } + set w(value2) { + this._w = value2; + this._onChangeCallback(); + } + set(x, y, z, w) { + this._x = x; + this._y = y; + this._z = z; + this._w = w; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._w); + } + copy(quaternion) { + this._x = quaternion.x; + this._y = quaternion.y; + this._z = quaternion.z; + this._w = quaternion.w; + this._onChangeCallback(); + return this; + } + setFromEuler(euler, update = true) { + const { _x: x, _y: y, _z: z, _order: order } = euler; + const cos = Math.cos; + const sin = Math.sin; + const c1 = cos(x / 2); + const c2 = cos(y / 2); + const c3 = cos(z / 2); + const s1 = sin(x / 2); + const s2 = sin(y / 2); + const s3 = sin(z / 2); + switch (order) { + case "XYZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "YXZ": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "ZXY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "ZYX": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + case "YZX": + this._x = s1 * c2 * c3 + c1 * s2 * s3; + this._y = c1 * s2 * c3 + s1 * c2 * s3; + this._z = c1 * c2 * s3 - s1 * s2 * c3; + this._w = c1 * c2 * c3 - s1 * s2 * s3; + break; + case "XZY": + this._x = s1 * c2 * c3 - c1 * s2 * s3; + this._y = c1 * s2 * c3 - s1 * c2 * s3; + this._z = c1 * c2 * s3 + s1 * s2 * c3; + this._w = c1 * c2 * c3 + s1 * s2 * s3; + break; + default: + console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + order); + } + if (update === true) + this._onChangeCallback(); + return this; + } + setFromAxisAngle(axis, angle) { + const halfAngle = angle / 2, s = Math.sin(halfAngle); + this._x = axis.x * s; + this._y = axis.y * s; + this._z = axis.z * s; + this._w = Math.cos(halfAngle); + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m) { + const te = m.elements, m11 = te[0], m12 = te[4], m13 = te[8], m21 = te[1], m22 = te[5], m23 = te[9], m31 = te[2], m32 = te[6], m33 = te[10], trace = m11 + m22 + m33; + if (trace > 0) { + const s = 0.5 / Math.sqrt(trace + 1); + this._w = 0.25 / s; + this._x = (m32 - m23) * s; + this._y = (m13 - m31) * s; + this._z = (m21 - m12) * s; + } else if (m11 > m22 && m11 > m33) { + const s = 2 * Math.sqrt(1 + m11 - m22 - m33); + this._w = (m32 - m23) / s; + this._x = 0.25 * s; + this._y = (m12 + m21) / s; + this._z = (m13 + m31) / s; + } else if (m22 > m33) { + const s = 2 * Math.sqrt(1 + m22 - m11 - m33); + this._w = (m13 - m31) / s; + this._x = (m12 + m21) / s; + this._y = 0.25 * s; + this._z = (m23 + m32) / s; + } else { + const s = 2 * Math.sqrt(1 + m33 - m11 - m22); + this._w = (m21 - m12) / s; + this._x = (m13 + m31) / s; + this._y = (m23 + m32) / s; + this._z = 0.25 * s; + } + this._onChangeCallback(); + return this; + } + setFromUnitVectors(vFrom, vTo) { + let r = vFrom.dot(vTo) + 1; + if (r < Number.EPSILON) { + r = 0; + if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) { + this._x = -vFrom.y; + this._y = vFrom.x; + this._z = 0; + this._w = r; + } else { + this._x = 0; + this._y = -vFrom.z; + this._z = vFrom.y; + this._w = r; + } + } else { + this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; + this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; + this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; + this._w = r; + } + return this.normalize(); + } + angleTo(q) { + return 2 * Math.acos(Math.abs(clamp2(this.dot(q), -1, 1))); + } + rotateTowards(q, step) { + const angle = this.angleTo(q); + if (angle === 0) + return this; + const t = Math.min(1, step / angle); + this.slerp(q, t); + return this; + } + identity() { + return this.set(0, 0, 0, 1); + } + invert() { + return this.conjugate(); + } + conjugate() { + this._x *= -1; + this._y *= -1; + this._z *= -1; + this._onChangeCallback(); + return this; + } + dot(v) { + return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; + } + lengthSq() { + return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; + } + length() { + return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); + } + normalize() { + let l = this.length(); + if (l === 0) { + this._x = 0; + this._y = 0; + this._z = 0; + this._w = 1; + } else { + l = 1 / l; + this._x = this._x * l; + this._y = this._y * l; + this._z = this._z * l; + this._w = this._w * l; + } + this._onChangeCallback(); + return this; + } + multiply(q) { + return this.multiplyQuaternions(this, q); + } + premultiply(q) { + return this.multiplyQuaternions(q, this); + } + multiplyQuaternions(a, b) { + const { _x: qax, _y: qay, _z: qaz, _w: qaw } = a; + const { _x: qbx, _y: qby, _z: qbz, _w: qbw } = b; + this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; + this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; + this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; + this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; + this._onChangeCallback(); + return this; + } + slerp(qb, t) { + if (t === 0) + return this; + if (t === 1) + return this.copy(qb); + const x = this._x, y = this._y, z = this._z, w = this._w; + let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z; + if (cosHalfTheta < 0) { + this._w = -qb._w; + this._x = -qb._x; + this._y = -qb._y; + this._z = -qb._z; + cosHalfTheta = -cosHalfTheta; + } else { + this.copy(qb); + } + if (cosHalfTheta >= 1) { + this._w = w; + this._x = x; + this._y = y; + this._z = z; + return this; + } + const sqrSinHalfTheta = 1 - cosHalfTheta * cosHalfTheta; + if (sqrSinHalfTheta <= Number.EPSILON) { + const s = 1 - t; + this._w = s * w + t * this._w; + this._x = s * x + t * this._x; + this._y = s * y + t * this._y; + this._z = s * z + t * this._z; + this.normalize(); + return this; + } + const sinHalfTheta = Math.sqrt(sqrSinHalfTheta); + const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta); + const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta, ratioB = Math.sin(t * halfTheta) / sinHalfTheta; + this._w = w * ratioA + this._w * ratioB; + this._x = x * ratioA + this._x * ratioB; + this._y = y * ratioA + this._y * ratioB; + this._z = z * ratioA + this._z * ratioB; + this._onChangeCallback(); + return this; + } + slerpQuaternions(qa, qb, t) { + return this.copy(qa).slerp(qb, t); + } + random() { + const theta1 = 2 * Math.PI * Math.random(); + const theta2 = 2 * Math.PI * Math.random(); + const x0 = Math.random(); + const r1 = Math.sqrt(1 - x0); + const r2 = Math.sqrt(x0); + return this.set(r1 * Math.sin(theta1), r1 * Math.cos(theta1), r2 * Math.sin(theta2), r2 * Math.cos(theta2)); + } + equals(quaternion) { + return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w; + } + fromArray(array, offset = 0) { + this._x = array[offset]; + this._y = array[offset + 1]; + this._z = array[offset + 2]; + this._w = array[offset + 3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._w; + return array; + } + fromBufferAttribute(attribute, index2) { + this._x = attribute.getX(index2); + this._y = attribute.getY(index2); + this._z = attribute.getZ(index2); + this._w = attribute.getW(index2); + this._onChangeCallback(); + return this; + } + toJSON() { + return this.toArray(); + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._w; + } +} + +class Vector3 { + constructor(x = 0, y = 0, z = 0) { + Vector3.prototype.isVector3 = true; + this.x = x; + this.y = y; + this.z = z; + } + set(x, y, z) { + if (z === undefined) + z = this.z; + this.x = x; + this.y = y; + this.z = z; + return this; + } + setScalar(scalar) { + this.x = scalar; + this.y = scalar; + this.z = scalar; + return this; + } + setX(x) { + this.x = x; + return this; + } + setY(y) { + this.y = y; + return this; + } + setZ(z) { + this.z = z; + return this; + } + setComponent(index2, value2) { + switch (index2) { + case 0: + this.x = value2; + break; + case 1: + this.y = value2; + break; + case 2: + this.z = value2; + break; + default: + throw new Error("index is out of range: " + index2); + } + return this; + } + getComponent(index2) { + switch (index2) { + case 0: + return this.x; + case 1: + return this.y; + case 2: + return this.z; + default: + throw new Error("index is out of range: " + index2); + } + } + clone() { + return new this.constructor(this.x, this.y, this.z); + } + copy(v) { + this.x = v.x; + this.y = v.y; + this.z = v.z; + return this; + } + add(v) { + this.x += v.x; + this.y += v.y; + this.z += v.z; + return this; + } + addScalar(s) { + this.x += s; + this.y += s; + this.z += s; + return this; + } + addVectors(a, b) { + this.x = a.x + b.x; + this.y = a.y + b.y; + this.z = a.z + b.z; + return this; + } + addScaledVector(v, s) { + this.x += v.x * s; + this.y += v.y * s; + this.z += v.z * s; + return this; + } + sub(v) { + this.x -= v.x; + this.y -= v.y; + this.z -= v.z; + return this; + } + subScalar(s) { + this.x -= s; + this.y -= s; + this.z -= s; + return this; + } + subVectors(a, b) { + this.x = a.x - b.x; + this.y = a.y - b.y; + this.z = a.z - b.z; + return this; + } + multiply(v) { + this.x *= v.x; + this.y *= v.y; + this.z *= v.z; + return this; + } + multiplyScalar(scalar) { + this.x *= scalar; + this.y *= scalar; + this.z *= scalar; + return this; + } + multiplyVectors(a, b) { + this.x = a.x * b.x; + this.y = a.y * b.y; + this.z = a.z * b.z; + return this; + } + applyEuler(euler) { + return this.applyQuaternion(_quaternion$4.setFromEuler(euler)); + } + applyAxisAngle(axis, angle) { + return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle)); + } + applyMatrix3(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + this.x = e[0] * x + e[3] * y + e[6] * z; + this.y = e[1] * x + e[4] * y + e[7] * z; + this.z = e[2] * x + e[5] * y + e[8] * z; + return this; + } + applyNormalMatrix(m) { + return this.applyMatrix3(m).normalize(); + } + applyMatrix4(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]); + this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w; + this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w; + this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w; + return this; + } + applyQuaternion(q) { + const vx = this.x, vy = this.y, vz = this.z; + const { x: qx, y: qy, z: qz, w: qw } = q; + const tx = 2 * (qy * vz - qz * vy); + const ty = 2 * (qz * vx - qx * vz); + const tz = 2 * (qx * vy - qy * vx); + this.x = vx + qw * tx + qy * tz - qz * ty; + this.y = vy + qw * ty + qz * tx - qx * tz; + this.z = vz + qw * tz + qx * ty - qy * tx; + return this; + } + project(camera) { + return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix); + } + unproject(camera) { + return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld); + } + transformDirection(m) { + const x = this.x, y = this.y, z = this.z; + const e = m.elements; + this.x = e[0] * x + e[4] * y + e[8] * z; + this.y = e[1] * x + e[5] * y + e[9] * z; + this.z = e[2] * x + e[6] * y + e[10] * z; + return this.normalize(); + } + divide(v) { + this.x /= v.x; + this.y /= v.y; + this.z /= v.z; + return this; + } + divideScalar(scalar) { + return this.multiplyScalar(1 / scalar); + } + min(v) { + this.x = Math.min(this.x, v.x); + this.y = Math.min(this.y, v.y); + this.z = Math.min(this.z, v.z); + return this; + } + max(v) { + this.x = Math.max(this.x, v.x); + this.y = Math.max(this.y, v.y); + this.z = Math.max(this.z, v.z); + return this; + } + clamp(min, max) { + this.x = clamp2(this.x, min.x, max.x); + this.y = clamp2(this.y, min.y, max.y); + this.z = clamp2(this.z, min.z, max.z); + return this; + } + clampScalar(minVal, maxVal) { + this.x = clamp2(this.x, minVal, maxVal); + this.y = clamp2(this.y, minVal, maxVal); + this.z = clamp2(this.z, minVal, maxVal); + return this; + } + clampLength(min, max) { + const length2 = this.length(); + return this.divideScalar(length2 || 1).multiplyScalar(clamp2(length2, min, max)); + } + floor() { + this.x = Math.floor(this.x); + this.y = Math.floor(this.y); + this.z = Math.floor(this.z); + return this; + } + ceil() { + this.x = Math.ceil(this.x); + this.y = Math.ceil(this.y); + this.z = Math.ceil(this.z); + return this; + } + round() { + this.x = Math.round(this.x); + this.y = Math.round(this.y); + this.z = Math.round(this.z); + return this; + } + roundToZero() { + this.x = Math.trunc(this.x); + this.y = Math.trunc(this.y); + this.z = Math.trunc(this.z); + return this; + } + negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + return this; + } + dot(v) { + return this.x * v.x + this.y * v.y + this.z * v.z; + } + lengthSq() { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); + } + manhattanLength() { + return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); + } + normalize() { + return this.divideScalar(this.length() || 1); + } + setLength(length2) { + return this.normalize().multiplyScalar(length2); + } + lerp(v, alpha) { + this.x += (v.x - this.x) * alpha; + this.y += (v.y - this.y) * alpha; + this.z += (v.z - this.z) * alpha; + return this; + } + lerpVectors(v1, v2, alpha) { + this.x = v1.x + (v2.x - v1.x) * alpha; + this.y = v1.y + (v2.y - v1.y) * alpha; + this.z = v1.z + (v2.z - v1.z) * alpha; + return this; + } + cross(v) { + return this.crossVectors(this, v); + } + crossVectors(a, b) { + const { x: ax, y: ay, z: az } = a; + const { x: bx, y: by, z: bz } = b; + this.x = ay * bz - az * by; + this.y = az * bx - ax * bz; + this.z = ax * by - ay * bx; + return this; + } + projectOnVector(v) { + const denominator = v.lengthSq(); + if (denominator === 0) + return this.set(0, 0, 0); + const scalar = v.dot(this) / denominator; + return this.copy(v).multiplyScalar(scalar); + } + projectOnPlane(planeNormal) { + _vector$c.copy(this).projectOnVector(planeNormal); + return this.sub(_vector$c); + } + reflect(normal) { + return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal))); + } + angleTo(v) { + const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); + if (denominator === 0) + return Math.PI / 2; + const theta = this.dot(v) / denominator; + return Math.acos(clamp2(theta, -1, 1)); + } + distanceTo(v) { + return Math.sqrt(this.distanceToSquared(v)); + } + distanceToSquared(v) { + const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; + return dx * dx + dy * dy + dz * dz; + } + manhattanDistanceTo(v) { + return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z); + } + setFromSpherical(s) { + return this.setFromSphericalCoords(s.radius, s.phi, s.theta); + } + setFromSphericalCoords(radius, phi, theta) { + const sinPhiRadius = Math.sin(phi) * radius; + this.x = sinPhiRadius * Math.sin(theta); + this.y = Math.cos(phi) * radius; + this.z = sinPhiRadius * Math.cos(theta); + return this; + } + setFromCylindrical(c) { + return this.setFromCylindricalCoords(c.radius, c.theta, c.y); + } + setFromCylindricalCoords(radius, theta, y) { + this.x = radius * Math.sin(theta); + this.y = y; + this.z = radius * Math.cos(theta); + return this; + } + setFromMatrixPosition(m) { + const e = m.elements; + this.x = e[12]; + this.y = e[13]; + this.z = e[14]; + return this; + } + setFromMatrixScale(m) { + const sx = this.setFromMatrixColumn(m, 0).length(); + const sy = this.setFromMatrixColumn(m, 1).length(); + const sz = this.setFromMatrixColumn(m, 2).length(); + this.x = sx; + this.y = sy; + this.z = sz; + return this; + } + setFromMatrixColumn(m, index2) { + return this.fromArray(m.elements, index2 * 4); + } + setFromMatrix3Column(m, index2) { + return this.fromArray(m.elements, index2 * 3); + } + setFromEuler(e) { + this.x = e._x; + this.y = e._y; + this.z = e._z; + return this; + } + setFromColor(c) { + this.x = c.r; + this.y = c.g; + this.z = c.b; + return this; + } + equals(v) { + return v.x === this.x && v.y === this.y && v.z === this.z; + } + fromArray(array, offset = 0) { + this.x = array[offset]; + this.y = array[offset + 1]; + this.z = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.x; + array[offset + 1] = this.y; + array[offset + 2] = this.z; + return array; + } + fromBufferAttribute(attribute, index2) { + this.x = attribute.getX(index2); + this.y = attribute.getY(index2); + this.z = attribute.getZ(index2); + return this; + } + random() { + this.x = Math.random(); + this.y = Math.random(); + this.z = Math.random(); + return this; + } + randomDirection() { + const theta = Math.random() * Math.PI * 2; + const u = Math.random() * 2 - 1; + const c = Math.sqrt(1 - u * u); + this.x = c * Math.cos(theta); + this.y = u; + this.z = c * Math.sin(theta); + return this; + } + *[Symbol.iterator]() { + yield this.x; + yield this.y; + yield this.z; + } +} +var _vector$c = /* @__PURE__ */ new Vector3; +var _quaternion$4 = /* @__PURE__ */ new Quaternion; + +class Box3 { + constructor(min = new Vector3(Infinity, Infinity, Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) { + this.isBox3 = true; + this.min = min; + this.max = max; + } + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + setFromArray(array) { + this.makeEmpty(); + for (let i = 0, il = array.length;i < il; i += 3) { + this.expandByPoint(_vector$b.fromArray(array, i)); + } + return this; + } + setFromBufferAttribute(attribute) { + this.makeEmpty(); + for (let i = 0, il = attribute.count;i < il; i++) { + this.expandByPoint(_vector$b.fromBufferAttribute(attribute, i)); + } + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length;i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size) { + const halfSize = _vector$b.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + setFromObject(object, precise = false) { + this.makeEmpty(); + return this.expandByObject(object, precise); + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = this.min.z = Infinity; + this.max.x = this.max.y = this.max.z = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + expandByObject(object, precise = false) { + object.updateWorldMatrix(false, false); + const geometry = object.geometry; + if (geometry !== undefined) { + const positionAttribute = geometry.getAttribute("position"); + if (precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true) { + for (let i = 0, l = positionAttribute.count;i < l; i++) { + if (object.isMesh === true) { + object.getVertexPosition(i, _vector$b); + } else { + _vector$b.fromBufferAttribute(positionAttribute, i); + } + _vector$b.applyMatrix4(object.matrixWorld); + this.expandByPoint(_vector$b); + } + } else { + if (object.boundingBox !== undefined) { + if (object.boundingBox === null) { + object.computeBoundingBox(); + } + _box$4.copy(object.boundingBox); + } else { + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + _box$4.copy(geometry.boundingBox); + } + _box$4.applyMatrix4(object.matrixWorld); + this.union(_box$4); + } + } + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + this.expandByObject(children[i], precise); + } + return this; + } + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y && point.z >= this.min.z && point.z <= this.max.z; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z; + } + getParameter(point, target) { + return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z)); + } + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y && box.max.z >= this.min.z && box.min.z <= this.max.z; + } + intersectsSphere(sphere) { + this.clampPoint(sphere.center, _vector$b); + return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; + } + intersectsPlane(plane) { + let min, max; + if (plane.normal.x > 0) { + min = plane.normal.x * this.min.x; + max = plane.normal.x * this.max.x; + } else { + min = plane.normal.x * this.max.x; + max = plane.normal.x * this.min.x; + } + if (plane.normal.y > 0) { + min += plane.normal.y * this.min.y; + max += plane.normal.y * this.max.y; + } else { + min += plane.normal.y * this.max.y; + max += plane.normal.y * this.min.y; + } + if (plane.normal.z > 0) { + min += plane.normal.z * this.min.z; + max += plane.normal.z * this.max.z; + } else { + min += plane.normal.z * this.max.z; + max += plane.normal.z * this.min.z; + } + return min <= -plane.constant && max >= -plane.constant; + } + intersectsTriangle(triangle) { + if (this.isEmpty()) { + return false; + } + this.getCenter(_center); + _extents.subVectors(this.max, _center); + _v0$2.subVectors(triangle.a, _center); + _v1$7.subVectors(triangle.b, _center); + _v2$4.subVectors(triangle.c, _center); + _f0.subVectors(_v1$7, _v0$2); + _f1.subVectors(_v2$4, _v1$7); + _f2.subVectors(_v0$2, _v2$4); + let axes = [ + 0, + -_f0.z, + _f0.y, + 0, + -_f1.z, + _f1.y, + 0, + -_f2.z, + _f2.y, + _f0.z, + 0, + -_f0.x, + _f1.z, + 0, + -_f1.x, + _f2.z, + 0, + -_f2.x, + -_f0.y, + _f0.x, + 0, + -_f1.y, + _f1.x, + 0, + -_f2.y, + _f2.x, + 0 + ]; + if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) { + return false; + } + axes = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) { + return false; + } + _triangleNormal.crossVectors(_f0, _f1); + axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z]; + return satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents); + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$b).distanceTo(point); + } + getBoundingSphere(target) { + if (this.isEmpty()) { + target.makeEmpty(); + } else { + this.getCenter(target.center); + target.radius = this.getSize(_vector$b).length() * 0.5; + } + return target; + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) + this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + applyMatrix4(matrix) { + if (this.isEmpty()) + return this; + _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); + _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); + _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); + _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); + _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); + this.setFromPoints(_points); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } +} +var _points = [ + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3, + /* @__PURE__ */ new Vector3 +]; +var _vector$b = /* @__PURE__ */ new Vector3; +var _box$4 = /* @__PURE__ */ new Box3; +var _v0$2 = /* @__PURE__ */ new Vector3; +var _v1$7 = /* @__PURE__ */ new Vector3; +var _v2$4 = /* @__PURE__ */ new Vector3; +var _f0 = /* @__PURE__ */ new Vector3; +var _f1 = /* @__PURE__ */ new Vector3; +var _f2 = /* @__PURE__ */ new Vector3; +var _center = /* @__PURE__ */ new Vector3; +var _extents = /* @__PURE__ */ new Vector3; +var _triangleNormal = /* @__PURE__ */ new Vector3; +var _testAxis = /* @__PURE__ */ new Vector3; +function satForAxes(axes, v0, v1, v2, extents) { + for (let i = 0, j = axes.length - 3;i <= j; i += 3) { + _testAxis.fromArray(axes, i); + const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); + const p0 = v0.dot(_testAxis); + const p1 = v1.dot(_testAxis); + const p2 = v2.dot(_testAxis); + if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) { + return false; + } + } + return true; +} +var _box$3 = /* @__PURE__ */ new Box3; +var _v1$6 = /* @__PURE__ */ new Vector3; +var _v2$3 = /* @__PURE__ */ new Vector3; + +class Sphere { + constructor(center = new Vector3, radius = -1) { + this.isSphere = true; + this.center = center; + this.radius = radius; + } + set(center, radius) { + this.center.copy(center); + this.radius = radius; + return this; + } + setFromPoints(points, optionalCenter) { + const center = this.center; + if (optionalCenter !== undefined) { + center.copy(optionalCenter); + } else { + _box$3.setFromPoints(points).getCenter(center); + } + let maxRadiusSq = 0; + for (let i = 0, il = points.length;i < il; i++) { + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i])); + } + this.radius = Math.sqrt(maxRadiusSq); + return this; + } + copy(sphere) { + this.center.copy(sphere.center); + this.radius = sphere.radius; + return this; + } + isEmpty() { + return this.radius < 0; + } + makeEmpty() { + this.center.set(0, 0, 0); + this.radius = -1; + return this; + } + containsPoint(point) { + return point.distanceToSquared(this.center) <= this.radius * this.radius; + } + distanceToPoint(point) { + return point.distanceTo(this.center) - this.radius; + } + intersectsSphere(sphere) { + const radiusSum = this.radius + sphere.radius; + return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum; + } + intersectsBox(box) { + return box.intersectsSphere(this); + } + intersectsPlane(plane) { + return Math.abs(plane.distanceToPoint(this.center)) <= this.radius; + } + clampPoint(point, target) { + const deltaLengthSq = this.center.distanceToSquared(point); + target.copy(point); + if (deltaLengthSq > this.radius * this.radius) { + target.sub(this.center).normalize(); + target.multiplyScalar(this.radius).add(this.center); + } + return target; + } + getBoundingBox(target) { + if (this.isEmpty()) { + target.makeEmpty(); + return target; + } + target.set(this.center, this.center); + target.expandByScalar(this.radius); + return target; + } + applyMatrix4(matrix) { + this.center.applyMatrix4(matrix); + this.radius = this.radius * matrix.getMaxScaleOnAxis(); + return this; + } + translate(offset) { + this.center.add(offset); + return this; + } + expandByPoint(point) { + if (this.isEmpty()) { + this.center.copy(point); + this.radius = 0; + return this; + } + _v1$6.subVectors(point, this.center); + const lengthSq = _v1$6.lengthSq(); + if (lengthSq > this.radius * this.radius) { + const length2 = Math.sqrt(lengthSq); + const delta = (length2 - this.radius) * 0.5; + this.center.addScaledVector(_v1$6, delta / length2); + this.radius += delta; + } + return this; + } + union(sphere) { + if (sphere.isEmpty()) { + return this; + } + if (this.isEmpty()) { + this.copy(sphere); + return this; + } + if (this.center.equals(sphere.center) === true) { + this.radius = Math.max(this.radius, sphere.radius); + } else { + _v2$3.subVectors(sphere.center, this.center).setLength(sphere.radius); + this.expandByPoint(_v1$6.copy(sphere.center).add(_v2$3)); + this.expandByPoint(_v1$6.copy(sphere.center).sub(_v2$3)); + } + return this; + } + equals(sphere) { + return sphere.center.equals(this.center) && sphere.radius === this.radius; + } + clone() { + return new this.constructor().copy(this); + } +} +var _vector$a = /* @__PURE__ */ new Vector3; +var _segCenter = /* @__PURE__ */ new Vector3; +var _segDir = /* @__PURE__ */ new Vector3; +var _diff = /* @__PURE__ */ new Vector3; +var _edge1 = /* @__PURE__ */ new Vector3; +var _edge2 = /* @__PURE__ */ new Vector3; +var _normal$1 = /* @__PURE__ */ new Vector3; + +class Ray { + constructor(origin = new Vector3, direction = new Vector3(0, 0, -1)) { + this.origin = origin; + this.direction = direction; + } + set(origin, direction) { + this.origin.copy(origin); + this.direction.copy(direction); + return this; + } + copy(ray) { + this.origin.copy(ray.origin); + this.direction.copy(ray.direction); + return this; + } + at(t, target) { + return target.copy(this.origin).addScaledVector(this.direction, t); + } + lookAt(v) { + this.direction.copy(v).sub(this.origin).normalize(); + return this; + } + recast(t) { + this.origin.copy(this.at(t, _vector$a)); + return this; + } + closestPointToPoint(point, target) { + target.subVectors(point, this.origin); + const directionDistance = target.dot(this.direction); + if (directionDistance < 0) { + return target.copy(this.origin); + } + return target.copy(this.origin).addScaledVector(this.direction, directionDistance); + } + distanceToPoint(point) { + return Math.sqrt(this.distanceSqToPoint(point)); + } + distanceSqToPoint(point) { + const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); + if (directionDistance < 0) { + return this.origin.distanceToSquared(point); + } + _vector$a.copy(this.origin).addScaledVector(this.direction, directionDistance); + return _vector$a.distanceToSquared(point); + } + distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) { + _segCenter.copy(v0).add(v1).multiplyScalar(0.5); + _segDir.copy(v1).sub(v0).normalize(); + _diff.copy(this.origin).sub(_segCenter); + const segExtent = v0.distanceTo(v1) * 0.5; + const a01 = -this.direction.dot(_segDir); + const b0 = _diff.dot(this.direction); + const b1 = -_diff.dot(_segDir); + const c = _diff.lengthSq(); + const det = Math.abs(1 - a01 * a01); + let s0, s1, sqrDist, extDet; + if (det > 0) { + s0 = a01 * b1 - b0; + s1 = a01 * b0 - b1; + extDet = segExtent * det; + if (s0 >= 0) { + if (s1 >= -extDet) { + if (s1 <= extDet) { + const invDet = 1 / det; + s0 *= invDet; + s1 *= invDet; + sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c; + } else { + s1 = segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } else { + s1 = -segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } else { + if (s1 <= -extDet) { + s0 = Math.max(0, -(-a01 * segExtent + b0)); + s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } else if (s1 <= extDet) { + s0 = 0; + s1 = Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = s1 * (s1 + 2 * b1) + c; + } else { + s0 = Math.max(0, -(a01 * segExtent + b0)); + s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + } + } else { + s1 = a01 > 0 ? -segExtent : segExtent; + s0 = Math.max(0, -(a01 * s1 + b0)); + sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; + } + if (optionalPointOnRay) { + optionalPointOnRay.copy(this.origin).addScaledVector(this.direction, s0); + } + if (optionalPointOnSegment) { + optionalPointOnSegment.copy(_segCenter).addScaledVector(_segDir, s1); + } + return sqrDist; + } + intersectSphere(sphere, target) { + _vector$a.subVectors(sphere.center, this.origin); + const tca = _vector$a.dot(this.direction); + const d2 = _vector$a.dot(_vector$a) - tca * tca; + const radius2 = sphere.radius * sphere.radius; + if (d2 > radius2) + return null; + const thc = Math.sqrt(radius2 - d2); + const t0 = tca - thc; + const t1 = tca + thc; + if (t1 < 0) + return null; + if (t0 < 0) + return this.at(t1, target); + return this.at(t0, target); + } + intersectsSphere(sphere) { + return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius; + } + distanceToPlane(plane) { + const denominator = plane.normal.dot(this.direction); + if (denominator === 0) { + if (plane.distanceToPoint(this.origin) === 0) { + return 0; + } + return null; + } + const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; + return t >= 0 ? t : null; + } + intersectPlane(plane, target) { + const t = this.distanceToPlane(plane); + if (t === null) { + return null; + } + return this.at(t, target); + } + intersectsPlane(plane) { + const distToPoint = plane.distanceToPoint(this.origin); + if (distToPoint === 0) { + return true; + } + const denominator = plane.normal.dot(this.direction); + if (denominator * distToPoint < 0) { + return true; + } + return false; + } + intersectBox(box, target) { + let tmin, tmax, tymin, tymax, tzmin, tzmax; + const invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z; + const origin = this.origin; + if (invdirx >= 0) { + tmin = (box.min.x - origin.x) * invdirx; + tmax = (box.max.x - origin.x) * invdirx; + } else { + tmin = (box.max.x - origin.x) * invdirx; + tmax = (box.min.x - origin.x) * invdirx; + } + if (invdiry >= 0) { + tymin = (box.min.y - origin.y) * invdiry; + tymax = (box.max.y - origin.y) * invdiry; + } else { + tymin = (box.max.y - origin.y) * invdiry; + tymax = (box.min.y - origin.y) * invdiry; + } + if (tmin > tymax || tymin > tmax) + return null; + if (tymin > tmin || isNaN(tmin)) + tmin = tymin; + if (tymax < tmax || isNaN(tmax)) + tmax = tymax; + if (invdirz >= 0) { + tzmin = (box.min.z - origin.z) * invdirz; + tzmax = (box.max.z - origin.z) * invdirz; + } else { + tzmin = (box.max.z - origin.z) * invdirz; + tzmax = (box.min.z - origin.z) * invdirz; + } + if (tmin > tzmax || tzmin > tmax) + return null; + if (tzmin > tmin || tmin !== tmin) + tmin = tzmin; + if (tzmax < tmax || tmax !== tmax) + tmax = tzmax; + if (tmax < 0) + return null; + return this.at(tmin >= 0 ? tmin : tmax, target); + } + intersectsBox(box) { + return this.intersectBox(box, _vector$a) !== null; + } + intersectTriangle(a, b, c, backfaceCulling, target) { + _edge1.subVectors(b, a); + _edge2.subVectors(c, a); + _normal$1.crossVectors(_edge1, _edge2); + let DdN = this.direction.dot(_normal$1); + let sign; + if (DdN > 0) { + if (backfaceCulling) + return null; + sign = 1; + } else if (DdN < 0) { + sign = -1; + DdN = -DdN; + } else { + return null; + } + _diff.subVectors(this.origin, a); + const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); + if (DdQxE2 < 0) { + return null; + } + const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); + if (DdE1xQ < 0) { + return null; + } + if (DdQxE2 + DdE1xQ > DdN) { + return null; + } + const QdN = -sign * _diff.dot(_normal$1); + if (QdN < 0) { + return null; + } + return this.at(QdN / DdN, target); + } + applyMatrix4(matrix4) { + this.origin.applyMatrix4(matrix4); + this.direction.transformDirection(matrix4); + return this; + } + equals(ray) { + return ray.origin.equals(this.origin) && ray.direction.equals(this.direction); + } + clone() { + return new this.constructor().copy(this); + } +} + +class Matrix4 { + constructor(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + Matrix4.prototype.isMatrix4 = true; + this.elements = [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44); + } + } + set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { + const te = this.elements; + te[0] = n11; + te[4] = n12; + te[8] = n13; + te[12] = n14; + te[1] = n21; + te[5] = n22; + te[9] = n23; + te[13] = n24; + te[2] = n31; + te[6] = n32; + te[10] = n33; + te[14] = n34; + te[3] = n41; + te[7] = n42; + te[11] = n43; + te[15] = n44; + return this; + } + identity() { + this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return this; + } + clone() { + return new Matrix4().fromArray(this.elements); + } + copy(m) { + const te = this.elements; + const me = m.elements; + te[0] = me[0]; + te[1] = me[1]; + te[2] = me[2]; + te[3] = me[3]; + te[4] = me[4]; + te[5] = me[5]; + te[6] = me[6]; + te[7] = me[7]; + te[8] = me[8]; + te[9] = me[9]; + te[10] = me[10]; + te[11] = me[11]; + te[12] = me[12]; + te[13] = me[13]; + te[14] = me[14]; + te[15] = me[15]; + return this; + } + copyPosition(m) { + const te = this.elements, me = m.elements; + te[12] = me[12]; + te[13] = me[13]; + te[14] = me[14]; + return this; + } + setFromMatrix3(m) { + const me = m.elements; + this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1); + return this; + } + extractBasis(xAxis, yAxis, zAxis) { + xAxis.setFromMatrixColumn(this, 0); + yAxis.setFromMatrixColumn(this, 1); + zAxis.setFromMatrixColumn(this, 2); + return this; + } + makeBasis(xAxis, yAxis, zAxis) { + this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1); + return this; + } + extractRotation(m) { + const te = this.elements; + const me = m.elements; + const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length(); + const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length(); + const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length(); + te[0] = me[0] * scaleX; + te[1] = me[1] * scaleX; + te[2] = me[2] * scaleX; + te[3] = 0; + te[4] = me[4] * scaleY; + te[5] = me[5] * scaleY; + te[6] = me[6] * scaleY; + te[7] = 0; + te[8] = me[8] * scaleZ; + te[9] = me[9] * scaleZ; + te[10] = me[10] * scaleZ; + te[11] = 0; + te[12] = 0; + te[13] = 0; + te[14] = 0; + te[15] = 1; + return this; + } + makeRotationFromEuler(euler) { + const te = this.elements; + const { x, y, z } = euler; + const a = Math.cos(x), b = Math.sin(x); + const c = Math.cos(y), d = Math.sin(y); + const e = Math.cos(z), f = Math.sin(z); + if (euler.order === "XYZ") { + const ae = a * e, af = a * f, be = b * e, bf = b * f; + te[0] = c * e; + te[4] = -c * f; + te[8] = d; + te[1] = af + be * d; + te[5] = ae - bf * d; + te[9] = -b * c; + te[2] = bf - ae * d; + te[6] = be + af * d; + te[10] = a * c; + } else if (euler.order === "YXZ") { + const ce = c * e, cf = c * f, de = d * e, df = d * f; + te[0] = ce + df * b; + te[4] = de * b - cf; + te[8] = a * d; + te[1] = a * f; + te[5] = a * e; + te[9] = -b; + te[2] = cf * b - de; + te[6] = df + ce * b; + te[10] = a * c; + } else if (euler.order === "ZXY") { + const ce = c * e, cf = c * f, de = d * e, df = d * f; + te[0] = ce - df * b; + te[4] = -a * f; + te[8] = de + cf * b; + te[1] = cf + de * b; + te[5] = a * e; + te[9] = df - ce * b; + te[2] = -a * d; + te[6] = b; + te[10] = a * c; + } else if (euler.order === "ZYX") { + const ae = a * e, af = a * f, be = b * e, bf = b * f; + te[0] = c * e; + te[4] = be * d - af; + te[8] = ae * d + bf; + te[1] = c * f; + te[5] = bf * d + ae; + te[9] = af * d - be; + te[2] = -d; + te[6] = b * c; + te[10] = a * c; + } else if (euler.order === "YZX") { + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + te[0] = c * e; + te[4] = bd - ac * f; + te[8] = bc * f + ad; + te[1] = f; + te[5] = a * e; + te[9] = -b * e; + te[2] = -d * e; + te[6] = ad * f + bc; + te[10] = ac - bd * f; + } else if (euler.order === "XZY") { + const ac = a * c, ad = a * d, bc = b * c, bd = b * d; + te[0] = c * e; + te[4] = -f; + te[8] = d * e; + te[1] = ac * f + bd; + te[5] = a * e; + te[9] = ad * f - bc; + te[2] = bc * f - ad; + te[6] = b * e; + te[10] = bd * f + ac; + } + te[3] = 0; + te[7] = 0; + te[11] = 0; + te[12] = 0; + te[13] = 0; + te[14] = 0; + te[15] = 1; + return this; + } + makeRotationFromQuaternion(q) { + return this.compose(_zero, q, _one); + } + lookAt(eye, target, up) { + const te = this.elements; + _z.subVectors(eye, target); + if (_z.lengthSq() === 0) { + _z.z = 1; + } + _z.normalize(); + _x.crossVectors(up, _z); + if (_x.lengthSq() === 0) { + if (Math.abs(up.z) === 1) { + _z.x += 0.0001; + } else { + _z.z += 0.0001; + } + _z.normalize(); + _x.crossVectors(up, _z); + } + _x.normalize(); + _y.crossVectors(_z, _x); + te[0] = _x.x; + te[4] = _y.x; + te[8] = _z.x; + te[1] = _x.y; + te[5] = _y.y; + te[9] = _z.y; + te[2] = _x.z; + te[6] = _y.z; + te[10] = _z.z; + return this; + } + multiply(m) { + return this.multiplyMatrices(this, m); + } + premultiply(m) { + return this.multiplyMatrices(m, this); + } + multiplyMatrices(a, b) { + const ae = a.elements; + const be = b.elements; + const te = this.elements; + const a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12]; + const a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13]; + const a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14]; + const a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15]; + const b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; + const b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; + const b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; + const b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; + te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; + te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; + te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; + te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; + te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; + te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; + te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; + te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; + te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; + te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; + te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; + te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; + te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; + te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; + te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; + te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; + return this; + } + multiplyScalar(s) { + const te = this.elements; + te[0] *= s; + te[4] *= s; + te[8] *= s; + te[12] *= s; + te[1] *= s; + te[5] *= s; + te[9] *= s; + te[13] *= s; + te[2] *= s; + te[6] *= s; + te[10] *= s; + te[14] *= s; + te[3] *= s; + te[7] *= s; + te[11] *= s; + te[15] *= s; + return this; + } + determinant() { + const te = this.elements; + const n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12]; + const n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13]; + const n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14]; + const n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15]; + return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31); + } + transpose() { + const te = this.elements; + let tmp; + tmp = te[1]; + te[1] = te[4]; + te[4] = tmp; + tmp = te[2]; + te[2] = te[8]; + te[8] = tmp; + tmp = te[6]; + te[6] = te[9]; + te[9] = tmp; + tmp = te[3]; + te[3] = te[12]; + te[12] = tmp; + tmp = te[7]; + te[7] = te[13]; + te[13] = tmp; + tmp = te[11]; + te[11] = te[14]; + te[14] = tmp; + return this; + } + setPosition(x, y, z) { + const te = this.elements; + if (x.isVector3) { + te[12] = x.x; + te[13] = x.y; + te[14] = x.z; + } else { + te[12] = x; + te[13] = y; + te[14] = z; + } + return this; + } + invert() { + const te = this.elements, n11 = te[0], n21 = te[1], n31 = te[2], n41 = te[3], n12 = te[4], n22 = te[5], n32 = te[6], n42 = te[7], n13 = te[8], n23 = te[9], n33 = te[10], n43 = te[11], n14 = te[12], n24 = te[13], n34 = te[14], n44 = te[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; + const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; + if (det === 0) + return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const detInv = 1 / det; + te[0] = t11 * detInv; + te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; + te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; + te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; + te[4] = t12 * detInv; + te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; + te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; + te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; + te[8] = t13 * detInv; + te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; + te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; + te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; + te[12] = t14 * detInv; + te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; + te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; + te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; + return this; + } + scale(v) { + const te = this.elements; + const { x, y, z } = v; + te[0] *= x; + te[4] *= y; + te[8] *= z; + te[1] *= x; + te[5] *= y; + te[9] *= z; + te[2] *= x; + te[6] *= y; + te[10] *= z; + te[3] *= x; + te[7] *= y; + te[11] *= z; + return this; + } + getMaxScaleOnAxis() { + const te = this.elements; + const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2]; + const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6]; + const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10]; + return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); + } + makeTranslation(x, y, z) { + if (x.isVector3) { + this.set(1, 0, 0, x.x, 0, 1, 0, x.y, 0, 0, 1, x.z, 0, 0, 0, 1); + } else { + this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1); + } + return this; + } + makeRotationX(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1); + return this; + } + makeRotationY(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1); + return this; + } + makeRotationZ(theta) { + const c = Math.cos(theta), s = Math.sin(theta); + this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + return this; + } + makeRotationAxis(axis, angle) { + const c = Math.cos(angle); + const s = Math.sin(angle); + const t = 1 - c; + const { x, y, z } = axis; + const tx = t * x, ty = t * y; + this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1); + return this; + } + makeScale(x, y, z) { + this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); + return this; + } + makeShear(xy, xz, yx, yz, zx, zy) { + this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1); + return this; + } + compose(position2, quaternion, scale2) { + const te = this.elements; + const { _x: x, _y: y, _z: z, _w: w } = quaternion; + const x2 = x + x, y2 = y + y, z2 = z + z; + const xx = x * x2, xy = x * y2, xz = x * z2; + const yy = y * y2, yz = y * z2, zz = z * z2; + const wx = w * x2, wy = w * y2, wz = w * z2; + const { x: sx, y: sy, z: sz } = scale2; + te[0] = (1 - (yy + zz)) * sx; + te[1] = (xy + wz) * sx; + te[2] = (xz - wy) * sx; + te[3] = 0; + te[4] = (xy - wz) * sy; + te[5] = (1 - (xx + zz)) * sy; + te[6] = (yz + wx) * sy; + te[7] = 0; + te[8] = (xz + wy) * sz; + te[9] = (yz - wx) * sz; + te[10] = (1 - (xx + yy)) * sz; + te[11] = 0; + te[12] = position2.x; + te[13] = position2.y; + te[14] = position2.z; + te[15] = 1; + return this; + } + decompose(position2, quaternion, scale2) { + const te = this.elements; + let sx = _v1$5.set(te[0], te[1], te[2]).length(); + const sy = _v1$5.set(te[4], te[5], te[6]).length(); + const sz = _v1$5.set(te[8], te[9], te[10]).length(); + const det = this.determinant(); + if (det < 0) + sx = -sx; + position2.x = te[12]; + position2.y = te[13]; + position2.z = te[14]; + _m1$2.copy(this); + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + _m1$2.elements[0] *= invSX; + _m1$2.elements[1] *= invSX; + _m1$2.elements[2] *= invSX; + _m1$2.elements[4] *= invSY; + _m1$2.elements[5] *= invSY; + _m1$2.elements[6] *= invSY; + _m1$2.elements[8] *= invSZ; + _m1$2.elements[9] *= invSZ; + _m1$2.elements[10] *= invSZ; + quaternion.setFromRotationMatrix(_m1$2); + scale2.x = sx; + scale2.y = sy; + scale2.z = sz; + return this; + } + makePerspective(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem) { + const te = this.elements; + const x = 2 * near / (right - left); + const y = 2 * near / (top - bottom); + const a = (right + left) / (right - left); + const b = (top + bottom) / (top - bottom); + let c, d; + if (coordinateSystem === WebGLCoordinateSystem) { + c = -(far + near) / (far - near); + d = -2 * far * near / (far - near); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + c = -far / (far - near); + d = -far * near / (far - near); + } else { + throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + coordinateSystem); + } + te[0] = x; + te[4] = 0; + te[8] = a; + te[12] = 0; + te[1] = 0; + te[5] = y; + te[9] = b; + te[13] = 0; + te[2] = 0; + te[6] = 0; + te[10] = c; + te[14] = d; + te[3] = 0; + te[7] = 0; + te[11] = -1; + te[15] = 0; + return this; + } + makeOrthographic(left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem) { + const te = this.elements; + const w = 1 / (right - left); + const h = 1 / (top - bottom); + const p = 1 / (far - near); + const x = (right + left) * w; + const y = (top + bottom) * h; + let z, zInv; + if (coordinateSystem === WebGLCoordinateSystem) { + z = (far + near) * p; + zInv = -2 * p; + } else if (coordinateSystem === WebGPUCoordinateSystem) { + z = near * p; + zInv = -1 * p; + } else { + throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + coordinateSystem); + } + te[0] = 2 * w; + te[4] = 0; + te[8] = 0; + te[12] = -x; + te[1] = 0; + te[5] = 2 * h; + te[9] = 0; + te[13] = -y; + te[2] = 0; + te[6] = 0; + te[10] = zInv; + te[14] = -z; + te[3] = 0; + te[7] = 0; + te[11] = 0; + te[15] = 1; + return this; + } + equals(matrix) { + const te = this.elements; + const me = matrix.elements; + for (let i = 0;i < 16; i++) { + if (te[i] !== me[i]) + return false; + } + return true; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 16; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + toArray(array = [], offset = 0) { + const te = this.elements; + array[offset] = te[0]; + array[offset + 1] = te[1]; + array[offset + 2] = te[2]; + array[offset + 3] = te[3]; + array[offset + 4] = te[4]; + array[offset + 5] = te[5]; + array[offset + 6] = te[6]; + array[offset + 7] = te[7]; + array[offset + 8] = te[8]; + array[offset + 9] = te[9]; + array[offset + 10] = te[10]; + array[offset + 11] = te[11]; + array[offset + 12] = te[12]; + array[offset + 13] = te[13]; + array[offset + 14] = te[14]; + array[offset + 15] = te[15]; + return array; + } +} +var _v1$5 = /* @__PURE__ */ new Vector3; +var _m1$2 = /* @__PURE__ */ new Matrix4; +var _zero = /* @__PURE__ */ new Vector3(0, 0, 0); +var _one = /* @__PURE__ */ new Vector3(1, 1, 1); +var _x = /* @__PURE__ */ new Vector3; +var _y = /* @__PURE__ */ new Vector3; +var _z = /* @__PURE__ */ new Vector3; +var _matrix$2 = /* @__PURE__ */ new Matrix4; +var _quaternion$3 = /* @__PURE__ */ new Quaternion; + +class Euler { + constructor(x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER) { + this.isEuler = true; + this._x = x; + this._y = y; + this._z = z; + this._order = order; + } + get x() { + return this._x; + } + set x(value2) { + this._x = value2; + this._onChangeCallback(); + } + get y() { + return this._y; + } + set y(value2) { + this._y = value2; + this._onChangeCallback(); + } + get z() { + return this._z; + } + set z(value2) { + this._z = value2; + this._onChangeCallback(); + } + get order() { + return this._order; + } + set order(value2) { + this._order = value2; + this._onChangeCallback(); + } + set(x, y, z, order = this._order) { + this._x = x; + this._y = y; + this._z = z; + this._order = order; + this._onChangeCallback(); + return this; + } + clone() { + return new this.constructor(this._x, this._y, this._z, this._order); + } + copy(euler) { + this._x = euler._x; + this._y = euler._y; + this._z = euler._z; + this._order = euler._order; + this._onChangeCallback(); + return this; + } + setFromRotationMatrix(m, order = this._order, update = true) { + const te = m.elements; + const m11 = te[0], m12 = te[4], m13 = te[8]; + const m21 = te[1], m22 = te[5], m23 = te[9]; + const m31 = te[2], m32 = te[6], m33 = te[10]; + switch (order) { + case "XYZ": + this._y = Math.asin(clamp2(m13, -1, 1)); + if (Math.abs(m13) < 0.9999999) { + this._x = Math.atan2(-m23, m33); + this._z = Math.atan2(-m12, m11); + } else { + this._x = Math.atan2(m32, m22); + this._z = 0; + } + break; + case "YXZ": + this._x = Math.asin(-clamp2(m23, -1, 1)); + if (Math.abs(m23) < 0.9999999) { + this._y = Math.atan2(m13, m33); + this._z = Math.atan2(m21, m22); + } else { + this._y = Math.atan2(-m31, m11); + this._z = 0; + } + break; + case "ZXY": + this._x = Math.asin(clamp2(m32, -1, 1)); + if (Math.abs(m32) < 0.9999999) { + this._y = Math.atan2(-m31, m33); + this._z = Math.atan2(-m12, m22); + } else { + this._y = 0; + this._z = Math.atan2(m21, m11); + } + break; + case "ZYX": + this._y = Math.asin(-clamp2(m31, -1, 1)); + if (Math.abs(m31) < 0.9999999) { + this._x = Math.atan2(m32, m33); + this._z = Math.atan2(m21, m11); + } else { + this._x = 0; + this._z = Math.atan2(-m12, m22); + } + break; + case "YZX": + this._z = Math.asin(clamp2(m21, -1, 1)); + if (Math.abs(m21) < 0.9999999) { + this._x = Math.atan2(-m23, m22); + this._y = Math.atan2(-m31, m11); + } else { + this._x = 0; + this._y = Math.atan2(m13, m33); + } + break; + case "XZY": + this._z = Math.asin(-clamp2(m12, -1, 1)); + if (Math.abs(m12) < 0.9999999) { + this._x = Math.atan2(m32, m22); + this._y = Math.atan2(m13, m11); + } else { + this._x = Math.atan2(-m23, m33); + this._y = 0; + } + break; + default: + console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + order); + } + this._order = order; + if (update === true) + this._onChangeCallback(); + return this; + } + setFromQuaternion(q, order, update) { + _matrix$2.makeRotationFromQuaternion(q); + return this.setFromRotationMatrix(_matrix$2, order, update); + } + setFromVector3(v, order = this._order) { + return this.set(v.x, v.y, v.z, order); + } + reorder(newOrder) { + _quaternion$3.setFromEuler(this); + return this.setFromQuaternion(_quaternion$3, newOrder); + } + equals(euler) { + return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order; + } + fromArray(array) { + this._x = array[0]; + this._y = array[1]; + this._z = array[2]; + if (array[3] !== undefined) + this._order = array[3]; + this._onChangeCallback(); + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this._x; + array[offset + 1] = this._y; + array[offset + 2] = this._z; + array[offset + 3] = this._order; + return array; + } + _onChange(callback) { + this._onChangeCallback = callback; + return this; + } + _onChangeCallback() { + } + *[Symbol.iterator]() { + yield this._x; + yield this._y; + yield this._z; + yield this._order; + } +} +Euler.DEFAULT_ORDER = "XYZ"; + +class Layers { + constructor() { + this.mask = 1 | 0; + } + set(channel) { + this.mask = (1 << channel | 0) >>> 0; + } + enable(channel) { + this.mask |= 1 << channel | 0; + } + enableAll() { + this.mask = 4294967295 | 0; + } + toggle(channel) { + this.mask ^= 1 << channel | 0; + } + disable(channel) { + this.mask &= ~(1 << channel | 0); + } + disableAll() { + this.mask = 0; + } + test(layers) { + return (this.mask & layers.mask) !== 0; + } + isEnabled(channel) { + return (this.mask & (1 << channel | 0)) !== 0; + } +} +var _object3DId = 0; +var _v1$4 = /* @__PURE__ */ new Vector3; +var _q1 = /* @__PURE__ */ new Quaternion; +var _m1$1 = /* @__PURE__ */ new Matrix4; +var _target = /* @__PURE__ */ new Vector3; +var _position$3 = /* @__PURE__ */ new Vector3; +var _scale$2 = /* @__PURE__ */ new Vector3; +var _quaternion$2 = /* @__PURE__ */ new Quaternion; +var _xAxis = /* @__PURE__ */ new Vector3(1, 0, 0); +var _yAxis = /* @__PURE__ */ new Vector3(0, 1, 0); +var _zAxis = /* @__PURE__ */ new Vector3(0, 0, 1); +var _addedEvent = { type: "added" }; +var _removedEvent = { type: "removed" }; +var _childaddedEvent = { type: "childadded", child: null }; +var _childremovedEvent = { type: "childremoved", child: null }; + +class Object3D extends EventDispatcher { + constructor() { + super(); + this.isObject3D = true; + Object.defineProperty(this, "id", { value: _object3DId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "Object3D"; + this.parent = null; + this.children = []; + this.up = Object3D.DEFAULT_UP.clone(); + const position2 = new Vector3; + const rotation2 = new Euler; + const quaternion = new Quaternion; + const scale2 = new Vector3(1, 1, 1); + function onRotationChange() { + quaternion.setFromEuler(rotation2, false); + } + function onQuaternionChange() { + rotation2.setFromQuaternion(quaternion, undefined, false); + } + rotation2._onChange(onRotationChange); + quaternion._onChange(onQuaternionChange); + Object.defineProperties(this, { + position: { + configurable: true, + enumerable: true, + value: position2 + }, + rotation: { + configurable: true, + enumerable: true, + value: rotation2 + }, + quaternion: { + configurable: true, + enumerable: true, + value: quaternion + }, + scale: { + configurable: true, + enumerable: true, + value: scale2 + }, + modelViewMatrix: { + value: new Matrix4 + }, + normalMatrix: { + value: new Matrix3 + } + }); + this.matrix = new Matrix4; + this.matrixWorld = new Matrix4; + this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE; + this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; + this.matrixWorldNeedsUpdate = false; + this.layers = new Layers; + this.visible = true; + this.castShadow = false; + this.receiveShadow = false; + this.frustumCulled = true; + this.renderOrder = 0; + this.animations = []; + this.userData = {}; + } + onBeforeShadow() { + } + onAfterShadow() { + } + onBeforeRender() { + } + onAfterRender() { + } + applyMatrix4(matrix) { + if (this.matrixAutoUpdate) + this.updateMatrix(); + this.matrix.premultiply(matrix); + this.matrix.decompose(this.position, this.quaternion, this.scale); + } + applyQuaternion(q) { + this.quaternion.premultiply(q); + return this; + } + setRotationFromAxisAngle(axis, angle) { + this.quaternion.setFromAxisAngle(axis, angle); + } + setRotationFromEuler(euler) { + this.quaternion.setFromEuler(euler, true); + } + setRotationFromMatrix(m) { + this.quaternion.setFromRotationMatrix(m); + } + setRotationFromQuaternion(q) { + this.quaternion.copy(q); + } + rotateOnAxis(axis, angle) { + _q1.setFromAxisAngle(axis, angle); + this.quaternion.multiply(_q1); + return this; + } + rotateOnWorldAxis(axis, angle) { + _q1.setFromAxisAngle(axis, angle); + this.quaternion.premultiply(_q1); + return this; + } + rotateX(angle) { + return this.rotateOnAxis(_xAxis, angle); + } + rotateY(angle) { + return this.rotateOnAxis(_yAxis, angle); + } + rotateZ(angle) { + return this.rotateOnAxis(_zAxis, angle); + } + translateOnAxis(axis, distance) { + _v1$4.copy(axis).applyQuaternion(this.quaternion); + this.position.add(_v1$4.multiplyScalar(distance)); + return this; + } + translateX(distance) { + return this.translateOnAxis(_xAxis, distance); + } + translateY(distance) { + return this.translateOnAxis(_yAxis, distance); + } + translateZ(distance) { + return this.translateOnAxis(_zAxis, distance); + } + localToWorld(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(this.matrixWorld); + } + worldToLocal(vector) { + this.updateWorldMatrix(true, false); + return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert()); + } + lookAt(x, y, z) { + if (x.isVector3) { + _target.copy(x); + } else { + _target.set(x, y, z); + } + const parent2 = this.parent; + this.updateWorldMatrix(true, false); + _position$3.setFromMatrixPosition(this.matrixWorld); + if (this.isCamera || this.isLight) { + _m1$1.lookAt(_position$3, _target, this.up); + } else { + _m1$1.lookAt(_target, _position$3, this.up); + } + this.quaternion.setFromRotationMatrix(_m1$1); + if (parent2) { + _m1$1.extractRotation(parent2.matrixWorld); + _q1.setFromRotationMatrix(_m1$1); + this.quaternion.premultiply(_q1.invert()); + } + } + add(object) { + if (arguments.length > 1) { + for (let i = 0;i < arguments.length; i++) { + this.add(arguments[i]); + } + return this; + } + if (object === this) { + console.error("THREE.Object3D.add: object can't be added as a child of itself.", object); + return this; + } + if (object && object.isObject3D) { + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.dispatchEvent(_addedEvent); + _childaddedEvent.child = object; + this.dispatchEvent(_childaddedEvent); + _childaddedEvent.child = null; + } else { + console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object); + } + return this; + } + remove(object) { + if (arguments.length > 1) { + for (let i = 0;i < arguments.length; i++) { + this.remove(arguments[i]); + } + return this; + } + const index2 = this.children.indexOf(object); + if (index2 !== -1) { + object.parent = null; + this.children.splice(index2, 1); + object.dispatchEvent(_removedEvent); + _childremovedEvent.child = object; + this.dispatchEvent(_childremovedEvent); + _childremovedEvent.child = null; + } + return this; + } + removeFromParent() { + const parent2 = this.parent; + if (parent2 !== null) { + parent2.remove(this); + } + return this; + } + clear() { + return this.remove(...this.children); + } + attach(object) { + this.updateWorldMatrix(true, false); + _m1$1.copy(this.matrixWorld).invert(); + if (object.parent !== null) { + object.parent.updateWorldMatrix(true, false); + _m1$1.multiply(object.parent.matrixWorld); + } + object.applyMatrix4(_m1$1); + object.removeFromParent(); + object.parent = this; + this.children.push(object); + object.updateWorldMatrix(false, true); + object.dispatchEvent(_addedEvent); + _childaddedEvent.child = object; + this.dispatchEvent(_childaddedEvent); + _childaddedEvent.child = null; + return this; + } + getObjectById(id) { + return this.getObjectByProperty("id", id); + } + getObjectByName(name2) { + return this.getObjectByProperty("name", name2); + } + getObjectByProperty(name2, value2) { + if (this[name2] === value2) + return this; + for (let i = 0, l = this.children.length;i < l; i++) { + const child = this.children[i]; + const object = child.getObjectByProperty(name2, value2); + if (object !== undefined) { + return object; + } + } + return; + } + getObjectsByProperty(name2, value2, result = []) { + if (this[name2] === value2) + result.push(this); + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + children[i].getObjectsByProperty(name2, value2, result); + } + return result; + } + getWorldPosition(target) { + this.updateWorldMatrix(true, false); + return target.setFromMatrixPosition(this.matrixWorld); + } + getWorldQuaternion(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$3, target, _scale$2); + return target; + } + getWorldScale(target) { + this.updateWorldMatrix(true, false); + this.matrixWorld.decompose(_position$3, _quaternion$2, target); + return target; + } + getWorldDirection(target) { + this.updateWorldMatrix(true, false); + const e = this.matrixWorld.elements; + return target.set(e[8], e[9], e[10]).normalize(); + } + raycast() { + } + traverse(callback) { + callback(this); + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + children[i].traverse(callback); + } + } + traverseVisible(callback) { + if (this.visible === false) + return; + callback(this); + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + children[i].traverseVisible(callback); + } + } + traverseAncestors(callback) { + const parent2 = this.parent; + if (parent2 !== null) { + callback(parent2); + parent2.traverseAncestors(callback); + } + } + updateMatrix() { + this.matrix.compose(this.position, this.quaternion, this.scale); + this.matrixWorldNeedsUpdate = true; + } + updateMatrixWorld(force) { + if (this.matrixAutoUpdate) + this.updateMatrix(); + if (this.matrixWorldNeedsUpdate || force) { + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + this.matrixWorldNeedsUpdate = false; + force = true; + } + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + const child = children[i]; + child.updateMatrixWorld(force); + } + } + updateWorldMatrix(updateParents, updateChildren) { + const parent2 = this.parent; + if (updateParents === true && parent2 !== null) { + parent2.updateWorldMatrix(true, false); + } + if (this.matrixAutoUpdate) + this.updateMatrix(); + if (this.matrixWorldAutoUpdate === true) { + if (this.parent === null) { + this.matrixWorld.copy(this.matrix); + } else { + this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); + } + } + if (updateChildren === true) { + const children = this.children; + for (let i = 0, l = children.length;i < l; i++) { + const child = children[i]; + child.updateWorldMatrix(false, true); + } + } + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + const output = {}; + if (isRootObject) { + meta = { + geometries: {}, + materials: {}, + textures: {}, + images: {}, + shapes: {}, + skeletons: {}, + animations: {}, + nodes: {} + }; + output.metadata = { + version: 4.6, + type: "Object", + generator: "Object3D.toJSON" + }; + } + const object = {}; + object.uuid = this.uuid; + object.type = this.type; + if (this.name !== "") + object.name = this.name; + if (this.castShadow === true) + object.castShadow = true; + if (this.receiveShadow === true) + object.receiveShadow = true; + if (this.visible === false) + object.visible = false; + if (this.frustumCulled === false) + object.frustumCulled = false; + if (this.renderOrder !== 0) + object.renderOrder = this.renderOrder; + if (Object.keys(this.userData).length > 0) + object.userData = this.userData; + object.layers = this.layers.mask; + object.matrix = this.matrix.toArray(); + object.up = this.up.toArray(); + if (this.matrixAutoUpdate === false) + object.matrixAutoUpdate = false; + if (this.isInstancedMesh) { + object.type = "InstancedMesh"; + object.count = this.count; + object.instanceMatrix = this.instanceMatrix.toJSON(); + if (this.instanceColor !== null) + object.instanceColor = this.instanceColor.toJSON(); + } + if (this.isBatchedMesh) { + object.type = "BatchedMesh"; + object.perObjectFrustumCulled = this.perObjectFrustumCulled; + object.sortObjects = this.sortObjects; + object.drawRanges = this._drawRanges; + object.reservedRanges = this._reservedRanges; + object.visibility = this._visibility; + object.active = this._active; + object.bounds = this._bounds.map((bound) => ({ + boxInitialized: bound.boxInitialized, + boxMin: bound.box.min.toArray(), + boxMax: bound.box.max.toArray(), + sphereInitialized: bound.sphereInitialized, + sphereRadius: bound.sphere.radius, + sphereCenter: bound.sphere.center.toArray() + })); + object.maxInstanceCount = this._maxInstanceCount; + object.maxVertexCount = this._maxVertexCount; + object.maxIndexCount = this._maxIndexCount; + object.geometryInitialized = this._geometryInitialized; + object.geometryCount = this._geometryCount; + object.matricesTexture = this._matricesTexture.toJSON(meta); + if (this._colorsTexture !== null) + object.colorsTexture = this._colorsTexture.toJSON(meta); + if (this.boundingSphere !== null) { + object.boundingSphere = { + center: object.boundingSphere.center.toArray(), + radius: object.boundingSphere.radius + }; + } + if (this.boundingBox !== null) { + object.boundingBox = { + min: object.boundingBox.min.toArray(), + max: object.boundingBox.max.toArray() + }; + } + } + function serialize(library, element) { + if (library[element.uuid] === undefined) { + library[element.uuid] = element.toJSON(meta); + } + return element.uuid; + } + if (this.isScene) { + if (this.background) { + if (this.background.isColor) { + object.background = this.background.toJSON(); + } else if (this.background.isTexture) { + object.background = this.background.toJSON(meta).uuid; + } + } + if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) { + object.environment = this.environment.toJSON(meta).uuid; + } + } else if (this.isMesh || this.isLine || this.isPoints) { + object.geometry = serialize(meta.geometries, this.geometry); + const parameters = this.geometry.parameters; + if (parameters !== undefined && parameters.shapes !== undefined) { + const shapes = parameters.shapes; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + serialize(meta.shapes, shape); + } + } else { + serialize(meta.shapes, shapes); + } + } + } + if (this.isSkinnedMesh) { + object.bindMode = this.bindMode; + object.bindMatrix = this.bindMatrix.toArray(); + if (this.skeleton !== undefined) { + serialize(meta.skeletons, this.skeleton); + object.skeleton = this.skeleton.uuid; + } + } + if (this.material !== undefined) { + if (Array.isArray(this.material)) { + const uuids = []; + for (let i = 0, l = this.material.length;i < l; i++) { + uuids.push(serialize(meta.materials, this.material[i])); + } + object.material = uuids; + } else { + object.material = serialize(meta.materials, this.material); + } + } + if (this.children.length > 0) { + object.children = []; + for (let i = 0;i < this.children.length; i++) { + object.children.push(this.children[i].toJSON(meta).object); + } + } + if (this.animations.length > 0) { + object.animations = []; + for (let i = 0;i < this.animations.length; i++) { + const animation = this.animations[i]; + object.animations.push(serialize(meta.animations, animation)); + } + } + if (isRootObject) { + const geometries = extractFromCache(meta.geometries); + const materials = extractFromCache(meta.materials); + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + const shapes = extractFromCache(meta.shapes); + const skeletons = extractFromCache(meta.skeletons); + const animations = extractFromCache(meta.animations); + const nodes = extractFromCache(meta.nodes); + if (geometries.length > 0) + output.geometries = geometries; + if (materials.length > 0) + output.materials = materials; + if (textures.length > 0) + output.textures = textures; + if (images.length > 0) + output.images = images; + if (shapes.length > 0) + output.shapes = shapes; + if (skeletons.length > 0) + output.skeletons = skeletons; + if (animations.length > 0) + output.animations = animations; + if (nodes.length > 0) + output.nodes = nodes; + } + output.object = object; + return output; + function extractFromCache(cache) { + const values2 = []; + for (const key2 in cache) { + const data2 = cache[key2]; + delete data2.metadata; + values2.push(data2); + } + return values2; + } + } + clone(recursive) { + return new this.constructor().copy(this, recursive); + } + copy(source, recursive = true) { + this.name = source.name; + this.up.copy(source.up); + this.position.copy(source.position); + this.rotation.order = source.rotation.order; + this.quaternion.copy(source.quaternion); + this.scale.copy(source.scale); + this.matrix.copy(source.matrix); + this.matrixWorld.copy(source.matrixWorld); + this.matrixAutoUpdate = source.matrixAutoUpdate; + this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; + this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; + this.layers.mask = source.layers.mask; + this.visible = source.visible; + this.castShadow = source.castShadow; + this.receiveShadow = source.receiveShadow; + this.frustumCulled = source.frustumCulled; + this.renderOrder = source.renderOrder; + this.animations = source.animations.slice(); + this.userData = JSON.parse(JSON.stringify(source.userData)); + if (recursive === true) { + for (let i = 0;i < source.children.length; i++) { + const child = source.children[i]; + this.add(child.clone()); + } + } + return this; + } +} +Object3D.DEFAULT_UP = /* @__PURE__ */ new Vector3(0, 1, 0); +Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true; +Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true; +var _v0$1 = /* @__PURE__ */ new Vector3; +var _v1$3 = /* @__PURE__ */ new Vector3; +var _v2$2 = /* @__PURE__ */ new Vector3; +var _v3$2 = /* @__PURE__ */ new Vector3; +var _vab = /* @__PURE__ */ new Vector3; +var _vac = /* @__PURE__ */ new Vector3; +var _vbc = /* @__PURE__ */ new Vector3; +var _vap = /* @__PURE__ */ new Vector3; +var _vbp = /* @__PURE__ */ new Vector3; +var _vcp = /* @__PURE__ */ new Vector3; +var _v40 = /* @__PURE__ */ new Vector4; +var _v41 = /* @__PURE__ */ new Vector4; +var _v42 = /* @__PURE__ */ new Vector4; + +class Triangle { + constructor(a = new Vector3, b = new Vector3, c = new Vector3) { + this.a = a; + this.b = b; + this.c = c; + } + static getNormal(a, b, c, target) { + target.subVectors(c, b); + _v0$1.subVectors(a, b); + target.cross(_v0$1); + const targetLengthSq = target.lengthSq(); + if (targetLengthSq > 0) { + return target.multiplyScalar(1 / Math.sqrt(targetLengthSq)); + } + return target.set(0, 0, 0); + } + static getBarycoord(point, a, b, c, target) { + _v0$1.subVectors(c, a); + _v1$3.subVectors(b, a); + _v2$2.subVectors(point, a); + const dot00 = _v0$1.dot(_v0$1); + const dot01 = _v0$1.dot(_v1$3); + const dot02 = _v0$1.dot(_v2$2); + const dot11 = _v1$3.dot(_v1$3); + const dot12 = _v1$3.dot(_v2$2); + const denom = dot00 * dot11 - dot01 * dot01; + if (denom === 0) { + target.set(0, 0, 0); + return null; + } + const invDenom = 1 / denom; + const u = (dot11 * dot02 - dot01 * dot12) * invDenom; + const v = (dot00 * dot12 - dot01 * dot02) * invDenom; + return target.set(1 - u - v, v, u); + } + static containsPoint(point, a, b, c) { + if (this.getBarycoord(point, a, b, c, _v3$2) === null) { + return false; + } + return _v3$2.x >= 0 && _v3$2.y >= 0 && _v3$2.x + _v3$2.y <= 1; + } + static getInterpolation(point, p1, p2, p3, v1, v2, v3, target) { + if (this.getBarycoord(point, p1, p2, p3, _v3$2) === null) { + target.x = 0; + target.y = 0; + if ("z" in target) + target.z = 0; + if ("w" in target) + target.w = 0; + return null; + } + target.setScalar(0); + target.addScaledVector(v1, _v3$2.x); + target.addScaledVector(v2, _v3$2.y); + target.addScaledVector(v3, _v3$2.z); + return target; + } + static getInterpolatedAttribute(attr, i1, i2, i3, barycoord, target) { + _v40.setScalar(0); + _v41.setScalar(0); + _v42.setScalar(0); + _v40.fromBufferAttribute(attr, i1); + _v41.fromBufferAttribute(attr, i2); + _v42.fromBufferAttribute(attr, i3); + target.setScalar(0); + target.addScaledVector(_v40, barycoord.x); + target.addScaledVector(_v41, barycoord.y); + target.addScaledVector(_v42, barycoord.z); + return target; + } + static isFrontFacing(a, b, c, direction) { + _v0$1.subVectors(c, b); + _v1$3.subVectors(a, b); + return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false; + } + set(a, b, c) { + this.a.copy(a); + this.b.copy(b); + this.c.copy(c); + return this; + } + setFromPointsAndIndices(points, i0, i1, i2) { + this.a.copy(points[i0]); + this.b.copy(points[i1]); + this.c.copy(points[i2]); + return this; + } + setFromAttributeAndIndices(attribute, i0, i1, i2) { + this.a.fromBufferAttribute(attribute, i0); + this.b.fromBufferAttribute(attribute, i1); + this.c.fromBufferAttribute(attribute, i2); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(triangle) { + this.a.copy(triangle.a); + this.b.copy(triangle.b); + this.c.copy(triangle.c); + return this; + } + getArea() { + _v0$1.subVectors(this.c, this.b); + _v1$3.subVectors(this.a, this.b); + return _v0$1.cross(_v1$3).length() * 0.5; + } + getMidpoint(target) { + return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); + } + getNormal(target) { + return Triangle.getNormal(this.a, this.b, this.c, target); + } + getPlane(target) { + return target.setFromCoplanarPoints(this.a, this.b, this.c); + } + getBarycoord(point, target) { + return Triangle.getBarycoord(point, this.a, this.b, this.c, target); + } + getInterpolation(point, v1, v2, v3, target) { + return Triangle.getInterpolation(point, this.a, this.b, this.c, v1, v2, v3, target); + } + containsPoint(point) { + return Triangle.containsPoint(point, this.a, this.b, this.c); + } + isFrontFacing(direction) { + return Triangle.isFrontFacing(this.a, this.b, this.c, direction); + } + intersectsBox(box) { + return box.intersectsTriangle(this); + } + closestPointToPoint(p, target) { + const a = this.a, b = this.b, c = this.c; + let v, w; + _vab.subVectors(b, a); + _vac.subVectors(c, a); + _vap.subVectors(p, a); + const d1 = _vab.dot(_vap); + const d2 = _vac.dot(_vap); + if (d1 <= 0 && d2 <= 0) { + return target.copy(a); + } + _vbp.subVectors(p, b); + const d3 = _vab.dot(_vbp); + const d4 = _vac.dot(_vbp); + if (d3 >= 0 && d4 <= d3) { + return target.copy(b); + } + const vc = d1 * d4 - d3 * d2; + if (vc <= 0 && d1 >= 0 && d3 <= 0) { + v = d1 / (d1 - d3); + return target.copy(a).addScaledVector(_vab, v); + } + _vcp.subVectors(p, c); + const d5 = _vab.dot(_vcp); + const d6 = _vac.dot(_vcp); + if (d6 >= 0 && d5 <= d6) { + return target.copy(c); + } + const vb = d5 * d2 - d1 * d6; + if (vb <= 0 && d2 >= 0 && d6 <= 0) { + w = d2 / (d2 - d6); + return target.copy(a).addScaledVector(_vac, w); + } + const va = d3 * d6 - d5 * d4; + if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { + _vbc.subVectors(c, b); + w = (d4 - d3) / (d4 - d3 + (d5 - d6)); + return target.copy(b).addScaledVector(_vbc, w); + } + const denom = 1 / (va + vb + vc); + v = vb * denom; + w = vc * denom; + return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w); + } + equals(triangle) { + return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c); + } +} +var _colorKeywords = { + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + rebeccapurple: 6697881, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 +}; +var _hslA = { h: 0, s: 0, l: 0 }; +var _hslB = { h: 0, s: 0, l: 0 }; +function hue2rgb2(p, q, t) { + if (t < 0) + t += 1; + if (t > 1) + t -= 1; + if (t < 1 / 6) + return p + (q - p) * 6 * t; + if (t < 1 / 2) + return q; + if (t < 2 / 3) + return p + (q - p) * 6 * (2 / 3 - t); + return p; +} + +class Color { + constructor(r, g, b) { + this.isColor = true; + this.r = 1; + this.g = 1; + this.b = 1; + return this.set(r, g, b); + } + set(r, g, b) { + if (g === undefined && b === undefined) { + const value2 = r; + if (value2 && value2.isColor) { + this.copy(value2); + } else if (typeof value2 === "number") { + this.setHex(value2); + } else if (typeof value2 === "string") { + this.setStyle(value2); + } + } else { + this.setRGB(r, g, b); + } + return this; + } + setScalar(scalar) { + this.r = scalar; + this.g = scalar; + this.b = scalar; + return this; + } + setHex(hex, colorSpace = SRGBColorSpace) { + hex = Math.floor(hex); + this.r = (hex >> 16 & 255) / 255; + this.g = (hex >> 8 & 255) / 255; + this.b = (hex & 255) / 255; + ColorManagement.toWorkingColorSpace(this, colorSpace); + return this; + } + setRGB(r, g, b, colorSpace = ColorManagement.workingColorSpace) { + this.r = r; + this.g = g; + this.b = b; + ColorManagement.toWorkingColorSpace(this, colorSpace); + return this; + } + setHSL(h, s, l, colorSpace = ColorManagement.workingColorSpace) { + h = euclideanModulo(h, 1); + s = clamp2(s, 0, 1); + l = clamp2(l, 0, 1); + if (s === 0) { + this.r = this.g = this.b = l; + } else { + const p = l <= 0.5 ? l * (1 + s) : l + s - l * s; + const q = 2 * l - p; + this.r = hue2rgb2(q, p, h + 1 / 3); + this.g = hue2rgb2(q, p, h); + this.b = hue2rgb2(q, p, h - 1 / 3); + } + ColorManagement.toWorkingColorSpace(this, colorSpace); + return this; + } + setStyle(style, colorSpace = SRGBColorSpace) { + function handleAlpha(string) { + if (string === undefined) + return; + if (parseFloat(string) < 1) { + console.warn("THREE.Color: Alpha component of " + style + " will be ignored."); + } + } + let m; + if (m = /^(\w+)\(([^\)]*)\)/.exec(style)) { + let color; + const name2 = m[1]; + const components = m[2]; + switch (name2) { + case "rgb": + case "rgba": + if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB(Math.min(255, parseInt(color[1], 10)) / 255, Math.min(255, parseInt(color[2], 10)) / 255, Math.min(255, parseInt(color[3], 10)) / 255, colorSpace); + } + if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setRGB(Math.min(100, parseInt(color[1], 10)) / 100, Math.min(100, parseInt(color[2], 10)) / 100, Math.min(100, parseInt(color[3], 10)) / 100, colorSpace); + } + break; + case "hsl": + case "hsla": + if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { + handleAlpha(color[4]); + return this.setHSL(parseFloat(color[1]) / 360, parseFloat(color[2]) / 100, parseFloat(color[3]) / 100, colorSpace); + } + break; + default: + console.warn("THREE.Color: Unknown color model " + style); + } + } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) { + const hex = m[1]; + const size = hex.length; + if (size === 3) { + return this.setRGB(parseInt(hex.charAt(0), 16) / 15, parseInt(hex.charAt(1), 16) / 15, parseInt(hex.charAt(2), 16) / 15, colorSpace); + } else if (size === 6) { + return this.setHex(parseInt(hex, 16), colorSpace); + } else { + console.warn("THREE.Color: Invalid hex color " + style); + } + } else if (style && style.length > 0) { + return this.setColorName(style, colorSpace); + } + return this; + } + setColorName(style, colorSpace = SRGBColorSpace) { + const hex = _colorKeywords[style.toLowerCase()]; + if (hex !== undefined) { + this.setHex(hex, colorSpace); + } else { + console.warn("THREE.Color: Unknown color " + style); + } + return this; + } + clone() { + return new this.constructor(this.r, this.g, this.b); + } + copy(color) { + this.r = color.r; + this.g = color.g; + this.b = color.b; + return this; + } + copySRGBToLinear(color) { + this.r = SRGBToLinear(color.r); + this.g = SRGBToLinear(color.g); + this.b = SRGBToLinear(color.b); + return this; + } + copyLinearToSRGB(color) { + this.r = LinearToSRGB(color.r); + this.g = LinearToSRGB(color.g); + this.b = LinearToSRGB(color.b); + return this; + } + convertSRGBToLinear() { + this.copySRGBToLinear(this); + return this; + } + convertLinearToSRGB() { + this.copyLinearToSRGB(this); + return this; + } + getHex(colorSpace = SRGBColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + return Math.round(clamp2(_color.r * 255, 0, 255)) * 65536 + Math.round(clamp2(_color.g * 255, 0, 255)) * 256 + Math.round(clamp2(_color.b * 255, 0, 255)); + } + getHexString(colorSpace = SRGBColorSpace) { + return ("000000" + this.getHex(colorSpace).toString(16)).slice(-6); + } + getHSL(target, colorSpace = ColorManagement.workingColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + const { r, g, b } = _color; + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + let hue, saturation; + const lightness = (min + max) / 2; + if (min === max) { + hue = 0; + saturation = 0; + } else { + const delta = max - min; + saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min); + switch (max) { + case r: + hue = (g - b) / delta + (g < b ? 6 : 0); + break; + case g: + hue = (b - r) / delta + 2; + break; + case b: + hue = (r - g) / delta + 4; + break; + } + hue /= 6; + } + target.h = hue; + target.s = saturation; + target.l = lightness; + return target; + } + getRGB(target, colorSpace = ColorManagement.workingColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + target.r = _color.r; + target.g = _color.g; + target.b = _color.b; + return target; + } + getStyle(colorSpace = SRGBColorSpace) { + ColorManagement.fromWorkingColorSpace(_color.copy(this), colorSpace); + const { r, g, b } = _color; + if (colorSpace !== SRGBColorSpace) { + return `color(${colorSpace} ${r.toFixed(3)} ${g.toFixed(3)} ${b.toFixed(3)})`; + } + return `rgb(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)})`; + } + offsetHSL(h, s, l) { + this.getHSL(_hslA); + return this.setHSL(_hslA.h + h, _hslA.s + s, _hslA.l + l); + } + add(color) { + this.r += color.r; + this.g += color.g; + this.b += color.b; + return this; + } + addColors(color1, color2) { + this.r = color1.r + color2.r; + this.g = color1.g + color2.g; + this.b = color1.b + color2.b; + return this; + } + addScalar(s) { + this.r += s; + this.g += s; + this.b += s; + return this; + } + sub(color) { + this.r = Math.max(0, this.r - color.r); + this.g = Math.max(0, this.g - color.g); + this.b = Math.max(0, this.b - color.b); + return this; + } + multiply(color) { + this.r *= color.r; + this.g *= color.g; + this.b *= color.b; + return this; + } + multiplyScalar(s) { + this.r *= s; + this.g *= s; + this.b *= s; + return this; + } + lerp(color, alpha) { + this.r += (color.r - this.r) * alpha; + this.g += (color.g - this.g) * alpha; + this.b += (color.b - this.b) * alpha; + return this; + } + lerpColors(color1, color2, alpha) { + this.r = color1.r + (color2.r - color1.r) * alpha; + this.g = color1.g + (color2.g - color1.g) * alpha; + this.b = color1.b + (color2.b - color1.b) * alpha; + return this; + } + lerpHSL(color, alpha) { + this.getHSL(_hslA); + color.getHSL(_hslB); + const h = lerp(_hslA.h, _hslB.h, alpha); + const s = lerp(_hslA.s, _hslB.s, alpha); + const l = lerp(_hslA.l, _hslB.l, alpha); + this.setHSL(h, s, l); + return this; + } + setFromVector3(v) { + this.r = v.x; + this.g = v.y; + this.b = v.z; + return this; + } + applyMatrix3(m) { + const r = this.r, g = this.g, b = this.b; + const e = m.elements; + this.r = e[0] * r + e[3] * g + e[6] * b; + this.g = e[1] * r + e[4] * g + e[7] * b; + this.b = e[2] * r + e[5] * g + e[8] * b; + return this; + } + equals(c) { + return c.r === this.r && c.g === this.g && c.b === this.b; + } + fromArray(array, offset = 0) { + this.r = array[offset]; + this.g = array[offset + 1]; + this.b = array[offset + 2]; + return this; + } + toArray(array = [], offset = 0) { + array[offset] = this.r; + array[offset + 1] = this.g; + array[offset + 2] = this.b; + return array; + } + fromBufferAttribute(attribute, index2) { + this.r = attribute.getX(index2); + this.g = attribute.getY(index2); + this.b = attribute.getZ(index2); + return this; + } + toJSON() { + return this.getHex(); + } + *[Symbol.iterator]() { + yield this.r; + yield this.g; + yield this.b; + } +} +var _color = /* @__PURE__ */ new Color; +Color.NAMES = _colorKeywords; +var _materialId = 0; + +class Material extends EventDispatcher { + constructor() { + super(); + this.isMaterial = true; + Object.defineProperty(this, "id", { value: _materialId++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "Material"; + this.blending = NormalBlending; + this.side = FrontSide; + this.vertexColors = false; + this.opacity = 1; + this.transparent = false; + this.alphaHash = false; + this.blendSrc = SrcAlphaFactor; + this.blendDst = OneMinusSrcAlphaFactor; + this.blendEquation = AddEquation; + this.blendSrcAlpha = null; + this.blendDstAlpha = null; + this.blendEquationAlpha = null; + this.blendColor = new Color(0, 0, 0); + this.blendAlpha = 0; + this.depthFunc = LessEqualDepth; + this.depthTest = true; + this.depthWrite = true; + this.stencilWriteMask = 255; + this.stencilFunc = AlwaysStencilFunc; + this.stencilRef = 0; + this.stencilFuncMask = 255; + this.stencilFail = KeepStencilOp; + this.stencilZFail = KeepStencilOp; + this.stencilZPass = KeepStencilOp; + this.stencilWrite = false; + this.clippingPlanes = null; + this.clipIntersection = false; + this.clipShadows = false; + this.shadowSide = null; + this.colorWrite = true; + this.precision = null; + this.polygonOffset = false; + this.polygonOffsetFactor = 0; + this.polygonOffsetUnits = 0; + this.dithering = false; + this.alphaToCoverage = false; + this.premultipliedAlpha = false; + this.forceSinglePass = false; + this.visible = true; + this.toneMapped = true; + this.userData = {}; + this.version = 0; + this._alphaTest = 0; + } + get alphaTest() { + return this._alphaTest; + } + set alphaTest(value2) { + if (this._alphaTest > 0 !== value2 > 0) { + this.version++; + } + this._alphaTest = value2; + } + onBeforeRender() { + } + onBeforeCompile() { + } + customProgramCacheKey() { + return this.onBeforeCompile.toString(); + } + setValues(values2) { + if (values2 === undefined) + return; + for (const key2 in values2) { + const newValue = values2[key2]; + if (newValue === undefined) { + console.warn(`THREE.Material: parameter '${key2}' has value of undefined.`); + continue; + } + const currentValue = this[key2]; + if (currentValue === undefined) { + console.warn(`THREE.Material: '${key2}' is not a property of THREE.${this.type}.`); + continue; + } + if (currentValue && currentValue.isColor) { + currentValue.set(newValue); + } else if (currentValue && currentValue.isVector3 && (newValue && newValue.isVector3)) { + currentValue.copy(newValue); + } else { + this[key2] = newValue; + } + } + } + toJSON(meta) { + const isRootObject = meta === undefined || typeof meta === "string"; + if (isRootObject) { + meta = { + textures: {}, + images: {} + }; + } + const data2 = { + metadata: { + version: 4.6, + type: "Material", + generator: "Material.toJSON" + } + }; + data2.uuid = this.uuid; + data2.type = this.type; + if (this.name !== "") + data2.name = this.name; + if (this.color && this.color.isColor) + data2.color = this.color.getHex(); + if (this.roughness !== undefined) + data2.roughness = this.roughness; + if (this.metalness !== undefined) + data2.metalness = this.metalness; + if (this.sheen !== undefined) + data2.sheen = this.sheen; + if (this.sheenColor && this.sheenColor.isColor) + data2.sheenColor = this.sheenColor.getHex(); + if (this.sheenRoughness !== undefined) + data2.sheenRoughness = this.sheenRoughness; + if (this.emissive && this.emissive.isColor) + data2.emissive = this.emissive.getHex(); + if (this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1) + data2.emissiveIntensity = this.emissiveIntensity; + if (this.specular && this.specular.isColor) + data2.specular = this.specular.getHex(); + if (this.specularIntensity !== undefined) + data2.specularIntensity = this.specularIntensity; + if (this.specularColor && this.specularColor.isColor) + data2.specularColor = this.specularColor.getHex(); + if (this.shininess !== undefined) + data2.shininess = this.shininess; + if (this.clearcoat !== undefined) + data2.clearcoat = this.clearcoat; + if (this.clearcoatRoughness !== undefined) + data2.clearcoatRoughness = this.clearcoatRoughness; + if (this.clearcoatMap && this.clearcoatMap.isTexture) { + data2.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid; + } + if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) { + data2.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid; + } + if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) { + data2.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid; + data2.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); + } + if (this.dispersion !== undefined) + data2.dispersion = this.dispersion; + if (this.iridescence !== undefined) + data2.iridescence = this.iridescence; + if (this.iridescenceIOR !== undefined) + data2.iridescenceIOR = this.iridescenceIOR; + if (this.iridescenceThicknessRange !== undefined) + data2.iridescenceThicknessRange = this.iridescenceThicknessRange; + if (this.iridescenceMap && this.iridescenceMap.isTexture) { + data2.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid; + } + if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) { + data2.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid; + } + if (this.anisotropy !== undefined) + data2.anisotropy = this.anisotropy; + if (this.anisotropyRotation !== undefined) + data2.anisotropyRotation = this.anisotropyRotation; + if (this.anisotropyMap && this.anisotropyMap.isTexture) { + data2.anisotropyMap = this.anisotropyMap.toJSON(meta).uuid; + } + if (this.map && this.map.isTexture) + data2.map = this.map.toJSON(meta).uuid; + if (this.matcap && this.matcap.isTexture) + data2.matcap = this.matcap.toJSON(meta).uuid; + if (this.alphaMap && this.alphaMap.isTexture) + data2.alphaMap = this.alphaMap.toJSON(meta).uuid; + if (this.lightMap && this.lightMap.isTexture) { + data2.lightMap = this.lightMap.toJSON(meta).uuid; + data2.lightMapIntensity = this.lightMapIntensity; + } + if (this.aoMap && this.aoMap.isTexture) { + data2.aoMap = this.aoMap.toJSON(meta).uuid; + data2.aoMapIntensity = this.aoMapIntensity; + } + if (this.bumpMap && this.bumpMap.isTexture) { + data2.bumpMap = this.bumpMap.toJSON(meta).uuid; + data2.bumpScale = this.bumpScale; + } + if (this.normalMap && this.normalMap.isTexture) { + data2.normalMap = this.normalMap.toJSON(meta).uuid; + data2.normalMapType = this.normalMapType; + data2.normalScale = this.normalScale.toArray(); + } + if (this.displacementMap && this.displacementMap.isTexture) { + data2.displacementMap = this.displacementMap.toJSON(meta).uuid; + data2.displacementScale = this.displacementScale; + data2.displacementBias = this.displacementBias; + } + if (this.roughnessMap && this.roughnessMap.isTexture) + data2.roughnessMap = this.roughnessMap.toJSON(meta).uuid; + if (this.metalnessMap && this.metalnessMap.isTexture) + data2.metalnessMap = this.metalnessMap.toJSON(meta).uuid; + if (this.emissiveMap && this.emissiveMap.isTexture) + data2.emissiveMap = this.emissiveMap.toJSON(meta).uuid; + if (this.specularMap && this.specularMap.isTexture) + data2.specularMap = this.specularMap.toJSON(meta).uuid; + if (this.specularIntensityMap && this.specularIntensityMap.isTexture) + data2.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid; + if (this.specularColorMap && this.specularColorMap.isTexture) + data2.specularColorMap = this.specularColorMap.toJSON(meta).uuid; + if (this.envMap && this.envMap.isTexture) { + data2.envMap = this.envMap.toJSON(meta).uuid; + if (this.combine !== undefined) + data2.combine = this.combine; + } + if (this.envMapRotation !== undefined) + data2.envMapRotation = this.envMapRotation.toArray(); + if (this.envMapIntensity !== undefined) + data2.envMapIntensity = this.envMapIntensity; + if (this.reflectivity !== undefined) + data2.reflectivity = this.reflectivity; + if (this.refractionRatio !== undefined) + data2.refractionRatio = this.refractionRatio; + if (this.gradientMap && this.gradientMap.isTexture) { + data2.gradientMap = this.gradientMap.toJSON(meta).uuid; + } + if (this.transmission !== undefined) + data2.transmission = this.transmission; + if (this.transmissionMap && this.transmissionMap.isTexture) + data2.transmissionMap = this.transmissionMap.toJSON(meta).uuid; + if (this.thickness !== undefined) + data2.thickness = this.thickness; + if (this.thicknessMap && this.thicknessMap.isTexture) + data2.thicknessMap = this.thicknessMap.toJSON(meta).uuid; + if (this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity) + data2.attenuationDistance = this.attenuationDistance; + if (this.attenuationColor !== undefined) + data2.attenuationColor = this.attenuationColor.getHex(); + if (this.size !== undefined) + data2.size = this.size; + if (this.shadowSide !== null) + data2.shadowSide = this.shadowSide; + if (this.sizeAttenuation !== undefined) + data2.sizeAttenuation = this.sizeAttenuation; + if (this.blending !== NormalBlending) + data2.blending = this.blending; + if (this.side !== FrontSide) + data2.side = this.side; + if (this.vertexColors === true) + data2.vertexColors = true; + if (this.opacity < 1) + data2.opacity = this.opacity; + if (this.transparent === true) + data2.transparent = true; + if (this.blendSrc !== SrcAlphaFactor) + data2.blendSrc = this.blendSrc; + if (this.blendDst !== OneMinusSrcAlphaFactor) + data2.blendDst = this.blendDst; + if (this.blendEquation !== AddEquation) + data2.blendEquation = this.blendEquation; + if (this.blendSrcAlpha !== null) + data2.blendSrcAlpha = this.blendSrcAlpha; + if (this.blendDstAlpha !== null) + data2.blendDstAlpha = this.blendDstAlpha; + if (this.blendEquationAlpha !== null) + data2.blendEquationAlpha = this.blendEquationAlpha; + if (this.blendColor && this.blendColor.isColor) + data2.blendColor = this.blendColor.getHex(); + if (this.blendAlpha !== 0) + data2.blendAlpha = this.blendAlpha; + if (this.depthFunc !== LessEqualDepth) + data2.depthFunc = this.depthFunc; + if (this.depthTest === false) + data2.depthTest = this.depthTest; + if (this.depthWrite === false) + data2.depthWrite = this.depthWrite; + if (this.colorWrite === false) + data2.colorWrite = this.colorWrite; + if (this.stencilWriteMask !== 255) + data2.stencilWriteMask = this.stencilWriteMask; + if (this.stencilFunc !== AlwaysStencilFunc) + data2.stencilFunc = this.stencilFunc; + if (this.stencilRef !== 0) + data2.stencilRef = this.stencilRef; + if (this.stencilFuncMask !== 255) + data2.stencilFuncMask = this.stencilFuncMask; + if (this.stencilFail !== KeepStencilOp) + data2.stencilFail = this.stencilFail; + if (this.stencilZFail !== KeepStencilOp) + data2.stencilZFail = this.stencilZFail; + if (this.stencilZPass !== KeepStencilOp) + data2.stencilZPass = this.stencilZPass; + if (this.stencilWrite === true) + data2.stencilWrite = this.stencilWrite; + if (this.rotation !== undefined && this.rotation !== 0) + data2.rotation = this.rotation; + if (this.polygonOffset === true) + data2.polygonOffset = true; + if (this.polygonOffsetFactor !== 0) + data2.polygonOffsetFactor = this.polygonOffsetFactor; + if (this.polygonOffsetUnits !== 0) + data2.polygonOffsetUnits = this.polygonOffsetUnits; + if (this.linewidth !== undefined && this.linewidth !== 1) + data2.linewidth = this.linewidth; + if (this.dashSize !== undefined) + data2.dashSize = this.dashSize; + if (this.gapSize !== undefined) + data2.gapSize = this.gapSize; + if (this.scale !== undefined) + data2.scale = this.scale; + if (this.dithering === true) + data2.dithering = true; + if (this.alphaTest > 0) + data2.alphaTest = this.alphaTest; + if (this.alphaHash === true) + data2.alphaHash = true; + if (this.alphaToCoverage === true) + data2.alphaToCoverage = true; + if (this.premultipliedAlpha === true) + data2.premultipliedAlpha = true; + if (this.forceSinglePass === true) + data2.forceSinglePass = true; + if (this.wireframe === true) + data2.wireframe = true; + if (this.wireframeLinewidth > 1) + data2.wireframeLinewidth = this.wireframeLinewidth; + if (this.wireframeLinecap !== "round") + data2.wireframeLinecap = this.wireframeLinecap; + if (this.wireframeLinejoin !== "round") + data2.wireframeLinejoin = this.wireframeLinejoin; + if (this.flatShading === true) + data2.flatShading = true; + if (this.visible === false) + data2.visible = false; + if (this.toneMapped === false) + data2.toneMapped = false; + if (this.fog === false) + data2.fog = false; + if (Object.keys(this.userData).length > 0) + data2.userData = this.userData; + function extractFromCache(cache) { + const values2 = []; + for (const key2 in cache) { + const data3 = cache[key2]; + delete data3.metadata; + values2.push(data3); + } + return values2; + } + if (isRootObject) { + const textures = extractFromCache(meta.textures); + const images = extractFromCache(meta.images); + if (textures.length > 0) + data2.textures = textures; + if (images.length > 0) + data2.images = images; + } + return data2; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.name = source.name; + this.blending = source.blending; + this.side = source.side; + this.vertexColors = source.vertexColors; + this.opacity = source.opacity; + this.transparent = source.transparent; + this.blendSrc = source.blendSrc; + this.blendDst = source.blendDst; + this.blendEquation = source.blendEquation; + this.blendSrcAlpha = source.blendSrcAlpha; + this.blendDstAlpha = source.blendDstAlpha; + this.blendEquationAlpha = source.blendEquationAlpha; + this.blendColor.copy(source.blendColor); + this.blendAlpha = source.blendAlpha; + this.depthFunc = source.depthFunc; + this.depthTest = source.depthTest; + this.depthWrite = source.depthWrite; + this.stencilWriteMask = source.stencilWriteMask; + this.stencilFunc = source.stencilFunc; + this.stencilRef = source.stencilRef; + this.stencilFuncMask = source.stencilFuncMask; + this.stencilFail = source.stencilFail; + this.stencilZFail = source.stencilZFail; + this.stencilZPass = source.stencilZPass; + this.stencilWrite = source.stencilWrite; + const srcPlanes = source.clippingPlanes; + let dstPlanes = null; + if (srcPlanes !== null) { + const n = srcPlanes.length; + dstPlanes = new Array(n); + for (let i = 0;i !== n; ++i) { + dstPlanes[i] = srcPlanes[i].clone(); + } + } + this.clippingPlanes = dstPlanes; + this.clipIntersection = source.clipIntersection; + this.clipShadows = source.clipShadows; + this.shadowSide = source.shadowSide; + this.colorWrite = source.colorWrite; + this.precision = source.precision; + this.polygonOffset = source.polygonOffset; + this.polygonOffsetFactor = source.polygonOffsetFactor; + this.polygonOffsetUnits = source.polygonOffsetUnits; + this.dithering = source.dithering; + this.alphaTest = source.alphaTest; + this.alphaHash = source.alphaHash; + this.alphaToCoverage = source.alphaToCoverage; + this.premultipliedAlpha = source.premultipliedAlpha; + this.forceSinglePass = source.forceSinglePass; + this.visible = source.visible; + this.toneMapped = source.toneMapped; + this.userData = JSON.parse(JSON.stringify(source.userData)); + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + onBuild() { + console.warn("Material: onBuild() has been removed."); + } +} + +class MeshBasicMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshBasicMaterial = true; + this.type = "MeshBasicMaterial"; + this.color = new Color(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } +} +var _tables = /* @__PURE__ */ _generateTables(); +function _generateTables() { + const buffer = new ArrayBuffer(4); + const floatView = new Float32Array(buffer); + const uint32View = new Uint32Array(buffer); + const baseTable = new Uint32Array(512); + const shiftTable = new Uint32Array(512); + for (let i = 0;i < 256; ++i) { + const e = i - 127; + if (e < -27) { + baseTable[i] = 0; + baseTable[i | 256] = 32768; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else if (e < -14) { + baseTable[i] = 1024 >> -e - 14; + baseTable[i | 256] = 1024 >> -e - 14 | 32768; + shiftTable[i] = -e - 1; + shiftTable[i | 256] = -e - 1; + } else if (e <= 15) { + baseTable[i] = e + 15 << 10; + baseTable[i | 256] = e + 15 << 10 | 32768; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } else if (e < 128) { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 24; + shiftTable[i | 256] = 24; + } else { + baseTable[i] = 31744; + baseTable[i | 256] = 64512; + shiftTable[i] = 13; + shiftTable[i | 256] = 13; + } + } + const mantissaTable = new Uint32Array(2048); + const exponentTable = new Uint32Array(64); + const offsetTable = new Uint32Array(64); + for (let i = 1;i < 1024; ++i) { + let m = i << 13; + let e = 0; + while ((m & 8388608) === 0) { + m <<= 1; + e -= 8388608; + } + m &= ~8388608; + e += 947912704; + mantissaTable[i] = m | e; + } + for (let i = 1024;i < 2048; ++i) { + mantissaTable[i] = 939524096 + (i - 1024 << 13); + } + for (let i = 1;i < 31; ++i) { + exponentTable[i] = i << 23; + } + exponentTable[31] = 1199570944; + exponentTable[32] = 2147483648; + for (let i = 33;i < 63; ++i) { + exponentTable[i] = 2147483648 + (i - 32 << 23); + } + exponentTable[63] = 3347054592; + for (let i = 1;i < 64; ++i) { + if (i !== 32) { + offsetTable[i] = 1024; + } + } + return { + floatView, + uint32View, + baseTable, + shiftTable, + mantissaTable, + exponentTable, + offsetTable + }; +} +function toHalfFloat(val2) { + if (Math.abs(val2) > 65504) + console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."); + val2 = clamp2(val2, -65504, 65504); + _tables.floatView[0] = val2; + const f = _tables.uint32View[0]; + const e = f >> 23 & 511; + return _tables.baseTable[e] + ((f & 8388607) >> _tables.shiftTable[e]); +} +function fromHalfFloat(val2) { + const m = val2 >> 10; + _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val2 & 1023)] + _tables.exponentTable[m]; + return _tables.floatView[0]; +} +var DataUtils = { + toHalfFloat, + fromHalfFloat +}; +var _vector$9 = /* @__PURE__ */ new Vector3; +var _vector2$1 = /* @__PURE__ */ new Vector2; +var _id$2 = 0; + +class BufferAttribute { + constructor(array, itemSize, normalized = false) { + if (Array.isArray(array)) { + throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); + } + this.isBufferAttribute = true; + Object.defineProperty(this, "id", { value: _id$2++ }); + this.name = ""; + this.array = array; + this.itemSize = itemSize; + this.count = array !== undefined ? array.length / itemSize : 0; + this.normalized = normalized; + this.usage = StaticDrawUsage; + this.updateRanges = []; + this.gpuType = FloatType; + this.version = 0; + } + onUploadCallback() { + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setUsage(value2) { + this.usage = value2; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.name = source.name; + this.array = new source.array.constructor(source.array); + this.itemSize = source.itemSize; + this.count = source.count; + this.normalized = source.normalized; + this.usage = source.usage; + this.gpuType = source.gpuType; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.itemSize; + index2 *= attribute.itemSize; + for (let i = 0, l = this.itemSize;i < l; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + copyArray(array) { + this.array.set(array); + return this; + } + applyMatrix3(m) { + if (this.itemSize === 2) { + for (let i = 0, l = this.count;i < l; i++) { + _vector2$1.fromBufferAttribute(this, i); + _vector2$1.applyMatrix3(m); + this.setXY(i, _vector2$1.x, _vector2$1.y); + } + } else if (this.itemSize === 3) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.applyMatrix3(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + } + return this; + } + applyMatrix4(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.applyMatrix4(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.applyNormalMatrix(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$9.fromBufferAttribute(this, i); + _vector$9.transformDirection(m); + this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); + } + return this; + } + set(value2, offset = 0) { + this.array.set(value2, offset); + return this; + } + getComponent(index2, component) { + let value2 = this.array[index2 * this.itemSize + component]; + if (this.normalized) + value2 = denormalize(value2, this.array); + return value2; + } + setComponent(index2, component, value2) { + if (this.normalized) + value2 = normalize2(value2, this.array); + this.array[index2 * this.itemSize + component] = value2; + return this; + } + getX(index2) { + let x = this.array[index2 * this.itemSize]; + if (this.normalized) + x = denormalize(x, this.array); + return x; + } + setX(index2, x) { + if (this.normalized) + x = normalize2(x, this.array); + this.array[index2 * this.itemSize] = x; + return this; + } + getY(index2) { + let y = this.array[index2 * this.itemSize + 1]; + if (this.normalized) + y = denormalize(y, this.array); + return y; + } + setY(index2, y) { + if (this.normalized) + y = normalize2(y, this.array); + this.array[index2 * this.itemSize + 1] = y; + return this; + } + getZ(index2) { + let z = this.array[index2 * this.itemSize + 2]; + if (this.normalized) + z = denormalize(z, this.array); + return z; + } + setZ(index2, z) { + if (this.normalized) + z = normalize2(z, this.array); + this.array[index2 * this.itemSize + 2] = z; + return this; + } + getW(index2) { + let w = this.array[index2 * this.itemSize + 3]; + if (this.normalized) + w = denormalize(w, this.array); + return w; + } + setW(index2, w) { + if (this.normalized) + w = normalize2(w, this.array); + this.array[index2 * this.itemSize + 3] = w; + return this; + } + setXY(index2, x, y) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + } + this.array[index2 + 0] = x; + this.array[index2 + 1] = y; + return this; + } + setXYZ(index2, x, y, z) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + } + this.array[index2 + 0] = x; + this.array[index2 + 1] = y; + this.array[index2 + 2] = z; + return this; + } + setXYZW(index2, x, y, z, w) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + w = normalize2(w, this.array); + } + this.array[index2 + 0] = x; + this.array[index2 + 1] = y; + this.array[index2 + 2] = z; + this.array[index2 + 3] = w; + return this; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + clone() { + return new this.constructor(this.array, this.itemSize).copy(this); + } + toJSON() { + const data2 = { + itemSize: this.itemSize, + type: this.array.constructor.name, + array: Array.from(this.array), + normalized: this.normalized + }; + if (this.name !== "") + data2.name = this.name; + if (this.usage !== StaticDrawUsage) + data2.usage = this.usage; + return data2; + } +} + +class Int8BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Int8Array(array), itemSize, normalized); + } +} + +class Uint8BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint8Array(array), itemSize, normalized); + } +} + +class Uint8ClampedBufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint8ClampedArray(array), itemSize, normalized); + } +} + +class Int16BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Int16Array(array), itemSize, normalized); + } +} + +class Uint16BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + } +} + +class Int32BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Int32Array(array), itemSize, normalized); + } +} + +class Uint32BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint32Array(array), itemSize, normalized); + } +} + +class Float16BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Uint16Array(array), itemSize, normalized); + this.isFloat16BufferAttribute = true; + } + getX(index2) { + let x = fromHalfFloat(this.array[index2 * this.itemSize]); + if (this.normalized) + x = denormalize(x, this.array); + return x; + } + setX(index2, x) { + if (this.normalized) + x = normalize2(x, this.array); + this.array[index2 * this.itemSize] = toHalfFloat(x); + return this; + } + getY(index2) { + let y = fromHalfFloat(this.array[index2 * this.itemSize + 1]); + if (this.normalized) + y = denormalize(y, this.array); + return y; + } + setY(index2, y) { + if (this.normalized) + y = normalize2(y, this.array); + this.array[index2 * this.itemSize + 1] = toHalfFloat(y); + return this; + } + getZ(index2) { + let z = fromHalfFloat(this.array[index2 * this.itemSize + 2]); + if (this.normalized) + z = denormalize(z, this.array); + return z; + } + setZ(index2, z) { + if (this.normalized) + z = normalize2(z, this.array); + this.array[index2 * this.itemSize + 2] = toHalfFloat(z); + return this; + } + getW(index2) { + let w = fromHalfFloat(this.array[index2 * this.itemSize + 3]); + if (this.normalized) + w = denormalize(w, this.array); + return w; + } + setW(index2, w) { + if (this.normalized) + w = normalize2(w, this.array); + this.array[index2 * this.itemSize + 3] = toHalfFloat(w); + return this; + } + setXY(index2, x, y) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + } + this.array[index2 + 0] = toHalfFloat(x); + this.array[index2 + 1] = toHalfFloat(y); + return this; + } + setXYZ(index2, x, y, z) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + } + this.array[index2 + 0] = toHalfFloat(x); + this.array[index2 + 1] = toHalfFloat(y); + this.array[index2 + 2] = toHalfFloat(z); + return this; + } + setXYZW(index2, x, y, z, w) { + index2 *= this.itemSize; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + w = normalize2(w, this.array); + } + this.array[index2 + 0] = toHalfFloat(x); + this.array[index2 + 1] = toHalfFloat(y); + this.array[index2 + 2] = toHalfFloat(z); + this.array[index2 + 3] = toHalfFloat(w); + return this; + } +} + +class Float32BufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized) { + super(new Float32Array(array), itemSize, normalized); + } +} +var _id$1 = 0; +var _m1 = /* @__PURE__ */ new Matrix4; +var _obj = /* @__PURE__ */ new Object3D; +var _offset = /* @__PURE__ */ new Vector3; +var _box$2 = /* @__PURE__ */ new Box3; +var _boxMorphTargets = /* @__PURE__ */ new Box3; +var _vector$8 = /* @__PURE__ */ new Vector3; + +class BufferGeometry extends EventDispatcher { + constructor() { + super(); + this.isBufferGeometry = true; + Object.defineProperty(this, "id", { value: _id$1++ }); + this.uuid = generateUUID(); + this.name = ""; + this.type = "BufferGeometry"; + this.index = null; + this.indirect = null; + this.attributes = {}; + this.morphAttributes = {}; + this.morphTargetsRelative = false; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + this.drawRange = { start: 0, count: Infinity }; + this.userData = {}; + } + getIndex() { + return this.index; + } + setIndex(index2) { + if (Array.isArray(index2)) { + this.index = new ((arrayNeedsUint32(index2)) ? Uint32BufferAttribute : Uint16BufferAttribute)(index2, 1); + } else { + this.index = index2; + } + return this; + } + setIndirect(indirect) { + this.indirect = indirect; + return this; + } + getIndirect() { + return this.indirect; + } + getAttribute(name2) { + return this.attributes[name2]; + } + setAttribute(name2, attribute) { + this.attributes[name2] = attribute; + return this; + } + deleteAttribute(name2) { + delete this.attributes[name2]; + return this; + } + hasAttribute(name2) { + return this.attributes[name2] !== undefined; + } + addGroup(start, count, materialIndex = 0) { + this.groups.push({ + start, + count, + materialIndex + }); + } + clearGroups() { + this.groups = []; + } + setDrawRange(start, count) { + this.drawRange.start = start; + this.drawRange.count = count; + } + applyMatrix4(matrix) { + const position2 = this.attributes.position; + if (position2 !== undefined) { + position2.applyMatrix4(matrix); + position2.needsUpdate = true; + } + const normal = this.attributes.normal; + if (normal !== undefined) { + const normalMatrix = new Matrix3().getNormalMatrix(matrix); + normal.applyNormalMatrix(normalMatrix); + normal.needsUpdate = true; + } + const tangent = this.attributes.tangent; + if (tangent !== undefined) { + tangent.transformDirection(matrix); + tangent.needsUpdate = true; + } + if (this.boundingBox !== null) { + this.computeBoundingBox(); + } + if (this.boundingSphere !== null) { + this.computeBoundingSphere(); + } + return this; + } + applyQuaternion(q) { + _m1.makeRotationFromQuaternion(q); + this.applyMatrix4(_m1); + return this; + } + rotateX(angle) { + _m1.makeRotationX(angle); + this.applyMatrix4(_m1); + return this; + } + rotateY(angle) { + _m1.makeRotationY(angle); + this.applyMatrix4(_m1); + return this; + } + rotateZ(angle) { + _m1.makeRotationZ(angle); + this.applyMatrix4(_m1); + return this; + } + translate(x, y, z) { + _m1.makeTranslation(x, y, z); + this.applyMatrix4(_m1); + return this; + } + scale(x, y, z) { + _m1.makeScale(x, y, z); + this.applyMatrix4(_m1); + return this; + } + lookAt(vector) { + _obj.lookAt(vector); + _obj.updateMatrix(); + this.applyMatrix4(_obj.matrix); + return this; + } + center() { + this.computeBoundingBox(); + this.boundingBox.getCenter(_offset).negate(); + this.translate(_offset.x, _offset.y, _offset.z); + return this; + } + setFromPoints(points) { + const positionAttribute = this.getAttribute("position"); + if (positionAttribute === undefined) { + const position2 = []; + for (let i = 0, l = points.length;i < l; i++) { + const point = points[i]; + position2.push(point.x, point.y, point.z || 0); + } + this.setAttribute("position", new Float32BufferAttribute(position2, 3)); + } else { + const l = Math.min(points.length, positionAttribute.count); + for (let i = 0;i < l; i++) { + const point = points[i]; + positionAttribute.setXYZ(i, point.x, point.y, point.z || 0); + } + if (points.length > positionAttribute.count) { + console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."); + } + positionAttribute.needsUpdate = true; + } + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box3; + } + const position2 = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position2 && position2.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this); + this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(Infinity, Infinity, Infinity)); + return; + } + if (position2 !== undefined) { + this.boundingBox.setFromBufferAttribute(position2); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _box$2.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$8.addVectors(this.boundingBox.min, _box$2.min); + this.boundingBox.expandByPoint(_vector$8); + _vector$8.addVectors(this.boundingBox.max, _box$2.max); + this.boundingBox.expandByPoint(_vector$8); + } else { + this.boundingBox.expandByPoint(_box$2.min); + this.boundingBox.expandByPoint(_box$2.max); + } + } + } + } else { + this.boundingBox.makeEmpty(); + } + if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) { + console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere; + } + const position2 = this.attributes.position; + const morphAttributesPosition = this.morphAttributes.position; + if (position2 && position2.isGLBufferAttribute) { + console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this); + this.boundingSphere.set(new Vector3, Infinity); + return; + } + if (position2) { + const center = this.boundingSphere.center; + _box$2.setFromBufferAttribute(position2); + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + _boxMorphTargets.setFromBufferAttribute(morphAttribute); + if (this.morphTargetsRelative) { + _vector$8.addVectors(_box$2.min, _boxMorphTargets.min); + _box$2.expandByPoint(_vector$8); + _vector$8.addVectors(_box$2.max, _boxMorphTargets.max); + _box$2.expandByPoint(_vector$8); + } else { + _box$2.expandByPoint(_boxMorphTargets.min); + _box$2.expandByPoint(_boxMorphTargets.max); + } + } + } + _box$2.getCenter(center); + let maxRadiusSq = 0; + for (let i = 0, il = position2.count;i < il; i++) { + _vector$8.fromBufferAttribute(position2, i); + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); + } + if (morphAttributesPosition) { + for (let i = 0, il = morphAttributesPosition.length;i < il; i++) { + const morphAttribute = morphAttributesPosition[i]; + const morphTargetsRelative = this.morphTargetsRelative; + for (let j = 0, jl = morphAttribute.count;j < jl; j++) { + _vector$8.fromBufferAttribute(morphAttribute, j); + if (morphTargetsRelative) { + _offset.fromBufferAttribute(position2, j); + _vector$8.add(_offset); + } + maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); + } + } + } + this.boundingSphere.radius = Math.sqrt(maxRadiusSq); + if (isNaN(this.boundingSphere.radius)) { + console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); + } + } + } + computeTangents() { + const index2 = this.index; + const attributes = this.attributes; + if (index2 === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) { + console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); + return; + } + const positionAttribute = attributes.position; + const normalAttribute = attributes.normal; + const uvAttribute = attributes.uv; + if (this.hasAttribute("tangent") === false) { + this.setAttribute("tangent", new BufferAttribute(new Float32Array(4 * positionAttribute.count), 4)); + } + const tangentAttribute = this.getAttribute("tangent"); + const tan1 = [], tan2 = []; + for (let i = 0;i < positionAttribute.count; i++) { + tan1[i] = new Vector3; + tan2[i] = new Vector3; + } + const vA = new Vector3, vB = new Vector3, vC = new Vector3, uvA = new Vector2, uvB = new Vector2, uvC = new Vector2, sdir = new Vector3, tdir = new Vector3; + function handleTriangle(a, b, c) { + vA.fromBufferAttribute(positionAttribute, a); + vB.fromBufferAttribute(positionAttribute, b); + vC.fromBufferAttribute(positionAttribute, c); + uvA.fromBufferAttribute(uvAttribute, a); + uvB.fromBufferAttribute(uvAttribute, b); + uvC.fromBufferAttribute(uvAttribute, c); + vB.sub(vA); + vC.sub(vA); + uvB.sub(uvA); + uvC.sub(uvA); + const r = 1 / (uvB.x * uvC.y - uvC.x * uvB.y); + if (!isFinite(r)) + return; + sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r); + tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r); + tan1[a].add(sdir); + tan1[b].add(sdir); + tan1[c].add(sdir); + tan2[a].add(tdir); + tan2[b].add(tdir); + tan2[c].add(tdir); + } + let groups = this.groups; + if (groups.length === 0) { + groups = [{ + start: 0, + count: index2.count + }]; + } + for (let i = 0, il = groups.length;i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j = start, jl = start + count;j < jl; j += 3) { + handleTriangle(index2.getX(j + 0), index2.getX(j + 1), index2.getX(j + 2)); + } + } + const tmp = new Vector3, tmp2 = new Vector3; + const n = new Vector3, n2 = new Vector3; + function handleVertex(v) { + n.fromBufferAttribute(normalAttribute, v); + n2.copy(n); + const t = tan1[v]; + tmp.copy(t); + tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); + tmp2.crossVectors(n2, t); + const test = tmp2.dot(tan2[v]); + const w = test < 0 ? -1 : 1; + tangentAttribute.setXYZW(v, tmp.x, tmp.y, tmp.z, w); + } + for (let i = 0, il = groups.length;i < il; ++i) { + const group = groups[i]; + const start = group.start; + const count = group.count; + for (let j = start, jl = start + count;j < jl; j += 3) { + handleVertex(index2.getX(j + 0)); + handleVertex(index2.getX(j + 1)); + handleVertex(index2.getX(j + 2)); + } + } + } + computeVertexNormals() { + const index2 = this.index; + const positionAttribute = this.getAttribute("position"); + if (positionAttribute !== undefined) { + let normalAttribute = this.getAttribute("normal"); + if (normalAttribute === undefined) { + normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3); + this.setAttribute("normal", normalAttribute); + } else { + for (let i = 0, il = normalAttribute.count;i < il; i++) { + normalAttribute.setXYZ(i, 0, 0, 0); + } + } + const pA = new Vector3, pB = new Vector3, pC = new Vector3; + const nA = new Vector3, nB = new Vector3, nC = new Vector3; + const cb = new Vector3, ab = new Vector3; + if (index2) { + for (let i = 0, il = index2.count;i < il; i += 3) { + const vA = index2.getX(i + 0); + const vB = index2.getX(i + 1); + const vC = index2.getX(i + 2); + pA.fromBufferAttribute(positionAttribute, vA); + pB.fromBufferAttribute(positionAttribute, vB); + pC.fromBufferAttribute(positionAttribute, vC); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + nA.fromBufferAttribute(normalAttribute, vA); + nB.fromBufferAttribute(normalAttribute, vB); + nC.fromBufferAttribute(normalAttribute, vC); + nA.add(cb); + nB.add(cb); + nC.add(cb); + normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z); + normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z); + normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z); + } + } else { + for (let i = 0, il = positionAttribute.count;i < il; i += 3) { + pA.fromBufferAttribute(positionAttribute, i + 0); + pB.fromBufferAttribute(positionAttribute, i + 1); + pC.fromBufferAttribute(positionAttribute, i + 2); + cb.subVectors(pC, pB); + ab.subVectors(pA, pB); + cb.cross(ab); + normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z); + normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z); + } + } + this.normalizeNormals(); + normalAttribute.needsUpdate = true; + } + } + normalizeNormals() { + const normals = this.attributes.normal; + for (let i = 0, il = normals.count;i < il; i++) { + _vector$8.fromBufferAttribute(normals, i); + _vector$8.normalize(); + normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z); + } + } + toNonIndexed() { + function convertBufferAttribute(attribute, indices2) { + const array = attribute.array; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + const array2 = new array.constructor(indices2.length * itemSize); + let index2 = 0, index22 = 0; + for (let i = 0, l = indices2.length;i < l; i++) { + if (attribute.isInterleavedBufferAttribute) { + index2 = indices2[i] * attribute.data.stride + attribute.offset; + } else { + index2 = indices2[i] * itemSize; + } + for (let j = 0;j < itemSize; j++) { + array2[index22++] = array[index2++]; + } + } + return new BufferAttribute(array2, itemSize, normalized); + } + if (this.index === null) { + console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."); + return this; + } + const geometry2 = new BufferGeometry; + const indices = this.index.array; + const attributes = this.attributes; + for (const name2 in attributes) { + const attribute = attributes[name2]; + const newAttribute = convertBufferAttribute(attribute, indices); + geometry2.setAttribute(name2, newAttribute); + } + const morphAttributes = this.morphAttributes; + for (const name2 in morphAttributes) { + const morphArray = []; + const morphAttribute = morphAttributes[name2]; + for (let i = 0, il = morphAttribute.length;i < il; i++) { + const attribute = morphAttribute[i]; + const newAttribute = convertBufferAttribute(attribute, indices); + morphArray.push(newAttribute); + } + geometry2.morphAttributes[name2] = morphArray; + } + geometry2.morphTargetsRelative = this.morphTargetsRelative; + const groups = this.groups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + geometry2.addGroup(group.start, group.count, group.materialIndex); + } + return geometry2; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "BufferGeometry", + generator: "BufferGeometry.toJSON" + } + }; + data2.uuid = this.uuid; + data2.type = this.type; + if (this.name !== "") + data2.name = this.name; + if (Object.keys(this.userData).length > 0) + data2.userData = this.userData; + if (this.parameters !== undefined) { + const parameters = this.parameters; + for (const key2 in parameters) { + if (parameters[key2] !== undefined) + data2[key2] = parameters[key2]; + } + return data2; + } + data2.data = { attributes: {} }; + const index2 = this.index; + if (index2 !== null) { + data2.data.index = { + type: index2.array.constructor.name, + array: Array.prototype.slice.call(index2.array) + }; + } + const attributes = this.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + data2.data.attributes[key2] = attribute.toJSON(data2.data); + } + const morphAttributes = {}; + let hasMorphAttributes = false; + for (const key2 in this.morphAttributes) { + const attributeArray = this.morphAttributes[key2]; + const array = []; + for (let i = 0, il = attributeArray.length;i < il; i++) { + const attribute = attributeArray[i]; + array.push(attribute.toJSON(data2.data)); + } + if (array.length > 0) { + morphAttributes[key2] = array; + hasMorphAttributes = true; + } + } + if (hasMorphAttributes) { + data2.data.morphAttributes = morphAttributes; + data2.data.morphTargetsRelative = this.morphTargetsRelative; + } + const groups = this.groups; + if (groups.length > 0) { + data2.data.groups = JSON.parse(JSON.stringify(groups)); + } + const boundingSphere = this.boundingSphere; + if (boundingSphere !== null) { + data2.data.boundingSphere = { + center: boundingSphere.center.toArray(), + radius: boundingSphere.radius + }; + } + return data2; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.index = null; + this.attributes = {}; + this.morphAttributes = {}; + this.groups = []; + this.boundingBox = null; + this.boundingSphere = null; + const data2 = {}; + this.name = source.name; + const index2 = source.index; + if (index2 !== null) { + this.setIndex(index2.clone(data2)); + } + const attributes = source.attributes; + for (const name2 in attributes) { + const attribute = attributes[name2]; + this.setAttribute(name2, attribute.clone(data2)); + } + const morphAttributes = source.morphAttributes; + for (const name2 in morphAttributes) { + const array = []; + const morphAttribute = morphAttributes[name2]; + for (let i = 0, l = morphAttribute.length;i < l; i++) { + array.push(morphAttribute[i].clone(data2)); + } + this.morphAttributes[name2] = array; + } + this.morphTargetsRelative = source.morphTargetsRelative; + const groups = source.groups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + this.addGroup(group.start, group.count, group.materialIndex); + } + const boundingBox = source.boundingBox; + if (boundingBox !== null) { + this.boundingBox = boundingBox.clone(); + } + const boundingSphere = source.boundingSphere; + if (boundingSphere !== null) { + this.boundingSphere = boundingSphere.clone(); + } + this.drawRange.start = source.drawRange.start; + this.drawRange.count = source.drawRange.count; + this.userData = source.userData; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + } +} +var _inverseMatrix$3 = /* @__PURE__ */ new Matrix4; +var _ray$3 = /* @__PURE__ */ new Ray; +var _sphere$6 = /* @__PURE__ */ new Sphere; +var _sphereHitAt = /* @__PURE__ */ new Vector3; +var _vA$1 = /* @__PURE__ */ new Vector3; +var _vB$1 = /* @__PURE__ */ new Vector3; +var _vC$1 = /* @__PURE__ */ new Vector3; +var _tempA = /* @__PURE__ */ new Vector3; +var _morphA = /* @__PURE__ */ new Vector3; +var _intersectionPoint = /* @__PURE__ */ new Vector3; +var _intersectionPointWorld = /* @__PURE__ */ new Vector3; + +class Mesh extends Object3D { + constructor(geometry = new BufferGeometry, material = new MeshBasicMaterial) { + super(); + this.isMesh = true; + this.type = "Mesh"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.morphTargetInfluences !== undefined) { + this.morphTargetInfluences = source.morphTargetInfluences.slice(); + } + if (source.morphTargetDictionary !== undefined) { + this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary); + } + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } + getVertexPosition(index2, target) { + const geometry = this.geometry; + const position2 = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + target.fromBufferAttribute(position2, index2); + const morphInfluences = this.morphTargetInfluences; + if (morphPosition && morphInfluences) { + _morphA.set(0, 0, 0); + for (let i = 0, il = morphPosition.length;i < il; i++) { + const influence = morphInfluences[i]; + const morphAttribute = morphPosition[i]; + if (influence === 0) + continue; + _tempA.fromBufferAttribute(morphAttribute, index2); + if (morphTargetsRelative) { + _morphA.addScaledVector(_tempA, influence); + } else { + _morphA.addScaledVector(_tempA.sub(target), influence); + } + } + target.add(_morphA); + } + return target; + } + raycast(raycaster, intersects) { + const geometry = this.geometry; + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === undefined) + return; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$6.copy(geometry.boundingSphere); + _sphere$6.applyMatrix4(matrixWorld); + _ray$3.copy(raycaster.ray).recast(raycaster.near); + if (_sphere$6.containsPoint(_ray$3.origin) === false) { + if (_ray$3.intersectSphere(_sphere$6, _sphereHitAt) === null) + return; + if (_ray$3.origin.distanceToSquared(_sphereHitAt) > (raycaster.far - raycaster.near) ** 2) + return; + } + _inverseMatrix$3.copy(matrixWorld).invert(); + _ray$3.copy(raycaster.ray).applyMatrix4(_inverseMatrix$3); + if (geometry.boundingBox !== null) { + if (_ray$3.intersectsBox(geometry.boundingBox) === false) + return; + } + this._computeIntersections(raycaster, intersects, _ray$3); + } + _computeIntersections(raycaster, intersects, rayLocalSpace) { + let intersection; + const geometry = this.geometry; + const material = this.material; + const index2 = geometry.index; + const position2 = geometry.attributes.position; + const uv = geometry.attributes.uv; + const uv1 = geometry.attributes.uv1; + const normal = geometry.attributes.normal; + const groups = geometry.groups; + const drawRange = geometry.drawRange; + if (index2 !== null) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length;i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(index2.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j = start, jl = end;j < jl; j += 3) { + const a = index2.getX(j); + const b = index2.getX(j + 1); + const c = index2.getX(j + 2); + intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(j / 3); + intersection.face.materialIndex = group.materialIndex; + intersects.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i += 3) { + const a = index2.getX(i); + const b = index2.getX(i + 1); + const c = index2.getX(i + 2); + intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects.push(intersection); + } + } + } + } else if (position2 !== undefined) { + if (Array.isArray(material)) { + for (let i = 0, il = groups.length;i < il; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + const start = Math.max(group.start, drawRange.start); + const end = Math.min(position2.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); + for (let j = start, jl = end;j < jl; j += 3) { + const a = j; + const b = j + 1; + const c = j + 2; + intersection = checkGeometryIntersection(this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(j / 3); + intersection.face.materialIndex = group.materialIndex; + intersects.push(intersection); + } + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(position2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i += 3) { + const a = i; + const b = i + 1; + const c = i + 2; + intersection = checkGeometryIntersection(this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c); + if (intersection) { + intersection.faceIndex = Math.floor(i / 3); + intersects.push(intersection); + } + } + } + } + } +} +function checkIntersection$1(object, material, raycaster, ray, pA, pB, pC, point) { + let intersect; + if (material.side === BackSide) { + intersect = ray.intersectTriangle(pC, pB, pA, true, point); + } else { + intersect = ray.intersectTriangle(pA, pB, pC, material.side === FrontSide, point); + } + if (intersect === null) + return null; + _intersectionPointWorld.copy(point); + _intersectionPointWorld.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld); + if (distance < raycaster.near || distance > raycaster.far) + return null; + return { + distance, + point: _intersectionPointWorld.clone(), + object + }; +} +function checkGeometryIntersection(object, material, raycaster, ray, uv, uv1, normal, a, b, c) { + object.getVertexPosition(a, _vA$1); + object.getVertexPosition(b, _vB$1); + object.getVertexPosition(c, _vC$1); + const intersection = checkIntersection$1(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint); + if (intersection) { + const barycoord = new Vector3; + Triangle.getBarycoord(_intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord); + if (uv) { + intersection.uv = Triangle.getInterpolatedAttribute(uv, a, b, c, barycoord, new Vector2); + } + if (uv1) { + intersection.uv1 = Triangle.getInterpolatedAttribute(uv1, a, b, c, barycoord, new Vector2); + } + if (normal) { + intersection.normal = Triangle.getInterpolatedAttribute(normal, a, b, c, barycoord, new Vector3); + if (intersection.normal.dot(ray.direction) > 0) { + intersection.normal.multiplyScalar(-1); + } + } + const face = { + a, + b, + c, + normal: new Vector3, + materialIndex: 0 + }; + Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal); + intersection.face = face; + intersection.barycoord = barycoord; + } + return intersection; +} + +class BoxGeometry extends BufferGeometry { + constructor(width2 = 1, height2 = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) { + super(); + this.type = "BoxGeometry"; + this.parameters = { + width: width2, + height: height2, + depth, + widthSegments, + heightSegments, + depthSegments + }; + const scope = this; + widthSegments = Math.floor(widthSegments); + heightSegments = Math.floor(heightSegments); + depthSegments = Math.floor(depthSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let numberOfVertices = 0; + let groupStart = 0; + buildPlane("z", "y", "x", -1, -1, depth, height2, width2, depthSegments, heightSegments, 0); + buildPlane("z", "y", "x", 1, -1, depth, height2, -width2, depthSegments, heightSegments, 1); + buildPlane("x", "z", "y", 1, 1, width2, depth, height2, widthSegments, depthSegments, 2); + buildPlane("x", "z", "y", 1, -1, width2, depth, -height2, widthSegments, depthSegments, 3); + buildPlane("x", "y", "z", 1, -1, width2, height2, depth, widthSegments, heightSegments, 4); + buildPlane("x", "y", "z", -1, -1, width2, height2, -depth, widthSegments, heightSegments, 5); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function buildPlane(u, v, w, udir, vdir, width3, height3, depth2, gridX, gridY, materialIndex) { + const segmentWidth = width3 / gridX; + const segmentHeight = height3 / gridY; + const widthHalf = width3 / 2; + const heightHalf = height3 / 2; + const depthHalf = depth2 / 2; + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + let vertexCounter = 0; + let groupCount = 0; + const vector = new Vector3; + for (let iy = 0;iy < gridY1; iy++) { + const y = iy * segmentHeight - heightHalf; + for (let ix = 0;ix < gridX1; ix++) { + const x = ix * segmentWidth - widthHalf; + vector[u] = x * udir; + vector[v] = y * vdir; + vector[w] = depthHalf; + vertices.push(vector.x, vector.y, vector.z); + vector[u] = 0; + vector[v] = 0; + vector[w] = depth2 > 0 ? 1 : -1; + normals.push(vector.x, vector.y, vector.z); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + vertexCounter += 1; + } + } + for (let iy = 0;iy < gridY; iy++) { + for (let ix = 0;ix < gridX; ix++) { + const a = numberOfVertices + ix + gridX1 * iy; + const b = numberOfVertices + ix + gridX1 * (iy + 1); + const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1); + const d = numberOfVertices + (ix + 1) + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + groupCount += 6; + } + } + scope.addGroup(groupStart, groupCount, materialIndex); + groupStart += groupCount; + numberOfVertices += vertexCounter; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new BoxGeometry(data2.width, data2.height, data2.depth, data2.widthSegments, data2.heightSegments, data2.depthSegments); + } +} +function cloneUniforms(src) { + const dst = {}; + for (const u in src) { + dst[u] = {}; + for (const p in src[u]) { + const property2 = src[u][p]; + if (property2 && (property2.isColor || property2.isMatrix3 || property2.isMatrix4 || property2.isVector2 || property2.isVector3 || property2.isVector4 || property2.isTexture || property2.isQuaternion)) { + if (property2.isRenderTargetTexture) { + console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."); + dst[u][p] = null; + } else { + dst[u][p] = property2.clone(); + } + } else if (Array.isArray(property2)) { + dst[u][p] = property2.slice(); + } else { + dst[u][p] = property2; + } + } + } + return dst; +} +function mergeUniforms(uniforms) { + const merged = {}; + for (let u = 0;u < uniforms.length; u++) { + const tmp = cloneUniforms(uniforms[u]); + for (const p in tmp) { + merged[p] = tmp[p]; + } + } + return merged; +} +function cloneUniformsGroups(src) { + const dst = []; + for (let u = 0;u < src.length; u++) { + dst.push(src[u].clone()); + } + return dst; +} +function getUnlitUniformColorSpace(renderer2) { + const currentRenderTarget = renderer2.getRenderTarget(); + if (currentRenderTarget === null) { + return renderer2.outputColorSpace; + } + if (currentRenderTarget.isXRRenderTarget === true) { + return currentRenderTarget.texture.colorSpace; + } + return ColorManagement.workingColorSpace; +} +var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; +var default_vertex = `void main() { + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); +}`; +var default_fragment = `void main() { + gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); +}`; + +class ShaderMaterial extends Material { + constructor(parameters) { + super(); + this.isShaderMaterial = true; + this.type = "ShaderMaterial"; + this.defines = {}; + this.uniforms = {}; + this.uniformsGroups = []; + this.vertexShader = default_vertex; + this.fragmentShader = default_fragment; + this.linewidth = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.fog = false; + this.lights = false; + this.clipping = false; + this.forceSinglePass = true; + this.extensions = { + clipCullDistance: false, + multiDraw: false + }; + this.defaultAttributeValues = { + color: [1, 1, 1], + uv: [0, 0], + uv1: [0, 0] + }; + this.index0AttributeName = undefined; + this.uniformsNeedUpdate = false; + this.glslVersion = null; + if (parameters !== undefined) { + this.setValues(parameters); + } + } + copy(source) { + super.copy(source); + this.fragmentShader = source.fragmentShader; + this.vertexShader = source.vertexShader; + this.uniforms = cloneUniforms(source.uniforms); + this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups); + this.defines = Object.assign({}, source.defines); + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.fog = source.fog; + this.lights = source.lights; + this.clipping = source.clipping; + this.extensions = Object.assign({}, source.extensions); + this.glslVersion = source.glslVersion; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.glslVersion = this.glslVersion; + data2.uniforms = {}; + for (const name2 in this.uniforms) { + const uniform = this.uniforms[name2]; + const value2 = uniform.value; + if (value2 && value2.isTexture) { + data2.uniforms[name2] = { + type: "t", + value: value2.toJSON(meta).uuid + }; + } else if (value2 && value2.isColor) { + data2.uniforms[name2] = { + type: "c", + value: value2.getHex() + }; + } else if (value2 && value2.isVector2) { + data2.uniforms[name2] = { + type: "v2", + value: value2.toArray() + }; + } else if (value2 && value2.isVector3) { + data2.uniforms[name2] = { + type: "v3", + value: value2.toArray() + }; + } else if (value2 && value2.isVector4) { + data2.uniforms[name2] = { + type: "v4", + value: value2.toArray() + }; + } else if (value2 && value2.isMatrix3) { + data2.uniforms[name2] = { + type: "m3", + value: value2.toArray() + }; + } else if (value2 && value2.isMatrix4) { + data2.uniforms[name2] = { + type: "m4", + value: value2.toArray() + }; + } else { + data2.uniforms[name2] = { + value: value2 + }; + } + } + if (Object.keys(this.defines).length > 0) + data2.defines = this.defines; + data2.vertexShader = this.vertexShader; + data2.fragmentShader = this.fragmentShader; + data2.lights = this.lights; + data2.clipping = this.clipping; + const extensions = {}; + for (const key2 in this.extensions) { + if (this.extensions[key2] === true) + extensions[key2] = true; + } + if (Object.keys(extensions).length > 0) + data2.extensions = extensions; + return data2; + } +} + +class Camera extends Object3D { + constructor() { + super(); + this.isCamera = true; + this.type = "Camera"; + this.matrixWorldInverse = new Matrix4; + this.projectionMatrix = new Matrix4; + this.projectionMatrixInverse = new Matrix4; + this.coordinateSystem = WebGLCoordinateSystem; + } + copy(source, recursive) { + super.copy(source, recursive); + this.matrixWorldInverse.copy(source.matrixWorldInverse); + this.projectionMatrix.copy(source.projectionMatrix); + this.projectionMatrixInverse.copy(source.projectionMatrixInverse); + this.coordinateSystem = source.coordinateSystem; + return this; + } + getWorldDirection(target) { + return super.getWorldDirection(target).negate(); + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + updateWorldMatrix(updateParents, updateChildren) { + super.updateWorldMatrix(updateParents, updateChildren); + this.matrixWorldInverse.copy(this.matrixWorld).invert(); + } + clone() { + return new this.constructor().copy(this); + } +} +var _v3$1 = /* @__PURE__ */ new Vector3; +var _minTarget = /* @__PURE__ */ new Vector2; +var _maxTarget = /* @__PURE__ */ new Vector2; + +class PerspectiveCamera extends Camera { + constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) { + super(); + this.isPerspectiveCamera = true; + this.type = "PerspectiveCamera"; + this.fov = fov; + this.zoom = 1; + this.near = near; + this.far = far; + this.focus = 10; + this.aspect = aspect; + this.view = null; + this.filmGauge = 35; + this.filmOffset = 0; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.fov = source.fov; + this.zoom = source.zoom; + this.near = source.near; + this.far = source.far; + this.focus = source.focus; + this.aspect = source.aspect; + this.view = source.view === null ? null : Object.assign({}, source.view); + this.filmGauge = source.filmGauge; + this.filmOffset = source.filmOffset; + return this; + } + setFocalLength(focalLength) { + const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; + this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope); + this.updateProjectionMatrix(); + } + getFocalLength() { + const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov); + return 0.5 * this.getFilmHeight() / vExtentSlope; + } + getEffectiveFOV() { + return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom); + } + getFilmWidth() { + return this.filmGauge * Math.min(this.aspect, 1); + } + getFilmHeight() { + return this.filmGauge / Math.max(this.aspect, 1); + } + getViewBounds(distance, minTarget, maxTarget) { + _v3$1.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse); + minTarget.set(_v3$1.x, _v3$1.y).multiplyScalar(-distance / _v3$1.z); + _v3$1.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse); + maxTarget.set(_v3$1.x, _v3$1.y).multiplyScalar(-distance / _v3$1.z); + } + getViewSize(distance, target) { + this.getViewBounds(distance, _minTarget, _maxTarget); + return target.subVectors(_maxTarget, _minTarget); + } + setViewOffset(fullWidth, fullHeight, x, y, width2, height2) { + this.aspect = fullWidth / fullHeight; + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width2; + this.view.height = height2; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const near = this.near; + let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom; + let height2 = 2 * top; + let width2 = this.aspect * height2; + let left = -0.5 * width2; + const view = this.view; + if (this.view !== null && this.view.enabled) { + const { fullWidth, fullHeight } = view; + left += view.offsetX * width2 / fullWidth; + top -= view.offsetY * height2 / fullHeight; + width2 *= view.width / fullWidth; + height2 *= view.height / fullHeight; + } + const skew = this.filmOffset; + if (skew !== 0) + left += near * skew / this.getFilmWidth(); + this.projectionMatrix.makePerspective(left, left + width2, top, top - height2, near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.fov = this.fov; + data2.object.zoom = this.zoom; + data2.object.near = this.near; + data2.object.far = this.far; + data2.object.focus = this.focus; + data2.object.aspect = this.aspect; + if (this.view !== null) + data2.object.view = Object.assign({}, this.view); + data2.object.filmGauge = this.filmGauge; + data2.object.filmOffset = this.filmOffset; + return data2; + } +} +var fov = -90; +var aspect = 1; + +class CubeCamera extends Object3D { + constructor(near, far, renderTarget) { + super(); + this.type = "CubeCamera"; + this.renderTarget = renderTarget; + this.coordinateSystem = null; + this.activeMipmapLevel = 0; + const cameraPX = new PerspectiveCamera(fov, aspect, near, far); + cameraPX.layers = this.layers; + this.add(cameraPX); + const cameraNX = new PerspectiveCamera(fov, aspect, near, far); + cameraNX.layers = this.layers; + this.add(cameraNX); + const cameraPY = new PerspectiveCamera(fov, aspect, near, far); + cameraPY.layers = this.layers; + this.add(cameraPY); + const cameraNY = new PerspectiveCamera(fov, aspect, near, far); + cameraNY.layers = this.layers; + this.add(cameraNY); + const cameraPZ = new PerspectiveCamera(fov, aspect, near, far); + cameraPZ.layers = this.layers; + this.add(cameraPZ); + const cameraNZ = new PerspectiveCamera(fov, aspect, near, far); + cameraNZ.layers = this.layers; + this.add(cameraNZ); + } + updateCoordinateSystem() { + const coordinateSystem = this.coordinateSystem; + const cameras = this.children.concat(); + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = cameras; + for (const camera of cameras) + this.remove(camera); + if (coordinateSystem === WebGLCoordinateSystem) { + cameraPX.up.set(0, 1, 0); + cameraPX.lookAt(1, 0, 0); + cameraNX.up.set(0, 1, 0); + cameraNX.lookAt(-1, 0, 0); + cameraPY.up.set(0, 0, -1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, 1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, 1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, 1, 0); + cameraNZ.lookAt(0, 0, -1); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + cameraPX.up.set(0, -1, 0); + cameraPX.lookAt(-1, 0, 0); + cameraNX.up.set(0, -1, 0); + cameraNX.lookAt(1, 0, 0); + cameraPY.up.set(0, 0, 1); + cameraPY.lookAt(0, 1, 0); + cameraNY.up.set(0, 0, -1); + cameraNY.lookAt(0, -1, 0); + cameraPZ.up.set(0, -1, 0); + cameraPZ.lookAt(0, 0, 1); + cameraNZ.up.set(0, -1, 0); + cameraNZ.lookAt(0, 0, -1); + } else { + throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + coordinateSystem); + } + for (const camera of cameras) { + this.add(camera); + camera.updateMatrixWorld(); + } + } + update(renderer2, scene) { + if (this.parent === null) + this.updateMatrixWorld(); + const { renderTarget, activeMipmapLevel } = this; + if (this.coordinateSystem !== renderer2.coordinateSystem) { + this.coordinateSystem = renderer2.coordinateSystem; + this.updateCoordinateSystem(); + } + const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children; + const currentRenderTarget = renderer2.getRenderTarget(); + const currentActiveCubeFace = renderer2.getActiveCubeFace(); + const currentActiveMipmapLevel = renderer2.getActiveMipmapLevel(); + const currentXrEnabled = renderer2.xr.enabled; + renderer2.xr.enabled = false; + const generateMipmaps = renderTarget.texture.generateMipmaps; + renderTarget.texture.generateMipmaps = false; + renderer2.setRenderTarget(renderTarget, 0, activeMipmapLevel); + renderer2.render(scene, cameraPX); + renderer2.setRenderTarget(renderTarget, 1, activeMipmapLevel); + renderer2.render(scene, cameraNX); + renderer2.setRenderTarget(renderTarget, 2, activeMipmapLevel); + renderer2.render(scene, cameraPY); + renderer2.setRenderTarget(renderTarget, 3, activeMipmapLevel); + renderer2.render(scene, cameraNY); + renderer2.setRenderTarget(renderTarget, 4, activeMipmapLevel); + renderer2.render(scene, cameraPZ); + renderTarget.texture.generateMipmaps = generateMipmaps; + renderer2.setRenderTarget(renderTarget, 5, activeMipmapLevel); + renderer2.render(scene, cameraNZ); + renderer2.setRenderTarget(currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel); + renderer2.xr.enabled = currentXrEnabled; + renderTarget.texture.needsPMREMUpdate = true; + } +} + +class CubeTexture extends Texture { + constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace) { + images = images !== undefined ? images : []; + mapping = mapping !== undefined ? mapping : CubeReflectionMapping; + super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCubeTexture = true; + this.flipY = false; + } + get images() { + return this.image; + } + set images(value2) { + this.image = value2; + } +} + +class WebGLCubeRenderTarget extends WebGLRenderTarget { + constructor(size = 1, options = {}) { + super(size, size, options); + this.isWebGLCubeRenderTarget = true; + const image = { width: size, height: size, depth: 1 }; + const images = [image, image, image, image, image, image]; + this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace); + this.texture.isRenderTargetTexture = true; + this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false; + this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter; + } + fromEquirectangularTexture(renderer2, texture) { + this.texture.type = texture.type; + this.texture.colorSpace = texture.colorSpace; + this.texture.generateMipmaps = texture.generateMipmaps; + this.texture.minFilter = texture.minFilter; + this.texture.magFilter = texture.magFilter; + const shader = { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `, + fragmentShader: ` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + ` + }; + const geometry = new BoxGeometry(5, 5, 5); + const material = new ShaderMaterial({ + name: "CubemapFromEquirect", + uniforms: cloneUniforms(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + blending: NoBlending + }); + material.uniforms.tEquirect.value = texture; + const mesh = new Mesh(geometry, material); + const currentMinFilter = texture.minFilter; + if (texture.minFilter === LinearMipmapLinearFilter) + texture.minFilter = LinearFilter; + const camera = new CubeCamera(1, 10, this); + camera.update(renderer2, mesh); + texture.minFilter = currentMinFilter; + mesh.geometry.dispose(); + mesh.material.dispose(); + return this; + } + clear(renderer2, color, depth, stencil) { + const currentRenderTarget = renderer2.getRenderTarget(); + for (let i = 0;i < 6; i++) { + renderer2.setRenderTarget(this, i); + renderer2.clear(color, depth, stencil); + } + renderer2.setRenderTarget(currentRenderTarget); + } +} + +class Group extends Object3D { + constructor() { + super(); + this.isGroup = true; + this.type = "Group"; + } +} +var _moveEvent = { type: "move" }; + +class WebXRController { + constructor() { + this._targetRay = null; + this._grip = null; + this._hand = null; + } + getHandSpace() { + if (this._hand === null) { + this._hand = new Group; + this._hand.matrixAutoUpdate = false; + this._hand.visible = false; + this._hand.joints = {}; + this._hand.inputState = { pinching: false }; + } + return this._hand; + } + getTargetRaySpace() { + if (this._targetRay === null) { + this._targetRay = new Group; + this._targetRay.matrixAutoUpdate = false; + this._targetRay.visible = false; + this._targetRay.hasLinearVelocity = false; + this._targetRay.linearVelocity = new Vector3; + this._targetRay.hasAngularVelocity = false; + this._targetRay.angularVelocity = new Vector3; + } + return this._targetRay; + } + getGripSpace() { + if (this._grip === null) { + this._grip = new Group; + this._grip.matrixAutoUpdate = false; + this._grip.visible = false; + this._grip.hasLinearVelocity = false; + this._grip.linearVelocity = new Vector3; + this._grip.hasAngularVelocity = false; + this._grip.angularVelocity = new Vector3; + } + return this._grip; + } + dispatchEvent(event) { + if (this._targetRay !== null) { + this._targetRay.dispatchEvent(event); + } + if (this._grip !== null) { + this._grip.dispatchEvent(event); + } + if (this._hand !== null) { + this._hand.dispatchEvent(event); + } + return this; + } + connect(inputSource) { + if (inputSource && inputSource.hand) { + const hand = this._hand; + if (hand) { + for (const inputjoint of inputSource.hand.values()) { + this._getHandJoint(hand, inputjoint); + } + } + } + this.dispatchEvent({ type: "connected", data: inputSource }); + return this; + } + disconnect(inputSource) { + this.dispatchEvent({ type: "disconnected", data: inputSource }); + if (this._targetRay !== null) { + this._targetRay.visible = false; + } + if (this._grip !== null) { + this._grip.visible = false; + } + if (this._hand !== null) { + this._hand.visible = false; + } + return this; + } + update(inputSource, frame, referenceSpace) { + let inputPose = null; + let gripPose = null; + let handPose = null; + const targetRay = this._targetRay; + const grip = this._grip; + const hand = this._hand; + if (inputSource && frame.session.visibilityState !== "visible-blurred") { + if (hand && inputSource.hand) { + handPose = true; + for (const inputjoint of inputSource.hand.values()) { + const jointPose = frame.getJointPose(inputjoint, referenceSpace); + const joint = this._getHandJoint(hand, inputjoint); + if (jointPose !== null) { + joint.matrix.fromArray(jointPose.transform.matrix); + joint.matrix.decompose(joint.position, joint.rotation, joint.scale); + joint.matrixWorldNeedsUpdate = true; + joint.jointRadius = jointPose.radius; + } + joint.visible = jointPose !== null; + } + const indexTip = hand.joints["index-finger-tip"]; + const thumbTip = hand.joints["thumb-tip"]; + const distance = indexTip.position.distanceTo(thumbTip.position); + const distanceToPinch = 0.02; + const threshold = 0.005; + if (hand.inputState.pinching && distance > distanceToPinch + threshold) { + hand.inputState.pinching = false; + this.dispatchEvent({ + type: "pinchend", + handedness: inputSource.handedness, + target: this + }); + } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) { + hand.inputState.pinching = true; + this.dispatchEvent({ + type: "pinchstart", + handedness: inputSource.handedness, + target: this + }); + } + } else { + if (grip !== null && inputSource.gripSpace) { + gripPose = frame.getPose(inputSource.gripSpace, referenceSpace); + if (gripPose !== null) { + grip.matrix.fromArray(gripPose.transform.matrix); + grip.matrix.decompose(grip.position, grip.rotation, grip.scale); + grip.matrixWorldNeedsUpdate = true; + if (gripPose.linearVelocity) { + grip.hasLinearVelocity = true; + grip.linearVelocity.copy(gripPose.linearVelocity); + } else { + grip.hasLinearVelocity = false; + } + if (gripPose.angularVelocity) { + grip.hasAngularVelocity = true; + grip.angularVelocity.copy(gripPose.angularVelocity); + } else { + grip.hasAngularVelocity = false; + } + } + } + } + if (targetRay !== null) { + inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); + if (inputPose === null && gripPose !== null) { + inputPose = gripPose; + } + if (inputPose !== null) { + targetRay.matrix.fromArray(inputPose.transform.matrix); + targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale); + targetRay.matrixWorldNeedsUpdate = true; + if (inputPose.linearVelocity) { + targetRay.hasLinearVelocity = true; + targetRay.linearVelocity.copy(inputPose.linearVelocity); + } else { + targetRay.hasLinearVelocity = false; + } + if (inputPose.angularVelocity) { + targetRay.hasAngularVelocity = true; + targetRay.angularVelocity.copy(inputPose.angularVelocity); + } else { + targetRay.hasAngularVelocity = false; + } + this.dispatchEvent(_moveEvent); + } + } + } + if (targetRay !== null) { + targetRay.visible = inputPose !== null; + } + if (grip !== null) { + grip.visible = gripPose !== null; + } + if (hand !== null) { + hand.visible = handPose !== null; + } + return this; + } + _getHandJoint(hand, inputjoint) { + if (hand.joints[inputjoint.jointName] === undefined) { + const joint = new Group; + joint.matrixAutoUpdate = false; + joint.visible = false; + hand.joints[inputjoint.jointName] = joint; + hand.add(joint); + } + return hand.joints[inputjoint.jointName]; + } +} + +class FogExp2 { + constructor(color, density = 0.00025) { + this.isFogExp2 = true; + this.name = ""; + this.color = new Color(color); + this.density = density; + } + clone() { + return new FogExp2(this.color, this.density); + } + toJSON() { + return { + type: "FogExp2", + name: this.name, + color: this.color.getHex(), + density: this.density + }; + } +} + +class Fog { + constructor(color, near = 1, far = 1000) { + this.isFog = true; + this.name = ""; + this.color = new Color(color); + this.near = near; + this.far = far; + } + clone() { + return new Fog(this.color, this.near, this.far); + } + toJSON() { + return { + type: "Fog", + name: this.name, + color: this.color.getHex(), + near: this.near, + far: this.far + }; + } +} + +class Scene extends Object3D { + constructor() { + super(); + this.isScene = true; + this.type = "Scene"; + this.background = null; + this.environment = null; + this.fog = null; + this.backgroundBlurriness = 0; + this.backgroundIntensity = 1; + this.backgroundRotation = new Euler; + this.environmentIntensity = 1; + this.environmentRotation = new Euler; + this.overrideMaterial = null; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.background !== null) + this.background = source.background.clone(); + if (source.environment !== null) + this.environment = source.environment.clone(); + if (source.fog !== null) + this.fog = source.fog.clone(); + this.backgroundBlurriness = source.backgroundBlurriness; + this.backgroundIntensity = source.backgroundIntensity; + this.backgroundRotation.copy(source.backgroundRotation); + this.environmentIntensity = source.environmentIntensity; + this.environmentRotation.copy(source.environmentRotation); + if (source.overrideMaterial !== null) + this.overrideMaterial = source.overrideMaterial.clone(); + this.matrixAutoUpdate = source.matrixAutoUpdate; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + if (this.fog !== null) + data2.object.fog = this.fog.toJSON(); + if (this.backgroundBlurriness > 0) + data2.object.backgroundBlurriness = this.backgroundBlurriness; + if (this.backgroundIntensity !== 1) + data2.object.backgroundIntensity = this.backgroundIntensity; + data2.object.backgroundRotation = this.backgroundRotation.toArray(); + if (this.environmentIntensity !== 1) + data2.object.environmentIntensity = this.environmentIntensity; + data2.object.environmentRotation = this.environmentRotation.toArray(); + return data2; + } +} + +class InterleavedBuffer { + constructor(array, stride) { + this.isInterleavedBuffer = true; + this.array = array; + this.stride = stride; + this.count = array !== undefined ? array.length / stride : 0; + this.usage = StaticDrawUsage; + this.updateRanges = []; + this.version = 0; + this.uuid = generateUUID(); + } + onUploadCallback() { + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setUsage(value2) { + this.usage = value2; + return this; + } + addUpdateRange(start, count) { + this.updateRanges.push({ start, count }); + } + clearUpdateRanges() { + this.updateRanges.length = 0; + } + copy(source) { + this.array = new source.array.constructor(source.array); + this.count = source.count; + this.stride = source.stride; + this.usage = source.usage; + return this; + } + copyAt(index1, attribute, index2) { + index1 *= this.stride; + index2 *= attribute.stride; + for (let i = 0, l = this.stride;i < l; i++) { + this.array[index1 + i] = attribute.array[index2 + i]; + } + return this; + } + set(value2, offset = 0) { + this.array.set(value2, offset); + return this; + } + clone(data2) { + if (data2.arrayBuffers === undefined) { + data2.arrayBuffers = {}; + } + if (this.array.buffer._uuid === undefined) { + this.array.buffer._uuid = generateUUID(); + } + if (data2.arrayBuffers[this.array.buffer._uuid] === undefined) { + data2.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer; + } + const array = new this.array.constructor(data2.arrayBuffers[this.array.buffer._uuid]); + const ib = new this.constructor(array, this.stride); + ib.setUsage(this.usage); + return ib; + } + onUpload(callback) { + this.onUploadCallback = callback; + return this; + } + toJSON(data2) { + if (data2.arrayBuffers === undefined) { + data2.arrayBuffers = {}; + } + if (this.array.buffer._uuid === undefined) { + this.array.buffer._uuid = generateUUID(); + } + if (data2.arrayBuffers[this.array.buffer._uuid] === undefined) { + data2.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer)); + } + return { + uuid: this.uuid, + buffer: this.array.buffer._uuid, + type: this.array.constructor.name, + stride: this.stride + }; + } +} +var _vector$7 = /* @__PURE__ */ new Vector3; + +class InterleavedBufferAttribute { + constructor(interleavedBuffer, itemSize, offset, normalized = false) { + this.isInterleavedBufferAttribute = true; + this.name = ""; + this.data = interleavedBuffer; + this.itemSize = itemSize; + this.offset = offset; + this.normalized = normalized; + } + get count() { + return this.data.count; + } + get array() { + return this.data.array; + } + set needsUpdate(value2) { + this.data.needsUpdate = value2; + } + applyMatrix4(m) { + for (let i = 0, l = this.data.count;i < l; i++) { + _vector$7.fromBufferAttribute(this, i); + _vector$7.applyMatrix4(m); + this.setXYZ(i, _vector$7.x, _vector$7.y, _vector$7.z); + } + return this; + } + applyNormalMatrix(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$7.fromBufferAttribute(this, i); + _vector$7.applyNormalMatrix(m); + this.setXYZ(i, _vector$7.x, _vector$7.y, _vector$7.z); + } + return this; + } + transformDirection(m) { + for (let i = 0, l = this.count;i < l; i++) { + _vector$7.fromBufferAttribute(this, i); + _vector$7.transformDirection(m); + this.setXYZ(i, _vector$7.x, _vector$7.y, _vector$7.z); + } + return this; + } + getComponent(index2, component) { + let value2 = this.array[index2 * this.data.stride + this.offset + component]; + if (this.normalized) + value2 = denormalize(value2, this.array); + return value2; + } + setComponent(index2, component, value2) { + if (this.normalized) + value2 = normalize2(value2, this.array); + this.data.array[index2 * this.data.stride + this.offset + component] = value2; + return this; + } + setX(index2, x) { + if (this.normalized) + x = normalize2(x, this.array); + this.data.array[index2 * this.data.stride + this.offset] = x; + return this; + } + setY(index2, y) { + if (this.normalized) + y = normalize2(y, this.array); + this.data.array[index2 * this.data.stride + this.offset + 1] = y; + return this; + } + setZ(index2, z) { + if (this.normalized) + z = normalize2(z, this.array); + this.data.array[index2 * this.data.stride + this.offset + 2] = z; + return this; + } + setW(index2, w) { + if (this.normalized) + w = normalize2(w, this.array); + this.data.array[index2 * this.data.stride + this.offset + 3] = w; + return this; + } + getX(index2) { + let x = this.data.array[index2 * this.data.stride + this.offset]; + if (this.normalized) + x = denormalize(x, this.array); + return x; + } + getY(index2) { + let y = this.data.array[index2 * this.data.stride + this.offset + 1]; + if (this.normalized) + y = denormalize(y, this.array); + return y; + } + getZ(index2) { + let z = this.data.array[index2 * this.data.stride + this.offset + 2]; + if (this.normalized) + z = denormalize(z, this.array); + return z; + } + getW(index2) { + let w = this.data.array[index2 * this.data.stride + this.offset + 3]; + if (this.normalized) + w = denormalize(w, this.array); + return w; + } + setXY(index2, x, y) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + } + this.data.array[index2 + 0] = x; + this.data.array[index2 + 1] = y; + return this; + } + setXYZ(index2, x, y, z) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + } + this.data.array[index2 + 0] = x; + this.data.array[index2 + 1] = y; + this.data.array[index2 + 2] = z; + return this; + } + setXYZW(index2, x, y, z, w) { + index2 = index2 * this.data.stride + this.offset; + if (this.normalized) { + x = normalize2(x, this.array); + y = normalize2(y, this.array); + z = normalize2(z, this.array); + w = normalize2(w, this.array); + } + this.data.array[index2 + 0] = x; + this.data.array[index2 + 1] = y; + this.data.array[index2 + 2] = z; + this.data.array[index2 + 3] = w; + return this; + } + clone(data2) { + if (data2 === undefined) { + console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0;i < this.count; i++) { + const index2 = i * this.data.stride + this.offset; + for (let j = 0;j < this.itemSize; j++) { + array.push(this.data.array[index2 + j]); + } + } + return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized); + } else { + if (data2.interleavedBuffers === undefined) { + data2.interleavedBuffers = {}; + } + if (data2.interleavedBuffers[this.data.uuid] === undefined) { + data2.interleavedBuffers[this.data.uuid] = this.data.clone(data2); + } + return new InterleavedBufferAttribute(data2.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized); + } + } + toJSON(data2) { + if (data2 === undefined) { + console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data."); + const array = []; + for (let i = 0;i < this.count; i++) { + const index2 = i * this.data.stride + this.offset; + for (let j = 0;j < this.itemSize; j++) { + array.push(this.data.array[index2 + j]); + } + } + return { + itemSize: this.itemSize, + type: this.array.constructor.name, + array, + normalized: this.normalized + }; + } else { + if (data2.interleavedBuffers === undefined) { + data2.interleavedBuffers = {}; + } + if (data2.interleavedBuffers[this.data.uuid] === undefined) { + data2.interleavedBuffers[this.data.uuid] = this.data.toJSON(data2); + } + return { + isInterleavedBufferAttribute: true, + itemSize: this.itemSize, + data: this.data.uuid, + offset: this.offset, + normalized: this.normalized + }; + } + } +} + +class SpriteMaterial extends Material { + constructor(parameters) { + super(); + this.isSpriteMaterial = true; + this.type = "SpriteMaterial"; + this.color = new Color(16777215); + this.map = null; + this.alphaMap = null; + this.rotation = 0; + this.sizeAttenuation = true; + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.rotation = source.rotation; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } +} +var _geometry; +var _intersectPoint = /* @__PURE__ */ new Vector3; +var _worldScale = /* @__PURE__ */ new Vector3; +var _mvPosition = /* @__PURE__ */ new Vector3; +var _alignedPosition = /* @__PURE__ */ new Vector2; +var _rotatedPosition = /* @__PURE__ */ new Vector2; +var _viewWorldMatrix = /* @__PURE__ */ new Matrix4; +var _vA = /* @__PURE__ */ new Vector3; +var _vB = /* @__PURE__ */ new Vector3; +var _vC = /* @__PURE__ */ new Vector3; +var _uvA = /* @__PURE__ */ new Vector2; +var _uvB = /* @__PURE__ */ new Vector2; +var _uvC = /* @__PURE__ */ new Vector2; + +class Sprite extends Object3D { + constructor(material = new SpriteMaterial) { + super(); + this.isSprite = true; + this.type = "Sprite"; + if (_geometry === undefined) { + _geometry = new BufferGeometry; + const float32Array = new Float32Array([ + -0.5, + -0.5, + 0, + 0, + 0, + 0.5, + -0.5, + 0, + 1, + 0, + 0.5, + 0.5, + 0, + 1, + 1, + -0.5, + 0.5, + 0, + 0, + 1 + ]); + const interleavedBuffer = new InterleavedBuffer(float32Array, 5); + _geometry.setIndex([0, 1, 2, 0, 2, 3]); + _geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false)); + _geometry.setAttribute("uv", new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false)); + } + this.geometry = _geometry; + this.material = material; + this.center = new Vector2(0.5, 0.5); + } + raycast(raycaster, intersects) { + if (raycaster.camera === null) { + console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'); + } + _worldScale.setFromMatrixScale(this.matrixWorld); + _viewWorldMatrix.copy(raycaster.camera.matrixWorld); + this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld); + _mvPosition.setFromMatrixPosition(this.modelViewMatrix); + if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) { + _worldScale.multiplyScalar(-_mvPosition.z); + } + const rotation2 = this.material.rotation; + let sin, cos; + if (rotation2 !== 0) { + cos = Math.cos(rotation2); + sin = Math.sin(rotation2); + } + const center = this.center; + transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos); + transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos); + transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos); + _uvA.set(0, 0); + _uvB.set(1, 0); + _uvC.set(1, 1); + let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint); + if (intersect === null) { + transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos); + _uvB.set(0, 1); + intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint); + if (intersect === null) { + return; + } + } + const distance = raycaster.ray.origin.distanceTo(_intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) + return; + intersects.push({ + distance, + point: _intersectPoint.clone(), + uv: Triangle.getInterpolation(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2), + face: null, + object: this + }); + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.center !== undefined) + this.center.copy(source.center); + this.material = source.material; + return this; + } +} +function transformVertex(vertexPosition, mvPosition, center, scale2, sin, cos) { + _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale2); + if (sin !== undefined) { + _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y; + _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y; + } else { + _rotatedPosition.copy(_alignedPosition); + } + vertexPosition.copy(mvPosition); + vertexPosition.x += _rotatedPosition.x; + vertexPosition.y += _rotatedPosition.y; + vertexPosition.applyMatrix4(_viewWorldMatrix); +} +var _v1$2 = /* @__PURE__ */ new Vector3; +var _v2$1 = /* @__PURE__ */ new Vector3; + +class LOD extends Object3D { + constructor() { + super(); + this._currentLevel = 0; + this.type = "LOD"; + Object.defineProperties(this, { + levels: { + enumerable: true, + value: [] + }, + isLOD: { + value: true + } + }); + this.autoUpdate = true; + } + copy(source) { + super.copy(source, false); + const levels = source.levels; + for (let i = 0, l = levels.length;i < l; i++) { + const level = levels[i]; + this.addLevel(level.object.clone(), level.distance, level.hysteresis); + } + this.autoUpdate = source.autoUpdate; + return this; + } + addLevel(object, distance = 0, hysteresis = 0) { + distance = Math.abs(distance); + const levels = this.levels; + let l; + for (l = 0;l < levels.length; l++) { + if (distance < levels[l].distance) { + break; + } + } + levels.splice(l, 0, { distance, hysteresis, object }); + this.add(object); + return this; + } + removeLevel(distance) { + const levels = this.levels; + for (let i = 0;i < levels.length; i++) { + if (levels[i].distance === distance) { + const removedElements = levels.splice(i, 1); + this.remove(removedElements[0].object); + return true; + } + } + return false; + } + getCurrentLevel() { + return this._currentLevel; + } + getObjectForDistance(distance) { + const levels = this.levels; + if (levels.length > 0) { + let i, l; + for (i = 1, l = levels.length;i < l; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance < levelDistance) { + break; + } + } + return levels[i - 1].object; + } + return null; + } + raycast(raycaster, intersects) { + const levels = this.levels; + if (levels.length > 0) { + _v1$2.setFromMatrixPosition(this.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_v1$2); + this.getObjectForDistance(distance).raycast(raycaster, intersects); + } + } + update(camera) { + const levels = this.levels; + if (levels.length > 1) { + _v1$2.setFromMatrixPosition(camera.matrixWorld); + _v2$1.setFromMatrixPosition(this.matrixWorld); + const distance = _v1$2.distanceTo(_v2$1) / camera.zoom; + levels[0].object.visible = true; + let i, l; + for (i = 1, l = levels.length;i < l; i++) { + let levelDistance = levels[i].distance; + if (levels[i].object.visible) { + levelDistance -= levelDistance * levels[i].hysteresis; + } + if (distance >= levelDistance) { + levels[i - 1].object.visible = false; + levels[i].object.visible = true; + } else { + break; + } + } + this._currentLevel = i - 1; + for (;i < l; i++) { + levels[i].object.visible = false; + } + } + } + toJSON(meta) { + const data2 = super.toJSON(meta); + if (this.autoUpdate === false) + data2.object.autoUpdate = false; + data2.object.levels = []; + const levels = this.levels; + for (let i = 0, l = levels.length;i < l; i++) { + const level = levels[i]; + data2.object.levels.push({ + object: level.object.uuid, + distance: level.distance, + hysteresis: level.hysteresis + }); + } + return data2; + } +} +var _basePosition = /* @__PURE__ */ new Vector3; +var _skinIndex = /* @__PURE__ */ new Vector4; +var _skinWeight = /* @__PURE__ */ new Vector4; +var _vector3 = /* @__PURE__ */ new Vector3; +var _matrix4 = /* @__PURE__ */ new Matrix4; +var _vertex = /* @__PURE__ */ new Vector3; +var _sphere$5 = /* @__PURE__ */ new Sphere; +var _inverseMatrix$2 = /* @__PURE__ */ new Matrix4; +var _ray$2 = /* @__PURE__ */ new Ray; + +class SkinnedMesh extends Mesh { + constructor(geometry, material) { + super(geometry, material); + this.isSkinnedMesh = true; + this.type = "SkinnedMesh"; + this.bindMode = AttachedBindMode; + this.bindMatrix = new Matrix4; + this.bindMatrixInverse = new Matrix4; + this.boundingBox = null; + this.boundingSphere = null; + } + computeBoundingBox() { + const geometry = this.geometry; + if (this.boundingBox === null) { + this.boundingBox = new Box3; + } + this.boundingBox.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0;i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex); + this.boundingBox.expandByPoint(_vertex); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere; + } + this.boundingSphere.makeEmpty(); + const positionAttribute = geometry.getAttribute("position"); + for (let i = 0;i < positionAttribute.count; i++) { + this.getVertexPosition(i, _vertex); + this.boundingSphere.expandByPoint(_vertex); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.bindMode = source.bindMode; + this.bindMatrix.copy(source.bindMatrix); + this.bindMatrixInverse.copy(source.bindMatrixInverse); + this.skeleton = source.skeleton; + if (source.boundingBox !== null) + this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) + this.boundingSphere = source.boundingSphere.clone(); + return this; + } + raycast(raycaster, intersects) { + const material = this.material; + const matrixWorld = this.matrixWorld; + if (material === undefined) + return; + if (this.boundingSphere === null) + this.computeBoundingSphere(); + _sphere$5.copy(this.boundingSphere); + _sphere$5.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$5) === false) + return; + _inverseMatrix$2.copy(matrixWorld).invert(); + _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); + if (this.boundingBox !== null) { + if (_ray$2.intersectsBox(this.boundingBox) === false) + return; + } + this._computeIntersections(raycaster, intersects, _ray$2); + } + getVertexPosition(index2, target) { + super.getVertexPosition(index2, target); + this.applyBoneTransform(index2, target); + return target; + } + bind(skeleton, bindMatrix) { + this.skeleton = skeleton; + if (bindMatrix === undefined) { + this.updateMatrixWorld(true); + this.skeleton.calculateInverses(); + bindMatrix = this.matrixWorld; + } + this.bindMatrix.copy(bindMatrix); + this.bindMatrixInverse.copy(bindMatrix).invert(); + } + pose() { + this.skeleton.pose(); + } + normalizeSkinWeights() { + const vector = new Vector4; + const skinWeight = this.geometry.attributes.skinWeight; + for (let i = 0, l = skinWeight.count;i < l; i++) { + vector.fromBufferAttribute(skinWeight, i); + const scale2 = 1 / vector.manhattanLength(); + if (scale2 !== Infinity) { + vector.multiplyScalar(scale2); + } else { + vector.set(1, 0, 0, 0); + } + skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w); + } + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.bindMode === AttachedBindMode) { + this.bindMatrixInverse.copy(this.matrixWorld).invert(); + } else if (this.bindMode === DetachedBindMode) { + this.bindMatrixInverse.copy(this.bindMatrix).invert(); + } else { + console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode); + } + } + applyBoneTransform(index2, vector) { + const skeleton = this.skeleton; + const geometry = this.geometry; + _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index2); + _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index2); + _basePosition.copy(vector).applyMatrix4(this.bindMatrix); + vector.set(0, 0, 0); + for (let i = 0;i < 4; i++) { + const weight = _skinWeight.getComponent(i); + if (weight !== 0) { + const boneIndex = _skinIndex.getComponent(i); + _matrix4.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]); + vector.addScaledVector(_vector3.copy(_basePosition).applyMatrix4(_matrix4), weight); + } + } + return vector.applyMatrix4(this.bindMatrixInverse); + } +} + +class Bone extends Object3D { + constructor() { + super(); + this.isBone = true; + this.type = "Bone"; + } +} + +class DataTexture extends Texture { + constructor(data2 = null, width2 = 1, height2 = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isDataTexture = true; + this.image = { data: data2, width: width2, height: height2 }; + this.generateMipmaps = false; + this.flipY = false; + this.unpackAlignment = 1; + } +} +var _offsetMatrix = /* @__PURE__ */ new Matrix4; +var _identityMatrix = /* @__PURE__ */ new Matrix4; + +class Skeleton { + constructor(bones = [], boneInverses = []) { + this.uuid = generateUUID(); + this.bones = bones.slice(0); + this.boneInverses = boneInverses; + this.boneMatrices = null; + this.boneTexture = null; + this.init(); + } + init() { + const bones = this.bones; + const boneInverses = this.boneInverses; + this.boneMatrices = new Float32Array(bones.length * 16); + if (boneInverses.length === 0) { + this.calculateInverses(); + } else { + if (bones.length !== boneInverses.length) { + console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."); + this.boneInverses = []; + for (let i = 0, il = this.bones.length;i < il; i++) { + this.boneInverses.push(new Matrix4); + } + } + } + } + calculateInverses() { + this.boneInverses.length = 0; + for (let i = 0, il = this.bones.length;i < il; i++) { + const inverse = new Matrix4; + if (this.bones[i]) { + inverse.copy(this.bones[i].matrixWorld).invert(); + } + this.boneInverses.push(inverse); + } + } + pose() { + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone) { + bone.matrixWorld.copy(this.boneInverses[i]).invert(); + } + } + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone) { + if (bone.parent && bone.parent.isBone) { + bone.matrix.copy(bone.parent.matrixWorld).invert(); + bone.matrix.multiply(bone.matrixWorld); + } else { + bone.matrix.copy(bone.matrixWorld); + } + bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); + } + } + } + update() { + const bones = this.bones; + const boneInverses = this.boneInverses; + const boneMatrices = this.boneMatrices; + const boneTexture = this.boneTexture; + for (let i = 0, il = bones.length;i < il; i++) { + const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix; + _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]); + _offsetMatrix.toArray(boneMatrices, i * 16); + } + if (boneTexture !== null) { + boneTexture.needsUpdate = true; + } + } + clone() { + return new Skeleton(this.bones, this.boneInverses); + } + computeBoneTexture() { + let size = Math.sqrt(this.bones.length * 4); + size = Math.ceil(size / 4) * 4; + size = Math.max(size, 4); + const boneMatrices = new Float32Array(size * size * 4); + boneMatrices.set(this.boneMatrices); + const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType); + boneTexture.needsUpdate = true; + this.boneMatrices = boneMatrices; + this.boneTexture = boneTexture; + return this; + } + getBoneByName(name2) { + for (let i = 0, il = this.bones.length;i < il; i++) { + const bone = this.bones[i]; + if (bone.name === name2) { + return bone; + } + } + return; + } + dispose() { + if (this.boneTexture !== null) { + this.boneTexture.dispose(); + this.boneTexture = null; + } + } + fromJSON(json, bones) { + this.uuid = json.uuid; + for (let i = 0, l = json.bones.length;i < l; i++) { + const uuid = json.bones[i]; + let bone = bones[uuid]; + if (bone === undefined) { + console.warn("THREE.Skeleton: No bone found with UUID:", uuid); + bone = new Bone; + } + this.bones.push(bone); + this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i])); + } + this.init(); + return this; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "Skeleton", + generator: "Skeleton.toJSON" + }, + bones: [], + boneInverses: [] + }; + data2.uuid = this.uuid; + const bones = this.bones; + const boneInverses = this.boneInverses; + for (let i = 0, l = bones.length;i < l; i++) { + const bone = bones[i]; + data2.bones.push(bone.uuid); + const boneInverse = boneInverses[i]; + data2.boneInverses.push(boneInverse.toArray()); + } + return data2; + } +} + +class InstancedBufferAttribute extends BufferAttribute { + constructor(array, itemSize, normalized, meshPerAttribute = 1) { + super(array, itemSize, normalized); + this.isInstancedBufferAttribute = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.meshPerAttribute = this.meshPerAttribute; + data2.isInstancedBufferAttribute = true; + return data2; + } +} +var _instanceLocalMatrix = /* @__PURE__ */ new Matrix4; +var _instanceWorldMatrix = /* @__PURE__ */ new Matrix4; +var _instanceIntersects = []; +var _box3 = /* @__PURE__ */ new Box3; +var _identity = /* @__PURE__ */ new Matrix4; +var _mesh$1 = /* @__PURE__ */ new Mesh; +var _sphere$4 = /* @__PURE__ */ new Sphere; + +class InstancedMesh extends Mesh { + constructor(geometry, material, count) { + super(geometry, material); + this.isInstancedMesh = true; + this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16); + this.instanceColor = null; + this.morphTexture = null; + this.count = count; + this.boundingBox = null; + this.boundingSphere = null; + for (let i = 0;i < count; i++) { + this.setMatrixAt(i, _identity); + } + } + computeBoundingBox() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingBox === null) { + this.boundingBox = new Box3; + } + if (geometry.boundingBox === null) { + geometry.computeBoundingBox(); + } + this.boundingBox.makeEmpty(); + for (let i = 0;i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix); + _box3.copy(geometry.boundingBox).applyMatrix4(_instanceLocalMatrix); + this.boundingBox.union(_box3); + } + } + computeBoundingSphere() { + const geometry = this.geometry; + const count = this.count; + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere; + } + if (geometry.boundingSphere === null) { + geometry.computeBoundingSphere(); + } + this.boundingSphere.makeEmpty(); + for (let i = 0;i < count; i++) { + this.getMatrixAt(i, _instanceLocalMatrix); + _sphere$4.copy(geometry.boundingSphere).applyMatrix4(_instanceLocalMatrix); + this.boundingSphere.union(_sphere$4); + } + } + copy(source, recursive) { + super.copy(source, recursive); + this.instanceMatrix.copy(source.instanceMatrix); + if (source.morphTexture !== null) + this.morphTexture = source.morphTexture.clone(); + if (source.instanceColor !== null) + this.instanceColor = source.instanceColor.clone(); + this.count = source.count; + if (source.boundingBox !== null) + this.boundingBox = source.boundingBox.clone(); + if (source.boundingSphere !== null) + this.boundingSphere = source.boundingSphere.clone(); + return this; + } + getColorAt(index2, color) { + color.fromArray(this.instanceColor.array, index2 * 3); + } + getMatrixAt(index2, matrix) { + matrix.fromArray(this.instanceMatrix.array, index2 * 16); + } + getMorphAt(index2, object) { + const objectInfluences = object.morphTargetInfluences; + const array = this.morphTexture.source.data.data; + const len = objectInfluences.length + 1; + const dataIndex = index2 * len + 1; + for (let i = 0;i < objectInfluences.length; i++) { + objectInfluences[i] = array[dataIndex + i]; + } + } + raycast(raycaster, intersects) { + const matrixWorld = this.matrixWorld; + const raycastTimes = this.count; + _mesh$1.geometry = this.geometry; + _mesh$1.material = this.material; + if (_mesh$1.material === undefined) + return; + if (this.boundingSphere === null) + this.computeBoundingSphere(); + _sphere$4.copy(this.boundingSphere); + _sphere$4.applyMatrix4(matrixWorld); + if (raycaster.ray.intersectsSphere(_sphere$4) === false) + return; + for (let instanceId = 0;instanceId < raycastTimes; instanceId++) { + this.getMatrixAt(instanceId, _instanceLocalMatrix); + _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); + _mesh$1.matrixWorld = _instanceWorldMatrix; + _mesh$1.raycast(raycaster, _instanceIntersects); + for (let i = 0, l = _instanceIntersects.length;i < l; i++) { + const intersect = _instanceIntersects[i]; + intersect.instanceId = instanceId; + intersect.object = this; + intersects.push(intersect); + } + _instanceIntersects.length = 0; + } + } + setColorAt(index2, color) { + if (this.instanceColor === null) { + this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3); + } + color.toArray(this.instanceColor.array, index2 * 3); + } + setMatrixAt(index2, matrix) { + matrix.toArray(this.instanceMatrix.array, index2 * 16); + } + setMorphAt(index2, object) { + const objectInfluences = object.morphTargetInfluences; + const len = objectInfluences.length + 1; + if (this.morphTexture === null) { + this.morphTexture = new DataTexture(new Float32Array(len * this.count), len, this.count, RedFormat, FloatType); + } + const array = this.morphTexture.source.data.data; + let morphInfluencesSum = 0; + for (let i = 0;i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + const dataIndex = len * index2; + array[dataIndex] = morphBaseInfluence; + array.set(objectInfluences, dataIndex + 1); + } + updateMorphTargets() { + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + if (this.morphTexture !== null) { + this.morphTexture.dispose(); + this.morphTexture = null; + } + return this; + } +} +var _vector1 = /* @__PURE__ */ new Vector3; +var _vector2 = /* @__PURE__ */ new Vector3; +var _normalMatrix = /* @__PURE__ */ new Matrix3; + +class Plane { + constructor(normal = new Vector3(1, 0, 0), constant = 0) { + this.isPlane = true; + this.normal = normal; + this.constant = constant; + } + set(normal, constant) { + this.normal.copy(normal); + this.constant = constant; + return this; + } + setComponents(x, y, z, w) { + this.normal.set(x, y, z); + this.constant = w; + return this; + } + setFromNormalAndCoplanarPoint(normal, point) { + this.normal.copy(normal); + this.constant = -point.dot(this.normal); + return this; + } + setFromCoplanarPoints(a, b, c) { + const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); + this.setFromNormalAndCoplanarPoint(normal, a); + return this; + } + copy(plane) { + this.normal.copy(plane.normal); + this.constant = plane.constant; + return this; + } + normalize() { + const inverseNormalLength = 1 / this.normal.length(); + this.normal.multiplyScalar(inverseNormalLength); + this.constant *= inverseNormalLength; + return this; + } + negate() { + this.constant *= -1; + this.normal.negate(); + return this; + } + distanceToPoint(point) { + return this.normal.dot(point) + this.constant; + } + distanceToSphere(sphere) { + return this.distanceToPoint(sphere.center) - sphere.radius; + } + projectPoint(point, target) { + return target.copy(point).addScaledVector(this.normal, -this.distanceToPoint(point)); + } + intersectLine(line, target) { + const direction = line.delta(_vector1); + const denominator = this.normal.dot(direction); + if (denominator === 0) { + if (this.distanceToPoint(line.start) === 0) { + return target.copy(line.start); + } + return null; + } + const t = -(line.start.dot(this.normal) + this.constant) / denominator; + if (t < 0 || t > 1) { + return null; + } + return target.copy(line.start).addScaledVector(direction, t); + } + intersectsLine(line) { + const startSign = this.distanceToPoint(line.start); + const endSign = this.distanceToPoint(line.end); + return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0; + } + intersectsBox(box) { + return box.intersectsPlane(this); + } + intersectsSphere(sphere) { + return sphere.intersectsPlane(this); + } + coplanarPoint(target) { + return target.copy(this.normal).multiplyScalar(-this.constant); + } + applyMatrix4(matrix, optionalNormalMatrix) { + const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix); + const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix); + const normal = this.normal.applyMatrix3(normalMatrix).normalize(); + this.constant = -referencePoint.dot(normal); + return this; + } + translate(offset) { + this.constant -= offset.dot(this.normal); + return this; + } + equals(plane) { + return plane.normal.equals(this.normal) && plane.constant === this.constant; + } + clone() { + return new this.constructor().copy(this); + } +} +var _sphere$3 = /* @__PURE__ */ new Sphere; +var _vector$6 = /* @__PURE__ */ new Vector3; + +class Frustum { + constructor(p0 = new Plane, p1 = new Plane, p2 = new Plane, p3 = new Plane, p4 = new Plane, p5 = new Plane) { + this.planes = [p0, p1, p2, p3, p4, p5]; + } + set(p0, p1, p2, p3, p4, p5) { + const planes = this.planes; + planes[0].copy(p0); + planes[1].copy(p1); + planes[2].copy(p2); + planes[3].copy(p3); + planes[4].copy(p4); + planes[5].copy(p5); + return this; + } + copy(frustum) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + planes[i].copy(frustum.planes[i]); + } + return this; + } + setFromProjectionMatrix(m, coordinateSystem = WebGLCoordinateSystem) { + const planes = this.planes; + const me = m.elements; + const me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3]; + const me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7]; + const me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11]; + const me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15]; + planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize(); + planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize(); + planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize(); + planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize(); + planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); + if (coordinateSystem === WebGLCoordinateSystem) { + planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize(); + } else if (coordinateSystem === WebGPUCoordinateSystem) { + planes[5].setComponents(me2, me6, me10, me14).normalize(); + } else { + throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + coordinateSystem); + } + return this; + } + intersectsObject(object) { + if (object.boundingSphere !== undefined) { + if (object.boundingSphere === null) + object.computeBoundingSphere(); + _sphere$3.copy(object.boundingSphere).applyMatrix4(object.matrixWorld); + } else { + const geometry = object.geometry; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$3.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld); + } + return this.intersectsSphere(_sphere$3); + } + intersectsSprite(sprite) { + _sphere$3.center.set(0, 0, 0); + _sphere$3.radius = 0.7071067811865476; + _sphere$3.applyMatrix4(sprite.matrixWorld); + return this.intersectsSphere(_sphere$3); + } + intersectsSphere(sphere) { + const planes = this.planes; + const center = sphere.center; + const negRadius = -sphere.radius; + for (let i = 0;i < 6; i++) { + const distance = planes[i].distanceToPoint(center); + if (distance < negRadius) { + return false; + } + } + return true; + } + intersectsBox(box) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + const plane = planes[i]; + _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x; + _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y; + _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z; + if (plane.distanceToPoint(_vector$6) < 0) { + return false; + } + } + return true; + } + containsPoint(point) { + const planes = this.planes; + for (let i = 0;i < 6; i++) { + if (planes[i].distanceToPoint(point) < 0) { + return false; + } + } + return true; + } + clone() { + return new this.constructor().copy(this); + } +} +function ascIdSort(a, b) { + return a - b; +} +function sortOpaque(a, b) { + return a.z - b.z; +} +function sortTransparent(a, b) { + return b.z - a.z; +} + +class MultiDrawRenderList { + constructor() { + this.index = 0; + this.pool = []; + this.list = []; + } + push(start, count, z, index2) { + const pool = this.pool; + const list = this.list; + if (this.index >= pool.length) { + pool.push({ + start: -1, + count: -1, + z: -1, + index: -1 + }); + } + const item = pool[this.index]; + list.push(item); + this.index++; + item.start = start; + item.count = count; + item.z = z; + item.index = index2; + } + reset() { + this.list.length = 0; + this.index = 0; + } +} +var _matrix$1 = /* @__PURE__ */ new Matrix4; +var _whiteColor = /* @__PURE__ */ new Color(1, 1, 1); +var _frustum = /* @__PURE__ */ new Frustum; +var _box$1 = /* @__PURE__ */ new Box3; +var _sphere$2 = /* @__PURE__ */ new Sphere; +var _vector$5 = /* @__PURE__ */ new Vector3; +var _forward = /* @__PURE__ */ new Vector3; +var _temp = /* @__PURE__ */ new Vector3; +var _renderList = /* @__PURE__ */ new MultiDrawRenderList; +var _mesh = /* @__PURE__ */ new Mesh; +var _batchIntersects = []; +function copyAttributeData(src, target, targetOffset = 0) { + const itemSize = target.itemSize; + if (src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor) { + const vertexCount = src.count; + for (let i = 0;i < vertexCount; i++) { + for (let c = 0;c < itemSize; c++) { + target.setComponent(i + targetOffset, c, src.getComponent(i, c)); + } + } + } else { + target.array.set(src.array, targetOffset * itemSize); + } + target.needsUpdate = true; +} +function copyArrayContents(src, target) { + if (src.constructor !== target.constructor) { + const len = Math.min(src.length, target.length); + for (let i = 0;i < len; i++) { + target[i] = src[i]; + } + } else { + const len = Math.min(src.length, target.length); + target.set(new src.constructor(src.buffer, 0, len)); + } +} + +class BatchedMesh extends Mesh { + get maxInstanceCount() { + return this._maxInstanceCount; + } + get instanceCount() { + return this._instanceInfo.length - this._availableInstanceIds.length; + } + get unusedVertexCount() { + return this._maxVertexCount - this._nextVertexStart; + } + get unusedIndexCount() { + return this._maxIndexCount - this._nextIndexStart; + } + constructor(maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material) { + super(new BufferGeometry, material); + this.isBatchedMesh = true; + this.perObjectFrustumCulled = true; + this.sortObjects = true; + this.boundingBox = null; + this.boundingSphere = null; + this.customSort = null; + this._instanceInfo = []; + this._geometryInfo = []; + this._availableInstanceIds = []; + this._availableGeometryIds = []; + this._nextIndexStart = 0; + this._nextVertexStart = 0; + this._geometryCount = 0; + this._visibilityChanged = true; + this._geometryInitialized = false; + this._maxInstanceCount = maxInstanceCount; + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + this._multiDrawCounts = new Int32Array(maxInstanceCount); + this._multiDrawStarts = new Int32Array(maxInstanceCount); + this._multiDrawCount = 0; + this._multiDrawInstances = null; + this._matricesTexture = null; + this._indirectTexture = null; + this._colorsTexture = null; + this._initMatricesTexture(); + this._initIndirectTexture(); + } + _initMatricesTexture() { + let size = Math.sqrt(this._maxInstanceCount * 4); + size = Math.ceil(size / 4) * 4; + size = Math.max(size, 4); + const matricesArray = new Float32Array(size * size * 4); + const matricesTexture = new DataTexture(matricesArray, size, size, RGBAFormat, FloatType); + this._matricesTexture = matricesTexture; + } + _initIndirectTexture() { + let size = Math.sqrt(this._maxInstanceCount); + size = Math.ceil(size); + const indirectArray = new Uint32Array(size * size); + const indirectTexture = new DataTexture(indirectArray, size, size, RedIntegerFormat, UnsignedIntType); + this._indirectTexture = indirectTexture; + } + _initColorsTexture() { + let size = Math.sqrt(this._maxInstanceCount); + size = Math.ceil(size); + const colorsArray = new Float32Array(size * size * 4).fill(1); + const colorsTexture = new DataTexture(colorsArray, size, size, RGBAFormat, FloatType); + colorsTexture.colorSpace = ColorManagement.workingColorSpace; + this._colorsTexture = colorsTexture; + } + _initializeGeometry(reference) { + const geometry = this.geometry; + const maxVertexCount = this._maxVertexCount; + const maxIndexCount = this._maxIndexCount; + if (this._geometryInitialized === false) { + for (const attributeName in reference.attributes) { + const srcAttribute = reference.getAttribute(attributeName); + const { array, itemSize, normalized } = srcAttribute; + const dstArray = new array.constructor(maxVertexCount * itemSize); + const dstAttribute = new BufferAttribute(dstArray, itemSize, normalized); + geometry.setAttribute(attributeName, dstAttribute); + } + if (reference.getIndex() !== null) { + const indexArray = maxVertexCount > 65535 ? new Uint32Array(maxIndexCount) : new Uint16Array(maxIndexCount); + geometry.setIndex(new BufferAttribute(indexArray, 1)); + } + this._geometryInitialized = true; + } + } + _validateGeometry(geometry) { + const batchGeometry = this.geometry; + if (Boolean(geometry.getIndex()) !== Boolean(batchGeometry.getIndex())) { + throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".'); + } + for (const attributeName in batchGeometry.attributes) { + if (!geometry.hasAttribute(attributeName)) { + throw new Error(`THREE.BatchedMesh: Added geometry missing "${attributeName}". All geometries must have consistent attributes.`); + } + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + if (srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized) { + throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value."); + } + } + } + validateInstanceId(instanceId) { + const instanceInfo = this._instanceInfo; + if (instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[instanceId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.`); + } + } + validateGeometryId(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + throw new Error(`THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.`); + } + } + setCustomSort(func) { + this.customSort = func; + return this; + } + computeBoundingBox() { + if (this.boundingBox === null) { + this.boundingBox = new Box3; + } + const boundingBox = this.boundingBox; + const instanceInfo = this._instanceInfo; + boundingBox.makeEmpty(); + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].active === false) + continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$1); + this.getBoundingBoxAt(geometryId, _box$1).applyMatrix4(_matrix$1); + boundingBox.union(_box$1); + } + } + computeBoundingSphere() { + if (this.boundingSphere === null) { + this.boundingSphere = new Sphere; + } + const boundingSphere = this.boundingSphere; + const instanceInfo = this._instanceInfo; + boundingSphere.makeEmpty(); + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].active === false) + continue; + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$1); + this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1); + boundingSphere.union(_sphere$2); + } + } + addInstance(geometryId) { + const atCapacity = this._instanceInfo.length >= this.maxInstanceCount; + if (atCapacity && this._availableInstanceIds.length === 0) { + throw new Error("THREE.BatchedMesh: Maximum item count reached."); + } + const instanceInfo = { + visible: true, + active: true, + geometryIndex: geometryId + }; + let drawId = null; + if (this._availableInstanceIds.length > 0) { + this._availableInstanceIds.sort(ascIdSort); + drawId = this._availableInstanceIds.shift(); + this._instanceInfo[drawId] = instanceInfo; + } else { + drawId = this._instanceInfo.length; + this._instanceInfo.push(instanceInfo); + } + const matricesTexture = this._matricesTexture; + _matrix$1.identity().toArray(matricesTexture.image.data, drawId * 16); + matricesTexture.needsUpdate = true; + const colorsTexture = this._colorsTexture; + if (colorsTexture) { + _whiteColor.toArray(colorsTexture.image.data, drawId * 4); + colorsTexture.needsUpdate = true; + } + this._visibilityChanged = true; + return drawId; + } + addGeometry(geometry, reservedVertexCount = -1, reservedIndexCount = -1) { + this._initializeGeometry(geometry); + this._validateGeometry(geometry); + const geometryInfo = { + vertexStart: -1, + vertexCount: -1, + reservedVertexCount: -1, + indexStart: -1, + indexCount: -1, + reservedIndexCount: -1, + start: -1, + count: -1, + boundingBox: null, + boundingSphere: null, + active: true + }; + const geometryInfoList = this._geometryInfo; + geometryInfo.vertexStart = this._nextVertexStart; + geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute("position").count : reservedVertexCount; + const index2 = geometry.getIndex(); + const hasIndex = index2 !== null; + if (hasIndex) { + geometryInfo.indexStart = this._nextIndexStart; + geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index2.count : reservedIndexCount; + } + if (geometryInfo.indexStart !== -1 && geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount || geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size."); + } + let geometryId; + if (this._availableGeometryIds.length > 0) { + this._availableGeometryIds.sort(ascIdSort); + geometryId = this._availableGeometryIds.shift(); + geometryInfoList[geometryId] = geometryInfo; + } else { + geometryId = this._geometryCount; + this._geometryCount++; + geometryInfoList.push(geometryInfo); + } + this.setGeometryAt(geometryId, geometry); + this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + return geometryId; + } + setGeometryAt(geometryId, geometry) { + if (geometryId >= this._geometryCount) { + throw new Error("THREE.BatchedMesh: Maximum geometry count reached."); + } + this._validateGeometry(geometry); + const batchGeometry = this.geometry; + const hasIndex = batchGeometry.getIndex() !== null; + const dstIndex = batchGeometry.getIndex(); + const srcIndex = geometry.getIndex(); + const geometryInfo = this._geometryInfo[geometryId]; + if (hasIndex && srcIndex.count > geometryInfo.reservedIndexCount || geometry.attributes.position.count > geometryInfo.reservedVertexCount) { + throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry."); + } + const vertexStart = geometryInfo.vertexStart; + const reservedVertexCount = geometryInfo.reservedVertexCount; + geometryInfo.vertexCount = geometry.getAttribute("position").count; + for (const attributeName in batchGeometry.attributes) { + const srcAttribute = geometry.getAttribute(attributeName); + const dstAttribute = batchGeometry.getAttribute(attributeName); + copyAttributeData(srcAttribute, dstAttribute, vertexStart); + const itemSize = srcAttribute.itemSize; + for (let i = srcAttribute.count, l = reservedVertexCount;i < l; i++) { + const index2 = vertexStart + i; + for (let c = 0;c < itemSize; c++) { + dstAttribute.setComponent(index2, c, 0); + } + } + dstAttribute.needsUpdate = true; + dstAttribute.addUpdateRange(vertexStart * itemSize, reservedVertexCount * itemSize); + } + if (hasIndex) { + const indexStart = geometryInfo.indexStart; + const reservedIndexCount = geometryInfo.reservedIndexCount; + geometryInfo.indexCount = geometry.getIndex().count; + for (let i = 0;i < srcIndex.count; i++) { + dstIndex.setX(indexStart + i, vertexStart + srcIndex.getX(i)); + } + for (let i = srcIndex.count, l = reservedIndexCount;i < l; i++) { + dstIndex.setX(indexStart + i, vertexStart); + } + dstIndex.needsUpdate = true; + dstIndex.addUpdateRange(indexStart, geometryInfo.reservedIndexCount); + } + geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart; + geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount; + geometryInfo.boundingBox = null; + if (geometry.boundingBox !== null) { + geometryInfo.boundingBox = geometry.boundingBox.clone(); + } + geometryInfo.boundingSphere = null; + if (geometry.boundingSphere !== null) { + geometryInfo.boundingSphere = geometry.boundingSphere.clone(); + } + this._visibilityChanged = true; + return geometryId; + } + deleteGeometry(geometryId) { + const geometryInfoList = this._geometryInfo; + if (geometryId >= geometryInfoList.length || geometryInfoList[geometryId].active === false) { + return this; + } + const instanceInfo = this._instanceInfo; + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].active && instanceInfo[i].geometryIndex === geometryId) { + this.deleteInstance(i); + } + } + geometryInfoList[geometryId].active = false; + this._availableGeometryIds.push(geometryId); + this._visibilityChanged = true; + return this; + } + deleteInstance(instanceId) { + this.validateInstanceId(instanceId); + this._instanceInfo[instanceId].active = false; + this._availableInstanceIds.push(instanceId); + this._visibilityChanged = true; + return this; + } + optimize() { + let nextVertexStart = 0; + let nextIndexStart = 0; + const geometryInfoList = this._geometryInfo; + const indices = geometryInfoList.map((e, i) => i).sort((a, b) => { + return geometryInfoList[a].vertexStart - geometryInfoList[b].vertexStart; + }); + const geometry = this.geometry; + for (let i = 0, l = geometryInfoList.length;i < l; i++) { + const index2 = indices[i]; + const geometryInfo = geometryInfoList[index2]; + if (geometryInfo.active === false) { + continue; + } + if (geometry.index !== null) { + if (geometryInfo.indexStart !== nextIndexStart) { + const { indexStart, vertexStart, reservedIndexCount } = geometryInfo; + const index3 = geometry.index; + const array = index3.array; + const elementDelta = nextVertexStart - vertexStart; + for (let j = indexStart;j < indexStart + reservedIndexCount; j++) { + array[j] = array[j] + elementDelta; + } + index3.array.copyWithin(nextIndexStart, indexStart, indexStart + reservedIndexCount); + index3.addUpdateRange(nextIndexStart, reservedIndexCount); + geometryInfo.indexStart = nextIndexStart; + } + nextIndexStart += geometryInfo.reservedIndexCount; + } + if (geometryInfo.vertexStart !== nextVertexStart) { + const { vertexStart, reservedVertexCount } = geometryInfo; + const attributes = geometry.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + const { array, itemSize } = attribute; + array.copyWithin(nextVertexStart * itemSize, vertexStart * itemSize, (vertexStart + reservedVertexCount) * itemSize); + attribute.addUpdateRange(nextVertexStart * itemSize, reservedVertexCount * itemSize); + } + geometryInfo.vertexStart = nextVertexStart; + } + nextVertexStart += geometryInfo.reservedVertexCount; + geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart; + this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0; + this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount; + } + return this; + } + getBoundingBoxAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingBox === null) { + const box = new Box3; + const index2 = geometry.index; + const position2 = geometry.attributes.position; + for (let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count;i < l; i++) { + let iv = i; + if (index2) { + iv = index2.getX(iv); + } + box.expandByPoint(_vector$5.fromBufferAttribute(position2, iv)); + } + geometryInfo.boundingBox = box; + } + target.copy(geometryInfo.boundingBox); + return target; + } + getBoundingSphereAt(geometryId, target) { + if (geometryId >= this._geometryCount) { + return null; + } + const geometry = this.geometry; + const geometryInfo = this._geometryInfo[geometryId]; + if (geometryInfo.boundingSphere === null) { + const sphere = new Sphere; + this.getBoundingBoxAt(geometryId, _box$1); + _box$1.getCenter(sphere.center); + const index2 = geometry.index; + const position2 = geometry.attributes.position; + let maxRadiusSq = 0; + for (let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count;i < l; i++) { + let iv = i; + if (index2) { + iv = index2.getX(iv); + } + _vector$5.fromBufferAttribute(position2, iv); + maxRadiusSq = Math.max(maxRadiusSq, sphere.center.distanceToSquared(_vector$5)); + } + sphere.radius = Math.sqrt(maxRadiusSq); + geometryInfo.boundingSphere = sphere; + } + target.copy(geometryInfo.boundingSphere); + return target; + } + setMatrixAt(instanceId, matrix) { + this.validateInstanceId(instanceId); + const matricesTexture = this._matricesTexture; + const matricesArray = this._matricesTexture.image.data; + matrix.toArray(matricesArray, instanceId * 16); + matricesTexture.needsUpdate = true; + return this; + } + getMatrixAt(instanceId, matrix) { + this.validateInstanceId(instanceId); + return matrix.fromArray(this._matricesTexture.image.data, instanceId * 16); + } + setColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + if (this._colorsTexture === null) { + this._initColorsTexture(); + } + color.toArray(this._colorsTexture.image.data, instanceId * 4); + this._colorsTexture.needsUpdate = true; + return this; + } + getColorAt(instanceId, color) { + this.validateInstanceId(instanceId); + return color.fromArray(this._colorsTexture.image.data, instanceId * 4); + } + setVisibleAt(instanceId, value2) { + this.validateInstanceId(instanceId); + if (this._instanceInfo[instanceId].visible === value2) { + return this; + } + this._instanceInfo[instanceId].visible = value2; + this._visibilityChanged = true; + return this; + } + getVisibleAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].visible; + } + setGeometryIdAt(instanceId, geometryId) { + this.validateInstanceId(instanceId); + this.validateGeometryId(geometryId); + this._instanceInfo[instanceId].geometryIndex = geometryId; + return this; + } + getGeometryIdAt(instanceId) { + this.validateInstanceId(instanceId); + return this._instanceInfo[instanceId].geometryIndex; + } + getGeometryRangeAt(geometryId, target = {}) { + this.validateGeometryId(geometryId); + const geometryInfo = this._geometryInfo[geometryId]; + target.vertexStart = geometryInfo.vertexStart; + target.vertexCount = geometryInfo.vertexCount; + target.reservedVertexCount = geometryInfo.reservedVertexCount; + target.indexStart = geometryInfo.indexStart; + target.indexCount = geometryInfo.indexCount; + target.reservedIndexCount = geometryInfo.reservedIndexCount; + target.start = geometryInfo.start; + target.count = geometryInfo.count; + return target; + } + setInstanceCount(maxInstanceCount) { + const availableInstanceIds = this._availableInstanceIds; + const instanceInfo = this._instanceInfo; + availableInstanceIds.sort(ascIdSort); + while (availableInstanceIds[availableInstanceIds.length - 1] === instanceInfo.length) { + instanceInfo.pop(); + availableInstanceIds.pop(); + } + if (maxInstanceCount < instanceInfo.length) { + throw new Error(`BatchedMesh: Instance ids outside the range ${maxInstanceCount} are being used. Cannot shrink instance count.`); + } + const multiDrawCounts = new Int32Array(maxInstanceCount); + const multiDrawStarts = new Int32Array(maxInstanceCount); + copyArrayContents(this._multiDrawCounts, multiDrawCounts); + copyArrayContents(this._multiDrawStarts, multiDrawStarts); + this._multiDrawCounts = multiDrawCounts; + this._multiDrawStarts = multiDrawStarts; + this._maxInstanceCount = maxInstanceCount; + const indirectTexture = this._indirectTexture; + const matricesTexture = this._matricesTexture; + const colorsTexture = this._colorsTexture; + indirectTexture.dispose(); + this._initIndirectTexture(); + copyArrayContents(indirectTexture.image.data, this._indirectTexture.image.data); + matricesTexture.dispose(); + this._initMatricesTexture(); + copyArrayContents(matricesTexture.image.data, this._matricesTexture.image.data); + if (colorsTexture) { + colorsTexture.dispose(); + this._initColorsTexture(); + copyArrayContents(colorsTexture.image.data, this._colorsTexture.image.data); + } + } + setGeometrySize(maxVertexCount, maxIndexCount) { + const validRanges = [...this._geometryInfo].filter((info) => info.active); + const requiredVertexLength = Math.max(...validRanges.map((range) => range.vertexStart + range.reservedVertexCount)); + if (requiredVertexLength > maxVertexCount) { + throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + if (this.geometry.index) { + const requiredIndexLength = Math.max(...validRanges.map((range) => range.indexStart + range.reservedIndexCount)); + if (requiredIndexLength > maxIndexCount) { + throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${maxIndexCount}. Cannot shrink further.`); + } + } + const oldGeometry = this.geometry; + oldGeometry.dispose(); + this._maxVertexCount = maxVertexCount; + this._maxIndexCount = maxIndexCount; + if (this._geometryInitialized) { + this._geometryInitialized = false; + this.geometry = new BufferGeometry; + this._initializeGeometry(oldGeometry); + } + const geometry = this.geometry; + if (oldGeometry.index) { + copyArrayContents(oldGeometry.index.array, geometry.index.array); + } + for (const key2 in oldGeometry.attributes) { + copyArrayContents(oldGeometry.attributes[key2].array, geometry.attributes[key2].array); + } + } + raycast(raycaster, intersects) { + const instanceInfo = this._instanceInfo; + const geometryInfoList = this._geometryInfo; + const matrixWorld = this.matrixWorld; + const batchGeometry = this.geometry; + _mesh.material = this.material; + _mesh.geometry.index = batchGeometry.index; + _mesh.geometry.attributes = batchGeometry.attributes; + if (_mesh.geometry.boundingBox === null) { + _mesh.geometry.boundingBox = new Box3; + } + if (_mesh.geometry.boundingSphere === null) { + _mesh.geometry.boundingSphere = new Sphere; + } + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (!instanceInfo[i].visible || !instanceInfo[i].active) { + continue; + } + const geometryId = instanceInfo[i].geometryIndex; + const geometryInfo = geometryInfoList[geometryId]; + _mesh.geometry.setDrawRange(geometryInfo.start, geometryInfo.count); + this.getMatrixAt(i, _mesh.matrixWorld).premultiply(matrixWorld); + this.getBoundingBoxAt(geometryId, _mesh.geometry.boundingBox); + this.getBoundingSphereAt(geometryId, _mesh.geometry.boundingSphere); + _mesh.raycast(raycaster, _batchIntersects); + for (let j = 0, l2 = _batchIntersects.length;j < l2; j++) { + const intersect = _batchIntersects[j]; + intersect.object = this; + intersect.batchId = i; + intersects.push(intersect); + } + _batchIntersects.length = 0; + } + _mesh.material = null; + _mesh.geometry.index = null; + _mesh.geometry.attributes = {}; + _mesh.geometry.setDrawRange(0, Infinity); + } + copy(source) { + super.copy(source); + this.geometry = source.geometry.clone(); + this.perObjectFrustumCulled = source.perObjectFrustumCulled; + this.sortObjects = source.sortObjects; + this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null; + this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null; + this._geometryInfo = source._geometryInfo.map((info) => ({ + ...info, + boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null, + boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null + })); + this._instanceInfo = source._instanceInfo.map((info) => ({ ...info })); + this._maxInstanceCount = source._maxInstanceCount; + this._maxVertexCount = source._maxVertexCount; + this._maxIndexCount = source._maxIndexCount; + this._geometryInitialized = source._geometryInitialized; + this._geometryCount = source._geometryCount; + this._multiDrawCounts = source._multiDrawCounts.slice(); + this._multiDrawStarts = source._multiDrawStarts.slice(); + this._matricesTexture = source._matricesTexture.clone(); + this._matricesTexture.image.data = this._matricesTexture.image.data.slice(); + if (this._colorsTexture !== null) { + this._colorsTexture = source._colorsTexture.clone(); + this._colorsTexture.image.data = this._colorsTexture.image.data.slice(); + } + return this; + } + dispose() { + this.geometry.dispose(); + this._matricesTexture.dispose(); + this._matricesTexture = null; + this._indirectTexture.dispose(); + this._indirectTexture = null; + if (this._colorsTexture !== null) { + this._colorsTexture.dispose(); + this._colorsTexture = null; + } + return this; + } + onBeforeRender(renderer2, scene, camera, geometry, material) { + if (!this._visibilityChanged && !this.perObjectFrustumCulled && !this.sortObjects) { + return; + } + const index2 = geometry.getIndex(); + const bytesPerElement = index2 === null ? 1 : index2.array.BYTES_PER_ELEMENT; + const instanceInfo = this._instanceInfo; + const multiDrawStarts = this._multiDrawStarts; + const multiDrawCounts = this._multiDrawCounts; + const geometryInfoList = this._geometryInfo; + const perObjectFrustumCulled = this.perObjectFrustumCulled; + const indirectTexture = this._indirectTexture; + const indirectArray = indirectTexture.image.data; + if (perObjectFrustumCulled) { + _matrix$1.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).multiply(this.matrixWorld); + _frustum.setFromProjectionMatrix(_matrix$1, renderer2.coordinateSystem); + } + let multiDrawCount = 0; + if (this.sortObjects) { + _matrix$1.copy(this.matrixWorld).invert(); + _vector$5.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(_matrix$1); + _forward.set(0, 0, -1).transformDirection(camera.matrixWorld).transformDirection(_matrix$1); + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + this.getMatrixAt(i, _matrix$1); + this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1); + let culled = false; + if (perObjectFrustumCulled) { + culled = !_frustum.intersectsSphere(_sphere$2); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + const z = _temp.subVectors(_sphere$2.center, _vector$5).dot(_forward); + _renderList.push(geometryInfo.start, geometryInfo.count, z, i); + } + } + } + const list = _renderList.list; + const customSort = this.customSort; + if (customSort === null) { + list.sort(material.transparent ? sortTransparent : sortOpaque); + } else { + customSort.call(this, list, camera); + } + for (let i = 0, l = list.length;i < l; i++) { + const item = list[i]; + multiDrawStarts[multiDrawCount] = item.start * bytesPerElement; + multiDrawCounts[multiDrawCount] = item.count; + indirectArray[multiDrawCount] = item.index; + multiDrawCount++; + } + _renderList.reset(); + } else { + for (let i = 0, l = instanceInfo.length;i < l; i++) { + if (instanceInfo[i].visible && instanceInfo[i].active) { + const geometryId = instanceInfo[i].geometryIndex; + let culled = false; + if (perObjectFrustumCulled) { + this.getMatrixAt(i, _matrix$1); + this.getBoundingSphereAt(geometryId, _sphere$2).applyMatrix4(_matrix$1); + culled = !_frustum.intersectsSphere(_sphere$2); + } + if (!culled) { + const geometryInfo = geometryInfoList[geometryId]; + multiDrawStarts[multiDrawCount] = geometryInfo.start * bytesPerElement; + multiDrawCounts[multiDrawCount] = geometryInfo.count; + indirectArray[multiDrawCount] = i; + multiDrawCount++; + } + } + } + } + indirectTexture.needsUpdate = true; + this._multiDrawCount = multiDrawCount; + this._visibilityChanged = false; + } + onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial) { + this.onBeforeRender(renderer2, null, shadowCamera, geometry, depthMaterial); + } +} + +class LineBasicMaterial extends Material { + constructor(parameters) { + super(); + this.isLineBasicMaterial = true; + this.type = "LineBasicMaterial"; + this.color = new Color(16777215); + this.map = null; + this.linewidth = 1; + this.linecap = "round"; + this.linejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.linewidth = source.linewidth; + this.linecap = source.linecap; + this.linejoin = source.linejoin; + this.fog = source.fog; + return this; + } +} +var _vStart = /* @__PURE__ */ new Vector3; +var _vEnd = /* @__PURE__ */ new Vector3; +var _inverseMatrix$1 = /* @__PURE__ */ new Matrix4; +var _ray$1 = /* @__PURE__ */ new Ray; +var _sphere$1 = /* @__PURE__ */ new Sphere; +var _intersectPointOnRay = /* @__PURE__ */ new Vector3; +var _intersectPointOnSegment = /* @__PURE__ */ new Vector3; + +class Line extends Object3D { + constructor(geometry = new BufferGeometry, material = new LineBasicMaterial) { + super(); + this.isLine = true; + this.type = "Line"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = [0]; + for (let i = 1, l = positionAttribute.count;i < l; i++) { + _vStart.fromBufferAttribute(positionAttribute, i - 1); + _vEnd.fromBufferAttribute(positionAttribute, i); + lineDistances[i] = lineDistances[i - 1]; + lineDistances[i] += _vStart.distanceTo(_vEnd); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1)); + } else { + console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } + raycast(raycaster, intersects) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Line.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere$1.copy(geometry.boundingSphere); + _sphere$1.applyMatrix4(matrixWorld); + _sphere$1.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere$1) === false) + return; + _inverseMatrix$1.copy(matrixWorld).invert(); + _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const step = this.isLineSegments ? 2 : 1; + const index2 = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index2 !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, l = end - 1;i < l; i += step) { + const a = index2.getX(i); + const b = index2.getX(i + 1); + const intersect = checkIntersection(this, raycaster, _ray$1, localThresholdSq, a, b, i); + if (intersect) { + intersects.push(intersect); + } + } + if (this.isLineLoop) { + const a = index2.getX(end - 1); + const b = index2.getX(start); + const intersect = checkIntersection(this, raycaster, _ray$1, localThresholdSq, a, b, end - 1); + if (intersect) { + intersects.push(intersect); + } + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l = end - 1;i < l; i += step) { + const intersect = checkIntersection(this, raycaster, _ray$1, localThresholdSq, i, i + 1, i); + if (intersect) { + intersects.push(intersect); + } + } + if (this.isLineLoop) { + const intersect = checkIntersection(this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1); + if (intersect) { + intersects.push(intersect); + } + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } +} +function checkIntersection(object, raycaster, ray, thresholdSq, a, b, i) { + const positionAttribute = object.geometry.attributes.position; + _vStart.fromBufferAttribute(positionAttribute, a); + _vEnd.fromBufferAttribute(positionAttribute, b); + const distSq = ray.distanceSqToSegment(_vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment); + if (distSq > thresholdSq) + return; + _intersectPointOnRay.applyMatrix4(object.matrixWorld); + const distance = raycaster.ray.origin.distanceTo(_intersectPointOnRay); + if (distance < raycaster.near || distance > raycaster.far) + return; + return { + distance, + point: _intersectPointOnSegment.clone().applyMatrix4(object.matrixWorld), + index: i, + face: null, + faceIndex: null, + barycoord: null, + object + }; +} +var _start = /* @__PURE__ */ new Vector3; +var _end = /* @__PURE__ */ new Vector3; + +class LineSegments extends Line { + constructor(geometry, material) { + super(geometry, material); + this.isLineSegments = true; + this.type = "LineSegments"; + } + computeLineDistances() { + const geometry = this.geometry; + if (geometry.index === null) { + const positionAttribute = geometry.attributes.position; + const lineDistances = []; + for (let i = 0, l = positionAttribute.count;i < l; i += 2) { + _start.fromBufferAttribute(positionAttribute, i); + _end.fromBufferAttribute(positionAttribute, i + 1); + lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1]; + lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end); + } + geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1)); + } else { + console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); + } + return this; + } +} + +class LineLoop extends Line { + constructor(geometry, material) { + super(geometry, material); + this.isLineLoop = true; + this.type = "LineLoop"; + } +} + +class PointsMaterial extends Material { + constructor(parameters) { + super(); + this.isPointsMaterial = true; + this.type = "PointsMaterial"; + this.color = new Color(16777215); + this.map = null; + this.alphaMap = null; + this.size = 1; + this.sizeAttenuation = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.size = source.size; + this.sizeAttenuation = source.sizeAttenuation; + this.fog = source.fog; + return this; + } +} +var _inverseMatrix = /* @__PURE__ */ new Matrix4; +var _ray = /* @__PURE__ */ new Ray; +var _sphere = /* @__PURE__ */ new Sphere; +var _position$2 = /* @__PURE__ */ new Vector3; + +class Points extends Object3D { + constructor(geometry = new BufferGeometry, material = new PointsMaterial) { + super(); + this.isPoints = true; + this.type = "Points"; + this.geometry = geometry; + this.material = material; + this.updateMorphTargets(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.material = Array.isArray(source.material) ? source.material.slice() : source.material; + this.geometry = source.geometry; + return this; + } + raycast(raycaster, intersects) { + const geometry = this.geometry; + const matrixWorld = this.matrixWorld; + const threshold = raycaster.params.Points.threshold; + const drawRange = geometry.drawRange; + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _sphere.copy(geometry.boundingSphere); + _sphere.applyMatrix4(matrixWorld); + _sphere.radius += threshold; + if (raycaster.ray.intersectsSphere(_sphere) === false) + return; + _inverseMatrix.copy(matrixWorld).invert(); + _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); + const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); + const localThresholdSq = localThreshold * localThreshold; + const index2 = geometry.index; + const attributes = geometry.attributes; + const positionAttribute = attributes.position; + if (index2 !== null) { + const start = Math.max(0, drawRange.start); + const end = Math.min(index2.count, drawRange.start + drawRange.count); + for (let i = start, il = end;i < il; i++) { + const a = index2.getX(i); + _position$2.fromBufferAttribute(positionAttribute, a); + testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this); + } + } else { + const start = Math.max(0, drawRange.start); + const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); + for (let i = start, l = end;i < l; i++) { + _position$2.fromBufferAttribute(positionAttribute, i); + testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this); + } + } + } + updateMorphTargets() { + const geometry = this.geometry; + const morphAttributes = geometry.morphAttributes; + const keys2 = Object.keys(morphAttributes); + if (keys2.length > 0) { + const morphAttribute = morphAttributes[keys2[0]]; + if (morphAttribute !== undefined) { + this.morphTargetInfluences = []; + this.morphTargetDictionary = {}; + for (let m = 0, ml = morphAttribute.length;m < ml; m++) { + const name2 = morphAttribute[m].name || String(m); + this.morphTargetInfluences.push(0); + this.morphTargetDictionary[name2] = m; + } + } + } + } +} +function testPoint(point, index2, localThresholdSq, matrixWorld, raycaster, intersects, object) { + const rayPointDistanceSq = _ray.distanceSqToPoint(point); + if (rayPointDistanceSq < localThresholdSq) { + const intersectPoint = new Vector3; + _ray.closestPointToPoint(point, intersectPoint); + intersectPoint.applyMatrix4(matrixWorld); + const distance = raycaster.ray.origin.distanceTo(intersectPoint); + if (distance < raycaster.near || distance > raycaster.far) + return; + intersects.push({ + distance, + distanceToRay: Math.sqrt(rayPointDistanceSq), + point: intersectPoint, + index: index2, + face: null, + faceIndex: null, + barycoord: null, + object + }); + } +} + +class VideoTexture extends Texture { + constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoTexture = true; + this.minFilter = minFilter !== undefined ? minFilter : LinearFilter; + this.magFilter = magFilter !== undefined ? magFilter : LinearFilter; + this.generateMipmaps = false; + const scope = this; + function updateVideo() { + scope.needsUpdate = true; + video.requestVideoFrameCallback(updateVideo); + } + if ("requestVideoFrameCallback" in video) { + video.requestVideoFrameCallback(updateVideo); + } + } + clone() { + return new this.constructor(this.image).copy(this); + } + update() { + const video = this.image; + const hasVideoFrameCallback = "requestVideoFrameCallback" in video; + if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) { + this.needsUpdate = true; + } + } +} + +class VideoFrameTexture extends VideoTexture { + constructor(mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super({}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isVideoFrameTexture = true; + } + update() { + } + clone() { + return new this.constructor().copy(this); + } + setFrame(frame) { + this.image = frame; + this.needsUpdate = true; + } +} + +class FramebufferTexture extends Texture { + constructor(width2, height2) { + super({ width: width2, height: height2 }); + this.isFramebufferTexture = true; + this.magFilter = NearestFilter; + this.minFilter = NearestFilter; + this.generateMipmaps = false; + this.needsUpdate = true; + } +} + +class CompressedTexture extends Texture { + constructor(mipmaps, width2, height2, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace) { + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace); + this.isCompressedTexture = true; + this.image = { width: width2, height: height2 }; + this.mipmaps = mipmaps; + this.flipY = false; + this.generateMipmaps = false; + } +} + +class CompressedArrayTexture extends CompressedTexture { + constructor(mipmaps, width2, height2, depth, format, type) { + super(mipmaps, width2, height2, format, type); + this.isCompressedArrayTexture = true; + this.image.depth = depth; + this.wrapR = ClampToEdgeWrapping; + this.layerUpdates = new Set; + } + addLayerUpdate(layerIndex) { + this.layerUpdates.add(layerIndex); + } + clearLayerUpdates() { + this.layerUpdates.clear(); + } +} + +class CompressedCubeTexture extends CompressedTexture { + constructor(images, format, type) { + super(undefined, images[0].width, images[0].height, format, type, CubeReflectionMapping); + this.isCompressedCubeTexture = true; + this.isCubeTexture = true; + this.image = images; + } +} + +class CanvasTexture extends Texture { + constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) { + super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isCanvasTexture = true; + this.needsUpdate = true; + } +} + +class DepthTexture extends Texture { + constructor(width2, height2, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat) { + if (format !== DepthFormat && format !== DepthStencilFormat) { + throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); + } + if (type === undefined && format === DepthFormat) + type = UnsignedIntType; + if (type === undefined && format === DepthStencilFormat) + type = UnsignedInt248Type; + super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); + this.isDepthTexture = true; + this.image = { width: width2, height: height2 }; + this.magFilter = magFilter !== undefined ? magFilter : NearestFilter; + this.minFilter = minFilter !== undefined ? minFilter : NearestFilter; + this.flipY = false; + this.generateMipmaps = false; + this.compareFunction = null; + } + copy(source) { + super.copy(source); + this.compareFunction = source.compareFunction; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + if (this.compareFunction !== null) + data2.compareFunction = this.compareFunction; + return data2; + } +} + +class Curve { + constructor() { + this.type = "Curve"; + this.arcLengthDivisions = 200; + } + getPoint() { + console.warn("THREE.Curve: .getPoint() not implemented."); + return null; + } + getPointAt(u, optionalTarget) { + const t = this.getUtoTmapping(u); + return this.getPoint(t, optionalTarget); + } + getPoints(divisions = 5) { + const points = []; + for (let d = 0;d <= divisions; d++) { + points.push(this.getPoint(d / divisions)); + } + return points; + } + getSpacedPoints(divisions = 5) { + const points = []; + for (let d = 0;d <= divisions; d++) { + points.push(this.getPointAt(d / divisions)); + } + return points; + } + getLength() { + const lengths = this.getLengths(); + return lengths[lengths.length - 1]; + } + getLengths(divisions = this.arcLengthDivisions) { + if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) { + return this.cacheArcLengths; + } + this.needsUpdate = false; + const cache = []; + let current, last2 = this.getPoint(0); + let sum2 = 0; + cache.push(0); + for (let p = 1;p <= divisions; p++) { + current = this.getPoint(p / divisions); + sum2 += current.distanceTo(last2); + cache.push(sum2); + last2 = current; + } + this.cacheArcLengths = cache; + return cache; + } + updateArcLengths() { + this.needsUpdate = true; + this.getLengths(); + } + getUtoTmapping(u, distance) { + const arcLengths = this.getLengths(); + let i = 0; + const il = arcLengths.length; + let targetArcLength; + if (distance) { + targetArcLength = distance; + } else { + targetArcLength = u * arcLengths[il - 1]; + } + let low = 0, high = il - 1, comparison; + while (low <= high) { + i = Math.floor(low + (high - low) / 2); + comparison = arcLengths[i] - targetArcLength; + if (comparison < 0) { + low = i + 1; + } else if (comparison > 0) { + high = i - 1; + } else { + high = i; + break; + } + } + i = high; + if (arcLengths[i] === targetArcLength) { + return i / (il - 1); + } + const lengthBefore = arcLengths[i]; + const lengthAfter = arcLengths[i + 1]; + const segmentLength = lengthAfter - lengthBefore; + const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; + const t = (i + segmentFraction) / (il - 1); + return t; + } + getTangent(t, optionalTarget) { + const delta = 0.0001; + let t1 = t - delta; + let t2 = t + delta; + if (t1 < 0) + t1 = 0; + if (t2 > 1) + t2 = 1; + const pt1 = this.getPoint(t1); + const pt2 = this.getPoint(t2); + const tangent = optionalTarget || (pt1.isVector2 ? new Vector2 : new Vector3); + tangent.copy(pt2).sub(pt1).normalize(); + return tangent; + } + getTangentAt(u, optionalTarget) { + const t = this.getUtoTmapping(u); + return this.getTangent(t, optionalTarget); + } + computeFrenetFrames(segments, closed) { + const normal = new Vector3; + const tangents = []; + const normals = []; + const binormals = []; + const vec = new Vector3; + const mat = new Matrix4; + for (let i = 0;i <= segments; i++) { + const u = i / segments; + tangents[i] = this.getTangentAt(u, new Vector3); + } + normals[0] = new Vector3; + binormals[0] = new Vector3; + let min = Number.MAX_VALUE; + const tx = Math.abs(tangents[0].x); + const ty = Math.abs(tangents[0].y); + const tz = Math.abs(tangents[0].z); + if (tx <= min) { + min = tx; + normal.set(1, 0, 0); + } + if (ty <= min) { + min = ty; + normal.set(0, 1, 0); + } + if (tz <= min) { + normal.set(0, 0, 1); + } + vec.crossVectors(tangents[0], normal).normalize(); + normals[0].crossVectors(tangents[0], vec); + binormals[0].crossVectors(tangents[0], normals[0]); + for (let i = 1;i <= segments; i++) { + normals[i] = normals[i - 1].clone(); + binormals[i] = binormals[i - 1].clone(); + vec.crossVectors(tangents[i - 1], tangents[i]); + if (vec.length() > Number.EPSILON) { + vec.normalize(); + const theta = Math.acos(clamp2(tangents[i - 1].dot(tangents[i]), -1, 1)); + normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta)); + } + binormals[i].crossVectors(tangents[i], normals[i]); + } + if (closed === true) { + let theta = Math.acos(clamp2(normals[0].dot(normals[segments]), -1, 1)); + theta /= segments; + if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) { + theta = -theta; + } + for (let i = 1;i <= segments; i++) { + normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i)); + binormals[i].crossVectors(tangents[i], normals[i]); + } + } + return { + tangents, + normals, + binormals + }; + } + clone() { + return new this.constructor().copy(this); + } + copy(source) { + this.arcLengthDivisions = source.arcLengthDivisions; + return this; + } + toJSON() { + const data2 = { + metadata: { + version: 4.6, + type: "Curve", + generator: "Curve.toJSON" + } + }; + data2.arcLengthDivisions = this.arcLengthDivisions; + data2.type = this.type; + return data2; + } + fromJSON(json) { + this.arcLengthDivisions = json.arcLengthDivisions; + return this; + } +} + +class EllipseCurve extends Curve { + constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) { + super(); + this.isEllipseCurve = true; + this.type = "EllipseCurve"; + this.aX = aX; + this.aY = aY; + this.xRadius = xRadius; + this.yRadius = yRadius; + this.aStartAngle = aStartAngle; + this.aEndAngle = aEndAngle; + this.aClockwise = aClockwise; + this.aRotation = aRotation; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + const twoPi = Math.PI * 2; + let deltaAngle = this.aEndAngle - this.aStartAngle; + const samePoints = Math.abs(deltaAngle) < Number.EPSILON; + while (deltaAngle < 0) + deltaAngle += twoPi; + while (deltaAngle > twoPi) + deltaAngle -= twoPi; + if (deltaAngle < Number.EPSILON) { + if (samePoints) { + deltaAngle = 0; + } else { + deltaAngle = twoPi; + } + } + if (this.aClockwise === true && !samePoints) { + if (deltaAngle === twoPi) { + deltaAngle = -twoPi; + } else { + deltaAngle = deltaAngle - twoPi; + } + } + const angle = this.aStartAngle + t * deltaAngle; + let x = this.aX + this.xRadius * Math.cos(angle); + let y = this.aY + this.yRadius * Math.sin(angle); + if (this.aRotation !== 0) { + const cos = Math.cos(this.aRotation); + const sin = Math.sin(this.aRotation); + const tx = x - this.aX; + const ty = y - this.aY; + x = tx * cos - ty * sin + this.aX; + y = tx * sin + ty * cos + this.aY; + } + return point.set(x, y); + } + copy(source) { + super.copy(source); + this.aX = source.aX; + this.aY = source.aY; + this.xRadius = source.xRadius; + this.yRadius = source.yRadius; + this.aStartAngle = source.aStartAngle; + this.aEndAngle = source.aEndAngle; + this.aClockwise = source.aClockwise; + this.aRotation = source.aRotation; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.aX = this.aX; + data2.aY = this.aY; + data2.xRadius = this.xRadius; + data2.yRadius = this.yRadius; + data2.aStartAngle = this.aStartAngle; + data2.aEndAngle = this.aEndAngle; + data2.aClockwise = this.aClockwise; + data2.aRotation = this.aRotation; + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.aX = json.aX; + this.aY = json.aY; + this.xRadius = json.xRadius; + this.yRadius = json.yRadius; + this.aStartAngle = json.aStartAngle; + this.aEndAngle = json.aEndAngle; + this.aClockwise = json.aClockwise; + this.aRotation = json.aRotation; + return this; + } +} + +class ArcCurve extends EllipseCurve { + constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + this.isArcCurve = true; + this.type = "ArcCurve"; + } +} +function CubicPoly() { + let c0 = 0, c1 = 0, c2 = 0, c3 = 0; + function init(x0, x1, t0, t1) { + c0 = x0; + c1 = t0; + c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1; + c3 = 2 * x0 - 2 * x1 + t0 + t1; + } + return { + initCatmullRom: function(x0, x1, x2, x3, tension) { + init(x1, x2, tension * (x2 - x0), tension * (x3 - x1)); + }, + initNonuniformCatmullRom: function(x0, x1, x2, x3, dt0, dt1, dt2) { + let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1; + let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; + t1 *= dt1; + t2 *= dt1; + init(x1, x2, t1, t2); + }, + calc: function(t) { + const t2 = t * t; + const t3 = t2 * t; + return c0 + c1 * t + c2 * t2 + c3 * t3; + } + }; +} +var tmp = /* @__PURE__ */ new Vector3; +var px = /* @__PURE__ */ new CubicPoly; +var py = /* @__PURE__ */ new CubicPoly; +var pz = /* @__PURE__ */ new CubicPoly; + +class CatmullRomCurve3 extends Curve { + constructor(points = [], closed = false, curveType = "centripetal", tension = 0.5) { + super(); + this.isCatmullRomCurve3 = true; + this.type = "CatmullRomCurve3"; + this.points = points; + this.closed = closed; + this.curveType = curveType; + this.tension = tension; + } + getPoint(t, optionalTarget = new Vector3) { + const point = optionalTarget; + const points = this.points; + const l = points.length; + const p = (l - (this.closed ? 0 : 1)) * t; + let intPoint = Math.floor(p); + let weight = p - intPoint; + if (this.closed) { + intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l; + } else if (weight === 0 && intPoint === l - 1) { + intPoint = l - 2; + weight = 1; + } + let p0, p3; + if (this.closed || intPoint > 0) { + p0 = points[(intPoint - 1) % l]; + } else { + tmp.subVectors(points[0], points[1]).add(points[0]); + p0 = tmp; + } + const p1 = points[intPoint % l]; + const p2 = points[(intPoint + 1) % l]; + if (this.closed || intPoint + 2 < l) { + p3 = points[(intPoint + 2) % l]; + } else { + tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]); + p3 = tmp; + } + if (this.curveType === "centripetal" || this.curveType === "chordal") { + const pow = this.curveType === "chordal" ? 0.5 : 0.25; + let dt0 = Math.pow(p0.distanceToSquared(p1), pow); + let dt1 = Math.pow(p1.distanceToSquared(p2), pow); + let dt2 = Math.pow(p2.distanceToSquared(p3), pow); + if (dt1 < 0.0001) + dt1 = 1; + if (dt0 < 0.0001) + dt0 = dt1; + if (dt2 < 0.0001) + dt2 = dt1; + px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2); + py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2); + pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2); + } else if (this.curveType === "catmullrom") { + px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension); + py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension); + pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension); + } + point.set(px.calc(weight), py.calc(weight), pz.calc(weight)); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l = source.points.length;i < l; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + this.closed = source.closed; + this.curveType = source.curveType; + this.tension = source.tension; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.points = []; + for (let i = 0, l = this.points.length;i < l; i++) { + const point = this.points[i]; + data2.points.push(point.toArray()); + } + data2.closed = this.closed; + data2.curveType = this.curveType; + data2.tension = this.tension; + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l = json.points.length;i < l; i++) { + const point = json.points[i]; + this.points.push(new Vector3().fromArray(point)); + } + this.closed = json.closed; + this.curveType = json.curveType; + this.tension = json.tension; + return this; + } +} +function CatmullRom(t, p0, p1, p2, p3) { + const v0 = (p2 - p0) * 0.5; + const v1 = (p3 - p1) * 0.5; + const t2 = t * t; + const t3 = t * t2; + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; +} +function QuadraticBezierP0(t, p) { + const k = 1 - t; + return k * k * p; +} +function QuadraticBezierP1(t, p) { + return 2 * (1 - t) * t * p; +} +function QuadraticBezierP2(t, p) { + return t * t * p; +} +function QuadraticBezier(t, p0, p1, p2) { + return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2); +} +function CubicBezierP0(t, p) { + const k = 1 - t; + return k * k * k * p; +} +function CubicBezierP1(t, p) { + const k = 1 - t; + return 3 * k * k * t * p; +} +function CubicBezierP2(t, p) { + return 3 * (1 - t) * t * t * p; +} +function CubicBezierP3(t, p) { + return t * t * t * p; +} +function CubicBezier(t, p0, p1, p2, p3) { + return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3); +} + +class CubicBezierCurve extends Curve { + constructor(v0 = new Vector2, v1 = new Vector2, v2 = new Vector2, v3 = new Vector2) { + super(); + this.isCubicBezierCurve = true; + this.type = "CubicBezierCurve"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + data2.v3 = this.v3.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } +} + +class CubicBezierCurve3 extends Curve { + constructor(v0 = new Vector3, v1 = new Vector3, v2 = new Vector3, v3 = new Vector3) { + super(); + this.isCubicBezierCurve3 = true; + this.type = "CubicBezierCurve3"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + this.v3 = v3; + } + getPoint(t, optionalTarget = new Vector3) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; + point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + this.v3.copy(source.v3); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + data2.v3 = this.v3.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + this.v3.fromArray(json.v3); + return this; + } +} + +class LineCurve extends Curve { + constructor(v1 = new Vector2, v2 = new Vector2) { + super(); + this.isLineCurve = true; + this.type = "LineCurve"; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + if (t === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t).add(this.v1); + } + return point; + } + getPointAt(u, optionalTarget) { + return this.getPoint(u, optionalTarget); + } + getTangent(t, optionalTarget = new Vector2) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u, optionalTarget) { + return this.getTangent(u, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } +} + +class LineCurve3 extends Curve { + constructor(v1 = new Vector3, v2 = new Vector3) { + super(); + this.isLineCurve3 = true; + this.type = "LineCurve3"; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector3) { + const point = optionalTarget; + if (t === 1) { + point.copy(this.v2); + } else { + point.copy(this.v2).sub(this.v1); + point.multiplyScalar(t).add(this.v1); + } + return point; + } + getPointAt(u, optionalTarget) { + return this.getPoint(u, optionalTarget); + } + getTangent(t, optionalTarget = new Vector3) { + return optionalTarget.subVectors(this.v2, this.v1).normalize(); + } + getTangentAt(u, optionalTarget) { + return this.getTangent(u, optionalTarget); + } + copy(source) { + super.copy(source); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } +} + +class QuadraticBezierCurve extends Curve { + constructor(v0 = new Vector2, v1 = new Vector2, v2 = new Vector2) { + super(); + this.isQuadraticBezierCurve = true; + this.type = "QuadraticBezierCurve"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } +} + +class QuadraticBezierCurve3 extends Curve { + constructor(v0 = new Vector3, v1 = new Vector3, v2 = new Vector3) { + super(); + this.isQuadraticBezierCurve3 = true; + this.type = "QuadraticBezierCurve3"; + this.v0 = v0; + this.v1 = v1; + this.v2 = v2; + } + getPoint(t, optionalTarget = new Vector3) { + const point = optionalTarget; + const v0 = this.v0, v1 = this.v1, v2 = this.v2; + point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z)); + return point; + } + copy(source) { + super.copy(source); + this.v0.copy(source.v0); + this.v1.copy(source.v1); + this.v2.copy(source.v2); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.v0 = this.v0.toArray(); + data2.v1 = this.v1.toArray(); + data2.v2 = this.v2.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.v0.fromArray(json.v0); + this.v1.fromArray(json.v1); + this.v2.fromArray(json.v2); + return this; + } +} + +class SplineCurve extends Curve { + constructor(points = []) { + super(); + this.isSplineCurve = true; + this.type = "SplineCurve"; + this.points = points; + } + getPoint(t, optionalTarget = new Vector2) { + const point = optionalTarget; + const points = this.points; + const p = (points.length - 1) * t; + const intPoint = Math.floor(p); + const weight = p - intPoint; + const p0 = points[intPoint === 0 ? intPoint : intPoint - 1]; + const p1 = points[intPoint]; + const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1]; + const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2]; + point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y)); + return point; + } + copy(source) { + super.copy(source); + this.points = []; + for (let i = 0, l = source.points.length;i < l; i++) { + const point = source.points[i]; + this.points.push(point.clone()); + } + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.points = []; + for (let i = 0, l = this.points.length;i < l; i++) { + const point = this.points[i]; + data2.points.push(point.toArray()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.points = []; + for (let i = 0, l = json.points.length;i < l; i++) { + const point = json.points[i]; + this.points.push(new Vector2().fromArray(point)); + } + return this; + } +} +var Curves = /* @__PURE__ */ Object.freeze({ + __proto__: null, + ArcCurve, + CatmullRomCurve3, + CubicBezierCurve, + CubicBezierCurve3, + EllipseCurve, + LineCurve, + LineCurve3, + QuadraticBezierCurve, + QuadraticBezierCurve3, + SplineCurve +}); + +class CurvePath extends Curve { + constructor() { + super(); + this.type = "CurvePath"; + this.curves = []; + this.autoClose = false; + } + add(curve) { + this.curves.push(curve); + } + closePath() { + const startPoint = this.curves[0].getPoint(0); + const endPoint = this.curves[this.curves.length - 1].getPoint(1); + if (!startPoint.equals(endPoint)) { + const lineType = startPoint.isVector2 === true ? "LineCurve" : "LineCurve3"; + this.curves.push(new Curves[lineType](endPoint, startPoint)); + } + return this; + } + getPoint(t, optionalTarget) { + const d = t * this.getLength(); + const curveLengths = this.getCurveLengths(); + let i = 0; + while (i < curveLengths.length) { + if (curveLengths[i] >= d) { + const diff = curveLengths[i] - d; + const curve = this.curves[i]; + const segmentLength = curve.getLength(); + const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; + return curve.getPointAt(u, optionalTarget); + } + i++; + } + return null; + } + getLength() { + const lens = this.getCurveLengths(); + return lens[lens.length - 1]; + } + updateArcLengths() { + this.needsUpdate = true; + this.cacheLengths = null; + this.getCurveLengths(); + } + getCurveLengths() { + if (this.cacheLengths && this.cacheLengths.length === this.curves.length) { + return this.cacheLengths; + } + const lengths = []; + let sums = 0; + for (let i = 0, l = this.curves.length;i < l; i++) { + sums += this.curves[i].getLength(); + lengths.push(sums); + } + this.cacheLengths = lengths; + return lengths; + } + getSpacedPoints(divisions = 40) { + const points = []; + for (let i = 0;i <= divisions; i++) { + points.push(this.getPoint(i / divisions)); + } + if (this.autoClose) { + points.push(points[0]); + } + return points; + } + getPoints(divisions = 12) { + const points = []; + let last2; + for (let i = 0, curves = this.curves;i < curves.length; i++) { + const curve = curves[i]; + const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions; + const pts = curve.getPoints(resolution); + for (let j = 0;j < pts.length; j++) { + const point = pts[j]; + if (last2 && last2.equals(point)) + continue; + points.push(point); + last2 = point; + } + } + if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) { + points.push(points[0]); + } + return points; + } + copy(source) { + super.copy(source); + this.curves = []; + for (let i = 0, l = source.curves.length;i < l; i++) { + const curve = source.curves[i]; + this.curves.push(curve.clone()); + } + this.autoClose = source.autoClose; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.autoClose = this.autoClose; + data2.curves = []; + for (let i = 0, l = this.curves.length;i < l; i++) { + const curve = this.curves[i]; + data2.curves.push(curve.toJSON()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.autoClose = json.autoClose; + this.curves = []; + for (let i = 0, l = json.curves.length;i < l; i++) { + const curve = json.curves[i]; + this.curves.push(new Curves[curve.type]().fromJSON(curve)); + } + return this; + } +} + +class Path extends CurvePath { + constructor(points) { + super(); + this.type = "Path"; + this.currentPoint = new Vector2; + if (points) { + this.setFromPoints(points); + } + } + setFromPoints(points) { + this.moveTo(points[0].x, points[0].y); + for (let i = 1, l = points.length;i < l; i++) { + this.lineTo(points[i].x, points[i].y); + } + return this; + } + moveTo(x, y) { + this.currentPoint.set(x, y); + return this; + } + lineTo(x, y) { + const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y)); + this.curves.push(curve); + this.currentPoint.set(x, y); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY)); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY)); + this.curves.push(curve); + this.currentPoint.set(aX, aY); + return this; + } + splineThru(pts) { + const npts = [this.currentPoint.clone()].concat(pts); + const curve = new SplineCurve(npts); + this.curves.push(curve); + this.currentPoint.copy(pts[pts.length - 1]); + return this; + } + arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { + this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); + return this; + } + ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const x0 = this.currentPoint.x; + const y0 = this.currentPoint.y; + this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + return this; + } + absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { + const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); + if (this.curves.length > 0) { + const firstPoint = curve.getPoint(0); + if (!firstPoint.equals(this.currentPoint)) { + this.lineTo(firstPoint.x, firstPoint.y); + } + } + this.curves.push(curve); + const lastPoint = curve.getPoint(1); + this.currentPoint.copy(lastPoint); + return this; + } + copy(source) { + super.copy(source); + this.currentPoint.copy(source.currentPoint); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.currentPoint = this.currentPoint.toArray(); + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.currentPoint.fromArray(json.currentPoint); + return this; + } +} + +class LatheGeometry extends BufferGeometry { + constructor(points = [new Vector2(0, -0.5), new Vector2(0.5, 0), new Vector2(0, 0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) { + super(); + this.type = "LatheGeometry"; + this.parameters = { + points, + segments, + phiStart, + phiLength + }; + segments = Math.floor(segments); + phiLength = clamp2(phiLength, 0, Math.PI * 2); + const indices = []; + const vertices = []; + const uvs = []; + const initNormals = []; + const normals = []; + const inverseSegments = 1 / segments; + const vertex = new Vector3; + const uv = new Vector2; + const normal = new Vector3; + const curNormal = new Vector3; + const prevNormal = new Vector3; + let dx = 0; + let dy = 0; + for (let j = 0;j <= points.length - 1; j++) { + switch (j) { + case 0: + dx = points[j + 1].x - points[j].x; + dy = points[j + 1].y - points[j].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + prevNormal.copy(normal); + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + break; + case points.length - 1: + initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z); + break; + default: + dx = points[j + 1].x - points[j].x; + dy = points[j + 1].y - points[j].y; + normal.x = dy * 1; + normal.y = -dx; + normal.z = dy * 0; + curNormal.copy(normal); + normal.x += prevNormal.x; + normal.y += prevNormal.y; + normal.z += prevNormal.z; + normal.normalize(); + initNormals.push(normal.x, normal.y, normal.z); + prevNormal.copy(curNormal); + } + } + for (let i = 0;i <= segments; i++) { + const phi = phiStart + i * inverseSegments * phiLength; + const sin = Math.sin(phi); + const cos = Math.cos(phi); + for (let j = 0;j <= points.length - 1; j++) { + vertex.x = points[j].x * sin; + vertex.y = points[j].y; + vertex.z = points[j].x * cos; + vertices.push(vertex.x, vertex.y, vertex.z); + uv.x = i / segments; + uv.y = j / (points.length - 1); + uvs.push(uv.x, uv.y); + const x = initNormals[3 * j + 0] * sin; + const y = initNormals[3 * j + 1]; + const z = initNormals[3 * j + 0] * cos; + normals.push(x, y, z); + } + } + for (let i = 0;i < segments; i++) { + for (let j = 0;j < points.length - 1; j++) { + const base = j + i * points.length; + const a = base; + const b = base + points.length; + const c = base + points.length + 1; + const d = base + 1; + indices.push(a, b, d); + indices.push(c, d, b); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new LatheGeometry(data2.points, data2.segments, data2.phiStart, data2.phiLength); + } +} + +class CapsuleGeometry extends LatheGeometry { + constructor(radius = 1, length2 = 1, capSegments = 4, radialSegments = 8) { + const path = new Path; + path.absarc(0, -length2 / 2, radius, Math.PI * 1.5, 0); + path.absarc(0, length2 / 2, radius, 0, Math.PI * 0.5); + super(path.getPoints(capSegments), radialSegments); + this.type = "CapsuleGeometry"; + this.parameters = { + radius, + length: length2, + capSegments, + radialSegments + }; + } + static fromJSON(data2) { + return new CapsuleGeometry(data2.radius, data2.length, data2.capSegments, data2.radialSegments); + } +} + +class CircleGeometry extends BufferGeometry { + constructor(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CircleGeometry"; + this.parameters = { + radius, + segments, + thetaStart, + thetaLength + }; + segments = Math.max(3, segments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex = new Vector3; + const uv = new Vector2; + vertices.push(0, 0, 0); + normals.push(0, 0, 1); + uvs.push(0.5, 0.5); + for (let s = 0, i = 3;s <= segments; s++, i += 3) { + const segment = thetaStart + s / segments * thetaLength; + vertex.x = radius * Math.cos(segment); + vertex.y = radius * Math.sin(segment); + vertices.push(vertex.x, vertex.y, vertex.z); + normals.push(0, 0, 1); + uv.x = (vertices[i] / radius + 1) / 2; + uv.y = (vertices[i + 1] / radius + 1) / 2; + uvs.push(uv.x, uv.y); + } + for (let i = 1;i <= segments; i++) { + indices.push(i, i + 1, 0); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new CircleGeometry(data2.radius, data2.segments, data2.thetaStart, data2.thetaLength); + } +} + +class CylinderGeometry extends BufferGeometry { + constructor(radiusTop = 1, radiusBottom = 1, height2 = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "CylinderGeometry"; + this.parameters = { + radiusTop, + radiusBottom, + height: height2, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + const scope = this; + radialSegments = Math.floor(radialSegments); + heightSegments = Math.floor(heightSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let index2 = 0; + const indexArray = []; + const halfHeight = height2 / 2; + let groupStart = 0; + generateTorso(); + if (openEnded === false) { + if (radiusTop > 0) + generateCap(true); + if (radiusBottom > 0) + generateCap(false); + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function generateTorso() { + const normal = new Vector3; + const vertex = new Vector3; + let groupCount = 0; + const slope = (radiusBottom - radiusTop) / height2; + for (let y = 0;y <= heightSegments; y++) { + const indexRow = []; + const v = y / heightSegments; + const radius = v * (radiusBottom - radiusTop) + radiusTop; + for (let x = 0;x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const sinTheta = Math.sin(theta); + const cosTheta = Math.cos(theta); + vertex.x = radius * sinTheta; + vertex.y = -v * height2 + halfHeight; + vertex.z = radius * cosTheta; + vertices.push(vertex.x, vertex.y, vertex.z); + normal.set(sinTheta, slope, cosTheta).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u, 1 - v); + indexRow.push(index2++); + } + indexArray.push(indexRow); + } + for (let x = 0;x < radialSegments; x++) { + for (let y = 0;y < heightSegments; y++) { + const a = indexArray[y][x]; + const b = indexArray[y + 1][x]; + const c = indexArray[y + 1][x + 1]; + const d = indexArray[y][x + 1]; + if (radiusTop > 0 || y !== 0) { + indices.push(a, b, d); + groupCount += 3; + } + if (radiusBottom > 0 || y !== heightSegments - 1) { + indices.push(b, c, d); + groupCount += 3; + } + } + } + scope.addGroup(groupStart, groupCount, 0); + groupStart += groupCount; + } + function generateCap(top) { + const centerIndexStart = index2; + const uv = new Vector2; + const vertex = new Vector3; + let groupCount = 0; + const radius = top === true ? radiusTop : radiusBottom; + const sign = top === true ? 1 : -1; + for (let x = 1;x <= radialSegments; x++) { + vertices.push(0, halfHeight * sign, 0); + normals.push(0, sign, 0); + uvs.push(0.5, 0.5); + index2++; + } + const centerIndexEnd = index2; + for (let x = 0;x <= radialSegments; x++) { + const u = x / radialSegments; + const theta = u * thetaLength + thetaStart; + const cosTheta = Math.cos(theta); + const sinTheta = Math.sin(theta); + vertex.x = radius * sinTheta; + vertex.y = halfHeight * sign; + vertex.z = radius * cosTheta; + vertices.push(vertex.x, vertex.y, vertex.z); + normals.push(0, sign, 0); + uv.x = cosTheta * 0.5 + 0.5; + uv.y = sinTheta * 0.5 * sign + 0.5; + uvs.push(uv.x, uv.y); + index2++; + } + for (let x = 0;x < radialSegments; x++) { + const c = centerIndexStart + x; + const i = centerIndexEnd + x; + if (top === true) { + indices.push(i, i + 1, c); + } else { + indices.push(i + 1, i, c); + } + groupCount += 3; + } + scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); + groupStart += groupCount; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new CylinderGeometry(data2.radiusTop, data2.radiusBottom, data2.height, data2.radialSegments, data2.heightSegments, data2.openEnded, data2.thetaStart, data2.thetaLength); + } +} + +class ConeGeometry extends CylinderGeometry { + constructor(radius = 1, height2 = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { + super(0, radius, height2, radialSegments, heightSegments, openEnded, thetaStart, thetaLength); + this.type = "ConeGeometry"; + this.parameters = { + radius, + height: height2, + radialSegments, + heightSegments, + openEnded, + thetaStart, + thetaLength + }; + } + static fromJSON(data2) { + return new ConeGeometry(data2.radius, data2.height, data2.radialSegments, data2.heightSegments, data2.openEnded, data2.thetaStart, data2.thetaLength); + } +} + +class PolyhedronGeometry extends BufferGeometry { + constructor(vertices = [], indices = [], radius = 1, detail = 0) { + super(); + this.type = "PolyhedronGeometry"; + this.parameters = { + vertices, + indices, + radius, + detail + }; + const vertexBuffer = []; + const uvBuffer = []; + subdivide(detail); + applyRadius(radius); + generateUVs(); + this.setAttribute("position", new Float32BufferAttribute(vertexBuffer, 3)); + this.setAttribute("normal", new Float32BufferAttribute(vertexBuffer.slice(), 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvBuffer, 2)); + if (detail === 0) { + this.computeVertexNormals(); + } else { + this.normalizeNormals(); + } + function subdivide(detail2) { + const a = new Vector3; + const b = new Vector3; + const c = new Vector3; + for (let i = 0;i < indices.length; i += 3) { + getVertexByIndex(indices[i + 0], a); + getVertexByIndex(indices[i + 1], b); + getVertexByIndex(indices[i + 2], c); + subdivideFace(a, b, c, detail2); + } + } + function subdivideFace(a, b, c, detail2) { + const cols = detail2 + 1; + const v = []; + for (let i = 0;i <= cols; i++) { + v[i] = []; + const aj = a.clone().lerp(c, i / cols); + const bj = b.clone().lerp(c, i / cols); + const rows = cols - i; + for (let j = 0;j <= rows; j++) { + if (j === 0 && i === cols) { + v[i][j] = aj; + } else { + v[i][j] = aj.clone().lerp(bj, j / rows); + } + } + } + for (let i = 0;i < cols; i++) { + for (let j = 0;j < 2 * (cols - i) - 1; j++) { + const k = Math.floor(j / 2); + if (j % 2 === 0) { + pushVertex(v[i][k + 1]); + pushVertex(v[i + 1][k]); + pushVertex(v[i][k]); + } else { + pushVertex(v[i][k + 1]); + pushVertex(v[i + 1][k + 1]); + pushVertex(v[i + 1][k]); + } + } + } + } + function applyRadius(radius2) { + const vertex = new Vector3; + for (let i = 0;i < vertexBuffer.length; i += 3) { + vertex.x = vertexBuffer[i + 0]; + vertex.y = vertexBuffer[i + 1]; + vertex.z = vertexBuffer[i + 2]; + vertex.normalize().multiplyScalar(radius2); + vertexBuffer[i + 0] = vertex.x; + vertexBuffer[i + 1] = vertex.y; + vertexBuffer[i + 2] = vertex.z; + } + } + function generateUVs() { + const vertex = new Vector3; + for (let i = 0;i < vertexBuffer.length; i += 3) { + vertex.x = vertexBuffer[i + 0]; + vertex.y = vertexBuffer[i + 1]; + vertex.z = vertexBuffer[i + 2]; + const u = azimuth(vertex) / 2 / Math.PI + 0.5; + const v = inclination(vertex) / Math.PI + 0.5; + uvBuffer.push(u, 1 - v); + } + correctUVs(); + correctSeam(); + } + function correctSeam() { + for (let i = 0;i < uvBuffer.length; i += 6) { + const x0 = uvBuffer[i + 0]; + const x1 = uvBuffer[i + 2]; + const x2 = uvBuffer[i + 4]; + const max = Math.max(x0, x1, x2); + const min = Math.min(x0, x1, x2); + if (max > 0.9 && min < 0.1) { + if (x0 < 0.2) + uvBuffer[i + 0] += 1; + if (x1 < 0.2) + uvBuffer[i + 2] += 1; + if (x2 < 0.2) + uvBuffer[i + 4] += 1; + } + } + } + function pushVertex(vertex) { + vertexBuffer.push(vertex.x, vertex.y, vertex.z); + } + function getVertexByIndex(index2, vertex) { + const stride = index2 * 3; + vertex.x = vertices[stride + 0]; + vertex.y = vertices[stride + 1]; + vertex.z = vertices[stride + 2]; + } + function correctUVs() { + const a = new Vector3; + const b = new Vector3; + const c = new Vector3; + const centroid = new Vector3; + const uvA = new Vector2; + const uvB = new Vector2; + const uvC = new Vector2; + for (let i = 0, j = 0;i < vertexBuffer.length; i += 9, j += 6) { + a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]); + b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]); + c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]); + uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]); + uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]); + uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]); + centroid.copy(a).add(b).add(c).divideScalar(3); + const azi = azimuth(centroid); + correctUV(uvA, j + 0, a, azi); + correctUV(uvB, j + 2, b, azi); + correctUV(uvC, j + 4, c, azi); + } + } + function correctUV(uv, stride, vector, azimuth2) { + if (azimuth2 < 0 && uv.x === 1) { + uvBuffer[stride] = uv.x - 1; + } + if (vector.x === 0 && vector.z === 0) { + uvBuffer[stride] = azimuth2 / 2 / Math.PI + 0.5; + } + } + function azimuth(vector) { + return Math.atan2(vector.z, -vector.x); + } + function inclination(vector) { + return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new PolyhedronGeometry(data2.vertices, data2.indices, data2.radius, data2.details); + } +} + +class DodecahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const t = (1 + Math.sqrt(5)) / 2; + const r = 1 / t; + const vertices = [ + -1, + -1, + -1, + -1, + -1, + 1, + -1, + 1, + -1, + -1, + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + 1, + 1, + -1, + 1, + 1, + 1, + 0, + -r, + -t, + 0, + -r, + t, + 0, + r, + -t, + 0, + r, + t, + -r, + -t, + 0, + -r, + t, + 0, + r, + -t, + 0, + r, + t, + 0, + -t, + 0, + -r, + t, + 0, + -r, + -t, + 0, + r, + t, + 0, + r + ]; + const indices = [ + 3, + 11, + 7, + 3, + 7, + 15, + 3, + 15, + 13, + 7, + 19, + 17, + 7, + 17, + 6, + 7, + 6, + 15, + 17, + 4, + 8, + 17, + 8, + 10, + 17, + 10, + 6, + 8, + 0, + 16, + 8, + 16, + 2, + 8, + 2, + 10, + 0, + 12, + 1, + 0, + 1, + 18, + 0, + 18, + 16, + 6, + 10, + 2, + 6, + 2, + 13, + 6, + 13, + 15, + 2, + 16, + 18, + 2, + 18, + 3, + 2, + 3, + 13, + 18, + 1, + 9, + 18, + 9, + 11, + 18, + 11, + 3, + 4, + 14, + 12, + 4, + 12, + 0, + 4, + 0, + 8, + 11, + 9, + 5, + 11, + 5, + 19, + 11, + 19, + 7, + 19, + 5, + 14, + 19, + 14, + 4, + 19, + 4, + 17, + 1, + 12, + 14, + 1, + 14, + 5, + 1, + 5, + 9 + ]; + super(vertices, indices, radius, detail); + this.type = "DodecahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new DodecahedronGeometry(data2.radius, data2.detail); + } +} +var _v0 = /* @__PURE__ */ new Vector3; +var _v1$1 = /* @__PURE__ */ new Vector3; +var _normal = /* @__PURE__ */ new Vector3; +var _triangle = /* @__PURE__ */ new Triangle; + +class EdgesGeometry extends BufferGeometry { + constructor(geometry = null, thresholdAngle = 1) { + super(); + this.type = "EdgesGeometry"; + this.parameters = { + geometry, + thresholdAngle + }; + if (geometry !== null) { + const precisionPoints = 4; + const precision = Math.pow(10, precisionPoints); + const thresholdDot = Math.cos(DEG2RAD * thresholdAngle); + const indexAttr = geometry.getIndex(); + const positionAttr = geometry.getAttribute("position"); + const indexCount = indexAttr ? indexAttr.count : positionAttr.count; + const indexArr = [0, 0, 0]; + const vertKeys = ["a", "b", "c"]; + const hashes = new Array(3); + const edgeData = {}; + const vertices = []; + for (let i = 0;i < indexCount; i += 3) { + if (indexAttr) { + indexArr[0] = indexAttr.getX(i); + indexArr[1] = indexAttr.getX(i + 1); + indexArr[2] = indexAttr.getX(i + 2); + } else { + indexArr[0] = i; + indexArr[1] = i + 1; + indexArr[2] = i + 2; + } + const { a, b, c } = _triangle; + a.fromBufferAttribute(positionAttr, indexArr[0]); + b.fromBufferAttribute(positionAttr, indexArr[1]); + c.fromBufferAttribute(positionAttr, indexArr[2]); + _triangle.getNormal(_normal); + hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`; + hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`; + hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; + if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) { + continue; + } + for (let j = 0;j < 3; j++) { + const jNext = (j + 1) % 3; + const vecHash0 = hashes[j]; + const vecHash1 = hashes[jNext]; + const v0 = _triangle[vertKeys[j]]; + const v1 = _triangle[vertKeys[jNext]]; + const hash = `${vecHash0}_${vecHash1}`; + const reverseHash = `${vecHash1}_${vecHash0}`; + if (reverseHash in edgeData && edgeData[reverseHash]) { + if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) { + vertices.push(v0.x, v0.y, v0.z); + vertices.push(v1.x, v1.y, v1.z); + } + edgeData[reverseHash] = null; + } else if (!(hash in edgeData)) { + edgeData[hash] = { + index0: indexArr[j], + index1: indexArr[jNext], + normal: _normal.clone() + }; + } + } + } + for (const key2 in edgeData) { + if (edgeData[key2]) { + const { index0, index1 } = edgeData[key2]; + _v0.fromBufferAttribute(positionAttr, index0); + _v1$1.fromBufferAttribute(positionAttr, index1); + vertices.push(_v0.x, _v0.y, _v0.z); + vertices.push(_v1$1.x, _v1$1.y, _v1$1.z); + } + } + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } +} + +class Shape extends Path { + constructor(points) { + super(points); + this.uuid = generateUUID(); + this.type = "Shape"; + this.holes = []; + } + getPointsHoles(divisions) { + const holesPts = []; + for (let i = 0, l = this.holes.length;i < l; i++) { + holesPts[i] = this.holes[i].getPoints(divisions); + } + return holesPts; + } + extractPoints(divisions) { + return { + shape: this.getPoints(divisions), + holes: this.getPointsHoles(divisions) + }; + } + copy(source) { + super.copy(source); + this.holes = []; + for (let i = 0, l = source.holes.length;i < l; i++) { + const hole = source.holes[i]; + this.holes.push(hole.clone()); + } + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.uuid = this.uuid; + data2.holes = []; + for (let i = 0, l = this.holes.length;i < l; i++) { + const hole = this.holes[i]; + data2.holes.push(hole.toJSON()); + } + return data2; + } + fromJSON(json) { + super.fromJSON(json); + this.uuid = json.uuid; + this.holes = []; + for (let i = 0, l = json.holes.length;i < l; i++) { + const hole = json.holes[i]; + this.holes.push(new Path().fromJSON(hole)); + } + return this; + } +} +var Earcut = { + triangulate: function(data2, holeIndices, dim = 2) { + const hasHoles = holeIndices && holeIndices.length; + const outerLen = hasHoles ? holeIndices[0] * dim : data2.length; + let outerNode = linkedList(data2, 0, outerLen, dim, true); + const triangles = []; + if (!outerNode || outerNode.next === outerNode.prev) + return triangles; + let minX, minY, maxX, maxY, x, y, invSize; + if (hasHoles) + outerNode = eliminateHoles(data2, holeIndices, outerNode, dim); + if (data2.length > 80 * dim) { + minX = maxX = data2[0]; + minY = maxY = data2[1]; + for (let i = dim;i < outerLen; i += dim) { + x = data2[i]; + y = data2[i + 1]; + if (x < minX) + minX = x; + if (y < minY) + minY = y; + if (x > maxX) + maxX = x; + if (y > maxY) + maxY = y; + } + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + return triangles; + } +}; +function linkedList(data2, start, end, dim, clockwise) { + let i, last2; + if (clockwise === signedArea(data2, start, end, dim) > 0) { + for (i = start;i < end; i += dim) + last2 = insertNode(i, data2[i], data2[i + 1], last2); + } else { + for (i = end - dim;i >= start; i -= dim) + last2 = insertNode(i, data2[i], data2[i + 1], last2); + } + if (last2 && equals(last2, last2.next)) { + removeNode(last2); + last2 = last2.next; + } + return last2; +} +function filterPoints(start, end) { + if (!start) + return start; + if (!end) + end = start; + let p = start, again; + do { + again = false; + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) + break; + again = true; + } else { + p = p.next; + } + } while (again || p !== end); + return end; +} +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) + return; + if (!pass && invSize) + indexCurve(ear, minX, minY, invSize); + let stop = ear, prev, next; + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + triangles.push(prev.i / dim | 0); + triangles.push(ear.i / dim | 0); + triangles.push(next.i / dim | 0); + removeNode(ear); + ear = next.next; + stop = next.next; + continue; + } + ear = next; + if (ear === stop) { + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + break; + } + } +} +function isEar(ear) { + const a = ear.prev, b = ear, c = ear.next; + if (area(a, b, c) >= 0) + return false; + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + let p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) + return false; + p = p.next; + } + return true; +} +function isEarHashed(ear, minX, minY, invSize) { + const a = ear.prev, b = ear, c = ear.next; + if (area(a, b, c) >= 0) + return false; + const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + const minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize); + let { prevZ: p, nextZ: n } = ear; + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) + return false; + p = p.prevZ; + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) + return false; + n = n.nextZ; + } + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) + return false; + p = p.prevZ; + } + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) + return false; + n = n.nextZ; + } + return true; +} +function cureLocalIntersections(start, triangles, dim) { + let p = start; + do { + const a = p.prev, b = p.next.next; + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + triangles.push(a.i / dim | 0); + triangles.push(p.i / dim | 0); + triangles.push(b.i / dim | 0); + removeNode(p); + removeNode(p.next); + p = start = b; + } + p = p.next; + } while (p !== start); + return filterPoints(p); +} +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + let a = start; + do { + let b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + let c = splitPolygon(a, b); + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} +function eliminateHoles(data2, holeIndices, outerNode, dim) { + const queue = []; + let i, len, start, end, list; + for (i = 0, len = holeIndices.length;i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data2.length; + list = linkedList(data2, start, end, dim, false); + if (list === list.next) + list.steiner = true; + queue.push(getLeftmost(list)); + } + queue.sort(compareX); + for (i = 0;i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + return outerNode; +} +function compareX(a, b) { + return a.x - b.x; +} +function eliminateHole(hole, outerNode) { + const bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + const bridgeReverse = splitPolygon(bridge, hole); + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); +} +function findHoleBridge(hole, outerNode) { + let p = outerNode, qx = -Infinity, m; + const { x: hx, y: hy } = hole; + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) + return m; + } + } + p = p.next; + } while (p !== outerNode); + if (!m) + return null; + const stop = m, mx = m.x, my = m.y; + let tanMin = Infinity, tan; + p = m; + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + tan = Math.abs(hy - p.y) / (hx - p.x); + if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) { + m = p; + tanMin = tan; + } + } + p = p.next; + } while (p !== stop); + return m; +} +function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; +} +function indexCurve(start, minX, minY, invSize) { + let p = start; + do { + if (p.z === 0) + p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + p.prevZ.nextZ = null; + p.prevZ = null; + sortLinked(p); +} +function sortLinked(list) { + let i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; + do { + p = list; + list = null; + tail = null; + numMerges = 0; + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0;i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) + break; + } + qSize = inSize; + while (pSize > 0 || qSize > 0 && q) { + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + if (tail) + tail.nextZ = e; + else + list = e; + e.prevZ = tail; + tail = e; + } + p = q; + } + tail.nextZ = null; + inSize *= 2; + } while (numMerges > 1); + return list; +} +function zOrder(x, y, minX, minY, invSize) { + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + x = (x | x << 8) & 16711935; + x = (x | x << 4) & 252645135; + x = (x | x << 2) & 858993459; + x = (x | x << 1) & 1431655765; + y = (y | y << 8) & 16711935; + y = (y | y << 4) & 252645135; + y = (y | y << 2) & 858993459; + y = (y | y << 1) & 1431655765; + return x | y << 1; +} +function getLeftmost(start) { + let p = start, leftmost = start; + do { + if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) + leftmost = p; + p = p.next; + } while (p !== start); + return leftmost; +} +function pointInTriangle(ax, ay, bx, by, cx, cy, px2, py2) { + return (cx - px2) * (ay - py2) >= (ax - px2) * (cy - py2) && (ax - px2) * (by - py2) >= (bx - px2) * (ay - py2) && (bx - px2) * (cy - py2) >= (cx - px2) * (by - py2); +} +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && (area(a.prev, a, b.prev) || area(a, b.prev, b)) || equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); +} +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} +function intersects(p1, q1, p2, q2) { + const o1 = sign(area(p1, q1, p2)); + const o2 = sign(area(p1, q1, q2)); + const o3 = sign(area(p2, q2, p1)); + const o4 = sign(area(p2, q2, q1)); + if (o1 !== o2 && o3 !== o4) + return true; + if (o1 === 0 && onSegment(p1, p2, q1)) + return true; + if (o2 === 0 && onSegment(p1, q2, q1)) + return true; + if (o3 === 0 && onSegment(p2, p1, q2)) + return true; + if (o4 === 0 && onSegment(p2, q1, q2)) + return true; + return false; +} +function onSegment(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); +} +function sign(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; +} +function intersectsPolygon(a, b) { + let p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) + return true; + p = p.next; + } while (p !== a); + return false; +} +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} +function middleInside(a, b) { + let p = a, inside = false; + const px2 = (a.x + b.x) / 2, py2 = (a.y + b.y) / 2; + do { + if (p.y > py2 !== p.next.y > py2 && p.next.y !== p.y && px2 < (p.next.x - p.x) * (py2 - p.y) / (p.next.y - p.y) + p.x) + inside = !inside; + p = p.next; + } while (p !== a); + return inside; +} +function splitPolygon(a, b) { + const a2 = new Node2(a.i, a.x, a.y), b2 = new Node2(b.i, b.x, b.y), an = a.next, bp = b.prev; + a.next = b; + b.prev = a; + a2.next = an; + an.prev = a2; + b2.next = a2; + a2.prev = b2; + bp.next = b2; + b2.prev = bp; + return b2; +} +function insertNode(i, x, y, last2) { + const p = new Node2(i, x, y); + if (!last2) { + p.prev = p; + p.next = p; + } else { + p.next = last2.next; + p.prev = last2; + last2.next.prev = p; + last2.next = p; + } + return p; +} +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + if (p.prevZ) + p.prevZ.nextZ = p.nextZ; + if (p.nextZ) + p.nextZ.prevZ = p.prevZ; +} +function Node2(i, x, y) { + this.i = i; + this.x = x; + this.y = y; + this.prev = null; + this.next = null; + this.z = 0; + this.prevZ = null; + this.nextZ = null; + this.steiner = false; +} +function signedArea(data2, start, end, dim) { + let sum2 = 0; + for (let i = start, j = end - dim;i < end; i += dim) { + sum2 += (data2[j] - data2[i]) * (data2[i + 1] + data2[j + 1]); + j = i; + } + return sum2; +} + +class ShapeUtils { + static area(contour) { + const n = contour.length; + let a = 0; + for (let p = n - 1, q = 0;q < n; p = q++) { + a += contour[p].x * contour[q].y - contour[q].x * contour[p].y; + } + return a * 0.5; + } + static isClockWise(pts) { + return ShapeUtils.area(pts) < 0; + } + static triangulateShape(contour, holes) { + const vertices = []; + const holeIndices = []; + const faces = []; + removeDupEndPts(contour); + addContour(vertices, contour); + let holeIndex = contour.length; + holes.forEach(removeDupEndPts); + for (let i = 0;i < holes.length; i++) { + holeIndices.push(holeIndex); + holeIndex += holes[i].length; + addContour(vertices, holes[i]); + } + const triangles = Earcut.triangulate(vertices, holeIndices); + for (let i = 0;i < triangles.length; i += 3) { + faces.push(triangles.slice(i, i + 3)); + } + return faces; + } +} +function removeDupEndPts(points) { + const l = points.length; + if (l > 2 && points[l - 1].equals(points[0])) { + points.pop(); + } +} +function addContour(vertices, contour) { + for (let i = 0;i < contour.length; i++) { + vertices.push(contour[i].x); + vertices.push(contour[i].y); + } +} + +class ExtrudeGeometry extends BufferGeometry { + constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) { + super(); + this.type = "ExtrudeGeometry"; + this.parameters = { + shapes, + options + }; + shapes = Array.isArray(shapes) ? shapes : [shapes]; + const scope = this; + const verticesArray = []; + const uvArray = []; + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + addShape(shape); + } + this.setAttribute("position", new Float32BufferAttribute(verticesArray, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvArray, 2)); + this.computeVertexNormals(); + function addShape(shape) { + const placeholder = []; + const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12; + const steps = options.steps !== undefined ? options.steps : 1; + const depth = options.depth !== undefined ? options.depth : 1; + let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; + let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2; + let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1; + let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; + let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; + const extrudePath = options.extrudePath; + const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; + let extrudePts, extrudeByPath = false; + let splineTube, binormal, normal, position2; + if (extrudePath) { + extrudePts = extrudePath.getSpacedPoints(steps); + extrudeByPath = true; + bevelEnabled = false; + splineTube = extrudePath.computeFrenetFrames(steps, false); + binormal = new Vector3; + normal = new Vector3; + position2 = new Vector3; + } + if (!bevelEnabled) { + bevelSegments = 0; + bevelThickness = 0; + bevelSize = 0; + bevelOffset = 0; + } + const shapePoints = shape.extractPoints(curveSegments); + let vertices = shapePoints.shape; + const holes = shapePoints.holes; + const reverse = !ShapeUtils.isClockWise(vertices); + if (reverse) { + vertices = vertices.reverse(); + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + if (ShapeUtils.isClockWise(ahole)) { + holes[h] = ahole.reverse(); + } + } + } + const faces = ShapeUtils.triangulateShape(vertices, holes); + const contour = vertices; + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + vertices = vertices.concat(ahole); + } + function scalePt2(pt, vec, size) { + if (!vec) + console.error("THREE.ExtrudeGeometry: vec does not exist"); + return pt.clone().addScaledVector(vec, size); + } + const vlen = vertices.length, flen = faces.length; + function getBevelVec(inPt, inPrev, inNext) { + let v_trans_x, v_trans_y, shrink_by; + const v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; + const v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; + const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; + const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x; + if (Math.abs(collinear0) > Number.EPSILON) { + const v_prev_len = Math.sqrt(v_prev_lensq); + const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); + const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len; + const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len; + const ptNextShift_x = inNext.x - v_next_y / v_next_len; + const ptNextShift_y = inNext.y + v_next_x / v_next_len; + const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); + v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x; + v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; + const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y; + if (v_trans_lensq <= 2) { + return new Vector2(v_trans_x, v_trans_y); + } else { + shrink_by = Math.sqrt(v_trans_lensq / 2); + } + } else { + let direction_eq = false; + if (v_prev_x > Number.EPSILON) { + if (v_next_x > Number.EPSILON) { + direction_eq = true; + } + } else { + if (v_prev_x < -Number.EPSILON) { + if (v_next_x < -Number.EPSILON) { + direction_eq = true; + } + } else { + if (Math.sign(v_prev_y) === Math.sign(v_next_y)) { + direction_eq = true; + } + } + } + if (direction_eq) { + v_trans_x = -v_prev_y; + v_trans_y = v_prev_x; + shrink_by = Math.sqrt(v_prev_lensq); + } else { + v_trans_x = v_prev_x; + v_trans_y = v_prev_y; + shrink_by = Math.sqrt(v_prev_lensq / 2); + } + } + return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by); + } + const contourMovements = []; + for (let i = 0, il = contour.length, j = il - 1, k = i + 1;i < il; i++, j++, k++) { + if (j === il) + j = 0; + if (k === il) + k = 0; + contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]); + } + const holesMovements = []; + let oneHoleMovements, verticesMovements = contourMovements.concat(); + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = []; + for (let i = 0, il = ahole.length, j = il - 1, k = i + 1;i < il; i++, j++, k++) { + if (j === il) + j = 0; + if (k === il) + k = 0; + oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]); + } + holesMovements.push(oneHoleMovements); + verticesMovements = verticesMovements.concat(oneHoleMovements); + } + for (let b = 0;b < bevelSegments; b++) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos(t * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length;i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, -z); + } + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length;i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + v(vert.x, vert.y, -z); + } + } + } + const bs = bevelSize + bevelOffset; + for (let i = 0;i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, 0); + } else { + normal.copy(splineTube.normals[0]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y); + position2.copy(extrudePts[0]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + for (let s = 1;s <= steps; s++) { + for (let i = 0;i < vlen; i++) { + const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; + if (!extrudeByPath) { + v(vert.x, vert.y, depth / steps * s); + } else { + normal.copy(splineTube.normals[s]).multiplyScalar(vert.x); + binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y); + position2.copy(extrudePts[s]).add(normal).add(binormal); + v(position2.x, position2.y, position2.z); + } + } + } + for (let b = bevelSegments - 1;b >= 0; b--) { + const t = b / bevelSegments; + const z = bevelThickness * Math.cos(t * Math.PI / 2); + const bs2 = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; + for (let i = 0, il = contour.length;i < il; i++) { + const vert = scalePt2(contour[i], contourMovements[i], bs2); + v(vert.x, vert.y, depth + z); + } + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + oneHoleMovements = holesMovements[h]; + for (let i = 0, il = ahole.length;i < il; i++) { + const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); + if (!extrudeByPath) { + v(vert.x, vert.y, depth + z); + } else { + v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z); + } + } + } + } + buildLidFaces(); + buildSideFaces(); + function buildLidFaces() { + const start = verticesArray.length / 3; + if (bevelEnabled) { + let layer = 0; + let offset = vlen * layer; + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[2] + offset, face[1] + offset, face[0] + offset); + } + layer = steps + bevelSegments * 2; + offset = vlen * layer; + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[0] + offset, face[1] + offset, face[2] + offset); + } + } else { + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[2], face[1], face[0]); + } + for (let i = 0;i < flen; i++) { + const face = faces[i]; + f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps); + } + } + scope.addGroup(start, verticesArray.length / 3 - start, 0); + } + function buildSideFaces() { + const start = verticesArray.length / 3; + let layeroffset = 0; + sidewalls(contour, layeroffset); + layeroffset += contour.length; + for (let h = 0, hl = holes.length;h < hl; h++) { + const ahole = holes[h]; + sidewalls(ahole, layeroffset); + layeroffset += ahole.length; + } + scope.addGroup(start, verticesArray.length / 3 - start, 1); + } + function sidewalls(contour2, layeroffset) { + let i = contour2.length; + while (--i >= 0) { + const j = i; + let k = i - 1; + if (k < 0) + k = contour2.length - 1; + for (let s = 0, sl = steps + bevelSegments * 2;s < sl; s++) { + const slen1 = vlen * s; + const slen2 = vlen * (s + 1); + const a = layeroffset + j + slen1, b = layeroffset + k + slen1, c = layeroffset + k + slen2, d = layeroffset + j + slen2; + f4(a, b, c, d); + } + } + } + function v(x, y, z) { + placeholder.push(x); + placeholder.push(y); + placeholder.push(z); + } + function f3(a, b, c) { + addVertex(a); + addVertex(b); + addVertex(c); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[2]); + } + function f4(a, b, c, d) { + addVertex(a); + addVertex(b); + addVertex(d); + addVertex(b); + addVertex(c); + addVertex(d); + const nextIndex = verticesArray.length / 3; + const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1); + addUV(uvs[0]); + addUV(uvs[1]); + addUV(uvs[3]); + addUV(uvs[1]); + addUV(uvs[2]); + addUV(uvs[3]); + } + function addVertex(index2) { + verticesArray.push(placeholder[index2 * 3 + 0]); + verticesArray.push(placeholder[index2 * 3 + 1]); + verticesArray.push(placeholder[index2 * 3 + 2]); + } + function addUV(vector2) { + uvArray.push(vector2.x); + uvArray.push(vector2.y); + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + const shapes = this.parameters.shapes; + const options = this.parameters.options; + return toJSON$1(shapes, options, data2); + } + static fromJSON(data2, shapes) { + const geometryShapes = []; + for (let j = 0, jl = data2.shapes.length;j < jl; j++) { + const shape = shapes[data2.shapes[j]]; + geometryShapes.push(shape); + } + const extrudePath = data2.options.extrudePath; + if (extrudePath !== undefined) { + data2.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath); + } + return new ExtrudeGeometry(geometryShapes, data2.options); + } +} +var WorldUVGenerator = { + generateTopUV: function(geometry, vertices, indexA, indexB, indexC) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + return [ + new Vector2(a_x, a_y), + new Vector2(b_x, b_y), + new Vector2(c_x, c_y) + ]; + }, + generateSideWallUV: function(geometry, vertices, indexA, indexB, indexC, indexD) { + const a_x = vertices[indexA * 3]; + const a_y = vertices[indexA * 3 + 1]; + const a_z = vertices[indexA * 3 + 2]; + const b_x = vertices[indexB * 3]; + const b_y = vertices[indexB * 3 + 1]; + const b_z = vertices[indexB * 3 + 2]; + const c_x = vertices[indexC * 3]; + const c_y = vertices[indexC * 3 + 1]; + const c_z = vertices[indexC * 3 + 2]; + const d_x = vertices[indexD * 3]; + const d_y = vertices[indexD * 3 + 1]; + const d_z = vertices[indexD * 3 + 2]; + if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) { + return [ + new Vector2(a_x, 1 - a_z), + new Vector2(b_x, 1 - b_z), + new Vector2(c_x, 1 - c_z), + new Vector2(d_x, 1 - d_z) + ]; + } else { + return [ + new Vector2(a_y, 1 - a_z), + new Vector2(b_y, 1 - b_z), + new Vector2(c_y, 1 - c_z), + new Vector2(d_y, 1 - d_z) + ]; + } + } +}; +function toJSON$1(shapes, options, data2) { + data2.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + data2.shapes.push(shape.uuid); + } + } else { + data2.shapes.push(shapes.uuid); + } + data2.options = Object.assign({}, options); + if (options.extrudePath !== undefined) + data2.options.extrudePath = options.extrudePath.toJSON(); + return data2; +} + +class IcosahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const t = (1 + Math.sqrt(5)) / 2; + const vertices = [ + -1, + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + 0, + 0, + -1, + t, + 0, + 1, + t, + 0, + -1, + -t, + 0, + 1, + -t, + t, + 0, + -1, + t, + 0, + 1, + -t, + 0, + -1, + -t, + 0, + 1 + ]; + const indices = [ + 0, + 11, + 5, + 0, + 5, + 1, + 0, + 1, + 7, + 0, + 7, + 10, + 0, + 10, + 11, + 1, + 5, + 9, + 5, + 11, + 4, + 11, + 10, + 2, + 10, + 7, + 6, + 7, + 1, + 8, + 3, + 9, + 4, + 3, + 4, + 2, + 3, + 2, + 6, + 3, + 6, + 8, + 3, + 8, + 9, + 4, + 9, + 5, + 2, + 4, + 11, + 6, + 2, + 10, + 8, + 6, + 7, + 9, + 8, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "IcosahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new IcosahedronGeometry(data2.radius, data2.detail); + } +} + +class OctahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1, + 0, + 0, + 0, + 1, + 0, + 0, + -1 + ]; + const indices = [ + 0, + 2, + 4, + 0, + 4, + 3, + 0, + 3, + 5, + 0, + 5, + 2, + 1, + 2, + 5, + 1, + 5, + 3, + 1, + 3, + 4, + 1, + 4, + 2 + ]; + super(vertices, indices, radius, detail); + this.type = "OctahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new OctahedronGeometry(data2.radius, data2.detail); + } +} + +class PlaneGeometry extends BufferGeometry { + constructor(width2 = 1, height2 = 1, widthSegments = 1, heightSegments = 1) { + super(); + this.type = "PlaneGeometry"; + this.parameters = { + width: width2, + height: height2, + widthSegments, + heightSegments + }; + const width_half = width2 / 2; + const height_half = height2 / 2; + const gridX = Math.floor(widthSegments); + const gridY = Math.floor(heightSegments); + const gridX1 = gridX + 1; + const gridY1 = gridY + 1; + const segment_width = width2 / gridX; + const segment_height = height2 / gridY; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0;iy < gridY1; iy++) { + const y = iy * segment_height - height_half; + for (let ix = 0;ix < gridX1; ix++) { + const x = ix * segment_width - width_half; + vertices.push(x, -y, 0); + normals.push(0, 0, 1); + uvs.push(ix / gridX); + uvs.push(1 - iy / gridY); + } + } + for (let iy = 0;iy < gridY; iy++) { + for (let ix = 0;ix < gridX; ix++) { + const a = ix + gridX1 * iy; + const b = ix + gridX1 * (iy + 1); + const c = ix + 1 + gridX1 * (iy + 1); + const d = ix + 1 + gridX1 * iy; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new PlaneGeometry(data2.width, data2.height, data2.widthSegments, data2.heightSegments); + } +} + +class RingGeometry extends BufferGeometry { + constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) { + super(); + this.type = "RingGeometry"; + this.parameters = { + innerRadius, + outerRadius, + thetaSegments, + phiSegments, + thetaStart, + thetaLength + }; + thetaSegments = Math.max(3, thetaSegments); + phiSegments = Math.max(1, phiSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let radius = innerRadius; + const radiusStep = (outerRadius - innerRadius) / phiSegments; + const vertex = new Vector3; + const uv = new Vector2; + for (let j = 0;j <= phiSegments; j++) { + for (let i = 0;i <= thetaSegments; i++) { + const segment = thetaStart + i / thetaSegments * thetaLength; + vertex.x = radius * Math.cos(segment); + vertex.y = radius * Math.sin(segment); + vertices.push(vertex.x, vertex.y, vertex.z); + normals.push(0, 0, 1); + uv.x = (vertex.x / outerRadius + 1) / 2; + uv.y = (vertex.y / outerRadius + 1) / 2; + uvs.push(uv.x, uv.y); + } + radius += radiusStep; + } + for (let j = 0;j < phiSegments; j++) { + const thetaSegmentLevel = j * (thetaSegments + 1); + for (let i = 0;i < thetaSegments; i++) { + const segment = i + thetaSegmentLevel; + const a = segment; + const b = segment + thetaSegments + 1; + const c = segment + thetaSegments + 2; + const d = segment + 1; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new RingGeometry(data2.innerRadius, data2.outerRadius, data2.thetaSegments, data2.phiSegments, data2.thetaStart, data2.thetaLength); + } +} + +class ShapeGeometry extends BufferGeometry { + constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) { + super(); + this.type = "ShapeGeometry"; + this.parameters = { + shapes, + curveSegments + }; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + let groupStart = 0; + let groupCount = 0; + if (Array.isArray(shapes) === false) { + addShape(shapes); + } else { + for (let i = 0;i < shapes.length; i++) { + addShape(shapes[i]); + this.addGroup(groupStart, groupCount, i); + groupStart += groupCount; + groupCount = 0; + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function addShape(shape) { + const indexOffset = vertices.length / 3; + const points = shape.extractPoints(curveSegments); + let shapeVertices = points.shape; + const shapeHoles = points.holes; + if (ShapeUtils.isClockWise(shapeVertices) === false) { + shapeVertices = shapeVertices.reverse(); + } + for (let i = 0, l = shapeHoles.length;i < l; i++) { + const shapeHole = shapeHoles[i]; + if (ShapeUtils.isClockWise(shapeHole) === true) { + shapeHoles[i] = shapeHole.reverse(); + } + } + const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); + for (let i = 0, l = shapeHoles.length;i < l; i++) { + const shapeHole = shapeHoles[i]; + shapeVertices = shapeVertices.concat(shapeHole); + } + for (let i = 0, l = shapeVertices.length;i < l; i++) { + const vertex = shapeVertices[i]; + vertices.push(vertex.x, vertex.y, 0); + normals.push(0, 0, 1); + uvs.push(vertex.x, vertex.y); + } + for (let i = 0, l = faces.length;i < l; i++) { + const face = faces[i]; + const a = face[0] + indexOffset; + const b = face[1] + indexOffset; + const c = face[2] + indexOffset; + indices.push(a, b, c); + groupCount += 3; + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + const shapes = this.parameters.shapes; + return toJSON(shapes, data2); + } + static fromJSON(data2, shapes) { + const geometryShapes = []; + for (let j = 0, jl = data2.shapes.length;j < jl; j++) { + const shape = shapes[data2.shapes[j]]; + geometryShapes.push(shape); + } + return new ShapeGeometry(geometryShapes, data2.curveSegments); + } +} +function toJSON(shapes, data2) { + data2.shapes = []; + if (Array.isArray(shapes)) { + for (let i = 0, l = shapes.length;i < l; i++) { + const shape = shapes[i]; + data2.shapes.push(shape.uuid); + } + } else { + data2.shapes.push(shapes.uuid); + } + return data2; +} + +class SphereGeometry extends BufferGeometry { + constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) { + super(); + this.type = "SphereGeometry"; + this.parameters = { + radius, + widthSegments, + heightSegments, + phiStart, + phiLength, + thetaStart, + thetaLength + }; + widthSegments = Math.max(3, Math.floor(widthSegments)); + heightSegments = Math.max(2, Math.floor(heightSegments)); + const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI); + let index2 = 0; + const grid = []; + const vertex = new Vector3; + const normal = new Vector3; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + for (let iy = 0;iy <= heightSegments; iy++) { + const verticesRow = []; + const v = iy / heightSegments; + let uOffset = 0; + if (iy === 0 && thetaStart === 0) { + uOffset = 0.5 / widthSegments; + } else if (iy === heightSegments && thetaEnd === Math.PI) { + uOffset = -0.5 / widthSegments; + } + for (let ix = 0;ix <= widthSegments; ix++) { + const u = ix / widthSegments; + vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertex.y = radius * Math.cos(thetaStart + v * thetaLength); + vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); + vertices.push(vertex.x, vertex.y, vertex.z); + normal.copy(vertex).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u + uOffset, 1 - v); + verticesRow.push(index2++); + } + grid.push(verticesRow); + } + for (let iy = 0;iy < heightSegments; iy++) { + for (let ix = 0;ix < widthSegments; ix++) { + const a = grid[iy][ix + 1]; + const b = grid[iy][ix]; + const c = grid[iy + 1][ix]; + const d = grid[iy + 1][ix + 1]; + if (iy !== 0 || thetaStart > 0) + indices.push(a, b, d); + if (iy !== heightSegments - 1 || thetaEnd < Math.PI) + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new SphereGeometry(data2.radius, data2.widthSegments, data2.heightSegments, data2.phiStart, data2.phiLength, data2.thetaStart, data2.thetaLength); + } +} + +class TetrahedronGeometry extends PolyhedronGeometry { + constructor(radius = 1, detail = 0) { + const vertices = [ + 1, + 1, + 1, + -1, + -1, + 1, + -1, + 1, + -1, + 1, + -1, + -1 + ]; + const indices = [ + 2, + 1, + 0, + 0, + 3, + 2, + 1, + 3, + 0, + 2, + 3, + 1 + ]; + super(vertices, indices, radius, detail); + this.type = "TetrahedronGeometry"; + this.parameters = { + radius, + detail + }; + } + static fromJSON(data2) { + return new TetrahedronGeometry(data2.radius, data2.detail); + } +} + +class TorusGeometry extends BufferGeometry { + constructor(radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2) { + super(); + this.type = "TorusGeometry"; + this.parameters = { + radius, + tube, + radialSegments, + tubularSegments, + arc + }; + radialSegments = Math.floor(radialSegments); + tubularSegments = Math.floor(tubularSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const center = new Vector3; + const vertex = new Vector3; + const normal = new Vector3; + for (let j = 0;j <= radialSegments; j++) { + for (let i = 0;i <= tubularSegments; i++) { + const u = i / tubularSegments * arc; + const v = j / radialSegments * Math.PI * 2; + vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u); + vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u); + vertex.z = tube * Math.sin(v); + vertices.push(vertex.x, vertex.y, vertex.z); + center.x = radius * Math.cos(u); + center.y = radius * Math.sin(u); + normal.subVectors(vertex, center).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j / radialSegments); + } + } + for (let j = 1;j <= radialSegments; j++) { + for (let i = 1;i <= tubularSegments; i++) { + const a = (tubularSegments + 1) * j + i - 1; + const b = (tubularSegments + 1) * (j - 1) + i - 1; + const c = (tubularSegments + 1) * (j - 1) + i; + const d = (tubularSegments + 1) * j + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new TorusGeometry(data2.radius, data2.tube, data2.radialSegments, data2.tubularSegments, data2.arc); + } +} + +class TorusKnotGeometry extends BufferGeometry { + constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) { + super(); + this.type = "TorusKnotGeometry"; + this.parameters = { + radius, + tube, + tubularSegments, + radialSegments, + p, + q + }; + tubularSegments = Math.floor(tubularSegments); + radialSegments = Math.floor(radialSegments); + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const vertex = new Vector3; + const normal = new Vector3; + const P1 = new Vector3; + const P2 = new Vector3; + const B = new Vector3; + const T = new Vector3; + const N = new Vector3; + for (let i = 0;i <= tubularSegments; ++i) { + const u = i / tubularSegments * p * Math.PI * 2; + calculatePositionOnCurve(u, p, q, radius, P1); + calculatePositionOnCurve(u + 0.01, p, q, radius, P2); + T.subVectors(P2, P1); + N.addVectors(P2, P1); + B.crossVectors(T, N); + N.crossVectors(B, T); + B.normalize(); + N.normalize(); + for (let j = 0;j <= radialSegments; ++j) { + const v = j / radialSegments * Math.PI * 2; + const cx = -tube * Math.cos(v); + const cy = tube * Math.sin(v); + vertex.x = P1.x + (cx * N.x + cy * B.x); + vertex.y = P1.y + (cx * N.y + cy * B.y); + vertex.z = P1.z + (cx * N.z + cy * B.z); + vertices.push(vertex.x, vertex.y, vertex.z); + normal.subVectors(vertex, P1).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(i / tubularSegments); + uvs.push(j / radialSegments); + } + } + for (let j = 1;j <= tubularSegments; j++) { + for (let i = 1;i <= radialSegments; i++) { + const a = (radialSegments + 1) * (j - 1) + (i - 1); + const b = (radialSegments + 1) * j + (i - 1); + const c = (radialSegments + 1) * j + i; + const d = (radialSegments + 1) * (j - 1) + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function calculatePositionOnCurve(u, p2, q2, radius2, position2) { + const cu = Math.cos(u); + const su = Math.sin(u); + const quOverP = q2 / p2 * u; + const cs = Math.cos(quOverP); + position2.x = radius2 * (2 + cs) * 0.5 * cu; + position2.y = radius2 * (2 + cs) * su * 0.5; + position2.z = radius2 * Math.sin(quOverP) * 0.5; + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + static fromJSON(data2) { + return new TorusKnotGeometry(data2.radius, data2.tube, data2.tubularSegments, data2.radialSegments, data2.p, data2.q); + } +} + +class TubeGeometry extends BufferGeometry { + constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) { + super(); + this.type = "TubeGeometry"; + this.parameters = { + path, + tubularSegments, + radius, + radialSegments, + closed + }; + const frames2 = path.computeFrenetFrames(tubularSegments, closed); + this.tangents = frames2.tangents; + this.normals = frames2.normals; + this.binormals = frames2.binormals; + const vertex = new Vector3; + const normal = new Vector3; + const uv = new Vector2; + let P = new Vector3; + const vertices = []; + const normals = []; + const uvs = []; + const indices = []; + generateBufferData(); + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + function generateBufferData() { + for (let i = 0;i < tubularSegments; i++) { + generateSegment(i); + } + generateSegment(closed === false ? tubularSegments : 0); + generateUVs(); + generateIndices(); + } + function generateSegment(i) { + P = path.getPointAt(i / tubularSegments, P); + const N = frames2.normals[i]; + const B = frames2.binormals[i]; + for (let j = 0;j <= radialSegments; j++) { + const v = j / radialSegments * Math.PI * 2; + const sin = Math.sin(v); + const cos = -Math.cos(v); + normal.x = cos * N.x + sin * B.x; + normal.y = cos * N.y + sin * B.y; + normal.z = cos * N.z + sin * B.z; + normal.normalize(); + normals.push(normal.x, normal.y, normal.z); + vertex.x = P.x + radius * normal.x; + vertex.y = P.y + radius * normal.y; + vertex.z = P.z + radius * normal.z; + vertices.push(vertex.x, vertex.y, vertex.z); + } + } + function generateIndices() { + for (let j = 1;j <= tubularSegments; j++) { + for (let i = 1;i <= radialSegments; i++) { + const a = (radialSegments + 1) * (j - 1) + (i - 1); + const b = (radialSegments + 1) * j + (i - 1); + const c = (radialSegments + 1) * j + i; + const d = (radialSegments + 1) * (j - 1) + i; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + } + function generateUVs() { + for (let i = 0;i <= tubularSegments; i++) { + for (let j = 0;j <= radialSegments; j++) { + uv.x = i / tubularSegments; + uv.y = j / radialSegments; + uvs.push(uv.x, uv.y); + } + } + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.path = this.parameters.path.toJSON(); + return data2; + } + static fromJSON(data2) { + return new TubeGeometry(new Curves[data2.path.type]().fromJSON(data2.path), data2.tubularSegments, data2.radius, data2.radialSegments, data2.closed); + } +} + +class WireframeGeometry extends BufferGeometry { + constructor(geometry = null) { + super(); + this.type = "WireframeGeometry"; + this.parameters = { + geometry + }; + if (geometry !== null) { + const vertices = []; + const edges = new Set; + const start = new Vector3; + const end = new Vector3; + if (geometry.index !== null) { + const position2 = geometry.attributes.position; + const indices = geometry.index; + let groups = geometry.groups; + if (groups.length === 0) { + groups = [{ start: 0, count: indices.count, materialIndex: 0 }]; + } + for (let o = 0, ol = groups.length;o < ol; ++o) { + const group = groups[o]; + const groupStart = group.start; + const groupCount = group.count; + for (let i = groupStart, l = groupStart + groupCount;i < l; i += 3) { + for (let j = 0;j < 3; j++) { + const index1 = indices.getX(i + j); + const index2 = indices.getX(i + (j + 1) % 3); + start.fromBufferAttribute(position2, index1); + end.fromBufferAttribute(position2, index2); + if (isUniqueEdge(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + } else { + const position2 = geometry.attributes.position; + for (let i = 0, l = position2.count / 3;i < l; i++) { + for (let j = 0;j < 3; j++) { + const index1 = 3 * i + j; + const index2 = 3 * i + (j + 1) % 3; + start.fromBufferAttribute(position2, index1); + end.fromBufferAttribute(position2, index2); + if (isUniqueEdge(start, end, edges) === true) { + vertices.push(start.x, start.y, start.z); + vertices.push(end.x, end.y, end.z); + } + } + } + } + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + } + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } +} +function isUniqueEdge(start, end, edges) { + const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; + const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; + if (edges.has(hash1) === true || edges.has(hash2) === true) { + return false; + } else { + edges.add(hash1); + edges.add(hash2); + return true; + } +} +var Geometries = /* @__PURE__ */ Object.freeze({ + __proto__: null, + BoxGeometry, + CapsuleGeometry, + CircleGeometry, + ConeGeometry, + CylinderGeometry, + DodecahedronGeometry, + EdgesGeometry, + ExtrudeGeometry, + IcosahedronGeometry, + LatheGeometry, + OctahedronGeometry, + PlaneGeometry, + PolyhedronGeometry, + RingGeometry, + ShapeGeometry, + SphereGeometry, + TetrahedronGeometry, + TorusGeometry, + TorusKnotGeometry, + TubeGeometry, + WireframeGeometry +}); + +class ShadowMaterial extends Material { + constructor(parameters) { + super(); + this.isShadowMaterial = true; + this.type = "ShadowMaterial"; + this.color = new Color(0); + this.transparent = true; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.fog = source.fog; + return this; + } +} + +class RawShaderMaterial extends ShaderMaterial { + constructor(parameters) { + super(parameters); + this.isRawShaderMaterial = true; + this.type = "RawShaderMaterial"; + } +} + +class MeshStandardMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshStandardMaterial = true; + this.type = "MeshStandardMaterial"; + this.defines = { STANDARD: "" }; + this.color = new Color(16777215); + this.roughness = 1; + this.metalness = 0; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.roughnessMap = null; + this.metalnessMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler; + this.envMapIntensity = 1; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { STANDARD: "" }; + this.color.copy(source.color); + this.roughness = source.roughness; + this.metalness = source.metalness; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.roughnessMap = source.roughnessMap; + this.metalnessMap = source.metalnessMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.envMapIntensity = source.envMapIntensity; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } +} + +class MeshPhysicalMaterial extends MeshStandardMaterial { + constructor(parameters) { + super(); + this.isMeshPhysicalMaterial = true; + this.defines = { + STANDARD: "", + PHYSICAL: "" + }; + this.type = "MeshPhysicalMaterial"; + this.anisotropyRotation = 0; + this.anisotropyMap = null; + this.clearcoatMap = null; + this.clearcoatRoughness = 0; + this.clearcoatRoughnessMap = null; + this.clearcoatNormalScale = new Vector2(1, 1); + this.clearcoatNormalMap = null; + this.ior = 1.5; + Object.defineProperty(this, "reflectivity", { + get: function() { + return clamp2(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1); + }, + set: function(reflectivity) { + this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity); + } + }); + this.iridescenceMap = null; + this.iridescenceIOR = 1.3; + this.iridescenceThicknessRange = [100, 400]; + this.iridescenceThicknessMap = null; + this.sheenColor = new Color(0); + this.sheenColorMap = null; + this.sheenRoughness = 1; + this.sheenRoughnessMap = null; + this.transmissionMap = null; + this.thickness = 0; + this.thicknessMap = null; + this.attenuationDistance = Infinity; + this.attenuationColor = new Color(1, 1, 1); + this.specularIntensity = 1; + this.specularIntensityMap = null; + this.specularColor = new Color(1, 1, 1); + this.specularColorMap = null; + this._anisotropy = 0; + this._clearcoat = 0; + this._dispersion = 0; + this._iridescence = 0; + this._sheen = 0; + this._transmission = 0; + this.setValues(parameters); + } + get anisotropy() { + return this._anisotropy; + } + set anisotropy(value2) { + if (this._anisotropy > 0 !== value2 > 0) { + this.version++; + } + this._anisotropy = value2; + } + get clearcoat() { + return this._clearcoat; + } + set clearcoat(value2) { + if (this._clearcoat > 0 !== value2 > 0) { + this.version++; + } + this._clearcoat = value2; + } + get iridescence() { + return this._iridescence; + } + set iridescence(value2) { + if (this._iridescence > 0 !== value2 > 0) { + this.version++; + } + this._iridescence = value2; + } + get dispersion() { + return this._dispersion; + } + set dispersion(value2) { + if (this._dispersion > 0 !== value2 > 0) { + this.version++; + } + this._dispersion = value2; + } + get sheen() { + return this._sheen; + } + set sheen(value2) { + if (this._sheen > 0 !== value2 > 0) { + this.version++; + } + this._sheen = value2; + } + get transmission() { + return this._transmission; + } + set transmission(value2) { + if (this._transmission > 0 !== value2 > 0) { + this.version++; + } + this._transmission = value2; + } + copy(source) { + super.copy(source); + this.defines = { + STANDARD: "", + PHYSICAL: "" + }; + this.anisotropy = source.anisotropy; + this.anisotropyRotation = source.anisotropyRotation; + this.anisotropyMap = source.anisotropyMap; + this.clearcoat = source.clearcoat; + this.clearcoatMap = source.clearcoatMap; + this.clearcoatRoughness = source.clearcoatRoughness; + this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; + this.clearcoatNormalMap = source.clearcoatNormalMap; + this.clearcoatNormalScale.copy(source.clearcoatNormalScale); + this.dispersion = source.dispersion; + this.ior = source.ior; + this.iridescence = source.iridescence; + this.iridescenceMap = source.iridescenceMap; + this.iridescenceIOR = source.iridescenceIOR; + this.iridescenceThicknessRange = [...source.iridescenceThicknessRange]; + this.iridescenceThicknessMap = source.iridescenceThicknessMap; + this.sheen = source.sheen; + this.sheenColor.copy(source.sheenColor); + this.sheenColorMap = source.sheenColorMap; + this.sheenRoughness = source.sheenRoughness; + this.sheenRoughnessMap = source.sheenRoughnessMap; + this.transmission = source.transmission; + this.transmissionMap = source.transmissionMap; + this.thickness = source.thickness; + this.thicknessMap = source.thicknessMap; + this.attenuationDistance = source.attenuationDistance; + this.attenuationColor.copy(source.attenuationColor); + this.specularIntensity = source.specularIntensity; + this.specularIntensityMap = source.specularIntensityMap; + this.specularColor.copy(source.specularColor); + this.specularColorMap = source.specularColorMap; + return this; + } +} + +class MeshPhongMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshPhongMaterial = true; + this.type = "MeshPhongMaterial"; + this.color = new Color(16777215); + this.specular = new Color(1118481); + this.shininess = 30; + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.specular.copy(source.specular); + this.shininess = source.shininess; + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } +} + +class MeshToonMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshToonMaterial = true; + this.defines = { TOON: "" }; + this.type = "MeshToonMaterial"; + this.color = new Color(16777215); + this.map = null; + this.gradientMap = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.gradientMap = source.gradientMap; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.fog = source.fog; + return this; + } +} + +class MeshNormalMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshNormalMaterial = true; + this.type = "MeshNormalMaterial"; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.flatShading = false; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.flatShading = source.flatShading; + return this; + } +} + +class MeshLambertMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshLambertMaterial = true; + this.type = "MeshLambertMaterial"; + this.color = new Color(16777215); + this.map = null; + this.lightMap = null; + this.lightMapIntensity = 1; + this.aoMap = null; + this.aoMapIntensity = 1; + this.emissive = new Color(0); + this.emissiveIntensity = 1; + this.emissiveMap = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.specularMap = null; + this.alphaMap = null; + this.envMap = null; + this.envMapRotation = new Euler; + this.combine = MultiplyOperation; + this.reflectivity = 1; + this.refractionRatio = 0.98; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.wireframeLinecap = "round"; + this.wireframeLinejoin = "round"; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.color.copy(source.color); + this.map = source.map; + this.lightMap = source.lightMap; + this.lightMapIntensity = source.lightMapIntensity; + this.aoMap = source.aoMap; + this.aoMapIntensity = source.aoMapIntensity; + this.emissive.copy(source.emissive); + this.emissiveMap = source.emissiveMap; + this.emissiveIntensity = source.emissiveIntensity; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.specularMap = source.specularMap; + this.alphaMap = source.alphaMap; + this.envMap = source.envMap; + this.envMapRotation.copy(source.envMapRotation); + this.combine = source.combine; + this.reflectivity = source.reflectivity; + this.refractionRatio = source.refractionRatio; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } +} + +class MeshDepthMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshDepthMaterial = true; + this.type = "MeshDepthMaterial"; + this.depthPacking = BasicDepthPacking; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.wireframe = false; + this.wireframeLinewidth = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.depthPacking = source.depthPacking; + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.wireframe = source.wireframe; + this.wireframeLinewidth = source.wireframeLinewidth; + return this; + } +} + +class MeshDistanceMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshDistanceMaterial = true; + this.type = "MeshDistanceMaterial"; + this.map = null; + this.alphaMap = null; + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.map = source.map; + this.alphaMap = source.alphaMap; + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + return this; + } +} + +class MeshMatcapMaterial extends Material { + constructor(parameters) { + super(); + this.isMeshMatcapMaterial = true; + this.defines = { MATCAP: "" }; + this.type = "MeshMatcapMaterial"; + this.color = new Color(16777215); + this.matcap = null; + this.map = null; + this.bumpMap = null; + this.bumpScale = 1; + this.normalMap = null; + this.normalMapType = TangentSpaceNormalMap; + this.normalScale = new Vector2(1, 1); + this.displacementMap = null; + this.displacementScale = 1; + this.displacementBias = 0; + this.alphaMap = null; + this.flatShading = false; + this.fog = true; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.defines = { MATCAP: "" }; + this.color.copy(source.color); + this.matcap = source.matcap; + this.map = source.map; + this.bumpMap = source.bumpMap; + this.bumpScale = source.bumpScale; + this.normalMap = source.normalMap; + this.normalMapType = source.normalMapType; + this.normalScale.copy(source.normalScale); + this.displacementMap = source.displacementMap; + this.displacementScale = source.displacementScale; + this.displacementBias = source.displacementBias; + this.alphaMap = source.alphaMap; + this.flatShading = source.flatShading; + this.fog = source.fog; + return this; + } +} + +class LineDashedMaterial extends LineBasicMaterial { + constructor(parameters) { + super(); + this.isLineDashedMaterial = true; + this.type = "LineDashedMaterial"; + this.scale = 1; + this.dashSize = 3; + this.gapSize = 1; + this.setValues(parameters); + } + copy(source) { + super.copy(source); + this.scale = source.scale; + this.dashSize = source.dashSize; + this.gapSize = source.gapSize; + return this; + } +} +function convertArray(array, type, forceClone) { + if (!array || !forceClone && array.constructor === type) + return array; + if (typeof type.BYTES_PER_ELEMENT === "number") { + return new type(array); + } + return Array.prototype.slice.call(array); +} +function isTypedArray(object) { + return ArrayBuffer.isView(object) && !(object instanceof DataView); +} +function getKeyframeOrder(times) { + function compareTime(i, j) { + return times[i] - times[j]; + } + const n = times.length; + const result = new Array(n); + for (let i = 0;i !== n; ++i) + result[i] = i; + result.sort(compareTime); + return result; +} +function sortedArray(values2, stride, order) { + const nValues = values2.length; + const result = new values2.constructor(nValues); + for (let i = 0, dstOffset = 0;dstOffset !== nValues; ++i) { + const srcOffset = order[i] * stride; + for (let j = 0;j !== stride; ++j) { + result[dstOffset++] = values2[srcOffset + j]; + } + } + return result; +} +function flattenJSON(jsonKeys, times, values2, valuePropertyName) { + let i = 1, key2 = jsonKeys[0]; + while (key2 !== undefined && key2[valuePropertyName] === undefined) { + key2 = jsonKeys[i++]; + } + if (key2 === undefined) + return; + let value2 = key2[valuePropertyName]; + if (value2 === undefined) + return; + if (Array.isArray(value2)) { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + values2.push.apply(values2, value2); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } else if (value2.toArray !== undefined) { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + value2.toArray(values2, values2.length); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } else { + do { + value2 = key2[valuePropertyName]; + if (value2 !== undefined) { + times.push(key2.time); + values2.push(value2); + } + key2 = jsonKeys[i++]; + } while (key2 !== undefined); + } +} +function subclip(sourceClip, name2, startFrame, endFrame, fps = 30) { + const clip = sourceClip.clone(); + clip.name = name2; + const tracks = []; + for (let i = 0;i < clip.tracks.length; ++i) { + const track = clip.tracks[i]; + const valueSize = track.getValueSize(); + const times = []; + const values2 = []; + for (let j = 0;j < track.times.length; ++j) { + const frame = track.times[j] * fps; + if (frame < startFrame || frame >= endFrame) + continue; + times.push(track.times[j]); + for (let k = 0;k < valueSize; ++k) { + values2.push(track.values[j * valueSize + k]); + } + } + if (times.length === 0) + continue; + track.times = convertArray(times, track.times.constructor); + track.values = convertArray(values2, track.values.constructor); + tracks.push(track); + } + clip.tracks = tracks; + let minStartTime = Infinity; + for (let i = 0;i < clip.tracks.length; ++i) { + if (minStartTime > clip.tracks[i].times[0]) { + minStartTime = clip.tracks[i].times[0]; + } + } + for (let i = 0;i < clip.tracks.length; ++i) { + clip.tracks[i].shift(-1 * minStartTime); + } + clip.resetDuration(); + return clip; +} +function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) { + if (fps <= 0) + fps = 30; + const numTracks = referenceClip.tracks.length; + const referenceTime = referenceFrame / fps; + for (let i = 0;i < numTracks; ++i) { + const referenceTrack = referenceClip.tracks[i]; + const referenceTrackType = referenceTrack.ValueTypeName; + if (referenceTrackType === "bool" || referenceTrackType === "string") + continue; + const targetTrack = targetClip.tracks.find(function(track) { + return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType; + }); + if (targetTrack === undefined) + continue; + let referenceOffset = 0; + const referenceValueSize = referenceTrack.getValueSize(); + if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + referenceOffset = referenceValueSize / 3; + } + let targetOffset = 0; + const targetValueSize = targetTrack.getValueSize(); + if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + targetOffset = targetValueSize / 3; + } + const lastIndex = referenceTrack.times.length - 1; + let referenceValue; + if (referenceTime <= referenceTrack.times[0]) { + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else if (referenceTime >= referenceTrack.times[lastIndex]) { + const startIndex = lastIndex * referenceValueSize + referenceOffset; + const endIndex = startIndex + referenceValueSize - referenceOffset; + referenceValue = referenceTrack.values.slice(startIndex, endIndex); + } else { + const interpolant = referenceTrack.createInterpolant(); + const startIndex = referenceOffset; + const endIndex = referenceValueSize - referenceOffset; + interpolant.evaluate(referenceTime); + referenceValue = interpolant.resultBuffer.slice(startIndex, endIndex); + } + if (referenceTrackType === "quaternion") { + const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate(); + referenceQuat.toArray(referenceValue); + } + const numTimes = targetTrack.times.length; + for (let j = 0;j < numTimes; ++j) { + const valueStart = j * targetValueSize + targetOffset; + if (referenceTrackType === "quaternion") { + Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart); + } else { + const valueEnd = targetValueSize - targetOffset * 2; + for (let k = 0;k < valueEnd; ++k) { + targetTrack.values[valueStart + k] -= referenceValue[k]; + } + } + } + } + targetClip.blendMode = AdditiveAnimationBlendMode; + return targetClip; +} +var AnimationUtils = { + convertArray, + isTypedArray, + getKeyframeOrder, + sortedArray, + flattenJSON, + subclip, + makeClipAdditive +}; + +class Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + this.parameterPositions = parameterPositions; + this._cachedIndex = 0; + this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize); + this.sampleValues = sampleValues; + this.valueSize = sampleSize; + this.settings = null; + this.DefaultSettings_ = {}; + } + evaluate(t) { + const pp = this.parameterPositions; + let i1 = this._cachedIndex, t1 = pp[i1], t0 = pp[i1 - 1]; + validate_interval: { + seek: { + let right; + linear_scan: { + forward_scan: + if (!(t < t1)) { + for (let giveUpAt = i1 + 2;; ) { + if (t1 === undefined) { + if (t < t0) + break forward_scan; + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + if (i1 === giveUpAt) + break; + t0 = t1; + t1 = pp[++i1]; + if (t < t1) { + break seek; + } + } + right = pp.length; + break linear_scan; + } + if (!(t >= t0)) { + const t1global = pp[1]; + if (t < t1global) { + i1 = 2; + t0 = t1global; + } + for (let giveUpAt = i1 - 2;; ) { + if (t0 === undefined) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (i1 === giveUpAt) + break; + t1 = t0; + t0 = pp[--i1 - 1]; + if (t >= t0) { + break seek; + } + } + right = i1; + i1 = 0; + break linear_scan; + } + break validate_interval; + } + while (i1 < right) { + const mid = i1 + right >>> 1; + if (t < pp[mid]) { + right = mid; + } else { + i1 = mid + 1; + } + } + t1 = pp[i1]; + t0 = pp[i1 - 1]; + if (t0 === undefined) { + this._cachedIndex = 0; + return this.copySampleValue_(0); + } + if (t1 === undefined) { + i1 = pp.length; + this._cachedIndex = i1; + return this.copySampleValue_(i1 - 1); + } + } + this._cachedIndex = i1; + this.intervalChanged_(i1, t0, t1); + } + return this.interpolate_(i1, t0, t, t1); + } + getSettings_() { + return this.settings || this.DefaultSettings_; + } + copySampleValue_(index2) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, offset = index2 * stride; + for (let i = 0;i !== stride; ++i) { + result[i] = values2[offset + i]; + } + return result; + } + interpolate_() { + throw new Error("call to abstract method"); + } + intervalChanged_() { + } +} + +class CubicInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + this._weightPrev = -0; + this._offsetPrev = -0; + this._weightNext = -0; + this._offsetNext = -0; + this.DefaultSettings_ = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + } + intervalChanged_(i1, t0, t1) { + const pp = this.parameterPositions; + let iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[iPrev], tNext = pp[iNext]; + if (tPrev === undefined) { + switch (this.getSettings_().endingStart) { + case ZeroSlopeEnding: + iPrev = i1; + tPrev = 2 * t0 - t1; + break; + case WrapAroundEnding: + iPrev = pp.length - 2; + tPrev = t0 + pp[iPrev] - pp[iPrev + 1]; + break; + default: + iPrev = i1; + tPrev = t1; + } + } + if (tNext === undefined) { + switch (this.getSettings_().endingEnd) { + case ZeroSlopeEnding: + iNext = i1; + tNext = 2 * t1 - t0; + break; + case WrapAroundEnding: + iNext = 1; + tNext = t1 + pp[1] - pp[0]; + break; + default: + iNext = i1 - 1; + tNext = t0; + } + } + const halfDt = (t1 - t0) * 0.5, stride = this.valueSize; + this._weightPrev = halfDt / (t0 - tPrev); + this._weightNext = halfDt / (tNext - t1); + this._offsetPrev = iPrev * stride; + this._offsetNext = iNext * stride; + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o0 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p = (t - t0) / (t1 - t0), pp = p * p, ppp = pp * p; + const sP = -wP * ppp + 2 * wP * pp - wP * p; + const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1; + const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p; + const sN = wN * ppp - wN * pp; + for (let i = 0;i !== stride; ++i) { + result[i] = sP * values2[oP + i] + s0 * values2[o0 + i] + s1 * values2[o1 + i] + sN * values2[oN + i]; + } + return result; + } +} + +class LinearInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = (t - t0) / (t1 - t0), weight0 = 1 - weight1; + for (let i = 0;i !== stride; ++i) { + result[i] = values2[offset0 + i] * weight0 + values2[offset1 + i] * weight1; + } + return result; + } +} + +class DiscreteInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1) { + return this.copySampleValue_(i1 - 1); + } +} + +class KeyframeTrack { + constructor(name2, times, values2, interpolation) { + if (name2 === undefined) + throw new Error("THREE.KeyframeTrack: track name is undefined"); + if (times === undefined || times.length === 0) + throw new Error("THREE.KeyframeTrack: no keyframes in track named " + name2); + this.name = name2; + this.times = convertArray(times, this.TimeBufferType); + this.values = convertArray(values2, this.ValueBufferType); + this.setInterpolation(interpolation || this.DefaultInterpolation); + } + static toJSON(track) { + const trackType = track.constructor; + let json; + if (trackType.toJSON !== this.toJSON) { + json = trackType.toJSON(track); + } else { + json = { + name: track.name, + times: convertArray(track.times, Array), + values: convertArray(track.values, Array) + }; + const interpolation = track.getInterpolation(); + if (interpolation !== track.DefaultInterpolation) { + json.interpolation = interpolation; + } + } + json.type = track.ValueTypeName; + return json; + } + InterpolantFactoryMethodDiscrete(result) { + return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodLinear(result) { + return new LinearInterpolant(this.times, this.values, this.getValueSize(), result); + } + InterpolantFactoryMethodSmooth(result) { + return new CubicInterpolant(this.times, this.values, this.getValueSize(), result); + } + setInterpolation(interpolation) { + let factoryMethod; + switch (interpolation) { + case InterpolateDiscrete: + factoryMethod = this.InterpolantFactoryMethodDiscrete; + break; + case InterpolateLinear: + factoryMethod = this.InterpolantFactoryMethodLinear; + break; + case InterpolateSmooth: + factoryMethod = this.InterpolantFactoryMethodSmooth; + break; + } + if (factoryMethod === undefined) { + const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; + if (this.createInterpolant === undefined) { + if (interpolation !== this.DefaultInterpolation) { + this.setInterpolation(this.DefaultInterpolation); + } else { + throw new Error(message); + } + } + console.warn("THREE.KeyframeTrack:", message); + return this; + } + this.createInterpolant = factoryMethod; + return this; + } + getInterpolation() { + switch (this.createInterpolant) { + case this.InterpolantFactoryMethodDiscrete: + return InterpolateDiscrete; + case this.InterpolantFactoryMethodLinear: + return InterpolateLinear; + case this.InterpolantFactoryMethodSmooth: + return InterpolateSmooth; + } + } + getValueSize() { + return this.values.length / this.times.length; + } + shift(timeOffset) { + if (timeOffset !== 0) { + const times = this.times; + for (let i = 0, n = times.length;i !== n; ++i) { + times[i] += timeOffset; + } + } + return this; + } + scale(timeScale) { + if (timeScale !== 1) { + const times = this.times; + for (let i = 0, n = times.length;i !== n; ++i) { + times[i] *= timeScale; + } + } + return this; + } + trim(startTime, endTime) { + const times = this.times, nKeys = times.length; + let from = 0, to = nKeys - 1; + while (from !== nKeys && times[from] < startTime) { + ++from; + } + while (to !== -1 && times[to] > endTime) { + --to; + } + ++to; + if (from !== 0 || to !== nKeys) { + if (from >= to) { + to = Math.max(to, 1); + from = to - 1; + } + const stride = this.getValueSize(); + this.times = times.slice(from, to); + this.values = this.values.slice(from * stride, to * stride); + } + return this; + } + validate() { + let valid = true; + const valueSize = this.getValueSize(); + if (valueSize - Math.floor(valueSize) !== 0) { + console.error("THREE.KeyframeTrack: Invalid value size in track.", this); + valid = false; + } + const times = this.times, values2 = this.values, nKeys = times.length; + if (nKeys === 0) { + console.error("THREE.KeyframeTrack: Track is empty.", this); + valid = false; + } + let prevTime = null; + for (let i = 0;i !== nKeys; i++) { + const currTime = times[i]; + if (typeof currTime === "number" && isNaN(currTime)) { + console.error("THREE.KeyframeTrack: Time is not a valid number.", this, i, currTime); + valid = false; + break; + } + if (prevTime !== null && prevTime > currTime) { + console.error("THREE.KeyframeTrack: Out of order keys.", this, i, currTime, prevTime); + valid = false; + break; + } + prevTime = currTime; + } + if (values2 !== undefined) { + if (isTypedArray(values2)) { + for (let i = 0, n = values2.length;i !== n; ++i) { + const value2 = values2[i]; + if (isNaN(value2)) { + console.error("THREE.KeyframeTrack: Value is not a valid number.", this, i, value2); + valid = false; + break; + } + } + } + } + return valid; + } + optimize() { + const times = this.times.slice(), values2 = this.values.slice(), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth, lastIndex = times.length - 1; + let writeIndex = 1; + for (let i = 1;i < lastIndex; ++i) { + let keep = false; + const time2 = times[i]; + const timeNext = times[i + 1]; + if (time2 !== timeNext && (i !== 1 || time2 !== times[0])) { + if (!smoothInterpolation) { + const offset = i * stride, offsetP = offset - stride, offsetN = offset + stride; + for (let j = 0;j !== stride; ++j) { + const value2 = values2[offset + j]; + if (value2 !== values2[offsetP + j] || value2 !== values2[offsetN + j]) { + keep = true; + break; + } + } + } else { + keep = true; + } + } + if (keep) { + if (i !== writeIndex) { + times[writeIndex] = times[i]; + const readOffset = i * stride, writeOffset = writeIndex * stride; + for (let j = 0;j !== stride; ++j) { + values2[writeOffset + j] = values2[readOffset + j]; + } + } + ++writeIndex; + } + } + if (lastIndex > 0) { + times[writeIndex] = times[lastIndex]; + for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0;j !== stride; ++j) { + values2[writeOffset + j] = values2[readOffset + j]; + } + ++writeIndex; + } + if (writeIndex !== times.length) { + this.times = times.slice(0, writeIndex); + this.values = values2.slice(0, writeIndex * stride); + } else { + this.times = times; + this.values = values2; + } + return this; + } + clone() { + const times = this.times.slice(); + const values2 = this.values.slice(); + const TypedKeyframeTrack = this.constructor; + const track = new TypedKeyframeTrack(this.name, times, values2); + track.createInterpolant = this.createInterpolant; + return track; + } +} +KeyframeTrack.prototype.TimeBufferType = Float32Array; +KeyframeTrack.prototype.ValueBufferType = Float32Array; +KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; + +class BooleanKeyframeTrack extends KeyframeTrack { + constructor(name2, times, values2) { + super(name2, times, values2); + } +} +BooleanKeyframeTrack.prototype.ValueTypeName = "bool"; +BooleanKeyframeTrack.prototype.ValueBufferType = Array; +BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +class ColorKeyframeTrack extends KeyframeTrack { +} +ColorKeyframeTrack.prototype.ValueTypeName = "color"; + +class NumberKeyframeTrack extends KeyframeTrack { +} +NumberKeyframeTrack.prototype.ValueTypeName = "number"; + +class QuaternionLinearInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + interpolate_(i1, t0, t, t1) { + const result = this.resultBuffer, values2 = this.sampleValues, stride = this.valueSize, alpha = (t - t0) / (t1 - t0); + let offset = i1 * stride; + for (let end = offset + stride;offset !== end; offset += 4) { + Quaternion.slerpFlat(result, 0, values2, offset - stride, values2, offset, alpha); + } + return result; + } +} + +class QuaternionKeyframeTrack extends KeyframeTrack { + InterpolantFactoryMethodLinear(result) { + return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result); + } +} +QuaternionKeyframeTrack.prototype.ValueTypeName = "quaternion"; +QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +class StringKeyframeTrack extends KeyframeTrack { + constructor(name2, times, values2) { + super(name2, times, values2); + } +} +StringKeyframeTrack.prototype.ValueTypeName = "string"; +StringKeyframeTrack.prototype.ValueBufferType = Array; +StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; +StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined; +StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; + +class VectorKeyframeTrack extends KeyframeTrack { +} +VectorKeyframeTrack.prototype.ValueTypeName = "vector"; + +class AnimationClip { + constructor(name2 = "", duration = -1, tracks = [], blendMode = NormalAnimationBlendMode) { + this.name = name2; + this.tracks = tracks; + this.duration = duration; + this.blendMode = blendMode; + this.uuid = generateUUID(); + if (this.duration < 0) { + this.resetDuration(); + } + } + static parse(json) { + const tracks = [], jsonTracks = json.tracks, frameTime = 1 / (json.fps || 1); + for (let i = 0, n = jsonTracks.length;i !== n; ++i) { + tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime)); + } + const clip = new this(json.name, json.duration, tracks, json.blendMode); + clip.uuid = json.uuid; + return clip; + } + static toJSON(clip) { + const tracks = [], clipTracks = clip.tracks; + const json = { + name: clip.name, + duration: clip.duration, + tracks, + uuid: clip.uuid, + blendMode: clip.blendMode + }; + for (let i = 0, n = clipTracks.length;i !== n; ++i) { + tracks.push(KeyframeTrack.toJSON(clipTracks[i])); + } + return json; + } + static CreateFromMorphTargetSequence(name2, morphTargetSequence, fps, noLoop) { + const numMorphTargets = morphTargetSequence.length; + const tracks = []; + for (let i = 0;i < numMorphTargets; i++) { + let times = []; + let values2 = []; + times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets); + values2.push(0, 1, 0); + const order = getKeyframeOrder(times); + times = sortedArray(times, 1, order); + values2 = sortedArray(values2, 1, order); + if (!noLoop && times[0] === 0) { + times.push(numMorphTargets); + values2.push(values2[0]); + } + tracks.push(new NumberKeyframeTrack(".morphTargetInfluences[" + morphTargetSequence[i].name + "]", times, values2).scale(1 / fps)); + } + return new this(name2, -1, tracks); + } + static findByName(objectOrClipArray, name2) { + let clipArray = objectOrClipArray; + if (!Array.isArray(objectOrClipArray)) { + const o = objectOrClipArray; + clipArray = o.geometry && o.geometry.animations || o.animations; + } + for (let i = 0;i < clipArray.length; i++) { + if (clipArray[i].name === name2) { + return clipArray[i]; + } + } + return null; + } + static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) { + const animationToMorphTargets = {}; + const pattern = /^([\w-]*?)([\d]+)$/; + for (let i = 0, il = morphTargets.length;i < il; i++) { + const morphTarget = morphTargets[i]; + const parts = morphTarget.name.match(pattern); + if (parts && parts.length > 1) { + const name2 = parts[1]; + let animationMorphTargets = animationToMorphTargets[name2]; + if (!animationMorphTargets) { + animationToMorphTargets[name2] = animationMorphTargets = []; + } + animationMorphTargets.push(morphTarget); + } + } + const clips = []; + for (const name2 in animationToMorphTargets) { + clips.push(this.CreateFromMorphTargetSequence(name2, animationToMorphTargets[name2], fps, noLoop)); + } + return clips; + } + static parseAnimation(animation, bones) { + if (!animation) { + console.error("THREE.AnimationClip: No animation in JSONLoader data."); + return null; + } + const addNonemptyTrack = function(trackType, trackName, animationKeys, propertyName, destTracks) { + if (animationKeys.length !== 0) { + const times = []; + const values2 = []; + flattenJSON(animationKeys, times, values2, propertyName); + if (times.length !== 0) { + destTracks.push(new trackType(trackName, times, values2)); + } + } + }; + const tracks = []; + const clipName = animation.name || "default"; + const fps = animation.fps || 30; + const blendMode = animation.blendMode; + let duration = animation.length || -1; + const hierarchyTracks = animation.hierarchy || []; + for (let h = 0;h < hierarchyTracks.length; h++) { + const animationKeys = hierarchyTracks[h].keys; + if (!animationKeys || animationKeys.length === 0) + continue; + if (animationKeys[0].morphTargets) { + const morphTargetNames = {}; + let k; + for (k = 0;k < animationKeys.length; k++) { + if (animationKeys[k].morphTargets) { + for (let m = 0;m < animationKeys[k].morphTargets.length; m++) { + morphTargetNames[animationKeys[k].morphTargets[m]] = -1; + } + } + } + for (const morphTargetName in morphTargetNames) { + const times = []; + const values2 = []; + for (let m = 0;m !== animationKeys[k].morphTargets.length; ++m) { + const animationKey = animationKeys[k]; + times.push(animationKey.time); + values2.push(animationKey.morphTarget === morphTargetName ? 1 : 0); + } + tracks.push(new NumberKeyframeTrack(".morphTargetInfluence[" + morphTargetName + "]", times, values2)); + } + duration = morphTargetNames.length * fps; + } else { + const boneName = ".bones[" + bones[h].name + "]"; + addNonemptyTrack(VectorKeyframeTrack, boneName + ".position", animationKeys, "pos", tracks); + addNonemptyTrack(QuaternionKeyframeTrack, boneName + ".quaternion", animationKeys, "rot", tracks); + addNonemptyTrack(VectorKeyframeTrack, boneName + ".scale", animationKeys, "scl", tracks); + } + } + if (tracks.length === 0) { + return null; + } + const clip = new this(clipName, duration, tracks, blendMode); + return clip; + } + resetDuration() { + const tracks = this.tracks; + let duration = 0; + for (let i = 0, n = tracks.length;i !== n; ++i) { + const track = this.tracks[i]; + duration = Math.max(duration, track.times[track.times.length - 1]); + } + this.duration = duration; + return this; + } + trim() { + for (let i = 0;i < this.tracks.length; i++) { + this.tracks[i].trim(0, this.duration); + } + return this; + } + validate() { + let valid = true; + for (let i = 0;i < this.tracks.length; i++) { + valid = valid && this.tracks[i].validate(); + } + return valid; + } + optimize() { + for (let i = 0;i < this.tracks.length; i++) { + this.tracks[i].optimize(); + } + return this; + } + clone() { + const tracks = []; + for (let i = 0;i < this.tracks.length; i++) { + tracks.push(this.tracks[i].clone()); + } + return new this.constructor(this.name, this.duration, tracks, this.blendMode); + } + toJSON() { + return this.constructor.toJSON(this); + } +} +function getTrackTypeForValueTypeName(typeName) { + switch (typeName.toLowerCase()) { + case "scalar": + case "double": + case "float": + case "number": + case "integer": + return NumberKeyframeTrack; + case "vector": + case "vector2": + case "vector3": + case "vector4": + return VectorKeyframeTrack; + case "color": + return ColorKeyframeTrack; + case "quaternion": + return QuaternionKeyframeTrack; + case "bool": + case "boolean": + return BooleanKeyframeTrack; + case "string": + return StringKeyframeTrack; + } + throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + typeName); +} +function parseKeyframeTrack(json) { + if (json.type === undefined) { + throw new Error("THREE.KeyframeTrack: track type undefined, can not parse"); + } + const trackType = getTrackTypeForValueTypeName(json.type); + if (json.times === undefined) { + const times = [], values2 = []; + flattenJSON(json.keys, times, values2, "value"); + json.times = times; + json.values = values2; + } + if (trackType.parse !== undefined) { + return trackType.parse(json); + } else { + return new trackType(json.name, json.times, json.values, json.interpolation); + } +} +var Cache = { + enabled: false, + files: {}, + add: function(key2, file) { + if (this.enabled === false) + return; + this.files[key2] = file; + }, + get: function(key2) { + if (this.enabled === false) + return; + return this.files[key2]; + }, + remove: function(key2) { + delete this.files[key2]; + }, + clear: function() { + this.files = {}; + } +}; + +class LoadingManager { + constructor(onLoad, onProgress, onError) { + const scope = this; + let isLoading = false; + let itemsLoaded = 0; + let itemsTotal = 0; + let urlModifier = undefined; + const handlers = []; + this.onStart = undefined; + this.onLoad = onLoad; + this.onProgress = onProgress; + this.onError = onError; + this.itemStart = function(url) { + itemsTotal++; + if (isLoading === false) { + if (scope.onStart !== undefined) { + scope.onStart(url, itemsLoaded, itemsTotal); + } + } + isLoading = true; + }; + this.itemEnd = function(url) { + itemsLoaded++; + if (scope.onProgress !== undefined) { + scope.onProgress(url, itemsLoaded, itemsTotal); + } + if (itemsLoaded === itemsTotal) { + isLoading = false; + if (scope.onLoad !== undefined) { + scope.onLoad(); + } + } + }; + this.itemError = function(url) { + if (scope.onError !== undefined) { + scope.onError(url); + } + }; + this.resolveURL = function(url) { + if (urlModifier) { + return urlModifier(url); + } + return url; + }; + this.setURLModifier = function(transform2) { + urlModifier = transform2; + return this; + }; + this.addHandler = function(regex, loader) { + handlers.push(regex, loader); + return this; + }; + this.removeHandler = function(regex) { + const index2 = handlers.indexOf(regex); + if (index2 !== -1) { + handlers.splice(index2, 2); + } + return this; + }; + this.getHandler = function(file) { + for (let i = 0, l = handlers.length;i < l; i += 2) { + const regex = handlers[i]; + const loader = handlers[i + 1]; + if (regex.global) + regex.lastIndex = 0; + if (regex.test(file)) { + return loader; + } + } + return null; + }; + } +} +var DefaultLoadingManager = /* @__PURE__ */ new LoadingManager; + +class Loader { + constructor(manager) { + this.manager = manager !== undefined ? manager : DefaultLoadingManager; + this.crossOrigin = "anonymous"; + this.withCredentials = false; + this.path = ""; + this.resourcePath = ""; + this.requestHeader = {}; + } + load() { + } + loadAsync(url, onProgress) { + const scope = this; + return new Promise(function(resolve, reject2) { + scope.load(url, resolve, onProgress, reject2); + }); + } + parse() { + } + setCrossOrigin(crossOrigin) { + this.crossOrigin = crossOrigin; + return this; + } + setWithCredentials(value2) { + this.withCredentials = value2; + return this; + } + setPath(path) { + this.path = path; + return this; + } + setResourcePath(resourcePath) { + this.resourcePath = resourcePath; + return this; + } + setRequestHeader(requestHeader) { + this.requestHeader = requestHeader; + return this; + } +} +Loader.DEFAULT_MATERIAL_NAME = "__DEFAULT"; +var loading = {}; + +class HttpError extends Error { + constructor(message, response) { + super(message); + this.response = response; + } +} + +class FileLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (url === undefined) + url = ""; + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const cached = Cache.get(url); + if (cached !== undefined) { + this.manager.itemStart(url); + setTimeout(() => { + if (onLoad) + onLoad(cached); + this.manager.itemEnd(url); + }, 0); + return cached; + } + if (loading[url] !== undefined) { + loading[url].push({ + onLoad, + onProgress, + onError + }); + return; + } + loading[url] = []; + loading[url].push({ + onLoad, + onProgress, + onError + }); + const req = new Request(url, { + headers: new Headers(this.requestHeader), + credentials: this.withCredentials ? "include" : "same-origin" + }); + const mimeType = this.mimeType; + const responseType = this.responseType; + fetch(req).then((response) => { + if (response.status === 200 || response.status === 0) { + if (response.status === 0) { + console.warn("THREE.FileLoader: HTTP Status 0 received."); + } + if (typeof ReadableStream === "undefined" || response.body === undefined || response.body.getReader === undefined) { + return response; + } + const callbacks = loading[url]; + const reader = response.body.getReader(); + const contentLength = response.headers.get("X-File-Size") || response.headers.get("Content-Length"); + const total = contentLength ? parseInt(contentLength) : 0; + const lengthComputable = total !== 0; + let loaded = 0; + const stream = new ReadableStream({ + start(controller) { + readData(); + function readData() { + reader.read().then(({ done, value: value2 }) => { + if (done) { + controller.close(); + } else { + loaded += value2.byteLength; + const event = new ProgressEvent("progress", { lengthComputable, loaded, total }); + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onProgress) + callback.onProgress(event); + } + controller.enqueue(value2); + readData(); + } + }, (e) => { + controller.error(e); + }); + } + } + }); + return new Response(stream); + } else { + throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response); + } + }).then((response) => { + switch (responseType) { + case "arraybuffer": + return response.arrayBuffer(); + case "blob": + return response.blob(); + case "document": + return response.text().then((text2) => { + const parser = new DOMParser; + return parser.parseFromString(text2, mimeType); + }); + case "json": + return response.json(); + default: + if (mimeType === undefined) { + return response.text(); + } else { + const re = /charset="?([^;"\s]*)"?/i; + const exec = re.exec(mimeType); + const label = exec && exec[1] ? exec[1].toLowerCase() : undefined; + const decoder = new TextDecoder(label); + return response.arrayBuffer().then((ab) => decoder.decode(ab)); + } + } + }).then((data2) => { + Cache.add(url, data2); + const callbacks = loading[url]; + delete loading[url]; + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onLoad) + callback.onLoad(data2); + } + }).catch((err) => { + const callbacks = loading[url]; + if (callbacks === undefined) { + this.manager.itemError(url); + throw err; + } + delete loading[url]; + for (let i = 0, il = callbacks.length;i < il; i++) { + const callback = callbacks[i]; + if (callback.onError) + callback.onError(err); + } + this.manager.itemError(url); + }).finally(() => { + this.manager.itemEnd(url); + }); + this.manager.itemStart(url); + } + setResponseType(value2) { + this.responseType = value2; + return this; + } + setMimeType(value2) { + this.mimeType = value2; + return this; + } +} + +class AnimationLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const animations = []; + for (let i = 0;i < json.length; i++) { + const clip = AnimationClip.parse(json[i]); + animations.push(clip); + } + return animations; + } +} + +class CompressedTextureLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const images = []; + const texture = new CompressedTexture; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(scope.withCredentials); + let loaded = 0; + function loadTexture(i) { + loader.load(url[i], function(buffer) { + const texDatas = scope.parse(buffer, true); + images[i] = { + width: texDatas.width, + height: texDatas.height, + format: texDatas.format, + mipmaps: texDatas.mipmaps + }; + loaded += 1; + if (loaded === 6) { + if (texDatas.mipmapCount === 1) + texture.minFilter = LinearFilter; + texture.image = images; + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + } + }, onProgress, onError); + } + if (Array.isArray(url)) { + for (let i = 0, il = url.length;i < il; ++i) { + loadTexture(i); + } + } else { + loader.load(url, function(buffer) { + const texDatas = scope.parse(buffer, true); + if (texDatas.isCubemap) { + const faces = texDatas.mipmaps.length / texDatas.mipmapCount; + for (let f = 0;f < faces; f++) { + images[f] = { mipmaps: [] }; + for (let i = 0;i < texDatas.mipmapCount; i++) { + images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]); + images[f].format = texDatas.format; + images[f].width = texDatas.width; + images[f].height = texDatas.height; + } + } + texture.image = images; + } else { + texture.image.width = texDatas.width; + texture.image.height = texDatas.height; + texture.mipmaps = texDatas.mipmaps; + } + if (texDatas.mipmapCount === 1) { + texture.minFilter = LinearFilter; + } + texture.format = texDatas.format; + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + }, onProgress, onError); + } + return texture; + } +} + +class ImageLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache.get(url); + if (cached !== undefined) { + scope.manager.itemStart(url); + setTimeout(function() { + if (onLoad) + onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const image = createElementNS("img"); + function onImageLoad() { + removeEventListeners(); + Cache.add(url, this); + if (onLoad) + onLoad(this); + scope.manager.itemEnd(url); + } + function onImageError(event) { + removeEventListeners(); + if (onError) + onError(event); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + } + function removeEventListeners() { + image.removeEventListener("load", onImageLoad, false); + image.removeEventListener("error", onImageError, false); + } + image.addEventListener("load", onImageLoad, false); + image.addEventListener("error", onImageError, false); + if (url.slice(0, 5) !== "data:") { + if (this.crossOrigin !== undefined) + image.crossOrigin = this.crossOrigin; + } + scope.manager.itemStart(url); + image.src = url; + return image; + } +} + +class CubeTextureLoader extends Loader { + constructor(manager) { + super(manager); + } + load(urls, onLoad, onProgress, onError) { + const texture = new CubeTexture; + texture.colorSpace = SRGBColorSpace; + const loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + let loaded = 0; + function loadTexture(i) { + loader.load(urls[i], function(image) { + texture.images[i] = image; + loaded++; + if (loaded === 6) { + texture.needsUpdate = true; + if (onLoad) + onLoad(texture); + } + }, undefined, onError); + } + for (let i = 0;i < urls.length; ++i) { + loadTexture(i); + } + return texture; + } +} + +class DataTextureLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const texture = new DataTexture; + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setPath(this.path); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(buffer) { + let texData; + try { + texData = scope.parse(buffer); + } catch (error) { + if (onError !== undefined) { + onError(error); + } else { + console.error(error); + return; + } + } + if (texData.image !== undefined) { + texture.image = texData.image; + } else if (texData.data !== undefined) { + texture.image.width = texData.width; + texture.image.height = texData.height; + texture.image.data = texData.data; + } + texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping; + texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping; + texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter; + texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter; + texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1; + if (texData.colorSpace !== undefined) { + texture.colorSpace = texData.colorSpace; + } + if (texData.flipY !== undefined) { + texture.flipY = texData.flipY; + } + if (texData.format !== undefined) { + texture.format = texData.format; + } + if (texData.type !== undefined) { + texture.type = texData.type; + } + if (texData.mipmaps !== undefined) { + texture.mipmaps = texData.mipmaps; + texture.minFilter = LinearMipmapLinearFilter; + } + if (texData.mipmapCount === 1) { + texture.minFilter = LinearFilter; + } + if (texData.generateMipmaps !== undefined) { + texture.generateMipmaps = texData.generateMipmaps; + } + texture.needsUpdate = true; + if (onLoad) + onLoad(texture, texData); + }, onProgress, onError); + return texture; + } +} + +class TextureLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const texture = new Texture; + const loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + loader.setPath(this.path); + loader.load(url, function(image) { + texture.image = image; + texture.needsUpdate = true; + if (onLoad !== undefined) { + onLoad(texture); + } + }, onProgress, onError); + return texture; + } +} + +class Light extends Object3D { + constructor(color, intensity = 1) { + super(); + this.isLight = true; + this.type = "Light"; + this.color = new Color(color); + this.intensity = intensity; + } + dispose() { + } + copy(source, recursive) { + super.copy(source, recursive); + this.color.copy(source.color); + this.intensity = source.intensity; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.color = this.color.getHex(); + data2.object.intensity = this.intensity; + if (this.groundColor !== undefined) + data2.object.groundColor = this.groundColor.getHex(); + if (this.distance !== undefined) + data2.object.distance = this.distance; + if (this.angle !== undefined) + data2.object.angle = this.angle; + if (this.decay !== undefined) + data2.object.decay = this.decay; + if (this.penumbra !== undefined) + data2.object.penumbra = this.penumbra; + if (this.shadow !== undefined) + data2.object.shadow = this.shadow.toJSON(); + if (this.target !== undefined) + data2.object.target = this.target.uuid; + return data2; + } +} + +class HemisphereLight extends Light { + constructor(skyColor, groundColor, intensity) { + super(skyColor, intensity); + this.isHemisphereLight = true; + this.type = "HemisphereLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.groundColor = new Color(groundColor); + } + copy(source, recursive) { + super.copy(source, recursive); + this.groundColor.copy(source.groundColor); + return this; + } +} +var _projScreenMatrix$1 = /* @__PURE__ */ new Matrix4; +var _lightPositionWorld$1 = /* @__PURE__ */ new Vector3; +var _lookTarget$1 = /* @__PURE__ */ new Vector3; + +class LightShadow { + constructor(camera) { + this.camera = camera; + this.intensity = 1; + this.bias = 0; + this.normalBias = 0; + this.radius = 1; + this.blurSamples = 8; + this.mapSize = new Vector2(512, 512); + this.map = null; + this.mapPass = null; + this.matrix = new Matrix4; + this.autoUpdate = true; + this.needsUpdate = false; + this._frustum = new Frustum; + this._frameExtents = new Vector2(1, 1); + this._viewportCount = 1; + this._viewports = [ + new Vector4(0, 0, 1, 1) + ]; + } + getViewportCount() { + return this._viewportCount; + } + getFrustum() { + return this._frustum; + } + updateMatrices(light) { + const shadowCamera = this.camera; + const shadowMatrix = this.matrix; + _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld); + shadowCamera.position.copy(_lightPositionWorld$1); + _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld); + shadowCamera.lookAt(_lookTarget$1); + shadowCamera.updateMatrixWorld(); + _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix$1); + shadowMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + shadowMatrix.multiply(_projScreenMatrix$1); + } + getViewport(viewportIndex) { + return this._viewports[viewportIndex]; + } + getFrameExtents() { + return this._frameExtents; + } + dispose() { + if (this.map) { + this.map.dispose(); + } + if (this.mapPass) { + this.mapPass.dispose(); + } + } + copy(source) { + this.camera = source.camera.clone(); + this.intensity = source.intensity; + this.bias = source.bias; + this.radius = source.radius; + this.mapSize.copy(source.mapSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + toJSON() { + const object = {}; + if (this.intensity !== 1) + object.intensity = this.intensity; + if (this.bias !== 0) + object.bias = this.bias; + if (this.normalBias !== 0) + object.normalBias = this.normalBias; + if (this.radius !== 1) + object.radius = this.radius; + if (this.mapSize.x !== 512 || this.mapSize.y !== 512) + object.mapSize = this.mapSize.toArray(); + object.camera = this.camera.toJSON(false).object; + delete object.camera.matrix; + return object; + } +} + +class SpotLightShadow extends LightShadow { + constructor() { + super(new PerspectiveCamera(50, 1, 0.5, 500)); + this.isSpotLightShadow = true; + this.focus = 1; + } + updateMatrices(light) { + const camera = this.camera; + const fov2 = RAD2DEG * 2 * light.angle * this.focus; + const aspect2 = this.mapSize.width / this.mapSize.height; + const far = light.distance || camera.far; + if (fov2 !== camera.fov || aspect2 !== camera.aspect || far !== camera.far) { + camera.fov = fov2; + camera.aspect = aspect2; + camera.far = far; + camera.updateProjectionMatrix(); + } + super.updateMatrices(light); + } + copy(source) { + super.copy(source); + this.focus = source.focus; + return this; + } +} + +class SpotLight extends Light { + constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2) { + super(color, intensity); + this.isSpotLight = true; + this.type = "SpotLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D; + this.distance = distance; + this.angle = angle; + this.penumbra = penumbra; + this.decay = decay; + this.map = null; + this.shadow = new SpotLightShadow; + } + get power() { + return this.intensity * Math.PI; + } + set power(power) { + this.intensity = power / Math.PI; + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.angle = source.angle; + this.penumbra = source.penumbra; + this.decay = source.decay; + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } +} +var _projScreenMatrix = /* @__PURE__ */ new Matrix4; +var _lightPositionWorld = /* @__PURE__ */ new Vector3; +var _lookTarget = /* @__PURE__ */ new Vector3; + +class PointLightShadow extends LightShadow { + constructor() { + super(new PerspectiveCamera(90, 1, 0.5, 500)); + this.isPointLightShadow = true; + this._frameExtents = new Vector2(4, 2); + this._viewportCount = 6; + this._viewports = [ + new Vector4(2, 1, 1, 1), + new Vector4(0, 1, 1, 1), + new Vector4(3, 1, 1, 1), + new Vector4(1, 1, 1, 1), + new Vector4(3, 0, 1, 1), + new Vector4(1, 0, 1, 1) + ]; + this._cubeDirections = [ + new Vector3(1, 0, 0), + new Vector3(-1, 0, 0), + new Vector3(0, 0, 1), + new Vector3(0, 0, -1), + new Vector3(0, 1, 0), + new Vector3(0, -1, 0) + ]; + this._cubeUps = [ + new Vector3(0, 1, 0), + new Vector3(0, 1, 0), + new Vector3(0, 1, 0), + new Vector3(0, 1, 0), + new Vector3(0, 0, 1), + new Vector3(0, 0, -1) + ]; + } + updateMatrices(light, viewportIndex = 0) { + const camera = this.camera; + const shadowMatrix = this.matrix; + const far = light.distance || camera.far; + if (far !== camera.far) { + camera.far = far; + camera.updateProjectionMatrix(); + } + _lightPositionWorld.setFromMatrixPosition(light.matrixWorld); + camera.position.copy(_lightPositionWorld); + _lookTarget.copy(camera.position); + _lookTarget.add(this._cubeDirections[viewportIndex]); + camera.up.copy(this._cubeUps[viewportIndex]); + camera.lookAt(_lookTarget); + camera.updateMatrixWorld(); + shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z); + _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + this._frustum.setFromProjectionMatrix(_projScreenMatrix); + } +} + +class PointLight extends Light { + constructor(color, intensity, distance = 0, decay = 2) { + super(color, intensity); + this.isPointLight = true; + this.type = "PointLight"; + this.distance = distance; + this.decay = decay; + this.shadow = new PointLightShadow; + } + get power() { + return this.intensity * 4 * Math.PI; + } + set power(power) { + this.intensity = power / (4 * Math.PI); + } + dispose() { + this.shadow.dispose(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.distance = source.distance; + this.decay = source.decay; + this.shadow = source.shadow.clone(); + return this; + } +} + +class OrthographicCamera extends Camera { + constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) { + super(); + this.isOrthographicCamera = true; + this.type = "OrthographicCamera"; + this.zoom = 1; + this.view = null; + this.left = left; + this.right = right; + this.top = top; + this.bottom = bottom; + this.near = near; + this.far = far; + this.updateProjectionMatrix(); + } + copy(source, recursive) { + super.copy(source, recursive); + this.left = source.left; + this.right = source.right; + this.top = source.top; + this.bottom = source.bottom; + this.near = source.near; + this.far = source.far; + this.zoom = source.zoom; + this.view = source.view === null ? null : Object.assign({}, source.view); + return this; + } + setViewOffset(fullWidth, fullHeight, x, y, width2, height2) { + if (this.view === null) { + this.view = { + enabled: true, + fullWidth: 1, + fullHeight: 1, + offsetX: 0, + offsetY: 0, + width: 1, + height: 1 + }; + } + this.view.enabled = true; + this.view.fullWidth = fullWidth; + this.view.fullHeight = fullHeight; + this.view.offsetX = x; + this.view.offsetY = y; + this.view.width = width2; + this.view.height = height2; + this.updateProjectionMatrix(); + } + clearViewOffset() { + if (this.view !== null) { + this.view.enabled = false; + } + this.updateProjectionMatrix(); + } + updateProjectionMatrix() { + const dx = (this.right - this.left) / (2 * this.zoom); + const dy = (this.top - this.bottom) / (2 * this.zoom); + const cx = (this.right + this.left) / 2; + const cy = (this.top + this.bottom) / 2; + let left = cx - dx; + let right = cx + dx; + let top = cy + dy; + let bottom = cy - dy; + if (this.view !== null && this.view.enabled) { + const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom; + const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom; + left += scaleW * this.view.offsetX; + right = left + scaleW * this.view.width; + top -= scaleH * this.view.offsetY; + bottom = top - scaleH * this.view.height; + } + this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far, this.coordinateSystem); + this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.zoom = this.zoom; + data2.object.left = this.left; + data2.object.right = this.right; + data2.object.top = this.top; + data2.object.bottom = this.bottom; + data2.object.near = this.near; + data2.object.far = this.far; + if (this.view !== null) + data2.object.view = Object.assign({}, this.view); + return data2; + } +} + +class DirectionalLightShadow extends LightShadow { + constructor() { + super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500)); + this.isDirectionalLightShadow = true; + } +} + +class DirectionalLight extends Light { + constructor(color, intensity) { + super(color, intensity); + this.isDirectionalLight = true; + this.type = "DirectionalLight"; + this.position.copy(Object3D.DEFAULT_UP); + this.updateMatrix(); + this.target = new Object3D; + this.shadow = new DirectionalLightShadow; + } + dispose() { + this.shadow.dispose(); + } + copy(source) { + super.copy(source); + this.target = source.target.clone(); + this.shadow = source.shadow.clone(); + return this; + } +} + +class AmbientLight extends Light { + constructor(color, intensity) { + super(color, intensity); + this.isAmbientLight = true; + this.type = "AmbientLight"; + } +} + +class RectAreaLight extends Light { + constructor(color, intensity, width2 = 10, height2 = 10) { + super(color, intensity); + this.isRectAreaLight = true; + this.type = "RectAreaLight"; + this.width = width2; + this.height = height2; + } + get power() { + return this.intensity * this.width * this.height * Math.PI; + } + set power(power) { + this.intensity = power / (this.width * this.height * Math.PI); + } + copy(source) { + super.copy(source); + this.width = source.width; + this.height = source.height; + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.width = this.width; + data2.object.height = this.height; + return data2; + } +} + +class SphericalHarmonics3 { + constructor() { + this.isSphericalHarmonics3 = true; + this.coefficients = []; + for (let i = 0;i < 9; i++) { + this.coefficients.push(new Vector3); + } + } + set(coefficients) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].copy(coefficients[i]); + } + return this; + } + zero() { + for (let i = 0;i < 9; i++) { + this.coefficients[i].set(0, 0, 0); + } + return this; + } + getAt(normal, target) { + const { x, y, z } = normal; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.282095); + target.addScaledVector(coeff[1], 0.488603 * y); + target.addScaledVector(coeff[2], 0.488603 * z); + target.addScaledVector(coeff[3], 0.488603 * x); + target.addScaledVector(coeff[4], 1.092548 * (x * y)); + target.addScaledVector(coeff[5], 1.092548 * (y * z)); + target.addScaledVector(coeff[6], 0.315392 * (3 * z * z - 1)); + target.addScaledVector(coeff[7], 1.092548 * (x * z)); + target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y)); + return target; + } + getIrradianceAt(normal, target) { + const { x, y, z } = normal; + const coeff = this.coefficients; + target.copy(coeff[0]).multiplyScalar(0.886227); + target.addScaledVector(coeff[1], 2 * 0.511664 * y); + target.addScaledVector(coeff[2], 2 * 0.511664 * z); + target.addScaledVector(coeff[3], 2 * 0.511664 * x); + target.addScaledVector(coeff[4], 2 * 0.429043 * x * y); + target.addScaledVector(coeff[5], 2 * 0.429043 * y * z); + target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); + target.addScaledVector(coeff[7], 2 * 0.429043 * x * z); + target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); + return target; + } + add(sh) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].add(sh.coefficients[i]); + } + return this; + } + addScaledSH(sh, s) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].addScaledVector(sh.coefficients[i], s); + } + return this; + } + scale(s) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].multiplyScalar(s); + } + return this; + } + lerp(sh, alpha) { + for (let i = 0;i < 9; i++) { + this.coefficients[i].lerp(sh.coefficients[i], alpha); + } + return this; + } + equals(sh) { + for (let i = 0;i < 9; i++) { + if (!this.coefficients[i].equals(sh.coefficients[i])) { + return false; + } + } + return true; + } + copy(sh) { + return this.set(sh.coefficients); + } + clone() { + return new this.constructor().copy(this); + } + fromArray(array, offset = 0) { + const coefficients = this.coefficients; + for (let i = 0;i < 9; i++) { + coefficients[i].fromArray(array, offset + i * 3); + } + return this; + } + toArray(array = [], offset = 0) { + const coefficients = this.coefficients; + for (let i = 0;i < 9; i++) { + coefficients[i].toArray(array, offset + i * 3); + } + return array; + } + static getBasisAt(normal, shBasis) { + const { x, y, z } = normal; + shBasis[0] = 0.282095; + shBasis[1] = 0.488603 * y; + shBasis[2] = 0.488603 * z; + shBasis[3] = 0.488603 * x; + shBasis[4] = 1.092548 * x * y; + shBasis[5] = 1.092548 * y * z; + shBasis[6] = 0.315392 * (3 * z * z - 1); + shBasis[7] = 1.092548 * x * z; + shBasis[8] = 0.546274 * (x * x - y * y); + } +} + +class LightProbe extends Light { + constructor(sh = new SphericalHarmonics3, intensity = 1) { + super(undefined, intensity); + this.isLightProbe = true; + this.sh = sh; + } + copy(source) { + super.copy(source); + this.sh.copy(source.sh); + return this; + } + fromJSON(json) { + this.intensity = json.intensity; + this.sh.fromArray(json.sh); + return this; + } + toJSON(meta) { + const data2 = super.toJSON(meta); + data2.object.sh = this.sh.toArray(); + return data2; + } +} + +class MaterialLoader extends Loader { + constructor(manager) { + super(manager); + this.textures = {}; + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const textures = this.textures; + function getTexture(name2) { + if (textures[name2] === undefined) { + console.warn("THREE.MaterialLoader: Undefined texture", name2); + } + return textures[name2]; + } + const material = this.createMaterialFromType(json.type); + if (json.uuid !== undefined) + material.uuid = json.uuid; + if (json.name !== undefined) + material.name = json.name; + if (json.color !== undefined && material.color !== undefined) + material.color.setHex(json.color); + if (json.roughness !== undefined) + material.roughness = json.roughness; + if (json.metalness !== undefined) + material.metalness = json.metalness; + if (json.sheen !== undefined) + material.sheen = json.sheen; + if (json.sheenColor !== undefined) + material.sheenColor = new Color().setHex(json.sheenColor); + if (json.sheenRoughness !== undefined) + material.sheenRoughness = json.sheenRoughness; + if (json.emissive !== undefined && material.emissive !== undefined) + material.emissive.setHex(json.emissive); + if (json.specular !== undefined && material.specular !== undefined) + material.specular.setHex(json.specular); + if (json.specularIntensity !== undefined) + material.specularIntensity = json.specularIntensity; + if (json.specularColor !== undefined && material.specularColor !== undefined) + material.specularColor.setHex(json.specularColor); + if (json.shininess !== undefined) + material.shininess = json.shininess; + if (json.clearcoat !== undefined) + material.clearcoat = json.clearcoat; + if (json.clearcoatRoughness !== undefined) + material.clearcoatRoughness = json.clearcoatRoughness; + if (json.dispersion !== undefined) + material.dispersion = json.dispersion; + if (json.iridescence !== undefined) + material.iridescence = json.iridescence; + if (json.iridescenceIOR !== undefined) + material.iridescenceIOR = json.iridescenceIOR; + if (json.iridescenceThicknessRange !== undefined) + material.iridescenceThicknessRange = json.iridescenceThicknessRange; + if (json.transmission !== undefined) + material.transmission = json.transmission; + if (json.thickness !== undefined) + material.thickness = json.thickness; + if (json.attenuationDistance !== undefined) + material.attenuationDistance = json.attenuationDistance; + if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) + material.attenuationColor.setHex(json.attenuationColor); + if (json.anisotropy !== undefined) + material.anisotropy = json.anisotropy; + if (json.anisotropyRotation !== undefined) + material.anisotropyRotation = json.anisotropyRotation; + if (json.fog !== undefined) + material.fog = json.fog; + if (json.flatShading !== undefined) + material.flatShading = json.flatShading; + if (json.blending !== undefined) + material.blending = json.blending; + if (json.combine !== undefined) + material.combine = json.combine; + if (json.side !== undefined) + material.side = json.side; + if (json.shadowSide !== undefined) + material.shadowSide = json.shadowSide; + if (json.opacity !== undefined) + material.opacity = json.opacity; + if (json.transparent !== undefined) + material.transparent = json.transparent; + if (json.alphaTest !== undefined) + material.alphaTest = json.alphaTest; + if (json.alphaHash !== undefined) + material.alphaHash = json.alphaHash; + if (json.depthFunc !== undefined) + material.depthFunc = json.depthFunc; + if (json.depthTest !== undefined) + material.depthTest = json.depthTest; + if (json.depthWrite !== undefined) + material.depthWrite = json.depthWrite; + if (json.colorWrite !== undefined) + material.colorWrite = json.colorWrite; + if (json.blendSrc !== undefined) + material.blendSrc = json.blendSrc; + if (json.blendDst !== undefined) + material.blendDst = json.blendDst; + if (json.blendEquation !== undefined) + material.blendEquation = json.blendEquation; + if (json.blendSrcAlpha !== undefined) + material.blendSrcAlpha = json.blendSrcAlpha; + if (json.blendDstAlpha !== undefined) + material.blendDstAlpha = json.blendDstAlpha; + if (json.blendEquationAlpha !== undefined) + material.blendEquationAlpha = json.blendEquationAlpha; + if (json.blendColor !== undefined && material.blendColor !== undefined) + material.blendColor.setHex(json.blendColor); + if (json.blendAlpha !== undefined) + material.blendAlpha = json.blendAlpha; + if (json.stencilWriteMask !== undefined) + material.stencilWriteMask = json.stencilWriteMask; + if (json.stencilFunc !== undefined) + material.stencilFunc = json.stencilFunc; + if (json.stencilRef !== undefined) + material.stencilRef = json.stencilRef; + if (json.stencilFuncMask !== undefined) + material.stencilFuncMask = json.stencilFuncMask; + if (json.stencilFail !== undefined) + material.stencilFail = json.stencilFail; + if (json.stencilZFail !== undefined) + material.stencilZFail = json.stencilZFail; + if (json.stencilZPass !== undefined) + material.stencilZPass = json.stencilZPass; + if (json.stencilWrite !== undefined) + material.stencilWrite = json.stencilWrite; + if (json.wireframe !== undefined) + material.wireframe = json.wireframe; + if (json.wireframeLinewidth !== undefined) + material.wireframeLinewidth = json.wireframeLinewidth; + if (json.wireframeLinecap !== undefined) + material.wireframeLinecap = json.wireframeLinecap; + if (json.wireframeLinejoin !== undefined) + material.wireframeLinejoin = json.wireframeLinejoin; + if (json.rotation !== undefined) + material.rotation = json.rotation; + if (json.linewidth !== undefined) + material.linewidth = json.linewidth; + if (json.dashSize !== undefined) + material.dashSize = json.dashSize; + if (json.gapSize !== undefined) + material.gapSize = json.gapSize; + if (json.scale !== undefined) + material.scale = json.scale; + if (json.polygonOffset !== undefined) + material.polygonOffset = json.polygonOffset; + if (json.polygonOffsetFactor !== undefined) + material.polygonOffsetFactor = json.polygonOffsetFactor; + if (json.polygonOffsetUnits !== undefined) + material.polygonOffsetUnits = json.polygonOffsetUnits; + if (json.dithering !== undefined) + material.dithering = json.dithering; + if (json.alphaToCoverage !== undefined) + material.alphaToCoverage = json.alphaToCoverage; + if (json.premultipliedAlpha !== undefined) + material.premultipliedAlpha = json.premultipliedAlpha; + if (json.forceSinglePass !== undefined) + material.forceSinglePass = json.forceSinglePass; + if (json.visible !== undefined) + material.visible = json.visible; + if (json.toneMapped !== undefined) + material.toneMapped = json.toneMapped; + if (json.userData !== undefined) + material.userData = json.userData; + if (json.vertexColors !== undefined) { + if (typeof json.vertexColors === "number") { + material.vertexColors = json.vertexColors > 0 ? true : false; + } else { + material.vertexColors = json.vertexColors; + } + } + if (json.uniforms !== undefined) { + for (const name2 in json.uniforms) { + const uniform = json.uniforms[name2]; + material.uniforms[name2] = {}; + switch (uniform.type) { + case "t": + material.uniforms[name2].value = getTexture(uniform.value); + break; + case "c": + material.uniforms[name2].value = new Color().setHex(uniform.value); + break; + case "v2": + material.uniforms[name2].value = new Vector2().fromArray(uniform.value); + break; + case "v3": + material.uniforms[name2].value = new Vector3().fromArray(uniform.value); + break; + case "v4": + material.uniforms[name2].value = new Vector4().fromArray(uniform.value); + break; + case "m3": + material.uniforms[name2].value = new Matrix3().fromArray(uniform.value); + break; + case "m4": + material.uniforms[name2].value = new Matrix4().fromArray(uniform.value); + break; + default: + material.uniforms[name2].value = uniform.value; + } + } + } + if (json.defines !== undefined) + material.defines = json.defines; + if (json.vertexShader !== undefined) + material.vertexShader = json.vertexShader; + if (json.fragmentShader !== undefined) + material.fragmentShader = json.fragmentShader; + if (json.glslVersion !== undefined) + material.glslVersion = json.glslVersion; + if (json.extensions !== undefined) { + for (const key2 in json.extensions) { + material.extensions[key2] = json.extensions[key2]; + } + } + if (json.lights !== undefined) + material.lights = json.lights; + if (json.clipping !== undefined) + material.clipping = json.clipping; + if (json.size !== undefined) + material.size = json.size; + if (json.sizeAttenuation !== undefined) + material.sizeAttenuation = json.sizeAttenuation; + if (json.map !== undefined) + material.map = getTexture(json.map); + if (json.matcap !== undefined) + material.matcap = getTexture(json.matcap); + if (json.alphaMap !== undefined) + material.alphaMap = getTexture(json.alphaMap); + if (json.bumpMap !== undefined) + material.bumpMap = getTexture(json.bumpMap); + if (json.bumpScale !== undefined) + material.bumpScale = json.bumpScale; + if (json.normalMap !== undefined) + material.normalMap = getTexture(json.normalMap); + if (json.normalMapType !== undefined) + material.normalMapType = json.normalMapType; + if (json.normalScale !== undefined) { + let normalScale = json.normalScale; + if (Array.isArray(normalScale) === false) { + normalScale = [normalScale, normalScale]; + } + material.normalScale = new Vector2().fromArray(normalScale); + } + if (json.displacementMap !== undefined) + material.displacementMap = getTexture(json.displacementMap); + if (json.displacementScale !== undefined) + material.displacementScale = json.displacementScale; + if (json.displacementBias !== undefined) + material.displacementBias = json.displacementBias; + if (json.roughnessMap !== undefined) + material.roughnessMap = getTexture(json.roughnessMap); + if (json.metalnessMap !== undefined) + material.metalnessMap = getTexture(json.metalnessMap); + if (json.emissiveMap !== undefined) + material.emissiveMap = getTexture(json.emissiveMap); + if (json.emissiveIntensity !== undefined) + material.emissiveIntensity = json.emissiveIntensity; + if (json.specularMap !== undefined) + material.specularMap = getTexture(json.specularMap); + if (json.specularIntensityMap !== undefined) + material.specularIntensityMap = getTexture(json.specularIntensityMap); + if (json.specularColorMap !== undefined) + material.specularColorMap = getTexture(json.specularColorMap); + if (json.envMap !== undefined) + material.envMap = getTexture(json.envMap); + if (json.envMapRotation !== undefined) + material.envMapRotation.fromArray(json.envMapRotation); + if (json.envMapIntensity !== undefined) + material.envMapIntensity = json.envMapIntensity; + if (json.reflectivity !== undefined) + material.reflectivity = json.reflectivity; + if (json.refractionRatio !== undefined) + material.refractionRatio = json.refractionRatio; + if (json.lightMap !== undefined) + material.lightMap = getTexture(json.lightMap); + if (json.lightMapIntensity !== undefined) + material.lightMapIntensity = json.lightMapIntensity; + if (json.aoMap !== undefined) + material.aoMap = getTexture(json.aoMap); + if (json.aoMapIntensity !== undefined) + material.aoMapIntensity = json.aoMapIntensity; + if (json.gradientMap !== undefined) + material.gradientMap = getTexture(json.gradientMap); + if (json.clearcoatMap !== undefined) + material.clearcoatMap = getTexture(json.clearcoatMap); + if (json.clearcoatRoughnessMap !== undefined) + material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap); + if (json.clearcoatNormalMap !== undefined) + material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap); + if (json.clearcoatNormalScale !== undefined) + material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale); + if (json.iridescenceMap !== undefined) + material.iridescenceMap = getTexture(json.iridescenceMap); + if (json.iridescenceThicknessMap !== undefined) + material.iridescenceThicknessMap = getTexture(json.iridescenceThicknessMap); + if (json.transmissionMap !== undefined) + material.transmissionMap = getTexture(json.transmissionMap); + if (json.thicknessMap !== undefined) + material.thicknessMap = getTexture(json.thicknessMap); + if (json.anisotropyMap !== undefined) + material.anisotropyMap = getTexture(json.anisotropyMap); + if (json.sheenColorMap !== undefined) + material.sheenColorMap = getTexture(json.sheenColorMap); + if (json.sheenRoughnessMap !== undefined) + material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap); + return material; + } + setTextures(value2) { + this.textures = value2; + return this; + } + createMaterialFromType(type) { + return MaterialLoader.createMaterialFromType(type); + } + static createMaterialFromType(type) { + const materialLib = { + ShadowMaterial, + SpriteMaterial, + RawShaderMaterial, + ShaderMaterial, + PointsMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MeshPhongMaterial, + MeshToonMaterial, + MeshNormalMaterial, + MeshLambertMaterial, + MeshDepthMaterial, + MeshDistanceMaterial, + MeshBasicMaterial, + MeshMatcapMaterial, + LineDashedMaterial, + LineBasicMaterial, + Material + }; + return new materialLib[type]; + } +} + +class LoaderUtils { + static decodeText(array) { + console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."); + if (typeof TextDecoder !== "undefined") { + return new TextDecoder().decode(array); + } + let s = ""; + for (let i = 0, il = array.length;i < il; i++) { + s += String.fromCharCode(array[i]); + } + try { + return decodeURIComponent(escape(s)); + } catch (e) { + return s; + } + } + static extractUrlBase(url) { + const index2 = url.lastIndexOf("/"); + if (index2 === -1) + return "./"; + return url.slice(0, index2 + 1); + } + static resolveURL(url, path) { + if (typeof url !== "string" || url === "") + return ""; + if (/^https?:\/\//i.test(path) && /^\//.test(url)) { + path = path.replace(/(^https?:\/\/[^\/]+).*/i, "$1"); + } + if (/^(https?:)?\/\//i.test(url)) + return url; + if (/^data:.*,.*$/i.test(url)) + return url; + if (/^blob:.*$/i.test(url)) + return url; + return path + url; + } +} + +class InstancedBufferGeometry extends BufferGeometry { + constructor() { + super(); + this.isInstancedBufferGeometry = true; + this.type = "InstancedBufferGeometry"; + this.instanceCount = Infinity; + } + copy(source) { + super.copy(source); + this.instanceCount = source.instanceCount; + return this; + } + toJSON() { + const data2 = super.toJSON(); + data2.instanceCount = this.instanceCount; + data2.isInstancedBufferGeometry = true; + return data2; + } +} + +class BufferGeometryLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(scope.manager); + loader.setPath(scope.path); + loader.setRequestHeader(scope.requestHeader); + loader.setWithCredentials(scope.withCredentials); + loader.load(url, function(text2) { + try { + onLoad(scope.parse(JSON.parse(text2))); + } catch (e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + }, onProgress, onError); + } + parse(json) { + const interleavedBufferMap = {}; + const arrayBufferMap = {}; + function getInterleavedBuffer(json2, uuid) { + if (interleavedBufferMap[uuid] !== undefined) + return interleavedBufferMap[uuid]; + const interleavedBuffers = json2.interleavedBuffers; + const interleavedBuffer = interleavedBuffers[uuid]; + const buffer = getArrayBuffer(json2, interleavedBuffer.buffer); + const array = getTypedArray(interleavedBuffer.type, buffer); + const ib = new InterleavedBuffer(array, interleavedBuffer.stride); + ib.uuid = interleavedBuffer.uuid; + interleavedBufferMap[uuid] = ib; + return ib; + } + function getArrayBuffer(json2, uuid) { + if (arrayBufferMap[uuid] !== undefined) + return arrayBufferMap[uuid]; + const arrayBuffers = json2.arrayBuffers; + const arrayBuffer = arrayBuffers[uuid]; + const ab = new Uint32Array(arrayBuffer).buffer; + arrayBufferMap[uuid] = ab; + return ab; + } + const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry : new BufferGeometry; + const index2 = json.data.index; + if (index2 !== undefined) { + const typedArray = getTypedArray(index2.type, index2.array); + geometry.setIndex(new BufferAttribute(typedArray, 1)); + } + const attributes = json.data.attributes; + for (const key2 in attributes) { + const attribute = attributes[key2]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray(attribute.type, attribute.array); + const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute; + bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== undefined) + bufferAttribute.name = attribute.name; + if (attribute.usage !== undefined) + bufferAttribute.setUsage(attribute.usage); + geometry.setAttribute(key2, bufferAttribute); + } + const morphAttributes = json.data.morphAttributes; + if (morphAttributes) { + for (const key2 in morphAttributes) { + const attributeArray = morphAttributes[key2]; + const array = []; + for (let i = 0, il = attributeArray.length;i < il; i++) { + const attribute = attributeArray[i]; + let bufferAttribute; + if (attribute.isInterleavedBufferAttribute) { + const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data); + bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized); + } else { + const typedArray = getTypedArray(attribute.type, attribute.array); + bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized); + } + if (attribute.name !== undefined) + bufferAttribute.name = attribute.name; + array.push(bufferAttribute); + } + geometry.morphAttributes[key2] = array; + } + } + const morphTargetsRelative = json.data.morphTargetsRelative; + if (morphTargetsRelative) { + geometry.morphTargetsRelative = true; + } + const groups = json.data.groups || json.data.drawcalls || json.data.offsets; + if (groups !== undefined) { + for (let i = 0, n = groups.length;i !== n; ++i) { + const group = groups[i]; + geometry.addGroup(group.start, group.count, group.materialIndex); + } + } + const boundingSphere = json.data.boundingSphere; + if (boundingSphere !== undefined) { + const center = new Vector3; + if (boundingSphere.center !== undefined) { + center.fromArray(boundingSphere.center); + } + geometry.boundingSphere = new Sphere(center, boundingSphere.radius); + } + if (json.name) + geometry.name = json.name; + if (json.userData) + geometry.userData = json.userData; + return geometry; + } +} + +class ObjectLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(text2) { + let json = null; + try { + json = JSON.parse(text2); + } catch (error) { + if (onError !== undefined) + onError(error); + console.error("THREE:ObjectLoader: Can't parse " + url + ".", error.message); + return; + } + const metadata = json.metadata; + if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === "geometry") { + if (onError !== undefined) + onError(new Error("THREE.ObjectLoader: Can't load " + url)); + console.error("THREE.ObjectLoader: Can't load " + url); + return; + } + scope.parse(json, onLoad); + }, onProgress, onError); + } + async loadAsync(url, onProgress) { + const scope = this; + const path = this.path === "" ? LoaderUtils.extractUrlBase(url) : this.path; + this.resourcePath = this.resourcePath || path; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + const text2 = await loader.loadAsync(url, onProgress); + const json = JSON.parse(text2); + const metadata = json.metadata; + if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === "geometry") { + throw new Error("THREE.ObjectLoader: Can't load " + url); + } + return await scope.parseAsync(json); + } + parse(json, onLoad) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = this.parseImages(json.images, function() { + if (onLoad !== undefined) + onLoad(object); + }); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + if (onLoad !== undefined) { + let hasImages = false; + for (const uuid in images) { + if (images[uuid].data instanceof HTMLImageElement) { + hasImages = true; + break; + } + } + if (hasImages === false) + onLoad(object); + } + return object; + } + async parseAsync(json) { + const animations = this.parseAnimations(json.animations); + const shapes = this.parseShapes(json.shapes); + const geometries = this.parseGeometries(json.geometries, shapes); + const images = await this.parseImagesAsync(json.images); + const textures = this.parseTextures(json.textures, images); + const materials = this.parseMaterials(json.materials, textures); + const object = this.parseObject(json.object, geometries, materials, textures, animations); + const skeletons = this.parseSkeletons(json.skeletons, object); + this.bindSkeletons(object, skeletons); + this.bindLightTargets(object); + return object; + } + parseShapes(json) { + const shapes = {}; + if (json !== undefined) { + for (let i = 0, l = json.length;i < l; i++) { + const shape = new Shape().fromJSON(json[i]); + shapes[shape.uuid] = shape; + } + } + return shapes; + } + parseSkeletons(json, object) { + const skeletons = {}; + const bones = {}; + object.traverse(function(child) { + if (child.isBone) + bones[child.uuid] = child; + }); + if (json !== undefined) { + for (let i = 0, l = json.length;i < l; i++) { + const skeleton = new Skeleton().fromJSON(json[i], bones); + skeletons[skeleton.uuid] = skeleton; + } + } + return skeletons; + } + parseGeometries(json, shapes) { + const geometries = {}; + if (json !== undefined) { + const bufferGeometryLoader = new BufferGeometryLoader; + for (let i = 0, l = json.length;i < l; i++) { + let geometry; + const data2 = json[i]; + switch (data2.type) { + case "BufferGeometry": + case "InstancedBufferGeometry": + geometry = bufferGeometryLoader.parse(data2); + break; + default: + if (data2.type in Geometries) { + geometry = Geometries[data2.type].fromJSON(data2, shapes); + } else { + console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data2.type}"`); + } + } + geometry.uuid = data2.uuid; + if (data2.name !== undefined) + geometry.name = data2.name; + if (data2.userData !== undefined) + geometry.userData = data2.userData; + geometries[data2.uuid] = geometry; + } + } + return geometries; + } + parseMaterials(json, textures) { + const cache = {}; + const materials = {}; + if (json !== undefined) { + const loader = new MaterialLoader; + loader.setTextures(textures); + for (let i = 0, l = json.length;i < l; i++) { + const data2 = json[i]; + if (cache[data2.uuid] === undefined) { + cache[data2.uuid] = loader.parse(data2); + } + materials[data2.uuid] = cache[data2.uuid]; + } + } + return materials; + } + parseAnimations(json) { + const animations = {}; + if (json !== undefined) { + for (let i = 0;i < json.length; i++) { + const data2 = json[i]; + const clip = AnimationClip.parse(data2); + animations[clip.uuid] = clip; + } + } + return animations; + } + parseImages(json, onLoad) { + const scope = this; + const images = {}; + let loader; + function loadImage(url) { + scope.manager.itemStart(url); + return loader.load(url, function() { + scope.manager.itemEnd(url); + }, undefined, function() { + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + } + function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return loadImage(path); + } else { + if (image.data) { + return { + data: getTypedArray(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== undefined && json.length > 0) { + const manager = new LoadingManager(onLoad); + loader = new ImageLoader(manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length;i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j = 0, jl = url.length;j < jl; j++) { + const currentUrl = url[j]; + const deserializedImage = deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source(imageArray); + } else { + const deserializedImage = deserializeImage(image.url); + images[image.uuid] = new Source(deserializedImage); + } + } + } + return images; + } + async parseImagesAsync(json) { + const scope = this; + const images = {}; + let loader; + async function deserializeImage(image) { + if (typeof image === "string") { + const url = image; + const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url; + return await loader.loadAsync(path); + } else { + if (image.data) { + return { + data: getTypedArray(image.type, image.data), + width: image.width, + height: image.height + }; + } else { + return null; + } + } + } + if (json !== undefined && json.length > 0) { + loader = new ImageLoader(this.manager); + loader.setCrossOrigin(this.crossOrigin); + for (let i = 0, il = json.length;i < il; i++) { + const image = json[i]; + const url = image.url; + if (Array.isArray(url)) { + const imageArray = []; + for (let j = 0, jl = url.length;j < jl; j++) { + const currentUrl = url[j]; + const deserializedImage = await deserializeImage(currentUrl); + if (deserializedImage !== null) { + if (deserializedImage instanceof HTMLImageElement) { + imageArray.push(deserializedImage); + } else { + imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height)); + } + } + } + images[image.uuid] = new Source(imageArray); + } else { + const deserializedImage = await deserializeImage(image.url); + images[image.uuid] = new Source(deserializedImage); + } + } + } + return images; + } + parseTextures(json, images) { + function parseConstant(value2, type) { + if (typeof value2 === "number") + return value2; + console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.", value2); + return type[value2]; + } + const textures = {}; + if (json !== undefined) { + for (let i = 0, l = json.length;i < l; i++) { + const data2 = json[i]; + if (data2.image === undefined) { + console.warn('THREE.ObjectLoader: No "image" specified for', data2.uuid); + } + if (images[data2.image] === undefined) { + console.warn("THREE.ObjectLoader: Undefined image", data2.image); + } + const source = images[data2.image]; + const image = source.data; + let texture; + if (Array.isArray(image)) { + texture = new CubeTexture; + if (image.length === 6) + texture.needsUpdate = true; + } else { + if (image && image.data) { + texture = new DataTexture; + } else { + texture = new Texture; + } + if (image) + texture.needsUpdate = true; + } + texture.source = source; + texture.uuid = data2.uuid; + if (data2.name !== undefined) + texture.name = data2.name; + if (data2.mapping !== undefined) + texture.mapping = parseConstant(data2.mapping, TEXTURE_MAPPING); + if (data2.channel !== undefined) + texture.channel = data2.channel; + if (data2.offset !== undefined) + texture.offset.fromArray(data2.offset); + if (data2.repeat !== undefined) + texture.repeat.fromArray(data2.repeat); + if (data2.center !== undefined) + texture.center.fromArray(data2.center); + if (data2.rotation !== undefined) + texture.rotation = data2.rotation; + if (data2.wrap !== undefined) { + texture.wrapS = parseConstant(data2.wrap[0], TEXTURE_WRAPPING); + texture.wrapT = parseConstant(data2.wrap[1], TEXTURE_WRAPPING); + } + if (data2.format !== undefined) + texture.format = data2.format; + if (data2.internalFormat !== undefined) + texture.internalFormat = data2.internalFormat; + if (data2.type !== undefined) + texture.type = data2.type; + if (data2.colorSpace !== undefined) + texture.colorSpace = data2.colorSpace; + if (data2.minFilter !== undefined) + texture.minFilter = parseConstant(data2.minFilter, TEXTURE_FILTER); + if (data2.magFilter !== undefined) + texture.magFilter = parseConstant(data2.magFilter, TEXTURE_FILTER); + if (data2.anisotropy !== undefined) + texture.anisotropy = data2.anisotropy; + if (data2.flipY !== undefined) + texture.flipY = data2.flipY; + if (data2.generateMipmaps !== undefined) + texture.generateMipmaps = data2.generateMipmaps; + if (data2.premultiplyAlpha !== undefined) + texture.premultiplyAlpha = data2.premultiplyAlpha; + if (data2.unpackAlignment !== undefined) + texture.unpackAlignment = data2.unpackAlignment; + if (data2.compareFunction !== undefined) + texture.compareFunction = data2.compareFunction; + if (data2.userData !== undefined) + texture.userData = data2.userData; + textures[data2.uuid] = texture; + } + } + return textures; + } + parseObject(data2, geometries, materials, textures, animations) { + let object; + function getGeometry(name2) { + if (geometries[name2] === undefined) { + console.warn("THREE.ObjectLoader: Undefined geometry", name2); + } + return geometries[name2]; + } + function getMaterial(name2) { + if (name2 === undefined) + return; + if (Array.isArray(name2)) { + const array = []; + for (let i = 0, l = name2.length;i < l; i++) { + const uuid = name2[i]; + if (materials[uuid] === undefined) { + console.warn("THREE.ObjectLoader: Undefined material", uuid); + } + array.push(materials[uuid]); + } + return array; + } + if (materials[name2] === undefined) { + console.warn("THREE.ObjectLoader: Undefined material", name2); + } + return materials[name2]; + } + function getTexture(uuid) { + if (textures[uuid] === undefined) { + console.warn("THREE.ObjectLoader: Undefined texture", uuid); + } + return textures[uuid]; + } + let geometry, material; + switch (data2.type) { + case "Scene": + object = new Scene; + if (data2.background !== undefined) { + if (Number.isInteger(data2.background)) { + object.background = new Color(data2.background); + } else { + object.background = getTexture(data2.background); + } + } + if (data2.environment !== undefined) { + object.environment = getTexture(data2.environment); + } + if (data2.fog !== undefined) { + if (data2.fog.type === "Fog") { + object.fog = new Fog(data2.fog.color, data2.fog.near, data2.fog.far); + } else if (data2.fog.type === "FogExp2") { + object.fog = new FogExp2(data2.fog.color, data2.fog.density); + } + if (data2.fog.name !== "") { + object.fog.name = data2.fog.name; + } + } + if (data2.backgroundBlurriness !== undefined) + object.backgroundBlurriness = data2.backgroundBlurriness; + if (data2.backgroundIntensity !== undefined) + object.backgroundIntensity = data2.backgroundIntensity; + if (data2.backgroundRotation !== undefined) + object.backgroundRotation.fromArray(data2.backgroundRotation); + if (data2.environmentIntensity !== undefined) + object.environmentIntensity = data2.environmentIntensity; + if (data2.environmentRotation !== undefined) + object.environmentRotation.fromArray(data2.environmentRotation); + break; + case "PerspectiveCamera": + object = new PerspectiveCamera(data2.fov, data2.aspect, data2.near, data2.far); + if (data2.focus !== undefined) + object.focus = data2.focus; + if (data2.zoom !== undefined) + object.zoom = data2.zoom; + if (data2.filmGauge !== undefined) + object.filmGauge = data2.filmGauge; + if (data2.filmOffset !== undefined) + object.filmOffset = data2.filmOffset; + if (data2.view !== undefined) + object.view = Object.assign({}, data2.view); + break; + case "OrthographicCamera": + object = new OrthographicCamera(data2.left, data2.right, data2.top, data2.bottom, data2.near, data2.far); + if (data2.zoom !== undefined) + object.zoom = data2.zoom; + if (data2.view !== undefined) + object.view = Object.assign({}, data2.view); + break; + case "AmbientLight": + object = new AmbientLight(data2.color, data2.intensity); + break; + case "DirectionalLight": + object = new DirectionalLight(data2.color, data2.intensity); + object.target = data2.target || ""; + break; + case "PointLight": + object = new PointLight(data2.color, data2.intensity, data2.distance, data2.decay); + break; + case "RectAreaLight": + object = new RectAreaLight(data2.color, data2.intensity, data2.width, data2.height); + break; + case "SpotLight": + object = new SpotLight(data2.color, data2.intensity, data2.distance, data2.angle, data2.penumbra, data2.decay); + object.target = data2.target || ""; + break; + case "HemisphereLight": + object = new HemisphereLight(data2.color, data2.groundColor, data2.intensity); + break; + case "LightProbe": + object = new LightProbe().fromJSON(data2); + break; + case "SkinnedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new SkinnedMesh(geometry, material); + if (data2.bindMode !== undefined) + object.bindMode = data2.bindMode; + if (data2.bindMatrix !== undefined) + object.bindMatrix.fromArray(data2.bindMatrix); + if (data2.skeleton !== undefined) + object.skeleton = data2.skeleton; + break; + case "Mesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new Mesh(geometry, material); + break; + case "InstancedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + const count = data2.count; + const instanceMatrix = data2.instanceMatrix; + const instanceColor = data2.instanceColor; + object = new InstancedMesh(geometry, material, count); + object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16); + if (instanceColor !== undefined) + object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize); + break; + case "BatchedMesh": + geometry = getGeometry(data2.geometry); + material = getMaterial(data2.material); + object = new BatchedMesh(data2.maxInstanceCount, data2.maxVertexCount, data2.maxIndexCount, material); + object.geometry = geometry; + object.perObjectFrustumCulled = data2.perObjectFrustumCulled; + object.sortObjects = data2.sortObjects; + object._drawRanges = data2.drawRanges; + object._reservedRanges = data2.reservedRanges; + object._visibility = data2.visibility; + object._active = data2.active; + object._bounds = data2.bounds.map((bound) => { + const box = new Box3; + box.min.fromArray(bound.boxMin); + box.max.fromArray(bound.boxMax); + const sphere = new Sphere; + sphere.radius = bound.sphereRadius; + sphere.center.fromArray(bound.sphereCenter); + return { + boxInitialized: bound.boxInitialized, + box, + sphereInitialized: bound.sphereInitialized, + sphere + }; + }); + object._maxInstanceCount = data2.maxInstanceCount; + object._maxVertexCount = data2.maxVertexCount; + object._maxIndexCount = data2.maxIndexCount; + object._geometryInitialized = data2.geometryInitialized; + object._geometryCount = data2.geometryCount; + object._matricesTexture = getTexture(data2.matricesTexture.uuid); + if (data2.colorsTexture !== undefined) + object._colorsTexture = getTexture(data2.colorsTexture.uuid); + break; + case "LOD": + object = new LOD; + break; + case "Line": + object = new Line(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "LineLoop": + object = new LineLoop(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "LineSegments": + object = new LineSegments(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "PointCloud": + case "Points": + object = new Points(getGeometry(data2.geometry), getMaterial(data2.material)); + break; + case "Sprite": + object = new Sprite(getMaterial(data2.material)); + break; + case "Group": + object = new Group; + break; + case "Bone": + object = new Bone; + break; + default: + object = new Object3D; + } + object.uuid = data2.uuid; + if (data2.name !== undefined) + object.name = data2.name; + if (data2.matrix !== undefined) { + object.matrix.fromArray(data2.matrix); + if (data2.matrixAutoUpdate !== undefined) + object.matrixAutoUpdate = data2.matrixAutoUpdate; + if (object.matrixAutoUpdate) + object.matrix.decompose(object.position, object.quaternion, object.scale); + } else { + if (data2.position !== undefined) + object.position.fromArray(data2.position); + if (data2.rotation !== undefined) + object.rotation.fromArray(data2.rotation); + if (data2.quaternion !== undefined) + object.quaternion.fromArray(data2.quaternion); + if (data2.scale !== undefined) + object.scale.fromArray(data2.scale); + } + if (data2.up !== undefined) + object.up.fromArray(data2.up); + if (data2.castShadow !== undefined) + object.castShadow = data2.castShadow; + if (data2.receiveShadow !== undefined) + object.receiveShadow = data2.receiveShadow; + if (data2.shadow) { + if (data2.shadow.intensity !== undefined) + object.shadow.intensity = data2.shadow.intensity; + if (data2.shadow.bias !== undefined) + object.shadow.bias = data2.shadow.bias; + if (data2.shadow.normalBias !== undefined) + object.shadow.normalBias = data2.shadow.normalBias; + if (data2.shadow.radius !== undefined) + object.shadow.radius = data2.shadow.radius; + if (data2.shadow.mapSize !== undefined) + object.shadow.mapSize.fromArray(data2.shadow.mapSize); + if (data2.shadow.camera !== undefined) + object.shadow.camera = this.parseObject(data2.shadow.camera); + } + if (data2.visible !== undefined) + object.visible = data2.visible; + if (data2.frustumCulled !== undefined) + object.frustumCulled = data2.frustumCulled; + if (data2.renderOrder !== undefined) + object.renderOrder = data2.renderOrder; + if (data2.userData !== undefined) + object.userData = data2.userData; + if (data2.layers !== undefined) + object.layers.mask = data2.layers; + if (data2.children !== undefined) { + const children = data2.children; + for (let i = 0;i < children.length; i++) { + object.add(this.parseObject(children[i], geometries, materials, textures, animations)); + } + } + if (data2.animations !== undefined) { + const objectAnimations = data2.animations; + for (let i = 0;i < objectAnimations.length; i++) { + const uuid = objectAnimations[i]; + object.animations.push(animations[uuid]); + } + } + if (data2.type === "LOD") { + if (data2.autoUpdate !== undefined) + object.autoUpdate = data2.autoUpdate; + const levels = data2.levels; + for (let l = 0;l < levels.length; l++) { + const level = levels[l]; + const child = object.getObjectByProperty("uuid", level.object); + if (child !== undefined) { + object.addLevel(child, level.distance, level.hysteresis); + } + } + } + return object; + } + bindSkeletons(object, skeletons) { + if (Object.keys(skeletons).length === 0) + return; + object.traverse(function(child) { + if (child.isSkinnedMesh === true && child.skeleton !== undefined) { + const skeleton = skeletons[child.skeleton]; + if (skeleton === undefined) { + console.warn("THREE.ObjectLoader: No skeleton found with UUID:", child.skeleton); + } else { + child.bind(skeleton, child.bindMatrix); + } + } + }); + } + bindLightTargets(object) { + object.traverse(function(child) { + if (child.isDirectionalLight || child.isSpotLight) { + const uuid = child.target; + const target = object.getObjectByProperty("uuid", uuid); + if (target !== undefined) { + child.target = target; + } else { + child.target = new Object3D; + } + } + }); + } +} +var TEXTURE_MAPPING = { + UVMapping, + CubeReflectionMapping, + CubeRefractionMapping, + EquirectangularReflectionMapping, + EquirectangularRefractionMapping, + CubeUVReflectionMapping +}; +var TEXTURE_WRAPPING = { + RepeatWrapping, + ClampToEdgeWrapping, + MirroredRepeatWrapping +}; +var TEXTURE_FILTER = { + NearestFilter, + NearestMipmapNearestFilter, + NearestMipmapLinearFilter, + LinearFilter, + LinearMipmapNearestFilter, + LinearMipmapLinearFilter +}; + +class ImageBitmapLoader extends Loader { + constructor(manager) { + super(manager); + this.isImageBitmapLoader = true; + if (typeof createImageBitmap === "undefined") { + console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."); + } + if (typeof fetch === "undefined") { + console.warn("THREE.ImageBitmapLoader: fetch() not supported."); + } + this.options = { premultiplyAlpha: "none" }; + } + setOptions(options) { + this.options = options; + return this; + } + load(url, onLoad, onProgress, onError) { + if (url === undefined) + url = ""; + if (this.path !== undefined) + url = this.path + url; + url = this.manager.resolveURL(url); + const scope = this; + const cached = Cache.get(url); + if (cached !== undefined) { + scope.manager.itemStart(url); + if (cached.then) { + cached.then((imageBitmap) => { + if (onLoad) + onLoad(imageBitmap); + scope.manager.itemEnd(url); + }).catch((e) => { + if (onError) + onError(e); + }); + return; + } + setTimeout(function() { + if (onLoad) + onLoad(cached); + scope.manager.itemEnd(url); + }, 0); + return cached; + } + const fetchOptions = {}; + fetchOptions.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include"; + fetchOptions.headers = this.requestHeader; + const promise = fetch(url, fetchOptions).then(function(res) { + return res.blob(); + }).then(function(blob) { + return createImageBitmap(blob, Object.assign(scope.options, { colorSpaceConversion: "none" })); + }).then(function(imageBitmap) { + Cache.add(url, imageBitmap); + if (onLoad) + onLoad(imageBitmap); + scope.manager.itemEnd(url); + return imageBitmap; + }).catch(function(e) { + if (onError) + onError(e); + Cache.remove(url); + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }); + Cache.add(url, promise); + scope.manager.itemStart(url); + } +} +var _context; + +class AudioContext { + static getContext() { + if (_context === undefined) { + _context = new (window.AudioContext || window.webkitAudioContext); + } + return _context; + } + static setContext(value2) { + _context = value2; + } +} + +class AudioLoader extends Loader { + constructor(manager) { + super(manager); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setPath(this.path); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(buffer) { + try { + const bufferCopy = buffer.slice(0); + const context = AudioContext.getContext(); + context.decodeAudioData(bufferCopy, function(audioBuffer) { + onLoad(audioBuffer); + }).catch(handleError); + } catch (e) { + handleError(e); + } + }, onProgress, onError); + function handleError(e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + } + } +} +var _eyeRight = /* @__PURE__ */ new Matrix4; +var _eyeLeft = /* @__PURE__ */ new Matrix4; +var _projectionMatrix = /* @__PURE__ */ new Matrix4; + +class StereoCamera { + constructor() { + this.type = "StereoCamera"; + this.aspect = 1; + this.eyeSep = 0.064; + this.cameraL = new PerspectiveCamera; + this.cameraL.layers.enable(1); + this.cameraL.matrixAutoUpdate = false; + this.cameraR = new PerspectiveCamera; + this.cameraR.layers.enable(2); + this.cameraR.matrixAutoUpdate = false; + this._cache = { + focus: null, + fov: null, + aspect: null, + near: null, + far: null, + zoom: null, + eyeSep: null + }; + } + update(camera) { + const cache = this._cache; + const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep; + if (needsUpdate) { + cache.focus = camera.focus; + cache.fov = camera.fov; + cache.aspect = camera.aspect * this.aspect; + cache.near = camera.near; + cache.far = camera.far; + cache.zoom = camera.zoom; + cache.eyeSep = this.eyeSep; + _projectionMatrix.copy(camera.projectionMatrix); + const eyeSepHalf = cache.eyeSep / 2; + const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus; + const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom; + let xmin, xmax; + _eyeLeft.elements[12] = -eyeSepHalf; + _eyeRight.elements[12] = eyeSepHalf; + xmin = -ymax * cache.aspect + eyeSepOnProjection; + xmax = ymax * cache.aspect + eyeSepOnProjection; + _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraL.projectionMatrix.copy(_projectionMatrix); + xmin = -ymax * cache.aspect - eyeSepOnProjection; + xmax = ymax * cache.aspect - eyeSepOnProjection; + _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin); + _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin); + this.cameraR.projectionMatrix.copy(_projectionMatrix); + } + this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft); + this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight); + } +} + +class ArrayCamera extends PerspectiveCamera { + constructor(array = []) { + super(); + this.isArrayCamera = true; + this.cameras = array; + this.index = 0; + } +} + +class Clock { + constructor(autoStart = true) { + this.autoStart = autoStart; + this.startTime = 0; + this.oldTime = 0; + this.elapsedTime = 0; + this.running = false; + } + start() { + this.startTime = now(); + this.oldTime = this.startTime; + this.elapsedTime = 0; + this.running = true; + } + stop() { + this.getElapsedTime(); + this.running = false; + this.autoStart = false; + } + getElapsedTime() { + this.getDelta(); + return this.elapsedTime; + } + getDelta() { + let diff = 0; + if (this.autoStart && !this.running) { + this.start(); + return 0; + } + if (this.running) { + const newTime = now(); + diff = (newTime - this.oldTime) / 1000; + this.oldTime = newTime; + this.elapsedTime += diff; + } + return diff; + } +} +function now() { + return performance.now(); +} +var _position$1 = /* @__PURE__ */ new Vector3; +var _quaternion$1 = /* @__PURE__ */ new Quaternion; +var _scale$1 = /* @__PURE__ */ new Vector3; +var _orientation$1 = /* @__PURE__ */ new Vector3; + +class AudioListener extends Object3D { + constructor() { + super(); + this.type = "AudioListener"; + this.context = AudioContext.getContext(); + this.gain = this.context.createGain(); + this.gain.connect(this.context.destination); + this.filter = null; + this.timeDelta = 0; + this._clock = new Clock; + } + getInput() { + return this.gain; + } + removeFilter() { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + this.gain.connect(this.context.destination); + this.filter = null; + } + return this; + } + getFilter() { + return this.filter; + } + setFilter(value2) { + if (this.filter !== null) { + this.gain.disconnect(this.filter); + this.filter.disconnect(this.context.destination); + } else { + this.gain.disconnect(this.context.destination); + } + this.filter = value2; + this.gain.connect(this.filter); + this.filter.connect(this.context.destination); + return this; + } + getMasterVolume() { + return this.gain.gain.value; + } + setMasterVolume(value2) { + this.gain.gain.setTargetAtTime(value2, this.context.currentTime, 0.01); + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + const listener = this.context.listener; + const up = this.up; + this.timeDelta = this._clock.getDelta(); + this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1); + _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1); + if (listener.positionX) { + const endTime = this.context.currentTime + this.timeDelta; + listener.positionX.linearRampToValueAtTime(_position$1.x, endTime); + listener.positionY.linearRampToValueAtTime(_position$1.y, endTime); + listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime); + listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime); + listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime); + listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime); + listener.upX.linearRampToValueAtTime(up.x, endTime); + listener.upY.linearRampToValueAtTime(up.y, endTime); + listener.upZ.linearRampToValueAtTime(up.z, endTime); + } else { + listener.setPosition(_position$1.x, _position$1.y, _position$1.z); + listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z); + } + } +} + +class Audio extends Object3D { + constructor(listener) { + super(); + this.type = "Audio"; + this.listener = listener; + this.context = listener.context; + this.gain = this.context.createGain(); + this.gain.connect(listener.getInput()); + this.autoplay = false; + this.buffer = null; + this.detune = 0; + this.loop = false; + this.loopStart = 0; + this.loopEnd = 0; + this.offset = 0; + this.duration = undefined; + this.playbackRate = 1; + this.isPlaying = false; + this.hasPlaybackControl = true; + this.source = null; + this.sourceType = "empty"; + this._startedAt = 0; + this._progress = 0; + this._connected = false; + this.filters = []; + } + getOutput() { + return this.gain; + } + setNodeSource(audioNode) { + this.hasPlaybackControl = false; + this.sourceType = "audioNode"; + this.source = audioNode; + this.connect(); + return this; + } + setMediaElementSource(mediaElement) { + this.hasPlaybackControl = false; + this.sourceType = "mediaNode"; + this.source = this.context.createMediaElementSource(mediaElement); + this.connect(); + return this; + } + setMediaStreamSource(mediaStream) { + this.hasPlaybackControl = false; + this.sourceType = "mediaStreamNode"; + this.source = this.context.createMediaStreamSource(mediaStream); + this.connect(); + return this; + } + setBuffer(audioBuffer) { + this.buffer = audioBuffer; + this.sourceType = "buffer"; + if (this.autoplay) + this.play(); + return this; + } + play(delay = 0) { + if (this.isPlaying === true) { + console.warn("THREE.Audio: Audio is already playing."); + return; + } + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._startedAt = this.context.currentTime + delay; + const source = this.context.createBufferSource(); + source.buffer = this.buffer; + source.loop = this.loop; + source.loopStart = this.loopStart; + source.loopEnd = this.loopEnd; + source.onended = this.onEnded.bind(this); + source.start(this._startedAt, this._progress + this.offset, this.duration); + this.isPlaying = true; + this.source = source; + this.setDetune(this.detune); + this.setPlaybackRate(this.playbackRate); + return this.connect(); + } + pause() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + if (this.isPlaying === true) { + this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate; + if (this.loop === true) { + this._progress = this._progress % (this.duration || this.buffer.duration); + } + this.source.stop(); + this.source.onended = null; + this.isPlaying = false; + } + return this; + } + stop(delay = 0) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this._progress = 0; + if (this.source !== null) { + this.source.stop(this.context.currentTime + delay); + this.source.onended = null; + } + this.isPlaying = false; + return this; + } + connect() { + if (this.filters.length > 0) { + this.source.connect(this.filters[0]); + for (let i = 1, l = this.filters.length;i < l; i++) { + this.filters[i - 1].connect(this.filters[i]); + } + this.filters[this.filters.length - 1].connect(this.getOutput()); + } else { + this.source.connect(this.getOutput()); + } + this._connected = true; + return this; + } + disconnect() { + if (this._connected === false) { + return; + } + if (this.filters.length > 0) { + this.source.disconnect(this.filters[0]); + for (let i = 1, l = this.filters.length;i < l; i++) { + this.filters[i - 1].disconnect(this.filters[i]); + } + this.filters[this.filters.length - 1].disconnect(this.getOutput()); + } else { + this.source.disconnect(this.getOutput()); + } + this._connected = false; + return this; + } + getFilters() { + return this.filters; + } + setFilters(value2) { + if (!value2) + value2 = []; + if (this._connected === true) { + this.disconnect(); + this.filters = value2.slice(); + this.connect(); + } else { + this.filters = value2.slice(); + } + return this; + } + setDetune(value2) { + this.detune = value2; + if (this.isPlaying === true && this.source.detune !== undefined) { + this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01); + } + return this; + } + getDetune() { + return this.detune; + } + getFilter() { + return this.getFilters()[0]; + } + setFilter(filter2) { + return this.setFilters(filter2 ? [filter2] : []); + } + setPlaybackRate(value2) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.playbackRate = value2; + if (this.isPlaying === true) { + this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01); + } + return this; + } + getPlaybackRate() { + return this.playbackRate; + } + onEnded() { + this.isPlaying = false; + this._progress = 0; + } + getLoop() { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return false; + } + return this.loop; + } + setLoop(value2) { + if (this.hasPlaybackControl === false) { + console.warn("THREE.Audio: this Audio has no playback control."); + return; + } + this.loop = value2; + if (this.isPlaying === true) { + this.source.loop = this.loop; + } + return this; + } + setLoopStart(value2) { + this.loopStart = value2; + return this; + } + setLoopEnd(value2) { + this.loopEnd = value2; + return this; + } + getVolume() { + return this.gain.gain.value; + } + setVolume(value2) { + this.gain.gain.setTargetAtTime(value2, this.context.currentTime, 0.01); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + if (source.sourceType !== "buffer") { + console.warn("THREE.Audio: Audio source type cannot be copied."); + return this; + } + this.autoplay = source.autoplay; + this.buffer = source.buffer; + this.detune = source.detune; + this.loop = source.loop; + this.loopStart = source.loopStart; + this.loopEnd = source.loopEnd; + this.offset = source.offset; + this.duration = source.duration; + this.playbackRate = source.playbackRate; + this.hasPlaybackControl = source.hasPlaybackControl; + this.sourceType = source.sourceType; + this.filters = source.filters.slice(); + return this; + } + clone(recursive) { + return new this.constructor(this.listener).copy(this, recursive); + } +} +var _position = /* @__PURE__ */ new Vector3; +var _quaternion = /* @__PURE__ */ new Quaternion; +var _scale = /* @__PURE__ */ new Vector3; +var _orientation = /* @__PURE__ */ new Vector3; + +class PositionalAudio extends Audio { + constructor(listener) { + super(listener); + this.panner = this.context.createPanner(); + this.panner.panningModel = "HRTF"; + this.panner.connect(this.gain); + } + connect() { + super.connect(); + this.panner.connect(this.gain); + } + disconnect() { + super.disconnect(); + this.panner.disconnect(this.gain); + } + getOutput() { + return this.panner; + } + getRefDistance() { + return this.panner.refDistance; + } + setRefDistance(value2) { + this.panner.refDistance = value2; + return this; + } + getRolloffFactor() { + return this.panner.rolloffFactor; + } + setRolloffFactor(value2) { + this.panner.rolloffFactor = value2; + return this; + } + getDistanceModel() { + return this.panner.distanceModel; + } + setDistanceModel(value2) { + this.panner.distanceModel = value2; + return this; + } + getMaxDistance() { + return this.panner.maxDistance; + } + setMaxDistance(value2) { + this.panner.maxDistance = value2; + return this; + } + setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) { + this.panner.coneInnerAngle = coneInnerAngle; + this.panner.coneOuterAngle = coneOuterAngle; + this.panner.coneOuterGain = coneOuterGain; + return this; + } + updateMatrixWorld(force) { + super.updateMatrixWorld(force); + if (this.hasPlaybackControl === true && this.isPlaying === false) + return; + this.matrixWorld.decompose(_position, _quaternion, _scale); + _orientation.set(0, 0, 1).applyQuaternion(_quaternion); + const panner = this.panner; + if (panner.positionX) { + const endTime = this.context.currentTime + this.listener.timeDelta; + panner.positionX.linearRampToValueAtTime(_position.x, endTime); + panner.positionY.linearRampToValueAtTime(_position.y, endTime); + panner.positionZ.linearRampToValueAtTime(_position.z, endTime); + panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime); + panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime); + panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime); + } else { + panner.setPosition(_position.x, _position.y, _position.z); + panner.setOrientation(_orientation.x, _orientation.y, _orientation.z); + } + } +} + +class AudioAnalyser { + constructor(audio, fftSize = 2048) { + this.analyser = audio.context.createAnalyser(); + this.analyser.fftSize = fftSize; + this.data = new Uint8Array(this.analyser.frequencyBinCount); + audio.getOutput().connect(this.analyser); + } + getFrequencyData() { + this.analyser.getByteFrequencyData(this.data); + return this.data; + } + getAverageFrequency() { + let value2 = 0; + const data2 = this.getFrequencyData(); + for (let i = 0;i < data2.length; i++) { + value2 += data2[i]; + } + return value2 / data2.length; + } +} + +class PropertyMixer { + constructor(binding, typeName, valueSize) { + this.binding = binding; + this.valueSize = valueSize; + let mixFunction, mixFunctionAdditive, setIdentity; + switch (typeName) { + case "quaternion": + mixFunction = this._slerp; + mixFunctionAdditive = this._slerpAdditive; + setIdentity = this._setAdditiveIdentityQuaternion; + this.buffer = new Float64Array(valueSize * 6); + this._workIndex = 5; + break; + case "string": + case "bool": + mixFunction = this._select; + mixFunctionAdditive = this._select; + setIdentity = this._setAdditiveIdentityOther; + this.buffer = new Array(valueSize * 5); + break; + default: + mixFunction = this._lerp; + mixFunctionAdditive = this._lerpAdditive; + setIdentity = this._setAdditiveIdentityNumeric; + this.buffer = new Float64Array(valueSize * 5); + } + this._mixBufferRegion = mixFunction; + this._mixBufferRegionAdditive = mixFunctionAdditive; + this._setIdentity = setIdentity; + this._origIndex = 3; + this._addIndex = 4; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + this.useCount = 0; + this.referenceCount = 0; + } + accumulate(accuIndex, weight) { + const buffer = this.buffer, stride = this.valueSize, offset = accuIndex * stride + stride; + let currentWeight = this.cumulativeWeight; + if (currentWeight === 0) { + for (let i = 0;i !== stride; ++i) { + buffer[offset + i] = buffer[i]; + } + currentWeight = weight; + } else { + currentWeight += weight; + const mix = weight / currentWeight; + this._mixBufferRegion(buffer, offset, 0, mix, stride); + } + this.cumulativeWeight = currentWeight; + } + accumulateAdditive(weight) { + const buffer = this.buffer, stride = this.valueSize, offset = stride * this._addIndex; + if (this.cumulativeWeightAdditive === 0) { + this._setIdentity(); + } + this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride); + this.cumulativeWeightAdditive += weight; + } + apply(accuIndex) { + const stride = this.valueSize, buffer = this.buffer, offset = accuIndex * stride + stride, weight = this.cumulativeWeight, weightAdditive = this.cumulativeWeightAdditive, binding = this.binding; + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + if (weight < 1) { + const originalValueOffset = stride * this._origIndex; + this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride); + } + if (weightAdditive > 0) { + this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride); + } + for (let i = stride, e = stride + stride;i !== e; ++i) { + if (buffer[i] !== buffer[i + stride]) { + binding.setValue(buffer, offset); + break; + } + } + } + saveOriginalState() { + const binding = this.binding; + const buffer = this.buffer, stride = this.valueSize, originalValueOffset = stride * this._origIndex; + binding.getValue(buffer, originalValueOffset); + for (let i = stride, e = originalValueOffset;i !== e; ++i) { + buffer[i] = buffer[originalValueOffset + i % stride]; + } + this._setIdentity(); + this.cumulativeWeight = 0; + this.cumulativeWeightAdditive = 0; + } + restoreOriginalState() { + const originalValueOffset = this.valueSize * 3; + this.binding.setValue(this.buffer, originalValueOffset); + } + _setAdditiveIdentityNumeric() { + const startIndex = this._addIndex * this.valueSize; + const endIndex = startIndex + this.valueSize; + for (let i = startIndex;i < endIndex; i++) { + this.buffer[i] = 0; + } + } + _setAdditiveIdentityQuaternion() { + this._setAdditiveIdentityNumeric(); + this.buffer[this._addIndex * this.valueSize + 3] = 1; + } + _setAdditiveIdentityOther() { + const startIndex = this._origIndex * this.valueSize; + const targetIndex = this._addIndex * this.valueSize; + for (let i = 0;i < this.valueSize; i++) { + this.buffer[targetIndex + i] = this.buffer[startIndex + i]; + } + } + _select(buffer, dstOffset, srcOffset, t, stride) { + if (t >= 0.5) { + for (let i = 0;i !== stride; ++i) { + buffer[dstOffset + i] = buffer[srcOffset + i]; + } + } + } + _slerp(buffer, dstOffset, srcOffset, t) { + Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t); + } + _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) { + const workOffset = this._workIndex * stride; + Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); + Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t); + } + _lerp(buffer, dstOffset, srcOffset, t, stride) { + const s = 1 - t; + for (let i = 0;i !== stride; ++i) { + const j = dstOffset + i; + buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t; + } + } + _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) { + for (let i = 0;i !== stride; ++i) { + const j = dstOffset + i; + buffer[j] = buffer[j] + buffer[srcOffset + i] * t; + } + } +} +var _RESERVED_CHARS_RE = "\\[\\]\\.:\\/"; +var _reservedRe = new RegExp("[" + _RESERVED_CHARS_RE + "]", "g"); +var _wordChar = "[^" + _RESERVED_CHARS_RE + "]"; +var _wordCharOrDot = "[^" + _RESERVED_CHARS_RE.replace("\\.", "") + "]"; +var _directoryRe = /* @__PURE__ */ /((?:WC+[\/:])*)/.source.replace("WC", _wordChar); +var _nodeRe = /* @__PURE__ */ /(WCOD+)?/.source.replace("WCOD", _wordCharOrDot); +var _objectRe = /* @__PURE__ */ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", _wordChar); +var _propertyRe = /* @__PURE__ */ /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", _wordChar); +var _trackRe = new RegExp("" + "^" + _directoryRe + _nodeRe + _objectRe + _propertyRe + "$"); +var _supportedObjectNames = ["material", "materials", "bones", "map"]; + +class Composite { + constructor(targetGroup, path, optionalParsedPath) { + const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path); + this._targetGroup = targetGroup; + this._bindings = targetGroup.subscribe_(path, parsedPath); + } + getValue(array, offset) { + this.bind(); + const firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[firstValidIndex]; + if (binding !== undefined) + binding.getValue(array, offset); + } + setValue(array, offset) { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) { + bindings[i].setValue(array, offset); + } + } + bind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) { + bindings[i].bind(); + } + } + unbind() { + const bindings = this._bindings; + for (let i = this._targetGroup.nCachedObjects_, n = bindings.length;i !== n; ++i) { + bindings[i].unbind(); + } + } +} + +class PropertyBinding { + constructor(rootNode, path, parsedPath) { + this.path = path; + this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path); + this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName); + this.rootNode = rootNode; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } + static create(root, path, parsedPath) { + if (!(root && root.isAnimationObjectGroup)) { + return new PropertyBinding(root, path, parsedPath); + } else { + return new PropertyBinding.Composite(root, path, parsedPath); + } + } + static sanitizeNodeName(name2) { + return name2.replace(/\s/g, "_").replace(_reservedRe, ""); + } + static parseTrackName(trackName) { + const matches = _trackRe.exec(trackName); + if (matches === null) { + throw new Error("PropertyBinding: Cannot parse trackName: " + trackName); + } + const results = { + nodeName: matches[2], + objectName: matches[3], + objectIndex: matches[4], + propertyName: matches[5], + propertyIndex: matches[6] + }; + const lastDot = results.nodeName && results.nodeName.lastIndexOf("."); + if (lastDot !== undefined && lastDot !== -1) { + const objectName = results.nodeName.substring(lastDot + 1); + if (_supportedObjectNames.indexOf(objectName) !== -1) { + results.nodeName = results.nodeName.substring(0, lastDot); + results.objectName = objectName; + } + } + if (results.propertyName === null || results.propertyName.length === 0) { + throw new Error("PropertyBinding: can not parse propertyName from trackName: " + trackName); + } + return results; + } + static findNode(root, nodeName) { + if (nodeName === undefined || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) { + return root; + } + if (root.skeleton) { + const bone = root.skeleton.getBoneByName(nodeName); + if (bone !== undefined) { + return bone; + } + } + if (root.children) { + const searchNodeSubtree = function(children) { + for (let i = 0;i < children.length; i++) { + const childNode = children[i]; + if (childNode.name === nodeName || childNode.uuid === nodeName) { + return childNode; + } + const result = searchNodeSubtree(childNode.children); + if (result) + return result; + } + return null; + }; + const subTreeNode = searchNodeSubtree(root.children); + if (subTreeNode) { + return subTreeNode; + } + } + return null; + } + _getValue_unavailable() { + } + _setValue_unavailable() { + } + _getValue_direct(buffer, offset) { + buffer[offset] = this.targetObject[this.propertyName]; + } + _getValue_array(buffer, offset) { + const source = this.resolvedProperty; + for (let i = 0, n = source.length;i !== n; ++i) { + buffer[offset++] = source[i]; + } + } + _getValue_arrayElement(buffer, offset) { + buffer[offset] = this.resolvedProperty[this.propertyIndex]; + } + _getValue_toArray(buffer, offset) { + this.resolvedProperty.toArray(buffer, offset); + } + _setValue_direct(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + } + _setValue_direct_setNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) { + this.targetObject[this.propertyName] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_array(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length;i !== n; ++i) { + dest[i] = buffer[offset++]; + } + } + _setValue_array_setNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length;i !== n; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.needsUpdate = true; + } + _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) { + const dest = this.resolvedProperty; + for (let i = 0, n = dest.length;i !== n; ++i) { + dest[i] = buffer[offset++]; + } + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_arrayElement(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + } + _setValue_arrayElement_setNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.needsUpdate = true; + } + _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty[this.propertyIndex] = buffer[offset]; + this.targetObject.matrixWorldNeedsUpdate = true; + } + _setValue_fromArray(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + } + _setValue_fromArray_setNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.needsUpdate = true; + } + _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) { + this.resolvedProperty.fromArray(buffer, offset); + this.targetObject.matrixWorldNeedsUpdate = true; + } + _getValue_unbound(targetArray, offset) { + this.bind(); + this.getValue(targetArray, offset); + } + _setValue_unbound(sourceArray, offset) { + this.bind(); + this.setValue(sourceArray, offset); + } + bind() { + let targetObject = this.node; + const parsedPath = this.parsedPath; + const objectName = parsedPath.objectName; + const propertyName = parsedPath.propertyName; + let propertyIndex = parsedPath.propertyIndex; + if (!targetObject) { + targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName); + this.node = targetObject; + } + this.getValue = this._getValue_unavailable; + this.setValue = this._setValue_unavailable; + if (!targetObject) { + console.warn("THREE.PropertyBinding: No target node found for track: " + this.path + "."); + return; + } + if (objectName) { + let objectIndex = parsedPath.objectIndex; + switch (objectName) { + case "materials": + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.materials) { + console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this); + return; + } + targetObject = targetObject.material.materials; + break; + case "bones": + if (!targetObject.skeleton) { + console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this); + return; + } + targetObject = targetObject.skeleton.bones; + for (let i = 0;i < targetObject.length; i++) { + if (targetObject[i].name === objectIndex) { + objectIndex = i; + break; + } + } + break; + case "map": + if ("map" in targetObject) { + targetObject = targetObject.map; + break; + } + if (!targetObject.material) { + console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); + return; + } + if (!targetObject.material.map) { + console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this); + return; + } + targetObject = targetObject.material.map; + break; + default: + if (targetObject[objectName] === undefined) { + console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this); + return; + } + targetObject = targetObject[objectName]; + } + if (objectIndex !== undefined) { + if (targetObject[objectIndex] === undefined) { + console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, targetObject); + return; + } + targetObject = targetObject[objectIndex]; + } + } + const nodeProperty = targetObject[propertyName]; + if (nodeProperty === undefined) { + const nodeName = parsedPath.nodeName; + console.error("THREE.PropertyBinding: Trying to update property for track: " + nodeName + "." + propertyName + " but it wasn't found.", targetObject); + return; + } + let versioning = this.Versioning.None; + this.targetObject = targetObject; + if (targetObject.isMaterial === true) { + versioning = this.Versioning.NeedsUpdate; + } else if (targetObject.isObject3D === true) { + versioning = this.Versioning.MatrixWorldNeedsUpdate; + } + let bindingType = this.BindingType.Direct; + if (propertyIndex !== undefined) { + if (propertyName === "morphTargetInfluences") { + if (!targetObject.geometry) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this); + return; + } + if (!targetObject.geometry.morphAttributes) { + console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this); + return; + } + if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) { + propertyIndex = targetObject.morphTargetDictionary[propertyIndex]; + } + } + bindingType = this.BindingType.ArrayElement; + this.resolvedProperty = nodeProperty; + this.propertyIndex = propertyIndex; + } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) { + bindingType = this.BindingType.HasFromToArray; + this.resolvedProperty = nodeProperty; + } else if (Array.isArray(nodeProperty)) { + bindingType = this.BindingType.EntireArray; + this.resolvedProperty = nodeProperty; + } else { + this.propertyName = propertyName; + } + this.getValue = this.GetterByBindingType[bindingType]; + this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning]; + } + unbind() { + this.node = null; + this.getValue = this._getValue_unbound; + this.setValue = this._setValue_unbound; + } +} +PropertyBinding.Composite = Composite; +PropertyBinding.prototype.BindingType = { + Direct: 0, + EntireArray: 1, + ArrayElement: 2, + HasFromToArray: 3 +}; +PropertyBinding.prototype.Versioning = { + None: 0, + NeedsUpdate: 1, + MatrixWorldNeedsUpdate: 2 +}; +PropertyBinding.prototype.GetterByBindingType = [ + PropertyBinding.prototype._getValue_direct, + PropertyBinding.prototype._getValue_array, + PropertyBinding.prototype._getValue_arrayElement, + PropertyBinding.prototype._getValue_toArray +]; +PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ + [ + PropertyBinding.prototype._setValue_direct, + PropertyBinding.prototype._setValue_direct_setNeedsUpdate, + PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding.prototype._setValue_array, + PropertyBinding.prototype._setValue_array_setNeedsUpdate, + PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding.prototype._setValue_arrayElement, + PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, + PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate + ], + [ + PropertyBinding.prototype._setValue_fromArray, + PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, + PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate + ] +]; + +class AnimationObjectGroup { + constructor() { + this.isAnimationObjectGroup = true; + this.uuid = generateUUID(); + this._objects = Array.prototype.slice.call(arguments); + this.nCachedObjects_ = 0; + const indices = {}; + this._indicesByUUID = indices; + for (let i = 0, n = arguments.length;i !== n; ++i) { + indices[arguments[i].uuid] = i; + } + this._paths = []; + this._parsedPaths = []; + this._bindings = []; + this._bindingsIndicesByPath = {}; + const scope = this; + this.stats = { + objects: { + get total() { + return scope._objects.length; + }, + get inUse() { + return this.total - scope.nCachedObjects_; + } + }, + get bindingsPerObject() { + return scope._bindings.length; + } + }; + } + add() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, nBindings = bindings.length; + let knownObject = undefined, nObjects = objects.length, nCachedObjects = this.nCachedObjects_; + for (let i = 0, n = arguments.length;i !== n; ++i) { + const object = arguments[i], uuid = object.uuid; + let index2 = indicesByUUID[uuid]; + if (index2 === undefined) { + index2 = nObjects++; + indicesByUUID[uuid] = index2; + objects.push(object); + for (let j = 0, m = nBindings;j !== m; ++j) { + bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j])); + } + } else if (index2 < nCachedObjects) { + knownObject = objects[index2]; + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex]; + indicesByUUID[lastCachedObject.uuid] = index2; + objects[index2] = lastCachedObject; + indicesByUUID[uuid] = firstActiveIndex; + objects[firstActiveIndex] = object; + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j], lastCached = bindingsForPath[firstActiveIndex]; + let binding = bindingsForPath[index2]; + bindingsForPath[index2] = lastCached; + if (binding === undefined) { + binding = new PropertyBinding(object, paths[j], parsedPaths[j]); + } + bindingsForPath[firstActiveIndex] = binding; + } + } else if (objects[index2] !== knownObject) { + console.error("THREE.AnimationObjectGroup: Different objects with the same UUID " + "detected. Clean the caches or recreate your infrastructure when reloading scenes."); + } + } + this.nCachedObjects_ = nCachedObjects; + } + remove() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_; + for (let i = 0, n = arguments.length;i !== n; ++i) { + const object = arguments[i], uuid = object.uuid, index2 = indicesByUUID[uuid]; + if (index2 !== undefined && index2 >= nCachedObjects) { + const lastCachedIndex = nCachedObjects++, firstActiveObject = objects[lastCachedIndex]; + indicesByUUID[firstActiveObject.uuid] = index2; + objects[index2] = firstActiveObject; + indicesByUUID[uuid] = lastCachedIndex; + objects[lastCachedIndex] = object; + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j], firstActive = bindingsForPath[lastCachedIndex], binding = bindingsForPath[index2]; + bindingsForPath[index2] = firstActive; + bindingsForPath[lastCachedIndex] = binding; + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + uncache() { + const objects = this._objects, indicesByUUID = this._indicesByUUID, bindings = this._bindings, nBindings = bindings.length; + let nCachedObjects = this.nCachedObjects_, nObjects = objects.length; + for (let i = 0, n = arguments.length;i !== n; ++i) { + const object = arguments[i], uuid = object.uuid, index2 = indicesByUUID[uuid]; + if (index2 !== undefined) { + delete indicesByUUID[uuid]; + if (index2 < nCachedObjects) { + const firstActiveIndex = --nCachedObjects, lastCachedObject = objects[firstActiveIndex], lastIndex = --nObjects, lastObject = objects[lastIndex]; + indicesByUUID[lastCachedObject.uuid] = index2; + objects[index2] = lastCachedObject; + indicesByUUID[lastObject.uuid] = firstActiveIndex; + objects[firstActiveIndex] = lastObject; + objects.pop(); + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j], lastCached = bindingsForPath[firstActiveIndex], last2 = bindingsForPath[lastIndex]; + bindingsForPath[index2] = lastCached; + bindingsForPath[firstActiveIndex] = last2; + bindingsForPath.pop(); + } + } else { + const lastIndex = --nObjects, lastObject = objects[lastIndex]; + if (lastIndex > 0) { + indicesByUUID[lastObject.uuid] = index2; + } + objects[index2] = lastObject; + objects.pop(); + for (let j = 0, m = nBindings;j !== m; ++j) { + const bindingsForPath = bindings[j]; + bindingsForPath[index2] = bindingsForPath[lastIndex]; + bindingsForPath.pop(); + } + } + } + } + this.nCachedObjects_ = nCachedObjects; + } + subscribe_(path, parsedPath) { + const indicesByPath = this._bindingsIndicesByPath; + let index2 = indicesByPath[path]; + const bindings = this._bindings; + if (index2 !== undefined) + return bindings[index2]; + const paths = this._paths, parsedPaths = this._parsedPaths, objects = this._objects, nObjects = objects.length, nCachedObjects = this.nCachedObjects_, bindingsForPath = new Array(nObjects); + index2 = bindings.length; + indicesByPath[path] = index2; + paths.push(path); + parsedPaths.push(parsedPath); + bindings.push(bindingsForPath); + for (let i = nCachedObjects, n = objects.length;i !== n; ++i) { + const object = objects[i]; + bindingsForPath[i] = new PropertyBinding(object, path, parsedPath); + } + return bindingsForPath; + } + unsubscribe_(path) { + const indicesByPath = this._bindingsIndicesByPath, index2 = indicesByPath[path]; + if (index2 !== undefined) { + const paths = this._paths, parsedPaths = this._parsedPaths, bindings = this._bindings, lastBindingsIndex = bindings.length - 1, lastBindings = bindings[lastBindingsIndex], lastBindingsPath = path[lastBindingsIndex]; + indicesByPath[lastBindingsPath] = index2; + bindings[index2] = lastBindings; + bindings.pop(); + parsedPaths[index2] = parsedPaths[lastBindingsIndex]; + parsedPaths.pop(); + paths[index2] = paths[lastBindingsIndex]; + paths.pop(); + } + } +} + +class AnimationAction { + constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) { + this._mixer = mixer; + this._clip = clip; + this._localRoot = localRoot; + this.blendMode = blendMode; + const tracks = clip.tracks, nTracks = tracks.length, interpolants = new Array(nTracks); + const interpolantSettings = { + endingStart: ZeroCurvatureEnding, + endingEnd: ZeroCurvatureEnding + }; + for (let i = 0;i !== nTracks; ++i) { + const interpolant = tracks[i].createInterpolant(null); + interpolants[i] = interpolant; + interpolant.settings = interpolantSettings; + } + this._interpolantSettings = interpolantSettings; + this._interpolants = interpolants; + this._propertyBindings = new Array(nTracks); + this._cacheIndex = null; + this._byClipCacheIndex = null; + this._timeScaleInterpolant = null; + this._weightInterpolant = null; + this.loop = LoopRepeat; + this._loopCount = -1; + this._startTime = null; + this.time = 0; + this.timeScale = 1; + this._effectiveTimeScale = 1; + this.weight = 1; + this._effectiveWeight = 1; + this.repetitions = Infinity; + this.paused = false; + this.enabled = true; + this.clampWhenFinished = false; + this.zeroSlopeAtStart = true; + this.zeroSlopeAtEnd = true; + } + play() { + this._mixer._activateAction(this); + return this; + } + stop() { + this._mixer._deactivateAction(this); + return this.reset(); + } + reset() { + this.paused = false; + this.enabled = true; + this.time = 0; + this._loopCount = -1; + this._startTime = null; + return this.stopFading().stopWarping(); + } + isRunning() { + return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this); + } + isScheduled() { + return this._mixer._isActiveAction(this); + } + startAt(time2) { + this._startTime = time2; + return this; + } + setLoop(mode, repetitions) { + this.loop = mode; + this.repetitions = repetitions; + return this; + } + setEffectiveWeight(weight) { + this.weight = weight; + this._effectiveWeight = this.enabled ? weight : 0; + return this.stopFading(); + } + getEffectiveWeight() { + return this._effectiveWeight; + } + fadeIn(duration) { + return this._scheduleFading(duration, 0, 1); + } + fadeOut(duration) { + return this._scheduleFading(duration, 1, 0); + } + crossFadeFrom(fadeOutAction, duration, warp) { + fadeOutAction.fadeOut(duration); + this.fadeIn(duration); + if (warp) { + const fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, startEndRatio = fadeOutDuration / fadeInDuration, endStartRatio = fadeInDuration / fadeOutDuration; + fadeOutAction.warp(1, startEndRatio, duration); + this.warp(endStartRatio, 1, duration); + } + return this; + } + crossFadeTo(fadeInAction, duration, warp) { + return fadeInAction.crossFadeFrom(this, duration, warp); + } + stopFading() { + const weightInterpolant = this._weightInterpolant; + if (weightInterpolant !== null) { + this._weightInterpolant = null; + this._mixer._takeBackControlInterpolant(weightInterpolant); + } + return this; + } + setEffectiveTimeScale(timeScale) { + this.timeScale = timeScale; + this._effectiveTimeScale = this.paused ? 0 : timeScale; + return this.stopWarping(); + } + getEffectiveTimeScale() { + return this._effectiveTimeScale; + } + setDuration(duration) { + this.timeScale = this._clip.duration / duration; + return this.stopWarping(); + } + syncWith(action) { + this.time = action.time; + this.timeScale = action.timeScale; + return this.stopWarping(); + } + halt(duration) { + return this.warp(this._effectiveTimeScale, 0, duration); + } + warp(startTimeScale, endTimeScale, duration) { + const mixer = this._mixer, now2 = mixer.time, timeScale = this.timeScale; + let interpolant = this._timeScaleInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._timeScaleInterpolant = interpolant; + } + const { parameterPositions: times, sampleValues: values2 } = interpolant; + times[0] = now2; + times[1] = now2 + duration; + values2[0] = startTimeScale / timeScale; + values2[1] = endTimeScale / timeScale; + return this; + } + stopWarping() { + const timeScaleInterpolant = this._timeScaleInterpolant; + if (timeScaleInterpolant !== null) { + this._timeScaleInterpolant = null; + this._mixer._takeBackControlInterpolant(timeScaleInterpolant); + } + return this; + } + getMixer() { + return this._mixer; + } + getClip() { + return this._clip; + } + getRoot() { + return this._localRoot || this._mixer._root; + } + _update(time2, deltaTime, timeDirection, accuIndex) { + if (!this.enabled) { + this._updateWeight(time2); + return; + } + const startTime = this._startTime; + if (startTime !== null) { + const timeRunning = (time2 - startTime) * timeDirection; + if (timeRunning < 0 || timeDirection === 0) { + deltaTime = 0; + } else { + this._startTime = null; + deltaTime = timeDirection * timeRunning; + } + } + deltaTime *= this._updateTimeScale(time2); + const clipTime = this._updateTime(deltaTime); + const weight = this._updateWeight(time2); + if (weight > 0) { + const interpolants = this._interpolants; + const propertyMixers = this._propertyBindings; + switch (this.blendMode) { + case AdditiveAnimationBlendMode: + for (let j = 0, m = interpolants.length;j !== m; ++j) { + interpolants[j].evaluate(clipTime); + propertyMixers[j].accumulateAdditive(weight); + } + break; + case NormalAnimationBlendMode: + default: + for (let j = 0, m = interpolants.length;j !== m; ++j) { + interpolants[j].evaluate(clipTime); + propertyMixers[j].accumulate(accuIndex, weight); + } + } + } + } + _updateWeight(time2) { + let weight = 0; + if (this.enabled) { + weight = this.weight; + const interpolant = this._weightInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time2)[0]; + weight *= interpolantValue; + if (time2 > interpolant.parameterPositions[1]) { + this.stopFading(); + if (interpolantValue === 0) { + this.enabled = false; + } + } + } + } + this._effectiveWeight = weight; + return weight; + } + _updateTimeScale(time2) { + let timeScale = 0; + if (!this.paused) { + timeScale = this.timeScale; + const interpolant = this._timeScaleInterpolant; + if (interpolant !== null) { + const interpolantValue = interpolant.evaluate(time2)[0]; + timeScale *= interpolantValue; + if (time2 > interpolant.parameterPositions[1]) { + this.stopWarping(); + if (timeScale === 0) { + this.paused = true; + } else { + this.timeScale = timeScale; + } + } + } + } + this._effectiveTimeScale = timeScale; + return timeScale; + } + _updateTime(deltaTime) { + const duration = this._clip.duration; + const loop = this.loop; + let time2 = this.time + deltaTime; + let loopCount = this._loopCount; + const pingPong = loop === LoopPingPong; + if (deltaTime === 0) { + if (loopCount === -1) + return time2; + return pingPong && (loopCount & 1) === 1 ? duration - time2 : time2; + } + if (loop === LoopOnce) { + if (loopCount === -1) { + this._loopCount = 0; + this._setEndings(true, true, false); + } + handle_stop: { + if (time2 >= duration) { + time2 = duration; + } else if (time2 < 0) { + time2 = 0; + } else { + this.time = time2; + break handle_stop; + } + if (this.clampWhenFinished) + this.paused = true; + else + this.enabled = false; + this.time = time2; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime < 0 ? -1 : 1 + }); + } + } else { + if (loopCount === -1) { + if (deltaTime >= 0) { + loopCount = 0; + this._setEndings(true, this.repetitions === 0, pingPong); + } else { + this._setEndings(this.repetitions === 0, true, pingPong); + } + } + if (time2 >= duration || time2 < 0) { + const loopDelta = Math.floor(time2 / duration); + time2 -= duration * loopDelta; + loopCount += Math.abs(loopDelta); + const pending = this.repetitions - loopCount; + if (pending <= 0) { + if (this.clampWhenFinished) + this.paused = true; + else + this.enabled = false; + time2 = deltaTime > 0 ? duration : 0; + this.time = time2; + this._mixer.dispatchEvent({ + type: "finished", + action: this, + direction: deltaTime > 0 ? 1 : -1 + }); + } else { + if (pending === 1) { + const atStart = deltaTime < 0; + this._setEndings(atStart, !atStart, pingPong); + } else { + this._setEndings(false, false, pingPong); + } + this._loopCount = loopCount; + this.time = time2; + this._mixer.dispatchEvent({ + type: "loop", + action: this, + loopDelta + }); + } + } else { + this.time = time2; + } + if (pingPong && (loopCount & 1) === 1) { + return duration - time2; + } + } + return time2; + } + _setEndings(atStart, atEnd, pingPong) { + const settings = this._interpolantSettings; + if (pingPong) { + settings.endingStart = ZeroSlopeEnding; + settings.endingEnd = ZeroSlopeEnding; + } else { + if (atStart) { + settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; + } else { + settings.endingStart = WrapAroundEnding; + } + if (atEnd) { + settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; + } else { + settings.endingEnd = WrapAroundEnding; + } + } + } + _scheduleFading(duration, weightNow, weightThen) { + const mixer = this._mixer, now2 = mixer.time; + let interpolant = this._weightInterpolant; + if (interpolant === null) { + interpolant = mixer._lendControlInterpolant(); + this._weightInterpolant = interpolant; + } + const { parameterPositions: times, sampleValues: values2 } = interpolant; + times[0] = now2; + values2[0] = weightNow; + times[1] = now2 + duration; + values2[1] = weightThen; + return this; + } +} +var _controlInterpolantsResultBuffer = new Float32Array(1); + +class AnimationMixer extends EventDispatcher { + constructor(root) { + super(); + this._root = root; + this._initMemoryManager(); + this._accuIndex = 0; + this.time = 0; + this.timeScale = 1; + } + _bindAction(action, prototypeAction) { + const root = action._localRoot || this._root, tracks = action._clip.tracks, nTracks = tracks.length, bindings = action._propertyBindings, interpolants = action._interpolants, rootUuid = root.uuid, bindingsByRoot = this._bindingsByRootAndName; + let bindingsByName = bindingsByRoot[rootUuid]; + if (bindingsByName === undefined) { + bindingsByName = {}; + bindingsByRoot[rootUuid] = bindingsByName; + } + for (let i = 0;i !== nTracks; ++i) { + const track = tracks[i], trackName = track.name; + let binding = bindingsByName[trackName]; + if (binding !== undefined) { + ++binding.referenceCount; + bindings[i] = binding; + } else { + binding = bindings[i]; + if (binding !== undefined) { + if (binding._cacheIndex === null) { + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + } + continue; + } + const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath; + binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize()); + ++binding.referenceCount; + this._addInactiveBinding(binding, rootUuid, trackName); + bindings[i] = binding; + } + interpolants[i].resultBuffer = binding.buffer; + } + } + _activateAction(action) { + if (!this._isActiveAction(action)) { + if (action._cacheIndex === null) { + const rootUuid = (action._localRoot || this._root).uuid, clipUuid = action._clip.uuid, actionsForClip = this._actionsByClip[clipUuid]; + this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]); + this._addInactiveAction(action, clipUuid, rootUuid); + } + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length;i !== n; ++i) { + const binding = bindings[i]; + if (binding.useCount++ === 0) { + this._lendBinding(binding); + binding.saveOriginalState(); + } + } + this._lendAction(action); + } + } + _deactivateAction(action) { + if (this._isActiveAction(action)) { + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length;i !== n; ++i) { + const binding = bindings[i]; + if (--binding.useCount === 0) { + binding.restoreOriginalState(); + this._takeBackBinding(binding); + } + } + this._takeBackAction(action); + } + } + _initMemoryManager() { + this._actions = []; + this._nActiveActions = 0; + this._actionsByClip = {}; + this._bindings = []; + this._nActiveBindings = 0; + this._bindingsByRootAndName = {}; + this._controlInterpolants = []; + this._nActiveControlInterpolants = 0; + const scope = this; + this.stats = { + actions: { + get total() { + return scope._actions.length; + }, + get inUse() { + return scope._nActiveActions; + } + }, + bindings: { + get total() { + return scope._bindings.length; + }, + get inUse() { + return scope._nActiveBindings; + } + }, + controlInterpolants: { + get total() { + return scope._controlInterpolants.length; + }, + get inUse() { + return scope._nActiveControlInterpolants; + } + } + }; + } + _isActiveAction(action) { + const index2 = action._cacheIndex; + return index2 !== null && index2 < this._nActiveActions; + } + _addInactiveAction(action, clipUuid, rootUuid) { + const actions = this._actions, actionsByClip = this._actionsByClip; + let actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip === undefined) { + actionsForClip = { + knownActions: [action], + actionByRoot: {} + }; + action._byClipCacheIndex = 0; + actionsByClip[clipUuid] = actionsForClip; + } else { + const knownActions = actionsForClip.knownActions; + action._byClipCacheIndex = knownActions.length; + knownActions.push(action); + } + action._cacheIndex = actions.length; + actions.push(action); + actionsForClip.actionByRoot[rootUuid] = action; + } + _removeInactiveAction(action) { + const actions = this._actions, lastInactiveAction = actions[actions.length - 1], cacheIndex = action._cacheIndex; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + action._cacheIndex = null; + const clipUuid = action._clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid], knownActionsForClip = actionsForClip.knownActions, lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1], byClipCacheIndex = action._byClipCacheIndex; + lastKnownAction._byClipCacheIndex = byClipCacheIndex; + knownActionsForClip[byClipCacheIndex] = lastKnownAction; + knownActionsForClip.pop(); + action._byClipCacheIndex = null; + const actionByRoot = actionsForClip.actionByRoot, rootUuid = (action._localRoot || this._root).uuid; + delete actionByRoot[rootUuid]; + if (knownActionsForClip.length === 0) { + delete actionsByClip[clipUuid]; + } + this._removeInactiveBindingsForAction(action); + } + _removeInactiveBindingsForAction(action) { + const bindings = action._propertyBindings; + for (let i = 0, n = bindings.length;i !== n; ++i) { + const binding = bindings[i]; + if (--binding.referenceCount === 0) { + this._removeInactiveBinding(binding); + } + } + } + _lendAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, lastActiveIndex = this._nActiveActions++, firstInactiveAction = actions[lastActiveIndex]; + action._cacheIndex = lastActiveIndex; + actions[lastActiveIndex] = action; + firstInactiveAction._cacheIndex = prevIndex; + actions[prevIndex] = firstInactiveAction; + } + _takeBackAction(action) { + const actions = this._actions, prevIndex = action._cacheIndex, firstInactiveIndex = --this._nActiveActions, lastActiveAction = actions[firstInactiveIndex]; + action._cacheIndex = firstInactiveIndex; + actions[firstInactiveIndex] = action; + lastActiveAction._cacheIndex = prevIndex; + actions[prevIndex] = lastActiveAction; + } + _addInactiveBinding(binding, rootUuid, trackName) { + const bindingsByRoot = this._bindingsByRootAndName, bindings = this._bindings; + let bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName === undefined) { + bindingByName = {}; + bindingsByRoot[rootUuid] = bindingByName; + } + bindingByName[trackName] = binding; + binding._cacheIndex = bindings.length; + bindings.push(binding); + } + _removeInactiveBinding(binding) { + const bindings = this._bindings, propBinding = binding.binding, rootUuid = propBinding.rootNode.uuid, trackName = propBinding.path, bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid], lastInactiveBinding = bindings[bindings.length - 1], cacheIndex = binding._cacheIndex; + lastInactiveBinding._cacheIndex = cacheIndex; + bindings[cacheIndex] = lastInactiveBinding; + bindings.pop(); + delete bindingByName[trackName]; + if (Object.keys(bindingByName).length === 0) { + delete bindingsByRoot[rootUuid]; + } + } + _lendBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, lastActiveIndex = this._nActiveBindings++, firstInactiveBinding = bindings[lastActiveIndex]; + binding._cacheIndex = lastActiveIndex; + bindings[lastActiveIndex] = binding; + firstInactiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = firstInactiveBinding; + } + _takeBackBinding(binding) { + const bindings = this._bindings, prevIndex = binding._cacheIndex, firstInactiveIndex = --this._nActiveBindings, lastActiveBinding = bindings[firstInactiveIndex]; + binding._cacheIndex = firstInactiveIndex; + bindings[firstInactiveIndex] = binding; + lastActiveBinding._cacheIndex = prevIndex; + bindings[prevIndex] = lastActiveBinding; + } + _lendControlInterpolant() { + const interpolants = this._controlInterpolants, lastActiveIndex = this._nActiveControlInterpolants++; + let interpolant = interpolants[lastActiveIndex]; + if (interpolant === undefined) { + interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer); + interpolant.__cacheIndex = lastActiveIndex; + interpolants[lastActiveIndex] = interpolant; + } + return interpolant; + } + _takeBackControlInterpolant(interpolant) { + const interpolants = this._controlInterpolants, prevIndex = interpolant.__cacheIndex, firstInactiveIndex = --this._nActiveControlInterpolants, lastActiveInterpolant = interpolants[firstInactiveIndex]; + interpolant.__cacheIndex = firstInactiveIndex; + interpolants[firstInactiveIndex] = interpolant; + lastActiveInterpolant.__cacheIndex = prevIndex; + interpolants[prevIndex] = lastActiveInterpolant; + } + clipAction(clip, optionalRoot, blendMode) { + const root = optionalRoot || this._root, rootUuid = root.uuid; + let clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip; + const clipUuid = clipObject !== null ? clipObject.uuid : clip; + const actionsForClip = this._actionsByClip[clipUuid]; + let prototypeAction = null; + if (blendMode === undefined) { + if (clipObject !== null) { + blendMode = clipObject.blendMode; + } else { + blendMode = NormalAnimationBlendMode; + } + } + if (actionsForClip !== undefined) { + const existingAction = actionsForClip.actionByRoot[rootUuid]; + if (existingAction !== undefined && existingAction.blendMode === blendMode) { + return existingAction; + } + prototypeAction = actionsForClip.knownActions[0]; + if (clipObject === null) + clipObject = prototypeAction._clip; + } + if (clipObject === null) + return null; + const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode); + this._bindAction(newAction, prototypeAction); + this._addInactiveAction(newAction, clipUuid, rootUuid); + return newAction; + } + existingAction(clip, optionalRoot) { + const root = optionalRoot || this._root, rootUuid = root.uuid, clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip, clipUuid = clipObject ? clipObject.uuid : clip, actionsForClip = this._actionsByClip[clipUuid]; + if (actionsForClip !== undefined) { + return actionsForClip.actionByRoot[rootUuid] || null; + } + return null; + } + stopAllAction() { + const actions = this._actions, nActions = this._nActiveActions; + for (let i = nActions - 1;i >= 0; --i) { + actions[i].stop(); + } + return this; + } + update(deltaTime) { + deltaTime *= this.timeScale; + const actions = this._actions, nActions = this._nActiveActions, time2 = this.time += deltaTime, timeDirection = Math.sign(deltaTime), accuIndex = this._accuIndex ^= 1; + for (let i = 0;i !== nActions; ++i) { + const action = actions[i]; + action._update(time2, deltaTime, timeDirection, accuIndex); + } + const bindings = this._bindings, nBindings = this._nActiveBindings; + for (let i = 0;i !== nBindings; ++i) { + bindings[i].apply(accuIndex); + } + return this; + } + setTime(timeInSeconds) { + this.time = 0; + for (let i = 0;i < this._actions.length; i++) { + this._actions[i].time = 0; + } + return this.update(timeInSeconds); + } + getRoot() { + return this._root; + } + uncacheClip(clip) { + const actions = this._actions, clipUuid = clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid]; + if (actionsForClip !== undefined) { + const actionsToRemove = actionsForClip.knownActions; + for (let i = 0, n = actionsToRemove.length;i !== n; ++i) { + const action = actionsToRemove[i]; + this._deactivateAction(action); + const cacheIndex = action._cacheIndex, lastInactiveAction = actions[actions.length - 1]; + action._cacheIndex = null; + action._byClipCacheIndex = null; + lastInactiveAction._cacheIndex = cacheIndex; + actions[cacheIndex] = lastInactiveAction; + actions.pop(); + this._removeInactiveBindingsForAction(action); + } + delete actionsByClip[clipUuid]; + } + } + uncacheRoot(root) { + const rootUuid = root.uuid, actionsByClip = this._actionsByClip; + for (const clipUuid in actionsByClip) { + const actionByRoot = actionsByClip[clipUuid].actionByRoot, action = actionByRoot[rootUuid]; + if (action !== undefined) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } + const bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid]; + if (bindingByName !== undefined) { + for (const trackName in bindingByName) { + const binding = bindingByName[trackName]; + binding.restoreOriginalState(); + this._removeInactiveBinding(binding); + } + } + } + uncacheAction(clip, optionalRoot) { + const action = this.existingAction(clip, optionalRoot); + if (action !== null) { + this._deactivateAction(action); + this._removeInactiveAction(action); + } + } +} + +class RenderTarget3D extends RenderTarget { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isRenderTarget3D = true; + this.depth = depth; + this.texture = new Data3DTexture(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } +} + +class RenderTargetArray extends RenderTarget { + constructor(width2 = 1, height2 = 1, depth = 1, options = {}) { + super(width2, height2, options); + this.isRenderTargetArray = true; + this.depth = depth; + this.texture = new DataArrayTexture(null, width2, height2, depth); + this.texture.isRenderTargetTexture = true; + } +} + +class Uniform { + constructor(value2) { + this.value = value2; + } + clone() { + return new Uniform(this.value.clone === undefined ? this.value : this.value.clone()); + } +} +var _id = 0; + +class UniformsGroup extends EventDispatcher { + constructor() { + super(); + this.isUniformsGroup = true; + Object.defineProperty(this, "id", { value: _id++ }); + this.name = ""; + this.usage = StaticDrawUsage; + this.uniforms = []; + } + add(uniform) { + this.uniforms.push(uniform); + return this; + } + remove(uniform) { + const index2 = this.uniforms.indexOf(uniform); + if (index2 !== -1) + this.uniforms.splice(index2, 1); + return this; + } + setName(name2) { + this.name = name2; + return this; + } + setUsage(value2) { + this.usage = value2; + return this; + } + dispose() { + this.dispatchEvent({ type: "dispose" }); + return this; + } + copy(source) { + this.name = source.name; + this.usage = source.usage; + const uniformsSource = source.uniforms; + this.uniforms.length = 0; + for (let i = 0, l = uniformsSource.length;i < l; i++) { + const uniforms = Array.isArray(uniformsSource[i]) ? uniformsSource[i] : [uniformsSource[i]]; + for (let j = 0;j < uniforms.length; j++) { + this.uniforms.push(uniforms[j].clone()); + } + } + return this; + } + clone() { + return new this.constructor().copy(this); + } +} + +class InstancedInterleavedBuffer extends InterleavedBuffer { + constructor(array, stride, meshPerAttribute = 1) { + super(array, stride); + this.isInstancedInterleavedBuffer = true; + this.meshPerAttribute = meshPerAttribute; + } + copy(source) { + super.copy(source); + this.meshPerAttribute = source.meshPerAttribute; + return this; + } + clone(data2) { + const ib = super.clone(data2); + ib.meshPerAttribute = this.meshPerAttribute; + return ib; + } + toJSON(data2) { + const json = super.toJSON(data2); + json.isInstancedInterleavedBuffer = true; + json.meshPerAttribute = this.meshPerAttribute; + return json; + } +} + +class GLBufferAttribute { + constructor(buffer, type, itemSize, elementSize, count) { + this.isGLBufferAttribute = true; + this.name = ""; + this.buffer = buffer; + this.type = type; + this.itemSize = itemSize; + this.elementSize = elementSize; + this.count = count; + this.version = 0; + } + set needsUpdate(value2) { + if (value2 === true) + this.version++; + } + setBuffer(buffer) { + this.buffer = buffer; + return this; + } + setType(type, elementSize) { + this.type = type; + this.elementSize = elementSize; + return this; + } + setItemSize(itemSize) { + this.itemSize = itemSize; + return this; + } + setCount(count) { + this.count = count; + return this; + } +} +var _matrix = /* @__PURE__ */ new Matrix4; + +class Raycaster { + constructor(origin, direction, near = 0, far = Infinity) { + this.ray = new Ray(origin, direction); + this.near = near; + this.far = far; + this.camera = null; + this.layers = new Layers; + this.params = { + Mesh: {}, + Line: { threshold: 1 }, + LOD: {}, + Points: { threshold: 1 }, + Sprite: {} + }; + } + set(origin, direction) { + this.ray.set(origin, direction); + } + setFromCamera(coords, camera) { + if (camera.isPerspectiveCamera) { + this.ray.origin.setFromMatrixPosition(camera.matrixWorld); + this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize(); + this.camera = camera; + } else if (camera.isOrthographicCamera) { + this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); + this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld); + this.camera = camera; + } else { + console.error("THREE.Raycaster: Unsupported camera type: " + camera.type); + } + } + setFromXRController(controller) { + _matrix.identity().extractRotation(controller.matrixWorld); + this.ray.origin.setFromMatrixPosition(controller.matrixWorld); + this.ray.direction.set(0, 0, -1).applyMatrix4(_matrix); + return this; + } + intersectObject(object, recursive = true, intersects2 = []) { + intersect(object, this, intersects2, recursive); + intersects2.sort(ascSort); + return intersects2; + } + intersectObjects(objects, recursive = true, intersects2 = []) { + for (let i = 0, l = objects.length;i < l; i++) { + intersect(objects[i], this, intersects2, recursive); + } + intersects2.sort(ascSort); + return intersects2; + } +} +function ascSort(a, b) { + return a.distance - b.distance; +} +function intersect(object, raycaster, intersects2, recursive) { + let propagate = true; + if (object.layers.test(raycaster.layers)) { + const result = object.raycast(raycaster, intersects2); + if (result === false) + propagate = false; + } + if (propagate === true && recursive === true) { + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + intersect(children[i], raycaster, intersects2, true); + } + } +} + +class Spherical { + constructor(radius = 1, phi = 0, theta = 0) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + set(radius, phi, theta) { + this.radius = radius; + this.phi = phi; + this.theta = theta; + return this; + } + copy(other) { + this.radius = other.radius; + this.phi = other.phi; + this.theta = other.theta; + return this; + } + makeSafe() { + const EPS = 0.000001; + this.phi = clamp2(this.phi, EPS, Math.PI - EPS); + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x, y, z) { + this.radius = Math.sqrt(x * x + y * y + z * z); + if (this.radius === 0) { + this.theta = 0; + this.phi = 0; + } else { + this.theta = Math.atan2(x, z); + this.phi = Math.acos(clamp2(y / this.radius, -1, 1)); + } + return this; + } + clone() { + return new this.constructor().copy(this); + } +} + +class Cylindrical { + constructor(radius = 1, theta = 0, y = 0) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + set(radius, theta, y) { + this.radius = radius; + this.theta = theta; + this.y = y; + return this; + } + copy(other) { + this.radius = other.radius; + this.theta = other.theta; + this.y = other.y; + return this; + } + setFromVector3(v) { + return this.setFromCartesianCoords(v.x, v.y, v.z); + } + setFromCartesianCoords(x, y, z) { + this.radius = Math.sqrt(x * x + z * z); + this.theta = Math.atan2(x, z); + this.y = y; + return this; + } + clone() { + return new this.constructor().copy(this); + } +} + +class Matrix2 { + constructor(n11, n12, n21, n22) { + Matrix2.prototype.isMatrix2 = true; + this.elements = [ + 1, + 0, + 0, + 1 + ]; + if (n11 !== undefined) { + this.set(n11, n12, n21, n22); + } + } + identity() { + this.set(1, 0, 0, 1); + return this; + } + fromArray(array, offset = 0) { + for (let i = 0;i < 4; i++) { + this.elements[i] = array[i + offset]; + } + return this; + } + set(n11, n12, n21, n22) { + const te = this.elements; + te[0] = n11; + te[2] = n12; + te[1] = n21; + te[3] = n22; + return this; + } +} +var _vector$4 = /* @__PURE__ */ new Vector2; + +class Box2 { + constructor(min = new Vector2(Infinity, Infinity), max = new Vector2(-Infinity, -Infinity)) { + this.isBox2 = true; + this.min = min; + this.max = max; + } + set(min, max) { + this.min.copy(min); + this.max.copy(max); + return this; + } + setFromPoints(points) { + this.makeEmpty(); + for (let i = 0, il = points.length;i < il; i++) { + this.expandByPoint(points[i]); + } + return this; + } + setFromCenterAndSize(center, size) { + const halfSize = _vector$4.copy(size).multiplyScalar(0.5); + this.min.copy(center).sub(halfSize); + this.max.copy(center).add(halfSize); + return this; + } + clone() { + return new this.constructor().copy(this); + } + copy(box) { + this.min.copy(box.min); + this.max.copy(box.max); + return this; + } + makeEmpty() { + this.min.x = this.min.y = Infinity; + this.max.x = this.max.y = -Infinity; + return this; + } + isEmpty() { + return this.max.x < this.min.x || this.max.y < this.min.y; + } + getCenter(target) { + return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5); + } + getSize(target) { + return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min); + } + expandByPoint(point) { + this.min.min(point); + this.max.max(point); + return this; + } + expandByVector(vector) { + this.min.sub(vector); + this.max.add(vector); + return this; + } + expandByScalar(scalar) { + this.min.addScalar(-scalar); + this.max.addScalar(scalar); + return this; + } + containsPoint(point) { + return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y; + } + containsBox(box) { + return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y; + } + getParameter(point, target) { + return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y)); + } + intersectsBox(box) { + return box.max.x >= this.min.x && box.min.x <= this.max.x && box.max.y >= this.min.y && box.min.y <= this.max.y; + } + clampPoint(point, target) { + return target.copy(point).clamp(this.min, this.max); + } + distanceToPoint(point) { + return this.clampPoint(point, _vector$4).distanceTo(point); + } + intersect(box) { + this.min.max(box.min); + this.max.min(box.max); + if (this.isEmpty()) + this.makeEmpty(); + return this; + } + union(box) { + this.min.min(box.min); + this.max.max(box.max); + return this; + } + translate(offset) { + this.min.add(offset); + this.max.add(offset); + return this; + } + equals(box) { + return box.min.equals(this.min) && box.max.equals(this.max); + } +} +var _startP = /* @__PURE__ */ new Vector3; +var _startEnd = /* @__PURE__ */ new Vector3; + +class Line3 { + constructor(start = new Vector3, end = new Vector3) { + this.start = start; + this.end = end; + } + set(start, end) { + this.start.copy(start); + this.end.copy(end); + return this; + } + copy(line) { + this.start.copy(line.start); + this.end.copy(line.end); + return this; + } + getCenter(target) { + return target.addVectors(this.start, this.end).multiplyScalar(0.5); + } + delta(target) { + return target.subVectors(this.end, this.start); + } + distanceSq() { + return this.start.distanceToSquared(this.end); + } + distance() { + return this.start.distanceTo(this.end); + } + at(t, target) { + return this.delta(target).multiplyScalar(t).add(this.start); + } + closestPointToPointParameter(point, clampToLine) { + _startP.subVectors(point, this.start); + _startEnd.subVectors(this.end, this.start); + const startEnd2 = _startEnd.dot(_startEnd); + const startEnd_startP = _startEnd.dot(_startP); + let t = startEnd_startP / startEnd2; + if (clampToLine) { + t = clamp2(t, 0, 1); + } + return t; + } + closestPointToPoint(point, clampToLine, target) { + const t = this.closestPointToPointParameter(point, clampToLine); + return this.delta(target).multiplyScalar(t).add(this.start); + } + applyMatrix4(matrix) { + this.start.applyMatrix4(matrix); + this.end.applyMatrix4(matrix); + return this; + } + equals(line) { + return line.start.equals(this.start) && line.end.equals(this.end); + } + clone() { + return new this.constructor().copy(this); + } +} +var _vector$3 = /* @__PURE__ */ new Vector3; + +class SpotLightHelper extends Object3D { + constructor(light, color) { + super(); + this.light = light; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "SpotLightHelper"; + const geometry = new BufferGeometry; + const positions = [ + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + -1, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + -1, + 1 + ]; + for (let i = 0, j = 1, l = 32;i < l; i++, j++) { + const p1 = i / l * Math.PI * 2; + const p2 = j / l * Math.PI * 2; + positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1); + } + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + const material = new LineBasicMaterial({ fog: false, toneMapped: false }); + this.cone = new LineSegments(geometry, material); + this.add(this.cone); + this.update(); + } + dispose() { + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + if (this.parent) { + this.parent.updateWorldMatrix(true); + this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld); + } else { + this.matrix.copy(this.light.matrixWorld); + } + this.matrixWorld.copy(this.light.matrixWorld); + const coneLength = this.light.distance ? this.light.distance : 1000; + const coneWidth = coneLength * Math.tan(this.light.angle); + this.cone.scale.set(coneWidth, coneWidth, coneLength); + _vector$3.setFromMatrixPosition(this.light.target.matrixWorld); + this.cone.lookAt(_vector$3); + if (this.color !== undefined) { + this.cone.material.color.set(this.color); + } else { + this.cone.material.color.copy(this.light.color); + } + } +} +var _vector$2 = /* @__PURE__ */ new Vector3; +var _boneMatrix = /* @__PURE__ */ new Matrix4; +var _matrixWorldInv = /* @__PURE__ */ new Matrix4; + +class SkeletonHelper extends LineSegments { + constructor(object) { + const bones = getBoneList(object); + const geometry = new BufferGeometry; + const vertices = []; + const colors = []; + const color1 = new Color(0, 0, 1); + const color2 = new Color(0, 1, 0); + for (let i = 0;i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + vertices.push(0, 0, 0); + vertices.push(0, 0, 0); + colors.push(color1.r, color1.g, color1.b); + colors.push(color2.r, color2.g, color2.b); + } + } + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true }); + super(geometry, material); + this.isSkeletonHelper = true; + this.type = "SkeletonHelper"; + this.root = object; + this.bones = bones; + this.matrix = object.matrixWorld; + this.matrixAutoUpdate = false; + } + updateMatrixWorld(force) { + const bones = this.bones; + const geometry = this.geometry; + const position2 = geometry.getAttribute("position"); + _matrixWorldInv.copy(this.root.matrixWorld).invert(); + for (let i = 0, j = 0;i < bones.length; i++) { + const bone = bones[i]; + if (bone.parent && bone.parent.isBone) { + _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld); + _vector$2.setFromMatrixPosition(_boneMatrix); + position2.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z); + _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld); + _vector$2.setFromMatrixPosition(_boneMatrix); + position2.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z); + j += 2; + } + } + geometry.getAttribute("position").needsUpdate = true; + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} +function getBoneList(object) { + const boneList = []; + if (object.isBone === true) { + boneList.push(object); + } + for (let i = 0;i < object.children.length; i++) { + boneList.push.apply(boneList, getBoneList(object.children[i])); + } + return boneList; +} + +class PointLightHelper extends Mesh { + constructor(light, sphereSize, color) { + const geometry = new SphereGeometry(sphereSize, 4, 2); + const material = new MeshBasicMaterial({ wireframe: true, fog: false, toneMapped: false }); + super(geometry, material); + this.light = light; + this.color = color; + this.type = "PointLightHelper"; + this.matrix = this.light.matrixWorld; + this.matrixAutoUpdate = false; + this.update(); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + if (this.color !== undefined) { + this.material.color.set(this.color); + } else { + this.material.color.copy(this.light.color); + } + } +} +var _vector$1 = /* @__PURE__ */ new Vector3; +var _color1 = /* @__PURE__ */ new Color; +var _color2 = /* @__PURE__ */ new Color; + +class HemisphereLightHelper extends Object3D { + constructor(light, size, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "HemisphereLightHelper"; + const geometry = new OctahedronGeometry(size); + geometry.rotateY(Math.PI * 0.5); + this.material = new MeshBasicMaterial({ wireframe: true, fog: false, toneMapped: false }); + if (this.color === undefined) + this.material.vertexColors = true; + const position2 = geometry.getAttribute("position"); + const colors = new Float32Array(position2.count * 3); + geometry.setAttribute("color", new BufferAttribute(colors, 3)); + this.add(new Mesh(geometry, this.material)); + this.update(); + } + dispose() { + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } + update() { + const mesh = this.children[0]; + if (this.color !== undefined) { + this.material.color.set(this.color); + } else { + const colors = mesh.geometry.getAttribute("color"); + _color1.copy(this.light.color); + _color2.copy(this.light.groundColor); + for (let i = 0, l = colors.count;i < l; i++) { + const color = i < l / 2 ? _color1 : _color2; + colors.setXYZ(i, color.r, color.g, color.b); + } + colors.needsUpdate = true; + } + this.light.updateWorldMatrix(true, false); + mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate()); + } +} + +class GridHelper extends LineSegments { + constructor(size = 10, divisions = 10, color1 = 4473924, color2 = 8947848) { + color1 = new Color(color1); + color2 = new Color(color2); + const center = divisions / 2; + const step = size / divisions; + const halfSize = size / 2; + const vertices = [], colors = []; + for (let i = 0, j = 0, k = -halfSize;i <= divisions; i++, k += step) { + vertices.push(-halfSize, 0, k, halfSize, 0, k); + vertices.push(k, 0, -halfSize, k, 0, halfSize); + const color = i === center ? color1 : color2; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + color.toArray(colors, j); + j += 3; + } + const geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "GridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} + +class PolarGridHelper extends LineSegments { + constructor(radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 4473924, color2 = 8947848) { + color1 = new Color(color1); + color2 = new Color(color2); + const vertices = []; + const colors = []; + if (sectors > 1) { + for (let i = 0;i < sectors; i++) { + const v = i / sectors * (Math.PI * 2); + const x = Math.sin(v) * radius; + const z = Math.cos(v) * radius; + vertices.push(0, 0, 0); + vertices.push(x, 0, z); + const color = i & 1 ? color1 : color2; + colors.push(color.r, color.g, color.b); + colors.push(color.r, color.g, color.b); + } + } + for (let i = 0;i < rings; i++) { + const color = i & 1 ? color1 : color2; + const r = radius - radius / rings * i; + for (let j = 0;j < divisions; j++) { + let v = j / divisions * (Math.PI * 2); + let x = Math.sin(v) * r; + let z = Math.cos(v) * r; + vertices.push(x, 0, z); + colors.push(color.r, color.g, color.b); + v = (j + 1) / divisions * (Math.PI * 2); + x = Math.sin(v) * r; + z = Math.cos(v) * r; + vertices.push(x, 0, z); + colors.push(color.r, color.g, color.b); + } + } + const geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "PolarGridHelper"; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} +var _v1 = /* @__PURE__ */ new Vector3; +var _v2 = /* @__PURE__ */ new Vector3; +var _v3 = /* @__PURE__ */ new Vector3; + +class DirectionalLightHelper extends Object3D { + constructor(light, size, color) { + super(); + this.light = light; + this.matrix = light.matrixWorld; + this.matrixAutoUpdate = false; + this.color = color; + this.type = "DirectionalLightHelper"; + if (size === undefined) + size = 1; + let geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute([ + -size, + size, + 0, + size, + size, + 0, + size, + -size, + 0, + -size, + -size, + 0, + -size, + size, + 0 + ], 3)); + const material = new LineBasicMaterial({ fog: false, toneMapped: false }); + this.lightPlane = new Line(geometry, material); + this.add(this.lightPlane); + geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3)); + this.targetLine = new Line(geometry, material); + this.add(this.targetLine); + this.update(); + } + dispose() { + this.lightPlane.geometry.dispose(); + this.lightPlane.material.dispose(); + this.targetLine.geometry.dispose(); + this.targetLine.material.dispose(); + } + update() { + this.light.updateWorldMatrix(true, false); + this.light.target.updateWorldMatrix(true, false); + _v1.setFromMatrixPosition(this.light.matrixWorld); + _v2.setFromMatrixPosition(this.light.target.matrixWorld); + _v3.subVectors(_v2, _v1); + this.lightPlane.lookAt(_v2); + if (this.color !== undefined) { + this.lightPlane.material.color.set(this.color); + this.targetLine.material.color.set(this.color); + } else { + this.lightPlane.material.color.copy(this.light.color); + this.targetLine.material.color.copy(this.light.color); + } + this.targetLine.lookAt(_v2); + this.targetLine.scale.z = _v3.length(); + } +} +var _vector = /* @__PURE__ */ new Vector3; +var _camera = /* @__PURE__ */ new Camera; + +class CameraHelper extends LineSegments { + constructor(camera) { + const geometry = new BufferGeometry; + const material = new LineBasicMaterial({ color: 16777215, vertexColors: true, toneMapped: false }); + const vertices = []; + const colors = []; + const pointMap = {}; + addLine("n1", "n2"); + addLine("n2", "n4"); + addLine("n4", "n3"); + addLine("n3", "n1"); + addLine("f1", "f2"); + addLine("f2", "f4"); + addLine("f4", "f3"); + addLine("f3", "f1"); + addLine("n1", "f1"); + addLine("n2", "f2"); + addLine("n3", "f3"); + addLine("n4", "f4"); + addLine("p", "n1"); + addLine("p", "n2"); + addLine("p", "n3"); + addLine("p", "n4"); + addLine("u1", "u2"); + addLine("u2", "u3"); + addLine("u3", "u1"); + addLine("c", "t"); + addLine("p", "c"); + addLine("cn1", "cn2"); + addLine("cn3", "cn4"); + addLine("cf1", "cf2"); + addLine("cf3", "cf4"); + function addLine(a, b) { + addPoint(a); + addPoint(b); + } + function addPoint(id) { + vertices.push(0, 0, 0); + colors.push(0, 0, 0); + if (pointMap[id] === undefined) { + pointMap[id] = []; + } + pointMap[id].push(vertices.length / 3 - 1); + } + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + super(geometry, material); + this.type = "CameraHelper"; + this.camera = camera; + if (this.camera.updateProjectionMatrix) + this.camera.updateProjectionMatrix(); + this.matrix = camera.matrixWorld; + this.matrixAutoUpdate = false; + this.pointMap = pointMap; + this.update(); + const colorFrustum = new Color(16755200); + const colorCone = new Color(16711680); + const colorUp = new Color(43775); + const colorTarget = new Color(16777215); + const colorCross = new Color(3355443); + this.setColors(colorFrustum, colorCone, colorUp, colorTarget, colorCross); + } + setColors(frustum, cone, up, target, cross) { + const geometry = this.geometry; + const colorAttribute = geometry.getAttribute("color"); + colorAttribute.setXYZ(0, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(1, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(2, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(3, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(4, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(5, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(6, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(7, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(8, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(9, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(10, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(11, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(12, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(13, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(14, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(15, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(16, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(17, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(18, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(19, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(20, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(21, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(22, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(23, frustum.r, frustum.g, frustum.b); + colorAttribute.setXYZ(24, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(25, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(26, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(27, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(28, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(29, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(30, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(31, cone.r, cone.g, cone.b); + colorAttribute.setXYZ(32, up.r, up.g, up.b); + colorAttribute.setXYZ(33, up.r, up.g, up.b); + colorAttribute.setXYZ(34, up.r, up.g, up.b); + colorAttribute.setXYZ(35, up.r, up.g, up.b); + colorAttribute.setXYZ(36, up.r, up.g, up.b); + colorAttribute.setXYZ(37, up.r, up.g, up.b); + colorAttribute.setXYZ(38, target.r, target.g, target.b); + colorAttribute.setXYZ(39, target.r, target.g, target.b); + colorAttribute.setXYZ(40, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(41, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(42, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(43, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(44, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(45, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(46, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(47, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(48, cross.r, cross.g, cross.b); + colorAttribute.setXYZ(49, cross.r, cross.g, cross.b); + colorAttribute.needsUpdate = true; + } + update() { + const geometry = this.geometry; + const pointMap = this.pointMap; + const w = 1, h = 1; + _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); + const nearZ = this.camera.coordinateSystem === WebGLCoordinateSystem ? -1 : 0; + setPoint("c", pointMap, geometry, _camera, 0, 0, nearZ); + setPoint("t", pointMap, geometry, _camera, 0, 0, 1); + setPoint("n1", pointMap, geometry, _camera, -w, -h, nearZ); + setPoint("n2", pointMap, geometry, _camera, w, -h, nearZ); + setPoint("n3", pointMap, geometry, _camera, -w, h, nearZ); + setPoint("n4", pointMap, geometry, _camera, w, h, nearZ); + setPoint("f1", pointMap, geometry, _camera, -w, -h, 1); + setPoint("f2", pointMap, geometry, _camera, w, -h, 1); + setPoint("f3", pointMap, geometry, _camera, -w, h, 1); + setPoint("f4", pointMap, geometry, _camera, w, h, 1); + setPoint("u1", pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ); + setPoint("u2", pointMap, geometry, _camera, -w * 0.7, h * 1.1, nearZ); + setPoint("u3", pointMap, geometry, _camera, 0, h * 2, nearZ); + setPoint("cf1", pointMap, geometry, _camera, -w, 0, 1); + setPoint("cf2", pointMap, geometry, _camera, w, 0, 1); + setPoint("cf3", pointMap, geometry, _camera, 0, -h, 1); + setPoint("cf4", pointMap, geometry, _camera, 0, h, 1); + setPoint("cn1", pointMap, geometry, _camera, -w, 0, nearZ); + setPoint("cn2", pointMap, geometry, _camera, w, 0, nearZ); + setPoint("cn3", pointMap, geometry, _camera, 0, -h, nearZ); + setPoint("cn4", pointMap, geometry, _camera, 0, h, nearZ); + geometry.getAttribute("position").needsUpdate = true; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} +function setPoint(point, pointMap, geometry, camera, x, y, z) { + _vector.set(x, y, z).unproject(camera); + const points = pointMap[point]; + if (points !== undefined) { + const position2 = geometry.getAttribute("position"); + for (let i = 0, l = points.length;i < l; i++) { + position2.setXYZ(points[i], _vector.x, _vector.y, _vector.z); + } + } +} +var _box = /* @__PURE__ */ new Box3; + +class BoxHelper extends LineSegments { + constructor(object, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = new Float32Array(8 * 3); + const geometry = new BufferGeometry; + geometry.setIndex(new BufferAttribute(indices, 1)); + geometry.setAttribute("position", new BufferAttribute(positions, 3)); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.object = object; + this.type = "BoxHelper"; + this.matrixAutoUpdate = false; + this.update(); + } + update(object) { + if (object !== undefined) { + console.warn("THREE.BoxHelper: .update() has no longer arguments."); + } + if (this.object !== undefined) { + _box.setFromObject(this.object); + } + if (_box.isEmpty()) + return; + const min = _box.min; + const max = _box.max; + const position2 = this.geometry.attributes.position; + const array = position2.array; + array[0] = max.x; + array[1] = max.y; + array[2] = max.z; + array[3] = min.x; + array[4] = max.y; + array[5] = max.z; + array[6] = min.x; + array[7] = min.y; + array[8] = max.z; + array[9] = max.x; + array[10] = min.y; + array[11] = max.z; + array[12] = max.x; + array[13] = max.y; + array[14] = min.z; + array[15] = min.x; + array[16] = max.y; + array[17] = min.z; + array[18] = min.x; + array[19] = min.y; + array[20] = min.z; + array[21] = max.x; + array[22] = min.y; + array[23] = min.z; + position2.needsUpdate = true; + this.geometry.computeBoundingSphere(); + } + setFromObject(object) { + this.object = object; + this.update(); + return this; + } + copy(source, recursive) { + super.copy(source, recursive); + this.object = source.object; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} + +class Box3Helper extends LineSegments { + constructor(box, color = 16776960) { + const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]); + const positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1]; + const geometry = new BufferGeometry; + geometry.setIndex(new BufferAttribute(indices, 1)); + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.box = box; + this.type = "Box3Helper"; + this.geometry.computeBoundingSphere(); + } + updateMatrixWorld(force) { + const box = this.box; + if (box.isEmpty()) + return; + box.getCenter(this.position); + box.getSize(this.scale); + this.scale.multiplyScalar(0.5); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} + +class PlaneHelper extends Line { + constructor(plane, size = 1, hex = 16776960) { + const color = hex; + const positions = [1, -1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0]; + const geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); + geometry.computeBoundingSphere(); + super(geometry, new LineBasicMaterial({ color, toneMapped: false })); + this.type = "PlaneHelper"; + this.plane = plane; + this.size = size; + const positions2 = [1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0]; + const geometry2 = new BufferGeometry; + geometry2.setAttribute("position", new Float32BufferAttribute(positions2, 3)); + geometry2.computeBoundingSphere(); + this.add(new Mesh(geometry2, new MeshBasicMaterial({ color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false }))); + } + updateMatrixWorld(force) { + this.position.set(0, 0, 0); + this.scale.set(0.5 * this.size, 0.5 * this.size, 1); + this.lookAt(this.plane.normal); + this.translateZ(-this.plane.constant); + super.updateMatrixWorld(force); + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + this.children[0].geometry.dispose(); + this.children[0].material.dispose(); + } +} +var _axis = /* @__PURE__ */ new Vector3; +var _lineGeometry; +var _coneGeometry; + +class ArrowHelper extends Object3D { + constructor(dir = new Vector3(0, 0, 1), origin = new Vector3(0, 0, 0), length2 = 1, color = 16776960, headLength = length2 * 0.2, headWidth = headLength * 0.2) { + super(); + this.type = "ArrowHelper"; + if (_lineGeometry === undefined) { + _lineGeometry = new BufferGeometry; + _lineGeometry.setAttribute("position", new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3)); + _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1); + _coneGeometry.translate(0, -0.5, 0); + } + this.position.copy(origin); + this.line = new Line(_lineGeometry, new LineBasicMaterial({ color, toneMapped: false })); + this.line.matrixAutoUpdate = false; + this.add(this.line); + this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({ color, toneMapped: false })); + this.cone.matrixAutoUpdate = false; + this.add(this.cone); + this.setDirection(dir); + this.setLength(length2, headLength, headWidth); + } + setDirection(dir) { + if (dir.y > 0.99999) { + this.quaternion.set(0, 0, 0, 1); + } else if (dir.y < -0.99999) { + this.quaternion.set(1, 0, 0, 0); + } else { + _axis.set(dir.z, 0, -dir.x).normalize(); + const radians = Math.acos(dir.y); + this.quaternion.setFromAxisAngle(_axis, radians); + } + } + setLength(length2, headLength = length2 * 0.2, headWidth = headLength * 0.2) { + this.line.scale.set(1, Math.max(0.0001, length2 - headLength), 1); + this.line.updateMatrix(); + this.cone.scale.set(headWidth, headLength, headWidth); + this.cone.position.y = length2; + this.cone.updateMatrix(); + } + setColor(color) { + this.line.material.color.set(color); + this.cone.material.color.set(color); + } + copy(source) { + super.copy(source, false); + this.line.copy(source.line); + this.cone.copy(source.cone); + return this; + } + dispose() { + this.line.geometry.dispose(); + this.line.material.dispose(); + this.cone.geometry.dispose(); + this.cone.material.dispose(); + } +} + +class AxesHelper extends LineSegments { + constructor(size = 1) { + const vertices = [ + 0, + 0, + 0, + size, + 0, + 0, + 0, + 0, + 0, + 0, + size, + 0, + 0, + 0, + 0, + 0, + 0, + size + ]; + const colors = [ + 1, + 0, + 0, + 1, + 0.6, + 0, + 0, + 1, + 0, + 0.6, + 1, + 0, + 0, + 0, + 1, + 0, + 0.6, + 1 + ]; + const geometry = new BufferGeometry; + geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + geometry.setAttribute("color", new Float32BufferAttribute(colors, 3)); + const material = new LineBasicMaterial({ vertexColors: true, toneMapped: false }); + super(geometry, material); + this.type = "AxesHelper"; + } + setColors(xAxisColor, yAxisColor, zAxisColor) { + const color = new Color; + const array = this.geometry.attributes.color.array; + color.set(xAxisColor); + color.toArray(array, 0); + color.toArray(array, 3); + color.set(yAxisColor); + color.toArray(array, 6); + color.toArray(array, 9); + color.set(zAxisColor); + color.toArray(array, 12); + color.toArray(array, 15); + this.geometry.attributes.color.needsUpdate = true; + return this; + } + dispose() { + this.geometry.dispose(); + this.material.dispose(); + } +} + +class ShapePath2 { + constructor() { + this.type = "ShapePath"; + this.color = new Color; + this.subPaths = []; + this.currentPath = null; + } + moveTo(x, y) { + this.currentPath = new Path; + this.subPaths.push(this.currentPath); + this.currentPath.moveTo(x, y); + return this; + } + lineTo(x, y) { + this.currentPath.lineTo(x, y); + return this; + } + quadraticCurveTo(aCPx, aCPy, aX, aY) { + this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY); + return this; + } + bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { + this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY); + return this; + } + splineThru(pts) { + this.currentPath.splineThru(pts); + return this; + } + toShapes(isCCW) { + function toShapesNoHoles(inSubpaths) { + const shapes2 = []; + for (let i = 0, l = inSubpaths.length;i < l; i++) { + const tmpPath2 = inSubpaths[i]; + const tmpShape2 = new Shape; + tmpShape2.curves = tmpPath2.curves; + shapes2.push(tmpShape2); + } + return shapes2; + } + function isPointInsidePolygon(inPt, inPolygon) { + const polyLen = inPolygon.length; + let inside = false; + for (let p = polyLen - 1, q = 0;q < polyLen; p = q++) { + let edgeLowPt = inPolygon[p]; + let edgeHighPt = inPolygon[q]; + let edgeDx = edgeHighPt.x - edgeLowPt.x; + let edgeDy = edgeHighPt.y - edgeLowPt.y; + if (Math.abs(edgeDy) > Number.EPSILON) { + if (edgeDy < 0) { + edgeLowPt = inPolygon[q]; + edgeDx = -edgeDx; + edgeHighPt = inPolygon[p]; + edgeDy = -edgeDy; + } + if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) + continue; + if (inPt.y === edgeLowPt.y) { + if (inPt.x === edgeLowPt.x) + return true; + } else { + const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y); + if (perpEdge === 0) + return true; + if (perpEdge < 0) + continue; + inside = !inside; + } + } else { + if (inPt.y !== edgeLowPt.y) + continue; + if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) + return true; + } + } + return inside; + } + const isClockWise = ShapeUtils.isClockWise; + const subPaths = this.subPaths; + if (subPaths.length === 0) + return []; + let solid, tmpPath, tmpShape; + const shapes = []; + if (subPaths.length === 1) { + tmpPath = subPaths[0]; + tmpShape = new Shape; + tmpShape.curves = tmpPath.curves; + shapes.push(tmpShape); + return shapes; + } + let holesFirst = !isClockWise(subPaths[0].getPoints()); + holesFirst = isCCW ? !holesFirst : holesFirst; + const betterShapeHoles = []; + const newShapes = []; + let newShapeHoles = []; + let mainIdx = 0; + let tmpPoints; + newShapes[mainIdx] = undefined; + newShapeHoles[mainIdx] = []; + for (let i = 0, l = subPaths.length;i < l; i++) { + tmpPath = subPaths[i]; + tmpPoints = tmpPath.getPoints(); + solid = isClockWise(tmpPoints); + solid = isCCW ? !solid : solid; + if (solid) { + if (!holesFirst && newShapes[mainIdx]) + mainIdx++; + newShapes[mainIdx] = { s: new Shape, p: tmpPoints }; + newShapes[mainIdx].s.curves = tmpPath.curves; + if (holesFirst) + mainIdx++; + newShapeHoles[mainIdx] = []; + } else { + newShapeHoles[mainIdx].push({ h: tmpPath, p: tmpPoints[0] }); + } + } + if (!newShapes[0]) + return toShapesNoHoles(subPaths); + if (newShapes.length > 1) { + let ambiguous = false; + let toChange = 0; + for (let sIdx = 0, sLen = newShapes.length;sIdx < sLen; sIdx++) { + betterShapeHoles[sIdx] = []; + } + for (let sIdx = 0, sLen = newShapes.length;sIdx < sLen; sIdx++) { + const sho = newShapeHoles[sIdx]; + for (let hIdx = 0;hIdx < sho.length; hIdx++) { + const ho = sho[hIdx]; + let hole_unassigned = true; + for (let s2Idx = 0;s2Idx < newShapes.length; s2Idx++) { + if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) { + if (sIdx !== s2Idx) + toChange++; + if (hole_unassigned) { + hole_unassigned = false; + betterShapeHoles[s2Idx].push(ho); + } else { + ambiguous = true; + } + } + } + if (hole_unassigned) { + betterShapeHoles[sIdx].push(ho); + } + } + } + if (toChange > 0 && ambiguous === false) { + newShapeHoles = betterShapeHoles; + } + } + let tmpHoles; + for (let i = 0, il = newShapes.length;i < il; i++) { + tmpShape = newShapes[i].s; + shapes.push(tmpShape); + tmpHoles = newShapeHoles[i]; + for (let j = 0, jl = tmpHoles.length;j < jl; j++) { + tmpShape.holes.push(tmpHoles[j].h); + } + } + return shapes; + } +} + +class Controls extends EventDispatcher { + constructor(object, domElement = null) { + super(); + this.object = object; + this.domElement = domElement; + this.enabled = true; + this.state = -1; + this.keys = {}; + this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null }; + this.touches = { ONE: null, TWO: null }; + } + connect() { + } + disconnect() { + } + dispose() { + } + update() { + } +} +function contain(texture, aspect2) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect2) { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect2; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } else { + texture.repeat.x = aspect2 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } + return texture; +} +function cover(texture, aspect2) { + const imageAspect = texture.image && texture.image.width ? texture.image.width / texture.image.height : 1; + if (imageAspect > aspect2) { + texture.repeat.x = aspect2 / imageAspect; + texture.repeat.y = 1; + texture.offset.x = (1 - texture.repeat.x) / 2; + texture.offset.y = 0; + } else { + texture.repeat.x = 1; + texture.repeat.y = imageAspect / aspect2; + texture.offset.x = 0; + texture.offset.y = (1 - texture.repeat.y) / 2; + } + return texture; +} +function fill(texture) { + texture.repeat.x = 1; + texture.repeat.y = 1; + texture.offset.x = 0; + texture.offset.y = 0; + return texture; +} +function getByteLength(width2, height2, format, type) { + const typeByteLength = getTextureTypeByteLength(type); + switch (format) { + case AlphaFormat: + return width2 * height2; + case LuminanceFormat: + return width2 * height2; + case LuminanceAlphaFormat: + return width2 * height2 * 2; + case RedFormat: + return width2 * height2 / typeByteLength.components * typeByteLength.byteLength; + case RedIntegerFormat: + return width2 * height2 / typeByteLength.components * typeByteLength.byteLength; + case RGFormat: + return width2 * height2 * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGIntegerFormat: + return width2 * height2 * 2 / typeByteLength.components * typeByteLength.byteLength; + case RGBFormat: + return width2 * height2 * 3 / typeByteLength.components * typeByteLength.byteLength; + case RGBAFormat: + return width2 * height2 * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGBAIntegerFormat: + return width2 * height2 * 4 / typeByteLength.components * typeByteLength.byteLength; + case RGB_S3TC_DXT1_Format: + case RGBA_S3TC_DXT1_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 8; + case RGBA_S3TC_DXT3_Format: + case RGBA_S3TC_DXT5_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGB_PVRTC_2BPPV1_Format: + case RGBA_PVRTC_2BPPV1_Format: + return Math.max(width2, 16) * Math.max(height2, 8) / 4; + case RGB_PVRTC_4BPPV1_Format: + case RGBA_PVRTC_4BPPV1_Format: + return Math.max(width2, 8) * Math.max(height2, 8) / 2; + case RGB_ETC1_Format: + case RGB_ETC2_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 8; + case RGBA_ETC2_EAC_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_4x4_Format: + return Math.floor((width2 + 3) / 4) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_5x4_Format: + return Math.floor((width2 + 4) / 5) * Math.floor((height2 + 3) / 4) * 16; + case RGBA_ASTC_5x5_Format: + return Math.floor((width2 + 4) / 5) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_6x5_Format: + return Math.floor((width2 + 5) / 6) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_6x6_Format: + return Math.floor((width2 + 5) / 6) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_8x5_Format: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_8x6_Format: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_8x8_Format: + return Math.floor((width2 + 7) / 8) * Math.floor((height2 + 7) / 8) * 16; + case RGBA_ASTC_10x5_Format: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 4) / 5) * 16; + case RGBA_ASTC_10x6_Format: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 5) / 6) * 16; + case RGBA_ASTC_10x8_Format: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 7) / 8) * 16; + case RGBA_ASTC_10x10_Format: + return Math.floor((width2 + 9) / 10) * Math.floor((height2 + 9) / 10) * 16; + case RGBA_ASTC_12x10_Format: + return Math.floor((width2 + 11) / 12) * Math.floor((height2 + 9) / 10) * 16; + case RGBA_ASTC_12x12_Format: + return Math.floor((width2 + 11) / 12) * Math.floor((height2 + 11) / 12) * 16; + case RGBA_BPTC_Format: + case RGB_BPTC_SIGNED_Format: + case RGB_BPTC_UNSIGNED_Format: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 16; + case RED_RGTC1_Format: + case SIGNED_RED_RGTC1_Format: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 8; + case RED_GREEN_RGTC2_Format: + case SIGNED_RED_GREEN_RGTC2_Format: + return Math.ceil(width2 / 4) * Math.ceil(height2 / 4) * 16; + } + throw new Error(`Unable to determine texture byte length for ${format} format.`); +} +function getTextureTypeByteLength(type) { + switch (type) { + case UnsignedByteType: + case ByteType: + return { byteLength: 1, components: 1 }; + case UnsignedShortType: + case ShortType: + case HalfFloatType: + return { byteLength: 2, components: 1 }; + case UnsignedShort4444Type: + case UnsignedShort5551Type: + return { byteLength: 2, components: 4 }; + case UnsignedIntType: + case IntType: + case FloatType: + return { byteLength: 4, components: 1 }; + case UnsignedInt5999Type: + return { byteLength: 4, components: 3 }; + } + throw new Error(`Unknown texture type ${type}.`); +} +var TextureUtils = { + contain, + cover, + fill, + getByteLength +}; +if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { + revision: REVISION + } })); +} +if (typeof window !== "undefined") { + if (window.__THREE__) { + console.warn("WARNING: Multiple instances of Three.js being imported."); + } else { + window.__THREE__ = REVISION; + } +} + +// node_modules/three/build/three.module.js +function WebGLAnimation() { + let context = null; + let isAnimating = false; + let animationLoop = null; + let requestId = null; + function onAnimationFrame(time2, frame) { + animationLoop(time2, frame); + requestId = context.requestAnimationFrame(onAnimationFrame); + } + return { + start: function() { + if (isAnimating === true) + return; + if (animationLoop === null) + return; + requestId = context.requestAnimationFrame(onAnimationFrame); + isAnimating = true; + }, + stop: function() { + context.cancelAnimationFrame(requestId); + isAnimating = false; + }, + setAnimationLoop: function(callback) { + animationLoop = callback; + }, + setContext: function(value2) { + context = value2; + } + }; +} +function WebGLAttributes(gl) { + const buffers = new WeakMap; + function createBuffer(attribute, bufferType) { + const array = attribute.array; + const usage = attribute.usage; + const size = array.byteLength; + const buffer = gl.createBuffer(); + gl.bindBuffer(bufferType, buffer); + gl.bufferData(bufferType, array, usage); + attribute.onUploadCallback(); + let type; + if (array instanceof Float32Array) { + type = gl.FLOAT; + } else if (array instanceof Uint16Array) { + if (attribute.isFloat16BufferAttribute) { + type = gl.HALF_FLOAT; + } else { + type = gl.UNSIGNED_SHORT; + } + } else if (array instanceof Int16Array) { + type = gl.SHORT; + } else if (array instanceof Uint32Array) { + type = gl.UNSIGNED_INT; + } else if (array instanceof Int32Array) { + type = gl.INT; + } else if (array instanceof Int8Array) { + type = gl.BYTE; + } else if (array instanceof Uint8Array) { + type = gl.UNSIGNED_BYTE; + } else if (array instanceof Uint8ClampedArray) { + type = gl.UNSIGNED_BYTE; + } else { + throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + array); + } + return { + buffer, + type, + bytesPerElement: array.BYTES_PER_ELEMENT, + version: attribute.version, + size + }; + } + function updateBuffer(buffer, attribute, bufferType) { + const array = attribute.array; + const updateRanges = attribute.updateRanges; + gl.bindBuffer(bufferType, buffer); + if (updateRanges.length === 0) { + gl.bufferSubData(bufferType, 0, array); + } else { + updateRanges.sort((a, b) => a.start - b.start); + let mergeIndex = 0; + for (let i = 1;i < updateRanges.length; i++) { + const previousRange = updateRanges[mergeIndex]; + const range = updateRanges[i]; + if (range.start <= previousRange.start + previousRange.count + 1) { + previousRange.count = Math.max(previousRange.count, range.start + range.count - previousRange.start); + } else { + ++mergeIndex; + updateRanges[mergeIndex] = range; + } + } + updateRanges.length = mergeIndex + 1; + for (let i = 0, l = updateRanges.length;i < l; i++) { + const range = updateRanges[i]; + gl.bufferSubData(bufferType, range.start * array.BYTES_PER_ELEMENT, array, range.start, range.count); + } + attribute.clearUpdateRanges(); + } + attribute.onUploadCallback(); + } + function get(attribute) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + return buffers.get(attribute); + } + function remove(attribute) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + const data2 = buffers.get(attribute); + if (data2) { + gl.deleteBuffer(data2.buffer); + buffers.delete(attribute); + } + } + function update(attribute, bufferType) { + if (attribute.isInterleavedBufferAttribute) + attribute = attribute.data; + if (attribute.isGLBufferAttribute) { + const cached = buffers.get(attribute); + if (!cached || cached.version < attribute.version) { + buffers.set(attribute, { + buffer: attribute.buffer, + type: attribute.type, + bytesPerElement: attribute.elementSize, + version: attribute.version + }); + } + return; + } + const data2 = buffers.get(attribute); + if (data2 === undefined) { + buffers.set(attribute, createBuffer(attribute, bufferType)); + } else if (data2.version < attribute.version) { + if (data2.size !== attribute.array.byteLength) { + throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported."); + } + updateBuffer(data2.buffer, attribute, bufferType); + data2.version = attribute.version; + } + } + return { + get, + remove, + update + }; +} +var alphahash_fragment = `#ifdef USE_ALPHAHASH + if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard; +#endif`; +var alphahash_pars_fragment = `#ifdef USE_ALPHAHASH + const float ALPHA_HASH_SCALE = 0.05; + float hash2D( vec2 value ) { + return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) ); + } + float hash3D( vec3 value ) { + return hash2D( vec2( hash2D( value.xy ), value.z ) ); + } + float getAlphaHashThreshold( vec3 position ) { + float maxDeriv = max( + length( dFdx( position.xyz ) ), + length( dFdy( position.xyz ) ) + ); + float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv ); + vec2 pixScales = vec2( + exp2( floor( log2( pixScale ) ) ), + exp2( ceil( log2( pixScale ) ) ) + ); + vec2 alpha = vec2( + hash3D( floor( pixScales.x * position.xyz ) ), + hash3D( floor( pixScales.y * position.xyz ) ) + ); + float lerpFactor = fract( log2( pixScale ) ); + float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y; + float a = min( lerpFactor, 1.0 - lerpFactor ); + vec3 cases = vec3( + x * x / ( 2.0 * a * ( 1.0 - a ) ), + ( x - 0.5 * a ) / ( 1.0 - a ), + 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) ) + ); + float threshold = ( x < ( 1.0 - a ) ) + ? ( ( x < a ) ? cases.x : cases.y ) + : cases.z; + return clamp( threshold , 1.0e-6, 1.0 ); + } +#endif`; +var alphamap_fragment = `#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g; +#endif`; +var alphamap_pars_fragment = `#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`; +var alphatest_fragment = `#ifdef USE_ALPHATEST + #ifdef ALPHA_TO_COVERAGE + diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a ); + if ( diffuseColor.a == 0.0 ) discard; + #else + if ( diffuseColor.a < alphaTest ) discard; + #endif +#endif`; +var alphatest_pars_fragment = `#ifdef USE_ALPHATEST + uniform float alphaTest; +#endif`; +var aomap_fragment = `#ifdef USE_AOMAP + float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0; + reflectedLight.indirectDiffuse *= ambientOcclusion; + #if defined( USE_CLEARCOAT ) + clearcoatSpecularIndirect *= ambientOcclusion; + #endif + #if defined( USE_SHEEN ) + sheenSpecularIndirect *= ambientOcclusion; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) + float dotNV = saturate( dot( geometryNormal, geometryViewDir ) ); + reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness ); + #endif +#endif`; +var aomap_pars_fragment = `#ifdef USE_AOMAP + uniform sampler2D aoMap; + uniform float aoMapIntensity; +#endif`; +var batching_pars_vertex = `#ifdef USE_BATCHING + #if ! defined( GL_ANGLE_multi_draw ) + #define gl_DrawID _gl_DrawID + uniform int _gl_DrawID; + #endif + uniform highp sampler2D batchingTexture; + uniform highp usampler2D batchingIdTexture; + mat4 getBatchingMatrix( const in float i ) { + int size = textureSize( batchingTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } + float getIndirectIndex( const in int i ) { + int size = textureSize( batchingIdTexture, 0 ).x; + int x = i % size; + int y = i / size; + return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r ); + } +#endif +#ifdef USE_BATCHING_COLOR + uniform sampler2D batchingColorTexture; + vec3 getBatchingColor( const in float i ) { + int size = textureSize( batchingColorTexture, 0 ).x; + int j = int( i ); + int x = j % size; + int y = j / size; + return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb; + } +#endif`; +var batching_vertex = `#ifdef USE_BATCHING + mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) ); +#endif`; +var begin_vertex = `vec3 transformed = vec3( position ); +#ifdef USE_ALPHAHASH + vPosition = vec3( position ); +#endif`; +var beginnormal_vertex = `vec3 objectNormal = vec3( normal ); +#ifdef USE_TANGENT + vec3 objectTangent = vec3( tangent.xyz ); +#endif`; +var bsdfs = `float G_BlinnPhong_Implicit( ) { + return 0.25; +} +float D_BlinnPhong( const in float shininess, const in float dotNH ) { + return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess ); +} +vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( specularColor, 1.0, dotVH ); + float G = G_BlinnPhong_Implicit( ); + float D = D_BlinnPhong( shininess, dotNH ); + return F * ( G * D ); +} // validated`; +var iridescence_fragment = `#ifdef USE_IRIDESCENCE + const mat3 XYZ_TO_REC709 = mat3( + 3.2404542, -0.9692660, 0.0556434, + -1.5371385, 1.8760108, -0.2040259, + -0.4985314, 0.0415560, 1.0572252 + ); + vec3 Fresnel0ToIor( vec3 fresnel0 ) { + vec3 sqrtF0 = sqrt( fresnel0 ); + return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 ); + } + vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) { + return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) ); + } + float IorToFresnel0( float transmittedIor, float incidentIor ) { + return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor )); + } + vec3 evalSensitivity( float OPD, vec3 shift ) { + float phase = 2.0 * PI * OPD * 1.0e-9; + vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 ); + vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 ); + vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 ); + vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var ); + xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) ); + xyz /= 1.0685e-7; + vec3 rgb = XYZ_TO_REC709 * xyz; + return rgb; + } + vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) { + vec3 I; + float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) ); + float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) ); + float cosTheta2Sq = 1.0 - sinTheta2Sq; + if ( cosTheta2Sq < 0.0 ) { + return vec3( 1.0 ); + } + float cosTheta2 = sqrt( cosTheta2Sq ); + float R0 = IorToFresnel0( iridescenceIOR, outsideIOR ); + float R12 = F_Schlick( R0, 1.0, cosTheta1 ); + float T121 = 1.0 - R12; + float phi12 = 0.0; + if ( iridescenceIOR < outsideIOR ) phi12 = PI; + float phi21 = PI - phi12; + vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR ); + vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 ); + vec3 phi23 = vec3( 0.0 ); + if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI; + if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI; + if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI; + float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2; + vec3 phi = vec3( phi21 ) + phi23; + vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 ); + vec3 r123 = sqrt( R123 ); + vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 ); + vec3 C0 = R12 + Rs; + I = C0; + vec3 Cm = Rs - T121; + for ( int m = 1; m <= 2; ++ m ) { + Cm *= r123; + vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi ); + I += Cm * Sm; + } + return max( I, vec3( 0.0 ) ); + } +#endif`; +var bumpmap_pars_fragment = `#ifdef USE_BUMPMAP + uniform sampler2D bumpMap; + uniform float bumpScale; + vec2 dHdxy_fwd() { + vec2 dSTdx = dFdx( vBumpMapUv ); + vec2 dSTdy = dFdy( vBumpMapUv ); + float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x; + float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll; + float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll; + return vec2( dBx, dBy ); + } + vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) { + vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) ); + vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) ); + vec3 vN = surf_norm; + vec3 R1 = cross( vSigmaY, vN ); + vec3 R2 = cross( vN, vSigmaX ); + float fDet = dot( vSigmaX, R1 ) * faceDirection; + vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 ); + return normalize( abs( fDet ) * surf_norm - vGrad ); + } +#endif`; +var clipping_planes_fragment = `#if NUM_CLIPPING_PLANES > 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`; +var clipping_planes_pars_fragment = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`; +var clipping_planes_pars_vertex = `#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`; +var clipping_planes_vertex = `#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`; +var color_fragment = `#if defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#elif defined( USE_COLOR ) + diffuseColor.rgb *= vColor; +#endif`; +var color_pars_fragment = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) + varying vec3 vColor; +#endif`; +var color_pars_vertex = `#if defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec3 vColor; +#endif`; +var color_vertex = `#if defined( USE_COLOR_ALPHA ) + vColor = vec4( 1.0 ); +#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec3( 1.0 ); +#endif +#ifdef USE_COLOR + vColor *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.xyz *= instanceColor.xyz; +#endif +#ifdef USE_BATCHING_COLOR + vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) ); + vColor.xyz *= batchingColor.xyz; +#endif`; +var common = `#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +mat3 transposeMat3( const in mat3 m ) { + mat3 tmp; + tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); + tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); + tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); + return tmp; +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`; +var cube_uv_reflection_fragment = `#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`; +var defaultnormal_vertex = `vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`; +var displacementmap_pars_vertex = `#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`; +var displacementmap_vertex = `#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`; +var emissivemap_fragment = `#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`; +var emissivemap_pars_fragment = `#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`; +var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; +var colorspace_pars_fragment = `vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`; +var envmap_fragment = `#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #else + vec4 envColor = vec4( 0.0 ); + #endif + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif +#endif`; +var envmap_common_pars_fragment = `#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif + +#endif`; +var envmap_pars_fragment = `#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`; +var envmap_pars_vertex = `#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`; +var envmap_vertex = `#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`; +var fog_vertex = `#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`; +var fog_pars_vertex = `#ifdef USE_FOG + varying float vFogDepth; +#endif`; +var fog_fragment = `#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`; +var fog_pars_fragment = `#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`; +var gradientmap_pars_fragment = `#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`; +var lightmap_pars_fragment = `#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`; +var lights_lambert_fragment = `LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`; +var lights_lambert_pars_fragment = `varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`; +var lights_pars_begin = `uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`; +var envmap_physical_pars_fragment = `#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`; +var lights_toon_fragment = `ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`; +var lights_toon_pars_fragment = `varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`; +var lights_phong_fragment = `BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`; +var lights_phong_pars_fragment = `varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`; +var lights_physical_fragment = `PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`; +var lights_physical_pars_fragment = `struct PhysicalMaterial { + vec3 diffuseColor; + float roughness; + vec3 specularColor; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return saturate(v); + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColor; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95; + float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72; + float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) ); + return saturate( DG * RECIPROCAL_PI ); +} +vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 ); + const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 ); + vec4 r = roughness * c0 + c1; + float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y; + vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw; + return fab; +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + vec2 fab = DFGApprox( normal, viewDir, roughness ); + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + vec2 fab = DFGApprox( normal, viewDir, roughness ); + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + #endif + vec3 singleScattering = vec3( 0.0 ); + vec3 multiScattering = vec3( 0.0 ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering ); + #endif + vec3 totalScattering = singleScattering + multiScattering; + vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) ); + reflectedLight.indirectSpecular += radiance * singleScattering; + reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance; + reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`; +var lights_fragment_begin = ` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`; +var lights_fragment_maps = `#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`; +var lights_fragment_end = `#if defined( RE_IndirectDiffuse ) + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`; +var logdepthbuf_fragment = `#if defined( USE_LOGDEPTHBUF ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`; +var logdepthbuf_pars_fragment = `#if defined( USE_LOGDEPTHBUF ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`; +var logdepthbuf_pars_vertex = `#ifdef USE_LOGDEPTHBUF + varying float vFragDepth; + varying float vIsPerspective; +#endif`; +var logdepthbuf_vertex = `#ifdef USE_LOGDEPTHBUF + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`; +var map_fragment = `#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`; +var map_pars_fragment = `#ifdef USE_MAP + uniform sampler2D map; +#endif`; +var map_particle_fragment = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`; +var map_particle_pars_fragment = `#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`; +var metalnessmap_fragment = `float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`; +var metalnessmap_pars_fragment = `#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`; +var morphinstance_vertex = `#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`; +var morphcolor_vertex = `#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`; +var morphnormal_vertex = `#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`; +var morphtarget_pars_vertex = `#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`; +var morphtarget_vertex = `#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`; +var normal_fragment_begin = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`; +var normal_fragment_maps = `#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`; +var normal_pars_fragment = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`; +var normal_pars_vertex = `#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`; +var normal_vertex = `#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`; +var normalmap_pars_fragment = `#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`; +var clearcoat_normal_fragment_begin = `#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`; +var clearcoat_normal_fragment_maps = `#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`; +var clearcoat_pars_fragment = `#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`; +var iridescence_pars_fragment = `#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`; +var opaque_fragment = `#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`; +var packing = `vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + return depth * ( near - far ) - near; +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + return ( near * far ) / ( ( far - near ) * depth - far ); +}`; +var premultiplied_alpha_fragment = `#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`; +var project_vertex = `vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`; +var dithering_fragment = `#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`; +var dithering_pars_fragment = `#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`; +var roughnessmap_fragment = `float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`; +var roughnessmap_pars_fragment = `#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`; +var shadowmap_pars_fragment = `#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + float texture2DCompare( sampler2D depths, vec2 uv, float compare ) { + return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) ); + } + vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) { + return unpackRGBATo2Half( texture2D( shadow, uv ) ); + } + float VSMShadow (sampler2D shadow, vec2 uv, float compare ){ + float occlusion = 1.0; + vec2 distribution = texture2DDistribution( shadow, uv ); + float hard_shadow = step( compare , distribution.x ); + if (hard_shadow != 1.0 ) { + float distance = compare - distribution.x ; + float variance = max( 0.00000, distribution.y * distribution.y ); + float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 ); + } + return occlusion; + } + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + #if defined( SHADOWMAP_TYPE_PCF ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx0 = - texelSize.x * shadowRadius; + float dy0 = - texelSize.y * shadowRadius; + float dx1 = + texelSize.x * shadowRadius; + float dy1 = + texelSize.y * shadowRadius; + float dx2 = dx0 / 2.0; + float dy2 = dy0 / 2.0; + float dx3 = dx1 / 2.0; + float dy3 = dy1 / 2.0; + shadow = ( + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) + + texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z ) + ) * ( 1.0 / 17.0 ); + #elif defined( SHADOWMAP_TYPE_PCF_SOFT ) + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float dx = texelSize.x; + float dy = texelSize.y; + vec2 uv = shadowCoord.xy; + vec2 f = fract( uv * shadowMapSize + 0.5 ); + uv -= f * texelSize; + shadow = ( + texture2DCompare( shadowMap, uv, shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) + + texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ), + f.x ) + + mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ), + f.y ) + + mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ), + f.x ), + mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), + texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ), + f.x ), + f.y ) + ) * ( 1.0 / 9.0 ); + #elif defined( SHADOWMAP_TYPE_VSM ) + shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z ); + #else + shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + vec2 cubeToUV( vec3 v, float texelSizeY ) { + vec3 absV = abs( v ); + float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) ); + absV *= scaleToCube; + v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY ); + vec2 planar = v.xy; + float almostATexel = 1.5 * texelSizeY; + float almostOne = 1.0 - almostATexel; + if ( absV.z >= almostOne ) { + if ( v.z > 0.0 ) + planar.x = 4.0 - v.x; + } else if ( absV.x >= almostOne ) { + float signX = sign( v.x ); + planar.x = v.z * signX + 2.0 * signX; + } else if ( absV.y >= almostOne ) { + float signY = sign( v.y ); + planar.x = v.x + 2.0 * signY + 2.0; + planar.y = v.z * signY - 2.0; + } + return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 ); + } + float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + + float lightToPositionLength = length( lightToPosition ); + if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) { + float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) ); + #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM ) + vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y; + shadow = ( + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) + + texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp ) + ) * ( 1.0 / 9.0 ); + #else + shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } +#endif`; +var shadowmap_pars_vertex = `#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`; +var shadowmap_vertex = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`; +var shadowmask_pars_fragment = `float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`; +var skinbase_vertex = `#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`; +var skinning_pars_vertex = `#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`; +var skinning_vertex = `#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`; +var skinnormal_vertex = `#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`; +var specularmap_fragment = `float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`; +var specularmap_pars_fragment = `#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`; +var tonemapping_fragment = `#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`; +var tonemapping_pars_fragment = `#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`; +var transmission_fragment = `#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`; +var transmission_pars_fragment = `#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`; +var uv_pars_fragment = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`; +var uv_pars_vertex = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`; +var uv_vertex = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`; +var worldpos_vertex = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`; +var vertex$h = `varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`; +var fragment$h = `uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`; +var vertex$g = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`; +var fragment$g = `#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`; +var vertex$f = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`; +var fragment$f = `uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`; +var vertex$e = `#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`; +var fragment$e = `#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5; + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`; +var vertex$d = `#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`; +var fragment$d = `#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = packDepthToRGBA( dist ); +}`; +var vertex$c = `varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`; +var fragment$c = `uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`; +var vertex$b = `uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; +var fragment$b = `uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`; +var vertex$a = `#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; +var fragment$a = `uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`; +var vertex$9 = `#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`; +var fragment$9 = `#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`; +var vertex$8 = `#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`; +var fragment$8 = `#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`; +var vertex$7 = `#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`; +var fragment$7 = `#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`; +var vertex$6 = `#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`; +var fragment$6 = `#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`; +var vertex$5 = `#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`; +var fragment$5 = `#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor ); + outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect; + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`; +var vertex$4 = `#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`; +var fragment$4 = `#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`; +var vertex$3 = `uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`; +var fragment$3 = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`; +var vertex$2 = `#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`; +var fragment$2 = `uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include +}`; +var vertex$1 = `uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`; +var fragment$1 = `uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`; +var ShaderChunk = { + alphahash_fragment, + alphahash_pars_fragment, + alphamap_fragment, + alphamap_pars_fragment, + alphatest_fragment, + alphatest_pars_fragment, + aomap_fragment, + aomap_pars_fragment, + batching_pars_vertex, + batching_vertex, + begin_vertex, + beginnormal_vertex, + bsdfs, + iridescence_fragment, + bumpmap_pars_fragment, + clipping_planes_fragment, + clipping_planes_pars_fragment, + clipping_planes_pars_vertex, + clipping_planes_vertex, + color_fragment, + color_pars_fragment, + color_pars_vertex, + color_vertex, + common, + cube_uv_reflection_fragment, + defaultnormal_vertex, + displacementmap_pars_vertex, + displacementmap_vertex, + emissivemap_fragment, + emissivemap_pars_fragment, + colorspace_fragment, + colorspace_pars_fragment, + envmap_fragment, + envmap_common_pars_fragment, + envmap_pars_fragment, + envmap_pars_vertex, + envmap_physical_pars_fragment, + envmap_vertex, + fog_vertex, + fog_pars_vertex, + fog_fragment, + fog_pars_fragment, + gradientmap_pars_fragment, + lightmap_pars_fragment, + lights_lambert_fragment, + lights_lambert_pars_fragment, + lights_pars_begin, + lights_toon_fragment, + lights_toon_pars_fragment, + lights_phong_fragment, + lights_phong_pars_fragment, + lights_physical_fragment, + lights_physical_pars_fragment, + lights_fragment_begin, + lights_fragment_maps, + lights_fragment_end, + logdepthbuf_fragment, + logdepthbuf_pars_fragment, + logdepthbuf_pars_vertex, + logdepthbuf_vertex, + map_fragment, + map_pars_fragment, + map_particle_fragment, + map_particle_pars_fragment, + metalnessmap_fragment, + metalnessmap_pars_fragment, + morphinstance_vertex, + morphcolor_vertex, + morphnormal_vertex, + morphtarget_pars_vertex, + morphtarget_vertex, + normal_fragment_begin, + normal_fragment_maps, + normal_pars_fragment, + normal_pars_vertex, + normal_vertex, + normalmap_pars_fragment, + clearcoat_normal_fragment_begin, + clearcoat_normal_fragment_maps, + clearcoat_pars_fragment, + iridescence_pars_fragment, + opaque_fragment, + packing, + premultiplied_alpha_fragment, + project_vertex, + dithering_fragment, + dithering_pars_fragment, + roughnessmap_fragment, + roughnessmap_pars_fragment, + shadowmap_pars_fragment, + shadowmap_pars_vertex, + shadowmap_vertex, + shadowmask_pars_fragment, + skinbase_vertex, + skinning_pars_vertex, + skinning_vertex, + skinnormal_vertex, + specularmap_fragment, + specularmap_pars_fragment, + tonemapping_fragment, + tonemapping_pars_fragment, + transmission_fragment, + transmission_pars_fragment, + uv_pars_fragment, + uv_pars_vertex, + uv_vertex, + worldpos_vertex, + background_vert: vertex$h, + background_frag: fragment$h, + backgroundCube_vert: vertex$g, + backgroundCube_frag: fragment$g, + cube_vert: vertex$f, + cube_frag: fragment$f, + depth_vert: vertex$e, + depth_frag: fragment$e, + distanceRGBA_vert: vertex$d, + distanceRGBA_frag: fragment$d, + equirect_vert: vertex$c, + equirect_frag: fragment$c, + linedashed_vert: vertex$b, + linedashed_frag: fragment$b, + meshbasic_vert: vertex$a, + meshbasic_frag: fragment$a, + meshlambert_vert: vertex$9, + meshlambert_frag: fragment$9, + meshmatcap_vert: vertex$8, + meshmatcap_frag: fragment$8, + meshnormal_vert: vertex$7, + meshnormal_frag: fragment$7, + meshphong_vert: vertex$6, + meshphong_frag: fragment$6, + meshphysical_vert: vertex$5, + meshphysical_frag: fragment$5, + meshtoon_vert: vertex$4, + meshtoon_frag: fragment$4, + points_vert: vertex$3, + points_frag: fragment$3, + shadow_vert: vertex$2, + shadow_frag: fragment$2, + sprite_vert: vertex$1, + sprite_frag: fragment$1 +}; +var UniformsLib = { + common: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaTest: { value: 0 } + }, + specularmap: { + specularMap: { value: null }, + specularMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + envmap: { + envMap: { value: null }, + envMapRotation: { value: /* @__PURE__ */ new Matrix3 }, + flipEnvMap: { value: -1 }, + reflectivity: { value: 1 }, + ior: { value: 1.5 }, + refractionRatio: { value: 0.98 } + }, + aomap: { + aoMap: { value: null }, + aoMapIntensity: { value: 1 }, + aoMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + lightmap: { + lightMap: { value: null }, + lightMapIntensity: { value: 1 }, + lightMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + bumpmap: { + bumpMap: { value: null }, + bumpMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + bumpScale: { value: 1 } + }, + normalmap: { + normalMap: { value: null }, + normalMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + normalScale: { value: /* @__PURE__ */ new Vector2(1, 1) } + }, + displacementmap: { + displacementMap: { value: null }, + displacementMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + displacementScale: { value: 1 }, + displacementBias: { value: 0 } + }, + emissivemap: { + emissiveMap: { value: null }, + emissiveMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + metalnessmap: { + metalnessMap: { value: null }, + metalnessMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + roughnessmap: { + roughnessMap: { value: null }, + roughnessMapTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + gradientmap: { + gradientMap: { value: null } + }, + fog: { + fogDensity: { value: 0.00025 }, + fogNear: { value: 1 }, + fogFar: { value: 2000 }, + fogColor: { value: /* @__PURE__ */ new Color(16777215) } + }, + lights: { + ambientLightColor: { value: [] }, + lightProbe: { value: [] }, + directionalLights: { value: [], properties: { + direction: {}, + color: {} + } }, + directionalLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + directionalShadowMap: { value: [] }, + directionalShadowMatrix: { value: [] }, + spotLights: { value: [], properties: { + color: {}, + position: {}, + direction: {}, + distance: {}, + coneCos: {}, + penumbraCos: {}, + decay: {} + } }, + spotLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {} + } }, + spotLightMap: { value: [] }, + spotShadowMap: { value: [] }, + spotLightMatrix: { value: [] }, + pointLights: { value: [], properties: { + color: {}, + position: {}, + decay: {}, + distance: {} + } }, + pointLightShadows: { value: [], properties: { + shadowIntensity: 1, + shadowBias: {}, + shadowNormalBias: {}, + shadowRadius: {}, + shadowMapSize: {}, + shadowCameraNear: {}, + shadowCameraFar: {} + } }, + pointShadowMap: { value: [] }, + pointShadowMatrix: { value: [] }, + hemisphereLights: { value: [], properties: { + direction: {}, + skyColor: {}, + groundColor: {} + } }, + rectAreaLights: { value: [], properties: { + color: {}, + position: {}, + width: {}, + height: {} + } }, + ltc_1: { value: null }, + ltc_2: { value: null } + }, + points: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + size: { value: 1 }, + scale: { value: 1 }, + map: { value: null }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaTest: { value: 0 }, + uvTransform: { value: /* @__PURE__ */ new Matrix3 } + }, + sprite: { + diffuse: { value: /* @__PURE__ */ new Color(16777215) }, + opacity: { value: 1 }, + center: { value: /* @__PURE__ */ new Vector2(0.5, 0.5) }, + rotation: { value: 0 }, + map: { value: null }, + mapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaMap: { value: null }, + alphaMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + alphaTest: { value: 0 } + } +}; +var ShaderLib = { + basic: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.meshbasic_vert, + fragmentShader: ShaderChunk.meshbasic_frag + }, + lambert: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) } + } + ]), + vertexShader: ShaderChunk.meshlambert_vert, + fragmentShader: ShaderChunk.meshlambert_frag + }, + phong: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + specular: { value: /* @__PURE__ */ new Color(1118481) }, + shininess: { value: 30 } + } + ]), + vertexShader: ShaderChunk.meshphong_vert, + fragmentShader: ShaderChunk.meshphong_frag + }, + standard: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.roughnessmap, + UniformsLib.metalnessmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) }, + roughness: { value: 1 }, + metalness: { value: 0 }, + envMapIntensity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag + }, + toon: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.gradientmap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: /* @__PURE__ */ new Color(0) } + } + ]), + vertexShader: ShaderChunk.meshtoon_vert, + fragmentShader: ShaderChunk.meshtoon_frag + }, + matcap: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + UniformsLib.fog, + { + matcap: { value: null } + } + ]), + vertexShader: ShaderChunk.meshmatcap_vert, + fragmentShader: ShaderChunk.meshmatcap_frag + }, + points: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.points, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.points_vert, + fragmentShader: ShaderChunk.points_frag + }, + dashed: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.fog, + { + scale: { value: 1 }, + dashSize: { value: 1 }, + totalSize: { value: 2 } + } + ]), + vertexShader: ShaderChunk.linedashed_vert, + fragmentShader: ShaderChunk.linedashed_frag + }, + depth: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.displacementmap + ]), + vertexShader: ShaderChunk.depth_vert, + fragmentShader: ShaderChunk.depth_frag + }, + normal: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.bumpmap, + UniformsLib.normalmap, + UniformsLib.displacementmap, + { + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.meshnormal_vert, + fragmentShader: ShaderChunk.meshnormal_frag + }, + sprite: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.sprite, + UniformsLib.fog + ]), + vertexShader: ShaderChunk.sprite_vert, + fragmentShader: ShaderChunk.sprite_frag + }, + background: { + uniforms: { + uvTransform: { value: /* @__PURE__ */ new Matrix3 }, + t2D: { value: null }, + backgroundIntensity: { value: 1 } + }, + vertexShader: ShaderChunk.background_vert, + fragmentShader: ShaderChunk.background_frag + }, + backgroundCube: { + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 }, + backgroundBlurriness: { value: 0 }, + backgroundIntensity: { value: 1 }, + backgroundRotation: { value: /* @__PURE__ */ new Matrix3 } + }, + vertexShader: ShaderChunk.backgroundCube_vert, + fragmentShader: ShaderChunk.backgroundCube_frag + }, + cube: { + uniforms: { + tCube: { value: null }, + tFlip: { value: -1 }, + opacity: { value: 1 } + }, + vertexShader: ShaderChunk.cube_vert, + fragmentShader: ShaderChunk.cube_frag + }, + equirect: { + uniforms: { + tEquirect: { value: null } + }, + vertexShader: ShaderChunk.equirect_vert, + fragmentShader: ShaderChunk.equirect_frag + }, + distanceRGBA: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.common, + UniformsLib.displacementmap, + { + referencePosition: { value: /* @__PURE__ */ new Vector3 }, + nearDistance: { value: 1 }, + farDistance: { value: 1000 } + } + ]), + vertexShader: ShaderChunk.distanceRGBA_vert, + fragmentShader: ShaderChunk.distanceRGBA_frag + }, + shadow: { + uniforms: /* @__PURE__ */ mergeUniforms([ + UniformsLib.lights, + UniformsLib.fog, + { + color: { value: /* @__PURE__ */ new Color(0) }, + opacity: { value: 1 } + } + ]), + vertexShader: ShaderChunk.shadow_vert, + fragmentShader: ShaderChunk.shadow_frag + } +}; +ShaderLib.physical = { + uniforms: /* @__PURE__ */ mergeUniforms([ + ShaderLib.standard.uniforms, + { + clearcoat: { value: 0 }, + clearcoatMap: { value: null }, + clearcoatMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + clearcoatNormalMap: { value: null }, + clearcoatNormalMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + clearcoatNormalScale: { value: /* @__PURE__ */ new Vector2(1, 1) }, + clearcoatRoughness: { value: 0 }, + clearcoatRoughnessMap: { value: null }, + clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + dispersion: { value: 0 }, + iridescence: { value: 0 }, + iridescenceMap: { value: null }, + iridescenceMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + iridescenceIOR: { value: 1.3 }, + iridescenceThicknessMinimum: { value: 100 }, + iridescenceThicknessMaximum: { value: 400 }, + iridescenceThicknessMap: { value: null }, + iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + sheen: { value: 0 }, + sheenColor: { value: /* @__PURE__ */ new Color(0) }, + sheenColorMap: { value: null }, + sheenColorMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + sheenRoughness: { value: 1 }, + sheenRoughnessMap: { value: null }, + sheenRoughnessMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + transmission: { value: 0 }, + transmissionMap: { value: null }, + transmissionMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + transmissionSamplerSize: { value: /* @__PURE__ */ new Vector2 }, + transmissionSamplerMap: { value: null }, + thickness: { value: 0 }, + thicknessMap: { value: null }, + thicknessMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + attenuationDistance: { value: 0 }, + attenuationColor: { value: /* @__PURE__ */ new Color(0) }, + specularColor: { value: /* @__PURE__ */ new Color(1, 1, 1) }, + specularColorMap: { value: null }, + specularColorMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + specularIntensity: { value: 1 }, + specularIntensityMap: { value: null }, + specularIntensityMapTransform: { value: /* @__PURE__ */ new Matrix3 }, + anisotropyVector: { value: /* @__PURE__ */ new Vector2 }, + anisotropyMap: { value: null }, + anisotropyMapTransform: { value: /* @__PURE__ */ new Matrix3 } + } + ]), + vertexShader: ShaderChunk.meshphysical_vert, + fragmentShader: ShaderChunk.meshphysical_frag +}; +var _rgb = { r: 0, b: 0, g: 0 }; +var _e1$1 = /* @__PURE__ */ new Euler; +var _m1$12 = /* @__PURE__ */ new Matrix4; +function WebGLBackground(renderer2, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) { + const clearColor = new Color(0); + let clearAlpha = alpha === true ? 0 : 1; + let planeMesh; + let boxMesh; + let currentBackground = null; + let currentBackgroundVersion = 0; + let currentTonemapping = null; + function getBackground(scene) { + let background = scene.isScene === true ? scene.background : null; + if (background && background.isTexture) { + const usePMREM = scene.backgroundBlurriness > 0; + background = (usePMREM ? cubeuvmaps : cubemaps).get(background); + } + return background; + } + function render(scene) { + let forceClear = false; + const background = getBackground(scene); + if (background === null) { + setClear(clearColor, clearAlpha); + } else if (background && background.isColor) { + setClear(background, 1); + forceClear = true; + } + const environmentBlendMode = renderer2.xr.getEnvironmentBlendMode(); + if (environmentBlendMode === "additive") { + state.buffers.color.setClear(0, 0, 0, 1, premultipliedAlpha); + } else if (environmentBlendMode === "alpha-blend") { + state.buffers.color.setClear(0, 0, 0, 0, premultipliedAlpha); + } + if (renderer2.autoClear || forceClear) { + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + renderer2.clear(renderer2.autoClearColor, renderer2.autoClearDepth, renderer2.autoClearStencil); + } + } + function addToRenderList(renderList, scene) { + const background = getBackground(scene); + if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) { + if (boxMesh === undefined) { + boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({ + name: "BackgroundCubeMaterial", + uniforms: cloneUniforms(ShaderLib.backgroundCube.uniforms), + vertexShader: ShaderLib.backgroundCube.vertexShader, + fragmentShader: ShaderLib.backgroundCube.fragmentShader, + side: BackSide, + depthTest: false, + depthWrite: false, + fog: false + })); + boxMesh.geometry.deleteAttribute("normal"); + boxMesh.geometry.deleteAttribute("uv"); + boxMesh.onBeforeRender = function(renderer3, scene2, camera) { + this.matrixWorld.copyPosition(camera.matrixWorld); + }; + Object.defineProperty(boxMesh.material, "envMap", { + get: function() { + return this.uniforms.envMap.value; + } + }); + objects.update(boxMesh); + } + _e1$1.copy(scene.backgroundRotation); + _e1$1.x *= -1; + _e1$1.y *= -1; + _e1$1.z *= -1; + if (background.isCubeTexture && background.isRenderTargetTexture === false) { + _e1$1.y *= -1; + _e1$1.z *= -1; + } + boxMesh.material.uniforms.envMap.value = background; + boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1; + boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; + boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4(_m1$12.makeRotationFromEuler(_e1$1)); + boxMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer; + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer2.toneMapping) { + boxMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer2.toneMapping; + } + boxMesh.layers.enableAll(); + renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null); + } else if (background && background.isTexture) { + if (planeMesh === undefined) { + planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({ + name: "BackgroundMaterial", + uniforms: cloneUniforms(ShaderLib.background.uniforms), + vertexShader: ShaderLib.background.vertexShader, + fragmentShader: ShaderLib.background.fragmentShader, + side: FrontSide, + depthTest: false, + depthWrite: false, + fog: false + })); + planeMesh.geometry.deleteAttribute("normal"); + Object.defineProperty(planeMesh.material, "map", { + get: function() { + return this.uniforms.t2D.value; + } + }); + objects.update(planeMesh); + } + planeMesh.material.uniforms.t2D.value = background; + planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity; + planeMesh.material.toneMapped = ColorManagement.getTransfer(background.colorSpace) !== SRGBTransfer; + if (background.matrixAutoUpdate === true) { + background.updateMatrix(); + } + planeMesh.material.uniforms.uvTransform.value.copy(background.matrix); + if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer2.toneMapping) { + planeMesh.material.needsUpdate = true; + currentBackground = background; + currentBackgroundVersion = background.version; + currentTonemapping = renderer2.toneMapping; + } + planeMesh.layers.enableAll(); + renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null); + } + } + function setClear(color, alpha2) { + color.getRGB(_rgb, getUnlitUniformColorSpace(renderer2)); + state.buffers.color.setClear(_rgb.r, _rgb.g, _rgb.b, alpha2, premultipliedAlpha); + } + function dispose() { + if (boxMesh !== undefined) { + boxMesh.geometry.dispose(); + boxMesh.material.dispose(); + boxMesh = undefined; + } + if (planeMesh !== undefined) { + planeMesh.geometry.dispose(); + planeMesh.material.dispose(); + planeMesh = undefined; + } + } + return { + getClearColor: function() { + return clearColor; + }, + setClearColor: function(color, alpha2 = 1) { + clearColor.set(color); + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + getClearAlpha: function() { + return clearAlpha; + }, + setClearAlpha: function(alpha2) { + clearAlpha = alpha2; + setClear(clearColor, clearAlpha); + }, + render, + addToRenderList, + dispose + }; +} +function WebGLBindingStates(gl, attributes) { + const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const bindingStates = {}; + const defaultState = createBindingState(null); + let currentState = defaultState; + let forceUpdate = false; + function setup(object, material, program, geometry, index2) { + let updateBuffers = false; + const state = getBindingState(geometry, program, material); + if (currentState !== state) { + currentState = state; + bindVertexArrayObject(currentState.object); + } + updateBuffers = needsUpdate(object, geometry, program, index2); + if (updateBuffers) + saveCache(object, geometry, program, index2); + if (index2 !== null) { + attributes.update(index2, gl.ELEMENT_ARRAY_BUFFER); + } + if (updateBuffers || forceUpdate) { + forceUpdate = false; + setupVertexAttributes(object, material, program, geometry); + if (index2 !== null) { + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index2).buffer); + } + } + } + function createVertexArrayObject() { + return gl.createVertexArray(); + } + function bindVertexArrayObject(vao) { + return gl.bindVertexArray(vao); + } + function deleteVertexArrayObject(vao) { + return gl.deleteVertexArray(vao); + } + function getBindingState(geometry, program, material) { + const wireframe = material.wireframe === true; + let programMap = bindingStates[geometry.id]; + if (programMap === undefined) { + programMap = {}; + bindingStates[geometry.id] = programMap; + } + let stateMap = programMap[program.id]; + if (stateMap === undefined) { + stateMap = {}; + programMap[program.id] = stateMap; + } + let state = stateMap[wireframe]; + if (state === undefined) { + state = createBindingState(createVertexArrayObject()); + stateMap[wireframe] = state; + } + return state; + } + function createBindingState(vao) { + const newAttributes = []; + const enabledAttributes = []; + const attributeDivisors = []; + for (let i = 0;i < maxVertexAttributes; i++) { + newAttributes[i] = 0; + enabledAttributes[i] = 0; + attributeDivisors[i] = 0; + } + return { + geometry: null, + program: null, + wireframe: false, + newAttributes, + enabledAttributes, + attributeDivisors, + object: vao, + attributes: {}, + index: null + }; + } + function needsUpdate(object, geometry, program, index2) { + const cachedAttributes = currentState.attributes; + const geometryAttributes = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + const cachedAttribute = cachedAttributes[name2]; + let geometryAttribute = geometryAttributes[name2]; + if (geometryAttribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + geometryAttribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + geometryAttribute = object.instanceColor; + } + if (cachedAttribute === undefined) + return true; + if (cachedAttribute.attribute !== geometryAttribute) + return true; + if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) + return true; + attributesNum++; + } + } + if (currentState.attributesNum !== attributesNum) + return true; + if (currentState.index !== index2) + return true; + return false; + } + function saveCache(object, geometry, program, index2) { + const cache = {}; + const attributes2 = geometry.attributes; + let attributesNum = 0; + const programAttributes = program.getAttributes(); + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + let attribute = attributes2[name2]; + if (attribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + attribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + attribute = object.instanceColor; + } + const data2 = {}; + data2.attribute = attribute; + if (attribute && attribute.data) { + data2.data = attribute.data; + } + cache[name2] = data2; + attributesNum++; + } + } + currentState.attributes = cache; + currentState.attributesNum = attributesNum; + currentState.index = index2; + } + function initAttributes() { + const newAttributes = currentState.newAttributes; + for (let i = 0, il = newAttributes.length;i < il; i++) { + newAttributes[i] = 0; + } + } + function enableAttribute(attribute) { + enableAttributeAndDivisor(attribute, 0); + } + function enableAttributeAndDivisor(attribute, meshPerAttribute) { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + const attributeDivisors = currentState.attributeDivisors; + newAttributes[attribute] = 1; + if (enabledAttributes[attribute] === 0) { + gl.enableVertexAttribArray(attribute); + enabledAttributes[attribute] = 1; + } + if (attributeDivisors[attribute] !== meshPerAttribute) { + gl.vertexAttribDivisor(attribute, meshPerAttribute); + attributeDivisors[attribute] = meshPerAttribute; + } + } + function disableUnusedAttributes() { + const newAttributes = currentState.newAttributes; + const enabledAttributes = currentState.enabledAttributes; + for (let i = 0, il = enabledAttributes.length;i < il; i++) { + if (enabledAttributes[i] !== newAttributes[i]) { + gl.disableVertexAttribArray(i); + enabledAttributes[i] = 0; + } + } + } + function vertexAttribPointer(index2, size, type, normalized, stride, offset, integer) { + if (integer === true) { + gl.vertexAttribIPointer(index2, size, type, stride, offset); + } else { + gl.vertexAttribPointer(index2, size, type, normalized, stride, offset); + } + } + function setupVertexAttributes(object, material, program, geometry) { + initAttributes(); + const geometryAttributes = geometry.attributes; + const programAttributes = program.getAttributes(); + const materialDefaultAttributeValues = material.defaultAttributeValues; + for (const name2 in programAttributes) { + const programAttribute = programAttributes[name2]; + if (programAttribute.location >= 0) { + let geometryAttribute = geometryAttributes[name2]; + if (geometryAttribute === undefined) { + if (name2 === "instanceMatrix" && object.instanceMatrix) + geometryAttribute = object.instanceMatrix; + if (name2 === "instanceColor" && object.instanceColor) + geometryAttribute = object.instanceColor; + } + if (geometryAttribute !== undefined) { + const normalized = geometryAttribute.normalized; + const size = geometryAttribute.itemSize; + const attribute = attributes.get(geometryAttribute); + if (attribute === undefined) + continue; + const buffer = attribute.buffer; + const type = attribute.type; + const bytesPerElement = attribute.bytesPerElement; + const integer = type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType; + if (geometryAttribute.isInterleavedBufferAttribute) { + const data2 = geometryAttribute.data; + const stride = data2.stride; + const offset = geometryAttribute.offset; + if (data2.isInstancedInterleavedBuffer) { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, data2.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { + geometry._maxInstanceCount = data2.meshPerAttribute * data2.count; + } + } else { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0;i < programAttribute.locationSize; i++) { + vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement, integer); + } + } else { + if (geometryAttribute.isInstancedBufferAttribute) { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute); + } + if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) { + geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; + } + } else { + for (let i = 0;i < programAttribute.locationSize; i++) { + enableAttribute(programAttribute.location + i); + } + } + gl.bindBuffer(gl.ARRAY_BUFFER, buffer); + for (let i = 0;i < programAttribute.locationSize; i++) { + vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement, integer); + } + } + } else if (materialDefaultAttributeValues !== undefined) { + const value2 = materialDefaultAttributeValues[name2]; + if (value2 !== undefined) { + switch (value2.length) { + case 2: + gl.vertexAttrib2fv(programAttribute.location, value2); + break; + case 3: + gl.vertexAttrib3fv(programAttribute.location, value2); + break; + case 4: + gl.vertexAttrib4fv(programAttribute.location, value2); + break; + default: + gl.vertexAttrib1fv(programAttribute.location, value2); + } + } + } + } + } + disableUnusedAttributes(); + } + function dispose() { + reset(); + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometryId]; + } + } + function releaseStatesOfGeometry(geometry) { + if (bindingStates[geometry.id] === undefined) + return; + const programMap = bindingStates[geometry.id]; + for (const programId in programMap) { + const stateMap = programMap[programId]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[programId]; + } + delete bindingStates[geometry.id]; + } + function releaseStatesOfProgram(program) { + for (const geometryId in bindingStates) { + const programMap = bindingStates[geometryId]; + if (programMap[program.id] === undefined) + continue; + const stateMap = programMap[program.id]; + for (const wireframe in stateMap) { + deleteVertexArrayObject(stateMap[wireframe].object); + delete stateMap[wireframe]; + } + delete programMap[program.id]; + } + } + function reset() { + resetDefaultState(); + forceUpdate = true; + if (currentState === defaultState) + return; + currentState = defaultState; + bindVertexArrayObject(currentState.object); + } + function resetDefaultState() { + defaultState.geometry = null; + defaultState.program = null; + defaultState.wireframe = false; + } + return { + setup, + reset, + resetDefaultState, + dispose, + releaseStatesOfGeometry, + releaseStatesOfProgram, + initAttributes, + enableAttribute, + disableUnusedAttributes + }; +} +function WebGLBufferRenderer(gl, extensions, info) { + let mode; + function setMode(value2) { + mode = value2; + } + function render(start, count) { + gl.drawArrays(mode, start, count); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) + return; + gl.drawArraysInstanced(mode, start, count, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawArraysWEBGL(mode, starts, 0, counts, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0;i < starts.length; i++) { + renderInstances(starts[i], counts[i], primcount[i]); + } + } else { + extension.multiDrawArraysInstancedWEBGL(mode, starts, 0, counts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i] * primcount[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; +} +function WebGLCapabilities(gl, extensions, parameters, utils) { + let maxAnisotropy; + function getMaxAnisotropy() { + if (maxAnisotropy !== undefined) + return maxAnisotropy; + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } else { + maxAnisotropy = 0; + } + return maxAnisotropy; + } + function textureFormatReadable(textureFormat) { + if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_FORMAT)) { + return false; + } + return true; + } + function textureTypeReadable(textureType) { + const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float")); + if (textureType !== UnsignedByteType && utils.convert(textureType) !== gl.getParameter(gl.IMPLEMENTATION_COLOR_READ_TYPE) && textureType !== FloatType && !halfFloatSupportedByExt) { + return false; + } + return true; + } + function getMaxPrecision(precision2) { + if (precision2 === "highp") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) { + return "highp"; + } + precision2 = "mediump"; + } + if (precision2 === "mediump") { + if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) { + return "mediump"; + } + } + return "lowp"; + } + let precision = parameters.precision !== undefined ? parameters.precision : "highp"; + const maxPrecision = getMaxPrecision(precision); + if (maxPrecision !== precision) { + console.warn("THREE.WebGLRenderer:", precision, "not supported, using", maxPrecision, "instead."); + precision = maxPrecision; + } + const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; + const reverseDepthBuffer = parameters.reverseDepthBuffer === true && extensions.has("EXT_clip_control"); + const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); + const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); + const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); + const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); + const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); + const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS); + const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); + const vertexTextures = maxVertexTextures > 0; + const maxSamples = gl.getParameter(gl.MAX_SAMPLES); + return { + isWebGL2: true, + getMaxAnisotropy, + getMaxPrecision, + textureFormatReadable, + textureTypeReadable, + precision, + logarithmicDepthBuffer, + reverseDepthBuffer, + maxTextures, + maxVertexTextures, + maxTextureSize, + maxCubemapSize, + maxAttributes, + maxVertexUniforms, + maxVaryings, + maxFragmentUniforms, + vertexTextures, + maxSamples + }; +} +function WebGLClipping(properties) { + const scope = this; + let globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false; + const plane = new Plane, viewNormalMatrix = new Matrix3, uniform = { value: null, needsUpdate: false }; + this.uniform = uniform; + this.numPlanes = 0; + this.numIntersection = 0; + this.init = function(planes, enableLocalClipping) { + const enabled = planes.length !== 0 || enableLocalClipping || numGlobalPlanes !== 0 || localClippingEnabled; + localClippingEnabled = enableLocalClipping; + numGlobalPlanes = planes.length; + return enabled; + }; + this.beginShadows = function() { + renderingShadows = true; + projectPlanes(null); + }; + this.endShadows = function() { + renderingShadows = false; + }; + this.setGlobalState = function(planes, camera) { + globalState = projectPlanes(planes, camera, 0); + }; + this.setState = function(material, camera, useCache) { + const { clippingPlanes: planes, clipIntersection, clipShadows } = material; + const materialProperties = properties.get(material); + if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) { + if (renderingShadows) { + projectPlanes(null); + } else { + resetGlobalState(); + } + } else { + const nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4; + let dstArray = materialProperties.clippingState || null; + uniform.value = dstArray; + dstArray = projectPlanes(planes, camera, lGlobal, useCache); + for (let i = 0;i !== lGlobal; ++i) { + dstArray[i] = globalState[i]; + } + materialProperties.clippingState = dstArray; + this.numIntersection = clipIntersection ? this.numPlanes : 0; + this.numPlanes += nGlobal; + } + }; + function resetGlobalState() { + if (uniform.value !== globalState) { + uniform.value = globalState; + uniform.needsUpdate = numGlobalPlanes > 0; + } + scope.numPlanes = numGlobalPlanes; + scope.numIntersection = 0; + } + function projectPlanes(planes, camera, dstOffset, skipTransform) { + const nPlanes = planes !== null ? planes.length : 0; + let dstArray = null; + if (nPlanes !== 0) { + dstArray = uniform.value; + if (skipTransform !== true || dstArray === null) { + const flatSize = dstOffset + nPlanes * 4, viewMatrix = camera.matrixWorldInverse; + viewNormalMatrix.getNormalMatrix(viewMatrix); + if (dstArray === null || dstArray.length < flatSize) { + dstArray = new Float32Array(flatSize); + } + for (let i = 0, i4 = dstOffset;i !== nPlanes; ++i, i4 += 4) { + plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix); + plane.normal.toArray(dstArray, i4); + dstArray[i4 + 3] = plane.constant; + } + } + uniform.value = dstArray; + uniform.needsUpdate = true; + } + scope.numPlanes = nPlanes; + scope.numIntersection = 0; + return dstArray; + } +} +function WebGLCubeMaps(renderer2) { + let cubemaps = new WeakMap; + function mapTextureMapping(texture, mapping) { + if (mapping === EquirectangularReflectionMapping) { + texture.mapping = CubeReflectionMapping; + } else if (mapping === EquirectangularRefractionMapping) { + texture.mapping = CubeRefractionMapping; + } + return texture; + } + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) { + if (cubemaps.has(texture)) { + const cubemap = cubemaps.get(texture).texture; + return mapTextureMapping(cubemap, texture.mapping); + } else { + const image = texture.image; + if (image && image.height > 0) { + const renderTarget = new WebGLCubeRenderTarget(image.height); + renderTarget.fromEquirectangularTexture(renderer2, texture); + cubemaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return mapTextureMapping(renderTarget.texture, texture.mapping); + } else { + return null; + } + } + } + } + return texture; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemap = cubemaps.get(texture); + if (cubemap !== undefined) { + cubemaps.delete(texture); + cubemap.dispose(); + } + } + function dispose() { + cubemaps = new WeakMap; + } + return { + get, + dispose + }; +} +var LOD_MIN = 4; +var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; +var MAX_SAMPLES = 20; +var _flatCamera = /* @__PURE__ */ new OrthographicCamera; +var _clearColor = /* @__PURE__ */ new Color; +var _oldTarget = null; +var _oldActiveCubeFace = 0; +var _oldActiveMipmapLevel = 0; +var _oldXrEnabled = false; +var PHI = (1 + Math.sqrt(5)) / 2; +var INV_PHI = 1 / PHI; +var _axisDirections = [ + /* @__PURE__ */ new Vector3(-PHI, INV_PHI, 0), + /* @__PURE__ */ new Vector3(PHI, INV_PHI, 0), + /* @__PURE__ */ new Vector3(-INV_PHI, 0, PHI), + /* @__PURE__ */ new Vector3(INV_PHI, 0, PHI), + /* @__PURE__ */ new Vector3(0, PHI, -INV_PHI), + /* @__PURE__ */ new Vector3(0, PHI, INV_PHI), + /* @__PURE__ */ new Vector3(-1, 1, -1), + /* @__PURE__ */ new Vector3(1, 1, -1), + /* @__PURE__ */ new Vector3(-1, 1, 1), + /* @__PURE__ */ new Vector3(1, 1, 1) +]; + +class PMREMGenerator { + constructor(renderer2) { + this._renderer = renderer2; + this._pingPongRenderTarget = null; + this._lodMax = 0; + this._cubeSize = 0; + this._lodPlanes = []; + this._sizeLods = []; + this._sigmas = []; + this._blurMaterial = null; + this._cubemapMaterial = null; + this._equirectMaterial = null; + this._compileMaterial(this._blurMaterial); + } + fromScene(scene, sigma = 0, near = 0.1, far = 100) { + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + this._setSize(256); + const cubeUVRenderTarget = this._allocateTargets(); + cubeUVRenderTarget.depthBuffer = true; + this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget); + if (sigma > 0) { + this._blur(cubeUVRenderTarget, 0, 0, sigma); + } + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + fromEquirectangular(equirectangular, renderTarget = null) { + return this._fromTexture(equirectangular, renderTarget); + } + fromCubemap(cubemap, renderTarget = null) { + return this._fromTexture(cubemap, renderTarget); + } + compileCubemapShader() { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial(); + this._compileMaterial(this._cubemapMaterial); + } + } + compileEquirectangularShader() { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial(); + this._compileMaterial(this._equirectMaterial); + } + } + dispose() { + this._dispose(); + if (this._cubemapMaterial !== null) + this._cubemapMaterial.dispose(); + if (this._equirectMaterial !== null) + this._equirectMaterial.dispose(); + } + _setSize(cubeSize) { + this._lodMax = Math.floor(Math.log2(cubeSize)); + this._cubeSize = Math.pow(2, this._lodMax); + } + _dispose() { + if (this._blurMaterial !== null) + this._blurMaterial.dispose(); + if (this._pingPongRenderTarget !== null) + this._pingPongRenderTarget.dispose(); + for (let i = 0;i < this._lodPlanes.length; i++) { + this._lodPlanes[i].dispose(); + } + } + _cleanup(outputTarget) { + this._renderer.setRenderTarget(_oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel); + this._renderer.xr.enabled = _oldXrEnabled; + outputTarget.scissorTest = false; + _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height); + } + _fromTexture(texture, renderTarget) { + if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) { + this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width); + } else { + this._setSize(texture.image.width / 4); + } + _oldTarget = this._renderer.getRenderTarget(); + _oldActiveCubeFace = this._renderer.getActiveCubeFace(); + _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel(); + _oldXrEnabled = this._renderer.xr.enabled; + this._renderer.xr.enabled = false; + const cubeUVRenderTarget = renderTarget || this._allocateTargets(); + this._textureToCubeUV(texture, cubeUVRenderTarget); + this._applyPMREM(cubeUVRenderTarget); + this._cleanup(cubeUVRenderTarget); + return cubeUVRenderTarget; + } + _allocateTargets() { + const width2 = 3 * Math.max(this._cubeSize, 16 * 7); + const height2 = 4 * this._cubeSize; + const params = { + magFilter: LinearFilter, + minFilter: LinearFilter, + generateMipmaps: false, + type: HalfFloatType, + format: RGBAFormat, + colorSpace: LinearSRGBColorSpace, + depthBuffer: false + }; + const cubeUVRenderTarget = _createRenderTarget(width2, height2, params); + if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width2 || this._pingPongRenderTarget.height !== height2) { + if (this._pingPongRenderTarget !== null) { + this._dispose(); + } + this._pingPongRenderTarget = _createRenderTarget(width2, height2, params); + const { _lodMax } = this; + ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes(_lodMax)); + this._blurMaterial = _getBlurShader(_lodMax, width2, height2); + } + return cubeUVRenderTarget; + } + _compileMaterial(material) { + const tmpMesh = new Mesh(this._lodPlanes[0], material); + this._renderer.compile(tmpMesh, _flatCamera); + } + _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) { + const fov2 = 90; + const aspect2 = 1; + const cubeCamera = new PerspectiveCamera(fov2, aspect2, near, far); + const upSign = [1, -1, 1, 1, 1, 1]; + const forwardSign = [1, 1, 1, -1, -1, -1]; + const renderer2 = this._renderer; + const originalAutoClear = renderer2.autoClear; + const toneMapping = renderer2.toneMapping; + renderer2.getClearColor(_clearColor); + renderer2.toneMapping = NoToneMapping; + renderer2.autoClear = false; + const backgroundMaterial = new MeshBasicMaterial({ + name: "PMREM.Background", + side: BackSide, + depthWrite: false, + depthTest: false + }); + const backgroundBox = new Mesh(new BoxGeometry, backgroundMaterial); + let useSolidColor = false; + const background = scene.background; + if (background) { + if (background.isColor) { + backgroundMaterial.color.copy(background); + scene.background = null; + useSolidColor = true; + } + } else { + backgroundMaterial.color.copy(_clearColor); + useSolidColor = true; + } + for (let i = 0;i < 6; i++) { + const col = i % 3; + if (col === 0) { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(forwardSign[i], 0, 0); + } else if (col === 1) { + cubeCamera.up.set(0, 0, upSign[i]); + cubeCamera.lookAt(0, forwardSign[i], 0); + } else { + cubeCamera.up.set(0, upSign[i], 0); + cubeCamera.lookAt(0, 0, forwardSign[i]); + } + const size = this._cubeSize; + _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size); + renderer2.setRenderTarget(cubeUVRenderTarget); + if (useSolidColor) { + renderer2.render(backgroundBox, cubeCamera); + } + renderer2.render(scene, cubeCamera); + } + backgroundBox.geometry.dispose(); + backgroundBox.material.dispose(); + renderer2.toneMapping = toneMapping; + renderer2.autoClear = originalAutoClear; + scene.background = background; + } + _textureToCubeUV(texture, cubeUVRenderTarget) { + const renderer2 = this._renderer; + const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping; + if (isCubeTexture) { + if (this._cubemapMaterial === null) { + this._cubemapMaterial = _getCubemapMaterial(); + } + this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1; + } else { + if (this._equirectMaterial === null) { + this._equirectMaterial = _getEquirectMaterial(); + } + } + const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; + const mesh = new Mesh(this._lodPlanes[0], material); + const uniforms = material.uniforms; + uniforms["envMap"].value = texture; + const size = this._cubeSize; + _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size); + renderer2.setRenderTarget(cubeUVRenderTarget); + renderer2.render(mesh, _flatCamera); + } + _applyPMREM(cubeUVRenderTarget) { + const renderer2 = this._renderer; + const autoClear = renderer2.autoClear; + renderer2.autoClear = false; + const n = this._lodPlanes.length; + for (let i = 1;i < n; i++) { + const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]); + const poleAxis = _axisDirections[(n - i - 1) % _axisDirections.length]; + this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis); + } + renderer2.autoClear = autoClear; + } + _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) { + const pingPongRenderTarget = this._pingPongRenderTarget; + this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, "latitudinal", poleAxis); + this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, "longitudinal", poleAxis); + } + _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) { + const renderer2 = this._renderer; + const blurMaterial = this._blurMaterial; + if (direction !== "latitudinal" && direction !== "longitudinal") { + console.error("blur direction must be either latitudinal or longitudinal!"); + } + const STANDARD_DEVIATIONS = 3; + const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial); + const blurUniforms = blurMaterial.uniforms; + const pixels = this._sizeLods[lodIn] - 1; + const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1); + const sigmaPixels = sigmaRadians / radiansPerPixel; + const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES; + if (samples > MAX_SAMPLES) { + console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`); + } + const weights = []; + let sum2 = 0; + for (let i = 0;i < MAX_SAMPLES; ++i) { + const x2 = i / sigmaPixels; + const weight = Math.exp(-x2 * x2 / 2); + weights.push(weight); + if (i === 0) { + sum2 += weight; + } else if (i < samples) { + sum2 += 2 * weight; + } + } + for (let i = 0;i < weights.length; i++) { + weights[i] = weights[i] / sum2; + } + blurUniforms["envMap"].value = targetIn.texture; + blurUniforms["samples"].value = samples; + blurUniforms["weights"].value = weights; + blurUniforms["latitudinal"].value = direction === "latitudinal"; + if (poleAxis) { + blurUniforms["poleAxis"].value = poleAxis; + } + const { _lodMax } = this; + blurUniforms["dTheta"].value = radiansPerPixel; + blurUniforms["mipInt"].value = _lodMax - lodIn; + const outputSize = this._sizeLods[lodOut]; + const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0); + const y = 4 * (this._cubeSize - outputSize); + _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize); + renderer2.setRenderTarget(targetOut); + renderer2.render(blurMesh, _flatCamera); + } +} +function _createPlanes(lodMax) { + const lodPlanes = []; + const sizeLods = []; + const sigmas = []; + let lod = lodMax; + const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; + for (let i = 0;i < totalLods; i++) { + const sizeLod = Math.pow(2, lod); + sizeLods.push(sizeLod); + let sigma = 1 / sizeLod; + if (i > lodMax - LOD_MIN) { + sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1]; + } else if (i === 0) { + sigma = 0; + } + sigmas.push(sigma); + const texelSize = 1 / (sizeLod - 2); + const min = -texelSize; + const max = 1 + texelSize; + const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max]; + const cubeFaces = 6; + const vertices = 6; + const positionSize = 3; + const uvSize = 2; + const faceIndexSize = 1; + const position2 = new Float32Array(positionSize * vertices * cubeFaces); + const uv = new Float32Array(uvSize * vertices * cubeFaces); + const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces); + for (let face = 0;face < cubeFaces; face++) { + const x = face % 3 * 2 / 3 - 1; + const y = face > 2 ? 0 : -1; + const coordinates = [ + x, + y, + 0, + x + 2 / 3, + y, + 0, + x + 2 / 3, + y + 1, + 0, + x, + y, + 0, + x + 2 / 3, + y + 1, + 0, + x, + y + 1, + 0 + ]; + position2.set(coordinates, positionSize * vertices * face); + uv.set(uv1, uvSize * vertices * face); + const fill2 = [face, face, face, face, face, face]; + faceIndex.set(fill2, faceIndexSize * vertices * face); + } + const planes = new BufferGeometry; + planes.setAttribute("position", new BufferAttribute(position2, positionSize)); + planes.setAttribute("uv", new BufferAttribute(uv, uvSize)); + planes.setAttribute("faceIndex", new BufferAttribute(faceIndex, faceIndexSize)); + lodPlanes.push(planes); + if (lod > LOD_MIN) { + lod--; + } + } + return { lodPlanes, sizeLods, sigmas }; +} +function _createRenderTarget(width2, height2, params) { + const cubeUVRenderTarget = new WebGLRenderTarget(width2, height2, params); + cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; + cubeUVRenderTarget.texture.name = "PMREM.cubeUv"; + cubeUVRenderTarget.scissorTest = true; + return cubeUVRenderTarget; +} +function _setViewport(target, x, y, width2, height2) { + target.viewport.set(x, y, width2, height2); + target.scissor.set(x, y, width2, height2); +} +function _getBlurShader(lodMax, width2, height2) { + const weights = new Float32Array(MAX_SAMPLES); + const poleAxis = new Vector3(0, 1, 0); + const shaderMaterial = new ShaderMaterial({ + name: "SphericalGaussianBlur", + defines: { + n: MAX_SAMPLES, + CUBEUV_TEXEL_WIDTH: 1 / width2, + CUBEUV_TEXEL_HEIGHT: 1 / height2, + CUBEUV_MAX_MIP: `${lodMax}.0` + }, + uniforms: { + envMap: { value: null }, + samples: { value: 1 }, + weights: { value: weights }, + latitudinal: { value: false }, + dTheta: { value: 0 }, + mipInt: { value: 0 }, + poleAxis: { value: poleAxis } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + return shaderMaterial; +} +function _getEquirectMaterial() { + return new ShaderMaterial({ + name: "EquirectangularToCubeUV", + uniforms: { + envMap: { value: null } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); +} +function _getCubemapMaterial() { + return new ShaderMaterial({ + name: "CubemapToCubeUV", + uniforms: { + envMap: { value: null }, + flipEnvMap: { value: -1 } + }, + vertexShader: _getCommonVertexShader(), + fragmentShader: ` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); +} +function _getCommonVertexShader() { + return ` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `; +} +function WebGLCubeUVMaps(renderer2) { + let cubeUVmaps = new WeakMap; + let pmremGenerator = null; + function get(texture) { + if (texture && texture.isTexture) { + const mapping = texture.mapping; + const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping; + const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; + if (isEquirectMap || isCubeMap) { + let renderTarget = cubeUVmaps.get(texture); + const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0; + if (texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion) { + if (pmremGenerator === null) + pmremGenerator = new PMREMGenerator(renderer2); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + return renderTarget.texture; + } else { + if (renderTarget !== undefined) { + return renderTarget.texture; + } else { + const image = texture.image; + if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) { + if (pmremGenerator === null) + pmremGenerator = new PMREMGenerator(renderer2); + renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture); + renderTarget.texture.pmremVersion = texture.pmremVersion; + cubeUVmaps.set(texture, renderTarget); + texture.addEventListener("dispose", onTextureDispose); + return renderTarget.texture; + } else { + return null; + } + } + } + } + } + return texture; + } + function isCubeTextureComplete(image) { + let count = 0; + const length2 = 6; + for (let i = 0;i < length2; i++) { + if (image[i] !== undefined) + count++; + } + return count === length2; + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + const cubemapUV = cubeUVmaps.get(texture); + if (cubemapUV !== undefined) { + cubeUVmaps.delete(texture); + cubemapUV.dispose(); + } + } + function dispose() { + cubeUVmaps = new WeakMap; + if (pmremGenerator !== null) { + pmremGenerator.dispose(); + pmremGenerator = null; + } + } + return { + get, + dispose + }; +} +function WebGLExtensions(gl) { + const extensions = {}; + function getExtension(name2) { + if (extensions[name2] !== undefined) { + return extensions[name2]; + } + let extension; + switch (name2) { + case "WEBGL_depth_texture": + extension = gl.getExtension("WEBGL_depth_texture") || gl.getExtension("MOZ_WEBGL_depth_texture") || gl.getExtension("WEBKIT_WEBGL_depth_texture"); + break; + case "EXT_texture_filter_anisotropic": + extension = gl.getExtension("EXT_texture_filter_anisotropic") || gl.getExtension("MOZ_EXT_texture_filter_anisotropic") || gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic"); + break; + case "WEBGL_compressed_texture_s3tc": + extension = gl.getExtension("WEBGL_compressed_texture_s3tc") || gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"); + break; + case "WEBGL_compressed_texture_pvrtc": + extension = gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"); + break; + default: + extension = gl.getExtension(name2); + } + extensions[name2] = extension; + return extension; + } + return { + has: function(name2) { + return getExtension(name2) !== null; + }, + init: function() { + getExtension("EXT_color_buffer_float"); + getExtension("WEBGL_clip_cull_distance"); + getExtension("OES_texture_float_linear"); + getExtension("EXT_color_buffer_half_float"); + getExtension("WEBGL_multisampled_render_to_texture"); + getExtension("WEBGL_render_shared_exponent"); + }, + get: function(name2) { + const extension = getExtension(name2); + if (extension === null) { + warnOnce("THREE.WebGLRenderer: " + name2 + " extension not supported."); + } + return extension; + } + }; +} +function WebGLGeometries(gl, attributes, info, bindingStates) { + const geometries = {}; + const wireframeAttributes = new WeakMap; + function onGeometryDispose(event) { + const geometry = event.target; + if (geometry.index !== null) { + attributes.remove(geometry.index); + } + for (const name2 in geometry.attributes) { + attributes.remove(geometry.attributes[name2]); + } + geometry.removeEventListener("dispose", onGeometryDispose); + delete geometries[geometry.id]; + const attribute = wireframeAttributes.get(geometry); + if (attribute) { + attributes.remove(attribute); + wireframeAttributes.delete(geometry); + } + bindingStates.releaseStatesOfGeometry(geometry); + if (geometry.isInstancedBufferGeometry === true) { + delete geometry._maxInstanceCount; + } + info.memory.geometries--; + } + function get(object, geometry) { + if (geometries[geometry.id] === true) + return geometry; + geometry.addEventListener("dispose", onGeometryDispose); + geometries[geometry.id] = true; + info.memory.geometries++; + return geometry; + } + function update(geometry) { + const geometryAttributes = geometry.attributes; + for (const name2 in geometryAttributes) { + attributes.update(geometryAttributes[name2], gl.ARRAY_BUFFER); + } + } + function updateWireframeAttribute(geometry) { + const indices = []; + const geometryIndex = geometry.index; + const geometryPosition = geometry.attributes.position; + let version = 0; + if (geometryIndex !== null) { + const array = geometryIndex.array; + version = geometryIndex.version; + for (let i = 0, l = array.length;i < l; i += 3) { + const a = array[i + 0]; + const b = array[i + 1]; + const c = array[i + 2]; + indices.push(a, b, b, c, c, a); + } + } else if (geometryPosition !== undefined) { + const array = geometryPosition.array; + version = geometryPosition.version; + for (let i = 0, l = array.length / 3 - 1;i < l; i += 3) { + const a = i + 0; + const b = i + 1; + const c = i + 2; + indices.push(a, b, b, c, c, a); + } + } else { + return; + } + const attribute = new ((arrayNeedsUint32(indices)) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1); + attribute.version = version; + const previousAttribute = wireframeAttributes.get(geometry); + if (previousAttribute) + attributes.remove(previousAttribute); + wireframeAttributes.set(geometry, attribute); + } + function getWireframeAttribute(geometry) { + const currentAttribute = wireframeAttributes.get(geometry); + if (currentAttribute) { + const geometryIndex = geometry.index; + if (geometryIndex !== null) { + if (currentAttribute.version < geometryIndex.version) { + updateWireframeAttribute(geometry); + } + } + } else { + updateWireframeAttribute(geometry); + } + return wireframeAttributes.get(geometry); + } + return { + get, + update, + getWireframeAttribute + }; +} +function WebGLIndexedBufferRenderer(gl, extensions, info) { + let mode; + function setMode(value2) { + mode = value2; + } + let type, bytesPerElement; + function setIndex(value2) { + type = value2.type; + bytesPerElement = value2.bytesPerElement; + } + function render(start, count) { + gl.drawElements(mode, count, type, start * bytesPerElement); + info.update(count, mode, 1); + } + function renderInstances(start, count, primcount) { + if (primcount === 0) + return; + gl.drawElementsInstanced(mode, count, type, start * bytesPerElement, primcount); + info.update(count, mode, primcount); + } + function renderMultiDraw(starts, counts, drawCount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + extension.multiDrawElementsWEBGL(mode, counts, 0, type, starts, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i]; + } + info.update(elementCount, mode, 1); + } + function renderMultiDrawInstances(starts, counts, drawCount, primcount) { + if (drawCount === 0) + return; + const extension = extensions.get("WEBGL_multi_draw"); + if (extension === null) { + for (let i = 0;i < starts.length; i++) { + renderInstances(starts[i] / bytesPerElement, counts[i], primcount[i]); + } + } else { + extension.multiDrawElementsInstancedWEBGL(mode, counts, 0, type, starts, 0, primcount, 0, drawCount); + let elementCount = 0; + for (let i = 0;i < drawCount; i++) { + elementCount += counts[i] * primcount[i]; + } + info.update(elementCount, mode, 1); + } + } + this.setMode = setMode; + this.setIndex = setIndex; + this.render = render; + this.renderInstances = renderInstances; + this.renderMultiDraw = renderMultiDraw; + this.renderMultiDrawInstances = renderMultiDrawInstances; +} +function WebGLInfo(gl) { + const memory = { + geometries: 0, + textures: 0 + }; + const render = { + frame: 0, + calls: 0, + triangles: 0, + points: 0, + lines: 0 + }; + function update(count, mode, instanceCount) { + render.calls++; + switch (mode) { + case gl.TRIANGLES: + render.triangles += instanceCount * (count / 3); + break; + case gl.LINES: + render.lines += instanceCount * (count / 2); + break; + case gl.LINE_STRIP: + render.lines += instanceCount * (count - 1); + break; + case gl.LINE_LOOP: + render.lines += instanceCount * count; + break; + case gl.POINTS: + render.points += instanceCount * count; + break; + default: + console.error("THREE.WebGLInfo: Unknown draw mode:", mode); + break; + } + } + function reset() { + render.calls = 0; + render.triangles = 0; + render.points = 0; + render.lines = 0; + } + return { + memory, + render, + programs: null, + autoReset: true, + reset, + update + }; +} +function WebGLMorphtargets(gl, capabilities, textures) { + const morphTextures = new WeakMap; + const morph = new Vector4; + function update(object, geometry, program) { + const objectInfluences = object.morphTargetInfluences; + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + let entry = morphTextures.get(geometry); + if (entry === undefined || entry.count !== morphTargetsCount) { + let disposeTexture = function() { + texture.dispose(); + morphTextures.delete(geometry); + geometry.removeEventListener("dispose", disposeTexture); + }; + if (entry !== undefined) + entry.texture.dispose(); + const hasMorphPosition = geometry.morphAttributes.position !== undefined; + const hasMorphNormals = geometry.morphAttributes.normal !== undefined; + const hasMorphColors = geometry.morphAttributes.color !== undefined; + const morphTargets = geometry.morphAttributes.position || []; + const morphNormals = geometry.morphAttributes.normal || []; + const morphColors = geometry.morphAttributes.color || []; + let vertexDataCount = 0; + if (hasMorphPosition === true) + vertexDataCount = 1; + if (hasMorphNormals === true) + vertexDataCount = 2; + if (hasMorphColors === true) + vertexDataCount = 3; + let width2 = geometry.attributes.position.count * vertexDataCount; + let height2 = 1; + if (width2 > capabilities.maxTextureSize) { + height2 = Math.ceil(width2 / capabilities.maxTextureSize); + width2 = capabilities.maxTextureSize; + } + const buffer = new Float32Array(width2 * height2 * 4 * morphTargetsCount); + const texture = new DataArrayTexture(buffer, width2, height2, morphTargetsCount); + texture.type = FloatType; + texture.needsUpdate = true; + const vertexDataStride = vertexDataCount * 4; + for (let i = 0;i < morphTargetsCount; i++) { + const morphTarget = morphTargets[i]; + const morphNormal = morphNormals[i]; + const morphColor = morphColors[i]; + const offset = width2 * height2 * 4 * i; + for (let j = 0;j < morphTarget.count; j++) { + const stride = j * vertexDataStride; + if (hasMorphPosition === true) { + morph.fromBufferAttribute(morphTarget, j); + buffer[offset + stride + 0] = morph.x; + buffer[offset + stride + 1] = morph.y; + buffer[offset + stride + 2] = morph.z; + buffer[offset + stride + 3] = 0; + } + if (hasMorphNormals === true) { + morph.fromBufferAttribute(morphNormal, j); + buffer[offset + stride + 4] = morph.x; + buffer[offset + stride + 5] = morph.y; + buffer[offset + stride + 6] = morph.z; + buffer[offset + stride + 7] = 0; + } + if (hasMorphColors === true) { + morph.fromBufferAttribute(morphColor, j); + buffer[offset + stride + 8] = morph.x; + buffer[offset + stride + 9] = morph.y; + buffer[offset + stride + 10] = morph.z; + buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1; + } + } + } + entry = { + count: morphTargetsCount, + texture, + size: new Vector2(width2, height2) + }; + morphTextures.set(geometry, entry); + geometry.addEventListener("dispose", disposeTexture); + } + if (object.isInstancedMesh === true && object.morphTexture !== null) { + program.getUniforms().setValue(gl, "morphTexture", object.morphTexture, textures); + } else { + let morphInfluencesSum = 0; + for (let i = 0;i < objectInfluences.length; i++) { + morphInfluencesSum += objectInfluences[i]; + } + const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; + program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence); + program.getUniforms().setValue(gl, "morphTargetInfluences", objectInfluences); + } + program.getUniforms().setValue(gl, "morphTargetsTexture", entry.texture, textures); + program.getUniforms().setValue(gl, "morphTargetsTextureSize", entry.size); + } + return { + update + }; +} +function WebGLObjects(gl, geometries, attributes, info) { + let updateMap = new WeakMap; + function update(object) { + const frame = info.render.frame; + const geometry = object.geometry; + const buffergeometry = geometries.get(object, geometry); + if (updateMap.get(buffergeometry) !== frame) { + geometries.update(buffergeometry); + updateMap.set(buffergeometry, frame); + } + if (object.isInstancedMesh) { + if (object.hasEventListener("dispose", onInstancedMeshDispose) === false) { + object.addEventListener("dispose", onInstancedMeshDispose); + } + if (updateMap.get(object) !== frame) { + attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER); + if (object.instanceColor !== null) { + attributes.update(object.instanceColor, gl.ARRAY_BUFFER); + } + updateMap.set(object, frame); + } + } + if (object.isSkinnedMesh) { + const skeleton = object.skeleton; + if (updateMap.get(skeleton) !== frame) { + skeleton.update(); + updateMap.set(skeleton, frame); + } + } + return buffergeometry; + } + function dispose() { + updateMap = new WeakMap; + } + function onInstancedMeshDispose(event) { + const instancedMesh = event.target; + instancedMesh.removeEventListener("dispose", onInstancedMeshDispose); + attributes.remove(instancedMesh.instanceMatrix); + if (instancedMesh.instanceColor !== null) + attributes.remove(instancedMesh.instanceColor); + } + return { + update, + dispose + }; +} +var emptyTexture = /* @__PURE__ */ new Texture; +var emptyShadowTexture = /* @__PURE__ */ new DepthTexture(1, 1); +var emptyArrayTexture = /* @__PURE__ */ new DataArrayTexture; +var empty3dTexture = /* @__PURE__ */ new Data3DTexture; +var emptyCubeTexture = /* @__PURE__ */ new CubeTexture; +var arrayCacheF32 = []; +var arrayCacheI32 = []; +var mat4array = new Float32Array(16); +var mat3array = new Float32Array(9); +var mat2array = new Float32Array(4); +function flatten2(array, nBlocks, blockSize) { + const firstElem = array[0]; + if (firstElem <= 0 || firstElem > 0) + return array; + const n = nBlocks * blockSize; + let r = arrayCacheF32[n]; + if (r === undefined) { + r = new Float32Array(n); + arrayCacheF32[n] = r; + } + if (nBlocks !== 0) { + firstElem.toArray(r, 0); + for (let i = 1, offset = 0;i !== nBlocks; ++i) { + offset += blockSize; + array[i].toArray(r, offset); + } + } + return r; +} +function arraysEqual(a, b) { + if (a.length !== b.length) + return false; + for (let i = 0, l = a.length;i < l; i++) { + if (a[i] !== b[i]) + return false; + } + return true; +} +function copyArray(a, b) { + for (let i = 0, l = b.length;i < l; i++) { + a[i] = b[i]; + } +} +function allocTexUnits(textures, n) { + let r = arrayCacheI32[n]; + if (r === undefined) { + r = new Int32Array(n); + arrayCacheI32[n] = r; + } + for (let i = 0;i !== n; ++i) { + r[i] = textures.allocateTextureUnit(); + } + return r; +} +function setValueV1f(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1f(this.addr, v); + cache[0] = v; +} +function setValueV2f(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2f(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform2fv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV3f(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3f(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else if (v.r !== undefined) { + if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) { + gl.uniform3f(this.addr, v.r, v.g, v.b); + cache[0] = v.r; + cache[1] = v.g; + cache[2] = v.b; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform3fv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV4f(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4f(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform4fv(this.addr, v); + copyArray(cache, v); + } +} +function setValueM2(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual(cache, v)) + return; + gl.uniformMatrix2fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) + return; + mat2array.set(elements); + gl.uniformMatrix2fv(this.addr, false, mat2array); + copyArray(cache, elements); + } +} +function setValueM3(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual(cache, v)) + return; + gl.uniformMatrix3fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) + return; + mat3array.set(elements); + gl.uniformMatrix3fv(this.addr, false, mat3array); + copyArray(cache, elements); + } +} +function setValueM4(gl, v) { + const cache = this.cache; + const elements = v.elements; + if (elements === undefined) { + if (arraysEqual(cache, v)) + return; + gl.uniformMatrix4fv(this.addr, false, v); + copyArray(cache, v); + } else { + if (arraysEqual(cache, elements)) + return; + mat4array.set(elements); + gl.uniformMatrix4fv(this.addr, false, mat4array); + copyArray(cache, elements); + } +} +function setValueV1i(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1i(this.addr, v); + cache[0] = v; +} +function setValueV2i(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2i(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform2iv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV3i(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3i(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform3iv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV4i(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4i(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform4iv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV1ui(gl, v) { + const cache = this.cache; + if (cache[0] === v) + return; + gl.uniform1ui(this.addr, v); + cache[0] = v; +} +function setValueV2ui(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y) { + gl.uniform2ui(this.addr, v.x, v.y); + cache[0] = v.x; + cache[1] = v.y; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform2uiv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV3ui(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) { + gl.uniform3ui(this.addr, v.x, v.y, v.z); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform3uiv(this.addr, v); + copyArray(cache, v); + } +} +function setValueV4ui(gl, v) { + const cache = this.cache; + if (v.x !== undefined) { + if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) { + gl.uniform4ui(this.addr, v.x, v.y, v.z, v.w); + cache[0] = v.x; + cache[1] = v.y; + cache[2] = v.z; + cache[3] = v.w; + } + } else { + if (arraysEqual(cache, v)) + return; + gl.uniform4uiv(this.addr, v); + copyArray(cache, v); + } +} +function setValueT1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + let emptyTexture2D; + if (this.type === gl.SAMPLER_2D_SHADOW) { + emptyShadowTexture.compareFunction = LessEqualCompare; + emptyTexture2D = emptyShadowTexture; + } else { + emptyTexture2D = emptyTexture; + } + textures.setTexture2D(v || emptyTexture2D, unit); +} +function setValueT3D1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture3D(v || empty3dTexture, unit); +} +function setValueT6(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTextureCube(v || emptyCubeTexture, unit); +} +function setValueT2DArray1(gl, v, textures) { + const cache = this.cache; + const unit = textures.allocateTextureUnit(); + if (cache[0] !== unit) { + gl.uniform1i(this.addr, unit); + cache[0] = unit; + } + textures.setTexture2DArray(v || emptyArrayTexture, unit); +} +function getSingularSetter(type) { + switch (type) { + case 5126: + return setValueV1f; + case 35664: + return setValueV2f; + case 35665: + return setValueV3f; + case 35666: + return setValueV4f; + case 35674: + return setValueM2; + case 35675: + return setValueM3; + case 35676: + return setValueM4; + case 5124: + case 35670: + return setValueV1i; + case 35667: + case 35671: + return setValueV2i; + case 35668: + case 35672: + return setValueV3i; + case 35669: + case 35673: + return setValueV4i; + case 5125: + return setValueV1ui; + case 36294: + return setValueV2ui; + case 36295: + return setValueV3ui; + case 36296: + return setValueV4ui; + case 35678: + case 36198: + case 36298: + case 36306: + case 35682: + return setValueT1; + case 35679: + case 36299: + case 36307: + return setValueT3D1; + case 35680: + case 36300: + case 36308: + case 36293: + return setValueT6; + case 36289: + case 36303: + case 36311: + case 36292: + return setValueT2DArray1; + } +} +function setValueV1fArray(gl, v) { + gl.uniform1fv(this.addr, v); +} +function setValueV2fArray(gl, v) { + const data2 = flatten2(v, this.size, 2); + gl.uniform2fv(this.addr, data2); +} +function setValueV3fArray(gl, v) { + const data2 = flatten2(v, this.size, 3); + gl.uniform3fv(this.addr, data2); +} +function setValueV4fArray(gl, v) { + const data2 = flatten2(v, this.size, 4); + gl.uniform4fv(this.addr, data2); +} +function setValueM2Array(gl, v) { + const data2 = flatten2(v, this.size, 4); + gl.uniformMatrix2fv(this.addr, false, data2); +} +function setValueM3Array(gl, v) { + const data2 = flatten2(v, this.size, 9); + gl.uniformMatrix3fv(this.addr, false, data2); +} +function setValueM4Array(gl, v) { + const data2 = flatten2(v, this.size, 16); + gl.uniformMatrix4fv(this.addr, false, data2); +} +function setValueV1iArray(gl, v) { + gl.uniform1iv(this.addr, v); +} +function setValueV2iArray(gl, v) { + gl.uniform2iv(this.addr, v); +} +function setValueV3iArray(gl, v) { + gl.uniform3iv(this.addr, v); +} +function setValueV4iArray(gl, v) { + gl.uniform4iv(this.addr, v); +} +function setValueV1uiArray(gl, v) { + gl.uniform1uiv(this.addr, v); +} +function setValueV2uiArray(gl, v) { + gl.uniform2uiv(this.addr, v); +} +function setValueV3uiArray(gl, v) { + gl.uniform3uiv(this.addr, v); +} +function setValueV4uiArray(gl, v) { + gl.uniform4uiv(this.addr, v); +} +function setValueT1Array(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTexture2D(v[i] || emptyTexture, units[i]); + } +} +function setValueT3DArray(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTexture3D(v[i] || empty3dTexture, units[i]); + } +} +function setValueT6Array(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTextureCube(v[i] || emptyCubeTexture, units[i]); + } +} +function setValueT2DArrayArray(gl, v, textures) { + const cache = this.cache; + const n = v.length; + const units = allocTexUnits(textures, n); + if (!arraysEqual(cache, units)) { + gl.uniform1iv(this.addr, units); + copyArray(cache, units); + } + for (let i = 0;i !== n; ++i) { + textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]); + } +} +function getPureArraySetter(type) { + switch (type) { + case 5126: + return setValueV1fArray; + case 35664: + return setValueV2fArray; + case 35665: + return setValueV3fArray; + case 35666: + return setValueV4fArray; + case 35674: + return setValueM2Array; + case 35675: + return setValueM3Array; + case 35676: + return setValueM4Array; + case 5124: + case 35670: + return setValueV1iArray; + case 35667: + case 35671: + return setValueV2iArray; + case 35668: + case 35672: + return setValueV3iArray; + case 35669: + case 35673: + return setValueV4iArray; + case 5125: + return setValueV1uiArray; + case 36294: + return setValueV2uiArray; + case 36295: + return setValueV3uiArray; + case 36296: + return setValueV4uiArray; + case 35678: + case 36198: + case 36298: + case 36306: + case 35682: + return setValueT1Array; + case 35679: + case 36299: + case 36307: + return setValueT3DArray; + case 35680: + case 36300: + case 36308: + case 36293: + return setValueT6Array; + case 36289: + case 36303: + case 36311: + case 36292: + return setValueT2DArrayArray; + } +} + +class SingleUniform { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.setValue = getSingularSetter(activeInfo.type); + } +} + +class PureArrayUniform { + constructor(id, activeInfo, addr) { + this.id = id; + this.addr = addr; + this.cache = []; + this.type = activeInfo.type; + this.size = activeInfo.size; + this.setValue = getPureArraySetter(activeInfo.type); + } +} + +class StructuredUniform { + constructor(id) { + this.id = id; + this.seq = []; + this.map = {}; + } + setValue(gl, value2, textures) { + const seq = this.seq; + for (let i = 0, n = seq.length;i !== n; ++i) { + const u = seq[i]; + u.setValue(gl, value2[u.id], textures); + } + } +} +var RePathPart = /(\w+)(\])?(\[|\.)?/g; +function addUniform(container, uniformObject) { + container.seq.push(uniformObject); + container.map[uniformObject.id] = uniformObject; +} +function parseUniform(activeInfo, addr, container) { + const path = activeInfo.name, pathLength = path.length; + RePathPart.lastIndex = 0; + while (true) { + const match = RePathPart.exec(path), matchEnd = RePathPart.lastIndex; + let id = match[1]; + const idIsIndex = match[2] === "]", subscript = match[3]; + if (idIsIndex) + id = id | 0; + if (subscript === undefined || subscript === "[" && matchEnd + 2 === pathLength) { + addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr)); + break; + } else { + const map2 = container.map; + let next = map2[id]; + if (next === undefined) { + next = new StructuredUniform(id); + addUniform(container, next); + } + container = next; + } + } +} + +class WebGLUniforms { + constructor(gl, program) { + this.seq = []; + this.map = {}; + const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (let i = 0;i < n; ++i) { + const info = gl.getActiveUniform(program, i), addr = gl.getUniformLocation(program, info.name); + parseUniform(info, addr, this); + } + } + setValue(gl, name2, value2, textures) { + const u = this.map[name2]; + if (u !== undefined) + u.setValue(gl, value2, textures); + } + setOptional(gl, object, name2) { + const v = object[name2]; + if (v !== undefined) + this.setValue(gl, name2, v); + } + static upload(gl, seq, values2, textures) { + for (let i = 0, n = seq.length;i !== n; ++i) { + const u = seq[i], v = values2[u.id]; + if (v.needsUpdate !== false) { + u.setValue(gl, v.value, textures); + } + } + } + static seqWithValue(seq, values2) { + const r = []; + for (let i = 0, n = seq.length;i !== n; ++i) { + const u = seq[i]; + if (u.id in values2) + r.push(u); + } + return r; + } +} +function WebGLShader(gl, type, string) { + const shader = gl.createShader(type); + gl.shaderSource(shader, string); + gl.compileShader(shader); + return shader; +} +var COMPLETION_STATUS_KHR = 37297; +var programIdCount = 0; +function handleSource(string, errorLine) { + const lines = string.split(` +`); + const lines2 = []; + const from = Math.max(errorLine - 6, 0); + const to = Math.min(errorLine + 6, lines.length); + for (let i = from;i < to; i++) { + const line = i + 1; + lines2.push(`${line === errorLine ? ">" : " "} ${line}: ${lines[i]}`); + } + return lines2.join(` +`); +} +var _m0 = /* @__PURE__ */ new Matrix3; +function getEncodingComponents(colorSpace) { + ColorManagement._getMatrix(_m0, ColorManagement.workingColorSpace, colorSpace); + const encodingMatrix = `mat3( ${_m0.elements.map((v) => v.toFixed(4))} )`; + switch (ColorManagement.getTransfer(colorSpace)) { + case LinearTransfer: + return [encodingMatrix, "LinearTransferOETF"]; + case SRGBTransfer: + return [encodingMatrix, "sRGBTransferOETF"]; + default: + console.warn("THREE.WebGLProgram: Unsupported color space: ", colorSpace); + return [encodingMatrix, "LinearTransferOETF"]; + } +} +function getShaderErrors(gl, shader, type) { + const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS); + const errors = gl.getShaderInfoLog(shader).trim(); + if (status && errors === "") + return ""; + const errorMatches = /ERROR: 0:(\d+)/.exec(errors); + if (errorMatches) { + const errorLine = parseInt(errorMatches[1]); + return type.toUpperCase() + ` + +` + errors + ` + +` + handleSource(gl.getShaderSource(shader), errorLine); + } else { + return errors; + } +} +function getTexelEncodingFunction(functionName, colorSpace) { + const components = getEncodingComponents(colorSpace); + return [ + `vec4 ${functionName}( vec4 value ) {`, + ` return ${components[1]}( vec4( value.rgb * ${components[0]}, value.a ) );`, + "}" + ].join(` +`); +} +function getToneMappingFunction(functionName, toneMapping) { + let toneMappingName; + switch (toneMapping) { + case LinearToneMapping: + toneMappingName = "Linear"; + break; + case ReinhardToneMapping: + toneMappingName = "Reinhard"; + break; + case CineonToneMapping: + toneMappingName = "Cineon"; + break; + case ACESFilmicToneMapping: + toneMappingName = "ACESFilmic"; + break; + case AgXToneMapping: + toneMappingName = "AgX"; + break; + case NeutralToneMapping: + toneMappingName = "Neutral"; + break; + case CustomToneMapping: + toneMappingName = "Custom"; + break; + default: + console.warn("THREE.WebGLProgram: Unsupported toneMapping:", toneMapping); + toneMappingName = "Linear"; + } + return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; +} +var _v02 = /* @__PURE__ */ new Vector3; +function getLuminanceFunction() { + ColorManagement.getLuminanceCoefficients(_v02); + const r = _v02.x.toFixed(4); + const g = _v02.y.toFixed(4); + const b = _v02.z.toFixed(4); + return [ + "float luminance( const in vec3 rgb ) {", + ` const vec3 weights = vec3( ${r}, ${g}, ${b} );`, + "\treturn dot( weights, rgb );", + "}" + ].join(` +`); +} +function generateVertexExtensions(parameters) { + const chunks = [ + parameters.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "", + parameters.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : "" + ]; + return chunks.filter(filterEmptyLine).join(` +`); +} +function generateDefines(defines) { + const chunks = []; + for (const name2 in defines) { + const value2 = defines[name2]; + if (value2 === false) + continue; + chunks.push("#define " + name2 + " " + value2); + } + return chunks.join(` +`); +} +function fetchAttributeLocations(gl, program) { + const attributes = {}; + const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (let i = 0;i < n; i++) { + const info = gl.getActiveAttrib(program, i); + const name2 = info.name; + let locationSize = 1; + if (info.type === gl.FLOAT_MAT2) + locationSize = 2; + if (info.type === gl.FLOAT_MAT3) + locationSize = 3; + if (info.type === gl.FLOAT_MAT4) + locationSize = 4; + attributes[name2] = { + type: info.type, + location: gl.getAttribLocation(program, name2), + locationSize + }; + } + return attributes; +} +function filterEmptyLine(string) { + return string !== ""; +} +function replaceLightNums(string, parameters) { + const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; + return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows); +} +function replaceClippingPlaneNums(string, parameters) { + return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection); +} +var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; +function resolveIncludes(string) { + return string.replace(includePattern, includeReplacer); +} +var shaderChunkMap = new Map; +function includeReplacer(match, include) { + let string = ShaderChunk[include]; + if (string === undefined) { + const newInclude = shaderChunkMap.get(include); + if (newInclude !== undefined) { + string = ShaderChunk[newInclude]; + console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude); + } else { + throw new Error("Can not resolve #include <" + include + ">"); + } + } + return resolveIncludes(string); +} +var unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; +function unrollLoops(string) { + return string.replace(unrollLoopPattern, loopReplacer); +} +function loopReplacer(match, start, end, snippet) { + let string = ""; + for (let i = parseInt(start);i < parseInt(end); i++) { + string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i + " ]").replace(/UNROLLED_LOOP_INDEX/g, i); + } + return string; +} +function generatePrecision(parameters) { + let precisionstring = `precision ${parameters.precision} float; + precision ${parameters.precision} int; + precision ${parameters.precision} sampler2D; + precision ${parameters.precision} samplerCube; + precision ${parameters.precision} sampler3D; + precision ${parameters.precision} sampler2DArray; + precision ${parameters.precision} sampler2DShadow; + precision ${parameters.precision} samplerCubeShadow; + precision ${parameters.precision} sampler2DArrayShadow; + precision ${parameters.precision} isampler2D; + precision ${parameters.precision} isampler3D; + precision ${parameters.precision} isamplerCube; + precision ${parameters.precision} isampler2DArray; + precision ${parameters.precision} usampler2D; + precision ${parameters.precision} usampler3D; + precision ${parameters.precision} usamplerCube; + precision ${parameters.precision} usampler2DArray; + `; + if (parameters.precision === "highp") { + precisionstring += ` +#define HIGH_PRECISION`; + } else if (parameters.precision === "mediump") { + precisionstring += ` +#define MEDIUM_PRECISION`; + } else if (parameters.precision === "lowp") { + precisionstring += ` +#define LOW_PRECISION`; + } + return precisionstring; +} +function generateShadowMapTypeDefine(parameters) { + let shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; + if (parameters.shadowMapType === PCFShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; + } else if (parameters.shadowMapType === PCFSoftShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; + } else if (parameters.shadowMapType === VSMShadowMap) { + shadowMapTypeDefine = "SHADOWMAP_TYPE_VSM"; + } + return shadowMapTypeDefine; +} +function generateEnvMapTypeDefine(parameters) { + let envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeReflectionMapping: + case CubeRefractionMapping: + envMapTypeDefine = "ENVMAP_TYPE_CUBE"; + break; + case CubeUVReflectionMapping: + envMapTypeDefine = "ENVMAP_TYPE_CUBE_UV"; + break; + } + } + return envMapTypeDefine; +} +function generateEnvMapModeDefine(parameters) { + let envMapModeDefine = "ENVMAP_MODE_REFLECTION"; + if (parameters.envMap) { + switch (parameters.envMapMode) { + case CubeRefractionMapping: + envMapModeDefine = "ENVMAP_MODE_REFRACTION"; + break; + } + } + return envMapModeDefine; +} +function generateEnvMapBlendingDefine(parameters) { + let envMapBlendingDefine = "ENVMAP_BLENDING_NONE"; + if (parameters.envMap) { + switch (parameters.combine) { + case MultiplyOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_MULTIPLY"; + break; + case MixOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_MIX"; + break; + case AddOperation: + envMapBlendingDefine = "ENVMAP_BLENDING_ADD"; + break; + } + } + return envMapBlendingDefine; +} +function generateCubeUVSize(parameters) { + const imageHeight = parameters.envMapCubeUVHeight; + if (imageHeight === null) + return null; + const maxMip = Math.log2(imageHeight) - 2; + const texelHeight = 1 / imageHeight; + const texelWidth = 1 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16)); + return { texelWidth, texelHeight, maxMip }; +} +function WebGLProgram(renderer2, cacheKey, parameters, bindingStates) { + const gl = renderer2.getContext(); + const defines = parameters.defines; + let vertexShader = parameters.vertexShader; + let fragmentShader = parameters.fragmentShader; + const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters); + const envMapTypeDefine = generateEnvMapTypeDefine(parameters); + const envMapModeDefine = generateEnvMapModeDefine(parameters); + const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters); + const envMapCubeUVSize = generateCubeUVSize(parameters); + const customVertexExtensions = generateVertexExtensions(parameters); + const customDefines = generateDefines(defines); + const program = gl.createProgram(); + let prefixVertex, prefixFragment; + let versionString = parameters.glslVersion ? "#version " + parameters.glslVersion + ` +` : ""; + if (parameters.isRawShaderMaterial) { + prefixVertex = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine).join(` +`); + if (prefixVertex.length > 0) { + prefixVertex += ` +`; + } + prefixFragment = [ + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines + ].filter(filterEmptyLine).join(` +`); + if (prefixFragment.length > 0) { + prefixFragment += ` +`; + } + } else { + prefixVertex = [ + generatePrecision(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "", + parameters.batching ? "#define USE_BATCHING" : "", + parameters.batchingColor ? "#define USE_BATCHING_COLOR" : "", + parameters.instancing ? "#define USE_INSTANCING" : "", + parameters.instancingColor ? "#define USE_INSTANCING_COLOR" : "", + parameters.instancingMorph ? "#define USE_INSTANCING_MORPH" : "", + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.displacementMap ? "#define USE_DISPLACEMENTMAP" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.mapUv ? "#define MAP_UV " + parameters.mapUv : "", + parameters.alphaMapUv ? "#define ALPHAMAP_UV " + parameters.alphaMapUv : "", + parameters.lightMapUv ? "#define LIGHTMAP_UV " + parameters.lightMapUv : "", + parameters.aoMapUv ? "#define AOMAP_UV " + parameters.aoMapUv : "", + parameters.emissiveMapUv ? "#define EMISSIVEMAP_UV " + parameters.emissiveMapUv : "", + parameters.bumpMapUv ? "#define BUMPMAP_UV " + parameters.bumpMapUv : "", + parameters.normalMapUv ? "#define NORMALMAP_UV " + parameters.normalMapUv : "", + parameters.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + parameters.displacementMapUv : "", + parameters.metalnessMapUv ? "#define METALNESSMAP_UV " + parameters.metalnessMapUv : "", + parameters.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + parameters.roughnessMapUv : "", + parameters.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + parameters.anisotropyMapUv : "", + parameters.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + parameters.clearcoatMapUv : "", + parameters.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + parameters.clearcoatNormalMapUv : "", + parameters.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + parameters.clearcoatRoughnessMapUv : "", + parameters.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + parameters.iridescenceMapUv : "", + parameters.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + parameters.iridescenceThicknessMapUv : "", + parameters.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + parameters.sheenColorMapUv : "", + parameters.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + parameters.sheenRoughnessMapUv : "", + parameters.specularMapUv ? "#define SPECULARMAP_UV " + parameters.specularMapUv : "", + parameters.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + parameters.specularColorMapUv : "", + parameters.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + parameters.specularIntensityMapUv : "", + parameters.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + parameters.transmissionMapUv : "", + parameters.thicknessMapUv ? "#define THICKNESSMAP_UV " + parameters.thicknessMapUv : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.skinning ? "#define USE_SKINNING" : "", + parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", + parameters.morphNormals && parameters.flatShading === false ? "#define USE_MORPHNORMALS" : "", + parameters.morphColors ? "#define USE_MORPHCOLORS" : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + parameters.morphTextureStride : "", + parameters.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + parameters.morphTargetsCount : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "", + "uniform mat4 modelMatrix;", + "uniform mat4 modelViewMatrix;", + "uniform mat4 projectionMatrix;", + "uniform mat4 viewMatrix;", + "uniform mat3 normalMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + "#ifdef USE_INSTANCING", + "\tattribute mat4 instanceMatrix;", + "#endif", + "#ifdef USE_INSTANCING_COLOR", + "\tattribute vec3 instanceColor;", + "#endif", + "#ifdef USE_INSTANCING_MORPH", + "\tuniform sampler2D morphTexture;", + "#endif", + "attribute vec3 position;", + "attribute vec3 normal;", + "attribute vec2 uv;", + "#ifdef USE_UV1", + "\tattribute vec2 uv1;", + "#endif", + "#ifdef USE_UV2", + "\tattribute vec2 uv2;", + "#endif", + "#ifdef USE_UV3", + "\tattribute vec2 uv3;", + "#endif", + "#ifdef USE_TANGENT", + "\tattribute vec4 tangent;", + "#endif", + "#if defined( USE_COLOR_ALPHA )", + "\tattribute vec4 color;", + "#elif defined( USE_COLOR )", + "\tattribute vec3 color;", + "#endif", + "#ifdef USE_SKINNING", + "\tattribute vec4 skinIndex;", + "\tattribute vec4 skinWeight;", + "#endif", + ` +` + ].filter(filterEmptyLine).join(` +`); + prefixFragment = [ + generatePrecision(parameters), + "#define SHADER_TYPE " + parameters.shaderType, + "#define SHADER_NAME " + parameters.shaderName, + customDefines, + parameters.useFog && parameters.fog ? "#define USE_FOG" : "", + parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", + parameters.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "", + parameters.map ? "#define USE_MAP" : "", + parameters.matcap ? "#define USE_MATCAP" : "", + parameters.envMap ? "#define USE_ENVMAP" : "", + parameters.envMap ? "#define " + envMapTypeDefine : "", + parameters.envMap ? "#define " + envMapModeDefine : "", + parameters.envMap ? "#define " + envMapBlendingDefine : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_WIDTH " + envMapCubeUVSize.texelWidth : "", + envMapCubeUVSize ? "#define CUBEUV_TEXEL_HEIGHT " + envMapCubeUVSize.texelHeight : "", + envMapCubeUVSize ? "#define CUBEUV_MAX_MIP " + envMapCubeUVSize.maxMip + ".0" : "", + parameters.lightMap ? "#define USE_LIGHTMAP" : "", + parameters.aoMap ? "#define USE_AOMAP" : "", + parameters.bumpMap ? "#define USE_BUMPMAP" : "", + parameters.normalMap ? "#define USE_NORMALMAP" : "", + parameters.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", + parameters.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", + parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", + parameters.anisotropy ? "#define USE_ANISOTROPY" : "", + parameters.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", + parameters.clearcoat ? "#define USE_CLEARCOAT" : "", + parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", + parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", + parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", + parameters.dispersion ? "#define USE_DISPERSION" : "", + parameters.iridescence ? "#define USE_IRIDESCENCE" : "", + parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", + parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", + parameters.specularMap ? "#define USE_SPECULARMAP" : "", + parameters.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", + parameters.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", + parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", + parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", + parameters.alphaMap ? "#define USE_ALPHAMAP" : "", + parameters.alphaTest ? "#define USE_ALPHATEST" : "", + parameters.alphaHash ? "#define USE_ALPHAHASH" : "", + parameters.sheen ? "#define USE_SHEEN" : "", + parameters.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", + parameters.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", + parameters.transmission ? "#define USE_TRANSMISSION" : "", + parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", + parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", + parameters.vertexTangents && parameters.flatShading === false ? "#define USE_TANGENT" : "", + parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? "#define USE_COLOR" : "", + parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", + parameters.vertexUv1s ? "#define USE_UV1" : "", + parameters.vertexUv2s ? "#define USE_UV2" : "", + parameters.vertexUv3s ? "#define USE_UV3" : "", + parameters.pointsUvs ? "#define USE_POINTS_UV" : "", + parameters.gradientMap ? "#define USE_GRADIENTMAP" : "", + parameters.flatShading ? "#define FLAT_SHADED" : "", + parameters.doubleSided ? "#define DOUBLE_SIDED" : "", + parameters.flipSided ? "#define FLIP_SIDED" : "", + parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", + parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", + parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", + parameters.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", + parameters.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", + parameters.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "", + parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", + parameters.reverseDepthBuffer ? "#define USE_REVERSEDEPTHBUF" : "", + "uniform mat4 viewMatrix;", + "uniform vec3 cameraPosition;", + "uniform bool isOrthographic;", + parameters.toneMapping !== NoToneMapping ? "#define TONE_MAPPING" : "", + parameters.toneMapping !== NoToneMapping ? ShaderChunk["tonemapping_pars_fragment"] : "", + parameters.toneMapping !== NoToneMapping ? getToneMappingFunction("toneMapping", parameters.toneMapping) : "", + parameters.dithering ? "#define DITHERING" : "", + parameters.opaque ? "#define OPAQUE" : "", + ShaderChunk["colorspace_pars_fragment"], + getTexelEncodingFunction("linearToOutputTexel", parameters.outputColorSpace), + getLuminanceFunction(), + parameters.useDepthPacking ? "#define DEPTH_PACKING " + parameters.depthPacking : "", + ` +` + ].filter(filterEmptyLine).join(` +`); + } + vertexShader = resolveIncludes(vertexShader); + vertexShader = replaceLightNums(vertexShader, parameters); + vertexShader = replaceClippingPlaneNums(vertexShader, parameters); + fragmentShader = resolveIncludes(fragmentShader); + fragmentShader = replaceLightNums(fragmentShader, parameters); + fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters); + vertexShader = unrollLoops(vertexShader); + fragmentShader = unrollLoops(fragmentShader); + if (parameters.isRawShaderMaterial !== true) { + versionString = `#version 300 es +`; + prefixVertex = [ + customVertexExtensions, + "#define attribute in", + "#define varying out", + "#define texture2D texture" + ].join(` +`) + ` +` + prefixVertex; + prefixFragment = [ + "#define varying in", + parameters.glslVersion === GLSL3 ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", + parameters.glslVersion === GLSL3 ? "" : "#define gl_FragColor pc_fragColor", + "#define gl_FragDepthEXT gl_FragDepth", + "#define texture2D texture", + "#define textureCube texture", + "#define texture2DProj textureProj", + "#define texture2DLodEXT textureLod", + "#define texture2DProjLodEXT textureProjLod", + "#define textureCubeLodEXT textureLod", + "#define texture2DGradEXT textureGrad", + "#define texture2DProjGradEXT textureProjGrad", + "#define textureCubeGradEXT textureGrad" + ].join(` +`) + ` +` + prefixFragment; + } + const vertexGlsl = versionString + prefixVertex + vertexShader; + const fragmentGlsl = versionString + prefixFragment + fragmentShader; + const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl); + const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl); + gl.attachShader(program, glVertexShader); + gl.attachShader(program, glFragmentShader); + if (parameters.index0AttributeName !== undefined) { + gl.bindAttribLocation(program, 0, parameters.index0AttributeName); + } else if (parameters.morphTargets === true) { + gl.bindAttribLocation(program, 0, "position"); + } + gl.linkProgram(program); + function onFirstUse(self2) { + if (renderer2.debug.checkShaderErrors) { + const programLog = gl.getProgramInfoLog(program).trim(); + const vertexLog = gl.getShaderInfoLog(glVertexShader).trim(); + const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim(); + let runnable = true; + let haveDiagnostics = true; + if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) { + runnable = false; + if (typeof renderer2.debug.onShaderError === "function") { + renderer2.debug.onShaderError(gl, program, glVertexShader, glFragmentShader); + } else { + const vertexErrors = getShaderErrors(gl, glVertexShader, "vertex"); + const fragmentErrors = getShaderErrors(gl, glFragmentShader, "fragment"); + console.error("THREE.WebGLProgram: Shader Error " + gl.getError() + " - " + "VALIDATE_STATUS " + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + ` + +` + "Material Name: " + self2.name + ` +` + "Material Type: " + self2.type + ` + +` + "Program Info Log: " + programLog + ` +` + vertexErrors + ` +` + fragmentErrors); + } + } else if (programLog !== "") { + console.warn("THREE.WebGLProgram: Program Info Log:", programLog); + } else if (vertexLog === "" || fragmentLog === "") { + haveDiagnostics = false; + } + if (haveDiagnostics) { + self2.diagnostics = { + runnable, + programLog, + vertexShader: { + log: vertexLog, + prefix: prefixVertex + }, + fragmentShader: { + log: fragmentLog, + prefix: prefixFragment + } + }; + } + } + gl.deleteShader(glVertexShader); + gl.deleteShader(glFragmentShader); + cachedUniforms = new WebGLUniforms(gl, program); + cachedAttributes = fetchAttributeLocations(gl, program); + } + let cachedUniforms; + this.getUniforms = function() { + if (cachedUniforms === undefined) { + onFirstUse(this); + } + return cachedUniforms; + }; + let cachedAttributes; + this.getAttributes = function() { + if (cachedAttributes === undefined) { + onFirstUse(this); + } + return cachedAttributes; + }; + let programReady = parameters.rendererExtensionParallelShaderCompile === false; + this.isReady = function() { + if (programReady === false) { + programReady = gl.getProgramParameter(program, COMPLETION_STATUS_KHR); + } + return programReady; + }; + this.destroy = function() { + bindingStates.releaseStatesOfProgram(this); + gl.deleteProgram(program); + this.program = undefined; + }; + this.type = parameters.shaderType; + this.name = parameters.shaderName; + this.id = programIdCount++; + this.cacheKey = cacheKey; + this.usedTimes = 1; + this.program = program; + this.vertexShader = glVertexShader; + this.fragmentShader = glFragmentShader; + return this; +} +var _id2 = 0; + +class WebGLShaderCache { + constructor() { + this.shaderCache = new Map; + this.materialCache = new Map; + } + update(material) { + const vertexShader = material.vertexShader; + const fragmentShader = material.fragmentShader; + const vertexShaderStage = this._getShaderStage(vertexShader); + const fragmentShaderStage = this._getShaderStage(fragmentShader); + const materialShaders = this._getShaderCacheForMaterial(material); + if (materialShaders.has(vertexShaderStage) === false) { + materialShaders.add(vertexShaderStage); + vertexShaderStage.usedTimes++; + } + if (materialShaders.has(fragmentShaderStage) === false) { + materialShaders.add(fragmentShaderStage); + fragmentShaderStage.usedTimes++; + } + return this; + } + remove(material) { + const materialShaders = this.materialCache.get(material); + for (const shaderStage of materialShaders) { + shaderStage.usedTimes--; + if (shaderStage.usedTimes === 0) + this.shaderCache.delete(shaderStage.code); + } + this.materialCache.delete(material); + return this; + } + getVertexShaderID(material) { + return this._getShaderStage(material.vertexShader).id; + } + getFragmentShaderID(material) { + return this._getShaderStage(material.fragmentShader).id; + } + dispose() { + this.shaderCache.clear(); + this.materialCache.clear(); + } + _getShaderCacheForMaterial(material) { + const cache = this.materialCache; + let set = cache.get(material); + if (set === undefined) { + set = new Set; + cache.set(material, set); + } + return set; + } + _getShaderStage(code) { + const cache = this.shaderCache; + let stage = cache.get(code); + if (stage === undefined) { + stage = new WebGLShaderStage(code); + cache.set(code, stage); + } + return stage; + } +} + +class WebGLShaderStage { + constructor(code) { + this.id = _id2++; + this.code = code; + this.usedTimes = 0; + } +} +function WebGLPrograms(renderer2, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) { + const _programLayers = new Layers; + const _customShaders = new WebGLShaderCache; + const _activeChannels = new Set; + const programs = []; + const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; + const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures; + let precision = capabilities.precision; + const shaderIDs = { + MeshDepthMaterial: "depth", + MeshDistanceMaterial: "distanceRGBA", + MeshNormalMaterial: "normal", + MeshBasicMaterial: "basic", + MeshLambertMaterial: "lambert", + MeshPhongMaterial: "phong", + MeshToonMaterial: "toon", + MeshStandardMaterial: "physical", + MeshPhysicalMaterial: "physical", + MeshMatcapMaterial: "matcap", + LineBasicMaterial: "basic", + LineDashedMaterial: "dashed", + PointsMaterial: "points", + ShadowMaterial: "shadow", + SpriteMaterial: "sprite" + }; + function getChannel(value2) { + _activeChannels.add(value2); + if (value2 === 0) + return "uv"; + return `uv${value2}`; + } + function getParameters(material, lights, shadows, scene, object) { + const fog = scene.fog; + const geometry = object.geometry; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null; + const shaderID = shaderIDs[material.type]; + if (material.precision !== null) { + precision = capabilities.getMaxPrecision(material.precision); + if (precision !== material.precision) { + console.warn("THREE.WebGLProgram.getParameters:", material.precision, "not supported, using", precision, "instead."); + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + let morphTextureStride = 0; + if (geometry.morphAttributes.position !== undefined) + morphTextureStride = 1; + if (geometry.morphAttributes.normal !== undefined) + morphTextureStride = 2; + if (geometry.morphAttributes.color !== undefined) + morphTextureStride = 3; + let vertexShader, fragmentShader; + let customVertexShaderID, customFragmentShaderID; + if (shaderID) { + const shader = ShaderLib[shaderID]; + vertexShader = shader.vertexShader; + fragmentShader = shader.fragmentShader; + } else { + vertexShader = material.vertexShader; + fragmentShader = material.fragmentShader; + _customShaders.update(material); + customVertexShaderID = _customShaders.getVertexShaderID(material); + customFragmentShaderID = _customShaders.getFragmentShaderID(material); + } + const currentRenderTarget = renderer2.getRenderTarget(); + const reverseDepthBuffer = renderer2.state.buffers.depth.getReversed(); + const IS_INSTANCEDMESH = object.isInstancedMesh === true; + const IS_BATCHEDMESH = object.isBatchedMesh === true; + const HAS_MAP = !!material.map; + const HAS_MATCAP = !!material.matcap; + const HAS_ENVMAP = !!envMap; + const HAS_AOMAP = !!material.aoMap; + const HAS_LIGHTMAP = !!material.lightMap; + const HAS_BUMPMAP = !!material.bumpMap; + const HAS_NORMALMAP = !!material.normalMap; + const HAS_DISPLACEMENTMAP = !!material.displacementMap; + const HAS_EMISSIVEMAP = !!material.emissiveMap; + const HAS_METALNESSMAP = !!material.metalnessMap; + const HAS_ROUGHNESSMAP = !!material.roughnessMap; + const HAS_ANISOTROPY = material.anisotropy > 0; + const HAS_CLEARCOAT = material.clearcoat > 0; + const HAS_DISPERSION = material.dispersion > 0; + const HAS_IRIDESCENCE = material.iridescence > 0; + const HAS_SHEEN = material.sheen > 0; + const HAS_TRANSMISSION = material.transmission > 0; + const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !!material.anisotropyMap; + const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !!material.clearcoatMap; + const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !!material.clearcoatNormalMap; + const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !!material.clearcoatRoughnessMap; + const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !!material.iridescenceMap; + const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !!material.iridescenceThicknessMap; + const HAS_SHEEN_COLORMAP = HAS_SHEEN && !!material.sheenColorMap; + const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !!material.sheenRoughnessMap; + const HAS_SPECULARMAP = !!material.specularMap; + const HAS_SPECULAR_COLORMAP = !!material.specularColorMap; + const HAS_SPECULAR_INTENSITYMAP = !!material.specularIntensityMap; + const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !!material.transmissionMap; + const HAS_THICKNESSMAP = HAS_TRANSMISSION && !!material.thicknessMap; + const HAS_GRADIENTMAP = !!material.gradientMap; + const HAS_ALPHAMAP = !!material.alphaMap; + const HAS_ALPHATEST = material.alphaTest > 0; + const HAS_ALPHAHASH = !!material.alphaHash; + const HAS_EXTENSIONS = !!material.extensions; + let toneMapping = NoToneMapping; + if (material.toneMapped) { + if (currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true) { + toneMapping = renderer2.toneMapping; + } + } + const parameters = { + shaderID, + shaderType: material.type, + shaderName: material.name, + vertexShader, + fragmentShader, + defines: material.defines, + customVertexShaderID, + customFragmentShaderID, + isRawShaderMaterial: material.isRawShaderMaterial === true, + glslVersion: material.glslVersion, + precision, + batching: IS_BATCHEDMESH, + batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null, + instancing: IS_INSTANCEDMESH, + instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null, + instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null, + supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES, + outputColorSpace: currentRenderTarget === null ? renderer2.outputColorSpace : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace, + alphaToCoverage: !!material.alphaToCoverage, + map: HAS_MAP, + matcap: HAS_MATCAP, + envMap: HAS_ENVMAP, + envMapMode: HAS_ENVMAP && envMap.mapping, + envMapCubeUVHeight, + aoMap: HAS_AOMAP, + lightMap: HAS_LIGHTMAP, + bumpMap: HAS_BUMPMAP, + normalMap: HAS_NORMALMAP, + displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP, + emissiveMap: HAS_EMISSIVEMAP, + normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap, + normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap, + metalnessMap: HAS_METALNESSMAP, + roughnessMap: HAS_ROUGHNESSMAP, + anisotropy: HAS_ANISOTROPY, + anisotropyMap: HAS_ANISOTROPYMAP, + clearcoat: HAS_CLEARCOAT, + clearcoatMap: HAS_CLEARCOATMAP, + clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP, + clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP, + dispersion: HAS_DISPERSION, + iridescence: HAS_IRIDESCENCE, + iridescenceMap: HAS_IRIDESCENCEMAP, + iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP, + sheen: HAS_SHEEN, + sheenColorMap: HAS_SHEEN_COLORMAP, + sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP, + specularMap: HAS_SPECULARMAP, + specularColorMap: HAS_SPECULAR_COLORMAP, + specularIntensityMap: HAS_SPECULAR_INTENSITYMAP, + transmission: HAS_TRANSMISSION, + transmissionMap: HAS_TRANSMISSIONMAP, + thicknessMap: HAS_THICKNESSMAP, + gradientMap: HAS_GRADIENTMAP, + opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false, + alphaMap: HAS_ALPHAMAP, + alphaTest: HAS_ALPHATEST, + alphaHash: HAS_ALPHAHASH, + combine: material.combine, + mapUv: HAS_MAP && getChannel(material.map.channel), + aoMapUv: HAS_AOMAP && getChannel(material.aoMap.channel), + lightMapUv: HAS_LIGHTMAP && getChannel(material.lightMap.channel), + bumpMapUv: HAS_BUMPMAP && getChannel(material.bumpMap.channel), + normalMapUv: HAS_NORMALMAP && getChannel(material.normalMap.channel), + displacementMapUv: HAS_DISPLACEMENTMAP && getChannel(material.displacementMap.channel), + emissiveMapUv: HAS_EMISSIVEMAP && getChannel(material.emissiveMap.channel), + metalnessMapUv: HAS_METALNESSMAP && getChannel(material.metalnessMap.channel), + roughnessMapUv: HAS_ROUGHNESSMAP && getChannel(material.roughnessMap.channel), + anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel(material.anisotropyMap.channel), + clearcoatMapUv: HAS_CLEARCOATMAP && getChannel(material.clearcoatMap.channel), + clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel(material.clearcoatNormalMap.channel), + clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel(material.clearcoatRoughnessMap.channel), + iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel(material.iridescenceMap.channel), + iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel(material.iridescenceThicknessMap.channel), + sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel(material.sheenColorMap.channel), + sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel(material.sheenRoughnessMap.channel), + specularMapUv: HAS_SPECULARMAP && getChannel(material.specularMap.channel), + specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel(material.specularColorMap.channel), + specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel(material.specularIntensityMap.channel), + transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel(material.transmissionMap.channel), + thicknessMapUv: HAS_THICKNESSMAP && getChannel(material.thicknessMap.channel), + alphaMapUv: HAS_ALPHAMAP && getChannel(material.alphaMap.channel), + vertexTangents: !!geometry.attributes.tangent && (HAS_NORMALMAP || HAS_ANISOTROPY), + vertexColors: material.vertexColors, + vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4, + pointsUvs: object.isPoints === true && !!geometry.attributes.uv && (HAS_MAP || HAS_ALPHAMAP), + fog: !!fog, + useFog: material.fog === true, + fogExp2: !!fog && fog.isFogExp2, + flatShading: material.flatShading === true, + sizeAttenuation: material.sizeAttenuation === true, + logarithmicDepthBuffer, + reverseDepthBuffer, + skinning: object.isSkinnedMesh === true, + morphTargets: geometry.morphAttributes.position !== undefined, + morphNormals: geometry.morphAttributes.normal !== undefined, + morphColors: geometry.morphAttributes.color !== undefined, + morphTargetsCount, + morphTextureStride, + numDirLights: lights.directional.length, + numPointLights: lights.point.length, + numSpotLights: lights.spot.length, + numSpotLightMaps: lights.spotLightMap.length, + numRectAreaLights: lights.rectArea.length, + numHemiLights: lights.hemi.length, + numDirLightShadows: lights.directionalShadowMap.length, + numPointLightShadows: lights.pointShadowMap.length, + numSpotLightShadows: lights.spotShadowMap.length, + numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, + numLightProbes: lights.numLightProbes, + numClippingPlanes: clipping.numPlanes, + numClipIntersection: clipping.numIntersection, + dithering: material.dithering, + shadowMapEnabled: renderer2.shadowMap.enabled && shadows.length > 0, + shadowMapType: renderer2.shadowMap.type, + toneMapping, + decodeVideoTexture: HAS_MAP && material.map.isVideoTexture === true && ColorManagement.getTransfer(material.map.colorSpace) === SRGBTransfer, + decodeVideoTextureEmissive: HAS_EMISSIVEMAP && material.emissiveMap.isVideoTexture === true && ColorManagement.getTransfer(material.emissiveMap.colorSpace) === SRGBTransfer, + premultipliedAlpha: material.premultipliedAlpha, + doubleSided: material.side === DoubleSide, + flipSided: material.side === BackSide, + useDepthPacking: material.depthPacking >= 0, + depthPacking: material.depthPacking || 0, + index0AttributeName: material.index0AttributeName, + extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has("WEBGL_clip_cull_distance"), + extensionMultiDraw: (HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH) && extensions.has("WEBGL_multi_draw"), + rendererExtensionParallelShaderCompile: extensions.has("KHR_parallel_shader_compile"), + customProgramCacheKey: material.customProgramCacheKey() + }; + parameters.vertexUv1s = _activeChannels.has(1); + parameters.vertexUv2s = _activeChannels.has(2); + parameters.vertexUv3s = _activeChannels.has(3); + _activeChannels.clear(); + return parameters; + } + function getProgramCacheKey(parameters) { + const array = []; + if (parameters.shaderID) { + array.push(parameters.shaderID); + } else { + array.push(parameters.customVertexShaderID); + array.push(parameters.customFragmentShaderID); + } + if (parameters.defines !== undefined) { + for (const name2 in parameters.defines) { + array.push(name2); + array.push(parameters.defines[name2]); + } + } + if (parameters.isRawShaderMaterial === false) { + getProgramCacheKeyParameters(array, parameters); + getProgramCacheKeyBooleans(array, parameters); + array.push(renderer2.outputColorSpace); + } + array.push(parameters.customProgramCacheKey); + return array.join(); + } + function getProgramCacheKeyParameters(array, parameters) { + array.push(parameters.precision); + array.push(parameters.outputColorSpace); + array.push(parameters.envMapMode); + array.push(parameters.envMapCubeUVHeight); + array.push(parameters.mapUv); + array.push(parameters.alphaMapUv); + array.push(parameters.lightMapUv); + array.push(parameters.aoMapUv); + array.push(parameters.bumpMapUv); + array.push(parameters.normalMapUv); + array.push(parameters.displacementMapUv); + array.push(parameters.emissiveMapUv); + array.push(parameters.metalnessMapUv); + array.push(parameters.roughnessMapUv); + array.push(parameters.anisotropyMapUv); + array.push(parameters.clearcoatMapUv); + array.push(parameters.clearcoatNormalMapUv); + array.push(parameters.clearcoatRoughnessMapUv); + array.push(parameters.iridescenceMapUv); + array.push(parameters.iridescenceThicknessMapUv); + array.push(parameters.sheenColorMapUv); + array.push(parameters.sheenRoughnessMapUv); + array.push(parameters.specularMapUv); + array.push(parameters.specularColorMapUv); + array.push(parameters.specularIntensityMapUv); + array.push(parameters.transmissionMapUv); + array.push(parameters.thicknessMapUv); + array.push(parameters.combine); + array.push(parameters.fogExp2); + array.push(parameters.sizeAttenuation); + array.push(parameters.morphTargetsCount); + array.push(parameters.morphAttributeCount); + array.push(parameters.numDirLights); + array.push(parameters.numPointLights); + array.push(parameters.numSpotLights); + array.push(parameters.numSpotLightMaps); + array.push(parameters.numHemiLights); + array.push(parameters.numRectAreaLights); + array.push(parameters.numDirLightShadows); + array.push(parameters.numPointLightShadows); + array.push(parameters.numSpotLightShadows); + array.push(parameters.numSpotLightShadowsWithMaps); + array.push(parameters.numLightProbes); + array.push(parameters.shadowMapType); + array.push(parameters.toneMapping); + array.push(parameters.numClippingPlanes); + array.push(parameters.numClipIntersection); + array.push(parameters.depthPacking); + } + function getProgramCacheKeyBooleans(array, parameters) { + _programLayers.disableAll(); + if (parameters.supportsVertexTextures) + _programLayers.enable(0); + if (parameters.instancing) + _programLayers.enable(1); + if (parameters.instancingColor) + _programLayers.enable(2); + if (parameters.instancingMorph) + _programLayers.enable(3); + if (parameters.matcap) + _programLayers.enable(4); + if (parameters.envMap) + _programLayers.enable(5); + if (parameters.normalMapObjectSpace) + _programLayers.enable(6); + if (parameters.normalMapTangentSpace) + _programLayers.enable(7); + if (parameters.clearcoat) + _programLayers.enable(8); + if (parameters.iridescence) + _programLayers.enable(9); + if (parameters.alphaTest) + _programLayers.enable(10); + if (parameters.vertexColors) + _programLayers.enable(11); + if (parameters.vertexAlphas) + _programLayers.enable(12); + if (parameters.vertexUv1s) + _programLayers.enable(13); + if (parameters.vertexUv2s) + _programLayers.enable(14); + if (parameters.vertexUv3s) + _programLayers.enable(15); + if (parameters.vertexTangents) + _programLayers.enable(16); + if (parameters.anisotropy) + _programLayers.enable(17); + if (parameters.alphaHash) + _programLayers.enable(18); + if (parameters.batching) + _programLayers.enable(19); + if (parameters.dispersion) + _programLayers.enable(20); + if (parameters.batchingColor) + _programLayers.enable(21); + array.push(_programLayers.mask); + _programLayers.disableAll(); + if (parameters.fog) + _programLayers.enable(0); + if (parameters.useFog) + _programLayers.enable(1); + if (parameters.flatShading) + _programLayers.enable(2); + if (parameters.logarithmicDepthBuffer) + _programLayers.enable(3); + if (parameters.reverseDepthBuffer) + _programLayers.enable(4); + if (parameters.skinning) + _programLayers.enable(5); + if (parameters.morphTargets) + _programLayers.enable(6); + if (parameters.morphNormals) + _programLayers.enable(7); + if (parameters.morphColors) + _programLayers.enable(8); + if (parameters.premultipliedAlpha) + _programLayers.enable(9); + if (parameters.shadowMapEnabled) + _programLayers.enable(10); + if (parameters.doubleSided) + _programLayers.enable(11); + if (parameters.flipSided) + _programLayers.enable(12); + if (parameters.useDepthPacking) + _programLayers.enable(13); + if (parameters.dithering) + _programLayers.enable(14); + if (parameters.transmission) + _programLayers.enable(15); + if (parameters.sheen) + _programLayers.enable(16); + if (parameters.opaque) + _programLayers.enable(17); + if (parameters.pointsUvs) + _programLayers.enable(18); + if (parameters.decodeVideoTexture) + _programLayers.enable(19); + if (parameters.decodeVideoTextureEmissive) + _programLayers.enable(20); + if (parameters.alphaToCoverage) + _programLayers.enable(21); + array.push(_programLayers.mask); + } + function getUniforms(material) { + const shaderID = shaderIDs[material.type]; + let uniforms; + if (shaderID) { + const shader = ShaderLib[shaderID]; + uniforms = UniformsUtils.clone(shader.uniforms); + } else { + uniforms = material.uniforms; + } + return uniforms; + } + function acquireProgram(parameters, cacheKey) { + let program; + for (let p = 0, pl = programs.length;p < pl; p++) { + const preexistingProgram = programs[p]; + if (preexistingProgram.cacheKey === cacheKey) { + program = preexistingProgram; + ++program.usedTimes; + break; + } + } + if (program === undefined) { + program = new WebGLProgram(renderer2, cacheKey, parameters, bindingStates); + programs.push(program); + } + return program; + } + function releaseProgram(program) { + if (--program.usedTimes === 0) { + const i = programs.indexOf(program); + programs[i] = programs[programs.length - 1]; + programs.pop(); + program.destroy(); + } + } + function releaseShaderCache(material) { + _customShaders.remove(material); + } + function dispose() { + _customShaders.dispose(); + } + return { + getParameters, + getProgramCacheKey, + getUniforms, + acquireProgram, + releaseProgram, + releaseShaderCache, + programs, + dispose + }; +} +function WebGLProperties() { + let properties = new WeakMap; + function has2(object) { + return properties.has(object); + } + function get(object) { + let map2 = properties.get(object); + if (map2 === undefined) { + map2 = {}; + properties.set(object, map2); + } + return map2; + } + function remove(object) { + properties.delete(object); + } + function update(object, key2, value2) { + properties.get(object)[key2] = value2; + } + function dispose() { + properties = new WeakMap; + } + return { + has: has2, + get, + remove, + update, + dispose + }; +} +function painterSortStable(a, b) { + if (a.groupOrder !== b.groupOrder) { + return a.groupOrder - b.groupOrder; + } else if (a.renderOrder !== b.renderOrder) { + return a.renderOrder - b.renderOrder; + } else if (a.material.id !== b.material.id) { + return a.material.id - b.material.id; + } else if (a.z !== b.z) { + return a.z - b.z; + } else { + return a.id - b.id; + } +} +function reversePainterSortStable(a, b) { + if (a.groupOrder !== b.groupOrder) { + return a.groupOrder - b.groupOrder; + } else if (a.renderOrder !== b.renderOrder) { + return a.renderOrder - b.renderOrder; + } else if (a.z !== b.z) { + return b.z - a.z; + } else { + return a.id - b.id; + } +} +function WebGLRenderList() { + const renderItems = []; + let renderItemsIndex = 0; + const opaque = []; + const transmissive = []; + const transparent = []; + function init() { + renderItemsIndex = 0; + opaque.length = 0; + transmissive.length = 0; + transparent.length = 0; + } + function getNextRenderItem(object, geometry, material, groupOrder, z, group) { + let renderItem = renderItems[renderItemsIndex]; + if (renderItem === undefined) { + renderItem = { + id: object.id, + object, + geometry, + material, + groupOrder, + renderOrder: object.renderOrder, + z, + group + }; + renderItems[renderItemsIndex] = renderItem; + } else { + renderItem.id = object.id; + renderItem.object = object; + renderItem.geometry = geometry; + renderItem.material = material; + renderItem.groupOrder = groupOrder; + renderItem.renderOrder = object.renderOrder; + renderItem.z = z; + renderItem.group = group; + } + renderItemsIndex++; + return renderItem; + } + function push(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.push(renderItem); + } else if (material.transparent === true) { + transparent.push(renderItem); + } else { + opaque.push(renderItem); + } + } + function unshift(object, geometry, material, groupOrder, z, group) { + const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); + if (material.transmission > 0) { + transmissive.unshift(renderItem); + } else if (material.transparent === true) { + transparent.unshift(renderItem); + } else { + opaque.unshift(renderItem); + } + } + function sort(customOpaqueSort, customTransparentSort) { + if (opaque.length > 1) + opaque.sort(customOpaqueSort || painterSortStable); + if (transmissive.length > 1) + transmissive.sort(customTransparentSort || reversePainterSortStable); + if (transparent.length > 1) + transparent.sort(customTransparentSort || reversePainterSortStable); + } + function finish() { + for (let i = renderItemsIndex, il = renderItems.length;i < il; i++) { + const renderItem = renderItems[i]; + if (renderItem.id === null) + break; + renderItem.id = null; + renderItem.object = null; + renderItem.geometry = null; + renderItem.material = null; + renderItem.group = null; + } + } + return { + opaque, + transmissive, + transparent, + init, + push, + unshift, + finish, + sort + }; +} +function WebGLRenderLists() { + let lists = new WeakMap; + function get(scene, renderCallDepth) { + const listArray = lists.get(scene); + let list; + if (listArray === undefined) { + list = new WebGLRenderList; + lists.set(scene, [list]); + } else { + if (renderCallDepth >= listArray.length) { + list = new WebGLRenderList; + listArray.push(list); + } else { + list = listArray[renderCallDepth]; + } + } + return list; + } + function dispose() { + lists = new WeakMap; + } + return { + get, + dispose + }; +} +function UniformsCache() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== undefined) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + direction: new Vector3, + color: new Color + }; + break; + case "SpotLight": + uniforms = { + position: new Vector3, + direction: new Vector3, + color: new Color, + distance: 0, + coneCos: 0, + penumbraCos: 0, + decay: 0 + }; + break; + case "PointLight": + uniforms = { + position: new Vector3, + color: new Color, + distance: 0, + decay: 0 + }; + break; + case "HemisphereLight": + uniforms = { + direction: new Vector3, + skyColor: new Color, + groundColor: new Color + }; + break; + case "RectAreaLight": + uniforms = { + color: new Color, + position: new Vector3, + halfWidth: new Vector3, + halfHeight: new Vector3 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; +} +function ShadowUniformsCache() { + const lights = {}; + return { + get: function(light) { + if (lights[light.id] !== undefined) { + return lights[light.id]; + } + let uniforms; + switch (light.type) { + case "DirectionalLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2 + }; + break; + case "SpotLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2 + }; + break; + case "PointLight": + uniforms = { + shadowIntensity: 1, + shadowBias: 0, + shadowNormalBias: 0, + shadowRadius: 1, + shadowMapSize: new Vector2, + shadowCameraNear: 1, + shadowCameraFar: 1000 + }; + break; + } + lights[light.id] = uniforms; + return uniforms; + } + }; +} +var nextVersion = 0; +function shadowCastingAndTexturingLightsFirst(lightA, lightB) { + return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0); +} +function WebGLLights(extensions) { + const cache = new UniformsCache; + const shadowCache = ShadowUniformsCache(); + const state = { + version: 0, + hash: { + directionalLength: -1, + pointLength: -1, + spotLength: -1, + rectAreaLength: -1, + hemiLength: -1, + numDirectionalShadows: -1, + numPointShadows: -1, + numSpotShadows: -1, + numSpotMaps: -1, + numLightProbes: -1 + }, + ambient: [0, 0, 0], + probe: [], + directional: [], + directionalShadow: [], + directionalShadowMap: [], + directionalShadowMatrix: [], + spot: [], + spotLightMap: [], + spotShadow: [], + spotShadowMap: [], + spotLightMatrix: [], + rectArea: [], + rectAreaLTC1: null, + rectAreaLTC2: null, + point: [], + pointShadow: [], + pointShadowMap: [], + pointShadowMatrix: [], + hemi: [], + numSpotLightShadowsWithMaps: 0, + numLightProbes: 0 + }; + for (let i = 0;i < 9; i++) + state.probe.push(new Vector3); + const vector3 = new Vector3; + const matrix4 = new Matrix4; + const matrix42 = new Matrix4; + function setup(lights) { + let r = 0, g = 0, b = 0; + for (let i = 0;i < 9; i++) + state.probe[i].set(0, 0, 0); + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + let numDirectionalShadows = 0; + let numPointShadows = 0; + let numSpotShadows = 0; + let numSpotMaps = 0; + let numSpotShadowsWithMaps = 0; + let numLightProbes = 0; + lights.sort(shadowCastingAndTexturingLightsFirst); + for (let i = 0, l = lights.length;i < l; i++) { + const light = lights[i]; + const color = light.color; + const intensity = light.intensity; + const distance = light.distance; + const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null; + if (light.isAmbientLight) { + r += color.r * intensity; + g += color.g * intensity; + b += color.b * intensity; + } else if (light.isLightProbe) { + for (let j = 0;j < 9; j++) { + state.probe[j].addScaledVector(light.sh.coefficients[j], intensity); + } + numLightProbes++; + } else if (light.isDirectionalLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.directionalShadow[directionalLength] = shadowUniforms; + state.directionalShadowMap[directionalLength] = shadowMap; + state.directionalShadowMatrix[directionalLength] = light.shadow.matrix; + numDirectionalShadows++; + } + state.directional[directionalLength] = uniforms; + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = cache.get(light); + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.distance = distance; + uniforms.coneCos = Math.cos(light.angle); + uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra)); + uniforms.decay = light.decay; + state.spot[spotLength] = uniforms; + const shadow = light.shadow; + if (light.map) { + state.spotLightMap[numSpotMaps] = light.map; + numSpotMaps++; + shadow.updateMatrices(light); + if (light.castShadow) + numSpotShadowsWithMaps++; + } + state.spotLightMatrix[spotLength] = shadow.matrix; + if (light.castShadow) { + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + state.spotShadow[spotLength] = shadowUniforms; + state.spotShadowMap[spotLength] = shadowMap; + numSpotShadows++; + } + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = cache.get(light); + uniforms.color.copy(color).multiplyScalar(intensity); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + state.rectArea[rectAreaLength] = uniforms; + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = cache.get(light); + uniforms.color.copy(light.color).multiplyScalar(light.intensity); + uniforms.distance = light.distance; + uniforms.decay = light.decay; + if (light.castShadow) { + const shadow = light.shadow; + const shadowUniforms = shadowCache.get(light); + shadowUniforms.shadowIntensity = shadow.intensity; + shadowUniforms.shadowBias = shadow.bias; + shadowUniforms.shadowNormalBias = shadow.normalBias; + shadowUniforms.shadowRadius = shadow.radius; + shadowUniforms.shadowMapSize = shadow.mapSize; + shadowUniforms.shadowCameraNear = shadow.camera.near; + shadowUniforms.shadowCameraFar = shadow.camera.far; + state.pointShadow[pointLength] = shadowUniforms; + state.pointShadowMap[pointLength] = shadowMap; + state.pointShadowMatrix[pointLength] = light.shadow.matrix; + numPointShadows++; + } + state.point[pointLength] = uniforms; + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = cache.get(light); + uniforms.skyColor.copy(light.color).multiplyScalar(intensity); + uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity); + state.hemi[hemiLength] = uniforms; + hemiLength++; + } + } + if (rectAreaLength > 0) { + if (extensions.has("OES_texture_float_linear") === true) { + state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; + state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; + } else { + state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; + state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; + } + } + state.ambient[0] = r; + state.ambient[1] = g; + state.ambient[2] = b; + const hash = state.hash; + if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps || hash.numLightProbes !== numLightProbes) { + state.directional.length = directionalLength; + state.spot.length = spotLength; + state.rectArea.length = rectAreaLength; + state.point.length = pointLength; + state.hemi.length = hemiLength; + state.directionalShadow.length = numDirectionalShadows; + state.directionalShadowMap.length = numDirectionalShadows; + state.pointShadow.length = numPointShadows; + state.pointShadowMap.length = numPointShadows; + state.spotShadow.length = numSpotShadows; + state.spotShadowMap.length = numSpotShadows; + state.directionalShadowMatrix.length = numDirectionalShadows; + state.pointShadowMatrix.length = numPointShadows; + state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; + state.spotLightMap.length = numSpotMaps; + state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; + state.numLightProbes = numLightProbes; + hash.directionalLength = directionalLength; + hash.pointLength = pointLength; + hash.spotLength = spotLength; + hash.rectAreaLength = rectAreaLength; + hash.hemiLength = hemiLength; + hash.numDirectionalShadows = numDirectionalShadows; + hash.numPointShadows = numPointShadows; + hash.numSpotShadows = numSpotShadows; + hash.numSpotMaps = numSpotMaps; + hash.numLightProbes = numLightProbes; + state.version = nextVersion++; + } + } + function setupView(lights, camera) { + let directionalLength = 0; + let pointLength = 0; + let spotLength = 0; + let rectAreaLength = 0; + let hemiLength = 0; + const viewMatrix = camera.matrixWorldInverse; + for (let i = 0, l = lights.length;i < l; i++) { + const light = lights[i]; + if (light.isDirectionalLight) { + const uniforms = state.directional[directionalLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + directionalLength++; + } else if (light.isSpotLight) { + const uniforms = state.spot[spotLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + vector3.setFromMatrixPosition(light.target.matrixWorld); + uniforms.direction.sub(vector3); + uniforms.direction.transformDirection(viewMatrix); + spotLength++; + } else if (light.isRectAreaLight) { + const uniforms = state.rectArea[rectAreaLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + matrix42.identity(); + matrix4.copy(light.matrixWorld); + matrix4.premultiply(viewMatrix); + matrix42.extractRotation(matrix4); + uniforms.halfWidth.set(light.width * 0.5, 0, 0); + uniforms.halfHeight.set(0, light.height * 0.5, 0); + uniforms.halfWidth.applyMatrix4(matrix42); + uniforms.halfHeight.applyMatrix4(matrix42); + rectAreaLength++; + } else if (light.isPointLight) { + const uniforms = state.point[pointLength]; + uniforms.position.setFromMatrixPosition(light.matrixWorld); + uniforms.position.applyMatrix4(viewMatrix); + pointLength++; + } else if (light.isHemisphereLight) { + const uniforms = state.hemi[hemiLength]; + uniforms.direction.setFromMatrixPosition(light.matrixWorld); + uniforms.direction.transformDirection(viewMatrix); + hemiLength++; + } + } + } + return { + setup, + setupView, + state + }; +} +function WebGLRenderState(extensions) { + const lights = new WebGLLights(extensions); + const lightsArray = []; + const shadowsArray = []; + function init(camera) { + state.camera = camera; + lightsArray.length = 0; + shadowsArray.length = 0; + } + function pushLight(light) { + lightsArray.push(light); + } + function pushShadow(shadowLight) { + shadowsArray.push(shadowLight); + } + function setupLights() { + lights.setup(lightsArray); + } + function setupLightsView(camera) { + lights.setupView(lightsArray, camera); + } + const state = { + lightsArray, + shadowsArray, + camera: null, + lights, + transmissionRenderTarget: {} + }; + return { + init, + state, + setupLights, + setupLightsView, + pushLight, + pushShadow + }; +} +function WebGLRenderStates(extensions) { + let renderStates = new WeakMap; + function get(scene, renderCallDepth = 0) { + const renderStateArray = renderStates.get(scene); + let renderState; + if (renderStateArray === undefined) { + renderState = new WebGLRenderState(extensions); + renderStates.set(scene, [renderState]); + } else { + if (renderCallDepth >= renderStateArray.length) { + renderState = new WebGLRenderState(extensions); + renderStateArray.push(renderState); + } else { + renderState = renderStateArray[renderCallDepth]; + } + } + return renderState; + } + function dispose() { + renderStates = new WeakMap; + } + return { + get, + dispose + }; +} +var vertex = `void main() { + gl_Position = vec4( position, 1.0 ); +}`; +var fragment = `uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +#include +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) ); + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) ); + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( squared_mean - mean * mean ); + gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) ); +}`; +function WebGLShadowMap(renderer2, objects, capabilities) { + let _frustum2 = new Frustum; + const _shadowMapSize = new Vector2, _viewportSize = new Vector2, _viewport = new Vector4, _depthMaterial = new MeshDepthMaterial({ depthPacking: RGBADepthPacking }), _distanceMaterial = new MeshDistanceMaterial, _materialCache = {}, _maxTextureSize = capabilities.maxTextureSize; + const shadowSide = { [FrontSide]: BackSide, [BackSide]: FrontSide, [DoubleSide]: DoubleSide }; + const shadowMaterialVertical = new ShaderMaterial({ + defines: { + VSM_SAMPLES: 8 + }, + uniforms: { + shadow_pass: { value: null }, + resolution: { value: new Vector2 }, + radius: { value: 4 } + }, + vertexShader: vertex, + fragmentShader: fragment + }); + const shadowMaterialHorizontal = shadowMaterialVertical.clone(); + shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; + const fullScreenTri = new BufferGeometry; + fullScreenTri.setAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3)); + const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); + const scope = this; + this.enabled = false; + this.autoUpdate = true; + this.needsUpdate = false; + this.type = PCFShadowMap; + let _previousType = this.type; + this.render = function(lights, scene, camera) { + if (scope.enabled === false) + return; + if (scope.autoUpdate === false && scope.needsUpdate === false) + return; + if (lights.length === 0) + return; + const currentRenderTarget = renderer2.getRenderTarget(); + const activeCubeFace = renderer2.getActiveCubeFace(); + const activeMipmapLevel = renderer2.getActiveMipmapLevel(); + const _state = renderer2.state; + _state.setBlending(NoBlending); + _state.buffers.color.setClear(1, 1, 1, 1); + _state.buffers.depth.setTest(true); + _state.setScissorTest(false); + const toVSM = _previousType !== VSMShadowMap && this.type === VSMShadowMap; + const fromVSM = _previousType === VSMShadowMap && this.type !== VSMShadowMap; + for (let i = 0, il = lights.length;i < il; i++) { + const light = lights[i]; + const shadow = light.shadow; + if (shadow === undefined) { + console.warn("THREE.WebGLShadowMap:", light, "has no shadow."); + continue; + } + if (shadow.autoUpdate === false && shadow.needsUpdate === false) + continue; + _shadowMapSize.copy(shadow.mapSize); + const shadowFrameExtents = shadow.getFrameExtents(); + _shadowMapSize.multiply(shadowFrameExtents); + _viewportSize.copy(shadow.mapSize); + if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) { + if (_shadowMapSize.x > _maxTextureSize) { + _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x); + _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; + shadow.mapSize.x = _viewportSize.x; + } + if (_shadowMapSize.y > _maxTextureSize) { + _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y); + _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; + shadow.mapSize.y = _viewportSize.y; + } + } + if (shadow.map === null || toVSM === true || fromVSM === true) { + const pars = this.type !== VSMShadowMap ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; + if (shadow.map !== null) { + shadow.map.dispose(); + } + shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars); + shadow.map.texture.name = light.name + ".shadowMap"; + shadow.camera.updateProjectionMatrix(); + } + renderer2.setRenderTarget(shadow.map); + renderer2.clear(); + const viewportCount = shadow.getViewportCount(); + for (let vp = 0;vp < viewportCount; vp++) { + const viewport = shadow.getViewport(vp); + _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w); + _state.viewport(_viewport); + shadow.updateMatrices(light, vp); + _frustum2 = shadow.getFrustum(); + renderObject(scene, camera, shadow.camera, light, this.type); + } + if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) { + VSMPass(shadow, camera); + } + shadow.needsUpdate = false; + } + _previousType = this.type; + scope.needsUpdate = false; + renderer2.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel); + }; + function VSMPass(shadow, camera) { + const geometry = objects.update(fullScreenMesh); + if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) { + shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; + shadowMaterialVertical.needsUpdate = true; + shadowMaterialHorizontal.needsUpdate = true; + } + if (shadow.mapPass === null) { + shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y); + } + shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; + shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; + shadowMaterialVertical.uniforms.radius.value = shadow.radius; + renderer2.setRenderTarget(shadow.mapPass); + renderer2.clear(); + renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); + shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; + shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; + shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; + renderer2.setRenderTarget(shadow.map); + renderer2.clear(); + renderer2.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null); + } + function getDepthMaterial(object, material, light, type) { + let result = null; + const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial; + if (customMaterial !== undefined) { + result = customMaterial; + } else { + result = light.isPointLight === true ? _distanceMaterial : _depthMaterial; + if (renderer2.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0 || material.map && material.alphaTest > 0) { + const keyA = result.uuid, keyB = material.uuid; + let materialsForVariant = _materialCache[keyA]; + if (materialsForVariant === undefined) { + materialsForVariant = {}; + _materialCache[keyA] = materialsForVariant; + } + let cachedMaterial = materialsForVariant[keyB]; + if (cachedMaterial === undefined) { + cachedMaterial = result.clone(); + materialsForVariant[keyB] = cachedMaterial; + material.addEventListener("dispose", onMaterialDispose); + } + result = cachedMaterial; + } + } + result.visible = material.visible; + result.wireframe = material.wireframe; + if (type === VSMShadowMap) { + result.side = material.shadowSide !== null ? material.shadowSide : material.side; + } else { + result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side]; + } + result.alphaMap = material.alphaMap; + result.alphaTest = material.alphaTest; + result.map = material.map; + result.clipShadows = material.clipShadows; + result.clippingPlanes = material.clippingPlanes; + result.clipIntersection = material.clipIntersection; + result.displacementMap = material.displacementMap; + result.displacementScale = material.displacementScale; + result.displacementBias = material.displacementBias; + result.wireframeLinewidth = material.wireframeLinewidth; + result.linewidth = material.linewidth; + if (light.isPointLight === true && result.isMeshDistanceMaterial === true) { + const materialProperties = renderer2.properties.get(result); + materialProperties.light = light; + } + return result; + } + function renderObject(object, camera, shadowCamera, light, type) { + if (object.visible === false) + return; + const visible = object.layers.test(camera.layers); + if (visible && (object.isMesh || object.isLine || object.isPoints)) { + if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum2.intersectsObject(object))) { + object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld); + const geometry = objects.update(object); + const material = object.material; + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let k = 0, kl = groups.length;k < kl; k++) { + const group = groups[k]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + const depthMaterial = getDepthMaterial(object, groupMaterial, light, type); + object.onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group); + object.onAfterShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, group); + } + } + } else if (material.visible) { + const depthMaterial = getDepthMaterial(object, material, light, type); + object.onBeforeShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + renderer2.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null); + object.onAfterShadow(renderer2, object, camera, shadowCamera, geometry, depthMaterial, null); + } + } + } + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + renderObject(children[i], camera, shadowCamera, light, type); + } + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + for (const id in _materialCache) { + const cache = _materialCache[id]; + const uuid = event.target.uuid; + if (uuid in cache) { + const shadowMaterial = cache[uuid]; + shadowMaterial.dispose(); + delete cache[uuid]; + } + } + } +} +var reversedFuncs = { + [NeverDepth]: AlwaysDepth, + [LessDepth]: GreaterDepth, + [EqualDepth]: NotEqualDepth, + [LessEqualDepth]: GreaterEqualDepth, + [AlwaysDepth]: NeverDepth, + [GreaterDepth]: LessDepth, + [NotEqualDepth]: EqualDepth, + [GreaterEqualDepth]: LessEqualDepth +}; +function WebGLState(gl, extensions) { + function ColorBuffer() { + let locked = false; + const color = new Vector4; + let currentColorMask = null; + const currentColorClear = new Vector4(0, 0, 0, 0); + return { + setMask: function(colorMask) { + if (currentColorMask !== colorMask && !locked) { + gl.colorMask(colorMask, colorMask, colorMask, colorMask); + currentColorMask = colorMask; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(r, g, b, a, premultipliedAlpha) { + if (premultipliedAlpha === true) { + r *= a; + g *= a; + b *= a; + } + color.set(r, g, b, a); + if (currentColorClear.equals(color) === false) { + gl.clearColor(r, g, b, a); + currentColorClear.copy(color); + } + }, + reset: function() { + locked = false; + currentColorMask = null; + currentColorClear.set(-1, 0, 0, 0); + } + }; + } + function DepthBuffer() { + let locked = false; + let reversed = false; + let currentDepthMask = null; + let currentDepthFunc = null; + let currentDepthClear = null; + return { + setReversed: function(value2) { + if (reversed !== value2) { + const ext = extensions.get("EXT_clip_control"); + if (reversed) { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT); + } else { + ext.clipControlEXT(ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT); + } + const oldDepth = currentDepthClear; + currentDepthClear = null; + this.setClear(oldDepth); + } + reversed = value2; + }, + getReversed: function() { + return reversed; + }, + setTest: function(depthTest) { + if (depthTest) { + enable(gl.DEPTH_TEST); + } else { + disable(gl.DEPTH_TEST); + } + }, + setMask: function(depthMask) { + if (currentDepthMask !== depthMask && !locked) { + gl.depthMask(depthMask); + currentDepthMask = depthMask; + } + }, + setFunc: function(depthFunc) { + if (reversed) + depthFunc = reversedFuncs[depthFunc]; + if (currentDepthFunc !== depthFunc) { + switch (depthFunc) { + case NeverDepth: + gl.depthFunc(gl.NEVER); + break; + case AlwaysDepth: + gl.depthFunc(gl.ALWAYS); + break; + case LessDepth: + gl.depthFunc(gl.LESS); + break; + case LessEqualDepth: + gl.depthFunc(gl.LEQUAL); + break; + case EqualDepth: + gl.depthFunc(gl.EQUAL); + break; + case GreaterEqualDepth: + gl.depthFunc(gl.GEQUAL); + break; + case GreaterDepth: + gl.depthFunc(gl.GREATER); + break; + case NotEqualDepth: + gl.depthFunc(gl.NOTEQUAL); + break; + default: + gl.depthFunc(gl.LEQUAL); + } + currentDepthFunc = depthFunc; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(depth) { + if (currentDepthClear !== depth) { + if (reversed) { + depth = 1 - depth; + } + gl.clearDepth(depth); + currentDepthClear = depth; + } + }, + reset: function() { + locked = false; + currentDepthMask = null; + currentDepthFunc = null; + currentDepthClear = null; + reversed = false; + } + }; + } + function StencilBuffer() { + let locked = false; + let currentStencilMask = null; + let currentStencilFunc = null; + let currentStencilRef = null; + let currentStencilFuncMask = null; + let currentStencilFail = null; + let currentStencilZFail = null; + let currentStencilZPass = null; + let currentStencilClear = null; + return { + setTest: function(stencilTest) { + if (!locked) { + if (stencilTest) { + enable(gl.STENCIL_TEST); + } else { + disable(gl.STENCIL_TEST); + } + } + }, + setMask: function(stencilMask) { + if (currentStencilMask !== stencilMask && !locked) { + gl.stencilMask(stencilMask); + currentStencilMask = stencilMask; + } + }, + setFunc: function(stencilFunc, stencilRef, stencilMask) { + if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) { + gl.stencilFunc(stencilFunc, stencilRef, stencilMask); + currentStencilFunc = stencilFunc; + currentStencilRef = stencilRef; + currentStencilFuncMask = stencilMask; + } + }, + setOp: function(stencilFail, stencilZFail, stencilZPass) { + if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) { + gl.stencilOp(stencilFail, stencilZFail, stencilZPass); + currentStencilFail = stencilFail; + currentStencilZFail = stencilZFail; + currentStencilZPass = stencilZPass; + } + }, + setLocked: function(lock) { + locked = lock; + }, + setClear: function(stencil) { + if (currentStencilClear !== stencil) { + gl.clearStencil(stencil); + currentStencilClear = stencil; + } + }, + reset: function() { + locked = false; + currentStencilMask = null; + currentStencilFunc = null; + currentStencilRef = null; + currentStencilFuncMask = null; + currentStencilFail = null; + currentStencilZFail = null; + currentStencilZPass = null; + currentStencilClear = null; + } + }; + } + const colorBuffer = new ColorBuffer; + const depthBuffer = new DepthBuffer; + const stencilBuffer = new StencilBuffer; + const uboBindings = new WeakMap; + const uboProgramMap = new WeakMap; + let enabledCapabilities = {}; + let currentBoundFramebuffers = {}; + let currentDrawbuffers = new WeakMap; + let defaultDrawbuffers = []; + let currentProgram = null; + let currentBlendingEnabled = false; + let currentBlending = null; + let currentBlendEquation = null; + let currentBlendSrc = null; + let currentBlendDst = null; + let currentBlendEquationAlpha = null; + let currentBlendSrcAlpha = null; + let currentBlendDstAlpha = null; + let currentBlendColor = new Color(0, 0, 0); + let currentBlendAlpha = 0; + let currentPremultipledAlpha = false; + let currentFlipSided = null; + let currentCullFace = null; + let currentLineWidth = null; + let currentPolygonOffsetFactor = null; + let currentPolygonOffsetUnits = null; + const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); + let lineWidthAvailable = false; + let version = 0; + const glVersion = gl.getParameter(gl.VERSION); + if (glVersion.indexOf("WebGL") !== -1) { + version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 1; + } else if (glVersion.indexOf("OpenGL ES") !== -1) { + version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]); + lineWidthAvailable = version >= 2; + } + let currentTextureSlot = null; + let currentBoundTextures = {}; + const scissorParam = gl.getParameter(gl.SCISSOR_BOX); + const viewportParam = gl.getParameter(gl.VIEWPORT); + const currentScissor = new Vector4().fromArray(scissorParam); + const currentViewport = new Vector4().fromArray(viewportParam); + function createTexture(type, target, count, dimensions) { + const data2 = new Uint8Array(4); + const texture = gl.createTexture(); + gl.bindTexture(type, texture); + gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + for (let i = 0;i < count; i++) { + if (type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY) { + gl.texImage3D(target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data2); + } else { + gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data2); + } + } + return texture; + } + const emptyTextures = {}; + emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1); + emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); + emptyTextures[gl.TEXTURE_2D_ARRAY] = createTexture(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1); + emptyTextures[gl.TEXTURE_3D] = createTexture(gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1); + colorBuffer.setClear(0, 0, 0, 1); + depthBuffer.setClear(1); + stencilBuffer.setClear(0); + enable(gl.DEPTH_TEST); + depthBuffer.setFunc(LessEqualDepth); + setFlipSided(false); + setCullFace(CullFaceBack); + enable(gl.CULL_FACE); + setBlending(NoBlending); + function enable(id) { + if (enabledCapabilities[id] !== true) { + gl.enable(id); + enabledCapabilities[id] = true; + } + } + function disable(id) { + if (enabledCapabilities[id] !== false) { + gl.disable(id); + enabledCapabilities[id] = false; + } + } + function bindFramebuffer(target, framebuffer) { + if (currentBoundFramebuffers[target] !== framebuffer) { + gl.bindFramebuffer(target, framebuffer); + currentBoundFramebuffers[target] = framebuffer; + if (target === gl.DRAW_FRAMEBUFFER) { + currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer; + } + if (target === gl.FRAMEBUFFER) { + currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer; + } + return true; + } + return false; + } + function drawBuffers(renderTarget, framebuffer) { + let drawBuffers2 = defaultDrawbuffers; + let needsUpdate = false; + if (renderTarget) { + drawBuffers2 = currentDrawbuffers.get(framebuffer); + if (drawBuffers2 === undefined) { + drawBuffers2 = []; + currentDrawbuffers.set(framebuffer, drawBuffers2); + } + const textures = renderTarget.textures; + if (drawBuffers2.length !== textures.length || drawBuffers2[0] !== gl.COLOR_ATTACHMENT0) { + for (let i = 0, il = textures.length;i < il; i++) { + drawBuffers2[i] = gl.COLOR_ATTACHMENT0 + i; + } + drawBuffers2.length = textures.length; + needsUpdate = true; + } + } else { + if (drawBuffers2[0] !== gl.BACK) { + drawBuffers2[0] = gl.BACK; + needsUpdate = true; + } + } + if (needsUpdate) { + gl.drawBuffers(drawBuffers2); + } + } + function useProgram(program) { + if (currentProgram !== program) { + gl.useProgram(program); + currentProgram = program; + return true; + } + return false; + } + const equationToGL = { + [AddEquation]: gl.FUNC_ADD, + [SubtractEquation]: gl.FUNC_SUBTRACT, + [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT + }; + equationToGL[MinEquation] = gl.MIN; + equationToGL[MaxEquation] = gl.MAX; + const factorToGL = { + [ZeroFactor]: gl.ZERO, + [OneFactor]: gl.ONE, + [SrcColorFactor]: gl.SRC_COLOR, + [SrcAlphaFactor]: gl.SRC_ALPHA, + [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE, + [DstColorFactor]: gl.DST_COLOR, + [DstAlphaFactor]: gl.DST_ALPHA, + [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR, + [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA, + [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR, + [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA, + [ConstantColorFactor]: gl.CONSTANT_COLOR, + [OneMinusConstantColorFactor]: gl.ONE_MINUS_CONSTANT_COLOR, + [ConstantAlphaFactor]: gl.CONSTANT_ALPHA, + [OneMinusConstantAlphaFactor]: gl.ONE_MINUS_CONSTANT_ALPHA + }; + function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha) { + if (blending === NoBlending) { + if (currentBlendingEnabled === true) { + disable(gl.BLEND); + currentBlendingEnabled = false; + } + return; + } + if (currentBlendingEnabled === false) { + enable(gl.BLEND); + currentBlendingEnabled = true; + } + if (blending !== CustomBlending) { + if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) { + if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) { + gl.blendEquation(gl.FUNC_ADD); + currentBlendEquation = AddEquation; + currentBlendEquationAlpha = AddEquation; + } + if (premultipliedAlpha) { + switch (blending) { + case NormalBlending: + gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending: + gl.blendFunc(gl.ONE, gl.ONE); + break; + case SubtractiveBlending: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending: + gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } else { + switch (blending) { + case NormalBlending: + gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + break; + case AdditiveBlending: + gl.blendFunc(gl.SRC_ALPHA, gl.ONE); + break; + case SubtractiveBlending: + gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE); + break; + case MultiplyBlending: + gl.blendFunc(gl.ZERO, gl.SRC_COLOR); + break; + default: + console.error("THREE.WebGLState: Invalid blending: ", blending); + break; + } + } + currentBlendSrc = null; + currentBlendDst = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor.set(0, 0, 0); + currentBlendAlpha = 0; + currentBlending = blending; + currentPremultipledAlpha = premultipliedAlpha; + } + return; + } + blendEquationAlpha = blendEquationAlpha || blendEquation; + blendSrcAlpha = blendSrcAlpha || blendSrc; + blendDstAlpha = blendDstAlpha || blendDst; + if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) { + gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]); + currentBlendEquation = blendEquation; + currentBlendEquationAlpha = blendEquationAlpha; + } + if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) { + gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]); + currentBlendSrc = blendSrc; + currentBlendDst = blendDst; + currentBlendSrcAlpha = blendSrcAlpha; + currentBlendDstAlpha = blendDstAlpha; + } + if (blendColor.equals(currentBlendColor) === false || blendAlpha !== currentBlendAlpha) { + gl.blendColor(blendColor.r, blendColor.g, blendColor.b, blendAlpha); + currentBlendColor.copy(blendColor); + currentBlendAlpha = blendAlpha; + } + currentBlending = blending; + currentPremultipledAlpha = false; + } + function setMaterial(material, frontFaceCW) { + material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE); + let flipSided = material.side === BackSide; + if (frontFaceCW) + flipSided = !flipSided; + setFlipSided(flipSided); + material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha); + depthBuffer.setFunc(material.depthFunc); + depthBuffer.setTest(material.depthTest); + depthBuffer.setMask(material.depthWrite); + colorBuffer.setMask(material.colorWrite); + const stencilWrite = material.stencilWrite; + stencilBuffer.setTest(stencilWrite); + if (stencilWrite) { + stencilBuffer.setMask(material.stencilWriteMask); + stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask); + stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass); + } + setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits); + material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + } + function setFlipSided(flipSided) { + if (currentFlipSided !== flipSided) { + if (flipSided) { + gl.frontFace(gl.CW); + } else { + gl.frontFace(gl.CCW); + } + currentFlipSided = flipSided; + } + } + function setCullFace(cullFace) { + if (cullFace !== CullFaceNone) { + enable(gl.CULL_FACE); + if (cullFace !== currentCullFace) { + if (cullFace === CullFaceBack) { + gl.cullFace(gl.BACK); + } else if (cullFace === CullFaceFront) { + gl.cullFace(gl.FRONT); + } else { + gl.cullFace(gl.FRONT_AND_BACK); + } + } + } else { + disable(gl.CULL_FACE); + } + currentCullFace = cullFace; + } + function setLineWidth(width2) { + if (width2 !== currentLineWidth) { + if (lineWidthAvailable) + gl.lineWidth(width2); + currentLineWidth = width2; + } + } + function setPolygonOffset(polygonOffset, factor, units) { + if (polygonOffset) { + enable(gl.POLYGON_OFFSET_FILL); + if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) { + gl.polygonOffset(factor, units); + currentPolygonOffsetFactor = factor; + currentPolygonOffsetUnits = units; + } + } else { + disable(gl.POLYGON_OFFSET_FILL); + } + } + function setScissorTest(scissorTest) { + if (scissorTest) { + enable(gl.SCISSOR_TEST); + } else { + disable(gl.SCISSOR_TEST); + } + } + function activeTexture(webglSlot) { + if (webglSlot === undefined) + webglSlot = gl.TEXTURE0 + maxTextures - 1; + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + } + function bindTexture(webglType, webglTexture, webglSlot) { + if (webglSlot === undefined) { + if (currentTextureSlot === null) { + webglSlot = gl.TEXTURE0 + maxTextures - 1; + } else { + webglSlot = currentTextureSlot; + } + } + let boundTexture = currentBoundTextures[webglSlot]; + if (boundTexture === undefined) { + boundTexture = { type: undefined, texture: undefined }; + currentBoundTextures[webglSlot] = boundTexture; + } + if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) { + if (currentTextureSlot !== webglSlot) { + gl.activeTexture(webglSlot); + currentTextureSlot = webglSlot; + } + gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]); + boundTexture.type = webglType; + boundTexture.texture = webglTexture; + } + } + function unbindTexture() { + const boundTexture = currentBoundTextures[currentTextureSlot]; + if (boundTexture !== undefined && boundTexture.type !== undefined) { + gl.bindTexture(boundTexture.type, null); + boundTexture.type = undefined; + boundTexture.texture = undefined; + } + } + function compressedTexImage2D() { + try { + gl.compressedTexImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexImage3D() { + try { + gl.compressedTexImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage2D() { + try { + gl.texSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texSubImage3D() { + try { + gl.texSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage2D() { + try { + gl.compressedTexSubImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function compressedTexSubImage3D() { + try { + gl.compressedTexSubImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage2D() { + try { + gl.texStorage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texStorage3D() { + try { + gl.texStorage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage2D() { + try { + gl.texImage2D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function texImage3D() { + try { + gl.texImage3D.apply(gl, arguments); + } catch (error) { + console.error("THREE.WebGLState:", error); + } + } + function scissor(scissor2) { + if (currentScissor.equals(scissor2) === false) { + gl.scissor(scissor2.x, scissor2.y, scissor2.z, scissor2.w); + currentScissor.copy(scissor2); + } + } + function viewport(viewport2) { + if (currentViewport.equals(viewport2) === false) { + gl.viewport(viewport2.x, viewport2.y, viewport2.z, viewport2.w); + currentViewport.copy(viewport2); + } + } + function updateUBOMapping(uniformsGroup, program) { + let mapping = uboProgramMap.get(program); + if (mapping === undefined) { + mapping = new WeakMap; + uboProgramMap.set(program, mapping); + } + let blockIndex = mapping.get(uniformsGroup); + if (blockIndex === undefined) { + blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name); + mapping.set(uniformsGroup, blockIndex); + } + } + function uniformBlockBinding(uniformsGroup, program) { + const mapping = uboProgramMap.get(program); + const blockIndex = mapping.get(uniformsGroup); + if (uboBindings.get(program) !== blockIndex) { + gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex); + uboBindings.set(program, blockIndex); + } + } + function reset() { + gl.disable(gl.BLEND); + gl.disable(gl.CULL_FACE); + gl.disable(gl.DEPTH_TEST); + gl.disable(gl.POLYGON_OFFSET_FILL); + gl.disable(gl.SCISSOR_TEST); + gl.disable(gl.STENCIL_TEST); + gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE); + gl.blendEquation(gl.FUNC_ADD); + gl.blendFunc(gl.ONE, gl.ZERO); + gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO); + gl.blendColor(0, 0, 0, 0); + gl.colorMask(true, true, true, true); + gl.clearColor(0, 0, 0, 0); + gl.depthMask(true); + gl.depthFunc(gl.LESS); + depthBuffer.setReversed(false); + gl.clearDepth(1); + gl.stencilMask(4294967295); + gl.stencilFunc(gl.ALWAYS, 0, 4294967295); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + gl.clearStencil(0); + gl.cullFace(gl.BACK); + gl.frontFace(gl.CCW); + gl.polygonOffset(0, 0); + gl.activeTexture(gl.TEXTURE0); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null); + gl.useProgram(null); + gl.lineWidth(1); + gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); + gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); + enabledCapabilities = {}; + currentTextureSlot = null; + currentBoundTextures = {}; + currentBoundFramebuffers = {}; + currentDrawbuffers = new WeakMap; + defaultDrawbuffers = []; + currentProgram = null; + currentBlendingEnabled = false; + currentBlending = null; + currentBlendEquation = null; + currentBlendSrc = null; + currentBlendDst = null; + currentBlendEquationAlpha = null; + currentBlendSrcAlpha = null; + currentBlendDstAlpha = null; + currentBlendColor = new Color(0, 0, 0); + currentBlendAlpha = 0; + currentPremultipledAlpha = false; + currentFlipSided = null; + currentCullFace = null; + currentLineWidth = null; + currentPolygonOffsetFactor = null; + currentPolygonOffsetUnits = null; + currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height); + currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height); + colorBuffer.reset(); + depthBuffer.reset(); + stencilBuffer.reset(); + } + return { + buffers: { + color: colorBuffer, + depth: depthBuffer, + stencil: stencilBuffer + }, + enable, + disable, + bindFramebuffer, + drawBuffers, + useProgram, + setBlending, + setMaterial, + setFlipSided, + setCullFace, + setLineWidth, + setPolygonOffset, + setScissorTest, + activeTexture, + bindTexture, + unbindTexture, + compressedTexImage2D, + compressedTexImage3D, + texImage2D, + texImage3D, + updateUBOMapping, + uniformBlockBinding, + texStorage2D, + texStorage3D, + texSubImage2D, + texSubImage3D, + compressedTexSubImage2D, + compressedTexSubImage3D, + scissor, + viewport, + reset + }; +} +function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) { + const multisampledRTTExt = extensions.has("WEBGL_multisampled_render_to_texture") ? extensions.get("WEBGL_multisampled_render_to_texture") : null; + const supportsInvalidateFramebuffer = typeof navigator === "undefined" ? false : /OculusBrowser/g.test(navigator.userAgent); + const _imageDimensions = new Vector2; + const _videoTextures = new WeakMap; + let _canvas2; + const _sources = new WeakMap; + let useOffscreenCanvas = false; + try { + useOffscreenCanvas = typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null; + } catch (err) { + } + function createCanvas(width2, height2) { + return useOffscreenCanvas ? new OffscreenCanvas(width2, height2) : createElementNS("canvas"); + } + function resizeImage(image, needsNewCanvas, maxSize) { + let scale2 = 1; + const dimensions = getDimensions(image); + if (dimensions.width > maxSize || dimensions.height > maxSize) { + scale2 = maxSize / Math.max(dimensions.width, dimensions.height); + } + if (scale2 < 1) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + const width2 = Math.floor(scale2 * dimensions.width); + const height2 = Math.floor(scale2 * dimensions.height); + if (_canvas2 === undefined) + _canvas2 = createCanvas(width2, height2); + const canvas = needsNewCanvas ? createCanvas(width2, height2) : _canvas2; + canvas.width = width2; + canvas.height = height2; + const context = canvas.getContext("2d"); + context.drawImage(image, 0, 0, width2, height2); + console.warn("THREE.WebGLRenderer: Texture has been resized from (" + dimensions.width + "x" + dimensions.height + ") to (" + width2 + "x" + height2 + ")."); + return canvas; + } else { + if ("data" in image) { + console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + dimensions.width + "x" + dimensions.height + ")."); + } + return image; + } + } + return image; + } + function textureNeedsGenerateMipmaps(texture) { + return texture.generateMipmaps; + } + function generateMipmap(target) { + _gl.generateMipmap(target); + } + function getTargetType(texture) { + if (texture.isWebGLCubeRenderTarget) + return _gl.TEXTURE_CUBE_MAP; + if (texture.isWebGL3DRenderTarget) + return _gl.TEXTURE_3D; + if (texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture) + return _gl.TEXTURE_2D_ARRAY; + return _gl.TEXTURE_2D; + } + function getInternalFormat(internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false) { + if (internalFormatName !== null) { + if (_gl[internalFormatName] !== undefined) + return _gl[internalFormatName]; + console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + internalFormatName + "'"); + } + let internalFormat = glFormat; + if (glFormat === _gl.RED) { + if (glType === _gl.FLOAT) + internalFormat = _gl.R32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.R16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.R8; + } + if (glFormat === _gl.RED_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.R8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.R16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.R32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.R8I; + if (glType === _gl.SHORT) + internalFormat = _gl.R16I; + if (glType === _gl.INT) + internalFormat = _gl.R32I; + } + if (glFormat === _gl.RG) { + if (glType === _gl.FLOAT) + internalFormat = _gl.RG32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.RG16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RG8; + } + if (glFormat === _gl.RG_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RG8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RG16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RG32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RG8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RG16I; + if (glType === _gl.INT) + internalFormat = _gl.RG32I; + } + if (glFormat === _gl.RGB_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RGB8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RGB16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RGB32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RGB8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RGB16I; + if (glType === _gl.INT) + internalFormat = _gl.RGB32I; + } + if (glFormat === _gl.RGBA_INTEGER) { + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = _gl.RGBA8UI; + if (glType === _gl.UNSIGNED_SHORT) + internalFormat = _gl.RGBA16UI; + if (glType === _gl.UNSIGNED_INT) + internalFormat = _gl.RGBA32UI; + if (glType === _gl.BYTE) + internalFormat = _gl.RGBA8I; + if (glType === _gl.SHORT) + internalFormat = _gl.RGBA16I; + if (glType === _gl.INT) + internalFormat = _gl.RGBA32I; + } + if (glFormat === _gl.RGB) { + if (glType === _gl.UNSIGNED_INT_5_9_9_9_REV) + internalFormat = _gl.RGB9_E5; + } + if (glFormat === _gl.RGBA) { + const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer(colorSpace); + if (glType === _gl.FLOAT) + internalFormat = _gl.RGBA32F; + if (glType === _gl.HALF_FLOAT) + internalFormat = _gl.RGBA16F; + if (glType === _gl.UNSIGNED_BYTE) + internalFormat = transfer === SRGBTransfer ? _gl.SRGB8_ALPHA8 : _gl.RGBA8; + if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) + internalFormat = _gl.RGBA4; + if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) + internalFormat = _gl.RGB5_A1; + } + if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) { + extensions.get("EXT_color_buffer_float"); + } + return internalFormat; + } + function getInternalDepthFormat(useStencil, depthType) { + let glInternalFormat; + if (useStencil) { + if (depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + } else if (depthType === FloatType) { + glInternalFormat = _gl.DEPTH32F_STENCIL8; + } else if (depthType === UnsignedShortType) { + glInternalFormat = _gl.DEPTH24_STENCIL8; + console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment."); + } + } else { + if (depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type) { + glInternalFormat = _gl.DEPTH_COMPONENT24; + } else if (depthType === FloatType) { + glInternalFormat = _gl.DEPTH_COMPONENT32F; + } else if (depthType === UnsignedShortType) { + glInternalFormat = _gl.DEPTH_COMPONENT16; + } + } + return glInternalFormat; + } + function getMipLevels(texture, image) { + if (textureNeedsGenerateMipmaps(texture) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) { + return Math.log2(Math.max(image.width, image.height)) + 1; + } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) { + return texture.mipmaps.length; + } else if (texture.isCompressedTexture && Array.isArray(texture.image)) { + return image.mipmaps.length; + } else { + return 1; + } + } + function onTextureDispose(event) { + const texture = event.target; + texture.removeEventListener("dispose", onTextureDispose); + deallocateTexture(texture); + if (texture.isVideoTexture) { + _videoTextures.delete(texture); + } + } + function onRenderTargetDispose(event) { + const renderTarget = event.target; + renderTarget.removeEventListener("dispose", onRenderTargetDispose); + deallocateRenderTarget(renderTarget); + } + function deallocateTexture(texture) { + const textureProperties = properties.get(texture); + if (textureProperties.__webglInit === undefined) + return; + const source = texture.source; + const webglTextures = _sources.get(source); + if (webglTextures) { + const webglTexture = webglTextures[textureProperties.__cacheKey]; + webglTexture.usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + if (Object.keys(webglTextures).length === 0) { + _sources.delete(source); + } + } + properties.remove(texture); + } + function deleteTexture(texture) { + const textureProperties = properties.get(texture); + _gl.deleteTexture(textureProperties.__webglTexture); + const source = texture.source; + const webglTextures = _sources.get(source); + delete webglTextures[textureProperties.__cacheKey]; + info.memory.textures--; + } + function deallocateRenderTarget(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTarget.depthTexture) { + renderTarget.depthTexture.dispose(); + properties.remove(renderTarget.depthTexture); + } + if (renderTarget.isWebGLCubeRenderTarget) { + for (let i = 0;i < 6; i++) { + if (Array.isArray(renderTargetProperties.__webglFramebuffer[i])) { + for (let level = 0;level < renderTargetProperties.__webglFramebuffer[i].length; level++) + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i][level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]); + } + if (renderTargetProperties.__webglDepthbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]); + } + } else { + if (Array.isArray(renderTargetProperties.__webglFramebuffer)) { + for (let level = 0;level < renderTargetProperties.__webglFramebuffer.length; level++) + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[level]); + } else { + _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer); + } + if (renderTargetProperties.__webglDepthbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer); + if (renderTargetProperties.__webglMultisampledFramebuffer) + _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer); + if (renderTargetProperties.__webglColorRenderbuffer) { + for (let i = 0;i < renderTargetProperties.__webglColorRenderbuffer.length; i++) { + if (renderTargetProperties.__webglColorRenderbuffer[i]) + _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]); + } + } + if (renderTargetProperties.__webglDepthRenderbuffer) + _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer); + } + const textures = renderTarget.textures; + for (let i = 0, il = textures.length;i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture) { + _gl.deleteTexture(attachmentProperties.__webglTexture); + info.memory.textures--; + } + properties.remove(textures[i]); + } + properties.remove(renderTarget); + } + let textureUnits = 0; + function resetTextureUnits() { + textureUnits = 0; + } + function allocateTextureUnit() { + const textureUnit = textureUnits; + if (textureUnit >= capabilities.maxTextures) { + console.warn("THREE.WebGLTextures: Trying to use " + textureUnit + " texture units while this GPU supports only " + capabilities.maxTextures); + } + textureUnits += 1; + return textureUnit; + } + function getTextureCacheKey(texture) { + const array = []; + array.push(texture.wrapS); + array.push(texture.wrapT); + array.push(texture.wrapR || 0); + array.push(texture.magFilter); + array.push(texture.minFilter); + array.push(texture.anisotropy); + array.push(texture.internalFormat); + array.push(texture.format); + array.push(texture.type); + array.push(texture.generateMipmaps); + array.push(texture.premultiplyAlpha); + array.push(texture.flipY); + array.push(texture.unpackAlignment); + array.push(texture.colorSpace); + return array.join(); + } + function setTexture2D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.isVideoTexture) + updateVideoTexture(texture); + if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { + const image = texture.image; + if (image === null) { + console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found."); + } else if (image.complete === false) { + console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete"); + } else { + uploadTexture(textureProperties, texture, slot); + return; + } + } + state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture2DArray(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTexture3D(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + function setTextureCube(texture, slot) { + const textureProperties = properties.get(texture); + if (texture.version > 0 && textureProperties.__version !== texture.version) { + uploadCubeTexture(textureProperties, texture, slot); + return; + } + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + } + const wrappingToGL = { + [RepeatWrapping]: _gl.REPEAT, + [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE, + [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT + }; + const filterToGL = { + [NearestFilter]: _gl.NEAREST, + [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST, + [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR, + [LinearFilter]: _gl.LINEAR, + [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST, + [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR + }; + const compareToGL = { + [NeverCompare]: _gl.NEVER, + [AlwaysCompare]: _gl.ALWAYS, + [LessCompare]: _gl.LESS, + [LessEqualCompare]: _gl.LEQUAL, + [EqualCompare]: _gl.EQUAL, + [GreaterEqualCompare]: _gl.GEQUAL, + [GreaterCompare]: _gl.GREATER, + [NotEqualCompare]: _gl.NOTEQUAL + }; + function setTextureParameters(textureType, texture) { + if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false && (texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter || texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter)) { + console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."); + } + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]); + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]); + if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) { + _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]); + } + _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]); + _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]); + if (texture.compareFunction) { + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE); + _gl.texParameteri(textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[texture.compareFunction]); + } + if (extensions.has("EXT_texture_filter_anisotropic") === true) { + if (texture.magFilter === NearestFilter) + return; + if (texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter) + return; + if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false) + return; + if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) { + const extension = extensions.get("EXT_texture_filter_anisotropic"); + _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy())); + properties.get(texture).__currentAnisotropy = texture.anisotropy; + } + } + } + function initTexture(textureProperties, texture) { + let forceUpload = false; + if (textureProperties.__webglInit === undefined) { + textureProperties.__webglInit = true; + texture.addEventListener("dispose", onTextureDispose); + } + const source = texture.source; + let webglTextures = _sources.get(source); + if (webglTextures === undefined) { + webglTextures = {}; + _sources.set(source, webglTextures); + } + const textureCacheKey = getTextureCacheKey(texture); + if (textureCacheKey !== textureProperties.__cacheKey) { + if (webglTextures[textureCacheKey] === undefined) { + webglTextures[textureCacheKey] = { + texture: _gl.createTexture(), + usedTimes: 0 + }; + info.memory.textures++; + forceUpload = true; + } + webglTextures[textureCacheKey].usedTimes++; + const webglTexture = webglTextures[textureProperties.__cacheKey]; + if (webglTexture !== undefined) { + webglTextures[textureProperties.__cacheKey].usedTimes--; + if (webglTexture.usedTimes === 0) { + deleteTexture(texture); + } + } + textureProperties.__cacheKey = textureCacheKey; + textureProperties.__webglTexture = webglTextures[textureCacheKey].texture; + } + return forceUpload; + } + function uploadTexture(textureProperties, texture, slot) { + let textureType = _gl.TEXTURE_2D; + if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) + textureType = _gl.TEXTURE_2D_ARRAY; + if (texture.isData3DTexture) + textureType = _gl.TEXTURE_3D; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + let image = resizeImage(texture.image, false, capabilities.maxTextureSize); + image = verifyColorSpace(texture, image); + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + let glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture); + setTextureParameters(textureType, texture); + let mipmap; + const mipmaps = texture.mipmaps; + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; + const dataReady = source.dataReady; + const levels = getMipLevels(texture, image); + if (texture.isDepthTexture) { + glInternalFormat = getInternalDepthFormat(texture.format === DepthStencilFormat, texture.type); + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height); + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null); + } + } + } else if (texture.isDataTexture) { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data); + } + } + } else if (texture.isCompressedTexture) { + if (texture.isCompressedArrayTexture) { + if (useTexStorage && allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength(mipmap.width, mipmap.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = mipmap.data.subarray(layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT, (layerIndex + 1) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT); + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData); + } + texture.clearLayerUpdates(); + } else { + state.compressedTexSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data); + } + } + } else { + state.compressedTexImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data); + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data); + } + } + } + } else { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else if (texture.isDataArrayTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + if (texture.layerUpdates.size > 0) { + const layerByteLength = getByteLength(image.width, image.height, texture.format, texture.type); + for (const layerIndex of texture.layerUpdates) { + const layerData = image.data.subarray(layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT, (layerIndex + 1) * layerByteLength / image.data.BYTES_PER_ELEMENT); + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData); + } + texture.clearLayerUpdates(); + } else { + state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } + } else { + state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isData3DTexture) { + if (useTexStorage) { + if (allocateMemory) { + state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth); + } + if (dataReady) { + state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); + } + } else { + state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); + } + } else if (texture.isFramebufferTexture) { + if (allocateMemory) { + if (useTexStorage) { + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height); + } else { + let { width: width2, height: height2 } = image; + for (let i = 0;i < levels; i++) { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width2, height2, 0, glFormat, glType, null); + width2 >>= 1; + height2 >>= 1; + } + } + } + } else { + if (mipmaps.length > 0) { + if (useTexStorage && allocateMemory) { + const dimensions = getDimensions(mipmaps[0]); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0, il = mipmaps.length;i < il; i++) { + mipmap = mipmaps[i]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap); + } + } + texture.generateMipmaps = false; + } else { + if (useTexStorage) { + if (allocateMemory) { + const dimensions = getDimensions(image); + state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height); + } + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image); + } + } else { + state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image); + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(textureType); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) + texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function uploadCubeTexture(textureProperties, texture, slot) { + if (texture.image.length !== 6) + return; + const forceUpload = initTexture(textureProperties, texture); + const source = texture.source; + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot); + const sourceProperties = properties.get(source); + if (source.version !== sourceProperties.__version || forceUpload === true) { + state.activeTexture(_gl.TEXTURE0 + slot); + const workingPrimaries = ColorManagement.getPrimaries(ColorManagement.workingColorSpace); + const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries(texture.colorSpace); + const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL; + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment); + _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion); + const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture; + const isDataTexture = texture.image[0] && texture.image[0].isDataTexture; + const cubeImage = []; + for (let i = 0;i < 6; i++) { + if (!isCompressed && !isDataTexture) { + cubeImage[i] = resizeImage(texture.image[i], true, capabilities.maxCubemapSize); + } else { + cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i]; + } + cubeImage[i] = verifyColorSpace(texture, cubeImage[i]); + } + const image = cubeImage[0], glFormat = utils.convert(texture.format, texture.colorSpace), glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const useTexStorage = texture.isVideoTexture !== true; + const allocateMemory = sourceProperties.__version === undefined || forceUpload === true; + const dataReady = source.dataReady; + let levels = getMipLevels(texture, image); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + let mipmaps; + if (isCompressed) { + if (useTexStorage && allocateMemory) { + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height); + } + for (let i = 0;i < 6; i++) { + mipmaps = cubeImage[i].mipmaps; + for (let j = 0;j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + if (texture.format !== RGBAFormat) { + if (glFormat !== null) { + if (useTexStorage) { + if (dataReady) { + state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); + } + } else { + state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); + } + } else { + console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"); + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); + } + } + } + } + } else { + mipmaps = texture.mipmaps; + if (useTexStorage && allocateMemory) { + if (mipmaps.length > 0) + levels++; + const dimensions = getDimensions(cubeImage[0]); + state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height); + } + for (let i = 0;i < 6; i++) { + if (isDataTexture) { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data); + } + for (let j = 0;j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + const mipmapImage = mipmap.image[i].image; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data); + } + } + } else { + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]); + } + for (let j = 0;j < mipmaps.length; j++) { + const mipmap = mipmaps[j]; + if (useTexStorage) { + if (dataReady) { + state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]); + } + } else { + state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]); + } + } + } + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + sourceProperties.__version = source.version; + if (texture.onUpdate) + texture.onUpdate(texture); + } + textureProperties.__version = texture.version; + } + function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget, level) { + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + textureProperties.__renderTarget = renderTarget; + if (!renderTargetProperties.__hasExternalTextures) { + const width2 = Math.max(1, renderTarget.width >> level); + const height2 = Math.max(1, renderTarget.height >> level); + if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) { + state.texImage3D(textureTarget, level, glInternalFormat, width2, height2, renderTarget.depth, 0, glFormat, glType, null); + } else { + state.texImage2D(textureTarget, level, glInternalFormat, width2, height2, 0, glFormat, glType, null); + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples(renderTarget)); + } else if (textureTarget === _gl.TEXTURE_2D || textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z) { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) { + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null; + const glInternalFormat = getInternalDepthFormat(renderTarget.stencilBuffer, depthType); + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const samples = getRenderTargetSamples(renderTarget); + const isUseMultisampledRTT = useMultisampledRTT(renderTarget); + if (isUseMultisampledRTT) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (isMultisample) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } else { + const textures = renderTarget.textures; + for (let i = 0;i < textures.length; i++) { + const texture = textures[i]; + const glFormat = utils.convert(texture.format, texture.colorSpace); + const glType = utils.convert(texture.type); + const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.colorSpace); + const samples = getRenderTargetSamples(renderTarget); + if (isMultisample && useMultisampledRTT(renderTarget) === false) { + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + } else { + _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height); + } + } + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + } + function setupDepthTexture(framebuffer, renderTarget) { + const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget; + if (isCube) + throw new Error("Depth Texture with cube render targets is not supported"); + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) { + throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); + } + const textureProperties = properties.get(renderTarget.depthTexture); + textureProperties.__renderTarget = renderTarget; + if (!textureProperties.__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) { + renderTarget.depthTexture.image.width = renderTarget.width; + renderTarget.depthTexture.image.height = renderTarget.height; + renderTarget.depthTexture.needsUpdate = true; + } + setTexture2D(renderTarget.depthTexture, 0); + const webglDepthTexture = textureProperties.__webglTexture; + const samples = getRenderTargetSamples(renderTarget); + if (renderTarget.depthTexture.format === DepthFormat) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else if (renderTarget.depthTexture.format === DepthStencilFormat) { + if (useMultisampledRTT(renderTarget)) { + multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples); + } else { + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0); + } + } else { + throw new Error("Unknown depthTexture format"); + } + } + function setupDepthRenderbuffer(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + if (renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__depthDisposeCallback) { + renderTargetProperties.__depthDisposeCallback(); + } + if (depthTexture) { + const disposeEvent = () => { + delete renderTargetProperties.__boundDepthTexture; + delete renderTargetProperties.__depthDisposeCallback; + depthTexture.removeEventListener("dispose", disposeEvent); + }; + depthTexture.addEventListener("dispose", disposeEvent); + renderTargetProperties.__depthDisposeCallback = disposeEvent; + } + renderTargetProperties.__boundDepthTexture = depthTexture; + } + if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) { + if (isCube) + throw new Error("target.depthTexture not supported in Cube render targets"); + setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget); + } else { + if (isCube) { + renderTargetProperties.__webglDepthbuffer = []; + for (let i = 0;i < 6; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]); + if (renderTargetProperties.__webglDepthbuffer[i] === undefined) { + renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer[i]; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } else { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + if (renderTargetProperties.__webglDepthbuffer === undefined) { + renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false); + } else { + const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderbuffer = renderTargetProperties.__webglDepthbuffer; + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer); + } + } + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + function rebindTextures(renderTarget, colorTexture, depthTexture) { + const renderTargetProperties = properties.get(renderTarget); + if (colorTexture !== undefined) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0); + } + if (depthTexture !== undefined) { + setupDepthRenderbuffer(renderTarget); + } + } + function setupRenderTarget(renderTarget) { + const texture = renderTarget.texture; + const renderTargetProperties = properties.get(renderTarget); + const textureProperties = properties.get(texture); + renderTarget.addEventListener("dispose", onRenderTargetDispose); + const textures = renderTarget.textures; + const isCube = renderTarget.isWebGLCubeRenderTarget === true; + const isMultipleRenderTargets = textures.length > 1; + if (!isMultipleRenderTargets) { + if (textureProperties.__webglTexture === undefined) { + textureProperties.__webglTexture = _gl.createTexture(); + } + textureProperties.__version = texture.version; + info.memory.textures++; + } + if (isCube) { + renderTargetProperties.__webglFramebuffer = []; + for (let i = 0;i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer[i] = []; + for (let level = 0;level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[i][level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer(); + } + } + } else { + if (texture.mipmaps && texture.mipmaps.length > 0) { + renderTargetProperties.__webglFramebuffer = []; + for (let level = 0;level < texture.mipmaps.length; level++) { + renderTargetProperties.__webglFramebuffer[level] = _gl.createFramebuffer(); + } + } else { + renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); + } + if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length;i < il; i++) { + const attachmentProperties = properties.get(textures[i]); + if (attachmentProperties.__webglTexture === undefined) { + attachmentProperties.__webglTexture = _gl.createTexture(); + info.memory.textures++; + } + } + } + if (renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { + renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); + renderTargetProperties.__webglColorRenderbuffer = []; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + for (let i = 0;i < textures.length; i++) { + const texture2 = textures[i]; + renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer(); + _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const glFormat = utils.convert(texture2.format, texture2.colorSpace); + const glType = utils.convert(texture2.type); + const glInternalFormat = getInternalFormat(texture2.internalFormat, glFormat, glType, texture2.colorSpace, renderTarget.isXRRenderTarget === true); + const samples = getRenderTargetSamples(renderTarget); + _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + } + _gl.bindRenderbuffer(_gl.RENDERBUFFER, null); + if (renderTarget.depthBuffer) { + renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); + setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true); + } + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + } + } + if (isCube) { + state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture); + for (let i = 0;i < 6; i++) { + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0;level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i][level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0); + } + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(_gl.TEXTURE_CUBE_MAP); + } + state.unbindTexture(); + } else if (isMultipleRenderTargets) { + for (let i = 0, il = textures.length;i < il; i++) { + const attachment = textures[i]; + const attachmentProperties = properties.get(attachment); + state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture); + setTextureParameters(_gl.TEXTURE_2D, attachment); + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0); + if (textureNeedsGenerateMipmaps(attachment)) { + generateMipmap(_gl.TEXTURE_2D); + } + } + state.unbindTexture(); + } else { + let glTextureType = _gl.TEXTURE_2D; + if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { + glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY; + } + state.bindTexture(glTextureType, textureProperties.__webglTexture); + setTextureParameters(glTextureType, texture); + if (texture.mipmaps && texture.mipmaps.length > 0) { + for (let level = 0;level < texture.mipmaps.length; level++) { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[level], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level); + } + } else { + setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0); + } + if (textureNeedsGenerateMipmaps(texture)) { + generateMipmap(glTextureType); + } + state.unbindTexture(); + } + if (renderTarget.depthBuffer) { + setupDepthRenderbuffer(renderTarget); + } + } + function updateRenderTargetMipmap(renderTarget) { + const textures = renderTarget.textures; + for (let i = 0, il = textures.length;i < il; i++) { + const texture = textures[i]; + if (textureNeedsGenerateMipmaps(texture)) { + const targetType = getTargetType(renderTarget); + const webglTexture = properties.get(texture).__webglTexture; + state.bindTexture(targetType, webglTexture); + generateMipmap(targetType); + state.unbindTexture(); + } + } + } + const invalidationArrayRead = []; + const invalidationArrayDraw = []; + function updateMultisampleRenderTarget(renderTarget) { + if (renderTarget.samples > 0) { + if (useMultisampledRTT(renderTarget) === false) { + const textures = renderTarget.textures; + const width2 = renderTarget.width; + const height2 = renderTarget.height; + let mask2 = _gl.COLOR_BUFFER_BIT; + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + const renderTargetProperties = properties.get(renderTarget); + const isMultipleRenderTargets = textures.length > 1; + if (isMultipleRenderTargets) { + for (let i = 0;i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null); + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + for (let i = 0;i < textures.length; i++) { + if (renderTarget.resolveDepthBuffer) { + if (renderTarget.depthBuffer) + mask2 |= _gl.DEPTH_BUFFER_BIT; + if (renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer) + mask2 |= _gl.STENCIL_BUFFER_BIT; + } + if (isMultipleRenderTargets) { + _gl.framebufferRenderbuffer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0); + } + _gl.blitFramebuffer(0, 0, width2, height2, 0, 0, width2, height2, mask2, _gl.NEAREST); + if (supportsInvalidateFramebuffer === true) { + invalidationArrayRead.length = 0; + invalidationArrayDraw.length = 0; + invalidationArrayRead.push(_gl.COLOR_ATTACHMENT0 + i); + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false) { + invalidationArrayRead.push(depthStyle); + invalidationArrayDraw.push(depthStyle); + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, invalidationArrayDraw); + } + _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArrayRead); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + if (isMultipleRenderTargets) { + for (let i = 0;i < textures.length; i++) { + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[i]); + const webglTexture = properties.get(textures[i]).__webglTexture; + state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer); + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0); + } + } + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer); + } else { + if (renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer) { + const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT; + _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]); + } + } + } + } + function getRenderTargetSamples(renderTarget) { + return Math.min(capabilities.maxSamples, renderTarget.samples); + } + function useMultisampledRTT(renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + return renderTarget.samples > 0 && extensions.has("WEBGL_multisampled_render_to_texture") === true && renderTargetProperties.__useRenderToTexture !== false; + } + function updateVideoTexture(texture) { + const frame = info.render.frame; + if (_videoTextures.get(texture) !== frame) { + _videoTextures.set(texture, frame); + texture.update(); + } + } + function verifyColorSpace(texture, image) { + const colorSpace = texture.colorSpace; + const format = texture.format; + const type = texture.type; + if (texture.isCompressedTexture === true || texture.isVideoTexture === true) + return image; + if (colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace) { + if (ColorManagement.getTransfer(colorSpace) === SRGBTransfer) { + if (format !== RGBAFormat || type !== UnsignedByteType) { + console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."); + } + } else { + console.error("THREE.WebGLTextures: Unsupported texture color space:", colorSpace); + } + } + return image; + } + function getDimensions(image) { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement) { + _imageDimensions.width = image.naturalWidth || image.width; + _imageDimensions.height = image.naturalHeight || image.height; + } else if (typeof VideoFrame !== "undefined" && image instanceof VideoFrame) { + _imageDimensions.width = image.displayWidth; + _imageDimensions.height = image.displayHeight; + } else { + _imageDimensions.width = image.width; + _imageDimensions.height = image.height; + } + return _imageDimensions; + } + this.allocateTextureUnit = allocateTextureUnit; + this.resetTextureUnits = resetTextureUnits; + this.setTexture2D = setTexture2D; + this.setTexture2DArray = setTexture2DArray; + this.setTexture3D = setTexture3D; + this.setTextureCube = setTextureCube; + this.rebindTextures = rebindTextures; + this.setupRenderTarget = setupRenderTarget; + this.updateRenderTargetMipmap = updateRenderTargetMipmap; + this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; + this.setupDepthRenderbuffer = setupDepthRenderbuffer; + this.setupFrameBufferTexture = setupFrameBufferTexture; + this.useMultisampledRTT = useMultisampledRTT; +} +function WebGLUtils(gl, extensions) { + function convert(p, colorSpace = NoColorSpace) { + let extension; + const transfer = ColorManagement.getTransfer(colorSpace); + if (p === UnsignedByteType) + return gl.UNSIGNED_BYTE; + if (p === UnsignedShort4444Type) + return gl.UNSIGNED_SHORT_4_4_4_4; + if (p === UnsignedShort5551Type) + return gl.UNSIGNED_SHORT_5_5_5_1; + if (p === UnsignedInt5999Type) + return gl.UNSIGNED_INT_5_9_9_9_REV; + if (p === ByteType) + return gl.BYTE; + if (p === ShortType) + return gl.SHORT; + if (p === UnsignedShortType) + return gl.UNSIGNED_SHORT; + if (p === IntType) + return gl.INT; + if (p === UnsignedIntType) + return gl.UNSIGNED_INT; + if (p === FloatType) + return gl.FLOAT; + if (p === HalfFloatType) + return gl.HALF_FLOAT; + if (p === AlphaFormat) + return gl.ALPHA; + if (p === RGBFormat) + return gl.RGB; + if (p === RGBAFormat) + return gl.RGBA; + if (p === LuminanceFormat) + return gl.LUMINANCE; + if (p === LuminanceAlphaFormat) + return gl.LUMINANCE_ALPHA; + if (p === DepthFormat) + return gl.DEPTH_COMPONENT; + if (p === DepthStencilFormat) + return gl.DEPTH_STENCIL; + if (p === RedFormat) + return gl.RED; + if (p === RedIntegerFormat) + return gl.RED_INTEGER; + if (p === RGFormat) + return gl.RG; + if (p === RGIntegerFormat) + return gl.RG_INTEGER; + if (p === RGBAIntegerFormat) + return gl.RGBA_INTEGER; + if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) { + if (transfer === SRGBTransfer) { + extension = extensions.get("WEBGL_compressed_texture_s3tc_srgb"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format) + return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format) + return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + } else { + return null; + } + } else { + extension = extensions.get("WEBGL_compressed_texture_s3tc"); + if (extension !== null) { + if (p === RGB_S3TC_DXT1_Format) + return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT1_Format) + return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; + if (p === RGBA_S3TC_DXT3_Format) + return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; + if (p === RGBA_S3TC_DXT5_Format) + return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; + } else { + return null; + } + } + } + if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) { + extension = extensions.get("WEBGL_compressed_texture_pvrtc"); + if (extension !== null) { + if (p === RGB_PVRTC_4BPPV1_Format) + return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; + if (p === RGB_PVRTC_2BPPV1_Format) + return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; + if (p === RGBA_PVRTC_4BPPV1_Format) + return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; + if (p === RGBA_PVRTC_2BPPV1_Format) + return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; + } else { + return null; + } + } + if (p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) { + extension = extensions.get("WEBGL_compressed_texture_etc"); + if (extension !== null) { + if (p === RGB_ETC1_Format || p === RGB_ETC2_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; + if (p === RGBA_ETC2_EAC_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; + } else { + return null; + } + } + if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format) { + extension = extensions.get("WEBGL_compressed_texture_astc"); + if (extension !== null) { + if (p === RGBA_ASTC_4x4_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; + if (p === RGBA_ASTC_5x4_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; + if (p === RGBA_ASTC_5x5_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; + if (p === RGBA_ASTC_6x5_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; + if (p === RGBA_ASTC_6x6_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; + if (p === RGBA_ASTC_8x5_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; + if (p === RGBA_ASTC_8x6_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; + if (p === RGBA_ASTC_8x8_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; + if (p === RGBA_ASTC_10x5_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; + if (p === RGBA_ASTC_10x6_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; + if (p === RGBA_ASTC_10x8_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; + if (p === RGBA_ASTC_10x10_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; + if (p === RGBA_ASTC_12x10_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; + if (p === RGBA_ASTC_12x12_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; + } else { + return null; + } + } + if (p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format) { + extension = extensions.get("EXT_texture_compression_bptc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format) + return transfer === SRGBTransfer ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; + if (p === RGB_BPTC_SIGNED_Format) + return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; + if (p === RGB_BPTC_UNSIGNED_Format) + return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; + } else { + return null; + } + } + if (p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format) { + extension = extensions.get("EXT_texture_compression_rgtc"); + if (extension !== null) { + if (p === RGBA_BPTC_Format) + return extension.COMPRESSED_RED_RGTC1_EXT; + if (p === SIGNED_RED_RGTC1_Format) + return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT; + if (p === RED_GREEN_RGTC2_Format) + return extension.COMPRESSED_RED_GREEN_RGTC2_EXT; + if (p === SIGNED_RED_GREEN_RGTC2_Format) + return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; + } else { + return null; + } + } + if (p === UnsignedInt248Type) + return gl.UNSIGNED_INT_24_8; + return gl[p] !== undefined ? gl[p] : null; + } + return { convert }; +} +var _occlusion_vertex = ` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`; +var _occlusion_fragment = ` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`; + +class WebXRDepthSensing { + constructor() { + this.texture = null; + this.mesh = null; + this.depthNear = 0; + this.depthFar = 0; + } + init(renderer2, depthData, renderState) { + if (this.texture === null) { + const texture = new Texture; + const texProps = renderer2.properties.get(texture); + texProps.__webglTexture = depthData.texture; + if (depthData.depthNear !== renderState.depthNear || depthData.depthFar !== renderState.depthFar) { + this.depthNear = depthData.depthNear; + this.depthFar = depthData.depthFar; + } + this.texture = texture; + } + } + getMesh(cameraXR) { + if (this.texture !== null) { + if (this.mesh === null) { + const viewport = cameraXR.cameras[0].viewport; + const material = new ShaderMaterial({ + vertexShader: _occlusion_vertex, + fragmentShader: _occlusion_fragment, + uniforms: { + depthColor: { value: this.texture }, + depthWidth: { value: viewport.z }, + depthHeight: { value: viewport.w } + } + }); + this.mesh = new Mesh(new PlaneGeometry(20, 20), material); + } + } + return this.mesh; + } + reset() { + this.texture = null; + this.mesh = null; + } + getDepthTexture() { + return this.texture; + } +} + +class WebXRManager extends EventDispatcher { + constructor(renderer2, gl) { + super(); + const scope = this; + let session = null; + let framebufferScaleFactor = 1; + let referenceSpace = null; + let referenceSpaceType = "local-floor"; + let foveation = 1; + let customReferenceSpace = null; + let pose = null; + let glBinding = null; + let glProjLayer = null; + let glBaseLayer = null; + let xrFrame = null; + const depthSensing = new WebXRDepthSensing; + const attributes = gl.getContextAttributes(); + let initialRenderTarget = null; + let newRenderTarget = null; + const controllers = []; + const controllerInputSources = []; + const currentSize = new Vector2; + let currentPixelRatio = null; + const cameraL = new PerspectiveCamera; + cameraL.viewport = new Vector4; + const cameraR = new PerspectiveCamera; + cameraR.viewport = new Vector4; + const cameras = [cameraL, cameraR]; + const cameraXR = new ArrayCamera; + let _currentDepthNear = null; + let _currentDepthFar = null; + this.cameraAutoUpdate = true; + this.enabled = false; + this.isPresenting = false; + this.getController = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController; + controllers[index2] = controller; + } + return controller.getTargetRaySpace(); + }; + this.getControllerGrip = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController; + controllers[index2] = controller; + } + return controller.getGripSpace(); + }; + this.getHand = function(index2) { + let controller = controllers[index2]; + if (controller === undefined) { + controller = new WebXRController; + controllers[index2] = controller; + } + return controller.getHandSpace(); + }; + function onSessionEvent(event) { + const controllerIndex = controllerInputSources.indexOf(event.inputSource); + if (controllerIndex === -1) { + return; + } + const controller = controllers[controllerIndex]; + if (controller !== undefined) { + controller.update(event.inputSource, event.frame, customReferenceSpace || referenceSpace); + controller.dispatchEvent({ type: event.type, data: event.inputSource }); + } + } + function onSessionEnd() { + session.removeEventListener("select", onSessionEvent); + session.removeEventListener("selectstart", onSessionEvent); + session.removeEventListener("selectend", onSessionEvent); + session.removeEventListener("squeeze", onSessionEvent); + session.removeEventListener("squeezestart", onSessionEvent); + session.removeEventListener("squeezeend", onSessionEvent); + session.removeEventListener("end", onSessionEnd); + session.removeEventListener("inputsourceschange", onInputSourcesChange); + for (let i = 0;i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + if (inputSource === null) + continue; + controllerInputSources[i] = null; + controllers[i].disconnect(inputSource); + } + _currentDepthNear = null; + _currentDepthFar = null; + depthSensing.reset(); + renderer2.setRenderTarget(initialRenderTarget); + glBaseLayer = null; + glProjLayer = null; + glBinding = null; + session = null; + newRenderTarget = null; + animation.stop(); + scope.isPresenting = false; + renderer2.setPixelRatio(currentPixelRatio); + renderer2.setSize(currentSize.width, currentSize.height, false); + scope.dispatchEvent({ type: "sessionend" }); + } + this.setFramebufferScaleFactor = function(value2) { + framebufferScaleFactor = value2; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting."); + } + }; + this.setReferenceSpaceType = function(value2) { + referenceSpaceType = value2; + if (scope.isPresenting === true) { + console.warn("THREE.WebXRManager: Cannot change reference space type while presenting."); + } + }; + this.getReferenceSpace = function() { + return customReferenceSpace || referenceSpace; + }; + this.setReferenceSpace = function(space) { + customReferenceSpace = space; + }; + this.getBaseLayer = function() { + return glProjLayer !== null ? glProjLayer : glBaseLayer; + }; + this.getBinding = function() { + return glBinding; + }; + this.getFrame = function() { + return xrFrame; + }; + this.getSession = function() { + return session; + }; + this.setSession = async function(value2) { + session = value2; + if (session !== null) { + initialRenderTarget = renderer2.getRenderTarget(); + session.addEventListener("select", onSessionEvent); + session.addEventListener("selectstart", onSessionEvent); + session.addEventListener("selectend", onSessionEvent); + session.addEventListener("squeeze", onSessionEvent); + session.addEventListener("squeezestart", onSessionEvent); + session.addEventListener("squeezeend", onSessionEvent); + session.addEventListener("end", onSessionEnd); + session.addEventListener("inputsourceschange", onInputSourcesChange); + if (attributes.xrCompatible !== true) { + await gl.makeXRCompatible(); + } + currentPixelRatio = renderer2.getPixelRatio(); + renderer2.getSize(currentSize); + const useLayers = typeof XRWebGLBinding !== "undefined" && "createProjectionLayer" in XRWebGLBinding.prototype; + if (!useLayers) { + const layerInit = { + antialias: attributes.antialias, + alpha: true, + depth: attributes.depth, + stencil: attributes.stencil, + framebufferScaleFactor + }; + glBaseLayer = new XRWebGLLayer(session, gl, layerInit); + session.updateRenderState({ baseLayer: glBaseLayer }); + renderer2.setPixelRatio(1); + renderer2.setSize(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false); + newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, { + format: RGBAFormat, + type: UnsignedByteType, + colorSpace: renderer2.outputColorSpace, + stencilBuffer: attributes.stencil + }); + } else { + let depthFormat = null; + let depthType = null; + let glDepthFormat = null; + if (attributes.depth) { + glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; + depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; + depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; + } + const projectionlayerInit = { + colorFormat: gl.RGBA8, + depthFormat: glDepthFormat, + scaleFactor: framebufferScaleFactor + }; + glBinding = new XRWebGLBinding(session, gl); + glProjLayer = glBinding.createProjectionLayer(projectionlayerInit); + session.updateRenderState({ layers: [glProjLayer] }); + renderer2.setPixelRatio(1); + renderer2.setSize(glProjLayer.textureWidth, glProjLayer.textureHeight, false); + newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, { + format: RGBAFormat, + type: UnsignedByteType, + depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat), + stencilBuffer: attributes.stencil, + colorSpace: renderer2.outputColorSpace, + samples: attributes.antialias ? 4 : 0, + resolveDepthBuffer: glProjLayer.ignoreDepthValues === false + }); + } + newRenderTarget.isXRRenderTarget = true; + this.setFoveation(foveation); + customReferenceSpace = null; + referenceSpace = await session.requestReferenceSpace(referenceSpaceType); + animation.setContext(session); + animation.start(); + scope.isPresenting = true; + scope.dispatchEvent({ type: "sessionstart" }); + } + }; + this.getEnvironmentBlendMode = function() { + if (session !== null) { + return session.environmentBlendMode; + } + }; + this.getDepthTexture = function() { + return depthSensing.getDepthTexture(); + }; + function onInputSourcesChange(event) { + for (let i = 0;i < event.removed.length; i++) { + const inputSource = event.removed[i]; + const index2 = controllerInputSources.indexOf(inputSource); + if (index2 >= 0) { + controllerInputSources[index2] = null; + controllers[index2].disconnect(inputSource); + } + } + for (let i = 0;i < event.added.length; i++) { + const inputSource = event.added[i]; + let controllerIndex = controllerInputSources.indexOf(inputSource); + if (controllerIndex === -1) { + for (let i2 = 0;i2 < controllers.length; i2++) { + if (i2 >= controllerInputSources.length) { + controllerInputSources.push(inputSource); + controllerIndex = i2; + break; + } else if (controllerInputSources[i2] === null) { + controllerInputSources[i2] = inputSource; + controllerIndex = i2; + break; + } + } + if (controllerIndex === -1) + break; + } + const controller = controllers[controllerIndex]; + if (controller) { + controller.connect(inputSource); + } + } + } + const cameraLPos = new Vector3; + const cameraRPos = new Vector3; + function setProjectionFromUnion(camera, cameraL2, cameraR2) { + cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld); + cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld); + const ipd = cameraLPos.distanceTo(cameraRPos); + const projL = cameraL2.projectionMatrix.elements; + const projR = cameraR2.projectionMatrix.elements; + const near = projL[14] / (projL[10] - 1); + const far = projL[14] / (projL[10] + 1); + const topFov = (projL[9] + 1) / projL[5]; + const bottomFov = (projL[9] - 1) / projL[5]; + const leftFov = (projL[8] - 1) / projL[0]; + const rightFov = (projR[8] + 1) / projR[0]; + const left = near * leftFov; + const right = near * rightFov; + const zOffset = ipd / (-leftFov + rightFov); + const xOffset = zOffset * -leftFov; + cameraL2.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale); + camera.translateX(xOffset); + camera.translateZ(zOffset); + camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale); + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + if (projL[10] === -1) { + camera.projectionMatrix.copy(cameraL2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraL2.projectionMatrixInverse); + } else { + const near2 = near + zOffset; + const far2 = far + zOffset; + const left2 = left - xOffset; + const right2 = right + (ipd - xOffset); + const top2 = topFov * far / far2 * near2; + const bottom2 = bottomFov * far / far2 * near2; + camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + } + } + function updateCamera(camera, parent2) { + if (parent2 === null) { + camera.matrixWorld.copy(camera.matrix); + } else { + camera.matrixWorld.multiplyMatrices(parent2.matrixWorld, camera.matrix); + } + camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); + } + this.updateCamera = function(camera) { + if (session === null) + return; + let depthNear = camera.near; + let depthFar = camera.far; + if (depthSensing.texture !== null) { + if (depthSensing.depthNear > 0) + depthNear = depthSensing.depthNear; + if (depthSensing.depthFar > 0) + depthFar = depthSensing.depthFar; + } + cameraXR.near = cameraR.near = cameraL.near = depthNear; + cameraXR.far = cameraR.far = cameraL.far = depthFar; + if (_currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far) { + session.updateRenderState({ + depthNear: cameraXR.near, + depthFar: cameraXR.far + }); + _currentDepthNear = cameraXR.near; + _currentDepthFar = cameraXR.far; + } + cameraL.layers.mask = camera.layers.mask | 2; + cameraR.layers.mask = camera.layers.mask | 4; + cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask; + const parent2 = camera.parent; + const cameras2 = cameraXR.cameras; + updateCamera(cameraXR, parent2); + for (let i = 0;i < cameras2.length; i++) { + updateCamera(cameras2[i], parent2); + } + if (cameras2.length === 2) { + setProjectionFromUnion(cameraXR, cameraL, cameraR); + } else { + cameraXR.projectionMatrix.copy(cameraL.projectionMatrix); + } + updateUserCamera(camera, cameraXR, parent2); + }; + function updateUserCamera(camera, cameraXR2, parent2) { + if (parent2 === null) { + camera.matrix.copy(cameraXR2.matrixWorld); + } else { + camera.matrix.copy(parent2.matrixWorld); + camera.matrix.invert(); + camera.matrix.multiply(cameraXR2.matrixWorld); + } + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.updateMatrixWorld(true); + camera.projectionMatrix.copy(cameraXR2.projectionMatrix); + camera.projectionMatrixInverse.copy(cameraXR2.projectionMatrixInverse); + if (camera.isPerspectiveCamera) { + camera.fov = RAD2DEG * 2 * Math.atan(1 / camera.projectionMatrix.elements[5]); + camera.zoom = 1; + } + } + this.getCamera = function() { + return cameraXR; + }; + this.getFoveation = function() { + if (glProjLayer === null && glBaseLayer === null) { + return; + } + return foveation; + }; + this.setFoveation = function(value2) { + foveation = value2; + if (glProjLayer !== null) { + glProjLayer.fixedFoveation = value2; + } + if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) { + glBaseLayer.fixedFoveation = value2; + } + }; + this.hasDepthSensing = function() { + return depthSensing.texture !== null; + }; + this.getDepthSensingMesh = function() { + return depthSensing.getMesh(cameraXR); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time2, frame) { + pose = frame.getViewerPose(customReferenceSpace || referenceSpace); + xrFrame = frame; + if (pose !== null) { + const views = pose.views; + if (glBaseLayer !== null) { + renderer2.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer); + renderer2.setRenderTarget(newRenderTarget); + } + let cameraXRNeedsUpdate = false; + if (views.length !== cameraXR.cameras.length) { + cameraXR.cameras.length = 0; + cameraXRNeedsUpdate = true; + } + for (let i = 0;i < views.length; i++) { + const view = views[i]; + let viewport = null; + if (glBaseLayer !== null) { + viewport = glBaseLayer.getViewport(view); + } else { + const glSubImage = glBinding.getViewSubImage(glProjLayer, view); + viewport = glSubImage.viewport; + if (i === 0) { + renderer2.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture); + renderer2.setRenderTarget(newRenderTarget); + } + } + let camera = cameras[i]; + if (camera === undefined) { + camera = new PerspectiveCamera; + camera.layers.enable(i); + camera.viewport = new Vector4; + cameras[i] = camera; + } + camera.matrix.fromArray(view.transform.matrix); + camera.matrix.decompose(camera.position, camera.quaternion, camera.scale); + camera.projectionMatrix.fromArray(view.projectionMatrix); + camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert(); + camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height); + if (i === 0) { + cameraXR.matrix.copy(camera.matrix); + cameraXR.matrix.decompose(cameraXR.position, cameraXR.quaternion, cameraXR.scale); + } + if (cameraXRNeedsUpdate === true) { + cameraXR.cameras.push(camera); + } + } + const enabledFeatures = session.enabledFeatures; + const gpuDepthSensingEnabled = enabledFeatures && enabledFeatures.includes("depth-sensing") && session.depthUsage == "gpu-optimized"; + if (gpuDepthSensingEnabled && glBinding) { + const depthData = glBinding.getDepthInformation(views[0]); + if (depthData && depthData.isValid && depthData.texture) { + depthSensing.init(renderer2, depthData, session.renderState); + } + } + } + for (let i = 0;i < controllers.length; i++) { + const inputSource = controllerInputSources[i]; + const controller = controllers[i]; + if (inputSource !== null && controller !== undefined) { + controller.update(inputSource, frame, customReferenceSpace || referenceSpace); + } + } + if (onAnimationFrameCallback) + onAnimationFrameCallback(time2, frame); + if (frame.detectedPlanes) { + scope.dispatchEvent({ type: "planesdetected", data: frame }); + } + xrFrame = null; + } + const animation = new WebGLAnimation; + animation.setAnimationLoop(onAnimationFrame); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + }; + this.dispose = function() { + }; + } +} +var _e1 = /* @__PURE__ */ new Euler; +var _m12 = /* @__PURE__ */ new Matrix4; +function WebGLMaterials(renderer2, properties) { + function refreshTransformUniform(map2, uniform) { + if (map2.matrixAutoUpdate === true) { + map2.updateMatrix(); + } + uniform.value.copy(map2.matrix); + } + function refreshFogUniforms(uniforms, fog) { + fog.color.getRGB(uniforms.fogColor.value, getUnlitUniformColorSpace(renderer2)); + if (fog.isFog) { + uniforms.fogNear.value = fog.near; + uniforms.fogFar.value = fog.far; + } else if (fog.isFogExp2) { + uniforms.fogDensity.value = fog.density; + } + } + function refreshMaterialUniforms(uniforms, material, pixelRatio, height2, transmissionRenderTarget) { + if (material.isMeshBasicMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshLambertMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshToonMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsToon(uniforms, material); + } else if (material.isMeshPhongMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsPhong(uniforms, material); + } else if (material.isMeshStandardMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsStandard(uniforms, material); + if (material.isMeshPhysicalMaterial) { + refreshUniformsPhysical(uniforms, material, transmissionRenderTarget); + } + } else if (material.isMeshMatcapMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsMatcap(uniforms, material); + } else if (material.isMeshDepthMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isMeshDistanceMaterial) { + refreshUniformsCommon(uniforms, material); + refreshUniformsDistance(uniforms, material); + } else if (material.isMeshNormalMaterial) { + refreshUniformsCommon(uniforms, material); + } else if (material.isLineBasicMaterial) { + refreshUniformsLine(uniforms, material); + if (material.isLineDashedMaterial) { + refreshUniformsDash(uniforms, material); + } + } else if (material.isPointsMaterial) { + refreshUniformsPoints(uniforms, material, pixelRatio, height2); + } else if (material.isSpriteMaterial) { + refreshUniformsSprites(uniforms, material); + } else if (material.isShadowMaterial) { + uniforms.color.value.copy(material.color); + uniforms.opacity.value = material.opacity; + } else if (material.isShaderMaterial) { + material.uniformsNeedUpdate = false; + } + } + function refreshUniformsCommon(uniforms, material) { + uniforms.opacity.value = material.opacity; + if (material.color) { + uniforms.diffuse.value.copy(material.color); + } + if (material.emissive) { + uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity); + } + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.bumpMap) { + uniforms.bumpMap.value = material.bumpMap; + refreshTransformUniform(material.bumpMap, uniforms.bumpMapTransform); + uniforms.bumpScale.value = material.bumpScale; + if (material.side === BackSide) { + uniforms.bumpScale.value *= -1; + } + } + if (material.normalMap) { + uniforms.normalMap.value = material.normalMap; + refreshTransformUniform(material.normalMap, uniforms.normalMapTransform); + uniforms.normalScale.value.copy(material.normalScale); + if (material.side === BackSide) { + uniforms.normalScale.value.negate(); + } + } + if (material.displacementMap) { + uniforms.displacementMap.value = material.displacementMap; + refreshTransformUniform(material.displacementMap, uniforms.displacementMapTransform); + uniforms.displacementScale.value = material.displacementScale; + uniforms.displacementBias.value = material.displacementBias; + } + if (material.emissiveMap) { + uniforms.emissiveMap.value = material.emissiveMap; + refreshTransformUniform(material.emissiveMap, uniforms.emissiveMapTransform); + } + if (material.specularMap) { + uniforms.specularMap.value = material.specularMap; + refreshTransformUniform(material.specularMap, uniforms.specularMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + const materialProperties = properties.get(material); + const envMap = materialProperties.envMap; + const envMapRotation = materialProperties.envMapRotation; + if (envMap) { + uniforms.envMap.value = envMap; + _e1.copy(envMapRotation); + _e1.x *= -1; + _e1.y *= -1; + _e1.z *= -1; + if (envMap.isCubeTexture && envMap.isRenderTargetTexture === false) { + _e1.y *= -1; + _e1.z *= -1; + } + uniforms.envMapRotation.value.setFromMatrix4(_m12.makeRotationFromEuler(_e1)); + uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + uniforms.reflectivity.value = material.reflectivity; + uniforms.ior.value = material.ior; + uniforms.refractionRatio.value = material.refractionRatio; + } + if (material.lightMap) { + uniforms.lightMap.value = material.lightMap; + uniforms.lightMapIntensity.value = material.lightMapIntensity; + refreshTransformUniform(material.lightMap, uniforms.lightMapTransform); + } + if (material.aoMap) { + uniforms.aoMap.value = material.aoMap; + uniforms.aoMapIntensity.value = material.aoMapIntensity; + refreshTransformUniform(material.aoMap, uniforms.aoMapTransform); + } + } + function refreshUniformsLine(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + } + function refreshUniformsDash(uniforms, material) { + uniforms.dashSize.value = material.dashSize; + uniforms.totalSize.value = material.dashSize + material.gapSize; + uniforms.scale.value = material.scale; + } + function refreshUniformsPoints(uniforms, material, pixelRatio, height2) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.size.value = material.size * pixelRatio; + uniforms.scale.value = height2 * 0.5; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.uvTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsSprites(uniforms, material) { + uniforms.diffuse.value.copy(material.color); + uniforms.opacity.value = material.opacity; + uniforms.rotation.value = material.rotation; + if (material.map) { + uniforms.map.value = material.map; + refreshTransformUniform(material.map, uniforms.mapTransform); + } + if (material.alphaMap) { + uniforms.alphaMap.value = material.alphaMap; + refreshTransformUniform(material.alphaMap, uniforms.alphaMapTransform); + } + if (material.alphaTest > 0) { + uniforms.alphaTest.value = material.alphaTest; + } + } + function refreshUniformsPhong(uniforms, material) { + uniforms.specular.value.copy(material.specular); + uniforms.shininess.value = Math.max(material.shininess, 0.0001); + } + function refreshUniformsToon(uniforms, material) { + if (material.gradientMap) { + uniforms.gradientMap.value = material.gradientMap; + } + } + function refreshUniformsStandard(uniforms, material) { + uniforms.metalness.value = material.metalness; + if (material.metalnessMap) { + uniforms.metalnessMap.value = material.metalnessMap; + refreshTransformUniform(material.metalnessMap, uniforms.metalnessMapTransform); + } + uniforms.roughness.value = material.roughness; + if (material.roughnessMap) { + uniforms.roughnessMap.value = material.roughnessMap; + refreshTransformUniform(material.roughnessMap, uniforms.roughnessMapTransform); + } + if (material.envMap) { + uniforms.envMapIntensity.value = material.envMapIntensity; + } + } + function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) { + uniforms.ior.value = material.ior; + if (material.sheen > 0) { + uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen); + uniforms.sheenRoughness.value = material.sheenRoughness; + if (material.sheenColorMap) { + uniforms.sheenColorMap.value = material.sheenColorMap; + refreshTransformUniform(material.sheenColorMap, uniforms.sheenColorMapTransform); + } + if (material.sheenRoughnessMap) { + uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; + refreshTransformUniform(material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform); + } + } + if (material.clearcoat > 0) { + uniforms.clearcoat.value = material.clearcoat; + uniforms.clearcoatRoughness.value = material.clearcoatRoughness; + if (material.clearcoatMap) { + uniforms.clearcoatMap.value = material.clearcoatMap; + refreshTransformUniform(material.clearcoatMap, uniforms.clearcoatMapTransform); + } + if (material.clearcoatRoughnessMap) { + uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; + refreshTransformUniform(material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform); + } + if (material.clearcoatNormalMap) { + uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; + refreshTransformUniform(material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform); + uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale); + if (material.side === BackSide) { + uniforms.clearcoatNormalScale.value.negate(); + } + } + } + if (material.dispersion > 0) { + uniforms.dispersion.value = material.dispersion; + } + if (material.iridescence > 0) { + uniforms.iridescence.value = material.iridescence; + uniforms.iridescenceIOR.value = material.iridescenceIOR; + uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0]; + uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1]; + if (material.iridescenceMap) { + uniforms.iridescenceMap.value = material.iridescenceMap; + refreshTransformUniform(material.iridescenceMap, uniforms.iridescenceMapTransform); + } + if (material.iridescenceThicknessMap) { + uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; + refreshTransformUniform(material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform); + } + } + if (material.transmission > 0) { + uniforms.transmission.value = material.transmission; + uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; + uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height); + if (material.transmissionMap) { + uniforms.transmissionMap.value = material.transmissionMap; + refreshTransformUniform(material.transmissionMap, uniforms.transmissionMapTransform); + } + uniforms.thickness.value = material.thickness; + if (material.thicknessMap) { + uniforms.thicknessMap.value = material.thicknessMap; + refreshTransformUniform(material.thicknessMap, uniforms.thicknessMapTransform); + } + uniforms.attenuationDistance.value = material.attenuationDistance; + uniforms.attenuationColor.value.copy(material.attenuationColor); + } + if (material.anisotropy > 0) { + uniforms.anisotropyVector.value.set(material.anisotropy * Math.cos(material.anisotropyRotation), material.anisotropy * Math.sin(material.anisotropyRotation)); + if (material.anisotropyMap) { + uniforms.anisotropyMap.value = material.anisotropyMap; + refreshTransformUniform(material.anisotropyMap, uniforms.anisotropyMapTransform); + } + } + uniforms.specularIntensity.value = material.specularIntensity; + uniforms.specularColor.value.copy(material.specularColor); + if (material.specularColorMap) { + uniforms.specularColorMap.value = material.specularColorMap; + refreshTransformUniform(material.specularColorMap, uniforms.specularColorMapTransform); + } + if (material.specularIntensityMap) { + uniforms.specularIntensityMap.value = material.specularIntensityMap; + refreshTransformUniform(material.specularIntensityMap, uniforms.specularIntensityMapTransform); + } + } + function refreshUniformsMatcap(uniforms, material) { + if (material.matcap) { + uniforms.matcap.value = material.matcap; + } + } + function refreshUniformsDistance(uniforms, material) { + const light = properties.get(material).light; + uniforms.referencePosition.value.setFromMatrixPosition(light.matrixWorld); + uniforms.nearDistance.value = light.shadow.camera.near; + uniforms.farDistance.value = light.shadow.camera.far; + } + return { + refreshFogUniforms, + refreshMaterialUniforms + }; +} +function WebGLUniformsGroups(gl, info, capabilities, state) { + let buffers = {}; + let updateList = {}; + let allocatedBindingPoints = []; + const maxBindingPoints = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS); + function bind(uniformsGroup, program) { + const webglProgram = program.program; + state.uniformBlockBinding(uniformsGroup, webglProgram); + } + function update(uniformsGroup, program) { + let buffer = buffers[uniformsGroup.id]; + if (buffer === undefined) { + prepareUniformsGroup(uniformsGroup); + buffer = createBuffer(uniformsGroup); + buffers[uniformsGroup.id] = buffer; + uniformsGroup.addEventListener("dispose", onUniformsGroupsDispose); + } + const webglProgram = program.program; + state.updateUBOMapping(uniformsGroup, webglProgram); + const frame = info.render.frame; + if (updateList[uniformsGroup.id] !== frame) { + updateBufferData(uniformsGroup); + updateList[uniformsGroup.id] = frame; + } + } + function createBuffer(uniformsGroup) { + const bindingPointIndex = allocateBindingPointIndex(); + uniformsGroup.__bindingPointIndex = bindingPointIndex; + const buffer = gl.createBuffer(); + const size = uniformsGroup.__size; + const usage = uniformsGroup.usage; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + gl.bufferData(gl.UNIFORM_BUFFER, size, usage); + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + gl.bindBufferBase(gl.UNIFORM_BUFFER, bindingPointIndex, buffer); + return buffer; + } + function allocateBindingPointIndex() { + for (let i = 0;i < maxBindingPoints; i++) { + if (allocatedBindingPoints.indexOf(i) === -1) { + allocatedBindingPoints.push(i); + return i; + } + } + console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."); + return 0; + } + function updateBufferData(uniformsGroup) { + const buffer = buffers[uniformsGroup.id]; + const uniforms = uniformsGroup.uniforms; + const cache = uniformsGroup.__cache; + gl.bindBuffer(gl.UNIFORM_BUFFER, buffer); + for (let i = 0, il = uniforms.length;i < il; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j = 0, jl = uniformArray.length;j < jl; j++) { + const uniform = uniformArray[j]; + if (hasUniformChanged(uniform, i, j, cache) === true) { + const offset = uniform.__offset; + const values2 = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + let arrayOffset = 0; + for (let k = 0;k < values2.length; k++) { + const value2 = values2[k]; + const info2 = getUniformSize(value2); + if (typeof value2 === "number" || typeof value2 === "boolean") { + uniform.__data[0] = value2; + gl.bufferSubData(gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data); + } else if (value2.isMatrix3) { + uniform.__data[0] = value2.elements[0]; + uniform.__data[1] = value2.elements[1]; + uniform.__data[2] = value2.elements[2]; + uniform.__data[3] = 0; + uniform.__data[4] = value2.elements[3]; + uniform.__data[5] = value2.elements[4]; + uniform.__data[6] = value2.elements[5]; + uniform.__data[7] = 0; + uniform.__data[8] = value2.elements[6]; + uniform.__data[9] = value2.elements[7]; + uniform.__data[10] = value2.elements[8]; + uniform.__data[11] = 0; + } else { + value2.toArray(uniform.__data, arrayOffset); + arrayOffset += info2.storage / Float32Array.BYTES_PER_ELEMENT; + } + } + gl.bufferSubData(gl.UNIFORM_BUFFER, offset, uniform.__data); + } + } + } + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + } + function hasUniformChanged(uniform, index2, indexArray, cache) { + const value2 = uniform.value; + const indexString = index2 + "_" + indexArray; + if (cache[indexString] === undefined) { + if (typeof value2 === "number" || typeof value2 === "boolean") { + cache[indexString] = value2; + } else { + cache[indexString] = value2.clone(); + } + return true; + } else { + const cachedObject = cache[indexString]; + if (typeof value2 === "number" || typeof value2 === "boolean") { + if (cachedObject !== value2) { + cache[indexString] = value2; + return true; + } + } else { + if (cachedObject.equals(value2) === false) { + cachedObject.copy(value2); + return true; + } + } + } + return false; + } + function prepareUniformsGroup(uniformsGroup) { + const uniforms = uniformsGroup.uniforms; + let offset = 0; + const chunkSize = 16; + for (let i = 0, l = uniforms.length;i < l; i++) { + const uniformArray = Array.isArray(uniforms[i]) ? uniforms[i] : [uniforms[i]]; + for (let j = 0, jl = uniformArray.length;j < jl; j++) { + const uniform = uniformArray[j]; + const values2 = Array.isArray(uniform.value) ? uniform.value : [uniform.value]; + for (let k = 0, kl = values2.length;k < kl; k++) { + const value2 = values2[k]; + const info2 = getUniformSize(value2); + const chunkOffset2 = offset % chunkSize; + const chunkPadding = chunkOffset2 % info2.boundary; + const chunkStart = chunkOffset2 + chunkPadding; + offset += chunkPadding; + if (chunkStart !== 0 && chunkSize - chunkStart < info2.storage) { + offset += chunkSize - chunkStart; + } + uniform.__data = new Float32Array(info2.storage / Float32Array.BYTES_PER_ELEMENT); + uniform.__offset = offset; + offset += info2.storage; + } + } + } + const chunkOffset = offset % chunkSize; + if (chunkOffset > 0) + offset += chunkSize - chunkOffset; + uniformsGroup.__size = offset; + uniformsGroup.__cache = {}; + return this; + } + function getUniformSize(value2) { + const info2 = { + boundary: 0, + storage: 0 + }; + if (typeof value2 === "number" || typeof value2 === "boolean") { + info2.boundary = 4; + info2.storage = 4; + } else if (value2.isVector2) { + info2.boundary = 8; + info2.storage = 8; + } else if (value2.isVector3 || value2.isColor) { + info2.boundary = 16; + info2.storage = 12; + } else if (value2.isVector4) { + info2.boundary = 16; + info2.storage = 16; + } else if (value2.isMatrix3) { + info2.boundary = 48; + info2.storage = 48; + } else if (value2.isMatrix4) { + info2.boundary = 64; + info2.storage = 64; + } else if (value2.isTexture) { + console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."); + } else { + console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", value2); + } + return info2; + } + function onUniformsGroupsDispose(event) { + const uniformsGroup = event.target; + uniformsGroup.removeEventListener("dispose", onUniformsGroupsDispose); + const index2 = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex); + allocatedBindingPoints.splice(index2, 1); + gl.deleteBuffer(buffers[uniformsGroup.id]); + delete buffers[uniformsGroup.id]; + delete updateList[uniformsGroup.id]; + } + function dispose() { + for (const id in buffers) { + gl.deleteBuffer(buffers[id]); + } + allocatedBindingPoints = []; + buffers = {}; + updateList = {}; + } + return { + bind, + update, + dispose + }; +} + +class WebGLRenderer { + constructor(parameters = {}) { + const { + canvas = createCanvasElement(), + context = null, + depth = true, + stencil = false, + alpha = false, + antialias = false, + premultipliedAlpha = true, + preserveDrawingBuffer = false, + powerPreference = "default", + failIfMajorPerformanceCaveat = false, + reverseDepthBuffer = false + } = parameters; + this.isWebGLRenderer = true; + let _alpha; + if (context !== null) { + if (typeof WebGLRenderingContext !== "undefined" && context instanceof WebGLRenderingContext) { + throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163."); + } + _alpha = context.getContextAttributes().alpha; + } else { + _alpha = alpha; + } + const uintClearColor = new Uint32Array(4); + const intClearColor = new Int32Array(4); + let currentRenderList = null; + let currentRenderState = null; + const renderListStack = []; + const renderStateStack = []; + this.domElement = canvas; + this.debug = { + checkShaderErrors: true, + onShaderError: null + }; + this.autoClear = true; + this.autoClearColor = true; + this.autoClearDepth = true; + this.autoClearStencil = true; + this.sortObjects = true; + this.clippingPlanes = []; + this.localClippingEnabled = false; + this._outputColorSpace = SRGBColorSpace; + this.toneMapping = NoToneMapping; + this.toneMappingExposure = 1; + const _this = this; + let _isContextLost = false; + let _currentActiveCubeFace = 0; + let _currentActiveMipmapLevel = 0; + let _currentRenderTarget = null; + let _currentMaterialId = -1; + let _currentCamera = null; + const _currentViewport = new Vector4; + const _currentScissor = new Vector4; + let _currentScissorTest = null; + const _currentClearColor = new Color(0); + let _currentClearAlpha = 0; + let _width = canvas.width; + let _height = canvas.height; + let _pixelRatio = 1; + let _opaqueSort = null; + let _transparentSort = null; + const _viewport = new Vector4(0, 0, _width, _height); + const _scissor = new Vector4(0, 0, _width, _height); + let _scissorTest = false; + const _frustum2 = new Frustum; + let _clippingEnabled = false; + let _localClippingEnabled = false; + this.transmissionResolutionScale = 1; + const _currentProjectionMatrix = new Matrix4; + const _projScreenMatrix2 = new Matrix4; + const _vector32 = new Vector3; + const _vector4 = new Vector4; + const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; + let _renderBackground = false; + function getTargetPixelRatio() { + return _currentRenderTarget === null ? _pixelRatio : 1; + } + let _gl = context; + function getContext(contextName, contextAttributes) { + return canvas.getContext(contextName, contextAttributes); + } + try { + const contextAttributes = { + alpha: true, + depth, + stencil, + antialias, + premultipliedAlpha, + preserveDrawingBuffer, + powerPreference, + failIfMajorPerformanceCaveat + }; + if ("setAttribute" in canvas) + canvas.setAttribute("data-engine", `three.js r${REVISION}`); + canvas.addEventListener("webglcontextlost", onContextLost, false); + canvas.addEventListener("webglcontextrestored", onContextRestore, false); + canvas.addEventListener("webglcontextcreationerror", onContextCreationError, false); + if (_gl === null) { + const contextName = "webgl2"; + _gl = getContext(contextName, contextAttributes); + if (_gl === null) { + if (getContext(contextName)) { + throw new Error("Error creating WebGL context with your selected attributes."); + } else { + throw new Error("Error creating WebGL context."); + } + } + } + } catch (error) { + console.error("THREE.WebGLRenderer: " + error.message); + throw error; + } + let extensions, capabilities, state, info; + let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; + let programCache, materials, renderLists, renderStates, clipping, shadowMap; + let background, morphtargets, bufferRenderer, indexedBufferRenderer; + let utils, bindingStates, uniformsGroups; + function initGLContext() { + extensions = new WebGLExtensions(_gl); + extensions.init(); + utils = new WebGLUtils(_gl, extensions); + capabilities = new WebGLCapabilities(_gl, extensions, parameters, utils); + state = new WebGLState(_gl, extensions); + if (capabilities.reverseDepthBuffer && reverseDepthBuffer) { + state.buffers.depth.setReversed(true); + } + info = new WebGLInfo(_gl); + properties = new WebGLProperties; + textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info); + cubemaps = new WebGLCubeMaps(_this); + cubeuvmaps = new WebGLCubeUVMaps(_this); + attributes = new WebGLAttributes(_gl); + bindingStates = new WebGLBindingStates(_gl, attributes); + geometries = new WebGLGeometries(_gl, attributes, info, bindingStates); + objects = new WebGLObjects(_gl, geometries, attributes, info); + morphtargets = new WebGLMorphtargets(_gl, capabilities, textures); + clipping = new WebGLClipping(properties); + programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping); + materials = new WebGLMaterials(_this, properties); + renderLists = new WebGLRenderLists; + renderStates = new WebGLRenderStates(extensions); + background = new WebGLBackground(_this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha); + shadowMap = new WebGLShadowMap(_this, objects, capabilities); + uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state); + bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info); + indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info); + info.programs = programCache.programs; + _this.capabilities = capabilities; + _this.extensions = extensions; + _this.properties = properties; + _this.renderLists = renderLists; + _this.shadowMap = shadowMap; + _this.state = state; + _this.info = info; + } + initGLContext(); + const xr = new WebXRManager(_this, _gl); + this.xr = xr; + this.getContext = function() { + return _gl; + }; + this.getContextAttributes = function() { + return _gl.getContextAttributes(); + }; + this.forceContextLoss = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) + extension.loseContext(); + }; + this.forceContextRestore = function() { + const extension = extensions.get("WEBGL_lose_context"); + if (extension) + extension.restoreContext(); + }; + this.getPixelRatio = function() { + return _pixelRatio; + }; + this.setPixelRatio = function(value2) { + if (value2 === undefined) + return; + _pixelRatio = value2; + this.setSize(_width, _height, false); + }; + this.getSize = function(target) { + return target.set(_width, _height); + }; + this.setSize = function(width2, height2, updateStyle = true) { + if (xr.isPresenting) { + console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."); + return; + } + _width = width2; + _height = height2; + canvas.width = Math.floor(width2 * _pixelRatio); + canvas.height = Math.floor(height2 * _pixelRatio); + if (updateStyle === true) { + canvas.style.width = width2 + "px"; + canvas.style.height = height2 + "px"; + } + this.setViewport(0, 0, width2, height2); + }; + this.getDrawingBufferSize = function(target) { + return target.set(_width * _pixelRatio, _height * _pixelRatio).floor(); + }; + this.setDrawingBufferSize = function(width2, height2, pixelRatio) { + _width = width2; + _height = height2; + _pixelRatio = pixelRatio; + canvas.width = Math.floor(width2 * pixelRatio); + canvas.height = Math.floor(height2 * pixelRatio); + this.setViewport(0, 0, width2, height2); + }; + this.getCurrentViewport = function(target) { + return target.copy(_currentViewport); + }; + this.getViewport = function(target) { + return target.copy(_viewport); + }; + this.setViewport = function(x, y, width2, height2) { + if (x.isVector4) { + _viewport.set(x.x, x.y, x.z, x.w); + } else { + _viewport.set(x, y, width2, height2); + } + state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).round()); + }; + this.getScissor = function(target) { + return target.copy(_scissor); + }; + this.setScissor = function(x, y, width2, height2) { + if (x.isVector4) { + _scissor.set(x.x, x.y, x.z, x.w); + } else { + _scissor.set(x, y, width2, height2); + } + state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).round()); + }; + this.getScissorTest = function() { + return _scissorTest; + }; + this.setScissorTest = function(boolean) { + state.setScissorTest(_scissorTest = boolean); + }; + this.setOpaqueSort = function(method) { + _opaqueSort = method; + }; + this.setTransparentSort = function(method) { + _transparentSort = method; + }; + this.getClearColor = function(target) { + return target.copy(background.getClearColor()); + }; + this.setClearColor = function() { + background.setClearColor.apply(background, arguments); + }; + this.getClearAlpha = function() { + return background.getClearAlpha(); + }; + this.setClearAlpha = function() { + background.setClearAlpha.apply(background, arguments); + }; + this.clear = function(color = true, depth2 = true, stencil2 = true) { + let bits = 0; + if (color) { + let isIntegerFormat = false; + if (_currentRenderTarget !== null) { + const targetFormat = _currentRenderTarget.texture.format; + isIntegerFormat = targetFormat === RGBAIntegerFormat || targetFormat === RGIntegerFormat || targetFormat === RedIntegerFormat; + } + if (isIntegerFormat) { + const targetType = _currentRenderTarget.texture.type; + const isUnsignedType = targetType === UnsignedByteType || targetType === UnsignedIntType || targetType === UnsignedShortType || targetType === UnsignedInt248Type || targetType === UnsignedShort4444Type || targetType === UnsignedShort5551Type; + const clearColor = background.getClearColor(); + const a = background.getClearAlpha(); + const r = clearColor.r; + const g = clearColor.g; + const b = clearColor.b; + if (isUnsignedType) { + uintClearColor[0] = r; + uintClearColor[1] = g; + uintClearColor[2] = b; + uintClearColor[3] = a; + _gl.clearBufferuiv(_gl.COLOR, 0, uintClearColor); + } else { + intClearColor[0] = r; + intClearColor[1] = g; + intClearColor[2] = b; + intClearColor[3] = a; + _gl.clearBufferiv(_gl.COLOR, 0, intClearColor); + } + } else { + bits |= _gl.COLOR_BUFFER_BIT; + } + } + if (depth2) { + bits |= _gl.DEPTH_BUFFER_BIT; + } + if (stencil2) { + bits |= _gl.STENCIL_BUFFER_BIT; + this.state.buffers.stencil.setMask(4294967295); + } + _gl.clear(bits); + }; + this.clearColor = function() { + this.clear(true, false, false); + }; + this.clearDepth = function() { + this.clear(false, true, false); + }; + this.clearStencil = function() { + this.clear(false, false, true); + }; + this.dispose = function() { + canvas.removeEventListener("webglcontextlost", onContextLost, false); + canvas.removeEventListener("webglcontextrestored", onContextRestore, false); + canvas.removeEventListener("webglcontextcreationerror", onContextCreationError, false); + background.dispose(); + renderLists.dispose(); + renderStates.dispose(); + properties.dispose(); + cubemaps.dispose(); + cubeuvmaps.dispose(); + objects.dispose(); + bindingStates.dispose(); + uniformsGroups.dispose(); + programCache.dispose(); + xr.dispose(); + xr.removeEventListener("sessionstart", onXRSessionStart); + xr.removeEventListener("sessionend", onXRSessionEnd); + animation.stop(); + }; + function onContextLost(event) { + event.preventDefault(); + console.log("THREE.WebGLRenderer: Context Lost."); + _isContextLost = true; + } + function onContextRestore() { + console.log("THREE.WebGLRenderer: Context Restored."); + _isContextLost = false; + const infoAutoReset = info.autoReset; + const shadowMapEnabled = shadowMap.enabled; + const shadowMapAutoUpdate = shadowMap.autoUpdate; + const shadowMapNeedsUpdate = shadowMap.needsUpdate; + const shadowMapType = shadowMap.type; + initGLContext(); + info.autoReset = infoAutoReset; + shadowMap.enabled = shadowMapEnabled; + shadowMap.autoUpdate = shadowMapAutoUpdate; + shadowMap.needsUpdate = shadowMapNeedsUpdate; + shadowMap.type = shadowMapType; + } + function onContextCreationError(event) { + console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", event.statusMessage); + } + function onMaterialDispose(event) { + const material = event.target; + material.removeEventListener("dispose", onMaterialDispose); + deallocateMaterial(material); + } + function deallocateMaterial(material) { + releaseMaterialProgramReferences(material); + properties.remove(material); + } + function releaseMaterialProgramReferences(material) { + const programs = properties.get(material).programs; + if (programs !== undefined) { + programs.forEach(function(program) { + programCache.releaseProgram(program); + }); + if (material.isShaderMaterial) { + programCache.releaseShaderCache(material); + } + } + } + this.renderBufferDirect = function(camera, scene, geometry, material, object, group) { + if (scene === null) + scene = _emptyScene; + const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0; + const program = setProgram(camera, scene, geometry, material, object); + state.setMaterial(material, frontFaceCW); + let index2 = geometry.index; + let rangeFactor = 1; + if (material.wireframe === true) { + index2 = geometries.getWireframeAttribute(geometry); + if (index2 === undefined) + return; + rangeFactor = 2; + } + const drawRange = geometry.drawRange; + const position2 = geometry.attributes.position; + let drawStart = drawRange.start * rangeFactor; + let drawEnd = (drawRange.start + drawRange.count) * rangeFactor; + if (group !== null) { + drawStart = Math.max(drawStart, group.start * rangeFactor); + drawEnd = Math.min(drawEnd, (group.start + group.count) * rangeFactor); + } + if (index2 !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, index2.count); + } else if (position2 !== undefined && position2 !== null) { + drawStart = Math.max(drawStart, 0); + drawEnd = Math.min(drawEnd, position2.count); + } + const drawCount = drawEnd - drawStart; + if (drawCount < 0 || drawCount === Infinity) + return; + bindingStates.setup(object, material, program, geometry, index2); + let attribute; + let renderer2 = bufferRenderer; + if (index2 !== null) { + attribute = attributes.get(index2); + renderer2 = indexedBufferRenderer; + renderer2.setIndex(attribute); + } + if (object.isMesh) { + if (material.wireframe === true) { + state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio()); + renderer2.setMode(_gl.LINES); + } else { + renderer2.setMode(_gl.TRIANGLES); + } + } else if (object.isLine) { + let lineWidth = material.linewidth; + if (lineWidth === undefined) + lineWidth = 1; + state.setLineWidth(lineWidth * getTargetPixelRatio()); + if (object.isLineSegments) { + renderer2.setMode(_gl.LINES); + } else if (object.isLineLoop) { + renderer2.setMode(_gl.LINE_LOOP); + } else { + renderer2.setMode(_gl.LINE_STRIP); + } + } else if (object.isPoints) { + renderer2.setMode(_gl.POINTS); + } else if (object.isSprite) { + renderer2.setMode(_gl.TRIANGLES); + } + if (object.isBatchedMesh) { + if (object._multiDrawInstances !== null) { + renderer2.renderMultiDrawInstances(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances); + } else { + if (!extensions.get("WEBGL_multi_draw")) { + const starts = object._multiDrawStarts; + const counts = object._multiDrawCounts; + const drawCount2 = object._multiDrawCount; + const bytesPerElement = index2 ? attributes.get(index2).bytesPerElement : 1; + const uniforms = properties.get(material).currentProgram.getUniforms(); + for (let i = 0;i < drawCount2; i++) { + uniforms.setValue(_gl, "_gl_DrawID", i); + renderer2.render(starts[i] / bytesPerElement, counts[i]); + } + } else { + renderer2.renderMultiDraw(object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount); + } + } + } else if (object.isInstancedMesh) { + renderer2.renderInstances(drawStart, drawCount, object.count); + } else if (geometry.isInstancedBufferGeometry) { + const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity; + const instanceCount = Math.min(geometry.instanceCount, maxInstanceCount); + renderer2.renderInstances(drawStart, drawCount, instanceCount); + } else { + renderer2.render(drawStart, drawCount); + } + }; + function prepareMaterial(material, scene, object) { + if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) { + material.side = BackSide; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = FrontSide; + material.needsUpdate = true; + getProgram(material, scene, object); + material.side = DoubleSide; + } else { + getProgram(material, scene, object); + } + } + this.compile = function(scene, camera, targetScene = null) { + if (targetScene === null) + targetScene = scene; + currentRenderState = renderStates.get(targetScene); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + targetScene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + if (scene !== targetScene) { + scene.traverseVisible(function(object) { + if (object.isLight && object.layers.test(camera.layers)) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } + }); + } + currentRenderState.setupLights(); + const materials2 = new Set; + scene.traverse(function(object) { + if (!(object.isMesh || object.isPoints || object.isLine || object.isSprite)) { + return; + } + const material = object.material; + if (material) { + if (Array.isArray(material)) { + for (let i = 0;i < material.length; i++) { + const material2 = material[i]; + prepareMaterial(material2, targetScene, object); + materials2.add(material2); + } + } else { + prepareMaterial(material, targetScene, object); + materials2.add(material); + } + } + }); + renderStateStack.pop(); + currentRenderState = null; + return materials2; + }; + this.compileAsync = function(scene, camera, targetScene = null) { + const materials2 = this.compile(scene, camera, targetScene); + return new Promise((resolve) => { + function checkMaterialsReady() { + materials2.forEach(function(material) { + const materialProperties = properties.get(material); + const program = materialProperties.currentProgram; + if (program.isReady()) { + materials2.delete(material); + } + }); + if (materials2.size === 0) { + resolve(scene); + return; + } + setTimeout(checkMaterialsReady, 10); + } + if (extensions.get("KHR_parallel_shader_compile") !== null) { + checkMaterialsReady(); + } else { + setTimeout(checkMaterialsReady, 10); + } + }); + }; + let onAnimationFrameCallback = null; + function onAnimationFrame(time2) { + if (onAnimationFrameCallback) + onAnimationFrameCallback(time2); + } + function onXRSessionStart() { + animation.stop(); + } + function onXRSessionEnd() { + animation.start(); + } + const animation = new WebGLAnimation; + animation.setAnimationLoop(onAnimationFrame); + if (typeof self !== "undefined") + animation.setContext(self); + this.setAnimationLoop = function(callback) { + onAnimationFrameCallback = callback; + xr.setAnimationLoop(callback); + callback === null ? animation.stop() : animation.start(); + }; + xr.addEventListener("sessionstart", onXRSessionStart); + xr.addEventListener("sessionend", onXRSessionEnd); + this.render = function(scene, camera) { + if (camera !== undefined && camera.isCamera !== true) { + console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera."); + return; + } + if (_isContextLost === true) + return; + if (scene.matrixWorldAutoUpdate === true) + scene.updateMatrixWorld(); + if (camera.parent === null && camera.matrixWorldAutoUpdate === true) + camera.updateMatrixWorld(); + if (xr.enabled === true && xr.isPresenting === true) { + if (xr.cameraAutoUpdate === true) + xr.updateCamera(camera); + camera = xr.getCamera(); + } + if (scene.isScene === true) + scene.onBeforeRender(_this, scene, camera, _currentRenderTarget); + currentRenderState = renderStates.get(scene, renderStateStack.length); + currentRenderState.init(camera); + renderStateStack.push(currentRenderState); + _projScreenMatrix2.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); + _frustum2.setFromProjectionMatrix(_projScreenMatrix2); + _localClippingEnabled = this.localClippingEnabled; + _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled); + currentRenderList = renderLists.get(scene, renderListStack.length); + currentRenderList.init(); + renderListStack.push(currentRenderList); + if (xr.enabled === true && xr.isPresenting === true) { + const depthSensingMesh = _this.xr.getDepthSensingMesh(); + if (depthSensingMesh !== null) { + projectObject(depthSensingMesh, camera, -Infinity, _this.sortObjects); + } + } + projectObject(scene, camera, 0, _this.sortObjects); + currentRenderList.finish(); + if (_this.sortObjects === true) { + currentRenderList.sort(_opaqueSort, _transparentSort); + } + _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false; + if (_renderBackground) { + background.addToRenderList(currentRenderList, scene); + } + this.info.render.frame++; + if (_clippingEnabled === true) + clipping.beginShadows(); + const shadowsArray = currentRenderState.state.shadowsArray; + shadowMap.render(shadowsArray, scene, camera); + if (_clippingEnabled === true) + clipping.endShadows(); + if (this.info.autoReset === true) + this.info.reset(); + const opaqueObjects = currentRenderList.opaque; + const transmissiveObjects = currentRenderList.transmissive; + currentRenderState.setupLights(); + if (camera.isArrayCamera) { + const cameras = camera.cameras; + if (transmissiveObjects.length > 0) { + for (let i = 0, l = cameras.length;i < l; i++) { + const camera2 = cameras[i]; + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera2); + } + } + if (_renderBackground) + background.render(scene); + for (let i = 0, l = cameras.length;i < l; i++) { + const camera2 = cameras[i]; + renderScene(currentRenderList, scene, camera2, camera2.viewport); + } + } else { + if (transmissiveObjects.length > 0) + renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera); + if (_renderBackground) + background.render(scene); + renderScene(currentRenderList, scene, camera); + } + if (_currentRenderTarget !== null && _currentActiveMipmapLevel === 0) { + textures.updateMultisampleRenderTarget(_currentRenderTarget); + textures.updateRenderTargetMipmap(_currentRenderTarget); + } + if (scene.isScene === true) + scene.onAfterRender(_this, scene, camera); + bindingStates.resetDefaultState(); + _currentMaterialId = -1; + _currentCamera = null; + renderStateStack.pop(); + if (renderStateStack.length > 0) { + currentRenderState = renderStateStack[renderStateStack.length - 1]; + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, currentRenderState.state.camera); + } else { + currentRenderState = null; + } + renderListStack.pop(); + if (renderListStack.length > 0) { + currentRenderList = renderListStack[renderListStack.length - 1]; + } else { + currentRenderList = null; + } + }; + function projectObject(object, camera, groupOrder, sortObjects) { + if (object.visible === false) + return; + const visible = object.layers.test(camera.layers); + if (visible) { + if (object.isGroup) { + groupOrder = object.renderOrder; + } else if (object.isLOD) { + if (object.autoUpdate === true) + object.update(camera); + } else if (object.isLight) { + currentRenderState.pushLight(object); + if (object.castShadow) { + currentRenderState.pushShadow(object); + } + } else if (object.isSprite) { + if (!object.frustumCulled || _frustum2.intersectsSprite(object)) { + if (sortObjects) { + _vector4.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix2); + } + const geometry = objects.update(object); + const material = object.material; + if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector4.z, null); + } + } + } else if (object.isMesh || object.isLine || object.isPoints) { + if (!object.frustumCulled || _frustum2.intersectsObject(object)) { + const geometry = objects.update(object); + const material = object.material; + if (sortObjects) { + if (object.boundingSphere !== undefined) { + if (object.boundingSphere === null) + object.computeBoundingSphere(); + _vector4.copy(object.boundingSphere.center); + } else { + if (geometry.boundingSphere === null) + geometry.computeBoundingSphere(); + _vector4.copy(geometry.boundingSphere.center); + } + _vector4.applyMatrix4(object.matrixWorld).applyMatrix4(_projScreenMatrix2); + } + if (Array.isArray(material)) { + const groups = geometry.groups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + const groupMaterial = material[group.materialIndex]; + if (groupMaterial && groupMaterial.visible) { + currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector4.z, group); + } + } + } else if (material.visible) { + currentRenderList.push(object, geometry, material, groupOrder, _vector4.z, null); + } + } + } + } + const children = object.children; + for (let i = 0, l = children.length;i < l; i++) { + projectObject(children[i], camera, groupOrder, sortObjects); + } + } + function renderScene(currentRenderList2, scene, camera, viewport) { + const opaqueObjects = currentRenderList2.opaque; + const transmissiveObjects = currentRenderList2.transmissive; + const transparentObjects = currentRenderList2.transparent; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, camera); + if (viewport) + state.viewport(_currentViewport.copy(viewport)); + if (opaqueObjects.length > 0) + renderObjects(opaqueObjects, scene, camera); + if (transmissiveObjects.length > 0) + renderObjects(transmissiveObjects, scene, camera); + if (transparentObjects.length > 0) + renderObjects(transparentObjects, scene, camera); + state.buffers.depth.setTest(true); + state.buffers.depth.setMask(true); + state.buffers.color.setMask(true); + state.setPolygonOffset(false); + } + function renderTransmissionPass(opaqueObjects, transmissiveObjects, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + if (overrideMaterial !== null) { + return; + } + if (currentRenderState.state.transmissionRenderTarget[camera.id] === undefined) { + currentRenderState.state.transmissionRenderTarget[camera.id] = new WebGLRenderTarget(1, 1, { + generateMipmaps: true, + type: extensions.has("EXT_color_buffer_half_float") || extensions.has("EXT_color_buffer_float") ? HalfFloatType : UnsignedByteType, + minFilter: LinearMipmapLinearFilter, + samples: 4, + stencilBuffer: stencil, + resolveDepthBuffer: false, + resolveStencilBuffer: false, + colorSpace: ColorManagement.workingColorSpace + }); + } + const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[camera.id]; + const activeViewport = camera.viewport || _currentViewport; + transmissionRenderTarget.setSize(activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale); + const currentRenderTarget = _this.getRenderTarget(); + _this.setRenderTarget(transmissionRenderTarget); + _this.getClearColor(_currentClearColor); + _currentClearAlpha = _this.getClearAlpha(); + if (_currentClearAlpha < 1) + _this.setClearColor(16777215, 0.5); + _this.clear(); + if (_renderBackground) + background.render(scene); + const currentToneMapping = _this.toneMapping; + _this.toneMapping = NoToneMapping; + const currentCameraViewport = camera.viewport; + if (camera.viewport !== undefined) + camera.viewport = undefined; + currentRenderState.setupLightsView(camera); + if (_clippingEnabled === true) + clipping.setGlobalState(_this.clippingPlanes, camera); + renderObjects(opaqueObjects, scene, camera); + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + if (extensions.has("WEBGL_multisampled_render_to_texture") === false) { + let renderTargetNeedsUpdate = false; + for (let i = 0, l = transmissiveObjects.length;i < l; i++) { + const renderItem = transmissiveObjects[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = renderItem.material; + const group = renderItem.group; + if (material.side === DoubleSide && object.layers.test(camera.layers)) { + const currentSide = material.side; + material.side = BackSide; + material.needsUpdate = true; + renderObject(object, scene, camera, geometry, material, group); + material.side = currentSide; + material.needsUpdate = true; + renderTargetNeedsUpdate = true; + } + } + if (renderTargetNeedsUpdate === true) { + textures.updateMultisampleRenderTarget(transmissionRenderTarget); + textures.updateRenderTargetMipmap(transmissionRenderTarget); + } + } + _this.setRenderTarget(currentRenderTarget); + _this.setClearColor(_currentClearColor, _currentClearAlpha); + if (currentCameraViewport !== undefined) + camera.viewport = currentCameraViewport; + _this.toneMapping = currentToneMapping; + } + function renderObjects(renderList, scene, camera) { + const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; + for (let i = 0, l = renderList.length;i < l; i++) { + const renderItem = renderList[i]; + const object = renderItem.object; + const geometry = renderItem.geometry; + const material = overrideMaterial === null ? renderItem.material : overrideMaterial; + const group = renderItem.group; + if (object.layers.test(camera.layers)) { + renderObject(object, scene, camera, geometry, material, group); + } + } + } + function renderObject(object, scene, camera, geometry, material, group) { + object.onBeforeRender(_this, scene, camera, geometry, material, group); + object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld); + object.normalMatrix.getNormalMatrix(object.modelViewMatrix); + material.onBeforeRender(_this, scene, camera, geometry, object, group); + if (material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false) { + material.side = BackSide; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = FrontSide; + material.needsUpdate = true; + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + material.side = DoubleSide; + } else { + _this.renderBufferDirect(camera, scene, geometry, material, object, group); + } + object.onAfterRender(_this, scene, camera, geometry, material, group); + } + function getProgram(material, scene, object) { + if (scene.isScene !== true) + scene = _emptyScene; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + const shadowsArray = currentRenderState.state.shadowsArray; + const lightsStateVersion = lights.state.version; + const parameters2 = programCache.getParameters(material, lights.state, shadowsArray, scene, object); + const programCacheKey = programCache.getProgramCacheKey(parameters2); + let programs = materialProperties.programs; + materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; + materialProperties.fog = scene.fog; + materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment); + materialProperties.envMapRotation = materialProperties.environment !== null && material.envMap === null ? scene.environmentRotation : material.envMapRotation; + if (programs === undefined) { + material.addEventListener("dispose", onMaterialDispose); + programs = new Map; + materialProperties.programs = programs; + } + let program = programs.get(programCacheKey); + if (program !== undefined) { + if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) { + updateCommonMaterialProperties(material, parameters2); + return program; + } + } else { + parameters2.uniforms = programCache.getUniforms(material); + material.onBeforeCompile(parameters2, _this); + program = programCache.acquireProgram(parameters2, programCacheKey); + programs.set(programCacheKey, program); + materialProperties.uniforms = parameters2.uniforms; + } + const uniforms = materialProperties.uniforms; + if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) { + uniforms.clippingPlanes = clipping.uniform; + } + updateCommonMaterialProperties(material, parameters2); + materialProperties.needsLights = materialNeedsLights(material); + materialProperties.lightsStateVersion = lightsStateVersion; + if (materialProperties.needsLights) { + uniforms.ambientLightColor.value = lights.state.ambient; + uniforms.lightProbe.value = lights.state.probe; + uniforms.directionalLights.value = lights.state.directional; + uniforms.directionalLightShadows.value = lights.state.directionalShadow; + uniforms.spotLights.value = lights.state.spot; + uniforms.spotLightShadows.value = lights.state.spotShadow; + uniforms.rectAreaLights.value = lights.state.rectArea; + uniforms.ltc_1.value = lights.state.rectAreaLTC1; + uniforms.ltc_2.value = lights.state.rectAreaLTC2; + uniforms.pointLights.value = lights.state.point; + uniforms.pointLightShadows.value = lights.state.pointShadow; + uniforms.hemisphereLights.value = lights.state.hemi; + uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; + uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; + uniforms.spotShadowMap.value = lights.state.spotShadowMap; + uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; + uniforms.spotLightMap.value = lights.state.spotLightMap; + uniforms.pointShadowMap.value = lights.state.pointShadowMap; + uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; + } + materialProperties.currentProgram = program; + materialProperties.uniformsList = null; + return program; + } + function getUniformList(materialProperties) { + if (materialProperties.uniformsList === null) { + const progUniforms = materialProperties.currentProgram.getUniforms(); + materialProperties.uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, materialProperties.uniforms); + } + return materialProperties.uniformsList; + } + function updateCommonMaterialProperties(material, parameters2) { + const materialProperties = properties.get(material); + materialProperties.outputColorSpace = parameters2.outputColorSpace; + materialProperties.batching = parameters2.batching; + materialProperties.batchingColor = parameters2.batchingColor; + materialProperties.instancing = parameters2.instancing; + materialProperties.instancingColor = parameters2.instancingColor; + materialProperties.instancingMorph = parameters2.instancingMorph; + materialProperties.skinning = parameters2.skinning; + materialProperties.morphTargets = parameters2.morphTargets; + materialProperties.morphNormals = parameters2.morphNormals; + materialProperties.morphColors = parameters2.morphColors; + materialProperties.morphTargetsCount = parameters2.morphTargetsCount; + materialProperties.numClippingPlanes = parameters2.numClippingPlanes; + materialProperties.numIntersection = parameters2.numClipIntersection; + materialProperties.vertexAlphas = parameters2.vertexAlphas; + materialProperties.vertexTangents = parameters2.vertexTangents; + materialProperties.toneMapping = parameters2.toneMapping; + } + function setProgram(camera, scene, geometry, material, object) { + if (scene.isScene !== true) + scene = _emptyScene; + textures.resetTextureUnits(); + const fog = scene.fog; + const environment = material.isMeshStandardMaterial ? scene.environment : null; + const colorSpace = _currentRenderTarget === null ? _this.outputColorSpace : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace; + const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); + const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4; + const vertexTangents = !!geometry.attributes.tangent && (!!material.normalMap || material.anisotropy > 0); + const morphTargets = !!geometry.morphAttributes.position; + const morphNormals = !!geometry.morphAttributes.normal; + const morphColors = !!geometry.morphAttributes.color; + let toneMapping = NoToneMapping; + if (material.toneMapped) { + if (_currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true) { + toneMapping = _this.toneMapping; + } + } + const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; + const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0; + const materialProperties = properties.get(material); + const lights = currentRenderState.state.lights; + if (_clippingEnabled === true) { + if (_localClippingEnabled === true || camera !== _currentCamera) { + const useCache = camera === _currentCamera && material.id === _currentMaterialId; + clipping.setState(material, camera, useCache); + } + } + let needsProgramChange = false; + if (material.version === materialProperties.__version) { + if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) { + needsProgramChange = true; + } else if (materialProperties.outputColorSpace !== colorSpace) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batching === false) { + needsProgramChange = true; + } else if (!object.isBatchedMesh && materialProperties.batching === true) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null) { + needsProgramChange = true; + } else if (object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancing === false) { + needsProgramChange = true; + } else if (!object.isInstancedMesh && materialProperties.instancing === true) { + needsProgramChange = true; + } else if (object.isSkinnedMesh && materialProperties.skinning === false) { + needsProgramChange = true; + } else if (!object.isSkinnedMesh && materialProperties.skinning === true) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null) { + needsProgramChange = true; + } else if (object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null) { + needsProgramChange = true; + } else if (materialProperties.envMap !== envMap) { + needsProgramChange = true; + } else if (material.fog === true && materialProperties.fog !== fog) { + needsProgramChange = true; + } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) { + needsProgramChange = true; + } else if (materialProperties.vertexAlphas !== vertexAlphas) { + needsProgramChange = true; + } else if (materialProperties.vertexTangents !== vertexTangents) { + needsProgramChange = true; + } else if (materialProperties.morphTargets !== morphTargets) { + needsProgramChange = true; + } else if (materialProperties.morphNormals !== morphNormals) { + needsProgramChange = true; + } else if (materialProperties.morphColors !== morphColors) { + needsProgramChange = true; + } else if (materialProperties.toneMapping !== toneMapping) { + needsProgramChange = true; + } else if (materialProperties.morphTargetsCount !== morphTargetsCount) { + needsProgramChange = true; + } + } else { + needsProgramChange = true; + materialProperties.__version = material.version; + } + let program = materialProperties.currentProgram; + if (needsProgramChange === true) { + program = getProgram(material, scene, object); + } + let refreshProgram = false; + let refreshMaterial = false; + let refreshLights = false; + const p_uniforms = program.getUniforms(), m_uniforms = materialProperties.uniforms; + if (state.useProgram(program.program)) { + refreshProgram = true; + refreshMaterial = true; + refreshLights = true; + } + if (material.id !== _currentMaterialId) { + _currentMaterialId = material.id; + refreshMaterial = true; + } + if (refreshProgram || _currentCamera !== camera) { + const reverseDepthBuffer2 = state.buffers.depth.getReversed(); + if (reverseDepthBuffer2) { + _currentProjectionMatrix.copy(camera.projectionMatrix); + toNormalizedProjectionMatrix(_currentProjectionMatrix); + toReversedProjectionMatrix(_currentProjectionMatrix); + p_uniforms.setValue(_gl, "projectionMatrix", _currentProjectionMatrix); + } else { + p_uniforms.setValue(_gl, "projectionMatrix", camera.projectionMatrix); + } + p_uniforms.setValue(_gl, "viewMatrix", camera.matrixWorldInverse); + const uCamPos = p_uniforms.map.cameraPosition; + if (uCamPos !== undefined) { + uCamPos.setValue(_gl, _vector32.setFromMatrixPosition(camera.matrixWorld)); + } + if (capabilities.logarithmicDepthBuffer) { + p_uniforms.setValue(_gl, "logDepthBufFC", 2 / (Math.log(camera.far + 1) / Math.LN2)); + } + if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) { + p_uniforms.setValue(_gl, "isOrthographic", camera.isOrthographicCamera === true); + } + if (_currentCamera !== camera) { + _currentCamera = camera; + refreshMaterial = true; + refreshLights = true; + } + } + if (object.isSkinnedMesh) { + p_uniforms.setOptional(_gl, object, "bindMatrix"); + p_uniforms.setOptional(_gl, object, "bindMatrixInverse"); + const skeleton = object.skeleton; + if (skeleton) { + if (skeleton.boneTexture === null) + skeleton.computeBoneTexture(); + p_uniforms.setValue(_gl, "boneTexture", skeleton.boneTexture, textures); + } + } + if (object.isBatchedMesh) { + p_uniforms.setOptional(_gl, object, "batchingTexture"); + p_uniforms.setValue(_gl, "batchingTexture", object._matricesTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingIdTexture"); + p_uniforms.setValue(_gl, "batchingIdTexture", object._indirectTexture, textures); + p_uniforms.setOptional(_gl, object, "batchingColorTexture"); + if (object._colorsTexture !== null) { + p_uniforms.setValue(_gl, "batchingColorTexture", object._colorsTexture, textures); + } + } + const morphAttributes = geometry.morphAttributes; + if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined) { + morphtargets.update(object, geometry, program); + } + if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) { + materialProperties.receiveShadow = object.receiveShadow; + p_uniforms.setValue(_gl, "receiveShadow", object.receiveShadow); + } + if (material.isMeshGouraudMaterial && material.envMap !== null) { + m_uniforms.envMap.value = envMap; + m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; + } + if (material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null) { + m_uniforms.envMapIntensity.value = scene.environmentIntensity; + } + if (refreshMaterial) { + p_uniforms.setValue(_gl, "toneMappingExposure", _this.toneMappingExposure); + if (materialProperties.needsLights) { + markUniformsLightsNeedsUpdate(m_uniforms, refreshLights); + } + if (fog && material.fog === true) { + materials.refreshFogUniforms(m_uniforms, fog); + } + materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[camera.id]); + WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + } + if (material.isShaderMaterial && material.uniformsNeedUpdate === true) { + WebGLUniforms.upload(_gl, getUniformList(materialProperties), m_uniforms, textures); + material.uniformsNeedUpdate = false; + } + if (material.isSpriteMaterial) { + p_uniforms.setValue(_gl, "center", object.center); + } + p_uniforms.setValue(_gl, "modelViewMatrix", object.modelViewMatrix); + p_uniforms.setValue(_gl, "normalMatrix", object.normalMatrix); + p_uniforms.setValue(_gl, "modelMatrix", object.matrixWorld); + if (material.isShaderMaterial || material.isRawShaderMaterial) { + const groups = material.uniformsGroups; + for (let i = 0, l = groups.length;i < l; i++) { + const group = groups[i]; + uniformsGroups.update(group, program); + uniformsGroups.bind(group, program); + } + } + return program; + } + function markUniformsLightsNeedsUpdate(uniforms, value2) { + uniforms.ambientLightColor.needsUpdate = value2; + uniforms.lightProbe.needsUpdate = value2; + uniforms.directionalLights.needsUpdate = value2; + uniforms.directionalLightShadows.needsUpdate = value2; + uniforms.pointLights.needsUpdate = value2; + uniforms.pointLightShadows.needsUpdate = value2; + uniforms.spotLights.needsUpdate = value2; + uniforms.spotLightShadows.needsUpdate = value2; + uniforms.rectAreaLights.needsUpdate = value2; + uniforms.hemisphereLights.needsUpdate = value2; + } + function materialNeedsLights(material) { + return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true; + } + this.getActiveCubeFace = function() { + return _currentActiveCubeFace; + }; + this.getActiveMipmapLevel = function() { + return _currentActiveMipmapLevel; + }; + this.getRenderTarget = function() { + return _currentRenderTarget; + }; + this.setRenderTargetTextures = function(renderTarget, colorTexture, depthTexture) { + properties.get(renderTarget.texture).__webglTexture = colorTexture; + properties.get(renderTarget.depthTexture).__webglTexture = depthTexture; + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__hasExternalTextures = true; + renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined; + if (!renderTargetProperties.__autoAllocateDepthBuffer) { + if (extensions.has("WEBGL_multisampled_render_to_texture") === true) { + console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"); + renderTargetProperties.__useRenderToTexture = false; + } + } + }; + this.setRenderTargetFramebuffer = function(renderTarget, defaultFramebuffer) { + const renderTargetProperties = properties.get(renderTarget); + renderTargetProperties.__webglFramebuffer = defaultFramebuffer; + renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined; + }; + const _scratchFrameBuffer = _gl.createFramebuffer(); + this.setRenderTarget = function(renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) { + _currentRenderTarget = renderTarget; + _currentActiveCubeFace = activeCubeFace; + _currentActiveMipmapLevel = activeMipmapLevel; + let useDefaultFramebuffer = true; + let framebuffer = null; + let isCube = false; + let isRenderTarget3D = false; + if (renderTarget) { + const renderTargetProperties = properties.get(renderTarget); + if (renderTargetProperties.__useDefaultFramebuffer !== undefined) { + state.bindFramebuffer(_gl.FRAMEBUFFER, null); + useDefaultFramebuffer = false; + } else if (renderTargetProperties.__webglFramebuffer === undefined) { + textures.setupRenderTarget(renderTarget); + } else if (renderTargetProperties.__hasExternalTextures) { + textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture); + } else if (renderTarget.depthBuffer) { + const depthTexture = renderTarget.depthTexture; + if (renderTargetProperties.__boundDepthTexture !== depthTexture) { + if (depthTexture !== null && properties.has(depthTexture) && (renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height)) { + throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size."); + } + textures.setupDepthRenderbuffer(renderTarget); + } + } + const texture = renderTarget.texture; + if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + isRenderTarget3D = true; + } + const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget) { + if (Array.isArray(__webglFramebuffer[activeCubeFace])) { + framebuffer = __webglFramebuffer[activeCubeFace][activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer[activeCubeFace]; + } + isCube = true; + } else if (renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) { + framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer; + } else { + if (Array.isArray(__webglFramebuffer)) { + framebuffer = __webglFramebuffer[activeMipmapLevel]; + } else { + framebuffer = __webglFramebuffer; + } + } + _currentViewport.copy(renderTarget.viewport); + _currentScissor.copy(renderTarget.scissor); + _currentScissorTest = renderTarget.scissorTest; + } else { + _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor(); + _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(); + _currentScissorTest = _scissorTest; + } + if (activeMipmapLevel !== 0) { + framebuffer = _scratchFrameBuffer; + } + const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + if (framebufferBound && useDefaultFramebuffer) { + state.drawBuffers(renderTarget, framebuffer); + } + state.viewport(_currentViewport); + state.scissor(_currentScissor); + state.setScissorTest(_currentScissorTest); + if (isCube) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel); + } else if (isRenderTarget3D) { + const textureProperties = properties.get(renderTarget.texture); + const layer = activeCubeFace; + _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel, layer); + } else if (renderTarget !== null && activeMipmapLevel !== 0) { + const textureProperties = properties.get(renderTarget.texture); + _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel); + } + _currentMaterialId = -1; + }; + this.readRenderTargetPixels = function(renderTarget, x, y, width2, height2, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + return; + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + try { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); + return; + } + if (!capabilities.textureTypeReadable(textureType)) { + console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); + return; + } + if (x >= 0 && x <= renderTarget.width - width2 && (y >= 0 && y <= renderTarget.height - height2)) { + _gl.readPixels(x, y, width2, height2, utils.convert(textureFormat), utils.convert(textureType), buffer); + } + } finally { + const framebuffer2 = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer2); + } + } + }; + this.readRenderTargetPixelsAsync = async function(renderTarget, x, y, width2, height2, buffer, activeCubeFaceIndex) { + if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); + } + let framebuffer = properties.get(renderTarget).__webglFramebuffer; + if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) { + framebuffer = framebuffer[activeCubeFaceIndex]; + } + if (framebuffer) { + const texture = renderTarget.texture; + const textureFormat = texture.format; + const textureType = texture.type; + if (!capabilities.textureFormatReadable(textureFormat)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format."); + } + if (!capabilities.textureTypeReadable(textureType)) { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type."); + } + if (x >= 0 && x <= renderTarget.width - width2 && (y >= 0 && y <= renderTarget.height - height2)) { + state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); + const glBuffer = _gl.createBuffer(); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.bufferData(_gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ); + _gl.readPixels(x, y, width2, height2, utils.convert(textureFormat), utils.convert(textureType), 0); + const currFramebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; + state.bindFramebuffer(_gl.FRAMEBUFFER, currFramebuffer); + const sync = _gl.fenceSync(_gl.SYNC_GPU_COMMANDS_COMPLETE, 0); + _gl.flush(); + await probeAsync(_gl, sync, 4); + _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, glBuffer); + _gl.getBufferSubData(_gl.PIXEL_PACK_BUFFER, 0, buffer); + _gl.deleteBuffer(glBuffer); + _gl.deleteSync(sync); + return buffer; + } else { + throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range."); + } + } + }; + this.copyFramebufferToTexture = function(texture, position2 = null, level = 0) { + if (texture.isTexture !== true) { + warnOnce("WebGLRenderer: copyFramebufferToTexture function signature has changed."); + position2 = arguments[0] || null; + texture = arguments[1]; + } + const levelScale = Math.pow(2, -level); + const width2 = Math.floor(texture.image.width * levelScale); + const height2 = Math.floor(texture.image.height * levelScale); + const x = position2 !== null ? position2.x : 0; + const y = position2 !== null ? position2.y : 0; + textures.setTexture2D(texture, 0); + _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, x, y, width2, height2); + state.unbindTexture(); + }; + const _srcFramebuffer = _gl.createFramebuffer(); + const _dstFramebuffer = _gl.createFramebuffer(); + this.copyTextureToTexture = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null) { + if (srcTexture.isTexture !== true) { + warnOnce("WebGLRenderer: copyTextureToTexture function signature has changed."); + dstPosition = arguments[0] || null; + srcTexture = arguments[1]; + dstTexture = arguments[2]; + dstLevel = arguments[3] || 0; + srcRegion = null; + } + if (dstLevel === null) { + if (srcLevel !== 0) { + warnOnce("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."); + dstLevel = srcLevel; + srcLevel = 0; + } else { + dstLevel = 0; + } + } + let width2, height2, depth2, minX, minY, minZ; + let dstX, dstY, dstZ; + const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[dstLevel] : srcTexture.image; + if (srcRegion !== null) { + width2 = srcRegion.max.x - srcRegion.min.x; + height2 = srcRegion.max.y - srcRegion.min.y; + depth2 = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1; + minX = srcRegion.min.x; + minY = srcRegion.min.y; + minZ = srcRegion.isBox3 ? srcRegion.min.z : 0; + } else { + const levelScale = Math.pow(2, -srcLevel); + width2 = Math.floor(image.width * levelScale); + height2 = Math.floor(image.height * levelScale); + if (srcTexture.isDataArrayTexture) { + depth2 = image.depth; + } else if (srcTexture.isData3DTexture) { + depth2 = Math.floor(image.depth * levelScale); + } else { + depth2 = 1; + } + minX = 0; + minY = 0; + minZ = 0; + } + if (dstPosition !== null) { + dstX = dstPosition.x; + dstY = dstPosition.y; + dstZ = dstPosition.z; + } else { + dstX = 0; + dstY = 0; + dstZ = 0; + } + const glFormat = utils.convert(dstTexture.format); + const glType = utils.convert(dstTexture.type); + let glTarget; + if (dstTexture.isData3DTexture) { + textures.setTexture3D(dstTexture, 0); + glTarget = _gl.TEXTURE_3D; + } else if (dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture) { + textures.setTexture2DArray(dstTexture, 0); + glTarget = _gl.TEXTURE_2D_ARRAY; + } else { + textures.setTexture2D(dstTexture, 0); + glTarget = _gl.TEXTURE_2D; + } + _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY); + _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha); + _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment); + const currentUnpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH); + const currentUnpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT); + const currentUnpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS); + const currentUnpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS); + const currentUnpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES); + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, minX); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, minY); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, minZ); + const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture; + const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture; + if (srcTexture.isDepthTexture) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + const srcRenderTargetProperties = properties.get(srcTextureProperties.__renderTarget); + const dstRenderTargetProperties = properties.get(dstTextureProperties.__renderTarget); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer); + for (let i = 0;i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(srcTexture).__webglTexture, srcLevel, minZ + i); + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get(dstTexture).__webglTexture, dstLevel, dstZ + i); + } + _gl.blitFramebuffer(minX, minY, width2, height2, dstX, dstY, width2, height2, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST); + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else if (srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has(srcTexture)) { + const srcTextureProperties = properties.get(srcTexture); + const dstTextureProperties = properties.get(dstTexture); + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, _srcFramebuffer); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, _dstFramebuffer); + for (let i = 0;i < depth2; i++) { + if (isSrc3D) { + _gl.framebufferTextureLayer(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i); + } else { + _gl.framebufferTexture2D(_gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel); + } + if (isDst3D) { + _gl.framebufferTextureLayer(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i); + } else { + _gl.framebufferTexture2D(_gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel); + } + if (srcLevel !== 0) { + _gl.blitFramebuffer(minX, minY, width2, height2, dstX, dstY, width2, height2, _gl.COLOR_BUFFER_BIT, _gl.NEAREST); + } else if (isDst3D) { + _gl.copyTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width2, height2); + } else { + _gl.copyTexSubImage2D(glTarget, dstLevel, dstX, dstY, minX, minY, width2, height2); + } + } + state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null); + state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, null); + } else { + if (isDst3D) { + if (srcTexture.isDataTexture || srcTexture.isData3DTexture) { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, glType, image.data); + } else if (dstTexture.isCompressedArrayTexture) { + _gl.compressedTexSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, image.data); + } else { + _gl.texSubImage3D(glTarget, dstLevel, dstX, dstY, dstZ, width2, height2, depth2, glFormat, glType, image); + } + } else { + if (srcTexture.isDataTexture) { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width2, height2, glFormat, glType, image.data); + } else if (srcTexture.isCompressedTexture) { + _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data); + } else { + _gl.texSubImage2D(_gl.TEXTURE_2D, dstLevel, dstX, dstY, width2, height2, glFormat, glType, image); + } + } + } + _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, currentUnpackRowLen); + _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight); + _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels); + _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows); + _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages); + if (dstLevel === 0 && dstTexture.generateMipmaps) { + _gl.generateMipmap(glTarget); + } + state.unbindTexture(); + }; + this.copyTextureToTexture3D = function(srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0) { + if (srcTexture.isTexture !== true) { + warnOnce("WebGLRenderer: copyTextureToTexture3D function signature has changed."); + srcRegion = arguments[0] || null; + dstPosition = arguments[1] || null; + srcTexture = arguments[2]; + dstTexture = arguments[3]; + level = arguments[4] || 0; + } + warnOnce('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'); + return this.copyTextureToTexture(srcTexture, dstTexture, srcRegion, dstPosition, level); + }; + this.initRenderTarget = function(target) { + if (properties.get(target).__webglFramebuffer === undefined) { + textures.setupRenderTarget(target); + } + }; + this.initTexture = function(texture) { + if (texture.isCubeTexture) { + textures.setTextureCube(texture, 0); + } else if (texture.isData3DTexture) { + textures.setTexture3D(texture, 0); + } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) { + textures.setTexture2DArray(texture, 0); + } else { + textures.setTexture2D(texture, 0); + } + state.unbindTexture(); + }; + this.resetState = function() { + _currentActiveCubeFace = 0; + _currentActiveMipmapLevel = 0; + _currentRenderTarget = null; + state.reset(); + bindingStates.reset(); + }; + if (typeof __THREE_DEVTOOLS__ !== "undefined") { + __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); + } + } + get coordinateSystem() { + return WebGLCoordinateSystem; + } + get outputColorSpace() { + return this._outputColorSpace; + } + set outputColorSpace(colorSpace) { + this._outputColorSpace = colorSpace; + const gl = this.getContext(); + gl.drawingBufferColorspace = ColorManagement._getDrawingBufferColorSpace(colorSpace); + gl.unpackColorSpace = ColorManagement._getUnpackColorSpace(); + } +} + +// src/external/ffl.js/ffl.js +var _Import = __toESM(require_struct_fu(), 1); +/*! + * Bindings for FFL, a Mii renderer, in JavaScript. + * https://github.com/ariankordi/FFL.js + * @author Arian Kordi + */ +globalThis._ = globalThis._; +globalThis.THREE = globalThis.THREE; +var _ = globalThis._; +_ = !_ ? _Import : _; +var FFLResult = { + OK: 0, + ERROR: 1, + HDB_EMPTY: 2, + FILE_INVALID: 3, + MANAGER_NOT_CONSTRUCT: 4, + FILE_LOAD_ERROR: 5, + FILE_SAVE_ERROR: 7, + RES_FS_ERROR: 9, + ODB_EMPTY: 10, + OUT_OF_MEMORY: 12, + UNKNOWN_17: 17, + FS_ERROR: 18, + FS_NOT_FOUND: 19, + MAX: 20 +}; +var FFLiShapeType = { + OPA_BEARD: 0, + OPA_FACELINE: 1, + OPA_HAIR_NORMAL: 2, + OPA_FOREHEAD_NORMAL: 3, + XLU_MASK: 4, + XLU_NOSELINE: 5, + OPA_NOSE: 6, + OPA_HAT_NORMAL: 7, + XLU_GLASS: 8, + OPA_HAIR_CAP: 9, + OPA_FOREHEAD_CAP: 10, + OPA_HAT_CAP: 11, + MAX: 12 +}; +var FFLAttributeBufferType = { + POSITION: 0, + TEXCOORD: 1, + NORMAL: 2, + TANGENT: 3, + COLOR: 4, + MAX: 5 +}; +var FFLCullMode = { + NONE: 0, + BACK: 1, + FRONT: 2, + MAX: 3 +}; +var FFLModulateMode = { + CONSTANT: 0, + TEXTURE_DIRECT: 1, + RGB_LAYERED: 2, + ALPHA: 3, + LUMINANCE_ALPHA: 4, + ALPHA_OPA: 5 +}; +var FFLModulateType = { + SHAPE_FACELINE: 0, + SHAPE_BEARD: 1, + SHAPE_NOSE: 2, + SHAPE_FOREHEAD: 3, + SHAPE_HAIR: 4, + SHAPE_CAP: 5, + SHAPE_MASK: 6, + SHAPE_NOSELINE: 7, + SHAPE_GLASS: 8, + MUSTACHE: 9, + MOUTH: 10, + EYEBROW: 11, + EYE: 12, + MOLE: 13, + FACE_MAKE: 14, + FACE_LINE: 15, + FACE_BEARD: 16, + FILL: 17, + SHAPE_MAX: 9 +}; +var FFLResourceType = { + MIDDLE: 0, + HIGH: 1, + MAX: 2 +}; +var FFLExpression = { + NORMAL: 0, + SMILE: 1, + ANGER: 2, + SORROW: 3, + PUZZLED: 3, + SURPRISE: 4, + SURPRISED: 4, + BLINK: 5, + OPEN_MOUTH: 6, + SMILE_OPEN_MOUTH: 7, + HAPPY: 7, + ANGER_OPEN_MOUTH: 8, + SORROW_OPEN_MOUTH: 9, + SURPRISE_OPEN_MOUTH: 10, + BLINK_OPEN_MOUTH: 11, + WINK_LEFT: 12, + WINK_RIGHT: 13, + WINK_LEFT_OPEN_MOUTH: 14, + WINK_RIGHT_OPEN_MOUTH: 15, + LIKE_WINK_LEFT: 16, + LIKE: 16, + LIKE_WINK_RIGHT: 17, + FRUSTRATED: 18, + BORED: 19, + BORED_OPEN_MOUTH: 20, + SIGH_MOUTH_STRAIGHT: 21, + SIGH: 22, + DISGUSTED_MOUTH_STRAIGHT: 23, + DISGUSTED: 24, + LOVE: 25, + LOVE_OPEN_MOUTH: 26, + DETERMINED_MOUTH_STRAIGHT: 27, + DETERMINED: 28, + CRY_MOUTH_STRAIGHT: 29, + CRY: 30, + BIG_SMILE_MOUTH_STRAIGHT: 31, + BIG_SMILE: 32, + CHEEKY: 33, + CHEEKY_DUPLICATE: 34, + JOJO_EYES_FUNNY_MOUTH: 35, + JOJO_EYES_FUNNY_MOUTH_OPEN: 36, + SMUG: 37, + SMUG_OPEN_MOUTH: 38, + RESOLVE: 39, + RESOLVE_OPEN_MOUTH: 40, + UNBELIEVABLE: 41, + UNBELIEVABLE_DUPLICATE: 42, + CUNNING: 43, + CUNNING_DUPLICATE: 44, + RASPBERRY: 45, + RASPBERRY_DUPLICATE: 46, + INNOCENT: 47, + INNOCENT_DUPLICATE: 48, + CAT: 49, + CAT_DUPLICATE: 50, + DOG: 51, + DOG_DUPLICATE: 52, + TASTY: 53, + TASTY_DUPLICATE: 54, + MONEY_MOUTH_STRAIGHT: 55, + MONEY: 56, + SPIRAL_MOUTH_STRAIGHT: 57, + CONFUSED: 58, + CHEERFUL_MOUTH_STRAIGHT: 59, + CHEERFUL: 60, + BLANK_61: 61, + BLANK_62: 62, + GRUMBLE_MOUTH_STRAIGHT: 63, + GRUMBLE: 64, + MOVED_MOUTH_STRAIGHT: 65, + MOVED: 66, + SINGING_MOUTH_SMALL: 67, + SINGING: 68, + STUNNED: 69, + MAX: 70 +}; +var FFLModelFlag = { + NORMAL: 1 << 0, + HAT: 1 << 1, + FACE_ONLY: 1 << 2, + FLATTEN_NOSE: 1 << 3, + NEW_EXPRESSIONS: 1 << 4, + NEW_MASK_ONLY: 1 << 5 +}; +var _uintptr = _.uint32le; +var FFLAttributeBuffer = _.struct([ + _.uint32le("size"), + _.uint32le("stride"), + _uintptr("ptr") +]); +var FFLAttributeBufferParam = _.struct([ + _.struct("attributeBuffers", [FFLAttributeBuffer], 5) +]); +var FFLPrimitiveParam = _.struct([ + _.uint32le("primitiveType"), + _.uint32le("indexCount"), + _uintptr("pAdjustMatrix"), + _uintptr("pIndexBuffer") +]); +var FFLColor = _.struct([ + _.float32le("r"), + _.float32le("g"), + _.float32le("b"), + _.float32le("a") +]); +var FFLVec3 = _.struct([ + _.float32le("x"), + _.float32le("y"), + _.float32le("z") +]); +var FFLModulateParam = _.struct([ + _.uint32le("mode"), + _.uint32le("type"), + _uintptr("pColorR"), + _uintptr("pColorG"), + _uintptr("pColorB"), + _uintptr("pTexture2D") +]); +var FFLDrawParam = _.struct([ + _.struct("attributeBufferParam", [FFLAttributeBufferParam]), + _.struct("modulateParam", [FFLModulateParam]), + _.uint32le("cullMode"), + _.struct("primitiveParam", [FFLPrimitiveParam]) +]); +var FFLCreateID = _.struct([ + _.uint8("data", 10) +]); +var FFLiCharInfo = _.struct([ + _.int32le("miiVersion"), + _.struct("faceline", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("texture"), + _.int32le("make") + ]), + _.struct("hair", [_.int32le("type"), _.int32le("color"), _.int32le("flip")]), + _.struct("eye", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("aspect"), + _.int32le("rotate"), + _.int32le("x"), + _.int32le("y") + ]), + _.struct("eyebrow", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("aspect"), + _.int32le("rotate"), + _.int32le("x"), + _.int32le("y") + ]), + _.struct("nose", [ + _.int32le("type"), + _.int32le("scale"), + _.int32le("y") + ]), + _.struct("mouth", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("aspect"), + _.int32le("y") + ]), + _.struct("beard", [ + _.int32le("mustache"), + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("y") + ]), + _.struct("glass", [ + _.int32le("type"), + _.int32le("color"), + _.int32le("scale"), + _.int32le("y") + ]), + _.struct("mole", [ + _.int32le("type"), + _.int32le("scale"), + _.int32le("x"), + _.int32le("y") + ]), + _.struct("body", [_.int32le("height"), _.int32le("build")]), + _.struct("personal", [ + _.char16le("name", 22), + _.char16le("creator", 22), + _.int32le("gender"), + _.int32le("birthMonth"), + _.int32le("birthDay"), + _.int32le("favoriteColor"), + _.uint8("favorite"), + _.uint8("copyable"), + _.uint8("ngWord"), + _.uint8("localonly"), + _.int32le("regionMove"), + _.int32le("fontRegion"), + _.int32le("roomIndex"), + _.int32le("positionInRoom"), + _.int32le("birthPlatform") + ]), + _.struct("createID", [FFLCreateID]), + _.uint16le("padding_0"), + _.int32le("authorType"), + _.uint8("authorID", 8) +]); +var FFLStoreData_size = 96; +var commonColorEnableMask = 1 << 31; +var commonColorMask = (color) => color | commonColorEnableMask; +var FFLAdditionalInfo = _.struct([ + _.char16le("name", 22), + _.char16le("creator", 22), + _.struct("createID", [FFLCreateID]), + _.byte("_padding0", 2), + _.struct("skinColor", [FFLColor]), + _.uint32le("flags"), + _.uint8("facelineType"), + _.uint8("hairType"), + _.byte("_padding1", 2) +]); +var FFLiRenderTexture = _.struct([ + _uintptr("pTexture2DRenderBufferColorTargetDepthTarget", 4) +]); +var FFLiFacelineTextureTempObject = _.struct([ + _uintptr("pTextureFaceLine"), + _.struct("drawParamFaceLine", [FFLDrawParam]), + _uintptr("pTextureFaceMake"), + _.struct("drawParamFaceMake", [FFLDrawParam]), + _uintptr("pTextureFaceBeard"), + _.struct("drawParamFaceBeard", [FFLDrawParam]), + _uintptr("pRenderTextureCompressorParam", 2) +]); +var FFLiRawMaskDrawParam = _.struct([ + _.struct("drawParamRawMaskPartsEye", [FFLDrawParam], 2), + _.struct("drawParamRawMaskPartsEyebrow", [FFLDrawParam], 2), + _.struct("drawParamRawMaskPartsMouth", [FFLDrawParam]), + _.struct("drawParamRawMaskPartsMustache", [FFLDrawParam], 2), + _.struct("drawParamRawMaskPartsMole", [FFLDrawParam]), + _.struct("drawParamRawMaskPartsFill", [FFLDrawParam]) +]); +var FFLiMaskTexturesTempObject = _.struct([ + _.uint8("partsTextures", 340), + _uintptr("pRawMaskDrawParam", FFLExpression.MAX), + _.byte("_remaining", 904 - 620) +]); +var FFLiTextureTempObject = _.struct([ + _.struct("maskTextures", [FFLiMaskTexturesTempObject]), + _.struct("facelineTexture", [FFLiFacelineTextureTempObject]) +]); +var FFLiMaskTextures = _.struct([ + _uintptr("pRenderTextures", FFLExpression.MAX) +]); +var FFL_RESOLUTION_MASK = 1073741823; +var FFLCharModelDesc = _.struct([ + _.uint32le("resolution"), + _.uint32le("allExpressionFlag", 3), + _.uint32le("modelFlag"), + _.uint32le("resourceType") +]); +var FFLCharModelDescDefault = { + resolution: 512, + allExpressionFlag: new Uint32Array([1, 0, 0]), + modelFlag: FFLModelFlag.NORMAL, + resourceType: FFLResourceType.HIGH +}; +var FFLBoundingBox = _.struct([ + _.struct("min", [FFLVec3]), + _.struct("max", [FFLVec3]) +]); +var FFLPartsTransform = _.struct([ + _.struct("hatTranslate", [FFLVec3]), + _.struct("headFrontRotate", [FFLVec3]), + _.struct("headFrontTranslate", [FFLVec3]), + _.struct("headSideRotate", [FFLVec3]), + _.struct("headSideTranslate", [FFLVec3]), + _.struct("headTopRotate", [FFLVec3]), + _.struct("headTopTranslate", [FFLVec3]) +]); +var FFLiCharModel = _.struct([ + _.struct("charInfo", [FFLiCharInfo]), + _.struct("charModelDesc", [FFLCharModelDesc]), + _.uint32le("expression"), + _uintptr("pTextureTempObject"), + _.struct("drawParam", [FFLDrawParam], FFLiShapeType.MAX), + _uintptr("pShapeData", FFLiShapeType.MAX), + _.struct("facelineRenderTexture", [FFLiRenderTexture]), + _uintptr("pCapGlassNoselineTextures", 3), + _.struct("maskTextures", [FFLiMaskTextures]), + _.struct("beardHairFaceCenterPos", [FFLVec3], 3), + _.struct("partsTransform", [FFLPartsTransform]), + _.uint32le("modelType"), + _.struct("boundingBox", [FFLBoundingBox], 3) +]); +var FFLDataSource = { + OFFICIAL: 0, + DEFAULT: 1, + MIDDLE_DB: 2, + STORE_DATA_OFFICIAL: 3, + STORE_DATA: 4, + BUFFER: 5, + DIRECT_POINTER: 6 +}; +var FFLCharModelSource = _.struct([ + _.uint32le("dataSource"), + _uintptr("pBuffer"), + _.uint16le("index") +]); +var FFLResourceDesc = _.struct([ + _uintptr("pData", FFLResourceType.MAX), + _.uint32le("size", FFLResourceType.MAX) +]); +var FFLTextureFormat = { + R8_UNORM: 0, + R8_G8_UNORM: 1, + R8_G8_B8_A8_UNORM: 2, + MAX: 3 +}; +var FFLTextureInfo = _.struct([ + _.uint16le("width"), + _.uint16le("height"), + _.uint8("mipCount"), + _.uint8("format"), + _.uint8("isGX2Tiled"), + _.byte("_padding", 1), + _.uint32le("imageSize"), + _uintptr("imagePtr"), + _.uint32le("mipSize"), + _uintptr("mipPtr"), + _.uint32le("mipLevelOffset", 13) +]); +var FFLTextureCallback = _.struct([ + _uintptr("pObj"), + _.uint8("useOriginalTileMode"), + _.byte("_padding", 3), + _uintptr("pCreateFunc"), + _uintptr("pDeleteFunc") +]); + +class TextureManager { + constructor(module2, setToFFLGlobal = false) { + this._module = module2; + this._textures = new Map; + this._textureCallbackPtr = 0; + this.logging = false; + this._setTextureCallback(); + if (setToFFLGlobal) { + module2._FFLSetTextureCallback(this._textureCallbackPtr); + } + } + static _allocateTextureCallback(module2, createCallback, deleteCallback) { + const ptr = module2._malloc(FFLTextureCallback.size); + const textureCallback = { + pObj: 0, + useOriginalTileMode: false, + _padding: [0, 0, 0], + pCreateFunc: createCallback, + pDeleteFunc: deleteCallback + }; + const packed = FFLTextureCallback.pack(textureCallback); + module2.HEAPU8.set(packed, ptr); + return ptr; + } + _setTextureCallback(addDeleteCallback = false) { + const mod2 = this._module; + this._createCallback = mod2.addFunction(this._textureCreateFunc.bind(this), "vppp"); + if (addDeleteCallback) { + this._deleteCallback = mod2.addFunction(this._textureDeleteFunc.bind(this), "vpp"); + } + this._textureCallbackPtr = TextureManager._allocateTextureCallback(mod2, this._createCallback, this._deleteCallback ? this._deleteCallback : 0); + } + _getTextureFormat(format) { + const useGLES2Formats = Number(REVISION) <= 136; + const r8 = useGLES2Formats ? LuminanceFormat : RedFormat; + const r8g8 = useGLES2Formats ? LuminanceAlphaFormat : RGFormat; + const textureFormatToThreeFormat = { + [FFLTextureFormat.R8_UNORM]: r8, + [FFLTextureFormat.R8_G8_UNORM]: r8g8, + [FFLTextureFormat.R8_G8_B8_A8_UNORM]: RGBAFormat + }; + const dataFormat = textureFormatToThreeFormat[format]; + if (dataFormat === undefined) { + throw new Error(`_textureCreateFunc: Unexpected FFLTextureFormat value: ${format}`); + } + return dataFormat; + } + _textureCreateFunc(_2, textureInfoPtr, texturePtrPtr) { + const u8 = this._module.HEAPU8.subarray(textureInfoPtr, textureInfoPtr + FFLTextureInfo.size); + const textureInfo = FFLTextureInfo.unpack(u8); + if (this.logging) { + console.debug(`_textureCreateFunc: width=${textureInfo.width}, height=${textureInfo.height}, format=${textureInfo.format}, imageSize=${textureInfo.imageSize}, mipCount=${textureInfo.mipCount}`); + } + const format = this._getTextureFormat(textureInfo.format); + const imageData = this._module.HEAPU8.slice(textureInfo.imagePtr, textureInfo.imagePtr + textureInfo.imageSize); + const canUseMipmaps = Number(REVISION) >= 138; + const useMipmaps = textureInfo.mipCount > 1 && canUseMipmaps; + const texture = new DataTexture(useMipmaps ? null : imageData, textureInfo.width, textureInfo.height, format, UnsignedByteType); + texture.magFilter = LinearFilter; + texture.minFilter = LinearFilter; + if (useMipmaps) { + texture.mipmaps = [{ + data: imageData, + width: textureInfo.width, + height: textureInfo.height + }]; + texture.minFilter = LinearMipmapLinearFilter; + texture.generateMipmaps = false; + this._addMipmaps(texture, textureInfo); + } + texture.needsUpdate = true; + this.set(texture.id, texture); + this._module.HEAPU32[texturePtrPtr / 4] = texture.id; + } + _addMipmaps(texture, textureInfo) { + if (textureInfo.mipPtr === 0) { + throw new Error("_addMipmaps: mipPtr is null, so the caller incorrectly assumed this texture has mipmaps"); + } + for (let mipLevel = 1;mipLevel < textureInfo.mipCount; mipLevel++) { + const mipOffset = textureInfo.mipLevelOffset[mipLevel - 1]; + const mipWidth = Math.max(1, textureInfo.width >> mipLevel); + const mipHeight = Math.max(1, textureInfo.height >> mipLevel); + const nextMipOffset = textureInfo.mipLevelOffset[mipLevel] || textureInfo.mipSize; + const end = textureInfo.mipPtr + nextMipOffset; + const start = textureInfo.mipPtr + mipOffset; + const mipData = this._module.HEAPU8.slice(start, end); + if (this.logging) { + console.debug(` - Mip ${mipLevel}: ${mipWidth}x${mipHeight}, offset=${mipOffset}, range=${start}-${end}`); + } + texture.mipmaps.push({ + data: mipData, + width: mipWidth, + height: mipHeight + }); + } + } + _textureDeleteFunc(_2, texturePtrPtr) { + const texId = this._module.HEAPU32[texturePtrPtr / 4]; + const tex = this._textures.get(texId); + if (tex && this.logging) { + console.debug("Delete texture ", tex.id); + } + } + get(id) { + const texture = this._textures.get(id); + if (!texture && this.logging) { + console.error("Unknown texture", id); + } + return texture; + } + set(id, texture) { + const disposeReal = texture.dispose.bind(texture); + texture.dispose = () => { + disposeReal(); + this.delete(id); + }; + this._textures.set(id, texture); + if (this.logging) { + console.debug("Adding texture ", texture.id); + } + } + delete(id) { + const texture = this._textures.get(id); + if (texture) { + texture.source = null; + texture.mipmaps = null; + if (this.logging) { + console.debug("Deleted texture ", id); + } + this._textures.delete(id); + } + } + disposeCallback() { + if (this._textureCallbackPtr) { + this._module._free(this._textureCallbackPtr); + this._textureCallbackPtr = 0; + } + if (this._deleteCallback) { + this._module.removeFunction(this._deleteCallback); + this._deleteCallback = 0; + } + if (this._createCallback) { + this._module.removeFunction(this._createCallback); + this._createCallback = 0; + } + } + dispose() { + this._textures.forEach((tex) => { + tex.dispose(); + }); + this._textures.clear(); + this.disposeCallback(); + } +} + +class FFLResultException extends Error { + constructor(result, funcName, message) { + if (!message) { + if (funcName) { + message = `${funcName} failed with FFLResult: ${result}`; + } else { + message = `From FFLResult: ${result}`; + } + } + super(message); + this.result = result; + } + static handleResult(result, funcName) { + switch (result) { + case FFLResult.ERROR: + throw new FFLResultWrongParam(funcName); + case FFLResult.FILE_INVALID: + throw new FFLResultBroken(funcName); + case FFLResult.MANAGER_NOT_CONSTRUCT: + throw new FFLResultNotAvailable(funcName); + case FFLResult.FILE_LOAD_ERROR: + throw new FFLResultFatal(funcName); + case FFLResult.OK: + return; + default: + throw new FFLResultException(result, funcName); + } + } +} + +class FFLResultWrongParam extends FFLResultException { + constructor(funcName) { + super(1, funcName, `${funcName} returned FFL_RESULT_WRONG_PARAM. This usually means parameters going into that function were invalid.`); + } +} + +class FFLResultBroken extends FFLResultException { + constructor(funcName, message) { + super(3, funcName, message ? message : `${funcName} returned FFL_RESULT_BROKEN. This usually indicates invalid underlying data.`); + } +} + +class BrokenInitRes extends FFLResultBroken { + constructor() { + super("FFLInitRes", 'The header for the FFL resource is probably invalid. Check the version and magic, should be "FFRA" or "ARFF".'); + } +} + +class BrokenInitModel extends FFLResultBroken { + constructor() { + super("FFLInitCharModelCPUStep", "FFLInitCharModelCPUStep failed probably because your data failed CRC or CharInfo verification (FFLiVerifyCharInfoWithReason)."); + } +} + +class FFLResultNotAvailable extends FFLResultException { + constructor(funcName) { + super(4, funcName, `Tried to call FFL function ${funcName} when FFLManager is not constructed (FFL is not initialized properly).`); + } +} + +class FFLResultFatal extends FFLResultException { + constructor(funcName) { + super(5, funcName, `Failed to uncompress or load a specific asset from the FFL resource file during call to ${funcName}`); + } +} + +class FFLiVerifyReasonException extends Error { + constructor(result) { + super(`FFLiVerifyCharInfoWithReason (CharInfo verification) failed with result: ${result}`); + this.result = result; + } +} + +class ExpressionNotSet extends Error { + constructor(expression) { + super(`Attempted to set expression ${expression}, but the mask for that expression does not exist. You must reinitialize the CharModel with this expression in the expression flags before using it.`); + this.expression = expression; + } +} +async function _loadDataIntoHeap(resource, module2) { + let heapSize; + let heapPtr; + try { + if (resource instanceof ArrayBuffer) { + resource = new Uint8Array(resource); + } + if (resource instanceof Uint8Array) { + heapSize = resource.length; + heapPtr = module2._malloc(heapSize); + console.debug(`_loadDataIntoHeap: Loading from buffer. Size: ${heapSize}, pointer: ${heapPtr}`); + module2.HEAPU8.set(resource, heapPtr); + } else if (resource instanceof Response) { + if (!resource.ok) { + throw new Error(`HTTP error while fetching resource at URL = ${resource.url}, response code = ${resource.status}`); + } + if (!resource.body) { + throw new Error(`Response body is null (resource.body = ${resource.body})`); + } + const contentLength = resource.headers.get("Content-Length"); + if (!contentLength) { + console.debug("_loadDataIntoHeap: Fetch response is missing Content-Length, falling back to reading as ArrayBuffer."); + return _loadDataIntoHeap(await resource.arrayBuffer(), module2); + } + heapSize = parseInt(contentLength, 10); + heapPtr = module2._malloc(heapSize); + console.debug(`loadDataIntoHeap: Streaming from fetch response. Size: ${heapSize}, pointer: ${heapPtr}, URL: ${resource.url}`); + const reader = resource.body.getReader(); + let offset = heapPtr; + while (true) { + const { done, value: value2 } = await reader.read(); + if (done) { + break; + } + module2.HEAPU8.set(value2, offset); + offset += value2.length; + } + } else { + throw new Error("loadDataIntoHeap: type is not Uint8Array or Response"); + } + return { pointer: heapPtr, size: heapSize }; + } catch (error) { + if (heapPtr) { + module2._free(heapPtr); + } + throw error; + } +} +async function initializeFFL(resource, moduleOrPromise) { + console.debug("initializeFFL: Entrypoint, waiting for module to be ready."); + let resourceDescPtr; + function freeResDesc() { + if (resourceDescPtr) { + module2._free(resourceDescPtr); + } + } + const resourceType = FFLResourceType.HIGH; + let module2; + if (typeof moduleOrPromise === "function") { + moduleOrPromise = moduleOrPromise(); + } + if (moduleOrPromise instanceof Promise) { + module2 = await moduleOrPromise; + } else { + module2 = moduleOrPromise; + } + if (!module2.calledRun && !module2.onRuntimeInitialized) { + await new Promise((resolve) => { + module2.onRuntimeInitialized = () => { + console.debug("initializeFFL: Emscripten runtime initialized, resolving."); + resolve(null); + }; + console.debug(`initializeFFL: module.calledRun: ${module2.calledRun}, module.onRuntimeInitialized: +${module2.onRuntimeInitialized} + // ^^ assigned and waiting.`); + }); + } else { + console.debug("initializeFFL: Assuming module is ready."); + } + let resourceDesc = null; + try { + if (resource instanceof Promise) { + resource = await resource; + } + const { pointer: heapPtr, size: heapSize } = await _loadDataIntoHeap(resource, module2); + console.debug(`initializeFFL: Resource loaded into heap. Pointer: ${heapPtr}, Size: ${heapSize}`); + resourceDesc = { pData: [0, 0], size: [0, 0] }; + resourceDesc.pData[resourceType] = heapPtr; + resourceDesc.size[resourceType] = heapSize; + const resourceDescData = FFLResourceDesc.pack(resourceDesc); + resourceDescPtr = module2._malloc(FFLResourceDesc.size); + module2.HEAPU8.set(resourceDescData, resourceDescPtr); + const result = module2._FFLInitRes(0, resourceDescPtr); + if (result === FFLResult.FILE_INVALID) { + throw new BrokenInitRes; + } + FFLResultException.handleResult(result, "FFLInitRes"); + module2._FFLInitResGPUStep(); + module2._FFLSetNormalIsSnorm8_8_8_8(true); + module2._FFLSetTextureFlipY(true); + } catch (error) { + _freeResourceDesc(resourceDesc, module2); + freeResDesc(); + console.error("initializeFFL failed:", error); + throw error; + } finally { + freeResDesc(); + } + return { + module: module2, + resourceDesc + }; +} +async function initializeFFLWithResource(module2, resourcePath) { + const querySelectorResourcePath = "meta[itemprop=ffl-js-resource-fetch-path]"; + if (!resourcePath && typeof document !== "undefined") { + const resourceFetchElement = document.querySelector(querySelectorResourcePath); + if (!resourceFetchElement || !resourceFetchElement.getAttribute("content")) { + throw new Error(`initializeFFLWithResource: Element not found or does not have "content" attribute with path to FFL resource: ${querySelectorResourcePath}`); + } + resourcePath = resourceFetchElement.getAttribute("content"); + } + if (!resourcePath) { + throw new Error("initializeFFLWithResource: resourcePath must be a string"); + } + try { + const response = await fetch(resourcePath); + const ret = await initializeFFL(response, module2); + console.debug("initializeFFLWithResource: FFLiManager and TextureManager initialized, exiting"); + return ret; + } catch (error) { + if (typeof alert !== "undefined") { + alert(`Error initializing FFL with resource: ${error}`); + } + throw error; + } +} +function _freeResourceDesc(desc, module2) { + if (!desc || !desc.pData) { + return; + } + desc.pData.forEach((ptr, i) => { + if (ptr) { + module2._free(ptr); + desc.pData[i] = 0; + } + }); +} +class CharModel { + constructor(ptr, module2, materialClass, texManager) { + this._module = module2; + this._data = null; + this._materialClass = materialClass; + this._materialTextureClass = materialClass; + this._textureManager = texManager; + this._ptr = ptr; + this.__ptr = ptr; + const charModelData = this._module.HEAPU8.subarray(ptr, ptr + FFLiCharModel.size); + this._model = FFLiCharModel.unpack(charModelData); + this._facelineTarget = null; + this._maskTargets = new Array(FFLExpression.MAX).fill(null); + this.meshes = new Group; + this._addCharModelMeshes(module2); + } + _addCharModelMeshes(module2) { + if (!this.meshes) { + throw new Error("_addCharModelMeshes: this.meshes is null or undefined, was this CharModel disposed?"); + } + for (let shapeType = 0;shapeType < FFLiShapeType.MAX; shapeType++) { + const drawParam = this._model.drawParam[shapeType]; + const mesh = drawParamToMesh(drawParam, this._materialClass, module2, this._textureManager); + if (!mesh) { + continue; + } + mesh.renderOrder = drawParam.modulateParam.type; + switch (shapeType) { + case FFLiShapeType.OPA_FACELINE: + this._facelineMesh = mesh; + break; + case FFLiShapeType.XLU_MASK: + this._maskMesh = mesh; + break; + } + this.meshes.add(mesh); + } + } + _getTextureTempObjectPtr() { + return this._model.pTextureTempObject; + } + _getTextureTempObject() { + const ptr = this._getTextureTempObjectPtr(); + return FFLiTextureTempObject.unpack(this._module.HEAPU8.subarray(ptr, ptr + FFLiTextureTempObject.size)); + } + _getPartsTransform() { + const obj = this._model.partsTransform; + const newPartsTransform = {}; + for (const key2 in obj) { + const vec = obj[key2]; + if (vec.x === undefined) { + throw new Error; + } + newPartsTransform[key2] = new Vector3(vec.x, vec.y, vec.z); + } + return newPartsTransform; + } + _getFacelineColor() { + const mod2 = this._module; + const facelineColor = this._model.charInfo.faceline.color; + const colorPtr = mod2._malloc(FFLColor.size); + mod2._FFLGetFacelineColor(colorPtr, facelineColor); + const color = _getFFLColor3(_getFFLColor(colorPtr, mod2.HEAPF32)); + mod2._free(colorPtr); + return color; + } + _getFavoriteColor() { + const mod2 = this._module; + const favoriteColor = this._model.charInfo.personal.favoriteColor; + const colorPtr = mod2._malloc(FFLColor.size); + mod2._FFLGetFavoriteColor(colorPtr, favoriteColor); + const color = _getFFLColor3(_getFFLColor(colorPtr, mod2.HEAPF32)); + mod2._free(colorPtr); + return color; + } + _getCharInfoUint8Array() { + return FFLiCharInfo.pack(this._model.charInfo); + } + _getPartsTexturesPtr() { + return this._model.pTextureTempObject + FFLiTextureTempObject.fields.maskTextures.offset + FFLiMaskTexturesTempObject.fields.partsTextures.offset; + } + _getFacelineTempObjectPtr() { + return this._model.pTextureTempObject + FFLiTextureTempObject.fields.facelineTexture.offset; + } + _getMaskTempObjectPtr() { + return this._model.pTextureTempObject + FFLiTextureTempObject.fields.maskTextures.offset; + } + _getExpressionFlagPtr() { + return this._ptr + FFLiCharModel.fields.charModelDesc.offset + FFLCharModelDesc.fields.allExpressionFlag.offset; + } + _getBoundingBox() { + const bbox = this._model.boundingBox[this._model.modelType]; + if (!(bbox.max.x === 0 && bbox.max.y === 0 && bbox.max.z === 0)) { + const min = new Vector3(bbox.min.x, bbox.min.y, bbox.min.z); + const max = new Vector3(bbox.max.x, bbox.max.y, bbox.max.z); + return new Box3(min, max); + } + const excludeFromBox = [FFLModulateType.SHAPE_MASK, FFLModulateType.SHAPE_GLASS]; + const box = new Box3; + if (!this.meshes) { + throw new Error("_getBoundingBox: this.meshes is null."); + } + this.meshes.traverse((child) => { + if (!(child instanceof Mesh) || excludeFromBox.indexOf(child.geometry.userData.modulateType) !== -1) { + return; + } + box.expandByObject(child); + }); + return box; + } + _getResolution() { + return this._model.charModelDesc.resolution & FFL_RESOLUTION_MASK; + } + _finalizeCharModel() { + if (!this._ptr) { + return; + } + this._module._FFLDeleteCharModel(this._ptr); + this._module._free(this._ptr); + this._ptr = 0; + } + disposeTargets() { + if (this._facelineTarget) { + console.debug(`Disposing target ${this._facelineTarget.texture.id} for faceline`); + this._facelineTarget.dispose(); + this._facelineTarget = null; + } + this._maskTargets.forEach((target, i) => { + if (!target) { + return; + } + console.debug(`Disposing target ${target.texture.id} for mask ${i}`); + target.dispose(); + this._maskTargets[i] = null; + }); + } + dispose(disposeTargets = true) { + console.debug("CharModel.dispose: ptr =", this.__ptr); + this._finalizeCharModel(); + if (this.meshes) { + this._facelineMesh = null; + this._maskMesh = null; + disposeMeshes(this.meshes); + this.meshes = null; + } + if (disposeTargets) { + this.disposeTargets(); + } + if (this._textureManager) { + this._textureManager.dispose(); + this._textureManager = null; + } + } + getStoreData() { + const charInfoData = this._getCharInfoUint8Array(); + const mod2 = this._module; + const charInfoPtr = mod2._malloc(FFLiCharInfo.size); + const storeDataPtr = mod2._malloc(FFLStoreData_size); + mod2.HEAPU8.set(charInfoData, charInfoPtr); + const result = mod2._FFLpGetStoreDataFromCharInfo(storeDataPtr, charInfoPtr); + const storeData = mod2.HEAPU8.slice(storeDataPtr, storeDataPtr + FFLStoreData_size); + mod2._free(charInfoPtr); + mod2._free(storeDataPtr); + if (!result) { + throw new Error("getStoreData: call to FFLpGetStoreDataFromCharInfo returned false, CharInfo verification probably failed"); + } + return storeData; + } + setExpression(expression) { + this._model.expression = expression; + const targ = this._maskTargets[expression]; + if (!targ || !targ.texture) { + throw new ExpressionNotSet(expression); + } + const mesh = this._maskMesh; + if (!mesh || !(mesh instanceof Mesh)) { + if (expression === FFLExpression.BLANK_61 || expression === FFLExpression.BLANK_62) { + return; + } + throw new Error("setExpression: mask mesh does not exist, cannot set expression on it"); + } + targ.texture._target = targ; + mesh.material.map = targ.texture; + mesh.material.needsUpdate = true; + } + getFaceline() { + if (this._facelineTarget) { + return this._facelineTarget; + } + return null; + } + getMask(expression = this.expression) { + if (this._maskTargets && this._maskTargets[expression]) { + return this._maskTargets[expression]; + } + return null; + } + get expression() { + return this._model.expression; + } + get charInfo() { + return this._model.charInfo; + } + get facelineColor() { + if (!this._facelineColor) { + this._facelineColor = this._getFacelineColor(); + } + return this._facelineColor; + } + get favoriteColor() { + if (!this._favoriteColor) { + this._favoriteColor = this._getFavoriteColor(); + } + return this._favoriteColor; + } + get gender() { + return this._model.charInfo.personal.gender; + } + get partsTransform() { + if (!this._partsTransform) { + this._partsTransform = this._getPartsTransform(); + } + return this._partsTransform; + } + get boundingBox() { + if (!this._boundingBox) { + this._boundingBox = this._getBoundingBox(); + } + return this._boundingBox; + } + static BodyScaleMode = { + Apply: 0, + Limit: 1 + }; + getBodyScale(scaleMode = CharModel.BodyScaleMode.Apply) { + const build = this._model.charInfo.body.build; + const height2 = this._model.charInfo.body.height; + const bodyScale = new Vector3; + switch (scaleMode) { + case CharModel.BodyScaleMode.Apply: { + bodyScale.x = build * (height2 * 0.003671875 + 0.4) / 128 + height2 * 0.001796875 + 0.4; + bodyScale.y = height2 * 0.006015625 + 0.5; + break; + } + case CharModel.BodyScaleMode.Limit: { + const heightFactor = height2 / 128; + bodyScale.y = heightFactor * 0.55 + 0.6; + bodyScale.x = heightFactor * 0.3 + 0.6; + bodyScale.x = (heightFactor * 0.6 + 0.8 - bodyScale.x) * (build / 128) + bodyScale.x; + break; + } + default: + throw new Error(`getBodyScale: Unexpected value for scaleMode: ${scaleMode}`); + } + bodyScale.z = bodyScale.x; + return bodyScale; + } +} +var PantsColor = { + GrayNormal: 0, + BluePresent: 1, + RedRegular: 2, + GoldSpecial: 3 +}; +var pantsColors = { + [PantsColor.GrayNormal]: new Color(4212558), + [PantsColor.BluePresent]: new Color(2637946), + [PantsColor.RedRegular]: new Color(7348245), + [PantsColor.GoldSpecial]: new Color(12623920) +}; +function _allocateModelSource(data2, module2) { + const bufferPtr = module2._malloc(FFLiCharInfo.size); + const modelSource = { + dataSource: FFLDataSource.DIRECT_POINTER, + pBuffer: bufferPtr, + index: 0 + }; + if (!(data2 instanceof Uint8Array)) { + try { + if (typeof data2 !== "object") { + throw new Error("_allocateModelSource: data passed in is not FFLiCharInfo object or Uint8Array"); + } + data2 = FFLiCharInfo.pack(data2); + } catch (e) { + module2._free(bufferPtr); + throw e; + } + } + function setStudioData(src) { + const studio = StudioCharInfo.unpack(src); + const charInfo = convertStudioCharInfoToFFLiCharInfo(studio); + data2 = FFLiCharInfo.pack(charInfo); + module2.HEAPU8.set(data2, bufferPtr); + } + function callGetCharInfoFunc(data3, size, funcName) { + const dataPtr = module2._malloc(size); + module2.HEAPU8.set(data3, dataPtr); + const result = module2[funcName](bufferPtr, dataPtr); + module2._free(dataPtr); + if (!result) { + module2._free(bufferPtr); + throw new Error(`_allocateModelSource: call to ${funcName} returned false, CharInfo verification probably failed`); + } + } + switch (data2.length) { + case FFLStoreData_size: { + callGetCharInfoFunc(data2, FFLStoreData_size, "_FFLpGetCharInfoFromStoreData"); + break; + } + case 74: + case 76: { + callGetCharInfoFunc(data2, 74, "_FFLpGetCharInfoFromMiiDataOfficialRFL"); + break; + } + case FFLiCharInfo.size: + module2.HEAPU8.set(data2, bufferPtr); + break; + case StudioCharInfo.size + 1: { + data2 = studioURLObfuscationDecode(data2); + setStudioData(data2); + break; + } + case StudioCharInfo.size: { + setStudioData(data2); + break; + } + default: { + module2._free(bufferPtr); + throw new Error(`_allocateModelSource: Unknown data length: ${data2.length}`); + } + } + return modelSource; +} +function verifyCharInfo(data2, module2, verifyName = false) { + let charInfoPtr = 0; + let charInfoAllocated = false; + if (typeof data2 === "number") { + charInfoPtr = data2; + charInfoAllocated = false; + } else { + charInfoAllocated = true; + charInfoPtr = module2._malloc(FFLiCharInfo.size); + module2.HEAPU8.set(data2, charInfoPtr); + } + const result = module2._FFLiVerifyCharInfoWithReason(charInfoPtr, verifyName); + if (charInfoAllocated) { + module2._free(charInfoPtr); + } + if (result !== 0) { + throw new FFLiVerifyReasonException(result); + } +} +function makeExpressionFlag(expressions) { + function checkRange(i) { + if (i >= FFLExpression.MAX) { + throw new Error(`makeExpressionFlag: input out of range: got ${i}, max: ${FFLExpression.MAX}`); + } + } + function warnIfChangesShapes(i) { + const expressionsDisablingNose = [49, 50, 51, 52, 61, 62]; + const expressionsDisablingMask = [61, 62]; + const prefix = `makeExpressionFlag > warnIfChangesShapes: An expression was enabled (${i}) that is meant to disable nose or mask shape for the entire CharModel, so it is only recommended to set this as a single expression rather than as one of multiple.`; + if (expressionsDisablingNose.indexOf(i) !== -1) { + console.warn(`${prefix} (nose shape)`); + } + if (expressionsDisablingMask.indexOf(i) !== -1) { + console.warn(`${prefix} (in this case, MASK SHAPE so there is supposed to be NO FACE)`); + } + } + const flags = new Uint32Array([0, 0, 0]); + if (typeof expressions === "number") { + expressions = [expressions]; + } else if (!Array.isArray(expressions)) { + throw new Error("makeExpressionFlag: expected array or single number"); + } + for (const index2 of expressions) { + checkRange(index2); + warnIfChangesShapes(index2); + const part = Math.floor(index2 / 32); + const bitIndex = index2 % 32; + flags[part] |= 1 << bitIndex; + } + return flags; +} +function createCharModel(data2, modelDesc, materialClass, module2, verify = true) { + modelDesc = modelDesc || FFLCharModelDescDefault; + if (!module2 || !module2._malloc) { + throw new Error("createCharModel: module is null or does not have ._malloc."); + } + if (!data2) { + throw new Error("createCharModel: data is null or undefined."); + } + if (typeof modelDesc !== "object" || modelDesc.allExpressionFlag === undefined) { + throw new Error("createCharModel: modelDesc argument is invalid, make sure it is FFLCharModelDesc."); + } + const modelSourcePtr = module2._malloc(FFLCharModelSource.size); + const modelDescPtr = module2._malloc(FFLCharModelDesc.size); + const charModelPtr = module2._malloc(FFLiCharModel.size); + const modelSource = _allocateModelSource(data2, module2); + const charInfoPtr = modelSource.pBuffer; + const modelSourceBuffer = FFLCharModelSource.pack(modelSource); + module2.HEAPU8.set(modelSourceBuffer, modelSourcePtr); + modelDesc.modelFlag |= FFLModelFlag.NEW_EXPRESSIONS; + const modelDescBuffer = FFLCharModelDesc.pack(modelDesc); + module2.HEAPU8.set(modelDescBuffer, modelDescPtr); + let textureManager = null; + try { + if (verify) { + verifyCharInfo(charInfoPtr, module2, false); + } + textureManager = new TextureManager(module2, false); + const result = module2._FFLInitCharModelCPUStepWithCallback(charModelPtr, modelSourcePtr, modelDescPtr, textureManager._textureCallbackPtr); + if (result === FFLResult.FILE_INVALID) { + throw new BrokenInitModel; + } + FFLResultException.handleResult(result, "FFLInitCharModelCPUStep"); + } catch (error) { + if (textureManager) { + textureManager.dispose(); + } + module2._free(charModelPtr); + throw error; + } finally { + module2._free(modelSourcePtr); + module2._free(modelDescPtr); + module2._free(charInfoPtr); + if (textureManager) { + textureManager.disposeCallback(); + } + } + const charModel = new CharModel(charModelPtr, module2, materialClass, textureManager); + charModel._data = data2; + console.debug(`createCharModel: Initialized for "${charModel._model.charInfo.personal.name}", ptr =`, charModelPtr); + return charModel; +} +function matSupportsFFL(material) { + return "modulateMode" in material.prototype; +} +function drawParamToMesh(drawParam, materialClass, module2, texManager) { + if (!drawParam) { + throw new Error("drawParamToMesh: drawParam may be null."); + } + if (!texManager) { + throw new Error("drawParamToMesh: Passed in TextureManager is null or undefined, is it constructed?"); + } + if (typeof materialClass !== "function") { + throw new Error("drawParamToMesh: materialClass is unexpectedly not a function."); + } + if (drawParam.primitiveParam.indexCount === 0) { + return null; + } + const geometry = _bindDrawParamGeometry(drawParam, module2); + const cullModeToThreeSide = { + [FFLCullMode.NONE]: DoubleSide, + [FFLCullMode.BACK]: FrontSide, + [FFLCullMode.FRONT]: BackSide, + [FFLCullMode.MAX]: DoubleSide + }; + const side = cullModeToThreeSide[drawParam.cullMode]; + if (side === undefined) { + throw new Error(`drawParamToMesh: Unexpected value for FFLCullMode: ${drawParam.cullMode}`); + } + const texture = _getTextureFromModulateParam(drawParam.modulateParam, texManager); + const isFFLMaterial = matSupportsFFL(materialClass); + const params = _applyModulateParam(drawParam.modulateParam, module2, isFFLMaterial); + const materialParam = { + side, + map: texture, + ...params + }; + if (geometry.attributes.tangent === undefined && "useSpecularModeBlinn" in materialClass.prototype) { + materialParam.useSpecularModeBlinn = true; + } + const material = new materialClass(materialParam); + const mesh = new Mesh(geometry, material); + if (drawParam.primitiveParam.pAdjustMatrix !== 0) { + _applyAdjustMatrixToMesh(drawParam.primitiveParam.pAdjustMatrix, mesh, module2.HEAPF32); + } + if (mesh.geometry.userData) { + mesh.geometry.userData.modulateMode = drawParam.modulateParam.mode; + mesh.geometry.userData.modulateType = drawParam.modulateParam.type; + mesh.geometry.userData.color = params.color instanceof Color ? [params.color.r, params.color.g, params.color.b, 1] : [1, 1, 1, 1]; + mesh.geometry.userData.cullMode = drawParam.cullMode; + } + return mesh; +} +function _bindDrawParamGeometry(drawParam, module2) { + function unexpectedStride(typeStr, stride) { + throw new Error(`_bindDrawParamGeometry: Unexpected stride for attribute ${typeStr}: ${stride}`); + } + const attributes = drawParam.attributeBufferParam.attributeBuffers; + const positionBuffer = attributes[FFLAttributeBufferType.POSITION]; + if (positionBuffer.size === 0) { + throw new Error("_bindDrawParamGeometry: Position buffer must not have size of 0"); + } + const vertexCount = positionBuffer.size / positionBuffer.stride; + const geometry = new BufferGeometry; + const indexPtr = drawParam.primitiveParam.pIndexBuffer / 2; + const indexCount = drawParam.primitiveParam.indexCount; + const indices = module2.HEAPU16.subarray(indexPtr, indexPtr + indexCount); + geometry.setIndex(new Uint16BufferAttribute(indices, 1)); + for (const typeStr in attributes) { + const buffer = attributes[typeStr]; + const type = parseInt(typeStr); + if (buffer.size === 0) { + continue; + } + switch (type) { + case FFLAttributeBufferType.POSITION: { + if (buffer.stride === 16) { + const ptr = buffer.ptr / 4; + const data2 = module2.HEAPF32.subarray(ptr, ptr + vertexCount * 4); + const interleavedBuffer = new InterleavedBuffer(data2, 4); + geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0)); + } else if (buffer.stride === 6) { + const ptr = buffer.ptr / 2; + const data2 = module2.HEAPU16.subarray(ptr, ptr + vertexCount * 3); + geometry.setAttribute("position", new Float16BufferAttribute(data2, 3)); + } else { + unexpectedStride(typeStr, buffer.stride); + } + break; + } + case FFLAttributeBufferType.NORMAL: { + const data2 = module2.HEAP8.subarray(buffer.ptr, buffer.ptr + buffer.size); + geometry.setAttribute("normal", new Int8BufferAttribute(data2, buffer.stride, true)); + break; + } + case FFLAttributeBufferType.TANGENT: { + const data2 = module2.HEAP8.subarray(buffer.ptr, buffer.ptr + buffer.size); + geometry.setAttribute("tangent", new Int8BufferAttribute(data2, buffer.stride, true)); + break; + } + case FFLAttributeBufferType.TEXCOORD: { + if (buffer.stride === 8) { + const ptr = buffer.ptr / 4; + const data2 = module2.HEAPF32.subarray(ptr, ptr + vertexCount * 2); + geometry.setAttribute("uv", new Float32BufferAttribute(data2, 2)); + } else if (buffer.stride === 4) { + const ptr = buffer.ptr / 2; + const data2 = module2.HEAPU16.subarray(ptr, ptr + vertexCount * 2); + geometry.setAttribute("uv", new Float16BufferAttribute(data2, 2)); + } else { + unexpectedStride(typeStr, buffer.stride); + } + break; + } + case FFLAttributeBufferType.COLOR: { + if (buffer.stride === 0) { + break; + } + const data2 = module2.HEAPU8.subarray(buffer.ptr, buffer.ptr + buffer.size); + geometry.setAttribute("_color", new Uint8BufferAttribute(data2, buffer.stride, true)); + break; + } + } + } + return geometry; +} +function _getTextureFromModulateParam(modulateParam, textureManager) { + if (!modulateParam.pTexture2D || modulateParam.pTexture2D === 1) { + return null; + } + const texturePtr = modulateParam.pTexture2D; + const texture = textureManager.get(texturePtr); + if (!texture) { + throw new Error(`_getTextureFromModulateParam: Texture not found for ${texturePtr}.`); + } + const applyMirrorTypes = [ + FFLModulateType.SHAPE_FACELINE, + FFLModulateType.SHAPE_CAP, + FFLModulateType.SHAPE_GLASS + ]; + if (applyMirrorTypes.indexOf(modulateParam.type) !== -1) { + texture.wrapS = MirroredRepeatWrapping; + texture.wrapT = MirroredRepeatWrapping; + texture.needsUpdate = true; + } + return texture; +} +function _getBlendOptionsFromModulateType(modulateType, modulateMode) { + if (modulateMode !== 0 && modulateType >= FFLModulateType.SHAPE_MAX && modulateType <= FFLModulateType.MOLE) { + return { + blending: CustomBlending, + blendSrc: OneMinusDstAlphaFactor, + blendSrcAlpha: SrcAlphaFactor, + blendDst: DstAlphaFactor + }; + } else if (modulateMode !== 0 && modulateType >= FFLModulateType.FACE_MAKE && modulateType <= FFLModulateType.FILL) { + return { + blending: CustomBlending, + blendSrc: SrcAlphaFactor, + blendDst: OneMinusSrcAlphaFactor, + blendSrcAlpha: OneFactor, + blendDstAlpha: OneFactor + }; + } + return {}; +} +function _applyModulateParam(modulateParam, module2, forFFLMaterial = true) { + let color = null; + let color4 = null; + const f32 = module2.HEAPF32; + if (modulateParam.pColorG !== 0 && modulateParam.pColorB !== 0) { + color = [ + _getFFLColor3(_getFFLColor(modulateParam.pColorR, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorG, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorB, f32)) + ]; + if (self.eyeScleraHack && modulateParam.type === 12) { + color = [ + _getFFLColor3(_getFFLColor(modulateParam.pColorR, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorB, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorB, f32)) + ]; + } + } else if (modulateParam.pColorR !== 0) { + color4 = _getFFLColor(modulateParam.pColorR, f32); + color = _getFFLColor3(color4); + } + const opacity = color4 ? color4.a : 1; + const transparent = modulateParam.type >= FFLModulateType.SHAPE_MASK; + const lightEnable = !(modulateParam.type >= FFLModulateType.SHAPE_MAX && modulateParam.mode !== FFLModulateMode.CONSTANT); + const modulateModeType = forFFLMaterial ? { + modulateMode: modulateParam.mode, + modulateType: modulateParam.type + } : {}; + const param = Object.assign(modulateModeType, { + color, + opacity, + transparent, + depthWrite: !transparent, + ..._getBlendOptionsFromModulateType(modulateParam.type, modulateParam.mode) + }); + if (!lightEnable) { + param.lightEnable = lightEnable; + } + return param; +} +function _getFFLColor(colorPtr, heapf32) { + if (!colorPtr) { + throw new Error("_getFFLColor: Received null pointer"); + } + const colorData = heapf32.subarray(colorPtr / 4, colorPtr / 4 + 4); + return { r: colorData[0], g: colorData[1], b: colorData[2], a: colorData[3] }; +} +function _getFFLColor3(color) { + return new Color(color.r, color.g, color.b); +} +function _applyAdjustMatrixToMesh(pMtx, mesh, heapf32) { + const ptr = pMtx / 4; + const m = heapf32.slice(ptr, ptr + 48 / 4); + function matrixFromRowMajor3x4(m2) { + const matrix2 = new Matrix4; + matrix2.set(m2[0], m2[4], m2[8], m2[3], m2[1], m2[5], m2[9], m2[7], m2[2], m2[6], m2[10], m2[11], 0, 0, 0, 1); + return matrix2; + } + const matrix = matrixFromRowMajor3x4(m); + mesh.scale.setFromMatrixScale(matrix); + mesh.position.setFromMatrixPosition(matrix); + if (matrix.elements[0] === -1) { + mesh.scale.x = -1; + } +} +function initCharModelTextures(charModel, renderer2, materialClass = charModel._materialClass) { + if (!(renderer2 instanceof WebGLRenderer) && renderer2["isWebGPURenderer"] === undefined) { + throw new Error("initCharModelTextures: renderer is an invalid or unexpected type."); + } + const module2 = charModel._module; + charModel._materialTextureClass = materialClass; + const textureTempObject = charModel._getTextureTempObject(); + _drawFacelineTexture(charModel, textureTempObject, renderer2, module2, materialClass); + const clearAlpha = renderer2.getClearAlpha(); + clearAlpha !== 0 && renderer2.setClearAlpha(0); + _drawMaskTextures(charModel, textureTempObject, renderer2, module2, materialClass); + charModel._finalizeCharModel(); + charModel.setExpression(charModel.expression); + clearAlpha !== 0 && renderer2.setClearAlpha(clearAlpha); + if (!matSupportsFFL(charModel._materialClass)) { + if (!matSupportsFFL(charModel._materialTextureClass)) { + console.warn("initCharModelTextures: charModel._materialClass does not support modulateMode (no getter), but the _materialTextureClass is either the same or also does not support modulateMode so textures will look wrong"); + } else { + convertModelTexturesToRGBA(charModel, renderer2, charModel._materialTextureClass); + } + } +} +function _drawFacelineTexture(charModel, textureTempObject, renderer2, module2, materialClass) { + const facelineTempObjectPtr = charModel._getFacelineTempObjectPtr(); + module2._FFLiInvalidateTempObjectFacelineTexture(facelineTempObjectPtr); + const drawParams = [ + textureTempObject.facelineTexture.drawParamFaceMake, + textureTempObject.facelineTexture.drawParamFaceLine, + textureTempObject.facelineTexture.drawParamFaceBeard + ].filter((dp) => dp && dp.modulateParam.pTexture2D !== 0); + if (drawParams.length === 0) { + console.debug("_drawFacelineTexture: Skipping faceline texture."); + return; + } + const bgColor = charModel.facelineColor; + const { scene: offscreenScene } = createSceneFromDrawParams(drawParams, bgColor, materialClass, charModel._module, charModel._textureManager); + const width2 = charModel._getResolution() / 2; + const height2 = charModel._getResolution(); + const options = { + depthBuffer: false, + stencilBuffer: false, + wrapS: MirroredRepeatWrapping, + wrapT: MirroredRepeatWrapping + }; + const target = createAndRenderToTarget(offscreenScene, getIdentCamera(), renderer2, width2, height2, options); + console.debug(`Creating target ${target.texture.id} for faceline`); + _setFaceline(charModel, target); + module2._FFLiDeleteTempObjectFacelineTexture(facelineTempObjectPtr, charModel._ptr, charModel._model.charModelDesc.resourceType); + disposeMeshes(offscreenScene); +} +function _drawMaskTextures(charModel, textureTempObject, renderer2, module2, materialClass) { + const maskTempObjectPtr = charModel._getMaskTempObjectPtr(); + const expressionFlagPtr = charModel._getExpressionFlagPtr(); + const scenes = []; + for (let i = 0;i < charModel._model.maskTextures.pRenderTextures.length; i++) { + if (charModel._model.maskTextures.pRenderTextures[i] === 0) { + continue; + } + const rawMaskDrawParamPtr = textureTempObject.maskTextures.pRawMaskDrawParam[i]; + const rawMaskDrawParam = FFLiRawMaskDrawParam.unpack(module2.HEAPU8.subarray(rawMaskDrawParamPtr, rawMaskDrawParamPtr + FFLiRawMaskDrawParam.size)); + module2._FFLiInvalidateRawMask(rawMaskDrawParamPtr); + const { target, scene } = _drawMaskTexture(charModel, rawMaskDrawParam, renderer2, module2, materialClass); + console.debug(`Creating target ${target.texture.id} for mask ${i}`); + charModel._maskTargets[i] = target; + scenes.push(scene); + } + scenes.forEach((scene) => { + disposeMeshes(scene); + }); + module2._FFLiDeleteTempObjectMaskTextures(maskTempObjectPtr, expressionFlagPtr, charModel._model.charModelDesc.resourceType); + module2._FFLiDeleteTextureTempObject(charModel._ptr); +} +function _drawMaskTexture(charModel, rawMaskParam, renderer2, module2, materialClass) { + const drawParams = [ + rawMaskParam.drawParamRawMaskPartsMustache[0], + rawMaskParam.drawParamRawMaskPartsMustache[1], + rawMaskParam.drawParamRawMaskPartsMouth, + rawMaskParam.drawParamRawMaskPartsEyebrow[0], + rawMaskParam.drawParamRawMaskPartsEyebrow[1], + rawMaskParam.drawParamRawMaskPartsEye[0], + rawMaskParam.drawParamRawMaskPartsEye[1], + rawMaskParam.drawParamRawMaskPartsMole + ].filter((dp) => dp && dp.primitiveParam.indexCount !== 0); + if (drawParams.length === 0) { + throw new Error("_drawMaskTexture: All DrawParams are empty."); + } + const options = { + depthBuffer: false, + stencilBuffer: false + }; + const { scene: offscreenScene } = createSceneFromDrawParams(drawParams, null, materialClass, module2, charModel._textureManager); + const width2 = charModel._getResolution(); + const target = createAndRenderToTarget(offscreenScene, getIdentCamera(), renderer2, width2, width2, options); + return { target, scene: offscreenScene }; +} +function _setFaceline(charModel, target) { + if (!target || !target.texture) { + throw new Error("setFaceline: passed in RenderTarget is invalid"); + } + charModel._facelineTarget = target; + const mesh = charModel._facelineMesh; + if (!mesh || !(mesh instanceof Mesh)) { + throw new Error("setFaceline: faceline shape does not exist"); + } + target.texture._target = target; + mesh.material.map = target.texture; + mesh.material.needsUpdate = true; +} +function _texDrawRGBATarget(renderer2, material, userData, materialTextureClass) { + const plane = new PlaneGeometry(2, 2); + const scene = new Scene; + const bgClearRGBMesh = new Mesh(plane, new MeshBasicMaterial({ + color: material.color, + transparent: true, + opacity: 0, + blending: NoBlending + })); + scene.add(bgClearRGBMesh); + if (!material.map) { + throw new Error("_texDrawRGBATarget: material.map is null or undefined"); + } + const tex = material.map; + const texMat = new materialTextureClass({ + map: tex, + modulateMode: userData.modulateMode, + color: material.color, + lightEnable: false + }); + texMat.blending = NoBlending; + texMat.transparent = true; + const textureMesh = new Mesh(plane, texMat); + scene.add(textureMesh); + const target = createAndRenderToTarget(scene, getIdentCamera(false), renderer2, tex.image.width, tex.image.height, { + wrapS: tex.wrapS, + wrapT: tex.wrapT, + depthBuffer: false, + stencilBuffer: false + }); + target.texture._target = target; + material.map.dispose(); + material.map = target.texture; + material.color = new Color(1, 1, 1); + userData.modulateMode = 1; + return target; +} +function convertModelTexturesToRGBA(charModel, renderer2, materialTextureClass) { + const convertTextureForTypes = [ + FFLModulateType.SHAPE_CAP, + FFLModulateType.SHAPE_NOSELINE, + FFLModulateType.SHAPE_GLASS + ]; + if (!charModel.meshes) { + throw new Error("convertModelTexturesToRGBA: charModel.meshes is null."); + } + charModel.meshes.traverse((mesh) => { + if (!(mesh instanceof Mesh) || !mesh.geometry.userData.modulateType || !mesh.material.map || convertTextureForTypes.indexOf(mesh.geometry.userData.modulateType) === -1) { + return; + } + const target = _texDrawRGBATarget(renderer2, mesh.material, mesh.geometry.userData, materialTextureClass); + charModel._maskTargets.push(target); + }); +} +function createSceneFromDrawParams(drawParams, bgColor, ...drawParamArgs) { + const scene = new Scene; + scene.background = bgColor || null; + const meshes = []; + drawParams.forEach((param) => { + const mesh = drawParamToMesh(param, ...drawParamArgs); + if (mesh) { + scene.add(mesh); + meshes.push(mesh); + } + }); + return { scene, meshes }; +} +function getIdentCamera(flipY = false) { + const camera = new OrthographicCamera(-1, 1, flipY ? -1 : 1, flipY ? 1 : -1, 0.1, 10); + camera.position.z = 1; + return camera; +} +function createAndRenderToTarget(scene, camera, renderer2, width2, height2, targetOptions = {}) { + const options = { + minFilter: LinearFilter, + magFilter: LinearFilter, + ...targetOptions + }; + const renderTarget = renderer2["isWebGPURenderer"] === undefined ? new WebGLRenderTarget(width2, height2, options) : new RenderTarget(width2, height2, options); + const prevTarget = renderer2.getRenderTarget(); + renderer2.setRenderTarget(renderTarget); + renderer2.render(scene, camera); + renderer2.setRenderTarget(prevTarget); + return renderTarget; +} +function disposeMeshes(group, scene) { + function disposeMaterial(material) { + if (material.map) { + material.map.dispose(); + } + material.dispose(); + } + group.traverse((child) => { + if (!(child instanceof Mesh)) { + return; + } + if (child.geometry) { + child.geometry.dispose(); + } + if (child.material) { + Array.isArray(child.material) ? child.material.forEach((material) => { + disposeMaterial(material); + }) : disposeMaterial(child.material); + } + }); + if (scene && scene instanceof Scene) { + scene.remove(group); + } + group.children = []; +} +var ViewType = { + Face: 0, + MakeIcon: 1, + IconFovy45: 2 +}; +var StudioCharInfo = _.struct([ + _.uint8("beardColor"), + _.uint8("beardType"), + _.uint8("build"), + _.uint8("eyeAspect"), + _.uint8("eyeColor"), + _.uint8("eyeRotate"), + _.uint8("eyeScale"), + _.uint8("eyeType"), + _.uint8("eyeX"), + _.uint8("eyeY"), + _.uint8("eyebrowAspect"), + _.uint8("eyebrowColor"), + _.uint8("eyebrowRotate"), + _.uint8("eyebrowScale"), + _.uint8("eyebrowType"), + _.uint8("eyebrowX"), + _.uint8("eyebrowY"), + _.uint8("facelineColor"), + _.uint8("facelineMake"), + _.uint8("facelineType"), + _.uint8("facelineWrinkle"), + _.uint8("favoriteColor"), + _.uint8("gender"), + _.uint8("glassColor"), + _.uint8("glassScale"), + _.uint8("glassType"), + _.uint8("glassY"), + _.uint8("hairColor"), + _.uint8("hairFlip"), + _.uint8("hairType"), + _.uint8("height"), + _.uint8("moleScale"), + _.uint8("moleType"), + _.uint8("moleX"), + _.uint8("moleY"), + _.uint8("mouthAspect"), + _.uint8("mouthColor"), + _.uint8("mouthScale"), + _.uint8("mouthType"), + _.uint8("mouthY"), + _.uint8("mustacheScale"), + _.uint8("mustacheType"), + _.uint8("mustacheY"), + _.uint8("noseScale"), + _.uint8("noseType"), + _.uint8("noseY") +]); +function convertStudioCharInfoToFFLiCharInfo(src) { + return { + miiVersion: 0, + faceline: { + type: src.facelineType, + color: src.facelineColor, + texture: src.facelineWrinkle, + make: src.facelineMake + }, + hair: { + type: src.hairType, + color: commonColorMask(src.hairColor), + flip: src.hairFlip + }, + eye: { + type: src.eyeType, + color: commonColorMask(src.eyeColor), + scale: src.eyeScale, + aspect: src.eyeAspect, + rotate: src.eyeRotate, + x: src.eyeX, + y: src.eyeY + }, + eyebrow: { + type: src.eyebrowType, + color: commonColorMask(src.eyebrowColor), + scale: src.eyebrowScale, + aspect: src.eyebrowAspect, + rotate: src.eyebrowRotate, + x: src.eyebrowX, + y: src.eyebrowY + }, + nose: { + type: src.noseType, + scale: src.noseScale, + y: src.noseY + }, + mouth: { + type: src.mouthType, + color: commonColorMask(src.mouthColor), + scale: src.mouthScale, + aspect: src.mouthAspect, + y: src.mouthY + }, + beard: { + mustache: src.mustacheType, + type: src.beardType, + color: commonColorMask(src.beardColor), + scale: src.mustacheScale, + y: src.mustacheY + }, + glass: { + type: src.glassType, + color: commonColorMask(src.glassColor), + scale: src.glassScale, + y: src.glassY + }, + mole: { + type: src.moleType, + scale: src.moleScale, + x: src.moleX, + y: src.moleY + }, + body: { + height: src.height, + build: src.build + }, + personal: { + name: "", + creator: "", + gender: src.gender, + birthMonth: 0, + birthDay: 0, + favoriteColor: src.favoriteColor, + favorite: 0, + copyable: 0, + ngWord: 0, + localonly: 0, + regionMove: 0, + fontRegion: 0, + roomIndex: 0, + positionInRoom: 0, + birthPlatform: 3 + }, + createID: { + data: new Array(10).fill(0) + }, + padding_0: 0, + authorType: 0, + authorID: new Array(8).fill(0) + }; +} +function studioURLObfuscationDecode(data2) { + const decodedData = new Uint8Array(data2); + const random2 = decodedData[0]; + let previous = random2; + for (let i = 1;i < 48; i++) { + const encodedByte = decodedData[i]; + const original = (encodedByte - 7 + 256) % 256; + decodedData[i - 1] = original ^ previous; + previous = encodedByte; + } + return decodedData.slice(0, StudioCharInfo.size); +} +function stripSpaces(str) { + return str.replace(/\s+/g, ""); +} +function hexToUint8Array(hex) { + const match = hex.match(/.{1,2}/g); + const arr = (match ? match : []).map(function(byte) { + return parseInt(byte, 16); + }); + return new Uint8Array(arr); +} +function base64ToUint8Array(base64) { + const normalizedBase64 = base64.replace(/-/g, "+").replace(/_/g, "/"); + function padBase64(str) { + while (str.length % 4 !== 0) { + str += "="; + } + return str; + } + const paddedBase64 = padBase64(normalizedBase64); + const binaryString = atob(paddedBase64); + const len = binaryString.length; + const bytes = new Uint8Array(len); + for (let i = 0;i < len; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function parseHexOrB64ToUint8Array(text2) { + let inputData; + const textData = stripSpaces(text2); + if (/^[0-9a-fA-F]+$/.test(textData)) { + inputData = hexToUint8Array(textData); + } else { + inputData = base64ToUint8Array(textData); + } + return inputData; +} + +// src/util/ModelLoader.ts +var import_jszip = __toESM(require_lib(), 1); +var import_localforage = __toESM(require_localforage(), 1); +// node_modules/three/examples/jsm/animation/CCDIKSolver.js +var _q = new Quaternion; +var _targetPos = new Vector3; +var _targetVec = new Vector3; +var _effectorPos = new Vector3; +var _effectorVec = new Vector3; +var _linkPos = new Vector3; +var _invLinkQ = new Quaternion; +var _linkScale = new Vector3; +var _axis2 = new Vector3; +var _vector4 = new Vector3; +var _matrix2 = new Matrix4; +// node_modules/three/examples/jsm/controls/ArcballControls.js +var STATE = { + IDLE: Symbol(), + ROTATE: Symbol(), + PAN: Symbol(), + SCALE: Symbol(), + FOV: Symbol(), + FOCUS: Symbol(), + ZROTATE: Symbol(), + TOUCH_MULTI: Symbol(), + ANIMATION_FOCUS: Symbol(), + ANIMATION_ROTATE: Symbol() +}; +var INPUT = { + NONE: Symbol(), + ONE_FINGER: Symbol(), + ONE_FINGER_SWITCHED: Symbol(), + TWO_FINGER: Symbol(), + MULT_FINGER: Symbol(), + CURSOR: Symbol() +}; +var _transformation = { + camera: new Matrix4, + gizmos: new Matrix4 +}; +var _raycaster = new Raycaster; +var _offset2 = new Vector3; +var _gizmoMatrixStateTemp = new Matrix4; +var _cameraMatrixStateTemp = new Matrix4; +var _scalePointTemp = new Vector3; +// node_modules/three/examples/jsm/controls/DragControls.js +var _plane = new Plane; +var _pointer = new Vector2; +var _offset3 = new Vector3; +var _diff2 = new Vector2; +var _previousPointer = new Vector2; +var _intersection = new Vector3; +var _worldPosition = new Vector3; +var _inverseMatrix2 = new Matrix4; +var _up = new Vector3; +var _right = new Vector3; +// node_modules/three/examples/jsm/controls/FirstPersonControls.js +var _lookDirection = new Vector3; +var _spherical = new Spherical; +var _target2 = new Vector3; +var _targetPosition = new Vector3; +// node_modules/three/examples/jsm/controls/FlyControls.js +var _tmpQuaternion = new Quaternion; +// node_modules/three/examples/jsm/controls/OrbitControls.js +var _ray2 = new Ray; +var _plane2 = new Plane; +var _TILT_LIMIT = Math.cos(70 * MathUtils.DEG2RAD); +var _v = new Vector3; +var _twoPI = 2 * Math.PI; +// node_modules/three/examples/jsm/controls/PointerLockControls.js +var _euler = new Euler(0, 0, 0, "YXZ"); +var _vector6 = new Vector3; +var _PI_2 = Math.PI / 2; +// node_modules/three/examples/jsm/controls/TrackballControls.js +var _v22 = new Vector2; +var _mouseChange = new Vector2; +var _objectUp = new Vector3; +var _pan = new Vector3; +var _axis3 = new Vector3; +var _quaternion2 = new Quaternion; +var _eyeDirection = new Vector3; +var _objectUpDirection = new Vector3; +var _objectSidewaysDirection = new Vector3; +var _moveDirection = new Vector3; +// node_modules/three/examples/jsm/controls/TransformControls.js +var _raycaster2 = new Raycaster; +var _tempVector = new Vector3; +var _tempVector2 = new Vector3; +var _tempQuaternion = new Quaternion; +var _unit = { + X: new Vector3(1, 0, 0), + Y: new Vector3(0, 1, 0), + Z: new Vector3(0, 0, 1) +}; +var _tempEuler = new Euler; +var _alignVector = new Vector3(0, 1, 0); +var _zeroVector = new Vector3(0, 0, 0); +var _lookAtMatrix = new Matrix4; +var _tempQuaternion2 = new Quaternion; +var _identityQuaternion = new Quaternion; +var _dirVector = new Vector3; +var _tempMatrix = new Matrix4; +var _unitX = new Vector3(1, 0, 0); +var _unitY = new Vector3(0, 1, 0); +var _unitZ = new Vector3(0, 0, 1); +var _v12 = new Vector3; +var _v23 = new Vector3; +var _v32 = new Vector3; +// node_modules/three/examples/jsm/csm/CSMFrustum.js +var inverseProjectionMatrix = new Matrix4; + +class CSMFrustum { + constructor(data2) { + data2 = data2 || {}; + this.zNear = data2.webGL === true ? -1 : 0; + this.vertices = { + near: [ + new Vector3, + new Vector3, + new Vector3, + new Vector3 + ], + far: [ + new Vector3, + new Vector3, + new Vector3, + new Vector3 + ] + }; + if (data2.projectionMatrix !== undefined) { + this.setFromProjectionMatrix(data2.projectionMatrix, data2.maxFar || 1e4); + } + } + setFromProjectionMatrix(projectionMatrix, maxFar) { + const zNear = this.zNear; + const isOrthographic = projectionMatrix.elements[2 * 4 + 3] === 0; + inverseProjectionMatrix.copy(projectionMatrix).invert(); + this.vertices.near[0].set(1, 1, zNear); + this.vertices.near[1].set(1, -1, zNear); + this.vertices.near[2].set(-1, -1, zNear); + this.vertices.near[3].set(-1, 1, zNear); + this.vertices.near.forEach(function(v) { + v.applyMatrix4(inverseProjectionMatrix); + }); + this.vertices.far[0].set(1, 1, 1); + this.vertices.far[1].set(1, -1, 1); + this.vertices.far[2].set(-1, -1, 1); + this.vertices.far[3].set(-1, 1, 1); + this.vertices.far.forEach(function(v) { + v.applyMatrix4(inverseProjectionMatrix); + const absZ = Math.abs(v.z); + if (isOrthographic) { + v.z *= Math.min(maxFar / absZ, 1); + } else { + v.multiplyScalar(Math.min(maxFar / absZ, 1)); + } + }); + return this.vertices; + } + split(breaks, target) { + while (breaks.length > target.length) { + target.push(new CSMFrustum); + } + target.length = breaks.length; + for (let i = 0;i < breaks.length; i++) { + const cascade = target[i]; + if (i === 0) { + for (let j = 0;j < 4; j++) { + cascade.vertices.near[j].copy(this.vertices.near[j]); + } + } else { + for (let j = 0;j < 4; j++) { + cascade.vertices.near[j].lerpVectors(this.vertices.near[j], this.vertices.far[j], breaks[i - 1]); + } + } + if (i === breaks.length - 1) { + for (let j = 0;j < 4; j++) { + cascade.vertices.far[j].copy(this.vertices.far[j]); + } + } else { + for (let j = 0;j < 4; j++) { + cascade.vertices.far[j].lerpVectors(this.vertices.near[j], this.vertices.far[j], breaks[i]); + } + } + } + } + toSpace(cameraMatrix, target) { + for (let i = 0;i < 4; i++) { + target.vertices.near[i].copy(this.vertices.near[i]).applyMatrix4(cameraMatrix); + target.vertices.far[i].copy(this.vertices.far[i]).applyMatrix4(cameraMatrix); + } + } +} + +// node_modules/three/examples/jsm/csm/CSMShader.js +var CSMShader = { + lights_fragment_begin: ` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); + +vec3 geometryClearcoatNormal = vec3( 0.0 ); + +#ifdef USE_CLEARCOAT + + geometryClearcoatNormal = clearcoatNormal; + +#endif + +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + // Iridescence F0 approximation + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif + +IncidentLight directLight; + +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + + pointLight = pointLights[ i ]; + + getPointLightInfo( pointLight, geometryPosition, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + + spotLight = spotLights[ i ]; + + getSpotLightInfo( spotLight, geometryPosition, directLight ); + + // spot lights are ordered [shadows with maps, shadows without maps, maps without shadows, none] + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + + #endif + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && defined( USE_CSM ) && defined( CSM_CASCADES ) + + DirectionalLight directionalLight; + float linearDepth = (vViewPosition.z) / (shadowFar - cameraNear); + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + + #if defined( USE_SHADOWMAP ) && defined( CSM_FADE ) + vec2 cascade; + float cascadeCenter; + float closestEdge; + float margin; + float csmx; + float csmy; + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + + #if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + // NOTE: Depth gets larger away from the camera. + // cascade.x is closer, cascade.y is further + cascade = CSM_cascades[ i ]; + cascadeCenter = ( cascade.x + cascade.y ) / 2.0; + closestEdge = linearDepth < cascadeCenter ? cascade.x : cascade.y; + margin = 0.25 * pow( closestEdge, 2.0 ); + csmx = cascade.x - margin / 2.0; + csmy = cascade.y + margin / 2.0; + if( linearDepth >= csmx && ( linearDepth < csmy || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 ) ) { + + float dist = min( linearDepth - csmx, csmy - linearDepth ); + float ratio = clamp( dist / margin, 0.0, 1.0 ); + + vec3 prevColor = directLight.color; + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + + bool shouldFadeLastCascade = UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth > cascadeCenter; + directLight.color = mix( prevColor, directLight.color, shouldFadeLastCascade ? ratio : 1.0 ); + + ReflectedLight prevLight = reflectedLight; + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + bool shouldBlend = UNROLLED_LOOP_INDEX != CSM_CASCADES - 1 || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1 && linearDepth < cascadeCenter; + float blendRatio = shouldBlend ? ratio : 1.0; + + reflectedLight.directDiffuse = mix( prevLight.directDiffuse, reflectedLight.directDiffuse, blendRatio ); + reflectedLight.directSpecular = mix( prevLight.directSpecular, reflectedLight.directSpecular, blendRatio ); + reflectedLight.indirectDiffuse = mix( prevLight.indirectDiffuse, reflectedLight.indirectDiffuse, blendRatio ); + reflectedLight.indirectSpecular = mix( prevLight.indirectSpecular, reflectedLight.indirectSpecular, blendRatio ); + + } + #endif + + } + #pragma unroll_loop_end + #elif defined (USE_SHADOWMAP) + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + + #if ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + + directionalLightShadow = directionalLightShadows[ i ]; + if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y) directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + + if(linearDepth >= CSM_cascades[UNROLLED_LOOP_INDEX].x && (linearDepth < CSM_cascades[UNROLLED_LOOP_INDEX].y || UNROLLED_LOOP_INDEX == CSM_CASCADES - 1)) RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + #endif + + } + #pragma unroll_loop_end + + #elif ( NUM_DIR_LIGHT_SHADOWS > 0 ) + // note: no loop here - all CSM lights are in fact one light only + getDirectionalLightInfo( directionalLights[0], directLight ); + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + #endif + + #if ( NUM_DIR_LIGHTS > NUM_DIR_LIGHT_SHADOWS) + // compute the lights not casting shadows (if any) + + #pragma unroll_loop_start + for ( int i = NUM_DIR_LIGHT_SHADOWS; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + + getDirectionalLightInfo( directionalLight, directLight ); + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + + #endif + +#endif + + +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) && !defined( USE_CSM ) && !defined( CSM_CASCADES ) + + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + + getDirectionalLightInfo( directionalLight, directLight ); + + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + + RectAreaLight rectAreaLight; + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + + } + #pragma unroll_loop_end + +#endif + +#if defined( RE_IndirectDiffuse ) + + vec3 iblIrradiance = vec3( 0.0 ); + + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + + #if defined( USE_LIGHT_PROBES ) + + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + + #endif + + #if ( NUM_HEMI_LIGHTS > 0 ) + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + + } + #pragma unroll_loop_end + + #endif + +#endif + +#if defined( RE_IndirectSpecular ) + + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); + +#endif +`, + lights_pars_begin: ` +#if defined( USE_CSM ) && defined( CSM_CASCADES ) +uniform vec2 CSM_cascades[CSM_CASCADES]; +uniform float cameraNear; +uniform float shadowFar; +#endif + ` + ShaderChunk.lights_pars_begin +}; + +// node_modules/three/examples/jsm/csm/CSM.js +var _cameraToLightMatrix = new Matrix4; +var _lightSpaceFrustum = new CSMFrustum({ webGL: true }); +var _center2 = new Vector3; +var _bbox = new Box3; +var _lightOrientationMatrix = new Matrix4; +var _lightOrientationMatrixInverse = new Matrix4; +var _up2 = new Vector3(0, 1, 0); +// node_modules/three/examples/jsm/postprocessing/Pass.js +class Pass { + constructor() { + this.isPass = true; + this.enabled = true; + this.needsSwap = true; + this.clear = false; + this.renderToScreen = false; + } + setSize() { + } + render() { + console.error("THREE.Pass: .render() must be implemented in derived pass."); + } + dispose() { + } +} +var _camera2 = new OrthographicCamera(-1, 1, 1, -1, 0, 1); + +class FullscreenTriangleGeometry extends BufferGeometry { + constructor() { + super(); + this.setAttribute("position", new Float32BufferAttribute([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3)); + this.setAttribute("uv", new Float32BufferAttribute([0, 2, 0, 0, 2, 0], 2)); + } +} +var _geometry2 = new FullscreenTriangleGeometry; + +class FullScreenQuad { + constructor(material) { + this._mesh = new Mesh(_geometry2, material); + } + dispose() { + this._mesh.geometry.dispose(); + } + render(renderer2) { + renderer2.render(this._mesh, _camera2); + } + get material() { + return this._mesh.material; + } + set material(value2) { + this._mesh.material = value2; + } +} +// node_modules/three/examples/jsm/exporters/DRACOExporter.js +class DRACOExporter { + parse(object, options = {}) { + options = Object.assign({ + decodeSpeed: 5, + encodeSpeed: 5, + encoderMethod: DRACOExporter.MESH_EDGEBREAKER_ENCODING, + quantization: [16, 8, 8, 8, 8], + exportUvs: true, + exportNormals: true, + exportColor: false + }, options); + if (DracoEncoderModule === undefined) { + throw new Error("THREE.DRACOExporter: required the draco_encoder to work."); + } + const geometry = object.geometry; + const dracoEncoder = DracoEncoderModule(); + const encoder = new dracoEncoder.Encoder; + let builder; + let dracoObject; + if (object.isMesh === true) { + builder = new dracoEncoder.MeshBuilder; + dracoObject = new dracoEncoder.Mesh; + const vertices = geometry.getAttribute("position"); + builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); + const faces = geometry.getIndex(); + if (faces !== null) { + builder.AddFacesToMesh(dracoObject, faces.count / 3, faces.array); + } else { + const faces2 = new (vertices.count > 65535 ? Uint32Array : Uint16Array)(vertices.count); + for (let i = 0;i < faces2.length; i++) { + faces2[i] = i; + } + builder.AddFacesToMesh(dracoObject, vertices.count, faces2); + } + if (options.exportNormals === true) { + const normals = geometry.getAttribute("normal"); + if (normals !== undefined) { + builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.NORMAL, normals.count, normals.itemSize, normals.array); + } + } + if (options.exportUvs === true) { + const uvs = geometry.getAttribute("uv"); + if (uvs !== undefined) { + builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.TEX_COORD, uvs.count, uvs.itemSize, uvs.array); + } + } + if (options.exportColor === true) { + const colors = geometry.getAttribute("color"); + if (colors !== undefined) { + const array = createVertexColorSRGBArray(colors); + builder.AddFloatAttributeToMesh(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, array); + } + } + } else if (object.isPoints === true) { + builder = new dracoEncoder.PointCloudBuilder; + dracoObject = new dracoEncoder.PointCloud; + const vertices = geometry.getAttribute("position"); + builder.AddFloatAttribute(dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array); + if (options.exportColor === true) { + const colors = geometry.getAttribute("color"); + if (colors !== undefined) { + const array = createVertexColorSRGBArray(colors); + builder.AddFloatAttribute(dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, array); + } + } + } else { + throw new Error("DRACOExporter: Unsupported object type."); + } + const encodedData = new dracoEncoder.DracoInt8Array; + const encodeSpeed = options.encodeSpeed !== undefined ? options.encodeSpeed : 5; + const decodeSpeed = options.decodeSpeed !== undefined ? options.decodeSpeed : 5; + encoder.SetSpeedOptions(encodeSpeed, decodeSpeed); + if (options.encoderMethod !== undefined) { + encoder.SetEncodingMethod(options.encoderMethod); + } + if (options.quantization !== undefined) { + for (let i = 0;i < 5; i++) { + if (options.quantization[i] !== undefined) { + encoder.SetAttributeQuantization(i, options.quantization[i]); + } + } + } + let length2; + if (object.isMesh === true) { + length2 = encoder.EncodeMeshToDracoBuffer(dracoObject, encodedData); + } else { + length2 = encoder.EncodePointCloudToDracoBuffer(dracoObject, true, encodedData); + } + dracoEncoder.destroy(dracoObject); + if (length2 === 0) { + throw new Error("THREE.DRACOExporter: Draco encoding failed."); + } + const outputData = new Int8Array(new ArrayBuffer(length2)); + for (let i = 0;i < length2; i++) { + outputData[i] = encodedData.GetValue(i); + } + dracoEncoder.destroy(encodedData); + dracoEncoder.destroy(encoder); + dracoEncoder.destroy(builder); + return outputData; + } +} +function createVertexColorSRGBArray(attribute) { + const _color3 = new Color; + const count = attribute.count; + const itemSize = attribute.itemSize; + const array = new Float32Array(count * itemSize); + for (let i = 0, il = count;i < il; i++) { + _color3.fromBufferAttribute(attribute, i); + ColorManagement.fromWorkingColorSpace(_color3, SRGBColorSpace); + array[i * itemSize] = _color3.r; + array[i * itemSize + 1] = _color3.g; + array[i * itemSize + 2] = _color3.b; + if (itemSize === 4) { + array[i * itemSize + 3] = attribute.getW(i); + } + } + return array; +} +DRACOExporter.MESH_EDGEBREAKER_ENCODING = 1; +DRACOExporter.MESH_SEQUENTIAL_ENCODING = 0; +DRACOExporter.POINT_CLOUD = 0; +DRACOExporter.TRIANGULAR_MESH = 1; +DRACOExporter.INVALID = -1; +DRACOExporter.POSITION = 0; +DRACOExporter.NORMAL = 1; +DRACOExporter.COLOR = 2; +DRACOExporter.TEX_COORD = 3; +DRACOExporter.GENERIC = 4; +// node_modules/three/examples/jsm/libs/fflate.module.js +/*! +fflate - fast JavaScript compression/decompression + +Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE +version 0.8.2 +*/ +var u8 = Uint8Array; +var u16 = Uint16Array; +var i32 = Int32Array; +var fleb = new u8([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, 0, 0, 0]); +var fdeb = new u8([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, 0, 0]); +var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); +var freb = function(eb, start) { + var b = new u16(31); + for (var i = 0;i < 31; ++i) { + b[i] = start += 1 << eb[i - 1]; + } + var r = new i32(b[30]); + for (var i = 1;i < 30; ++i) { + for (var j = b[i];j < b[i + 1]; ++j) { + r[j] = j - b[i] << 5 | i; + } + } + return { b, r }; +}; +var _a = freb(fleb, 2); +var fl2 = _a.b; +var revfl = _a.r; +fl2[28] = 258, revfl[258] = 28; +var _b = freb(fdeb, 0); +var fd = _b.b; +var revfd = _b.r; +var rev = new u16(32768); +for (i = 0;i < 32768; ++i) { + x = (i & 43690) >> 1 | (i & 21845) << 1; + x = (x & 52428) >> 2 | (x & 13107) << 2; + x = (x & 61680) >> 4 | (x & 3855) << 4; + rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1; +} +var x; +var i; +var flt = new u8(288); +for (i = 0;i < 144; ++i) + flt[i] = 8; +var i; +for (i = 144;i < 256; ++i) + flt[i] = 9; +var i; +for (i = 256;i < 280; ++i) + flt[i] = 7; +var i; +for (i = 280;i < 288; ++i) + flt[i] = 8; +var i; +var fdt = new u8(32); +for (i = 0;i < 32; ++i) + fdt[i] = 5; +var i; +var et2 = /* @__PURE__ */ new u8(0); +var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder; +var tds = 0; +try { + td.decode(et2, { stream: true }); + tds = 1; +} catch (e) { +} + +// node_modules/three/examples/jsm/exporters/EXRExporter.js +var textEncoder = new TextEncoder; +// node_modules/three/examples/jsm/exporters/GLTFExporter.js +var KHR_mesh_quantization_ExtraAttrTypes = { + POSITION: [ + "byte", + "byte normalized", + "unsigned byte", + "unsigned byte normalized", + "short", + "short normalized", + "unsigned short", + "unsigned short normalized" + ], + NORMAL: [ + "byte normalized", + "short normalized" + ], + TANGENT: [ + "byte normalized", + "short normalized" + ], + TEXCOORD: [ + "byte", + "byte normalized", + "unsigned byte", + "short", + "short normalized", + "unsigned short" + ] +}; + +class GLTFExporter { + constructor() { + this.textureUtils = null; + this.pluginCallbacks = []; + this.register(function(writer) { + return new GLTFLightExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsUnlitExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsTransmissionExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsVolumeExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsIorExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsSpecularExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsClearcoatExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsDispersionExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsIridescenceExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsSheenExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsAnisotropyExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsEmissiveStrengthExtension(writer); + }); + this.register(function(writer) { + return new GLTFMaterialsBumpExtension(writer); + }); + this.register(function(writer) { + return new GLTFMeshGpuInstancing(writer); + }); + } + register(callback) { + if (this.pluginCallbacks.indexOf(callback) === -1) { + this.pluginCallbacks.push(callback); + } + return this; + } + unregister(callback) { + if (this.pluginCallbacks.indexOf(callback) !== -1) { + this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); + } + return this; + } + setTextureUtils(utils) { + this.textureUtils = utils; + return this; + } + parse(input, onDone, onError, options) { + const writer = new GLTFWriter; + const plugins = []; + for (let i = 0, il = this.pluginCallbacks.length;i < il; i++) { + plugins.push(this.pluginCallbacks[i](writer)); + } + writer.setPlugins(plugins); + writer.setTextureUtils(this.textureUtils); + writer.writeAsync(input, onDone, options).catch(onError); + } + parseAsync(input, options) { + const scope = this; + return new Promise(function(resolve, reject2) { + scope.parse(input, resolve, reject2, options); + }); + } +} +var WEBGL_CONSTANTS = { + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6, + BYTE: 5120, + UNSIGNED_BYTE: 5121, + SHORT: 5122, + UNSIGNED_SHORT: 5123, + INT: 5124, + UNSIGNED_INT: 5125, + FLOAT: 5126, + ARRAY_BUFFER: 34962, + ELEMENT_ARRAY_BUFFER: 34963, + NEAREST: 9728, + LINEAR: 9729, + NEAREST_MIPMAP_NEAREST: 9984, + LINEAR_MIPMAP_NEAREST: 9985, + NEAREST_MIPMAP_LINEAR: 9986, + LINEAR_MIPMAP_LINEAR: 9987, + CLAMP_TO_EDGE: 33071, + MIRRORED_REPEAT: 33648, + REPEAT: 10497 +}; +var KHR_MESH_QUANTIZATION = "KHR_mesh_quantization"; +var THREE_TO_WEBGL = {}; +THREE_TO_WEBGL[NearestFilter] = WEBGL_CONSTANTS.NEAREST; +THREE_TO_WEBGL[NearestMipmapNearestFilter] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST; +THREE_TO_WEBGL[NearestMipmapLinearFilter] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR; +THREE_TO_WEBGL[LinearFilter] = WEBGL_CONSTANTS.LINEAR; +THREE_TO_WEBGL[LinearMipmapNearestFilter] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST; +THREE_TO_WEBGL[LinearMipmapLinearFilter] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR; +THREE_TO_WEBGL[ClampToEdgeWrapping] = WEBGL_CONSTANTS.CLAMP_TO_EDGE; +THREE_TO_WEBGL[RepeatWrapping] = WEBGL_CONSTANTS.REPEAT; +THREE_TO_WEBGL[MirroredRepeatWrapping] = WEBGL_CONSTANTS.MIRRORED_REPEAT; +var PATH_PROPERTIES = { + scale: "scale", + position: "translation", + quaternion: "rotation", + morphTargetInfluences: "weights" +}; +var DEFAULT_SPECULAR_COLOR = new Color; +var GLB_HEADER_BYTES = 12; +var GLB_HEADER_MAGIC = 1179937895; +var GLB_VERSION = 2; +var GLB_CHUNK_PREFIX_BYTES = 8; +var GLB_CHUNK_TYPE_JSON = 1313821514; +var GLB_CHUNK_TYPE_BIN = 5130562; +function equalArray(array1, array2) { + return array1.length === array2.length && array1.every(function(element, index2) { + return element === array2[index2]; + }); +} +function stringToArrayBuffer(text2) { + return new TextEncoder().encode(text2).buffer; +} +function isIdentityMatrix(matrix) { + return equalArray(matrix.elements, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); +} +function getMinMax(attribute, start, count) { + const output = { + min: new Array(attribute.itemSize).fill(Number.POSITIVE_INFINITY), + max: new Array(attribute.itemSize).fill(Number.NEGATIVE_INFINITY) + }; + for (let i = start;i < start + count; i++) { + for (let a = 0;a < attribute.itemSize; a++) { + let value2; + if (attribute.itemSize > 4) { + value2 = attribute.array[i * attribute.itemSize + a]; + } else { + if (a === 0) + value2 = attribute.getX(i); + else if (a === 1) + value2 = attribute.getY(i); + else if (a === 2) + value2 = attribute.getZ(i); + else if (a === 3) + value2 = attribute.getW(i); + if (attribute.normalized === true) { + value2 = MathUtils.normalize(value2, attribute.array); + } + } + output.min[a] = Math.min(output.min[a], value2); + output.max[a] = Math.max(output.max[a], value2); + } + } + return output; +} +function getPaddedBufferSize(bufferSize) { + return Math.ceil(bufferSize / 4) * 4; +} +function getPaddedArrayBuffer(arrayBuffer, paddingByte = 0) { + const paddedLength = getPaddedBufferSize(arrayBuffer.byteLength); + if (paddedLength !== arrayBuffer.byteLength) { + const array = new Uint8Array(paddedLength); + array.set(new Uint8Array(arrayBuffer)); + if (paddingByte !== 0) { + for (let i = arrayBuffer.byteLength;i < paddedLength; i++) { + array[i] = paddingByte; + } + } + return array.buffer; + } + return arrayBuffer; +} +function getCanvas() { + if (typeof document === "undefined" && typeof OffscreenCanvas !== "undefined") { + return new OffscreenCanvas(1, 1); + } + return document.createElement("canvas"); +} +function getToBlobPromise(canvas, mimeType) { + if (canvas.toBlob !== undefined) { + return new Promise((resolve) => canvas.toBlob(resolve, mimeType)); + } + let quality; + if (mimeType === "image/jpeg") { + quality = 0.92; + } else if (mimeType === "image/webp") { + quality = 0.8; + } + return canvas.convertToBlob({ + type: mimeType, + quality + }); +} + +class GLTFWriter { + constructor() { + this.plugins = []; + this.options = {}; + this.pending = []; + this.buffers = []; + this.byteOffset = 0; + this.buffers = []; + this.nodeMap = new Map; + this.skins = []; + this.extensionsUsed = {}; + this.extensionsRequired = {}; + this.uids = new Map; + this.uid = 0; + this.json = { + asset: { + version: "2.0", + generator: "THREE.GLTFExporter r" + REVISION + } + }; + this.cache = { + meshes: new Map, + attributes: new Map, + attributesNormalized: new Map, + materials: new Map, + textures: new Map, + images: new Map + }; + this.textureUtils = null; + } + setPlugins(plugins) { + this.plugins = plugins; + } + setTextureUtils(utils) { + this.textureUtils = utils; + } + async writeAsync(input, onDone, options = {}) { + this.options = Object.assign({ + binary: false, + trs: false, + onlyVisible: true, + maxTextureSize: Infinity, + animations: [], + includeCustomExtensions: false + }, options); + if (this.options.animations.length > 0) { + this.options.trs = true; + } + await this.processInputAsync(input); + await Promise.all(this.pending); + const writer = this; + const buffers = writer.buffers; + const json = writer.json; + options = writer.options; + const extensionsUsed = writer.extensionsUsed; + const extensionsRequired = writer.extensionsRequired; + const blob = new Blob(buffers, { type: "application/octet-stream" }); + const extensionsUsedList = Object.keys(extensionsUsed); + const extensionsRequiredList = Object.keys(extensionsRequired); + if (extensionsUsedList.length > 0) + json.extensionsUsed = extensionsUsedList; + if (extensionsRequiredList.length > 0) + json.extensionsRequired = extensionsRequiredList; + if (json.buffers && json.buffers.length > 0) + json.buffers[0].byteLength = blob.size; + if (options.binary === true) { + const reader = new FileReader; + reader.readAsArrayBuffer(blob); + reader.onloadend = function() { + const binaryChunk = getPaddedArrayBuffer(reader.result); + const binaryChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); + binaryChunkPrefix.setUint32(0, binaryChunk.byteLength, true); + binaryChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_BIN, true); + const jsonChunk = getPaddedArrayBuffer(stringToArrayBuffer(JSON.stringify(json)), 32); + const jsonChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); + jsonChunkPrefix.setUint32(0, jsonChunk.byteLength, true); + jsonChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_JSON, true); + const header = new ArrayBuffer(GLB_HEADER_BYTES); + const headerView = new DataView(header); + headerView.setUint32(0, GLB_HEADER_MAGIC, true); + headerView.setUint32(4, GLB_VERSION, true); + const totalByteLength = GLB_HEADER_BYTES + jsonChunkPrefix.byteLength + jsonChunk.byteLength + binaryChunkPrefix.byteLength + binaryChunk.byteLength; + headerView.setUint32(8, totalByteLength, true); + const glbBlob = new Blob([ + header, + jsonChunkPrefix, + jsonChunk, + binaryChunkPrefix, + binaryChunk + ], { type: "application/octet-stream" }); + const glbReader = new FileReader; + glbReader.readAsArrayBuffer(glbBlob); + glbReader.onloadend = function() { + onDone(glbReader.result); + }; + }; + } else { + if (json.buffers && json.buffers.length > 0) { + const reader = new FileReader; + reader.readAsDataURL(blob); + reader.onloadend = function() { + const base64data = reader.result; + json.buffers[0].uri = base64data; + onDone(json); + }; + } else { + onDone(json); + } + } + } + serializeUserData(object, objectDef) { + if (Object.keys(object.userData).length === 0) + return; + const options = this.options; + const extensionsUsed = this.extensionsUsed; + try { + const json = JSON.parse(JSON.stringify(object.userData)); + if (options.includeCustomExtensions && json.gltfExtensions) { + if (objectDef.extensions === undefined) + objectDef.extensions = {}; + for (const extensionName in json.gltfExtensions) { + objectDef.extensions[extensionName] = json.gltfExtensions[extensionName]; + extensionsUsed[extensionName] = true; + } + delete json.gltfExtensions; + } + if (Object.keys(json).length > 0) + objectDef.extras = json; + } catch (error) { + console.warn("THREE.GLTFExporter: userData of '" + object.name + "' " + "won't be serialized because of JSON.stringify error - " + error.message); + } + } + getUID(attribute, isRelativeCopy = false) { + if (this.uids.has(attribute) === false) { + const uids2 = new Map; + uids2.set(true, this.uid++); + uids2.set(false, this.uid++); + this.uids.set(attribute, uids2); + } + const uids = this.uids.get(attribute); + return uids.get(isRelativeCopy); + } + isNormalizedNormalAttribute(normal) { + const cache = this.cache; + if (cache.attributesNormalized.has(normal)) + return false; + const v = new Vector3; + for (let i = 0, il = normal.count;i < il; i++) { + if (Math.abs(v.fromBufferAttribute(normal, i).length() - 1) > 0.0005) + return false; + } + return true; + } + createNormalizedNormalAttribute(normal) { + const cache = this.cache; + if (cache.attributesNormalized.has(normal)) + return cache.attributesNormalized.get(normal); + const attribute = normal.clone(); + const v = new Vector3; + for (let i = 0, il = attribute.count;i < il; i++) { + v.fromBufferAttribute(attribute, i); + if (v.x === 0 && v.y === 0 && v.z === 0) { + v.setX(1); + } else { + v.normalize(); + } + attribute.setXYZ(i, v.x, v.y, v.z); + } + cache.attributesNormalized.set(normal, attribute); + return attribute; + } + applyTextureTransform(mapDef, texture) { + let didTransform = false; + const transformDef = {}; + if (texture.offset.x !== 0 || texture.offset.y !== 0) { + transformDef.offset = texture.offset.toArray(); + didTransform = true; + } + if (texture.rotation !== 0) { + transformDef.rotation = texture.rotation; + didTransform = true; + } + if (texture.repeat.x !== 1 || texture.repeat.y !== 1) { + transformDef.scale = texture.repeat.toArray(); + didTransform = true; + } + if (didTransform) { + mapDef.extensions = mapDef.extensions || {}; + mapDef.extensions["KHR_texture_transform"] = transformDef; + this.extensionsUsed["KHR_texture_transform"] = true; + } + } + async buildMetalRoughTextureAsync(metalnessMap, roughnessMap) { + if (metalnessMap === roughnessMap) + return metalnessMap; + function getEncodingConversion(map2) { + if (map2.colorSpace === SRGBColorSpace) { + return function SRGBToLinear(c) { + return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); + }; + } + return function LinearToLinear(c) { + return c; + }; + } + if (metalnessMap instanceof CompressedTexture) { + metalnessMap = await this.decompressTextureAsync(metalnessMap); + } + if (roughnessMap instanceof CompressedTexture) { + roughnessMap = await this.decompressTextureAsync(roughnessMap); + } + const metalness = metalnessMap ? metalnessMap.image : null; + const roughness = roughnessMap ? roughnessMap.image : null; + const width2 = Math.max(metalness ? metalness.width : 0, roughness ? roughness.width : 0); + const height2 = Math.max(metalness ? metalness.height : 0, roughness ? roughness.height : 0); + const canvas = getCanvas(); + canvas.width = width2; + canvas.height = height2; + const context = canvas.getContext("2d", { + willReadFrequently: true + }); + context.fillStyle = "#00ffff"; + context.fillRect(0, 0, width2, height2); + const composite = context.getImageData(0, 0, width2, height2); + if (metalness) { + context.drawImage(metalness, 0, 0, width2, height2); + const convert = getEncodingConversion(metalnessMap); + const data2 = context.getImageData(0, 0, width2, height2).data; + for (let i = 2;i < data2.length; i += 4) { + composite.data[i] = convert(data2[i] / 256) * 256; + } + } + if (roughness) { + context.drawImage(roughness, 0, 0, width2, height2); + const convert = getEncodingConversion(roughnessMap); + const data2 = context.getImageData(0, 0, width2, height2).data; + for (let i = 1;i < data2.length; i += 4) { + composite.data[i] = convert(data2[i] / 256) * 256; + } + } + context.putImageData(composite, 0, 0); + const reference = metalnessMap || roughnessMap; + const texture = reference.clone(); + texture.source = new Source(canvas); + texture.colorSpace = NoColorSpace; + texture.channel = (metalnessMap || roughnessMap).channel; + if (metalnessMap && roughnessMap && metalnessMap.channel !== roughnessMap.channel) { + console.warn("THREE.GLTFExporter: UV channels for metalnessMap and roughnessMap textures must match."); + } + console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."); + return texture; + } + async decompressTextureAsync(texture, maxTextureSize = Infinity) { + if (this.textureUtils === null) { + throw new Error("THREE.GLTFExporter: setTextureUtils() must be called to process compressed textures."); + } + return await this.textureUtils.decompress(texture, maxTextureSize); + } + processBuffer(buffer) { + const json = this.json; + const buffers = this.buffers; + if (!json.buffers) + json.buffers = [{ byteLength: 0 }]; + buffers.push(buffer); + return 0; + } + processBufferView(attribute, componentType, start, count, target) { + const json = this.json; + if (!json.bufferViews) + json.bufferViews = []; + let componentSize; + switch (componentType) { + case WEBGL_CONSTANTS.BYTE: + case WEBGL_CONSTANTS.UNSIGNED_BYTE: + componentSize = 1; + break; + case WEBGL_CONSTANTS.SHORT: + case WEBGL_CONSTANTS.UNSIGNED_SHORT: + componentSize = 2; + break; + default: + componentSize = 4; + } + let byteStride = attribute.itemSize * componentSize; + if (target === WEBGL_CONSTANTS.ARRAY_BUFFER) { + byteStride = Math.ceil(byteStride / 4) * 4; + } + const byteLength = getPaddedBufferSize(count * byteStride); + const dataView = new DataView(new ArrayBuffer(byteLength)); + let offset = 0; + for (let i = start;i < start + count; i++) { + for (let a = 0;a < attribute.itemSize; a++) { + let value2; + if (attribute.itemSize > 4) { + value2 = attribute.array[i * attribute.itemSize + a]; + } else { + if (a === 0) + value2 = attribute.getX(i); + else if (a === 1) + value2 = attribute.getY(i); + else if (a === 2) + value2 = attribute.getZ(i); + else if (a === 3) + value2 = attribute.getW(i); + if (attribute.normalized === true) { + value2 = MathUtils.normalize(value2, attribute.array); + } + } + if (componentType === WEBGL_CONSTANTS.FLOAT) { + dataView.setFloat32(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.INT) { + dataView.setInt32(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_INT) { + dataView.setUint32(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.SHORT) { + dataView.setInt16(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT) { + dataView.setUint16(offset, value2, true); + } else if (componentType === WEBGL_CONSTANTS.BYTE) { + dataView.setInt8(offset, value2); + } else if (componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE) { + dataView.setUint8(offset, value2); + } + offset += componentSize; + } + if (offset % byteStride !== 0) { + offset += byteStride - offset % byteStride; + } + } + const bufferViewDef = { + buffer: this.processBuffer(dataView.buffer), + byteOffset: this.byteOffset, + byteLength + }; + if (target !== undefined) + bufferViewDef.target = target; + if (target === WEBGL_CONSTANTS.ARRAY_BUFFER) { + bufferViewDef.byteStride = byteStride; + } + this.byteOffset += byteLength; + json.bufferViews.push(bufferViewDef); + const output = { + id: json.bufferViews.length - 1, + byteLength: 0 + }; + return output; + } + processBufferViewImage(blob) { + const writer = this; + const json = writer.json; + if (!json.bufferViews) + json.bufferViews = []; + return new Promise(function(resolve) { + const reader = new FileReader; + reader.readAsArrayBuffer(blob); + reader.onloadend = function() { + const buffer = getPaddedArrayBuffer(reader.result); + const bufferViewDef = { + buffer: writer.processBuffer(buffer), + byteOffset: writer.byteOffset, + byteLength: buffer.byteLength + }; + writer.byteOffset += buffer.byteLength; + resolve(json.bufferViews.push(bufferViewDef) - 1); + }; + }); + } + processAccessor(attribute, geometry, start, count) { + const json = this.json; + const types = { + 1: "SCALAR", + 2: "VEC2", + 3: "VEC3", + 4: "VEC4", + 9: "MAT3", + 16: "MAT4" + }; + let componentType; + if (attribute.array.constructor === Float32Array) { + componentType = WEBGL_CONSTANTS.FLOAT; + } else if (attribute.array.constructor === Int32Array) { + componentType = WEBGL_CONSTANTS.INT; + } else if (attribute.array.constructor === Uint32Array) { + componentType = WEBGL_CONSTANTS.UNSIGNED_INT; + } else if (attribute.array.constructor === Int16Array) { + componentType = WEBGL_CONSTANTS.SHORT; + } else if (attribute.array.constructor === Uint16Array) { + componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT; + } else if (attribute.array.constructor === Int8Array) { + componentType = WEBGL_CONSTANTS.BYTE; + } else if (attribute.array.constructor === Uint8Array) { + componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE; + } else { + throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type: " + attribute.array.constructor.name); + } + if (start === undefined) + start = 0; + if (count === undefined || count === Infinity) + count = attribute.count; + if (count === 0) + return null; + const minMax = getMinMax(attribute, start, count); + let bufferViewTarget; + if (geometry !== undefined) { + bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER; + } + const bufferView = this.processBufferView(attribute, componentType, start, count, bufferViewTarget); + const accessorDef = { + bufferView: bufferView.id, + byteOffset: bufferView.byteOffset, + componentType, + count, + max: minMax.max, + min: minMax.min, + type: types[attribute.itemSize] + }; + if (attribute.normalized === true) + accessorDef.normalized = true; + if (!json.accessors) + json.accessors = []; + return json.accessors.push(accessorDef) - 1; + } + processImage(image, format, flipY, mimeType = "image/png") { + if (image !== null) { + const writer = this; + const cache = writer.cache; + const json = writer.json; + const options = writer.options; + const pending = writer.pending; + if (!cache.images.has(image)) + cache.images.set(image, {}); + const cachedImages = cache.images.get(image); + const key2 = mimeType + ":flipY/" + flipY.toString(); + if (cachedImages[key2] !== undefined) + return cachedImages[key2]; + if (!json.images) + json.images = []; + const imageDef = { mimeType }; + const canvas = getCanvas(); + canvas.width = Math.min(image.width, options.maxTextureSize); + canvas.height = Math.min(image.height, options.maxTextureSize); + const ctx = canvas.getContext("2d", { + willReadFrequently: true + }); + if (flipY === true) { + ctx.translate(0, canvas.height); + ctx.scale(1, -1); + } + if (image.data !== undefined) { + if (format !== RGBAFormat) { + console.error("GLTFExporter: Only RGBAFormat is supported.", format); + } + if (image.width > options.maxTextureSize || image.height > options.maxTextureSize) { + console.warn("GLTFExporter: Image size is bigger than maxTextureSize", image); + } + const data2 = new Uint8ClampedArray(image.height * image.width * 4); + for (let i = 0;i < data2.length; i += 4) { + data2[i + 0] = image.data[i + 0]; + data2[i + 1] = image.data[i + 1]; + data2[i + 2] = image.data[i + 2]; + data2[i + 3] = image.data[i + 3]; + } + ctx.putImageData(new ImageData(data2, image.width, image.height), 0, 0); + } else { + if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap || typeof OffscreenCanvas !== "undefined" && image instanceof OffscreenCanvas) { + ctx.drawImage(image, 0, 0, canvas.width, canvas.height); + } else { + throw new Error("THREE.GLTFExporter: Invalid image type. Use HTMLImageElement, HTMLCanvasElement, ImageBitmap or OffscreenCanvas."); + } + } + if (options.binary === true) { + pending.push(getToBlobPromise(canvas, mimeType).then((blob) => writer.processBufferViewImage(blob)).then((bufferViewIndex) => { + imageDef.bufferView = bufferViewIndex; + })); + } else { + if (canvas.toDataURL !== undefined) { + imageDef.uri = canvas.toDataURL(mimeType); + } else { + pending.push(getToBlobPromise(canvas, mimeType).then((blob) => new FileReader().readAsDataURL(blob)).then((dataURL) => { + imageDef.uri = dataURL; + })); + } + } + const index2 = json.images.push(imageDef) - 1; + cachedImages[key2] = index2; + return index2; + } else { + throw new Error("THREE.GLTFExporter: No valid image data found. Unable to process texture."); + } + } + processSampler(map2) { + const json = this.json; + if (!json.samplers) + json.samplers = []; + const samplerDef = { + magFilter: THREE_TO_WEBGL[map2.magFilter], + minFilter: THREE_TO_WEBGL[map2.minFilter], + wrapS: THREE_TO_WEBGL[map2.wrapS], + wrapT: THREE_TO_WEBGL[map2.wrapT] + }; + return json.samplers.push(samplerDef) - 1; + } + async processTextureAsync(map2) { + const writer = this; + const options = writer.options; + const cache = this.cache; + const json = this.json; + if (cache.textures.has(map2)) + return cache.textures.get(map2); + if (!json.textures) + json.textures = []; + if (map2 instanceof CompressedTexture) { + map2 = await this.decompressTextureAsync(map2, options.maxTextureSize); + } + let mimeType = map2.userData.mimeType; + if (mimeType === "image/webp") + mimeType = "image/png"; + const textureDef = { + sampler: this.processSampler(map2), + source: this.processImage(map2.image, map2.format, map2.flipY, mimeType) + }; + if (map2.name) + textureDef.name = map2.name; + await this._invokeAllAsync(async function(ext) { + ext.writeTexture && await ext.writeTexture(map2, textureDef); + }); + const index2 = json.textures.push(textureDef) - 1; + cache.textures.set(map2, index2); + return index2; + } + async processMaterialAsync(material) { + const cache = this.cache; + const json = this.json; + if (cache.materials.has(material)) + return cache.materials.get(material); + if (material.isShaderMaterial) { + console.warn("GLTFExporter: THREE.ShaderMaterial not supported."); + return null; + } + if (!json.materials) + json.materials = []; + const materialDef = { pbrMetallicRoughness: {} }; + if (material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true) { + console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results."); + } + const color = material.color.toArray().concat([material.opacity]); + if (!equalArray(color, [1, 1, 1, 1])) { + materialDef.pbrMetallicRoughness.baseColorFactor = color; + } + if (material.isMeshStandardMaterial) { + materialDef.pbrMetallicRoughness.metallicFactor = material.metalness; + materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness; + } else { + materialDef.pbrMetallicRoughness.metallicFactor = 0; + materialDef.pbrMetallicRoughness.roughnessFactor = 1; + } + if (material.metalnessMap || material.roughnessMap) { + const metalRoughTexture = await this.buildMetalRoughTextureAsync(material.metalnessMap, material.roughnessMap); + const metalRoughMapDef = { + index: await this.processTextureAsync(metalRoughTexture), + texCoord: metalRoughTexture.channel + }; + this.applyTextureTransform(metalRoughMapDef, metalRoughTexture); + materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef; + } + if (material.map) { + const baseColorMapDef = { + index: await this.processTextureAsync(material.map), + texCoord: material.map.channel + }; + this.applyTextureTransform(baseColorMapDef, material.map); + materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef; + } + if (material.emissive) { + const emissive = material.emissive; + const maxEmissiveComponent = Math.max(emissive.r, emissive.g, emissive.b); + if (maxEmissiveComponent > 0) { + materialDef.emissiveFactor = material.emissive.toArray(); + } + if (material.emissiveMap) { + const emissiveMapDef = { + index: await this.processTextureAsync(material.emissiveMap), + texCoord: material.emissiveMap.channel + }; + this.applyTextureTransform(emissiveMapDef, material.emissiveMap); + materialDef.emissiveTexture = emissiveMapDef; + } + } + if (material.normalMap) { + const normalMapDef = { + index: await this.processTextureAsync(material.normalMap), + texCoord: material.normalMap.channel + }; + if (material.normalScale && material.normalScale.x !== 1) { + normalMapDef.scale = material.normalScale.x; + } + this.applyTextureTransform(normalMapDef, material.normalMap); + materialDef.normalTexture = normalMapDef; + } + if (material.aoMap) { + const occlusionMapDef = { + index: await this.processTextureAsync(material.aoMap), + texCoord: material.aoMap.channel + }; + if (material.aoMapIntensity !== 1) { + occlusionMapDef.strength = material.aoMapIntensity; + } + this.applyTextureTransform(occlusionMapDef, material.aoMap); + materialDef.occlusionTexture = occlusionMapDef; + } + if (material.transparent) { + materialDef.alphaMode = "BLEND"; + } else { + if (material.alphaTest > 0) { + materialDef.alphaMode = "MASK"; + materialDef.alphaCutoff = material.alphaTest; + } + } + if (material.side === DoubleSide) + materialDef.doubleSided = true; + if (material.name !== "") + materialDef.name = material.name; + this.serializeUserData(material, materialDef); + await this._invokeAllAsync(async function(ext) { + ext.writeMaterialAsync && await ext.writeMaterialAsync(material, materialDef); + }); + const index2 = json.materials.push(materialDef) - 1; + cache.materials.set(material, index2); + return index2; + } + async processMeshAsync(mesh) { + const cache = this.cache; + const json = this.json; + const meshCacheKeyParts = [mesh.geometry.uuid]; + if (Array.isArray(mesh.material)) { + for (let i = 0, l = mesh.material.length;i < l; i++) { + meshCacheKeyParts.push(mesh.material[i].uuid); + } + } else { + meshCacheKeyParts.push(mesh.material.uuid); + } + const meshCacheKey = meshCacheKeyParts.join(":"); + if (cache.meshes.has(meshCacheKey)) + return cache.meshes.get(meshCacheKey); + const geometry = mesh.geometry; + let mode; + if (mesh.isLineSegments) { + mode = WEBGL_CONSTANTS.LINES; + } else if (mesh.isLineLoop) { + mode = WEBGL_CONSTANTS.LINE_LOOP; + } else if (mesh.isLine) { + mode = WEBGL_CONSTANTS.LINE_STRIP; + } else if (mesh.isPoints) { + mode = WEBGL_CONSTANTS.POINTS; + } else { + mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES; + } + const meshDef = {}; + const attributes = {}; + const primitives = []; + const targets = []; + const nameConversion = { + uv: "TEXCOORD_0", + uv1: "TEXCOORD_1", + uv2: "TEXCOORD_2", + uv3: "TEXCOORD_3", + color: "COLOR_0", + skinWeight: "WEIGHTS_0", + skinIndex: "JOINTS_0" + }; + const originalNormal = geometry.getAttribute("normal"); + if (originalNormal !== undefined && !this.isNormalizedNormalAttribute(originalNormal)) { + console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."); + geometry.setAttribute("normal", this.createNormalizedNormalAttribute(originalNormal)); + } + let modifiedAttribute = null; + for (let attributeName in geometry.attributes) { + if (attributeName.slice(0, 5) === "morph") + continue; + const attribute = geometry.attributes[attributeName]; + attributeName = nameConversion[attributeName] || attributeName.toUpperCase(); + const validVertexAttributes = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/; + if (!validVertexAttributes.test(attributeName)) + attributeName = "_" + attributeName; + if (cache.attributes.has(this.getUID(attribute))) { + attributes[attributeName] = cache.attributes.get(this.getUID(attribute)); + continue; + } + modifiedAttribute = null; + const array = attribute.array; + if (attributeName === "JOINTS_0" && !(array instanceof Uint16Array) && !(array instanceof Uint8Array)) { + console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'); + modifiedAttribute = new BufferAttribute(new Uint16Array(array), attribute.itemSize, attribute.normalized); + } else if ((array instanceof Uint32Array || array instanceof Int32Array) && !attributeName.startsWith("_")) { + console.warn(`GLTFExporter: Attribute "${attributeName}" converted to type FLOAT.`); + modifiedAttribute = GLTFExporter.Utils.toFloat32BufferAttribute(attribute); + } + const accessor = this.processAccessor(modifiedAttribute || attribute, geometry); + if (accessor !== null) { + if (!attributeName.startsWith("_")) { + this.detectMeshQuantization(attributeName, attribute); + } + attributes[attributeName] = accessor; + cache.attributes.set(this.getUID(attribute), accessor); + } + } + if (originalNormal !== undefined) + geometry.setAttribute("normal", originalNormal); + if (Object.keys(attributes).length === 0) + return null; + if (mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0) { + const weights = []; + const targetNames = []; + const reverseDictionary = {}; + if (mesh.morphTargetDictionary !== undefined) { + for (const key2 in mesh.morphTargetDictionary) { + reverseDictionary[mesh.morphTargetDictionary[key2]] = key2; + } + } + for (let i = 0;i < mesh.morphTargetInfluences.length; ++i) { + const target = {}; + let warned = false; + for (const attributeName in geometry.morphAttributes) { + if (attributeName !== "position" && attributeName !== "normal") { + if (!warned) { + console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."); + warned = true; + } + continue; + } + const attribute = geometry.morphAttributes[attributeName][i]; + const gltfAttributeName = attributeName.toUpperCase(); + const baseAttribute = geometry.attributes[attributeName]; + if (cache.attributes.has(this.getUID(attribute, true))) { + target[gltfAttributeName] = cache.attributes.get(this.getUID(attribute, true)); + continue; + } + const relativeAttribute = attribute.clone(); + if (!geometry.morphTargetsRelative) { + for (let j = 0, jl = attribute.count;j < jl; j++) { + for (let a = 0;a < attribute.itemSize; a++) { + if (a === 0) + relativeAttribute.setX(j, attribute.getX(j) - baseAttribute.getX(j)); + if (a === 1) + relativeAttribute.setY(j, attribute.getY(j) - baseAttribute.getY(j)); + if (a === 2) + relativeAttribute.setZ(j, attribute.getZ(j) - baseAttribute.getZ(j)); + if (a === 3) + relativeAttribute.setW(j, attribute.getW(j) - baseAttribute.getW(j)); + } + } + } + target[gltfAttributeName] = this.processAccessor(relativeAttribute, geometry); + cache.attributes.set(this.getUID(baseAttribute, true), target[gltfAttributeName]); + } + targets.push(target); + weights.push(mesh.morphTargetInfluences[i]); + if (mesh.morphTargetDictionary !== undefined) + targetNames.push(reverseDictionary[i]); + } + meshDef.weights = weights; + if (targetNames.length > 0) { + meshDef.extras = {}; + meshDef.extras.targetNames = targetNames; + } + } + const isMultiMaterial = Array.isArray(mesh.material); + if (isMultiMaterial && geometry.groups.length === 0) + return null; + let didForceIndices = false; + if (isMultiMaterial && geometry.index === null) { + const indices = []; + for (let i = 0, il = geometry.attributes.position.count;i < il; i++) { + indices[i] = i; + } + geometry.setIndex(indices); + didForceIndices = true; + } + const materials = isMultiMaterial ? mesh.material : [mesh.material]; + const groups = isMultiMaterial ? geometry.groups : [{ materialIndex: 0, start: undefined, count: undefined }]; + for (let i = 0, il = groups.length;i < il; i++) { + const primitive = { + mode, + attributes + }; + this.serializeUserData(geometry, primitive); + if (targets.length > 0) + primitive.targets = targets; + if (geometry.index !== null) { + let cacheKey = this.getUID(geometry.index); + if (groups[i].start !== undefined || groups[i].count !== undefined) { + cacheKey += ":" + groups[i].start + ":" + groups[i].count; + } + if (cache.attributes.has(cacheKey)) { + primitive.indices = cache.attributes.get(cacheKey); + } else { + primitive.indices = this.processAccessor(geometry.index, geometry, groups[i].start, groups[i].count); + cache.attributes.set(cacheKey, primitive.indices); + } + if (primitive.indices === null) + delete primitive.indices; + } + const material = await this.processMaterialAsync(materials[groups[i].materialIndex]); + if (material !== null) + primitive.material = material; + primitives.push(primitive); + } + if (didForceIndices === true) { + geometry.setIndex(null); + } + meshDef.primitives = primitives; + if (!json.meshes) + json.meshes = []; + await this._invokeAllAsync(function(ext) { + ext.writeMesh && ext.writeMesh(mesh, meshDef); + }); + const index2 = json.meshes.push(meshDef) - 1; + cache.meshes.set(meshCacheKey, index2); + return index2; + } + detectMeshQuantization(attributeName, attribute) { + if (this.extensionsUsed[KHR_MESH_QUANTIZATION]) + return; + let attrType = undefined; + switch (attribute.array.constructor) { + case Int8Array: + attrType = "byte"; + break; + case Uint8Array: + attrType = "unsigned byte"; + break; + case Int16Array: + attrType = "short"; + break; + case Uint16Array: + attrType = "unsigned short"; + break; + default: + return; + } + if (attribute.normalized) + attrType += " normalized"; + const attrNamePrefix = attributeName.split("_", 1)[0]; + if (KHR_mesh_quantization_ExtraAttrTypes[attrNamePrefix] && KHR_mesh_quantization_ExtraAttrTypes[attrNamePrefix].includes(attrType)) { + this.extensionsUsed[KHR_MESH_QUANTIZATION] = true; + this.extensionsRequired[KHR_MESH_QUANTIZATION] = true; + } + } + processCamera(camera) { + const json = this.json; + if (!json.cameras) + json.cameras = []; + const isOrtho = camera.isOrthographicCamera; + const cameraDef = { + type: isOrtho ? "orthographic" : "perspective" + }; + if (isOrtho) { + cameraDef.orthographic = { + xmag: camera.right * 2, + ymag: camera.top * 2, + zfar: camera.far <= 0 ? 0.001 : camera.far, + znear: camera.near < 0 ? 0 : camera.near + }; + } else { + cameraDef.perspective = { + aspectRatio: camera.aspect, + yfov: MathUtils.degToRad(camera.fov), + zfar: camera.far <= 0 ? 0.001 : camera.far, + znear: camera.near < 0 ? 0 : camera.near + }; + } + if (camera.name !== "") + cameraDef.name = camera.type; + return json.cameras.push(cameraDef) - 1; + } + processAnimation(clip, root) { + const json = this.json; + const nodeMap = this.nodeMap; + if (!json.animations) + json.animations = []; + clip = GLTFExporter.Utils.mergeMorphTargetTracks(clip.clone(), root); + const tracks = clip.tracks; + const channels = []; + const samplers = []; + for (let i = 0;i < tracks.length; ++i) { + const track = tracks[i]; + const trackBinding = PropertyBinding.parseTrackName(track.name); + let trackNode = PropertyBinding.findNode(root, trackBinding.nodeName); + const trackProperty = PATH_PROPERTIES[trackBinding.propertyName]; + if (trackBinding.objectName === "bones") { + if (trackNode.isSkinnedMesh === true) { + trackNode = trackNode.skeleton.getBoneByName(trackBinding.objectIndex); + } else { + trackNode = undefined; + } + } + if (!trackNode || !trackProperty) { + console.warn('THREE.GLTFExporter: Could not export animation track "%s".', track.name); + continue; + } + const inputItemSize = 1; + let outputItemSize = track.values.length / track.times.length; + if (trackProperty === PATH_PROPERTIES.morphTargetInfluences) { + outputItemSize /= trackNode.morphTargetInfluences.length; + } + let interpolation; + if (track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true) { + interpolation = "CUBICSPLINE"; + outputItemSize /= 3; + } else if (track.getInterpolation() === InterpolateDiscrete) { + interpolation = "STEP"; + } else { + interpolation = "LINEAR"; + } + samplers.push({ + input: this.processAccessor(new BufferAttribute(track.times, inputItemSize)), + output: this.processAccessor(new BufferAttribute(track.values, outputItemSize)), + interpolation + }); + channels.push({ + sampler: samplers.length - 1, + target: { + node: nodeMap.get(trackNode), + path: trackProperty + } + }); + } + json.animations.push({ + name: clip.name || "clip_" + json.animations.length, + samplers, + channels + }); + return json.animations.length - 1; + } + processSkin(object) { + const json = this.json; + const nodeMap = this.nodeMap; + const node = json.nodes[nodeMap.get(object)]; + const skeleton = object.skeleton; + if (skeleton === undefined) + return null; + const rootJoint = object.skeleton.bones[0]; + if (rootJoint === undefined) + return null; + const joints = []; + const inverseBindMatrices = new Float32Array(skeleton.bones.length * 16); + const temporaryBoneInverse = new Matrix4; + for (let i = 0;i < skeleton.bones.length; ++i) { + joints.push(nodeMap.get(skeleton.bones[i])); + temporaryBoneInverse.copy(skeleton.boneInverses[i]); + temporaryBoneInverse.multiply(object.bindMatrix).toArray(inverseBindMatrices, i * 16); + } + if (json.skins === undefined) + json.skins = []; + json.skins.push({ + inverseBindMatrices: this.processAccessor(new BufferAttribute(inverseBindMatrices, 16)), + joints, + skeleton: nodeMap.get(rootJoint) + }); + const skinIndex = node.skin = json.skins.length - 1; + return skinIndex; + } + async processNodeAsync(object) { + const json = this.json; + const options = this.options; + const nodeMap = this.nodeMap; + if (!json.nodes) + json.nodes = []; + const nodeDef = {}; + if (options.trs) { + const rotation2 = object.quaternion.toArray(); + const position2 = object.position.toArray(); + const scale2 = object.scale.toArray(); + if (!equalArray(rotation2, [0, 0, 0, 1])) { + nodeDef.rotation = rotation2; + } + if (!equalArray(position2, [0, 0, 0])) { + nodeDef.translation = position2; + } + if (!equalArray(scale2, [1, 1, 1])) { + nodeDef.scale = scale2; + } + } else { + if (object.matrixAutoUpdate) { + object.updateMatrix(); + } + if (isIdentityMatrix(object.matrix) === false) { + nodeDef.matrix = object.matrix.elements; + } + } + if (object.name !== "") + nodeDef.name = String(object.name); + this.serializeUserData(object, nodeDef); + if (object.isMesh || object.isLine || object.isPoints) { + const meshIndex = await this.processMeshAsync(object); + if (meshIndex !== null) + nodeDef.mesh = meshIndex; + } else if (object.isCamera) { + nodeDef.camera = this.processCamera(object); + } + if (object.isSkinnedMesh) + this.skins.push(object); + if (object.children.length > 0) { + const children = []; + for (let i = 0, l = object.children.length;i < l; i++) { + const child = object.children[i]; + if (child.visible || options.onlyVisible === false) { + const nodeIndex2 = await this.processNodeAsync(child); + if (nodeIndex2 !== null) + children.push(nodeIndex2); + } + } + if (children.length > 0) + nodeDef.children = children; + } + await this._invokeAllAsync(function(ext) { + ext.writeNode && ext.writeNode(object, nodeDef); + }); + const nodeIndex = json.nodes.push(nodeDef) - 1; + nodeMap.set(object, nodeIndex); + return nodeIndex; + } + async processSceneAsync(scene) { + const json = this.json; + const options = this.options; + if (!json.scenes) { + json.scenes = []; + json.scene = 0; + } + const sceneDef = {}; + if (scene.name !== "") + sceneDef.name = scene.name; + json.scenes.push(sceneDef); + const nodes = []; + for (let i = 0, l = scene.children.length;i < l; i++) { + const child = scene.children[i]; + if (child.visible || options.onlyVisible === false) { + const nodeIndex = await this.processNodeAsync(child); + if (nodeIndex !== null) + nodes.push(nodeIndex); + } + } + if (nodes.length > 0) + sceneDef.nodes = nodes; + this.serializeUserData(scene, sceneDef); + } + async processObjectsAsync(objects) { + const scene = new Scene; + scene.name = "AuxScene"; + for (let i = 0;i < objects.length; i++) { + scene.children.push(objects[i]); + } + await this.processSceneAsync(scene); + } + async processInputAsync(input) { + const options = this.options; + input = input instanceof Array ? input : [input]; + await this._invokeAllAsync(function(ext) { + ext.beforeParse && ext.beforeParse(input); + }); + const objectsWithoutScene = []; + for (let i = 0;i < input.length; i++) { + if (input[i] instanceof Scene) { + await this.processSceneAsync(input[i]); + } else { + objectsWithoutScene.push(input[i]); + } + } + if (objectsWithoutScene.length > 0) { + await this.processObjectsAsync(objectsWithoutScene); + } + for (let i = 0;i < this.skins.length; ++i) { + this.processSkin(this.skins[i]); + } + for (let i = 0;i < options.animations.length; ++i) { + this.processAnimation(options.animations[i], input[0]); + } + await this._invokeAllAsync(function(ext) { + ext.afterParse && ext.afterParse(input); + }); + } + async _invokeAllAsync(func) { + for (let i = 0, il = this.plugins.length;i < il; i++) { + await func(this.plugins[i]); + } + } +} + +class GLTFLightExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_lights_punctual"; + } + writeNode(light, nodeDef) { + if (!light.isLight) + return; + if (!light.isDirectionalLight && !light.isPointLight && !light.isSpotLight) { + console.warn("THREE.GLTFExporter: Only directional, point, and spot lights are supported.", light); + return; + } + const writer = this.writer; + const json = writer.json; + const extensionsUsed = writer.extensionsUsed; + const lightDef = {}; + if (light.name) + lightDef.name = light.name; + lightDef.color = light.color.toArray(); + lightDef.intensity = light.intensity; + if (light.isDirectionalLight) { + lightDef.type = "directional"; + } else if (light.isPointLight) { + lightDef.type = "point"; + if (light.distance > 0) + lightDef.range = light.distance; + } else if (light.isSpotLight) { + lightDef.type = "spot"; + if (light.distance > 0) + lightDef.range = light.distance; + lightDef.spot = {}; + lightDef.spot.innerConeAngle = (1 - light.penumbra) * light.angle; + lightDef.spot.outerConeAngle = light.angle; + } + if (light.decay !== undefined && light.decay !== 2) { + console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, " + "and expects light.decay=2."); + } + if (light.target && (light.target.parent !== light || light.target.position.x !== 0 || light.target.position.y !== 0 || light.target.position.z !== -1)) { + console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, " + "make light.target a child of the light with position 0,0,-1."); + } + if (!extensionsUsed[this.name]) { + json.extensions = json.extensions || {}; + json.extensions[this.name] = { lights: [] }; + extensionsUsed[this.name] = true; + } + const lights = json.extensions[this.name].lights; + lights.push(lightDef); + nodeDef.extensions = nodeDef.extensions || {}; + nodeDef.extensions[this.name] = { light: lights.length - 1 }; + } +} + +class GLTFMaterialsUnlitExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_unlit"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshBasicMaterial) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = {}; + extensionsUsed[this.name] = true; + materialDef.pbrMetallicRoughness.metallicFactor = 0; + materialDef.pbrMetallicRoughness.roughnessFactor = 0.9; + } +} + +class GLTFMaterialsClearcoatExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_clearcoat"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.clearcoat === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.clearcoatFactor = material.clearcoat; + if (material.clearcoatMap) { + const clearcoatMapDef = { + index: await writer.processTextureAsync(material.clearcoatMap), + texCoord: material.clearcoatMap.channel + }; + writer.applyTextureTransform(clearcoatMapDef, material.clearcoatMap); + extensionDef.clearcoatTexture = clearcoatMapDef; + } + extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness; + if (material.clearcoatRoughnessMap) { + const clearcoatRoughnessMapDef = { + index: await writer.processTextureAsync(material.clearcoatRoughnessMap), + texCoord: material.clearcoatRoughnessMap.channel + }; + writer.applyTextureTransform(clearcoatRoughnessMapDef, material.clearcoatRoughnessMap); + extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef; + } + if (material.clearcoatNormalMap) { + const clearcoatNormalMapDef = { + index: await writer.processTextureAsync(material.clearcoatNormalMap), + texCoord: material.clearcoatNormalMap.channel + }; + if (material.clearcoatNormalScale.x !== 1) + clearcoatNormalMapDef.scale = material.clearcoatNormalScale.x; + writer.applyTextureTransform(clearcoatNormalMapDef, material.clearcoatNormalMap); + extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef; + } + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsDispersionExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_dispersion"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.dispersion === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.dispersion = material.dispersion; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsIridescenceExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_iridescence"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.iridescence === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.iridescenceFactor = material.iridescence; + if (material.iridescenceMap) { + const iridescenceMapDef = { + index: await writer.processTextureAsync(material.iridescenceMap), + texCoord: material.iridescenceMap.channel + }; + writer.applyTextureTransform(iridescenceMapDef, material.iridescenceMap); + extensionDef.iridescenceTexture = iridescenceMapDef; + } + extensionDef.iridescenceIor = material.iridescenceIOR; + extensionDef.iridescenceThicknessMinimum = material.iridescenceThicknessRange[0]; + extensionDef.iridescenceThicknessMaximum = material.iridescenceThicknessRange[1]; + if (material.iridescenceThicknessMap) { + const iridescenceThicknessMapDef = { + index: await writer.processTextureAsync(material.iridescenceThicknessMap), + texCoord: material.iridescenceThicknessMap.channel + }; + writer.applyTextureTransform(iridescenceThicknessMapDef, material.iridescenceThicknessMap); + extensionDef.iridescenceThicknessTexture = iridescenceThicknessMapDef; + } + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsTransmissionExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_transmission"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.transmission === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.transmissionFactor = material.transmission; + if (material.transmissionMap) { + const transmissionMapDef = { + index: await writer.processTextureAsync(material.transmissionMap), + texCoord: material.transmissionMap.channel + }; + writer.applyTextureTransform(transmissionMapDef, material.transmissionMap); + extensionDef.transmissionTexture = transmissionMapDef; + } + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsVolumeExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_volume"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.transmission === 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.thicknessFactor = material.thickness; + if (material.thicknessMap) { + const thicknessMapDef = { + index: await writer.processTextureAsync(material.thicknessMap), + texCoord: material.thicknessMap.channel + }; + writer.applyTextureTransform(thicknessMapDef, material.thicknessMap); + extensionDef.thicknessTexture = thicknessMapDef; + } + if (material.attenuationDistance !== Infinity) { + extensionDef.attenuationDistance = material.attenuationDistance; + } + extensionDef.attenuationColor = material.attenuationColor.toArray(); + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsIorExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_ior"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.ior === 1.5) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.ior = material.ior; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsSpecularExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_specular"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.specularIntensity === 1 && material.specularColor.equals(DEFAULT_SPECULAR_COLOR) && !material.specularIntensityMap && !material.specularColorMap) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.specularIntensityMap) { + const specularIntensityMapDef = { + index: await writer.processTextureAsync(material.specularIntensityMap), + texCoord: material.specularIntensityMap.channel + }; + writer.applyTextureTransform(specularIntensityMapDef, material.specularIntensityMap); + extensionDef.specularTexture = specularIntensityMapDef; + } + if (material.specularColorMap) { + const specularColorMapDef = { + index: await writer.processTextureAsync(material.specularColorMap), + texCoord: material.specularColorMap.channel + }; + writer.applyTextureTransform(specularColorMapDef, material.specularColorMap); + extensionDef.specularColorTexture = specularColorMapDef; + } + extensionDef.specularFactor = material.specularIntensity; + extensionDef.specularColorFactor = material.specularColor.toArray(); + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsSheenExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_sheen"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.sheen == 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.sheenRoughnessMap) { + const sheenRoughnessMapDef = { + index: await writer.processTextureAsync(material.sheenRoughnessMap), + texCoord: material.sheenRoughnessMap.channel + }; + writer.applyTextureTransform(sheenRoughnessMapDef, material.sheenRoughnessMap); + extensionDef.sheenRoughnessTexture = sheenRoughnessMapDef; + } + if (material.sheenColorMap) { + const sheenColorMapDef = { + index: await writer.processTextureAsync(material.sheenColorMap), + texCoord: material.sheenColorMap.channel + }; + writer.applyTextureTransform(sheenColorMapDef, material.sheenColorMap); + extensionDef.sheenColorTexture = sheenColorMapDef; + } + extensionDef.sheenRoughnessFactor = material.sheenRoughness; + extensionDef.sheenColorFactor = material.sheenColor.toArray(); + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsAnisotropyExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_anisotropy"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshPhysicalMaterial || material.anisotropy == 0) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.anisotropyMap) { + const anisotropyMapDef = { index: await writer.processTextureAsync(material.anisotropyMap) }; + writer.applyTextureTransform(anisotropyMapDef, material.anisotropyMap); + extensionDef.anisotropyTexture = anisotropyMapDef; + } + extensionDef.anisotropyStrength = material.anisotropy; + extensionDef.anisotropyRotation = material.anisotropyRotation; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsEmissiveStrengthExtension { + constructor(writer) { + this.writer = writer; + this.name = "KHR_materials_emissive_strength"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshStandardMaterial || material.emissiveIntensity === 1) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + extensionDef.emissiveStrength = material.emissiveIntensity; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMaterialsBumpExtension { + constructor(writer) { + this.writer = writer; + this.name = "EXT_materials_bump"; + } + async writeMaterialAsync(material, materialDef) { + if (!material.isMeshStandardMaterial || material.bumpScale === 1 && !material.bumpMap) + return; + const writer = this.writer; + const extensionsUsed = writer.extensionsUsed; + const extensionDef = {}; + if (material.bumpMap) { + const bumpMapDef = { + index: await writer.processTextureAsync(material.bumpMap), + texCoord: material.bumpMap.channel + }; + writer.applyTextureTransform(bumpMapDef, material.bumpMap); + extensionDef.bumpTexture = bumpMapDef; + } + extensionDef.bumpFactor = material.bumpScale; + materialDef.extensions = materialDef.extensions || {}; + materialDef.extensions[this.name] = extensionDef; + extensionsUsed[this.name] = true; + } +} + +class GLTFMeshGpuInstancing { + constructor(writer) { + this.writer = writer; + this.name = "EXT_mesh_gpu_instancing"; + } + writeNode(object, nodeDef) { + if (!object.isInstancedMesh) + return; + const writer = this.writer; + const mesh = object; + const translationAttr = new Float32Array(mesh.count * 3); + const rotationAttr = new Float32Array(mesh.count * 4); + const scaleAttr = new Float32Array(mesh.count * 3); + const matrix = new Matrix4; + const position2 = new Vector3; + const quaternion = new Quaternion; + const scale2 = new Vector3; + for (let i = 0;i < mesh.count; i++) { + mesh.getMatrixAt(i, matrix); + matrix.decompose(position2, quaternion, scale2); + position2.toArray(translationAttr, i * 3); + quaternion.toArray(rotationAttr, i * 4); + scale2.toArray(scaleAttr, i * 3); + } + const attributes = { + TRANSLATION: writer.processAccessor(new BufferAttribute(translationAttr, 3)), + ROTATION: writer.processAccessor(new BufferAttribute(rotationAttr, 4)), + SCALE: writer.processAccessor(new BufferAttribute(scaleAttr, 3)) + }; + if (mesh.instanceColor) + attributes._COLOR_0 = writer.processAccessor(mesh.instanceColor); + nodeDef.extensions = nodeDef.extensions || {}; + nodeDef.extensions[this.name] = { attributes }; + writer.extensionsUsed[this.name] = true; + writer.extensionsRequired[this.name] = true; + } +} +GLTFExporter.Utils = { + insertKeyframe: function(track, time2) { + const tolerance = 0.001; + const valueSize = track.getValueSize(); + const times = new track.TimeBufferType(track.times.length + 1); + const values2 = new track.ValueBufferType(track.values.length + valueSize); + const interpolant = track.createInterpolant(new track.ValueBufferType(valueSize)); + let index2; + if (track.times.length === 0) { + times[0] = time2; + for (let i = 0;i < valueSize; i++) { + values2[i] = 0; + } + index2 = 0; + } else if (time2 < track.times[0]) { + if (Math.abs(track.times[0] - time2) < tolerance) + return 0; + times[0] = time2; + times.set(track.times, 1); + values2.set(interpolant.evaluate(time2), 0); + values2.set(track.values, valueSize); + index2 = 0; + } else if (time2 > track.times[track.times.length - 1]) { + if (Math.abs(track.times[track.times.length - 1] - time2) < tolerance) { + return track.times.length - 1; + } + times[times.length - 1] = time2; + times.set(track.times, 0); + values2.set(track.values, 0); + values2.set(interpolant.evaluate(time2), track.values.length); + index2 = times.length - 1; + } else { + for (let i = 0;i < track.times.length; i++) { + if (Math.abs(track.times[i] - time2) < tolerance) + return i; + if (track.times[i] < time2 && track.times[i + 1] > time2) { + times.set(track.times.slice(0, i + 1), 0); + times[i + 1] = time2; + times.set(track.times.slice(i + 1), i + 2); + values2.set(track.values.slice(0, (i + 1) * valueSize), 0); + values2.set(interpolant.evaluate(time2), (i + 1) * valueSize); + values2.set(track.values.slice((i + 1) * valueSize), (i + 2) * valueSize); + index2 = i + 1; + break; + } + } + } + track.times = times; + track.values = values2; + return index2; + }, + mergeMorphTargetTracks: function(clip, root) { + const tracks = []; + const mergedTracks = {}; + const sourceTracks = clip.tracks; + for (let i = 0;i < sourceTracks.length; ++i) { + let sourceTrack = sourceTracks[i]; + const sourceTrackBinding = PropertyBinding.parseTrackName(sourceTrack.name); + const sourceTrackNode = PropertyBinding.findNode(root, sourceTrackBinding.nodeName); + if (sourceTrackBinding.propertyName !== "morphTargetInfluences" || sourceTrackBinding.propertyIndex === undefined) { + tracks.push(sourceTrack); + continue; + } + if (sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear) { + if (sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { + throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation."); + } + console.warn("THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead."); + sourceTrack = sourceTrack.clone(); + sourceTrack.setInterpolation(InterpolateLinear); + } + const targetCount = sourceTrackNode.morphTargetInfluences.length; + const targetIndex = sourceTrackNode.morphTargetDictionary[sourceTrackBinding.propertyIndex]; + if (targetIndex === undefined) { + throw new Error("THREE.GLTFExporter: Morph target name not found: " + sourceTrackBinding.propertyIndex); + } + let mergedTrack; + if (mergedTracks[sourceTrackNode.uuid] === undefined) { + mergedTrack = sourceTrack.clone(); + const values2 = new mergedTrack.ValueBufferType(targetCount * mergedTrack.times.length); + for (let j = 0;j < mergedTrack.times.length; j++) { + values2[j * targetCount + targetIndex] = mergedTrack.values[j]; + } + mergedTrack.name = (sourceTrackBinding.nodeName || "") + ".morphTargetInfluences"; + mergedTrack.values = values2; + mergedTracks[sourceTrackNode.uuid] = mergedTrack; + tracks.push(mergedTrack); + continue; + } + const sourceInterpolant = sourceTrack.createInterpolant(new sourceTrack.ValueBufferType(1)); + mergedTrack = mergedTracks[sourceTrackNode.uuid]; + for (let j = 0;j < mergedTrack.times.length; j++) { + mergedTrack.values[j * targetCount + targetIndex] = sourceInterpolant.evaluate(mergedTrack.times[j]); + } + for (let j = 0;j < sourceTrack.times.length; j++) { + const keyframeIndex = this.insertKeyframe(mergedTrack, sourceTrack.times[j]); + mergedTrack.values[keyframeIndex * targetCount + targetIndex] = sourceTrack.values[j]; + } + } + clip.tracks = tracks; + return clip; + }, + toFloat32BufferAttribute: function(srcAttribute) { + const dstAttribute = new BufferAttribute(new Float32Array(srcAttribute.count * srcAttribute.itemSize), srcAttribute.itemSize, false); + if (!srcAttribute.normalized && !srcAttribute.isInterleavedBufferAttribute) { + dstAttribute.array.set(srcAttribute.array); + return dstAttribute; + } + for (let i = 0, il = srcAttribute.count;i < il; i++) { + for (let j = 0;j < srcAttribute.itemSize; j++) { + dstAttribute.setComponent(i, j, srcAttribute.getComponent(i, j)); + } + } + return dstAttribute; + } +}; +// node_modules/three/examples/jsm/libs/ktx-parse.module.js +var t = 0; +var n = 2; +var g = 1; +var u = 2; +var T = 0; +var C2 = 1; +var R = 10; +var it = 0; +var ct = 9; +var yt = 15; +var xt2 = 16; +var wt = 22; +var Ft = 37; +var Ct = 43; +var te2 = 76; +var ae2 = 83; +var ge = 97; +var ue2 = 100; +var we = 103; +var Ae = 109; +var In = 165; +var Sn = 166; +var pi = 1000066000; +class Ii { + constructor() { + this.vkFormat = 0, this.typeSize = 1, this.pixelWidth = 0, this.pixelHeight = 0, this.pixelDepth = 0, this.layerCount = 0, this.faceCount = 1, this.supercompressionScheme = 0, this.levels = [], this.dataFormatDescriptor = [{ vendorId: 0, descriptorType: 0, descriptorBlockSize: 0, versionNumber: 2, colorModel: 0, colorPrimaries: 1, transferFunction: 2, flags: 0, texelBlockDimension: [0, 0, 0, 0], bytesPlane: [0, 0, 0, 0, 0, 0, 0, 0], samples: [] }], this.keyValue = {}, this.globalData = null; + } +} + +class Si { + constructor(t2, e, n2, i) { + this._dataView = undefined, this._littleEndian = undefined, this._offset = undefined, this._dataView = new DataView(t2.buffer, t2.byteOffset + e, n2), this._littleEndian = i, this._offset = 0; + } + _nextUint8() { + const t2 = this._dataView.getUint8(this._offset); + return this._offset += 1, t2; + } + _nextUint16() { + const t2 = this._dataView.getUint16(this._offset, this._littleEndian); + return this._offset += 2, t2; + } + _nextUint32() { + const t2 = this._dataView.getUint32(this._offset, this._littleEndian); + return this._offset += 4, t2; + } + _nextUint64() { + const t2 = this._dataView.getUint32(this._offset, this._littleEndian) + 2 ** 32 * this._dataView.getUint32(this._offset + 4, this._littleEndian); + return this._offset += 8, t2; + } + _nextInt32() { + const t2 = this._dataView.getInt32(this._offset, this._littleEndian); + return this._offset += 4, t2; + } + _nextUint8Array(t2) { + const e = new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + this._offset, t2); + return this._offset += t2, e; + } + _skip(t2) { + return this._offset += t2, this; + } + _scan(t2, e) { + e === undefined && (e = 0); + const n2 = this._offset; + let i = 0; + for (;this._dataView.getUint8(this._offset) !== e && i < t2; ) + i++, this._offset++; + return i < t2 && this._offset++, new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + n2, i); + } +} +var Fi = new Uint8Array([0]); +var Oi = [171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10]; +function Ti(t2) { + return new TextDecoder().decode(t2); +} +function Pi2(t2) { + const e = new Uint8Array(t2.buffer, t2.byteOffset, Oi.length); + if (e[0] !== Oi[0] || e[1] !== Oi[1] || e[2] !== Oi[2] || e[3] !== Oi[3] || e[4] !== Oi[4] || e[5] !== Oi[5] || e[6] !== Oi[6] || e[7] !== Oi[7] || e[8] !== Oi[8] || e[9] !== Oi[9] || e[10] !== Oi[10] || e[11] !== Oi[11]) + throw new Error("Missing KTX 2.0 identifier."); + const n2 = new Ii, i = 17 * Uint32Array.BYTES_PER_ELEMENT, s = new Si(t2, Oi.length, i, true); + n2.vkFormat = s._nextUint32(), n2.typeSize = s._nextUint32(), n2.pixelWidth = s._nextUint32(), n2.pixelHeight = s._nextUint32(), n2.pixelDepth = s._nextUint32(), n2.layerCount = s._nextUint32(), n2.faceCount = s._nextUint32(); + const a = s._nextUint32(); + n2.supercompressionScheme = s._nextUint32(); + const r = s._nextUint32(), o = s._nextUint32(), l = s._nextUint32(), f = s._nextUint32(), h = s._nextUint64(), U = s._nextUint64(), c = new Si(t2, Oi.length + i, 3 * a * 8, true); + for (let e2 = 0;e2 < a; e2++) + n2.levels.push({ levelData: new Uint8Array(t2.buffer, t2.byteOffset + c._nextUint64(), c._nextUint64()), uncompressedByteLength: c._nextUint64() }); + const _2 = new Si(t2, r, o, true), p = { vendorId: _2._skip(4)._nextUint16(), descriptorType: _2._nextUint16(), versionNumber: _2._nextUint16(), descriptorBlockSize: _2._nextUint16(), colorModel: _2._nextUint8(), colorPrimaries: _2._nextUint8(), transferFunction: _2._nextUint8(), flags: _2._nextUint8(), texelBlockDimension: [_2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8()], bytesPlane: [_2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8()], samples: [] }, g2 = (p.descriptorBlockSize / 4 - 6) / 4; + for (let t3 = 0;t3 < g2; t3++) { + const e2 = { bitOffset: _2._nextUint16(), bitLength: _2._nextUint8(), channelType: _2._nextUint8(), samplePosition: [_2._nextUint8(), _2._nextUint8(), _2._nextUint8(), _2._nextUint8()], sampleLower: -Infinity, sampleUpper: Infinity }; + 64 & e2.channelType ? (e2.sampleLower = _2._nextInt32(), e2.sampleUpper = _2._nextInt32()) : (e2.sampleLower = _2._nextUint32(), e2.sampleUpper = _2._nextUint32()), p.samples[t3] = e2; + } + n2.dataFormatDescriptor.length = 0, n2.dataFormatDescriptor.push(p); + const y = new Si(t2, l, f, true); + for (;y._offset < f; ) { + const t3 = y._nextUint32(), e2 = y._scan(t3), i2 = Ti(e2); + if (n2.keyValue[i2] = y._nextUint8Array(t3 - e2.byteLength - 1), i2.match(/^ktx/i)) { + const t4 = Ti(n2.keyValue[i2]); + n2.keyValue[i2] = t4.substring(0, t4.lastIndexOf("\x00")); + } + y._skip(t3 % 4 ? 4 - t3 % 4 : 0); + } + if (U <= 0) + return n2; + const x = new Si(t2, h, U, true), u2 = x._nextUint16(), b = x._nextUint16(), d = x._nextUint32(), w = x._nextUint32(), m = x._nextUint32(), D = x._nextUint32(), B = []; + for (let t3 = 0;t3 < a; t3++) + B.push({ imageFlags: x._nextUint32(), rgbSliceByteOffset: x._nextUint32(), rgbSliceByteLength: x._nextUint32(), alphaSliceByteOffset: x._nextUint32(), alphaSliceByteLength: x._nextUint32() }); + const L = h + x._offset, v = L + d, A = v + w, k2 = A + m, V2 = new Uint8Array(t2.buffer, t2.byteOffset + L, d), I2 = new Uint8Array(t2.buffer, t2.byteOffset + v, w), S = new Uint8Array(t2.buffer, t2.byteOffset + A, m), F = new Uint8Array(t2.buffer, t2.byteOffset + k2, D); + return n2.globalData = { endpointCount: u2, selectorCount: b, imageDescs: B, endpointsData: V2, selectorsData: I2, tablesData: S, extendedData: F }, n2; +} + +// node_modules/three/examples/jsm/exporters/KTX2Exporter.js +var VK_FORMAT_MAP = { + [RGBAFormat]: { + [FloatType]: { + [NoColorSpace]: Ae, + [LinearSRGBColorSpace]: Ae + }, + [HalfFloatType]: { + [NoColorSpace]: ge, + [LinearSRGBColorSpace]: ge + }, + [UnsignedByteType]: { + [NoColorSpace]: Ft, + [LinearSRGBColorSpace]: Ft, + [SRGBColorSpace]: Ct + } + }, + [RGFormat]: { + [FloatType]: { + [NoColorSpace]: we, + [LinearSRGBColorSpace]: we + }, + [HalfFloatType]: { + [NoColorSpace]: ae2, + [LinearSRGBColorSpace]: ae2 + }, + [UnsignedByteType]: { + [NoColorSpace]: xt2, + [LinearSRGBColorSpace]: xt2, + [SRGBColorSpace]: wt + } + }, + [RedFormat]: { + [FloatType]: { + [NoColorSpace]: ue2, + [LinearSRGBColorSpace]: ue2 + }, + [HalfFloatType]: { + [NoColorSpace]: te2, + [LinearSRGBColorSpace]: te2 + }, + [UnsignedByteType]: { + [NoColorSpace]: ct, + [LinearSRGBColorSpace]: ct, + [SRGBColorSpace]: yt + } + } +}; +var KHR_DF_CHANNEL_SAMPLE_LOWER_UPPER = { + [FloatType]: [3212836864, 1065353216], + [HalfFloatType]: [3212836864, 1065353216], + [UnsignedByteType]: [0, 255] +}; +// node_modules/three/examples/jsm/math/ConvexHull.js +var _v13 = new Vector3; +var _line3 = new Line3; +var _plane3 = new Plane; +var _closestPoint = new Vector3; +var _triangle2 = new Triangle; +// node_modules/three/examples/jsm/geometries/ParametricGeometry.js +class ParametricGeometry extends BufferGeometry { + constructor(func = (u2, v, target) => target.set(u2, v, Math.cos(u2) * Math.sin(v)), slices = 8, stacks = 8) { + super(); + this.type = "ParametricGeometry"; + this.parameters = { + func, + slices, + stacks + }; + const indices = []; + const vertices = []; + const normals = []; + const uvs = []; + const EPS = 0.00001; + const normal = new Vector3; + const p0 = new Vector3, p1 = new Vector3; + const pu = new Vector3, pv = new Vector3; + const sliceCount = slices + 1; + for (let i = 0;i <= stacks; i++) { + const v = i / stacks; + for (let j2 = 0;j2 <= slices; j2++) { + const u2 = j2 / slices; + func(u2, v, p0); + vertices.push(p0.x, p0.y, p0.z); + if (u2 - EPS >= 0) { + func(u2 - EPS, v, p1); + pu.subVectors(p0, p1); + } else { + func(u2 + EPS, v, p1); + pu.subVectors(p1, p0); + } + if (v - EPS >= 0) { + func(u2, v - EPS, p1); + pv.subVectors(p0, p1); + } else { + func(u2, v + EPS, p1); + pv.subVectors(p1, p0); + } + normal.crossVectors(pu, pv).normalize(); + normals.push(normal.x, normal.y, normal.z); + uvs.push(u2, v); + } + } + for (let i = 0;i < stacks; i++) { + for (let j2 = 0;j2 < slices; j2++) { + const a = i * sliceCount + j2; + const b = i * sliceCount + j2 + 1; + const c = (i + 1) * sliceCount + j2 + 1; + const d = (i + 1) * sliceCount + j2; + indices.push(a, b, d); + indices.push(b, c, d); + } + } + this.setIndex(indices); + this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); + this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); + this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); + } + copy(source) { + super.copy(source); + this.parameters = Object.assign({}, source.parameters); + return this; + } +} + +// node_modules/three/examples/jsm/geometries/ParametricGeometries.js +var ParametricGeometries = { + klein: function(v, u2, target) { + u2 *= Math.PI; + v *= 2 * Math.PI; + u2 = u2 * 2; + let x2, z; + if (u2 < Math.PI) { + x2 = 3 * Math.cos(u2) * (1 + Math.sin(u2)) + 2 * (1 - Math.cos(u2) / 2) * Math.cos(u2) * Math.cos(v); + z = -8 * Math.sin(u2) - 2 * (1 - Math.cos(u2) / 2) * Math.sin(u2) * Math.cos(v); + } else { + x2 = 3 * Math.cos(u2) * (1 + Math.sin(u2)) + 2 * (1 - Math.cos(u2) / 2) * Math.cos(v + Math.PI); + z = -8 * Math.sin(u2); + } + const y = -2 * (1 - Math.cos(u2) / 2) * Math.sin(v); + target.set(x2, y, z); + }, + plane: function(width2, height2) { + return function(u2, v, target) { + const x2 = u2 * width2; + const y = 0; + const z = v * height2; + target.set(x2, y, z); + }; + }, + mobius: function(u2, t2, target) { + u2 = u2 - 0.5; + const v = 2 * Math.PI * t2; + const a = 2; + const x2 = Math.cos(v) * (a + u2 * Math.cos(v / 2)); + const y = Math.sin(v) * (a + u2 * Math.cos(v / 2)); + const z = u2 * Math.sin(v / 2); + target.set(x2, y, z); + }, + mobius3d: function(u2, t2, target) { + u2 *= Math.PI; + t2 *= 2 * Math.PI; + u2 = u2 * 2; + const phi = u2 / 2; + const major = 2.25, a = 0.125, b = 0.65; + let x2 = a * Math.cos(t2) * Math.cos(phi) - b * Math.sin(t2) * Math.sin(phi); + const z = a * Math.cos(t2) * Math.sin(phi) + b * Math.sin(t2) * Math.cos(phi); + const y = (major + x2) * Math.sin(u2); + x2 = (major + x2) * Math.cos(u2); + target.set(x2, y, z); + } +}; +ParametricGeometries.TubeGeometry = class TubeGeometry2 extends ParametricGeometry { + constructor(path, segments = 64, radius = 1, segmentsRadius = 8, closed = false) { + const numpoints = segments + 1; + const frames2 = path.computeFrenetFrames(segments, closed), tangents = frames2.tangents, normals = frames2.normals, binormals = frames2.binormals; + const position2 = new Vector3; + function ParametricTube(u2, v, target) { + v *= 2 * Math.PI; + const i = Math.floor(u2 * (numpoints - 1)); + path.getPointAt(u2, position2); + const normal = normals[i]; + const binormal = binormals[i]; + const cx = -radius * Math.cos(v); + const cy = radius * Math.sin(v); + position2.x += cx * normal.x + cy * binormal.x; + position2.y += cx * normal.y + cy * binormal.y; + position2.z += cx * normal.z + cy * binormal.z; + target.copy(position2); + } + super(ParametricTube, segments, segmentsRadius); + this.tangents = tangents; + this.normals = normals; + this.binormals = binormals; + this.path = path; + this.segments = segments; + this.radius = radius; + this.segmentsRadius = segmentsRadius; + this.closed = closed; + } +}; +ParametricGeometries.TorusKnotGeometry = class TorusKnotGeometry2 extends ParametricGeometries.TubeGeometry { + constructor(radius = 200, tube = 40, segmentsT = 64, segmentsR = 8, p = 2, q2 = 3) { + + class TorusKnotCurve extends Curve { + getPoint(t2, optionalTarget = new Vector3) { + const point = optionalTarget; + t2 *= Math.PI * 2; + const r = 0.5; + const x2 = (1 + r * Math.cos(q2 * t2)) * Math.cos(p * t2); + const y = (1 + r * Math.cos(q2 * t2)) * Math.sin(p * t2); + const z = r * Math.sin(q2 * t2); + return point.set(x2, y, z).multiplyScalar(radius); + } + } + const segments = segmentsT; + const radiusSegments = segmentsR; + const extrudePath = new TorusKnotCurve; + super(extrudePath, segments, tube, radiusSegments, true, false); + this.radius = radius; + this.tube = tube; + this.segmentsT = segmentsT; + this.segmentsR = segmentsR; + this.p = p; + this.q = q2; + } +}; +ParametricGeometries.SphereGeometry = class SphereGeometry2 extends ParametricGeometry { + constructor(size, u2, v) { + function sphere(u3, v2, target) { + u3 *= Math.PI; + v2 *= 2 * Math.PI; + const x2 = size * Math.sin(u3) * Math.cos(v2); + const y = size * Math.sin(u3) * Math.sin(v2); + const z = size * Math.cos(u3); + target.set(x2, y, z); + } + super(sphere, u2, v); + } +}; +ParametricGeometries.PlaneGeometry = class PlaneGeometry2 extends ParametricGeometry { + constructor(width2, depth, segmentsWidth, segmentsDepth) { + function plane(u2, v, target) { + const x2 = u2 * width2; + const y = 0; + const z = v * depth; + target.set(x2, y, z); + } + super(plane, segmentsWidth, segmentsDepth); + } +}; +// node_modules/three/examples/jsm/geometries/RoundedBoxGeometry.js +var _tempNormal = new Vector3; +// node_modules/three/examples/jsm/utils/BufferGeometryUtils.js +function toTrianglesDrawMode(geometry, drawMode) { + if (drawMode === TrianglesDrawMode) { + console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."); + return geometry; + } + if (drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode) { + let index2 = geometry.getIndex(); + if (index2 === null) { + const indices = []; + const position2 = geometry.getAttribute("position"); + if (position2 !== undefined) { + for (let i = 0;i < position2.count; i++) { + indices.push(i); + } + geometry.setIndex(indices); + index2 = geometry.getIndex(); + } else { + console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."); + return geometry; + } + } + const numberOfTriangles = index2.count - 2; + const newIndices = []; + if (drawMode === TriangleFanDrawMode) { + for (let i = 1;i <= numberOfTriangles; i++) { + newIndices.push(index2.getX(0)); + newIndices.push(index2.getX(i)); + newIndices.push(index2.getX(i + 1)); + } + } else { + for (let i = 0;i < numberOfTriangles; i++) { + if (i % 2 === 0) { + newIndices.push(index2.getX(i)); + newIndices.push(index2.getX(i + 1)); + newIndices.push(index2.getX(i + 2)); + } else { + newIndices.push(index2.getX(i + 2)); + newIndices.push(index2.getX(i + 1)); + newIndices.push(index2.getX(i)); + } + } + } + if (newIndices.length / 3 !== numberOfTriangles) { + console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles."); + } + const newGeometry = geometry.clone(); + newGeometry.setIndex(newIndices); + newGeometry.clearGroups(); + return newGeometry; + } else { + console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:", drawMode); + return geometry; + } +} +// node_modules/three/examples/jsm/helpers/VertexNormalsHelper.js +var _v14 = new Vector3; +var _v24 = new Vector3; +var _normalMatrix2 = new Matrix3; +// node_modules/three/examples/jsm/helpers/VertexTangentsHelper.js +var _v15 = new Vector3; +var _v25 = new Vector3; +// node_modules/three/examples/jsm/interactive/HTMLMesh.js +var canvases = new WeakMap; +// node_modules/three/examples/jsm/interactive/InteractiveGroup.js +var _pointer2 = new Vector2; +var _raycaster3 = new Raycaster; +// node_modules/three/examples/jsm/interactive/SelectionBox.js +var _frustum2 = new Frustum; +var _center3 = new Vector3; +var _tmpPoint = new Vector3; +var _vecNear = new Vector3; +var _vecTopLeft = new Vector3; +var _vecTopRight = new Vector3; +var _vecDownRight = new Vector3; +var _vecDownLeft = new Vector3; +var _vecFarTopLeft = new Vector3; +var _vecFarTopRight = new Vector3; +var _vecFarDownRight = new Vector3; +var _vecFarDownLeft = new Vector3; +var _vectemp1 = new Vector3; +var _vectemp2 = new Vector3; +var _vectemp3 = new Vector3; +var _matrix3 = new Matrix4; +var _quaternion3 = new Quaternion; +var _scale2 = new Vector3; +// node_modules/three/examples/jsm/lights/RectAreaLightTexturesLib.js +class RectAreaLightTexturesLib { + static init() { + const LTC_MAT_1 = [1, 0, 0, 0.00002, 1, 0, 0, 0.000503905, 1, 0, 0, 0.00201562, 1, 0, 0, 0.00453516, 1, 0, 0, 0.00806253, 1, 0, 0, 0.0125978, 1, 0, 0, 0.018141, 1, 0, 0, 0.0246924, 1, 0, 0, 0.0322525, 1, 0, 0, 0.0408213, 1, 0, 0, 0.0503999, 1, 0, 0, 0.0609894, 1, 0, 0, 0.0725906, 1, 0, 0, 0.0852058, 1, 0, 0, 0.0988363, 1, 0, 0, 0.113484, 1, 0, 0, 0.129153, 1, 0, 0, 0.145839, 1, 0, 0, 0.163548, 1, 0, 0, 0.182266, 1, 0, 0, 0.201942, 1, 0, 0, 0.222314, 1, 0, 0, 0.241906, 1, 0, 0, 0.262314, 1, 0, 0, 0.285754, 1, 0, 0, 0.310159, 1, 0, 0, 0.335426, 1, 0, 0, 0.361341, 1, 0, 0, 0.387445, 1, 0, 0, 0.412784, 1, 0, 0, 0.438197, 1, 0, 0, 0.466966, 1, 0, 0, 0.49559, 1, 0, 0, 0.523448, 1, 0, 0, 0.549938, 1, 0, 0, 0.57979, 1, 0, 0, 0.608746, 1, 0, 0, 0.636185, 1, 0, 0, 0.664748, 1, 0, 0, 0.69313, 1, 0, 0, 0.71966, 1, 0, 0, 0.747662, 1, 0, 0, 0.774023, 1, 0, 0, 0.799775, 1, 0, 0, 0.825274, 1, 0, 0, 0.849156, 1, 0, 0, 0.873248, 1, 0, 0, 0.89532, 1, 0, 0, 0.917565, 1, 0, 0, 0.937863, 1, 0, 0, 0.958139, 1, 0, 0, 0.976563, 1, 0, 0, 0.994658, 1, 0, 0, 1.0112, 1, 0, 0, 1.02712, 1, 0, 0, 1.04189, 1, 0, 0, 1.05568, 1, 0, 0, 1.06877, 1, 0, 0, 1.08058, 1, 0, 0, 1.09194, 1, 0, 0, 1.10191, 1, 0, 0, 1.11161, 1, 0, 0, 1.1199, 1, 0, 0, 1.12813, 0.999547, -0.000000448815, 0.0224417, 0.0000199902, 0.999495, -0.0000113079, 0.0224406, 0.000503651, 0.999496, -0.0000452317, 0.0224406, 0.00201461, 0.999496, -0.000101772, 0.0224406, 0.00453287, 0.999495, -0.000180928, 0.0224406, 0.00805845, 0.999497, -0.000282702, 0.0224406, 0.0125914, 0.999496, -0.000407096, 0.0224406, 0.0181319, 0.999498, -0.000554114, 0.0224406, 0.02468, 0.999499, -0.000723768, 0.0224406, 0.0322363, 0.999495, -0.000916058, 0.0224405, 0.0408009, 0.999499, -0.00113101, 0.0224408, 0.050375, 0.999494, -0.00136863, 0.0224405, 0.0609586, 0.999489, -0.00162896, 0.0224401, 0.0725537, 0.999489, -0.00191201, 0.0224414, 0.0851619, 0.999498, -0.00221787, 0.0224413, 0.0987867, 0.999492, -0.00254642, 0.0224409, 0.113426, 0.999507, -0.00289779, 0.0224417, 0.129088, 0.999494, -0.0032716, 0.0224386, 0.145767, 0.999546, -0.0036673, 0.0224424, 0.163472, 0.999543, -0.00408166, 0.0224387, 0.182182, 0.999499, -0.00450056, 0.0224338, 0.201843, 0.999503, -0.00483661, 0.0224203, 0.222198, 0.999546, -0.00452928, 0.022315, 0.241714, 0.999508, -0.00587403, 0.0224329, 0.262184, 0.999509, -0.00638806, 0.0224271, 0.285609, 0.999501, -0.00691028, 0.0224166, 0.309998, 0.999539, -0.00741979, 0.0223989, 0.335262, 0.999454, -0.00786282, 0.0223675, 0.361154, 0.999529, -0.00811928, 0.0222828, 0.387224, 0.999503, -0.00799941, 0.0221063, 0.41252, 0.999561, -0.00952753, 0.0223057, 0.438006, 0.999557, -0.0099134, 0.0222065, 0.466735, 0.999541, -0.0100935, 0.0220402, 0.495332, 0.999562, -0.00996821, 0.0218067, 0.523197, 0.999556, -0.0105031, 0.0217096, 0.550223, 0.999561, -0.0114191, 0.0217215, 0.579498, 0.999588, -0.0111818, 0.0213357, 0.608416, 0.999633, -0.0107725, 0.0208689, 0.635965, 0.999527, -0.0121671, 0.0210149, 0.664476, 0.999508, -0.0116005, 0.020431, 0.692786, 0.999568, -0.0115604, 0.0199791, 0.719709, 0.999671, -0.0121117, 0.0197415, 0.74737, 0.999688, -0.0110769, 0.0188846, 0.773692, 0.99962, -0.0122368, 0.0188452, 0.799534, 0.999823, -0.0110325, 0.0178001, 0.825046, 0.999599, -0.0114923, 0.0174221, 0.849075, 0.999619, -0.0105923, 0.0164345, 0.872999, 0.999613, -0.0105988, 0.0158227, 0.895371, 0.99964, -0.00979861, 0.0148131, 0.917364, 0.99977, -0.00967238, 0.0140721, 0.938002, 0.999726, -0.00869175, 0.0129543, 0.957917, 0.99973, -0.00866872, 0.0122329, 0.976557, 0.999773, -0.00731956, 0.0108958, 0.994459, 0.999811, -0.00756027, 0.0102715, 1.01118, 0.999862, -0.00583732, 0.00878781, 1.02701, 0.999835, -0.00631438, 0.00827529, 1.04186, 0.999871, -0.00450785, 0.00674583, 1.05569, 0.999867, -0.00486079, 0.00621041, 1.06861, 0.999939, -0.00322072, 0.00478301, 1.08064, 0.999918, -0.00318199, 0.00406395, 1.09181, 1.00003, -0.00193348, 0.00280682, 1.10207, 0.999928, -0.00153729, 0.00198741, 1.11152, 0.999933, -0.000623666, 0.000917714, 1.12009, 1, -0.00000102387, 0.000000907581, 1.12813, 0.997866, -0.000000896716, 0.0448334, 0.0000199584, 0.997987, -0.0000225945, 0.0448389, 0.000502891, 0.997987, -0.0000903781, 0.0448388, 0.00201156, 0.997985, -0.000203351, 0.0448388, 0.00452602, 0.997986, -0.000361514, 0.0448388, 0.00804629, 0.997987, -0.00056487, 0.0448389, 0.0125724, 0.997988, -0.000813423, 0.0448389, 0.0181045, 0.997984, -0.00110718, 0.0448387, 0.0246427, 0.997985, -0.00144616, 0.0448388, 0.0321875, 0.997987, -0.00183038, 0.044839, 0.0407392, 0.997983, -0.00225987, 0.0448387, 0.0502986, 0.997991, -0.00273467, 0.0448389, 0.0608667, 0.997984, -0.00325481, 0.0448384, 0.0724444, 0.998002, -0.00382043, 0.044839, 0.0850348, 0.997997, -0.00443145, 0.0448396, 0.0986372, 0.998007, -0.00508796, 0.0448397, 0.113255, 0.998008, -0.00578985, 0.04484, 0.128891, 0.998003, -0.00653683, 0.0448384, 0.145548, 0.997983, -0.00732713, 0.0448358, 0.163221, 0.997985, -0.00815454, 0.0448358, 0.181899, 0.998005, -0.00898985, 0.0448286, 0.201533, 0.998026, -0.00964404, 0.0447934, 0.221821, 0.998055, -0.00922677, 0.044611, 0.241282, 0.99804, -0.0117361, 0.0448245, 0.261791, 0.998048, -0.0127628, 0.0448159, 0.285181, 0.998088, -0.0138055, 0.0447996, 0.30954, 0.998058, -0.0148206, 0.0447669, 0.334751, 0.998099, -0.0156998, 0.044697, 0.36061, 0.998116, -0.0161976, 0.0445122, 0.386603, 0.998195, -0.015945, 0.0441711, 0.411844, 0.998168, -0.0183947, 0.0444255, 0.43773, 0.998184, -0.0197913, 0.0443809, 0.466009, 0.998251, -0.0201426, 0.0440689, 0.494574, 0.998305, -0.0198847, 0.0435632, 0.522405, 0.998273, -0.0210577, 0.043414, 0.549967, 0.998254, -0.0227901, 0.0433943, 0.578655, 0.998349, -0.0223108, 0.0426529, 0.60758, 0.99843, -0.0223088, 0.042, 0.635524, 0.998373, -0.0241141, 0.0418987, 0.663621, 0.998425, -0.0231446, 0.0408118, 0.691906, 0.998504, -0.0233684, 0.0400565, 0.719339, 0.998443, -0.0241652, 0.0394634, 0.74643, 0.99848, -0.0228715, 0.0380002, 0.773086, 0.998569, -0.023519, 0.0372322, 0.798988, 0.998619, -0.0223108, 0.0356468, 0.824249, 0.998594, -0.0223105, 0.034523, 0.848808, 0.998622, -0.0213426, 0.0328887, 0.87227, 0.998669, -0.0207912, 0.0314374, 0.895157, 0.998705, -0.0198416, 0.0296925, 0.916769, 0.998786, -0.0189168, 0.0279634, 0.937773, 0.998888, -0.0178811, 0.0261597, 0.957431, 0.99906, -0.0166845, 0.0242159, 0.976495, 0.999038, -0.0155464, 0.0222638, 0.994169, 0.999237, -0.0141349, 0.0201967, 1.01112, 0.999378, -0.0129324, 0.0181744, 1.02692, 0.999433, -0.0113192, 0.0159898, 1.04174, 0.999439, -0.0101244, 0.0140385, 1.05559, 0.999614, -0.00837456, 0.0117826, 1.06852, 0.999722, -0.00721769, 0.00983745, 1.08069, 0.999817, -0.00554067, 0.00769002, 1.09176, 0.99983, -0.00426961, 0.005782, 1.10211, 0.999964, -0.00273904, 0.00374503, 1.11152, 1.00001, -0.00136739, 0.00187176, 1.12031, 0.999946, 0.0000393227, -0.000028919, 1.12804, 0.995847, -0.0000013435, 0.0671785, 0.000019916, 0.995464, -0.0000338387, 0.0671527, 0.000501622, 0.99547, -0.000135355, 0.0671531, 0.00200649, 0.995471, -0.00030455, 0.0671532, 0.00451461, 0.99547, -0.000541423, 0.0671531, 0.008026, 0.995471, -0.00084598, 0.0671531, 0.0125407, 0.99547, -0.00121823, 0.0671531, 0.0180589, 0.99547, -0.00165817, 0.0671531, 0.0245806, 0.995463, -0.00216583, 0.0671526, 0.0321062, 0.995468, -0.00274127, 0.0671527, 0.0406366, 0.995474, -0.00338447, 0.0671534, 0.0501717, 0.995473, -0.00409554, 0.0671533, 0.0607131, 0.995478, -0.00487451, 0.0671531, 0.0722618, 0.995476, -0.00572148, 0.0671532, 0.0848191, 0.995477, -0.00663658, 0.0671539, 0.0983882, 0.995498, -0.00761986, 0.0671541, 0.112972, 0.995509, -0.00867094, 0.0671542, 0.128568, 0.995509, -0.00978951, 0.0671531, 0.145183, 0.995503, -0.0109725, 0.0671491, 0.162808, 0.995501, -0.012211, 0.0671465, 0.181441, 0.99553, -0.0134565, 0.0671371, 0.201015, 0.99555, -0.014391, 0.0670831, 0.221206, 0.99558, -0.014351, 0.0668883, 0.240813, 0.995577, -0.0173997, 0.0671055, 0.261257, 0.995602, -0.0191111, 0.0671178, 0.284467, 0.995623, -0.0206705, 0.0670946, 0.308765, 0.995658, -0.022184, 0.0670472, 0.333905, 0.995705, -0.0234832, 0.0669417, 0.359677, 0.995719, -0.0241933, 0.0666714, 0.385554, 0.995786, -0.0243539, 0.066266, 0.410951, 0.995887, -0.0271866, 0.0664367, 0.437163, 0.995944, -0.0296012, 0.0664931, 0.464842, 0.996004, -0.0301045, 0.0660105, 0.49332, 0.996128, -0.0298311, 0.0652694, 0.521131, 0.996253, -0.0316426, 0.0650739, 0.549167, 0.996244, -0.0339043, 0.0649433, 0.57737, 0.996309, -0.033329, 0.0638926, 0.606073, 0.996417, -0.0338935, 0.0630849, 0.634527, 0.996372, -0.0353104, 0.0625083, 0.66256, 0.996542, -0.0348942, 0.0611986, 0.690516, 0.996568, -0.0351614, 0.060069, 0.718317, 0.996711, -0.0354317, 0.0588522, 0.74528, 0.996671, -0.0349513, 0.0571902, 0.772061, 0.996865, -0.0345622, 0.0555321, 0.798089, 0.996802, -0.0342566, 0.0537816, 0.823178, 0.996992, -0.0330862, 0.0516095, 0.847949, 0.996944, -0.0324666, 0.0495537, 0.871431, 0.997146, -0.0309544, 0.0470302, 0.894357, 0.997189, -0.0299372, 0.0446043, 0.916142, 0.997471, -0.0281389, 0.0418812, 0.937193, 0.997515, -0.0268702, 0.0391823, 0.957, 0.997812, -0.0247166, 0.0361338, 0.975936, 0.998027, -0.0233525, 0.0333945, 0.99391, 0.998233, -0.0209839, 0.0301917, 1.01075, 0.998481, -0.0194309, 0.027271, 1.02669, 0.998859, -0.0169728, 0.0240162, 1.04173, 0.99894, -0.0152322, 0.0210517, 1.05551, 0.999132, -0.0127497, 0.0178632, 1.06856, 0.999369, -0.0108282, 0.014787, 1.08054, 0.999549, -0.00845886, 0.0116185, 1.09185, 0.999805, -0.0063937, 0.00867209, 1.10207, 0.99985, -0.00414582, 0.00566823, 1.1117, 0.999912, -0.00207443, 0.00277562, 1.12022, 1.00001, 0.0000870226, -0.000053766, 1.12832, 0.991943, -0.00000178672, 0.0893382, 0.0000198384, 0.991952, -0.0000450183, 0.089339, 0.000499849, 0.991956, -0.000180074, 0.0893394, 0.0019994, 0.991955, -0.000405167, 0.0893393, 0.00449867, 0.991953, -0.000720298, 0.0893391, 0.00799764, 0.991955, -0.00112548, 0.0893393, 0.0124964, 0.991957, -0.0016207, 0.0893395, 0.0179951, 0.991958, -0.00220601, 0.0893396, 0.0244939, 0.991947, -0.00288137, 0.0893385, 0.0319929, 0.991962, -0.00364693, 0.0893399, 0.0404933, 0.991965, -0.00450264, 0.0893399, 0.049995, 0.99198, -0.00544862, 0.0893411, 0.0604995, 0.99197, -0.00648491, 0.0893397, 0.0720074, 0.991976, -0.00761164, 0.089341, 0.0845207, 0.99198, -0.00882891, 0.0893405, 0.0980413, 0.991982, -0.0101367, 0.0893396, 0.112571, 0.992008, -0.011535, 0.0893415, 0.128115, 0.992026, -0.0130228, 0.0893414, 0.144672, 0.992064, -0.0145966, 0.0893418, 0.162241, 0.992041, -0.0162421, 0.0893359, 0.180801, 0.992086, -0.0178888, 0.0893214, 0.200302, 0.992157, -0.0190368, 0.0892401, 0.220332, 0.992181, -0.0195584, 0.0890525, 0.240144, 0.992175, -0.0227257, 0.0892153, 0.260728, 0.99221, -0.0254195, 0.089304, 0.283473, 0.99222, -0.0274883, 0.0892703, 0.307673, 0.992317, -0.0294905, 0.0892027, 0.332729, 0.992374, -0.0311861, 0.0890577, 0.358387, 0.992505, -0.0320656, 0.0886994, 0.384102, 0.992568, -0.0329715, 0.0883198, 0.409767, 0.992675, -0.036006, 0.0883602, 0.436145, 0.992746, -0.0392897, 0.0884591, 0.463217, 0.992873, -0.0399337, 0.0878287, 0.491557, 0.992934, -0.040231, 0.0870108, 0.519516, 0.993091, -0.0422013, 0.0865857, 0.547741, 0.993259, -0.0443503, 0.0861937, 0.575792, 0.993455, -0.0446368, 0.0851187, 0.604233, 0.993497, -0.0454299, 0.0840576, 0.632925, 0.993694, -0.0463296, 0.0829671, 0.660985, 0.993718, -0.0470619, 0.0817185, 0.688714, 0.993973, -0.0468838, 0.0800294, 0.716743, 0.994207, -0.046705, 0.0781286, 0.74377, 0.994168, -0.0469698, 0.0763337, 0.77042, 0.9945, -0.0456816, 0.0738184, 0.796659, 0.994356, -0.0455518, 0.0715545, 0.821868, 0.994747, -0.0439488, 0.0686085, 0.846572, 0.994937, -0.0430056, 0.065869, 0.870435, 0.995142, -0.0413414, 0.0626446, 0.893272, 0.995451, -0.0396521, 0.05929, 0.915376, 0.995445, -0.0378453, 0.0558503, 0.936196, 0.995967, -0.0355219, 0.0520949, 0.956376, 0.996094, -0.0335146, 0.048377, 0.975327, 0.996622, -0.030682, 0.0442575, 0.993471, 0.996938, -0.0285504, 0.0404693, 1.01052, 0.997383, -0.0253399, 0.0360903, 1.02637, 0.997714, -0.0231651, 0.0322176, 1.04139, 0.998249, -0.0198138, 0.0278433, 1.05542, 0.998596, -0.0174337, 0.0238759, 1.06846, 0.998946, -0.0141349, 0.0195944, 1.08056, 0.99928, -0.0115603, 0.0156279, 1.09181, 0.999507, -0.00839065, 0.0114607, 1.10213, 0.999697, -0.005666, 0.00763325, 1.11169, 0.999869, -0.00269902, 0.00364946, 1.12042, 1.00001, 0.0000623836, -0.0000319288, 1.12832, 0.987221, -0.00000222675, 0.111332, 0.0000197456, 0.98739, -0.0000561116, 0.111351, 0.000497563, 0.987448, -0.000224453, 0.111357, 0.00199031, 0.987441, -0.000505019, 0.111357, 0.0044782, 0.987442, -0.000897816, 0.111357, 0.00796129, 0.987442, -0.00140284, 0.111357, 0.0124396, 0.987444, -0.00202012, 0.111357, 0.0179132, 0.987442, -0.00274964, 0.111357, 0.0243824, 0.987446, -0.00359147, 0.111357, 0.0318474, 0.987435, -0.00454562, 0.111356, 0.0403086, 0.987461, -0.00561225, 0.111358, 0.0497678, 0.987458, -0.00679125, 0.111358, 0.0602239, 0.987443, -0.0080828, 0.111356, 0.0716792, 0.987476, -0.0094872, 0.111358, 0.0841364, 0.98749, -0.0110044, 0.111361, 0.097597, 0.987508, -0.0126344, 0.111362, 0.112062, 0.987494, -0.0143767, 0.111357, 0.127533, 0.987526, -0.0162307, 0.111359, 0.144015, 0.987558, -0.0181912, 0.111361, 0.161502, 0.987602, -0.0202393, 0.111355, 0.179979, 0.987692, -0.022273, 0.111346, 0.199386, 0.987702, -0.0235306, 0.111215, 0.219183, 0.987789, -0.0247628, 0.111061, 0.239202, 0.987776, -0.0280668, 0.111171, 0.259957, 0.987856, -0.0316751, 0.111327, 0.282198, 0.987912, -0.0342468, 0.111282, 0.306294, 0.988, -0.0367205, 0.111198, 0.331219, 0.988055, -0.0387766, 0.110994, 0.356708, 0.988241, -0.0397722, 0.110547, 0.382234, 0.988399, -0.0416076, 0.110198, 0.408227, 0.988539, -0.0448192, 0.110137, 0.434662, 0.988661, -0.0483793, 0.110143, 0.461442, 0.988967, -0.0495895, 0.109453, 0.489318, 0.989073, -0.0506797, 0.108628, 0.517516, 0.989274, -0.0526953, 0.108003, 0.545844, 0.989528, -0.054578, 0.107255, 0.573823, 0.989709, -0.0561503, 0.106294, 0.601944, 0.989991, -0.056866, 0.104896, 0.630855, 0.990392, -0.0572914, 0.103336, 0.658925, 0.990374, -0.0586224, 0.10189, 0.686661, 0.990747, -0.0584764, 0.099783, 0.714548, 0.991041, -0.0582662, 0.0974309, 0.74186, 0.991236, -0.0584118, 0.0951678, 0.768422, 0.991585, -0.0573055, 0.0921581, 0.794817, 0.991984, -0.0564241, 0.0891167, 0.820336, 0.9921, -0.0553608, 0.085805, 0.84493, 0.992749, -0.0533816, 0.0820354, 0.868961, 0.99288, -0.0518661, 0.0782181, 0.891931, 0.993511, -0.0492492, 0.0738935, 0.914186, 0.993617, -0.0471956, 0.0696402, 0.93532, 0.99411, -0.044216, 0.0649659, 0.95543, 0.994595, -0.0416654, 0.0603177, 0.974685, 0.994976, -0.0384314, 0.0553493, 0.992807, 0.995579, -0.0353491, 0.0503942, 1.00996, 0.996069, -0.0319787, 0.0452123, 1.02606, 0.996718, -0.028472, 0.0400112, 1.04114, 0.997173, -0.0250789, 0.0349456, 1.05517, 0.997818, -0.0213326, 0.029653, 1.0683, 0.998318, -0.0178509, 0.024549, 1.0805, 0.998853, -0.0141118, 0.0194197, 1.09177, 0.999218, -0.0105914, 0.0143869, 1.1022, 0.999594, -0.00693474, 0.00943517, 1.11175, 0.99975, -0.00340478, 0.00464051, 1.12056, 1.00001, 0.000109172, -0.000112821, 1.12853, 0.983383, -0.00000266524, 0.133358, 0.0000196534, 0.981942, -0.0000671009, 0.133162, 0.000494804, 0.981946, -0.000268405, 0.133163, 0.00197923, 0.981944, -0.000603912, 0.133163, 0.00445326, 0.981941, -0.00107362, 0.133162, 0.00791693, 0.981946, -0.00167755, 0.133163, 0.0123703, 0.981944, -0.00241569, 0.133162, 0.0178135, 0.981945, -0.00328807, 0.133163, 0.0242466, 0.981945, -0.00429472, 0.133162, 0.03167, 0.981955, -0.00543573, 0.133164, 0.0400846, 0.981951, -0.00671105, 0.133163, 0.0494901, 0.981968, -0.00812092, 0.133165, 0.0598886, 0.981979, -0.00966541, 0.133166, 0.0712811, 0.981996, -0.0113446, 0.133168, 0.083669, 0.982014, -0.0131585, 0.133169, 0.0970533, 0.982011, -0.0151073, 0.133167, 0.111438, 0.982062, -0.0171906, 0.133172, 0.126826, 0.9821, -0.0194067, 0.133175, 0.143215, 0.982149, -0.0217502, 0.133176, 0.160609, 0.982163, -0.0241945, 0.133173, 0.178981, 0.982247, -0.0265907, 0.133148, 0.198249, 0.982291, -0.027916, 0.132974, 0.217795, 0.982396, -0.0299663, 0.132868, 0.238042, 0.982456, -0.0334544, 0.132934, 0.258901, 0.982499, -0.0378636, 0.133137, 0.280639, 0.982617, -0.0409274, 0.133085, 0.304604, 0.98274, -0.0438523, 0.132985, 0.329376, 0.982944, -0.0462288, 0.132728, 0.354697, 0.98308, -0.0475995, 0.132228, 0.380102, 0.983391, -0.0501901, 0.131924, 0.406256, 0.983514, -0.0535899, 0.131737, 0.432735, 0.98373, -0.0571858, 0.131567, 0.459359, 0.984056, -0.0592353, 0.130932, 0.486637, 0.984234, -0.0610488, 0.130092, 0.51509, 0.984748, -0.0630758, 0.12923, 0.543461, 0.985073, -0.0647398, 0.128174, 0.571376, 0.985195, -0.0671941, 0.127133, 0.599414, 0.985734, -0.0681345, 0.125576, 0.628134, 0.986241, -0.0686089, 0.123639, 0.656399, 0.986356, -0.0698511, 0.121834, 0.684258, 0.986894, -0.0700931, 0.119454, 0.711818, 0.987382, -0.0698321, 0.116718, 0.739511, 0.988109, -0.0693975, 0.113699, 0.766267, 0.988363, -0.0689584, 0.110454, 0.792456, 0.989112, -0.0672353, 0.106602, 0.81813, 0.989241, -0.0662034, 0.10267, 0.842889, 0.990333, -0.0638938, 0.0981381, 0.867204, 0.990591, -0.0618534, 0.0935388, 0.89038, 0.991106, -0.0593117, 0.088553, 0.912576, 0.991919, -0.0562676, 0.0832187, 0.934118, 0.992111, -0.0534085, 0.0778302, 0.954254, 0.992997, -0.0495459, 0.0720453, 0.973722, 0.993317, -0.0463707, 0.0663458, 0.991949, 0.994133, -0.0421245, 0.0601883, 1.00936, 0.994705, -0.0384977, 0.0542501, 1.02559, 0.995495, -0.0340956, 0.0479862, 1.04083, 0.996206, -0.030105, 0.041887, 1.05497, 0.996971, -0.0256095, 0.0355355, 1.06824, 0.997796, -0.0213932, 0.0293655, 1.08056, 0.998272, -0.0169612, 0.0232926, 1.09182, 0.998857, -0.0126756, 0.0172786, 1.10219, 0.99939, -0.00832486, 0.0113156, 1.11192, 0.999752, -0.00410826, 0.00557892, 1.12075, 1, 0.000150957, -0.000119101, 1.12885, 0.975169, -0.00000309397, 0.154669, 0.0000195073, 0.975439, -0.0000779608, 0.154712, 0.000491534, 0.975464, -0.000311847, 0.154716, 0.00196617, 0.975464, -0.000701656, 0.154716, 0.00442387, 0.975462, -0.0012474, 0.154715, 0.0078647, 0.975461, -0.00194906, 0.154715, 0.0122886, 0.975464, -0.00280667, 0.154715, 0.0176959, 0.975468, -0.00382025, 0.154716, 0.0240867, 0.975471, -0.00498985, 0.154716, 0.0314612, 0.975472, -0.00631541, 0.154717, 0.0398199, 0.975486, -0.00779719, 0.154718, 0.0491639, 0.975489, -0.00943505, 0.154718, 0.0594932, 0.975509, -0.0112295, 0.154721, 0.0708113, 0.97554, -0.0131802, 0.154724, 0.0831176, 0.975557, -0.0152876, 0.154726, 0.096415, 0.975585, -0.0175512, 0.154728, 0.110705, 0.975605, -0.0199713, 0.154729, 0.125992, 0.975645, -0.0225447, 0.154729, 0.142272, 0.975711, -0.0252649, 0.154735, 0.159549, 0.975788, -0.0280986, 0.154736, 0.177805, 0.975872, -0.0308232, 0.154704, 0.196911, 0.975968, -0.0324841, 0.154525, 0.216324, 0.976063, -0.0351281, 0.154432, 0.236628, 0.976157, -0.0388618, 0.15446, 0.257539, 0.976204, -0.0437704, 0.154665, 0.278975, 0.976358, -0.047514, 0.154652, 0.302606, 0.976571, -0.0508638, 0.154535, 0.327204, 0.976725, -0.0534995, 0.154221, 0.352276, 0.977013, -0.0555547, 0.153737, 0.377696, 0.977294, -0.0586728, 0.153403, 0.403855, 0.977602, -0.0622715, 0.15312, 0.430333, 0.977932, -0.0658166, 0.152755, 0.456855, 0.978241, -0.0689877, 0.152233, 0.483668, 0.978602, -0.0712805, 0.15132, 0.512097, 0.979234, -0.0732775, 0.150235, 0.540455, 0.97977, -0.075163, 0.148978, 0.568486, 0.979995, -0.0778026, 0.147755, 0.596524, 0.98078, -0.0791854, 0.146019, 0.624825, 0.981628, -0.0799666, 0.143906, 0.653403, 0.982067, -0.0808532, 0.141561, 0.681445, 0.98271, -0.0816024, 0.139025, 0.708918, 0.983734, -0.0812511, 0.135764, 0.736594, 0.98431, -0.0806201, 0.132152, 0.763576, 0.985071, -0.0801605, 0.12846, 0.789797, 0.98618, -0.0784208, 0.124084, 0.815804, 0.986886, -0.0766643, 0.1193, 0.840869, 0.987485, -0.0747744, 0.114236, 0.864952, 0.988431, -0.0716701, 0.108654, 0.888431, 0.988886, -0.0691609, 0.102994, 0.910963, 0.990024, -0.0654048, 0.0967278, 0.932629, 0.990401, -0.0619765, 0.090384, 0.95313, 0.991093, -0.0579296, 0.0837885, 0.972587, 0.992018, -0.0536576, 0.0770171, 0.991184, 0.992536, -0.0493719, 0.0701486, 1.00863, 0.993421, -0.0444813, 0.062953, 1.02494, 0.993928, -0.040008, 0.0560455, 1.04017, 0.994994, -0.0347982, 0.04856, 1.05463, 0.995866, -0.0301017, 0.0416152, 1.06807, 0.996916, -0.0248225, 0.0342597, 1.08039, 0.997766, -0.0199229, 0.0271668, 1.09177, 0.998479, -0.0147422, 0.0201387, 1.10235, 0.99921, -0.00980173, 0.0131944, 1.11206, 0.999652, -0.0047426, 0.00640712, 1.12104, 0.999998, 0.0000891673, -0.00010379, 1.12906, 0.967868, -0.00000351885, 0.175947, 0.0000193569, 0.968001, -0.0000886733, 0.175972, 0.000487782, 0.96801, -0.000354697, 0.175973, 0.00195115, 0.968012, -0.000798063, 0.175974, 0.00439006, 0.968011, -0.00141879, 0.175973, 0.00780461, 0.968011, -0.00221686, 0.175973, 0.0121948, 0.968016, -0.00319231, 0.175974, 0.0175607, 0.968019, -0.00434515, 0.175974, 0.0239027, 0.968018, -0.00567538, 0.175974, 0.0312208, 0.968033, -0.00718308, 0.175977, 0.0395158, 0.968049, -0.00886836, 0.175979, 0.0487885, 0.968047, -0.0107312, 0.175978, 0.0590394, 0.968072, -0.0127719, 0.175981, 0.0702705, 0.968108, -0.0149905, 0.175986, 0.0824836, 0.968112, -0.0173866, 0.175985, 0.0956783, 0.968173, -0.0199611, 0.175993, 0.109862, 0.96827, -0.0227128, 0.176008, 0.125033, 0.968292, -0.025639, 0.17601, 0.141193, 0.968339, -0.0287299, 0.176007, 0.158336, 0.968389, -0.0319399, 0.176001, 0.176441, 0.968501, -0.034941, 0.175962, 0.195359, 0.968646, -0.0370812, 0.175793, 0.214686, 0.968789, -0.0402329, 0.175708, 0.234973, 0.96886, -0.0442601, 0.1757, 0.255871, 0.969013, -0.049398, 0.175876, 0.277238, 0.969242, -0.0539932, 0.17594, 0.300326, 0.969419, -0.0577299, 0.175781, 0.324702, 0.969763, -0.0605643, 0.175432, 0.349527, 0.970093, -0.0634488, 0.174992, 0.374976, 0.970361, -0.0670589, 0.174611, 0.401097, 0.970825, -0.0708246, 0.174226, 0.427496, 0.971214, -0.0742871, 0.173684, 0.453858, 0.971622, -0.0782608, 0.173186, 0.480637, 0.972175, -0.0813151, 0.172288, 0.508655, 0.972944, -0.0832678, 0.170979, 0.536973, 0.973595, -0.0855964, 0.169573, 0.565138, 0.974345, -0.0882163, 0.168152, 0.593222, 0.975233, -0.0901671, 0.166314, 0.621201, 0.976239, -0.0912111, 0.163931, 0.649919, 0.977289, -0.0916959, 0.161106, 0.678011, 0.978076, -0.0927061, 0.158272, 0.705717, 0.979533, -0.0925562, 0.15475, 0.733228, 0.980335, -0.0918159, 0.150638, 0.760454, 0.981808, -0.0908508, 0.146201, 0.786918, 0.983061, -0.0896172, 0.141386, 0.812953, 0.984148, -0.0871588, 0.135837, 0.838281, 0.985047, -0.0850624, 0.130135, 0.862594, 0.986219, -0.0818541, 0.123882, 0.88633, 0.987043, -0.0784523, 0.117126, 0.908952, 0.988107, -0.0749601, 0.110341, 0.930744, 0.988955, -0.0703548, 0.102885, 0.951728, 0.989426, -0.0662798, 0.0954167, 0.971166, 0.990421, -0.0610834, 0.0876331, 0.989984, 0.991032, -0.0562936, 0.0797785, 1.00765, 0.992041, -0.0508154, 0.0718166, 1.02434, 0.992794, -0.0454045, 0.0637125, 1.03976, 0.993691, -0.0398194, 0.0555338, 1.05418, 0.994778, -0.0341482, 0.0473388, 1.06772, 0.995915, -0.028428, 0.0391016, 1.08028, 0.997109, -0.022642, 0.0309953, 1.09185, 0.998095, -0.0168738, 0.0230288, 1.10247, 0.998985, -0.0111274, 0.0150722, 1.11229, 0.999581, -0.00543881, 0.00740605, 1.12131, 1.00003, 0.000162239, -0.000105549, 1.12946, 0.959505, -0.00000393734, 0.196876, 0.0000191893, 0.959599, -0.0000992157, 0.196895, 0.000483544, 0.959641, -0.000396868, 0.196903, 0.0019342, 0.959599, -0.000892948, 0.196895, 0.00435193, 0.959603, -0.00158747, 0.196896, 0.0077368, 0.959604, -0.00248042, 0.196896, 0.0120888, 0.959605, -0.00357184, 0.196896, 0.0174082, 0.959605, -0.00486169, 0.196896, 0.0236949, 0.959613, -0.00635008, 0.196897, 0.0309497, 0.959619, -0.00803696, 0.196898, 0.0391725, 0.959636, -0.00992255, 0.196901, 0.0483649, 0.959634, -0.0120067, 0.1969, 0.0585266, 0.959675, -0.0142898, 0.196906, 0.0696609, 0.959712, -0.0167717, 0.196911, 0.0817678, 0.959752, -0.0194524, 0.196918, 0.0948494, 0.959807, -0.0223321, 0.196925, 0.10891, 0.959828, -0.0254091, 0.196924, 0.123947, 0.959906, -0.0286815, 0.196934, 0.139968, 0.960005, -0.0321371, 0.196944, 0.156968, 0.960071, -0.0357114, 0.196936, 0.17491, 0.960237, -0.0389064, 0.196882, 0.193597, 0.960367, -0.041623, 0.196731, 0.21285, 0.960562, -0.0452655, 0.196654, 0.233075, 0.960735, -0.0496207, 0.196643, 0.253941, 0.960913, -0.0549379, 0.196774, 0.275278, 0.961121, -0.0603414, 0.196893, 0.297733, 0.96139, -0.0644244, 0.196717, 0.321877, 0.961818, -0.067556, 0.196314, 0.346476, 0.962175, -0.0712709, 0.195917, 0.371907, 0.96255, -0.0752848, 0.1955, 0.397916, 0.963164, -0.0792073, 0.195026, 0.424229, 0.963782, -0.0828225, 0.194424, 0.450637, 0.964306, -0.0873119, 0.193831, 0.477288, 0.964923, -0.0911051, 0.192973, 0.504716, 0.966048, -0.093251, 0.19151, 0.533053, 0.967024, -0.0958983, 0.190013, 0.561366, 0.968038, -0.09835, 0.188253, 0.589464, 0.969152, -0.100754, 0.186257, 0.617433, 0.970557, -0.102239, 0.183775, 0.645801, 0.972104, -0.102767, 0.180645, 0.674278, 0.973203, -0.103492, 0.177242, 0.702004, 0.975123, -0.103793, 0.17345, 0.729529, 0.97641, -0.102839, 0.168886, 0.756712, 0.978313, -0.101687, 0.163892, 0.783801, 0.980036, -0.100314, 0.158439, 0.809671, 0.981339, -0.097836, 0.152211, 0.835402, 0.982794, -0.0950006, 0.145679, 0.860081, 0.984123, -0.0920994, 0.138949, 0.883757, 0.984918, -0.0878641, 0.131283, 0.90685, 0.985999, -0.083939, 0.123464, 0.928786, 0.987151, -0.0791234, 0.115324, 0.94983, 0.987827, -0.0739332, 0.106854, 0.96962, 0.988806, -0.0688088, 0.0982691, 0.98861, 0.989588, -0.0628962, 0.0893456, 1.00667, 0.990438, -0.0573146, 0.0805392, 1.02344, 0.991506, -0.0509433, 0.0713725, 1.03933, 0.992492, -0.0448724, 0.0623732, 1.05378, 0.993663, -0.0383497, 0.0530838, 1.06747, 0.994956, -0.0319593, 0.0439512, 1.08007, 0.99634, -0.025401, 0.0347803, 1.09182, 0.99761, -0.0189687, 0.0257954, 1.1025, 0.99863, -0.0124441, 0.0169893, 1.11247, 0.99947, -0.00614003, 0.00829498, 1.12151, 1.00008, 0.000216624, -0.000146107, 1.12993, 0.950129, -0.00000434955, 0.217413, 0.0000190081, 0.950264, -0.00010957, 0.217444, 0.00047884, 0.9503, -0.000438299, 0.217451, 0.00191543, 0.950246, -0.000986124, 0.21744, 0.00430951, 0.950246, -0.00175311, 0.21744, 0.00766137, 0.950245, -0.00273923, 0.21744, 0.011971, 0.950253, -0.00394453, 0.217441, 0.0172385, 0.950258, -0.00536897, 0.217442, 0.0234641, 0.950267, -0.00701262, 0.217444, 0.030648, 0.950277, -0.00887551, 0.217446, 0.038791, 0.950284, -0.0109576, 0.217446, 0.0478931, 0.950312, -0.0132591, 0.217451, 0.0579568, 0.950334, -0.01578, 0.217454, 0.0689821, 0.950378, -0.0185204, 0.217462, 0.0809714, 0.950417, -0.0214803, 0.217467, 0.0939265, 0.950488, -0.0246594, 0.217479, 0.10785, 0.950534, -0.0280565, 0.217483, 0.122743, 0.950633, -0.0316685, 0.217498, 0.138611, 0.950698, -0.0354787, 0.217499, 0.155442, 0.950844, -0.0394003, 0.217507, 0.173208, 0.950999, -0.0426812, 0.217419, 0.191605, 0.951221, -0.0461302, 0.217317, 0.21084, 0.951412, -0.0502131, 0.217238, 0.230945, 0.951623, -0.0549183, 0.21722, 0.251745, 0.951867, -0.0604493, 0.217306, 0.273001, 0.952069, -0.0665189, 0.217466, 0.294874, 0.952459, -0.0709179, 0.217266, 0.318732, 0.952996, -0.0746112, 0.216891, 0.34318, 0.953425, -0.0789252, 0.216503, 0.36849, 0.953885, -0.0833293, 0.216042, 0.394373, 0.954617, -0.087371, 0.215469, 0.420505, 0.955429, -0.0914054, 0.214802, 0.446907, 0.956068, -0.0961671, 0.214146, 0.473522, 0.957094, -0.10048, 0.213286, 0.50052, 0.958372, -0.103248, 0.211796, 0.528715, 0.959654, -0.106033, 0.21016, 0.557065, 0.961305, -0.108384, 0.208149, 0.585286, 0.962785, -0.111122, 0.206024, 0.613334, 0.964848, -0.112981, 0.203442, 0.641334, 0.966498, -0.113717, 0.19996, 0.669955, 0.968678, -0.114121, 0.196105, 0.698094, 0.970489, -0.114524, 0.191906, 0.725643, 0.972903, -0.113792, 0.186963, 0.752856, 0.974701, -0.112406, 0.181343, 0.780013, 0.976718, -0.110685, 0.175185, 0.806268, 0.978905, -0.108468, 0.168535, 0.832073, 0.980267, -0.105061, 0.161106, 0.857149, 0.981967, -0.101675, 0.153387, 0.881145, 0.983063, -0.0974492, 0.145199, 0.904255, 0.984432, -0.0925815, 0.136527, 0.926686, 0.985734, -0.0877983, 0.127584, 0.947901, 0.986228, -0.081884, 0.118125, 0.968111, 0.98719, -0.0761208, 0.108594, 0.98719, 0.988228, -0.0698196, 0.0989996, 1.00559, 0.989046, -0.0632739, 0.0890074, 1.02246, 0.990242, -0.056522, 0.0790832, 1.03841, 0.991252, -0.0495272, 0.0689182, 1.05347, 0.992542, -0.0425373, 0.0588592, 1.06724, 0.994096, -0.0353198, 0.0486833, 1.08009, 0.995593, -0.028235, 0.0385977, 1.09177, 0.99711, -0.0209511, 0.0286457, 1.10274, 0.998263, -0.0139289, 0.0188497, 1.11262, 0.999254, -0.0067359, 0.009208, 1.12191, 0.999967, 0.000141846, -0.0000657764, 1.13024, 0.935608, -0.00000474692, 0.236466, 0.0000187817, 0.93996, -0.00011971, 0.237568, 0.000473646, 0.939959, -0.000478845, 0.237567, 0.0018946, 0.939954, -0.0010774, 0.237566, 0.00426284, 0.939956, -0.00191538, 0.237566, 0.00757842, 0.939954, -0.00299277, 0.237566, 0.0118413, 0.93996, -0.00430961, 0.237567, 0.0170518, 0.939969, -0.00586589, 0.237569, 0.02321, 0.939982, -0.00766166, 0.237572, 0.0303164, 0.939987, -0.00969686, 0.237572, 0.0383711, 0.939997, -0.0119715, 0.237574, 0.0473751, 0.940031, -0.0144858, 0.237581, 0.0573298, 0.940073, -0.0172399, 0.237589, 0.0682366, 0.94012, -0.0202335, 0.237598, 0.080097, 0.940162, -0.0234663, 0.237604, 0.0929116, 0.940237, -0.0269387, 0.237615, 0.106686, 0.940328, -0.0306489, 0.237632, 0.121421, 0.940419, -0.0345917, 0.237645, 0.137115, 0.940522, -0.0387481, 0.237654, 0.153766, 0.940702, -0.0429906, 0.237661, 0.17133, 0.940871, -0.0465089, 0.237561, 0.189502, 0.941103, -0.050531, 0.23748, 0.208616, 0.941369, -0.0550657, 0.237423, 0.228595, 0.941641, -0.0601337, 0.237399, 0.249287, 0.941903, -0.0658804, 0.237443, 0.270467, 0.942224, -0.0722674, 0.237597, 0.292024, 0.942633, -0.0771788, 0.237419, 0.315272, 0.943172, -0.0815623, 0.237068, 0.339579, 0.943691, -0.0863973, 0.236682, 0.364717, 0.944382, -0.0911536, 0.236213, 0.390435, 0.945392, -0.0952967, 0.235562, 0.416425, 0.946185, -0.0998948, 0.234832, 0.442772, 0.947212, -0.104796, 0.234114, 0.469347, 0.948778, -0.10928, 0.233222, 0.496162, 0.950149, -0.113081, 0.231845, 0.523978, 0.951989, -0.115893, 0.230005, 0.552295, 0.953921, -0.11846, 0.227862, 0.580569, 0.955624, -0.12115, 0.225439, 0.608698, 0.958234, -0.123373, 0.222635, 0.636696, 0.960593, -0.124519, 0.219093, 0.665208, 0.963201, -0.124736, 0.214749, 0.693557, 0.965642, -0.125012, 0.210059, 0.721334, 0.968765, -0.124661, 0.204935, 0.748613, 0.971753, -0.122996, 0.198661, 0.776224, 0.973751, -0.120998, 0.191823, 0.802461, 0.976709, -0.118583, 0.184359, 0.828399, 0.977956, -0.115102, 0.176437, 0.853693, 0.979672, -0.111077, 0.167681, 0.877962, 0.981816, -0.10688, 0.158872, 0.901564, 0.98238, -0.101469, 0.149398, 0.924057, 0.983964, -0.0960013, 0.139436, 0.945751, 0.984933, -0.0899626, 0.12943, 0.966272, 0.985694, -0.0832973, 0.11894, 0.985741, 0.986822, -0.0767082, 0.108349, 1.00407, 0.987725, -0.0693614, 0.0976026, 1.02154, 0.98877, -0.06211, 0.086652, 1.03757, 0.990129, -0.0544143, 0.0756182, 1.05296, 0.991337, -0.046744, 0.0645753, 1.06683, 0.992978, -0.0387931, 0.0534683, 1.0798, 0.994676, -0.030973, 0.0424137, 1.09181, 0.99645, -0.0230311, 0.0314035, 1.10286, 0.997967, -0.0152065, 0.0206869, 1.11291, 0.99922, -0.00744837, 0.010155, 1.12237, 1.00002, 0.000240209, -0.0000752767, 1.13089, 0.922948, -0.00000515351, 0.255626, 0.0000186069, 0.928785, -0.000129623, 0.257244, 0.000468009, 0.928761, -0.00051849, 0.257237, 0.00187202, 0.928751, -0.0011666, 0.257235, 0.00421204, 0.928751, -0.00207395, 0.257234, 0.0074881, 0.928754, -0.00324055, 0.257235, 0.0117002, 0.92876, -0.00466639, 0.257236, 0.0168486, 0.928763, -0.00635149, 0.257237, 0.0229334, 0.928774, -0.00829584, 0.257239, 0.029955, 0.928791, -0.0104995, 0.257243, 0.0379139, 0.928804, -0.0129623, 0.257245, 0.0468108, 0.928847, -0.0156846, 0.257255, 0.0566473, 0.92889, -0.0186661, 0.257263, 0.0674246, 0.928924, -0.0219067, 0.257268, 0.0791433, 0.928989, -0.0254066, 0.257282, 0.0918076, 0.92909, -0.0291651, 0.257301, 0.105419, 0.92918, -0.0331801, 0.257316, 0.119978, 0.92929, -0.0374469, 0.257332, 0.135491, 0.929453, -0.041939, 0.257357, 0.151948, 0.929586, -0.0464612, 0.257347, 0.169275, 0.929858, -0.0503426, 0.257269, 0.187257, 0.930125, -0.0548409, 0.257199, 0.206204, 0.930403, -0.0598063, 0.257149, 0.22601, 0.930726, -0.0652437, 0.257122, 0.246561, 0.931098, -0.0712376, 0.257153, 0.267618, 0.931396, -0.0777506, 0.257237, 0.288993, 0.931947, -0.0832374, 0.257124, 0.311527, 0.932579, -0.0883955, 0.25683, 0.335697, 0.933194, -0.0937037, 0.256444, 0.360634, 0.934013, -0.0987292, 0.255939, 0.386126, 0.935307, -0.103215, 0.255282, 0.412018, 0.936374, -0.108234, 0.254538, 0.438292, 0.93776, -0.113234, 0.253728, 0.464805, 0.939599, -0.118013, 0.25275, 0.491464, 0.941036, -0.122661, 0.251404, 0.518751, 0.94337, -0.125477, 0.249435, 0.547133, 0.945318, -0.128374, 0.247113, 0.575456, 0.947995, -0.130996, 0.244441, 0.60372, 0.950818, -0.133438, 0.241352, 0.63174, 0.954378, -0.135004, 0.237849, 0.659971, 0.957151, -0.135313, 0.233188, 0.688478, 0.960743, -0.13521, 0.228001, 0.716767, 0.964352, -0.135007, 0.222249, 0.744349, 0.967273, -0.133523, 0.21542, 0.771786, 0.969767, -0.131155, 0.208039, 0.798639, 0.973195, -0.128492, 0.200076, 0.824774, 0.975557, -0.125094, 0.191451, 0.850222, 0.977692, -0.120578, 0.18184, 0.874761, 0.98026, -0.115882, 0.172102, 0.898497, 0.981394, -0.110372, 0.161859, 0.921636, 0.982386, -0.10415, 0.15108, 0.943467, 0.983783, -0.0978128, 0.140407, 0.964045, 0.98422, -0.0906171, 0.129058, 0.98398, 0.985447, -0.0832921, 0.117614, 1.00276, 0.986682, -0.0754412, 0.10585, 1.02047, 0.987326, -0.0673885, 0.0940943, 1.03678, 0.988707, -0.0592565, 0.0822093, 1.05218, 0.990185, -0.050717, 0.070192, 1.06652, 0.991866, -0.0423486, 0.0582081, 1.07965, 0.993897, -0.0336118, 0.0460985, 1.09188, 0.995841, -0.0252178, 0.0342737, 1.10307, 0.997605, -0.0164893, 0.0224829, 1.11324, 0.999037, -0.00817112, 0.0110647, 1.12262, 1.00003, 0.000291686, -0.000168673, 1.13139, 0.915304, -0.00000552675, 0.275999, 0.0000183285, 0.91668, -0.000139285, 0.276414, 0.000461914, 0.916664, -0.00055713, 0.276409, 0.00184763, 0.916653, -0.00125354, 0.276406, 0.00415715, 0.916651, -0.00222851, 0.276405, 0.00739053, 0.916655, -0.00348205, 0.276406, 0.0115478, 0.916653, -0.00501414, 0.276405, 0.0166291, 0.916667, -0.00682478, 0.276409, 0.0226346, 0.91668, -0.00891398, 0.276412, 0.0295648, 0.91669, -0.0112817, 0.276413, 0.0374199, 0.916727, -0.013928, 0.276422, 0.0462016, 0.916759, -0.0168528, 0.276429, 0.0559101, 0.916793, -0.0200558, 0.276436, 0.0665466, 0.916849, -0.0235373, 0.276448, 0.0781139, 0.916964, -0.0272973, 0.276474, 0.0906156, 0.917047, -0.0313344, 0.276491, 0.104051, 0.917152, -0.0356465, 0.276511, 0.118424, 0.917286, -0.0402271, 0.276533, 0.133736, 0.917469, -0.0450408, 0.276564, 0.149978, 0.917686, -0.0497872, 0.276563, 0.167057, 0.917953, -0.0540937, 0.276493, 0.184846, 0.918228, -0.0590709, 0.276437, 0.203614, 0.918572, -0.0644277, 0.276398, 0.223212, 0.918918, -0.0702326, 0.276362, 0.243584, 0.919356, -0.076484, 0.276383, 0.264465, 0.919842, -0.0830808, 0.276434, 0.285701, 0.920451, -0.0892972, 0.276407, 0.307559, 0.921113, -0.095016, 0.276128, 0.331501, 0.921881, -0.100771, 0.275754, 0.356207, 0.923027, -0.106029, 0.275254, 0.381477, 0.924364, -0.111029, 0.274595, 0.40722, 0.925818, -0.116345, 0.273841, 0.433385, 0.92746, -0.121424, 0.272913, 0.459848, 0.929167, -0.12657, 0.271837, 0.486493, 0.931426, -0.131581, 0.270575, 0.513432, 0.934001, -0.135038, 0.268512, 0.541502, 0.936296, -0.138039, 0.266135, 0.569658, 0.939985, -0.140687, 0.263271, 0.598375, 0.943516, -0.143247, 0.260058, 0.626563, 0.94782, -0.145135, 0.256138, 0.654711, 0.951023, -0.145733, 0.251154, 0.683285, 0.955338, -0.145554, 0.245562, 0.711831, 0.959629, -0.145008, 0.239265, 0.739573, 0.963123, -0.144003, 0.232064, 0.767027, 0.966742, -0.141289, 0.224036, 0.794359, 0.969991, -0.138247, 0.215305, 0.820361, 0.973403, -0.134786, 0.206051, 0.846548, 0.975317, -0.129966, 0.195914, 0.871541, 0.977647, -0.12471, 0.185184, 0.895313, 0.980137, -0.119086, 0.174161, 0.918398, 0.981031, -0.112297, 0.162792, 0.940679, 0.982037, -0.105372, 0.150952, 0.961991, 0.983164, -0.097821, 0.138921, 0.981913, 0.983757, -0.0897245, 0.126611, 1.00109, 0.985036, -0.0815974, 0.114228, 1.01902, 0.986289, -0.0727725, 0.101389, 1.03604, 0.987329, -0.0639323, 0.0886476, 1.05149, 0.989193, -0.0548109, 0.0756837, 1.06619, 0.990716, -0.045687, 0.0627581, 1.07948, 0.992769, -0.0364315, 0.0498337, 1.09172, 0.99524, -0.0271761, 0.0370305, 1.1033, 0.997154, -0.0179609, 0.0243959, 1.11353, 0.998845, -0.00878063, 0.0119567, 1.12319, 1.00002, 0.000259038, -0.000108146, 1.13177, 0.903945, -0.00000591681, 0.295126, 0.0000181226, 0.903668, -0.000148672, 0.295037, 0.000455367, 0.903677, -0.000594683, 0.29504, 0.00182145, 0.903673, -0.00133805, 0.295039, 0.00409831, 0.903666, -0.00237872, 0.295036, 0.00728584, 0.903668, -0.00371676, 0.295037, 0.0113842, 0.903679, -0.00535212, 0.29504, 0.0163936, 0.903684, -0.00728479, 0.295041, 0.0223141, 0.903698, -0.00951473, 0.295044, 0.0291462, 0.903718, -0.0120419, 0.295049, 0.0368904, 0.903754, -0.0148664, 0.295058, 0.0455477, 0.903801, -0.017988, 0.29507, 0.0551194, 0.903851, -0.0214064, 0.295082, 0.0656058, 0.903921, -0.0251219, 0.295097, 0.0770109, 0.904002, -0.0291337, 0.295116, 0.0893354, 0.904111, -0.033441, 0.29514, 0.102583, 0.904246, -0.0380415, 0.295169, 0.116755, 0.904408, -0.0429258, 0.295202, 0.131853, 0.904637, -0.0480468, 0.295245, 0.147869, 0.904821, -0.0529208, 0.295214, 0.164658, 0.905163, -0.0577748, 0.295185, 0.182274, 0.905469, -0.0631763, 0.295143, 0.200828, 0.905851, -0.068917, 0.295112, 0.2202, 0.906322, -0.0750861, 0.295104, 0.240372, 0.906761, -0.0815855, 0.295086, 0.261082, 0.90735, -0.0882138, 0.295095, 0.282123, 0.908087, -0.095082, 0.295139, 0.303563, 0.908826, -0.101488, 0.29492, 0.327028, 0.909832, -0.107577, 0.294577, 0.351464, 0.911393, -0.113033, 0.294115, 0.376497, 0.912804, -0.118629, 0.293446, 0.402115, 0.914081, -0.124232, 0.292581, 0.428111, 0.91637, -0.129399, 0.29166, 0.454442, 0.91814, -0.134892, 0.290422, 0.481024, 0.921179, -0.140069, 0.289194, 0.507924, 0.924544, -0.144431, 0.287421, 0.535557, 0.927995, -0.147498, 0.284867, 0.563984, 0.931556, -0.150197, 0.281722, 0.5923, 0.935777, -0.152711, 0.278207, 0.620832, 0.940869, -0.154836, 0.274148, 0.649069, 0.945994, -0.155912, 0.269057, 0.677746, 0.949634, -0.155641, 0.262799, 0.706293, 0.955032, -0.154809, 0.256097, 0.734278, 0.95917, -0.153678, 0.248618, 0.761751, 0.962931, -0.151253, 0.239794, 0.789032, 0.966045, -0.147625, 0.230281, 0.815422, 0.96971, -0.143964, 0.220382, 0.841787, 0.972747, -0.139464, 0.209846, 0.867446, 0.975545, -0.133459, 0.198189, 0.892004, 0.978381, -0.127424, 0.186362, 0.915458, 0.979935, -0.120506, 0.173964, 0.937948, 0.980948, -0.11282, 0.161429, 0.959732, 0.982234, -0.104941, 0.148557, 0.980118, 0.982767, -0.0962905, 0.135508, 0.999463, 0.983544, -0.0873625, 0.122338, 1.01756, 0.984965, -0.0783447, 0.108669, 1.03492, 0.986233, -0.0684798, 0.0949911, 1.05087, 0.987796, -0.0590867, 0.0811386, 1.0656, 0.989885, -0.0489145, 0.0673099, 1.0794, 0.991821, -0.0391, 0.0535665, 1.09174, 0.99448, -0.029087, 0.0397529, 1.10341, 0.996769, -0.019114, 0.0261463, 1.11383, 0.998641, -0.00947007, 0.0128731, 1.1237, 0.999978, 0.000446316, -0.000169093, 1.13253, 0.888362, -0.00000627064, 0.312578, 0.0000178215, 0.889988, -0.000157791, 0.313148, 0.000448451, 0.889825, -0.000631076, 0.313092, 0.00179356, 0.88984, -0.00141994, 0.313097, 0.00403554, 0.889828, -0.0025243, 0.313092, 0.00717429, 0.889831, -0.00394421, 0.313093, 0.0112099, 0.889831, -0.00567962, 0.313093, 0.0161425, 0.889844, -0.00773051, 0.313096, 0.0219724, 0.889858, -0.0100968, 0.3131, 0.0286999, 0.889882, -0.0127786, 0.313106, 0.0363256, 0.889918, -0.0157757, 0.313116, 0.0448509, 0.889967, -0.0190878, 0.313129, 0.0542758, 0.89003, -0.022715, 0.313145, 0.0646032, 0.890108, -0.0266566, 0.313165, 0.0758339, 0.890218, -0.0309131, 0.313193, 0.0879729, 0.890351, -0.0354819, 0.313226, 0.101019, 0.89051, -0.0403613, 0.313263, 0.114979, 0.890672, -0.0455385, 0.313294, 0.129848, 0.890882, -0.0509444, 0.313333, 0.145616, 0.891189, -0.0559657, 0.313324, 0.162122, 0.891457, -0.0613123, 0.313281, 0.179524, 0.891856, -0.0671488, 0.313281, 0.197855, 0.892312, -0.0732732, 0.313268, 0.216991, 0.892819, -0.0797865, 0.313263, 0.236924, 0.893369, -0.0865269, 0.313247, 0.257433, 0.894045, -0.0931592, 0.313205, 0.278215, 0.894884, -0.100532, 0.313276, 0.299467, 0.895832, -0.107716, 0.313205, 0.322276, 0.897043, -0.114099, 0.312873, 0.34642, 0.898515, -0.119941, 0.312331, 0.371187, 0.900191, -0.126044, 0.311731, 0.396656, 0.90188, -0.131808, 0.310859, 0.422488, 0.904359, -0.137289, 0.309857, 0.448744, 0.906923, -0.142991, 0.308714, 0.475239, 0.910634, -0.148253, 0.307465, 0.501983, 0.914502, -0.153332, 0.305774, 0.529254, 0.919046, -0.156646, 0.303156, 0.557709, 0.923194, -0.159612, 0.299928, 0.586267, 0.928858, -0.162027, 0.296245, 0.614925, 0.934464, -0.164203, 0.291832, 0.643187, 0.939824, -0.165602, 0.286565, 0.671601, 0.944582, -0.165383, 0.280073, 0.700213, 0.949257, -0.164439, 0.272891, 0.728432, 0.954389, -0.162953, 0.264771, 0.756082, 0.958595, -0.161007, 0.255927, 0.78369, 0.962138, -0.157243, 0.245769, 0.810769, 0.966979, -0.152872, 0.235127, 0.836999, 0.969566, -0.148209, 0.22347, 0.862684, 0.972372, -0.142211, 0.211147, 0.887847, 0.975916, -0.135458, 0.198606, 0.911843, 0.978026, -0.128398, 0.185498, 0.934795, 0.979686, -0.120313, 0.17171, 0.956787, 0.980748, -0.11166, 0.158159, 0.978046, 0.981622, -0.103035, 0.144399, 0.997693, 0.982356, -0.0930328, 0.13001, 1.01642, 0.983308, -0.0834627, 0.115778, 1.03366, 0.985037, -0.0732249, 0.101327, 1.05014, 0.986493, -0.0628145, 0.086554, 1.06507, 0.988484, -0.0526556, 0.0720413, 1.07907, 0.991051, -0.0415744, 0.0571151, 1.09189, 0.993523, -0.0314275, 0.0426643, 1.10369, 0.99628, -0.0203603, 0.0279325, 1.11423, 0.998344, -0.0102446, 0.0138182, 1.12421, 0.999997, 0.00042612, -0.000193628, 1.1333, 0.871555, -0.00000660007, 0.329176, 0.0000174749, 0.875255, -0.000166579, 0.330571, 0.000441051, 0.875644, -0.000666394, 0.330718, 0.00176441, 0.875159, -0.00149903, 0.330536, 0.00396899, 0.87516, -0.00266493, 0.330536, 0.007056, 0.875158, -0.00416393, 0.330535, 0.0110251, 0.87516, -0.00599598, 0.330535, 0.0158764, 0.875163, -0.00816108, 0.330536, 0.0216101, 0.875174, -0.0106591, 0.330538, 0.0282266, 0.875199, -0.0134899, 0.330545, 0.0357266, 0.875257, -0.0166538, 0.330563, 0.0441117, 0.875304, -0.0201501, 0.330575, 0.0533821, 0.875373, -0.0239785, 0.330595, 0.0635395, 0.875464, -0.0281389, 0.330619, 0.0745872, 0.875565, -0.0326301, 0.330645, 0.0865255, 0.875691, -0.0374516, 0.330676, 0.0993599, 0.875897, -0.0425993, 0.330733, 0.113093, 0.876091, -0.0480576, 0.330776, 0.127722, 0.876353, -0.0537216, 0.330826, 0.143227, 0.876649, -0.0589807, 0.330809, 0.159462, 0.877034, -0.0647865, 0.330819, 0.176642, 0.877443, -0.0709789, 0.330817, 0.194702, 0.877956, -0.0774782, 0.330832, 0.213577, 0.878499, -0.0843175, 0.330822, 0.233246, 0.879144, -0.0912714, 0.330804, 0.253512, 0.879982, -0.0980824, 0.330766, 0.274137, 0.88097, -0.105823, 0.330864, 0.295209, 0.882051, -0.113671, 0.330896, 0.317226, 0.883397, -0.120303, 0.330545, 0.341068, 0.884987, -0.12667, 0.330068, 0.365613, 0.886789, -0.133118, 0.329418, 0.390807, 0.889311, -0.139024, 0.328683, 0.416494, 0.891995, -0.144971, 0.327729, 0.442618, 0.895106, -0.150747, 0.326521, 0.469131, 0.899527, -0.156283, 0.325229, 0.495921, 0.90504, -0.161707, 0.32378, 0.523162, 0.909875, -0.165661, 0.32122, 0.55092, 0.91561, -0.168755, 0.317942, 0.579928, 0.921225, -0.171193, 0.313983, 0.608539, 0.927308, -0.17319, 0.309636, 0.636854, 0.933077, -0.174819, 0.304262, 0.66523, 0.938766, -0.175002, 0.297563, 0.693609, 0.943667, -0.173946, 0.289613, 0.722157, 0.949033, -0.172221, 0.281227, 0.750021, 0.953765, -0.169869, 0.271545, 0.777466, 0.95804, -0.166578, 0.261034, 0.804853, 0.962302, -0.161761, 0.249434, 0.831569, 0.966544, -0.156636, 0.237484, 0.857779, 0.969372, -0.150784, 0.224395, 0.883051, 0.972486, -0.143672, 0.210786, 0.907864, 0.975853, -0.135772, 0.196556, 0.931223, 0.977975, -0.127942, 0.182307, 0.954061, 0.979122, -0.118347, 0.167607, 0.97531, 0.980719, -0.109112, 0.152739, 0.995666, 0.981223, -0.0991789, 0.137932, 1.01475, 0.98216, -0.0883553, 0.122692, 1.03253, 0.983379, -0.0780825, 0.107493, 1.04917, 0.985434, -0.0665646, 0.0917791, 1.06464, 0.987332, -0.0557714, 0.0764949, 1.07896, 0.990004, -0.0442805, 0.060721, 1.09199, 0.992975, -0.0331676, 0.0452284, 1.10393, 0.995811, -0.0219547, 0.0297934, 1.11476, 0.9982, -0.0107613, 0.0146415, 1.12484, 1.00002, 0.000248678, -0.00014555, 1.13413, 0.859519, -0.00000693595, 0.347264, 0.0000171673, 0.859843, -0.00017503, 0.347394, 0.000433219, 0.859656, -0.000700076, 0.347319, 0.00173277, 0.859671, -0.00157517, 0.347325, 0.00389875, 0.859669, -0.00280028, 0.347324, 0.00693112, 0.85967, -0.0043754, 0.347324, 0.01083, 0.859665, -0.00630049, 0.347321, 0.0155954, 0.859685, -0.0085755, 0.347328, 0.0212278, 0.859694, -0.0112003, 0.347329, 0.0277273, 0.859718, -0.0141747, 0.347336, 0.0350946, 0.85976, -0.0174988, 0.347348, 0.0433314, 0.85982, -0.0211722, 0.347366, 0.0524384, 0.859892, -0.0251941, 0.347387, 0.0624168, 0.860006, -0.0295649, 0.347422, 0.0732708, 0.860122, -0.0342825, 0.347453, 0.0849999, 0.860282, -0.0393462, 0.347499, 0.0976102, 0.860482, -0.0447513, 0.347554, 0.111104, 0.860719, -0.0504775, 0.347614, 0.125479, 0.860998, -0.0563577, 0.347666, 0.140703, 0.861322, -0.0619473, 0.347662, 0.156681, 0.861724, -0.0681277, 0.347684, 0.173597, 0.862198, -0.0746567, 0.347709, 0.191371, 0.862733, -0.0815234, 0.347727, 0.209976, 0.863371, -0.0886643, 0.347744, 0.229351, 0.86414, -0.0957908, 0.347734, 0.24934, 0.865138, -0.102912, 0.34772, 0.269797, 0.866182, -0.110924, 0.3478, 0.290654, 0.867436, -0.119223, 0.347911, 0.312074, 0.869087, -0.126197, 0.347649, 0.335438, 0.870859, -0.133145, 0.347222, 0.359732, 0.872997, -0.139869, 0.346645, 0.38467, 0.875939, -0.146089, 0.345935, 0.41019, 0.879012, -0.152334, 0.345012, 0.436218, 0.883353, -0.15821, 0.343924, 0.462641, 0.888362, -0.164097, 0.342636, 0.489449, 0.895026, -0.169528, 0.341351, 0.516629, 0.900753, -0.174408, 0.339115, 0.544109, 0.906814, -0.17751, 0.335809, 0.572857, 0.912855, -0.180101, 0.331597, 0.601554, 0.919438, -0.182116, 0.32698, 0.630198, 0.925962, -0.183494, 0.321449, 0.658404, 0.931734, -0.184159, 0.314595, 0.686625, 0.93762, -0.18304, 0.306462, 0.71531, 0.943858, -0.181323, 0.297514, 0.744272, 0.948662, -0.178683, 0.287447, 0.771462, 0.953299, -0.175379, 0.276166, 0.798593, 0.957346, -0.170395, 0.263758, 0.8256, 0.962565, -0.165042, 0.251019, 0.852575, 0.966075, -0.158655, 0.237011, 0.878316, 0.969048, -0.151707, 0.222518, 0.90329, 0.972423, -0.143271, 0.207848, 0.927745, 0.975833, -0.134824, 0.192463, 0.950859, 0.977629, -0.125444, 0.1768, 0.972947, 0.978995, -0.114949, 0.161033, 0.993263, 0.980533, -0.104936, 0.145523, 1.01337, 0.980745, -0.0935577, 0.129799, 1.03128, 0.981814, -0.0822956, 0.113486, 1.04825, 0.983943, -0.0710082, 0.0972925, 1.06405, 0.986141, -0.0587931, 0.0808138, 1.0785, 0.988878, -0.0472755, 0.0644915, 1.09204, 0.992132, -0.0349128, 0.0478128, 1.10413, 0.9953, -0.0232407, 0.031621, 1.11527, 0.998117, -0.0112713, 0.0154935, 1.12551, 1.00003, 0.000339743, -0.000195763, 1.13504, 0.845441, -0.00000729126, 0.364305, 0.0000169208, 0.843588, -0.000183164, 0.363506, 0.000425067, 0.843412, -0.00073253, 0.36343, 0.00169999, 0.843401, -0.00164818, 0.363426, 0.00382495, 0.843399, -0.00293008, 0.363425, 0.00679993, 0.843401, -0.00457822, 0.363425, 0.010625, 0.843394, -0.00659249, 0.363421, 0.0153002, 0.843398, -0.00897282, 0.363421, 0.0208258, 0.843415, -0.0117191, 0.363426, 0.0272024, 0.843438, -0.0148312, 0.363432, 0.0344305, 0.843483, -0.018309, 0.363447, 0.0425116, 0.84356, -0.0221521, 0.363472, 0.0514471, 0.843646, -0.0263597, 0.363499, 0.061238, 0.843743, -0.0309315, 0.363527, 0.0718873, 0.84388, -0.0358658, 0.363569, 0.0833969, 0.844079, -0.0411624, 0.363631, 0.0957742, 0.844279, -0.0468128, 0.363688, 0.109015, 0.844549, -0.0527923, 0.363761, 0.123124, 0.844858, -0.0588204, 0.363817, 0.138044, 0.84522, -0.0647573, 0.36383, 0.153755, 0.845669, -0.0713181, 0.363879, 0.170394, 0.846155, -0.0781697, 0.363908, 0.187861, 0.846789, -0.0853913, 0.363969, 0.206176, 0.847502, -0.0928086, 0.363999, 0.225244, 0.8484, -0.10005, 0.363997, 0.244926, 0.849461, -0.107615, 0.364008, 0.265188, 0.850562, -0.115814, 0.364055, 0.28587, 0.851962, -0.124334, 0.364179, 0.306926, 0.854326, -0.131995, 0.364233, 0.329605, 0.856295, -0.139338, 0.363856, 0.35359, 0.858857, -0.146346, 0.363347, 0.37831, 0.862428, -0.152994, 0.362807, 0.403722, 0.866203, -0.159463, 0.361963, 0.429537, 0.871629, -0.165623, 0.36112, 0.456, 0.877365, -0.171649, 0.359917, 0.482773, 0.883744, -0.177151, 0.35848, 0.509705, 0.890693, -0.182381, 0.356523, 0.537215, 0.897278, -0.186076, 0.3533, 0.565493, 0.903958, -0.188602, 0.349095, 0.594293, 0.910908, -0.190755, 0.344215, 0.623165, 0.918117, -0.192063, 0.338606, 0.651573, 0.924644, -0.192758, 0.331544, 0.679869, 0.931054, -0.192238, 0.323163, 0.708668, 0.937303, -0.190035, 0.313529, 0.737201, 0.943387, -0.187162, 0.303152, 0.764977, 0.948494, -0.183876, 0.29146, 0.792683, 0.952546, -0.178901, 0.277917, 0.819228, 0.958077, -0.173173, 0.264753, 0.846559, 0.962462, -0.16645, 0.25002, 0.872962, 0.966569, -0.159452, 0.234873, 0.898729, 0.969108, -0.15074, 0.218752, 0.923126, 0.973072, -0.141523, 0.202673, 0.947278, 0.975452, -0.132075, 0.186326, 0.969938, 0.977784, -0.121257, 0.169396, 0.991325, 0.97899, -0.110182, 0.153044, 1.01123, 0.979777, -0.0989634, 0.136485, 1.0299, 0.980865, -0.0865894, 0.119343, 1.04727, 0.982432, -0.0746115, 0.102452, 1.06341, 0.984935, -0.0621822, 0.0852423, 1.07834, 0.987776, -0.0495694, 0.0678546, 1.092, 0.99103, -0.0372386, 0.0506917, 1.1043, 0.99474, -0.0244353, 0.0333316, 1.11576, 0.997768, -0.0121448, 0.0164348, 1.12617, 1.00003, 0.00031774, -0.000169504, 1.13598, 0.825551, -0.00000756799, 0.378425, 0.0000165099, 0.82664, -0.000190922, 0.378923, 0.000416504, 0.826323, -0.000763495, 0.378779, 0.0016656, 0.826359, -0.00171789, 0.378795, 0.00374768, 0.82636, -0.00305402, 0.378795, 0.00666259, 0.826368, -0.00477185, 0.378798, 0.0104104, 0.826364, -0.00687131, 0.378795, 0.0149912, 0.826368, -0.00935232, 0.378795, 0.0204054, 0.826376, -0.0122146, 0.378797, 0.0266532, 0.826399, -0.0154581, 0.378803, 0.0337355, 0.82646, -0.0190825, 0.378824, 0.0416537, 0.826525, -0.0230873, 0.378846, 0.0504091, 0.826614, -0.0274719, 0.378876, 0.0600032, 0.82674, -0.0322355, 0.378917, 0.0704393, 0.826888, -0.0373766, 0.378964, 0.0817195, 0.827078, -0.0428936, 0.379024, 0.0938492, 0.827318, -0.0487778, 0.379099, 0.106828, 0.82764, -0.0549935, 0.379199, 0.120659, 0.827926, -0.0611058, 0.379227, 0.13526, 0.828325, -0.0675054, 0.379275, 0.150713, 0.828801, -0.0743455, 0.379332, 0.167034, 0.8294, -0.0815523, 0.379415, 0.184209, 0.830094, -0.0890779, 0.379495, 0.202203, 0.8309, -0.096736, 0.379555, 0.220945, 0.831943, -0.104135, 0.379577, 0.240306, 0.833037, -0.112106, 0.379604, 0.260317, 0.834278, -0.120554, 0.379668, 0.2808, 0.836192, -0.129128, 0.3799, 0.301654, 0.838671, -0.137541, 0.380109, 0.323502, 0.840939, -0.14523, 0.379809, 0.347176, 0.844575, -0.15248, 0.379593, 0.371706, 0.848379, -0.159607, 0.37909, 0.39688, 0.853616, -0.166267, 0.378617, 0.422702, 0.858921, -0.172698, 0.377746, 0.448919, 0.865324, -0.178823, 0.376749, 0.475661, 0.872207, -0.184542, 0.375363, 0.502599, 0.880018, -0.189836, 0.373657, 0.529914, 0.88694, -0.194294, 0.370673, 0.557683, 0.894779, -0.197022, 0.36662, 0.586848, 0.902242, -0.199108, 0.36138, 0.615831, 0.909914, -0.200398, 0.355434, 0.644478, 0.917088, -0.20094, 0.348173, 0.672905, 0.923888, -0.200671, 0.339482, 0.701327, 0.930495, -0.198773, 0.32956, 0.730101, 0.937247, -0.195394, 0.318363, 0.758383, 0.943108, -0.191956, 0.306323, 0.786539, 0.948296, -0.187227, 0.292576, 0.813637, 0.953472, -0.181165, 0.278234, 0.840793, 0.958485, -0.174119, 0.263054, 0.867712, 0.962714, -0.166564, 0.246756, 0.893635, 0.966185, -0.158181, 0.229945, 0.919028, 0.970146, -0.148275, 0.212633, 0.943413, 0.973491, -0.138157, 0.195229, 0.966627, 0.975741, -0.127574, 0.178048, 0.988817, 0.977238, -0.11554, 0.160312, 1.00924, 0.978411, -0.10364, 0.142857, 1.02845, 0.979811, -0.0913122, 0.125317, 1.04648, 0.98116, -0.0782558, 0.107627, 1.06284, 0.983543, -0.0655957, 0.0895862, 1.07798, 0.986789, -0.0520411, 0.0713756, 1.092, 0.990292, -0.0389727, 0.053228, 1.10484, 0.994187, -0.025808, 0.0351945, 1.11642, 0.997499, -0.0126071, 0.0173198, 1.12703, 0.999999, 0.000275604, -0.000148602, 1.13674, 0.81075, -0.0000078735, 0.394456, 0.0000161829, 0.808692, -0.000198293, 0.393453, 0.000407564, 0.80846, -0.000792877, 0.39334, 0.00162965, 0.808595, -0.00178416, 0.393407, 0.00366711, 0.808597, -0.00317182, 0.393408, 0.00651934, 0.808598, -0.00495589, 0.393408, 0.0101866, 0.808591, -0.00713627, 0.393403, 0.0146689, 0.808592, -0.00971285, 0.393402, 0.0199667, 0.80861, -0.0126855, 0.393407, 0.0260803, 0.808633, -0.0160538, 0.393413, 0.0330107, 0.80868, -0.0198175, 0.393429, 0.0407589, 0.808748, -0.0239758, 0.393453, 0.0493264, 0.808854, -0.0285286, 0.39349, 0.0587161, 0.808992, -0.0334748, 0.39354, 0.0689304, 0.809141, -0.0388116, 0.393588, 0.0799707, 0.809352, -0.0445375, 0.39366, 0.0918432, 0.809608, -0.0506427, 0.393742, 0.104549, 0.809915, -0.0570708, 0.393834, 0.118085, 0.810253, -0.0633526, 0.393885, 0.132377, 0.810687, -0.0700966, 0.393953, 0.147537, 0.811233, -0.0772274, 0.394047, 0.163543, 0.811865, -0.0847629, 0.394148, 0.180394, 0.812648, -0.0925663, 0.394265, 0.198051, 0.813583, -0.100416, 0.394363, 0.216443, 0.814683, -0.108119, 0.394402, 0.235502, 0.815948, -0.11644, 0.394489, 0.255242, 0.817278, -0.125036, 0.394542, 0.275441, 0.819605, -0.133655, 0.39486, 0.296094, 0.822256, -0.142682, 0.395248, 0.317309, 0.825349, -0.150756, 0.395241, 0.340516, 0.829605, -0.158392, 0.395285, 0.364819, 0.83391, -0.165801, 0.394922, 0.389736, 0.839808, -0.172677, 0.394691, 0.415409, 0.845708, -0.179448, 0.394006, 0.441546, 0.853025, -0.185746, 0.393279, 0.46832, 0.859666, -0.191684, 0.391655, 0.495302, 0.86789, -0.197146, 0.390068, 0.52262, 0.875845, -0.201904, 0.38727, 0.550336, 0.882634, -0.205023, 0.382688, 0.578825, 0.891076, -0.207098, 0.377543, 0.608103, 0.900589, -0.208474, 0.371752, 0.63723, 0.90791, -0.209068, 0.364016, 0.665769, 0.915971, -0.208655, 0.355593, 0.694428, 0.923455, -0.20729, 0.345439, 0.723224, 0.931514, -0.203821, 0.334099, 0.751925, 0.937885, -0.19986, 0.321069, 0.780249, 0.943136, -0.194993, 0.306571, 0.8077, 0.948818, -0.189132, 0.291556, 0.83497, 0.954433, -0.181617, 0.275745, 0.86188, 0.959078, -0.173595, 0.258695, 0.888562, 0.962705, -0.164855, 0.240825, 0.914008, 0.966753, -0.155129, 0.22268, 0.939145, 0.970704, -0.144241, 0.204542, 0.963393, 0.973367, -0.133188, 0.185927, 0.985983, 0.975984, -0.121146, 0.167743, 1.00704, 0.976994, -0.108366, 0.149218, 1.02715, 0.978485, -0.0956746, 0.13131, 1.0455, 0.980074, -0.0820733, 0.112513, 1.06221, 0.98225, -0.0684061, 0.0938323, 1.07782, 0.98553, -0.0549503, 0.0749508, 1.09199, 0.989529, -0.0407857, 0.055848, 1.10508, 0.993536, -0.0271978, 0.0368581, 1.11684, 0.997247, -0.0132716, 0.0181845, 1.12789, 1, 0.000431817, -0.000198809, 1.13792, 0.785886, -0.00000812608, 0.405036, 0.0000157669, 0.790388, -0.000205278, 0.407355, 0.000398297, 0.790145, -0.000820824, 0.407231, 0.00159263, 0.790135, -0.00184681, 0.407226, 0.00358336, 0.790119, -0.00328316, 0.407218, 0.00637039, 0.790126, -0.00512988, 0.40722, 0.0099539, 0.79013, -0.00738684, 0.407221, 0.0143339, 0.790135, -0.0100538, 0.407221, 0.0195107, 0.790134, -0.0131306, 0.407217, 0.0254848, 0.79016, -0.0166169, 0.407224, 0.0322572, 0.790197, -0.020512, 0.407236, 0.0398284, 0.790273, -0.0248157, 0.407263, 0.0482014, 0.790381, -0.029527, 0.407304, 0.0573777, 0.790521, -0.0346446, 0.407355, 0.0673602, 0.790704, -0.0401665, 0.40742, 0.0781522, 0.790925, -0.0460896, 0.407499, 0.0897582, 0.791195, -0.0524017, 0.407589, 0.10218, 0.791522, -0.0590121, 0.407691, 0.11541, 0.791878, -0.0654876, 0.407748, 0.12939, 0.792361, -0.0725207, 0.407849, 0.144237, 0.792942, -0.0799844, 0.407963, 0.159924, 0.79362, -0.0877896, 0.408087, 0.176425, 0.794529, -0.0958451, 0.408259, 0.193733, 0.795521, -0.103827, 0.408362, 0.211756, 0.796778, -0.111937, 0.408482, 0.230524, 0.798027, -0.120521, 0.408547, 0.249967, 0.799813, -0.129242, 0.408721, 0.269926, 0.802387, -0.138048, 0.409148, 0.290338, 0.805279, -0.147301, 0.409641, 0.311193, 0.809251, -0.155895, 0.410154, 0.333611, 0.813733, -0.163942, 0.410297, 0.357615, 0.819081, -0.171666, 0.410373, 0.382339, 0.825427, -0.178905, 0.410348, 0.407828, 0.83172, -0.185812, 0.409486, 0.434034, 0.83877, -0.192318, 0.408776, 0.460493, 0.845817, -0.198249, 0.407176, 0.487346, 0.854664, -0.204034, 0.405719, 0.514832, 0.863495, -0.208908, 0.403282, 0.542401, 0.871883, -0.212765, 0.399293, 0.570683, 0.88065, -0.214911, 0.393803, 0.599947, 0.89004, -0.216214, 0.387536, 0.62932, 0.898476, -0.216745, 0.379846, 0.658319, 0.906738, -0.216387, 0.370625, 0.687138, 0.914844, -0.215053, 0.360139, 0.71601, 0.923877, -0.212007, 0.348849, 0.745124, 0.931925, -0.207481, 0.335639, 0.773366, 0.938054, -0.202418, 0.320798, 0.801636, 0.943895, -0.196507, 0.304772, 0.829055, 0.949468, -0.189009, 0.288033, 0.856097, 0.955152, -0.180539, 0.270532, 0.88301, 0.959403, -0.171437, 0.251639, 0.909296, 0.963309, -0.161661, 0.232563, 0.934868, 0.967399, -0.150425, 0.213231, 0.959662, 0.972009, -0.138659, 0.194247, 0.98302, 0.97433, -0.126595, 0.174718, 1.00517, 0.975823, -0.113205, 0.155518, 1.02566, 0.976371, -0.0996096, 0.136709, 1.04418, 0.978705, -0.0860754, 0.117571, 1.06146, 0.981477, -0.0714438, 0.0980046, 1.07777, 0.984263, -0.0572304, 0.0782181, 1.09214, 0.988423, -0.0428875, 0.0584052, 1.10553, 0.993, -0.0282442, 0.038522, 1.11758, 0.99704, -0.0140183, 0.0190148, 1.12864, 0.999913, 0.000369494, -0.000145203, 1.13901, 0.777662, -0.0000084153, 0.423844, 0.0000154403, 0.770458, -0.000211714, 0.419915, 0.00038845, 0.770716, -0.000846888, 0.420055, 0.00155386, 0.770982, -0.00190567, 0.420202, 0.00349653, 0.770981, -0.00338782, 0.420201, 0.00621606, 0.77098, -0.00529338, 0.4202, 0.00971274, 0.770983, -0.00762223, 0.4202, 0.0139867, 0.770985, -0.0103741, 0.420198, 0.0190381, 0.770996, -0.0135489, 0.4202, 0.0248677, 0.771029, -0.0171461, 0.420212, 0.0314764, 0.771052, -0.0211647, 0.420215, 0.0388648, 0.771131, -0.0256048, 0.420245, 0.047036, 0.771235, -0.0304647, 0.420284, 0.0559911, 0.771383, -0.0357436, 0.420341, 0.0657346, 0.771591, -0.0414392, 0.420423, 0.0762694, 0.771819, -0.0475462, 0.420506, 0.0875984, 0.772123, -0.0540506, 0.420617, 0.099727, 0.772464, -0.060797, 0.42072, 0.112637, 0.772855, -0.0675393, 0.420799, 0.126313, 0.773317, -0.0748323, 0.420893, 0.140824, 0.773981, -0.0825681, 0.421058, 0.15617, 0.774746, -0.0906307, 0.421226, 0.172322, 0.77566, -0.0988982, 0.421397, 0.189253, 0.776837, -0.106994, 0.421569, 0.206912, 0.778097, -0.115528, 0.421704, 0.225359, 0.779588, -0.124317, 0.421849, 0.24447, 0.781574, -0.133139, 0.422097, 0.264156, 0.784451, -0.142179, 0.422615, 0.284318, 0.787682, -0.15165, 0.423269, 0.304902, 0.792433, -0.160771, 0.424396, 0.3265, 0.797359, -0.169166, 0.424772, 0.35014, 0.803986, -0.177149, 0.425475, 0.374768, 0.809504, -0.184745, 0.424996, 0.399928, 0.815885, -0.19173, 0.424247, 0.425796, 0.823513, -0.198525, 0.423515, 0.452287, 0.832549, -0.204709, 0.422787, 0.479321, 0.841653, -0.210447, 0.421187, 0.506718, 0.850401, -0.215501, 0.418519, 0.53432, 0.859854, -0.219752, 0.414715, 0.56242, 0.869364, -0.222305, 0.409462, 0.591558, 0.878837, -0.223744, 0.402926, 0.621074, 0.888636, -0.224065, 0.395043, 0.650538, 0.898132, -0.223742, 0.38564, 0.679538, 0.907181, -0.222308, 0.375378, 0.708674, 0.915621, -0.219837, 0.363212, 0.737714, 0.9239, -0.215233, 0.349313, 0.767014, 0.931644, -0.209592, 0.334162, 0.795133, 0.938887, -0.203644, 0.317943, 0.823228, 0.945282, -0.196349, 0.300581, 0.850822, 0.950758, -0.18742, 0.282195, 0.877594, 0.956146, -0.177879, 0.262481, 0.904564, 0.960355, -0.167643, 0.242487, 0.930741, 0.965256, -0.156671, 0.222668, 0.955868, 0.968029, -0.144123, 0.201907, 0.979869, 0.97251, -0.131305, 0.18202, 1.00291, 0.974925, -0.118335, 0.161909, 1.02392, 0.975402, -0.103714, 0.142129, 1.0433, 0.976987, -0.089415, 0.122447, 1.06089, 0.979677, -0.0748858, 0.102248, 1.07713, 0.983184, -0.0596086, 0.0814851, 1.09218, 0.987466, -0.0447671, 0.0609484, 1.10585, 0.992348, -0.0295217, 0.0401835, 1.11829, 0.996674, -0.0143917, 0.0198163, 1.12966, 1.00003, 0.000321364, -0.000149983, 1.1402, 0.757901, -0.00000869074, 0.436176, 0.0000151011, 0.751195, -0.000217848, 0.432317, 0.000378533, 0.751178, -0.000871373, 0.432307, 0.0015141, 0.751195, -0.00196061, 0.432317, 0.0034068, 0.751198, -0.00348552, 0.432318, 0.00605659, 0.751195, -0.00544599, 0.432315, 0.00946353, 0.751207, -0.00784203, 0.43232, 0.013628, 0.751213, -0.0106732, 0.43232, 0.0185499, 0.751221, -0.0139393, 0.432319, 0.0242302, 0.751244, -0.0176398, 0.432325, 0.0306694, 0.7513, -0.0217743, 0.432348, 0.0378698, 0.751358, -0.0263412, 0.432367, 0.0458321, 0.751458, -0.0313396, 0.432404, 0.0545587, 0.751608, -0.0367682, 0.432464, 0.0640543, 0.7518, -0.0426246, 0.43254, 0.0743222, 0.752065, -0.0489031, 0.432645, 0.0853668, 0.752376, -0.0555828, 0.432762, 0.0971911, 0.752715, -0.0623861, 0.432859, 0.109768, 0.753137, -0.069415, 0.432958, 0.123126, 0.753676, -0.0770039, 0.433099, 0.137308, 0.754345, -0.084971, 0.433272, 0.15229, 0.755235, -0.0932681, 0.433504, 0.168075, 0.756186, -0.10171, 0.433693, 0.184625, 0.757363, -0.110019, 0.433857, 0.201897, 0.75884, -0.11887, 0.434102, 0.220014, 0.760467, -0.127881, 0.434306, 0.238778, 0.762969, -0.136766, 0.434751, 0.258172, 0.765823, -0.14612, 0.43529, 0.278062, 0.769676, -0.15566, 0.436236, 0.298437, 0.774909, -0.165177, 0.437754, 0.319532, 0.77994, -0.17402, 0.438343, 0.342505, 0.785757, -0.182201, 0.438609, 0.366693, 0.792487, -0.190104, 0.438762, 0.391668, 0.80038, -0.197438, 0.438795, 0.417494, 0.808494, -0.204365, 0.438226, 0.443933, 0.817695, -0.210714, 0.437283, 0.470929, 0.828111, -0.216651, 0.436087, 0.498569, 0.837901, -0.221804, 0.433717, 0.526165, 0.847813, -0.226318, 0.430133, 0.554155, 0.858314, -0.229297, 0.425213, 0.582822, 0.868891, -0.230999, 0.418576, 0.612847, 0.878941, -0.231155, 0.410405, 0.642445, 0.888809, -0.230935, 0.400544, 0.672024, 0.898089, -0.229343, 0.389613, 0.701366, 0.908081, -0.226886, 0.377197, 0.730763, 0.916819, -0.222676, 0.363397, 0.759642, 0.924968, -0.216835, 0.347437, 0.788775, 0.932906, -0.210245, 0.32995, 0.817135, 0.940025, -0.202992, 0.312262, 0.844912, 0.946101, -0.19436, 0.293313, 0.872164, 0.952835, -0.184125, 0.273638, 0.899443, 0.957347, -0.173657, 0.252385, 0.926389, 0.961434, -0.162204, 0.231038, 0.951947, 0.965522, -0.14979, 0.209834, 0.976751, 0.969412, -0.136307, 0.188821, 1.00022, 0.973902, -0.122527, 0.168013, 1.02229, 0.974045, -0.108213, 0.147634, 1.04199, 0.975775, -0.0927397, 0.12705, 1.06019, 0.978383, -0.0778212, 0.106309, 1.07711, 0.98211, -0.0621216, 0.0849279, 1.09245, 0.986517, -0.0463847, 0.0633519, 1.10651, 0.991696, -0.0309353, 0.0419698, 1.11903, 0.996349, -0.0150914, 0.0206272, 1.13073, 1.00003, 0.000442449, -0.000231396, 1.14146, 0.727498, -0.00000885074, 0.441528, 0.0000145832, 0.730897, -0.000223525, 0.443589, 0.000368298, 0.730796, -0.000893996, 0.443528, 0.00147303, 0.730805, -0.00201149, 0.443533, 0.00331433, 0.730814, -0.00357596, 0.443538, 0.00589222, 0.730815, -0.00558734, 0.443538, 0.00920678, 0.730822, -0.00804544, 0.44354, 0.0132582, 0.730836, -0.0109501, 0.443545, 0.0180468, 0.730848, -0.0143008, 0.443546, 0.0235732, 0.730871, -0.0180969, 0.443552, 0.0298382, 0.730915, -0.022338, 0.443567, 0.0368438, 0.730982, -0.0270225, 0.443591, 0.044591, 0.731076, -0.0321491, 0.443627, 0.0530831, 0.731245, -0.0377166, 0.443699, 0.0623243, 0.73144, -0.0437216, 0.443777, 0.0723181, 0.7317, -0.0501576, 0.443881, 0.0830691, 0.732034, -0.0569942, 0.444014, 0.0945809, 0.732388, -0.0638756, 0.444113, 0.106825, 0.732853, -0.071203, 0.444247, 0.119859, 0.733473, -0.0790076, 0.444442, 0.13369, 0.734195, -0.0871937, 0.444645, 0.148304, 0.735069, -0.095696, 0.444877, 0.163702, 0.736169, -0.10426, 0.445133, 0.179861, 0.73747, -0.112853, 0.44537, 0.196778, 0.738991, -0.12199, 0.445651, 0.214496, 0.740865, -0.131153, 0.445958, 0.232913, 0.743637, -0.140245, 0.446548, 0.251977, 0.746797, -0.149722, 0.447246, 0.271551, 0.751517, -0.159341, 0.448656, 0.291774, 0.756156, -0.169106, 0.449866, 0.312455, 0.761519, -0.178436, 0.450919, 0.334552, 0.768295, -0.186904, 0.451776, 0.358491, 0.776613, -0.195117, 0.452832, 0.383446, 0.783966, -0.202695, 0.45249, 0.408945, 0.793542, -0.20985, 0.452587, 0.435364, 0.803192, -0.216403, 0.451852, 0.462336, 0.813892, -0.22251, 0.450708, 0.48987, 0.824968, -0.227676, 0.4486, 0.517697, 0.835859, -0.232443, 0.445156, 0.545975, 0.846825, -0.235775, 0.440351, 0.574483, 0.858085, -0.237897, 0.433641, 0.604246, 0.868825, -0.238074, 0.425354, 0.634101, 0.879638, -0.237661, 0.415383, 0.664201, 0.889966, -0.236186, 0.404136, 0.693918, 0.899479, -0.233599, 0.390917, 0.723481, 0.908769, -0.229737, 0.376352, 0.75258, 0.917966, -0.223836, 0.360372, 0.781764, 0.926304, -0.217067, 0.342551, 0.811139, 0.934626, -0.209309, 0.324238, 0.839585, 0.941841, -0.20071, 0.304484, 0.867044, 0.94789, -0.190602, 0.283607, 0.894579, 0.954196, -0.179253, 0.262205, 0.921743, 0.958383, -0.167646, 0.239847, 0.948026, 0.963119, -0.155073, 0.218078, 0.973296, 0.966941, -0.141426, 0.195899, 0.998135, 0.970836, -0.126849, 0.174121, 1.02021, 0.973301, -0.112296, 0.153052, 1.04085, 0.97448, -0.0964965, 0.131733, 1.05946, 0.977045, -0.080489, 0.10997, 1.07693, 0.980751, -0.064844, 0.0881657, 1.09254, 0.985475, -0.0481938, 0.0657987, 1.10697, 0.991089, -0.0319185, 0.0435215, 1.12004, 0.996122, -0.0158088, 0.0214779, 1.13173, 1.00001, 0.000372455, -0.000200295, 1.14291, 0.708622, -0.00000907597, 0.45304, 0.0000141962, 0.711162, -0.000228911, 0.454662, 0.000358052, 0.709812, -0.000914446, 0.453797, 0.00143034, 0.709865, -0.00205819, 0.453834, 0.00321935, 0.709864, -0.00365894, 0.453833, 0.00572331, 0.709855, -0.00571692, 0.453826, 0.00894278, 0.709862, -0.00823201, 0.453828, 0.012878, 0.709875, -0.011204, 0.453832, 0.0175295, 0.709896, -0.0146323, 0.453839, 0.0228978, 0.709925, -0.0185163, 0.453847, 0.0289839, 0.709974, -0.0228551, 0.453866, 0.0357894, 0.710045, -0.0276473, 0.453892, 0.0433161, 0.710133, -0.032891, 0.453924, 0.0515665, 0.710292, -0.0385851, 0.453992, 0.0605458, 0.710485, -0.0447254, 0.45407, 0.0702574, 0.710769, -0.0513051, 0.454192, 0.0807077, 0.711106, -0.0582733, 0.454329, 0.091896, 0.711516, -0.0652866, 0.45446, 0.103814, 0.712071, -0.0728426, 0.454653, 0.116508, 0.712676, -0.0808307, 0.45484, 0.129968, 0.713476, -0.0892216, 0.455096, 0.144206, 0.714377, -0.0979047, 0.455346, 0.159212, 0.715579, -0.106531, 0.455647, 0.174973, 0.716977, -0.115492, 0.455961, 0.191504, 0.71862, -0.124821, 0.456315, 0.208835, 0.72084, -0.134079, 0.4568, 0.226869, 0.723786, -0.143427, 0.457521, 0.245582, 0.727464, -0.153061, 0.458475, 0.264957, 0.732771, -0.162768, 0.460239, 0.284948, 0.736515, -0.172627, 0.460899, 0.30522, 0.743519, -0.182487, 0.463225, 0.326717, 0.750041, -0.191295, 0.464027, 0.350113, 0.758589, -0.199746, 0.465227, 0.374782, 0.767703, -0.207584, 0.465877, 0.400226, 0.777484, -0.214973, 0.465996, 0.426442, 0.788792, -0.221796, 0.466019, 0.453688, 0.800194, -0.228038, 0.465083, 0.481246, 0.811234, -0.233346, 0.462506, 0.509086, 0.822859, -0.238073, 0.459257, 0.537338, 0.835082, -0.241764, 0.454863, 0.566108, 0.846332, -0.244241, 0.448163, 0.595126, 0.858355, -0.244736, 0.439709, 0.625574, 0.87034, -0.244278, 0.429837, 0.65617, 0.881027, -0.24255, 0.418002, 0.686029, 0.891007, -0.239912, 0.404325, 0.716039, 0.900874, -0.236133, 0.389222, 0.745518, 0.911072, -0.230672, 0.373269, 0.775026, 0.920359, -0.22356, 0.355083, 0.804521, 0.928604, -0.215591, 0.335533, 0.834045, 0.937175, -0.206503, 0.315278, 0.861612, 0.942825, -0.196684, 0.293653, 0.889131, 0.949805, -0.185116, 0.271503, 0.916853, 0.955535, -0.172703, 0.248821, 0.943541, 0.959843, -0.159978, 0.225591, 0.970132, 0.964393, -0.146375, 0.202719, 0.994709, 0.968008, -0.131269, 0.179928, 1.0186, 0.971013, -0.11569, 0.158007, 1.03928, 0.973334, -0.1003, 0.13624, 1.05887, 0.975775, -0.0833352, 0.1138, 1.07652, 0.979579, -0.0668981, 0.0913141, 1.09297, 0.984323, -0.0500902, 0.0683051, 1.10734, 0.990351, -0.0332377, 0.0451771, 1.12084, 0.995823, -0.0161491, 0.0221705, 1.13296, 1.0001, 0.000234083, -0.000108712, 1.14441, 0.683895, -0.00000924677, 0.46015, 0.0000137429, 0.68833, -0.000233383, 0.463134, 0.000346865, 0.688368, -0.000933547, 0.463159, 0.00138748, 0.688367, -0.00210049, 0.463159, 0.00312187, 0.688369, -0.00373415, 0.463159, 0.00555004, 0.688377, -0.00583449, 0.463163, 0.00867216, 0.688386, -0.00840128, 0.463166, 0.0124884, 0.688398, -0.0114343, 0.463169, 0.0169993, 0.688418, -0.0149329, 0.463175, 0.0222054, 0.688453, -0.0188964, 0.463188, 0.028108, 0.688515, -0.0233239, 0.463214, 0.0347085, 0.68857, -0.0282136, 0.463231, 0.0420091, 0.688679, -0.033564, 0.463276, 0.0500132, 0.688854, -0.0393733, 0.463356, 0.0587255, 0.689038, -0.0456354, 0.46343, 0.0681476, 0.689321, -0.0523433, 0.463553, 0.0782897, 0.689662, -0.059412, 0.463693, 0.0891501, 0.690188, -0.0665736, 0.4639, 0.100735, 0.690755, -0.0743106, 0.464107, 0.113074, 0.691405, -0.0824722, 0.464329, 0.126161, 0.692198, -0.0910484, 0.464585, 0.140007, 0.693196, -0.0998778, 0.464893, 0.154612, 0.69454, -0.108651, 0.465285, 0.169984, 0.695921, -0.117855, 0.465596, 0.186106, 0.697749, -0.12734, 0.466056, 0.203034, 0.700375, -0.136714, 0.466771, 0.220703, 0.703395, -0.146386, 0.467579, 0.239062, 0.707904, -0.156096, 0.469067, 0.258188, 0.711673, -0.165904, 0.469851, 0.277759, 0.717489, -0.175812, 0.471815, 0.297935, 0.724051, -0.185931, 0.47389, 0.318916, 0.731965, -0.195238, 0.47587, 0.341591, 0.741151, -0.204021, 0.477523, 0.366062, 0.751416, -0.212113, 0.478881, 0.391396, 0.761848, -0.21979, 0.479226, 0.417599, 0.771886, -0.2267, 0.478495, 0.444401, 0.783998, -0.232991, 0.477622, 0.472084, 0.796523, -0.238645, 0.475833, 0.500193, 0.808851, -0.243396, 0.472568, 0.52865, 0.821191, -0.247226, 0.467857, 0.557362, 0.834261, -0.250102, 0.461871, 0.586768, 0.846762, -0.251056, 0.453543, 0.617085, 0.859867, -0.250604, 0.443494, 0.647659, 0.871948, -0.248783, 0.431711, 0.678119, 0.882967, -0.245855, 0.417911, 0.708399, 0.892826, -0.242168, 0.401993, 0.738256, 0.90332, -0.237062, 0.385371, 0.767999, 0.913633, -0.22997, 0.366837, 0.798191, 0.922774, -0.221687, 0.346372, 0.827756, 0.931371, -0.212345, 0.325682, 0.856425, 0.938929, -0.20206, 0.303665, 0.884299, 0.944821, -0.190981, 0.280786, 0.912023, 0.951792, -0.178065, 0.2573, 0.939669, 0.957712, -0.164634, 0.233448, 0.96655, 0.961912, -0.150863, 0.209504, 0.992366, 0.966382, -0.13577, 0.18597, 1.01633, 0.969588, -0.119593, 0.162905, 1.03843, 0.971777, -0.103203, 0.14053, 1.05841, 0.97433, -0.0865888, 0.117909, 1.07632, 0.978686, -0.0690829, 0.0944101, 1.09326, 0.983281, -0.0516568, 0.0705671, 1.10796, 0.989562, -0.034558, 0.0468592, 1.12182, 0.995465, -0.0167808, 0.0229846, 1.1342, 0.999991, 0.000373016, -0.000235606, 1.1459, 0.662251, -0.00000939016, 0.468575, 0.0000132714, 0.666634, -0.000237624, 0.471675, 0.000335842, 0.666411, -0.000950385, 0.471516, 0.00134321, 0.666399, -0.00213833, 0.471509, 0.00302221, 0.666386, -0.0038014, 0.471499, 0.00537283, 0.666405, -0.00593958, 0.471511, 0.00839533, 0.666406, -0.00855253, 0.471508, 0.0120898, 0.666428, -0.0116401, 0.471519, 0.0164569, 0.666444, -0.0152015, 0.471522, 0.0214971, 0.66649, -0.0192362, 0.471543, 0.027212, 0.666537, -0.0237428, 0.471558, 0.033603, 0.666617, -0.0287198, 0.471591, 0.0406728, 0.666718, -0.0341647, 0.471631, 0.0484238, 0.666889, -0.0400759, 0.47171, 0.0568621, 0.667104, -0.0464479, 0.471805, 0.0659915, 0.667374, -0.0532677, 0.471923, 0.0758178, 0.667772, -0.0603805, 0.472098, 0.0863425, 0.668371, -0.0677392, 0.472363, 0.0975917, 0.668971, -0.0756028, 0.472596, 0.109567, 0.669696, -0.0839293, 0.472869, 0.122272, 0.670481, -0.0926683, 0.473126, 0.135718, 0.6715, -0.1016, 0.473442, 0.149914, 0.672911, -0.110566, 0.47389, 0.164882, 0.674512, -0.119984, 0.474354, 0.180602, 0.67651, -0.129574, 0.474922, 0.19711, 0.679292, -0.139106, 0.475764, 0.214371, 0.682798, -0.148993, 0.476886, 0.232405, 0.686955, -0.158737, 0.478179, 0.251153, 0.691406, -0.168754, 0.479432, 0.270436, 0.697438, -0.178703, 0.481481, 0.290374, 0.704761, -0.188955, 0.484143, 0.311044, 0.713599, -0.198814, 0.487007, 0.333003, 0.723194, -0.207869, 0.488962, 0.357144, 0.732601, -0.216189, 0.489815, 0.382169, 0.744193, -0.22398, 0.490888, 0.408227, 0.754907, -0.231156, 0.490355, 0.434928, 0.767403, -0.23747, 0.489548, 0.462599, 0.78107, -0.243503, 0.488274, 0.490908, 0.793893, -0.248114, 0.484843, 0.519421, 0.807296, -0.25222, 0.4803, 0.548561, 0.820529, -0.255265, 0.474097, 0.577772, 0.833716, -0.256741, 0.466041, 0.607782, 0.848403, -0.25637, 0.456547, 0.638807, 0.860755, -0.254804, 0.443946, 0.670058, 0.874012, -0.251834, 0.430852, 0.700749, 0.885619, -0.247867, 0.414903, 0.731446, 0.896069, -0.242634, 0.397276, 0.761191, 0.906266, -0.236093, 0.378535, 0.791053, 0.916759, -0.227543, 0.358038, 0.821298, 0.92523, -0.21783, 0.335705, 0.850747, 0.93436, -0.207534, 0.313797, 0.879258, 0.941631, -0.195983, 0.289671, 0.907734, 0.947564, -0.183567, 0.265319, 0.935206, 0.953681, -0.169345, 0.240815, 0.962739, 0.960008, -0.154909, 0.216119, 0.989227, 0.964145, -0.140161, 0.192096, 1.01465, 0.968171, -0.123411, 0.167855, 1.03737, 0.969859, -0.106525, 0.144817, 1.05767, 0.972666, -0.0891023, 0.12149, 1.0761, 0.977055, -0.0718094, 0.0975306, 1.09336, 0.982527, -0.0534213, 0.0730217, 1.10878, 0.989001, -0.0355579, 0.0483366, 1.12285, 0.99512, -0.0176383, 0.023938, 1.13548, 1.00007, 0.000368831, -0.000211581, 1.14744, 0.651047, -0.00000960845, 0.484101, 0.000012922, 0.644145, -0.000241347, 0.478968, 0.000324578, 0.64396, -0.000965142, 0.478831, 0.00129798, 0.64396, -0.00217154, 0.47883, 0.00292046, 0.643968, -0.00386049, 0.478835, 0.00519202, 0.643974, -0.00603186, 0.478838, 0.0081128, 0.643977, -0.0086854, 0.478836, 0.011683, 0.643982, -0.0118207, 0.478834, 0.0159031, 0.644024, -0.0154374, 0.478856, 0.0207743, 0.644059, -0.0195343, 0.478868, 0.0262975, 0.644122, -0.0241103, 0.478896, 0.0324747, 0.644207, -0.0291638, 0.478933, 0.039309, 0.64432, -0.0346919, 0.478981, 0.0468029, 0.644481, -0.0406919, 0.479053, 0.0549614, 0.644722, -0.047159, 0.479169, 0.0637909, 0.645013, -0.0540748, 0.479302, 0.0732974, 0.645503, -0.0612001, 0.479541, 0.0834898, 0.646117, -0.0687303, 0.479829, 0.0943873, 0.646707, -0.0767846, 0.480061, 0.105991, 0.647431, -0.0852465, 0.480343, 0.11831, 0.64831, -0.0940719, 0.48066, 0.131348, 0.649486, -0.103056, 0.481083, 0.14514, 0.650864, -0.112261, 0.481528, 0.159676, 0.652604, -0.121852, 0.482102, 0.174979, 0.654825, -0.131505, 0.482813, 0.191079, 0.657876, -0.141189, 0.483876, 0.207927, 0.661339, -0.151239, 0.48499, 0.225586, 0.665463, -0.161091, 0.486279, 0.243947, 0.670542, -0.171235, 0.487968, 0.262957, 0.677361, -0.181347, 0.49053, 0.282781, 0.685672, -0.191679, 0.493862, 0.303311, 0.694551, -0.201781, 0.49699, 0.324607, 0.703753, -0.211164, 0.498884, 0.347916, 0.713703, -0.219675, 0.500086, 0.372628, 0.725911, -0.227836, 0.501554, 0.398694, 0.73862, -0.23533, 0.502193, 0.425529, 0.752118, -0.241786, 0.501811, 0.453209, 0.76579, -0.247865, 0.500185, 0.481381, 0.779568, -0.252696, 0.497159, 0.51011, 0.793991, -0.256802, 0.492765, 0.539322, 0.808182, -0.259942, 0.486827, 0.569078, 0.821698, -0.261703, 0.478386, 0.598818, 0.836009, -0.262006, 0.468772, 0.629762, 0.849824, -0.260333, 0.456352, 0.661366, 0.863888, -0.257398, 0.442533, 0.69295, 0.876585, -0.253264, 0.426573, 0.723608, 0.888665, -0.248026, 0.408964, 0.754378, 0.899537, -0.241487, 0.389677, 0.784761, 0.9094, -0.233463, 0.368516, 0.814688, 0.920166, -0.223397, 0.346624, 0.845009, 0.928899, -0.21255, 0.322717, 0.874431, 0.937156, -0.200869, 0.298698, 0.902922, 0.943861, -0.188387, 0.273491, 0.931356, 0.949557, -0.174341, 0.247866, 0.958854, 0.955862, -0.158994, 0.222496, 0.986098, 0.961721, -0.143664, 0.197522, 1.01229, 0.965976, -0.127412, 0.17302, 1.03571, 0.968652, -0.109798, 0.148954, 1.05699, 0.971084, -0.0916787, 0.125044, 1.07587, 0.975584, -0.0739634, 0.100577, 1.09372, 0.98122, -0.055322, 0.0753666, 1.10948, 0.988253, -0.0366825, 0.0498899, 1.12394, 0.99482, -0.0180389, 0.024611, 1.13694, 1.00001, 0.000229839, -0.000188283, 1.14919, 0.613867, -0.00000964198, 0.479449, 0.0000123452, 0.621485, -0.000244534, 0.485399, 0.000313091, 0.621429, -0.000978202, 0.485353, 0.00125245, 0.62112, -0.00220004, 0.485114, 0.00281687, 0.621119, -0.0039111, 0.485112, 0.00500783, 0.621122, -0.00611091, 0.485112, 0.00782498, 0.621133, -0.00879922, 0.485117, 0.0112687, 0.621152, -0.0119756, 0.485125, 0.0153394, 0.621183, -0.0156396, 0.485139, 0.0200382, 0.621227, -0.0197898, 0.485158, 0.0253663, 0.621298, -0.0244253, 0.485192, 0.0313261, 0.621388, -0.0295441, 0.485233, 0.0379204, 0.621507, -0.0351432, 0.485286, 0.0451523, 0.621693, -0.0412198, 0.485378, 0.0530277, 0.621933, -0.0477673, 0.485495, 0.0615522, 0.622232, -0.0547574, 0.485635, 0.0707316, 0.622809, -0.0619417, 0.485943, 0.0805883, 0.623407, -0.069625, 0.486232, 0.0911267, 0.62406, -0.077796, 0.486516, 0.102354, 0.624835, -0.0863731, 0.486838, 0.114279, 0.625758, -0.095251, 0.487188, 0.126902, 0.627043, -0.104299, 0.487695, 0.140285, 0.628438, -0.113724, 0.488163, 0.154397, 0.630325, -0.123417, 0.488858, 0.169267, 0.632801, -0.133137, 0.489754, 0.184941, 0.635784, -0.143052, 0.490815, 0.20136, 0.639406, -0.153132, 0.492048, 0.218643, 0.643872, -0.163143, 0.49363, 0.236615, 0.6499, -0.17333, 0.496009, 0.255449, 0.657201, -0.183622, 0.498994, 0.275006, 0.666221, -0.194019, 0.502888, 0.295354, 0.674419, -0.204192, 0.505459, 0.316244, 0.683729, -0.21406, 0.507771, 0.33849, 0.695584, -0.222854, 0.510245, 0.363166, 0.708583, -0.231315, 0.512293, 0.389071, 0.721233, -0.238911, 0.512747, 0.415737, 0.735134, -0.245657, 0.512482, 0.443331, 0.750179, -0.251879, 0.511526, 0.471891, 0.765073, -0.256911, 0.508935, 0.500892, 0.779794, -0.261144, 0.504341, 0.530294, 0.794801, -0.264316, 0.498515, 0.560144, 0.810339, -0.266276, 0.491015, 0.590213, 0.824818, -0.266981, 0.481126, 0.620865, 0.839375, -0.265778, 0.468685, 0.652687, 0.853043, -0.262748, 0.453925, 0.684759, 0.867335, -0.258474, 0.437912, 0.716209, 0.88037, -0.253187, 0.419648, 0.747508, 0.891711, -0.246476, 0.39982, 0.77797, 0.902896, -0.238735, 0.37879, 0.808586, 0.913601, -0.22885, 0.355891, 0.838843, 0.923019, -0.217656, 0.331773, 0.869014, 0.933432, -0.205539, 0.307356, 0.898512, 0.939691, -0.192595, 0.281321, 0.9269, 0.946938, -0.178945, 0.255441, 0.955297, 0.952372, -0.163587, 0.229013, 0.983231, 0.95909, -0.147214, 0.203179, 1.00971, 0.963675, -0.13064, 0.17792, 1.03438, 0.968247, -0.113121, 0.152898, 1.05625, 0.97001, -0.0945824, 0.128712, 1.07598, 0.974458, -0.0755648, 0.103349, 1.094, 0.980168, -0.0571998, 0.0776731, 1.1104, 0.987295, -0.0377994, 0.0514445, 1.12491, 0.994432, -0.0186417, 0.025429, 1.13851, 0.999975, 0.000542714, -0.000282356, 1.15108, 0.592656, -0.00000980249, 0.486018, 0.0000119532, 0.598467, -0.000247275, 0.490781, 0.000301531, 0.597934, -0.000988317, 0.490343, 0.00120517, 0.597903, -0.00222366, 0.490319, 0.0027116, 0.597913, -0.00395315, 0.490327, 0.00482077, 0.597919, -0.00617653, 0.490329, 0.00753264, 0.597936, -0.00889375, 0.490339, 0.0108478, 0.597956, -0.0121043, 0.490347, 0.0147668, 0.597992, -0.0158073, 0.490365, 0.0192905, 0.598032, -0.0200017, 0.490382, 0.0244204, 0.598109, -0.0246865, 0.49042, 0.0301593, 0.598215, -0.0298594, 0.490474, 0.03651, 0.59833, -0.0355167, 0.490524, 0.0434757, 0.598525, -0.0416559, 0.490624, 0.0510629, 0.598778, -0.0482692, 0.490753, 0.0592781, 0.599135, -0.0553114, 0.49094, 0.0681304, 0.599802, -0.062542, 0.491328, 0.0776467, 0.600361, -0.0703638, 0.491598, 0.0878184, 0.60101, -0.0786256, 0.491882, 0.0986573, 0.601811, -0.0872962, 0.492232, 0.11018, 0.602861, -0.0962284, 0.492684, 0.1224, 0.604167, -0.10538, 0.493213, 0.135354, 0.605693, -0.114896, 0.493799, 0.149034, 0.607682, -0.124654, 0.494576, 0.163469, 0.610672, -0.13456, 0.4959, 0.178747, 0.613313, -0.144581, 0.496713, 0.194723, 0.617603, -0.154703, 0.498499, 0.211617, 0.622174, -0.16489, 0.500188, 0.229183, 0.628855, -0.175164, 0.503072, 0.247786, 0.636963, -0.185565, 0.506798, 0.267116, 0.644866, -0.195911, 0.509719, 0.28702, 0.653741, -0.206104, 0.512776, 0.307763, 0.664942, -0.216447, 0.516812, 0.329631, 0.67633, -0.22552, 0.519181, 0.353515, 0.690012, -0.234316, 0.521681, 0.379226, 0.704243, -0.242032, 0.523129, 0.405901, 0.719396, -0.249172, 0.523768, 0.433585, 0.734471, -0.255543, 0.522541, 0.462085, 0.750539, -0.260697, 0.520217, 0.491233, 0.766365, -0.26501, 0.516293, 0.521094, 0.781677, -0.268409, 0.509708, 0.551014, 0.797132, -0.270399, 0.501944, 0.581463, 0.812655, -0.271247, 0.492025, 0.612402, 0.828592, -0.270708, 0.480424, 0.643798, 0.844044, -0.268085, 0.465955, 0.67682, 0.857305, -0.263459, 0.448425, 0.708496, 0.87114, -0.258151, 0.430243, 0.74046, 0.884936, -0.251171, 0.410578, 0.771583, 0.895772, -0.243305, 0.38862, 0.802234, 0.906961, -0.234037, 0.365214, 0.833179, 0.917775, -0.222714, 0.34116, 0.86353, 0.927883, -0.210175, 0.31572, 0.893557, 0.936617, -0.196925, 0.289159, 0.922976, 0.943384, -0.182788, 0.261996, 0.951606, 0.949713, -0.167965, 0.235324, 0.979958, 0.955818, -0.151109, 0.208408, 1.00765, 0.961344, -0.133834, 0.182591, 1.03329, 0.965469, -0.115987, 0.156958, 1.0557, 0.968693, -0.09746, 0.132239, 1.07583, 0.973165, -0.0778514, 0.106195, 1.09451, 0.979387, -0.0585067, 0.0797669, 1.11137, 0.98671, -0.0390409, 0.0530263, 1.12643, 0.994093, -0.019408, 0.0263163, 1.14016, 1.00002, 0.000540029, -0.000194487, 1.15299, 0.574483, -0.00000989066, 0.494533, 0.0000114896, 0.574478, -0.000249127, 0.494528, 0.000289403, 0.574607, -0.000996811, 0.494637, 0.00115797, 0.574396, -0.00224241, 0.494458, 0.00260498, 0.574377, -0.00398632, 0.49444, 0.00463102, 0.574386, -0.00622836, 0.494445, 0.00723623, 0.574401, -0.0089683, 0.494453, 0.010421, 0.574419, -0.0122056, 0.49446, 0.0141859, 0.574459, -0.0159396, 0.494481, 0.0185322, 0.574525, -0.0201692, 0.49452, 0.0234617, 0.574587, -0.0248924, 0.494547, 0.0289762, 0.574697, -0.0301074, 0.494604, 0.0350797, 0.574853, -0.0358114, 0.494688, 0.0417767, 0.575027, -0.041999, 0.494772, 0.0490718, 0.575294, -0.0486618, 0.494915, 0.0569728, 0.575733, -0.0557148, 0.495173, 0.0654955, 0.576356, -0.0630489, 0.495537, 0.0746612, 0.576944, -0.0709285, 0.495836, 0.0844615, 0.57765, -0.0792723, 0.496177, 0.0949142, 0.578491, -0.0880167, 0.496563, 0.10603, 0.579639, -0.0969462, 0.497096, 0.117841, 0.580989, -0.10622, 0.497684, 0.130367, 0.582587, -0.115861, 0.498337, 0.143609, 0.584951, -0.125605, 0.499414, 0.157625, 0.587602, -0.135608, 0.500518, 0.172413, 0.59076, -0.145742, 0.501767, 0.187999, 0.594992, -0.155934, 0.503542, 0.20445, 0.600656, -0.166303, 0.506135, 0.221764, 0.607816, -0.176681, 0.509542, 0.24002, 0.61522, -0.187071, 0.51263, 0.258992, 0.623702, -0.197465, 0.516021, 0.278773, 0.634192, -0.207816, 0.520422, 0.299377, 0.644936, -0.218183, 0.524073, 0.320802, 0.657888, -0.2278, 0.528049, 0.34384, 0.670666, -0.236747, 0.52986, 0.36916, 0.685626, -0.24484, 0.531892, 0.395867, 0.701304, -0.252071, 0.532727, 0.423488, 0.717727, -0.258714, 0.532146, 0.452201, 0.733914, -0.264211, 0.529883, 0.481579, 0.750529, -0.26859, 0.5259, 0.511558, 0.76747, -0.272046, 0.51999, 0.542042, 0.785189, -0.274225, 0.513083, 0.572799, 0.800954, -0.275189, 0.502936, 0.603816, 0.816962, -0.274946, 0.490921, 0.635461, 0.83336, -0.272695, 0.47684, 0.6676, 0.848143, -0.268223, 0.459405, 0.70051, 0.861818, -0.262768, 0.440319, 0.732902, 0.876828, -0.255872, 0.420123, 0.765084, 0.889312, -0.247703, 0.398379, 0.796391, 0.900412, -0.238381, 0.374496, 0.827333, 0.912251, -0.227783, 0.349874, 0.858385, 0.921792, -0.214832, 0.323181, 0.888652, 0.931273, -0.200949, 0.296624, 0.917763, 0.940295, -0.186537, 0.269211, 0.947878, 0.946812, -0.171538, 0.241447, 0.977016, 0.953588, -0.155254, 0.213829, 1.00501, 0.958841, -0.137156, 0.186807, 1.03179, 0.963746, -0.118699, 0.160706, 1.05502, 0.966468, -0.0998358, 0.135504, 1.07568, 0.971178, -0.0805186, 0.109131, 1.09479, 0.97831, -0.0599348, 0.0818293, 1.1123, 0.985886, -0.0399661, 0.0545872, 1.12771, 0.994021, -0.0198682, 0.0269405, 1.14186, 1.00009, 0.000271022, -0.00012989, 1.15514, 0.538716, -0.00000990918, 0.486732, 0.0000109675, 0.550656, -0.000250642, 0.497518, 0.000277412, 0.55057, -0.00100265, 0.497441, 0.00110974, 0.550903, -0.00225672, 0.497733, 0.00249779, 0.550568, -0.00401046, 0.497438, 0.00443906, 0.550574, -0.00626613, 0.49744, 0.00693637, 0.550591, -0.0090226, 0.497449, 0.00998921, 0.550623, -0.0122795, 0.497469, 0.0135984, 0.550667, -0.0160361, 0.497495, 0.0177654, 0.550724, -0.0202908, 0.497526, 0.0224915, 0.550792, -0.0250421, 0.497557, 0.0277795, 0.550918, -0.0302878, 0.49763, 0.0336334, 0.551058, -0.0360241, 0.497701, 0.0400573, 0.551276, -0.0422473, 0.497824, 0.0470585, 0.551551, -0.0489441, 0.497977, 0.0546433, 0.552074, -0.0559596, 0.498312, 0.0628367, 0.552681, -0.0633978, 0.498679, 0.071646, 0.553324, -0.0713176, 0.499031, 0.0810746, 0.554011, -0.0797268, 0.499365, 0.091129, 0.55488, -0.0885238, 0.499779, 0.101837, 0.556171, -0.0974417, 0.500444, 0.113239, 0.557498, -0.106841, 0.501025, 0.125316, 0.559299, -0.116533, 0.501864, 0.138128, 0.561647, -0.126298, 0.502967, 0.151695, 0.564347, -0.136388, 0.504129, 0.16604, 0.567863, -0.146576, 0.505713, 0.181207, 0.572569, -0.156832, 0.507953, 0.197259, 0.578919, -0.167323, 0.511186, 0.214258, 0.585387, -0.177712, 0.514042, 0.232038, 0.593134, -0.188184, 0.517484, 0.250733, 0.603295, -0.198717, 0.522345, 0.270454, 0.613854, -0.209177, 0.526751, 0.290807, 0.626092, -0.219644, 0.531595, 0.312202, 0.637868, -0.229494, 0.534721, 0.334435, 0.652458, -0.238718, 0.538304, 0.359184, 0.666985, -0.247061, 0.539875, 0.385637, 0.683301, -0.254652, 0.541042, 0.41328, 0.69998, -0.261376, 0.540735, 0.441903, 0.717824, -0.267085, 0.539139, 0.471609, 0.734617, -0.271465, 0.534958, 0.501446, 0.753663, -0.27528, 0.53032, 0.532571, 0.770512, -0.277617, 0.522134, 0.563641, 0.787356, -0.278525, 0.51206, 0.595067, 0.806252, -0.278512, 0.50119, 0.627226, 0.822061, -0.277023, 0.486791, 0.659402, 0.838959, -0.273175, 0.470467, 0.692874, 0.85379, -0.267238, 0.450688, 0.725702, 0.868268, -0.260327, 0.429741, 0.75832, 0.881994, -0.251946, 0.407223, 0.790189, 0.893885, -0.242432, 0.383214, 0.821625, 0.905118, -0.231904, 0.357297, 0.853011, 0.916045, -0.219545, 0.330733, 0.883773, 0.927614, -0.205378, 0.303916, 0.914435, 0.936005, -0.190388, 0.275941, 0.944502, 0.944533, -0.1749, 0.247493, 0.974439, 0.950758, -0.158588, 0.218996, 1.00286, 0.957078, -0.141027, 0.191559, 1.0304, 0.962448, -0.121507, 0.164457, 1.05466, 0.964993, -0.102068, 0.138636, 1.0761, 0.970017, -0.0822598, 0.111861, 1.09541, 0.97661, -0.062033, 0.0843438, 1.11317, 0.985073, -0.0409832, 0.0558496, 1.12911, 0.993515, -0.020146, 0.0275331, 1.1438, 1.00006, 0.00027329, -0.000107883, 1.15736, 0.525324, -0.00000999341, 0.498153, 0.0000105385, 0.526513, -0.000251605, 0.499277, 0.000265329, 0.526517, -0.00100641, 0.499282, 0.0010613, 0.526588, -0.00226466, 0.499337, 0.00238823, 0.526539, -0.0040255, 0.499302, 0.00424535, 0.526547, -0.00628954, 0.499306, 0.00663364, 0.526561, -0.00905628, 0.499313, 0.00955337, 0.526593, -0.0123253, 0.499334, 0.0130054, 0.526642, -0.0160957, 0.499365, 0.0169911, 0.5267, -0.0203661, 0.499396, 0.0215122, 0.526792, -0.0251347, 0.499451, 0.0265718, 0.526904, -0.0303985, 0.499511, 0.0321732, 0.527079, -0.0361554, 0.499617, 0.0383231, 0.527285, -0.0423982, 0.499731, 0.045026, 0.527602, -0.0491121, 0.499924, 0.0522936, 0.528166, -0.0561127, 0.500306, 0.0601528, 0.52879, -0.0635988, 0.5007, 0.0686059, 0.529421, -0.071581, 0.501048, 0.0776518, 0.530144, -0.0799854, 0.501421, 0.0873148, 0.531062, -0.0888032, 0.501884, 0.0976084, 0.532374, -0.0977643, 0.50259, 0.108588, 0.533828, -0.107197, 0.50329, 0.120234, 0.53581, -0.116887, 0.504312, 0.132602, 0.538063, -0.126755, 0.505365, 0.145721, 0.5409, -0.136819, 0.506668, 0.159617, 0.544882, -0.147117, 0.508731, 0.174369, 0.550238, -0.157446, 0.511601, 0.190028, 0.556038, -0.167988, 0.514431, 0.206587, 0.563031, -0.178364, 0.517808, 0.224046, 0.571543, -0.189007, 0.521937, 0.242503, 0.582255, -0.199546, 0.527415, 0.261977, 0.59272, -0.210084, 0.531682, 0.282162, 0.605648, -0.220448, 0.537123, 0.303426, 0.61785, -0.230593, 0.540664, 0.325323, 0.632223, -0.240238, 0.544467, 0.348993, 0.648819, -0.24887, 0.547594, 0.375462, 0.665825, -0.256657, 0.54912, 0.403024, 0.683389, -0.263711, 0.549294, 0.431773, 0.701495, -0.269666, 0.547649, 0.461494, 0.719197, -0.274169, 0.543786, 0.491623, 0.737906, -0.278124, 0.538644, 0.522994, 0.756652, -0.280632, 0.531057, 0.554775, 0.775279, -0.281741, 0.521972, 0.586441, 0.792688, -0.281652, 0.509613, 0.618596, 0.811894, -0.280345, 0.496497, 0.651462, 0.827938, -0.277128, 0.47968, 0.684023, 0.844837, -0.271646, 0.460688, 0.718024, 0.859239, -0.264397, 0.438872, 0.751207, 0.874088, -0.256144, 0.41577, 0.784232, 0.887693, -0.246311, 0.391369, 0.816191, 0.899402, -0.235497, 0.365872, 0.847828, 0.910973, -0.223631, 0.338618, 0.87934, 0.92204, -0.209874, 0.310803, 0.910325, 0.930987, -0.194265, 0.281802, 0.940695, 0.94, -0.178125, 0.252836, 0.970958, 0.948018, -0.161479, 0.224239, 1.00078, 0.955141, -0.144038, 0.195857, 1.0288, 0.960513, -0.124915, 0.168487, 1.05371, 0.963964, -0.104284, 0.141495, 1.07596, 0.968713, -0.0838732, 0.114437, 1.09628, 0.975524, -0.0635579, 0.0863105, 1.11448, 0.98431, -0.042291, 0.0574774, 1.13069, 0.992916, -0.0209131, 0.0284343, 1.14568, 0.999926, 0.000743097, -0.000379265, 1.15955, 0.501042, -0.00000998428, 0.498726, 0.0000100306, 0.502992, -0.000252112, 0.500665, 0.000253283, 0.502417, -0.00100791, 0.500092, 0.00101259, 0.502965, -0.00226919, 0.500621, 0.00227978, 0.502318, -0.00403109, 0.499994, 0.00405011, 0.502333, -0.00629832, 0.500005, 0.00632868, 0.502362, -0.00906907, 0.500027, 0.00911446, 0.502369, -0.0123423, 0.500023, 0.0124078, 0.50243, -0.0161178, 0.500066, 0.016211, 0.502493, -0.0203937, 0.500103, 0.0205256, 0.502592, -0.0251684, 0.500166, 0.0253548, 0.502707, -0.0304389, 0.50023, 0.0307029, 0.502881, -0.0362015, 0.500335, 0.0365753, 0.503124, -0.0424507, 0.500488, 0.0429798, 0.503443, -0.0491582, 0.500686, 0.0499268, 0.504083, -0.0561476, 0.501155, 0.0574541, 0.504668, -0.0636846, 0.501524, 0.0655408, 0.505319, -0.0716834, 0.501904, 0.0742072, 0.50609, -0.0800925, 0.502321, 0.0834699, 0.507122, -0.0888425, 0.502896, 0.0933603, 0.508414, -0.097855, 0.503603, 0.10391, 0.509955, -0.107304, 0.504416, 0.115113, 0.512061, -0.116921, 0.505565, 0.127054, 0.514419, -0.12689, 0.506732, 0.139709, 0.517529, -0.136934, 0.508338, 0.153173, 0.522085, -0.147327, 0.510987, 0.167528, 0.526986, -0.157612, 0.513527, 0.182708, 0.533122, -0.168213, 0.516717, 0.198881, 0.540807, -0.178688, 0.520832, 0.215986, 0.550687, -0.189511, 0.52632, 0.234335, 0.560567, -0.199998, 0.531009, 0.253375, 0.571698, -0.210652, 0.535839, 0.273499, 0.584364, -0.220917, 0.541091, 0.294355, 0.599066, -0.23137, 0.546875, 0.316525, 0.614148, -0.241206, 0.551306, 0.339671, 0.631157, -0.250379, 0.555187, 0.36531, 0.647919, -0.258397, 0.556595, 0.392767, 0.666112, -0.265528, 0.556949, 0.421397, 0.686158, -0.271827, 0.556617, 0.451433, 0.704838, -0.27674, 0.552975, 0.482131, 0.723957, -0.280733, 0.547814, 0.513458, 0.74262, -0.283359, 0.53997, 0.545446, 0.762009, -0.284541, 0.530422, 0.57775, 0.781314, -0.284507, 0.518546, 0.610434, 0.799116, -0.283309, 0.504178, 0.643178, 0.817604, -0.280378, 0.48843, 0.676248, 0.83459, -0.275619, 0.469457, 0.709698, 0.850974, -0.26856, 0.447698, 0.744245, 0.866747, -0.260094, 0.424791, 0.777695, 0.881412, -0.249929, 0.399913, 0.810392, 0.8936, -0.239137, 0.37308, 0.842872, 0.905943, -0.226818, 0.345705, 0.874677, 0.916408, -0.213699, 0.31706, 0.906257, 0.927215, -0.198428, 0.288444, 0.936881, 0.935625, -0.181643, 0.258329, 0.96795, 0.944076, -0.164386, 0.228488, 0.998216, 0.951229, -0.146339, 0.199763, 1.02689, 0.958793, -0.127709, 0.172153, 1.0535, 0.963219, -0.107244, 0.144989, 1.07646, 0.967562, -0.0857764, 0.11685, 1.09675, 0.974866, -0.0645377, 0.0880571, 1.11576, 0.983353, -0.0431732, 0.0587352, 1.13227, 0.992503, -0.0218356, 0.0294181, 1.1478, 1.00003, 0.000605203, -0.000231013, 1.16207, 0.482935, -0.0000101177, 0.504695, 0.00000968142, 0.477554, -0.000251521, 0.499071, 0.000240676, 0.477904, -0.00100683, 0.499436, 0.00096342, 0.478368, -0.00226636, 0.499899, 0.0021687, 0.477977, -0.00402719, 0.499513, 0.00385384, 0.477993, -0.00629226, 0.499525, 0.0060221, 0.478011, -0.00906011, 0.499536, 0.00867289, 0.478051, -0.0123305, 0.499566, 0.0118074, 0.478089, -0.016102, 0.499587, 0.0154269, 0.478171, -0.0203736, 0.499645, 0.0195341, 0.478254, -0.025143, 0.499692, 0.0241318, 0.47839, -0.0304071, 0.499779, 0.0292247, 0.478588, -0.0361631, 0.499911, 0.0348196, 0.478812, -0.0424023, 0.500046, 0.0409231, 0.479208, -0.0490724, 0.500326, 0.047552, 0.479841, -0.0560722, 0.500805, 0.0547377, 0.480392, -0.0636125, 0.501152, 0.0624607, 0.481068, -0.0716134, 0.501561, 0.0707473, 0.481898, -0.0800062, 0.502054, 0.0796118, 0.483022, -0.0886568, 0.502728, 0.0890974, 0.484332, -0.0977553, 0.503479, 0.0992099, 0.486126, -0.107173, 0.504546, 0.10999, 0.488066, -0.11677, 0.50557, 0.121476, 0.490521, -0.126725, 0.506849, 0.133672, 0.494232, -0.136793, 0.50911, 0.146731, 0.498302, -0.147116, 0.511345, 0.160577, 0.503565, -0.157446, 0.514344, 0.175335, 0.510902, -0.168121, 0.518824, 0.191207, 0.519263, -0.178799, 0.523666, 0.208058, 0.528204, -0.189407, 0.528296, 0.225875, 0.538854, -0.200145, 0.533724, 0.244782, 0.551278, -0.210701, 0.539833, 0.264753, 0.565222, -0.221303, 0.546131, 0.285745, 0.579403, -0.231688, 0.551496, 0.307592, 0.595469, -0.241718, 0.556809, 0.330582, 0.610929, -0.250992, 0.559641, 0.354995, 0.629433, -0.259602, 0.562379, 0.382471, 0.648504, -0.267038, 0.563676, 0.411126, 0.66756, -0.273388, 0.562092, 0.440924, 0.689143, -0.278788, 0.560807, 0.472118, 0.709056, -0.282783, 0.555701, 0.503774, 0.729855, -0.285836, 0.548698, 0.536364, 0.748954, -0.287078, 0.538544, 0.56895, 0.768373, -0.287133, 0.526711, 0.601991, 0.78827, -0.285839, 0.512511, 0.635403, 0.807465, -0.283238, 0.496323, 0.668797, 0.825194, -0.27906, 0.477638, 0.702584, 0.842203, -0.272286, 0.456253, 0.736393, 0.857749, -0.263854, 0.432412, 0.77096, 0.874799, -0.253943, 0.407806, 0.80489, 0.887497, -0.24237, 0.38033, 0.83771, 0.89966, -0.230278, 0.352446, 0.870376, 0.911753, -0.21646, 0.323268, 0.902256, 0.923011, -0.202071, 0.294314, 0.933306, 0.932375, -0.185519, 0.264104, 0.965177, 0.940537, -0.167604, 0.234035, 0.996303, 0.948904, -0.149068, 0.20412, 1.0261, 0.955263, -0.129539, 0.175431, 1.05304, 0.960303, -0.109932, 0.148116, 1.07617, 0.965512, -0.0880572, 0.119693, 1.09742, 0.973466, -0.0660548, 0.0901619, 1.11721, 0.98284, -0.0439228, 0.0599875, 1.13436, 0.992216, -0.0219588, 0.0298975, 1.15006, 0.999946, 0.000119402, -0.0000208547, 1.16471, 0.447827, -0.0000100414, 0.491543, 0.00000914833, 0.454778, -0.000251257, 0.499172, 0.00022891, 0.453519, -0.00100342, 0.497787, 0.000914184, 0.45357, -0.00225776, 0.497847, 0.00205701, 0.453578, -0.00401371, 0.497855, 0.00365705, 0.45357, -0.00627107, 0.497841, 0.00571453, 0.453598, -0.00902968, 0.497864, 0.00823019, 0.453627, -0.0122888, 0.497882, 0.0112049, 0.453684, -0.0160475, 0.497923, 0.0146405, 0.453764, -0.0203044, 0.49798, 0.0185394, 0.453866, -0.0250576, 0.498049, 0.0229054, 0.453996, -0.0303028, 0.49813, 0.0277424, 0.454196, -0.0360379, 0.498267, 0.0330587, 0.454457, -0.0422521, 0.498445, 0.0388613, 0.454926, -0.0488393, 0.498812, 0.0451767, 0.455525, -0.0558653, 0.499272, 0.0520153, 0.456074, -0.0633772, 0.499625, 0.0593754, 0.456752, -0.0713606, 0.500049, 0.0672751, 0.457648, -0.07971, 0.500615, 0.0757447, 0.458849, -0.0883032, 0.501399, 0.0848231, 0.46029, -0.0974095, 0.502293, 0.0945135, 0.462, -0.106729, 0.503301, 0.104848, 0.464121, -0.116354, 0.504533, 0.115884, 0.466889, -0.126214, 0.506172, 0.127652, 0.470744, -0.136324, 0.508667, 0.14024, 0.47488, -0.146595, 0.510995, 0.153673, 0.480845, -0.157027, 0.514832, 0.168053, 0.488262, -0.167658, 0.519506, 0.183508, 0.496547, -0.178343, 0.524347, 0.199948, 0.506254, -0.188916, 0.52983, 0.217503, 0.517961, -0.199975, 0.536357, 0.236272, 0.531484, -0.210624, 0.543641, 0.256096, 0.545496, -0.221227, 0.550048, 0.277085, 0.559497, -0.231568, 0.555076, 0.298615, 0.575752, -0.241698, 0.560541, 0.321547, 0.591999, -0.251172, 0.564156, 0.345602, 0.610654, -0.260178, 0.567607, 0.371851, 0.630484, -0.268094, 0.56923, 0.40076, 0.651807, -0.274661, 0.569779, 0.430801, 0.67239, -0.280331, 0.566791, 0.461939, 0.693024, -0.284501, 0.562007, 0.493854, 0.715473, -0.287852, 0.555791, 0.526992, 0.736323, -0.28929, 0.546345, 0.560102, 0.755771, -0.289405, 0.534, 0.593543, 0.775424, -0.2881, 0.519114, 0.627256, 0.795447, -0.285562, 0.502543, 0.661464, 0.815319, -0.281416, 0.484773, 0.695206, 0.831769, -0.275523, 0.463445, 0.729044, 0.849464, -0.267516, 0.440269, 0.764069, 0.866775, -0.257584, 0.415049, 0.799089, 0.881252, -0.245817, 0.388049, 0.831948, 0.894209, -0.233127, 0.35889, 0.865526, 0.906922, -0.219579, 0.329915, 0.89818, 0.919686, -0.204491, 0.300441, 0.930013, 0.929044, -0.188962, 0.269445, 0.962061, 0.938393, -0.171079, 0.238402, 0.994214, 0.94661, -0.15199, 0.208204, 1.02533, 0.953095, -0.131953, 0.178653, 1.0529, 0.958644, -0.111233, 0.150684, 1.0771, 0.963925, -0.0903098, 0.122359, 1.09855, 0.971995, -0.0680505, 0.0923342, 1.11874, 0.981658, -0.0448512, 0.0614195, 1.13635, 0.991649, -0.0221931, 0.0303582, 1.15238, 0.999985, 0.000393403, -0.000111086, 1.16772, 0.396806, -0.00000971563, 0.457671, 0.00000842355, 0.429186, -0.000249421, 0.495017, 0.00021625, 0.429324, -0.000998052, 0.495173, 0.000865322, 0.429175, -0.00224487, 0.494999, 0.00194637, 0.429129, -0.00399041, 0.494952, 0.00346004, 0.429153, -0.00623476, 0.494974, 0.00540684, 0.429168, -0.0089773, 0.494983, 0.00778714, 0.429207, -0.0122175, 0.495012, 0.0106022, 0.429257, -0.0159542, 0.495047, 0.0138535, 0.429338, -0.0201864, 0.495106, 0.0175443, 0.429431, -0.0249104, 0.495165, 0.0216774, 0.429587, -0.0301252, 0.495279, 0.0262594, 0.429796, -0.0358249, 0.495432, 0.0312968, 0.430065, -0.0419972, 0.495621, 0.0367985, 0.430588, -0.0485144, 0.496061, 0.042798, 0.43113, -0.0555028, 0.496472, 0.0492914, 0.431743, -0.0629852, 0.496904, 0.0562907, 0.432448, -0.0709256, 0.497369, 0.0638056, 0.433414, -0.0791942, 0.498032, 0.071885, 0.434638, -0.0877346, 0.498854, 0.0805517, 0.43611, -0.0968056, 0.499812, 0.0898047, 0.437859, -0.106002, 0.500891, 0.0997142, 0.440017, -0.115648, 0.502198, 0.110289, 0.443236, -0.125427, 0.504389, 0.121644, 0.44697, -0.135492, 0.506809, 0.133769, 0.451689, -0.145746, 0.509858, 0.146787, 0.45811, -0.156219, 0.514247, 0.160793, 0.465305, -0.166834, 0.518816, 0.175791, 0.474085, -0.177546, 0.524331, 0.191906, 0.484808, -0.188262, 0.53104, 0.209199, 0.49732, -0.199346, 0.538511, 0.227825, 0.509693, -0.209951, 0.544554, 0.247269, 0.524367, -0.220533, 0.551616, 0.267978, 0.539228, -0.231082, 0.557368, 0.289672, 0.55644, -0.241342, 0.563782, 0.31268, 0.574204, -0.250964, 0.568851, 0.33651, 0.593388, -0.260306, 0.57312, 0.362219, 0.613358, -0.268667, 0.574916, 0.390322, 0.634512, -0.275591, 0.575053, 0.420478, 0.65563, -0.281328, 0.572404, 0.451614, 0.678265, -0.285948, 0.568893, 0.484112, 0.70011, -0.289408, 0.561878, 0.517348, 0.723005, -0.291328, 0.55359, 0.551355, 0.743744, -0.291418, 0.541099, 0.585109, 0.763949, -0.290252, 0.526489, 0.619487, 0.784186, -0.287648, 0.509496, 0.65404, 0.804304, -0.283782, 0.491484, 0.688649, 0.823629, -0.278067, 0.470517, 0.723133, 0.84094, -0.270588, 0.44705, 0.757163, 0.857852, -0.261188, 0.421252, 0.792816, 0.874934, -0.249313, 0.394191, 0.827248, 0.888709, -0.236492, 0.365359, 0.861074, 0.902589, -0.222185, 0.336016, 0.894417, 0.914201, -0.207314, 0.30527, 0.926825, 0.925978, -0.191146, 0.274532, 0.9595, 0.93512, -0.174135, 0.243393, 0.991583, 0.943656, -0.155231, 0.212414, 1.02356, 0.951719, -0.134403, 0.182005, 1.05239, 0.957164, -0.113023, 0.153043, 1.07754, 0.962656, -0.0914493, 0.124186, 1.09984, 0.970695, -0.0694179, 0.0941654, 1.12, 0.980749, -0.0466199, 0.0629671, 1.13849, 0.991205, -0.0227032, 0.0311146, 1.15494, 0.999884, 0.000632388, -0.000254483, 1.1706, 0.379821, -0.00000957289, 0.460637, 0.00000789337, 0.405188, -0.000247483, 0.491396, 0.000204064, 0.404796, -0.000989434, 0.490914, 0.000815853, 0.40483, -0.00222607, 0.490949, 0.00183559, 0.40473, -0.00395723, 0.49084, 0.00326332, 0.404731, -0.00618287, 0.490836, 0.00509945, 0.404768, -0.00890258, 0.490871, 0.00734463, 0.404791, -0.0121156, 0.490883, 0.00999992, 0.404857, -0.0158214, 0.490938, 0.0130676, 0.404943, -0.0200178, 0.491004, 0.0165503, 0.405059, -0.0247027, 0.491093, 0.0204521, 0.405213, -0.0298729, 0.491205, 0.0247788, 0.405399, -0.0355226, 0.491333, 0.0295373, 0.405731, -0.0416352, 0.491604, 0.034741, 0.406303, -0.0480807, 0.492116, 0.0404255, 0.406814, -0.0550458, 0.492506, 0.0465732, 0.407404, -0.0624652, 0.492926, 0.0532058, 0.408149, -0.0702958, 0.493442, 0.0603442, 0.409128, -0.0784623, 0.494136, 0.0680297, 0.410408, -0.087007, 0.495054, 0.0762786, 0.411813, -0.0959639, 0.495962, 0.0851046, 0.413735, -0.105075, 0.497257, 0.0945878, 0.416137, -0.114646, 0.498882, 0.104725, 0.41934, -0.124394, 0.501132, 0.11563, 0.423326, -0.134328, 0.503883, 0.127325, 0.428419, -0.14458, 0.50747, 0.139911, 0.43484, -0.154979, 0.511964, 0.153481, 0.442641, -0.165628, 0.517328, 0.168114, 0.452511, -0.176365, 0.524258, 0.183995, 0.463473, -0.187298, 0.531248, 0.200953, 0.475564, -0.198244, 0.538367, 0.219176, 0.488664, -0.208938, 0.545175, 0.238514, 0.504073, -0.219599, 0.553227, 0.259129, 0.520832, -0.230378, 0.560653, 0.280997, 0.538455, -0.240703, 0.567523, 0.303821, 0.55709, -0.250548, 0.573287, 0.327948, 0.576646, -0.259964, 0.577795, 0.353362, 0.596705, -0.268721, 0.580077, 0.380336, 0.618053, -0.276054, 0.58018, 0.4101, 0.640303, -0.282176, 0.578747, 0.44161, 0.662365, -0.286931, 0.574294, 0.474106, 0.684542, -0.290521, 0.567035, 0.507549, 0.707984, -0.292672, 0.558687, 0.541853, 0.730913, -0.293189, 0.547606, 0.576581, 0.752948, -0.292199, 0.533471, 0.61172, 0.773452, -0.289508, 0.516395, 0.646339, 0.794715, -0.285716, 0.497873, 0.682131, 0.814251, -0.280051, 0.476845, 0.716396, 0.833057, -0.272873, 0.453449, 0.751503, 0.84959, -0.263982, 0.427857, 0.786085, 0.867022, -0.252745, 0.400335, 0.821355, 0.882277, -0.239655, 0.371304, 0.85646, 0.895375, -0.225386, 0.340397, 0.890828, 0.909347, -0.209587, 0.310005, 0.923532, 0.921885, -0.193433, 0.2796, 0.956419, 0.932127, -0.176135, 0.247276, 0.989445, 0.941869, -0.157872, 0.216186, 1.02221, 0.949735, -0.137577, 0.185602, 1.05195, 0.956617, -0.115285, 0.155767, 1.07822, 0.961974, -0.0928418, 0.126103, 1.10149, 0.96972, -0.0700592, 0.0956758, 1.12207, 0.98012, -0.0474671, 0.0643269, 1.1408, 0.990825, -0.0238113, 0.0320863, 1.1577, 0.999876, 0.000381574, -0.0000812203, 1.17403, 0.367636, -0.00000961342, 0.469176, 0.00000753287, 0.380377, -0.000244772, 0.485434, 0.000191797, 0.380416, -0.000978857, 0.485475, 0.000767015, 0.380376, -0.00220165, 0.485435, 0.00172522, 0.380419, -0.00391408, 0.485487, 0.00306734, 0.380438, -0.00611549, 0.485505, 0.00479332, 0.380462, -0.00880558, 0.485525, 0.00690391, 0.380496, -0.0119837, 0.485551, 0.00940039, 0.38056, -0.0156487, 0.485605, 0.0122848, 0.38064, -0.0197988, 0.485666, 0.0155601, 0.380767, -0.0244324, 0.48577, 0.0192313, 0.380909, -0.0295444, 0.485871, 0.0233032, 0.381142, -0.0351321, 0.48606, 0.0277861, 0.381472, -0.0411535, 0.486336, 0.0326939, 0.382015, -0.0475408, 0.486833, 0.0380565, 0.382523, -0.0544395, 0.487231, 0.0438615, 0.383129, -0.061784, 0.487683, 0.0501332, 0.383952, -0.0695085, 0.488313, 0.0568996, 0.38498, -0.0775819, 0.489077, 0.0641952, 0.386331, -0.0860443, 0.490113, 0.0720324, 0.387788, -0.0948406, 0.491099, 0.0804379, 0.389808, -0.103899, 0.492566, 0.0894899, 0.39252, -0.113313, 0.494601, 0.0992098, 0.395493, -0.123007, 0.496619, 0.109641, 0.399826, -0.132859, 0.499912, 0.120919, 0.405341, -0.143077, 0.504061, 0.133107, 0.411932, -0.153465, 0.508905, 0.146263, 0.420591, -0.164108, 0.515482, 0.160544, 0.43101, -0.174893, 0.523191, 0.176123, 0.441881, -0.185839, 0.53026, 0.192757, 0.453919, -0.196633, 0.537295, 0.210535, 0.468715, -0.207611, 0.546156, 0.229886, 0.485182, -0.218517, 0.555173, 0.250543, 0.501926, -0.229249, 0.562728, 0.27221, 0.51785, -0.239481, 0.567494, 0.294892, 0.536947, -0.249395, 0.573889, 0.318987, 0.557115, -0.259, 0.578831, 0.344348, 0.577966, -0.268075, 0.582055, 0.371223, 0.599489, -0.276115, 0.583307, 0.399834, 0.62479, -0.282523, 0.583902, 0.431415, 0.647504, -0.287663, 0.57953, 0.464301, 0.670601, -0.291538, 0.573103, 0.498123, 0.693539, -0.293842, 0.563731, 0.532662, 0.717385, -0.294681, 0.553169, 0.567925, 0.741533, -0.293717, 0.539908, 0.603502, 0.762142, -0.291156, 0.521902, 0.639074, 0.783014, -0.28719, 0.502815, 0.674439, 0.805158, -0.281773, 0.482598, 0.710497, 0.823646, -0.274682, 0.458949, 0.7456, 0.841879, -0.266184, 0.433129, 0.781085, 0.859515, -0.255682, 0.406064, 0.816, 0.875335, -0.242849, 0.376509, 0.851074, 0.890147, -0.228329, 0.345502, 0.886473, 0.903144, -0.212491, 0.31428, 0.920751, 0.916618, -0.195695, 0.282994, 0.954606, 0.927953, -0.178267, 0.251091, 0.988402, 0.937414, -0.159549, 0.219107, 1.02141, 0.946823, -0.140022, 0.18896, 1.05167, 0.954651, -0.118154, 0.158667, 1.07819, 0.959955, -0.0946636, 0.128808, 1.1025, 0.96858, -0.0711792, 0.0973787, 1.12391, 0.97938, -0.0475046, 0.0650965, 1.14322, 0.990498, -0.024059, 0.0326267, 1.16077, 0.999844, -0.0000512408, 0.000112444, 1.17727, 0.316912, -0.00000934977, 0.425996, 0.00000695559, 0.356423, -0.000241372, 0.479108, 0.000179562, 0.356272, -0.000965292, 0.478897, 0.00071811, 0.356262, -0.00217182, 0.478894, 0.00161574, 0.356265, -0.00386092, 0.478895, 0.00287261, 0.356278, -0.0060324, 0.478905, 0.00448907, 0.356293, -0.00868565, 0.478914, 0.00646572, 0.356346, -0.0118207, 0.478965, 0.00880438, 0.356395, -0.0154355, 0.479001, 0.0115066, 0.356484, -0.019529, 0.479075, 0.0145762, 0.356609, -0.0240991, 0.47918, 0.018018, 0.356766, -0.0291413, 0.479305, 0.0218379, 0.357009, -0.0346498, 0.479512, 0.0260454, 0.357424, -0.0405462, 0.479909, 0.0306657, 0.357899, -0.0468825, 0.480337, 0.0357054, 0.358424, -0.0536887, 0.480771, 0.0411728, 0.359041, -0.0609416, 0.481242, 0.0470841, 0.359903, -0.0685239, 0.481943, 0.0534831, 0.360932, -0.0764883, 0.482741, 0.0603795, 0.362196, -0.0848364, 0.483688, 0.0678028, 0.363847, -0.0935002, 0.484947, 0.0758086, 0.365972, -0.102471, 0.486588, 0.0844173, 0.368741, -0.111751, 0.488787, 0.0937199, 0.372146, -0.121334, 0.491405, 0.103732, 0.377114, -0.131147, 0.495604, 0.114608, 0.38226, -0.141213, 0.499436, 0.126345, 0.389609, -0.151632, 0.505334, 0.139116, 0.397925, -0.162073, 0.51168, 0.152995, 0.407824, -0.172819, 0.518876, 0.168071, 0.420014, -0.183929, 0.527639, 0.184495, 0.434266, -0.195032, 0.537588, 0.20232, 0.447352, -0.205792, 0.544379, 0.221189, 0.463726, -0.216704, 0.553422, 0.241616, 0.481406, -0.227531, 0.562074, 0.263298, 0.498707, -0.238017, 0.568227, 0.286116, 0.518039, -0.247936, 0.574473, 0.3101, 0.538277, -0.257437, 0.579191, 0.335401, 0.561166, -0.266829, 0.584807, 0.362246, 0.583189, -0.275329, 0.586476, 0.390609, 0.606024, -0.28234, 0.585578, 0.420998, 0.632419, -0.287924, 0.584496, 0.454357, 0.656128, -0.291972, 0.577766, 0.488233, 0.679953, -0.29456, 0.56875, 0.523248, 0.704654, -0.295816, 0.558388, 0.559168, 0.729016, -0.295157, 0.544826, 0.595326, 0.752062, -0.292779, 0.528273, 0.631864, 0.773138, -0.288681, 0.508482, 0.667793, 0.794869, -0.283358, 0.487341, 0.704035, 0.815101, -0.27608, 0.46354, 0.739925, 0.834212, -0.26767, 0.438672, 0.775539, 0.852368, -0.257397, 0.411239, 0.810895, 0.870207, -0.245689, 0.3829, 0.846472, 0.884063, -0.231452, 0.351496, 0.881788, 0.898284, -0.215561, 0.31895, 0.917438, 0.912964, -0.198208, 0.287367, 0.952422, 0.924666, -0.180426, 0.254487, 0.987551, 0.934429, -0.161525, 0.222226, 1.02142, 0.943485, -0.141197, 0.191143, 1.05218, 0.9521, -0.120085, 0.161112, 1.07937, 0.957876, -0.0975881, 0.130982, 1.10403, 0.966943, -0.0726842, 0.0990553, 1.12616, 0.978313, -0.0483705, 0.0662818, 1.14619, 0.990048, -0.0239072, 0.0329243, 1.16413, 0.999984, 0.000461885, -0.0000772859, 1.18099, 0.321287, -0.00000935049, 0.455413, 0.00000659662, 0.332595, -0.000237513, 0.471437, 0.000167562, 0.332729, -0.000949964, 0.471618, 0.000670192, 0.332305, -0.00213618, 0.471028, 0.00150712, 0.332326, -0.00379765, 0.471055, 0.00267959, 0.332344, -0.00593353, 0.471072, 0.00418751, 0.332356, -0.00854349, 0.471077, 0.00603172, 0.332403, -0.0116268, 0.471121, 0.00821362, 0.332461, -0.0151824, 0.47117, 0.0107357, 0.332552, -0.0192088, 0.471251, 0.0136014, 0.332657, -0.0237024, 0.47133, 0.0168152, 0.332835, -0.0286615, 0.471487, 0.0203853, 0.333083, -0.0340765, 0.471708, 0.0243212, 0.333547, -0.0398563, 0.47219, 0.0286518, 0.333989, -0.0460916, 0.472587, 0.0333763, 0.334532, -0.0527897, 0.473054, 0.0385084, 0.335167, -0.0599284, 0.473568, 0.0440638, 0.33608, -0.0673514, 0.474362, 0.0500962, 0.337146, -0.0752237, 0.475231, 0.0566022, 0.338462, -0.083418, 0.476282, 0.0636272, 0.34014, -0.0919382, 0.477615, 0.0712153, 0.342341, -0.100741, 0.479404, 0.079417, 0.345088, -0.109905, 0.481618, 0.0882631, 0.349049, -0.119369, 0.485081, 0.0978851, 0.353939, -0.129033, 0.489317, 0.108336, 0.359893, -0.139038, 0.494309, 0.119698, 0.366945, -0.149411, 0.499983, 0.132024, 0.375814, -0.159843, 0.507185, 0.145558, 0.387112, -0.170664, 0.516392, 0.160433, 0.40023, -0.181897, 0.526519, 0.176648, 0.412555, -0.192785, 0.53423, 0.193922, 0.427023, -0.203663, 0.542741, 0.212662, 0.443685, -0.214695, 0.552066, 0.232944, 0.461499, -0.225561, 0.560762, 0.254495, 0.480975, -0.236257, 0.569421, 0.277531, 0.501, -0.24639, 0.576101, 0.301724, 0.521691, -0.256101, 0.581493, 0.327112, 0.543478, -0.265289, 0.585221, 0.353917, 0.566094, -0.273938, 0.587614, 0.381941, 0.589578, -0.281679, 0.587991, 0.41172, 0.614583, -0.287655, 0.585928, 0.444148, 0.641813, -0.292228, 0.582092, 0.478617, 0.666189, -0.295172, 0.57398, 0.51397, 0.690475, -0.29648, 0.561676, 0.550118, 0.715543, -0.296203, 0.548758, 0.586933, 0.740405, -0.293999, 0.532792, 0.62384, 0.762183, -0.28998, 0.512735, 0.660723, 0.786069, -0.28478, 0.492402, 0.69807, 0.806812, -0.277568, 0.469058, 0.734422, 0.826987, -0.268951, 0.443017, 0.770946, 0.844588, -0.259049, 0.415501, 0.80699, 0.863725, -0.2471, 0.387328, 0.842107, 0.879137, -0.234157, 0.356108, 0.878078, 0.894634, -0.218719, 0.324315, 0.914058, 0.909162, -0.201293, 0.291813, 0.949922, 0.92072, -0.18267, 0.258474, 0.985337, 0.93158, -0.163212, 0.225593, 1.0205, 0.941238, -0.142771, 0.193986, 1.05273, 0.949293, -0.120956, 0.163392, 1.08075, 0.956226, -0.0985743, 0.132934, 1.10559, 0.96546, -0.075118, 0.101255, 1.12823, 0.977403, -0.0497921, 0.0675441, 1.149, 0.989648, -0.0241574, 0.0334681, 1.16765, 1.00001, 0.0005762, -0.000184807, 1.18519, 0.303474, -0.00000916603, 0.4542, 0.0000061243, 0.308894, -0.000232869, 0.462306, 0.000155592, 0.309426, -0.000931661, 0.463093, 0.000622499, 0.308643, -0.0020949, 0.461933, 0.00139979, 0.308651, -0.0037242, 0.461941, 0.00248874, 0.308662, -0.00581873, 0.46195, 0.00388933, 0.308687, -0.00837818, 0.461974, 0.00560247, 0.308728, -0.0114016, 0.462011, 0.00762948, 0.308789, -0.0148884, 0.462067, 0.00997326, 0.308882, -0.0188369, 0.462151, 0.0126375, 0.309007, -0.0232436, 0.462263, 0.0156271, 0.30918, -0.0281054, 0.462417, 0.0189498, 0.309442, -0.0334065, 0.462667, 0.0226167, 0.309901, -0.0390589, 0.463162, 0.0266614, 0.310331, -0.0452042, 0.463555, 0.0310715, 0.310858, -0.0517735, 0.464019, 0.0358698, 0.311576, -0.0587359, 0.464669, 0.0410848, 0.312436, -0.0660383, 0.465406, 0.0467453, 0.313526, -0.0737266, 0.466339, 0.0528718, 0.314903, -0.0817574, 0.467504, 0.0595039, 0.316814, -0.090167, 0.469226, 0.0666888, 0.318965, -0.0987555, 0.470981, 0.0744658, 0.322077, -0.107792, 0.473814, 0.082912, 0.325947, -0.117098, 0.477241, 0.0920846, 0.331008, -0.126602, 0.48184, 0.102137, 0.337893, -0.136619, 0.488334, 0.113135, 0.345106, -0.146838, 0.494415, 0.12511, 0.355111, -0.157357, 0.503275, 0.138356, 0.365095, -0.167955, 0.510966, 0.152686, 0.378344, -0.179157, 0.521508, 0.16856, 0.391599, -0.190143, 0.530455, 0.18561, 0.407786, -0.20123, 0.541275, 0.204308, 0.425294, -0.212456, 0.551784, 0.224623, 0.444021, -0.223568, 0.561493, 0.246172, 0.463418, -0.234154, 0.569886, 0.268979, 0.484077, -0.244546, 0.577116, 0.293411, 0.505513, -0.254301, 0.582914, 0.318936, 0.527672, -0.263564, 0.587208, 0.345856, 0.550565, -0.272332, 0.589277, 0.374054, 0.573656, -0.280011, 0.588426, 0.403276, 0.59827, -0.286924, 0.587504, 0.43474, 0.624731, -0.291994, 0.583401, 0.468767, 0.652396, -0.295159, 0.576997, 0.504411, 0.67732, -0.296954, 0.565863, 0.54114, 0.703147, -0.296877, 0.552316, 0.57816, 0.728715, -0.295147, 0.536773, 0.616124, 0.752448, -0.291275, 0.51771, 0.653885, 0.775169, -0.285905, 0.496087, 0.691537, 0.799307, -0.279064, 0.474232, 0.729251, 0.819482, -0.270294, 0.447676, 0.766267, 0.837659, -0.260032, 0.419656, 0.802616, 0.856903, -0.248497, 0.391328, 0.838583, 0.873325, -0.235252, 0.360285, 0.874711, 0.889788, -0.221126, 0.329215, 0.91077, 0.904486, -0.204304, 0.296392, 0.94653, 0.917711, -0.185562, 0.262159, 0.983828, 0.928969, -0.165635, 0.229142, 1.01955, 0.939707, -0.14442, 0.19673, 1.05317, 0.948167, -0.122147, 0.165095, 1.0823, 0.955222, -0.099098, 0.13451, 1.10791, 0.964401, -0.0755332, 0.102476, 1.1312, 0.976605, -0.0513817, 0.0689667, 1.15218, 0.989085, -0.0258499, 0.034506, 1.17129, 0.999908, 0.000617773, -0.000271268, 1.18961, 0.285803, -0.00000905752, 0.452348, 0.00000572272, 0.284689, -0.00022732, 0.450581, 0.000143626, 0.285263, -0.000910214, 0.451482, 0.000575099, 0.285302, -0.00204784, 0.451553, 0.00129395, 0.285318, -0.00364057, 0.451574, 0.0023006, 0.28533, -0.00568813, 0.451585, 0.00359547, 0.285361, -0.00819001, 0.451618, 0.00517934, 0.285397, -0.0111458, 0.45165, 0.007054, 0.285447, -0.0145536, 0.451688, 0.00922167, 0.285527, -0.0184127, 0.451758, 0.0116869, 0.285688, -0.0227207, 0.451929, 0.0144555, 0.28584, -0.0274712, 0.452055, 0.0175341, 0.286136, -0.0326278, 0.452369, 0.0209406, 0.286574, -0.0381792, 0.452853, 0.0246965, 0.287012, -0.0441879, 0.453272, 0.0287996, 0.287542, -0.0506096, 0.453752, 0.033268, 0.288299, -0.0573634, 0.454488, 0.0381504, 0.289186, -0.0645458, 0.455294, 0.0434447, 0.290302, -0.0720405, 0.456301, 0.0491973, 0.291776, -0.0799046, 0.457648, 0.0554453, 0.29372, -0.088117, 0.459483, 0.0622311, 0.296052, -0.0965328, 0.461571, 0.0695992, 0.299563, -0.105409, 0.465085, 0.077658, 0.30335, -0.114553, 0.468506, 0.0864176, 0.309167, -0.123917, 0.474423, 0.0961078, 0.31529, -0.13381, 0.47995, 0.106643, 0.324163, -0.144021, 0.488592, 0.118322, 0.333272, -0.154382, 0.496461, 0.131133, 0.344224, -0.165015, 0.50562, 0.145208, 0.357733, -0.176168, 0.516719, 0.16073, 0.373046, -0.187468, 0.528513, 0.177807, 0.38788, -0.198488, 0.537713, 0.196072, 0.405133, -0.209545, 0.547999, 0.21605, 0.423845, -0.220724, 0.55759, 0.237484, 0.443777, -0.231518, 0.566246, 0.26039, 0.464824, -0.242035, 0.574326, 0.284835, 0.486635, -0.251898, 0.58037, 0.310518, 0.51012, -0.261304, 0.58568, 0.337678, 0.535301, -0.270384, 0.590197, 0.366242, 0.559193, -0.27841, 0.590569, 0.395873, 0.583544, -0.285325, 0.588161, 0.426857, 0.608834, -0.291113, 0.584249, 0.459477, 0.635753, -0.294882, 0.57763, 0.494734, 0.664367, -0.297088, 0.569479, 0.532023, 0.689688, -0.297364, 0.555064, 0.569629, 0.715732, -0.295949, 0.539522, 0.608124, 0.741307, -0.292259, 0.521613, 0.646231, 0.764949, -0.287063, 0.49969, 0.684938, 0.788599, -0.28012, 0.476747, 0.723548, 0.81048, -0.27153, 0.45116, 0.761135, 0.831372, -0.261289, 0.424101, 0.798916, 0.850092, -0.249559, 0.39443, 0.835952, 0.867777, -0.236348, 0.363849, 0.871606, 0.884632, -0.221569, 0.332477, 0.907843, 0.90047, -0.20618, 0.300667, 0.944187, 0.914524, -0.188771, 0.266552, 0.981371, 0.926892, -0.168362, 0.232349, 1.01841, 0.937951, -0.146761, 0.199359, 1.05308, 0.947236, -0.123813, 0.1675, 1.0839, 0.954367, -0.099984, 0.136166, 1.11047, 0.963907, -0.0759278, 0.103808, 1.13414, 0.976218, -0.0511367, 0.0697061, 1.15575, 0.988772, -0.0267415, 0.0352529, 1.17531, 0.999888, -0.000520778, 0.000289926, 1.19389, 0.263546, -0.00000883274, 0.441896, 0.00000526783, 0.262352, -0.000221849, 0.439889, 0.000132311, 0.262325, -0.000886683, 0.439848, 0.000528824, 0.26228, -0.00199476, 0.439765, 0.00118975, 0.262372, -0.00354671, 0.439922, 0.00211568, 0.26239, -0.00554141, 0.439941, 0.00330652, 0.262412, -0.00797888, 0.439961, 0.00476346, 0.262453, -0.0108584, 0.440002, 0.00648818, 0.262528, -0.0141788, 0.440085, 0.0084835, 0.262615, -0.017938, 0.440166, 0.0107533, 0.262744, -0.0221346, 0.440291, 0.0133044, 0.262939, -0.026762, 0.440493, 0.0161445, 0.263277, -0.0317573, 0.440889, 0.0192974, 0.26368, -0.0371832, 0.441338, 0.0227699, 0.264106, -0.0430371, 0.441753, 0.0265698, 0.264624, -0.0493035, 0.442227, 0.0307178, 0.265378, -0.0558669, 0.442985, 0.0352616, 0.266253, -0.0628718, 0.443795, 0.0401968, 0.267478, -0.0701569, 0.445008, 0.04559, 0.269062, -0.077845, 0.446599, 0.0514539, 0.270926, -0.0857941, 0.448349, 0.0578382, 0.273693, -0.0940773, 0.451221, 0.0648363, 0.276746, -0.102704, 0.454097, 0.0724389, 0.281693, -0.111735, 0.459517, 0.0808744, 0.287335, -0.121004, 0.46531, 0.0901551, 0.29448, -0.130734, 0.472605, 0.100371, 0.30257, -0.140777, 0.480251, 0.111644, 0.312465, -0.15111, 0.489444, 0.124111, 0.324856, -0.16189, 0.500919, 0.137979, 0.33774, -0.172946, 0.511317, 0.153163, 0.35255, -0.184152, 0.522684, 0.169817, 0.367786, -0.19522, 0.53248, 0.187886, 0.385474, -0.20632, 0.543326, 0.207634, 0.404976, -0.217744, 0.554109, 0.229165, 0.425203, -0.228691, 0.563395, 0.252068, 0.446704, -0.239299, 0.571565, 0.276471, 0.468951, -0.249348, 0.577935, 0.302323, 0.493487, -0.258933, 0.584309, 0.329882, 0.517861, -0.268009, 0.58773, 0.358525, 0.543309, -0.276238, 0.589612, 0.388585, 0.569704, -0.28356, 0.589294, 0.419787, 0.594871, -0.289497, 0.585137, 0.452114, 0.622555, -0.294452, 0.580356, 0.486466, 0.651167, -0.296918, 0.57185, 0.523079, 0.677332, -0.297647, 0.558428, 0.5611, 0.703718, -0.296321, 0.542232, 0.599592, 0.730262, -0.293339, 0.524541, 0.639138, 0.754304, -0.288036, 0.502691, 0.677978, 0.778051, -0.281018, 0.479212, 0.716537, 0.801557, -0.272414, 0.454071, 0.75586, 0.822559, -0.262419, 0.425952, 0.794477, 0.843051, -0.250702, 0.397313, 0.832664, 0.86232, -0.237264, 0.366534, 0.869876, 0.879044, -0.222716, 0.334816, 0.906973, 0.896362, -0.206827, 0.303143, 0.943558, 0.910342, -0.189659, 0.269699, 0.979759, 0.924119, -0.171108, 0.236411, 1.01718, 0.935374, -0.149579, 0.202224, 1.05289, 0.944295, -0.126295, 0.16989, 1.08496, 0.952227, -0.101511, 0.138089, 1.11256, 0.962041, -0.0766392, 0.105053, 1.1375, 0.97528, -0.0511967, 0.070329, 1.15983, 0.988476, -0.025463, 0.0351268, 1.17987, 0.999962, 0.0000286808, 0.0000145564, 1.19901, 0.227089, -0.00000841413, 0.404216, 0.00000472707, 0.239725, -0.000215083, 0.426708, 0.000120833, 0.239904, -0.000860718, 0.427028, 0.000483555, 0.239911, -0.00193661, 0.427039, 0.00108806, 0.239914, -0.00344276, 0.42704, 0.00193457, 0.239933, -0.00537907, 0.427064, 0.00302363, 0.239944, -0.00774482, 0.427065, 0.00435604, 0.239993, -0.01054, 0.427122, 0.00593398, 0.240052, -0.0137626, 0.427179, 0.00775987, 0.240148, -0.0174115, 0.427279, 0.00983854, 0.240278, -0.021484, 0.42741, 0.0121763, 0.240472, -0.0259729, 0.427618, 0.0147827, 0.240839, -0.0308131, 0.428086, 0.0176837, 0.241201, -0.0360893, 0.428482, 0.0208775, 0.241626, -0.0417723, 0.428907, 0.0243821, 0.242207, -0.0478337, 0.42952, 0.0282228, 0.24298, -0.0542199, 0.430332, 0.0324333, 0.243881, -0.0610015, 0.431222, 0.0370252, 0.245123, -0.0680874, 0.432512, 0.0420535, 0.24667, -0.0755482, 0.434088, 0.0475414, 0.248779, -0.0832873, 0.436323, 0.0535542, 0.251665, -0.0913546, 0.439509, 0.0601716, 0.255305, -0.0998489, 0.443478, 0.0674282, 0.260049, -0.108576, 0.448713, 0.0754673, 0.266192, -0.117754, 0.455524, 0.084339, 0.273158, -0.127294, 0.4627, 0.0941683, 0.282131, -0.137311, 0.472068, 0.10515, 0.293332, -0.147736, 0.483565, 0.117402, 0.304667, -0.158357, 0.493702, 0.130824, 0.317785, -0.169274, 0.504708, 0.145724, 0.333245, -0.180595, 0.517107, 0.16215, 0.349843, -0.191892, 0.528849, 0.180149, 0.367944, -0.203168, 0.540301, 0.199746, 0.387579, -0.214443, 0.551514, 0.221047, 0.408247, -0.225624, 0.560906, 0.243981, 0.43014, -0.236422, 0.56959, 0.268513, 0.452669, -0.24654, 0.576098, 0.294409, 0.476196, -0.256157, 0.580925, 0.322002, 0.501157, -0.265289, 0.584839, 0.351052, 0.527632, -0.273671, 0.587614, 0.3812, 0.555754, -0.281254, 0.589119, 0.412994, 0.581682, -0.287448, 0.585204, 0.445498, 0.608196, -0.292614, 0.579006, 0.479505, 0.635661, -0.296068, 0.571297, 0.514643, 0.664999, -0.297395, 0.560855, 0.552213, 0.691039, -0.296645, 0.544525, 0.591365, 0.7179, -0.293785, 0.526535, 0.630883, 0.744059, -0.289089, 0.50545, 0.670932, 0.76863, -0.282239, 0.482514, 0.710904, 0.793273, -0.273688, 0.457246, 0.750259, 0.814731, -0.26328, 0.428872, 0.78948, 0.835603, -0.251526, 0.399384, 0.828597, 0.85489, -0.238339, 0.368811, 0.866892, 0.872828, -0.223607, 0.336617, 0.90563, 0.889462, -0.207538, 0.303997, 0.943538, 0.904929, -0.190297, 0.270812, 0.980591, 0.919101, -0.172034, 0.237453, 1.01935, 0.930536, -0.152058, 0.204431, 1.05498, 0.941223, -0.129515, 0.172495, 1.08717, 0.94982, -0.104263, 0.140175, 1.11551, 0.960592, -0.0781944, 0.106465, 1.14098, 0.974629, -0.051688, 0.0711592, 1.16418, 0.98811, -0.0253929, 0.0354432, 1.18465, 1.00004, 0.000804378, -0.000330876, 1.20462, 0.214668, -0.00000821282, 0.406619, 0.00000433582, 0.218053, -0.000208144, 0.413025, 0.000109887, 0.217987, -0.000832212, 0.412901, 0.000439362, 0.217971, -0.00187246, 0.412876, 0.000988623, 0.217968, -0.00332855, 0.41286, 0.00175772, 0.217985, -0.00520055, 0.412882, 0.00274729, 0.218014, -0.00748814, 0.412916, 0.00395842, 0.218054, -0.0101901, 0.412957, 0.00539274, 0.218106, -0.0133057, 0.413005, 0.00705348, 0.218217, -0.0168342, 0.413139, 0.00894581, 0.218338, -0.0207707, 0.413258, 0.0110754, 0.21855, -0.0251001, 0.413509, 0.0134551, 0.218913, -0.0297861, 0.413992, 0.0161081, 0.219265, -0.0348956, 0.414383, 0.0190307, 0.219696, -0.0403909, 0.414839, 0.0222458, 0.220329, -0.0462003, 0.415567, 0.025792, 0.220989, -0.0524208, 0.41621, 0.0296637, 0.222027, -0.058948, 0.417385, 0.0339323, 0.223301, -0.0658208, 0.418779, 0.0386055, 0.224988, -0.0730347, 0.420665, 0.0437355, 0.227211, -0.0805274, 0.423198, 0.0493844, 0.230131, -0.088395, 0.426566, 0.0556135, 0.233908, -0.0966208, 0.43091, 0.0624829, 0.239092, -0.105223, 0.437148, 0.0701636, 0.245315, -0.11424, 0.444302, 0.0786949, 0.253166, -0.12368, 0.453262, 0.0882382, 0.262374, -0.133569, 0.463211, 0.0988682, 0.273145, -0.143836, 0.474271, 0.110727, 0.285512, -0.154577, 0.4863, 0.123945, 0.299512, -0.165501, 0.498817, 0.138581, 0.314287, -0.176698, 0.510341, 0.154676, 0.331083, -0.188066, 0.522583, 0.172459, 0.349615, -0.199597, 0.534879, 0.191979, 0.369318, -0.210843, 0.546083, 0.21309, 0.390377, -0.222068, 0.5562, 0.235998, 0.412411, -0.233059, 0.564704, 0.260518, 0.435715, -0.24357, 0.572314, 0.286795, 0.461196, -0.253356, 0.579395, 0.314559, 0.485587, -0.262362, 0.581985, 0.343581, 0.511908, -0.270895, 0.584347, 0.374367, 0.539798, -0.278452, 0.58505, 0.406015, 0.567974, -0.284877, 0.583344, 0.439168, 0.594303, -0.290124, 0.577348, 0.473005, 0.622951, -0.294183, 0.570751, 0.508534, 0.652404, -0.296389, 0.561541, 0.544764, 0.679291, -0.296605, 0.546426, 0.582927, 0.706437, -0.294095, 0.528599, 0.622681, 0.734485, -0.28978, 0.508676, 0.663567, 0.758841, -0.283363, 0.484768, 0.704092, 0.78537, -0.275015, 0.460434, 0.745101, 0.807315, -0.264689, 0.432166, 0.784712, 0.8271, -0.252597, 0.401807, 0.824241, 0.849191, -0.239154, 0.371458, 0.863803, 0.867046, -0.224451, 0.338873, 0.903063, 0.8852, -0.208342, 0.306175, 0.942763, 0.901771, -0.190684, 0.272759, 0.981559, 0.915958, -0.172105, 0.239306, 1.02048, 0.928046, -0.152214, 0.206071, 1.05765, 0.939961, -0.130247, 0.17367, 1.08999, 0.948711, -0.10672, 0.142201, 1.11829, 0.959305, -0.0808688, 0.108454, 1.14467, 0.973009, -0.0539145, 0.0728109, 1.16839, 0.987631, -0.0262947, 0.0360625, 1.19004, 0.999978, 0.00132758, -0.000559424, 1.21058, 0.193925, -0.00000793421, 0.391974, 0.00000392537, 0.196746, -0.000200315, 0.397675, 0.0000991033, 0.19667, -0.000801099, 0.397521, 0.000396342, 0.196633, -0.00180246, 0.397445, 0.000891829, 0.196654, -0.00320443, 0.397482, 0.00158582, 0.196659, -0.00500647, 0.39748, 0.00247867, 0.196683, -0.0072086, 0.397506, 0.00357167, 0.196728, -0.00981001, 0.397562, 0.00486675, 0.196792, -0.0128096, 0.397633, 0.00636707, 0.19689, -0.0162055, 0.397746, 0.00807752, 0.197017, -0.0199943, 0.397884, 0.0100052, 0.19729, -0.024139, 0.39827, 0.0121691, 0.197583, -0.0286671, 0.398639, 0.0145755, 0.197927, -0.0335858, 0.399034, 0.0172355, 0.198383, -0.0388806, 0.399554, 0.0201718, 0.199002, -0.0444736, 0.400289, 0.0234194, 0.199739, -0.0504583, 0.401111, 0.026984, 0.200784, -0.056729, 0.402349, 0.0309217, 0.202075, -0.0633643, 0.403841, 0.0352496, 0.203898, -0.0703247, 0.406076, 0.0400313, 0.206199, -0.0775565, 0.408841, 0.0453282, 0.209252, -0.085184, 0.41259, 0.0511794, 0.213638, -0.0931994, 0.418288, 0.0577459, 0.21881, -0.101617, 0.424681, 0.0650508, 0.225642, -0.11052, 0.433429, 0.0732759, 0.233717, -0.119772, 0.442897, 0.0824683, 0.242823, -0.129505, 0.452888, 0.0927484, 0.254772, -0.139906, 0.466407, 0.104417, 0.266603, -0.150402, 0.477413, 0.117211, 0.28073, -0.161395, 0.490519, 0.131598, 0.295399, -0.172465, 0.50201, 0.147407, 0.312705, -0.183982, 0.515311, 0.165031, 0.331335, -0.195532, 0.52786, 0.184336, 0.351037, -0.206971, 0.5392, 0.205361, 0.372175, -0.218117, 0.54941, 0.228043, 0.394548, -0.229327, 0.558642, 0.25267, 0.419598, -0.240052, 0.567861, 0.279071, 0.443922, -0.249937, 0.573332, 0.306882, 0.471495, -0.259407, 0.58013, 0.33661, 0.496769, -0.267749, 0.580564, 0.367328, 0.524951, -0.275524, 0.581696, 0.399753, 0.55318, -0.282148, 0.579885, 0.433134, 0.581577, -0.287533, 0.575471, 0.467534, 0.609231, -0.291612, 0.567445, 0.502943, 0.637478, -0.293911, 0.557657, 0.53871, 0.667795, -0.295096, 0.546535, 0.576568, 0.694272, -0.294073, 0.529561, 0.614929, 0.722937, -0.290386, 0.510561, 0.655909, 0.749682, -0.284481, 0.487846, 0.697663, 0.774754, -0.276188, 0.462487, 0.738515, 0.799301, -0.266215, 0.43481, 0.779802, 0.820762, -0.254116, 0.404879, 0.820045, 0.843231, -0.240393, 0.374559, 0.860294, 0.861857, -0.225503, 0.341582, 0.900965, 0.880815, -0.209382, 0.308778, 0.941727, 0.89766, -0.19155, 0.275232, 0.980916, 0.912926, -0.172346, 0.240938, 1.02162, 0.926391, -0.151799, 0.207223, 1.0597, 0.938429, -0.129968, 0.17484, 1.09291, 0.947834, -0.10651, 0.142984, 1.12248, 0.958432, -0.0824098, 0.109902, 1.149, 0.972402, -0.0565242, 0.0744454, 1.1733, 0.987191, -0.028427, 0.0373794, 1.19538, 0.999975, 0.0000385685, -0.00004203, 1.21676, 0.178114, -0.00000766075, 0.385418, 0.00000354027, 0.176074, -0.000191966, 0.381002, 0.0000887135, 0.17601, -0.000767549, 0.380861, 0.000354715, 0.17598, -0.00172696, 0.380798, 0.000798168, 0.175994, -0.00307012, 0.380824, 0.00141928, 0.176017, -0.00479684, 0.380858, 0.00221859, 0.176019, -0.00690648, 0.380839, 0.00319714, 0.176072, -0.00939888, 0.380913, 0.0043572, 0.176131, -0.0122726, 0.380979, 0.005702, 0.176239, -0.0155264, 0.38112, 0.00723689, 0.176371, -0.0191551, 0.381272, 0.00896907, 0.176638, -0.023117, 0.381669, 0.0109194, 0.176912, -0.0274633, 0.382015, 0.0130903, 0.177279, -0.032173, 0.382476, 0.0154949, 0.17774, -0.0372219, 0.383041, 0.0181669, 0.178344, -0.0426132, 0.38378, 0.0211209, 0.179153, -0.0483309, 0.384773, 0.0243899, 0.180197, -0.0543447, 0.386076, 0.0280062, 0.181581, -0.0607122, 0.387809, 0.032004, 0.18344, -0.0673855, 0.390205, 0.036453, 0.186139, -0.0743989, 0.393944, 0.0414162, 0.189432, -0.0817731, 0.39832, 0.0469394, 0.193795, -0.0895464, 0.404188, 0.0531442, 0.199641, -0.0978264, 0.4121, 0.0601374, 0.206679, -0.106499, 0.421425, 0.0680078, 0.214865, -0.115654, 0.431504, 0.076919, 0.224406, -0.125268, 0.442526, 0.0868835, 0.235876, -0.135475, 0.455465, 0.0981875, 0.248335, -0.146023, 0.4681, 0.110759, 0.262868, -0.157016, 0.482069, 0.124885, 0.278962, -0.168245, 0.496182, 0.140645, 0.295082, -0.17958, 0.507401, 0.157838, 0.313738, -0.191227, 0.520252, 0.17695, 0.333573, -0.202718, 0.531708, 0.197817, 0.356433, -0.214424, 0.544509, 0.220785, 0.378853, -0.225492, 0.55373, 0.245306, 0.402717, -0.236236, 0.561348, 0.271593, 0.428375, -0.246568, 0.568538, 0.299776, 0.454724, -0.255941, 0.573462, 0.329433, 0.482291, -0.264511, 0.576356, 0.360598, 0.509706, -0.272129, 0.576446, 0.393204, 0.538805, -0.278979, 0.575298, 0.427227, 0.568919, -0.284528, 0.572154, 0.462157, 0.596804, -0.288801, 0.564691, 0.497997, 0.625987, -0.291334, 0.555134, 0.534467, 0.656414, -0.292722, 0.545051, 0.571736, 0.683916, -0.292185, 0.528813, 0.610158, 0.711809, -0.290043, 0.51106, 0.649061, 0.739547, -0.285246, 0.490103, 0.690081, 0.766914, -0.277647, 0.465523, 0.732554, 0.791375, -0.267603, 0.437718, 0.773982, 0.814772, -0.256109, 0.40882, 0.81609, 0.836691, -0.242281, 0.377823, 0.856849, 0.856984, -0.227155, 0.34496, 0.898363, 0.876332, -0.210395, 0.311335, 0.939471, 0.894988, -0.192612, 0.277703, 0.980799, 0.911113, -0.173236, 0.243019, 1.02215, 0.924092, -0.152258, 0.209037, 1.06139, 0.936828, -0.129575, 0.175909, 1.09635, 0.946869, -0.10594, 0.143852, 1.12707, 0.958284, -0.081318, 0.110289, 1.15419, 0.972325, -0.0556133, 0.0747232, 1.17909, 0.986878, -0.0297899, 0.0383149, 1.20163, 0.999936, -0.00197169, 0.000912402, 1.22338, 0.151174, -0.00000720365, 0.351531, 0.00000309789, 0.155594, -0.00018279, 0.361806, 0.000078608, 0.156099, -0.000731569, 0.362982, 0.000314615, 0.156053, -0.00164578, 0.362869, 0.000707845, 0.156093, -0.0029261, 0.362961, 0.00125884, 0.156099, -0.00457155, 0.362959, 0.00196783, 0.15612, -0.00658224, 0.362982, 0.00283622, 0.156168, -0.00895774, 0.363048, 0.00386625, 0.156221, -0.0116962, 0.363101, 0.00506109, 0.156324, -0.0147973, 0.363241, 0.00642675, 0.156476, -0.0182503, 0.363448, 0.00797175, 0.156731, -0.0220266, 0.36384, 0.00971484, 0.156994, -0.026176, 0.364179, 0.0116575, 0.157341, -0.0306701, 0.36462, 0.0138207, 0.157867, -0.0354591, 0.365364, 0.0162356, 0.15846, -0.0406141, 0.366111, 0.0189092, 0.159308, -0.0460519, 0.367248, 0.021885, 0.160426, -0.0518096, 0.368767, 0.0252004, 0.161877, -0.0578906, 0.370745, 0.0288825, 0.163995, -0.0642812, 0.373831, 0.0330139, 0.16655, -0.0710067, 0.377366, 0.0376283, 0.170237, -0.0781522, 0.382799, 0.0428493, 0.175096, -0.0857172, 0.389915, 0.0487324, 0.181069, -0.0938025, 0.398487, 0.0554214, 0.188487, -0.102363, 0.408799, 0.0630189, 0.197029, -0.111343, 0.419991, 0.071634, 0.206684, -0.120812, 0.431455, 0.0812797, 0.218698, -0.131033, 0.445746, 0.0923651, 0.230726, -0.141373, 0.457471, 0.104545, 0.245516, -0.152387, 0.472388, 0.118449, 0.261551, -0.163628, 0.486671, 0.133923, 0.277437, -0.174814, 0.49762, 0.150849, 0.296662, -0.186713, 0.51162, 0.169924, 0.31795, -0.198513, 0.525435, 0.190848, 0.339422, -0.210119, 0.536267, 0.213504, 0.362143, -0.221354, 0.545982, 0.237947, 0.387198, -0.23224, 0.555364, 0.264427, 0.412349, -0.24257, 0.561489, 0.292519, 0.439274, -0.252284, 0.566903, 0.322561, 0.466779, -0.261023, 0.569614, 0.353952, 0.496011, -0.26899, 0.571589, 0.387278, 0.524964, -0.275498, 0.570325, 0.421356, 0.556518, -0.281449, 0.568792, 0.457314, 0.584363, -0.285526, 0.560268, 0.493199, 0.614214, -0.28844, 0.55205, 0.530276, 0.645684, -0.289777, 0.541906, 0.56855, 0.673446, -0.289722, 0.526464, 0.606927, 0.701924, -0.287792, 0.509872, 0.645945, 0.73037, -0.284315, 0.490649, 0.685564, 0.757405, -0.278804, 0.467964, 0.726511, 0.784025, -0.269543, 0.441468, 0.768601, 0.808255, -0.258117, 0.41216, 0.811321, 0.830739, -0.244728, 0.380606, 0.853496, 0.851914, -0.229428, 0.348111, 0.895374, 0.872586, -0.212508, 0.314732, 0.937674, 0.891581, -0.194025, 0.280338, 0.979869, 0.907641, -0.174711, 0.245203, 1.02253, 0.922233, -0.153509, 0.21077, 1.06371, 0.935878, -0.130418, 0.177399, 1.09972, 0.946338, -0.105558, 0.144507, 1.13124, 0.957265, -0.080059, 0.110508, 1.15973, 0.971668, -0.0539766, 0.0742311, 1.18515, 0.9866, -0.0277101, 0.0375224, 1.20858, 1.00021, -0.000515531, 0.000135226, 1.23135, 0.137468, -0.00000686011, 0.345041, 0.00000273315, 0.13703, -0.000173378, 0.343936, 0.0000690761, 0.136986, -0.000693048, 0.34383, 0.000276126, 0.136964, -0.00155931, 0.343761, 0.000621337, 0.137003, -0.00277211, 0.343863, 0.00110494, 0.137012, -0.00433103, 0.343868, 0.00172744, 0.137043, -0.00623606, 0.343916, 0.00249022, 0.13709, -0.0084868, 0.343986, 0.00339559, 0.137145, -0.0110814, 0.344045, 0.00444687, 0.137242, -0.0140187, 0.344177, 0.00565007, 0.137431, -0.0172713, 0.344491, 0.00701868, 0.137644, -0.0208605, 0.344805, 0.00856042, 0.13791, -0.024792, 0.345172, 0.0102863, 0.138295, -0.0290461, 0.345734, 0.0122185, 0.138764, -0.0335957, 0.346371, 0.0143771, 0.139415, -0.038467, 0.347298, 0.0167894, 0.140272, -0.0436176, 0.348527, 0.0194895, 0.141457, -0.0491016, 0.350276, 0.0225043, 0.14303, -0.0548764, 0.352646, 0.0258962, 0.145289, -0.0610096, 0.356206, 0.0297168, 0.148502, -0.0674777, 0.361488, 0.0340562, 0.152188, -0.074345, 0.367103, 0.0389534, 0.157359, -0.0817442, 0.375247, 0.0445541, 0.16379, -0.0896334, 0.385064, 0.0509535, 0.171376, -0.098005, 0.396082, 0.0582611, 0.179901, -0.106817, 0.407418, 0.06654, 0.189892, -0.116239, 0.420031, 0.075994, 0.201838, -0.12627, 0.434321, 0.0867239, 0.214311, -0.136701, 0.447631, 0.0987517, 0.228902, -0.147616, 0.462046, 0.112353, 0.245107, -0.158871, 0.476942, 0.127605, 0.262292, -0.170261, 0.490285, 0.144469, 0.281215, -0.182017, 0.503783, 0.163282, 0.301058, -0.193729, 0.515505, 0.183873, 0.322752, -0.205512, 0.52682, 0.206466, 0.347547, -0.217214, 0.539473, 0.231194, 0.370969, -0.227966, 0.546625, 0.257288, 0.397533, -0.238555, 0.55472, 0.285789, 0.42398, -0.248278, 0.559468, 0.315746, 0.452928, -0.257422, 0.564095, 0.347724, 0.482121, -0.265306, 0.565426, 0.380922, 0.510438, -0.272043, 0.563205, 0.415639, 0.541188, -0.277614, 0.561087, 0.451702, 0.571667, -0.281927, 0.554922, 0.48845, 0.602432, -0.285015, 0.546838, 0.526442, 0.634126, -0.286512, 0.537415, 0.564896, 0.662816, -0.286388, 0.522906, 0.604037, 0.692411, -0.284734, 0.507003, 0.643795, 0.720946, -0.281297, 0.488398, 0.68298, 0.748293, -0.276262, 0.466353, 0.723466, 0.776931, -0.269978, 0.443573, 0.764565, 0.801065, -0.260305, 0.415279, 0.805838, 0.825843, -0.247426, 0.384773, 0.849985, 0.84807, -0.232437, 0.352555, 0.893174, 0.869122, -0.215806, 0.318642, 0.936564, 0.888963, -0.197307, 0.28381, 0.980253, 0.905547, -0.177203, 0.247888, 1.02463, 0.918554, -0.155542, 0.212904, 1.06714, 0.931395, -0.131948, 0.1787, 1.10451, 0.941749, -0.106723, 0.145902, 1.13694, 0.954551, -0.0804939, 0.111193, 1.1666, 0.970279, -0.0534239, 0.0744697, 1.19249, 0.986117, -0.0257452, 0.0368788, 1.21665, 0.999938, 0.00190634, -0.0010291, 1.23981, 0.118493, -0.00000647439, 0.32272, 0.0000023772, 0.118765, -0.000163023, 0.323456, 0.0000598573, 0.118772, -0.00065212, 0.323477, 0.000239447, 0.118843, -0.00146741, 0.323657, 0.000538881, 0.118804, -0.00260846, 0.323553, 0.00095826, 0.118826, -0.00407576, 0.323595, 0.00149845, 0.118846, -0.00586826, 0.323617, 0.00216047, 0.118886, -0.00798578, 0.32367, 0.00294679, 0.118947, -0.0104273, 0.323753, 0.00386124, 0.119055, -0.0131909, 0.323922, 0.00490999, 0.119241, -0.0162444, 0.324251, 0.00610804, 0.11944, -0.0196339, 0.324544, 0.00745805, 0.119739, -0.0233378, 0.325026, 0.00897805, 0.12011, -0.0273179, 0.325586, 0.0106895, 0.120571, -0.0316143, 0.326231, 0.0126073, 0.12124, -0.0361939, 0.327264, 0.0147654, 0.122162, -0.0410511, 0.328733, 0.0172001, 0.123378, -0.0462233, 0.330659, 0.0199375, 0.125183, -0.0517109, 0.333754, 0.0230498, 0.127832, -0.0575652, 0.338507, 0.026597, 0.130909, -0.0637441, 0.343666, 0.0306345, 0.135221, -0.0704302, 0.351063, 0.035273, 0.14082, -0.0776364, 0.360604, 0.0406137, 0.146781, -0.0852293, 0.369638, 0.0466788, 0.155121, -0.0935351, 0.3827, 0.0537628, 0.16398, -0.102234, 0.39522, 0.0617985, 0.173926, -0.111465, 0.40793, 0.07097, 0.185137, -0.121296, 0.42105, 0.0813426, 0.19826, -0.13169, 0.435735, 0.0931596, 0.212938, -0.142614, 0.450932, 0.106547, 0.229046, -0.153884, 0.465726, 0.121575, 0.246246, -0.165382, 0.479461, 0.138286, 0.264637, -0.176806, 0.492106, 0.15666, 0.284959, -0.188793, 0.504774, 0.17728, 0.308157, -0.200763, 0.518805, 0.19988, 0.330951, -0.21239, 0.528231, 0.224293, 0.3549, -0.223521, 0.536376, 0.250541, 0.381502, -0.234169, 0.544846, 0.278902, 0.409529, -0.244077, 0.551717, 0.309227, 0.437523, -0.253363, 0.55517, 0.341426, 0.467624, -0.261659, 0.557772, 0.37518, 0.497268, -0.268498, 0.556442, 0.41007, 0.528294, -0.274018, 0.553915, 0.446445, 0.559053, -0.278169, 0.549153, 0.483779, 0.589329, -0.281229, 0.539878, 0.522249, 0.622503, -0.282902, 0.53162, 0.561754, 0.652382, -0.282815, 0.518119, 0.601544, 0.681847, -0.281247, 0.502187, 0.641574, 0.712285, -0.277986, 0.484824, 0.682633, 0.740094, -0.273017, 0.463483, 0.723426, 0.768478, -0.266692, 0.441299, 0.763747, 0.794556, -0.258358, 0.415238, 0.805565, 0.819408, -0.248807, 0.386912, 0.847254, 0.843411, -0.236214, 0.356165, 0.891091, 0.862397, -0.219794, 0.320562, 0.936174, 0.883113, -0.201768, 0.285322, 0.982562, 0.90023, -0.181672, 0.249713, 1.02862, 0.915192, -0.159279, 0.214546, 1.07163, 0.928458, -0.134725, 0.180285, 1.10995, 0.94069, -0.10913, 0.147119, 1.14354, 0.953409, -0.0821315, 0.112492, 1.17372, 0.969537, -0.0542677, 0.0752014, 1.20043, 0.985612, -0.0259096, 0.0370361, 1.22528, 0.999835, 0.00298198, -0.00151801, 1.24959, 0.10097, -0.00000602574, 0.300277, 0.00000202619, 0.101577, -0.000152164, 0.302077, 0.0000511662, 0.101572, -0.000608889, 0.302066, 0.000204751, 0.101566, -0.00136997, 0.302047, 0.000460753, 0.101592, -0.00243557, 0.302114, 0.000819497, 0.101608, -0.0038053, 0.30214, 0.00128154, 0.101627, -0.00547906, 0.30216, 0.0018483, 0.101669, -0.00745647, 0.302224, 0.00252223, 0.101732, -0.00973615, 0.302318, 0.00330716, 0.101844, -0.0123097, 0.302513, 0.00421061, 0.102025, -0.0151681, 0.30285, 0.00524481, 0.102224, -0.0183334, 0.303166, 0.0064154, 0.102515, -0.0217819, 0.303654, 0.00774063, 0.102886, -0.0255067, 0.304243, 0.0092398, 0.103395, -0.029514, 0.305089, 0.0109339, 0.104109, -0.0337912, 0.306301, 0.0128561, 0.105074, -0.0383565, 0.30798, 0.0150338, 0.10654, -0.0432132, 0.310726, 0.0175228, 0.108478, -0.0484244, 0.314351, 0.0203648, 0.111015, -0.0539339, 0.319032, 0.0236325, 0.114682, -0.0598885, 0.32605, 0.0274188, 0.11911, -0.0663375, 0.334109, 0.0317905, 0.124736, -0.0733011, 0.344013, 0.0368502, 0.131479, -0.0807744, 0.355358, 0.0427104, 0.139283, -0.0888204, 0.367614, 0.0494788, 0.148054, -0.0973394, 0.380072, 0.0572367, 0.159037, -0.10665, 0.395678, 0.0662704, 0.169794, -0.116221, 0.40795, 0.0763192, 0.18314, -0.126632, 0.423546, 0.087956, 0.197515, -0.137383, 0.438213, 0.101042, 0.213514, -0.148641, 0.453248, 0.115827, 0.23065, -0.160117, 0.46688, 0.132283, 0.249148, -0.171807, 0.479962, 0.150644, 0.270219, -0.183695, 0.494618, 0.171073, 0.292338, -0.195574, 0.506937, 0.193378, 0.314999, -0.207205, 0.516463, 0.217585, 0.340991, -0.218955, 0.528123, 0.24428, 0.367982, -0.229917, 0.537025, 0.272784, 0.39432, -0.239737, 0.541627, 0.302742, 0.423364, -0.249048, 0.546466, 0.335112, 0.453751, -0.257329, 0.549466, 0.369032, 0.48416, -0.264623, 0.549503, 0.404577, 0.515262, -0.270411, 0.547008, 0.441337, 0.547036, -0.274581, 0.542249, 0.479162, 0.576614, -0.277266, 0.533015, 0.517904, 0.611143, -0.279144, 0.525512, 0.558508, 0.640989, -0.279001, 0.51154, 0.598995, 0.671182, -0.277324, 0.495641, 0.639935, 0.700848, -0.273908, 0.477526, 0.681017, 0.729862, -0.269063, 0.457955, 0.722764, 0.758273, -0.262282, 0.434846, 0.764349, 0.784121, -0.254281, 0.409203, 0.806206, 0.809798, -0.24505, 0.382694, 0.848617, 0.834953, -0.233861, 0.354034, 0.892445, 0.856817, -0.221308, 0.321764, 0.936263, 0.877609, -0.205996, 0.288118, 0.982401, 0.897489, -0.186702, 0.253277, 1.02975, 0.913792, -0.164618, 0.217963, 1.07488, 0.92785, -0.140023, 0.183221, 1.11487, 0.940378, -0.11328, 0.149385, 1.14947, 0.95273, -0.0853958, 0.114152, 1.1807, 0.969059, -0.0568698, 0.0769845, 1.20912, 0.985574, -0.0276502, 0.0381186, 1.23498, 0.999943, 0.00239052, -0.00126861, 1.25987, 0.0852715, -0.00000560067, 0.279021, 0.00000171162, 0.0854143, -0.000140871, 0.279483, 0.0000430516, 0.0854191, -0.000563385, 0.2795, 0.000172184, 0.0854188, -0.00126753, 0.279493, 0.000387464, 0.0854229, -0.00225337, 0.279501, 0.00068918, 0.0854443, -0.00352086, 0.279549, 0.00107803, 0.0854697, -0.00506962, 0.279591, 0.00155536, 0.0855093, -0.00689873, 0.279652, 0.00212354, 0.0855724, -0.00900821, 0.279752, 0.00278703, 0.0856991, -0.0113799, 0.280011, 0.0035551, 0.085855, -0.0140314, 0.280297, 0.00443449, 0.0860682, -0.016963, 0.280682, 0.00543636, 0.086344, -0.0201438, 0.281159, 0.0065788, 0.0867426, -0.0235999, 0.281886, 0.00787977, 0.087239, -0.0273069, 0.282745, 0.0093606, 0.0879815, -0.031269, 0.284139, 0.011056, 0.0891258, -0.035531, 0.28647, 0.0130065, 0.0906909, -0.0400947, 0.289708, 0.0152495, 0.0927624, -0.0449638, 0.293904, 0.0178454, 0.0958376, -0.0502427, 0.300471, 0.0208915, 0.0995827, -0.0559514, 0.30806, 0.0244247, 0.104526, -0.0622152, 0.317874, 0.0285721, 0.110532, -0.0690046, 0.329332, 0.0334227, 0.117385, -0.0763068, 0.341217, 0.0390466, 0.12522, -0.084184, 0.353968, 0.0455786, 0.134037, -0.0925248, 0.366797, 0.0530773, 0.144014, -0.101487, 0.380209, 0.0617424, 0.156013, -0.111273, 0.395956, 0.071777, 0.168872, -0.121431, 0.41053, 0.0830905, 0.183089, -0.132105, 0.425073, 0.0959341, 0.198763, -0.143286, 0.439833, 0.110448, 0.216159, -0.154841, 0.454507, 0.126769, 0.234859, -0.166588, 0.468368, 0.14495, 0.255879, -0.178626, 0.482846, 0.165233, 0.27677, -0.190218, 0.493489, 0.187217, 0.301184, -0.202227, 0.506549, 0.211659, 0.325852, -0.213764, 0.5158, 0.237922, 0.352824, -0.22487, 0.525442, 0.26632, 0.380882, -0.235246, 0.532487, 0.296691, 0.410137, -0.244847, 0.537703, 0.329179, 0.439787, -0.253122, 0.540361, 0.363135, 0.472291, -0.260517, 0.542734, 0.399222, 0.501856, -0.266519, 0.538826, 0.436352, 0.534816, -0.270905, 0.535152, 0.474505, 0.565069, -0.273826, 0.525979, 0.513988, 0.597154, -0.275333, 0.516394, 0.554852, 0.630473, -0.275314, 0.506206, 0.596592, 0.660574, -0.273323, 0.489769, 0.638117, 0.692015, -0.270008, 0.472578, 0.680457, 0.720647, -0.265001, 0.452134, 0.723008, 0.750528, -0.258311, 0.430344, 0.765954, 0.777568, -0.250046, 0.405624, 0.809012, 0.80387, -0.240114, 0.378339, 0.852425, 0.828439, -0.228737, 0.349877, 0.895346, 0.851472, -0.216632, 0.318968, 0.940695, 0.873906, -0.202782, 0.287489, 0.987235, 0.89467, -0.187059, 0.254394, 1.03348, 0.912281, -0.168818, 0.221294, 1.07812, 0.927358, -0.146494, 0.18675, 1.11928, 0.940385, -0.120009, 0.152322, 1.15609, 0.952672, -0.0917183, 0.117514, 1.18875, 0.968496, -0.0620321, 0.0797405, 1.21821, 0.985236, -0.0314945, 0.0402383, 1.24523, 0.99998, -0.000575153, 0.000110644, 1.27133, 0.0702429, -0.00000512222, 0.255273, 0.00000140947, 0.0702981, -0.000128826, 0.255469, 0.0000354488, 0.0703691, -0.000515562, 0.255727, 0.000141874, 0.0703805, -0.00116, 0.255754, 0.00031929, 0.0703961, -0.00206224, 0.255813, 0.000567999, 0.0704102, -0.00322223, 0.255839, 0.00088871, 0.0704298, -0.00463928, 0.255863, 0.00128272, 0.0704759, -0.00631375, 0.255953, 0.00175283, 0.0705434, -0.00824317, 0.256079, 0.00230342, 0.0706693, -0.010412, 0.25636, 0.0029443, 0.0708189, -0.0128439, 0.256647, 0.00368031, 0.0710364, -0.0155177, 0.257084, 0.00452614, 0.0713223, -0.0184374, 0.257637, 0.00549706, 0.0717182, -0.0216002, 0.258416, 0.00661246, 0.072321, -0.0249966, 0.259699, 0.00790147, 0.0731446, -0.0286566, 0.261475, 0.0093884, 0.0743352, -0.0325888, 0.264132, 0.0111186, 0.0760676, -0.036843, 0.26815, 0.013145, 0.078454, -0.0414292, 0.273636, 0.0155251, 0.0818618, -0.0464634, 0.281653, 0.0183525, 0.0857382, -0.0519478, 0.289992, 0.0216642, 0.0908131, -0.0579836, 0.30066, 0.0255956, 0.0967512, -0.0645124, 0.312204, 0.0301954, 0.103717, -0.0716505, 0.325001, 0.0356017, 0.111596, -0.0793232, 0.338129, 0.041896, 0.120933, -0.087645, 0.352853, 0.0492447, 0.130787, -0.096492, 0.366192, 0.0576749, 0.142311, -0.105973, 0.380864, 0.0673969, 0.155344, -0.116182, 0.396575, 0.0785899, 0.169535, -0.126815, 0.411443, 0.0912377, 0.185173, -0.138015, 0.426256, 0.105607, 0.201755, -0.149325, 0.439607, 0.121551, 0.221334, -0.161207, 0.455467, 0.139608, 0.241461, -0.173162, 0.469096, 0.159591, 0.26294, -0.18504, 0.481014, 0.18156, 0.286776, -0.196881, 0.493291, 0.205781, 0.311596, -0.208311, 0.503556, 0.231819, 0.338667, -0.219671, 0.513268, 0.260274, 0.366021, -0.230451, 0.519414, 0.290862, 0.395875, -0.240131, 0.526766, 0.323196, 0.425564, -0.248566, 0.52905, 0.357071, 0.457094, -0.256195, 0.530796, 0.393262, 0.488286, -0.262331, 0.528703, 0.430797, 0.522291, -0.267141, 0.52727, 0.470231, 0.554172, -0.270411, 0.519848, 0.510477, 0.586427, -0.271986, 0.510307, 0.551594, 0.619638, -0.27192, 0.499158, 0.593849, 0.650656, -0.269817, 0.483852, 0.636314, 0.68284, -0.266267, 0.467515, 0.679679, 0.714356, -0.26113, 0.44931, 0.723884, 0.742717, -0.254067, 0.425789, 0.767245, 0.770894, -0.245652, 0.401144, 0.811819, 0.797358, -0.235554, 0.374224, 0.856315, 0.823377, -0.223896, 0.346167, 0.901077, 0.847456, -0.210865, 0.316056, 0.946502, 0.870697, -0.196574, 0.284503, 0.993711, 0.891068, -0.180814, 0.251628, 1.04134, 0.909267, -0.163314, 0.219065, 1.08609, 0.925653, -0.143304, 0.186446, 1.12702, 0.940017, -0.121322, 0.153416, 1.16371, 0.952398, -0.0973872, 0.120334, 1.19712, 0.967568, -0.0698785, 0.08352, 1.22791, 0.984772, -0.0390031, 0.0439209, 1.25672, 1.00026, -0.0070087, 0.00315668, 1.28428, 0.0556653, -0.00000459654, 0.227325, 0.00000112556, 0.0565238, -0.000116382, 0.230826, 0.0000284985, 0.0565717, -0.000465666, 0.231026, 0.000114036, 0.0565859, -0.00104773, 0.231079, 0.000256656, 0.0565761, -0.00186255, 0.231025, 0.00045663, 0.0565913, -0.00291002, 0.231058, 0.000714664, 0.0566108, -0.00418998, 0.231085, 0.00103224, 0.0566532, -0.00570206, 0.231169, 0.00141202, 0.0567473, -0.00743666, 0.231417, 0.00186018, 0.0568567, -0.00940298, 0.231661, 0.00238264, 0.0569859, -0.0115991, 0.231895, 0.00298699, 0.0572221, -0.0140096, 0.232456, 0.00368957, 0.057519, -0.0166508, 0.233096, 0.00450303, 0.0579534, -0.01951, 0.234094, 0.00544945, 0.0585922, -0.0225991, 0.235629, 0.00655564, 0.0595647, -0.0259416, 0.238106, 0.00785724, 0.0609109, -0.0295661, 0.241557, 0.00939127, 0.0628751, -0.0335126, 0.246652, 0.0112198, 0.0656908, -0.0378604, 0.254091, 0.0134168, 0.0691347, -0.0426543, 0.262666, 0.0160374, 0.0732165, -0.0478967, 0.272029, 0.0191514, 0.0782863, -0.0536716, 0.283007, 0.0228597, 0.0843973, -0.0600683, 0.295732, 0.0272829, 0.0913598, -0.0670095, 0.308779, 0.032484, 0.0994407, -0.0745516, 0.322886, 0.0385886, 0.108189, -0.082712, 0.336408, 0.0457133, 0.118574, -0.0914927, 0.351692, 0.0539832, 0.129989, -0.100854, 0.366502, 0.0635162, 0.142722, -0.110837, 0.381675, 0.0744386, 0.156654, -0.121353, 0.3963, 0.0868483, 0.172151, -0.132414, 0.411477, 0.100963, 0.188712, -0.143809, 0.42508, 0.116795, 0.208093, -0.155765, 0.441328, 0.134715, 0.227936, -0.167608, 0.454328, 0.154396, 0.249495, -0.179579, 0.467235, 0.176179, 0.27362, -0.191488, 0.480248, 0.200193, 0.296371, -0.202618, 0.487886, 0.225775, 0.324234, -0.214133, 0.499632, 0.25441, 0.353049, -0.225212, 0.509532, 0.285077, 0.381785, -0.234875, 0.514265, 0.317047, 0.414038, -0.244205, 0.521282, 0.351874, 0.445251, -0.252145, 0.522931, 0.388279, 0.476819, -0.258433, 0.520947, 0.425825, 0.509209, -0.263411, 0.517669, 0.465104, 0.542759, -0.266732, 0.512841, 0.505741, 0.574822, -0.268263, 0.503317, 0.547611, 0.609324, -0.268489, 0.493035, 0.590953, 0.641772, -0.266941, 0.478816, 0.63488, 0.674049, -0.263297, 0.462863, 0.679072, 0.705071, -0.257618, 0.442931, 0.723487, 0.734709, -0.250625, 0.421299, 0.768708, 0.763704, -0.24179, 0.397085, 0.814375, 0.791818, -0.231115, 0.370577, 0.859907, 0.817439, -0.21922, 0.34232, 0.906715, 0.843202, -0.205658, 0.312627, 0.953943, 0.866639, -0.190563, 0.280933, 1.00185, 0.888129, -0.173978, 0.248393, 1.05105, 0.907239, -0.155485, 0.216007, 1.09704, 0.923893, -0.134782, 0.183233, 1.13857, 0.938882, -0.11249, 0.150376, 1.17539, 0.952464, -0.0890706, 0.117177, 1.20924, 0.968529, -0.0646523, 0.0813095, 1.24055, 0.984763, -0.038606, 0.0439378, 1.27018, 1.00053, -0.01238, 0.00598668, 1.29873, 0.0437928, -0.00000409594, 0.204012, 0.000000879224, 0.0440166, -0.000103395, 0.205049, 0.0000221946, 0.0440529, -0.000413633, 0.205225, 0.0000887981, 0.0440493, -0.000930594, 0.2052, 0.000199858, 0.0439884, -0.00165352, 0.204901, 0.000355495, 0.0440716, -0.0025849, 0.205255, 0.000556983, 0.0440968, -0.00372222, 0.205311, 0.000805326, 0.0441359, -0.00506478, 0.205391, 0.00110333, 0.0442231, -0.00660384, 0.205638, 0.00145768, 0.0443254, -0.00835246, 0.205877, 0.00187275, 0.0444832, -0.0102992, 0.20627, 0.00235938, 0.0447001, -0.0124449, 0.206796, 0.0029299, 0.0450168, -0.0147935, 0.207593, 0.0036005, 0.0454816, -0.017336, 0.208819, 0.00439246, 0.0462446, -0.0201156, 0.211036, 0.00533864, 0.0473694, -0.0231568, 0.214388, 0.00646984, 0.0490191, -0.0264941, 0.219357, 0.00783856, 0.0512776, -0.030184, 0.226061, 0.00950182, 0.0541279, -0.0342661, 0.234094, 0.0115156, 0.0578989, -0.0388539, 0.244297, 0.0139687, 0.0620835, -0.0438735, 0.254457, 0.0169015, 0.0673497, -0.04951, 0.266706, 0.0204554, 0.0731759, -0.0556263, 0.278753, 0.0246606, 0.0803937, -0.0624585, 0.29309, 0.0297126, 0.0879287, -0.0697556, 0.305856, 0.0355868, 0.0970669, -0.0778795, 0.321059, 0.0425768, 0.106508, -0.0863541, 0.333873, 0.05056, 0.11776, -0.0955935, 0.349008, 0.0598972, 0.130081, -0.105438, 0.363776, 0.0706314, 0.144454, -0.115899, 0.380112, 0.0828822, 0.1596, -0.126827, 0.394843, 0.0967611, 0.176097, -0.138161, 0.409033, 0.112381, 0.194726, -0.149904, 0.424257, 0.129952, 0.213944, -0.161675, 0.436945, 0.149333, 0.235516, -0.173659, 0.450176, 0.170892, 0.260564, -0.185963, 0.466305, 0.194984, 0.285183, -0.197582, 0.477328, 0.220805, 0.311095, -0.208697, 0.486566, 0.248694, 0.338924, -0.219519, 0.494811, 0.279015, 0.369757, -0.229766, 0.504065, 0.311725, 0.3996, -0.238879, 0.507909, 0.345844, 0.430484, -0.246802, 0.509805, 0.381749, 0.46413, -0.253924, 0.511436, 0.420251, 0.497077, -0.259319, 0.508787, 0.459957, 0.530434, -0.263297, 0.50394, 0.501356, 0.565725, -0.265619, 0.49804, 0.544252, 0.599254, -0.265842, 0.487346, 0.587856, 0.631251, -0.263978, 0.472975, 0.631969, 0.663972, -0.26043, 0.457135, 0.677471, 0.697724, -0.255358, 0.439844, 0.723744, 0.727725, -0.248308, 0.417872, 0.770653, 0.756417, -0.239181, 0.39273, 0.817357, 0.785419, -0.22814, 0.367839, 0.864221, 0.81266, -0.215681, 0.339449, 0.912701, 0.839391, -0.201623, 0.309279, 0.962419, 0.86366, -0.185624, 0.278029, 1.0122, 0.885028, -0.16797, 0.245294, 1.06186, 0.904639, -0.148336, 0.212689, 1.10934, 0.922048, -0.12637, 0.179616, 1.15063, 0.936952, -0.102928, 0.146749, 1.18885, 0.951895, -0.0785268, 0.112733, 1.22352, 0.967198, -0.0530153, 0.0760056, 1.25681, 0.984405, -0.02649, 0.0383183, 1.28762, 1.00021, 0.00070019, -0.00020039, 1.31656, 0.0325964, -0.00000355447, 0.176706, 0.000000655682, 0.0329333, -0.0000899174, 0.178527, 0.0000165869, 0.0329181, -0.000359637, 0.178453, 0.0000663498, 0.0329085, -0.000808991, 0.178383, 0.000149332, 0.0329181, -0.00143826, 0.178394, 0.000265873, 0.0329425, -0.00224678, 0.178517, 0.000416597, 0.0329511, -0.00323575, 0.17849, 0.000603299, 0.033011, -0.00439875, 0.178695, 0.000829422, 0.0330733, -0.00574059, 0.178843, 0.00109908, 0.0331857, -0.00725896, 0.179176, 0.00141933, 0.0333445, -0.00895289, 0.179618, 0.0017999, 0.0335674, -0.0108219, 0.180238, 0.00225316, 0.033939, -0.0128687, 0.181417, 0.00279765, 0.0345239, -0.015114, 0.183395, 0.0034564, 0.0354458, -0.017596, 0.186616, 0.00425864, 0.0368313, -0.0203524, 0.191547, 0.00524936, 0.0386115, -0.0234105, 0.197508, 0.00647033, 0.0410303, -0.0268509, 0.205395, 0.00798121, 0.0442245, -0.0307481, 0.215365, 0.0098557, 0.0478659, -0.0350863, 0.225595, 0.0121417, 0.0522416, -0.0399506, 0.236946, 0.0149385, 0.0574513, -0.045357, 0.249442, 0.0183189, 0.0631208, -0.0512863, 0.261222, 0.0223644, 0.0701124, -0.0579273, 0.275418, 0.0272418, 0.0777331, -0.0650652, 0.288989, 0.0329458, 0.0862709, -0.0728813, 0.302546, 0.0396819, 0.096103, -0.081363, 0.317164, 0.04757, 0.106976, -0.0904463, 0.331733, 0.0567012, 0.119175, -0.100105, 0.34661, 0.067202, 0.132919, -0.110375, 0.362249, 0.0792588, 0.147727, -0.121115, 0.376978, 0.0928672, 0.163618, -0.132299, 0.390681, 0.108228, 0.182234, -0.143887, 0.406571, 0.125502, 0.201809, -0.155827, 0.42042, 0.144836, 0.225041, -0.168357, 0.438411, 0.166706, 0.247621, -0.18004, 0.450368, 0.189909, 0.27097, -0.191536, 0.460083, 0.215251, 0.296658, -0.203024, 0.469765, 0.243164, 0.325892, -0.214056, 0.481837, 0.273388, 0.35406, -0.224104, 0.487474, 0.305344, 0.384372, -0.233489, 0.492773, 0.339741, 0.41749, -0.241874, 0.498451, 0.376287, 0.45013, -0.248834, 0.499632, 0.414195, 0.481285, -0.254658, 0.495233, 0.454077, 0.519183, -0.259367, 0.496401, 0.496352, 0.551544, -0.261818, 0.487686, 0.538798, 0.587349, -0.262964, 0.479453, 0.583626, 0.621679, -0.262128, 0.467709, 0.629451, 0.654991, -0.258998, 0.452123, 0.67566, 0.686873, -0.254119, 0.433495, 0.723248, 0.719801, -0.246946, 0.413657, 0.771156, 0.750355, -0.237709, 0.390366, 0.81989, 0.780033, -0.226549, 0.364947, 0.868601, 0.809254, -0.214186, 0.337256, 0.920034, 0.836576, -0.199639, 0.307395, 0.971706, 0.861774, -0.183169, 0.275431, 1.02479, 0.885707, -0.165111, 0.243431, 1.07837, 0.904742, -0.144363, 0.210921, 1.12783, 0.915604, -0.121305, 0.17647, 1.17254, 0.930959, -0.0962119, 0.143106, 1.21012, 0.948404, -0.069969, 0.108112, 1.24474, 0.967012, -0.0427586, 0.0708478, 1.27718, 0.984183, -0.0147043, 0.032335, 1.3083, 0.999577, 0.0142165, -0.00726867, 1.3382, 0.0229227, -0.00000299799, 0.148623, 0.000000462391, 0.0232194, -0.0000758796, 0.15054, 0.0000117033, 0.0232315, -0.000303636, 0.15063, 0.0000468397, 0.0232354, -0.000683189, 0.150624, 0.000105472, 0.0232092, -0.0012136, 0.150445, 0.000187744, 0.0232523, -0.00189765, 0.150679, 0.000294847, 0.0232828, -0.00273247, 0.150789, 0.000428013, 0.0233371, -0.00371287, 0.150995, 0.000591134, 0.0234015, -0.00484794, 0.15118, 0.000787642, 0.023514, -0.00612877, 0.151562, 0.00102547, 0.023679, -0.00756125, 0.152116, 0.00131351, 0.0239559, -0.00914651, 0.153162, 0.00166594, 0.0244334, -0.010904, 0.155133, 0.00210182, 0.025139, -0.0128615, 0.158035, 0.00264406, 0.0262598, -0.0150628, 0.162751, 0.00332923, 0.0277875, -0.0175532, 0.168944, 0.00419773, 0.0298472, -0.0203981, 0.176835, 0.00530034, 0.0325444, -0.023655, 0.186686, 0.00669777, 0.0355581, -0.0272982, 0.196248, 0.00842661, 0.0392841, -0.0314457, 0.207352, 0.0105854, 0.0436815, -0.0361157, 0.219279, 0.0132458, 0.0485272, -0.0412932, 0.230728, 0.0164736, 0.0541574, -0.0470337, 0.242994, 0.0203715, 0.0609479, -0.0535002, 0.257042, 0.0250953, 0.0685228, -0.0605409, 0.27102, 0.0306856, 0.0768042, -0.0680553, 0.28406, 0.037193, 0.0864844, -0.0765011, 0.299186, 0.0449795, 0.0969415, -0.0852674, 0.3132, 0.0538316, 0.108478, -0.0947333, 0.327138, 0.0641149, 0.121705, -0.10481, 0.342345, 0.0759185, 0.136743, -0.115474, 0.358472, 0.0894116, 0.152986, -0.126536, 0.374067, 0.104562, 0.170397, -0.138061, 0.388267, 0.121632, 0.191392, -0.150203, 0.406467, 0.140996, 0.211566, -0.161751, 0.418641, 0.161696, 0.233567, -0.173407, 0.430418, 0.184557, 0.257769, -0.185397, 0.44277, 0.210092, 0.28531, -0.197048, 0.457191, 0.237827, 0.311726, -0.20784, 0.464712, 0.267253, 0.340537, -0.218345, 0.472539, 0.299332, 0.372921, -0.228306, 0.482331, 0.333988, 0.402924, -0.236665, 0.484378, 0.369722, 0.434475, -0.244097, 0.484717, 0.407836, 0.469736, -0.250547, 0.487093, 0.448465, 0.505045, -0.25511, 0.485575, 0.490263, 0.540262, -0.258444, 0.481225, 0.534495, 0.576347, -0.259903, 0.473481, 0.579451, 0.608656, -0.259572, 0.4603, 0.625604, 0.646679, -0.257908, 0.450341, 0.674511, 0.679902, -0.253663, 0.431561, 0.723269, 0.714159, -0.247419, 0.412684, 0.773263, 0.745345, -0.239122, 0.389388, 0.824182, 0.778248, -0.228837, 0.365361, 0.876634, 0.807208, -0.216197, 0.337667, 0.92945, 0.835019, -0.201772, 0.307197, 0.985261, 0.860261, -0.185291, 0.274205, 1.04299, 0.877601, -0.165809, 0.240178, 1.09816, 0.898211, -0.143897, 0.207571, 1.14694, 0.915789, -0.119513, 0.174904, 1.19008, 0.931831, -0.0932919, 0.141423, 1.2297, 0.949244, -0.0656528, 0.105603, 1.26553, 0.967527, -0.0370262, 0.0679551, 1.29986, 0.984139, -0.00730117, 0.0283133, 1.33252, 0.999713, 0.0234648, -0.0121785, 1.36397, 0.0152135, -0.00000245447, 0.122795, 0.000000304092, 0.0151652, -0.0000615778, 0.122399, 0.0000076292, 0.0151181, -0.000245948, 0.122023, 0.0000304802, 0.0151203, -0.000553394, 0.12203, 0.0000686634, 0.015125, -0.000983841, 0.122037, 0.000122463, 0.0151427, -0.00153774, 0.12214, 0.000192706, 0.0151708, -0.0022103, 0.122237, 0.000281219, 0.0152115, -0.00300741, 0.12238, 0.000390804, 0.0152877, -0.00392494, 0.1227, 0.000526317, 0.015412, -0.00496597, 0.123244, 0.00069443, 0.0156201, -0.00613314, 0.124228, 0.00090547, 0.0159658, -0.00744113, 0.125945, 0.0011732, 0.0165674, -0.00892546, 0.129098, 0.00151888, 0.017487, -0.010627, 0.133865, 0.00197007, 0.018839, -0.0126043, 0.140682, 0.0025637, 0.020554, -0.0148814, 0.148534, 0.00333637, 0.0226727, -0.0175123, 0.157381, 0.00433738, 0.0251879, -0.0205266, 0.166685, 0.00561664, 0.0283635, -0.0240319, 0.177796, 0.00725563, 0.0318694, -0.0279432, 0.188251, 0.00928811, 0.0361044, -0.0324313, 0.200038, 0.011835, 0.0406656, -0.0373527, 0.210685, 0.0149146, 0.0463846, -0.0430132, 0.224182, 0.0187254, 0.0525696, -0.0491013, 0.23634, 0.0232283, 0.0598083, -0.0559175, 0.250013, 0.0286521, 0.0679437, -0.0633657, 0.263981, 0.0350634, 0.0771181, -0.0714602, 0.278072, 0.0425882, 0.0881273, -0.0803502, 0.29511, 0.0514487, 0.0996628, -0.0896903, 0.309976, 0.0615766, 0.112702, -0.099644, 0.325611, 0.0732139, 0.126488, -0.109829, 0.339321, 0.0862324, 0.142625, -0.120859, 0.35574, 0.101275, 0.15953, -0.131956, 0.369845, 0.117892, 0.176991, -0.143145, 0.38146, 0.136205, 0.199715, -0.155292, 0.40052, 0.157252, 0.220787, -0.167066, 0.412055, 0.179966, 0.243697, -0.178396, 0.423133, 0.204418, 0.272106, -0.190433, 0.439524, 0.232141, 0.297637, -0.201265, 0.447041, 0.261109, 0.325273, -0.211834, 0.454488, 0.292627, 0.357219, -0.221889, 0.465004, 0.326669, 0.387362, -0.230729, 0.468527, 0.362426, 0.423131, -0.23924, 0.475836, 0.401533, 0.45543, -0.246067, 0.475017, 0.441902, 0.493393, -0.251557, 0.478017, 0.484239, 0.526253, -0.255571, 0.4709, 0.528586, 0.560554, -0.257752, 0.463167, 0.574346, 0.599306, -0.258076, 0.456452, 0.621655, 0.634541, -0.256471, 0.443725, 0.670492, 0.668907, -0.253283, 0.428719, 0.721943, 0.705619, -0.247562, 0.411348, 0.772477, 0.739034, -0.240626, 0.388939, 0.8264, 0.771408, -0.231493, 0.36425, 0.881702, 0.803312, -0.220125, 0.337321, 0.9385, 0.828457, -0.206645, 0.305364, 0.997437, 0.854819, -0.190664, 0.273715, 1.05693, 0.878666, -0.171429, 0.242218, 1.11251, 0.898404, -0.149235, 0.209556, 1.16398, 0.917416, -0.12435, 0.176863, 1.21014, 0.933133, -0.0972703, 0.142775, 1.25178, 0.95066, -0.0683607, 0.106735, 1.29028, 0.968589, -0.0378724, 0.0681609, 1.32703, 0.984776, -0.00605712, 0.0273966, 1.36158, 0.99994, 0.0263276, -0.0138124, 1.3943, 0.00867437, -0.00000186005, 0.0928979, 0.000000173682, 0.00864003, -0.0000466389, 0.0925237, 0.00000435505, 0.00864593, -0.000186594, 0.0925806, 0.0000174322, 0.00864095, -0.000419639, 0.0924903, 0.0000392862, 0.00863851, -0.000746272, 0.0924589, 0.0000702598, 0.00868531, -0.00116456, 0.0929, 0.000111188, 0.00869667, -0.00167711, 0.0928529, 0.000163867, 0.00874332, -0.00228051, 0.0930914, 0.00023104, 0.00882709, -0.00297864, 0.0935679, 0.00031741, 0.00898874, -0.00377557, 0.0946165, 0.000430186, 0.00929346, -0.00469247, 0.0967406, 0.000580383, 0.00978271, -0.00575491, 0.100084, 0.000783529, 0.0105746, -0.00701514, 0.105447, 0.00106304, 0.0116949, -0.00851797, 0.112494, 0.00144685, 0.0130419, -0.0102757, 0.119876, 0.00196439, 0.0148375, -0.012381, 0.129034, 0.00266433, 0.0168725, -0.01482, 0.137812, 0.00358364, 0.0193689, -0.0176563, 0.147696, 0.00478132, 0.0222691, -0.0209211, 0.157795, 0.00631721, 0.0256891, -0.0246655, 0.168431, 0.00826346, 0.0294686, -0.0288597, 0.178587, 0.0106714, 0.0340412, -0.0336441, 0.190251, 0.0136629, 0.0393918, -0.039033, 0.202999, 0.0173272, 0.0453947, -0.0450087, 0.215655, 0.0217448, 0.0521936, -0.0515461, 0.228686, 0.0269941, 0.0600279, -0.058817, 0.242838, 0.033272, 0.0692398, -0.0667228, 0.258145, 0.0406457, 0.0793832, -0.0752401, 0.273565, 0.0492239, 0.0902297, -0.0841851, 0.287735, 0.0590105, 0.102014, -0.0936479, 0.301161, 0.0702021, 0.116054, -0.103967, 0.317438, 0.0832001, 0.13191, -0.114622, 0.334166, 0.0977951, 0.148239, -0.125452, 0.348192, 0.113985, 0.165809, -0.136453, 0.361094, 0.131928, 0.184616, -0.147648, 0.373534, 0.151811, 0.207491, -0.159607, 0.39101, 0.174476, 0.230106, -0.171119, 0.402504, 0.198798, 0.257036, -0.182906, 0.418032, 0.225796, 0.281172, -0.193605, 0.425468, 0.254027, 0.312034, -0.204771, 0.440379, 0.285713, 0.340402, -0.214988, 0.445406, 0.319196, 0.370231, -0.224711, 0.44968, 0.35537, 0.407105, -0.233516, 0.460747, 0.393838, 0.439037, -0.240801, 0.460624, 0.433747, 0.47781, -0.24762, 0.465957, 0.477234, 0.510655, -0.251823, 0.460054, 0.52044, 0.550584, -0.255552, 0.459172, 0.567853, 0.585872, -0.257036, 0.450311, 0.615943, 0.620466, -0.257535, 0.437763, 0.667693, 0.660496, -0.255248, 0.426639, 0.718988, 0.695578, -0.251141, 0.409185, 0.772503, 0.732176, -0.244718, 0.39015, 0.827023, 0.760782, -0.236782, 0.362594, 0.885651, 0.79422, -0.225923, 0.33711, 0.943756, 0.824521, -0.213855, 0.308272, 1.00874, 0.854964, -0.197723, 0.278529, 1.06764, 0.878065, -0.179209, 0.246208, 1.12836, 0.899834, -0.157569, 0.21329, 1.18318, 0.918815, -0.133206, 0.181038, 1.23161, 0.934934, -0.106545, 0.146993, 1.27644, 0.952115, -0.0780574, 0.111175, 1.31842, 0.96906, -0.0478279, 0.0728553, 1.35839, 0.985178, -0.0160014, 0.032579, 1.39697, 1.00039, 0.0173126, -0.0095256, 1.43312, 0.00384146, -0.00000124311, 0.0613583, 0.0000000778271, 0.00390023, -0.0000314043, 0.0622919, 0.00000196626, 0.00389971, -0.000125622, 0.0622632, 0.00000787379, 0.00389491, -0.000282352, 0.0620659, 0.00001778, 0.00391618, -0.000502512, 0.0624687, 0.0000320918, 0.00392662, -0.000784458, 0.0625113, 0.0000515573, 0.00396053, -0.00112907, 0.0628175, 0.0000778668, 0.00401911, -0.00153821, 0.0633286, 0.000113811, 0.00414994, -0.0020208, 0.0646443, 0.00016445, 0.00441223, -0.00260007, 0.0673886, 0.000237734, 0.00484427, -0.0033097, 0.0716528, 0.000345929, 0.00549109, -0.00418966, 0.0774998, 0.000505987, 0.00636293, -0.00527331, 0.0844758, 0.000739208, 0.00746566, -0.00660428, 0.0921325, 0.00107347, 0.00876625, -0.00818826, 0.0997067, 0.00153691, 0.0103125, -0.0100811, 0.107433, 0.00217153, 0.0123309, -0.0123643, 0.117088, 0.00303427, 0.0146274, -0.0150007, 0.126438, 0.00416018, 0.0172295, -0.0180531, 0.135672, 0.00561513, 0.0204248, -0.0215962, 0.146244, 0.007478, 0.0241597, -0.0256234, 0.157481, 0.00981046, 0.0284693, -0.0302209, 0.169125, 0.0127148, 0.033445, -0.0353333, 0.181659, 0.0162453, 0.0391251, -0.0410845, 0.1944, 0.0205417, 0.0454721, -0.0473451, 0.207082, 0.0256333, 0.0530983, -0.0542858, 0.221656, 0.0317036, 0.0615356, -0.0618384, 0.236036, 0.0388319, 0.0703363, -0.0697631, 0.248398, 0.046974, 0.0810391, -0.0784757, 0.263611, 0.0565246, 0.0920144, -0.0873488, 0.275857, 0.0671724, 0.105584, -0.0973652, 0.292555, 0.0798105, 0.119506, -0.107271, 0.306333, 0.0935945, 0.134434, -0.117608, 0.318888, 0.109106, 0.153399, -0.128938, 0.337552, 0.127074, 0.171258, -0.139944, 0.349955, 0.14643, 0.191059, -0.151288, 0.361545, 0.168, 0.215069, -0.163018, 0.378421, 0.192082, 0.237838, -0.174226, 0.38879, 0.217838, 0.266965, -0.186063, 0.405857, 0.246931, 0.292827, -0.196909, 0.414146, 0.277505, 0.324352, -0.207473, 0.426955, 0.310711, 0.354427, -0.217713, 0.433429, 0.346794, 0.389854, -0.227183, 0.443966, 0.385237, 0.420749, -0.235131, 0.44471, 0.424955, 0.459597, -0.242786, 0.451729, 0.468446, 0.495316, -0.248767, 0.45072, 0.513422, 0.534903, -0.253351, 0.450924, 0.560618, 0.572369, -0.256277, 0.445266, 0.609677, 0.612383, -0.2576, 0.438798, 0.660995, 0.644037, -0.256931, 0.421693, 0.713807, 0.686749, -0.254036, 0.4109, 0.767616, 0.719814, -0.249785, 0.390151, 0.82533, 0.754719, -0.244283, 0.367847, 0.888311, 0.792022, -0.235076, 0.345013, 0.948177, 0.822404, -0.225061, 0.316193, 1.01661, 0.853084, -0.211113, 0.287013, 1.08075, 0.879871, -0.19449, 0.255424, 1.14501, 0.901655, -0.174023, 0.222879, 1.20203, 0.919957, -0.1509, 0.18989, 1.25698, 0.938412, -0.124923, 0.15606, 1.30588, 0.953471, -0.0968139, 0.120512, 1.3529, 0.970451, -0.066734, 0.0828515, 1.3986, 0.985522, -0.034734, 0.0424458, 1.44148, 1.00099, -0.00102222, 0.000678929, 1.48398, 0.000965494, -0.000000627338, 0.0306409, 0.0000000197672, 0.00099168, -0.0000158573, 0.0314638, 0.000000499803, 0.000991068, -0.0000634012, 0.031363, 0.00000200682, 0.000974567, -0.00014144, 0.03036, 0.00000457312, 0.000998079, -0.000252812, 0.031496, 0.00000860131, 0.00102243, -0.000396506, 0.0319955, 0.0000148288, 0.00107877, -0.000577593, 0.0331376, 0.0000249141, 0.00121622, -0.000816816, 0.0359396, 0.0000423011, 0.0014455, -0.00113761, 0.0399652, 0.0000724613, 0.00178791, -0.00156959, 0.0450556, 0.000123929, 0.00225668, -0.00214064, 0.0508025, 0.000208531, 0.00285627, -0.00287655, 0.0568443, 0.000341969, 0.0035991, -0.00380271, 0.0630892, 0.000544158, 0.00455524, -0.00496264, 0.0702204, 0.000842423, 0.00569143, -0.0063793, 0.0773426, 0.00126704, 0.00716928, -0.00813531, 0.0860839, 0.00186642, 0.00885307, -0.0101946, 0.0944079, 0.00267014, 0.0109316, -0.0126386, 0.103951, 0.00374033, 0.0133704, -0.0154876, 0.113786, 0.0051304, 0.0161525, -0.0187317, 0.123477, 0.00688858, 0.0194267, -0.0224652, 0.133986, 0.00910557, 0.0230967, -0.0265976, 0.143979, 0.0118074, 0.0273627, -0.0312848, 0.154645, 0.0151266, 0.0323898, -0.0365949, 0.166765, 0.0191791, 0.0379225, -0.0422914, 0.177932, 0.0239236, 0.0447501, -0.0487469, 0.19167, 0.0296568, 0.0519391, -0.0556398, 0.203224, 0.0362924, 0.0599464, -0.0631646, 0.215652, 0.0440585, 0.0702427, -0.0714308, 0.232089, 0.0531619, 0.0806902, -0.0800605, 0.245258, 0.0634564, 0.0923194, -0.0892815, 0.258609, 0.0752481, 0.106938, -0.09931, 0.276654, 0.0888914, 0.121238, -0.109575, 0.289847, 0.104055, 0.138817, -0.120461, 0.307566, 0.121266, 0.15595, -0.131209, 0.320117, 0.139944, 0.178418, -0.143049, 0.339677, 0.161591, 0.197875, -0.154074, 0.349886, 0.184303, 0.224368, -0.166307, 0.369352, 0.210669, 0.252213, -0.178051, 0.386242, 0.238895, 0.277321, -0.189335, 0.395294, 0.269182, 0.310332, -0.200683, 0.412148, 0.302508, 0.338809, -0.210856, 0.418266, 0.337264, 0.372678, -0.220655, 0.428723, 0.374881, 0.405632, -0.230053, 0.433887, 0.415656, 0.442293, -0.237993, 0.439911, 0.457982, 0.477256, -0.244897, 0.440175, 0.502831, 0.515592, -0.250657, 0.441079, 0.550277, 0.550969, -0.255459, 0.435219, 0.601102, 0.592883, -0.257696, 0.432882, 0.651785, 0.629092, -0.259894, 0.421054, 0.708961, 0.672033, -0.258592, 0.41177, 0.763806, 0.709147, -0.256525, 0.395267, 0.824249, 0.745367, -0.254677, 0.375013, 0.8951, 0.784715, -0.247892, 0.353906, 0.959317, 0.818107, -0.240162, 0.327801, 1.03153, 0.847895, -0.229741, 0.298821, 1.10601, 0.879603, -0.213084, 0.269115, 1.164, 0.902605, -0.195242, 0.236606, 1.22854, 0.922788, -0.174505, 0.203442, 1.29017, 0.944831, -0.150169, 0.169594, 1.34157, 0.959656, -0.124099, 0.135909, 1.3956, 0.972399, -0.0960626, 0.0990563, 1.45128, 0.986549, -0.0657097, 0.0602348, 1.50312, 1.00013, -0.0333558, 0.0186694, 1.55364, 0.00000619747, -0.0000001, 0.00778326, 0.0000000000796756, 0.0000000237499, -0.0000000999999, 0.0000282592, 0.000000000114596, 0.00000100292, -0.00000166369, 0.000250354, 0.00000000677492, 0.00000350752, -0.00000637769, 0.000357289, 0.0000000631655, 0.00000826445, -0.0000174689, 0.000516179, 0.00000031851, 0.0000242481, -0.0000450868, 0.0010223, 0.00000130577, 0.0000455631, -0.000089044, 0.00144302, 0.00000374587, 0.0000971222, -0.000178311, 0.00241912, 0.0000102584, 0.000171403, -0.000313976, 0.00354938, 0.0000236481, 0.000292747, -0.000520026, 0.00513765, 0.0000496014, 0.000789827, -0.00118187, 0.0238621, 0.000139056, 0.00114093, -0.00171827, 0.0286691, 0.000244093, 0.00176119, -0.00249667, 0.0368565, 0.000420623, 0.0022233, -0.00333742, 0.0400469, 0.00065673, 0.00343382, -0.00481976, 0.0535751, 0.00109323, 0.00427602, -0.00600755, 0.057099, 0.00155268, 0.00461435, -0.00737637, 0.0551084, 0.00215031, 0.00695698, -0.00971401, 0.0715767, 0.00316529, 0.00867619, -0.0120943, 0.0793314, 0.00436995, 0.0106694, -0.0148202, 0.0869391, 0.0058959, 0.0140351, -0.0183501, 0.101572, 0.00798757, 0.0168939, -0.022006, 0.11018, 0.0104233, 0.020197, -0.0261568, 0.119041, 0.0134167, 0.0254702, -0.0312778, 0.135404, 0.0173009, 0.0298384, -0.0362469, 0.1437, 0.0215428, 0.035159, -0.042237, 0.15512, 0.0268882, 0.0427685, -0.0488711, 0.17128, 0.033235, 0.0494848, -0.0557997, 0.181813, 0.0404443, 0.0592394, -0.0635578, 0.198745, 0.0490043, 0.0681463, -0.071838, 0.210497, 0.0588239, 0.0804753, -0.0809297, 0.228864, 0.0702835, 0.0942205, -0.0906488, 0.247008, 0.0834012, 0.106777, -0.100216, 0.258812, 0.0975952, 0.124471, -0.110827, 0.278617, 0.114162, 0.138389, -0.121193, 0.287049, 0.131983, 0.159543, -0.13253, 0.307151, 0.152541, 0.176432, -0.143611, 0.31564, 0.174673, 0.201723, -0.15548, 0.33538, 0.199842, 0.229721, -0.167166, 0.355256, 0.227097, 0.250206, -0.178238, 0.360047, 0.256014, 0.282118, -0.189905, 0.378761, 0.28855, 0.312821, -0.201033, 0.39181, 0.323348, 0.341482, -0.211584, 0.397716, 0.360564, 0.377368, -0.221314, 0.410141, 0.400004, 0.418229, -0.230474, 0.423485, 0.442371, 0.444881, -0.239443, 0.418874, 0.488796, 0.488899, -0.245987, 0.427545, 0.535012, 0.520317, -0.253948, 0.422147, 0.589678, 0.568566, -0.256616, 0.42719, 0.637683, 0.599607, -0.26376, 0.415114, 0.703363, 0.64222, -0.268687, 0.408715, 0.771363, 0.685698, -0.2694, 0.399722, 0.83574, 0.732327, -0.266642, 0.388651, 0.897764, 0.769873, -0.267712, 0.369198, 0.983312, 0.806733, -0.263479, 0.346802, 1.06222, 0.843466, -0.254575, 0.321368, 1.13477, 0.873008, -0.242749, 0.29211, 1.20712, 0.908438, -0.22725, 0.262143, 1.27465, 0.936321, -0.207621, 0.228876, 1.33203, 0.950353, -0.187932, 0.19484, 1.40439, 0.96442, -0.165154, 0.163178, 1.4732, 0.979856, -0.139302, 0.127531, 1.53574, 0.982561, -0.11134, 0.0903457, 1.59982, 0.996389, -0.0808124, 0.0489007, 1.6577]; + const LTC_MAT_2 = [1, 0, 0, 0, 1, 0.000000000000000000000000000000791421, 0, 0, 1, 0.00000000000000000000000104392, 0, 0, 1, 0.00000000000000000000349405, 0, 0, 1, 0.00000000000000000109923, 0, 0, 1, 0.0000000000000000947414, 0, 0, 1, 0.00000000000000359627, 0, 0, 1, 0.0000000000000772053, 0, 0, 1, 0.00000000000108799, 0, 0, 1, 0.0000000000110655, 0, 0, 1, 0.0000000000865818, 0, 0, 0.999998, 0.000000000545037, 0, 0, 0.999994, 0.00000000285095, 0, 0, 0.999989, 0.0000000126931, 0, 0, 0.999973, 0.0000000489938, 0, 0, 0.999947, 0.000000166347, 0, 0, 0.999894, 0.000000502694, 0, 0, 0.999798, 0.00000136532, 0, 0, 0.999617, 0.00000335898, 0, 0, 0.999234, 0.00000752126, 0, 0, 0.998258, 0.0000152586, 0, 0, 0.99504, 0.0000266207, 0, 0, 0.980816, 0.0000236802, 0, 0, 0.967553, 0.00000207684, 0, 0, 0.966877, 0.00000403733, 0, 0, 0.965752, 0.00000741174, 0, 0, 0.96382, 0.0000127746, 0, 0, 0.960306, 0.0000202792, 0, 0, 0.953619, 0.0000280232, 0, 0, 0.941103, 0.0000278816, 0, 0, 0.926619, 0.0000160221, 0, 0, 0.920983, 0.0000235164, 0, 0, 0.912293, 0.0000311924, 0, 0.0158731, 0.899277, 0.0000348118, 0, 0.0476191, 0.880884, 0.000026041, 0, 0.0793651, 0.870399, 0.0000338726, 0, 0.111111, 0.856138, 0.0000392906, 0, 0.142857, 0.837436, 0.0000372874, 0, 0.174603, 0.820973, 0.0000392558, 0, 0.206349, 0.803583, 0.0000434658, 0, 0.238095, 0.782168, 0.000040256, 0, 0.269841, 0.764107, 0.0000448159, 0, 0.301587, 0.743092, 0.0000457627, 0, 0.333333, 0.721626, 0.0000455314, 0, 0.365079, 0.700375, 0.0000477335, 0, 0.396825, 0.677334, 0.0000461072, 0, 0.428571, 0.655702, 0.0000484393, 0, 0.460317, 0.632059, 0.0000464583, 0, 0.492064, 0.610125, 0.0000483923, 0, 0.52381, 0.58653, 0.0000464342, 0, 0.555556, 0.564508, 0.0000477033, 0, 0.587302, 0.541405, 0.0000459263, 0, 0.619048, 0.519556, 0.000046412, 0, 0.650794, 0.497292, 0.0000448913, 0, 0.68254, 0.475898, 0.0000445789, 0, 0.714286, 0.454722, 0.0000433496, 0, 0.746032, 0.434042, 0.0000423054, 0, 0.777778, 0.414126, 0.0000413737, 0, 0.809524, 0.394387, 0.0000397265, 0, 0.84127, 0.375841, 0.0000390709, 0, 0.873016, 0.357219, 0.0000369938, 0, 0.904762, 0.340084, 0.0000365618, 0, 0.936508, 0.322714, 0.0000342533, 0, 0.968254, 0.306974, 0.0000339596, 0, 1, 1, 0.00000000000000000101524, 0, 0, 1, 0.0000000000000000010292, 0, 0, 1, 0.00000000000000000130908, 0, 0, 1, 0.00000000000000000473331, 0, 0, 1, 0.0000000000000000625319, 0, 0, 1, 0.00000000000000107932, 0, 0, 1, 0.0000000000000163779, 0, 0, 1, 0.000000000000203198, 0, 0, 1, 0.00000000000204717, 0, 0, 0.999999, 0.0000000000168995, 0, 0, 0.999998, 0.000000000115855, 0, 0, 0.999996, 0.00000000066947, 0, 0, 0.999991, 0.00000000330863, 0, 0, 0.999983, 0.0000000141737, 0, 0, 0.999968, 0.0000000532626, 0, 0, 0.99994, 0.000000177431, 0, 0, 0.999891, 0.000000528835, 0, 0, 0.999797, 0.00000142169, 0, 0, 0.999617, 0.00000347057, 0, 0, 0.999227, 0.0000077231, 0, 0, 0.998239, 0.0000155753, 0, 0, 0.994937, 0.0000268495, 0, 0, 0.980225, 0.0000213742, 0, 0, 0.967549, 0.0000021631, 0, 0, 0.966865, 0.00000417989, 0, 0, 0.965739, 0.00000763341, 0, 0, 0.963794, 0.0000130892, 0, 0, 0.960244, 0.0000206456, 0, 0, 0.953495, 0.0000282016, 0, 0.000148105, 0.940876, 0.0000271581, 0, 0.002454, 0.926569, 0.0000164159, 0, 0.00867491, 0.920905, 0.0000239521, 0, 0.01956, 0.912169, 0.0000315127, 0, 0.035433, 0.899095, 0.0000346626, 0, 0.056294, 0.882209, 0.0000290223, 0, 0.0818191, 0.870272, 0.0000342992, 0, 0.111259, 0.855977, 0.0000394164, 0, 0.142857, 0.837431, 0.0000372343, 0, 0.174603, 0.820826, 0.0000396691, 0, 0.206349, 0.803408, 0.0000435395, 0, 0.238095, 0.782838, 0.0000419579, 0, 0.269841, 0.763941, 0.0000450953, 0, 0.301587, 0.742904, 0.0000455847, 0, 0.333333, 0.721463, 0.0000458833, 0, 0.365079, 0.700197, 0.0000477159, 0, 0.396825, 0.677501, 0.0000470641, 0, 0.428571, 0.655527, 0.0000484732, 0, 0.460317, 0.6324, 0.0000476834, 0, 0.492064, 0.609964, 0.0000484213, 0, 0.52381, 0.586839, 0.0000475541, 0, 0.555556, 0.564353, 0.0000476951, 0, 0.587302, 0.541589, 0.0000467611, 0, 0.619048, 0.519413, 0.0000463493, 0, 0.650794, 0.497337, 0.0000453994, 0, 0.68254, 0.475797, 0.0000445308, 0, 0.714286, 0.454659, 0.0000435787, 0, 0.746032, 0.434065, 0.0000424839, 0, 0.777778, 0.414018, 0.000041436, 0, 0.809524, 0.39455, 0.0000401902, 0, 0.84127, 0.375742, 0.0000390813, 0, 0.873016, 0.357501, 0.0000377116, 0, 0.904762, 0.339996, 0.000036535, 0, 0.936508, 0.323069, 0.0000351265, 0, 0.968254, 0.306897, 0.0000339112, 0, 1, 1, 0.0000000000000010396, 0, 0, 1, 0.00000000000000104326, 0, 0, 1, 0.00000000000000110153, 0, 0, 1, 0.00000000000000144668, 0, 0, 1, 0.0000000000000034528, 0, 0, 1, 0.0000000000000175958, 0, 0, 1, 0.00000000000012627, 0, 0, 1, 0.000000000000936074, 0, 0, 1, 0.00000000000645742, 0, 0, 0.999998, 0.0000000000401228, 0, 0, 0.999997, 0.000000000222338, 0, 0, 0.999995, 0.0000000010967, 0, 0, 0.999991, 0.00000000482132, 0, 0, 0.999981, 0.0000000189434, 0, 0, 0.999967, 0.0000000667716, 0, 0, 0.999938, 0.000000212066, 0, 0, 0.999886, 0.00000060977, 0, 0, 0.999792, 0.00000159504, 0, 0, 0.999608, 0.00000381191, 0, 0, 0.999209, 0.00000833727, 0, 0, 0.998179, 0.0000165288, 0, 0, 0.994605, 0.0000274387, 0, 0, 0.979468, 0.0000167316, 0, 0, 0.967529, 0.00000242877, 0, 0, 0.966836, 0.00000461696, 0, 0, 0.96569, 0.00000830977, 0, 0, 0.963706, 0.0000140427, 0, 0.00000244659, 0.960063, 0.0000217353, 0, 0.000760774, 0.953113, 0.0000286606, 0, 0.00367261, 0.940192, 0.0000247691, 0, 0.00940263, 0.927731, 0.0000195814, 0, 0.018333, 0.920669, 0.0000252531, 0, 0.0306825, 0.911799, 0.0000324277, 0, 0.0465556, 0.89857, 0.0000340982, 0, 0.0659521, 0.883283, 0.0000319622, 0, 0.0887677, 0.86989, 0.000035548, 0, 0.114784, 0.855483, 0.0000397143, 0, 0.143618, 0.837987, 0.0000391665, 0, 0.174606, 0.820546, 0.0000411306, 0, 0.206349, 0.802878, 0.0000436753, 0, 0.238095, 0.783402, 0.0000444, 0, 0.269841, 0.763439, 0.0000458726, 0, 0.301587, 0.742925, 0.0000467097, 0, 0.333333, 0.721633, 0.0000478887, 0, 0.365079, 0.69985, 0.0000481251, 0, 0.396825, 0.67783, 0.0000491811, 0, 0.428571, 0.655126, 0.0000488199, 0, 0.460318, 0.632697, 0.0000496025, 0, 0.492064, 0.609613, 0.000048829, 0, 0.52381, 0.587098, 0.0000492754, 0, 0.555556, 0.564119, 0.0000482625, 0, 0.587302, 0.541813, 0.0000482807, 0, 0.619048, 0.519342, 0.0000471552, 0, 0.650794, 0.497514, 0.0000466765, 0, 0.68254, 0.475879, 0.0000455582, 0, 0.714286, 0.454789, 0.0000446007, 0, 0.746032, 0.434217, 0.0000435382, 0, 0.777778, 0.414086, 0.0000421753, 0, 0.809524, 0.394744, 0.0000412093, 0, 0.84127, 0.375782, 0.0000396634, 0, 0.873016, 0.357707, 0.0000386419, 0, 0.904762, 0.340038, 0.0000370345, 0, 0.936508, 0.323284, 0.0000359725, 0, 0.968254, 0.306954, 0.00003436, 0, 1, 1, 0.0000000000000599567, 0, 0, 1, 0.0000000000000600497, 0, 0, 1, 0.0000000000000614839, 0, 0, 1, 0.0000000000000686641, 0, 0, 1, 0.0000000000000972658, 0, 0, 1, 0.000000000000221271, 0, 0, 1, 0.000000000000833195, 0, 0, 1, 0.00000000000403601, 0, 0, 0.999999, 0.0000000000206001, 0, 0, 0.999998, 0.000000000101739, 0, 0, 0.999997, 0.000000000470132, 0, 0, 0.999993, 0.00000000200436, 0, 0, 0.999988, 0.00000000783682, 0, 0, 0.999979, 0.0000000280338, 0, 0, 0.999962, 0.0000000917033, 0, 0, 0.999933, 0.000000274514, 0, 0, 0.999881, 0.000000753201, 0, 0, 0.999783, 0.00000189826, 0, 0, 0.999594, 0.00000440279, 0, 0, 0.999178, 0.0000093898, 0, 0, 0.998073, 0.0000181265, 0, 0, 0.993993, 0.0000280487, 0, 0, 0.979982, 0.0000149422, 0, 0, 0.968145, 0.00000378481, 0, 0, 0.966786, 0.0000053771, 0, 0, 0.965611, 0.00000947508, 0, 0.0000388934, 0.963557, 0.0000156616, 0, 0.0009693, 0.959752, 0.0000235144, 0, 0.00370329, 0.952461, 0.0000291568, 0, 0.00868428, 0.940193, 0.0000240102, 0, 0.0161889, 0.929042, 0.0000231235, 0, 0.0263948, 0.920266, 0.0000273968, 0, 0.0394088, 0.911178, 0.0000337915, 0, 0.0552818, 0.897873, 0.0000333629, 0, 0.0740138, 0.884053, 0.0000351405, 0, 0.0955539, 0.869455, 0.0000378034, 0, 0.119795, 0.854655, 0.0000399378, 0, 0.14656, 0.838347, 0.0000419108, 0, 0.175573, 0.820693, 0.0000440831, 0, 0.206388, 0.802277, 0.0000445599, 0, 0.238095, 0.783634, 0.0000472691, 0, 0.269841, 0.763159, 0.0000476984, 0, 0.301587, 0.742914, 0.0000491487, 0, 0.333333, 0.721662, 0.0000502312, 0, 0.365079, 0.699668, 0.0000502817, 0, 0.396825, 0.677839, 0.000051406, 0, 0.428571, 0.655091, 0.0000511095, 0, 0.460317, 0.632665, 0.0000516067, 0, 0.492064, 0.609734, 0.0000512255, 0, 0.52381, 0.587043, 0.0000510263, 0, 0.555556, 0.564298, 0.000050565, 0, 0.587302, 0.541769, 0.0000497951, 0, 0.619048, 0.519529, 0.0000492698, 0, 0.650794, 0.497574, 0.0000482066, 0, 0.68254, 0.476028, 0.0000473689, 0, 0.714286, 0.454961, 0.0000461941, 0, 0.746032, 0.434341, 0.0000450618, 0, 0.777778, 0.414364, 0.0000438355, 0, 0.809524, 0.394832, 0.0000424196, 0, 0.84127, 0.376109, 0.0000412563, 0, 0.873016, 0.35779, 0.0000396226, 0, 0.904762, 0.340379, 0.0000384886, 0, 0.936508, 0.323385, 0.0000368214, 0, 0.968254, 0.307295, 0.0000356636, 0, 1, 1, 0.00000000000106465, 0, 0, 1, 0.00000000000106555, 0, 0, 1, 0.00000000000107966, 0, 0, 1, 0.00000000000114601, 0, 0, 1, 0.00000000000137123, 0, 0, 1, 0.0000000000021243, 0, 0, 0.999999, 0.00000000000489653, 0, 0, 0.999999, 0.0000000000160283, 0, 0, 0.999998, 0.000000000062269, 0, 0, 0.999997, 0.000000000251859, 0, 0, 0.999996, 0.000000000996192, 0, 0, 0.999992, 0.00000000374531, 0, 0, 0.999986, 0.0000000132022, 0, 0, 0.999975, 0.0000000433315, 0, 0, 0.999959, 0.000000131956, 0, 0, 0.999927, 0.000000372249, 0, 0, 0.999871, 0.000000972461, 0, 0, 0.999771, 0.00000235343, 0, 0, 0.999572, 0.0000052768, 0, 0, 0.999133, 0.0000109237, 0, 0, 0.997912, 0.0000203675, 0, 0, 0.993008, 0.0000279396, 0, 0, 0.980645, 0.0000139604, 0, 0, 0.970057, 0.00000646596, 0, 0, 0.966717, 0.0000065089, 0, 0.0000474145, 0.965497, 0.0000111863, 0, 0.00089544, 0.96334, 0.0000179857, 0, 0.0032647, 0.959294, 0.0000259045, 0, 0.0075144, 0.951519, 0.0000292327, 0, 0.0138734, 0.940517, 0.0000249769, 0, 0.0224952, 0.93014, 0.000026803, 0, 0.0334828, 0.91972, 0.0000303656, 0, 0.0468973, 0.910294, 0.0000353323, 0, 0.0627703, 0.897701, 0.0000351002, 0, 0.0811019, 0.884522, 0.0000388104, 0, 0.10186, 0.869489, 0.0000412932, 0, 0.124985, 0.853983, 0.0000415781, 0, 0.150372, 0.838425, 0.0000454066, 0, 0.177868, 0.820656, 0.0000471624, 0, 0.207245, 0.801875, 0.0000475243, 0, 0.238143, 0.783521, 0.0000505621, 0, 0.269841, 0.763131, 0.000050721, 0, 0.301587, 0.74261, 0.0000523293, 0, 0.333333, 0.72148, 0.0000528699, 0, 0.365079, 0.699696, 0.0000538677, 0, 0.396825, 0.677592, 0.0000539255, 0, 0.428571, 0.65525, 0.0000546367, 0, 0.460317, 0.632452, 0.0000541348, 0, 0.492064, 0.609903, 0.0000544976, 0, 0.52381, 0.586928, 0.0000536201, 0, 0.555556, 0.564464, 0.0000535185, 0, 0.587302, 0.541801, 0.0000524949, 0, 0.619048, 0.519681, 0.000051812, 0, 0.650794, 0.497685, 0.0000507687, 0, 0.68254, 0.47622, 0.0000496243, 0, 0.714286, 0.455135, 0.0000485714, 0, 0.746032, 0.4346, 0.0000471847, 0, 0.777778, 0.414564, 0.0000459294, 0, 0.809524, 0.395165, 0.0000444705, 0, 0.84127, 0.376333, 0.0000430772, 0, 0.873016, 0.358197, 0.0000416229, 0, 0.904762, 0.34064, 0.0000401019, 0, 0.936508, 0.323816, 0.0000386623, 0, 0.968254, 0.307581, 0.0000370933, 0, 1, 1, 0.00000000000991541, 0, 0, 1, 0.00000000000992077, 0, 0, 1, 0.0000000000100041, 0, 0, 1, 0.000000000010385, 0, 0, 1, 0.0000000000115777, 0, 0, 1, 0.0000000000150215, 0, 0, 0.999999, 0.0000000000254738, 0, 0, 0.999999, 0.0000000000598822, 0, 0, 0.999998, 0.000000000179597, 0, 0, 0.999997, 0.000000000602367, 0, 0, 0.999994, 0.00000000206835, 0, 0, 0.99999, 0.00000000694952, 0, 0, 0.999984, 0.0000000223363, 0, 0, 0.999972, 0.0000000678578, 0, 0, 0.999952, 0.000000193571, 0, 0, 0.999919, 0.000000516594, 0, 0, 0.99986, 0.00000128739, 0, 0, 0.999753, 0.00000299298, 0, 0, 0.999546, 0.00000648258, 0, 0, 0.999074, 0.0000129985, 0, 0, 0.997671, 0.0000232176, 0, 0, 0.991504, 0.0000256701, 0, 0, 0.981148, 0.0000131141, 0, 0, 0.971965, 0.00000869048, 0, 0.0000280182, 0.966624, 0.00000808301, 0, 0.000695475, 0.965344, 0.0000135235, 0, 0.00265522, 0.963048, 0.0000210592, 0, 0.00622975, 0.958673, 0.0000287473, 0, 0.0116234, 0.950262, 0.0000281379, 0, 0.018976, 0.940836, 0.0000271089, 0, 0.0283844, 0.930996, 0.000030926, 0, 0.0399151, 0.919848, 0.0000348359, 0, 0.0536063, 0.909136, 0.0000366092, 0, 0.0694793, 0.897554, 0.0000384162, 0, 0.0875342, 0.884691, 0.0000430971, 0, 0.107749, 0.869414, 0.0000447803, 0, 0.130087, 0.853462, 0.0000452858, 0, 0.154481, 0.838187, 0.0000495769, 0, 0.180833, 0.820381, 0.0000502709, 0, 0.209005, 0.801844, 0.0000522713, 0, 0.238791, 0.783061, 0.0000541505, 0, 0.269869, 0.763205, 0.0000553712, 0, 0.301587, 0.742362, 0.0000564909, 0, 0.333333, 0.721393, 0.0000572646, 0, 0.365079, 0.699676, 0.0000581012, 0, 0.396825, 0.677395, 0.000058096, 0, 0.428571, 0.655208, 0.0000585766, 0, 0.460317, 0.632451, 0.0000583602, 0, 0.492064, 0.609839, 0.0000580234, 0, 0.52381, 0.587093, 0.0000577161, 0, 0.555556, 0.564467, 0.0000568447, 0, 0.587302, 0.542043, 0.0000563166, 0, 0.619048, 0.519826, 0.000055156, 0, 0.650794, 0.497952, 0.0000541682, 0, 0.68254, 0.476477, 0.0000528971, 0, 0.714286, 0.455412, 0.0000514952, 0, 0.746032, 0.434926, 0.0000502222, 0, 0.777778, 0.4149, 0.0000485779, 0, 0.809524, 0.395552, 0.0000472242, 0, 0.84127, 0.376712, 0.0000454891, 0, 0.873016, 0.358622, 0.0000440924, 0, 0.904762, 0.341048, 0.0000422984, 0, 0.936508, 0.324262, 0.0000408582, 0, 0.968254, 0.308013, 0.0000390839, 0, 1, 1, 0.0000000000613913, 0, 0, 1, 0.0000000000614145, 0, 0, 1, 0.0000000000617708, 0, 0, 1, 0.0000000000633717, 0, 0, 1, 0.0000000000681648, 0, 0, 1, 0.0000000000808291, 0, 0, 1, 0.000000000114608, 0, 0, 0.999998, 0.000000000210507, 0, 0, 0.999997, 0.000000000499595, 0, 0, 0.999995, 0.00000000139897, 0, 0, 0.999994, 0.00000000419818, 0, 0, 0.999988, 0.0000000127042, 0, 0, 0.999979, 0.0000000375153, 0, 0, 0.999965, 0.000000106206, 0, 0, 0.999945, 0.000000285381, 0, 0, 0.999908, 0.000000723611, 0, 0, 0.999846, 0.0000017255, 0, 0, 0.999733, 0.00000386104, 0, 0, 0.999511, 0.00000808493, 0, 0, 0.998993, 0.0000156884, 0, 0, 0.997326, 0.0000265538, 0, 0, 0.989706, 0.0000206466, 0, 0, 0.981713, 0.0000130756, 0, 0.0000070005, 0.973636, 0.0000106473, 0, 0.000464797, 0.966509, 0.000010194, 0, 0.00201743, 0.965149, 0.0000165881, 0, 0.00497549, 0.962669, 0.0000249147, 0, 0.00953262, 0.95786, 0.0000317449, 0, 0.0158211, 0.949334, 0.0000281045, 0, 0.0239343, 0.941041, 0.0000303263, 0, 0.0339372, 0.931575, 0.0000356754, 0, 0.0458738, 0.920102, 0.0000397075, 0, 0.059772, 0.908002, 0.0000384886, 0, 0.075645, 0.897269, 0.000043027, 0, 0.0934929, 0.884559, 0.0000479925, 0, 0.113302, 0.869161, 0.000048246, 0, 0.135045, 0.853342, 0.0000509505, 0, 0.158678, 0.837633, 0.0000542846, 0, 0.184136, 0.820252, 0.0000554139, 0, 0.211325, 0.801872, 0.0000581412, 0, 0.240113, 0.782418, 0.0000585535, 0, 0.270306, 0.7631, 0.0000610923, 0, 0.301594, 0.742183, 0.0000613678, 0, 0.333333, 0.721098, 0.0000627275, 0, 0.365079, 0.699512, 0.0000629413, 0, 0.396825, 0.677372, 0.0000636351, 0, 0.428571, 0.655059, 0.0000633555, 0, 0.460317, 0.632567, 0.0000636513, 0, 0.492064, 0.609784, 0.0000628965, 0, 0.52381, 0.587237, 0.0000625546, 0, 0.555556, 0.564525, 0.0000615825, 0, 0.587302, 0.542181, 0.0000605048, 0, 0.619048, 0.520017, 0.0000596329, 0, 0.650794, 0.498204, 0.0000581516, 0, 0.68254, 0.476742, 0.0000569186, 0, 0.714286, 0.455803, 0.0000553833, 0, 0.746032, 0.435251, 0.0000537807, 0, 0.777778, 0.415374, 0.0000522025, 0, 0.809524, 0.395921, 0.0000503421, 0, 0.84127, 0.377253, 0.0000488211, 0, 0.873016, 0.359021, 0.0000468234, 0, 0.904762, 0.341637, 0.0000453269, 0, 0.936508, 0.3247, 0.0000433014, 0, 0.968254, 0.308625, 0.0000418007, 0, 1, 1, 0.000000000286798, 0, 0, 1, 0.000000000286877, 0, 0, 1, 0.000000000288094, 0, 0, 1, 0.000000000293506, 0, 0, 1, 0.000000000309262, 0, 0, 0.999999, 0.000000000348593, 0, 0, 0.999999, 0.000000000444582, 0, 0, 0.999998, 0.000000000688591, 0, 0, 0.999996, 0.00000000134391, 0, 0, 0.999993, 0.00000000317438, 0, 0, 0.999989, 0.00000000835609, 0, 0, 0.999983, 0.0000000228677, 0, 0, 0.999974, 0.0000000623361, 0, 0, 0.999959, 0.000000165225, 0, 0, 0.999936, 0.000000419983, 0, 0, 0.999896, 0.00000101546, 0, 0, 0.99983, 0.00000232376, 0, 0, 0.999709, 0.0000050156, 0, 0, 0.999469, 0.000010167, 0, 0, 0.998886, 0.0000190775, 0, 0, 0.996819, 0.0000300511, 0, 0, 0.988837, 0.0000185092, 0, 0.000000168222, 0.982178, 0.0000134622, 0, 0.000259622, 0.975017, 0.0000125961, 0, 0.00142595, 0.967101, 0.000013507, 0, 0.00382273, 0.964905, 0.0000205003, 0, 0.00764164, 0.96218, 0.000029546, 0, 0.0130121, 0.956821, 0.0000343738, 0, 0.0200253, 0.948829, 0.0000305063, 0, 0.0287452, 0.941092, 0.0000346487, 0, 0.039218, 0.931883, 0.0000412061, 0, 0.0514748, 0.920211, 0.0000444651, 0, 0.0655351, 0.907307, 0.0000431252, 0, 0.0814082, 0.89684, 0.0000490382, 0, 0.0990939, 0.884119, 0.000053334, 0, 0.118583, 0.869148, 0.000054114, 0, 0.139856, 0.853377, 0.0000578536, 0, 0.162882, 0.836753, 0.0000592285, 0, 0.187615, 0.820063, 0.0000622787, 0, 0.213991, 0.801694, 0.0000645492, 0, 0.241918, 0.782116, 0.000065353, 0, 0.271267, 0.762673, 0.0000674344, 0, 0.301847, 0.742133, 0.0000682788, 0, 0.333333, 0.720779, 0.0000691959, 0, 0.365079, 0.699386, 0.0000696817, 0, 0.396826, 0.67732, 0.0000699583, 0, 0.428572, 0.654888, 0.0000698447, 0, 0.460318, 0.632499, 0.0000694063, 0, 0.492064, 0.609825, 0.0000691612, 0, 0.52381, 0.587287, 0.0000681576, 0, 0.555556, 0.564743, 0.0000674138, 0, 0.587302, 0.542409, 0.0000661617, 0, 0.619048, 0.520282, 0.0000647785, 0, 0.650794, 0.498506, 0.0000633836, 0, 0.68254, 0.477102, 0.0000615905, 0, 0.714286, 0.456167, 0.0000601013, 0, 0.746032, 0.435728, 0.0000581457, 0, 0.777778, 0.415809, 0.0000564215, 0, 0.809524, 0.396517, 0.0000544997, 0, 0.84127, 0.377737, 0.0000525061, 0, 0.873016, 0.359698, 0.0000506831, 0, 0.904762, 0.342164, 0.000048568, 0, 0.936508, 0.325417, 0.0000467826, 0, 0.968254, 0.309186, 0.0000446736, 0, 1, 1, 0.00000000109018, 0, 0, 1, 0.0000000010904, 0, 0, 1, 0.00000000109393, 0, 0, 1, 0.0000000011095, 0, 0, 1, 0.000000001154, 0, 0, 1, 0.00000000126089, 0, 0, 0.999999, 0.0000000015059, 0, 0, 0.999997, 0.00000000207899, 0, 0, 0.999994, 0.00000000348164, 0, 0, 0.999993, 0.00000000705728, 0, 0, 0.999987, 0.0000000163692, 0, 0, 0.999981, 0.0000000406033, 0, 0, 0.999969, 0.00000010245, 0, 0, 0.999953, 0.000000255023, 0, 0, 0.999925, 0.00000061511, 0, 0, 0.999881, 0.00000142218, 0, 0, 0.99981, 0.00000313086, 0, 0, 0.99968, 0.00000653119, 0, 0, 0.999418, 0.000012832, 0, 0, 0.998748, 0.0000232497, 0, 0, 0.996066, 0.0000329522, 0, 0, 0.988379, 0.0000179613, 0, 0.000108799, 0.982567, 0.0000143715, 0, 0.000921302, 0.976097, 0.0000148096, 0, 0.00280738, 0.968475, 0.0000178905, 0, 0.00596622, 0.964606, 0.0000253921, 0, 0.0105284, 0.961564, 0.0000348623, 0, 0.0165848, 0.955517, 0.0000357612, 0, 0.0242, 0.948381, 0.0000343493, 0, 0.03342, 0.941095, 0.0000405849, 0, 0.0442777, 0.931923, 0.0000475394, 0, 0.0567958, 0.91996, 0.0000484328, 0, 0.0709879, 0.907419, 0.0000502146, 0, 0.086861, 0.89618, 0.0000561654, 0, 0.104415, 0.88337, 0.0000587612, 0, 0.123643, 0.869046, 0.0000618057, 0, 0.144531, 0.853278, 0.0000657392, 0, 0.167057, 0.836091, 0.000066303, 0, 0.191188, 0.819644, 0.0000704445, 0, 0.216878, 0.801246, 0.0000714071, 0, 0.244062, 0.782031, 0.0000740093, 0, 0.272649, 0.762066, 0.000074685, 0, 0.302509, 0.741964, 0.0000766647, 0, 0.333442, 0.720554, 0.0000766328, 0, 0.365079, 0.699098, 0.0000777857, 0, 0.396826, 0.677189, 0.0000774633, 0, 0.428572, 0.65484, 0.0000776235, 0, 0.460318, 0.632496, 0.0000770316, 0, 0.492064, 0.609908, 0.0000762669, 0, 0.52381, 0.587312, 0.0000753972, 0, 0.555556, 0.564938, 0.0000739994, 0, 0.587302, 0.542577, 0.0000728382, 0, 0.619048, 0.52062, 0.000071112, 0, 0.650794, 0.498819, 0.0000694004, 0, 0.68254, 0.477555, 0.0000675575, 0, 0.714286, 0.456568, 0.0000653449, 0, 0.746032, 0.436278, 0.0000636068, 0, 0.777778, 0.41637, 0.0000613466, 0, 0.809524, 0.397144, 0.0000594177, 0, 0.84127, 0.378412, 0.0000570987, 0, 0.873016, 0.360376, 0.0000550419, 0, 0.904762, 0.342906, 0.0000527422, 0, 0.936508, 0.326136, 0.0000506544, 0, 0.968254, 0.30997, 0.0000484307, 0, 1, 1, 0.00000000354014, 0, 0, 1, 0.00000000354073, 0, 0, 1, 0.00000000354972, 0, 0, 1, 0.00000000358929, 0, 0, 1, 0.00000000370093, 0, 0, 0.999999, 0.00000000396194, 0, 0, 0.999998, 0.00000000453352, 0, 0, 0.999997, 0.00000000578828, 0, 0, 0.999994, 0.00000000863812, 0, 0, 0.999991, 0.0000000153622, 0, 0, 0.999985, 0.0000000316356, 0, 0, 0.999977, 0.0000000712781, 0, 0, 0.999964, 0.000000166725, 0, 0, 0.999945, 0.000000390501, 0, 0, 0.999912, 0.000000895622, 0, 0, 0.999866, 0.00000198428, 0, 0, 0.999786, 0.00000421038, 0, 0, 0.999647, 0.00000850239, 0, 0, 0.999356, 0.0000162059, 0, 0, 0.998563, 0.0000282652, 0, 0, 0.994928, 0.0000336309, 0, 0.0000244244, 0.987999, 0.0000178458, 0, 0.000523891, 0.982893, 0.0000159162, 0, 0.00194729, 0.977044, 0.0000178056, 0, 0.00451099, 0.969972, 0.0000230624, 0, 0.00835132, 0.964237, 0.0000313922, 0, 0.013561, 0.960791, 0.0000406145, 0, 0.0202056, 0.954292, 0.0000372796, 0, 0.0283321, 0.948052, 0.0000403199, 0, 0.0379739, 0.940938, 0.0000479537, 0, 0.0491551, 0.931689, 0.0000545292, 0, 0.0618918, 0.91987, 0.000054038, 0, 0.0761941, 0.907665, 0.0000589909, 0, 0.0920672, 0.895281, 0.0000642651, 0, 0.109511, 0.882621, 0.0000659707, 0, 0.12852, 0.86873, 0.0000709973, 0, 0.149085, 0.853008, 0.0000742221, 0, 0.171189, 0.835944, 0.0000761754, 0, 0.194809, 0.818949, 0.0000797052, 0, 0.21991, 0.800951, 0.0000812434, 0, 0.246447, 0.781847, 0.0000838075, 0, 0.274352, 0.761649, 0.000084501, 0, 0.303535, 0.74152, 0.0000860258, 0, 0.333857, 0.720495, 0.0000866233, 0, 0.365104, 0.698742, 0.0000868326, 0, 0.396826, 0.677096, 0.000087133, 0, 0.428572, 0.654782, 0.0000863497, 0, 0.460318, 0.632335, 0.0000860206, 0, 0.492064, 0.610031, 0.0000849337, 0, 0.52381, 0.587457, 0.0000838279, 0, 0.555556, 0.56513, 0.000082309, 0, 0.587302, 0.542877, 0.0000803542, 0, 0.619048, 0.5209, 0.0000786928, 0, 0.650794, 0.499291, 0.0000765171, 0, 0.68254, 0.477971, 0.0000744753, 0, 0.714286, 0.457221, 0.000072209, 0, 0.746032, 0.436803, 0.0000697448, 0, 0.777778, 0.417083, 0.0000675333, 0, 0.809524, 0.397749, 0.0000648058, 0, 0.84127, 0.379177, 0.0000625759, 0, 0.873016, 0.361061, 0.0000598584, 0, 0.904762, 0.343713, 0.0000575797, 0, 0.936508, 0.326894, 0.0000549999, 0, 0.968254, 0.310816, 0.0000527482, 0, 1, 1, 0.000000010153, 0, 0, 1, 0.0000000101544, 0, 0, 1, 0.0000000101751, 0, 0, 1, 0.0000000102662, 0, 0, 1, 0.000000010521, 0, 0, 0.999999, 0.0000000111049, 0, 0, 0.999999, 0.0000000123408, 0, 0, 0.999996, 0.000000014924, 0, 0, 0.999992, 0.0000000204471, 0, 0, 0.999989, 0.0000000326539, 0, 0, 0.99998, 0.0000000603559, 0, 0, 0.999971, 0.000000123936, 0, 0, 0.999955, 0.000000269058, 0, 0, 0.999933, 0.000000593604, 0, 0, 0.999901, 0.00000129633, 0, 0, 0.999847, 0.00000275621, 0, 0, 0.999761, 0.00000564494, 0, 0, 0.999607, 0.0000110485, 0, 0, 0.999282, 0.0000204388, 0, 0, 0.99831, 0.0000341084, 0, 0.00000022038, 0.993288, 0.0000294949, 0, 0.000242388, 0.987855, 0.0000192736, 0, 0.0012503, 0.983167, 0.0000182383, 0, 0.0032745, 0.977908, 0.0000218633, 0, 0.00646321, 0.971194, 0.0000290662, 0, 0.0109133, 0.963867, 0.0000386401, 0, 0.0166927, 0.95982, 0.0000462827, 0, 0.0238494, 0.953497, 0.0000420705, 0, 0.0324178, 0.947621, 0.0000477743, 0, 0.0424225, 0.940611, 0.0000568258, 0, 0.0538808, 0.931174, 0.0000618061, 0, 0.0668047, 0.919919, 0.0000627098, 0, 0.0812014, 0.907856, 0.0000694714, 0, 0.0970745, 0.894509, 0.0000735008, 0, 0.114424, 0.881954, 0.0000763369, 0, 0.133246, 0.868309, 0.0000821896, 0, 0.153534, 0.852511, 0.000083769, 0, 0.175275, 0.835821, 0.0000881615, 0, 0.198453, 0.817981, 0.0000896368, 0, 0.223042, 0.800504, 0.0000930906, 0, 0.249009, 0.78141, 0.0000945056, 0, 0.276304, 0.761427, 0.0000963605, 0, 0.304862, 0.74094, 0.0000968088, 0, 0.334584, 0.720233, 0.0000981481, 0, 0.365322, 0.698592, 0.0000979122, 0, 0.396826, 0.676763, 0.0000981057, 0, 0.428571, 0.654808, 0.0000973956, 0, 0.460318, 0.632326, 0.0000962619, 0, 0.492064, 0.610049, 0.0000952996, 0, 0.52381, 0.58763, 0.0000933334, 0, 0.555556, 0.565261, 0.0000917573, 0, 0.587302, 0.543244, 0.0000896636, 0, 0.619048, 0.521273, 0.0000873304, 0, 0.650794, 0.499818, 0.0000852648, 0, 0.68254, 0.478536, 0.0000823961, 0, 0.714286, 0.457826, 0.000079939, 0, 0.746032, 0.437549, 0.000077126, 0, 0.777778, 0.41776, 0.0000743043, 0, 0.809524, 0.39863, 0.0000716426, 0, 0.84127, 0.379954, 0.0000686456, 0, 0.873016, 0.362025, 0.0000660514, 0, 0.904762, 0.344581, 0.0000630755, 0, 0.936508, 0.327909, 0.0000605439, 0, 0.968254, 0.311736, 0.0000576345, 0, 1, 1, 0.0000000263344, 0, 0, 1, 0.0000000263373, 0, 0, 1, 0.0000000263815, 0, 0, 1, 0.0000000265753, 0, 0, 1, 0.0000000271132, 0, 0, 0.999999, 0.0000000283279, 0, 0, 0.999997, 0.000000030833, 0, 0, 0.999995, 0.0000000358711, 0, 0, 0.999992, 0.0000000461266, 0, 0, 0.999985, 0.000000067574, 0, 0, 0.999977, 0.00000011358, 0, 0, 0.999966, 0.000000213657, 0, 0, 0.999948, 0.000000431151, 0, 0, 0.999923, 0.000000896656, 0, 0, 0.999884, 0.00000186603, 0, 0, 0.999826, 0.00000381115, 0, 0, 0.999732, 0.00000754184, 0, 0, 0.999561, 0.0000143192, 0, 0, 0.999191, 0.0000257061, 0, 0, 0.997955, 0.0000405724, 0, 0.0000744132, 0.992228, 0.0000276537, 0, 0.000716477, 0.987638, 0.0000208885, 0, 0.0022524, 0.983395, 0.0000215226, 0, 0.00484816, 0.978614, 0.0000270795, 0, 0.00860962, 0.972389, 0.0000365282, 0, 0.0136083, 0.964392, 0.0000474747, 0, 0.0198941, 0.95861, 0.0000509141, 0, 0.0275023, 0.952806, 0.000048963, 0, 0.0364584, 0.94712, 0.0000571119, 0, 0.04678, 0.940104, 0.0000671704, 0, 0.0584799, 0.930398, 0.0000687586, 0, 0.0715665, 0.919866, 0.0000738161, 0, 0.086045, 0.907853, 0.0000813235, 0, 0.101918, 0.894078, 0.0000834582, 0, 0.119186, 0.881177, 0.0000892093, 0, 0.137845, 0.867575, 0.0000944548, 0, 0.157891, 0.852107, 0.0000969607, 0, 0.179316, 0.835502, 0.000101456, 0, 0.202106, 0.81756, 0.000103256, 0, 0.226243, 0.79984, 0.000106954, 0, 0.251704, 0.780998, 0.000108066, 0, 0.278451, 0.761132, 0.000110111, 0, 0.306436, 0.740429, 0.000110459, 0, 0.335586, 0.719836, 0.000111219, 0, 0.365796, 0.698467, 0.00011145, 0, 0.3969, 0.676446, 0.000110393, 0, 0.428571, 0.654635, 0.000110035, 0, 0.460318, 0.632411, 0.000108548, 0, 0.492064, 0.609986, 0.000106963, 0, 0.52381, 0.587872, 0.000105238, 0, 0.555556, 0.565528, 0.000102665, 0, 0.587302, 0.543563, 0.000100543, 0, 0.619048, 0.52176, 0.0000976182, 0, 0.650794, 0.500188, 0.0000947099, 0, 0.68254, 0.479204, 0.0000919929, 0, 0.714286, 0.458413, 0.0000886139, 0, 0.746032, 0.438314, 0.0000857839, 0, 0.777778, 0.418573, 0.000082411, 0, 0.809524, 0.39947, 0.0000792211, 0, 0.84127, 0.380892, 0.0000759546, 0, 0.873016, 0.362953, 0.0000727571, 0, 0.904762, 0.345601, 0.0000695738, 0, 0.936508, 0.328895, 0.0000664907, 0, 0.968254, 0.312808, 0.0000634277, 0, 1, 1, 0.0000000628647, 0, 0, 1, 0.0000000628705, 0, 0, 1, 0.0000000629587, 0, 0, 1, 0.0000000633441, 0, 0, 0.999999, 0.0000000644087, 0, 0, 0.999998, 0.0000000667856, 0, 0, 0.999997, 0.0000000715889, 0, 0, 0.999995, 0.0000000809577, 0, 0, 0.999989, 0.0000000992764, 0, 0, 0.999983, 0.000000135834, 0, 0, 0.999974, 0.000000210482, 0, 0, 0.999959, 0.000000365215, 0, 0, 0.999939, 0.000000686693, 0, 0, 0.999911, 0.0000013472, 0, 0, 0.999868, 0.0000026731, 0, 0, 0.999804, 0.00000524756, 0, 0, 0.9997, 0.0000100403, 0, 0, 0.99951, 0.0000185019, 0, 0, 0.999078, 0.0000322036, 0, 0.00000620676, 0.997428, 0.0000470002, 0, 0.000341552, 0.99162, 0.0000287123, 0, 0.00143727, 0.987479, 0.0000234706, 0, 0.00349201, 0.983582, 0.0000260083, 0, 0.0066242, 0.979186, 0.0000337927, 0, 0.0109113, 0.97325, 0.0000454689, 0, 0.0164064, 0.965221, 0.0000573759, 0, 0.0231463, 0.957262, 0.0000544114, 0, 0.0311571, 0.952211, 0.0000587006, 0, 0.0404572, 0.946631, 0.0000692256, 0, 0.0510592, 0.939391, 0.0000787819, 0, 0.0629723, 0.929795, 0.0000792368, 0, 0.0762025, 0.91965, 0.0000875075, 0, 0.090753, 0.907737, 0.0000950903, 0, 0.106626, 0.893899, 0.0000972963, 0, 0.123822, 0.880239, 0.00010459, 0, 0.142337, 0.866562, 0.000107689, 0, 0.16217, 0.85164, 0.000113081, 0, 0.183314, 0.835021, 0.000116636, 0, 0.20576, 0.817311, 0.000120074, 0, 0.229496, 0.798845, 0.000121921, 0, 0.254502, 0.780479, 0.00012475, 0, 0.280753, 0.760694, 0.000125255, 0, 0.308212, 0.740142, 0.000126719, 0, 0.336825, 0.719248, 0.00012636, 0, 0.366517, 0.698209, 0.000126712, 0, 0.397167, 0.676398, 0.000125769, 0, 0.428578, 0.654378, 0.000124432, 0, 0.460318, 0.632484, 0.000123272, 0, 0.492064, 0.610113, 0.00012085, 0, 0.52381, 0.587931, 0.000118411, 0, 0.555556, 0.565872, 0.00011569, 0, 0.587302, 0.543814, 0.000112521, 0, 0.619048, 0.522265, 0.000109737, 0, 0.650794, 0.500835, 0.000106228, 0, 0.68254, 0.479818, 0.000102591, 0, 0.714286, 0.459258, 0.0000991288, 0, 0.746032, 0.439061, 0.0000952325, 0, 0.777778, 0.419552, 0.000091895, 0, 0.809524, 0.400399, 0.0000879051, 0, 0.84127, 0.381976, 0.0000844775, 0, 0.873016, 0.364009, 0.0000806316, 0, 0.904762, 0.346761, 0.0000771848, 0, 0.936508, 0.330049, 0.0000735429, 0, 0.968254, 0.314018, 0.0000702103, 0, 1, 1, 0.000000139968, 0, 0, 1, 0.000000139979, 0, 0, 1, 0.000000140145, 0, 0, 1, 0.00000014087, 0, 0, 0.999999, 0.000000142865, 0, 0, 0.999998, 0.000000147279, 0, 0, 0.999997, 0.000000156057, 0, 0, 0.999992, 0.00000017276, 0, 0, 0.999989, 0.000000204352, 0, 0, 0.99998, 0.00000026494, 0, 0, 0.999969, 0.000000383435, 0, 0, 0.999953, 0.000000618641, 0, 0, 0.999929, 0.00000108755, 0, 0, 0.999898, 0.00000201497, 0, 0, 0.999849, 0.00000381346, 0, 0, 0.999778, 0.00000719815, 0, 0, 0.999661, 0.0000133215, 0, 0, 0.999451, 0.0000238313, 0, 0, 0.998936, 0.0000401343, 0, 0.000113724, 0.99662, 0.0000517346, 0, 0.000820171, 0.991094, 0.0000304323, 0, 0.00238143, 0.987487, 0.0000281757, 0, 0.00493527, 0.983731, 0.0000320048, 0, 0.00856859, 0.979647, 0.0000423905, 0, 0.0133393, 0.973837, 0.0000562935, 0, 0.0192863, 0.96584, 0.0000677442, 0, 0.0264369, 0.956309, 0.0000623073, 0, 0.03481, 0.951523, 0.0000704131, 0, 0.0444184, 0.946003, 0.0000836594, 0, 0.0552713, 0.938454, 0.0000911736, 0, 0.0673749, 0.929279, 0.0000938264, 0, 0.0807329, 0.919239, 0.000103754, 0, 0.0953479, 0.907293, 0.000109928, 0, 0.111221, 0.893936, 0.000115257, 0, 0.128352, 0.879674, 0.000122265, 0, 0.14674, 0.865668, 0.000125733, 0, 0.166382, 0.850998, 0.000132305, 0, 0.187276, 0.834498, 0.000134844, 0, 0.209413, 0.816903, 0.000139276, 0, 0.232786, 0.798235, 0.000140984, 0, 0.257382, 0.779724, 0.00014378, 0, 0.283181, 0.760251, 0.000144623, 0, 0.310156, 0.739808, 0.000145228, 0, 0.338269, 0.718762, 0.00014539, 0, 0.367461, 0.697815, 0.000144432, 0, 0.397646, 0.67631, 0.000143893, 0, 0.428685, 0.654278, 0.000141846, 0, 0.460318, 0.632347, 0.00013935, 0, 0.492064, 0.610296, 0.000137138, 0, 0.52381, 0.588039, 0.000133806, 0, 0.555556, 0.566218, 0.000130755, 0, 0.587302, 0.544346, 0.000127128, 0, 0.619048, 0.522701, 0.000123002, 0, 0.650794, 0.501542, 0.000119443, 0, 0.68254, 0.480508, 0.000115055, 0, 0.714286, 0.460092, 0.000111032, 0, 0.746032, 0.440021, 0.000106635, 0, 0.777778, 0.420446, 0.000102162, 0, 0.809524, 0.401512, 0.000098184, 0, 0.84127, 0.38299, 0.0000936497, 0, 0.873016, 0.365232, 0.000089813, 0, 0.904762, 0.347865, 0.0000853073, 0, 0.936508, 0.331342, 0.0000817068, 0, 0.968254, 0.315202, 0.0000773818, 0, 1, 1, 0.00000029368, 0, 0, 1, 0.0000002937, 0, 0, 1, 0.000000293998, 0, 0, 1, 0.000000295298, 0, 0, 0.999999, 0.000000298865, 0, 0, 0.999998, 0.0000003067, 0, 0, 0.999995, 0.000000322082, 0, 0, 0.999992, 0.000000350767, 0, 0, 0.999986, 0.000000403538, 0, 0, 0.999976, 0.000000501372, 0, 0, 0.999964, 0.00000068562, 0, 0, 0.999945, 0.0000010374, 0, 0, 0.999919, 0.00000171269, 0, 0, 0.999882, 0.00000300175, 0, 0, 0.999829, 0.00000542144, 0, 0, 0.999749, 0.00000984182, 0, 0, 0.99962, 0.0000176213, 0, 0, 0.999382, 0.0000305995, 0, 0.0000138418, 0.998751, 0.0000496686, 0, 0.000389844, 0.995344, 0.0000510733, 0, 0.00150343, 0.990768, 0.0000345829, 0, 0.00352451, 0.987464, 0.0000342841, 0, 0.00655379, 0.983846, 0.0000399072, 0, 0.0106554, 0.980007, 0.0000533219, 0, 0.0158723, 0.974494, 0.0000696992, 0, 0.0222333, 0.96622, 0.0000776754, 0, 0.029758, 0.956273, 0.0000747718, 0, 0.0384596, 0.950952, 0.0000864611, 0, 0.0483473, 0.945215, 0.000100464, 0, 0.0594266, 0.937287, 0.000103729, 0, 0.0717019, 0.928649, 0.000111665, 0, 0.0851752, 0.918791, 0.00012353, 0, 0.0998479, 0.906685, 0.000127115, 0, 0.115721, 0.893706, 0.00013628, 0, 0.132794, 0.879248, 0.000142427, 0, 0.151067, 0.864685, 0.000148091, 0, 0.170538, 0.850032, 0.000153517, 0, 0.191204, 0.833853, 0.000157322, 0, 0.213063, 0.816353, 0.000161086, 0, 0.236107, 0.797834, 0.000164111, 0, 0.260329, 0.778831, 0.000165446, 0, 0.285714, 0.759756, 0.000167492, 0, 0.312243, 0.739419, 0.000166928, 0, 0.339887, 0.718491, 0.000167, 0, 0.368604, 0.697392, 0.000165674, 0, 0.398329, 0.676102, 0.000163815, 0, 0.428961, 0.654243, 0.000162003, 0, 0.460331, 0.632176, 0.000158831, 0, 0.492064, 0.610407, 0.000155463, 0, 0.52381, 0.588394, 0.000152062, 0, 0.555556, 0.56645, 0.000147665, 0, 0.587302, 0.5449, 0.00014375, 0, 0.619048, 0.523276, 0.000138905, 0, 0.650794, 0.502179, 0.000134189, 0, 0.68254, 0.481359, 0.000129392, 0, 0.714286, 0.46092, 0.000124556, 0, 0.746032, 0.441084, 0.00011957, 0, 0.777778, 0.421517, 0.000114652, 0, 0.809524, 0.402721, 0.000109688, 0, 0.84127, 0.384222, 0.000104667, 0, 0.873016, 0.366534, 0.0000999633, 0, 0.904762, 0.349205, 0.0000950177, 0, 0.936508, 0.332702, 0.0000907301, 0, 0.968254, 0.316599, 0.0000859769, 0, 1, 1, 0.000000585473, 0, 0, 1, 0.000000585507, 0, 0, 1, 0.00000058602, 0, 0, 0.999999, 0.000000588259, 0, 0, 0.999999, 0.000000594381, 0, 0, 0.999998, 0.000000607754, 0, 0, 0.999995, 0.000000633729, 0, 0, 0.99999, 0.00000068137, 0, 0, 0.999984, 0.000000767003, 0, 0, 0.999973, 0.000000921212, 0, 0, 0.999959, 0.00000120218, 0, 0, 0.999936, 0.00000172024, 0, 0, 0.999907, 0.00000268088, 0, 0, 0.999866, 0.00000445512, 0, 0, 0.999806, 0.00000768481, 0, 0, 0.999716, 0.00001342, 0, 0, 0.999576, 0.0000232473, 0, 0, 0.9993, 0.0000391694, 0, 0.000129917, 0.998498, 0.0000608429, 0, 0.000845035, 0.994132, 0.0000489743, 0, 0.00237616, 0.99031, 0.0000384644, 0, 0.00484456, 0.987409, 0.0000421768, 0, 0.00832472, 0.983981, 0.0000504854, 0, 0.0128643, 0.980268, 0.0000671028, 0, 0.0184947, 0.974875, 0.0000852749, 0, 0.025237, 0.966063, 0.000085531, 0, 0.0331046, 0.956779, 0.0000900588, 0, 0.0421067, 0.950259, 0.00010577, 0, 0.0522487, 0.944239, 0.000119458, 0, 0.0635343, 0.936341, 0.000122164, 0, 0.0759654, 0.928047, 0.000134929, 0, 0.0895434, 0.918065, 0.000145544, 0, 0.104269, 0.906267, 0.000150531, 0, 0.120142, 0.893419, 0.000161652, 0, 0.137163, 0.878758, 0.00016593, 0, 0.15533, 0.863699, 0.000174014, 0, 0.174645, 0.848876, 0.000177877, 0, 0.195106, 0.833032, 0.000184049, 0, 0.21671, 0.815557, 0.000186088, 0, 0.239454, 0.797323, 0.00019054, 0, 0.263332, 0.778124, 0.000191765, 0, 0.288336, 0.758929, 0.000192535, 0, 0.314451, 0.738979, 0.000192688, 0, 0.341658, 0.718213, 0.000191522, 0, 0.369924, 0.696947, 0.000190491, 0, 0.399202, 0.675807, 0.000187913, 0, 0.429416, 0.654147, 0.000184451, 0, 0.460447, 0.63229, 0.000181442, 0, 0.492064, 0.610499, 0.000177139, 0, 0.523809, 0.588747, 0.000172596, 0, 0.555555, 0.566783, 0.000167457, 0, 0.587301, 0.545359, 0.000162518, 0, 0.619048, 0.523984, 0.000156818, 0, 0.650794, 0.502917, 0.000151884, 0, 0.68254, 0.482294, 0.000145514, 0, 0.714286, 0.461945, 0.000140199, 0, 0.746032, 0.442133, 0.000134101, 0, 0.777778, 0.422705, 0.000128374, 0, 0.809524, 0.403916, 0.000122996, 0, 0.84127, 0.38554, 0.000116808, 0, 0.873016, 0.367909, 0.000111973, 0, 0.904762, 0.350651, 0.000105938, 0, 0.936508, 0.334208, 0.000101355, 0, 0.968254, 0.318123, 0.0000957629, 0, 1, 1, 0.00000111633, 0, 0, 1, 0.00000111639, 0, 0, 1, 0.00000111725, 0, 0, 1, 0.00000112096, 0, 0, 0.999999, 0.0000011311, 0, 0, 0.999997, 0.00000115315, 0, 0, 0.999995, 0.0000011956, 0, 0, 0.999989, 0.00000127239, 0, 0, 0.999981, 0.00000140772, 0, 0, 0.999969, 0.00000164541, 0, 0, 0.999952, 0.00000206607, 0, 0, 0.999928, 0.00000281783, 0, 0, 0.999895, 0.00000416835, 0, 0, 0.999848, 0.00000658728, 0, 0, 0.999781, 0.0000108648, 0, 0, 0.999682, 0.0000182579, 0, 0, 0.999523, 0.0000306003, 0, 0.0000159122, 0.999205, 0.0000499862, 0, 0.000391184, 0.998131, 0.000073306, 0, 0.00147534, 0.993334, 0.0000513229, 0, 0.0034227, 0.99016, 0.0000467783, 0, 0.00632232, 0.987321, 0.0000523413, 0, 0.0102295, 0.984099, 0.000064267, 0, 0.0151794, 0.980432, 0.0000843042, 0, 0.0211947, 0.974976, 0.000102819, 0, 0.0282899, 0.966429, 0.0000996234, 0, 0.0364739, 0.957633, 0.000111074, 0, 0.0457522, 0.949422, 0.000128644, 0, 0.0561278, 0.943045, 0.000140076, 0, 0.0676023, 0.935448, 0.000146349, 0, 0.0801762, 0.927225, 0.000161854, 0, 0.0938499, 0.917033, 0.000169135, 0, 0.108623, 0.905762, 0.000179987, 0, 0.124496, 0.892879, 0.000189832, 0, 0.141469, 0.878435, 0.000195881, 0, 0.159541, 0.863114, 0.00020466, 0, 0.178713, 0.84776, 0.000209473, 0, 0.198985, 0.832084, 0.000214861, 0, 0.220355, 0.814915, 0.000217695, 0, 0.242823, 0.796711, 0.000220313, 0, 0.266385, 0.777603, 0.00022313, 0, 0.291036, 0.757991, 0.000222471, 0, 0.316767, 0.738371, 0.000222869, 0, 0.343563, 0.717872, 0.000221243, 0, 0.371402, 0.696619, 0.000218089, 0, 0.400248, 0.675379, 0.00021562, 0, 0.430047, 0.65411, 0.00021169, 0, 0.460709, 0.63241, 0.000206947, 0, 0.492079, 0.61046, 0.000201709, 0, 0.52381, 0.58903, 0.000196753, 0, 0.555556, 0.567267, 0.000189637, 0, 0.587302, 0.545886, 0.000184735, 0, 0.619048, 0.524714, 0.000177257, 0, 0.650794, 0.503789, 0.000171424, 0, 0.68254, 0.483204, 0.000164688, 0, 0.714286, 0.462976, 0.000157172, 0, 0.746032, 0.443294, 0.000151341, 0, 0.777778, 0.423988, 0.000143737, 0, 0.809524, 0.405325, 0.000138098, 0, 0.84127, 0.386981, 0.000130698, 0, 0.873016, 0.369436, 0.000125276, 0, 0.904762, 0.35219, 0.000118349, 0, 0.936508, 0.335804, 0.00011312, 0, 0.968254, 0.319749, 0.000106687, 0, 1, 1, 0.00000204685, 0, 0, 1, 0.00000204694, 0, 0, 1, 0.00000204831, 0, 0, 0.999999, 0.00000205428, 0, 0, 0.999999, 0.00000207056, 0, 0, 0.999997, 0.00000210581, 0, 0, 0.999993, 0.0000021732, 0, 0, 0.999987, 0.00000229365, 0, 0, 0.999979, 0.00000250243, 0, 0, 0.999965, 0.00000286127, 0, 0, 0.999947, 0.00000348028, 0, 0, 0.999918, 0.00000455588, 0, 0, 0.999881, 0.00000643303, 0, 0, 0.999828, 0.00000970064, 0, 0, 0.999753, 0.0000153233, 0, 0, 0.999642, 0.000024793, 0, 0, 0.999464, 0.0000402032, 0, 0.000122947, 0.999089, 0.0000635852, 0, 0.000807414, 0.997567, 0.0000857026, 0, 0.00227206, 0.992903, 0.0000594912, 0, 0.00462812, 0.990011, 0.0000578515, 0, 0.00794162, 0.987192, 0.000065399, 0, 0.0122534, 0.98418, 0.0000819675, 0, 0.0175888, 0.980491, 0.000105514, 0, 0.0239635, 0.974779, 0.000121532, 0, 0.031387, 0.96675, 0.000119144, 0, 0.0398644, 0.958248, 0.000136125, 0, 0.0493982, 0.948884, 0.000155408, 0, 0.0599896, 0.941673, 0.000162281, 0, 0.0716382, 0.934521, 0.000176754, 0, 0.0843437, 0.926205, 0.000192873, 0, 0.0981056, 0.916089, 0.000200038, 0, 0.112923, 0.904963, 0.000213624, 0, 0.128796, 0.892089, 0.000221834, 0, 0.145725, 0.878028, 0.000232619, 0, 0.163709, 0.86249, 0.000238632, 0, 0.182749, 0.846587, 0.000247002, 0, 0.202847, 0.830988, 0.000250702, 0, 0.224001, 0.814165, 0.000255562, 0, 0.246214, 0.796135, 0.000257505, 0, 0.269482, 0.777052, 0.000258625, 0, 0.293805, 0.757201, 0.000258398, 0, 0.319176, 0.737655, 0.000256714, 0, 0.345587, 0.717477, 0.000255187, 0, 0.373021, 0.696433, 0.000251792, 0, 0.401454, 0.675084, 0.000247223, 0, 0.430844, 0.653907, 0.000242213, 0, 0.461125, 0.632561, 0.000237397, 0, 0.492187, 0.610658, 0.000229313, 0, 0.52381, 0.589322, 0.000224402, 0, 0.555556, 0.567857, 0.000216116, 0, 0.587302, 0.54652, 0.000209124, 0, 0.619048, 0.525433, 0.000201601, 0, 0.650794, 0.504679, 0.000192957, 0, 0.68254, 0.484203, 0.000186052, 0, 0.714286, 0.464203, 0.000177672, 0, 0.746032, 0.444549, 0.000170005, 0, 0.777778, 0.425346, 0.000162401, 0, 0.809524, 0.406706, 0.0001544, 0, 0.84127, 0.388576, 0.000147437, 0, 0.873016, 0.37094, 0.000139493, 0, 0.904762, 0.353996, 0.000133219, 0, 0.936508, 0.337391, 0.000125573, 0, 0.968254, 0.321648, 0.000119867, 0, 1, 1, 0.00000362511, 0, 0, 1, 0.00000362525, 0, 0, 1, 0.00000362739, 0, 0, 0.999999, 0.00000363673, 0, 0, 0.999998, 0.00000366214, 0, 0, 0.999996, 0.00000371698, 0, 0, 0.999992, 0.00000382116, 0, 0, 0.999986, 0.00000400554, 0, 0, 0.999976, 0.00000432058, 0, 0, 0.999961, 0.00000485194, 0, 0, 0.999938, 0.00000574808, 0, 0, 0.999908, 0.00000726643, 0, 0, 0.999865, 0.00000984707, 0, 0, 0.999807, 0.0000142217, 0, 0, 0.999723, 0.0000215581, 0, 0, 0.999602, 0.0000336114, 0, 0.0000119113, 0.999398, 0.0000527353, 0, 0.000355813, 0.998946, 0.0000805809, 0, 0.00137768, 0.996647, 0.0000942908, 0, 0.00322469, 0.992298, 0.0000668733, 0, 0.00597897, 0.989802, 0.0000716564, 0, 0.00968903, 0.987019, 0.0000821355, 0, 0.0143845, 0.984219, 0.000104555, 0, 0.0200831, 0.980425, 0.000131245, 0, 0.0267948, 0.974241, 0.000139613, 0, 0.034525, 0.967006, 0.000145931, 0, 0.0432757, 0.95893, 0.000167153, 0, 0.0530471, 0.949157, 0.000188146, 0, 0.0638386, 0.94062, 0.000194625, 0, 0.0756487, 0.933509, 0.000213721, 0, 0.0884762, 0.925088, 0.000229616, 0, 0.10232, 0.915178, 0.000239638, 0, 0.117178, 0.904093, 0.000254814, 0, 0.133051, 0.891337, 0.000263685, 0, 0.149939, 0.877326, 0.000274789, 0, 0.167841, 0.861794, 0.000280534, 0, 0.18676, 0.845758, 0.000289534, 0, 0.206696, 0.829792, 0.000294446, 0, 0.22765, 0.813037, 0.000296877, 0, 0.249625, 0.795285, 0.000300217, 0, 0.27262, 0.776323, 0.000299826, 0, 0.296636, 0.756673, 0.000299787, 0, 0.321671, 0.736856, 0.000297867, 0, 0.347718, 0.716883, 0.000294052, 0, 0.374768, 0.696089, 0.000289462, 0, 0.402804, 0.67505, 0.000285212, 0, 0.431796, 0.653509, 0.00027653, 0, 0.461695, 0.63258, 0.000271759, 0, 0.49242, 0.61104, 0.000262811, 0, 0.523822, 0.589567, 0.000255151, 0, 0.555556, 0.568322, 0.000246434, 0, 0.587302, 0.547235, 0.000237061, 0, 0.619048, 0.52616, 0.000228343, 0, 0.650794, 0.505716, 0.000219236, 0, 0.68254, 0.485274, 0.000209595, 0, 0.714286, 0.465411, 0.000201011, 0, 0.746032, 0.445854, 0.00019109, 0, 0.777778, 0.426911, 0.000182897, 0, 0.809524, 0.408222, 0.000173569, 0, 0.84127, 0.390307, 0.000165496, 0, 0.873016, 0.372624, 0.000156799, 0, 0.904762, 0.355804, 0.00014917, 0, 0.936508, 0.33924, 0.000140907, 0, 0.968254, 0.323534, 0.000134062, 0, 1, 1, 0.00000622487, 0, 0, 1, 0.0000062251, 0, 0, 1, 0.00000622837, 0, 0, 0.999999, 0.00000624259, 0, 0, 0.999998, 0.00000628127, 0, 0, 0.999996, 0.00000636451, 0, 0, 0.999991, 0.0000065218, 0, 0, 0.999984, 0.00000679782, 0, 0, 0.999973, 0.00000726361, 0, 0, 0.999955, 0.00000803644, 0, 0, 0.999931, 0.00000931397, 0, 0, 0.999896, 0.0000114299, 0, 0, 0.999847, 0.0000149402, 0, 0, 0.999784, 0.0000207461, 0, 0, 0.999692, 0.0000302493, 0, 0, 0.999554, 0.0000454957, 0, 0.0000997275, 0.999326, 0.0000690762, 0, 0.000724813, 0.998757, 0.000101605, 0, 0.0020972, 0.995367, 0.0000958745, 0, 0.00432324, 0.99209, 0.0000832808, 0, 0.00746347, 0.989517, 0.0000887601, 0, 0.0115534, 0.987008, 0.00010564, 0, 0.0166134, 0.98421, 0.000133179, 0, 0.0226552, 0.98021, 0.000161746, 0, 0.0296838, 0.973676, 0.000161821, 0, 0.0377016, 0.967052, 0.000178635, 0, 0.0467079, 0.959385, 0.000206765, 0, 0.0567013, 0.949461, 0.00022476, 0, 0.0676796, 0.939578, 0.00023574, 0, 0.0796403, 0.932416, 0.00025893, 0, 0.0925812, 0.923759, 0.000271228, 0, 0.106501, 0.914223, 0.000289165, 0, 0.121397, 0.902942, 0.000301156, 0, 0.13727, 0.890419, 0.000313852, 0, 0.15412, 0.876639, 0.000324408, 0, 0.171946, 0.861316, 0.00033249, 0, 0.190751, 0.84496, 0.000338497, 0, 0.210537, 0.828427, 0.000345861, 0, 0.231305, 0.811871, 0.000347863, 0, 0.253057, 0.794397, 0.000350225, 0, 0.275797, 0.775726, 0.000349915, 0, 0.299525, 0.75617, 0.000347297, 0, 0.324242, 0.736091, 0.000344232, 0, 0.349947, 0.716213, 0.000340835, 0, 0.376633, 0.695736, 0.000332369, 0, 0.404289, 0.674961, 0.000327943, 0, 0.432895, 0.653518, 0.000318533, 0, 0.462415, 0.632574, 0.000310391, 0, 0.492788, 0.61134, 0.000300755, 0, 0.523909, 0.590017, 0.000290506, 0, 0.555556, 0.568752, 0.000280446, 0, 0.587302, 0.548061, 0.000269902, 0, 0.619048, 0.52711, 0.000258815, 0, 0.650794, 0.506682, 0.000248481, 0, 0.68254, 0.486524, 0.000237141, 0, 0.714286, 0.466812, 0.000226872, 0, 0.746032, 0.44732, 0.000216037, 0, 0.777778, 0.428473, 0.000205629, 0, 0.809524, 0.409921, 0.000195691, 0, 0.84127, 0.392028, 0.000185457, 0, 0.873016, 0.374606, 0.000176436, 0, 0.904762, 0.357601, 0.000166508, 0, 0.936508, 0.341348, 0.000158385, 0, 0.968254, 0.32542, 0.000149203, 0, 1, 1, 0.0000103967, 0, 0, 1, 0.000010397, 0, 0, 1, 0.0000104019, 0, 0, 0.999999, 0.0000104231, 0, 0, 0.999998, 0.0000104806, 0, 0, 0.999995, 0.0000106042, 0, 0, 0.999991, 0.0000108366, 0, 0, 0.999982, 0.0000112415, 0, 0, 0.999968, 0.0000119174, 0, 0, 0.99995, 0.0000130227, 0, 0, 0.999922, 0.0000148176, 0, 0, 0.999884, 0.0000177303, 0, 0, 0.99983, 0.0000224564, 0, 0, 0.999758, 0.0000300966, 0, 0, 0.999654, 0.0000423193, 0, 0.00000549083, 0.999503, 0.0000614848, 0, 0.000296087, 0.999237, 0.0000903576, 0, 0.00123144, 0.998491, 0.0001271, 0, 0.00295954, 0.994594, 0.000107754, 0, 0.00555829, 0.99178, 0.000103025, 0, 0.00907209, 0.989265, 0.00011154, 0, 0.0135257, 0.986998, 0.000136296, 0, 0.0189327, 0.984137, 0.000169154, 0, 0.0252993, 0.979798, 0.000196671, 0, 0.0326272, 0.97337, 0.000196678, 0, 0.0409157, 0.967239, 0.000223121, 0, 0.0501623, 0.959543, 0.000253809, 0, 0.0603638, 0.949466, 0.000265972, 0, 0.0715171, 0.939074, 0.000288372, 0, 0.0836187, 0.931118, 0.000310983, 0, 0.0966657, 0.922525, 0.000325561, 0, 0.110656, 0.912983, 0.000345725, 0, 0.125588, 0.901617, 0.0003556, 0, 0.141461, 0.889487, 0.000374012, 0, 0.158275, 0.875787, 0.000383445, 0, 0.176031, 0.860654, 0.000393972, 0, 0.19473, 0.844417, 0.000400311, 0, 0.214374, 0.82741, 0.000405004, 0, 0.234967, 0.810545, 0.000407378, 0, 0.256512, 0.793312, 0.000407351, 0, 0.279011, 0.774847, 0.000406563, 0, 0.302468, 0.755621, 0.000404903, 0, 0.326887, 0.735511, 0.000397486, 0, 0.352266, 0.715435, 0.00039357, 0, 0.378605, 0.695403, 0.000384739, 0, 0.405897, 0.674681, 0.000376108, 0, 0.43413, 0.65359, 0.000365997, 0, 0.463277, 0.632471, 0.000354957, 0, 0.493295, 0.61151, 0.000343593, 0, 0.524106, 0.59064, 0.000331841, 0, 0.555561, 0.569386, 0.000318891, 0, 0.587302, 0.548785, 0.0003072, 0, 0.619048, 0.528146, 0.00029361, 0, 0.650794, 0.507872, 0.000281709, 0, 0.68254, 0.487805, 0.000268627, 0, 0.714286, 0.468196, 0.000255887, 0, 0.746032, 0.448922, 0.000243997, 0, 0.777778, 0.430093, 0.000231662, 0, 0.809524, 0.411845, 0.000220339, 0, 0.84127, 0.393808, 0.000208694, 0, 0.873016, 0.376615, 0.000198045, 0, 0.904762, 0.359655, 0.000187375, 0, 0.936508, 0.343452, 0.000177371, 0, 0.968254, 0.32765, 0.000167525, 0, 1, 1, 0.0000169351, 0, 0, 1, 0.0000169356, 0, 0, 1, 0.0000169427, 0, 0, 0.999999, 0.0000169736, 0, 0, 0.999998, 0.0000170575, 0, 0, 0.999995, 0.0000172372, 0, 0, 0.99999, 0.0000175739, 0, 0, 0.999979, 0.0000181568, 0, 0, 0.999966, 0.0000191206, 0, 0, 0.999944, 0.000020677, 0, 0, 0.999912, 0.0000231644, 0, 0, 0.999869, 0.0000271268, 0, 0, 0.999811, 0.0000334272, 0, 0, 0.99973, 0.0000433979, 0, 0, 0.999617, 0.0000590083, 0, 0.0000680315, 0.999445, 0.0000829497, 0, 0.000612796, 0.999138, 0.000118019, 0, 0.00187408, 0.998095, 0.000156712, 0, 0.00395791, 0.993919, 0.000125054, 0, 0.00692144, 0.991333, 0.000126091, 0, 0.0107962, 0.989226, 0.000144912, 0, 0.0155986, 0.986954, 0.000175737, 0, 0.0213364, 0.983982, 0.000213883, 0, 0.0280114, 0.979128, 0.000234526, 0, 0.0356226, 0.973327, 0.000243725, 0, 0.0441668, 0.967416, 0.0002773, 0, 0.0536399, 0.959729, 0.000308799, 0, 0.0640376, 0.949758, 0.000322447, 0, 0.0753554, 0.939173, 0.000350021, 0, 0.0875893, 0.9296, 0.000370089, 0, 0.100736, 0.921181, 0.000391365, 0, 0.114793, 0.91164, 0.000413636, 0, 0.129759, 0.900435, 0.000427068, 0, 0.145632, 0.888183, 0.000441046, 0, 0.162412, 0.874772, 0.000454968, 0, 0.180101, 0.859566, 0.000461882, 0, 0.1987, 0.843579, 0.000471556, 0, 0.218213, 0.826453, 0.000474335, 0, 0.238641, 0.809164, 0.000477078, 0, 0.259989, 0.792179, 0.00047755, 0, 0.282262, 0.773866, 0.000472573, 0, 0.305464, 0.754944, 0.000469765, 0, 0.329599, 0.735133, 0.000462371, 0, 0.35467, 0.714858, 0.000453674, 0, 0.380678, 0.694829, 0.000443888, 0, 0.407622, 0.674453, 0.000432052, 0, 0.435493, 0.653685, 0.000420315, 0, 0.464275, 0.632666, 0.000406829, 0, 0.493938, 0.611676, 0.000392234, 0, 0.524422, 0.591193, 0.000379208, 0, 0.555624, 0.570145, 0.00036319, 0, 0.587302, 0.549566, 0.000349111, 0, 0.619048, 0.529278, 0.000334166, 0, 0.650794, 0.509026, 0.000318456, 0, 0.68254, 0.489186, 0.00030449, 0, 0.714286, 0.469662, 0.000289051, 0, 0.746032, 0.450691, 0.000275494, 0, 0.777778, 0.431841, 0.000261437, 0, 0.809524, 0.413752, 0.000247846, 0, 0.84127, 0.395951, 0.000235085, 0, 0.873016, 0.378633, 0.000222245, 0, 0.904762, 0.36194, 0.000210533, 0, 0.936508, 0.345599, 0.000198494, 0, 0.968254, 0.329999, 0.000188133, 0, 1, 1, 0.0000269663, 0, 0, 1, 0.000026967, 0, 0, 1, 0.0000269772, 0, 0, 0.999999, 0.0000270214, 0, 0, 0.999998, 0.0000271415, 0, 0, 0.999994, 0.000027398, 0, 0, 0.999988, 0.0000278771, 0, 0, 0.999977, 0.0000287019, 0, 0, 0.999961, 0.0000300544, 0, 0, 0.999937, 0.0000322138, 0, 0, 0.999904, 0.0000356163, 0, 0, 0.999854, 0.0000409465, 0, 0, 0.99979, 0.0000492651, 0, 0, 0.999699, 0.0000621722, 0, 0.00000088288, 0.999572, 0.0000819715, 0, 0.000223369, 0.999381, 0.000111689, 0, 0.00105414, 0.999016, 0.000153862, 0, 0.0026493, 0.997437, 0.000187667, 0, 0.00508608, 0.993545, 0.000155672, 0, 0.00840554, 0.991135, 0.000161455, 0, 0.012629, 0.989157, 0.000188241, 0, 0.0177661, 0.986874, 0.000226229, 0, 0.0238198, 0.983714, 0.000268668, 0, 0.0307887, 0.978301, 0.000277109, 0, 0.0386688, 0.973227, 0.000303446, 0, 0.0474554, 0.967317, 0.000341851, 0, 0.0571428, 0.959477, 0.000370885, 0, 0.0677256, 0.950012, 0.000392753, 0, 0.0791988, 0.939484, 0.00042781, 0, 0.0915576, 0.928135, 0.000443866, 0, 0.104798, 0.919819, 0.000472959, 0, 0.118918, 0.910049, 0.000491551, 0, 0.133915, 0.899181, 0.000512616, 0, 0.149788, 0.886881, 0.000523563, 0, 0.166537, 0.87359, 0.000540183, 0, 0.184164, 0.858613, 0.000547386, 0, 0.202669, 0.842809, 0.000554809, 0, 0.222056, 0.825727, 0.000558316, 0, 0.242329, 0.808086, 0.000557824, 0, 0.263492, 0.790728, 0.000556346, 0, 0.285551, 0.772987, 0.000552672, 0, 0.30851, 0.7541, 0.000543738, 0, 0.332376, 0.734669, 0.000536107, 0, 0.357153, 0.714411, 0.000523342, 0, 0.382845, 0.694196, 0.000512238, 0, 0.409454, 0.674252, 0.000497465, 0, 0.436977, 0.65357, 0.000481096, 0, 0.465404, 0.632999, 0.000467054, 0, 0.494713, 0.611994, 0.000448771, 0, 0.524864, 0.591604, 0.000431889, 0, 0.555779, 0.571134, 0.000415238, 0, 0.587302, 0.550528, 0.000396369, 0, 0.619048, 0.530292, 0.000379477, 0, 0.650794, 0.510364, 0.000361488, 0, 0.68254, 0.490749, 0.000343787, 0, 0.714286, 0.471266, 0.000327822, 0, 0.746032, 0.452462, 0.000310626, 0, 0.777778, 0.433907, 0.000295352, 0, 0.809524, 0.415659, 0.000279179, 0, 0.84127, 0.398138, 0.000264685, 0, 0.873016, 0.380833, 0.000249905, 0, 0.904762, 0.364247, 0.000236282, 0, 0.936508, 0.348041, 0.000222905, 0, 0.968254, 0.332389, 0.000210522, 0, 1, 1, 0.0000420604, 0, 0, 1, 0.0000420614, 0, 0, 1, 0.0000420757, 0, 0, 0.999999, 0.000042138, 0, 0, 0.999997, 0.0000423067, 0, 0, 0.999993, 0.0000426668, 0, 0, 0.999986, 0.0000433372, 0, 0, 0.999974, 0.0000444857, 0, 0, 0.999956, 0.0000463554, 0, 0, 0.99993, 0.0000493105, 0, 0, 0.999892, 0.0000539077, 0, 0, 0.999838, 0.0000610005, 0, 0, 0.999767, 0.0000718822, 0, 0, 0.999666, 0.0000884581, 0, 0.0000365471, 0.999525, 0.000113398, 0, 0.000485623, 0.999311, 0.000150043, 0, 0.00162096, 0.998865, 0.000200063, 0, 0.00355319, 0.996278, 0.000211014, 0, 0.00633818, 0.992956, 0.000189672, 0, 0.0100043, 0.991017, 0.000210262, 0, 0.0145648, 0.989055, 0.000244292, 0, 0.0200237, 0.986741, 0.000290481, 0, 0.0263798, 0.983288, 0.000334303, 0, 0.033629, 0.977784, 0.000340307, 0, 0.0417652, 0.973037, 0.000377864, 0, 0.0507821, 0.967181, 0.0004239, 0, 0.060673, 0.958971, 0.000443854, 0, 0.0714314, 0.950093, 0.000483039, 0, 0.0830518, 0.939552, 0.000517934, 0, 0.0955288, 0.927678, 0.000539449, 0, 0.108859, 0.918278, 0.000568604, 0, 0.123038, 0.908449, 0.000588505, 0, 0.138065, 0.897713, 0.000612473, 0, 0.153938, 0.885533, 0.000625575, 0, 0.170657, 0.872131, 0.00063854, 0, 0.188224, 0.857517, 0.000647034, 0, 0.20664, 0.841796, 0.00065209, 0, 0.225909, 0.824726, 0.0006544, 0, 0.246035, 0.807297, 0.000655744, 0, 0.267022, 0.789058, 0.000646716, 0, 0.288878, 0.77189, 0.000643898, 0, 0.311607, 0.753082, 0.000629973, 0, 0.335216, 0.7341, 0.000621564, 0, 0.359713, 0.714094, 0.000605171, 0, 0.385103, 0.693839, 0.000588752, 0, 0.41139, 0.673891, 0.000573294, 0, 0.438576, 0.653565, 0.000552682, 0, 0.466656, 0.633326, 0.000533446, 0, 0.495617, 0.612582, 0.000514635, 0, 0.525431, 0.59205, 0.00049303, 0, 0.556041, 0.571918, 0.000471842, 0, 0.587338, 0.551572, 0.000451713, 0, 0.619048, 0.531553, 0.000430049, 0, 0.650794, 0.51175, 0.000410445, 0, 0.68254, 0.49238, 0.000390098, 0, 0.714286, 0.473143, 0.000370033, 0, 0.746032, 0.45423, 0.000351205, 0, 0.777778, 0.435963, 0.000332049, 0, 0.809524, 0.41787, 0.000315021, 0, 0.84127, 0.400387, 0.000297315, 0, 0.873016, 0.383332, 0.000281385, 0, 0.904762, 0.366665, 0.000265397, 0, 0.936508, 0.350633, 0.000250601, 0, 0.968254, 0.334964, 0.00023589, 0, 1, 1, 0.0000643736, 0, 0, 1, 0.000064375, 0, 0, 1, 0.0000643947, 0, 0, 0.999999, 0.000064481, 0, 0, 0.999997, 0.0000647143, 0, 0, 0.999994, 0.0000652119, 0, 0, 0.999985, 0.0000661359, 0, 0, 0.999972, 0.0000677116, 0, 0, 0.999952, 0.0000702599, 0, 0, 0.999922, 0.0000742517, 0, 0, 0.99988, 0.0000803906, 0, 0, 0.99982, 0.0000897315, 0, 0, 0.999741, 0.000103838, 0, 0, 0.999629, 0.00012496, 0, 0.000149024, 0.999474, 0.000156161, 0, 0.000861027, 0.999229, 0.000201034, 0, 0.00231198, 0.998662, 0.000259069, 0, 0.00458147, 0.995299, 0.000245439, 0, 0.00770895, 0.992732, 0.00024498, 0, 0.0117126, 0.990847, 0.000273211, 0, 0.0165989, 0.988911, 0.000316492, 0, 0.0223674, 0.98654, 0.00037161, 0, 0.0290135, 0.982636, 0.000410352, 0, 0.0365309, 0.977346, 0.000421756, 0, 0.0449117, 0.972909, 0.000475578, 0, 0.0541481, 0.966821, 0.000522482, 0, 0.0642326, 0.958686, 0.000545008, 0, 0.075158, 0.949754, 0.000589286, 0, 0.0869181, 0.939184, 0.000619995, 0, 0.0995074, 0.927505, 0.000654266, 0, 0.112922, 0.916606, 0.000682362, 0, 0.127157, 0.906707, 0.000704286, 0, 0.142212, 0.895937, 0.000725909, 0, 0.158085, 0.883913, 0.000743939, 0, 0.174776, 0.870642, 0.000755157, 0, 0.192287, 0.856241, 0.000764387, 0, 0.210619, 0.84069, 0.000771032, 0, 0.229775, 0.823728, 0.000765906, 0, 0.249761, 0.806481, 0.000767604, 0, 0.270582, 0.787924, 0.000754385, 0, 0.292243, 0.770588, 0.000749668, 0, 0.314753, 0.751991, 0.000731613, 0, 0.338118, 0.733407, 0.000717655, 0, 0.362347, 0.713688, 0.000700604, 0, 0.387447, 0.693595, 0.000678765, 0, 0.413424, 0.673426, 0.000657042, 0, 0.440284, 0.65359, 0.000635892, 0, 0.468027, 0.633576, 0.000611569, 0, 0.496645, 0.613144, 0.000586011, 0, 0.526122, 0.592711, 0.000563111, 0, 0.556417, 0.572722, 0.000537699, 0, 0.587451, 0.552762, 0.000512556, 0, 0.619048, 0.532985, 0.000489757, 0, 0.650794, 0.513219, 0.000464139, 0, 0.68254, 0.493992, 0.000442193, 0, 0.714286, 0.47509, 0.000418629, 0, 0.746032, 0.456287, 0.000397045, 0, 0.777778, 0.438152, 0.000375504, 0, 0.809524, 0.420294, 0.00035492, 0, 0.84127, 0.402749, 0.000335327, 0, 0.873016, 0.385879, 0.000316422, 0, 0.904762, 0.369352, 0.000298333, 0, 0.936508, 0.353301, 0.000281417, 0, 0.968254, 0.337781, 0.000265203, 0, 1, 1, 0.0000968267, 0, 0, 1, 0.0000968284, 0, 0, 1, 0.0000968556, 0, 0, 0.999999, 0.0000969733, 0, 0, 0.999997, 0.0000972913, 0, 0, 0.999993, 0.0000979688, 0, 0, 0.999984, 0.0000992239, 0, 0, 0.999969, 0.000101356, 0, 0, 0.999946, 0.000104784, 0, 0, 0.999913, 0.000110111, 0, 0, 0.999868, 0.000118217, 0, 0, 0.999801, 0.000130396, 0, 0, 0.999712, 0.000148523, 0, 0.0000124907, 0.999589, 0.000175233, 0, 0.000355405, 0.999416, 0.000213999, 0, 0.0013528, 0.999136, 0.000268529, 0, 0.00312557, 0.998367, 0.000333088, 0, 0.00573045, 0.994701, 0.000304757, 0, 0.00919397, 0.992497, 0.000318031, 0, 0.0135261, 0.990608, 0.000353863, 0, 0.0187278, 0.988715, 0.000409044, 0, 0.0247947, 0.986241, 0.000472967, 0, 0.0317196, 0.981696, 0.000495104, 0, 0.039494, 0.977097, 0.000532873, 0, 0.0481087, 0.972583, 0.000594447, 0, 0.0575549, 0.966142, 0.000636867, 0, 0.0678242, 0.95823, 0.000669899, 0, 0.0789089, 0.949677, 0.000719499, 0, 0.0908023, 0.939226, 0.000750584, 0, 0.103499, 0.927501, 0.000793183, 0, 0.116993, 0.915199, 0.00081995, 0, 0.131282, 0.90498, 0.000847654, 0, 0.146364, 0.894243, 0.000868929, 0, 0.162237, 0.882154, 0.000884278, 0, 0.178902, 0.869161, 0.000898108, 0, 0.196358, 0.854751, 0.000901254, 0, 0.21461, 0.839368, 0.00090679, 0, 0.23366, 0.822874, 0.000901541, 0, 0.253512, 0.805514, 0.000897297, 0, 0.274174, 0.78716, 0.000881856, 0, 0.29565, 0.769061, 0.000870032, 0, 0.31795, 0.751, 0.000851719, 0, 0.341081, 0.732614, 0.000830671, 0, 0.365053, 0.713171, 0.000806569, 0, 0.389874, 0.693472, 0.00078338, 0, 0.415553, 0.673528, 0.000756404, 0, 0.442098, 0.653397, 0.000726872, 0, 0.469512, 0.633781, 0.000700494, 0, 0.497794, 0.613877, 0.00067105, 0, 0.526935, 0.593506, 0.000640361, 0, 0.556908, 0.573667, 0.000613502, 0, 0.587657, 0.553932, 0.000583177, 0, 0.61906, 0.534345, 0.000554375, 0, 0.650794, 0.515042, 0.000527811, 0, 0.68254, 0.495674, 0.000499367, 0, 0.714286, 0.477132, 0.00047429, 0, 0.746032, 0.458609, 0.000447726, 0, 0.777778, 0.440354, 0.000424205, 0, 0.809524, 0.422765, 0.000399549, 0, 0.84127, 0.405472, 0.000378315, 0, 0.873016, 0.388482, 0.000355327, 0, 0.904762, 0.372191, 0.000336122, 0, 0.936508, 0.356099, 0.000315247, 0, 0.968254, 0.340737, 0.00029794, 0, 1, 1, 0.000143327, 0, 0, 1, 0.00014333, 0, 0, 1, 0.000143366, 0, 0, 0.999999, 0.000143524, 0, 0, 0.999996, 0.000143952, 0, 0, 0.999991, 0.000144862, 0, 0, 0.999981, 0.000146544, 0, 0, 0.999966, 0.000149391, 0, 0, 0.999941, 0.000153946, 0, 0, 0.999905, 0.000160971, 0, 0, 0.999852, 0.000171562, 0, 0, 0.99978, 0.00018729, 0, 0, 0.999681, 0.000210386, 0, 0.0000826239, 0.999546, 0.000243906, 0, 0.000664807, 0.999352, 0.000291739, 0, 0.00196192, 0.999027, 0.000357419, 0, 0.00405941, 0.997886, 0.000422349, 0, 0.00699664, 0.99419, 0.000385008, 0, 0.0107896, 0.99214, 0.000409775, 0, 0.0154415, 0.990274, 0.000456418, 0, 0.0209488, 0.988455, 0.000527008, 0, 0.0273037, 0.985804, 0.000597685, 0, 0.0344969, 0.98103, 0.000613124, 0, 0.0425183, 0.976674, 0.000668321, 0, 0.0513575, 0.972021, 0.000736985, 0, 0.0610046, 0.965274, 0.000773789, 0, 0.0714508, 0.958046, 0.000830852, 0, 0.0826877, 0.949333, 0.000875766, 0, 0.0947085, 0.939135, 0.000917088, 0, 0.107507, 0.927119, 0.000952244, 0, 0.121078, 0.91469, 0.000990626, 0, 0.135419, 0.903006, 0.00101304, 0, 0.150526, 0.892368, 0.00103834, 0, 0.166399, 0.880231, 0.00105002, 0, 0.183038, 0.867432, 0.00106331, 0, 0.200443, 0.853208, 0.00106783, 0, 0.218618, 0.837956, 0.00106458, 0, 0.237566, 0.821772, 0.00105945, 0, 0.257291, 0.804328, 0.00104685, 0, 0.2778, 0.786465, 0.00103178, 0, 0.2991, 0.768004, 0.00101077, 0, 0.321199, 0.74972, 0.000985504, 0, 0.344106, 0.731682, 0.000962893, 0, 0.36783, 0.712813, 0.000932146, 0, 0.392383, 0.693139, 0.00089871, 0, 0.417774, 0.673566, 0.000869678, 0, 0.444013, 0.653483, 0.000835525, 0, 0.471107, 0.633891, 0.000799853, 0, 0.49906, 0.614433, 0.000766838, 0, 0.527869, 0.594586, 0.000732227, 0, 0.557517, 0.574769, 0.000696442, 0, 0.587966, 0.555149, 0.000663935, 0, 0.61913, 0.535898, 0.000629826, 0, 0.650794, 0.516753, 0.000596486, 0, 0.68254, 0.497816, 0.000567078, 0, 0.714286, 0.479034, 0.000534399, 0, 0.746032, 0.460975, 0.000507013, 0, 0.777778, 0.442935, 0.000477421, 0, 0.809524, 0.425263, 0.000451101, 0, 0.84127, 0.408248, 0.000424964, 0, 0.873016, 0.391339, 0.00039993, 0, 0.904762, 0.37513, 0.000377619, 0, 0.936508, 0.359172, 0.000354418, 0, 0.968254, 0.343876, 0.000334823, 0, 1, 1, 0.000209042, 0, 0, 1, 0.000209045, 0, 0, 1, 0.000209093, 0, 0, 0.999999, 0.000209304, 0, 0, 0.999996, 0.000209871, 0, 0, 0.999991, 0.000211078, 0, 0, 0.999979, 0.000213304, 0, 0, 0.999963, 0.000217061, 0, 0, 0.999933, 0.000223042, 0, 0, 0.999894, 0.000232206, 0, 0, 0.999837, 0.000245901, 0, 0, 0.999756, 0.000266023, 0, 0.00000102927, 0.999648, 0.000295204, 0, 0.000233468, 0.999499, 0.000336958, 0, 0.00108237, 0.999283, 0.000395563, 0, 0.00268832, 0.998896, 0.000473785, 0, 0.00511138, 0.997006, 0.000520008, 0, 0.00837705, 0.993819, 0.000497261, 0, 0.0124928, 0.991632, 0.000523722, 0, 0.0174561, 0.989875, 0.000587258, 0, 0.0232596, 0.988109, 0.000676329, 0, 0.0298932, 0.985155, 0.000747701, 0, 0.0373453, 0.980479, 0.000768803, 0, 0.0456045, 0.976271, 0.000841054, 0, 0.0546593, 0.971347, 0.000911469, 0, 0.0644994, 0.964528, 0.000953057, 0, 0.0751152, 0.957632, 0.00102221, 0, 0.0864981, 0.948681, 0.00106122, 0, 0.0986407, 0.938716, 0.00111857, 0, 0.111537, 0.926629, 0.00114762, 0, 0.125182, 0.914025, 0.00118995, 0, 0.139571, 0.901026, 0.00121228, 0, 0.154703, 0.890358, 0.00123946, 0, 0.170576, 0.878283, 0.0012527, 0, 0.18719, 0.865459, 0.00125536, 0, 0.204547, 0.851407, 0.00126134, 0, 0.222648, 0.836276, 0.00124759, 0, 0.241498, 0.820436, 0.00124443, 0, 0.261101, 0.803253, 0.00122071, 0, 0.281465, 0.785562, 0.00120107, 0, 0.302595, 0.76718, 0.00117762, 0, 0.324501, 0.748551, 0.00114289, 0, 0.347192, 0.730564, 0.00110872, 0, 0.370679, 0.712253, 0.00107636, 0, 0.394973, 0.692867, 0.00103646, 0, 0.420085, 0.673695, 0.000996793, 0, 0.446027, 0.653912, 0.00095675, 0, 0.47281, 0.634129, 0.000916739, 0, 0.500441, 0.615004, 0.000874401, 0, 0.528921, 0.595587, 0.000833411, 0, 0.558244, 0.575965, 0.000794556, 0, 0.588384, 0.5566, 0.00075196, 0, 0.619281, 0.537428, 0.000716381, 0, 0.650795, 0.518623, 0.000676558, 0, 0.68254, 0.499964, 0.00064074, 0, 0.714286, 0.481356, 0.000605984, 0, 0.746032, 0.463279, 0.000570256, 0, 0.777778, 0.445673, 0.000540138, 0, 0.809524, 0.428032, 0.000507299, 0, 0.84127, 0.411112, 0.000479553, 0, 0.873016, 0.394444, 0.000450737, 0, 0.904762, 0.378247, 0.000424269, 0, 0.936508, 0.362415, 0.000399111, 0, 0.968254, 0.347103, 0.000375274, 0, 1, 1, 0.000300729, 0, 0, 1, 0.000300733, 0, 0, 1, 0.000300797, 0, 0, 0.999998, 0.000301072, 0, 0, 0.999996, 0.000301817, 0, 0, 0.999989, 0.000303398, 0, 0, 0.999977, 0.000306309, 0, 0, 0.999958, 0.000311209, 0, 0, 0.999927, 0.000318975, 0, 0, 0.999884, 0.000330804, 0, 0, 0.99982, 0.00034834, 0, 0, 0.999733, 0.000373854, 0, 0.0000326995, 0.999613, 0.000410424, 0, 0.000477174, 0.999447, 0.000462047, 0, 0.00161099, 0.999204, 0.000533322, 0, 0.00353153, 0.998725, 0.000624964, 0, 0.00627965, 0.995871, 0.000631786, 0, 0.0098693, 0.993194, 0.000632017, 0, 0.0143011, 0.991541, 0.00068923, 0, 0.019568, 0.989773, 0.000766892, 0, 0.0256593, 0.987647, 0.000863668, 0, 0.0325625, 0.984193, 0.000922089, 0, 0.0402647, 0.980016, 0.000970749, 0, 0.0487532, 0.975859, 0.00106027, 0, 0.058016, 0.970514, 0.00112239, 0, 0.0680419, 0.963625, 0.00117212, 0, 0.0788208, 0.956959, 0.00125211, 0, 0.0903439, 0.947956, 0.00129411, 0, 0.102604, 0.93809, 0.00135879, 0, 0.115594, 0.92659, 0.00139309, 0, 0.129309, 0.913829, 0.00143253, 0, 0.143745, 0.90005, 0.00145809, 0, 0.158901, 0.888129, 0.0014748, 0, 0.174774, 0.87607, 0.00148756, 0, 0.191365, 0.863461, 0.00148714, 0, 0.208674, 0.849594, 0.00148892, 0, 0.226705, 0.834531, 0.00146496, 0, 0.245461, 0.81903, 0.0014579, 0, 0.264947, 0.802122, 0.00143039, 0, 0.28517, 0.78445, 0.00139717, 0, 0.306137, 0.766434, 0.00136312, 0, 0.327857, 0.747816, 0.00132597, 0, 0.350341, 0.729519, 0.00128323, 0, 0.373598, 0.711454, 0.00123803, 0, 0.397642, 0.692699, 0.00119097, 0, 0.422485, 0.673723, 0.00114565, 0, 0.448139, 0.654386, 0.00109552, 0, 0.474619, 0.634673, 0.00104553, 0, 0.501933, 0.615554, 0.00099985, 0, 0.530089, 0.596462, 0.000948207, 0, 0.559087, 0.577385, 0.000902299, 0, 0.588913, 0.558257, 0.000856448, 0, 0.619525, 0.5392, 0.000810395, 0, 0.650826, 0.520543, 0.000768558, 0, 0.68254, 0.502206, 0.0007239, 0, 0.714286, 0.48402, 0.000685794, 0, 0.746032, 0.465779, 0.00064471, 0, 0.777778, 0.448455, 0.000609583, 0, 0.809524, 0.431091, 0.00057227, 0, 0.84127, 0.414147, 0.00054042, 0, 0.873016, 0.39765, 0.000506545, 0, 0.904762, 0.381576, 0.000477635, 0, 0.936508, 0.365881, 0.000448446, 0, 0.968254, 0.350582, 0.000421424, 0, 1, 1, 0.000427144, 0, 0, 1, 0.000427151, 0, 0, 1, 0.000427232, 0, 0, 0.999998, 0.00042759, 0, 0, 0.999995, 0.000428555, 0, 0, 0.999988, 0.000430603, 0, 0, 0.999976, 0.000434368, 0, 0, 0.999952, 0.000440688, 0, 0, 0.999919, 0.000450667, 0, 0, 0.999871, 0.00046578, 0, 0, 0.999801, 0.000488024, 0, 0, 0.999704, 0.000520092, 0, 0.000129791, 0.999572, 0.000565553, 0, 0.000821056, 0.999389, 0.000628906, 0, 0.00225241, 0.999114, 0.000714911, 0, 0.00449109, 0.998488, 0.000819218, 0, 0.00756249, 0.995234, 0.00080415, 0, 0.0114716, 0.993021, 0.000830181, 0, 0.0162131, 0.991407, 0.000902645, 0, 0.021776, 0.989625, 0.000996934, 0, 0.0281471, 0.987064, 0.00109707, 0, 0.0353118, 0.983265, 0.00114353, 0, 0.0432562, 0.979535, 0.0012272, 0, 0.0519665, 0.975224, 0.00132642, 0, 0.0614298, 0.969574, 0.00138092, 0, 0.0716348, 0.963021, 0.00145896, 0, 0.0825709, 0.956046, 0.00152834, 0, 0.094229, 0.947136, 0.00158217, 0, 0.106602, 0.937313, 0.0016347, 0, 0.119682, 0.926073, 0.00168383, 0, 0.133465, 0.913121, 0.00171627, 0, 0.147947, 0.899165, 0.00174229, 0, 0.163125, 0.885891, 0.00176137, 0, 0.178998, 0.873783, 0.00176406, 0, 0.195566, 0.861331, 0.00176156, 0, 0.21283, 0.847569, 0.00175346, 0, 0.230793, 0.832785, 0.00172753, 0, 0.249459, 0.817442, 0.00170204, 0, 0.268832, 0.800613, 0.00166576, 0, 0.28892, 0.783597, 0.00162909, 0, 0.30973, 0.76571, 0.0015826, 0, 0.331271, 0.747021, 0.00153106, 0, 0.353554, 0.728593, 0.00148036, 0, 0.37659, 0.710661, 0.00142808, 0, 0.400391, 0.692426, 0.00136906, 0, 0.424973, 0.673623, 0.00131066, 0, 0.450347, 0.65494, 0.00125569, 0, 0.476531, 0.635448, 0.00119517, 0, 0.503535, 0.616221, 0.00113828, 0, 0.531372, 0.597531, 0.0010816, 0, 0.560047, 0.578795, 0.00102673, 0, 0.589554, 0.559892, 0.000970985, 0, 0.619869, 0.541307, 0.000919773, 0, 0.650923, 0.522608, 0.000868479, 0, 0.68254, 0.504484, 0.00082137, 0, 0.714286, 0.486603, 0.000772916, 0, 0.746032, 0.468802, 0.000730353, 0, 0.777778, 0.451172, 0.000684955, 0, 0.809524, 0.434348, 0.000647565, 0, 0.84127, 0.417445, 0.000605863, 0, 0.873016, 0.401077, 0.000571885, 0, 0.904762, 0.385039, 0.000536034, 0, 0.936508, 0.369483, 0.000504227, 0, 0.968254, 0.354272, 0.000473165, 0, 1, 1, 0.000599525, 0, 0, 1, 0.000599533, 0, 0, 1, 0.000599639, 0, 0, 0.999998, 0.000600097, 0, 0, 0.999994, 0.000601336, 0, 0, 0.999987, 0.000603958, 0, 0, 0.999972, 0.000608775, 0, 0, 0.999949, 0.000616842, 0, 0, 0.999912, 0.000629534, 0, 0, 0.999857, 0.000648658, 0, 0, 0.999781, 0.000676615, 0, 0.00000538873, 0.999674, 0.000716574, 0, 0.000308602, 0.999528, 0.000772641, 0, 0.00127003, 0.999326, 0.000849806, 0, 0.00300783, 0.999009, 0.000952682, 0, 0.00556637, 0.998112, 0.00106394, 0, 0.00895889, 0.994496, 0.00102228, 0, 0.0131827, 0.992806, 0.00108586, 0, 0.0182277, 0.991211, 0.0011759, 0, 0.0240795, 0.989415, 0.00128955, 0, 0.030723, 0.986499, 0.00139038, 0, 0.0381418, 0.982679, 0.00144539, 0, 0.046321, 0.978839, 0.00153954, 0, 0.0552459, 0.974295, 0.00164417, 0, 0.0649034, 0.968784, 0.00171517, 0, 0.0752814, 0.962324, 0.00180282, 0, 0.0863693, 0.954956, 0.00186387, 0, 0.0981578, 0.94624, 0.00193817, 0, 0.110639, 0.936517, 0.00198156, 0, 0.123806, 0.925186, 0.00203042, 0, 0.137655, 0.91252, 0.0020664, 0, 0.15218, 0.898441, 0.00207822, 0, 0.16738, 0.884394, 0.0020992, 0, 0.183253, 0.871273, 0.00208748, 0, 0.199799, 0.859057, 0.00208686, 0, 0.21702, 0.845243, 0.00205519, 0, 0.234918, 0.830723, 0.00202868, 0, 0.253496, 0.815801, 0.00199501, 0, 0.272761, 0.79914, 0.00194193, 0, 0.292719, 0.782372, 0.00188824, 0, 0.313377, 0.76482, 0.00183695, 0, 0.334745, 0.746586, 0.00177418, 0, 0.356833, 0.7281, 0.00170628, 0, 0.379654, 0.709842, 0.00164063, 0, 0.403221, 0.692019, 0.00157355, 0, 0.427548, 0.67364, 0.00150262, 0, 0.452651, 0.655277, 0.00143473, 0, 0.478545, 0.636438, 0.00136371, 0, 0.505246, 0.617364, 0.00129911, 0, 0.532768, 0.598603, 0.00123014, 0, 0.561122, 0.580195, 0.00116587, 0, 0.590309, 0.561786, 0.00110398, 0, 0.620318, 0.543377, 0.00104148, 0, 0.651102, 0.525093, 0.000983984, 0, 0.682545, 0.506791, 0.00092667, 0, 0.714286, 0.489291, 0.000874326, 0, 0.746032, 0.471811, 0.000821734, 0, 0.777778, 0.454435, 0.000774698, 0, 0.809524, 0.437493, 0.000727302, 0, 0.84127, 0.420977, 0.000684039, 0, 0.873016, 0.404729, 0.00064373, 0, 0.904762, 0.388756, 0.00060285, 0, 0.936508, 0.373344, 0.00056765, 0, 0.968254, 0.358191, 0.000531929, 0, 1, 1, 0.000832169, 0, 0, 1, 0.000832178, 0, 0, 1, 0.00083231, 0, 0, 0.999998, 0.000832893, 0, 0, 0.999995, 0.000834465, 0, 0, 0.999985, 0.000837791, 0, 0, 0.999969, 0.000843893, 0, 0, 0.999944, 0.000854086, 0, 0, 0.999903, 0.000870071, 0, 0, 0.999843, 0.000894042, 0, 0, 0.999759, 0.000928865, 0, 0.0000531805, 0.999643, 0.000978242, 0, 0.000579365, 0.99948, 0.00104684, 0, 0.00182774, 0.999255, 0.00114012, 0, 0.00387804, 0.998885, 0.00126188, 0, 0.00675709, 0.997405, 0.00135888, 0, 0.010468, 0.99424, 0.00133626, 0, 0.0150018, 0.992458, 0.00140905, 0, 0.0203443, 0.990929, 0.00152305, 0, 0.0264786, 0.989116, 0.00165882, 0, 0.0333875, 0.985624, 0.00174128, 0, 0.0410536, 0.982003, 0.00182108, 0, 0.0494609, 0.978336, 0.00194498, 0, 0.0585941, 0.973184, 0.00202708, 0, 0.0684396, 0.9678, 0.00212166, 0, 0.0789851, 0.961348, 0.00221366, 0, 0.0902199, 0.953841, 0.00228219, 0, 0.102134, 0.94534, 0.00235662, 0, 0.114721, 0.935552, 0.00240572, 0, 0.127972, 0.924064, 0.00244405, 0, 0.141884, 0.911827, 0.00247557, 0, 0.156451, 0.897731, 0.00248374, 0, 0.171672, 0.883409, 0.00249863, 0, 0.187545, 0.868625, 0.00246688, 0, 0.20407, 0.856529, 0.00246523, 0, 0.221249, 0.842999, 0.00242368, 0, 0.239083, 0.828505, 0.00237354, 0, 0.257578, 0.813825, 0.00232588, 0, 0.276738, 0.797813, 0.00226731, 0, 0.296569, 0.781097, 0.00219704, 0, 0.31708, 0.764038, 0.00212394, 0, 0.338281, 0.746067, 0.00204786, 0, 0.360181, 0.727687, 0.00196728, 0, 0.382794, 0.709571, 0.00188779, 0, 0.406133, 0.691503, 0.00180532, 0, 0.430213, 0.673673, 0.00171849, 0, 0.45505, 0.655732, 0.00164147, 0, 0.480662, 0.637399, 0.00155858, 0, 0.507065, 0.618616, 0.00147641, 0, 0.534278, 0.60005, 0.00140125, 0, 0.562313, 0.581713, 0.00132441, 0, 0.59118, 0.563546, 0.00125014, 0, 0.620875, 0.545605, 0.00118249, 0, 0.651373, 0.527559, 0.0011116, 0, 0.682593, 0.509764, 0.00104979, 0, 0.714286, 0.49193, 0.000985977, 0, 0.746032, 0.475011, 0.000928592, 0, 0.777778, 0.457878, 0.000873466, 0, 0.809524, 0.440979, 0.000819585, 0, 0.84127, 0.424613, 0.000772365, 0, 0.873016, 0.408549, 0.000722195, 0, 0.904762, 0.392771, 0.000680014, 0, 0.936508, 0.377317, 0.000636797, 0, 0.968254, 0.362352, 0.000598318, 0, 1, 1, 0.00114313, 0, 0, 1, 0.00114314, 0, 0, 0.999999, 0.00114331, 0, 0, 0.999998, 0.00114404, 0, 0, 0.999994, 0.00114601, 0, 0, 0.999984, 0.00115019, 0, 0, 0.999967, 0.00115784, 0, 0, 0.999937, 0.0011706, 0, 0, 0.999894, 0.00119054, 0, 0, 0.999828, 0.00122031, 0, 0, 0.999735, 0.00126331, 0, 0.000169263, 0.999606, 0.00132382, 0, 0.000949167, 0.999426, 0.0014071, 0, 0.00249668, 0.999173, 0.00151895, 0, 0.00486392, 0.99873, 0.00166102, 0, 0.00806323, 0.996243, 0.0017023, 0, 0.0120895, 0.993779, 0.00172782, 0, 0.0169288, 0.9919, 0.0018108, 0, 0.0225633, 0.990524, 0.00196028, 0, 0.028974, 0.98868, 0.00212014, 0, 0.036142, 0.984663, 0.00217598, 0, 0.044049, 0.981457, 0.00230563, 0, 0.0526781, 0.977608, 0.00243966, 0, 0.0620137, 0.972215, 0.00251336, 0, 0.0720418, 0.966798, 0.0026285, 0, 0.0827499, 0.960241, 0.00271409, 0, 0.0941271, 0.952489, 0.00278381, 0, 0.106164, 0.944127, 0.00285399, 0, 0.118852, 0.934282, 0.00290994, 0, 0.132185, 0.923271, 0.00294558, 0, 0.146157, 0.910803, 0.00296269, 0, 0.160766, 0.896705, 0.00296803, 0, 0.176007, 0.88238, 0.00296637, 0, 0.19188, 0.867116, 0.00293163, 0, 0.208385, 0.853636, 0.00289418, 0, 0.225523, 0.840469, 0.00284663, 0, 0.243296, 0.82639, 0.00278594, 0, 0.261709, 0.811759, 0.00271618, 0, 0.280767, 0.796113, 0.00263187, 0, 0.300476, 0.779518, 0.00254589, 0, 0.320845, 0.763142, 0.00246003, 0, 0.341883, 0.745464, 0.00236529, 0, 0.363601, 0.727491, 0.00226536, 0, 0.386011, 0.709414, 0.00216375, 0, 0.409128, 0.691396, 0.00207127, 0, 0.432967, 0.67368, 0.00197106, 0, 0.457545, 0.656049, 0.00187022, 0, 0.482881, 0.638188, 0.00177605, 0, 0.508992, 0.620177, 0.00168482, 0, 0.535899, 0.601506, 0.00158909, 0, 0.563619, 0.58362, 0.00150583, 0, 0.592165, 0.565496, 0.00141791, 0, 0.621544, 0.54789, 0.00133693, 0, 0.651743, 0.530323, 0.00126038, 0, 0.682709, 0.512795, 0.00118556, 0, 0.714286, 0.495199, 0.00111527, 0, 0.746032, 0.478101, 0.0010489, 0, 0.777778, 0.461511, 0.000984264, 0, 0.809524, 0.444879, 0.00092591, 0, 0.84127, 0.428424, 0.000866582, 0, 0.873016, 0.412495, 0.000814463, 0, 0.904762, 0.396975, 0.000764498, 0, 0.936508, 0.381614, 0.000715967, 0, 0.968254, 0.366732, 0.000672483, 0, 1, 1, 0.00155501, 0, 0, 1, 0.00155503, 0, 0, 1, 0.00155524, 0, 0, 0.999998, 0.00155615, 0, 0, 0.999994, 0.0015586, 0, 0, 0.999983, 0.00156379, 0, 0, 0.999963, 0.0015733, 0, 0, 0.999932, 0.00158911, 0, 0, 0.999882, 0.00161376, 0, 0, 0.99981, 0.00165041, 0, 0.0000100875, 0.999708, 0.00170304, 0, 0.000367658, 0.999565, 0.00177658, 0, 0.0014234, 0.999368, 0.00187688, 0, 0.00327939, 0.999081, 0.00200989, 0, 0.00596629, 0.99852, 0.00217177, 0, 0.0094852, 0.99549, 0.0021745, 0, 0.013824, 0.993252, 0.00222357, 0, 0.0189642, 0.991727, 0.00235022, 0, 0.0248856, 0.989951, 0.00250561, 0, 0.0315669, 0.988029, 0.00268829, 0, 0.0389882, 0.984029, 0.0027496, 0, 0.0471302, 0.980683, 0.00289793, 0, 0.0559754, 0.976554, 0.00303315, 0, 0.0655081, 0.97139, 0.00313257, 0, 0.0757138, 0.965544, 0.00323656, 0, 0.08658, 0.95912, 0.00333432, 0, 0.0980954, 0.951183, 0.0034039, 0, 0.110251, 0.942974, 0.00347515, 0, 0.123038, 0.932642, 0.00350381, 0, 0.13645, 0.922158, 0.00354519, 0, 0.150482, 0.909404, 0.00353851, 0, 0.165129, 0.896071, 0.0035435, 0, 0.18039, 0.881206, 0.00349936, 0, 0.196263, 0.866077, 0.00347256, 0, 0.212748, 0.85093, 0.003415, 0, 0.229847, 0.837703, 0.00333367, 0, 0.247561, 0.823878, 0.003249, 0, 0.265895, 0.809449, 0.00316347, 0, 0.284854, 0.794379, 0.00306351, 0, 0.304445, 0.778138, 0.0029499, 0, 0.324675, 0.761997, 0.00284099, 0, 0.345555, 0.744938, 0.00272104, 0, 0.367095, 0.727212, 0.00260715, 0, 0.389309, 0.709549, 0.00248855, 0, 0.41221, 0.691704, 0.00236783, 0, 0.435814, 0.673689, 0.00225178, 0, 0.460138, 0.656453, 0.00213765, 0, 0.485203, 0.639128, 0.00202178, 0, 0.511028, 0.621512, 0.00191443, 0, 0.537634, 0.603598, 0.00180977, 0, 0.565041, 0.58559, 0.00170456, 0, 0.593268, 0.567852, 0.00160927, 0, 0.622327, 0.5503, 0.00151395, 0, 0.652217, 0.533033, 0.00142499, 0, 0.682907, 0.515942, 0.00133955, 0, 0.714296, 0.498814, 0.0012602, 0, 0.746032, 0.481595, 0.00118188, 0, 0.777778, 0.465117, 0.00111171, 0, 0.809524, 0.448865, 0.00104091, 0, 0.84127, 0.432711, 0.000976618, 0, 0.873016, 0.416822, 0.00091859, 0, 0.904762, 0.401272, 0.000857704, 0, 0.936508, 0.386226, 0.000807172, 0, 0.968254, 0.371321, 0.00075464, 0, 1, 1, 0.00209596, 0, 0, 1, 0.00209598, 0, 0, 1, 0.00209624, 0, 0, 0.999997, 0.00209736, 0, 0, 0.999991, 0.00210039, 0, 0, 0.999979, 0.00210678, 0, 0, 0.999959, 0.00211847, 0, 0, 0.999925, 0.0021379, 0, 0, 0.99987, 0.00216809, 0, 0, 0.999791, 0.00221281, 0, 0.0000681487, 0.999677, 0.00227669, 0, 0.000658161, 0.999521, 0.00236533, 0, 0.00200635, 0.999301, 0.00248514, 0, 0.0041779, 0.998977, 0.00264185, 0, 0.00718648, 0.998191, 0.00281695, 0, 0.0110239, 0.994801, 0.00278518, 0, 0.015672, 0.993091, 0.00288774, 0, 0.0211091, 0.991571, 0.00303931, 0, 0.0273123, 0.9897, 0.00321643, 0, 0.034259, 0.987023, 0.00337332, 0, 0.0419282, 0.983289, 0.00346146, 0, 0.0502998, 0.979892, 0.00363704, 0, 0.0593562, 0.975111, 0.00373601, 0, 0.069081, 0.970351, 0.0038842, 0, 0.0794598, 0.964131, 0.00397053, 0, 0.0904798, 0.957747, 0.00408078, 0, 0.10213, 0.949536, 0.00413533, 0, 0.1144, 0.941372, 0.00420305, 0, 0.127284, 0.931049, 0.00422815, 0, 0.140772, 0.920647, 0.00425048, 0, 0.154862, 0.908033, 0.0042281, 0, 0.169548, 0.895028, 0.00422026, 0, 0.184828, 0.879968, 0.00415042, 0, 0.200701, 0.864875, 0.00408821, 0, 0.217167, 0.84918, 0.00400909, 0, 0.234227, 0.834934, 0.00391178, 0, 0.251884, 0.821397, 0.00380066, 0, 0.270141, 0.807135, 0.00367974, 0, 0.289004, 0.792363, 0.00355172, 0, 0.308479, 0.776661, 0.003411, 0, 0.328575, 0.760705, 0.00328123, 0, 0.349301, 0.744408, 0.00314003, 0, 0.370668, 0.726994, 0.0029906, 0, 0.392689, 0.709598, 0.00285034, 0, 0.415379, 0.692112, 0.00271179, 0, 0.438754, 0.674435, 0.00257185, 0, 0.46283, 0.65676, 0.00243425, 0, 0.48763, 0.639982, 0.00230351, 0, 0.513173, 0.622983, 0.0021777, 0, 0.539482, 0.605471, 0.00204991, 0, 0.566579, 0.58796, 0.00193759, 0, 0.594488, 0.570463, 0.00181976, 0, 0.623226, 0.553058, 0.00171497, 0, 0.6528, 0.535894, 0.00161109, 0, 0.683198, 0.519089, 0.00151394, 0, 0.714354, 0.502454, 0.00142122, 0, 0.746032, 0.485681, 0.00133488, 0, 0.777778, 0.468935, 0.00124975, 0, 0.809524, 0.452951, 0.00117309, 0, 0.84127, 0.437139, 0.00110155, 0, 0.873016, 0.421446, 0.00103124, 0, 0.904762, 0.405951, 0.000966387, 0, 0.936508, 0.391003, 0.000908119, 0, 0.968254, 0.376198, 0.000848057, 0, 1, 1, 0.00280076, 0, 0, 1, 0.00280078, 0, 0, 0.999999, 0.00280109, 0, 0, 0.999997, 0.00280246, 0, 0, 0.999992, 0.00280616, 0, 0, 0.999979, 0.00281396, 0, 0, 0.999956, 0.00282822, 0, 0, 0.999916, 0.00285186, 0, 0, 0.999857, 0.0028885, 0, 0, 0.999768, 0.00294259, 0, 0.000196026, 0.999645, 0.00301946, 0, 0.00104842, 0.99947, 0.00312541, 0, 0.00270199, 0.999229, 0.00326733, 0, 0.00519449, 0.998852, 0.00344992, 0, 0.00852602, 0.997558, 0.00361052, 0, 0.0126804, 0.994417, 0.0035898, 0, 0.017635, 0.992824, 0.00372393, 0, 0.023365, 0.991344, 0.00390695, 0, 0.0298456, 0.989337, 0.00410392, 0, 0.0370529, 0.985811, 0.00420987, 0, 0.0449651, 0.982772, 0.00437488, 0, 0.0535615, 0.979001, 0.00455069, 0, 0.0628243, 0.974102, 0.00464462, 0, 0.0727368, 0.969197, 0.00480577, 0, 0.0832844, 0.962759, 0.00487818, 0, 0.0944545, 0.956207, 0.00498176, 0, 0.106236, 0.947909, 0.00503392, 0, 0.118619, 0.939596, 0.00507474, 0, 0.131595, 0.929642, 0.00509798, 0, 0.145159, 0.918807, 0.00508476, 0, 0.159305, 0.906921, 0.00505634, 0, 0.174028, 0.893312, 0.00498845, 0, 0.189327, 0.878933, 0.0049133, 0, 0.2052, 0.863986, 0.0048259, 0, 0.221647, 0.847936, 0.00470848, 0, 0.23867, 0.832253, 0.00456889, 0, 0.25627, 0.818619, 0.00442726, 0, 0.274453, 0.804788, 0.00427677, 0, 0.293222, 0.790241, 0.00411906, 0, 0.312585, 0.775162, 0.00394833, 0, 0.33255, 0.759463, 0.00377366, 0, 0.353126, 0.743598, 0.00361026, 0, 0.374324, 0.72697, 0.00343627, 0, 0.396158, 0.709646, 0.00326422, 0, 0.418641, 0.69277, 0.00309717, 0, 0.44179, 0.675371, 0.0029356, 0, 0.465624, 0.657863, 0.00277712, 0, 0.490163, 0.640772, 0.00261738, 0, 0.515429, 0.624441, 0.0024737, 0, 0.541445, 0.607497, 0.00233125, 0, 0.568236, 0.590438, 0.00218994, 0, 0.595828, 0.573224, 0.0020664, 0, 0.624242, 0.556168, 0.00193526, 0, 0.653496, 0.539232, 0.00182463, 0, 0.683588, 0.522352, 0.00170735, 0, 0.714482, 0.506172, 0.00160555, 0, 0.746032, 0.489842, 0.00150451, 0, 0.777778, 0.473463, 0.00140938, 0, 0.809524, 0.457266, 0.00132568, 0, 0.84127, 0.441609, 0.0012376, 0, 0.873016, 0.426348, 0.00116265, 0, 0.904762, 0.411002, 0.00108935, 0, 0.936508, 0.396045, 0.00101946, 0, 0.968254, 0.381448, 0.000955665, 0, 1, 1, 0.0037121, 0, 0, 1, 0.00371213, 0, 0, 1, 0.00371251, 0, 0, 0.999997, 0.00371417, 0, 0, 0.99999, 0.00371863, 0, 0, 0.999977, 0.00372807, 0, 0, 0.99995, 0.00374529, 0, 0, 0.999908, 0.0037738, 0, 0, 0.999843, 0.00381789, 0, 0.0000123596, 0.999745, 0.00388273, 0, 0.000407442, 0.999608, 0.00397443, 0, 0.0015447, 0.999415, 0.00409998, 0, 0.00351385, 0.999143, 0.00426662, 0, 0.0063316, 0.9987, 0.00447625, 0, 0.00998679, 0.996363, 0.00455323, 0, 0.0144569, 0.994021, 0.00461052, 0, 0.0197151, 0.992372, 0.00476359, 0, 0.0257344, 0.991007, 0.00499101, 0, 0.0324882, 0.988767, 0.0051972, 0, 0.0399517, 0.984872, 0.00528407, 0, 0.0481022, 0.982004, 0.00548926, 0, 0.0569191, 0.977714, 0.00564385, 0, 0.0663839, 0.973076, 0.0057693, 0, 0.0764801, 0.967565, 0.0058924, 0, 0.0871928, 0.961384, 0.00599629, 0, 0.0985095, 0.954435, 0.00605998, 0, 0.110419, 0.946303, 0.0061133, 0, 0.122912, 0.937662, 0.00612028, 0, 0.13598, 0.927867, 0.00612209, 0, 0.149617, 0.916475, 0.00604813, 0, 0.163817, 0.90541, 0.00603088, 0, 0.178577, 0.891591, 0.00592218, 0, 0.193894, 0.877573, 0.00578854, 0, 0.209767, 0.862511, 0.00566648, 0, 0.226196, 0.846861, 0.00551481, 0, 0.243182, 0.83068, 0.00533754, 0, 0.260728, 0.815725, 0.00515487, 0, 0.278837, 0.802321, 0.0049655, 0, 0.297515, 0.787826, 0.00475421, 0, 0.316768, 0.773454, 0.00456002, 0, 0.336605, 0.758224, 0.00434727, 0, 0.357034, 0.74265, 0.00414444, 0, 0.378067, 0.726729, 0.00393738, 0, 0.399717, 0.710155, 0.00373575, 0, 0.421998, 0.693312, 0.00353736, 0, 0.444928, 0.67653, 0.00334368, 0, 0.468523, 0.659444, 0.00315981, 0, 0.492806, 0.642051, 0.00297809, 0, 0.517798, 0.625758, 0.00280592, 0, 0.543525, 0.609615, 0.00264254, 0, 0.570012, 0.592919, 0.00248459, 0, 0.597288, 0.576298, 0.00233327, 0, 0.625379, 0.559489, 0.00219519, 0, 0.654307, 0.542891, 0.00205441, 0, 0.684084, 0.526255, 0.00193385, 0, 0.714693, 0.509853, 0.00180745, 0, 0.746044, 0.494131, 0.00169817, 0, 0.777778, 0.478114, 0.0015913, 0, 0.809524, 0.462274, 0.00148981, 0, 0.84127, 0.446412, 0.00139537, 0, 0.873016, 0.431274, 0.00130984, 0, 0.904762, 0.41635, 0.00122403, 0, 0.936508, 0.401476, 0.00114809, 0, 0.968254, 0.386993, 0.00107563, 0, 1, 1, 0.00488216, 0, 0, 1, 0.0048822, 0, 0, 1, 0.00488265, 0, 0, 0.999997, 0.00488463, 0, 0, 0.999988, 0.00488999, 0, 0, 0.999974, 0.00490129, 0, 0, 0.999946, 0.00492191, 0, 0, 0.999897, 0.00495598, 0, 0, 0.999825, 0.00500855, 0, 0.0000744791, 0.999718, 0.00508559, 0, 0.000712744, 0.999565, 0.005194, 0, 0.00215249, 0.999352, 0.00534147, 0, 0.00444576, 0.999046, 0.00553523, 0, 0.00759218, 0.998492, 0.00577016, 0, 0.0115714, 0.995564, 0.00578487, 0, 0.0163557, 0.993339, 0.00586414, 0, 0.021915, 0.991834, 0.00606002, 0, 0.0282201, 0.990496, 0.00633312, 0, 0.0352433, 0.987826, 0.00651941, 0, 0.042959, 0.98383, 0.00660842, 0, 0.0513439, 0.98109, 0.00685523, 0, 0.0603772, 0.976131, 0.00695778, 0, 0.0700402, 0.971922, 0.00714236, 0, 0.0803163, 0.965901, 0.00721437, 0, 0.0911908, 0.959606, 0.00732017, 0, 0.102651, 0.952504, 0.00735788, 0, 0.114686, 0.944365, 0.00738493, 0, 0.127286, 0.935652, 0.00737969, 0, 0.140443, 0.925813, 0.00733612, 0, 0.154151, 0.914397, 0.00723094, 0, 0.168405, 0.903257, 0.00714002, 0, 0.183201, 0.890015, 0.00700149, 0, 0.198536, 0.876014, 0.00682813, 0, 0.214409, 0.861436, 0.00665567, 0, 0.23082, 0.845752, 0.00644526, 0, 0.24777, 0.829169, 0.00621635, 0, 0.265263, 0.813435, 0.00597789, 0, 0.283301, 0.799701, 0.00575694, 0, 0.301889, 0.785726, 0.00549866, 0, 0.321035, 0.77152, 0.0052503, 0, 0.340746, 0.75683, 0.00499619, 0, 0.361032, 0.741951, 0.0047543, 0, 0.381904, 0.726367, 0.0045084, 0, 0.403374, 0.710537, 0.00426784, 0, 0.425457, 0.693965, 0.00403487, 0, 0.448169, 0.677724, 0.0038075, 0, 0.47153, 0.66117, 0.00359431, 0, 0.495561, 0.644274, 0.00338354, 0, 0.520284, 0.627449, 0.00318163, 0, 0.545725, 0.611645, 0.00299672, 0, 0.571911, 0.595614, 0.00281016, 0, 0.598873, 0.579426, 0.00264252, 0, 0.62664, 0.563016, 0.00247509, 0, 0.655239, 0.546728, 0.00232647, 0, 0.684692, 0.530539, 0.00217803, 0, 0.714999, 0.514164, 0.00204216, 0, 0.746106, 0.498344, 0.00191403, 0, 0.777778, 0.482957, 0.00179203, 0, 0.809524, 0.467336, 0.00167695, 0, 0.84127, 0.451994, 0.00157567, 0, 0.873016, 0.436514, 0.00147113, 0, 0.904762, 0.42178, 0.00138034, 0, 0.936508, 0.407271, 0.00129219, 0, 0.968254, 0.392822, 0.0012098, 0, 1, 1, 0.00637427, 0, 0, 1, 0.00637431, 0, 0, 0.999999, 0.00637485, 0, 0, 0.999996, 0.00637721, 0, 0, 0.999987, 0.00638357, 0, 0, 0.999971, 0.006397, 0, 0, 0.999939, 0.00642142, 0, 0, 0.999888, 0.00646177, 0, 0, 0.999807, 0.00652387, 0, 0.000207916, 0.999689, 0.00661454, 0, 0.00112051, 0.99952, 0.00674155, 0, 0.00287719, 0.999283, 0.00691313, 0, 0.00550145, 0.998936, 0.00713598, 0, 0.00897928, 0.998165, 0.00738501, 0, 0.0132829, 0.994847, 0.00734388, 0, 0.01838, 0.993182, 0.00749991, 0, 0.0242381, 0.991665, 0.0077246, 0, 0.030826, 0.989708, 0.00797579, 0, 0.0381152, 0.986663, 0.00813011, 0, 0.0460794, 0.983288, 0.00830365, 0, 0.0546951, 0.980104, 0.00853496, 0, 0.0639411, 0.974855, 0.00861045, 0, 0.0737988, 0.97045, 0.00879133, 0, 0.0842516, 0.964509, 0.00886377, 0, 0.0952848, 0.957594, 0.00890346, 0, 0.106886, 0.950546, 0.00893289, 0, 0.119044, 0.942225, 0.00890074, 0, 0.131749, 0.933365, 0.00886826, 0, 0.144994, 0.923202, 0.0087316, 0, 0.158772, 0.912605, 0.00863082, 0, 0.173078, 0.901099, 0.00847403, 0, 0.187908, 0.888177, 0.00825838, 0, 0.203261, 0.873955, 0.00801834, 0, 0.219134, 0.860091, 0.00779026, 0, 0.235527, 0.84434, 0.00752478, 0, 0.252443, 0.828517, 0.00724074, 0, 0.269883, 0.81239, 0.00693769, 0, 0.287851, 0.79721, 0.00664817, 0, 0.306352, 0.783489, 0.00634763, 0, 0.325393, 0.769514, 0.00604221, 0, 0.344981, 0.755419, 0.00573568, 0, 0.365126, 0.741083, 0.00544359, 0, 0.385839, 0.726059, 0.00515515, 0, 0.407132, 0.710809, 0.00487139, 0, 0.42902, 0.695052, 0.00459846, 0, 0.45152, 0.678886, 0.00433412, 0, 0.474651, 0.663042, 0.00407981, 0, 0.498433, 0.646634, 0.00384264, 0, 0.52289, 0.630117, 0.00360897, 0, 0.548048, 0.613804, 0.00338863, 0, 0.573936, 0.598338, 0.00318486, 0, 0.600584, 0.582687, 0.00298377, 0, 0.628027, 0.566809, 0.00280082, 0, 0.656295, 0.550817, 0.00262255, 0, 0.685417, 0.534937, 0.00245835, 0, 0.715406, 0.519151, 0.00230574, 0, 0.74624, 0.503118, 0.0021549, 0, 0.777778, 0.487723, 0.00202008, 0, 0.809524, 0.472725, 0.00189355, 0, 0.84127, 0.457599, 0.00177108, 0, 0.873016, 0.442558, 0.00165843, 0, 0.904762, 0.427624, 0.00155494, 0, 0.936508, 0.413171, 0.00145273, 0, 0.968254, 0.399122, 0.00136454, 0, 1, 1, 0.00826496, 0, 0, 1, 0.00826499, 0, 0, 1, 0.00826564, 0, 0, 0.999996, 0.00826842, 0, 0, 0.999987, 0.00827589, 0, 0, 0.999967, 0.00829167, 0, 0, 0.999933, 0.00832037, 0, 0, 0.999876, 0.00836768, 0, 0.0000109338, 0.999786, 0.00844031, 0, 0.000427145, 0.999655, 0.00854603, 0, 0.0016384, 0.999468, 0.00869337, 0, 0.00372392, 0.999203, 0.008891, 0, 0.00668513, 0.998803, 0.00914387, 0, 0.0104968, 0.99748, 0.00935838, 0, 0.015125, 0.994446, 0.00933309, 0, 0.0205338, 0.99292, 0.00953084, 0, 0.0266884, 0.991414, 0.0097893, 0, 0.0335565, 0.989049, 0.0100228, 0, 0.0411086, 0.98582, 0.0101664, 0, 0.0493181, 0.982441, 0.0103582, 0, 0.0581613, 0.978595, 0.0105292, 0, 0.0676169, 0.973495, 0.0106274, 0, 0.0776661, 0.968405, 0.0107261, 0, 0.0882926, 0.962717, 0.0108234, 0, 0.0994817, 0.955478, 0.0108102, 0, 0.111221, 0.948275, 0.0107914, 0, 0.123499, 0.940006, 0.0107161, 0, 0.136308, 0.930831, 0.0106309, 0, 0.149639, 0.920648, 0.0104083, 0, 0.163485, 0.910205, 0.0102312, 0, 0.177843, 0.898445, 0.0100051, 0, 0.192707, 0.885986, 0.00971928, 0, 0.208077, 0.872204, 0.00940747, 0, 0.22395, 0.858436, 0.0091085, 0, 0.240326, 0.843454, 0.00876595, 0, 0.257208, 0.827437, 0.00839794, 0, 0.274596, 0.811488, 0.00803692, 0, 0.292496, 0.796039, 0.00767352, 0, 0.310911, 0.781083, 0.0073097, 0, 0.329849, 0.767642, 0.00694032, 0, 0.349316, 0.753901, 0.00657476, 0, 0.369323, 0.740131, 0.00622699, 0, 0.38988, 0.725845, 0.0058838, 0, 0.410999, 0.710991, 0.00555586, 0, 0.432696, 0.696002, 0.00523089, 0, 0.454987, 0.680461, 0.00492494, 0, 0.47789, 0.664875, 0.00463464, 0, 0.501426, 0.649273, 0.00435422, 0, 0.52562, 0.63302, 0.0040875, 0, 0.550498, 0.61705, 0.00384075, 0, 0.576089, 0.601154, 0.00359557, 0, 0.602427, 0.586008, 0.00337636, 0, 0.629544, 0.570699, 0.00316019, 0, 0.657479, 0.555166, 0.00296033, 0, 0.686264, 0.539645, 0.00277552, 0, 0.715924, 0.524159, 0.00259499, 0, 0.746459, 0.508682, 0.00243257, 0, 0.777789, 0.493163, 0.00227851, 0, 0.809524, 0.478004, 0.00213083, 0, 0.84127, 0.46347, 0.00199502, 0, 0.873016, 0.448778, 0.00186967, 0, 0.904762, 0.434105, 0.00174732, 0, 0.936508, 0.419576, 0.00163861, 0, 0.968254, 0.405541, 0.00153341, 0, 1, 1, 0.0106462, 0, 0, 1, 0.0106462, 0, 0, 0.999999, 0.010647, 0, 0, 0.999995, 0.0106502, 0, 0, 0.999985, 0.0106589, 0, 0, 0.999964, 0.0106773, 0, 0, 0.999925, 0.0107106, 0, 0, 0.999861, 0.0107655, 0, 0.0000712986, 0.999763, 0.0108497, 0, 0.000743959, 0.999616, 0.0109716, 0, 0.00227361, 0.999408, 0.0111408, 0, 0.0046983, 0.999112, 0.0113659, 0, 0.00800158, 0.998637, 0.0116475, 0, 0.0121493, 0.996223, 0.0117231, 0, 0.0171023, 0.994006, 0.0118064, 0, 0.0228218, 0.992444, 0.0120254, 0, 0.0292711, 0.991028, 0.0123314, 0, 0.036417, 0.98803, 0.0124954, 0, 0.0442295, 0.984816, 0.0126538, 0, 0.0526815, 0.981399, 0.0128537, 0, 0.0617492, 0.977085, 0.0129694, 0, 0.0714114, 0.972154, 0.013091, 0, 0.0816495, 0.966617, 0.0131166, 0, 0.0924472, 0.960628, 0.0131583, 0, 0.10379, 0.953295, 0.0131094, 0, 0.115665, 0.94575, 0.0129966, 0, 0.128062, 0.937654, 0.0128796, 0, 0.140972, 0.927716, 0.0126477, 0, 0.154387, 0.917932, 0.0123889, 0, 0.168301, 0.907719, 0.012131, 0, 0.182709, 0.89584, 0.0118013, 0, 0.197608, 0.883526, 0.0114145, 0, 0.212994, 0.870301, 0.0110075, 0, 0.228867, 0.856272, 0.0106019, 0, 0.245227, 0.842251, 0.0101938, 0, 0.262074, 0.826466, 0.00973254, 0, 0.279412, 0.810859, 0.0092846, 0, 0.297244, 0.795051, 0.00883304, 0, 0.315575, 0.780053, 0.00840272, 0, 0.334412, 0.76575, 0.00796438, 0, 0.35376, 0.752298, 0.00752526, 0, 0.373631, 0.739153, 0.00711486, 0, 0.394034, 0.725514, 0.00670361, 0, 0.414983, 0.711473, 0.00632656, 0, 0.436491, 0.696936, 0.00595206, 0, 0.458575, 0.682126, 0.00559191, 0, 0.481253, 0.667027, 0.00525362, 0, 0.504547, 0.651875, 0.00493805, 0, 0.528481, 0.636463, 0.00462848, 0, 0.553081, 0.620641, 0.00433936, 0, 0.578377, 0.604931, 0.00407, 0, 0.604404, 0.589549, 0.00380864, 0, 0.631197, 0.574712, 0.00357049, 0, 0.658795, 0.559775, 0.00334466, 0, 0.687238, 0.544514, 0.00312505, 0, 0.716559, 0.529555, 0.00293199, 0, 0.746776, 0.514402, 0.00274204, 0, 0.777849, 0.499302, 0.00256647, 0, 0.809524, 0.484114, 0.00239901, 0, 0.84127, 0.469308, 0.00225148, 0, 0.873016, 0.455133, 0.00210178, 0, 0.904762, 0.440939, 0.0019727, 0, 0.936508, 0.426627, 0.00184382, 0, 0.968254, 0.412509, 0.00172548, 0, 1, 1, 0.013628, 0, 0, 1, 0.0136281, 0, 0, 0.999999, 0.0136289, 0, 0, 0.999995, 0.0136327, 0, 0, 0.999983, 0.0136427, 0, 0, 0.99996, 0.0136638, 0, 0, 0.999917, 0.0137022, 0, 0, 0.999846, 0.0137652, 0, 0.000204597, 0.999736, 0.0138615, 0, 0.00116837, 0.999573, 0.0140007, 0, 0.00303325, 0.99934, 0.0141927, 0, 0.00580613, 0.999004, 0.0144457, 0, 0.00945626, 0.998407, 0.0147489, 0, 0.0139421, 0.995464, 0.014731, 0, 0.0192202, 0.993328, 0.0148283, 0, 0.0252495, 0.991799, 0.0150797, 0, 0.0319921, 0.990397, 0.0154316, 0, 0.0394138, 0.986835, 0.0155005, 0, 0.0474843, 0.983938, 0.0157308, 0, 0.0561763, 0.980154, 0.0158753, 0, 0.0654661, 0.975659, 0.0159581, 0, 0.0753326, 0.970171, 0.0159832, 0, 0.0857571, 0.964803, 0.0160084, 0, 0.0967236, 0.958366, 0.0159484, 0, 0.108218, 0.950613, 0.0158001, 0, 0.120227, 0.942874, 0.0155845, 0, 0.132741, 0.935005, 0.0154292, 0, 0.145751, 0.924991, 0.0150742, 0, 0.159249, 0.914814, 0.0146757, 0, 0.17323, 0.904743, 0.0143097, 0, 0.187687, 0.893216, 0.0138695, 0, 0.202619, 0.880769, 0.0133706, 0, 0.218021, 0.868136, 0.0128606, 0, 0.233894, 0.85469, 0.0123403, 0, 0.250238, 0.840593, 0.0118091, 0, 0.267052, 0.825808, 0.011253, 0, 0.284341, 0.81009, 0.0107099, 0, 0.302106, 0.79504, 0.0101636, 0, 0.320354, 0.779757, 0.00964041, 0, 0.33909, 0.764697, 0.00911896, 0, 0.358322, 0.750913, 0.00859533, 0, 0.378059, 0.738175, 0.00811592, 0, 0.398311, 0.725242, 0.00764504, 0, 0.41909, 0.711864, 0.00718885, 0, 0.440412, 0.698009, 0.00675843, 0, 0.462292, 0.683841, 0.00634984, 0, 0.484748, 0.669391, 0.00595502, 0, 0.507802, 0.654731, 0.00558671, 0, 0.531477, 0.639805, 0.00523578, 0, 0.555802, 0.624789, 0.00490834, 0, 0.580805, 0.609325, 0.00459448, 0, 0.606522, 0.593975, 0.00430342, 0, 0.63299, 0.578983, 0.00403019, 0, 0.66025, 0.564442, 0.0037707, 0, 0.688346, 0.549835, 0.0035316, 0, 0.717319, 0.535039, 0.00330255, 0, 0.7472, 0.520403, 0.00308932, 0, 0.777982, 0.505687, 0.00289335, 0, 0.809524, 0.490939, 0.00270818, 0, 0.84127, 0.476233, 0.0025343, 0, 0.873016, 0.461624, 0.00237097, 0, 0.904762, 0.447833, 0.00222065, 0, 0.936508, 0.433992, 0.00207561, 0, 0.968254, 0.420147, 0.00194955, 0, 1, 1, 0.0173415, 0, 0, 1, 0.0173416, 0, 0, 0.999999, 0.0173426, 0, 0, 0.999995, 0.0173468, 0, 0, 0.999983, 0.0173582, 0, 0, 0.999954, 0.0173822, 0, 0, 0.999908, 0.0174258, 0, 0.00000669501, 0.999828, 0.0174973, 0, 0.000427399, 0.999705, 0.0176063, 0, 0.00171019, 0.999524, 0.0177631, 0, 0.0039248, 0.999263, 0.0179781, 0, 0.00705382, 0.998878, 0.018258, 0, 0.0110552, 0.998012, 0.0185551, 0, 0.0158812, 0.994614, 0.0184264, 0, 0.0214852, 0.993132, 0.0186385, 0, 0.0278239, 0.991563, 0.0189067, 0, 0.0348585, 0.989298, 0.0191577, 0, 0.0425544, 0.986036, 0.0192522, 0, 0.050881, 0.982558, 0.0194063, 0, 0.059811, 0.978531, 0.019486, 0, 0.0693209, 0.974198, 0.0195847, 0, 0.0793895, 0.968148, 0.0194749, 0, 0.0899984, 0.962565, 0.0194277, 0, 0.101132, 0.956041, 0.0192991, 0, 0.112775, 0.947749, 0.0189893, 0, 0.124917, 0.94018, 0.018704, 0, 0.137547, 0.93165, 0.0183458, 0, 0.150655, 0.921798, 0.0178775, 0, 0.164236, 0.911573, 0.0173618, 0, 0.178281, 0.901569, 0.0168482, 0, 0.192788, 0.890341, 0.016265, 0, 0.207752, 0.877835, 0.0156199, 0, 0.223171, 0.865472, 0.0149516, 0, 0.239044, 0.852905, 0.0143274, 0, 0.255371, 0.838906, 0.0136643, 0, 0.272153, 0.824888, 0.0129903, 0, 0.289393, 0.809977, 0.0123218, 0, 0.307093, 0.794697, 0.0116572, 0, 0.325259, 0.780028, 0.0110307, 0, 0.343896, 0.765124, 0.0104236, 0, 0.363012, 0.750411, 0.0098219, 0, 0.382617, 0.737264, 0.00924397, 0, 0.402719, 0.724799, 0.00868719, 0, 0.423332, 0.712253, 0.00816476, 0, 0.444469, 0.699267, 0.00767262, 0, 0.466146, 0.685618, 0.00719746, 0, 0.488383, 0.671736, 0.00673916, 0, 0.511199, 0.657777, 0.00631937, 0, 0.534618, 0.643497, 0.00592411, 0, 0.558668, 0.62889, 0.00553928, 0, 0.58338, 0.614299, 0.0051934, 0, 0.608787, 0.599197, 0.00485985, 0, 0.634929, 0.584175, 0.00454357, 0, 0.661849, 0.569541, 0.00425787, 0, 0.689594, 0.555193, 0.00397905, 0, 0.718211, 0.540947, 0.00372364, 0, 0.747742, 0.526593, 0.00348599, 0, 0.778205, 0.512335, 0.00326103, 0, 0.80953, 0.498017, 0.00305137, 0, 0.84127, 0.483609, 0.00285485, 0, 0.873016, 0.469368, 0.00267472, 0, 0.904762, 0.455037, 0.00249945, 0, 0.936508, 0.441493, 0.00234792, 0, 0.968254, 0.428147, 0.00219936, 0, 1, 1, 0.0219422, 0, 0, 1, 0.0219423, 0, 0, 0.999998, 0.0219434, 0, 0, 0.999993, 0.0219481, 0, 0, 0.999981, 0.021961, 0, 0, 0.999949, 0.0219879, 0, 0, 0.999896, 0.0220367, 0, 0.0000593194, 0.999808, 0.0221167, 0, 0.00075364, 0.99967, 0.0222383, 0, 0.00237884, 0.999466, 0.0224125, 0, 0.00495612, 0.999174, 0.0226495, 0, 0.00844887, 0.998725, 0.0229525, 0, 0.0128058, 0.996979, 0.0231123, 0, 0.0179742, 0.994317, 0.0230742, 0, 0.0239047, 0.992781, 0.0232895, 0, 0.0305526, 0.991191, 0.0235734, 0, 0.0378786, 0.987787, 0.0236152, 0, 0.0458475, 0.985092, 0.0237994, 0, 0.0544287, 0.981121, 0.0238553, 0, 0.0635952, 0.976924, 0.0238706, 0, 0.0733233, 0.97218, 0.0238704, 0, 0.0835922, 0.965956, 0.0236598, 0, 0.0943839, 0.959998, 0.0234735, 0, 0.105682, 0.953245, 0.0232277, 0, 0.117474, 0.944445, 0.0226973, 0, 0.129747, 0.937087, 0.0223527, 0, 0.142491, 0.928341, 0.0218144, 0, 0.155697, 0.9184, 0.0211516, 0, 0.169358, 0.907959, 0.0204553, 0, 0.183469, 0.89808, 0.0197673, 0, 0.198024, 0.887047, 0.0189915, 0, 0.21302, 0.875221, 0.0182082, 0, 0.228455, 0.86269, 0.0173584, 0, 0.244329, 0.850735, 0.0165718, 0, 0.260639, 0.837545, 0.0157524, 0, 0.277389, 0.823639, 0.0149482, 0, 0.29458, 0.809699, 0.0141431, 0, 0.312216, 0.794797, 0.0133527, 0, 0.3303, 0.780578, 0.0126193, 0, 0.34884, 0.766019, 0.0118914, 0, 0.367842, 0.751447, 0.0111839, 0, 0.387315, 0.737275, 0.010514, 0, 0.40727, 0.724545, 0.00987277, 0, 0.427717, 0.712644, 0.00926569, 0, 0.448671, 0.700432, 0.00869029, 0, 0.470149, 0.687664, 0.00814691, 0, 0.492167, 0.674288, 0.00763012, 0, 0.514746, 0.660966, 0.00714437, 0, 0.537911, 0.647264, 0.00668457, 0, 0.561688, 0.633431, 0.00626581, 0, 0.586108, 0.619133, 0.00585593, 0, 0.611206, 0.604935, 0.00548188, 0, 0.637022, 0.590236, 0.00513288, 0, 0.663599, 0.575473, 0.0047906, 0, 0.690989, 0.561228, 0.00448895, 0, 0.719242, 0.547054, 0.00420233, 0, 0.748411, 0.533175, 0.00392869, 0, 0.778531, 0.519163, 0.00367445, 0, 0.809583, 0.505328, 0.00344097, 0, 0.84127, 0.491446, 0.00322003, 0, 0.873016, 0.477356, 0.00301283, 0, 0.904762, 0.46356, 0.00282592, 0, 0.936508, 0.449623, 0.00264956, 0, 0.968254, 0.436068, 0.00246956, 0, 1, 1, 0.0276135, 0, 0, 1, 0.0276136, 0, 0, 0.999998, 0.0276148, 0, 0, 0.999993, 0.0276201, 0, 0, 0.999976, 0.0276342, 0, 0, 0.999945, 0.027664, 0, 0, 0.999884, 0.0277179, 0, 0.00018679, 0.999784, 0.027806, 0, 0.00119607, 0.99963, 0.0279394, 0, 0.00318407, 0.999401, 0.0281295, 0, 0.00613601, 0.999066, 0.0283858, 0, 0.00999963, 0.998524, 0.0287027, 0, 0.0147164, 0.995702, 0.0286256, 0, 0.0202295, 0.993593, 0.0286733, 0, 0.0264876, 0.992067, 0.0288989, 0, 0.0334452, 0.990548, 0.0292135, 0, 0.0410621, 0.986775, 0.0291296, 0, 0.0493032, 0.984054, 0.0293099, 0, 0.0581381, 0.979481, 0.0291881, 0, 0.0675397, 0.975297, 0.0291598, 0, 0.0774848, 0.96981, 0.028954, 0, 0.0879528, 0.963524, 0.028628, 0, 0.0989258, 0.957398, 0.0283135, 0, 0.110388, 0.950088, 0.0278469, 0, 0.122327, 0.941538, 0.0271798, 0, 0.134729, 0.933332, 0.0265388, 0, 0.147587, 0.924392, 0.0257776, 0, 0.160889, 0.914581, 0.024916, 0, 0.174631, 0.904347, 0.0240242, 0, 0.188806, 0.894324, 0.0231229, 0, 0.203409, 0.883724, 0.022153, 0, 0.218437, 0.872207, 0.0211355, 0, 0.233888, 0.859927, 0.0201048, 0, 0.249761, 0.848373, 0.0191263, 0, 0.266056, 0.836023, 0.0181306, 0, 0.282774, 0.82289, 0.0171718, 0, 0.299917, 0.809324, 0.0162196, 0, 0.317488, 0.795361, 0.0152622, 0, 0.335493, 0.781253, 0.01439, 0, 0.353936, 0.767338, 0.013533, 0, 0.372825, 0.753156, 0.0127244, 0, 0.392168, 0.739122, 0.0119454, 0, 0.411976, 0.725358, 0.0112054, 0, 0.432259, 0.712949, 0.010487, 0, 0.453032, 0.701621, 0.00984032, 0, 0.47431, 0.689703, 0.00921495, 0, 0.496111, 0.677216, 0.00862492, 0, 0.518456, 0.664217, 0.00806882, 0, 0.541367, 0.65137, 0.00755922, 0, 0.564872, 0.638, 0.00705705, 0, 0.589001, 0.62453, 0.00661266, 0, 0.613789, 0.610601, 0.00618432, 0, 0.639277, 0.59676, 0.00578033, 0, 0.66551, 0.582433, 0.00540927, 0, 0.692539, 0.568026, 0.00506104, 0, 0.720422, 0.55414, 0.0047353, 0, 0.749216, 0.540178, 0.00442889, 0, 0.778974, 0.526513, 0.00414363, 0, 0.809711, 0.512954, 0.00388237, 0, 0.84127, 0.499403, 0.00362875, 0, 0.873016, 0.486026, 0.00340827, 0, 0.904762, 0.472345, 0.00318598, 0, 0.936508, 0.458828, 0.00297635, 0, 0.968254, 0.445379, 0.00279447, 0, 1, 1, 0.0345716, 0, 0, 1, 0.0345717, 0, 0, 0.999999, 0.034573, 0, 0, 0.999991, 0.0345787, 0, 0, 0.999974, 0.0345941, 0, 0, 0.999937, 0.0346263, 0, 0.00000188589, 0.999869, 0.0346847, 0, 0.000409238, 0.999757, 0.0347798, 0, 0.0017674, 0.999582, 0.0349233, 0, 0.00413658, 0.999322, 0.0351265, 0, 0.00747408, 0.998939, 0.0353967, 0, 0.0117157, 0.998219, 0.0357018, 0, 0.0167966, 0.994974, 0.0354726, 0, 0.0226572, 0.993201, 0.0355621, 0, 0.0292445, 0.991573, 0.0357641, 0, 0.0365123, 0.989301, 0.0359252, 0, 0.0444203, 0.985712, 0.0358017, 0, 0.0529334, 0.982411, 0.0358353, 0, 0.0620214, 0.977827, 0.035617, 0, 0.0716574, 0.973278, 0.0354398, 0, 0.0818186, 0.967397, 0.0350483, 0, 0.0924846, 0.960696, 0.0344795, 0, 0.103638, 0.954349, 0.0339861, 0, 0.115263, 0.946066, 0.0331323, 0, 0.127348, 0.938012, 0.032359, 0, 0.13988, 0.929413, 0.0314413, 0, 0.152849, 0.920355, 0.0304103, 0, 0.166248, 0.910586, 0.0292785, 0, 0.18007, 0.900609, 0.0281391, 0, 0.194308, 0.890093, 0.0269103, 0, 0.208958, 0.880013, 0.0257269, 0, 0.224018, 0.869001, 0.0244671, 0, 0.239485, 0.85751, 0.0232252, 0, 0.255359, 0.84582, 0.0220117, 0, 0.271638, 0.834383, 0.0208274, 0, 0.288324, 0.822158, 0.0196628, 0, 0.305419, 0.809056, 0.0185306, 0, 0.322927, 0.795832, 0.0174174, 0, 0.340851, 0.782547, 0.0163758, 0, 0.359199, 0.7689, 0.015391, 0, 0.377975, 0.755526, 0.0144488, 0, 0.397189, 0.741681, 0.0135372, 0, 0.416851, 0.728178, 0.0126957, 0, 0.436971, 0.714642, 0.0118812, 0, 0.457564, 0.702756, 0.0111165, 0, 0.478644, 0.69175, 0.0104145, 0, 0.500229, 0.680159, 0.00974439, 0, 0.522339, 0.668073, 0.00911926, 0, 0.544997, 0.655405, 0.00851393, 0, 0.56823, 0.642921, 0.00797637, 0, 0.592068, 0.629993, 0.00745119, 0, 0.616546, 0.616828, 0.00696972, 0, 0.641705, 0.603305, 0.00652425, 0, 0.66759, 0.589833, 0.00610188, 0, 0.694255, 0.575945, 0.00570834, 0, 0.72176, 0.561745, 0.00533384, 0, 0.750168, 0.548277, 0.00500001, 0, 0.779545, 0.534467, 0.00467582, 0, 0.809933, 0.521032, 0.00438092, 0, 0.841272, 0.507877, 0.00410348, 0, 0.873016, 0.494654, 0.00383618, 0, 0.904762, 0.481592, 0.00358699, 0, 0.936508, 0.468509, 0.00337281, 0, 0.968254, 0.455293, 0.00316196, 0, 1, 1, 0.0430698, 0, 0, 1, 0.0430699, 0, 0, 0.999998, 0.0430713, 0, 0, 0.999991, 0.0430773, 0, 0, 0.99997, 0.0430936, 0, 0, 0.999928, 0.0431277, 0, 0.0000406396, 0.999852, 0.0431893, 0, 0.000744376, 0.999724, 0.0432895, 0, 0.0024806, 0.999527, 0.0434397, 0, 0.00524779, 0.99923, 0.0436507, 0, 0.00898164, 0.998783, 0.0439255, 0, 0.0136083, 0.997507, 0.0441104, 0, 0.0190582, 0.994418, 0.0438225, 0, 0.0252694, 0.992864, 0.0439396, 0, 0.0321879, 0.991127, 0.0440962, 0, 0.039767, 0.987331, 0.0438408, 0, 0.0479667, 0.984819, 0.0438991, 0, 0.056752, 0.980384, 0.0435906, 0, 0.0660929, 0.975846, 0.0432543, 0, 0.075963, 0.970748, 0.0428293, 0, 0.0863398, 0.964303, 0.042153, 0, 0.0972035, 0.95772, 0.0414111, 0, 0.108537, 0.950747, 0.0405893, 0, 0.120325, 0.942533, 0.0394887, 0, 0.132554, 0.934045, 0.0383544, 0, 0.145215, 0.924942, 0.037057, 0, 0.158296, 0.915811, 0.0356993, 0, 0.17179, 0.90612, 0.0342401, 0, 0.185691, 0.896434, 0.0328078, 0, 0.199993, 0.886021, 0.031288, 0, 0.214691, 0.876081, 0.0297776, 0, 0.229782, 0.865608, 0.0282334, 0, 0.245265, 0.854924, 0.026749, 0, 0.261138, 0.843607, 0.02526, 0, 0.277401, 0.832456, 0.0238214, 0, 0.294056, 0.821342, 0.0224682, 0, 0.311104, 0.809303, 0.0211297, 0, 0.328548, 0.796468, 0.0198387, 0, 0.346394, 0.784046, 0.0186227, 0, 0.364645, 0.771262, 0.0174561, 0, 0.38331, 0.758118, 0.0163806, 0, 0.402396, 0.745075, 0.0153287, 0, 0.421912, 0.731926, 0.0143647, 0, 0.44187, 0.71863, 0.0134363, 0, 0.462283, 0.705414, 0.0125603, 0, 0.483165, 0.693792, 0.0117508, 0, 0.504535, 0.683108, 0.0110016, 0, 0.52641, 0.67183, 0.0102757, 0, 0.548816, 0.66015, 0.00962044, 0, 0.571776, 0.647907, 0.00898031, 0, 0.595323, 0.635734, 0.00840811, 0, 0.619489, 0.623208, 0.00786211, 0, 0.644317, 0.610438, 0.00734953, 0, 0.669852, 0.597345, 0.00687688, 0, 0.696148, 0.584138, 0.00643469, 0, 0.723267, 0.5707, 0.00602236, 0, 0.75128, 0.556966, 0.0056324, 0, 0.780258, 0.543607, 0.00528277, 0, 0.810268, 0.530213, 0.00493999, 0, 0.841311, 0.516912, 0.00462265, 0, 0.873016, 0.503916, 0.0043307, 0, 0.904762, 0.491146, 0.00406858, 0, 0.936508, 0.478439, 0.00381436, 0, 0.968254, 0.465834, 0.00358003, 0, 1, 1, 0.0534039, 0, 0, 1, 0.053404, 0, 0, 0.999998, 0.0534055, 0, 0, 0.999989, 0.0534116, 0, 0, 0.999968, 0.0534283, 0, 0, 0.999918, 0.0534633, 0, 0.000155895, 0.99983, 0.0535262, 0, 0.00120914, 0.999685, 0.0536281, 0, 0.00334944, 0.999461, 0.0537799, 0, 0.00653077, 0.999119, 0.0539902, 0, 0.0106718, 0.998582, 0.0542524, 0, 0.0156907, 0.995919, 0.0540318, 0, 0.0215147, 0.993735, 0.0538914, 0, 0.0280801, 0.992126, 0.0539557, 0, 0.0353323, 0.990266, 0.0540401, 0, 0.0432247, 0.986317, 0.0536064, 0, 0.0517172, 0.983213, 0.0534425, 0, 0.0607754, 0.978303, 0.0528622, 0, 0.0703698, 0.973665, 0.0523363, 0, 0.0804742, 0.968091, 0.0516165, 0, 0.0910667, 0.961026, 0.0505434, 0, 0.102128, 0.954333, 0.049523, 0, 0.113641, 0.946372, 0.0481698, 0, 0.125591, 0.938254, 0.0467674, 0, 0.137965, 0.929516, 0.0452341, 0, 0.150754, 0.920106, 0.0435083, 0, 0.163947, 0.910899, 0.0417399, 0, 0.177537, 0.901532, 0.0399389, 0, 0.191516, 0.891919, 0.0380901, 0, 0.205881, 0.882006, 0.0362341, 0, 0.220626, 0.871965, 0.0343444, 0, 0.235749, 0.862145, 0.0324832, 0, 0.251248, 0.852058, 0.0306681, 0, 0.267121, 0.84161, 0.0289097, 0, 0.283368, 0.830806, 0.0272079, 0, 0.299992, 0.820476, 0.0256089, 0, 0.316992, 0.809514, 0.0240394, 0, 0.334374, 0.797865, 0.0225379, 0, 0.35214, 0.785621, 0.0211235, 0, 0.370296, 0.773765, 0.0197908, 0, 0.388849, 0.761629, 0.0185235, 0, 0.407807, 0.748891, 0.0173358, 0, 0.427178, 0.736437, 0.0162305, 0, 0.446974, 0.723707, 0.0151778, 0, 0.467207, 0.710606, 0.0141791, 0, 0.487892, 0.698019, 0.0132592, 0, 0.509046, 0.686203, 0.0123887, 0, 0.530687, 0.675692, 0.0115976, 0, 0.552839, 0.664826, 0.0108325, 0, 0.575527, 0.65349, 0.0101348, 0, 0.59878, 0.641774, 0.00947756, 0, 0.622634, 0.629794, 0.00886058, 0, 0.647128, 0.617647, 0.00828526, 0, 0.672308, 0.60534, 0.00775312, 0, 0.698231, 0.592718, 0.00726033, 0, 0.724958, 0.579746, 0.00679731, 0, 0.752563, 0.566763, 0.00636111, 0, 0.781127, 0.553515, 0.00595228, 0, 0.810733, 0.540118, 0.00556876, 0, 0.841426, 0.527325, 0.00523051, 0, 0.873016, 0.514265, 0.00490712, 0, 0.904762, 0.501406, 0.00460297, 0, 0.936508, 0.488922, 0.00431247, 0, 0.968254, 0.476541, 0.0040472, 0, 1, 1, 0.0659184, 0, 0, 1, 0.0659185, 0, 0, 0.999998, 0.06592, 0, 0, 0.999988, 0.0659259, 0, 0, 0.999963, 0.0659423, 0, 0, 0.999907, 0.0659764, 0, 0.000374198, 0.999806, 0.0660376, 0, 0.00182071, 0.999639, 0.0661361, 0, 0.0043894, 0.999378, 0.0662814, 0, 0.00800055, 0.998985, 0.0664779, 0, 0.0125594, 0.998285, 0.0666914, 0, 0.0179786, 0.995071, 0.0661989, 0, 0.0241822, 0.993172, 0.0660454, 0, 0.031106, 0.991438, 0.0660105, 0, 0.0386952, 0.988428, 0.0656875, 0, 0.0469032, 0.985218, 0.0652913, 0, 0.0556905, 0.981128, 0.0647107, 0, 0.065023, 0.976015, 0.0638491, 0, 0.0748717, 0.97097, 0.062993, 0, 0.0852112, 0.964582, 0.0617927, 0, 0.0960199, 0.957383, 0.0603626, 0, 0.107279, 0.949969, 0.0588128, 0, 0.118971, 0.941843, 0.0570274, 0, 0.131084, 0.933624, 0.0551885, 0, 0.143604, 0.924543, 0.053122, 0, 0.156521, 0.914919, 0.0508897, 0, 0.169825, 0.905773, 0.0486418, 0, 0.18351, 0.896434, 0.0463364, 0, 0.197569, 0.887195, 0.0440623, 0, 0.211997, 0.877706, 0.0417799, 0, 0.226789, 0.867719, 0.03945, 0, 0.241944, 0.858587, 0.037243, 0, 0.257458, 0.849317, 0.0350956, 0, 0.273331, 0.839585, 0.0329852, 0, 0.289563, 0.829856, 0.0310028, 0, 0.306154, 0.819589, 0.0290953, 0, 0.323108, 0.809714, 0.0272738, 0, 0.340426, 0.79934, 0.0255631, 0, 0.358113, 0.788224, 0.0239175, 0, 0.376175, 0.776619, 0.0223831, 0, 0.394616, 0.76521, 0.0209298, 0, 0.413445, 0.753716, 0.0195786, 0, 0.432671, 0.741564, 0.0183001, 0, 0.452305, 0.729413, 0.0171259, 0, 0.472358, 0.717146, 0.0159933, 0, 0.492845, 0.70436, 0.0149495, 0, 0.513783, 0.69219, 0.0139681, 0, 0.535189, 0.680289, 0.0130577, 0, 0.557087, 0.669611, 0.0122198, 0, 0.5795, 0.659113, 0.0114174, 0, 0.602459, 0.648148, 0.0106729, 0, 0.625997, 0.636905, 0.00998997, 0, 0.650154, 0.625154, 0.00934313, 0, 0.674976, 0.613481, 0.00874839, 0, 0.700518, 0.60154, 0.00818265, 0, 0.726845, 0.58943, 0.00766889, 0, 0.754032, 0.576828, 0.00717153, 0, 0.782167, 0.564194, 0.00672696, 0, 0.811344, 0.551501, 0.00630863, 0, 0.841644, 0.538635, 0.00592177, 0, 0.873016, 0.525724, 0.00554888, 0, 0.904762, 0.513209, 0.00520225, 0, 0.936508, 0.500457, 0.00488231, 0, 0.968254, 0.48799, 0.00457153, 0, 1, 1, 0.0810131, 0, 0, 1, 0.0810133, 0, 0, 0.999997, 0.0810145, 0, 0, 0.999985, 0.08102, 0, 0, 0.999956, 0.0810347, 0, 0.0000195026, 0.999893, 0.0810656, 0, 0.000719316, 0.999777, 0.0811205, 0, 0.00259774, 0.999583, 0.081208, 0, 0.00561807, 0.999281, 0.0813343, 0, 0.00967472, 0.998813, 0.0814969, 0, 0.0146627, 0.997597, 0.0815217, 0, 0.0204902, 0.994379, 0.0808502, 0, 0.0270802, 0.992744, 0.0806792, 0, 0.0343674, 0.990745, 0.0804589, 0, 0.0422974, 0.986646, 0.0796107, 0, 0.0508242, 0.983611, 0.0790913, 0, 0.0599087, 0.978869, 0.0780746, 0, 0.0695175, 0.973475, 0.0768218, 0, 0.0796223, 0.967845, 0.0754926, 0, 0.0901983, 0.960778, 0.0737063, 0, 0.101224, 0.953333, 0.0718052, 0, 0.112682, 0.945274, 0.0695946, 0, 0.124555, 0.936955, 0.0672492, 0, 0.136831, 0.928319, 0.0647732, 0, 0.149496, 0.919075, 0.0620947, 0, 0.162542, 0.909114, 0.0591816, 0, 0.175958, 0.900137, 0.0563917, 0, 0.189739, 0.891069, 0.0535392, 0, 0.203877, 0.882262, 0.0507642, 0, 0.218368, 0.873232, 0.0479793, 0, 0.233208, 0.864042, 0.045226, 0, 0.248393, 0.855002, 0.0425413, 0, 0.263923, 0.846569, 0.0400126, 0, 0.279796, 0.837714, 0.0375269, 0, 0.296012, 0.828918, 0.0352027, 0, 0.312573, 0.819783, 0.0330011, 0, 0.329479, 0.810129, 0.0308908, 0, 0.346734, 0.800866, 0.0289112, 0, 0.364342, 0.79093, 0.0270255, 0, 0.382307, 0.780593, 0.0252758, 0, 0.400637, 0.769511, 0.0236178, 0, 0.419337, 0.758558, 0.0220652, 0, 0.438418, 0.747632, 0.0206289, 0, 0.457889, 0.736146, 0.0192873, 0, 0.477761, 0.724093, 0.0180333, 0, 0.49805, 0.71234, 0.0168264, 0, 0.51877, 0.700201, 0.015746, 0, 0.53994, 0.687949, 0.0147027, 0, 0.561581, 0.676163, 0.0137512, 0, 0.583718, 0.665001, 0.0128655, 0, 0.60638, 0.65472, 0.0120366, 0, 0.629599, 0.644213, 0.0112604, 0, 0.653415, 0.633382, 0.0105413, 0, 0.677874, 0.62212, 0.00986498, 0, 0.70303, 0.610631, 0.00923308, 0, 0.728948, 0.599078, 0.00864206, 0, 0.755706, 0.587519, 0.00811784, 0, 0.783396, 0.575505, 0.00761237, 0, 0.812121, 0.563148, 0.00713949, 0, 0.841989, 0.550828, 0.00668379, 0, 0.873035, 0.538458, 0.00627715, 0, 0.904762, 0.525905, 0.00588336, 0, 0.936508, 0.513517, 0.00552687, 0, 0.968254, 0.501395, 0.00519681, 0, 1, 1, 0.0991506, 0, 0, 1, 0.0991504, 0, 0, 0.999996, 0.0991515, 0, 0, 0.999984, 0.0991558, 0, 0, 0.999947, 0.0991672, 0, 0.000114389, 0.999874, 0.0991912, 0, 0.00121503, 0.999739, 0.0992331, 0, 0.00356108, 0.999514, 0.0992983, 0, 0.00705578, 0.999159, 0.0993877, 0, 0.011574, 0.998586, 0.0994837, 0, 0.017003, 0.995731, 0.0988425, 0, 0.0232484, 0.993384, 0.098276, 0, 0.0302318, 0.991615, 0.0979269, 0, 0.0378884, 0.989029, 0.0973432, 0, 0.0461641, 0.985373, 0.0963539, 0, 0.0550136, 0.981278, 0.0952306, 0, 0.0643988, 0.975777, 0.0936233, 0, 0.0742868, 0.970526, 0.0920219, 0, 0.0846501, 0.963755, 0.0898912, 0, 0.0954644, 0.956676, 0.0876064, 0, 0.106709, 0.948099, 0.0847751, 0, 0.118367, 0.939718, 0.0818638, 0, 0.130423, 0.931305, 0.078857, 0, 0.142862, 0.922342, 0.0756127, 0, 0.155674, 0.912842, 0.0721473, 0, 0.168849, 0.903304, 0.0686195, 0, 0.182378, 0.89411, 0.0650589, 0, 0.196255, 0.885512, 0.0616022, 0, 0.210473, 0.877193, 0.0582434, 0, 0.225027, 0.86877, 0.0548979, 0, 0.239915, 0.860267, 0.0516095, 0, 0.255132, 0.851915, 0.048468, 0, 0.270678, 0.843912, 0.0454447, 0, 0.286551, 0.83604, 0.0425612, 0, 0.302751, 0.828245, 0.0398752, 0, 0.31928, 0.820159, 0.0373198, 0, 0.336138, 0.81167, 0.034916, 0, 0.35333, 0.802659, 0.0326402, 0, 0.370858, 0.793921, 0.0304901, 0, 0.388728, 0.784713, 0.0284857, 0, 0.406944, 0.774946, 0.0266186, 0, 0.425515, 0.76448, 0.0248593, 0, 0.444449, 0.753793, 0.0232114, 0, 0.463756, 0.743506, 0.0217039, 0, 0.483447, 0.732555, 0.0202841, 0, 0.503535, 0.720965, 0.0189648, 0, 0.524036, 0.709422, 0.0177189, 0, 0.544968, 0.697756, 0.0165626, 0, 0.56635, 0.685565, 0.015483, 0, 0.588208, 0.673987, 0.0144892, 0, 0.610569, 0.66244, 0.0135607, 0, 0.633466, 0.651675, 0.0126956, 0, 0.656936, 0.641598, 0.0118788, 0, 0.681025, 0.63121, 0.0111261, 0, 0.705788, 0.620514, 0.010437, 0, 0.731289, 0.609366, 0.00978747, 0, 0.757606, 0.598137, 0.00917257, 0, 0.784834, 0.586966, 0.00859778, 0, 0.813085, 0.575549, 0.00806803, 0, 0.842485, 0.563797, 0.00757294, 0, 0.87313, 0.551758, 0.00710592, 0, 0.904762, 0.539894, 0.0066841, 0, 0.936508, 0.527901, 0.00627901, 0, 0.968254, 0.515819, 0.00590506, 0, 1, 1, 0.120864, 0, 0, 1, 0.120864, 0, 0, 0.999996, 0.120864, 0, 0, 0.99998, 0.120867, 0, 0, 0.99994, 0.120872, 0, 0.000323781, 0.999852, 0.120884, 0, 0.00188693, 0.999693, 0.120903, 0, 0.00473489, 0.999426, 0.120929, 0, 0.00872704, 0.999002, 0.120955, 0, 0.0137237, 0.998235, 0.120918, 0, 0.0196068, 0.994608, 0.119764, 0, 0.0262803, 0.992997, 0.119265, 0, 0.0336657, 0.990968, 0.11863, 0, 0.0416987, 0.987002, 0.117261, 0, 0.0503261, 0.983524, 0.116009, 0, 0.0595035, 0.97875, 0.114252, 0, 0.0691935, 0.972652, 0.11193, 0, 0.0793645, 0.966613, 0.109555, 0, 0.0899894, 0.959275, 0.106612, 0, 0.101045, 0.951272, 0.103375, 0, 0.112512, 0.942323, 0.0996594, 0, 0.124372, 0.933679, 0.0958841, 0, 0.136611, 0.924822, 0.0919265, 0, 0.149216, 0.915742, 0.0878061, 0, 0.162176, 0.906348, 0.0834894, 0, 0.175482, 0.896883, 0.079085, 0, 0.189125, 0.88774, 0.0746745, 0, 0.203098, 0.87986, 0.0705773, 0, 0.217396, 0.871998, 0.0665005, 0, 0.232015, 0.864325, 0.0625413, 0, 0.24695, 0.856685, 0.0586781, 0, 0.2622, 0.84925, 0.0550063, 0, 0.277761, 0.841719, 0.0514727, 0, 0.293634, 0.834755, 0.0481398, 0, 0.309819, 0.827853, 0.0450172, 0, 0.326315, 0.820888, 0.0420969, 0, 0.343126, 0.813616, 0.0393702, 0, 0.360254, 0.805767, 0.0367771, 0, 0.377701, 0.797338, 0.0343274, 0, 0.395474, 0.789122, 0.0320529, 0, 0.413577, 0.780601, 0.0299485, 0, 0.432018, 0.771424, 0.0279812, 0, 0.450804, 0.761502, 0.0261054, 0, 0.469944, 0.751166, 0.0243942, 0, 0.489451, 0.741276, 0.0228087, 0, 0.509337, 0.730898, 0.0213265, 0, 0.529617, 0.719878, 0.0199307, 0, 0.550307, 0.708379, 0.0186574, 0, 0.571428, 0.697165, 0.0174446, 0, 0.593003, 0.685554, 0.0163144, 0, 0.615059, 0.673631, 0.015276, 0, 0.637628, 0.662385, 0.0143003, 0, 0.660746, 0.651059, 0.0134112, 0, 0.68446, 0.640451, 0.0125794, 0, 0.70882, 0.630536, 0.011793, 0, 0.733893, 0.620316, 0.0110547, 0, 0.759756, 0.609722, 0.0103668, 0, 0.786505, 0.598804, 0.00973009, 0, 0.814259, 0.587871, 0.00912812, 0, 0.843157, 0.577121, 0.00858916, 0, 0.87334, 0.566019, 0.00807333, 0, 0.904762, 0.554664, 0.00759687, 0, 0.936508, 0.543101, 0.00714759, 0, 0.968254, 0.531558, 0.00673418, 0, 1, 1, 0.146767, 0, 0, 1, 0.146767, 0, 0, 0.999997, 0.146767, 0, 0, 0.999977, 0.146765, 0, 0.00000320658, 0.999929, 0.146762, 0, 0.000682576, 0.999823, 0.146753, 0, 0.00276402, 0.999633, 0.146735, 0, 0.00614771, 0.999314, 0.146699, 0, 0.0106613, 0.998796, 0.14662, 0, 0.0161546, 0.997124, 0.146107, 0, 0.0225063, 0.994062, 0.144857, 0, 0.0296198, 0.992154, 0.144011, 0, 0.037417, 0.989186, 0.142712, 0, 0.0458348, 0.985279, 0.140926, 0, 0.0548211, 0.980826, 0.13885, 0, 0.0643326, 0.975056, 0.136168, 0, 0.074333, 0.969005, 0.133217, 0, 0.0847917, 0.961554, 0.12959, 0, 0.0956828, 0.954206, 0.125886, 0, 0.106984, 0.945046, 0.121335, 0, 0.118675, 0.935678, 0.116492, 0, 0.130741, 0.926748, 0.111635, 0, 0.143166, 0.917764, 0.106625, 0, 0.155939, 0.908358, 0.101325, 0, 0.169049, 0.899219, 0.0960249, 0, 0.182487, 0.890089, 0.0906527, 0, 0.196245, 0.881488, 0.0853905, 0, 0.210317, 0.874031, 0.0804177, 0, 0.224697, 0.866932, 0.0756005, 0, 0.23938, 0.859976, 0.0709019, 0, 0.254364, 0.853375, 0.0664391, 0, 0.269646, 0.846971, 0.0622012, 0, 0.285223, 0.840483, 0.058129, 0, 0.301096, 0.833969, 0.0542762, 0, 0.317265, 0.82806, 0.0507042, 0, 0.333729, 0.822128, 0.047368, 0, 0.350491, 0.815989, 0.044272, 0, 0.367554, 0.809336, 0.0413444, 0, 0.38492, 0.802177, 0.038601, 0, 0.402594, 0.79441, 0.0360227, 0, 0.420582, 0.786573, 0.0336383, 0, 0.438891, 0.778619, 0.0314321, 0, 0.457527, 0.77, 0.029362, 0, 0.476499, 0.760698, 0.0274102, 0, 0.49582, 0.750932, 0.0256146, 0, 0.5155, 0.740993, 0.023974, 0, 0.535555, 0.731159, 0.0224182, 0, 0.556, 0.720836, 0.0209889, 0, 0.576855, 0.709913, 0.0196411, 0, 0.598143, 0.698415, 0.0183824, 0, 0.619888, 0.68745, 0.0172222, 0, 0.642123, 0.676154, 0.0161509, 0, 0.664883, 0.664383, 0.0151397, 0, 0.688211, 0.6533, 0.0141873, 0, 0.71216, 0.642072, 0.0133105, 0, 0.736792, 0.631412, 0.0124932, 0, 0.762186, 0.621622, 0.0117408, 0, 0.788439, 0.611681, 0.0110358, 0, 0.815672, 0.60142, 0.0103775, 0, 0.844034, 0.59083, 0.00975623, 0, 0.873699, 0.580254, 0.00918084, 0, 0.904765, 0.569841, 0.00864721, 0, 0.936508, 0.559224, 0.00815731, 0, 0.968254, 0.548315, 0.00767924, 0, 1, 1, 0.177563, 0, 0, 1, 0.177563, 0, 0, 0.999994, 0.177562, 0, 0, 0.999972, 0.177555, 0, 0.0000664171, 0.999914, 0.177536, 0, 0.0012276, 0.999787, 0.177496, 0, 0.00388025, 0.999556, 0.17742, 0, 0.00783463, 0.999165, 0.177285, 0, 0.0128953, 0.9985, 0.177037, 0, 0.0189053, 0.995388, 0.175634, 0, 0.025742, 0.993102, 0.174375, 0, 0.033309, 0.990992, 0.173121, 0, 0.0415298, 0.986932, 0.170896, 0, 0.0503425, 0.982786, 0.16847, 0, 0.0596964, 0.977592, 0.165455, 0, 0.0695498, 0.971075, 0.161676, 0, 0.0798676, 0.963967, 0.157458, 0, 0.0906201, 0.956397, 0.152836, 0, 0.101783, 0.947489, 0.147467, 0, 0.113333, 0.937564, 0.14145, 0, 0.125254, 0.928182, 0.135383, 0, 0.137529, 0.919027, 0.129212, 0, 0.150144, 0.909618, 0.12276, 0, 0.163088, 0.900492, 0.116273, 0, 0.176351, 0.891671, 0.1098, 0, 0.189924, 0.883146, 0.103362, 0, 0.203799, 0.875151, 0.0970799, 0, 0.21797, 0.868338, 0.0911732, 0, 0.232433, 0.862033, 0.0854966, 0, 0.247182, 0.856107, 0.0800691, 0, 0.262216, 0.850644, 0.0749618, 0, 0.27753, 0.845261, 0.070079, 0, 0.293124, 0.839885, 0.0654321, 0, 0.308997, 0.834609, 0.0610975, 0, 0.325149, 0.829083, 0.0569741, 0, 0.341581, 0.82404, 0.0531736, 0, 0.358294, 0.818968, 0.049665, 0, 0.37529, 0.813496, 0.0463856, 0, 0.392573, 0.807533, 0.0433217, 0, 0.410148, 0.80099, 0.0404402, 0, 0.428019, 0.793891, 0.0377578, 0, 0.446192, 0.786281, 0.0352616, 0, 0.464676, 0.778773, 0.0329577, 0, 0.483478, 0.770737, 0.030808, 0, 0.502608, 0.762094, 0.0287964, 0, 0.522079, 0.752898, 0.0269254, 0, 0.541905, 0.743306, 0.0251926, 0, 0.5621, 0.733416, 0.023595, 0, 0.582684, 0.723742, 0.0221155, 0, 0.603677, 0.713542, 0.0207435, 0, 0.625106, 0.702755, 0.019434, 0, 0.646998, 0.691484, 0.0182046, 0, 0.66939, 0.680531, 0.0170771, 0, 0.692324, 0.66953, 0.0160339, 0, 0.715849, 0.658126, 0.0150677, 0, 0.740028, 0.646933, 0.0141551, 0, 0.764937, 0.636107, 0.0133179, 0, 0.790673, 0.625271, 0.0125284, 0, 0.817358, 0.615225, 0.0117937, 0, 0.84515, 0.605678, 0.0111181, 0, 0.874244, 0.59583, 0.0104759, 0, 0.904828, 0.585704, 0.00986672, 0, 0.936508, 0.575413, 0.00929712, 0, 0.968254, 0.565373, 0.00876713, 0, 1, 1, 0.214058, 0, 0, 0.999999, 0.214058, 0, 0, 0.999994, 0.214055, 0, 0, 0.999966, 0.214039, 0, 0.000259642, 0.999893, 0.213998, 0, 0.00200075, 0.999737, 0.21391, 0, 0.00527775, 0.999449, 0.213745, 0, 0.00983959, 0.99896, 0.213458, 0, 0.0154755, 0.9979, 0.212855, 0, 0.0220249, 0.994278, 0.210779, 0, 0.0293654, 0.992254, 0.20926, 0, 0.0374021, 0.98881, 0.206908, 0, 0.0460604, 0.984715, 0.204009, 0, 0.0552802, 0.979738, 0.200471, 0, 0.0650127, 0.972884, 0.195813, 0, 0.0752175, 0.965996, 0.190856, 0, 0.0858612, 0.957974, 0.185077, 0, 0.0969155, 0.949155, 0.17868, 0, 0.108356, 0.939288, 0.171513, 0, 0.120163, 0.928996, 0.163838, 0, 0.132319, 0.919563, 0.156246, 0, 0.144808, 0.910004, 0.148359, 0, 0.157618, 0.900791, 0.140417, 0, 0.170737, 0.892135, 0.132569, 0, 0.184155, 0.883803, 0.124741, 0, 0.197866, 0.876034, 0.117091, 0, 0.211861, 0.869219, 0.109835, 0, 0.226134, 0.863062, 0.102859, 0, 0.240682, 0.857795, 0.0962928, 0, 0.255499, 0.853009, 0.0900725, 0, 0.270583, 0.848603, 0.0842101, 0, 0.285931, 0.844335, 0.0786527, 0, 0.301542, 0.840208, 0.0734397, 0, 0.317415, 0.836035, 0.0685334, 0, 0.33355, 0.83172, 0.0639275, 0, 0.349948, 0.827135, 0.0595909, 0, 0.36661, 0.822797, 0.0556204, 0, 0.383539, 0.818387, 0.0519394, 0, 0.400738, 0.813565, 0.0485317, 0, 0.41821, 0.808142, 0.0453138, 0, 0.435961, 0.802212, 0.0423354, 0, 0.453997, 0.79573, 0.0395553, 0, 0.472324, 0.788741, 0.036988, 0, 0.490951, 0.781093, 0.0345688, 0, 0.509887, 0.773597, 0.0323297, 0, 0.529144, 0.765622, 0.0302719, 0, 0.548735, 0.757083, 0.0283477, 0, 0.568674, 0.747992, 0.0265562, 0, 0.588979, 0.738591, 0.0248844, 0, 0.609671, 0.728719, 0.0233342, 0, 0.630773, 0.719146, 0.0219081, 0, 0.652314, 0.709165, 0.0205711, 0, 0.674328, 0.69875, 0.0193248, 0, 0.696854, 0.687884, 0.0181582, 0, 0.719942, 0.676818, 0.0170746, 0, 0.743651, 0.666247, 0.0160718, 0, 0.768057, 0.655284, 0.0151262, 0, 0.793253, 0.64401, 0.0142561, 0, 0.819363, 0.633353, 0.0134327, 0, 0.846547, 0.622674, 0.012653, 0, 0.875017, 0.612265, 0.0119354, 0, 0.905021, 0.602455, 0.0112533, 0, 0.936508, 0.593147, 0.0106234, 0, 0.968254, 0.583592, 0.0100213, 0, 1, 1, 0.25717, 0, 0, 1, 0.25717, 0, 0, 0.999992, 0.257164, 0, 0, 0.999958, 0.257135, 0, 0.000641715, 0.999864, 0.25706, 0, 0.00305314, 0.999666, 0.256897, 0, 0.00700975, 0.999302, 0.256596, 0, 0.0122194, 0.998663, 0.25607, 0, 0.0184622, 0.995607, 0.254123, 0, 0.0255773, 0.993094, 0.252081, 0, 0.0334439, 0.9907, 0.249867, 0, 0.0419696, 0.98594, 0.246118, 0, 0.0510823, 0.981214, 0.242049, 0, 0.0607242, 0.974966, 0.236869, 0, 0.0708486, 0.967589, 0.230724, 0, 0.081417, 0.95915, 0.223635, 0, 0.0923974, 0.950257, 0.21596, 0, 0.103763, 0.940165, 0.207296, 0, 0.115491, 0.929396, 0.197901, 0, 0.127562, 0.919288, 0.188437, 0, 0.13996, 0.909428, 0.178762, 0, 0.15267, 0.900105, 0.169072, 0, 0.165679, 0.891418, 0.159478, 0, 0.178979, 0.883347, 0.15002, 0, 0.192558, 0.875992, 0.140813, 0, 0.20641, 0.869466, 0.13196, 0, 0.220529, 0.863699, 0.123501, 0, 0.234907, 0.858553, 0.115436, 0, 0.249542, 0.854379, 0.107901, 0, 0.264428, 0.850894, 0.10088, 0, 0.279564, 0.847632, 0.0942296, 0, 0.294947, 0.844571, 0.0879861, 0, 0.310575, 0.84163, 0.0821534, 0, 0.326448, 0.838542, 0.0766409, 0, 0.342566, 0.835412, 0.0715322, 0, 0.358929, 0.831899, 0.0666883, 0, 0.37554, 0.828177, 0.0622175, 0, 0.392399, 0.82416, 0.0580452, 0, 0.409511, 0.820393, 0.054267, 0, 0.426878, 0.816068, 0.0507172, 0, 0.444506, 0.811201, 0.0474041, 0, 0.4624, 0.805785, 0.0443174, 0, 0.480566, 0.799878, 0.0414562, 0, 0.499013, 0.793469, 0.0388147, 0, 0.517749, 0.786473, 0.0363453, 0, 0.536785, 0.778874, 0.0340225, 0, 0.556134, 0.771277, 0.0318599, 0, 0.575809, 0.763426, 0.0298859, 0, 0.595827, 0.755044, 0.0280357, 0, 0.616207, 0.746161, 0.0262979, 0, 0.636973, 0.737124, 0.0247295, 0, 0.65815, 0.72761, 0.0232514, 0, 0.679772, 0.717822, 0.0218755, 0, 0.701876, 0.708279, 0.0205942, 0, 0.724509, 0.698333, 0.0193947, 0, 0.74773, 0.68802, 0.0182717, 0, 0.771609, 0.677321, 0.0172044, 0, 0.79624, 0.666504, 0.0162122, 0, 0.821743, 0.656184, 0.0152924, 0, 0.84828, 0.64556, 0.0144326, 0, 0.876069, 0.634636, 0.0136157, 0, 0.905404, 0.624124, 0.0128612, 0, 0.936508, 0.613914, 0.0121435, 0, 0.968254, 0.603589, 0.0114887, 0, 1, 1, 0.307946, 0, 0, 0.999999, 0.307945, 0, 0, 0.999988, 0.307934, 0, 0.0000204479, 0.999944, 0.307886, 0, 0.00127833, 0.999824, 0.307756, 0, 0.00445047, 0.999565, 0.30748, 0, 0.00914673, 0.999085, 0.306966, 0, 0.0150498, 0.998103, 0.306004, 0, 0.0219367, 0.994249, 0.303028, 0, 0.0296485, 0.991807, 0.300435, 0, 0.038068, 0.987773, 0.296554, 0, 0.0471062, 0.982673, 0.2916, 0, 0.0566942, 0.976623, 0.285641, 0, 0.0667768, 0.968757, 0.27815, 0, 0.0773099, 0.959849, 0.269529, 0, 0.088257, 0.950663, 0.260248, 0, 0.0995879, 0.940129, 0.249704, 0, 0.111277, 0.92895, 0.238291, 0, 0.123304, 0.917996, 0.226501, 0, 0.13565, 0.907813, 0.214669, 0, 0.148299, 0.898305, 0.202835, 0, 0.161237, 0.889626, 0.191158, 0, 0.174455, 0.88175, 0.179695, 0, 0.187941, 0.874715, 0.168548, 0, 0.201687, 0.868746, 0.15792, 0, 0.215687, 0.863703, 0.147807, 0, 0.229933, 0.859315, 0.138149, 0, 0.24442, 0.855538, 0.128993, 0, 0.259145, 0.852428, 0.120414, 0, 0.274103, 0.850168, 0.112498, 0, 0.289293, 0.848132, 0.105054, 0, 0.304711, 0.846291, 0.0981087, 0, 0.320357, 0.844431, 0.0915942, 0, 0.33623, 0.842493, 0.0855056, 0, 0.35233, 0.840368, 0.0798204, 0, 0.368658, 0.83798, 0.0745097, 0, 0.385214, 0.83523, 0.0695424, 0, 0.402002, 0.832091, 0.0649092, 0, 0.419023, 0.828667, 0.0606291, 0, 0.436282, 0.824805, 0.0566523, 0, 0.453782, 0.820988, 0.0530229, 0, 0.471529, 0.816635, 0.0496364, 0, 0.489528, 0.811725, 0.0464658, 0, 0.507788, 0.806316, 0.0435082, 0, 0.526317, 0.800469, 0.0407873, 0, 0.545124, 0.794107, 0.038255, 0, 0.564221, 0.787218, 0.0358825, 0, 0.583621, 0.779872, 0.0336785, 0, 0.603341, 0.772097, 0.0316379, 0, 0.623397, 0.764484, 0.0297379, 0, 0.643812, 0.756428, 0.0279581, 0, 0.664611, 0.748022, 0.0263153, 0, 0.685824, 0.739268, 0.0247799, 0, 0.707488, 0.73024, 0.0233385, 0, 0.729646, 0.720893, 0.0220035, 0, 0.752354, 0.71119, 0.0207555, 0, 0.77568, 0.701791, 0.0195843, 0, 0.799715, 0.692184, 0.0184891, 0, 0.824574, 0.682258, 0.0174541, 0, 0.850417, 0.67206, 0.0164873, 0, 0.877466, 0.661717, 0.0155959, 0, 0.90604, 0.651462, 0.0147519, 0, 0.936528, 0.641467, 0.0139727, 0, 0.968254, 0.631229, 0.0132363, 0, 1, 1, 0.367573, 0, 0, 0.999999, 0.367571, 0, 0, 0.999984, 0.367553, 0, 0.000183382, 0.999925, 0.367473, 0, 0.00225254, 0.999759, 0.367259, 0, 0.00628165, 0.99941, 0.366801, 0, 0.0117858, 0.998739, 0.365946, 0, 0.0184359, 0.995529, 0.363191, 0, 0.0260114, 0.992875, 0.360171, 0, 0.0343581, 0.989135, 0.355981, 0, 0.0433637, 0.984166, 0.350401, 0, 0.0529438, 0.977871, 0.343348, 0, 0.0630334, 0.96951, 0.334341, 0, 0.0735805, 0.959964, 0.323862, 0, 0.0845437, 0.950162, 0.312521, 0, 0.095889, 0.938882, 0.299577, 0, 0.107588, 0.926992, 0.285573, 0, 0.119617, 0.915589, 0.271212, 0, 0.131957, 0.904791, 0.256611, 0, 0.144591, 0.895177, 0.242224, 0, 0.157503, 0.886403, 0.227952, 0, 0.170682, 0.878957, 0.214192, 0, 0.184117, 0.872418, 0.200795, 0, 0.197799, 0.867029, 0.188015, 0, 0.21172, 0.862835, 0.175975, 0, 0.225873, 0.859411, 0.164526, 0, 0.240253, 0.856655, 0.153693, 0, 0.254854, 0.854519, 0.14352, 0, 0.269673, 0.852828, 0.13397, 0, 0.284707, 0.851412, 0.124984, 0, 0.299953, 0.850609, 0.116748, 0, 0.315408, 0.849855, 0.10905, 0, 0.331073, 0.849017, 0.101839, 0, 0.346946, 0.848079, 0.0951359, 0, 0.363028, 0.846911, 0.0888774, 0, 0.379318, 0.845445, 0.0830375, 0, 0.395818, 0.84362, 0.0775844, 0, 0.41253, 0.841411, 0.0725054, 0, 0.429457, 0.838768, 0.0677691, 0, 0.446602, 0.835801, 0.0634016, 0, 0.463968, 0.832341, 0.0593095, 0, 0.481561, 0.828424, 0.0555121, 0, 0.499386, 0.824312, 0.052024, 0, 0.51745, 0.819918, 0.0487865, 0, 0.535761, 0.815072, 0.0457801, 0, 0.554328, 0.809863, 0.0430184, 0, 0.573162, 0.804164, 0.0404245, 0, 0.592275, 0.798034, 0.0380146, 0, 0.611681, 0.791436, 0.0357436, 0, 0.631398, 0.784498, 0.0336475, 0, 0.651445, 0.777125, 0.0316666, 0, 0.671845, 0.769365, 0.0298122, 0, 0.692628, 0.761579, 0.0281001, 0, 0.713827, 0.753746, 0.0265049, 0, 0.735484, 0.745573, 0.0250067, 0, 0.75765, 0.737083, 0.0236026, 0, 0.78039, 0.728545, 0.0223302, 0, 0.803789, 0.719691, 0.0211243, 0, 0.82796, 0.710569, 0.0199983, 0, 0.853056, 0.701216, 0.0189569, 0, 0.879298, 0.692094, 0.0179702, 0, 0.907014, 0.682909, 0.0170418, 0, 0.936691, 0.673509, 0.0161732, 0, 0.968254, 0.663863, 0.0153406, 0, 1, 1, 0.437395, 0, 0, 0.999998, 0.437394, 0, 0, 0.99998, 0.437363, 0, 0.000616704, 0.999891, 0.437232, 0, 0.00367925, 0.999656, 0.436877, 0, 0.00867446, 0.999148, 0.436121, 0, 0.0150679, 0.997959, 0.434564, 0, 0.022531, 0.993464, 0.430134, 0, 0.0308507, 0.990606, 0.426077, 0, 0.0398805, 0.985027, 0.419397, 0, 0.0495148, 0.978491, 0.41118, 0, 0.0596749, 0.969643, 0.40048, 0, 0.0703001, 0.959189, 0.38769, 0, 0.0813427, 0.948223, 0.373575, 0, 0.0927641, 0.935955, 0.357622, 0, 0.104533, 0.923237, 0.34043, 0, 0.116624, 0.911074, 0.322735, 0, 0.129015, 0.899724, 0.30479, 0, 0.141687, 0.890189, 0.287392, 0, 0.154626, 0.881796, 0.270248, 0, 0.167818, 0.874781, 0.253659, 0, 0.181252, 0.869166, 0.237786, 0, 0.194918, 0.864725, 0.222618, 0, 0.208807, 0.861565, 0.208356, 0, 0.222913, 0.859284, 0.194867, 0, 0.237229, 0.857677, 0.18212, 0, 0.25175, 0.856714, 0.17018, 0, 0.266473, 0.856155, 0.158969, 0, 0.281392, 0.8558, 0.148413, 0, 0.296505, 0.855672, 0.138578, 0, 0.311811, 0.855538, 0.129345, 0, 0.327306, 0.855689, 0.120861, 0, 0.342991, 0.855767, 0.112969, 0, 0.358864, 0.855618, 0.105593, 0, 0.374925, 0.85525, 0.0987451, 0, 0.391176, 0.854583, 0.0923727, 0, 0.407616, 0.853534, 0.0864143, 0, 0.424249, 0.852061, 0.0808338, 0, 0.441076, 0.850253, 0.0756771, 0, 0.4581, 0.848004, 0.0708612, 0, 0.475324, 0.845333, 0.0663784, 0, 0.492754, 0.842376, 0.0622631, 0, 0.510394, 0.838956, 0.0584112, 0, 0.528251, 0.835121, 0.0548328, 0, 0.546331, 0.830842, 0.0514838, 0, 0.564644, 0.826212, 0.048355, 0, 0.583198, 0.821522, 0.0454714, 0, 0.602005, 0.816551, 0.0428263, 0, 0.621078, 0.811211, 0.0403612, 0, 0.640434, 0.805479, 0.038039, 0, 0.660089, 0.799409, 0.0358739, 0, 0.680066, 0.79306, 0.0338727, 0, 0.70039, 0.786395, 0.0319985, 0, 0.721094, 0.779416, 0.030241, 0, 0.742215, 0.77214, 0.0285951, 0, 0.7638, 0.764636, 0.0270747, 0, 0.785912, 0.756836, 0.0256354, 0, 0.808628, 0.749315, 0.0243027, 0, 0.832055, 0.741561, 0.0230497, 0, 0.856338, 0.733589, 0.0218801, 0, 0.88169, 0.725479, 0.020784, 0, 0.908441, 0.717255, 0.0197702, 0, 0.937125, 0.708829, 0.0188168, 0, 0.968254, 0.700191, 0.0179113, 0, 1, 1, 0.518937, 0, 0, 0.999998, 0.518933, 0, 0, 0.999967, 0.518883, 0, 0.00147741, 0.999832, 0.51866, 0, 0.00573221, 0.999466, 0.518057, 0, 0.011826, 0.998644, 0.516752, 0, 0.0192116, 0.994458, 0.512347, 0, 0.027573, 0.991223, 0.507675, 0, 0.0367099, 0.985515, 0.500188, 0, 0.046487, 0.978308, 0.490408, 0, 0.0568071, 0.968359, 0.477357, 0, 0.0675984, 0.95682, 0.461752, 0, 0.0788059, 0.943929, 0.443796, 0, 0.090386, 0.930224, 0.423893, 0, 0.102304, 0.916514, 0.402682, 0, 0.114532, 0.903653, 0.380914, 0, 0.127047, 0.892315, 0.359212, 0, 0.139828, 0.882942, 0.338102, 0, 0.152861, 0.875438, 0.31773, 0, 0.16613, 0.869642, 0.298186, 0, 0.179624, 0.865304, 0.279491, 0, 0.193332, 0.862382, 0.261804, 0, 0.207247, 0.860666, 0.245146, 0, 0.22136, 0.859788, 0.229406, 0, 0.235666, 0.859608, 0.214605, 0, 0.250158, 0.859912, 0.200691, 0, 0.264832, 0.86053, 0.187623, 0, 0.279684, 0.861368, 0.17539, 0, 0.294711, 0.862237, 0.163901, 0, 0.309911, 0.863127, 0.153175, 0, 0.32528, 0.863923, 0.143147, 0, 0.340819, 0.864567, 0.133781, 0, 0.356524, 0.865013, 0.125042, 0, 0.372397, 0.86539, 0.116952, 0, 0.388438, 0.865591, 0.109476, 0, 0.404645, 0.865517, 0.102542, 0, 0.421022, 0.865084, 0.0960688, 0, 0.437569, 0.864309, 0.0900499, 0, 0.454287, 0.863151, 0.0844328, 0, 0.471181, 0.861649, 0.0792218, 0, 0.488253, 0.859742, 0.0743482, 0, 0.505507, 0.857446, 0.0697963, 0, 0.522947, 0.854757, 0.0655364, 0, 0.54058, 0.851783, 0.061608, 0, 0.558412, 0.848516, 0.0579701, 0, 0.576449, 0.844897, 0.0545742, 0, 0.594701, 0.840956, 0.0514167, 0, 0.613178, 0.836676, 0.0484598, 0, 0.631892, 0.832075, 0.0456934, 0, 0.650856, 0.827191, 0.0431178, 0, 0.670088, 0.822295, 0.0407718, 0, 0.689606, 0.817294, 0.0386032, 0, 0.709434, 0.812013, 0.0365675, 0, 0.7296, 0.806465, 0.0346547, 0, 0.750138, 0.800691, 0.0328717, 0, 0.771093, 0.794709, 0.031211, 0, 0.792519, 0.788493, 0.0296504, 0, 0.814488, 0.782049, 0.0281782, 0, 0.837097, 0.775403, 0.0267965, 0, 0.860481, 0.76857, 0.0255002, 0, 0.884842, 0.761536, 0.0242759, 0, 0.910494, 0.754303, 0.0231142, 0, 0.937985, 0.74692, 0.0220305, 0, 0.968254, 0.739745, 0.0210192, 0, 1, 1, 0.613914, 0, 0, 0.999996, 0.613907, 0, 0.0000963597, 0.999942, 0.613814, 0, 0.00301247, 0.999704, 0.613407, 0, 0.00870385, 0.999046, 0.612302, 0, 0.0160714, 0.995516, 0.608266, 0, 0.0245899, 0.991726, 0.602863, 0, 0.0339681, 0.985157, 0.593956, 0, 0.0440254, 0.97642, 0.581748, 0, 0.0546409, 0.964404, 0.565183, 0, 0.0657284, 0.950601, 0.545273, 0, 0.0772246, 0.935158, 0.522129, 0, 0.0890812, 0.919364, 0.496782, 0, 0.10126, 0.904754, 0.470571, 0, 0.113731, 0.89176, 0.444037, 0, 0.126469, 0.881492, 0.418322, 0, 0.139454, 0.873656, 0.393522, 0, 0.15267, 0.868053, 0.369795, 0, 0.166101, 0.864336, 0.347171, 0, 0.179736, 0.862259, 0.325737, 0, 0.193565, 0.861556, 0.305532, 0, 0.207578, 0.861776, 0.286416, 0, 0.221769, 0.862661, 0.268355, 0, 0.23613, 0.864015, 0.251334, 0, 0.250656, 0.865711, 0.235352, 0, 0.265343, 0.867519, 0.220302, 0, 0.280187, 0.869351, 0.206161, 0, 0.295183, 0.871144, 0.192908, 0, 0.31033, 0.872839, 0.180505, 0, 0.325624, 0.874307, 0.168848, 0, 0.341065, 0.875667, 0.158021, 0, 0.35665, 0.876758, 0.147877, 0, 0.37238, 0.87764, 0.138441, 0, 0.388253, 0.878237, 0.129627, 0, 0.404269, 0.878563, 0.121415, 0, 0.42043, 0.878572, 0.113741, 0, 0.436735, 0.87842, 0.106652, 0, 0.453187, 0.878057, 0.100097, 0, 0.469786, 0.877413, 0.0940128, 0, 0.486536, 0.87646, 0.0883462, 0, 0.503439, 0.875233, 0.0830924, 0, 0.520498, 0.8737, 0.0781975, 0, 0.537717, 0.871873, 0.07364, 0, 0.555102, 0.86978, 0.0694103, 0, 0.572657, 0.867405, 0.0654696, 0, 0.59039, 0.864751, 0.0617914, 0, 0.608307, 0.861818, 0.0583491, 0, 0.626419, 0.858645, 0.0551443, 0, 0.644733, 0.855307, 0.0521894, 0, 0.663264, 0.851736, 0.0494334, 0, 0.682025, 0.847927, 0.0468504, 0, 0.701032, 0.843888, 0.0444261, 0, 0.720308, 0.839629, 0.0421497, 0, 0.739875, 0.835158, 0.0400082, 0, 0.759764, 0.830509, 0.0380076, 0, 0.780014, 0.825714, 0.0361488, 0, 0.800673, 0.820729, 0.0343956, 0, 0.821803, 0.815751, 0.0327781, 0, 0.843492, 0.810752, 0.031275, 0, 0.86586, 0.805587, 0.0298542, 0, 0.889087, 0.800317, 0.0285397, 0, 0.913466, 0.79489, 0.0272948, 0, 0.93952, 0.789314, 0.0261139, 0, 0.96835, 0.783593, 0.0249938, 0, 1, 1, 0.724258, 0, 0, 0.999992, 0.724243, 0, 0.000726889, 0.99987, 0.724044, 0, 0.00569574, 0.999336, 0.72317, 0, 0.0131702, 0.996271, 0.719432, 0, 0.0220738, 0.991159, 0.712576, 0, 0.0319405, 0.982465, 0.700927, 0, 0.0425202, 0.97049, 0.684297, 0, 0.0536599, 0.953973, 0.661244, 0, 0.065258, 0.935546, 0.633804, 0, 0.0772427, 0.916596, 0.603071, 0, 0.0895616, 0.899353, 0.57105, 0, 0.102175, 0.885216, 0.539206, 0, 0.11505, 0.875076, 0.508714, 0, 0.128164, 0.868334, 0.479571, 0, 0.141495, 0.864414, 0.451796, 0, 0.155026, 0.862678, 0.425328, 0, 0.168745, 0.862835, 0.400352, 0, 0.182639, 0.864067, 0.376532, 0, 0.196699, 0.866086, 0.35391, 0, 0.210915, 0.868557, 0.332424, 0, 0.225282, 0.871271, 0.312053, 0, 0.239792, 0.874058, 0.292764, 0, 0.25444, 0.8768, 0.27453, 0, 0.269223, 0.87939, 0.257297, 0, 0.284135, 0.8819, 0.24114, 0, 0.299174, 0.884187, 0.225934, 0, 0.314337, 0.886262, 0.211669, 0, 0.329622, 0.888119, 0.198311, 0, 0.345026, 0.889709, 0.185783, 0, 0.360549, 0.891054, 0.174063, 0, 0.376189, 0.892196, 0.163143, 0, 0.391946, 0.893101, 0.152952, 0, 0.407819, 0.893803, 0.143475, 0, 0.423808, 0.894277, 0.134647, 0, 0.439914, 0.894532, 0.126434, 0, 0.456137, 0.894576, 0.1188, 0, 0.472479, 0.894393, 0.111694, 0, 0.48894, 0.893976, 0.105069, 0, 0.505523, 0.893346, 0.0989077, 0, 0.52223, 0.892502, 0.0931724, 0, 0.539064, 0.891441, 0.0878276, 0, 0.556028, 0.890276, 0.082903, 0, 0.573125, 0.888972, 0.0783505, 0, 0.590361, 0.887469, 0.0741083, 0, 0.607741, 0.885785, 0.0701633, 0, 0.62527, 0.883914, 0.0664835, 0, 0.642957, 0.881872, 0.0630567, 0, 0.660809, 0.879651, 0.0598527, 0, 0.678836, 0.877267, 0.0568615, 0, 0.69705, 0.874717, 0.05406, 0, 0.715465, 0.872012, 0.0514378, 0, 0.734098, 0.869157, 0.0489805, 0, 0.752968, 0.866155, 0.0466727, 0, 0.772101, 0.863014, 0.0445056, 0, 0.791529, 0.859748, 0.0424733, 0, 0.81129, 0.856416, 0.0405957, 0, 0.831438, 0.852958, 0.0388273, 0, 0.852044, 0.849382, 0.0371619, 0, 0.87321, 0.845694, 0.0355959, 0, 0.89509, 0.841893, 0.0341155, 0, 0.917932, 0.837981, 0.0327141, 0, 0.942204, 0.833963, 0.0313856, 0, 0.968981, 0.829847, 0.0301275, 0, 1, 1, 0.85214, 0, 0, 0.999969, 0.852095, 0, 0.00279627, 0.999483, 0.851408, 0, 0.0107635, 0.994545, 0.84579, 0, 0.0206454, 0.986188, 0.835231, 0, 0.0315756, 0.969847, 0.814687, 0, 0.0432021, 0.945951, 0.783735, 0, 0.0553396, 0.91917, 0.746074, 0, 0.0678766, 0.895488, 0.706938, 0, 0.0807395, 0.878232, 0.669534, 0, 0.0938767, 0.868252, 0.635168, 0, 0.10725, 0.863873, 0.603069, 0, 0.120832, 0.863369, 0.572514, 0, 0.134598, 0.86545, 0.543169, 0, 0.148533, 0.868803, 0.514578, 0, 0.16262, 0.872794, 0.486762, 0, 0.176849, 0.87702, 0.459811, 0, 0.19121, 0.881054, 0.433654, 0, 0.205694, 0.884974, 0.408574, 0, 0.220294, 0.888587, 0.384525, 0, 0.235005, 0.891877, 0.36156, 0, 0.24982, 0.894793, 0.339661, 0, 0.264737, 0.89743, 0.318913, 0, 0.279751, 0.899796, 0.299302, 0, 0.294859, 0.901943, 0.280843, 0, 0.310058, 0.903858, 0.263481, 0, 0.325346, 0.905574, 0.247197, 0, 0.340721, 0.907069, 0.231915, 0, 0.356181, 0.908379, 0.217614, 0, 0.371725, 0.90952, 0.20425, 0, 0.387353, 0.910483, 0.191758, 0, 0.403063, 0.91128, 0.180092, 0, 0.418854, 0.911936, 0.169222, 0, 0.434727, 0.912454, 0.159098, 0, 0.450682, 0.912835, 0.149668, 0, 0.466718, 0.913078, 0.140884, 0, 0.482837, 0.913192, 0.132709, 0, 0.499038, 0.913175, 0.125095, 0, 0.515324, 0.91304, 0.118012, 0, 0.531695, 0.912781, 0.111417, 0, 0.548153, 0.91241, 0.105281, 0, 0.5647, 0.911924, 0.0995691, 0, 0.581338, 0.911331, 0.0942531, 0, 0.59807, 0.910637, 0.0893076, 0, 0.6149, 0.90984, 0.0846998, 0, 0.63183, 0.908941, 0.0804044, 0, 0.648865, 0.907944, 0.0763984, 0, 0.666011, 0.906857, 0.0726638, 0, 0.683273, 0.90568, 0.0691783, 0, 0.700659, 0.904416, 0.0659222, 0, 0.718176, 0.903067, 0.0628782, 0, 0.735834, 0.901637, 0.0600307, 0, 0.753646, 0.900128, 0.0573647, 0, 0.771625, 0.898544, 0.0548668, 0, 0.78979, 0.89689, 0.052527, 0, 0.808162, 0.895165, 0.0503306, 0, 0.826771, 0.893371, 0.0482668, 0, 0.845654, 0.891572, 0.0463605, 0, 0.864863, 0.889763, 0.0445998, 0, 0.884472, 0.887894, 0.0429451, 0, 0.904592, 0.885967, 0.0413884, 0, 0.925407, 0.883984, 0.0399225, 0, 0.947271, 0.881945, 0.0385405, 0, 0.97105, 0.879854, 0.0372362, 0, 1, 0.999804, 0.995833, 0, 0, 0.938155, 0.933611, 0, 0.0158731, 0.864755, 0.854311, 0, 0.0317461, 0.888594, 0.865264, 0, 0.0476191, 0.905575, 0.863922, 0, 0.0634921, 0.915125, 0.850558, 0, 0.0793651, 0.920665, 0.829254, 0, 0.0952381, 0.924073, 0.802578, 0, 0.111111, 0.926304, 0.772211, 0, 0.126984, 0.927829, 0.739366, 0, 0.142857, 0.928924, 0.705033, 0, 0.15873, 0.92973, 0.670019, 0, 0.174603, 0.930339, 0.634993, 0, 0.190476, 0.930811, 0.600485, 0, 0.206349, 0.931191, 0.566897, 0, 0.222222, 0.93149, 0.534485, 0, 0.238095, 0.931737, 0.503429, 0, 0.253968, 0.931939, 0.473811, 0, 0.269841, 0.932108, 0.445668, 0, 0.285714, 0.93225, 0.418993, 0, 0.301587, 0.932371, 0.393762, 0, 0.31746, 0.932474, 0.369939, 0, 0.333333, 0.932562, 0.347479, 0, 0.349206, 0.932638, 0.326336, 0, 0.365079, 0.932703, 0.306462, 0, 0.380952, 0.93276, 0.287805, 0, 0.396825, 0.932809, 0.270313, 0, 0.412698, 0.932851, 0.253933, 0, 0.428571, 0.932887, 0.23861, 0, 0.444444, 0.932917, 0.224289, 0, 0.460317, 0.932943, 0.210917, 0, 0.47619, 0.932965, 0.19844, 0, 0.492063, 0.932982, 0.186807, 0, 0.507937, 0.932995, 0.175966, 0, 0.52381, 0.933005, 0.165869, 0, 0.539683, 0.933011, 0.156468, 0, 0.555556, 0.933013, 0.147719, 0, 0.571429, 0.933013, 0.139579, 0, 0.587302, 0.93301, 0.132007, 0, 0.603175, 0.933004, 0.124965, 0, 0.619048, 0.932994, 0.118416, 0, 0.634921, 0.932982, 0.112326, 0, 0.650794, 0.932968, 0.106663, 0, 0.666667, 0.93295, 0.101397, 0, 0.68254, 0.932931, 0.0964993, 0, 0.698413, 0.932908, 0.0919438, 0, 0.714286, 0.932883, 0.0877057, 0, 0.730159, 0.932856, 0.0837623, 0, 0.746032, 0.932827, 0.0800921, 0, 0.761905, 0.932796, 0.0766754, 0, 0.777778, 0.932762, 0.0734936, 0, 0.793651, 0.932727, 0.0705296, 0, 0.809524, 0.932689, 0.0677676, 0, 0.825397, 0.93265, 0.0651929, 0, 0.84127, 0.932609, 0.0627917, 0, 0.857143, 0.932565, 0.0605515, 0, 0.873016, 0.932521, 0.0584606, 0, 0.888889, 0.932474, 0.0565082, 0, 0.904762, 0.932427, 0.0546841, 0, 0.920635, 0.932377, 0.0529793, 0, 0.936508, 0.932326, 0.0513851, 0, 0.952381, 0.932274, 0.0498936, 0, 0.968254, 0.93222, 0.0484975, 0, 0.984127, 0.932164, 0.0471899, 0, 1]; + const ltc_float_1 = new Float32Array(LTC_MAT_1); + const ltc_float_2 = new Float32Array(LTC_MAT_2); + const LTC_FLOAT_1 = new DataTexture(ltc_float_1, 64, 64, RGBAFormat, FloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); + const LTC_FLOAT_2 = new DataTexture(ltc_float_2, 64, 64, RGBAFormat, FloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); + LTC_FLOAT_1.needsUpdate = true; + LTC_FLOAT_2.needsUpdate = true; + const ltc_half_1 = new Uint16Array(LTC_MAT_1.length); + LTC_MAT_1.forEach(function(x2, index2) { + ltc_half_1[index2] = DataUtils.toHalfFloat(x2); + }); + const ltc_half_2 = new Uint16Array(LTC_MAT_2.length); + LTC_MAT_2.forEach(function(x2, index2) { + ltc_half_2[index2] = DataUtils.toHalfFloat(x2); + }); + const LTC_HALF_1 = new DataTexture(ltc_half_1, 64, 64, RGBAFormat, HalfFloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); + const LTC_HALF_2 = new DataTexture(ltc_half_2, 64, 64, RGBAFormat, HalfFloatType, UVMapping, ClampToEdgeWrapping, ClampToEdgeWrapping, LinearFilter, NearestFilter, 1); + LTC_HALF_1.needsUpdate = true; + LTC_HALF_2.needsUpdate = true; + this.LTC_HALF_1 = LTC_HALF_1; + this.LTC_HALF_2 = LTC_HALF_2; + this.LTC_FLOAT_1 = LTC_FLOAT_1; + this.LTC_FLOAT_2 = LTC_FLOAT_2; + return this; + } +} +RectAreaLightTexturesLib.LTC_HALF_1 = null; +RectAreaLightTexturesLib.LTC_HALF_1 = null; +RectAreaLightTexturesLib.LTC_FLOAT_1 = null; +RectAreaLightTexturesLib.LTC_FLOAT_2 = null; +// node_modules/three/examples/jsm/lines/LineSegmentsGeometry.js +var _box2 = new Box3; +var _vector7 = new Vector3; + +// node_modules/three/examples/jsm/lines/LineMaterial.js +UniformsLib.line = { + worldUnits: { value: 1 }, + linewidth: { value: 1 }, + resolution: { value: new Vector2(1, 1) }, + dashOffset: { value: 0 }, + dashScale: { value: 1 }, + dashSize: { value: 1 }, + gapSize: { value: 1 } +}; +ShaderLib["line"] = { + uniforms: UniformsUtils.merge([ + UniformsLib.common, + UniformsLib.fog, + UniformsLib.line + ]), + vertexShader: ` + #include + #include + #include + #include + #include + + uniform float linewidth; + uniform vec2 resolution; + + attribute vec3 instanceStart; + attribute vec3 instanceEnd; + + attribute vec3 instanceColorStart; + attribute vec3 instanceColorEnd; + + #ifdef WORLD_UNITS + + varying vec4 worldPos; + varying vec3 worldStart; + varying vec3 worldEnd; + + #ifdef USE_DASH + + varying vec2 vUv; + + #endif + + #else + + varying vec2 vUv; + + #endif + + #ifdef USE_DASH + + uniform float dashScale; + attribute float instanceDistanceStart; + attribute float instanceDistanceEnd; + varying float vLineDistance; + + #endif + + void trimSegment( const in vec4 start, inout vec4 end ) { + + // trim end segment so it terminates between the camera plane and the near plane + + // conservative estimate of the near plane + float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column + float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column + float nearEstimate = - 0.5 * b / a; + + float alpha = ( nearEstimate - start.z ) / ( end.z - start.z ); + + end.xyz = mix( start.xyz, end.xyz, alpha ); + + } + + void main() { + + #ifdef USE_COLOR + + vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd; + + #endif + + #ifdef USE_DASH + + vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd; + vUv = uv; + + #endif + + float aspect = resolution.x / resolution.y; + + // camera space + vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 ); + vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 ); + + #ifdef WORLD_UNITS + + worldStart = start.xyz; + worldEnd = end.xyz; + + #else + + vUv = uv; + + #endif + + // special case for perspective projection, and segments that terminate either in, or behind, the camera plane + // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space + // but we need to perform ndc-space calculations in the shader, so we must address this issue directly + // perhaps there is a more elegant solution -- WestLangley + + bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column + + if ( perspective ) { + + if ( start.z < 0.0 && end.z >= 0.0 ) { + + trimSegment( start, end ); + + } else if ( end.z < 0.0 && start.z >= 0.0 ) { + + trimSegment( end, start ); + + } + + } + + // clip space + vec4 clipStart = projectionMatrix * start; + vec4 clipEnd = projectionMatrix * end; + + // ndc space + vec3 ndcStart = clipStart.xyz / clipStart.w; + vec3 ndcEnd = clipEnd.xyz / clipEnd.w; + + // direction + vec2 dir = ndcEnd.xy - ndcStart.xy; + + // account for clip-space aspect ratio + dir.x *= aspect; + dir = normalize( dir ); + + #ifdef WORLD_UNITS + + vec3 worldDir = normalize( end.xyz - start.xyz ); + vec3 tmpFwd = normalize( mix( start.xyz, end.xyz, 0.5 ) ); + vec3 worldUp = normalize( cross( worldDir, tmpFwd ) ); + vec3 worldFwd = cross( worldDir, worldUp ); + worldPos = position.y < 0.5 ? start: end; + + // height offset + float hw = linewidth * 0.5; + worldPos.xyz += position.x < 0.0 ? hw * worldUp : - hw * worldUp; + + // don't extend the line if we're rendering dashes because we + // won't be rendering the endcaps + #ifndef USE_DASH + + // cap extension + worldPos.xyz += position.y < 0.5 ? - hw * worldDir : hw * worldDir; + + // add width to the box + worldPos.xyz += worldFwd * hw; + + // endcaps + if ( position.y > 1.0 || position.y < 0.0 ) { + + worldPos.xyz -= worldFwd * 2.0 * hw; + + } + + #endif + + // project the worldpos + vec4 clip = projectionMatrix * worldPos; + + // shift the depth of the projected points so the line + // segments overlap neatly + vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd; + clip.z = clipPose.z * clip.w; + + #else + + vec2 offset = vec2( dir.y, - dir.x ); + // undo aspect ratio adjustment + dir.x /= aspect; + offset.x /= aspect; + + // sign flip + if ( position.x < 0.0 ) offset *= - 1.0; + + // endcaps + if ( position.y < 0.0 ) { + + offset += - dir; + + } else if ( position.y > 1.0 ) { + + offset += dir; + + } + + // adjust for linewidth + offset *= linewidth; + + // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ... + offset /= resolution.y; + + // select end + vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd; + + // back to clip space + offset *= clip.w; + + clip.xy += offset; + + #endif + + gl_Position = clip; + + vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation + + #include + #include + #include + + } + `, + fragmentShader: ` + uniform vec3 diffuse; + uniform float opacity; + uniform float linewidth; + + #ifdef USE_DASH + + uniform float dashOffset; + uniform float dashSize; + uniform float gapSize; + + #endif + + varying float vLineDistance; + + #ifdef WORLD_UNITS + + varying vec4 worldPos; + varying vec3 worldStart; + varying vec3 worldEnd; + + #ifdef USE_DASH + + varying vec2 vUv; + + #endif + + #else + + varying vec2 vUv; + + #endif + + #include + #include + #include + #include + #include + + vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) { + + float mua; + float mub; + + vec3 p13 = p1 - p3; + vec3 p43 = p4 - p3; + + vec3 p21 = p2 - p1; + + float d1343 = dot( p13, p43 ); + float d4321 = dot( p43, p21 ); + float d1321 = dot( p13, p21 ); + float d4343 = dot( p43, p43 ); + float d2121 = dot( p21, p21 ); + + float denom = d2121 * d4343 - d4321 * d4321; + + float numer = d1343 * d4321 - d1321 * d4343; + + mua = numer / denom; + mua = clamp( mua, 0.0, 1.0 ); + mub = ( d1343 + d4321 * ( mua ) ) / d4343; + mub = clamp( mub, 0.0, 1.0 ); + + return vec2( mua, mub ); + + } + + void main() { + + #include + + #ifdef USE_DASH + + if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps + + if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX + + #endif + + float alpha = opacity; + + #ifdef WORLD_UNITS + + // Find the closest points on the view ray and the line segment + vec3 rayEnd = normalize( worldPos.xyz ) * 1e5; + vec3 lineDir = worldEnd - worldStart; + vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd ); + + vec3 p1 = worldStart + lineDir * params.x; + vec3 p2 = rayEnd * params.y; + vec3 delta = p1 - p2; + float len = length( delta ); + float norm = len / linewidth; + + #ifndef USE_DASH + + #ifdef USE_ALPHA_TO_COVERAGE + + float dnorm = fwidth( norm ); + alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm ); + + #else + + if ( norm > 0.5 ) { + + discard; + + } + + #endif + + #endif + + #else + + #ifdef USE_ALPHA_TO_COVERAGE + + // artifacts appear on some hardware if a derivative is taken within a conditional + float a = vUv.x; + float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; + float len2 = a * a + b * b; + float dlen = fwidth( len2 ); + + if ( abs( vUv.y ) > 1.0 ) { + + alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 ); + + } + + #else + + if ( abs( vUv.y ) > 1.0 ) { + + float a = vUv.x; + float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0; + float len2 = a * a + b * b; + + if ( len2 > 1.0 ) discard; + + } + + #endif + + #endif + + vec4 diffuseColor = vec4( diffuse, alpha ); + + #include + #include + + gl_FragColor = vec4( diffuseColor.rgb, alpha ); + + #include + #include + #include + #include + + } + ` +}; + +// node_modules/three/examples/jsm/lines/LineSegments2.js +var _viewport = new Vector4; +var _start2 = new Vector3; +var _end2 = new Vector3; +var _start4 = new Vector4; +var _end4 = new Vector4; +var _ssOrigin = new Vector4; +var _ssOrigin3 = new Vector3; +var _mvMatrix = new Matrix4; +var _line = new Line3; +var _closestPoint2 = new Vector3; +var _box4 = new Box3; +var _sphere2 = new Sphere; +var _clipToWorldVector = new Vector4; +// node_modules/three/examples/jsm/lines/Wireframe.js +var _start3 = new Vector3; +var _end3 = new Vector3; +var _viewport2 = new Vector4; +// node_modules/three/examples/jsm/loaders/3DMLoader.js +var _taskCache = new WeakMap; +// node_modules/three/examples/jsm/loaders/DRACOLoader.js +var _taskCache2 = new WeakMap; +// node_modules/three/examples/jsm/loaders/FBXLoader.js +var tempEuler = new Euler; +var tempVec = new Vector3; +// node_modules/three/examples/jsm/loaders/GLTFLoader.js +class GLTFLoader extends Loader { + constructor(manager) { + super(manager); + this.dracoLoader = null; + this.ktx2Loader = null; + this.meshoptDecoder = null; + this.pluginCallbacks = []; + this.register(function(parser) { + return new GLTFMaterialsClearcoatExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsDispersionExtension2(parser); + }); + this.register(function(parser) { + return new GLTFTextureBasisUExtension(parser); + }); + this.register(function(parser) { + return new GLTFTextureWebPExtension(parser); + }); + this.register(function(parser) { + return new GLTFTextureAVIFExtension(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsSheenExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsTransmissionExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsVolumeExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsIorExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsEmissiveStrengthExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsSpecularExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsIridescenceExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsAnisotropyExtension2(parser); + }); + this.register(function(parser) { + return new GLTFMaterialsBumpExtension2(parser); + }); + this.register(function(parser) { + return new GLTFLightsExtension(parser); + }); + this.register(function(parser) { + return new GLTFMeshoptCompression(parser); + }); + this.register(function(parser) { + return new GLTFMeshGpuInstancing2(parser); + }); + } + load(url, onLoad, onProgress, onError) { + const scope = this; + let resourcePath; + if (this.resourcePath !== "") { + resourcePath = this.resourcePath; + } else if (this.path !== "") { + const relativeUrl = LoaderUtils.extractUrlBase(url); + resourcePath = LoaderUtils.resolveURL(relativeUrl, this.path); + } else { + resourcePath = LoaderUtils.extractUrlBase(url); + } + this.manager.itemStart(url); + const _onError = function(e) { + if (onError) { + onError(e); + } else { + console.error(e); + } + scope.manager.itemError(url); + scope.manager.itemEnd(url); + }; + const loader = new FileLoader(this.manager); + loader.setPath(this.path); + loader.setResponseType("arraybuffer"); + loader.setRequestHeader(this.requestHeader); + loader.setWithCredentials(this.withCredentials); + loader.load(url, function(data2) { + try { + scope.parse(data2, resourcePath, function(gltf) { + onLoad(gltf); + scope.manager.itemEnd(url); + }, _onError); + } catch (e) { + _onError(e); + } + }, onProgress, _onError); + } + setDRACOLoader(dracoLoader) { + this.dracoLoader = dracoLoader; + return this; + } + setKTX2Loader(ktx2Loader) { + this.ktx2Loader = ktx2Loader; + return this; + } + setMeshoptDecoder(meshoptDecoder) { + this.meshoptDecoder = meshoptDecoder; + return this; + } + register(callback) { + if (this.pluginCallbacks.indexOf(callback) === -1) { + this.pluginCallbacks.push(callback); + } + return this; + } + unregister(callback) { + if (this.pluginCallbacks.indexOf(callback) !== -1) { + this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); + } + return this; + } + parse(data2, path, onLoad, onError) { + let json; + const extensions = {}; + const plugins = {}; + const textDecoder = new TextDecoder; + if (typeof data2 === "string") { + json = JSON.parse(data2); + } else if (data2 instanceof ArrayBuffer) { + const magic = textDecoder.decode(new Uint8Array(data2, 0, 4)); + if (magic === BINARY_EXTENSION_HEADER_MAGIC) { + try { + extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data2); + } catch (error) { + if (onError) + onError(error); + return; + } + json = JSON.parse(extensions[EXTENSIONS.KHR_BINARY_GLTF].content); + } else { + json = JSON.parse(textDecoder.decode(data2)); + } + } else { + json = data2; + } + if (json.asset === undefined || json.asset.version[0] < 2) { + if (onError) + onError(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")); + return; + } + const parser = new GLTFParser(json, { + path: path || this.resourcePath || "", + crossOrigin: this.crossOrigin, + requestHeader: this.requestHeader, + manager: this.manager, + ktx2Loader: this.ktx2Loader, + meshoptDecoder: this.meshoptDecoder + }); + parser.fileLoader.setRequestHeader(this.requestHeader); + for (let i = 0;i < this.pluginCallbacks.length; i++) { + const plugin = this.pluginCallbacks[i](parser); + if (!plugin.name) + console.error("THREE.GLTFLoader: Invalid plugin found: missing name"); + plugins[plugin.name] = plugin; + extensions[plugin.name] = true; + } + if (json.extensionsUsed) { + for (let i = 0;i < json.extensionsUsed.length; ++i) { + const extensionName = json.extensionsUsed[i]; + const extensionsRequired = json.extensionsRequired || []; + switch (extensionName) { + case EXTENSIONS.KHR_MATERIALS_UNLIT: + extensions[extensionName] = new GLTFMaterialsUnlitExtension2; + break; + case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: + extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader); + break; + case EXTENSIONS.KHR_TEXTURE_TRANSFORM: + extensions[extensionName] = new GLTFTextureTransformExtension; + break; + case EXTENSIONS.KHR_MESH_QUANTIZATION: + extensions[extensionName] = new GLTFMeshQuantizationExtension; + break; + default: + if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === undefined) { + console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".'); + } + } + } + } + parser.setExtensions(extensions); + parser.setPlugins(plugins); + parser.parse(onLoad, onError); + } + parseAsync(data2, path) { + const scope = this; + return new Promise(function(resolve, reject2) { + scope.parse(data2, path, resolve, reject2); + }); + } +} +function GLTFRegistry() { + let objects = {}; + return { + get: function(key2) { + return objects[key2]; + }, + add: function(key2, object) { + objects[key2] = object; + }, + remove: function(key2) { + delete objects[key2]; + }, + removeAll: function() { + objects = {}; + } + }; +} +var EXTENSIONS = { + KHR_BINARY_GLTF: "KHR_binary_glTF", + KHR_DRACO_MESH_COMPRESSION: "KHR_draco_mesh_compression", + KHR_LIGHTS_PUNCTUAL: "KHR_lights_punctual", + KHR_MATERIALS_CLEARCOAT: "KHR_materials_clearcoat", + KHR_MATERIALS_DISPERSION: "KHR_materials_dispersion", + KHR_MATERIALS_IOR: "KHR_materials_ior", + KHR_MATERIALS_SHEEN: "KHR_materials_sheen", + KHR_MATERIALS_SPECULAR: "KHR_materials_specular", + KHR_MATERIALS_TRANSMISSION: "KHR_materials_transmission", + KHR_MATERIALS_IRIDESCENCE: "KHR_materials_iridescence", + KHR_MATERIALS_ANISOTROPY: "KHR_materials_anisotropy", + KHR_MATERIALS_UNLIT: "KHR_materials_unlit", + KHR_MATERIALS_VOLUME: "KHR_materials_volume", + KHR_TEXTURE_BASISU: "KHR_texture_basisu", + KHR_TEXTURE_TRANSFORM: "KHR_texture_transform", + KHR_MESH_QUANTIZATION: "KHR_mesh_quantization", + KHR_MATERIALS_EMISSIVE_STRENGTH: "KHR_materials_emissive_strength", + EXT_MATERIALS_BUMP: "EXT_materials_bump", + EXT_TEXTURE_WEBP: "EXT_texture_webp", + EXT_TEXTURE_AVIF: "EXT_texture_avif", + EXT_MESHOPT_COMPRESSION: "EXT_meshopt_compression", + EXT_MESH_GPU_INSTANCING: "EXT_mesh_gpu_instancing" +}; + +class GLTFLightsExtension { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; + this.cache = { refs: {}, uses: {} }; + } + _markDefs() { + const parser = this.parser; + const nodeDefs = this.parser.json.nodes || []; + for (let nodeIndex = 0, nodeLength = nodeDefs.length;nodeIndex < nodeLength; nodeIndex++) { + const nodeDef = nodeDefs[nodeIndex]; + if (nodeDef.extensions && nodeDef.extensions[this.name] && nodeDef.extensions[this.name].light !== undefined) { + parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light); + } + } + } + _loadLight(lightIndex) { + const parser = this.parser; + const cacheKey = "light:" + lightIndex; + let dependency = parser.cache.get(cacheKey); + if (dependency) + return dependency; + const json = parser.json; + const extensions = json.extensions && json.extensions[this.name] || {}; + const lightDefs = extensions.lights || []; + const lightDef = lightDefs[lightIndex]; + let lightNode; + const color = new Color(16777215); + if (lightDef.color !== undefined) + color.setRGB(lightDef.color[0], lightDef.color[1], lightDef.color[2], LinearSRGBColorSpace); + const range = lightDef.range !== undefined ? lightDef.range : 0; + switch (lightDef.type) { + case "directional": + lightNode = new DirectionalLight(color); + lightNode.target.position.set(0, 0, -1); + lightNode.add(lightNode.target); + break; + case "point": + lightNode = new PointLight(color); + lightNode.distance = range; + break; + case "spot": + lightNode = new SpotLight(color); + lightNode.distance = range; + lightDef.spot = lightDef.spot || {}; + lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0; + lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4; + lightNode.angle = lightDef.spot.outerConeAngle; + lightNode.penumbra = 1 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle; + lightNode.target.position.set(0, 0, -1); + lightNode.add(lightNode.target); + break; + default: + throw new Error("THREE.GLTFLoader: Unexpected light type: " + lightDef.type); + } + lightNode.position.set(0, 0, 0); + assignExtrasToUserData(lightNode, lightDef); + if (lightDef.intensity !== undefined) + lightNode.intensity = lightDef.intensity; + lightNode.name = parser.createUniqueName(lightDef.name || "light_" + lightIndex); + dependency = Promise.resolve(lightNode); + parser.cache.add(cacheKey, dependency); + return dependency; + } + getDependency(type, index2) { + if (type !== "light") + return; + return this._loadLight(index2); + } + createNodeAttachment(nodeIndex) { + const self2 = this; + const parser = this.parser; + const json = parser.json; + const nodeDef = json.nodes[nodeIndex]; + const lightDef = nodeDef.extensions && nodeDef.extensions[this.name] || {}; + const lightIndex = lightDef.light; + if (lightIndex === undefined) + return null; + return this._loadLight(lightIndex).then(function(light) { + return parser._getNodeRef(self2.cache, lightIndex, light); + }); + } +} + +class GLTFMaterialsUnlitExtension2 { + constructor() { + this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; + } + getMaterialType() { + return MeshBasicMaterial; + } + extendParams(materialParams, materialDef, parser) { + const pending = []; + materialParams.color = new Color(1, 1, 1); + materialParams.opacity = 1; + const metallicRoughness = materialDef.pbrMetallicRoughness; + if (metallicRoughness) { + if (Array.isArray(metallicRoughness.baseColorFactor)) { + const array = metallicRoughness.baseColorFactor; + materialParams.color.setRGB(array[0], array[1], array[2], LinearSRGBColorSpace); + materialParams.opacity = array[3]; + } + if (metallicRoughness.baseColorTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, SRGBColorSpace)); + } + } + return Promise.all(pending); + } +} + +class GLTFMaterialsEmissiveStrengthExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const emissiveStrength = materialDef.extensions[this.name].emissiveStrength; + if (emissiveStrength !== undefined) { + materialParams.emissiveIntensity = emissiveStrength; + } + return Promise.resolve(); + } +} + +class GLTFMaterialsClearcoatExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + if (extension.clearcoatFactor !== undefined) { + materialParams.clearcoat = extension.clearcoatFactor; + } + if (extension.clearcoatTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "clearcoatMap", extension.clearcoatTexture)); + } + if (extension.clearcoatRoughnessFactor !== undefined) { + materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor; + } + if (extension.clearcoatRoughnessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "clearcoatRoughnessMap", extension.clearcoatRoughnessTexture)); + } + if (extension.clearcoatNormalTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "clearcoatNormalMap", extension.clearcoatNormalTexture)); + if (extension.clearcoatNormalTexture.scale !== undefined) { + const scale2 = extension.clearcoatNormalTexture.scale; + materialParams.clearcoatNormalScale = new Vector2(scale2, scale2); + } + } + return Promise.all(pending); + } +} + +class GLTFMaterialsDispersionExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_DISPERSION; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const extension = materialDef.extensions[this.name]; + materialParams.dispersion = extension.dispersion !== undefined ? extension.dispersion : 0; + return Promise.resolve(); + } +} + +class GLTFMaterialsIridescenceExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + if (extension.iridescenceFactor !== undefined) { + materialParams.iridescence = extension.iridescenceFactor; + } + if (extension.iridescenceTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "iridescenceMap", extension.iridescenceTexture)); + } + if (extension.iridescenceIor !== undefined) { + materialParams.iridescenceIOR = extension.iridescenceIor; + } + if (materialParams.iridescenceThicknessRange === undefined) { + materialParams.iridescenceThicknessRange = [100, 400]; + } + if (extension.iridescenceThicknessMinimum !== undefined) { + materialParams.iridescenceThicknessRange[0] = extension.iridescenceThicknessMinimum; + } + if (extension.iridescenceThicknessMaximum !== undefined) { + materialParams.iridescenceThicknessRange[1] = extension.iridescenceThicknessMaximum; + } + if (extension.iridescenceThicknessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "iridescenceThicknessMap", extension.iridescenceThicknessTexture)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsSheenExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_SHEEN; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + materialParams.sheenColor = new Color(0, 0, 0); + materialParams.sheenRoughness = 0; + materialParams.sheen = 1; + const extension = materialDef.extensions[this.name]; + if (extension.sheenColorFactor !== undefined) { + const colorFactor = extension.sheenColorFactor; + materialParams.sheenColor.setRGB(colorFactor[0], colorFactor[1], colorFactor[2], LinearSRGBColorSpace); + } + if (extension.sheenRoughnessFactor !== undefined) { + materialParams.sheenRoughness = extension.sheenRoughnessFactor; + } + if (extension.sheenColorTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "sheenColorMap", extension.sheenColorTexture, SRGBColorSpace)); + } + if (extension.sheenRoughnessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "sheenRoughnessMap", extension.sheenRoughnessTexture)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsTransmissionExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + if (extension.transmissionFactor !== undefined) { + materialParams.transmission = extension.transmissionFactor; + } + if (extension.transmissionTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "transmissionMap", extension.transmissionTexture)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsVolumeExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_VOLUME; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0; + if (extension.thicknessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "thicknessMap", extension.thicknessTexture)); + } + materialParams.attenuationDistance = extension.attenuationDistance || Infinity; + const colorArray = extension.attenuationColor || [1, 1, 1]; + materialParams.attenuationColor = new Color().setRGB(colorArray[0], colorArray[1], colorArray[2], LinearSRGBColorSpace); + return Promise.all(pending); + } +} + +class GLTFMaterialsIorExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_IOR; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const extension = materialDef.extensions[this.name]; + materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5; + return Promise.resolve(); + } +} + +class GLTFMaterialsSpecularExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1; + if (extension.specularTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "specularIntensityMap", extension.specularTexture)); + } + const colorArray = extension.specularColorFactor || [1, 1, 1]; + materialParams.specularColor = new Color().setRGB(colorArray[0], colorArray[1], colorArray[2], LinearSRGBColorSpace); + if (extension.specularColorTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "specularColorMap", extension.specularColorTexture, SRGBColorSpace)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsBumpExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.EXT_MATERIALS_BUMP; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + materialParams.bumpScale = extension.bumpFactor !== undefined ? extension.bumpFactor : 1; + if (extension.bumpTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "bumpMap", extension.bumpTexture)); + } + return Promise.all(pending); + } +} + +class GLTFMaterialsAnisotropyExtension2 { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY; + } + getMaterialType(materialIndex) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) + return null; + return MeshPhysicalMaterial; + } + extendMaterialParams(materialIndex, materialParams) { + const parser = this.parser; + const materialDef = parser.json.materials[materialIndex]; + if (!materialDef.extensions || !materialDef.extensions[this.name]) { + return Promise.resolve(); + } + const pending = []; + const extension = materialDef.extensions[this.name]; + if (extension.anisotropyStrength !== undefined) { + materialParams.anisotropy = extension.anisotropyStrength; + } + if (extension.anisotropyRotation !== undefined) { + materialParams.anisotropyRotation = extension.anisotropyRotation; + } + if (extension.anisotropyTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "anisotropyMap", extension.anisotropyTexture)); + } + return Promise.all(pending); + } +} + +class GLTFTextureBasisUExtension { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.KHR_TEXTURE_BASISU; + } + loadTexture(textureIndex) { + const parser = this.parser; + const json = parser.json; + const textureDef = json.textures[textureIndex]; + if (!textureDef.extensions || !textureDef.extensions[this.name]) { + return null; + } + const extension = textureDef.extensions[this.name]; + const loader = parser.options.ktx2Loader; + if (!loader) { + if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) { + throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures"); + } else { + return null; + } + } + return parser.loadTextureImage(textureIndex, extension.source, loader); + } +} + +class GLTFTextureWebPExtension { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.EXT_TEXTURE_WEBP; + this.isSupported = null; + } + loadTexture(textureIndex) { + const name2 = this.name; + const parser = this.parser; + const json = parser.json; + const textureDef = json.textures[textureIndex]; + if (!textureDef.extensions || !textureDef.extensions[name2]) { + return null; + } + const extension = textureDef.extensions[name2]; + const source = json.images[extension.source]; + let loader = parser.textureLoader; + if (source.uri) { + const handler = parser.options.manager.getHandler(source.uri); + if (handler !== null) + loader = handler; + } + return this.detectSupport().then(function(isSupported) { + if (isSupported) + return parser.loadTextureImage(textureIndex, extension.source, loader); + if (json.extensionsRequired && json.extensionsRequired.indexOf(name2) >= 0) { + throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported."); + } + return parser.loadTexture(textureIndex); + }); + } + detectSupport() { + if (!this.isSupported) { + this.isSupported = new Promise(function(resolve) { + const image = new Image; + image.src = "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA"; + image.onload = image.onerror = function() { + resolve(image.height === 1); + }; + }); + } + return this.isSupported; + } +} + +class GLTFTextureAVIFExtension { + constructor(parser) { + this.parser = parser; + this.name = EXTENSIONS.EXT_TEXTURE_AVIF; + this.isSupported = null; + } + loadTexture(textureIndex) { + const name2 = this.name; + const parser = this.parser; + const json = parser.json; + const textureDef = json.textures[textureIndex]; + if (!textureDef.extensions || !textureDef.extensions[name2]) { + return null; + } + const extension = textureDef.extensions[name2]; + const source = json.images[extension.source]; + let loader = parser.textureLoader; + if (source.uri) { + const handler = parser.options.manager.getHandler(source.uri); + if (handler !== null) + loader = handler; + } + return this.detectSupport().then(function(isSupported) { + if (isSupported) + return parser.loadTextureImage(textureIndex, extension.source, loader); + if (json.extensionsRequired && json.extensionsRequired.indexOf(name2) >= 0) { + throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported."); + } + return parser.loadTexture(textureIndex); + }); + } + detectSupport() { + if (!this.isSupported) { + this.isSupported = new Promise(function(resolve) { + const image = new Image; + image.src = "data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI="; + image.onload = image.onerror = function() { + resolve(image.height === 1); + }; + }); + } + return this.isSupported; + } +} + +class GLTFMeshoptCompression { + constructor(parser) { + this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION; + this.parser = parser; + } + loadBufferView(index2) { + const json = this.parser.json; + const bufferView = json.bufferViews[index2]; + if (bufferView.extensions && bufferView.extensions[this.name]) { + const extensionDef = bufferView.extensions[this.name]; + const buffer = this.parser.getDependency("buffer", extensionDef.buffer); + const decoder = this.parser.options.meshoptDecoder; + if (!decoder || !decoder.supported) { + if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) { + throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files"); + } else { + return null; + } + } + return buffer.then(function(res) { + const byteOffset = extensionDef.byteOffset || 0; + const byteLength = extensionDef.byteLength || 0; + const count = extensionDef.count; + const stride = extensionDef.byteStride; + const source = new Uint8Array(res, byteOffset, byteLength); + if (decoder.decodeGltfBufferAsync) { + return decoder.decodeGltfBufferAsync(count, stride, source, extensionDef.mode, extensionDef.filter).then(function(res2) { + return res2.buffer; + }); + } else { + return decoder.ready.then(function() { + const result = new ArrayBuffer(count * stride); + decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter); + return result; + }); + } + }); + } else { + return null; + } + } +} + +class GLTFMeshGpuInstancing2 { + constructor(parser) { + this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING; + this.parser = parser; + } + createNodeMesh(nodeIndex) { + const json = this.parser.json; + const nodeDef = json.nodes[nodeIndex]; + if (!nodeDef.extensions || !nodeDef.extensions[this.name] || nodeDef.mesh === undefined) { + return null; + } + const meshDef = json.meshes[nodeDef.mesh]; + for (const primitive of meshDef.primitives) { + if (primitive.mode !== WEBGL_CONSTANTS2.TRIANGLES && primitive.mode !== WEBGL_CONSTANTS2.TRIANGLE_STRIP && primitive.mode !== WEBGL_CONSTANTS2.TRIANGLE_FAN && primitive.mode !== undefined) { + return null; + } + } + const extensionDef = nodeDef.extensions[this.name]; + const attributesDef = extensionDef.attributes; + const pending = []; + const attributes = {}; + for (const key2 in attributesDef) { + pending.push(this.parser.getDependency("accessor", attributesDef[key2]).then((accessor) => { + attributes[key2] = accessor; + return attributes[key2]; + })); + } + if (pending.length < 1) { + return null; + } + pending.push(this.parser.createNodeMesh(nodeIndex)); + return Promise.all(pending).then((results) => { + const nodeObject = results.pop(); + const meshes = nodeObject.isGroup ? nodeObject.children : [nodeObject]; + const count = results[0].count; + const instancedMeshes = []; + for (const mesh of meshes) { + const m = new Matrix4; + const p = new Vector3; + const q2 = new Quaternion; + const s = new Vector3(1, 1, 1); + const instancedMesh = new InstancedMesh(mesh.geometry, mesh.material, count); + for (let i = 0;i < count; i++) { + if (attributes.TRANSLATION) { + p.fromBufferAttribute(attributes.TRANSLATION, i); + } + if (attributes.ROTATION) { + q2.fromBufferAttribute(attributes.ROTATION, i); + } + if (attributes.SCALE) { + s.fromBufferAttribute(attributes.SCALE, i); + } + instancedMesh.setMatrixAt(i, m.compose(p, q2, s)); + } + for (const attributeName in attributes) { + if (attributeName === "_COLOR_0") { + const attr = attributes[attributeName]; + instancedMesh.instanceColor = new InstancedBufferAttribute(attr.array, attr.itemSize, attr.normalized); + } else if (attributeName !== "TRANSLATION" && attributeName !== "ROTATION" && attributeName !== "SCALE") { + mesh.geometry.setAttribute(attributeName, attributes[attributeName]); + } + } + Object3D.prototype.copy.call(instancedMesh, mesh); + this.parser.assignFinalMaterial(instancedMesh); + instancedMeshes.push(instancedMesh); + } + if (nodeObject.isGroup) { + nodeObject.clear(); + nodeObject.add(...instancedMeshes); + return nodeObject; + } + return instancedMeshes[0]; + }); + } +} +var BINARY_EXTENSION_HEADER_MAGIC = "glTF"; +var BINARY_EXTENSION_HEADER_LENGTH = 12; +var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 1313821514, BIN: 5130562 }; + +class GLTFBinaryExtension { + constructor(data2) { + this.name = EXTENSIONS.KHR_BINARY_GLTF; + this.content = null; + this.body = null; + const headerView = new DataView(data2, 0, BINARY_EXTENSION_HEADER_LENGTH); + const textDecoder = new TextDecoder; + this.header = { + magic: textDecoder.decode(new Uint8Array(data2.slice(0, 4))), + version: headerView.getUint32(4, true), + length: headerView.getUint32(8, true) + }; + if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) { + throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header."); + } else if (this.header.version < 2) { + throw new Error("THREE.GLTFLoader: Legacy binary file detected."); + } + const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH; + const chunkView = new DataView(data2, BINARY_EXTENSION_HEADER_LENGTH); + let chunkIndex = 0; + while (chunkIndex < chunkContentsLength) { + const chunkLength = chunkView.getUint32(chunkIndex, true); + chunkIndex += 4; + const chunkType = chunkView.getUint32(chunkIndex, true); + chunkIndex += 4; + if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) { + const contentArray = new Uint8Array(data2, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength); + this.content = textDecoder.decode(contentArray); + } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) { + const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; + this.body = data2.slice(byteOffset, byteOffset + chunkLength); + } + chunkIndex += chunkLength; + } + if (this.content === null) { + throw new Error("THREE.GLTFLoader: JSON content not found."); + } + } +} + +class GLTFDracoMeshCompressionExtension { + constructor(json, dracoLoader) { + if (!dracoLoader) { + throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided."); + } + this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; + this.json = json; + this.dracoLoader = dracoLoader; + this.dracoLoader.preload(); + } + decodePrimitive(primitive, parser) { + const json = this.json; + const dracoLoader = this.dracoLoader; + const bufferViewIndex = primitive.extensions[this.name].bufferView; + const gltfAttributeMap = primitive.extensions[this.name].attributes; + const threeAttributeMap = {}; + const attributeNormalizedMap = {}; + const attributeTypeMap = {}; + for (const attributeName in gltfAttributeMap) { + const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); + threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName]; + } + for (const attributeName in primitive.attributes) { + const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); + if (gltfAttributeMap[attributeName] !== undefined) { + const accessorDef = json.accessors[primitive.attributes[attributeName]]; + const componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; + attributeTypeMap[threeAttributeName] = componentType.name; + attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true; + } + } + return parser.getDependency("bufferView", bufferViewIndex).then(function(bufferView) { + return new Promise(function(resolve, reject2) { + dracoLoader.decodeDracoFile(bufferView, function(geometry) { + for (const attributeName in geometry.attributes) { + const attribute = geometry.attributes[attributeName]; + const normalized = attributeNormalizedMap[attributeName]; + if (normalized !== undefined) + attribute.normalized = normalized; + } + resolve(geometry); + }, threeAttributeMap, attributeTypeMap, LinearSRGBColorSpace, reject2); + }); + }); + } +} + +class GLTFTextureTransformExtension { + constructor() { + this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; + } + extendTexture(texture, transform2) { + if ((transform2.texCoord === undefined || transform2.texCoord === texture.channel) && transform2.offset === undefined && transform2.rotation === undefined && transform2.scale === undefined) { + return texture; + } + texture = texture.clone(); + if (transform2.texCoord !== undefined) { + texture.channel = transform2.texCoord; + } + if (transform2.offset !== undefined) { + texture.offset.fromArray(transform2.offset); + } + if (transform2.rotation !== undefined) { + texture.rotation = transform2.rotation; + } + if (transform2.scale !== undefined) { + texture.repeat.fromArray(transform2.scale); + } + texture.needsUpdate = true; + return texture; + } +} + +class GLTFMeshQuantizationExtension { + constructor() { + this.name = EXTENSIONS.KHR_MESH_QUANTIZATION; + } +} + +class GLTFCubicSplineInterpolant extends Interpolant { + constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { + super(parameterPositions, sampleValues, sampleSize, resultBuffer); + } + copySampleValue_(index2) { + const result = this.resultBuffer, values2 = this.sampleValues, valueSize = this.valueSize, offset = index2 * valueSize * 3 + valueSize; + for (let i = 0;i !== valueSize; i++) { + result[i] = values2[offset + i]; + } + return result; + } + interpolate_(i1, t0, t2, t1) { + const result = this.resultBuffer; + const values2 = this.sampleValues; + const stride = this.valueSize; + const stride2 = stride * 2; + const stride3 = stride * 3; + const td2 = t1 - t0; + const p = (t2 - t0) / td2; + const pp = p * p; + const ppp = pp * p; + const offset1 = i1 * stride3; + const offset0 = offset1 - stride3; + const s2 = -2 * ppp + 3 * pp; + const s3 = ppp - pp; + const s0 = 1 - s2; + const s1 = s3 - pp + p; + for (let i = 0;i !== stride; i++) { + const p0 = values2[offset0 + i + stride]; + const m0 = values2[offset0 + i + stride2] * td2; + const p1 = values2[offset1 + i + stride]; + const m1 = values2[offset1 + i] * td2; + result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; + } + return result; + } +} +var _q2 = new Quaternion; + +class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant { + interpolate_(i1, t0, t2, t1) { + const result = super.interpolate_(i1, t0, t2, t1); + _q2.fromArray(result).normalize().toArray(result); + return result; + } +} +var WEBGL_CONSTANTS2 = { + FLOAT: 5126, + FLOAT_MAT3: 35675, + FLOAT_MAT4: 35676, + FLOAT_VEC2: 35664, + FLOAT_VEC3: 35665, + FLOAT_VEC4: 35666, + LINEAR: 9729, + REPEAT: 10497, + SAMPLER_2D: 35678, + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6, + UNSIGNED_BYTE: 5121, + UNSIGNED_SHORT: 5123 +}; +var WEBGL_COMPONENT_TYPES = { + 5120: Int8Array, + 5121: Uint8Array, + 5122: Int16Array, + 5123: Uint16Array, + 5125: Uint32Array, + 5126: Float32Array +}; +var WEBGL_FILTERS = { + 9728: NearestFilter, + 9729: LinearFilter, + 9984: NearestMipmapNearestFilter, + 9985: LinearMipmapNearestFilter, + 9986: NearestMipmapLinearFilter, + 9987: LinearMipmapLinearFilter +}; +var WEBGL_WRAPPINGS = { + 33071: ClampToEdgeWrapping, + 33648: MirroredRepeatWrapping, + 10497: RepeatWrapping +}; +var WEBGL_TYPE_SIZES = { + SCALAR: 1, + VEC2: 2, + VEC3: 3, + VEC4: 4, + MAT2: 4, + MAT3: 9, + MAT4: 16 +}; +var ATTRIBUTES = { + POSITION: "position", + NORMAL: "normal", + TANGENT: "tangent", + TEXCOORD_0: "uv", + TEXCOORD_1: "uv1", + TEXCOORD_2: "uv2", + TEXCOORD_3: "uv3", + COLOR_0: "color", + WEIGHTS_0: "skinWeight", + JOINTS_0: "skinIndex" +}; +var PATH_PROPERTIES2 = { + scale: "scale", + translation: "position", + rotation: "quaternion", + weights: "morphTargetInfluences" +}; +var INTERPOLATION = { + CUBICSPLINE: undefined, + LINEAR: InterpolateLinear, + STEP: InterpolateDiscrete +}; +var ALPHA_MODES = { + OPAQUE: "OPAQUE", + MASK: "MASK", + BLEND: "BLEND" +}; +function createDefaultMaterial(cache) { + if (cache["DefaultMaterial"] === undefined) { + cache["DefaultMaterial"] = new MeshStandardMaterial({ + color: 16777215, + emissive: 0, + metalness: 1, + roughness: 1, + transparent: false, + depthTest: true, + side: FrontSide + }); + } + return cache["DefaultMaterial"]; +} +function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) { + for (const name2 in objectDef.extensions) { + if (knownExtensions[name2] === undefined) { + object.userData.gltfExtensions = object.userData.gltfExtensions || {}; + object.userData.gltfExtensions[name2] = objectDef.extensions[name2]; + } + } +} +function assignExtrasToUserData(object, gltfDef) { + if (gltfDef.extras !== undefined) { + if (typeof gltfDef.extras === "object") { + Object.assign(object.userData, gltfDef.extras); + } else { + console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, " + gltfDef.extras); + } + } +} +function addMorphTargets(geometry, targets, parser) { + let hasMorphPosition = false; + let hasMorphNormal = false; + let hasMorphColor = false; + for (let i = 0, il = targets.length;i < il; i++) { + const target = targets[i]; + if (target.POSITION !== undefined) + hasMorphPosition = true; + if (target.NORMAL !== undefined) + hasMorphNormal = true; + if (target.COLOR_0 !== undefined) + hasMorphColor = true; + if (hasMorphPosition && hasMorphNormal && hasMorphColor) + break; + } + if (!hasMorphPosition && !hasMorphNormal && !hasMorphColor) + return Promise.resolve(geometry); + const pendingPositionAccessors = []; + const pendingNormalAccessors = []; + const pendingColorAccessors = []; + for (let i = 0, il = targets.length;i < il; i++) { + const target = targets[i]; + if (hasMorphPosition) { + const pendingAccessor = target.POSITION !== undefined ? parser.getDependency("accessor", target.POSITION) : geometry.attributes.position; + pendingPositionAccessors.push(pendingAccessor); + } + if (hasMorphNormal) { + const pendingAccessor = target.NORMAL !== undefined ? parser.getDependency("accessor", target.NORMAL) : geometry.attributes.normal; + pendingNormalAccessors.push(pendingAccessor); + } + if (hasMorphColor) { + const pendingAccessor = target.COLOR_0 !== undefined ? parser.getDependency("accessor", target.COLOR_0) : geometry.attributes.color; + pendingColorAccessors.push(pendingAccessor); + } + } + return Promise.all([ + Promise.all(pendingPositionAccessors), + Promise.all(pendingNormalAccessors), + Promise.all(pendingColorAccessors) + ]).then(function(accessors) { + const morphPositions = accessors[0]; + const morphNormals = accessors[1]; + const morphColors = accessors[2]; + if (hasMorphPosition) + geometry.morphAttributes.position = morphPositions; + if (hasMorphNormal) + geometry.morphAttributes.normal = morphNormals; + if (hasMorphColor) + geometry.morphAttributes.color = morphColors; + geometry.morphTargetsRelative = true; + return geometry; + }); +} +function updateMorphTargets(mesh, meshDef) { + mesh.updateMorphTargets(); + if (meshDef.weights !== undefined) { + for (let i = 0, il = meshDef.weights.length;i < il; i++) { + mesh.morphTargetInfluences[i] = meshDef.weights[i]; + } + } + if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) { + const targetNames = meshDef.extras.targetNames; + if (mesh.morphTargetInfluences.length === targetNames.length) { + mesh.morphTargetDictionary = {}; + for (let i = 0, il = targetNames.length;i < il; i++) { + mesh.morphTargetDictionary[targetNames[i]] = i; + } + } else { + console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names."); + } + } +} +function createPrimitiveKey(primitiveDef) { + let geometryKey; + const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]; + if (dracoExtension) { + geometryKey = "draco:" + dracoExtension.bufferView + ":" + dracoExtension.indices + ":" + createAttributesKey(dracoExtension.attributes); + } else { + geometryKey = primitiveDef.indices + ":" + createAttributesKey(primitiveDef.attributes) + ":" + primitiveDef.mode; + } + if (primitiveDef.targets !== undefined) { + for (let i = 0, il = primitiveDef.targets.length;i < il; i++) { + geometryKey += ":" + createAttributesKey(primitiveDef.targets[i]); + } + } + return geometryKey; +} +function createAttributesKey(attributes) { + let attributesKey = ""; + const keys2 = Object.keys(attributes).sort(); + for (let i = 0, il = keys2.length;i < il; i++) { + attributesKey += keys2[i] + ":" + attributes[keys2[i]] + ";"; + } + return attributesKey; +} +function getNormalizedComponentScale(constructor) { + switch (constructor) { + case Int8Array: + return 1 / 127; + case Uint8Array: + return 1 / 255; + case Int16Array: + return 1 / 32767; + case Uint16Array: + return 1 / 65535; + default: + throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type."); + } +} +function getImageURIMimeType(uri) { + if (uri.search(/\.jpe?g($|\?)/i) > 0 || uri.search(/^data\:image\/jpeg/) === 0) + return "image/jpeg"; + if (uri.search(/\.webp($|\?)/i) > 0 || uri.search(/^data\:image\/webp/) === 0) + return "image/webp"; + if (uri.search(/\.ktx2($|\?)/i) > 0 || uri.search(/^data\:image\/ktx2/) === 0) + return "image/ktx2"; + return "image/png"; +} +var _identityMatrix2 = new Matrix4; + +class GLTFParser { + constructor(json = {}, options = {}) { + this.json = json; + this.extensions = {}; + this.plugins = {}; + this.options = options; + this.cache = new GLTFRegistry; + this.associations = new Map; + this.primitiveCache = {}; + this.nodeCache = {}; + this.meshCache = { refs: {}, uses: {} }; + this.cameraCache = { refs: {}, uses: {} }; + this.lightCache = { refs: {}, uses: {} }; + this.sourceCache = {}; + this.textureCache = {}; + this.nodeNamesUsed = {}; + let isSafari2 = false; + let safariVersion = -1; + let isFirefox = false; + let firefoxVersion = -1; + if (typeof navigator !== "undefined") { + const userAgent = navigator.userAgent; + isSafari2 = /^((?!chrome|android).)*safari/i.test(userAgent) === true; + const safariMatch = userAgent.match(/Version\/(\d+)/); + safariVersion = isSafari2 && safariMatch ? parseInt(safariMatch[1], 10) : -1; + isFirefox = userAgent.indexOf("Firefox") > -1; + firefoxVersion = isFirefox ? userAgent.match(/Firefox\/([0-9]+)\./)[1] : -1; + } + if (typeof createImageBitmap === "undefined" || isSafari2 && safariVersion < 17 || isFirefox && firefoxVersion < 98) { + this.textureLoader = new TextureLoader(this.options.manager); + } else { + this.textureLoader = new ImageBitmapLoader(this.options.manager); + } + this.textureLoader.setCrossOrigin(this.options.crossOrigin); + this.textureLoader.setRequestHeader(this.options.requestHeader); + this.fileLoader = new FileLoader(this.options.manager); + this.fileLoader.setResponseType("arraybuffer"); + if (this.options.crossOrigin === "use-credentials") { + this.fileLoader.setWithCredentials(true); + } + } + setExtensions(extensions) { + this.extensions = extensions; + } + setPlugins(plugins) { + this.plugins = plugins; + } + parse(onLoad, onError) { + const parser = this; + const json = this.json; + const extensions = this.extensions; + this.cache.removeAll(); + this.nodeCache = {}; + this._invokeAll(function(ext) { + return ext._markDefs && ext._markDefs(); + }); + Promise.all(this._invokeAll(function(ext) { + return ext.beforeRoot && ext.beforeRoot(); + })).then(function() { + return Promise.all([ + parser.getDependencies("scene"), + parser.getDependencies("animation"), + parser.getDependencies("camera") + ]); + }).then(function(dependencies) { + const result = { + scene: dependencies[0][json.scene || 0], + scenes: dependencies[0], + animations: dependencies[1], + cameras: dependencies[2], + asset: json.asset, + parser, + userData: {} + }; + addUnknownExtensionsToUserData(extensions, result, json); + assignExtrasToUserData(result, json); + return Promise.all(parser._invokeAll(function(ext) { + return ext.afterRoot && ext.afterRoot(result); + })).then(function() { + for (const scene of result.scenes) { + scene.updateMatrixWorld(); + } + onLoad(result); + }); + }).catch(onError); + } + _markDefs() { + const nodeDefs = this.json.nodes || []; + const skinDefs = this.json.skins || []; + const meshDefs = this.json.meshes || []; + for (let skinIndex = 0, skinLength = skinDefs.length;skinIndex < skinLength; skinIndex++) { + const joints = skinDefs[skinIndex].joints; + for (let i = 0, il = joints.length;i < il; i++) { + nodeDefs[joints[i]].isBone = true; + } + } + for (let nodeIndex = 0, nodeLength = nodeDefs.length;nodeIndex < nodeLength; nodeIndex++) { + const nodeDef = nodeDefs[nodeIndex]; + if (nodeDef.mesh !== undefined) { + this._addNodeRef(this.meshCache, nodeDef.mesh); + if (nodeDef.skin !== undefined) { + meshDefs[nodeDef.mesh].isSkinnedMesh = true; + } + } + if (nodeDef.camera !== undefined) { + this._addNodeRef(this.cameraCache, nodeDef.camera); + } + } + } + _addNodeRef(cache, index2) { + if (index2 === undefined) + return; + if (cache.refs[index2] === undefined) { + cache.refs[index2] = cache.uses[index2] = 0; + } + cache.refs[index2]++; + } + _getNodeRef(cache, index2, object) { + if (cache.refs[index2] <= 1) + return object; + const ref = object.clone(); + const updateMappings = (original, clone) => { + const mappings = this.associations.get(original); + if (mappings != null) { + this.associations.set(clone, mappings); + } + for (const [i, child] of original.children.entries()) { + updateMappings(child, clone.children[i]); + } + }; + updateMappings(object, ref); + ref.name += "_instance_" + cache.uses[index2]++; + return ref; + } + _invokeOne(func) { + const extensions = Object.values(this.plugins); + extensions.push(this); + for (let i = 0;i < extensions.length; i++) { + const result = func(extensions[i]); + if (result) + return result; + } + return null; + } + _invokeAll(func) { + const extensions = Object.values(this.plugins); + extensions.unshift(this); + const pending = []; + for (let i = 0;i < extensions.length; i++) { + const result = func(extensions[i]); + if (result) + pending.push(result); + } + return pending; + } + getDependency(type, index2) { + const cacheKey = type + ":" + index2; + let dependency = this.cache.get(cacheKey); + if (!dependency) { + switch (type) { + case "scene": + dependency = this.loadScene(index2); + break; + case "node": + dependency = this._invokeOne(function(ext) { + return ext.loadNode && ext.loadNode(index2); + }); + break; + case "mesh": + dependency = this._invokeOne(function(ext) { + return ext.loadMesh && ext.loadMesh(index2); + }); + break; + case "accessor": + dependency = this.loadAccessor(index2); + break; + case "bufferView": + dependency = this._invokeOne(function(ext) { + return ext.loadBufferView && ext.loadBufferView(index2); + }); + break; + case "buffer": + dependency = this.loadBuffer(index2); + break; + case "material": + dependency = this._invokeOne(function(ext) { + return ext.loadMaterial && ext.loadMaterial(index2); + }); + break; + case "texture": + dependency = this._invokeOne(function(ext) { + return ext.loadTexture && ext.loadTexture(index2); + }); + break; + case "skin": + dependency = this.loadSkin(index2); + break; + case "animation": + dependency = this._invokeOne(function(ext) { + return ext.loadAnimation && ext.loadAnimation(index2); + }); + break; + case "camera": + dependency = this.loadCamera(index2); + break; + default: + dependency = this._invokeOne(function(ext) { + return ext != this && ext.getDependency && ext.getDependency(type, index2); + }); + if (!dependency) { + throw new Error("Unknown type: " + type); + } + break; + } + this.cache.add(cacheKey, dependency); + } + return dependency; + } + getDependencies(type) { + let dependencies = this.cache.get(type); + if (!dependencies) { + const parser = this; + const defs = this.json[type + (type === "mesh" ? "es" : "s")] || []; + dependencies = Promise.all(defs.map(function(def, index2) { + return parser.getDependency(type, index2); + })); + this.cache.add(type, dependencies); + } + return dependencies; + } + loadBuffer(bufferIndex) { + const bufferDef = this.json.buffers[bufferIndex]; + const loader = this.fileLoader; + if (bufferDef.type && bufferDef.type !== "arraybuffer") { + throw new Error("THREE.GLTFLoader: " + bufferDef.type + " buffer type is not supported."); + } + if (bufferDef.uri === undefined && bufferIndex === 0) { + return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body); + } + const options = this.options; + return new Promise(function(resolve, reject2) { + loader.load(LoaderUtils.resolveURL(bufferDef.uri, options.path), resolve, undefined, function() { + reject2(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".')); + }); + }); + } + loadBufferView(bufferViewIndex) { + const bufferViewDef = this.json.bufferViews[bufferViewIndex]; + return this.getDependency("buffer", bufferViewDef.buffer).then(function(buffer) { + const byteLength = bufferViewDef.byteLength || 0; + const byteOffset = bufferViewDef.byteOffset || 0; + return buffer.slice(byteOffset, byteOffset + byteLength); + }); + } + loadAccessor(accessorIndex) { + const parser = this; + const json = this.json; + const accessorDef = this.json.accessors[accessorIndex]; + if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) { + const itemSize = WEBGL_TYPE_SIZES[accessorDef.type]; + const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; + const normalized = accessorDef.normalized === true; + const array = new TypedArray(accessorDef.count * itemSize); + return Promise.resolve(new BufferAttribute(array, itemSize, normalized)); + } + const pendingBufferViews = []; + if (accessorDef.bufferView !== undefined) { + pendingBufferViews.push(this.getDependency("bufferView", accessorDef.bufferView)); + } else { + pendingBufferViews.push(null); + } + if (accessorDef.sparse !== undefined) { + pendingBufferViews.push(this.getDependency("bufferView", accessorDef.sparse.indices.bufferView)); + pendingBufferViews.push(this.getDependency("bufferView", accessorDef.sparse.values.bufferView)); + } + return Promise.all(pendingBufferViews).then(function(bufferViews) { + const bufferView = bufferViews[0]; + const itemSize = WEBGL_TYPE_SIZES[accessorDef.type]; + const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; + const elementBytes = TypedArray.BYTES_PER_ELEMENT; + const itemBytes = elementBytes * itemSize; + const byteOffset = accessorDef.byteOffset || 0; + const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined; + const normalized = accessorDef.normalized === true; + let array, bufferAttribute; + if (byteStride && byteStride !== itemBytes) { + const ibSlice = Math.floor(byteOffset / byteStride); + const ibCacheKey = "InterleavedBuffer:" + accessorDef.bufferView + ":" + accessorDef.componentType + ":" + ibSlice + ":" + accessorDef.count; + let ib = parser.cache.get(ibCacheKey); + if (!ib) { + array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); + ib = new InterleavedBuffer(array, byteStride / elementBytes); + parser.cache.add(ibCacheKey, ib); + } + bufferAttribute = new InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized); + } else { + if (bufferView === null) { + array = new TypedArray(accessorDef.count * itemSize); + } else { + array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize); + } + bufferAttribute = new BufferAttribute(array, itemSize, normalized); + } + if (accessorDef.sparse !== undefined) { + const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; + const TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType]; + const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; + const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; + const sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices); + const sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize); + if (bufferView !== null) { + bufferAttribute = new BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized); + } + bufferAttribute.normalized = false; + for (let i = 0, il = sparseIndices.length;i < il; i++) { + const index2 = sparseIndices[i]; + bufferAttribute.setX(index2, sparseValues[i * itemSize]); + if (itemSize >= 2) + bufferAttribute.setY(index2, sparseValues[i * itemSize + 1]); + if (itemSize >= 3) + bufferAttribute.setZ(index2, sparseValues[i * itemSize + 2]); + if (itemSize >= 4) + bufferAttribute.setW(index2, sparseValues[i * itemSize + 3]); + if (itemSize >= 5) + throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute."); + } + bufferAttribute.normalized = normalized; + } + return bufferAttribute; + }); + } + loadTexture(textureIndex) { + const json = this.json; + const options = this.options; + const textureDef = json.textures[textureIndex]; + const sourceIndex = textureDef.source; + const sourceDef = json.images[sourceIndex]; + let loader = this.textureLoader; + if (sourceDef.uri) { + const handler = options.manager.getHandler(sourceDef.uri); + if (handler !== null) + loader = handler; + } + return this.loadTextureImage(textureIndex, sourceIndex, loader); + } + loadTextureImage(textureIndex, sourceIndex, loader) { + const parser = this; + const json = this.json; + const textureDef = json.textures[textureIndex]; + const sourceDef = json.images[sourceIndex]; + const cacheKey = (sourceDef.uri || sourceDef.bufferView) + ":" + textureDef.sampler; + if (this.textureCache[cacheKey]) { + return this.textureCache[cacheKey]; + } + const promise = this.loadImageSource(sourceIndex, loader).then(function(texture) { + texture.flipY = false; + texture.name = textureDef.name || sourceDef.name || ""; + if (texture.name === "" && typeof sourceDef.uri === "string" && sourceDef.uri.startsWith("data:image/") === false) { + texture.name = sourceDef.uri; + } + const samplers = json.samplers || {}; + const sampler = samplers[textureDef.sampler] || {}; + texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || LinearFilter; + texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || LinearMipmapLinearFilter; + texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || RepeatWrapping; + texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || RepeatWrapping; + texture.generateMipmaps = !texture.isCompressedTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; + parser.associations.set(texture, { textures: textureIndex }); + return texture; + }).catch(function() { + return null; + }); + this.textureCache[cacheKey] = promise; + return promise; + } + loadImageSource(sourceIndex, loader) { + const parser = this; + const json = this.json; + const options = this.options; + if (this.sourceCache[sourceIndex] !== undefined) { + return this.sourceCache[sourceIndex].then((texture) => texture.clone()); + } + const sourceDef = json.images[sourceIndex]; + const URL2 = self.URL || self.webkitURL; + let sourceURI = sourceDef.uri || ""; + let isObjectURL = false; + if (sourceDef.bufferView !== undefined) { + sourceURI = parser.getDependency("bufferView", sourceDef.bufferView).then(function(bufferView) { + isObjectURL = true; + const blob = new Blob([bufferView], { type: sourceDef.mimeType }); + sourceURI = URL2.createObjectURL(blob); + return sourceURI; + }); + } else if (sourceDef.uri === undefined) { + throw new Error("THREE.GLTFLoader: Image " + sourceIndex + " is missing URI and bufferView"); + } + const promise = Promise.resolve(sourceURI).then(function(sourceURI2) { + return new Promise(function(resolve, reject2) { + let onLoad = resolve; + if (loader.isImageBitmapLoader === true) { + onLoad = function(imageBitmap) { + const texture = new Texture(imageBitmap); + texture.needsUpdate = true; + resolve(texture); + }; + } + loader.load(LoaderUtils.resolveURL(sourceURI2, options.path), onLoad, undefined, reject2); + }); + }).then(function(texture) { + if (isObjectURL === true) { + URL2.revokeObjectURL(sourceURI); + } + assignExtrasToUserData(texture, sourceDef); + texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType(sourceDef.uri); + return texture; + }).catch(function(error) { + console.error("THREE.GLTFLoader: Couldn't load texture", sourceURI); + throw error; + }); + this.sourceCache[sourceIndex] = promise; + return promise; + } + assignTexture(materialParams, mapName, mapDef, colorSpace) { + const parser = this; + return this.getDependency("texture", mapDef.index).then(function(texture) { + if (!texture) + return null; + if (mapDef.texCoord !== undefined && mapDef.texCoord > 0) { + texture = texture.clone(); + texture.channel = mapDef.texCoord; + } + if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) { + const transform2 = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined; + if (transform2) { + const gltfReference = parser.associations.get(texture); + texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform2); + parser.associations.set(texture, gltfReference); + } + } + if (colorSpace !== undefined) { + texture.colorSpace = colorSpace; + } + materialParams[mapName] = texture; + return texture; + }); + } + assignFinalMaterial(mesh) { + const geometry = mesh.geometry; + let material = mesh.material; + const useDerivativeTangents = geometry.attributes.tangent === undefined; + const useVertexColors = geometry.attributes.color !== undefined; + const useFlatShading = geometry.attributes.normal === undefined; + if (mesh.isPoints) { + const cacheKey = "PointsMaterial:" + material.uuid; + let pointsMaterial = this.cache.get(cacheKey); + if (!pointsMaterial) { + pointsMaterial = new PointsMaterial; + Material.prototype.copy.call(pointsMaterial, material); + pointsMaterial.color.copy(material.color); + pointsMaterial.map = material.map; + pointsMaterial.sizeAttenuation = false; + this.cache.add(cacheKey, pointsMaterial); + } + material = pointsMaterial; + } else if (mesh.isLine) { + const cacheKey = "LineBasicMaterial:" + material.uuid; + let lineMaterial = this.cache.get(cacheKey); + if (!lineMaterial) { + lineMaterial = new LineBasicMaterial; + Material.prototype.copy.call(lineMaterial, material); + lineMaterial.color.copy(material.color); + lineMaterial.map = material.map; + this.cache.add(cacheKey, lineMaterial); + } + material = lineMaterial; + } + if (useDerivativeTangents || useVertexColors || useFlatShading) { + let cacheKey = "ClonedMaterial:" + material.uuid + ":"; + if (useDerivativeTangents) + cacheKey += "derivative-tangents:"; + if (useVertexColors) + cacheKey += "vertex-colors:"; + if (useFlatShading) + cacheKey += "flat-shading:"; + let cachedMaterial = this.cache.get(cacheKey); + if (!cachedMaterial) { + cachedMaterial = material.clone(); + if (useVertexColors) + cachedMaterial.vertexColors = true; + if (useFlatShading) + cachedMaterial.flatShading = true; + if (useDerivativeTangents) { + if (cachedMaterial.normalScale) + cachedMaterial.normalScale.y *= -1; + if (cachedMaterial.clearcoatNormalScale) + cachedMaterial.clearcoatNormalScale.y *= -1; + } + this.cache.add(cacheKey, cachedMaterial); + this.associations.set(cachedMaterial, this.associations.get(material)); + } + material = cachedMaterial; + } + mesh.material = material; + } + getMaterialType() { + return MeshStandardMaterial; + } + loadMaterial(materialIndex) { + const parser = this; + const json = this.json; + const extensions = this.extensions; + const materialDef = json.materials[materialIndex]; + let materialType; + const materialParams = {}; + const materialExtensions = materialDef.extensions || {}; + const pending = []; + if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) { + const kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT]; + materialType = kmuExtension.getMaterialType(); + pending.push(kmuExtension.extendParams(materialParams, materialDef, parser)); + } else { + const metallicRoughness = materialDef.pbrMetallicRoughness || {}; + materialParams.color = new Color(1, 1, 1); + materialParams.opacity = 1; + if (Array.isArray(metallicRoughness.baseColorFactor)) { + const array = metallicRoughness.baseColorFactor; + materialParams.color.setRGB(array[0], array[1], array[2], LinearSRGBColorSpace); + materialParams.opacity = array[3]; + } + if (metallicRoughness.baseColorTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, SRGBColorSpace)); + } + materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1; + materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1; + if (metallicRoughness.metallicRoughnessTexture !== undefined) { + pending.push(parser.assignTexture(materialParams, "metalnessMap", metallicRoughness.metallicRoughnessTexture)); + pending.push(parser.assignTexture(materialParams, "roughnessMap", metallicRoughness.metallicRoughnessTexture)); + } + materialType = this._invokeOne(function(ext) { + return ext.getMaterialType && ext.getMaterialType(materialIndex); + }); + pending.push(Promise.all(this._invokeAll(function(ext) { + return ext.extendMaterialParams && ext.extendMaterialParams(materialIndex, materialParams); + }))); + } + if (materialDef.doubleSided === true) { + materialParams.side = DoubleSide; + } + const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; + if (alphaMode === ALPHA_MODES.BLEND) { + materialParams.transparent = true; + materialParams.depthWrite = false; + } else { + materialParams.transparent = false; + if (alphaMode === ALPHA_MODES.MASK) { + materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5; + } + } + if (materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial) { + pending.push(parser.assignTexture(materialParams, "normalMap", materialDef.normalTexture)); + materialParams.normalScale = new Vector2(1, 1); + if (materialDef.normalTexture.scale !== undefined) { + const scale2 = materialDef.normalTexture.scale; + materialParams.normalScale.set(scale2, scale2); + } + } + if (materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial) { + pending.push(parser.assignTexture(materialParams, "aoMap", materialDef.occlusionTexture)); + if (materialDef.occlusionTexture.strength !== undefined) { + materialParams.aoMapIntensity = materialDef.occlusionTexture.strength; + } + } + if (materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial) { + const emissiveFactor = materialDef.emissiveFactor; + materialParams.emissive = new Color().setRGB(emissiveFactor[0], emissiveFactor[1], emissiveFactor[2], LinearSRGBColorSpace); + } + if (materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial) { + pending.push(parser.assignTexture(materialParams, "emissiveMap", materialDef.emissiveTexture, SRGBColorSpace)); + } + return Promise.all(pending).then(function() { + const material = new materialType(materialParams); + if (materialDef.name) + material.name = materialDef.name; + assignExtrasToUserData(material, materialDef); + parser.associations.set(material, { materials: materialIndex }); + if (materialDef.extensions) + addUnknownExtensionsToUserData(extensions, material, materialDef); + return material; + }); + } + createUniqueName(originalName) { + const sanitizedName = PropertyBinding.sanitizeNodeName(originalName || ""); + if (sanitizedName in this.nodeNamesUsed) { + return sanitizedName + "_" + ++this.nodeNamesUsed[sanitizedName]; + } else { + this.nodeNamesUsed[sanitizedName] = 0; + return sanitizedName; + } + } + loadGeometries(primitives) { + const parser = this; + const extensions = this.extensions; + const cache = this.primitiveCache; + function createDracoPrimitive(primitive) { + return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function(geometry) { + return addPrimitiveAttributes(geometry, primitive, parser); + }); + } + const pending = []; + for (let i = 0, il = primitives.length;i < il; i++) { + const primitive = primitives[i]; + const cacheKey = createPrimitiveKey(primitive); + const cached = cache[cacheKey]; + if (cached) { + pending.push(cached.promise); + } else { + let geometryPromise; + if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) { + geometryPromise = createDracoPrimitive(primitive); + } else { + geometryPromise = addPrimitiveAttributes(new BufferGeometry, primitive, parser); + } + cache[cacheKey] = { primitive, promise: geometryPromise }; + pending.push(geometryPromise); + } + } + return Promise.all(pending); + } + loadMesh(meshIndex) { + const parser = this; + const json = this.json; + const extensions = this.extensions; + const meshDef = json.meshes[meshIndex]; + const primitives = meshDef.primitives; + const pending = []; + for (let i = 0, il = primitives.length;i < il; i++) { + const material = primitives[i].material === undefined ? createDefaultMaterial(this.cache) : this.getDependency("material", primitives[i].material); + pending.push(material); + } + pending.push(parser.loadGeometries(primitives)); + return Promise.all(pending).then(function(results) { + const materials = results.slice(0, results.length - 1); + const geometries = results[results.length - 1]; + const meshes = []; + for (let i = 0, il = geometries.length;i < il; i++) { + const geometry = geometries[i]; + const primitive = primitives[i]; + let mesh; + const material = materials[i]; + if (primitive.mode === WEBGL_CONSTANTS2.TRIANGLES || primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_FAN || primitive.mode === undefined) { + mesh = meshDef.isSkinnedMesh === true ? new SkinnedMesh(geometry, material) : new Mesh(geometry, material); + if (mesh.isSkinnedMesh === true) { + mesh.normalizeSkinWeights(); + } + if (primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_STRIP) { + mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleStripDrawMode); + } else if (primitive.mode === WEBGL_CONSTANTS2.TRIANGLE_FAN) { + mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleFanDrawMode); + } + } else if (primitive.mode === WEBGL_CONSTANTS2.LINES) { + mesh = new LineSegments(geometry, material); + } else if (primitive.mode === WEBGL_CONSTANTS2.LINE_STRIP) { + mesh = new Line(geometry, material); + } else if (primitive.mode === WEBGL_CONSTANTS2.LINE_LOOP) { + mesh = new LineLoop(geometry, material); + } else if (primitive.mode === WEBGL_CONSTANTS2.POINTS) { + mesh = new Points(geometry, material); + } else { + throw new Error("THREE.GLTFLoader: Primitive mode unsupported: " + primitive.mode); + } + if (Object.keys(mesh.geometry.morphAttributes).length > 0) { + updateMorphTargets(mesh, meshDef); + } + mesh.name = parser.createUniqueName(meshDef.name || "mesh_" + meshIndex); + assignExtrasToUserData(mesh, meshDef); + if (primitive.extensions) + addUnknownExtensionsToUserData(extensions, mesh, primitive); + parser.assignFinalMaterial(mesh); + meshes.push(mesh); + } + for (let i = 0, il = meshes.length;i < il; i++) { + parser.associations.set(meshes[i], { + meshes: meshIndex, + primitives: i + }); + } + if (meshes.length === 1) { + if (meshDef.extensions) + addUnknownExtensionsToUserData(extensions, meshes[0], meshDef); + return meshes[0]; + } + const group = new Group; + if (meshDef.extensions) + addUnknownExtensionsToUserData(extensions, group, meshDef); + parser.associations.set(group, { meshes: meshIndex }); + for (let i = 0, il = meshes.length;i < il; i++) { + group.add(meshes[i]); + } + return group; + }); + } + loadCamera(cameraIndex) { + let camera; + const cameraDef = this.json.cameras[cameraIndex]; + const params = cameraDef[cameraDef.type]; + if (!params) { + console.warn("THREE.GLTFLoader: Missing camera parameters."); + return; + } + if (cameraDef.type === "perspective") { + camera = new PerspectiveCamera(MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2000000); + } else if (cameraDef.type === "orthographic") { + camera = new OrthographicCamera(-params.xmag, params.xmag, params.ymag, -params.ymag, params.znear, params.zfar); + } + if (cameraDef.name) + camera.name = this.createUniqueName(cameraDef.name); + assignExtrasToUserData(camera, cameraDef); + return Promise.resolve(camera); + } + loadSkin(skinIndex) { + const skinDef = this.json.skins[skinIndex]; + const pending = []; + for (let i = 0, il = skinDef.joints.length;i < il; i++) { + pending.push(this._loadNodeShallow(skinDef.joints[i])); + } + if (skinDef.inverseBindMatrices !== undefined) { + pending.push(this.getDependency("accessor", skinDef.inverseBindMatrices)); + } else { + pending.push(null); + } + return Promise.all(pending).then(function(results) { + const inverseBindMatrices = results.pop(); + const jointNodes = results; + const bones = []; + const boneInverses = []; + for (let i = 0, il = jointNodes.length;i < il; i++) { + const jointNode = jointNodes[i]; + if (jointNode) { + bones.push(jointNode); + const mat = new Matrix4; + if (inverseBindMatrices !== null) { + mat.fromArray(inverseBindMatrices.array, i * 16); + } + boneInverses.push(mat); + } else { + console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[i]); + } + } + return new Skeleton(bones, boneInverses); + }); + } + loadAnimation(animationIndex) { + const json = this.json; + const parser = this; + const animationDef = json.animations[animationIndex]; + const animationName = animationDef.name ? animationDef.name : "animation_" + animationIndex; + const pendingNodes = []; + const pendingInputAccessors = []; + const pendingOutputAccessors = []; + const pendingSamplers = []; + const pendingTargets = []; + for (let i = 0, il = animationDef.channels.length;i < il; i++) { + const channel = animationDef.channels[i]; + const sampler = animationDef.samplers[channel.sampler]; + const target = channel.target; + const name2 = target.node; + const input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input; + const output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output; + if (target.node === undefined) + continue; + pendingNodes.push(this.getDependency("node", name2)); + pendingInputAccessors.push(this.getDependency("accessor", input)); + pendingOutputAccessors.push(this.getDependency("accessor", output)); + pendingSamplers.push(sampler); + pendingTargets.push(target); + } + return Promise.all([ + Promise.all(pendingNodes), + Promise.all(pendingInputAccessors), + Promise.all(pendingOutputAccessors), + Promise.all(pendingSamplers), + Promise.all(pendingTargets) + ]).then(function(dependencies) { + const nodes = dependencies[0]; + const inputAccessors = dependencies[1]; + const outputAccessors = dependencies[2]; + const samplers = dependencies[3]; + const targets = dependencies[4]; + const tracks = []; + for (let i = 0, il = nodes.length;i < il; i++) { + const node = nodes[i]; + const inputAccessor = inputAccessors[i]; + const outputAccessor = outputAccessors[i]; + const sampler = samplers[i]; + const target = targets[i]; + if (node === undefined) + continue; + if (node.updateMatrix) { + node.updateMatrix(); + } + const createdTracks = parser._createAnimationTracks(node, inputAccessor, outputAccessor, sampler, target); + if (createdTracks) { + for (let k2 = 0;k2 < createdTracks.length; k2++) { + tracks.push(createdTracks[k2]); + } + } + } + return new AnimationClip(animationName, undefined, tracks); + }); + } + createNodeMesh(nodeIndex) { + const json = this.json; + const parser = this; + const nodeDef = json.nodes[nodeIndex]; + if (nodeDef.mesh === undefined) + return null; + return parser.getDependency("mesh", nodeDef.mesh).then(function(mesh) { + const node = parser._getNodeRef(parser.meshCache, nodeDef.mesh, mesh); + if (nodeDef.weights !== undefined) { + node.traverse(function(o) { + if (!o.isMesh) + return; + for (let i = 0, il = nodeDef.weights.length;i < il; i++) { + o.morphTargetInfluences[i] = nodeDef.weights[i]; + } + }); + } + return node; + }); + } + loadNode(nodeIndex) { + const json = this.json; + const parser = this; + const nodeDef = json.nodes[nodeIndex]; + const nodePending = parser._loadNodeShallow(nodeIndex); + const childPending = []; + const childrenDef = nodeDef.children || []; + for (let i = 0, il = childrenDef.length;i < il; i++) { + childPending.push(parser.getDependency("node", childrenDef[i])); + } + const skeletonPending = nodeDef.skin === undefined ? Promise.resolve(null) : parser.getDependency("skin", nodeDef.skin); + return Promise.all([ + nodePending, + Promise.all(childPending), + skeletonPending + ]).then(function(results) { + const node = results[0]; + const children = results[1]; + const skeleton = results[2]; + if (skeleton !== null) { + node.traverse(function(mesh) { + if (!mesh.isSkinnedMesh) + return; + mesh.bind(skeleton, _identityMatrix2); + }); + } + for (let i = 0, il = children.length;i < il; i++) { + node.add(children[i]); + } + return node; + }); + } + _loadNodeShallow(nodeIndex) { + const json = this.json; + const extensions = this.extensions; + const parser = this; + if (this.nodeCache[nodeIndex] !== undefined) { + return this.nodeCache[nodeIndex]; + } + const nodeDef = json.nodes[nodeIndex]; + const nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : ""; + const pending = []; + const meshPromise = parser._invokeOne(function(ext) { + return ext.createNodeMesh && ext.createNodeMesh(nodeIndex); + }); + if (meshPromise) { + pending.push(meshPromise); + } + if (nodeDef.camera !== undefined) { + pending.push(parser.getDependency("camera", nodeDef.camera).then(function(camera) { + return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera); + })); + } + parser._invokeAll(function(ext) { + return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex); + }).forEach(function(promise) { + pending.push(promise); + }); + this.nodeCache[nodeIndex] = Promise.all(pending).then(function(objects) { + let node; + if (nodeDef.isBone === true) { + node = new Bone; + } else if (objects.length > 1) { + node = new Group; + } else if (objects.length === 1) { + node = objects[0]; + } else { + node = new Object3D; + } + if (node !== objects[0]) { + for (let i = 0, il = objects.length;i < il; i++) { + node.add(objects[i]); + } + } + if (nodeDef.name) { + node.userData.name = nodeDef.name; + node.name = nodeName; + } + assignExtrasToUserData(node, nodeDef); + if (nodeDef.extensions) + addUnknownExtensionsToUserData(extensions, node, nodeDef); + if (nodeDef.matrix !== undefined) { + const matrix = new Matrix4; + matrix.fromArray(nodeDef.matrix); + node.applyMatrix4(matrix); + } else { + if (nodeDef.translation !== undefined) { + node.position.fromArray(nodeDef.translation); + } + if (nodeDef.rotation !== undefined) { + node.quaternion.fromArray(nodeDef.rotation); + } + if (nodeDef.scale !== undefined) { + node.scale.fromArray(nodeDef.scale); + } + } + if (!parser.associations.has(node)) { + parser.associations.set(node, {}); + } + parser.associations.get(node).nodes = nodeIndex; + return node; + }); + return this.nodeCache[nodeIndex]; + } + loadScene(sceneIndex) { + const extensions = this.extensions; + const sceneDef = this.json.scenes[sceneIndex]; + const parser = this; + const scene = new Group; + if (sceneDef.name) + scene.name = parser.createUniqueName(sceneDef.name); + assignExtrasToUserData(scene, sceneDef); + if (sceneDef.extensions) + addUnknownExtensionsToUserData(extensions, scene, sceneDef); + const nodeIds = sceneDef.nodes || []; + const pending = []; + for (let i = 0, il = nodeIds.length;i < il; i++) { + pending.push(parser.getDependency("node", nodeIds[i])); + } + return Promise.all(pending).then(function(nodes) { + for (let i = 0, il = nodes.length;i < il; i++) { + scene.add(nodes[i]); + } + const reduceAssociations = (node) => { + const reducedAssociations = new Map; + for (const [key2, value2] of parser.associations) { + if (key2 instanceof Material || key2 instanceof Texture) { + reducedAssociations.set(key2, value2); + } + } + node.traverse((node2) => { + const mappings = parser.associations.get(node2); + if (mappings != null) { + reducedAssociations.set(node2, mappings); + } + }); + return reducedAssociations; + }; + parser.associations = reduceAssociations(scene); + return scene; + }); + } + _createAnimationTracks(node, inputAccessor, outputAccessor, sampler, target) { + const tracks = []; + const targetName = node.name ? node.name : node.uuid; + const targetNames = []; + if (PATH_PROPERTIES2[target.path] === PATH_PROPERTIES2.weights) { + node.traverse(function(object) { + if (object.morphTargetInfluences) { + targetNames.push(object.name ? object.name : object.uuid); + } + }); + } else { + targetNames.push(targetName); + } + let TypedKeyframeTrack; + switch (PATH_PROPERTIES2[target.path]) { + case PATH_PROPERTIES2.weights: + TypedKeyframeTrack = NumberKeyframeTrack; + break; + case PATH_PROPERTIES2.rotation: + TypedKeyframeTrack = QuaternionKeyframeTrack; + break; + case PATH_PROPERTIES2.position: + case PATH_PROPERTIES2.scale: + TypedKeyframeTrack = VectorKeyframeTrack; + break; + default: + switch (outputAccessor.itemSize) { + case 1: + TypedKeyframeTrack = NumberKeyframeTrack; + break; + case 2: + case 3: + default: + TypedKeyframeTrack = VectorKeyframeTrack; + break; + } + break; + } + const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : InterpolateLinear; + const outputArray = this._getArrayFromAccessor(outputAccessor); + for (let j2 = 0, jl = targetNames.length;j2 < jl; j2++) { + const track = new TypedKeyframeTrack(targetNames[j2] + "." + PATH_PROPERTIES2[target.path], inputAccessor.array, outputArray, interpolation); + if (sampler.interpolation === "CUBICSPLINE") { + this._createCubicSplineTrackInterpolant(track); + } + tracks.push(track); + } + return tracks; + } + _getArrayFromAccessor(accessor) { + let outputArray = accessor.array; + if (accessor.normalized) { + const scale2 = getNormalizedComponentScale(outputArray.constructor); + const scaled = new Float32Array(outputArray.length); + for (let j2 = 0, jl = outputArray.length;j2 < jl; j2++) { + scaled[j2] = outputArray[j2] * scale2; + } + outputArray = scaled; + } + return outputArray; + } + _createCubicSplineTrackInterpolant(track) { + track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) { + const interpolantType = this instanceof QuaternionKeyframeTrack ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant; + return new interpolantType(this.times, this.values, this.getValueSize() / 3, result); + }; + track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true; + } +} +function computeBounds(geometry, primitiveDef, parser) { + const attributes = primitiveDef.attributes; + const box = new Box3; + if (attributes.POSITION !== undefined) { + const accessor = parser.json.accessors[attributes.POSITION]; + const min = accessor.min; + const max = accessor.max; + if (min !== undefined && max !== undefined) { + box.set(new Vector3(min[0], min[1], min[2]), new Vector3(max[0], max[1], max[2])); + if (accessor.normalized) { + const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]); + box.min.multiplyScalar(boxScale); + box.max.multiplyScalar(boxScale); + } + } else { + console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION."); + return; + } + } else { + return; + } + const targets = primitiveDef.targets; + if (targets !== undefined) { + const maxDisplacement = new Vector3; + const vector = new Vector3; + for (let i = 0, il = targets.length;i < il; i++) { + const target = targets[i]; + if (target.POSITION !== undefined) { + const accessor = parser.json.accessors[target.POSITION]; + const min = accessor.min; + const max = accessor.max; + if (min !== undefined && max !== undefined) { + vector.setX(Math.max(Math.abs(min[0]), Math.abs(max[0]))); + vector.setY(Math.max(Math.abs(min[1]), Math.abs(max[1]))); + vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max[2]))); + if (accessor.normalized) { + const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]); + vector.multiplyScalar(boxScale); + } + maxDisplacement.max(vector); + } else { + console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION."); + } + } + } + box.expandByVector(maxDisplacement); + } + geometry.boundingBox = box; + const sphere = new Sphere; + box.getCenter(sphere.center); + sphere.radius = box.min.distanceTo(box.max) / 2; + geometry.boundingSphere = sphere; +} +function addPrimitiveAttributes(geometry, primitiveDef, parser) { + const attributes = primitiveDef.attributes; + const pending = []; + function assignAttributeAccessor(accessorIndex, attributeName) { + return parser.getDependency("accessor", accessorIndex).then(function(accessor) { + geometry.setAttribute(attributeName, accessor); + }); + } + for (const gltfAttributeName in attributes) { + const threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); + if (threeAttributeName in geometry.attributes) + continue; + pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName)); + } + if (primitiveDef.indices !== undefined && !geometry.index) { + const accessor = parser.getDependency("accessor", primitiveDef.indices).then(function(accessor2) { + geometry.setIndex(accessor2); + }); + pending.push(accessor); + } + if (ColorManagement.workingColorSpace !== LinearSRGBColorSpace && "COLOR_0" in attributes) { + console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ColorManagement.workingColorSpace}" not supported.`); + } + assignExtrasToUserData(geometry, primitiveDef); + computeBounds(geometry, primitiveDef, parser); + return Promise.all(pending).then(function() { + return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry; + }); +} +// node_modules/three/examples/jsm/utils/WorkerPool.js +class WorkerPool { + constructor(pool = 4) { + this.pool = pool; + this.queue = []; + this.workers = []; + this.workersResolve = []; + this.workerStatus = 0; + } + _initWorker(workerId) { + if (!this.workers[workerId]) { + const worker = this.workerCreator(); + worker.addEventListener("message", this._onMessage.bind(this, workerId)); + this.workers[workerId] = worker; + } + } + _getIdleWorker() { + for (let i = 0;i < this.pool; i++) + if (!(this.workerStatus & 1 << i)) + return i; + return -1; + } + _onMessage(workerId, msg) { + const resolve = this.workersResolve[workerId]; + resolve && resolve(msg); + if (this.queue.length) { + const { resolve: resolve2, msg: msg2, transfer } = this.queue.shift(); + this.workersResolve[workerId] = resolve2; + this.workers[workerId].postMessage(msg2, transfer); + } else { + this.workerStatus ^= 1 << workerId; + } + } + setWorkerCreator(workerCreator) { + this.workerCreator = workerCreator; + } + setWorkerLimit(pool) { + this.pool = pool; + } + postMessage(msg, transfer) { + return new Promise((resolve) => { + const workerId = this._getIdleWorker(); + if (workerId !== -1) { + this._initWorker(workerId); + this.workerStatus |= 1 << workerId; + this.workersResolve[workerId] = resolve; + this.workers[workerId].postMessage(msg, transfer); + } else { + this.queue.push({ resolve, msg, transfer }); + } + }); + } + dispose() { + this.workers.forEach((worker) => worker.terminate()); + this.workersResolve.length = 0; + this.workers.length = 0; + this.queue.length = 0; + this.workerStatus = 0; + } +} + +// node_modules/three/examples/jsm/libs/zstddec.module.js +var A; +var I2; +var B; +var g2 = { env: { emscripten_notify_memory_growth: function(A2) { + B = new Uint8Array(I2.exports.memory.buffer); +} } }; + +class Q { + init() { + return A || (A = typeof fetch != "undefined" ? fetch("data:application/wasm;base64," + C3).then((A2) => A2.arrayBuffer()).then((A2) => WebAssembly.instantiate(A2, g2)).then(this._init) : WebAssembly.instantiate(Buffer.from(C3, "base64"), g2).then(this._init), A); + } + _init(A2) { + I2 = A2.instance, g2.env.emscripten_notify_memory_growth(0); + } + decode(A2, g3 = 0) { + if (!I2) + throw new Error("ZSTDDecoder: Await .init() before decoding."); + const Q2 = A2.byteLength, C3 = I2.exports.malloc(Q2); + B.set(A2, C3), g3 = g3 || Number(I2.exports.ZSTD_findDecompressedSize(C3, Q2)); + const E2 = I2.exports.malloc(g3), i = I2.exports.ZSTD_decompress(E2, g3, C3, Q2), D = B.slice(E2, E2 + i); + return I2.exports.free(C3), I2.exports.free(E2), D; + } +} +var C3 = "AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDBgEACQkHBgICAAYGAgQUBwYGAwIGAAMCAQgBBwUGCgoEEQAEBAEIAwgDBQgDEA8IAAcABAUBcAECAgUEAQCAAgYJAX8BQaCgwAILB2AHBm1lbW9yeQIABm1hbGxvYwAoBGZyZWUAJgxaU1REX2lzRXJyb3IAaBlaU1REX2ZpbmREZWNvbXByZXNzZWRTaXplAFQPWlNURF9kZWNvbXByZXNzAEoGX3N0YXJ0ACQJBwEAQQELASQKussBaA8AIAAgACgCBCABajYCBAsZACAAKAIAIAAoAgRBH3F0QQAgAWtBH3F2CwgAIABBiH9LC34BBH9BAyEBIAAoAgQiA0EgTQRAIAAoAggiASAAKAIQTwRAIAAQDQ8LIAAoAgwiAiABRgRAQQFBAiADQSBJGw8LIAAgASABIAJrIANBA3YiBCABIARrIAJJIgEbIgJrIgQ2AgggACADIAJBA3RrNgIEIAAgBCgAADYCAAsgAQsUAQF/IAAgARACIQIgACABEAEgAgv3AQECfyACRQRAIABCADcCACAAQQA2AhAgAEIANwIIQbh/DwsgACABNgIMIAAgAUEEajYCECACQQRPBEAgACABIAJqIgFBfGoiAzYCCCAAIAMoAAA2AgAgAUF/ai0AACIBBEAgAEEIIAEQFGs2AgQgAg8LIABBADYCBEF/DwsgACABNgIIIAAgAS0AACIDNgIAIAJBfmoiBEEBTQRAIARBAWtFBEAgACABLQACQRB0IANyIgM2AgALIAAgAS0AAUEIdCADajYCAAsgASACakF/ai0AACIBRQRAIABBADYCBEFsDwsgAEEoIAEQFCACQQN0ams2AgQgAgsWACAAIAEpAAA3AAAgACABKQAINwAICy8BAX8gAUECdEGgHWooAgAgACgCAEEgIAEgACgCBGprQR9xdnEhAiAAIAEQASACCyEAIAFCz9bTvtLHq9lCfiAAfEIfiUKHla+vmLbem55/fgsdAQF/IAAoAgggACgCDEYEfyAAKAIEQSBGBUEACwuCBAEDfyACQYDAAE8EQCAAIAEgAhBnIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAsMACAAIAEpAAA3AAALQQECfyAAKAIIIgEgACgCEEkEQEEDDwsgACAAKAIEIgJBB3E2AgQgACABIAJBA3ZrIgE2AgggACABKAAANgIAQQALDAAgACABKAIANgAAC/cCAQJ/AkAgACABRg0AAkAgASACaiAASwRAIAAgAmoiBCABSw0BCyAAIAEgAhALDwsgACABc0EDcSEDAkACQCAAIAFJBEAgAwRAIAAhAwwDCyAAQQNxRQRAIAAhAwwCCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigCACACaiAAQQZ2IgFBAnRBsB5qKAIAaiAAQSBxIgBFaiABRSAAQQV2cWoFQbh/CwsdACAAKAKQ4gEQWiAAQQA2AqDiASAAQgA3A5DiAQu1AwEFfyMAQZACayIKJABBuH8hBgJAIAVFDQAgBCwAACIIQf8BcSEHAkAgCEF/TARAIAdBgn9qQQF2IgggBU8NAkFsIQYgB0GBf2oiBUGAAk8NAiAEQQFqIQdBACEGA0AgBiAFTwRAIAUhBiAIIQcMAwUgACAGaiAHIAZBAXZqIgQtAABBBHY6AAAgACAGQQFyaiAELQAAQQ9xOgAAIAZBAmohBgwBCwAACwALIAcgBU8NASAAIARBAWogByAKEFMiBhADDQELIAYhBEEAIQYgAUEAQTQQECEJQQAhBQNAIAQgBkcEQCAAIAZqIggtAAAiAUELSwRAQWwhBgwDBSAJIAFBAnRqIgEgASgCAEEBajYCACAGQQFqIQZBASAILQAAdEEBdSAFaiEFDAILAAsLQWwhBiAFRQ0AIAUQFEEBaiIBQQxLDQAgAyABNgIAQQFBASABdCAFayIDEBQiAXQgA0cNACAAIARqIAFBAWoiADoAACAJIABBAnRqIgAgACgCAEEBajYCACAJKAIEIgBBAkkgAEEBcXINACACIARBAWo2AgAgB0EBaiEGCyAKQZACaiQAIAYLxhEBDH8jAEHwAGsiBSQAQWwhCwJAIANBCkkNACACLwAAIQogAi8AAiEJIAIvAAQhByAFQQhqIAQQDgJAIAMgByAJIApqakEGaiIMSQ0AIAUtAAohCCAFQdgAaiACQQZqIgIgChAGIgsQAw0BIAVBQGsgAiAKaiICIAkQBiILEAMNASAFQShqIAIgCWoiAiAHEAYiCxADDQEgBUEQaiACIAdqIAMgDGsQBiILEAMNASAAIAFqIg9BfWohECAEQQRqIQZBASELIAAgAUEDakECdiIDaiIMIANqIgIgA2oiDiEDIAIhBCAMIQcDQCALIAMgEElxBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgCS0AAyELIAcgBiAFQUBrIAgQAkECdGoiCS8BADsAACAFQUBrIAktAAIQASAJLQADIQogBCAGIAVBKGogCBACQQJ0aiIJLwEAOwAAIAVBKGogCS0AAhABIAktAAMhCSADIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgDS0AAyENIAAgC2oiCyAGIAVB2ABqIAgQAkECdGoiAC8BADsAACAFQdgAaiAALQACEAEgAC0AAyEAIAcgCmoiCiAGIAVBQGsgCBACQQJ0aiIHLwEAOwAAIAVBQGsgBy0AAhABIActAAMhByAEIAlqIgkgBiAFQShqIAgQAkECdGoiBC8BADsAACAFQShqIAQtAAIQASAELQADIQQgAyANaiIDIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgACALaiEAIAcgCmohByAEIAlqIQQgAyANLQADaiEDIAVB2ABqEA0gBUFAaxANciAFQShqEA1yIAVBEGoQDXJFIQsMAQsLIAQgDksgByACS3INAEFsIQsgACAMSw0BIAxBfWohCQNAQQAgACAJSSAFQdgAahAEGwRAIAAgBiAFQdgAaiAIEAJBAnRqIgovAQA7AAAgBUHYAGogCi0AAhABIAAgCi0AA2oiACAGIAVB2ABqIAgQAkECdGoiCi8BADsAACAFQdgAaiAKLQACEAEgACAKLQADaiEADAEFIAxBfmohCgNAIAVB2ABqEAQgACAKS3JFBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgACAJLQADaiEADAELCwNAIAAgCk0EQCAAIAYgBUHYAGogCBACQQJ0aiIJLwEAOwAAIAVB2ABqIAktAAIQASAAIAktAANqIQAMAQsLAkAgACAMTw0AIAAgBiAFQdgAaiAIEAIiAEECdGoiDC0AADoAACAMLQADQQFGBEAgBUHYAGogDC0AAhABDAELIAUoAlxBH0sNACAFQdgAaiAGIABBAnRqLQACEAEgBSgCXEEhSQ0AIAVBIDYCXAsgAkF9aiEMA0BBACAHIAxJIAVBQGsQBBsEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiIAIAYgBUFAayAIEAJBAnRqIgcvAQA7AAAgBUFAayAHLQACEAEgACAHLQADaiEHDAEFIAJBfmohDANAIAVBQGsQBCAHIAxLckUEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwNAIAcgDE0EQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwJAIAcgAk8NACAHIAYgBUFAayAIEAIiAEECdGoiAi0AADoAACACLQADQQFGBEAgBUFAayACLQACEAEMAQsgBSgCREEfSw0AIAVBQGsgBiAAQQJ0ai0AAhABIAUoAkRBIUkNACAFQSA2AkQLIA5BfWohAgNAQQAgBCACSSAFQShqEAQbBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2oiACAGIAVBKGogCBACQQJ0aiIELwEAOwAAIAVBKGogBC0AAhABIAAgBC0AA2ohBAwBBSAOQX5qIQIDQCAFQShqEAQgBCACS3JFBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsDQCAEIAJNBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsCQCAEIA5PDQAgBCAGIAVBKGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBKGogAi0AAhABDAELIAUoAixBH0sNACAFQShqIAYgAEECdGotAAIQASAFKAIsQSFJDQAgBUEgNgIsCwNAQQAgAyAQSSAFQRBqEAQbBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2oiACAGIAVBEGogCBACQQJ0aiICLwEAOwAAIAVBEGogAi0AAhABIAAgAi0AA2ohAwwBBSAPQX5qIQIDQCAFQRBqEAQgAyACS3JFBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsDQCADIAJNBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsCQCADIA9PDQAgAyAGIAVBEGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBEGogAi0AAhABDAELIAUoAhRBH0sNACAFQRBqIAYgAEECdGotAAIQASAFKAIUQSFJDQAgBUEgNgIUCyABQWwgBUHYAGoQCiAFQUBrEApxIAVBKGoQCnEgBUEQahAKcRshCwwJCwAACwALAAALAAsAAAsACwAACwALQWwhCwsgBUHwAGokACALC7UEAQ5/IwBBEGsiBiQAIAZBBGogABAOQVQhBQJAIARB3AtJDQAgBi0ABCEHIANB8ARqQQBB7AAQECEIIAdBDEsNACADQdwJaiIJIAggBkEIaiAGQQxqIAEgAhAxIhAQA0UEQCAGKAIMIgQgB0sNASADQdwFaiEPIANBpAVqIREgAEEEaiESIANBqAVqIQEgBCEFA0AgBSICQX9qIQUgCCACQQJ0aigCAEUNAAsgAkEBaiEOQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgASALaiAKNgIAIAVBAWohBSAKIAxqIQoMAQsLIAEgCjYCAEEAIQUgBigCCCELA0AgBSALRkUEQCABIAUgCWotAAAiDEECdGoiDSANKAIAIg1BAWo2AgAgDyANQQF0aiINIAw6AAEgDSAFOgAAIAVBAWohBQwBCwtBACEBIANBADYCqAUgBEF/cyAHaiEJQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgAyALaiABNgIAIAwgBSAJanQgAWohASAFQQFqIQUMAQsLIAcgBEEBaiIBIAJrIgRrQQFqIQgDQEEBIQUgBCAIT0UEQANAIAUgDk9FBEAgBUECdCIJIAMgBEE0bGpqIAMgCWooAgAgBHY2AgAgBUEBaiEFDAELCyAEQQFqIQQMAQsLIBIgByAPIAogESADIAIgARBkIAZBAToABSAGIAc6AAYgACAGKAIENgIACyAQIQULIAZBEGokACAFC8ENAQt/IwBB8ABrIgUkAEFsIQkCQCADQQpJDQAgAi8AACEKIAIvAAIhDCACLwAEIQYgBUEIaiAEEA4CQCADIAYgCiAMampBBmoiDUkNACAFLQAKIQcgBUHYAGogAkEGaiICIAoQBiIJEAMNASAFQUBrIAIgCmoiAiAMEAYiCRADDQEgBUEoaiACIAxqIgIgBhAGIgkQAw0BIAVBEGogAiAGaiADIA1rEAYiCRADDQEgACABaiIOQX1qIQ8gBEEEaiEGQQEhCSAAIAFBA2pBAnYiAmoiCiACaiIMIAJqIg0hAyAMIQQgCiECA0AgCSADIA9JcQRAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAACAGIAVBQGsgBxACQQF0aiIILQAAIQsgBUFAayAILQABEAEgAiALOgAAIAYgBUEoaiAHEAJBAXRqIggtAAAhCyAFQShqIAgtAAEQASAEIAs6AAAgBiAFQRBqIAcQAkEBdGoiCC0AACELIAVBEGogCC0AARABIAMgCzoAACAGIAVB2ABqIAcQAkEBdGoiCC0AACELIAVB2ABqIAgtAAEQASAAIAs6AAEgBiAFQUBrIAcQAkEBdGoiCC0AACELIAVBQGsgCC0AARABIAIgCzoAASAGIAVBKGogBxACQQF0aiIILQAAIQsgBUEoaiAILQABEAEgBCALOgABIAYgBUEQaiAHEAJBAXRqIggtAAAhCyAFQRBqIAgtAAEQASADIAs6AAEgA0ECaiEDIARBAmohBCACQQJqIQIgAEECaiEAIAkgBUHYAGoQDUVxIAVBQGsQDUVxIAVBKGoQDUVxIAVBEGoQDUVxIQkMAQsLIAQgDUsgAiAMS3INAEFsIQkgACAKSw0BIApBfWohCQNAIAVB2ABqEAQgACAJT3JFBEAgBiAFQdgAaiAHEAJBAXRqIggtAAAhCyAFQdgAaiAILQABEAEgACALOgAAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAASAAQQJqIQAMAQsLA0AgBUHYAGoQBCAAIApPckUEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCwNAIAAgCkkEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCyAMQX1qIQADQCAFQUBrEAQgAiAAT3JFBEAgBiAFQUBrIAcQAkEBdGoiCi0AACEJIAVBQGsgCi0AARABIAIgCToAACAGIAVBQGsgBxACQQF0aiIKLQAAIQkgBUFAayAKLQABEAEgAiAJOgABIAJBAmohAgwBCwsDQCAFQUBrEAQgAiAMT3JFBEAgBiAFQUBrIAcQAkEBdGoiAC0AACEKIAVBQGsgAC0AARABIAIgCjoAACACQQFqIQIMAQsLA0AgAiAMSQRAIAYgBUFAayAHEAJBAXRqIgAtAAAhCiAFQUBrIAAtAAEQASACIAo6AAAgAkEBaiECDAELCyANQX1qIQADQCAFQShqEAQgBCAAT3JFBEAgBiAFQShqIAcQAkEBdGoiAi0AACEKIAVBKGogAi0AARABIAQgCjoAACAGIAVBKGogBxACQQF0aiICLQAAIQogBUEoaiACLQABEAEgBCAKOgABIARBAmohBAwBCwsDQCAFQShqEAQgBCANT3JFBEAgBiAFQShqIAcQAkEBdGoiAC0AACECIAVBKGogAC0AARABIAQgAjoAACAEQQFqIQQMAQsLA0AgBCANSQRAIAYgBUEoaiAHEAJBAXRqIgAtAAAhAiAFQShqIAAtAAEQASAEIAI6AAAgBEEBaiEEDAELCwNAIAVBEGoQBCADIA9PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIAYgBUEQaiAHEAJBAXRqIgAtAAAhAiAFQRBqIAAtAAEQASADIAI6AAEgA0ECaiEDDAELCwNAIAVBEGoQBCADIA5PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIANBAWohAwwBCwsDQCADIA5JBEAgBiAFQRBqIAcQAkEBdGoiAC0AACECIAVBEGogAC0AARABIAMgAjoAACADQQFqIQMMAQsLIAFBbCAFQdgAahAKIAVBQGsQCnEgBUEoahAKcSAFQRBqEApxGyEJDAELQWwhCQsgBUHwAGokACAJC8oCAQR/IwBBIGsiBSQAIAUgBBAOIAUtAAIhByAFQQhqIAIgAxAGIgIQA0UEQCAEQQRqIQIgACABaiIDQX1qIQQDQCAFQQhqEAQgACAET3JFBEAgAiAFQQhqIAcQAkEBdGoiBi0AACEIIAVBCGogBi0AARABIAAgCDoAACACIAVBCGogBxACQQF0aiIGLQAAIQggBUEIaiAGLQABEAEgACAIOgABIABBAmohAAwBCwsDQCAFQQhqEAQgACADT3JFBEAgAiAFQQhqIAcQAkEBdGoiBC0AACEGIAVBCGogBC0AARABIAAgBjoAACAAQQFqIQAMAQsLA0AgACADT0UEQCACIAVBCGogBxACQQF0aiIELQAAIQYgBUEIaiAELQABEAEgACAGOgAAIABBAWohAAwBCwsgAUFsIAVBCGoQChshAgsgBUEgaiQAIAILtgMBCX8jAEEQayIGJAAgBkEANgIMIAZBADYCCEFUIQQCQAJAIANBQGsiDCADIAZBCGogBkEMaiABIAIQMSICEAMNACAGQQRqIAAQDiAGKAIMIgcgBi0ABEEBaksNASAAQQRqIQogBkEAOgAFIAYgBzoABiAAIAYoAgQ2AgAgB0EBaiEJQQEhBANAIAQgCUkEQCADIARBAnRqIgEoAgAhACABIAU2AgAgACAEQX9qdCAFaiEFIARBAWohBAwBCwsgB0EBaiEHQQAhBSAGKAIIIQkDQCAFIAlGDQEgAyAFIAxqLQAAIgRBAnRqIgBBASAEdEEBdSILIAAoAgAiAWoiADYCACAHIARrIQhBACEEAkAgC0EDTQRAA0AgBCALRg0CIAogASAEakEBdGoiACAIOgABIAAgBToAACAEQQFqIQQMAAALAAsDQCABIABPDQEgCiABQQF0aiIEIAg6AAEgBCAFOgAAIAQgCDoAAyAEIAU6AAIgBCAIOgAFIAQgBToABCAEIAg6AAcgBCAFOgAGIAFBBGohAQwAAAsACyAFQQFqIQUMAAALAAsgAiEECyAGQRBqJAAgBAutAQECfwJAQYQgKAIAIABHIAAoAgBBAXYiAyABa0F4aiICQXhxQQhHcgR/IAIFIAMQJ0UNASACQQhqC0EQSQ0AIAAgACgCACICQQFxIAAgAWpBD2pBeHEiASAAa0EBdHI2AgAgASAANgIEIAEgASgCAEEBcSAAIAJBAXZqIAFrIgJBAXRyNgIAQYQgIAEgAkH/////B3FqQQRqQYQgKAIAIABGGyABNgIAIAEQJQsLygIBBX8CQAJAAkAgAEEIIABBCEsbZ0EfcyAAaUEBR2oiAUEESSAAIAF2cg0AIAFBAnRB/B5qKAIAIgJFDQADQCACQXhqIgMoAgBBAXZBeGoiBSAATwRAIAIgBUEIIAVBCEsbZ0Efc0ECdEGAH2oiASgCAEYEQCABIAIoAgQ2AgALDAMLIARBHksNASAEQQFqIQQgAigCBCICDQALC0EAIQMgAUEgTw0BA0AgAUECdEGAH2ooAgAiAkUEQCABQR5LIQIgAUEBaiEBIAJFDQEMAwsLIAIgAkF4aiIDKAIAQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgBGBEAgASACKAIENgIACwsgAigCACIBBEAgASACKAIENgIECyACKAIEIgEEQCABIAIoAgA2AgALIAMgAygCAEEBcjYCACADIAAQNwsgAwvhCwINfwV+IwBB8ABrIgckACAHIAAoAvDhASIINgJcIAEgAmohDSAIIAAoAoDiAWohDwJAAkAgBUUEQCABIQQMAQsgACgCxOABIRAgACgCwOABIREgACgCvOABIQ4gAEEBNgKM4QFBACEIA0AgCEEDRwRAIAcgCEECdCICaiAAIAJqQazQAWooAgA2AkQgCEEBaiEIDAELC0FsIQwgB0EYaiADIAQQBhADDQEgB0EsaiAHQRhqIAAoAgAQEyAHQTRqIAdBGGogACgCCBATIAdBPGogB0EYaiAAKAIEEBMgDUFgaiESIAEhBEEAIQwDQCAHKAIwIAcoAixBA3RqKQIAIhRCEIinQf8BcSEIIAcoAkAgBygCPEEDdGopAgAiFUIQiKdB/wFxIQsgBygCOCAHKAI0QQN0aikCACIWQiCIpyEJIBVCIIghFyAUQiCIpyECAkAgFkIQiKdB/wFxIgNBAk8EQAJAIAZFIANBGUlyRQRAIAkgB0EYaiADQSAgBygCHGsiCiAKIANLGyIKEAUgAyAKayIDdGohCSAHQRhqEAQaIANFDQEgB0EYaiADEAUgCWohCQwBCyAHQRhqIAMQBSAJaiEJIAdBGGoQBBoLIAcpAkQhGCAHIAk2AkQgByAYNwNIDAELAkAgA0UEQCACBEAgBygCRCEJDAMLIAcoAkghCQwBCwJAAkAgB0EYakEBEAUgCSACRWpqIgNBA0YEQCAHKAJEQX9qIgMgA0VqIQkMAQsgA0ECdCAHaigCRCIJIAlFaiEJIANBAUYNAQsgByAHKAJINgJMCwsgByAHKAJENgJIIAcgCTYCRAsgF6chAyALBEAgB0EYaiALEAUgA2ohAwsgCCALakEUTwRAIAdBGGoQBBoLIAgEQCAHQRhqIAgQBSACaiECCyAHQRhqEAQaIAcgB0EYaiAUQhiIp0H/AXEQCCAUp0H//wNxajYCLCAHIAdBGGogFUIYiKdB/wFxEAggFadB//8DcWo2AjwgB0EYahAEGiAHIAdBGGogFkIYiKdB/wFxEAggFqdB//8DcWo2AjQgByACNgJgIAcoAlwhCiAHIAk2AmggByADNgJkAkACQAJAIAQgAiADaiILaiASSw0AIAIgCmoiEyAPSw0AIA0gBGsgC0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ"; + +// node_modules/three/examples/jsm/math/ColorSpaces.js +var DisplayP3ColorSpace = "display-p3"; +var LinearDisplayP3ColorSpace = "display-p3-linear"; + +// node_modules/three/examples/jsm/loaders/KTX2Loader.js +var _taskCache3 = new WeakMap; +var _activeLoaders = 0; +var _zstd; + +class KTX2Loader extends Loader { + constructor(manager) { + super(manager); + this.transcoderPath = ""; + this.transcoderBinary = null; + this.transcoderPending = null; + this.workerPool = new WorkerPool; + this.workerSourceURL = ""; + this.workerConfig = null; + if (typeof MSC_TRANSCODER !== "undefined") { + console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder".' + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'); + } + } + setTranscoderPath(path) { + this.transcoderPath = path; + return this; + } + setWorkerLimit(num) { + this.workerPool.setWorkerLimit(num); + return this; + } + async detectSupportAsync(renderer2) { + this.workerConfig = { + astcSupported: await renderer2.hasFeatureAsync("texture-compression-astc"), + astcHDRSupported: false, + etc1Supported: await renderer2.hasFeatureAsync("texture-compression-etc1"), + etc2Supported: await renderer2.hasFeatureAsync("texture-compression-etc2"), + dxtSupported: await renderer2.hasFeatureAsync("texture-compression-bc"), + bptcSupported: await renderer2.hasFeatureAsync("texture-compression-bptc"), + pvrtcSupported: await renderer2.hasFeatureAsync("texture-compression-pvrtc") + }; + return this; + } + detectSupport(renderer2) { + if (renderer2.isWebGPURenderer === true) { + this.workerConfig = { + astcSupported: renderer2.hasFeature("texture-compression-astc"), + astcHDRSupported: false, + etc1Supported: renderer2.hasFeature("texture-compression-etc1"), + etc2Supported: renderer2.hasFeature("texture-compression-etc2"), + dxtSupported: renderer2.hasFeature("texture-compression-bc"), + bptcSupported: renderer2.hasFeature("texture-compression-bptc"), + pvrtcSupported: renderer2.hasFeature("texture-compression-pvrtc") + }; + } else { + this.workerConfig = { + astcSupported: renderer2.extensions.has("WEBGL_compressed_texture_astc"), + astcHDRSupported: renderer2.extensions.has("WEBGL_compressed_texture_astc") && renderer2.extensions.get("WEBGL_compressed_texture_astc").getSupportedProfiles().includes("hdr"), + etc1Supported: renderer2.extensions.has("WEBGL_compressed_texture_etc1"), + etc2Supported: renderer2.extensions.has("WEBGL_compressed_texture_etc"), + dxtSupported: renderer2.extensions.has("WEBGL_compressed_texture_s3tc"), + bptcSupported: renderer2.extensions.has("EXT_texture_compression_bptc"), + pvrtcSupported: renderer2.extensions.has("WEBGL_compressed_texture_pvrtc") || renderer2.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc") + }; + } + return this; + } + init() { + if (!this.transcoderPending) { + const jsLoader = new FileLoader(this.manager); + jsLoader.setPath(this.transcoderPath); + jsLoader.setWithCredentials(this.withCredentials); + const jsContent = jsLoader.loadAsync("basis_transcoder.js"); + const binaryLoader = new FileLoader(this.manager); + binaryLoader.setPath(this.transcoderPath); + binaryLoader.setResponseType("arraybuffer"); + binaryLoader.setWithCredentials(this.withCredentials); + const binaryContent = binaryLoader.loadAsync("basis_transcoder.wasm"); + this.transcoderPending = Promise.all([jsContent, binaryContent]).then(([jsContent2, binaryContent2]) => { + const fn = KTX2Loader.BasisWorker.toString(); + const body = [ + "/* constants */", + "let _EngineFormat = " + JSON.stringify(KTX2Loader.EngineFormat), + "let _EngineType = " + JSON.stringify(KTX2Loader.EngineType), + "let _TranscoderFormat = " + JSON.stringify(KTX2Loader.TranscoderFormat), + "let _BasisFormat = " + JSON.stringify(KTX2Loader.BasisFormat), + "/* basis_transcoder.js */", + jsContent2, + "/* worker */", + fn.substring(fn.indexOf("{") + 1, fn.lastIndexOf("}")) + ].join(` +`); + this.workerSourceURL = URL.createObjectURL(new Blob([body])); + this.transcoderBinary = binaryContent2; + this.workerPool.setWorkerCreator(() => { + const worker = new Worker(this.workerSourceURL); + const transcoderBinary = this.transcoderBinary.slice(0); + worker.postMessage({ type: "init", config: this.workerConfig, transcoderBinary }, [transcoderBinary]); + return worker; + }); + }); + if (_activeLoaders > 0) { + console.warn("THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues." + " Use a single KTX2Loader instance, or call .dispose() on old instances."); + } + _activeLoaders++; + } + return this.transcoderPending; + } + load(url, onLoad, onProgress, onError) { + if (this.workerConfig === null) { + throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`."); + } + const loader = new FileLoader(this.manager); + loader.setResponseType("arraybuffer"); + loader.setWithCredentials(this.withCredentials); + loader.load(url, (buffer) => { + this.parse(buffer, onLoad, onError); + }, onProgress, onError); + } + parse(buffer, onLoad, onError) { + if (this.workerConfig === null) { + throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`."); + } + if (_taskCache3.has(buffer)) { + const cachedTask = _taskCache3.get(buffer); + return cachedTask.promise.then(onLoad).catch(onError); + } + this._createTexture(buffer).then((texture) => onLoad ? onLoad(texture) : null).catch(onError); + } + _createTextureFrom(transcodeResult, container) { + const { type: messageType, error, data: { faces, width: width2, height: height2, format, type, dfdFlags } } = transcodeResult; + if (messageType === "error") + return Promise.reject(error); + let texture; + if (container.faceCount === 6) { + texture = new CompressedCubeTexture(faces, format, type); + } else { + const mipmaps = faces[0].mipmaps; + texture = container.layerCount > 1 ? new CompressedArrayTexture(mipmaps, width2, height2, container.layerCount, format, type) : new CompressedTexture(mipmaps, width2, height2, format, type); + } + texture.minFilter = faces[0].mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; + texture.magFilter = LinearFilter; + texture.generateMipmaps = false; + texture.needsUpdate = true; + texture.colorSpace = parseColorSpace(container); + texture.premultiplyAlpha = !!(dfdFlags & g); + return texture; + } + async _createTexture(buffer, config = {}) { + const container = Pi2(new Uint8Array(buffer)); + const isBasisHDR = container.vkFormat === pi && container.dataFormatDescriptor[0].colorModel === 167; + const needsTranscoder = container.vkFormat === it || isBasisHDR && !this.workerConfig.astcHDRSupported; + if (!needsTranscoder) { + return createRawTexture(container); + } + const taskConfig = config; + const texturePending = this.init().then(() => { + return this.workerPool.postMessage({ type: "transcode", buffer, taskConfig }, [buffer]); + }).then((e) => this._createTextureFrom(e.data, container)); + _taskCache3.set(buffer, { promise: texturePending }); + return texturePending; + } + dispose() { + this.workerPool.dispose(); + if (this.workerSourceURL) + URL.revokeObjectURL(this.workerSourceURL); + _activeLoaders--; + return this; + } +} +KTX2Loader.BasisFormat = { + ETC1S: 0, + UASTC: 1, + UASTC_HDR: 2 +}; +KTX2Loader.TranscoderFormat = { + ETC1: 0, + ETC2: 1, + BC1: 2, + BC3: 3, + BC4: 4, + BC5: 5, + BC7_M6_OPAQUE_ONLY: 6, + BC7_M5: 7, + PVRTC1_4_RGB: 8, + PVRTC1_4_RGBA: 9, + ASTC_4x4: 10, + ATC_RGB: 11, + ATC_RGBA_INTERPOLATED_ALPHA: 12, + RGBA32: 13, + RGB565: 14, + BGR565: 15, + RGBA4444: 16, + BC6H: 22, + RGB_HALF: 24, + RGBA_HALF: 25 +}; +KTX2Loader.EngineFormat = { + RGBAFormat, + RGBA_ASTC_4x4_Format, + RGB_BPTC_UNSIGNED_Format, + RGBA_BPTC_Format, + RGBA_ETC2_EAC_Format, + RGBA_PVRTC_4BPPV1_Format, + RGBA_S3TC_DXT5_Format, + RGB_ETC1_Format, + RGB_ETC2_Format, + RGB_PVRTC_4BPPV1_Format, + RGBA_S3TC_DXT1_Format +}; +KTX2Loader.EngineType = { + UnsignedByteType, + HalfFloatType, + FloatType +}; +KTX2Loader.BasisWorker = function() { + let config; + let transcoderPending; + let BasisModule; + const EngineFormat = _EngineFormat; + const EngineType = _EngineType; + const TranscoderFormat = _TranscoderFormat; + const BasisFormat = _BasisFormat; + self.addEventListener("message", function(e) { + const message = e.data; + switch (message.type) { + case "init": + config = message.config; + init(message.transcoderBinary); + break; + case "transcode": + transcoderPending.then(() => { + try { + const { faces, buffers, width: width2, height: height2, hasAlpha, format, type, dfdFlags } = transcode(message.buffer); + self.postMessage({ type: "transcode", id: message.id, data: { faces, width: width2, height: height2, hasAlpha, format, type, dfdFlags } }, buffers); + } catch (error) { + console.error(error); + self.postMessage({ type: "error", id: message.id, error: error.message }); + } + }); + break; + } + }); + function init(wasmBinary) { + transcoderPending = new Promise((resolve) => { + BasisModule = { wasmBinary, onRuntimeInitialized: resolve }; + BASIS(BasisModule); + }).then(() => { + BasisModule.initializeBasis(); + if (BasisModule.KTX2File === undefined) { + console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder."); + } + }); + } + function transcode(buffer) { + const ktx2File = new BasisModule.KTX2File(new Uint8Array(buffer)); + function cleanup() { + ktx2File.close(); + ktx2File.delete(); + } + if (!ktx2File.isValid()) { + cleanup(); + throw new Error("THREE.KTX2Loader:\tInvalid or unsupported .ktx2 file"); + } + let basisFormat; + if (ktx2File.isUASTC()) { + basisFormat = BasisFormat.UASTC; + } else if (ktx2File.isETC1S()) { + basisFormat = BasisFormat.ETC1S; + } else if (ktx2File.isHDR()) { + basisFormat = BasisFormat.UASTC_HDR; + } else { + throw new Error("THREE.KTX2Loader: Unknown Basis encoding"); + } + const width2 = ktx2File.getWidth(); + const height2 = ktx2File.getHeight(); + const layerCount = ktx2File.getLayers() || 1; + const levelCount = ktx2File.getLevels(); + const faceCount = ktx2File.getFaces(); + const hasAlpha = ktx2File.getHasAlpha(); + const dfdFlags = ktx2File.getDFDFlags(); + const { transcoderFormat, engineFormat, engineType } = getTranscoderFormat(basisFormat, width2, height2, hasAlpha); + if (!width2 || !height2 || !levelCount) { + cleanup(); + throw new Error("THREE.KTX2Loader:\tInvalid texture"); + } + if (!ktx2File.startTranscoding()) { + cleanup(); + throw new Error("THREE.KTX2Loader: .startTranscoding failed"); + } + const faces = []; + const buffers = []; + for (let face = 0;face < faceCount; face++) { + const mipmaps = []; + for (let mip = 0;mip < levelCount; mip++) { + const layerMips = []; + let mipWidth, mipHeight; + for (let layer = 0;layer < layerCount; layer++) { + const levelInfo = ktx2File.getImageLevelInfo(mip, layer, face); + if (face === 0 && mip === 0 && layer === 0 && (levelInfo.origWidth % 4 !== 0 || levelInfo.origHeight % 4 !== 0)) { + console.warn("THREE.KTX2Loader: ETC1S and UASTC textures should use multiple-of-four dimensions."); + } + if (levelCount > 1) { + mipWidth = levelInfo.origWidth; + mipHeight = levelInfo.origHeight; + } else { + mipWidth = levelInfo.width; + mipHeight = levelInfo.height; + } + let dst = new Uint8Array(ktx2File.getImageTranscodedSizeInBytes(mip, layer, 0, transcoderFormat)); + const status = ktx2File.transcodeImage(dst, mip, layer, face, transcoderFormat, 0, -1, -1); + if (engineType === EngineType.HalfFloatType) { + dst = new Uint16Array(dst.buffer, dst.byteOffset, dst.byteLength / Uint16Array.BYTES_PER_ELEMENT); + } + if (!status) { + cleanup(); + throw new Error("THREE.KTX2Loader: .transcodeImage failed."); + } + layerMips.push(dst); + } + const mipData = concat(layerMips); + mipmaps.push({ data: mipData, width: mipWidth, height: mipHeight }); + buffers.push(mipData.buffer); + } + faces.push({ mipmaps, width: width2, height: height2, format: engineFormat, type: engineType }); + } + cleanup(); + return { faces, buffers, width: width2, height: height2, hasAlpha, dfdFlags, format: engineFormat, type: engineType }; + } + const FORMAT_OPTIONS = [ + { + if: "astcSupported", + basisFormat: [BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4], + engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: Infinity, + priorityUASTC: 1, + needsPowerOfTwo: false + }, + { + if: "bptcSupported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5], + engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 3, + priorityUASTC: 2, + needsPowerOfTwo: false + }, + { + if: "dxtSupported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3], + engineFormat: [EngineFormat.RGBA_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 4, + priorityUASTC: 5, + needsPowerOfTwo: false + }, + { + if: "etc2Supported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2], + engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 1, + priorityUASTC: 3, + needsPowerOfTwo: false + }, + { + if: "etc1Supported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.ETC1], + engineFormat: [EngineFormat.RGB_ETC1_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 2, + priorityUASTC: 4, + needsPowerOfTwo: false + }, + { + if: "pvrtcSupported", + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA], + engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format], + engineType: [EngineType.UnsignedByteType], + priorityETC1S: 5, + priorityUASTC: 6, + needsPowerOfTwo: true + }, + { + if: "bptcSupported", + basisFormat: [BasisFormat.UASTC_HDR], + transcoderFormat: [TranscoderFormat.BC6H], + engineFormat: [EngineFormat.RGB_BPTC_UNSIGNED_Format], + engineType: [EngineType.HalfFloatType], + priorityHDR: 1, + needsPowerOfTwo: false + }, + { + basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC], + transcoderFormat: [TranscoderFormat.RGBA32, TranscoderFormat.RGBA32], + engineFormat: [EngineFormat.RGBAFormat, EngineFormat.RGBAFormat], + engineType: [EngineType.UnsignedByteType, EngineType.UnsignedByteType], + priorityETC1S: 100, + priorityUASTC: 100, + needsPowerOfTwo: false + }, + { + basisFormat: [BasisFormat.UASTC_HDR], + transcoderFormat: [TranscoderFormat.RGBA_HALF], + engineFormat: [EngineFormat.RGBAFormat], + engineType: [EngineType.HalfFloatType], + priorityHDR: 100, + needsPowerOfTwo: false + } + ]; + const OPTIONS = { + [BasisFormat.ETC1S]: FORMAT_OPTIONS.filter((opt) => opt.basisFormat.includes(BasisFormat.ETC1S)).sort((a, b) => a.priorityUASTC - b.priorityUASTC), + [BasisFormat.UASTC]: FORMAT_OPTIONS.filter((opt) => opt.basisFormat.includes(BasisFormat.UASTC)).sort((a, b) => a.priorityUASTC - b.priorityUASTC), + [BasisFormat.UASTC_HDR]: FORMAT_OPTIONS.filter((opt) => opt.basisFormat.includes(BasisFormat.UASTC_HDR)).sort((a, b) => a.priorityHDR - b.priorityHDR) + }; + function getTranscoderFormat(basisFormat, width2, height2, hasAlpha) { + const options = OPTIONS[basisFormat]; + for (let i = 0;i < options.length; i++) { + const opt = options[i]; + if (opt.if && !config[opt.if]) + continue; + if (!opt.basisFormat.includes(basisFormat)) + continue; + if (hasAlpha && opt.transcoderFormat.length < 2) + continue; + if (opt.needsPowerOfTwo && !(isPowerOfTwo2(width2) && isPowerOfTwo2(height2))) + continue; + const transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0]; + const engineFormat = opt.engineFormat[hasAlpha ? 1 : 0]; + const engineType = opt.engineType[0]; + return { transcoderFormat, engineFormat, engineType }; + } + throw new Error("THREE.KTX2Loader: Failed to identify transcoding target."); + } + function isPowerOfTwo2(value2) { + if (value2 <= 2) + return true; + return (value2 & value2 - 1) === 0 && value2 !== 0; + } + function concat(arrays) { + if (arrays.length === 1) + return arrays[0]; + let totalByteLength = 0; + for (let i = 0;i < arrays.length; i++) { + const array = arrays[i]; + totalByteLength += array.byteLength; + } + const result = new Uint8Array(totalByteLength); + let byteOffset = 0; + for (let i = 0;i < arrays.length; i++) { + const array = arrays[i]; + result.set(array, byteOffset); + byteOffset += array.byteLength; + } + return result; + } +}; +var UNCOMPRESSED_FORMATS = new Set([RGBAFormat, RGFormat, RedFormat]); +var FORMAT_MAP = { + [Ae]: RGBAFormat, + [ge]: RGBAFormat, + [Ft]: RGBAFormat, + [Ct]: RGBAFormat, + [we]: RGFormat, + [ae2]: RGFormat, + [xt2]: RGFormat, + [wt]: RGFormat, + [ue2]: RedFormat, + [te2]: RedFormat, + [yt]: RedFormat, + [ct]: RedFormat, + [pi]: RGBA_ASTC_4x4_Format, + [Sn]: RGBA_ASTC_6x6_Format, + [In]: RGBA_ASTC_6x6_Format +}; +var TYPE_MAP = { + [Ae]: FloatType, + [ge]: HalfFloatType, + [Ft]: UnsignedByteType, + [Ct]: UnsignedByteType, + [we]: FloatType, + [ae2]: HalfFloatType, + [xt2]: UnsignedByteType, + [wt]: UnsignedByteType, + [ue2]: FloatType, + [te2]: HalfFloatType, + [yt]: UnsignedByteType, + [ct]: UnsignedByteType, + [pi]: HalfFloatType, + [Sn]: UnsignedByteType, + [In]: UnsignedByteType +}; +async function createRawTexture(container) { + const { vkFormat } = container; + if (FORMAT_MAP[vkFormat] === undefined) { + throw new Error("THREE.KTX2Loader: Unsupported vkFormat."); + } + let zstd; + if (container.supercompressionScheme === n) { + if (!_zstd) { + _zstd = new Promise(async (resolve) => { + const zstd2 = new Q; + await zstd2.init(); + resolve(zstd2); + }); + } + zstd = await _zstd; + } + const mipmaps = []; + for (let levelIndex = 0;levelIndex < container.levels.length; levelIndex++) { + const levelWidth = Math.max(1, container.pixelWidth >> levelIndex); + const levelHeight = Math.max(1, container.pixelHeight >> levelIndex); + const levelDepth = container.pixelDepth ? Math.max(1, container.pixelDepth >> levelIndex) : 0; + const level = container.levels[levelIndex]; + let levelData; + if (container.supercompressionScheme === t) { + levelData = level.levelData; + } else if (container.supercompressionScheme === n) { + levelData = zstd.decode(level.levelData, level.uncompressedByteLength); + } else { + throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme."); + } + let data2; + if (TYPE_MAP[vkFormat] === FloatType) { + data2 = new Float32Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Float32Array.BYTES_PER_ELEMENT); + } else if (TYPE_MAP[vkFormat] === HalfFloatType) { + data2 = new Uint16Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT); + } else { + data2 = levelData; + } + mipmaps.push({ + data: data2, + width: levelWidth, + height: levelHeight, + depth: levelDepth + }); + } + let texture; + if (UNCOMPRESSED_FORMATS.has(FORMAT_MAP[vkFormat])) { + texture = container.pixelDepth === 0 ? new DataTexture(mipmaps[0].data, container.pixelWidth, container.pixelHeight) : new Data3DTexture(mipmaps[0].data, container.pixelWidth, container.pixelHeight, container.pixelDepth); + } else { + if (container.pixelDepth > 0) + throw new Error("THREE.KTX2Loader: Unsupported pixelDepth."); + texture = new CompressedTexture(mipmaps, container.pixelWidth, container.pixelHeight); + texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; + texture.magFilter = LinearFilter; + } + texture.mipmaps = mipmaps; + texture.type = TYPE_MAP[vkFormat]; + texture.format = FORMAT_MAP[vkFormat]; + texture.colorSpace = parseColorSpace(container); + texture.needsUpdate = true; + return Promise.resolve(texture); +} +function parseColorSpace(container) { + const dfd = container.dataFormatDescriptor[0]; + if (dfd.colorPrimaries === C2) { + return dfd.transferFunction === u ? SRGBColorSpace : LinearSRGBColorSpace; + } else if (dfd.colorPrimaries === R) { + return dfd.transferFunction === u ? DisplayP3ColorSpace : LinearDisplayP3ColorSpace; + } else if (dfd.colorPrimaries === T) { + return NoColorSpace; + } else { + console.warn(`THREE.KTX2Loader: Unsupported color primaries, "${dfd.colorPrimaries}"`); + return NoColorSpace; + } +} +// node_modules/three/examples/jsm/loaders/KTXLoader.js +var HEADER_LEN = 12 + 13 * 4; +// node_modules/three/examples/jsm/loaders/LDrawLoader.js +var _tempVec0 = new Vector3; +var _tempVec1 = new Vector3; +var _ray3 = new Ray; +// node_modules/three/examples/jsm/libs/lottie_canvas.module.js +var exports_lottie_canvas_module = {}; +__export(exports_lottie_canvas_module, { + default: () => lottie +}); +var lottie = {}; +if (typeof document !== "undefined") { + function createTag(type) { + return document.createElement(type); + } + function extendPrototype(sources, destination) { + var i; + var len = sources.length; + var sourcePrototype; + for (i = 0;i < len; i += 1) { + sourcePrototype = sources[i].prototype; + for (var attr in sourcePrototype) { + if (Object.prototype.hasOwnProperty.call(sourcePrototype, attr)) + destination.prototype[attr] = sourcePrototype[attr]; + } + } + } + function getDescriptor(object, prop) { + return Object.getOwnPropertyDescriptor(object, prop); + } + function createProxyFunction(prototype) { + function ProxyFunction() { + } + ProxyFunction.prototype = prototype; + return ProxyFunction; + } + function createSizedArray(len) { + return Array.apply(null, { length: len }); + } + function ProjectInterface$1() { + return {}; + } + function roundValues(flag) { + _shouldRoundValues = !!flag; + } + function bmRnd(value2) { + if (_shouldRoundValues) { + return Math.round(value2); + } + return value2; + } + function styleDiv(element) { + element.style.position = "absolute"; + element.style.top = 0; + element.style.left = 0; + element.style.display = "block"; + element.style.transformOrigin = "0 0"; + element.style.webkitTransformOrigin = "0 0"; + element.style.backfaceVisibility = "visible"; + element.style.webkitBackfaceVisibility = "visible"; + element.style.transformStyle = "preserve-3d"; + element.style.webkitTransformStyle = "preserve-3d"; + element.style.mozTransformStyle = "preserve-3d"; + } + function BMEnterFrameEvent(type, currentTime, totalTime, frameMultiplier) { + this.type = type; + this.currentTime = currentTime; + this.totalTime = totalTime; + this.direction = frameMultiplier < 0 ? -1 : 1; + } + function BMCompleteEvent(type, frameMultiplier) { + this.type = type; + this.direction = frameMultiplier < 0 ? -1 : 1; + } + function BMCompleteLoopEvent(type, totalLoops, currentLoop, frameMultiplier) { + this.type = type; + this.currentLoop = currentLoop; + this.totalLoops = totalLoops; + this.direction = frameMultiplier < 0 ? -1 : 1; + } + function BMSegmentStartEvent(type, firstFrame, totalFrames) { + this.type = type; + this.firstFrame = firstFrame; + this.totalFrames = totalFrames; + } + function BMDestroyEvent(type, target) { + this.type = type; + this.target = target; + } + function BMRenderFrameErrorEvent(nativeError, currentTime) { + this.type = "renderFrameError"; + this.nativeError = nativeError; + this.currentTime = currentTime; + } + function BMConfigErrorEvent(nativeError) { + this.type = "configError"; + this.nativeError = nativeError; + } + function BMAnimationConfigErrorEvent(type, nativeError) { + this.type = type; + this.nativeError = nativeError; + } + function HSVtoRGB(h, s, v) { + var r; + var g3; + var b; + var i; + var f; + var p; + var q2; + var t2; + i = Math.floor(h * 6); + f = h * 6 - i; + p = v * (1 - s); + q2 = v * (1 - f * s); + t2 = v * (1 - (1 - f) * s); + switch (i % 6) { + case 0: + r = v; + g3 = t2; + b = p; + break; + case 1: + r = q2; + g3 = v; + b = p; + break; + case 2: + r = p; + g3 = v; + b = t2; + break; + case 3: + r = p; + g3 = q2; + b = v; + break; + case 4: + r = t2; + g3 = p; + b = v; + break; + case 5: + r = v; + g3 = p; + b = q2; + break; + default: + break; + } + return [ + r, + g3, + b + ]; + } + function RGBtoHSV(r, g3, b) { + var max = Math.max(r, g3, b); + var min = Math.min(r, g3, b); + var d = max - min; + var h; + var s = max === 0 ? 0 : d / max; + var v = max / 255; + switch (max) { + case min: + h = 0; + break; + case r: + h = g3 - b + d * (g3 < b ? 6 : 0); + h /= 6 * d; + break; + case g3: + h = b - r + d * 2; + h /= 6 * d; + break; + case b: + h = r - g3 + d * 4; + h /= 6 * d; + break; + default: + break; + } + return [ + h, + s, + v + ]; + } + function addSaturationToRGB(color, offset) { + var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255); + hsv[1] += offset; + if (hsv[1] > 1) { + hsv[1] = 1; + } else if (hsv[1] <= 0) { + hsv[1] = 0; + } + return HSVtoRGB(hsv[0], hsv[1], hsv[2]); + } + function addBrightnessToRGB(color, offset) { + var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255); + hsv[2] += offset; + if (hsv[2] > 1) { + hsv[2] = 1; + } else if (hsv[2] < 0) { + hsv[2] = 0; + } + return HSVtoRGB(hsv[0], hsv[1], hsv[2]); + } + function addHueToRGB(color, offset) { + var hsv = RGBtoHSV(color[0] * 255, color[1] * 255, color[2] * 255); + hsv[0] += offset / 360; + if (hsv[0] > 1) { + hsv[0] -= 1; + } else if (hsv[0] < 0) { + hsv[0] += 1; + } + return HSVtoRGB(hsv[0], hsv[1], hsv[2]); + } + function createNS(type) { + return document.createElementNS(svgNS, type); + } + function BaseEvent() { + } + function getRenderer(key2) { + return renderers[key2]; + } + function bezFunction() { + var math = Math; + function pointOnLine2D(x1, y1, x2, y2, x3, y3) { + var det1 = x1 * y2 + y1 * x3 + x2 * y3 - x3 * y2 - y3 * x1 - x2 * y1; + return det1 > -0.001 && det1 < 0.001; + } + function pointOnLine3D(x1, y1, z1, x2, y2, z2, x3, y3, z3) { + if (z1 === 0 && z2 === 0 && z3 === 0) { + return pointOnLine2D(x1, y1, x2, y2, x3, y3); + } + var dist1 = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2) + math.pow(z2 - z1, 2)); + var dist2 = math.sqrt(math.pow(x3 - x1, 2) + math.pow(y3 - y1, 2) + math.pow(z3 - z1, 2)); + var dist3 = math.sqrt(math.pow(x3 - x2, 2) + math.pow(y3 - y2, 2) + math.pow(z3 - z2, 2)); + var diffDist; + if (dist1 > dist2) { + if (dist1 > dist3) { + diffDist = dist1 - dist2 - dist3; + } else { + diffDist = dist3 - dist2 - dist1; + } + } else if (dist3 > dist2) { + diffDist = dist3 - dist2 - dist1; + } else { + diffDist = dist2 - dist1 - dist3; + } + return diffDist > -0.0001 && diffDist < 0.0001; + } + var getBezierLength = function() { + return function(pt1, pt2, pt3, pt4) { + var curveSegments = getDefaultCurveSegments(); + var k2; + var i; + var len; + var ptCoord; + var perc; + var addedLength = 0; + var ptDistance; + var point = []; + var lastPoint = []; + var lengthData = bezierLengthPool.newElement(); + len = pt3.length; + for (k2 = 0;k2 < curveSegments; k2 += 1) { + perc = k2 / (curveSegments - 1); + ptDistance = 0; + for (i = 0;i < len; i += 1) { + ptCoord = bmPow(1 - perc, 3) * pt1[i] + 3 * bmPow(1 - perc, 2) * perc * pt3[i] + 3 * (1 - perc) * bmPow(perc, 2) * pt4[i] + bmPow(perc, 3) * pt2[i]; + point[i] = ptCoord; + if (lastPoint[i] !== null) { + ptDistance += bmPow(point[i] - lastPoint[i], 2); + } + lastPoint[i] = point[i]; + } + if (ptDistance) { + ptDistance = bmSqrt(ptDistance); + addedLength += ptDistance; + } + lengthData.percents[k2] = perc; + lengthData.lengths[k2] = addedLength; + } + lengthData.addedLength = addedLength; + return lengthData; + }; + }(); + function getSegmentsLength(shapeData) { + var segmentsLength = segmentsLengthPool.newElement(); + var closed = shapeData.c; + var pathV = shapeData.v; + var pathO = shapeData.o; + var pathI = shapeData.i; + var i; + var len = shapeData._length; + var lengths = segmentsLength.lengths; + var totalLength = 0; + for (i = 0;i < len - 1; i += 1) { + lengths[i] = getBezierLength(pathV[i], pathV[i + 1], pathO[i], pathI[i + 1]); + totalLength += lengths[i].addedLength; + } + if (closed && len) { + lengths[i] = getBezierLength(pathV[i], pathV[0], pathO[i], pathI[0]); + totalLength += lengths[i].addedLength; + } + segmentsLength.totalLength = totalLength; + return segmentsLength; + } + function BezierData(length2) { + this.segmentLength = 0; + this.points = new Array(length2); + } + function PointData(partial2, point) { + this.partialLength = partial2; + this.point = point; + } + var buildBezierData = function() { + var storedData = {}; + return function(pt1, pt2, pt3, pt4) { + var bezierName = (pt1[0] + "_" + pt1[1] + "_" + pt2[0] + "_" + pt2[1] + "_" + pt3[0] + "_" + pt3[1] + "_" + pt4[0] + "_" + pt4[1]).replace(/\./g, "p"); + if (!storedData[bezierName]) { + var curveSegments = getDefaultCurveSegments(); + var k2; + var i; + var len; + var ptCoord; + var perc; + var addedLength = 0; + var ptDistance; + var point; + var lastPoint = null; + if (pt1.length === 2 && (pt1[0] !== pt2[0] || pt1[1] !== pt2[1]) && pointOnLine2D(pt1[0], pt1[1], pt2[0], pt2[1], pt1[0] + pt3[0], pt1[1] + pt3[1]) && pointOnLine2D(pt1[0], pt1[1], pt2[0], pt2[1], pt2[0] + pt4[0], pt2[1] + pt4[1])) { + curveSegments = 2; + } + var bezierData = new BezierData(curveSegments); + len = pt3.length; + for (k2 = 0;k2 < curveSegments; k2 += 1) { + point = createSizedArray(len); + perc = k2 / (curveSegments - 1); + ptDistance = 0; + for (i = 0;i < len; i += 1) { + ptCoord = bmPow(1 - perc, 3) * pt1[i] + 3 * bmPow(1 - perc, 2) * perc * (pt1[i] + pt3[i]) + 3 * (1 - perc) * bmPow(perc, 2) * (pt2[i] + pt4[i]) + bmPow(perc, 3) * pt2[i]; + point[i] = ptCoord; + if (lastPoint !== null) { + ptDistance += bmPow(point[i] - lastPoint[i], 2); + } + } + ptDistance = bmSqrt(ptDistance); + addedLength += ptDistance; + bezierData.points[k2] = new PointData(ptDistance, point); + lastPoint = point; + } + bezierData.segmentLength = addedLength; + storedData[bezierName] = bezierData; + } + return storedData[bezierName]; + }; + }(); + function getDistancePerc(perc, bezierData) { + var percents = bezierData.percents; + var lengths = bezierData.lengths; + var len = percents.length; + var initPos = bmFloor((len - 1) * perc); + var lengthPos = perc * bezierData.addedLength; + var lPerc = 0; + if (initPos === len - 1 || initPos === 0 || lengthPos === lengths[initPos]) { + return percents[initPos]; + } + var dir = lengths[initPos] > lengthPos ? -1 : 1; + var flag = true; + while (flag) { + if (lengths[initPos] <= lengthPos && lengths[initPos + 1] > lengthPos) { + lPerc = (lengthPos - lengths[initPos]) / (lengths[initPos + 1] - lengths[initPos]); + flag = false; + } else { + initPos += dir; + } + if (initPos < 0 || initPos >= len - 1) { + if (initPos === len - 1) { + return percents[initPos]; + } + flag = false; + } + } + return percents[initPos] + (percents[initPos + 1] - percents[initPos]) * lPerc; + } + function getPointInSegment(pt1, pt2, pt3, pt4, percent, bezierData) { + var t1 = getDistancePerc(percent, bezierData); + var u1 = 1 - t1; + var ptX = math.round((u1 * u1 * u1 * pt1[0] + (t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1) * pt3[0] + (t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1) * pt4[0] + t1 * t1 * t1 * pt2[0]) * 1000) / 1000; + var ptY = math.round((u1 * u1 * u1 * pt1[1] + (t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1) * pt3[1] + (t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1) * pt4[1] + t1 * t1 * t1 * pt2[1]) * 1000) / 1000; + return [ptX, ptY]; + } + var bezierSegmentPoints = createTypedArray("float32", 8); + function getNewSegment(pt1, pt2, pt3, pt4, startPerc, endPerc, bezierData) { + if (startPerc < 0) { + startPerc = 0; + } else if (startPerc > 1) { + startPerc = 1; + } + var t0 = getDistancePerc(startPerc, bezierData); + endPerc = endPerc > 1 ? 1 : endPerc; + var t1 = getDistancePerc(endPerc, bezierData); + var i; + var len = pt1.length; + var u0 = 1 - t0; + var u1 = 1 - t1; + var u0u0u0 = u0 * u0 * u0; + var t0u0u0_3 = t0 * u0 * u0 * 3; + var t0t0u0_3 = t0 * t0 * u0 * 3; + var t0t0t0 = t0 * t0 * t0; + var u0u0u1 = u0 * u0 * u1; + var t0u0u1_3 = t0 * u0 * u1 + u0 * t0 * u1 + u0 * u0 * t1; + var t0t0u1_3 = t0 * t0 * u1 + u0 * t0 * t1 + t0 * u0 * t1; + var t0t0t1 = t0 * t0 * t1; + var u0u1u1 = u0 * u1 * u1; + var t0u1u1_3 = t0 * u1 * u1 + u0 * t1 * u1 + u0 * u1 * t1; + var t0t1u1_3 = t0 * t1 * u1 + u0 * t1 * t1 + t0 * u1 * t1; + var t0t1t1 = t0 * t1 * t1; + var u1u1u1 = u1 * u1 * u1; + var t1u1u1_3 = t1 * u1 * u1 + u1 * t1 * u1 + u1 * u1 * t1; + var t1t1u1_3 = t1 * t1 * u1 + u1 * t1 * t1 + t1 * u1 * t1; + var t1t1t1 = t1 * t1 * t1; + for (i = 0;i < len; i += 1) { + bezierSegmentPoints[i * 4] = math.round((u0u0u0 * pt1[i] + t0u0u0_3 * pt3[i] + t0t0u0_3 * pt4[i] + t0t0t0 * pt2[i]) * 1000) / 1000; + bezierSegmentPoints[i * 4 + 1] = math.round((u0u0u1 * pt1[i] + t0u0u1_3 * pt3[i] + t0t0u1_3 * pt4[i] + t0t0t1 * pt2[i]) * 1000) / 1000; + bezierSegmentPoints[i * 4 + 2] = math.round((u0u1u1 * pt1[i] + t0u1u1_3 * pt3[i] + t0t1u1_3 * pt4[i] + t0t1t1 * pt2[i]) * 1000) / 1000; + bezierSegmentPoints[i * 4 + 3] = math.round((u1u1u1 * pt1[i] + t1u1u1_3 * pt3[i] + t1t1u1_3 * pt4[i] + t1t1t1 * pt2[i]) * 1000) / 1000; + } + return bezierSegmentPoints; + } + return { + getSegmentsLength, + getNewSegment, + getPointInSegment, + buildBezierData, + pointOnLine2D, + pointOnLine3D + }; + } + function DynamicPropertyContainer() { + } + function ShapePath() { + this.c = false; + this._length = 0; + this._maxLength = 8; + this.v = createSizedArray(this._maxLength); + this.o = createSizedArray(this._maxLength); + this.i = createSizedArray(this._maxLength); + } + function ShapeCollection() { + this._length = 0; + this._maxLength = 4; + this.shapes = createSizedArray(this._maxLength); + } + function setLocation(href) { + setLocationHref(href); + } + function searchAnimations() { + if (standalone === true) { + animationManager.searchAnimations(animationData, standalone, renderer); + } else { + animationManager.searchAnimations(); + } + } + function setSubframeRendering(flag) { + setSubframeEnabled(flag); + } + function setPrefix(prefix) { + setIdPrefix(prefix); + } + function loadAnimation(params) { + if (standalone === true) { + params.animationData = JSON.parse(animationData); + } + return animationManager.loadAnimation(params); + } + function setQuality(value2) { + if (typeof value2 === "string") { + switch (value2) { + case "high": + setDefaultCurveSegments(200); + break; + default: + case "medium": + setDefaultCurveSegments(50); + break; + case "low": + setDefaultCurveSegments(10); + break; + } + } else if (!isNaN(value2) && value2 > 1) { + setDefaultCurveSegments(value2); + } + if (getDefaultCurveSegments() >= 50) { + roundValues(false); + } else { + roundValues(true); + } + } + function inBrowser() { + return typeof navigator !== "undefined"; + } + function installPlugin(type, plugin) { + if (type === "expressions") { + setExpressionsPlugin(plugin); + } + } + function getFactory(name2) { + switch (name2) { + case "propertyFactory": + return PropertyFactory; + case "shapePropertyFactory": + return ShapePropertyFactory; + case "matrix": + return Matrix; + default: + return null; + } + } + function checkReady() { + if (document.readyState === "complete") { + clearInterval(readyStateCheckInterval); + searchAnimations(); + } + } + function getQueryVariable(variable) { + var vars = queryString.split("&"); + for (var i = 0;i < vars.length; i += 1) { + var pair = vars[i].split("="); + if (decodeURIComponent(pair[0]) == variable) { + return decodeURIComponent(pair[1]); + } + } + return null; + } + function ShapeModifier() { + } + function TrimModifier() { + } + function PuckerAndBloatModifier() { + } + function RepeaterModifier() { + } + function RoundCornersModifier() { + } + function getFontProperties(fontData) { + var styles = fontData.fStyle ? fontData.fStyle.split(" ") : []; + var fWeight = "normal"; + var fStyle = "normal"; + var len = styles.length; + var styleName; + for (var i = 0;i < len; i += 1) { + styleName = styles[i].toLowerCase(); + switch (styleName) { + case "italic": + fStyle = "italic"; + break; + case "bold": + fWeight = "700"; + break; + case "black": + fWeight = "900"; + break; + case "medium": + fWeight = "500"; + break; + case "regular": + case "normal": + fWeight = "400"; + break; + case "light": + case "thin": + fWeight = "200"; + break; + default: + break; + } + } + return { + style: fStyle, + weight: fontData.fWeight || fWeight + }; + } + function RenderableElement() { + } + function SliderEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function AngleEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function ColorEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 1, 0, container); + } + function PointEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 1, 0, container); + } + function LayerIndexEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function MaskIndexEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function CheckboxEffect(data2, elem2, container) { + this.p = PropertyFactory.getProp(elem2, data2.v, 0, 0, container); + } + function NoValueEffect() { + this.p = {}; + } + function EffectsManager(data2, element) { + var effects = data2.ef || []; + this.effectElements = []; + var i; + var len = effects.length; + var effectItem; + for (i = 0;i < len; i += 1) { + effectItem = new GroupEffect(effects[i], element); + this.effectElements.push(effectItem); + } + } + function GroupEffect(data2, element) { + this.init(data2, element); + } + function BaseElement() { + } + function FrameElement() { + } + function FootageElement(data2, globalData2, comp2) { + this.initFrame(); + this.initRenderable(); + this.assetData = globalData2.getAssetData(data2.refId); + this.footageData = globalData2.imageLoader.getAsset(this.assetData); + this.initBaseData(data2, globalData2, comp2); + } + function AudioElement(data2, globalData2, comp2) { + this.initFrame(); + this.initRenderable(); + this.assetData = globalData2.getAssetData(data2.refId); + this.initBaseData(data2, globalData2, comp2); + this._isPlaying = false; + this._canPlay = false; + var assetPath = this.globalData.getAssetsPath(this.assetData); + this.audio = this.globalData.audioController.createAudio(assetPath); + this._currentTime = 0; + this.globalData.audioController.addAudio(this); + this._volumeMultiplier = 1; + this._volume = 1; + this._previousVolume = null; + this.tm = data2.tm ? PropertyFactory.getProp(this, data2.tm, 0, globalData2.frameRate, this) : { _placeholder: true }; + this.lv = PropertyFactory.getProp(this, data2.au && data2.au.lv ? data2.au.lv : { k: [100] }, 1, 0.01, this); + } + function BaseRenderer() { + } + function TransformElement() { + } + function MaskElement(data2, element, globalData2) { + this.data = data2; + this.element = element; + this.globalData = globalData2; + this.storedData = []; + this.masksProperties = this.data.masksProperties || []; + this.maskElement = null; + var defs = this.globalData.defs; + var i; + var len = this.masksProperties ? this.masksProperties.length : 0; + this.viewData = createSizedArray(len); + this.solidPath = ""; + var path; + var properties = this.masksProperties; + var count = 0; + var currentMasks = []; + var j2; + var jLen; + var layerId = createElementID(); + var rect; + var expansor; + var feMorph; + var x2; + var maskType = "clipPath"; + var maskRef = "clip-path"; + for (i = 0;i < len; i += 1) { + if (properties[i].mode !== "a" && properties[i].mode !== "n" || properties[i].inv || properties[i].o.k !== 100 || properties[i].o.x) { + maskType = "mask"; + maskRef = "mask"; + } + if ((properties[i].mode === "s" || properties[i].mode === "i") && count === 0) { + rect = createNS("rect"); + rect.setAttribute("fill", "#ffffff"); + rect.setAttribute("width", this.element.comp.data.w || 0); + rect.setAttribute("height", this.element.comp.data.h || 0); + currentMasks.push(rect); + } else { + rect = null; + } + path = createNS("path"); + if (properties[i].mode === "n") { + this.viewData[i] = { + op: PropertyFactory.getProp(this.element, properties[i].o, 0, 0.01, this.element), + prop: ShapePropertyFactory.getShapeProp(this.element, properties[i], 3), + elem: path, + lastPath: "" + }; + defs.appendChild(path); + } else { + count += 1; + path.setAttribute("fill", properties[i].mode === "s" ? "#000000" : "#ffffff"); + path.setAttribute("clip-rule", "nonzero"); + var filterID; + if (properties[i].x.k !== 0) { + maskType = "mask"; + maskRef = "mask"; + x2 = PropertyFactory.getProp(this.element, properties[i].x, 0, null, this.element); + filterID = createElementID(); + expansor = createNS("filter"); + expansor.setAttribute("id", filterID); + feMorph = createNS("feMorphology"); + feMorph.setAttribute("operator", "erode"); + feMorph.setAttribute("in", "SourceGraphic"); + feMorph.setAttribute("radius", "0"); + expansor.appendChild(feMorph); + defs.appendChild(expansor); + path.setAttribute("stroke", properties[i].mode === "s" ? "#000000" : "#ffffff"); + } else { + feMorph = null; + x2 = null; + } + this.storedData[i] = { + elem: path, + x: x2, + expan: feMorph, + lastPath: "", + lastOperator: "", + filterId: filterID, + lastRadius: 0 + }; + if (properties[i].mode === "i") { + jLen = currentMasks.length; + var g3 = createNS("g"); + for (j2 = 0;j2 < jLen; j2 += 1) { + g3.appendChild(currentMasks[j2]); + } + var mask2 = createNS("mask"); + mask2.setAttribute("mask-type", "alpha"); + mask2.setAttribute("id", layerId + "_" + count); + mask2.appendChild(path); + defs.appendChild(mask2); + g3.setAttribute("mask", "url(" + getLocationHref() + "#" + layerId + "_" + count + ")"); + currentMasks.length = 0; + currentMasks.push(g3); + } else { + currentMasks.push(path); + } + if (properties[i].inv && !this.solidPath) { + this.solidPath = this.createLayerSolidPath(); + } + this.viewData[i] = { + elem: path, + lastPath: "", + op: PropertyFactory.getProp(this.element, properties[i].o, 0, 0.01, this.element), + prop: ShapePropertyFactory.getShapeProp(this.element, properties[i], 3), + invRect: rect + }; + if (!this.viewData[i].prop.k) { + this.drawPath(properties[i], this.viewData[i].prop.v, this.viewData[i]); + } + } + } + this.maskElement = createNS(maskType); + len = currentMasks.length; + for (i = 0;i < len; i += 1) { + this.maskElement.appendChild(currentMasks[i]); + } + if (count > 0) { + this.maskElement.setAttribute("id", layerId); + this.element.maskedElement.setAttribute(maskRef, "url(" + getLocationHref() + "#" + layerId + ")"); + defs.appendChild(this.maskElement); + } + if (this.viewData.length) { + this.element.addRenderableComponent(this); + } + } + function SVGEffects(elem2) { + var i; + var source = "SourceGraphic"; + var len = elem2.data.ef ? elem2.data.ef.length : 0; + var filId = createElementID(); + var fil = filtersFactory.createFilter(filId, true); + var count = 0; + this.filters = []; + var filterManager; + for (i = 0;i < len; i += 1) { + filterManager = null; + var type = elem2.data.ef[i].ty; + if (registeredEffects[type]) { + var Effect = registeredEffects[type].effect; + filterManager = new Effect(fil, elem2.effectsManager.effectElements[i], elem2, idPrefix + count, source); + source = idPrefix + count; + if (registeredEffects[type].countsAsEffect) { + count += 1; + } + } + if (filterManager) { + this.filters.push(filterManager); + } + } + if (count) { + elem2.globalData.defs.appendChild(fil); + elem2.layerElement.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")"); + } + if (this.filters.length) { + elem2.addRenderableComponent(this); + } + } + function registerEffect(id, effect2, countsAsEffect) { + registeredEffects[id] = { + effect: effect2, + countsAsEffect + }; + } + function SVGBaseElement() { + } + function HierarchyElement() { + } + function RenderableDOMElement() { + } + function IImageElement(data2, globalData2, comp2) { + this.assetData = globalData2.getAssetData(data2.refId); + this.initElement(data2, globalData2, comp2); + this.sourceRect = { + top: 0, + left: 0, + width: this.assetData.w, + height: this.assetData.h + }; + } + function ProcessedElement(element, position2) { + this.elem = element; + this.pos = position2; + } + function IShapeElement() { + } + function SVGShapeData(transformers, level, shape) { + this.caches = []; + this.styles = []; + this.transformers = transformers; + this.lStr = ""; + this.sh = shape; + this.lvl = level; + this._isAnimated = !!shape.k; + var i = 0; + var len = transformers.length; + while (i < len) { + if (transformers[i].mProps.dynamicProperties.length) { + this._isAnimated = true; + break; + } + i += 1; + } + } + function SVGStyleData(data2, level) { + this.data = data2; + this.type = data2.ty; + this.d = ""; + this.lvl = level; + this._mdf = false; + this.closed = data2.hd === true; + this.pElem = createNS("path"); + this.msElem = null; + } + function DashProperty(elem2, data2, renderer2, container) { + this.elem = elem2; + this.frameId = -1; + this.dataProps = createSizedArray(data2.length); + this.renderer = renderer2; + this.k = false; + this.dashStr = ""; + this.dashArray = createTypedArray("float32", data2.length ? data2.length - 1 : 0); + this.dashoffset = createTypedArray("float32", 1); + this.initDynamicPropertyContainer(container); + var i; + var len = data2.length || 0; + var prop; + for (i = 0;i < len; i += 1) { + prop = PropertyFactory.getProp(elem2, data2[i].v, 0, 0, this); + this.k = prop.k || this.k; + this.dataProps[i] = { n: data2[i].n, p: prop }; + } + if (!this.k) { + this.getValue(true); + } + this._isAnimated = this.k; + } + function SVGStrokeStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, this); + this.w = PropertyFactory.getProp(elem2, data2.w, 0, null, this); + this.d = new DashProperty(elem2, data2.d || {}, "svg", this); + this.c = PropertyFactory.getProp(elem2, data2.c, 1, 255, this); + this.style = styleOb; + this._isAnimated = !!this._isAnimated; + } + function SVGFillStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, this); + this.c = PropertyFactory.getProp(elem2, data2.c, 1, 255, this); + this.style = styleOb; + } + function SVGNoStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.style = styleOb; + } + function GradientProperty(elem2, data2, container) { + this.data = data2; + this.c = createTypedArray("uint8c", data2.p * 4); + var cLength = data2.k.k[0].s ? data2.k.k[0].s.length - data2.p * 4 : data2.k.k.length - data2.p * 4; + this.o = createTypedArray("float32", cLength); + this._cmdf = false; + this._omdf = false; + this._collapsable = this.checkCollapsable(); + this._hasOpacity = cLength; + this.initDynamicPropertyContainer(container); + this.prop = PropertyFactory.getProp(elem2, data2.k, 1, null, this); + this.k = this.prop.k; + this.getValue(true); + } + function SVGGradientFillStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.initGradientData(elem2, data2, styleOb); + } + function SVGGradientStrokeStyleData(elem2, data2, styleOb) { + this.initDynamicPropertyContainer(elem2); + this.getValue = this.iterateDynamicProperties; + this.w = PropertyFactory.getProp(elem2, data2.w, 0, null, this); + this.d = new DashProperty(elem2, data2.d || {}, "svg", this); + this.initGradientData(elem2, data2, styleOb); + this._isAnimated = !!this._isAnimated; + } + function ShapeGroupData() { + this.it = []; + this.prevViewData = []; + this.gr = createNS("g"); + } + function SVGTransformData(mProps, op, container) { + this.transform = { + mProps, + op, + container + }; + this.elements = []; + this._isAnimated = this.transform.mProps.dynamicProperties.length || this.transform.op.effectsSequence.length; + } + function SVGShapeElement(data2, globalData2, comp2) { + this.shapes = []; + this.shapesData = data2.shapes; + this.stylesList = []; + this.shapeModifiers = []; + this.itemsData = []; + this.processedElements = []; + this.animatedContents = []; + this.initElement(data2, globalData2, comp2); + this.prevViewData = []; + } + function LetterProps(o, sw, sc, fc, m, p) { + this.o = o; + this.sw = sw; + this.sc = sc; + this.fc = fc; + this.m = m; + this.p = p; + this._mdf = { + o: true, + sw: !!sw, + sc: !!sc, + fc: !!fc, + m: true, + p: true + }; + } + function TextProperty(elem2, data2) { + this._frameId = initialDefaultFrame; + this.pv = ""; + this.v = ""; + this.kf = false; + this._isFirstFrame = true; + this._mdf = false; + this.data = data2; + this.elem = elem2; + this.comp = this.elem.comp; + this.keysIndex = 0; + this.canResize = false; + this.minimumFontSize = 1; + this.effectsSequence = []; + this.currentData = { + ascent: 0, + boxWidth: this.defaultBoxWidth, + f: "", + fStyle: "", + fWeight: "", + fc: "", + j: "", + justifyOffset: "", + l: [], + lh: 0, + lineWidths: [], + ls: "", + of: "", + s: "", + sc: "", + sw: 0, + t: 0, + tr: 0, + sz: 0, + ps: null, + fillColorAnim: false, + strokeColorAnim: false, + strokeWidthAnim: false, + yOffset: 0, + finalSize: 0, + finalText: [], + finalLineHeight: 0, + __complete: false + }; + this.copyData(this.currentData, this.data.d.k[0].s); + if (!this.searchProperty()) { + this.completeTextData(this.currentData); + } + } + function TextAnimatorDataProperty(elem2, animatorProps, container) { + var defaultData = { propType: false }; + var getProp = PropertyFactory.getProp; + var textAnimatorAnimatables = animatorProps.a; + this.a = { + r: textAnimatorAnimatables.r ? getProp(elem2, textAnimatorAnimatables.r, 0, degToRads, container) : defaultData, + rx: textAnimatorAnimatables.rx ? getProp(elem2, textAnimatorAnimatables.rx, 0, degToRads, container) : defaultData, + ry: textAnimatorAnimatables.ry ? getProp(elem2, textAnimatorAnimatables.ry, 0, degToRads, container) : defaultData, + sk: textAnimatorAnimatables.sk ? getProp(elem2, textAnimatorAnimatables.sk, 0, degToRads, container) : defaultData, + sa: textAnimatorAnimatables.sa ? getProp(elem2, textAnimatorAnimatables.sa, 0, degToRads, container) : defaultData, + s: textAnimatorAnimatables.s ? getProp(elem2, textAnimatorAnimatables.s, 1, 0.01, container) : defaultData, + a: textAnimatorAnimatables.a ? getProp(elem2, textAnimatorAnimatables.a, 1, 0, container) : defaultData, + o: textAnimatorAnimatables.o ? getProp(elem2, textAnimatorAnimatables.o, 0, 0.01, container) : defaultData, + p: textAnimatorAnimatables.p ? getProp(elem2, textAnimatorAnimatables.p, 1, 0, container) : defaultData, + sw: textAnimatorAnimatables.sw ? getProp(elem2, textAnimatorAnimatables.sw, 0, 0, container) : defaultData, + sc: textAnimatorAnimatables.sc ? getProp(elem2, textAnimatorAnimatables.sc, 1, 0, container) : defaultData, + fc: textAnimatorAnimatables.fc ? getProp(elem2, textAnimatorAnimatables.fc, 1, 0, container) : defaultData, + fh: textAnimatorAnimatables.fh ? getProp(elem2, textAnimatorAnimatables.fh, 0, 0, container) : defaultData, + fs: textAnimatorAnimatables.fs ? getProp(elem2, textAnimatorAnimatables.fs, 0, 0.01, container) : defaultData, + fb: textAnimatorAnimatables.fb ? getProp(elem2, textAnimatorAnimatables.fb, 0, 0.01, container) : defaultData, + t: textAnimatorAnimatables.t ? getProp(elem2, textAnimatorAnimatables.t, 0, 0, container) : defaultData + }; + this.s = TextSelectorProp.getTextSelectorProp(elem2, animatorProps.s, container); + this.s.t = animatorProps.s.t; + } + function TextAnimatorProperty(textData, renderType, elem2) { + this._isFirstFrame = true; + this._hasMaskedPath = false; + this._frameId = -1; + this._textData = textData; + this._renderType = renderType; + this._elem = elem2; + this._animatorsData = createSizedArray(this._textData.a.length); + this._pathData = {}; + this._moreOptions = { + alignment: {} + }; + this.renderedLetters = []; + this.lettersChangedFlag = false; + this.initDynamicPropertyContainer(elem2); + } + function ITextElement() { + } + function SVGTextLottieElement(data2, globalData2, comp2) { + this.textSpans = []; + this.renderType = "svg"; + this.initElement(data2, globalData2, comp2); + } + function ISolidElement(data2, globalData2, comp2) { + this.initElement(data2, globalData2, comp2); + } + function NullElement(data2, globalData2, comp2) { + this.initFrame(); + this.initBaseData(data2, globalData2, comp2); + this.initFrame(); + this.initTransform(data2, globalData2, comp2); + this.initHierarchy(); + } + function SVGRendererBase() { + } + function ICompElement() { + } + function SVGCompElement(data2, globalData2, comp2) { + this.layers = data2.layers; + this.supports3d = true; + this.completeLayers = false; + this.pendingElements = []; + this.elements = this.layers ? createSizedArray(this.layers.length) : []; + this.initElement(data2, globalData2, comp2); + this.tm = data2.tm ? PropertyFactory.getProp(this, data2.tm, 0, globalData2.frameRate, this) : { _placeholder: true }; + } + function SVGRenderer(animationItem, config) { + this.animationItem = animationItem; + this.layers = null; + this.renderedFrame = -1; + this.svgElement = createNS("svg"); + var ariaLabel = ""; + if (config && config.title) { + var titleElement = createNS("title"); + var titleId = createElementID(); + titleElement.setAttribute("id", titleId); + titleElement.textContent = config.title; + this.svgElement.appendChild(titleElement); + ariaLabel += titleId; + } + if (config && config.description) { + var descElement = createNS("desc"); + var descId = createElementID(); + descElement.setAttribute("id", descId); + descElement.textContent = config.description; + this.svgElement.appendChild(descElement); + ariaLabel += " " + descId; + } + if (ariaLabel) { + this.svgElement.setAttribute("aria-labelledby", ariaLabel); + } + var defs = createNS("defs"); + this.svgElement.appendChild(defs); + var maskElement = createNS("g"); + this.svgElement.appendChild(maskElement); + this.layerElement = maskElement; + this.renderConfig = { + preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet", + imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice", + contentVisibility: config && config.contentVisibility || "visible", + progressiveLoad: config && config.progressiveLoad || false, + hideOnTransparent: !(config && config.hideOnTransparent === false), + viewBoxOnly: config && config.viewBoxOnly || false, + viewBoxSize: config && config.viewBoxSize || false, + className: config && config.className || "", + id: config && config.id || "", + focusable: config && config.focusable, + filterSize: { + width: config && config.filterSize && config.filterSize.width || "100%", + height: config && config.filterSize && config.filterSize.height || "100%", + x: config && config.filterSize && config.filterSize.x || "0%", + y: config && config.filterSize && config.filterSize.y || "0%" + }, + width: config && config.width, + height: config && config.height + }; + this.globalData = { + _mdf: false, + frameNum: -1, + defs, + renderConfig: this.renderConfig + }; + this.elements = []; + this.pendingElements = []; + this.destroyed = false; + this.rendererType = "svg"; + } + function CVContextData() { + this.saved = []; + this.cArrPos = 0; + this.cTr = new Matrix; + this.cO = 1; + var i; + var len = 15; + this.savedOp = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + this.saved[i] = createTypedArray("float32", 16); + } + this._length = len; + } + function ShapeTransformManager() { + this.sequences = {}; + this.sequenceList = []; + this.transform_key_count = 0; + } + function CVEffects() { + } + function CVMaskElement(data2, element) { + this.data = data2; + this.element = element; + this.masksProperties = this.data.masksProperties || []; + this.viewData = createSizedArray(this.masksProperties.length); + var i; + var len = this.masksProperties.length; + var hasMasks = false; + for (i = 0;i < len; i += 1) { + if (this.masksProperties[i].mode !== "n") { + hasMasks = true; + } + this.viewData[i] = ShapePropertyFactory.getShapeProp(this.element, this.masksProperties[i], 3); + } + this.hasMasks = hasMasks; + if (hasMasks) { + this.element.addRenderableComponent(this); + } + } + function CVBaseElement() { + } + function CVShapeData(element, data2, styles, transformsManager) { + this.styledShapes = []; + this.tr = [0, 0, 0, 0, 0, 0]; + var ty = 4; + if (data2.ty === "rc") { + ty = 5; + } else if (data2.ty === "el") { + ty = 6; + } else if (data2.ty === "sr") { + ty = 7; + } + this.sh = ShapePropertyFactory.getShapeProp(element, data2, ty, element); + var i; + var len = styles.length; + var styledShape; + for (i = 0;i < len; i += 1) { + if (!styles[i].closed) { + styledShape = { + transforms: transformsManager.addTransformSequence(styles[i].transforms), + trNodes: [] + }; + this.styledShapes.push(styledShape); + styles[i].elements.push(styledShape); + } + } + } + function CVShapeElement(data2, globalData2, comp2) { + this.shapes = []; + this.shapesData = data2.shapes; + this.stylesList = []; + this.itemsData = []; + this.prevViewData = []; + this.shapeModifiers = []; + this.processedElements = []; + this.transformsManager = new ShapeTransformManager; + this.initElement(data2, globalData2, comp2); + } + function CVTextElement(data2, globalData2, comp2) { + this.textSpans = []; + this.yOffset = 0; + this.fillColorAnim = false; + this.strokeColorAnim = false; + this.strokeWidthAnim = false; + this.stroke = false; + this.fill = false; + this.justifyOffset = 0; + this.currentRender = null; + this.renderType = "canvas"; + this.values = { + fill: "rgba(0,0,0,0)", + stroke: "rgba(0,0,0,0)", + sWidth: 0, + fValue: "" + }; + this.initElement(data2, globalData2, comp2); + } + function CVImageElement(data2, globalData2, comp2) { + this.assetData = globalData2.getAssetData(data2.refId); + this.img = globalData2.imageLoader.getAsset(this.assetData); + this.initElement(data2, globalData2, comp2); + } + function CVSolidElement(data2, globalData2, comp2) { + this.initElement(data2, globalData2, comp2); + } + function CanvasRendererBase(animationItem, config) { + this.animationItem = animationItem; + this.renderConfig = { + clearCanvas: config && config.clearCanvas !== undefined ? config.clearCanvas : true, + context: config && config.context || null, + progressiveLoad: config && config.progressiveLoad || false, + preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet", + imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice", + contentVisibility: config && config.contentVisibility || "visible", + className: config && config.className || "", + id: config && config.id || "" + }; + this.renderConfig.dpr = config && config.dpr || 1; + if (this.animationItem.wrapper) { + this.renderConfig.dpr = config && config.dpr || window.devicePixelRatio || 1; + } + this.renderedFrame = -1; + this.globalData = { + frameNum: -1, + _mdf: false, + renderConfig: this.renderConfig, + currentGlobalAlpha: -1 + }; + this.contextData = new CVContextData; + this.elements = []; + this.pendingElements = []; + this.transformMat = new Matrix; + this.completeLayers = false; + this.rendererType = "canvas"; + } + function CVCompElement(data2, globalData2, comp2) { + this.completeLayers = false; + this.layers = data2.layers; + this.pendingElements = []; + this.elements = createSizedArray(this.layers.length); + this.initElement(data2, globalData2, comp2); + this.tm = data2.tm ? PropertyFactory.getProp(this, data2.tm, 0, globalData2.frameRate, this) : { _placeholder: true }; + } + function CanvasRenderer(animationItem, config) { + this.animationItem = animationItem; + this.renderConfig = { + clearCanvas: config && config.clearCanvas !== undefined ? config.clearCanvas : true, + context: config && config.context || null, + progressiveLoad: config && config.progressiveLoad || false, + preserveAspectRatio: config && config.preserveAspectRatio || "xMidYMid meet", + imagePreserveAspectRatio: config && config.imagePreserveAspectRatio || "xMidYMid slice", + contentVisibility: config && config.contentVisibility || "visible", + className: config && config.className || "", + id: config && config.id || "" + }; + this.renderConfig.dpr = config && config.dpr || 1; + if (this.animationItem.wrapper) { + this.renderConfig.dpr = config && config.dpr || window.devicePixelRatio || 1; + } + this.renderedFrame = -1; + this.globalData = { + frameNum: -1, + _mdf: false, + renderConfig: this.renderConfig, + currentGlobalAlpha: -1 + }; + this.contextData = new CVContextData; + this.elements = []; + this.pendingElements = []; + this.transformMat = new Matrix; + this.completeLayers = false; + this.rendererType = "canvas"; + } + function seedRandom(pool, math) { + var global2 = this, width2 = 256, chunks = 6, digits = 52, rngname = "random", startdenom = math.pow(width2, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask2 = width2 - 1, nodecrypto; + function seedrandom(seed, options, callback) { + var key2 = []; + options = options === true ? { entropy: true } : options || {}; + var shortseed = mixkey(flatten3(options.entropy ? [seed, tostring(pool)] : seed === null ? autoseed() : seed, 3), key2); + var arc4 = new ARC4(key2); + var prng = function() { + var n2 = arc4.g(chunks), d = startdenom, x2 = 0; + while (n2 < significance) { + n2 = (n2 + x2) * width2; + d *= width2; + x2 = arc4.g(1); + } + while (n2 >= overflow) { + n2 /= 2; + d /= 2; + x2 >>>= 1; + } + return (n2 + x2) / d; + }; + prng.int32 = function() { + return arc4.g(4) | 0; + }; + prng.quick = function() { + return arc4.g(4) / 4294967296; + }; + prng.double = prng; + mixkey(tostring(arc4.S), pool); + return (options.pass || callback || function(prng2, seed2, is_math_call, state) { + if (state) { + if (state.S) { + copy(state, arc4); + } + prng2.state = function() { + return copy(arc4, {}); + }; + } + if (is_math_call) { + math[rngname] = prng2; + return seed2; + } else + return prng2; + })(prng, shortseed, "global" in options ? options.global : this == math, options.state); + } + math["seed" + rngname] = seedrandom; + function ARC4(key2) { + var t2, keylen = key2.length, me = this, i = 0, j2 = me.i = me.j = 0, s = me.S = []; + if (!keylen) { + key2 = [keylen++]; + } + while (i < width2) { + s[i] = i++; + } + for (i = 0;i < width2; i++) { + s[i] = s[j2 = mask2 & j2 + key2[i % keylen] + (t2 = s[i])]; + s[j2] = t2; + } + me.g = function(count) { + var t3, r = 0, i2 = me.i, j3 = me.j, s2 = me.S; + while (count--) { + t3 = s2[i2 = mask2 & i2 + 1]; + r = r * width2 + s2[mask2 & (s2[i2] = s2[j3 = mask2 & j3 + t3]) + (s2[j3] = t3)]; + } + me.i = i2; + me.j = j3; + return r; + }; + } + function copy(f, t2) { + t2.i = f.i; + t2.j = f.j; + t2.S = f.S.slice(); + return t2; + } + function flatten3(obj, depth) { + var result = [], typ = typeof obj, prop; + if (depth && typ == "object") { + for (prop in obj) { + try { + result.push(flatten3(obj[prop], depth - 1)); + } catch (e) { + } + } + } + return result.length ? result : typ == "string" ? obj : obj + "\x00"; + } + function mixkey(seed, key2) { + var stringseed = seed + "", smear, j2 = 0; + while (j2 < stringseed.length) { + key2[mask2 & j2] = mask2 & (smear ^= key2[mask2 & j2] * 19) + stringseed.charCodeAt(j2++); + } + return tostring(key2); + } + function autoseed() { + try { + if (nodecrypto) { + return tostring(nodecrypto.randomBytes(width2)); + } + var out = new Uint8Array(width2); + (global2.crypto || global2.msCrypto).getRandomValues(out); + return tostring(out); + } catch (e) { + var browser = global2.navigator, plugins = browser && browser.plugins; + return [+new Date, global2, plugins, global2.screen, tostring(pool)]; + } + } + function tostring(a) { + return String.fromCharCode.apply(0, a); + } + mixkey(math.random(), pool); + } + function initialize$2(BMMath2) { + seedRandom([], BMMath2); + } + function addPropertyDecorator() { + function loopOut2(type, duration, durationFlag) { + if (!this.k || !this.keyframes) { + return this.pv; + } + type = type ? type.toLowerCase() : ""; + var currentFrame = this.comp.renderedFrame; + var keyframes = this.keyframes; + var lastKeyFrame = keyframes[keyframes.length - 1].t; + if (currentFrame <= lastKeyFrame) { + return this.pv; + } + var cycleDuration; + var firstKeyFrame; + if (!durationFlag) { + if (!duration || duration > keyframes.length - 1) { + duration = keyframes.length - 1; + } + firstKeyFrame = keyframes[keyframes.length - 1 - duration].t; + cycleDuration = lastKeyFrame - firstKeyFrame; + } else { + if (!duration) { + cycleDuration = Math.max(0, lastKeyFrame - this.elem.data.ip); + } else { + cycleDuration = Math.abs(lastKeyFrame - this.elem.comp.globalData.frameRate * duration); + } + firstKeyFrame = lastKeyFrame - cycleDuration; + } + var i; + var len; + var ret; + if (type === "pingpong") { + var iterations = Math.floor((currentFrame - firstKeyFrame) / cycleDuration); + if (iterations % 2 !== 0) { + return this.getValueAtTime((cycleDuration - (currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + } + } else if (type === "offset") { + var initV = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0); + var endV = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0); + var current = this.getValueAtTime(((currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + var repeats = Math.floor((currentFrame - firstKeyFrame) / cycleDuration); + if (this.pv.length) { + ret = new Array(initV.length); + len = ret.length; + for (i = 0;i < len; i += 1) { + ret[i] = (endV[i] - initV[i]) * repeats + current[i]; + } + return ret; + } + return (endV - initV) * repeats + current; + } else if (type === "continue") { + var lastValue = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0); + var nextLastValue = this.getValueAtTime((lastKeyFrame - 0.001) / this.comp.globalData.frameRate, 0); + if (this.pv.length) { + ret = new Array(lastValue.length); + len = ret.length; + for (i = 0;i < len; i += 1) { + ret[i] = lastValue[i] + (lastValue[i] - nextLastValue[i]) * ((currentFrame - lastKeyFrame) / this.comp.globalData.frameRate) / 0.0005; + } + return ret; + } + return lastValue + (lastValue - nextLastValue) * ((currentFrame - lastKeyFrame) / 0.001); + } + return this.getValueAtTime(((currentFrame - firstKeyFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + } + function loopIn2(type, duration, durationFlag) { + if (!this.k) { + return this.pv; + } + type = type ? type.toLowerCase() : ""; + var currentFrame = this.comp.renderedFrame; + var keyframes = this.keyframes; + var firstKeyFrame = keyframes[0].t; + if (currentFrame >= firstKeyFrame) { + return this.pv; + } + var cycleDuration; + var lastKeyFrame; + if (!durationFlag) { + if (!duration || duration > keyframes.length - 1) { + duration = keyframes.length - 1; + } + lastKeyFrame = keyframes[duration].t; + cycleDuration = lastKeyFrame - firstKeyFrame; + } else { + if (!duration) { + cycleDuration = Math.max(0, this.elem.data.op - firstKeyFrame); + } else { + cycleDuration = Math.abs(this.elem.comp.globalData.frameRate * duration); + } + lastKeyFrame = firstKeyFrame + cycleDuration; + } + var i; + var len; + var ret; + if (type === "pingpong") { + var iterations = Math.floor((firstKeyFrame - currentFrame) / cycleDuration); + if (iterations % 2 === 0) { + return this.getValueAtTime(((firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + } + } else if (type === "offset") { + var initV = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0); + var endV = this.getValueAtTime(lastKeyFrame / this.comp.globalData.frameRate, 0); + var current = this.getValueAtTime((cycleDuration - (firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame) / this.comp.globalData.frameRate, 0); + var repeats = Math.floor((firstKeyFrame - currentFrame) / cycleDuration) + 1; + if (this.pv.length) { + ret = new Array(initV.length); + len = ret.length; + for (i = 0;i < len; i += 1) { + ret[i] = current[i] - (endV[i] - initV[i]) * repeats; + } + return ret; + } + return current - (endV - initV) * repeats; + } else if (type === "continue") { + var firstValue = this.getValueAtTime(firstKeyFrame / this.comp.globalData.frameRate, 0); + var nextFirstValue = this.getValueAtTime((firstKeyFrame + 0.001) / this.comp.globalData.frameRate, 0); + if (this.pv.length) { + ret = new Array(firstValue.length); + len = ret.length; + for (i = 0;i < len; i += 1) { + ret[i] = firstValue[i] + (firstValue[i] - nextFirstValue[i]) * (firstKeyFrame - currentFrame) / 0.001; + } + return ret; + } + return firstValue + (firstValue - nextFirstValue) * (firstKeyFrame - currentFrame) / 0.001; + } + return this.getValueAtTime((cycleDuration - ((firstKeyFrame - currentFrame) % cycleDuration + firstKeyFrame)) / this.comp.globalData.frameRate, 0); + } + function smooth2(width2, samples) { + if (!this.k) { + return this.pv; + } + width2 = (width2 || 0.4) * 0.5; + samples = Math.floor(samples || 5); + if (samples <= 1) { + return this.pv; + } + var currentTime = this.comp.renderedFrame / this.comp.globalData.frameRate; + var initFrame = currentTime - width2; + var endFrame = currentTime + width2; + var sampleFrequency = samples > 1 ? (endFrame - initFrame) / (samples - 1) : 1; + var i = 0; + var j2 = 0; + var value2; + if (this.pv.length) { + value2 = createTypedArray("float32", this.pv.length); + } else { + value2 = 0; + } + var sampleValue; + while (i < samples) { + sampleValue = this.getValueAtTime(initFrame + i * sampleFrequency); + if (this.pv.length) { + for (j2 = 0;j2 < this.pv.length; j2 += 1) { + value2[j2] += sampleValue[j2]; + } + } else { + value2 += sampleValue; + } + i += 1; + } + if (this.pv.length) { + for (j2 = 0;j2 < this.pv.length; j2 += 1) { + value2[j2] /= samples; + } + } else { + value2 /= samples; + } + return value2; + } + function getTransformValueAtTime(time2) { + if (!this._transformCachingAtTime) { + this._transformCachingAtTime = { + v: new Matrix + }; + } + var matrix = this._transformCachingAtTime.v; + matrix.cloneFromProps(this.pre.props); + if (this.appliedTransformations < 1) { + var anchor = this.a.getValueAtTime(time2); + matrix.translate(-anchor[0] * this.a.mult, -anchor[1] * this.a.mult, anchor[2] * this.a.mult); + } + if (this.appliedTransformations < 2) { + var scale2 = this.s.getValueAtTime(time2); + matrix.scale(scale2[0] * this.s.mult, scale2[1] * this.s.mult, scale2[2] * this.s.mult); + } + if (this.sk && this.appliedTransformations < 3) { + var skew = this.sk.getValueAtTime(time2); + var skewAxis = this.sa.getValueAtTime(time2); + matrix.skewFromAxis(-skew * this.sk.mult, skewAxis * this.sa.mult); + } + if (this.r && this.appliedTransformations < 4) { + var rotation2 = this.r.getValueAtTime(time2); + matrix.rotate(-rotation2 * this.r.mult); + } else if (!this.r && this.appliedTransformations < 4) { + var rotationZ = this.rz.getValueAtTime(time2); + var rotationY = this.ry.getValueAtTime(time2); + var rotationX = this.rx.getValueAtTime(time2); + var orientation = this.or.getValueAtTime(time2); + matrix.rotateZ(-rotationZ * this.rz.mult).rotateY(rotationY * this.ry.mult).rotateX(rotationX * this.rx.mult).rotateZ(-orientation[2] * this.or.mult).rotateY(orientation[1] * this.or.mult).rotateX(orientation[0] * this.or.mult); + } + if (this.data.p && this.data.p.s) { + var positionX = this.px.getValueAtTime(time2); + var positionY = this.py.getValueAtTime(time2); + if (this.data.p.z) { + var positionZ = this.pz.getValueAtTime(time2); + matrix.translate(positionX * this.px.mult, positionY * this.py.mult, -positionZ * this.pz.mult); + } else { + matrix.translate(positionX * this.px.mult, positionY * this.py.mult, 0); + } + } else { + var position2 = this.p.getValueAtTime(time2); + matrix.translate(position2[0] * this.p.mult, position2[1] * this.p.mult, -position2[2] * this.p.mult); + } + return matrix; + } + function getTransformStaticValueAtTime() { + return this.v.clone(new Matrix); + } + var getTransformProperty = TransformPropertyFactory.getTransformProperty; + TransformPropertyFactory.getTransformProperty = function(elem2, data2, container) { + var prop = getTransformProperty(elem2, data2, container); + if (prop.dynamicProperties.length) { + prop.getValueAtTime = getTransformValueAtTime.bind(prop); + } else { + prop.getValueAtTime = getTransformStaticValueAtTime.bind(prop); + } + prop.setGroupProperty = expressionHelpers.setGroupProperty; + return prop; + }; + var propertyGetProp = PropertyFactory.getProp; + PropertyFactory.getProp = function(elem2, data2, type, mult, container) { + var prop = propertyGetProp(elem2, data2, type, mult, container); + if (prop.kf) { + prop.getValueAtTime = expressionHelpers.getValueAtTime.bind(prop); + } else { + prop.getValueAtTime = expressionHelpers.getStaticValueAtTime.bind(prop); + } + prop.setGroupProperty = expressionHelpers.setGroupProperty; + prop.loopOut = loopOut2; + prop.loopIn = loopIn2; + prop.smooth = smooth2; + prop.getVelocityAtTime = expressionHelpers.getVelocityAtTime.bind(prop); + prop.getSpeedAtTime = expressionHelpers.getSpeedAtTime.bind(prop); + prop.numKeys = data2.a === 1 ? data2.k.length : 0; + prop.propertyIndex = data2.ix; + var value2 = 0; + if (type !== 0) { + value2 = createTypedArray("float32", data2.a === 1 ? data2.k[0].s.length : data2.k.length); + } + prop._cachingAtTime = { + lastFrame: initialDefaultFrame, + lastIndex: 0, + value: value2 + }; + expressionHelpers.searchExpressions(elem2, data2, prop); + if (prop.k) { + container.addDynamicProperty(prop); + } + return prop; + }; + function getShapeValueAtTime(frameNum) { + if (!this._cachingAtTime) { + this._cachingAtTime = { + shapeValue: shapePool.clone(this.pv), + lastIndex: 0, + lastTime: initialDefaultFrame + }; + } + frameNum *= this.elem.globalData.frameRate; + frameNum -= this.offsetTime; + if (frameNum !== this._cachingAtTime.lastTime) { + this._cachingAtTime.lastIndex = this._cachingAtTime.lastTime < frameNum ? this._caching.lastIndex : 0; + this._cachingAtTime.lastTime = frameNum; + this.interpolateShape(frameNum, this._cachingAtTime.shapeValue, this._cachingAtTime); + } + return this._cachingAtTime.shapeValue; + } + var ShapePropertyConstructorFunction = ShapePropertyFactory.getConstructorFunction(); + var KeyframedShapePropertyConstructorFunction = ShapePropertyFactory.getKeyframedConstructorFunction(); + function ShapeExpressions() { + } + ShapeExpressions.prototype = { + vertices: function(prop, time2) { + if (this.k) { + this.getValue(); + } + var shapePath = this.v; + if (time2 !== undefined) { + shapePath = this.getValueAtTime(time2, 0); + } + var i; + var len = shapePath._length; + var vertices = shapePath[prop]; + var points = shapePath.v; + var arr = createSizedArray(len); + for (i = 0;i < len; i += 1) { + if (prop === "i" || prop === "o") { + arr[i] = [vertices[i][0] - points[i][0], vertices[i][1] - points[i][1]]; + } else { + arr[i] = [vertices[i][0], vertices[i][1]]; + } + } + return arr; + }, + points: function(time2) { + return this.vertices("v", time2); + }, + inTangents: function(time2) { + return this.vertices("i", time2); + }, + outTangents: function(time2) { + return this.vertices("o", time2); + }, + isClosed: function() { + return this.v.c; + }, + pointOnPath: function(perc, time2) { + var shapePath = this.v; + if (time2 !== undefined) { + shapePath = this.getValueAtTime(time2, 0); + } + if (!this._segmentsLength) { + this._segmentsLength = bez.getSegmentsLength(shapePath); + } + var segmentsLength = this._segmentsLength; + var lengths = segmentsLength.lengths; + var lengthPos = segmentsLength.totalLength * perc; + var i = 0; + var len = lengths.length; + var accumulatedLength = 0; + var pt; + while (i < len) { + if (accumulatedLength + lengths[i].addedLength > lengthPos) { + var initIndex = i; + var endIndex = shapePath.c && i === len - 1 ? 0 : i + 1; + var segmentPerc = (lengthPos - accumulatedLength) / lengths[i].addedLength; + pt = bez.getPointInSegment(shapePath.v[initIndex], shapePath.v[endIndex], shapePath.o[initIndex], shapePath.i[endIndex], segmentPerc, lengths[i]); + break; + } else { + accumulatedLength += lengths[i].addedLength; + } + i += 1; + } + if (!pt) { + pt = shapePath.c ? [shapePath.v[0][0], shapePath.v[0][1]] : [shapePath.v[shapePath._length - 1][0], shapePath.v[shapePath._length - 1][1]]; + } + return pt; + }, + vectorOnPath: function(perc, time2, vectorType) { + if (perc == 1) { + perc = this.v.c; + } else if (perc == 0) { + perc = 0.999; + } + var pt1 = this.pointOnPath(perc, time2); + var pt2 = this.pointOnPath(perc + 0.001, time2); + var xLength = pt2[0] - pt1[0]; + var yLength = pt2[1] - pt1[1]; + var magnitude = Math.sqrt(Math.pow(xLength, 2) + Math.pow(yLength, 2)); + if (magnitude === 0) { + return [0, 0]; + } + var unitVector = vectorType === "tangent" ? [xLength / magnitude, yLength / magnitude] : [-yLength / magnitude, xLength / magnitude]; + return unitVector; + }, + tangentOnPath: function(perc, time2) { + return this.vectorOnPath(perc, time2, "tangent"); + }, + normalOnPath: function(perc, time2) { + return this.vectorOnPath(perc, time2, "normal"); + }, + setGroupProperty: expressionHelpers.setGroupProperty, + getValueAtTime: expressionHelpers.getStaticValueAtTime + }; + extendPrototype([ShapeExpressions], ShapePropertyConstructorFunction); + extendPrototype([ShapeExpressions], KeyframedShapePropertyConstructorFunction); + KeyframedShapePropertyConstructorFunction.prototype.getValueAtTime = getShapeValueAtTime; + KeyframedShapePropertyConstructorFunction.prototype.initiateExpression = ExpressionManager.initiateExpression; + var propertyGetShapeProp = ShapePropertyFactory.getShapeProp; + ShapePropertyFactory.getShapeProp = function(elem2, data2, type, arr, trims) { + var prop = propertyGetShapeProp(elem2, data2, type, arr, trims); + prop.propertyIndex = data2.ix; + prop.lock = false; + if (type === 3) { + expressionHelpers.searchExpressions(elem2, data2.pt, prop); + } else if (type === 4) { + expressionHelpers.searchExpressions(elem2, data2.ks, prop); + } + if (prop.k) { + elem2.addDynamicProperty(prop); + } + return prop; + }; + } + function initialize$1() { + addPropertyDecorator(); + } + function addDecorator() { + function searchExpressions() { + if (this.data.d.x) { + this.calculateExpression = ExpressionManager.initiateExpression.bind(this)(this.elem, this.data.d, this); + this.addEffect(this.getExpressionValue.bind(this)); + return true; + } + return null; + } + TextProperty.prototype.getExpressionValue = function(currentValue, text2) { + var newValue = this.calculateExpression(text2); + if (currentValue.t !== newValue) { + var newData = {}; + this.copyData(newData, currentValue); + newData.t = newValue.toString(); + newData.__complete = false; + return newData; + } + return currentValue; + }; + TextProperty.prototype.searchProperty = function() { + var isKeyframed = this.searchKeyframes(); + var hasExpressions = this.searchExpressions(); + this.kf = isKeyframed || hasExpressions; + return this.kf; + }; + TextProperty.prototype.searchExpressions = searchExpressions; + } + function initialize() { + addDecorator(); + } + const svgNS = "http://www.w3.org/2000/svg"; + let locationHref = ""; + let _useWebWorker = false; + const initialDefaultFrame = -999999; + const setWebWorker = (flag) => { + _useWebWorker = !!flag; + }; + const getWebWorker = () => _useWebWorker; + const setLocationHref = (value2) => { + locationHref = value2; + }; + const getLocationHref = () => locationHref; + const audioControllerFactory = function() { + function AudioController(audioFactory) { + this.audios = []; + this.audioFactory = audioFactory; + this._volume = 1; + this._isMuted = false; + } + AudioController.prototype = { + addAudio: function(audio) { + this.audios.push(audio); + }, + pause: function() { + var i; + var len = this.audios.length; + for (i = 0;i < len; i += 1) { + this.audios[i].pause(); + } + }, + resume: function() { + var i; + var len = this.audios.length; + for (i = 0;i < len; i += 1) { + this.audios[i].resume(); + } + }, + setRate: function(rateValue) { + var i; + var len = this.audios.length; + for (i = 0;i < len; i += 1) { + this.audios[i].setRate(rateValue); + } + }, + createAudio: function(assetPath) { + if (this.audioFactory) { + return this.audioFactory(assetPath); + } + if (window.Howl) { + return new window.Howl({ + src: [assetPath] + }); + } + return { + isPlaying: false, + play: function() { + this.isPlaying = true; + }, + seek: function() { + this.isPlaying = false; + }, + playing: function() { + }, + rate: function() { + }, + setVolume: function() { + } + }; + }, + setAudioFactory: function(audioFactory) { + this.audioFactory = audioFactory; + }, + setVolume: function(value2) { + this._volume = value2; + this._updateVolume(); + }, + mute: function() { + this._isMuted = true; + this._updateVolume(); + }, + unmute: function() { + this._isMuted = false; + this._updateVolume(); + }, + getVolume: function() { + return this._volume; + }, + _updateVolume: function() { + var i; + var len = this.audios.length; + for (i = 0;i < len; i += 1) { + this.audios[i].volume(this._volume * (this._isMuted ? 0 : 1)); + } + } + }; + return function() { + return new AudioController; + }; + }(); + const createTypedArray = function() { + function createRegularArray(type, len) { + var i = 0; + var arr = []; + var value2; + switch (type) { + case "int16": + case "uint8c": + value2 = 1; + break; + default: + value2 = 1.1; + break; + } + for (i = 0;i < len; i += 1) { + arr.push(value2); + } + return arr; + } + function createTypedArrayFactory(type, len) { + if (type === "float32") { + return new Float32Array(len); + } + if (type === "int16") { + return new Int16Array(len); + } + if (type === "uint8c") { + return new Uint8ClampedArray(len); + } + return createRegularArray(type, len); + } + if (typeof Uint8ClampedArray === "function" && typeof Float32Array === "function") { + return createTypedArrayFactory; + } + return createRegularArray; + }(); + let subframeEnabled = true; + let expressionsPlugin = null; + let idPrefix$1 = ""; + const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); + let _shouldRoundValues = false; + const bmPow = Math.pow; + const bmSqrt = Math.sqrt; + const bmFloor = Math.floor; + const bmMax = Math.max; + const bmMin = Math.min; + const BMMath = {}; + (function() { + var propertyNames = ["abs", "acos", "acosh", "asin", "asinh", "atan", "atanh", "atan2", "ceil", "cbrt", "expm1", "clz32", "cos", "cosh", "exp", "floor", "fround", "hypot", "imul", "log", "log1p", "log2", "log10", "max", "min", "pow", "random", "round", "sign", "sin", "sinh", "sqrt", "tan", "tanh", "trunc", "E", "LN10", "LN2", "LOG10E", "LOG2E", "PI", "SQRT1_2", "SQRT2"]; + var i; + var len = propertyNames.length; + for (i = 0;i < len; i += 1) { + BMMath[propertyNames[i]] = Math[propertyNames[i]]; + } + })(); + BMMath.random = Math.random; + BMMath.abs = function(val2) { + var tOfVal = typeof val2; + if (tOfVal === "object" && val2.length) { + var absArr = createSizedArray(val2.length); + var i; + var len = val2.length; + for (i = 0;i < len; i += 1) { + absArr[i] = Math.abs(val2[i]); + } + return absArr; + } + return Math.abs(val2); + }; + let defaultCurveSegments = 150; + const degToRads = Math.PI / 180; + const roundCorner = 0.5519; + const createElementID = function() { + var _count = 0; + return function createID() { + _count += 1; + return idPrefix$1 + "__lottie_element_" + _count; + }; + }(); + const rgbToHex = function() { + var colorMap = []; + var i; + var hex; + for (i = 0;i < 256; i += 1) { + hex = i.toString(16); + colorMap[i] = hex.length === 1 ? "0" + hex : hex; + } + return function(r, g3, b) { + if (r < 0) { + r = 0; + } + if (g3 < 0) { + g3 = 0; + } + if (b < 0) { + b = 0; + } + return "#" + colorMap[r] + colorMap[g3] + colorMap[b]; + }; + }(); + const setSubframeEnabled = (flag) => { + subframeEnabled = !!flag; + }; + const getSubframeEnabled = () => subframeEnabled; + const setExpressionsPlugin = (value2) => { + expressionsPlugin = value2; + }; + const getExpressionsPlugin = () => expressionsPlugin; + const setDefaultCurveSegments = (value2) => { + defaultCurveSegments = value2; + }; + const getDefaultCurveSegments = () => defaultCurveSegments; + const setIdPrefix = (value2) => { + idPrefix$1 = value2; + }; + const getIdPrefix = () => idPrefix$1; + const dataManager = function() { + var _counterId = 1; + var processes = []; + var workerFn; + var workerInstance; + var workerProxy = { + onmessage: function() { + }, + postMessage: function(path) { + workerFn({ + data: path + }); + } + }; + var _workerSelf = { + postMessage: function(data2) { + workerProxy.onmessage({ + data: data2 + }); + } + }; + function createWorker(fn) { + if (window.Worker && window.Blob && getWebWorker()) { + var blob = new Blob(["var _workerSelf = self; self.onmessage = ", fn.toString()], { type: "text/javascript" }); + var url = URL.createObjectURL(blob); + return new Worker(url); + } + workerFn = fn; + return workerProxy; + } + function setupWorker() { + if (!workerInstance) { + workerInstance = createWorker(function workerStart(e) { + function dataFunctionManager() { + function completeLayers(layers, comps) { + var layerData; + var i; + var len = layers.length; + var j2; + var jLen; + var k2; + var kLen; + for (i = 0;i < len; i += 1) { + layerData = layers[i]; + if ("ks" in layerData && !layerData.completed) { + layerData.completed = true; + if (layerData.tt) { + layers[i - 1].td = layerData.tt; + } + if (layerData.hasMask) { + var maskProps = layerData.masksProperties; + jLen = maskProps.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (maskProps[j2].pt.k.i) { + convertPathsToAbsoluteValues(maskProps[j2].pt.k); + } else { + kLen = maskProps[j2].pt.k.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + if (maskProps[j2].pt.k[k2].s) { + convertPathsToAbsoluteValues(maskProps[j2].pt.k[k2].s[0]); + } + if (maskProps[j2].pt.k[k2].e) { + convertPathsToAbsoluteValues(maskProps[j2].pt.k[k2].e[0]); + } + } + } + } + } + if (layerData.ty === 0) { + layerData.layers = findCompLayers(layerData.refId, comps); + completeLayers(layerData.layers, comps); + } else if (layerData.ty === 4) { + completeShapes(layerData.shapes); + } else if (layerData.ty === 5) { + completeText(layerData); + } + } + } + } + function completeChars(chars, assets) { + if (chars) { + var i = 0; + var len = chars.length; + for (i = 0;i < len; i += 1) { + if (chars[i].t === 1) { + chars[i].data.layers = findCompLayers(chars[i].data.refId, assets); + completeLayers(chars[i].data.layers, assets); + } + } + } + } + function findComp(id, comps) { + var i = 0; + var len = comps.length; + while (i < len) { + if (comps[i].id === id) { + return comps[i]; + } + i += 1; + } + return null; + } + function findCompLayers(id, comps) { + var comp2 = findComp(id, comps); + if (comp2) { + if (!comp2.layers.__used) { + comp2.layers.__used = true; + return comp2.layers; + } + return JSON.parse(JSON.stringify(comp2.layers)); + } + return null; + } + function completeShapes(arr) { + var i; + var len = arr.length; + var j2; + var jLen; + for (i = len - 1;i >= 0; i -= 1) { + if (arr[i].ty === "sh") { + if (arr[i].ks.k.i) { + convertPathsToAbsoluteValues(arr[i].ks.k); + } else { + jLen = arr[i].ks.k.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (arr[i].ks.k[j2].s) { + convertPathsToAbsoluteValues(arr[i].ks.k[j2].s[0]); + } + if (arr[i].ks.k[j2].e) { + convertPathsToAbsoluteValues(arr[i].ks.k[j2].e[0]); + } + } + } + } else if (arr[i].ty === "gr") { + completeShapes(arr[i].it); + } + } + } + function convertPathsToAbsoluteValues(path) { + var i; + var len = path.i.length; + for (i = 0;i < len; i += 1) { + path.i[i][0] += path.v[i][0]; + path.i[i][1] += path.v[i][1]; + path.o[i][0] += path.v[i][0]; + path.o[i][1] += path.v[i][1]; + } + } + function checkVersion(minimum, animVersionString) { + var animVersion = animVersionString ? animVersionString.split(".") : [100, 100, 100]; + if (minimum[0] > animVersion[0]) { + return true; + } + if (animVersion[0] > minimum[0]) { + return false; + } + if (minimum[1] > animVersion[1]) { + return true; + } + if (animVersion[1] > minimum[1]) { + return false; + } + if (minimum[2] > animVersion[2]) { + return true; + } + if (animVersion[2] > minimum[2]) { + return false; + } + return null; + } + var checkText = function() { + var minimumVersion = [4, 4, 14]; + function updateTextLayer(textLayer) { + var documentData = textLayer.t.d; + textLayer.t.d = { + k: [ + { + s: documentData, + t: 0 + } + ] + }; + } + function iterateLayers(layers) { + var i; + var len = layers.length; + for (i = 0;i < len; i += 1) { + if (layers[i].ty === 5) { + updateTextLayer(layers[i]); + } + } + } + return function(animationData2) { + if (checkVersion(minimumVersion, animationData2.v)) { + iterateLayers(animationData2.layers); + if (animationData2.assets) { + var i; + var len = animationData2.assets.length; + for (i = 0;i < len; i += 1) { + if (animationData2.assets[i].layers) { + iterateLayers(animationData2.assets[i].layers); + } + } + } + } + }; + }(); + var checkChars = function() { + var minimumVersion = [4, 7, 99]; + return function(animationData2) { + if (animationData2.chars && !checkVersion(minimumVersion, animationData2.v)) { + var i; + var len = animationData2.chars.length; + for (i = 0;i < len; i += 1) { + var charData = animationData2.chars[i]; + if (charData.data && charData.data.shapes) { + completeShapes(charData.data.shapes); + charData.data.ip = 0; + charData.data.op = 99999; + charData.data.st = 0; + charData.data.sr = 1; + charData.data.ks = { + p: { k: [0, 0], a: 0 }, + s: { k: [100, 100], a: 0 }, + a: { k: [0, 0], a: 0 }, + r: { k: 0, a: 0 }, + o: { k: 100, a: 0 } + }; + if (!animationData2.chars[i].t) { + charData.data.shapes.push({ + ty: "no" + }); + charData.data.shapes[0].it.push({ + p: { k: [0, 0], a: 0 }, + s: { k: [100, 100], a: 0 }, + a: { k: [0, 0], a: 0 }, + r: { k: 0, a: 0 }, + o: { k: 100, a: 0 }, + sk: { k: 0, a: 0 }, + sa: { k: 0, a: 0 }, + ty: "tr" + }); + } + } + } + } + }; + }(); + var checkPathProperties = function() { + var minimumVersion = [5, 7, 15]; + function updateTextLayer(textLayer) { + var pathData = textLayer.t.p; + if (typeof pathData.a === "number") { + pathData.a = { + a: 0, + k: pathData.a + }; + } + if (typeof pathData.p === "number") { + pathData.p = { + a: 0, + k: pathData.p + }; + } + if (typeof pathData.r === "number") { + pathData.r = { + a: 0, + k: pathData.r + }; + } + } + function iterateLayers(layers) { + var i; + var len = layers.length; + for (i = 0;i < len; i += 1) { + if (layers[i].ty === 5) { + updateTextLayer(layers[i]); + } + } + } + return function(animationData2) { + if (checkVersion(minimumVersion, animationData2.v)) { + iterateLayers(animationData2.layers); + if (animationData2.assets) { + var i; + var len = animationData2.assets.length; + for (i = 0;i < len; i += 1) { + if (animationData2.assets[i].layers) { + iterateLayers(animationData2.assets[i].layers); + } + } + } + } + }; + }(); + var checkColors = function() { + var minimumVersion = [4, 1, 9]; + function iterateShapes(shapes) { + var i; + var len = shapes.length; + var j2; + var jLen; + for (i = 0;i < len; i += 1) { + if (shapes[i].ty === "gr") { + iterateShapes(shapes[i].it); + } else if (shapes[i].ty === "fl" || shapes[i].ty === "st") { + if (shapes[i].c.k && shapes[i].c.k[0].i) { + jLen = shapes[i].c.k.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (shapes[i].c.k[j2].s) { + shapes[i].c.k[j2].s[0] /= 255; + shapes[i].c.k[j2].s[1] /= 255; + shapes[i].c.k[j2].s[2] /= 255; + shapes[i].c.k[j2].s[3] /= 255; + } + if (shapes[i].c.k[j2].e) { + shapes[i].c.k[j2].e[0] /= 255; + shapes[i].c.k[j2].e[1] /= 255; + shapes[i].c.k[j2].e[2] /= 255; + shapes[i].c.k[j2].e[3] /= 255; + } + } + } else { + shapes[i].c.k[0] /= 255; + shapes[i].c.k[1] /= 255; + shapes[i].c.k[2] /= 255; + shapes[i].c.k[3] /= 255; + } + } + } + } + function iterateLayers(layers) { + var i; + var len = layers.length; + for (i = 0;i < len; i += 1) { + if (layers[i].ty === 4) { + iterateShapes(layers[i].shapes); + } + } + } + return function(animationData2) { + if (checkVersion(minimumVersion, animationData2.v)) { + iterateLayers(animationData2.layers); + if (animationData2.assets) { + var i; + var len = animationData2.assets.length; + for (i = 0;i < len; i += 1) { + if (animationData2.assets[i].layers) { + iterateLayers(animationData2.assets[i].layers); + } + } + } + } + }; + }(); + var checkShapes = function() { + var minimumVersion = [4, 4, 18]; + function completeClosingShapes(arr) { + var i; + var len = arr.length; + var j2; + var jLen; + for (i = len - 1;i >= 0; i -= 1) { + if (arr[i].ty === "sh") { + if (arr[i].ks.k.i) { + arr[i].ks.k.c = arr[i].closed; + } else { + jLen = arr[i].ks.k.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (arr[i].ks.k[j2].s) { + arr[i].ks.k[j2].s[0].c = arr[i].closed; + } + if (arr[i].ks.k[j2].e) { + arr[i].ks.k[j2].e[0].c = arr[i].closed; + } + } + } + } else if (arr[i].ty === "gr") { + completeClosingShapes(arr[i].it); + } + } + } + function iterateLayers(layers) { + var layerData; + var i; + var len = layers.length; + var j2; + var jLen; + var k2; + var kLen; + for (i = 0;i < len; i += 1) { + layerData = layers[i]; + if (layerData.hasMask) { + var maskProps = layerData.masksProperties; + jLen = maskProps.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (maskProps[j2].pt.k.i) { + maskProps[j2].pt.k.c = maskProps[j2].cl; + } else { + kLen = maskProps[j2].pt.k.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + if (maskProps[j2].pt.k[k2].s) { + maskProps[j2].pt.k[k2].s[0].c = maskProps[j2].cl; + } + if (maskProps[j2].pt.k[k2].e) { + maskProps[j2].pt.k[k2].e[0].c = maskProps[j2].cl; + } + } + } + } + } + if (layerData.ty === 4) { + completeClosingShapes(layerData.shapes); + } + } + } + return function(animationData2) { + if (checkVersion(minimumVersion, animationData2.v)) { + iterateLayers(animationData2.layers); + if (animationData2.assets) { + var i; + var len = animationData2.assets.length; + for (i = 0;i < len; i += 1) { + if (animationData2.assets[i].layers) { + iterateLayers(animationData2.assets[i].layers); + } + } + } + } + }; + }(); + function completeData(animationData2) { + if (animationData2.__complete) { + return; + } + checkColors(animationData2); + checkText(animationData2); + checkChars(animationData2); + checkPathProperties(animationData2); + checkShapes(animationData2); + completeLayers(animationData2.layers, animationData2.assets); + completeChars(animationData2.chars, animationData2.assets); + animationData2.__complete = true; + } + function completeText(data2) { + if (data2.t.a.length === 0 && !("m" in data2.t.p)) { + } + } + var moduleOb = {}; + moduleOb.completeData = completeData; + moduleOb.checkColors = checkColors; + moduleOb.checkChars = checkChars; + moduleOb.checkPathProperties = checkPathProperties; + moduleOb.checkShapes = checkShapes; + moduleOb.completeLayers = completeLayers; + return moduleOb; + } + if (!_workerSelf.dataManager) { + _workerSelf.dataManager = dataFunctionManager(); + } + if (!_workerSelf.assetLoader) { + _workerSelf.assetLoader = function() { + function formatResponse(xhr) { + var contentTypeHeader = xhr.getResponseHeader("content-type"); + if (contentTypeHeader && xhr.responseType === "json" && contentTypeHeader.indexOf("json") !== -1) { + return xhr.response; + } + if (xhr.response && typeof xhr.response === "object") { + return xhr.response; + } + if (xhr.response && typeof xhr.response === "string") { + return JSON.parse(xhr.response); + } + if (xhr.responseText) { + return JSON.parse(xhr.responseText); + } + return null; + } + function loadAsset(path, fullPath, callback, errorCallback) { + var response; + var xhr = new XMLHttpRequest; + try { + xhr.responseType = "json"; + } catch (err) { + } + xhr.onreadystatechange = function() { + if (xhr.readyState === 4) { + if (xhr.status === 200) { + response = formatResponse(xhr); + callback(response); + } else { + try { + response = formatResponse(xhr); + callback(response); + } catch (err) { + if (errorCallback) { + errorCallback(err); + } + } + } + } + }; + try { + xhr.open("GET", path, true); + } catch (error) { + xhr.open("GET", fullPath + "/" + path, true); + } + xhr.send(); + } + return { + load: loadAsset + }; + }(); + } + if (e.data.type === "loadAnimation") { + _workerSelf.assetLoader.load(e.data.path, e.data.fullPath, function(data2) { + _workerSelf.dataManager.completeData(data2); + _workerSelf.postMessage({ + id: e.data.id, + payload: data2, + status: "success" + }); + }, function() { + _workerSelf.postMessage({ + id: e.data.id, + status: "error" + }); + }); + } else if (e.data.type === "complete") { + var animation = e.data.animation; + _workerSelf.dataManager.completeData(animation); + _workerSelf.postMessage({ + id: e.data.id, + payload: animation, + status: "success" + }); + } else if (e.data.type === "loadData") { + _workerSelf.assetLoader.load(e.data.path, e.data.fullPath, function(data2) { + _workerSelf.postMessage({ + id: e.data.id, + payload: data2, + status: "success" + }); + }, function() { + _workerSelf.postMessage({ + id: e.data.id, + status: "error" + }); + }); + } + }); + workerInstance.onmessage = function(event) { + var data2 = event.data; + var id = data2.id; + var process2 = processes[id]; + processes[id] = null; + if (data2.status === "success") { + process2.onComplete(data2.payload); + } else if (process2.onError) { + process2.onError(); + } + }; + } + } + function createProcess(onComplete, onError) { + _counterId += 1; + var id = "processId_" + _counterId; + processes[id] = { + onComplete, + onError + }; + return id; + } + function loadAnimation2(path, onComplete, onError) { + setupWorker(); + var processId = createProcess(onComplete, onError); + workerInstance.postMessage({ + type: "loadAnimation", + path, + fullPath: window.location.origin + window.location.pathname, + id: processId + }); + } + function loadData(path, onComplete, onError) { + setupWorker(); + var processId = createProcess(onComplete, onError); + workerInstance.postMessage({ + type: "loadData", + path, + fullPath: window.location.origin + window.location.pathname, + id: processId + }); + } + function completeAnimation(anim, onComplete, onError) { + setupWorker(); + var processId = createProcess(onComplete, onError); + workerInstance.postMessage({ + type: "complete", + animation: anim, + id: processId + }); + } + return { + loadAnimation: loadAnimation2, + loadData, + completeAnimation + }; + }(); + const ImagePreloader = function() { + var proxyImage = function() { + var canvas = createTag("canvas"); + canvas.width = 1; + canvas.height = 1; + var ctx = canvas.getContext("2d"); + ctx.fillStyle = "rgba(0,0,0,0)"; + ctx.fillRect(0, 0, 1, 1); + return canvas; + }(); + function imageLoaded() { + this.loadedAssets += 1; + if (this.loadedAssets === this.totalImages && this.loadedFootagesCount === this.totalFootages) { + if (this.imagesLoadedCb) { + this.imagesLoadedCb(null); + } + } + } + function footageLoaded() { + this.loadedFootagesCount += 1; + if (this.loadedAssets === this.totalImages && this.loadedFootagesCount === this.totalFootages) { + if (this.imagesLoadedCb) { + this.imagesLoadedCb(null); + } + } + } + function getAssetsPath(assetData, assetsPath, originalPath) { + var path = ""; + if (assetData.e) { + path = assetData.p; + } else if (assetsPath) { + var imagePath = assetData.p; + if (imagePath.indexOf("images/") !== -1) { + imagePath = imagePath.split("/")[1]; + } + path = assetsPath + imagePath; + } else { + path = originalPath; + path += assetData.u ? assetData.u : ""; + path += assetData.p; + } + return path; + } + function testImageLoaded(img) { + var _count = 0; + var intervalId = setInterval(function() { + var box = img.getBBox(); + if (box.width || _count > 500) { + this._imageLoaded(); + clearInterval(intervalId); + } + _count += 1; + }.bind(this), 50); + } + function createImageData(assetData) { + var path = getAssetsPath(assetData, this.assetsPath, this.path); + var img = createNS("image"); + if (isSafari) { + this.testImageLoaded(img); + } else { + img.addEventListener("load", this._imageLoaded, false); + } + img.addEventListener("error", function() { + ob2.img = proxyImage; + this._imageLoaded(); + }.bind(this), false); + img.setAttributeNS("http://www.w3.org/1999/xlink", "href", path); + if (this._elementHelper.append) { + this._elementHelper.append(img); + } else { + this._elementHelper.appendChild(img); + } + var ob2 = { + img, + assetData + }; + return ob2; + } + function createImgData(assetData) { + var path = getAssetsPath(assetData, this.assetsPath, this.path); + var img = createTag("img"); + img.crossOrigin = "anonymous"; + img.addEventListener("load", this._imageLoaded, false); + img.addEventListener("error", function() { + ob2.img = proxyImage; + this._imageLoaded(); + }.bind(this), false); + img.src = path; + var ob2 = { + img, + assetData + }; + return ob2; + } + function createFootageData(data2) { + var ob2 = { + assetData: data2 + }; + var path = getAssetsPath(data2, this.assetsPath, this.path); + dataManager.loadData(path, function(footageData) { + ob2.img = footageData; + this._footageLoaded(); + }.bind(this), function() { + ob2.img = {}; + this._footageLoaded(); + }.bind(this)); + return ob2; + } + function loadAssets(assets, cb) { + this.imagesLoadedCb = cb; + var i; + var len = assets.length; + for (i = 0;i < len; i += 1) { + if (!assets[i].layers) { + if (!assets[i].t || assets[i].t === "seq") { + this.totalImages += 1; + this.images.push(this._createImageData(assets[i])); + } else if (assets[i].t === 3) { + this.totalFootages += 1; + this.images.push(this.createFootageData(assets[i])); + } + } + } + } + function setPath(path) { + this.path = path || ""; + } + function setAssetsPath(path) { + this.assetsPath = path || ""; + } + function getAsset(assetData) { + var i = 0; + var len = this.images.length; + while (i < len) { + if (this.images[i].assetData === assetData) { + return this.images[i].img; + } + i += 1; + } + return null; + } + function destroy() { + this.imagesLoadedCb = null; + this.images.length = 0; + } + function loadedImages() { + return this.totalImages === this.loadedAssets; + } + function loadedFootages() { + return this.totalFootages === this.loadedFootagesCount; + } + function setCacheType(type, elementHelper) { + if (type === "svg") { + this._elementHelper = elementHelper; + this._createImageData = this.createImageData.bind(this); + } else { + this._createImageData = this.createImgData.bind(this); + } + } + function ImagePreloaderFactory() { + this._imageLoaded = imageLoaded.bind(this); + this._footageLoaded = footageLoaded.bind(this); + this.testImageLoaded = testImageLoaded.bind(this); + this.createFootageData = createFootageData.bind(this); + this.assetsPath = ""; + this.path = ""; + this.totalImages = 0; + this.totalFootages = 0; + this.loadedAssets = 0; + this.loadedFootagesCount = 0; + this.imagesLoadedCb = null; + this.images = []; + } + ImagePreloaderFactory.prototype = { + loadAssets, + setAssetsPath, + setPath, + loadedImages, + loadedFootages, + destroy, + getAsset, + createImgData, + createImageData, + imageLoaded, + footageLoaded, + setCacheType + }; + return ImagePreloaderFactory; + }(); + BaseEvent.prototype = { + triggerEvent: function(eventName, args) { + if (this._cbs[eventName]) { + var callbacks = this._cbs[eventName]; + for (var i = 0;i < callbacks.length; i += 1) { + callbacks[i](args); + } + } + }, + addEventListener: function(eventName, callback) { + if (!this._cbs[eventName]) { + this._cbs[eventName] = []; + } + this._cbs[eventName].push(callback); + return function() { + this.removeEventListener(eventName, callback); + }.bind(this); + }, + removeEventListener: function(eventName, callback) { + if (!callback) { + this._cbs[eventName] = null; + } else if (this._cbs[eventName]) { + var i = 0; + var len = this._cbs[eventName].length; + while (i < len) { + if (this._cbs[eventName][i] === callback) { + this._cbs[eventName].splice(i, 1); + i -= 1; + len -= 1; + } + i += 1; + } + if (!this._cbs[eventName].length) { + this._cbs[eventName] = null; + } + } + } + }; + const markerParser = function() { + function parsePayloadLines(payload) { + var lines = payload.split(`\r +`); + var keys2 = {}; + var line; + var keysCount = 0; + for (var i = 0;i < lines.length; i += 1) { + line = lines[i].split(":"); + if (line.length === 2) { + keys2[line[0]] = line[1].trim(); + keysCount += 1; + } + } + if (keysCount === 0) { + throw new Error; + } + return keys2; + } + return function(_markers) { + var markers = []; + for (var i = 0;i < _markers.length; i += 1) { + var _marker = _markers[i]; + var markerData = { + time: _marker.tm, + duration: _marker.dr + }; + try { + markerData.payload = JSON.parse(_markers[i].cm); + } catch (_2) { + try { + markerData.payload = parsePayloadLines(_markers[i].cm); + } catch (__) { + markerData.payload = { + name: _markers[i].cm + }; + } + } + markers.push(markerData); + } + return markers; + }; + }(); + const ProjectInterface = function() { + function registerComposition(comp2) { + this.compositions.push(comp2); + } + return function() { + function _thisProjectFunction(name2) { + var i = 0; + var len = this.compositions.length; + while (i < len) { + if (this.compositions[i].data && this.compositions[i].data.nm === name2) { + if (this.compositions[i].prepareFrame && this.compositions[i].data.xt) { + this.compositions[i].prepareFrame(this.currentFrame); + } + return this.compositions[i].compInterface; + } + i += 1; + } + return null; + } + _thisProjectFunction.compositions = []; + _thisProjectFunction.currentFrame = 0; + _thisProjectFunction.registerComposition = registerComposition; + return _thisProjectFunction; + }; + }(); + const renderers = {}; + const registerRenderer = (key2, value2) => { + renderers[key2] = value2; + }; + const AnimationItem = function() { + this._cbs = []; + this.name = ""; + this.path = ""; + this.isLoaded = false; + this.currentFrame = 0; + this.currentRawFrame = 0; + this.firstFrame = 0; + this.totalFrames = 0; + this.frameRate = 0; + this.frameMult = 0; + this.playSpeed = 1; + this.playDirection = 1; + this.playCount = 0; + this.animationData = {}; + this.assets = []; + this.isPaused = true; + this.autoplay = false; + this.loop = true; + this.renderer = null; + this.animationID = createElementID(); + this.assetsPath = ""; + this.timeCompleted = 0; + this.segmentPos = 0; + this.isSubframeEnabled = getSubframeEnabled(); + this.segments = []; + this._idle = true; + this._completedLoop = false; + this.projectInterface = ProjectInterface(); + this.imagePreloader = new ImagePreloader; + this.audioController = audioControllerFactory(); + this.markers = []; + this.configAnimation = this.configAnimation.bind(this); + this.onSetupError = this.onSetupError.bind(this); + this.onSegmentComplete = this.onSegmentComplete.bind(this); + this.drawnFrameEvent = new BMEnterFrameEvent("drawnFrame", 0, 0, 0); + }; + extendPrototype([BaseEvent], AnimationItem); + AnimationItem.prototype.setParams = function(params) { + if (params.wrapper || params.container) { + this.wrapper = params.wrapper || params.container; + } + var animType = "svg"; + if (params.animType) { + animType = params.animType; + } else if (params.renderer) { + animType = params.renderer; + } + const RendererClass = getRenderer(animType); + this.renderer = new RendererClass(this, params.rendererSettings); + this.imagePreloader.setCacheType(animType, this.renderer.globalData.defs); + this.renderer.setProjectInterface(this.projectInterface); + this.animType = animType; + if (params.loop === "" || params.loop === null || params.loop === undefined || params.loop === true) { + this.loop = true; + } else if (params.loop === false) { + this.loop = false; + } else { + this.loop = parseInt(params.loop, 10); + } + this.autoplay = "autoplay" in params ? params.autoplay : true; + this.name = params.name ? params.name : ""; + this.autoloadSegments = Object.prototype.hasOwnProperty.call(params, "autoloadSegments") ? params.autoloadSegments : true; + this.assetsPath = params.assetsPath; + this.initialSegment = params.initialSegment; + if (params.audioFactory) { + this.audioController.setAudioFactory(params.audioFactory); + } + if (params.animationData) { + this.setupAnimation(params.animationData); + } else if (params.path) { + if (params.path.lastIndexOf("\\") !== -1) { + this.path = params.path.substr(0, params.path.lastIndexOf("\\") + 1); + } else { + this.path = params.path.substr(0, params.path.lastIndexOf("/") + 1); + } + this.fileName = params.path.substr(params.path.lastIndexOf("/") + 1); + this.fileName = this.fileName.substr(0, this.fileName.lastIndexOf(".json")); + dataManager.loadAnimation(params.path, this.configAnimation, this.onSetupError); + } + }; + AnimationItem.prototype.onSetupError = function() { + this.trigger("data_failed"); + }; + AnimationItem.prototype.setupAnimation = function(data2) { + dataManager.completeAnimation(data2, this.configAnimation); + }; + AnimationItem.prototype.setData = function(wrapper, animationData2) { + if (animationData2) { + if (typeof animationData2 !== "object") { + animationData2 = JSON.parse(animationData2); + } + } + var params = { + wrapper, + animationData: animationData2 + }; + var wrapperAttributes = wrapper.attributes; + params.path = wrapperAttributes.getNamedItem("data-animation-path") ? wrapperAttributes.getNamedItem("data-animation-path").value : wrapperAttributes.getNamedItem("data-bm-path") ? wrapperAttributes.getNamedItem("data-bm-path").value : wrapperAttributes.getNamedItem("bm-path") ? wrapperAttributes.getNamedItem("bm-path").value : ""; + params.animType = wrapperAttributes.getNamedItem("data-anim-type") ? wrapperAttributes.getNamedItem("data-anim-type").value : wrapperAttributes.getNamedItem("data-bm-type") ? wrapperAttributes.getNamedItem("data-bm-type").value : wrapperAttributes.getNamedItem("bm-type") ? wrapperAttributes.getNamedItem("bm-type").value : wrapperAttributes.getNamedItem("data-bm-renderer") ? wrapperAttributes.getNamedItem("data-bm-renderer").value : wrapperAttributes.getNamedItem("bm-renderer") ? wrapperAttributes.getNamedItem("bm-renderer").value : "canvas"; + var loop = wrapperAttributes.getNamedItem("data-anim-loop") ? wrapperAttributes.getNamedItem("data-anim-loop").value : wrapperAttributes.getNamedItem("data-bm-loop") ? wrapperAttributes.getNamedItem("data-bm-loop").value : wrapperAttributes.getNamedItem("bm-loop") ? wrapperAttributes.getNamedItem("bm-loop").value : ""; + if (loop === "false") { + params.loop = false; + } else if (loop === "true") { + params.loop = true; + } else if (loop !== "") { + params.loop = parseInt(loop, 10); + } + var autoplay = wrapperAttributes.getNamedItem("data-anim-autoplay") ? wrapperAttributes.getNamedItem("data-anim-autoplay").value : wrapperAttributes.getNamedItem("data-bm-autoplay") ? wrapperAttributes.getNamedItem("data-bm-autoplay").value : wrapperAttributes.getNamedItem("bm-autoplay") ? wrapperAttributes.getNamedItem("bm-autoplay").value : true; + params.autoplay = autoplay !== "false"; + params.name = wrapperAttributes.getNamedItem("data-name") ? wrapperAttributes.getNamedItem("data-name").value : wrapperAttributes.getNamedItem("data-bm-name") ? wrapperAttributes.getNamedItem("data-bm-name").value : wrapperAttributes.getNamedItem("bm-name") ? wrapperAttributes.getNamedItem("bm-name").value : ""; + var prerender = wrapperAttributes.getNamedItem("data-anim-prerender") ? wrapperAttributes.getNamedItem("data-anim-prerender").value : wrapperAttributes.getNamedItem("data-bm-prerender") ? wrapperAttributes.getNamedItem("data-bm-prerender").value : wrapperAttributes.getNamedItem("bm-prerender") ? wrapperAttributes.getNamedItem("bm-prerender").value : ""; + if (prerender === "false") { + params.prerender = false; + } + this.setParams(params); + }; + AnimationItem.prototype.includeLayers = function(data2) { + if (data2.op > this.animationData.op) { + this.animationData.op = data2.op; + this.totalFrames = Math.floor(data2.op - this.animationData.ip); + } + var layers = this.animationData.layers; + var i; + var len = layers.length; + var newLayers = data2.layers; + var j2; + var jLen = newLayers.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + i = 0; + while (i < len) { + if (layers[i].id === newLayers[j2].id) { + layers[i] = newLayers[j2]; + break; + } + i += 1; + } + } + if (data2.chars || data2.fonts) { + this.renderer.globalData.fontManager.addChars(data2.chars); + this.renderer.globalData.fontManager.addFonts(data2.fonts, this.renderer.globalData.defs); + } + if (data2.assets) { + len = data2.assets.length; + for (i = 0;i < len; i += 1) { + this.animationData.assets.push(data2.assets[i]); + } + } + this.animationData.__complete = false; + dataManager.completeAnimation(this.animationData, this.onSegmentComplete); + }; + AnimationItem.prototype.onSegmentComplete = function(data2) { + this.animationData = data2; + var expressionsPlugin2 = getExpressionsPlugin(); + if (expressionsPlugin2) { + expressionsPlugin2.initExpressions(this); + } + this.loadNextSegment(); + }; + AnimationItem.prototype.loadNextSegment = function() { + var segments = this.animationData.segments; + if (!segments || segments.length === 0 || !this.autoloadSegments) { + this.trigger("data_ready"); + this.timeCompleted = this.totalFrames; + return; + } + var segment = segments.shift(); + this.timeCompleted = segment.time * this.frameRate; + var segmentPath = this.path + this.fileName + "_" + this.segmentPos + ".json"; + this.segmentPos += 1; + dataManager.loadData(segmentPath, this.includeLayers.bind(this), function() { + this.trigger("data_failed"); + }.bind(this)); + }; + AnimationItem.prototype.loadSegments = function() { + var segments = this.animationData.segments; + if (!segments) { + this.timeCompleted = this.totalFrames; + } + this.loadNextSegment(); + }; + AnimationItem.prototype.imagesLoaded = function() { + this.trigger("loaded_images"); + this.checkLoaded(); + }; + AnimationItem.prototype.preloadImages = function() { + this.imagePreloader.setAssetsPath(this.assetsPath); + this.imagePreloader.setPath(this.path); + this.imagePreloader.loadAssets(this.animationData.assets, this.imagesLoaded.bind(this)); + }; + AnimationItem.prototype.configAnimation = function(animData) { + if (!this.renderer) { + return; + } + try { + this.animationData = animData; + if (this.initialSegment) { + this.totalFrames = Math.floor(this.initialSegment[1] - this.initialSegment[0]); + this.firstFrame = Math.round(this.initialSegment[0]); + } else { + this.totalFrames = Math.floor(this.animationData.op - this.animationData.ip); + this.firstFrame = Math.round(this.animationData.ip); + } + this.renderer.configAnimation(animData); + if (!animData.assets) { + animData.assets = []; + } + this.assets = this.animationData.assets; + this.frameRate = this.animationData.fr; + this.frameMult = this.animationData.fr / 1000; + this.renderer.searchExtraCompositions(animData.assets); + this.markers = markerParser(animData.markers || []); + this.trigger("config_ready"); + this.preloadImages(); + this.loadSegments(); + this.updaFrameModifier(); + this.waitForFontsLoaded(); + if (this.isPaused) { + this.audioController.pause(); + } + } catch (error) { + this.triggerConfigError(error); + } + }; + AnimationItem.prototype.waitForFontsLoaded = function() { + if (!this.renderer) { + return; + } + if (this.renderer.globalData.fontManager.isLoaded) { + this.checkLoaded(); + } else { + setTimeout(this.waitForFontsLoaded.bind(this), 20); + } + }; + AnimationItem.prototype.checkLoaded = function() { + if (!this.isLoaded && this.renderer.globalData.fontManager.isLoaded && (this.imagePreloader.loadedImages() || this.renderer.rendererType !== "canvas") && this.imagePreloader.loadedFootages()) { + this.isLoaded = true; + var expressionsPlugin2 = getExpressionsPlugin(); + if (expressionsPlugin2) { + expressionsPlugin2.initExpressions(this); + } + this.renderer.initItems(); + setTimeout(function() { + this.trigger("DOMLoaded"); + }.bind(this), 0); + this.gotoFrame(); + if (this.autoplay) { + this.play(); + } + } + }; + AnimationItem.prototype.resize = function() { + this.renderer.updateContainerSize(); + }; + AnimationItem.prototype.setSubframe = function(flag) { + this.isSubframeEnabled = !!flag; + }; + AnimationItem.prototype.gotoFrame = function() { + this.currentFrame = this.isSubframeEnabled ? this.currentRawFrame : ~~this.currentRawFrame; + if (this.timeCompleted !== this.totalFrames && this.currentFrame > this.timeCompleted) { + this.currentFrame = this.timeCompleted; + } + this.trigger("enterFrame"); + this.renderFrame(); + this.trigger("drawnFrame"); + }; + AnimationItem.prototype.renderFrame = function() { + if (this.isLoaded === false || !this.renderer) { + return; + } + try { + this.renderer.renderFrame(this.currentFrame + this.firstFrame); + } catch (error) { + this.triggerRenderFrameError(error); + } + }; + AnimationItem.prototype.play = function(name2) { + if (name2 && this.name !== name2) { + return; + } + if (this.isPaused === true) { + this.isPaused = false; + this.trigger("_pause"); + this.audioController.resume(); + if (this._idle) { + this._idle = false; + this.trigger("_active"); + } + } + }; + AnimationItem.prototype.pause = function(name2) { + if (name2 && this.name !== name2) { + return; + } + if (this.isPaused === false) { + this.isPaused = true; + this.trigger("_play"); + this._idle = true; + this.trigger("_idle"); + this.audioController.pause(); + } + }; + AnimationItem.prototype.togglePause = function(name2) { + if (name2 && this.name !== name2) { + return; + } + if (this.isPaused === true) { + this.play(); + } else { + this.pause(); + } + }; + AnimationItem.prototype.stop = function(name2) { + if (name2 && this.name !== name2) { + return; + } + this.pause(); + this.playCount = 0; + this._completedLoop = false; + this.setCurrentRawFrameValue(0); + }; + AnimationItem.prototype.getMarkerData = function(markerName) { + var marker; + for (var i = 0;i < this.markers.length; i += 1) { + marker = this.markers[i]; + if (marker.payload && marker.payload.name === markerName) { + return marker; + } + } + return null; + }; + AnimationItem.prototype.goToAndStop = function(value2, isFrame, name2) { + if (name2 && this.name !== name2) { + return; + } + var numValue = Number(value2); + if (isNaN(numValue)) { + var marker = this.getMarkerData(value2); + if (marker) { + this.goToAndStop(marker.time, true); + } + } else if (isFrame) { + this.setCurrentRawFrameValue(value2); + } else { + this.setCurrentRawFrameValue(value2 * this.frameModifier); + } + this.pause(); + }; + AnimationItem.prototype.goToAndPlay = function(value2, isFrame, name2) { + if (name2 && this.name !== name2) { + return; + } + var numValue = Number(value2); + if (isNaN(numValue)) { + var marker = this.getMarkerData(value2); + if (marker) { + if (!marker.duration) { + this.goToAndStop(marker.time, true); + } else { + this.playSegments([marker.time, marker.time + marker.duration], true); + } + } + } else { + this.goToAndStop(numValue, isFrame, name2); + } + this.play(); + }; + AnimationItem.prototype.advanceTime = function(value2) { + if (this.isPaused === true || this.isLoaded === false) { + return; + } + var nextValue = this.currentRawFrame + value2 * this.frameModifier; + var _isComplete = false; + if (nextValue >= this.totalFrames - 1 && this.frameModifier > 0) { + if (!this.loop || this.playCount === this.loop) { + if (!this.checkSegments(nextValue > this.totalFrames ? nextValue % this.totalFrames : 0)) { + _isComplete = true; + nextValue = this.totalFrames - 1; + } + } else if (nextValue >= this.totalFrames) { + this.playCount += 1; + if (!this.checkSegments(nextValue % this.totalFrames)) { + this.setCurrentRawFrameValue(nextValue % this.totalFrames); + this._completedLoop = true; + this.trigger("loopComplete"); + } + } else { + this.setCurrentRawFrameValue(nextValue); + } + } else if (nextValue < 0) { + if (!this.checkSegments(nextValue % this.totalFrames)) { + if (this.loop && !(this.playCount-- <= 0 && this.loop !== true)) { + this.setCurrentRawFrameValue(this.totalFrames + nextValue % this.totalFrames); + if (!this._completedLoop) { + this._completedLoop = true; + } else { + this.trigger("loopComplete"); + } + } else { + _isComplete = true; + nextValue = 0; + } + } + } else { + this.setCurrentRawFrameValue(nextValue); + } + if (_isComplete) { + this.setCurrentRawFrameValue(nextValue); + this.pause(); + this.trigger("complete"); + } + }; + AnimationItem.prototype.adjustSegment = function(arr, offset) { + this.playCount = 0; + if (arr[1] < arr[0]) { + if (this.frameModifier > 0) { + if (this.playSpeed < 0) { + this.setSpeed(-this.playSpeed); + } else { + this.setDirection(-1); + } + } + this.totalFrames = arr[0] - arr[1]; + this.timeCompleted = this.totalFrames; + this.firstFrame = arr[1]; + this.setCurrentRawFrameValue(this.totalFrames - 0.001 - offset); + } else if (arr[1] > arr[0]) { + if (this.frameModifier < 0) { + if (this.playSpeed < 0) { + this.setSpeed(-this.playSpeed); + } else { + this.setDirection(1); + } + } + this.totalFrames = arr[1] - arr[0]; + this.timeCompleted = this.totalFrames; + this.firstFrame = arr[0]; + this.setCurrentRawFrameValue(0.001 + offset); + } + this.trigger("segmentStart"); + }; + AnimationItem.prototype.setSegment = function(init, end) { + var pendingFrame = -1; + if (this.isPaused) { + if (this.currentRawFrame + this.firstFrame < init) { + pendingFrame = init; + } else if (this.currentRawFrame + this.firstFrame > end) { + pendingFrame = end - init; + } + } + this.firstFrame = init; + this.totalFrames = end - init; + this.timeCompleted = this.totalFrames; + if (pendingFrame !== -1) { + this.goToAndStop(pendingFrame, true); + } + }; + AnimationItem.prototype.playSegments = function(arr, forceFlag) { + if (forceFlag) { + this.segments.length = 0; + } + if (typeof arr[0] === "object") { + var i; + var len = arr.length; + for (i = 0;i < len; i += 1) { + this.segments.push(arr[i]); + } + } else { + this.segments.push(arr); + } + if (this.segments.length && forceFlag) { + this.adjustSegment(this.segments.shift(), 0); + } + if (this.isPaused) { + this.play(); + } + }; + AnimationItem.prototype.resetSegments = function(forceFlag) { + this.segments.length = 0; + this.segments.push([this.animationData.ip, this.animationData.op]); + if (forceFlag) { + this.checkSegments(0); + } + }; + AnimationItem.prototype.checkSegments = function(offset) { + if (this.segments.length) { + this.adjustSegment(this.segments.shift(), offset); + return true; + } + return false; + }; + AnimationItem.prototype.destroy = function(name2) { + if (name2 && this.name !== name2 || !this.renderer) { + return; + } + this.renderer.destroy(); + this.imagePreloader.destroy(); + this.trigger("destroy"); + this._cbs = null; + this.onEnterFrame = null; + this.onLoopComplete = null; + this.onComplete = null; + this.onSegmentStart = null; + this.onDestroy = null; + this.renderer = null; + this.renderer = null; + this.imagePreloader = null; + this.projectInterface = null; + }; + AnimationItem.prototype.setCurrentRawFrameValue = function(value2) { + this.currentRawFrame = value2; + this.gotoFrame(); + }; + AnimationItem.prototype.setSpeed = function(val2) { + this.playSpeed = val2; + this.updaFrameModifier(); + }; + AnimationItem.prototype.setDirection = function(val2) { + this.playDirection = val2 < 0 ? -1 : 1; + this.updaFrameModifier(); + }; + AnimationItem.prototype.setVolume = function(val2, name2) { + if (name2 && this.name !== name2) { + return; + } + this.audioController.setVolume(val2); + }; + AnimationItem.prototype.getVolume = function() { + return this.audioController.getVolume(); + }; + AnimationItem.prototype.mute = function(name2) { + if (name2 && this.name !== name2) { + return; + } + this.audioController.mute(); + }; + AnimationItem.prototype.unmute = function(name2) { + if (name2 && this.name !== name2) { + return; + } + this.audioController.unmute(); + }; + AnimationItem.prototype.updaFrameModifier = function() { + this.frameModifier = this.frameMult * this.playSpeed * this.playDirection; + this.audioController.setRate(this.playSpeed * this.playDirection); + }; + AnimationItem.prototype.getPath = function() { + return this.path; + }; + AnimationItem.prototype.getAssetsPath = function(assetData) { + var path = ""; + if (assetData.e) { + path = assetData.p; + } else if (this.assetsPath) { + var imagePath = assetData.p; + if (imagePath.indexOf("images/") !== -1) { + imagePath = imagePath.split("/")[1]; + } + path = this.assetsPath + imagePath; + } else { + path = this.path; + path += assetData.u ? assetData.u : ""; + path += assetData.p; + } + return path; + }; + AnimationItem.prototype.getAssetData = function(id) { + var i = 0; + var len = this.assets.length; + while (i < len) { + if (id === this.assets[i].id) { + return this.assets[i]; + } + i += 1; + } + return null; + }; + AnimationItem.prototype.hide = function() { + this.renderer.hide(); + }; + AnimationItem.prototype.show = function() { + this.renderer.show(); + }; + AnimationItem.prototype.getDuration = function(isFrame) { + return isFrame ? this.totalFrames : this.totalFrames / this.frameRate; + }; + AnimationItem.prototype.updateDocumentData = function(path, documentData, index2) { + try { + var element = this.renderer.getElementByPath(path); + element.updateDocumentData(documentData, index2); + } catch (error) { + } + }; + AnimationItem.prototype.trigger = function(name2) { + if (this._cbs && this._cbs[name2]) { + switch (name2) { + case "enterFrame": + this.triggerEvent(name2, new BMEnterFrameEvent(name2, this.currentFrame, this.totalFrames, this.frameModifier)); + break; + case "drawnFrame": + this.drawnFrameEvent.currentTime = this.currentFrame; + this.drawnFrameEvent.totalTime = this.totalFrames; + this.drawnFrameEvent.direction = this.frameModifier; + this.triggerEvent(name2, this.drawnFrameEvent); + break; + case "loopComplete": + this.triggerEvent(name2, new BMCompleteLoopEvent(name2, this.loop, this.playCount, this.frameMult)); + break; + case "complete": + this.triggerEvent(name2, new BMCompleteEvent(name2, this.frameMult)); + break; + case "segmentStart": + this.triggerEvent(name2, new BMSegmentStartEvent(name2, this.firstFrame, this.totalFrames)); + break; + case "destroy": + this.triggerEvent(name2, new BMDestroyEvent(name2, this)); + break; + default: + this.triggerEvent(name2); + } + } + if (name2 === "enterFrame" && this.onEnterFrame) { + this.onEnterFrame.call(this, new BMEnterFrameEvent(name2, this.currentFrame, this.totalFrames, this.frameMult)); + } + if (name2 === "loopComplete" && this.onLoopComplete) { + this.onLoopComplete.call(this, new BMCompleteLoopEvent(name2, this.loop, this.playCount, this.frameMult)); + } + if (name2 === "complete" && this.onComplete) { + this.onComplete.call(this, new BMCompleteEvent(name2, this.frameMult)); + } + if (name2 === "segmentStart" && this.onSegmentStart) { + this.onSegmentStart.call(this, new BMSegmentStartEvent(name2, this.firstFrame, this.totalFrames)); + } + if (name2 === "destroy" && this.onDestroy) { + this.onDestroy.call(this, new BMDestroyEvent(name2, this)); + } + }; + AnimationItem.prototype.triggerRenderFrameError = function(nativeError) { + var error = new BMRenderFrameErrorEvent(nativeError, this.currentFrame); + this.triggerEvent("error", error); + if (this.onError) { + this.onError.call(this, error); + } + }; + AnimationItem.prototype.triggerConfigError = function(nativeError) { + var error = new BMConfigErrorEvent(nativeError, this.currentFrame); + this.triggerEvent("error", error); + if (this.onError) { + this.onError.call(this, error); + } + }; + const animationManager = function() { + var moduleOb = {}; + var registeredAnimations = []; + var initTime = 0; + var len = 0; + var playingAnimationsNum = 0; + var _stopped = true; + var _isFrozen = false; + function removeElement(ev) { + var i = 0; + var animItem = ev.target; + while (i < len) { + if (registeredAnimations[i].animation === animItem) { + registeredAnimations.splice(i, 1); + i -= 1; + len -= 1; + if (!animItem.isPaused) { + subtractPlayingCount(); + } + } + i += 1; + } + } + function registerAnimation(element, animationData2) { + if (!element) { + return null; + } + var i = 0; + while (i < len) { + if (registeredAnimations[i].elem === element && registeredAnimations[i].elem !== null) { + return registeredAnimations[i].animation; + } + i += 1; + } + var animItem = new AnimationItem; + setupAnimation(animItem, element); + animItem.setData(element, animationData2); + return animItem; + } + function getRegisteredAnimations() { + var i; + var lenAnims = registeredAnimations.length; + var animations = []; + for (i = 0;i < lenAnims; i += 1) { + animations.push(registeredAnimations[i].animation); + } + return animations; + } + function addPlayingCount() { + playingAnimationsNum += 1; + activate(); + } + function subtractPlayingCount() { + playingAnimationsNum -= 1; + } + function setupAnimation(animItem, element) { + animItem.addEventListener("destroy", removeElement); + animItem.addEventListener("_active", addPlayingCount); + animItem.addEventListener("_idle", subtractPlayingCount); + registeredAnimations.push({ elem: element, animation: animItem }); + len += 1; + } + function loadAnimation2(params) { + var animItem = new AnimationItem; + setupAnimation(animItem, null); + animItem.setParams(params); + return animItem; + } + function setSpeed(val2, animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.setSpeed(val2, animation); + } + } + function setDirection(val2, animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.setDirection(val2, animation); + } + } + function play(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.play(animation); + } + } + function resume(nowTime) { + var elapsedTime = nowTime - initTime; + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.advanceTime(elapsedTime); + } + initTime = nowTime; + if (playingAnimationsNum && !_isFrozen) { + window.requestAnimationFrame(resume); + } else { + _stopped = true; + } + } + function first2(nowTime) { + initTime = nowTime; + window.requestAnimationFrame(resume); + } + function pause(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.pause(animation); + } + } + function goToAndStop(value2, isFrame, animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.goToAndStop(value2, isFrame, animation); + } + } + function stop(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.stop(animation); + } + } + function togglePause(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.togglePause(animation); + } + } + function destroy(animation) { + var i; + for (i = len - 1;i >= 0; i -= 1) { + registeredAnimations[i].animation.destroy(animation); + } + } + function searchAnimations2(animationData2, standalone2, renderer2) { + var animElements = [].concat([].slice.call(document.getElementsByClassName("lottie")), [].slice.call(document.getElementsByClassName("bodymovin"))); + var i; + var lenAnims = animElements.length; + for (i = 0;i < lenAnims; i += 1) { + if (renderer2) { + animElements[i].setAttribute("data-bm-type", renderer2); + } + registerAnimation(animElements[i], animationData2); + } + if (standalone2 && lenAnims === 0) { + if (!renderer2) { + renderer2 = "svg"; + } + var body = document.getElementsByTagName("body")[0]; + body.innerText = ""; + var div2 = createTag("div"); + div2.style.width = "100%"; + div2.style.height = "100%"; + div2.setAttribute("data-bm-type", renderer2); + body.appendChild(div2); + registerAnimation(div2, animationData2); + } + } + function resize() { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.resize(); + } + } + function activate() { + if (!_isFrozen && playingAnimationsNum) { + if (_stopped) { + window.requestAnimationFrame(first2); + _stopped = false; + } + } + } + function freeze() { + _isFrozen = true; + } + function unfreeze() { + _isFrozen = false; + activate(); + } + function setVolume(val2, animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.setVolume(val2, animation); + } + } + function mute(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.mute(animation); + } + } + function unmute(animation) { + var i; + for (i = 0;i < len; i += 1) { + registeredAnimations[i].animation.unmute(animation); + } + } + moduleOb.registerAnimation = registerAnimation; + moduleOb.loadAnimation = loadAnimation2; + moduleOb.setSpeed = setSpeed; + moduleOb.setDirection = setDirection; + moduleOb.play = play; + moduleOb.pause = pause; + moduleOb.stop = stop; + moduleOb.togglePause = togglePause; + moduleOb.searchAnimations = searchAnimations2; + moduleOb.resize = resize; + moduleOb.goToAndStop = goToAndStop; + moduleOb.destroy = destroy; + moduleOb.freeze = freeze; + moduleOb.unfreeze = unfreeze; + moduleOb.setVolume = setVolume; + moduleOb.mute = mute; + moduleOb.unmute = unmute; + moduleOb.getRegisteredAnimations = getRegisteredAnimations; + return moduleOb; + }(); + const BezierFactory = function() { + var ob2 = {}; + ob2.getBezierEasing = getBezierEasing; + var beziers = {}; + function getBezierEasing(a, b, c, d, nm) { + var str = nm || ("bez_" + a + "_" + b + "_" + c + "_" + d).replace(/\./g, "p"); + if (beziers[str]) { + return beziers[str]; + } + var bezEasing = new BezierEasing([a, b, c, d]); + beziers[str] = bezEasing; + return bezEasing; + } + var NEWTON_ITERATIONS = 4; + var NEWTON_MIN_SLOPE = 0.001; + var SUBDIVISION_PRECISION = 0.0000001; + var SUBDIVISION_MAX_ITERATIONS = 10; + var kSplineTableSize = 11; + var kSampleStepSize = 1 / (kSplineTableSize - 1); + var float32ArraySupported = typeof Float32Array === "function"; + function A2(aA1, aA2) { + return 1 - 3 * aA2 + 3 * aA1; + } + function B2(aA1, aA2) { + return 3 * aA2 - 6 * aA1; + } + function C4(aA1) { + return 3 * aA1; + } + function calcBezier(aT, aA1, aA2) { + return ((A2(aA1, aA2) * aT + B2(aA1, aA2)) * aT + C4(aA1)) * aT; + } + function getSlope(aT, aA1, aA2) { + return 3 * A2(aA1, aA2) * aT * aT + 2 * B2(aA1, aA2) * aT + C4(aA1); + } + function binarySubdivide(aX, aA, aB, mX1, mX2) { + var currentX, currentT, i = 0; + do { + currentT = aA + (aB - aA) / 2; + currentX = calcBezier(currentT, mX1, mX2) - aX; + if (currentX > 0) { + aB = currentT; + } else { + aA = currentT; + } + } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS); + return currentT; + } + function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) { + for (var i = 0;i < NEWTON_ITERATIONS; ++i) { + var currentSlope = getSlope(aGuessT, mX1, mX2); + if (currentSlope === 0) + return aGuessT; + var currentX = calcBezier(aGuessT, mX1, mX2) - aX; + aGuessT -= currentX / currentSlope; + } + return aGuessT; + } + function BezierEasing(points) { + this._p = points; + this._mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize); + this._precomputed = false; + this.get = this.get.bind(this); + } + BezierEasing.prototype = { + get: function(x2) { + var mX1 = this._p[0], mY1 = this._p[1], mX2 = this._p[2], mY2 = this._p[3]; + if (!this._precomputed) + this._precompute(); + if (mX1 === mY1 && mX2 === mY2) + return x2; + if (x2 === 0) + return 0; + if (x2 === 1) + return 1; + return calcBezier(this._getTForX(x2), mY1, mY2); + }, + _precompute: function() { + var mX1 = this._p[0], mY1 = this._p[1], mX2 = this._p[2], mY2 = this._p[3]; + this._precomputed = true; + if (mX1 !== mY1 || mX2 !== mY2) { + this._calcSampleValues(); + } + }, + _calcSampleValues: function() { + var mX1 = this._p[0], mX2 = this._p[2]; + for (var i = 0;i < kSplineTableSize; ++i) { + this._mSampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2); + } + }, + _getTForX: function(aX) { + var mX1 = this._p[0], mX2 = this._p[2], mSampleValues = this._mSampleValues; + var intervalStart = 0; + var currentSample = 1; + var lastSample = kSplineTableSize - 1; + for (;currentSample !== lastSample && mSampleValues[currentSample] <= aX; ++currentSample) { + intervalStart += kSampleStepSize; + } + --currentSample; + var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample + 1] - mSampleValues[currentSample]); + var guessForT = intervalStart + dist * kSampleStepSize; + var initialSlope = getSlope(guessForT, mX1, mX2); + if (initialSlope >= NEWTON_MIN_SLOPE) { + return newtonRaphsonIterate(aX, guessForT, mX1, mX2); + } + if (initialSlope === 0) { + return guessForT; + } + return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2); + } + }; + return ob2; + }(); + const pooling = function() { + function double(arr) { + return arr.concat(createSizedArray(arr.length)); + } + return { + double + }; + }(); + const poolFactory = function() { + return function(initialLength, _create, _release) { + var _length = 0; + var _maxLength = initialLength; + var pool = createSizedArray(_maxLength); + var ob2 = { + newElement, + release + }; + function newElement() { + var element; + if (_length) { + _length -= 1; + element = pool[_length]; + } else { + element = _create(); + } + return element; + } + function release(element) { + if (_length === _maxLength) { + pool = pooling.double(pool); + _maxLength *= 2; + } + if (_release) { + _release(element); + } + pool[_length] = element; + _length += 1; + } + return ob2; + }; + }(); + const bezierLengthPool = function() { + function create() { + return { + addedLength: 0, + percents: createTypedArray("float32", getDefaultCurveSegments()), + lengths: createTypedArray("float32", getDefaultCurveSegments()) + }; + } + return poolFactory(8, create); + }(); + const segmentsLengthPool = function() { + function create() { + return { + lengths: [], + totalLength: 0 + }; + } + function release(element) { + var i; + var len = element.lengths.length; + for (i = 0;i < len; i += 1) { + bezierLengthPool.release(element.lengths[i]); + } + element.lengths.length = 0; + } + return poolFactory(8, create, release); + }(); + const bez = bezFunction(); + const PropertyFactory = function() { + var initFrame = initialDefaultFrame; + var mathAbs = Math.abs; + function interpolateValue(frameNum, caching) { + var offsetTime = this.offsetTime; + var newValue; + if (this.propType === "multidimensional") { + newValue = createTypedArray("float32", this.pv.length); + } + var iterationIndex = caching.lastIndex; + var i = iterationIndex; + var len = this.keyframes.length - 1; + var flag = true; + var keyData; + var nextKeyData; + var keyframeMetadata; + while (flag) { + keyData = this.keyframes[i]; + nextKeyData = this.keyframes[i + 1]; + if (i === len - 1 && frameNum >= nextKeyData.t - offsetTime) { + if (keyData.h) { + keyData = nextKeyData; + } + iterationIndex = 0; + break; + } + if (nextKeyData.t - offsetTime > frameNum) { + iterationIndex = i; + break; + } + if (i < len - 1) { + i += 1; + } else { + iterationIndex = 0; + flag = false; + } + } + keyframeMetadata = this.keyframesMetadata[i] || {}; + var k2; + var kLen; + var perc; + var jLen; + var j2; + var fnc; + var nextKeyTime = nextKeyData.t - offsetTime; + var keyTime = keyData.t - offsetTime; + var endValue; + if (keyData.to) { + if (!keyframeMetadata.bezierData) { + keyframeMetadata.bezierData = bez.buildBezierData(keyData.s, nextKeyData.s || keyData.e, keyData.to, keyData.ti); + } + var bezierData = keyframeMetadata.bezierData; + if (frameNum >= nextKeyTime || frameNum < keyTime) { + var ind = frameNum >= nextKeyTime ? bezierData.points.length - 1 : 0; + kLen = bezierData.points[ind].point.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + newValue[k2] = bezierData.points[ind].point[k2]; + } + } else { + if (keyframeMetadata.__fnct) { + fnc = keyframeMetadata.__fnct; + } else { + fnc = BezierFactory.getBezierEasing(keyData.o.x, keyData.o.y, keyData.i.x, keyData.i.y, keyData.n).get; + keyframeMetadata.__fnct = fnc; + } + perc = fnc((frameNum - keyTime) / (nextKeyTime - keyTime)); + var distanceInLine = bezierData.segmentLength * perc; + var segmentPerc; + var addedLength = caching.lastFrame < frameNum && caching._lastKeyframeIndex === i ? caching._lastAddedLength : 0; + j2 = caching.lastFrame < frameNum && caching._lastKeyframeIndex === i ? caching._lastPoint : 0; + flag = true; + jLen = bezierData.points.length; + while (flag) { + addedLength += bezierData.points[j2].partialLength; + if (distanceInLine === 0 || perc === 0 || j2 === bezierData.points.length - 1) { + kLen = bezierData.points[j2].point.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + newValue[k2] = bezierData.points[j2].point[k2]; + } + break; + } else if (distanceInLine >= addedLength && distanceInLine < addedLength + bezierData.points[j2 + 1].partialLength) { + segmentPerc = (distanceInLine - addedLength) / bezierData.points[j2 + 1].partialLength; + kLen = bezierData.points[j2].point.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + newValue[k2] = bezierData.points[j2].point[k2] + (bezierData.points[j2 + 1].point[k2] - bezierData.points[j2].point[k2]) * segmentPerc; + } + break; + } + if (j2 < jLen - 1) { + j2 += 1; + } else { + flag = false; + } + } + caching._lastPoint = j2; + caching._lastAddedLength = addedLength - bezierData.points[j2].partialLength; + caching._lastKeyframeIndex = i; + } + } else { + var outX; + var outY; + var inX; + var inY; + var keyValue; + len = keyData.s.length; + endValue = nextKeyData.s || keyData.e; + if (this.sh && keyData.h !== 1) { + if (frameNum >= nextKeyTime) { + newValue[0] = endValue[0]; + newValue[1] = endValue[1]; + newValue[2] = endValue[2]; + } else if (frameNum <= keyTime) { + newValue[0] = keyData.s[0]; + newValue[1] = keyData.s[1]; + newValue[2] = keyData.s[2]; + } else { + var quatStart = createQuaternion(keyData.s); + var quatEnd = createQuaternion(endValue); + var time2 = (frameNum - keyTime) / (nextKeyTime - keyTime); + quaternionToEuler(newValue, slerp(quatStart, quatEnd, time2)); + } + } else { + for (i = 0;i < len; i += 1) { + if (keyData.h !== 1) { + if (frameNum >= nextKeyTime) { + perc = 1; + } else if (frameNum < keyTime) { + perc = 0; + } else { + if (keyData.o.x.constructor === Array) { + if (!keyframeMetadata.__fnct) { + keyframeMetadata.__fnct = []; + } + if (!keyframeMetadata.__fnct[i]) { + outX = keyData.o.x[i] === undefined ? keyData.o.x[0] : keyData.o.x[i]; + outY = keyData.o.y[i] === undefined ? keyData.o.y[0] : keyData.o.y[i]; + inX = keyData.i.x[i] === undefined ? keyData.i.x[0] : keyData.i.x[i]; + inY = keyData.i.y[i] === undefined ? keyData.i.y[0] : keyData.i.y[i]; + fnc = BezierFactory.getBezierEasing(outX, outY, inX, inY).get; + keyframeMetadata.__fnct[i] = fnc; + } else { + fnc = keyframeMetadata.__fnct[i]; + } + } else if (!keyframeMetadata.__fnct) { + outX = keyData.o.x; + outY = keyData.o.y; + inX = keyData.i.x; + inY = keyData.i.y; + fnc = BezierFactory.getBezierEasing(outX, outY, inX, inY).get; + keyData.keyframeMetadata = fnc; + } else { + fnc = keyframeMetadata.__fnct; + } + perc = fnc((frameNum - keyTime) / (nextKeyTime - keyTime)); + } + } + endValue = nextKeyData.s || keyData.e; + keyValue = keyData.h === 1 ? keyData.s[i] : keyData.s[i] + (endValue[i] - keyData.s[i]) * perc; + if (this.propType === "multidimensional") { + newValue[i] = keyValue; + } else { + newValue = keyValue; + } + } + } + } + caching.lastIndex = iterationIndex; + return newValue; + } + function slerp(a, b, t2) { + var out = []; + var ax = a[0]; + var ay = a[1]; + var az = a[2]; + var aw = a[3]; + var bx = b[0]; + var by = b[1]; + var bz = b[2]; + var bw = b[3]; + var omega; + var cosom; + var sinom; + var scale0; + var scale1; + cosom = ax * bx + ay * by + az * bz + aw * bw; + if (cosom < 0) { + cosom = -cosom; + bx = -bx; + by = -by; + bz = -bz; + bw = -bw; + } + if (1 - cosom > 0.000001) { + omega = Math.acos(cosom); + sinom = Math.sin(omega); + scale0 = Math.sin((1 - t2) * omega) / sinom; + scale1 = Math.sin(t2 * omega) / sinom; + } else { + scale0 = 1 - t2; + scale1 = t2; + } + out[0] = scale0 * ax + scale1 * bx; + out[1] = scale0 * ay + scale1 * by; + out[2] = scale0 * az + scale1 * bz; + out[3] = scale0 * aw + scale1 * bw; + return out; + } + function quaternionToEuler(out, quat) { + var qx = quat[0]; + var qy = quat[1]; + var qz = quat[2]; + var qw = quat[3]; + var heading = Math.atan2(2 * qy * qw - 2 * qx * qz, 1 - 2 * qy * qy - 2 * qz * qz); + var attitude = Math.asin(2 * qx * qy + 2 * qz * qw); + var bank = Math.atan2(2 * qx * qw - 2 * qy * qz, 1 - 2 * qx * qx - 2 * qz * qz); + out[0] = heading / degToRads; + out[1] = attitude / degToRads; + out[2] = bank / degToRads; + } + function createQuaternion(values2) { + var heading = values2[0] * degToRads; + var attitude = values2[1] * degToRads; + var bank = values2[2] * degToRads; + var c1 = Math.cos(heading / 2); + var c2 = Math.cos(attitude / 2); + var c3 = Math.cos(bank / 2); + var s1 = Math.sin(heading / 2); + var s2 = Math.sin(attitude / 2); + var s3 = Math.sin(bank / 2); + var w = c1 * c2 * c3 - s1 * s2 * s3; + var x2 = s1 * s2 * c3 + c1 * c2 * s3; + var y = s1 * c2 * c3 + c1 * s2 * s3; + var z = c1 * s2 * c3 - s1 * c2 * s3; + return [x2, y, z, w]; + } + function getValueAtCurrentTime() { + var frameNum = this.comp.renderedFrame - this.offsetTime; + var initTime = this.keyframes[0].t - this.offsetTime; + var endTime = this.keyframes[this.keyframes.length - 1].t - this.offsetTime; + if (!(frameNum === this._caching.lastFrame || this._caching.lastFrame !== initFrame && (this._caching.lastFrame >= endTime && frameNum >= endTime || this._caching.lastFrame < initTime && frameNum < initTime))) { + if (this._caching.lastFrame >= frameNum) { + this._caching._lastKeyframeIndex = -1; + this._caching.lastIndex = 0; + } + var renderResult = this.interpolateValue(frameNum, this._caching); + this.pv = renderResult; + } + this._caching.lastFrame = frameNum; + return this.pv; + } + function setVValue(val2) { + var multipliedValue; + if (this.propType === "unidimensional") { + multipliedValue = val2 * this.mult; + if (mathAbs(this.v - multipliedValue) > 0.00001) { + this.v = multipliedValue; + this._mdf = true; + } + } else { + var i = 0; + var len = this.v.length; + while (i < len) { + multipliedValue = val2[i] * this.mult; + if (mathAbs(this.v[i] - multipliedValue) > 0.00001) { + this.v[i] = multipliedValue; + this._mdf = true; + } + i += 1; + } + } + } + function processEffectsSequence() { + if (this.elem.globalData.frameId === this.frameId || !this.effectsSequence.length) { + return; + } + if (this.lock) { + this.setVValue(this.pv); + return; + } + this.lock = true; + this._mdf = this._isFirstFrame; + var i; + var len = this.effectsSequence.length; + var finalValue = this.kf ? this.pv : this.data.k; + for (i = 0;i < len; i += 1) { + finalValue = this.effectsSequence[i](finalValue); + } + this.setVValue(finalValue); + this._isFirstFrame = false; + this.lock = false; + this.frameId = this.elem.globalData.frameId; + } + function addEffect(effectFunction) { + this.effectsSequence.push(effectFunction); + this.container.addDynamicProperty(this); + } + function ValueProperty(elem2, data2, mult, container) { + this.propType = "unidimensional"; + this.mult = mult || 1; + this.data = data2; + this.v = mult ? data2.k * mult : data2.k; + this.pv = data2.k; + this._mdf = false; + this.elem = elem2; + this.container = container; + this.comp = elem2.comp; + this.k = false; + this.kf = false; + this.vel = 0; + this.effectsSequence = []; + this._isFirstFrame = true; + this.getValue = processEffectsSequence; + this.setVValue = setVValue; + this.addEffect = addEffect; + } + function MultiDimensionalProperty(elem2, data2, mult, container) { + this.propType = "multidimensional"; + this.mult = mult || 1; + this.data = data2; + this._mdf = false; + this.elem = elem2; + this.container = container; + this.comp = elem2.comp; + this.k = false; + this.kf = false; + this.frameId = -1; + var i; + var len = data2.k.length; + this.v = createTypedArray("float32", len); + this.pv = createTypedArray("float32", len); + this.vel = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + this.v[i] = data2.k[i] * this.mult; + this.pv[i] = data2.k[i]; + } + this._isFirstFrame = true; + this.effectsSequence = []; + this.getValue = processEffectsSequence; + this.setVValue = setVValue; + this.addEffect = addEffect; + } + function KeyframedValueProperty(elem2, data2, mult, container) { + this.propType = "unidimensional"; + this.keyframes = data2.k; + this.keyframesMetadata = []; + this.offsetTime = elem2.data.st; + this.frameId = -1; + this._caching = { + lastFrame: initFrame, + lastIndex: 0, + value: 0, + _lastKeyframeIndex: -1 + }; + this.k = true; + this.kf = true; + this.data = data2; + this.mult = mult || 1; + this.elem = elem2; + this.container = container; + this.comp = elem2.comp; + this.v = initFrame; + this.pv = initFrame; + this._isFirstFrame = true; + this.getValue = processEffectsSequence; + this.setVValue = setVValue; + this.interpolateValue = interpolateValue; + this.effectsSequence = [getValueAtCurrentTime.bind(this)]; + this.addEffect = addEffect; + } + function KeyframedMultidimensionalProperty(elem2, data2, mult, container) { + this.propType = "multidimensional"; + var i; + var len = data2.k.length; + var s; + var e; + var to; + var ti; + for (i = 0;i < len - 1; i += 1) { + if (data2.k[i].to && data2.k[i].s && data2.k[i + 1] && data2.k[i + 1].s) { + s = data2.k[i].s; + e = data2.k[i + 1].s; + to = data2.k[i].to; + ti = data2.k[i].ti; + if (s.length === 2 && !(s[0] === e[0] && s[1] === e[1]) && bez.pointOnLine2D(s[0], s[1], e[0], e[1], s[0] + to[0], s[1] + to[1]) && bez.pointOnLine2D(s[0], s[1], e[0], e[1], e[0] + ti[0], e[1] + ti[1]) || s.length === 3 && !(s[0] === e[0] && s[1] === e[1] && s[2] === e[2]) && bez.pointOnLine3D(s[0], s[1], s[2], e[0], e[1], e[2], s[0] + to[0], s[1] + to[1], s[2] + to[2]) && bez.pointOnLine3D(s[0], s[1], s[2], e[0], e[1], e[2], e[0] + ti[0], e[1] + ti[1], e[2] + ti[2])) { + data2.k[i].to = null; + data2.k[i].ti = null; + } + if (s[0] === e[0] && s[1] === e[1] && to[0] === 0 && to[1] === 0 && ti[0] === 0 && ti[1] === 0) { + if (s.length === 2 || s[2] === e[2] && to[2] === 0 && ti[2] === 0) { + data2.k[i].to = null; + data2.k[i].ti = null; + } + } + } + } + this.effectsSequence = [getValueAtCurrentTime.bind(this)]; + this.data = data2; + this.keyframes = data2.k; + this.keyframesMetadata = []; + this.offsetTime = elem2.data.st; + this.k = true; + this.kf = true; + this._isFirstFrame = true; + this.mult = mult || 1; + this.elem = elem2; + this.container = container; + this.comp = elem2.comp; + this.getValue = processEffectsSequence; + this.setVValue = setVValue; + this.interpolateValue = interpolateValue; + this.frameId = -1; + var arrLen = data2.k[0].s.length; + this.v = createTypedArray("float32", arrLen); + this.pv = createTypedArray("float32", arrLen); + for (i = 0;i < arrLen; i += 1) { + this.v[i] = initFrame; + this.pv[i] = initFrame; + } + this._caching = { lastFrame: initFrame, lastIndex: 0, value: createTypedArray("float32", arrLen) }; + this.addEffect = addEffect; + } + function getProp(elem2, data2, type, mult, container) { + var p; + if (!data2.k.length) { + p = new ValueProperty(elem2, data2, mult, container); + } else if (typeof data2.k[0] === "number") { + p = new MultiDimensionalProperty(elem2, data2, mult, container); + } else { + switch (type) { + case 0: + p = new KeyframedValueProperty(elem2, data2, mult, container); + break; + case 1: + p = new KeyframedMultidimensionalProperty(elem2, data2, mult, container); + break; + default: + break; + } + } + if (p.effectsSequence.length) { + container.addDynamicProperty(p); + } + return p; + } + var ob2 = { + getProp + }; + return ob2; + }(); + DynamicPropertyContainer.prototype = { + addDynamicProperty: function(prop) { + if (this.dynamicProperties.indexOf(prop) === -1) { + this.dynamicProperties.push(prop); + this.container.addDynamicProperty(this); + this._isAnimated = true; + } + }, + iterateDynamicProperties: function() { + this._mdf = false; + var i; + var len = this.dynamicProperties.length; + for (i = 0;i < len; i += 1) { + this.dynamicProperties[i].getValue(); + if (this.dynamicProperties[i]._mdf) { + this._mdf = true; + } + } + }, + initDynamicPropertyContainer: function(container) { + this.container = container; + this.dynamicProperties = []; + this._mdf = false; + this._isAnimated = false; + } + }; + const pointPool = function() { + function create() { + return createTypedArray("float32", 2); + } + return poolFactory(8, create); + }(); + ShapePath.prototype.setPathData = function(closed, len) { + this.c = closed; + this.setLength(len); + var i = 0; + while (i < len) { + this.v[i] = pointPool.newElement(); + this.o[i] = pointPool.newElement(); + this.i[i] = pointPool.newElement(); + i += 1; + } + }; + ShapePath.prototype.setLength = function(len) { + while (this._maxLength < len) { + this.doubleArrayLength(); + } + this._length = len; + }; + ShapePath.prototype.doubleArrayLength = function() { + this.v = this.v.concat(createSizedArray(this._maxLength)); + this.i = this.i.concat(createSizedArray(this._maxLength)); + this.o = this.o.concat(createSizedArray(this._maxLength)); + this._maxLength *= 2; + }; + ShapePath.prototype.setXYAt = function(x2, y, type, pos, replace) { + var arr; + this._length = Math.max(this._length, pos + 1); + if (this._length >= this._maxLength) { + this.doubleArrayLength(); + } + switch (type) { + case "v": + arr = this.v; + break; + case "i": + arr = this.i; + break; + case "o": + arr = this.o; + break; + default: + arr = []; + break; + } + if (!arr[pos] || arr[pos] && !replace) { + arr[pos] = pointPool.newElement(); + } + arr[pos][0] = x2; + arr[pos][1] = y; + }; + ShapePath.prototype.setTripleAt = function(vX, vY, oX, oY, iX, iY, pos, replace) { + this.setXYAt(vX, vY, "v", pos, replace); + this.setXYAt(oX, oY, "o", pos, replace); + this.setXYAt(iX, iY, "i", pos, replace); + }; + ShapePath.prototype.reverse = function() { + var newPath = new ShapePath; + newPath.setPathData(this.c, this._length); + var vertices = this.v; + var outPoints = this.o; + var inPoints = this.i; + var init = 0; + if (this.c) { + newPath.setTripleAt(vertices[0][0], vertices[0][1], inPoints[0][0], inPoints[0][1], outPoints[0][0], outPoints[0][1], 0, false); + init = 1; + } + var cnt = this._length - 1; + var len = this._length; + var i; + for (i = init;i < len; i += 1) { + newPath.setTripleAt(vertices[cnt][0], vertices[cnt][1], inPoints[cnt][0], inPoints[cnt][1], outPoints[cnt][0], outPoints[cnt][1], i, false); + cnt -= 1; + } + return newPath; + }; + const shapePool = function() { + function create() { + return new ShapePath; + } + function release(shapePath) { + var len = shapePath._length; + var i; + for (i = 0;i < len; i += 1) { + pointPool.release(shapePath.v[i]); + pointPool.release(shapePath.i[i]); + pointPool.release(shapePath.o[i]); + shapePath.v[i] = null; + shapePath.i[i] = null; + shapePath.o[i] = null; + } + shapePath._length = 0; + shapePath.c = false; + } + function clone(shape) { + var cloned = factory.newElement(); + var i; + var len = shape._length === undefined ? shape.v.length : shape._length; + cloned.setLength(len); + cloned.c = shape.c; + for (i = 0;i < len; i += 1) { + cloned.setTripleAt(shape.v[i][0], shape.v[i][1], shape.o[i][0], shape.o[i][1], shape.i[i][0], shape.i[i][1], i); + } + return cloned; + } + var factory = poolFactory(4, create, release); + factory.clone = clone; + return factory; + }(); + ShapeCollection.prototype.addShape = function(shapeData) { + if (this._length === this._maxLength) { + this.shapes = this.shapes.concat(createSizedArray(this._maxLength)); + this._maxLength *= 2; + } + this.shapes[this._length] = shapeData; + this._length += 1; + }; + ShapeCollection.prototype.releaseShapes = function() { + var i; + for (i = 0;i < this._length; i += 1) { + shapePool.release(this.shapes[i]); + } + this._length = 0; + }; + const shapeCollectionPool = function() { + var ob2 = { + newShapeCollection, + release + }; + var _length = 0; + var _maxLength = 4; + var pool = createSizedArray(_maxLength); + function newShapeCollection() { + var shapeCollection; + if (_length) { + _length -= 1; + shapeCollection = pool[_length]; + } else { + shapeCollection = new ShapeCollection; + } + return shapeCollection; + } + function release(shapeCollection) { + var i; + var len = shapeCollection._length; + for (i = 0;i < len; i += 1) { + shapePool.release(shapeCollection.shapes[i]); + } + shapeCollection._length = 0; + if (_length === _maxLength) { + pool = pooling.double(pool); + _maxLength *= 2; + } + pool[_length] = shapeCollection; + _length += 1; + } + return ob2; + }(); + const ShapePropertyFactory = function() { + var initFrame = -999999; + function interpolateShape(frameNum, previousValue, caching) { + var iterationIndex = caching.lastIndex; + var keyPropS; + var keyPropE; + var isHold; + var j2; + var k2; + var jLen; + var kLen; + var perc; + var vertexValue; + var kf = this.keyframes; + if (frameNum < kf[0].t - this.offsetTime) { + keyPropS = kf[0].s[0]; + isHold = true; + iterationIndex = 0; + } else if (frameNum >= kf[kf.length - 1].t - this.offsetTime) { + keyPropS = kf[kf.length - 1].s ? kf[kf.length - 1].s[0] : kf[kf.length - 2].e[0]; + isHold = true; + } else { + var i = iterationIndex; + var len = kf.length - 1; + var flag = true; + var keyData; + var nextKeyData; + var keyframeMetadata; + while (flag) { + keyData = kf[i]; + nextKeyData = kf[i + 1]; + if (nextKeyData.t - this.offsetTime > frameNum) { + break; + } + if (i < len - 1) { + i += 1; + } else { + flag = false; + } + } + keyframeMetadata = this.keyframesMetadata[i] || {}; + isHold = keyData.h === 1; + iterationIndex = i; + if (!isHold) { + if (frameNum >= nextKeyData.t - this.offsetTime) { + perc = 1; + } else if (frameNum < keyData.t - this.offsetTime) { + perc = 0; + } else { + var fnc; + if (keyframeMetadata.__fnct) { + fnc = keyframeMetadata.__fnct; + } else { + fnc = BezierFactory.getBezierEasing(keyData.o.x, keyData.o.y, keyData.i.x, keyData.i.y).get; + keyframeMetadata.__fnct = fnc; + } + perc = fnc((frameNum - (keyData.t - this.offsetTime)) / (nextKeyData.t - this.offsetTime - (keyData.t - this.offsetTime))); + } + keyPropE = nextKeyData.s ? nextKeyData.s[0] : keyData.e[0]; + } + keyPropS = keyData.s[0]; + } + jLen = previousValue._length; + kLen = keyPropS.i[0].length; + caching.lastIndex = iterationIndex; + for (j2 = 0;j2 < jLen; j2 += 1) { + for (k2 = 0;k2 < kLen; k2 += 1) { + vertexValue = isHold ? keyPropS.i[j2][k2] : keyPropS.i[j2][k2] + (keyPropE.i[j2][k2] - keyPropS.i[j2][k2]) * perc; + previousValue.i[j2][k2] = vertexValue; + vertexValue = isHold ? keyPropS.o[j2][k2] : keyPropS.o[j2][k2] + (keyPropE.o[j2][k2] - keyPropS.o[j2][k2]) * perc; + previousValue.o[j2][k2] = vertexValue; + vertexValue = isHold ? keyPropS.v[j2][k2] : keyPropS.v[j2][k2] + (keyPropE.v[j2][k2] - keyPropS.v[j2][k2]) * perc; + previousValue.v[j2][k2] = vertexValue; + } + } + } + function interpolateShapeCurrentTime() { + var frameNum = this.comp.renderedFrame - this.offsetTime; + var initTime = this.keyframes[0].t - this.offsetTime; + var endTime = this.keyframes[this.keyframes.length - 1].t - this.offsetTime; + var lastFrame = this._caching.lastFrame; + if (!(lastFrame !== initFrame && (lastFrame < initTime && frameNum < initTime || lastFrame > endTime && frameNum > endTime))) { + this._caching.lastIndex = lastFrame < frameNum ? this._caching.lastIndex : 0; + this.interpolateShape(frameNum, this.pv, this._caching); + } + this._caching.lastFrame = frameNum; + return this.pv; + } + function resetShape() { + this.paths = this.localShapeCollection; + } + function shapesEqual(shape1, shape2) { + if (shape1._length !== shape2._length || shape1.c !== shape2.c) { + return false; + } + var i; + var len = shape1._length; + for (i = 0;i < len; i += 1) { + if (shape1.v[i][0] !== shape2.v[i][0] || shape1.v[i][1] !== shape2.v[i][1] || shape1.o[i][0] !== shape2.o[i][0] || shape1.o[i][1] !== shape2.o[i][1] || shape1.i[i][0] !== shape2.i[i][0] || shape1.i[i][1] !== shape2.i[i][1]) { + return false; + } + } + return true; + } + function setVValue(newPath) { + if (!shapesEqual(this.v, newPath)) { + this.v = shapePool.clone(newPath); + this.localShapeCollection.releaseShapes(); + this.localShapeCollection.addShape(this.v); + this._mdf = true; + this.paths = this.localShapeCollection; + } + } + function processEffectsSequence() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + if (!this.effectsSequence.length) { + this._mdf = false; + return; + } + if (this.lock) { + this.setVValue(this.pv); + return; + } + this.lock = true; + this._mdf = false; + var finalValue; + if (this.kf) { + finalValue = this.pv; + } else if (this.data.ks) { + finalValue = this.data.ks.k; + } else { + finalValue = this.data.pt.k; + } + var i; + var len = this.effectsSequence.length; + for (i = 0;i < len; i += 1) { + finalValue = this.effectsSequence[i](finalValue); + } + this.setVValue(finalValue); + this.lock = false; + this.frameId = this.elem.globalData.frameId; + } + function ShapeProperty(elem2, data2, type) { + this.propType = "shape"; + this.comp = elem2.comp; + this.container = elem2; + this.elem = elem2; + this.data = data2; + this.k = false; + this.kf = false; + this._mdf = false; + var pathData = type === 3 ? data2.pt.k : data2.ks.k; + this.v = shapePool.clone(pathData); + this.pv = shapePool.clone(this.v); + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.paths = this.localShapeCollection; + this.paths.addShape(this.v); + this.reset = resetShape; + this.effectsSequence = []; + } + function addEffect(effectFunction) { + this.effectsSequence.push(effectFunction); + this.container.addDynamicProperty(this); + } + ShapeProperty.prototype.interpolateShape = interpolateShape; + ShapeProperty.prototype.getValue = processEffectsSequence; + ShapeProperty.prototype.setVValue = setVValue; + ShapeProperty.prototype.addEffect = addEffect; + function KeyframedShapeProperty(elem2, data2, type) { + this.propType = "shape"; + this.comp = elem2.comp; + this.elem = elem2; + this.container = elem2; + this.offsetTime = elem2.data.st; + this.keyframes = type === 3 ? data2.pt.k : data2.ks.k; + this.keyframesMetadata = []; + this.k = true; + this.kf = true; + var len = this.keyframes[0].s[0].i.length; + this.v = shapePool.newElement(); + this.v.setPathData(this.keyframes[0].s[0].c, len); + this.pv = shapePool.clone(this.v); + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.paths = this.localShapeCollection; + this.paths.addShape(this.v); + this.lastFrame = initFrame; + this.reset = resetShape; + this._caching = { lastFrame: initFrame, lastIndex: 0 }; + this.effectsSequence = [interpolateShapeCurrentTime.bind(this)]; + } + KeyframedShapeProperty.prototype.getValue = processEffectsSequence; + KeyframedShapeProperty.prototype.interpolateShape = interpolateShape; + KeyframedShapeProperty.prototype.setVValue = setVValue; + KeyframedShapeProperty.prototype.addEffect = addEffect; + var EllShapeProperty = function() { + var cPoint = roundCorner; + function EllShapePropertyFactory(elem2, data2) { + this.v = shapePool.newElement(); + this.v.setPathData(true, 4); + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.paths = this.localShapeCollection; + this.localShapeCollection.addShape(this.v); + this.d = data2.d; + this.elem = elem2; + this.comp = elem2.comp; + this.frameId = -1; + this.initDynamicPropertyContainer(elem2); + this.p = PropertyFactory.getProp(elem2, data2.p, 1, 0, this); + this.s = PropertyFactory.getProp(elem2, data2.s, 1, 0, this); + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.k = false; + this.convertEllToPath(); + } + } + EllShapePropertyFactory.prototype = { + reset: resetShape, + getValue: function() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + if (this._mdf) { + this.convertEllToPath(); + } + }, + convertEllToPath: function() { + var p0 = this.p.v[0]; + var p1 = this.p.v[1]; + var s0 = this.s.v[0] / 2; + var s1 = this.s.v[1] / 2; + var _cw = this.d !== 3; + var _v4 = this.v; + _v4.v[0][0] = p0; + _v4.v[0][1] = p1 - s1; + _v4.v[1][0] = _cw ? p0 + s0 : p0 - s0; + _v4.v[1][1] = p1; + _v4.v[2][0] = p0; + _v4.v[2][1] = p1 + s1; + _v4.v[3][0] = _cw ? p0 - s0 : p0 + s0; + _v4.v[3][1] = p1; + _v4.i[0][0] = _cw ? p0 - s0 * cPoint : p0 + s0 * cPoint; + _v4.i[0][1] = p1 - s1; + _v4.i[1][0] = _cw ? p0 + s0 : p0 - s0; + _v4.i[1][1] = p1 - s1 * cPoint; + _v4.i[2][0] = _cw ? p0 + s0 * cPoint : p0 - s0 * cPoint; + _v4.i[2][1] = p1 + s1; + _v4.i[3][0] = _cw ? p0 - s0 : p0 + s0; + _v4.i[3][1] = p1 + s1 * cPoint; + _v4.o[0][0] = _cw ? p0 + s0 * cPoint : p0 - s0 * cPoint; + _v4.o[0][1] = p1 - s1; + _v4.o[1][0] = _cw ? p0 + s0 : p0 - s0; + _v4.o[1][1] = p1 + s1 * cPoint; + _v4.o[2][0] = _cw ? p0 - s0 * cPoint : p0 + s0 * cPoint; + _v4.o[2][1] = p1 + s1; + _v4.o[3][0] = _cw ? p0 - s0 : p0 + s0; + _v4.o[3][1] = p1 - s1 * cPoint; + } + }; + extendPrototype([DynamicPropertyContainer], EllShapePropertyFactory); + return EllShapePropertyFactory; + }(); + var StarShapeProperty = function() { + function StarShapePropertyFactory(elem2, data2) { + this.v = shapePool.newElement(); + this.v.setPathData(true, 0); + this.elem = elem2; + this.comp = elem2.comp; + this.data = data2; + this.frameId = -1; + this.d = data2.d; + this.initDynamicPropertyContainer(elem2); + if (data2.sy === 1) { + this.ir = PropertyFactory.getProp(elem2, data2.ir, 0, 0, this); + this.is = PropertyFactory.getProp(elem2, data2.is, 0, 0.01, this); + this.convertToPath = this.convertStarToPath; + } else { + this.convertToPath = this.convertPolygonToPath; + } + this.pt = PropertyFactory.getProp(elem2, data2.pt, 0, 0, this); + this.p = PropertyFactory.getProp(elem2, data2.p, 1, 0, this); + this.r = PropertyFactory.getProp(elem2, data2.r, 0, degToRads, this); + this.or = PropertyFactory.getProp(elem2, data2.or, 0, 0, this); + this.os = PropertyFactory.getProp(elem2, data2.os, 0, 0.01, this); + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.localShapeCollection.addShape(this.v); + this.paths = this.localShapeCollection; + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.k = false; + this.convertToPath(); + } + } + StarShapePropertyFactory.prototype = { + reset: resetShape, + getValue: function() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + if (this._mdf) { + this.convertToPath(); + } + }, + convertStarToPath: function() { + var numPts = Math.floor(this.pt.v) * 2; + var angle = Math.PI * 2 / numPts; + var longFlag = true; + var longRad = this.or.v; + var shortRad = this.ir.v; + var longRound = this.os.v; + var shortRound = this.is.v; + var longPerimSegment = 2 * Math.PI * longRad / (numPts * 2); + var shortPerimSegment = 2 * Math.PI * shortRad / (numPts * 2); + var i; + var rad; + var roundness; + var perimSegment; + var currentAng = -Math.PI / 2; + currentAng += this.r.v; + var dir = this.data.d === 3 ? -1 : 1; + this.v._length = 0; + for (i = 0;i < numPts; i += 1) { + rad = longFlag ? longRad : shortRad; + roundness = longFlag ? longRound : shortRound; + perimSegment = longFlag ? longPerimSegment : shortPerimSegment; + var x2 = rad * Math.cos(currentAng); + var y = rad * Math.sin(currentAng); + var ox = x2 === 0 && y === 0 ? 0 : y / Math.sqrt(x2 * x2 + y * y); + var oy = x2 === 0 && y === 0 ? 0 : -x2 / Math.sqrt(x2 * x2 + y * y); + x2 += +this.p.v[0]; + y += +this.p.v[1]; + this.v.setTripleAt(x2, y, x2 - ox * perimSegment * roundness * dir, y - oy * perimSegment * roundness * dir, x2 + ox * perimSegment * roundness * dir, y + oy * perimSegment * roundness * dir, i, true); + longFlag = !longFlag; + currentAng += angle * dir; + } + }, + convertPolygonToPath: function() { + var numPts = Math.floor(this.pt.v); + var angle = Math.PI * 2 / numPts; + var rad = this.or.v; + var roundness = this.os.v; + var perimSegment = 2 * Math.PI * rad / (numPts * 4); + var i; + var currentAng = -Math.PI * 0.5; + var dir = this.data.d === 3 ? -1 : 1; + currentAng += this.r.v; + this.v._length = 0; + for (i = 0;i < numPts; i += 1) { + var x2 = rad * Math.cos(currentAng); + var y = rad * Math.sin(currentAng); + var ox = x2 === 0 && y === 0 ? 0 : y / Math.sqrt(x2 * x2 + y * y); + var oy = x2 === 0 && y === 0 ? 0 : -x2 / Math.sqrt(x2 * x2 + y * y); + x2 += +this.p.v[0]; + y += +this.p.v[1]; + this.v.setTripleAt(x2, y, x2 - ox * perimSegment * roundness * dir, y - oy * perimSegment * roundness * dir, x2 + ox * perimSegment * roundness * dir, y + oy * perimSegment * roundness * dir, i, true); + currentAng += angle * dir; + } + this.paths.length = 0; + this.paths[0] = this.v; + } + }; + extendPrototype([DynamicPropertyContainer], StarShapePropertyFactory); + return StarShapePropertyFactory; + }(); + var RectShapeProperty = function() { + function RectShapePropertyFactory(elem2, data2) { + this.v = shapePool.newElement(); + this.v.c = true; + this.localShapeCollection = shapeCollectionPool.newShapeCollection(); + this.localShapeCollection.addShape(this.v); + this.paths = this.localShapeCollection; + this.elem = elem2; + this.comp = elem2.comp; + this.frameId = -1; + this.d = data2.d; + this.initDynamicPropertyContainer(elem2); + this.p = PropertyFactory.getProp(elem2, data2.p, 1, 0, this); + this.s = PropertyFactory.getProp(elem2, data2.s, 1, 0, this); + this.r = PropertyFactory.getProp(elem2, data2.r, 0, 0, this); + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.k = false; + this.convertRectToPath(); + } + } + RectShapePropertyFactory.prototype = { + convertRectToPath: function() { + var p0 = this.p.v[0]; + var p1 = this.p.v[1]; + var v0 = this.s.v[0] / 2; + var v1 = this.s.v[1] / 2; + var round = bmMin(v0, v1, this.r.v); + var cPoint = round * (1 - roundCorner); + this.v._length = 0; + if (this.d === 2 || this.d === 1) { + this.v.setTripleAt(p0 + v0, p1 - v1 + round, p0 + v0, p1 - v1 + round, p0 + v0, p1 - v1 + cPoint, 0, true); + this.v.setTripleAt(p0 + v0, p1 + v1 - round, p0 + v0, p1 + v1 - cPoint, p0 + v0, p1 + v1 - round, 1, true); + if (round !== 0) { + this.v.setTripleAt(p0 + v0 - round, p1 + v1, p0 + v0 - round, p1 + v1, p0 + v0 - cPoint, p1 + v1, 2, true); + this.v.setTripleAt(p0 - v0 + round, p1 + v1, p0 - v0 + cPoint, p1 + v1, p0 - v0 + round, p1 + v1, 3, true); + this.v.setTripleAt(p0 - v0, p1 + v1 - round, p0 - v0, p1 + v1 - round, p0 - v0, p1 + v1 - cPoint, 4, true); + this.v.setTripleAt(p0 - v0, p1 - v1 + round, p0 - v0, p1 - v1 + cPoint, p0 - v0, p1 - v1 + round, 5, true); + this.v.setTripleAt(p0 - v0 + round, p1 - v1, p0 - v0 + round, p1 - v1, p0 - v0 + cPoint, p1 - v1, 6, true); + this.v.setTripleAt(p0 + v0 - round, p1 - v1, p0 + v0 - cPoint, p1 - v1, p0 + v0 - round, p1 - v1, 7, true); + } else { + this.v.setTripleAt(p0 - v0, p1 + v1, p0 - v0 + cPoint, p1 + v1, p0 - v0, p1 + v1, 2); + this.v.setTripleAt(p0 - v0, p1 - v1, p0 - v0, p1 - v1 + cPoint, p0 - v0, p1 - v1, 3); + } + } else { + this.v.setTripleAt(p0 + v0, p1 - v1 + round, p0 + v0, p1 - v1 + cPoint, p0 + v0, p1 - v1 + round, 0, true); + if (round !== 0) { + this.v.setTripleAt(p0 + v0 - round, p1 - v1, p0 + v0 - round, p1 - v1, p0 + v0 - cPoint, p1 - v1, 1, true); + this.v.setTripleAt(p0 - v0 + round, p1 - v1, p0 - v0 + cPoint, p1 - v1, p0 - v0 + round, p1 - v1, 2, true); + this.v.setTripleAt(p0 - v0, p1 - v1 + round, p0 - v0, p1 - v1 + round, p0 - v0, p1 - v1 + cPoint, 3, true); + this.v.setTripleAt(p0 - v0, p1 + v1 - round, p0 - v0, p1 + v1 - cPoint, p0 - v0, p1 + v1 - round, 4, true); + this.v.setTripleAt(p0 - v0 + round, p1 + v1, p0 - v0 + round, p1 + v1, p0 - v0 + cPoint, p1 + v1, 5, true); + this.v.setTripleAt(p0 + v0 - round, p1 + v1, p0 + v0 - cPoint, p1 + v1, p0 + v0 - round, p1 + v1, 6, true); + this.v.setTripleAt(p0 + v0, p1 + v1 - round, p0 + v0, p1 + v1 - round, p0 + v0, p1 + v1 - cPoint, 7, true); + } else { + this.v.setTripleAt(p0 - v0, p1 - v1, p0 - v0 + cPoint, p1 - v1, p0 - v0, p1 - v1, 1, true); + this.v.setTripleAt(p0 - v0, p1 + v1, p0 - v0, p1 + v1 - cPoint, p0 - v0, p1 + v1, 2, true); + this.v.setTripleAt(p0 + v0, p1 + v1, p0 + v0 - cPoint, p1 + v1, p0 + v0, p1 + v1, 3, true); + } + } + }, + getValue: function() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + if (this._mdf) { + this.convertRectToPath(); + } + }, + reset: resetShape + }; + extendPrototype([DynamicPropertyContainer], RectShapePropertyFactory); + return RectShapePropertyFactory; + }(); + function getShapeProp(elem2, data2, type) { + var prop; + if (type === 3 || type === 4) { + var dataProp = type === 3 ? data2.pt : data2.ks; + var keys2 = dataProp.k; + if (keys2.length) { + prop = new KeyframedShapeProperty(elem2, data2, type); + } else { + prop = new ShapeProperty(elem2, data2, type); + } + } else if (type === 5) { + prop = new RectShapeProperty(elem2, data2); + } else if (type === 6) { + prop = new EllShapeProperty(elem2, data2); + } else if (type === 7) { + prop = new StarShapeProperty(elem2, data2); + } + if (prop.k) { + elem2.addDynamicProperty(prop); + } + return prop; + } + function getConstructorFunction() { + return ShapeProperty; + } + function getKeyframedConstructorFunction() { + return KeyframedShapeProperty; + } + var ob2 = {}; + ob2.getShapeProp = getShapeProp; + ob2.getConstructorFunction = getConstructorFunction; + ob2.getKeyframedConstructorFunction = getKeyframedConstructorFunction; + return ob2; + }(); + /*! + Transformation Matrix v2.0 + (c) Epistemex 2014-2015 + www.epistemex.com + By Ken Fyrstenberg + Contributions by leeoniya. + License: MIT, header required. + */ + const Matrix = function() { + var _cos = Math.cos; + var _sin = Math.sin; + var _tan = Math.tan; + var _rnd = Math.round; + function reset() { + this.props[0] = 1; + this.props[1] = 0; + this.props[2] = 0; + this.props[3] = 0; + this.props[4] = 0; + this.props[5] = 1; + this.props[6] = 0; + this.props[7] = 0; + this.props[8] = 0; + this.props[9] = 0; + this.props[10] = 1; + this.props[11] = 0; + this.props[12] = 0; + this.props[13] = 0; + this.props[14] = 0; + this.props[15] = 1; + return this; + } + function rotate(angle) { + if (angle === 0) { + return this; + } + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + } + function rotateX(angle) { + if (angle === 0) { + return this; + } + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(1, 0, 0, 0, 0, mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1); + } + function rotateY(angle) { + if (angle === 0) { + return this; + } + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(mCos, 0, mSin, 0, 0, 1, 0, 0, -mSin, 0, mCos, 0, 0, 0, 0, 1); + } + function rotateZ(angle) { + if (angle === 0) { + return this; + } + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + } + function shear(sx, sy) { + return this._t(1, sy, sx, 1, 0, 0); + } + function skew(ax, ay) { + return this.shear(_tan(ax), _tan(ay)); + } + function skewFromAxis(ax, angle) { + var mCos = _cos(angle); + var mSin = _sin(angle); + return this._t(mCos, mSin, 0, 0, -mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)._t(1, 0, 0, 0, _tan(ax), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)._t(mCos, -mSin, 0, 0, mSin, mCos, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); + } + function scale2(sx, sy, sz) { + if (!sz && sz !== 0) { + sz = 1; + } + if (sx === 1 && sy === 1 && sz === 1) { + return this; + } + return this._t(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, 0, 0, 0, 1); + } + function setTransform(a, b, c, d, e, f, g3, h, i, j2, k2, l2, m, n2, o, p) { + this.props[0] = a; + this.props[1] = b; + this.props[2] = c; + this.props[3] = d; + this.props[4] = e; + this.props[5] = f; + this.props[6] = g3; + this.props[7] = h; + this.props[8] = i; + this.props[9] = j2; + this.props[10] = k2; + this.props[11] = l2; + this.props[12] = m; + this.props[13] = n2; + this.props[14] = o; + this.props[15] = p; + return this; + } + function translate(tx, ty, tz) { + tz = tz || 0; + if (tx !== 0 || ty !== 0 || tz !== 0) { + return this._t(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, tx, ty, tz, 1); + } + return this; + } + function transform2(a2, b2, c2, d2, e2, f2, g22, h2, i2, j2, k2, l2, m2, n2, o2, p2) { + var _p = this.props; + if (a2 === 1 && b2 === 0 && c2 === 0 && d2 === 0 && e2 === 0 && f2 === 1 && g22 === 0 && h2 === 0 && i2 === 0 && j2 === 0 && k2 === 1 && l2 === 0) { + _p[12] = _p[12] * a2 + _p[15] * m2; + _p[13] = _p[13] * f2 + _p[15] * n2; + _p[14] = _p[14] * k2 + _p[15] * o2; + _p[15] *= p2; + this._identityCalculated = false; + return this; + } + var a1 = _p[0]; + var b1 = _p[1]; + var c1 = _p[2]; + var d1 = _p[3]; + var e1 = _p[4]; + var f1 = _p[5]; + var g1 = _p[6]; + var h1 = _p[7]; + var i1 = _p[8]; + var j1 = _p[9]; + var k1 = _p[10]; + var l1 = _p[11]; + var m1 = _p[12]; + var n1 = _p[13]; + var o1 = _p[14]; + var p1 = _p[15]; + _p[0] = a1 * a2 + b1 * e2 + c1 * i2 + d1 * m2; + _p[1] = a1 * b2 + b1 * f2 + c1 * j2 + d1 * n2; + _p[2] = a1 * c2 + b1 * g22 + c1 * k2 + d1 * o2; + _p[3] = a1 * d2 + b1 * h2 + c1 * l2 + d1 * p2; + _p[4] = e1 * a2 + f1 * e2 + g1 * i2 + h1 * m2; + _p[5] = e1 * b2 + f1 * f2 + g1 * j2 + h1 * n2; + _p[6] = e1 * c2 + f1 * g22 + g1 * k2 + h1 * o2; + _p[7] = e1 * d2 + f1 * h2 + g1 * l2 + h1 * p2; + _p[8] = i1 * a2 + j1 * e2 + k1 * i2 + l1 * m2; + _p[9] = i1 * b2 + j1 * f2 + k1 * j2 + l1 * n2; + _p[10] = i1 * c2 + j1 * g22 + k1 * k2 + l1 * o2; + _p[11] = i1 * d2 + j1 * h2 + k1 * l2 + l1 * p2; + _p[12] = m1 * a2 + n1 * e2 + o1 * i2 + p1 * m2; + _p[13] = m1 * b2 + n1 * f2 + o1 * j2 + p1 * n2; + _p[14] = m1 * c2 + n1 * g22 + o1 * k2 + p1 * o2; + _p[15] = m1 * d2 + n1 * h2 + o1 * l2 + p1 * p2; + this._identityCalculated = false; + return this; + } + function isIdentity() { + if (!this._identityCalculated) { + this._identity = !(this.props[0] !== 1 || this.props[1] !== 0 || this.props[2] !== 0 || this.props[3] !== 0 || this.props[4] !== 0 || this.props[5] !== 1 || this.props[6] !== 0 || this.props[7] !== 0 || this.props[8] !== 0 || this.props[9] !== 0 || this.props[10] !== 1 || this.props[11] !== 0 || this.props[12] !== 0 || this.props[13] !== 0 || this.props[14] !== 0 || this.props[15] !== 1); + this._identityCalculated = true; + } + return this._identity; + } + function equals2(matr) { + var i = 0; + while (i < 16) { + if (matr.props[i] !== this.props[i]) { + return false; + } + i += 1; + } + return true; + } + function clone(matr) { + var i; + for (i = 0;i < 16; i += 1) { + matr.props[i] = this.props[i]; + } + return matr; + } + function cloneFromProps(props) { + var i; + for (i = 0;i < 16; i += 1) { + this.props[i] = props[i]; + } + } + function applyToPoint(x2, y, z) { + return { + x: x2 * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12], + y: x2 * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13], + z: x2 * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14] + }; + } + function applyToX(x2, y, z) { + return x2 * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12]; + } + function applyToY(x2, y, z) { + return x2 * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13]; + } + function applyToZ(x2, y, z) { + return x2 * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14]; + } + function getInverseMatrix() { + var determinant = this.props[0] * this.props[5] - this.props[1] * this.props[4]; + var a = this.props[5] / determinant; + var b = -this.props[1] / determinant; + var c = -this.props[4] / determinant; + var d = this.props[0] / determinant; + var e = (this.props[4] * this.props[13] - this.props[5] * this.props[12]) / determinant; + var f = -(this.props[0] * this.props[13] - this.props[1] * this.props[12]) / determinant; + var inverseMatrix = new Matrix; + inverseMatrix.props[0] = a; + inverseMatrix.props[1] = b; + inverseMatrix.props[4] = c; + inverseMatrix.props[5] = d; + inverseMatrix.props[12] = e; + inverseMatrix.props[13] = f; + return inverseMatrix; + } + function inversePoint(pt) { + var inverseMatrix = this.getInverseMatrix(); + return inverseMatrix.applyToPointArray(pt[0], pt[1], pt[2] || 0); + } + function inversePoints(pts) { + var i; + var len = pts.length; + var retPts = []; + for (i = 0;i < len; i += 1) { + retPts[i] = inversePoint(pts[i]); + } + return retPts; + } + function applyToTriplePoints(pt1, pt2, pt3) { + var arr = createTypedArray("float32", 6); + if (this.isIdentity()) { + arr[0] = pt1[0]; + arr[1] = pt1[1]; + arr[2] = pt2[0]; + arr[3] = pt2[1]; + arr[4] = pt3[0]; + arr[5] = pt3[1]; + } else { + var p0 = this.props[0]; + var p1 = this.props[1]; + var p4 = this.props[4]; + var p5 = this.props[5]; + var p12 = this.props[12]; + var p13 = this.props[13]; + arr[0] = pt1[0] * p0 + pt1[1] * p4 + p12; + arr[1] = pt1[0] * p1 + pt1[1] * p5 + p13; + arr[2] = pt2[0] * p0 + pt2[1] * p4 + p12; + arr[3] = pt2[0] * p1 + pt2[1] * p5 + p13; + arr[4] = pt3[0] * p0 + pt3[1] * p4 + p12; + arr[5] = pt3[0] * p1 + pt3[1] * p5 + p13; + } + return arr; + } + function applyToPointArray(x2, y, z) { + var arr; + if (this.isIdentity()) { + arr = [x2, y, z]; + } else { + arr = [ + x2 * this.props[0] + y * this.props[4] + z * this.props[8] + this.props[12], + x2 * this.props[1] + y * this.props[5] + z * this.props[9] + this.props[13], + x2 * this.props[2] + y * this.props[6] + z * this.props[10] + this.props[14] + ]; + } + return arr; + } + function applyToPointStringified(x2, y) { + if (this.isIdentity()) { + return x2 + "," + y; + } + var _p = this.props; + return Math.round((x2 * _p[0] + y * _p[4] + _p[12]) * 100) / 100 + "," + Math.round((x2 * _p[1] + y * _p[5] + _p[13]) * 100) / 100; + } + function toCSS() { + var i = 0; + var props = this.props; + var cssValue = "matrix3d("; + var v = 1e4; + while (i < 16) { + cssValue += _rnd(props[i] * v) / v; + cssValue += i === 15 ? ")" : ","; + i += 1; + } + return cssValue; + } + function roundMatrixProperty(val2) { + var v = 1e4; + if (val2 < 0.000001 && val2 > 0 || val2 > -0.000001 && val2 < 0) { + return _rnd(val2 * v) / v; + } + return val2; + } + function to2dCSS() { + var props = this.props; + var _a2 = roundMatrixProperty(props[0]); + var _b2 = roundMatrixProperty(props[1]); + var _c = roundMatrixProperty(props[4]); + var _d = roundMatrixProperty(props[5]); + var _e = roundMatrixProperty(props[12]); + var _f = roundMatrixProperty(props[13]); + return "matrix(" + _a2 + "," + _b2 + "," + _c + "," + _d + "," + _e + "," + _f + ")"; + } + return function() { + this.reset = reset; + this.rotate = rotate; + this.rotateX = rotateX; + this.rotateY = rotateY; + this.rotateZ = rotateZ; + this.skew = skew; + this.skewFromAxis = skewFromAxis; + this.shear = shear; + this.scale = scale2; + this.setTransform = setTransform; + this.translate = translate; + this.transform = transform2; + this.applyToPoint = applyToPoint; + this.applyToX = applyToX; + this.applyToY = applyToY; + this.applyToZ = applyToZ; + this.applyToPointArray = applyToPointArray; + this.applyToTriplePoints = applyToTriplePoints; + this.applyToPointStringified = applyToPointStringified; + this.toCSS = toCSS; + this.to2dCSS = to2dCSS; + this.clone = clone; + this.cloneFromProps = cloneFromProps; + this.equals = equals2; + this.inversePoints = inversePoints; + this.inversePoint = inversePoint; + this.getInverseMatrix = getInverseMatrix; + this._t = this.transform; + this.isIdentity = isIdentity; + this._identity = true; + this._identityCalculated = false; + this.props = createTypedArray("float32", 16); + this.reset(); + }; + }(); + standalone = "__[STANDALONE]__"; + animationData = "__[ANIMATIONDATA]__"; + renderer = ""; + lottie.play = animationManager.play; + lottie.pause = animationManager.pause; + lottie.setLocationHref = setLocation; + lottie.togglePause = animationManager.togglePause; + lottie.setSpeed = animationManager.setSpeed; + lottie.setDirection = animationManager.setDirection; + lottie.stop = animationManager.stop; + lottie.searchAnimations = searchAnimations; + lottie.registerAnimation = animationManager.registerAnimation; + lottie.loadAnimation = loadAnimation; + lottie.setSubframeRendering = setSubframeRendering; + lottie.resize = animationManager.resize; + lottie.goToAndStop = animationManager.goToAndStop; + lottie.destroy = animationManager.destroy; + lottie.setQuality = setQuality; + lottie.inBrowser = inBrowser; + lottie.installPlugin = installPlugin; + lottie.freeze = animationManager.freeze; + lottie.unfreeze = animationManager.unfreeze; + lottie.setVolume = animationManager.setVolume; + lottie.mute = animationManager.mute; + lottie.unmute = animationManager.unmute; + lottie.getRegisteredAnimations = animationManager.getRegisteredAnimations; + lottie.useWebWorker = setWebWorker; + lottie.setIDPrefix = setPrefix; + lottie.__getFactory = getFactory; + lottie.version = "[[BM_VERSION]]"; + queryString = ""; + if (standalone) { + scripts = document.getElementsByTagName("script"); + index2 = scripts.length - 1; + myScript = scripts[index2] || { + src: "" + }; + queryString = myScript.src ? myScript.src.replace(/^[^\?]+\??/, "") : ""; + renderer = getQueryVariable("renderer"); + } + readyStateCheckInterval = setInterval(checkReady, 100); + try { + if (!(typeof exports_lottie_canvas_module === "object" && typeof module_lottie_canvas_module !== "undefined") && !(typeof define === "function" && define.amd)) { + window.bodymovin = lottie; + } + } catch (err) { + } + const ShapeModifiers = function() { + var ob2 = {}; + var modifiers = {}; + ob2.registerModifier = registerModifier; + ob2.getModifier = getModifier; + function registerModifier(nm, factory) { + if (!modifiers[nm]) { + modifiers[nm] = factory; + } + } + function getModifier(nm, elem2, data2) { + return new modifiers[nm](elem2, data2); + } + return ob2; + }(); + ShapeModifier.prototype.initModifierProperties = function() { + }; + ShapeModifier.prototype.addShapeToModifier = function() { + }; + ShapeModifier.prototype.addShape = function(data2) { + if (!this.closed) { + data2.sh.container.addDynamicProperty(data2.sh); + var shapeData = { shape: data2.sh, data: data2, localShapeCollection: shapeCollectionPool.newShapeCollection() }; + this.shapes.push(shapeData); + this.addShapeToModifier(shapeData); + if (this._isAnimated) { + data2.setAsAnimated(); + } + } + }; + ShapeModifier.prototype.init = function(elem2, data2) { + this.shapes = []; + this.elem = elem2; + this.initDynamicPropertyContainer(elem2); + this.initModifierProperties(elem2, data2); + this.frameId = initialDefaultFrame; + this.closed = false; + this.k = false; + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.getValue(true); + } + }; + ShapeModifier.prototype.processKeys = function() { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + }; + extendPrototype([DynamicPropertyContainer], ShapeModifier); + extendPrototype([ShapeModifier], TrimModifier); + TrimModifier.prototype.initModifierProperties = function(elem2, data2) { + this.s = PropertyFactory.getProp(elem2, data2.s, 0, 0.01, this); + this.e = PropertyFactory.getProp(elem2, data2.e, 0, 0.01, this); + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0, this); + this.sValue = 0; + this.eValue = 0; + this.getValue = this.processKeys; + this.m = data2.m; + this._isAnimated = !!this.s.effectsSequence.length || !!this.e.effectsSequence.length || !!this.o.effectsSequence.length; + }; + TrimModifier.prototype.addShapeToModifier = function(shapeData) { + shapeData.pathsData = []; + }; + TrimModifier.prototype.calculateShapeEdges = function(s, e, shapeLength, addedLength, totalModifierLength) { + var segments = []; + if (e <= 1) { + segments.push({ + s, + e + }); + } else if (s >= 1) { + segments.push({ + s: s - 1, + e: e - 1 + }); + } else { + segments.push({ + s, + e: 1 + }); + segments.push({ + s: 0, + e: e - 1 + }); + } + var shapeSegments = []; + var i; + var len = segments.length; + var segmentOb; + for (i = 0;i < len; i += 1) { + segmentOb = segments[i]; + if (!(segmentOb.e * totalModifierLength < addedLength || segmentOb.s * totalModifierLength > addedLength + shapeLength)) { + var shapeS; + var shapeE; + if (segmentOb.s * totalModifierLength <= addedLength) { + shapeS = 0; + } else { + shapeS = (segmentOb.s * totalModifierLength - addedLength) / shapeLength; + } + if (segmentOb.e * totalModifierLength >= addedLength + shapeLength) { + shapeE = 1; + } else { + shapeE = (segmentOb.e * totalModifierLength - addedLength) / shapeLength; + } + shapeSegments.push([shapeS, shapeE]); + } + } + if (!shapeSegments.length) { + shapeSegments.push([0, 0]); + } + return shapeSegments; + }; + TrimModifier.prototype.releasePathsData = function(pathsData) { + var i; + var len = pathsData.length; + for (i = 0;i < len; i += 1) { + segmentsLengthPool.release(pathsData[i]); + } + pathsData.length = 0; + return pathsData; + }; + TrimModifier.prototype.processShapes = function(_isFirstFrame) { + var s; + var e; + if (this._mdf || _isFirstFrame) { + var o = this.o.v % 360 / 360; + if (o < 0) { + o += 1; + } + if (this.s.v > 1) { + s = 1 + o; + } else if (this.s.v < 0) { + s = 0 + o; + } else { + s = this.s.v + o; + } + if (this.e.v > 1) { + e = 1 + o; + } else if (this.e.v < 0) { + e = 0 + o; + } else { + e = this.e.v + o; + } + if (s > e) { + var _s = s; + s = e; + e = _s; + } + s = Math.round(s * 1e4) * 0.0001; + e = Math.round(e * 1e4) * 0.0001; + this.sValue = s; + this.eValue = e; + } else { + s = this.sValue; + e = this.eValue; + } + var shapePaths; + var i; + var len = this.shapes.length; + var j2; + var jLen; + var pathsData; + var pathData; + var totalShapeLength; + var totalModifierLength = 0; + if (e === s) { + for (i = 0;i < len; i += 1) { + this.shapes[i].localShapeCollection.releaseShapes(); + this.shapes[i].shape._mdf = true; + this.shapes[i].shape.paths = this.shapes[i].localShapeCollection; + if (this._mdf) { + this.shapes[i].pathsData.length = 0; + } + } + } else if (!(e === 1 && s === 0 || e === 0 && s === 1)) { + var segments = []; + var shapeData; + var localShapeCollection; + for (i = 0;i < len; i += 1) { + shapeData = this.shapes[i]; + if (!shapeData.shape._mdf && !this._mdf && !_isFirstFrame && this.m !== 2) { + shapeData.shape.paths = shapeData.localShapeCollection; + } else { + shapePaths = shapeData.shape.paths; + jLen = shapePaths._length; + totalShapeLength = 0; + if (!shapeData.shape._mdf && shapeData.pathsData.length) { + totalShapeLength = shapeData.totalShapeLength; + } else { + pathsData = this.releasePathsData(shapeData.pathsData); + for (j2 = 0;j2 < jLen; j2 += 1) { + pathData = bez.getSegmentsLength(shapePaths.shapes[j2]); + pathsData.push(pathData); + totalShapeLength += pathData.totalLength; + } + shapeData.totalShapeLength = totalShapeLength; + shapeData.pathsData = pathsData; + } + totalModifierLength += totalShapeLength; + shapeData.shape._mdf = true; + } + } + var shapeS = s; + var shapeE = e; + var addedLength = 0; + var edges; + for (i = len - 1;i >= 0; i -= 1) { + shapeData = this.shapes[i]; + if (shapeData.shape._mdf) { + localShapeCollection = shapeData.localShapeCollection; + localShapeCollection.releaseShapes(); + if (this.m === 2 && len > 1) { + edges = this.calculateShapeEdges(s, e, shapeData.totalShapeLength, addedLength, totalModifierLength); + addedLength += shapeData.totalShapeLength; + } else { + edges = [[shapeS, shapeE]]; + } + jLen = edges.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + shapeS = edges[j2][0]; + shapeE = edges[j2][1]; + segments.length = 0; + if (shapeE <= 1) { + segments.push({ + s: shapeData.totalShapeLength * shapeS, + e: shapeData.totalShapeLength * shapeE + }); + } else if (shapeS >= 1) { + segments.push({ + s: shapeData.totalShapeLength * (shapeS - 1), + e: shapeData.totalShapeLength * (shapeE - 1) + }); + } else { + segments.push({ + s: shapeData.totalShapeLength * shapeS, + e: shapeData.totalShapeLength + }); + segments.push({ + s: 0, + e: shapeData.totalShapeLength * (shapeE - 1) + }); + } + var newShapesData = this.addShapes(shapeData, segments[0]); + if (segments[0].s !== segments[0].e) { + if (segments.length > 1) { + var lastShapeInCollection = shapeData.shape.paths.shapes[shapeData.shape.paths._length - 1]; + if (lastShapeInCollection.c) { + var lastShape = newShapesData.pop(); + this.addPaths(newShapesData, localShapeCollection); + newShapesData = this.addShapes(shapeData, segments[1], lastShape); + } else { + this.addPaths(newShapesData, localShapeCollection); + newShapesData = this.addShapes(shapeData, segments[1]); + } + } + this.addPaths(newShapesData, localShapeCollection); + } + } + shapeData.shape.paths = localShapeCollection; + } + } + } else if (this._mdf) { + for (i = 0;i < len; i += 1) { + this.shapes[i].pathsData.length = 0; + this.shapes[i].shape._mdf = true; + } + } + }; + TrimModifier.prototype.addPaths = function(newPaths, localShapeCollection) { + var i; + var len = newPaths.length; + for (i = 0;i < len; i += 1) { + localShapeCollection.addShape(newPaths[i]); + } + }; + TrimModifier.prototype.addSegment = function(pt1, pt2, pt3, pt4, shapePath, pos, newShape) { + shapePath.setXYAt(pt2[0], pt2[1], "o", pos); + shapePath.setXYAt(pt3[0], pt3[1], "i", pos + 1); + if (newShape) { + shapePath.setXYAt(pt1[0], pt1[1], "v", pos); + } + shapePath.setXYAt(pt4[0], pt4[1], "v", pos + 1); + }; + TrimModifier.prototype.addSegmentFromArray = function(points, shapePath, pos, newShape) { + shapePath.setXYAt(points[1], points[5], "o", pos); + shapePath.setXYAt(points[2], points[6], "i", pos + 1); + if (newShape) { + shapePath.setXYAt(points[0], points[4], "v", pos); + } + shapePath.setXYAt(points[3], points[7], "v", pos + 1); + }; + TrimModifier.prototype.addShapes = function(shapeData, shapeSegment, shapePath) { + var pathsData = shapeData.pathsData; + var shapePaths = shapeData.shape.paths.shapes; + var i; + var len = shapeData.shape.paths._length; + var j2; + var jLen; + var addedLength = 0; + var currentLengthData; + var segmentCount; + var lengths; + var segment; + var shapes = []; + var initPos; + var newShape = true; + if (!shapePath) { + shapePath = shapePool.newElement(); + segmentCount = 0; + initPos = 0; + } else { + segmentCount = shapePath._length; + initPos = shapePath._length; + } + shapes.push(shapePath); + for (i = 0;i < len; i += 1) { + lengths = pathsData[i].lengths; + shapePath.c = shapePaths[i].c; + jLen = shapePaths[i].c ? lengths.length : lengths.length + 1; + for (j2 = 1;j2 < jLen; j2 += 1) { + currentLengthData = lengths[j2 - 1]; + if (addedLength + currentLengthData.addedLength < shapeSegment.s) { + addedLength += currentLengthData.addedLength; + shapePath.c = false; + } else if (addedLength > shapeSegment.e) { + shapePath.c = false; + break; + } else { + if (shapeSegment.s <= addedLength && shapeSegment.e >= addedLength + currentLengthData.addedLength) { + this.addSegment(shapePaths[i].v[j2 - 1], shapePaths[i].o[j2 - 1], shapePaths[i].i[j2], shapePaths[i].v[j2], shapePath, segmentCount, newShape); + newShape = false; + } else { + segment = bez.getNewSegment(shapePaths[i].v[j2 - 1], shapePaths[i].v[j2], shapePaths[i].o[j2 - 1], shapePaths[i].i[j2], (shapeSegment.s - addedLength) / currentLengthData.addedLength, (shapeSegment.e - addedLength) / currentLengthData.addedLength, lengths[j2 - 1]); + this.addSegmentFromArray(segment, shapePath, segmentCount, newShape); + newShape = false; + shapePath.c = false; + } + addedLength += currentLengthData.addedLength; + segmentCount += 1; + } + } + if (shapePaths[i].c && lengths.length) { + currentLengthData = lengths[j2 - 1]; + if (addedLength <= shapeSegment.e) { + var segmentLength = lengths[j2 - 1].addedLength; + if (shapeSegment.s <= addedLength && shapeSegment.e >= addedLength + segmentLength) { + this.addSegment(shapePaths[i].v[j2 - 1], shapePaths[i].o[j2 - 1], shapePaths[i].i[0], shapePaths[i].v[0], shapePath, segmentCount, newShape); + newShape = false; + } else { + segment = bez.getNewSegment(shapePaths[i].v[j2 - 1], shapePaths[i].v[0], shapePaths[i].o[j2 - 1], shapePaths[i].i[0], (shapeSegment.s - addedLength) / segmentLength, (shapeSegment.e - addedLength) / segmentLength, lengths[j2 - 1]); + this.addSegmentFromArray(segment, shapePath, segmentCount, newShape); + newShape = false; + shapePath.c = false; + } + } else { + shapePath.c = false; + } + addedLength += currentLengthData.addedLength; + segmentCount += 1; + } + if (shapePath._length) { + shapePath.setXYAt(shapePath.v[initPos][0], shapePath.v[initPos][1], "i", initPos); + shapePath.setXYAt(shapePath.v[shapePath._length - 1][0], shapePath.v[shapePath._length - 1][1], "o", shapePath._length - 1); + } + if (addedLength > shapeSegment.e) { + break; + } + if (i < len - 1) { + shapePath = shapePool.newElement(); + newShape = true; + shapes.push(shapePath); + segmentCount = 0; + } + } + return shapes; + }; + extendPrototype([ShapeModifier], PuckerAndBloatModifier); + PuckerAndBloatModifier.prototype.initModifierProperties = function(elem2, data2) { + this.getValue = this.processKeys; + this.amount = PropertyFactory.getProp(elem2, data2.a, 0, null, this); + this._isAnimated = !!this.amount.effectsSequence.length; + }; + PuckerAndBloatModifier.prototype.processPath = function(path, amount) { + var percent = amount / 100; + var centerPoint = [0, 0]; + var pathLength = path._length; + var i = 0; + for (i = 0;i < pathLength; i += 1) { + centerPoint[0] += path.v[i][0]; + centerPoint[1] += path.v[i][1]; + } + centerPoint[0] /= pathLength; + centerPoint[1] /= pathLength; + var clonedPath = shapePool.newElement(); + clonedPath.c = path.c; + var vX; + var vY; + var oX; + var oY; + var iX; + var iY; + for (i = 0;i < pathLength; i += 1) { + vX = path.v[i][0] + (centerPoint[0] - path.v[i][0]) * percent; + vY = path.v[i][1] + (centerPoint[1] - path.v[i][1]) * percent; + oX = path.o[i][0] + (centerPoint[0] - path.o[i][0]) * -percent; + oY = path.o[i][1] + (centerPoint[1] - path.o[i][1]) * -percent; + iX = path.i[i][0] + (centerPoint[0] - path.i[i][0]) * -percent; + iY = path.i[i][1] + (centerPoint[1] - path.i[i][1]) * -percent; + clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, i); + } + return clonedPath; + }; + PuckerAndBloatModifier.prototype.processShapes = function(_isFirstFrame) { + var shapePaths; + var i; + var len = this.shapes.length; + var j2; + var jLen; + var amount = this.amount.v; + if (amount !== 0) { + var shapeData; + var localShapeCollection; + for (i = 0;i < len; i += 1) { + shapeData = this.shapes[i]; + localShapeCollection = shapeData.localShapeCollection; + if (!(!shapeData.shape._mdf && !this._mdf && !_isFirstFrame)) { + localShapeCollection.releaseShapes(); + shapeData.shape._mdf = true; + shapePaths = shapeData.shape.paths.shapes; + jLen = shapeData.shape.paths._length; + for (j2 = 0;j2 < jLen; j2 += 1) { + localShapeCollection.addShape(this.processPath(shapePaths[j2], amount)); + } + } + shapeData.shape.paths = shapeData.localShapeCollection; + } + } + if (!this.dynamicProperties.length) { + this._mdf = false; + } + }; + const TransformPropertyFactory = function() { + var defaultVector = [0, 0]; + function applyToMatrix(mat) { + var _mdf = this._mdf; + this.iterateDynamicProperties(); + this._mdf = this._mdf || _mdf; + if (this.a) { + mat.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]); + } + if (this.s) { + mat.scale(this.s.v[0], this.s.v[1], this.s.v[2]); + } + if (this.sk) { + mat.skewFromAxis(-this.sk.v, this.sa.v); + } + if (this.r) { + mat.rotate(-this.r.v); + } else { + mat.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]); + } + if (this.data.p.s) { + if (this.data.p.z) { + mat.translate(this.px.v, this.py.v, -this.pz.v); + } else { + mat.translate(this.px.v, this.py.v, 0); + } + } else { + mat.translate(this.p.v[0], this.p.v[1], -this.p.v[2]); + } + } + function processKeys(forceRender) { + if (this.elem.globalData.frameId === this.frameId) { + return; + } + if (this._isDirty) { + this.precalculateMatrix(); + this._isDirty = false; + } + this.iterateDynamicProperties(); + if (this._mdf || forceRender) { + var frameRate; + this.v.cloneFromProps(this.pre.props); + if (this.appliedTransformations < 1) { + this.v.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]); + } + if (this.appliedTransformations < 2) { + this.v.scale(this.s.v[0], this.s.v[1], this.s.v[2]); + } + if (this.sk && this.appliedTransformations < 3) { + this.v.skewFromAxis(-this.sk.v, this.sa.v); + } + if (this.r && this.appliedTransformations < 4) { + this.v.rotate(-this.r.v); + } else if (!this.r && this.appliedTransformations < 4) { + this.v.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]); + } + if (this.autoOriented) { + var v1; + var v2; + frameRate = this.elem.globalData.frameRate; + if (this.p && this.p.keyframes && this.p.getValueAtTime) { + if (this.p._caching.lastFrame + this.p.offsetTime <= this.p.keyframes[0].t) { + v1 = this.p.getValueAtTime((this.p.keyframes[0].t + 0.01) / frameRate, 0); + v2 = this.p.getValueAtTime(this.p.keyframes[0].t / frameRate, 0); + } else if (this.p._caching.lastFrame + this.p.offsetTime >= this.p.keyframes[this.p.keyframes.length - 1].t) { + v1 = this.p.getValueAtTime(this.p.keyframes[this.p.keyframes.length - 1].t / frameRate, 0); + v2 = this.p.getValueAtTime((this.p.keyframes[this.p.keyframes.length - 1].t - 0.05) / frameRate, 0); + } else { + v1 = this.p.pv; + v2 = this.p.getValueAtTime((this.p._caching.lastFrame + this.p.offsetTime - 0.01) / frameRate, this.p.offsetTime); + } + } else if (this.px && this.px.keyframes && this.py.keyframes && this.px.getValueAtTime && this.py.getValueAtTime) { + v1 = []; + v2 = []; + var px2 = this.px; + var py2 = this.py; + if (px2._caching.lastFrame + px2.offsetTime <= px2.keyframes[0].t) { + v1[0] = px2.getValueAtTime((px2.keyframes[0].t + 0.01) / frameRate, 0); + v1[1] = py2.getValueAtTime((py2.keyframes[0].t + 0.01) / frameRate, 0); + v2[0] = px2.getValueAtTime(px2.keyframes[0].t / frameRate, 0); + v2[1] = py2.getValueAtTime(py2.keyframes[0].t / frameRate, 0); + } else if (px2._caching.lastFrame + px2.offsetTime >= px2.keyframes[px2.keyframes.length - 1].t) { + v1[0] = px2.getValueAtTime(px2.keyframes[px2.keyframes.length - 1].t / frameRate, 0); + v1[1] = py2.getValueAtTime(py2.keyframes[py2.keyframes.length - 1].t / frameRate, 0); + v2[0] = px2.getValueAtTime((px2.keyframes[px2.keyframes.length - 1].t - 0.01) / frameRate, 0); + v2[1] = py2.getValueAtTime((py2.keyframes[py2.keyframes.length - 1].t - 0.01) / frameRate, 0); + } else { + v1 = [px2.pv, py2.pv]; + v2[0] = px2.getValueAtTime((px2._caching.lastFrame + px2.offsetTime - 0.01) / frameRate, px2.offsetTime); + v2[1] = py2.getValueAtTime((py2._caching.lastFrame + py2.offsetTime - 0.01) / frameRate, py2.offsetTime); + } + } else { + v2 = defaultVector; + v1 = v2; + } + this.v.rotate(-Math.atan2(v1[1] - v2[1], v1[0] - v2[0])); + } + if (this.data.p && this.data.p.s) { + if (this.data.p.z) { + this.v.translate(this.px.v, this.py.v, -this.pz.v); + } else { + this.v.translate(this.px.v, this.py.v, 0); + } + } else { + this.v.translate(this.p.v[0], this.p.v[1], -this.p.v[2]); + } + } + this.frameId = this.elem.globalData.frameId; + } + function precalculateMatrix() { + if (!this.a.k) { + this.pre.translate(-this.a.v[0], -this.a.v[1], this.a.v[2]); + this.appliedTransformations = 1; + } else { + return; + } + if (!this.s.effectsSequence.length) { + this.pre.scale(this.s.v[0], this.s.v[1], this.s.v[2]); + this.appliedTransformations = 2; + } else { + return; + } + if (this.sk) { + if (!this.sk.effectsSequence.length && !this.sa.effectsSequence.length) { + this.pre.skewFromAxis(-this.sk.v, this.sa.v); + this.appliedTransformations = 3; + } else { + return; + } + } + if (this.r) { + if (!this.r.effectsSequence.length) { + this.pre.rotate(-this.r.v); + this.appliedTransformations = 4; + } + } else if (!this.rz.effectsSequence.length && !this.ry.effectsSequence.length && !this.rx.effectsSequence.length && !this.or.effectsSequence.length) { + this.pre.rotateZ(-this.rz.v).rotateY(this.ry.v).rotateX(this.rx.v).rotateZ(-this.or.v[2]).rotateY(this.or.v[1]).rotateX(this.or.v[0]); + this.appliedTransformations = 4; + } + } + function autoOrient() { + } + function addDynamicProperty(prop) { + this._addDynamicProperty(prop); + this.elem.addDynamicProperty(prop); + this._isDirty = true; + } + function TransformProperty(elem2, data2, container) { + this.elem = elem2; + this.frameId = -1; + this.propType = "transform"; + this.data = data2; + this.v = new Matrix; + this.pre = new Matrix; + this.appliedTransformations = 0; + this.initDynamicPropertyContainer(container || elem2); + if (data2.p && data2.p.s) { + this.px = PropertyFactory.getProp(elem2, data2.p.x, 0, 0, this); + this.py = PropertyFactory.getProp(elem2, data2.p.y, 0, 0, this); + if (data2.p.z) { + this.pz = PropertyFactory.getProp(elem2, data2.p.z, 0, 0, this); + } + } else { + this.p = PropertyFactory.getProp(elem2, data2.p || { k: [0, 0, 0] }, 1, 0, this); + } + if (data2.rx) { + this.rx = PropertyFactory.getProp(elem2, data2.rx, 0, degToRads, this); + this.ry = PropertyFactory.getProp(elem2, data2.ry, 0, degToRads, this); + this.rz = PropertyFactory.getProp(elem2, data2.rz, 0, degToRads, this); + if (data2.or.k[0].ti) { + var i; + var len = data2.or.k.length; + for (i = 0;i < len; i += 1) { + data2.or.k[i].to = null; + data2.or.k[i].ti = null; + } + } + this.or = PropertyFactory.getProp(elem2, data2.or, 1, degToRads, this); + this.or.sh = true; + } else { + this.r = PropertyFactory.getProp(elem2, data2.r || { k: 0 }, 0, degToRads, this); + } + if (data2.sk) { + this.sk = PropertyFactory.getProp(elem2, data2.sk, 0, degToRads, this); + this.sa = PropertyFactory.getProp(elem2, data2.sa, 0, degToRads, this); + } + this.a = PropertyFactory.getProp(elem2, data2.a || { k: [0, 0, 0] }, 1, 0, this); + this.s = PropertyFactory.getProp(elem2, data2.s || { k: [100, 100, 100] }, 1, 0.01, this); + if (data2.o) { + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, elem2); + } else { + this.o = { _mdf: false, v: 1 }; + } + this._isDirty = true; + if (!this.dynamicProperties.length) { + this.getValue(true); + } + } + TransformProperty.prototype = { + applyToMatrix, + getValue: processKeys, + precalculateMatrix, + autoOrient + }; + extendPrototype([DynamicPropertyContainer], TransformProperty); + TransformProperty.prototype.addDynamicProperty = addDynamicProperty; + TransformProperty.prototype._addDynamicProperty = DynamicPropertyContainer.prototype.addDynamicProperty; + function getTransformProperty(elem2, data2, container) { + return new TransformProperty(elem2, data2, container); + } + return { + getTransformProperty + }; + }(); + extendPrototype([ShapeModifier], RepeaterModifier); + RepeaterModifier.prototype.initModifierProperties = function(elem2, data2) { + this.getValue = this.processKeys; + this.c = PropertyFactory.getProp(elem2, data2.c, 0, null, this); + this.o = PropertyFactory.getProp(elem2, data2.o, 0, null, this); + this.tr = TransformPropertyFactory.getTransformProperty(elem2, data2.tr, this); + this.so = PropertyFactory.getProp(elem2, data2.tr.so, 0, 0.01, this); + this.eo = PropertyFactory.getProp(elem2, data2.tr.eo, 0, 0.01, this); + this.data = data2; + if (!this.dynamicProperties.length) { + this.getValue(true); + } + this._isAnimated = !!this.dynamicProperties.length; + this.pMatrix = new Matrix; + this.rMatrix = new Matrix; + this.sMatrix = new Matrix; + this.tMatrix = new Matrix; + this.matrix = new Matrix; + }; + RepeaterModifier.prototype.applyTransforms = function(pMatrix, rMatrix, sMatrix, transform2, perc, inv) { + var dir = inv ? -1 : 1; + var scaleX = transform2.s.v[0] + (1 - transform2.s.v[0]) * (1 - perc); + var scaleY = transform2.s.v[1] + (1 - transform2.s.v[1]) * (1 - perc); + pMatrix.translate(transform2.p.v[0] * dir * perc, transform2.p.v[1] * dir * perc, transform2.p.v[2]); + rMatrix.translate(-transform2.a.v[0], -transform2.a.v[1], transform2.a.v[2]); + rMatrix.rotate(-transform2.r.v * dir * perc); + rMatrix.translate(transform2.a.v[0], transform2.a.v[1], transform2.a.v[2]); + sMatrix.translate(-transform2.a.v[0], -transform2.a.v[1], transform2.a.v[2]); + sMatrix.scale(inv ? 1 / scaleX : scaleX, inv ? 1 / scaleY : scaleY); + sMatrix.translate(transform2.a.v[0], transform2.a.v[1], transform2.a.v[2]); + }; + RepeaterModifier.prototype.init = function(elem2, arr, pos, elemsData) { + this.elem = elem2; + this.arr = arr; + this.pos = pos; + this.elemsData = elemsData; + this._currentCopies = 0; + this._elements = []; + this._groups = []; + this.frameId = -1; + this.initDynamicPropertyContainer(elem2); + this.initModifierProperties(elem2, arr[pos]); + while (pos > 0) { + pos -= 1; + this._elements.unshift(arr[pos]); + } + if (this.dynamicProperties.length) { + this.k = true; + } else { + this.getValue(true); + } + }; + RepeaterModifier.prototype.resetElements = function(elements) { + var i; + var len = elements.length; + for (i = 0;i < len; i += 1) { + elements[i]._processed = false; + if (elements[i].ty === "gr") { + this.resetElements(elements[i].it); + } + } + }; + RepeaterModifier.prototype.cloneElements = function(elements) { + var newElements = JSON.parse(JSON.stringify(elements)); + this.resetElements(newElements); + return newElements; + }; + RepeaterModifier.prototype.changeGroupRender = function(elements, renderFlag) { + var i; + var len = elements.length; + for (i = 0;i < len; i += 1) { + elements[i]._render = renderFlag; + if (elements[i].ty === "gr") { + this.changeGroupRender(elements[i].it, renderFlag); + } + } + }; + RepeaterModifier.prototype.processShapes = function(_isFirstFrame) { + var items; + var itemsTransform; + var i; + var dir; + var cont; + var hasReloaded = false; + if (this._mdf || _isFirstFrame) { + var copies = Math.ceil(this.c.v); + if (this._groups.length < copies) { + while (this._groups.length < copies) { + var group = { + it: this.cloneElements(this._elements), + ty: "gr" + }; + group.it.push({ + a: { a: 0, ix: 1, k: [0, 0] }, + nm: "Transform", + o: { a: 0, ix: 7, k: 100 }, + p: { a: 0, ix: 2, k: [0, 0] }, + r: { a: 1, ix: 6, k: [{ s: 0, e: 0, t: 0 }, { s: 0, e: 0, t: 1 }] }, + s: { a: 0, ix: 3, k: [100, 100] }, + sa: { a: 0, ix: 5, k: 0 }, + sk: { a: 0, ix: 4, k: 0 }, + ty: "tr" + }); + this.arr.splice(0, 0, group); + this._groups.splice(0, 0, group); + this._currentCopies += 1; + } + this.elem.reloadShapes(); + hasReloaded = true; + } + cont = 0; + var renderFlag; + for (i = 0;i <= this._groups.length - 1; i += 1) { + renderFlag = cont < copies; + this._groups[i]._render = renderFlag; + this.changeGroupRender(this._groups[i].it, renderFlag); + if (!renderFlag) { + var elems = this.elemsData[i].it; + var transformData = elems[elems.length - 1]; + if (transformData.transform.op.v !== 0) { + transformData.transform.op._mdf = true; + transformData.transform.op.v = 0; + } else { + transformData.transform.op._mdf = false; + } + } + cont += 1; + } + this._currentCopies = copies; + var offset = this.o.v; + var offsetModulo = offset % 1; + var roundOffset = offset > 0 ? Math.floor(offset) : Math.ceil(offset); + var pProps = this.pMatrix.props; + var rProps = this.rMatrix.props; + var sProps = this.sMatrix.props; + this.pMatrix.reset(); + this.rMatrix.reset(); + this.sMatrix.reset(); + this.tMatrix.reset(); + this.matrix.reset(); + var iteration = 0; + if (offset > 0) { + while (iteration < roundOffset) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, false); + iteration += 1; + } + if (offsetModulo) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, offsetModulo, false); + iteration += offsetModulo; + } + } else if (offset < 0) { + while (iteration > roundOffset) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, true); + iteration -= 1; + } + if (offsetModulo) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, -offsetModulo, true); + iteration -= offsetModulo; + } + } + i = this.data.m === 1 ? 0 : this._currentCopies - 1; + dir = this.data.m === 1 ? 1 : -1; + cont = this._currentCopies; + var j2; + var jLen; + while (cont) { + items = this.elemsData[i].it; + itemsTransform = items[items.length - 1].transform.mProps.v.props; + jLen = itemsTransform.length; + items[items.length - 1].transform.mProps._mdf = true; + items[items.length - 1].transform.op._mdf = true; + items[items.length - 1].transform.op.v = this._currentCopies === 1 ? this.so.v : this.so.v + (this.eo.v - this.so.v) * (i / (this._currentCopies - 1)); + if (iteration !== 0) { + if (i !== 0 && dir === 1 || i !== this._currentCopies - 1 && dir === -1) { + this.applyTransforms(this.pMatrix, this.rMatrix, this.sMatrix, this.tr, 1, false); + } + this.matrix.transform(rProps[0], rProps[1], rProps[2], rProps[3], rProps[4], rProps[5], rProps[6], rProps[7], rProps[8], rProps[9], rProps[10], rProps[11], rProps[12], rProps[13], rProps[14], rProps[15]); + this.matrix.transform(sProps[0], sProps[1], sProps[2], sProps[3], sProps[4], sProps[5], sProps[6], sProps[7], sProps[8], sProps[9], sProps[10], sProps[11], sProps[12], sProps[13], sProps[14], sProps[15]); + this.matrix.transform(pProps[0], pProps[1], pProps[2], pProps[3], pProps[4], pProps[5], pProps[6], pProps[7], pProps[8], pProps[9], pProps[10], pProps[11], pProps[12], pProps[13], pProps[14], pProps[15]); + for (j2 = 0;j2 < jLen; j2 += 1) { + itemsTransform[j2] = this.matrix.props[j2]; + } + this.matrix.reset(); + } else { + this.matrix.reset(); + for (j2 = 0;j2 < jLen; j2 += 1) { + itemsTransform[j2] = this.matrix.props[j2]; + } + } + iteration += 1; + cont -= 1; + i += dir; + } + } else { + cont = this._currentCopies; + i = 0; + dir = 1; + while (cont) { + items = this.elemsData[i].it; + itemsTransform = items[items.length - 1].transform.mProps.v.props; + items[items.length - 1].transform.mProps._mdf = false; + items[items.length - 1].transform.op._mdf = false; + cont -= 1; + i += dir; + } + } + return hasReloaded; + }; + RepeaterModifier.prototype.addShape = function() { + }; + extendPrototype([ShapeModifier], RoundCornersModifier); + RoundCornersModifier.prototype.initModifierProperties = function(elem2, data2) { + this.getValue = this.processKeys; + this.rd = PropertyFactory.getProp(elem2, data2.r, 0, null, this); + this._isAnimated = !!this.rd.effectsSequence.length; + }; + RoundCornersModifier.prototype.processPath = function(path, round) { + var clonedPath = shapePool.newElement(); + clonedPath.c = path.c; + var i; + var len = path._length; + var currentV; + var currentI; + var currentO; + var closerV; + var distance; + var newPosPerc; + var index2 = 0; + var vX; + var vY; + var oX; + var oY; + var iX; + var iY; + for (i = 0;i < len; i += 1) { + currentV = path.v[i]; + currentO = path.o[i]; + currentI = path.i[i]; + if (currentV[0] === currentO[0] && currentV[1] === currentO[1] && currentV[0] === currentI[0] && currentV[1] === currentI[1]) { + if ((i === 0 || i === len - 1) && !path.c) { + clonedPath.setTripleAt(currentV[0], currentV[1], currentO[0], currentO[1], currentI[0], currentI[1], index2); + index2 += 1; + } else { + if (i === 0) { + closerV = path.v[len - 1]; + } else { + closerV = path.v[i - 1]; + } + distance = Math.sqrt(Math.pow(currentV[0] - closerV[0], 2) + Math.pow(currentV[1] - closerV[1], 2)); + newPosPerc = distance ? Math.min(distance / 2, round) / distance : 0; + iX = currentV[0] + (closerV[0] - currentV[0]) * newPosPerc; + vX = iX; + iY = currentV[1] - (currentV[1] - closerV[1]) * newPosPerc; + vY = iY; + oX = vX - (vX - currentV[0]) * roundCorner; + oY = vY - (vY - currentV[1]) * roundCorner; + clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, index2); + index2 += 1; + if (i === len - 1) { + closerV = path.v[0]; + } else { + closerV = path.v[i + 1]; + } + distance = Math.sqrt(Math.pow(currentV[0] - closerV[0], 2) + Math.pow(currentV[1] - closerV[1], 2)); + newPosPerc = distance ? Math.min(distance / 2, round) / distance : 0; + oX = currentV[0] + (closerV[0] - currentV[0]) * newPosPerc; + vX = oX; + oY = currentV[1] + (closerV[1] - currentV[1]) * newPosPerc; + vY = oY; + iX = vX - (vX - currentV[0]) * roundCorner; + iY = vY - (vY - currentV[1]) * roundCorner; + clonedPath.setTripleAt(vX, vY, oX, oY, iX, iY, index2); + index2 += 1; + } + } else { + clonedPath.setTripleAt(path.v[i][0], path.v[i][1], path.o[i][0], path.o[i][1], path.i[i][0], path.i[i][1], index2); + index2 += 1; + } + } + return clonedPath; + }; + RoundCornersModifier.prototype.processShapes = function(_isFirstFrame) { + var shapePaths; + var i; + var len = this.shapes.length; + var j2; + var jLen; + var rd = this.rd.v; + if (rd !== 0) { + var shapeData; + var localShapeCollection; + for (i = 0;i < len; i += 1) { + shapeData = this.shapes[i]; + localShapeCollection = shapeData.localShapeCollection; + if (!(!shapeData.shape._mdf && !this._mdf && !_isFirstFrame)) { + localShapeCollection.releaseShapes(); + shapeData.shape._mdf = true; + shapePaths = shapeData.shape.paths.shapes; + jLen = shapeData.shape.paths._length; + for (j2 = 0;j2 < jLen; j2 += 1) { + localShapeCollection.addShape(this.processPath(shapePaths[j2], rd)); + } + } + shapeData.shape.paths = shapeData.localShapeCollection; + } + } + if (!this.dynamicProperties.length) { + this._mdf = false; + } + }; + const FontManager = function() { + var maxWaitingTime = 5000; + var emptyChar = { + w: 0, + size: 0, + shapes: [], + data: { + shapes: [] + } + }; + var combinedCharacters = []; + combinedCharacters = combinedCharacters.concat([ + 2304, + 2305, + 2306, + 2307, + 2362, + 2363, + 2364, + 2364, + 2366, + 2367, + 2368, + 2369, + 2370, + 2371, + 2372, + 2373, + 2374, + 2375, + 2376, + 2377, + 2378, + 2379, + 2380, + 2381, + 2382, + 2383, + 2387, + 2388, + 2389, + 2390, + 2391, + 2402, + 2403 + ]); + var surrogateModifiers = [ + "d83cdffb", + "d83cdffc", + "d83cdffd", + "d83cdffe", + "d83cdfff" + ]; + var zeroWidthJoiner = [65039, 8205]; + function trimFontOptions(font) { + var familyArray = font.split(","); + var i; + var len = familyArray.length; + var enabledFamilies = []; + for (i = 0;i < len; i += 1) { + if (familyArray[i] !== "sans-serif" && familyArray[i] !== "monospace") { + enabledFamilies.push(familyArray[i]); + } + } + return enabledFamilies.join(","); + } + function setUpNode(font, family) { + var parentNode = createTag("span"); + parentNode.setAttribute("aria-hidden", true); + parentNode.style.fontFamily = family; + var node = createTag("span"); + node.innerText = "giItT1WQy@!-/#"; + parentNode.style.position = "absolute"; + parentNode.style.left = "-10000px"; + parentNode.style.top = "-10000px"; + parentNode.style.fontSize = "300px"; + parentNode.style.fontVariant = "normal"; + parentNode.style.fontStyle = "normal"; + parentNode.style.fontWeight = "normal"; + parentNode.style.letterSpacing = "0"; + parentNode.appendChild(node); + document.body.appendChild(parentNode); + var width2 = node.offsetWidth; + node.style.fontFamily = trimFontOptions(font) + ", " + family; + return { node, w: width2, parent: parentNode }; + } + function checkLoadedFonts() { + var i; + var len = this.fonts.length; + var node; + var w; + var loadedCount = len; + for (i = 0;i < len; i += 1) { + if (this.fonts[i].loaded) { + loadedCount -= 1; + } else if (this.fonts[i].fOrigin === "n" || this.fonts[i].origin === 0) { + this.fonts[i].loaded = true; + } else { + node = this.fonts[i].monoCase.node; + w = this.fonts[i].monoCase.w; + if (node.offsetWidth !== w) { + loadedCount -= 1; + this.fonts[i].loaded = true; + } else { + node = this.fonts[i].sansCase.node; + w = this.fonts[i].sansCase.w; + if (node.offsetWidth !== w) { + loadedCount -= 1; + this.fonts[i].loaded = true; + } + } + if (this.fonts[i].loaded) { + this.fonts[i].sansCase.parent.parentNode.removeChild(this.fonts[i].sansCase.parent); + this.fonts[i].monoCase.parent.parentNode.removeChild(this.fonts[i].monoCase.parent); + } + } + } + if (loadedCount !== 0 && Date.now() - this.initTime < maxWaitingTime) { + setTimeout(this.checkLoadedFontsBinded, 20); + } else { + setTimeout(this.setIsLoadedBinded, 10); + } + } + function createHelper(fontData, def) { + var engine = document.body && def ? "svg" : "canvas"; + var helper; + var fontProps = getFontProperties(fontData); + if (engine === "svg") { + var tHelper = createNS("text"); + tHelper.style.fontSize = "100px"; + tHelper.setAttribute("font-family", fontData.fFamily); + tHelper.setAttribute("font-style", fontProps.style); + tHelper.setAttribute("font-weight", fontProps.weight); + tHelper.textContent = "1"; + if (fontData.fClass) { + tHelper.style.fontFamily = "inherit"; + tHelper.setAttribute("class", fontData.fClass); + } else { + tHelper.style.fontFamily = fontData.fFamily; + } + def.appendChild(tHelper); + helper = tHelper; + } else { + var tCanvasHelper = new OffscreenCanvas(500, 500).getContext("2d"); + tCanvasHelper.font = fontProps.style + " " + fontProps.weight + " 100px " + fontData.fFamily; + helper = tCanvasHelper; + } + function measure(text2) { + if (engine === "svg") { + helper.textContent = text2; + return helper.getComputedTextLength(); + } + return helper.measureText(text2).width; + } + return { + measureText: measure + }; + } + function addFonts(fontData, defs) { + if (!fontData) { + this.isLoaded = true; + return; + } + if (this.chars) { + this.isLoaded = true; + this.fonts = fontData.list; + return; + } + if (!document.body) { + this.isLoaded = true; + fontData.list.forEach((data2) => { + data2.helper = createHelper(data2); + data2.cache = {}; + }); + this.fonts = fontData.list; + return; + } + var fontArr = fontData.list; + var i; + var len = fontArr.length; + var _pendingFonts = len; + for (i = 0;i < len; i += 1) { + var shouldLoadFont = true; + var loadedSelector; + var j2; + fontArr[i].loaded = false; + fontArr[i].monoCase = setUpNode(fontArr[i].fFamily, "monospace"); + fontArr[i].sansCase = setUpNode(fontArr[i].fFamily, "sans-serif"); + if (!fontArr[i].fPath) { + fontArr[i].loaded = true; + _pendingFonts -= 1; + } else if (fontArr[i].fOrigin === "p" || fontArr[i].origin === 3) { + loadedSelector = document.querySelectorAll('style[f-forigin="p"][f-family="' + fontArr[i].fFamily + '"], style[f-origin="3"][f-family="' + fontArr[i].fFamily + '"]'); + if (loadedSelector.length > 0) { + shouldLoadFont = false; + } + if (shouldLoadFont) { + var s = createTag("style"); + s.setAttribute("f-forigin", fontArr[i].fOrigin); + s.setAttribute("f-origin", fontArr[i].origin); + s.setAttribute("f-family", fontArr[i].fFamily); + s.type = "text/css"; + s.innerText = "@font-face {font-family: " + fontArr[i].fFamily + "; font-style: normal; src: url('" + fontArr[i].fPath + "');}"; + defs.appendChild(s); + } + } else if (fontArr[i].fOrigin === "g" || fontArr[i].origin === 1) { + loadedSelector = document.querySelectorAll('link[f-forigin="g"], link[f-origin="1"]'); + for (j2 = 0;j2 < loadedSelector.length; j2 += 1) { + if (loadedSelector[j2].href.indexOf(fontArr[i].fPath) !== -1) { + shouldLoadFont = false; + } + } + if (shouldLoadFont) { + var l2 = createTag("link"); + l2.setAttribute("f-forigin", fontArr[i].fOrigin); + l2.setAttribute("f-origin", fontArr[i].origin); + l2.type = "text/css"; + l2.rel = "stylesheet"; + l2.href = fontArr[i].fPath; + document.body.appendChild(l2); + } + } else if (fontArr[i].fOrigin === "t" || fontArr[i].origin === 2) { + loadedSelector = document.querySelectorAll('script[f-forigin="t"], script[f-origin="2"]'); + for (j2 = 0;j2 < loadedSelector.length; j2 += 1) { + if (fontArr[i].fPath === loadedSelector[j2].src) { + shouldLoadFont = false; + } + } + if (shouldLoadFont) { + var sc = createTag("link"); + sc.setAttribute("f-forigin", fontArr[i].fOrigin); + sc.setAttribute("f-origin", fontArr[i].origin); + sc.setAttribute("rel", "stylesheet"); + sc.setAttribute("href", fontArr[i].fPath); + defs.appendChild(sc); + } + } + fontArr[i].helper = createHelper(fontArr[i], defs); + fontArr[i].cache = {}; + this.fonts.push(fontArr[i]); + } + if (_pendingFonts === 0) { + this.isLoaded = true; + } else { + setTimeout(this.checkLoadedFonts.bind(this), 100); + } + } + function addChars(chars) { + if (!chars) { + return; + } + if (!this.chars) { + this.chars = []; + } + var i; + var len = chars.length; + var j2; + var jLen = this.chars.length; + var found; + for (i = 0;i < len; i += 1) { + j2 = 0; + found = false; + while (j2 < jLen) { + if (this.chars[j2].style === chars[i].style && this.chars[j2].fFamily === chars[i].fFamily && this.chars[j2].ch === chars[i].ch) { + found = true; + } + j2 += 1; + } + if (!found) { + this.chars.push(chars[i]); + jLen += 1; + } + } + } + function getCharData(char, style, font) { + var i = 0; + var len = this.chars.length; + while (i < len) { + if (this.chars[i].ch === char && this.chars[i].style === style && this.chars[i].fFamily === font) { + return this.chars[i]; + } + i += 1; + } + if ((typeof char === "string" && char.charCodeAt(0) !== 13 || !char) && console && console.warn && !this._warned) { + this._warned = true; + console.warn("Missing character from exported characters list: ", char, style, font); + } + return emptyChar; + } + function measureText(char, fontName, size) { + var fontData = this.getFontByName(fontName); + var index2 = char.charCodeAt(0); + if (!fontData.cache[index2 + 1]) { + var tHelper = fontData.helper; + if (char === " ") { + var doubleSize = tHelper.measureText("|" + char + "|"); + var singleSize = tHelper.measureText("||"); + fontData.cache[index2 + 1] = (doubleSize - singleSize) / 100; + } else { + fontData.cache[index2 + 1] = tHelper.measureText(char) / 100; + } + } + return fontData.cache[index2 + 1] * size; + } + function getFontByName(name2) { + var i = 0; + var len = this.fonts.length; + while (i < len) { + if (this.fonts[i].fName === name2) { + return this.fonts[i]; + } + i += 1; + } + return this.fonts[0]; + } + function isModifier(firstCharCode, secondCharCode) { + var sum2 = firstCharCode.toString(16) + secondCharCode.toString(16); + return surrogateModifiers.indexOf(sum2) !== -1; + } + function isZeroWidthJoiner(firstCharCode, secondCharCode) { + if (!secondCharCode) { + return firstCharCode === zeroWidthJoiner[1]; + } + return firstCharCode === zeroWidthJoiner[0] && secondCharCode === zeroWidthJoiner[1]; + } + function isCombinedCharacter(char) { + return combinedCharacters.indexOf(char) !== -1; + } + function setIsLoaded() { + this.isLoaded = true; + } + var Font = function() { + this.fonts = []; + this.chars = null; + this.typekitLoaded = 0; + this.isLoaded = false; + this._warned = false; + this.initTime = Date.now(); + this.setIsLoadedBinded = this.setIsLoaded.bind(this); + this.checkLoadedFontsBinded = this.checkLoadedFonts.bind(this); + }; + Font.isModifier = isModifier; + Font.isZeroWidthJoiner = isZeroWidthJoiner; + Font.isCombinedCharacter = isCombinedCharacter; + var fontPrototype = { + addChars, + addFonts, + getCharData, + getFontByName, + measureText, + checkLoadedFonts, + setIsLoaded + }; + Font.prototype = fontPrototype; + return Font; + }(); + RenderableElement.prototype = { + initRenderable: function() { + this.isInRange = false; + this.hidden = false; + this.isTransparent = false; + this.renderableComponents = []; + }, + addRenderableComponent: function(component) { + if (this.renderableComponents.indexOf(component) === -1) { + this.renderableComponents.push(component); + } + }, + removeRenderableComponent: function(component) { + if (this.renderableComponents.indexOf(component) !== -1) { + this.renderableComponents.splice(this.renderableComponents.indexOf(component), 1); + } + }, + prepareRenderableFrame: function(num) { + this.checkLayerLimits(num); + }, + checkTransparency: function() { + if (this.finalTransform.mProp.o.v <= 0) { + if (!this.isTransparent && this.globalData.renderConfig.hideOnTransparent) { + this.isTransparent = true; + this.hide(); + } + } else if (this.isTransparent) { + this.isTransparent = false; + this.show(); + } + }, + checkLayerLimits: function(num) { + if (this.data.ip - this.data.st <= num && this.data.op - this.data.st > num) { + if (this.isInRange !== true) { + this.globalData._mdf = true; + this._mdf = true; + this.isInRange = true; + this.show(); + } + } else if (this.isInRange !== false) { + this.globalData._mdf = true; + this.isInRange = false; + this.hide(); + } + }, + renderRenderable: function() { + var i; + var len = this.renderableComponents.length; + for (i = 0;i < len; i += 1) { + this.renderableComponents[i].renderFrame(this._isFirstFrame); + } + }, + sourceRectAtTime: function() { + return { + top: 0, + left: 0, + width: 100, + height: 100 + }; + }, + getLayerSize: function() { + if (this.data.ty === 5) { + return { w: this.data.textData.width, h: this.data.textData.height }; + } + return { w: this.data.width, h: this.data.height }; + } + }; + const MaskManagerInterface = function() { + function MaskInterface(mask2, data2) { + this._mask = mask2; + this._data = data2; + } + Object.defineProperty(MaskInterface.prototype, "maskPath", { + get: function() { + if (this._mask.prop.k) { + this._mask.prop.getValue(); + } + return this._mask.prop; + } + }); + Object.defineProperty(MaskInterface.prototype, "maskOpacity", { + get: function() { + if (this._mask.op.k) { + this._mask.op.getValue(); + } + return this._mask.op.v * 100; + } + }); + var MaskManager = function(maskManager) { + var _masksInterfaces = createSizedArray(maskManager.viewData.length); + var i; + var len = maskManager.viewData.length; + for (i = 0;i < len; i += 1) { + _masksInterfaces[i] = new MaskInterface(maskManager.viewData[i], maskManager.masksProperties[i]); + } + var maskFunction = function(name2) { + i = 0; + while (i < len) { + if (maskManager.masksProperties[i].nm === name2) { + return _masksInterfaces[i]; + } + i += 1; + } + return null; + }; + return maskFunction; + }; + return MaskManager; + }(); + const ExpressionPropertyInterface = function() { + var defaultUnidimensionalValue = { pv: 0, v: 0, mult: 1 }; + var defaultMultidimensionalValue = { pv: [0, 0, 0], v: [0, 0, 0], mult: 1 }; + function completeProperty(expressionValue, property2, type) { + Object.defineProperty(expressionValue, "velocity", { + get: function() { + return property2.getVelocityAtTime(property2.comp.currentFrame); + } + }); + expressionValue.numKeys = property2.keyframes ? property2.keyframes.length : 0; + expressionValue.key = function(pos) { + if (!expressionValue.numKeys) { + return 0; + } + var value2 = ""; + if ("s" in property2.keyframes[pos - 1]) { + value2 = property2.keyframes[pos - 1].s; + } else if ("e" in property2.keyframes[pos - 2]) { + value2 = property2.keyframes[pos - 2].e; + } else { + value2 = property2.keyframes[pos - 2].s; + } + var valueProp = type === "unidimensional" ? new Number(value2) : Object.assign({}, value2); + valueProp.time = property2.keyframes[pos - 1].t / property2.elem.comp.globalData.frameRate; + valueProp.value = type === "unidimensional" ? value2[0] : value2; + return valueProp; + }; + expressionValue.valueAtTime = property2.getValueAtTime; + expressionValue.speedAtTime = property2.getSpeedAtTime; + expressionValue.velocityAtTime = property2.getVelocityAtTime; + expressionValue.propertyGroup = property2.propertyGroup; + } + function UnidimensionalPropertyInterface(property2) { + if (!property2 || !("pv" in property2)) { + property2 = defaultUnidimensionalValue; + } + var mult = 1 / property2.mult; + var val2 = property2.pv * mult; + var expressionValue = new Number(val2); + expressionValue.value = val2; + completeProperty(expressionValue, property2, "unidimensional"); + return function() { + if (property2.k) { + property2.getValue(); + } + val2 = property2.v * mult; + if (expressionValue.value !== val2) { + expressionValue = new Number(val2); + expressionValue.value = val2; + completeProperty(expressionValue, property2, "unidimensional"); + } + return expressionValue; + }; + } + function MultidimensionalPropertyInterface(property2) { + if (!property2 || !("pv" in property2)) { + property2 = defaultMultidimensionalValue; + } + var mult = 1 / property2.mult; + var len = property2.data && property2.data.l || property2.pv.length; + var expressionValue = createTypedArray("float32", len); + var arrValue = createTypedArray("float32", len); + expressionValue.value = arrValue; + completeProperty(expressionValue, property2, "multidimensional"); + return function() { + if (property2.k) { + property2.getValue(); + } + for (var i = 0;i < len; i += 1) { + arrValue[i] = property2.v[i] * mult; + expressionValue[i] = arrValue[i]; + } + return expressionValue; + }; + } + function defaultGetter() { + return defaultUnidimensionalValue; + } + return function(property2) { + if (!property2) { + return defaultGetter; + } + if (property2.propType === "unidimensional") { + return UnidimensionalPropertyInterface(property2); + } + return MultidimensionalPropertyInterface(property2); + }; + }(); + const TransformExpressionInterface = function() { + return function(transform2) { + function _thisFunction(name2) { + switch (name2) { + case "scale": + case "Scale": + case "ADBE Scale": + case 6: + return _thisFunction.scale; + case "rotation": + case "Rotation": + case "ADBE Rotation": + case "ADBE Rotate Z": + case 10: + return _thisFunction.rotation; + case "ADBE Rotate X": + return _thisFunction.xRotation; + case "ADBE Rotate Y": + return _thisFunction.yRotation; + case "position": + case "Position": + case "ADBE Position": + case 2: + return _thisFunction.position; + case "ADBE Position_0": + return _thisFunction.xPosition; + case "ADBE Position_1": + return _thisFunction.yPosition; + case "ADBE Position_2": + return _thisFunction.zPosition; + case "anchorPoint": + case "AnchorPoint": + case "Anchor Point": + case "ADBE AnchorPoint": + case 1: + return _thisFunction.anchorPoint; + case "opacity": + case "Opacity": + case 11: + return _thisFunction.opacity; + default: + return null; + } + } + Object.defineProperty(_thisFunction, "rotation", { + get: ExpressionPropertyInterface(transform2.r || transform2.rz) + }); + Object.defineProperty(_thisFunction, "zRotation", { + get: ExpressionPropertyInterface(transform2.rz || transform2.r) + }); + Object.defineProperty(_thisFunction, "xRotation", { + get: ExpressionPropertyInterface(transform2.rx) + }); + Object.defineProperty(_thisFunction, "yRotation", { + get: ExpressionPropertyInterface(transform2.ry) + }); + Object.defineProperty(_thisFunction, "scale", { + get: ExpressionPropertyInterface(transform2.s) + }); + var _px; + var _py; + var _pz; + var _transformFactory; + if (transform2.p) { + _transformFactory = ExpressionPropertyInterface(transform2.p); + } else { + _px = ExpressionPropertyInterface(transform2.px); + _py = ExpressionPropertyInterface(transform2.py); + if (transform2.pz) { + _pz = ExpressionPropertyInterface(transform2.pz); + } + } + Object.defineProperty(_thisFunction, "position", { + get: function() { + if (transform2.p) { + return _transformFactory(); + } + return [ + _px(), + _py(), + _pz ? _pz() : 0 + ]; + } + }); + Object.defineProperty(_thisFunction, "xPosition", { + get: ExpressionPropertyInterface(transform2.px) + }); + Object.defineProperty(_thisFunction, "yPosition", { + get: ExpressionPropertyInterface(transform2.py) + }); + Object.defineProperty(_thisFunction, "zPosition", { + get: ExpressionPropertyInterface(transform2.pz) + }); + Object.defineProperty(_thisFunction, "anchorPoint", { + get: ExpressionPropertyInterface(transform2.a) + }); + Object.defineProperty(_thisFunction, "opacity", { + get: ExpressionPropertyInterface(transform2.o) + }); + Object.defineProperty(_thisFunction, "skew", { + get: ExpressionPropertyInterface(transform2.sk) + }); + Object.defineProperty(_thisFunction, "skewAxis", { + get: ExpressionPropertyInterface(transform2.sa) + }); + Object.defineProperty(_thisFunction, "orientation", { + get: ExpressionPropertyInterface(transform2.or) + }); + return _thisFunction; + }; + }(); + const LayerExpressionInterface = function() { + function getMatrix(time2) { + var toWorldMat = new Matrix; + if (time2 !== undefined) { + var propMatrix = this._elem.finalTransform.mProp.getValueAtTime(time2); + propMatrix.clone(toWorldMat); + } else { + var transformMat = this._elem.finalTransform.mProp; + transformMat.applyToMatrix(toWorldMat); + } + return toWorldMat; + } + function toWorldVec(arr, time2) { + var toWorldMat = this.getMatrix(time2); + toWorldMat.props[12] = 0; + toWorldMat.props[13] = 0; + toWorldMat.props[14] = 0; + return this.applyPoint(toWorldMat, arr); + } + function toWorld2(arr, time2) { + var toWorldMat = this.getMatrix(time2); + return this.applyPoint(toWorldMat, arr); + } + function fromWorldVec(arr, time2) { + var toWorldMat = this.getMatrix(time2); + toWorldMat.props[12] = 0; + toWorldMat.props[13] = 0; + toWorldMat.props[14] = 0; + return this.invertPoint(toWorldMat, arr); + } + function fromWorld2(arr, time2) { + var toWorldMat = this.getMatrix(time2); + return this.invertPoint(toWorldMat, arr); + } + function applyPoint(matrix, arr) { + if (this._elem.hierarchy && this._elem.hierarchy.length) { + var i; + var len = this._elem.hierarchy.length; + for (i = 0;i < len; i += 1) { + this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(matrix); + } + } + return matrix.applyToPointArray(arr[0], arr[1], arr[2] || 0); + } + function invertPoint(matrix, arr) { + if (this._elem.hierarchy && this._elem.hierarchy.length) { + var i; + var len = this._elem.hierarchy.length; + for (i = 0;i < len; i += 1) { + this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(matrix); + } + } + return matrix.inversePoint(arr); + } + function fromComp2(arr) { + var toWorldMat = new Matrix; + toWorldMat.reset(); + this._elem.finalTransform.mProp.applyToMatrix(toWorldMat); + if (this._elem.hierarchy && this._elem.hierarchy.length) { + var i; + var len = this._elem.hierarchy.length; + for (i = 0;i < len; i += 1) { + this._elem.hierarchy[i].finalTransform.mProp.applyToMatrix(toWorldMat); + } + return toWorldMat.inversePoint(arr); + } + return toWorldMat.inversePoint(arr); + } + function sampleImage() { + return [1, 1, 1, 1]; + } + return function(elem2) { + var transformInterface; + function _registerMaskInterface(maskManager) { + _thisLayerFunction.mask = new MaskManagerInterface(maskManager, elem2); + } + function _registerEffectsInterface(effects) { + _thisLayerFunction.effect = effects; + } + function _thisLayerFunction(name2) { + switch (name2) { + case "ADBE Root Vectors Group": + case "Contents": + case 2: + return _thisLayerFunction.shapeInterface; + case 1: + case 6: + case "Transform": + case "transform": + case "ADBE Transform Group": + return transformInterface; + case 4: + case "ADBE Effect Parade": + case "effects": + case "Effects": + return _thisLayerFunction.effect; + case "ADBE Text Properties": + return _thisLayerFunction.textInterface; + default: + return null; + } + } + _thisLayerFunction.getMatrix = getMatrix; + _thisLayerFunction.invertPoint = invertPoint; + _thisLayerFunction.applyPoint = applyPoint; + _thisLayerFunction.toWorld = toWorld2; + _thisLayerFunction.toWorldVec = toWorldVec; + _thisLayerFunction.fromWorld = fromWorld2; + _thisLayerFunction.fromWorldVec = fromWorldVec; + _thisLayerFunction.toComp = toWorld2; + _thisLayerFunction.fromComp = fromComp2; + _thisLayerFunction.sampleImage = sampleImage; + _thisLayerFunction.sourceRectAtTime = elem2.sourceRectAtTime.bind(elem2); + _thisLayerFunction._elem = elem2; + transformInterface = TransformExpressionInterface(elem2.finalTransform.mProp); + var anchorPointDescriptor = getDescriptor(transformInterface, "anchorPoint"); + Object.defineProperties(_thisLayerFunction, { + hasParent: { + get: function() { + return elem2.hierarchy.length; + } + }, + parent: { + get: function() { + return elem2.hierarchy[0].layerInterface; + } + }, + rotation: getDescriptor(transformInterface, "rotation"), + scale: getDescriptor(transformInterface, "scale"), + position: getDescriptor(transformInterface, "position"), + opacity: getDescriptor(transformInterface, "opacity"), + anchorPoint: anchorPointDescriptor, + anchor_point: anchorPointDescriptor, + transform: { + get: function() { + return transformInterface; + } + }, + active: { + get: function() { + return elem2.isInRange; + } + } + }); + _thisLayerFunction.startTime = elem2.data.st; + _thisLayerFunction.index = elem2.data.ind; + _thisLayerFunction.source = elem2.data.refId; + _thisLayerFunction.height = elem2.data.ty === 0 ? elem2.data.h : 100; + _thisLayerFunction.width = elem2.data.ty === 0 ? elem2.data.w : 100; + _thisLayerFunction.inPoint = elem2.data.ip / elem2.comp.globalData.frameRate; + _thisLayerFunction.outPoint = elem2.data.op / elem2.comp.globalData.frameRate; + _thisLayerFunction._name = elem2.data.nm; + _thisLayerFunction.registerMaskInterface = _registerMaskInterface; + _thisLayerFunction.registerEffectsInterface = _registerEffectsInterface; + return _thisLayerFunction; + }; + }(); + const propertyGroupFactory = function() { + return function(interfaceFunction, parentPropertyGroup) { + return function(val2) { + val2 = val2 === undefined ? 1 : val2; + if (val2 <= 0) { + return interfaceFunction; + } + return parentPropertyGroup(val2 - 1); + }; + }; + }(); + const PropertyInterface = function() { + return function(propertyName, propertyGroup) { + var interfaceFunction = { + _name: propertyName + }; + function _propertyGroup(val2) { + val2 = val2 === undefined ? 1 : val2; + if (val2 <= 0) { + return interfaceFunction; + } + return propertyGroup(val2 - 1); + } + return _propertyGroup; + }; + }(); + const EffectsExpressionInterface = function() { + var ob2 = { + createEffectsInterface + }; + function createEffectsInterface(elem2, propertyGroup) { + if (elem2.effectsManager) { + var effectElements = []; + var effectsData = elem2.data.ef; + var i; + var len = elem2.effectsManager.effectElements.length; + for (i = 0;i < len; i += 1) { + effectElements.push(createGroupInterface(effectsData[i], elem2.effectsManager.effectElements[i], propertyGroup, elem2)); + } + var effects = elem2.data.ef || []; + var groupInterface = function(name2) { + i = 0; + len = effects.length; + while (i < len) { + if (name2 === effects[i].nm || name2 === effects[i].mn || name2 === effects[i].ix) { + return effectElements[i]; + } + i += 1; + } + return null; + }; + Object.defineProperty(groupInterface, "numProperties", { + get: function() { + return effects.length; + } + }); + return groupInterface; + } + return null; + } + function createGroupInterface(data2, elements, propertyGroup, elem2) { + function groupInterface(name2) { + var effects = data2.ef; + var i2 = 0; + var len2 = effects.length; + while (i2 < len2) { + if (name2 === effects[i2].nm || name2 === effects[i2].mn || name2 === effects[i2].ix) { + if (effects[i2].ty === 5) { + return effectElements[i2]; + } + return effectElements[i2](); + } + i2 += 1; + } + throw new Error; + } + var _propertyGroup = propertyGroupFactory(groupInterface, propertyGroup); + var effectElements = []; + var i; + var len = data2.ef.length; + for (i = 0;i < len; i += 1) { + if (data2.ef[i].ty === 5) { + effectElements.push(createGroupInterface(data2.ef[i], elements.effectElements[i], elements.effectElements[i].propertyGroup, elem2)); + } else { + effectElements.push(createValueInterface(elements.effectElements[i], data2.ef[i].ty, elem2, _propertyGroup)); + } + } + if (data2.mn === "ADBE Color Control") { + Object.defineProperty(groupInterface, "color", { + get: function() { + return effectElements[0](); + } + }); + } + Object.defineProperties(groupInterface, { + numProperties: { + get: function() { + return data2.np; + } + }, + _name: { value: data2.nm }, + propertyGroup: { value: _propertyGroup } + }); + groupInterface.enabled = data2.en !== 0; + groupInterface.active = groupInterface.enabled; + return groupInterface; + } + function createValueInterface(element, type, elem2, propertyGroup) { + var expressionProperty = ExpressionPropertyInterface(element.p); + function interfaceFunction() { + if (type === 10) { + return elem2.comp.compInterface(element.p.v); + } + return expressionProperty(); + } + if (element.p.setGroupProperty) { + element.p.setGroupProperty(PropertyInterface("", propertyGroup)); + } + return interfaceFunction; + } + return ob2; + }(); + const CompExpressionInterface = function() { + return function(comp2) { + function _thisLayerFunction(name2) { + var i = 0; + var len = comp2.layers.length; + while (i < len) { + if (comp2.layers[i].nm === name2 || comp2.layers[i].ind === name2) { + return comp2.elements[i].layerInterface; + } + i += 1; + } + return null; + } + Object.defineProperty(_thisLayerFunction, "_name", { value: comp2.data.nm }); + _thisLayerFunction.layer = _thisLayerFunction; + _thisLayerFunction.pixelAspect = 1; + _thisLayerFunction.height = comp2.data.h || comp2.globalData.compSize.h; + _thisLayerFunction.width = comp2.data.w || comp2.globalData.compSize.w; + _thisLayerFunction.pixelAspect = 1; + _thisLayerFunction.frameDuration = 1 / comp2.globalData.frameRate; + _thisLayerFunction.displayStartTime = 0; + _thisLayerFunction.numLayers = comp2.layers.length; + return _thisLayerFunction; + }; + }(); + const ShapePathInterface = function() { + return function pathInterfaceFactory(shape, view, propertyGroup) { + var prop = view.sh; + function interfaceFunction(val2) { + if (val2 === "Shape" || val2 === "shape" || val2 === "Path" || val2 === "path" || val2 === "ADBE Vector Shape" || val2 === 2) { + return interfaceFunction.path; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + prop.setGroupProperty(PropertyInterface("Path", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + path: { + get: function() { + if (prop.k) { + prop.getValue(); + } + return prop; + } + }, + shape: { + get: function() { + if (prop.k) { + prop.getValue(); + } + return prop; + } + }, + _name: { value: shape.nm }, + ix: { value: shape.ix }, + propertyIndex: { value: shape.ix }, + mn: { value: shape.mn }, + propertyGroup: { value: propertyGroup } + }); + return interfaceFunction; + }; + }(); + const ShapeExpressionInterface = function() { + function iterateElements(shapes, view, propertyGroup) { + var arr = []; + var i; + var len = shapes ? shapes.length : 0; + for (i = 0;i < len; i += 1) { + if (shapes[i].ty === "gr") { + arr.push(groupInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "fl") { + arr.push(fillInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "st") { + arr.push(strokeInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "tm") { + arr.push(trimInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "tr") { + } else if (shapes[i].ty === "el") { + arr.push(ellipseInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "sr") { + arr.push(starInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "sh") { + arr.push(ShapePathInterface(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "rc") { + arr.push(rectInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "rd") { + arr.push(roundedInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "rp") { + arr.push(repeaterInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else if (shapes[i].ty === "gf") { + arr.push(gradientFillInterfaceFactory(shapes[i], view[i], propertyGroup)); + } else { + arr.push(defaultInterfaceFactory(shapes[i], view[i], propertyGroup)); + } + } + return arr; + } + function contentsInterfaceFactory(shape, view, propertyGroup) { + var interfaces; + var interfaceFunction = function _interfaceFunction(value2) { + var i = 0; + var len = interfaces.length; + while (i < len) { + if (interfaces[i]._name === value2 || interfaces[i].mn === value2 || interfaces[i].propertyIndex === value2 || interfaces[i].ix === value2 || interfaces[i].ind === value2) { + return interfaces[i]; + } + i += 1; + } + if (typeof value2 === "number") { + return interfaces[value2 - 1]; + } + return null; + }; + interfaceFunction.propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + interfaces = iterateElements(shape.it, view.it, interfaceFunction.propertyGroup); + interfaceFunction.numProperties = interfaces.length; + var transformInterface = transformInterfaceFactory(shape.it[shape.it.length - 1], view.it[view.it.length - 1], interfaceFunction.propertyGroup); + interfaceFunction.transform = transformInterface; + interfaceFunction.propertyIndex = shape.cix; + interfaceFunction._name = shape.nm; + return interfaceFunction; + } + function groupInterfaceFactory(shape, view, propertyGroup) { + var interfaceFunction = function _interfaceFunction(value2) { + switch (value2) { + case "ADBE Vectors Group": + case "Contents": + case 2: + return interfaceFunction.content; + default: + return interfaceFunction.transform; + } + }; + interfaceFunction.propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var content2 = contentsInterfaceFactory(shape, view, interfaceFunction.propertyGroup); + var transformInterface = transformInterfaceFactory(shape.it[shape.it.length - 1], view.it[view.it.length - 1], interfaceFunction.propertyGroup); + interfaceFunction.content = content2; + interfaceFunction.transform = transformInterface; + Object.defineProperty(interfaceFunction, "_name", { + get: function() { + return shape.nm; + } + }); + interfaceFunction.numProperties = shape.np; + interfaceFunction.propertyIndex = shape.ix; + interfaceFunction.nm = shape.nm; + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function fillInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(val2) { + if (val2 === "Color" || val2 === "color") { + return interfaceFunction.color; + } + if (val2 === "Opacity" || val2 === "opacity") { + return interfaceFunction.opacity; + } + return null; + } + Object.defineProperties(interfaceFunction, { + color: { + get: ExpressionPropertyInterface(view.c) + }, + opacity: { + get: ExpressionPropertyInterface(view.o) + }, + _name: { value: shape.nm }, + mn: { value: shape.mn } + }); + view.c.setGroupProperty(PropertyInterface("Color", propertyGroup)); + view.o.setGroupProperty(PropertyInterface("Opacity", propertyGroup)); + return interfaceFunction; + } + function gradientFillInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(val2) { + if (val2 === "Start Point" || val2 === "start point") { + return interfaceFunction.startPoint; + } + if (val2 === "End Point" || val2 === "end point") { + return interfaceFunction.endPoint; + } + if (val2 === "Opacity" || val2 === "opacity") { + return interfaceFunction.opacity; + } + return null; + } + Object.defineProperties(interfaceFunction, { + startPoint: { + get: ExpressionPropertyInterface(view.s) + }, + endPoint: { + get: ExpressionPropertyInterface(view.e) + }, + opacity: { + get: ExpressionPropertyInterface(view.o) + }, + type: { + get: function() { + return "a"; + } + }, + _name: { value: shape.nm }, + mn: { value: shape.mn } + }); + view.s.setGroupProperty(PropertyInterface("Start Point", propertyGroup)); + view.e.setGroupProperty(PropertyInterface("End Point", propertyGroup)); + view.o.setGroupProperty(PropertyInterface("Opacity", propertyGroup)); + return interfaceFunction; + } + function defaultInterfaceFactory() { + function interfaceFunction() { + return null; + } + return interfaceFunction; + } + function strokeInterfaceFactory(shape, view, propertyGroup) { + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var _dashPropertyGroup = propertyGroupFactory(dashOb, _propertyGroup); + function addPropertyToDashOb(i2) { + Object.defineProperty(dashOb, shape.d[i2].nm, { + get: ExpressionPropertyInterface(view.d.dataProps[i2].p) + }); + } + var i; + var len = shape.d ? shape.d.length : 0; + var dashOb = {}; + for (i = 0;i < len; i += 1) { + addPropertyToDashOb(i); + view.d.dataProps[i].p.setGroupProperty(_dashPropertyGroup); + } + function interfaceFunction(val2) { + if (val2 === "Color" || val2 === "color") { + return interfaceFunction.color; + } + if (val2 === "Opacity" || val2 === "opacity") { + return interfaceFunction.opacity; + } + if (val2 === "Stroke Width" || val2 === "stroke width") { + return interfaceFunction.strokeWidth; + } + return null; + } + Object.defineProperties(interfaceFunction, { + color: { + get: ExpressionPropertyInterface(view.c) + }, + opacity: { + get: ExpressionPropertyInterface(view.o) + }, + strokeWidth: { + get: ExpressionPropertyInterface(view.w) + }, + dash: { + get: function() { + return dashOb; + } + }, + _name: { value: shape.nm }, + mn: { value: shape.mn } + }); + view.c.setGroupProperty(PropertyInterface("Color", _propertyGroup)); + view.o.setGroupProperty(PropertyInterface("Opacity", _propertyGroup)); + view.w.setGroupProperty(PropertyInterface("Stroke Width", _propertyGroup)); + return interfaceFunction; + } + function trimInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(val2) { + if (val2 === shape.e.ix || val2 === "End" || val2 === "end") { + return interfaceFunction.end; + } + if (val2 === shape.s.ix) { + return interfaceFunction.start; + } + if (val2 === shape.o.ix) { + return interfaceFunction.offset; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + interfaceFunction.propertyIndex = shape.ix; + view.s.setGroupProperty(PropertyInterface("Start", _propertyGroup)); + view.e.setGroupProperty(PropertyInterface("End", _propertyGroup)); + view.o.setGroupProperty(PropertyInterface("Offset", _propertyGroup)); + interfaceFunction.propertyIndex = shape.ix; + interfaceFunction.propertyGroup = propertyGroup; + Object.defineProperties(interfaceFunction, { + start: { + get: ExpressionPropertyInterface(view.s) + }, + end: { + get: ExpressionPropertyInterface(view.e) + }, + offset: { + get: ExpressionPropertyInterface(view.o) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function transformInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.a.ix === value2 || value2 === "Anchor Point") { + return interfaceFunction.anchorPoint; + } + if (shape.o.ix === value2 || value2 === "Opacity") { + return interfaceFunction.opacity; + } + if (shape.p.ix === value2 || value2 === "Position") { + return interfaceFunction.position; + } + if (shape.r.ix === value2 || value2 === "Rotation" || value2 === "ADBE Vector Rotation") { + return interfaceFunction.rotation; + } + if (shape.s.ix === value2 || value2 === "Scale") { + return interfaceFunction.scale; + } + if (shape.sk && shape.sk.ix === value2 || value2 === "Skew") { + return interfaceFunction.skew; + } + if (shape.sa && shape.sa.ix === value2 || value2 === "Skew Axis") { + return interfaceFunction.skewAxis; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + view.transform.mProps.o.setGroupProperty(PropertyInterface("Opacity", _propertyGroup)); + view.transform.mProps.p.setGroupProperty(PropertyInterface("Position", _propertyGroup)); + view.transform.mProps.a.setGroupProperty(PropertyInterface("Anchor Point", _propertyGroup)); + view.transform.mProps.s.setGroupProperty(PropertyInterface("Scale", _propertyGroup)); + view.transform.mProps.r.setGroupProperty(PropertyInterface("Rotation", _propertyGroup)); + if (view.transform.mProps.sk) { + view.transform.mProps.sk.setGroupProperty(PropertyInterface("Skew", _propertyGroup)); + view.transform.mProps.sa.setGroupProperty(PropertyInterface("Skew Angle", _propertyGroup)); + } + view.transform.op.setGroupProperty(PropertyInterface("Opacity", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + opacity: { + get: ExpressionPropertyInterface(view.transform.mProps.o) + }, + position: { + get: ExpressionPropertyInterface(view.transform.mProps.p) + }, + anchorPoint: { + get: ExpressionPropertyInterface(view.transform.mProps.a) + }, + scale: { + get: ExpressionPropertyInterface(view.transform.mProps.s) + }, + rotation: { + get: ExpressionPropertyInterface(view.transform.mProps.r) + }, + skew: { + get: ExpressionPropertyInterface(view.transform.mProps.sk) + }, + skewAxis: { + get: ExpressionPropertyInterface(view.transform.mProps.sa) + }, + _name: { value: shape.nm } + }); + interfaceFunction.ty = "tr"; + interfaceFunction.mn = shape.mn; + interfaceFunction.propertyGroup = propertyGroup; + return interfaceFunction; + } + function ellipseInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.p.ix === value2) { + return interfaceFunction.position; + } + if (shape.s.ix === value2) { + return interfaceFunction.size; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + interfaceFunction.propertyIndex = shape.ix; + var prop = view.sh.ty === "tm" ? view.sh.prop : view.sh; + prop.s.setGroupProperty(PropertyInterface("Size", _propertyGroup)); + prop.p.setGroupProperty(PropertyInterface("Position", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + size: { + get: ExpressionPropertyInterface(prop.s) + }, + position: { + get: ExpressionPropertyInterface(prop.p) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function starInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.p.ix === value2) { + return interfaceFunction.position; + } + if (shape.r.ix === value2) { + return interfaceFunction.rotation; + } + if (shape.pt.ix === value2) { + return interfaceFunction.points; + } + if (shape.or.ix === value2 || value2 === "ADBE Vector Star Outer Radius") { + return interfaceFunction.outerRadius; + } + if (shape.os.ix === value2) { + return interfaceFunction.outerRoundness; + } + if (shape.ir && (shape.ir.ix === value2 || value2 === "ADBE Vector Star Inner Radius")) { + return interfaceFunction.innerRadius; + } + if (shape.is && shape.is.ix === value2) { + return interfaceFunction.innerRoundness; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var prop = view.sh.ty === "tm" ? view.sh.prop : view.sh; + interfaceFunction.propertyIndex = shape.ix; + prop.or.setGroupProperty(PropertyInterface("Outer Radius", _propertyGroup)); + prop.os.setGroupProperty(PropertyInterface("Outer Roundness", _propertyGroup)); + prop.pt.setGroupProperty(PropertyInterface("Points", _propertyGroup)); + prop.p.setGroupProperty(PropertyInterface("Position", _propertyGroup)); + prop.r.setGroupProperty(PropertyInterface("Rotation", _propertyGroup)); + if (shape.ir) { + prop.ir.setGroupProperty(PropertyInterface("Inner Radius", _propertyGroup)); + prop.is.setGroupProperty(PropertyInterface("Inner Roundness", _propertyGroup)); + } + Object.defineProperties(interfaceFunction, { + position: { + get: ExpressionPropertyInterface(prop.p) + }, + rotation: { + get: ExpressionPropertyInterface(prop.r) + }, + points: { + get: ExpressionPropertyInterface(prop.pt) + }, + outerRadius: { + get: ExpressionPropertyInterface(prop.or) + }, + outerRoundness: { + get: ExpressionPropertyInterface(prop.os) + }, + innerRadius: { + get: ExpressionPropertyInterface(prop.ir) + }, + innerRoundness: { + get: ExpressionPropertyInterface(prop.is) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function rectInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.p.ix === value2) { + return interfaceFunction.position; + } + if (shape.r.ix === value2) { + return interfaceFunction.roundness; + } + if (shape.s.ix === value2 || value2 === "Size" || value2 === "ADBE Vector Rect Size") { + return interfaceFunction.size; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var prop = view.sh.ty === "tm" ? view.sh.prop : view.sh; + interfaceFunction.propertyIndex = shape.ix; + prop.p.setGroupProperty(PropertyInterface("Position", _propertyGroup)); + prop.s.setGroupProperty(PropertyInterface("Size", _propertyGroup)); + prop.r.setGroupProperty(PropertyInterface("Rotation", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + position: { + get: ExpressionPropertyInterface(prop.p) + }, + roundness: { + get: ExpressionPropertyInterface(prop.r) + }, + size: { + get: ExpressionPropertyInterface(prop.s) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function roundedInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.r.ix === value2 || value2 === "Round Corners 1") { + return interfaceFunction.radius; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var prop = view; + interfaceFunction.propertyIndex = shape.ix; + prop.rd.setGroupProperty(PropertyInterface("Radius", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + radius: { + get: ExpressionPropertyInterface(prop.rd) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + function repeaterInterfaceFactory(shape, view, propertyGroup) { + function interfaceFunction(value2) { + if (shape.c.ix === value2 || value2 === "Copies") { + return interfaceFunction.copies; + } + if (shape.o.ix === value2 || value2 === "Offset") { + return interfaceFunction.offset; + } + return null; + } + var _propertyGroup = propertyGroupFactory(interfaceFunction, propertyGroup); + var prop = view; + interfaceFunction.propertyIndex = shape.ix; + prop.c.setGroupProperty(PropertyInterface("Copies", _propertyGroup)); + prop.o.setGroupProperty(PropertyInterface("Offset", _propertyGroup)); + Object.defineProperties(interfaceFunction, { + copies: { + get: ExpressionPropertyInterface(prop.c) + }, + offset: { + get: ExpressionPropertyInterface(prop.o) + }, + _name: { value: shape.nm } + }); + interfaceFunction.mn = shape.mn; + return interfaceFunction; + } + return function(shapes, view, propertyGroup) { + var interfaces; + function _interfaceFunction(value2) { + if (typeof value2 === "number") { + value2 = value2 === undefined ? 1 : value2; + if (value2 === 0) { + return propertyGroup; + } + return interfaces[value2 - 1]; + } + var i = 0; + var len = interfaces.length; + while (i < len) { + if (interfaces[i]._name === value2) { + return interfaces[i]; + } + i += 1; + } + return null; + } + function parentGroupWrapper() { + return propertyGroup; + } + _interfaceFunction.propertyGroup = propertyGroupFactory(_interfaceFunction, parentGroupWrapper); + interfaces = iterateElements(shapes, view, _interfaceFunction.propertyGroup); + _interfaceFunction.numProperties = interfaces.length; + _interfaceFunction._name = "Contents"; + return _interfaceFunction; + }; + }(); + const TextExpressionInterface = function() { + return function(elem2) { + var _prevValue; + var _sourceText; + function _thisLayerFunction(name2) { + switch (name2) { + case "ADBE Text Document": + return _thisLayerFunction.sourceText; + default: + return null; + } + } + Object.defineProperty(_thisLayerFunction, "sourceText", { + get: function() { + elem2.textProperty.getValue(); + var stringValue = elem2.textProperty.currentData.t; + if (stringValue !== _prevValue) { + elem2.textProperty.currentData.t = _prevValue; + _sourceText = new String(stringValue); + _sourceText.value = stringValue || new String(stringValue); + } + return _sourceText; + } + }); + return _thisLayerFunction; + }; + }(); + const getBlendMode = function() { + var blendModeEnums = { + 0: "source-over", + 1: "multiply", + 2: "screen", + 3: "overlay", + 4: "darken", + 5: "lighten", + 6: "color-dodge", + 7: "color-burn", + 8: "hard-light", + 9: "soft-light", + 10: "difference", + 11: "exclusion", + 12: "hue", + 13: "saturation", + 14: "color", + 15: "luminosity" + }; + return function(mode) { + return blendModeEnums[mode] || ""; + }; + }(); + extendPrototype([DynamicPropertyContainer], GroupEffect); + GroupEffect.prototype.getValue = GroupEffect.prototype.iterateDynamicProperties; + GroupEffect.prototype.init = function(data2, element) { + this.data = data2; + this.effectElements = []; + this.initDynamicPropertyContainer(element); + var i; + var len = this.data.ef.length; + var eff; + var effects = this.data.ef; + for (i = 0;i < len; i += 1) { + eff = null; + switch (effects[i].ty) { + case 0: + eff = new SliderEffect(effects[i], element, this); + break; + case 1: + eff = new AngleEffect(effects[i], element, this); + break; + case 2: + eff = new ColorEffect(effects[i], element, this); + break; + case 3: + eff = new PointEffect(effects[i], element, this); + break; + case 4: + case 7: + eff = new CheckboxEffect(effects[i], element, this); + break; + case 10: + eff = new LayerIndexEffect(effects[i], element, this); + break; + case 11: + eff = new MaskIndexEffect(effects[i], element, this); + break; + case 5: + eff = new EffectsManager(effects[i], element, this); + break; + default: + eff = new NoValueEffect(effects[i], element, this); + break; + } + if (eff) { + this.effectElements.push(eff); + } + } + }; + BaseElement.prototype = { + checkMasks: function() { + if (!this.data.hasMask) { + return false; + } + var i = 0; + var len = this.data.masksProperties.length; + while (i < len) { + if (this.data.masksProperties[i].mode !== "n" && this.data.masksProperties[i].cl !== false) { + return true; + } + i += 1; + } + return false; + }, + initExpressions: function() { + this.layerInterface = LayerExpressionInterface(this); + if (this.data.hasMask && this.maskManager) { + this.layerInterface.registerMaskInterface(this.maskManager); + } + var effectsInterface = EffectsExpressionInterface.createEffectsInterface(this, this.layerInterface); + this.layerInterface.registerEffectsInterface(effectsInterface); + if (this.data.ty === 0 || this.data.xt) { + this.compInterface = CompExpressionInterface(this); + } else if (this.data.ty === 4) { + this.layerInterface.shapeInterface = ShapeExpressionInterface(this.shapesData, this.itemsData, this.layerInterface); + this.layerInterface.content = this.layerInterface.shapeInterface; + } else if (this.data.ty === 5) { + this.layerInterface.textInterface = TextExpressionInterface(this); + this.layerInterface.text = this.layerInterface.textInterface; + } + }, + setBlendMode: function() { + var blendModeValue = getBlendMode(this.data.bm); + var elem2 = this.baseElement || this.layerElement; + elem2.style["mix-blend-mode"] = blendModeValue; + }, + initBaseData: function(data2, globalData2, comp2) { + this.globalData = globalData2; + this.comp = comp2; + this.data = data2; + this.layerId = createElementID(); + if (!this.data.sr) { + this.data.sr = 1; + } + this.effectsManager = new EffectsManager(this.data, this, this.dynamicProperties); + }, + getType: function() { + return this.type; + }, + sourceRectAtTime: function() { + } + }; + FrameElement.prototype = { + initFrame: function() { + this._isFirstFrame = false; + this.dynamicProperties = []; + this._mdf = false; + }, + prepareProperties: function(num, isVisible) { + var i; + var len = this.dynamicProperties.length; + for (i = 0;i < len; i += 1) { + if (isVisible || this._isParent && this.dynamicProperties[i].propType === "transform") { + this.dynamicProperties[i].getValue(); + if (this.dynamicProperties[i]._mdf) { + this.globalData._mdf = true; + this._mdf = true; + } + } + } + }, + addDynamicProperty: function(prop) { + if (this.dynamicProperties.indexOf(prop) === -1) { + this.dynamicProperties.push(prop); + } + } + }; + const FootageInterface = function() { + var outlineInterfaceFactory = function(elem2) { + var currentPropertyName = ""; + var currentProperty = elem2.getFootageData(); + function init() { + currentPropertyName = ""; + currentProperty = elem2.getFootageData(); + return searchProperty; + } + function searchProperty(value2) { + if (currentProperty[value2]) { + currentPropertyName = value2; + currentProperty = currentProperty[value2]; + if (typeof currentProperty === "object") { + return searchProperty; + } + return currentProperty; + } + var propertyNameIndex = value2.indexOf(currentPropertyName); + if (propertyNameIndex !== -1) { + var index2 = parseInt(value2.substr(propertyNameIndex + currentPropertyName.length), 10); + currentProperty = currentProperty[index2]; + if (typeof currentProperty === "object") { + return searchProperty; + } + return currentProperty; + } + return ""; + } + return init; + }; + var dataInterfaceFactory = function(elem2) { + function interfaceFunction(value2) { + if (value2 === "Outline") { + return interfaceFunction.outlineInterface(); + } + return null; + } + interfaceFunction._name = "Outline"; + interfaceFunction.outlineInterface = outlineInterfaceFactory(elem2); + return interfaceFunction; + }; + return function(elem2) { + function _interfaceFunction(value2) { + if (value2 === "Data") { + return _interfaceFunction.dataInterface; + } + return null; + } + _interfaceFunction._name = "Data"; + _interfaceFunction.dataInterface = dataInterfaceFactory(elem2); + return _interfaceFunction; + }; + }(); + FootageElement.prototype.prepareFrame = function() { + }; + extendPrototype([RenderableElement, BaseElement, FrameElement], FootageElement); + FootageElement.prototype.getBaseElement = function() { + return null; + }; + FootageElement.prototype.renderFrame = function() { + }; + FootageElement.prototype.destroy = function() { + }; + FootageElement.prototype.initExpressions = function() { + this.layerInterface = FootageInterface(this); + }; + FootageElement.prototype.getFootageData = function() { + return this.footageData; + }; + AudioElement.prototype.prepareFrame = function(num) { + this.prepareRenderableFrame(num, true); + this.prepareProperties(num, true); + if (!this.tm._placeholder) { + var timeRemapped = this.tm.v; + this._currentTime = timeRemapped; + } else { + this._currentTime = num / this.data.sr; + } + this._volume = this.lv.v[0]; + var totalVolume = this._volume * this._volumeMultiplier; + if (this._previousVolume !== totalVolume) { + this._previousVolume = totalVolume; + this.audio.volume(totalVolume); + } + }; + extendPrototype([RenderableElement, BaseElement, FrameElement], AudioElement); + AudioElement.prototype.renderFrame = function() { + if (this.isInRange && this._canPlay) { + if (!this._isPlaying) { + this.audio.play(); + this.audio.seek(this._currentTime / this.globalData.frameRate); + this._isPlaying = true; + } else if (!this.audio.playing() || Math.abs(this._currentTime / this.globalData.frameRate - this.audio.seek()) > 0.1) { + this.audio.seek(this._currentTime / this.globalData.frameRate); + } + } + }; + AudioElement.prototype.show = function() { + }; + AudioElement.prototype.hide = function() { + this.audio.pause(); + this._isPlaying = false; + }; + AudioElement.prototype.pause = function() { + this.audio.pause(); + this._isPlaying = false; + this._canPlay = false; + }; + AudioElement.prototype.resume = function() { + this._canPlay = true; + }; + AudioElement.prototype.setRate = function(rateValue) { + this.audio.rate(rateValue); + }; + AudioElement.prototype.volume = function(volumeValue) { + this._volumeMultiplier = volumeValue; + this._previousVolume = volumeValue * this._volume; + this.audio.volume(this._previousVolume); + }; + AudioElement.prototype.getBaseElement = function() { + return null; + }; + AudioElement.prototype.destroy = function() { + }; + AudioElement.prototype.sourceRectAtTime = function() { + }; + AudioElement.prototype.initExpressions = function() { + }; + BaseRenderer.prototype.checkLayers = function(num) { + var i; + var len = this.layers.length; + var data2; + this.completeLayers = true; + for (i = len - 1;i >= 0; i -= 1) { + if (!this.elements[i]) { + data2 = this.layers[i]; + if (data2.ip - data2.st <= num - this.layers[i].st && data2.op - data2.st > num - this.layers[i].st) { + this.buildItem(i); + } + } + this.completeLayers = this.elements[i] ? this.completeLayers : false; + } + this.checkPendingElements(); + }; + BaseRenderer.prototype.createItem = function(layer) { + switch (layer.ty) { + case 2: + return this.createImage(layer); + case 0: + return this.createComp(layer); + case 1: + return this.createSolid(layer); + case 3: + return this.createNull(layer); + case 4: + return this.createShape(layer); + case 5: + return this.createText(layer); + case 6: + return this.createAudio(layer); + case 13: + return this.createCamera(layer); + case 15: + return this.createFootage(layer); + default: + return this.createNull(layer); + } + }; + BaseRenderer.prototype.createCamera = function() { + throw new Error("You're using a 3d camera. Try the html renderer."); + }; + BaseRenderer.prototype.createAudio = function(data2) { + return new AudioElement(data2, this.globalData, this); + }; + BaseRenderer.prototype.createFootage = function(data2) { + return new FootageElement(data2, this.globalData, this); + }; + BaseRenderer.prototype.buildAllItems = function() { + var i; + var len = this.layers.length; + for (i = 0;i < len; i += 1) { + this.buildItem(i); + } + this.checkPendingElements(); + }; + BaseRenderer.prototype.includeLayers = function(newLayers) { + this.completeLayers = false; + var i; + var len = newLayers.length; + var j2; + var jLen = this.layers.length; + for (i = 0;i < len; i += 1) { + j2 = 0; + while (j2 < jLen) { + if (this.layers[j2].id === newLayers[i].id) { + this.layers[j2] = newLayers[i]; + break; + } + j2 += 1; + } + } + }; + BaseRenderer.prototype.setProjectInterface = function(pInterface) { + this.globalData.projectInterface = pInterface; + }; + BaseRenderer.prototype.initItems = function() { + if (!this.globalData.progressiveLoad) { + this.buildAllItems(); + } + }; + BaseRenderer.prototype.buildElementParenting = function(element, parentName, hierarchy) { + var elements = this.elements; + var layers = this.layers; + var i = 0; + var len = layers.length; + while (i < len) { + if (layers[i].ind == parentName) { + if (!elements[i] || elements[i] === true) { + this.buildItem(i); + this.addPendingElement(element); + } else { + hierarchy.push(elements[i]); + elements[i].setAsParent(); + if (layers[i].parent !== undefined) { + this.buildElementParenting(element, layers[i].parent, hierarchy); + } else { + element.setHierarchy(hierarchy); + } + } + } + i += 1; + } + }; + BaseRenderer.prototype.addPendingElement = function(element) { + this.pendingElements.push(element); + }; + BaseRenderer.prototype.searchExtraCompositions = function(assets) { + var i; + var len = assets.length; + for (i = 0;i < len; i += 1) { + if (assets[i].xt) { + var comp2 = this.createComp(assets[i]); + comp2.initExpressions(); + this.globalData.projectInterface.registerComposition(comp2); + } + } + }; + BaseRenderer.prototype.getElementByPath = function(path) { + var pathValue = path.shift(); + var element; + if (typeof pathValue === "number") { + element = this.elements[pathValue]; + } else { + var i; + var len = this.elements.length; + for (i = 0;i < len; i += 1) { + if (this.elements[i].data.nm === pathValue) { + element = this.elements[i]; + break; + } + } + } + if (path.length === 0) { + return element; + } + return element.getElementByPath(path); + }; + BaseRenderer.prototype.setupGlobalData = function(animData, fontsContainer) { + this.globalData.fontManager = new FontManager; + this.globalData.fontManager.addChars(animData.chars); + this.globalData.fontManager.addFonts(animData.fonts, fontsContainer); + this.globalData.getAssetData = this.animationItem.getAssetData.bind(this.animationItem); + this.globalData.getAssetsPath = this.animationItem.getAssetsPath.bind(this.animationItem); + this.globalData.imageLoader = this.animationItem.imagePreloader; + this.globalData.audioController = this.animationItem.audioController; + this.globalData.frameId = 0; + this.globalData.frameRate = animData.fr; + this.globalData.nm = animData.nm; + this.globalData.compSize = { + w: animData.w, + h: animData.h + }; + }; + TransformElement.prototype = { + initTransform: function() { + this.finalTransform = { + mProp: this.data.ks ? TransformPropertyFactory.getTransformProperty(this, this.data.ks, this) : { o: 0 }, + _matMdf: false, + _opMdf: false, + mat: new Matrix + }; + if (this.data.ao) { + this.finalTransform.mProp.autoOriented = true; + } + if (this.data.ty !== 11) { + } + }, + renderTransform: function() { + this.finalTransform._opMdf = this.finalTransform.mProp.o._mdf || this._isFirstFrame; + this.finalTransform._matMdf = this.finalTransform.mProp._mdf || this._isFirstFrame; + if (this.hierarchy) { + var mat; + var finalMat = this.finalTransform.mat; + var i = 0; + var len = this.hierarchy.length; + if (!this.finalTransform._matMdf) { + while (i < len) { + if (this.hierarchy[i].finalTransform.mProp._mdf) { + this.finalTransform._matMdf = true; + break; + } + i += 1; + } + } + if (this.finalTransform._matMdf) { + mat = this.finalTransform.mProp.v.props; + finalMat.cloneFromProps(mat); + for (i = 0;i < len; i += 1) { + mat = this.hierarchy[i].finalTransform.mProp.v.props; + finalMat.transform(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5], mat[6], mat[7], mat[8], mat[9], mat[10], mat[11], mat[12], mat[13], mat[14], mat[15]); + } + } + } + }, + globalToLocal: function(pt) { + var transforms = []; + transforms.push(this.finalTransform); + var flag = true; + var comp2 = this.comp; + while (flag) { + if (comp2.finalTransform) { + if (comp2.data.hasMask) { + transforms.splice(0, 0, comp2.finalTransform); + } + comp2 = comp2.comp; + } else { + flag = false; + } + } + var i; + var len = transforms.length; + var ptNew; + for (i = 0;i < len; i += 1) { + ptNew = transforms[i].mat.applyToPointArray(0, 0, 0); + pt = [pt[0] - ptNew[0], pt[1] - ptNew[1], 0]; + } + return pt; + }, + mHelper: new Matrix + }; + MaskElement.prototype.getMaskProperty = function(pos) { + return this.viewData[pos].prop; + }; + MaskElement.prototype.renderFrame = function(isFirstFrame) { + var finalMat = this.element.finalTransform.mat; + var i; + var len = this.masksProperties.length; + for (i = 0;i < len; i += 1) { + if (this.viewData[i].prop._mdf || isFirstFrame) { + this.drawPath(this.masksProperties[i], this.viewData[i].prop.v, this.viewData[i]); + } + if (this.viewData[i].op._mdf || isFirstFrame) { + this.viewData[i].elem.setAttribute("fill-opacity", this.viewData[i].op.v); + } + if (this.masksProperties[i].mode !== "n") { + if (this.viewData[i].invRect && (this.element.finalTransform.mProp._mdf || isFirstFrame)) { + this.viewData[i].invRect.setAttribute("transform", finalMat.getInverseMatrix().to2dCSS()); + } + if (this.storedData[i].x && (this.storedData[i].x._mdf || isFirstFrame)) { + var feMorph = this.storedData[i].expan; + if (this.storedData[i].x.v < 0) { + if (this.storedData[i].lastOperator !== "erode") { + this.storedData[i].lastOperator = "erode"; + this.storedData[i].elem.setAttribute("filter", "url(" + getLocationHref() + "#" + this.storedData[i].filterId + ")"); + } + feMorph.setAttribute("radius", -this.storedData[i].x.v); + } else { + if (this.storedData[i].lastOperator !== "dilate") { + this.storedData[i].lastOperator = "dilate"; + this.storedData[i].elem.setAttribute("filter", null); + } + this.storedData[i].elem.setAttribute("stroke-width", this.storedData[i].x.v * 2); + } + } + } + } + }; + MaskElement.prototype.getMaskelement = function() { + return this.maskElement; + }; + MaskElement.prototype.createLayerSolidPath = function() { + var path = "M0,0 "; + path += " h" + this.globalData.compSize.w; + path += " v" + this.globalData.compSize.h; + path += " h-" + this.globalData.compSize.w; + path += " v-" + this.globalData.compSize.h + " "; + return path; + }; + MaskElement.prototype.drawPath = function(pathData, pathNodes, viewData) { + var pathString = " M" + pathNodes.v[0][0] + "," + pathNodes.v[0][1]; + var i; + var len; + len = pathNodes._length; + for (i = 1;i < len; i += 1) { + pathString += " C" + pathNodes.o[i - 1][0] + "," + pathNodes.o[i - 1][1] + " " + pathNodes.i[i][0] + "," + pathNodes.i[i][1] + " " + pathNodes.v[i][0] + "," + pathNodes.v[i][1]; + } + if (pathNodes.c && len > 1) { + pathString += " C" + pathNodes.o[i - 1][0] + "," + pathNodes.o[i - 1][1] + " " + pathNodes.i[0][0] + "," + pathNodes.i[0][1] + " " + pathNodes.v[0][0] + "," + pathNodes.v[0][1]; + } + if (viewData.lastPath !== pathString) { + var pathShapeValue = ""; + if (viewData.elem) { + if (pathNodes.c) { + pathShapeValue = pathData.inv ? this.solidPath + pathString : pathString; + } + viewData.elem.setAttribute("d", pathShapeValue); + } + viewData.lastPath = pathString; + } + }; + MaskElement.prototype.destroy = function() { + this.element = null; + this.globalData = null; + this.maskElement = null; + this.data = null; + this.masksProperties = null; + }; + const filtersFactory = function() { + var ob2 = {}; + ob2.createFilter = createFilter; + ob2.createAlphaToLuminanceFilter = createAlphaToLuminanceFilter; + function createFilter(filId, skipCoordinates) { + var fil = createNS("filter"); + fil.setAttribute("id", filId); + if (skipCoordinates !== true) { + fil.setAttribute("filterUnits", "objectBoundingBox"); + fil.setAttribute("x", "0%"); + fil.setAttribute("y", "0%"); + fil.setAttribute("width", "100%"); + fil.setAttribute("height", "100%"); + } + return fil; + } + function createAlphaToLuminanceFilter() { + var feColorMatrix = createNS("feColorMatrix"); + feColorMatrix.setAttribute("type", "matrix"); + feColorMatrix.setAttribute("color-interpolation-filters", "sRGB"); + feColorMatrix.setAttribute("values", "0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1"); + return feColorMatrix; + } + return ob2; + }(); + const featureSupport = function() { + var ob2 = { + maskType: true + }; + if (/MSIE 10/i.test(navigator.userAgent) || /MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent) || /Edge\/\d./i.test(navigator.userAgent)) { + ob2.maskType = false; + } + return ob2; + }(); + registeredEffects = {}; + idPrefix = "filter_result_"; + SVGEffects.prototype.renderFrame = function(_isFirstFrame) { + var i; + var len = this.filters.length; + for (i = 0;i < len; i += 1) { + this.filters[i].renderFrame(_isFirstFrame); + } + }; + SVGBaseElement.prototype = { + initRendererElement: function() { + this.layerElement = createNS("g"); + }, + createContainerElements: function() { + this.matteElement = createNS("g"); + this.transformedElement = this.layerElement; + this.maskedElement = this.layerElement; + this._sizeChanged = false; + var layerElementParent = null; + var filId; + var fil; + var gg; + if (this.data.td) { + if (this.data.td == 3 || this.data.td == 1) { + var masker = createNS("mask"); + masker.setAttribute("id", this.layerId); + masker.setAttribute("mask-type", this.data.td == 3 ? "luminance" : "alpha"); + masker.appendChild(this.layerElement); + layerElementParent = masker; + this.globalData.defs.appendChild(masker); + if (!featureSupport.maskType && this.data.td == 1) { + masker.setAttribute("mask-type", "luminance"); + filId = createElementID(); + fil = filtersFactory.createFilter(filId); + this.globalData.defs.appendChild(fil); + fil.appendChild(filtersFactory.createAlphaToLuminanceFilter()); + gg = createNS("g"); + gg.appendChild(this.layerElement); + layerElementParent = gg; + masker.appendChild(gg); + gg.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")"); + } + } else if (this.data.td == 2) { + var maskGroup = createNS("mask"); + maskGroup.setAttribute("id", this.layerId); + maskGroup.setAttribute("mask-type", "alpha"); + var maskGrouper = createNS("g"); + maskGroup.appendChild(maskGrouper); + filId = createElementID(); + fil = filtersFactory.createFilter(filId); + var feCTr = createNS("feComponentTransfer"); + feCTr.setAttribute("in", "SourceGraphic"); + fil.appendChild(feCTr); + var feFunc = createNS("feFuncA"); + feFunc.setAttribute("type", "table"); + feFunc.setAttribute("tableValues", "1.0 0.0"); + feCTr.appendChild(feFunc); + this.globalData.defs.appendChild(fil); + var alphaRect = createNS("rect"); + alphaRect.setAttribute("width", this.comp.data.w); + alphaRect.setAttribute("height", this.comp.data.h); + alphaRect.setAttribute("x", "0"); + alphaRect.setAttribute("y", "0"); + alphaRect.setAttribute("fill", "#ffffff"); + alphaRect.setAttribute("opacity", "0"); + maskGrouper.setAttribute("filter", "url(" + getLocationHref() + "#" + filId + ")"); + maskGrouper.appendChild(alphaRect); + maskGrouper.appendChild(this.layerElement); + layerElementParent = maskGrouper; + if (!featureSupport.maskType) { + maskGroup.setAttribute("mask-type", "luminance"); + fil.appendChild(filtersFactory.createAlphaToLuminanceFilter()); + gg = createNS("g"); + maskGrouper.appendChild(alphaRect); + gg.appendChild(this.layerElement); + layerElementParent = gg; + maskGrouper.appendChild(gg); + } + this.globalData.defs.appendChild(maskGroup); + } + } else if (this.data.tt) { + this.matteElement.appendChild(this.layerElement); + layerElementParent = this.matteElement; + this.baseElement = this.matteElement; + } else { + this.baseElement = this.layerElement; + } + if (this.data.ln) { + this.layerElement.setAttribute("id", this.data.ln); + } + if (this.data.cl) { + this.layerElement.setAttribute("class", this.data.cl); + } + if (this.data.ty === 0 && !this.data.hd) { + var cp = createNS("clipPath"); + var pt = createNS("path"); + pt.setAttribute("d", "M0,0 L" + this.data.w + ",0 L" + this.data.w + "," + this.data.h + " L0," + this.data.h + "z"); + var clipId = createElementID(); + cp.setAttribute("id", clipId); + cp.appendChild(pt); + this.globalData.defs.appendChild(cp); + if (this.checkMasks()) { + var cpGroup = createNS("g"); + cpGroup.setAttribute("clip-path", "url(" + getLocationHref() + "#" + clipId + ")"); + cpGroup.appendChild(this.layerElement); + this.transformedElement = cpGroup; + if (layerElementParent) { + layerElementParent.appendChild(this.transformedElement); + } else { + this.baseElement = this.transformedElement; + } + } else { + this.layerElement.setAttribute("clip-path", "url(" + getLocationHref() + "#" + clipId + ")"); + } + } + if (this.data.bm !== 0) { + this.setBlendMode(); + } + }, + renderElement: function() { + if (this.finalTransform._matMdf) { + this.transformedElement.setAttribute("transform", this.finalTransform.mat.to2dCSS()); + } + if (this.finalTransform._opMdf) { + this.transformedElement.setAttribute("opacity", this.finalTransform.mProp.o.v); + } + }, + destroyBaseElement: function() { + this.layerElement = null; + this.matteElement = null; + this.maskManager.destroy(); + }, + getBaseElement: function() { + if (this.data.hd) { + return null; + } + return this.baseElement; + }, + createRenderableComponents: function() { + this.maskManager = new MaskElement(this.data, this, this.globalData); + this.renderableEffectsManager = new SVGEffects(this); + }, + setMatte: function(id) { + if (!this.matteElement) { + return; + } + this.matteElement.setAttribute("mask", "url(" + getLocationHref() + "#" + id + ")"); + } + }; + HierarchyElement.prototype = { + initHierarchy: function() { + this.hierarchy = []; + this._isParent = false; + this.checkParenting(); + }, + setHierarchy: function(hierarchy) { + this.hierarchy = hierarchy; + }, + setAsParent: function() { + this._isParent = true; + }, + checkParenting: function() { + if (this.data.parent !== undefined) { + this.comp.buildElementParenting(this, this.data.parent, []); + } + } + }; + (function() { + var _prototype = { + initElement: function(data2, globalData2, comp2) { + this.initFrame(); + this.initBaseData(data2, globalData2, comp2); + this.initTransform(data2, globalData2, comp2); + this.initHierarchy(); + this.initRenderable(); + this.initRendererElement(); + this.createContainerElements(); + this.createRenderableComponents(); + this.createContent(); + this.hide(); + }, + hide: function() { + if (!this.hidden && (!this.isInRange || this.isTransparent)) { + var elem2 = this.baseElement || this.layerElement; + elem2.style.display = "none"; + this.hidden = true; + } + }, + show: function() { + if (this.isInRange && !this.isTransparent) { + if (!this.data.hd) { + var elem2 = this.baseElement || this.layerElement; + elem2.style.display = "block"; + } + this.hidden = false; + this._isFirstFrame = true; + } + }, + renderFrame: function() { + if (this.data.hd || this.hidden) { + return; + } + this.renderTransform(); + this.renderRenderable(); + this.renderElement(); + this.renderInnerContent(); + if (this._isFirstFrame) { + this._isFirstFrame = false; + } + }, + renderInnerContent: function() { + }, + prepareFrame: function(num) { + this._mdf = false; + this.prepareRenderableFrame(num); + this.prepareProperties(num, this.isInRange); + this.checkTransparency(); + }, + destroy: function() { + this.innerElem = null; + this.destroyBaseElement(); + } + }; + extendPrototype([RenderableElement, createProxyFunction(_prototype)], RenderableDOMElement); + })(); + extendPrototype([BaseElement, TransformElement, SVGBaseElement, HierarchyElement, FrameElement, RenderableDOMElement], IImageElement); + IImageElement.prototype.createContent = function() { + var assetPath = this.globalData.getAssetsPath(this.assetData); + this.innerElem = createNS("image"); + this.innerElem.setAttribute("width", this.assetData.w + "px"); + this.innerElem.setAttribute("height", this.assetData.h + "px"); + this.innerElem.setAttribute("preserveAspectRatio", this.assetData.pr || this.globalData.renderConfig.imagePreserveAspectRatio); + this.innerElem.setAttributeNS("http://www.w3.org/1999/xlink", "href", assetPath); + this.layerElement.appendChild(this.innerElem); + }; + IImageElement.prototype.sourceRectAtTime = function() { + return this.sourceRect; + }; + IShapeElement.prototype = { + addShapeToModifiers: function(data2) { + var i; + var len = this.shapeModifiers.length; + for (i = 0;i < len; i += 1) { + this.shapeModifiers[i].addShape(data2); + } + }, + isShapeInAnimatedModifiers: function(data2) { + var i = 0; + var len = this.shapeModifiers.length; + while (i < len) { + if (this.shapeModifiers[i].isAnimatedWithShape(data2)) { + return true; + } + } + return false; + }, + renderModifiers: function() { + if (!this.shapeModifiers.length) { + return; + } + var i; + var len = this.shapes.length; + for (i = 0;i < len; i += 1) { + this.shapes[i].sh.reset(); + } + len = this.shapeModifiers.length; + var shouldBreakProcess; + for (i = len - 1;i >= 0; i -= 1) { + shouldBreakProcess = this.shapeModifiers[i].processShapes(this._isFirstFrame); + if (shouldBreakProcess) { + break; + } + } + }, + searchProcessedElement: function(elem2) { + var elements = this.processedElements; + var i = 0; + var len = elements.length; + while (i < len) { + if (elements[i].elem === elem2) { + return elements[i].pos; + } + i += 1; + } + return 0; + }, + addProcessedElement: function(elem2, pos) { + var elements = this.processedElements; + var i = elements.length; + while (i) { + i -= 1; + if (elements[i].elem === elem2) { + elements[i].pos = pos; + return; + } + } + elements.push(new ProcessedElement(elem2, pos)); + }, + prepareFrame: function(num) { + this.prepareRenderableFrame(num); + this.prepareProperties(num, this.isInRange); + } + }; + const lineCapEnum = { + 1: "butt", + 2: "round", + 3: "square" + }; + const lineJoinEnum = { + 1: "miter", + 2: "round", + 3: "bevel" + }; + SVGShapeData.prototype.setAsAnimated = function() { + this._isAnimated = true; + }; + SVGStyleData.prototype.reset = function() { + this.d = ""; + this._mdf = false; + }; + DashProperty.prototype.getValue = function(forceRender) { + if (this.elem.globalData.frameId === this.frameId && !forceRender) { + return; + } + this.frameId = this.elem.globalData.frameId; + this.iterateDynamicProperties(); + this._mdf = this._mdf || forceRender; + if (this._mdf) { + var i = 0; + var len = this.dataProps.length; + if (this.renderer === "svg") { + this.dashStr = ""; + } + for (i = 0;i < len; i += 1) { + if (this.dataProps[i].n !== "o") { + if (this.renderer === "svg") { + this.dashStr += " " + this.dataProps[i].p.v; + } else { + this.dashArray[i] = this.dataProps[i].p.v; + } + } else { + this.dashoffset[0] = this.dataProps[i].p.v; + } + } + } + }; + extendPrototype([DynamicPropertyContainer], DashProperty); + extendPrototype([DynamicPropertyContainer], SVGStrokeStyleData); + extendPrototype([DynamicPropertyContainer], SVGFillStyleData); + extendPrototype([DynamicPropertyContainer], SVGNoStyleData); + GradientProperty.prototype.comparePoints = function(values2, points) { + var i = 0; + var len = this.o.length / 2; + var diff; + while (i < len) { + diff = Math.abs(values2[i * 4] - values2[points * 4 + i * 2]); + if (diff > 0.01) { + return false; + } + i += 1; + } + return true; + }; + GradientProperty.prototype.checkCollapsable = function() { + if (this.o.length / 2 !== this.c.length / 4) { + return false; + } + if (this.data.k.k[0].s) { + var i = 0; + var len = this.data.k.k.length; + while (i < len) { + if (!this.comparePoints(this.data.k.k[i].s, this.data.p)) { + return false; + } + i += 1; + } + } else if (!this.comparePoints(this.data.k.k, this.data.p)) { + return false; + } + return true; + }; + GradientProperty.prototype.getValue = function(forceRender) { + this.prop.getValue(); + this._mdf = false; + this._cmdf = false; + this._omdf = false; + if (this.prop._mdf || forceRender) { + var i; + var len = this.data.p * 4; + var mult; + var val2; + for (i = 0;i < len; i += 1) { + mult = i % 4 === 0 ? 100 : 255; + val2 = Math.round(this.prop.v[i] * mult); + if (this.c[i] !== val2) { + this.c[i] = val2; + this._cmdf = !forceRender; + } + } + if (this.o.length) { + len = this.prop.v.length; + for (i = this.data.p * 4;i < len; i += 1) { + mult = i % 2 === 0 ? 100 : 1; + val2 = i % 2 === 0 ? Math.round(this.prop.v[i] * 100) : this.prop.v[i]; + if (this.o[i - this.data.p * 4] !== val2) { + this.o[i - this.data.p * 4] = val2; + this._omdf = !forceRender; + } + } + } + this._mdf = !forceRender; + } + }; + extendPrototype([DynamicPropertyContainer], GradientProperty); + SVGGradientFillStyleData.prototype.initGradientData = function(elem2, data2, styleOb) { + this.o = PropertyFactory.getProp(elem2, data2.o, 0, 0.01, this); + this.s = PropertyFactory.getProp(elem2, data2.s, 1, null, this); + this.e = PropertyFactory.getProp(elem2, data2.e, 1, null, this); + this.h = PropertyFactory.getProp(elem2, data2.h || { k: 0 }, 0, 0.01, this); + this.a = PropertyFactory.getProp(elem2, data2.a || { k: 0 }, 0, degToRads, this); + this.g = new GradientProperty(elem2, data2.g, this); + this.style = styleOb; + this.stops = []; + this.setGradientData(styleOb.pElem, data2); + this.setGradientOpacity(data2, styleOb); + this._isAnimated = !!this._isAnimated; + }; + SVGGradientFillStyleData.prototype.setGradientData = function(pathElement, data2) { + var gradientId = createElementID(); + var gfill = createNS(data2.t === 1 ? "linearGradient" : "radialGradient"); + gfill.setAttribute("id", gradientId); + gfill.setAttribute("spreadMethod", "pad"); + gfill.setAttribute("gradientUnits", "userSpaceOnUse"); + var stops = []; + var stop; + var j2; + var jLen; + jLen = data2.g.p * 4; + for (j2 = 0;j2 < jLen; j2 += 4) { + stop = createNS("stop"); + gfill.appendChild(stop); + stops.push(stop); + } + pathElement.setAttribute(data2.ty === "gf" ? "fill" : "stroke", "url(" + getLocationHref() + "#" + gradientId + ")"); + this.gf = gfill; + this.cst = stops; + }; + SVGGradientFillStyleData.prototype.setGradientOpacity = function(data2, styleOb) { + if (this.g._hasOpacity && !this.g._collapsable) { + var stop; + var j2; + var jLen; + var mask2 = createNS("mask"); + var maskElement = createNS("path"); + mask2.appendChild(maskElement); + var opacityId = createElementID(); + var maskId = createElementID(); + mask2.setAttribute("id", maskId); + var opFill = createNS(data2.t === 1 ? "linearGradient" : "radialGradient"); + opFill.setAttribute("id", opacityId); + opFill.setAttribute("spreadMethod", "pad"); + opFill.setAttribute("gradientUnits", "userSpaceOnUse"); + jLen = data2.g.k.k[0].s ? data2.g.k.k[0].s.length : data2.g.k.k.length; + var stops = this.stops; + for (j2 = data2.g.p * 4;j2 < jLen; j2 += 2) { + stop = createNS("stop"); + stop.setAttribute("stop-color", "rgb(255,255,255)"); + opFill.appendChild(stop); + stops.push(stop); + } + maskElement.setAttribute(data2.ty === "gf" ? "fill" : "stroke", "url(" + getLocationHref() + "#" + opacityId + ")"); + if (data2.ty === "gs") { + maskElement.setAttribute("stroke-linecap", lineCapEnum[data2.lc || 2]); + maskElement.setAttribute("stroke-linejoin", lineJoinEnum[data2.lj || 2]); + if (data2.lj === 1) { + maskElement.setAttribute("stroke-miterlimit", data2.ml); + } + } + this.of = opFill; + this.ms = mask2; + this.ost = stops; + this.maskId = maskId; + styleOb.msElem = maskElement; + } + }; + extendPrototype([DynamicPropertyContainer], SVGGradientFillStyleData); + extendPrototype([SVGGradientFillStyleData, DynamicPropertyContainer], SVGGradientStrokeStyleData); + const buildShapeString = function(pathNodes, length2, closed, mat) { + if (length2 === 0) { + return ""; + } + var _o = pathNodes.o; + var _i = pathNodes.i; + var _v4 = pathNodes.v; + var i; + var shapeString = " M" + mat.applyToPointStringified(_v4[0][0], _v4[0][1]); + for (i = 1;i < length2; i += 1) { + shapeString += " C" + mat.applyToPointStringified(_o[i - 1][0], _o[i - 1][1]) + " " + mat.applyToPointStringified(_i[i][0], _i[i][1]) + " " + mat.applyToPointStringified(_v4[i][0], _v4[i][1]); + } + if (closed && length2) { + shapeString += " C" + mat.applyToPointStringified(_o[i - 1][0], _o[i - 1][1]) + " " + mat.applyToPointStringified(_i[0][0], _i[0][1]) + " " + mat.applyToPointStringified(_v4[0][0], _v4[0][1]); + shapeString += "z"; + } + return shapeString; + }; + const SVGElementsRenderer = function() { + var _identityMatrix3 = new Matrix; + var _matrixHelper = new Matrix; + var ob2 = { + createRenderFunction + }; + function createRenderFunction(data2) { + switch (data2.ty) { + case "fl": + return renderFill; + case "gf": + return renderGradient; + case "gs": + return renderGradientStroke; + case "st": + return renderStroke; + case "sh": + case "el": + case "rc": + case "sr": + return renderPath; + case "tr": + return renderContentTransform; + case "no": + return renderNoop; + default: + return null; + } + } + function renderContentTransform(styleData, itemData, isFirstFrame) { + if (isFirstFrame || itemData.transform.op._mdf) { + itemData.transform.container.setAttribute("opacity", itemData.transform.op.v); + } + if (isFirstFrame || itemData.transform.mProps._mdf) { + itemData.transform.container.setAttribute("transform", itemData.transform.mProps.v.to2dCSS()); + } + } + function renderNoop() { + } + function renderPath(styleData, itemData, isFirstFrame) { + var j2; + var jLen; + var pathStringTransformed; + var redraw; + var pathNodes; + var l2; + var lLen = itemData.styles.length; + var lvl = itemData.lvl; + var paths; + var mat; + var props; + var iterations; + var k2; + for (l2 = 0;l2 < lLen; l2 += 1) { + redraw = itemData.sh._mdf || isFirstFrame; + if (itemData.styles[l2].lvl < lvl) { + mat = _matrixHelper.reset(); + iterations = lvl - itemData.styles[l2].lvl; + k2 = itemData.transformers.length - 1; + while (!redraw && iterations > 0) { + redraw = itemData.transformers[k2].mProps._mdf || redraw; + iterations -= 1; + k2 -= 1; + } + if (redraw) { + iterations = lvl - itemData.styles[l2].lvl; + k2 = itemData.transformers.length - 1; + while (iterations > 0) { + props = itemData.transformers[k2].mProps.v.props; + mat.transform(props[0], props[1], props[2], props[3], props[4], props[5], props[6], props[7], props[8], props[9], props[10], props[11], props[12], props[13], props[14], props[15]); + iterations -= 1; + k2 -= 1; + } + } + } else { + mat = _identityMatrix3; + } + paths = itemData.sh.paths; + jLen = paths._length; + if (redraw) { + pathStringTransformed = ""; + for (j2 = 0;j2 < jLen; j2 += 1) { + pathNodes = paths.shapes[j2]; + if (pathNodes && pathNodes._length) { + pathStringTransformed += buildShapeString(pathNodes, pathNodes._length, pathNodes.c, mat); + } + } + itemData.caches[l2] = pathStringTransformed; + } else { + pathStringTransformed = itemData.caches[l2]; + } + itemData.styles[l2].d += styleData.hd === true ? "" : pathStringTransformed; + itemData.styles[l2]._mdf = redraw || itemData.styles[l2]._mdf; + } + } + function renderFill(styleData, itemData, isFirstFrame) { + var styleElem = itemData.style; + if (itemData.c._mdf || isFirstFrame) { + styleElem.pElem.setAttribute("fill", "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"); + } + if (itemData.o._mdf || isFirstFrame) { + styleElem.pElem.setAttribute("fill-opacity", itemData.o.v); + } + } + function renderGradientStroke(styleData, itemData, isFirstFrame) { + renderGradient(styleData, itemData, isFirstFrame); + renderStroke(styleData, itemData, isFirstFrame); + } + function renderGradient(styleData, itemData, isFirstFrame) { + var gfill = itemData.gf; + var hasOpacity = itemData.g._hasOpacity; + var pt1 = itemData.s.v; + var pt2 = itemData.e.v; + if (itemData.o._mdf || isFirstFrame) { + var attr = styleData.ty === "gf" ? "fill-opacity" : "stroke-opacity"; + itemData.style.pElem.setAttribute(attr, itemData.o.v); + } + if (itemData.s._mdf || isFirstFrame) { + var attr1 = styleData.t === 1 ? "x1" : "cx"; + var attr2 = attr1 === "x1" ? "y1" : "cy"; + gfill.setAttribute(attr1, pt1[0]); + gfill.setAttribute(attr2, pt1[1]); + if (hasOpacity && !itemData.g._collapsable) { + itemData.of.setAttribute(attr1, pt1[0]); + itemData.of.setAttribute(attr2, pt1[1]); + } + } + var stops; + var i; + var len; + var stop; + if (itemData.g._cmdf || isFirstFrame) { + stops = itemData.cst; + var cValues = itemData.g.c; + len = stops.length; + for (i = 0;i < len; i += 1) { + stop = stops[i]; + stop.setAttribute("offset", cValues[i * 4] + "%"); + stop.setAttribute("stop-color", "rgb(" + cValues[i * 4 + 1] + "," + cValues[i * 4 + 2] + "," + cValues[i * 4 + 3] + ")"); + } + } + if (hasOpacity && (itemData.g._omdf || isFirstFrame)) { + var oValues = itemData.g.o; + if (itemData.g._collapsable) { + stops = itemData.cst; + } else { + stops = itemData.ost; + } + len = stops.length; + for (i = 0;i < len; i += 1) { + stop = stops[i]; + if (!itemData.g._collapsable) { + stop.setAttribute("offset", oValues[i * 2] + "%"); + } + stop.setAttribute("stop-opacity", oValues[i * 2 + 1]); + } + } + if (styleData.t === 1) { + if (itemData.e._mdf || isFirstFrame) { + gfill.setAttribute("x2", pt2[0]); + gfill.setAttribute("y2", pt2[1]); + if (hasOpacity && !itemData.g._collapsable) { + itemData.of.setAttribute("x2", pt2[0]); + itemData.of.setAttribute("y2", pt2[1]); + } + } + } else { + var rad; + if (itemData.s._mdf || itemData.e._mdf || isFirstFrame) { + rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); + gfill.setAttribute("r", rad); + if (hasOpacity && !itemData.g._collapsable) { + itemData.of.setAttribute("r", rad); + } + } + if (itemData.e._mdf || itemData.h._mdf || itemData.a._mdf || isFirstFrame) { + if (!rad) { + rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); + } + var ang = Math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]); + var percent = itemData.h.v; + if (percent >= 1) { + percent = 0.99; + } else if (percent <= -1) { + percent = -0.99; + } + var dist = rad * percent; + var x2 = Math.cos(ang + itemData.a.v) * dist + pt1[0]; + var y = Math.sin(ang + itemData.a.v) * dist + pt1[1]; + gfill.setAttribute("fx", x2); + gfill.setAttribute("fy", y); + if (hasOpacity && !itemData.g._collapsable) { + itemData.of.setAttribute("fx", x2); + itemData.of.setAttribute("fy", y); + } + } + } + } + function renderStroke(styleData, itemData, isFirstFrame) { + var styleElem = itemData.style; + var d = itemData.d; + if (d && (d._mdf || isFirstFrame) && d.dashStr) { + styleElem.pElem.setAttribute("stroke-dasharray", d.dashStr); + styleElem.pElem.setAttribute("stroke-dashoffset", d.dashoffset[0]); + } + if (itemData.c && (itemData.c._mdf || isFirstFrame)) { + styleElem.pElem.setAttribute("stroke", "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"); + } + if (itemData.o._mdf || isFirstFrame) { + styleElem.pElem.setAttribute("stroke-opacity", itemData.o.v); + } + if (itemData.w._mdf || isFirstFrame) { + styleElem.pElem.setAttribute("stroke-width", itemData.w.v); + if (styleElem.msElem) { + styleElem.msElem.setAttribute("stroke-width", itemData.w.v); + } + } + } + return ob2; + }(); + extendPrototype([BaseElement, TransformElement, SVGBaseElement, IShapeElement, HierarchyElement, FrameElement, RenderableDOMElement], SVGShapeElement); + SVGShapeElement.prototype.initSecondaryElement = function() { + }; + SVGShapeElement.prototype.identityMatrix = new Matrix; + SVGShapeElement.prototype.buildExpressionInterface = function() { + }; + SVGShapeElement.prototype.createContent = function() { + this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, this.layerElement, 0, [], true); + this.filterUniqueShapes(); + }; + SVGShapeElement.prototype.filterUniqueShapes = function() { + var i; + var len = this.shapes.length; + var shape; + var j2; + var jLen = this.stylesList.length; + var style; + var tempShapes = []; + var areAnimated = false; + for (j2 = 0;j2 < jLen; j2 += 1) { + style = this.stylesList[j2]; + areAnimated = false; + tempShapes.length = 0; + for (i = 0;i < len; i += 1) { + shape = this.shapes[i]; + if (shape.styles.indexOf(style) !== -1) { + tempShapes.push(shape); + areAnimated = shape._isAnimated || areAnimated; + } + } + if (tempShapes.length > 1 && areAnimated) { + this.setShapesAsAnimated(tempShapes); + } + } + }; + SVGShapeElement.prototype.setShapesAsAnimated = function(shapes) { + var i; + var len = shapes.length; + for (i = 0;i < len; i += 1) { + shapes[i].setAsAnimated(); + } + }; + SVGShapeElement.prototype.createStyleElement = function(data2, level) { + var elementData; + var styleOb = new SVGStyleData(data2, level); + var pathElement = styleOb.pElem; + if (data2.ty === "st") { + elementData = new SVGStrokeStyleData(this, data2, styleOb); + } else if (data2.ty === "fl") { + elementData = new SVGFillStyleData(this, data2, styleOb); + } else if (data2.ty === "gf" || data2.ty === "gs") { + var GradientConstructor = data2.ty === "gf" ? SVGGradientFillStyleData : SVGGradientStrokeStyleData; + elementData = new GradientConstructor(this, data2, styleOb); + this.globalData.defs.appendChild(elementData.gf); + if (elementData.maskId) { + this.globalData.defs.appendChild(elementData.ms); + this.globalData.defs.appendChild(elementData.of); + pathElement.setAttribute("mask", "url(" + getLocationHref() + "#" + elementData.maskId + ")"); + } + } else if (data2.ty === "no") { + elementData = new SVGNoStyleData(this, data2, styleOb); + } + if (data2.ty === "st" || data2.ty === "gs") { + pathElement.setAttribute("stroke-linecap", lineCapEnum[data2.lc || 2]); + pathElement.setAttribute("stroke-linejoin", lineJoinEnum[data2.lj || 2]); + pathElement.setAttribute("fill-opacity", "0"); + if (data2.lj === 1) { + pathElement.setAttribute("stroke-miterlimit", data2.ml); + } + } + if (data2.r === 2) { + pathElement.setAttribute("fill-rule", "evenodd"); + } + if (data2.ln) { + pathElement.setAttribute("id", data2.ln); + } + if (data2.cl) { + pathElement.setAttribute("class", data2.cl); + } + if (data2.bm) { + pathElement.style["mix-blend-mode"] = getBlendMode(data2.bm); + } + this.stylesList.push(styleOb); + this.addToAnimatedContents(data2, elementData); + return elementData; + }; + SVGShapeElement.prototype.createGroupElement = function(data2) { + var elementData = new ShapeGroupData; + if (data2.ln) { + elementData.gr.setAttribute("id", data2.ln); + } + if (data2.cl) { + elementData.gr.setAttribute("class", data2.cl); + } + if (data2.bm) { + elementData.gr.style["mix-blend-mode"] = getBlendMode(data2.bm); + } + return elementData; + }; + SVGShapeElement.prototype.createTransformElement = function(data2, container) { + var transformProperty = TransformPropertyFactory.getTransformProperty(this, data2, this); + var elementData = new SVGTransformData(transformProperty, transformProperty.o, container); + this.addToAnimatedContents(data2, elementData); + return elementData; + }; + SVGShapeElement.prototype.createShapeElement = function(data2, ownTransformers, level) { + var ty = 4; + if (data2.ty === "rc") { + ty = 5; + } else if (data2.ty === "el") { + ty = 6; + } else if (data2.ty === "sr") { + ty = 7; + } + var shapeProperty = ShapePropertyFactory.getShapeProp(this, data2, ty, this); + var elementData = new SVGShapeData(ownTransformers, level, shapeProperty); + this.shapes.push(elementData); + this.addShapeToModifiers(elementData); + this.addToAnimatedContents(data2, elementData); + return elementData; + }; + SVGShapeElement.prototype.addToAnimatedContents = function(data2, element) { + var i = 0; + var len = this.animatedContents.length; + while (i < len) { + if (this.animatedContents[i].element === element) { + return; + } + i += 1; + } + this.animatedContents.push({ + fn: SVGElementsRenderer.createRenderFunction(data2), + element, + data: data2 + }); + }; + SVGShapeElement.prototype.setElementStyles = function(elementData) { + var arr = elementData.styles; + var j2; + var jLen = this.stylesList.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (!this.stylesList[j2].closed) { + arr.push(this.stylesList[j2]); + } + } + }; + SVGShapeElement.prototype.reloadShapes = function() { + this._isFirstFrame = true; + var i; + var len = this.itemsData.length; + for (i = 0;i < len; i += 1) { + this.prevViewData[i] = this.itemsData[i]; + } + this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, this.layerElement, 0, [], true); + this.filterUniqueShapes(); + len = this.dynamicProperties.length; + for (i = 0;i < len; i += 1) { + this.dynamicProperties[i].getValue(); + } + this.renderModifiers(); + }; + SVGShapeElement.prototype.searchShapes = function(arr, itemsData, prevViewData, container, level, transformers, render) { + var ownTransformers = [].concat(transformers); + var i; + var len = arr.length - 1; + var j2; + var jLen; + var ownStyles = []; + var ownModifiers = []; + var currentTransform; + var modifier; + var processedPos; + for (i = len;i >= 0; i -= 1) { + processedPos = this.searchProcessedElement(arr[i]); + if (!processedPos) { + arr[i]._render = render; + } else { + itemsData[i] = prevViewData[processedPos - 1]; + } + if (arr[i].ty === "fl" || arr[i].ty === "st" || arr[i].ty === "gf" || arr[i].ty === "gs" || arr[i].ty === "no") { + if (!processedPos) { + itemsData[i] = this.createStyleElement(arr[i], level); + } else { + itemsData[i].style.closed = false; + } + if (arr[i]._render) { + if (itemsData[i].style.pElem.parentNode !== container) { + container.appendChild(itemsData[i].style.pElem); + } + } + ownStyles.push(itemsData[i].style); + } else if (arr[i].ty === "gr") { + if (!processedPos) { + itemsData[i] = this.createGroupElement(arr[i]); + } else { + jLen = itemsData[i].it.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + itemsData[i].prevViewData[j2] = itemsData[i].it[j2]; + } + } + this.searchShapes(arr[i].it, itemsData[i].it, itemsData[i].prevViewData, itemsData[i].gr, level + 1, ownTransformers, render); + if (arr[i]._render) { + if (itemsData[i].gr.parentNode !== container) { + container.appendChild(itemsData[i].gr); + } + } + } else if (arr[i].ty === "tr") { + if (!processedPos) { + itemsData[i] = this.createTransformElement(arr[i], container); + } + currentTransform = itemsData[i].transform; + ownTransformers.push(currentTransform); + } else if (arr[i].ty === "sh" || arr[i].ty === "rc" || arr[i].ty === "el" || arr[i].ty === "sr") { + if (!processedPos) { + itemsData[i] = this.createShapeElement(arr[i], ownTransformers, level); + } + this.setElementStyles(itemsData[i]); + } else if (arr[i].ty === "tm" || arr[i].ty === "rd" || arr[i].ty === "ms" || arr[i].ty === "pb") { + if (!processedPos) { + modifier = ShapeModifiers.getModifier(arr[i].ty); + modifier.init(this, arr[i]); + itemsData[i] = modifier; + this.shapeModifiers.push(modifier); + } else { + modifier = itemsData[i]; + modifier.closed = false; + } + ownModifiers.push(modifier); + } else if (arr[i].ty === "rp") { + if (!processedPos) { + modifier = ShapeModifiers.getModifier(arr[i].ty); + itemsData[i] = modifier; + modifier.init(this, arr, i, itemsData); + this.shapeModifiers.push(modifier); + render = false; + } else { + modifier = itemsData[i]; + modifier.closed = true; + } + ownModifiers.push(modifier); + } + this.addProcessedElement(arr[i], i + 1); + } + len = ownStyles.length; + for (i = 0;i < len; i += 1) { + ownStyles[i].closed = true; + } + len = ownModifiers.length; + for (i = 0;i < len; i += 1) { + ownModifiers[i].closed = true; + } + }; + SVGShapeElement.prototype.renderInnerContent = function() { + this.renderModifiers(); + var i; + var len = this.stylesList.length; + for (i = 0;i < len; i += 1) { + this.stylesList[i].reset(); + } + this.renderShape(); + for (i = 0;i < len; i += 1) { + if (this.stylesList[i]._mdf || this._isFirstFrame) { + if (this.stylesList[i].msElem) { + this.stylesList[i].msElem.setAttribute("d", this.stylesList[i].d); + this.stylesList[i].d = "M0 0" + this.stylesList[i].d; + } + this.stylesList[i].pElem.setAttribute("d", this.stylesList[i].d || "M0 0"); + } + } + }; + SVGShapeElement.prototype.renderShape = function() { + var i; + var len = this.animatedContents.length; + var animatedContent; + for (i = 0;i < len; i += 1) { + animatedContent = this.animatedContents[i]; + if ((this._isFirstFrame || animatedContent.element._isAnimated) && animatedContent.data !== true) { + animatedContent.fn(animatedContent.data, animatedContent.element, this._isFirstFrame); + } + } + }; + SVGShapeElement.prototype.destroy = function() { + this.destroyBaseElement(); + this.shapesData = null; + this.itemsData = null; + }; + LetterProps.prototype.update = function(o, sw, sc, fc, m, p) { + this._mdf.o = false; + this._mdf.sw = false; + this._mdf.sc = false; + this._mdf.fc = false; + this._mdf.m = false; + this._mdf.p = false; + var updated = false; + if (this.o !== o) { + this.o = o; + this._mdf.o = true; + updated = true; + } + if (this.sw !== sw) { + this.sw = sw; + this._mdf.sw = true; + updated = true; + } + if (this.sc !== sc) { + this.sc = sc; + this._mdf.sc = true; + updated = true; + } + if (this.fc !== fc) { + this.fc = fc; + this._mdf.fc = true; + updated = true; + } + if (this.m !== m) { + this.m = m; + this._mdf.m = true; + updated = true; + } + if (p.length && (this.p[0] !== p[0] || this.p[1] !== p[1] || this.p[4] !== p[4] || this.p[5] !== p[5] || this.p[12] !== p[12] || this.p[13] !== p[13])) { + this.p = p; + this._mdf.p = true; + updated = true; + } + return updated; + }; + TextProperty.prototype.defaultBoxWidth = [0, 0]; + TextProperty.prototype.copyData = function(obj, data2) { + for (var s in data2) { + if (Object.prototype.hasOwnProperty.call(data2, s)) { + obj[s] = data2[s]; + } + } + return obj; + }; + TextProperty.prototype.setCurrentData = function(data2) { + if (!data2.__complete) { + this.completeTextData(data2); + } + this.currentData = data2; + this.currentData.boxWidth = this.currentData.boxWidth || this.defaultBoxWidth; + this._mdf = true; + }; + TextProperty.prototype.searchProperty = function() { + return this.searchKeyframes(); + }; + TextProperty.prototype.searchKeyframes = function() { + this.kf = this.data.d.k.length > 1; + if (this.kf) { + this.addEffect(this.getKeyframeValue.bind(this)); + } + return this.kf; + }; + TextProperty.prototype.addEffect = function(effectFunction) { + this.effectsSequence.push(effectFunction); + this.elem.addDynamicProperty(this); + }; + TextProperty.prototype.getValue = function(_finalValue) { + if ((this.elem.globalData.frameId === this.frameId || !this.effectsSequence.length) && !_finalValue) { + return; + } + this.currentData.t = this.data.d.k[this.keysIndex].s.t; + var currentValue = this.currentData; + var currentIndex = this.keysIndex; + if (this.lock) { + this.setCurrentData(this.currentData); + return; + } + this.lock = true; + this._mdf = false; + var i; + var len = this.effectsSequence.length; + var finalValue = _finalValue || this.data.d.k[this.keysIndex].s; + for (i = 0;i < len; i += 1) { + if (currentIndex !== this.keysIndex) { + finalValue = this.effectsSequence[i](finalValue, finalValue.t); + } else { + finalValue = this.effectsSequence[i](this.currentData, finalValue.t); + } + } + if (currentValue !== finalValue) { + this.setCurrentData(finalValue); + } + this.v = this.currentData; + this.pv = this.v; + this.lock = false; + this.frameId = this.elem.globalData.frameId; + }; + TextProperty.prototype.getKeyframeValue = function() { + var textKeys = this.data.d.k; + var frameNum = this.elem.comp.renderedFrame; + var i = 0; + var len = textKeys.length; + while (i <= len - 1) { + if (i === len - 1 || textKeys[i + 1].t > frameNum) { + break; + } + i += 1; + } + if (this.keysIndex !== i) { + this.keysIndex = i; + } + return this.data.d.k[this.keysIndex].s; + }; + TextProperty.prototype.buildFinalText = function(text2) { + var charactersArray = []; + var i = 0; + var len = text2.length; + var charCode; + var secondCharCode; + var shouldCombine = false; + while (i < len) { + charCode = text2.charCodeAt(i); + if (FontManager.isCombinedCharacter(charCode)) { + charactersArray[charactersArray.length - 1] += text2.charAt(i); + } else if (charCode >= 55296 && charCode <= 56319) { + secondCharCode = text2.charCodeAt(i + 1); + if (secondCharCode >= 56320 && secondCharCode <= 57343) { + if (shouldCombine || FontManager.isModifier(charCode, secondCharCode)) { + charactersArray[charactersArray.length - 1] += text2.substr(i, 2); + shouldCombine = false; + } else { + charactersArray.push(text2.substr(i, 2)); + } + i += 1; + } else { + charactersArray.push(text2.charAt(i)); + } + } else if (charCode > 56319) { + secondCharCode = text2.charCodeAt(i + 1); + if (FontManager.isZeroWidthJoiner(charCode, secondCharCode)) { + shouldCombine = true; + charactersArray[charactersArray.length - 1] += text2.substr(i, 2); + i += 1; + } else { + charactersArray.push(text2.charAt(i)); + } + } else if (FontManager.isZeroWidthJoiner(charCode)) { + charactersArray[charactersArray.length - 1] += text2.charAt(i); + shouldCombine = true; + } else { + charactersArray.push(text2.charAt(i)); + } + i += 1; + } + return charactersArray; + }; + TextProperty.prototype.completeTextData = function(documentData) { + documentData.__complete = true; + var fontManager = this.elem.globalData.fontManager; + var data2 = this.data; + var letters = []; + var i; + var len; + var newLineFlag; + var index2 = 0; + var val2; + var anchorGrouping = data2.m.g; + var currentSize = 0; + var currentPos = 0; + var currentLine = 0; + var lineWidths = []; + var lineWidth = 0; + var maxLineWidth = 0; + var j2; + var jLen; + var fontData = fontManager.getFontByName(documentData.f); + var charData; + var cLength = 0; + var fontProps = getFontProperties(fontData); + documentData.fWeight = fontProps.weight; + documentData.fStyle = fontProps.style; + documentData.finalSize = documentData.s; + documentData.finalText = this.buildFinalText(documentData.t); + len = documentData.finalText.length; + documentData.finalLineHeight = documentData.lh; + var trackingOffset = documentData.tr / 1000 * documentData.finalSize; + var charCode; + if (documentData.sz) { + var flag = true; + var boxWidth = documentData.sz[0]; + var boxHeight = documentData.sz[1]; + var currentHeight; + var finalText; + while (flag) { + finalText = this.buildFinalText(documentData.t); + currentHeight = 0; + lineWidth = 0; + len = finalText.length; + trackingOffset = documentData.tr / 1000 * documentData.finalSize; + var lastSpaceIndex = -1; + for (i = 0;i < len; i += 1) { + charCode = finalText[i].charCodeAt(0); + newLineFlag = false; + if (finalText[i] === " ") { + lastSpaceIndex = i; + } else if (charCode === 13 || charCode === 3) { + lineWidth = 0; + newLineFlag = true; + currentHeight += documentData.finalLineHeight || documentData.finalSize * 1.2; + } + if (fontManager.chars) { + charData = fontManager.getCharData(finalText[i], fontData.fStyle, fontData.fFamily); + cLength = newLineFlag ? 0 : charData.w * documentData.finalSize / 100; + } else { + cLength = fontManager.measureText(finalText[i], documentData.f, documentData.finalSize); + } + if (lineWidth + cLength > boxWidth && finalText[i] !== " ") { + if (lastSpaceIndex === -1) { + len += 1; + } else { + i = lastSpaceIndex; + } + currentHeight += documentData.finalLineHeight || documentData.finalSize * 1.2; + finalText.splice(i, lastSpaceIndex === i ? 1 : 0, "\r"); + lastSpaceIndex = -1; + lineWidth = 0; + } else { + lineWidth += cLength; + lineWidth += trackingOffset; + } + } + currentHeight += fontData.ascent * documentData.finalSize / 100; + if (this.canResize && documentData.finalSize > this.minimumFontSize && boxHeight < currentHeight) { + documentData.finalSize -= 1; + documentData.finalLineHeight = documentData.finalSize * documentData.lh / documentData.s; + } else { + documentData.finalText = finalText; + len = documentData.finalText.length; + flag = false; + } + } + } + lineWidth = -trackingOffset; + cLength = 0; + var uncollapsedSpaces = 0; + var currentChar; + for (i = 0;i < len; i += 1) { + newLineFlag = false; + currentChar = documentData.finalText[i]; + charCode = currentChar.charCodeAt(0); + if (charCode === 13 || charCode === 3) { + uncollapsedSpaces = 0; + lineWidths.push(lineWidth); + maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth; + lineWidth = -2 * trackingOffset; + val2 = ""; + newLineFlag = true; + currentLine += 1; + } else { + val2 = currentChar; + } + if (fontManager.chars) { + charData = fontManager.getCharData(currentChar, fontData.fStyle, fontManager.getFontByName(documentData.f).fFamily); + cLength = newLineFlag ? 0 : charData.w * documentData.finalSize / 100; + } else { + cLength = fontManager.measureText(val2, documentData.f, documentData.finalSize); + } + if (currentChar === " ") { + uncollapsedSpaces += cLength + trackingOffset; + } else { + lineWidth += cLength + trackingOffset + uncollapsedSpaces; + uncollapsedSpaces = 0; + } + letters.push({ + l: cLength, + an: cLength, + add: currentSize, + n: newLineFlag, + anIndexes: [], + val: val2, + line: currentLine, + animatorJustifyOffset: 0 + }); + if (anchorGrouping == 2) { + currentSize += cLength; + if (val2 === "" || val2 === " " || i === len - 1) { + if (val2 === "" || val2 === " ") { + currentSize -= cLength; + } + while (currentPos <= i) { + letters[currentPos].an = currentSize; + letters[currentPos].ind = index2; + letters[currentPos].extra = cLength; + currentPos += 1; + } + index2 += 1; + currentSize = 0; + } + } else if (anchorGrouping == 3) { + currentSize += cLength; + if (val2 === "" || i === len - 1) { + if (val2 === "") { + currentSize -= cLength; + } + while (currentPos <= i) { + letters[currentPos].an = currentSize; + letters[currentPos].ind = index2; + letters[currentPos].extra = cLength; + currentPos += 1; + } + currentSize = 0; + index2 += 1; + } + } else { + letters[index2].ind = index2; + letters[index2].extra = 0; + index2 += 1; + } + } + documentData.l = letters; + maxLineWidth = lineWidth > maxLineWidth ? lineWidth : maxLineWidth; + lineWidths.push(lineWidth); + if (documentData.sz) { + documentData.boxWidth = documentData.sz[0]; + documentData.justifyOffset = 0; + } else { + documentData.boxWidth = maxLineWidth; + switch (documentData.j) { + case 1: + documentData.justifyOffset = -documentData.boxWidth; + break; + case 2: + documentData.justifyOffset = -documentData.boxWidth / 2; + break; + default: + documentData.justifyOffset = 0; + } + } + documentData.lineWidths = lineWidths; + var animators = data2.a; + var animatorData; + var letterData; + jLen = animators.length; + var based; + var ind; + var indexes = []; + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorData = animators[j2]; + if (animatorData.a.sc) { + documentData.strokeColorAnim = true; + } + if (animatorData.a.sw) { + documentData.strokeWidthAnim = true; + } + if (animatorData.a.fc || animatorData.a.fh || animatorData.a.fs || animatorData.a.fb) { + documentData.fillColorAnim = true; + } + ind = 0; + based = animatorData.s.b; + for (i = 0;i < len; i += 1) { + letterData = letters[i]; + letterData.anIndexes[j2] = ind; + if (based == 1 && letterData.val !== "" || based == 2 && letterData.val !== "" && letterData.val !== " " || based == 3 && (letterData.n || letterData.val == " " || i == len - 1) || based == 4 && (letterData.n || i == len - 1)) { + if (animatorData.s.rn === 1) { + indexes.push(ind); + } + ind += 1; + } + } + data2.a[j2].s.totalChars = ind; + var currentInd = -1; + var newInd; + if (animatorData.s.rn === 1) { + for (i = 0;i < len; i += 1) { + letterData = letters[i]; + if (currentInd != letterData.anIndexes[j2]) { + currentInd = letterData.anIndexes[j2]; + newInd = indexes.splice(Math.floor(Math.random() * indexes.length), 1)[0]; + } + letterData.anIndexes[j2] = newInd; + } + } + } + documentData.yOffset = documentData.finalLineHeight || documentData.finalSize * 1.2; + documentData.ls = documentData.ls || 0; + documentData.ascent = fontData.ascent * documentData.finalSize / 100; + }; + TextProperty.prototype.updateDocumentData = function(newData, index2) { + index2 = index2 === undefined ? this.keysIndex : index2; + var dData = this.copyData({}, this.data.d.k[index2].s); + dData = this.copyData(dData, newData); + this.data.d.k[index2].s = dData; + this.recalculate(index2); + this.elem.addDynamicProperty(this); + }; + TextProperty.prototype.recalculate = function(index2) { + var dData = this.data.d.k[index2].s; + dData.__complete = false; + this.keysIndex = 0; + this._isFirstFrame = true; + this.getValue(dData); + }; + TextProperty.prototype.canResizeFont = function(_canResize) { + this.canResize = _canResize; + this.recalculate(this.keysIndex); + this.elem.addDynamicProperty(this); + }; + TextProperty.prototype.setMinimumFontSize = function(_fontValue) { + this.minimumFontSize = Math.floor(_fontValue) || 1; + this.recalculate(this.keysIndex); + this.elem.addDynamicProperty(this); + }; + const TextSelectorProp = function() { + var max = Math.max; + var min = Math.min; + var floor = Math.floor; + function TextSelectorPropFactory(elem2, data2) { + this._currentTextLength = -1; + this.k = false; + this.data = data2; + this.elem = elem2; + this.comp = elem2.comp; + this.finalS = 0; + this.finalE = 0; + this.initDynamicPropertyContainer(elem2); + this.s = PropertyFactory.getProp(elem2, data2.s || { k: 0 }, 0, 0, this); + if ("e" in data2) { + this.e = PropertyFactory.getProp(elem2, data2.e, 0, 0, this); + } else { + this.e = { v: 100 }; + } + this.o = PropertyFactory.getProp(elem2, data2.o || { k: 0 }, 0, 0, this); + this.xe = PropertyFactory.getProp(elem2, data2.xe || { k: 0 }, 0, 0, this); + this.ne = PropertyFactory.getProp(elem2, data2.ne || { k: 0 }, 0, 0, this); + this.sm = PropertyFactory.getProp(elem2, data2.sm || { k: 100 }, 0, 0, this); + this.a = PropertyFactory.getProp(elem2, data2.a, 0, 0.01, this); + if (!this.dynamicProperties.length) { + this.getValue(); + } + } + TextSelectorPropFactory.prototype = { + getMult: function(ind) { + if (this._currentTextLength !== this.elem.textProperty.currentData.l.length) { + this.getValue(); + } + var x1 = 0; + var y1 = 0; + var x2 = 1; + var y2 = 1; + if (this.ne.v > 0) { + x1 = this.ne.v / 100; + } else { + y1 = -this.ne.v / 100; + } + if (this.xe.v > 0) { + x2 = 1 - this.xe.v / 100; + } else { + y2 = 1 + this.xe.v / 100; + } + var easer = BezierFactory.getBezierEasing(x1, y1, x2, y2).get; + var mult = 0; + var s = this.finalS; + var e = this.finalE; + var type = this.data.sh; + if (type === 2) { + if (e === s) { + mult = ind >= e ? 1 : 0; + } else { + mult = max(0, min(0.5 / (e - s) + (ind - s) / (e - s), 1)); + } + mult = easer(mult); + } else if (type === 3) { + if (e === s) { + mult = ind >= e ? 0 : 1; + } else { + mult = 1 - max(0, min(0.5 / (e - s) + (ind - s) / (e - s), 1)); + } + mult = easer(mult); + } else if (type === 4) { + if (e === s) { + mult = 0; + } else { + mult = max(0, min(0.5 / (e - s) + (ind - s) / (e - s), 1)); + if (mult < 0.5) { + mult *= 2; + } else { + mult = 1 - 2 * (mult - 0.5); + } + } + mult = easer(mult); + } else if (type === 5) { + if (e === s) { + mult = 0; + } else { + var tot = e - s; + ind = min(max(0, ind + 0.5 - s), e - s); + var x3 = -tot / 2 + ind; + var a = tot / 2; + mult = Math.sqrt(1 - x3 * x3 / (a * a)); + } + mult = easer(mult); + } else if (type === 6) { + if (e === s) { + mult = 0; + } else { + ind = min(max(0, ind + 0.5 - s), e - s); + mult = (1 + Math.cos(Math.PI + Math.PI * 2 * ind / (e - s))) / 2; + } + mult = easer(mult); + } else { + if (ind >= floor(s)) { + if (ind - s < 0) { + mult = max(0, min(min(e, 1) - (s - ind), 1)); + } else { + mult = max(0, min(e - ind, 1)); + } + } + mult = easer(mult); + } + if (this.sm.v !== 100) { + var smoothness = this.sm.v * 0.01; + if (smoothness === 0) { + smoothness = 0.00000001; + } + var threshold = 0.5 - smoothness * 0.5; + if (mult < threshold) { + mult = 0; + } else { + mult = (mult - threshold) / smoothness; + if (mult > 1) { + mult = 1; + } + } + } + return mult * this.a.v; + }, + getValue: function(newCharsFlag) { + this.iterateDynamicProperties(); + this._mdf = newCharsFlag || this._mdf; + this._currentTextLength = this.elem.textProperty.currentData.l.length || 0; + if (newCharsFlag && this.data.r === 2) { + this.e.v = this._currentTextLength; + } + var divisor = this.data.r === 2 ? 1 : 100 / this.data.totalChars; + var o = this.o.v / divisor; + var s = this.s.v / divisor + o; + var e = this.e.v / divisor + o; + if (s > e) { + var _s = s; + s = e; + e = _s; + } + this.finalS = s; + this.finalE = e; + } + }; + extendPrototype([DynamicPropertyContainer], TextSelectorPropFactory); + function getTextSelectorProp(elem2, data2, arr) { + return new TextSelectorPropFactory(elem2, data2, arr); + } + return { + getTextSelectorProp + }; + }(); + TextAnimatorProperty.prototype.searchProperties = function() { + var i; + var len = this._textData.a.length; + var animatorProps; + var getProp = PropertyFactory.getProp; + for (i = 0;i < len; i += 1) { + animatorProps = this._textData.a[i]; + this._animatorsData[i] = new TextAnimatorDataProperty(this._elem, animatorProps, this); + } + if (this._textData.p && "m" in this._textData.p) { + this._pathData = { + a: getProp(this._elem, this._textData.p.a, 0, 0, this), + f: getProp(this._elem, this._textData.p.f, 0, 0, this), + l: getProp(this._elem, this._textData.p.l, 0, 0, this), + r: getProp(this._elem, this._textData.p.r, 0, 0, this), + p: getProp(this._elem, this._textData.p.p, 0, 0, this), + m: this._elem.maskManager.getMaskProperty(this._textData.p.m) + }; + this._hasMaskedPath = true; + } else { + this._hasMaskedPath = false; + } + this._moreOptions.alignment = getProp(this._elem, this._textData.m.a, 1, 0, this); + }; + TextAnimatorProperty.prototype.getMeasures = function(documentData, lettersChangedFlag) { + this.lettersChangedFlag = lettersChangedFlag; + if (!this._mdf && !this._isFirstFrame && !lettersChangedFlag && (!this._hasMaskedPath || !this._pathData.m._mdf)) { + return; + } + this._isFirstFrame = false; + var alignment = this._moreOptions.alignment.v; + var animators = this._animatorsData; + var textData = this._textData; + var matrixHelper = this.mHelper; + var renderType = this._renderType; + var renderedLettersCount = this.renderedLetters.length; + var xPos; + var yPos; + var i; + var len; + var letters = documentData.l; + var pathInfo; + var currentLength; + var currentPoint; + var segmentLength; + var flag; + var pointInd; + var segmentInd; + var prevPoint; + var points; + var segments; + var partialLength; + var totalLength; + var perc; + var tanAngle; + var mask2; + if (this._hasMaskedPath) { + mask2 = this._pathData.m; + if (!this._pathData.n || this._pathData._mdf) { + var paths = mask2.v; + if (this._pathData.r.v) { + paths = paths.reverse(); + } + pathInfo = { + tLength: 0, + segments: [] + }; + len = paths._length - 1; + var bezierData; + totalLength = 0; + for (i = 0;i < len; i += 1) { + bezierData = bez.buildBezierData(paths.v[i], paths.v[i + 1], [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]], [paths.i[i + 1][0] - paths.v[i + 1][0], paths.i[i + 1][1] - paths.v[i + 1][1]]); + pathInfo.tLength += bezierData.segmentLength; + pathInfo.segments.push(bezierData); + totalLength += bezierData.segmentLength; + } + i = len; + if (mask2.v.c) { + bezierData = bez.buildBezierData(paths.v[i], paths.v[0], [paths.o[i][0] - paths.v[i][0], paths.o[i][1] - paths.v[i][1]], [paths.i[0][0] - paths.v[0][0], paths.i[0][1] - paths.v[0][1]]); + pathInfo.tLength += bezierData.segmentLength; + pathInfo.segments.push(bezierData); + totalLength += bezierData.segmentLength; + } + this._pathData.pi = pathInfo; + } + pathInfo = this._pathData.pi; + currentLength = this._pathData.f.v; + segmentInd = 0; + pointInd = 1; + segmentLength = 0; + flag = true; + segments = pathInfo.segments; + if (currentLength < 0 && mask2.v.c) { + if (pathInfo.tLength < Math.abs(currentLength)) { + currentLength = -Math.abs(currentLength) % pathInfo.tLength; + } + segmentInd = segments.length - 1; + points = segments[segmentInd].points; + pointInd = points.length - 1; + while (currentLength < 0) { + currentLength += points[pointInd].partialLength; + pointInd -= 1; + if (pointInd < 0) { + segmentInd -= 1; + points = segments[segmentInd].points; + pointInd = points.length - 1; + } + } + } + points = segments[segmentInd].points; + prevPoint = points[pointInd - 1]; + currentPoint = points[pointInd]; + partialLength = currentPoint.partialLength; + } + len = letters.length; + xPos = 0; + yPos = 0; + var yOff = documentData.finalSize * 1.2 * 0.714; + var firstLine = true; + var animatorProps; + var animatorSelector; + var j2; + var jLen; + var letterValue; + jLen = animators.length; + var mult; + var ind = -1; + var offf; + var xPathPos; + var yPathPos; + var initPathPos = currentLength; + var initSegmentInd = segmentInd; + var initPointInd = pointInd; + var currentLine = -1; + var elemOpacity; + var sc; + var sw; + var fc; + var k2; + var letterSw; + var letterSc; + var letterFc; + var letterM = ""; + var letterP = this.defaultPropsArray; + var letterO; + if (documentData.j === 2 || documentData.j === 1) { + var animatorJustifyOffset = 0; + var animatorFirstCharOffset = 0; + var justifyOffsetMult = documentData.j === 2 ? -0.5 : -1; + var lastIndex = 0; + var isNewLine = true; + for (i = 0;i < len; i += 1) { + if (letters[i].n) { + if (animatorJustifyOffset) { + animatorJustifyOffset += animatorFirstCharOffset; + } + while (lastIndex < i) { + letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset; + lastIndex += 1; + } + animatorJustifyOffset = 0; + isNewLine = true; + } else { + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.t.propType) { + if (isNewLine && documentData.j === 2) { + animatorFirstCharOffset += animatorProps.t.v * justifyOffsetMult; + } + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + animatorJustifyOffset += animatorProps.t.v * mult[0] * justifyOffsetMult; + } else { + animatorJustifyOffset += animatorProps.t.v * mult * justifyOffsetMult; + } + } + } + isNewLine = false; + } + } + if (animatorJustifyOffset) { + animatorJustifyOffset += animatorFirstCharOffset; + } + while (lastIndex < i) { + letters[lastIndex].animatorJustifyOffset = animatorJustifyOffset; + lastIndex += 1; + } + } + for (i = 0;i < len; i += 1) { + matrixHelper.reset(); + elemOpacity = 1; + if (letters[i].n) { + xPos = 0; + yPos += documentData.yOffset; + yPos += firstLine ? 1 : 0; + currentLength = initPathPos; + firstLine = false; + if (this._hasMaskedPath) { + segmentInd = initSegmentInd; + pointInd = initPointInd; + points = segments[segmentInd].points; + prevPoint = points[pointInd - 1]; + currentPoint = points[pointInd]; + partialLength = currentPoint.partialLength; + segmentLength = 0; + } + letterM = ""; + letterFc = ""; + letterSw = ""; + letterO = ""; + letterP = this.defaultPropsArray; + } else { + if (this._hasMaskedPath) { + if (currentLine !== letters[i].line) { + switch (documentData.j) { + case 1: + currentLength += totalLength - documentData.lineWidths[letters[i].line]; + break; + case 2: + currentLength += (totalLength - documentData.lineWidths[letters[i].line]) / 2; + break; + default: + break; + } + currentLine = letters[i].line; + } + if (ind !== letters[i].ind) { + if (letters[ind]) { + currentLength += letters[ind].extra; + } + currentLength += letters[i].an / 2; + ind = letters[i].ind; + } + currentLength += alignment[0] * letters[i].an * 0.005; + var animatorOffset = 0; + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.p.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + animatorOffset += animatorProps.p.v[0] * mult[0]; + } else { + animatorOffset += animatorProps.p.v[0] * mult; + } + } + if (animatorProps.a.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + animatorOffset += animatorProps.a.v[0] * mult[0]; + } else { + animatorOffset += animatorProps.a.v[0] * mult; + } + } + } + flag = true; + if (this._pathData.a.v) { + currentLength = letters[0].an * 0.5 + (totalLength - this._pathData.f.v - letters[0].an * 0.5 - letters[letters.length - 1].an * 0.5) * ind / (len - 1); + currentLength += this._pathData.f.v; + } + while (flag) { + if (segmentLength + partialLength >= currentLength + animatorOffset || !points) { + perc = (currentLength + animatorOffset - segmentLength) / currentPoint.partialLength; + xPathPos = prevPoint.point[0] + (currentPoint.point[0] - prevPoint.point[0]) * perc; + yPathPos = prevPoint.point[1] + (currentPoint.point[1] - prevPoint.point[1]) * perc; + matrixHelper.translate(-alignment[0] * letters[i].an * 0.005, -(alignment[1] * yOff) * 0.01); + flag = false; + } else if (points) { + segmentLength += currentPoint.partialLength; + pointInd += 1; + if (pointInd >= points.length) { + pointInd = 0; + segmentInd += 1; + if (!segments[segmentInd]) { + if (mask2.v.c) { + pointInd = 0; + segmentInd = 0; + points = segments[segmentInd].points; + } else { + segmentLength -= currentPoint.partialLength; + points = null; + } + } else { + points = segments[segmentInd].points; + } + } + if (points) { + prevPoint = currentPoint; + currentPoint = points[pointInd]; + partialLength = currentPoint.partialLength; + } + } + } + offf = letters[i].an / 2 - letters[i].add; + matrixHelper.translate(-offf, 0, 0); + } else { + offf = letters[i].an / 2 - letters[i].add; + matrixHelper.translate(-offf, 0, 0); + matrixHelper.translate(-alignment[0] * letters[i].an * 0.005, -alignment[1] * yOff * 0.01, 0); + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.t.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (xPos !== 0 || documentData.j !== 0) { + if (this._hasMaskedPath) { + if (mult.length) { + currentLength += animatorProps.t.v * mult[0]; + } else { + currentLength += animatorProps.t.v * mult; + } + } else if (mult.length) { + xPos += animatorProps.t.v * mult[0]; + } else { + xPos += animatorProps.t.v * mult; + } + } + } + } + if (documentData.strokeWidthAnim) { + sw = documentData.sw || 0; + } + if (documentData.strokeColorAnim) { + if (documentData.sc) { + sc = [documentData.sc[0], documentData.sc[1], documentData.sc[2]]; + } else { + sc = [0, 0, 0]; + } + } + if (documentData.fillColorAnim && documentData.fc) { + fc = [documentData.fc[0], documentData.fc[1], documentData.fc[2]]; + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.a.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + matrixHelper.translate(-animatorProps.a.v[0] * mult[0], -animatorProps.a.v[1] * mult[1], animatorProps.a.v[2] * mult[2]); + } else { + matrixHelper.translate(-animatorProps.a.v[0] * mult, -animatorProps.a.v[1] * mult, animatorProps.a.v[2] * mult); + } + } + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.s.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (mult.length) { + matrixHelper.scale(1 + (animatorProps.s.v[0] - 1) * mult[0], 1 + (animatorProps.s.v[1] - 1) * mult[1], 1); + } else { + matrixHelper.scale(1 + (animatorProps.s.v[0] - 1) * mult, 1 + (animatorProps.s.v[1] - 1) * mult, 1); + } + } + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (animatorProps.sk.propType) { + if (mult.length) { + matrixHelper.skewFromAxis(-animatorProps.sk.v * mult[0], animatorProps.sa.v * mult[1]); + } else { + matrixHelper.skewFromAxis(-animatorProps.sk.v * mult, animatorProps.sa.v * mult); + } + } + if (animatorProps.r.propType) { + if (mult.length) { + matrixHelper.rotateZ(-animatorProps.r.v * mult[2]); + } else { + matrixHelper.rotateZ(-animatorProps.r.v * mult); + } + } + if (animatorProps.ry.propType) { + if (mult.length) { + matrixHelper.rotateY(animatorProps.ry.v * mult[1]); + } else { + matrixHelper.rotateY(animatorProps.ry.v * mult); + } + } + if (animatorProps.rx.propType) { + if (mult.length) { + matrixHelper.rotateX(animatorProps.rx.v * mult[0]); + } else { + matrixHelper.rotateX(animatorProps.rx.v * mult); + } + } + if (animatorProps.o.propType) { + if (mult.length) { + elemOpacity += (animatorProps.o.v * mult[0] - elemOpacity) * mult[0]; + } else { + elemOpacity += (animatorProps.o.v * mult - elemOpacity) * mult; + } + } + if (documentData.strokeWidthAnim && animatorProps.sw.propType) { + if (mult.length) { + sw += animatorProps.sw.v * mult[0]; + } else { + sw += animatorProps.sw.v * mult; + } + } + if (documentData.strokeColorAnim && animatorProps.sc.propType) { + for (k2 = 0;k2 < 3; k2 += 1) { + if (mult.length) { + sc[k2] += (animatorProps.sc.v[k2] - sc[k2]) * mult[0]; + } else { + sc[k2] += (animatorProps.sc.v[k2] - sc[k2]) * mult; + } + } + } + if (documentData.fillColorAnim && documentData.fc) { + if (animatorProps.fc.propType) { + for (k2 = 0;k2 < 3; k2 += 1) { + if (mult.length) { + fc[k2] += (animatorProps.fc.v[k2] - fc[k2]) * mult[0]; + } else { + fc[k2] += (animatorProps.fc.v[k2] - fc[k2]) * mult; + } + } + } + if (animatorProps.fh.propType) { + if (mult.length) { + fc = addHueToRGB(fc, animatorProps.fh.v * mult[0]); + } else { + fc = addHueToRGB(fc, animatorProps.fh.v * mult); + } + } + if (animatorProps.fs.propType) { + if (mult.length) { + fc = addSaturationToRGB(fc, animatorProps.fs.v * mult[0]); + } else { + fc = addSaturationToRGB(fc, animatorProps.fs.v * mult); + } + } + if (animatorProps.fb.propType) { + if (mult.length) { + fc = addBrightnessToRGB(fc, animatorProps.fb.v * mult[0]); + } else { + fc = addBrightnessToRGB(fc, animatorProps.fb.v * mult); + } + } + } + } + for (j2 = 0;j2 < jLen; j2 += 1) { + animatorProps = animators[j2].a; + if (animatorProps.p.propType) { + animatorSelector = animators[j2].s; + mult = animatorSelector.getMult(letters[i].anIndexes[j2], textData.a[j2].s.totalChars); + if (this._hasMaskedPath) { + if (mult.length) { + matrixHelper.translate(0, animatorProps.p.v[1] * mult[0], -animatorProps.p.v[2] * mult[1]); + } else { + matrixHelper.translate(0, animatorProps.p.v[1] * mult, -animatorProps.p.v[2] * mult); + } + } else if (mult.length) { + matrixHelper.translate(animatorProps.p.v[0] * mult[0], animatorProps.p.v[1] * mult[1], -animatorProps.p.v[2] * mult[2]); + } else { + matrixHelper.translate(animatorProps.p.v[0] * mult, animatorProps.p.v[1] * mult, -animatorProps.p.v[2] * mult); + } + } + } + if (documentData.strokeWidthAnim) { + letterSw = sw < 0 ? 0 : sw; + } + if (documentData.strokeColorAnim) { + letterSc = "rgb(" + Math.round(sc[0] * 255) + "," + Math.round(sc[1] * 255) + "," + Math.round(sc[2] * 255) + ")"; + } + if (documentData.fillColorAnim && documentData.fc) { + letterFc = "rgb(" + Math.round(fc[0] * 255) + "," + Math.round(fc[1] * 255) + "," + Math.round(fc[2] * 255) + ")"; + } + if (this._hasMaskedPath) { + matrixHelper.translate(0, -documentData.ls); + matrixHelper.translate(0, alignment[1] * yOff * 0.01 + yPos, 0); + if (this._pathData.p.v) { + tanAngle = (currentPoint.point[1] - prevPoint.point[1]) / (currentPoint.point[0] - prevPoint.point[0]); + var rot = Math.atan(tanAngle) * 180 / Math.PI; + if (currentPoint.point[0] < prevPoint.point[0]) { + rot += 180; + } + matrixHelper.rotate(-rot * Math.PI / 180); + } + matrixHelper.translate(xPathPos, yPathPos, 0); + currentLength -= alignment[0] * letters[i].an * 0.005; + if (letters[i + 1] && ind !== letters[i + 1].ind) { + currentLength += letters[i].an / 2; + currentLength += documentData.tr * 0.001 * documentData.finalSize; + } + } else { + matrixHelper.translate(xPos, yPos, 0); + if (documentData.ps) { + matrixHelper.translate(documentData.ps[0], documentData.ps[1] + documentData.ascent, 0); + } + switch (documentData.j) { + case 1: + matrixHelper.translate(letters[i].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i].line]), 0, 0); + break; + case 2: + matrixHelper.translate(letters[i].animatorJustifyOffset + documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[letters[i].line]) / 2, 0, 0); + break; + default: + break; + } + matrixHelper.translate(0, -documentData.ls); + matrixHelper.translate(offf, 0, 0); + matrixHelper.translate(alignment[0] * letters[i].an * 0.005, alignment[1] * yOff * 0.01, 0); + xPos += letters[i].l + documentData.tr * 0.001 * documentData.finalSize; + } + if (renderType === "html") { + letterM = matrixHelper.toCSS(); + } else if (renderType === "svg") { + letterM = matrixHelper.to2dCSS(); + } else { + letterP = [matrixHelper.props[0], matrixHelper.props[1], matrixHelper.props[2], matrixHelper.props[3], matrixHelper.props[4], matrixHelper.props[5], matrixHelper.props[6], matrixHelper.props[7], matrixHelper.props[8], matrixHelper.props[9], matrixHelper.props[10], matrixHelper.props[11], matrixHelper.props[12], matrixHelper.props[13], matrixHelper.props[14], matrixHelper.props[15]]; + } + letterO = elemOpacity; + } + if (renderedLettersCount <= i) { + letterValue = new LetterProps(letterO, letterSw, letterSc, letterFc, letterM, letterP); + this.renderedLetters.push(letterValue); + renderedLettersCount += 1; + this.lettersChangedFlag = true; + } else { + letterValue = this.renderedLetters[i]; + this.lettersChangedFlag = letterValue.update(letterO, letterSw, letterSc, letterFc, letterM, letterP) || this.lettersChangedFlag; + } + } + }; + TextAnimatorProperty.prototype.getValue = function() { + if (this._elem.globalData.frameId === this._frameId) { + return; + } + this._frameId = this._elem.globalData.frameId; + this.iterateDynamicProperties(); + }; + TextAnimatorProperty.prototype.mHelper = new Matrix; + TextAnimatorProperty.prototype.defaultPropsArray = []; + extendPrototype([DynamicPropertyContainer], TextAnimatorProperty); + ITextElement.prototype.initElement = function(data2, globalData2, comp2) { + this.lettersChangedFlag = true; + this.initFrame(); + this.initBaseData(data2, globalData2, comp2); + this.textProperty = new TextProperty(this, data2.t, this.dynamicProperties); + this.textAnimator = new TextAnimatorProperty(data2.t, this.renderType, this); + this.initTransform(data2, globalData2, comp2); + this.initHierarchy(); + this.initRenderable(); + this.initRendererElement(); + this.createContainerElements(); + this.createRenderableComponents(); + this.createContent(); + this.hide(); + this.textAnimator.searchProperties(this.dynamicProperties); + }; + ITextElement.prototype.prepareFrame = function(num) { + this._mdf = false; + this.prepareRenderableFrame(num); + this.prepareProperties(num, this.isInRange); + if (this.textProperty._mdf || this.textProperty._isFirstFrame) { + this.buildNewText(); + this.textProperty._isFirstFrame = false; + this.textProperty._mdf = false; + } + }; + ITextElement.prototype.createPathShape = function(matrixHelper, shapes) { + var j2; + var jLen = shapes.length; + var pathNodes; + var shapeStr = ""; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (shapes[j2].ty === "sh") { + pathNodes = shapes[j2].ks.k; + shapeStr += buildShapeString(pathNodes, pathNodes.i.length, true, matrixHelper); + } + } + return shapeStr; + }; + ITextElement.prototype.updateDocumentData = function(newData, index2) { + this.textProperty.updateDocumentData(newData, index2); + }; + ITextElement.prototype.canResizeFont = function(_canResize) { + this.textProperty.canResizeFont(_canResize); + }; + ITextElement.prototype.setMinimumFontSize = function(_fontSize) { + this.textProperty.setMinimumFontSize(_fontSize); + }; + ITextElement.prototype.applyTextPropertiesToMatrix = function(documentData, matrixHelper, lineNumber, xPos, yPos) { + if (documentData.ps) { + matrixHelper.translate(documentData.ps[0], documentData.ps[1] + documentData.ascent, 0); + } + matrixHelper.translate(0, -documentData.ls, 0); + switch (documentData.j) { + case 1: + matrixHelper.translate(documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[lineNumber]), 0, 0); + break; + case 2: + matrixHelper.translate(documentData.justifyOffset + (documentData.boxWidth - documentData.lineWidths[lineNumber]) / 2, 0, 0); + break; + default: + break; + } + matrixHelper.translate(xPos, yPos, 0); + }; + ITextElement.prototype.buildColor = function(colorData) { + return "rgb(" + Math.round(colorData[0] * 255) + "," + Math.round(colorData[1] * 255) + "," + Math.round(colorData[2] * 255) + ")"; + }; + ITextElement.prototype.emptyProp = new LetterProps; + ITextElement.prototype.destroy = function() { + }; + emptyShapeData = { + shapes: [] + }; + extendPrototype([BaseElement, TransformElement, SVGBaseElement, HierarchyElement, FrameElement, RenderableDOMElement, ITextElement], SVGTextLottieElement); + SVGTextLottieElement.prototype.createContent = function() { + if (this.data.singleShape && !this.globalData.fontManager.chars) { + this.textContainer = createNS("text"); + } + }; + SVGTextLottieElement.prototype.buildTextContents = function(textArray) { + var i = 0; + var len = textArray.length; + var textContents = []; + var currentTextContent = ""; + while (i < len) { + if (textArray[i] === String.fromCharCode(13) || textArray[i] === String.fromCharCode(3)) { + textContents.push(currentTextContent); + currentTextContent = ""; + } else { + currentTextContent += textArray[i]; + } + i += 1; + } + textContents.push(currentTextContent); + return textContents; + }; + SVGTextLottieElement.prototype.buildShapeData = function(data2, scale2) { + if (data2.shapes && data2.shapes.length) { + var shape = data2.shapes[0]; + if (shape.it) { + var shapeItem = shape.it[shape.it.length - 1]; + if (shapeItem.s) { + shapeItem.s.k[0] = scale2; + shapeItem.s.k[1] = scale2; + } + } + } + return data2; + }; + SVGTextLottieElement.prototype.buildNewText = function() { + this.addDynamicProperty(this); + var i; + var len; + var documentData = this.textProperty.currentData; + this.renderedLetters = createSizedArray(documentData ? documentData.l.length : 0); + if (documentData.fc) { + this.layerElement.setAttribute("fill", this.buildColor(documentData.fc)); + } else { + this.layerElement.setAttribute("fill", "rgba(0,0,0,0)"); + } + if (documentData.sc) { + this.layerElement.setAttribute("stroke", this.buildColor(documentData.sc)); + this.layerElement.setAttribute("stroke-width", documentData.sw); + } + this.layerElement.setAttribute("font-size", documentData.finalSize); + var fontData = this.globalData.fontManager.getFontByName(documentData.f); + if (fontData.fClass) { + this.layerElement.setAttribute("class", fontData.fClass); + } else { + this.layerElement.setAttribute("font-family", fontData.fFamily); + var fWeight = documentData.fWeight; + var fStyle = documentData.fStyle; + this.layerElement.setAttribute("font-style", fStyle); + this.layerElement.setAttribute("font-weight", fWeight); + } + this.layerElement.setAttribute("aria-label", documentData.t); + var letters = documentData.l || []; + var usesGlyphs = !!this.globalData.fontManager.chars; + len = letters.length; + var tSpan; + var matrixHelper = this.mHelper; + var shapeStr = ""; + var singleShape = this.data.singleShape; + var xPos = 0; + var yPos = 0; + var firstLine = true; + var trackingOffset = documentData.tr * 0.001 * documentData.finalSize; + if (singleShape && !usesGlyphs && !documentData.sz) { + var tElement = this.textContainer; + var justify = "start"; + switch (documentData.j) { + case 1: + justify = "end"; + break; + case 2: + justify = "middle"; + break; + default: + justify = "start"; + break; + } + tElement.setAttribute("text-anchor", justify); + tElement.setAttribute("letter-spacing", trackingOffset); + var textContent = this.buildTextContents(documentData.finalText); + len = textContent.length; + yPos = documentData.ps ? documentData.ps[1] + documentData.ascent : 0; + for (i = 0;i < len; i += 1) { + tSpan = this.textSpans[i].span || createNS("tspan"); + tSpan.textContent = textContent[i]; + tSpan.setAttribute("x", 0); + tSpan.setAttribute("y", yPos); + tSpan.style.display = "inherit"; + tElement.appendChild(tSpan); + if (!this.textSpans[i]) { + this.textSpans[i] = { + span: null, + glyph: null + }; + } + this.textSpans[i].span = tSpan; + yPos += documentData.finalLineHeight; + } + this.layerElement.appendChild(tElement); + } else { + var cachedSpansLength = this.textSpans.length; + var charData; + for (i = 0;i < len; i += 1) { + if (!this.textSpans[i]) { + this.textSpans[i] = { + span: null, + childSpan: null, + glyph: null + }; + } + if (!usesGlyphs || !singleShape || i === 0) { + tSpan = cachedSpansLength > i ? this.textSpans[i].span : createNS(usesGlyphs ? "g" : "text"); + if (cachedSpansLength <= i) { + tSpan.setAttribute("stroke-linecap", "butt"); + tSpan.setAttribute("stroke-linejoin", "round"); + tSpan.setAttribute("stroke-miterlimit", "4"); + this.textSpans[i].span = tSpan; + if (usesGlyphs) { + var childSpan = createNS("g"); + tSpan.appendChild(childSpan); + this.textSpans[i].childSpan = childSpan; + } + this.textSpans[i].span = tSpan; + this.layerElement.appendChild(tSpan); + } + tSpan.style.display = "inherit"; + } + matrixHelper.reset(); + if (singleShape) { + if (letters[i].n) { + xPos = -trackingOffset; + yPos += documentData.yOffset; + yPos += firstLine ? 1 : 0; + firstLine = false; + } + this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i].line, xPos, yPos); + xPos += letters[i].l || 0; + xPos += trackingOffset; + } + if (usesGlyphs) { + charData = this.globalData.fontManager.getCharData(documentData.finalText[i], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily); + var glyphElement; + if (charData.t === 1) { + glyphElement = new SVGCompElement(charData.data, this.globalData, this); + } else { + var data2 = emptyShapeData; + if (charData.data && charData.data.shapes) { + data2 = this.buildShapeData(charData.data, documentData.finalSize); + } + glyphElement = new SVGShapeElement(data2, this.globalData, this); + } + if (this.textSpans[i].glyph) { + var glyph = this.textSpans[i].glyph; + this.textSpans[i].childSpan.removeChild(glyph.layerElement); + glyph.destroy(); + } + this.textSpans[i].glyph = glyphElement; + glyphElement._debug = true; + glyphElement.prepareFrame(0); + glyphElement.renderFrame(); + this.textSpans[i].childSpan.appendChild(glyphElement.layerElement); + if (charData.t === 1) { + this.textSpans[i].childSpan.setAttribute("transform", "scale(" + documentData.finalSize / 100 + "," + documentData.finalSize / 100 + ")"); + } + } else { + if (singleShape) { + tSpan.setAttribute("transform", "translate(" + matrixHelper.props[12] + "," + matrixHelper.props[13] + ")"); + } + tSpan.textContent = letters[i].val; + tSpan.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space", "preserve"); + } + } + if (singleShape && tSpan) { + tSpan.setAttribute("d", shapeStr); + } + } + while (i < this.textSpans.length) { + this.textSpans[i].span.style.display = "none"; + i += 1; + } + this._sizeChanged = true; + }; + SVGTextLottieElement.prototype.sourceRectAtTime = function() { + this.prepareFrame(this.comp.renderedFrame - this.data.st); + this.renderInnerContent(); + if (this._sizeChanged) { + this._sizeChanged = false; + var textBox = this.layerElement.getBBox(); + this.bbox = { + top: textBox.y, + left: textBox.x, + width: textBox.width, + height: textBox.height + }; + } + return this.bbox; + }; + SVGTextLottieElement.prototype.getValue = function() { + var i; + var len = this.textSpans.length; + var glyphElement; + this.renderedFrame = this.comp.renderedFrame; + for (i = 0;i < len; i += 1) { + glyphElement = this.textSpans[i].glyph; + if (glyphElement) { + glyphElement.prepareFrame(this.comp.renderedFrame - this.data.st); + if (glyphElement._mdf) { + this._mdf = true; + } + } + } + }; + SVGTextLottieElement.prototype.renderInnerContent = function() { + if (!this.data.singleShape || this._mdf) { + this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag); + if (this.lettersChangedFlag || this.textAnimator.lettersChangedFlag) { + this._sizeChanged = true; + var i; + var len; + var renderedLetters = this.textAnimator.renderedLetters; + var letters = this.textProperty.currentData.l; + len = letters.length; + var renderedLetter; + var textSpan; + var glyphElement; + for (i = 0;i < len; i += 1) { + if (!letters[i].n) { + renderedLetter = renderedLetters[i]; + textSpan = this.textSpans[i].span; + glyphElement = this.textSpans[i].glyph; + if (glyphElement) { + glyphElement.renderFrame(); + } + if (renderedLetter._mdf.m) { + textSpan.setAttribute("transform", renderedLetter.m); + } + if (renderedLetter._mdf.o) { + textSpan.setAttribute("opacity", renderedLetter.o); + } + if (renderedLetter._mdf.sw) { + textSpan.setAttribute("stroke-width", renderedLetter.sw); + } + if (renderedLetter._mdf.sc) { + textSpan.setAttribute("stroke", renderedLetter.sc); + } + if (renderedLetter._mdf.fc) { + textSpan.setAttribute("fill", renderedLetter.fc); + } + } + } + } + } + }; + extendPrototype([IImageElement], ISolidElement); + ISolidElement.prototype.createContent = function() { + var rect = createNS("rect"); + rect.setAttribute("width", this.data.sw); + rect.setAttribute("height", this.data.sh); + rect.setAttribute("fill", this.data.sc); + this.layerElement.appendChild(rect); + }; + NullElement.prototype.prepareFrame = function(num) { + this.prepareProperties(num, true); + }; + NullElement.prototype.renderFrame = function() { + }; + NullElement.prototype.getBaseElement = function() { + return null; + }; + NullElement.prototype.destroy = function() { + }; + NullElement.prototype.sourceRectAtTime = function() { + }; + NullElement.prototype.hide = function() { + }; + extendPrototype([BaseElement, TransformElement, HierarchyElement, FrameElement], NullElement); + extendPrototype([BaseRenderer], SVGRendererBase); + SVGRendererBase.prototype.createNull = function(data2) { + return new NullElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.createShape = function(data2) { + return new SVGShapeElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.createText = function(data2) { + return new SVGTextLottieElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.createImage = function(data2) { + return new IImageElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.createSolid = function(data2) { + return new ISolidElement(data2, this.globalData, this); + }; + SVGRendererBase.prototype.configAnimation = function(animData) { + this.svgElement.setAttribute("xmlns", "http://www.w3.org/2000/svg"); + if (this.renderConfig.viewBoxSize) { + this.svgElement.setAttribute("viewBox", this.renderConfig.viewBoxSize); + } else { + this.svgElement.setAttribute("viewBox", "0 0 " + animData.w + " " + animData.h); + } + if (!this.renderConfig.viewBoxOnly) { + this.svgElement.setAttribute("width", animData.w); + this.svgElement.setAttribute("height", animData.h); + this.svgElement.style.width = "100%"; + this.svgElement.style.height = "100%"; + this.svgElement.style.transform = "translate3d(0,0,0)"; + this.svgElement.style.contentVisibility = this.renderConfig.contentVisibility; + } + if (this.renderConfig.width) { + this.svgElement.setAttribute("width", this.renderConfig.width); + } + if (this.renderConfig.height) { + this.svgElement.setAttribute("height", this.renderConfig.height); + } + if (this.renderConfig.className) { + this.svgElement.setAttribute("class", this.renderConfig.className); + } + if (this.renderConfig.id) { + this.svgElement.setAttribute("id", this.renderConfig.id); + } + if (this.renderConfig.focusable !== undefined) { + this.svgElement.setAttribute("focusable", this.renderConfig.focusable); + } + this.svgElement.setAttribute("preserveAspectRatio", this.renderConfig.preserveAspectRatio); + this.animationItem.wrapper.appendChild(this.svgElement); + var defs = this.globalData.defs; + this.setupGlobalData(animData, defs); + this.globalData.progressiveLoad = this.renderConfig.progressiveLoad; + this.data = animData; + var maskElement = createNS("clipPath"); + var rect = createNS("rect"); + rect.setAttribute("width", animData.w); + rect.setAttribute("height", animData.h); + rect.setAttribute("x", 0); + rect.setAttribute("y", 0); + var maskId = createElementID(); + maskElement.setAttribute("id", maskId); + maskElement.appendChild(rect); + this.layerElement.setAttribute("clip-path", "url(" + getLocationHref() + "#" + maskId + ")"); + defs.appendChild(maskElement); + this.layers = animData.layers; + this.elements = createSizedArray(animData.layers.length); + }; + SVGRendererBase.prototype.destroy = function() { + if (this.animationItem.wrapper) { + this.animationItem.wrapper.innerText = ""; + } + this.layerElement = null; + this.globalData.defs = null; + var i; + var len = this.layers ? this.layers.length : 0; + for (i = 0;i < len; i += 1) { + if (this.elements[i]) { + this.elements[i].destroy(); + } + } + this.elements.length = 0; + this.destroyed = true; + this.animationItem = null; + }; + SVGRendererBase.prototype.updateContainerSize = function() { + }; + SVGRendererBase.prototype.buildItem = function(pos) { + var elements = this.elements; + if (elements[pos] || this.layers[pos].ty === 99) { + return; + } + elements[pos] = true; + var element = this.createItem(this.layers[pos]); + elements[pos] = element; + if (getExpressionsPlugin()) { + if (this.layers[pos].ty === 0) { + this.globalData.projectInterface.registerComposition(element); + } + element.initExpressions(); + } + this.appendElementInPos(element, pos); + if (this.layers[pos].tt) { + if (!this.elements[pos - 1] || this.elements[pos - 1] === true) { + this.buildItem(pos - 1); + this.addPendingElement(element); + } else { + element.setMatte(elements[pos - 1].layerId); + } + } + }; + SVGRendererBase.prototype.checkPendingElements = function() { + while (this.pendingElements.length) { + var element = this.pendingElements.pop(); + element.checkParenting(); + if (element.data.tt) { + var i = 0; + var len = this.elements.length; + while (i < len) { + if (this.elements[i] === element) { + element.setMatte(this.elements[i - 1].layerId); + break; + } + i += 1; + } + } + } + }; + SVGRendererBase.prototype.renderFrame = function(num) { + if (this.renderedFrame === num || this.destroyed) { + return; + } + if (num === null) { + num = this.renderedFrame; + } else { + this.renderedFrame = num; + } + this.globalData.frameNum = num; + this.globalData.frameId += 1; + this.globalData.projectInterface.currentFrame = num; + this.globalData._mdf = false; + var i; + var len = this.layers.length; + if (!this.completeLayers) { + this.checkLayers(num); + } + for (i = len - 1;i >= 0; i -= 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].prepareFrame(num - this.layers[i].st); + } + } + if (this.globalData._mdf) { + for (i = 0;i < len; i += 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].renderFrame(); + } + } + } + }; + SVGRendererBase.prototype.appendElementInPos = function(element, pos) { + var newElement = element.getBaseElement(); + if (!newElement) { + return; + } + var i = 0; + var nextElement; + while (i < pos) { + if (this.elements[i] && this.elements[i] !== true && this.elements[i].getBaseElement()) { + nextElement = this.elements[i].getBaseElement(); + } + i += 1; + } + if (nextElement) { + this.layerElement.insertBefore(newElement, nextElement); + } else { + this.layerElement.appendChild(newElement); + } + }; + SVGRendererBase.prototype.hide = function() { + this.layerElement.style.display = "none"; + }; + SVGRendererBase.prototype.show = function() { + this.layerElement.style.display = "block"; + }; + extendPrototype([BaseElement, TransformElement, HierarchyElement, FrameElement, RenderableDOMElement], ICompElement); + ICompElement.prototype.initElement = function(data2, globalData2, comp2) { + this.initFrame(); + this.initBaseData(data2, globalData2, comp2); + this.initTransform(data2, globalData2, comp2); + this.initRenderable(); + this.initHierarchy(); + this.initRendererElement(); + this.createContainerElements(); + this.createRenderableComponents(); + if (this.data.xt || !globalData2.progressiveLoad) { + this.buildAllItems(); + } + this.hide(); + }; + ICompElement.prototype.prepareFrame = function(num) { + this._mdf = false; + this.prepareRenderableFrame(num); + this.prepareProperties(num, this.isInRange); + if (!this.isInRange && !this.data.xt) { + return; + } + if (!this.tm._placeholder) { + var timeRemapped = this.tm.v; + if (timeRemapped === this.data.op) { + timeRemapped = this.data.op - 1; + } + this.renderedFrame = timeRemapped; + } else { + this.renderedFrame = num / this.data.sr; + } + var i; + var len = this.elements.length; + if (!this.completeLayers) { + this.checkLayers(this.renderedFrame); + } + for (i = len - 1;i >= 0; i -= 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].prepareFrame(this.renderedFrame - this.layers[i].st); + if (this.elements[i]._mdf) { + this._mdf = true; + } + } + } + }; + ICompElement.prototype.renderInnerContent = function() { + var i; + var len = this.layers.length; + for (i = 0;i < len; i += 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].renderFrame(); + } + } + }; + ICompElement.prototype.setElements = function(elems) { + this.elements = elems; + }; + ICompElement.prototype.getElements = function() { + return this.elements; + }; + ICompElement.prototype.destroyElements = function() { + var i; + var len = this.layers.length; + for (i = 0;i < len; i += 1) { + if (this.elements[i]) { + this.elements[i].destroy(); + } + } + }; + ICompElement.prototype.destroy = function() { + this.destroyElements(); + this.destroyBaseElement(); + }; + extendPrototype([SVGRendererBase, ICompElement, SVGBaseElement], SVGCompElement); + SVGCompElement.prototype.createComp = function(data2) { + return new SVGCompElement(data2, this.globalData, this); + }; + extendPrototype([SVGRendererBase], SVGRenderer); + SVGRenderer.prototype.createComp = function(data2) { + return new SVGCompElement(data2, this.globalData, this); + }; + CVContextData.prototype.duplicate = function() { + var newLength = this._length * 2; + var currentSavedOp = this.savedOp; + this.savedOp = createTypedArray("float32", newLength); + this.savedOp.set(currentSavedOp); + var i = 0; + for (i = this._length;i < newLength; i += 1) { + this.saved[i] = createTypedArray("float32", 16); + } + this._length = newLength; + }; + CVContextData.prototype.reset = function() { + this.cArrPos = 0; + this.cTr.reset(); + this.cO = 1; + }; + ShapeTransformManager.prototype = { + addTransformSequence: function(transforms) { + var i; + var len = transforms.length; + var key2 = "_"; + for (i = 0;i < len; i += 1) { + key2 += transforms[i].transform.key + "_"; + } + var sequence = this.sequences[key2]; + if (!sequence) { + sequence = { + transforms: [].concat(transforms), + finalTransform: new Matrix, + _mdf: false + }; + this.sequences[key2] = sequence; + this.sequenceList.push(sequence); + } + return sequence; + }, + processSequence: function(sequence, isFirstFrame) { + var i = 0; + var len = sequence.transforms.length; + var _mdf = isFirstFrame; + while (i < len && !isFirstFrame) { + if (sequence.transforms[i].transform.mProps._mdf) { + _mdf = true; + break; + } + i += 1; + } + if (_mdf) { + var props; + sequence.finalTransform.reset(); + for (i = len - 1;i >= 0; i -= 1) { + props = sequence.transforms[i].transform.mProps.v.props; + sequence.finalTransform.transform(props[0], props[1], props[2], props[3], props[4], props[5], props[6], props[7], props[8], props[9], props[10], props[11], props[12], props[13], props[14], props[15]); + } + } + sequence._mdf = _mdf; + }, + processSequences: function(isFirstFrame) { + var i; + var len = this.sequenceList.length; + for (i = 0;i < len; i += 1) { + this.processSequence(this.sequenceList[i], isFirstFrame); + } + }, + getNewKey: function() { + this.transform_key_count += 1; + return "_" + this.transform_key_count; + } + }; + CVEffects.prototype.renderFrame = function() { + }; + CVMaskElement.prototype.renderFrame = function() { + if (!this.hasMasks) { + return; + } + var transform2 = this.element.finalTransform.mat; + var ctx = this.element.canvasContext; + var i; + var len = this.masksProperties.length; + var pt; + var pts; + var data2; + ctx.beginPath(); + for (i = 0;i < len; i += 1) { + if (this.masksProperties[i].mode !== "n") { + if (this.masksProperties[i].inv) { + ctx.moveTo(0, 0); + ctx.lineTo(this.element.globalData.compSize.w, 0); + ctx.lineTo(this.element.globalData.compSize.w, this.element.globalData.compSize.h); + ctx.lineTo(0, this.element.globalData.compSize.h); + ctx.lineTo(0, 0); + } + data2 = this.viewData[i].v; + pt = transform2.applyToPointArray(data2.v[0][0], data2.v[0][1], 0); + ctx.moveTo(pt[0], pt[1]); + var j2; + var jLen = data2._length; + for (j2 = 1;j2 < jLen; j2 += 1) { + pts = transform2.applyToTriplePoints(data2.o[j2 - 1], data2.i[j2], data2.v[j2]); + ctx.bezierCurveTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]); + } + pts = transform2.applyToTriplePoints(data2.o[j2 - 1], data2.i[0], data2.v[0]); + ctx.bezierCurveTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]); + } + } + this.element.globalData.renderer.save(true); + ctx.clip(); + }; + CVMaskElement.prototype.getMaskProperty = MaskElement.prototype.getMaskProperty; + CVMaskElement.prototype.destroy = function() { + this.element = null; + }; + CVBaseElement.prototype = { + createElements: function() { + }, + initRendererElement: function() { + }, + createContainerElements: function() { + this.canvasContext = this.globalData.canvasContext; + this.renderableEffectsManager = new CVEffects(this); + }, + createContent: function() { + }, + setBlendMode: function() { + var globalData2 = this.globalData; + if (globalData2.blendMode !== this.data.bm) { + globalData2.blendMode = this.data.bm; + var blendModeValue = getBlendMode(this.data.bm); + globalData2.canvasContext.globalCompositeOperation = blendModeValue; + } + }, + createRenderableComponents: function() { + this.maskManager = new CVMaskElement(this.data, this); + }, + hideElement: function() { + if (!this.hidden && (!this.isInRange || this.isTransparent)) { + this.hidden = true; + } + }, + showElement: function() { + if (this.isInRange && !this.isTransparent) { + this.hidden = false; + this._isFirstFrame = true; + this.maskManager._isFirstFrame = true; + } + }, + renderFrame: function() { + if (this.hidden || this.data.hd) { + return; + } + this.renderTransform(); + this.renderRenderable(); + this.setBlendMode(); + var forceRealStack = this.data.ty === 0; + this.globalData.renderer.save(forceRealStack); + this.globalData.renderer.ctxTransform(this.finalTransform.mat.props); + this.globalData.renderer.ctxOpacity(this.finalTransform.mProp.o.v); + this.renderInnerContent(); + this.globalData.renderer.restore(forceRealStack); + if (this.maskManager.hasMasks) { + this.globalData.renderer.restore(true); + } + if (this._isFirstFrame) { + this._isFirstFrame = false; + } + }, + destroy: function() { + this.canvasContext = null; + this.data = null; + this.globalData = null; + this.maskManager.destroy(); + }, + mHelper: new Matrix + }; + CVBaseElement.prototype.hide = CVBaseElement.prototype.hideElement; + CVBaseElement.prototype.show = CVBaseElement.prototype.showElement; + CVShapeData.prototype.setAsAnimated = SVGShapeData.prototype.setAsAnimated; + extendPrototype([BaseElement, TransformElement, CVBaseElement, IShapeElement, HierarchyElement, FrameElement, RenderableElement], CVShapeElement); + CVShapeElement.prototype.initElement = RenderableDOMElement.prototype.initElement; + CVShapeElement.prototype.transformHelper = { opacity: 1, _opMdf: false }; + CVShapeElement.prototype.dashResetter = []; + CVShapeElement.prototype.createContent = function() { + this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, true, []); + }; + CVShapeElement.prototype.createStyleElement = function(data2, transforms) { + var styleElem = { + data: data2, + type: data2.ty, + preTransforms: this.transformsManager.addTransformSequence(transforms), + transforms: [], + elements: [], + closed: data2.hd === true + }; + var elementData = {}; + if (data2.ty === "fl" || data2.ty === "st") { + elementData.c = PropertyFactory.getProp(this, data2.c, 1, 255, this); + if (!elementData.c.k) { + styleElem.co = "rgb(" + bmFloor(elementData.c.v[0]) + "," + bmFloor(elementData.c.v[1]) + "," + bmFloor(elementData.c.v[2]) + ")"; + } + } else if (data2.ty === "gf" || data2.ty === "gs") { + elementData.s = PropertyFactory.getProp(this, data2.s, 1, null, this); + elementData.e = PropertyFactory.getProp(this, data2.e, 1, null, this); + elementData.h = PropertyFactory.getProp(this, data2.h || { k: 0 }, 0, 0.01, this); + elementData.a = PropertyFactory.getProp(this, data2.a || { k: 0 }, 0, degToRads, this); + elementData.g = new GradientProperty(this, data2.g, this); + } + elementData.o = PropertyFactory.getProp(this, data2.o, 0, 0.01, this); + if (data2.ty === "st" || data2.ty === "gs") { + styleElem.lc = lineCapEnum[data2.lc || 2]; + styleElem.lj = lineJoinEnum[data2.lj || 2]; + if (data2.lj == 1) { + styleElem.ml = data2.ml; + } + elementData.w = PropertyFactory.getProp(this, data2.w, 0, null, this); + if (!elementData.w.k) { + styleElem.wi = elementData.w.v; + } + if (data2.d) { + var d = new DashProperty(this, data2.d, "canvas", this); + elementData.d = d; + if (!elementData.d.k) { + styleElem.da = elementData.d.dashArray; + styleElem.do = elementData.d.dashoffset[0]; + } + } + } else { + styleElem.r = data2.r === 2 ? "evenodd" : "nonzero"; + } + this.stylesList.push(styleElem); + elementData.style = styleElem; + return elementData; + }; + CVShapeElement.prototype.createGroupElement = function() { + var elementData = { + it: [], + prevViewData: [] + }; + return elementData; + }; + CVShapeElement.prototype.createTransformElement = function(data2) { + var elementData = { + transform: { + opacity: 1, + _opMdf: false, + key: this.transformsManager.getNewKey(), + op: PropertyFactory.getProp(this, data2.o, 0, 0.01, this), + mProps: TransformPropertyFactory.getTransformProperty(this, data2, this) + } + }; + return elementData; + }; + CVShapeElement.prototype.createShapeElement = function(data2) { + var elementData = new CVShapeData(this, data2, this.stylesList, this.transformsManager); + this.shapes.push(elementData); + this.addShapeToModifiers(elementData); + return elementData; + }; + CVShapeElement.prototype.reloadShapes = function() { + this._isFirstFrame = true; + var i; + var len = this.itemsData.length; + for (i = 0;i < len; i += 1) { + this.prevViewData[i] = this.itemsData[i]; + } + this.searchShapes(this.shapesData, this.itemsData, this.prevViewData, true, []); + len = this.dynamicProperties.length; + for (i = 0;i < len; i += 1) { + this.dynamicProperties[i].getValue(); + } + this.renderModifiers(); + this.transformsManager.processSequences(this._isFirstFrame); + }; + CVShapeElement.prototype.addTransformToStyleList = function(transform2) { + var i; + var len = this.stylesList.length; + for (i = 0;i < len; i += 1) { + if (!this.stylesList[i].closed) { + this.stylesList[i].transforms.push(transform2); + } + } + }; + CVShapeElement.prototype.removeTransformFromStyleList = function() { + var i; + var len = this.stylesList.length; + for (i = 0;i < len; i += 1) { + if (!this.stylesList[i].closed) { + this.stylesList[i].transforms.pop(); + } + } + }; + CVShapeElement.prototype.closeStyles = function(styles) { + var i; + var len = styles.length; + for (i = 0;i < len; i += 1) { + styles[i].closed = true; + } + }; + CVShapeElement.prototype.searchShapes = function(arr, itemsData, prevViewData, shouldRender, transforms) { + var i; + var len = arr.length - 1; + var j2; + var jLen; + var ownStyles = []; + var ownModifiers = []; + var processedPos; + var modifier; + var currentTransform; + var ownTransforms = [].concat(transforms); + for (i = len;i >= 0; i -= 1) { + processedPos = this.searchProcessedElement(arr[i]); + if (!processedPos) { + arr[i]._shouldRender = shouldRender; + } else { + itemsData[i] = prevViewData[processedPos - 1]; + } + if (arr[i].ty === "fl" || arr[i].ty === "st" || arr[i].ty === "gf" || arr[i].ty === "gs") { + if (!processedPos) { + itemsData[i] = this.createStyleElement(arr[i], ownTransforms); + } else { + itemsData[i].style.closed = false; + } + ownStyles.push(itemsData[i].style); + } else if (arr[i].ty === "gr") { + if (!processedPos) { + itemsData[i] = this.createGroupElement(arr[i]); + } else { + jLen = itemsData[i].it.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + itemsData[i].prevViewData[j2] = itemsData[i].it[j2]; + } + } + this.searchShapes(arr[i].it, itemsData[i].it, itemsData[i].prevViewData, shouldRender, ownTransforms); + } else if (arr[i].ty === "tr") { + if (!processedPos) { + currentTransform = this.createTransformElement(arr[i]); + itemsData[i] = currentTransform; + } + ownTransforms.push(itemsData[i]); + this.addTransformToStyleList(itemsData[i]); + } else if (arr[i].ty === "sh" || arr[i].ty === "rc" || arr[i].ty === "el" || arr[i].ty === "sr") { + if (!processedPos) { + itemsData[i] = this.createShapeElement(arr[i]); + } + } else if (arr[i].ty === "tm" || arr[i].ty === "rd" || arr[i].ty === "pb") { + if (!processedPos) { + modifier = ShapeModifiers.getModifier(arr[i].ty); + modifier.init(this, arr[i]); + itemsData[i] = modifier; + this.shapeModifiers.push(modifier); + } else { + modifier = itemsData[i]; + modifier.closed = false; + } + ownModifiers.push(modifier); + } else if (arr[i].ty === "rp") { + if (!processedPos) { + modifier = ShapeModifiers.getModifier(arr[i].ty); + itemsData[i] = modifier; + modifier.init(this, arr, i, itemsData); + this.shapeModifiers.push(modifier); + shouldRender = false; + } else { + modifier = itemsData[i]; + modifier.closed = true; + } + ownModifiers.push(modifier); + } + this.addProcessedElement(arr[i], i + 1); + } + this.removeTransformFromStyleList(); + this.closeStyles(ownStyles); + len = ownModifiers.length; + for (i = 0;i < len; i += 1) { + ownModifiers[i].closed = true; + } + }; + CVShapeElement.prototype.renderInnerContent = function() { + this.transformHelper.opacity = 1; + this.transformHelper._opMdf = false; + this.renderModifiers(); + this.transformsManager.processSequences(this._isFirstFrame); + this.renderShape(this.transformHelper, this.shapesData, this.itemsData, true); + }; + CVShapeElement.prototype.renderShapeTransform = function(parentTransform, groupTransform) { + if (parentTransform._opMdf || groupTransform.op._mdf || this._isFirstFrame) { + groupTransform.opacity = parentTransform.opacity; + groupTransform.opacity *= groupTransform.op.v; + groupTransform._opMdf = true; + } + }; + CVShapeElement.prototype.drawLayer = function() { + var i; + var len = this.stylesList.length; + var j2; + var jLen; + var k2; + var kLen; + var elems; + var nodes; + var renderer2 = this.globalData.renderer; + var ctx = this.globalData.canvasContext; + var type; + var currentStyle; + for (i = 0;i < len; i += 1) { + currentStyle = this.stylesList[i]; + type = currentStyle.type; + if (!((type === "st" || type === "gs") && currentStyle.wi === 0 || !currentStyle.data._shouldRender || currentStyle.coOp === 0 || this.globalData.currentGlobalAlpha === 0)) { + renderer2.save(); + elems = currentStyle.elements; + if (type === "st" || type === "gs") { + ctx.strokeStyle = type === "st" ? currentStyle.co : currentStyle.grd; + ctx.lineWidth = currentStyle.wi; + ctx.lineCap = currentStyle.lc; + ctx.lineJoin = currentStyle.lj; + ctx.miterLimit = currentStyle.ml || 0; + } else { + ctx.fillStyle = type === "fl" ? currentStyle.co : currentStyle.grd; + } + renderer2.ctxOpacity(currentStyle.coOp); + if (type !== "st" && type !== "gs") { + ctx.beginPath(); + } + renderer2.ctxTransform(currentStyle.preTransforms.finalTransform.props); + jLen = elems.length; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (type === "st" || type === "gs") { + ctx.beginPath(); + if (currentStyle.da) { + ctx.setLineDash(currentStyle.da); + ctx.lineDashOffset = currentStyle.do; + } + } + nodes = elems[j2].trNodes; + kLen = nodes.length; + for (k2 = 0;k2 < kLen; k2 += 1) { + if (nodes[k2].t === "m") { + ctx.moveTo(nodes[k2].p[0], nodes[k2].p[1]); + } else if (nodes[k2].t === "c") { + ctx.bezierCurveTo(nodes[k2].pts[0], nodes[k2].pts[1], nodes[k2].pts[2], nodes[k2].pts[3], nodes[k2].pts[4], nodes[k2].pts[5]); + } else { + ctx.closePath(); + } + } + if (type === "st" || type === "gs") { + ctx.stroke(); + if (currentStyle.da) { + ctx.setLineDash(this.dashResetter); + } + } + } + if (type !== "st" && type !== "gs") { + ctx.fill(currentStyle.r); + } + renderer2.restore(); + } + } + }; + CVShapeElement.prototype.renderShape = function(parentTransform, items, data2, isMain) { + var i; + var len = items.length - 1; + var groupTransform; + groupTransform = parentTransform; + for (i = len;i >= 0; i -= 1) { + if (items[i].ty === "tr") { + groupTransform = data2[i].transform; + this.renderShapeTransform(parentTransform, groupTransform); + } else if (items[i].ty === "sh" || items[i].ty === "el" || items[i].ty === "rc" || items[i].ty === "sr") { + this.renderPath(items[i], data2[i]); + } else if (items[i].ty === "fl") { + this.renderFill(items[i], data2[i], groupTransform); + } else if (items[i].ty === "st") { + this.renderStroke(items[i], data2[i], groupTransform); + } else if (items[i].ty === "gf" || items[i].ty === "gs") { + this.renderGradientFill(items[i], data2[i], groupTransform); + } else if (items[i].ty === "gr") { + this.renderShape(groupTransform, items[i].it, data2[i].it); + } else if (items[i].ty === "tm") { + } + } + if (isMain) { + this.drawLayer(); + } + }; + CVShapeElement.prototype.renderStyledShape = function(styledShape, shape) { + if (this._isFirstFrame || shape._mdf || styledShape.transforms._mdf) { + var shapeNodes = styledShape.trNodes; + var paths = shape.paths; + var i; + var len; + var j2; + var jLen = paths._length; + shapeNodes.length = 0; + var groupTransformMat = styledShape.transforms.finalTransform; + for (j2 = 0;j2 < jLen; j2 += 1) { + var pathNodes = paths.shapes[j2]; + if (pathNodes && pathNodes.v) { + len = pathNodes._length; + for (i = 1;i < len; i += 1) { + if (i === 1) { + shapeNodes.push({ + t: "m", + p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0) + }); + } + shapeNodes.push({ + t: "c", + pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[i], pathNodes.v[i]) + }); + } + if (len === 1) { + shapeNodes.push({ + t: "m", + p: groupTransformMat.applyToPointArray(pathNodes.v[0][0], pathNodes.v[0][1], 0) + }); + } + if (pathNodes.c && len) { + shapeNodes.push({ + t: "c", + pts: groupTransformMat.applyToTriplePoints(pathNodes.o[i - 1], pathNodes.i[0], pathNodes.v[0]) + }); + shapeNodes.push({ + t: "z" + }); + } + } + } + styledShape.trNodes = shapeNodes; + } + }; + CVShapeElement.prototype.renderPath = function(pathData, itemData) { + if (pathData.hd !== true && pathData._shouldRender) { + var i; + var len = itemData.styledShapes.length; + for (i = 0;i < len; i += 1) { + this.renderStyledShape(itemData.styledShapes[i], itemData.sh); + } + } + }; + CVShapeElement.prototype.renderFill = function(styleData, itemData, groupTransform) { + var styleElem = itemData.style; + if (itemData.c._mdf || this._isFirstFrame) { + styleElem.co = "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"; + } + if (itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame) { + styleElem.coOp = itemData.o.v * groupTransform.opacity; + } + }; + CVShapeElement.prototype.renderGradientFill = function(styleData, itemData, groupTransform) { + var styleElem = itemData.style; + var grd; + if (!styleElem.grd || itemData.g._mdf || itemData.s._mdf || itemData.e._mdf || styleData.t !== 1 && (itemData.h._mdf || itemData.a._mdf)) { + var ctx = this.globalData.canvasContext; + var pt1 = itemData.s.v; + var pt2 = itemData.e.v; + if (styleData.t === 1) { + grd = ctx.createLinearGradient(pt1[0], pt1[1], pt2[0], pt2[1]); + } else { + var rad = Math.sqrt(Math.pow(pt1[0] - pt2[0], 2) + Math.pow(pt1[1] - pt2[1], 2)); + var ang = Math.atan2(pt2[1] - pt1[1], pt2[0] - pt1[0]); + var percent = itemData.h.v; + if (percent >= 1) { + percent = 0.99; + } else if (percent <= -1) { + percent = -0.99; + } + var dist = rad * percent; + var x2 = Math.cos(ang + itemData.a.v) * dist + pt1[0]; + var y = Math.sin(ang + itemData.a.v) * dist + pt1[1]; + grd = ctx.createRadialGradient(x2, y, 0, pt1[0], pt1[1], rad); + } + var i; + var len = styleData.g.p; + var cValues = itemData.g.c; + var opacity = 1; + for (i = 0;i < len; i += 1) { + if (itemData.g._hasOpacity && itemData.g._collapsable) { + opacity = itemData.g.o[i * 2 + 1]; + } + grd.addColorStop(cValues[i * 4] / 100, "rgba(" + cValues[i * 4 + 1] + "," + cValues[i * 4 + 2] + "," + cValues[i * 4 + 3] + "," + opacity + ")"); + } + styleElem.grd = grd; + } + styleElem.coOp = itemData.o.v * groupTransform.opacity; + }; + CVShapeElement.prototype.renderStroke = function(styleData, itemData, groupTransform) { + var styleElem = itemData.style; + var d = itemData.d; + if (d && (d._mdf || this._isFirstFrame)) { + styleElem.da = d.dashArray; + styleElem.do = d.dashoffset[0]; + } + if (itemData.c._mdf || this._isFirstFrame) { + styleElem.co = "rgb(" + bmFloor(itemData.c.v[0]) + "," + bmFloor(itemData.c.v[1]) + "," + bmFloor(itemData.c.v[2]) + ")"; + } + if (itemData.o._mdf || groupTransform._opMdf || this._isFirstFrame) { + styleElem.coOp = itemData.o.v * groupTransform.opacity; + } + if (itemData.w._mdf || this._isFirstFrame) { + styleElem.wi = itemData.w.v; + } + }; + CVShapeElement.prototype.destroy = function() { + this.shapesData = null; + this.globalData = null; + this.canvasContext = null; + this.stylesList.length = 0; + this.itemsData.length = 0; + }; + extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement, ITextElement], CVTextElement); + CVTextElement.prototype.tHelper = createTag("canvas").getContext("2d"); + CVTextElement.prototype.buildNewText = function() { + var documentData = this.textProperty.currentData; + this.renderedLetters = createSizedArray(documentData.l ? documentData.l.length : 0); + var hasFill = false; + if (documentData.fc) { + hasFill = true; + this.values.fill = this.buildColor(documentData.fc); + } else { + this.values.fill = "rgba(0,0,0,0)"; + } + this.fill = hasFill; + var hasStroke = false; + if (documentData.sc) { + hasStroke = true; + this.values.stroke = this.buildColor(documentData.sc); + this.values.sWidth = documentData.sw; + } + var fontData = this.globalData.fontManager.getFontByName(documentData.f); + var i; + var len; + var letters = documentData.l; + var matrixHelper = this.mHelper; + this.stroke = hasStroke; + this.values.fValue = documentData.finalSize + "px " + this.globalData.fontManager.getFontByName(documentData.f).fFamily; + len = documentData.finalText.length; + var charData; + var shapeData; + var k2; + var kLen; + var shapes; + var j2; + var jLen; + var pathNodes; + var commands; + var pathArr; + var singleShape = this.data.singleShape; + var trackingOffset = documentData.tr * 0.001 * documentData.finalSize; + var xPos = 0; + var yPos = 0; + var firstLine = true; + var cnt = 0; + for (i = 0;i < len; i += 1) { + charData = this.globalData.fontManager.getCharData(documentData.finalText[i], fontData.fStyle, this.globalData.fontManager.getFontByName(documentData.f).fFamily); + shapeData = charData && charData.data || {}; + matrixHelper.reset(); + if (singleShape && letters[i].n) { + xPos = -trackingOffset; + yPos += documentData.yOffset; + yPos += firstLine ? 1 : 0; + firstLine = false; + } + shapes = shapeData.shapes ? shapeData.shapes[0].it : []; + jLen = shapes.length; + matrixHelper.scale(documentData.finalSize / 100, documentData.finalSize / 100); + if (singleShape) { + this.applyTextPropertiesToMatrix(documentData, matrixHelper, letters[i].line, xPos, yPos); + } + commands = createSizedArray(jLen - 1); + var commandsCounter = 0; + for (j2 = 0;j2 < jLen; j2 += 1) { + if (shapes[j2].ty === "sh") { + kLen = shapes[j2].ks.k.i.length; + pathNodes = shapes[j2].ks.k; + pathArr = []; + for (k2 = 1;k2 < kLen; k2 += 1) { + if (k2 === 1) { + pathArr.push(matrixHelper.applyToX(pathNodes.v[0][0], pathNodes.v[0][1], 0), matrixHelper.applyToY(pathNodes.v[0][0], pathNodes.v[0][1], 0)); + } + pathArr.push(matrixHelper.applyToX(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToY(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToX(pathNodes.i[k2][0], pathNodes.i[k2][1], 0), matrixHelper.applyToY(pathNodes.i[k2][0], pathNodes.i[k2][1], 0), matrixHelper.applyToX(pathNodes.v[k2][0], pathNodes.v[k2][1], 0), matrixHelper.applyToY(pathNodes.v[k2][0], pathNodes.v[k2][1], 0)); + } + pathArr.push(matrixHelper.applyToX(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToY(pathNodes.o[k2 - 1][0], pathNodes.o[k2 - 1][1], 0), matrixHelper.applyToX(pathNodes.i[0][0], pathNodes.i[0][1], 0), matrixHelper.applyToY(pathNodes.i[0][0], pathNodes.i[0][1], 0), matrixHelper.applyToX(pathNodes.v[0][0], pathNodes.v[0][1], 0), matrixHelper.applyToY(pathNodes.v[0][0], pathNodes.v[0][1], 0)); + commands[commandsCounter] = pathArr; + commandsCounter += 1; + } + } + if (singleShape) { + xPos += letters[i].l; + xPos += trackingOffset; + } + if (this.textSpans[cnt]) { + this.textSpans[cnt].elem = commands; + } else { + this.textSpans[cnt] = { elem: commands }; + } + cnt += 1; + } + }; + CVTextElement.prototype.renderInnerContent = function() { + var ctx = this.canvasContext; + ctx.font = this.values.fValue; + ctx.lineCap = "butt"; + ctx.lineJoin = "miter"; + ctx.miterLimit = 4; + if (!this.data.singleShape) { + this.textAnimator.getMeasures(this.textProperty.currentData, this.lettersChangedFlag); + } + var i; + var len; + var j2; + var jLen; + var k2; + var kLen; + var renderedLetters = this.textAnimator.renderedLetters; + var letters = this.textProperty.currentData.l; + len = letters.length; + var renderedLetter; + var lastFill = null; + var lastStroke = null; + var lastStrokeW = null; + var commands; + var pathArr; + for (i = 0;i < len; i += 1) { + if (!letters[i].n) { + renderedLetter = renderedLetters[i]; + if (renderedLetter) { + this.globalData.renderer.save(); + this.globalData.renderer.ctxTransform(renderedLetter.p); + this.globalData.renderer.ctxOpacity(renderedLetter.o); + } + if (this.fill) { + if (renderedLetter && renderedLetter.fc) { + if (lastFill !== renderedLetter.fc) { + lastFill = renderedLetter.fc; + ctx.fillStyle = renderedLetter.fc; + } + } else if (lastFill !== this.values.fill) { + lastFill = this.values.fill; + ctx.fillStyle = this.values.fill; + } + commands = this.textSpans[i].elem; + jLen = commands.length; + this.globalData.canvasContext.beginPath(); + for (j2 = 0;j2 < jLen; j2 += 1) { + pathArr = commands[j2]; + kLen = pathArr.length; + this.globalData.canvasContext.moveTo(pathArr[0], pathArr[1]); + for (k2 = 2;k2 < kLen; k2 += 6) { + this.globalData.canvasContext.bezierCurveTo(pathArr[k2], pathArr[k2 + 1], pathArr[k2 + 2], pathArr[k2 + 3], pathArr[k2 + 4], pathArr[k2 + 5]); + } + } + this.globalData.canvasContext.closePath(); + this.globalData.canvasContext.fill(); + } + if (this.stroke) { + if (renderedLetter && renderedLetter.sw) { + if (lastStrokeW !== renderedLetter.sw) { + lastStrokeW = renderedLetter.sw; + ctx.lineWidth = renderedLetter.sw; + } + } else if (lastStrokeW !== this.values.sWidth) { + lastStrokeW = this.values.sWidth; + ctx.lineWidth = this.values.sWidth; + } + if (renderedLetter && renderedLetter.sc) { + if (lastStroke !== renderedLetter.sc) { + lastStroke = renderedLetter.sc; + ctx.strokeStyle = renderedLetter.sc; + } + } else if (lastStroke !== this.values.stroke) { + lastStroke = this.values.stroke; + ctx.strokeStyle = this.values.stroke; + } + commands = this.textSpans[i].elem; + jLen = commands.length; + this.globalData.canvasContext.beginPath(); + for (j2 = 0;j2 < jLen; j2 += 1) { + pathArr = commands[j2]; + kLen = pathArr.length; + this.globalData.canvasContext.moveTo(pathArr[0], pathArr[1]); + for (k2 = 2;k2 < kLen; k2 += 6) { + this.globalData.canvasContext.bezierCurveTo(pathArr[k2], pathArr[k2 + 1], pathArr[k2 + 2], pathArr[k2 + 3], pathArr[k2 + 4], pathArr[k2 + 5]); + } + } + this.globalData.canvasContext.closePath(); + this.globalData.canvasContext.stroke(); + } + if (renderedLetter) { + this.globalData.renderer.restore(); + } + } + } + }; + extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement], CVImageElement); + CVImageElement.prototype.initElement = SVGShapeElement.prototype.initElement; + CVImageElement.prototype.prepareFrame = IImageElement.prototype.prepareFrame; + CVImageElement.prototype.createContent = function() { + if (this.img.width && (this.assetData.w !== this.img.width || this.assetData.h !== this.img.height)) { + var canvas = createTag("canvas"); + canvas.width = this.assetData.w; + canvas.height = this.assetData.h; + var ctx = canvas.getContext("2d"); + var imgW = this.img.width; + var imgH = this.img.height; + var imgRel = imgW / imgH; + var canvasRel = this.assetData.w / this.assetData.h; + var widthCrop; + var heightCrop; + var par = this.assetData.pr || this.globalData.renderConfig.imagePreserveAspectRatio; + if (imgRel > canvasRel && par === "xMidYMid slice" || imgRel < canvasRel && par !== "xMidYMid slice") { + heightCrop = imgH; + widthCrop = heightCrop * canvasRel; + } else { + widthCrop = imgW; + heightCrop = widthCrop / canvasRel; + } + ctx.drawImage(this.img, (imgW - widthCrop) / 2, (imgH - heightCrop) / 2, widthCrop, heightCrop, 0, 0, this.assetData.w, this.assetData.h); + this.img = canvas; + } + }; + CVImageElement.prototype.renderInnerContent = function() { + this.canvasContext.drawImage(this.img, 0, 0); + }; + CVImageElement.prototype.destroy = function() { + this.img = null; + }; + extendPrototype([BaseElement, TransformElement, CVBaseElement, HierarchyElement, FrameElement, RenderableElement], CVSolidElement); + CVSolidElement.prototype.initElement = SVGShapeElement.prototype.initElement; + CVSolidElement.prototype.prepareFrame = IImageElement.prototype.prepareFrame; + CVSolidElement.prototype.renderInnerContent = function() { + var ctx = this.canvasContext; + ctx.fillStyle = this.data.sc; + ctx.fillRect(0, 0, this.data.sw, this.data.sh); + }; + extendPrototype([BaseRenderer], CanvasRendererBase); + CanvasRendererBase.prototype.createShape = function(data2) { + return new CVShapeElement(data2, this.globalData, this); + }; + CanvasRendererBase.prototype.createText = function(data2) { + return new CVTextElement(data2, this.globalData, this); + }; + CanvasRendererBase.prototype.createImage = function(data2) { + return new CVImageElement(data2, this.globalData, this); + }; + CanvasRendererBase.prototype.createSolid = function(data2) { + return new CVSolidElement(data2, this.globalData, this); + }; + CanvasRendererBase.prototype.createNull = SVGRenderer.prototype.createNull; + CanvasRendererBase.prototype.ctxTransform = function(props) { + if (props[0] === 1 && props[1] === 0 && props[4] === 0 && props[5] === 1 && props[12] === 0 && props[13] === 0) { + return; + } + if (!this.renderConfig.clearCanvas) { + this.canvasContext.transform(props[0], props[1], props[4], props[5], props[12], props[13]); + return; + } + this.transformMat.cloneFromProps(props); + var cProps = this.contextData.cTr.props; + this.transformMat.transform(cProps[0], cProps[1], cProps[2], cProps[3], cProps[4], cProps[5], cProps[6], cProps[7], cProps[8], cProps[9], cProps[10], cProps[11], cProps[12], cProps[13], cProps[14], cProps[15]); + this.contextData.cTr.cloneFromProps(this.transformMat.props); + var trProps = this.contextData.cTr.props; + this.canvasContext.setTransform(trProps[0], trProps[1], trProps[4], trProps[5], trProps[12], trProps[13]); + }; + CanvasRendererBase.prototype.ctxOpacity = function(op) { + if (!this.renderConfig.clearCanvas) { + this.canvasContext.globalAlpha *= op < 0 ? 0 : op; + this.globalData.currentGlobalAlpha = this.contextData.cO; + return; + } + this.contextData.cO *= op < 0 ? 0 : op; + if (this.globalData.currentGlobalAlpha !== this.contextData.cO) { + this.canvasContext.globalAlpha = this.contextData.cO; + this.globalData.currentGlobalAlpha = this.contextData.cO; + } + }; + CanvasRendererBase.prototype.reset = function() { + if (!this.renderConfig.clearCanvas) { + this.canvasContext.restore(); + return; + } + this.contextData.reset(); + }; + CanvasRendererBase.prototype.save = function(actionFlag) { + if (!this.renderConfig.clearCanvas) { + this.canvasContext.save(); + return; + } + if (actionFlag) { + this.canvasContext.save(); + } + var props = this.contextData.cTr.props; + if (this.contextData._length <= this.contextData.cArrPos) { + this.contextData.duplicate(); + } + var i; + var arr = this.contextData.saved[this.contextData.cArrPos]; + for (i = 0;i < 16; i += 1) { + arr[i] = props[i]; + } + this.contextData.savedOp[this.contextData.cArrPos] = this.contextData.cO; + this.contextData.cArrPos += 1; + }; + CanvasRendererBase.prototype.restore = function(actionFlag) { + if (!this.renderConfig.clearCanvas) { + this.canvasContext.restore(); + return; + } + if (actionFlag) { + this.canvasContext.restore(); + this.globalData.blendMode = "source-over"; + } + this.contextData.cArrPos -= 1; + var popped = this.contextData.saved[this.contextData.cArrPos]; + var i; + var arr = this.contextData.cTr.props; + for (i = 0;i < 16; i += 1) { + arr[i] = popped[i]; + } + this.canvasContext.setTransform(popped[0], popped[1], popped[4], popped[5], popped[12], popped[13]); + popped = this.contextData.savedOp[this.contextData.cArrPos]; + this.contextData.cO = popped; + if (this.globalData.currentGlobalAlpha !== popped) { + this.canvasContext.globalAlpha = popped; + this.globalData.currentGlobalAlpha = popped; + } + }; + CanvasRendererBase.prototype.configAnimation = function(animData) { + if (this.animationItem.wrapper) { + this.animationItem.container = createTag("canvas"); + var containerStyle = this.animationItem.container.style; + containerStyle.width = "100%"; + containerStyle.height = "100%"; + var origin = "0px 0px 0px"; + containerStyle.transformOrigin = origin; + containerStyle.mozTransformOrigin = origin; + containerStyle.webkitTransformOrigin = origin; + containerStyle["-webkit-transform"] = origin; + containerStyle.contentVisibility = this.renderConfig.contentVisibility; + this.animationItem.wrapper.appendChild(this.animationItem.container); + this.canvasContext = this.animationItem.container.getContext("2d"); + if (this.renderConfig.className) { + this.animationItem.container.setAttribute("class", this.renderConfig.className); + } + if (this.renderConfig.id) { + this.animationItem.container.setAttribute("id", this.renderConfig.id); + } + } else { + this.canvasContext = this.renderConfig.context; + } + this.data = animData; + this.layers = animData.layers; + this.transformCanvas = { + w: animData.w, + h: animData.h, + sx: 0, + sy: 0, + tx: 0, + ty: 0 + }; + this.setupGlobalData(animData, document.body); + this.globalData.canvasContext = this.canvasContext; + this.globalData.renderer = this; + this.globalData.isDashed = false; + this.globalData.progressiveLoad = this.renderConfig.progressiveLoad; + this.globalData.transformCanvas = this.transformCanvas; + this.elements = createSizedArray(animData.layers.length); + this.updateContainerSize(); + }; + CanvasRendererBase.prototype.updateContainerSize = function() { + this.reset(); + var elementWidth; + var elementHeight; + if (this.animationItem.wrapper && this.animationItem.container) { + elementWidth = this.animationItem.wrapper.offsetWidth; + elementHeight = this.animationItem.wrapper.offsetHeight; + this.animationItem.container.setAttribute("width", elementWidth * this.renderConfig.dpr); + this.animationItem.container.setAttribute("height", elementHeight * this.renderConfig.dpr); + } else { + elementWidth = this.canvasContext.canvas.width * this.renderConfig.dpr; + elementHeight = this.canvasContext.canvas.height * this.renderConfig.dpr; + } + var elementRel; + var animationRel; + if (this.renderConfig.preserveAspectRatio.indexOf("meet") !== -1 || this.renderConfig.preserveAspectRatio.indexOf("slice") !== -1) { + var par = this.renderConfig.preserveAspectRatio.split(" "); + var fillType = par[1] || "meet"; + var pos = par[0] || "xMidYMid"; + var xPos = pos.substr(0, 4); + var yPos = pos.substr(4); + elementRel = elementWidth / elementHeight; + animationRel = this.transformCanvas.w / this.transformCanvas.h; + if (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice") { + this.transformCanvas.sx = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr); + this.transformCanvas.sy = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr); + } else { + this.transformCanvas.sx = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr); + this.transformCanvas.sy = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr); + } + if (xPos === "xMid" && (animationRel < elementRel && fillType === "meet" || animationRel > elementRel && fillType === "slice")) { + this.transformCanvas.tx = (elementWidth - this.transformCanvas.w * (elementHeight / this.transformCanvas.h)) / 2 * this.renderConfig.dpr; + } else if (xPos === "xMax" && (animationRel < elementRel && fillType === "meet" || animationRel > elementRel && fillType === "slice")) { + this.transformCanvas.tx = (elementWidth - this.transformCanvas.w * (elementHeight / this.transformCanvas.h)) * this.renderConfig.dpr; + } else { + this.transformCanvas.tx = 0; + } + if (yPos === "YMid" && (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice")) { + this.transformCanvas.ty = (elementHeight - this.transformCanvas.h * (elementWidth / this.transformCanvas.w)) / 2 * this.renderConfig.dpr; + } else if (yPos === "YMax" && (animationRel > elementRel && fillType === "meet" || animationRel < elementRel && fillType === "slice")) { + this.transformCanvas.ty = (elementHeight - this.transformCanvas.h * (elementWidth / this.transformCanvas.w)) * this.renderConfig.dpr; + } else { + this.transformCanvas.ty = 0; + } + } else if (this.renderConfig.preserveAspectRatio === "none") { + this.transformCanvas.sx = elementWidth / (this.transformCanvas.w / this.renderConfig.dpr); + this.transformCanvas.sy = elementHeight / (this.transformCanvas.h / this.renderConfig.dpr); + this.transformCanvas.tx = 0; + this.transformCanvas.ty = 0; + } else { + this.transformCanvas.sx = this.renderConfig.dpr; + this.transformCanvas.sy = this.renderConfig.dpr; + this.transformCanvas.tx = 0; + this.transformCanvas.ty = 0; + } + this.transformCanvas.props = [this.transformCanvas.sx, 0, 0, 0, 0, this.transformCanvas.sy, 0, 0, 0, 0, 1, 0, this.transformCanvas.tx, this.transformCanvas.ty, 0, 1]; + this.ctxTransform(this.transformCanvas.props); + this.canvasContext.beginPath(); + this.canvasContext.rect(0, 0, this.transformCanvas.w, this.transformCanvas.h); + this.canvasContext.closePath(); + this.canvasContext.clip(); + this.renderFrame(this.renderedFrame, true); + }; + CanvasRendererBase.prototype.destroy = function() { + if (this.renderConfig.clearCanvas && this.animationItem.wrapper) { + this.animationItem.wrapper.innerText = ""; + } + var i; + var len = this.layers ? this.layers.length : 0; + for (i = len - 1;i >= 0; i -= 1) { + if (this.elements[i]) { + this.elements[i].destroy(); + } + } + this.elements.length = 0; + this.globalData.canvasContext = null; + this.animationItem.container = null; + this.destroyed = true; + }; + CanvasRendererBase.prototype.renderFrame = function(num, forceRender) { + if (this.renderedFrame === num && this.renderConfig.clearCanvas === true && !forceRender || this.destroyed || num === -1) { + return; + } + this.renderedFrame = num; + this.globalData.frameNum = num - this.animationItem._isFirstFrame; + this.globalData.frameId += 1; + this.globalData._mdf = !this.renderConfig.clearCanvas || forceRender; + this.globalData.projectInterface.currentFrame = num; + var i; + var len = this.layers.length; + if (!this.completeLayers) { + this.checkLayers(num); + } + for (i = 0;i < len; i += 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].prepareFrame(num - this.layers[i].st); + } + } + if (this.globalData._mdf) { + if (this.renderConfig.clearCanvas === true) { + this.canvasContext.clearRect(0, 0, this.transformCanvas.w, this.transformCanvas.h); + } else { + this.save(); + } + for (i = len - 1;i >= 0; i -= 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].renderFrame(); + } + } + if (this.renderConfig.clearCanvas !== true) { + this.restore(); + } + } + }; + CanvasRendererBase.prototype.buildItem = function(pos) { + var elements = this.elements; + if (elements[pos] || this.layers[pos].ty === 99) { + return; + } + var element = this.createItem(this.layers[pos], this, this.globalData); + elements[pos] = element; + element.initExpressions(); + }; + CanvasRendererBase.prototype.checkPendingElements = function() { + while (this.pendingElements.length) { + var element = this.pendingElements.pop(); + element.checkParenting(); + } + }; + CanvasRendererBase.prototype.hide = function() { + this.animationItem.container.style.display = "none"; + }; + CanvasRendererBase.prototype.show = function() { + this.animationItem.container.style.display = "block"; + }; + extendPrototype([CanvasRendererBase, ICompElement, CVBaseElement], CVCompElement); + CVCompElement.prototype.renderInnerContent = function() { + var ctx = this.canvasContext; + ctx.beginPath(); + ctx.moveTo(0, 0); + ctx.lineTo(this.data.w, 0); + ctx.lineTo(this.data.w, this.data.h); + ctx.lineTo(0, this.data.h); + ctx.lineTo(0, 0); + ctx.clip(); + var i; + var len = this.layers.length; + for (i = len - 1;i >= 0; i -= 1) { + if (this.completeLayers || this.elements[i]) { + this.elements[i].renderFrame(); + } + } + }; + CVCompElement.prototype.destroy = function() { + var i; + var len = this.layers.length; + for (i = len - 1;i >= 0; i -= 1) { + if (this.elements[i]) { + this.elements[i].destroy(); + } + } + this.layers = null; + this.elements = null; + }; + CVCompElement.prototype.createComp = function(data2) { + return new CVCompElement(data2, this.globalData, this); + }; + extendPrototype([CanvasRendererBase], CanvasRenderer); + CanvasRenderer.prototype.createComp = function(data2) { + return new CVCompElement(data2, this.globalData, this); + }; + registerRenderer("canvas", CanvasRenderer); + ShapeModifiers.registerModifier("tm", TrimModifier); + ShapeModifiers.registerModifier("pb", PuckerAndBloatModifier); + ShapeModifiers.registerModifier("rp", RepeaterModifier); + ShapeModifiers.registerModifier("rd", RoundCornersModifier); + const Expressions = function() { + var ob2 = {}; + ob2.initExpressions = initExpressions; + function initExpressions(animation) { + var stackCount = 0; + var registers = []; + function pushExpression() { + stackCount += 1; + } + function popExpression() { + stackCount -= 1; + if (stackCount === 0) { + releaseInstances(); + } + } + function registerExpressionProperty(expression) { + if (registers.indexOf(expression) === -1) { + registers.push(expression); + } + } + function releaseInstances() { + var i; + var len = registers.length; + for (i = 0;i < len; i += 1) { + registers[i].release(); + } + registers.length = 0; + } + animation.renderer.compInterface = CompExpressionInterface(animation.renderer); + animation.renderer.globalData.projectInterface.registerComposition(animation.renderer); + animation.renderer.globalData.pushExpression = pushExpression; + animation.renderer.globalData.popExpression = popExpression; + animation.renderer.globalData.registerExpressionProperty = registerExpressionProperty; + } + return ob2; + }(); + propTypes = { + SHAPE: "shape" + }; + const ExpressionManager = function() { + var ob = {}; + var Math = BMMath; + var window = null; + var document = null; + var XMLHttpRequest = null; + var fetch = null; + var frames = null; + initialize$2(BMMath); + function $bm_isInstanceOfArray(arr) { + return arr.constructor === Array || arr.constructor === Float32Array; + } + function isNumerable(tOfV, v) { + return tOfV === "number" || tOfV === "boolean" || tOfV === "string" || v instanceof Number; + } + function $bm_neg(a) { + var tOfA = typeof a; + if (tOfA === "number" || tOfA === "boolean" || a instanceof Number) { + return -a; + } + if ($bm_isInstanceOfArray(a)) { + var i; + var lenA = a.length; + var retArr = []; + for (i = 0;i < lenA; i += 1) { + retArr[i] = -a[i]; + } + return retArr; + } + if (a.propType) { + return a.v; + } + return -a; + } + var easeInBez = BezierFactory.getBezierEasing(0.333, 0, 0.833, 0.833, "easeIn").get; + var easeOutBez = BezierFactory.getBezierEasing(0.167, 0.167, 0.667, 1, "easeOut").get; + var easeInOutBez = BezierFactory.getBezierEasing(0.33, 0, 0.667, 1, "easeInOut").get; + function sum(a, b) { + var tOfA = typeof a; + var tOfB = typeof b; + if (tOfA === "string" || tOfB === "string") { + return a + b; + } + if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { + return a + b; + } + if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { + a = a.slice(0); + a[0] += b; + return a; + } + if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { + b = b.slice(0); + b[0] = a + b[0]; + return b; + } + if ($bm_isInstanceOfArray(a) && $bm_isInstanceOfArray(b)) { + var i = 0; + var lenA = a.length; + var lenB = b.length; + var retArr = []; + while (i < lenA || i < lenB) { + if ((typeof a[i] === "number" || a[i] instanceof Number) && (typeof b[i] === "number" || b[i] instanceof Number)) { + retArr[i] = a[i] + b[i]; + } else { + retArr[i] = b[i] === undefined ? a[i] : a[i] || b[i]; + } + i += 1; + } + return retArr; + } + return 0; + } + var add = sum; + function sub(a, b) { + var tOfA = typeof a; + var tOfB = typeof b; + if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { + if (tOfA === "string") { + a = parseInt(a, 10); + } + if (tOfB === "string") { + b = parseInt(b, 10); + } + return a - b; + } + if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { + a = a.slice(0); + a[0] -= b; + return a; + } + if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { + b = b.slice(0); + b[0] = a - b[0]; + return b; + } + if ($bm_isInstanceOfArray(a) && $bm_isInstanceOfArray(b)) { + var i = 0; + var lenA = a.length; + var lenB = b.length; + var retArr = []; + while (i < lenA || i < lenB) { + if ((typeof a[i] === "number" || a[i] instanceof Number) && (typeof b[i] === "number" || b[i] instanceof Number)) { + retArr[i] = a[i] - b[i]; + } else { + retArr[i] = b[i] === undefined ? a[i] : a[i] || b[i]; + } + i += 1; + } + return retArr; + } + return 0; + } + function mul(a, b) { + var tOfA = typeof a; + var tOfB = typeof b; + var arr; + if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { + return a * b; + } + var i; + var len; + if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { + len = a.length; + arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = a[i] * b; + } + return arr; + } + if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { + len = b.length; + arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = a * b[i]; + } + return arr; + } + return 0; + } + function div(a, b) { + var tOfA = typeof a; + var tOfB = typeof b; + var arr; + if (isNumerable(tOfA, a) && isNumerable(tOfB, b)) { + return a / b; + } + var i; + var len; + if ($bm_isInstanceOfArray(a) && isNumerable(tOfB, b)) { + len = a.length; + arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = a[i] / b; + } + return arr; + } + if (isNumerable(tOfA, a) && $bm_isInstanceOfArray(b)) { + len = b.length; + arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = a / b[i]; + } + return arr; + } + return 0; + } + function mod(a, b) { + if (typeof a === "string") { + a = parseInt(a, 10); + } + if (typeof b === "string") { + b = parseInt(b, 10); + } + return a % b; + } + var $bm_sum = sum; + var $bm_sub = sub; + var $bm_mul = mul; + var $bm_div = div; + var $bm_mod = mod; + function clamp(num, min, max) { + if (min > max) { + var mm = max; + max = min; + min = mm; + } + return Math.min(Math.max(num, min), max); + } + function radiansToDegrees(val2) { + return val2 / degToRads; + } + var radians_to_degrees = radiansToDegrees; + function degreesToRadians(val2) { + return val2 * degToRads; + } + var degrees_to_radians = radiansToDegrees; + var helperLengthArray = [0, 0, 0, 0, 0, 0]; + function length(arr1, arr2) { + if (typeof arr1 === "number" || arr1 instanceof Number) { + arr2 = arr2 || 0; + return Math.abs(arr1 - arr2); + } + if (!arr2) { + arr2 = helperLengthArray; + } + var i; + var len = Math.min(arr1.length, arr2.length); + var addedLength = 0; + for (i = 0;i < len; i += 1) { + addedLength += Math.pow(arr2[i] - arr1[i], 2); + } + return Math.sqrt(addedLength); + } + function normalize(vec) { + return div(vec, length(vec)); + } + function rgbToHsl(val2) { + var r = val2[0]; + var g3 = val2[1]; + var b = val2[2]; + var max = Math.max(r, g3, b); + var min = Math.min(r, g3, b); + var h; + var s; + var l2 = (max + min) / 2; + if (max === min) { + h = 0; + s = 0; + } else { + var d = max - min; + s = l2 > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g3 - b) / d + (g3 < b ? 6 : 0); + break; + case g3: + h = (b - r) / d + 2; + break; + case b: + h = (r - g3) / d + 4; + break; + default: + break; + } + h /= 6; + } + return [h, s, l2, val2[3]]; + } + function hue2rgb(p, q2, t2) { + if (t2 < 0) + t2 += 1; + if (t2 > 1) + t2 -= 1; + if (t2 < 1 / 6) + return p + (q2 - p) * 6 * t2; + if (t2 < 1 / 2) + return q2; + if (t2 < 2 / 3) + return p + (q2 - p) * (2 / 3 - t2) * 6; + return p; + } + function hslToRgb(val2) { + var h = val2[0]; + var s = val2[1]; + var l2 = val2[2]; + var r; + var g3; + var b; + if (s === 0) { + r = l2; + b = l2; + g3 = l2; + } else { + var q2 = l2 < 0.5 ? l2 * (1 + s) : l2 + s - l2 * s; + var p = 2 * l2 - q2; + r = hue2rgb(p, q2, h + 1 / 3); + g3 = hue2rgb(p, q2, h); + b = hue2rgb(p, q2, h - 1 / 3); + } + return [r, g3, b, val2[3]]; + } + function linear(t2, tMin, tMax, value1, value2) { + if (value1 === undefined || value2 === undefined) { + value1 = tMin; + value2 = tMax; + tMin = 0; + tMax = 1; + } + if (tMax < tMin) { + var _tMin = tMax; + tMax = tMin; + tMin = _tMin; + } + if (t2 <= tMin) { + return value1; + } + if (t2 >= tMax) { + return value2; + } + var perc = tMax === tMin ? 0 : (t2 - tMin) / (tMax - tMin); + if (!value1.length) { + return value1 + (value2 - value1) * perc; + } + var i; + var len = value1.length; + var arr = createTypedArray("float32", len); + for (i = 0;i < len; i += 1) { + arr[i] = value1[i] + (value2[i] - value1[i]) * perc; + } + return arr; + } + function random(min, max) { + if (max === undefined) { + if (min === undefined) { + min = 0; + max = 1; + } else { + max = min; + min = undefined; + } + } + if (max.length) { + var i; + var len = max.length; + if (!min) { + min = createTypedArray("float32", len); + } + var arr = createTypedArray("float32", len); + var rnd = BMMath.random(); + for (i = 0;i < len; i += 1) { + arr[i] = min[i] + rnd * (max[i] - min[i]); + } + return arr; + } + if (min === undefined) { + min = 0; + } + var rndm = BMMath.random(); + return min + rndm * (max - min); + } + function createPath(points, inTangents, outTangents, closed) { + var i; + var len = points.length; + var path = shapePool.newElement(); + path.setPathData(!!closed, len); + var arrPlaceholder = [0, 0]; + var inVertexPoint; + var outVertexPoint; + for (i = 0;i < len; i += 1) { + inVertexPoint = inTangents && inTangents[i] ? inTangents[i] : arrPlaceholder; + outVertexPoint = outTangents && outTangents[i] ? outTangents[i] : arrPlaceholder; + path.setTripleAt(points[i][0], points[i][1], outVertexPoint[0] + points[i][0], outVertexPoint[1] + points[i][1], inVertexPoint[0] + points[i][0], inVertexPoint[1] + points[i][1], i, true); + } + return path; + } + function initiateExpression(elem, data, property) { + var val = data.x; + var needsVelocity = /velocity(?![\w\d])/.test(val); + var _needsRandom = val.indexOf("random") !== -1; + var elemType = elem.data.ty; + var transform; + var $bm_transform; + var content; + var effect; + var thisProperty = property; + thisProperty.valueAtTime = thisProperty.getValueAtTime; + Object.defineProperty(thisProperty, "value", { + get: function() { + return thisProperty.v; + } + }); + elem.comp.frameDuration = 1 / elem.comp.globalData.frameRate; + elem.comp.displayStartTime = 0; + var inPoint = elem.data.ip / elem.comp.globalData.frameRate; + var outPoint = elem.data.op / elem.comp.globalData.frameRate; + var width = elem.data.sw ? elem.data.sw : 0; + var height = elem.data.sh ? elem.data.sh : 0; + var name = elem.data.nm; + var loopIn; + var loop_in; + var loopOut; + var loop_out; + var smooth; + var toWorld; + var fromWorld; + var fromComp; + var toComp; + var fromCompToSurface; + var position; + var rotation; + var anchorPoint; + var scale; + var thisLayer; + var thisComp; + var mask; + var valueAtTime; + var velocityAtTime; + var scoped_bm_rt; + var expression_function = eval("[function _expression_function(){" + val + ";scoped_bm_rt=$bm_rt}]")[0]; + var numKeys = property.kf ? data.k.length : 0; + var active = !this.data || this.data.hd !== true; + var wiggle = function wiggle(freq, amp) { + var iWiggle; + var j2; + var lenWiggle = this.pv.length ? this.pv.length : 1; + var addedAmps = createTypedArray("float32", lenWiggle); + freq = 5; + var iterations = Math.floor(time * freq); + iWiggle = 0; + j2 = 0; + while (iWiggle < iterations) { + for (j2 = 0;j2 < lenWiggle; j2 += 1) { + addedAmps[j2] += -amp + amp * 2 * BMMath.random(); + } + iWiggle += 1; + } + var periods = time * freq; + var perc = periods - Math.floor(periods); + var arr = createTypedArray("float32", lenWiggle); + if (lenWiggle > 1) { + for (j2 = 0;j2 < lenWiggle; j2 += 1) { + arr[j2] = this.pv[j2] + addedAmps[j2] + (-amp + amp * 2 * BMMath.random()) * perc; + } + return arr; + } + return this.pv + addedAmps[0] + (-amp + amp * 2 * BMMath.random()) * perc; + }.bind(this); + if (thisProperty.loopIn) { + loopIn = thisProperty.loopIn.bind(thisProperty); + loop_in = loopIn; + } + if (thisProperty.loopOut) { + loopOut = thisProperty.loopOut.bind(thisProperty); + loop_out = loopOut; + } + if (thisProperty.smooth) { + smooth = thisProperty.smooth.bind(thisProperty); + } + function loopInDuration(type, duration) { + return loopIn(type, duration, true); + } + function loopOutDuration(type, duration) { + return loopOut(type, duration, true); + } + if (this.getValueAtTime) { + valueAtTime = this.getValueAtTime.bind(this); + } + if (this.getVelocityAtTime) { + velocityAtTime = this.getVelocityAtTime.bind(this); + } + var comp = elem.comp.globalData.projectInterface.bind(elem.comp.globalData.projectInterface); + function lookAt(elem1, elem2) { + var fVec = [elem2[0] - elem1[0], elem2[1] - elem1[1], elem2[2] - elem1[2]]; + var pitch = Math.atan2(fVec[0], Math.sqrt(fVec[1] * fVec[1] + fVec[2] * fVec[2])) / degToRads; + var yaw = -Math.atan2(fVec[1], fVec[2]) / degToRads; + return [yaw, pitch, 0]; + } + function easeOut(t2, tMin, tMax, val1, val2) { + return applyEase(easeOutBez, t2, tMin, tMax, val1, val2); + } + function easeIn(t2, tMin, tMax, val1, val2) { + return applyEase(easeInBez, t2, tMin, tMax, val1, val2); + } + function ease(t2, tMin, tMax, val1, val2) { + return applyEase(easeInOutBez, t2, tMin, tMax, val1, val2); + } + function applyEase(fn, t2, tMin, tMax, val1, val2) { + if (val1 === undefined) { + val1 = tMin; + val2 = tMax; + } else { + t2 = (t2 - tMin) / (tMax - tMin); + } + if (t2 > 1) { + t2 = 1; + } else if (t2 < 0) { + t2 = 0; + } + var mult = fn(t2); + if ($bm_isInstanceOfArray(val1)) { + var iKey; + var lenKey = val1.length; + var arr = createTypedArray("float32", lenKey); + for (iKey = 0;iKey < lenKey; iKey += 1) { + arr[iKey] = (val2[iKey] - val1[iKey]) * mult + val1[iKey]; + } + return arr; + } + return (val2 - val1) * mult + val1; + } + function nearestKey(time2) { + var iKey; + var lenKey = data.k.length; + var index2; + var keyTime; + if (!data.k.length || typeof data.k[0] === "number") { + index2 = 0; + keyTime = 0; + } else { + index2 = -1; + time2 *= elem.comp.globalData.frameRate; + if (time2 < data.k[0].t) { + index2 = 1; + keyTime = data.k[0].t; + } else { + for (iKey = 0;iKey < lenKey - 1; iKey += 1) { + if (time2 === data.k[iKey].t) { + index2 = iKey + 1; + keyTime = data.k[iKey].t; + break; + } else if (time2 > data.k[iKey].t && time2 < data.k[iKey + 1].t) { + if (time2 - data.k[iKey].t > data.k[iKey + 1].t - time2) { + index2 = iKey + 2; + keyTime = data.k[iKey + 1].t; + } else { + index2 = iKey + 1; + keyTime = data.k[iKey].t; + } + break; + } + } + if (index2 === -1) { + index2 = iKey + 1; + keyTime = data.k[iKey].t; + } + } + } + var obKey = {}; + obKey.index = index2; + obKey.time = keyTime / elem.comp.globalData.frameRate; + return obKey; + } + function key(ind) { + var obKey; + var iKey; + var lenKey; + if (!data.k.length || typeof data.k[0] === "number") { + throw new Error("The property has no keyframe at index " + ind); + } + ind -= 1; + obKey = { + time: data.k[ind].t / elem.comp.globalData.frameRate, + value: [] + }; + var arr = Object.prototype.hasOwnProperty.call(data.k[ind], "s") ? data.k[ind].s : data.k[ind - 1].e; + lenKey = arr.length; + for (iKey = 0;iKey < lenKey; iKey += 1) { + obKey[iKey] = arr[iKey]; + obKey.value[iKey] = arr[iKey]; + } + return obKey; + } + function framesToTime(fr, fps) { + if (!fps) { + fps = elem.comp.globalData.frameRate; + } + return fr / fps; + } + function timeToFrames(t2, fps) { + if (!t2 && t2 !== 0) { + t2 = time; + } + if (!fps) { + fps = elem.comp.globalData.frameRate; + } + return t2 * fps; + } + function seedRandom(seed) { + BMMath.seedrandom(randSeed + seed); + } + function sourceRectAtTime() { + return elem.sourceRectAtTime(); + } + function substring(init, end) { + if (typeof value === "string") { + if (end === undefined) { + return value.substring(init); + } + return value.substring(init, end); + } + return ""; + } + function substr(init, end) { + if (typeof value === "string") { + if (end === undefined) { + return value.substr(init); + } + return value.substr(init, end); + } + return ""; + } + function posterizeTime(framesPerSecond) { + time = framesPerSecond === 0 ? 0 : Math.floor(time * framesPerSecond) / framesPerSecond; + value = valueAtTime(time); + } + var time; + var velocity; + var value; + var text; + var textIndex; + var textTotal; + var selectorValue; + var index = elem.data.ind; + var hasParent = !!(elem.hierarchy && elem.hierarchy.length); + var parent; + var randSeed = Math.floor(Math.random() * 1e6); + var globalData = elem.globalData; + function executeExpression(_value) { + value = _value; + if (this.frameExpressionId === elem.globalData.frameId && this.propType !== "textSelector") { + return value; + } + if (this.propType === "textSelector") { + textIndex = this.textIndex; + textTotal = this.textTotal; + selectorValue = this.selectorValue; + } + if (!thisLayer) { + text = elem.layerInterface.text; + thisLayer = elem.layerInterface; + thisComp = elem.comp.compInterface; + toWorld = thisLayer.toWorld.bind(thisLayer); + fromWorld = thisLayer.fromWorld.bind(thisLayer); + fromComp = thisLayer.fromComp.bind(thisLayer); + toComp = thisLayer.toComp.bind(thisLayer); + mask = thisLayer.mask ? thisLayer.mask.bind(thisLayer) : null; + fromCompToSurface = fromComp; + } + if (!transform) { + transform = elem.layerInterface("ADBE Transform Group"); + $bm_transform = transform; + if (transform) { + anchorPoint = transform.anchorPoint; + } + } + if (elemType === 4 && !content) { + content = thisLayer("ADBE Root Vectors Group"); + } + if (!effect) { + effect = thisLayer(4); + } + hasParent = !!(elem.hierarchy && elem.hierarchy.length); + if (hasParent && !parent) { + parent = elem.hierarchy[0].layerInterface; + } + time = this.comp.renderedFrame / this.comp.globalData.frameRate; + if (_needsRandom) { + seedRandom(randSeed + time); + } + if (needsVelocity) { + velocity = velocityAtTime(time); + } + expression_function(); + this.frameExpressionId = elem.globalData.frameId; + scoped_bm_rt = scoped_bm_rt.propType === propTypes.SHAPE ? scoped_bm_rt.v : scoped_bm_rt; + return scoped_bm_rt; + } + executeExpression.__preventDeadCodeRemoval = [$bm_transform, anchorPoint, time, velocity, inPoint, outPoint, width, height, name, loop_in, loop_out, smooth, toComp, fromCompToSurface, toWorld, fromWorld, mask, position, rotation, scale, thisComp, numKeys, active, wiggle, loopInDuration, loopOutDuration, comp, lookAt, easeOut, easeIn, ease, nearestKey, key, text, textIndex, textTotal, selectorValue, framesToTime, timeToFrames, sourceRectAtTime, substring, substr, posterizeTime, index, globalData]; + return executeExpression; + } + ob.initiateExpression = initiateExpression; + ob.__preventDeadCodeRemoval = [window, document, XMLHttpRequest, fetch, frames, $bm_neg, add, $bm_sum, $bm_sub, $bm_mul, $bm_div, $bm_mod, clamp, radians_to_degrees, degreesToRadians, degrees_to_radians, normalize, rgbToHsl, hslToRgb, linear, random, createPath]; + return ob; + }(); + const expressionHelpers = function() { + function searchExpressions(elem2, data2, prop) { + if (data2.x) { + prop.k = true; + prop.x = true; + prop.initiateExpression = ExpressionManager.initiateExpression; + prop.effectsSequence.push(prop.initiateExpression(elem2, data2, prop).bind(prop)); + } + } + function getValueAtTime(frameNum) { + frameNum *= this.elem.globalData.frameRate; + frameNum -= this.offsetTime; + if (frameNum !== this._cachingAtTime.lastFrame) { + this._cachingAtTime.lastIndex = this._cachingAtTime.lastFrame < frameNum ? this._cachingAtTime.lastIndex : 0; + this._cachingAtTime.value = this.interpolateValue(frameNum, this._cachingAtTime); + this._cachingAtTime.lastFrame = frameNum; + } + return this._cachingAtTime.value; + } + function getSpeedAtTime(frameNum) { + var delta = -0.01; + var v1 = this.getValueAtTime(frameNum); + var v2 = this.getValueAtTime(frameNum + delta); + var speed = 0; + if (v1.length) { + var i; + for (i = 0;i < v1.length; i += 1) { + speed += Math.pow(v2[i] - v1[i], 2); + } + speed = Math.sqrt(speed) * 100; + } else { + speed = 0; + } + return speed; + } + function getVelocityAtTime(frameNum) { + if (this.vel !== undefined) { + return this.vel; + } + var delta = -0.001; + var v1 = this.getValueAtTime(frameNum); + var v2 = this.getValueAtTime(frameNum + delta); + var velocity2; + if (v1.length) { + velocity2 = createTypedArray("float32", v1.length); + var i; + for (i = 0;i < v1.length; i += 1) { + velocity2[i] = (v2[i] - v1[i]) / delta; + } + } else { + velocity2 = (v2 - v1) / delta; + } + return velocity2; + } + function getStaticValueAtTime() { + return this.pv; + } + function setGroupProperty(propertyGroup) { + this.propertyGroup = propertyGroup; + } + return { + searchExpressions, + getSpeedAtTime, + getVelocityAtTime, + getValueAtTime, + getStaticValueAtTime, + setGroupProperty + }; + }(); + setExpressionsPlugin(Expressions); + initialize$1(); + initialize(); +} +var standalone; +var animationData; +var renderer; +var queryString; +var scripts; +var index2; +var myScript; +var readyStateCheckInterval; +var registeredEffects; +var idPrefix; +var emptyShapeData; +var propTypes; +// node_modules/three/examples/jsm/loaders/OBJLoader.js +var _vA2 = new Vector3; +var _vB2 = new Vector3; +var _vC2 = new Vector3; +var _ab = new Vector3; +var _cb = new Vector3; +var _color3 = new Color; +// node_modules/three/examples/jsm/loaders/PLYLoader.js +var _color5 = new Color; +// node_modules/three/examples/jsm/loaders/UltraHDRLoader.js +var SRGB_TO_LINEAR = Array(1024).fill(0).map((_2, value2) => Math.pow(value2 / 255 * 0.9478672986 + 0.0521327014, 2.4)); +// node_modules/three/examples/jsm/loaders/RGBMLoader.js +var UPNG = {}; +UPNG.toRGBA8 = function(out) { + var { width: w, height: h } = out; + if (out.tabs.acTL == null) + return [UPNG.toRGBA8.decodeImage(out.data, w, h, out).buffer]; + var frms = []; + if (out.frames[0].data == null) + out.frames[0].data = out.data; + var len = w * h * 4, img = new Uint8Array(len), empty = new Uint8Array(len), prev = new Uint8Array(len); + for (var i = 0;i < out.frames.length; i++) { + var frm = out.frames[i]; + var fx = frm.rect.x, fy = frm.rect.y, fw = frm.rect.width, fh = frm.rect.height; + var fdata = UPNG.toRGBA8.decodeImage(frm.data, fw, fh, out); + if (i != 0) + for (var j2 = 0;j2 < len; j2++) + prev[j2] = img[j2]; + if (frm.blend == 0) + UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 0); + else if (frm.blend == 1) + UPNG._copyTile(fdata, fw, fh, img, w, h, fx, fy, 1); + frms.push(img.buffer.slice(0)); + if (frm.dispose == 1) + UPNG._copyTile(empty, fw, fh, img, w, h, fx, fy, 0); + else if (frm.dispose == 2) + for (var j2 = 0;j2 < len; j2++) + img[j2] = prev[j2]; + } + return frms; +}; +UPNG.toRGBA8.decodeImage = function(data2, w, h, out) { + var area2 = w * h, bpp = UPNG.decode._getBPP(out); + var bpl = Math.ceil(w * bpp / 8); + var bf = new Uint8Array(area2 * 4), bf32 = new Uint32Array(bf.buffer); + var { ctype, depth } = out; + var rs = UPNG._bin.readUshort; + if (ctype == 6) { + var qarea = area2 << 2; + if (depth == 8) + for (var i = 0;i < qarea; i += 4) { + bf[i] = data2[i]; + bf[i + 1] = data2[i + 1]; + bf[i + 2] = data2[i + 2]; + bf[i + 3] = data2[i + 3]; + } + if (depth == 16) + for (var i = 0;i < qarea; i++) { + bf[i] = data2[i << 1]; + } + } else if (ctype == 2) { + var ts = out.tabs["tRNS"]; + if (ts == null) { + if (depth == 8) + for (var i = 0;i < area2; i++) { + var ti = i * 3; + bf32[i] = 255 << 24 | data2[ti + 2] << 16 | data2[ti + 1] << 8 | data2[ti]; + } + if (depth == 16) + for (var i = 0;i < area2; i++) { + var ti = i * 6; + bf32[i] = 255 << 24 | data2[ti + 4] << 16 | data2[ti + 2] << 8 | data2[ti]; + } + } else { + var tr = ts[0], tg = ts[1], tb = ts[2]; + if (depth == 8) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 3; + bf32[i] = 255 << 24 | data2[ti + 2] << 16 | data2[ti + 1] << 8 | data2[ti]; + if (data2[ti] == tr && data2[ti + 1] == tg && data2[ti + 2] == tb) + bf[qi + 3] = 0; + } + if (depth == 16) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 6; + bf32[i] = 255 << 24 | data2[ti + 4] << 16 | data2[ti + 2] << 8 | data2[ti]; + if (rs(data2, ti) == tr && rs(data2, ti + 2) == tg && rs(data2, ti + 4) == tb) + bf[qi + 3] = 0; + } + } + } else if (ctype == 3) { + var p = out.tabs["PLTE"], ap = out.tabs["tRNS"], tl = ap ? ap.length : 0; + if (depth == 1) + for (var y = 0;y < h; y++) { + var s0 = y * bpl, t0 = y * w; + for (var i = 0;i < w; i++) { + var qi = t0 + i << 2, j2 = data2[s0 + (i >> 3)] >> 7 - ((i & 7) << 0) & 1, cj = 3 * j2; + bf[qi] = p[cj]; + bf[qi + 1] = p[cj + 1]; + bf[qi + 2] = p[cj + 2]; + bf[qi + 3] = j2 < tl ? ap[j2] : 255; + } + } + if (depth == 2) + for (var y = 0;y < h; y++) { + var s0 = y * bpl, t0 = y * w; + for (var i = 0;i < w; i++) { + var qi = t0 + i << 2, j2 = data2[s0 + (i >> 2)] >> 6 - ((i & 3) << 1) & 3, cj = 3 * j2; + bf[qi] = p[cj]; + bf[qi + 1] = p[cj + 1]; + bf[qi + 2] = p[cj + 2]; + bf[qi + 3] = j2 < tl ? ap[j2] : 255; + } + } + if (depth == 4) + for (var y = 0;y < h; y++) { + var s0 = y * bpl, t0 = y * w; + for (var i = 0;i < w; i++) { + var qi = t0 + i << 2, j2 = data2[s0 + (i >> 1)] >> 4 - ((i & 1) << 2) & 15, cj = 3 * j2; + bf[qi] = p[cj]; + bf[qi + 1] = p[cj + 1]; + bf[qi + 2] = p[cj + 2]; + bf[qi + 3] = j2 < tl ? ap[j2] : 255; + } + } + if (depth == 8) + for (var i = 0;i < area2; i++) { + var qi = i << 2, j2 = data2[i], cj = 3 * j2; + bf[qi] = p[cj]; + bf[qi + 1] = p[cj + 1]; + bf[qi + 2] = p[cj + 2]; + bf[qi + 3] = j2 < tl ? ap[j2] : 255; + } + } else if (ctype == 4) { + if (depth == 8) + for (var i = 0;i < area2; i++) { + var qi = i << 2, di2 = i << 1, gr = data2[di2]; + bf[qi] = gr; + bf[qi + 1] = gr; + bf[qi + 2] = gr; + bf[qi + 3] = data2[di2 + 1]; + } + if (depth == 16) + for (var i = 0;i < area2; i++) { + var qi = i << 2, di2 = i << 2, gr = data2[di2]; + bf[qi] = gr; + bf[qi + 1] = gr; + bf[qi + 2] = gr; + bf[qi + 3] = data2[di2 + 2]; + } + } else if (ctype == 0) { + var tr = out.tabs["tRNS"] ? out.tabs["tRNS"] : -1; + for (var y = 0;y < h; y++) { + var off = y * bpl, to = y * w; + if (depth == 1) + for (var x2 = 0;x2 < w; x2++) { + var gr = 255 * (data2[off + (x2 >>> 3)] >>> 7 - (x2 & 7) & 1), al2 = gr == tr * 255 ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + else if (depth == 2) + for (var x2 = 0;x2 < w; x2++) { + var gr = 85 * (data2[off + (x2 >>> 2)] >>> 6 - ((x2 & 3) << 1) & 3), al2 = gr == tr * 85 ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + else if (depth == 4) + for (var x2 = 0;x2 < w; x2++) { + var gr = 17 * (data2[off + (x2 >>> 1)] >>> 4 - ((x2 & 1) << 2) & 15), al2 = gr == tr * 17 ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + else if (depth == 8) + for (var x2 = 0;x2 < w; x2++) { + var gr = data2[off + x2], al2 = gr == tr ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + else if (depth == 16) + for (var x2 = 0;x2 < w; x2++) { + var gr = data2[off + (x2 << 1)], al2 = rs(data2, off + (x2 << 1)) == tr ? 0 : 255; + bf32[to + x2] = al2 << 24 | gr << 16 | gr << 8 | gr; + } + } + } + return bf; +}; +UPNG.decode = function(buff) { + var data2 = new Uint8Array(buff), offset = 8, bin = UPNG._bin, rUs = bin.readUshort, rUi = bin.readUint; + var out = { tabs: {}, frames: [] }; + var dd = new Uint8Array(data2.length), doff = 0; + var fd2, foff = 0; + var text2, keyw, bfr; + var mgck = [137, 80, 78, 71, 13, 10, 26, 10]; + for (var i = 0;i < 8; i++) + if (data2[i] != mgck[i]) + throw new Error("The input is not a PNG file!"); + while (offset < data2.length) { + var len = bin.readUint(data2, offset); + offset += 4; + var type = bin.readASCII(data2, offset, 4); + offset += 4; + if (type == "IHDR") { + UPNG.decode._IHDR(data2, offset, out); + } else if (type == "CgBI") { + out.tabs[type] = data2.slice(offset, offset + 4); + } else if (type == "IDAT") { + for (var i = 0;i < len; i++) + dd[doff + i] = data2[offset + i]; + doff += len; + } else if (type == "acTL") { + out.tabs[type] = { num_frames: rUi(data2, offset), num_plays: rUi(data2, offset + 4) }; + fd2 = new Uint8Array(data2.length); + } else if (type == "fcTL") { + if (foff != 0) { + var fr = out.frames[out.frames.length - 1]; + fr.data = UPNG.decode._decompress(out, fd2.slice(0, foff), fr.rect.width, fr.rect.height); + foff = 0; + } + var rct = { x: rUi(data2, offset + 12), y: rUi(data2, offset + 16), width: rUi(data2, offset + 4), height: rUi(data2, offset + 8) }; + var del = rUs(data2, offset + 22); + del = rUs(data2, offset + 20) / (del == 0 ? 100 : del); + var frm = { rect: rct, delay: Math.round(del * 1000), dispose: data2[offset + 24], blend: data2[offset + 25] }; + out.frames.push(frm); + } else if (type == "fdAT") { + for (var i = 0;i < len - 4; i++) + fd2[foff + i] = data2[offset + i + 4]; + foff += len - 4; + } else if (type == "pHYs") { + out.tabs[type] = [bin.readUint(data2, offset), bin.readUint(data2, offset + 4), data2[offset + 8]]; + } else if (type == "cHRM") { + out.tabs[type] = []; + for (var i = 0;i < 8; i++) + out.tabs[type].push(bin.readUint(data2, offset + i * 4)); + } else if (type == "tEXt" || type == "zTXt") { + if (out.tabs[type] == null) + out.tabs[type] = {}; + var nz = bin.nextZero(data2, offset); + keyw = bin.readASCII(data2, offset, nz - offset); + var tl = offset + len - nz - 1; + if (type == "tEXt") + text2 = bin.readASCII(data2, nz + 1, tl); + else { + bfr = UPNG.decode._inflate(data2.slice(nz + 2, nz + 2 + tl)); + text2 = bin.readUTF8(bfr, 0, bfr.length); + } + out.tabs[type][keyw] = text2; + } else if (type == "iTXt") { + if (out.tabs[type] == null) + out.tabs[type] = {}; + var nz = 0, off = offset; + nz = bin.nextZero(data2, off); + keyw = bin.readASCII(data2, off, nz - off); + off = nz + 1; + var cflag = data2[off]; + off += 2; + nz = bin.nextZero(data2, off); + bin.readASCII(data2, off, nz - off); + off = nz + 1; + nz = bin.nextZero(data2, off); + bin.readUTF8(data2, off, nz - off); + off = nz + 1; + var tl = len - (off - offset); + if (cflag == 0) + text2 = bin.readUTF8(data2, off, tl); + else { + bfr = UPNG.decode._inflate(data2.slice(off, off + tl)); + text2 = bin.readUTF8(bfr, 0, bfr.length); + } + out.tabs[type][keyw] = text2; + } else if (type == "PLTE") { + out.tabs[type] = bin.readBytes(data2, offset, len); + } else if (type == "hIST") { + var pl2 = out.tabs["PLTE"].length / 3; + out.tabs[type] = []; + for (var i = 0;i < pl2; i++) + out.tabs[type].push(rUs(data2, offset + i * 2)); + } else if (type == "tRNS") { + if (out.ctype == 3) + out.tabs[type] = bin.readBytes(data2, offset, len); + else if (out.ctype == 0) + out.tabs[type] = rUs(data2, offset); + else if (out.ctype == 2) + out.tabs[type] = [rUs(data2, offset), rUs(data2, offset + 2), rUs(data2, offset + 4)]; + } else if (type == "gAMA") + out.tabs[type] = bin.readUint(data2, offset) / 1e5; + else if (type == "sRGB") + out.tabs[type] = data2[offset]; + else if (type == "bKGD") { + if (out.ctype == 0 || out.ctype == 4) + out.tabs[type] = [rUs(data2, offset)]; + else if (out.ctype == 2 || out.ctype == 6) + out.tabs[type] = [rUs(data2, offset), rUs(data2, offset + 2), rUs(data2, offset + 4)]; + else if (out.ctype == 3) + out.tabs[type] = data2[offset]; + } else if (type == "IEND") { + break; + } + offset += len; + bin.readUint(data2, offset); + offset += 4; + } + if (foff != 0) { + var fr = out.frames[out.frames.length - 1]; + fr.data = UPNG.decode._decompress(out, fd2.slice(0, foff), fr.rect.width, fr.rect.height); + } + out.data = UPNG.decode._decompress(out, dd, out.width, out.height); + delete out.compress; + delete out.interlace; + delete out.filter; + return out; +}; +UPNG.decode._decompress = function(out, dd, w, h) { + var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w * bpp / 8), buff = new Uint8Array((bpl + 1 + out.interlace) * h); + if (out.tabs["CgBI"]) + dd = UPNG.inflateRaw(dd, buff); + else + dd = UPNG.decode._inflate(dd, buff); + if (out.interlace == 0) + dd = UPNG.decode._filterZero(dd, out, 0, w, h); + else if (out.interlace == 1) + dd = UPNG.decode._readInterlace(dd, out); + return dd; +}; +UPNG.decode._inflate = function(data2, buff) { + var out = UPNG["inflateRaw"](new Uint8Array(data2.buffer, 2, data2.length - 6), buff); + return out; +}; +UPNG.inflateRaw = function() { + var H = {}; + H.H = {}; + H.H.N = function(N, W) { + var R2 = Uint8Array, i = 0, m = 0, J2 = 0, h = 0, Q2 = 0, X = 0, u2 = 0, w = 0, d = 0, v, C4; + if (N[0] == 3 && N[1] == 0) + return W ? W : new R2(0); + var V2 = H.H, n2 = V2.b, A2 = V2.e, l2 = V2.R, M = V2.n, I3 = V2.A, e = V2.Z, b = V2.m, Z2 = W == null; + if (Z2) + W = new R2(N.length >>> 2 << 5); + while (i == 0) { + i = n2(N, d, 1); + m = n2(N, d + 1, 2); + d += 3; + if (m == 0) { + if ((d & 7) != 0) + d += 8 - (d & 7); + var D = (d >>> 3) + 4, q2 = N[D - 4] | N[D - 3] << 8; + if (Z2) + W = H.H.W(W, w + q2); + W.set(new R2(N.buffer, N.byteOffset + D, q2), w); + d = D + q2 << 3; + w += q2; + continue; + } + if (Z2) + W = H.H.W(W, w + (1 << 17)); + if (m == 1) { + v = b.J; + C4 = b.h; + X = (1 << 9) - 1; + u2 = (1 << 5) - 1; + } + if (m == 2) { + J2 = A2(N, d, 5) + 257; + h = A2(N, d + 5, 5) + 1; + Q2 = A2(N, d + 10, 4) + 4; + d += 14; + var j2 = 1; + for (var c = 0;c < 38; c += 2) { + b.Q[c] = 0; + b.Q[c + 1] = 0; + } + for (var c = 0;c < Q2; c++) { + var K = A2(N, d + c * 3, 3); + b.Q[(b.X[c] << 1) + 1] = K; + if (K > j2) + j2 = K; + } + d += 3 * Q2; + M(b.Q, j2); + I3(b.Q, j2, b.u); + v = b.w; + C4 = b.d; + d = l2(b.u, (1 << j2) - 1, J2 + h, N, d, b.v); + var r = V2.V(b.v, 0, J2, b.C); + X = (1 << r) - 1; + var S = V2.V(b.v, J2, h, b.D); + u2 = (1 << S) - 1; + M(b.C, r); + I3(b.C, r, v); + M(b.D, S); + I3(b.D, S, C4); + } + while (true) { + var T2 = v[e(N, d) & X]; + d += T2 & 15; + var p = T2 >>> 4; + if (p >>> 8 == 0) { + W[w++] = p; + } else if (p == 256) { + break; + } else { + var z = w + p - 254; + if (p > 264) { + var _2 = b.q[p - 257]; + z = w + (_2 >>> 3) + A2(N, d, _2 & 7); + d += _2 & 7; + } + var $2 = C4[e(N, d) & u2]; + d += $2 & 15; + var s = $2 >>> 4, Y = b.c[s], a = (Y >>> 4) + n2(N, d, Y & 15); + d += Y & 15; + while (w < z) { + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + } + w = z; + } + } + } + return W.length == w ? W : W.slice(0, w); + }; + H.H.W = function(N, W) { + var R2 = N.length; + if (W <= R2) + return N; + var V2 = new Uint8Array(R2 << 1); + V2.set(N, 0); + return V2; + }; + H.H.R = function(N, W, R2, V2, n2, A2) { + var l2 = H.H.e, M = H.H.Z, I3 = 0; + while (I3 < R2) { + var e = N[M(V2, n2) & W]; + n2 += e & 15; + var b = e >>> 4; + if (b <= 15) { + A2[I3] = b; + I3++; + } else { + var Z2 = 0, m = 0; + if (b == 16) { + m = 3 + l2(V2, n2, 2); + n2 += 2; + Z2 = A2[I3 - 1]; + } else if (b == 17) { + m = 3 + l2(V2, n2, 3); + n2 += 3; + } else if (b == 18) { + m = 11 + l2(V2, n2, 7); + n2 += 7; + } + var J2 = I3 + m; + while (I3 < J2) { + A2[I3] = Z2; + I3++; + } + } + } + return n2; + }; + H.H.V = function(N, W, R2, V2) { + var n2 = 0, A2 = 0, l2 = V2.length >>> 1; + while (A2 < R2) { + var M = N[A2 + W]; + V2[A2 << 1] = 0; + V2[(A2 << 1) + 1] = M; + if (M > n2) + n2 = M; + A2++; + } + while (A2 < l2) { + V2[A2 << 1] = 0; + V2[(A2 << 1) + 1] = 0; + A2++; + } + return n2; + }; + H.H.n = function(N, W) { + var R2 = H.H.m, V2 = N.length, n2, A2, l2, M, I3, e = R2.j; + for (var M = 0;M <= W; M++) + e[M] = 0; + for (M = 1;M < V2; M += 2) + e[N[M]]++; + var b = R2.K; + n2 = 0; + e[0] = 0; + for (A2 = 1;A2 <= W; A2++) { + n2 = n2 + e[A2 - 1] << 1; + b[A2] = n2; + } + for (l2 = 0;l2 < V2; l2 += 2) { + I3 = N[l2 + 1]; + if (I3 != 0) { + N[l2] = b[I3]; + b[I3]++; + } + } + }; + H.H.A = function(N, W, R2) { + var V2 = N.length, n2 = H.H.m, A2 = n2.r; + for (var l2 = 0;l2 < V2; l2 += 2) + if (N[l2 + 1] != 0) { + var M = l2 >> 1, I3 = N[l2 + 1], e = M << 4 | I3, b = W - I3, Z2 = N[l2] << b, m = Z2 + (1 << b); + while (Z2 != m) { + var J2 = A2[Z2] >>> 15 - W; + R2[J2] = e; + Z2++; + } + } + }; + H.H.l = function(N, W) { + var R2 = H.H.m.r, V2 = 15 - W; + for (var n2 = 0;n2 < N.length; n2 += 2) { + var A2 = N[n2] << W - N[n2 + 1]; + N[n2] = R2[A2] >>> V2; + } + }; + H.H.M = function(N, W, R2) { + R2 = R2 << (W & 7); + var V2 = W >>> 3; + N[V2] |= R2; + N[V2 + 1] |= R2 >>> 8; + }; + H.H.I = function(N, W, R2) { + R2 = R2 << (W & 7); + var V2 = W >>> 3; + N[V2] |= R2; + N[V2 + 1] |= R2 >>> 8; + N[V2 + 2] |= R2 >>> 16; + }; + H.H.e = function(N, W, R2) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8) >>> (W & 7) & (1 << R2) - 1; + }; + H.H.b = function(N, W, R2) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7) & (1 << R2) - 1; + }; + H.H.Z = function(N, W) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7); + }; + H.H.i = function(N, W) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16 | N[(W >>> 3) + 3] << 24) >>> (W & 7); + }; + H.H.m = function() { + var N = Uint16Array, W = Uint32Array; + return { K: new N(16), j: new N(16), X: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], S: [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, 999, 999, 999], T: [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, 0, 0, 0], q: new N(32), 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, 65535, 65535], z: [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, 0, 0], c: new W(32), J: new N(512), _: [], h: new N(32), $: [], w: new N(32768), C: [], v: [], d: new N(32768), D: [], u: new N(512), Q: [], r: new N(1 << 15), s: new W(286), Y: new W(30), a: new W(19), t: new W(15000), k: new N(1 << 16), g: new N(1 << 15) }; + }(); + (function() { + var N = H.H.m, W = 1 << 15; + for (var R2 = 0;R2 < W; R2++) { + var V2 = R2; + V2 = (V2 & 2863311530) >>> 1 | (V2 & 1431655765) << 1; + V2 = (V2 & 3435973836) >>> 2 | (V2 & 858993459) << 2; + V2 = (V2 & 4042322160) >>> 4 | (V2 & 252645135) << 4; + V2 = (V2 & 4278255360) >>> 8 | (V2 & 16711935) << 8; + N.r[R2] = (V2 >>> 16 | V2 << 16) >>> 17; + } + function n2(A2, l2, M) { + while (l2-- != 0) + A2.push(0, M); + } + for (var R2 = 0;R2 < 32; R2++) { + N.q[R2] = N.S[R2] << 3 | N.T[R2]; + N.c[R2] = N.p[R2] << 4 | N.z[R2]; + } + n2(N._, 144, 8); + n2(N._, 255 - 143, 9); + n2(N._, 279 - 255, 7); + n2(N._, 287 - 279, 8); + H.H.n(N._, 9); + H.H.A(N._, 9, N.J); + H.H.l(N._, 9); + n2(N.$, 32, 5); + H.H.n(N.$, 5); + H.H.A(N.$, 5, N.h); + H.H.l(N.$, 5); + n2(N.Q, 19, 0); + n2(N.C, 286, 0); + n2(N.D, 30, 0); + n2(N.v, 320, 0); + })(); + return H.H.N; +}(); +UPNG.decode._readInterlace = function(data2, out) { + var { width: w, height: h } = out; + var bpp = UPNG.decode._getBPP(out), cbpp = bpp >> 3, bpl = Math.ceil(w * bpp / 8); + var img = new Uint8Array(h * bpl); + var di2 = 0; + var starting_row = [0, 0, 4, 0, 2, 0, 1]; + var starting_col = [0, 4, 0, 2, 0, 1, 0]; + var row_increment = [8, 8, 8, 4, 4, 2, 2]; + var col_increment = [8, 8, 4, 4, 2, 2, 1]; + var pass = 0; + while (pass < 7) { + var ri = row_increment[pass], ci = col_increment[pass]; + var sw = 0, sh = 0; + var cr = starting_row[pass]; + while (cr < h) { + cr += ri; + sh++; + } + var cc = starting_col[pass]; + while (cc < w) { + cc += ci; + sw++; + } + var bpll = Math.ceil(sw * bpp / 8); + UPNG.decode._filterZero(data2, out, di2, sw, sh); + var y = 0, row = starting_row[pass]; + var val2; + while (row < h) { + var col = starting_col[pass]; + var cdi = di2 + y * bpll << 3; + while (col < w) { + if (bpp == 1) { + val2 = data2[cdi >> 3]; + val2 = val2 >> 7 - (cdi & 7) & 1; + img[row * bpl + (col >> 3)] |= val2 << 7 - ((col & 7) << 0); + } + if (bpp == 2) { + val2 = data2[cdi >> 3]; + val2 = val2 >> 6 - (cdi & 7) & 3; + img[row * bpl + (col >> 2)] |= val2 << 6 - ((col & 3) << 1); + } + if (bpp == 4) { + val2 = data2[cdi >> 3]; + val2 = val2 >> 4 - (cdi & 7) & 15; + img[row * bpl + (col >> 1)] |= val2 << 4 - ((col & 1) << 2); + } + if (bpp >= 8) { + var ii = row * bpl + col * cbpp; + for (var j2 = 0;j2 < cbpp; j2++) + img[ii + j2] = data2[(cdi >> 3) + j2]; + } + cdi += bpp; + col += ci; + } + y++; + row += ri; + } + if (sw * sh != 0) + di2 += sh * (1 + bpll); + pass = pass + 1; + } + return img; +}; +UPNG.decode._getBPP = function(out) { + var noc = [1, null, 3, 1, 2, null, 4][out.ctype]; + return noc * out.depth; +}; +UPNG.decode._filterZero = function(data2, out, off, w, h) { + var bpp = UPNG.decode._getBPP(out), bpl = Math.ceil(w * bpp / 8), paeth = UPNG.decode._paeth; + bpp = Math.ceil(bpp / 8); + var i, di2, type = data2[off], x2 = 0; + if (type > 1) + data2[off] = [0, 0, 1][type - 2]; + if (type == 3) + for (x2 = bpp;x2 < bpl; x2++) + data2[x2 + 1] = data2[x2 + 1] + (data2[x2 + 1 - bpp] >>> 1) & 255; + for (var y = 0;y < h; y++) { + i = off + y * bpl; + di2 = i + y + 1; + type = data2[di2 - 1]; + x2 = 0; + if (type == 0) + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2]; + else if (type == 1) { + for (;x2 < bpp; x2++) + data2[i + x2] = data2[di2 + x2]; + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2] + data2[i + x2 - bpp]; + } else if (type == 2) { + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2] + data2[i + x2 - bpl]; + } else if (type == 3) { + for (;x2 < bpp; x2++) + data2[i + x2] = data2[di2 + x2] + (data2[i + x2 - bpl] >>> 1); + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2] + (data2[i + x2 - bpl] + data2[i + x2 - bpp] >>> 1); + } else { + for (;x2 < bpp; x2++) + data2[i + x2] = data2[di2 + x2] + paeth(0, data2[i + x2 - bpl], 0); + for (;x2 < bpl; x2++) + data2[i + x2] = data2[di2 + x2] + paeth(data2[i + x2 - bpp], data2[i + x2 - bpl], data2[i + x2 - bpp - bpl]); + } + } + return data2; +}; +UPNG.decode._paeth = function(a, b, c) { + var p = a + b - c, pa = p - a, pb = p - b, pc = p - c; + if (pa * pa <= pb * pb && pa * pa <= pc * pc) + return a; + else if (pb * pb <= pc * pc) + return b; + return c; +}; +UPNG.decode._IHDR = function(data2, offset, out) { + var bin = UPNG._bin; + out.width = bin.readUint(data2, offset); + offset += 4; + out.height = bin.readUint(data2, offset); + offset += 4; + out.depth = data2[offset]; + offset++; + out.ctype = data2[offset]; + offset++; + out.compress = data2[offset]; + offset++; + out.filter = data2[offset]; + offset++; + out.interlace = data2[offset]; + offset++; +}; +UPNG._bin = { + nextZero: function(data2, p) { + while (data2[p] != 0) + p++; + return p; + }, + readUshort: function(buff, p) { + return buff[p] << 8 | buff[p + 1]; + }, + writeUshort: function(buff, p, n2) { + buff[p] = n2 >> 8 & 255; + buff[p + 1] = n2 & 255; + }, + readUint: function(buff, p) { + return buff[p] * (256 * 256 * 256) + (buff[p + 1] << 16 | buff[p + 2] << 8 | buff[p + 3]); + }, + writeUint: function(buff, p, n2) { + buff[p] = n2 >> 24 & 255; + buff[p + 1] = n2 >> 16 & 255; + buff[p + 2] = n2 >> 8 & 255; + buff[p + 3] = n2 & 255; + }, + readASCII: function(buff, p, l2) { + var s = ""; + for (var i = 0;i < l2; i++) + s += String.fromCharCode(buff[p + i]); + return s; + }, + writeASCII: function(data2, p, s) { + for (var i = 0;i < s.length; i++) + data2[p + i] = s.charCodeAt(i); + }, + readBytes: function(buff, p, l2) { + var arr = []; + for (var i = 0;i < l2; i++) + arr.push(buff[p + i]); + return arr; + }, + pad: function(n2) { + return n2.length < 2 ? "0" + n2 : n2; + }, + readUTF8: function(buff, p, l2) { + var s = "", ns; + for (var i = 0;i < l2; i++) + s += "%" + UPNG._bin.pad(buff[p + i].toString(16)); + try { + ns = decodeURIComponent(s); + } catch (e) { + return UPNG._bin.readASCII(buff, p, l2); + } + return ns; + } +}; +UPNG._copyTile = function(sb, sw, sh, tb, tw, th, xoff, yoff, mode) { + var w = Math.min(sw, tw), h = Math.min(sh, th); + var si = 0, ti = 0; + for (var y = 0;y < h; y++) + for (var x2 = 0;x2 < w; x2++) { + if (xoff >= 0 && yoff >= 0) { + si = y * sw + x2 << 2; + ti = (yoff + y) * tw + xoff + x2 << 2; + } else { + si = (-yoff + y) * sw - xoff + x2 << 2; + ti = y * tw + x2 << 2; + } + if (mode == 0) { + tb[ti] = sb[si]; + tb[ti + 1] = sb[si + 1]; + tb[ti + 2] = sb[si + 2]; + tb[ti + 3] = sb[si + 3]; + } else if (mode == 1) { + var fa = sb[si + 3] * (1 / 255), fr = sb[si] * fa, fg = sb[si + 1] * fa, fb = sb[si + 2] * fa; + var ba = tb[ti + 3] * (1 / 255), br = tb[ti] * ba, bg = tb[ti + 1] * ba, bb = tb[ti + 2] * ba; + var ifa = 1 - fa, oa = fa + ba * ifa, ioa = oa == 0 ? 0 : 1 / oa; + tb[ti + 3] = 255 * oa; + tb[ti + 0] = (fr + br * ifa) * ioa; + tb[ti + 1] = (fg + bg * ifa) * ioa; + tb[ti + 2] = (fb + bb * ifa) * ioa; + } else if (mode == 2) { + var fa = sb[si + 3], fr = sb[si], fg = sb[si + 1], fb = sb[si + 2]; + var ba = tb[ti + 3], br = tb[ti], bg = tb[ti + 1], bb = tb[ti + 2]; + if (fa == ba && fr == br && fg == bg && fb == bb) { + tb[ti] = 0; + tb[ti + 1] = 0; + tb[ti + 2] = 0; + tb[ti + 3] = 0; + } else { + tb[ti] = fr; + tb[ti + 1] = fg; + tb[ti + 2] = fb; + tb[ti + 3] = fa; + } + } else if (mode == 3) { + var fa = sb[si + 3], fr = sb[si], fg = sb[si + 1], fb = sb[si + 2]; + var ba = tb[ti + 3], br = tb[ti], bg = tb[ti + 1], bb = tb[ti + 2]; + if (fa == ba && fr == br && fg == bg && fb == bb) + continue; + if (fa < 220 && ba > 20) + return false; + } + } + return true; +}; +// node_modules/three/examples/jsm/libs/utif.module.js +var UTIF = {}; +(function() { + var W = function a1() { + function W2(p) { + this.message = "JPEG error: " + p; + } + W2.prototype = new Error; + W2.prototype.name = "JpegError"; + W2.constructor = W2; + return W2; + }(), ak = function ag() { + var p = new Uint8Array([0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]), t2 = 4017, ac = 799, ah = 3406, ao = 2276, ar = 1567, ai = 3784, s = 5793, ad = 2896; + function ak2(Q2) { + if (Q2 == null) + Q2 = {}; + if (Q2.w == null) + Q2.w = -1; + this.V = Q2.n; + this.N = Q2.w; + } + function a5(Q2, h) { + var f = 0, G2 = [], n2, E2, a = 16, F; + while (a > 0 && !Q2[a - 1]) { + a--; + } + G2.push({ children: [], index: 0 }); + var C4 = G2[0]; + for (n2 = 0;n2 < a; n2++) { + for (E2 = 0;E2 < Q2[n2]; E2++) { + C4 = G2.pop(); + C4.children[C4.index] = h[f]; + while (C4.index > 0) { + C4 = G2.pop(); + } + C4.index++; + G2.push(C4); + while (G2.length <= n2) { + G2.push(F = { children: [], index: 0 }); + C4.children[C4.index] = F.children; + C4 = F; + } + f++; + } + if (n2 + 1 < a) { + G2.push(F = { children: [], index: 0 }); + C4.children[C4.index] = F.children; + C4 = F; + } + } + return G2[0].children; + } + function a2(Q2, h, f) { + return 64 * ((Q2.P + 1) * h + f); + } + function a7(Q2, h, f, G2, n2, E2, a, C4, F, d) { + if (d == null) + d = false; + var { m: T2, Z: U } = f, z = h, J2 = 0, V2 = 0, r = 0, D = 0, a8, q2 = 0, X, O, _2, N, e, K, x2 = 0, k2, g3, R2, c; + function Y() { + if (V2 > 0) { + V2--; + return J2 >> V2 & 1; + } + J2 = Q2[h++]; + if (J2 === 255) { + var I3 = Q2[h++]; + if (I3) { + if (I3 === 220 && d) { + h += 2; + var l2 = Z2(Q2, h); + h += 2; + if (l2 > 0 && l2 !== f.s) { + throw new DNLMarkerError("Found DNL marker (0xFFDC) while parsing scan data", l2); + } + } else if (I3 === 217) { + if (d) { + var M = q2 * 8; + if (M > 0 && M < f.s / 10) { + throw new DNLMarkerError("Found EOI marker (0xFFD9) while parsing scan data, " + "possibly caused by incorrect `scanLines` parameter", M); + } + } + throw new EOIMarkerError("Found EOI marker (0xFFD9) while parsing scan data"); + } + throw new W("unexpected marker"); + } + } + V2 = 7; + return J2 >>> 7; + } + function u2(I3) { + var l2 = I3; + while (true) { + l2 = l2[Y()]; + switch (typeof l2) { + case "number": + return l2; + case "object": + continue; + } + throw new W("invalid huffman sequence"); + } + } + function m(I3) { + var e2 = 0; + while (I3 > 0) { + e2 = e2 << 1 | Y(); + I3--; + } + return e2; + } + function j2(I3) { + if (I3 === 1) { + return Y() === 1 ? 1 : -1; + } + var e2 = m(I3); + if (e2 >= 1 << I3 - 1) { + return e2; + } + return e2 + (-1 << I3) + 1; + } + function v(X2, I3) { + var l2 = u2(X2.J), M = l2 === 0 ? 0 : j2(l2), N2 = 1; + X2.D[I3] = X2.Q += M; + while (N2 < 64) { + var S = u2(X2.i), i = S & 15, A2 = S >> 4; + if (i === 0) { + if (A2 < 15) { + break; + } + N2 += 16; + continue; + } + N2 += A2; + var o = p[N2]; + X2.D[I3 + o] = j2(i); + N2++; + } + } + function $2(X2, I3) { + var l2 = u2(X2.J), M = l2 === 0 ? 0 : j2(l2) << F; + X2.D[I3] = X2.Q += M; + } + function b(X2, I3) { + X2.D[I3] |= Y() << F; + } + function P(X2, I3) { + if (r > 0) { + r--; + return; + } + var N2 = E2, l2 = a; + while (N2 <= l2) { + var M = u2(X2.i), S = M & 15, i = M >> 4; + if (S === 0) { + if (i < 15) { + r = m(i) + (1 << i) - 1; + break; + } + N2 += 16; + continue; + } + N2 += i; + var A2 = p[N2]; + X2.D[I3 + A2] = j2(S) * (1 << F); + N2++; + } + } + function a4(X2, I3) { + var N2 = E2, l2 = a, M = 0, S, i; + while (N2 <= l2) { + var A2 = I3 + p[N2], o = X2.D[A2] < 0 ? -1 : 1; + switch (D) { + case 0: + i = u2(X2.i); + S = i & 15; + M = i >> 4; + if (S === 0) { + if (M < 15) { + r = m(M) + (1 << M); + D = 4; + } else { + M = 16; + D = 1; + } + } else { + if (S !== 1) { + throw new W("invalid ACn encoding"); + } + a8 = j2(S); + D = M ? 2 : 3; + } + continue; + case 1: + case 2: + if (X2.D[A2]) { + X2.D[A2] += o * (Y() << F); + } else { + M--; + if (M === 0) { + D = D === 2 ? 3 : 0; + } + } + break; + case 3: + if (X2.D[A2]) { + X2.D[A2] += o * (Y() << F); + } else { + X2.D[A2] = a8 << F; + D = 0; + } + break; + case 4: + if (X2.D[A2]) { + X2.D[A2] += o * (Y() << F); + } + break; + } + N2++; + } + if (D === 4) { + r--; + if (r === 0) { + D = 0; + } + } + } + function H(X2, I3, x3, l2, M) { + var S = x3 / T2 | 0, i = x3 % T2; + q2 = S * X2.A + l2; + var A2 = i * X2.h + M, o = a2(X2, q2, A2); + I3(X2, o); + } + function w(X2, I3, x3) { + q2 = x3 / X2.P | 0; + var l2 = x3 % X2.P, M = a2(X2, q2, l2); + I3(X2, M); + } + var y = G2.length; + if (U) { + if (E2 === 0) { + K = C4 === 0 ? $2 : b; + } else { + K = C4 === 0 ? P : a4; + } + } else { + K = v; + } + if (y === 1) { + g3 = G2[0].P * G2[0].c; + } else { + g3 = T2 * f.R; + } + while (x2 <= g3) { + var L = n2 ? Math.min(g3 - x2, n2) : g3; + if (L > 0) { + for (O = 0;O < y; O++) { + G2[O].Q = 0; + } + r = 0; + if (y === 1) { + X = G2[0]; + for (e = 0;e < L; e++) { + w(X, K, x2); + x2++; + } + } else { + for (e = 0;e < L; e++) { + for (O = 0;O < y; O++) { + X = G2[O]; + R2 = X.h; + c = X.A; + for (_2 = 0;_2 < c; _2++) { + for (N = 0;N < R2; N++) { + H(X, K, x2, _2, N); + } + } + } + x2++; + } + } + } + V2 = 0; + k2 = an(Q2, h); + if (!k2) { + break; + } + if (k2.u) { + var a6 = L > 0 ? "unexpected" : "excessive"; + h = k2.offset; + } + if (k2.M >= 65488 && k2.M <= 65495) { + h += 2; + } else { + break; + } + } + return h - z; + } + function al2(Q2, h, f) { + var { $: G2, D: n2 } = Q2, E2, a, C4, F, d, T2, U, z, J2, V2, Y, u2, m, j2, v, $2, b; + if (!G2) { + throw new W("missing required Quantization Table."); + } + for (var r = 0;r < 64; r += 8) { + J2 = n2[h + r]; + V2 = n2[h + r + 1]; + Y = n2[h + r + 2]; + u2 = n2[h + r + 3]; + m = n2[h + r + 4]; + j2 = n2[h + r + 5]; + v = n2[h + r + 6]; + $2 = n2[h + r + 7]; + J2 *= G2[r]; + if ((V2 | Y | u2 | m | j2 | v | $2) === 0) { + b = s * J2 + 512 >> 10; + f[r] = b; + f[r + 1] = b; + f[r + 2] = b; + f[r + 3] = b; + f[r + 4] = b; + f[r + 5] = b; + f[r + 6] = b; + f[r + 7] = b; + continue; + } + V2 *= G2[r + 1]; + Y *= G2[r + 2]; + u2 *= G2[r + 3]; + m *= G2[r + 4]; + j2 *= G2[r + 5]; + v *= G2[r + 6]; + $2 *= G2[r + 7]; + E2 = s * J2 + 128 >> 8; + a = s * m + 128 >> 8; + C4 = Y; + F = v; + d = ad * (V2 - $2) + 128 >> 8; + z = ad * (V2 + $2) + 128 >> 8; + T2 = u2 << 4; + U = j2 << 4; + E2 = E2 + a + 1 >> 1; + a = E2 - a; + b = C4 * ai + F * ar + 128 >> 8; + C4 = C4 * ar - F * ai + 128 >> 8; + F = b; + d = d + U + 1 >> 1; + U = d - U; + z = z + T2 + 1 >> 1; + T2 = z - T2; + E2 = E2 + F + 1 >> 1; + F = E2 - F; + a = a + C4 + 1 >> 1; + C4 = a - C4; + b = d * ao + z * ah + 2048 >> 12; + d = d * ah - z * ao + 2048 >> 12; + z = b; + b = T2 * ac + U * t2 + 2048 >> 12; + T2 = T2 * t2 - U * ac + 2048 >> 12; + U = b; + f[r] = E2 + z; + f[r + 7] = E2 - z; + f[r + 1] = a + U; + f[r + 6] = a - U; + f[r + 2] = C4 + T2; + f[r + 5] = C4 - T2; + f[r + 3] = F + d; + f[r + 4] = F - d; + } + for (var P = 0;P < 8; ++P) { + J2 = f[P]; + V2 = f[P + 8]; + Y = f[P + 16]; + u2 = f[P + 24]; + m = f[P + 32]; + j2 = f[P + 40]; + v = f[P + 48]; + $2 = f[P + 56]; + if ((V2 | Y | u2 | m | j2 | v | $2) === 0) { + b = s * J2 + 8192 >> 14; + if (b < -2040) { + b = 0; + } else if (b >= 2024) { + b = 255; + } else { + b = b + 2056 >> 4; + } + n2[h + P] = b; + n2[h + P + 8] = b; + n2[h + P + 16] = b; + n2[h + P + 24] = b; + n2[h + P + 32] = b; + n2[h + P + 40] = b; + n2[h + P + 48] = b; + n2[h + P + 56] = b; + continue; + } + E2 = s * J2 + 2048 >> 12; + a = s * m + 2048 >> 12; + C4 = Y; + F = v; + d = ad * (V2 - $2) + 2048 >> 12; + z = ad * (V2 + $2) + 2048 >> 12; + T2 = u2; + U = j2; + E2 = (E2 + a + 1 >> 1) + 4112; + a = E2 - a; + b = C4 * ai + F * ar + 2048 >> 12; + C4 = C4 * ar - F * ai + 2048 >> 12; + F = b; + d = d + U + 1 >> 1; + U = d - U; + z = z + T2 + 1 >> 1; + T2 = z - T2; + E2 = E2 + F + 1 >> 1; + F = E2 - F; + a = a + C4 + 1 >> 1; + C4 = a - C4; + b = d * ao + z * ah + 2048 >> 12; + d = d * ah - z * ao + 2048 >> 12; + z = b; + b = T2 * ac + U * t2 + 2048 >> 12; + T2 = T2 * t2 - U * ac + 2048 >> 12; + U = b; + J2 = E2 + z; + $2 = E2 - z; + V2 = a + U; + v = a - U; + Y = C4 + T2; + j2 = C4 - T2; + u2 = F + d; + m = F - d; + if (J2 < 16) { + J2 = 0; + } else if (J2 >= 4080) { + J2 = 255; + } else { + J2 >>= 4; + } + if (V2 < 16) { + V2 = 0; + } else if (V2 >= 4080) { + V2 = 255; + } else { + V2 >>= 4; + } + if (Y < 16) { + Y = 0; + } else if (Y >= 4080) { + Y = 255; + } else { + Y >>= 4; + } + if (u2 < 16) { + u2 = 0; + } else if (u2 >= 4080) { + u2 = 255; + } else { + u2 >>= 4; + } + if (m < 16) { + m = 0; + } else if (m >= 4080) { + m = 255; + } else { + m >>= 4; + } + if (j2 < 16) { + j2 = 0; + } else if (j2 >= 4080) { + j2 = 255; + } else { + j2 >>= 4; + } + if (v < 16) { + v = 0; + } else if (v >= 4080) { + v = 255; + } else { + v >>= 4; + } + if ($2 < 16) { + $2 = 0; + } else if ($2 >= 4080) { + $2 = 255; + } else { + $2 >>= 4; + } + n2[h + P] = J2; + n2[h + P + 8] = V2; + n2[h + P + 16] = Y; + n2[h + P + 24] = u2; + n2[h + P + 32] = m; + n2[h + P + 40] = j2; + n2[h + P + 48] = v; + n2[h + P + 56] = $2; + } + } + function a0(Q2, h) { + var { P: f, c: G2 } = h, n2 = new Int16Array(64); + for (var E2 = 0;E2 < G2; E2++) { + for (var a = 0;a < f; a++) { + var C4 = a2(h, E2, a); + al2(h, C4, n2); + } + } + return h.D; + } + function an(Q2, h, f) { + if (f == null) + f = h; + var G2 = Q2.length - 1, n2 = f < h ? f : h; + if (h >= G2) { + return null; + } + var E2 = Z2(Q2, h); + if (E2 >= 65472 && E2 <= 65534) { + return { u: null, M: E2, offset: h }; + } + var a = Z2(Q2, n2); + while (!(a >= 65472 && a <= 65534)) { + if (++n2 >= G2) { + return null; + } + a = Z2(Q2, n2); + } + return { u: E2.toString(16), M: a, offset: n2 }; + } + ak2.prototype = { parse(Q2, h) { + if (h == null) + h = {}; + var f = h.F, E2 = 0, a = null, C4 = null, F, d, T2 = 0; + function G2() { + var o = Z2(Q2, E2); + E2 += 2; + var B2 = E2 + o - 2, V3 = an(Q2, B2, E2); + if (V3 && V3.u) { + B2 = V3.offset; + } + var ab = Q2.subarray(E2, B2); + E2 += ab.length; + return ab; + } + function n2(F2) { + var o = Math.ceil(F2.o / 8 / F2.X), B2 = Math.ceil(F2.s / 8 / F2.B); + for (var Y2 = 0;Y2 < F2.W.length; Y2++) { + R2 = F2.W[Y2]; + var ab = Math.ceil(Math.ceil(F2.o / 8) * R2.h / F2.X), af = Math.ceil(Math.ceil(F2.s / 8) * R2.A / F2.B), ap = o * R2.h, aq = B2 * R2.A, ae3 = 64 * aq * (ap + 1); + R2.D = new Int16Array(ae3); + R2.P = ab; + R2.c = af; + } + F2.m = o; + F2.R = B2; + } + var U = [], z = [], J2 = [], V2 = Z2(Q2, E2); + E2 += 2; + if (V2 !== 65496) { + throw new W("SOI not found"); + } + V2 = Z2(Q2, E2); + E2 += 2; + markerLoop: + while (V2 !== 65497) { + var Y, u2, m; + switch (V2) { + case 65504: + case 65505: + case 65506: + case 65507: + case 65508: + case 65509: + case 65510: + case 65511: + case 65512: + case 65513: + case 65514: + case 65515: + case 65516: + case 65517: + case 65518: + case 65519: + case 65534: + var j2 = G2(); + if (V2 === 65504) { + if (j2[0] === 74 && j2[1] === 70 && j2[2] === 73 && j2[3] === 70 && j2[4] === 0) { + a = { version: { d: j2[5], T: j2[6] }, K: j2[7], j: j2[8] << 8 | j2[9], H: j2[10] << 8 | j2[11], S: j2[12], I: j2[13], C: j2.subarray(14, 14 + 3 * j2[12] * j2[13]) }; + } + } + if (V2 === 65518) { + if (j2[0] === 65 && j2[1] === 100 && j2[2] === 111 && j2[3] === 98 && j2[4] === 101) { + C4 = { version: j2[5] << 8 | j2[6], k: j2[7] << 8 | j2[8], q: j2[9] << 8 | j2[10], a: j2[11] }; + } + } + break; + case 65499: + var v = Z2(Q2, E2), b; + E2 += 2; + var $2 = v + E2 - 2; + while (E2 < $2) { + var r = Q2[E2++], P = new Uint16Array(64); + if (r >> 4 === 0) { + for (u2 = 0;u2 < 64; u2++) { + b = p[u2]; + P[b] = Q2[E2++]; + } + } else if (r >> 4 === 1) { + for (u2 = 0;u2 < 64; u2++) { + b = p[u2]; + P[b] = Z2(Q2, E2); + E2 += 2; + } + } else { + throw new W("DQT - invalid table spec"); + } + U[r & 15] = P; + } + break; + case 65472: + case 65473: + case 65474: + if (F) { + throw new W("Only single frame JPEGs supported"); + } + E2 += 2; + F = {}; + F.G = V2 === 65473; + F.Z = V2 === 65474; + F.precision = Q2[E2++]; + var D = Z2(Q2, E2), a4, q2 = 0, H = 0; + E2 += 2; + F.s = f || D; + F.o = Z2(Q2, E2); + E2 += 2; + F.W = []; + F._ = {}; + var a8 = Q2[E2++]; + for (Y = 0;Y < a8; Y++) { + a4 = Q2[E2]; + var w = Q2[E2 + 1] >> 4, y = Q2[E2 + 1] & 15; + if (q2 < w) { + q2 = w; + } + if (H < y) { + H = y; + } + var X = Q2[E2 + 2]; + m = F.W.push({ h: w, A: y, L: X, $: null }); + F._[a4] = m - 1; + E2 += 3; + } + F.X = q2; + F.B = H; + n2(F); + break; + case 65476: + var O = Z2(Q2, E2); + E2 += 2; + for (Y = 2;Y < O; ) { + var _2 = Q2[E2++], N = new Uint8Array(16), e = 0; + for (u2 = 0;u2 < 16; u2++, E2++) { + e += N[u2] = Q2[E2]; + } + var K = new Uint8Array(e); + for (u2 = 0;u2 < e; u2++, E2++) { + K[u2] = Q2[E2]; + } + Y += 17 + e; + (_2 >> 4 === 0 ? J2 : z)[_2 & 15] = a5(N, K); + } + break; + case 65501: + E2 += 2; + d = Z2(Q2, E2); + E2 += 2; + break; + case 65498: + var x2 = ++T2 === 1 && !f, R2; + E2 += 2; + var k2 = Q2[E2++], g3 = []; + for (Y = 0;Y < k2; Y++) { + var c = Q2[E2++], L = F._[c]; + R2 = F.W[L]; + R2.index = c; + var a6 = Q2[E2++]; + R2.J = J2[a6 >> 4]; + R2.i = z[a6 & 15]; + g3.push(R2); + } + var I3 = Q2[E2++], l2 = Q2[E2++], M = Q2[E2++]; + try { + var S = a7(Q2, E2, F, g3, d, I3, l2, M >> 4, M & 15, x2); + E2 += S; + } catch (ex) { + if (ex instanceof DNLMarkerError) { + return this.parse(Q2, { F: ex.s }); + } else if (ex instanceof EOIMarkerError) { + break markerLoop; + } + throw ex; + } + break; + case 65500: + E2 += 4; + break; + case 65535: + if (Q2[E2] !== 255) { + E2--; + } + break; + default: + var i = an(Q2, E2 - 2, E2 - 3); + if (i && i.u) { + E2 = i.offset; + break; + } + if (E2 >= Q2.length - 1) { + break markerLoop; + } + throw new W("JpegImage.parse - unknown marker: " + V2.toString(16)); + } + V2 = Z2(Q2, E2); + E2 += 2; + } + this.width = F.o; + this.height = F.s; + this.g = a; + this.b = C4; + this.W = []; + for (Y = 0;Y < F.W.length; Y++) { + R2 = F.W[Y]; + var A2 = U[R2.L]; + if (A2) { + R2.$ = A2; + } + this.W.push({ index: R2.index, e: a0(F, R2), l: R2.h / F.X, t: R2.A / F.B, P: R2.P, c: R2.c }); + } + this.p = this.W.length; + return; + }, Y(Q2, h, f) { + if (f == null) + f = false; + var G2 = this.width / Q2, n2 = this.height / h, E2, a, C4, F, d, T2, U, z, J2, V2, Y = 0, u2, m = this.W.length, j2 = Q2 * h * m, v = new Uint8ClampedArray(j2), $2 = new Uint32Array(Q2), b = 4294967288, r; + for (U = 0;U < m; U++) { + E2 = this.W[U]; + a = E2.l * G2; + C4 = E2.t * n2; + Y = U; + u2 = E2.e; + F = E2.P + 1 << 3; + if (a !== r) { + for (d = 0;d < Q2; d++) { + z = 0 | d * a; + $2[d] = (z & b) << 3 | z & 7; + } + r = a; + } + for (T2 = 0;T2 < h; T2++) { + z = 0 | T2 * C4; + V2 = F * (z & b) | (z & 7) << 3; + for (d = 0;d < Q2; d++) { + v[Y] = u2[V2 + $2[d]]; + Y += m; + } + } + } + var P = this.V; + if (!f && m === 4 && !P) { + P = new Int32Array([-256, 255, -256, 255, -256, 255, -256, 255]); + } + if (P) { + for (U = 0;U < j2; ) { + for (z = 0, J2 = 0;z < m; z++, U++, J2 += 2) { + v[U] = (v[U] * P[J2] >> 8) + P[J2 + 1]; + } + } + } + return v; + }, get f() { + if (this.b) { + return !!this.b.a; + } + if (this.p === 3) { + if (this.N === 0) { + return false; + } else if (this.W[0].index === 82 && this.W[1].index === 71 && this.W[2].index === 66) { + return false; + } + return true; + } + if (this.N === 1) { + return true; + } + return false; + }, z: function aj(Q2) { + var h, f, G2; + for (var n2 = 0, E2 = Q2.length;n2 < E2; n2 += 3) { + h = Q2[n2]; + f = Q2[n2 + 1]; + G2 = Q2[n2 + 2]; + Q2[n2] = h - 179.456 + 1.402 * G2; + Q2[n2 + 1] = h + 135.459 - 0.344 * f - 0.714 * G2; + Q2[n2 + 2] = h - 226.816 + 1.772 * f; + } + return Q2; + }, O: function aa(Q2) { + var h, f, G2, n2, E2 = 0; + for (var a = 0, C4 = Q2.length;a < C4; a += 4) { + h = Q2[a]; + f = Q2[a + 1]; + G2 = Q2[a + 2]; + n2 = Q2[a + 3]; + Q2[E2++] = -122.67195406894 + f * (-0.0000660635669420364 * f + 0.000437130475926232 * G2 - 0.000054080610064599 * h + 0.00048449797120281 * n2 - 0.154362151871126) + G2 * (-0.000957964378445773 * G2 + 0.000817076911346625 * h - 0.00477271405408747 * n2 + 1.53380253221734) + h * (0.000961250184130688 * h - 0.00266257332283933 * n2 + 0.48357088451265) + n2 * (-0.000336197177618394 * n2 + 0.484791561490776); + Q2[E2++] = 107.268039397724 + f * (0.0000219927104525741 * f - 0.000640992018297945 * G2 + 0.000659397001245577 * h + 0.000426105652938837 * n2 - 0.176491792462875) + G2 * (-0.000778269941513683 * G2 + 0.00130872261408275 * h + 0.000770482631801132 * n2 - 0.151051492775562) + h * (0.00126935368114843 * h - 0.00265090189010898 * n2 + 0.25802910206845) + n2 * (-0.000318913117588328 * n2 - 0.213742400323665); + Q2[E2++] = -20.810012546947 + f * (-0.000570115196973677 * f - 0.0000263409051004589 * G2 + 0.0020741088115012 * h - 0.00288260236853442 * n2 + 0.814272968359295) + G2 * (-0.0000153496057440975 * G2 - 0.000132689043961446 * h + 0.000560833691242812 * n2 - 0.195152027534049) + h * (0.00174418132927582 * h - 0.00255243321439347 * n2 + 0.116935020465145) + n2 * (-0.000343531996510555 * n2 + 0.24165260232407); + } + return Q2.subarray(0, E2); + }, r: function a3(Q2) { + var h, f, G2; + for (var n2 = 0, E2 = Q2.length;n2 < E2; n2 += 4) { + h = Q2[n2]; + f = Q2[n2 + 1]; + G2 = Q2[n2 + 2]; + Q2[n2] = 434.456 - h - 1.402 * G2; + Q2[n2 + 1] = 119.541 - h + 0.344 * f + 0.714 * G2; + Q2[n2 + 2] = 481.816 - h - 1.772 * f; + } + return Q2; + }, U: function as(Q2) { + var h, f, G2, n2, E2 = 0; + for (var a = 0, C4 = Q2.length;a < C4; a += 4) { + h = Q2[a]; + f = Q2[a + 1]; + G2 = Q2[a + 2]; + n2 = Q2[a + 3]; + Q2[E2++] = 255 + h * (-0.00006747147073602441 * h + 0.0008379262121013727 * f + 0.0002894718188643294 * G2 + 0.003264231057537806 * n2 - 1.1185611867203937) + f * (0.000026374107616089405 * f - 0.00008626949158638572 * G2 - 0.0002748769067499491 * n2 - 0.02155688794978967) + G2 * (-0.00003878099212869363 * G2 - 0.0003267808279485286 * n2 + 0.0686742238595345) - n2 * (0.0003361971776183937 * n2 + 0.7430659151342254); + Q2[E2++] = 255 + h * (0.00013596372813588848 * h + 0.000924537132573585 * f + 0.00010567359618683593 * G2 + 0.0004791864687436512 * n2 - 0.3109689587515875) + f * (-0.00023545346108370344 * f + 0.0002702845253534714 * G2 + 0.0020200308977307156 * n2 - 0.7488052167015494) + G2 * (0.00006834815998235662 * G2 + 0.00015168452363460973 * n2 - 0.09751927774728933) - n2 * (0.0003189131175883281 * n2 + 0.7364883807733168); + Q2[E2++] = 255 + h * (0.000013598650411385307 * h + 0.00012423956175490851 * f + 0.0004751985097583589 * G2 - 0.0000036729317476630422 * n2 - 0.05562186980264034) + f * (0.00016141380598724676 * f + 0.0009692239130725186 * G2 + 0.0007782692450036253 * n2 - 0.44015232367526463) + G2 * (0.0000005068882914068769 * G2 + 0.0017778369011375071 * n2 - 0.7591454649749609) - n2 * (0.0003435319965105553 * n2 + 0.7063770186160144); + } + return Q2.subarray(0, E2); + }, getData: function(Q2) { + var { width: h, height: f, forceRGB: G2, isSourcePDF: n2 } = Q2; + if (this.p > 4) { + throw new W("Unsupported color mode"); + } + var E2 = this.Y(h, f, n2); + if (this.p === 1 && G2) { + var a = E2.length, C4 = new Uint8ClampedArray(a * 3), F = 0; + for (var d = 0;d < a; d++) { + var T2 = E2[d]; + C4[F++] = T2; + C4[F++] = T2; + C4[F++] = T2; + } + return C4; + } else if (this.p === 3 && this.f) { + return this.z(E2); + } else if (this.p === 4) { + if (this.f) { + if (G2) { + return this.O(E2); + } + return this.r(E2); + } else if (G2) { + return this.U(E2); + } + } + return E2; + } }; + return ak2; + }(); + function a9(p, t2) { + return p[t2] << 24 >> 24; + } + function Z2(p, t2) { + return p[t2] << 8 | p[t2 + 1]; + } + function am(p, t2) { + return (p[t2] << 24 | p[t2 + 1] << 16 | p[t2 + 2] << 8 | p[t2 + 3]) >>> 0; + } + UTIF.JpegDecoder = ak; +})(); +UTIF.encodeImage = function(rgba, w, h, metadata) { + var idf = { + t256: [w], + t257: [h], + t258: [8, 8, 8, 8], + t259: [1], + t262: [2], + t273: [1000], + t277: [4], + t278: [h], + t279: [w * h * 4], + t282: [[72, 1]], + t283: [[72, 1]], + t284: [1], + t286: [[0, 1]], + t287: [[0, 1]], + t296: [1], + t305: ["Photopea (UTIF.js)"], + t338: [1] + }; + if (metadata) + for (var i in metadata) + idf[i] = metadata[i]; + var prfx = new Uint8Array(UTIF.encode([idf])); + var img = new Uint8Array(rgba); + var data2 = new Uint8Array(1000 + w * h * 4); + for (var i = 0;i < prfx.length; i++) + data2[i] = prfx[i]; + for (var i = 0;i < img.length; i++) + data2[1000 + i] = img[i]; + return data2.buffer; +}; +UTIF.encode = function(ifds) { + var LE = false; + var data2 = new Uint8Array(20000), offset = 4, bin = LE ? UTIF._binLE : UTIF._binBE; + data2[0] = data2[1] = LE ? 73 : 77; + bin.writeUshort(data2, 2, 42); + var ifdo = 8; + bin.writeUint(data2, offset, ifdo); + offset += 4; + for (var i = 0;i < ifds.length; i++) { + var noffs = UTIF._writeIFD(bin, UTIF._types.basic, data2, ifdo, ifds[i]); + ifdo = noffs[1]; + if (i < ifds.length - 1) { + if ((ifdo & 3) != 0) + ifdo += 4 - (ifdo & 3); + bin.writeUint(data2, noffs[0], ifdo); + } + } + return data2.slice(0, ifdo).buffer; +}; +UTIF.decode = function(buff, prm) { + if (prm == null) + prm = { parseMN: true, debug: false }; + var data2 = new Uint8Array(buff), offset = 0; + var id = UTIF._binBE.readASCII(data2, offset, 2); + offset += 2; + var bin = id == "II" ? UTIF._binLE : UTIF._binBE; + var num = bin.readUshort(data2, offset); + offset += 2; + var ifdo = bin.readUint(data2, offset); + offset += 4; + var ifds = []; + while (true) { + var cnt = bin.readUshort(data2, ifdo), typ = bin.readUshort(data2, ifdo + 4); + if (cnt != 0) { + if (typ < 1 || 13 < typ) { + log("error in TIFF"); + break; + } + } + UTIF._readIFD(bin, data2, ifdo, ifds, 0, prm); + ifdo = bin.readUint(data2, ifdo + 2 + cnt * 12); + if (ifdo == 0) + break; + } + return ifds; +}; +UTIF.decodeImage = function(buff, img, ifds) { + if (img.data) + return; + var data2 = new Uint8Array(buff); + var id = UTIF._binBE.readASCII(data2, 0, 2); + if (img["t256"] == null) + return; + img.isLE = id == "II"; + img.width = img["t256"][0]; + img.height = img["t257"][0]; + var cmpr = img["t259"] ? img["t259"][0] : 1; + var fo = img["t266"] ? img["t266"][0] : 1; + if (img["t284"] && img["t284"][0] == 2) + log("PlanarConfiguration 2 should not be used!"); + if (cmpr == 7 && img["t258"] && img["t258"].length > 3) + img["t258"] = img["t258"].slice(0, 3); + var spp = img["t277"] ? img["t277"][0] : 1; + var bps = img["t258"] ? img["t258"][0] : 1; + var bipp = bps * spp; + if (cmpr == 1 && img["t279"] != null && img["t278"] && img["t262"][0] == 32803) { + bipp = Math.round(img["t279"][0] * 8 / (img.width * img["t278"][0])); + } + if (img["t50885"] && img["t50885"][0] == 4) + bipp = img["t258"][0] * 3; + var bipl = Math.ceil(img.width * bipp / 8) * 8; + var soff = img["t273"]; + if (soff == null || img["t322"]) + soff = img["t324"]; + var bcnt = img["t279"]; + if (cmpr == 1 && soff.length == 1) + bcnt = [img.height * (bipl >>> 3)]; + if (bcnt == null || img["t322"]) + bcnt = img["t325"]; + var bytes = new Uint8Array(img.height * (bipl >>> 3)), bilen = 0; + if (img["t322"] != null) { + var tw = img["t322"][0], th = img["t323"][0]; + var tx = Math.floor((img.width + tw - 1) / tw); + var ty = Math.floor((img.height + th - 1) / th); + var tbuff = new Uint8Array(Math.ceil(tw * th * bipp / 8) | 0); + console.log("====", tx, ty); + for (var y = 0;y < ty; y++) + for (var x2 = 0;x2 < tx; x2++) { + var i = y * tx + x2; + tbuff.fill(0); + UTIF.decode._decompress(img, ifds, data2, soff[i], bcnt[i], cmpr, tbuff, 0, fo, tw, th); + if (cmpr == 6) + bytes = tbuff; + else + UTIF._copyTile(tbuff, Math.ceil(tw * bipp / 8) | 0, th, bytes, Math.ceil(img.width * bipp / 8) | 0, img.height, Math.ceil(x2 * tw * bipp / 8) | 0, y * th); + } + bilen = bytes.length * 8; + } else { + if (soff == null) + return; + var rps = img["t278"] ? img["t278"][0] : img.height; + rps = Math.min(rps, img.height); + for (var i = 0;i < soff.length; i++) { + UTIF.decode._decompress(img, ifds, data2, soff[i], bcnt[i], cmpr, bytes, Math.ceil(bilen / 8) | 0, fo, img.width, rps); + bilen += bipl * rps; + } + bilen = Math.min(bilen, bytes.length * 8); + } + img.data = new Uint8Array(bytes.buffer, 0, Math.ceil(bilen / 8) | 0); +}; +UTIF.decode._decompress = function(img, ifds, data2, off, len, cmpr, tgt, toff, fo, w, h) { + if (img["t271"] && img["t271"][0] == "Panasonic" && img["t45"] && img["t45"][0] == 6) + cmpr = 34316; + if (false) { + } else if (cmpr == 1) + for (var j2 = 0;j2 < len; j2++) + tgt[toff + j2] = data2[off + j2]; + else if (cmpr == 2) + UTIF.decode._decodeG2(data2, off, len, tgt, toff, w, fo); + else if (cmpr == 3) + UTIF.decode._decodeG3(data2, off, len, tgt, toff, w, fo, img["t292"] ? (img["t292"][0] & 1) == 1 : false); + else if (cmpr == 4) + UTIF.decode._decodeG4(data2, off, len, tgt, toff, w, fo); + else if (cmpr == 5) + UTIF.decode._decodeLZW(data2, off, len, tgt, toff, 8); + else if (cmpr == 6) + UTIF.decode._decodeOldJPEG(img, data2, off, len, tgt, toff); + else if (cmpr == 7 || cmpr == 34892) + UTIF.decode._decodeNewJPEG(img, data2, off, len, tgt, toff); + else if (cmpr == 8 || cmpr == 32946) { + var src = new Uint8Array(data2.buffer, off + 2, len - 6); + var bin = UTIF._inflateRaw(src); + if (toff + bin.length <= tgt.length) + tgt.set(bin, toff); + } else if (cmpr == 9) + UTIF.decode._decodeVC5(data2, off, len, tgt, toff, img["t33422"]); + else if (cmpr == 32767) + UTIF.decode._decodeARW(img, data2, off, len, tgt, toff); + else if (cmpr == 32773) + UTIF.decode._decodePackBits(data2, off, len, tgt, toff); + else if (cmpr == 32809) + UTIF.decode._decodeThunder(data2, off, len, tgt, toff); + else if (cmpr == 34316) + UTIF.decode._decodePanasonic(img, data2, off, len, tgt, toff); + else if (cmpr == 34713) + UTIF.decode._decodeNikon(img, ifds, data2, off, len, tgt, toff); + else if (cmpr == 34676) + UTIF.decode._decodeLogLuv32(img, data2, off, len, tgt, toff); + else + log("Unknown compression", cmpr); + var bps = img["t258"] ? Math.min(32, img["t258"][0]) : 1; + var noc = img["t277"] ? img["t277"][0] : 1, bpp = bps * noc >>> 3, bpl = Math.ceil(bps * noc * w / 8); + if (bps == 16 && !img.isLE && img["t33422"] == null) + for (var y = 0;y < h; y++) { + var roff = toff + y * bpl; + for (var x2 = 1;x2 < bpl; x2 += 2) { + var t2 = tgt[roff + x2]; + tgt[roff + x2] = tgt[roff + x2 - 1]; + tgt[roff + x2 - 1] = t2; + } + } + if (img["t317"] && img["t317"][0] == 2) { + for (var y = 0;y < h; y++) { + var ntoff = toff + y * bpl; + if (bps == 16) + for (var j2 = bpp;j2 < bpl; j2 += 2) { + var nv = (tgt[ntoff + j2 + 1] << 8 | tgt[ntoff + j2]) + (tgt[ntoff + j2 - bpp + 1] << 8 | tgt[ntoff + j2 - bpp]); + tgt[ntoff + j2] = nv & 255; + tgt[ntoff + j2 + 1] = nv >>> 8 & 255; + } + else if (noc == 3) + for (var j2 = 3;j2 < bpl; j2 += 3) { + tgt[ntoff + j2] = tgt[ntoff + j2] + tgt[ntoff + j2 - 3] & 255; + tgt[ntoff + j2 + 1] = tgt[ntoff + j2 + 1] + tgt[ntoff + j2 - 2] & 255; + tgt[ntoff + j2 + 2] = tgt[ntoff + j2 + 2] + tgt[ntoff + j2 - 1] & 255; + } + else + for (var j2 = bpp;j2 < bpl; j2++) + tgt[ntoff + j2] = tgt[ntoff + j2] + tgt[ntoff + j2 - bpp] & 255; + } + } +}; +UTIF.decode._decodePanasonic = function(img, data2, off, len, tgt, toff) { + var img_buffer = data2.buffer; + var rawWidth = img["t2"][0]; + var rawHeight = img["t3"][0]; + var bitsPerSample = img["t10"][0]; + var RW2_Format = img["t45"][0]; + var bidx = 0; + var imageIndex = 0; + var vpos = 0; + var byte = 0; + var arr_a, arr_b; + var bytes = RW2_Format == 6 ? new Uint32Array(18) : new Uint8Array(16); + var i, j2, sh, pred = [0, 0], nonz = [0, 0], isOdd, idx = 0, pixel_base; + var row, col, crow; + var buffer = new Uint8Array(16384); + var result = new Uint16Array(tgt.buffer); + function getDataRaw(bits) { + if (vpos == 0) { + var arr_a2 = new Uint8Array(img_buffer, off + imageIndex + 8184, 16384 - 8184); + var arr_b2 = new Uint8Array(img_buffer, off + imageIndex, 8184); + buffer.set(arr_a2); + buffer.set(arr_b2, arr_a2.length); + imageIndex += 16384; + } + if (RW2_Format == 5) { + for (i = 0;i < 16; i++) { + bytes[i] = buffer[vpos++]; + vpos &= 16383; + } + } else { + vpos = vpos - bits & 131071; + byte = vpos >> 3 ^ 16368; + return (buffer[byte] | buffer[byte + 1] << 8) >> (vpos & 7) & ~(-1 << bits); + } + } + function getBufferDataRW6(i2) { + return buffer[vpos + 15 - i2]; + } + function readPageRW6() { + bytes[0] = getBufferDataRW6(0) << 6 | getBufferDataRW6(1) >> 2; + bytes[1] = ((getBufferDataRW6(1) & 3) << 12 | getBufferDataRW6(2) << 4 | getBufferDataRW6(3) >> 4) & 16383; + bytes[2] = getBufferDataRW6(3) >> 2 & 3; + bytes[3] = (getBufferDataRW6(3) & 3) << 8 | getBufferDataRW6(4); + bytes[4] = getBufferDataRW6(5) << 2 | getBufferDataRW6(6) >> 6; + bytes[5] = (getBufferDataRW6(6) & 63) << 4 | getBufferDataRW6(7) >> 4; + bytes[6] = getBufferDataRW6(7) >> 2 & 3; + bytes[7] = (getBufferDataRW6(7) & 3) << 8 | getBufferDataRW6(8); + bytes[8] = getBufferDataRW6(9) << 2 & 1020 | getBufferDataRW6(10) >> 6; + bytes[9] = (getBufferDataRW6(10) << 4 | getBufferDataRW6(11) >> 4) & 1023; + bytes[10] = getBufferDataRW6(11) >> 2 & 3; + bytes[11] = (getBufferDataRW6(11) & 3) << 8 | getBufferDataRW6(12); + bytes[12] = (getBufferDataRW6(13) << 2 & 1020 | getBufferDataRW6(14) >> 6) & 1023; + bytes[13] = (getBufferDataRW6(14) << 4 | getBufferDataRW6(15) >> 4) & 1023; + vpos += 16; + byte = 0; + } + function readPageRw6_bps12() { + bytes[0] = getBufferDataRW6(0) << 4 | getBufferDataRW6(1) >> 4; + bytes[1] = ((getBufferDataRW6(1) & 15) << 8 | getBufferDataRW6(2)) & 4095; + bytes[2] = getBufferDataRW6(3) >> 6 & 3; + bytes[3] = (getBufferDataRW6(3) & 63) << 2 | getBufferDataRW6(4) >> 6; + bytes[4] = (getBufferDataRW6(4) & 63) << 2 | getBufferDataRW6(5) >> 6; + bytes[5] = (getBufferDataRW6(5) & 63) << 2 | getBufferDataRW6(6) >> 6; + bytes[6] = getBufferDataRW6(6) >> 4 & 3; + bytes[7] = (getBufferDataRW6(6) & 15) << 4 | getBufferDataRW6(7) >> 4; + bytes[8] = (getBufferDataRW6(7) & 15) << 4 | getBufferDataRW6(8) >> 4; + bytes[9] = (getBufferDataRW6(8) & 15) << 4 | getBufferDataRW6(9) >> 4; + bytes[10] = getBufferDataRW6(9) >> 2 & 3; + bytes[11] = (getBufferDataRW6(9) & 3) << 6 | getBufferDataRW6(10) >> 2; + bytes[12] = (getBufferDataRW6(10) & 3) << 6 | getBufferDataRW6(11) >> 2; + bytes[13] = (getBufferDataRW6(11) & 3) << 6 | getBufferDataRW6(12) >> 2; + bytes[14] = getBufferDataRW6(12) & 3; + bytes[15] = getBufferDataRW6(13); + bytes[16] = getBufferDataRW6(14); + bytes[17] = getBufferDataRW6(15); + vpos += 16; + byte = 0; + } + function resetPredNonzeros() { + pred[0] = 0; + pred[1] = 0; + nonz[0] = 0; + nonz[1] = 0; + } + if (RW2_Format == 7) { + throw RW2_Format; + } else if (RW2_Format == 6) { + var is12bit = bitsPerSample == 12, readPageRw6Fn = is12bit ? readPageRw6_bps12 : readPageRW6, pixelsPerBlock = is12bit ? 14 : 11, pixelbase0 = is12bit ? 128 : 512, pixelbase_compare = is12bit ? 2048 : 8192, spix_compare = is12bit ? 16383 : 65535, pixel_mask = is12bit ? 4095 : 16383, blocksperrow = rawWidth / pixelsPerBlock, rowbytes = blocksperrow * 16, bufferSize = is12bit ? 18 : 14; + for (row = 0;row < rawHeight - 15; row += 16) { + var rowstoread = Math.min(16, rawHeight - row); + var readlen = rowbytes * rowstoread; + buffer = new Uint8Array(img_buffer, off + bidx, readlen); + vpos = 0; + bidx += readlen; + for (crow = 0, col = 0;crow < rowstoread; crow++, col = 0) { + idx = (row + crow) * rawWidth; + for (var rblock = 0;rblock < blocksperrow; rblock++) { + readPageRw6Fn(); + resetPredNonzeros(); + sh = 0; + pixel_base = 0; + for (i = 0;i < pixelsPerBlock; i++) { + isOdd = i & 1; + if (i % 3 == 2) { + var base = byte < bufferSize ? bytes[byte++] : 0; + if (base == 3) + base = 4; + pixel_base = pixelbase0 << base; + sh = 1 << base; + } + var epixel = byte < bufferSize ? bytes[byte++] : 0; + if (pred[isOdd]) { + epixel *= sh; + if (pixel_base < pixelbase_compare && nonz[isOdd] > pixel_base) + epixel += nonz[isOdd] - pixel_base; + nonz[isOdd] = epixel; + } else { + pred[isOdd] = epixel; + if (epixel) + nonz[isOdd] = epixel; + else + epixel = nonz[isOdd]; + } + result[idx + col++] = epixel - 15 <= spix_compare ? epixel - 15 & spix_compare : epixel + 2147483633 >> 31 & pixel_mask; + } + } + } + } + } else if (RW2_Format == 5) { + var blockSize = bitsPerSample == 12 ? 10 : 9; + for (row = 0;row < rawHeight; row++) { + for (col = 0;col < rawWidth; col += blockSize) { + getDataRaw(0); + if (bitsPerSample == 12) { + result[idx++] = ((bytes[1] & 15) << 8) + bytes[0]; + result[idx++] = 16 * bytes[2] + (bytes[1] >> 4); + result[idx++] = ((bytes[4] & 15) << 8) + bytes[3]; + result[idx++] = 16 * bytes[5] + (bytes[4] >> 4); + result[idx++] = ((bytes[7] & 15) << 8) + bytes[6]; + result[idx++] = 16 * bytes[8] + (bytes[7] >> 4); + result[idx++] = ((bytes[10] & 15) << 8) + bytes[9]; + result[idx++] = 16 * bytes[11] + (bytes[10] >> 4); + result[idx++] = ((bytes[13] & 15) << 8) + bytes[12]; + result[idx++] = 16 * bytes[14] + (bytes[13] >> 4); + } else if (bitsPerSample == 14) { + result[idx++] = bytes[0] + ((bytes[1] & 63) << 8); + result[idx++] = (bytes[1] >> 6) + 4 * bytes[2] + ((bytes[3] & 15) << 10); + result[idx++] = (bytes[3] >> 4) + 16 * bytes[4] + ((bytes[5] & 3) << 12); + result[idx++] = ((bytes[5] & 252) >> 2) + (bytes[6] << 6); + result[idx++] = bytes[7] + ((bytes[8] & 63) << 8); + result[idx++] = (bytes[8] >> 6) + 4 * bytes[9] + ((bytes[10] & 15) << 10); + result[idx++] = (bytes[10] >> 4) + 16 * bytes[11] + ((bytes[12] & 3) << 12); + result[idx++] = ((bytes[12] & 252) >> 2) + (bytes[13] << 6); + result[idx++] = bytes[14] + ((bytes[15] & 63) << 8); + } + } + } + } else if (RW2_Format == 4) { + for (row = 0;row < rawHeight; row++) { + for (col = 0;col < rawWidth; col++) { + i = col % 14; + isOdd = i & 1; + if (i == 0) + resetPredNonzeros(); + if (i % 3 == 2) + sh = 4 >> 3 - getDataRaw(2); + if (nonz[isOdd]) { + j2 = getDataRaw(8); + if (j2 != 0) { + pred[isOdd] -= 128 << sh; + if (pred[isOdd] < 0 || sh == 4) + pred[isOdd] &= ~(-1 << sh); + pred[isOdd] += j2 << sh; + } + } else { + nonz[isOdd] = getDataRaw(8); + if (nonz[isOdd] || i > 11) + pred[isOdd] = nonz[isOdd] << 4 | getDataRaw(4); + } + result[idx++] = pred[col & 1]; + } + } + } else + throw RW2_Format; +}; +UTIF.decode._decodeVC5 = function() { + var x2 = [1, 0, 1, 0, 2, 2, 1, 1, 3, 7, 1, 2, 5, 25, 1, 3, 6, 48, 1, 4, 6, 54, 1, 5, 7, 111, 1, 8, 7, 99, 1, 6, 7, 105, 12, 0, 7, 107, 1, 7, 8, 209, 20, 0, 8, 212, 1, 9, 8, 220, 1, 10, 9, 393, 1, 11, 9, 394, 32, 0, 9, 416, 1, 12, 9, 427, 1, 13, 10, 887, 1, 18, 10, 784, 1, 14, 10, 790, 1, 15, 10, 835, 60, 0, 10, 852, 1, 16, 10, 885, 1, 17, 11, 1571, 1, 19, 11, 1668, 1, 20, 11, 1669, 100, 0, 11, 1707, 1, 21, 11, 1772, 1, 22, 12, 3547, 1, 29, 12, 3164, 1, 24, 12, 3166, 1, 25, 12, 3140, 1, 23, 12, 3413, 1, 26, 12, 3537, 1, 27, 12, 3539, 1, 28, 13, 7093, 1, 35, 13, 6283, 1, 30, 13, 6331, 1, 31, 13, 6335, 180, 0, 13, 6824, 1, 32, 13, 7072, 1, 33, 13, 7077, 320, 0, 13, 7076, 1, 34, 14, 12565, 1, 36, 14, 12661, 1, 37, 14, 12669, 1, 38, 14, 13651, 1, 39, 14, 14184, 1, 40, 15, 28295, 1, 46, 15, 28371, 1, 47, 15, 25320, 1, 42, 15, 25336, 1, 43, 15, 25128, 1, 41, 15, 27300, 1, 44, 15, 28293, 1, 45, 16, 50259, 1, 48, 16, 50643, 1, 49, 16, 50675, 1, 50, 16, 56740, 1, 53, 16, 56584, 1, 51, 16, 56588, 1, 52, 17, 113483, 1, 61, 17, 113482, 1, 60, 17, 101285, 1, 55, 17, 101349, 1, 56, 17, 109205, 1, 57, 17, 109207, 1, 58, 17, 100516, 1, 54, 17, 113171, 1, 59, 18, 202568, 1, 62, 18, 202696, 1, 63, 18, 218408, 1, 64, 18, 218412, 1, 65, 18, 226340, 1, 66, 18, 226356, 1, 67, 18, 226358, 1, 68, 19, 402068, 1, 69, 19, 405138, 1, 70, 19, 405394, 1, 71, 19, 436818, 1, 72, 19, 436826, 1, 73, 19, 452714, 1, 75, 19, 452718, 1, 76, 19, 452682, 1, 74, 20, 804138, 1, 77, 20, 810279, 1, 78, 20, 810790, 1, 79, 20, 873638, 1, 80, 20, 873654, 1, 81, 20, 905366, 1, 82, 20, 905430, 1, 83, 20, 905438, 1, 84, 21, 1608278, 1, 85, 21, 1620557, 1, 86, 21, 1621582, 1, 87, 21, 1621583, 1, 88, 21, 1747310, 1, 89, 21, 1810734, 1, 90, 21, 1810735, 1, 91, 21, 1810863, 1, 92, 21, 1810879, 1, 93, 22, 3621725, 1, 99, 22, 3621757, 1, 100, 22, 3241112, 1, 94, 22, 3494556, 1, 95, 22, 3494557, 1, 96, 22, 3494622, 1, 97, 22, 3494623, 1, 98, 23, 6482227, 1, 102, 23, 6433117, 1, 101, 23, 6989117, 1, 103, 23, 6989119, 1, 105, 23, 6989118, 1, 104, 23, 7243449, 1, 106, 23, 7243512, 1, 107, 24, 13978233, 1, 111, 24, 12964453, 1, 109, 24, 12866232, 1, 108, 24, 14486897, 1, 113, 24, 13978232, 1, 110, 24, 14486896, 1, 112, 24, 14487026, 1, 114, 24, 14487027, 1, 115, 25, 25732598, 1, 225, 25, 25732597, 1, 189, 25, 25732596, 1, 188, 25, 25732595, 1, 203, 25, 25732594, 1, 202, 25, 25732593, 1, 197, 25, 25732592, 1, 207, 25, 25732591, 1, 169, 25, 25732590, 1, 223, 25, 25732589, 1, 159, 25, 25732522, 1, 235, 25, 25732579, 1, 152, 25, 25732575, 1, 192, 25, 25732489, 1, 179, 25, 25732573, 1, 201, 25, 25732472, 1, 172, 25, 25732576, 1, 149, 25, 25732488, 1, 178, 25, 25732566, 1, 120, 25, 25732571, 1, 219, 25, 25732577, 1, 150, 25, 25732487, 1, 127, 25, 25732506, 1, 211, 25, 25732548, 1, 125, 25, 25732588, 1, 158, 25, 25732486, 1, 247, 25, 25732467, 1, 238, 25, 25732508, 1, 163, 25, 25732552, 1, 228, 25, 25732603, 1, 183, 25, 25732513, 1, 217, 25, 25732587, 1, 168, 25, 25732520, 1, 122, 25, 25732484, 1, 128, 25, 25732562, 1, 249, 25, 25732505, 1, 187, 25, 25732504, 1, 186, 25, 25732483, 1, 136, 25, 25928905, 1, 181, 25, 25732560, 1, 255, 25, 25732500, 1, 230, 25, 25732482, 1, 135, 25, 25732555, 1, 233, 25, 25732568, 1, 222, 25, 25732583, 1, 145, 25, 25732481, 1, 134, 25, 25732586, 1, 167, 25, 25732521, 1, 248, 25, 25732518, 1, 209, 25, 25732480, 1, 243, 25, 25732512, 1, 216, 25, 25732509, 1, 164, 25, 25732547, 1, 140, 25, 25732479, 1, 157, 25, 25732544, 1, 239, 25, 25732574, 1, 191, 25, 25732564, 1, 251, 25, 25732478, 1, 156, 25, 25732546, 1, 139, 25, 25732498, 1, 242, 25, 25732557, 1, 133, 25, 25732477, 1, 162, 25, 25732515, 1, 213, 25, 25732584, 1, 165, 25, 25732514, 1, 212, 25, 25732476, 1, 227, 25, 25732494, 1, 198, 25, 25732531, 1, 236, 25, 25732530, 1, 234, 25, 25732529, 1, 117, 25, 25732528, 1, 215, 25, 25732527, 1, 124, 25, 25732526, 1, 123, 25, 25732525, 1, 254, 25, 25732524, 1, 253, 25, 25732523, 1, 148, 25, 25732570, 1, 218, 25, 25732580, 1, 146, 25, 25732581, 1, 147, 25, 25732569, 1, 224, 25, 25732533, 1, 143, 25, 25732540, 1, 184, 25, 25732541, 1, 185, 25, 25732585, 1, 166, 25, 25732556, 1, 132, 25, 25732485, 1, 129, 25, 25732563, 1, 250, 25, 25732578, 1, 151, 25, 25732501, 1, 119, 25, 25732502, 1, 193, 25, 25732536, 1, 176, 25, 25732496, 1, 245, 25, 25732553, 1, 229, 25, 25732516, 1, 206, 25, 25732582, 1, 144, 25, 25732517, 1, 208, 25, 25732558, 1, 137, 25, 25732543, 1, 241, 25, 25732466, 1, 237, 25, 25732507, 1, 190, 25, 25732542, 1, 240, 25, 25732551, 1, 131, 25, 25732554, 1, 232, 25, 25732565, 1, 252, 25, 25732475, 1, 171, 25, 25732493, 1, 205, 25, 25732492, 1, 204, 25, 25732491, 1, 118, 25, 25732490, 1, 214, 25, 25928904, 1, 180, 25, 25732549, 1, 126, 25, 25732602, 1, 182, 25, 25732539, 1, 175, 25, 25732545, 1, 141, 25, 25732559, 1, 138, 25, 25732537, 1, 177, 25, 25732534, 1, 153, 25, 25732503, 1, 194, 25, 25732606, 1, 160, 25, 25732567, 1, 121, 25, 25732538, 1, 174, 25, 25732497, 1, 246, 25, 25732550, 1, 130, 25, 25732572, 1, 200, 25, 25732474, 1, 170, 25, 25732511, 1, 221, 25, 25732601, 1, 196, 25, 25732532, 1, 142, 25, 25732519, 1, 210, 25, 25732495, 1, 199, 25, 25732605, 1, 155, 25, 25732535, 1, 154, 25, 25732499, 1, 244, 25, 25732510, 1, 220, 25, 25732600, 1, 195, 25, 25732607, 1, 161, 25, 25732604, 1, 231, 25, 25732473, 1, 173, 25, 25732599, 1, 226, 26, 51465122, 1, 116, 26, 51465123, 0, 1], o, C4, k2, P = [3, 3, 3, 3, 2, 2, 2, 1, 1, 1], V2 = 24576, ar = 16384, H = 8192, az = ar | H; + function d(t2) { + var E2 = t2[1], h = t2[0][E2 >>> 3] >>> 7 - (E2 & 7) & 1; + t2[1]++; + return h; + } + function ag(t2, E2) { + if (o == null) { + o = {}; + for (var h = 0;h < x2.length; h += 4) + o[x2[h + 1]] = x2.slice(h, h + 4); + } + var L = d(t2), g3 = o[L]; + while (g3 == null) { + L = L << 1 | d(t2); + g3 = o[L]; + } + var n2 = g3[3]; + if (n2 != 0) + n2 = d(t2) == 0 ? n2 : -n2; + E2[0] = g3[2]; + E2[1] = n2; + } + function m(t2, E2) { + for (var h = 0;h < E2; h++) { + if ((t2 & 1) == 1) + t2++; + t2 = t2 >>> 1; + } + return t2; + } + function A2(t2, E2) { + return t2 >> E2; + } + function O(t2, E2, h, L, g3, n2) { + E2[h] = A2(A2(11 * t2[g3] - 4 * t2[g3 + n2] + t2[g3 + n2 + n2] + 4, 3) + t2[L], 1); + E2[h + n2] = A2(A2(5 * t2[g3] + 4 * t2[g3 + n2] - t2[g3 + n2 + n2] + 4, 3) - t2[L], 1); + } + function J2(t2, E2, h, L, g3, n2) { + var W = t2[g3 - n2] - t2[g3 + n2], j2 = t2[g3], $2 = t2[L]; + E2[h] = A2(A2(W + 4, 3) + j2 + $2, 1); + E2[h + n2] = A2(A2(-W + 4, 3) + j2 - $2, 1); + } + function y(t2, E2, h, L, g3, n2) { + E2[h] = A2(A2(5 * t2[g3] + 4 * t2[g3 - n2] - t2[g3 - n2 - n2] + 4, 3) + t2[L], 1); + E2[h + n2] = A2(A2(11 * t2[g3] - 4 * t2[g3 - n2] + t2[g3 - n2 - n2] + 4, 3) - t2[L], 1); + } + function q2(t2) { + t2 = t2 < 0 ? 0 : t2 > 4095 ? 4095 : t2; + t2 = k2[t2] >>> 2; + return t2; + } + function av(t2, E2, h, L, g3, n2) { + L = new Uint16Array(L.buffer); + var W = Date.now(), j2 = UTIF._binBE, $2 = E2 + h, r, u2, X, I3, ax, a3, R2, ai, aa, ap, ah, ae3, aD, al2, i, aE, T2, B2; + E2 += 4; + var a5 = n2[0] == 1; + while (E2 < $2) { + var S = j2.readShort(t2, E2), s = j2.readUshort(t2, E2 + 2); + E2 += 4; + if (S == 12) + r = s; + else if (S == 20) + u2 = s; + else if (S == 21) + X = s; + else if (S == 48) + I3 = s; + else if (S == 53) + ax = s; + else if (S == 35) + a3 = s; + else if (S == 62) + R2 = s; + else if (S == 101) + ai = s; + else if (S == 109) + aa = s; + else if (S == 84) + ap = s; + else if (S == 106) + ah = s; + else if (S == 107) + ae3 = s; + else if (S == 108) + aD = s; + else if (S == 102) + al2 = s; + else if (S == 104) + i = s; + else if (S == 105) + aE = s; + else { + var F = S < 0 ? -S : S, D = F & 65280, _2 = 0; + if (F & az) { + if (F & H) { + _2 = s & 65535; + _2 += (F & 255) << 16; + } else { + _2 = s & 65535; + } + } + if ((F & V2) == V2) { + if (T2 == null) { + T2 = []; + for (var M = 0;M < 4; M++) + T2[M] = new Int16Array((u2 >>> 1) * (X >>> 1)); + B2 = new Int16Array((u2 >>> 1) * (X >>> 1)); + C4 = new Int16Array(1024); + for (var M = 0;M < 1024; M++) { + var aG = M - 512, p = Math.abs(aG), r = Math.floor(768 * p * p * p / (255 * 255 * 255)) + p; + C4[M] = Math.sign(aG) * r; + } + k2 = new Uint16Array(4096); + var aA = (1 << 16) - 1; + for (var M = 0;M < 4096; M++) { + var at = M, a1 = aA * (Math.pow(113, at / 4095) - 1) / 112; + k2[M] = Math.min(a1, aA); + } + } + var w = T2[R2], v = m(u2, 1 + P[I3]), N = m(X, 1 + P[I3]); + if (I3 == 0) { + for (var b = 0;b < N; b++) + for (var G2 = 0;G2 < v; G2++) { + var c = E2 + (b * v + G2) * 2; + w[b * (u2 >>> 1) + G2] = t2[c] << 8 | t2[c + 1]; + } + } else { + var a7 = [t2, E2 * 8], a4 = [], ay = 0, aw = v * N, f = [0, 0], Q2 = 0, s = 0; + while (ay < aw) { + ag(a7, f); + Q2 = f[0]; + s = f[1]; + while (Q2 > 0) { + a4[ay++] = s; + Q2--; + } + } + var l2 = (I3 - 1) % 3, aF = l2 != 1 ? v : 0, a2 = l2 != 0 ? N : 0; + for (var b = 0;b < N; b++) { + var af = (b + a2) * (u2 >>> 1) + aF, au = b * v; + for (var G2 = 0;G2 < v; G2++) + w[af + G2] = C4[a4[au + G2] + 512] * ax; + } + if (l2 == 2) { + var i = u2 >>> 1, an = v * 2, a9 = N * 2; + for (var b = 0;b < N; b++) { + for (var G2 = 0;G2 < an; G2++) { + var M = b * 2 * i + G2, a = b * i + G2, e = N * i + a; + if (b == 0) + O(w, B2, M, e, a, i); + else if (b == N - 1) + y(w, B2, M, e, a, i); + else + J2(w, B2, M, e, a, i); + } + } + var Z2 = w; + w = B2; + B2 = Z2; + for (var b = 0;b < a9; b++) { + for (var G2 = 0;G2 < v; G2++) { + var M = b * i + 2 * G2, a = b * i + G2, e = v + a; + if (G2 == 0) + O(w, B2, M, e, a, 1); + else if (G2 == v - 1) + y(w, B2, M, e, a, 1); + else + J2(w, B2, M, e, a, 1); + } + } + var Z2 = w; + w = B2; + B2 = Z2; + var aC = [], aB = 2 - ~~((I3 - 1) / 3); + for (var K = 0;K < 3; K++) + aC[K] = aa >> 14 - K * 2 & 3; + var a6 = aC[aB]; + if (a6 != 0) + for (var b = 0;b < a9; b++) + for (var G2 = 0;G2 < an; G2++) { + var M = b * i + G2; + w[M] = w[M] << a6; + } + } + } + if (I3 == 9 && R2 == 3) { + var a8 = T2[0], ab = T2[1], aq = T2[2], as = T2[3]; + for (var b = 0;b < X; b += 2) + for (var G2 = 0;G2 < u2; G2 += 2) { + var U = b * u2 + G2, c = (b >>> 1) * (u2 >>> 1) + (G2 >>> 1), z = a8[c], ao = ab[c] - 2048, ak = aq[c] - 2048, ad = as[c] - 2048, aj = (ao << 1) + z, a0 = (ak << 1) + z, aH = z + ad, am = z - ad; + if (a5) { + L[U] = q2(aH); + L[U + 1] = q2(a0); + L[U + u2] = q2(aj); + L[U + u2 + 1] = q2(am); + } else { + L[U] = q2(aj); + L[U + 1] = q2(aH); + L[U + u2] = q2(am); + L[U + u2 + 1] = q2(a0); + } + } + } + E2 += _2 * 4; + } else if (F == 16388) { + E2 += _2 * 4; + } else if (D == 8192 || D == 8448 || D == 9216) { + } else + throw F.toString(16); + } + } + console.log(Date.now() - W); + } + return av; +}(); +UTIF.decode._decodeLogLuv32 = function(img, data2, off, len, tgt, toff) { + var w = img.width, qw = w * 4; + var io = 0, out = new Uint8Array(qw); + while (io < len) { + var oo = 0; + while (oo < qw) { + var c = data2[off + io]; + io++; + if (c < 128) { + for (var j2 = 0;j2 < c; j2++) + out[oo + j2] = data2[off + io + j2]; + oo += c; + io += c; + } else { + c = c - 126; + for (var j2 = 0;j2 < c; j2++) + out[oo + j2] = data2[off + io]; + oo += c; + io++; + } + } + for (var x2 = 0;x2 < w; x2++) { + tgt[toff + 0] = out[x2]; + tgt[toff + 1] = out[x2 + w]; + tgt[toff + 2] = out[x2 + w * 2]; + tgt[toff + 4] = out[x2 + w * 3]; + toff += 6; + } + } +}; +UTIF.decode._ljpeg_diff = function(data2, prm, huff) { + var getbithuff = UTIF.decode._getbithuff; + var len, diff; + len = getbithuff(data2, prm, huff[0], huff); + diff = getbithuff(data2, prm, len, 0); + if ((diff & 1 << len - 1) == 0) + diff -= (1 << len) - 1; + return diff; +}; +UTIF.decode._decodeARW = function(img, inp, off, src_length, tgt, toff) { + var raw_width = img["t256"][0], height2 = img["t257"][0], tiff_bps = img["t258"][0]; + var bin = img.isLE ? UTIF._binLE : UTIF._binBE; + var arw2 = raw_width * height2 == src_length || raw_width * height2 * 1.5 == src_length; + if (!arw2) { + height2 += 8; + var prm = [off, 0, 0, 0]; + var huff = new Uint16Array(32770); + var tab = [ + 3857, + 3856, + 3599, + 3342, + 3085, + 2828, + 2571, + 2314, + 2057, + 1800, + 1543, + 1286, + 1029, + 772, + 771, + 768, + 514, + 513 + ]; + var i, c, n2, col, row, sum2 = 0; + var ljpeg_diff = UTIF.decode._ljpeg_diff; + huff[0] = 15; + for (n2 = i = 0;i < 18; i++) { + var lim = 32768 >>> (tab[i] >>> 8); + for (var c = 0;c < lim; c++) + huff[++n2] = tab[i]; + } + for (col = raw_width;col--; ) + for (row = 0;row < height2 + 1; row += 2) { + if (row == height2) + row = 1; + sum2 += ljpeg_diff(inp, prm, huff); + if (row < height2) { + var clr = sum2 & 4095; + UTIF.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps); + } + } + return; + } + if (raw_width * height2 * 1.5 == src_length) { + for (var i = 0;i < src_length; i += 3) { + var b0 = inp[off + i + 0], b1 = inp[off + i + 1], b2 = inp[off + i + 2]; + tgt[toff + i] = b1 << 4 | b0 >>> 4; + tgt[toff + i + 1] = b0 << 4 | b2 >>> 4; + tgt[toff + i + 2] = b2 << 4 | b1 >>> 4; + } + return; + } + var pix = new Uint16Array(16); + var row, col, val2, max, min, imax, imin, sh, bit, i, dp; + var data2 = new Uint8Array(raw_width + 1); + for (row = 0;row < height2; row++) { + for (var j2 = 0;j2 < raw_width; j2++) + data2[j2] = inp[off++]; + for (dp = 0, col = 0;col < raw_width - 30; dp += 16) { + max = 2047 & (val2 = bin.readUint(data2, dp)); + min = 2047 & val2 >>> 11; + imax = 15 & val2 >>> 22; + imin = 15 & val2 >>> 26; + for (sh = 0;sh < 4 && 128 << sh <= max - min; sh++) + ; + for (bit = 30, i = 0;i < 16; i++) + if (i == imax) + pix[i] = max; + else if (i == imin) + pix[i] = min; + else { + pix[i] = ((bin.readUshort(data2, dp + (bit >> 3)) >>> (bit & 7) & 127) << sh) + min; + if (pix[i] > 2047) + pix[i] = 2047; + bit += 7; + } + for (i = 0;i < 16; i++, col += 2) { + var clr = pix[i] << 1; + UTIF.decode._putsF(tgt, (row * raw_width + col) * tiff_bps, clr << 16 - tiff_bps); + } + col -= col & 1 ? 1 : 31; + } + } +}; +UTIF.decode._decodeNikon = function(img, imgs, data2, off, src_length, tgt, toff) { + var nikon_tree = [ + [ + 0, + 0, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 5, + 4, + 3, + 6, + 2, + 7, + 1, + 0, + 8, + 9, + 11, + 10, + 12 + ], + [ + 0, + 0, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 57, + 90, + 56, + 39, + 22, + 5, + 4, + 3, + 2, + 1, + 0, + 11, + 12, + 12 + ], + [ + 0, + 0, + 1, + 4, + 2, + 3, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 5, + 4, + 6, + 3, + 7, + 2, + 8, + 1, + 9, + 0, + 10, + 11, + 12 + ], + [ + 0, + 0, + 1, + 4, + 3, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 5, + 6, + 4, + 7, + 8, + 3, + 9, + 2, + 1, + 0, + 10, + 11, + 12, + 13, + 14 + ], + [ + 0, + 0, + 1, + 5, + 1, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 8, + 92, + 75, + 58, + 41, + 7, + 6, + 5, + 4, + 3, + 2, + 1, + 0, + 13, + 14 + ], + [ + 0, + 0, + 1, + 4, + 2, + 2, + 3, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 6, + 8, + 5, + 9, + 4, + 10, + 3, + 11, + 12, + 2, + 0, + 1, + 13, + 14 + ] + ]; + var raw_width = img["t256"][0], height2 = img["t257"][0], tiff_bps = img["t258"][0]; + var tree = 0, split = 0; + var make_decoder = UTIF.decode._make_decoder; + var getbithuff = UTIF.decode._getbithuff; + var mn = imgs[0].exifIFD.makerNote, md = mn["t150"] ? mn["t150"] : mn["t140"], mdo = 0; + var ver0 = md[mdo++], ver1 = md[mdo++]; + if (ver0 == 73 || ver1 == 88) + mdo += 2110; + if (ver0 == 70) + tree = 2; + if (tiff_bps == 14) + tree += 3; + var vpred = [[0, 0], [0, 0]], bin = img.isLE ? UTIF._binLE : UTIF._binBE; + for (var i = 0;i < 2; i++) + for (var j2 = 0;j2 < 2; j2++) { + vpred[i][j2] = bin.readShort(md, mdo); + mdo += 2; + } + var max = 1 << tiff_bps & 32767, step = 0; + var csize = bin.readShort(md, mdo); + mdo += 2; + if (csize > 1) + step = Math.floor(max / (csize - 1)); + if (ver0 == 68 && ver1 == 32 && step > 0) + split = bin.readShort(md, 562); + var i; + var row, col; + var len, shl, diff; + var min_v = 0; + var hpred = [0, 0]; + var huff = make_decoder(nikon_tree[tree]); + var prm = [off, 0, 0, 0]; + for (min_v = row = 0;row < height2; row++) { + if (split && row == split) { + huff = make_decoder(nikon_tree[tree + 1]); + } + for (col = 0;col < raw_width; col++) { + i = getbithuff(data2, prm, huff[0], huff); + len = i & 15; + shl = i >>> 4; + diff = (getbithuff(data2, prm, len - shl, 0) << 1) + 1 << shl >>> 1; + if ((diff & 1 << len - 1) == 0) + diff -= (1 << len) - (shl == 0 ? 1 : 0); + if (col < 2) + hpred[col] = vpred[row & 1][col] += diff; + else + hpred[col & 1] += diff; + var clr = Math.min(Math.max(hpred[col & 1], 0), (1 << tiff_bps) - 1); + var bti = (row * raw_width + col) * tiff_bps; + UTIF.decode._putsF(tgt, bti, clr << 16 - tiff_bps); + } + } +}; +UTIF.decode._putsF = function(dt, pos, val2) { + val2 = val2 << 8 - (pos & 7); + var o = pos >>> 3; + dt[o] |= val2 >>> 16; + dt[o + 1] |= val2 >>> 8; + dt[o + 2] |= val2; +}; +UTIF.decode._getbithuff = function(data2, prm, nbits, huff) { + var zero_after_ff = 0; + var get_byte = UTIF.decode._get_byte; + var c; + var off = prm[0], bitbuf = prm[1], vbits = prm[2], reset = prm[3]; + if (nbits == 0 || vbits < 0) + return 0; + while (!reset && vbits < nbits && (c = data2[off++]) != -1 && !(reset = zero_after_ff && c == 255 && data2[off++])) { + bitbuf = (bitbuf << 8) + c; + vbits += 8; + } + c = bitbuf << 32 - vbits >>> 32 - nbits; + if (huff) { + vbits -= huff[c + 1] >>> 8; + c = huff[c + 1] & 255; + } else + vbits -= nbits; + if (vbits < 0) + throw "e"; + prm[0] = off; + prm[1] = bitbuf; + prm[2] = vbits; + prm[3] = reset; + return c; +}; +UTIF.decode._make_decoder = function(source) { + var max, len, h, i, j2; + var huff = []; + for (max = 16;max != 0 && !source[max]; max--) + ; + var si = 17; + huff[0] = max; + for (h = len = 1;len <= max; len++) + for (i = 0;i < source[len]; i++, ++si) + for (j2 = 0;j2 < 1 << max - len; j2++) + if (h <= 1 << max) + huff[h++] = len << 8 | source[si]; + return huff; +}; +UTIF.decode._decodeNewJPEG = function(img, data2, off, len, tgt, toff) { + len = Math.min(len, data2.length - off); + var tables = img["t347"], tlen = tables ? tables.length : 0, buff = new Uint8Array(tlen + len); + if (tables) { + var SOI = 216, EOI2 = 217, boff = 0; + for (var i = 0;i < tlen - 1; i++) { + if (tables[i] == 255 && tables[i + 1] == EOI2) + break; + buff[boff++] = tables[i]; + } + var byte1 = data2[off], byte2 = data2[off + 1]; + if (byte1 != 255 || byte2 != SOI) { + buff[boff++] = byte1; + buff[boff++] = byte2; + } + for (var i = 2;i < len; i++) + buff[boff++] = data2[off + i]; + } else + for (var i = 0;i < len; i++) + buff[i] = data2[off + i]; + if (img["t262"][0] == 32803 || img["t259"][0] == 7 && img["t262"][0] == 34892) { + var bps = img["t258"][0]; + var out = UTIF.LosslessJpegDecode(buff), olen = out.length; + if (false) { + } else if (bps == 16) { + if (img.isLE) + for (var i = 0;i < olen; i++) { + tgt[toff + (i << 1)] = out[i] & 255; + tgt[toff + (i << 1) + 1] = out[i] >>> 8; + } + else + for (var i = 0;i < olen; i++) { + tgt[toff + (i << 1)] = out[i] >>> 8; + tgt[toff + (i << 1) + 1] = out[i] & 255; + } + } else if (bps == 14 || bps == 12 || bps == 10) { + var rst = 16 - bps; + for (var i = 0;i < olen; i++) + UTIF.decode._putsF(tgt, i * bps, out[i] << rst); + } else if (bps == 8) { + for (var i = 0;i < olen; i++) + tgt[toff + i] = out[i]; + } else + throw new Error("unsupported bit depth " + bps); + } else { + var parser = new UTIF.JpegDecoder; + parser.parse(buff); + var decoded = parser.getData({ width: parser.width, height: parser.height, forceRGB: true, isSourcePDF: false }); + for (var i = 0;i < decoded.length; i++) + tgt[toff + i] = decoded[i]; + } + if (img["t262"][0] == 6) + img["t262"][0] = 2; +}; +UTIF.decode._decodeOldJPEGInit = function(img, data2, off, len) { + var SOI = 216, EOI2 = 217, DQT = 219, DHT = 196, DRI = 221, SOF0 = 192, SOS2 = 218; + var joff = 0, soff = 0, tables, sosMarker2, isTiled = false, i, j2, k2; + var jpgIchgFmt = img["t513"], jifoff = jpgIchgFmt ? jpgIchgFmt[0] : 0; + var jpgIchgFmtLen = img["t514"], jiflen = jpgIchgFmtLen ? jpgIchgFmtLen[0] : 0; + var soffTag = img["t324"] || img["t273"] || jpgIchgFmt; + var ycbcrss = img["t530"], ssx = 0, ssy = 0; + var spp = img["t277"] ? img["t277"][0] : 1; + var jpgresint = img["t515"]; + if (soffTag) { + soff = soffTag[0]; + isTiled = soffTag.length > 1; + } + if (!isTiled) { + if (data2[off] == 255 && data2[off + 1] == SOI) + return { jpegOffset: off }; + if (jpgIchgFmt != null) { + if (data2[off + jifoff] == 255 && data2[off + jifoff + 1] == SOI) + joff = off + jifoff; + else + log("JPEGInterchangeFormat does not point to SOI"); + if (jpgIchgFmtLen == null) + log("JPEGInterchangeFormatLength field is missing"); + else if (jifoff >= soff || jifoff + jiflen <= soff) + log("JPEGInterchangeFormatLength field value is invalid"); + if (joff != null) + return { jpegOffset: joff }; + } + } + if (ycbcrss != null) { + ssx = ycbcrss[0]; + ssy = ycbcrss[1]; + } + if (jpgIchgFmt != null) { + if (jpgIchgFmtLen != null) + if (jiflen >= 2 && jifoff + jiflen <= soff) { + if (data2[off + jifoff + jiflen - 2] == 255 && data2[off + jifoff + jiflen - 1] == SOI) + tables = new Uint8Array(jiflen - 2); + else + tables = new Uint8Array(jiflen); + for (i = 0;i < tables.length; i++) + tables[i] = data2[off + jifoff + i]; + log("Incorrect JPEG interchange format: using JPEGInterchangeFormat offset to derive tables"); + } else + log("JPEGInterchangeFormat+JPEGInterchangeFormatLength > offset to first strip or tile"); + } + if (tables == null) { + var ooff = 0, out = []; + out[ooff++] = 255; + out[ooff++] = SOI; + var qtables = img["t519"]; + if (qtables == null) + throw new Error("JPEGQTables tag is missing"); + for (i = 0;i < qtables.length; i++) { + out[ooff++] = 255; + out[ooff++] = DQT; + out[ooff++] = 0; + out[ooff++] = 67; + out[ooff++] = i; + for (j2 = 0;j2 < 64; j2++) + out[ooff++] = data2[off + qtables[i] + j2]; + } + for (k2 = 0;k2 < 2; k2++) { + var htables = img[k2 == 0 ? "t520" : "t521"]; + if (htables == null) + throw new Error((k2 == 0 ? "JPEGDCTables" : "JPEGACTables") + " tag is missing"); + for (i = 0;i < htables.length; i++) { + out[ooff++] = 255; + out[ooff++] = DHT; + var nc = 19; + for (j2 = 0;j2 < 16; j2++) + nc += data2[off + htables[i] + j2]; + out[ooff++] = nc >>> 8; + out[ooff++] = nc & 255; + out[ooff++] = i | k2 << 4; + for (j2 = 0;j2 < 16; j2++) + out[ooff++] = data2[off + htables[i] + j2]; + for (j2 = 0;j2 < nc; j2++) + out[ooff++] = data2[off + htables[i] + 16 + j2]; + } + } + out[ooff++] = 255; + out[ooff++] = SOF0; + out[ooff++] = 0; + out[ooff++] = 8 + 3 * spp; + out[ooff++] = 8; + out[ooff++] = img.height >>> 8 & 255; + out[ooff++] = img.height & 255; + out[ooff++] = img.width >>> 8 & 255; + out[ooff++] = img.width & 255; + out[ooff++] = spp; + if (spp == 1) { + out[ooff++] = 1; + out[ooff++] = 17; + out[ooff++] = 0; + } else + for (i = 0;i < 3; i++) { + out[ooff++] = i + 1; + out[ooff++] = i != 0 ? 17 : (ssx & 15) << 4 | ssy & 15; + out[ooff++] = i; + } + if (jpgresint != null && jpgresint[0] != 0) { + out[ooff++] = 255; + out[ooff++] = DRI; + out[ooff++] = 0; + out[ooff++] = 4; + out[ooff++] = jpgresint[0] >>> 8 & 255; + out[ooff++] = jpgresint[0] & 255; + } + tables = new Uint8Array(out); + } + var sofpos = -1; + i = 0; + while (i < tables.length - 1) { + if (tables[i] == 255 && tables[i + 1] == SOF0) { + sofpos = i; + break; + } + i++; + } + if (sofpos == -1) { + var tmptab = new Uint8Array(tables.length + 10 + 3 * spp); + tmptab.set(tables); + var tmpoff = tables.length; + sofpos = tables.length; + tables = tmptab; + tables[tmpoff++] = 255; + tables[tmpoff++] = SOF0; + tables[tmpoff++] = 0; + tables[tmpoff++] = 8 + 3 * spp; + tables[tmpoff++] = 8; + tables[tmpoff++] = img.height >>> 8 & 255; + tables[tmpoff++] = img.height & 255; + tables[tmpoff++] = img.width >>> 8 & 255; + tables[tmpoff++] = img.width & 255; + tables[tmpoff++] = spp; + if (spp == 1) { + tables[tmpoff++] = 1; + tables[tmpoff++] = 17; + tables[tmpoff++] = 0; + } else + for (i = 0;i < 3; i++) { + tables[tmpoff++] = i + 1; + tables[tmpoff++] = i != 0 ? 17 : (ssx & 15) << 4 | ssy & 15; + tables[tmpoff++] = i; + } + } + if (data2[soff] == 255 && data2[soff + 1] == SOS2) { + var soslen = data2[soff + 2] << 8 | data2[soff + 3]; + sosMarker2 = new Uint8Array(soslen + 2); + sosMarker2[0] = data2[soff]; + sosMarker2[1] = data2[soff + 1]; + sosMarker2[2] = data2[soff + 2]; + sosMarker2[3] = data2[soff + 3]; + for (i = 0;i < soslen - 2; i++) + sosMarker2[i + 4] = data2[soff + i + 4]; + } else { + sosMarker2 = new Uint8Array(2 + 6 + 2 * spp); + var sosoff = 0; + sosMarker2[sosoff++] = 255; + sosMarker2[sosoff++] = SOS2; + sosMarker2[sosoff++] = 0; + sosMarker2[sosoff++] = 6 + 2 * spp; + sosMarker2[sosoff++] = spp; + if (spp == 1) { + sosMarker2[sosoff++] = 1; + sosMarker2[sosoff++] = 0; + } else + for (i = 0;i < 3; i++) { + sosMarker2[sosoff++] = i + 1; + sosMarker2[sosoff++] = i << 4 | i; + } + sosMarker2[sosoff++] = 0; + sosMarker2[sosoff++] = 63; + sosMarker2[sosoff++] = 0; + } + return { jpegOffset: off, tables, sosMarker: sosMarker2, sofPosition: sofpos }; +}; +UTIF.decode._decodeOldJPEG = function(img, data2, off, len, tgt, toff) { + var i, dlen, tlen, buff, buffoff; + var jpegData = UTIF.decode._decodeOldJPEGInit(img, data2, off, len); + if (jpegData.jpegOffset != null) { + dlen = off + len - jpegData.jpegOffset; + buff = new Uint8Array(dlen); + for (i = 0;i < dlen; i++) + buff[i] = data2[jpegData.jpegOffset + i]; + } else { + tlen = jpegData.tables.length; + buff = new Uint8Array(tlen + jpegData.sosMarker.length + len + 2); + buff.set(jpegData.tables); + buffoff = tlen; + buff[jpegData.sofPosition + 5] = img.height >>> 8 & 255; + buff[jpegData.sofPosition + 6] = img.height & 255; + buff[jpegData.sofPosition + 7] = img.width >>> 8 & 255; + buff[jpegData.sofPosition + 8] = img.width & 255; + if (data2[off] != 255 || data2[off + 1] != SOS) { + buff.set(jpegData.sosMarker, buffoff); + buffoff += sosMarker.length; + } + for (i = 0;i < len; i++) + buff[buffoff++] = data2[off + i]; + buff[buffoff++] = 255; + buff[buffoff++] = EOI; + } + var parser = new UTIF.JpegDecoder; + parser.parse(buff); + var decoded = parser.getData({ width: parser.width, height: parser.height, forceRGB: true, isSourcePDF: false }); + for (var i = 0;i < decoded.length; i++) + tgt[toff + i] = decoded[i]; + if (img["t262"] && img["t262"][0] == 6) + img["t262"][0] = 2; +}; +UTIF.decode._decodePackBits = function(data2, off, len, tgt, toff) { + var sa = new Int8Array(data2.buffer), ta = new Int8Array(tgt.buffer), lim = off + len; + while (off < lim) { + var n2 = sa[off]; + off++; + if (n2 >= 0 && n2 < 128) + for (var i = 0;i < n2 + 1; i++) { + ta[toff] = sa[off]; + toff++; + off++; + } + if (n2 >= -127 && n2 < 0) { + for (var i = 0;i < -n2 + 1; i++) { + ta[toff] = sa[off]; + toff++; + } + off++; + } + } + return toff; +}; +UTIF.decode._decodeThunder = function(data2, off, len, tgt, toff) { + var d2 = [0, 1, 0, -1], d3 = [0, 1, 2, 3, 0, -3, -2, -1]; + var lim = off + len, qoff = toff * 2, px2 = 0; + while (off < lim) { + var b = data2[off], msk = b >>> 6, n2 = b & 63; + off++; + if (msk == 3) { + px2 = n2 & 15; + tgt[qoff >>> 1] |= px2 << 4 * (1 - qoff & 1); + qoff++; + } + if (msk == 0) + for (var i = 0;i < n2; i++) { + tgt[qoff >>> 1] |= px2 << 4 * (1 - qoff & 1); + qoff++; + } + if (msk == 2) + for (var i = 0;i < 2; i++) { + var d = n2 >>> 3 * (1 - i) & 7; + if (d != 4) { + px2 += d3[d]; + tgt[qoff >>> 1] |= px2 << 4 * (1 - qoff & 1); + qoff++; + } + } + if (msk == 1) + for (var i = 0;i < 3; i++) { + var d = n2 >>> 2 * (2 - i) & 3; + if (d != 2) { + px2 += d2[d]; + tgt[qoff >>> 1] |= px2 << 4 * (1 - qoff & 1); + qoff++; + } + } + } +}; +UTIF.decode._dmap = { "1": 0, "011": 1, "000011": 2, "0000011": 3, "010": -1, "000010": -2, "0000010": -3 }; +UTIF.decode._lens = function() { + var addKeys = function(lens, arr, i0, inc) { + for (var i = 0;i < arr.length; i++) + lens[arr[i]] = i0 + i * inc; + }; + var termW = "00110101,000111,0111,1000,1011,1100,1110,1111,10011,10100,00111,01000,001000,000011,110100,110101," + "101010,101011,0100111,0001100,0001000,0010111,0000011,0000100,0101000,0101011,0010011,0100100,0011000,00000010,00000011,00011010," + "00011011,00010010,00010011,00010100,00010101,00010110,00010111,00101000,00101001,00101010,00101011,00101100,00101101,00000100,00000101,00001010," + "00001011,01010010,01010011,01010100,01010101,00100100,00100101,01011000,01011001,01011010,01011011,01001010,01001011,00110010,00110011,00110100"; + var termB = "0000110111,010,11,10,011,0011,0010,00011,000101,000100,0000100,0000101,0000111,00000100,00000111,000011000," + "0000010111,0000011000,0000001000,00001100111,00001101000,00001101100,00000110111,00000101000,00000010111,00000011000,000011001010,000011001011,000011001100,000011001101,000001101000,000001101001," + "000001101010,000001101011,000011010010,000011010011,000011010100,000011010101,000011010110,000011010111,000001101100,000001101101,000011011010,000011011011,000001010100,000001010101,000001010110,000001010111," + "000001100100,000001100101,000001010010,000001010011,000000100100,000000110111,000000111000,000000100111,000000101000,000001011000,000001011001,000000101011,000000101100,000001011010,000001100110,000001100111"; + var makeW = "11011,10010,010111,0110111,00110110,00110111,01100100,01100101,01101000,01100111,011001100,011001101,011010010,011010011,011010100,011010101,011010110," + "011010111,011011000,011011001,011011010,011011011,010011000,010011001,010011010,011000,010011011"; + var makeB = "0000001111,000011001000,000011001001,000001011011,000000110011,000000110100,000000110101,0000001101100,0000001101101,0000001001010,0000001001011,0000001001100," + "0000001001101,0000001110010,0000001110011,0000001110100,0000001110101,0000001110110,0000001110111,0000001010010,0000001010011,0000001010100,0000001010101,0000001011010," + "0000001011011,0000001100100,0000001100101"; + var makeA = "00000001000,00000001100,00000001101,000000010010,000000010011,000000010100,000000010101,000000010110,000000010111,000000011100,000000011101,000000011110,000000011111"; + termW = termW.split(","); + termB = termB.split(","); + makeW = makeW.split(","); + makeB = makeB.split(","); + makeA = makeA.split(","); + var lensW = {}, lensB = {}; + addKeys(lensW, termW, 0, 1); + addKeys(lensW, makeW, 64, 64); + addKeys(lensW, makeA, 1792, 64); + addKeys(lensB, termB, 0, 1); + addKeys(lensB, makeB, 64, 64); + addKeys(lensB, makeA, 1792, 64); + return [lensW, lensB]; +}(); +UTIF.decode._decodeG4 = function(data2, off, slen, tgt, toff, w, fo) { + var U = UTIF.decode, boff = off << 3, len = 0, wrd = ""; + var line = [], pline = []; + for (var i = 0;i < w; i++) + pline.push(0); + pline = U._makeDiff(pline); + var a0 = 0, a1 = 0, a2 = 0, b1 = 0, b2 = 0, clr = 0; + var y = 0, mode = "", toRead = 0; + var bipl = Math.ceil(w / 8) * 8; + while (boff >>> 3 < off + slen) { + b1 = U._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b2 = U._findDiff(pline, b1, clr); + var bit = 0; + if (fo == 1) + bit = data2[boff >>> 3] >>> 7 - (boff & 7) & 1; + if (fo == 2) + bit = data2[boff >>> 3] >>> (boff & 7) & 1; + boff++; + wrd += bit; + if (mode == "H") { + if (U._lens[clr][wrd] != null) { + var dl2 = U._lens[clr][wrd]; + wrd = ""; + len += dl2; + if (dl2 < 64) { + U._addNtimes(line, len, clr); + a0 += len; + clr = 1 - clr; + len = 0; + toRead--; + if (toRead == 0) + mode = ""; + } + } + } else { + if (wrd == "0001") { + wrd = ""; + U._addNtimes(line, b2 - a0, clr); + a0 = b2; + } + if (wrd == "001") { + wrd = ""; + mode = "H"; + toRead = 2; + } + if (U._dmap[wrd] != null) { + a1 = b1 + U._dmap[wrd]; + U._addNtimes(line, a1 - a0, clr); + a0 = a1; + wrd = ""; + clr = 1 - clr; + } + } + if (line.length == w && mode == "") { + U._writeBits(line, tgt, toff * 8 + y * bipl); + clr = 0; + y++; + a0 = 0; + pline = U._makeDiff(line); + line = []; + } + } +}; +UTIF.decode._findDiff = function(line, x2, clr) { + for (var i = 0;i < line.length; i += 2) + if (line[i] >= x2 && line[i + 1] == clr) + return line[i]; +}; +UTIF.decode._makeDiff = function(line) { + var out = []; + if (line[0] == 1) + out.push(0, 1); + for (var i = 1;i < line.length; i++) + if (line[i - 1] != line[i]) + out.push(i, line[i]); + out.push(line.length, 0, line.length, 1); + return out; +}; +UTIF.decode._decodeG2 = function(data2, off, slen, tgt, toff, w, fo) { + var U = UTIF.decode, boff = off << 3, len = 0, wrd = ""; + var line = []; + var clr = 0; + var y = 0; + var bipl = Math.ceil(w / 8) * 8; + while (boff >>> 3 < off + slen) { + var bit = 0; + if (fo == 1) + bit = data2[boff >>> 3] >>> 7 - (boff & 7) & 1; + if (fo == 2) + bit = data2[boff >>> 3] >>> (boff & 7) & 1; + boff++; + wrd += bit; + len = U._lens[clr][wrd]; + if (len != null) { + U._addNtimes(line, len, clr); + wrd = ""; + if (len < 64) + clr = 1 - clr; + if (line.length == w) { + U._writeBits(line, tgt, toff * 8 + y * bipl); + line = []; + y++; + clr = 0; + if ((boff & 7) != 0) + boff += 8 - (boff & 7); + if (len >= 64) + boff += 8; + } + } + } +}; +UTIF.decode._decodeG3 = function(data2, off, slen, tgt, toff, w, fo, twoDim) { + var U = UTIF.decode, boff = off << 3, len = 0, wrd = ""; + var line = [], pline = []; + for (var i = 0;i < w; i++) + line.push(0); + var a0 = 0, a1 = 0, a2 = 0, b1 = 0, b2 = 0, clr = 0; + var y = -1, mode = "", toRead = 0, is1D = true; + var bipl = Math.ceil(w / 8) * 8; + while (boff >>> 3 < off + slen) { + b1 = U._findDiff(pline, a0 + (a0 == 0 ? 0 : 1), 1 - clr), b2 = U._findDiff(pline, b1, clr); + var bit = 0; + if (fo == 1) + bit = data2[boff >>> 3] >>> 7 - (boff & 7) & 1; + if (fo == 2) + bit = data2[boff >>> 3] >>> (boff & 7) & 1; + boff++; + wrd += bit; + if (is1D) { + if (U._lens[clr][wrd] != null) { + var dl2 = U._lens[clr][wrd]; + wrd = ""; + len += dl2; + if (dl2 < 64) { + U._addNtimes(line, len, clr); + clr = 1 - clr; + len = 0; + } + } + } else { + if (mode == "H") { + if (U._lens[clr][wrd] != null) { + var dl2 = U._lens[clr][wrd]; + wrd = ""; + len += dl2; + if (dl2 < 64) { + U._addNtimes(line, len, clr); + a0 += len; + clr = 1 - clr; + len = 0; + toRead--; + if (toRead == 0) + mode = ""; + } + } + } else { + if (wrd == "0001") { + wrd = ""; + U._addNtimes(line, b2 - a0, clr); + a0 = b2; + } + if (wrd == "001") { + wrd = ""; + mode = "H"; + toRead = 2; + } + if (U._dmap[wrd] != null) { + a1 = b1 + U._dmap[wrd]; + U._addNtimes(line, a1 - a0, clr); + a0 = a1; + wrd = ""; + clr = 1 - clr; + } + } + } + if (wrd.endsWith("000000000001")) { + if (y >= 0) + U._writeBits(line, tgt, toff * 8 + y * bipl); + if (twoDim) { + if (fo == 1) + is1D = (data2[boff >>> 3] >>> 7 - (boff & 7) & 1) == 1; + if (fo == 2) + is1D = (data2[boff >>> 3] >>> (boff & 7) & 1) == 1; + boff++; + } + wrd = ""; + clr = 0; + y++; + a0 = 0; + pline = U._makeDiff(line); + line = []; + } + } + if (line.length == w) + U._writeBits(line, tgt, toff * 8 + y * bipl); +}; +UTIF.decode._addNtimes = function(arr, n2, val2) { + for (var i = 0;i < n2; i++) + arr.push(val2); +}; +UTIF.decode._writeBits = function(bits, tgt, boff) { + for (var i = 0;i < bits.length; i++) + tgt[boff + i >>> 3] |= bits[i] << 7 - (boff + i & 7); +}; +UTIF.decode._decodeLZW = UTIF.decode._decodeLZW = function() { + var e, U, Z2, u2, K = 0, V2 = 0, g3 = 0, N = 0, O = function() { + var S = e >>> 3, A2 = U[S] << 16 | U[S + 1] << 8 | U[S + 2], j2 = A2 >>> 24 - (e & 7) - V2 & (1 << V2) - 1; + e += V2; + return j2; + }, h = new Uint32Array(4096 * 4), w = 0, m = function(S) { + if (S == w) + return; + w = S; + g3 = 1 << S; + N = g3 + 1; + for (var A2 = 0;A2 < N + 1; A2++) { + h[4 * A2] = h[4 * A2 + 3] = A2; + h[4 * A2 + 1] = 65535; + h[4 * A2 + 2] = 1; + } + }, i = function(S) { + V2 = S + 1; + K = N + 1; + }, D = function(S) { + var A2 = S << 2, j2 = h[A2 + 2], a = u2 + j2 - 1; + while (A2 != 65535) { + Z2[a--] = h[A2]; + A2 = h[A2 + 1]; + } + u2 += j2; + }, L = function(S, A2) { + var j2 = K << 2, a = S << 2; + h[j2] = h[(A2 << 2) + 3]; + h[j2 + 1] = a; + h[j2 + 2] = h[a + 2] + 1; + h[j2 + 3] = h[a + 3]; + K++; + if (K + 1 == 1 << V2 && V2 != 12) + V2++; + }, T2 = function(S, A2, j2, a, n2, q2) { + e = A2 << 3; + U = S; + Z2 = a; + u2 = n2; + var B2 = A2 + j2 << 3, _2 = 0, t2 = 0; + m(q2); + i(q2); + while (e < B2 && (_2 = O()) != N) { + if (_2 == g3) { + i(q2); + _2 = O(); + if (_2 == N) + break; + D(_2); + } else { + if (_2 < K) { + D(_2); + L(t2, _2); + } else { + L(t2, t2); + D(K - 1); + } + } + t2 = _2; + } + return u2; + }; + return T2; +}(); +UTIF.tags = {}; +UTIF._types = function() { + var main = new Array(250); + main.fill(0); + main = main.concat([0, 0, 0, 0, 4, 3, 3, 3, 3, 3, 0, 0, 3, 0, 0, 0, 3, 0, 0, 2, 2, 2, 2, 4, 3, 0, 0, 3, 4, 4, 3, 3, 5, 5, 3, 2, 5, 5, 0, 0, 0, 0, 4, 4, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 5, 5, 3, 0, 3, 3, 4, 4, 4, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + var rest = { 33432: 2, 33434: 5, 33437: 5, 34665: 4, 34850: 3, 34853: 4, 34855: 3, 34864: 3, 34866: 4, 36864: 7, 36867: 2, 36868: 2, 37121: 7, 37377: 10, 37378: 5, 37380: 10, 37381: 5, 37383: 3, 37384: 3, 37385: 3, 37386: 5, 37510: 7, 37520: 2, 37521: 2, 37522: 2, 40960: 7, 40961: 3, 40962: 4, 40963: 4, 40965: 4, 41486: 5, 41487: 5, 41488: 3, 41985: 3, 41986: 3, 41987: 3, 41988: 5, 41989: 3, 41990: 3, 41993: 3, 41994: 3, 41995: 7, 41996: 3, 42032: 2, 42033: 2, 42034: 5, 42036: 2, 42037: 2, 59932: 7 }; + return { + basic: { + main, + rest + }, + gps: { + main: [1, 2, 5, 2, 5, 1, 5, 5, 0, 9], + rest: { 18: 2, 29: 2 } + } + }; +}(); +UTIF._readIFD = function(bin, data2, offset, ifds, depth, prm) { + var cnt = bin.readUshort(data2, offset); + offset += 2; + var ifd = {}; + if (prm.debug) + log(" ".repeat(depth), ifds.length - 1, ">>>----------------"); + for (var i = 0;i < cnt; i++) { + var tag = bin.readUshort(data2, offset); + offset += 2; + var type = bin.readUshort(data2, offset); + offset += 2; + var num = bin.readUint(data2, offset); + offset += 4; + var voff = bin.readUint(data2, offset); + offset += 4; + var arr = []; + if (type == 1 || type == 7) { + var no = num < 5 ? offset - 4 : voff; + if (no + num > data2.buffer.byteLength) + num = data2.buffer.byteLength - no; + arr = new Uint8Array(data2.buffer, no, num); + } + if (type == 2) { + var o0 = num < 5 ? offset - 4 : voff, c = data2[o0], len = Math.max(0, Math.min(num - 1, data2.length - o0)); + if (c < 128 || len == 0) + arr.push(bin.readASCII(data2, o0, len)); + else + arr = new Uint8Array(data2.buffer, o0, len); + } + if (type == 3) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readUshort(data2, (num < 3 ? offset - 4 : voff) + 2 * j2)); + } + if (type == 4 || type == 13) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readUint(data2, (num < 2 ? offset - 4 : voff) + 4 * j2)); + } + if (type == 5 || type == 10) { + var ri = type == 5 ? bin.readUint : bin.readInt; + for (var j2 = 0;j2 < num; j2++) + arr.push([ri(data2, voff + j2 * 8), ri(data2, voff + j2 * 8 + 4)]); + } + if (type == 8) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readShort(data2, (num < 3 ? offset - 4 : voff) + 2 * j2)); + } + if (type == 9) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readInt(data2, (num < 2 ? offset - 4 : voff) + 4 * j2)); + } + if (type == 11) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readFloat(data2, voff + j2 * 4)); + } + if (type == 12) { + for (var j2 = 0;j2 < num; j2++) + arr.push(bin.readDouble(data2, voff + j2 * 8)); + } + if (num != 0 && arr.length == 0) { + log(tag, "unknown TIFF tag type: ", type, "num:", num); + if (i == 0) + return; + continue; + } + if (prm.debug) + log(" ".repeat(depth), tag, type, UTIF.tags[tag], arr); + ifd["t" + tag] = arr; + if (tag == 330 && ifd["t272"] && ifd["t272"][0] == "DSLR-A100") { + } else if (tag == 330 || tag == 34665 || tag == 34853 || tag == 50740 && bin.readUshort(data2, bin.readUint(arr, 0)) < 300 || tag == 61440) { + var oarr = tag == 50740 ? [bin.readUint(arr, 0)] : arr; + var subfd = []; + for (var j2 = 0;j2 < oarr.length; j2++) + UTIF._readIFD(bin, data2, oarr[j2], subfd, depth + 1, prm); + if (tag == 330) + ifd.subIFD = subfd; + if (tag == 34665) + ifd.exifIFD = subfd[0]; + if (tag == 34853) + ifd.gpsiIFD = subfd[0]; + if (tag == 50740) + ifd.dngPrvt = subfd[0]; + if (tag == 61440) + ifd.fujiIFD = subfd[0]; + } + if (tag == 37500 && prm.parseMN) { + var mn = arr; + if (bin.readASCII(mn, 0, 5) == "Nikon") + ifd.makerNote = UTIF["decode"](mn.slice(10).buffer)[0]; + else if (bin.readASCII(mn, 0, 5) == "OLYMP" || bin.readASCII(mn, 0, 9) == "OM SYSTEM") { + var inds = [8208, 8224, 8240, 8256, 8272]; + var subsub = []; + UTIF._readIFD(bin, mn, mn[1] == 77 ? 16 : mn[5] == 85 ? 12 : 8, subsub, depth + 1, prm); + var obj = ifd.makerNote = subsub.pop(); + for (var j2 = 0;j2 < inds.length; j2++) { + var k2 = "t" + inds[j2]; + if (obj[k2] == null) + continue; + UTIF._readIFD(bin, mn, obj[k2][0], subsub, depth + 1, prm); + obj[k2] = subsub.pop(); + } + if (obj["t12288"]) { + UTIF._readIFD(bin, obj["t12288"], 0, subsub, depth + 1, prm); + obj["t12288"] = subsub.pop(); + } + } else if (bin.readUshort(data2, voff) < 300 && bin.readUshort(data2, voff + 4) <= 12) { + var subsub = []; + UTIF._readIFD(bin, data2, voff, subsub, depth + 1, prm); + ifd.makerNote = subsub[0]; + } + } + } + ifds.push(ifd); + if (prm.debug) + log(" ".repeat(depth), "<<<---------------"); + return offset; +}; +UTIF._writeIFD = function(bin, types, data2, offset, ifd) { + var keys2 = Object.keys(ifd), knum = keys2.length; + if (ifd["exifIFD"]) + knum--; + if (ifd["gpsiIFD"]) + knum--; + bin.writeUshort(data2, offset, knum); + offset += 2; + var eoff = offset + knum * 12 + 4; + for (var ki = 0;ki < keys2.length; ki++) { + var key2 = keys2[ki]; + if (key2 == "t34665" || key2 == "t34853") + continue; + if (key2 == "exifIFD") + key2 = "t34665"; + if (key2 == "gpsiIFD") + key2 = "t34853"; + var tag = parseInt(key2.slice(1)), type = types.main[tag]; + if (type == null) + type = types.rest[tag]; + if (type == null || type == 0) + throw new Error("unknown type of tag: " + tag); + var val2 = ifd[key2]; + if (tag == 34665) { + var outp = UTIF._writeIFD(bin, types, data2, eoff, ifd["exifIFD"]); + val2 = [eoff]; + eoff = outp[1]; + } + if (tag == 34853) { + var outp = UTIF._writeIFD(bin, UTIF._types.gps, data2, eoff, ifd["gpsiIFD"]); + val2 = [eoff]; + eoff = outp[1]; + } + if (type == 2) + val2 = val2[0] + "\x00"; + var num = val2.length; + bin.writeUshort(data2, offset, tag); + offset += 2; + bin.writeUshort(data2, offset, type); + offset += 2; + bin.writeUint(data2, offset, num); + offset += 4; + var dlen = [-1, 1, 1, 2, 4, 8, 0, 1, 0, 4, 8, 0, 8][type] * num; + var toff = offset; + if (dlen > 4) { + bin.writeUint(data2, offset, eoff); + toff = eoff; + } + if (type == 1 || type == 7) { + for (var i = 0;i < num; i++) + data2[toff + i] = val2[i]; + } else if (type == 2) { + bin.writeASCII(data2, toff, val2); + } else if (type == 3) { + for (var i = 0;i < num; i++) + bin.writeUshort(data2, toff + 2 * i, val2[i]); + } else if (type == 4) { + for (var i = 0;i < num; i++) + bin.writeUint(data2, toff + 4 * i, val2[i]); + } else if (type == 5 || type == 10) { + var wr = type == 5 ? bin.writeUint : bin.writeInt; + for (var i = 0;i < num; i++) { + var v = val2[i], nu = v[0], de = v[1]; + if (nu == null) + throw "e"; + wr(data2, toff + 8 * i, nu); + wr(data2, toff + 8 * i + 4, de); + } + } else if (type == 9) { + for (var i = 0;i < num; i++) + bin.writeInt(data2, toff + 4 * i, val2[i]); + } else if (type == 12) { + for (var i = 0;i < num; i++) + bin.writeDouble(data2, toff + 8 * i, val2[i]); + } else + throw type; + if (dlen > 4) { + dlen += dlen & 1; + eoff += dlen; + } + offset += 4; + } + return [offset, eoff]; +}; +UTIF.toRGBA8 = function(out, scl) { + function gamma(x3) { + return x3 < 0.0031308 ? 12.92 * x3 : 1.055 * Math.pow(x3, 1 / 2.4) - 0.055; + } + var { width: w, height: h } = out, area2 = w * h, qarea = area2 * 4, data2 = out.data; + var img = new Uint8Array(area2 * 4); + var intp = out["t262"] ? out["t262"][0] : 2, bps = out["t258"] ? Math.min(32, out["t258"][0]) : 1; + if (out["t262"] == null && bps == 1) + intp = 0; + var smpls = out["t277"] ? out["t277"][0] : out["t258"] ? out["t258"].length : [1, 1, 3, 1, 1, 4, 3][intp]; + var sfmt = out["t339"] ? out["t339"][0] : null; + if (intp == 1 && bps == 32 && sfmt != 3) + throw "e"; + var bpl = Math.ceil(smpls * bps * w / 8); + if (false) { + } else if (intp == 0) { + scl = 1 / 256; + for (var y = 0;y < h; y++) { + var off = y * bpl, io = y * w; + if (bps == 1) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + (i >> 3)] >> 7 - (i & 7) & 1; + img[qi] = img[qi + 1] = img[qi + 2] = (1 - px2) * 255; + img[qi + 3] = 255; + } + if (bps == 4) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + (i >> 1)] >> 4 - 4 * (i & 1) & 15; + img[qi] = img[qi + 1] = img[qi + 2] = (15 - px2) * 17; + img[qi + 3] = 255; + } + if (bps == 8) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + i]; + img[qi] = img[qi + 1] = img[qi + 2] = 255 - px2; + img[qi + 3] = 255; + } + if (bps == 16) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, o = off + 2 * i, px2 = data2[o + 1] << 8 | data2[o]; + img[qi] = img[qi + 1] = img[qi + 2] = Math.min(255, 255 - ~~(px2 * scl)); + img[qi + 3] = 255; + } + } + } else if (intp == 1) { + if (scl == null) + scl = 1 / 256; + var f32 = (data2.length & 3) == 0 ? new Float32Array(data2.buffer) : null; + for (var y = 0;y < h; y++) { + var off = y * bpl, io = y * w; + if (bps == 1) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + (i >> 3)] >> 7 - (i & 7) & 1; + img[qi] = img[qi + 1] = img[qi + 2] = px2 * 255; + img[qi + 3] = 255; + } + if (bps == 2) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + (i >> 2)] >> 6 - 2 * (i & 3) & 3; + img[qi] = img[qi + 1] = img[qi + 2] = px2 * 85; + img[qi + 3] = 255; + } + if (bps == 8) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, px2 = data2[off + i * smpls]; + img[qi] = img[qi + 1] = img[qi + 2] = px2; + img[qi + 3] = 255; + } + if (bps == 16) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, o = off + 2 * i, px2 = data2[o + 1] << 8 | data2[o]; + img[qi] = img[qi + 1] = img[qi + 2] = Math.min(255, ~~(px2 * scl)); + img[qi + 3] = 255; + } + if (bps == 32) + for (var i = 0;i < w; i++) { + var qi = io + i << 2, o = (off >>> 2) + i, px2 = f32[o]; + img[qi] = img[qi + 1] = img[qi + 2] = ~~(0.5 + 255 * px2); + img[qi + 3] = 255; + } + } + } else if (intp == 2) { + if (bps == 8) { + if (smpls == 1) + for (var i = 0;i < area2; i++) { + img[4 * i] = img[4 * i + 1] = img[4 * i + 2] = data2[i]; + img[4 * i + 3] = 255; + } + if (smpls == 3) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 3; + img[qi] = data2[ti]; + img[qi + 1] = data2[ti + 1]; + img[qi + 2] = data2[ti + 2]; + img[qi + 3] = 255; + } + if (smpls >= 4) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * smpls; + img[qi] = data2[ti]; + img[qi + 1] = data2[ti + 1]; + img[qi + 2] = data2[ti + 2]; + img[qi + 3] = data2[ti + 3]; + } + } else if (bps == 16) { + if (smpls == 4) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 8 + 1; + img[qi] = data2[ti]; + img[qi + 1] = data2[ti + 2]; + img[qi + 2] = data2[ti + 4]; + img[qi + 3] = data2[ti + 6]; + } + if (smpls == 3) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 6 + 1; + img[qi] = data2[ti]; + img[qi + 1] = data2[ti + 2]; + img[qi + 2] = data2[ti + 4]; + img[qi + 3] = 255; + } + } else if (bps == 32) { + var ndt = new Float32Array(data2.buffer); + var min = 0; + for (var i = 0;i < ndt.length; i++) + min = Math.min(min, ndt[i]); + if (min < 0) + for (var i = 0;i < data2.length; i += 4) { + var t2 = data2[i]; + data2[i] = data2[i + 3]; + data2[i + 3] = t2; + t2 = data2[i + 1]; + data2[i + 1] = data2[i + 2]; + data2[i + 2] = t2; + } + var pmap = []; + for (var i = 0;i < 65536; i++) + pmap.push(gamma(i / 65535)); + for (var i = 0;i < ndt.length; i++) { + var cv = Math.max(0, Math.min(1, ndt[i])); + ndt[i] = pmap[~~(0.5 + cv * 65535)]; + } + if (smpls == 3) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 3; + img[qi] = ~~(0.5 + ndt[ti] * 255); + img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255); + img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255); + img[qi + 3] = 255; + } + else if (smpls == 4) + for (var i = 0;i < area2; i++) { + var qi = i << 2, ti = i * 4; + img[qi] = ~~(0.5 + ndt[ti] * 255); + img[qi + 1] = ~~(0.5 + ndt[ti + 1] * 255); + img[qi + 2] = ~~(0.5 + ndt[ti + 2] * 255); + img[qi + 3] = ~~(0.5 + ndt[ti + 3] * 255); + } + else + throw smpls; + } else + throw bps; + } else if (intp == 3) { + var map2 = out["t320"]; + var cn = 1 << bps; + var nexta = bps == 8 && smpls > 1 && out["t338"] && out["t338"][0] != 0; + for (var y = 0;y < h; y++) + for (var x2 = 0;x2 < w; x2++) { + var i = y * w + x2; + var qi = i << 2, mi = 0; + var dof = y * bpl; + if (false) { + } else if (bps == 1) + mi = data2[dof + (x2 >>> 3)] >>> 7 - (x2 & 7) & 1; + else if (bps == 2) + mi = data2[dof + (x2 >>> 2)] >>> 6 - 2 * (x2 & 3) & 3; + else if (bps == 4) + mi = data2[dof + (x2 >>> 1)] >>> 4 - 4 * (x2 & 1) & 15; + else if (bps == 8) + mi = data2[dof + x2 * smpls]; + else + throw bps; + img[qi] = map2[mi] >> 8; + img[qi + 1] = map2[cn + mi] >> 8; + img[qi + 2] = map2[cn + cn + mi] >> 8; + img[qi + 3] = nexta ? data2[dof + x2 * smpls + 1] : 255; + } + } else if (intp == 5) { + var gotAlpha = smpls > 4 ? 1 : 0; + for (var i = 0;i < area2; i++) { + var qi = i << 2, si = i * smpls; + if (window.UDOC) { + var C4 = data2[si], M = data2[si + 1], Y = data2[si + 2], K = data2[si + 3]; + var c = UDOC.C.cmykToRgb([C4 * (1 / 255), M * (1 / 255), Y * (1 / 255), K * (1 / 255)]); + img[qi] = ~~(0.5 + 255 * c[0]); + img[qi + 1] = ~~(0.5 + 255 * c[1]); + img[qi + 2] = ~~(0.5 + 255 * c[2]); + } else { + var C4 = 255 - data2[si], M = 255 - data2[si + 1], Y = 255 - data2[si + 2], K = (255 - data2[si + 3]) * (1 / 255); + img[qi] = ~~(C4 * K + 0.5); + img[qi + 1] = ~~(M * K + 0.5); + img[qi + 2] = ~~(Y * K + 0.5); + } + img[qi + 3] = 255 * (1 - gotAlpha) + data2[si + 4] * gotAlpha; + } + } else if (intp == 6 && out["t278"]) { + var rps = out["t278"][0]; + for (var y = 0;y < h; y += rps) { + var i = y * w, len = rps * w; + for (var j2 = 0;j2 < len; j2++) { + var qi = 4 * (i + j2), si = 3 * i + 4 * (j2 >>> 1); + var Y = data2[si + (j2 & 1)], Cb = data2[si + 2] - 128, Cr2 = data2[si + 3] - 128; + var r = Y + ((Cr2 >> 2) + (Cr2 >> 3) + (Cr2 >> 5)); + var g3 = Y - ((Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ((Cr2 >> 1) + (Cr2 >> 3) + (Cr2 >> 4) + (Cr2 >> 5)); + var b = Y + (Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)); + img[qi] = Math.max(0, Math.min(255, r)); + img[qi + 1] = Math.max(0, Math.min(255, g3)); + img[qi + 2] = Math.max(0, Math.min(255, b)); + img[qi + 3] = 255; + } + } + } else if (intp == 32845) { + for (var y = 0;y < h; y++) + for (var x2 = 0;x2 < w; x2++) { + var si = (y * w + x2) * 6, qi = (y * w + x2) * 4; + var L = data2[si + 1] << 8 | data2[si]; + var L = Math.pow(2, (L + 0.5) / 256 - 64); + var u2 = (data2[si + 3] + 0.5) / 410; + var v = (data2[si + 5] + 0.5) / 410; + var sX = 9 * u2 / (6 * u2 - 16 * v + 12); + var sY = 4 * v / (6 * u2 - 16 * v + 12); + var bY = L; + var X = sX * bY / sY, Y = bY, Z2 = (1 - sX - sY) * bY / sY; + var r = 2.69 * X - 1.276 * Y - 0.414 * Z2; + var g3 = -1.022 * X + 1.978 * Y + 0.044 * Z2; + var b = 0.061 * X - 0.224 * Y + 1.163 * Z2; + img[qi] = gamma(Math.min(r, 1)) * 255; + img[qi + 1] = gamma(Math.min(g3, 1)) * 255; + img[qi + 2] = gamma(Math.min(b, 1)) * 255; + img[qi + 3] = 255; + } + } else + log("Unknown Photometric interpretation: " + intp); + return img; +}; +UTIF.replaceIMG = function(imgs) { + if (imgs == null) + imgs = document.getElementsByTagName("img"); + var sufs = ["tif", "tiff", "dng", "cr2", "nef"]; + for (var i = 0;i < imgs.length; i++) { + var img = imgs[i], src = img.getAttribute("src"); + if (src == null) + continue; + var suff = src.split(".").pop().toLowerCase(); + if (sufs.indexOf(suff) == -1) + continue; + var xhr = new XMLHttpRequest; + UTIF._xhrs.push(xhr); + UTIF._imgs.push(img); + xhr.open("GET", src); + xhr.responseType = "arraybuffer"; + xhr.onload = UTIF._imgLoaded; + xhr.send(); + } +}; +UTIF._xhrs = []; +UTIF._imgs = []; +UTIF._imgLoaded = function(e) { + var ind = UTIF._xhrs.indexOf(e.target), img = UTIF._imgs[ind]; + UTIF._xhrs.splice(ind, 1); + UTIF._imgs.splice(ind, 1); + img.setAttribute("src", UTIF.bufferToURI(e.target.response)); +}; +UTIF.bufferToURI = function(buff) { + var ifds = UTIF.decode(buff); + var vsns = ifds, ma = 0, page = vsns[0]; + if (ifds[0].subIFD) + vsns = vsns.concat(ifds[0].subIFD); + for (var i = 0;i < vsns.length; i++) { + var img = vsns[i]; + if (img["t258"] == null || img["t258"].length < 3) + continue; + var ar = img["t256"] * img["t257"]; + if (ar > ma) { + ma = ar; + page = img; + } + } + UTIF.decodeImage(buff, page, ifds); + var rgba = UTIF.toRGBA8(page), w = page.width, h = page.height; + var cnv = document.createElement("canvas"); + cnv.width = w; + cnv.height = h; + var ctx = cnv.getContext("2d"); + var imgd = new ImageData(new Uint8ClampedArray(rgba.buffer), w, h); + ctx.putImageData(imgd, 0, 0); + return cnv.toDataURL(); +}; +UTIF._binBE = { + nextZero: function(data2, o) { + while (data2[o] != 0) + o++; + return o; + }, + readUshort: function(buff, p) { + return buff[p] << 8 | buff[p + 1]; + }, + readShort: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 1]; + a[1] = buff[p + 0]; + return UTIF._binBE.i16[0]; + }, + readInt: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 3]; + a[1] = buff[p + 2]; + a[2] = buff[p + 1]; + a[3] = buff[p + 0]; + return UTIF._binBE.i32[0]; + }, + readUint: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 3]; + a[1] = buff[p + 2]; + a[2] = buff[p + 1]; + a[3] = buff[p + 0]; + return UTIF._binBE.ui32[0]; + }, + readASCII: function(buff, p, l2) { + var s = ""; + for (var i = 0;i < l2; i++) + s += String.fromCharCode(buff[p + i]); + return s; + }, + readFloat: function(buff, p) { + var a = UTIF._binBE.ui8; + for (var i = 0;i < 4; i++) + a[i] = buff[p + 3 - i]; + return UTIF._binBE.fl32[0]; + }, + readDouble: function(buff, p) { + var a = UTIF._binBE.ui8; + for (var i = 0;i < 8; i++) + a[i] = buff[p + 7 - i]; + return UTIF._binBE.fl64[0]; + }, + writeUshort: function(buff, p, n2) { + buff[p] = n2 >> 8 & 255; + buff[p + 1] = n2 & 255; + }, + writeInt: function(buff, p, n2) { + var a = UTIF._binBE.ui8; + UTIF._binBE.i32[0] = n2; + buff[p + 3] = a[0]; + buff[p + 2] = a[1]; + buff[p + 1] = a[2]; + buff[p + 0] = a[3]; + }, + writeUint: function(buff, p, n2) { + buff[p] = n2 >> 24 & 255; + buff[p + 1] = n2 >> 16 & 255; + buff[p + 2] = n2 >> 8 & 255; + buff[p + 3] = n2 >> 0 & 255; + }, + writeASCII: function(buff, p, s) { + for (var i = 0;i < s.length; i++) + buff[p + i] = s.charCodeAt(i); + }, + writeDouble: function(buff, p, n2) { + UTIF._binBE.fl64[0] = n2; + for (var i = 0;i < 8; i++) + buff[p + i] = UTIF._binBE.ui8[7 - i]; + } +}; +UTIF._binBE.ui8 = new Uint8Array(8); +UTIF._binBE.i16 = new Int16Array(UTIF._binBE.ui8.buffer); +UTIF._binBE.i32 = new Int32Array(UTIF._binBE.ui8.buffer); +UTIF._binBE.ui32 = new Uint32Array(UTIF._binBE.ui8.buffer); +UTIF._binBE.fl32 = new Float32Array(UTIF._binBE.ui8.buffer); +UTIF._binBE.fl64 = new Float64Array(UTIF._binBE.ui8.buffer); +UTIF._binLE = { + nextZero: UTIF._binBE.nextZero, + readUshort: function(buff, p) { + return buff[p + 1] << 8 | buff[p]; + }, + readShort: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 0]; + a[1] = buff[p + 1]; + return UTIF._binBE.i16[0]; + }, + readInt: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 0]; + a[1] = buff[p + 1]; + a[2] = buff[p + 2]; + a[3] = buff[p + 3]; + return UTIF._binBE.i32[0]; + }, + readUint: function(buff, p) { + var a = UTIF._binBE.ui8; + a[0] = buff[p + 0]; + a[1] = buff[p + 1]; + a[2] = buff[p + 2]; + a[3] = buff[p + 3]; + return UTIF._binBE.ui32[0]; + }, + readASCII: UTIF._binBE.readASCII, + readFloat: function(buff, p) { + var a = UTIF._binBE.ui8; + for (var i = 0;i < 4; i++) + a[i] = buff[p + i]; + return UTIF._binBE.fl32[0]; + }, + readDouble: function(buff, p) { + var a = UTIF._binBE.ui8; + for (var i = 0;i < 8; i++) + a[i] = buff[p + i]; + return UTIF._binBE.fl64[0]; + }, + writeUshort: function(buff, p, n2) { + buff[p] = n2 & 255; + buff[p + 1] = n2 >> 8 & 255; + }, + writeInt: function(buff, p, n2) { + var a = UTIF._binBE.ui8; + UTIF._binBE.i32[0] = n2; + buff[p + 0] = a[0]; + buff[p + 1] = a[1]; + buff[p + 2] = a[2]; + buff[p + 3] = a[3]; + }, + writeUint: function(buff, p, n2) { + buff[p] = n2 >>> 0 & 255; + buff[p + 1] = n2 >>> 8 & 255; + buff[p + 2] = n2 >>> 16 & 255; + buff[p + 3] = n2 >>> 24 & 255; + }, + writeASCII: UTIF._binBE.writeASCII +}; +UTIF._copyTile = function(tb, tw, th, b, w, h, xoff, yoff) { + var xlim = Math.min(tw, w - xoff); + var ylim = Math.min(th, h - yoff); + for (var y = 0;y < ylim; y++) { + var tof = (yoff + y) * w + xoff; + var sof = y * tw; + for (var x2 = 0;x2 < xlim; x2++) + b[tof + x2] = tb[sof + x2]; + } +}; +UTIF._inflateRaw = function() { + var H = {}; + H.H = {}; + H.H.N = function(N, W) { + var R2 = Uint8Array, i = 0, m = 0, J2 = 0, h = 0, Q2 = 0, X = 0, u2 = 0, w = 0, d = 0, v, C4; + if (N[0] == 3 && N[1] == 0) + return W ? W : new R2(0); + var V2 = H.H, n2 = V2.b, A2 = V2.e, l2 = V2.R, M = V2.n, I3 = V2.A, e = V2.Z, b = V2.m, Z2 = W == null; + if (Z2) + W = new R2(N.length >>> 2 << 5); + while (i == 0) { + i = n2(N, d, 1); + m = n2(N, d + 1, 2); + d += 3; + if (m == 0) { + if ((d & 7) != 0) + d += 8 - (d & 7); + var D = (d >>> 3) + 4, q2 = N[D - 4] | N[D - 3] << 8; + if (Z2) + W = H.H.W(W, w + q2); + W.set(new R2(N.buffer, N.byteOffset + D, q2), w); + d = D + q2 << 3; + w += q2; + continue; + } + if (Z2) + W = H.H.W(W, w + (1 << 17)); + if (m == 1) { + v = b.J; + C4 = b.h; + X = (1 << 9) - 1; + u2 = (1 << 5) - 1; + } + if (m == 2) { + J2 = A2(N, d, 5) + 257; + h = A2(N, d + 5, 5) + 1; + Q2 = A2(N, d + 10, 4) + 4; + d += 14; + var E2 = d, j2 = 1; + for (var c = 0;c < 38; c += 2) { + b.Q[c] = 0; + b.Q[c + 1] = 0; + } + for (var c = 0;c < Q2; c++) { + var K = A2(N, d + c * 3, 3); + b.Q[(b.X[c] << 1) + 1] = K; + if (K > j2) + j2 = K; + } + d += 3 * Q2; + M(b.Q, j2); + I3(b.Q, j2, b.u); + v = b.w; + C4 = b.d; + d = l2(b.u, (1 << j2) - 1, J2 + h, N, d, b.v); + var r = V2.V(b.v, 0, J2, b.C); + X = (1 << r) - 1; + var S = V2.V(b.v, J2, h, b.D); + u2 = (1 << S) - 1; + M(b.C, r); + I3(b.C, r, v); + M(b.D, S); + I3(b.D, S, C4); + } + while (true) { + var T2 = v[e(N, d) & X]; + d += T2 & 15; + var p = T2 >>> 4; + if (p >>> 8 == 0) { + W[w++] = p; + } else if (p == 256) { + break; + } else { + var z = w + p - 254; + if (p > 264) { + var _2 = b.q[p - 257]; + z = w + (_2 >>> 3) + A2(N, d, _2 & 7); + d += _2 & 7; + } + var $2 = C4[e(N, d) & u2]; + d += $2 & 15; + var s = $2 >>> 4, Y = b.c[s], a = (Y >>> 4) + n2(N, d, Y & 15); + d += Y & 15; + while (w < z) { + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + W[w] = W[w++ - a]; + } + w = z; + } + } + } + return W.length == w ? W : W.slice(0, w); + }; + H.H.W = function(N, W) { + var R2 = N.length; + if (W <= R2) + return N; + var V2 = new Uint8Array(R2 << 1); + V2.set(N, 0); + return V2; + }; + H.H.R = function(N, W, R2, V2, n2, A2) { + var l2 = H.H.e, M = H.H.Z, I3 = 0; + while (I3 < R2) { + var e = N[M(V2, n2) & W]; + n2 += e & 15; + var b = e >>> 4; + if (b <= 15) { + A2[I3] = b; + I3++; + } else { + var Z2 = 0, m = 0; + if (b == 16) { + m = 3 + l2(V2, n2, 2); + n2 += 2; + Z2 = A2[I3 - 1]; + } else if (b == 17) { + m = 3 + l2(V2, n2, 3); + n2 += 3; + } else if (b == 18) { + m = 11 + l2(V2, n2, 7); + n2 += 7; + } + var J2 = I3 + m; + while (I3 < J2) { + A2[I3] = Z2; + I3++; + } + } + } + return n2; + }; + H.H.V = function(N, W, R2, V2) { + var n2 = 0, A2 = 0, l2 = V2.length >>> 1; + while (A2 < R2) { + var M = N[A2 + W]; + V2[A2 << 1] = 0; + V2[(A2 << 1) + 1] = M; + if (M > n2) + n2 = M; + A2++; + } + while (A2 < l2) { + V2[A2 << 1] = 0; + V2[(A2 << 1) + 1] = 0; + A2++; + } + return n2; + }; + H.H.n = function(N, W) { + var R2 = H.H.m, V2 = N.length, n2, A2, l2, M, I3, e = R2.j; + for (var M = 0;M <= W; M++) + e[M] = 0; + for (M = 1;M < V2; M += 2) + e[N[M]]++; + var b = R2.K; + n2 = 0; + e[0] = 0; + for (A2 = 1;A2 <= W; A2++) { + n2 = n2 + e[A2 - 1] << 1; + b[A2] = n2; + } + for (l2 = 0;l2 < V2; l2 += 2) { + I3 = N[l2 + 1]; + if (I3 != 0) { + N[l2] = b[I3]; + b[I3]++; + } + } + }; + H.H.A = function(N, W, R2) { + var V2 = N.length, n2 = H.H.m, A2 = n2.r; + for (var l2 = 0;l2 < V2; l2 += 2) + if (N[l2 + 1] != 0) { + var M = l2 >> 1, I3 = N[l2 + 1], e = M << 4 | I3, b = W - I3, Z2 = N[l2] << b, m = Z2 + (1 << b); + while (Z2 != m) { + var J2 = A2[Z2] >>> 15 - W; + R2[J2] = e; + Z2++; + } + } + }; + H.H.l = function(N, W) { + var R2 = H.H.m.r, V2 = 15 - W; + for (var n2 = 0;n2 < N.length; n2 += 2) { + var A2 = N[n2] << W - N[n2 + 1]; + N[n2] = R2[A2] >>> V2; + } + }; + H.H.M = function(N, W, R2) { + R2 = R2 << (W & 7); + var V2 = W >>> 3; + N[V2] |= R2; + N[V2 + 1] |= R2 >>> 8; + }; + H.H.I = function(N, W, R2) { + R2 = R2 << (W & 7); + var V2 = W >>> 3; + N[V2] |= R2; + N[V2 + 1] |= R2 >>> 8; + N[V2 + 2] |= R2 >>> 16; + }; + H.H.e = function(N, W, R2) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8) >>> (W & 7) & (1 << R2) - 1; + }; + H.H.b = function(N, W, R2) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7) & (1 << R2) - 1; + }; + H.H.Z = function(N, W) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16) >>> (W & 7); + }; + H.H.i = function(N, W) { + return (N[W >>> 3] | N[(W >>> 3) + 1] << 8 | N[(W >>> 3) + 2] << 16 | N[(W >>> 3) + 3] << 24) >>> (W & 7); + }; + H.H.m = function() { + var N = Uint16Array, W = Uint32Array; + return { K: new N(16), j: new N(16), X: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15], S: [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, 999, 999, 999], T: [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, 0, 0, 0], q: new N(32), 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, 65535, 65535], z: [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, 0, 0], c: new W(32), J: new N(512), _: [], h: new N(32), $: [], w: new N(32768), C: [], v: [], d: new N(32768), D: [], u: new N(512), Q: [], r: new N(1 << 15), s: new W(286), Y: new W(30), a: new W(19), t: new W(15000), k: new N(1 << 16), g: new N(1 << 15) }; + }(); + (function() { + var N = H.H.m, W = 1 << 15; + for (var R2 = 0;R2 < W; R2++) { + var V2 = R2; + V2 = (V2 & 2863311530) >>> 1 | (V2 & 1431655765) << 1; + V2 = (V2 & 3435973836) >>> 2 | (V2 & 858993459) << 2; + V2 = (V2 & 4042322160) >>> 4 | (V2 & 252645135) << 4; + V2 = (V2 & 4278255360) >>> 8 | (V2 & 16711935) << 8; + N.r[R2] = (V2 >>> 16 | V2 << 16) >>> 17; + } + function n2(A2, l2, M) { + while (l2-- != 0) + A2.push(0, M); + } + for (var R2 = 0;R2 < 32; R2++) { + N.q[R2] = N.S[R2] << 3 | N.T[R2]; + N.c[R2] = N.p[R2] << 4 | N.z[R2]; + } + n2(N._, 144, 8); + n2(N._, 255 - 143, 9); + n2(N._, 279 - 255, 7); + n2(N._, 287 - 279, 8); + H.H.n(N._, 9); + H.H.A(N._, 9, N.J); + H.H.l(N._, 9); + n2(N.$, 32, 5); + H.H.n(N.$, 5); + H.H.A(N.$, 5, N.h); + H.H.l(N.$, 5); + n2(N.Q, 19, 0); + n2(N.C, 286, 0); + n2(N.D, 30, 0); + n2(N.v, 320, 0); + })(); + return H.H.N; +}(); +UTIF.LosslessJpegDecode = function() { + var b, O; + function l2() { + return b[O++]; + } + function m() { + return b[O++] << 8 | b[O++]; + } + function a0(h) { + var V2 = l2(), I3 = [0, 0, 0, 255], f = [], G2 = 8; + for (var w = 0;w < 16; w++) + f[w] = l2(); + for (var w = 0;w < 16; w++) { + for (var x2 = 0;x2 < f[w]; x2++) { + var T2 = z(I3, 0, w + 1, 1); + I3[T2 + 3] = l2(); + } + } + var E2 = new Uint8Array(1 << G2); + h[V2] = [new Uint8Array(I3), E2]; + for (var w = 0;w < 1 << G2; w++) { + var s = G2, _2 = w, Y = 0, F = 0; + while (I3[Y + 3] == 255 && s != 0) { + F = _2 >> --s & 1; + Y = I3[Y + F]; + } + E2[w] = Y; + } + } + function z(h, V2, I3, f) { + if (h[V2 + 3] != 255) + return 0; + if (I3 == 0) + return V2; + for (var w = 0;w < 2; w++) { + if (h[V2 + w] == 0) { + h[V2 + w] = h.length; + h.push(0, 0, f, 255); + } + var x2 = z(h, h[V2 + w], I3 - 1, f + 1); + if (x2 != 0) + return x2; + } + return 0; + } + function i(h) { + var { b: V2, f: I3 } = h; + while (V2 < 25 && h.a < h.d) { + var f = h.data[h.a++]; + if (f == 255 && !h.c) + h.a++; + I3 = I3 << 8 | f; + V2 += 8; + } + if (V2 < 0) + throw "e"; + h.b = V2; + h.f = I3; + } + function H(h, V2) { + if (V2.b < h) + i(V2); + return V2.f >> (V2.b -= h) & 65535 >> 16 - h; + } + function g3(h, V2) { + var I3 = h[0], f = 0, w = 255, x2 = 0; + if (V2.b < 16) + i(V2); + var T2 = V2.f >> V2.b - 8 & 255; + f = h[1][T2]; + w = I3[f + 3]; + V2.b -= I3[f + 2]; + while (w == 255) { + x2 = V2.f >> --V2.b & 1; + f = I3[f + x2]; + w = I3[f + 3]; + } + return w; + } + function P(h, V2) { + if (h < 32768 >> 16 - V2) + h += -(1 << V2) + 1; + return h; + } + function a2(h, V2) { + var I3 = g3(h, V2); + if (I3 == 0) + return 0; + if (I3 == 16) + return -32768; + var f = H(I3, V2); + return P(f, I3); + } + function X(h, V2, I3, f, w, x2) { + var T2 = 0; + for (var G2 = 0;G2 < x2; G2++) { + var s = G2 * V2; + for (var _2 = 0;_2 < V2; _2 += w) { + T2++; + for (var Y = 0;Y < w; Y++) + h[s + _2 + Y] = a2(f[Y], I3); + } + if (I3.e != 0 && T2 % I3.e == 0 && G2 != 0) { + var { a: F, data: t2 } = I3; + while (t2[F] != 255 || !(208 <= t2[F + 1] && t2[F + 1] <= 215)) + F--; + I3.a = F + 2; + I3.f = 0; + I3.b = 0; + } + } + } + function o(h, V2) { + return P(H(h, V2), h); + } + function a1(h, V2, I3, f, w) { + var x2 = b.length - O; + for (var T2 = 0;T2 < x2; T2 += 4) { + var G2 = b[O + T2]; + b[O + T2] = b[O + T2 + 3]; + b[O + T2 + 3] = G2; + var G2 = b[O + T2 + 1]; + b[O + T2 + 1] = b[O + T2 + 2]; + b[O + T2 + 2] = G2; + } + for (var E2 = 0;E2 < w; E2++) { + var s = 32768, _2 = 32768; + for (var Y = 0;Y < V2; Y += 2) { + var F = g3(f, I3), t2 = g3(f, I3); + if (F != 0) + s += o(F, I3); + if (t2 != 0) + _2 += o(t2, I3); + h[E2 * V2 + Y] = s & 65535; + h[E2 * V2 + Y + 1] = _2 & 65535; + } + } + } + function C4(h) { + b = h; + O = 0; + if (m() != 65496) + throw "e"; + var V2 = [], I3 = 0, f = 0, w = 0, x2 = [], T2 = [], G2 = [], E2 = 0, s = 0, _2 = 0; + while (true) { + var Y = m(); + if (Y == 65535) { + O--; + continue; + } + var F = m(); + if (Y == 65475) { + f = l2(); + s = m(); + _2 = m(); + E2 = l2(); + for (var t2 = 0;t2 < E2; t2++) { + var a = l2(), J2 = l2(), r = l2(); + if (r != 0) + throw "e"; + V2[a] = [t2, J2 >> 4, J2 & 15]; + } + } else if (Y == 65476) { + var a3 = O + F - 2; + while (O < a3) + a0(T2); + } else if (Y == 65498) { + O++; + for (var t2 = 0;t2 < E2; t2++) { + var a5 = l2(), v = V2[a5]; + G2[v[0]] = T2[l2() >>> 4]; + x2[v[0]] = v.slice(1); + } + I3 = l2(); + O += 2; + break; + } else if (Y == 65501) { + w = m(); + } else { + O += F - 2; + } + } + var a4 = f > 8 ? Uint16Array : Uint8Array, $2 = new a4(s * _2 * E2), M = { b: 0, f: 0, c: I3 == 8, a: O, data: b, d: b.length, e: w }; + if (M.c) + a1($2, _2 * E2, M, G2[0], s); + else { + var c = [], p = 0, D = 0; + for (var t2 = 0;t2 < E2; t2++) { + var N = x2[t2], S = N[0], K = N[1]; + if (S > p) + p = S; + if (K > D) + D = K; + c.push(S * K); + } + if (p != 1 || D != 1) { + if (E2 != 3 || c[1] != 1 || c[2] != 1) + throw "e"; + if (p != 2 || D != 1 && D != 2) + throw "e"; + var u2 = [], Z2 = 0; + for (var t2 = 0;t2 < E2; t2++) { + for (var R2 = 0;R2 < c[t2]; R2++) + u2.push(G2[t2]); + Z2 += c[t2]; + } + var B2 = _2 / p, e = s / D, d = B2 * e; + X($2, B2 * Z2, M, u2, Z2, e); + j2($2, I3, B2, e, Z2 - 2, Z2, Z2, f); + var A2 = new Uint16Array(d * c[0]); + if (p == 2 && D == 2) { + for (var t2 = 0;t2 < d; t2++) { + A2[4 * t2] = $2[6 * t2]; + A2[4 * t2 + 1] = $2[6 * t2 + 1]; + A2[4 * t2 + 2] = $2[6 * t2 + 2]; + A2[4 * t2 + 3] = $2[6 * t2 + 3]; + } + j2(A2, I3, B2 * 4, e, 0, 1, 1, f); + for (var t2 = 0;t2 < d; t2++) { + $2[6 * t2] = A2[4 * t2]; + $2[6 * t2 + 1] = A2[4 * t2 + 1]; + $2[6 * t2 + 2] = A2[4 * t2 + 2]; + $2[6 * t2 + 3] = A2[4 * t2 + 3]; + } + } + if (p == 2 && D == 1) { + for (var t2 = 0;t2 < d; t2++) { + A2[2 * t2] = $2[4 * t2]; + A2[2 * t2 + 1] = $2[4 * t2 + 1]; + } + j2(A2, I3, B2 * 2, e, 0, 1, 1, f); + for (var t2 = 0;t2 < d; t2++) { + $2[4 * t2] = A2[2 * t2]; + $2[4 * t2 + 1] = A2[2 * t2 + 1]; + } + } + var n2 = $2.slice(0); + for (var K = 0;K < s; K++) { + if (D == 2) + for (var S = 0;S < _2; S++) { + var q2 = (K * _2 + S) * E2, k2 = ((K >>> 1) * B2 + (S >>> 1)) * Z2, y = (K & 1) * 2 + (S & 1); + $2[q2] = n2[k2 + y]; + $2[q2 + 1] = n2[k2 + 4]; + $2[q2 + 2] = n2[k2 + 5]; + } + else + for (var S = 0;S < _2; S++) { + var q2 = (K * _2 + S) * E2, k2 = (K * B2 + (S >>> 1)) * Z2, y = S & 1; + $2[q2] = n2[k2 + y]; + $2[q2 + 1] = n2[k2 + 2]; + $2[q2 + 2] = n2[k2 + 3]; + } + } + } else { + X($2, _2 * E2, M, G2, E2, s); + if (w == 0) + j2($2, I3, _2, s, 0, E2, E2, f); + else { + var U = Math.floor(w / _2); + for (var K = 0;K < s; K += U) { + var L = $2.slice(K * _2 * E2, (K + U) * _2 * E2); + j2(L, I3, _2, U, 0, E2, E2, f); + $2.set(L, K * _2 * E2); + } + } + } + } + return $2; + } + function j2(h, V2, I3, f, w, x2, G2, E2) { + var s = I3 * G2; + for (var _2 = w;_2 < x2; _2++) + h[_2] += 1 << E2 - 1; + for (var Y = G2;Y < s; Y += G2) + for (var _2 = w;_2 < x2; _2++) + h[Y + _2] += h[Y + _2 - G2]; + for (var F = 1;F < f; F++) { + var t2 = F * s; + for (var _2 = w;_2 < x2; _2++) + h[t2 + _2] += h[t2 + _2 - s]; + for (var Y = G2;Y < s; Y += G2) { + for (var _2 = w;_2 < x2; _2++) { + var a = t2 + Y + _2, J2 = a - s, r = h[a - G2], Q2 = 0; + if (V2 == 0) + Q2 = 0; + else if (V2 == 1) + Q2 = r; + else if (V2 == 2) + Q2 = h[J2]; + else if (V2 == 3) + Q2 = h[J2 - G2]; + else if (V2 == 4) + Q2 = r + (h[J2] - h[J2 - G2]); + else if (V2 == 5) + Q2 = r + (h[J2] - h[J2 - G2] >>> 1); + else if (V2 == 6) + Q2 = h[J2] + (r - h[J2 - G2] >>> 1); + else if (V2 == 7) + Q2 = r + h[J2] >>> 1; + else + throw V2; + h[a] += Q2; + } + } + } + } + return C4; +}(); +(function() { + var G2 = 0, F = 1, i = 2, b = 3, J2 = 4, N = 5, E2 = 6, s = 7, c = 8, T2 = 9, a3 = 10, f = 11, q2 = 12, M = 13, m = 14, x2 = 15, L = 16, $2 = 17, p = 18; + function a5(t2) { + var Z2 = UTIF._binBE.readUshort, u2 = { b: Z2(t2, 0), i: t2[2], C: t2[3], u: t2[4], q: Z2(t2, 5), k: Z2(t2, 7), e: Z2(t2, 9), l: Z2(t2, 11), s: t2[13], d: Z2(t2, 14) }; + if (u2.b != 18771 || u2.i > 1 || u2.q < 6 || u2.q % 6 || u2.e < 768 || u2.e % 24 || u2.l != 768 || u2.k < u2.l || u2.k % u2.l || u2.k - u2.e >= u2.l || u2.s > 16 || u2.s != u2.k / u2.l || u2.s != Math.ceil(u2.e / u2.l) || u2.d != u2.q / 6 || u2.u != 12 && u2.u != 14 && u2.u != 16 || u2.C != 16 && u2.C != 0) { + throw "Invalid data"; + } + if (u2.i == 0) { + throw "Not implemented. We need this file!"; + } + u2.h = u2.C == 16; + u2.m = (u2.h ? u2.l * 2 / 3 : u2.l >>> 1) | 0; + u2.A = u2.m + 2; + u2.f = 64; + u2.g = (1 << u2.u) - 1; + u2.n = 4 * u2.u; + return u2; + } + function a7(t2, Z2) { + var u2 = new Array(Z2.s), e = 4 * Z2.s, Q2 = 16 + e; + if (e & 12) + Q2 += 16 - (e & 12); + for (var V2 = 0, O = 16;V2 < Z2.s; O += 4) { + var o = UTIF._binBE.readUint(t2, O); + u2[V2] = t2.slice(Q2, Q2 + o); + u2[V2].j = 0; + u2[V2].a = 0; + Q2 += o; + V2++; + } + if (Q2 != t2.length) + throw "Invalid data"; + return u2; + } + function a6(t2, Z2) { + for (var u2 = -Z2[4], e = 0;u2 <= Z2[4]; e++, u2++) { + t2[e] = u2 <= -Z2[3] ? -4 : u2 <= -Z2[2] ? -3 : u2 <= -Z2[1] ? -2 : u2 < -Z2[0] ? -1 : u2 <= Z2[0] ? 0 : u2 < Z2[1] ? 1 : u2 < Z2[2] ? 2 : u2 < Z2[3] ? 3 : 4; + } + } + function a1(t2, Z2, u2) { + var e = [Z2, 3 * Z2 + 18, 5 * Z2 + 67, 7 * Z2 + 276, u2]; + t2.o = Z2; + t2.w = (e[4] + 2 * Z2) / (2 * Z2 + 1) + 1 | 0; + t2.v = Math.ceil(Math.log2(t2.w)); + t2.t = 9; + a6(t2.c, e); + } + function a2(t2) { + var Z2 = { c: new Int8Array(2 << t2.u) }; + a1(Z2, 0, t2.g); + return Z2; + } + function D(t2) { + var Z2 = [[], [], []], u2 = Math.max(2, t2.w + 32 >>> 6); + for (var e = 0;e < 3; e++) { + for (var Q2 = 0;Q2 < 41; Q2++) { + Z2[e][Q2] = [u2, 1]; + } + } + return Z2; + } + function a4(t2) { + for (var Z2 = -1, u2 = 0;!u2; Z2++) { + u2 = t2[t2.j] >>> 7 - t2.a & 1; + t2.a++; + t2.a &= 7; + if (!t2.a) + t2.j++; + } + return Z2; + } + function K(t2, Z2) { + var u2 = 0, e = 8 - t2.a, Q2 = t2.j, V2 = t2.a; + if (Z2) { + if (Z2 >= e) { + do { + u2 <<= e; + Z2 -= e; + u2 |= t2[t2.j] & (1 << e) - 1; + t2.j++; + e = 8; + } while (Z2 >= 8); + } + if (Z2) { + u2 <<= Z2; + e -= Z2; + u2 |= t2[t2.j] >>> e & (1 << Z2) - 1; + } + t2.a = 8 - e; + } + return u2; + } + function a0(t2, Z2) { + var u2 = 0; + if (Z2 < t2) { + while (u2 <= 14 && Z2 << ++u2 < t2) + ; + } + return u2; + } + function r(t2, Z2, u2, e, Q2, V2, O, o) { + if (o == null) + o = 0; + var X = V2 + 1, k2 = X % 2, j2 = 0, I3 = 0, a = 0, l2, R2, w = e[Q2], S = e[Q2 - 1], H = e[Q2 - 2][X], g3 = S[X - 1], Y = S[X], P = S[X + 1], A2 = w[X - 1], v = w[X + 1], y = Math.abs, d, C4, n2, h; + if (k2) { + d = y(P - Y); + C4 = y(H - Y); + n2 = y(g3 - Y); + } + if (k2) { + h = d > n2 && C4 < d ? H + g3 : d < n2 && C4 < n2 ? H + P : P + g3; + h = h + 2 * Y >>> 2; + if (o) { + w[X] = h; + return; + } + l2 = Z2.t * Z2.c[t2.g + Y - H] + Z2.c[t2.g + g3 - Y]; + } else { + h = Y > g3 && Y > P || Y < g3 && Y < P ? v + A2 + 2 * Y >>> 2 : A2 + v >>> 1; + l2 = Z2.t * Z2.c[t2.g + Y - g3] + Z2.c[t2.g + g3 - A2]; + } + R2 = y(l2); + var W = a4(u2); + if (W < t2.n - Z2.v - 1) { + var z = a0(O[R2][0], O[R2][1]); + a = K(u2, z) + (W << z); + } else { + a = K(u2, Z2.v) + 1; + } + a = a & 1 ? -1 - (a >>> 1) : a >>> 1; + O[R2][0] += y(a); + if (O[R2][1] == t2.f) { + O[R2][0] >>>= 1; + O[R2][1] >>>= 1; + } + O[R2][1]++; + h = l2 < 0 ? h - a : h + a; + if (t2.i) { + if (h < 0) + h += Z2.w; + else if (h > t2.g) + h -= Z2.w; + } + w[X] = h >= 0 ? Math.min(h, t2.g) : 0; + } + function U(t2, Z2, u2) { + var e = t2[0].length; + for (var Q2 = Z2;Q2 <= u2; Q2++) { + t2[Q2][0] = t2[Q2 - 1][1]; + t2[Q2][e - 1] = t2[Q2 - 1][e - 2]; + } + } + function B2(t2) { + U(t2, s, q2); + U(t2, i, J2); + U(t2, x2, $2); + } + function _2(t2, Z2, u2, e, Q2, V2, O, o, X, k2, j2, I3, a) { + var l2 = 0, R2 = 1, w = Q2 < M && Q2 > J2; + while (R2 < t2.m) { + if (l2 < t2.m) { + r(t2, Z2, u2, e, Q2, l2, O[X], t2.h && (w && k2 || !w && (j2 || (l2 & I3) == a))); + r(t2, Z2, u2, e, V2, l2, O[X], t2.h && (!w && k2 || w && (j2 || (l2 & I3) == a))); + l2 += 2; + } + if (l2 > 8) { + r(t2, Z2, u2, e, Q2, R2, o[X]); + r(t2, Z2, u2, e, V2, R2, o[X]); + R2 += 2; + } + } + B2(e); + } + function a8(t2, Z2, u2, e, Q2, V2) { + _2(t2, Z2, u2, e, i, s, Q2, V2, 0, 0, 1, 0, 8); + _2(t2, Z2, u2, e, c, x2, Q2, V2, 1, 0, 1, 0, 8); + _2(t2, Z2, u2, e, b, T2, Q2, V2, 2, 1, 0, 3, 0); + _2(t2, Z2, u2, e, a3, L, Q2, V2, 0, 0, 0, 3, 2); + _2(t2, Z2, u2, e, J2, f, Q2, V2, 1, 0, 0, 3, 2); + _2(t2, Z2, u2, e, q2, $2, Q2, V2, 2, 1, 0, 3, 0); + } + function a9(t2, Z2, u2, e, Q2, V2) { + var O = V2.length, o = t2.l; + if (Q2 + 1 == t2.s) + o = t2.e - Q2 * t2.l; + var X = 6 * t2.e * e + Q2 * t2.l; + for (var k2 = 0;k2 < 6; k2++) { + for (var j2 = 0;j2 < o; j2++) { + var I3 = V2[k2 % O][j2 % O], a; + if (I3 == 0) { + a = i + (k2 >>> 1); + } else if (I3 == 2) { + a = x2 + (k2 >>> 1); + } else { + a = s + k2; + } + var l2 = t2.h ? (j2 * 2 / 3 & 2147483646 | j2 % 3 & 1) + (j2 % 3 >>> 1) : j2 >>> 1; + Z2[X + j2] = u2[a][l2 + 1]; + } + X += t2.e; + } + } + UTIF._decompressRAF = function(t2, Z2) { + var u2 = a5(t2), e = a7(t2, u2), Q2 = a2(u2), V2 = new Int16Array(u2.e * u2.q); + if (Z2 == null) { + Z2 = u2.h ? [[1, 1, 0, 1, 1, 2], [1, 1, 2, 1, 1, 0], [2, 0, 1, 0, 2, 1], [1, 1, 2, 1, 1, 0], [1, 1, 0, 1, 1, 2], [0, 2, 1, 2, 0, 1]] : [[0, 1], [3, 2]]; + } + var O = [[G2, b], [F, J2], [N, f], [E2, q2], [M, L], [m, $2]], o = []; + for (var X = 0;X < p; X++) { + o[X] = new Uint16Array(u2.A); + } + for (var k2 = 0;k2 < u2.s; k2++) { + var j2 = D(Q2), I3 = D(Q2); + for (var X = 0;X < p; X++) { + for (var a = 0;a < u2.A; a++) { + o[X][a] = 0; + } + } + for (var l2 = 0;l2 < u2.d; l2++) { + a8(u2, Q2, e[k2], o, j2, I3); + for (var X = 0;X < 6; X++) { + for (var a = 0;a < u2.A; a++) { + o[O[X][0]][a] = o[O[X][1]][a]; + } + } + a9(u2, V2, o, l2, k2, Z2); + for (var X = i;X < p; X++) { + if ([N, E2, M, m].indexOf(X) == -1) { + for (var a = 0;a < u2.A; a++) { + o[X][a] = 0; + } + } + } + B2(o); + } + } + return V2; + }; +})(); +// node_modules/three/examples/jsm/libs/opentype.module.js +/*! https://mths.be/codepointat v0.2.0 by @mathias */ +if (!String.prototype.codePointAt) { + (function() { + var defineProperty = function() { + try { + var object = {}; + var $defineProperty = Object.defineProperty; + var result = $defineProperty(object, object, object) && $defineProperty; + } catch (error) { + } + return result; + }(); + var codePointAt = function(position2) { + if (this == null) { + throw TypeError(); + } + var string = String(this); + var size = string.length; + var index2 = position2 ? Number(position2) : 0; + if (index2 != index2) { + index2 = 0; + } + if (index2 < 0 || index2 >= size) { + return; + } + var first2 = string.charCodeAt(index2); + var second; + if (first2 >= 55296 && first2 <= 56319 && size > index2 + 1) { + second = string.charCodeAt(index2 + 1); + if (second >= 56320 && second <= 57343) { + return (first2 - 55296) * 1024 + second - 56320 + 65536; + } + } + return first2; + }; + if (defineProperty) { + defineProperty(String.prototype, "codePointAt", { + value: codePointAt, + configurable: true, + writable: true + }); + } else { + String.prototype.codePointAt = codePointAt; + } + })(); +} +function Tree() { + this.table = new Uint16Array(16); + this.trans = new Uint16Array(288); +} +var sltree = new Tree; +var sdtree = new Tree; +var length_bits = new Uint8Array(30); +var length_base = new Uint16Array(30); +var dist_bits = new Uint8Array(30); +var dist_base = new Uint16Array(30); +var clcidx = new Uint8Array([ + 16, + 17, + 18, + 0, + 8, + 7, + 9, + 6, + 10, + 5, + 11, + 4, + 12, + 3, + 13, + 2, + 14, + 1, + 15 +]); +var code_tree = new Tree; +var lengths = new Uint8Array(288 + 32); +function tinf_build_bits_base(bits, base, delta, first2) { + var i, sum2; + for (i = 0;i < delta; ++i) { + bits[i] = 0; + } + for (i = 0;i < 30 - delta; ++i) { + bits[i + delta] = i / delta | 0; + } + for (sum2 = first2, i = 0;i < 30; ++i) { + base[i] = sum2; + sum2 += 1 << bits[i]; + } +} +function tinf_build_fixed_trees(lt, dt) { + var i; + for (i = 0;i < 7; ++i) { + lt.table[i] = 0; + } + lt.table[7] = 24; + lt.table[8] = 152; + lt.table[9] = 112; + for (i = 0;i < 24; ++i) { + lt.trans[i] = 256 + i; + } + for (i = 0;i < 144; ++i) { + lt.trans[24 + i] = i; + } + for (i = 0;i < 8; ++i) { + lt.trans[24 + 144 + i] = 280 + i; + } + for (i = 0;i < 112; ++i) { + lt.trans[24 + 144 + 8 + i] = 144 + i; + } + for (i = 0;i < 5; ++i) { + dt.table[i] = 0; + } + dt.table[5] = 32; + for (i = 0;i < 32; ++i) { + dt.trans[i] = i; + } +} +var offs = new Uint16Array(16); +tinf_build_fixed_trees(sltree, sdtree); +tinf_build_bits_base(length_bits, length_base, 4, 3); +tinf_build_bits_base(dist_bits, dist_base, 2, 1); +length_bits[28] = 0; +length_base[28] = 258; +function derive(v0, v1, v2, v3, t2) { + return Math.pow(1 - t2, 3) * v0 + 3 * Math.pow(1 - t2, 2) * t2 * v1 + 3 * (1 - t2) * Math.pow(t2, 2) * v2 + Math.pow(t2, 3) * v3; +} +function BoundingBox() { + this.x1 = Number.NaN; + this.y1 = Number.NaN; + this.x2 = Number.NaN; + this.y2 = Number.NaN; +} +BoundingBox.prototype.isEmpty = function() { + return isNaN(this.x1) || isNaN(this.y1) || isNaN(this.x2) || isNaN(this.y2); +}; +BoundingBox.prototype.addPoint = function(x2, y) { + if (typeof x2 === "number") { + if (isNaN(this.x1) || isNaN(this.x2)) { + this.x1 = x2; + this.x2 = x2; + } + if (x2 < this.x1) { + this.x1 = x2; + } + if (x2 > this.x2) { + this.x2 = x2; + } + } + if (typeof y === "number") { + if (isNaN(this.y1) || isNaN(this.y2)) { + this.y1 = y; + this.y2 = y; + } + if (y < this.y1) { + this.y1 = y; + } + if (y > this.y2) { + this.y2 = y; + } + } +}; +BoundingBox.prototype.addX = function(x2) { + this.addPoint(x2, null); +}; +BoundingBox.prototype.addY = function(y) { + this.addPoint(null, y); +}; +BoundingBox.prototype.addBezier = function(x0, y0, x1, y1, x2, y2, x3, y) { + var p0 = [x0, y0]; + var p1 = [x1, y1]; + var p2 = [x2, y2]; + var p3 = [x3, y]; + this.addPoint(x0, y0); + this.addPoint(x3, y); + for (var i = 0;i <= 1; i++) { + var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; + var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; + var c = 3 * p1[i] - 3 * p0[i]; + if (a === 0) { + if (b === 0) { + continue; + } + var t2 = -c / b; + if (0 < t2 && t2 < 1) { + if (i === 0) { + this.addX(derive(p0[i], p1[i], p2[i], p3[i], t2)); + } + if (i === 1) { + this.addY(derive(p0[i], p1[i], p2[i], p3[i], t2)); + } + } + continue; + } + var b2ac = Math.pow(b, 2) - 4 * c * a; + if (b2ac < 0) { + continue; + } + var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); + if (0 < t1 && t1 < 1) { + if (i === 0) { + this.addX(derive(p0[i], p1[i], p2[i], p3[i], t1)); + } + if (i === 1) { + this.addY(derive(p0[i], p1[i], p2[i], p3[i], t1)); + } + } + var t22 = (-b - Math.sqrt(b2ac)) / (2 * a); + if (0 < t22 && t22 < 1) { + if (i === 0) { + this.addX(derive(p0[i], p1[i], p2[i], p3[i], t22)); + } + if (i === 1) { + this.addY(derive(p0[i], p1[i], p2[i], p3[i], t22)); + } + } + } +}; +BoundingBox.prototype.addQuad = function(x0, y0, x1, y1, x2, y) { + var cp1x = x0 + 2 / 3 * (x1 - x0); + var cp1y = y0 + 2 / 3 * (y1 - y0); + var cp2x = cp1x + 1 / 3 * (x2 - x0); + var cp2y = cp1y + 1 / 3 * (y - y0); + this.addBezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x2, y); +}; +function Path2() { + this.commands = []; + this.fill = "black"; + this.stroke = null; + this.strokeWidth = 1; +} +Path2.prototype.moveTo = function(x2, y) { + this.commands.push({ + type: "M", + x: x2, + y + }); +}; +Path2.prototype.lineTo = function(x2, y) { + this.commands.push({ + type: "L", + x: x2, + y + }); +}; +Path2.prototype.curveTo = Path2.prototype.bezierCurveTo = function(x1, y1, x2, y2, x3, y) { + this.commands.push({ + type: "C", + x1, + y1, + x2, + y2, + x: x3, + y + }); +}; +Path2.prototype.quadTo = Path2.prototype.quadraticCurveTo = function(x1, y1, x2, y) { + this.commands.push({ + type: "Q", + x1, + y1, + x: x2, + y + }); +}; +Path2.prototype.close = Path2.prototype.closePath = function() { + this.commands.push({ + type: "Z" + }); +}; +Path2.prototype.extend = function(pathOrCommands) { + if (pathOrCommands.commands) { + pathOrCommands = pathOrCommands.commands; + } else if (pathOrCommands instanceof BoundingBox) { + var box = pathOrCommands; + this.moveTo(box.x1, box.y1); + this.lineTo(box.x2, box.y1); + this.lineTo(box.x2, box.y2); + this.lineTo(box.x1, box.y2); + this.close(); + return; + } + Array.prototype.push.apply(this.commands, pathOrCommands); +}; +Path2.prototype.getBoundingBox = function() { + var box = new BoundingBox; + var startX = 0; + var startY = 0; + var prevX = 0; + var prevY = 0; + for (var i = 0;i < this.commands.length; i++) { + var cmd = this.commands[i]; + switch (cmd.type) { + case "M": + box.addPoint(cmd.x, cmd.y); + startX = prevX = cmd.x; + startY = prevY = cmd.y; + break; + case "L": + box.addPoint(cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case "Q": + box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case "C": + box.addBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + prevX = cmd.x; + prevY = cmd.y; + break; + case "Z": + prevX = startX; + prevY = startY; + break; + default: + throw new Error("Unexpected path command " + cmd.type); + } + } + if (box.isEmpty()) { + box.addPoint(0, 0); + } + return box; +}; +Path2.prototype.draw = function(ctx) { + ctx.beginPath(); + for (var i = 0;i < this.commands.length; i += 1) { + var cmd = this.commands[i]; + if (cmd.type === "M") { + ctx.moveTo(cmd.x, cmd.y); + } else if (cmd.type === "L") { + ctx.lineTo(cmd.x, cmd.y); + } else if (cmd.type === "C") { + ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === "Q") { + ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); + } else if (cmd.type === "Z") { + ctx.closePath(); + } + } + if (this.fill) { + ctx.fillStyle = this.fill; + ctx.fill(); + } + if (this.stroke) { + ctx.strokeStyle = this.stroke; + ctx.lineWidth = this.strokeWidth; + ctx.stroke(); + } +}; +Path2.prototype.toPathData = function(decimalPlaces) { + decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2; + function floatToString(v) { + if (Math.round(v) === v) { + return "" + Math.round(v); + } else { + return v.toFixed(decimalPlaces); + } + } + function packValues() { + var arguments$1 = arguments; + var s = ""; + for (var i2 = 0;i2 < arguments.length; i2 += 1) { + var v = arguments$1[i2]; + if (v >= 0 && i2 > 0) { + s += " "; + } + s += floatToString(v); + } + return s; + } + var d = ""; + for (var i = 0;i < this.commands.length; i += 1) { + var cmd = this.commands[i]; + if (cmd.type === "M") { + d += "M" + packValues(cmd.x, cmd.y); + } else if (cmd.type === "L") { + d += "L" + packValues(cmd.x, cmd.y); + } else if (cmd.type === "C") { + d += "C" + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); + } else if (cmd.type === "Q") { + d += "Q" + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y); + } else if (cmd.type === "Z") { + d += "Z"; + } + } + return d; +}; +Path2.prototype.toSVG = function(decimalPlaces) { + var svg = '= 0 && v <= 255, "Byte value should be between 0 and 255."); + return [v]; +}; +sizeOf.BYTE = constant(1); +encode.CHAR = function(v) { + return [v.charCodeAt(0)]; +}; +sizeOf.CHAR = constant(1); +encode.CHARARRAY = function(v) { + if (typeof v === "undefined") { + v = ""; + console.warn("Undefined CHARARRAY encountered and treated as an empty string. This is probably caused by a missing glyph name."); + } + var b = []; + for (var i = 0;i < v.length; i += 1) { + b[i] = v.charCodeAt(i); + } + return b; +}; +sizeOf.CHARARRAY = function(v) { + if (typeof v === "undefined") { + return 0; + } + return v.length; +}; +encode.USHORT = function(v) { + return [v >> 8 & 255, v & 255]; +}; +sizeOf.USHORT = constant(2); +encode.SHORT = function(v) { + if (v >= LIMIT16) { + v = -(2 * LIMIT16 - v); + } + return [v >> 8 & 255, v & 255]; +}; +sizeOf.SHORT = constant(2); +encode.UINT24 = function(v) { + return [v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.UINT24 = constant(3); +encode.ULONG = function(v) { + return [v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.ULONG = constant(4); +encode.LONG = function(v) { + if (v >= LIMIT32) { + v = -(2 * LIMIT32 - v); + } + return [v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.LONG = constant(4); +encode.FIXED = encode.ULONG; +sizeOf.FIXED = sizeOf.ULONG; +encode.FWORD = encode.SHORT; +sizeOf.FWORD = sizeOf.SHORT; +encode.UFWORD = encode.USHORT; +sizeOf.UFWORD = sizeOf.USHORT; +encode.LONGDATETIME = function(v) { + return [0, 0, 0, 0, v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.LONGDATETIME = constant(8); +encode.TAG = function(v) { + check.argument(v.length === 4, "Tag should be exactly 4 ASCII characters."); + return [ + v.charCodeAt(0), + v.charCodeAt(1), + v.charCodeAt(2), + v.charCodeAt(3) + ]; +}; +sizeOf.TAG = constant(4); +encode.Card8 = encode.BYTE; +sizeOf.Card8 = sizeOf.BYTE; +encode.Card16 = encode.USHORT; +sizeOf.Card16 = sizeOf.USHORT; +encode.OffSize = encode.BYTE; +sizeOf.OffSize = sizeOf.BYTE; +encode.SID = encode.USHORT; +sizeOf.SID = sizeOf.USHORT; +encode.NUMBER = function(v) { + if (v >= -107 && v <= 107) { + return [v + 139]; + } else if (v >= 108 && v <= 1131) { + v = v - 108; + return [(v >> 8) + 247, v & 255]; + } else if (v >= -1131 && v <= -108) { + v = -v - 108; + return [(v >> 8) + 251, v & 255]; + } else if (v >= -32768 && v <= 32767) { + return encode.NUMBER16(v); + } else { + return encode.NUMBER32(v); + } +}; +sizeOf.NUMBER = function(v) { + return encode.NUMBER(v).length; +}; +encode.NUMBER16 = function(v) { + return [28, v >> 8 & 255, v & 255]; +}; +sizeOf.NUMBER16 = constant(3); +encode.NUMBER32 = function(v) { + return [29, v >> 24 & 255, v >> 16 & 255, v >> 8 & 255, v & 255]; +}; +sizeOf.NUMBER32 = constant(5); +encode.REAL = function(v) { + var value2 = v.toString(); + var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value2); + if (m) { + var epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length)); + value2 = (Math.round(v * epsilon) / epsilon).toString(); + } + var nibbles = ""; + for (var i = 0, ii = value2.length;i < ii; i += 1) { + var c = value2[i]; + if (c === "e") { + nibbles += value2[++i] === "-" ? "c" : "b"; + } else if (c === ".") { + nibbles += "a"; + } else if (c === "-") { + nibbles += "e"; + } else { + nibbles += c; + } + } + nibbles += nibbles.length & 1 ? "f" : "ff"; + var out = [30]; + for (var i$1 = 0, ii$1 = nibbles.length;i$1 < ii$1; i$1 += 2) { + out.push(parseInt(nibbles.substr(i$1, 2), 16)); + } + return out; +}; +sizeOf.REAL = function(v) { + return encode.REAL(v).length; +}; +encode.NAME = encode.CHARARRAY; +sizeOf.NAME = sizeOf.CHARARRAY; +encode.STRING = encode.CHARARRAY; +sizeOf.STRING = sizeOf.CHARARRAY; +decode.UTF8 = function(data2, offset, numBytes) { + var codePoints = []; + var numChars = numBytes; + for (var j2 = 0;j2 < numChars; j2++, offset += 1) { + codePoints[j2] = data2.getUint8(offset); + } + return String.fromCharCode.apply(null, codePoints); +}; +decode.UTF16 = function(data2, offset, numBytes) { + var codePoints = []; + var numChars = numBytes / 2; + for (var j2 = 0;j2 < numChars; j2++, offset += 2) { + codePoints[j2] = data2.getUint16(offset); + } + return String.fromCharCode.apply(null, codePoints); +}; +encode.UTF16 = function(v) { + var b = []; + for (var i = 0;i < v.length; i += 1) { + var codepoint = v.charCodeAt(i); + b[b.length] = codepoint >> 8 & 255; + b[b.length] = codepoint & 255; + } + return b; +}; +sizeOf.UTF16 = function(v) { + return v.length * 2; +}; +var eightBitMacEncodings = { + "x-mac-croatian": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø" + "¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ", + "x-mac-cyrillic": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ" + "јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю", + "x-mac-gaelic": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø" + "ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ", + "x-mac-greek": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ" + "άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­", + "x-mac-icelandic": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø" + "¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", + "x-mac-inuit": "ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ" + "ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł", + "x-mac-ce": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ" + "ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ", + macintosh: "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø" + "¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", + "x-mac-romanian": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș" + "¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ", + "x-mac-turkish": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø" + "¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ" +}; +decode.MACSTRING = function(dataView, offset, dataLength, encoding) { + var table = eightBitMacEncodings[encoding]; + if (table === undefined) { + return; + } + var result = ""; + for (var i = 0;i < dataLength; i++) { + var c = dataView.getUint8(offset + i); + if (c <= 127) { + result += String.fromCharCode(c); + } else { + result += table[c & 127]; + } + } + return result; +}; +var macEncodingTableCache = typeof WeakMap === "function" && new WeakMap; +var macEncodingCacheKeys; +var getMacEncodingTable = function(encoding) { + if (!macEncodingCacheKeys) { + macEncodingCacheKeys = {}; + for (var e in eightBitMacEncodings) { + macEncodingCacheKeys[e] = new String(e); + } + } + var cacheKey = macEncodingCacheKeys[encoding]; + if (cacheKey === undefined) { + return; + } + if (macEncodingTableCache) { + var cachedTable = macEncodingTableCache.get(cacheKey); + if (cachedTable !== undefined) { + return cachedTable; + } + } + var decodingTable = eightBitMacEncodings[encoding]; + if (decodingTable === undefined) { + return; + } + var encodingTable = {}; + for (var i = 0;i < decodingTable.length; i++) { + encodingTable[decodingTable.charCodeAt(i)] = i + 128; + } + if (macEncodingTableCache) { + macEncodingTableCache.set(cacheKey, encodingTable); + } + return encodingTable; +}; +encode.MACSTRING = function(str, encoding) { + var table = getMacEncodingTable(encoding); + if (table === undefined) { + return; + } + var result = []; + for (var i = 0;i < str.length; i++) { + var c = str.charCodeAt(i); + if (c >= 128) { + c = table[c]; + if (c === undefined) { + return; + } + } + result[i] = c; + } + return result; +}; +sizeOf.MACSTRING = function(str, encoding) { + var b = encode.MACSTRING(str, encoding); + if (b !== undefined) { + return b.length; + } else { + return 0; + } +}; +function isByteEncodable(value2) { + return value2 >= -128 && value2 <= 127; +} +function encodeVarDeltaRunAsZeroes(deltas, pos, result) { + var runLength = 0; + var numDeltas = deltas.length; + while (pos < numDeltas && runLength < 64 && deltas[pos] === 0) { + ++pos; + ++runLength; + } + result.push(128 | runLength - 1); + return pos; +} +function encodeVarDeltaRunAsBytes(deltas, offset, result) { + var runLength = 0; + var numDeltas = deltas.length; + var pos = offset; + while (pos < numDeltas && runLength < 64) { + var value2 = deltas[pos]; + if (!isByteEncodable(value2)) { + break; + } + if (value2 === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) { + break; + } + ++pos; + ++runLength; + } + result.push(runLength - 1); + for (var i = offset;i < pos; ++i) { + result.push(deltas[i] + 256 & 255); + } + return pos; +} +function encodeVarDeltaRunAsWords(deltas, offset, result) { + var runLength = 0; + var numDeltas = deltas.length; + var pos = offset; + while (pos < numDeltas && runLength < 64) { + var value2 = deltas[pos]; + if (value2 === 0) { + break; + } + if (isByteEncodable(value2) && pos + 1 < numDeltas && isByteEncodable(deltas[pos + 1])) { + break; + } + ++pos; + ++runLength; + } + result.push(64 | runLength - 1); + for (var i = offset;i < pos; ++i) { + var val2 = deltas[i]; + result.push(val2 + 65536 >> 8 & 255, val2 + 256 & 255); + } + return pos; +} +encode.VARDELTAS = function(deltas) { + var pos = 0; + var result = []; + while (pos < deltas.length) { + var value2 = deltas[pos]; + if (value2 === 0) { + pos = encodeVarDeltaRunAsZeroes(deltas, pos, result); + } else if (value2 >= -128 && value2 <= 127) { + pos = encodeVarDeltaRunAsBytes(deltas, pos, result); + } else { + pos = encodeVarDeltaRunAsWords(deltas, pos, result); + } + } + return result; +}; +encode.INDEX = function(l2) { + var offset = 1; + var offsets = [offset]; + var data2 = []; + for (var i = 0;i < l2.length; i += 1) { + var v = encode.OBJECT(l2[i]); + Array.prototype.push.apply(data2, v); + offset += v.length; + offsets.push(offset); + } + if (data2.length === 0) { + return [0, 0]; + } + var encodedOffsets = []; + var offSize = 1 + Math.floor(Math.log(offset) / Math.log(2)) / 8 | 0; + var offsetEncoder = [undefined, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize]; + for (var i$1 = 0;i$1 < offsets.length; i$1 += 1) { + var encodedOffset = offsetEncoder(offsets[i$1]); + Array.prototype.push.apply(encodedOffsets, encodedOffset); + } + return Array.prototype.concat(encode.Card16(l2.length), encode.OffSize(offSize), encodedOffsets, data2); +}; +sizeOf.INDEX = function(v) { + return encode.INDEX(v).length; +}; +encode.DICT = function(m) { + var d = []; + var keys2 = Object.keys(m); + var length2 = keys2.length; + for (var i = 0;i < length2; i += 1) { + var k2 = parseInt(keys2[i], 0); + var v = m[k2]; + d = d.concat(encode.OPERAND(v.value, v.type)); + d = d.concat(encode.OPERATOR(k2)); + } + return d; +}; +sizeOf.DICT = function(m) { + return encode.DICT(m).length; +}; +encode.OPERATOR = function(v) { + if (v < 1200) { + return [v]; + } else { + return [12, v - 1200]; + } +}; +encode.OPERAND = function(v, type) { + var d = []; + if (Array.isArray(type)) { + for (var i = 0;i < type.length; i += 1) { + check.argument(v.length === type.length, "Not enough arguments given for type" + type); + d = d.concat(encode.OPERAND(v[i], type[i])); + } + } else { + if (type === "SID") { + d = d.concat(encode.NUMBER(v)); + } else if (type === "offset") { + d = d.concat(encode.NUMBER32(v)); + } else if (type === "number") { + d = d.concat(encode.NUMBER(v)); + } else if (type === "real") { + d = d.concat(encode.REAL(v)); + } else { + throw new Error("Unknown operand type " + type); + } + } + return d; +}; +encode.OP = encode.BYTE; +sizeOf.OP = sizeOf.BYTE; +var wmm = typeof WeakMap === "function" && new WeakMap; +encode.CHARSTRING = function(ops) { + if (wmm) { + var cachedValue = wmm.get(ops); + if (cachedValue !== undefined) { + return cachedValue; + } + } + var d = []; + var length2 = ops.length; + for (var i = 0;i < length2; i += 1) { + var op = ops[i]; + d = d.concat(encode[op.type](op.value)); + } + if (wmm) { + wmm.set(ops, d); + } + return d; +}; +sizeOf.CHARSTRING = function(ops) { + return encode.CHARSTRING(ops).length; +}; +encode.OBJECT = function(v) { + var encodingFunction = encode[v.type]; + check.argument(encodingFunction !== undefined, "No encoding function for type " + v.type); + return encodingFunction(v.value); +}; +sizeOf.OBJECT = function(v) { + var sizeOfFunction = sizeOf[v.type]; + check.argument(sizeOfFunction !== undefined, "No sizeOf function for type " + v.type); + return sizeOfFunction(v.value); +}; +encode.TABLE = function(table) { + var d = []; + var length2 = table.fields.length; + var subtables = []; + var subtableOffsets = []; + for (var i = 0;i < length2; i += 1) { + var field = table.fields[i]; + var encodingFunction = encode[field.type]; + check.argument(encodingFunction !== undefined, "No encoding function for field type " + field.type + " (" + field.name + ")"); + var value2 = table[field.name]; + if (value2 === undefined) { + value2 = field.value; + } + var bytes = encodingFunction(value2); + if (field.type === "TABLE") { + subtableOffsets.push(d.length); + d = d.concat([0, 0]); + subtables.push(bytes); + } else { + d = d.concat(bytes); + } + } + for (var i$1 = 0;i$1 < subtables.length; i$1 += 1) { + var o = subtableOffsets[i$1]; + var offset = d.length; + check.argument(offset < 65536, "Table " + table.tableName + " too big."); + d[o] = offset >> 8; + d[o + 1] = offset & 255; + d = d.concat(subtables[i$1]); + } + return d; +}; +sizeOf.TABLE = function(table) { + var numBytes = 0; + var length2 = table.fields.length; + for (var i = 0;i < length2; i += 1) { + var field = table.fields[i]; + var sizeOfFunction = sizeOf[field.type]; + check.argument(sizeOfFunction !== undefined, "No sizeOf function for field type " + field.type + " (" + field.name + ")"); + var value2 = table[field.name]; + if (value2 === undefined) { + value2 = field.value; + } + numBytes += sizeOfFunction(value2); + if (field.type === "TABLE") { + numBytes += 2; + } + } + return numBytes; +}; +encode.RECORD = encode.TABLE; +sizeOf.RECORD = sizeOf.TABLE; +encode.LITERAL = function(v) { + return v; +}; +sizeOf.LITERAL = function(v) { + return v.length; +}; +function Table(tableName, fields, options) { + if (fields.length && (fields[0].name !== "coverageFormat" || fields[0].value === 1)) { + for (var i = 0;i < fields.length; i += 1) { + var field = fields[i]; + this[field.name] = field.value; + } + } + this.tableName = tableName; + this.fields = fields; + if (options) { + var optionKeys = Object.keys(options); + for (var i$1 = 0;i$1 < optionKeys.length; i$1 += 1) { + var k2 = optionKeys[i$1]; + var v = options[k2]; + if (this[k2] !== undefined) { + this[k2] = v; + } + } + } +} +Table.prototype.encode = function() { + return encode.TABLE(this); +}; +Table.prototype.sizeOf = function() { + return sizeOf.TABLE(this); +}; +function ushortList(itemName, list, count) { + if (count === undefined) { + count = list.length; + } + var fields = new Array(list.length + 1); + fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; + for (var i = 0;i < list.length; i++) { + fields[i + 1] = { name: itemName + i, type: "USHORT", value: list[i] }; + } + return fields; +} +function tableList(itemName, records, itemCallback) { + var count = records.length; + var fields = new Array(count + 1); + fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; + for (var i = 0;i < count; i++) { + fields[i + 1] = { name: itemName + i, type: "TABLE", value: itemCallback(records[i], i) }; + } + return fields; +} +function recordList(itemName, records, itemCallback) { + var count = records.length; + var fields = []; + fields[0] = { name: itemName + "Count", type: "USHORT", value: count }; + for (var i = 0;i < count; i++) { + fields = fields.concat(itemCallback(records[i], i)); + } + return fields; +} +function Coverage(coverageTable) { + if (coverageTable.format === 1) { + Table.call(this, "coverageTable", [{ name: "coverageFormat", type: "USHORT", value: 1 }].concat(ushortList("glyph", coverageTable.glyphs))); + } else if (coverageTable.format === 2) { + Table.call(this, "coverageTable", [{ name: "coverageFormat", type: "USHORT", value: 2 }].concat(recordList("rangeRecord", coverageTable.ranges, function(RangeRecord) { + return [ + { name: "startGlyphID", type: "USHORT", value: RangeRecord.start }, + { name: "endGlyphID", type: "USHORT", value: RangeRecord.end }, + { name: "startCoverageIndex", type: "USHORT", value: RangeRecord.index } + ]; + }))); + } else { + check.assert(false, "Coverage format must be 1 or 2."); + } +} +Coverage.prototype = Object.create(Table.prototype); +Coverage.prototype.constructor = Coverage; +function ScriptList(scriptListTable) { + Table.call(this, "scriptListTable", recordList("scriptRecord", scriptListTable, function(scriptRecord, i) { + var script = scriptRecord.script; + var defaultLangSys = script.defaultLangSys; + check.assert(!!defaultLangSys, "Unable to write GSUB: script " + scriptRecord.tag + " has no default language system."); + return [ + { name: "scriptTag" + i, type: "TAG", value: scriptRecord.tag }, + { name: "script" + i, type: "TABLE", value: new Table("scriptTable", [ + { name: "defaultLangSys", type: "TABLE", value: new Table("defaultLangSys", [ + { name: "lookupOrder", type: "USHORT", value: 0 }, + { name: "reqFeatureIndex", type: "USHORT", value: defaultLangSys.reqFeatureIndex } + ].concat(ushortList("featureIndex", defaultLangSys.featureIndexes))) } + ].concat(recordList("langSys", script.langSysRecords, function(langSysRecord, i2) { + var langSys = langSysRecord.langSys; + return [ + { name: "langSysTag" + i2, type: "TAG", value: langSysRecord.tag }, + { name: "langSys" + i2, type: "TABLE", value: new Table("langSys", [ + { name: "lookupOrder", type: "USHORT", value: 0 }, + { name: "reqFeatureIndex", type: "USHORT", value: langSys.reqFeatureIndex } + ].concat(ushortList("featureIndex", langSys.featureIndexes))) } + ]; + }))) } + ]; + })); +} +ScriptList.prototype = Object.create(Table.prototype); +ScriptList.prototype.constructor = ScriptList; +function FeatureList(featureListTable) { + Table.call(this, "featureListTable", recordList("featureRecord", featureListTable, function(featureRecord, i) { + var feature = featureRecord.feature; + return [ + { name: "featureTag" + i, type: "TAG", value: featureRecord.tag }, + { name: "feature" + i, type: "TABLE", value: new Table("featureTable", [ + { name: "featureParams", type: "USHORT", value: feature.featureParams } + ].concat(ushortList("lookupListIndex", feature.lookupListIndexes))) } + ]; + })); +} +FeatureList.prototype = Object.create(Table.prototype); +FeatureList.prototype.constructor = FeatureList; +function LookupList(lookupListTable, subtableMakers) { + Table.call(this, "lookupListTable", tableList("lookup", lookupListTable, function(lookupTable) { + var subtableCallback = subtableMakers[lookupTable.lookupType]; + check.assert(!!subtableCallback, "Unable to write GSUB lookup type " + lookupTable.lookupType + " tables."); + return new Table("lookupTable", [ + { name: "lookupType", type: "USHORT", value: lookupTable.lookupType }, + { name: "lookupFlag", type: "USHORT", value: lookupTable.lookupFlag } + ].concat(tableList("subtable", lookupTable.subtables, subtableCallback))); + })); +} +LookupList.prototype = Object.create(Table.prototype); +LookupList.prototype.constructor = LookupList; +var table = { + Table, + Record: Table, + Coverage, + ScriptList, + FeatureList, + LookupList, + ushortList, + tableList, + recordList +}; +function getByte(dataView, offset) { + return dataView.getUint8(offset); +} +function getUShort(dataView, offset) { + return dataView.getUint16(offset, false); +} +function getShort(dataView, offset) { + return dataView.getInt16(offset, false); +} +function getULong(dataView, offset) { + return dataView.getUint32(offset, false); +} +function getFixed(dataView, offset) { + var decimal = dataView.getInt16(offset, false); + var fraction = dataView.getUint16(offset + 2, false); + return decimal + fraction / 65535; +} +function getTag(dataView, offset) { + var tag = ""; + for (var i = offset;i < offset + 4; i += 1) { + tag += String.fromCharCode(dataView.getInt8(i)); + } + return tag; +} +function getOffset(dataView, offset, offSize) { + var v = 0; + for (var i = 0;i < offSize; i += 1) { + v <<= 8; + v += dataView.getUint8(offset + i); + } + return v; +} +function getBytes(dataView, startOffset, endOffset) { + var bytes = []; + for (var i = startOffset;i < endOffset; i += 1) { + bytes.push(dataView.getUint8(i)); + } + return bytes; +} +function bytesToString(bytes) { + var s = ""; + for (var i = 0;i < bytes.length; i += 1) { + s += String.fromCharCode(bytes[i]); + } + return s; +} +var typeOffsets = { + byte: 1, + uShort: 2, + short: 2, + uLong: 4, + fixed: 4, + longDateTime: 8, + tag: 4 +}; +function Parser(data2, offset) { + this.data = data2; + this.offset = offset; + this.relativeOffset = 0; +} +Parser.prototype.parseByte = function() { + var v = this.data.getUint8(this.offset + this.relativeOffset); + this.relativeOffset += 1; + return v; +}; +Parser.prototype.parseChar = function() { + var v = this.data.getInt8(this.offset + this.relativeOffset); + this.relativeOffset += 1; + return v; +}; +Parser.prototype.parseCard8 = Parser.prototype.parseByte; +Parser.prototype.parseUShort = function() { + var v = this.data.getUint16(this.offset + this.relativeOffset); + this.relativeOffset += 2; + return v; +}; +Parser.prototype.parseCard16 = Parser.prototype.parseUShort; +Parser.prototype.parseSID = Parser.prototype.parseUShort; +Parser.prototype.parseOffset16 = Parser.prototype.parseUShort; +Parser.prototype.parseShort = function() { + var v = this.data.getInt16(this.offset + this.relativeOffset); + this.relativeOffset += 2; + return v; +}; +Parser.prototype.parseF2Dot14 = function() { + var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384; + this.relativeOffset += 2; + return v; +}; +Parser.prototype.parseULong = function() { + var v = getULong(this.data, this.offset + this.relativeOffset); + this.relativeOffset += 4; + return v; +}; +Parser.prototype.parseOffset32 = Parser.prototype.parseULong; +Parser.prototype.parseFixed = function() { + var v = getFixed(this.data, this.offset + this.relativeOffset); + this.relativeOffset += 4; + return v; +}; +Parser.prototype.parseString = function(length2) { + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + var string = ""; + this.relativeOffset += length2; + for (var i = 0;i < length2; i++) { + string += String.fromCharCode(dataView.getUint8(offset + i)); + } + return string; +}; +Parser.prototype.parseTag = function() { + return this.parseString(4); +}; +Parser.prototype.parseLongDateTime = function() { + var v = getULong(this.data, this.offset + this.relativeOffset + 4); + v -= 2082844800; + this.relativeOffset += 8; + return v; +}; +Parser.prototype.parseVersion = function(minorBase) { + var major = getUShort(this.data, this.offset + this.relativeOffset); + var minor = getUShort(this.data, this.offset + this.relativeOffset + 2); + this.relativeOffset += 4; + if (minorBase === undefined) { + minorBase = 4096; + } + return major + minor / minorBase / 10; +}; +Parser.prototype.skip = function(type, amount) { + if (amount === undefined) { + amount = 1; + } + this.relativeOffset += typeOffsets[type] * amount; +}; +Parser.prototype.parseULongList = function(count) { + if (count === undefined) { + count = this.parseULong(); + } + var offsets = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0;i < count; i++) { + offsets[i] = dataView.getUint32(offset); + offset += 4; + } + this.relativeOffset += count * 4; + return offsets; +}; +Parser.prototype.parseOffset16List = Parser.prototype.parseUShortList = function(count) { + if (count === undefined) { + count = this.parseUShort(); + } + var offsets = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0;i < count; i++) { + offsets[i] = dataView.getUint16(offset); + offset += 2; + } + this.relativeOffset += count * 2; + return offsets; +}; +Parser.prototype.parseShortList = function(count) { + var list = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0;i < count; i++) { + list[i] = dataView.getInt16(offset); + offset += 2; + } + this.relativeOffset += count * 2; + return list; +}; +Parser.prototype.parseByteList = function(count) { + var list = new Array(count); + var dataView = this.data; + var offset = this.offset + this.relativeOffset; + for (var i = 0;i < count; i++) { + list[i] = dataView.getUint8(offset++); + } + this.relativeOffset += count; + return list; +}; +Parser.prototype.parseList = function(count, itemCallback) { + if (!itemCallback) { + itemCallback = count; + count = this.parseUShort(); + } + var list = new Array(count); + for (var i = 0;i < count; i++) { + list[i] = itemCallback.call(this); + } + return list; +}; +Parser.prototype.parseList32 = function(count, itemCallback) { + if (!itemCallback) { + itemCallback = count; + count = this.parseULong(); + } + var list = new Array(count); + for (var i = 0;i < count; i++) { + list[i] = itemCallback.call(this); + } + return list; +}; +Parser.prototype.parseRecordList = function(count, recordDescription) { + if (!recordDescription) { + recordDescription = count; + count = this.parseUShort(); + } + var records = new Array(count); + var fields = Object.keys(recordDescription); + for (var i = 0;i < count; i++) { + var rec = {}; + for (var j2 = 0;j2 < fields.length; j2++) { + var fieldName = fields[j2]; + var fieldType = recordDescription[fieldName]; + rec[fieldName] = fieldType.call(this); + } + records[i] = rec; + } + return records; +}; +Parser.prototype.parseRecordList32 = function(count, recordDescription) { + if (!recordDescription) { + recordDescription = count; + count = this.parseULong(); + } + var records = new Array(count); + var fields = Object.keys(recordDescription); + for (var i = 0;i < count; i++) { + var rec = {}; + for (var j2 = 0;j2 < fields.length; j2++) { + var fieldName = fields[j2]; + var fieldType = recordDescription[fieldName]; + rec[fieldName] = fieldType.call(this); + } + records[i] = rec; + } + return records; +}; +Parser.prototype.parseStruct = function(description) { + if (typeof description === "function") { + return description.call(this); + } else { + var fields = Object.keys(description); + var struct = {}; + for (var j2 = 0;j2 < fields.length; j2++) { + var fieldName = fields[j2]; + var fieldType = description[fieldName]; + struct[fieldName] = fieldType.call(this); + } + return struct; + } +}; +Parser.prototype.parseValueRecord = function(valueFormat) { + if (valueFormat === undefined) { + valueFormat = this.parseUShort(); + } + if (valueFormat === 0) { + return; + } + var valueRecord = {}; + if (valueFormat & 1) { + valueRecord.xPlacement = this.parseShort(); + } + if (valueFormat & 2) { + valueRecord.yPlacement = this.parseShort(); + } + if (valueFormat & 4) { + valueRecord.xAdvance = this.parseShort(); + } + if (valueFormat & 8) { + valueRecord.yAdvance = this.parseShort(); + } + if (valueFormat & 16) { + valueRecord.xPlaDevice = undefined; + this.parseShort(); + } + if (valueFormat & 32) { + valueRecord.yPlaDevice = undefined; + this.parseShort(); + } + if (valueFormat & 64) { + valueRecord.xAdvDevice = undefined; + this.parseShort(); + } + if (valueFormat & 128) { + valueRecord.yAdvDevice = undefined; + this.parseShort(); + } + return valueRecord; +}; +Parser.prototype.parseValueRecordList = function() { + var valueFormat = this.parseUShort(); + var valueCount = this.parseUShort(); + var values2 = new Array(valueCount); + for (var i = 0;i < valueCount; i++) { + values2[i] = this.parseValueRecord(valueFormat); + } + return values2; +}; +Parser.prototype.parsePointer = function(description) { + var structOffset = this.parseOffset16(); + if (structOffset > 0) { + return new Parser(this.data, this.offset + structOffset).parseStruct(description); + } + return; +}; +Parser.prototype.parsePointer32 = function(description) { + var structOffset = this.parseOffset32(); + if (structOffset > 0) { + return new Parser(this.data, this.offset + structOffset).parseStruct(description); + } + return; +}; +Parser.prototype.parseListOfLists = function(itemCallback) { + var offsets = this.parseOffset16List(); + var count = offsets.length; + var relativeOffset = this.relativeOffset; + var list = new Array(count); + for (var i = 0;i < count; i++) { + var start = offsets[i]; + if (start === 0) { + list[i] = undefined; + continue; + } + this.relativeOffset = start; + if (itemCallback) { + var subOffsets = this.parseOffset16List(); + var subList = new Array(subOffsets.length); + for (var j2 = 0;j2 < subOffsets.length; j2++) { + this.relativeOffset = start + subOffsets[j2]; + subList[j2] = itemCallback.call(this); + } + list[i] = subList; + } else { + list[i] = this.parseUShortList(); + } + } + this.relativeOffset = relativeOffset; + return list; +}; +Parser.prototype.parseCoverage = function() { + var startOffset = this.offset + this.relativeOffset; + var format = this.parseUShort(); + var count = this.parseUShort(); + if (format === 1) { + return { + format: 1, + glyphs: this.parseUShortList(count) + }; + } else if (format === 2) { + var ranges = new Array(count); + for (var i = 0;i < count; i++) { + ranges[i] = { + start: this.parseUShort(), + end: this.parseUShort(), + index: this.parseUShort() + }; + } + return { + format: 2, + ranges + }; + } + throw new Error("0x" + startOffset.toString(16) + ": Coverage format must be 1 or 2."); +}; +Parser.prototype.parseClassDef = function() { + var startOffset = this.offset + this.relativeOffset; + var format = this.parseUShort(); + if (format === 1) { + return { + format: 1, + startGlyph: this.parseUShort(), + classes: this.parseUShortList() + }; + } else if (format === 2) { + return { + format: 2, + ranges: this.parseRecordList({ + start: Parser.uShort, + end: Parser.uShort, + classId: Parser.uShort + }) + }; + } + throw new Error("0x" + startOffset.toString(16) + ": ClassDef format must be 1 or 2."); +}; +Parser.list = function(count, itemCallback) { + return function() { + return this.parseList(count, itemCallback); + }; +}; +Parser.list32 = function(count, itemCallback) { + return function() { + return this.parseList32(count, itemCallback); + }; +}; +Parser.recordList = function(count, recordDescription) { + return function() { + return this.parseRecordList(count, recordDescription); + }; +}; +Parser.recordList32 = function(count, recordDescription) { + return function() { + return this.parseRecordList32(count, recordDescription); + }; +}; +Parser.pointer = function(description) { + return function() { + return this.parsePointer(description); + }; +}; +Parser.pointer32 = function(description) { + return function() { + return this.parsePointer32(description); + }; +}; +Parser.tag = Parser.prototype.parseTag; +Parser.byte = Parser.prototype.parseByte; +Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort; +Parser.uShortList = Parser.prototype.parseUShortList; +Parser.uLong = Parser.offset32 = Parser.prototype.parseULong; +Parser.uLongList = Parser.prototype.parseULongList; +Parser.struct = Parser.prototype.parseStruct; +Parser.coverage = Parser.prototype.parseCoverage; +Parser.classDef = Parser.prototype.parseClassDef; +var langSysTable = { + reserved: Parser.uShort, + reqFeatureIndex: Parser.uShort, + featureIndexes: Parser.uShortList +}; +Parser.prototype.parseScriptList = function() { + return this.parsePointer(Parser.recordList({ + tag: Parser.tag, + script: Parser.pointer({ + defaultLangSys: Parser.pointer(langSysTable), + langSysRecords: Parser.recordList({ + tag: Parser.tag, + langSys: Parser.pointer(langSysTable) + }) + }) + })) || []; +}; +Parser.prototype.parseFeatureList = function() { + return this.parsePointer(Parser.recordList({ + tag: Parser.tag, + feature: Parser.pointer({ + featureParams: Parser.offset16, + lookupListIndexes: Parser.uShortList + }) + })) || []; +}; +Parser.prototype.parseLookupList = function(lookupTableParsers) { + return this.parsePointer(Parser.list(Parser.pointer(function() { + var lookupType = this.parseUShort(); + check.argument(1 <= lookupType && lookupType <= 9, "GPOS/GSUB lookup type " + lookupType + " unknown."); + var lookupFlag = this.parseUShort(); + var useMarkFilteringSet = lookupFlag & 16; + return { + lookupType, + lookupFlag, + subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])), + markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined + }; + }))) || []; +}; +Parser.prototype.parseFeatureVariationsList = function() { + return this.parsePointer32(function() { + var majorVersion = this.parseUShort(); + var minorVersion = this.parseUShort(); + check.argument(majorVersion === 1 && minorVersion < 1, "GPOS/GSUB feature variations table unknown."); + var featureVariations = this.parseRecordList32({ + conditionSetOffset: Parser.offset32, + featureTableSubstitutionOffset: Parser.offset32 + }); + return featureVariations; + }) || []; +}; +var parse = { + getByte, + getCard8: getByte, + getUShort, + getCard16: getUShort, + getShort, + getULong, + getFixed, + getTag, + getOffset, + getBytes, + bytesToString, + Parser +}; +function parseCmapTableFormat12(cmap, p) { + p.parseUShort(); + cmap.length = p.parseULong(); + cmap.language = p.parseULong(); + var groupCount; + cmap.groupCount = groupCount = p.parseULong(); + cmap.glyphIndexMap = {}; + for (var i = 0;i < groupCount; i += 1) { + var startCharCode = p.parseULong(); + var endCharCode = p.parseULong(); + var startGlyphId = p.parseULong(); + for (var c = startCharCode;c <= endCharCode; c += 1) { + cmap.glyphIndexMap[c] = startGlyphId; + startGlyphId++; + } + } +} +function parseCmapTableFormat4(cmap, p, data2, start, offset) { + cmap.length = p.parseUShort(); + cmap.language = p.parseUShort(); + var segCount; + cmap.segCount = segCount = p.parseUShort() >> 1; + p.skip("uShort", 3); + cmap.glyphIndexMap = {}; + var endCountParser = new parse.Parser(data2, start + offset + 14); + var startCountParser = new parse.Parser(data2, start + offset + 16 + segCount * 2); + var idDeltaParser = new parse.Parser(data2, start + offset + 16 + segCount * 4); + var idRangeOffsetParser = new parse.Parser(data2, start + offset + 16 + segCount * 6); + var glyphIndexOffset = start + offset + 16 + segCount * 8; + for (var i = 0;i < segCount - 1; i += 1) { + var glyphIndex = undefined; + var endCount = endCountParser.parseUShort(); + var startCount = startCountParser.parseUShort(); + var idDelta = idDeltaParser.parseShort(); + var idRangeOffset = idRangeOffsetParser.parseUShort(); + for (var c = startCount;c <= endCount; c += 1) { + if (idRangeOffset !== 0) { + glyphIndexOffset = idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2; + glyphIndexOffset += idRangeOffset; + glyphIndexOffset += (c - startCount) * 2; + glyphIndex = parse.getUShort(data2, glyphIndexOffset); + if (glyphIndex !== 0) { + glyphIndex = glyphIndex + idDelta & 65535; + } + } else { + glyphIndex = c + idDelta & 65535; + } + cmap.glyphIndexMap[c] = glyphIndex; + } + } +} +function parseCmapTable(data2, start) { + var cmap = {}; + cmap.version = parse.getUShort(data2, start); + check.argument(cmap.version === 0, "cmap table version should be 0."); + cmap.numTables = parse.getUShort(data2, start + 2); + var offset = -1; + for (var i = cmap.numTables - 1;i >= 0; i -= 1) { + var platformId = parse.getUShort(data2, start + 4 + i * 8); + var encodingId = parse.getUShort(data2, start + 4 + i * 8 + 2); + if (platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10) || platformId === 0 && (encodingId === 0 || encodingId === 1 || encodingId === 2 || encodingId === 3 || encodingId === 4)) { + offset = parse.getULong(data2, start + 4 + i * 8 + 4); + break; + } + } + if (offset === -1) { + throw new Error("No valid cmap sub-tables found."); + } + var p = new parse.Parser(data2, start + offset); + cmap.format = p.parseUShort(); + if (cmap.format === 12) { + parseCmapTableFormat12(cmap, p); + } else if (cmap.format === 4) { + parseCmapTableFormat4(cmap, p, data2, start, offset); + } else { + throw new Error("Only format 4 and 12 cmap tables are supported (found format " + cmap.format + ")."); + } + return cmap; +} +function addSegment(t2, code, glyphIndex) { + t2.segments.push({ + end: code, + start: code, + delta: -(code - glyphIndex), + offset: 0, + glyphIndex + }); +} +function addTerminatorSegment(t2) { + t2.segments.push({ + end: 65535, + start: 65535, + delta: 1, + offset: 0 + }); +} +function makeCmapTable(glyphs) { + var isPlan0Only = true; + var i; + for (i = glyphs.length - 1;i > 0; i -= 1) { + var g3 = glyphs.get(i); + if (g3.unicode > 65535) { + console.log("Adding CMAP format 12 (needed!)"); + isPlan0Only = false; + break; + } + } + var cmapTable = [ + { name: "version", type: "USHORT", value: 0 }, + { name: "numTables", type: "USHORT", value: isPlan0Only ? 1 : 2 }, + { name: "platformID", type: "USHORT", value: 3 }, + { name: "encodingID", type: "USHORT", value: 1 }, + { name: "offset", type: "ULONG", value: isPlan0Only ? 12 : 12 + 8 } + ]; + if (!isPlan0Only) { + cmapTable = cmapTable.concat([ + { name: "cmap12PlatformID", type: "USHORT", value: 3 }, + { name: "cmap12EncodingID", type: "USHORT", value: 10 }, + { name: "cmap12Offset", type: "ULONG", value: 0 } + ]); + } + cmapTable = cmapTable.concat([ + { name: "format", type: "USHORT", value: 4 }, + { name: "cmap4Length", type: "USHORT", value: 0 }, + { name: "language", type: "USHORT", value: 0 }, + { name: "segCountX2", type: "USHORT", value: 0 }, + { name: "searchRange", type: "USHORT", value: 0 }, + { name: "entrySelector", type: "USHORT", value: 0 }, + { name: "rangeShift", type: "USHORT", value: 0 } + ]); + var t2 = new table.Table("cmap", cmapTable); + t2.segments = []; + for (i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + for (var j2 = 0;j2 < glyph.unicodes.length; j2 += 1) { + addSegment(t2, glyph.unicodes[j2], i); + } + t2.segments = t2.segments.sort(function(a, b) { + return a.start - b.start; + }); + } + addTerminatorSegment(t2); + var segCount = t2.segments.length; + var segCountToRemove = 0; + var endCounts = []; + var startCounts = []; + var idDeltas = []; + var idRangeOffsets = []; + var glyphIds = []; + var cmap12Groups = []; + for (i = 0;i < segCount; i += 1) { + var segment = t2.segments[i]; + if (segment.end <= 65535 && segment.start <= 65535) { + endCounts = endCounts.concat({ name: "end_" + i, type: "USHORT", value: segment.end }); + startCounts = startCounts.concat({ name: "start_" + i, type: "USHORT", value: segment.start }); + idDeltas = idDeltas.concat({ name: "idDelta_" + i, type: "SHORT", value: segment.delta }); + idRangeOffsets = idRangeOffsets.concat({ name: "idRangeOffset_" + i, type: "USHORT", value: segment.offset }); + if (segment.glyphId !== undefined) { + glyphIds = glyphIds.concat({ name: "glyph_" + i, type: "USHORT", value: segment.glyphId }); + } + } else { + segCountToRemove += 1; + } + if (!isPlan0Only && segment.glyphIndex !== undefined) { + cmap12Groups = cmap12Groups.concat({ name: "cmap12Start_" + i, type: "ULONG", value: segment.start }); + cmap12Groups = cmap12Groups.concat({ name: "cmap12End_" + i, type: "ULONG", value: segment.end }); + cmap12Groups = cmap12Groups.concat({ name: "cmap12Glyph_" + i, type: "ULONG", value: segment.glyphIndex }); + } + } + t2.segCountX2 = (segCount - segCountToRemove) * 2; + t2.searchRange = Math.pow(2, Math.floor(Math.log(segCount - segCountToRemove) / Math.log(2))) * 2; + t2.entrySelector = Math.log(t2.searchRange / 2) / Math.log(2); + t2.rangeShift = t2.segCountX2 - t2.searchRange; + t2.fields = t2.fields.concat(endCounts); + t2.fields.push({ name: "reservedPad", type: "USHORT", value: 0 }); + t2.fields = t2.fields.concat(startCounts); + t2.fields = t2.fields.concat(idDeltas); + t2.fields = t2.fields.concat(idRangeOffsets); + t2.fields = t2.fields.concat(glyphIds); + t2.cmap4Length = 14 + endCounts.length * 2 + 2 + startCounts.length * 2 + idDeltas.length * 2 + idRangeOffsets.length * 2 + glyphIds.length * 2; + if (!isPlan0Only) { + var cmap12Length = 16 + cmap12Groups.length * 4; + t2.cmap12Offset = 12 + 2 * 2 + 4 + t2.cmap4Length; + t2.fields = t2.fields.concat([ + { name: "cmap12Format", type: "USHORT", value: 12 }, + { name: "cmap12Reserved", type: "USHORT", value: 0 }, + { name: "cmap12Length", type: "ULONG", value: cmap12Length }, + { name: "cmap12Language", type: "ULONG", value: 0 }, + { name: "cmap12nGroups", type: "ULONG", value: cmap12Groups.length / 3 } + ]); + t2.fields = t2.fields.concat(cmap12Groups); + } + return t2; +} +var cmap = { parse: parseCmapTable, make: makeCmapTable }; +var cffStandardStrings = [ + ".notdef", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quoteright", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "quoteleft", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "exclamdown", + "cent", + "sterling", + "fraction", + "yen", + "florin", + "section", + "currency", + "quotesingle", + "quotedblleft", + "guillemotleft", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "endash", + "dagger", + "daggerdbl", + "periodcentered", + "paragraph", + "bullet", + "quotesinglbase", + "quotedblbase", + "quotedblright", + "guillemotright", + "ellipsis", + "perthousand", + "questiondown", + "grave", + "acute", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "dieresis", + "ring", + "cedilla", + "hungarumlaut", + "ogonek", + "caron", + "emdash", + "AE", + "ordfeminine", + "Lslash", + "Oslash", + "OE", + "ordmasculine", + "ae", + "dotlessi", + "lslash", + "oslash", + "oe", + "germandbls", + "onesuperior", + "logicalnot", + "mu", + "trademark", + "Eth", + "onehalf", + "plusminus", + "Thorn", + "onequarter", + "divide", + "brokenbar", + "degree", + "thorn", + "threequarters", + "twosuperior", + "registered", + "minus", + "eth", + "multiply", + "threesuperior", + "copyright", + "Aacute", + "Acircumflex", + "Adieresis", + "Agrave", + "Aring", + "Atilde", + "Ccedilla", + "Eacute", + "Ecircumflex", + "Edieresis", + "Egrave", + "Iacute", + "Icircumflex", + "Idieresis", + "Igrave", + "Ntilde", + "Oacute", + "Ocircumflex", + "Odieresis", + "Ograve", + "Otilde", + "Scaron", + "Uacute", + "Ucircumflex", + "Udieresis", + "Ugrave", + "Yacute", + "Ydieresis", + "Zcaron", + "aacute", + "acircumflex", + "adieresis", + "agrave", + "aring", + "atilde", + "ccedilla", + "eacute", + "ecircumflex", + "edieresis", + "egrave", + "iacute", + "icircumflex", + "idieresis", + "igrave", + "ntilde", + "oacute", + "ocircumflex", + "odieresis", + "ograve", + "otilde", + "scaron", + "uacute", + "ucircumflex", + "udieresis", + "ugrave", + "yacute", + "ydieresis", + "zcaron", + "exclamsmall", + "Hungarumlautsmall", + "dollaroldstyle", + "dollarsuperior", + "ampersandsmall", + "Acutesmall", + "parenleftsuperior", + "parenrightsuperior", + "266 ff", + "onedotenleader", + "zerooldstyle", + "oneoldstyle", + "twooldstyle", + "threeoldstyle", + "fouroldstyle", + "fiveoldstyle", + "sixoldstyle", + "sevenoldstyle", + "eightoldstyle", + "nineoldstyle", + "commasuperior", + "threequartersemdash", + "periodsuperior", + "questionsmall", + "asuperior", + "bsuperior", + "centsuperior", + "dsuperior", + "esuperior", + "isuperior", + "lsuperior", + "msuperior", + "nsuperior", + "osuperior", + "rsuperior", + "ssuperior", + "tsuperior", + "ff", + "ffi", + "ffl", + "parenleftinferior", + "parenrightinferior", + "Circumflexsmall", + "hyphensuperior", + "Gravesmall", + "Asmall", + "Bsmall", + "Csmall", + "Dsmall", + "Esmall", + "Fsmall", + "Gsmall", + "Hsmall", + "Ismall", + "Jsmall", + "Ksmall", + "Lsmall", + "Msmall", + "Nsmall", + "Osmall", + "Psmall", + "Qsmall", + "Rsmall", + "Ssmall", + "Tsmall", + "Usmall", + "Vsmall", + "Wsmall", + "Xsmall", + "Ysmall", + "Zsmall", + "colonmonetary", + "onefitted", + "rupiah", + "Tildesmall", + "exclamdownsmall", + "centoldstyle", + "Lslashsmall", + "Scaronsmall", + "Zcaronsmall", + "Dieresissmall", + "Brevesmall", + "Caronsmall", + "Dotaccentsmall", + "Macronsmall", + "figuredash", + "hypheninferior", + "Ogoneksmall", + "Ringsmall", + "Cedillasmall", + "questiondownsmall", + "oneeighth", + "threeeighths", + "fiveeighths", + "seveneighths", + "onethird", + "twothirds", + "zerosuperior", + "foursuperior", + "fivesuperior", + "sixsuperior", + "sevensuperior", + "eightsuperior", + "ninesuperior", + "zeroinferior", + "oneinferior", + "twoinferior", + "threeinferior", + "fourinferior", + "fiveinferior", + "sixinferior", + "seveninferior", + "eightinferior", + "nineinferior", + "centinferior", + "dollarinferior", + "periodinferior", + "commainferior", + "Agravesmall", + "Aacutesmall", + "Acircumflexsmall", + "Atildesmall", + "Adieresissmall", + "Aringsmall", + "AEsmall", + "Ccedillasmall", + "Egravesmall", + "Eacutesmall", + "Ecircumflexsmall", + "Edieresissmall", + "Igravesmall", + "Iacutesmall", + "Icircumflexsmall", + "Idieresissmall", + "Ethsmall", + "Ntildesmall", + "Ogravesmall", + "Oacutesmall", + "Ocircumflexsmall", + "Otildesmall", + "Odieresissmall", + "OEsmall", + "Oslashsmall", + "Ugravesmall", + "Uacutesmall", + "Ucircumflexsmall", + "Udieresissmall", + "Yacutesmall", + "Thornsmall", + "Ydieresissmall", + "001.000", + "001.001", + "001.002", + "001.003", + "Black", + "Bold", + "Book", + "Light", + "Medium", + "Regular", + "Roman", + "Semibold" +]; +var cffStandardEncoding = [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quoteright", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "quoteleft", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "exclamdown", + "cent", + "sterling", + "fraction", + "yen", + "florin", + "section", + "currency", + "quotesingle", + "quotedblleft", + "guillemotleft", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "", + "endash", + "dagger", + "daggerdbl", + "periodcentered", + "", + "paragraph", + "bullet", + "quotesinglbase", + "quotedblbase", + "quotedblright", + "guillemotright", + "ellipsis", + "perthousand", + "", + "questiondown", + "", + "grave", + "acute", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "dieresis", + "", + "ring", + "cedilla", + "", + "hungarumlaut", + "ogonek", + "caron", + "emdash", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "AE", + "", + "ordfeminine", + "", + "", + "", + "", + "Lslash", + "Oslash", + "OE", + "ordmasculine", + "", + "", + "", + "", + "", + "ae", + "", + "", + "", + "dotlessi", + "", + "", + "lslash", + "oslash", + "oe", + "germandbls" +]; +var cffExpertEncoding = [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "space", + "exclamsmall", + "Hungarumlautsmall", + "", + "dollaroldstyle", + "dollarsuperior", + "ampersandsmall", + "Acutesmall", + "parenleftsuperior", + "parenrightsuperior", + "twodotenleader", + "onedotenleader", + "comma", + "hyphen", + "period", + "fraction", + "zerooldstyle", + "oneoldstyle", + "twooldstyle", + "threeoldstyle", + "fouroldstyle", + "fiveoldstyle", + "sixoldstyle", + "sevenoldstyle", + "eightoldstyle", + "nineoldstyle", + "colon", + "semicolon", + "commasuperior", + "threequartersemdash", + "periodsuperior", + "questionsmall", + "", + "asuperior", + "bsuperior", + "centsuperior", + "dsuperior", + "esuperior", + "", + "", + "isuperior", + "", + "", + "lsuperior", + "msuperior", + "nsuperior", + "osuperior", + "", + "", + "rsuperior", + "ssuperior", + "tsuperior", + "", + "ff", + "fi", + "fl", + "ffi", + "ffl", + "parenleftinferior", + "", + "parenrightinferior", + "Circumflexsmall", + "hyphensuperior", + "Gravesmall", + "Asmall", + "Bsmall", + "Csmall", + "Dsmall", + "Esmall", + "Fsmall", + "Gsmall", + "Hsmall", + "Ismall", + "Jsmall", + "Ksmall", + "Lsmall", + "Msmall", + "Nsmall", + "Osmall", + "Psmall", + "Qsmall", + "Rsmall", + "Ssmall", + "Tsmall", + "Usmall", + "Vsmall", + "Wsmall", + "Xsmall", + "Ysmall", + "Zsmall", + "colonmonetary", + "onefitted", + "rupiah", + "Tildesmall", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "exclamdownsmall", + "centoldstyle", + "Lslashsmall", + "", + "", + "Scaronsmall", + "Zcaronsmall", + "Dieresissmall", + "Brevesmall", + "Caronsmall", + "", + "Dotaccentsmall", + "", + "", + "Macronsmall", + "", + "", + "figuredash", + "hypheninferior", + "", + "", + "Ogoneksmall", + "Ringsmall", + "Cedillasmall", + "", + "", + "", + "onequarter", + "onehalf", + "threequarters", + "questiondownsmall", + "oneeighth", + "threeeighths", + "fiveeighths", + "seveneighths", + "onethird", + "twothirds", + "", + "", + "zerosuperior", + "onesuperior", + "twosuperior", + "threesuperior", + "foursuperior", + "fivesuperior", + "sixsuperior", + "sevensuperior", + "eightsuperior", + "ninesuperior", + "zeroinferior", + "oneinferior", + "twoinferior", + "threeinferior", + "fourinferior", + "fiveinferior", + "sixinferior", + "seveninferior", + "eightinferior", + "nineinferior", + "centinferior", + "dollarinferior", + "periodinferior", + "commainferior", + "Agravesmall", + "Aacutesmall", + "Acircumflexsmall", + "Atildesmall", + "Adieresissmall", + "Aringsmall", + "AEsmall", + "Ccedillasmall", + "Egravesmall", + "Eacutesmall", + "Ecircumflexsmall", + "Edieresissmall", + "Igravesmall", + "Iacutesmall", + "Icircumflexsmall", + "Idieresissmall", + "Ethsmall", + "Ntildesmall", + "Ogravesmall", + "Oacutesmall", + "Ocircumflexsmall", + "Otildesmall", + "Odieresissmall", + "OEsmall", + "Oslashsmall", + "Ugravesmall", + "Uacutesmall", + "Ucircumflexsmall", + "Udieresissmall", + "Yacutesmall", + "Thornsmall", + "Ydieresissmall" +]; +var standardNames = [ + ".notdef", + ".null", + "nonmarkingreturn", + "space", + "exclam", + "quotedbl", + "numbersign", + "dollar", + "percent", + "ampersand", + "quotesingle", + "parenleft", + "parenright", + "asterisk", + "plus", + "comma", + "hyphen", + "period", + "slash", + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "colon", + "semicolon", + "less", + "equal", + "greater", + "question", + "at", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + "bracketleft", + "backslash", + "bracketright", + "asciicircum", + "underscore", + "grave", + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + "braceleft", + "bar", + "braceright", + "asciitilde", + "Adieresis", + "Aring", + "Ccedilla", + "Eacute", + "Ntilde", + "Odieresis", + "Udieresis", + "aacute", + "agrave", + "acircumflex", + "adieresis", + "atilde", + "aring", + "ccedilla", + "eacute", + "egrave", + "ecircumflex", + "edieresis", + "iacute", + "igrave", + "icircumflex", + "idieresis", + "ntilde", + "oacute", + "ograve", + "ocircumflex", + "odieresis", + "otilde", + "uacute", + "ugrave", + "ucircumflex", + "udieresis", + "dagger", + "degree", + "cent", + "sterling", + "section", + "bullet", + "paragraph", + "germandbls", + "registered", + "copyright", + "trademark", + "acute", + "dieresis", + "notequal", + "AE", + "Oslash", + "infinity", + "plusminus", + "lessequal", + "greaterequal", + "yen", + "mu", + "partialdiff", + "summation", + "product", + "pi", + "integral", + "ordfeminine", + "ordmasculine", + "Omega", + "ae", + "oslash", + "questiondown", + "exclamdown", + "logicalnot", + "radical", + "florin", + "approxequal", + "Delta", + "guillemotleft", + "guillemotright", + "ellipsis", + "nonbreakingspace", + "Agrave", + "Atilde", + "Otilde", + "OE", + "oe", + "endash", + "emdash", + "quotedblleft", + "quotedblright", + "quoteleft", + "quoteright", + "divide", + "lozenge", + "ydieresis", + "Ydieresis", + "fraction", + "currency", + "guilsinglleft", + "guilsinglright", + "fi", + "fl", + "daggerdbl", + "periodcentered", + "quotesinglbase", + "quotedblbase", + "perthousand", + "Acircumflex", + "Ecircumflex", + "Aacute", + "Edieresis", + "Egrave", + "Iacute", + "Icircumflex", + "Idieresis", + "Igrave", + "Oacute", + "Ocircumflex", + "apple", + "Ograve", + "Uacute", + "Ucircumflex", + "Ugrave", + "dotlessi", + "circumflex", + "tilde", + "macron", + "breve", + "dotaccent", + "ring", + "cedilla", + "hungarumlaut", + "ogonek", + "caron", + "Lslash", + "lslash", + "Scaron", + "scaron", + "Zcaron", + "zcaron", + "brokenbar", + "Eth", + "eth", + "Yacute", + "yacute", + "Thorn", + "thorn", + "minus", + "multiply", + "onesuperior", + "twosuperior", + "threesuperior", + "onehalf", + "onequarter", + "threequarters", + "franc", + "Gbreve", + "gbreve", + "Idotaccent", + "Scedilla", + "scedilla", + "Cacute", + "cacute", + "Ccaron", + "ccaron", + "dcroat" +]; +function DefaultEncoding(font) { + this.font = font; +} +DefaultEncoding.prototype.charToGlyphIndex = function(c) { + var code = c.codePointAt(0); + var glyphs = this.font.glyphs; + if (glyphs) { + for (var i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + for (var j2 = 0;j2 < glyph.unicodes.length; j2 += 1) { + if (glyph.unicodes[j2] === code) { + return i; + } + } + } + } + return null; +}; +function CmapEncoding(cmap2) { + this.cmap = cmap2; +} +CmapEncoding.prototype.charToGlyphIndex = function(c) { + return this.cmap.glyphIndexMap[c.codePointAt(0)] || 0; +}; +function CffEncoding(encoding, charset) { + this.encoding = encoding; + this.charset = charset; +} +CffEncoding.prototype.charToGlyphIndex = function(s) { + var code = s.codePointAt(0); + var charName = this.encoding[code]; + return this.charset.indexOf(charName); +}; +function GlyphNames(post) { + switch (post.version) { + case 1: + this.names = standardNames.slice(); + break; + case 2: + this.names = new Array(post.numberOfGlyphs); + for (var i = 0;i < post.numberOfGlyphs; i++) { + if (post.glyphNameIndex[i] < standardNames.length) { + this.names[i] = standardNames[post.glyphNameIndex[i]]; + } else { + this.names[i] = post.names[post.glyphNameIndex[i] - standardNames.length]; + } + } + break; + case 2.5: + this.names = new Array(post.numberOfGlyphs); + for (var i$1 = 0;i$1 < post.numberOfGlyphs; i$1++) { + this.names[i$1] = standardNames[i$1 + post.glyphNameIndex[i$1]]; + } + break; + case 3: + this.names = []; + break; + default: + this.names = []; + break; + } +} +GlyphNames.prototype.nameToGlyphIndex = function(name2) { + return this.names.indexOf(name2); +}; +GlyphNames.prototype.glyphIndexToName = function(gid) { + return this.names[gid]; +}; +function line(ctx, x1, y1, x2, y2) { + ctx.beginPath(); + ctx.moveTo(x1, y1); + ctx.lineTo(x2, y2); + ctx.stroke(); +} +var draw = { line }; +function getPathDefinition(glyph, path) { + var _path = path || new Path2; + return { + configurable: true, + get: function() { + if (typeof _path === "function") { + _path = _path(); + } + return _path; + }, + set: function(p) { + _path = p; + } + }; +} +function Glyph(options) { + this.bindConstructorValues(options); +} +Glyph.prototype.bindConstructorValues = function(options) { + this.index = options.index || 0; + this.name = options.name || null; + this.unicode = options.unicode || undefined; + this.unicodes = options.unicodes || options.unicode !== undefined ? [options.unicode] : []; + if ("xMin" in options) { + this.xMin = options.xMin; + } + if ("yMin" in options) { + this.yMin = options.yMin; + } + if ("xMax" in options) { + this.xMax = options.xMax; + } + if ("yMax" in options) { + this.yMax = options.yMax; + } + if ("advanceWidth" in options) { + this.advanceWidth = options.advanceWidth; + } + Object.defineProperty(this, "path", getPathDefinition(this, options.path)); +}; +Glyph.prototype.addUnicode = function(unicode) { + if (this.unicodes.length === 0) { + this.unicode = unicode; + } + this.unicodes.push(unicode); +}; +Glyph.prototype.getBoundingBox = function() { + return this.path.getBoundingBox(); +}; +Glyph.prototype.getPath = function(x2, y, fontSize, options, font) { + x2 = x2 !== undefined ? x2 : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 72; + var commands; + var hPoints; + if (!options) { + options = {}; + } + var xScale = options.xScale; + var yScale = options.yScale; + if (options.hinting && font && font.hinting) { + hPoints = this.path && font.hinting.exec(this, fontSize); + } + if (hPoints) { + commands = font.hinting.getCommands(hPoints); + x2 = Math.round(x2); + y = Math.round(y); + xScale = yScale = 1; + } else { + commands = this.path.commands; + var scale2 = 1 / (this.path.unitsPerEm || 1000) * fontSize; + if (xScale === undefined) { + xScale = scale2; + } + if (yScale === undefined) { + yScale = scale2; + } + } + var p = new Path2; + for (var i = 0;i < commands.length; i += 1) { + var cmd = commands[i]; + if (cmd.type === "M") { + p.moveTo(x2 + cmd.x * xScale, y + -cmd.y * yScale); + } else if (cmd.type === "L") { + p.lineTo(x2 + cmd.x * xScale, y + -cmd.y * yScale); + } else if (cmd.type === "Q") { + p.quadraticCurveTo(x2 + cmd.x1 * xScale, y + -cmd.y1 * yScale, x2 + cmd.x * xScale, y + -cmd.y * yScale); + } else if (cmd.type === "C") { + p.curveTo(x2 + cmd.x1 * xScale, y + -cmd.y1 * yScale, x2 + cmd.x2 * xScale, y + -cmd.y2 * yScale, x2 + cmd.x * xScale, y + -cmd.y * yScale); + } else if (cmd.type === "Z") { + p.closePath(); + } + } + return p; +}; +Glyph.prototype.getContours = function() { + if (this.points === undefined) { + return []; + } + var contours = []; + var currentContour = []; + for (var i = 0;i < this.points.length; i += 1) { + var pt = this.points[i]; + currentContour.push(pt); + if (pt.lastPointOfContour) { + contours.push(currentContour); + currentContour = []; + } + } + check.argument(currentContour.length === 0, "There are still points left in the current contour."); + return contours; +}; +Glyph.prototype.getMetrics = function() { + var commands = this.path.commands; + var xCoords = []; + var yCoords = []; + for (var i = 0;i < commands.length; i += 1) { + var cmd = commands[i]; + if (cmd.type !== "Z") { + xCoords.push(cmd.x); + yCoords.push(cmd.y); + } + if (cmd.type === "Q" || cmd.type === "C") { + xCoords.push(cmd.x1); + yCoords.push(cmd.y1); + } + if (cmd.type === "C") { + xCoords.push(cmd.x2); + yCoords.push(cmd.y2); + } + } + var metrics = { + xMin: Math.min.apply(null, xCoords), + yMin: Math.min.apply(null, yCoords), + xMax: Math.max.apply(null, xCoords), + yMax: Math.max.apply(null, yCoords), + leftSideBearing: this.leftSideBearing + }; + if (!isFinite(metrics.xMin)) { + metrics.xMin = 0; + } + if (!isFinite(metrics.xMax)) { + metrics.xMax = this.advanceWidth; + } + if (!isFinite(metrics.yMin)) { + metrics.yMin = 0; + } + if (!isFinite(metrics.yMax)) { + metrics.yMax = 0; + } + metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin); + return metrics; +}; +Glyph.prototype.draw = function(ctx, x2, y, fontSize, options) { + this.getPath(x2, y, fontSize, options).draw(ctx); +}; +Glyph.prototype.drawPoints = function(ctx, x2, y, fontSize) { + function drawCircles(l2, x3, y2, scale3) { + ctx.beginPath(); + for (var j2 = 0;j2 < l2.length; j2 += 1) { + ctx.moveTo(x3 + l2[j2].x * scale3, y2 + l2[j2].y * scale3); + ctx.arc(x3 + l2[j2].x * scale3, y2 + l2[j2].y * scale3, 2, 0, Math.PI * 2, false); + } + ctx.closePath(); + ctx.fill(); + } + x2 = x2 !== undefined ? x2 : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 24; + var scale2 = 1 / this.path.unitsPerEm * fontSize; + var blueCircles = []; + var redCircles = []; + var path = this.path; + for (var i = 0;i < path.commands.length; i += 1) { + var cmd = path.commands[i]; + if (cmd.x !== undefined) { + blueCircles.push({ x: cmd.x, y: -cmd.y }); + } + if (cmd.x1 !== undefined) { + redCircles.push({ x: cmd.x1, y: -cmd.y1 }); + } + if (cmd.x2 !== undefined) { + redCircles.push({ x: cmd.x2, y: -cmd.y2 }); + } + } + ctx.fillStyle = "blue"; + drawCircles(blueCircles, x2, y, scale2); + ctx.fillStyle = "red"; + drawCircles(redCircles, x2, y, scale2); +}; +Glyph.prototype.drawMetrics = function(ctx, x2, y, fontSize) { + var scale2; + x2 = x2 !== undefined ? x2 : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 24; + scale2 = 1 / this.path.unitsPerEm * fontSize; + ctx.lineWidth = 1; + ctx.strokeStyle = "black"; + draw.line(ctx, x2, -1e4, x2, 1e4); + draw.line(ctx, -1e4, y, 1e4, y); + var xMin = this.xMin || 0; + var yMin = this.yMin || 0; + var xMax = this.xMax || 0; + var yMax = this.yMax || 0; + var advanceWidth = this.advanceWidth || 0; + ctx.strokeStyle = "blue"; + draw.line(ctx, x2 + xMin * scale2, -1e4, x2 + xMin * scale2, 1e4); + draw.line(ctx, x2 + xMax * scale2, -1e4, x2 + xMax * scale2, 1e4); + draw.line(ctx, -1e4, y + -yMin * scale2, 1e4, y + -yMin * scale2); + draw.line(ctx, -1e4, y + -yMax * scale2, 1e4, y + -yMax * scale2); + ctx.strokeStyle = "green"; + draw.line(ctx, x2 + advanceWidth * scale2, -1e4, x2 + advanceWidth * scale2, 1e4); +}; +function defineDependentProperty(glyph, externalName, internalName) { + Object.defineProperty(glyph, externalName, { + get: function() { + glyph.path; + return glyph[internalName]; + }, + set: function(newValue) { + glyph[internalName] = newValue; + }, + enumerable: true, + configurable: true + }); +} +function GlyphSet(font, glyphs) { + this.font = font; + this.glyphs = {}; + if (Array.isArray(glyphs)) { + for (var i = 0;i < glyphs.length; i++) { + var glyph = glyphs[i]; + glyph.path.unitsPerEm = font.unitsPerEm; + this.glyphs[i] = glyph; + } + } + this.length = glyphs && glyphs.length || 0; +} +GlyphSet.prototype.get = function(index2) { + if (this.glyphs[index2] === undefined) { + this.font._push(index2); + if (typeof this.glyphs[index2] === "function") { + this.glyphs[index2] = this.glyphs[index2](); + } + var glyph = this.glyphs[index2]; + var unicodeObj = this.font._IndexToUnicodeMap[index2]; + if (unicodeObj) { + for (var j2 = 0;j2 < unicodeObj.unicodes.length; j2++) { + glyph.addUnicode(unicodeObj.unicodes[j2]); + } + } + if (this.font.cffEncoding) { + if (this.font.isCIDFont) { + glyph.name = "gid" + index2; + } else { + glyph.name = this.font.cffEncoding.charset[index2]; + } + } else if (this.font.glyphNames.names) { + glyph.name = this.font.glyphNames.glyphIndexToName(index2); + } + this.glyphs[index2].advanceWidth = this.font._hmtxTableData[index2].advanceWidth; + this.glyphs[index2].leftSideBearing = this.font._hmtxTableData[index2].leftSideBearing; + } else { + if (typeof this.glyphs[index2] === "function") { + this.glyphs[index2] = this.glyphs[index2](); + } + } + return this.glyphs[index2]; +}; +GlyphSet.prototype.push = function(index2, loader) { + this.glyphs[index2] = loader; + this.length++; +}; +function glyphLoader(font, index2) { + return new Glyph({ index: index2, font }); +} +function ttfGlyphLoader(font, index2, parseGlyph, data2, position2, buildPath) { + return function() { + var glyph = new Glyph({ index: index2, font }); + glyph.path = function() { + parseGlyph(glyph, data2, position2); + var path = buildPath(font.glyphs, glyph); + path.unitsPerEm = font.unitsPerEm; + return path; + }; + defineDependentProperty(glyph, "xMin", "_xMin"); + defineDependentProperty(glyph, "xMax", "_xMax"); + defineDependentProperty(glyph, "yMin", "_yMin"); + defineDependentProperty(glyph, "yMax", "_yMax"); + return glyph; + }; +} +function cffGlyphLoader(font, index2, parseCFFCharstring, charstring) { + return function() { + var glyph = new Glyph({ index: index2, font }); + glyph.path = function() { + var path = parseCFFCharstring(font, glyph, charstring); + path.unitsPerEm = font.unitsPerEm; + return path; + }; + return glyph; + }; +} +var glyphset = { GlyphSet, glyphLoader, ttfGlyphLoader, cffGlyphLoader }; +function equals2(a, b) { + if (a === b) { + return true; + } else if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return false; + } + for (var i = 0;i < a.length; i += 1) { + if (!equals2(a[i], b[i])) { + return false; + } + } + return true; + } else { + return false; + } +} +function calcCFFSubroutineBias(subrs) { + var bias; + if (subrs.length < 1240) { + bias = 107; + } else if (subrs.length < 33900) { + bias = 1131; + } else { + bias = 32768; + } + return bias; +} +function parseCFFIndex(data2, start, conversionFn) { + var offsets = []; + var objects = []; + var count = parse.getCard16(data2, start); + var objectOffset; + var endOffset; + if (count !== 0) { + var offsetSize = parse.getByte(data2, start + 2); + objectOffset = start + (count + 1) * offsetSize + 2; + var pos = start + 3; + for (var i = 0;i < count + 1; i += 1) { + offsets.push(parse.getOffset(data2, pos, offsetSize)); + pos += offsetSize; + } + endOffset = objectOffset + offsets[count]; + } else { + endOffset = start + 2; + } + for (var i$1 = 0;i$1 < offsets.length - 1; i$1 += 1) { + var value2 = parse.getBytes(data2, objectOffset + offsets[i$1], objectOffset + offsets[i$1 + 1]); + if (conversionFn) { + value2 = conversionFn(value2); + } + objects.push(value2); + } + return { objects, startOffset: start, endOffset }; +} +function parseCFFIndexLowMemory(data2, start) { + var offsets = []; + var count = parse.getCard16(data2, start); + var objectOffset; + var endOffset; + if (count !== 0) { + var offsetSize = parse.getByte(data2, start + 2); + objectOffset = start + (count + 1) * offsetSize + 2; + var pos = start + 3; + for (var i = 0;i < count + 1; i += 1) { + offsets.push(parse.getOffset(data2, pos, offsetSize)); + pos += offsetSize; + } + endOffset = objectOffset + offsets[count]; + } else { + endOffset = start + 2; + } + return { offsets, startOffset: start, endOffset }; +} +function getCffIndexObject(i, offsets, data2, start, conversionFn) { + var count = parse.getCard16(data2, start); + var objectOffset = 0; + if (count !== 0) { + var offsetSize = parse.getByte(data2, start + 2); + objectOffset = start + (count + 1) * offsetSize + 2; + } + var value2 = parse.getBytes(data2, objectOffset + offsets[i], objectOffset + offsets[i + 1]); + if (conversionFn) { + value2 = conversionFn(value2); + } + return value2; +} +function parseFloatOperand(parser) { + var s = ""; + var eof = 15; + var lookup = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "E", "E-", null, "-"]; + while (true) { + var b = parser.parseByte(); + var n1 = b >> 4; + var n2 = b & 15; + if (n1 === eof) { + break; + } + s += lookup[n1]; + if (n2 === eof) { + break; + } + s += lookup[n2]; + } + return parseFloat(s); +} +function parseOperand(parser, b0) { + var b1; + var b2; + var b3; + var b4; + if (b0 === 28) { + b1 = parser.parseByte(); + b2 = parser.parseByte(); + return b1 << 8 | b2; + } + if (b0 === 29) { + b1 = parser.parseByte(); + b2 = parser.parseByte(); + b3 = parser.parseByte(); + b4 = parser.parseByte(); + return b1 << 24 | b2 << 16 | b3 << 8 | b4; + } + if (b0 === 30) { + return parseFloatOperand(parser); + } + if (b0 >= 32 && b0 <= 246) { + return b0 - 139; + } + if (b0 >= 247 && b0 <= 250) { + b1 = parser.parseByte(); + return (b0 - 247) * 256 + b1 + 108; + } + if (b0 >= 251 && b0 <= 254) { + b1 = parser.parseByte(); + return -(b0 - 251) * 256 - b1 - 108; + } + throw new Error("Invalid b0 " + b0); +} +function entriesToObject(entries) { + var o = {}; + for (var i = 0;i < entries.length; i += 1) { + var key2 = entries[i][0]; + var values2 = entries[i][1]; + var value2 = undefined; + if (values2.length === 1) { + value2 = values2[0]; + } else { + value2 = values2; + } + if (o.hasOwnProperty(key2) && !isNaN(o[key2])) { + throw new Error("Object " + o + " already has key " + key2); + } + o[key2] = value2; + } + return o; +} +function parseCFFDict(data2, start, size) { + start = start !== undefined ? start : 0; + var parser = new parse.Parser(data2, start); + var entries = []; + var operands = []; + size = size !== undefined ? size : data2.length; + while (parser.relativeOffset < size) { + var op = parser.parseByte(); + if (op <= 21) { + if (op === 12) { + op = 1200 + parser.parseByte(); + } + entries.push([op, operands]); + operands = []; + } else { + operands.push(parseOperand(parser, op)); + } + } + return entriesToObject(entries); +} +function getCFFString(strings, index2) { + if (index2 <= 390) { + index2 = cffStandardStrings[index2]; + } else { + index2 = strings[index2 - 391]; + } + return index2; +} +function interpretDict(dict, meta, strings) { + var newDict = {}; + var value2; + for (var i = 0;i < meta.length; i += 1) { + var m = meta[i]; + if (Array.isArray(m.type)) { + var values2 = []; + values2.length = m.type.length; + for (var j2 = 0;j2 < m.type.length; j2++) { + value2 = dict[m.op] !== undefined ? dict[m.op][j2] : undefined; + if (value2 === undefined) { + value2 = m.value !== undefined && m.value[j2] !== undefined ? m.value[j2] : null; + } + if (m.type[j2] === "SID") { + value2 = getCFFString(strings, value2); + } + values2[j2] = value2; + } + newDict[m.name] = values2; + } else { + value2 = dict[m.op]; + if (value2 === undefined) { + value2 = m.value !== undefined ? m.value : null; + } + if (m.type === "SID") { + value2 = getCFFString(strings, value2); + } + newDict[m.name] = value2; + } + } + return newDict; +} +function parseCFFHeader(data2, start) { + var header = {}; + header.formatMajor = parse.getCard8(data2, start); + header.formatMinor = parse.getCard8(data2, start + 1); + header.size = parse.getCard8(data2, start + 2); + header.offsetSize = parse.getCard8(data2, start + 3); + header.startOffset = start; + header.endOffset = start + 4; + return header; +} +var TOP_DICT_META = [ + { name: "version", op: 0, type: "SID" }, + { name: "notice", op: 1, type: "SID" }, + { name: "copyright", op: 1200, type: "SID" }, + { name: "fullName", op: 2, type: "SID" }, + { name: "familyName", op: 3, type: "SID" }, + { name: "weight", op: 4, type: "SID" }, + { name: "isFixedPitch", op: 1201, type: "number", value: 0 }, + { name: "italicAngle", op: 1202, type: "number", value: 0 }, + { name: "underlinePosition", op: 1203, type: "number", value: -100 }, + { name: "underlineThickness", op: 1204, type: "number", value: 50 }, + { name: "paintType", op: 1205, type: "number", value: 0 }, + { name: "charstringType", op: 1206, type: "number", value: 2 }, + { + name: "fontMatrix", + op: 1207, + type: ["real", "real", "real", "real", "real", "real"], + value: [0.001, 0, 0, 0.001, 0, 0] + }, + { name: "uniqueId", op: 13, type: "number" }, + { name: "fontBBox", op: 5, type: ["number", "number", "number", "number"], value: [0, 0, 0, 0] }, + { name: "strokeWidth", op: 1208, type: "number", value: 0 }, + { name: "xuid", op: 14, type: [], value: null }, + { name: "charset", op: 15, type: "offset", value: 0 }, + { name: "encoding", op: 16, type: "offset", value: 0 }, + { name: "charStrings", op: 17, type: "offset", value: 0 }, + { name: "private", op: 18, type: ["number", "offset"], value: [0, 0] }, + { name: "ros", op: 1230, type: ["SID", "SID", "number"] }, + { name: "cidFontVersion", op: 1231, type: "number", value: 0 }, + { name: "cidFontRevision", op: 1232, type: "number", value: 0 }, + { name: "cidFontType", op: 1233, type: "number", value: 0 }, + { name: "cidCount", op: 1234, type: "number", value: 8720 }, + { name: "uidBase", op: 1235, type: "number" }, + { name: "fdArray", op: 1236, type: "offset" }, + { name: "fdSelect", op: 1237, type: "offset" }, + { name: "fontName", op: 1238, type: "SID" } +]; +var PRIVATE_DICT_META = [ + { name: "subrs", op: 19, type: "offset", value: 0 }, + { name: "defaultWidthX", op: 20, type: "number", value: 0 }, + { name: "nominalWidthX", op: 21, type: "number", value: 0 } +]; +function parseCFFTopDict(data2, strings) { + var dict = parseCFFDict(data2, 0, data2.byteLength); + return interpretDict(dict, TOP_DICT_META, strings); +} +function parseCFFPrivateDict(data2, start, size, strings) { + var dict = parseCFFDict(data2, start, size); + return interpretDict(dict, PRIVATE_DICT_META, strings); +} +function gatherCFFTopDicts(data2, start, cffIndex, strings) { + var topDictArray = []; + for (var iTopDict = 0;iTopDict < cffIndex.length; iTopDict += 1) { + var topDictData = new DataView(new Uint8Array(cffIndex[iTopDict]).buffer); + var topDict = parseCFFTopDict(topDictData, strings); + topDict._subrs = []; + topDict._subrsBias = 0; + topDict._defaultWidthX = 0; + topDict._nominalWidthX = 0; + var privateSize = topDict.private[0]; + var privateOffset = topDict.private[1]; + if (privateSize !== 0 && privateOffset !== 0) { + var privateDict = parseCFFPrivateDict(data2, privateOffset + start, privateSize, strings); + topDict._defaultWidthX = privateDict.defaultWidthX; + topDict._nominalWidthX = privateDict.nominalWidthX; + if (privateDict.subrs !== 0) { + var subrOffset = privateOffset + privateDict.subrs; + var subrIndex = parseCFFIndex(data2, subrOffset + start); + topDict._subrs = subrIndex.objects; + topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs); + } + topDict._privateDict = privateDict; + } + topDictArray.push(topDict); + } + return topDictArray; +} +function parseCFFCharset(data2, start, nGlyphs, strings) { + var sid; + var count; + var parser = new parse.Parser(data2, start); + nGlyphs -= 1; + var charset = [".notdef"]; + var format = parser.parseCard8(); + if (format === 0) { + for (var i = 0;i < nGlyphs; i += 1) { + sid = parser.parseSID(); + charset.push(getCFFString(strings, sid)); + } + } else if (format === 1) { + while (charset.length <= nGlyphs) { + sid = parser.parseSID(); + count = parser.parseCard8(); + for (var i$1 = 0;i$1 <= count; i$1 += 1) { + charset.push(getCFFString(strings, sid)); + sid += 1; + } + } + } else if (format === 2) { + while (charset.length <= nGlyphs) { + sid = parser.parseSID(); + count = parser.parseCard16(); + for (var i$2 = 0;i$2 <= count; i$2 += 1) { + charset.push(getCFFString(strings, sid)); + sid += 1; + } + } + } else { + throw new Error("Unknown charset format " + format); + } + return charset; +} +function parseCFFEncoding(data2, start, charset) { + var code; + var enc = {}; + var parser = new parse.Parser(data2, start); + var format = parser.parseCard8(); + if (format === 0) { + var nCodes = parser.parseCard8(); + for (var i = 0;i < nCodes; i += 1) { + code = parser.parseCard8(); + enc[code] = i; + } + } else if (format === 1) { + var nRanges = parser.parseCard8(); + code = 1; + for (var i$1 = 0;i$1 < nRanges; i$1 += 1) { + var first2 = parser.parseCard8(); + var nLeft = parser.parseCard8(); + for (var j2 = first2;j2 <= first2 + nLeft; j2 += 1) { + enc[j2] = code; + code += 1; + } + } + } else { + throw new Error("Unknown encoding format " + format); + } + return new CffEncoding(enc, charset); +} +function parseCFFCharstring(font, glyph, code) { + var c1x; + var c1y; + var c2x; + var c2y; + var p = new Path2; + var stack = []; + var nStems = 0; + var haveWidth = false; + var open = false; + var x2 = 0; + var y = 0; + var subrs; + var subrsBias; + var defaultWidthX; + var nominalWidthX; + if (font.isCIDFont) { + var fdIndex = font.tables.cff.topDict._fdSelect[glyph.index]; + var fdDict = font.tables.cff.topDict._fdArray[fdIndex]; + subrs = fdDict._subrs; + subrsBias = fdDict._subrsBias; + defaultWidthX = fdDict._defaultWidthX; + nominalWidthX = fdDict._nominalWidthX; + } else { + subrs = font.tables.cff.topDict._subrs; + subrsBias = font.tables.cff.topDict._subrsBias; + defaultWidthX = font.tables.cff.topDict._defaultWidthX; + nominalWidthX = font.tables.cff.topDict._nominalWidthX; + } + var width2 = defaultWidthX; + function newContour(x3, y2) { + if (open) { + p.closePath(); + } + p.moveTo(x3, y2); + open = true; + } + function parseStems() { + var hasWidthArg; + hasWidthArg = stack.length % 2 !== 0; + if (hasWidthArg && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + } + nStems += stack.length >> 1; + stack.length = 0; + haveWidth = true; + } + function parse2(code2) { + var b1; + var b2; + var b3; + var b4; + var codeIndex; + var subrCode; + var jpx; + var jpy; + var c3x; + var c3y; + var c4x; + var c4y; + var i = 0; + while (i < code2.length) { + var v = code2[i]; + i += 1; + switch (v) { + case 1: + parseStems(); + break; + case 3: + parseStems(); + break; + case 4: + if (stack.length > 1 && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + haveWidth = true; + } + y += stack.pop(); + newContour(x2, y); + break; + case 5: + while (stack.length > 0) { + x2 += stack.shift(); + y += stack.shift(); + p.lineTo(x2, y); + } + break; + case 6: + while (stack.length > 0) { + x2 += stack.shift(); + p.lineTo(x2, y); + if (stack.length === 0) { + break; + } + y += stack.shift(); + p.lineTo(x2, y); + } + break; + case 7: + while (stack.length > 0) { + y += stack.shift(); + p.lineTo(x2, y); + if (stack.length === 0) { + break; + } + x2 += stack.shift(); + p.lineTo(x2, y); + } + break; + case 8: + while (stack.length > 0) { + c1x = x2 + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + } + break; + case 10: + codeIndex = stack.pop() + subrsBias; + subrCode = subrs[codeIndex]; + if (subrCode) { + parse2(subrCode); + } + break; + case 11: + return; + case 12: + v = code2[i]; + i += 1; + switch (v) { + case 35: + c1x = x2 + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + jpx = c2x + stack.shift(); + jpy = c2y + stack.shift(); + c3x = jpx + stack.shift(); + c3y = jpy + stack.shift(); + c4x = c3x + stack.shift(); + c4y = c3y + stack.shift(); + x2 = c4x + stack.shift(); + y = c4y + stack.shift(); + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x2, y); + break; + case 34: + c1x = x2 + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + jpx = c2x + stack.shift(); + jpy = c2y; + c3x = jpx + stack.shift(); + c3y = c2y; + c4x = c3x + stack.shift(); + c4y = y; + x2 = c4x + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x2, y); + break; + case 36: + c1x = x2 + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + jpx = c2x + stack.shift(); + jpy = c2y; + c3x = jpx + stack.shift(); + c3y = c2y; + c4x = c3x + stack.shift(); + c4y = c3y + stack.shift(); + x2 = c4x + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x2, y); + break; + case 37: + c1x = x2 + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + jpx = c2x + stack.shift(); + jpy = c2y + stack.shift(); + c3x = jpx + stack.shift(); + c3y = jpy + stack.shift(); + c4x = c3x + stack.shift(); + c4y = c3y + stack.shift(); + if (Math.abs(c4x - x2) > Math.abs(c4y - y)) { + x2 = c4x + stack.shift(); + } else { + y = c4y + stack.shift(); + } + p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); + p.curveTo(c3x, c3y, c4x, c4y, x2, y); + break; + default: + console.log("Glyph " + glyph.index + ": unknown operator " + 1200 + v); + stack.length = 0; + } + break; + case 14: + if (stack.length > 0 && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + haveWidth = true; + } + if (open) { + p.closePath(); + open = false; + } + break; + case 18: + parseStems(); + break; + case 19: + case 20: + parseStems(); + i += nStems + 7 >> 3; + break; + case 21: + if (stack.length > 2 && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + haveWidth = true; + } + y += stack.pop(); + x2 += stack.pop(); + newContour(x2, y); + break; + case 22: + if (stack.length > 1 && !haveWidth) { + width2 = stack.shift() + nominalWidthX; + haveWidth = true; + } + x2 += stack.pop(); + newContour(x2, y); + break; + case 23: + parseStems(); + break; + case 24: + while (stack.length > 2) { + c1x = x2 + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + } + x2 += stack.shift(); + y += stack.shift(); + p.lineTo(x2, y); + break; + case 25: + while (stack.length > 6) { + x2 += stack.shift(); + y += stack.shift(); + p.lineTo(x2, y); + } + c1x = x2 + stack.shift(); + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + break; + case 26: + if (stack.length % 2) { + x2 += stack.shift(); + } + while (stack.length > 0) { + c1x = x2; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x; + y = c2y + stack.shift(); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + } + break; + case 27: + if (stack.length % 2) { + y += stack.shift(); + } + while (stack.length > 0) { + c1x = x2 + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y = c2y; + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + } + break; + case 28: + b1 = code2[i]; + b2 = code2[i + 1]; + stack.push((b1 << 24 | b2 << 16) >> 16); + i += 2; + break; + case 29: + codeIndex = stack.pop() + font.gsubrsBias; + subrCode = font.gsubrs[codeIndex]; + if (subrCode) { + parse2(subrCode); + } + break; + case 30: + while (stack.length > 0) { + c1x = x2; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y = c2y + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + if (stack.length === 0) { + break; + } + c1x = x2 + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + y = c2y + stack.shift(); + x2 = c2x + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + } + break; + case 31: + while (stack.length > 0) { + c1x = x2 + stack.shift(); + c1y = y; + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + y = c2y + stack.shift(); + x2 = c2x + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + if (stack.length === 0) { + break; + } + c1x = x2; + c1y = y + stack.shift(); + c2x = c1x + stack.shift(); + c2y = c1y + stack.shift(); + x2 = c2x + stack.shift(); + y = c2y + (stack.length === 1 ? stack.shift() : 0); + p.curveTo(c1x, c1y, c2x, c2y, x2, y); + } + break; + default: + if (v < 32) { + console.log("Glyph " + glyph.index + ": unknown operator " + v); + } else if (v < 247) { + stack.push(v - 139); + } else if (v < 251) { + b1 = code2[i]; + i += 1; + stack.push((v - 247) * 256 + b1 + 108); + } else if (v < 255) { + b1 = code2[i]; + i += 1; + stack.push(-(v - 251) * 256 - b1 - 108); + } else { + b1 = code2[i]; + b2 = code2[i + 1]; + b3 = code2[i + 2]; + b4 = code2[i + 3]; + i += 4; + stack.push((b1 << 24 | b2 << 16 | b3 << 8 | b4) / 65536); + } + } + } + } + parse2(code); + glyph.advanceWidth = width2; + return p; +} +function parseCFFFDSelect(data2, start, nGlyphs, fdArrayCount) { + var fdSelect = []; + var fdIndex; + var parser = new parse.Parser(data2, start); + var format = parser.parseCard8(); + if (format === 0) { + for (var iGid = 0;iGid < nGlyphs; iGid++) { + fdIndex = parser.parseCard8(); + if (fdIndex >= fdArrayCount) { + throw new Error("CFF table CID Font FDSelect has bad FD index value " + fdIndex + " (FD count " + fdArrayCount + ")"); + } + fdSelect.push(fdIndex); + } + } else if (format === 3) { + var nRanges = parser.parseCard16(); + var first2 = parser.parseCard16(); + if (first2 !== 0) { + throw new Error("CFF Table CID Font FDSelect format 3 range has bad initial GID " + first2); + } + var next; + for (var iRange = 0;iRange < nRanges; iRange++) { + fdIndex = parser.parseCard8(); + next = parser.parseCard16(); + if (fdIndex >= fdArrayCount) { + throw new Error("CFF table CID Font FDSelect has bad FD index value " + fdIndex + " (FD count " + fdArrayCount + ")"); + } + if (next > nGlyphs) { + throw new Error("CFF Table CID Font FDSelect format 3 range has bad GID " + next); + } + for (;first2 < next; first2++) { + fdSelect.push(fdIndex); + } + first2 = next; + } + if (next !== nGlyphs) { + throw new Error("CFF Table CID Font FDSelect format 3 range has bad final GID " + next); + } + } else { + throw new Error("CFF Table CID Font FDSelect table has unsupported format " + format); + } + return fdSelect; +} +function parseCFFTable(data2, start, font, opt) { + font.tables.cff = {}; + var header = parseCFFHeader(data2, start); + var nameIndex = parseCFFIndex(data2, header.endOffset, parse.bytesToString); + var topDictIndex = parseCFFIndex(data2, nameIndex.endOffset); + var stringIndex = parseCFFIndex(data2, topDictIndex.endOffset, parse.bytesToString); + var globalSubrIndex = parseCFFIndex(data2, stringIndex.endOffset); + font.gsubrs = globalSubrIndex.objects; + font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs); + var topDictArray = gatherCFFTopDicts(data2, start, topDictIndex.objects, stringIndex.objects); + if (topDictArray.length !== 1) { + throw new Error("CFF table has too many fonts in 'FontSet' - count of fonts NameIndex.length = " + topDictArray.length); + } + var topDict = topDictArray[0]; + font.tables.cff.topDict = topDict; + if (topDict._privateDict) { + font.defaultWidthX = topDict._privateDict.defaultWidthX; + font.nominalWidthX = topDict._privateDict.nominalWidthX; + } + if (topDict.ros[0] !== undefined && topDict.ros[1] !== undefined) { + font.isCIDFont = true; + } + if (font.isCIDFont) { + var fdArrayOffset = topDict.fdArray; + var fdSelectOffset = topDict.fdSelect; + if (fdArrayOffset === 0 || fdSelectOffset === 0) { + throw new Error("Font is marked as a CID font, but FDArray and/or FDSelect information is missing"); + } + fdArrayOffset += start; + var fdArrayIndex = parseCFFIndex(data2, fdArrayOffset); + var fdArray = gatherCFFTopDicts(data2, start, fdArrayIndex.objects, stringIndex.objects); + topDict._fdArray = fdArray; + fdSelectOffset += start; + topDict._fdSelect = parseCFFFDSelect(data2, fdSelectOffset, font.numGlyphs, fdArray.length); + } + var privateDictOffset = start + topDict.private[1]; + var privateDict = parseCFFPrivateDict(data2, privateDictOffset, topDict.private[0], stringIndex.objects); + font.defaultWidthX = privateDict.defaultWidthX; + font.nominalWidthX = privateDict.nominalWidthX; + if (privateDict.subrs !== 0) { + var subrOffset = privateDictOffset + privateDict.subrs; + var subrIndex = parseCFFIndex(data2, subrOffset); + font.subrs = subrIndex.objects; + font.subrsBias = calcCFFSubroutineBias(font.subrs); + } else { + font.subrs = []; + font.subrsBias = 0; + } + var charStringsIndex; + if (opt.lowMemory) { + charStringsIndex = parseCFFIndexLowMemory(data2, start + topDict.charStrings); + font.nGlyphs = charStringsIndex.offsets.length; + } else { + charStringsIndex = parseCFFIndex(data2, start + topDict.charStrings); + font.nGlyphs = charStringsIndex.objects.length; + } + var charset = parseCFFCharset(data2, start + topDict.charset, font.nGlyphs, stringIndex.objects); + if (topDict.encoding === 0) { + font.cffEncoding = new CffEncoding(cffStandardEncoding, charset); + } else if (topDict.encoding === 1) { + font.cffEncoding = new CffEncoding(cffExpertEncoding, charset); + } else { + font.cffEncoding = parseCFFEncoding(data2, start + topDict.encoding, charset); + } + font.encoding = font.encoding || font.cffEncoding; + font.glyphs = new glyphset.GlyphSet(font); + if (opt.lowMemory) { + font._push = function(i2) { + var charString2 = getCffIndexObject(i2, charStringsIndex.offsets, data2, start + topDict.charStrings); + font.glyphs.push(i2, glyphset.cffGlyphLoader(font, i2, parseCFFCharstring, charString2)); + }; + } else { + for (var i = 0;i < font.nGlyphs; i += 1) { + var charString = charStringsIndex.objects[i]; + font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); + } + } +} +function encodeString(s, strings) { + var sid; + var i = cffStandardStrings.indexOf(s); + if (i >= 0) { + sid = i; + } + i = strings.indexOf(s); + if (i >= 0) { + sid = i + cffStandardStrings.length; + } else { + sid = cffStandardStrings.length + strings.length; + strings.push(s); + } + return sid; +} +function makeHeader() { + return new table.Record("Header", [ + { name: "major", type: "Card8", value: 1 }, + { name: "minor", type: "Card8", value: 0 }, + { name: "hdrSize", type: "Card8", value: 4 }, + { name: "major", type: "Card8", value: 1 } + ]); +} +function makeNameIndex(fontNames) { + var t2 = new table.Record("Name INDEX", [ + { name: "names", type: "INDEX", value: [] } + ]); + t2.names = []; + for (var i = 0;i < fontNames.length; i += 1) { + t2.names.push({ name: "name_" + i, type: "NAME", value: fontNames[i] }); + } + return t2; +} +function makeDict(meta, attrs, strings) { + var m = {}; + for (var i = 0;i < meta.length; i += 1) { + var entry = meta[i]; + var value2 = attrs[entry.name]; + if (value2 !== undefined && !equals2(value2, entry.value)) { + if (entry.type === "SID") { + value2 = encodeString(value2, strings); + } + m[entry.op] = { name: entry.name, type: entry.type, value: value2 }; + } + } + return m; +} +function makeTopDict(attrs, strings) { + var t2 = new table.Record("Top DICT", [ + { name: "dict", type: "DICT", value: {} } + ]); + t2.dict = makeDict(TOP_DICT_META, attrs, strings); + return t2; +} +function makeTopDictIndex(topDict) { + var t2 = new table.Record("Top DICT INDEX", [ + { name: "topDicts", type: "INDEX", value: [] } + ]); + t2.topDicts = [{ name: "topDict_0", type: "TABLE", value: topDict }]; + return t2; +} +function makeStringIndex(strings) { + var t2 = new table.Record("String INDEX", [ + { name: "strings", type: "INDEX", value: [] } + ]); + t2.strings = []; + for (var i = 0;i < strings.length; i += 1) { + t2.strings.push({ name: "string_" + i, type: "STRING", value: strings[i] }); + } + return t2; +} +function makeGlobalSubrIndex() { + return new table.Record("Global Subr INDEX", [ + { name: "subrs", type: "INDEX", value: [] } + ]); +} +function makeCharsets(glyphNames, strings) { + var t2 = new table.Record("Charsets", [ + { name: "format", type: "Card8", value: 0 } + ]); + for (var i = 0;i < glyphNames.length; i += 1) { + var glyphName = glyphNames[i]; + var glyphSID = encodeString(glyphName, strings); + t2.fields.push({ name: "glyph_" + i, type: "SID", value: glyphSID }); + } + return t2; +} +function glyphToOps(glyph) { + var ops = []; + var path = glyph.path; + ops.push({ name: "width", type: "NUMBER", value: glyph.advanceWidth }); + var x2 = 0; + var y = 0; + for (var i = 0;i < path.commands.length; i += 1) { + var dx = undefined; + var dy = undefined; + var cmd = path.commands[i]; + if (cmd.type === "Q") { + var _13 = 1 / 3; + var _23 = 2 / 3; + cmd = { + type: "C", + x: cmd.x, + y: cmd.y, + x1: Math.round(_13 * x2 + _23 * cmd.x1), + y1: Math.round(_13 * y + _23 * cmd.y1), + x2: Math.round(_13 * cmd.x + _23 * cmd.x1), + y2: Math.round(_13 * cmd.y + _23 * cmd.y1) + }; + } + if (cmd.type === "M") { + dx = Math.round(cmd.x - x2); + dy = Math.round(cmd.y - y); + ops.push({ name: "dx", type: "NUMBER", value: dx }); + ops.push({ name: "dy", type: "NUMBER", value: dy }); + ops.push({ name: "rmoveto", type: "OP", value: 21 }); + x2 = Math.round(cmd.x); + y = Math.round(cmd.y); + } else if (cmd.type === "L") { + dx = Math.round(cmd.x - x2); + dy = Math.round(cmd.y - y); + ops.push({ name: "dx", type: "NUMBER", value: dx }); + ops.push({ name: "dy", type: "NUMBER", value: dy }); + ops.push({ name: "rlineto", type: "OP", value: 5 }); + x2 = Math.round(cmd.x); + y = Math.round(cmd.y); + } else if (cmd.type === "C") { + var dx1 = Math.round(cmd.x1 - x2); + var dy1 = Math.round(cmd.y1 - y); + var dx2 = Math.round(cmd.x2 - cmd.x1); + var dy2 = Math.round(cmd.y2 - cmd.y1); + dx = Math.round(cmd.x - cmd.x2); + dy = Math.round(cmd.y - cmd.y2); + ops.push({ name: "dx1", type: "NUMBER", value: dx1 }); + ops.push({ name: "dy1", type: "NUMBER", value: dy1 }); + ops.push({ name: "dx2", type: "NUMBER", value: dx2 }); + ops.push({ name: "dy2", type: "NUMBER", value: dy2 }); + ops.push({ name: "dx", type: "NUMBER", value: dx }); + ops.push({ name: "dy", type: "NUMBER", value: dy }); + ops.push({ name: "rrcurveto", type: "OP", value: 8 }); + x2 = Math.round(cmd.x); + y = Math.round(cmd.y); + } + } + ops.push({ name: "endchar", type: "OP", value: 14 }); + return ops; +} +function makeCharStringsIndex(glyphs) { + var t2 = new table.Record("CharStrings INDEX", [ + { name: "charStrings", type: "INDEX", value: [] } + ]); + for (var i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + var ops = glyphToOps(glyph); + t2.charStrings.push({ name: glyph.name, type: "CHARSTRING", value: ops }); + } + return t2; +} +function makePrivateDict(attrs, strings) { + var t2 = new table.Record("Private DICT", [ + { name: "dict", type: "DICT", value: {} } + ]); + t2.dict = makeDict(PRIVATE_DICT_META, attrs, strings); + return t2; +} +function makeCFFTable(glyphs, options) { + var t2 = new table.Table("CFF ", [ + { name: "header", type: "RECORD" }, + { name: "nameIndex", type: "RECORD" }, + { name: "topDictIndex", type: "RECORD" }, + { name: "stringIndex", type: "RECORD" }, + { name: "globalSubrIndex", type: "RECORD" }, + { name: "charsets", type: "RECORD" }, + { name: "charStringsIndex", type: "RECORD" }, + { name: "privateDict", type: "RECORD" } + ]); + var fontScale = 1 / options.unitsPerEm; + var attrs = { + version: options.version, + fullName: options.fullName, + familyName: options.familyName, + weight: options.weightName, + fontBBox: options.fontBBox || [0, 0, 0, 0], + fontMatrix: [fontScale, 0, 0, fontScale, 0, 0], + charset: 999, + encoding: 0, + charStrings: 999, + private: [0, 999] + }; + var privateAttrs = {}; + var glyphNames = []; + var glyph; + for (var i = 1;i < glyphs.length; i += 1) { + glyph = glyphs.get(i); + glyphNames.push(glyph.name); + } + var strings = []; + t2.header = makeHeader(); + t2.nameIndex = makeNameIndex([options.postScriptName]); + var topDict = makeTopDict(attrs, strings); + t2.topDictIndex = makeTopDictIndex(topDict); + t2.globalSubrIndex = makeGlobalSubrIndex(); + t2.charsets = makeCharsets(glyphNames, strings); + t2.charStringsIndex = makeCharStringsIndex(glyphs); + t2.privateDict = makePrivateDict(privateAttrs, strings); + t2.stringIndex = makeStringIndex(strings); + var startOffset = t2.header.sizeOf() + t2.nameIndex.sizeOf() + t2.topDictIndex.sizeOf() + t2.stringIndex.sizeOf() + t2.globalSubrIndex.sizeOf(); + attrs.charset = startOffset; + attrs.encoding = 0; + attrs.charStrings = attrs.charset + t2.charsets.sizeOf(); + attrs.private[1] = attrs.charStrings + t2.charStringsIndex.sizeOf(); + topDict = makeTopDict(attrs, strings); + t2.topDictIndex = makeTopDictIndex(topDict); + return t2; +} +var cff = { parse: parseCFFTable, make: makeCFFTable }; +function parseHeadTable(data2, start) { + var head = {}; + var p = new parse.Parser(data2, start); + head.version = p.parseVersion(); + head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000; + head.checkSumAdjustment = p.parseULong(); + head.magicNumber = p.parseULong(); + check.argument(head.magicNumber === 1594834165, "Font header has wrong magic number."); + head.flags = p.parseUShort(); + head.unitsPerEm = p.parseUShort(); + head.created = p.parseLongDateTime(); + head.modified = p.parseLongDateTime(); + head.xMin = p.parseShort(); + head.yMin = p.parseShort(); + head.xMax = p.parseShort(); + head.yMax = p.parseShort(); + head.macStyle = p.parseUShort(); + head.lowestRecPPEM = p.parseUShort(); + head.fontDirectionHint = p.parseShort(); + head.indexToLocFormat = p.parseShort(); + head.glyphDataFormat = p.parseShort(); + return head; +} +function makeHeadTable(options) { + var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800; + var createdTimestamp = timestamp; + if (options.createdTimestamp) { + createdTimestamp = options.createdTimestamp + 2082844800; + } + return new table.Table("head", [ + { name: "version", type: "FIXED", value: 65536 }, + { name: "fontRevision", type: "FIXED", value: 65536 }, + { name: "checkSumAdjustment", type: "ULONG", value: 0 }, + { name: "magicNumber", type: "ULONG", value: 1594834165 }, + { name: "flags", type: "USHORT", value: 0 }, + { name: "unitsPerEm", type: "USHORT", value: 1000 }, + { name: "created", type: "LONGDATETIME", value: createdTimestamp }, + { name: "modified", type: "LONGDATETIME", value: timestamp }, + { name: "xMin", type: "SHORT", value: 0 }, + { name: "yMin", type: "SHORT", value: 0 }, + { name: "xMax", type: "SHORT", value: 0 }, + { name: "yMax", type: "SHORT", value: 0 }, + { name: "macStyle", type: "USHORT", value: 0 }, + { name: "lowestRecPPEM", type: "USHORT", value: 0 }, + { name: "fontDirectionHint", type: "SHORT", value: 2 }, + { name: "indexToLocFormat", type: "SHORT", value: 0 }, + { name: "glyphDataFormat", type: "SHORT", value: 0 } + ], options); +} +var head = { parse: parseHeadTable, make: makeHeadTable }; +function parseHheaTable(data2, start) { + var hhea = {}; + var p = new parse.Parser(data2, start); + hhea.version = p.parseVersion(); + hhea.ascender = p.parseShort(); + hhea.descender = p.parseShort(); + hhea.lineGap = p.parseShort(); + hhea.advanceWidthMax = p.parseUShort(); + hhea.minLeftSideBearing = p.parseShort(); + hhea.minRightSideBearing = p.parseShort(); + hhea.xMaxExtent = p.parseShort(); + hhea.caretSlopeRise = p.parseShort(); + hhea.caretSlopeRun = p.parseShort(); + hhea.caretOffset = p.parseShort(); + p.relativeOffset += 8; + hhea.metricDataFormat = p.parseShort(); + hhea.numberOfHMetrics = p.parseUShort(); + return hhea; +} +function makeHheaTable(options) { + return new table.Table("hhea", [ + { name: "version", type: "FIXED", value: 65536 }, + { name: "ascender", type: "FWORD", value: 0 }, + { name: "descender", type: "FWORD", value: 0 }, + { name: "lineGap", type: "FWORD", value: 0 }, + { name: "advanceWidthMax", type: "UFWORD", value: 0 }, + { name: "minLeftSideBearing", type: "FWORD", value: 0 }, + { name: "minRightSideBearing", type: "FWORD", value: 0 }, + { name: "xMaxExtent", type: "FWORD", value: 0 }, + { name: "caretSlopeRise", type: "SHORT", value: 1 }, + { name: "caretSlopeRun", type: "SHORT", value: 0 }, + { name: "caretOffset", type: "SHORT", value: 0 }, + { name: "reserved1", type: "SHORT", value: 0 }, + { name: "reserved2", type: "SHORT", value: 0 }, + { name: "reserved3", type: "SHORT", value: 0 }, + { name: "reserved4", type: "SHORT", value: 0 }, + { name: "metricDataFormat", type: "SHORT", value: 0 }, + { name: "numberOfHMetrics", type: "USHORT", value: 0 } + ], options); +} +var hhea = { parse: parseHheaTable, make: makeHheaTable }; +function parseHmtxTableAll(data2, start, numMetrics, numGlyphs, glyphs) { + var advanceWidth; + var leftSideBearing; + var p = new parse.Parser(data2, start); + for (var i = 0;i < numGlyphs; i += 1) { + if (i < numMetrics) { + advanceWidth = p.parseUShort(); + leftSideBearing = p.parseShort(); + } + var glyph = glyphs.get(i); + glyph.advanceWidth = advanceWidth; + glyph.leftSideBearing = leftSideBearing; + } +} +function parseHmtxTableOnLowMemory(font, data2, start, numMetrics, numGlyphs) { + font._hmtxTableData = {}; + var advanceWidth; + var leftSideBearing; + var p = new parse.Parser(data2, start); + for (var i = 0;i < numGlyphs; i += 1) { + if (i < numMetrics) { + advanceWidth = p.parseUShort(); + leftSideBearing = p.parseShort(); + } + font._hmtxTableData[i] = { + advanceWidth, + leftSideBearing + }; + } +} +function parseHmtxTable(font, data2, start, numMetrics, numGlyphs, glyphs, opt) { + if (opt.lowMemory) { + parseHmtxTableOnLowMemory(font, data2, start, numMetrics, numGlyphs); + } else { + parseHmtxTableAll(data2, start, numMetrics, numGlyphs, glyphs); + } +} +function makeHmtxTable(glyphs) { + var t2 = new table.Table("hmtx", []); + for (var i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs.get(i); + var advanceWidth = glyph.advanceWidth || 0; + var leftSideBearing = glyph.leftSideBearing || 0; + t2.fields.push({ name: "advanceWidth_" + i, type: "USHORT", value: advanceWidth }); + t2.fields.push({ name: "leftSideBearing_" + i, type: "SHORT", value: leftSideBearing }); + } + return t2; +} +var hmtx = { parse: parseHmtxTable, make: makeHmtxTable }; +function makeLtagTable(tags) { + var result = new table.Table("ltag", [ + { name: "version", type: "ULONG", value: 1 }, + { name: "flags", type: "ULONG", value: 0 }, + { name: "numTags", type: "ULONG", value: tags.length } + ]); + var stringPool = ""; + var stringPoolOffset = 12 + tags.length * 4; + for (var i = 0;i < tags.length; ++i) { + var pos = stringPool.indexOf(tags[i]); + if (pos < 0) { + pos = stringPool.length; + stringPool += tags[i]; + } + result.fields.push({ name: "offset " + i, type: "USHORT", value: stringPoolOffset + pos }); + result.fields.push({ name: "length " + i, type: "USHORT", value: tags[i].length }); + } + result.fields.push({ name: "stringPool", type: "CHARARRAY", value: stringPool }); + return result; +} +function parseLtagTable(data2, start) { + var p = new parse.Parser(data2, start); + var tableVersion = p.parseULong(); + check.argument(tableVersion === 1, "Unsupported ltag table version."); + p.skip("uLong", 1); + var numTags = p.parseULong(); + var tags = []; + for (var i = 0;i < numTags; i++) { + var tag = ""; + var offset = start + p.parseUShort(); + var length2 = p.parseUShort(); + for (var j2 = offset;j2 < offset + length2; ++j2) { + tag += String.fromCharCode(data2.getInt8(j2)); + } + tags.push(tag); + } + return tags; +} +var ltag = { make: makeLtagTable, parse: parseLtagTable }; +function parseMaxpTable(data2, start) { + var maxp = {}; + var p = new parse.Parser(data2, start); + maxp.version = p.parseVersion(); + maxp.numGlyphs = p.parseUShort(); + if (maxp.version === 1) { + maxp.maxPoints = p.parseUShort(); + maxp.maxContours = p.parseUShort(); + maxp.maxCompositePoints = p.parseUShort(); + maxp.maxCompositeContours = p.parseUShort(); + maxp.maxZones = p.parseUShort(); + maxp.maxTwilightPoints = p.parseUShort(); + maxp.maxStorage = p.parseUShort(); + maxp.maxFunctionDefs = p.parseUShort(); + maxp.maxInstructionDefs = p.parseUShort(); + maxp.maxStackElements = p.parseUShort(); + maxp.maxSizeOfInstructions = p.parseUShort(); + maxp.maxComponentElements = p.parseUShort(); + maxp.maxComponentDepth = p.parseUShort(); + } + return maxp; +} +function makeMaxpTable(numGlyphs) { + return new table.Table("maxp", [ + { name: "version", type: "FIXED", value: 20480 }, + { name: "numGlyphs", type: "USHORT", value: numGlyphs } + ]); +} +var maxp = { parse: parseMaxpTable, make: makeMaxpTable }; +var nameTableNames = [ + "copyright", + "fontFamily", + "fontSubfamily", + "uniqueID", + "fullName", + "version", + "postScriptName", + "trademark", + "manufacturer", + "designer", + "description", + "manufacturerURL", + "designerURL", + "license", + "licenseURL", + "reserved", + "preferredFamily", + "preferredSubfamily", + "compatibleFullName", + "sampleText", + "postScriptFindFontName", + "wwsFamily", + "wwsSubfamily" +]; +var macLanguages = { + 0: "en", + 1: "fr", + 2: "de", + 3: "it", + 4: "nl", + 5: "sv", + 6: "es", + 7: "da", + 8: "pt", + 9: "no", + 10: "he", + 11: "ja", + 12: "ar", + 13: "fi", + 14: "el", + 15: "is", + 16: "mt", + 17: "tr", + 18: "hr", + 19: "zh-Hant", + 20: "ur", + 21: "hi", + 22: "th", + 23: "ko", + 24: "lt", + 25: "pl", + 26: "hu", + 27: "es", + 28: "lv", + 29: "se", + 30: "fo", + 31: "fa", + 32: "ru", + 33: "zh", + 34: "nl-BE", + 35: "ga", + 36: "sq", + 37: "ro", + 38: "cz", + 39: "sk", + 40: "si", + 41: "yi", + 42: "sr", + 43: "mk", + 44: "bg", + 45: "uk", + 46: "be", + 47: "uz", + 48: "kk", + 49: "az-Cyrl", + 50: "az-Arab", + 51: "hy", + 52: "ka", + 53: "mo", + 54: "ky", + 55: "tg", + 56: "tk", + 57: "mn-CN", + 58: "mn", + 59: "ps", + 60: "ks", + 61: "ku", + 62: "sd", + 63: "bo", + 64: "ne", + 65: "sa", + 66: "mr", + 67: "bn", + 68: "as", + 69: "gu", + 70: "pa", + 71: "or", + 72: "ml", + 73: "kn", + 74: "ta", + 75: "te", + 76: "si", + 77: "my", + 78: "km", + 79: "lo", + 80: "vi", + 81: "id", + 82: "tl", + 83: "ms", + 84: "ms-Arab", + 85: "am", + 86: "ti", + 87: "om", + 88: "so", + 89: "sw", + 90: "rw", + 91: "rn", + 92: "ny", + 93: "mg", + 94: "eo", + 128: "cy", + 129: "eu", + 130: "ca", + 131: "la", + 132: "qu", + 133: "gn", + 134: "ay", + 135: "tt", + 136: "ug", + 137: "dz", + 138: "jv", + 139: "su", + 140: "gl", + 141: "af", + 142: "br", + 143: "iu", + 144: "gd", + 145: "gv", + 146: "ga", + 147: "to", + 148: "el-polyton", + 149: "kl", + 150: "az", + 151: "nn" +}; +var macLanguageToScript = { + 0: 0, + 1: 0, + 2: 0, + 3: 0, + 4: 0, + 5: 0, + 6: 0, + 7: 0, + 8: 0, + 9: 0, + 10: 5, + 11: 1, + 12: 4, + 13: 0, + 14: 6, + 15: 0, + 16: 0, + 17: 0, + 18: 0, + 19: 2, + 20: 4, + 21: 9, + 22: 21, + 23: 3, + 24: 29, + 25: 29, + 26: 29, + 27: 29, + 28: 29, + 29: 0, + 30: 0, + 31: 4, + 32: 7, + 33: 25, + 34: 0, + 35: 0, + 36: 0, + 37: 0, + 38: 29, + 39: 29, + 40: 0, + 41: 5, + 42: 7, + 43: 7, + 44: 7, + 45: 7, + 46: 7, + 47: 7, + 48: 7, + 49: 7, + 50: 4, + 51: 24, + 52: 23, + 53: 7, + 54: 7, + 55: 7, + 56: 7, + 57: 27, + 58: 7, + 59: 4, + 60: 4, + 61: 4, + 62: 4, + 63: 26, + 64: 9, + 65: 9, + 66: 9, + 67: 13, + 68: 13, + 69: 11, + 70: 10, + 71: 12, + 72: 17, + 73: 16, + 74: 14, + 75: 15, + 76: 18, + 77: 19, + 78: 20, + 79: 22, + 80: 30, + 81: 0, + 82: 0, + 83: 0, + 84: 4, + 85: 28, + 86: 28, + 87: 28, + 88: 0, + 89: 0, + 90: 0, + 91: 0, + 92: 0, + 93: 0, + 94: 0, + 128: 0, + 129: 0, + 130: 0, + 131: 0, + 132: 0, + 133: 0, + 134: 0, + 135: 7, + 136: 4, + 137: 26, + 138: 0, + 139: 0, + 140: 0, + 141: 0, + 142: 0, + 143: 28, + 144: 0, + 145: 0, + 146: 0, + 147: 0, + 148: 6, + 149: 0, + 150: 0, + 151: 0 +}; +var windowsLanguages = { + 1078: "af", + 1052: "sq", + 1156: "gsw", + 1118: "am", + 5121: "ar-DZ", + 15361: "ar-BH", + 3073: "ar", + 2049: "ar-IQ", + 11265: "ar-JO", + 13313: "ar-KW", + 12289: "ar-LB", + 4097: "ar-LY", + 6145: "ary", + 8193: "ar-OM", + 16385: "ar-QA", + 1025: "ar-SA", + 10241: "ar-SY", + 7169: "aeb", + 14337: "ar-AE", + 9217: "ar-YE", + 1067: "hy", + 1101: "as", + 2092: "az-Cyrl", + 1068: "az", + 1133: "ba", + 1069: "eu", + 1059: "be", + 2117: "bn", + 1093: "bn-IN", + 8218: "bs-Cyrl", + 5146: "bs", + 1150: "br", + 1026: "bg", + 1027: "ca", + 3076: "zh-HK", + 5124: "zh-MO", + 2052: "zh", + 4100: "zh-SG", + 1028: "zh-TW", + 1155: "co", + 1050: "hr", + 4122: "hr-BA", + 1029: "cs", + 1030: "da", + 1164: "prs", + 1125: "dv", + 2067: "nl-BE", + 1043: "nl", + 3081: "en-AU", + 10249: "en-BZ", + 4105: "en-CA", + 9225: "en-029", + 16393: "en-IN", + 6153: "en-IE", + 8201: "en-JM", + 17417: "en-MY", + 5129: "en-NZ", + 13321: "en-PH", + 18441: "en-SG", + 7177: "en-ZA", + 11273: "en-TT", + 2057: "en-GB", + 1033: "en", + 12297: "en-ZW", + 1061: "et", + 1080: "fo", + 1124: "fil", + 1035: "fi", + 2060: "fr-BE", + 3084: "fr-CA", + 1036: "fr", + 5132: "fr-LU", + 6156: "fr-MC", + 4108: "fr-CH", + 1122: "fy", + 1110: "gl", + 1079: "ka", + 3079: "de-AT", + 1031: "de", + 5127: "de-LI", + 4103: "de-LU", + 2055: "de-CH", + 1032: "el", + 1135: "kl", + 1095: "gu", + 1128: "ha", + 1037: "he", + 1081: "hi", + 1038: "hu", + 1039: "is", + 1136: "ig", + 1057: "id", + 1117: "iu", + 2141: "iu-Latn", + 2108: "ga", + 1076: "xh", + 1077: "zu", + 1040: "it", + 2064: "it-CH", + 1041: "ja", + 1099: "kn", + 1087: "kk", + 1107: "km", + 1158: "quc", + 1159: "rw", + 1089: "sw", + 1111: "kok", + 1042: "ko", + 1088: "ky", + 1108: "lo", + 1062: "lv", + 1063: "lt", + 2094: "dsb", + 1134: "lb", + 1071: "mk", + 2110: "ms-BN", + 1086: "ms", + 1100: "ml", + 1082: "mt", + 1153: "mi", + 1146: "arn", + 1102: "mr", + 1148: "moh", + 1104: "mn", + 2128: "mn-CN", + 1121: "ne", + 1044: "nb", + 2068: "nn", + 1154: "oc", + 1096: "or", + 1123: "ps", + 1045: "pl", + 1046: "pt", + 2070: "pt-PT", + 1094: "pa", + 1131: "qu-BO", + 2155: "qu-EC", + 3179: "qu", + 1048: "ro", + 1047: "rm", + 1049: "ru", + 9275: "smn", + 4155: "smj-NO", + 5179: "smj", + 3131: "se-FI", + 1083: "se", + 2107: "se-SE", + 8251: "sms", + 6203: "sma-NO", + 7227: "sms", + 1103: "sa", + 7194: "sr-Cyrl-BA", + 3098: "sr", + 6170: "sr-Latn-BA", + 2074: "sr-Latn", + 1132: "nso", + 1074: "tn", + 1115: "si", + 1051: "sk", + 1060: "sl", + 11274: "es-AR", + 16394: "es-BO", + 13322: "es-CL", + 9226: "es-CO", + 5130: "es-CR", + 7178: "es-DO", + 12298: "es-EC", + 17418: "es-SV", + 4106: "es-GT", + 18442: "es-HN", + 2058: "es-MX", + 19466: "es-NI", + 6154: "es-PA", + 15370: "es-PY", + 10250: "es-PE", + 20490: "es-PR", + 3082: "es", + 1034: "es", + 21514: "es-US", + 14346: "es-UY", + 8202: "es-VE", + 2077: "sv-FI", + 1053: "sv", + 1114: "syr", + 1064: "tg", + 2143: "tzm", + 1097: "ta", + 1092: "tt", + 1098: "te", + 1054: "th", + 1105: "bo", + 1055: "tr", + 1090: "tk", + 1152: "ug", + 1058: "uk", + 1070: "hsb", + 1056: "ur", + 2115: "uz-Cyrl", + 1091: "uz", + 1066: "vi", + 1106: "cy", + 1160: "wo", + 1157: "sah", + 1144: "ii", + 1130: "yo" +}; +function getLanguageCode(platformID, languageID, ltag2) { + switch (platformID) { + case 0: + if (languageID === 65535) { + return "und"; + } else if (ltag2) { + return ltag2[languageID]; + } + break; + case 1: + return macLanguages[languageID]; + case 3: + return windowsLanguages[languageID]; + } + return; +} +var utf16 = "utf-16"; +var macScriptEncodings = { + 0: "macintosh", + 1: "x-mac-japanese", + 2: "x-mac-chinesetrad", + 3: "x-mac-korean", + 6: "x-mac-greek", + 7: "x-mac-cyrillic", + 9: "x-mac-devanagai", + 10: "x-mac-gurmukhi", + 11: "x-mac-gujarati", + 12: "x-mac-oriya", + 13: "x-mac-bengali", + 14: "x-mac-tamil", + 15: "x-mac-telugu", + 16: "x-mac-kannada", + 17: "x-mac-malayalam", + 18: "x-mac-sinhalese", + 19: "x-mac-burmese", + 20: "x-mac-khmer", + 21: "x-mac-thai", + 22: "x-mac-lao", + 23: "x-mac-georgian", + 24: "x-mac-armenian", + 25: "x-mac-chinesesimp", + 26: "x-mac-tibetan", + 27: "x-mac-mongolian", + 28: "x-mac-ethiopic", + 29: "x-mac-ce", + 30: "x-mac-vietnamese", + 31: "x-mac-extarabic" +}; +var macLanguageEncodings = { + 15: "x-mac-icelandic", + 17: "x-mac-turkish", + 18: "x-mac-croatian", + 24: "x-mac-ce", + 25: "x-mac-ce", + 26: "x-mac-ce", + 27: "x-mac-ce", + 28: "x-mac-ce", + 30: "x-mac-icelandic", + 37: "x-mac-romanian", + 38: "x-mac-ce", + 39: "x-mac-ce", + 40: "x-mac-ce", + 143: "x-mac-inuit", + 146: "x-mac-gaelic" +}; +function getEncoding(platformID, encodingID, languageID) { + switch (platformID) { + case 0: + return utf16; + case 1: + return macLanguageEncodings[languageID] || macScriptEncodings[encodingID]; + case 3: + if (encodingID === 1 || encodingID === 10) { + return utf16; + } + break; + } + return; +} +function parseNameTable(data2, start, ltag2) { + var name2 = {}; + var p = new parse.Parser(data2, start); + var format = p.parseUShort(); + var count = p.parseUShort(); + var stringOffset = p.offset + p.parseUShort(); + for (var i = 0;i < count; i++) { + var platformID = p.parseUShort(); + var encodingID = p.parseUShort(); + var languageID = p.parseUShort(); + var nameID = p.parseUShort(); + var property2 = nameTableNames[nameID] || nameID; + var byteLength = p.parseUShort(); + var offset = p.parseUShort(); + var language = getLanguageCode(platformID, languageID, ltag2); + var encoding = getEncoding(platformID, encodingID, languageID); + if (encoding !== undefined && language !== undefined) { + var text2 = undefined; + if (encoding === utf16) { + text2 = decode.UTF16(data2, stringOffset + offset, byteLength); + } else { + text2 = decode.MACSTRING(data2, stringOffset + offset, byteLength, encoding); + } + if (text2) { + var translations = name2[property2]; + if (translations === undefined) { + translations = name2[property2] = {}; + } + translations[language] = text2; + } + } + } + var langTagCount = 0; + if (format === 1) { + langTagCount = p.parseUShort(); + } + return name2; +} +function reverseDict(dict) { + var result = {}; + for (var key2 in dict) { + result[dict[key2]] = parseInt(key2); + } + return result; +} +function makeNameRecord(platformID, encodingID, languageID, nameID, length2, offset) { + return new table.Record("NameRecord", [ + { name: "platformID", type: "USHORT", value: platformID }, + { name: "encodingID", type: "USHORT", value: encodingID }, + { name: "languageID", type: "USHORT", value: languageID }, + { name: "nameID", type: "USHORT", value: nameID }, + { name: "length", type: "USHORT", value: length2 }, + { name: "offset", type: "USHORT", value: offset } + ]); +} +function findSubArray(needle, haystack) { + var needleLength = needle.length; + var limit = haystack.length - needleLength + 1; + loop: + for (var pos = 0;pos < limit; pos++) { + for (;pos < limit; pos++) { + for (var k2 = 0;k2 < needleLength; k2++) { + if (haystack[pos + k2] !== needle[k2]) { + continue loop; + } + } + return pos; + } + } + return -1; +} +function addStringToPool(s, pool) { + var offset = findSubArray(s, pool); + if (offset < 0) { + offset = pool.length; + var i = 0; + var len = s.length; + for (;i < len; ++i) { + pool.push(s[i]); + } + } + return offset; +} +function makeNameTable(names, ltag2) { + var nameID; + var nameIDs = []; + var namesWithNumericKeys = {}; + var nameTableIds = reverseDict(nameTableNames); + for (var key2 in names) { + var id = nameTableIds[key2]; + if (id === undefined) { + id = key2; + } + nameID = parseInt(id); + if (isNaN(nameID)) { + throw new Error('Name table entry "' + key2 + '" does not exist, see nameTableNames for complete list.'); + } + namesWithNumericKeys[nameID] = names[key2]; + nameIDs.push(nameID); + } + var macLanguageIds = reverseDict(macLanguages); + var windowsLanguageIds = reverseDict(windowsLanguages); + var nameRecords = []; + var stringPool = []; + for (var i = 0;i < nameIDs.length; i++) { + nameID = nameIDs[i]; + var translations = namesWithNumericKeys[nameID]; + for (var lang in translations) { + var text2 = translations[lang]; + var macPlatform = 1; + var macLanguage = macLanguageIds[lang]; + var macScript = macLanguageToScript[macLanguage]; + var macEncoding = getEncoding(macPlatform, macScript, macLanguage); + var macName = encode.MACSTRING(text2, macEncoding); + if (macName === undefined) { + macPlatform = 0; + macLanguage = ltag2.indexOf(lang); + if (macLanguage < 0) { + macLanguage = ltag2.length; + ltag2.push(lang); + } + macScript = 4; + macName = encode.UTF16(text2); + } + var macNameOffset = addStringToPool(macName, stringPool); + nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage, nameID, macName.length, macNameOffset)); + var winLanguage = windowsLanguageIds[lang]; + if (winLanguage !== undefined) { + var winName = encode.UTF16(text2); + var winNameOffset = addStringToPool(winName, stringPool); + nameRecords.push(makeNameRecord(3, 1, winLanguage, nameID, winName.length, winNameOffset)); + } + } + } + nameRecords.sort(function(a, b) { + return a.platformID - b.platformID || a.encodingID - b.encodingID || a.languageID - b.languageID || a.nameID - b.nameID; + }); + var t2 = new table.Table("name", [ + { name: "format", type: "USHORT", value: 0 }, + { name: "count", type: "USHORT", value: nameRecords.length }, + { name: "stringOffset", type: "USHORT", value: 6 + nameRecords.length * 12 } + ]); + for (var r = 0;r < nameRecords.length; r++) { + t2.fields.push({ name: "record_" + r, type: "RECORD", value: nameRecords[r] }); + } + t2.fields.push({ name: "strings", type: "LITERAL", value: stringPool }); + return t2; +} +var _name = { parse: parseNameTable, make: makeNameTable }; +var unicodeRanges = [ + { begin: 0, end: 127 }, + { begin: 128, end: 255 }, + { begin: 256, end: 383 }, + { begin: 384, end: 591 }, + { begin: 592, end: 687 }, + { begin: 688, end: 767 }, + { begin: 768, end: 879 }, + { begin: 880, end: 1023 }, + { begin: 11392, end: 11519 }, + { begin: 1024, end: 1279 }, + { begin: 1328, end: 1423 }, + { begin: 1424, end: 1535 }, + { begin: 42240, end: 42559 }, + { begin: 1536, end: 1791 }, + { begin: 1984, end: 2047 }, + { begin: 2304, end: 2431 }, + { begin: 2432, end: 2559 }, + { begin: 2560, end: 2687 }, + { begin: 2688, end: 2815 }, + { begin: 2816, end: 2943 }, + { begin: 2944, end: 3071 }, + { begin: 3072, end: 3199 }, + { begin: 3200, end: 3327 }, + { begin: 3328, end: 3455 }, + { begin: 3584, end: 3711 }, + { begin: 3712, end: 3839 }, + { begin: 4256, end: 4351 }, + { begin: 6912, end: 7039 }, + { begin: 4352, end: 4607 }, + { begin: 7680, end: 7935 }, + { begin: 7936, end: 8191 }, + { begin: 8192, end: 8303 }, + { begin: 8304, end: 8351 }, + { begin: 8352, end: 8399 }, + { begin: 8400, end: 8447 }, + { begin: 8448, end: 8527 }, + { begin: 8528, end: 8591 }, + { begin: 8592, end: 8703 }, + { begin: 8704, end: 8959 }, + { begin: 8960, end: 9215 }, + { begin: 9216, end: 9279 }, + { begin: 9280, end: 9311 }, + { begin: 9312, end: 9471 }, + { begin: 9472, end: 9599 }, + { begin: 9600, end: 9631 }, + { begin: 9632, end: 9727 }, + { begin: 9728, end: 9983 }, + { begin: 9984, end: 10175 }, + { begin: 12288, end: 12351 }, + { begin: 12352, end: 12447 }, + { begin: 12448, end: 12543 }, + { begin: 12544, end: 12591 }, + { begin: 12592, end: 12687 }, + { begin: 43072, end: 43135 }, + { begin: 12800, end: 13055 }, + { begin: 13056, end: 13311 }, + { begin: 44032, end: 55215 }, + { begin: 55296, end: 57343 }, + { begin: 67840, end: 67871 }, + { begin: 19968, end: 40959 }, + { begin: 57344, end: 63743 }, + { begin: 12736, end: 12783 }, + { begin: 64256, end: 64335 }, + { begin: 64336, end: 65023 }, + { begin: 65056, end: 65071 }, + { begin: 65040, end: 65055 }, + { begin: 65104, end: 65135 }, + { begin: 65136, end: 65279 }, + { begin: 65280, end: 65519 }, + { begin: 65520, end: 65535 }, + { begin: 3840, end: 4095 }, + { begin: 1792, end: 1871 }, + { begin: 1920, end: 1983 }, + { begin: 3456, end: 3583 }, + { begin: 4096, end: 4255 }, + { begin: 4608, end: 4991 }, + { begin: 5024, end: 5119 }, + { begin: 5120, end: 5759 }, + { begin: 5760, end: 5791 }, + { begin: 5792, end: 5887 }, + { begin: 6016, end: 6143 }, + { begin: 6144, end: 6319 }, + { begin: 10240, end: 10495 }, + { begin: 40960, end: 42127 }, + { begin: 5888, end: 5919 }, + { begin: 66304, end: 66351 }, + { begin: 66352, end: 66383 }, + { begin: 66560, end: 66639 }, + { begin: 118784, end: 119039 }, + { begin: 119808, end: 120831 }, + { begin: 1044480, end: 1048573 }, + { begin: 65024, end: 65039 }, + { begin: 917504, end: 917631 }, + { begin: 6400, end: 6479 }, + { begin: 6480, end: 6527 }, + { begin: 6528, end: 6623 }, + { begin: 6656, end: 6687 }, + { begin: 11264, end: 11359 }, + { begin: 11568, end: 11647 }, + { begin: 19904, end: 19967 }, + { begin: 43008, end: 43055 }, + { begin: 65536, end: 65663 }, + { begin: 65856, end: 65935 }, + { begin: 66432, end: 66463 }, + { begin: 66464, end: 66527 }, + { begin: 66640, end: 66687 }, + { begin: 66688, end: 66735 }, + { begin: 67584, end: 67647 }, + { begin: 68096, end: 68191 }, + { begin: 119552, end: 119647 }, + { begin: 73728, end: 74751 }, + { begin: 119648, end: 119679 }, + { begin: 7040, end: 7103 }, + { begin: 7168, end: 7247 }, + { begin: 7248, end: 7295 }, + { begin: 43136, end: 43231 }, + { begin: 43264, end: 43311 }, + { begin: 43312, end: 43359 }, + { begin: 43520, end: 43615 }, + { begin: 65936, end: 65999 }, + { begin: 66000, end: 66047 }, + { begin: 66208, end: 66271 }, + { begin: 127024, end: 127135 } +]; +function getUnicodeRange(unicode) { + for (var i = 0;i < unicodeRanges.length; i += 1) { + var range = unicodeRanges[i]; + if (unicode >= range.begin && unicode < range.end) { + return i; + } + } + return -1; +} +function parseOS2Table(data2, start) { + var os2 = {}; + var p = new parse.Parser(data2, start); + os2.version = p.parseUShort(); + os2.xAvgCharWidth = p.parseShort(); + os2.usWeightClass = p.parseUShort(); + os2.usWidthClass = p.parseUShort(); + os2.fsType = p.parseUShort(); + os2.ySubscriptXSize = p.parseShort(); + os2.ySubscriptYSize = p.parseShort(); + os2.ySubscriptXOffset = p.parseShort(); + os2.ySubscriptYOffset = p.parseShort(); + os2.ySuperscriptXSize = p.parseShort(); + os2.ySuperscriptYSize = p.parseShort(); + os2.ySuperscriptXOffset = p.parseShort(); + os2.ySuperscriptYOffset = p.parseShort(); + os2.yStrikeoutSize = p.parseShort(); + os2.yStrikeoutPosition = p.parseShort(); + os2.sFamilyClass = p.parseShort(); + os2.panose = []; + for (var i = 0;i < 10; i++) { + os2.panose[i] = p.parseByte(); + } + os2.ulUnicodeRange1 = p.parseULong(); + os2.ulUnicodeRange2 = p.parseULong(); + os2.ulUnicodeRange3 = p.parseULong(); + os2.ulUnicodeRange4 = p.parseULong(); + os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte()); + os2.fsSelection = p.parseUShort(); + os2.usFirstCharIndex = p.parseUShort(); + os2.usLastCharIndex = p.parseUShort(); + os2.sTypoAscender = p.parseShort(); + os2.sTypoDescender = p.parseShort(); + os2.sTypoLineGap = p.parseShort(); + os2.usWinAscent = p.parseUShort(); + os2.usWinDescent = p.parseUShort(); + if (os2.version >= 1) { + os2.ulCodePageRange1 = p.parseULong(); + os2.ulCodePageRange2 = p.parseULong(); + } + if (os2.version >= 2) { + os2.sxHeight = p.parseShort(); + os2.sCapHeight = p.parseShort(); + os2.usDefaultChar = p.parseUShort(); + os2.usBreakChar = p.parseUShort(); + os2.usMaxContent = p.parseUShort(); + } + return os2; +} +function makeOS2Table(options) { + return new table.Table("OS/2", [ + { name: "version", type: "USHORT", value: 3 }, + { name: "xAvgCharWidth", type: "SHORT", value: 0 }, + { name: "usWeightClass", type: "USHORT", value: 0 }, + { name: "usWidthClass", type: "USHORT", value: 0 }, + { name: "fsType", type: "USHORT", value: 0 }, + { name: "ySubscriptXSize", type: "SHORT", value: 650 }, + { name: "ySubscriptYSize", type: "SHORT", value: 699 }, + { name: "ySubscriptXOffset", type: "SHORT", value: 0 }, + { name: "ySubscriptYOffset", type: "SHORT", value: 140 }, + { name: "ySuperscriptXSize", type: "SHORT", value: 650 }, + { name: "ySuperscriptYSize", type: "SHORT", value: 699 }, + { name: "ySuperscriptXOffset", type: "SHORT", value: 0 }, + { name: "ySuperscriptYOffset", type: "SHORT", value: 479 }, + { name: "yStrikeoutSize", type: "SHORT", value: 49 }, + { name: "yStrikeoutPosition", type: "SHORT", value: 258 }, + { name: "sFamilyClass", type: "SHORT", value: 0 }, + { name: "bFamilyType", type: "BYTE", value: 0 }, + { name: "bSerifStyle", type: "BYTE", value: 0 }, + { name: "bWeight", type: "BYTE", value: 0 }, + { name: "bProportion", type: "BYTE", value: 0 }, + { name: "bContrast", type: "BYTE", value: 0 }, + { name: "bStrokeVariation", type: "BYTE", value: 0 }, + { name: "bArmStyle", type: "BYTE", value: 0 }, + { name: "bLetterform", type: "BYTE", value: 0 }, + { name: "bMidline", type: "BYTE", value: 0 }, + { name: "bXHeight", type: "BYTE", value: 0 }, + { name: "ulUnicodeRange1", type: "ULONG", value: 0 }, + { name: "ulUnicodeRange2", type: "ULONG", value: 0 }, + { name: "ulUnicodeRange3", type: "ULONG", value: 0 }, + { name: "ulUnicodeRange4", type: "ULONG", value: 0 }, + { name: "achVendID", type: "CHARARRAY", value: "XXXX" }, + { name: "fsSelection", type: "USHORT", value: 0 }, + { name: "usFirstCharIndex", type: "USHORT", value: 0 }, + { name: "usLastCharIndex", type: "USHORT", value: 0 }, + { name: "sTypoAscender", type: "SHORT", value: 0 }, + { name: "sTypoDescender", type: "SHORT", value: 0 }, + { name: "sTypoLineGap", type: "SHORT", value: 0 }, + { name: "usWinAscent", type: "USHORT", value: 0 }, + { name: "usWinDescent", type: "USHORT", value: 0 }, + { name: "ulCodePageRange1", type: "ULONG", value: 0 }, + { name: "ulCodePageRange2", type: "ULONG", value: 0 }, + { name: "sxHeight", type: "SHORT", value: 0 }, + { name: "sCapHeight", type: "SHORT", value: 0 }, + { name: "usDefaultChar", type: "USHORT", value: 0 }, + { name: "usBreakChar", type: "USHORT", value: 0 }, + { name: "usMaxContext", type: "USHORT", value: 0 } + ], options); +} +var os2 = { parse: parseOS2Table, make: makeOS2Table, unicodeRanges, getUnicodeRange }; +function parsePostTable(data2, start) { + var post = {}; + var p = new parse.Parser(data2, start); + post.version = p.parseVersion(); + post.italicAngle = p.parseFixed(); + post.underlinePosition = p.parseShort(); + post.underlineThickness = p.parseShort(); + post.isFixedPitch = p.parseULong(); + post.minMemType42 = p.parseULong(); + post.maxMemType42 = p.parseULong(); + post.minMemType1 = p.parseULong(); + post.maxMemType1 = p.parseULong(); + switch (post.version) { + case 1: + post.names = standardNames.slice(); + break; + case 2: + post.numberOfGlyphs = p.parseUShort(); + post.glyphNameIndex = new Array(post.numberOfGlyphs); + for (var i = 0;i < post.numberOfGlyphs; i++) { + post.glyphNameIndex[i] = p.parseUShort(); + } + post.names = []; + for (var i$1 = 0;i$1 < post.numberOfGlyphs; i$1++) { + if (post.glyphNameIndex[i$1] >= standardNames.length) { + var nameLength = p.parseChar(); + post.names.push(p.parseString(nameLength)); + } + } + break; + case 2.5: + post.numberOfGlyphs = p.parseUShort(); + post.offset = new Array(post.numberOfGlyphs); + for (var i$2 = 0;i$2 < post.numberOfGlyphs; i$2++) { + post.offset[i$2] = p.parseChar(); + } + break; + } + return post; +} +function makePostTable() { + return new table.Table("post", [ + { name: "version", type: "FIXED", value: 196608 }, + { name: "italicAngle", type: "FIXED", value: 0 }, + { name: "underlinePosition", type: "FWORD", value: 0 }, + { name: "underlineThickness", type: "FWORD", value: 0 }, + { name: "isFixedPitch", type: "ULONG", value: 0 }, + { name: "minMemType42", type: "ULONG", value: 0 }, + { name: "maxMemType42", type: "ULONG", value: 0 }, + { name: "minMemType1", type: "ULONG", value: 0 }, + { name: "maxMemType1", type: "ULONG", value: 0 } + ]); +} +var post = { parse: parsePostTable, make: makePostTable }; +var subtableParsers = new Array(9); +subtableParsers[1] = function parseLookup1() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat: 1, + coverage: this.parsePointer(Parser.coverage), + deltaGlyphId: this.parseUShort() + }; + } else if (substFormat === 2) { + return { + substFormat: 2, + coverage: this.parsePointer(Parser.coverage), + substitute: this.parseOffset16List() + }; + } + check.assert(false, "0x" + start.toString(16) + ": lookup type 1 format must be 1 or 2."); +}; +subtableParsers[2] = function parseLookup2() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB Multiple Substitution Subtable identifier-format must be 1"); + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + sequences: this.parseListOfLists() + }; +}; +subtableParsers[3] = function parseLookup3() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB Alternate Substitution Subtable identifier-format must be 1"); + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + alternateSets: this.parseListOfLists() + }; +}; +subtableParsers[4] = function parseLookup4() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB ligature table identifier-format must be 1"); + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + ligatureSets: this.parseListOfLists(function() { + return { + ligGlyph: this.parseUShort(), + components: this.parseUShortList(this.parseUShort() - 1) + }; + }) + }; +}; +var lookupRecordDesc = { + sequenceIndex: Parser.uShort, + lookupListIndex: Parser.uShort +}; +subtableParsers[5] = function parseLookup5() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + ruleSets: this.parseListOfLists(function() { + var glyphCount2 = this.parseUShort(); + var substCount2 = this.parseUShort(); + return { + input: this.parseUShortList(glyphCount2 - 1), + lookupRecords: this.parseRecordList(substCount2, lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 2) { + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + classDef: this.parsePointer(Parser.classDef), + classSets: this.parseListOfLists(function() { + var glyphCount2 = this.parseUShort(); + var substCount2 = this.parseUShort(); + return { + classes: this.parseUShortList(glyphCount2 - 1), + lookupRecords: this.parseRecordList(substCount2, lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 3) { + var glyphCount = this.parseUShort(); + var substCount = this.parseUShort(); + return { + substFormat, + coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)), + lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) + }; + } + check.assert(false, "0x" + start.toString(16) + ": lookup type 5 format must be 1, 2 or 3."); +}; +subtableParsers[6] = function parseLookup6() { + var start = this.offset + this.relativeOffset; + var substFormat = this.parseUShort(); + if (substFormat === 1) { + return { + substFormat: 1, + coverage: this.parsePointer(Parser.coverage), + chainRuleSets: this.parseListOfLists(function() { + return { + backtrack: this.parseUShortList(), + input: this.parseUShortList(this.parseShort() - 1), + lookahead: this.parseUShortList(), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 2) { + return { + substFormat: 2, + coverage: this.parsePointer(Parser.coverage), + backtrackClassDef: this.parsePointer(Parser.classDef), + inputClassDef: this.parsePointer(Parser.classDef), + lookaheadClassDef: this.parsePointer(Parser.classDef), + chainClassSet: this.parseListOfLists(function() { + return { + backtrack: this.parseUShortList(), + input: this.parseUShortList(this.parseShort() - 1), + lookahead: this.parseUShortList(), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + }) + }; + } else if (substFormat === 3) { + return { + substFormat: 3, + backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), + inputCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookupRecords: this.parseRecordList(lookupRecordDesc) + }; + } + check.assert(false, "0x" + start.toString(16) + ": lookup type 6 format must be 1, 2 or 3."); +}; +subtableParsers[7] = function parseLookup7() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB Extension Substitution subtable identifier-format must be 1"); + var extensionLookupType = this.parseUShort(); + var extensionParser = new Parser(this.data, this.offset + this.parseULong()); + return { + substFormat: 1, + lookupType: extensionLookupType, + extension: subtableParsers[extensionLookupType].call(extensionParser) + }; +}; +subtableParsers[8] = function parseLookup8() { + var substFormat = this.parseUShort(); + check.argument(substFormat === 1, "GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1"); + return { + substFormat, + coverage: this.parsePointer(Parser.coverage), + backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), + lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), + substitutes: this.parseUShortList() + }; +}; +function parseGsubTable(data2, start) { + start = start || 0; + var p = new Parser(data2, start); + var tableVersion = p.parseVersion(1); + check.argument(tableVersion === 1 || tableVersion === 1.1, "Unsupported GSUB table version."); + if (tableVersion === 1) { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers) + }; + } else { + return { + version: tableVersion, + scripts: p.parseScriptList(), + features: p.parseFeatureList(), + lookups: p.parseLookupList(subtableParsers), + variations: p.parseFeatureVariationsList() + }; + } +} +var subtableMakers = new Array(9); +subtableMakers[1] = function makeLookup1(subtable) { + if (subtable.substFormat === 1) { + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 1 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) }, + { name: "deltaGlyphID", type: "USHORT", value: subtable.deltaGlyphId } + ]); + } else { + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 2 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.ushortList("substitute", subtable.substitute))); + } +}; +subtableMakers[2] = function makeLookup2(subtable) { + check.assert(subtable.substFormat === 1, "Lookup type 2 substFormat must be 1."); + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 1 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.tableList("seqSet", subtable.sequences, function(sequenceSet) { + return new table.Table("sequenceSetTable", table.ushortList("sequence", sequenceSet)); + }))); +}; +subtableMakers[3] = function makeLookup3(subtable) { + check.assert(subtable.substFormat === 1, "Lookup type 3 substFormat must be 1."); + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 1 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.tableList("altSet", subtable.alternateSets, function(alternateSet) { + return new table.Table("alternateSetTable", table.ushortList("alternate", alternateSet)); + }))); +}; +subtableMakers[4] = function makeLookup4(subtable) { + check.assert(subtable.substFormat === 1, "Lookup type 4 substFormat must be 1."); + return new table.Table("substitutionTable", [ + { name: "substFormat", type: "USHORT", value: 1 }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.tableList("ligSet", subtable.ligatureSets, function(ligatureSet) { + return new table.Table("ligatureSetTable", table.tableList("ligature", ligatureSet, function(ligature) { + return new table.Table("ligatureTable", [{ name: "ligGlyph", type: "USHORT", value: ligature.ligGlyph }].concat(table.ushortList("component", ligature.components, ligature.components.length + 1))); + })); + }))); +}; +subtableMakers[6] = function makeLookup6(subtable) { + if (subtable.substFormat === 1) { + var returnTable = new table.Table("chainContextTable", [ + { name: "substFormat", type: "USHORT", value: subtable.substFormat }, + { name: "coverage", type: "TABLE", value: new table.Coverage(subtable.coverage) } + ].concat(table.tableList("chainRuleSet", subtable.chainRuleSets, function(chainRuleSet) { + return new table.Table("chainRuleSetTable", table.tableList("chainRule", chainRuleSet, function(chainRule) { + var tableData2 = table.ushortList("backtrackGlyph", chainRule.backtrack, chainRule.backtrack.length).concat(table.ushortList("inputGlyph", chainRule.input, chainRule.input.length + 1)).concat(table.ushortList("lookaheadGlyph", chainRule.lookahead, chainRule.lookahead.length)).concat(table.ushortList("substitution", [], chainRule.lookupRecords.length)); + chainRule.lookupRecords.forEach(function(record, i) { + tableData2 = tableData2.concat({ name: "sequenceIndex" + i, type: "USHORT", value: record.sequenceIndex }).concat({ name: "lookupListIndex" + i, type: "USHORT", value: record.lookupListIndex }); + }); + return new table.Table("chainRuleTable", tableData2); + })); + }))); + return returnTable; + } else if (subtable.substFormat === 2) { + check.assert(false, "lookup type 6 format 2 is not yet supported."); + } else if (subtable.substFormat === 3) { + var tableData = [ + { name: "substFormat", type: "USHORT", value: subtable.substFormat } + ]; + tableData.push({ name: "backtrackGlyphCount", type: "USHORT", value: subtable.backtrackCoverage.length }); + subtable.backtrackCoverage.forEach(function(coverage, i) { + tableData.push({ name: "backtrackCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) }); + }); + tableData.push({ name: "inputGlyphCount", type: "USHORT", value: subtable.inputCoverage.length }); + subtable.inputCoverage.forEach(function(coverage, i) { + tableData.push({ name: "inputCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) }); + }); + tableData.push({ name: "lookaheadGlyphCount", type: "USHORT", value: subtable.lookaheadCoverage.length }); + subtable.lookaheadCoverage.forEach(function(coverage, i) { + tableData.push({ name: "lookaheadCoverage" + i, type: "TABLE", value: new table.Coverage(coverage) }); + }); + tableData.push({ name: "substitutionCount", type: "USHORT", value: subtable.lookupRecords.length }); + subtable.lookupRecords.forEach(function(record, i) { + tableData = tableData.concat({ name: "sequenceIndex" + i, type: "USHORT", value: record.sequenceIndex }).concat({ name: "lookupListIndex" + i, type: "USHORT", value: record.lookupListIndex }); + }); + var returnTable$1 = new table.Table("chainContextTable", tableData); + return returnTable$1; + } + check.assert(false, "lookup type 6 format must be 1, 2 or 3."); +}; +function makeGsubTable(gsub) { + return new table.Table("GSUB", [ + { name: "version", type: "ULONG", value: 65536 }, + { name: "scripts", type: "TABLE", value: new table.ScriptList(gsub.scripts) }, + { name: "features", type: "TABLE", value: new table.FeatureList(gsub.features) }, + { name: "lookups", type: "TABLE", value: new table.LookupList(gsub.lookups, subtableMakers) } + ]); +} +var gsub = { parse: parseGsubTable, make: makeGsubTable }; +function parseMetaTable(data2, start) { + var p = new parse.Parser(data2, start); + var tableVersion = p.parseULong(); + check.argument(tableVersion === 1, "Unsupported META table version."); + p.parseULong(); + p.parseULong(); + var numDataMaps = p.parseULong(); + var tags = {}; + for (var i = 0;i < numDataMaps; i++) { + var tag = p.parseTag(); + var dataOffset = p.parseULong(); + var dataLength = p.parseULong(); + var text2 = decode.UTF8(data2, start + dataOffset, dataLength); + tags[tag] = text2; + } + return tags; +} +function makeMetaTable(tags) { + var numTags = Object.keys(tags).length; + var stringPool = ""; + var stringPoolOffset = 16 + numTags * 12; + var result = new table.Table("meta", [ + { name: "version", type: "ULONG", value: 1 }, + { name: "flags", type: "ULONG", value: 0 }, + { name: "offset", type: "ULONG", value: stringPoolOffset }, + { name: "numTags", type: "ULONG", value: numTags } + ]); + for (var tag in tags) { + var pos = stringPool.length; + stringPool += tags[tag]; + result.fields.push({ name: "tag " + tag, type: "TAG", value: tag }); + result.fields.push({ name: "offset " + tag, type: "ULONG", value: stringPoolOffset + pos }); + result.fields.push({ name: "length " + tag, type: "ULONG", value: tags[tag].length }); + } + result.fields.push({ name: "stringPool", type: "CHARARRAY", value: stringPool }); + return result; +} +var meta = { parse: parseMetaTable, make: makeMetaTable }; +function parseColrTable(data2, start) { + var p = new Parser(data2, start); + var version = p.parseUShort(); + check.argument(version === 0, "Only COLRv0 supported."); + var numBaseGlyphRecords = p.parseUShort(); + var baseGlyphRecordsOffset = p.parseOffset32(); + var layerRecordsOffset = p.parseOffset32(); + var numLayerRecords = p.parseUShort(); + p.relativeOffset = baseGlyphRecordsOffset; + var baseGlyphRecords = p.parseRecordList(numBaseGlyphRecords, { + glyphID: Parser.uShort, + firstLayerIndex: Parser.uShort, + numLayers: Parser.uShort + }); + p.relativeOffset = layerRecordsOffset; + var layerRecords = p.parseRecordList(numLayerRecords, { + glyphID: Parser.uShort, + paletteIndex: Parser.uShort + }); + return { + version, + baseGlyphRecords, + layerRecords + }; +} +function makeColrTable(ref) { + var version = ref.version; + if (version === undefined) + version = 0; + var baseGlyphRecords = ref.baseGlyphRecords; + if (baseGlyphRecords === undefined) + baseGlyphRecords = []; + var layerRecords = ref.layerRecords; + if (layerRecords === undefined) + layerRecords = []; + check.argument(version === 0, "Only COLRv0 supported."); + var baseGlyphRecordsOffset = 14; + var layerRecordsOffset = baseGlyphRecordsOffset + baseGlyphRecords.length * 6; + return new table.Table("COLR", [ + { name: "version", type: "USHORT", value: version }, + { name: "numBaseGlyphRecords", type: "USHORT", value: baseGlyphRecords.length }, + { name: "baseGlyphRecordsOffset", type: "ULONG", value: baseGlyphRecordsOffset }, + { name: "layerRecordsOffset", type: "ULONG", value: layerRecordsOffset }, + { name: "numLayerRecords", type: "USHORT", value: layerRecords.length } + ].concat(baseGlyphRecords.map(function(glyph, i) { + return [ + { name: "glyphID_" + i, type: "USHORT", value: glyph.glyphID }, + { name: "firstLayerIndex_" + i, type: "USHORT", value: glyph.firstLayerIndex }, + { name: "numLayers_" + i, type: "USHORT", value: glyph.numLayers } + ]; + }).flat(), layerRecords.map(function(layer, i) { + return [ + { name: "LayerGlyphID_" + i, type: "USHORT", value: layer.glyphID }, + { name: "paletteIndex_" + i, type: "USHORT", value: layer.paletteIndex } + ]; + }).flat())); +} +var colr = { parse: parseColrTable, make: makeColrTable }; +function parseCpalTable(data2, start) { + var p = new Parser(data2, start); + var version = p.parseShort(); + var numPaletteEntries = p.parseShort(); + var numPalettes = p.parseShort(); + var numColorRecords = p.parseShort(); + var colorRecordsArrayOffset = p.parseOffset32(); + var colorRecordIndices = p.parseUShortList(numPalettes); + p.relativeOffset = colorRecordsArrayOffset; + var colorRecords = p.parseULongList(numColorRecords); + return { + version, + numPaletteEntries, + colorRecords, + colorRecordIndices + }; +} +function makeCpalTable(ref) { + var version = ref.version; + if (version === undefined) + version = 0; + var numPaletteEntries = ref.numPaletteEntries; + if (numPaletteEntries === undefined) + numPaletteEntries = 0; + var colorRecords = ref.colorRecords; + if (colorRecords === undefined) + colorRecords = []; + var colorRecordIndices = ref.colorRecordIndices; + if (colorRecordIndices === undefined) + colorRecordIndices = [0]; + check.argument(version === 0, "Only CPALv0 are supported."); + check.argument(colorRecords.length, "No colorRecords given."); + check.argument(colorRecordIndices.length, "No colorRecordIndices given."); + check.argument(!numPaletteEntries && colorRecordIndices.length == 1, "Can't infer numPaletteEntries on multiple colorRecordIndices"); + return new table.Table("CPAL", [ + { name: "version", type: "USHORT", value: version }, + { name: "numPaletteEntries", type: "USHORT", value: numPaletteEntries || colorRecords.length }, + { name: "numPalettes", type: "USHORT", value: colorRecordIndices.length }, + { name: "numColorRecords", type: "USHORT", value: colorRecords.length }, + { name: "colorRecordsArrayOffset", type: "ULONG", value: 12 + 2 * colorRecordIndices.length } + ].concat(colorRecordIndices.map(function(palette, i) { + return { name: "colorRecordIndices_" + i, type: "USHORT", value: palette }; + }), colorRecords.map(function(color, i) { + return { name: "colorRecords_" + i, type: "ULONG", value: color }; + }))); +} +var cpal = { parse: parseCpalTable, make: makeCpalTable }; +function log2(v) { + return Math.log(v) / Math.log(2) | 0; +} +function computeCheckSum(bytes) { + while (bytes.length % 4 !== 0) { + bytes.push(0); + } + var sum2 = 0; + for (var i = 0;i < bytes.length; i += 4) { + sum2 += (bytes[i] << 24) + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + bytes[i + 3]; + } + sum2 %= Math.pow(2, 32); + return sum2; +} +function makeTableRecord(tag, checkSum, offset, length2) { + return new table.Record("Table Record", [ + { name: "tag", type: "TAG", value: tag !== undefined ? tag : "" }, + { name: "checkSum", type: "ULONG", value: checkSum !== undefined ? checkSum : 0 }, + { name: "offset", type: "ULONG", value: offset !== undefined ? offset : 0 }, + { name: "length", type: "ULONG", value: length2 !== undefined ? length2 : 0 } + ]); +} +function makeSfntTable(tables) { + var sfnt = new table.Table("sfnt", [ + { name: "version", type: "TAG", value: "OTTO" }, + { name: "numTables", type: "USHORT", value: 0 }, + { name: "searchRange", type: "USHORT", value: 0 }, + { name: "entrySelector", type: "USHORT", value: 0 }, + { name: "rangeShift", type: "USHORT", value: 0 } + ]); + sfnt.tables = tables; + sfnt.numTables = tables.length; + var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables)); + sfnt.searchRange = 16 * highestPowerOf2; + sfnt.entrySelector = log2(highestPowerOf2); + sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange; + var recordFields = []; + var tableFields = []; + var offset = sfnt.sizeOf() + makeTableRecord().sizeOf() * sfnt.numTables; + while (offset % 4 !== 0) { + offset += 1; + tableFields.push({ name: "padding", type: "BYTE", value: 0 }); + } + for (var i = 0;i < tables.length; i += 1) { + var t2 = tables[i]; + check.argument(t2.tableName.length === 4, "Table name" + t2.tableName + " is invalid."); + var tableLength = t2.sizeOf(); + var tableRecord = makeTableRecord(t2.tableName, computeCheckSum(t2.encode()), offset, tableLength); + recordFields.push({ name: tableRecord.tag + " Table Record", type: "RECORD", value: tableRecord }); + tableFields.push({ name: t2.tableName + " table", type: "RECORD", value: t2 }); + offset += tableLength; + check.argument(!isNaN(offset), "Something went wrong calculating the offset."); + while (offset % 4 !== 0) { + offset += 1; + tableFields.push({ name: "padding", type: "BYTE", value: 0 }); + } + } + recordFields.sort(function(r1, r2) { + if (r1.value.tag > r2.value.tag) { + return 1; + } else { + return -1; + } + }); + sfnt.fields = sfnt.fields.concat(recordFields); + sfnt.fields = sfnt.fields.concat(tableFields); + return sfnt; +} +function metricsForChar(font, chars, notFoundMetrics) { + for (var i = 0;i < chars.length; i += 1) { + var glyphIndex = font.charToGlyphIndex(chars[i]); + if (glyphIndex > 0) { + var glyph = font.glyphs.get(glyphIndex); + return glyph.getMetrics(); + } + } + return notFoundMetrics; +} +function average(vs) { + var sum2 = 0; + for (var i = 0;i < vs.length; i += 1) { + sum2 += vs[i]; + } + return sum2 / vs.length; +} +function fontToSfntTable(font) { + var xMins = []; + var yMins = []; + var xMaxs = []; + var yMaxs = []; + var advanceWidths = []; + var leftSideBearings = []; + var rightSideBearings = []; + var firstCharIndex; + var lastCharIndex = 0; + var ulUnicodeRange1 = 0; + var ulUnicodeRange2 = 0; + var ulUnicodeRange3 = 0; + var ulUnicodeRange4 = 0; + for (var i = 0;i < font.glyphs.length; i += 1) { + var glyph = font.glyphs.get(i); + var unicode = glyph.unicode | 0; + if (isNaN(glyph.advanceWidth)) { + throw new Error("Glyph " + glyph.name + " (" + i + "): advanceWidth is not a number."); + } + if (firstCharIndex > unicode || firstCharIndex === undefined) { + if (unicode > 0) { + firstCharIndex = unicode; + } + } + if (lastCharIndex < unicode) { + lastCharIndex = unicode; + } + var position2 = os2.getUnicodeRange(unicode); + if (position2 < 32) { + ulUnicodeRange1 |= 1 << position2; + } else if (position2 < 64) { + ulUnicodeRange2 |= 1 << position2 - 32; + } else if (position2 < 96) { + ulUnicodeRange3 |= 1 << position2 - 64; + } else if (position2 < 123) { + ulUnicodeRange4 |= 1 << position2 - 96; + } else { + throw new Error("Unicode ranges bits > 123 are reserved for internal usage"); + } + if (glyph.name === ".notdef") { + continue; + } + var metrics = glyph.getMetrics(); + xMins.push(metrics.xMin); + yMins.push(metrics.yMin); + xMaxs.push(metrics.xMax); + yMaxs.push(metrics.yMax); + leftSideBearings.push(metrics.leftSideBearing); + rightSideBearings.push(metrics.rightSideBearing); + advanceWidths.push(glyph.advanceWidth); + } + var globals = { + xMin: Math.min.apply(null, xMins), + yMin: Math.min.apply(null, yMins), + xMax: Math.max.apply(null, xMaxs), + yMax: Math.max.apply(null, yMaxs), + advanceWidthMax: Math.max.apply(null, advanceWidths), + advanceWidthAvg: average(advanceWidths), + minLeftSideBearing: Math.min.apply(null, leftSideBearings), + maxLeftSideBearing: Math.max.apply(null, leftSideBearings), + minRightSideBearing: Math.min.apply(null, rightSideBearings) + }; + globals.ascender = font.ascender; + globals.descender = font.descender; + var headTable = head.make({ + flags: 3, + unitsPerEm: font.unitsPerEm, + xMin: globals.xMin, + yMin: globals.yMin, + xMax: globals.xMax, + yMax: globals.yMax, + lowestRecPPEM: 3, + createdTimestamp: font.createdTimestamp + }); + var hheaTable = hhea.make({ + ascender: globals.ascender, + descender: globals.descender, + advanceWidthMax: globals.advanceWidthMax, + minLeftSideBearing: globals.minLeftSideBearing, + minRightSideBearing: globals.minRightSideBearing, + xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin), + numberOfHMetrics: font.glyphs.length + }); + var maxpTable = maxp.make(font.glyphs.length); + var os2Table = os2.make(Object.assign({ + xAvgCharWidth: Math.round(globals.advanceWidthAvg), + usFirstCharIndex: firstCharIndex, + usLastCharIndex: lastCharIndex, + ulUnicodeRange1, + ulUnicodeRange2, + ulUnicodeRange3, + ulUnicodeRange4, + sTypoAscender: globals.ascender, + sTypoDescender: globals.descender, + sTypoLineGap: 0, + usWinAscent: globals.yMax, + usWinDescent: Math.abs(globals.yMin), + ulCodePageRange1: 1, + sxHeight: metricsForChar(font, "xyvw", { yMax: Math.round(globals.ascender / 2) }).yMax, + sCapHeight: metricsForChar(font, "HIKLEFJMNTZBDPRAGOQSUVWXY", globals).yMax, + usDefaultChar: font.hasChar(" ") ? 32 : 0, + usBreakChar: font.hasChar(" ") ? 32 : 0 + }, font.tables.os2)); + var hmtxTable = hmtx.make(font.glyphs); + var cmapTable = cmap.make(font.glyphs); + var englishFamilyName = font.getEnglishName("fontFamily"); + var englishStyleName = font.getEnglishName("fontSubfamily"); + var englishFullName = englishFamilyName + " " + englishStyleName; + var postScriptName = font.getEnglishName("postScriptName"); + if (!postScriptName) { + postScriptName = englishFamilyName.replace(/\s/g, "") + "-" + englishStyleName; + } + var names = {}; + for (var n2 in font.names) { + names[n2] = font.names[n2]; + } + if (!names.uniqueID) { + names.uniqueID = { en: font.getEnglishName("manufacturer") + ":" + englishFullName }; + } + if (!names.postScriptName) { + names.postScriptName = { en: postScriptName }; + } + if (!names.preferredFamily) { + names.preferredFamily = font.names.fontFamily; + } + if (!names.preferredSubfamily) { + names.preferredSubfamily = font.names.fontSubfamily; + } + var languageTags = []; + var nameTable = _name.make(names, languageTags); + var ltagTable = languageTags.length > 0 ? ltag.make(languageTags) : undefined; + var postTable = post.make(); + var cffTable = cff.make(font.glyphs, { + version: font.getEnglishName("version"), + fullName: englishFullName, + familyName: englishFamilyName, + weightName: englishStyleName, + postScriptName, + unitsPerEm: font.unitsPerEm, + fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax] + }); + var metaTable = font.metas && Object.keys(font.metas).length > 0 ? meta.make(font.metas) : undefined; + var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable]; + if (ltagTable) { + tables.push(ltagTable); + } + if (font.tables.gsub) { + tables.push(gsub.make(font.tables.gsub)); + } + if (font.tables.cpal) { + tables.push(cpal.make(font.tables.cpal)); + } + if (font.tables.colr) { + tables.push(colr.make(font.tables.colr)); + } + if (metaTable) { + tables.push(metaTable); + } + var sfntTable = makeSfntTable(tables); + var bytes = sfntTable.encode(); + var checkSum = computeCheckSum(bytes); + var tableFields = sfntTable.fields; + var checkSumAdjusted = false; + for (var i$1 = 0;i$1 < tableFields.length; i$1 += 1) { + if (tableFields[i$1].name === "head table") { + tableFields[i$1].value.checkSumAdjustment = 2981146554 - checkSum; + checkSumAdjusted = true; + break; + } + } + if (!checkSumAdjusted) { + throw new Error("Could not find head table with checkSum to adjust."); + } + return sfntTable; +} +var sfnt = { make: makeSfntTable, fontToTable: fontToSfntTable, computeCheckSum }; +function searchTag(arr, tag) { + var imin = 0; + var imax = arr.length - 1; + while (imin <= imax) { + var imid = imin + imax >>> 1; + var val2 = arr[imid].tag; + if (val2 === tag) { + return imid; + } else if (val2 < tag) { + imin = imid + 1; + } else { + imax = imid - 1; + } + } + return -imin - 1; +} +function binSearch(arr, value2) { + var imin = 0; + var imax = arr.length - 1; + while (imin <= imax) { + var imid = imin + imax >>> 1; + var val2 = arr[imid]; + if (val2 === value2) { + return imid; + } else if (val2 < value2) { + imin = imid + 1; + } else { + imax = imid - 1; + } + } + return -imin - 1; +} +function searchRange(ranges, value2) { + var range; + var imin = 0; + var imax = ranges.length - 1; + while (imin <= imax) { + var imid = imin + imax >>> 1; + range = ranges[imid]; + var start = range.start; + if (start === value2) { + return range; + } else if (start < value2) { + imin = imid + 1; + } else { + imax = imid - 1; + } + } + if (imin > 0) { + range = ranges[imin - 1]; + if (value2 > range.end) { + return 0; + } + return range; + } +} +function Layout(font, tableName) { + this.font = font; + this.tableName = tableName; +} +Layout.prototype = { + searchTag, + binSearch, + getTable: function(create) { + var layout = this.font.tables[this.tableName]; + if (!layout && create) { + layout = this.font.tables[this.tableName] = this.createDefaultTable(); + } + return layout; + }, + getScriptNames: function() { + var layout = this.getTable(); + if (!layout) { + return []; + } + return layout.scripts.map(function(script) { + return script.tag; + }); + }, + getDefaultScriptName: function() { + var layout = this.getTable(); + if (!layout) { + return; + } + var hasLatn = false; + for (var i = 0;i < layout.scripts.length; i++) { + var name2 = layout.scripts[i].tag; + if (name2 === "DFLT") { + return name2; + } + if (name2 === "latn") { + hasLatn = true; + } + } + if (hasLatn) { + return "latn"; + } + }, + getScriptTable: function(script, create) { + var layout = this.getTable(create); + if (layout) { + script = script || "DFLT"; + var scripts = layout.scripts; + var pos = searchTag(layout.scripts, script); + if (pos >= 0) { + return scripts[pos].script; + } else if (create) { + var scr = { + tag: script, + script: { + defaultLangSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] }, + langSysRecords: [] + } + }; + scripts.splice(-1 - pos, 0, scr); + return scr.script; + } + } + }, + getLangSysTable: function(script, language, create) { + var scriptTable = this.getScriptTable(script, create); + if (scriptTable) { + if (!language || language === "dflt" || language === "DFLT") { + return scriptTable.defaultLangSys; + } + var pos = searchTag(scriptTable.langSysRecords, language); + if (pos >= 0) { + return scriptTable.langSysRecords[pos].langSys; + } else if (create) { + var langSysRecord = { + tag: language, + langSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] } + }; + scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord); + return langSysRecord.langSys; + } + } + }, + getFeatureTable: function(script, language, feature, create) { + var langSysTable2 = this.getLangSysTable(script, language, create); + if (langSysTable2) { + var featureRecord; + var featIndexes = langSysTable2.featureIndexes; + var allFeatures = this.font.tables[this.tableName].features; + for (var i = 0;i < featIndexes.length; i++) { + featureRecord = allFeatures[featIndexes[i]]; + if (featureRecord.tag === feature) { + return featureRecord.feature; + } + } + if (create) { + var index2 = allFeatures.length; + check.assert(index2 === 0 || feature >= allFeatures[index2 - 1].tag, "Features must be added in alphabetical order."); + featureRecord = { + tag: feature, + feature: { params: 0, lookupListIndexes: [] } + }; + allFeatures.push(featureRecord); + featIndexes.push(index2); + return featureRecord.feature; + } + } + }, + getLookupTables: function(script, language, feature, lookupType, create) { + var featureTable = this.getFeatureTable(script, language, feature, create); + var tables = []; + if (featureTable) { + var lookupTable; + var lookupListIndexes = featureTable.lookupListIndexes; + var allLookups = this.font.tables[this.tableName].lookups; + for (var i = 0;i < lookupListIndexes.length; i++) { + lookupTable = allLookups[lookupListIndexes[i]]; + if (lookupTable.lookupType === lookupType) { + tables.push(lookupTable); + } + } + if (tables.length === 0 && create) { + lookupTable = { + lookupType, + lookupFlag: 0, + subtables: [], + markFilteringSet: undefined + }; + var index2 = allLookups.length; + allLookups.push(lookupTable); + lookupListIndexes.push(index2); + return [lookupTable]; + } + } + return tables; + }, + getGlyphClass: function(classDefTable, glyphIndex) { + switch (classDefTable.format) { + case 1: + if (classDefTable.startGlyph <= glyphIndex && glyphIndex < classDefTable.startGlyph + classDefTable.classes.length) { + return classDefTable.classes[glyphIndex - classDefTable.startGlyph]; + } + return 0; + case 2: + var range = searchRange(classDefTable.ranges, glyphIndex); + return range ? range.classId : 0; + } + }, + getCoverageIndex: function(coverageTable, glyphIndex) { + switch (coverageTable.format) { + case 1: + var index2 = binSearch(coverageTable.glyphs, glyphIndex); + return index2 >= 0 ? index2 : -1; + case 2: + var range = searchRange(coverageTable.ranges, glyphIndex); + return range ? range.index + glyphIndex - range.start : -1; + } + }, + expandCoverage: function(coverageTable) { + if (coverageTable.format === 1) { + return coverageTable.glyphs; + } else { + var glyphs = []; + var ranges = coverageTable.ranges; + for (var i = 0;i < ranges.length; i++) { + var range = ranges[i]; + var start = range.start; + var end = range.end; + for (var j2 = start;j2 <= end; j2++) { + glyphs.push(j2); + } + } + return glyphs; + } + } +}; +function Position(font) { + Layout.call(this, font, "gpos"); +} +Position.prototype = Layout.prototype; +Position.prototype.init = function() { + var script = this.getDefaultScriptName(); + this.defaultKerningTables = this.getKerningTables(script); +}; +Position.prototype.getKerningValue = function(kerningLookups, leftIndex, rightIndex) { + for (var i = 0;i < kerningLookups.length; i++) { + var subtables = kerningLookups[i].subtables; + for (var j2 = 0;j2 < subtables.length; j2++) { + var subtable = subtables[j2]; + var covIndex = this.getCoverageIndex(subtable.coverage, leftIndex); + if (covIndex < 0) { + continue; + } + switch (subtable.posFormat) { + case 1: + var pairSet = subtable.pairSets[covIndex]; + for (var k2 = 0;k2 < pairSet.length; k2++) { + var pair = pairSet[k2]; + if (pair.secondGlyph === rightIndex) { + return pair.value1 && pair.value1.xAdvance || 0; + } + } + break; + case 2: + var class1 = this.getGlyphClass(subtable.classDef1, leftIndex); + var class2 = this.getGlyphClass(subtable.classDef2, rightIndex); + var pair$1 = subtable.classRecords[class1][class2]; + return pair$1.value1 && pair$1.value1.xAdvance || 0; + } + } + } + return 0; +}; +Position.prototype.getKerningTables = function(script, language) { + if (this.font.tables.gpos) { + return this.getLookupTables(script, language, "kern", 2); + } +}; +function Substitution(font) { + Layout.call(this, font, "gsub"); +} +function arraysEqual2(ar1, ar2) { + var n2 = ar1.length; + if (n2 !== ar2.length) { + return false; + } + for (var i = 0;i < n2; i++) { + if (ar1[i] !== ar2[i]) { + return false; + } + } + return true; +} +function getSubstFormat(lookupTable, format, defaultSubtable) { + var subtables = lookupTable.subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + if (subtable.substFormat === format) { + return subtable; + } + } + if (defaultSubtable) { + subtables.push(defaultSubtable); + return defaultSubtable; + } + return; +} +Substitution.prototype = Layout.prototype; +Substitution.prototype.createDefaultTable = function() { + return { + version: 1, + scripts: [{ + tag: "DFLT", + script: { + defaultLangSys: { reserved: 0, reqFeatureIndex: 65535, featureIndexes: [] }, + langSysRecords: [] + } + }], + features: [], + lookups: [] + }; +}; +Substitution.prototype.getSingle = function(feature, script, language) { + var substitutions = []; + var lookupTables = this.getLookupTables(script, language, feature, 1); + for (var idx = 0;idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var j2 = undefined; + if (subtable.substFormat === 1) { + var delta = subtable.deltaGlyphId; + for (j2 = 0;j2 < glyphs.length; j2++) { + var glyph = glyphs[j2]; + substitutions.push({ sub: glyph, by: glyph + delta }); + } + } else { + var substitute = subtable.substitute; + for (j2 = 0;j2 < glyphs.length; j2++) { + substitutions.push({ sub: glyphs[j2], by: substitute[j2] }); + } + } + } + } + return substitutions; +}; +Substitution.prototype.getMultiple = function(feature, script, language) { + var substitutions = []; + var lookupTables = this.getLookupTables(script, language, feature, 2); + for (var idx = 0;idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var j2 = undefined; + for (j2 = 0;j2 < glyphs.length; j2++) { + var glyph = glyphs[j2]; + var replacements = subtable.sequences[j2]; + substitutions.push({ sub: glyph, by: replacements }); + } + } + } + return substitutions; +}; +Substitution.prototype.getAlternates = function(feature, script, language) { + var alternates = []; + var lookupTables = this.getLookupTables(script, language, feature, 3); + for (var idx = 0;idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var alternateSets = subtable.alternateSets; + for (var j2 = 0;j2 < glyphs.length; j2++) { + alternates.push({ sub: glyphs[j2], by: alternateSets[j2] }); + } + } + } + return alternates; +}; +Substitution.prototype.getLigatures = function(feature, script, language) { + var ligatures = []; + var lookupTables = this.getLookupTables(script, language, feature, 4); + for (var idx = 0;idx < lookupTables.length; idx++) { + var subtables = lookupTables[idx].subtables; + for (var i = 0;i < subtables.length; i++) { + var subtable = subtables[i]; + var glyphs = this.expandCoverage(subtable.coverage); + var ligatureSets = subtable.ligatureSets; + for (var j2 = 0;j2 < glyphs.length; j2++) { + var startGlyph = glyphs[j2]; + var ligSet = ligatureSets[j2]; + for (var k2 = 0;k2 < ligSet.length; k2++) { + var lig = ligSet[k2]; + ligatures.push({ + sub: [startGlyph].concat(lig.components), + by: lig.ligGlyph + }); + } + } + } + } + return ligatures; +}; +Substitution.prototype.addSingle = function(feature, substitution, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 1, true)[0]; + var subtable = getSubstFormat(lookupTable, 2, { + substFormat: 2, + coverage: { format: 1, glyphs: [] }, + substitute: [] + }); + check.assert(subtable.coverage.format === 1, "Single: unable to modify coverage table format " + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.substitute.splice(pos, 0, 0); + } + subtable.substitute[pos] = substitution.by; +}; +Substitution.prototype.addMultiple = function(feature, substitution, script, language) { + check.assert(substitution.by instanceof Array && substitution.by.length > 1, 'Multiple: "by" must be an array of two or more ids'); + var lookupTable = this.getLookupTables(script, language, feature, 2, true)[0]; + var subtable = getSubstFormat(lookupTable, 1, { + substFormat: 1, + coverage: { format: 1, glyphs: [] }, + sequences: [] + }); + check.assert(subtable.coverage.format === 1, "Multiple: unable to modify coverage table format " + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.sequences.splice(pos, 0, 0); + } + subtable.sequences[pos] = substitution.by; +}; +Substitution.prototype.addAlternate = function(feature, substitution, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 3, true)[0]; + var subtable = getSubstFormat(lookupTable, 1, { + substFormat: 1, + coverage: { format: 1, glyphs: [] }, + alternateSets: [] + }); + check.assert(subtable.coverage.format === 1, "Alternate: unable to modify coverage table format " + subtable.coverage.format); + var coverageGlyph = substitution.sub; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos < 0) { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.alternateSets.splice(pos, 0, 0); + } + subtable.alternateSets[pos] = substitution.by; +}; +Substitution.prototype.addLigature = function(feature, ligature, script, language) { + var lookupTable = this.getLookupTables(script, language, feature, 4, true)[0]; + var subtable = lookupTable.subtables[0]; + if (!subtable) { + subtable = { + substFormat: 1, + coverage: { format: 1, glyphs: [] }, + ligatureSets: [] + }; + lookupTable.subtables[0] = subtable; + } + check.assert(subtable.coverage.format === 1, "Ligature: unable to modify coverage table format " + subtable.coverage.format); + var coverageGlyph = ligature.sub[0]; + var ligComponents = ligature.sub.slice(1); + var ligatureTable = { + ligGlyph: ligature.by, + components: ligComponents + }; + var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph); + if (pos >= 0) { + var ligatureSet = subtable.ligatureSets[pos]; + for (var i = 0;i < ligatureSet.length; i++) { + if (arraysEqual2(ligatureSet[i].components, ligComponents)) { + return; + } + } + ligatureSet.push(ligatureTable); + } else { + pos = -1 - pos; + subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); + subtable.ligatureSets.splice(pos, 0, [ligatureTable]); + } +}; +Substitution.prototype.getFeature = function(feature, script, language) { + if (/ss\d\d/.test(feature)) { + return this.getSingle(feature, script, language); + } + switch (feature) { + case "aalt": + case "salt": + return this.getSingle(feature, script, language).concat(this.getAlternates(feature, script, language)); + case "dlig": + case "liga": + case "rlig": + return this.getLigatures(feature, script, language); + case "ccmp": + return this.getMultiple(feature, script, language).concat(this.getLigatures(feature, script, language)); + case "stch": + return this.getMultiple(feature, script, language); + } + return; +}; +Substitution.prototype.add = function(feature, sub2, script, language) { + if (/ss\d\d/.test(feature)) { + return this.addSingle(feature, sub2, script, language); + } + switch (feature) { + case "aalt": + case "salt": + if (typeof sub2.by === "number") { + return this.addSingle(feature, sub2, script, language); + } + return this.addAlternate(feature, sub2, script, language); + case "dlig": + case "liga": + case "rlig": + return this.addLigature(feature, sub2, script, language); + case "ccmp": + if (sub2.by instanceof Array) { + return this.addMultiple(feature, sub2, script, language); + } + return this.addLigature(feature, sub2, script, language); + } + return; +}; +function checkArgument(expression, message) { + if (!expression) { + throw message; + } +} +function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { + var v; + if ((flag & shortVectorBitMask) > 0) { + v = p.parseByte(); + if ((flag & sameBitMask) === 0) { + v = -v; + } + v = previousValue + v; + } else { + if ((flag & sameBitMask) > 0) { + v = previousValue; + } else { + v = previousValue + p.parseShort(); + } + } + return v; +} +function parseGlyph(glyph, data2, start) { + var p = new parse.Parser(data2, start); + glyph.numberOfContours = p.parseShort(); + glyph._xMin = p.parseShort(); + glyph._yMin = p.parseShort(); + glyph._xMax = p.parseShort(); + glyph._yMax = p.parseShort(); + var flags; + var flag; + if (glyph.numberOfContours > 0) { + var endPointIndices = glyph.endPointIndices = []; + for (var i = 0;i < glyph.numberOfContours; i += 1) { + endPointIndices.push(p.parseUShort()); + } + glyph.instructionLength = p.parseUShort(); + glyph.instructions = []; + for (var i$1 = 0;i$1 < glyph.instructionLength; i$1 += 1) { + glyph.instructions.push(p.parseByte()); + } + var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; + flags = []; + for (var i$2 = 0;i$2 < numberOfCoordinates; i$2 += 1) { + flag = p.parseByte(); + flags.push(flag); + if ((flag & 8) > 0) { + var repeatCount = p.parseByte(); + for (var j2 = 0;j2 < repeatCount; j2 += 1) { + flags.push(flag); + i$2 += 1; + } + } + } + check.argument(flags.length === numberOfCoordinates, "Bad flags."); + if (endPointIndices.length > 0) { + var points = []; + var point; + if (numberOfCoordinates > 0) { + for (var i$3 = 0;i$3 < numberOfCoordinates; i$3 += 1) { + flag = flags[i$3]; + point = {}; + point.onCurve = !!(flag & 1); + point.lastPointOfContour = endPointIndices.indexOf(i$3) >= 0; + points.push(point); + } + var px2 = 0; + for (var i$4 = 0;i$4 < numberOfCoordinates; i$4 += 1) { + flag = flags[i$4]; + point = points[i$4]; + point.x = parseGlyphCoordinate(p, flag, px2, 2, 16); + px2 = point.x; + } + var py2 = 0; + for (var i$5 = 0;i$5 < numberOfCoordinates; i$5 += 1) { + flag = flags[i$5]; + point = points[i$5]; + point.y = parseGlyphCoordinate(p, flag, py2, 4, 32); + py2 = point.y; + } + } + glyph.points = points; + } else { + glyph.points = []; + } + } else if (glyph.numberOfContours === 0) { + glyph.points = []; + } else { + glyph.isComposite = true; + glyph.points = []; + glyph.components = []; + var moreComponents = true; + while (moreComponents) { + flags = p.parseUShort(); + var component = { + glyphIndex: p.parseUShort(), + xScale: 1, + scale01: 0, + scale10: 0, + yScale: 1, + dx: 0, + dy: 0 + }; + if ((flags & 1) > 0) { + if ((flags & 2) > 0) { + component.dx = p.parseShort(); + component.dy = p.parseShort(); + } else { + component.matchedPoints = [p.parseUShort(), p.parseUShort()]; + } + } else { + if ((flags & 2) > 0) { + component.dx = p.parseChar(); + component.dy = p.parseChar(); + } else { + component.matchedPoints = [p.parseByte(), p.parseByte()]; + } + } + if ((flags & 8) > 0) { + component.xScale = component.yScale = p.parseF2Dot14(); + } else if ((flags & 64) > 0) { + component.xScale = p.parseF2Dot14(); + component.yScale = p.parseF2Dot14(); + } else if ((flags & 128) > 0) { + component.xScale = p.parseF2Dot14(); + component.scale01 = p.parseF2Dot14(); + component.scale10 = p.parseF2Dot14(); + component.yScale = p.parseF2Dot14(); + } + glyph.components.push(component); + moreComponents = !!(flags & 32); + } + if (flags & 256) { + glyph.instructionLength = p.parseUShort(); + glyph.instructions = []; + for (var i$6 = 0;i$6 < glyph.instructionLength; i$6 += 1) { + glyph.instructions.push(p.parseByte()); + } + } + } +} +function transformPoints(points, transform2) { + var newPoints = []; + for (var i = 0;i < points.length; i += 1) { + var pt = points[i]; + var newPt = { + x: transform2.xScale * pt.x + transform2.scale01 * pt.y + transform2.dx, + y: transform2.scale10 * pt.x + transform2.yScale * pt.y + transform2.dy, + onCurve: pt.onCurve, + lastPointOfContour: pt.lastPointOfContour + }; + newPoints.push(newPt); + } + return newPoints; +} +function getContours(points) { + var contours = []; + var currentContour = []; + for (var i = 0;i < points.length; i += 1) { + var pt = points[i]; + currentContour.push(pt); + if (pt.lastPointOfContour) { + contours.push(currentContour); + currentContour = []; + } + } + check.argument(currentContour.length === 0, "There are still points left in the current contour."); + return contours; +} +function getPath(points) { + var p = new Path2; + if (!points) { + return p; + } + var contours = getContours(points); + for (var contourIndex = 0;contourIndex < contours.length; ++contourIndex) { + var contour = contours[contourIndex]; + var prev = null; + var curr = contour[contour.length - 1]; + var next = contour[0]; + if (curr.onCurve) { + p.moveTo(curr.x, curr.y); + } else { + if (next.onCurve) { + p.moveTo(next.x, next.y); + } else { + var start = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 }; + p.moveTo(start.x, start.y); + } + } + for (var i = 0;i < contour.length; ++i) { + prev = curr; + curr = next; + next = contour[(i + 1) % contour.length]; + if (curr.onCurve) { + p.lineTo(curr.x, curr.y); + } else { + var prev2 = prev; + var next2 = next; + if (!prev.onCurve) { + prev2 = { x: (curr.x + prev.x) * 0.5, y: (curr.y + prev.y) * 0.5 }; + } + if (!next.onCurve) { + next2 = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 }; + } + p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y); + } + } + p.closePath(); + } + return p; +} +function buildPath(glyphs, glyph) { + if (glyph.isComposite) { + for (var j2 = 0;j2 < glyph.components.length; j2 += 1) { + var component = glyph.components[j2]; + var componentGlyph = glyphs.get(component.glyphIndex); + componentGlyph.getPath(); + if (componentGlyph.points) { + var transformedPoints = undefined; + if (component.matchedPoints === undefined) { + transformedPoints = transformPoints(componentGlyph.points, component); + } else { + if (component.matchedPoints[0] > glyph.points.length - 1 || component.matchedPoints[1] > componentGlyph.points.length - 1) { + throw Error("Matched points out of range in " + glyph.name); + } + var firstPt = glyph.points[component.matchedPoints[0]]; + var secondPt = componentGlyph.points[component.matchedPoints[1]]; + var transform2 = { + xScale: component.xScale, + scale01: component.scale01, + scale10: component.scale10, + yScale: component.yScale, + dx: 0, + dy: 0 + }; + secondPt = transformPoints([secondPt], transform2)[0]; + transform2.dx = firstPt.x - secondPt.x; + transform2.dy = firstPt.y - secondPt.y; + transformedPoints = transformPoints(componentGlyph.points, transform2); + } + glyph.points = glyph.points.concat(transformedPoints); + } + } + } + return getPath(glyph.points); +} +function parseGlyfTableAll(data2, start, loca, font) { + var glyphs = new glyphset.GlyphSet(font); + for (var i = 0;i < loca.length - 1; i += 1) { + var offset = loca[i]; + var nextOffset = loca[i + 1]; + if (offset !== nextOffset) { + glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data2, start + offset, buildPath)); + } else { + glyphs.push(i, glyphset.glyphLoader(font, i)); + } + } + return glyphs; +} +function parseGlyfTableOnLowMemory(data2, start, loca, font) { + var glyphs = new glyphset.GlyphSet(font); + font._push = function(i) { + var offset = loca[i]; + var nextOffset = loca[i + 1]; + if (offset !== nextOffset) { + glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data2, start + offset, buildPath)); + } else { + glyphs.push(i, glyphset.glyphLoader(font, i)); + } + }; + return glyphs; +} +function parseGlyfTable(data2, start, loca, font, opt) { + if (opt.lowMemory) { + return parseGlyfTableOnLowMemory(data2, start, loca, font); + } else { + return parseGlyfTableAll(data2, start, loca, font); + } +} +var glyf = { getPath, parse: parseGlyfTable }; +var instructionTable; +var exec; +var execGlyph; +var execComponent; +function Hinting(font) { + this.font = font; + this.getCommands = function(hPoints) { + return glyf.getPath(hPoints).commands; + }; + this._fpgmState = this._prepState = undefined; + this._errorState = 0; +} +function roundOff(v) { + return v; +} +function roundToGrid(v) { + return Math.sign(v) * Math.round(Math.abs(v)); +} +function roundToDoubleGrid(v) { + return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2; +} +function roundToHalfGrid(v) { + return Math.sign(v) * (Math.round(Math.abs(v) + 0.5) - 0.5); +} +function roundUpToGrid(v) { + return Math.sign(v) * Math.ceil(Math.abs(v)); +} +function roundDownToGrid(v) { + return Math.sign(v) * Math.floor(Math.abs(v)); +} +var roundSuper = function(v) { + var period = this.srPeriod; + var phase = this.srPhase; + var threshold = this.srThreshold; + var sign2 = 1; + if (v < 0) { + v = -v; + sign2 = -1; + } + v += threshold - phase; + v = Math.trunc(v / period) * period; + v += phase; + if (v < 0) { + return phase * sign2; + } + return v * sign2; +}; +var xUnitVector = { + x: 1, + y: 0, + axis: "x", + distance: function(p1, p2, o1, o2) { + return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x); + }, + interpolate: function(p, rp1, rp2, pv) { + var do1; + var do2; + var doa1; + var doa2; + var dm1; + var dm2; + var dt; + if (!pv || pv === this) { + do1 = p.xo - rp1.xo; + do2 = p.xo - rp2.xo; + dm1 = rp1.x - rp1.xo; + dm2 = rp2.x - rp2.xo; + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + p.x = p.xo + (dm1 + dm2) / 2; + return; + } + p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt; + return; + } + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); + }, + normalSlope: Number.NEGATIVE_INFINITY, + setRelative: function(p, rp, d, pv, org) { + if (!pv || pv === this) { + p.x = (org ? rp.xo : rp.x) + d; + return; + } + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + p.x = rpdx + (p.y - rpdy) / pv.normalSlope; + }, + slope: 0, + touch: function(p) { + p.xTouched = true; + }, + touched: function(p) { + return p.xTouched; + }, + untouch: function(p) { + p.xTouched = false; + } +}; +var yUnitVector = { + x: 0, + y: 1, + axis: "y", + distance: function(p1, p2, o1, o2) { + return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y); + }, + interpolate: function(p, rp1, rp2, pv) { + var do1; + var do2; + var doa1; + var doa2; + var dm1; + var dm2; + var dt; + if (!pv || pv === this) { + do1 = p.yo - rp1.yo; + do2 = p.yo - rp2.yo; + dm1 = rp1.y - rp1.yo; + dm2 = rp2.y - rp2.yo; + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + p.y = p.yo + (dm1 + dm2) / 2; + return; + } + p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt; + return; + } + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); + }, + normalSlope: 0, + setRelative: function(p, rp, d, pv, org) { + if (!pv || pv === this) { + p.y = (org ? rp.yo : rp.y) + d; + return; + } + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + p.y = rpdy + pv.normalSlope * (p.x - rpdx); + }, + slope: Number.POSITIVE_INFINITY, + touch: function(p) { + p.yTouched = true; + }, + touched: function(p) { + return p.yTouched; + }, + untouch: function(p) { + p.yTouched = false; + } +}; +Object.freeze(xUnitVector); +Object.freeze(yUnitVector); +function UnitVector(x2, y) { + this.x = x2; + this.y = y; + this.axis = undefined; + this.slope = y / x2; + this.normalSlope = -x2 / y; + Object.freeze(this); +} +UnitVector.prototype.distance = function(p1, p2, o1, o2) { + return this.x * xUnitVector.distance(p1, p2, o1, o2) + this.y * yUnitVector.distance(p1, p2, o1, o2); +}; +UnitVector.prototype.interpolate = function(p, rp1, rp2, pv) { + var dm1; + var dm2; + var do1; + var do2; + var doa1; + var doa2; + var dt; + do1 = pv.distance(p, rp1, true, true); + do2 = pv.distance(p, rp2, true, true); + dm1 = pv.distance(rp1, rp1, false, true); + dm2 = pv.distance(rp2, rp2, false, true); + doa1 = Math.abs(do1); + doa2 = Math.abs(do2); + dt = doa1 + doa2; + if (dt === 0) { + this.setRelative(p, p, (dm1 + dm2) / 2, pv, true); + return; + } + this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); +}; +UnitVector.prototype.setRelative = function(p, rp, d, pv, org) { + pv = pv || this; + var rpx = org ? rp.xo : rp.x; + var rpy = org ? rp.yo : rp.y; + var rpdx = rpx + d * pv.x; + var rpdy = rpy + d * pv.y; + var pvns = pv.normalSlope; + var fvs = this.slope; + var px2 = p.x; + var py2 = p.y; + p.x = (fvs * px2 - pvns * rpdx + rpdy - py2) / (fvs - pvns); + p.y = fvs * (p.x - px2) + py2; +}; +UnitVector.prototype.touch = function(p) { + p.xTouched = true; + p.yTouched = true; +}; +function getUnitVector(x2, y) { + var d = Math.sqrt(x2 * x2 + y * y); + x2 /= d; + y /= d; + if (x2 === 1 && y === 0) { + return xUnitVector; + } else if (x2 === 0 && y === 1) { + return yUnitVector; + } else { + return new UnitVector(x2, y); + } +} +function HPoint(x2, y, lastPointOfContour, onCurve) { + this.x = this.xo = Math.round(x2 * 64) / 64; + this.y = this.yo = Math.round(y * 64) / 64; + this.lastPointOfContour = lastPointOfContour; + this.onCurve = onCurve; + this.prevPointOnContour = undefined; + this.nextPointOnContour = undefined; + this.xTouched = false; + this.yTouched = false; + Object.preventExtensions(this); +} +HPoint.prototype.nextTouched = function(v) { + var p = this.nextPointOnContour; + while (!v.touched(p) && p !== this) { + p = p.nextPointOnContour; + } + return p; +}; +HPoint.prototype.prevTouched = function(v) { + var p = this.prevPointOnContour; + while (!v.touched(p) && p !== this) { + p = p.prevPointOnContour; + } + return p; +}; +var HPZero = Object.freeze(new HPoint(0, 0)); +var defaultState = { + cvCutIn: 17 / 16, + deltaBase: 9, + deltaShift: 0.125, + loop: 1, + minDis: 1, + autoFlip: true +}; +function State(env, prog) { + this.env = env; + this.stack = []; + this.prog = prog; + switch (env) { + case "glyf": + this.zp0 = this.zp1 = this.zp2 = 1; + this.rp0 = this.rp1 = this.rp2 = 0; + case "prep": + this.fv = this.pv = this.dpv = xUnitVector; + this.round = roundToGrid; + } +} +Hinting.prototype.exec = function(glyph, ppem) { + if (typeof ppem !== "number") { + throw new Error("Point size is not a number!"); + } + if (this._errorState > 2) { + return; + } + var font = this.font; + var prepState = this._prepState; + if (!prepState || prepState.ppem !== ppem) { + var fpgmState = this._fpgmState; + if (!fpgmState) { + State.prototype = defaultState; + fpgmState = this._fpgmState = new State("fpgm", font.tables.fpgm); + fpgmState.funcs = []; + fpgmState.font = font; + if (exports_opentype_module.DEBUG) { + console.log("---EXEC FPGM---"); + fpgmState.step = -1; + } + try { + exec(fpgmState); + } catch (e) { + console.log("Hinting error in FPGM:" + e); + this._errorState = 3; + return; + } + } + State.prototype = fpgmState; + prepState = this._prepState = new State("prep", font.tables.prep); + prepState.ppem = ppem; + var oCvt = font.tables.cvt; + if (oCvt) { + var cvt = prepState.cvt = new Array(oCvt.length); + var scale2 = ppem / font.unitsPerEm; + for (var c = 0;c < oCvt.length; c++) { + cvt[c] = oCvt[c] * scale2; + } + } else { + prepState.cvt = []; + } + if (exports_opentype_module.DEBUG) { + console.log("---EXEC PREP---"); + prepState.step = -1; + } + try { + exec(prepState); + } catch (e) { + if (this._errorState < 2) { + console.log("Hinting error in PREP:" + e); + } + this._errorState = 2; + } + } + if (this._errorState > 1) { + return; + } + try { + return execGlyph(glyph, prepState); + } catch (e) { + if (this._errorState < 1) { + console.log("Hinting error:" + e); + console.log("Note: further hinting errors are silenced"); + } + this._errorState = 1; + return; + } +}; +execGlyph = function(glyph, prepState) { + var xScale = prepState.ppem / prepState.font.unitsPerEm; + var yScale = xScale; + var components = glyph.components; + var contours; + var gZone; + var state; + State.prototype = prepState; + if (!components) { + state = new State("glyf", glyph.instructions); + if (exports_opentype_module.DEBUG) { + console.log("---EXEC GLYPH---"); + state.step = -1; + } + execComponent(glyph, state, xScale, yScale); + gZone = state.gZone; + } else { + var font = prepState.font; + gZone = []; + contours = []; + for (var i = 0;i < components.length; i++) { + var c = components[i]; + var cg = font.glyphs.get(c.glyphIndex); + state = new State("glyf", cg.instructions); + if (exports_opentype_module.DEBUG) { + console.log("---EXEC COMP " + i + "---"); + state.step = -1; + } + execComponent(cg, state, xScale, yScale); + var dx = Math.round(c.dx * xScale); + var dy = Math.round(c.dy * yScale); + var gz = state.gZone; + var cc = state.contours; + for (var pi2 = 0;pi2 < gz.length; pi2++) { + var p = gz[pi2]; + p.xTouched = p.yTouched = false; + p.xo = p.x = p.x + dx; + p.yo = p.y = p.y + dy; + } + var gLen = gZone.length; + gZone.push.apply(gZone, gz); + for (var j2 = 0;j2 < cc.length; j2++) { + contours.push(cc[j2] + gLen); + } + } + if (glyph.instructions && !state.inhibitGridFit) { + state = new State("glyf", glyph.instructions); + state.gZone = state.z0 = state.z1 = state.z2 = gZone; + state.contours = contours; + gZone.push(new HPoint(0, 0), new HPoint(Math.round(glyph.advanceWidth * xScale), 0)); + if (exports_opentype_module.DEBUG) { + console.log("---EXEC COMPOSITE---"); + state.step = -1; + } + exec(state); + gZone.length -= 2; + } + } + return gZone; +}; +execComponent = function(glyph, state, xScale, yScale) { + var points = glyph.points || []; + var pLen = points.length; + var gZone = state.gZone = state.z0 = state.z1 = state.z2 = []; + var contours = state.contours = []; + var cp; + for (var i = 0;i < pLen; i++) { + cp = points[i]; + gZone[i] = new HPoint(cp.x * xScale, cp.y * yScale, cp.lastPointOfContour, cp.onCurve); + } + var sp; + var np; + for (var i$1 = 0;i$1 < pLen; i$1++) { + cp = gZone[i$1]; + if (!sp) { + sp = cp; + contours.push(i$1); + } + if (cp.lastPointOfContour) { + cp.nextPointOnContour = sp; + sp.prevPointOnContour = cp; + sp = undefined; + } else { + np = gZone[i$1 + 1]; + cp.nextPointOnContour = np; + np.prevPointOnContour = cp; + } + } + if (state.inhibitGridFit) { + return; + } + if (exports_opentype_module.DEBUG) { + console.log("PROCESSING GLYPH", state.stack); + for (var i$2 = 0;i$2 < pLen; i$2++) { + console.log(i$2, gZone[i$2].x, gZone[i$2].y); + } + } + gZone.push(new HPoint(0, 0), new HPoint(Math.round(glyph.advanceWidth * xScale), 0)); + exec(state); + gZone.length -= 2; + if (exports_opentype_module.DEBUG) { + console.log("FINISHED GLYPH", state.stack); + for (var i$3 = 0;i$3 < pLen; i$3++) { + console.log(i$3, gZone[i$3].x, gZone[i$3].y); + } + } +}; +exec = function(state) { + var prog = state.prog; + if (!prog) { + return; + } + var pLen = prog.length; + var ins; + for (state.ip = 0;state.ip < pLen; state.ip++) { + if (exports_opentype_module.DEBUG) { + state.step++; + } + ins = instructionTable[prog[state.ip]]; + if (!ins) { + throw new Error("unknown instruction: 0x" + Number(prog[state.ip]).toString(16)); + } + ins(state); + } +}; +function initTZone(state) { + var tZone = state.tZone = new Array(state.gZone.length); + for (var i = 0;i < tZone.length; i++) { + tZone[i] = new HPoint(0, 0); + } +} +function skip(state, handleElse) { + var prog = state.prog; + var ip = state.ip; + var nesting = 1; + var ins; + do { + ins = prog[++ip]; + if (ins === 88) { + nesting++; + } else if (ins === 89) { + nesting--; + } else if (ins === 64) { + ip += prog[ip + 1] + 1; + } else if (ins === 65) { + ip += 2 * prog[ip + 1] + 1; + } else if (ins >= 176 && ins <= 183) { + ip += ins - 176 + 1; + } else if (ins >= 184 && ins <= 191) { + ip += (ins - 184 + 1) * 2; + } else if (handleElse && nesting === 1 && ins === 27) { + break; + } + } while (nesting > 0); + state.ip = ip; +} +function SVTCA(v, state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SVTCA[" + v.axis + "]"); + } + state.fv = state.pv = state.dpv = v; +} +function SPVTCA(v, state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SPVTCA[" + v.axis + "]"); + } + state.pv = state.dpv = v; +} +function SFVTCA(v, state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SFVTCA[" + v.axis + "]"); + } + state.fv = v; +} +function SPVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + if (exports_opentype_module.DEBUG) { + console.log("SPVTL[" + a + "]", p2i, p1i); + } + var dx; + var dy; + if (!a) { + dx = p1.x - p2.x; + dy = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy = p1.x - p2.x; + } + state.pv = state.dpv = getUnitVector(dx, dy); +} +function SFVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + if (exports_opentype_module.DEBUG) { + console.log("SFVTL[" + a + "]", p2i, p1i); + } + var dx; + var dy; + if (!a) { + dx = p1.x - p2.x; + dy = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy = p1.x - p2.x; + } + state.fv = getUnitVector(dx, dy); +} +function SPVFS(state) { + var stack = state.stack; + var y = stack.pop(); + var x2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SPVFS[]", y, x2); + } + state.pv = state.dpv = getUnitVector(x2, y); +} +function SFVFS(state) { + var stack = state.stack; + var y = stack.pop(); + var x2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SPVFS[]", y, x2); + } + state.fv = getUnitVector(x2, y); +} +function GPV(state) { + var stack = state.stack; + var pv = state.pv; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GPV[]"); + } + stack.push(pv.x * 16384); + stack.push(pv.y * 16384); +} +function GFV(state) { + var stack = state.stack; + var fv = state.fv; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GFV[]"); + } + stack.push(fv.x * 16384); + stack.push(fv.y * 16384); +} +function SFVTPV(state) { + state.fv = state.pv; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SFVTPV[]"); + } +} +function ISECT(state) { + var stack = state.stack; + var pa0i = stack.pop(); + var pa1i = stack.pop(); + var pb0i = stack.pop(); + var pb1i = stack.pop(); + var pi2 = stack.pop(); + var z0 = state.z0; + var z1 = state.z1; + var pa0 = z0[pa0i]; + var pa1 = z0[pa1i]; + var pb0 = z1[pb0i]; + var pb1 = z1[pb1i]; + var p = state.z2[pi2]; + if (exports_opentype_module.DEBUG) { + console.log("ISECT[], ", pa0i, pa1i, pb0i, pb1i, pi2); + } + var x1 = pa0.x; + var y1 = pa0.y; + var x2 = pa1.x; + var y2 = pa1.y; + var x3 = pb0.x; + var y3 = pb0.y; + var x4 = pb1.x; + var y4 = pb1.y; + var div2 = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); + var f1 = x1 * y2 - y1 * x2; + var f2 = x3 * y4 - y3 * x4; + p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div2; + p.y = (f1 * (y3 - y4) - f2 * (y1 - y2)) / div2; +} +function SRP0(state) { + state.rp0 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SRP0[]", state.rp0); + } +} +function SRP1(state) { + state.rp1 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SRP1[]", state.rp1); + } +} +function SRP2(state) { + state.rp2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SRP2[]", state.rp2); + } +} +function SZP0(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SZP0[]", n2); + } + state.zp0 = n2; + switch (n2) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z0 = state.tZone; + break; + case 1: + state.z0 = state.gZone; + break; + default: + throw new Error("Invalid zone pointer"); + } +} +function SZP1(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SZP1[]", n2); + } + state.zp1 = n2; + switch (n2) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z1 = state.tZone; + break; + case 1: + state.z1 = state.gZone; + break; + default: + throw new Error("Invalid zone pointer"); + } +} +function SZP2(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SZP2[]", n2); + } + state.zp2 = n2; + switch (n2) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z2 = state.tZone; + break; + case 1: + state.z2 = state.gZone; + break; + default: + throw new Error("Invalid zone pointer"); + } +} +function SZPS(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SZPS[]", n2); + } + state.zp0 = state.zp1 = state.zp2 = n2; + switch (n2) { + case 0: + if (!state.tZone) { + initTZone(state); + } + state.z0 = state.z1 = state.z2 = state.tZone; + break; + case 1: + state.z0 = state.z1 = state.z2 = state.gZone; + break; + default: + throw new Error("Invalid zone pointer"); + } +} +function SLOOP(state) { + state.loop = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SLOOP[]", state.loop); + } +} +function RTG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RTG[]"); + } + state.round = roundToGrid; +} +function RTHG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RTHG[]"); + } + state.round = roundToHalfGrid; +} +function SMD(state) { + var d = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SMD[]", d); + } + state.minDis = d / 64; +} +function ELSE(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ELSE[]"); + } + skip(state, false); +} +function JMPR(state) { + var o = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "JMPR[]", o); + } + state.ip += o - 1; +} +function SCVTCI(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SCVTCI[]", n2); + } + state.cvCutIn = n2 / 64; +} +function DUP(state) { + var stack = state.stack; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DUP[]"); + } + stack.push(stack[stack.length - 1]); +} +function POP(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "POP[]"); + } + state.stack.pop(); +} +function CLEAR(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "CLEAR[]"); + } + state.stack.length = 0; +} +function SWAP(state) { + var stack = state.stack; + var a = stack.pop(); + var b = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SWAP[]"); + } + stack.push(a); + stack.push(b); +} +function DEPTH(state) { + var stack = state.stack; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DEPTH[]"); + } + stack.push(stack.length); +} +function LOOPCALL(state) { + var stack = state.stack; + var fn = stack.pop(); + var c = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "LOOPCALL[]", fn, c); + } + var cip = state.ip; + var cprog = state.prog; + state.prog = state.funcs[fn]; + for (var i = 0;i < c; i++) { + exec(state); + if (exports_opentype_module.DEBUG) { + console.log(++state.step, i + 1 < c ? "next loopcall" : "done loopcall", i); + } + } + state.ip = cip; + state.prog = cprog; +} +function CALL(state) { + var fn = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "CALL[]", fn); + } + var cip = state.ip; + var cprog = state.prog; + state.prog = state.funcs[fn]; + exec(state); + state.ip = cip; + state.prog = cprog; + if (exports_opentype_module.DEBUG) { + console.log(++state.step, "returning from", fn); + } +} +function CINDEX(state) { + var stack = state.stack; + var k2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "CINDEX[]", k2); + } + stack.push(stack[stack.length - k2]); +} +function MINDEX(state) { + var stack = state.stack; + var k2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MINDEX[]", k2); + } + stack.push(stack.splice(stack.length - k2, 1)[0]); +} +function FDEF(state) { + if (state.env !== "fpgm") { + throw new Error("FDEF not allowed here"); + } + var stack = state.stack; + var prog = state.prog; + var ip = state.ip; + var fn = stack.pop(); + var ipBegin = ip; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "FDEF[]", fn); + } + while (prog[++ip] !== 45) { + } + state.ip = ip; + state.funcs[fn] = prog.slice(ipBegin + 1, ip); +} +function MDAP(round, state) { + var pi2 = state.stack.pop(); + var p = state.z0[pi2]; + var fv = state.fv; + var pv = state.pv; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MDAP[" + round + "]", pi2); + } + var d = pv.distance(p, HPZero); + if (round) { + d = state.round(d); + } + fv.setRelative(p, HPZero, d, pv); + fv.touch(p); + state.rp0 = state.rp1 = pi2; +} +function IUP(v, state) { + var z2 = state.z2; + var pLen = z2.length - 2; + var cp; + var pp; + var np; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "IUP[" + v.axis + "]"); + } + for (var i = 0;i < pLen; i++) { + cp = z2[i]; + if (v.touched(cp)) { + continue; + } + pp = cp.prevTouched(v); + if (pp === cp) { + continue; + } + np = cp.nextTouched(v); + if (pp === np) { + v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true); + } + v.interpolate(cp, pp, np, v); + } +} +function SHP(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1)[rpi]; + var fv = state.fv; + var pv = state.pv; + var loop = state.loop; + var z2 = state.z2; + while (loop--) { + var pi2 = stack.pop(); + var p = z2[pi2]; + var d = pv.distance(rp, rp, false, true); + fv.setRelative(p, p, d, pv); + fv.touch(p); + if (exports_opentype_module.DEBUG) { + console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "SHP[" + (a ? "rp1" : "rp2") + "]", pi2); + } + } + state.loop = 1; +} +function SHC(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1)[rpi]; + var fv = state.fv; + var pv = state.pv; + var ci = stack.pop(); + var sp = state.z2[state.contours[ci]]; + var p = sp; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SHC[" + a + "]", ci); + } + var d = pv.distance(rp, rp, false, true); + do { + if (p !== rp) { + fv.setRelative(p, p, d, pv); + } + p = p.nextPointOnContour; + } while (p !== sp); +} +function SHZ(a, state) { + var stack = state.stack; + var rpi = a ? state.rp1 : state.rp2; + var rp = (a ? state.z0 : state.z1)[rpi]; + var fv = state.fv; + var pv = state.pv; + var e = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SHZ[" + a + "]", e); + } + var z; + switch (e) { + case 0: + z = state.tZone; + break; + case 1: + z = state.gZone; + break; + default: + throw new Error("Invalid zone"); + } + var p; + var d = pv.distance(rp, rp, false, true); + var pLen = z.length - 2; + for (var i = 0;i < pLen; i++) { + p = z[i]; + fv.setRelative(p, p, d, pv); + } +} +function SHPIX(state) { + var stack = state.stack; + var loop = state.loop; + var fv = state.fv; + var d = stack.pop() / 64; + var z2 = state.z2; + while (loop--) { + var pi2 = stack.pop(); + var p = z2[pi2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "SHPIX[]", pi2, d); + } + fv.setRelative(p, p, d); + fv.touch(p); + } + state.loop = 1; +} +function IP(state) { + var stack = state.stack; + var rp1i = state.rp1; + var rp2i = state.rp2; + var loop = state.loop; + var rp1 = state.z0[rp1i]; + var rp2 = state.z1[rp2i]; + var fv = state.fv; + var pv = state.dpv; + var z2 = state.z2; + while (loop--) { + var pi2 = stack.pop(); + var p = z2[pi2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "IP[]", pi2, rp1i, "<->", rp2i); + } + fv.interpolate(p, rp1, rp2, pv); + fv.touch(p); + } + state.loop = 1; +} +function MSIRP(a, state) { + var stack = state.stack; + var d = stack.pop() / 64; + var pi2 = stack.pop(); + var p = state.z1[pi2]; + var rp0 = state.z0[state.rp0]; + var fv = state.fv; + var pv = state.pv; + fv.setRelative(p, rp0, d, pv); + fv.touch(p); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MSIRP[" + a + "]", d, pi2); + } + state.rp1 = state.rp0; + state.rp2 = pi2; + if (a) { + state.rp0 = pi2; + } +} +function ALIGNRP(state) { + var stack = state.stack; + var rp0i = state.rp0; + var rp0 = state.z0[rp0i]; + var loop = state.loop; + var fv = state.fv; + var pv = state.pv; + var z1 = state.z1; + while (loop--) { + var pi2 = stack.pop(); + var p = z1[pi2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, (state.loop > 1 ? "loop " + (state.loop - loop) + ": " : "") + "ALIGNRP[]", pi2); + } + fv.setRelative(p, rp0, 0, pv); + fv.touch(p); + } + state.loop = 1; +} +function RTDG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RTDG[]"); + } + state.round = roundToDoubleGrid; +} +function MIAP(round, state) { + var stack = state.stack; + var n2 = stack.pop(); + var pi2 = stack.pop(); + var p = state.z0[pi2]; + var fv = state.fv; + var pv = state.pv; + var cv = state.cvt[n2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MIAP[" + round + "]", n2, "(", cv, ")", pi2); + } + var d = pv.distance(p, HPZero); + if (round) { + if (Math.abs(d - cv) < state.cvCutIn) { + d = cv; + } + d = state.round(d); + } + fv.setRelative(p, HPZero, d, pv); + if (state.zp0 === 0) { + p.xo = p.x; + p.yo = p.y; + } + fv.touch(p); + state.rp0 = state.rp1 = pi2; +} +function NPUSHB(state) { + var prog = state.prog; + var ip = state.ip; + var stack = state.stack; + var n2 = prog[++ip]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NPUSHB[]", n2); + } + for (var i = 0;i < n2; i++) { + stack.push(prog[++ip]); + } + state.ip = ip; +} +function NPUSHW(state) { + var ip = state.ip; + var prog = state.prog; + var stack = state.stack; + var n2 = prog[++ip]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NPUSHW[]", n2); + } + for (var i = 0;i < n2; i++) { + var w = prog[++ip] << 8 | prog[++ip]; + if (w & 32768) { + w = -((w ^ 65535) + 1); + } + stack.push(w); + } + state.ip = ip; +} +function WS(state) { + var stack = state.stack; + var store = state.store; + if (!store) { + store = state.store = []; + } + var v = stack.pop(); + var l2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "WS", v, l2); + } + store[l2] = v; +} +function RS(state) { + var stack = state.stack; + var store = state.store; + var l2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RS", l2); + } + var v = store && store[l2] || 0; + stack.push(v); +} +function WCVTP(state) { + var stack = state.stack; + var v = stack.pop(); + var l2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "WCVTP", v, l2); + } + state.cvt[l2] = v / 64; +} +function RCVT(state) { + var stack = state.stack; + var cvte = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RCVT", cvte); + } + stack.push(state.cvt[cvte] * 64); +} +function GC(a, state) { + var stack = state.stack; + var pi2 = stack.pop(); + var p = state.z2[pi2]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GC[" + a + "]", pi2); + } + stack.push(state.dpv.distance(p, HPZero, a, false) * 64); +} +function MD(a, state) { + var stack = state.stack; + var pi2 = stack.pop(); + var pi1 = stack.pop(); + var p2 = state.z1[pi2]; + var p1 = state.z0[pi1]; + var d = state.dpv.distance(p1, p2, a, a); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MD[" + a + "]", pi2, pi1, "->", d); + } + state.stack.push(Math.round(d * 64)); +} +function MPPEM(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MPPEM[]"); + } + state.stack.push(state.ppem); +} +function FLIPON(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "FLIPON[]"); + } + state.autoFlip = true; +} +function LT(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "LT[]", e2, e1); + } + stack.push(e1 < e2 ? 1 : 0); +} +function LTEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "LTEQ[]", e2, e1); + } + stack.push(e1 <= e2 ? 1 : 0); +} +function GT(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GT[]", e2, e1); + } + stack.push(e1 > e2 ? 1 : 0); +} +function GTEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GTEQ[]", e2, e1); + } + stack.push(e1 >= e2 ? 1 : 0); +} +function EQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "EQ[]", e2, e1); + } + stack.push(e2 === e1 ? 1 : 0); +} +function NEQ(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NEQ[]", e2, e1); + } + stack.push(e2 !== e1 ? 1 : 0); +} +function ODD(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ODD[]", n2); + } + stack.push(Math.trunc(n2) % 2 ? 1 : 0); +} +function EVEN(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "EVEN[]", n2); + } + stack.push(Math.trunc(n2) % 2 ? 0 : 1); +} +function IF(state) { + var test = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "IF[]", test); + } + if (!test) { + skip(state, true); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "EIF[]"); + } + } +} +function EIF(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "EIF[]"); + } +} +function AND(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "AND[]", e2, e1); + } + stack.push(e2 && e1 ? 1 : 0); +} +function OR(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "OR[]", e2, e1); + } + stack.push(e2 || e1 ? 1 : 0); +} +function NOT(state) { + var stack = state.stack; + var e = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NOT[]", e); + } + stack.push(e ? 0 : 1); +} +function DELTAP123(b, state) { + var stack = state.stack; + var n2 = stack.pop(); + var fv = state.fv; + var pv = state.pv; + var ppem = state.ppem; + var base = state.deltaBase + (b - 1) * 16; + var ds = state.deltaShift; + var z0 = state.z0; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DELTAP[" + b + "]", n2, stack); + } + for (var i = 0;i < n2; i++) { + var pi2 = stack.pop(); + var arg = stack.pop(); + var appem = base + ((arg & 240) >> 4); + if (appem !== ppem) { + continue; + } + var mag = (arg & 15) - 8; + if (mag >= 0) { + mag++; + } + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DELTAPFIX", pi2, "by", mag * ds); + } + var p = z0[pi2]; + fv.setRelative(p, p, mag * ds, pv); + } +} +function SDB(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SDB[]", n2); + } + state.deltaBase = n2; +} +function SDS(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SDS[]", n2); + } + state.deltaShift = Math.pow(0.5, n2); +} +function ADD(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ADD[]", n2, n1); + } + stack.push(n1 + n2); +} +function SUB(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SUB[]", n2, n1); + } + stack.push(n1 - n2); +} +function DIV(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DIV[]", n2, n1); + } + stack.push(n1 * 64 / n2); +} +function MUL(state) { + var stack = state.stack; + var n2 = stack.pop(); + var n1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MUL[]", n2, n1); + } + stack.push(n1 * n2 / 64); +} +function ABS(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ABS[]", n2); + } + stack.push(Math.abs(n2)); +} +function NEG(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "NEG[]", n2); + } + stack.push(-n2); +} +function FLOOR(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "FLOOR[]", n2); + } + stack.push(Math.floor(n2 / 64) * 64); +} +function CEILING(state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "CEILING[]", n2); + } + stack.push(Math.ceil(n2 / 64) * 64); +} +function ROUND(dt, state) { + var stack = state.stack; + var n2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ROUND[]"); + } + stack.push(state.round(n2 / 64) * 64); +} +function WCVTF(state) { + var stack = state.stack; + var v = stack.pop(); + var l2 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "WCVTF[]", v, l2); + } + state.cvt[l2] = v * state.ppem / state.font.unitsPerEm; +} +function DELTAC123(b, state) { + var stack = state.stack; + var n2 = stack.pop(); + var ppem = state.ppem; + var base = state.deltaBase + (b - 1) * 16; + var ds = state.deltaShift; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DELTAC[" + b + "]", n2, stack); + } + for (var i = 0;i < n2; i++) { + var c = stack.pop(); + var arg = stack.pop(); + var appem = base + ((arg & 240) >> 4); + if (appem !== ppem) { + continue; + } + var mag = (arg & 15) - 8; + if (mag >= 0) { + mag++; + } + var delta = mag * ds; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "DELTACFIX", c, "by", delta); + } + state.cvt[c] += delta; + } +} +function SROUND(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SROUND[]", n2); + } + state.round = roundSuper; + var period; + switch (n2 & 192) { + case 0: + period = 0.5; + break; + case 64: + period = 1; + break; + case 128: + period = 2; + break; + default: + throw new Error("invalid SROUND value"); + } + state.srPeriod = period; + switch (n2 & 48) { + case 0: + state.srPhase = 0; + break; + case 16: + state.srPhase = 0.25 * period; + break; + case 32: + state.srPhase = 0.5 * period; + break; + case 48: + state.srPhase = 0.75 * period; + break; + default: + throw new Error("invalid SROUND value"); + } + n2 &= 15; + if (n2 === 0) { + state.srThreshold = 0; + } else { + state.srThreshold = (n2 / 8 - 0.5) * period; + } +} +function S45ROUND(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "S45ROUND[]", n2); + } + state.round = roundSuper; + var period; + switch (n2 & 192) { + case 0: + period = Math.sqrt(2) / 2; + break; + case 64: + period = Math.sqrt(2); + break; + case 128: + period = 2 * Math.sqrt(2); + break; + default: + throw new Error("invalid S45ROUND value"); + } + state.srPeriod = period; + switch (n2 & 48) { + case 0: + state.srPhase = 0; + break; + case 16: + state.srPhase = 0.25 * period; + break; + case 32: + state.srPhase = 0.5 * period; + break; + case 48: + state.srPhase = 0.75 * period; + break; + default: + throw new Error("invalid S45ROUND value"); + } + n2 &= 15; + if (n2 === 0) { + state.srThreshold = 0; + } else { + state.srThreshold = (n2 / 8 - 0.5) * period; + } +} +function ROFF(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ROFF[]"); + } + state.round = roundOff; +} +function RUTG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RUTG[]"); + } + state.round = roundUpToGrid; +} +function RDTG(state) { + if (exports_opentype_module.DEBUG) { + console.log(state.step, "RDTG[]"); + } + state.round = roundDownToGrid; +} +function SCANCTRL(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SCANCTRL[]", n2); + } +} +function SDPVTL(a, state) { + var stack = state.stack; + var p2i = stack.pop(); + var p1i = stack.pop(); + var p2 = state.z2[p2i]; + var p1 = state.z1[p1i]; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SDPVTL[" + a + "]", p2i, p1i); + } + var dx; + var dy; + if (!a) { + dx = p1.x - p2.x; + dy = p1.y - p2.y; + } else { + dx = p2.y - p1.y; + dy = p1.x - p2.x; + } + state.dpv = getUnitVector(dx, dy); +} +function GETINFO(state) { + var stack = state.stack; + var sel = stack.pop(); + var r = 0; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "GETINFO[]", sel); + } + if (sel & 1) { + r = 35; + } + if (sel & 32) { + r |= 4096; + } + stack.push(r); +} +function ROLL(state) { + var stack = state.stack; + var a = stack.pop(); + var b = stack.pop(); + var c = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "ROLL[]"); + } + stack.push(b); + stack.push(a); + stack.push(c); +} +function MAX(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MAX[]", e2, e1); + } + stack.push(Math.max(e1, e2)); +} +function MIN(state) { + var stack = state.stack; + var e2 = stack.pop(); + var e1 = stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "MIN[]", e2, e1); + } + stack.push(Math.min(e1, e2)); +} +function SCANTYPE(state) { + var n2 = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "SCANTYPE[]", n2); + } +} +function INSTCTRL(state) { + var s = state.stack.pop(); + var v = state.stack.pop(); + if (exports_opentype_module.DEBUG) { + console.log(state.step, "INSTCTRL[]", s, v); + } + switch (s) { + case 1: + state.inhibitGridFit = !!v; + return; + case 2: + state.ignoreCvt = !!v; + return; + default: + throw new Error("invalid INSTCTRL[] selector"); + } +} +function PUSHB(n2, state) { + var stack = state.stack; + var prog = state.prog; + var ip = state.ip; + if (exports_opentype_module.DEBUG) { + console.log(state.step, "PUSHB[" + n2 + "]"); + } + for (var i = 0;i < n2; i++) { + stack.push(prog[++ip]); + } + state.ip = ip; +} +function PUSHW(n2, state) { + var ip = state.ip; + var prog = state.prog; + var stack = state.stack; + if (exports_opentype_module.DEBUG) { + console.log(state.ip, "PUSHW[" + n2 + "]"); + } + for (var i = 0;i < n2; i++) { + var w = prog[++ip] << 8 | prog[++ip]; + if (w & 32768) { + w = -((w ^ 65535) + 1); + } + stack.push(w); + } + state.ip = ip; +} +function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) { + var stack = state.stack; + var cvte = indirect && stack.pop(); + var pi2 = stack.pop(); + var rp0i = state.rp0; + var rp = state.z0[rp0i]; + var p = state.z1[pi2]; + var md = state.minDis; + var fv = state.fv; + var pv = state.dpv; + var od; + var d; + var sign2; + var cv; + d = od = pv.distance(p, rp, true, true); + sign2 = d >= 0 ? 1 : -1; + d = Math.abs(d); + if (indirect) { + cv = state.cvt[cvte]; + if (ro && Math.abs(d - cv) < state.cvCutIn) { + d = cv; + } + } + if (keepD && d < md) { + d = md; + } + if (ro) { + d = state.round(d); + } + fv.setRelative(p, rp, sign2 * d, pv); + fv.touch(p); + if (exports_opentype_module.DEBUG) { + console.log(state.step, (indirect ? "MIRP[" : "MDRP[") + (setRp0 ? "M" : "m") + (keepD ? ">" : "_") + (ro ? "R" : "_") + (dt === 0 ? "Gr" : dt === 1 ? "Bl" : dt === 2 ? "Wh" : "") + "]", indirect ? cvte + "(" + state.cvt[cvte] + "," + cv + ")" : "", pi2, "(d =", od, "->", sign2 * d, ")"); + } + state.rp1 = state.rp0; + state.rp2 = pi2; + if (setRp0) { + state.rp0 = pi2; + } +} +instructionTable = [ + SVTCA.bind(undefined, yUnitVector), + SVTCA.bind(undefined, xUnitVector), + SPVTCA.bind(undefined, yUnitVector), + SPVTCA.bind(undefined, xUnitVector), + SFVTCA.bind(undefined, yUnitVector), + SFVTCA.bind(undefined, xUnitVector), + SPVTL.bind(undefined, 0), + SPVTL.bind(undefined, 1), + SFVTL.bind(undefined, 0), + SFVTL.bind(undefined, 1), + SPVFS, + SFVFS, + GPV, + GFV, + SFVTPV, + ISECT, + SRP0, + SRP1, + SRP2, + SZP0, + SZP1, + SZP2, + SZPS, + SLOOP, + RTG, + RTHG, + SMD, + ELSE, + JMPR, + SCVTCI, + undefined, + undefined, + DUP, + POP, + CLEAR, + SWAP, + DEPTH, + CINDEX, + MINDEX, + undefined, + undefined, + undefined, + LOOPCALL, + CALL, + FDEF, + undefined, + MDAP.bind(undefined, 0), + MDAP.bind(undefined, 1), + IUP.bind(undefined, yUnitVector), + IUP.bind(undefined, xUnitVector), + SHP.bind(undefined, 0), + SHP.bind(undefined, 1), + SHC.bind(undefined, 0), + SHC.bind(undefined, 1), + SHZ.bind(undefined, 0), + SHZ.bind(undefined, 1), + SHPIX, + IP, + MSIRP.bind(undefined, 0), + MSIRP.bind(undefined, 1), + ALIGNRP, + RTDG, + MIAP.bind(undefined, 0), + MIAP.bind(undefined, 1), + NPUSHB, + NPUSHW, + WS, + RS, + WCVTP, + RCVT, + GC.bind(undefined, 0), + GC.bind(undefined, 1), + undefined, + MD.bind(undefined, 0), + MD.bind(undefined, 1), + MPPEM, + undefined, + FLIPON, + undefined, + undefined, + LT, + LTEQ, + GT, + GTEQ, + EQ, + NEQ, + ODD, + EVEN, + IF, + EIF, + AND, + OR, + NOT, + DELTAP123.bind(undefined, 1), + SDB, + SDS, + ADD, + SUB, + DIV, + MUL, + ABS, + NEG, + FLOOR, + CEILING, + ROUND.bind(undefined, 0), + ROUND.bind(undefined, 1), + ROUND.bind(undefined, 2), + ROUND.bind(undefined, 3), + undefined, + undefined, + undefined, + undefined, + WCVTF, + DELTAP123.bind(undefined, 2), + DELTAP123.bind(undefined, 3), + DELTAC123.bind(undefined, 1), + DELTAC123.bind(undefined, 2), + DELTAC123.bind(undefined, 3), + SROUND, + S45ROUND, + undefined, + undefined, + ROFF, + undefined, + RUTG, + RDTG, + POP, + POP, + undefined, + undefined, + undefined, + undefined, + undefined, + SCANCTRL, + SDPVTL.bind(undefined, 0), + SDPVTL.bind(undefined, 1), + GETINFO, + undefined, + ROLL, + MAX, + MIN, + SCANTYPE, + INSTCTRL, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + PUSHB.bind(undefined, 1), + PUSHB.bind(undefined, 2), + PUSHB.bind(undefined, 3), + PUSHB.bind(undefined, 4), + PUSHB.bind(undefined, 5), + PUSHB.bind(undefined, 6), + PUSHB.bind(undefined, 7), + PUSHB.bind(undefined, 8), + PUSHW.bind(undefined, 1), + PUSHW.bind(undefined, 2), + PUSHW.bind(undefined, 3), + PUSHW.bind(undefined, 4), + PUSHW.bind(undefined, 5), + PUSHW.bind(undefined, 6), + PUSHW.bind(undefined, 7), + PUSHW.bind(undefined, 8), + MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 0), + MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 1), + MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 2), + MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 3), + MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 0), + MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 1), + MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 2), + MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 3), + MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 0), + MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 1), + MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 2), + MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 3), + MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 0), + MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 1), + MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 2), + MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 3), + MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 0), + MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 1), + MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 2), + MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 3), + MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 0), + MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 1), + MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 2), + MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 3), + MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 0), + MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 1), + MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 2), + MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 3), + MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 0), + MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 1), + MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 2), + MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 3), + MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 0), + MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 1), + MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 2), + MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 3), + MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 0), + MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 1), + MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 2), + MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 3), + MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 0), + MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 1), + MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 2), + MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 3), + MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 0), + MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 1), + MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 2), + MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 3), + MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 0), + MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 1), + MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 2), + MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 3), + MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 0), + MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 1), + MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 2), + MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 3), + MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 0), + MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 1), + MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 2), + MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 3), + MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 0), + MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 1), + MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 2), + MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 3) +]; +function Token(char) { + this.char = char; + this.state = {}; + this.activeState = null; +} +function ContextRange(startIndex, endOffset, contextName) { + this.contextName = contextName; + this.startIndex = startIndex; + this.endOffset = endOffset; +} +function ContextChecker(contextName, checkStart, checkEnd) { + this.contextName = contextName; + this.openRange = null; + this.ranges = []; + this.checkStart = checkStart; + this.checkEnd = checkEnd; +} +function ContextParams(context, currentIndex) { + this.context = context; + this.index = currentIndex; + this.length = context.length; + this.current = context[currentIndex]; + this.backtrack = context.slice(0, currentIndex); + this.lookahead = context.slice(currentIndex + 1); +} +function Event(eventId) { + this.eventId = eventId; + this.subscribers = []; +} +function initializeCoreEvents(events) { + var this$1 = this; + var coreEvents = [ + "start", + "end", + "next", + "newToken", + "contextStart", + "contextEnd", + "insertToken", + "removeToken", + "removeRange", + "replaceToken", + "replaceRange", + "composeRUD", + "updateContextsRanges" + ]; + coreEvents.forEach(function(eventId) { + Object.defineProperty(this$1.events, eventId, { + value: new Event(eventId) + }); + }); + if (!!events) { + coreEvents.forEach(function(eventId) { + var event = events[eventId]; + if (typeof event === "function") { + this$1.events[eventId].subscribe(event); + } + }); + } + var requiresContextUpdate = [ + "insertToken", + "removeToken", + "removeRange", + "replaceToken", + "replaceRange", + "composeRUD" + ]; + requiresContextUpdate.forEach(function(eventId) { + this$1.events[eventId].subscribe(this$1.updateContextsRanges); + }); +} +function Tokenizer(events) { + this.tokens = []; + this.registeredContexts = {}; + this.contextCheckers = []; + this.events = {}; + this.registeredModifiers = []; + initializeCoreEvents.call(this, events); +} +Token.prototype.setState = function(key2, value2) { + this.state[key2] = value2; + this.activeState = { key: key2, value: this.state[key2] }; + return this.activeState; +}; +Token.prototype.getState = function(stateId) { + return this.state[stateId] || null; +}; +Tokenizer.prototype.inboundIndex = function(index2) { + return index2 >= 0 && index2 < this.tokens.length; +}; +Tokenizer.prototype.composeRUD = function(RUDs) { + var this$1 = this; + var silent = true; + var state = RUDs.map(function(RUD) { + return this$1[RUD[0]].apply(this$1, RUD.slice(1).concat(silent)); + }); + var hasFAILObject = function(obj) { + return typeof obj === "object" && obj.hasOwnProperty("FAIL"); + }; + if (state.every(hasFAILObject)) { + return { + FAIL: "composeRUD: one or more operations hasn't completed successfully", + report: state.filter(hasFAILObject) + }; + } + this.dispatch("composeRUD", [state.filter(function(op) { + return !hasFAILObject(op); + })]); +}; +Tokenizer.prototype.replaceRange = function(startIndex, offset, tokens, silent) { + offset = offset !== null ? offset : this.tokens.length; + var isTokenType = tokens.every(function(token) { + return token instanceof Token; + }); + if (!isNaN(startIndex) && this.inboundIndex(startIndex) && isTokenType) { + var replaced = this.tokens.splice.apply(this.tokens, [startIndex, offset].concat(tokens)); + if (!silent) { + this.dispatch("replaceToken", [startIndex, offset, tokens]); + } + return [replaced, tokens]; + } else { + return { FAIL: "replaceRange: invalid tokens or startIndex." }; + } +}; +Tokenizer.prototype.replaceToken = function(index2, token, silent) { + if (!isNaN(index2) && this.inboundIndex(index2) && token instanceof Token) { + var replaced = this.tokens.splice(index2, 1, token); + if (!silent) { + this.dispatch("replaceToken", [index2, token]); + } + return [replaced[0], token]; + } else { + return { FAIL: "replaceToken: invalid token or index." }; + } +}; +Tokenizer.prototype.removeRange = function(startIndex, offset, silent) { + offset = !isNaN(offset) ? offset : this.tokens.length; + var tokens = this.tokens.splice(startIndex, offset); + if (!silent) { + this.dispatch("removeRange", [tokens, startIndex, offset]); + } + return tokens; +}; +Tokenizer.prototype.removeToken = function(index2, silent) { + if (!isNaN(index2) && this.inboundIndex(index2)) { + var token = this.tokens.splice(index2, 1); + if (!silent) { + this.dispatch("removeToken", [token, index2]); + } + return token; + } else { + return { FAIL: "removeToken: invalid token index." }; + } +}; +Tokenizer.prototype.insertToken = function(tokens, index2, silent) { + var tokenType = tokens.every(function(token) { + return token instanceof Token; + }); + if (tokenType) { + this.tokens.splice.apply(this.tokens, [index2, 0].concat(tokens)); + if (!silent) { + this.dispatch("insertToken", [tokens, index2]); + } + return tokens; + } else { + return { FAIL: "insertToken: invalid token(s)." }; + } +}; +Tokenizer.prototype.registerModifier = function(modifierId, condition, modifier) { + this.events.newToken.subscribe(function(token, contextParams) { + var conditionParams = [token, contextParams]; + var canApplyModifier = condition === null || condition.apply(this, conditionParams) === true; + var modifierParams = [token, contextParams]; + if (canApplyModifier) { + var newStateValue = modifier.apply(this, modifierParams); + token.setState(modifierId, newStateValue); + } + }); + this.registeredModifiers.push(modifierId); +}; +Event.prototype.subscribe = function(eventHandler) { + if (typeof eventHandler === "function") { + return this.subscribers.push(eventHandler) - 1; + } else { + return { FAIL: "invalid '" + this.eventId + "' event handler" }; + } +}; +Event.prototype.unsubscribe = function(subsId) { + this.subscribers.splice(subsId, 1); +}; +ContextParams.prototype.setCurrentIndex = function(index2) { + this.index = index2; + this.current = this.context[index2]; + this.backtrack = this.context.slice(0, index2); + this.lookahead = this.context.slice(index2 + 1); +}; +ContextParams.prototype.get = function(offset) { + switch (true) { + case offset === 0: + return this.current; + case (offset < 0 && Math.abs(offset) <= this.backtrack.length): + return this.backtrack.slice(offset)[0]; + case (offset > 0 && offset <= this.lookahead.length): + return this.lookahead[offset - 1]; + default: + return null; + } +}; +Tokenizer.prototype.rangeToText = function(range) { + if (range instanceof ContextRange) { + return this.getRangeTokens(range).map(function(token) { + return token.char; + }).join(""); + } +}; +Tokenizer.prototype.getText = function() { + return this.tokens.map(function(token) { + return token.char; + }).join(""); +}; +Tokenizer.prototype.getContext = function(contextName) { + var context = this.registeredContexts[contextName]; + return context ? context : null; +}; +Tokenizer.prototype.on = function(eventName, eventHandler) { + var event = this.events[eventName]; + if (!!event) { + return event.subscribe(eventHandler); + } else { + return null; + } +}; +Tokenizer.prototype.dispatch = function(eventName, args) { + var this$1 = this; + var event = this.events[eventName]; + if (event instanceof Event) { + event.subscribers.forEach(function(subscriber) { + subscriber.apply(this$1, args || []); + }); + } +}; +Tokenizer.prototype.registerContextChecker = function(contextName, contextStartCheck, contextEndCheck) { + if (!!this.getContext(contextName)) { + return { + FAIL: "context name '" + contextName + "' is already registered." + }; + } + if (typeof contextStartCheck !== "function") { + return { + FAIL: "missing context start check." + }; + } + if (typeof contextEndCheck !== "function") { + return { + FAIL: "missing context end check." + }; + } + var contextCheckers = new ContextChecker(contextName, contextStartCheck, contextEndCheck); + this.registeredContexts[contextName] = contextCheckers; + this.contextCheckers.push(contextCheckers); + return contextCheckers; +}; +Tokenizer.prototype.getRangeTokens = function(range) { + var endIndex = range.startIndex + range.endOffset; + return [].concat(this.tokens.slice(range.startIndex, endIndex)); +}; +Tokenizer.prototype.getContextRanges = function(contextName) { + var context = this.getContext(contextName); + if (!!context) { + return context.ranges; + } else { + return { FAIL: "context checker '" + contextName + "' is not registered." }; + } +}; +Tokenizer.prototype.resetContextsRanges = function() { + var registeredContexts = this.registeredContexts; + for (var contextName in registeredContexts) { + if (registeredContexts.hasOwnProperty(contextName)) { + var context = registeredContexts[contextName]; + context.ranges = []; + } + } +}; +Tokenizer.prototype.updateContextsRanges = function() { + this.resetContextsRanges(); + var chars = this.tokens.map(function(token) { + return token.char; + }); + for (var i = 0;i < chars.length; i++) { + var contextParams = new ContextParams(chars, i); + this.runContextCheck(contextParams); + } + this.dispatch("updateContextsRanges", [this.registeredContexts]); +}; +Tokenizer.prototype.setEndOffset = function(offset, contextName) { + var startIndex = this.getContext(contextName).openRange.startIndex; + var range = new ContextRange(startIndex, offset, contextName); + var ranges = this.getContext(contextName).ranges; + range.rangeId = contextName + "." + ranges.length; + ranges.push(range); + this.getContext(contextName).openRange = null; + return range; +}; +Tokenizer.prototype.runContextCheck = function(contextParams) { + var this$1 = this; + var index2 = contextParams.index; + this.contextCheckers.forEach(function(contextChecker) { + var contextName = contextChecker.contextName; + var openRange = this$1.getContext(contextName).openRange; + if (!openRange && contextChecker.checkStart(contextParams)) { + openRange = new ContextRange(index2, null, contextName); + this$1.getContext(contextName).openRange = openRange; + this$1.dispatch("contextStart", [contextName, index2]); + } + if (!!openRange && contextChecker.checkEnd(contextParams)) { + var offset = index2 - openRange.startIndex + 1; + var range = this$1.setEndOffset(offset, contextName); + this$1.dispatch("contextEnd", [contextName, range]); + } + }); +}; +Tokenizer.prototype.tokenize = function(text2) { + this.tokens = []; + this.resetContextsRanges(); + var chars = Array.from(text2); + this.dispatch("start"); + for (var i = 0;i < chars.length; i++) { + var char = chars[i]; + var contextParams = new ContextParams(chars, i); + this.dispatch("next", [contextParams]); + this.runContextCheck(contextParams); + var token = new Token(char); + this.tokens.push(token); + this.dispatch("newToken", [token, contextParams]); + } + this.dispatch("end", [this.tokens]); + return this.tokens; +}; +function isArabicChar(c) { + return /[\u0600-\u065F\u066A-\u06D2\u06FA-\u06FF]/.test(c); +} +function isIsolatedArabicChar(char) { + return /[\u0630\u0690\u0621\u0631\u0661\u0671\u0622\u0632\u0672\u0692\u06C2\u0623\u0673\u0693\u06C3\u0624\u0694\u06C4\u0625\u0675\u0695\u06C5\u06E5\u0676\u0696\u06C6\u0627\u0677\u0697\u06C7\u0648\u0688\u0698\u06C8\u0689\u0699\u06C9\u068A\u06CA\u066B\u068B\u06CB\u068C\u068D\u06CD\u06FD\u068E\u06EE\u06FE\u062F\u068F\u06CF\u06EF]/.test(char); +} +function isTashkeelArabicChar(char) { + return /[\u0600-\u0605\u060C-\u060E\u0610-\u061B\u061E\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED]/.test(char); +} +function isLatinChar(c) { + return /[A-z]/.test(c); +} +function isWhiteSpace(c) { + return /\s/.test(c); +} +function FeatureQuery(font) { + this.font = font; + this.features = {}; +} +function SubstitutionAction(action) { + this.id = action.id; + this.tag = action.tag; + this.substitution = action.substitution; +} +function lookupCoverage(glyphIndex, coverage) { + if (!glyphIndex) { + return -1; + } + switch (coverage.format) { + case 1: + return coverage.glyphs.indexOf(glyphIndex); + case 2: + var ranges = coverage.ranges; + for (var i = 0;i < ranges.length; i++) { + var range = ranges[i]; + if (glyphIndex >= range.start && glyphIndex <= range.end) { + var offset = glyphIndex - range.start; + return range.index + offset; + } + } + break; + default: + return -1; + } + return -1; +} +function singleSubstitutionFormat1(glyphIndex, subtable) { + var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (substituteIndex === -1) { + return null; + } + return glyphIndex + subtable.deltaGlyphId; +} +function singleSubstitutionFormat2(glyphIndex, subtable) { + var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (substituteIndex === -1) { + return null; + } + return subtable.substitute[substituteIndex]; +} +function lookupCoverageList(coverageList, contextParams) { + var lookupList = []; + for (var i = 0;i < coverageList.length; i++) { + var coverage = coverageList[i]; + var glyphIndex = contextParams.current; + glyphIndex = Array.isArray(glyphIndex) ? glyphIndex[0] : glyphIndex; + var lookupIndex = lookupCoverage(glyphIndex, coverage); + if (lookupIndex !== -1) { + lookupList.push(lookupIndex); + } + } + if (lookupList.length !== coverageList.length) { + return -1; + } + return lookupList; +} +function chainingSubstitutionFormat3(contextParams, subtable) { + var lookupsCount = subtable.inputCoverage.length + subtable.lookaheadCoverage.length + subtable.backtrackCoverage.length; + if (contextParams.context.length < lookupsCount) { + return []; + } + var inputLookups = lookupCoverageList(subtable.inputCoverage, contextParams); + if (inputLookups === -1) { + return []; + } + var lookaheadOffset = subtable.inputCoverage.length - 1; + if (contextParams.lookahead.length < subtable.lookaheadCoverage.length) { + return []; + } + var lookaheadContext = contextParams.lookahead.slice(lookaheadOffset); + while (lookaheadContext.length && isTashkeelArabicChar(lookaheadContext[0].char)) { + lookaheadContext.shift(); + } + var lookaheadParams = new ContextParams(lookaheadContext, 0); + var lookaheadLookups = lookupCoverageList(subtable.lookaheadCoverage, lookaheadParams); + var backtrackContext = [].concat(contextParams.backtrack); + backtrackContext.reverse(); + while (backtrackContext.length && isTashkeelArabicChar(backtrackContext[0].char)) { + backtrackContext.shift(); + } + if (backtrackContext.length < subtable.backtrackCoverage.length) { + return []; + } + var backtrackParams = new ContextParams(backtrackContext, 0); + var backtrackLookups = lookupCoverageList(subtable.backtrackCoverage, backtrackParams); + var contextRulesMatch = inputLookups.length === subtable.inputCoverage.length && lookaheadLookups.length === subtable.lookaheadCoverage.length && backtrackLookups.length === subtable.backtrackCoverage.length; + var substitutions = []; + if (contextRulesMatch) { + for (var i = 0;i < subtable.lookupRecords.length; i++) { + var lookupRecord = subtable.lookupRecords[i]; + var lookupListIndex = lookupRecord.lookupListIndex; + var lookupTable = this.getLookupByIndex(lookupListIndex); + for (var s = 0;s < lookupTable.subtables.length; s++) { + var subtable$1 = lookupTable.subtables[s]; + var lookup = this.getLookupMethod(lookupTable, subtable$1); + var substitutionType = this.getSubstitutionType(lookupTable, subtable$1); + if (substitutionType === "12") { + for (var n2 = 0;n2 < inputLookups.length; n2++) { + var glyphIndex = contextParams.get(n2); + var substitution = lookup(glyphIndex); + if (substitution) { + substitutions.push(substitution); + } + } + } + } + } + } + return substitutions; +} +function ligatureSubstitutionFormat1(contextParams, subtable) { + var glyphIndex = contextParams.current; + var ligSetIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (ligSetIndex === -1) { + return null; + } + var ligature; + var ligatureSet = subtable.ligatureSets[ligSetIndex]; + for (var s = 0;s < ligatureSet.length; s++) { + ligature = ligatureSet[s]; + for (var l2 = 0;l2 < ligature.components.length; l2++) { + var lookaheadItem = contextParams.lookahead[l2]; + var component = ligature.components[l2]; + if (lookaheadItem !== component) { + break; + } + if (l2 === ligature.components.length - 1) { + return ligature; + } + } + } + return null; +} +function decompositionSubstitutionFormat1(glyphIndex, subtable) { + var substituteIndex = lookupCoverage(glyphIndex, subtable.coverage); + if (substituteIndex === -1) { + return null; + } + return subtable.sequences[substituteIndex]; +} +FeatureQuery.prototype.getDefaultScriptFeaturesIndexes = function() { + var scripts = this.font.tables.gsub.scripts; + for (var s = 0;s < scripts.length; s++) { + var script = scripts[s]; + if (script.tag === "DFLT") { + return script.script.defaultLangSys.featureIndexes; + } + } + return []; +}; +FeatureQuery.prototype.getScriptFeaturesIndexes = function(scriptTag) { + var tables = this.font.tables; + if (!tables.gsub) { + return []; + } + if (!scriptTag) { + return this.getDefaultScriptFeaturesIndexes(); + } + var scripts = this.font.tables.gsub.scripts; + for (var i = 0;i < scripts.length; i++) { + var script = scripts[i]; + if (script.tag === scriptTag && script.script.defaultLangSys) { + return script.script.defaultLangSys.featureIndexes; + } else { + var langSysRecords = script.langSysRecords; + if (!!langSysRecords) { + for (var j2 = 0;j2 < langSysRecords.length; j2++) { + var langSysRecord = langSysRecords[j2]; + if (langSysRecord.tag === scriptTag) { + var langSys = langSysRecord.langSys; + return langSys.featureIndexes; + } + } + } + } + } + return this.getDefaultScriptFeaturesIndexes(); +}; +FeatureQuery.prototype.mapTagsToFeatures = function(features, scriptTag) { + var tags = {}; + for (var i = 0;i < features.length; i++) { + var tag = features[i].tag; + var feature = features[i].feature; + tags[tag] = feature; + } + this.features[scriptTag].tags = tags; +}; +FeatureQuery.prototype.getScriptFeatures = function(scriptTag) { + var features = this.features[scriptTag]; + if (this.features.hasOwnProperty(scriptTag)) { + return features; + } + var featuresIndexes = this.getScriptFeaturesIndexes(scriptTag); + if (!featuresIndexes) { + return null; + } + var gsub2 = this.font.tables.gsub; + features = featuresIndexes.map(function(index2) { + return gsub2.features[index2]; + }); + this.features[scriptTag] = features; + this.mapTagsToFeatures(features, scriptTag); + return features; +}; +FeatureQuery.prototype.getSubstitutionType = function(lookupTable, subtable) { + var lookupType = lookupTable.lookupType.toString(); + var substFormat = subtable.substFormat.toString(); + return lookupType + substFormat; +}; +FeatureQuery.prototype.getLookupMethod = function(lookupTable, subtable) { + var this$1 = this; + var substitutionType = this.getSubstitutionType(lookupTable, subtable); + switch (substitutionType) { + case "11": + return function(glyphIndex) { + return singleSubstitutionFormat1.apply(this$1, [glyphIndex, subtable]); + }; + case "12": + return function(glyphIndex) { + return singleSubstitutionFormat2.apply(this$1, [glyphIndex, subtable]); + }; + case "63": + return function(contextParams) { + return chainingSubstitutionFormat3.apply(this$1, [contextParams, subtable]); + }; + case "41": + return function(contextParams) { + return ligatureSubstitutionFormat1.apply(this$1, [contextParams, subtable]); + }; + case "21": + return function(glyphIndex) { + return decompositionSubstitutionFormat1.apply(this$1, [glyphIndex, subtable]); + }; + default: + throw new Error("lookupType: " + lookupTable.lookupType + " - " + "substFormat: " + subtable.substFormat + " " + "is not yet supported"); + } +}; +FeatureQuery.prototype.lookupFeature = function(query) { + var contextParams = query.contextParams; + var currentIndex = contextParams.index; + var feature = this.getFeature({ + tag: query.tag, + script: query.script + }); + if (!feature) { + return new Error("font '" + this.font.names.fullName.en + "' " + "doesn't support feature '" + query.tag + "' " + "for script '" + query.script + "'."); + } + var lookups = this.getFeatureLookups(feature); + var substitutions = [].concat(contextParams.context); + for (var l2 = 0;l2 < lookups.length; l2++) { + var lookupTable = lookups[l2]; + var subtables = this.getLookupSubtables(lookupTable); + for (var s = 0;s < subtables.length; s++) { + var subtable = subtables[s]; + var substType = this.getSubstitutionType(lookupTable, subtable); + var lookup = this.getLookupMethod(lookupTable, subtable); + var substitution = undefined; + switch (substType) { + case "11": + substitution = lookup(contextParams.current); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 11, + tag: query.tag, + substitution + })); + } + break; + case "12": + substitution = lookup(contextParams.current); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 12, + tag: query.tag, + substitution + })); + } + break; + case "63": + substitution = lookup(contextParams); + if (Array.isArray(substitution) && substitution.length) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 63, + tag: query.tag, + substitution + })); + } + break; + case "41": + substitution = lookup(contextParams); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 41, + tag: query.tag, + substitution + })); + } + break; + case "21": + substitution = lookup(contextParams.current); + if (substitution) { + substitutions.splice(currentIndex, 1, new SubstitutionAction({ + id: 21, + tag: query.tag, + substitution + })); + } + break; + } + contextParams = new ContextParams(substitutions, currentIndex); + if (Array.isArray(substitution) && !substitution.length) { + continue; + } + substitution = null; + } + } + return substitutions.length ? substitutions : null; +}; +FeatureQuery.prototype.supports = function(query) { + if (!query.script) { + return false; + } + this.getScriptFeatures(query.script); + var supportedScript = this.features.hasOwnProperty(query.script); + if (!query.tag) { + return supportedScript; + } + var supportedFeature = this.features[query.script].some(function(feature) { + return feature.tag === query.tag; + }); + return supportedScript && supportedFeature; +}; +FeatureQuery.prototype.getLookupSubtables = function(lookupTable) { + return lookupTable.subtables || null; +}; +FeatureQuery.prototype.getLookupByIndex = function(index2) { + var lookups = this.font.tables.gsub.lookups; + return lookups[index2] || null; +}; +FeatureQuery.prototype.getFeatureLookups = function(feature) { + return feature.lookupListIndexes.map(this.getLookupByIndex.bind(this)); +}; +FeatureQuery.prototype.getFeature = function getFeature(query) { + if (!this.font) { + return { FAIL: "No font was found" }; + } + if (!this.features.hasOwnProperty(query.script)) { + this.getScriptFeatures(query.script); + } + var scriptFeatures = this.features[query.script]; + if (!scriptFeatures) { + return { FAIL: "No feature for script " + query.script }; + } + if (!scriptFeatures.tags[query.tag]) { + return null; + } + return this.features[query.script].tags[query.tag]; +}; +function arabicWordStartCheck(contextParams) { + var char = contextParams.current; + var prevChar = contextParams.get(-1); + return prevChar === null && isArabicChar(char) || !isArabicChar(prevChar) && isArabicChar(char); +} +function arabicWordEndCheck(contextParams) { + var nextChar = contextParams.get(1); + return nextChar === null || !isArabicChar(nextChar); +} +var arabicWordCheck = { + startCheck: arabicWordStartCheck, + endCheck: arabicWordEndCheck +}; +function arabicSentenceStartCheck(contextParams) { + var char = contextParams.current; + var prevChar = contextParams.get(-1); + return (isArabicChar(char) || isTashkeelArabicChar(char)) && !isArabicChar(prevChar); +} +function arabicSentenceEndCheck(contextParams) { + var nextChar = contextParams.get(1); + switch (true) { + case nextChar === null: + return true; + case (!isArabicChar(nextChar) && !isTashkeelArabicChar(nextChar)): + var nextIsWhitespace = isWhiteSpace(nextChar); + if (!nextIsWhitespace) { + return true; + } + if (nextIsWhitespace) { + var arabicCharAhead = false; + arabicCharAhead = contextParams.lookahead.some(function(c) { + return isArabicChar(c) || isTashkeelArabicChar(c); + }); + if (!arabicCharAhead) { + return true; + } + } + break; + default: + return false; + } +} +var arabicSentenceCheck = { + startCheck: arabicSentenceStartCheck, + endCheck: arabicSentenceEndCheck +}; +function singleSubstitutionFormat1$1(action, tokens, index2) { + tokens[index2].setState(action.tag, action.substitution); +} +function singleSubstitutionFormat2$1(action, tokens, index2) { + tokens[index2].setState(action.tag, action.substitution); +} +function chainingSubstitutionFormat3$1(action, tokens, index2) { + action.substitution.forEach(function(subst, offset) { + var token = tokens[index2 + offset]; + token.setState(action.tag, subst); + }); +} +function ligatureSubstitutionFormat1$1(action, tokens, index2) { + var token = tokens[index2]; + token.setState(action.tag, action.substitution.ligGlyph); + var compsCount = action.substitution.components.length; + for (var i = 0;i < compsCount; i++) { + token = tokens[index2 + i + 1]; + token.setState("deleted", true); + } +} +var SUBSTITUTIONS = { + 11: singleSubstitutionFormat1$1, + 12: singleSubstitutionFormat2$1, + 63: chainingSubstitutionFormat3$1, + 41: ligatureSubstitutionFormat1$1 +}; +function applySubstitution(action, tokens, index2) { + if (action instanceof SubstitutionAction && SUBSTITUTIONS[action.id]) { + SUBSTITUTIONS[action.id](action, tokens, index2); + } +} +function willConnectPrev(charContextParams) { + var backtrack = [].concat(charContextParams.backtrack); + for (var i = backtrack.length - 1;i >= 0; i--) { + var prevChar = backtrack[i]; + var isolated = isIsolatedArabicChar(prevChar); + var tashkeel = isTashkeelArabicChar(prevChar); + if (!isolated && !tashkeel) { + return true; + } + if (isolated) { + return false; + } + } + return false; +} +function willConnectNext(charContextParams) { + if (isIsolatedArabicChar(charContextParams.current)) { + return false; + } + for (var i = 0;i < charContextParams.lookahead.length; i++) { + var nextChar = charContextParams.lookahead[i]; + var tashkeel = isTashkeelArabicChar(nextChar); + if (!tashkeel) { + return true; + } + } + return false; +} +function arabicPresentationForms(range) { + var this$1 = this; + var script = "arab"; + var tags = this.featuresTags[script]; + var tokens = this.tokenizer.getRangeTokens(range); + if (tokens.length === 1) { + return; + } + var contextParams = new ContextParams(tokens.map(function(token) { + return token.getState("glyphIndex"); + }), 0); + var charContextParams = new ContextParams(tokens.map(function(token) { + return token.char; + }), 0); + tokens.forEach(function(token, index2) { + if (isTashkeelArabicChar(token.char)) { + return; + } + contextParams.setCurrentIndex(index2); + charContextParams.setCurrentIndex(index2); + var CONNECT = 0; + if (willConnectPrev(charContextParams)) { + CONNECT |= 1; + } + if (willConnectNext(charContextParams)) { + CONNECT |= 2; + } + var tag; + switch (CONNECT) { + case 1: + tag = "fina"; + break; + case 2: + tag = "init"; + break; + case 3: + tag = "medi"; + break; + } + if (tags.indexOf(tag) === -1) { + return; + } + var substitutions = this$1.query.lookupFeature({ + tag, + script, + contextParams + }); + if (substitutions instanceof Error) { + return console.info(substitutions.message); + } + substitutions.forEach(function(action, index3) { + if (action instanceof SubstitutionAction) { + applySubstitution(action, tokens, index3); + contextParams.context[index3] = action.substitution; + } + }); + }); +} +function getContextParams(tokens, index2) { + var context = tokens.map(function(token) { + return token.activeState.value; + }); + return new ContextParams(context, index2 || 0); +} +function arabicRequiredLigatures(range) { + var this$1 = this; + var script = "arab"; + var tokens = this.tokenizer.getRangeTokens(range); + var contextParams = getContextParams(tokens); + contextParams.context.forEach(function(glyphIndex, index2) { + contextParams.setCurrentIndex(index2); + var substitutions = this$1.query.lookupFeature({ + tag: "rlig", + script, + contextParams + }); + if (substitutions.length) { + substitutions.forEach(function(action) { + return applySubstitution(action, tokens, index2); + }); + contextParams = getContextParams(tokens); + } + }); +} +function latinWordStartCheck(contextParams) { + var char = contextParams.current; + var prevChar = contextParams.get(-1); + return prevChar === null && isLatinChar(char) || !isLatinChar(prevChar) && isLatinChar(char); +} +function latinWordEndCheck(contextParams) { + var nextChar = contextParams.get(1); + return nextChar === null || !isLatinChar(nextChar); +} +var latinWordCheck = { + startCheck: latinWordStartCheck, + endCheck: latinWordEndCheck +}; +function getContextParams$1(tokens, index2) { + var context = tokens.map(function(token) { + return token.activeState.value; + }); + return new ContextParams(context, index2 || 0); +} +function latinLigature(range) { + var this$1 = this; + var script = "latn"; + var tokens = this.tokenizer.getRangeTokens(range); + var contextParams = getContextParams$1(tokens); + contextParams.context.forEach(function(glyphIndex, index2) { + contextParams.setCurrentIndex(index2); + var substitutions = this$1.query.lookupFeature({ + tag: "liga", + script, + contextParams + }); + if (substitutions.length) { + substitutions.forEach(function(action) { + return applySubstitution(action, tokens, index2); + }); + contextParams = getContextParams$1(tokens); + } + }); +} +function Bidi(baseDir) { + this.baseDir = baseDir || "ltr"; + this.tokenizer = new Tokenizer; + this.featuresTags = {}; +} +Bidi.prototype.setText = function(text2) { + this.text = text2; +}; +Bidi.prototype.contextChecks = { + latinWordCheck, + arabicWordCheck, + arabicSentenceCheck +}; +function registerContextChecker(checkId) { + var check2 = this.contextChecks[checkId + "Check"]; + return this.tokenizer.registerContextChecker(checkId, check2.startCheck, check2.endCheck); +} +function tokenizeText() { + registerContextChecker.call(this, "latinWord"); + registerContextChecker.call(this, "arabicWord"); + registerContextChecker.call(this, "arabicSentence"); + return this.tokenizer.tokenize(this.text); +} +function reverseArabicSentences() { + var this$1 = this; + var ranges = this.tokenizer.getContextRanges("arabicSentence"); + ranges.forEach(function(range) { + var rangeTokens = this$1.tokenizer.getRangeTokens(range); + this$1.tokenizer.replaceRange(range.startIndex, range.endOffset, rangeTokens.reverse()); + }); +} +Bidi.prototype.registerFeatures = function(script, tags) { + var this$1 = this; + var supportedTags = tags.filter(function(tag) { + return this$1.query.supports({ script, tag }); + }); + if (!this.featuresTags.hasOwnProperty(script)) { + this.featuresTags[script] = supportedTags; + } else { + this.featuresTags[script] = this.featuresTags[script].concat(supportedTags); + } +}; +Bidi.prototype.applyFeatures = function(font, features) { + if (!font) { + throw new Error("No valid font was provided to apply features"); + } + if (!this.query) { + this.query = new FeatureQuery(font); + } + for (var f = 0;f < features.length; f++) { + var feature = features[f]; + if (!this.query.supports({ script: feature.script })) { + continue; + } + this.registerFeatures(feature.script, feature.tags); + } +}; +Bidi.prototype.registerModifier = function(modifierId, condition, modifier) { + this.tokenizer.registerModifier(modifierId, condition, modifier); +}; +function checkGlyphIndexStatus() { + if (this.tokenizer.registeredModifiers.indexOf("glyphIndex") === -1) { + throw new Error("glyphIndex modifier is required to apply " + "arabic presentation features."); + } +} +function applyArabicPresentationForms() { + var this$1 = this; + var script = "arab"; + if (!this.featuresTags.hasOwnProperty(script)) { + return; + } + checkGlyphIndexStatus.call(this); + var ranges = this.tokenizer.getContextRanges("arabicWord"); + ranges.forEach(function(range) { + arabicPresentationForms.call(this$1, range); + }); +} +function applyArabicRequireLigatures() { + var this$1 = this; + var script = "arab"; + if (!this.featuresTags.hasOwnProperty(script)) { + return; + } + var tags = this.featuresTags[script]; + if (tags.indexOf("rlig") === -1) { + return; + } + checkGlyphIndexStatus.call(this); + var ranges = this.tokenizer.getContextRanges("arabicWord"); + ranges.forEach(function(range) { + arabicRequiredLigatures.call(this$1, range); + }); +} +function applyLatinLigatures() { + var this$1 = this; + var script = "latn"; + if (!this.featuresTags.hasOwnProperty(script)) { + return; + } + var tags = this.featuresTags[script]; + if (tags.indexOf("liga") === -1) { + return; + } + checkGlyphIndexStatus.call(this); + var ranges = this.tokenizer.getContextRanges("latinWord"); + ranges.forEach(function(range) { + latinLigature.call(this$1, range); + }); +} +Bidi.prototype.checkContextReady = function(contextId) { + return !!this.tokenizer.getContext(contextId); +}; +Bidi.prototype.applyFeaturesToContexts = function() { + if (this.checkContextReady("arabicWord")) { + applyArabicPresentationForms.call(this); + applyArabicRequireLigatures.call(this); + } + if (this.checkContextReady("latinWord")) { + applyLatinLigatures.call(this); + } + if (this.checkContextReady("arabicSentence")) { + reverseArabicSentences.call(this); + } +}; +Bidi.prototype.processText = function(text2) { + if (!this.text || this.text !== text2) { + this.setText(text2); + tokenizeText.call(this); + this.applyFeaturesToContexts(); + } +}; +Bidi.prototype.getBidiText = function(text2) { + this.processText(text2); + return this.tokenizer.getText(); +}; +Bidi.prototype.getTextGlyphs = function(text2) { + this.processText(text2); + var indexes = []; + for (var i = 0;i < this.tokenizer.tokens.length; i++) { + var token = this.tokenizer.tokens[i]; + if (token.state.deleted) { + continue; + } + var index2 = token.activeState.value; + indexes.push(Array.isArray(index2) ? index2[0] : index2); + } + return indexes; +}; +function Font(options) { + options = options || {}; + options.tables = options.tables || {}; + if (!options.empty) { + checkArgument(options.familyName, "When creating a new Font object, familyName is required."); + checkArgument(options.styleName, "When creating a new Font object, styleName is required."); + checkArgument(options.unitsPerEm, "When creating a new Font object, unitsPerEm is required."); + checkArgument(options.ascender, "When creating a new Font object, ascender is required."); + checkArgument(options.descender <= 0, "When creating a new Font object, negative descender value is required."); + this.names = { + fontFamily: { en: options.familyName || " " }, + fontSubfamily: { en: options.styleName || " " }, + fullName: { en: options.fullName || options.familyName + " " + options.styleName }, + postScriptName: { en: options.postScriptName || (options.familyName + options.styleName).replace(/\s/g, "") }, + designer: { en: options.designer || " " }, + designerURL: { en: options.designerURL || " " }, + manufacturer: { en: options.manufacturer || " " }, + manufacturerURL: { en: options.manufacturerURL || " " }, + license: { en: options.license || " " }, + licenseURL: { en: options.licenseURL || " " }, + version: { en: options.version || "Version 0.1" }, + description: { en: options.description || " " }, + copyright: { en: options.copyright || " " }, + trademark: { en: options.trademark || " " } + }; + this.unitsPerEm = options.unitsPerEm || 1000; + this.ascender = options.ascender; + this.descender = options.descender; + this.createdTimestamp = options.createdTimestamp; + this.tables = Object.assign(options.tables, { + os2: Object.assign({ + usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM, + usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM, + fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR + }, options.tables.os2) + }); + } + this.supported = true; + this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []); + this.encoding = new DefaultEncoding(this); + this.position = new Position(this); + this.substitution = new Substitution(this); + this.tables = this.tables || {}; + this._push = null; + this._hmtxTableData = {}; + Object.defineProperty(this, "hinting", { + get: function() { + if (this._hinting) { + return this._hinting; + } + if (this.outlinesFormat === "truetype") { + return this._hinting = new Hinting(this); + } + } + }); +} +Font.prototype.hasChar = function(c) { + return this.encoding.charToGlyphIndex(c) !== null; +}; +Font.prototype.charToGlyphIndex = function(s) { + return this.encoding.charToGlyphIndex(s); +}; +Font.prototype.charToGlyph = function(c) { + var glyphIndex = this.charToGlyphIndex(c); + var glyph = this.glyphs.get(glyphIndex); + if (!glyph) { + glyph = this.glyphs.get(0); + } + return glyph; +}; +Font.prototype.updateFeatures = function(options) { + return this.defaultRenderOptions.features.map(function(feature) { + if (feature.script === "latn") { + return { + script: "latn", + tags: feature.tags.filter(function(tag) { + return options[tag]; + }) + }; + } else { + return feature; + } + }); +}; +Font.prototype.stringToGlyphs = function(s, options) { + var this$1 = this; + var bidi = new Bidi; + var charToGlyphIndexMod = function(token) { + return this$1.charToGlyphIndex(token.char); + }; + bidi.registerModifier("glyphIndex", null, charToGlyphIndexMod); + var features = options ? this.updateFeatures(options.features) : this.defaultRenderOptions.features; + bidi.applyFeatures(this, features); + var indexes = bidi.getTextGlyphs(s); + var length2 = indexes.length; + var glyphs = new Array(length2); + var notdef = this.glyphs.get(0); + for (var i = 0;i < length2; i += 1) { + glyphs[i] = this.glyphs.get(indexes[i]) || notdef; + } + return glyphs; +}; +Font.prototype.nameToGlyphIndex = function(name2) { + return this.glyphNames.nameToGlyphIndex(name2); +}; +Font.prototype.nameToGlyph = function(name2) { + var glyphIndex = this.nameToGlyphIndex(name2); + var glyph = this.glyphs.get(glyphIndex); + if (!glyph) { + glyph = this.glyphs.get(0); + } + return glyph; +}; +Font.prototype.glyphIndexToName = function(gid) { + if (!this.glyphNames.glyphIndexToName) { + return ""; + } + return this.glyphNames.glyphIndexToName(gid); +}; +Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) { + leftGlyph = leftGlyph.index || leftGlyph; + rightGlyph = rightGlyph.index || rightGlyph; + var gposKerning = this.position.defaultKerningTables; + if (gposKerning) { + return this.position.getKerningValue(gposKerning, leftGlyph, rightGlyph); + } + return this.kerningPairs[leftGlyph + "," + rightGlyph] || 0; +}; +Font.prototype.defaultRenderOptions = { + kerning: true, + features: [ + { script: "arab", tags: ["init", "medi", "fina", "rlig"] }, + { script: "latn", tags: ["liga", "rlig"] } + ] +}; +Font.prototype.forEachGlyph = function(text2, x2, y, fontSize, options, callback) { + x2 = x2 !== undefined ? x2 : 0; + y = y !== undefined ? y : 0; + fontSize = fontSize !== undefined ? fontSize : 72; + options = Object.assign({}, this.defaultRenderOptions, options); + var fontScale = 1 / this.unitsPerEm * fontSize; + var glyphs = this.stringToGlyphs(text2, options); + var kerningLookups; + if (options.kerning) { + var script = options.script || this.position.getDefaultScriptName(); + kerningLookups = this.position.getKerningTables(script, options.language); + } + for (var i = 0;i < glyphs.length; i += 1) { + var glyph = glyphs[i]; + callback.call(this, glyph, x2, y, fontSize, options); + if (glyph.advanceWidth) { + x2 += glyph.advanceWidth * fontScale; + } + if (options.kerning && i < glyphs.length - 1) { + var kerningValue = kerningLookups ? this.position.getKerningValue(kerningLookups, glyph.index, glyphs[i + 1].index) : this.getKerningValue(glyph, glyphs[i + 1]); + x2 += kerningValue * fontScale; + } + if (options.letterSpacing) { + x2 += options.letterSpacing * fontSize; + } else if (options.tracking) { + x2 += options.tracking / 1000 * fontSize; + } + } + return x2; +}; +Font.prototype.getPath = function(text2, x2, y, fontSize, options) { + var fullPath = new Path2; + this.forEachGlyph(text2, x2, y, fontSize, options, function(glyph, gX, gY, gFontSize) { + var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); + fullPath.extend(glyphPath); + }); + return fullPath; +}; +Font.prototype.getPaths = function(text2, x2, y, fontSize, options) { + var glyphPaths = []; + this.forEachGlyph(text2, x2, y, fontSize, options, function(glyph, gX, gY, gFontSize) { + var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); + glyphPaths.push(glyphPath); + }); + return glyphPaths; +}; +Font.prototype.getAdvanceWidth = function(text2, fontSize, options) { + return this.forEachGlyph(text2, 0, 0, fontSize, options, function() { + }); +}; +Font.prototype.draw = function(ctx, text2, x2, y, fontSize, options) { + this.getPath(text2, x2, y, fontSize, options).draw(ctx); +}; +Font.prototype.drawPoints = function(ctx, text2, x2, y, fontSize, options) { + this.forEachGlyph(text2, x2, y, fontSize, options, function(glyph, gX, gY, gFontSize) { + glyph.drawPoints(ctx, gX, gY, gFontSize); + }); +}; +Font.prototype.drawMetrics = function(ctx, text2, x2, y, fontSize, options) { + this.forEachGlyph(text2, x2, y, fontSize, options, function(glyph, gX, gY, gFontSize) { + glyph.drawMetrics(ctx, gX, gY, gFontSize); + }); +}; +Font.prototype.getEnglishName = function(name2) { + var translations = this.names[name2]; + if (translations) { + return translations.en; + } +}; +Font.prototype.validate = function() { + var _this = this; + function assert(predicate, message) { + } + function assertNamePresent(name2) { + var englishName = _this.getEnglishName(name2); + assert(englishName && englishName.trim().length > 0); + } + assertNamePresent("fontFamily"); + assertNamePresent("weightName"); + assertNamePresent("manufacturer"); + assertNamePresent("copyright"); + assertNamePresent("version"); + assert(this.unitsPerEm > 0); +}; +Font.prototype.toTables = function() { + return sfnt.fontToTable(this); +}; +Font.prototype.toBuffer = function() { + console.warn("Font.toBuffer is deprecated. Use Font.toArrayBuffer instead."); + return this.toArrayBuffer(); +}; +Font.prototype.toArrayBuffer = function() { + var sfntTable = this.toTables(); + var bytes = sfntTable.encode(); + var buffer = new ArrayBuffer(bytes.length); + var intArray = new Uint8Array(buffer); + for (var i = 0;i < bytes.length; i++) { + intArray[i] = bytes[i]; + } + return buffer; +}; +Font.prototype.download = function(fileName) { + var familyName = this.getEnglishName("fontFamily"); + var styleName = this.getEnglishName("fontSubfamily"); + fileName = fileName || familyName.replace(/\s/g, "") + "-" + styleName + ".otf"; + var arrayBuffer = this.toArrayBuffer(); + window.URL = window.URL || window.webkitURL; + if (window.URL) { + var dataView = new DataView(arrayBuffer); + var blob = new Blob([dataView], { type: "font/opentype" }); + var link = document.createElement("a"); + link.href = window.URL.createObjectURL(blob); + link.download = fileName; + var event = document.createEvent("MouseEvents"); + event.initEvent("click", true, false); + link.dispatchEvent(event); + } else { + console.warn("Font file could not be downloaded. Try using a different browser."); + } +}; +Font.prototype.fsSelectionValues = { + ITALIC: 1, + UNDERSCORE: 2, + NEGATIVE: 4, + OUTLINED: 8, + STRIKEOUT: 16, + BOLD: 32, + REGULAR: 64, + USER_TYPO_METRICS: 128, + WWS: 256, + OBLIQUE: 512 +}; +Font.prototype.usWidthClasses = { + ULTRA_CONDENSED: 1, + EXTRA_CONDENSED: 2, + CONDENSED: 3, + SEMI_CONDENSED: 4, + MEDIUM: 5, + SEMI_EXPANDED: 6, + EXPANDED: 7, + EXTRA_EXPANDED: 8, + ULTRA_EXPANDED: 9 +}; +Font.prototype.usWeightClasses = { + THIN: 100, + EXTRA_LIGHT: 200, + LIGHT: 300, + NORMAL: 400, + MEDIUM: 500, + SEMI_BOLD: 600, + BOLD: 700, + EXTRA_BOLD: 800, + BLACK: 900 +}; +var subtableParsers$1 = new Array(10); +subtableParsers$1[1] = function parseLookup12() { + var start = this.offset + this.relativeOffset; + var posformat = this.parseUShort(); + if (posformat === 1) { + return { + posFormat: 1, + coverage: this.parsePointer(Parser.coverage), + value: this.parseValueRecord() + }; + } else if (posformat === 2) { + return { + posFormat: 2, + coverage: this.parsePointer(Parser.coverage), + values: this.parseValueRecordList() + }; + } + check.assert(false, "0x" + start.toString(16) + ": GPOS lookup type 1 format must be 1 or 2."); +}; +subtableParsers$1[2] = function parseLookup22() { + var start = this.offset + this.relativeOffset; + var posFormat = this.parseUShort(); + check.assert(posFormat === 1 || posFormat === 2, "0x" + start.toString(16) + ": GPOS lookup type 2 format must be 1 or 2."); + var coverage = this.parsePointer(Parser.coverage); + var valueFormat1 = this.parseUShort(); + var valueFormat2 = this.parseUShort(); + if (posFormat === 1) { + return { + posFormat, + coverage, + valueFormat1, + valueFormat2, + pairSets: this.parseList(Parser.pointer(Parser.list(function() { + return { + secondGlyph: this.parseUShort(), + value1: this.parseValueRecord(valueFormat1), + value2: this.parseValueRecord(valueFormat2) + }; + }))) + }; + } else if (posFormat === 2) { + var classDef1 = this.parsePointer(Parser.classDef); + var classDef2 = this.parsePointer(Parser.classDef); + var class1Count = this.parseUShort(); + var class2Count = this.parseUShort(); + return { + posFormat, + coverage, + valueFormat1, + valueFormat2, + classDef1, + classDef2, + class1Count, + class2Count, + classRecords: this.parseList(class1Count, Parser.list(class2Count, function() { + return { + value1: this.parseValueRecord(valueFormat1), + value2: this.parseValueRecord(valueFormat2) + }; + })) + }; + } +}; +subtableParsers$1[3] = function parseLookup32() { + return { error: "GPOS Lookup 3 not supported" }; +}; +subtableParsers$1[4] = function parseLookup42() { + return { error: "GPOS Lookup 4 not supported" }; +}; +subtableParsers$1[5] = function parseLookup52() { + return { error: "GPOS Lookup 5 not supported" }; +}; +subtableParsers$1[6] = function parseLookup62() { + return { error: "GPOS Lookup 6 not supported" }; +}; +subtableParsers$1[7] = function parseLookup72() { + return { error: "GPOS Lookup 7 not supported" }; +}; +subtableParsers$1[8] = function parseLookup82() { + return { error: "GPOS Lookup 8 not supported" }; +}; +subtableParsers$1[9] = function parseLookup9() { + return { error: "GPOS Lookup 9 not supported" }; +}; +var subtableMakers$1 = new Array(10); +// node_modules/three/examples/jsm/libs/chevrotain.module.min.js +/*! chevrotain - v9.0.1 */ +var R2 = (t2, e) => () => (e || (e = { exports: {} }, t2(e.exports, e)), e.exports); +var Er2 = R2((Pt) => { + Object.defineProperty(Pt, "__esModule", { value: true }); + Pt.VERSION = undefined; + Pt.VERSION = "9.0.1"; +}); +var k2 = R2((exports, module) => { + var __spreadArray = exports && exports.__spreadArray || function(t2, e) { + for (var r = 0, n2 = e.length, i = t2.length;r < n2; r++, i++) + t2[i] = e[r]; + return t2; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toFastProperties = exports.timer = exports.peek = exports.isES2015MapSupported = exports.PRINT_WARNING = exports.PRINT_ERROR = exports.packArray = exports.IDENTITY = exports.NOOP = exports.merge = exports.groupBy = exports.defaults = exports.assignNoOverwrite = exports.assign = exports.zipObject = exports.sortBy = exports.indexOf = exports.some = exports.difference = exports.every = exports.isObject = exports.isRegExp = exports.isArray = exports.partial = exports.uniq = exports.compact = exports.reduce = exports.findAll = exports.find = exports.cloneObj = exports.cloneArr = exports.contains = exports.has = exports.pick = exports.reject = exports.filter = exports.dropRight = exports.drop = exports.isFunction = exports.isUndefined = exports.isString = exports.forEach = exports.last = exports.first = exports.flatten = exports.map = exports.mapValues = exports.values = exports.keys = exports.isEmpty = undefined; + function isEmpty(t2) { + return t2 && t2.length === 0; + } + exports.isEmpty = isEmpty; + function keys(t2) { + return t2 == null ? [] : Object.keys(t2); + } + exports.keys = keys; + function values(t2) { + for (var e = [], r = Object.keys(t2), n2 = 0;n2 < r.length; n2++) + e.push(t2[r[n2]]); + return e; + } + exports.values = values; + function mapValues(t2, e) { + for (var r = [], n2 = keys(t2), i = 0;i < n2.length; i++) { + var a = n2[i]; + r.push(e.call(null, t2[a], a)); + } + return r; + } + exports.mapValues = mapValues; + function map(t2, e) { + for (var r = [], n2 = 0;n2 < t2.length; n2++) + r.push(e.call(null, t2[n2], n2)); + return r; + } + exports.map = map; + function flatten(t2) { + for (var e = [], r = 0;r < t2.length; r++) { + var n2 = t2[r]; + Array.isArray(n2) ? e = e.concat(flatten(n2)) : e.push(n2); + } + return e; + } + exports.flatten = flatten; + function first(t2) { + return isEmpty(t2) ? undefined : t2[0]; + } + exports.first = first; + function last(t2) { + var e = t2 && t2.length; + return e ? t2[e - 1] : undefined; + } + exports.last = last; + function forEach(t2, e) { + if (Array.isArray(t2)) + for (var r = 0;r < t2.length; r++) + e.call(null, t2[r], r); + else if (isObject(t2)) + for (var n2 = keys(t2), r = 0;r < n2.length; r++) { + var i = n2[r], a = t2[i]; + e.call(null, a, i); + } + else + throw Error("non exhaustive match"); + } + exports.forEach = forEach; + function isString(t2) { + return typeof t2 == "string"; + } + exports.isString = isString; + function isUndefined(t2) { + return t2 === undefined; + } + exports.isUndefined = isUndefined; + function isFunction(t2) { + return t2 instanceof Function; + } + exports.isFunction = isFunction; + function drop(t2, e) { + return e === undefined && (e = 1), t2.slice(e, t2.length); + } + exports.drop = drop; + function dropRight(t2, e) { + return e === undefined && (e = 1), t2.slice(0, t2.length - e); + } + exports.dropRight = dropRight; + function filter(t2, e) { + var r = []; + if (Array.isArray(t2)) + for (var n2 = 0;n2 < t2.length; n2++) { + var i = t2[n2]; + e.call(null, i) && r.push(i); + } + return r; + } + exports.filter = filter; + function reject(t2, e) { + return filter(t2, function(r) { + return !e(r); + }); + } + exports.reject = reject; + function pick(t2, e) { + for (var r = Object.keys(t2), n2 = {}, i = 0;i < r.length; i++) { + var a = r[i], o = t2[a]; + e(o) && (n2[a] = o); + } + return n2; + } + exports.pick = pick; + function has(t2, e) { + return isObject(t2) ? t2.hasOwnProperty(e) : false; + } + exports.has = has; + function contains(t2, e) { + return find(t2, function(r) { + return r === e; + }) !== undefined; + } + exports.contains = contains; + function cloneArr(t2) { + for (var e = [], r = 0;r < t2.length; r++) + e.push(t2[r]); + return e; + } + exports.cloneArr = cloneArr; + function cloneObj(t2) { + var e = {}; + for (var r in t2) + Object.prototype.hasOwnProperty.call(t2, r) && (e[r] = t2[r]); + return e; + } + exports.cloneObj = cloneObj; + function find(t2, e) { + for (var r = 0;r < t2.length; r++) { + var n2 = t2[r]; + if (e.call(null, n2)) + return n2; + } + } + exports.find = find; + function findAll(t2, e) { + for (var r = [], n2 = 0;n2 < t2.length; n2++) { + var i = t2[n2]; + e.call(null, i) && r.push(i); + } + return r; + } + exports.findAll = findAll; + function reduce(t2, e, r) { + for (var n2 = Array.isArray(t2), i = n2 ? t2 : values(t2), a = n2 ? [] : keys(t2), o = r, s = 0;s < i.length; s++) + o = e.call(null, o, i[s], n2 ? s : a[s]); + return o; + } + exports.reduce = reduce; + function compact(t2) { + return reject(t2, function(e) { + return e == null; + }); + } + exports.compact = compact; + function uniq(t2, e) { + e === undefined && (e = function(n2) { + return n2; + }); + var r = []; + return reduce(t2, function(n2, i) { + var a = e(i); + return contains(r, a) ? n2 : (r.push(a), n2.concat(i)); + }, []); + } + exports.uniq = uniq; + function partial(t2) { + for (var e = [], r = 1;r < arguments.length; r++) + e[r - 1] = arguments[r]; + var n2 = [null], i = n2.concat(e); + return Function.bind.apply(t2, i); + } + exports.partial = partial; + function isArray(t2) { + return Array.isArray(t2); + } + exports.isArray = isArray; + function isRegExp(t2) { + return t2 instanceof RegExp; + } + exports.isRegExp = isRegExp; + function isObject(t2) { + return t2 instanceof Object; + } + exports.isObject = isObject; + function every(t2, e) { + for (var r = 0;r < t2.length; r++) + if (!e(t2[r], r)) + return false; + return true; + } + exports.every = every; + function difference(t2, e) { + return reject(t2, function(r) { + return contains(e, r); + }); + } + exports.difference = difference; + function some(t2, e) { + for (var r = 0;r < t2.length; r++) + if (e(t2[r])) + return true; + return false; + } + exports.some = some; + function indexOf(t2, e) { + for (var r = 0;r < t2.length; r++) + if (t2[r] === e) + return r; + return -1; + } + exports.indexOf = indexOf; + function sortBy(t2, e) { + var r = cloneArr(t2); + return r.sort(function(n2, i) { + return e(n2) - e(i); + }), r; + } + exports.sortBy = sortBy; + function zipObject(t2, e) { + if (t2.length !== e.length) + throw Error("can't zipObject with different number of keys and values!"); + for (var r = {}, n2 = 0;n2 < t2.length; n2++) + r[t2[n2]] = e[n2]; + return r; + } + exports.zipObject = zipObject; + function assign(t2) { + for (var e = [], r = 1;r < arguments.length; r++) + e[r - 1] = arguments[r]; + for (var n2 = 0;n2 < e.length; n2++) + for (var i = e[n2], a = keys(i), o = 0;o < a.length; o++) { + var s = a[o]; + t2[s] = i[s]; + } + return t2; + } + exports.assign = assign; + function assignNoOverwrite(t2) { + for (var e = [], r = 1;r < arguments.length; r++) + e[r - 1] = arguments[r]; + for (var n2 = 0;n2 < e.length; n2++) + for (var i = e[n2], a = keys(i), o = 0;o < a.length; o++) { + var s = a[o]; + has(t2, s) || (t2[s] = i[s]); + } + return t2; + } + exports.assignNoOverwrite = assignNoOverwrite; + function defaults() { + for (var t2 = [], e = 0;e < arguments.length; e++) + t2[e] = arguments[e]; + return assignNoOverwrite.apply(undefined, __spreadArray([{}], t2)); + } + exports.defaults = defaults; + function groupBy(t2, e) { + var r = {}; + return forEach(t2, function(n2) { + var i = e(n2), a = r[i]; + a ? a.push(n2) : r[i] = [n2]; + }), r; + } + exports.groupBy = groupBy; + function merge(t2, e) { + for (var r = cloneObj(t2), n2 = keys(e), i = 0;i < n2.length; i++) { + var a = n2[i], o = e[a]; + r[a] = o; + } + return r; + } + exports.merge = merge; + function NOOP() { + } + exports.NOOP = NOOP; + function IDENTITY(t2) { + return t2; + } + exports.IDENTITY = IDENTITY; + function packArray(t2) { + for (var e = [], r = 0;r < t2.length; r++) { + var n2 = t2[r]; + e.push(n2 !== undefined ? n2 : undefined); + } + return e; + } + exports.packArray = packArray; + function PRINT_ERROR(t2) { + console && console.error && console.error("Error: " + t2); + } + exports.PRINT_ERROR = PRINT_ERROR; + function PRINT_WARNING(t2) { + console && console.warn && console.warn("Warning: " + t2); + } + exports.PRINT_WARNING = PRINT_WARNING; + function isES2015MapSupported() { + return typeof Map == "function"; + } + exports.isES2015MapSupported = isES2015MapSupported; + function peek(t2) { + return t2[t2.length - 1]; + } + exports.peek = peek; + function timer(t2) { + var e = new Date().getTime(), r = t2(), n2 = new Date().getTime(), i = n2 - e; + return { time: i, value: r }; + } + exports.timer = timer; + function toFastProperties(toBecomeFast) { + function FakeConstructor() { + } + FakeConstructor.prototype = toBecomeFast; + var fakeInstance = new FakeConstructor; + function fakeAccess() { + return typeof fakeInstance.bar; + } + return fakeAccess(), fakeAccess(), toBecomeFast; + eval(toBecomeFast); + } + exports.toFastProperties = toFastProperties; +}); +var xt3 = R2((sn, St) => { + (function(t2, e) { + typeof define == "function" && define.amd ? define([], e) : typeof St == "object" && St.exports ? St.exports = e() : t2.regexpToAst = e(); + })(typeof self != "undefined" ? self : sn, function() { + function t2() { + } + t2.prototype.saveState = function() { + return { idx: this.idx, input: this.input, groupIdx: this.groupIdx }; + }, t2.prototype.restoreState = function(u2) { + this.idx = u2.idx, this.input = u2.input, this.groupIdx = u2.groupIdx; + }, t2.prototype.pattern = function(u2) { + this.idx = 0, this.input = u2, this.groupIdx = 0, this.consumeChar("/"); + var d = this.disjunction(); + this.consumeChar("/"); + for (var A2 = { type: "Flags", loc: { begin: this.idx, end: u2.length }, global: false, ignoreCase: false, multiLine: false, unicode: false, sticky: false };this.isRegExpFlag(); ) + switch (this.popChar()) { + case "g": + o(A2, "global"); + break; + case "i": + o(A2, "ignoreCase"); + break; + case "m": + o(A2, "multiLine"); + break; + case "u": + o(A2, "unicode"); + break; + case "y": + o(A2, "sticky"); + break; + } + if (this.idx !== this.input.length) + throw Error("Redundant input: " + this.input.substring(this.idx)); + return { type: "Pattern", flags: A2, value: d, loc: this.loc(0) }; + }, t2.prototype.disjunction = function() { + var u2 = [], d = this.idx; + for (u2.push(this.alternative());this.peekChar() === "|"; ) + this.consumeChar("|"), u2.push(this.alternative()); + return { type: "Disjunction", value: u2, loc: this.loc(d) }; + }, t2.prototype.alternative = function() { + for (var u2 = [], d = this.idx;this.isTerm(); ) + u2.push(this.term()); + return { type: "Alternative", value: u2, loc: this.loc(d) }; + }, t2.prototype.term = function() { + return this.isAssertion() ? this.assertion() : this.atom(); + }, t2.prototype.assertion = function() { + var u2 = this.idx; + switch (this.popChar()) { + case "^": + return { type: "StartAnchor", loc: this.loc(u2) }; + case "$": + return { type: "EndAnchor", loc: this.loc(u2) }; + case "\\": + switch (this.popChar()) { + case "b": + return { type: "WordBoundary", loc: this.loc(u2) }; + case "B": + return { type: "NonWordBoundary", loc: this.loc(u2) }; + } + throw Error("Invalid Assertion Escape"); + case "(": + this.consumeChar("?"); + var d; + switch (this.popChar()) { + case "=": + d = "Lookahead"; + break; + case "!": + d = "NegativeLookahead"; + break; + } + s(d); + var A2 = this.disjunction(); + return this.consumeChar(")"), { type: d, value: A2, loc: this.loc(u2) }; + } + c(); + }, t2.prototype.quantifier = function(u2) { + var d, A2 = this.idx; + switch (this.popChar()) { + case "*": + d = { atLeast: 0, atMost: Infinity }; + break; + case "+": + d = { atLeast: 1, atMost: Infinity }; + break; + case "?": + d = { atLeast: 0, atMost: 1 }; + break; + case "{": + var _2 = this.integerIncludingZero(); + switch (this.popChar()) { + case "}": + d = { atLeast: _2, atMost: _2 }; + break; + case ",": + var g3; + this.isDigit() ? (g3 = this.integerIncludingZero(), d = { atLeast: _2, atMost: g3 }) : d = { atLeast: _2, atMost: Infinity }, this.consumeChar("}"); + break; + } + if (u2 === true && d === undefined) + return; + s(d); + break; + } + if (!(u2 === true && d === undefined)) + return s(d), this.peekChar(0) === "?" ? (this.consumeChar("?"), d.greedy = false) : d.greedy = true, d.type = "Quantifier", d.loc = this.loc(A2), d; + }, t2.prototype.atom = function() { + var u2, d = this.idx; + switch (this.peekChar()) { + case ".": + u2 = this.dotAll(); + break; + case "\\": + u2 = this.atomEscape(); + break; + case "[": + u2 = this.characterClass(); + break; + case "(": + u2 = this.group(); + break; + } + return u2 === undefined && this.isPatternCharacter() && (u2 = this.patternCharacter()), s(u2), u2.loc = this.loc(d), this.isQuantifier() && (u2.quantifier = this.quantifier()), u2; + }, t2.prototype.dotAll = function() { + return this.consumeChar("."), { type: "Set", complement: true, value: [i(` +`), i("\r"), i("\u2028"), i("\u2029")] }; + }, t2.prototype.atomEscape = function() { + switch (this.consumeChar("\\"), this.peekChar()) { + case "1": + case "2": + case "3": + case "4": + case "5": + case "6": + case "7": + case "8": + case "9": + return this.decimalEscapeAtom(); + case "d": + case "D": + case "s": + case "S": + case "w": + case "W": + return this.characterClassEscape(); + case "f": + case "n": + case "r": + case "t": + case "v": + return this.controlEscapeAtom(); + case "c": + return this.controlLetterEscapeAtom(); + case "0": + return this.nulCharacterAtom(); + case "x": + return this.hexEscapeSequenceAtom(); + case "u": + return this.regExpUnicodeEscapeSequenceAtom(); + default: + return this.identityEscapeAtom(); + } + }, t2.prototype.decimalEscapeAtom = function() { + var u2 = this.positiveInteger(); + return { type: "GroupBackReference", value: u2 }; + }, t2.prototype.characterClassEscape = function() { + var u2, d = false; + switch (this.popChar()) { + case "d": + u2 = p; + break; + case "D": + u2 = p, d = true; + break; + case "s": + u2 = m; + break; + case "S": + u2 = m, d = true; + break; + case "w": + u2 = l2; + break; + case "W": + u2 = l2, d = true; + break; + } + return s(u2), { type: "Set", value: u2, complement: d }; + }, t2.prototype.controlEscapeAtom = function() { + var u2; + switch (this.popChar()) { + case "f": + u2 = i("\f"); + break; + case "n": + u2 = i(` +`); + break; + case "r": + u2 = i("\r"); + break; + case "t": + u2 = i("\t"); + break; + case "v": + u2 = i("\v"); + break; + } + return s(u2), { type: "Character", value: u2 }; + }, t2.prototype.controlLetterEscapeAtom = function() { + this.consumeChar("c"); + var u2 = this.popChar(); + if (/[a-zA-Z]/.test(u2) === false) + throw Error("Invalid "); + var d = u2.toUpperCase().charCodeAt(0) - 64; + return { type: "Character", value: d }; + }, t2.prototype.nulCharacterAtom = function() { + return this.consumeChar("0"), { type: "Character", value: i("\x00") }; + }, t2.prototype.hexEscapeSequenceAtom = function() { + return this.consumeChar("x"), this.parseHexDigits(2); + }, t2.prototype.regExpUnicodeEscapeSequenceAtom = function() { + return this.consumeChar("u"), this.parseHexDigits(4); + }, t2.prototype.identityEscapeAtom = function() { + var u2 = this.popChar(); + return { type: "Character", value: i(u2) }; + }, t2.prototype.classPatternCharacterAtom = function() { + switch (this.peekChar()) { + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + case "\\": + case "]": + throw Error("TBD"); + default: + var u2 = this.popChar(); + return { type: "Character", value: i(u2) }; + } + }, t2.prototype.characterClass = function() { + var u2 = [], d = false; + for (this.consumeChar("["), this.peekChar(0) === "^" && (this.consumeChar("^"), d = true);this.isClassAtom(); ) { + var A2 = this.classAtom(), _2 = A2.type === "Character"; + if (_2 && this.isRangeDash()) { + this.consumeChar("-"); + var g3 = this.classAtom(), y = g3.type === "Character"; + if (y) { + if (g3.value < A2.value) + throw Error("Range out of order in character class"); + u2.push({ from: A2.value, to: g3.value }); + } else + a(A2.value, u2), u2.push(i("-")), a(g3.value, u2); + } else + a(A2.value, u2); + } + return this.consumeChar("]"), { type: "Set", complement: d, value: u2 }; + }, t2.prototype.classAtom = function() { + switch (this.peekChar()) { + case "]": + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + throw Error("TBD"); + case "\\": + return this.classEscape(); + default: + return this.classPatternCharacterAtom(); + } + }, t2.prototype.classEscape = function() { + switch (this.consumeChar("\\"), this.peekChar()) { + case "b": + return this.consumeChar("b"), { type: "Character", value: i("\b") }; + case "d": + case "D": + case "s": + case "S": + case "w": + case "W": + return this.characterClassEscape(); + case "f": + case "n": + case "r": + case "t": + case "v": + return this.controlEscapeAtom(); + case "c": + return this.controlLetterEscapeAtom(); + case "0": + return this.nulCharacterAtom(); + case "x": + return this.hexEscapeSequenceAtom(); + case "u": + return this.regExpUnicodeEscapeSequenceAtom(); + default: + return this.identityEscapeAtom(); + } + }, t2.prototype.group = function() { + var u2 = true; + switch (this.consumeChar("("), this.peekChar(0)) { + case "?": + this.consumeChar("?"), this.consumeChar(":"), u2 = false; + break; + default: + this.groupIdx++; + break; + } + var d = this.disjunction(); + this.consumeChar(")"); + var A2 = { type: "Group", capturing: u2, value: d }; + return u2 && (A2.idx = this.groupIdx), A2; + }, t2.prototype.positiveInteger = function() { + var u2 = this.popChar(); + if (n2.test(u2) === false) + throw Error("Expecting a positive integer"); + for (;r.test(this.peekChar(0)); ) + u2 += this.popChar(); + return parseInt(u2, 10); + }, t2.prototype.integerIncludingZero = function() { + var u2 = this.popChar(); + if (r.test(u2) === false) + throw Error("Expecting an integer"); + for (;r.test(this.peekChar(0)); ) + u2 += this.popChar(); + return parseInt(u2, 10); + }, t2.prototype.patternCharacter = function() { + var u2 = this.popChar(); + switch (u2) { + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + case "^": + case "$": + case "\\": + case ".": + case "*": + case "+": + case "?": + case "(": + case ")": + case "[": + case "|": + throw Error("TBD"); + default: + return { type: "Character", value: i(u2) }; + } + }, t2.prototype.isRegExpFlag = function() { + switch (this.peekChar(0)) { + case "g": + case "i": + case "m": + case "u": + case "y": + return true; + default: + return false; + } + }, t2.prototype.isRangeDash = function() { + return this.peekChar() === "-" && this.isClassAtom(1); + }, t2.prototype.isDigit = function() { + return r.test(this.peekChar(0)); + }, t2.prototype.isClassAtom = function(u2) { + switch (u2 === undefined && (u2 = 0), this.peekChar(u2)) { + case "]": + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + return false; + default: + return true; + } + }, t2.prototype.isTerm = function() { + return this.isAtom() || this.isAssertion(); + }, t2.prototype.isAtom = function() { + if (this.isPatternCharacter()) + return true; + switch (this.peekChar(0)) { + case ".": + case "\\": + case "[": + case "(": + return true; + default: + return false; + } + }, t2.prototype.isAssertion = function() { + switch (this.peekChar(0)) { + case "^": + case "$": + return true; + case "\\": + switch (this.peekChar(1)) { + case "b": + case "B": + return true; + default: + return false; + } + case "(": + return this.peekChar(1) === "?" && (this.peekChar(2) === "=" || this.peekChar(2) === "!"); + default: + return false; + } + }, t2.prototype.isQuantifier = function() { + var u2 = this.saveState(); + try { + return this.quantifier(true) !== undefined; + } catch (d) { + return false; + } finally { + this.restoreState(u2); + } + }, t2.prototype.isPatternCharacter = function() { + switch (this.peekChar()) { + case "^": + case "$": + case "\\": + case ".": + case "*": + case "+": + case "?": + case "(": + case ")": + case "[": + case "|": + case "/": + case ` +`: + case "\r": + case "\u2028": + case "\u2029": + return false; + default: + return true; + } + }, t2.prototype.parseHexDigits = function(u2) { + for (var d = "", A2 = 0;A2 < u2; A2++) { + var _2 = this.popChar(); + if (e.test(_2) === false) + throw Error("Expecting a HexDecimal digits"); + d += _2; + } + var g3 = parseInt(d, 16); + return { type: "Character", value: g3 }; + }, t2.prototype.peekChar = function(u2) { + return u2 === undefined && (u2 = 0), this.input[this.idx + u2]; + }, t2.prototype.popChar = function() { + var u2 = this.peekChar(0); + return this.consumeChar(), u2; + }, t2.prototype.consumeChar = function(u2) { + if (u2 !== undefined && this.input[this.idx] !== u2) + throw Error("Expected: '" + u2 + "' but found: '" + this.input[this.idx] + "' at offset: " + this.idx); + if (this.idx >= this.input.length) + throw Error("Unexpected end of input"); + this.idx++; + }, t2.prototype.loc = function(u2) { + return { begin: u2, end: this.idx }; + }; + var e = /[0-9a-fA-F]/, r = /[0-9]/, n2 = /[1-9]/; + function i(u2) { + return u2.charCodeAt(0); + } + function a(u2, d) { + u2.length !== undefined ? u2.forEach(function(A2) { + d.push(A2); + }) : d.push(u2); + } + function o(u2, d) { + if (u2[d] === true) + throw "duplicate flag " + d; + u2[d] = true; + } + function s(u2) { + if (u2 === undefined) + throw Error("Internal Error - Should never get here!"); + } + function c() { + throw Error("Internal Error - Should never get here!"); + } + var f, p = []; + for (f = i("0");f <= i("9"); f++) + p.push(f); + var l2 = [i("_")].concat(p); + for (f = i("a");f <= i("z"); f++) + l2.push(f); + for (f = i("A");f <= i("Z"); f++) + l2.push(f); + var m = [i(" "), i("\f"), i(` +`), i("\r"), i("\t"), i("\v"), i("\t"), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i(" "), i("\u2028"), i("\u2029"), i(" "), i(" "), i(" "), i("\uFEFF")]; + function v() { + } + return v.prototype.visitChildren = function(u2) { + for (var d in u2) { + var A2 = u2[d]; + u2.hasOwnProperty(d) && (A2.type !== undefined ? this.visit(A2) : Array.isArray(A2) && A2.forEach(function(_2) { + this.visit(_2); + }, this)); + } + }, v.prototype.visit = function(u2) { + switch (u2.type) { + case "Pattern": + this.visitPattern(u2); + break; + case "Flags": + this.visitFlags(u2); + break; + case "Disjunction": + this.visitDisjunction(u2); + break; + case "Alternative": + this.visitAlternative(u2); + break; + case "StartAnchor": + this.visitStartAnchor(u2); + break; + case "EndAnchor": + this.visitEndAnchor(u2); + break; + case "WordBoundary": + this.visitWordBoundary(u2); + break; + case "NonWordBoundary": + this.visitNonWordBoundary(u2); + break; + case "Lookahead": + this.visitLookahead(u2); + break; + case "NegativeLookahead": + this.visitNegativeLookahead(u2); + break; + case "Character": + this.visitCharacter(u2); + break; + case "Set": + this.visitSet(u2); + break; + case "Group": + this.visitGroup(u2); + break; + case "GroupBackReference": + this.visitGroupBackReference(u2); + break; + case "Quantifier": + this.visitQuantifier(u2); + break; + } + this.visitChildren(u2); + }, v.prototype.visitPattern = function(u2) { + }, v.prototype.visitFlags = function(u2) { + }, v.prototype.visitDisjunction = function(u2) { + }, v.prototype.visitAlternative = function(u2) { + }, v.prototype.visitStartAnchor = function(u2) { + }, v.prototype.visitEndAnchor = function(u2) { + }, v.prototype.visitWordBoundary = function(u2) { + }, v.prototype.visitNonWordBoundary = function(u2) { + }, v.prototype.visitLookahead = function(u2) { + }, v.prototype.visitNegativeLookahead = function(u2) { + }, v.prototype.visitCharacter = function(u2) { + }, v.prototype.visitSet = function(u2) { + }, v.prototype.visitGroup = function(u2) { + }, v.prototype.visitGroupBackReference = function(u2) { + }, v.prototype.visitQuantifier = function(u2) { + }, { RegExpParser: t2, BaseRegExpVisitor: v, VERSION: "0.5.0" }; + }); +}); +var Lt = R2((He2) => { + Object.defineProperty(He2, "__esModule", { value: true }); + He2.clearRegExpParserCache = He2.getRegExpAst = undefined; + var Ga = xt3(), Ct2 = {}, Wa = new Ga.RegExpParser; + function Ba(t2) { + var e = t2.toString(); + if (Ct2.hasOwnProperty(e)) + return Ct2[e]; + var r = Wa.pattern(e); + return Ct2[e] = r, r; + } + He2.getRegExpAst = Ba; + function qa() { + Ct2 = {}; + } + He2.clearRegExpParserCache = qa; +}); +var pn = R2((re) => { + var ja = re && re.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(re, "__esModule", { value: true }); + re.canMatchCharCode = re.firstCharOptimizedIndices = re.getOptimizedStartCodesIndices = re.failedOptimizationPrefixMsg = undefined; + var un = xt3(), pe2 = k2(), cn = Lt(), Ce = Tr(), ln = "Complement Sets are not supported for first char optimization"; + re.failedOptimizationPrefixMsg = `Unable to use "first char" lexer optimizations: +`; + function Va(t2, e) { + e === undefined && (e = false); + try { + var r = cn.getRegExpAst(t2), n2 = Mt(r.value, {}, r.flags.ignoreCase); + return n2; + } catch (a) { + if (a.message === ln) + e && pe2.PRINT_WARNING("" + re.failedOptimizationPrefixMsg + ("\tUnable to optimize: < " + t2.toString() + ` > +`) + ` Complement Sets cannot be automatically optimized. + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`); + else { + var i = ""; + e && (i = ` + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`), pe2.PRINT_ERROR(re.failedOptimizationPrefixMsg + ` +` + ("\tFailed parsing: < " + t2.toString() + ` > +`) + ("\tUsing the regexp-to-ast library version: " + un.VERSION + ` +`) + "\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues" + i); + } + } + return []; + } + re.getOptimizedStartCodesIndices = Va; + function Mt(t2, e, r) { + switch (t2.type) { + case "Disjunction": + for (var n2 = 0;n2 < t2.value.length; n2++) + Mt(t2.value[n2], e, r); + break; + case "Alternative": + for (var i = t2.value, n2 = 0;n2 < i.length; n2++) { + var a = i[n2]; + switch (a.type) { + case "EndAnchor": + case "GroupBackReference": + case "Lookahead": + case "NegativeLookahead": + case "StartAnchor": + case "WordBoundary": + case "NonWordBoundary": + continue; + } + var o = a; + switch (o.type) { + case "Character": + bt(o.value, e, r); + break; + case "Set": + if (o.complement === true) + throw Error(ln); + pe2.forEach(o.value, function(f) { + if (typeof f == "number") + bt(f, e, r); + else { + var p = f; + if (r === true) + for (var l2 = p.from;l2 <= p.to; l2++) + bt(l2, e, r); + else { + for (var l2 = p.from;l2 <= p.to && l2 < Ce.minOptimizationVal; l2++) + bt(l2, e, r); + if (p.to >= Ce.minOptimizationVal) + for (var m = p.from >= Ce.minOptimizationVal ? p.from : Ce.minOptimizationVal, v = p.to, u2 = Ce.charCodeToOptimizedIndex(m), d = Ce.charCodeToOptimizedIndex(v), A2 = u2;A2 <= d; A2++) + e[A2] = A2; + } + } + }); + break; + case "Group": + Mt(o.value, e, r); + break; + default: + throw Error("Non Exhaustive Match"); + } + var s = o.quantifier !== undefined && o.quantifier.atLeast === 0; + if (o.type === "Group" && yr(o) === false || o.type !== "Group" && s === false) + break; + } + break; + default: + throw Error("non exhaustive match!"); + } + return pe2.values(e); + } + re.firstCharOptimizedIndices = Mt; + function bt(t2, e, r) { + var n2 = Ce.charCodeToOptimizedIndex(t2); + e[n2] = n2, r === true && Ka(t2, e); + } + function Ka(t2, e) { + var r = String.fromCharCode(t2), n2 = r.toUpperCase(); + if (n2 !== r) { + var i = Ce.charCodeToOptimizedIndex(n2.charCodeAt(0)); + e[i] = i; + } else { + var a = r.toLowerCase(); + if (a !== r) { + var i = Ce.charCodeToOptimizedIndex(a.charCodeAt(0)); + e[i] = i; + } + } + } + function fn(t2, e) { + return pe2.find(t2.value, function(r) { + if (typeof r == "number") + return pe2.contains(e, r); + var n2 = r; + return pe2.find(e, function(i) { + return n2.from <= i && i <= n2.to; + }) !== undefined; + }); + } + function yr(t2) { + return t2.quantifier && t2.quantifier.atLeast === 0 ? true : t2.value ? pe2.isArray(t2.value) ? pe2.every(t2.value, yr) : yr(t2.value) : false; + } + var za = function(t2) { + ja(e, t2); + function e(r) { + var n2 = t2.call(this) || this; + return n2.targetCharCodes = r, n2.found = false, n2; + } + return e.prototype.visitChildren = function(r) { + if (this.found !== true) { + switch (r.type) { + case "Lookahead": + this.visitLookahead(r); + return; + case "NegativeLookahead": + this.visitNegativeLookahead(r); + return; + } + t2.prototype.visitChildren.call(this, r); + } + }, e.prototype.visitCharacter = function(r) { + pe2.contains(this.targetCharCodes, r.value) && (this.found = true); + }, e.prototype.visitSet = function(r) { + r.complement ? fn(r, this.targetCharCodes) === undefined && (this.found = true) : fn(r, this.targetCharCodes) !== undefined && (this.found = true); + }, e; + }(un.BaseRegExpVisitor); + function Ha(t2, e) { + if (e instanceof RegExp) { + var r = cn.getRegExpAst(e), n2 = new za(t2); + return n2.visit(r), n2.found; + } else + return pe2.find(e, function(i) { + return pe2.contains(t2, i.charCodeAt(0)); + }) !== undefined; + } + re.canMatchCharCode = Ha; +}); +var Tr = R2((T2) => { + var hn = T2 && T2.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(T2, "__esModule", { value: true }); + T2.charCodeToOptimizedIndex = T2.minOptimizationVal = T2.buildLineBreakIssueMessage = T2.LineTerminatorOptimizedTester = T2.isShortPattern = T2.isCustomPattern = T2.cloneEmptyGroups = T2.performWarningRuntimeChecks = T2.performRuntimeChecks = T2.addStickyFlag = T2.addStartOfInput = T2.findUnreachablePatterns = T2.findModesThatDoNotExist = T2.findInvalidGroupType = T2.findDuplicatePatterns = T2.findUnsupportedFlags = T2.findStartOfInputAnchor = T2.findEmptyMatchRegExps = T2.findEndOfInputAnchor = T2.findInvalidPatterns = T2.findMissingPatterns = T2.validatePatterns = T2.analyzeTokenTypes = T2.enableSticky = T2.disableSticky = T2.SUPPORT_STICKY = T2.MODES = T2.DEFAULT_MODE = undefined; + var dn = xt3(), F = ft(), h = k2(), Ye = pn(), vn = Lt(), Ae2 = "PATTERN"; + T2.DEFAULT_MODE = "defaultMode"; + T2.MODES = "modes"; + T2.SUPPORT_STICKY = typeof new RegExp("(?:)").sticky == "boolean"; + function Ya() { + T2.SUPPORT_STICKY = false; + } + T2.disableSticky = Ya; + function Xa() { + T2.SUPPORT_STICKY = true; + } + T2.enableSticky = Xa; + function Za(t2, e) { + e = h.defaults(e, { useSticky: T2.SUPPORT_STICKY, debug: false, safeMode: false, positionTracking: "full", lineTerminatorCharacters: ["\r", ` +`], tracer: function(g3, y) { + return y(); + } }); + var r = e.tracer; + r("initCharCodeToOptimizedIndexMap", function() { + $a(); + }); + var n2; + r("Reject Lexer.NA", function() { + n2 = h.reject(t2, function(g3) { + return g3[Ae2] === F.Lexer.NA; + }); + }); + var i = false, a; + r("Transform Patterns", function() { + i = false, a = h.map(n2, function(g3) { + var y = g3[Ae2]; + if (h.isRegExp(y)) { + var b = y.source; + return b.length === 1 && b !== "^" && b !== "$" && b !== "." && !y.ignoreCase ? b : b.length === 2 && b[0] === "\\" && !h.contains(["d", "D", "s", "S", "t", "r", "n", "t", "0", "c", "b", "B", "f", "v", "w", "W"], b[1]) ? b[1] : e.useSticky ? gr(y) : _r(y); + } else { + if (h.isFunction(y)) + return i = true, { exec: y }; + if (h.has(y, "exec")) + return i = true, y; + if (typeof y == "string") { + if (y.length === 1) + return y; + var L = y.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&"), se2 = new RegExp(L); + return e.useSticky ? gr(se2) : _r(se2); + } else + throw Error("non exhaustive match"); + } + }); + }); + var o, s, c, f, p; + r("misc mapping", function() { + o = h.map(n2, function(g3) { + return g3.tokenTypeIdx; + }), s = h.map(n2, function(g3) { + var y = g3.GROUP; + if (y !== F.Lexer.SKIPPED) { + if (h.isString(y)) + return y; + if (h.isUndefined(y)) + return false; + throw Error("non exhaustive match"); + } + }), c = h.map(n2, function(g3) { + var y = g3.LONGER_ALT; + if (y) { + var b = h.indexOf(n2, y); + return b; + } + }), f = h.map(n2, function(g3) { + return g3.PUSH_MODE; + }), p = h.map(n2, function(g3) { + return h.has(g3, "POP_MODE"); + }); + }); + var l2; + r("Line Terminator Handling", function() { + var g3 = Tn(e.lineTerminatorCharacters); + l2 = h.map(n2, function(y) { + return false; + }), e.positionTracking !== "onlyOffset" && (l2 = h.map(n2, function(y) { + if (h.has(y, "LINE_BREAKS")) + return y.LINE_BREAKS; + if (En(y, g3) === false) + return Ye.canMatchCharCode(g3, y.PATTERN); + })); + }); + var m, v, u2, d; + r("Misc Mapping #2", function() { + m = h.map(n2, Ar), v = h.map(a, mn), u2 = h.reduce(n2, function(g3, y) { + var b = y.GROUP; + return h.isString(b) && b !== F.Lexer.SKIPPED && (g3[b] = []), g3; + }, {}), d = h.map(a, function(g3, y) { + return { pattern: a[y], longerAlt: c[y], canLineTerminator: l2[y], isCustom: m[y], short: v[y], group: s[y], push: f[y], pop: p[y], tokenTypeIdx: o[y], tokenType: n2[y] }; + }); + }); + var A2 = true, _2 = []; + return e.safeMode || r("First Char Optimization", function() { + _2 = h.reduce(n2, function(g3, y, b) { + if (typeof y.PATTERN == "string") { + var L = y.PATTERN.charCodeAt(0), se2 = Or(L); + Rr(g3, se2, d[b]); + } else if (h.isArray(y.START_CHARS_HINT)) { + var fe; + h.forEach(y.START_CHARS_HINT, function(ue3) { + var Q2 = typeof ue3 == "string" ? ue3.charCodeAt(0) : ue3, te3 = Or(Q2); + fe !== te3 && (fe = te3, Rr(g3, te3, d[b])); + }); + } else if (h.isRegExp(y.PATTERN)) + if (y.PATTERN.unicode) + A2 = false, e.ensureOptimizations && h.PRINT_ERROR("" + Ye.failedOptimizationPrefixMsg + ("\tUnable to analyze < " + y.PATTERN.toString() + ` > pattern. +`) + ` The regexp unicode flag is not currently supported by the regexp-to-ast library. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`); + else { + var Z2 = Ye.getOptimizedStartCodesIndices(y.PATTERN, e.ensureOptimizations); + h.isEmpty(Z2) && (A2 = false), h.forEach(Z2, function(ue3) { + Rr(g3, ue3, d[b]); + }); + } + else + e.ensureOptimizations && h.PRINT_ERROR("" + Ye.failedOptimizationPrefixMsg + ("\tTokenType: <" + y.name + `> is using a custom token pattern without providing parameter. +`) + ` This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`), A2 = false; + return g3; + }, []); + }), r("ArrayPacking", function() { + _2 = h.packArray(_2); + }), { emptyGroups: u2, patternIdxToConfig: d, charCodeToPatternIdxToConfig: _2, hasCustom: i, canBeOptimized: A2 }; + } + T2.analyzeTokenTypes = Za; + function Ja(t2, e) { + var r = [], n2 = yn(t2); + r = r.concat(n2.errors); + var i = _n(n2.valid), a = i.valid; + return r = r.concat(i.errors), r = r.concat(Qa(a)), r = r.concat(gn(a)), r = r.concat(An(a, e)), r = r.concat(Rn(a)), r; + } + T2.validatePatterns = Ja; + function Qa(t2) { + var e = [], r = h.filter(t2, function(n2) { + return h.isRegExp(n2[Ae2]); + }); + return e = e.concat(On(r)), e = e.concat(In2(r)), e = e.concat(kn(r)), e = e.concat(Pn(r)), e = e.concat(Nn(r)), e; + } + function yn(t2) { + var e = h.filter(t2, function(i) { + return !h.has(i, Ae2); + }), r = h.map(e, function(i) { + return { message: "Token Type: ->" + i.name + "<- missing static 'PATTERN' property", type: F.LexerDefinitionErrorType.MISSING_PATTERN, tokenTypes: [i] }; + }), n2 = h.difference(t2, e); + return { errors: r, valid: n2 }; + } + T2.findMissingPatterns = yn; + function _n(t2) { + var e = h.filter(t2, function(i) { + var a = i[Ae2]; + return !h.isRegExp(a) && !h.isFunction(a) && !h.has(a, "exec") && !h.isString(a); + }), r = h.map(e, function(i) { + return { message: "Token Type: ->" + i.name + "<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.", type: F.LexerDefinitionErrorType.INVALID_PATTERN, tokenTypes: [i] }; + }), n2 = h.difference(t2, e); + return { errors: r, valid: n2 }; + } + T2.findInvalidPatterns = _n; + var eo = /[^\\][\$]/; + function On(t2) { + var e = function(i) { + hn(a, i); + function a() { + var o = i !== null && i.apply(this, arguments) || this; + return o.found = false, o; + } + return a.prototype.visitEndAnchor = function(o) { + this.found = true; + }, a; + }(dn.BaseRegExpVisitor), r = h.filter(t2, function(i) { + var a = i[Ae2]; + try { + var o = vn.getRegExpAst(a), s = new e; + return s.visit(o), s.found; + } catch (c) { + return eo.test(a.source); + } + }), n2 = h.map(r, function(i) { + return { message: `Unexpected RegExp Anchor Error: + Token Type: ->` + i.name + `<- static 'PATTERN' cannot contain end of input anchor '$' + See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`, type: F.LexerDefinitionErrorType.EOI_ANCHOR_FOUND, tokenTypes: [i] }; + }); + return n2; + } + T2.findEndOfInputAnchor = On; + function Nn(t2) { + var e = h.filter(t2, function(n2) { + var i = n2[Ae2]; + return i.test(""); + }), r = h.map(e, function(n2) { + return { message: "Token Type: ->" + n2.name + "<- static 'PATTERN' must not match an empty string", type: F.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN, tokenTypes: [n2] }; + }); + return r; + } + T2.findEmptyMatchRegExps = Nn; + var to = /[^\\[][\^]|^\^/; + function In2(t2) { + var e = function(i) { + hn(a, i); + function a() { + var o = i !== null && i.apply(this, arguments) || this; + return o.found = false, o; + } + return a.prototype.visitStartAnchor = function(o) { + this.found = true; + }, a; + }(dn.BaseRegExpVisitor), r = h.filter(t2, function(i) { + var a = i[Ae2]; + try { + var o = vn.getRegExpAst(a), s = new e; + return s.visit(o), s.found; + } catch (c) { + return to.test(a.source); + } + }), n2 = h.map(r, function(i) { + return { message: `Unexpected RegExp Anchor Error: + Token Type: ->` + i.name + `<- static 'PATTERN' cannot contain start of input anchor '^' + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`, type: F.LexerDefinitionErrorType.SOI_ANCHOR_FOUND, tokenTypes: [i] }; + }); + return n2; + } + T2.findStartOfInputAnchor = In2; + function kn(t2) { + var e = h.filter(t2, function(n2) { + var i = n2[Ae2]; + return i instanceof RegExp && (i.multiline || i.global); + }), r = h.map(e, function(n2) { + return { message: "Token Type: ->" + n2.name + "<- static 'PATTERN' may NOT contain global('g') or multiline('m')", type: F.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND, tokenTypes: [n2] }; + }); + return r; + } + T2.findUnsupportedFlags = kn; + function Pn(t2) { + var e = [], r = h.map(t2, function(a) { + return h.reduce(t2, function(o, s) { + return a.PATTERN.source === s.PATTERN.source && !h.contains(e, s) && s.PATTERN !== F.Lexer.NA && (e.push(s), o.push(s)), o; + }, []); + }); + r = h.compact(r); + var n2 = h.filter(r, function(a) { + return a.length > 1; + }), i = h.map(n2, function(a) { + var o = h.map(a, function(c) { + return c.name; + }), s = h.first(a).PATTERN; + return { message: "The same RegExp pattern ->" + s + "<-" + ("has been used in all of the following Token Types: " + o.join(", ") + " <-"), type: F.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND, tokenTypes: a }; + }); + return i; + } + T2.findDuplicatePatterns = Pn; + function gn(t2) { + var e = h.filter(t2, function(n2) { + if (!h.has(n2, "GROUP")) + return false; + var i = n2.GROUP; + return i !== F.Lexer.SKIPPED && i !== F.Lexer.NA && !h.isString(i); + }), r = h.map(e, function(n2) { + return { message: "Token Type: ->" + n2.name + "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String", type: F.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND, tokenTypes: [n2] }; + }); + return r; + } + T2.findInvalidGroupType = gn; + function An(t2, e) { + var r = h.filter(t2, function(i) { + return i.PUSH_MODE !== undefined && !h.contains(e, i.PUSH_MODE); + }), n2 = h.map(r, function(i) { + var a = "Token Type: ->" + i.name + "<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->" + i.PUSH_MODE + "<-which does not exist"; + return { message: a, type: F.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST, tokenTypes: [i] }; + }); + return n2; + } + T2.findModesThatDoNotExist = An; + function Rn(t2) { + var e = [], r = h.reduce(t2, function(n2, i, a) { + var o = i.PATTERN; + return o === F.Lexer.NA || (h.isString(o) ? n2.push({ str: o, idx: a, tokenType: i }) : h.isRegExp(o) && no(o) && n2.push({ str: o.source, idx: a, tokenType: i })), n2; + }, []); + return h.forEach(t2, function(n2, i) { + h.forEach(r, function(a) { + var { str: o, idx: s, tokenType: c } = a; + if (i < s && ro(o, n2.PATTERN)) { + var f = "Token: ->" + c.name + `<- can never be matched. +` + ("Because it appears AFTER the Token Type ->" + n2.name + "<-") + `in the lexer's definition. +See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`; + e.push({ message: f, type: F.LexerDefinitionErrorType.UNREACHABLE_PATTERN, tokenTypes: [n2, c] }); + } + }); + }), e; + } + T2.findUnreachablePatterns = Rn; + function ro(t2, e) { + if (h.isRegExp(e)) { + var r = e.exec(t2); + return r !== null && r.index === 0; + } else { + if (h.isFunction(e)) + return e(t2, 0, [], {}); + if (h.has(e, "exec")) + return e.exec(t2, 0, [], {}); + if (typeof e == "string") + return e === t2; + throw Error("non exhaustive match"); + } + } + function no(t2) { + var e = [".", "\\", "[", "]", "|", "^", "$", "(", ")", "?", "*", "+", "{"]; + return h.find(e, function(r) { + return t2.source.indexOf(r) !== -1; + }) === undefined; + } + function _r(t2) { + var e = t2.ignoreCase ? "i" : ""; + return new RegExp("^(?:" + t2.source + ")", e); + } + T2.addStartOfInput = _r; + function gr(t2) { + var e = t2.ignoreCase ? "iy" : "y"; + return new RegExp("" + t2.source, e); + } + T2.addStickyFlag = gr; + function io(t2, e, r) { + var n2 = []; + return h.has(t2, T2.DEFAULT_MODE) || n2.push({ message: "A MultiMode Lexer cannot be initialized without a <" + T2.DEFAULT_MODE + `> property in its definition +`, type: F.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE }), h.has(t2, T2.MODES) || n2.push({ message: "A MultiMode Lexer cannot be initialized without a <" + T2.MODES + `> property in its definition +`, type: F.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY }), h.has(t2, T2.MODES) && h.has(t2, T2.DEFAULT_MODE) && !h.has(t2.modes, t2.defaultMode) && n2.push({ message: "A MultiMode Lexer cannot be initialized with a " + T2.DEFAULT_MODE + ": <" + t2.defaultMode + `>which does not exist +`, type: F.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST }), h.has(t2, T2.MODES) && h.forEach(t2.modes, function(i, a) { + h.forEach(i, function(o, s) { + h.isUndefined(o) && n2.push({ message: "A Lexer cannot be initialized using an undefined Token Type. Mode:" + ("<" + a + "> at index: <" + s + `> +`), type: F.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED }); + }); + }), n2; + } + T2.performRuntimeChecks = io; + function ao(t2, e, r) { + var n2 = [], i = false, a = h.compact(h.flatten(h.mapValues(t2.modes, function(c) { + return c; + }))), o = h.reject(a, function(c) { + return c[Ae2] === F.Lexer.NA; + }), s = Tn(r); + return e && h.forEach(o, function(c) { + var f = En(c, s); + if (f !== false) { + var p = Sn2(c, f), l2 = { message: p, type: f.issue, tokenType: c }; + n2.push(l2); + } else + h.has(c, "LINE_BREAKS") ? c.LINE_BREAKS === true && (i = true) : Ye.canMatchCharCode(s, c.PATTERN) && (i = true); + }), e && !i && n2.push({ message: `Warning: No LINE_BREAKS Found. + This Lexer has been defined to track line and column information, + But none of the Token Types can be identified as matching a line terminator. + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS + for details.`, type: F.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS }), n2; + } + T2.performWarningRuntimeChecks = ao; + function oo(t2) { + var e = {}, r = h.keys(t2); + return h.forEach(r, function(n2) { + var i = t2[n2]; + if (h.isArray(i)) + e[n2] = []; + else + throw Error("non exhaustive match"); + }), e; + } + T2.cloneEmptyGroups = oo; + function Ar(t2) { + var e = t2.PATTERN; + if (h.isRegExp(e)) + return false; + if (h.isFunction(e)) + return true; + if (h.has(e, "exec")) + return true; + if (h.isString(e)) + return false; + throw Error("non exhaustive match"); + } + T2.isCustomPattern = Ar; + function mn(t2) { + return h.isString(t2) && t2.length === 1 ? t2.charCodeAt(0) : false; + } + T2.isShortPattern = mn; + T2.LineTerminatorOptimizedTester = { test: function(t2) { + for (var e = t2.length, r = this.lastIndex;r < e; r++) { + var n2 = t2.charCodeAt(r); + if (n2 === 10) + return this.lastIndex = r + 1, true; + if (n2 === 13) + return t2.charCodeAt(r + 1) === 10 ? this.lastIndex = r + 2 : this.lastIndex = r + 1, true; + } + return false; + }, lastIndex: 0 }; + function En(t2, e) { + if (h.has(t2, "LINE_BREAKS")) + return false; + if (h.isRegExp(t2.PATTERN)) { + try { + Ye.canMatchCharCode(e, t2.PATTERN); + } catch (r) { + return { issue: F.LexerDefinitionErrorType.IDENTIFY_TERMINATOR, errMsg: r.message }; + } + return false; + } else { + if (h.isString(t2.PATTERN)) + return false; + if (Ar(t2)) + return { issue: F.LexerDefinitionErrorType.CUSTOM_LINE_BREAK }; + throw Error("non exhaustive match"); + } + } + function Sn2(t2, e) { + if (e.issue === F.LexerDefinitionErrorType.IDENTIFY_TERMINATOR) + return `Warning: unable to identify line terminator usage in pattern. +` + ("\tThe problem is in the <" + t2.name + `> Token Type +`) + ("\t Root cause: " + e.errMsg + `. +`) + "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR"; + if (e.issue === F.LexerDefinitionErrorType.CUSTOM_LINE_BREAK) + return `Warning: A Custom Token Pattern should specify the option. +` + ("\tThe problem is in the <" + t2.name + `> Token Type +`) + "\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK"; + throw Error("non exhaustive match"); + } + T2.buildLineBreakIssueMessage = Sn2; + function Tn(t2) { + var e = h.map(t2, function(r) { + return h.isString(r) && r.length > 0 ? r.charCodeAt(0) : r; + }); + return e; + } + function Rr(t2, e, r) { + t2[e] === undefined ? t2[e] = [r] : t2[e].push(r); + } + T2.minOptimizationVal = 256; + var Ft2 = []; + function Or(t2) { + return t2 < T2.minOptimizationVal ? t2 : Ft2[t2]; + } + T2.charCodeToOptimizedIndex = Or; + function $a() { + if (h.isEmpty(Ft2)) { + Ft2 = new Array(65536); + for (var t2 = 0;t2 < 65536; t2++) + Ft2[t2] = t2 > 255 ? 255 + ~~(t2 / 255) : t2; + } + } +}); +var Xe = R2((N) => { + Object.defineProperty(N, "__esModule", { value: true }); + N.isTokenType = N.hasExtendingTokensTypesMapProperty = N.hasExtendingTokensTypesProperty = N.hasCategoriesProperty = N.hasShortKeyProperty = N.singleAssignCategoriesToksMap = N.assignCategoriesMapProp = N.assignCategoriesTokensProp = N.assignTokenDefaultProps = N.expandCategories = N.augmentTokenTypes = N.tokenIdxToClass = N.tokenShortNameIdx = N.tokenStructuredMatcherNoCategories = N.tokenStructuredMatcher = undefined; + var V2 = k2(); + function so(t2, e) { + var r = t2.tokenTypeIdx; + return r === e.tokenTypeIdx ? true : e.isParent === true && e.categoryMatchesMap[r] === true; + } + N.tokenStructuredMatcher = so; + function uo(t2, e) { + return t2.tokenTypeIdx === e.tokenTypeIdx; + } + N.tokenStructuredMatcherNoCategories = uo; + N.tokenShortNameIdx = 1; + N.tokenIdxToClass = {}; + function co(t2) { + var e = xn(t2); + Cn(e), Mn(e), Ln(e), V2.forEach(e, function(r) { + r.isParent = r.categoryMatches.length > 0; + }); + } + N.augmentTokenTypes = co; + function xn(t2) { + for (var e = V2.cloneArr(t2), r = t2, n2 = true;n2; ) { + r = V2.compact(V2.flatten(V2.map(r, function(a) { + return a.CATEGORIES; + }))); + var i = V2.difference(r, e); + e = e.concat(i), V2.isEmpty(i) ? n2 = false : r = i; + } + return e; + } + N.expandCategories = xn; + function Cn(t2) { + V2.forEach(t2, function(e) { + bn(e) || (N.tokenIdxToClass[N.tokenShortNameIdx] = e, e.tokenTypeIdx = N.tokenShortNameIdx++), Nr(e) && !V2.isArray(e.CATEGORIES) && (e.CATEGORIES = [e.CATEGORIES]), Nr(e) || (e.CATEGORIES = []), Fn(e) || (e.categoryMatches = []), wn(e) || (e.categoryMatchesMap = {}); + }); + } + N.assignTokenDefaultProps = Cn; + function Ln(t2) { + V2.forEach(t2, function(e) { + e.categoryMatches = [], V2.forEach(e.categoryMatchesMap, function(r, n2) { + e.categoryMatches.push(N.tokenIdxToClass[n2].tokenTypeIdx); + }); + }); + } + N.assignCategoriesTokensProp = Ln; + function Mn(t2) { + V2.forEach(t2, function(e) { + Ir([], e); + }); + } + N.assignCategoriesMapProp = Mn; + function Ir(t2, e) { + V2.forEach(t2, function(r) { + e.categoryMatchesMap[r.tokenTypeIdx] = true; + }), V2.forEach(e.CATEGORIES, function(r) { + var n2 = t2.concat(e); + V2.contains(n2, r) || Ir(n2, r); + }); + } + N.singleAssignCategoriesToksMap = Ir; + function bn(t2) { + return V2.has(t2, "tokenTypeIdx"); + } + N.hasShortKeyProperty = bn; + function Nr(t2) { + return V2.has(t2, "CATEGORIES"); + } + N.hasCategoriesProperty = Nr; + function Fn(t2) { + return V2.has(t2, "categoryMatches"); + } + N.hasExtendingTokensTypesProperty = Fn; + function wn(t2) { + return V2.has(t2, "categoryMatchesMap"); + } + N.hasExtendingTokensTypesMapProperty = wn; + function lo(t2) { + return V2.has(t2, "tokenTypeIdx"); + } + N.isTokenType = lo; +}); +var kr = R2((wt2) => { + Object.defineProperty(wt2, "__esModule", { value: true }); + wt2.defaultLexerErrorProvider = undefined; + wt2.defaultLexerErrorProvider = { buildUnableToPopLexerModeMessage: function(t2) { + return "Unable to pop Lexer Mode after encountering Token ->" + t2.image + "<- The Mode Stack is empty"; + }, buildUnexpectedCharactersMessage: function(t2, e, r, n2, i) { + return "unexpected character: ->" + t2.charAt(e) + "<- at offset: " + e + "," + (" skipped " + r + " characters."); + } }; +}); +var ft = R2((qe) => { + Object.defineProperty(qe, "__esModule", { value: true }); + qe.Lexer = qe.LexerDefinitionErrorType = undefined; + var Ee = Tr(), w = k2(), fo = Xe(), po = kr(), ho = Lt(), vo; + (function(t2) { + t2[t2.MISSING_PATTERN = 0] = "MISSING_PATTERN", t2[t2.INVALID_PATTERN = 1] = "INVALID_PATTERN", t2[t2.EOI_ANCHOR_FOUND = 2] = "EOI_ANCHOR_FOUND", t2[t2.UNSUPPORTED_FLAGS_FOUND = 3] = "UNSUPPORTED_FLAGS_FOUND", t2[t2.DUPLICATE_PATTERNS_FOUND = 4] = "DUPLICATE_PATTERNS_FOUND", t2[t2.INVALID_GROUP_TYPE_FOUND = 5] = "INVALID_GROUP_TYPE_FOUND", t2[t2.PUSH_MODE_DOES_NOT_EXIST = 6] = "PUSH_MODE_DOES_NOT_EXIST", t2[t2.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE = 7] = "MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE", t2[t2.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY = 8] = "MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY", t2[t2.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST = 9] = "MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST", t2[t2.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED = 10] = "LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED", t2[t2.SOI_ANCHOR_FOUND = 11] = "SOI_ANCHOR_FOUND", t2[t2.EMPTY_MATCH_PATTERN = 12] = "EMPTY_MATCH_PATTERN", t2[t2.NO_LINE_BREAKS_FLAGS = 13] = "NO_LINE_BREAKS_FLAGS", t2[t2.UNREACHABLE_PATTERN = 14] = "UNREACHABLE_PATTERN", t2[t2.IDENTIFY_TERMINATOR = 15] = "IDENTIFY_TERMINATOR", t2[t2.CUSTOM_LINE_BREAK = 16] = "CUSTOM_LINE_BREAK"; + })(vo = qe.LexerDefinitionErrorType || (qe.LexerDefinitionErrorType = {})); + var pt = { deferDefinitionErrorsHandling: false, positionTracking: "full", lineTerminatorsPattern: /\n|\r\n?/g, lineTerminatorCharacters: [` +`, "\r"], ensureOptimizations: false, safeMode: false, errorMessageProvider: po.defaultLexerErrorProvider, traceInitPerf: false, skipValidations: false }; + Object.freeze(pt); + var mo = function() { + function t2(e, r) { + var n2 = this; + if (r === undefined && (r = pt), this.lexerDefinition = e, this.lexerDefinitionErrors = [], this.lexerDefinitionWarning = [], this.patternIdxToConfig = {}, this.charCodeToPatternIdxToConfig = {}, this.modes = [], this.emptyGroups = {}, this.config = undefined, this.trackStartLines = true, this.trackEndLines = true, this.hasCustom = false, this.canModeBeOptimized = {}, typeof r == "boolean") + throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. +a boolean 2nd argument is no longer supported`); + this.config = w.merge(pt, r); + var i = this.config.traceInitPerf; + i === true ? (this.traceInitMaxIdent = Infinity, this.traceInitPerf = true) : typeof i == "number" && (this.traceInitMaxIdent = i, this.traceInitPerf = true), this.traceInitIndent = -1, this.TRACE_INIT("Lexer Constructor", function() { + var a, o = true; + n2.TRACE_INIT("Lexer Config handling", function() { + if (n2.config.lineTerminatorsPattern === pt.lineTerminatorsPattern) + n2.config.lineTerminatorsPattern = Ee.LineTerminatorOptimizedTester; + else if (n2.config.lineTerminatorCharacters === pt.lineTerminatorCharacters) + throw Error(`Error: Missing property on the Lexer config. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`); + if (r.safeMode && r.ensureOptimizations) + throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.'); + n2.trackStartLines = /full|onlyStart/i.test(n2.config.positionTracking), n2.trackEndLines = /full/i.test(n2.config.positionTracking), w.isArray(e) ? (a = { modes: {} }, a.modes[Ee.DEFAULT_MODE] = w.cloneArr(e), a[Ee.DEFAULT_MODE] = Ee.DEFAULT_MODE) : (o = false, a = w.cloneObj(e)); + }), n2.config.skipValidations === false && (n2.TRACE_INIT("performRuntimeChecks", function() { + n2.lexerDefinitionErrors = n2.lexerDefinitionErrors.concat(Ee.performRuntimeChecks(a, n2.trackStartLines, n2.config.lineTerminatorCharacters)); + }), n2.TRACE_INIT("performWarningRuntimeChecks", function() { + n2.lexerDefinitionWarning = n2.lexerDefinitionWarning.concat(Ee.performWarningRuntimeChecks(a, n2.trackStartLines, n2.config.lineTerminatorCharacters)); + })), a.modes = a.modes ? a.modes : {}, w.forEach(a.modes, function(p, l2) { + a.modes[l2] = w.reject(p, function(m) { + return w.isUndefined(m); + }); + }); + var s = w.keys(a.modes); + if (w.forEach(a.modes, function(p, l2) { + n2.TRACE_INIT("Mode: <" + l2 + "> processing", function() { + if (n2.modes.push(l2), n2.config.skipValidations === false && n2.TRACE_INIT("validatePatterns", function() { + n2.lexerDefinitionErrors = n2.lexerDefinitionErrors.concat(Ee.validatePatterns(p, s)); + }), w.isEmpty(n2.lexerDefinitionErrors)) { + fo.augmentTokenTypes(p); + var m; + n2.TRACE_INIT("analyzeTokenTypes", function() { + m = Ee.analyzeTokenTypes(p, { lineTerminatorCharacters: n2.config.lineTerminatorCharacters, positionTracking: r.positionTracking, ensureOptimizations: r.ensureOptimizations, safeMode: r.safeMode, tracer: n2.TRACE_INIT.bind(n2) }); + }), n2.patternIdxToConfig[l2] = m.patternIdxToConfig, n2.charCodeToPatternIdxToConfig[l2] = m.charCodeToPatternIdxToConfig, n2.emptyGroups = w.merge(n2.emptyGroups, m.emptyGroups), n2.hasCustom = m.hasCustom || n2.hasCustom, n2.canModeBeOptimized[l2] = m.canBeOptimized; + } + }); + }), n2.defaultMode = a.defaultMode, !w.isEmpty(n2.lexerDefinitionErrors) && !n2.config.deferDefinitionErrorsHandling) { + var c = w.map(n2.lexerDefinitionErrors, function(p) { + return p.message; + }), f = c.join(`----------------------- +`); + throw new Error(`Errors detected in definition of Lexer: +` + f); + } + w.forEach(n2.lexerDefinitionWarning, function(p) { + w.PRINT_WARNING(p.message); + }), n2.TRACE_INIT("Choosing sub-methods implementations", function() { + if (Ee.SUPPORT_STICKY ? (n2.chopInput = w.IDENTITY, n2.match = n2.matchWithTest) : (n2.updateLastIndex = w.NOOP, n2.match = n2.matchWithExec), o && (n2.handleModes = w.NOOP), n2.trackStartLines === false && (n2.computeNewColumn = w.IDENTITY), n2.trackEndLines === false && (n2.updateTokenEndLineColumnLocation = w.NOOP), /full/i.test(n2.config.positionTracking)) + n2.createTokenInstance = n2.createFullToken; + else if (/onlyStart/i.test(n2.config.positionTracking)) + n2.createTokenInstance = n2.createStartOnlyToken; + else if (/onlyOffset/i.test(n2.config.positionTracking)) + n2.createTokenInstance = n2.createOffsetOnlyToken; + else + throw Error('Invalid config option: "' + n2.config.positionTracking + '"'); + n2.hasCustom ? (n2.addToken = n2.addTokenUsingPush, n2.handlePayload = n2.handlePayloadWithCustom) : (n2.addToken = n2.addTokenUsingMemberAccess, n2.handlePayload = n2.handlePayloadNoCustom); + }), n2.TRACE_INIT("Failed Optimization Warnings", function() { + var p = w.reduce(n2.canModeBeOptimized, function(l2, m, v) { + return m === false && l2.push(v), l2; + }, []); + if (r.ensureOptimizations && !w.isEmpty(p)) + throw Error("Lexer Modes: < " + p.join(", ") + ` > cannot be optimized. + Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. + Or inspect the console log for details on how to resolve these issues.`); + }), n2.TRACE_INIT("clearRegExpParserCache", function() { + ho.clearRegExpParserCache(); + }), n2.TRACE_INIT("toFastProperties", function() { + w.toFastProperties(n2); + }); + }); + } + return t2.prototype.tokenize = function(e, r) { + if (r === undefined && (r = this.defaultMode), !w.isEmpty(this.lexerDefinitionErrors)) { + var n2 = w.map(this.lexerDefinitionErrors, function(o) { + return o.message; + }), i = n2.join(`----------------------- +`); + throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: +` + i); + } + var a = this.tokenizeInternal(e, r); + return a; + }, t2.prototype.tokenizeInternal = function(e, r) { + var n2 = this, i, a, o, s, c, f, p, l2, m, v, u2, d, A2, _2, g3, y = e, b = y.length, L = 0, se2 = 0, fe = this.hasCustom ? 0 : Math.floor(e.length / 10), Z2 = new Array(fe), ue3 = [], Q2 = this.trackStartLines ? 1 : undefined, te3 = this.trackStartLines ? 1 : undefined, xe = Ee.cloneEmptyGroups(this.emptyGroups), it2 = this.trackStartLines, at = this.config.lineTerminatorsPattern, Ke2 = 0, we2 = [], ot = [], It = [], Qr2 = []; + Object.freeze(Qr2); + var st = undefined; + function Jr2() { + return we2; + } + function en(J2) { + var lt = Ee.charCodeToOptimizedIndex(J2), ze = ot[lt]; + return ze === undefined ? Qr2 : ze; + } + var wa = function(J2) { + if (It.length === 1 && J2.tokenType.PUSH_MODE === undefined) { + var lt = n2.config.errorMessageProvider.buildUnableToPopLexerModeMessage(J2); + ue3.push({ offset: J2.startOffset, line: J2.startLine !== undefined ? J2.startLine : undefined, column: J2.startColumn !== undefined ? J2.startColumn : undefined, length: J2.image.length, message: lt }); + } else { + It.pop(); + var ze = w.last(It); + we2 = n2.patternIdxToConfig[ze], ot = n2.charCodeToPatternIdxToConfig[ze], Ke2 = we2.length; + var Ua = n2.canModeBeOptimized[ze] && n2.config.safeMode === false; + ot && Ua ? st = en : st = Jr2; + } + }; + function tn2(J2) { + It.push(J2), ot = this.charCodeToPatternIdxToConfig[J2], we2 = this.patternIdxToConfig[J2], Ke2 = we2.length, Ke2 = we2.length; + var lt = this.canModeBeOptimized[J2] && this.config.safeMode === false; + ot && lt ? st = en : st = Jr2; + } + tn2.call(this, r); + for (var me;L < b; ) { + c = null; + var rn2 = y.charCodeAt(L), nn = st(rn2), Da = nn.length; + for (i = 0;i < Da; i++) { + me = nn[i]; + var De = me.pattern; + f = null; + var ut2 = me.short; + if (ut2 !== false ? rn2 === ut2 && (c = De) : me.isCustom === true ? (g3 = De.exec(y, L, Z2, xe), g3 !== null ? (c = g3[0], g3.payload !== undefined && (f = g3.payload)) : c = null) : (this.updateLastIndex(De, L), c = this.match(De, e, L)), c !== null) { + if (s = me.longerAlt, s !== undefined) { + var fr = we2[s], pr = fr.pattern; + p = null, fr.isCustom === true ? (g3 = pr.exec(y, L, Z2, xe), g3 !== null ? (o = g3[0], g3.payload !== undefined && (p = g3.payload)) : o = null) : (this.updateLastIndex(pr, L), o = this.match(pr, e, L)), o && o.length > c.length && (c = o, f = p, me = fr); + } + break; + } + } + if (c !== null) { + if (l2 = c.length, m = me.group, m !== undefined && (v = me.tokenTypeIdx, u2 = this.createTokenInstance(c, L, v, me.tokenType, Q2, te3, l2), this.handlePayload(u2, f), m === false ? se2 = this.addToken(Z2, se2, u2) : xe[m].push(u2)), e = this.chopInput(e, l2), L = L + l2, te3 = this.computeNewColumn(te3, l2), it2 === true && me.canLineTerminator === true) { + var kt = 0, hr = undefined, dr = undefined; + at.lastIndex = 0; + do + hr = at.test(c), hr === true && (dr = at.lastIndex - 1, kt++); + while (hr === true); + kt !== 0 && (Q2 = Q2 + kt, te3 = l2 - dr, this.updateTokenEndLineColumnLocation(u2, m, dr, kt, Q2, te3, l2)); + } + this.handleModes(me, wa, tn2, u2); + } else { + for (var vr = L, an = Q2, on = te3, ct2 = false;!ct2 && L < b; ) + for (A2 = y.charCodeAt(L), e = this.chopInput(e, 1), L++, a = 0;a < Ke2; a++) { + var mr = we2[a], De = mr.pattern, ut2 = mr.short; + if (ut2 !== false ? y.charCodeAt(L) === ut2 && (ct2 = true) : mr.isCustom === true ? ct2 = De.exec(y, L, Z2, xe) !== null : (this.updateLastIndex(De, L), ct2 = De.exec(e) !== null), ct2 === true) + break; + } + d = L - vr, _2 = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(y, vr, d, an, on), ue3.push({ offset: vr, line: an, column: on, length: d, message: _2 }); + } + } + return this.hasCustom || (Z2.length = se2), { tokens: Z2, groups: xe, errors: ue3 }; + }, t2.prototype.handleModes = function(e, r, n2, i) { + if (e.pop === true) { + var a = e.push; + r(i), a !== undefined && n2.call(this, a); + } else + e.push !== undefined && n2.call(this, e.push); + }, t2.prototype.chopInput = function(e, r) { + return e.substring(r); + }, t2.prototype.updateLastIndex = function(e, r) { + e.lastIndex = r; + }, t2.prototype.updateTokenEndLineColumnLocation = function(e, r, n2, i, a, o, s) { + var c, f; + r !== undefined && (c = n2 === s - 1, f = c ? -1 : 0, i === 1 && c === true || (e.endLine = a + f, e.endColumn = o - 1 + -f)); + }, t2.prototype.computeNewColumn = function(e, r) { + return e + r; + }, t2.prototype.createTokenInstance = function() { + for (var e = [], r = 0;r < arguments.length; r++) + e[r] = arguments[r]; + return null; + }, t2.prototype.createOffsetOnlyToken = function(e, r, n2, i) { + return { image: e, startOffset: r, tokenTypeIdx: n2, tokenType: i }; + }, t2.prototype.createStartOnlyToken = function(e, r, n2, i, a, o) { + return { image: e, startOffset: r, startLine: a, startColumn: o, tokenTypeIdx: n2, tokenType: i }; + }, t2.prototype.createFullToken = function(e, r, n2, i, a, o, s) { + return { image: e, startOffset: r, endOffset: r + s - 1, startLine: a, endLine: a, startColumn: o, endColumn: o + s - 1, tokenTypeIdx: n2, tokenType: i }; + }, t2.prototype.addToken = function(e, r, n2) { + return 666; + }, t2.prototype.addTokenUsingPush = function(e, r, n2) { + return e.push(n2), r; + }, t2.prototype.addTokenUsingMemberAccess = function(e, r, n2) { + return e[r] = n2, r++, r; + }, t2.prototype.handlePayload = function(e, r) { + }, t2.prototype.handlePayloadNoCustom = function(e, r) { + }, t2.prototype.handlePayloadWithCustom = function(e, r) { + r !== null && (e.payload = r); + }, t2.prototype.match = function(e, r, n2) { + return null; + }, t2.prototype.matchWithTest = function(e, r, n2) { + var i = e.test(r); + return i === true ? r.substring(n2, e.lastIndex) : null; + }, t2.prototype.matchWithExec = function(e, r) { + var n2 = e.exec(r); + return n2 !== null ? n2[0] : n2; + }, t2.prototype.TRACE_INIT = function(e, r) { + if (this.traceInitPerf === true) { + this.traceInitIndent++; + var n2 = new Array(this.traceInitIndent + 1).join("\t"); + this.traceInitIndent < this.traceInitMaxIdent && console.log(n2 + "--> <" + e + ">"); + var i = w.timer(r), a = i.time, o = i.value, s = a > 10 ? console.warn : console.log; + return this.traceInitIndent < this.traceInitMaxIdent && s(n2 + "<-- <" + e + "> time: " + a + "ms"), this.traceInitIndent--, o; + } else + return r(); + }, t2.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.", t2.NA = /NOT_APPLICABLE/, t2; + }(); + qe.Lexer = mo; +}); +var Ue = R2((H) => { + Object.defineProperty(H, "__esModule", { value: true }); + H.tokenMatcher = H.createTokenInstance = H.EOF = H.createToken = H.hasTokenLabel = H.tokenName = H.tokenLabel = undefined; + var Te = k2(), Eo = ft(), Pr = Xe(); + function To(t2) { + return Dn(t2) ? t2.LABEL : t2.name; + } + H.tokenLabel = To; + function yo(t2) { + return t2.name; + } + H.tokenName = yo; + function Dn(t2) { + return Te.isString(t2.LABEL) && t2.LABEL !== ""; + } + H.hasTokenLabel = Dn; + var _o = "parent", Un = "categories", Gn = "label", Wn = "group", Bn = "push_mode", qn = "pop_mode", jn = "longer_alt", Vn = "line_breaks", Kn = "start_chars_hint"; + function zn(t2) { + return go(t2); + } + H.createToken = zn; + function go(t2) { + var e = t2.pattern, r = {}; + if (r.name = t2.name, Te.isUndefined(e) || (r.PATTERN = e), Te.has(t2, _o)) + throw `The parent property is no longer supported. +See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.`; + return Te.has(t2, Un) && (r.CATEGORIES = t2[Un]), Pr.augmentTokenTypes([r]), Te.has(t2, Gn) && (r.LABEL = t2[Gn]), Te.has(t2, Wn) && (r.GROUP = t2[Wn]), Te.has(t2, qn) && (r.POP_MODE = t2[qn]), Te.has(t2, Bn) && (r.PUSH_MODE = t2[Bn]), Te.has(t2, jn) && (r.LONGER_ALT = t2[jn]), Te.has(t2, Vn) && (r.LINE_BREAKS = t2[Vn]), Te.has(t2, Kn) && (r.START_CHARS_HINT = t2[Kn]), r; + } + H.EOF = zn({ name: "EOF", pattern: Eo.Lexer.NA }); + Pr.augmentTokenTypes([H.EOF]); + function Ao(t2, e, r, n2, i, a, o, s) { + return { image: e, startOffset: r, endOffset: n2, startLine: i, endLine: a, startColumn: o, endColumn: s, tokenTypeIdx: t2.tokenTypeIdx, tokenType: t2 }; + } + H.createTokenInstance = Ao; + function Ro(t2, e) { + return Pr.tokenStructuredMatcher(t2, e); + } + H.tokenMatcher = Ro; +}); +var ne = R2((S) => { + var Le = S && S.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(S, "__esModule", { value: true }); + S.serializeProduction = S.serializeGrammar = S.Terminal = S.Alternation = S.RepetitionWithSeparator = S.Repetition = S.RepetitionMandatoryWithSeparator = S.RepetitionMandatory = S.Option = S.Alternative = S.Rule = S.NonTerminal = S.AbstractProduction = undefined; + var G2 = k2(), Oo = Ue(), Re = function() { + function t2(e) { + this._definition = e; + } + return Object.defineProperty(t2.prototype, "definition", { get: function() { + return this._definition; + }, set: function(e) { + this._definition = e; + }, enumerable: false, configurable: true }), t2.prototype.accept = function(e) { + e.visit(this), G2.forEach(this.definition, function(r) { + r.accept(e); + }); + }, t2; + }(); + S.AbstractProduction = Re; + var Hn = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, []) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return Object.defineProperty(e.prototype, "definition", { get: function() { + return this.referencedRule !== undefined ? this.referencedRule.definition : []; + }, set: function(r) { + }, enumerable: false, configurable: true }), e.prototype.accept = function(r) { + r.visit(this); + }, e; + }(Re); + S.NonTerminal = Hn; + var Yn = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.orgText = "", G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.Rule = Yn; + var Xn = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.ignoreAmbiguities = false, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.Alternative = Xn; + var $n = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.Option = $n; + var Zn = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.RepetitionMandatory = Zn; + var Qn = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.RepetitionMandatoryWithSeparator = Qn; + var Jn = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.Repetition = Jn; + var ei = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.idx = 1, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return e; + }(Re); + S.RepetitionWithSeparator = ei; + var ti = function(t2) { + Le(e, t2); + function e(r) { + var n2 = t2.call(this, r.definition) || this; + return n2.idx = 1, n2.ignoreAmbiguities = false, n2.hasPredicates = false, G2.assign(n2, G2.pick(r, function(i) { + return i !== undefined; + })), n2; + } + return Object.defineProperty(e.prototype, "definition", { get: function() { + return this._definition; + }, set: function(r) { + this._definition = r; + }, enumerable: false, configurable: true }), e; + }(Re); + S.Alternation = ti; + var Dt = function() { + function t2(e) { + this.idx = 1, G2.assign(this, G2.pick(e, function(r) { + return r !== undefined; + })); + } + return t2.prototype.accept = function(e) { + e.visit(this); + }, t2; + }(); + S.Terminal = Dt; + function No(t2) { + return G2.map(t2, ht); + } + S.serializeGrammar = No; + function ht(t2) { + function e(i) { + return G2.map(i, ht); + } + if (t2 instanceof Hn) + return { type: "NonTerminal", name: t2.nonTerminalName, idx: t2.idx }; + if (t2 instanceof Xn) + return { type: "Alternative", definition: e(t2.definition) }; + if (t2 instanceof $n) + return { type: "Option", idx: t2.idx, definition: e(t2.definition) }; + if (t2 instanceof Zn) + return { type: "RepetitionMandatory", idx: t2.idx, definition: e(t2.definition) }; + if (t2 instanceof Qn) + return { type: "RepetitionMandatoryWithSeparator", idx: t2.idx, separator: ht(new Dt({ terminalType: t2.separator })), definition: e(t2.definition) }; + if (t2 instanceof ei) + return { type: "RepetitionWithSeparator", idx: t2.idx, separator: ht(new Dt({ terminalType: t2.separator })), definition: e(t2.definition) }; + if (t2 instanceof Jn) + return { type: "Repetition", idx: t2.idx, definition: e(t2.definition) }; + if (t2 instanceof ti) + return { type: "Alternation", idx: t2.idx, definition: e(t2.definition) }; + if (t2 instanceof Dt) { + var r = { type: "Terminal", name: t2.terminalType.name, label: Oo.tokenLabel(t2.terminalType), idx: t2.idx }, n2 = t2.terminalType.PATTERN; + return t2.terminalType.PATTERN && (r.pattern = G2.isRegExp(n2) ? n2.source : n2), r; + } else { + if (t2 instanceof Yn) + return { type: "Rule", name: t2.name, orgText: t2.orgText, definition: e(t2.definition) }; + throw Error("non exhaustive match"); + } + } + S.serializeProduction = ht; +}); +var Gt = R2((Ut2) => { + Object.defineProperty(Ut2, "__esModule", { value: true }); + Ut2.RestWalker = undefined; + var Sr = k2(), ie = ne(), Io = function() { + function t2() { + } + return t2.prototype.walk = function(e, r) { + var n2 = this; + r === undefined && (r = []), Sr.forEach(e.definition, function(i, a) { + var o = Sr.drop(e.definition, a + 1); + if (i instanceof ie.NonTerminal) + n2.walkProdRef(i, o, r); + else if (i instanceof ie.Terminal) + n2.walkTerminal(i, o, r); + else if (i instanceof ie.Alternative) + n2.walkFlat(i, o, r); + else if (i instanceof ie.Option) + n2.walkOption(i, o, r); + else if (i instanceof ie.RepetitionMandatory) + n2.walkAtLeastOne(i, o, r); + else if (i instanceof ie.RepetitionMandatoryWithSeparator) + n2.walkAtLeastOneSep(i, o, r); + else if (i instanceof ie.RepetitionWithSeparator) + n2.walkManySep(i, o, r); + else if (i instanceof ie.Repetition) + n2.walkMany(i, o, r); + else if (i instanceof ie.Alternation) + n2.walkOr(i, o, r); + else + throw Error("non exhaustive match"); + }); + }, t2.prototype.walkTerminal = function(e, r, n2) { + }, t2.prototype.walkProdRef = function(e, r, n2) { + }, t2.prototype.walkFlat = function(e, r, n2) { + var i = r.concat(n2); + this.walk(e, i); + }, t2.prototype.walkOption = function(e, r, n2) { + var i = r.concat(n2); + this.walk(e, i); + }, t2.prototype.walkAtLeastOne = function(e, r, n2) { + var i = [new ie.Option({ definition: e.definition })].concat(r, n2); + this.walk(e, i); + }, t2.prototype.walkAtLeastOneSep = function(e, r, n2) { + var i = ri(e, r, n2); + this.walk(e, i); + }, t2.prototype.walkMany = function(e, r, n2) { + var i = [new ie.Option({ definition: e.definition })].concat(r, n2); + this.walk(e, i); + }, t2.prototype.walkManySep = function(e, r, n2) { + var i = ri(e, r, n2); + this.walk(e, i); + }, t2.prototype.walkOr = function(e, r, n2) { + var i = this, a = r.concat(n2); + Sr.forEach(e.definition, function(o) { + var s = new ie.Alternative({ definition: [o] }); + i.walk(s, a); + }); + }, t2; + }(); + Ut2.RestWalker = Io; + function ri(t2, e, r) { + var n2 = [new ie.Option({ definition: [new ie.Terminal({ terminalType: t2.separator })].concat(t2.definition) })], i = n2.concat(e, r); + return i; + } +}); +var $e = R2((Wt) => { + Object.defineProperty(Wt, "__esModule", { value: true }); + Wt.GAstVisitor = undefined; + var Oe = ne(), ko = function() { + function t2() { + } + return t2.prototype.visit = function(e) { + var r = e; + switch (r.constructor) { + case Oe.NonTerminal: + return this.visitNonTerminal(r); + case Oe.Alternative: + return this.visitAlternative(r); + case Oe.Option: + return this.visitOption(r); + case Oe.RepetitionMandatory: + return this.visitRepetitionMandatory(r); + case Oe.RepetitionMandatoryWithSeparator: + return this.visitRepetitionMandatoryWithSeparator(r); + case Oe.RepetitionWithSeparator: + return this.visitRepetitionWithSeparator(r); + case Oe.Repetition: + return this.visitRepetition(r); + case Oe.Alternation: + return this.visitAlternation(r); + case Oe.Terminal: + return this.visitTerminal(r); + case Oe.Rule: + return this.visitRule(r); + default: + throw Error("non exhaustive match"); + } + }, t2.prototype.visitNonTerminal = function(e) { + }, t2.prototype.visitAlternative = function(e) { + }, t2.prototype.visitOption = function(e) { + }, t2.prototype.visitRepetition = function(e) { + }, t2.prototype.visitRepetitionMandatory = function(e) { + }, t2.prototype.visitRepetitionMandatoryWithSeparator = function(e) { + }, t2.prototype.visitRepetitionWithSeparator = function(e) { + }, t2.prototype.visitAlternation = function(e) { + }, t2.prototype.visitTerminal = function(e) { + }, t2.prototype.visitRule = function(e) { + }, t2; + }(); + Wt.GAstVisitor = ko; +}); +var vt = R2((X) => { + var Po = X && X.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(X, "__esModule", { value: true }); + X.collectMethods = X.DslMethodsCollectorVisitor = X.getProductionDslName = X.isBranchingProd = X.isOptionalProd = X.isSequenceProd = undefined; + var dt = k2(), W = ne(), So = $e(); + function xo(t2) { + return t2 instanceof W.Alternative || t2 instanceof W.Option || t2 instanceof W.Repetition || t2 instanceof W.RepetitionMandatory || t2 instanceof W.RepetitionMandatoryWithSeparator || t2 instanceof W.RepetitionWithSeparator || t2 instanceof W.Terminal || t2 instanceof W.Rule; + } + X.isSequenceProd = xo; + function xr(t2, e) { + e === undefined && (e = []); + var r = t2 instanceof W.Option || t2 instanceof W.Repetition || t2 instanceof W.RepetitionWithSeparator; + return r ? true : t2 instanceof W.Alternation ? dt.some(t2.definition, function(n2) { + return xr(n2, e); + }) : t2 instanceof W.NonTerminal && dt.contains(e, t2) ? false : t2 instanceof W.AbstractProduction ? (t2 instanceof W.NonTerminal && e.push(t2), dt.every(t2.definition, function(n2) { + return xr(n2, e); + })) : false; + } + X.isOptionalProd = xr; + function Co(t2) { + return t2 instanceof W.Alternation; + } + X.isBranchingProd = Co; + function Lo(t2) { + if (t2 instanceof W.NonTerminal) + return "SUBRULE"; + if (t2 instanceof W.Option) + return "OPTION"; + if (t2 instanceof W.Alternation) + return "OR"; + if (t2 instanceof W.RepetitionMandatory) + return "AT_LEAST_ONE"; + if (t2 instanceof W.RepetitionMandatoryWithSeparator) + return "AT_LEAST_ONE_SEP"; + if (t2 instanceof W.RepetitionWithSeparator) + return "MANY_SEP"; + if (t2 instanceof W.Repetition) + return "MANY"; + if (t2 instanceof W.Terminal) + return "CONSUME"; + throw Error("non exhaustive match"); + } + X.getProductionDslName = Lo; + var ni = function(t2) { + Po(e, t2); + function e() { + var r = t2 !== null && t2.apply(this, arguments) || this; + return r.separator = "-", r.dslMethods = { option: [], alternation: [], repetition: [], repetitionWithSeparator: [], repetitionMandatory: [], repetitionMandatoryWithSeparator: [] }, r; + } + return e.prototype.reset = function() { + this.dslMethods = { option: [], alternation: [], repetition: [], repetitionWithSeparator: [], repetitionMandatory: [], repetitionMandatoryWithSeparator: [] }; + }, e.prototype.visitTerminal = function(r) { + var n2 = r.terminalType.name + this.separator + "Terminal"; + dt.has(this.dslMethods, n2) || (this.dslMethods[n2] = []), this.dslMethods[n2].push(r); + }, e.prototype.visitNonTerminal = function(r) { + var n2 = r.nonTerminalName + this.separator + "Terminal"; + dt.has(this.dslMethods, n2) || (this.dslMethods[n2] = []), this.dslMethods[n2].push(r); + }, e.prototype.visitOption = function(r) { + this.dslMethods.option.push(r); + }, e.prototype.visitRepetitionWithSeparator = function(r) { + this.dslMethods.repetitionWithSeparator.push(r); + }, e.prototype.visitRepetitionMandatory = function(r) { + this.dslMethods.repetitionMandatory.push(r); + }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) { + this.dslMethods.repetitionMandatoryWithSeparator.push(r); + }, e.prototype.visitRepetition = function(r) { + this.dslMethods.repetition.push(r); + }, e.prototype.visitAlternation = function(r) { + this.dslMethods.alternation.push(r); + }, e; + }(So.GAstVisitor); + X.DslMethodsCollectorVisitor = ni; + var Bt = new ni; + function Mo2(t2) { + Bt.reset(), t2.accept(Bt); + var e = Bt.dslMethods; + return Bt.reset(), e; + } + X.collectMethods = Mo2; +}); +var Lr = R2((Ne) => { + Object.defineProperty(Ne, "__esModule", { value: true }); + Ne.firstForTerminal = Ne.firstForBranching = Ne.firstForSequence = Ne.first = undefined; + var qt = k2(), ii = ne(), Cr2 = vt(); + function jt(t2) { + if (t2 instanceof ii.NonTerminal) + return jt(t2.referencedRule); + if (t2 instanceof ii.Terminal) + return si(t2); + if (Cr2.isSequenceProd(t2)) + return ai(t2); + if (Cr2.isBranchingProd(t2)) + return oi(t2); + throw Error("non exhaustive match"); + } + Ne.first = jt; + function ai(t2) { + for (var e = [], r = t2.definition, n2 = 0, i = r.length > n2, a, o = true;i && o; ) + a = r[n2], o = Cr2.isOptionalProd(a), e = e.concat(jt(a)), n2 = n2 + 1, i = r.length > n2; + return qt.uniq(e); + } + Ne.firstForSequence = ai; + function oi(t2) { + var e = qt.map(t2.definition, function(r) { + return jt(r); + }); + return qt.uniq(qt.flatten(e)); + } + Ne.firstForBranching = oi; + function si(t2) { + return [t2.terminalType]; + } + Ne.firstForTerminal = si; +}); +var Mr = R2((Vt) => { + Object.defineProperty(Vt, "__esModule", { value: true }); + Vt.IN = undefined; + Vt.IN = "_~IN~_"; +}); +var pi2 = R2((he) => { + var bo = he && he.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(he, "__esModule", { value: true }); + he.buildInProdFollowPrefix = he.buildBetweenProdsFollowPrefix = he.computeAllProdsFollows = he.ResyncFollowsWalker = undefined; + var Fo = Gt(), wo = Lr(), ui = k2(), ci = Mr(), Do = ne(), fi = function(t2) { + bo(e, t2); + function e(r) { + var n2 = t2.call(this) || this; + return n2.topProd = r, n2.follows = {}, n2; + } + return e.prototype.startWalking = function() { + return this.walk(this.topProd), this.follows; + }, e.prototype.walkTerminal = function(r, n2, i) { + }, e.prototype.walkProdRef = function(r, n2, i) { + var a = li(r.referencedRule, r.idx) + this.topProd.name, o = n2.concat(i), s = new Do.Alternative({ definition: o }), c = wo.first(s); + this.follows[a] = c; + }, e; + }(Fo.RestWalker); + he.ResyncFollowsWalker = fi; + function Uo(t2) { + var e = {}; + return ui.forEach(t2, function(r) { + var n2 = new fi(r).startWalking(); + ui.assign(e, n2); + }), e; + } + he.computeAllProdsFollows = Uo; + function li(t2, e) { + return t2.name + e + ci.IN; + } + he.buildBetweenProdsFollowPrefix = li; + function Go(t2) { + var e = t2.terminalType.name; + return e + t2.idx + ci.IN; + } + he.buildInProdFollowPrefix = Go; +}); +var mt = R2((Me) => { + Object.defineProperty(Me, "__esModule", { value: true }); + Me.defaultGrammarValidatorErrorProvider = Me.defaultGrammarResolverErrorProvider = Me.defaultParserErrorProvider = undefined; + var Ze2 = Ue(), Wo = k2(), ye = k2(), br = ne(), hi = vt(); + Me.defaultParserErrorProvider = { buildMismatchTokenMessage: function(t2) { + var { expected: e, actual: r, previous: n2, ruleName: i } = t2, a = Ze2.hasTokenLabel(e), o = a ? "--> " + Ze2.tokenLabel(e) + " <--" : "token of type --> " + e.name + " <--", s = "Expecting " + o + " but found --> '" + r.image + "' <--"; + return s; + }, buildNotAllInputParsedMessage: function(t2) { + var { firstRedundant: e, ruleName: r } = t2; + return "Redundant input, expecting EOF but found: " + e.image; + }, buildNoViableAltMessage: function(t2) { + var { expectedPathsPerAlt: e, actual: r, previous: n2, customUserDescription: i, ruleName: a } = t2, o = "Expecting: ", s = ye.first(r).image, c = ` +but found: '` + s + "'"; + if (i) + return o + i + c; + var f = ye.reduce(e, function(v, u2) { + return v.concat(u2); + }, []), p = ye.map(f, function(v) { + return "[" + ye.map(v, function(u2) { + return Ze2.tokenLabel(u2); + }).join(", ") + "]"; + }), l2 = ye.map(p, function(v, u2) { + return " " + (u2 + 1) + ". " + v; + }), m = `one of these possible Token sequences: +` + l2.join(` +`); + return o + m + c; + }, buildEarlyExitMessage: function(t2) { + var { expectedIterationPaths: e, actual: r, customUserDescription: n2, ruleName: i } = t2, a = "Expecting: ", o = ye.first(r).image, s = ` +but found: '` + o + "'"; + if (n2) + return a + n2 + s; + var c = ye.map(e, function(p) { + return "[" + ye.map(p, function(l2) { + return Ze2.tokenLabel(l2); + }).join(",") + "]"; + }), f = `expecting at least one iteration which starts with one of these possible Token sequences:: + ` + ("<" + c.join(" ,") + ">"); + return a + f + s; + } }; + Object.freeze(Me.defaultParserErrorProvider); + Me.defaultGrammarResolverErrorProvider = { buildRuleNotFoundError: function(t2, e) { + var r = "Invalid grammar, reference to a rule which is not defined: ->" + e.nonTerminalName + `<- +inside top level rule: ->` + t2.name + "<-"; + return r; + } }; + Me.defaultGrammarValidatorErrorProvider = { buildDuplicateFoundError: function(t2, e) { + function r(p) { + return p instanceof br.Terminal ? p.terminalType.name : p instanceof br.NonTerminal ? p.nonTerminalName : ""; + } + var n2 = t2.name, i = ye.first(e), a = i.idx, o = hi.getProductionDslName(i), s = r(i), c = a > 0, f = "->" + o + (c ? a : "") + "<- " + (s ? "with argument: ->" + s + "<-" : "") + ` + appears more than once (` + e.length + " times) in the top level rule: ->" + n2 + `<-. + For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES + `; + return f = f.replace(/[ \t]+/g, " "), f = f.replace(/\s\s+/g, ` +`), f; + }, buildNamespaceConflictError: function(t2) { + var e = `Namespace conflict found in grammar. +` + ("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <" + t2.name + `>. +`) + `To resolve this make sure each Terminal and Non-Terminal names are unique +This is easy to accomplish by using the convention that Terminal names start with an uppercase letter +and Non-Terminal names start with a lower case letter.`; + return e; + }, buildAlternationPrefixAmbiguityError: function(t2) { + var e = ye.map(t2.prefixPath, function(i) { + return Ze2.tokenLabel(i); + }).join(", "), r = t2.alternation.idx === 0 ? "" : t2.alternation.idx, n2 = "Ambiguous alternatives: <" + t2.ambiguityIndices.join(" ,") + `> due to common lookahead prefix +` + ("in inside <" + t2.topLevelRule.name + `> Rule, +`) + ("<" + e + `> may appears as a prefix path in all these alternatives. +`) + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX +For Further details.`; + return n2; + }, buildAlternationAmbiguityError: function(t2) { + var e = ye.map(t2.prefixPath, function(i) { + return Ze2.tokenLabel(i); + }).join(", "), r = t2.alternation.idx === 0 ? "" : t2.alternation.idx, n2 = "Ambiguous Alternatives Detected: <" + t2.ambiguityIndices.join(" ,") + "> in " + (" inside <" + t2.topLevelRule.name + `> Rule, +`) + ("<" + e + `> may appears as a prefix path in all these alternatives. +`); + return n2 = n2 + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`, n2; + }, buildEmptyRepetitionError: function(t2) { + var e = hi.getProductionDslName(t2.repetition); + t2.repetition.idx !== 0 && (e += t2.repetition.idx); + var r = "The repetition <" + e + "> within Rule <" + t2.topLevelRule.name + `> can never consume any tokens. +This could lead to an infinite loop.`; + return r; + }, buildTokenNameError: function(t2) { + return "deprecated"; + }, buildEmptyAlternationError: function(t2) { + var e = "Ambiguous empty alternative: <" + (t2.emptyChoiceIdx + 1) + ">" + (" in inside <" + t2.topLevelRule.name + `> Rule. +`) + "Only the last alternative may be an empty alternative."; + return e; + }, buildTooManyAlternativesError: function(t2) { + var e = `An Alternation cannot have more than 256 alternatives: +` + (" inside <" + t2.topLevelRule.name + `> Rule. + has ` + (t2.alternation.definition.length + 1) + " alternatives."); + return e; + }, buildLeftRecursionError: function(t2) { + var e = t2.topLevelRule.name, r = Wo.map(t2.leftRecursionPath, function(a) { + return a.name; + }), n2 = e + " --> " + r.concat([e]).join(" --> "), i = `Left Recursion found in grammar. +` + ("rule: <" + e + `> can be invoked from itself (directly or indirectly) +`) + (`without consuming any Tokens. The grammar path that causes this is: + ` + n2 + ` +`) + ` To fix this refactor your grammar to remove the left recursion. +see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring.`; + return i; + }, buildInvalidRuleNameError: function(t2) { + return "deprecated"; + }, buildDuplicateRuleNameError: function(t2) { + var e; + t2.topLevelRule instanceof br.Rule ? e = t2.topLevelRule.name : e = t2.topLevelRule; + var r = "Duplicate definition, rule: ->" + e + "<- is already defined in the grammar: ->" + t2.grammarName + "<-"; + return r; + } }; +}); +var mi = R2((Ge) => { + var Bo = Ge && Ge.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(Ge, "__esModule", { value: true }); + Ge.GastRefResolverVisitor = Ge.resolveGrammar = undefined; + var qo = ce2(), di2 = k2(), jo = $e(); + function Vo(t2, e) { + var r = new vi(t2, e); + return r.resolveRefs(), r.errors; + } + Ge.resolveGrammar = Vo; + var vi = function(t2) { + Bo(e, t2); + function e(r, n2) { + var i = t2.call(this) || this; + return i.nameToTopRule = r, i.errMsgProvider = n2, i.errors = [], i; + } + return e.prototype.resolveRefs = function() { + var r = this; + di2.forEach(di2.values(this.nameToTopRule), function(n2) { + r.currTopLevel = n2, n2.accept(r); + }); + }, e.prototype.visitNonTerminal = function(r) { + var n2 = this.nameToTopRule[r.nonTerminalName]; + if (n2) + r.referencedRule = n2; + else { + var i = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, r); + this.errors.push({ message: i, type: qo.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF, ruleName: this.currTopLevel.name, unresolvedRefName: r.nonTerminalName }); + } + }, e; + }(jo.GAstVisitor); + Ge.GastRefResolverVisitor = vi; +}); +var Tt2 = R2((j2) => { + var je = j2 && j2.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(j2, "__esModule", { value: true }); + j2.nextPossibleTokensAfter = j2.possiblePathsFrom = j2.NextTerminalAfterAtLeastOneSepWalker = j2.NextTerminalAfterAtLeastOneWalker = j2.NextTerminalAfterManySepWalker = j2.NextTerminalAfterManyWalker = j2.AbstractNextTerminalAfterProductionWalker = j2.NextAfterTokenWalker = j2.AbstractNextPossibleTokensWalker = undefined; + var Ei = Gt(), I3 = k2(), Ko = Lr(), O = ne(), Ti2 = function(t2) { + je(e, t2); + function e(r, n2) { + var i = t2.call(this) || this; + return i.topProd = r, i.path = n2, i.possibleTokTypes = [], i.nextProductionName = "", i.nextProductionOccurrence = 0, i.found = false, i.isAtEndOfPath = false, i; + } + return e.prototype.startWalking = function() { + if (this.found = false, this.path.ruleStack[0] !== this.topProd.name) + throw Error("The path does not start with the walker's top Rule!"); + return this.ruleStack = I3.cloneArr(this.path.ruleStack).reverse(), this.occurrenceStack = I3.cloneArr(this.path.occurrenceStack).reverse(), this.ruleStack.pop(), this.occurrenceStack.pop(), this.updateExpectedNext(), this.walk(this.topProd), this.possibleTokTypes; + }, e.prototype.walk = function(r, n2) { + n2 === undefined && (n2 = []), this.found || t2.prototype.walk.call(this, r, n2); + }, e.prototype.walkProdRef = function(r, n2, i) { + if (r.referencedRule.name === this.nextProductionName && r.idx === this.nextProductionOccurrence) { + var a = n2.concat(i); + this.updateExpectedNext(), this.walk(r.referencedRule, a); + } + }, e.prototype.updateExpectedNext = function() { + I3.isEmpty(this.ruleStack) ? (this.nextProductionName = "", this.nextProductionOccurrence = 0, this.isAtEndOfPath = true) : (this.nextProductionName = this.ruleStack.pop(), this.nextProductionOccurrence = this.occurrenceStack.pop()); + }, e; + }(Ei.RestWalker); + j2.AbstractNextPossibleTokensWalker = Ti2; + var zo = function(t2) { + je(e, t2); + function e(r, n2) { + var i = t2.call(this, r, n2) || this; + return i.path = n2, i.nextTerminalName = "", i.nextTerminalOccurrence = 0, i.nextTerminalName = i.path.lastTok.name, i.nextTerminalOccurrence = i.path.lastTokOccurrence, i; + } + return e.prototype.walkTerminal = function(r, n2, i) { + if (this.isAtEndOfPath && r.terminalType.name === this.nextTerminalName && r.idx === this.nextTerminalOccurrence && !this.found) { + var a = n2.concat(i), o = new O.Alternative({ definition: a }); + this.possibleTokTypes = Ko.first(o), this.found = true; + } + }, e; + }(Ti2); + j2.NextAfterTokenWalker = zo; + var Et2 = function(t2) { + je(e, t2); + function e(r, n2) { + var i = t2.call(this) || this; + return i.topRule = r, i.occurrence = n2, i.result = { token: undefined, occurrence: undefined, isEndOfRule: undefined }, i; + } + return e.prototype.startWalking = function() { + return this.walk(this.topRule), this.result; + }, e; + }(Ei.RestWalker); + j2.AbstractNextTerminalAfterProductionWalker = Et2; + var Ho = function(t2) { + je(e, t2); + function e() { + return t2 !== null && t2.apply(this, arguments) || this; + } + return e.prototype.walkMany = function(r, n2, i) { + if (r.idx === this.occurrence) { + var a = I3.first(n2.concat(i)); + this.result.isEndOfRule = a === undefined, a instanceof O.Terminal && (this.result.token = a.terminalType, this.result.occurrence = a.idx); + } else + t2.prototype.walkMany.call(this, r, n2, i); + }, e; + }(Et2); + j2.NextTerminalAfterManyWalker = Ho; + var Yo = function(t2) { + je(e, t2); + function e() { + return t2 !== null && t2.apply(this, arguments) || this; + } + return e.prototype.walkManySep = function(r, n2, i) { + if (r.idx === this.occurrence) { + var a = I3.first(n2.concat(i)); + this.result.isEndOfRule = a === undefined, a instanceof O.Terminal && (this.result.token = a.terminalType, this.result.occurrence = a.idx); + } else + t2.prototype.walkManySep.call(this, r, n2, i); + }, e; + }(Et2); + j2.NextTerminalAfterManySepWalker = Yo; + var Xo = function(t2) { + je(e, t2); + function e() { + return t2 !== null && t2.apply(this, arguments) || this; + } + return e.prototype.walkAtLeastOne = function(r, n2, i) { + if (r.idx === this.occurrence) { + var a = I3.first(n2.concat(i)); + this.result.isEndOfRule = a === undefined, a instanceof O.Terminal && (this.result.token = a.terminalType, this.result.occurrence = a.idx); + } else + t2.prototype.walkAtLeastOne.call(this, r, n2, i); + }, e; + }(Et2); + j2.NextTerminalAfterAtLeastOneWalker = Xo; + var $o = function(t2) { + je(e, t2); + function e() { + return t2 !== null && t2.apply(this, arguments) || this; + } + return e.prototype.walkAtLeastOneSep = function(r, n2, i) { + if (r.idx === this.occurrence) { + var a = I3.first(n2.concat(i)); + this.result.isEndOfRule = a === undefined, a instanceof O.Terminal && (this.result.token = a.terminalType, this.result.occurrence = a.idx); + } else + t2.prototype.walkAtLeastOneSep.call(this, r, n2, i); + }, e; + }(Et2); + j2.NextTerminalAfterAtLeastOneSepWalker = $o; + function yi(t2, e, r) { + r === undefined && (r = []), r = I3.cloneArr(r); + var n2 = [], i = 0; + function a(f) { + return f.concat(I3.drop(t2, i + 1)); + } + function o(f) { + var p = yi(a(f), e, r); + return n2.concat(p); + } + for (;r.length < e && i < t2.length; ) { + var s = t2[i]; + if (s instanceof O.Alternative) + return o(s.definition); + if (s instanceof O.NonTerminal) + return o(s.definition); + if (s instanceof O.Option) + n2 = o(s.definition); + else if (s instanceof O.RepetitionMandatory) { + var c = s.definition.concat([new O.Repetition({ definition: s.definition })]); + return o(c); + } else if (s instanceof O.RepetitionMandatoryWithSeparator) { + var c = [new O.Alternative({ definition: s.definition }), new O.Repetition({ definition: [new O.Terminal({ terminalType: s.separator })].concat(s.definition) })]; + return o(c); + } else if (s instanceof O.RepetitionWithSeparator) { + var c = s.definition.concat([new O.Repetition({ definition: [new O.Terminal({ terminalType: s.separator })].concat(s.definition) })]); + n2 = o(c); + } else if (s instanceof O.Repetition) { + var c = s.definition.concat([new O.Repetition({ definition: s.definition })]); + n2 = o(c); + } else { + if (s instanceof O.Alternation) + return I3.forEach(s.definition, function(f) { + I3.isEmpty(f.definition) === false && (n2 = o(f.definition)); + }), n2; + if (s instanceof O.Terminal) + r.push(s.terminalType); + else + throw Error("non exhaustive match"); + } + i++; + } + return n2.push({ partialPath: r, suffixDef: I3.drop(t2, i) }), n2; + } + j2.possiblePathsFrom = yi; + function Qo(t2, e, r, n2) { + var i = "EXIT_NONE_TERMINAL", a = [i], o = "EXIT_ALTERNATIVE", s = false, c = e.length, f = c - n2 - 1, p = [], l2 = []; + for (l2.push({ idx: -1, def: t2, ruleStack: [], occurrenceStack: [] });!I3.isEmpty(l2); ) { + var m = l2.pop(); + if (m === o) { + s && I3.last(l2).idx <= f && l2.pop(); + continue; + } + var { def: v, idx: u2, ruleStack: d, occurrenceStack: A2 } = m; + if (!I3.isEmpty(v)) { + var _2 = v[0]; + if (_2 === i) { + var g3 = { idx: u2, def: I3.drop(v), ruleStack: I3.dropRight(d), occurrenceStack: I3.dropRight(A2) }; + l2.push(g3); + } else if (_2 instanceof O.Terminal) + if (u2 < c - 1) { + var y = u2 + 1, b = e[y]; + if (r(b, _2.terminalType)) { + var g3 = { idx: y, def: I3.drop(v), ruleStack: d, occurrenceStack: A2 }; + l2.push(g3); + } + } else if (u2 === c - 1) + p.push({ nextTokenType: _2.terminalType, nextTokenOccurrence: _2.idx, ruleStack: d, occurrenceStack: A2 }), s = true; + else + throw Error("non exhaustive match"); + else if (_2 instanceof O.NonTerminal) { + var L = I3.cloneArr(d); + L.push(_2.nonTerminalName); + var se2 = I3.cloneArr(A2); + se2.push(_2.idx); + var g3 = { idx: u2, def: _2.definition.concat(a, I3.drop(v)), ruleStack: L, occurrenceStack: se2 }; + l2.push(g3); + } else if (_2 instanceof O.Option) { + var fe = { idx: u2, def: I3.drop(v), ruleStack: d, occurrenceStack: A2 }; + l2.push(fe), l2.push(o); + var Z2 = { idx: u2, def: _2.definition.concat(I3.drop(v)), ruleStack: d, occurrenceStack: A2 }; + l2.push(Z2); + } else if (_2 instanceof O.RepetitionMandatory) { + var ue3 = new O.Repetition({ definition: _2.definition, idx: _2.idx }), Q2 = _2.definition.concat([ue3], I3.drop(v)), g3 = { idx: u2, def: Q2, ruleStack: d, occurrenceStack: A2 }; + l2.push(g3); + } else if (_2 instanceof O.RepetitionMandatoryWithSeparator) { + var te3 = new O.Terminal({ terminalType: _2.separator }), ue3 = new O.Repetition({ definition: [te3].concat(_2.definition), idx: _2.idx }), Q2 = _2.definition.concat([ue3], I3.drop(v)), g3 = { idx: u2, def: Q2, ruleStack: d, occurrenceStack: A2 }; + l2.push(g3); + } else if (_2 instanceof O.RepetitionWithSeparator) { + var fe = { idx: u2, def: I3.drop(v), ruleStack: d, occurrenceStack: A2 }; + l2.push(fe), l2.push(o); + var te3 = new O.Terminal({ terminalType: _2.separator }), xe = new O.Repetition({ definition: [te3].concat(_2.definition), idx: _2.idx }), Q2 = _2.definition.concat([xe], I3.drop(v)), Z2 = { idx: u2, def: Q2, ruleStack: d, occurrenceStack: A2 }; + l2.push(Z2); + } else if (_2 instanceof O.Repetition) { + var fe = { idx: u2, def: I3.drop(v), ruleStack: d, occurrenceStack: A2 }; + l2.push(fe), l2.push(o); + var xe = new O.Repetition({ definition: _2.definition, idx: _2.idx }), Q2 = _2.definition.concat([xe], I3.drop(v)), Z2 = { idx: u2, def: Q2, ruleStack: d, occurrenceStack: A2 }; + l2.push(Z2); + } else if (_2 instanceof O.Alternation) + for (var it2 = _2.definition.length - 1;it2 >= 0; it2--) { + var at = _2.definition[it2], Ke2 = { idx: u2, def: at.definition.concat(I3.drop(v)), ruleStack: d, occurrenceStack: A2 }; + l2.push(Ke2), l2.push(o); + } + else if (_2 instanceof O.Alternative) + l2.push({ idx: u2, def: _2.definition.concat(I3.drop(v)), ruleStack: d, occurrenceStack: A2 }); + else if (_2 instanceof O.Rule) + l2.push(Zo(_2, u2, d, A2)); + else + throw Error("non exhaustive match"); + } + } + return p; + } + j2.nextPossibleTokensAfter = Qo; + function Zo(t2, e, r, n2) { + var i = I3.cloneArr(r); + i.push(t2.name); + var a = I3.cloneArr(n2); + return a.push(1), { idx: e, def: t2.definition, ruleStack: i, occurrenceStack: a }; + } +}); +var yt2 = R2((C4) => { + var _i = C4 && C4.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(C4, "__esModule", { value: true }); + C4.areTokenCategoriesNotUsed = C4.isStrictPrefixOfPath = C4.containsPath = C4.getLookaheadPathsForOptionalProd = C4.getLookaheadPathsForOr = C4.lookAheadSequenceFromAlternatives = C4.buildSingleAlternativeLookaheadFunction = C4.buildAlternativesLookAheadFunc = C4.buildLookaheadFuncForOptionalProd = C4.buildLookaheadFuncForOr = C4.getProdType = C4.PROD_TYPE = undefined; + var D = k2(), gi = Tt2(), Jo2 = Gt(), Kt = Xe(), We = ne(), es = $e(), z; + (function(t2) { + t2[t2.OPTION = 0] = "OPTION", t2[t2.REPETITION = 1] = "REPETITION", t2[t2.REPETITION_MANDATORY = 2] = "REPETITION_MANDATORY", t2[t2.REPETITION_MANDATORY_WITH_SEPARATOR = 3] = "REPETITION_MANDATORY_WITH_SEPARATOR", t2[t2.REPETITION_WITH_SEPARATOR = 4] = "REPETITION_WITH_SEPARATOR", t2[t2.ALTERNATION = 5] = "ALTERNATION"; + })(z = C4.PROD_TYPE || (C4.PROD_TYPE = {})); + function ts(t2) { + if (t2 instanceof We.Option) + return z.OPTION; + if (t2 instanceof We.Repetition) + return z.REPETITION; + if (t2 instanceof We.RepetitionMandatory) + return z.REPETITION_MANDATORY; + if (t2 instanceof We.RepetitionMandatoryWithSeparator) + return z.REPETITION_MANDATORY_WITH_SEPARATOR; + if (t2 instanceof We.RepetitionWithSeparator) + return z.REPETITION_WITH_SEPARATOR; + if (t2 instanceof We.Alternation) + return z.ALTERNATION; + throw Error("non exhaustive match"); + } + C4.getProdType = ts; + function rs(t2, e, r, n2, i, a) { + var o = Ai(t2, e, r), s = Fr(o) ? Kt.tokenStructuredMatcherNoCategories : Kt.tokenStructuredMatcher; + return a(o, n2, s, i); + } + C4.buildLookaheadFuncForOr = rs; + function ns(t2, e, r, n2, i, a) { + var o = Ri(t2, e, i, r), s = Fr(o) ? Kt.tokenStructuredMatcherNoCategories : Kt.tokenStructuredMatcher; + return a(o[0], s, n2); + } + C4.buildLookaheadFuncForOptionalProd = ns; + function is(t2, e, r, n2) { + var i = t2.length, a = D.every(t2, function(c) { + return D.every(c, function(f) { + return f.length === 1; + }); + }); + if (e) + return function(c) { + for (var f = D.map(c, function(y) { + return y.GATE; + }), p = 0;p < i; p++) { + var l2 = t2[p], m = l2.length, v = f[p]; + if (v !== undefined && v.call(this) === false) + continue; + e: + for (var u2 = 0;u2 < m; u2++) { + for (var d = l2[u2], A2 = d.length, _2 = 0;_2 < A2; _2++) { + var g3 = this.LA(_2 + 1); + if (r(g3, d[_2]) === false) + continue e; + } + return p; + } + } + }; + if (a && !n2) { + var o = D.map(t2, function(c) { + return D.flatten(c); + }), s = D.reduce(o, function(c, f, p) { + return D.forEach(f, function(l2) { + D.has(c, l2.tokenTypeIdx) || (c[l2.tokenTypeIdx] = p), D.forEach(l2.categoryMatches, function(m) { + D.has(c, m) || (c[m] = p); + }); + }), c; + }, []); + return function() { + var c = this.LA(1); + return s[c.tokenTypeIdx]; + }; + } else + return function() { + for (var c = 0;c < i; c++) { + var f = t2[c], p = f.length; + e: + for (var l2 = 0;l2 < p; l2++) { + for (var m = f[l2], v = m.length, u2 = 0;u2 < v; u2++) { + var d = this.LA(u2 + 1); + if (r(d, m[u2]) === false) + continue e; + } + return c; + } + } + }; + } + C4.buildAlternativesLookAheadFunc = is; + function as(t2, e, r) { + var n2 = D.every(t2, function(f) { + return f.length === 1; + }), i = t2.length; + if (n2 && !r) { + var a = D.flatten(t2); + if (a.length === 1 && D.isEmpty(a[0].categoryMatches)) { + var o = a[0], s = o.tokenTypeIdx; + return function() { + return this.LA(1).tokenTypeIdx === s; + }; + } else { + var c = D.reduce(a, function(f, p, l2) { + return f[p.tokenTypeIdx] = true, D.forEach(p.categoryMatches, function(m) { + f[m] = true; + }), f; + }, []); + return function() { + var f = this.LA(1); + return c[f.tokenTypeIdx] === true; + }; + } + } else + return function() { + e: + for (var f = 0;f < i; f++) { + for (var p = t2[f], l2 = p.length, m = 0;m < l2; m++) { + var v = this.LA(m + 1); + if (e(v, p[m]) === false) + continue e; + } + return true; + } + return false; + }; + } + C4.buildSingleAlternativeLookaheadFunction = as; + var os = function(t2) { + _i(e, t2); + function e(r, n2, i) { + var a = t2.call(this) || this; + return a.topProd = r, a.targetOccurrence = n2, a.targetProdType = i, a; + } + return e.prototype.startWalking = function() { + return this.walk(this.topProd), this.restDef; + }, e.prototype.checkIsTarget = function(r, n2, i, a) { + return r.idx === this.targetOccurrence && this.targetProdType === n2 ? (this.restDef = i.concat(a), true) : false; + }, e.prototype.walkOption = function(r, n2, i) { + this.checkIsTarget(r, z.OPTION, n2, i) || t2.prototype.walkOption.call(this, r, n2, i); + }, e.prototype.walkAtLeastOne = function(r, n2, i) { + this.checkIsTarget(r, z.REPETITION_MANDATORY, n2, i) || t2.prototype.walkOption.call(this, r, n2, i); + }, e.prototype.walkAtLeastOneSep = function(r, n2, i) { + this.checkIsTarget(r, z.REPETITION_MANDATORY_WITH_SEPARATOR, n2, i) || t2.prototype.walkOption.call(this, r, n2, i); + }, e.prototype.walkMany = function(r, n2, i) { + this.checkIsTarget(r, z.REPETITION, n2, i) || t2.prototype.walkOption.call(this, r, n2, i); + }, e.prototype.walkManySep = function(r, n2, i) { + this.checkIsTarget(r, z.REPETITION_WITH_SEPARATOR, n2, i) || t2.prototype.walkOption.call(this, r, n2, i); + }, e; + }(Jo2.RestWalker), Oi2 = function(t2) { + _i(e, t2); + function e(r, n2, i) { + var a = t2.call(this) || this; + return a.targetOccurrence = r, a.targetProdType = n2, a.targetRef = i, a.result = [], a; + } + return e.prototype.checkIsTarget = function(r, n2) { + r.idx === this.targetOccurrence && this.targetProdType === n2 && (this.targetRef === undefined || r === this.targetRef) && (this.result = r.definition); + }, e.prototype.visitOption = function(r) { + this.checkIsTarget(r, z.OPTION); + }, e.prototype.visitRepetition = function(r) { + this.checkIsTarget(r, z.REPETITION); + }, e.prototype.visitRepetitionMandatory = function(r) { + this.checkIsTarget(r, z.REPETITION_MANDATORY); + }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) { + this.checkIsTarget(r, z.REPETITION_MANDATORY_WITH_SEPARATOR); + }, e.prototype.visitRepetitionWithSeparator = function(r) { + this.checkIsTarget(r, z.REPETITION_WITH_SEPARATOR); + }, e.prototype.visitAlternation = function(r) { + this.checkIsTarget(r, z.ALTERNATION); + }, e; + }(es.GAstVisitor); + function Ni(t2) { + for (var e = new Array(t2), r = 0;r < t2; r++) + e[r] = []; + return e; + } + function wr(t2) { + for (var e = [""], r = 0;r < t2.length; r++) { + for (var n2 = t2[r], i = [], a = 0;a < e.length; a++) { + var o = e[a]; + i.push(o + "_" + n2.tokenTypeIdx); + for (var s = 0;s < n2.categoryMatches.length; s++) { + var c = "_" + n2.categoryMatches[s]; + i.push(o + c); + } + } + e = i; + } + return e; + } + function ss(t2, e, r) { + for (var n2 = 0;n2 < t2.length; n2++) + if (n2 !== r) + for (var i = t2[n2], a = 0;a < e.length; a++) { + var o = e[a]; + if (i[o] === true) + return false; + } + return true; + } + function Dr(t2, e) { + for (var r = D.map(t2, function(p) { + return gi.possiblePathsFrom([p], 1); + }), n2 = Ni(r.length), i = D.map(r, function(p) { + var l2 = {}; + return D.forEach(p, function(m) { + var v = wr(m.partialPath); + D.forEach(v, function(u2) { + l2[u2] = true; + }); + }), l2; + }), a = r, o = 1;o <= e; o++) { + var s = a; + a = Ni(s.length); + for (var c = function(p) { + for (var l2 = s[p], m = 0;m < l2.length; m++) { + var v = l2[m].partialPath, u2 = l2[m].suffixDef, d = wr(v), A2 = ss(i, d, p); + if (A2 || D.isEmpty(u2) || v.length === e) { + var _2 = n2[p]; + if (Ii2(_2, v) === false) { + _2.push(v); + for (var g3 = 0;g3 < d.length; g3++) { + var y = d[g3]; + i[p][y] = true; + } + } + } else { + var b = gi.possiblePathsFrom(u2, o + 1, v); + a[p] = a[p].concat(b), D.forEach(b, function(L) { + var se2 = wr(L.partialPath); + D.forEach(se2, function(fe) { + i[p][fe] = true; + }); + }); + } + } + }, f = 0;f < s.length; f++) + c(f); + } + return n2; + } + C4.lookAheadSequenceFromAlternatives = Dr; + function Ai(t2, e, r, n2) { + var i = new Oi2(t2, z.ALTERNATION, n2); + return e.accept(i), Dr(i.result, r); + } + C4.getLookaheadPathsForOr = Ai; + function Ri(t2, e, r, n2) { + var i = new Oi2(t2, r); + e.accept(i); + var a = i.result, o = new os(e, t2, r), s = o.startWalking(), c = new We.Alternative({ definition: a }), f = new We.Alternative({ definition: s }); + return Dr([c, f], n2); + } + C4.getLookaheadPathsForOptionalProd = Ri; + function Ii2(t2, e) { + e: + for (var r = 0;r < t2.length; r++) { + var n2 = t2[r]; + if (n2.length === e.length) { + for (var i = 0;i < n2.length; i++) { + var a = e[i], o = n2[i], s = a === o || o.categoryMatchesMap[a.tokenTypeIdx] !== undefined; + if (s === false) + continue e; + } + return true; + } + } + return false; + } + C4.containsPath = Ii2; + function us(t2, e) { + return t2.length < e.length && D.every(t2, function(r, n2) { + var i = e[n2]; + return r === i || i.categoryMatchesMap[r.tokenTypeIdx]; + }); + } + C4.isStrictPrefixOfPath = us; + function Fr(t2) { + return D.every(t2, function(e) { + return D.every(e, function(r) { + return D.every(r, function(n2) { + return D.isEmpty(n2.categoryMatches); + }); + }); + }); + } + C4.areTokenCategoriesNotUsed = Fr; +}); +var jr = R2((x2) => { + var Ur = x2 && x2.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(x2, "__esModule", { value: true }); + x2.checkPrefixAlternativesAmbiguities = x2.validateSomeNonEmptyLookaheadPath = x2.validateTooManyAlts = x2.RepetionCollector = x2.validateAmbiguousAlternationAlternatives = x2.validateEmptyOrAlternative = x2.getFirstNoneTerminal = x2.validateNoLeftRecursion = x2.validateRuleIsOverridden = x2.validateRuleDoesNotAlreadyExist = x2.OccurrenceValidationCollector = x2.identifyProductionForDuplicates = x2.validateGrammar = undefined; + var M = k2(), B2 = k2(), Ie = ce2(), Gr = vt(), Qe = yt2(), cs = Tt2(), _e = ne(), Wr = $e(); + function ps(t2, e, r, n2, i) { + var a = M.map(t2, function(v) { + return ls(v, n2); + }), o = M.map(t2, function(v) { + return Br(v, v, n2); + }), s = [], c = [], f = []; + B2.every(o, B2.isEmpty) && (s = B2.map(t2, function(v) { + return Pi3(v, n2); + }), c = B2.map(t2, function(v) { + return Si2(v, e, n2); + }), f = Ci(t2, e, n2)); + var p = fs(t2, r, n2), l2 = B2.map(t2, function(v) { + return xi(v, n2); + }), m = B2.map(t2, function(v) { + return ki(v, t2, i, n2); + }); + return M.flatten(a.concat(f, o, s, c, p, l2, m)); + } + x2.validateGrammar = ps; + function ls(t2, e) { + var r = new bi; + t2.accept(r); + var n2 = r.allProductions, i = M.groupBy(n2, Li), a = M.pick(i, function(s) { + return s.length > 1; + }), o = M.map(M.values(a), function(s) { + var c = M.first(s), f = e.buildDuplicateFoundError(t2, s), p = Gr.getProductionDslName(c), l2 = { message: f, type: Ie.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS, ruleName: t2.name, dslName: p, occurrence: c.idx }, m = Mi(c); + return m && (l2.parameter = m), l2; + }); + return o; + } + function Li(t2) { + return Gr.getProductionDslName(t2) + "_#_" + t2.idx + "_#_" + Mi(t2); + } + x2.identifyProductionForDuplicates = Li; + function Mi(t2) { + return t2 instanceof _e.Terminal ? t2.terminalType.name : t2 instanceof _e.NonTerminal ? t2.nonTerminalName : ""; + } + var bi = function(t2) { + Ur(e, t2); + function e() { + var r = t2 !== null && t2.apply(this, arguments) || this; + return r.allProductions = [], r; + } + return e.prototype.visitNonTerminal = function(r) { + this.allProductions.push(r); + }, e.prototype.visitOption = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionWithSeparator = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionMandatory = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetition = function(r) { + this.allProductions.push(r); + }, e.prototype.visitAlternation = function(r) { + this.allProductions.push(r); + }, e.prototype.visitTerminal = function(r) { + this.allProductions.push(r); + }, e; + }(Wr.GAstVisitor); + x2.OccurrenceValidationCollector = bi; + function ki(t2, e, r, n2) { + var i = [], a = B2.reduce(e, function(s, c) { + return c.name === t2.name ? s + 1 : s; + }, 0); + if (a > 1) { + var o = n2.buildDuplicateRuleNameError({ topLevelRule: t2, grammarName: r }); + i.push({ message: o, type: Ie.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, ruleName: t2.name }); + } + return i; + } + x2.validateRuleDoesNotAlreadyExist = ki; + function hs(t2, e, r) { + var n2 = [], i; + return M.contains(e, t2) || (i = "Invalid rule override, rule: ->" + t2 + "<- cannot be overridden in the grammar: ->" + r + "<-as it is not defined in any of the super grammars ", n2.push({ message: i, type: Ie.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE, ruleName: t2 })), n2; + } + x2.validateRuleIsOverridden = hs; + function Br(t2, e, r, n2) { + n2 === undefined && (n2 = []); + var i = [], a = _t(e.definition); + if (M.isEmpty(a)) + return []; + var o = t2.name, s = M.contains(a, t2); + s && i.push({ message: r.buildLeftRecursionError({ topLevelRule: t2, leftRecursionPath: n2 }), type: Ie.ParserDefinitionErrorType.LEFT_RECURSION, ruleName: o }); + var c = M.difference(a, n2.concat([t2])), f = M.map(c, function(p) { + var l2 = M.cloneArr(n2); + return l2.push(p), Br(t2, p, r, l2); + }); + return i.concat(M.flatten(f)); + } + x2.validateNoLeftRecursion = Br; + function _t(t2) { + var e = []; + if (M.isEmpty(t2)) + return e; + var r = M.first(t2); + if (r instanceof _e.NonTerminal) + e.push(r.referencedRule); + else if (r instanceof _e.Alternative || r instanceof _e.Option || r instanceof _e.RepetitionMandatory || r instanceof _e.RepetitionMandatoryWithSeparator || r instanceof _e.RepetitionWithSeparator || r instanceof _e.Repetition) + e = e.concat(_t(r.definition)); + else if (r instanceof _e.Alternation) + e = M.flatten(M.map(r.definition, function(o) { + return _t(o.definition); + })); + else if (!(r instanceof _e.Terminal)) + throw Error("non exhaustive match"); + var n2 = Gr.isOptionalProd(r), i = t2.length > 1; + if (n2 && i) { + var a = M.drop(t2); + return e.concat(_t(a)); + } else + return e; + } + x2.getFirstNoneTerminal = _t; + var qr2 = function(t2) { + Ur(e, t2); + function e() { + var r = t2 !== null && t2.apply(this, arguments) || this; + return r.alternations = [], r; + } + return e.prototype.visitAlternation = function(r) { + this.alternations.push(r); + }, e; + }(Wr.GAstVisitor); + function Pi3(t2, e) { + var r = new qr2; + t2.accept(r); + var n2 = r.alternations, i = M.reduce(n2, function(a, o) { + var s = M.dropRight(o.definition), c = M.map(s, function(f, p) { + var l2 = cs.nextPossibleTokensAfter([f], [], null, 1); + return M.isEmpty(l2) ? { message: e.buildEmptyAlternationError({ topLevelRule: t2, alternation: o, emptyChoiceIdx: p }), type: Ie.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT, ruleName: t2.name, occurrence: o.idx, alternative: p + 1 } : null; + }); + return a.concat(M.compact(c)); + }, []); + return i; + } + x2.validateEmptyOrAlternative = Pi3; + function Si2(t2, e, r) { + var n2 = new qr2; + t2.accept(n2); + var i = n2.alternations; + i = B2.reject(i, function(o) { + return o.ignoreAmbiguities === true; + }); + var a = M.reduce(i, function(o, s) { + var c = s.idx, f = s.maxLookahead || e, p = Qe.getLookaheadPathsForOr(c, t2, f, s), l2 = ds(p, s, t2, r), m = Fi2(p, s, t2, r); + return o.concat(l2, m); + }, []); + return a; + } + x2.validateAmbiguousAlternationAlternatives = Si2; + var wi = function(t2) { + Ur(e, t2); + function e() { + var r = t2 !== null && t2.apply(this, arguments) || this; + return r.allProductions = [], r; + } + return e.prototype.visitRepetitionWithSeparator = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionMandatory = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetitionMandatoryWithSeparator = function(r) { + this.allProductions.push(r); + }, e.prototype.visitRepetition = function(r) { + this.allProductions.push(r); + }, e; + }(Wr.GAstVisitor); + x2.RepetionCollector = wi; + function xi(t2, e) { + var r = new qr2; + t2.accept(r); + var n2 = r.alternations, i = M.reduce(n2, function(a, o) { + return o.definition.length > 255 && a.push({ message: e.buildTooManyAlternativesError({ topLevelRule: t2, alternation: o }), type: Ie.ParserDefinitionErrorType.TOO_MANY_ALTS, ruleName: t2.name, occurrence: o.idx }), a; + }, []); + return i; + } + x2.validateTooManyAlts = xi; + function Ci(t2, e, r) { + var n2 = []; + return B2.forEach(t2, function(i) { + var a = new wi; + i.accept(a); + var o = a.allProductions; + B2.forEach(o, function(s) { + var c = Qe.getProdType(s), f = s.maxLookahead || e, p = s.idx, l2 = Qe.getLookaheadPathsForOptionalProd(p, i, c, f), m = l2[0]; + if (B2.isEmpty(B2.flatten(m))) { + var v = r.buildEmptyRepetitionError({ topLevelRule: i, repetition: s }); + n2.push({ message: v, type: Ie.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD, ruleName: i.name }); + } + }); + }), n2; + } + x2.validateSomeNonEmptyLookaheadPath = Ci; + function ds(t2, e, r, n2) { + var i = [], a = B2.reduce(t2, function(s, c, f) { + return e.definition[f].ignoreAmbiguities === true || B2.forEach(c, function(p) { + var l2 = [f]; + B2.forEach(t2, function(m, v) { + f !== v && Qe.containsPath(m, p) && e.definition[v].ignoreAmbiguities !== true && l2.push(v); + }), l2.length > 1 && !Qe.containsPath(i, p) && (i.push(p), s.push({ alts: l2, path: p })); + }), s; + }, []), o = M.map(a, function(s) { + var c = B2.map(s.alts, function(p) { + return p + 1; + }), f = n2.buildAlternationAmbiguityError({ topLevelRule: r, alternation: e, ambiguityIndices: c, prefixPath: s.path }); + return { message: f, type: Ie.ParserDefinitionErrorType.AMBIGUOUS_ALTS, ruleName: r.name, occurrence: e.idx, alternatives: [s.alts] }; + }); + return o; + } + function Fi2(t2, e, r, n2) { + var i = [], a = B2.reduce(t2, function(o, s, c) { + var f = B2.map(s, function(p) { + return { idx: c, path: p }; + }); + return o.concat(f); + }, []); + return B2.forEach(a, function(o) { + var s = e.definition[o.idx]; + if (s.ignoreAmbiguities !== true) { + var { idx: c, path: f } = o, p = B2.findAll(a, function(m) { + return e.definition[m.idx].ignoreAmbiguities !== true && m.idx < c && Qe.isStrictPrefixOfPath(m.path, f); + }), l2 = B2.map(p, function(m) { + var v = [m.idx + 1, c + 1], u2 = e.idx === 0 ? "" : e.idx, d = n2.buildAlternationPrefixAmbiguityError({ topLevelRule: r, alternation: e, ambiguityIndices: v, prefixPath: m.path }); + return { message: d, type: Ie.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS, ruleName: r.name, occurrence: u2, alternatives: v }; + }); + i = i.concat(l2); + } + }), i; + } + x2.checkPrefixAlternativesAmbiguities = Fi2; + function fs(t2, e, r) { + var n2 = [], i = B2.map(e, function(a) { + return a.name; + }); + return B2.forEach(t2, function(a) { + var o = a.name; + if (B2.contains(i, o)) { + var s = r.buildNamespaceConflictError(a); + n2.push({ message: s, type: Ie.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE, ruleName: o }); + } + }), n2; + } +}); +var Ui = R2((Je) => { + Object.defineProperty(Je, "__esModule", { value: true }); + Je.validateGrammar = Je.resolveGrammar = undefined; + var Vr = k2(), vs = mi(), ms = jr(), Di = mt(); + function Es(t2) { + t2 = Vr.defaults(t2, { errMsgProvider: Di.defaultGrammarResolverErrorProvider }); + var e = {}; + return Vr.forEach(t2.rules, function(r) { + e[r.name] = r; + }), vs.resolveGrammar(e, t2.errMsgProvider); + } + Je.resolveGrammar = Es; + function Ts(t2) { + return t2 = Vr.defaults(t2, { errMsgProvider: Di.defaultGrammarValidatorErrorProvider }), ms.validateGrammar(t2.rules, t2.maxLookahead, t2.tokenTypes, t2.errMsgProvider, t2.grammarName); + } + Je.validateGrammar = Ts; +}); +var et3 = R2((ae3) => { + var gt = ae3 && ae3.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(ae3, "__esModule", { value: true }); + ae3.EarlyExitException = ae3.NotAllInputParsedException = ae3.NoViableAltException = ae3.MismatchedTokenException = ae3.isRecognitionException = undefined; + var ys = k2(), Gi2 = "MismatchedTokenException", Wi3 = "NoViableAltException", Bi = "EarlyExitException", qi = "NotAllInputParsedException", ji = [Gi2, Wi3, Bi, qi]; + Object.freeze(ji); + function _s(t2) { + return ys.contains(ji, t2.name); + } + ae3.isRecognitionException = _s; + var zt = function(t2) { + gt(e, t2); + function e(r, n2) { + var i = this.constructor, a = t2.call(this, r) || this; + return a.token = n2, a.resyncedTokens = [], Object.setPrototypeOf(a, i.prototype), Error.captureStackTrace && Error.captureStackTrace(a, a.constructor), a; + } + return e; + }(Error), gs = function(t2) { + gt(e, t2); + function e(r, n2, i) { + var a = t2.call(this, r, n2) || this; + return a.previousToken = i, a.name = Gi2, a; + } + return e; + }(zt); + ae3.MismatchedTokenException = gs; + var As = function(t2) { + gt(e, t2); + function e(r, n2, i) { + var a = t2.call(this, r, n2) || this; + return a.previousToken = i, a.name = Wi3, a; + } + return e; + }(zt); + ae3.NoViableAltException = As; + var Rs = function(t2) { + gt(e, t2); + function e(r, n2) { + var i = t2.call(this, r, n2) || this; + return i.name = qi, i; + } + return e; + }(zt); + ae3.NotAllInputParsedException = Rs; + var Os = function(t2) { + gt(e, t2); + function e(r, n2, i) { + var a = t2.call(this, r, n2) || this; + return a.previousToken = i, a.name = Bi, a; + } + return e; + }(zt); + ae3.EarlyExitException = Os; +}); +var zr = R2(($2) => { + Object.defineProperty($2, "__esModule", { value: true }); + $2.attemptInRepetitionRecovery = $2.Recoverable = $2.InRuleRecoveryException = $2.IN_RULE_RECOVERY_EXCEPTION = $2.EOF_FOLLOW_KEY = undefined; + var Ht = Ue(), de = k2(), Ns = et3(), Is = Mr(), ks = ce2(); + $2.EOF_FOLLOW_KEY = {}; + $2.IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException"; + function Kr2(t2) { + this.name = $2.IN_RULE_RECOVERY_EXCEPTION, this.message = t2; + } + $2.InRuleRecoveryException = Kr2; + Kr2.prototype = Error.prototype; + var Ps = function() { + function t2() { + } + return t2.prototype.initRecoverable = function(e) { + this.firstAfterRepMap = {}, this.resyncFollows = {}, this.recoveryEnabled = de.has(e, "recoveryEnabled") ? e.recoveryEnabled : ks.DEFAULT_PARSER_CONFIG.recoveryEnabled, this.recoveryEnabled && (this.attemptInRepetitionRecovery = Vi); + }, t2.prototype.getTokenToInsert = function(e) { + var r = Ht.createTokenInstance(e, "", NaN, NaN, NaN, NaN, NaN, NaN); + return r.isInsertedInRecovery = true, r; + }, t2.prototype.canTokenTypeBeInsertedInRecovery = function(e) { + return true; + }, t2.prototype.tryInRepetitionRecovery = function(e, r, n2, i) { + for (var a = this, o = this.findReSyncTokenType(), s = this.exportLexerState(), c = [], f = false, p = this.LA(1), l2 = this.LA(1), m = function() { + var v = a.LA(0), u2 = a.errorMessageProvider.buildMismatchTokenMessage({ expected: i, actual: p, previous: v, ruleName: a.getCurrRuleFullName() }), d = new Ns.MismatchedTokenException(u2, p, a.LA(0)); + d.resyncedTokens = de.dropRight(c), a.SAVE_ERROR(d); + };!f; ) + if (this.tokenMatcher(l2, i)) { + m(); + return; + } else if (n2.call(this)) { + m(), e.apply(this, r); + return; + } else + this.tokenMatcher(l2, o) ? f = true : (l2 = this.SKIP_TOKEN(), this.addToResyncTokens(l2, c)); + this.importLexerState(s); + }, t2.prototype.shouldInRepetitionRecoveryBeTried = function(e, r, n2) { + return !(n2 === false || e === undefined || r === undefined || this.tokenMatcher(this.LA(1), e) || this.isBackTracking() || this.canPerformInRuleRecovery(e, this.getFollowsForInRuleRecovery(e, r))); + }, t2.prototype.getFollowsForInRuleRecovery = function(e, r) { + var n2 = this.getCurrentGrammarPath(e, r), i = this.getNextPossibleTokenTypes(n2); + return i; + }, t2.prototype.tryInRuleRecovery = function(e, r) { + if (this.canRecoverWithSingleTokenInsertion(e, r)) { + var n2 = this.getTokenToInsert(e); + return n2; + } + if (this.canRecoverWithSingleTokenDeletion(e)) { + var i = this.SKIP_TOKEN(); + return this.consumeToken(), i; + } + throw new Kr2("sad sad panda"); + }, t2.prototype.canPerformInRuleRecovery = function(e, r) { + return this.canRecoverWithSingleTokenInsertion(e, r) || this.canRecoverWithSingleTokenDeletion(e); + }, t2.prototype.canRecoverWithSingleTokenInsertion = function(e, r) { + var n2 = this; + if (!this.canTokenTypeBeInsertedInRecovery(e) || de.isEmpty(r)) + return false; + var i = this.LA(1), a = de.find(r, function(o) { + return n2.tokenMatcher(i, o); + }) !== undefined; + return a; + }, t2.prototype.canRecoverWithSingleTokenDeletion = function(e) { + var r = this.tokenMatcher(this.LA(2), e); + return r; + }, t2.prototype.isInCurrentRuleReSyncSet = function(e) { + var r = this.getCurrFollowKey(), n2 = this.getFollowSetFromFollowKey(r); + return de.contains(n2, e); + }, t2.prototype.findReSyncTokenType = function() { + for (var e = this.flattenFollowSet(), r = this.LA(1), n2 = 2;; ) { + var i = r.tokenType; + if (de.contains(e, i)) + return i; + r = this.LA(n2), n2++; + } + }, t2.prototype.getCurrFollowKey = function() { + if (this.RULE_STACK.length === 1) + return $2.EOF_FOLLOW_KEY; + var e = this.getLastExplicitRuleShortName(), r = this.getLastExplicitRuleOccurrenceIndex(), n2 = this.getPreviousExplicitRuleShortName(); + return { ruleName: this.shortRuleNameToFullName(e), idxInCallingRule: r, inRule: this.shortRuleNameToFullName(n2) }; + }, t2.prototype.buildFullFollowKeyStack = function() { + var e = this, r = this.RULE_STACK, n2 = this.RULE_OCCURRENCE_STACK; + return de.map(r, function(i, a) { + return a === 0 ? $2.EOF_FOLLOW_KEY : { ruleName: e.shortRuleNameToFullName(i), idxInCallingRule: n2[a], inRule: e.shortRuleNameToFullName(r[a - 1]) }; + }); + }, t2.prototype.flattenFollowSet = function() { + var e = this, r = de.map(this.buildFullFollowKeyStack(), function(n2) { + return e.getFollowSetFromFollowKey(n2); + }); + return de.flatten(r); + }, t2.prototype.getFollowSetFromFollowKey = function(e) { + if (e === $2.EOF_FOLLOW_KEY) + return [Ht.EOF]; + var r = e.ruleName + e.idxInCallingRule + Is.IN + e.inRule; + return this.resyncFollows[r]; + }, t2.prototype.addToResyncTokens = function(e, r) { + return this.tokenMatcher(e, Ht.EOF) || r.push(e), r; + }, t2.prototype.reSyncTo = function(e) { + for (var r = [], n2 = this.LA(1);this.tokenMatcher(n2, e) === false; ) + n2 = this.SKIP_TOKEN(), this.addToResyncTokens(n2, r); + return de.dropRight(r); + }, t2.prototype.attemptInRepetitionRecovery = function(e, r, n2, i, a, o, s) { + }, t2.prototype.getCurrentGrammarPath = function(e, r) { + var n2 = this.getHumanReadableRuleStack(), i = de.cloneArr(this.RULE_OCCURRENCE_STACK), a = { ruleStack: n2, occurrenceStack: i, lastTok: e, lastTokOccurrence: r }; + return a; + }, t2.prototype.getHumanReadableRuleStack = function() { + var e = this; + return de.map(this.RULE_STACK, function(r) { + return e.shortRuleNameToFullName(r); + }); + }, t2; + }(); + $2.Recoverable = Ps; + function Vi(t2, e, r, n2, i, a, o) { + var s = this.getKeyForAutomaticLookahead(n2, i), c = this.firstAfterRepMap[s]; + if (c === undefined) { + var f = this.getCurrRuleFullName(), p = this.getGAstProductions()[f], l2 = new a(p, i); + c = l2.startWalking(), this.firstAfterRepMap[s] = c; + } + var { token: m, occurrence: v, isEndOfRule: u2 } = c; + this.RULE_STACK.length === 1 && u2 && m === undefined && (m = Ht.EOF, v = 1), this.shouldInRepetitionRecoveryBeTried(m, v, o) && this.tryInRepetitionRecovery(t2, e, r, m); + } + $2.attemptInRepetitionRecovery = Vi; +}); +var Yt = R2((P) => { + Object.defineProperty(P, "__esModule", { value: true }); + P.getKeyForAutomaticLookahead = P.AT_LEAST_ONE_SEP_IDX = P.MANY_SEP_IDX = P.AT_LEAST_ONE_IDX = P.MANY_IDX = P.OPTION_IDX = P.OR_IDX = P.BITS_FOR_ALT_IDX = P.BITS_FOR_RULE_IDX = P.BITS_FOR_OCCURRENCE_IDX = P.BITS_FOR_METHOD_TYPE = undefined; + P.BITS_FOR_METHOD_TYPE = 4; + P.BITS_FOR_OCCURRENCE_IDX = 8; + P.BITS_FOR_RULE_IDX = 12; + P.BITS_FOR_ALT_IDX = 8; + P.OR_IDX = 1 << P.BITS_FOR_OCCURRENCE_IDX; + P.OPTION_IDX = 2 << P.BITS_FOR_OCCURRENCE_IDX; + P.MANY_IDX = 3 << P.BITS_FOR_OCCURRENCE_IDX; + P.AT_LEAST_ONE_IDX = 4 << P.BITS_FOR_OCCURRENCE_IDX; + P.MANY_SEP_IDX = 5 << P.BITS_FOR_OCCURRENCE_IDX; + P.AT_LEAST_ONE_SEP_IDX = 6 << P.BITS_FOR_OCCURRENCE_IDX; + function Ss(t2, e, r) { + return r | e | t2; + } + P.getKeyForAutomaticLookahead = Ss; + var ic = 32 - P.BITS_FOR_ALT_IDX; +}); +var zi = R2((Xt) => { + Object.defineProperty(Xt, "__esModule", { value: true }); + Xt.LooksAhead = undefined; + var be = yt2(), ge2 = k2(), Ki = ce2(), Fe = Yt(), Ve = vt(), xs = function() { + function t2() { + } + return t2.prototype.initLooksAhead = function(e) { + this.dynamicTokensEnabled = ge2.has(e, "dynamicTokensEnabled") ? e.dynamicTokensEnabled : Ki.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled, this.maxLookahead = ge2.has(e, "maxLookahead") ? e.maxLookahead : Ki.DEFAULT_PARSER_CONFIG.maxLookahead, this.lookAheadFuncsCache = ge2.isES2015MapSupported() ? new Map : [], ge2.isES2015MapSupported() ? (this.getLaFuncFromCache = this.getLaFuncFromMap, this.setLaFuncCache = this.setLaFuncCacheUsingMap) : (this.getLaFuncFromCache = this.getLaFuncFromObj, this.setLaFuncCache = this.setLaFuncUsingObj); + }, t2.prototype.preComputeLookaheadFunctions = function(e) { + var r = this; + ge2.forEach(e, function(n2) { + r.TRACE_INIT(n2.name + " Rule Lookahead", function() { + var i = Ve.collectMethods(n2), a = i.alternation, o = i.repetition, s = i.option, c = i.repetitionMandatory, f = i.repetitionMandatoryWithSeparator, p = i.repetitionWithSeparator; + ge2.forEach(a, function(l2) { + var m = l2.idx === 0 ? "" : l2.idx; + r.TRACE_INIT("" + Ve.getProductionDslName(l2) + m, function() { + var v = be.buildLookaheadFuncForOr(l2.idx, n2, l2.maxLookahead || r.maxLookahead, l2.hasPredicates, r.dynamicTokensEnabled, r.lookAheadBuilderForAlternatives), u2 = Fe.getKeyForAutomaticLookahead(r.fullRuleNameToShort[n2.name], Fe.OR_IDX, l2.idx); + r.setLaFuncCache(u2, v); + }); + }), ge2.forEach(o, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.MANY_IDX, be.PROD_TYPE.REPETITION, l2.maxLookahead, Ve.getProductionDslName(l2)); + }), ge2.forEach(s, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.OPTION_IDX, be.PROD_TYPE.OPTION, l2.maxLookahead, Ve.getProductionDslName(l2)); + }), ge2.forEach(c, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.AT_LEAST_ONE_IDX, be.PROD_TYPE.REPETITION_MANDATORY, l2.maxLookahead, Ve.getProductionDslName(l2)); + }), ge2.forEach(f, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.AT_LEAST_ONE_SEP_IDX, be.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, l2.maxLookahead, Ve.getProductionDslName(l2)); + }), ge2.forEach(p, function(l2) { + r.computeLookaheadFunc(n2, l2.idx, Fe.MANY_SEP_IDX, be.PROD_TYPE.REPETITION_WITH_SEPARATOR, l2.maxLookahead, Ve.getProductionDslName(l2)); + }); + }); + }); + }, t2.prototype.computeLookaheadFunc = function(e, r, n2, i, a, o) { + var s = this; + this.TRACE_INIT("" + o + (r === 0 ? "" : r), function() { + var c = be.buildLookaheadFuncForOptionalProd(r, e, a || s.maxLookahead, s.dynamicTokensEnabled, i, s.lookAheadBuilderForOptional), f = Fe.getKeyForAutomaticLookahead(s.fullRuleNameToShort[e.name], n2, r); + s.setLaFuncCache(f, c); + }); + }, t2.prototype.lookAheadBuilderForOptional = function(e, r, n2) { + return be.buildSingleAlternativeLookaheadFunction(e, r, n2); + }, t2.prototype.lookAheadBuilderForAlternatives = function(e, r, n2, i) { + return be.buildAlternativesLookAheadFunc(e, r, n2, i); + }, t2.prototype.getKeyForAutomaticLookahead = function(e, r) { + var n2 = this.getLastExplicitRuleShortName(); + return Fe.getKeyForAutomaticLookahead(n2, e, r); + }, t2.prototype.getLaFuncFromCache = function(e) { + }, t2.prototype.getLaFuncFromMap = function(e) { + return this.lookAheadFuncsCache.get(e); + }, t2.prototype.getLaFuncFromObj = function(e) { + return this.lookAheadFuncsCache[e]; + }, t2.prototype.setLaFuncCache = function(e, r) { + }, t2.prototype.setLaFuncCacheUsingMap = function(e, r) { + this.lookAheadFuncsCache.set(e, r); + }, t2.prototype.setLaFuncUsingObj = function(e, r) { + this.lookAheadFuncsCache[e] = r; + }, t2; + }(); + Xt.LooksAhead = xs; +}); +var Hi = R2((ke) => { + Object.defineProperty(ke, "__esModule", { value: true }); + ke.addNoneTerminalToCst = ke.addTerminalToCst = ke.setNodeLocationFull = ke.setNodeLocationOnlyOffset = undefined; + function Cs(t2, e) { + isNaN(t2.startOffset) === true ? (t2.startOffset = e.startOffset, t2.endOffset = e.endOffset) : t2.endOffset < e.endOffset && (t2.endOffset = e.endOffset); + } + ke.setNodeLocationOnlyOffset = Cs; + function Ls(t2, e) { + isNaN(t2.startOffset) === true ? (t2.startOffset = e.startOffset, t2.startColumn = e.startColumn, t2.startLine = e.startLine, t2.endOffset = e.endOffset, t2.endColumn = e.endColumn, t2.endLine = e.endLine) : t2.endOffset < e.endOffset && (t2.endOffset = e.endOffset, t2.endColumn = e.endColumn, t2.endLine = e.endLine); + } + ke.setNodeLocationFull = Ls; + function Ms(t2, e, r) { + t2.children[r] === undefined ? t2.children[r] = [e] : t2.children[r].push(e); + } + ke.addTerminalToCst = Ms; + function bs(t2, e, r) { + t2.children[e] === undefined ? t2.children[e] = [r] : t2.children[e].push(r); + } + ke.addNoneTerminalToCst = bs; +}); +var Hr = R2((Be) => { + Object.defineProperty(Be, "__esModule", { value: true }); + Be.defineNameProp = Be.functionName = Be.classNameFromInstance = undefined; + var Fs = k2(); + function ws(t2) { + return Yi(t2.constructor); + } + Be.classNameFromInstance = ws; + var Xi = "name"; + function Yi(t2) { + var e = t2.name; + return e || "anonymous"; + } + Be.functionName = Yi; + function Ds(t2, e) { + var r = Object.getOwnPropertyDescriptor(t2, Xi); + return Fs.isUndefined(r) || r.configurable ? (Object.defineProperty(t2, Xi, { enumerable: false, configurable: true, writable: false, value: e }), true) : false; + } + Be.defineNameProp = Ds; +}); +var ea = R2((Y) => { + Object.defineProperty(Y, "__esModule", { value: true }); + Y.validateRedundantMethods = Y.validateMissingCstMethods = Y.validateVisitor = Y.CstVisitorDefinitionError = Y.createBaseVisitorConstructorWithDefaults = Y.createBaseSemanticVisitorConstructor = Y.defaultVisit = undefined; + var ve = k2(), At2 = Hr(); + function $i(t2, e) { + for (var r = ve.keys(t2), n2 = r.length, i = 0;i < n2; i++) + for (var a = r[i], o = t2[a], s = o.length, c = 0;c < s; c++) { + var f = o[c]; + f.tokenTypeIdx === undefined && this[f.name](f.children, e); + } + } + Y.defaultVisit = $i; + function Us(t2, e) { + var r = function() { + }; + At2.defineNameProp(r, t2 + "BaseSemantics"); + var n2 = { visit: function(i, a) { + if (ve.isArray(i) && (i = i[0]), !ve.isUndefined(i)) + return this[i.name](i.children, a); + }, validateVisitor: function() { + var i = Zi(this, e); + if (!ve.isEmpty(i)) { + var a = ve.map(i, function(o) { + return o.msg; + }); + throw Error("Errors Detected in CST Visitor <" + At2.functionName(this.constructor) + `>: + ` + ("" + a.join(` + +`).replace(/\n/g, ` + `))); + } + } }; + return r.prototype = n2, r.prototype.constructor = r, r._RULE_NAMES = e, r; + } + Y.createBaseSemanticVisitorConstructor = Us; + function Gs(t2, e, r) { + var n2 = function() { + }; + At2.defineNameProp(n2, t2 + "BaseSemanticsWithDefaults"); + var i = Object.create(r.prototype); + return ve.forEach(e, function(a) { + i[a] = $i; + }), n2.prototype = i, n2.prototype.constructor = n2, n2; + } + Y.createBaseVisitorConstructorWithDefaults = Gs; + var Yr; + (function(t2) { + t2[t2.REDUNDANT_METHOD = 0] = "REDUNDANT_METHOD", t2[t2.MISSING_METHOD = 1] = "MISSING_METHOD"; + })(Yr = Y.CstVisitorDefinitionError || (Y.CstVisitorDefinitionError = {})); + function Zi(t2, e) { + var r = Qi(t2, e), n2 = Ji(t2, e); + return r.concat(n2); + } + Y.validateVisitor = Zi; + function Qi(t2, e) { + var r = ve.map(e, function(n2) { + if (!ve.isFunction(t2[n2])) + return { msg: "Missing visitor method: <" + n2 + "> on " + At2.functionName(t2.constructor) + " CST Visitor.", type: Yr.MISSING_METHOD, methodName: n2 }; + }); + return ve.compact(r); + } + Y.validateMissingCstMethods = Qi; + var Ws = ["constructor", "visit", "validateVisitor"]; + function Ji(t2, e) { + var r = []; + for (var n2 in t2) + ve.isFunction(t2[n2]) && !ve.contains(Ws, n2) && !ve.contains(e, n2) && r.push({ msg: "Redundant visitor method: <" + n2 + "> on " + At2.functionName(t2.constructor) + ` CST Visitor +There is no Grammar Rule corresponding to this method's name. +`, type: Yr.REDUNDANT_METHOD, methodName: n2 }); + return r; + } + Y.validateRedundantMethods = Ji; +}); +var ra = R2(($t) => { + Object.defineProperty($t, "__esModule", { value: true }); + $t.TreeBuilder = undefined; + var tt3 = Hi(), K = k2(), ta = ea(), Bs = ce2(), qs = function() { + function t2() { + } + return t2.prototype.initTreeBuilder = function(e) { + if (this.CST_STACK = [], this.outputCst = e.outputCst, this.nodeLocationTracking = K.has(e, "nodeLocationTracking") ? e.nodeLocationTracking : Bs.DEFAULT_PARSER_CONFIG.nodeLocationTracking, !this.outputCst) + this.cstInvocationStateUpdate = K.NOOP, this.cstFinallyStateUpdate = K.NOOP, this.cstPostTerminal = K.NOOP, this.cstPostNonTerminal = K.NOOP, this.cstPostRule = K.NOOP; + else if (/full/i.test(this.nodeLocationTracking)) + this.recoveryEnabled ? (this.setNodeLocationFromToken = tt3.setNodeLocationFull, this.setNodeLocationFromNode = tt3.setNodeLocationFull, this.cstPostRule = K.NOOP, this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery) : (this.setNodeLocationFromToken = K.NOOP, this.setNodeLocationFromNode = K.NOOP, this.cstPostRule = this.cstPostRuleFull, this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular); + else if (/onlyOffset/i.test(this.nodeLocationTracking)) + this.recoveryEnabled ? (this.setNodeLocationFromToken = tt3.setNodeLocationOnlyOffset, this.setNodeLocationFromNode = tt3.setNodeLocationOnlyOffset, this.cstPostRule = K.NOOP, this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery) : (this.setNodeLocationFromToken = K.NOOP, this.setNodeLocationFromNode = K.NOOP, this.cstPostRule = this.cstPostRuleOnlyOffset, this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular); + else if (/none/i.test(this.nodeLocationTracking)) + this.setNodeLocationFromToken = K.NOOP, this.setNodeLocationFromNode = K.NOOP, this.cstPostRule = K.NOOP, this.setInitialNodeLocation = K.NOOP; + else + throw Error('Invalid config option: "' + e.nodeLocationTracking + '"'); + }, t2.prototype.setInitialNodeLocationOnlyOffsetRecovery = function(e) { + e.location = { startOffset: NaN, endOffset: NaN }; + }, t2.prototype.setInitialNodeLocationOnlyOffsetRegular = function(e) { + e.location = { startOffset: this.LA(1).startOffset, endOffset: NaN }; + }, t2.prototype.setInitialNodeLocationFullRecovery = function(e) { + e.location = { startOffset: NaN, startLine: NaN, startColumn: NaN, endOffset: NaN, endLine: NaN, endColumn: NaN }; + }, t2.prototype.setInitialNodeLocationFullRegular = function(e) { + var r = this.LA(1); + e.location = { startOffset: r.startOffset, startLine: r.startLine, startColumn: r.startColumn, endOffset: NaN, endLine: NaN, endColumn: NaN }; + }, t2.prototype.cstInvocationStateUpdate = function(e, r) { + var n2 = { name: e, children: {} }; + this.setInitialNodeLocation(n2), this.CST_STACK.push(n2); + }, t2.prototype.cstFinallyStateUpdate = function() { + this.CST_STACK.pop(); + }, t2.prototype.cstPostRuleFull = function(e) { + var r = this.LA(0), n2 = e.location; + n2.startOffset <= r.startOffset ? (n2.endOffset = r.endOffset, n2.endLine = r.endLine, n2.endColumn = r.endColumn) : (n2.startOffset = NaN, n2.startLine = NaN, n2.startColumn = NaN); + }, t2.prototype.cstPostRuleOnlyOffset = function(e) { + var r = this.LA(0), n2 = e.location; + n2.startOffset <= r.startOffset ? n2.endOffset = r.endOffset : n2.startOffset = NaN; + }, t2.prototype.cstPostTerminal = function(e, r) { + var n2 = this.CST_STACK[this.CST_STACK.length - 1]; + tt3.addTerminalToCst(n2, r, e), this.setNodeLocationFromToken(n2.location, r); + }, t2.prototype.cstPostNonTerminal = function(e, r) { + var n2 = this.CST_STACK[this.CST_STACK.length - 1]; + tt3.addNoneTerminalToCst(n2, r, e), this.setNodeLocationFromNode(n2.location, e.location); + }, t2.prototype.getBaseCstVisitorConstructor = function() { + if (K.isUndefined(this.baseCstVisitorConstructor)) { + var e = ta.createBaseSemanticVisitorConstructor(this.className, K.keys(this.gastProductionsCache)); + return this.baseCstVisitorConstructor = e, e; + } + return this.baseCstVisitorConstructor; + }, t2.prototype.getBaseCstVisitorConstructorWithDefaults = function() { + if (K.isUndefined(this.baseCstVisitorWithDefaultsConstructor)) { + var e = ta.createBaseVisitorConstructorWithDefaults(this.className, K.keys(this.gastProductionsCache), this.getBaseCstVisitorConstructor()); + return this.baseCstVisitorWithDefaultsConstructor = e, e; + } + return this.baseCstVisitorWithDefaultsConstructor; + }, t2.prototype.getLastExplicitRuleShortName = function() { + var e = this.RULE_STACK; + return e[e.length - 1]; + }, t2.prototype.getPreviousExplicitRuleShortName = function() { + var e = this.RULE_STACK; + return e[e.length - 2]; + }, t2.prototype.getLastExplicitRuleOccurrenceIndex = function() { + var e = this.RULE_OCCURRENCE_STACK; + return e[e.length - 1]; + }, t2; + }(); + $t.TreeBuilder = qs; +}); +var ia = R2((Zt) => { + Object.defineProperty(Zt, "__esModule", { value: true }); + Zt.LexerAdapter = undefined; + var na = ce2(), js = function() { + function t2() { + } + return t2.prototype.initLexerAdapter = function() { + this.tokVector = [], this.tokVectorLength = 0, this.currIdx = -1; + }, Object.defineProperty(t2.prototype, "input", { get: function() { + return this.tokVector; + }, set: function(e) { + if (this.selfAnalysisDone !== true) + throw Error("Missing invocation at the end of the Parser's constructor."); + this.reset(), this.tokVector = e, this.tokVectorLength = e.length; + }, enumerable: false, configurable: true }), t2.prototype.SKIP_TOKEN = function() { + return this.currIdx <= this.tokVector.length - 2 ? (this.consumeToken(), this.LA(1)) : na.END_OF_FILE; + }, t2.prototype.LA = function(e) { + var r = this.currIdx + e; + return r < 0 || this.tokVectorLength <= r ? na.END_OF_FILE : this.tokVector[r]; + }, t2.prototype.consumeToken = function() { + this.currIdx++; + }, t2.prototype.exportLexerState = function() { + return this.currIdx; + }, t2.prototype.importLexerState = function(e) { + this.currIdx = e; + }, t2.prototype.resetLexerState = function() { + this.currIdx = -1; + }, t2.prototype.moveToTerminatedState = function() { + this.currIdx = this.tokVector.length - 1; + }, t2.prototype.getLexerPosition = function() { + return this.exportLexerState(); + }, t2; + }(); + Zt.LexerAdapter = js; +}); +var oa = R2((Qt) => { + Object.defineProperty(Qt, "__esModule", { value: true }); + Qt.RecognizerApi = undefined; + var aa = k2(), Vs = et3(), Xr = ce2(), Ks = mt(), zs = jr(), Hs = ne(), Ys = function() { + function t2() { + } + return t2.prototype.ACTION = function(e) { + return e.call(this); + }, t2.prototype.consume = function(e, r, n2) { + return this.consumeInternal(r, e, n2); + }, t2.prototype.subrule = function(e, r, n2) { + return this.subruleInternal(r, e, n2); + }, t2.prototype.option = function(e, r) { + return this.optionInternal(r, e); + }, t2.prototype.or = function(e, r) { + return this.orInternal(r, e); + }, t2.prototype.many = function(e, r) { + return this.manyInternal(e, r); + }, t2.prototype.atLeastOne = function(e, r) { + return this.atLeastOneInternal(e, r); + }, t2.prototype.CONSUME = function(e, r) { + return this.consumeInternal(e, 0, r); + }, t2.prototype.CONSUME1 = function(e, r) { + return this.consumeInternal(e, 1, r); + }, t2.prototype.CONSUME2 = function(e, r) { + return this.consumeInternal(e, 2, r); + }, t2.prototype.CONSUME3 = function(e, r) { + return this.consumeInternal(e, 3, r); + }, t2.prototype.CONSUME4 = function(e, r) { + return this.consumeInternal(e, 4, r); + }, t2.prototype.CONSUME5 = function(e, r) { + return this.consumeInternal(e, 5, r); + }, t2.prototype.CONSUME6 = function(e, r) { + return this.consumeInternal(e, 6, r); + }, t2.prototype.CONSUME7 = function(e, r) { + return this.consumeInternal(e, 7, r); + }, t2.prototype.CONSUME8 = function(e, r) { + return this.consumeInternal(e, 8, r); + }, t2.prototype.CONSUME9 = function(e, r) { + return this.consumeInternal(e, 9, r); + }, t2.prototype.SUBRULE = function(e, r) { + return this.subruleInternal(e, 0, r); + }, t2.prototype.SUBRULE1 = function(e, r) { + return this.subruleInternal(e, 1, r); + }, t2.prototype.SUBRULE2 = function(e, r) { + return this.subruleInternal(e, 2, r); + }, t2.prototype.SUBRULE3 = function(e, r) { + return this.subruleInternal(e, 3, r); + }, t2.prototype.SUBRULE4 = function(e, r) { + return this.subruleInternal(e, 4, r); + }, t2.prototype.SUBRULE5 = function(e, r) { + return this.subruleInternal(e, 5, r); + }, t2.prototype.SUBRULE6 = function(e, r) { + return this.subruleInternal(e, 6, r); + }, t2.prototype.SUBRULE7 = function(e, r) { + return this.subruleInternal(e, 7, r); + }, t2.prototype.SUBRULE8 = function(e, r) { + return this.subruleInternal(e, 8, r); + }, t2.prototype.SUBRULE9 = function(e, r) { + return this.subruleInternal(e, 9, r); + }, t2.prototype.OPTION = function(e) { + return this.optionInternal(e, 0); + }, t2.prototype.OPTION1 = function(e) { + return this.optionInternal(e, 1); + }, t2.prototype.OPTION2 = function(e) { + return this.optionInternal(e, 2); + }, t2.prototype.OPTION3 = function(e) { + return this.optionInternal(e, 3); + }, t2.prototype.OPTION4 = function(e) { + return this.optionInternal(e, 4); + }, t2.prototype.OPTION5 = function(e) { + return this.optionInternal(e, 5); + }, t2.prototype.OPTION6 = function(e) { + return this.optionInternal(e, 6); + }, t2.prototype.OPTION7 = function(e) { + return this.optionInternal(e, 7); + }, t2.prototype.OPTION8 = function(e) { + return this.optionInternal(e, 8); + }, t2.prototype.OPTION9 = function(e) { + return this.optionInternal(e, 9); + }, t2.prototype.OR = function(e) { + return this.orInternal(e, 0); + }, t2.prototype.OR1 = function(e) { + return this.orInternal(e, 1); + }, t2.prototype.OR2 = function(e) { + return this.orInternal(e, 2); + }, t2.prototype.OR3 = function(e) { + return this.orInternal(e, 3); + }, t2.prototype.OR4 = function(e) { + return this.orInternal(e, 4); + }, t2.prototype.OR5 = function(e) { + return this.orInternal(e, 5); + }, t2.prototype.OR6 = function(e) { + return this.orInternal(e, 6); + }, t2.prototype.OR7 = function(e) { + return this.orInternal(e, 7); + }, t2.prototype.OR8 = function(e) { + return this.orInternal(e, 8); + }, t2.prototype.OR9 = function(e) { + return this.orInternal(e, 9); + }, t2.prototype.MANY = function(e) { + this.manyInternal(0, e); + }, t2.prototype.MANY1 = function(e) { + this.manyInternal(1, e); + }, t2.prototype.MANY2 = function(e) { + this.manyInternal(2, e); + }, t2.prototype.MANY3 = function(e) { + this.manyInternal(3, e); + }, t2.prototype.MANY4 = function(e) { + this.manyInternal(4, e); + }, t2.prototype.MANY5 = function(e) { + this.manyInternal(5, e); + }, t2.prototype.MANY6 = function(e) { + this.manyInternal(6, e); + }, t2.prototype.MANY7 = function(e) { + this.manyInternal(7, e); + }, t2.prototype.MANY8 = function(e) { + this.manyInternal(8, e); + }, t2.prototype.MANY9 = function(e) { + this.manyInternal(9, e); + }, t2.prototype.MANY_SEP = function(e) { + this.manySepFirstInternal(0, e); + }, t2.prototype.MANY_SEP1 = function(e) { + this.manySepFirstInternal(1, e); + }, t2.prototype.MANY_SEP2 = function(e) { + this.manySepFirstInternal(2, e); + }, t2.prototype.MANY_SEP3 = function(e) { + this.manySepFirstInternal(3, e); + }, t2.prototype.MANY_SEP4 = function(e) { + this.manySepFirstInternal(4, e); + }, t2.prototype.MANY_SEP5 = function(e) { + this.manySepFirstInternal(5, e); + }, t2.prototype.MANY_SEP6 = function(e) { + this.manySepFirstInternal(6, e); + }, t2.prototype.MANY_SEP7 = function(e) { + this.manySepFirstInternal(7, e); + }, t2.prototype.MANY_SEP8 = function(e) { + this.manySepFirstInternal(8, e); + }, t2.prototype.MANY_SEP9 = function(e) { + this.manySepFirstInternal(9, e); + }, t2.prototype.AT_LEAST_ONE = function(e) { + this.atLeastOneInternal(0, e); + }, t2.prototype.AT_LEAST_ONE1 = function(e) { + return this.atLeastOneInternal(1, e); + }, t2.prototype.AT_LEAST_ONE2 = function(e) { + this.atLeastOneInternal(2, e); + }, t2.prototype.AT_LEAST_ONE3 = function(e) { + this.atLeastOneInternal(3, e); + }, t2.prototype.AT_LEAST_ONE4 = function(e) { + this.atLeastOneInternal(4, e); + }, t2.prototype.AT_LEAST_ONE5 = function(e) { + this.atLeastOneInternal(5, e); + }, t2.prototype.AT_LEAST_ONE6 = function(e) { + this.atLeastOneInternal(6, e); + }, t2.prototype.AT_LEAST_ONE7 = function(e) { + this.atLeastOneInternal(7, e); + }, t2.prototype.AT_LEAST_ONE8 = function(e) { + this.atLeastOneInternal(8, e); + }, t2.prototype.AT_LEAST_ONE9 = function(e) { + this.atLeastOneInternal(9, e); + }, t2.prototype.AT_LEAST_ONE_SEP = function(e) { + this.atLeastOneSepFirstInternal(0, e); + }, t2.prototype.AT_LEAST_ONE_SEP1 = function(e) { + this.atLeastOneSepFirstInternal(1, e); + }, t2.prototype.AT_LEAST_ONE_SEP2 = function(e) { + this.atLeastOneSepFirstInternal(2, e); + }, t2.prototype.AT_LEAST_ONE_SEP3 = function(e) { + this.atLeastOneSepFirstInternal(3, e); + }, t2.prototype.AT_LEAST_ONE_SEP4 = function(e) { + this.atLeastOneSepFirstInternal(4, e); + }, t2.prototype.AT_LEAST_ONE_SEP5 = function(e) { + this.atLeastOneSepFirstInternal(5, e); + }, t2.prototype.AT_LEAST_ONE_SEP6 = function(e) { + this.atLeastOneSepFirstInternal(6, e); + }, t2.prototype.AT_LEAST_ONE_SEP7 = function(e) { + this.atLeastOneSepFirstInternal(7, e); + }, t2.prototype.AT_LEAST_ONE_SEP8 = function(e) { + this.atLeastOneSepFirstInternal(8, e); + }, t2.prototype.AT_LEAST_ONE_SEP9 = function(e) { + this.atLeastOneSepFirstInternal(9, e); + }, t2.prototype.RULE = function(e, r, n2) { + if (n2 === undefined && (n2 = Xr.DEFAULT_RULE_CONFIG), aa.contains(this.definedRulesNames, e)) { + var i = Ks.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({ topLevelRule: e, grammarName: this.className }), a = { message: i, type: Xr.ParserDefinitionErrorType.DUPLICATE_RULE_NAME, ruleName: e }; + this.definitionErrors.push(a); + } + this.definedRulesNames.push(e); + var o = this.defineRule(e, r, n2); + return this[e] = o, o; + }, t2.prototype.OVERRIDE_RULE = function(e, r, n2) { + n2 === undefined && (n2 = Xr.DEFAULT_RULE_CONFIG); + var i = []; + i = i.concat(zs.validateRuleIsOverridden(e, this.definedRulesNames, this.className)), this.definitionErrors = this.definitionErrors.concat(i); + var a = this.defineRule(e, r, n2); + return this[e] = a, a; + }, t2.prototype.BACKTRACK = function(e, r) { + return function() { + this.isBackTrackingStack.push(1); + var n2 = this.saveRecogState(); + try { + return e.apply(this, r), true; + } catch (i) { + if (Vs.isRecognitionException(i)) + return false; + throw i; + } finally { + this.reloadRecogState(n2), this.isBackTrackingStack.pop(); + } + }; + }, t2.prototype.getGAstProductions = function() { + return this.gastProductionsCache; + }, t2.prototype.getSerializedGastProductions = function() { + return Hs.serializeGrammar(aa.values(this.gastProductionsCache)); + }, t2; + }(); + Qt.RecognizerApi = Ys; +}); +var la = R2((Jt) => { + Object.defineProperty(Jt, "__esModule", { value: true }); + Jt.RecognizerEngine = undefined; + var q2 = k2(), le = Yt(), er = et3(), sa = yt2(), rt2 = Tt2(), ua = ce2(), Xs = zr(), ca = Ue(), Rt = Xe(), $s = Hr(), Zs = function() { + function t2() { + } + return t2.prototype.initRecognizerEngine = function(e, r) { + if (this.className = $s.classNameFromInstance(this), this.shortRuleNameToFull = {}, this.fullRuleNameToShort = {}, this.ruleShortNameIdx = 256, this.tokenMatcher = Rt.tokenStructuredMatcherNoCategories, this.definedRulesNames = [], this.tokensMap = {}, this.isBackTrackingStack = [], this.RULE_STACK = [], this.RULE_OCCURRENCE_STACK = [], this.gastProductionsCache = {}, q2.has(r, "serializedGrammar")) + throw Error(`The Parser's configuration can no longer contain a property. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 + For Further details.`); + if (q2.isArray(e)) { + if (q2.isEmpty(e)) + throw Error(`A Token Vocabulary cannot be empty. + Note that the first argument for the parser constructor + is no longer a Token vector (since v4.0).`); + if (typeof e[0].startOffset == "number") + throw Error(`The Parser constructor no longer accepts a token vector as the first argument. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 + For Further details.`); + } + if (q2.isArray(e)) + this.tokensMap = q2.reduce(e, function(o, s) { + return o[s.name] = s, o; + }, {}); + else if (q2.has(e, "modes") && q2.every(q2.flatten(q2.values(e.modes)), Rt.isTokenType)) { + var n2 = q2.flatten(q2.values(e.modes)), i = q2.uniq(n2); + this.tokensMap = q2.reduce(i, function(o, s) { + return o[s.name] = s, o; + }, {}); + } else if (q2.isObject(e)) + this.tokensMap = q2.cloneObj(e); + else + throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition"); + this.tokensMap.EOF = ca.EOF; + var a = q2.every(q2.values(e), function(o) { + return q2.isEmpty(o.categoryMatches); + }); + this.tokenMatcher = a ? Rt.tokenStructuredMatcherNoCategories : Rt.tokenStructuredMatcher, Rt.augmentTokenTypes(q2.values(this.tokensMap)); + }, t2.prototype.defineRule = function(e, r, n2) { + if (this.selfAnalysisDone) + throw Error("Grammar rule <" + e + `> may not be defined after the 'performSelfAnalysis' method has been called' +Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`); + var i = q2.has(n2, "resyncEnabled") ? n2.resyncEnabled : ua.DEFAULT_RULE_CONFIG.resyncEnabled, a = q2.has(n2, "recoveryValueFunc") ? n2.recoveryValueFunc : ua.DEFAULT_RULE_CONFIG.recoveryValueFunc, o = this.ruleShortNameIdx << le.BITS_FOR_METHOD_TYPE + le.BITS_FOR_OCCURRENCE_IDX; + this.ruleShortNameIdx++, this.shortRuleNameToFull[o] = e, this.fullRuleNameToShort[e] = o; + function s(p) { + try { + if (this.outputCst === true) { + r.apply(this, p); + var l2 = this.CST_STACK[this.CST_STACK.length - 1]; + return this.cstPostRule(l2), l2; + } else + return r.apply(this, p); + } catch (m) { + return this.invokeRuleCatch(m, i, a); + } finally { + this.ruleFinallyStateUpdate(); + } + } + var c = function(p, l2) { + return p === undefined && (p = 0), this.ruleInvocationStateUpdate(o, e, p), s.call(this, l2); + }, f = "ruleName"; + return c[f] = e, c.originalGrammarAction = r, c; + }, t2.prototype.invokeRuleCatch = function(e, r, n2) { + var i = this.RULE_STACK.length === 1, a = r && !this.isBackTracking() && this.recoveryEnabled; + if (er.isRecognitionException(e)) { + var o = e; + if (a) { + var s = this.findReSyncTokenType(); + if (this.isInCurrentRuleReSyncSet(s)) + if (o.resyncedTokens = this.reSyncTo(s), this.outputCst) { + var c = this.CST_STACK[this.CST_STACK.length - 1]; + return c.recoveredNode = true, c; + } else + return n2(); + else { + if (this.outputCst) { + var c = this.CST_STACK[this.CST_STACK.length - 1]; + c.recoveredNode = true, o.partialCstResult = c; + } + throw o; + } + } else { + if (i) + return this.moveToTerminatedState(), n2(); + throw o; + } + } else + throw e; + }, t2.prototype.optionInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.OPTION_IDX, r); + return this.optionInternalLogic(e, r, n2); + }, t2.prototype.optionInternalLogic = function(e, r, n2) { + var i = this, a = this.getLaFuncFromCache(n2), o, s; + if (e.DEF !== undefined) { + if (o = e.DEF, s = e.GATE, s !== undefined) { + var c = a; + a = function() { + return s.call(i) && c.call(i); + }; + } + } else + o = e; + if (a.call(this) === true) + return o.call(this); + }, t2.prototype.atLeastOneInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.AT_LEAST_ONE_IDX, e); + return this.atLeastOneInternalLogic(e, r, n2); + }, t2.prototype.atLeastOneInternalLogic = function(e, r, n2) { + var i = this, a = this.getLaFuncFromCache(n2), o, s; + if (r.DEF !== undefined) { + if (o = r.DEF, s = r.GATE, s !== undefined) { + var c = a; + a = function() { + return s.call(i) && c.call(i); + }; + } + } else + o = r; + if (a.call(this) === true) + for (var f = this.doSingleRepetition(o);a.call(this) === true && f === true; ) + f = this.doSingleRepetition(o); + else + throw this.raiseEarlyExitException(e, sa.PROD_TYPE.REPETITION_MANDATORY, r.ERR_MSG); + this.attemptInRepetitionRecovery(this.atLeastOneInternal, [e, r], a, le.AT_LEAST_ONE_IDX, e, rt2.NextTerminalAfterAtLeastOneWalker); + }, t2.prototype.atLeastOneSepFirstInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.AT_LEAST_ONE_SEP_IDX, e); + this.atLeastOneSepFirstInternalLogic(e, r, n2); + }, t2.prototype.atLeastOneSepFirstInternalLogic = function(e, r, n2) { + var i = this, a = r.DEF, o = r.SEP, s = this.getLaFuncFromCache(n2); + if (s.call(this) === true) { + a.call(this); + for (var c = function() { + return i.tokenMatcher(i.LA(1), o); + };this.tokenMatcher(this.LA(1), o) === true; ) + this.CONSUME(o), a.call(this); + this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [e, o, c, a, rt2.NextTerminalAfterAtLeastOneSepWalker], c, le.AT_LEAST_ONE_SEP_IDX, e, rt2.NextTerminalAfterAtLeastOneSepWalker); + } else + throw this.raiseEarlyExitException(e, sa.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, r.ERR_MSG); + }, t2.prototype.manyInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.MANY_IDX, e); + return this.manyInternalLogic(e, r, n2); + }, t2.prototype.manyInternalLogic = function(e, r, n2) { + var i = this, a = this.getLaFuncFromCache(n2), o, s; + if (r.DEF !== undefined) { + if (o = r.DEF, s = r.GATE, s !== undefined) { + var c = a; + a = function() { + return s.call(i) && c.call(i); + }; + } + } else + o = r; + for (var f = true;a.call(this) === true && f === true; ) + f = this.doSingleRepetition(o); + this.attemptInRepetitionRecovery(this.manyInternal, [e, r], a, le.MANY_IDX, e, rt2.NextTerminalAfterManyWalker, f); + }, t2.prototype.manySepFirstInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.MANY_SEP_IDX, e); + this.manySepFirstInternalLogic(e, r, n2); + }, t2.prototype.manySepFirstInternalLogic = function(e, r, n2) { + var i = this, a = r.DEF, o = r.SEP, s = this.getLaFuncFromCache(n2); + if (s.call(this) === true) { + a.call(this); + for (var c = function() { + return i.tokenMatcher(i.LA(1), o); + };this.tokenMatcher(this.LA(1), o) === true; ) + this.CONSUME(o), a.call(this); + this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [e, o, c, a, rt2.NextTerminalAfterManySepWalker], c, le.MANY_SEP_IDX, e, rt2.NextTerminalAfterManySepWalker); + } + }, t2.prototype.repetitionSepSecondInternal = function(e, r, n2, i, a) { + for (;n2(); ) + this.CONSUME(r), i.call(this); + this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [e, r, n2, i, a], n2, le.AT_LEAST_ONE_SEP_IDX, e, a); + }, t2.prototype.doSingleRepetition = function(e) { + var r = this.getLexerPosition(); + e.call(this); + var n2 = this.getLexerPosition(); + return n2 > r; + }, t2.prototype.orInternal = function(e, r) { + var n2 = this.getKeyForAutomaticLookahead(le.OR_IDX, r), i = q2.isArray(e) ? e : e.DEF, a = this.getLaFuncFromCache(n2), o = a.call(this, i); + if (o !== undefined) { + var s = i[o]; + return s.ALT.call(this); + } + this.raiseNoAltException(r, e.ERR_MSG); + }, t2.prototype.ruleFinallyStateUpdate = function() { + if (this.RULE_STACK.pop(), this.RULE_OCCURRENCE_STACK.pop(), this.cstFinallyStateUpdate(), this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) { + var e = this.LA(1), r = this.errorMessageProvider.buildNotAllInputParsedMessage({ firstRedundant: e, ruleName: this.getCurrRuleFullName() }); + this.SAVE_ERROR(new er.NotAllInputParsedException(r, e)); + } + }, t2.prototype.subruleInternal = function(e, r, n2) { + var i; + try { + var a = n2 !== undefined ? n2.ARGS : undefined; + return i = e.call(this, r, a), this.cstPostNonTerminal(i, n2 !== undefined && n2.LABEL !== undefined ? n2.LABEL : e.ruleName), i; + } catch (o) { + this.subruleInternalError(o, n2, e.ruleName); + } + }, t2.prototype.subruleInternalError = function(e, r, n2) { + throw er.isRecognitionException(e) && e.partialCstResult !== undefined && (this.cstPostNonTerminal(e.partialCstResult, r !== undefined && r.LABEL !== undefined ? r.LABEL : n2), delete e.partialCstResult), e; + }, t2.prototype.consumeInternal = function(e, r, n2) { + var i; + try { + var a = this.LA(1); + this.tokenMatcher(a, e) === true ? (this.consumeToken(), i = a) : this.consumeInternalError(e, a, n2); + } catch (o) { + i = this.consumeInternalRecovery(e, r, o); + } + return this.cstPostTerminal(n2 !== undefined && n2.LABEL !== undefined ? n2.LABEL : e.name, i), i; + }, t2.prototype.consumeInternalError = function(e, r, n2) { + var i, a = this.LA(0); + throw n2 !== undefined && n2.ERR_MSG ? i = n2.ERR_MSG : i = this.errorMessageProvider.buildMismatchTokenMessage({ expected: e, actual: r, previous: a, ruleName: this.getCurrRuleFullName() }), this.SAVE_ERROR(new er.MismatchedTokenException(i, r, a)); + }, t2.prototype.consumeInternalRecovery = function(e, r, n2) { + if (this.recoveryEnabled && n2.name === "MismatchedTokenException" && !this.isBackTracking()) { + var i = this.getFollowsForInRuleRecovery(e, r); + try { + return this.tryInRuleRecovery(e, i); + } catch (a) { + throw a.name === Xs.IN_RULE_RECOVERY_EXCEPTION ? n2 : a; + } + } else + throw n2; + }, t2.prototype.saveRecogState = function() { + var e = this.errors, r = q2.cloneArr(this.RULE_STACK); + return { errors: e, lexerState: this.exportLexerState(), RULE_STACK: r, CST_STACK: this.CST_STACK }; + }, t2.prototype.reloadRecogState = function(e) { + this.errors = e.errors, this.importLexerState(e.lexerState), this.RULE_STACK = e.RULE_STACK; + }, t2.prototype.ruleInvocationStateUpdate = function(e, r, n2) { + this.RULE_OCCURRENCE_STACK.push(n2), this.RULE_STACK.push(e), this.cstInvocationStateUpdate(r, e); + }, t2.prototype.isBackTracking = function() { + return this.isBackTrackingStack.length !== 0; + }, t2.prototype.getCurrRuleFullName = function() { + var e = this.getLastExplicitRuleShortName(); + return this.shortRuleNameToFull[e]; + }, t2.prototype.shortRuleNameToFullName = function(e) { + return this.shortRuleNameToFull[e]; + }, t2.prototype.isAtEndOfInput = function() { + return this.tokenMatcher(this.LA(1), ca.EOF); + }, t2.prototype.reset = function() { + this.resetLexerState(), this.isBackTrackingStack = [], this.errors = [], this.RULE_STACK = [], this.CST_STACK = [], this.RULE_OCCURRENCE_STACK = []; + }, t2; + }(); + Jt.RecognizerEngine = Zs; +}); +var pa = R2((tr) => { + Object.defineProperty(tr, "__esModule", { value: true }); + tr.ErrorHandler = undefined; + var $r2 = et3(), Zr = k2(), fa = yt2(), Qs = ce2(), Js = function() { + function t2() { + } + return t2.prototype.initErrorHandler = function(e) { + this._errors = [], this.errorMessageProvider = Zr.has(e, "errorMessageProvider") ? e.errorMessageProvider : Qs.DEFAULT_PARSER_CONFIG.errorMessageProvider; + }, t2.prototype.SAVE_ERROR = function(e) { + if ($r2.isRecognitionException(e)) + return e.context = { ruleStack: this.getHumanReadableRuleStack(), ruleOccurrenceStack: Zr.cloneArr(this.RULE_OCCURRENCE_STACK) }, this._errors.push(e), e; + throw Error("Trying to save an Error which is not a RecognitionException"); + }, Object.defineProperty(t2.prototype, "errors", { get: function() { + return Zr.cloneArr(this._errors); + }, set: function(e) { + this._errors = e; + }, enumerable: false, configurable: true }), t2.prototype.raiseEarlyExitException = function(e, r, n2) { + for (var i = this.getCurrRuleFullName(), a = this.getGAstProductions()[i], o = fa.getLookaheadPathsForOptionalProd(e, a, r, this.maxLookahead), s = o[0], c = [], f = 1;f <= this.maxLookahead; f++) + c.push(this.LA(f)); + var p = this.errorMessageProvider.buildEarlyExitMessage({ expectedIterationPaths: s, actual: c, previous: this.LA(0), customUserDescription: n2, ruleName: i }); + throw this.SAVE_ERROR(new $r2.EarlyExitException(p, this.LA(1), this.LA(0))); + }, t2.prototype.raiseNoAltException = function(e, r) { + for (var n2 = this.getCurrRuleFullName(), i = this.getGAstProductions()[n2], a = fa.getLookaheadPathsForOr(e, i, this.maxLookahead), o = [], s = 1;s <= this.maxLookahead; s++) + o.push(this.LA(s)); + var c = this.LA(0), f = this.errorMessageProvider.buildNoViableAltMessage({ expectedPathsPerAlt: a, actual: o, previous: c, customUserDescription: r, ruleName: this.getCurrRuleFullName() }); + throw this.SAVE_ERROR(new $r2.NoViableAltException(f, this.LA(1), c)); + }, t2; + }(); + tr.ErrorHandler = Js; +}); +var va = R2((rr) => { + Object.defineProperty(rr, "__esModule", { value: true }); + rr.ContentAssist = undefined; + var ha = Tt2(), da = k2(), eu = function() { + function t2() { + } + return t2.prototype.initContentAssist = function() { + }, t2.prototype.computeContentAssist = function(e, r) { + var n2 = this.gastProductionsCache[e]; + if (da.isUndefined(n2)) + throw Error("Rule ->" + e + "<- does not exist in this grammar."); + return ha.nextPossibleTokensAfter([n2], r, this.tokenMatcher, this.maxLookahead); + }, t2.prototype.getNextPossibleTokenTypes = function(e) { + var r = da.first(e.ruleStack), n2 = this.getGAstProductions(), i = n2[r], a = new ha.NextAfterTokenWalker(i, e).startWalking(); + return a; + }, t2; + }(); + rr.ContentAssist = eu; +}); +var Ra = R2((nr) => { + Object.defineProperty(nr, "__esModule", { value: true }); + nr.GastRecorder = undefined; + var oe = k2(), Pe = ne(), tu = ft(), ma = Xe(), Ea = Ue(), ru = ce2(), nu = Yt(), ir2 = { description: "This Object indicates the Parser is during Recording Phase" }; + Object.freeze(ir2); + var Ta = true, ya = Math.pow(2, nu.BITS_FOR_OCCURRENCE_IDX) - 1, _a2 = Ea.createToken({ name: "RECORDING_PHASE_TOKEN", pattern: tu.Lexer.NA }); + ma.augmentTokenTypes([_a2]); + var ga = Ea.createTokenInstance(_a2, `This IToken indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`, -1, -1, -1, -1, -1, -1); + Object.freeze(ga); + var iu = { name: `This CSTNode indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`, children: {} }, ou = function() { + function t2() { + } + return t2.prototype.initGastRecorder = function(e) { + this.recordingProdStack = [], this.RECORDING_PHASE = false; + }, t2.prototype.enableRecording = function() { + var e = this; + this.RECORDING_PHASE = true, this.TRACE_INIT("Enable Recording", function() { + for (var r = function(i) { + var a = i > 0 ? i : ""; + e["CONSUME" + a] = function(o, s) { + return this.consumeInternalRecord(o, i, s); + }, e["SUBRULE" + a] = function(o, s) { + return this.subruleInternalRecord(o, i, s); + }, e["OPTION" + a] = function(o) { + return this.optionInternalRecord(o, i); + }, e["OR" + a] = function(o) { + return this.orInternalRecord(o, i); + }, e["MANY" + a] = function(o) { + this.manyInternalRecord(i, o); + }, e["MANY_SEP" + a] = function(o) { + this.manySepFirstInternalRecord(i, o); + }, e["AT_LEAST_ONE" + a] = function(o) { + this.atLeastOneInternalRecord(i, o); + }, e["AT_LEAST_ONE_SEP" + a] = function(o) { + this.atLeastOneSepFirstInternalRecord(i, o); + }; + }, n2 = 0;n2 < 10; n2++) + r(n2); + e.consume = function(i, a, o) { + return this.consumeInternalRecord(a, i, o); + }, e.subrule = function(i, a, o) { + return this.subruleInternalRecord(a, i, o); + }, e.option = function(i, a) { + return this.optionInternalRecord(a, i); + }, e.or = function(i, a) { + return this.orInternalRecord(a, i); + }, e.many = function(i, a) { + this.manyInternalRecord(i, a); + }, e.atLeastOne = function(i, a) { + this.atLeastOneInternalRecord(i, a); + }, e.ACTION = e.ACTION_RECORD, e.BACKTRACK = e.BACKTRACK_RECORD, e.LA = e.LA_RECORD; + }); + }, t2.prototype.disableRecording = function() { + var e = this; + this.RECORDING_PHASE = false, this.TRACE_INIT("Deleting Recording methods", function() { + for (var r = 0;r < 10; r++) { + var n2 = r > 0 ? r : ""; + delete e["CONSUME" + n2], delete e["SUBRULE" + n2], delete e["OPTION" + n2], delete e["OR" + n2], delete e["MANY" + n2], delete e["MANY_SEP" + n2], delete e["AT_LEAST_ONE" + n2], delete e["AT_LEAST_ONE_SEP" + n2]; + } + delete e.consume, delete e.subrule, delete e.option, delete e.or, delete e.many, delete e.atLeastOne, delete e.ACTION, delete e.BACKTRACK, delete e.LA; + }); + }, t2.prototype.ACTION_RECORD = function(e) { + }, t2.prototype.BACKTRACK_RECORD = function(e, r) { + return function() { + return true; + }; + }, t2.prototype.LA_RECORD = function(e) { + return ru.END_OF_FILE; + }, t2.prototype.topLevelRuleRecord = function(e, r) { + try { + var n2 = new Pe.Rule({ definition: [], name: e }); + return n2.name = e, this.recordingProdStack.push(n2), r.call(this), this.recordingProdStack.pop(), n2; + } catch (i) { + if (i.KNOWN_RECORDER_ERROR !== true) + try { + i.message = i.message + ` + This error was thrown during the "grammar recording phase" For more info see: + https://chevrotain.io/docs/guide/internals.html#grammar-recording`; + } catch (a) { + throw i; + } + throw i; + } + }, t2.prototype.optionInternalRecord = function(e, r) { + return Ot.call(this, Pe.Option, e, r); + }, t2.prototype.atLeastOneInternalRecord = function(e, r) { + Ot.call(this, Pe.RepetitionMandatory, r, e); + }, t2.prototype.atLeastOneSepFirstInternalRecord = function(e, r) { + Ot.call(this, Pe.RepetitionMandatoryWithSeparator, r, e, Ta); + }, t2.prototype.manyInternalRecord = function(e, r) { + Ot.call(this, Pe.Repetition, r, e); + }, t2.prototype.manySepFirstInternalRecord = function(e, r) { + Ot.call(this, Pe.RepetitionWithSeparator, r, e, Ta); + }, t2.prototype.orInternalRecord = function(e, r) { + return au.call(this, e, r); + }, t2.prototype.subruleInternalRecord = function(e, r, n2) { + if (ar(r), !e || oe.has(e, "ruleName") === false) { + var i = new Error(" argument is invalid" + (" expecting a Parser method reference but got: <" + JSON.stringify(e) + ">") + (` + inside top level rule: <` + this.recordingProdStack[0].name + ">")); + throw i.KNOWN_RECORDER_ERROR = true, i; + } + var a = oe.peek(this.recordingProdStack), o = e.ruleName, s = new Pe.NonTerminal({ idx: r, nonTerminalName: o, referencedRule: undefined }); + return a.definition.push(s), this.outputCst ? iu : ir2; + }, t2.prototype.consumeInternalRecord = function(e, r, n2) { + if (ar(r), !ma.hasShortKeyProperty(e)) { + var i = new Error(" argument is invalid" + (" expecting a TokenType reference but got: <" + JSON.stringify(e) + ">") + (` + inside top level rule: <` + this.recordingProdStack[0].name + ">")); + throw i.KNOWN_RECORDER_ERROR = true, i; + } + var a = oe.peek(this.recordingProdStack), o = new Pe.Terminal({ idx: r, terminalType: e }); + return a.definition.push(o), ga; + }, t2; + }(); + nr.GastRecorder = ou; + function Ot(t2, e, r, n2) { + n2 === undefined && (n2 = false), ar(r); + var i = oe.peek(this.recordingProdStack), a = oe.isFunction(e) ? e : e.DEF, o = new t2({ definition: [], idx: r }); + return n2 && (o.separator = e.SEP), oe.has(e, "MAX_LOOKAHEAD") && (o.maxLookahead = e.MAX_LOOKAHEAD), this.recordingProdStack.push(o), a.call(this), i.definition.push(o), this.recordingProdStack.pop(), ir2; + } + function au(t2, e) { + var r = this; + ar(e); + var n2 = oe.peek(this.recordingProdStack), i = oe.isArray(t2) === false, a = i === false ? t2 : t2.DEF, o = new Pe.Alternation({ definition: [], idx: e, ignoreAmbiguities: i && t2.IGNORE_AMBIGUITIES === true }); + oe.has(t2, "MAX_LOOKAHEAD") && (o.maxLookahead = t2.MAX_LOOKAHEAD); + var s = oe.some(a, function(c) { + return oe.isFunction(c.GATE); + }); + return o.hasPredicates = s, n2.definition.push(o), oe.forEach(a, function(c) { + var f = new Pe.Alternative({ definition: [] }); + o.definition.push(f), oe.has(c, "IGNORE_AMBIGUITIES") ? f.ignoreAmbiguities = c.IGNORE_AMBIGUITIES : oe.has(c, "GATE") && (f.ignoreAmbiguities = true), r.recordingProdStack.push(f), c.ALT.call(r), r.recordingProdStack.pop(); + }), ir2; + } + function Aa(t2) { + return t2 === 0 ? "" : "" + t2; + } + function ar(t2) { + if (t2 < 0 || t2 > ya) { + var e = new Error("Invalid DSL Method idx value: <" + t2 + `> + ` + ("Idx value must be a none negative value smaller than " + (ya + 1))); + throw e.KNOWN_RECORDER_ERROR = true, e; + } + } +}); +var Na = R2((or) => { + Object.defineProperty(or, "__esModule", { value: true }); + or.PerformanceTracer = undefined; + var Oa = k2(), su = ce2(), uu = function() { + function t2() { + } + return t2.prototype.initPerformanceTracer = function(e) { + if (Oa.has(e, "traceInitPerf")) { + var r = e.traceInitPerf, n2 = typeof r == "number"; + this.traceInitMaxIdent = n2 ? r : Infinity, this.traceInitPerf = n2 ? r > 0 : r; + } else + this.traceInitMaxIdent = 0, this.traceInitPerf = su.DEFAULT_PARSER_CONFIG.traceInitPerf; + this.traceInitIndent = -1; + }, t2.prototype.TRACE_INIT = function(e, r) { + if (this.traceInitPerf === true) { + this.traceInitIndent++; + var n2 = new Array(this.traceInitIndent + 1).join("\t"); + this.traceInitIndent < this.traceInitMaxIdent && console.log(n2 + "--> <" + e + ">"); + var i = Oa.timer(r), a = i.time, o = i.value, s = a > 10 ? console.warn : console.log; + return this.traceInitIndent < this.traceInitMaxIdent && s(n2 + "<-- <" + e + "> time: " + a + "ms"), this.traceInitIndent--, o; + } else + return r(); + }, t2; + }(); + or.PerformanceTracer = uu; +}); +var Ia = R2((sr) => { + Object.defineProperty(sr, "__esModule", { value: true }); + sr.applyMixins = undefined; + function cu(t2, e) { + e.forEach(function(r) { + var n2 = r.prototype; + Object.getOwnPropertyNames(n2).forEach(function(i) { + if (i !== "constructor") { + var a = Object.getOwnPropertyDescriptor(n2, i); + a && (a.get || a.set) ? Object.defineProperty(t2.prototype, i, a) : t2.prototype[i] = r.prototype[i]; + } + }); + }); + } + sr.applyMixins = cu; +}); +var ce2 = R2((U) => { + var ka = U && U.__extends || function() { + var t2 = function(e, r) { + return t2 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(n2, i) { + n2.__proto__ = i; + } || function(n2, i) { + for (var a in i) + Object.prototype.hasOwnProperty.call(i, a) && (n2[a] = i[a]); + }, t2(e, r); + }; + return function(e, r) { + if (typeof r != "function" && r !== null) + throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + t2(e, r); + function n2() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (n2.prototype = r.prototype, new n2); + }; + }(); + Object.defineProperty(U, "__esModule", { value: true }); + U.EmbeddedActionsParser = U.CstParser = U.Parser = U.EMPTY_ALT = U.ParserDefinitionErrorType = U.DEFAULT_RULE_CONFIG = U.DEFAULT_PARSER_CONFIG = U.END_OF_FILE = undefined; + var ee = k2(), lu = pi2(), Pa = Ue(), Sa = mt(), xa = Ui(), fu = zr(), pu = zi(), hu = ra(), du = ia(), vu = oa(), mu = la(), Eu = pa(), Tu = va(), yu = Ra(), _u = Na(), gu = Ia(); + U.END_OF_FILE = Pa.createTokenInstance(Pa.EOF, "", NaN, NaN, NaN, NaN, NaN, NaN); + Object.freeze(U.END_OF_FILE); + U.DEFAULT_PARSER_CONFIG = Object.freeze({ recoveryEnabled: false, maxLookahead: 3, dynamicTokensEnabled: false, outputCst: true, errorMessageProvider: Sa.defaultParserErrorProvider, nodeLocationTracking: "none", traceInitPerf: false, skipValidations: false }); + U.DEFAULT_RULE_CONFIG = Object.freeze({ recoveryValueFunc: function() { + }, resyncEnabled: true }); + var Au; + (function(t2) { + t2[t2.INVALID_RULE_NAME = 0] = "INVALID_RULE_NAME", t2[t2.DUPLICATE_RULE_NAME = 1] = "DUPLICATE_RULE_NAME", t2[t2.INVALID_RULE_OVERRIDE = 2] = "INVALID_RULE_OVERRIDE", t2[t2.DUPLICATE_PRODUCTIONS = 3] = "DUPLICATE_PRODUCTIONS", t2[t2.UNRESOLVED_SUBRULE_REF = 4] = "UNRESOLVED_SUBRULE_REF", t2[t2.LEFT_RECURSION = 5] = "LEFT_RECURSION", t2[t2.NONE_LAST_EMPTY_ALT = 6] = "NONE_LAST_EMPTY_ALT", t2[t2.AMBIGUOUS_ALTS = 7] = "AMBIGUOUS_ALTS", t2[t2.CONFLICT_TOKENS_RULES_NAMESPACE = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE", t2[t2.INVALID_TOKEN_NAME = 9] = "INVALID_TOKEN_NAME", t2[t2.NO_NON_EMPTY_LOOKAHEAD = 10] = "NO_NON_EMPTY_LOOKAHEAD", t2[t2.AMBIGUOUS_PREFIX_ALTS = 11] = "AMBIGUOUS_PREFIX_ALTS", t2[t2.TOO_MANY_ALTS = 12] = "TOO_MANY_ALTS"; + })(Au = U.ParserDefinitionErrorType || (U.ParserDefinitionErrorType = {})); + function Ru(t2) { + return t2 === undefined && (t2 = undefined), function() { + return t2; + }; + } + U.EMPTY_ALT = Ru; + var ur = function() { + function t2(e, r) { + this.definitionErrors = [], this.selfAnalysisDone = false; + var n2 = this; + if (n2.initErrorHandler(r), n2.initLexerAdapter(), n2.initLooksAhead(r), n2.initRecognizerEngine(e, r), n2.initRecoverable(r), n2.initTreeBuilder(r), n2.initContentAssist(), n2.initGastRecorder(r), n2.initPerformanceTracer(r), ee.has(r, "ignoredIssues")) + throw new Error(`The IParserConfig property has been deprecated. + Please use the flag on the relevant DSL method instead. + See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES + For further details.`); + this.skipValidations = ee.has(r, "skipValidations") ? r.skipValidations : U.DEFAULT_PARSER_CONFIG.skipValidations; + } + return t2.performSelfAnalysis = function(e) { + throw Error("The **static** `performSelfAnalysis` method has been deprecated.\t\nUse the **instance** method with the same name instead."); + }, t2.prototype.performSelfAnalysis = function() { + var e = this; + this.TRACE_INIT("performSelfAnalysis", function() { + var r; + e.selfAnalysisDone = true; + var n2 = e.className; + e.TRACE_INIT("toFastProps", function() { + ee.toFastProperties(e); + }), e.TRACE_INIT("Grammar Recording", function() { + try { + e.enableRecording(), ee.forEach(e.definedRulesNames, function(a) { + var o = e[a], s = o.originalGrammarAction, c = undefined; + e.TRACE_INIT(a + " Rule", function() { + c = e.topLevelRuleRecord(a, s); + }), e.gastProductionsCache[a] = c; + }); + } finally { + e.disableRecording(); + } + }); + var i = []; + if (e.TRACE_INIT("Grammar Resolving", function() { + i = xa.resolveGrammar({ rules: ee.values(e.gastProductionsCache) }), e.definitionErrors = e.definitionErrors.concat(i); + }), e.TRACE_INIT("Grammar Validations", function() { + if (ee.isEmpty(i) && e.skipValidations === false) { + var a = xa.validateGrammar({ rules: ee.values(e.gastProductionsCache), maxLookahead: e.maxLookahead, tokenTypes: ee.values(e.tokensMap), errMsgProvider: Sa.defaultGrammarValidatorErrorProvider, grammarName: n2 }); + e.definitionErrors = e.definitionErrors.concat(a); + } + }), ee.isEmpty(e.definitionErrors) && (e.recoveryEnabled && e.TRACE_INIT("computeAllProdsFollows", function() { + var a = lu.computeAllProdsFollows(ee.values(e.gastProductionsCache)); + e.resyncFollows = a; + }), e.TRACE_INIT("ComputeLookaheadFunctions", function() { + e.preComputeLookaheadFunctions(ee.values(e.gastProductionsCache)); + })), !t2.DEFER_DEFINITION_ERRORS_HANDLING && !ee.isEmpty(e.definitionErrors)) + throw r = ee.map(e.definitionErrors, function(a) { + return a.message; + }), new Error(`Parser Definition Errors detected: + ` + r.join(` +------------------------------- +`)); + }); + }, t2.DEFER_DEFINITION_ERRORS_HANDLING = false, t2; + }(); + U.Parser = ur; + gu.applyMixins(ur, [fu.Recoverable, pu.LooksAhead, hu.TreeBuilder, du.LexerAdapter, mu.RecognizerEngine, vu.RecognizerApi, Eu.ErrorHandler, Tu.ContentAssist, yu.GastRecorder, _u.PerformanceTracer]); + var Ou = function(t2) { + ka(e, t2); + function e(r, n2) { + n2 === undefined && (n2 = U.DEFAULT_PARSER_CONFIG); + var i = this, a = ee.cloneObj(n2); + return a.outputCst = true, i = t2.call(this, r, a) || this, i; + } + return e; + }(ur); + U.CstParser = Ou; + var Nu = function(t2) { + ka(e, t2); + function e(r, n2) { + n2 === undefined && (n2 = U.DEFAULT_PARSER_CONFIG); + var i = this, a = ee.cloneObj(n2); + return a.outputCst = false, i = t2.call(this, r, a) || this, i; + } + return e; + }(ur); + U.EmbeddedActionsParser = Nu; +}); +var La = R2((cr) => { + Object.defineProperty(cr, "__esModule", { value: true }); + cr.createSyntaxDiagramsCode = undefined; + var Ca = Er2(); + function Iu(t2, e) { + var r = e === undefined ? {} : e, n2 = r.resourceBase, i = n2 === undefined ? "https://unpkg.com/chevrotain@" + Ca.VERSION + "/diagrams/" : n2, a = r.css, o = a === undefined ? "https://unpkg.com/chevrotain@" + Ca.VERSION + "/diagrams/diagrams.css" : a, s = ` + + + + + +`, c = ` + +`, f = ` + + + + +`, p = ` +
+`, l2 = ` + +`, m = ` + +`; + return s + c + f + p + l2 + m; + } + cr.createSyntaxDiagramsCode = Iu; +}); +var Fa = R2((E2) => { + Object.defineProperty(E2, "__esModule", { value: true }); + E2.Parser = E2.createSyntaxDiagramsCode = E2.clearCache = E2.GAstVisitor = E2.serializeProduction = E2.serializeGrammar = E2.Terminal = E2.Rule = E2.RepetitionWithSeparator = E2.RepetitionMandatoryWithSeparator = E2.RepetitionMandatory = E2.Repetition = E2.Option = E2.NonTerminal = E2.Alternative = E2.Alternation = E2.defaultLexerErrorProvider = E2.NoViableAltException = E2.NotAllInputParsedException = E2.MismatchedTokenException = E2.isRecognitionException = E2.EarlyExitException = E2.defaultParserErrorProvider = E2.tokenName = E2.tokenMatcher = E2.tokenLabel = E2.EOF = E2.createTokenInstance = E2.createToken = E2.LexerDefinitionErrorType = E2.Lexer = E2.EMPTY_ALT = E2.ParserDefinitionErrorType = E2.EmbeddedActionsParser = E2.CstParser = E2.VERSION = undefined; + var ku = Er2(); + Object.defineProperty(E2, "VERSION", { enumerable: true, get: function() { + return ku.VERSION; + } }); + var lr = ce2(); + Object.defineProperty(E2, "CstParser", { enumerable: true, get: function() { + return lr.CstParser; + } }); + Object.defineProperty(E2, "EmbeddedActionsParser", { enumerable: true, get: function() { + return lr.EmbeddedActionsParser; + } }); + Object.defineProperty(E2, "ParserDefinitionErrorType", { enumerable: true, get: function() { + return lr.ParserDefinitionErrorType; + } }); + Object.defineProperty(E2, "EMPTY_ALT", { enumerable: true, get: function() { + return lr.EMPTY_ALT; + } }); + var Ma = ft(); + Object.defineProperty(E2, "Lexer", { enumerable: true, get: function() { + return Ma.Lexer; + } }); + Object.defineProperty(E2, "LexerDefinitionErrorType", { enumerable: true, get: function() { + return Ma.LexerDefinitionErrorType; + } }); + var nt2 = Ue(); + Object.defineProperty(E2, "createToken", { enumerable: true, get: function() { + return nt2.createToken; + } }); + Object.defineProperty(E2, "createTokenInstance", { enumerable: true, get: function() { + return nt2.createTokenInstance; + } }); + Object.defineProperty(E2, "EOF", { enumerable: true, get: function() { + return nt2.EOF; + } }); + Object.defineProperty(E2, "tokenLabel", { enumerable: true, get: function() { + return nt2.tokenLabel; + } }); + Object.defineProperty(E2, "tokenMatcher", { enumerable: true, get: function() { + return nt2.tokenMatcher; + } }); + Object.defineProperty(E2, "tokenName", { enumerable: true, get: function() { + return nt2.tokenName; + } }); + var Pu = mt(); + Object.defineProperty(E2, "defaultParserErrorProvider", { enumerable: true, get: function() { + return Pu.defaultParserErrorProvider; + } }); + var Nt = et3(); + Object.defineProperty(E2, "EarlyExitException", { enumerable: true, get: function() { + return Nt.EarlyExitException; + } }); + Object.defineProperty(E2, "isRecognitionException", { enumerable: true, get: function() { + return Nt.isRecognitionException; + } }); + Object.defineProperty(E2, "MismatchedTokenException", { enumerable: true, get: function() { + return Nt.MismatchedTokenException; + } }); + Object.defineProperty(E2, "NotAllInputParsedException", { enumerable: true, get: function() { + return Nt.NotAllInputParsedException; + } }); + Object.defineProperty(E2, "NoViableAltException", { enumerable: true, get: function() { + return Nt.NoViableAltException; + } }); + var Su = kr(); + Object.defineProperty(E2, "defaultLexerErrorProvider", { enumerable: true, get: function() { + return Su.defaultLexerErrorProvider; + } }); + var Se2 = ne(); + Object.defineProperty(E2, "Alternation", { enumerable: true, get: function() { + return Se2.Alternation; + } }); + Object.defineProperty(E2, "Alternative", { enumerable: true, get: function() { + return Se2.Alternative; + } }); + Object.defineProperty(E2, "NonTerminal", { enumerable: true, get: function() { + return Se2.NonTerminal; + } }); + Object.defineProperty(E2, "Option", { enumerable: true, get: function() { + return Se2.Option; + } }); + Object.defineProperty(E2, "Repetition", { enumerable: true, get: function() { + return Se2.Repetition; + } }); + Object.defineProperty(E2, "RepetitionMandatory", { enumerable: true, get: function() { + return Se2.RepetitionMandatory; + } }); + Object.defineProperty(E2, "RepetitionMandatoryWithSeparator", { enumerable: true, get: function() { + return Se2.RepetitionMandatoryWithSeparator; + } }); + Object.defineProperty(E2, "RepetitionWithSeparator", { enumerable: true, get: function() { + return Se2.RepetitionWithSeparator; + } }); + Object.defineProperty(E2, "Rule", { enumerable: true, get: function() { + return Se2.Rule; + } }); + Object.defineProperty(E2, "Terminal", { enumerable: true, get: function() { + return Se2.Terminal; + } }); + var ba = ne(); + Object.defineProperty(E2, "serializeGrammar", { enumerable: true, get: function() { + return ba.serializeGrammar; + } }); + Object.defineProperty(E2, "serializeProduction", { enumerable: true, get: function() { + return ba.serializeProduction; + } }); + var xu = $e(); + Object.defineProperty(E2, "GAstVisitor", { enumerable: true, get: function() { + return xu.GAstVisitor; + } }); + function Cu() { + console.warn(`The clearCache function was 'soft' removed from the Chevrotain API. + It performs no action other than printing this message. + Please avoid using it as it will be completely removed in the future`); + } + E2.clearCache = Cu; + var Lu = La(); + Object.defineProperty(E2, "createSyntaxDiagramsCode", { enumerable: true, get: function() { + return Lu.createSyntaxDiagramsCode; + } }); + var Mu = function() { + function t2() { + throw new Error(`The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead. +See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_7-0-0`); + } + return t2; + }(); + E2.Parser = Mu; +}); +var chevrotain_module_min_default = Fa(); + +// node_modules/three/examples/jsm/loaders/VRMLLoader.js +var CstParser = chevrotain_module_min_default.CstParser; +// node_modules/three/examples/jsm/materials/MeshGouraudMaterial.js +var GouraudShader = { + name: "GouraudShader", + uniforms: UniformsUtils.merge([ + UniformsLib.common, + UniformsLib.specularmap, + UniformsLib.envmap, + UniformsLib.aomap, + UniformsLib.lightmap, + UniformsLib.emissivemap, + UniformsLib.fog, + UniformsLib.lights, + { + emissive: { value: new Color(0) } + } + ]), + vertexShader: ` + + #define GOURAUD + + varying vec3 vLightFront; + varying vec3 vIndirectFront; + + #ifdef DOUBLE_SIDED + varying vec3 vLightBack; + varying vec3 vIndirectBack; + #endif + + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + void main() { + + #include + #include + #include + + #include + #include + #include + #include + #include + + #include + #include + #include + #include + #include + #include + + #include + #include + + // inlining legacy + + vec3 diffuse = vec3( 1.0 ); + + vec3 geometryPosition = mvPosition.xyz; + vec3 geometryNormal = normalize( transformedNormal ); + vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz ); + + vec3 backGeometryNormal = - geometryNormal; + + vLightFront = vec3( 0.0 ); + vIndirectFront = vec3( 0.0 ); + #ifdef DOUBLE_SIDED + vLightBack = vec3( 0.0 ); + vIndirectBack = vec3( 0.0 ); + #endif + + IncidentLight directLight; + float dotNL; + vec3 directLightColor_Diffuse; + + vIndirectFront += getAmbientLightIrradiance( ambientLightColor ); + + #if defined( USE_LIGHT_PROBES ) + + vIndirectFront += getLightProbeIrradiance( lightProbe, geometryNormal ); + + #endif + + #ifdef DOUBLE_SIDED + + vIndirectBack += getAmbientLightIrradiance( ambientLightColor ); + + #if defined( USE_LIGHT_PROBES ) + + vIndirectBack += getLightProbeIrradiance( lightProbe, backGeometryNormal ); + + #endif + + #endif + + #if NUM_POINT_LIGHTS > 0 + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + + getPointLightInfo( pointLights[ i ], geometryPosition, directLight ); + + dotNL = dot( geometryNormal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + + #ifdef DOUBLE_SIDED + + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + + #endif + + } + #pragma unroll_loop_end + + #endif + + #if NUM_SPOT_LIGHTS > 0 + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + + getSpotLightInfo( spotLights[ i ], geometryPosition, directLight ); + + dotNL = dot( geometryNormal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + + #ifdef DOUBLE_SIDED + + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + + #endif + } + #pragma unroll_loop_end + + #endif + + #if NUM_DIR_LIGHTS > 0 + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + getDirectionalLightInfo( directionalLights[ i ], directLight ); + + dotNL = dot( geometryNormal, directLight.direction ); + directLightColor_Diffuse = directLight.color; + + vLightFront += saturate( dotNL ) * directLightColor_Diffuse; + + #ifdef DOUBLE_SIDED + + vLightBack += saturate( - dotNL ) * directLightColor_Diffuse; + + #endif + + } + #pragma unroll_loop_end + + #endif + + #if NUM_HEMI_LIGHTS > 0 + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + + vIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + + #ifdef DOUBLE_SIDED + + vIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometryNormal ); + + #endif + + } + #pragma unroll_loop_end + + #endif + + #include + #include + + }`, + fragmentShader: ` + + #define GOURAUD + + uniform vec3 diffuse; + uniform vec3 emissive; + uniform float opacity; + + varying vec3 vLightFront; + varying vec3 vIndirectFront; + + #ifdef DOUBLE_SIDED + varying vec3 vLightBack; + varying vec3 vIndirectBack; + #endif + + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + void main() { + + #include + + vec4 diffuseColor = vec4( diffuse, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + + #include + #include + #include + #include + #include + #include + #include + + // accumulation + + #ifdef DOUBLE_SIDED + + reflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack; + + #else + + reflectedLight.indirectDiffuse += vIndirectFront; + + #endif + + #ifdef USE_LIGHTMAP + + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + reflectedLight.indirectDiffuse += lightMapIrradiance; + + #endif + + reflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb ); + + #ifdef DOUBLE_SIDED + + reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack; + + #else + + reflectedLight.directDiffuse = vLightFront; + + #endif + + reflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask(); + + // modulation + + #include + + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + + #include + + #include + #include + #include + #include + #include + #include + + }` +}; +// node_modules/three/examples/jsm/math/Capsule.js +class Capsule { + constructor(start = new Vector3(0, 0, 0), end = new Vector3(0, 1, 0), radius = 1) { + this.start = start; + this.end = end; + this.radius = radius; + } + clone() { + return new Capsule(this.start.clone(), this.end.clone(), this.radius); + } + set(start, end, radius) { + this.start.copy(start); + this.end.copy(end); + this.radius = radius; + } + copy(capsule) { + this.start.copy(capsule.start); + this.end.copy(capsule.end); + this.radius = capsule.radius; + } + getCenter(target) { + return target.copy(this.end).add(this.start).multiplyScalar(0.5); + } + translate(v) { + this.start.add(v); + this.end.add(v); + } + checkAABBAxis(p1x, p1y, p2x, p2y, minx, maxx, miny, maxy, radius) { + return (minx - p1x < radius || minx - p2x < radius) && (p1x - maxx < radius || p2x - maxx < radius) && (miny - p1y < radius || miny - p2y < radius) && (p1y - maxy < radius || p2y - maxy < radius); + } + intersectsBox(box) { + return this.checkAABBAxis(this.start.x, this.start.y, this.end.x, this.end.y, box.min.x, box.max.x, box.min.y, box.max.y, this.radius) && this.checkAABBAxis(this.start.x, this.start.z, this.end.x, this.end.z, box.min.x, box.max.x, box.min.z, box.max.z, this.radius) && this.checkAABBAxis(this.start.y, this.start.z, this.end.y, this.end.z, box.min.y, box.max.y, box.min.z, box.max.z, this.radius); + } +} +// node_modules/three/examples/jsm/math/ImprovedNoise.js +var _p = [ + 151, + 160, + 137, + 91, + 90, + 15, + 131, + 13, + 201, + 95, + 96, + 53, + 194, + 233, + 7, + 225, + 140, + 36, + 103, + 30, + 69, + 142, + 8, + 99, + 37, + 240, + 21, + 10, + 23, + 190, + 6, + 148, + 247, + 120, + 234, + 75, + 0, + 26, + 197, + 62, + 94, + 252, + 219, + 203, + 117, + 35, + 11, + 32, + 57, + 177, + 33, + 88, + 237, + 149, + 56, + 87, + 174, + 20, + 125, + 136, + 171, + 168, + 68, + 175, + 74, + 165, + 71, + 134, + 139, + 48, + 27, + 166, + 77, + 146, + 158, + 231, + 83, + 111, + 229, + 122, + 60, + 211, + 133, + 230, + 220, + 105, + 92, + 41, + 55, + 46, + 245, + 40, + 244, + 102, + 143, + 54, + 65, + 25, + 63, + 161, + 1, + 216, + 80, + 73, + 209, + 76, + 132, + 187, + 208, + 89, + 18, + 169, + 200, + 196, + 135, + 130, + 116, + 188, + 159, + 86, + 164, + 100, + 109, + 198, + 173, + 186, + 3, + 64, + 52, + 217, + 226, + 250, + 124, + 123, + 5, + 202, + 38, + 147, + 118, + 126, + 255, + 82, + 85, + 212, + 207, + 206, + 59, + 227, + 47, + 16, + 58, + 17, + 182, + 189, + 28, + 42, + 223, + 183, + 170, + 213, + 119, + 248, + 152, + 2, + 44, + 154, + 163, + 70, + 221, + 153, + 101, + 155, + 167, + 43, + 172, + 9, + 129, + 22, + 39, + 253, + 19, + 98, + 108, + 110, + 79, + 113, + 224, + 232, + 178, + 185, + 112, + 104, + 218, + 246, + 97, + 228, + 251, + 34, + 242, + 193, + 238, + 210, + 144, + 12, + 191, + 179, + 162, + 241, + 81, + 51, + 145, + 235, + 249, + 14, + 239, + 107, + 49, + 192, + 214, + 31, + 181, + 199, + 106, + 157, + 184, + 84, + 204, + 176, + 115, + 121, + 50, + 45, + 127, + 4, + 150, + 254, + 138, + 236, + 205, + 93, + 222, + 114, + 67, + 29, + 24, + 72, + 243, + 141, + 128, + 195, + 78, + 66, + 215, + 61, + 156, + 180 +]; +for (let i = 0;i < 256; i++) { + _p[256 + i] = _p[i]; +} +// node_modules/three/examples/jsm/math/MeshSurfaceSampler.js +var _face = new Triangle; +var _color6 = new Vector3; +var _uva = new Vector2; +var _uvb = new Vector2; +var _uvc = new Vector2; +// node_modules/three/examples/jsm/math/OBB.js +var a = { + c: null, + u: [new Vector3, new Vector3, new Vector3], + e: [] +}; +var b = { + c: null, + u: [new Vector3, new Vector3, new Vector3], + e: [] +}; +var R3 = [[], [], []]; +var AbsR = [[], [], []]; +var t2 = []; +var xAxis = new Vector3; +var yAxis = new Vector3; +var zAxis = new Vector3; +var v1 = new Vector3; +var size = new Vector3; +var closestPoint = new Vector3; +var rotationMatrix = new Matrix3; +var aabb = new Box3; +var matrix = new Matrix4; +var inverse = new Matrix4; +var localRay = new Ray; + +class OBB { + constructor(center = new Vector3, halfSize = new Vector3, rotation2 = new Matrix3) { + this.center = center; + this.halfSize = halfSize; + this.rotation = rotation2; + } + set(center, halfSize, rotation2) { + this.center = center; + this.halfSize = halfSize; + this.rotation = rotation2; + return this; + } + copy(obb) { + this.center.copy(obb.center); + this.halfSize.copy(obb.halfSize); + this.rotation.copy(obb.rotation); + return this; + } + clone() { + return new this.constructor().copy(this); + } + getSize(result) { + return result.copy(this.halfSize).multiplyScalar(2); + } + clampPoint(point, result) { + const halfSize = this.halfSize; + v1.subVectors(point, this.center); + this.rotation.extractBasis(xAxis, yAxis, zAxis); + result.copy(this.center); + const x2 = MathUtils.clamp(v1.dot(xAxis), -halfSize.x, halfSize.x); + result.add(xAxis.multiplyScalar(x2)); + const y = MathUtils.clamp(v1.dot(yAxis), -halfSize.y, halfSize.y); + result.add(yAxis.multiplyScalar(y)); + const z = MathUtils.clamp(v1.dot(zAxis), -halfSize.z, halfSize.z); + result.add(zAxis.multiplyScalar(z)); + return result; + } + containsPoint(point) { + v1.subVectors(point, this.center); + this.rotation.extractBasis(xAxis, yAxis, zAxis); + return Math.abs(v1.dot(xAxis)) <= this.halfSize.x && Math.abs(v1.dot(yAxis)) <= this.halfSize.y && Math.abs(v1.dot(zAxis)) <= this.halfSize.z; + } + intersectsBox3(box3) { + return this.intersectsOBB(obb.fromBox3(box3)); + } + intersectsSphere(sphere) { + this.clampPoint(sphere.center, closestPoint); + return closestPoint.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; + } + intersectsOBB(obb, epsilon = Number.EPSILON) { + a.c = this.center; + a.e[0] = this.halfSize.x; + a.e[1] = this.halfSize.y; + a.e[2] = this.halfSize.z; + this.rotation.extractBasis(a.u[0], a.u[1], a.u[2]); + b.c = obb.center; + b.e[0] = obb.halfSize.x; + b.e[1] = obb.halfSize.y; + b.e[2] = obb.halfSize.z; + obb.rotation.extractBasis(b.u[0], b.u[1], b.u[2]); + for (let i = 0;i < 3; i++) { + for (let j2 = 0;j2 < 3; j2++) { + R3[i][j2] = a.u[i].dot(b.u[j2]); + } + } + v1.subVectors(b.c, a.c); + t2[0] = v1.dot(a.u[0]); + t2[1] = v1.dot(a.u[1]); + t2[2] = v1.dot(a.u[2]); + for (let i = 0;i < 3; i++) { + for (let j2 = 0;j2 < 3; j2++) { + AbsR[i][j2] = Math.abs(R3[i][j2]) + epsilon; + } + } + let ra2, rb; + for (let i = 0;i < 3; i++) { + ra2 = a.e[i]; + rb = b.e[0] * AbsR[i][0] + b.e[1] * AbsR[i][1] + b.e[2] * AbsR[i][2]; + if (Math.abs(t2[i]) > ra2 + rb) + return false; + } + for (let i = 0;i < 3; i++) { + ra2 = a.e[0] * AbsR[0][i] + a.e[1] * AbsR[1][i] + a.e[2] * AbsR[2][i]; + rb = b.e[i]; + if (Math.abs(t2[0] * R3[0][i] + t2[1] * R3[1][i] + t2[2] * R3[2][i]) > ra2 + rb) + return false; + } + ra2 = a.e[1] * AbsR[2][0] + a.e[2] * AbsR[1][0]; + rb = b.e[1] * AbsR[0][2] + b.e[2] * AbsR[0][1]; + if (Math.abs(t2[2] * R3[1][0] - t2[1] * R3[2][0]) > ra2 + rb) + return false; + ra2 = a.e[1] * AbsR[2][1] + a.e[2] * AbsR[1][1]; + rb = b.e[0] * AbsR[0][2] + b.e[2] * AbsR[0][0]; + if (Math.abs(t2[2] * R3[1][1] - t2[1] * R3[2][1]) > ra2 + rb) + return false; + ra2 = a.e[1] * AbsR[2][2] + a.e[2] * AbsR[1][2]; + rb = b.e[0] * AbsR[0][1] + b.e[1] * AbsR[0][0]; + if (Math.abs(t2[2] * R3[1][2] - t2[1] * R3[2][2]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[2][0] + a.e[2] * AbsR[0][0]; + rb = b.e[1] * AbsR[1][2] + b.e[2] * AbsR[1][1]; + if (Math.abs(t2[0] * R3[2][0] - t2[2] * R3[0][0]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[2][1] + a.e[2] * AbsR[0][1]; + rb = b.e[0] * AbsR[1][2] + b.e[2] * AbsR[1][0]; + if (Math.abs(t2[0] * R3[2][1] - t2[2] * R3[0][1]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[2][2] + a.e[2] * AbsR[0][2]; + rb = b.e[0] * AbsR[1][1] + b.e[1] * AbsR[1][0]; + if (Math.abs(t2[0] * R3[2][2] - t2[2] * R3[0][2]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[1][0] + a.e[1] * AbsR[0][0]; + rb = b.e[1] * AbsR[2][2] + b.e[2] * AbsR[2][1]; + if (Math.abs(t2[1] * R3[0][0] - t2[0] * R3[1][0]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[1][1] + a.e[1] * AbsR[0][1]; + rb = b.e[0] * AbsR[2][2] + b.e[2] * AbsR[2][0]; + if (Math.abs(t2[1] * R3[0][1] - t2[0] * R3[1][1]) > ra2 + rb) + return false; + ra2 = a.e[0] * AbsR[1][2] + a.e[1] * AbsR[0][2]; + rb = b.e[0] * AbsR[2][1] + b.e[1] * AbsR[2][0]; + if (Math.abs(t2[1] * R3[0][2] - t2[0] * R3[1][2]) > ra2 + rb) + return false; + return true; + } + intersectsPlane(plane) { + this.rotation.extractBasis(xAxis, yAxis, zAxis); + const r = this.halfSize.x * Math.abs(plane.normal.dot(xAxis)) + this.halfSize.y * Math.abs(plane.normal.dot(yAxis)) + this.halfSize.z * Math.abs(plane.normal.dot(zAxis)); + const d = plane.normal.dot(this.center) - plane.constant; + return Math.abs(d) <= r; + } + intersectRay(ray, result) { + this.getSize(size); + aabb.setFromCenterAndSize(v1.set(0, 0, 0), size); + matrix.setFromMatrix3(this.rotation); + matrix.setPosition(this.center); + inverse.copy(matrix).invert(); + localRay.copy(ray).applyMatrix4(inverse); + if (localRay.intersectBox(aabb, result)) { + return result.applyMatrix4(matrix); + } else { + return null; + } + } + intersectsRay(ray) { + return this.intersectRay(ray, v1) !== null; + } + fromBox3(box3) { + box3.getCenter(this.center); + box3.getSize(this.halfSize).multiplyScalar(0.5); + this.rotation.identity(); + return this; + } + equals(obb) { + return obb.center.equals(this.center) && obb.halfSize.equals(this.halfSize) && obb.rotation.equals(this.rotation); + } + applyMatrix4(matrix2) { + const e = matrix2.elements; + let sx = v1.set(e[0], e[1], e[2]).length(); + const sy = v1.set(e[4], e[5], e[6]).length(); + const sz = v1.set(e[8], e[9], e[10]).length(); + const det = matrix2.determinant(); + if (det < 0) + sx = -sx; + rotationMatrix.setFromMatrix4(matrix2); + const invSX = 1 / sx; + const invSY = 1 / sy; + const invSZ = 1 / sz; + rotationMatrix.elements[0] *= invSX; + rotationMatrix.elements[1] *= invSX; + rotationMatrix.elements[2] *= invSX; + rotationMatrix.elements[3] *= invSY; + rotationMatrix.elements[4] *= invSY; + rotationMatrix.elements[5] *= invSY; + rotationMatrix.elements[6] *= invSZ; + rotationMatrix.elements[7] *= invSZ; + rotationMatrix.elements[8] *= invSZ; + this.rotation.multiply(rotationMatrix); + this.halfSize.x *= sx; + this.halfSize.y *= sy; + this.halfSize.z *= sz; + v1.setFromMatrixPosition(matrix2); + this.center.add(v1); + return this; + } +} +var obb = new OBB; +// node_modules/three/examples/jsm/math/Octree.js +var _v16 = new Vector3; +var _v26 = new Vector3; +var _point1 = new Vector3; +var _point2 = new Vector3; +var _plane4 = new Plane; +var _line1 = new Line3; +var _line2 = new Line3; +var _sphere3 = new Sphere; +var _capsule = new Capsule; +var _temp1 = new Vector3; +var _temp2 = new Vector3; +var _temp3 = new Vector3; +// node_modules/three/examples/jsm/math/SimplexNoise.js +class SimplexNoise { + constructor(r = Math) { + this.grad3 = [ + [1, 1, 0], + [-1, 1, 0], + [1, -1, 0], + [-1, -1, 0], + [1, 0, 1], + [-1, 0, 1], + [1, 0, -1], + [-1, 0, -1], + [0, 1, 1], + [0, -1, 1], + [0, 1, -1], + [0, -1, -1] + ]; + this.grad4 = [ + [0, 1, 1, 1], + [0, 1, 1, -1], + [0, 1, -1, 1], + [0, 1, -1, -1], + [0, -1, 1, 1], + [0, -1, 1, -1], + [0, -1, -1, 1], + [0, -1, -1, -1], + [1, 0, 1, 1], + [1, 0, 1, -1], + [1, 0, -1, 1], + [1, 0, -1, -1], + [-1, 0, 1, 1], + [-1, 0, 1, -1], + [-1, 0, -1, 1], + [-1, 0, -1, -1], + [1, 1, 0, 1], + [1, 1, 0, -1], + [1, -1, 0, 1], + [1, -1, 0, -1], + [-1, 1, 0, 1], + [-1, 1, 0, -1], + [-1, -1, 0, 1], + [-1, -1, 0, -1], + [1, 1, 1, 0], + [1, 1, -1, 0], + [1, -1, 1, 0], + [1, -1, -1, 0], + [-1, 1, 1, 0], + [-1, 1, -1, 0], + [-1, -1, 1, 0], + [-1, -1, -1, 0] + ]; + this.p = []; + for (let i = 0;i < 256; i++) { + this.p[i] = Math.floor(r.random() * 256); + } + this.perm = []; + for (let i = 0;i < 512; i++) { + this.perm[i] = this.p[i & 255]; + } + this.simplex = [ + [0, 1, 2, 3], + [0, 1, 3, 2], + [0, 0, 0, 0], + [0, 2, 3, 1], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 2, 3, 0], + [0, 2, 1, 3], + [0, 0, 0, 0], + [0, 3, 1, 2], + [0, 3, 2, 1], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 3, 2, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [1, 2, 0, 3], + [0, 0, 0, 0], + [1, 3, 0, 2], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [2, 3, 0, 1], + [2, 3, 1, 0], + [1, 0, 2, 3], + [1, 0, 3, 2], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [2, 0, 3, 1], + [0, 0, 0, 0], + [2, 1, 3, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [2, 0, 1, 3], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [3, 0, 1, 2], + [3, 0, 2, 1], + [0, 0, 0, 0], + [3, 1, 2, 0], + [2, 1, 0, 3], + [0, 0, 0, 0], + [0, 0, 0, 0], + [0, 0, 0, 0], + [3, 1, 0, 2], + [0, 0, 0, 0], + [3, 2, 0, 1], + [3, 2, 1, 0] + ]; + } + dot(g3, x2, y) { + return g3[0] * x2 + g3[1] * y; + } + dot3(g3, x2, y, z) { + return g3[0] * x2 + g3[1] * y + g3[2] * z; + } + dot4(g3, x2, y, z, w) { + return g3[0] * x2 + g3[1] * y + g3[2] * z + g3[3] * w; + } + noise(xin, yin) { + let n0; + let n1; + let n2; + const F2 = 0.5 * (Math.sqrt(3) - 1); + const s = (xin + yin) * F2; + const i = Math.floor(xin + s); + const j2 = Math.floor(yin + s); + const G2 = (3 - Math.sqrt(3)) / 6; + const t3 = (i + j2) * G2; + const X0 = i - t3; + const Y0 = j2 - t3; + const x0 = xin - X0; + const y0 = yin - Y0; + let i1; + let j1; + if (x0 > y0) { + i1 = 1; + j1 = 0; + } else { + i1 = 0; + j1 = 1; + } + const x1 = x0 - i1 + G2; + const y1 = y0 - j1 + G2; + const x2 = x0 - 1 + 2 * G2; + const y2 = y0 - 1 + 2 * G2; + const ii = i & 255; + const jj = j2 & 255; + const gi0 = this.perm[ii + this.perm[jj]] % 12; + const gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12; + const gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12; + let t0 = 0.5 - x0 * x0 - y0 * y0; + if (t0 < 0) + n0 = 0; + else { + t0 *= t0; + n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0); + } + let t1 = 0.5 - x1 * x1 - y1 * y1; + if (t1 < 0) + n1 = 0; + else { + t1 *= t1; + n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1); + } + let t22 = 0.5 - x2 * x2 - y2 * y2; + if (t22 < 0) + n2 = 0; + else { + t22 *= t22; + n2 = t22 * t22 * this.dot(this.grad3[gi2], x2, y2); + } + return 70 * (n0 + n1 + n2); + } + noise3d(xin, yin, zin) { + let n0; + let n1; + let n2; + let n3; + const F3 = 1 / 3; + const s = (xin + yin + zin) * F3; + const i = Math.floor(xin + s); + const j2 = Math.floor(yin + s); + const k3 = Math.floor(zin + s); + const G3 = 1 / 6; + const t3 = (i + j2 + k3) * G3; + const X0 = i - t3; + const Y0 = j2 - t3; + const Z0 = k3 - t3; + const x0 = xin - X0; + const y0 = yin - Y0; + const z0 = zin - Z0; + let i1; + let j1; + let k1; + let i2; + let j22; + let k22; + if (x0 >= y0) { + if (y0 >= z0) { + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j22 = 1; + k22 = 0; + } else if (x0 >= z0) { + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j22 = 0; + k22 = 1; + } else { + i1 = 0; + j1 = 0; + k1 = 1; + i2 = 1; + j22 = 0; + k22 = 1; + } + } else { + if (y0 < z0) { + i1 = 0; + j1 = 0; + k1 = 1; + i2 = 0; + j22 = 1; + k22 = 1; + } else if (x0 < z0) { + i1 = 0; + j1 = 1; + k1 = 0; + i2 = 0; + j22 = 1; + k22 = 1; + } else { + i1 = 0; + j1 = 1; + k1 = 0; + i2 = 1; + j22 = 1; + k22 = 0; + } + } + const x1 = x0 - i1 + G3; + const y1 = y0 - j1 + G3; + const z1 = z0 - k1 + G3; + const x2 = x0 - i2 + 2 * G3; + const y2 = y0 - j22 + 2 * G3; + const z2 = z0 - k22 + 2 * G3; + const x3 = x0 - 1 + 3 * G3; + const y3 = y0 - 1 + 3 * G3; + const z3 = z0 - 1 + 3 * G3; + const ii = i & 255; + const jj = j2 & 255; + const kk = k3 & 255; + const gi0 = this.perm[ii + this.perm[jj + this.perm[kk]]] % 12; + const gi1 = this.perm[ii + i1 + this.perm[jj + j1 + this.perm[kk + k1]]] % 12; + const gi2 = this.perm[ii + i2 + this.perm[jj + j22 + this.perm[kk + k22]]] % 12; + const gi3 = this.perm[ii + 1 + this.perm[jj + 1 + this.perm[kk + 1]]] % 12; + let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0; + if (t0 < 0) + n0 = 0; + else { + t0 *= t0; + n0 = t0 * t0 * this.dot3(this.grad3[gi0], x0, y0, z0); + } + let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1; + if (t1 < 0) + n1 = 0; + else { + t1 *= t1; + n1 = t1 * t1 * this.dot3(this.grad3[gi1], x1, y1, z1); + } + let t22 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2; + if (t22 < 0) + n2 = 0; + else { + t22 *= t22; + n2 = t22 * t22 * this.dot3(this.grad3[gi2], x2, y2, z2); + } + let t32 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3; + if (t32 < 0) + n3 = 0; + else { + t32 *= t32; + n3 = t32 * t32 * this.dot3(this.grad3[gi3], x3, y3, z3); + } + return 32 * (n0 + n1 + n2 + n3); + } + noise4d(x2, y, z, w) { + const grad4 = this.grad4; + const simplex = this.simplex; + const perm = this.perm; + const F4 = (Math.sqrt(5) - 1) / 4; + const G4 = (5 - Math.sqrt(5)) / 20; + let n0; + let n1; + let n2; + let n3; + let n4; + const s = (x2 + y + z + w) * F4; + const i = Math.floor(x2 + s); + const j2 = Math.floor(y + s); + const k3 = Math.floor(z + s); + const l2 = Math.floor(w + s); + const t3 = (i + j2 + k3 + l2) * G4; + const X0 = i - t3; + const Y0 = j2 - t3; + const Z0 = k3 - t3; + const W0 = l2 - t3; + const x0 = x2 - X0; + const y0 = y - Y0; + const z0 = z - Z0; + const w0 = w - W0; + const c1 = x0 > y0 ? 32 : 0; + const c2 = x0 > z0 ? 16 : 0; + const c3 = y0 > z0 ? 8 : 0; + const c4 = x0 > w0 ? 4 : 0; + const c5 = y0 > w0 ? 2 : 0; + const c6 = z0 > w0 ? 1 : 0; + const c = c1 + c2 + c3 + c4 + c5 + c6; + const i1 = simplex[c][0] >= 3 ? 1 : 0; + const j1 = simplex[c][1] >= 3 ? 1 : 0; + const k1 = simplex[c][2] >= 3 ? 1 : 0; + const l1 = simplex[c][3] >= 3 ? 1 : 0; + const i2 = simplex[c][0] >= 2 ? 1 : 0; + const j22 = simplex[c][1] >= 2 ? 1 : 0; + const k22 = simplex[c][2] >= 2 ? 1 : 0; + const l22 = simplex[c][3] >= 2 ? 1 : 0; + const i3 = simplex[c][0] >= 1 ? 1 : 0; + const j3 = simplex[c][1] >= 1 ? 1 : 0; + const k32 = simplex[c][2] >= 1 ? 1 : 0; + const l3 = simplex[c][3] >= 1 ? 1 : 0; + const x1 = x0 - i1 + G4; + const y1 = y0 - j1 + G4; + const z1 = z0 - k1 + G4; + const w1 = w0 - l1 + G4; + const x22 = x0 - i2 + 2 * G4; + const y2 = y0 - j22 + 2 * G4; + const z2 = z0 - k22 + 2 * G4; + const w2 = w0 - l22 + 2 * G4; + const x3 = x0 - i3 + 3 * G4; + const y3 = y0 - j3 + 3 * G4; + const z3 = z0 - k32 + 3 * G4; + const w3 = w0 - l3 + 3 * G4; + const x4 = x0 - 1 + 4 * G4; + const y4 = y0 - 1 + 4 * G4; + const z4 = z0 - 1 + 4 * G4; + const w4 = w0 - 1 + 4 * G4; + const ii = i & 255; + const jj = j2 & 255; + const kk = k3 & 255; + const ll = l2 & 255; + const gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32; + const gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32; + const gi2 = perm[ii + i2 + perm[jj + j22 + perm[kk + k22 + perm[ll + l22]]]] % 32; + const gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k32 + perm[ll + l3]]]] % 32; + const gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32; + let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; + if (t0 < 0) + n0 = 0; + else { + t0 *= t0; + n0 = t0 * t0 * this.dot4(grad4[gi0], x0, y0, z0, w0); + } + let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; + if (t1 < 0) + n1 = 0; + else { + t1 *= t1; + n1 = t1 * t1 * this.dot4(grad4[gi1], x1, y1, z1, w1); + } + let t22 = 0.6 - x22 * x22 - y2 * y2 - z2 * z2 - w2 * w2; + if (t22 < 0) + n2 = 0; + else { + t22 *= t22; + n2 = t22 * t22 * this.dot4(grad4[gi2], x22, y2, z2, w2); + } + let t32 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; + if (t32 < 0) + n3 = 0; + else { + t32 *= t32; + n3 = t32 * t32 * this.dot4(grad4[gi3], x3, y3, z3, w3); + } + let t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; + if (t4 < 0) + n4 = 0; + else { + t4 *= t4; + n4 = t4 * t4 * this.dot4(grad4[gi4], x4, y4, z4, w4); + } + return 27 * (n0 + n1 + n2 + n3 + n4); + } +} +// node_modules/three/examples/jsm/misc/ConvexObjectBreaker.js +var _v17 = new Vector3; +// node_modules/three/examples/jsm/misc/Gyroscope.js +var _translationObject = new Vector3; +var _quaternionObject = new Quaternion; +var _scaleObject = new Vector3; +var _translationWorld = new Vector3; +var _quaternionWorld = new Quaternion; +var _scaleWorld = new Vector3; +// node_modules/three/examples/jsm/modifiers/CurveModifier.js +var matrix2 = new Matrix4; +// node_modules/three/examples/jsm/modifiers/EdgeSplitModifier.js +var _A = new Vector3; +var _B = new Vector3; +var _C = new Vector3; +// node_modules/three/examples/jsm/modifiers/SimplifyModifier.js +var _cb2 = new Vector3; +var _ab2 = new Vector3; +// node_modules/three/examples/jsm/objects/Lensflare.js +class Lensflare extends Mesh { + constructor() { + super(Lensflare.Geometry, new MeshBasicMaterial({ opacity: 0, transparent: true })); + this.isLensflare = true; + this.type = "Lensflare"; + this.frustumCulled = false; + this.renderOrder = Infinity; + const positionScreen = new Vector3; + const positionView = new Vector3; + const tempMap = new FramebufferTexture(16, 16); + const occlusionMap = new FramebufferTexture(16, 16); + let currentType = UnsignedByteType; + const geometry = Lensflare.Geometry; + const material1a = new RawShaderMaterial({ + uniforms: { + scale: { value: null }, + screenPosition: { value: null } + }, + vertexShader: ` + + precision highp float; + + uniform vec3 screenPosition; + uniform vec2 scale; + + attribute vec3 position; + + void main() { + + gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); + + }`, + fragmentShader: ` + + precision highp float; + + void main() { + + gl_FragColor = vec4( 1.0, 0.0, 1.0, 1.0 ); + + }`, + depthTest: true, + depthWrite: false, + transparent: false + }); + const material1b = new RawShaderMaterial({ + uniforms: { + map: { value: tempMap }, + scale: { value: null }, + screenPosition: { value: null } + }, + vertexShader: ` + + precision highp float; + + uniform vec3 screenPosition; + uniform vec2 scale; + + attribute vec3 position; + attribute vec2 uv; + + varying vec2 vUV; + + void main() { + + vUV = uv; + + gl_Position = vec4( position.xy * scale + screenPosition.xy, screenPosition.z, 1.0 ); + + }`, + fragmentShader: ` + + precision highp float; + + uniform sampler2D map; + + varying vec2 vUV; + + void main() { + + gl_FragColor = texture2D( map, vUV ); + + }`, + depthTest: false, + depthWrite: false, + transparent: false + }); + const mesh1 = new Mesh(geometry, material1a); + const elements = []; + const shader = LensflareElement.Shader; + const material2 = new RawShaderMaterial({ + name: shader.name, + uniforms: { + map: { value: null }, + occlusionMap: { value: occlusionMap }, + color: { value: new Color(16777215) }, + scale: { value: new Vector2 }, + screenPosition: { value: new Vector3 } + }, + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + blending: AdditiveBlending, + transparent: true, + depthWrite: false + }); + const mesh2 = new Mesh(geometry, material2); + this.addElement = function(element) { + elements.push(element); + }; + const scale2 = new Vector2; + const screenPositionPixels = new Vector2; + const validArea = new Box2; + const viewport = new Vector4; + this.onBeforeRender = function(renderer2, scene, camera) { + renderer2.getCurrentViewport(viewport); + const renderTarget = renderer2.getRenderTarget(); + const type = renderTarget !== null ? renderTarget.texture.type : UnsignedByteType; + if (currentType !== type) { + tempMap.dispose(); + occlusionMap.dispose(); + tempMap.type = occlusionMap.type = type; + currentType = type; + } + const invAspect = viewport.w / viewport.z; + const halfViewportWidth = viewport.z / 2; + const halfViewportHeight = viewport.w / 2; + let size2 = 16 / viewport.w; + scale2.set(size2 * invAspect, size2); + validArea.min.set(viewport.x, viewport.y); + validArea.max.set(viewport.x + (viewport.z - 16), viewport.y + (viewport.w - 16)); + positionView.setFromMatrixPosition(this.matrixWorld); + positionView.applyMatrix4(camera.matrixWorldInverse); + if (positionView.z > 0) + return; + positionScreen.copy(positionView).applyMatrix4(camera.projectionMatrix); + screenPositionPixels.x = viewport.x + positionScreen.x * halfViewportWidth + halfViewportWidth - 8; + screenPositionPixels.y = viewport.y + positionScreen.y * halfViewportHeight + halfViewportHeight - 8; + if (validArea.containsPoint(screenPositionPixels)) { + renderer2.copyFramebufferToTexture(tempMap, screenPositionPixels); + let uniforms = material1a.uniforms; + uniforms["scale"].value = scale2; + uniforms["screenPosition"].value = positionScreen; + renderer2.renderBufferDirect(camera, null, geometry, material1a, mesh1, null); + renderer2.copyFramebufferToTexture(occlusionMap, screenPositionPixels); + uniforms = material1b.uniforms; + uniforms["scale"].value = scale2; + uniforms["screenPosition"].value = positionScreen; + renderer2.renderBufferDirect(camera, null, geometry, material1b, mesh1, null); + const vecX = -positionScreen.x * 2; + const vecY = -positionScreen.y * 2; + for (let i = 0, l2 = elements.length;i < l2; i++) { + const element = elements[i]; + const uniforms2 = material2.uniforms; + uniforms2["color"].value.copy(element.color); + uniforms2["map"].value = element.texture; + uniforms2["screenPosition"].value.x = positionScreen.x + vecX * element.distance; + uniforms2["screenPosition"].value.y = positionScreen.y + vecY * element.distance; + size2 = element.size / viewport.w; + const invAspect2 = viewport.w / viewport.z; + uniforms2["scale"].value.set(size2 * invAspect2, size2); + material2.uniformsNeedUpdate = true; + renderer2.renderBufferDirect(camera, null, geometry, material2, mesh2, null); + } + } + }; + this.dispose = function() { + material1a.dispose(); + material1b.dispose(); + material2.dispose(); + tempMap.dispose(); + occlusionMap.dispose(); + for (let i = 0, l2 = elements.length;i < l2; i++) { + elements[i].texture.dispose(); + } + }; + } +} + +class LensflareElement { + constructor(texture, size2 = 1, distance = 0, color = new Color(16777215)) { + this.texture = texture; + this.size = size2; + this.distance = distance; + this.color = color; + } +} +LensflareElement.Shader = { + name: "LensflareElementShader", + uniforms: { + map: { value: null }, + occlusionMap: { value: null }, + color: { value: null }, + scale: { value: null }, + screenPosition: { value: null } + }, + vertexShader: ` + + precision highp float; + + uniform vec3 screenPosition; + uniform vec2 scale; + + uniform sampler2D occlusionMap; + + attribute vec3 position; + attribute vec2 uv; + + varying vec2 vUV; + varying float vVisibility; + + void main() { + + vUV = uv; + + vec2 pos = position.xy; + + vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ); + visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) ); + visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) ); + visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ); + visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) ); + visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ); + visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) ); + visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ); + visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) ); + + vVisibility = visibility.r / 9.0; + vVisibility *= 1.0 - visibility.g / 9.0; + vVisibility *= visibility.b / 9.0; + + gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 ); + + }`, + fragmentShader: ` + + precision highp float; + + uniform sampler2D map; + uniform vec3 color; + + varying vec2 vUV; + varying float vVisibility; + + void main() { + + vec4 texture = texture2D( map, vUV ); + texture.a *= vVisibility; + gl_FragColor = texture; + gl_FragColor.rgb *= color; + + }` +}; +Lensflare.Geometry = function() { + const geometry = new BufferGeometry; + const float32Array = new Float32Array([ + -1, + -1, + 0, + 0, + 0, + 1, + -1, + 0, + 1, + 0, + 1, + 1, + 0, + 1, + 1, + -1, + 1, + 0, + 0, + 1 + ]); + const interleavedBuffer = new InterleavedBuffer(float32Array, 5); + geometry.setIndex([0, 1, 2, 0, 2, 3]); + geometry.setAttribute("position", new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false)); + geometry.setAttribute("uv", new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false)); + return geometry; +}(); +// node_modules/three/examples/jsm/objects/MarchingCubes.js +var edgeTable = new Int32Array([ + 0, + 265, + 515, + 778, + 1030, + 1295, + 1541, + 1804, + 2060, + 2309, + 2575, + 2822, + 3082, + 3331, + 3593, + 3840, + 400, + 153, + 915, + 666, + 1430, + 1183, + 1941, + 1692, + 2460, + 2197, + 2975, + 2710, + 3482, + 3219, + 3993, + 3728, + 560, + 825, + 51, + 314, + 1590, + 1855, + 1077, + 1340, + 2620, + 2869, + 2111, + 2358, + 3642, + 3891, + 3129, + 3376, + 928, + 681, + 419, + 170, + 1958, + 1711, + 1445, + 1196, + 2988, + 2725, + 2479, + 2214, + 4010, + 3747, + 3497, + 3232, + 1120, + 1385, + 1635, + 1898, + 102, + 367, + 613, + 876, + 3180, + 3429, + 3695, + 3942, + 2154, + 2403, + 2665, + 2912, + 1520, + 1273, + 2035, + 1786, + 502, + 255, + 1013, + 764, + 3580, + 3317, + 4095, + 3830, + 2554, + 2291, + 3065, + 2800, + 1616, + 1881, + 1107, + 1370, + 598, + 863, + 85, + 348, + 3676, + 3925, + 3167, + 3414, + 2650, + 2899, + 2137, + 2384, + 1984, + 1737, + 1475, + 1226, + 966, + 719, + 453, + 204, + 4044, + 3781, + 3535, + 3270, + 3018, + 2755, + 2505, + 2240, + 2240, + 2505, + 2755, + 3018, + 3270, + 3535, + 3781, + 4044, + 204, + 453, + 719, + 966, + 1226, + 1475, + 1737, + 1984, + 2384, + 2137, + 2899, + 2650, + 3414, + 3167, + 3925, + 3676, + 348, + 85, + 863, + 598, + 1370, + 1107, + 1881, + 1616, + 2800, + 3065, + 2291, + 2554, + 3830, + 4095, + 3317, + 3580, + 764, + 1013, + 255, + 502, + 1786, + 2035, + 1273, + 1520, + 2912, + 2665, + 2403, + 2154, + 3942, + 3695, + 3429, + 3180, + 876, + 613, + 367, + 102, + 1898, + 1635, + 1385, + 1120, + 3232, + 3497, + 3747, + 4010, + 2214, + 2479, + 2725, + 2988, + 1196, + 1445, + 1711, + 1958, + 170, + 419, + 681, + 928, + 3376, + 3129, + 3891, + 3642, + 2358, + 2111, + 2869, + 2620, + 1340, + 1077, + 1855, + 1590, + 314, + 51, + 825, + 560, + 3728, + 3993, + 3219, + 3482, + 2710, + 2975, + 2197, + 2460, + 1692, + 1941, + 1183, + 1430, + 666, + 915, + 153, + 400, + 3840, + 3593, + 3331, + 3082, + 2822, + 2575, + 2309, + 2060, + 1804, + 1541, + 1295, + 1030, + 778, + 515, + 265, + 0 +]); +var triTable = new Int32Array([ + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 8, + 3, + 9, + 8, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 1, + 2, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 2, + 10, + 0, + 2, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 8, + 3, + 2, + 10, + 8, + 10, + 9, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 11, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 11, + 2, + 8, + 11, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 9, + 0, + 2, + 3, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 11, + 2, + 1, + 9, + 11, + 9, + 8, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 10, + 1, + 11, + 10, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 10, + 1, + 0, + 8, + 10, + 8, + 11, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 9, + 0, + 3, + 11, + 9, + 11, + 10, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 8, + 10, + 10, + 8, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 7, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 3, + 0, + 7, + 3, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 8, + 4, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 1, + 9, + 4, + 7, + 1, + 7, + 3, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 8, + 4, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 4, + 7, + 3, + 0, + 4, + 1, + 2, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 2, + 10, + 9, + 0, + 2, + 8, + 4, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 10, + 9, + 2, + 9, + 7, + 2, + 7, + 3, + 7, + 9, + 4, + -1, + -1, + -1, + -1, + 8, + 4, + 7, + 3, + 11, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 4, + 7, + 11, + 2, + 4, + 2, + 0, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 0, + 1, + 8, + 4, + 7, + 2, + 3, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 7, + 11, + 9, + 4, + 11, + 9, + 11, + 2, + 9, + 2, + 1, + -1, + -1, + -1, + -1, + 3, + 10, + 1, + 3, + 11, + 10, + 7, + 8, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 11, + 10, + 1, + 4, + 11, + 1, + 0, + 4, + 7, + 11, + 4, + -1, + -1, + -1, + -1, + 4, + 7, + 8, + 9, + 0, + 11, + 9, + 11, + 10, + 11, + 0, + 3, + -1, + -1, + -1, + -1, + 4, + 7, + 11, + 4, + 11, + 9, + 9, + 11, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + 0, + 8, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 5, + 4, + 1, + 5, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 5, + 4, + 8, + 3, + 5, + 3, + 1, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 9, + 5, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 8, + 1, + 2, + 10, + 4, + 9, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 2, + 10, + 5, + 4, + 2, + 4, + 0, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 10, + 5, + 3, + 2, + 5, + 3, + 5, + 4, + 3, + 4, + 8, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + 2, + 3, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 11, + 2, + 0, + 8, + 11, + 4, + 9, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 5, + 4, + 0, + 1, + 5, + 2, + 3, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 1, + 5, + 2, + 5, + 8, + 2, + 8, + 11, + 4, + 8, + 5, + -1, + -1, + -1, + -1, + 10, + 3, + 11, + 10, + 1, + 3, + 9, + 5, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 9, + 5, + 0, + 8, + 1, + 8, + 10, + 1, + 8, + 11, + 10, + -1, + -1, + -1, + -1, + 5, + 4, + 0, + 5, + 0, + 11, + 5, + 11, + 10, + 11, + 0, + 3, + -1, + -1, + -1, + -1, + 5, + 4, + 8, + 5, + 8, + 10, + 10, + 8, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 7, + 8, + 5, + 7, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 3, + 0, + 9, + 5, + 3, + 5, + 7, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 7, + 8, + 0, + 1, + 7, + 1, + 5, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 5, + 3, + 3, + 5, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 7, + 8, + 9, + 5, + 7, + 10, + 1, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 1, + 2, + 9, + 5, + 0, + 5, + 3, + 0, + 5, + 7, + 3, + -1, + -1, + -1, + -1, + 8, + 0, + 2, + 8, + 2, + 5, + 8, + 5, + 7, + 10, + 5, + 2, + -1, + -1, + -1, + -1, + 2, + 10, + 5, + 2, + 5, + 3, + 3, + 5, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 9, + 5, + 7, + 8, + 9, + 3, + 11, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 7, + 9, + 7, + 2, + 9, + 2, + 0, + 2, + 7, + 11, + -1, + -1, + -1, + -1, + 2, + 3, + 11, + 0, + 1, + 8, + 1, + 7, + 8, + 1, + 5, + 7, + -1, + -1, + -1, + -1, + 11, + 2, + 1, + 11, + 1, + 7, + 7, + 1, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 8, + 8, + 5, + 7, + 10, + 1, + 3, + 10, + 3, + 11, + -1, + -1, + -1, + -1, + 5, + 7, + 0, + 5, + 0, + 9, + 7, + 11, + 0, + 1, + 0, + 10, + 11, + 10, + 0, + -1, + 11, + 10, + 0, + 11, + 0, + 3, + 10, + 5, + 0, + 8, + 0, + 7, + 5, + 7, + 0, + -1, + 11, + 10, + 5, + 7, + 11, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 6, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 0, + 1, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 8, + 3, + 1, + 9, + 8, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 6, + 5, + 2, + 6, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 6, + 5, + 1, + 2, + 6, + 3, + 0, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 6, + 5, + 9, + 0, + 6, + 0, + 2, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 9, + 8, + 5, + 8, + 2, + 5, + 2, + 6, + 3, + 2, + 8, + -1, + -1, + -1, + -1, + 2, + 3, + 11, + 10, + 6, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 0, + 8, + 11, + 2, + 0, + 10, + 6, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 2, + 3, + 11, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 10, + 6, + 1, + 9, + 2, + 9, + 11, + 2, + 9, + 8, + 11, + -1, + -1, + -1, + -1, + 6, + 3, + 11, + 6, + 5, + 3, + 5, + 1, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 11, + 0, + 11, + 5, + 0, + 5, + 1, + 5, + 11, + 6, + -1, + -1, + -1, + -1, + 3, + 11, + 6, + 0, + 3, + 6, + 0, + 6, + 5, + 0, + 5, + 9, + -1, + -1, + -1, + -1, + 6, + 5, + 9, + 6, + 9, + 11, + 11, + 9, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 10, + 6, + 4, + 7, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 3, + 0, + 4, + 7, + 3, + 6, + 5, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 9, + 0, + 5, + 10, + 6, + 8, + 4, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 6, + 5, + 1, + 9, + 7, + 1, + 7, + 3, + 7, + 9, + 4, + -1, + -1, + -1, + -1, + 6, + 1, + 2, + 6, + 5, + 1, + 4, + 7, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 5, + 5, + 2, + 6, + 3, + 0, + 4, + 3, + 4, + 7, + -1, + -1, + -1, + -1, + 8, + 4, + 7, + 9, + 0, + 5, + 0, + 6, + 5, + 0, + 2, + 6, + -1, + -1, + -1, + -1, + 7, + 3, + 9, + 7, + 9, + 4, + 3, + 2, + 9, + 5, + 9, + 6, + 2, + 6, + 9, + -1, + 3, + 11, + 2, + 7, + 8, + 4, + 10, + 6, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 10, + 6, + 4, + 7, + 2, + 4, + 2, + 0, + 2, + 7, + 11, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 4, + 7, + 8, + 2, + 3, + 11, + 5, + 10, + 6, + -1, + -1, + -1, + -1, + 9, + 2, + 1, + 9, + 11, + 2, + 9, + 4, + 11, + 7, + 11, + 4, + 5, + 10, + 6, + -1, + 8, + 4, + 7, + 3, + 11, + 5, + 3, + 5, + 1, + 5, + 11, + 6, + -1, + -1, + -1, + -1, + 5, + 1, + 11, + 5, + 11, + 6, + 1, + 0, + 11, + 7, + 11, + 4, + 0, + 4, + 11, + -1, + 0, + 5, + 9, + 0, + 6, + 5, + 0, + 3, + 6, + 11, + 6, + 3, + 8, + 4, + 7, + -1, + 6, + 5, + 9, + 6, + 9, + 11, + 4, + 7, + 9, + 7, + 11, + 9, + -1, + -1, + -1, + -1, + 10, + 4, + 9, + 6, + 4, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 10, + 6, + 4, + 9, + 10, + 0, + 8, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 0, + 1, + 10, + 6, + 0, + 6, + 4, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 3, + 1, + 8, + 1, + 6, + 8, + 6, + 4, + 6, + 1, + 10, + -1, + -1, + -1, + -1, + 1, + 4, + 9, + 1, + 2, + 4, + 2, + 6, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 8, + 1, + 2, + 9, + 2, + 4, + 9, + 2, + 6, + 4, + -1, + -1, + -1, + -1, + 0, + 2, + 4, + 4, + 2, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 3, + 2, + 8, + 2, + 4, + 4, + 2, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 4, + 9, + 10, + 6, + 4, + 11, + 2, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 2, + 2, + 8, + 11, + 4, + 9, + 10, + 4, + 10, + 6, + -1, + -1, + -1, + -1, + 3, + 11, + 2, + 0, + 1, + 6, + 0, + 6, + 4, + 6, + 1, + 10, + -1, + -1, + -1, + -1, + 6, + 4, + 1, + 6, + 1, + 10, + 4, + 8, + 1, + 2, + 1, + 11, + 8, + 11, + 1, + -1, + 9, + 6, + 4, + 9, + 3, + 6, + 9, + 1, + 3, + 11, + 6, + 3, + -1, + -1, + -1, + -1, + 8, + 11, + 1, + 8, + 1, + 0, + 11, + 6, + 1, + 9, + 1, + 4, + 6, + 4, + 1, + -1, + 3, + 11, + 6, + 3, + 6, + 0, + 0, + 6, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 6, + 4, + 8, + 11, + 6, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 10, + 6, + 7, + 8, + 10, + 8, + 9, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 7, + 3, + 0, + 10, + 7, + 0, + 9, + 10, + 6, + 7, + 10, + -1, + -1, + -1, + -1, + 10, + 6, + 7, + 1, + 10, + 7, + 1, + 7, + 8, + 1, + 8, + 0, + -1, + -1, + -1, + -1, + 10, + 6, + 7, + 10, + 7, + 1, + 1, + 7, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 6, + 1, + 6, + 8, + 1, + 8, + 9, + 8, + 6, + 7, + -1, + -1, + -1, + -1, + 2, + 6, + 9, + 2, + 9, + 1, + 6, + 7, + 9, + 0, + 9, + 3, + 7, + 3, + 9, + -1, + 7, + 8, + 0, + 7, + 0, + 6, + 6, + 0, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 3, + 2, + 6, + 7, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 3, + 11, + 10, + 6, + 8, + 10, + 8, + 9, + 8, + 6, + 7, + -1, + -1, + -1, + -1, + 2, + 0, + 7, + 2, + 7, + 11, + 0, + 9, + 7, + 6, + 7, + 10, + 9, + 10, + 7, + -1, + 1, + 8, + 0, + 1, + 7, + 8, + 1, + 10, + 7, + 6, + 7, + 10, + 2, + 3, + 11, + -1, + 11, + 2, + 1, + 11, + 1, + 7, + 10, + 6, + 1, + 6, + 7, + 1, + -1, + -1, + -1, + -1, + 8, + 9, + 6, + 8, + 6, + 7, + 9, + 1, + 6, + 11, + 6, + 3, + 1, + 3, + 6, + -1, + 0, + 9, + 1, + 11, + 6, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 8, + 0, + 7, + 0, + 6, + 3, + 11, + 0, + 11, + 6, + 0, + -1, + -1, + -1, + -1, + 7, + 11, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 6, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 8, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 1, + 9, + 8, + 3, + 1, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 1, + 2, + 6, + 11, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 3, + 0, + 8, + 6, + 11, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 9, + 0, + 2, + 10, + 9, + 6, + 11, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 6, + 11, + 7, + 2, + 10, + 3, + 10, + 8, + 3, + 10, + 9, + 8, + -1, + -1, + -1, + -1, + 7, + 2, + 3, + 6, + 2, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 7, + 0, + 8, + 7, + 6, + 0, + 6, + 2, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 7, + 6, + 2, + 3, + 7, + 0, + 1, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 6, + 2, + 1, + 8, + 6, + 1, + 9, + 8, + 8, + 7, + 6, + -1, + -1, + -1, + -1, + 10, + 7, + 6, + 10, + 1, + 7, + 1, + 3, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 7, + 6, + 1, + 7, + 10, + 1, + 8, + 7, + 1, + 0, + 8, + -1, + -1, + -1, + -1, + 0, + 3, + 7, + 0, + 7, + 10, + 0, + 10, + 9, + 6, + 10, + 7, + -1, + -1, + -1, + -1, + 7, + 6, + 10, + 7, + 10, + 8, + 8, + 10, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 6, + 8, + 4, + 11, + 8, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 6, + 11, + 3, + 0, + 6, + 0, + 4, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 6, + 11, + 8, + 4, + 6, + 9, + 0, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 4, + 6, + 9, + 6, + 3, + 9, + 3, + 1, + 11, + 3, + 6, + -1, + -1, + -1, + -1, + 6, + 8, + 4, + 6, + 11, + 8, + 2, + 10, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 3, + 0, + 11, + 0, + 6, + 11, + 0, + 4, + 6, + -1, + -1, + -1, + -1, + 4, + 11, + 8, + 4, + 6, + 11, + 0, + 2, + 9, + 2, + 10, + 9, + -1, + -1, + -1, + -1, + 10, + 9, + 3, + 10, + 3, + 2, + 9, + 4, + 3, + 11, + 3, + 6, + 4, + 6, + 3, + -1, + 8, + 2, + 3, + 8, + 4, + 2, + 4, + 6, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 4, + 2, + 4, + 6, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 9, + 0, + 2, + 3, + 4, + 2, + 4, + 6, + 4, + 3, + 8, + -1, + -1, + -1, + -1, + 1, + 9, + 4, + 1, + 4, + 2, + 2, + 4, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 1, + 3, + 8, + 6, + 1, + 8, + 4, + 6, + 6, + 10, + 1, + -1, + -1, + -1, + -1, + 10, + 1, + 0, + 10, + 0, + 6, + 6, + 0, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 6, + 3, + 4, + 3, + 8, + 6, + 10, + 3, + 0, + 3, + 9, + 10, + 9, + 3, + -1, + 10, + 9, + 4, + 6, + 10, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 9, + 5, + 7, + 6, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 4, + 9, + 5, + 11, + 7, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 0, + 1, + 5, + 4, + 0, + 7, + 6, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 7, + 6, + 8, + 3, + 4, + 3, + 5, + 4, + 3, + 1, + 5, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + 10, + 1, + 2, + 7, + 6, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 6, + 11, + 7, + 1, + 2, + 10, + 0, + 8, + 3, + 4, + 9, + 5, + -1, + -1, + -1, + -1, + 7, + 6, + 11, + 5, + 4, + 10, + 4, + 2, + 10, + 4, + 0, + 2, + -1, + -1, + -1, + -1, + 3, + 4, + 8, + 3, + 5, + 4, + 3, + 2, + 5, + 10, + 5, + 2, + 11, + 7, + 6, + -1, + 7, + 2, + 3, + 7, + 6, + 2, + 5, + 4, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 5, + 4, + 0, + 8, + 6, + 0, + 6, + 2, + 6, + 8, + 7, + -1, + -1, + -1, + -1, + 3, + 6, + 2, + 3, + 7, + 6, + 1, + 5, + 0, + 5, + 4, + 0, + -1, + -1, + -1, + -1, + 6, + 2, + 8, + 6, + 8, + 7, + 2, + 1, + 8, + 4, + 8, + 5, + 1, + 5, + 8, + -1, + 9, + 5, + 4, + 10, + 1, + 6, + 1, + 7, + 6, + 1, + 3, + 7, + -1, + -1, + -1, + -1, + 1, + 6, + 10, + 1, + 7, + 6, + 1, + 0, + 7, + 8, + 7, + 0, + 9, + 5, + 4, + -1, + 4, + 0, + 10, + 4, + 10, + 5, + 0, + 3, + 10, + 6, + 10, + 7, + 3, + 7, + 10, + -1, + 7, + 6, + 10, + 7, + 10, + 8, + 5, + 4, + 10, + 4, + 8, + 10, + -1, + -1, + -1, + -1, + 6, + 9, + 5, + 6, + 11, + 9, + 11, + 8, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 6, + 11, + 0, + 6, + 3, + 0, + 5, + 6, + 0, + 9, + 5, + -1, + -1, + -1, + -1, + 0, + 11, + 8, + 0, + 5, + 11, + 0, + 1, + 5, + 5, + 6, + 11, + -1, + -1, + -1, + -1, + 6, + 11, + 3, + 6, + 3, + 5, + 5, + 3, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 10, + 9, + 5, + 11, + 9, + 11, + 8, + 11, + 5, + 6, + -1, + -1, + -1, + -1, + 0, + 11, + 3, + 0, + 6, + 11, + 0, + 9, + 6, + 5, + 6, + 9, + 1, + 2, + 10, + -1, + 11, + 8, + 5, + 11, + 5, + 6, + 8, + 0, + 5, + 10, + 5, + 2, + 0, + 2, + 5, + -1, + 6, + 11, + 3, + 6, + 3, + 5, + 2, + 10, + 3, + 10, + 5, + 3, + -1, + -1, + -1, + -1, + 5, + 8, + 9, + 5, + 2, + 8, + 5, + 6, + 2, + 3, + 8, + 2, + -1, + -1, + -1, + -1, + 9, + 5, + 6, + 9, + 6, + 0, + 0, + 6, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 5, + 8, + 1, + 8, + 0, + 5, + 6, + 8, + 3, + 8, + 2, + 6, + 2, + 8, + -1, + 1, + 5, + 6, + 2, + 1, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 3, + 6, + 1, + 6, + 10, + 3, + 8, + 6, + 5, + 6, + 9, + 8, + 9, + 6, + -1, + 10, + 1, + 0, + 10, + 0, + 6, + 9, + 5, + 0, + 5, + 6, + 0, + -1, + -1, + -1, + -1, + 0, + 3, + 8, + 5, + 6, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 5, + 6, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 5, + 10, + 7, + 5, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 5, + 10, + 11, + 7, + 5, + 8, + 3, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 11, + 7, + 5, + 10, + 11, + 1, + 9, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 10, + 7, + 5, + 10, + 11, + 7, + 9, + 8, + 1, + 8, + 3, + 1, + -1, + -1, + -1, + -1, + 11, + 1, + 2, + 11, + 7, + 1, + 7, + 5, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 1, + 2, + 7, + 1, + 7, + 5, + 7, + 2, + 11, + -1, + -1, + -1, + -1, + 9, + 7, + 5, + 9, + 2, + 7, + 9, + 0, + 2, + 2, + 11, + 7, + -1, + -1, + -1, + -1, + 7, + 5, + 2, + 7, + 2, + 11, + 5, + 9, + 2, + 3, + 2, + 8, + 9, + 8, + 2, + -1, + 2, + 5, + 10, + 2, + 3, + 5, + 3, + 7, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 2, + 0, + 8, + 5, + 2, + 8, + 7, + 5, + 10, + 2, + 5, + -1, + -1, + -1, + -1, + 9, + 0, + 1, + 5, + 10, + 3, + 5, + 3, + 7, + 3, + 10, + 2, + -1, + -1, + -1, + -1, + 9, + 8, + 2, + 9, + 2, + 1, + 8, + 7, + 2, + 10, + 2, + 5, + 7, + 5, + 2, + -1, + 1, + 3, + 5, + 3, + 7, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 7, + 0, + 7, + 1, + 1, + 7, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 0, + 3, + 9, + 3, + 5, + 5, + 3, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 8, + 7, + 5, + 9, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 8, + 4, + 5, + 10, + 8, + 10, + 11, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 5, + 0, + 4, + 5, + 11, + 0, + 5, + 10, + 11, + 11, + 3, + 0, + -1, + -1, + -1, + -1, + 0, + 1, + 9, + 8, + 4, + 10, + 8, + 10, + 11, + 10, + 4, + 5, + -1, + -1, + -1, + -1, + 10, + 11, + 4, + 10, + 4, + 5, + 11, + 3, + 4, + 9, + 4, + 1, + 3, + 1, + 4, + -1, + 2, + 5, + 1, + 2, + 8, + 5, + 2, + 11, + 8, + 4, + 5, + 8, + -1, + -1, + -1, + -1, + 0, + 4, + 11, + 0, + 11, + 3, + 4, + 5, + 11, + 2, + 11, + 1, + 5, + 1, + 11, + -1, + 0, + 2, + 5, + 0, + 5, + 9, + 2, + 11, + 5, + 4, + 5, + 8, + 11, + 8, + 5, + -1, + 9, + 4, + 5, + 2, + 11, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 5, + 10, + 3, + 5, + 2, + 3, + 4, + 5, + 3, + 8, + 4, + -1, + -1, + -1, + -1, + 5, + 10, + 2, + 5, + 2, + 4, + 4, + 2, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 10, + 2, + 3, + 5, + 10, + 3, + 8, + 5, + 4, + 5, + 8, + 0, + 1, + 9, + -1, + 5, + 10, + 2, + 5, + 2, + 4, + 1, + 9, + 2, + 9, + 4, + 2, + -1, + -1, + -1, + -1, + 8, + 4, + 5, + 8, + 5, + 3, + 3, + 5, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 4, + 5, + 1, + 0, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 8, + 4, + 5, + 8, + 5, + 3, + 9, + 0, + 5, + 0, + 3, + 5, + -1, + -1, + -1, + -1, + 9, + 4, + 5, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 11, + 7, + 4, + 9, + 11, + 9, + 10, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 8, + 3, + 4, + 9, + 7, + 9, + 11, + 7, + 9, + 10, + 11, + -1, + -1, + -1, + -1, + 1, + 10, + 11, + 1, + 11, + 4, + 1, + 4, + 0, + 7, + 4, + 11, + -1, + -1, + -1, + -1, + 3, + 1, + 4, + 3, + 4, + 8, + 1, + 10, + 4, + 7, + 4, + 11, + 10, + 11, + 4, + -1, + 4, + 11, + 7, + 9, + 11, + 4, + 9, + 2, + 11, + 9, + 1, + 2, + -1, + -1, + -1, + -1, + 9, + 7, + 4, + 9, + 11, + 7, + 9, + 1, + 11, + 2, + 11, + 1, + 0, + 8, + 3, + -1, + 11, + 7, + 4, + 11, + 4, + 2, + 2, + 4, + 0, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 11, + 7, + 4, + 11, + 4, + 2, + 8, + 3, + 4, + 3, + 2, + 4, + -1, + -1, + -1, + -1, + 2, + 9, + 10, + 2, + 7, + 9, + 2, + 3, + 7, + 7, + 4, + 9, + -1, + -1, + -1, + -1, + 9, + 10, + 7, + 9, + 7, + 4, + 10, + 2, + 7, + 8, + 7, + 0, + 2, + 0, + 7, + -1, + 3, + 7, + 10, + 3, + 10, + 2, + 7, + 4, + 10, + 1, + 10, + 0, + 4, + 0, + 10, + -1, + 1, + 10, + 2, + 8, + 7, + 4, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 9, + 1, + 4, + 1, + 7, + 7, + 1, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 9, + 1, + 4, + 1, + 7, + 0, + 8, + 1, + 8, + 7, + 1, + -1, + -1, + -1, + -1, + 4, + 0, + 3, + 7, + 4, + 3, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 4, + 8, + 7, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 10, + 8, + 10, + 11, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 9, + 3, + 9, + 11, + 11, + 9, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 1, + 10, + 0, + 10, + 8, + 8, + 10, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 1, + 10, + 11, + 3, + 10, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 2, + 11, + 1, + 11, + 9, + 9, + 11, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 0, + 9, + 3, + 9, + 11, + 1, + 2, + 9, + 2, + 11, + 9, + -1, + -1, + -1, + -1, + 0, + 2, + 11, + 8, + 0, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 3, + 2, + 11, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 3, + 8, + 2, + 8, + 10, + 10, + 8, + 9, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 9, + 10, + 2, + 0, + 9, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 2, + 3, + 8, + 2, + 8, + 10, + 0, + 1, + 8, + 1, + 10, + 8, + -1, + -1, + -1, + -1, + 1, + 10, + 2, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 1, + 3, + 8, + 9, + 1, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 9, + 1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + 0, + 3, + 8, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1, + -1 +]); +// node_modules/three/examples/jsm/objects/Reflector.js +class Reflector extends Mesh { + constructor(geometry, options = {}) { + super(geometry); + this.isReflector = true; + this.type = "Reflector"; + this.camera = new PerspectiveCamera; + const scope = this; + const color = options.color !== undefined ? new Color(options.color) : new Color(8355711); + const textureWidth = options.textureWidth || 512; + const textureHeight = options.textureHeight || 512; + const clipBias = options.clipBias || 0; + const shader = options.shader || Reflector.ReflectorShader; + const multisample = options.multisample !== undefined ? options.multisample : 4; + const reflectorPlane = new Plane; + const normal = new Vector3; + const reflectorWorldPosition = new Vector3; + const cameraWorldPosition = new Vector3; + const rotationMatrix2 = new Matrix4; + const lookAtPosition = new Vector3(0, 0, -1); + const clipPlane = new Vector4; + const view = new Vector3; + const target = new Vector3; + const q2 = new Vector4; + const textureMatrix = new Matrix4; + const virtualCamera = this.camera; + const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, { samples: multisample, type: HalfFloatType }); + const material = new ShaderMaterial({ + name: shader.name !== undefined ? shader.name : "unspecified", + uniforms: UniformsUtils.clone(shader.uniforms), + fragmentShader: shader.fragmentShader, + vertexShader: shader.vertexShader + }); + material.uniforms["tDiffuse"].value = renderTarget.texture; + material.uniforms["color"].value = color; + material.uniforms["textureMatrix"].value = textureMatrix; + this.material = material; + this.onBeforeRender = function(renderer2, scene, camera) { + reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld); + cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); + rotationMatrix2.extractRotation(scope.matrixWorld); + normal.set(0, 0, 1); + normal.applyMatrix4(rotationMatrix2); + view.subVectors(reflectorWorldPosition, cameraWorldPosition); + if (view.dot(normal) > 0) + return; + view.reflect(normal).negate(); + view.add(reflectorWorldPosition); + rotationMatrix2.extractRotation(camera.matrixWorld); + lookAtPosition.set(0, 0, -1); + lookAtPosition.applyMatrix4(rotationMatrix2); + lookAtPosition.add(cameraWorldPosition); + target.subVectors(reflectorWorldPosition, lookAtPosition); + target.reflect(normal).negate(); + target.add(reflectorWorldPosition); + virtualCamera.position.copy(view); + virtualCamera.up.set(0, 1, 0); + virtualCamera.up.applyMatrix4(rotationMatrix2); + virtualCamera.up.reflect(normal); + virtualCamera.lookAt(target); + virtualCamera.far = camera.far; + virtualCamera.updateMatrixWorld(); + virtualCamera.projectionMatrix.copy(camera.projectionMatrix); + textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + textureMatrix.multiply(virtualCamera.projectionMatrix); + textureMatrix.multiply(virtualCamera.matrixWorldInverse); + textureMatrix.multiply(scope.matrixWorld); + reflectorPlane.setFromNormalAndCoplanarPoint(normal, reflectorWorldPosition); + reflectorPlane.applyMatrix4(virtualCamera.matrixWorldInverse); + clipPlane.set(reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant); + const projectionMatrix = virtualCamera.projectionMatrix; + q2.x = (Math.sign(clipPlane.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; + q2.y = (Math.sign(clipPlane.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; + q2.z = -1; + q2.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; + clipPlane.multiplyScalar(2 / clipPlane.dot(q2)); + projectionMatrix.elements[2] = clipPlane.x; + projectionMatrix.elements[6] = clipPlane.y; + projectionMatrix.elements[10] = clipPlane.z + 1 - clipBias; + projectionMatrix.elements[14] = clipPlane.w; + scope.visible = false; + const currentRenderTarget = renderer2.getRenderTarget(); + const currentXrEnabled = renderer2.xr.enabled; + const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate; + renderer2.xr.enabled = false; + renderer2.shadowMap.autoUpdate = false; + renderer2.setRenderTarget(renderTarget); + renderer2.state.buffers.depth.setMask(true); + if (renderer2.autoClear === false) + renderer2.clear(); + renderer2.render(scene, virtualCamera); + renderer2.xr.enabled = currentXrEnabled; + renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate; + renderer2.setRenderTarget(currentRenderTarget); + const viewport = camera.viewport; + if (viewport !== undefined) { + renderer2.state.viewport(viewport); + } + scope.visible = true; + }; + this.getRenderTarget = function() { + return renderTarget; + }; + this.dispose = function() { + renderTarget.dispose(); + scope.material.dispose(); + }; + } +} +Reflector.ReflectorShader = { + name: "ReflectorShader", + uniforms: { + color: { + value: null + }, + tDiffuse: { + value: null + }, + textureMatrix: { + value: null + } + }, + vertexShader: ` + uniform mat4 textureMatrix; + varying vec4 vUv; + + #include + #include + + void main() { + + vUv = textureMatrix * vec4( position, 1.0 ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + #include + + }`, + fragmentShader: ` + uniform vec3 color; + uniform sampler2D tDiffuse; + varying vec4 vUv; + + #include + + float blendOverlay( float base, float blend ) { + + return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); + + } + + vec3 blendOverlay( vec3 base, vec3 blend ) { + + return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); + + } + + void main() { + + #include + + vec4 base = texture2DProj( tDiffuse, vUv ); + gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); + + #include + #include + + }` +}; +// node_modules/three/examples/jsm/objects/ReflectorForSSRPass.js +class ReflectorForSSRPass extends Mesh { + constructor(geometry, options = {}) { + super(geometry); + this.isReflectorForSSRPass = true; + this.type = "ReflectorForSSRPass"; + const scope = this; + const color = options.color !== undefined ? new Color(options.color) : new Color(8355711); + const textureWidth = options.textureWidth || 512; + const textureHeight = options.textureHeight || 512; + const clipBias = options.clipBias || 0; + const shader = options.shader || ReflectorForSSRPass.ReflectorShader; + const useDepthTexture = options.useDepthTexture === true; + const yAxis2 = new Vector3(0, 1, 0); + const vecTemp0 = new Vector3; + const vecTemp1 = new Vector3; + scope.needsUpdate = false; + scope.maxDistance = ReflectorForSSRPass.ReflectorShader.uniforms.maxDistance.value; + scope.opacity = ReflectorForSSRPass.ReflectorShader.uniforms.opacity.value; + scope.color = color; + scope.resolution = options.resolution || new Vector2(window.innerWidth, window.innerHeight); + scope._distanceAttenuation = ReflectorForSSRPass.ReflectorShader.defines.DISTANCE_ATTENUATION; + Object.defineProperty(scope, "distanceAttenuation", { + get() { + return scope._distanceAttenuation; + }, + set(val2) { + if (scope._distanceAttenuation === val2) + return; + scope._distanceAttenuation = val2; + scope.material.defines.DISTANCE_ATTENUATION = val2; + scope.material.needsUpdate = true; + } + }); + scope._fresnel = ReflectorForSSRPass.ReflectorShader.defines.FRESNEL; + Object.defineProperty(scope, "fresnel", { + get() { + return scope._fresnel; + }, + set(val2) { + if (scope._fresnel === val2) + return; + scope._fresnel = val2; + scope.material.defines.FRESNEL = val2; + scope.material.needsUpdate = true; + } + }); + const normal = new Vector3; + const reflectorWorldPosition = new Vector3; + const cameraWorldPosition = new Vector3; + const rotationMatrix2 = new Matrix4; + const lookAtPosition = new Vector3(0, 0, -1); + const view = new Vector3; + const target = new Vector3; + const textureMatrix = new Matrix4; + const virtualCamera = new PerspectiveCamera; + let depthTexture; + if (useDepthTexture) { + depthTexture = new DepthTexture; + depthTexture.type = UnsignedShortType; + depthTexture.minFilter = NearestFilter; + depthTexture.magFilter = NearestFilter; + } + const parameters = { + depthTexture: useDepthTexture ? depthTexture : null, + type: HalfFloatType + }; + const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, parameters); + const material = new ShaderMaterial({ + name: shader.name !== undefined ? shader.name : "unspecified", + transparent: useDepthTexture, + defines: Object.assign({}, ReflectorForSSRPass.ReflectorShader.defines, { + useDepthTexture + }), + uniforms: UniformsUtils.clone(shader.uniforms), + fragmentShader: shader.fragmentShader, + vertexShader: shader.vertexShader + }); + material.uniforms["tDiffuse"].value = renderTarget.texture; + material.uniforms["color"].value = scope.color; + material.uniforms["textureMatrix"].value = textureMatrix; + if (useDepthTexture) { + material.uniforms["tDepth"].value = renderTarget.depthTexture; + } + this.material = material; + const globalPlane = new Plane(new Vector3(0, 1, 0), clipBias); + const globalPlanes = [globalPlane]; + this.doRender = function(renderer2, scene, camera) { + material.uniforms["maxDistance"].value = scope.maxDistance; + material.uniforms["color"].value = scope.color; + material.uniforms["opacity"].value = scope.opacity; + vecTemp0.copy(camera.position).normalize(); + vecTemp1.copy(vecTemp0).reflect(yAxis2); + material.uniforms["fresnelCoe"].value = (vecTemp0.dot(vecTemp1) + 1) / 2; + reflectorWorldPosition.setFromMatrixPosition(scope.matrixWorld); + cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); + rotationMatrix2.extractRotation(scope.matrixWorld); + normal.set(0, 0, 1); + normal.applyMatrix4(rotationMatrix2); + view.subVectors(reflectorWorldPosition, cameraWorldPosition); + if (view.dot(normal) > 0) + return; + view.reflect(normal).negate(); + view.add(reflectorWorldPosition); + rotationMatrix2.extractRotation(camera.matrixWorld); + lookAtPosition.set(0, 0, -1); + lookAtPosition.applyMatrix4(rotationMatrix2); + lookAtPosition.add(cameraWorldPosition); + target.subVectors(reflectorWorldPosition, lookAtPosition); + target.reflect(normal).negate(); + target.add(reflectorWorldPosition); + virtualCamera.position.copy(view); + virtualCamera.up.set(0, 1, 0); + virtualCamera.up.applyMatrix4(rotationMatrix2); + virtualCamera.up.reflect(normal); + virtualCamera.lookAt(target); + virtualCamera.far = camera.far; + virtualCamera.updateMatrixWorld(); + virtualCamera.projectionMatrix.copy(camera.projectionMatrix); + material.uniforms["virtualCameraNear"].value = camera.near; + material.uniforms["virtualCameraFar"].value = camera.far; + material.uniforms["virtualCameraMatrixWorld"].value = virtualCamera.matrixWorld; + material.uniforms["virtualCameraProjectionMatrix"].value = camera.projectionMatrix; + material.uniforms["virtualCameraProjectionMatrixInverse"].value = camera.projectionMatrixInverse; + material.uniforms["resolution"].value = scope.resolution; + textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + textureMatrix.multiply(virtualCamera.projectionMatrix); + textureMatrix.multiply(virtualCamera.matrixWorldInverse); + textureMatrix.multiply(scope.matrixWorld); + const currentRenderTarget = renderer2.getRenderTarget(); + const currentXrEnabled = renderer2.xr.enabled; + const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate; + const currentClippingPlanes = renderer2.clippingPlanes; + renderer2.xr.enabled = false; + renderer2.shadowMap.autoUpdate = false; + renderer2.clippingPlanes = globalPlanes; + renderer2.setRenderTarget(renderTarget); + renderer2.state.buffers.depth.setMask(true); + if (renderer2.autoClear === false) + renderer2.clear(); + renderer2.render(scene, virtualCamera); + renderer2.xr.enabled = currentXrEnabled; + renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate; + renderer2.clippingPlanes = currentClippingPlanes; + renderer2.setRenderTarget(currentRenderTarget); + const viewport = camera.viewport; + if (viewport !== undefined) { + renderer2.state.viewport(viewport); + } + }; + this.getRenderTarget = function() { + return renderTarget; + }; + } +} +ReflectorForSSRPass.ReflectorShader = { + name: "ReflectorShader", + defines: { + DISTANCE_ATTENUATION: true, + FRESNEL: true + }, + uniforms: { + color: { value: null }, + tDiffuse: { value: null }, + tDepth: { value: null }, + textureMatrix: { value: new Matrix4 }, + maxDistance: { value: 180 }, + opacity: { value: 0.5 }, + fresnelCoe: { value: null }, + virtualCameraNear: { value: null }, + virtualCameraFar: { value: null }, + virtualCameraProjectionMatrix: { value: new Matrix4 }, + virtualCameraMatrixWorld: { value: new Matrix4 }, + virtualCameraProjectionMatrixInverse: { value: new Matrix4 }, + resolution: { value: new Vector2 } + }, + vertexShader: ` + uniform mat4 textureMatrix; + varying vec4 vUv; + + void main() { + + vUv = textureMatrix * vec4( position, 1.0 ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + uniform vec3 color; + uniform sampler2D tDiffuse; + uniform sampler2D tDepth; + uniform float maxDistance; + uniform float opacity; + uniform float fresnelCoe; + uniform float virtualCameraNear; + uniform float virtualCameraFar; + uniform mat4 virtualCameraProjectionMatrix; + uniform mat4 virtualCameraProjectionMatrixInverse; + uniform mat4 virtualCameraMatrixWorld; + uniform vec2 resolution; + varying vec4 vUv; + #include + float blendOverlay( float base, float blend ) { + return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); + } + vec3 blendOverlay( vec3 base, vec3 blend ) { + return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); + } + float getDepth( const in vec2 uv ) { + return texture2D( tDepth, uv ).x; + } + float getViewZ( const in float depth ) { + return perspectiveDepthToViewZ( depth, virtualCameraNear, virtualCameraFar ); + } + vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { + vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc + clipPosition *= clipW; //clip + return ( virtualCameraProjectionMatrixInverse * clipPosition ).xyz;//view + } + void main() { + vec4 base = texture2DProj( tDiffuse, vUv ); + #ifdef useDepthTexture + vec2 uv=(gl_FragCoord.xy-.5)/resolution.xy; + uv.x=1.-uv.x; + float depth = texture2DProj( tDepth, vUv ).r; + float viewZ = getViewZ( depth ); + float clipW = virtualCameraProjectionMatrix[2][3] * viewZ+virtualCameraProjectionMatrix[3][3]; + vec3 viewPosition=getViewPosition( uv, depth, clipW ); + vec3 worldPosition=(virtualCameraMatrixWorld*vec4(viewPosition,1)).xyz; + if(worldPosition.y>maxDistance) discard; + float op=opacity; + #ifdef DISTANCE_ATTENUATION + float ratio=1.-(worldPosition.y/maxDistance); + float attenuation=ratio*ratio; + op=opacity*attenuation; + #endif + #ifdef FRESNEL + op*=fresnelCoe; + #endif + gl_FragColor = vec4( blendOverlay( base.rgb, color ), op ); + #else + gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); + #endif + } + ` +}; +// node_modules/three/examples/jsm/objects/Refractor.js +class Refractor extends Mesh { + constructor(geometry, options = {}) { + super(geometry); + this.isRefractor = true; + this.type = "Refractor"; + this.camera = new PerspectiveCamera; + const scope = this; + const color = options.color !== undefined ? new Color(options.color) : new Color(8355711); + const textureWidth = options.textureWidth || 512; + const textureHeight = options.textureHeight || 512; + const clipBias = options.clipBias || 0; + const shader = options.shader || Refractor.RefractorShader; + const multisample = options.multisample !== undefined ? options.multisample : 4; + const virtualCamera = this.camera; + virtualCamera.matrixAutoUpdate = false; + virtualCamera.userData.refractor = true; + const refractorPlane = new Plane; + const textureMatrix = new Matrix4; + const renderTarget = new WebGLRenderTarget(textureWidth, textureHeight, { samples: multisample, type: HalfFloatType }); + this.material = new ShaderMaterial({ + name: shader.name !== undefined ? shader.name : "unspecified", + uniforms: UniformsUtils.clone(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + transparent: true + }); + this.material.uniforms["color"].value = color; + this.material.uniforms["tDiffuse"].value = renderTarget.texture; + this.material.uniforms["textureMatrix"].value = textureMatrix; + const visible = function() { + const refractorWorldPosition = new Vector3; + const cameraWorldPosition = new Vector3; + const rotationMatrix2 = new Matrix4; + const view = new Vector3; + const normal = new Vector3; + return function visible(camera) { + refractorWorldPosition.setFromMatrixPosition(scope.matrixWorld); + cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld); + view.subVectors(refractorWorldPosition, cameraWorldPosition); + rotationMatrix2.extractRotation(scope.matrixWorld); + normal.set(0, 0, 1); + normal.applyMatrix4(rotationMatrix2); + return view.dot(normal) < 0; + }; + }(); + const updateRefractorPlane = function() { + const normal = new Vector3; + const position2 = new Vector3; + const quaternion = new Quaternion; + const scale2 = new Vector3; + return function updateRefractorPlane() { + scope.matrixWorld.decompose(position2, quaternion, scale2); + normal.set(0, 0, 1).applyQuaternion(quaternion).normalize(); + normal.negate(); + refractorPlane.setFromNormalAndCoplanarPoint(normal, position2); + }; + }(); + const updateVirtualCamera = function() { + const clipPlane = new Plane; + const clipVector = new Vector4; + const q2 = new Vector4; + return function updateVirtualCamera(camera) { + virtualCamera.matrixWorld.copy(camera.matrixWorld); + virtualCamera.matrixWorldInverse.copy(virtualCamera.matrixWorld).invert(); + virtualCamera.projectionMatrix.copy(camera.projectionMatrix); + virtualCamera.far = camera.far; + clipPlane.copy(refractorPlane); + clipPlane.applyMatrix4(virtualCamera.matrixWorldInverse); + clipVector.set(clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.constant); + const projectionMatrix = virtualCamera.projectionMatrix; + q2.x = (Math.sign(clipVector.x) + projectionMatrix.elements[8]) / projectionMatrix.elements[0]; + q2.y = (Math.sign(clipVector.y) + projectionMatrix.elements[9]) / projectionMatrix.elements[5]; + q2.z = -1; + q2.w = (1 + projectionMatrix.elements[10]) / projectionMatrix.elements[14]; + clipVector.multiplyScalar(2 / clipVector.dot(q2)); + projectionMatrix.elements[2] = clipVector.x; + projectionMatrix.elements[6] = clipVector.y; + projectionMatrix.elements[10] = clipVector.z + 1 - clipBias; + projectionMatrix.elements[14] = clipVector.w; + }; + }(); + function updateTextureMatrix(camera) { + textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + textureMatrix.multiply(camera.projectionMatrix); + textureMatrix.multiply(camera.matrixWorldInverse); + textureMatrix.multiply(scope.matrixWorld); + } + function render(renderer2, scene, camera) { + scope.visible = false; + const currentRenderTarget = renderer2.getRenderTarget(); + const currentXrEnabled = renderer2.xr.enabled; + const currentShadowAutoUpdate = renderer2.shadowMap.autoUpdate; + renderer2.xr.enabled = false; + renderer2.shadowMap.autoUpdate = false; + renderer2.setRenderTarget(renderTarget); + if (renderer2.autoClear === false) + renderer2.clear(); + renderer2.render(scene, virtualCamera); + renderer2.xr.enabled = currentXrEnabled; + renderer2.shadowMap.autoUpdate = currentShadowAutoUpdate; + renderer2.setRenderTarget(currentRenderTarget); + const viewport = camera.viewport; + if (viewport !== undefined) { + renderer2.state.viewport(viewport); + } + scope.visible = true; + } + this.onBeforeRender = function(renderer2, scene, camera) { + if (camera.userData.refractor === true) + return; + if (!visible(camera) === true) + return; + updateRefractorPlane(); + updateTextureMatrix(camera); + updateVirtualCamera(camera); + render(renderer2, scene, camera); + }; + this.getRenderTarget = function() { + return renderTarget; + }; + this.dispose = function() { + renderTarget.dispose(); + scope.material.dispose(); + }; + } +} +Refractor.RefractorShader = { + name: "RefractorShader", + uniforms: { + color: { + value: null + }, + tDiffuse: { + value: null + }, + textureMatrix: { + value: null + } + }, + vertexShader: ` + + uniform mat4 textureMatrix; + + varying vec4 vUv; + + void main() { + + vUv = textureMatrix * vec4( position, 1.0 ); + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform vec3 color; + uniform sampler2D tDiffuse; + + varying vec4 vUv; + + float blendOverlay( float base, float blend ) { + + return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) ); + + } + + vec3 blendOverlay( vec3 base, vec3 blend ) { + + return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) ); + + } + + void main() { + + vec4 base = texture2DProj( tDiffuse, vUv ); + gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 ); + + #include + #include + + }` +}; +// node_modules/three/examples/jsm/objects/ShadowMesh.js +var _shadowMatrix = new Matrix4; +// node_modules/three/examples/jsm/objects/Sky.js +class Sky extends Mesh { + constructor() { + const shader = Sky.SkyShader; + const material = new ShaderMaterial({ + name: shader.name, + uniforms: UniformsUtils.clone(shader.uniforms), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + side: BackSide, + depthWrite: false + }); + super(new BoxGeometry(1, 1, 1), material); + this.isSky = true; + } +} +Sky.SkyShader = { + name: "SkyShader", + uniforms: { + turbidity: { value: 2 }, + rayleigh: { value: 1 }, + mieCoefficient: { value: 0.005 }, + mieDirectionalG: { value: 0.8 }, + sunPosition: { value: new Vector3 }, + up: { value: new Vector3(0, 1, 0) } + }, + vertexShader: ` + uniform vec3 sunPosition; + uniform float rayleigh; + uniform float turbidity; + uniform float mieCoefficient; + uniform vec3 up; + + varying vec3 vWorldPosition; + varying vec3 vSunDirection; + varying float vSunfade; + varying vec3 vBetaR; + varying vec3 vBetaM; + varying float vSunE; + + // constants for atmospheric scattering + const float e = 2.71828182845904523536028747135266249775724709369995957; + const float pi = 3.141592653589793238462643383279502884197169; + + // wavelength of used primaries, according to preetham + const vec3 lambda = vec3( 680E-9, 550E-9, 450E-9 ); + // this pre-calculation replaces older TotalRayleigh(vec3 lambda) function: + // (8.0 * pow(pi, 3.0) * pow(pow(n, 2.0) - 1.0, 2.0) * (6.0 + 3.0 * pn)) / (3.0 * N * pow(lambda, vec3(4.0)) * (6.0 - 7.0 * pn)) + const vec3 totalRayleigh = vec3( 5.804542996261093E-6, 1.3562911419845635E-5, 3.0265902468824876E-5 ); + + // mie stuff + // K coefficient for the primaries + const float v = 4.0; + const vec3 K = vec3( 0.686, 0.678, 0.666 ); + // MieConst = pi * pow( ( 2.0 * pi ) / lambda, vec3( v - 2.0 ) ) * K + const vec3 MieConst = vec3( 1.8399918514433978E14, 2.7798023919660528E14, 4.0790479543861094E14 ); + + // earth shadow hack + // cutoffAngle = pi / 1.95; + const float cutoffAngle = 1.6110731556870734; + const float steepness = 1.5; + const float EE = 1000.0; + + float sunIntensity( float zenithAngleCos ) { + zenithAngleCos = clamp( zenithAngleCos, -1.0, 1.0 ); + return EE * max( 0.0, 1.0 - pow( e, -( ( cutoffAngle - acos( zenithAngleCos ) ) / steepness ) ) ); + } + + vec3 totalMie( float T ) { + float c = ( 0.2 * T ) * 10E-18; + return 0.434 * c * MieConst; + } + + void main() { + + vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); + vWorldPosition = worldPosition.xyz; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + gl_Position.z = gl_Position.w; // set z to camera.far + + vSunDirection = normalize( sunPosition ); + + vSunE = sunIntensity( dot( vSunDirection, up ) ); + + vSunfade = 1.0 - clamp( 1.0 - exp( ( sunPosition.y / 450000.0 ) ), 0.0, 1.0 ); + + float rayleighCoefficient = rayleigh - ( 1.0 * ( 1.0 - vSunfade ) ); + + // extinction (absorption + out scattering) + // rayleigh coefficients + vBetaR = totalRayleigh * rayleighCoefficient; + + // mie coefficients + vBetaM = totalMie( turbidity ) * mieCoefficient; + + }`, + fragmentShader: ` + varying vec3 vWorldPosition; + varying vec3 vSunDirection; + varying float vSunfade; + varying vec3 vBetaR; + varying vec3 vBetaM; + varying float vSunE; + + uniform float mieDirectionalG; + uniform vec3 up; + + // constants for atmospheric scattering + const float pi = 3.141592653589793238462643383279502884197169; + + const float n = 1.0003; // refractive index of air + const float N = 2.545E25; // number of molecules per unit volume for air at 288.15K and 1013mb (sea level -45 celsius) + + // optical length at zenith for molecules + const float rayleighZenithLength = 8.4E3; + const float mieZenithLength = 1.25E3; + // 66 arc seconds -> degrees, and the cosine of that + const float sunAngularDiameterCos = 0.999956676946448443553574619906976478926848692873900859324; + + // 3.0 / ( 16.0 * pi ) + const float THREE_OVER_SIXTEENPI = 0.05968310365946075; + // 1.0 / ( 4.0 * pi ) + const float ONE_OVER_FOURPI = 0.07957747154594767; + + float rayleighPhase( float cosTheta ) { + return THREE_OVER_SIXTEENPI * ( 1.0 + pow( cosTheta, 2.0 ) ); + } + + float hgPhase( float cosTheta, float g ) { + float g2 = pow( g, 2.0 ); + float inverse = 1.0 / pow( 1.0 - 2.0 * g * cosTheta + g2, 1.5 ); + return ONE_OVER_FOURPI * ( ( 1.0 - g2 ) * inverse ); + } + + void main() { + + vec3 direction = normalize( vWorldPosition - cameraPosition ); + + // optical length + // cutoff angle at 90 to avoid singularity in next formula. + float zenithAngle = acos( max( 0.0, dot( up, direction ) ) ); + float inverse = 1.0 / ( cos( zenithAngle ) + 0.15 * pow( 93.885 - ( ( zenithAngle * 180.0 ) / pi ), -1.253 ) ); + float sR = rayleighZenithLength * inverse; + float sM = mieZenithLength * inverse; + + // combined extinction factor + vec3 Fex = exp( -( vBetaR * sR + vBetaM * sM ) ); + + // in scattering + float cosTheta = dot( direction, vSunDirection ); + + float rPhase = rayleighPhase( cosTheta * 0.5 + 0.5 ); + vec3 betaRTheta = vBetaR * rPhase; + + float mPhase = hgPhase( cosTheta, mieDirectionalG ); + vec3 betaMTheta = vBetaM * mPhase; + + vec3 Lin = pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * ( 1.0 - Fex ), vec3( 1.5 ) ); + Lin *= mix( vec3( 1.0 ), pow( vSunE * ( ( betaRTheta + betaMTheta ) / ( vBetaR + vBetaM ) ) * Fex, vec3( 1.0 / 2.0 ) ), clamp( pow( 1.0 - dot( up, vSunDirection ), 5.0 ), 0.0, 1.0 ) ); + + // nightsky + float theta = acos( direction.y ); // elevation --> y-axis, [-pi/2, pi/2] + float phi = atan( direction.z, direction.x ); // azimuth --> x-axis [-pi/2, pi/2] + vec2 uv = vec2( phi, theta ) / vec2( 2.0 * pi, pi ) + vec2( 0.5, 0.0 ); + vec3 L0 = vec3( 0.1 ) * Fex; + + // composition + solar disc + float sundisk = smoothstep( sunAngularDiameterCos, sunAngularDiameterCos + 0.00002, cosTheta ); + L0 += ( vSunE * 19000.0 * Fex ) * sundisk; + + vec3 texColor = ( Lin + L0 ) * 0.04 + vec3( 0.0, 0.0003, 0.00075 ); + + vec3 retColor = pow( texColor, vec3( 1.0 / ( 1.2 + ( 1.2 * vSunfade ) ) ) ); + + gl_FragColor = vec4( retColor, 1.0 ); + + #include + #include + + }` +}; +// node_modules/three/examples/jsm/objects/Water2.js +class Water extends Mesh { + constructor(geometry, options = {}) { + super(geometry); + this.isWater = true; + this.type = "Water"; + const scope = this; + const color = options.color !== undefined ? new Color(options.color) : new Color(16777215); + const textureWidth = options.textureWidth !== undefined ? options.textureWidth : 512; + const textureHeight = options.textureHeight !== undefined ? options.textureHeight : 512; + const clipBias = options.clipBias !== undefined ? options.clipBias : 0; + const flowDirection = options.flowDirection !== undefined ? options.flowDirection : new Vector2(1, 0); + const flowSpeed = options.flowSpeed !== undefined ? options.flowSpeed : 0.03; + const reflectivity = options.reflectivity !== undefined ? options.reflectivity : 0.02; + const scale2 = options.scale !== undefined ? options.scale : 1; + const shader = options.shader !== undefined ? options.shader : Water.WaterShader; + const textureLoader = new TextureLoader; + const flowMap = options.flowMap || undefined; + const normalMap0 = options.normalMap0 || textureLoader.load("textures/water/Water_1_M_Normal.jpg"); + const normalMap1 = options.normalMap1 || textureLoader.load("textures/water/Water_2_M_Normal.jpg"); + const cycle = 0.15; + const halfCycle = cycle * 0.5; + const textureMatrix = new Matrix4; + const clock = new Clock; + if (Reflector === undefined) { + console.error("THREE.Water: Required component Reflector not found."); + return; + } + if (Refractor === undefined) { + console.error("THREE.Water: Required component Refractor not found."); + return; + } + const reflector = new Reflector(geometry, { + textureWidth, + textureHeight, + clipBias + }); + const refractor = new Refractor(geometry, { + textureWidth, + textureHeight, + clipBias + }); + reflector.matrixAutoUpdate = false; + refractor.matrixAutoUpdate = false; + this.material = new ShaderMaterial({ + name: shader.name, + uniforms: UniformsUtils.merge([ + UniformsLib["fog"], + shader.uniforms + ]), + vertexShader: shader.vertexShader, + fragmentShader: shader.fragmentShader, + transparent: true, + fog: true + }); + if (flowMap !== undefined) { + this.material.defines.USE_FLOWMAP = ""; + this.material.uniforms["tFlowMap"] = { + type: "t", + value: flowMap + }; + } else { + this.material.uniforms["flowDirection"] = { + type: "v2", + value: flowDirection + }; + } + normalMap0.wrapS = normalMap0.wrapT = RepeatWrapping; + normalMap1.wrapS = normalMap1.wrapT = RepeatWrapping; + this.material.uniforms["tReflectionMap"].value = reflector.getRenderTarget().texture; + this.material.uniforms["tRefractionMap"].value = refractor.getRenderTarget().texture; + this.material.uniforms["tNormalMap0"].value = normalMap0; + this.material.uniforms["tNormalMap1"].value = normalMap1; + this.material.uniforms["color"].value = color; + this.material.uniforms["reflectivity"].value = reflectivity; + this.material.uniforms["textureMatrix"].value = textureMatrix; + this.material.uniforms["config"].value.x = 0; + this.material.uniforms["config"].value.y = halfCycle; + this.material.uniforms["config"].value.z = halfCycle; + this.material.uniforms["config"].value.w = scale2; + function updateTextureMatrix(camera) { + textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + textureMatrix.multiply(camera.projectionMatrix); + textureMatrix.multiply(camera.matrixWorldInverse); + textureMatrix.multiply(scope.matrixWorld); + } + function updateFlow() { + const delta = clock.getDelta(); + const config = scope.material.uniforms["config"]; + config.value.x += flowSpeed * delta; + config.value.y = config.value.x + halfCycle; + if (config.value.x >= cycle) { + config.value.x = 0; + config.value.y = halfCycle; + } else if (config.value.y >= cycle) { + config.value.y = config.value.y - cycle; + } + } + this.onBeforeRender = function(renderer2, scene, camera) { + updateTextureMatrix(camera); + updateFlow(); + scope.visible = false; + reflector.matrixWorld.copy(scope.matrixWorld); + refractor.matrixWorld.copy(scope.matrixWorld); + reflector.onBeforeRender(renderer2, scene, camera); + refractor.onBeforeRender(renderer2, scene, camera); + scope.visible = true; + }; + } +} +Water.WaterShader = { + name: "WaterShader", + uniforms: { + color: { + type: "c", + value: null + }, + reflectivity: { + type: "f", + value: 0 + }, + tReflectionMap: { + type: "t", + value: null + }, + tRefractionMap: { + type: "t", + value: null + }, + tNormalMap0: { + type: "t", + value: null + }, + tNormalMap1: { + type: "t", + value: null + }, + textureMatrix: { + type: "m4", + value: null + }, + config: { + type: "v4", + value: new Vector4 + } + }, + vertexShader: ` + + #include + #include + #include + + uniform mat4 textureMatrix; + + varying vec4 vCoord; + varying vec2 vUv; + varying vec3 vToEye; + + void main() { + + vUv = uv; + vCoord = textureMatrix * vec4( position, 1.0 ); + + vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); + vToEye = cameraPosition - worldPosition.xyz; + + vec4 mvPosition = viewMatrix * worldPosition; // used in fog_vertex + gl_Position = projectionMatrix * mvPosition; + + #include + #include + + }`, + fragmentShader: ` + + #include + #include + #include + + uniform sampler2D tReflectionMap; + uniform sampler2D tRefractionMap; + uniform sampler2D tNormalMap0; + uniform sampler2D tNormalMap1; + + #ifdef USE_FLOWMAP + uniform sampler2D tFlowMap; + #else + uniform vec2 flowDirection; + #endif + + uniform vec3 color; + uniform float reflectivity; + uniform vec4 config; + + varying vec4 vCoord; + varying vec2 vUv; + varying vec3 vToEye; + + void main() { + + #include + + float flowMapOffset0 = config.x; + float flowMapOffset1 = config.y; + float halfCycle = config.z; + float scale = config.w; + + vec3 toEye = normalize( vToEye ); + + // determine flow direction + vec2 flow; + #ifdef USE_FLOWMAP + flow = texture2D( tFlowMap, vUv ).rg * 2.0 - 1.0; + #else + flow = flowDirection; + #endif + flow.x *= - 1.0; + + // sample normal maps (distort uvs with flowdata) + vec4 normalColor0 = texture2D( tNormalMap0, ( vUv * scale ) + flow * flowMapOffset0 ); + vec4 normalColor1 = texture2D( tNormalMap1, ( vUv * scale ) + flow * flowMapOffset1 ); + + // linear interpolate to get the final normal color + float flowLerp = abs( halfCycle - flowMapOffset0 ) / halfCycle; + vec4 normalColor = mix( normalColor0, normalColor1, flowLerp ); + + // calculate normal vector + vec3 normal = normalize( vec3( normalColor.r * 2.0 - 1.0, normalColor.b, normalColor.g * 2.0 - 1.0 ) ); + + // calculate the fresnel term to blend reflection and refraction maps + float theta = max( dot( toEye, normal ), 0.0 ); + float reflectance = reflectivity + ( 1.0 - reflectivity ) * pow( ( 1.0 - theta ), 5.0 ); + + // calculate final uv coords + vec3 coord = vCoord.xyz / vCoord.w; + vec2 uv = coord.xy + coord.z * normal.xz * 0.05; + + vec4 reflectColor = texture2D( tReflectionMap, vec2( 1.0 - uv.x, uv.y ) ); + vec4 refractColor = texture2D( tRefractionMap, uv ); + + // multiply water color with the mix of both textures + gl_FragColor = vec4( color, 1.0 ) * mix( refractColor, reflectColor, reflectance ); + + #include + #include + #include + + }` +}; +// node_modules/three/examples/jsm/physics/RapierPhysics.js +var _scale3 = new Vector3(1, 1, 1); +var ZERO = new Vector3; +// node_modules/three/examples/jsm/shaders/CopyShader.js +var CopyShader = { + name: "CopyShader", + uniforms: { + tDiffuse: { value: null }, + opacity: { value: 1 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform float opacity; + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + gl_FragColor = opacity * texel; + + + }` +}; +// node_modules/three/examples/jsm/shaders/ConvolutionShader.js +var ConvolutionShader = { + name: "ConvolutionShader", + defines: { + KERNEL_SIZE_FLOAT: "25.0", + KERNEL_SIZE_INT: "25" + }, + uniforms: { + tDiffuse: { value: null }, + uImageIncrement: { value: new Vector2(0.001953125, 0) }, + cKernel: { value: [] } + }, + vertexShader: ` + + uniform vec2 uImageIncrement; + + varying vec2 vUv; + + void main() { + + vUv = uv - ( ( KERNEL_SIZE_FLOAT - 1.0 ) / 2.0 ) * uImageIncrement; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform float cKernel[ KERNEL_SIZE_INT ]; + + uniform sampler2D tDiffuse; + uniform vec2 uImageIncrement; + + varying vec2 vUv; + + void main() { + + vec2 imageCoord = vUv; + vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 ); + + for( int i = 0; i < KERNEL_SIZE_INT; i ++ ) { + + sum += texture2D( tDiffuse, imageCoord ) * cKernel[ i ]; + imageCoord += uImageIncrement; + + } + + gl_FragColor = sum; + + }`, + buildKernel: function(sigma) { + const kMaxKernelSize = 25; + let kernelSize = 2 * Math.ceil(sigma * 3) + 1; + if (kernelSize > kMaxKernelSize) + kernelSize = kMaxKernelSize; + const halfWidth = (kernelSize - 1) * 0.5; + const values2 = new Array(kernelSize); + let sum2 = 0; + for (let i = 0;i < kernelSize; ++i) { + values2[i] = gauss(i - halfWidth, sigma); + sum2 += values2[i]; + } + for (let i = 0;i < kernelSize; ++i) + values2[i] /= sum2; + return values2; + } +}; +function gauss(x2, sigma) { + return Math.exp(-(x2 * x2) / (2 * sigma * sigma)); +} + +// node_modules/three/examples/jsm/postprocessing/BloomPass.js +class BloomPass extends Pass { + constructor(strength = 1, kernelSize = 25, sigma = 4) { + super(); + this.renderTargetX = new WebGLRenderTarget(1, 1, { type: HalfFloatType }); + this.renderTargetX.texture.name = "BloomPass.x"; + this.renderTargetY = new WebGLRenderTarget(1, 1, { type: HalfFloatType }); + this.renderTargetY.texture.name = "BloomPass.y"; + this.combineUniforms = UniformsUtils.clone(CombineShader.uniforms); + this.combineUniforms["strength"].value = strength; + this.materialCombine = new ShaderMaterial({ + name: CombineShader.name, + uniforms: this.combineUniforms, + vertexShader: CombineShader.vertexShader, + fragmentShader: CombineShader.fragmentShader, + blending: AdditiveBlending, + transparent: true + }); + const convolutionShader = ConvolutionShader; + this.convolutionUniforms = UniformsUtils.clone(convolutionShader.uniforms); + this.convolutionUniforms["uImageIncrement"].value = BloomPass.blurX; + this.convolutionUniforms["cKernel"].value = ConvolutionShader.buildKernel(sigma); + this.materialConvolution = new ShaderMaterial({ + name: convolutionShader.name, + uniforms: this.convolutionUniforms, + vertexShader: convolutionShader.vertexShader, + fragmentShader: convolutionShader.fragmentShader, + defines: { + KERNEL_SIZE_FLOAT: kernelSize.toFixed(1), + KERNEL_SIZE_INT: kernelSize.toFixed(0) + } + }); + this.needsSwap = false; + this.fsQuad = new FullScreenQuad(null); + } + render(renderer2, writeBuffer, readBuffer, deltaTime, maskActive) { + if (maskActive) + renderer2.state.buffers.stencil.setTest(false); + this.fsQuad.material = this.materialConvolution; + this.convolutionUniforms["tDiffuse"].value = readBuffer.texture; + this.convolutionUniforms["uImageIncrement"].value = BloomPass.blurX; + renderer2.setRenderTarget(this.renderTargetX); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.convolutionUniforms["tDiffuse"].value = this.renderTargetX.texture; + this.convolutionUniforms["uImageIncrement"].value = BloomPass.blurY; + renderer2.setRenderTarget(this.renderTargetY); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.materialCombine; + this.combineUniforms["tDiffuse"].value = this.renderTargetY.texture; + if (maskActive) + renderer2.state.buffers.stencil.setTest(true); + renderer2.setRenderTarget(readBuffer); + if (this.clear) + renderer2.clear(); + this.fsQuad.render(renderer2); + } + setSize(width2, height2) { + this.renderTargetX.setSize(width2, height2); + this.renderTargetY.setSize(width2, height2); + } + dispose() { + this.renderTargetX.dispose(); + this.renderTargetY.dispose(); + this.materialCombine.dispose(); + this.materialConvolution.dispose(); + this.fsQuad.dispose(); + } +} +var CombineShader = { + name: "CombineShader", + uniforms: { + tDiffuse: { value: null }, + strength: { value: 1 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform float strength; + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + gl_FragColor = strength * texel; + + }` +}; +BloomPass.blurX = new Vector2(0.001953125, 0); +BloomPass.blurY = new Vector2(0, 0.001953125); +// node_modules/three/examples/jsm/shaders/DotScreenShader.js +var DotScreenShader = { + name: "DotScreenShader", + uniforms: { + tDiffuse: { value: null }, + tSize: { value: new Vector2(256, 256) }, + center: { value: new Vector2(0.5, 0.5) }, + angle: { value: 1.57 }, + scale: { value: 1 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform vec2 center; + uniform float angle; + uniform float scale; + uniform vec2 tSize; + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + float pattern() { + + float s = sin( angle ), c = cos( angle ); + + vec2 tex = vUv * tSize - center; + vec2 point = vec2( c * tex.x - s * tex.y, s * tex.x + c * tex.y ) * scale; + + return ( sin( point.x ) * sin( point.y ) ) * 4.0; + + } + + void main() { + + vec4 color = texture2D( tDiffuse, vUv ); + + float average = ( color.r + color.g + color.b ) / 3.0; + + gl_FragColor = vec4( vec3( average * 10.0 - 5.0 + pattern() ), color.a ); + + }` +}; +// node_modules/three/examples/jsm/shaders/GTAOShader.js +var GTAOShader = { + name: "GTAOShader", + defines: { + PERSPECTIVE_CAMERA: 1, + SAMPLES: 16, + NORMAL_VECTOR_TYPE: 1, + DEPTH_SWIZZLING: "x", + SCREEN_SPACE_RADIUS: 0, + SCREEN_SPACE_RADIUS_SCALE: 100, + SCENE_CLIP_BOX: 0 + }, + uniforms: { + tNormal: { value: null }, + tDepth: { value: null }, + tNoise: { value: null }, + resolution: { value: new Vector2 }, + cameraNear: { value: null }, + cameraFar: { value: null }, + cameraProjectionMatrix: { value: new Matrix4 }, + cameraProjectionMatrixInverse: { value: new Matrix4 }, + cameraWorldMatrix: { value: new Matrix4 }, + radius: { value: 0.25 }, + distanceExponent: { value: 1 }, + thickness: { value: 1 }, + distanceFallOff: { value: 1 }, + scale: { value: 1 }, + sceneBoxMin: { value: new Vector3(-1, -1, -1) }, + sceneBoxMax: { value: new Vector3(1, 1, 1) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + varying vec2 vUv; + uniform highp sampler2D tNormal; + uniform highp sampler2D tDepth; + uniform sampler2D tNoise; + uniform vec2 resolution; + uniform float cameraNear; + uniform float cameraFar; + uniform mat4 cameraProjectionMatrix; + uniform mat4 cameraProjectionMatrixInverse; + uniform mat4 cameraWorldMatrix; + uniform float radius; + uniform float distanceExponent; + uniform float thickness; + uniform float distanceFallOff; + uniform float scale; + #if SCENE_CLIP_BOX == 1 + uniform vec3 sceneBoxMin; + uniform vec3 sceneBoxMax; + #endif + + #include + #include + + #ifndef FRAGMENT_OUTPUT + #define FRAGMENT_OUTPUT vec4(vec3(ao), 1.) + #endif + + vec3 getViewPosition(const in vec2 screenPosition, const in float depth) { + vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); + vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; + return viewSpacePosition.xyz / viewSpacePosition.w; + } + + float getDepth(const vec2 uv) { + return textureLod(tDepth, uv.xy, 0.0).DEPTH_SWIZZLING; + } + + float fetchDepth(const ivec2 uv) { + return texelFetch(tDepth, uv.xy, 0).DEPTH_SWIZZLING; + } + + float getViewZ(const in float depth) { + #if PERSPECTIVE_CAMERA == 1 + return perspectiveDepthToViewZ(depth, cameraNear, cameraFar); + #else + return orthographicDepthToViewZ(depth, cameraNear, cameraFar); + #endif + } + + vec3 computeNormalFromDepth(const vec2 uv) { + vec2 size = vec2(textureSize(tDepth, 0)); + ivec2 p = ivec2(uv * size); + float c0 = fetchDepth(p); + float l2 = fetchDepth(p - ivec2(2, 0)); + float l1 = fetchDepth(p - ivec2(1, 0)); + float r1 = fetchDepth(p + ivec2(1, 0)); + float r2 = fetchDepth(p + ivec2(2, 0)); + float b2 = fetchDepth(p - ivec2(0, 2)); + float b1 = fetchDepth(p - ivec2(0, 1)); + float t1 = fetchDepth(p + ivec2(0, 1)); + float t2 = fetchDepth(p + ivec2(0, 2)); + float dl = abs((2.0 * l1 - l2) - c0); + float dr = abs((2.0 * r1 - r2) - c0); + float db = abs((2.0 * b1 - b2) - c0); + float dt = abs((2.0 * t1 - t2) - c0); + vec3 ce = getViewPosition(uv, c0).xyz; + vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; + vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; + return normalize(cross(dpdx, dpdy)); + } + + vec3 getViewNormal(const vec2 uv) { + #if NORMAL_VECTOR_TYPE == 2 + return normalize(textureLod(tNormal, uv, 0.).rgb); + #elif NORMAL_VECTOR_TYPE == 1 + return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); + #else + return computeNormalFromDepth(uv); + #endif + } + + vec3 getSceneUvAndDepth(vec3 sampleViewPos) { + vec4 sampleClipPos = cameraProjectionMatrix * vec4(sampleViewPos, 1.); + vec2 sampleUv = sampleClipPos.xy / sampleClipPos.w * 0.5 + 0.5; + float sampleSceneDepth = getDepth(sampleUv); + return vec3(sampleUv, sampleSceneDepth); + } + + void main() { + float depth = getDepth(vUv.xy); + if (depth >= 1.0) { + discard; + return; + } + vec3 viewPos = getViewPosition(vUv, depth); + vec3 viewNormal = getViewNormal(vUv); + + float radiusToUse = radius; + float distanceFalloffToUse = thickness; + #if SCREEN_SPACE_RADIUS == 1 + float radiusScale = getViewPosition(vec2(0.5 + float(SCREEN_SPACE_RADIUS_SCALE) / resolution.x, 0.0), depth).x; + radiusToUse *= radiusScale; + distanceFalloffToUse *= radiusScale; + #endif + + #if SCENE_CLIP_BOX == 1 + vec3 worldPos = (cameraWorldMatrix * vec4(viewPos, 1.0)).xyz; + float boxDistance = length(max(vec3(0.0), max(sceneBoxMin - worldPos, worldPos - sceneBoxMax))); + if (boxDistance > radiusToUse) { + discard; + return; + } + #endif + + vec2 noiseResolution = vec2(textureSize(tNoise, 0)); + vec2 noiseUv = vUv * resolution / noiseResolution; + vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); + vec3 randomVec = noiseTexel.xyz * 2.0 - 1.0; + vec3 tangent = normalize(vec3(randomVec.xy, 0.)); + vec3 bitangent = vec3(-tangent.y, tangent.x, 0.); + mat3 kernelMatrix = mat3(tangent, bitangent, vec3(0., 0., 1.)); + + const int DIRECTIONS = SAMPLES < 30 ? 3 : 5; + const int STEPS = (SAMPLES + DIRECTIONS - 1) / DIRECTIONS; + float ao = 0.0; + for (int i = 0; i < DIRECTIONS; ++i) { + + float angle = float(i) / float(DIRECTIONS) * PI; + vec4 sampleDir = vec4(cos(angle), sin(angle), 0., 0.5 + 0.5 * noiseTexel.w); + sampleDir.xyz = normalize(kernelMatrix * sampleDir.xyz); + + vec3 viewDir = normalize(-viewPos.xyz); + vec3 sliceBitangent = normalize(cross(sampleDir.xyz, viewDir)); + vec3 sliceTangent = cross(sliceBitangent, viewDir); + vec3 normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent)); + + vec3 tangentToNormalInSlice = cross(normalInSlice, sliceBitangent); + vec2 cosHorizons = vec2(dot(viewDir, tangentToNormalInSlice), dot(viewDir, -tangentToNormalInSlice)); + + for (int j = 0; j < STEPS; ++j) { + vec3 sampleViewOffset = sampleDir.xyz * radiusToUse * sampleDir.w * pow(float(j + 1) / float(STEPS), distanceExponent); + + vec3 sampleSceneUvDepth = getSceneUvAndDepth(viewPos + sampleViewOffset); + vec3 sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); + vec3 viewDelta = sampleSceneViewPos - viewPos; + if (abs(viewDelta.z) < thickness) { + float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); + cosHorizons.x += max(0., (sampleCosHorizon - cosHorizons.x) * mix(1., 2. / float(j + 2), distanceFallOff)); + } + + sampleSceneUvDepth = getSceneUvAndDepth(viewPos - sampleViewOffset); + sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z); + viewDelta = sampleSceneViewPos - viewPos; + if (abs(viewDelta.z) < thickness) { + float sampleCosHorizon = dot(viewDir, normalize(viewDelta)); + cosHorizons.y += max(0., (sampleCosHorizon - cosHorizons.y) * mix(1., 2. / float(j + 2), distanceFallOff)); + } + } + + vec2 sinHorizons = sqrt(1. - cosHorizons * cosHorizons); + float nx = dot(normalInSlice, sliceTangent); + float ny = dot(normalInSlice, viewDir); + float nxb = 1. / 2. * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y); + float nyb = 1. / 2. * (2. - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y); + float occlusion = nx * nxb + ny * nyb; + ao += occlusion; + } + + ao = clamp(ao / float(DIRECTIONS), 0., 1.); + #if SCENE_CLIP_BOX == 1 + ao = mix(ao, 1., smoothstep(0., radiusToUse, boxDistance)); + #endif + ao = pow(ao, scale); + + gl_FragColor = FRAGMENT_OUTPUT; + }` +}; +var GTAODepthShader = { + name: "GTAODepthShader", + defines: { + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDepth: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null } + }, + vertexShader: ` + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + uniform sampler2D tDepth; + uniform float cameraNear; + uniform float cameraFar; + varying vec2 vUv; + + #include + + float getLinearDepth( const in vec2 screenPosition ) { + #if PERSPECTIVE_CAMERA == 1 + float fragCoordZ = texture2D( tDepth, screenPosition ).x; + float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); + return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + #else + return texture2D( tDepth, screenPosition ).x; + #endif + } + + void main() { + float depth = getLinearDepth( vUv ); + gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); + + }` +}; +var GTAOBlendShader = { + name: "GTAOBlendShader", + uniforms: { + tDiffuse: { value: null }, + intensity: { value: 1 } + }, + vertexShader: ` + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + uniform float intensity; + uniform sampler2D tDiffuse; + varying vec2 vUv; + + void main() { + vec4 texel = texture2D( tDiffuse, vUv ); + gl_FragColor = vec4(mix(vec3(1.), texel.rgb, intensity), texel.a); + }` +}; +function generateMagicSquareNoise(size2 = 5) { + const noiseSize = Math.floor(size2) % 2 === 0 ? Math.floor(size2) + 1 : Math.floor(size2); + const magicSquare = generateMagicSquare(noiseSize); + const noiseSquareSize = magicSquare.length; + const data2 = new Uint8Array(noiseSquareSize * 4); + for (let inx = 0;inx < noiseSquareSize; ++inx) { + const iAng = magicSquare[inx]; + const angle = 2 * Math.PI * iAng / noiseSquareSize; + const randomVec = new Vector3(Math.cos(angle), Math.sin(angle), 0).normalize(); + data2[inx * 4] = (randomVec.x * 0.5 + 0.5) * 255; + data2[inx * 4 + 1] = (randomVec.y * 0.5 + 0.5) * 255; + data2[inx * 4 + 2] = 127; + data2[inx * 4 + 3] = 255; + } + const noiseTexture = new DataTexture(data2, noiseSize, noiseSize); + noiseTexture.wrapS = RepeatWrapping; + noiseTexture.wrapT = RepeatWrapping; + noiseTexture.needsUpdate = true; + return noiseTexture; +} +function generateMagicSquare(size2) { + const noiseSize = Math.floor(size2) % 2 === 0 ? Math.floor(size2) + 1 : Math.floor(size2); + const noiseSquareSize = noiseSize * noiseSize; + const magicSquare = Array(noiseSquareSize).fill(0); + let i = Math.floor(noiseSize / 2); + let j2 = noiseSize - 1; + for (let num = 1;num <= noiseSquareSize; ) { + if (i === -1 && j2 === noiseSize) { + j2 = noiseSize - 2; + i = 0; + } else { + if (j2 === noiseSize) { + j2 = 0; + } + if (i < 0) { + i = noiseSize - 1; + } + } + if (magicSquare[i * noiseSize + j2] !== 0) { + j2 -= 2; + i++; + continue; + } else { + magicSquare[i * noiseSize + j2] = num++; + } + j2++; + i--; + } + return magicSquare; +} + +// node_modules/three/examples/jsm/shaders/PoissonDenoiseShader.js +var PoissonDenoiseShader = { + name: "PoissonDenoiseShader", + defines: { + SAMPLES: 16, + SAMPLE_VECTORS: generatePdSamplePointInitializer(16, 2, 1), + NORMAL_VECTOR_TYPE: 1, + DEPTH_VALUE_SOURCE: 0 + }, + uniforms: { + tDiffuse: { value: null }, + tNormal: { value: null }, + tDepth: { value: null }, + tNoise: { value: null }, + resolution: { value: new Vector2 }, + cameraProjectionMatrixInverse: { value: new Matrix4 }, + lumaPhi: { value: 5 }, + depthPhi: { value: 5 }, + normalPhi: { value: 5 }, + radius: { value: 4 }, + index: { value: 0 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + + varying vec2 vUv; + + uniform sampler2D tDiffuse; + uniform sampler2D tNormal; + uniform sampler2D tDepth; + uniform sampler2D tNoise; + uniform vec2 resolution; + uniform mat4 cameraProjectionMatrixInverse; + uniform float lumaPhi; + uniform float depthPhi; + uniform float normalPhi; + uniform float radius; + uniform int index; + + #include + #include + + #ifndef SAMPLE_LUMINANCE + #define SAMPLE_LUMINANCE dot(vec3(0.2125, 0.7154, 0.0721), a) + #endif + + #ifndef FRAGMENT_OUTPUT + #define FRAGMENT_OUTPUT vec4(denoised, 1.) + #endif + + float getLuminance(const in vec3 a) { + return SAMPLE_LUMINANCE; + } + + const vec3 poissonDisk[SAMPLES] = SAMPLE_VECTORS; + + vec3 getViewPosition(const in vec2 screenPosition, const in float depth) { + vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0); + vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition; + return viewSpacePosition.xyz / viewSpacePosition.w; + } + + float getDepth(const vec2 uv) { + #if DEPTH_VALUE_SOURCE == 1 + return textureLod(tDepth, uv.xy, 0.0).a; + #else + return textureLod(tDepth, uv.xy, 0.0).r; + #endif + } + + float fetchDepth(const ivec2 uv) { + #if DEPTH_VALUE_SOURCE == 1 + return texelFetch(tDepth, uv.xy, 0).a; + #else + return texelFetch(tDepth, uv.xy, 0).r; + #endif + } + + vec3 computeNormalFromDepth(const vec2 uv) { + vec2 size = vec2(textureSize(tDepth, 0)); + ivec2 p = ivec2(uv * size); + float c0 = fetchDepth(p); + float l2 = fetchDepth(p - ivec2(2, 0)); + float l1 = fetchDepth(p - ivec2(1, 0)); + float r1 = fetchDepth(p + ivec2(1, 0)); + float r2 = fetchDepth(p + ivec2(2, 0)); + float b2 = fetchDepth(p - ivec2(0, 2)); + float b1 = fetchDepth(p - ivec2(0, 1)); + float t1 = fetchDepth(p + ivec2(0, 1)); + float t2 = fetchDepth(p + ivec2(0, 2)); + float dl = abs((2.0 * l1 - l2) - c0); + float dr = abs((2.0 * r1 - r2) - c0); + float db = abs((2.0 * b1 - b2) - c0); + float dt = abs((2.0 * t1 - t2) - c0); + vec3 ce = getViewPosition(uv, c0).xyz; + vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz + : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz; + vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz + : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz; + return normalize(cross(dpdx, dpdy)); + } + + vec3 getViewNormal(const vec2 uv) { + #if NORMAL_VECTOR_TYPE == 2 + return normalize(textureLod(tNormal, uv, 0.).rgb); + #elif NORMAL_VECTOR_TYPE == 1 + return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb); + #else + return computeNormalFromDepth(uv); + #endif + } + + void denoiseSample(in vec3 center, in vec3 viewNormal, in vec3 viewPos, in vec2 sampleUv, inout vec3 denoised, inout float totalWeight) { + vec4 sampleTexel = textureLod(tDiffuse, sampleUv, 0.0); + float sampleDepth = getDepth(sampleUv); + vec3 sampleNormal = getViewNormal(sampleUv); + vec3 neighborColor = sampleTexel.rgb; + vec3 viewPosSample = getViewPosition(sampleUv, sampleDepth); + + float normalDiff = dot(viewNormal, sampleNormal); + float normalSimilarity = pow(max(normalDiff, 0.), normalPhi); + float lumaDiff = abs(getLuminance(neighborColor) - getLuminance(center)); + float lumaSimilarity = max(1.0 - lumaDiff / lumaPhi, 0.0); + float depthDiff = abs(dot(viewPos - viewPosSample, viewNormal)); + float depthSimilarity = max(1. - depthDiff / depthPhi, 0.); + float w = lumaSimilarity * depthSimilarity * normalSimilarity; + + denoised += w * neighborColor; + totalWeight += w; + } + + void main() { + float depth = getDepth(vUv.xy); + vec3 viewNormal = getViewNormal(vUv); + if (depth == 1. || dot(viewNormal, viewNormal) == 0.) { + discard; + return; + } + vec4 texel = textureLod(tDiffuse, vUv, 0.0); + vec3 center = texel.rgb; + vec3 viewPos = getViewPosition(vUv, depth); + + vec2 noiseResolution = vec2(textureSize(tNoise, 0)); + vec2 noiseUv = vUv * resolution / noiseResolution; + vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0); + vec2 noiseVec = vec2(sin(noiseTexel[index % 4] * 2. * PI), cos(noiseTexel[index % 4] * 2. * PI)); + mat2 rotationMatrix = mat2(noiseVec.x, -noiseVec.y, noiseVec.x, noiseVec.y); + + float totalWeight = 1.0; + vec3 denoised = texel.rgb; + for (int i = 0; i < SAMPLES; i++) { + vec3 sampleDir = poissonDisk[i]; + vec2 offset = rotationMatrix * (sampleDir.xy * (1. + sampleDir.z * (radius - 1.)) / resolution); + vec2 sampleUv = vUv + offset; + denoiseSample(center, viewNormal, viewPos, sampleUv, denoised, totalWeight); + } + + if (totalWeight > 0.) { + denoised /= totalWeight; + } + gl_FragColor = FRAGMENT_OUTPUT; + }` +}; +function generatePdSamplePointInitializer(samples, rings, radiusExponent) { + const poissonDisk = generateDenoiseSamples(samples, rings, radiusExponent); + let glslCode = "vec3[SAMPLES]("; + for (let i = 0;i < samples; i++) { + const sample = poissonDisk[i]; + glslCode += `vec3(${sample.x}, ${sample.y}, ${sample.z})${i < samples - 1 ? "," : ")"}`; + } + return glslCode; +} +function generateDenoiseSamples(numSamples, numRings, radiusExponent) { + const samples = []; + for (let i = 0;i < numSamples; i++) { + const angle = 2 * Math.PI * numRings * i / numSamples; + const radius = Math.pow(i / (numSamples - 1), radiusExponent); + samples.push(new Vector3(Math.cos(angle), Math.sin(angle), radius)); + } + return samples; +} + +// node_modules/three/examples/jsm/postprocessing/GTAOPass.js +class GTAOPass extends Pass { + constructor(scene, camera, width2, height2, parameters, aoParameters, pdParameters) { + super(); + this.width = width2 !== undefined ? width2 : 512; + this.height = height2 !== undefined ? height2 : 512; + this.clear = true; + this.camera = camera; + this.scene = scene; + this.output = 0; + this._renderGBuffer = true; + this._visibilityCache = new Map; + this.blendIntensity = 1; + this.pdRings = 2; + this.pdRadiusExponent = 2; + this.pdSamples = 16; + this.gtaoNoiseTexture = generateMagicSquareNoise(); + this.pdNoiseTexture = this.generateNoise(); + this.gtaoRenderTarget = new WebGLRenderTarget(this.width, this.height, { type: HalfFloatType }); + this.pdRenderTarget = this.gtaoRenderTarget.clone(); + this.gtaoMaterial = new ShaderMaterial({ + defines: Object.assign({}, GTAOShader.defines), + uniforms: UniformsUtils.clone(GTAOShader.uniforms), + vertexShader: GTAOShader.vertexShader, + fragmentShader: GTAOShader.fragmentShader, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + this.gtaoMaterial.defines.PERSPECTIVE_CAMERA = this.camera.isPerspectiveCamera ? 1 : 0; + this.gtaoMaterial.uniforms.tNoise.value = this.gtaoNoiseTexture; + this.gtaoMaterial.uniforms.resolution.value.set(this.width, this.height); + this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near; + this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far; + this.normalMaterial = new MeshNormalMaterial; + this.normalMaterial.blending = NoBlending; + this.pdMaterial = new ShaderMaterial({ + defines: Object.assign({}, PoissonDenoiseShader.defines), + uniforms: UniformsUtils.clone(PoissonDenoiseShader.uniforms), + vertexShader: PoissonDenoiseShader.vertexShader, + fragmentShader: PoissonDenoiseShader.fragmentShader, + depthTest: false, + depthWrite: false + }); + this.pdMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture; + this.pdMaterial.uniforms.tNoise.value = this.pdNoiseTexture; + this.pdMaterial.uniforms.resolution.value.set(this.width, this.height); + this.pdMaterial.uniforms.lumaPhi.value = 10; + this.pdMaterial.uniforms.depthPhi.value = 2; + this.pdMaterial.uniforms.normalPhi.value = 3; + this.pdMaterial.uniforms.radius.value = 8; + this.depthRenderMaterial = new ShaderMaterial({ + defines: Object.assign({}, GTAODepthShader.defines), + uniforms: UniformsUtils.clone(GTAODepthShader.uniforms), + vertexShader: GTAODepthShader.vertexShader, + fragmentShader: GTAODepthShader.fragmentShader, + blending: NoBlending + }); + this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near; + this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far; + this.copyMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(CopyShader.uniforms), + vertexShader: CopyShader.vertexShader, + fragmentShader: CopyShader.fragmentShader, + transparent: true, + depthTest: false, + depthWrite: false, + blendSrc: DstColorFactor, + blendDst: ZeroFactor, + blendEquation: AddEquation, + blendSrcAlpha: DstAlphaFactor, + blendDstAlpha: ZeroFactor, + blendEquationAlpha: AddEquation + }); + this.blendMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(GTAOBlendShader.uniforms), + vertexShader: GTAOBlendShader.vertexShader, + fragmentShader: GTAOBlendShader.fragmentShader, + transparent: true, + depthTest: false, + depthWrite: false, + blending: CustomBlending, + blendSrc: DstColorFactor, + blendDst: ZeroFactor, + blendEquation: AddEquation, + blendSrcAlpha: DstAlphaFactor, + blendDstAlpha: ZeroFactor, + blendEquationAlpha: AddEquation + }); + this.fsQuad = new FullScreenQuad(null); + this.originalClearColor = new Color; + this.setGBuffer(parameters ? parameters.depthTexture : undefined, parameters ? parameters.normalTexture : undefined); + if (aoParameters !== undefined) { + this.updateGtaoMaterial(aoParameters); + } + if (pdParameters !== undefined) { + this.updatePdMaterial(pdParameters); + } + } + dispose() { + this.gtaoNoiseTexture.dispose(); + this.pdNoiseTexture.dispose(); + this.normalRenderTarget.dispose(); + this.gtaoRenderTarget.dispose(); + this.pdRenderTarget.dispose(); + this.normalMaterial.dispose(); + this.pdMaterial.dispose(); + this.copyMaterial.dispose(); + this.depthRenderMaterial.dispose(); + this.fsQuad.dispose(); + } + get gtaoMap() { + return this.pdRenderTarget.texture; + } + setGBuffer(depthTexture, normalTexture) { + if (depthTexture !== undefined) { + this.depthTexture = depthTexture; + this.normalTexture = normalTexture; + this._renderGBuffer = false; + } else { + this.depthTexture = new DepthTexture; + this.depthTexture.format = DepthStencilFormat; + this.depthTexture.type = UnsignedInt248Type; + this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType, + depthTexture: this.depthTexture + }); + this.normalTexture = this.normalRenderTarget.texture; + this._renderGBuffer = true; + } + const normalVectorType = this.normalTexture ? 1 : 0; + const depthValueSource = this.depthTexture === this.normalTexture ? "w" : "x"; + this.gtaoMaterial.defines.NORMAL_VECTOR_TYPE = normalVectorType; + this.gtaoMaterial.defines.DEPTH_SWIZZLING = depthValueSource; + this.gtaoMaterial.uniforms.tNormal.value = this.normalTexture; + this.gtaoMaterial.uniforms.tDepth.value = this.depthTexture; + this.pdMaterial.defines.NORMAL_VECTOR_TYPE = normalVectorType; + this.pdMaterial.defines.DEPTH_SWIZZLING = depthValueSource; + this.pdMaterial.uniforms.tNormal.value = this.normalTexture; + this.pdMaterial.uniforms.tDepth.value = this.depthTexture; + this.depthRenderMaterial.uniforms.tDepth.value = this.normalRenderTarget.depthTexture; + } + setSceneClipBox(box) { + if (box) { + this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX !== 1; + this.gtaoMaterial.defines.SCENE_CLIP_BOX = 1; + this.gtaoMaterial.uniforms.sceneBoxMin.value.copy(box.min); + this.gtaoMaterial.uniforms.sceneBoxMax.value.copy(box.max); + } else { + this.gtaoMaterial.needsUpdate = this.gtaoMaterial.defines.SCENE_CLIP_BOX === 0; + this.gtaoMaterial.defines.SCENE_CLIP_BOX = 0; + } + } + updateGtaoMaterial(parameters) { + if (parameters.radius !== undefined) { + this.gtaoMaterial.uniforms.radius.value = parameters.radius; + } + if (parameters.distanceExponent !== undefined) { + this.gtaoMaterial.uniforms.distanceExponent.value = parameters.distanceExponent; + } + if (parameters.thickness !== undefined) { + this.gtaoMaterial.uniforms.thickness.value = parameters.thickness; + } + if (parameters.distanceFallOff !== undefined) { + this.gtaoMaterial.uniforms.distanceFallOff.value = parameters.distanceFallOff; + this.gtaoMaterial.needsUpdate = true; + } + if (parameters.scale !== undefined) { + this.gtaoMaterial.uniforms.scale.value = parameters.scale; + } + if (parameters.samples !== undefined && parameters.samples !== this.gtaoMaterial.defines.SAMPLES) { + this.gtaoMaterial.defines.SAMPLES = parameters.samples; + this.gtaoMaterial.needsUpdate = true; + } + if (parameters.screenSpaceRadius !== undefined && (parameters.screenSpaceRadius ? 1 : 0) !== this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS) { + this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS = parameters.screenSpaceRadius ? 1 : 0; + this.gtaoMaterial.needsUpdate = true; + } + } + updatePdMaterial(parameters) { + let updateShader = false; + if (parameters.lumaPhi !== undefined) { + this.pdMaterial.uniforms.lumaPhi.value = parameters.lumaPhi; + } + if (parameters.depthPhi !== undefined) { + this.pdMaterial.uniforms.depthPhi.value = parameters.depthPhi; + } + if (parameters.normalPhi !== undefined) { + this.pdMaterial.uniforms.normalPhi.value = parameters.normalPhi; + } + if (parameters.radius !== undefined && parameters.radius !== this.radius) { + this.pdMaterial.uniforms.radius.value = parameters.radius; + } + if (parameters.radiusExponent !== undefined && parameters.radiusExponent !== this.pdRadiusExponent) { + this.pdRadiusExponent = parameters.radiusExponent; + updateShader = true; + } + if (parameters.rings !== undefined && parameters.rings !== this.pdRings) { + this.pdRings = parameters.rings; + updateShader = true; + } + if (parameters.samples !== undefined && parameters.samples !== this.pdSamples) { + this.pdSamples = parameters.samples; + updateShader = true; + } + if (updateShader) { + this.pdMaterial.defines.SAMPLES = this.pdSamples; + this.pdMaterial.defines.SAMPLE_VECTORS = generatePdSamplePointInitializer(this.pdSamples, this.pdRings, this.pdRadiusExponent); + this.pdMaterial.needsUpdate = true; + } + } + render(renderer2, writeBuffer, readBuffer) { + if (this._renderGBuffer) { + this.overrideVisibility(); + this.renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 7829503, 1); + this.restoreVisibility(); + } + this.gtaoMaterial.uniforms.cameraNear.value = this.camera.near; + this.gtaoMaterial.uniforms.cameraFar.value = this.camera.far; + this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix); + this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); + this.gtaoMaterial.uniforms.cameraWorldMatrix.value.copy(this.camera.matrixWorld); + this.renderPass(renderer2, this.gtaoMaterial, this.gtaoRenderTarget, 16777215, 1); + this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); + this.renderPass(renderer2, this.pdMaterial, this.pdRenderTarget, 16777215, 1); + switch (this.output) { + case GTAOPass.OUTPUT.Off: + break; + case GTAOPass.OUTPUT.Diffuse: + this.copyMaterial.uniforms.tDiffuse.value = readBuffer.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.AO: + this.copyMaterial.uniforms.tDiffuse.value = this.gtaoRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.Denoise: + this.copyMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.Depth: + this.depthRenderMaterial.uniforms.cameraNear.value = this.camera.near; + this.depthRenderMaterial.uniforms.cameraFar.value = this.camera.far; + this.renderPass(renderer2, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.Normal: + this.copyMaterial.uniforms.tDiffuse.value = this.normalRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case GTAOPass.OUTPUT.Default: + this.copyMaterial.uniforms.tDiffuse.value = readBuffer.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + this.blendMaterial.uniforms.intensity.value = this.blendIntensity; + this.blendMaterial.uniforms.tDiffuse.value = this.pdRenderTarget.texture; + this.renderPass(renderer2, this.blendMaterial, this.renderToScreen ? null : writeBuffer); + break; + default: + console.warn("THREE.GTAOPass: Unknown output type."); + } + } + renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.fsQuad.material = passMaterial; + this.fsQuad.render(renderer2); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.overrideMaterial = overrideMaterial; + renderer2.render(this.scene, this.camera); + this.scene.overrideMaterial = null; + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + setSize(width2, height2) { + this.width = width2; + this.height = height2; + this.gtaoRenderTarget.setSize(width2, height2); + this.normalRenderTarget.setSize(width2, height2); + this.pdRenderTarget.setSize(width2, height2); + this.gtaoMaterial.uniforms.resolution.value.set(width2, height2); + this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix); + this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); + this.pdMaterial.uniforms.resolution.value.set(width2, height2); + this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse); + } + overrideVisibility() { + const scene = this.scene; + const cache = this._visibilityCache; + scene.traverse(function(object) { + cache.set(object, object.visible); + if (object.isPoints || object.isLine) + object.visible = false; + }); + } + restoreVisibility() { + const scene = this.scene; + const cache = this._visibilityCache; + scene.traverse(function(object) { + const visible = cache.get(object); + object.visible = visible; + }); + cache.clear(); + } + generateNoise(size2 = 64) { + const simplex = new SimplexNoise; + const arraySize = size2 * size2 * 4; + const data2 = new Uint8Array(arraySize); + for (let i = 0;i < size2; i++) { + for (let j2 = 0;j2 < size2; j2++) { + const x2 = i; + const y = j2; + data2[(i * size2 + j2) * 4] = (simplex.noise(x2, y) * 0.5 + 0.5) * 255; + data2[(i * size2 + j2) * 4 + 1] = (simplex.noise(x2 + size2, y) * 0.5 + 0.5) * 255; + data2[(i * size2 + j2) * 4 + 2] = (simplex.noise(x2, y + size2) * 0.5 + 0.5) * 255; + data2[(i * size2 + j2) * 4 + 3] = (simplex.noise(x2 + size2, y + size2) * 0.5 + 0.5) * 255; + } + } + const noiseTexture = new DataTexture(data2, size2, size2, RGBAFormat, UnsignedByteType); + noiseTexture.wrapS = RepeatWrapping; + noiseTexture.wrapT = RepeatWrapping; + noiseTexture.needsUpdate = true; + return noiseTexture; + } +} +GTAOPass.OUTPUT = { + Off: -1, + Default: 0, + Diffuse: 1, + Depth: 2, + Normal: 3, + AO: 4, + Denoise: 5 +}; +// node_modules/three/examples/jsm/shaders/HalftoneShader.js +var HalftoneShader = { + name: "HalftoneShader", + uniforms: { + tDiffuse: { value: null }, + shape: { value: 1 }, + radius: { value: 4 }, + rotateR: { value: Math.PI / 12 * 1 }, + rotateG: { value: Math.PI / 12 * 2 }, + rotateB: { value: Math.PI / 12 * 3 }, + scatter: { value: 0 }, + width: { value: 1 }, + height: { value: 1 }, + blending: { value: 1 }, + blendingMode: { value: 1 }, + greyscale: { value: false }, + disable: { value: false } + }, + vertexShader: ` + + varying vec2 vUV; + + void main() { + + vUV = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + + }`, + fragmentShader: ` + + #define SQRT2_MINUS_ONE 0.41421356 + #define SQRT2_HALF_MINUS_ONE 0.20710678 + #define PI2 6.28318531 + #define SHAPE_DOT 1 + #define SHAPE_ELLIPSE 2 + #define SHAPE_LINE 3 + #define SHAPE_SQUARE 4 + #define BLENDING_LINEAR 1 + #define BLENDING_MULTIPLY 2 + #define BLENDING_ADD 3 + #define BLENDING_LIGHTER 4 + #define BLENDING_DARKER 5 + uniform sampler2D tDiffuse; + uniform float radius; + uniform float rotateR; + uniform float rotateG; + uniform float rotateB; + uniform float scatter; + uniform float width; + uniform float height; + uniform int shape; + uniform bool disable; + uniform float blending; + uniform int blendingMode; + varying vec2 vUV; + uniform bool greyscale; + const int samples = 8; + + float blend( float a, float b, float t ) { + + // linear blend + return a * ( 1.0 - t ) + b * t; + + } + + float hypot( float x, float y ) { + + // vector magnitude + return sqrt( x * x + y * y ); + + } + + float rand( vec2 seed ){ + + // get pseudo-random number + return fract( sin( dot( seed.xy, vec2( 12.9898, 78.233 ) ) ) * 43758.5453 ); + + } + + float distanceToDotRadius( float channel, vec2 coord, vec2 normal, vec2 p, float angle, float rad_max ) { + + // apply shape-specific transforms + float dist = hypot( coord.x - p.x, coord.y - p.y ); + float rad = channel; + + if ( shape == SHAPE_DOT ) { + + rad = pow( abs( rad ), 1.125 ) * rad_max; + + } else if ( shape == SHAPE_ELLIPSE ) { + + rad = pow( abs( rad ), 1.125 ) * rad_max; + + if ( dist != 0.0 ) { + float dot_p = abs( ( p.x - coord.x ) / dist * normal.x + ( p.y - coord.y ) / dist * normal.y ); + dist = ( dist * ( 1.0 - SQRT2_HALF_MINUS_ONE ) ) + dot_p * dist * SQRT2_MINUS_ONE; + } + + } else if ( shape == SHAPE_LINE ) { + + rad = pow( abs( rad ), 1.5) * rad_max; + float dot_p = ( p.x - coord.x ) * normal.x + ( p.y - coord.y ) * normal.y; + dist = hypot( normal.x * dot_p, normal.y * dot_p ); + + } else if ( shape == SHAPE_SQUARE ) { + + float theta = atan( p.y - coord.y, p.x - coord.x ) - angle; + float sin_t = abs( sin( theta ) ); + float cos_t = abs( cos( theta ) ); + rad = pow( abs( rad ), 1.4 ); + rad = rad_max * ( rad + ( ( sin_t > cos_t ) ? rad - sin_t * rad : rad - cos_t * rad ) ); + + } + + return rad - dist; + + } + + struct Cell { + + // grid sample positions + vec2 normal; + vec2 p1; + vec2 p2; + vec2 p3; + vec2 p4; + float samp2; + float samp1; + float samp3; + float samp4; + + }; + + vec4 getSample( vec2 point ) { + + // multi-sampled point + vec4 tex = texture2D( tDiffuse, vec2( point.x / width, point.y / height ) ); + float base = rand( vec2( floor( point.x ), floor( point.y ) ) ) * PI2; + float step = PI2 / float( samples ); + float dist = radius * 0.66; + + for ( int i = 0; i < samples; ++i ) { + + float r = base + step * float( i ); + vec2 coord = point + vec2( cos( r ) * dist, sin( r ) * dist ); + tex += texture2D( tDiffuse, vec2( coord.x / width, coord.y / height ) ); + + } + + tex /= float( samples ) + 1.0; + return tex; + + } + + float getDotColour( Cell c, vec2 p, int channel, float angle, float aa ) { + + // get colour for given point + float dist_c_1, dist_c_2, dist_c_3, dist_c_4, res; + + if ( channel == 0 ) { + + c.samp1 = getSample( c.p1 ).r; + c.samp2 = getSample( c.p2 ).r; + c.samp3 = getSample( c.p3 ).r; + c.samp4 = getSample( c.p4 ).r; + + } else if (channel == 1) { + + c.samp1 = getSample( c.p1 ).g; + c.samp2 = getSample( c.p2 ).g; + c.samp3 = getSample( c.p3 ).g; + c.samp4 = getSample( c.p4 ).g; + + } else { + + c.samp1 = getSample( c.p1 ).b; + c.samp3 = getSample( c.p3 ).b; + c.samp2 = getSample( c.p2 ).b; + c.samp4 = getSample( c.p4 ).b; + + } + + dist_c_1 = distanceToDotRadius( c.samp1, c.p1, c.normal, p, angle, radius ); + dist_c_2 = distanceToDotRadius( c.samp2, c.p2, c.normal, p, angle, radius ); + dist_c_3 = distanceToDotRadius( c.samp3, c.p3, c.normal, p, angle, radius ); + dist_c_4 = distanceToDotRadius( c.samp4, c.p4, c.normal, p, angle, radius ); + res = ( dist_c_1 > 0.0 ) ? clamp( dist_c_1 / aa, 0.0, 1.0 ) : 0.0; + res += ( dist_c_2 > 0.0 ) ? clamp( dist_c_2 / aa, 0.0, 1.0 ) : 0.0; + res += ( dist_c_3 > 0.0 ) ? clamp( dist_c_3 / aa, 0.0, 1.0 ) : 0.0; + res += ( dist_c_4 > 0.0 ) ? clamp( dist_c_4 / aa, 0.0, 1.0 ) : 0.0; + res = clamp( res, 0.0, 1.0 ); + + return res; + + } + + Cell getReferenceCell( vec2 p, vec2 origin, float grid_angle, float step ) { + + // get containing cell + Cell c; + + // calc grid + vec2 n = vec2( cos( grid_angle ), sin( grid_angle ) ); + float threshold = step * 0.5; + float dot_normal = n.x * ( p.x - origin.x ) + n.y * ( p.y - origin.y ); + float dot_line = -n.y * ( p.x - origin.x ) + n.x * ( p.y - origin.y ); + vec2 offset = vec2( n.x * dot_normal, n.y * dot_normal ); + float offset_normal = mod( hypot( offset.x, offset.y ), step ); + float normal_dir = ( dot_normal < 0.0 ) ? 1.0 : -1.0; + float normal_scale = ( ( offset_normal < threshold ) ? -offset_normal : step - offset_normal ) * normal_dir; + float offset_line = mod( hypot( ( p.x - offset.x ) - origin.x, ( p.y - offset.y ) - origin.y ), step ); + float line_dir = ( dot_line < 0.0 ) ? 1.0 : -1.0; + float line_scale = ( ( offset_line < threshold ) ? -offset_line : step - offset_line ) * line_dir; + + // get closest corner + c.normal = n; + c.p1.x = p.x - n.x * normal_scale + n.y * line_scale; + c.p1.y = p.y - n.y * normal_scale - n.x * line_scale; + + // scatter + if ( scatter != 0.0 ) { + + float off_mag = scatter * threshold * 0.5; + float off_angle = rand( vec2( floor( c.p1.x ), floor( c.p1.y ) ) ) * PI2; + c.p1.x += cos( off_angle ) * off_mag; + c.p1.y += sin( off_angle ) * off_mag; + + } + + // find corners + float normal_step = normal_dir * ( ( offset_normal < threshold ) ? step : -step ); + float line_step = line_dir * ( ( offset_line < threshold ) ? step : -step ); + c.p2.x = c.p1.x - n.x * normal_step; + c.p2.y = c.p1.y - n.y * normal_step; + c.p3.x = c.p1.x + n.y * line_step; + c.p3.y = c.p1.y - n.x * line_step; + c.p4.x = c.p1.x - n.x * normal_step + n.y * line_step; + c.p4.y = c.p1.y - n.y * normal_step - n.x * line_step; + + return c; + + } + + float blendColour( float a, float b, float t ) { + + // blend colours + if ( blendingMode == BLENDING_LINEAR ) { + return blend( a, b, 1.0 - t ); + } else if ( blendingMode == BLENDING_ADD ) { + return blend( a, min( 1.0, a + b ), t ); + } else if ( blendingMode == BLENDING_MULTIPLY ) { + return blend( a, max( 0.0, a * b ), t ); + } else if ( blendingMode == BLENDING_LIGHTER ) { + return blend( a, max( a, b ), t ); + } else if ( blendingMode == BLENDING_DARKER ) { + return blend( a, min( a, b ), t ); + } else { + return blend( a, b, 1.0 - t ); + } + + } + + void main() { + + if ( ! disable ) { + + // setup + vec2 p = vec2( vUV.x * width, vUV.y * height ); + vec2 origin = vec2( 0, 0 ); + float aa = ( radius < 2.5 ) ? radius * 0.5 : 1.25; + + // get channel samples + Cell cell_r = getReferenceCell( p, origin, rotateR, radius ); + Cell cell_g = getReferenceCell( p, origin, rotateG, radius ); + Cell cell_b = getReferenceCell( p, origin, rotateB, radius ); + float r = getDotColour( cell_r, p, 0, rotateR, aa ); + float g = getDotColour( cell_g, p, 1, rotateG, aa ); + float b = getDotColour( cell_b, p, 2, rotateB, aa ); + + // blend with original + vec4 colour = texture2D( tDiffuse, vUV ); + r = blendColour( r, colour.r, blending ); + g = blendColour( g, colour.g, blending ); + b = blendColour( b, colour.b, blending ); + + if ( greyscale ) { + r = g = b = (r + b + g) / 3.0; + } + + gl_FragColor = vec4( r, g, b, 1.0 ); + + } else { + + gl_FragColor = texture2D( tDiffuse, vUV ); + + } + + }` +}; +// node_modules/three/examples/jsm/postprocessing/OutlinePass.js +class OutlinePass extends Pass { + constructor(resolution, scene, camera, selectedObjects) { + super(); + this.renderScene = scene; + this.renderCamera = camera; + this.selectedObjects = selectedObjects !== undefined ? selectedObjects : []; + this.visibleEdgeColor = new Color(1, 1, 1); + this.hiddenEdgeColor = new Color(0.1, 0.04, 0.02); + this.edgeGlow = 0; + this.usePatternTexture = false; + this.edgeThickness = 1; + this.edgeStrength = 3; + this.downSampleRatio = 2; + this.pulsePeriod = 0; + this._visibilityCache = new Map; + this._selectionCache = new Set; + this.resolution = resolution !== undefined ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256); + const resx = Math.round(this.resolution.x / this.downSampleRatio); + const resy = Math.round(this.resolution.y / this.downSampleRatio); + this.renderTargetMaskBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y); + this.renderTargetMaskBuffer.texture.name = "OutlinePass.mask"; + this.renderTargetMaskBuffer.texture.generateMipmaps = false; + this.depthMaterial = new MeshDepthMaterial; + this.depthMaterial.side = DoubleSide; + this.depthMaterial.depthPacking = RGBADepthPacking; + this.depthMaterial.blending = NoBlending; + this.prepareMaskMaterial = this.getPrepareMaskMaterial(); + this.prepareMaskMaterial.side = DoubleSide; + this.prepareMaskMaterial.fragmentShader = replaceDepthToViewZ(this.prepareMaskMaterial.fragmentShader, this.renderCamera); + this.renderTargetDepthBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { type: HalfFloatType }); + this.renderTargetDepthBuffer.texture.name = "OutlinePass.depth"; + this.renderTargetDepthBuffer.texture.generateMipmaps = false; + this.renderTargetMaskDownSampleBuffer = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + this.renderTargetMaskDownSampleBuffer.texture.name = "OutlinePass.depthDownSample"; + this.renderTargetMaskDownSampleBuffer.texture.generateMipmaps = false; + this.renderTargetBlurBuffer1 = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + this.renderTargetBlurBuffer1.texture.name = "OutlinePass.blur1"; + this.renderTargetBlurBuffer1.texture.generateMipmaps = false; + this.renderTargetBlurBuffer2 = new WebGLRenderTarget(Math.round(resx / 2), Math.round(resy / 2), { type: HalfFloatType }); + this.renderTargetBlurBuffer2.texture.name = "OutlinePass.blur2"; + this.renderTargetBlurBuffer2.texture.generateMipmaps = false; + this.edgeDetectionMaterial = this.getEdgeDetectionMaterial(); + this.renderTargetEdgeBuffer1 = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + this.renderTargetEdgeBuffer1.texture.name = "OutlinePass.edge1"; + this.renderTargetEdgeBuffer1.texture.generateMipmaps = false; + this.renderTargetEdgeBuffer2 = new WebGLRenderTarget(Math.round(resx / 2), Math.round(resy / 2), { type: HalfFloatType }); + this.renderTargetEdgeBuffer2.texture.name = "OutlinePass.edge2"; + this.renderTargetEdgeBuffer2.texture.generateMipmaps = false; + const MAX_EDGE_THICKNESS = 4; + const MAX_EDGE_GLOW = 4; + this.separableBlurMaterial1 = this.getSeparableBlurMaterial(MAX_EDGE_THICKNESS); + this.separableBlurMaterial1.uniforms["texSize"].value.set(resx, resy); + this.separableBlurMaterial1.uniforms["kernelRadius"].value = 1; + this.separableBlurMaterial2 = this.getSeparableBlurMaterial(MAX_EDGE_GLOW); + this.separableBlurMaterial2.uniforms["texSize"].value.set(Math.round(resx / 2), Math.round(resy / 2)); + this.separableBlurMaterial2.uniforms["kernelRadius"].value = MAX_EDGE_GLOW; + this.overlayMaterial = this.getOverlayMaterial(); + const copyShader = CopyShader; + this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); + this.materialCopy = new ShaderMaterial({ + uniforms: this.copyUniforms, + vertexShader: copyShader.vertexShader, + fragmentShader: copyShader.fragmentShader, + blending: NoBlending, + depthTest: false, + depthWrite: false + }); + this.enabled = true; + this.needsSwap = false; + this._oldClearColor = new Color; + this.oldClearAlpha = 1; + this.fsQuad = new FullScreenQuad(null); + this.tempPulseColor1 = new Color; + this.tempPulseColor2 = new Color; + this.textureMatrix = new Matrix4; + function replaceDepthToViewZ(string, camera2) { + const type = camera2.isPerspectiveCamera ? "perspective" : "orthographic"; + return string.replace(/DEPTH_TO_VIEW_Z/g, type + "DepthToViewZ"); + } + } + dispose() { + this.renderTargetMaskBuffer.dispose(); + this.renderTargetDepthBuffer.dispose(); + this.renderTargetMaskDownSampleBuffer.dispose(); + this.renderTargetBlurBuffer1.dispose(); + this.renderTargetBlurBuffer2.dispose(); + this.renderTargetEdgeBuffer1.dispose(); + this.renderTargetEdgeBuffer2.dispose(); + this.depthMaterial.dispose(); + this.prepareMaskMaterial.dispose(); + this.edgeDetectionMaterial.dispose(); + this.separableBlurMaterial1.dispose(); + this.separableBlurMaterial2.dispose(); + this.overlayMaterial.dispose(); + this.materialCopy.dispose(); + this.fsQuad.dispose(); + } + setSize(width2, height2) { + this.renderTargetMaskBuffer.setSize(width2, height2); + this.renderTargetDepthBuffer.setSize(width2, height2); + let resx = Math.round(width2 / this.downSampleRatio); + let resy = Math.round(height2 / this.downSampleRatio); + this.renderTargetMaskDownSampleBuffer.setSize(resx, resy); + this.renderTargetBlurBuffer1.setSize(resx, resy); + this.renderTargetEdgeBuffer1.setSize(resx, resy); + this.separableBlurMaterial1.uniforms["texSize"].value.set(resx, resy); + resx = Math.round(resx / 2); + resy = Math.round(resy / 2); + this.renderTargetBlurBuffer2.setSize(resx, resy); + this.renderTargetEdgeBuffer2.setSize(resx, resy); + this.separableBlurMaterial2.uniforms["texSize"].value.set(resx, resy); + } + updateSelectionCache() { + const cache = this._selectionCache; + function gatherSelectedMeshesCallBack(object) { + if (object.isMesh) + cache.add(object); + } + cache.clear(); + for (let i = 0;i < this.selectedObjects.length; i++) { + const selectedObject = this.selectedObjects[i]; + selectedObject.traverse(gatherSelectedMeshesCallBack); + } + } + changeVisibilityOfSelectedObjects(bVisible) { + const cache = this._visibilityCache; + for (const mesh of this._selectionCache) { + if (bVisible === true) { + mesh.visible = cache.get(mesh); + } else { + cache.set(mesh, mesh.visible); + mesh.visible = bVisible; + } + } + } + changeVisibilityOfNonSelectedObjects(bVisible) { + const visibilityCache = this._visibilityCache; + const selectionCache = this._selectionCache; + function VisibilityChangeCallBack(object) { + if (object.isMesh || object.isSprite) { + if (!selectionCache.has(object)) { + const visibility = object.visible; + if (bVisible === false || visibilityCache.get(object) === true) { + object.visible = bVisible; + } + visibilityCache.set(object, visibility); + } + } else if (object.isPoints || object.isLine) { + if (bVisible === true) { + object.visible = visibilityCache.get(object); + } else { + visibilityCache.set(object, object.visible); + object.visible = bVisible; + } + } + } + this.renderScene.traverse(VisibilityChangeCallBack); + } + updateTextureMatrix() { + this.textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1); + this.textureMatrix.multiply(this.renderCamera.projectionMatrix); + this.textureMatrix.multiply(this.renderCamera.matrixWorldInverse); + } + render(renderer2, writeBuffer, readBuffer, deltaTime, maskActive) { + if (this.selectedObjects.length > 0) { + renderer2.getClearColor(this._oldClearColor); + this.oldClearAlpha = renderer2.getClearAlpha(); + const oldAutoClear = renderer2.autoClear; + renderer2.autoClear = false; + if (maskActive) + renderer2.state.buffers.stencil.setTest(false); + renderer2.setClearColor(16777215, 1); + this.updateSelectionCache(); + this.changeVisibilityOfSelectedObjects(false); + const currentBackground = this.renderScene.background; + this.renderScene.background = null; + this.renderScene.overrideMaterial = this.depthMaterial; + renderer2.setRenderTarget(this.renderTargetDepthBuffer); + renderer2.clear(); + renderer2.render(this.renderScene, this.renderCamera); + this.changeVisibilityOfSelectedObjects(true); + this._visibilityCache.clear(); + this.updateTextureMatrix(); + this.changeVisibilityOfNonSelectedObjects(false); + this.renderScene.overrideMaterial = this.prepareMaskMaterial; + this.prepareMaskMaterial.uniforms["cameraNearFar"].value.set(this.renderCamera.near, this.renderCamera.far); + this.prepareMaskMaterial.uniforms["depthTexture"].value = this.renderTargetDepthBuffer.texture; + this.prepareMaskMaterial.uniforms["textureMatrix"].value = this.textureMatrix; + renderer2.setRenderTarget(this.renderTargetMaskBuffer); + renderer2.clear(); + renderer2.render(this.renderScene, this.renderCamera); + this.renderScene.overrideMaterial = null; + this.changeVisibilityOfNonSelectedObjects(true); + this._visibilityCache.clear(); + this._selectionCache.clear(); + this.renderScene.background = currentBackground; + this.fsQuad.material = this.materialCopy; + this.copyUniforms["tDiffuse"].value = this.renderTargetMaskBuffer.texture; + renderer2.setRenderTarget(this.renderTargetMaskDownSampleBuffer); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.tempPulseColor1.copy(this.visibleEdgeColor); + this.tempPulseColor2.copy(this.hiddenEdgeColor); + if (this.pulsePeriod > 0) { + const scalar = (1 + 0.25) / 2 + Math.cos(performance.now() * 0.01 / this.pulsePeriod) * (1 - 0.25) / 2; + this.tempPulseColor1.multiplyScalar(scalar); + this.tempPulseColor2.multiplyScalar(scalar); + } + this.fsQuad.material = this.edgeDetectionMaterial; + this.edgeDetectionMaterial.uniforms["maskTexture"].value = this.renderTargetMaskDownSampleBuffer.texture; + this.edgeDetectionMaterial.uniforms["texSize"].value.set(this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height); + this.edgeDetectionMaterial.uniforms["visibleEdgeColor"].value = this.tempPulseColor1; + this.edgeDetectionMaterial.uniforms["hiddenEdgeColor"].value = this.tempPulseColor2; + renderer2.setRenderTarget(this.renderTargetEdgeBuffer1); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.separableBlurMaterial1; + this.separableBlurMaterial1.uniforms["colorTexture"].value = this.renderTargetEdgeBuffer1.texture; + this.separableBlurMaterial1.uniforms["direction"].value = OutlinePass.BlurDirectionX; + this.separableBlurMaterial1.uniforms["kernelRadius"].value = this.edgeThickness; + renderer2.setRenderTarget(this.renderTargetBlurBuffer1); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.separableBlurMaterial1.uniforms["colorTexture"].value = this.renderTargetBlurBuffer1.texture; + this.separableBlurMaterial1.uniforms["direction"].value = OutlinePass.BlurDirectionY; + renderer2.setRenderTarget(this.renderTargetEdgeBuffer1); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.separableBlurMaterial2; + this.separableBlurMaterial2.uniforms["colorTexture"].value = this.renderTargetEdgeBuffer1.texture; + this.separableBlurMaterial2.uniforms["direction"].value = OutlinePass.BlurDirectionX; + renderer2.setRenderTarget(this.renderTargetBlurBuffer2); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.separableBlurMaterial2.uniforms["colorTexture"].value = this.renderTargetBlurBuffer2.texture; + this.separableBlurMaterial2.uniforms["direction"].value = OutlinePass.BlurDirectionY; + renderer2.setRenderTarget(this.renderTargetEdgeBuffer2); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.overlayMaterial; + this.overlayMaterial.uniforms["maskTexture"].value = this.renderTargetMaskBuffer.texture; + this.overlayMaterial.uniforms["edgeTexture1"].value = this.renderTargetEdgeBuffer1.texture; + this.overlayMaterial.uniforms["edgeTexture2"].value = this.renderTargetEdgeBuffer2.texture; + this.overlayMaterial.uniforms["patternTexture"].value = this.patternTexture; + this.overlayMaterial.uniforms["edgeStrength"].value = this.edgeStrength; + this.overlayMaterial.uniforms["edgeGlow"].value = this.edgeGlow; + this.overlayMaterial.uniforms["usePatternTexture"].value = this.usePatternTexture; + if (maskActive) + renderer2.state.buffers.stencil.setTest(true); + renderer2.setRenderTarget(readBuffer); + this.fsQuad.render(renderer2); + renderer2.setClearColor(this._oldClearColor, this.oldClearAlpha); + renderer2.autoClear = oldAutoClear; + } + if (this.renderToScreen) { + this.fsQuad.material = this.materialCopy; + this.copyUniforms["tDiffuse"].value = readBuffer.texture; + renderer2.setRenderTarget(null); + this.fsQuad.render(renderer2); + } + } + getPrepareMaskMaterial() { + return new ShaderMaterial({ + uniforms: { + depthTexture: { value: null }, + cameraNearFar: { value: new Vector2(0.5, 0.5) }, + textureMatrix: { value: null } + }, + vertexShader: `#include + #include + + varying vec4 projTexCoord; + varying vec4 vPosition; + uniform mat4 textureMatrix; + + void main() { + + #include + #include + #include + #include + #include + + vPosition = mvPosition; + + vec4 worldPosition = vec4( transformed, 1.0 ); + + #ifdef USE_INSTANCING + + worldPosition = instanceMatrix * worldPosition; + + #endif + + worldPosition = modelMatrix * worldPosition; + + projTexCoord = textureMatrix * worldPosition; + + }`, + fragmentShader: `#include + varying vec4 vPosition; + varying vec4 projTexCoord; + uniform sampler2D depthTexture; + uniform vec2 cameraNearFar; + + void main() { + + float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord )); + float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y ); + float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0; + gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0); + + }` + }); + } + getEdgeDetectionMaterial() { + return new ShaderMaterial({ + uniforms: { + maskTexture: { value: null }, + texSize: { value: new Vector2(0.5, 0.5) }, + visibleEdgeColor: { value: new Vector3(1, 1, 1) }, + hiddenEdgeColor: { value: new Vector3(1, 1, 1) } + }, + vertexShader: `varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `varying vec2 vUv; + + uniform sampler2D maskTexture; + uniform vec2 texSize; + uniform vec3 visibleEdgeColor; + uniform vec3 hiddenEdgeColor; + + void main() { + vec2 invSize = 1.0 / texSize; + vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize); + vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy); + vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy); + vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw); + vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw); + float diff1 = (c1.r - c2.r)*0.5; + float diff2 = (c3.r - c4.r)*0.5; + float d = length( vec2(diff1, diff2) ); + float a1 = min(c1.g, c2.g); + float a2 = min(c3.g, c4.g); + float visibilityFactor = min(a1, a2); + vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor; + gl_FragColor = vec4(edgeColor, 1.0) * vec4(d); + }` + }); + } + getSeparableBlurMaterial(maxRadius) { + return new ShaderMaterial({ + defines: { + MAX_RADIUS: maxRadius + }, + uniforms: { + colorTexture: { value: null }, + texSize: { value: new Vector2(0.5, 0.5) }, + direction: { value: new Vector2(0.5, 0.5) }, + kernelRadius: { value: 1 } + }, + vertexShader: `varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `#include + varying vec2 vUv; + uniform sampler2D colorTexture; + uniform vec2 texSize; + uniform vec2 direction; + uniform float kernelRadius; + + float gaussianPdf(in float x, in float sigma) { + return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma; + } + + void main() { + vec2 invSize = 1.0 / texSize; + float sigma = kernelRadius/2.0; + float weightSum = gaussianPdf(0.0, sigma); + vec4 diffuseSum = texture2D( colorTexture, vUv) * weightSum; + vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS); + vec2 uvOffset = delta; + for( int i = 1; i <= MAX_RADIUS; i ++ ) { + float x = kernelRadius * float(i) / float(MAX_RADIUS); + float w = gaussianPdf(x, sigma); + vec4 sample1 = texture2D( colorTexture, vUv + uvOffset); + vec4 sample2 = texture2D( colorTexture, vUv - uvOffset); + diffuseSum += ((sample1 + sample2) * w); + weightSum += (2.0 * w); + uvOffset += delta; + } + gl_FragColor = diffuseSum/weightSum; + }` + }); + } + getOverlayMaterial() { + return new ShaderMaterial({ + uniforms: { + maskTexture: { value: null }, + edgeTexture1: { value: null }, + edgeTexture2: { value: null }, + patternTexture: { value: null }, + edgeStrength: { value: 1 }, + edgeGlow: { value: 1 }, + usePatternTexture: { value: 0 } + }, + vertexShader: `varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `varying vec2 vUv; + + uniform sampler2D maskTexture; + uniform sampler2D edgeTexture1; + uniform sampler2D edgeTexture2; + uniform sampler2D patternTexture; + uniform float edgeStrength; + uniform float edgeGlow; + uniform bool usePatternTexture; + + void main() { + vec4 edgeValue1 = texture2D(edgeTexture1, vUv); + vec4 edgeValue2 = texture2D(edgeTexture2, vUv); + vec4 maskColor = texture2D(maskTexture, vUv); + vec4 patternColor = texture2D(patternTexture, 6.0 * vUv); + float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5; + vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow; + vec4 finalColor = edgeStrength * maskColor.r * edgeValue; + if(usePatternTexture) + finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r); + gl_FragColor = finalColor; + }`, + blending: AdditiveBlending, + depthTest: false, + depthWrite: false, + transparent: true + }); + } +} +OutlinePass.BlurDirectionX = new Vector2(1, 0); +OutlinePass.BlurDirectionY = new Vector2(0, 1); +// node_modules/three/examples/jsm/shaders/SAOShader.js +var SAOShader = { + name: "SAOShader", + defines: { + NUM_SAMPLES: 7, + NUM_RINGS: 4, + DIFFUSE_TEXTURE: 0, + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDepth: { value: null }, + tDiffuse: { value: null }, + tNormal: { value: null }, + size: { value: new Vector2(512, 512) }, + cameraNear: { value: 1 }, + cameraFar: { value: 100 }, + cameraProjectionMatrix: { value: new Matrix4 }, + cameraInverseProjectionMatrix: { value: new Matrix4 }, + scale: { value: 1 }, + intensity: { value: 0.1 }, + bias: { value: 0.5 }, + minResolution: { value: 0 }, + kernelRadius: { value: 100 }, + randomSeed: { value: 0 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + #include + + varying vec2 vUv; + + #if DIFFUSE_TEXTURE == 1 + uniform sampler2D tDiffuse; + #endif + + uniform highp sampler2D tDepth; + uniform highp sampler2D tNormal; + + uniform float cameraNear; + uniform float cameraFar; + uniform mat4 cameraProjectionMatrix; + uniform mat4 cameraInverseProjectionMatrix; + + uniform float scale; + uniform float intensity; + uniform float bias; + uniform float kernelRadius; + uniform float minResolution; + uniform vec2 size; + uniform float randomSeed; + + // RGBA depth + + #include + + vec4 getDefaultColor( const in vec2 screenPosition ) { + #if DIFFUSE_TEXTURE == 1 + return texture2D( tDiffuse, vUv ); + #else + return vec4( 1.0 ); + #endif + } + + float getDepth( const in vec2 screenPosition ) { + return texture2D( tDepth, screenPosition ).x; + } + + float getViewZ( const in float depth ) { + #if PERSPECTIVE_CAMERA == 1 + return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + #else + return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + #endif + } + + vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) { + float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3]; + vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 ); + clipPosition *= clipW; // unprojection. + + return ( cameraInverseProjectionMatrix * clipPosition ).xyz; + } + + vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPosition ) { + return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); + } + + float scaleDividedByCameraFar; + float minResolutionMultipliedByCameraFar; + + float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) { + vec3 viewDelta = sampleViewPosition - centerViewPosition; + float viewDistance = length( viewDelta ); + float scaledScreenDistance = scaleDividedByCameraFar * viewDistance; + + return max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - bias) / (1.0 + pow2( scaledScreenDistance ) ); + } + + // moving costly divides into consts + const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES ); + const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES ); + + float getAmbientOcclusion( const in vec3 centerViewPosition ) { + // precompute some variables require in getOcclusion. + scaleDividedByCameraFar = scale / cameraFar; + minResolutionMultipliedByCameraFar = minResolution * cameraFar; + vec3 centerViewNormal = getViewNormal( centerViewPosition, vUv ); + + // jsfiddle that shows sample pattern: https://jsfiddle.net/a16ff1p7/ + float angle = rand( vUv + randomSeed ) * PI2; + vec2 radius = vec2( kernelRadius * INV_NUM_SAMPLES ) / size; + vec2 radiusStep = radius; + + float occlusionSum = 0.0; + float weightSum = 0.0; + + for( int i = 0; i < NUM_SAMPLES; i ++ ) { + vec2 sampleUv = vUv + vec2( cos( angle ), sin( angle ) ) * radius; + radius += radiusStep; + angle += ANGLE_STEP; + + float sampleDepth = getDepth( sampleUv ); + if( sampleDepth >= ( 1.0 - EPSILON ) ) { + continue; + } + + float sampleViewZ = getViewZ( sampleDepth ); + vec3 sampleViewPosition = getViewPosition( sampleUv, sampleDepth, sampleViewZ ); + occlusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition ); + weightSum += 1.0; + } + + if( weightSum == 0.0 ) discard; + + return occlusionSum * ( intensity / weightSum ); + } + + void main() { + float centerDepth = getDepth( vUv ); + if( centerDepth >= ( 1.0 - EPSILON ) ) { + discard; + } + + float centerViewZ = getViewZ( centerDepth ); + vec3 viewPosition = getViewPosition( vUv, centerDepth, centerViewZ ); + + float ambientOcclusion = getAmbientOcclusion( viewPosition ); + + gl_FragColor = getDefaultColor( vUv ); + gl_FragColor.xyz *= 1.0 - ambientOcclusion; + }` +}; + +// node_modules/three/examples/jsm/shaders/DepthLimitedBlurShader.js +var DepthLimitedBlurShader = { + name: "DepthLimitedBlurShader", + defines: { + KERNEL_RADIUS: 4, + DEPTH_PACKING: 1, + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDiffuse: { value: null }, + size: { value: new Vector2(512, 512) }, + sampleUvOffsets: { value: [new Vector2(0, 0)] }, + sampleWeights: { value: [1] }, + tDepth: { value: null }, + cameraNear: { value: 10 }, + cameraFar: { value: 1000 }, + depthCutoff: { value: 10 } + }, + vertexShader: ` + + #include + + uniform vec2 size; + + varying vec2 vUv; + varying vec2 vInvSize; + + void main() { + vUv = uv; + vInvSize = 1.0 / size; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: ` + + #include + #include + + uniform sampler2D tDiffuse; + uniform sampler2D tDepth; + + uniform float cameraNear; + uniform float cameraFar; + uniform float depthCutoff; + + uniform vec2 sampleUvOffsets[ KERNEL_RADIUS + 1 ]; + uniform float sampleWeights[ KERNEL_RADIUS + 1 ]; + + varying vec2 vUv; + varying vec2 vInvSize; + + float getDepth( const in vec2 screenPosition ) { + #if DEPTH_PACKING == 1 + return unpackRGBAToDepth( texture2D( tDepth, screenPosition ) ); + #else + return texture2D( tDepth, screenPosition ).x; + #endif + } + + float getViewZ( const in float depth ) { + #if PERSPECTIVE_CAMERA == 1 + return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + #else + return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + #endif + } + + void main() { + float depth = getDepth( vUv ); + if( depth >= ( 1.0 - EPSILON ) ) { + discard; + } + + float centerViewZ = -getViewZ( depth ); + bool rBreak = false, lBreak = false; + + float weightSum = sampleWeights[0]; + vec4 diffuseSum = texture2D( tDiffuse, vUv ) * weightSum; + + for( int i = 1; i <= KERNEL_RADIUS; i ++ ) { + + float sampleWeight = sampleWeights[i]; + vec2 sampleUvOffset = sampleUvOffsets[i] * vInvSize; + + vec2 sampleUv = vUv + sampleUvOffset; + float viewZ = -getViewZ( getDepth( sampleUv ) ); + + if( abs( viewZ - centerViewZ ) > depthCutoff ) rBreak = true; + + if( ! rBreak ) { + diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight; + weightSum += sampleWeight; + } + + sampleUv = vUv - sampleUvOffset; + viewZ = -getViewZ( getDepth( sampleUv ) ); + + if( abs( viewZ - centerViewZ ) > depthCutoff ) lBreak = true; + + if( ! lBreak ) { + diffuseSum += texture2D( tDiffuse, sampleUv ) * sampleWeight; + weightSum += sampleWeight; + } + + } + + gl_FragColor = diffuseSum / weightSum; + }` +}; +var BlurShaderUtils = { + createSampleWeights: function(kernelRadius, stdDev) { + const weights = []; + for (let i = 0;i <= kernelRadius; i++) { + weights.push(gaussian(i, stdDev)); + } + return weights; + }, + createSampleOffsets: function(kernelRadius, uvIncrement) { + const offsets = []; + for (let i = 0;i <= kernelRadius; i++) { + offsets.push(uvIncrement.clone().multiplyScalar(i)); + } + return offsets; + }, + configure: function(material, kernelRadius, stdDev, uvIncrement) { + material.defines["KERNEL_RADIUS"] = kernelRadius; + material.uniforms["sampleUvOffsets"].value = BlurShaderUtils.createSampleOffsets(kernelRadius, uvIncrement); + material.uniforms["sampleWeights"].value = BlurShaderUtils.createSampleWeights(kernelRadius, stdDev); + material.needsUpdate = true; + } +}; +function gaussian(x2, stdDev) { + return Math.exp(-(x2 * x2) / (2 * (stdDev * stdDev))) / (Math.sqrt(2 * Math.PI) * stdDev); +} + +// node_modules/three/examples/jsm/postprocessing/SAOPass.js +class SAOPass extends Pass { + constructor(scene, camera, resolution = new Vector2(256, 256)) { + super(); + this.scene = scene; + this.camera = camera; + this.clear = true; + this.needsSwap = false; + this.originalClearColor = new Color; + this._oldClearColor = new Color; + this.oldClearAlpha = 1; + this.params = { + output: 0, + saoBias: 0.5, + saoIntensity: 0.18, + saoScale: 1, + saoKernelRadius: 100, + saoMinResolution: 0, + saoBlur: true, + saoBlurRadius: 8, + saoBlurStdDev: 4, + saoBlurDepthCutoff: 0.01 + }; + this.resolution = new Vector2(resolution.x, resolution.y); + this.saoRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { type: HalfFloatType }); + this.blurIntermediateRenderTarget = this.saoRenderTarget.clone(); + const depthTexture = new DepthTexture; + depthTexture.format = DepthStencilFormat; + depthTexture.type = UnsignedInt248Type; + this.normalRenderTarget = new WebGLRenderTarget(this.resolution.x, this.resolution.y, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType, + depthTexture + }); + this.normalMaterial = new MeshNormalMaterial; + this.normalMaterial.blending = NoBlending; + this.saoMaterial = new ShaderMaterial({ + defines: Object.assign({}, SAOShader.defines), + fragmentShader: SAOShader.fragmentShader, + vertexShader: SAOShader.vertexShader, + uniforms: UniformsUtils.clone(SAOShader.uniforms) + }); + this.saoMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0; + this.saoMaterial.uniforms["tDepth"].value = depthTexture; + this.saoMaterial.uniforms["tNormal"].value = this.normalRenderTarget.texture; + this.saoMaterial.uniforms["size"].value.set(this.resolution.x, this.resolution.y); + this.saoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.saoMaterial.uniforms["cameraProjectionMatrix"].value = this.camera.projectionMatrix; + this.saoMaterial.blending = NoBlending; + this.vBlurMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(DepthLimitedBlurShader.uniforms), + defines: Object.assign({}, DepthLimitedBlurShader.defines), + vertexShader: DepthLimitedBlurShader.vertexShader, + fragmentShader: DepthLimitedBlurShader.fragmentShader + }); + this.vBlurMaterial.defines["DEPTH_PACKING"] = 0; + this.vBlurMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0; + this.vBlurMaterial.uniforms["tDiffuse"].value = this.saoRenderTarget.texture; + this.vBlurMaterial.uniforms["tDepth"].value = depthTexture; + this.vBlurMaterial.uniforms["size"].value.set(this.resolution.x, this.resolution.y); + this.vBlurMaterial.blending = NoBlending; + this.hBlurMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(DepthLimitedBlurShader.uniforms), + defines: Object.assign({}, DepthLimitedBlurShader.defines), + vertexShader: DepthLimitedBlurShader.vertexShader, + fragmentShader: DepthLimitedBlurShader.fragmentShader + }); + this.hBlurMaterial.defines["DEPTH_PACKING"] = 0; + this.hBlurMaterial.defines["PERSPECTIVE_CAMERA"] = this.camera.isPerspectiveCamera ? 1 : 0; + this.hBlurMaterial.uniforms["tDiffuse"].value = this.blurIntermediateRenderTarget.texture; + this.hBlurMaterial.uniforms["tDepth"].value = depthTexture; + this.hBlurMaterial.uniforms["size"].value.set(this.resolution.x, this.resolution.y); + this.hBlurMaterial.blending = NoBlending; + this.materialCopy = new ShaderMaterial({ + uniforms: UniformsUtils.clone(CopyShader.uniforms), + vertexShader: CopyShader.vertexShader, + fragmentShader: CopyShader.fragmentShader, + blending: NoBlending + }); + this.materialCopy.transparent = true; + this.materialCopy.depthTest = false; + this.materialCopy.depthWrite = false; + this.materialCopy.blending = CustomBlending; + this.materialCopy.blendSrc = DstColorFactor; + this.materialCopy.blendDst = ZeroFactor; + this.materialCopy.blendEquation = AddEquation; + this.materialCopy.blendSrcAlpha = DstAlphaFactor; + this.materialCopy.blendDstAlpha = ZeroFactor; + this.materialCopy.blendEquationAlpha = AddEquation; + this.fsQuad = new FullScreenQuad(null); + } + render(renderer2, writeBuffer, readBuffer) { + if (this.renderToScreen) { + this.materialCopy.blending = NoBlending; + this.materialCopy.uniforms["tDiffuse"].value = readBuffer.texture; + this.materialCopy.needsUpdate = true; + this.renderPass(renderer2, this.materialCopy, null); + } + renderer2.getClearColor(this._oldClearColor); + this.oldClearAlpha = renderer2.getClearAlpha(); + const oldAutoClear = renderer2.autoClear; + renderer2.autoClear = false; + this.saoMaterial.uniforms["bias"].value = this.params.saoBias; + this.saoMaterial.uniforms["intensity"].value = this.params.saoIntensity; + this.saoMaterial.uniforms["scale"].value = this.params.saoScale; + this.saoMaterial.uniforms["kernelRadius"].value = this.params.saoKernelRadius; + this.saoMaterial.uniforms["minResolution"].value = this.params.saoMinResolution; + this.saoMaterial.uniforms["cameraNear"].value = this.camera.near; + this.saoMaterial.uniforms["cameraFar"].value = this.camera.far; + const depthCutoff = this.params.saoBlurDepthCutoff * (this.camera.far - this.camera.near); + this.vBlurMaterial.uniforms["depthCutoff"].value = depthCutoff; + this.hBlurMaterial.uniforms["depthCutoff"].value = depthCutoff; + this.vBlurMaterial.uniforms["cameraNear"].value = this.camera.near; + this.vBlurMaterial.uniforms["cameraFar"].value = this.camera.far; + this.hBlurMaterial.uniforms["cameraNear"].value = this.camera.near; + this.hBlurMaterial.uniforms["cameraFar"].value = this.camera.far; + this.params.saoBlurRadius = Math.floor(this.params.saoBlurRadius); + if (this.prevStdDev !== this.params.saoBlurStdDev || this.prevNumSamples !== this.params.saoBlurRadius) { + BlurShaderUtils.configure(this.vBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2(0, 1)); + BlurShaderUtils.configure(this.hBlurMaterial, this.params.saoBlurRadius, this.params.saoBlurStdDev, new Vector2(1, 0)); + this.prevStdDev = this.params.saoBlurStdDev; + this.prevNumSamples = this.params.saoBlurRadius; + } + this.renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 7829503, 1); + this.renderPass(renderer2, this.saoMaterial, this.saoRenderTarget, 16777215, 1); + if (this.params.saoBlur) { + this.renderPass(renderer2, this.vBlurMaterial, this.blurIntermediateRenderTarget, 16777215, 1); + this.renderPass(renderer2, this.hBlurMaterial, this.saoRenderTarget, 16777215, 1); + } + const outputMaterial = this.materialCopy; + if (this.params.output === SAOPass.OUTPUT.Normal) { + this.materialCopy.uniforms["tDiffuse"].value = this.normalRenderTarget.texture; + this.materialCopy.needsUpdate = true; + } else { + this.materialCopy.uniforms["tDiffuse"].value = this.saoRenderTarget.texture; + this.materialCopy.needsUpdate = true; + } + if (this.params.output === SAOPass.OUTPUT.Default) { + outputMaterial.blending = CustomBlending; + } else { + outputMaterial.blending = NoBlending; + } + this.renderPass(renderer2, outputMaterial, this.renderToScreen ? null : readBuffer); + renderer2.setClearColor(this._oldClearColor, this.oldClearAlpha); + renderer2.autoClear = oldAutoClear; + } + renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.fsQuad.material = passMaterial; + this.fsQuad.render(renderer2); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.overrideMaterial = overrideMaterial; + renderer2.render(this.scene, this.camera); + this.scene.overrideMaterial = null; + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + setSize(width2, height2) { + this.saoRenderTarget.setSize(width2, height2); + this.blurIntermediateRenderTarget.setSize(width2, height2); + this.normalRenderTarget.setSize(width2, height2); + this.saoMaterial.uniforms["size"].value.set(width2, height2); + this.saoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.saoMaterial.uniforms["cameraProjectionMatrix"].value = this.camera.projectionMatrix; + this.saoMaterial.needsUpdate = true; + this.vBlurMaterial.uniforms["size"].value.set(width2, height2); + this.vBlurMaterial.needsUpdate = true; + this.hBlurMaterial.uniforms["size"].value.set(width2, height2); + this.hBlurMaterial.needsUpdate = true; + } + dispose() { + this.saoRenderTarget.dispose(); + this.blurIntermediateRenderTarget.dispose(); + this.normalRenderTarget.dispose(); + this.normalMaterial.dispose(); + this.saoMaterial.dispose(); + this.vBlurMaterial.dispose(); + this.hBlurMaterial.dispose(); + this.materialCopy.dispose(); + this.fsQuad.dispose(); + } +} +SAOPass.OUTPUT = { + Default: 0, + SAO: 1, + Normal: 2 +}; +// node_modules/three/examples/jsm/shaders/SMAAShader.js +var SMAAEdgesShader = { + name: "SMAAEdgesShader", + defines: { + SMAA_THRESHOLD: "0.1" + }, + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2(1 / 1024, 1 / 512) } + }, + vertexShader: ` + + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 3 ]; + + void SMAAEdgeDetectionVS( vec2 texcoord ) { + vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component + vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component + vOffset[ 2 ] = texcoord.xyxy + resolution.xyxy * vec4( -2.0, 0.0, 0.0, 2.0 ); // WebGL port note: Changed sign in W component + } + + void main() { + + vUv = uv; + + SMAAEdgeDetectionVS( vUv ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + + varying vec2 vUv; + varying vec4 vOffset[ 3 ]; + + vec4 SMAAColorEdgeDetectionPS( vec2 texcoord, vec4 offset[3], sampler2D colorTex ) { + vec2 threshold = vec2( SMAA_THRESHOLD, SMAA_THRESHOLD ); + + // Calculate color deltas: + vec4 delta; + vec3 C = texture2D( colorTex, texcoord ).rgb; + + vec3 Cleft = texture2D( colorTex, offset[0].xy ).rgb; + vec3 t = abs( C - Cleft ); + delta.x = max( max( t.r, t.g ), t.b ); + + vec3 Ctop = texture2D( colorTex, offset[0].zw ).rgb; + t = abs( C - Ctop ); + delta.y = max( max( t.r, t.g ), t.b ); + + // We do the usual threshold: + vec2 edges = step( threshold, delta.xy ); + + // Then discard if there is no edge: + if ( dot( edges, vec2( 1.0, 1.0 ) ) == 0.0 ) + discard; + + // Calculate right and bottom deltas: + vec3 Cright = texture2D( colorTex, offset[1].xy ).rgb; + t = abs( C - Cright ); + delta.z = max( max( t.r, t.g ), t.b ); + + vec3 Cbottom = texture2D( colorTex, offset[1].zw ).rgb; + t = abs( C - Cbottom ); + delta.w = max( max( t.r, t.g ), t.b ); + + // Calculate the maximum delta in the direct neighborhood: + float maxDelta = max( max( max( delta.x, delta.y ), delta.z ), delta.w ); + + // Calculate left-left and top-top deltas: + vec3 Cleftleft = texture2D( colorTex, offset[2].xy ).rgb; + t = abs( C - Cleftleft ); + delta.z = max( max( t.r, t.g ), t.b ); + + vec3 Ctoptop = texture2D( colorTex, offset[2].zw ).rgb; + t = abs( C - Ctoptop ); + delta.w = max( max( t.r, t.g ), t.b ); + + // Calculate the final maximum delta: + maxDelta = max( max( maxDelta, delta.z ), delta.w ); + + // Local contrast adaptation in action: + edges.xy *= step( 0.5 * maxDelta, delta.xy ); + + return vec4( edges, 0.0, 0.0 ); + } + + void main() { + + gl_FragColor = SMAAColorEdgeDetectionPS( vUv, vOffset, tDiffuse ); + + }` +}; +var SMAAWeightsShader = { + name: "SMAAWeightsShader", + defines: { + SMAA_MAX_SEARCH_STEPS: "8", + SMAA_AREATEX_MAX_DISTANCE: "16", + SMAA_AREATEX_PIXEL_SIZE: "( 1.0 / vec2( 160.0, 560.0 ) )", + SMAA_AREATEX_SUBTEX_SIZE: "( 1.0 / 7.0 )" + }, + uniforms: { + tDiffuse: { value: null }, + tArea: { value: null }, + tSearch: { value: null }, + resolution: { value: new Vector2(1 / 1024, 1 / 512) } + }, + vertexShader: ` + + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 3 ]; + varying vec2 vPixcoord; + + void SMAABlendingWeightCalculationVS( vec2 texcoord ) { + vPixcoord = texcoord / resolution; + + // We will use these offsets for the searches later on (see @PSEUDO_GATHER4): + vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.25, 0.125, 1.25, 0.125 ); // WebGL port note: Changed sign in Y and W components + vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.125, 0.25, -0.125, -1.25 ); // WebGL port note: Changed sign in Y and W components + + // And these for the searches, they indicate the ends of the loops: + vOffset[ 2 ] = vec4( vOffset[ 0 ].xz, vOffset[ 1 ].yw ) + vec4( -2.0, 2.0, -2.0, 2.0 ) * resolution.xxyy * float( SMAA_MAX_SEARCH_STEPS ); + + } + + void main() { + + vUv = uv; + + SMAABlendingWeightCalculationVS( vUv ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + #define SMAASampleLevelZeroOffset( tex, coord, offset ) texture2D( tex, coord + float( offset ) * resolution, 0.0 ) + + uniform sampler2D tDiffuse; + uniform sampler2D tArea; + uniform sampler2D tSearch; + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[3]; + varying vec2 vPixcoord; + + #if __VERSION__ == 100 + vec2 round( vec2 x ) { + return sign( x ) * floor( abs( x ) + 0.5 ); + } + #endif + + float SMAASearchLength( sampler2D searchTex, vec2 e, float bias, float scale ) { + // Not required if searchTex accesses are set to point: + // float2 SEARCH_TEX_PIXEL_SIZE = 1.0 / float2(66.0, 33.0); + // e = float2(bias, 0.0) + 0.5 * SEARCH_TEX_PIXEL_SIZE + + // e * float2(scale, 1.0) * float2(64.0, 32.0) * SEARCH_TEX_PIXEL_SIZE; + e.r = bias + e.r * scale; + return 255.0 * texture2D( searchTex, e, 0.0 ).r; + } + + float SMAASearchXLeft( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + /** + * @PSEUDO_GATHER4 + * This texcoord has been offset by (-0.25, -0.125) in the vertex shader to + * sample between edge, thus fetching four edges in a row. + * Sampling with different offsets in each direction allows to disambiguate + * which edges are active from the four fetched ones. + */ + vec2 e = vec2( 0.0, 1.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord -= vec2( 2.0, 0.0 ) * resolution; + if ( ! ( texcoord.x > end && e.g > 0.8281 && e.r == 0.0 ) ) break; + } + + // We correct the previous (-0.25, -0.125) offset we applied: + texcoord.x += 0.25 * resolution.x; + + // The searches are bias by 1, so adjust the coords accordingly: + texcoord.x += resolution.x; + + // Disambiguate the length added by the last step: + texcoord.x += 2.0 * resolution.x; // Undo last step + texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5); + + return texcoord.x; + } + + float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + vec2 e = vec2( 0.0, 1.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord += vec2( 2.0, 0.0 ) * resolution; + if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break; + } + + texcoord.x -= 0.25 * resolution.x; + texcoord.x -= resolution.x; + texcoord.x -= 2.0 * resolution.x; + texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 ); + + return texcoord.x; + } + + float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + vec2 e = vec2( 1.0, 0.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord += vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign + if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break; + } + + texcoord.y -= 0.25 * resolution.y; // WebGL port note: Changed sign + texcoord.y -= resolution.y; // WebGL port note: Changed sign + texcoord.y -= 2.0 * resolution.y; // WebGL port note: Changed sign + texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 ); // WebGL port note: Changed sign + + return texcoord.y; + } + + float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) { + vec2 e = vec2( 1.0, 0.0 ); + + for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for + e = texture2D( edgesTex, texcoord, 0.0 ).rg; + texcoord -= vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign + if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break; + } + + texcoord.y += 0.25 * resolution.y; // WebGL port note: Changed sign + texcoord.y += resolution.y; // WebGL port note: Changed sign + texcoord.y += 2.0 * resolution.y; // WebGL port note: Changed sign + texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 ); // WebGL port note: Changed sign + + return texcoord.y; + } + + vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) { + // Rounding prevents precision errors of bilinear filtering: + vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist; + + // We do a scale and bias for mapping to texel space: + texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE ); + + // Move to proper place, according to the subpixel offset: + texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset; + + return texture2D( areaTex, texcoord, 0.0 ).rg; + } + + vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) { + vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 ); + + vec2 e = texture2D( edgesTex, texcoord ).rg; + + if ( e.g > 0.0 ) { // Edge at north + vec2 d; + + // Find the distance to the left: + vec2 coords; + coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x ); + coords.y = offset[ 1 ].y; // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET) + d.x = coords.x; + + // Now fetch the left crossing edges, two at a time using bilinear + // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to + // discern what value each edge has: + float e1 = texture2D( edgesTex, coords, 0.0 ).r; + + // Find the distance to the right: + coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y ); + d.y = coords.x; + + // We want the distances to be in pixel units (doing this here allow to + // better interleave arithmetic and memory accesses): + d = d / resolution.x - pixcoord.x; + + // SMAAArea below needs a sqrt, as the areas texture is compressed + // quadratically: + vec2 sqrt_d = sqrt( abs( d ) ); + + // Fetch the right crossing edges: + coords.y -= 1.0 * resolution.y; // WebGL port note: Added + float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r; + + // Ok, we know how this pattern looks like, now it is time for getting + // the actual area: + weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) ); + } + + if ( e.r > 0.0 ) { // Edge at west + vec2 d; + + // Find the distance to the top: + vec2 coords; + + coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z ); + coords.x = offset[ 0 ].x; // offset[1].x = texcoord.x - 0.25 * resolution.x; + d.x = coords.y; + + // Fetch the top crossing edges: + float e1 = texture2D( edgesTex, coords, 0.0 ).g; + + // Find the distance to the bottom: + coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w ); + d.y = coords.y; + + // We want the distances to be in pixel units: + d = d / resolution.y - pixcoord.y; + + // SMAAArea below needs a sqrt, as the areas texture is compressed + // quadratically: + vec2 sqrt_d = sqrt( abs( d ) ); + + // Fetch the bottom crossing edges: + coords.y -= 1.0 * resolution.y; // WebGL port note: Added + float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g; + + // Get the area for this direction: + weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) ); + } + + return weights; + } + + void main() { + + gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) ); + + }` +}; +var SMAABlendShader = { + name: "SMAABlendShader", + uniforms: { + tDiffuse: { value: null }, + tColor: { value: null }, + resolution: { value: new Vector2(1 / 1024, 1 / 512) } + }, + vertexShader: ` + + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 2 ]; + + void SMAANeighborhoodBlendingVS( vec2 texcoord ) { + vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component + vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component + } + + void main() { + + vUv = uv; + + SMAANeighborhoodBlendingVS( vUv ); + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform sampler2D tColor; + uniform vec2 resolution; + + varying vec2 vUv; + varying vec4 vOffset[ 2 ]; + + vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) { + // Fetch the blending weights for current pixel: + vec4 a; + a.xz = texture2D( blendTex, texcoord ).xz; + a.y = texture2D( blendTex, offset[ 1 ].zw ).g; + a.w = texture2D( blendTex, offset[ 1 ].xy ).a; + + // Is there any blending weight with a value greater than 0.0? + if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) { + return texture2D( colorTex, texcoord, 0.0 ); + } else { + // Up to 4 lines can be crossing a pixel (one through each edge). We + // favor blending by choosing the line with the maximum weight for each + // direction: + vec2 offset; + offset.x = a.a > a.b ? a.a : -a.b; // left vs. right + offset.y = a.g > a.r ? -a.g : a.r; // top vs. bottom // WebGL port note: Changed signs + + // Then we go in the direction that has the maximum weight: + if ( abs( offset.x ) > abs( offset.y )) { // horizontal vs. vertical + offset.y = 0.0; + } else { + offset.x = 0.0; + } + + // Fetch the opposite color and lerp by hand: + vec4 C = texture2D( colorTex, texcoord, 0.0 ); + texcoord += sign( offset ) * resolution; + vec4 Cop = texture2D( colorTex, texcoord, 0.0 ); + float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y ); + + // WebGL port note: Added gamma correction + C.xyz = pow(C.xyz, vec3(2.2)); + Cop.xyz = pow(Cop.xyz, vec3(2.2)); + vec4 mixed = mix(C, Cop, s); + mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2)); + + return mixed; + } + } + + void main() { + + gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse ); + + }` +}; +// node_modules/three/examples/jsm/shaders/SSAOShader.js +var SSAOShader = { + name: "SSAOShader", + defines: { + PERSPECTIVE_CAMERA: 1, + KERNEL_SIZE: 32 + }, + uniforms: { + tNormal: { value: null }, + tDepth: { value: null }, + tNoise: { value: null }, + kernel: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null }, + resolution: { value: new Vector2 }, + cameraProjectionMatrix: { value: new Matrix4 }, + cameraInverseProjectionMatrix: { value: new Matrix4 }, + kernelRadius: { value: 8 }, + minDistance: { value: 0.005 }, + maxDistance: { value: 0.05 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + uniform highp sampler2D tNormal; + uniform highp sampler2D tDepth; + uniform sampler2D tNoise; + + uniform vec3 kernel[ KERNEL_SIZE ]; + + uniform vec2 resolution; + + uniform float cameraNear; + uniform float cameraFar; + uniform mat4 cameraProjectionMatrix; + uniform mat4 cameraInverseProjectionMatrix; + + uniform float kernelRadius; + uniform float minDistance; // avoid artifacts caused by neighbour fragments with minimal depth difference + uniform float maxDistance; // avoid the influence of fragments which are too far away + + varying vec2 vUv; + + #include + + float getDepth( const in vec2 screenPosition ) { + + return texture2D( tDepth, screenPosition ).x; + + } + + float getLinearDepth( const in vec2 screenPosition ) { + + #if PERSPECTIVE_CAMERA == 1 + + float fragCoordZ = texture2D( tDepth, screenPosition ).x; + float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); + return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + + #else + + return texture2D( tDepth, screenPosition ).x; + + #endif + + } + + float getViewZ( const in float depth ) { + + #if PERSPECTIVE_CAMERA == 1 + + return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + + #else + + return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + + #endif + + } + + vec3 getViewPosition( const in vec2 screenPosition, const in float depth, const in float viewZ ) { + + float clipW = cameraProjectionMatrix[2][3] * viewZ + cameraProjectionMatrix[3][3]; + + vec4 clipPosition = vec4( ( vec3( screenPosition, depth ) - 0.5 ) * 2.0, 1.0 ); + + clipPosition *= clipW; // unprojection. + + return ( cameraInverseProjectionMatrix * clipPosition ).xyz; + + } + + vec3 getViewNormal( const in vec2 screenPosition ) { + + return unpackRGBToNormal( texture2D( tNormal, screenPosition ).xyz ); + + } + + void main() { + + float depth = getDepth( vUv ); + + if ( depth == 1.0 ) { + + gl_FragColor = vec4( 1.0 ); // don't influence background + + } else { + + float viewZ = getViewZ( depth ); + + vec3 viewPosition = getViewPosition( vUv, depth, viewZ ); + vec3 viewNormal = getViewNormal( vUv ); + + vec2 noiseScale = vec2( resolution.x / 4.0, resolution.y / 4.0 ); + vec3 random = vec3( texture2D( tNoise, vUv * noiseScale ).r ); + + // compute matrix used to reorient a kernel vector + + vec3 tangent = normalize( random - viewNormal * dot( random, viewNormal ) ); + vec3 bitangent = cross( viewNormal, tangent ); + mat3 kernelMatrix = mat3( tangent, bitangent, viewNormal ); + + float occlusion = 0.0; + + for ( int i = 0; i < KERNEL_SIZE; i ++ ) { + + vec3 sampleVector = kernelMatrix * kernel[ i ]; // reorient sample vector in view space + vec3 samplePoint = viewPosition + ( sampleVector * kernelRadius ); // calculate sample point + + vec4 samplePointNDC = cameraProjectionMatrix * vec4( samplePoint, 1.0 ); // project point and calculate NDC + samplePointNDC /= samplePointNDC.w; + + vec2 samplePointUv = samplePointNDC.xy * 0.5 + 0.5; // compute uv coordinates + + float realDepth = getLinearDepth( samplePointUv ); // get linear depth from depth texture + float sampleDepth = viewZToOrthographicDepth( samplePoint.z, cameraNear, cameraFar ); // compute linear depth of the sample view Z value + float delta = sampleDepth - realDepth; + + if ( delta > minDistance && delta < maxDistance ) { // if fragment is before sample point, increase occlusion + + occlusion += 1.0; + + } + + } + + occlusion = clamp( occlusion / float( KERNEL_SIZE ), 0.0, 1.0 ); + + gl_FragColor = vec4( vec3( 1.0 - occlusion ), 1.0 ); + + } + + }` +}; +var SSAODepthShader = { + name: "SSAODepthShader", + defines: { + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDepth: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null } + }, + vertexShader: `varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: `uniform sampler2D tDepth; + + uniform float cameraNear; + uniform float cameraFar; + + varying vec2 vUv; + + #include + + float getLinearDepth( const in vec2 screenPosition ) { + + #if PERSPECTIVE_CAMERA == 1 + + float fragCoordZ = texture2D( tDepth, screenPosition ).x; + float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); + return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + + #else + + return texture2D( tDepth, screenPosition ).x; + + #endif + + } + + void main() { + + float depth = getLinearDepth( vUv ); + gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 ); + + }` +}; +var SSAOBlurShader = { + name: "SSAOBlurShader", + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2 } + }, + vertexShader: `varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: `uniform sampler2D tDiffuse; + + uniform vec2 resolution; + + varying vec2 vUv; + + void main() { + + vec2 texelSize = ( 1.0 / resolution ); + float result = 0.0; + + for ( int i = - 2; i <= 2; i ++ ) { + + for ( int j = - 2; j <= 2; j ++ ) { + + vec2 offset = ( vec2( float( i ), float( j ) ) ) * texelSize; + result += texture2D( tDiffuse, vUv + offset ).r; + + } + + } + + gl_FragColor = vec4( vec3( result / ( 5.0 * 5.0 ) ), 1.0 ); + + }` +}; + +// node_modules/three/examples/jsm/postprocessing/SSAOPass.js +class SSAOPass extends Pass { + constructor(scene, camera, width2, height2, kernelSize = 32) { + super(); + this.width = width2 !== undefined ? width2 : 512; + this.height = height2 !== undefined ? height2 : 512; + this.clear = true; + this.needsSwap = false; + this.camera = camera; + this.scene = scene; + this.kernelRadius = 8; + this.kernel = []; + this.noiseTexture = null; + this.output = 0; + this.minDistance = 0.005; + this.maxDistance = 0.1; + this._visibilityCache = new Map; + this.generateSampleKernel(kernelSize); + this.generateRandomKernelRotations(); + const depthTexture = new DepthTexture; + depthTexture.format = DepthStencilFormat; + depthTexture.type = UnsignedInt248Type; + this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType, + depthTexture + }); + this.ssaoRenderTarget = new WebGLRenderTarget(this.width, this.height, { type: HalfFloatType }); + this.blurRenderTarget = this.ssaoRenderTarget.clone(); + this.ssaoMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSAOShader.defines), + uniforms: UniformsUtils.clone(SSAOShader.uniforms), + vertexShader: SSAOShader.vertexShader, + fragmentShader: SSAOShader.fragmentShader, + blending: NoBlending + }); + this.ssaoMaterial.defines["KERNEL_SIZE"] = kernelSize; + this.ssaoMaterial.uniforms["tNormal"].value = this.normalRenderTarget.texture; + this.ssaoMaterial.uniforms["tDepth"].value = this.normalRenderTarget.depthTexture; + this.ssaoMaterial.uniforms["tNoise"].value = this.noiseTexture; + this.ssaoMaterial.uniforms["kernel"].value = this.kernel; + this.ssaoMaterial.uniforms["cameraNear"].value = this.camera.near; + this.ssaoMaterial.uniforms["cameraFar"].value = this.camera.far; + this.ssaoMaterial.uniforms["resolution"].value.set(this.width, this.height); + this.ssaoMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); + this.ssaoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.normalMaterial = new MeshNormalMaterial; + this.normalMaterial.blending = NoBlending; + this.blurMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSAOBlurShader.defines), + uniforms: UniformsUtils.clone(SSAOBlurShader.uniforms), + vertexShader: SSAOBlurShader.vertexShader, + fragmentShader: SSAOBlurShader.fragmentShader + }); + this.blurMaterial.uniforms["tDiffuse"].value = this.ssaoRenderTarget.texture; + this.blurMaterial.uniforms["resolution"].value.set(this.width, this.height); + this.depthRenderMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSAODepthShader.defines), + uniforms: UniformsUtils.clone(SSAODepthShader.uniforms), + vertexShader: SSAODepthShader.vertexShader, + fragmentShader: SSAODepthShader.fragmentShader, + blending: NoBlending + }); + this.depthRenderMaterial.uniforms["tDepth"].value = this.normalRenderTarget.depthTexture; + this.depthRenderMaterial.uniforms["cameraNear"].value = this.camera.near; + this.depthRenderMaterial.uniforms["cameraFar"].value = this.camera.far; + this.copyMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(CopyShader.uniforms), + vertexShader: CopyShader.vertexShader, + fragmentShader: CopyShader.fragmentShader, + transparent: true, + depthTest: false, + depthWrite: false, + blendSrc: DstColorFactor, + blendDst: ZeroFactor, + blendEquation: AddEquation, + blendSrcAlpha: DstAlphaFactor, + blendDstAlpha: ZeroFactor, + blendEquationAlpha: AddEquation + }); + this.fsQuad = new FullScreenQuad(null); + this.originalClearColor = new Color; + } + dispose() { + this.normalRenderTarget.dispose(); + this.ssaoRenderTarget.dispose(); + this.blurRenderTarget.dispose(); + this.normalMaterial.dispose(); + this.blurMaterial.dispose(); + this.copyMaterial.dispose(); + this.depthRenderMaterial.dispose(); + this.fsQuad.dispose(); + } + render(renderer2, writeBuffer, readBuffer) { + this.overrideVisibility(); + this.renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 7829503, 1); + this.restoreVisibility(); + this.ssaoMaterial.uniforms["kernelRadius"].value = this.kernelRadius; + this.ssaoMaterial.uniforms["minDistance"].value = this.minDistance; + this.ssaoMaterial.uniforms["maxDistance"].value = this.maxDistance; + this.renderPass(renderer2, this.ssaoMaterial, this.ssaoRenderTarget); + this.renderPass(renderer2, this.blurMaterial, this.blurRenderTarget); + switch (this.output) { + case SSAOPass.OUTPUT.SSAO: + this.copyMaterial.uniforms["tDiffuse"].value = this.ssaoRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer); + break; + case SSAOPass.OUTPUT.Blur: + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer); + break; + case SSAOPass.OUTPUT.Depth: + this.renderPass(renderer2, this.depthRenderMaterial, this.renderToScreen ? null : readBuffer); + break; + case SSAOPass.OUTPUT.Normal: + this.copyMaterial.uniforms["tDiffuse"].value = this.normalRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer); + break; + case SSAOPass.OUTPUT.Default: + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget.texture; + this.copyMaterial.blending = CustomBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : readBuffer); + break; + default: + console.warn("THREE.SSAOPass: Unknown output type."); + } + } + renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.fsQuad.material = passMaterial; + this.fsQuad.render(renderer2); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + renderer2.getClearColor(this.originalClearColor); + const originalClearAlpha = renderer2.getClearAlpha(); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.overrideMaterial = overrideMaterial; + renderer2.render(this.scene, this.camera); + this.scene.overrideMaterial = null; + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + setSize(width2, height2) { + this.width = width2; + this.height = height2; + this.ssaoRenderTarget.setSize(width2, height2); + this.normalRenderTarget.setSize(width2, height2); + this.blurRenderTarget.setSize(width2, height2); + this.ssaoMaterial.uniforms["resolution"].value.set(width2, height2); + this.ssaoMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); + this.ssaoMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.blurMaterial.uniforms["resolution"].value.set(width2, height2); + } + generateSampleKernel(kernelSize) { + const kernel = this.kernel; + for (let i = 0;i < kernelSize; i++) { + const sample = new Vector3; + sample.x = Math.random() * 2 - 1; + sample.y = Math.random() * 2 - 1; + sample.z = Math.random(); + sample.normalize(); + let scale2 = i / kernelSize; + scale2 = MathUtils.lerp(0.1, 1, scale2 * scale2); + sample.multiplyScalar(scale2); + kernel.push(sample); + } + } + generateRandomKernelRotations() { + const width2 = 4, height2 = 4; + const simplex = new SimplexNoise; + const size2 = width2 * height2; + const data2 = new Float32Array(size2); + for (let i = 0;i < size2; i++) { + const x2 = Math.random() * 2 - 1; + const y = Math.random() * 2 - 1; + const z = 0; + data2[i] = simplex.noise3d(x2, y, z); + } + this.noiseTexture = new DataTexture(data2, width2, height2, RedFormat, FloatType); + this.noiseTexture.wrapS = RepeatWrapping; + this.noiseTexture.wrapT = RepeatWrapping; + this.noiseTexture.needsUpdate = true; + } + overrideVisibility() { + const scene = this.scene; + const cache = this._visibilityCache; + scene.traverse(function(object) { + cache.set(object, object.visible); + if (object.isPoints || object.isLine) + object.visible = false; + }); + } + restoreVisibility() { + const scene = this.scene; + const cache = this._visibilityCache; + scene.traverse(function(object) { + const visible = cache.get(object); + object.visible = visible; + }); + cache.clear(); + } +} +SSAOPass.OUTPUT = { + Default: 0, + SSAO: 1, + Blur: 2, + Depth: 3, + Normal: 4 +}; +// node_modules/three/examples/jsm/shaders/SSRShader.js +var SSRShader = { + name: "SSRShader", + defines: { + MAX_STEP: 0, + PERSPECTIVE_CAMERA: true, + DISTANCE_ATTENUATION: true, + FRESNEL: true, + INFINITE_THICK: false, + SELECTIVE: false + }, + uniforms: { + tDiffuse: { value: null }, + tNormal: { value: null }, + tMetalness: { value: null }, + tDepth: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null }, + resolution: { value: new Vector2 }, + cameraProjectionMatrix: { value: new Matrix4 }, + cameraInverseProjectionMatrix: { value: new Matrix4 }, + opacity: { value: 0.5 }, + maxDistance: { value: 180 }, + cameraRange: { value: 0 }, + thickness: { value: 0.018 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + } + + `, + fragmentShader: ` + // precision highp float; + precision highp sampler2D; + varying vec2 vUv; + uniform sampler2D tDepth; + uniform sampler2D tNormal; + uniform sampler2D tMetalness; + uniform sampler2D tDiffuse; + uniform float cameraRange; + uniform vec2 resolution; + uniform float opacity; + uniform float cameraNear; + uniform float cameraFar; + uniform float maxDistance; + uniform float thickness; + uniform mat4 cameraProjectionMatrix; + uniform mat4 cameraInverseProjectionMatrix; + #include + float pointToLineDistance(vec3 x0, vec3 x1, vec3 x2) { + //x0: point, x1: linePointA, x2: linePointB + //https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html + return length(cross(x0-x1,x0-x2))/length(x2-x1); + } + float pointPlaneDistance(vec3 point,vec3 planePoint,vec3 planeNormal){ + // https://mathworld.wolfram.com/Point-PlaneDistance.html + //// https://en.wikipedia.org/wiki/Plane_(geometry) + //// http://paulbourke.net/geometry/pointlineplane/ + float a=planeNormal.x,b=planeNormal.y,c=planeNormal.z; + float x0=point.x,y0=point.y,z0=point.z; + float x=planePoint.x,y=planePoint.y,z=planePoint.z; + float d=-(a*x+b*y+c*z); + float distance=(a*x0+b*y0+c*z0+d)/sqrt(a*a+b*b+c*c); + return distance; + } + float getDepth( const in vec2 uv ) { + return texture2D( tDepth, uv ).x; + } + float getViewZ( const in float depth ) { + #ifdef PERSPECTIVE_CAMERA + return perspectiveDepthToViewZ( depth, cameraNear, cameraFar ); + #else + return orthographicDepthToViewZ( depth, cameraNear, cameraFar ); + #endif + } + vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) { + vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc + clipPosition *= clipW; //clip + return ( cameraInverseProjectionMatrix * clipPosition ).xyz;//view + } + vec3 getViewNormal( const in vec2 uv ) { + return unpackRGBToNormal( texture2D( tNormal, uv ).xyz ); + } + vec2 viewPositionToXY(vec3 viewPosition){ + vec2 xy; + vec4 clip=cameraProjectionMatrix*vec4(viewPosition,1); + xy=clip.xy;//clip + float clipW=clip.w; + xy/=clipW;//NDC + xy=(xy+1.)/2.;//uv + xy*=resolution;//screen + return xy; + } + void main(){ + #ifdef SELECTIVE + float metalness=texture2D(tMetalness,vUv).r; + if(metalness==0.) return; + #endif + + float depth = getDepth( vUv ); + float viewZ = getViewZ( depth ); + if(-viewZ>=cameraFar) return; + + float clipW = cameraProjectionMatrix[2][3] * viewZ+cameraProjectionMatrix[3][3]; + vec3 viewPosition=getViewPosition( vUv, depth, clipW ); + + vec2 d0=gl_FragCoord.xy; + vec2 d1; + + vec3 viewNormal=getViewNormal( vUv ); + + #ifdef PERSPECTIVE_CAMERA + vec3 viewIncidentDir=normalize(viewPosition); + vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal); + #else + vec3 viewIncidentDir=vec3(0,0,-1); + vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal); + #endif + + float maxReflectRayLen=maxDistance/dot(-viewIncidentDir,viewNormal); + // dot(a,b)==length(a)*length(b)*cos(theta) // https://www.mathsisfun.com/algebra/vectors-dot-product.html + // if(a.isNormalized&&b.isNormalized) dot(a,b)==cos(theta) + // maxDistance/maxReflectRayLen=cos(theta) + // maxDistance/maxReflectRayLen==dot(a,b) + // maxReflectRayLen==maxDistance/dot(a,b) + + vec3 d1viewPosition=viewPosition+viewReflectDir*maxReflectRayLen; + #ifdef PERSPECTIVE_CAMERA + if(d1viewPosition.z>-cameraNear){ + //https://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx + float t=(-cameraNear-viewPosition.z)/viewReflectDir.z; + d1viewPosition=viewPosition+viewReflectDir*t; + } + #endif + d1=viewPositionToXY(d1viewPosition); + + float totalLen=length(d1-d0); + float xLen=d1.x-d0.x; + float yLen=d1.y-d0.y; + float totalStep=max(abs(xLen),abs(yLen)); + float xSpan=xLen/totalStep; + float ySpan=yLen/totalStep; + for(float i=0.;i=totalStep) break; + vec2 xy=vec2(d0.x+i*xSpan,d0.y+i*ySpan); + if(xy.x<0.||xy.x>resolution.x||xy.y<0.||xy.y>resolution.y) break; + float s=length(xy-d0)/totalLen; + vec2 uv=xy/resolution; + + float d = getDepth(uv); + float vZ = getViewZ( d ); + if(-vZ>=cameraFar) continue; + float cW = cameraProjectionMatrix[2][3] * vZ+cameraProjectionMatrix[3][3]; + vec3 vP=getViewPosition( uv, d, cW ); + + #ifdef PERSPECTIVE_CAMERA + // https://comp.nus.edu.sg/~lowkl/publications/lowk_persp_interp_techrep.pdf + float recipVPZ=1./viewPosition.z; + float viewReflectRayZ=1./(recipVPZ+s*(1./d1viewPosition.z-recipVPZ)); + #else + float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z); + #endif + + // if(viewReflectRayZ>vZ) continue; // will cause "npm run make-screenshot webgl_postprocessing_ssr" high probability hang. + // https://github.com/mrdoob/three.js/pull/21539#issuecomment-821061164 + if(viewReflectRayZ<=vZ){ + + bool hit; + #ifdef INFINITE_THICK + hit=true; + #else + float away=pointToLineDistance(vP,viewPosition,d1viewPosition); + + float minThickness; + vec2 xyNeighbor=xy; + xyNeighbor.x+=1.; + vec2 uvNeighbor=xyNeighbor/resolution; + vec3 vPNeighbor=getViewPosition(uvNeighbor,d,cW); + minThickness=vPNeighbor.x-vP.x; + minThickness*=3.; + float tk=max(minThickness,thickness); + + hit=away<=tk; + #endif + + if(hit){ + vec3 vN=getViewNormal( uv ); + if(dot(viewReflectDir,vN)>=0.) continue; + float distance=pointPlaneDistance(vP,viewPosition,viewNormal); + if(distance>maxDistance) break; + float op=opacity; + #ifdef DISTANCE_ATTENUATION + float ratio=1.-(distance/maxDistance); + float attenuation=ratio*ratio; + op=opacity*attenuation; + #endif + #ifdef FRESNEL + float fresnelCoe=(dot(viewIncidentDir,viewReflectDir)+1.)/2.; + op*=fresnelCoe; + #endif + vec4 reflectColor=texture2D(tDiffuse,uv); + gl_FragColor.xyz=reflectColor.xyz; + gl_FragColor.a=op; + break; + } + } + } + } + ` +}; +var SSRDepthShader = { + name: "SSRDepthShader", + defines: { + PERSPECTIVE_CAMERA: 1 + }, + uniforms: { + tDepth: { value: null }, + cameraNear: { value: null }, + cameraFar: { value: null } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + } + + `, + fragmentShader: ` + + uniform sampler2D tDepth; + + uniform float cameraNear; + uniform float cameraFar; + + varying vec2 vUv; + + #include + + float getLinearDepth( const in vec2 uv ) { + + #if PERSPECTIVE_CAMERA == 1 + + float fragCoordZ = texture2D( tDepth, uv ).x; + float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar ); + return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar ); + + #else + + return texture2D( tDepth, uv ).x; + + #endif + + } + + void main() { + + float depth = getLinearDepth( vUv ); + float d = 1.0 - depth; + // d=(d-.999)*1000.; + gl_FragColor = vec4( vec3( d ), 1.0 ); + + } + + ` +}; +var SSRBlurShader = { + name: "SSRBlurShader", + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2 }, + opacity: { value: 0.5 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + } + + `, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform vec2 resolution; + varying vec2 vUv; + void main() { + //reverse engineering from PhotoShop blur filter, then change coefficient + + vec2 texelSize = ( 1.0 / resolution ); + + vec4 c=texture2D(tDiffuse,vUv); + + vec2 offset; + + offset=(vec2(-1,0))*texelSize; + vec4 cl=texture2D(tDiffuse,vUv+offset); + + offset=(vec2(1,0))*texelSize; + vec4 cr=texture2D(tDiffuse,vUv+offset); + + offset=(vec2(0,-1))*texelSize; + vec4 cb=texture2D(tDiffuse,vUv+offset); + + offset=(vec2(0,1))*texelSize; + vec4 ct=texture2D(tDiffuse,vUv+offset); + + // float coeCenter=.5; + // float coeSide=.125; + float coeCenter=.2; + float coeSide=.2; + float a=c.a*coeCenter+cl.a*coeSide+cr.a*coeSide+cb.a*coeSide+ct.a*coeSide; + vec3 rgb=(c.rgb*c.a*coeCenter+cl.rgb*cl.a*coeSide+cr.rgb*cr.a*coeSide+cb.rgb*cb.a*coeSide+ct.rgb*ct.a*coeSide)/a; + gl_FragColor=vec4(rgb,a); + + } + ` +}; + +// node_modules/three/examples/jsm/postprocessing/SSRPass.js +class SSRPass extends Pass { + constructor({ renderer: renderer2, scene, camera, width: width2, height: height2, selects, bouncing = false, groundReflector }) { + super(); + this.width = width2 !== undefined ? width2 : 512; + this.height = height2 !== undefined ? height2 : 512; + this.clear = true; + this.renderer = renderer2; + this.scene = scene; + this.camera = camera; + this.groundReflector = groundReflector; + this.opacity = SSRShader.uniforms.opacity.value; + this.output = 0; + this.maxDistance = SSRShader.uniforms.maxDistance.value; + this.thickness = SSRShader.uniforms.thickness.value; + this.tempColor = new Color; + this._selects = selects; + this.selective = Array.isArray(this._selects); + Object.defineProperty(this, "selects", { + get() { + return this._selects; + }, + set(val2) { + if (this._selects === val2) + return; + this._selects = val2; + if (Array.isArray(val2)) { + this.selective = true; + this.ssrMaterial.defines.SELECTIVE = true; + this.ssrMaterial.needsUpdate = true; + } else { + this.selective = false; + this.ssrMaterial.defines.SELECTIVE = false; + this.ssrMaterial.needsUpdate = true; + } + } + }); + this._bouncing = bouncing; + Object.defineProperty(this, "bouncing", { + get() { + return this._bouncing; + }, + set(val2) { + if (this._bouncing === val2) + return; + this._bouncing = val2; + if (val2) { + this.ssrMaterial.uniforms["tDiffuse"].value = this.prevRenderTarget.texture; + } else { + this.ssrMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + } + } + }); + this.blur = true; + this._distanceAttenuation = SSRShader.defines.DISTANCE_ATTENUATION; + Object.defineProperty(this, "distanceAttenuation", { + get() { + return this._distanceAttenuation; + }, + set(val2) { + if (this._distanceAttenuation === val2) + return; + this._distanceAttenuation = val2; + this.ssrMaterial.defines.DISTANCE_ATTENUATION = val2; + this.ssrMaterial.needsUpdate = true; + } + }); + this._fresnel = SSRShader.defines.FRESNEL; + Object.defineProperty(this, "fresnel", { + get() { + return this._fresnel; + }, + set(val2) { + if (this._fresnel === val2) + return; + this._fresnel = val2; + this.ssrMaterial.defines.FRESNEL = val2; + this.ssrMaterial.needsUpdate = true; + } + }); + this._infiniteThick = SSRShader.defines.INFINITE_THICK; + Object.defineProperty(this, "infiniteThick", { + get() { + return this._infiniteThick; + }, + set(val2) { + if (this._infiniteThick === val2) + return; + this._infiniteThick = val2; + this.ssrMaterial.defines.INFINITE_THICK = val2; + this.ssrMaterial.needsUpdate = true; + } + }); + const depthTexture = new DepthTexture; + depthTexture.type = UnsignedShortType; + depthTexture.minFilter = NearestFilter; + depthTexture.magFilter = NearestFilter; + this.beautyRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType, + depthTexture, + depthBuffer: true + }); + this.prevRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter + }); + this.normalRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType + }); + this.metalnessRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter, + type: HalfFloatType + }); + this.ssrRenderTarget = new WebGLRenderTarget(this.width, this.height, { + minFilter: NearestFilter, + magFilter: NearestFilter + }); + this.blurRenderTarget = this.ssrRenderTarget.clone(); + this.blurRenderTarget2 = this.ssrRenderTarget.clone(); + this.ssrMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSRShader.defines, { + MAX_STEP: Math.sqrt(this.width * this.width + this.height * this.height) + }), + uniforms: UniformsUtils.clone(SSRShader.uniforms), + vertexShader: SSRShader.vertexShader, + fragmentShader: SSRShader.fragmentShader, + blending: NoBlending + }); + this.ssrMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.ssrMaterial.uniforms["tNormal"].value = this.normalRenderTarget.texture; + this.ssrMaterial.defines.SELECTIVE = this.selective; + this.ssrMaterial.needsUpdate = true; + this.ssrMaterial.uniforms["tMetalness"].value = this.metalnessRenderTarget.texture; + this.ssrMaterial.uniforms["tDepth"].value = this.beautyRenderTarget.depthTexture; + this.ssrMaterial.uniforms["cameraNear"].value = this.camera.near; + this.ssrMaterial.uniforms["cameraFar"].value = this.camera.far; + this.ssrMaterial.uniforms["thickness"].value = this.thickness; + this.ssrMaterial.uniforms["resolution"].value.set(this.width, this.height); + this.ssrMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); + this.ssrMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.normalMaterial = new MeshNormalMaterial; + this.normalMaterial.blending = NoBlending; + this.metalnessOnMaterial = new MeshBasicMaterial({ + color: "white" + }); + this.metalnessOffMaterial = new MeshBasicMaterial({ + color: "black" + }); + this.blurMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSRBlurShader.defines), + uniforms: UniformsUtils.clone(SSRBlurShader.uniforms), + vertexShader: SSRBlurShader.vertexShader, + fragmentShader: SSRBlurShader.fragmentShader + }); + this.blurMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.blurMaterial.uniforms["resolution"].value.set(this.width, this.height); + this.blurMaterial2 = new ShaderMaterial({ + defines: Object.assign({}, SSRBlurShader.defines), + uniforms: UniformsUtils.clone(SSRBlurShader.uniforms), + vertexShader: SSRBlurShader.vertexShader, + fragmentShader: SSRBlurShader.fragmentShader + }); + this.blurMaterial2.uniforms["tDiffuse"].value = this.blurRenderTarget.texture; + this.blurMaterial2.uniforms["resolution"].value.set(this.width, this.height); + this.depthRenderMaterial = new ShaderMaterial({ + defines: Object.assign({}, SSRDepthShader.defines), + uniforms: UniformsUtils.clone(SSRDepthShader.uniforms), + vertexShader: SSRDepthShader.vertexShader, + fragmentShader: SSRDepthShader.fragmentShader, + blending: NoBlending + }); + this.depthRenderMaterial.uniforms["tDepth"].value = this.beautyRenderTarget.depthTexture; + this.depthRenderMaterial.uniforms["cameraNear"].value = this.camera.near; + this.depthRenderMaterial.uniforms["cameraFar"].value = this.camera.far; + this.copyMaterial = new ShaderMaterial({ + uniforms: UniformsUtils.clone(CopyShader.uniforms), + vertexShader: CopyShader.vertexShader, + fragmentShader: CopyShader.fragmentShader, + transparent: true, + depthTest: false, + depthWrite: false, + blendSrc: SrcAlphaFactor, + blendDst: OneMinusSrcAlphaFactor, + blendEquation: AddEquation, + blendSrcAlpha: SrcAlphaFactor, + blendDstAlpha: OneMinusSrcAlphaFactor, + blendEquationAlpha: AddEquation + }); + this.fsQuad = new FullScreenQuad(null); + this.originalClearColor = new Color; + } + dispose() { + this.beautyRenderTarget.dispose(); + this.prevRenderTarget.dispose(); + this.normalRenderTarget.dispose(); + this.metalnessRenderTarget.dispose(); + this.ssrRenderTarget.dispose(); + this.blurRenderTarget.dispose(); + this.blurRenderTarget2.dispose(); + this.normalMaterial.dispose(); + this.metalnessOnMaterial.dispose(); + this.metalnessOffMaterial.dispose(); + this.blurMaterial.dispose(); + this.blurMaterial2.dispose(); + this.copyMaterial.dispose(); + this.depthRenderMaterial.dispose(); + this.fsQuad.dispose(); + } + render(renderer2, writeBuffer) { + renderer2.setRenderTarget(this.beautyRenderTarget); + renderer2.clear(); + if (this.groundReflector) { + this.groundReflector.visible = false; + this.groundReflector.doRender(this.renderer, this.scene, this.camera); + this.groundReflector.visible = true; + } + renderer2.render(this.scene, this.camera); + if (this.groundReflector) + this.groundReflector.visible = false; + this.renderOverride(renderer2, this.normalMaterial, this.normalRenderTarget, 0, 0); + if (this.selective) { + this.renderMetalness(renderer2, this.metalnessOnMaterial, this.metalnessRenderTarget, 0, 0); + } + this.ssrMaterial.uniforms["opacity"].value = this.opacity; + this.ssrMaterial.uniforms["maxDistance"].value = this.maxDistance; + this.ssrMaterial.uniforms["thickness"].value = this.thickness; + this.renderPass(renderer2, this.ssrMaterial, this.ssrRenderTarget); + if (this.blur) { + this.renderPass(renderer2, this.blurMaterial, this.blurRenderTarget); + this.renderPass(renderer2, this.blurMaterial2, this.blurRenderTarget2); + } + switch (this.output) { + case SSRPass.OUTPUT.Default: + if (this.bouncing) { + this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.prevRenderTarget); + if (this.blur) + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture; + else + this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.copyMaterial.blending = NormalBlending; + this.renderPass(renderer2, this.copyMaterial, this.prevRenderTarget); + this.copyMaterial.uniforms["tDiffuse"].value = this.prevRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + } else { + this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + if (this.blur) + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture; + else + this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.copyMaterial.blending = NormalBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + } + break; + case SSRPass.OUTPUT.SSR: + if (this.blur) + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture; + else + this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + if (this.bouncing) { + if (this.blur) + this.copyMaterial.uniforms["tDiffuse"].value = this.blurRenderTarget2.texture; + else + this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.prevRenderTarget); + this.copyMaterial.uniforms["tDiffuse"].value = this.ssrRenderTarget.texture; + this.copyMaterial.blending = NormalBlending; + this.renderPass(renderer2, this.copyMaterial, this.prevRenderTarget); + } + break; + case SSRPass.OUTPUT.Beauty: + this.copyMaterial.uniforms["tDiffuse"].value = this.beautyRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case SSRPass.OUTPUT.Depth: + this.renderPass(renderer2, this.depthRenderMaterial, this.renderToScreen ? null : writeBuffer); + break; + case SSRPass.OUTPUT.Normal: + this.copyMaterial.uniforms["tDiffuse"].value = this.normalRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + case SSRPass.OUTPUT.Metalness: + this.copyMaterial.uniforms["tDiffuse"].value = this.metalnessRenderTarget.texture; + this.copyMaterial.blending = NoBlending; + this.renderPass(renderer2, this.copyMaterial, this.renderToScreen ? null : writeBuffer); + break; + default: + console.warn("THREE.SSRPass: Unknown output type."); + } + } + renderPass(renderer2, passMaterial, renderTarget, clearColor, clearAlpha) { + this.originalClearColor.copy(renderer2.getClearColor(this.tempColor)); + const originalClearAlpha = renderer2.getClearAlpha(this.tempColor); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.fsQuad.material = passMaterial; + this.fsQuad.render(renderer2); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderOverride(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + this.originalClearColor.copy(renderer2.getClearColor(this.tempColor)); + const originalClearAlpha = renderer2.getClearAlpha(this.tempColor); + const originalAutoClear = renderer2.autoClear; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.overrideMaterial = overrideMaterial; + renderer2.render(this.scene, this.camera); + this.scene.overrideMaterial = null; + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + } + renderMetalness(renderer2, overrideMaterial, renderTarget, clearColor, clearAlpha) { + this.originalClearColor.copy(renderer2.getClearColor(this.tempColor)); + const originalClearAlpha = renderer2.getClearAlpha(this.tempColor); + const originalAutoClear = renderer2.autoClear; + const originalBackground = this.scene.background; + const originalFog = this.scene.fog; + renderer2.setRenderTarget(renderTarget); + renderer2.autoClear = false; + this.scene.background = null; + this.scene.fog = null; + clearColor = overrideMaterial.clearColor || clearColor; + clearAlpha = overrideMaterial.clearAlpha || clearAlpha; + if (clearColor !== undefined && clearColor !== null) { + renderer2.setClearColor(clearColor); + renderer2.setClearAlpha(clearAlpha || 0); + renderer2.clear(); + } + this.scene.traverseVisible((child) => { + child._SSRPassBackupMaterial = child.material; + if (this._selects.includes(child)) { + child.material = this.metalnessOnMaterial; + } else { + child.material = this.metalnessOffMaterial; + } + }); + renderer2.render(this.scene, this.camera); + this.scene.traverseVisible((child) => { + child.material = child._SSRPassBackupMaterial; + }); + renderer2.autoClear = originalAutoClear; + renderer2.setClearColor(this.originalClearColor); + renderer2.setClearAlpha(originalClearAlpha); + this.scene.background = originalBackground; + this.scene.fog = originalFog; + } + setSize(width2, height2) { + this.width = width2; + this.height = height2; + this.ssrMaterial.defines.MAX_STEP = Math.sqrt(width2 * width2 + height2 * height2); + this.ssrMaterial.needsUpdate = true; + this.beautyRenderTarget.setSize(width2, height2); + this.prevRenderTarget.setSize(width2, height2); + this.ssrRenderTarget.setSize(width2, height2); + this.normalRenderTarget.setSize(width2, height2); + this.metalnessRenderTarget.setSize(width2, height2); + this.blurRenderTarget.setSize(width2, height2); + this.blurRenderTarget2.setSize(width2, height2); + this.ssrMaterial.uniforms["resolution"].value.set(width2, height2); + this.ssrMaterial.uniforms["cameraProjectionMatrix"].value.copy(this.camera.projectionMatrix); + this.ssrMaterial.uniforms["cameraInverseProjectionMatrix"].value.copy(this.camera.projectionMatrixInverse); + this.blurMaterial.uniforms["resolution"].value.set(width2, height2); + this.blurMaterial2.uniforms["resolution"].value.set(width2, height2); + } +} +SSRPass.OUTPUT = { + Default: 0, + SSR: 1, + Beauty: 3, + Depth: 4, + Normal: 5, + Metalness: 7 +}; +// node_modules/three/examples/jsm/shaders/LuminosityHighPassShader.js +var LuminosityHighPassShader = { + name: "LuminosityHighPassShader", + shaderID: "luminosityHighPass", + uniforms: { + tDiffuse: { value: null }, + luminosityThreshold: { value: 1 }, + smoothWidth: { value: 1 }, + defaultColor: { value: new Color(0) }, + defaultOpacity: { value: 0 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform vec3 defaultColor; + uniform float defaultOpacity; + uniform float luminosityThreshold; + uniform float smoothWidth; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + + float v = luminance( texel.xyz ); + + vec4 outputColor = vec4( defaultColor.rgb, defaultOpacity ); + + float alpha = smoothstep( luminosityThreshold, luminosityThreshold + smoothWidth, v ); + + gl_FragColor = mix( outputColor, texel, alpha ); + + }` +}; + +// node_modules/three/examples/jsm/postprocessing/UnrealBloomPass.js +class UnrealBloomPass extends Pass { + constructor(resolution, strength, radius, threshold) { + super(); + this.strength = strength !== undefined ? strength : 1; + this.radius = radius; + this.threshold = threshold; + this.resolution = resolution !== undefined ? new Vector2(resolution.x, resolution.y) : new Vector2(256, 256); + this.clearColor = new Color(0, 0, 0); + this.renderTargetsHorizontal = []; + this.renderTargetsVertical = []; + this.nMips = 5; + let resx = Math.round(this.resolution.x / 2); + let resy = Math.round(this.resolution.y / 2); + this.renderTargetBright = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + this.renderTargetBright.texture.name = "UnrealBloomPass.bright"; + this.renderTargetBright.texture.generateMipmaps = false; + for (let i = 0;i < this.nMips; i++) { + const renderTargetHorizontal = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + renderTargetHorizontal.texture.name = "UnrealBloomPass.h" + i; + renderTargetHorizontal.texture.generateMipmaps = false; + this.renderTargetsHorizontal.push(renderTargetHorizontal); + const renderTargetVertical = new WebGLRenderTarget(resx, resy, { type: HalfFloatType }); + renderTargetVertical.texture.name = "UnrealBloomPass.v" + i; + renderTargetVertical.texture.generateMipmaps = false; + this.renderTargetsVertical.push(renderTargetVertical); + resx = Math.round(resx / 2); + resy = Math.round(resy / 2); + } + const highPassShader = LuminosityHighPassShader; + this.highPassUniforms = UniformsUtils.clone(highPassShader.uniforms); + this.highPassUniforms["luminosityThreshold"].value = threshold; + this.highPassUniforms["smoothWidth"].value = 0.01; + this.materialHighPassFilter = new ShaderMaterial({ + uniforms: this.highPassUniforms, + vertexShader: highPassShader.vertexShader, + fragmentShader: highPassShader.fragmentShader + }); + this.separableBlurMaterials = []; + const kernelSizeArray = [3, 5, 7, 9, 11]; + resx = Math.round(this.resolution.x / 2); + resy = Math.round(this.resolution.y / 2); + for (let i = 0;i < this.nMips; i++) { + this.separableBlurMaterials.push(this.getSeparableBlurMaterial(kernelSizeArray[i])); + this.separableBlurMaterials[i].uniforms["invSize"].value = new Vector2(1 / resx, 1 / resy); + resx = Math.round(resx / 2); + resy = Math.round(resy / 2); + } + this.compositeMaterial = this.getCompositeMaterial(this.nMips); + this.compositeMaterial.uniforms["blurTexture1"].value = this.renderTargetsVertical[0].texture; + this.compositeMaterial.uniforms["blurTexture2"].value = this.renderTargetsVertical[1].texture; + this.compositeMaterial.uniforms["blurTexture3"].value = this.renderTargetsVertical[2].texture; + this.compositeMaterial.uniforms["blurTexture4"].value = this.renderTargetsVertical[3].texture; + this.compositeMaterial.uniforms["blurTexture5"].value = this.renderTargetsVertical[4].texture; + this.compositeMaterial.uniforms["bloomStrength"].value = strength; + this.compositeMaterial.uniforms["bloomRadius"].value = 0.1; + const bloomFactors = [1, 0.8, 0.6, 0.4, 0.2]; + this.compositeMaterial.uniforms["bloomFactors"].value = bloomFactors; + this.bloomTintColors = [new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, 1, 1)]; + this.compositeMaterial.uniforms["bloomTintColors"].value = this.bloomTintColors; + const copyShader = CopyShader; + this.copyUniforms = UniformsUtils.clone(copyShader.uniforms); + this.blendMaterial = new ShaderMaterial({ + uniforms: this.copyUniforms, + vertexShader: copyShader.vertexShader, + fragmentShader: copyShader.fragmentShader, + blending: AdditiveBlending, + depthTest: false, + depthWrite: false, + transparent: true + }); + this.enabled = true; + this.needsSwap = false; + this._oldClearColor = new Color; + this.oldClearAlpha = 1; + this.basic = new MeshBasicMaterial; + this.fsQuad = new FullScreenQuad(null); + } + dispose() { + for (let i = 0;i < this.renderTargetsHorizontal.length; i++) { + this.renderTargetsHorizontal[i].dispose(); + } + for (let i = 0;i < this.renderTargetsVertical.length; i++) { + this.renderTargetsVertical[i].dispose(); + } + this.renderTargetBright.dispose(); + for (let i = 0;i < this.separableBlurMaterials.length; i++) { + this.separableBlurMaterials[i].dispose(); + } + this.compositeMaterial.dispose(); + this.blendMaterial.dispose(); + this.basic.dispose(); + this.fsQuad.dispose(); + } + setSize(width2, height2) { + let resx = Math.round(width2 / 2); + let resy = Math.round(height2 / 2); + this.renderTargetBright.setSize(resx, resy); + for (let i = 0;i < this.nMips; i++) { + this.renderTargetsHorizontal[i].setSize(resx, resy); + this.renderTargetsVertical[i].setSize(resx, resy); + this.separableBlurMaterials[i].uniforms["invSize"].value = new Vector2(1 / resx, 1 / resy); + resx = Math.round(resx / 2); + resy = Math.round(resy / 2); + } + } + render(renderer2, writeBuffer, readBuffer, deltaTime, maskActive) { + renderer2.getClearColor(this._oldClearColor); + this.oldClearAlpha = renderer2.getClearAlpha(); + const oldAutoClear = renderer2.autoClear; + renderer2.autoClear = false; + renderer2.setClearColor(this.clearColor, 0); + if (maskActive) + renderer2.state.buffers.stencil.setTest(false); + if (this.renderToScreen) { + this.fsQuad.material = this.basic; + this.basic.map = readBuffer.texture; + renderer2.setRenderTarget(null); + renderer2.clear(); + this.fsQuad.render(renderer2); + } + this.highPassUniforms["tDiffuse"].value = readBuffer.texture; + this.highPassUniforms["luminosityThreshold"].value = this.threshold; + this.fsQuad.material = this.materialHighPassFilter; + renderer2.setRenderTarget(this.renderTargetBright); + renderer2.clear(); + this.fsQuad.render(renderer2); + let inputRenderTarget = this.renderTargetBright; + for (let i = 0;i < this.nMips; i++) { + this.fsQuad.material = this.separableBlurMaterials[i]; + this.separableBlurMaterials[i].uniforms["colorTexture"].value = inputRenderTarget.texture; + this.separableBlurMaterials[i].uniforms["direction"].value = UnrealBloomPass.BlurDirectionX; + renderer2.setRenderTarget(this.renderTargetsHorizontal[i]); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.separableBlurMaterials[i].uniforms["colorTexture"].value = this.renderTargetsHorizontal[i].texture; + this.separableBlurMaterials[i].uniforms["direction"].value = UnrealBloomPass.BlurDirectionY; + renderer2.setRenderTarget(this.renderTargetsVertical[i]); + renderer2.clear(); + this.fsQuad.render(renderer2); + inputRenderTarget = this.renderTargetsVertical[i]; + } + this.fsQuad.material = this.compositeMaterial; + this.compositeMaterial.uniforms["bloomStrength"].value = this.strength; + this.compositeMaterial.uniforms["bloomRadius"].value = this.radius; + this.compositeMaterial.uniforms["bloomTintColors"].value = this.bloomTintColors; + renderer2.setRenderTarget(this.renderTargetsHorizontal[0]); + renderer2.clear(); + this.fsQuad.render(renderer2); + this.fsQuad.material = this.blendMaterial; + this.copyUniforms["tDiffuse"].value = this.renderTargetsHorizontal[0].texture; + if (maskActive) + renderer2.state.buffers.stencil.setTest(true); + if (this.renderToScreen) { + renderer2.setRenderTarget(null); + this.fsQuad.render(renderer2); + } else { + renderer2.setRenderTarget(readBuffer); + this.fsQuad.render(renderer2); + } + renderer2.setClearColor(this._oldClearColor, this.oldClearAlpha); + renderer2.autoClear = oldAutoClear; + } + getSeparableBlurMaterial(kernelRadius) { + const coefficients = []; + for (let i = 0;i < kernelRadius; i++) { + coefficients.push(0.39894 * Math.exp(-0.5 * i * i / (kernelRadius * kernelRadius)) / kernelRadius); + } + return new ShaderMaterial({ + defines: { + KERNEL_RADIUS: kernelRadius + }, + uniforms: { + colorTexture: { value: null }, + invSize: { value: new Vector2(0.5, 0.5) }, + direction: { value: new Vector2(0.5, 0.5) }, + gaussianCoefficients: { value: coefficients } + }, + vertexShader: `varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `#include + varying vec2 vUv; + uniform sampler2D colorTexture; + uniform vec2 invSize; + uniform vec2 direction; + uniform float gaussianCoefficients[KERNEL_RADIUS]; + + void main() { + float weightSum = gaussianCoefficients[0]; + vec3 diffuseSum = texture2D( colorTexture, vUv ).rgb * weightSum; + for( int i = 1; i < KERNEL_RADIUS; i ++ ) { + float x = float(i); + float w = gaussianCoefficients[i]; + vec2 uvOffset = direction * invSize * x; + vec3 sample1 = texture2D( colorTexture, vUv + uvOffset ).rgb; + vec3 sample2 = texture2D( colorTexture, vUv - uvOffset ).rgb; + diffuseSum += (sample1 + sample2) * w; + weightSum += 2.0 * w; + } + gl_FragColor = vec4(diffuseSum/weightSum, 1.0); + }` + }); + } + getCompositeMaterial(nMips) { + return new ShaderMaterial({ + defines: { + NUM_MIPS: nMips + }, + uniforms: { + blurTexture1: { value: null }, + blurTexture2: { value: null }, + blurTexture3: { value: null }, + blurTexture4: { value: null }, + blurTexture5: { value: null }, + bloomStrength: { value: 1 }, + bloomFactors: { value: null }, + bloomTintColors: { value: null }, + bloomRadius: { value: 0 } + }, + vertexShader: `varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + }`, + fragmentShader: `varying vec2 vUv; + uniform sampler2D blurTexture1; + uniform sampler2D blurTexture2; + uniform sampler2D blurTexture3; + uniform sampler2D blurTexture4; + uniform sampler2D blurTexture5; + uniform float bloomStrength; + uniform float bloomRadius; + uniform float bloomFactors[NUM_MIPS]; + uniform vec3 bloomTintColors[NUM_MIPS]; + + float lerpBloomFactor(const in float factor) { + float mirrorFactor = 1.2 - factor; + return mix(factor, mirrorFactor, bloomRadius); + } + + void main() { + gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) + + lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) + + lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) + + lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) + + lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) ); + }` + }); + } +} +UnrealBloomPass.BlurDirectionX = new Vector2(1, 0); +UnrealBloomPass.BlurDirectionY = new Vector2(0, 1); +// node_modules/three/examples/jsm/renderers/CSS2DRenderer.js +var _vector8 = new Vector3; +var _viewMatrix = new Matrix4; +var _viewProjectionMatrix = new Matrix4; +var _a2 = new Vector3; +var _b2 = new Vector3; +// node_modules/three/examples/jsm/renderers/CSS3DRenderer.js +var _position2 = new Vector3; +var _quaternion4 = new Quaternion; +var _scale4 = new Vector3; +var _matrix5 = new Matrix4; +var _matrix22 = new Matrix4; +// node_modules/three/examples/jsm/shaders/BokehShader2.js +var BokehShader2 = { + name: "BokehShader", + uniforms: { + textureWidth: { value: 1 }, + textureHeight: { value: 1 }, + focalDepth: { value: 1 }, + focalLength: { value: 24 }, + fstop: { value: 0.9 }, + tColor: { value: null }, + tDepth: { value: null }, + maxblur: { value: 1 }, + showFocus: { value: 0 }, + manualdof: { value: 0 }, + vignetting: { value: 0 }, + depthblur: { value: 0 }, + threshold: { value: 0.5 }, + gain: { value: 2 }, + bias: { value: 0.5 }, + fringe: { value: 0.7 }, + znear: { value: 0.1 }, + zfar: { value: 100 }, + noise: { value: 1 }, + dithering: { value: 0.0001 }, + pentagon: { value: 0 }, + shaderFocus: { value: 1 }, + focusCoords: { value: new Vector2 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + #include + + varying vec2 vUv; + + uniform sampler2D tColor; + uniform sampler2D tDepth; + uniform float textureWidth; + uniform float textureHeight; + + uniform float focalDepth; //focal distance value in meters, but you may use autofocus option below + uniform float focalLength; //focal length in mm + uniform float fstop; //f-stop value + uniform bool showFocus; //show debug focus point and focal range (red = focal point, green = focal range) + + /* + make sure that these two values are the same for your camera, otherwise distances will be wrong. + */ + + uniform float znear; // camera clipping start + uniform float zfar; // camera clipping end + + //------------------------------------------ + //user variables + + const int samples = SAMPLES; //samples on the first ring + const int rings = RINGS; //ring count + + const int maxringsamples = rings * samples; + + uniform bool manualdof; // manual dof calculation + float ndofstart = 1.0; // near dof blur start + float ndofdist = 2.0; // near dof blur falloff distance + float fdofstart = 1.0; // far dof blur start + float fdofdist = 3.0; // far dof blur falloff distance + + float CoC = 0.03; //circle of confusion size in mm (35mm film = 0.03mm) + + uniform bool vignetting; // use optical lens vignetting + + float vignout = 1.3; // vignetting outer border + float vignin = 0.0; // vignetting inner border + float vignfade = 22.0; // f-stops till vignette fades + + uniform bool shaderFocus; + // disable if you use external focalDepth value + + uniform vec2 focusCoords; + // autofocus point on screen (0.0,0.0 - left lower corner, 1.0,1.0 - upper right) + // if center of screen use vec2(0.5, 0.5); + + uniform float maxblur; + //clamp value of max blur (0.0 = no blur, 1.0 default) + + uniform float threshold; // highlight threshold; + uniform float gain; // highlight gain; + + uniform float bias; // bokeh edge bias + uniform float fringe; // bokeh chromatic aberration / fringing + + uniform bool noise; //use noise instead of pattern for sample dithering + + uniform float dithering; + + uniform bool depthblur; // blur the depth buffer + float dbsize = 1.25; // depth blur size + + /* + next part is experimental + not looking good with small sample and ring count + looks okay starting from samples = 4, rings = 4 + */ + + uniform bool pentagon; //use pentagon as bokeh shape? + float feather = 0.4; //pentagon shape feather + + //------------------------------------------ + + float penta(vec2 coords) { + //pentagonal shape + float scale = float(rings) - 1.3; + vec4 HS0 = vec4( 1.0, 0.0, 0.0, 1.0); + vec4 HS1 = vec4( 0.309016994, 0.951056516, 0.0, 1.0); + vec4 HS2 = vec4(-0.809016994, 0.587785252, 0.0, 1.0); + vec4 HS3 = vec4(-0.809016994,-0.587785252, 0.0, 1.0); + vec4 HS4 = vec4( 0.309016994,-0.951056516, 0.0, 1.0); + vec4 HS5 = vec4( 0.0 ,0.0 , 1.0, 1.0); + + vec4 one = vec4( 1.0 ); + + vec4 P = vec4((coords),vec2(scale, scale)); + + vec4 dist = vec4(0.0); + float inorout = -4.0; + + dist.x = dot( P, HS0 ); + dist.y = dot( P, HS1 ); + dist.z = dot( P, HS2 ); + dist.w = dot( P, HS3 ); + + dist = smoothstep( -feather, feather, dist ); + + inorout += dot( dist, one ); + + dist.x = dot( P, HS4 ); + dist.y = HS5.w - abs( P.z ); + + dist = smoothstep( -feather, feather, dist ); + inorout += dist.x; + + return clamp( inorout, 0.0, 1.0 ); + } + + float bdepth(vec2 coords) { + // Depth buffer blur + float d = 0.0; + float kernel[9]; + vec2 offset[9]; + + vec2 wh = vec2(1.0/textureWidth,1.0/textureHeight) * dbsize; + + offset[0] = vec2(-wh.x,-wh.y); + offset[1] = vec2( 0.0, -wh.y); + offset[2] = vec2( wh.x -wh.y); + + offset[3] = vec2(-wh.x, 0.0); + offset[4] = vec2( 0.0, 0.0); + offset[5] = vec2( wh.x, 0.0); + + offset[6] = vec2(-wh.x, wh.y); + offset[7] = vec2( 0.0, wh.y); + offset[8] = vec2( wh.x, wh.y); + + kernel[0] = 1.0/16.0; kernel[1] = 2.0/16.0; kernel[2] = 1.0/16.0; + kernel[3] = 2.0/16.0; kernel[4] = 4.0/16.0; kernel[5] = 2.0/16.0; + kernel[6] = 1.0/16.0; kernel[7] = 2.0/16.0; kernel[8] = 1.0/16.0; + + + for( int i=0; i<9; i++ ) { + float tmp = texture2D(tDepth, coords + offset[i]).r; + d += tmp * kernel[i]; + } + + return d; + } + + + vec3 color(vec2 coords,float blur) { + //processing the sample + + vec3 col = vec3(0.0); + vec2 texel = vec2(1.0/textureWidth,1.0/textureHeight); + + col.r = texture2D(tColor,coords + vec2(0.0,1.0)*texel*fringe*blur).r; + col.g = texture2D(tColor,coords + vec2(-0.866,-0.5)*texel*fringe*blur).g; + col.b = texture2D(tColor,coords + vec2(0.866,-0.5)*texel*fringe*blur).b; + + vec3 lumcoeff = vec3(0.299,0.587,0.114); + float lum = dot(col.rgb, lumcoeff); + float thresh = max((lum-threshold)*gain, 0.0); + return col+mix(vec3(0.0),col,thresh*blur); + } + + vec3 debugFocus(vec3 col, float blur, float depth) { + float edge = 0.002*depth; //distance based edge smoothing + float m = clamp(smoothstep(0.0,edge,blur),0.0,1.0); + float e = clamp(smoothstep(1.0-edge,1.0,blur),0.0,1.0); + + col = mix(col,vec3(1.0,0.5,0.0),(1.0-m)*0.6); + col = mix(col,vec3(0.0,0.5,1.0),((1.0-e)-(1.0-m))*0.2); + + return col; + } + + float linearize(float depth) { + return -zfar * znear / (depth * (zfar - znear) - zfar); + } + + float vignette() { + float dist = distance(vUv.xy, vec2(0.5,0.5)); + dist = smoothstep(vignout+(fstop/vignfade), vignin+(fstop/vignfade), dist); + return clamp(dist,0.0,1.0); + } + + float gather(float i, float j, int ringsamples, inout vec3 col, float w, float h, float blur) { + float rings2 = float(rings); + float step = PI*2.0 / float(ringsamples); + float pw = cos(j*step)*i; + float ph = sin(j*step)*i; + float p = 1.0; + if (pentagon) { + p = penta(vec2(pw,ph)); + } + col += color(vUv.xy + vec2(pw*w,ph*h), blur) * mix(1.0, i/rings2, bias) * p; + return 1.0 * mix(1.0, i /rings2, bias) * p; + } + + void main() { + //scene depth calculation + + float depth = linearize(texture2D(tDepth,vUv.xy).x); + + // Blur depth? + if ( depthblur ) { + depth = linearize(bdepth(vUv.xy)); + } + + //focal plane calculation + + float fDepth = focalDepth; + + if (shaderFocus) { + + fDepth = linearize(texture2D(tDepth,focusCoords).x); + + } + + // dof blur factor calculation + + float blur = 0.0; + + if (manualdof) { + float a = depth-fDepth; // Focal plane + float b = (a-fdofstart)/fdofdist; // Far DoF + float c = (-a-ndofstart)/ndofdist; // Near Dof + blur = (a>0.0) ? b : c; + } else { + float f = focalLength; // focal length in mm + float d = fDepth*1000.0; // focal plane in mm + float o = depth*1000.0; // depth in mm + + float a = (o*f)/(o-f); + float b = (d*f)/(d-f); + float c = (d-f)/(d*fstop*CoC); + + blur = abs(a-b)*c; + } + + blur = clamp(blur,0.0,1.0); + + // calculation of pattern for dithering + + vec2 noise = vec2(rand(vUv.xy), rand( vUv.xy + vec2( 0.4, 0.6 ) ) )*dithering*blur; + + // getting blur x and y step factor + + float w = (1.0/textureWidth)*blur*maxblur+noise.x; + float h = (1.0/textureHeight)*blur*maxblur+noise.y; + + // calculation of final color + + vec3 col = vec3(0.0); + + if(blur < 0.05) { + //some optimization thingy + col = texture2D(tColor, vUv.xy).rgb; + } else { + col = texture2D(tColor, vUv.xy).rgb; + float s = 1.0; + int ringsamples; + + for (int i = 1; i <= rings; i++) { + /*unboxstart*/ + ringsamples = i * samples; + + for (int j = 0 ; j < maxringsamples ; j++) { + if (j >= ringsamples) break; + s += gather(float(i), float(j), ringsamples, col, w, h, blur); + } + /*unboxend*/ + } + + col /= s; //divide by sample count + } + + if (showFocus) { + col = debugFocus(col, blur, depth); + } + + if (vignetting) { + col *= vignette(); + } + + gl_FragColor.rgb = col; + gl_FragColor.a = 1.0; + + #include + #include + }` +}; +// node_modules/three/examples/jsm/shaders/ColorCorrectionShader.js +var ColorCorrectionShader = { + name: "ColorCorrectionShader", + uniforms: { + tDiffuse: { value: null }, + powRGB: { value: new Vector3(2, 2, 2) }, + mulRGB: { value: new Vector3(1, 1, 1) }, + addRGB: { value: new Vector3(0, 0, 0) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform vec3 powRGB; + uniform vec3 mulRGB; + uniform vec3 addRGB; + + varying vec2 vUv; + + void main() { + + gl_FragColor = texture2D( tDiffuse, vUv ); + gl_FragColor.rgb = mulRGB * pow( ( gl_FragColor.rgb + addRGB ), powRGB ); + + }` +}; +// node_modules/three/examples/jsm/shaders/ColorifyShader.js +var ColorifyShader = { + name: "ColorifyShader", + uniforms: { + tDiffuse: { value: null }, + color: { value: new Color(16777215) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform vec3 color; + uniform sampler2D tDiffuse; + + varying vec2 vUv; + + void main() { + + vec4 texel = texture2D( tDiffuse, vUv ); + + float v = luminance( texel.xyz ); + + gl_FragColor = vec4( v * color, texel.w ); + + }` +}; +// node_modules/three/examples/jsm/shaders/FXAAShader.js +var FXAAShader = { + name: "FXAAShader", + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2(1 / 1024, 1 / 512) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + // FXAA algorithm from NVIDIA, C# implementation by Jasper Flick, GLSL port by Dave Hoskins + // http://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf + // https://catlikecoding.com/unity/tutorials/advanced-rendering/fxaa/ + + uniform sampler2D tDiffuse; + uniform vec2 resolution; + varying vec2 vUv; + + #define EDGE_STEP_COUNT 6 + #define EDGE_GUESS 8.0 + #define EDGE_STEPS 1.0, 1.5, 2.0, 2.0, 2.0, 4.0 + const float edgeSteps[EDGE_STEP_COUNT] = float[EDGE_STEP_COUNT]( EDGE_STEPS ); + + float _ContrastThreshold = 0.0312; + float _RelativeThreshold = 0.063; + float _SubpixelBlending = 1.0; + + vec4 Sample( sampler2D tex2D, vec2 uv ) { + + return texture( tex2D, uv ); + + } + + float SampleLuminance( sampler2D tex2D, vec2 uv ) { + + return dot( Sample( tex2D, uv ).rgb, vec3( 0.3, 0.59, 0.11 ) ); + + } + + float SampleLuminance( sampler2D tex2D, vec2 texSize, vec2 uv, float uOffset, float vOffset ) { + + uv += texSize * vec2(uOffset, vOffset); + return SampleLuminance(tex2D, uv); + + } + + struct LuminanceData { + + float m, n, e, s, w; + float ne, nw, se, sw; + float highest, lowest, contrast; + + }; + + LuminanceData SampleLuminanceNeighborhood( sampler2D tex2D, vec2 texSize, vec2 uv ) { + + LuminanceData l; + l.m = SampleLuminance( tex2D, uv ); + l.n = SampleLuminance( tex2D, texSize, uv, 0.0, 1.0 ); + l.e = SampleLuminance( tex2D, texSize, uv, 1.0, 0.0 ); + l.s = SampleLuminance( tex2D, texSize, uv, 0.0, -1.0 ); + l.w = SampleLuminance( tex2D, texSize, uv, -1.0, 0.0 ); + + l.ne = SampleLuminance( tex2D, texSize, uv, 1.0, 1.0 ); + l.nw = SampleLuminance( tex2D, texSize, uv, -1.0, 1.0 ); + l.se = SampleLuminance( tex2D, texSize, uv, 1.0, -1.0 ); + l.sw = SampleLuminance( tex2D, texSize, uv, -1.0, -1.0 ); + + l.highest = max( max( max( max( l.n, l.e ), l.s ), l.w ), l.m ); + l.lowest = min( min( min( min( l.n, l.e ), l.s ), l.w ), l.m ); + l.contrast = l.highest - l.lowest; + return l; + + } + + bool ShouldSkipPixel( LuminanceData l ) { + + float threshold = max( _ContrastThreshold, _RelativeThreshold * l.highest ); + return l.contrast < threshold; + + } + + float DeterminePixelBlendFactor( LuminanceData l ) { + + float f = 2.0 * ( l.n + l.e + l.s + l.w ); + f += l.ne + l.nw + l.se + l.sw; + f *= 1.0 / 12.0; + f = abs( f - l.m ); + f = clamp( f / l.contrast, 0.0, 1.0 ); + + float blendFactor = smoothstep( 0.0, 1.0, f ); + return blendFactor * blendFactor * _SubpixelBlending; + + } + + struct EdgeData { + + bool isHorizontal; + float pixelStep; + float oppositeLuminance, gradient; + + }; + + EdgeData DetermineEdge( vec2 texSize, LuminanceData l ) { + + EdgeData e; + float horizontal = + abs( l.n + l.s - 2.0 * l.m ) * 2.0 + + abs( l.ne + l.se - 2.0 * l.e ) + + abs( l.nw + l.sw - 2.0 * l.w ); + float vertical = + abs( l.e + l.w - 2.0 * l.m ) * 2.0 + + abs( l.ne + l.nw - 2.0 * l.n ) + + abs( l.se + l.sw - 2.0 * l.s ); + e.isHorizontal = horizontal >= vertical; + + float pLuminance = e.isHorizontal ? l.n : l.e; + float nLuminance = e.isHorizontal ? l.s : l.w; + float pGradient = abs( pLuminance - l.m ); + float nGradient = abs( nLuminance - l.m ); + + e.pixelStep = e.isHorizontal ? texSize.y : texSize.x; + + if (pGradient < nGradient) { + + e.pixelStep = -e.pixelStep; + e.oppositeLuminance = nLuminance; + e.gradient = nGradient; + + } else { + + e.oppositeLuminance = pLuminance; + e.gradient = pGradient; + + } + + return e; + + } + + float DetermineEdgeBlendFactor( sampler2D tex2D, vec2 texSize, LuminanceData l, EdgeData e, vec2 uv ) { + + vec2 uvEdge = uv; + vec2 edgeStep; + if (e.isHorizontal) { + + uvEdge.y += e.pixelStep * 0.5; + edgeStep = vec2( texSize.x, 0.0 ); + + } else { + + uvEdge.x += e.pixelStep * 0.5; + edgeStep = vec2( 0.0, texSize.y ); + + } + + float edgeLuminance = ( l.m + e.oppositeLuminance ) * 0.5; + float gradientThreshold = e.gradient * 0.25; + + vec2 puv = uvEdge + edgeStep * edgeSteps[0]; + float pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; + bool pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; + + for ( int i = 1; i < EDGE_STEP_COUNT && !pAtEnd; i++ ) { + + puv += edgeStep * edgeSteps[i]; + pLuminanceDelta = SampleLuminance( tex2D, puv ) - edgeLuminance; + pAtEnd = abs( pLuminanceDelta ) >= gradientThreshold; + + } + + if ( !pAtEnd ) { + + puv += edgeStep * EDGE_GUESS; + + } + + vec2 nuv = uvEdge - edgeStep * edgeSteps[0]; + float nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; + bool nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; + + for ( int i = 1; i < EDGE_STEP_COUNT && !nAtEnd; i++ ) { + + nuv -= edgeStep * edgeSteps[i]; + nLuminanceDelta = SampleLuminance( tex2D, nuv ) - edgeLuminance; + nAtEnd = abs( nLuminanceDelta ) >= gradientThreshold; + + } + + if ( !nAtEnd ) { + + nuv -= edgeStep * EDGE_GUESS; + + } + + float pDistance, nDistance; + if ( e.isHorizontal ) { + + pDistance = puv.x - uv.x; + nDistance = uv.x - nuv.x; + + } else { + + pDistance = puv.y - uv.y; + nDistance = uv.y - nuv.y; + + } + + float shortestDistance; + bool deltaSign; + if ( pDistance <= nDistance ) { + + shortestDistance = pDistance; + deltaSign = pLuminanceDelta >= 0.0; + + } else { + + shortestDistance = nDistance; + deltaSign = nLuminanceDelta >= 0.0; + + } + + if ( deltaSign == ( l.m - edgeLuminance >= 0.0 ) ) { + + return 0.0; + + } + + return 0.5 - shortestDistance / ( pDistance + nDistance ); + + } + + vec4 ApplyFXAA( sampler2D tex2D, vec2 texSize, vec2 uv ) { + + LuminanceData luminance = SampleLuminanceNeighborhood( tex2D, texSize, uv ); + if ( ShouldSkipPixel( luminance ) ) { + + return Sample( tex2D, uv ); + + } + + float pixelBlend = DeterminePixelBlendFactor( luminance ); + EdgeData edge = DetermineEdge( texSize, luminance ); + float edgeBlend = DetermineEdgeBlendFactor( tex2D, texSize, luminance, edge, uv ); + float finalBlend = max( pixelBlend, edgeBlend ); + + if (edge.isHorizontal) { + + uv.y += edge.pixelStep * finalBlend; + + } else { + + uv.x += edge.pixelStep * finalBlend; + + } + + return Sample( tex2D, uv ); + + } + + void main() { + + gl_FragColor = ApplyFXAA( tDiffuse, resolution.xy, vUv ); + + }` +}; +// node_modules/three/examples/jsm/shaders/FreiChenShader.js +var FreiChenShader = { + name: "FreiChenShader", + uniforms: { + tDiffuse: { value: null }, + aspect: { value: new Vector2(512, 512) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + varying vec2 vUv; + + uniform vec2 aspect; + + vec2 texel = vec2( 1.0 / aspect.x, 1.0 / aspect.y ); + + + mat3 G[9]; + + // hard coded matrix values!!!! as suggested in https://github.com/neilmendoza/ofxPostProcessing/blob/master/src/EdgePass.cpp#L45 + + const mat3 g0 = mat3( 0.3535533845424652, 0, -0.3535533845424652, 0.5, 0, -0.5, 0.3535533845424652, 0, -0.3535533845424652 ); + const mat3 g1 = mat3( 0.3535533845424652, 0.5, 0.3535533845424652, 0, 0, 0, -0.3535533845424652, -0.5, -0.3535533845424652 ); + const mat3 g2 = mat3( 0, 0.3535533845424652, -0.5, -0.3535533845424652, 0, 0.3535533845424652, 0.5, -0.3535533845424652, 0 ); + const mat3 g3 = mat3( 0.5, -0.3535533845424652, 0, -0.3535533845424652, 0, 0.3535533845424652, 0, 0.3535533845424652, -0.5 ); + const mat3 g4 = mat3( 0, -0.5, 0, 0.5, 0, 0.5, 0, -0.5, 0 ); + const mat3 g5 = mat3( -0.5, 0, 0.5, 0, 0, 0, 0.5, 0, -0.5 ); + const mat3 g6 = mat3( 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.6666666865348816, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204 ); + const mat3 g7 = mat3( -0.3333333432674408, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, 0.6666666865348816, 0.1666666716337204, -0.3333333432674408, 0.1666666716337204, -0.3333333432674408 ); + const mat3 g8 = mat3( 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408, 0.3333333432674408 ); + + void main(void) + { + + G[0] = g0, + G[1] = g1, + G[2] = g2, + G[3] = g3, + G[4] = g4, + G[5] = g5, + G[6] = g6, + G[7] = g7, + G[8] = g8; + + mat3 I; + float cnv[9]; + vec3 sample; + + /* fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */ + for (float i=0.0; i<3.0; i++) { + for (float j=0.0; j<3.0; j++) { + sample = texture2D(tDiffuse, vUv + texel * vec2(i-1.0,j-1.0) ).rgb; + I[int(i)][int(j)] = length(sample); + } + } + + /* calculate the convolution values for all the masks */ + for (int i=0; i<9; i++) { + float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]); + cnv[i] = dp3 * dp3; + } + + float M = (cnv[0] + cnv[1]) + (cnv[2] + cnv[3]); + float S = (cnv[4] + cnv[5]) + (cnv[6] + cnv[7]) + (cnv[8] + M); + + gl_FragColor = vec4(vec3(sqrt(M/S)), 1.0); + }` +}; +// node_modules/three/examples/jsm/shaders/GodRaysShader.js +var GodRaysGenerateShader = { + name: "GodRaysGenerateShader", + uniforms: { + tInput: { + value: null + }, + fStepSize: { + value: 1 + }, + vSunPositionScreenSpace: { + value: new Vector3 + } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + #define TAPS_PER_PASS 6.0 + + varying vec2 vUv; + + uniform sampler2D tInput; + + uniform vec3 vSunPositionScreenSpace; + uniform float fStepSize; // filter step size + + void main() { + + // delta from current pixel to "sun" position + + vec2 delta = vSunPositionScreenSpace.xy - vUv; + float dist = length( delta ); + + // Step vector (uv space) + + vec2 stepv = fStepSize * delta / dist; + + // Number of iterations between pixel and sun + + float iters = dist/fStepSize; + + vec2 uv = vUv.xy; + float col = 0.0; + + // This breaks ANGLE in Chrome 22 + // - see http://code.google.com/p/chromium/issues/detail?id=153105 + + /* + // Unrolling didn't do much on my hardware (ATI Mobility Radeon 3450), + // so i've just left the loop + + "for ( float i = 0.0; i < TAPS_PER_PASS; i += 1.0 ) {", + + // Accumulate samples, making sure we don't walk past the light source. + + // The check for uv.y < 1 would not be necessary with "border" UV wrap + // mode, with a black border color. I don't think this is currently + // exposed by three.js. As a result there might be artifacts when the + // sun is to the left, right or bottom of screen as these cases are + // not specifically handled. + + " col += ( i <= iters && uv.y < 1.0 ? texture2D( tInput, uv ).r : 0.0 );", + " uv += stepv;", + + "}", + */ + + // Unrolling loop manually makes it work in ANGLE + + float f = min( 1.0, max( vSunPositionScreenSpace.z / 1000.0, 0.0 ) ); // used to fade out godrays + + if ( 0.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 1.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 2.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 3.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 4.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + if ( 5.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv ).r * f; + uv += stepv; + + // Should technically be dividing by 'iters but 'TAPS_PER_PASS' smooths out + // objectionable artifacts, in particular near the sun position. The side + // effect is that the result is darker than it should be around the sun, as + // TAPS_PER_PASS is greater than the number of samples actually accumulated. + // When the result is inverted (in the shader 'godrays_combine this produces + // a slight bright spot at the position of the sun, even when it is occluded. + + gl_FragColor = vec4( col/TAPS_PER_PASS ); + gl_FragColor.a = 1.0; + + }` +}; +var GodRaysFakeSunShader = { + name: "GodRaysFakeSunShader", + uniforms: { + vSunPositionScreenSpace: { + value: new Vector3 + }, + fAspect: { + value: 1 + }, + sunColor: { + value: new Color(16772608) + }, + bgColor: { + value: new Color(0) + } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + varying vec2 vUv; + + uniform vec3 vSunPositionScreenSpace; + uniform float fAspect; + + uniform vec3 sunColor; + uniform vec3 bgColor; + + void main() { + + vec2 diff = vUv - vSunPositionScreenSpace.xy; + + // Correct for aspect ratio + + diff.x *= fAspect; + + float prop = clamp( length( diff ) / 0.5, 0.0, 1.0 ); + prop = 0.35 * pow( 1.0 - prop, 3.0 ); + + gl_FragColor.xyz = ( vSunPositionScreenSpace.z > 0.0 ) ? mix( sunColor, bgColor, 1.0 - prop ) : bgColor; + gl_FragColor.w = 1.0; + + }` +}; +// node_modules/three/examples/jsm/shaders/HorizontalBlurShader.js +var HorizontalBlurShader = { + name: "HorizontalBlurShader", + uniforms: { + tDiffuse: { value: null }, + h: { value: 1 / 512 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform float h; + + varying vec2 vUv; + + void main() { + + vec4 sum = vec4( 0.0 ); + + sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ) * 0.051; + sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; + sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ) * 0.051; + + gl_FragColor = sum; + + }` +}; +// node_modules/three/examples/jsm/shaders/HorizontalTiltShiftShader.js +var HorizontalTiltShiftShader = { + name: "HorizontalTiltShiftShader", + uniforms: { + tDiffuse: { value: null }, + h: { value: 1 / 512 }, + r: { value: 0.35 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform float h; + uniform float r; + + varying vec2 vUv; + + void main() { + + vec4 sum = vec4( 0.0 ); + + float hh = h * abs( r - vUv.y ); + + sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * hh, vUv.y ) ) * 0.051; + sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * hh, vUv.y ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * hh, vUv.y ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * hh, vUv.y ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; + sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * hh, vUv.y ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * hh, vUv.y ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * hh, vUv.y ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * hh, vUv.y ) ) * 0.051; + + gl_FragColor = sum; + + }` +}; +// node_modules/three/examples/jsm/shaders/NormalMapShader.js +var NormalMapShader = { + name: "NormalMapShader", + uniforms: { + heightMap: { value: null }, + resolution: { value: new Vector2(512, 512) }, + scale: { value: new Vector2(1, 1) }, + height: { value: 0.05 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform float height; + uniform vec2 resolution; + uniform sampler2D heightMap; + + varying vec2 vUv; + + void main() { + + float val = texture2D( heightMap, vUv ).x; + + float valU = texture2D( heightMap, vUv + vec2( 1.0 / resolution.x, 0.0 ) ).x; + float valV = texture2D( heightMap, vUv + vec2( 0.0, 1.0 / resolution.y ) ).x; + + gl_FragColor = vec4( ( 0.5 * normalize( vec3( val - valU, val - valV, height ) ) + 0.5 ), 1.0 ); + + }` +}; +// node_modules/three/examples/jsm/shaders/SobelOperatorShader.js +var SobelOperatorShader = { + name: "SobelOperatorShader", + uniforms: { + tDiffuse: { value: null }, + resolution: { value: new Vector2 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform vec2 resolution; + varying vec2 vUv; + + void main() { + + vec2 texel = vec2( 1.0 / resolution.x, 1.0 / resolution.y ); + + // kernel definition (in glsl matrices are filled in column-major order) + + const mat3 Gx = mat3( -1, -2, -1, 0, 0, 0, 1, 2, 1 ); // x direction kernel + const mat3 Gy = mat3( -1, 0, 1, -2, 0, 2, -1, 0, 1 ); // y direction kernel + + // fetch the 3x3 neighbourhood of a fragment + + // first column + + float tx0y0 = texture2D( tDiffuse, vUv + texel * vec2( -1, -1 ) ).r; + float tx0y1 = texture2D( tDiffuse, vUv + texel * vec2( -1, 0 ) ).r; + float tx0y2 = texture2D( tDiffuse, vUv + texel * vec2( -1, 1 ) ).r; + + // second column + + float tx1y0 = texture2D( tDiffuse, vUv + texel * vec2( 0, -1 ) ).r; + float tx1y1 = texture2D( tDiffuse, vUv + texel * vec2( 0, 0 ) ).r; + float tx1y2 = texture2D( tDiffuse, vUv + texel * vec2( 0, 1 ) ).r; + + // third column + + float tx2y0 = texture2D( tDiffuse, vUv + texel * vec2( 1, -1 ) ).r; + float tx2y1 = texture2D( tDiffuse, vUv + texel * vec2( 1, 0 ) ).r; + float tx2y2 = texture2D( tDiffuse, vUv + texel * vec2( 1, 1 ) ).r; + + // gradient value in x direction + + float valueGx = Gx[0][0] * tx0y0 + Gx[1][0] * tx1y0 + Gx[2][0] * tx2y0 + + Gx[0][1] * tx0y1 + Gx[1][1] * tx1y1 + Gx[2][1] * tx2y1 + + Gx[0][2] * tx0y2 + Gx[1][2] * tx1y2 + Gx[2][2] * tx2y2; + + // gradient value in y direction + + float valueGy = Gy[0][0] * tx0y0 + Gy[1][0] * tx1y0 + Gy[2][0] * tx2y0 + + Gy[0][1] * tx0y1 + Gy[1][1] * tx1y1 + Gy[2][1] * tx2y1 + + Gy[0][2] * tx0y2 + Gy[1][2] * tx1y2 + Gy[2][2] * tx2y2; + + // magnitude of the total gradient + + float G = sqrt( ( valueGx * valueGx ) + ( valueGy * valueGy ) ); + + gl_FragColor = vec4( vec3( G ), 1 ); + + }` +}; +// node_modules/three/examples/jsm/shaders/SubsurfaceScatteringShader.js +function replaceAll(string, find2, replace) { + return string.split(find2).join(replace); +} +var meshphong_frag_head = ShaderChunk["meshphong_frag"].slice(0, ShaderChunk["meshphong_frag"].indexOf("void main() {")); +var meshphong_frag_body = ShaderChunk["meshphong_frag"].slice(ShaderChunk["meshphong_frag"].indexOf("void main() {")); +var SubsurfaceScatteringShader = { + name: "SubsurfaceScatteringShader", + uniforms: UniformsUtils.merge([ + ShaderLib["phong"].uniforms, + { + thicknessMap: { value: null }, + thicknessColor: { value: new Color(16777215) }, + thicknessDistortion: { value: 0.1 }, + thicknessAmbient: { value: 0 }, + thicknessAttenuation: { value: 0.1 }, + thicknessPower: { value: 2 }, + thicknessScale: { value: 10 } + } + ]), + vertexShader: [ + "#define USE_UV", + ShaderChunk["meshphong_vert"] + ].join(` +`), + fragmentShader: [ + "#define USE_UV", + "#define SUBSURFACE", + meshphong_frag_head, + "uniform sampler2D thicknessMap;", + "uniform float thicknessPower;", + "uniform float thicknessScale;", + "uniform float thicknessDistortion;", + "uniform float thicknessAmbient;", + "uniform float thicknessAttenuation;", + "uniform vec3 thicknessColor;", + "void RE_Direct_Scattering(const in IncidentLight directLight, const in vec2 uv, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, inout ReflectedLight reflectedLight) {", + "\tvec3 thickness = thicknessColor * texture2D(thicknessMap, uv).r;", + "\tvec3 scatteringHalf = normalize(directLight.direction + (geometryNormal * thicknessDistortion));", + "\tfloat scatteringDot = pow(saturate(dot(geometryViewDir, -scatteringHalf)), thicknessPower) * thicknessScale;", + "\tvec3 scatteringIllu = (scatteringDot + thicknessAmbient) * thickness;", + "\treflectedLight.directDiffuse += scatteringIllu * thicknessAttenuation * directLight.color;", + "}", + meshphong_frag_body.replace("#include ", replaceAll(ShaderChunk["lights_fragment_begin"], "RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );", [ + "RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );", + "#if defined( SUBSURFACE ) && defined( USE_UV )", + " RE_Direct_Scattering(directLight, vUv, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, reflectedLight);", + "#endif" + ].join(` +`))) + ].join(` +`) +}; +// node_modules/three/examples/jsm/shaders/ToonShader.js +var ToonShader1 = { + uniforms: { + uDirLightPos: { value: new Vector3 }, + uDirLightColor: { value: new Color(15658734) }, + uAmbientLightColor: { value: new Color(328965) }, + uBaseColor: { value: new Color(16777215) } + }, + vertexShader: ` + + varying vec3 vNormal; + varying vec3 vRefract; + + void main() { + + vec4 worldPosition = modelMatrix * vec4( position, 1.0 ); + vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 ); + vec3 worldNormal = normalize ( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal ); + + vNormal = normalize( normalMatrix * normal ); + + vec3 I = worldPosition.xyz - cameraPosition; + vRefract = refract( normalize( I ), worldNormal, 1.02 ); + + gl_Position = projectionMatrix * mvPosition; + + }`, + fragmentShader: ` + + uniform vec3 uBaseColor; + + uniform vec3 uDirLightPos; + uniform vec3 uDirLightColor; + + uniform vec3 uAmbientLightColor; + + varying vec3 vNormal; + + varying vec3 vRefract; + + void main() { + + float directionalLightWeighting = max( dot( normalize( vNormal ), uDirLightPos ), 0.0); + vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; + + float intensity = smoothstep( - 0.5, 1.0, pow( length(lightWeighting), 20.0 ) ); + intensity += length(lightWeighting) * 0.2; + + float cameraWeighting = dot( normalize( vNormal ), vRefract ); + intensity += pow( 1.0 - length( cameraWeighting ), 6.0 ); + intensity = intensity * 0.2 + 0.3; + + if ( intensity < 0.50 ) { + + gl_FragColor = vec4( 2.0 * intensity * uBaseColor, 1.0 ); + + } else { + + gl_FragColor = vec4( 1.0 - 2.0 * ( 1.0 - intensity ) * ( 1.0 - uBaseColor ), 1.0 ); + + } + + #include + + }` +}; +var ToonShader2 = { + uniforms: { + uDirLightPos: { value: new Vector3 }, + uDirLightColor: { value: new Color(15658734) }, + uAmbientLightColor: { value: new Color(328965) }, + uBaseColor: { value: new Color(15658734) }, + uLineColor1: { value: new Color(8421504) }, + uLineColor2: { value: new Color(0) }, + uLineColor3: { value: new Color(0) }, + uLineColor4: { value: new Color(0) } + }, + vertexShader: ` + + varying vec3 vNormal; + + void main() { + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + vNormal = normalize( normalMatrix * normal ); + + }`, + fragmentShader: ` + + uniform vec3 uBaseColor; + uniform vec3 uLineColor1; + uniform vec3 uLineColor2; + uniform vec3 uLineColor3; + uniform vec3 uLineColor4; + + uniform vec3 uDirLightPos; + uniform vec3 uDirLightColor; + + uniform vec3 uAmbientLightColor; + + varying vec3 vNormal; + + void main() { + + float camera = max( dot( normalize( vNormal ), vec3( 0.0, 0.0, 1.0 ) ), 0.4); + float light = max( dot( normalize( vNormal ), uDirLightPos ), 0.0); + + gl_FragColor = vec4( uBaseColor, 1.0 ); + + if ( length(uAmbientLightColor + uDirLightColor * light) < 1.00 ) { + + gl_FragColor *= vec4( uLineColor1, 1.0 ); + + } + + if ( length(uAmbientLightColor + uDirLightColor * camera) < 0.50 ) { + + gl_FragColor *= vec4( uLineColor2, 1.0 ); + + } + + #include + + }` +}; +var ToonShaderHatching = { + uniforms: { + uDirLightPos: { value: new Vector3 }, + uDirLightColor: { value: new Color(15658734) }, + uAmbientLightColor: { value: new Color(328965) }, + uBaseColor: { value: new Color(16777215) }, + uLineColor1: { value: new Color(0) }, + uLineColor2: { value: new Color(0) }, + uLineColor3: { value: new Color(0) }, + uLineColor4: { value: new Color(0) } + }, + vertexShader: ` + + varying vec3 vNormal; + + void main() { + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + vNormal = normalize( normalMatrix * normal ); + + }`, + fragmentShader: ` + + uniform vec3 uBaseColor; + uniform vec3 uLineColor1; + uniform vec3 uLineColor2; + uniform vec3 uLineColor3; + uniform vec3 uLineColor4; + + uniform vec3 uDirLightPos; + uniform vec3 uDirLightColor; + + uniform vec3 uAmbientLightColor; + + varying vec3 vNormal; + + void main() { + + float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0); + vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; + + gl_FragColor = vec4( uBaseColor, 1.0 ); + + if ( length(lightWeighting) < 1.00 ) { + + if ( mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) { + + gl_FragColor = vec4( uLineColor1, 1.0 ); + + } + + } + + if ( length(lightWeighting) < 0.75 ) { + + if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) { + + gl_FragColor = vec4( uLineColor2, 1.0 ); + + } + + } + + if ( length(lightWeighting) < 0.50 ) { + + if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) { + + gl_FragColor = vec4( uLineColor3, 1.0 ); + + } + + } + + if ( length(lightWeighting) < 0.3465 ) { + + if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) { + + gl_FragColor = vec4( uLineColor4, 1.0 ); + + } + + } + + #include + + }` +}; +var ToonShaderDotted = { + uniforms: { + uDirLightPos: { value: new Vector3 }, + uDirLightColor: { value: new Color(15658734) }, + uAmbientLightColor: { value: new Color(328965) }, + uBaseColor: { value: new Color(16777215) }, + uLineColor1: { value: new Color(0) } + }, + vertexShader: ` + + varying vec3 vNormal; + + void main() { + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + vNormal = normalize( normalMatrix * normal ); + + }`, + fragmentShader: ` + + uniform vec3 uBaseColor; + uniform vec3 uLineColor1; + uniform vec3 uLineColor2; + uniform vec3 uLineColor3; + uniform vec3 uLineColor4; + + uniform vec3 uDirLightPos; + uniform vec3 uDirLightColor; + + uniform vec3 uAmbientLightColor; + + varying vec3 vNormal; + + void main() { + + float directionalLightWeighting = max( dot( normalize(vNormal), uDirLightPos ), 0.0); + vec3 lightWeighting = uAmbientLightColor + uDirLightColor * directionalLightWeighting; + + gl_FragColor = vec4( uBaseColor, 1.0 ); + + if ( length(lightWeighting) < 1.00 ) { + + if ( ( mod(gl_FragCoord.x, 4.001) + mod(gl_FragCoord.y, 4.0) ) > 6.00 ) { + + gl_FragColor = vec4( uLineColor1, 1.0 ); + + } + + } + + if ( length(lightWeighting) < 0.50 ) { + + if ( ( mod(gl_FragCoord.x + 2.0, 4.001) + mod(gl_FragCoord.y + 2.0, 4.0) ) > 6.00 ) { + + gl_FragColor = vec4( uLineColor1, 1.0 ); + + } + + } + + #include + + }` +}; +// node_modules/three/examples/jsm/shaders/TriangleBlurShader.js +var TriangleBlurShader = { + name: "TriangleBlurShader", + uniforms: { + texture: { value: null }, + delta: { value: new Vector2(1, 1) } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + #include + + #define ITERATIONS 10.0 + + uniform sampler2D texture; + uniform vec2 delta; + + varying vec2 vUv; + + void main() { + + vec4 color = vec4( 0.0 ); + + float total = 0.0; + + // randomize the lookup values to hide the fixed number of samples + + float offset = rand( vUv ); + + for ( float t = -ITERATIONS; t <= ITERATIONS; t ++ ) { + + float percent = ( t + offset - 0.5 ) / ITERATIONS; + float weight = 1.0 - abs( percent ); + + color += texture2D( texture, vUv + delta * percent ) * weight; + total += weight; + + } + + gl_FragColor = color / total; + + }` +}; +// node_modules/three/examples/jsm/shaders/VelocityShader.js +var VelocityShader = { + name: "VelocityShader", + uniforms: UniformsUtils.merge([ + UniformsLib.common, + UniformsLib.displacementmap, + { + modelMatrixPrev: { value: new Matrix4 }, + currentProjectionViewMatrix: { value: new Matrix4 }, + previousProjectionViewMatrix: { value: new Matrix4 } + } + ]), + vertexShader: ` +#define NORMAL + +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + + varying vec3 vViewPosition; + +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +uniform mat4 previousProjectionViewMatrix; +uniform mat4 currentProjectionViewMatrix; + +uniform mat4 modelMatrixPrev; + +varying vec4 clipPositionCurrent; +varying vec4 clipPositionPrevious; + +void main() { + + + #include + + #include + #include + #include + #include + #include + #include + + #include + #include + #include + #include + #include + +#ifdef USE_SKINNING + + vec4 mvPosition = modelViewMatrix * skinned; + clipPositionCurrent = currentProjectionViewMatrix * modelMatrix * skinned; + clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * skinned; + +#else + + vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 ); + clipPositionCurrent = currentProjectionViewMatrix * modelMatrix * vec4( transformed, 1.0 ); + clipPositionPrevious = previousProjectionViewMatrix * modelMatrixPrev * vec4( transformed, 1.0 ); + +#endif + + gl_Position = projectionMatrix * mvPosition; + + #include + #include +} +`, + fragmentShader: ` +#define NORMAL + +uniform float opacity; + +#include +#include +#include +#include +#include +#include +#include + +varying vec4 clipPositionCurrent; +varying vec4 clipPositionPrevious; + +void main() { + + vec4 diffuseColor = vec4( 1.0 ); + diffuseColor.a = opacity; + + #include + #include + #include + + vec2 ndcPositionCurrent = clipPositionCurrent.xy/clipPositionCurrent.w; + vec2 ndcPositionPrevious = clipPositionPrevious.xy/clipPositionPrevious.w; + vec2 vel = ( ndcPositionCurrent - ndcPositionPrevious ) * 0.5; + vel = vel * 0.5 + 0.5; + vec2 v1 = packDepthToRG(vel.x); + vec2 v2 = packDepthToRG(vel.y); + gl_FragColor = vec4(v1.x, v1.y, v2.x, v2.y); + + #include + +} + +` +}; +// node_modules/three/examples/jsm/shaders/VerticalBlurShader.js +var VerticalBlurShader = { + name: "VerticalBlurShader", + uniforms: { + tDiffuse: { value: null }, + v: { value: 1 / 512 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform float v; + + varying vec2 vUv; + + void main() { + + vec4 sum = vec4( 0.0 ); + + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ) * 0.051; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ) * 0.051; + + gl_FragColor = sum; + + }` +}; +// node_modules/three/examples/jsm/shaders/VerticalTiltShiftShader.js +var VerticalTiltShiftShader = { + name: "VerticalTiltShiftShader", + uniforms: { + tDiffuse: { value: null }, + v: { value: 1 / 512 }, + r: { value: 0.35 } + }, + vertexShader: ` + + varying vec2 vUv; + + void main() { + + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + + }`, + fragmentShader: ` + + uniform sampler2D tDiffuse; + uniform float v; + uniform float r; + + varying vec2 vUv; + + void main() { + + vec4 sum = vec4( 0.0 ); + + float vv = v * abs( r - vUv.y ); + + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * vv ) ) * 0.051; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * vv ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * vv ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * vv ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * vv ) ) * 0.1531; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * vv ) ) * 0.12245; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * vv ) ) * 0.0918; + sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * vv ) ) * 0.051; + + gl_FragColor = sum; + + }` +}; +// node_modules/three/examples/jsm/shaders/VolumeShader.js +var VolumeRenderShader1 = { + uniforms: { + u_size: { value: new Vector3(1, 1, 1) }, + u_renderstyle: { value: 0 }, + u_renderthreshold: { value: 0.5 }, + u_clim: { value: new Vector2(1, 1) }, + u_data: { value: null }, + u_cmdata: { value: null } + }, + vertexShader: ` + + varying vec4 v_nearpos; + varying vec4 v_farpos; + varying vec3 v_position; + + void main() { + // Prepare transforms to map to "camera view". See also: + // https://threejs.org/docs/#api/renderers/webgl/WebGLProgram + mat4 viewtransformf = modelViewMatrix; + mat4 viewtransformi = inverse(modelViewMatrix); + + // Project local vertex coordinate to camera position. Then do a step + // backward (in cam coords) to the near clipping plane, and project back. Do + // the same for the far clipping plane. This gives us all the information we + // need to calculate the ray and truncate it to the viewing cone. + vec4 position4 = vec4(position, 1.0); + vec4 pos_in_cam = viewtransformf * position4; + + // Intersection of ray and near clipping plane (z = -1 in clip coords) + pos_in_cam.z = -pos_in_cam.w; + v_nearpos = viewtransformi * pos_in_cam; + + // Intersection of ray and far clipping plane (z = +1 in clip coords) + pos_in_cam.z = pos_in_cam.w; + v_farpos = viewtransformi * pos_in_cam; + + // Set varyings and output pos + v_position = position; + gl_Position = projectionMatrix * viewMatrix * modelMatrix * position4; + }`, + fragmentShader: ` + + precision highp float; + precision mediump sampler3D; + + uniform vec3 u_size; + uniform int u_renderstyle; + uniform float u_renderthreshold; + uniform vec2 u_clim; + + uniform sampler3D u_data; + uniform sampler2D u_cmdata; + + varying vec3 v_position; + varying vec4 v_nearpos; + varying vec4 v_farpos; + + // The maximum distance through our rendering volume is sqrt(3). + const int MAX_STEPS = 887; // 887 for 512^3, 1774 for 1024^3 + const int REFINEMENT_STEPS = 4; + const float relative_step_size = 1.0; + const vec4 ambient_color = vec4(0.2, 0.4, 0.2, 1.0); + const vec4 diffuse_color = vec4(0.8, 0.2, 0.2, 1.0); + const vec4 specular_color = vec4(1.0, 1.0, 1.0, 1.0); + const float shininess = 40.0; + + void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray); + void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray); + + float sample1(vec3 texcoords); + vec4 apply_colormap(float val); + vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray); + + + void main() { + // Normalize clipping plane info + vec3 farpos = v_farpos.xyz / v_farpos.w; + vec3 nearpos = v_nearpos.xyz / v_nearpos.w; + + // Calculate unit vector pointing in the view direction through this fragment. + vec3 view_ray = normalize(nearpos.xyz - farpos.xyz); + + // Compute the (negative) distance to the front surface or near clipping plane. + // v_position is the back face of the cuboid, so the initial distance calculated in the dot + // product below is the distance from near clip plane to the back of the cuboid + float distance = dot(nearpos - v_position, view_ray); + distance = max(distance, min((-0.5 - v_position.x) / view_ray.x, + (u_size.x - 0.5 - v_position.x) / view_ray.x)); + distance = max(distance, min((-0.5 - v_position.y) / view_ray.y, + (u_size.y - 0.5 - v_position.y) / view_ray.y)); + distance = max(distance, min((-0.5 - v_position.z) / view_ray.z, + (u_size.z - 0.5 - v_position.z) / view_ray.z)); + + // Now we have the starting position on the front surface + vec3 front = v_position + view_ray * distance; + + // Decide how many steps to take + int nsteps = int(-distance / relative_step_size + 0.5); + if ( nsteps < 1 ) + discard; + + // Get starting location and step vector in texture coordinates + vec3 step = ((v_position - front) / u_size) / float(nsteps); + vec3 start_loc = front / u_size; + + // For testing: show the number of steps. This helps to establish + // whether the rays are correctly oriented + //'gl_FragColor = vec4(0.0, float(nsteps) / 1.0 / u_size.x, 1.0, 1.0); + //'return; + + if (u_renderstyle == 0) + cast_mip(start_loc, step, nsteps, view_ray); + else if (u_renderstyle == 1) + cast_iso(start_loc, step, nsteps, view_ray); + + if (gl_FragColor.a < 0.05) + discard; + } + + + float sample1(vec3 texcoords) { + /* Sample float value from a 3D texture. Assumes intensity data. */ + return texture(u_data, texcoords.xyz).r; + } + + + vec4 apply_colormap(float val) { + val = (val - u_clim[0]) / (u_clim[1] - u_clim[0]); + return texture2D(u_cmdata, vec2(val, 0.5)); + } + + + void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) { + + float max_val = -1e6; + int max_i = 100; + vec3 loc = start_loc; + + // Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with + // non-constant expression. So we use a hard-coded max, and an additional condition + // inside the loop. + for (int iter=0; iter= nsteps) + break; + // Sample from the 3D texture + float val = sample1(loc); + // Apply MIP operation + if (val > max_val) { + max_val = val; + max_i = iter; + } + // Advance location deeper into the volume + loc += step; + } + + // Refine location, gives crispier images + vec3 iloc = start_loc + step * (float(max_i) - 0.5); + vec3 istep = step / float(REFINEMENT_STEPS); + for (int i=0; i= nsteps) + break; + + // Sample from the 3D texture + float val = sample1(loc); + + if (val > low_threshold) { + // Take the last interval in smaller steps + vec3 iloc = loc - 0.5 * step; + vec3 istep = step / float(REFINEMENT_STEPS); + for (int i=0; i u_renderthreshold) { + gl_FragColor = add_lighting(val, iloc, dstep, view_ray); + return; + } + iloc += istep; + } + } + + // Advance location deeper into the volume + loc += step; + } + } + + + vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray) + { + // Calculate color by incorporating lighting + + // View direction + vec3 V = normalize(view_ray); + + // calculate normal vector from gradient + vec3 N; + float val1, val2; + val1 = sample1(loc + vec3(-step[0], 0.0, 0.0)); + val2 = sample1(loc + vec3(+step[0], 0.0, 0.0)); + N[0] = val1 - val2; + val = max(max(val1, val2), val); + val1 = sample1(loc + vec3(0.0, -step[1], 0.0)); + val2 = sample1(loc + vec3(0.0, +step[1], 0.0)); + N[1] = val1 - val2; + val = max(max(val1, val2), val); + val1 = sample1(loc + vec3(0.0, 0.0, -step[2])); + val2 = sample1(loc + vec3(0.0, 0.0, +step[2])); + N[2] = val1 - val2; + val = max(max(val1, val2), val); + + float gm = length(N); // gradient magnitude + N = normalize(N); + + // Flip normal so it points towards viewer + float Nselect = float(dot(N, V) > 0.0); + N = (2.0 * Nselect - 1.0) * N; // == Nselect * N - (1.0-Nselect)*N; + + // Init colors + vec4 ambient_color = vec4(0.0, 0.0, 0.0, 0.0); + vec4 diffuse_color = vec4(0.0, 0.0, 0.0, 0.0); + vec4 specular_color = vec4(0.0, 0.0, 0.0, 0.0); + + // note: could allow multiple lights + for (int i=0; i<1; i++) + { + // Get light direction (make sure to prevent zero devision) + vec3 L = normalize(view_ray); //lightDirs[i]; + float lightEnabled = float( length(L) > 0.0 ); + L = normalize(L + (1.0 - lightEnabled)); + + // Calculate lighting properties + float lambertTerm = clamp(dot(N, L), 0.0, 1.0); + vec3 H = normalize(L+V); // Halfway vector + float specularTerm = pow(max(dot(H, N), 0.0), shininess); + + // Calculate mask + float mask1 = lightEnabled; + + // Calculate colors + ambient_color += mask1 * ambient_color; // * gl_LightSource[i].ambient; + diffuse_color += mask1 * lambertTerm; + specular_color += mask1 * specularTerm * specular_color; + } + + // Calculate final color by componing different components + vec4 final_color; + vec4 color = apply_colormap(val); + final_color = color * (ambient_color + diffuse_color) + specular_color; + final_color.a = color.a; + return final_color; + }` +}; +// node_modules/three/examples/jsm/utils/SkeletonUtils.js +var exports_SkeletonUtils = {}; +__export(exports_SkeletonUtils, { + retargetClip: () => retargetClip, + retarget: () => retarget, + clone: () => clone +}); +function getBoneName(bone, options) { + if (options.getBoneName !== undefined) { + return options.getBoneName(bone); + } + return options.names[bone.name]; +} +function retarget(target, source, options = {}) { + const quat = new Quaternion, scale2 = new Vector3, relativeMatrix = new Matrix4, globalMatrix = new Matrix4; + options.preserveBoneMatrix = options.preserveBoneMatrix !== undefined ? options.preserveBoneMatrix : true; + options.preserveBonePositions = options.preserveBonePositions !== undefined ? options.preserveBonePositions : true; + options.useTargetMatrix = options.useTargetMatrix !== undefined ? options.useTargetMatrix : false; + options.hip = options.hip !== undefined ? options.hip : "hip"; + options.hipInfluence = options.hipInfluence !== undefined ? options.hipInfluence : new Vector3(1, 1, 1); + options.scale = options.scale !== undefined ? options.scale : 1; + options.names = options.names || {}; + const sourceBones = source.isObject3D ? source.skeleton.bones : getBones(source), bones = target.isObject3D ? target.skeleton.bones : getBones(target); + let bone, name2, boneTo, bonesPosition; + if (target.isObject3D) { + target.skeleton.pose(); + } else { + options.useTargetMatrix = true; + options.preserveBoneMatrix = false; + } + if (options.preserveBonePositions) { + bonesPosition = []; + for (let i = 0;i < bones.length; i++) { + bonesPosition.push(bones[i].position.clone()); + } + } + if (options.preserveBoneMatrix) { + target.updateMatrixWorld(); + target.matrixWorld.identity(); + for (let i = 0;i < target.children.length; ++i) { + target.children[i].updateMatrixWorld(true); + } + } + for (let i = 0;i < bones.length; ++i) { + bone = bones[i]; + name2 = getBoneName(bone, options); + boneTo = getBoneByName(name2, sourceBones); + globalMatrix.copy(bone.matrixWorld); + if (boneTo) { + boneTo.updateMatrixWorld(); + if (options.useTargetMatrix) { + relativeMatrix.copy(boneTo.matrixWorld); + } else { + relativeMatrix.copy(target.matrixWorld).invert(); + relativeMatrix.multiply(boneTo.matrixWorld); + } + scale2.setFromMatrixScale(relativeMatrix); + relativeMatrix.scale(scale2.set(1 / scale2.x, 1 / scale2.y, 1 / scale2.z)); + globalMatrix.makeRotationFromQuaternion(quat.setFromRotationMatrix(relativeMatrix)); + if (target.isObject3D) { + if (options.localOffsets) { + if (options.localOffsets[bone.name]) { + globalMatrix.multiply(options.localOffsets[bone.name]); + } + } + } + globalMatrix.copyPosition(relativeMatrix); + } + if (name2 === options.hip) { + globalMatrix.elements[12] *= options.scale * options.hipInfluence.x; + globalMatrix.elements[13] *= options.scale * options.hipInfluence.y; + globalMatrix.elements[14] *= options.scale * options.hipInfluence.z; + if (options.hipPosition !== undefined) { + globalMatrix.elements[12] += options.hipPosition.x * options.scale; + globalMatrix.elements[13] += options.hipPosition.y * options.scale; + globalMatrix.elements[14] += options.hipPosition.z * options.scale; + } + } + if (bone.parent) { + bone.matrix.copy(bone.parent.matrixWorld).invert(); + bone.matrix.multiply(globalMatrix); + } else { + bone.matrix.copy(globalMatrix); + } + bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); + bone.updateMatrixWorld(); + } + if (options.preserveBonePositions) { + for (let i = 0;i < bones.length; ++i) { + bone = bones[i]; + name2 = getBoneName(bone, options) || bone.name; + if (name2 !== options.hip) { + bone.position.copy(bonesPosition[i]); + } + } + } + if (options.preserveBoneMatrix) { + target.updateMatrixWorld(true); + } +} +function retargetClip(target, source, clip, options = {}) { + options.useFirstFramePosition = options.useFirstFramePosition !== undefined ? options.useFirstFramePosition : false; + options.fps = options.fps !== undefined ? options.fps : Math.max(...clip.tracks.map((track) => track.times.length)) / clip.duration; + options.names = options.names || []; + if (!source.isObject3D) { + source = getHelperFromSkeleton(source); + } + const numFrames = Math.round(clip.duration * (options.fps / 1000) * 1000), delta = clip.duration / (numFrames - 1), convertedTracks = [], mixer = new AnimationMixer(source), bones = getBones(target.skeleton), boneDatas = []; + let positionOffset, bone, boneTo, boneData, name2; + mixer.clipAction(clip).play(); + let start = 0, end = numFrames; + if (options.trim !== undefined) { + start = Math.round(options.trim[0] * options.fps); + end = Math.min(Math.round(options.trim[1] * options.fps), numFrames) - start; + mixer.update(options.trim[0]); + } else { + mixer.update(0); + } + source.updateMatrixWorld(); + for (let frame = 0;frame < end; ++frame) { + const time2 = frame * delta; + retarget(target, source, options); + for (let j2 = 0;j2 < bones.length; ++j2) { + bone = bones[j2]; + name2 = getBoneName(bone, options) || bone.name; + boneTo = getBoneByName(name2, source.skeleton); + if (boneTo) { + boneData = boneDatas[j2] = boneDatas[j2] || { bone }; + if (options.hip === name2) { + if (!boneData.pos) { + boneData.pos = { + times: new Float32Array(end), + values: new Float32Array(end * 3) + }; + } + if (options.useFirstFramePosition) { + if (frame === 0) { + positionOffset = bone.position.clone(); + } + bone.position.sub(positionOffset); + } + boneData.pos.times[frame] = time2; + bone.position.toArray(boneData.pos.values, frame * 3); + } + if (!boneData.quat) { + boneData.quat = { + times: new Float32Array(end), + values: new Float32Array(end * 4) + }; + } + boneData.quat.times[frame] = time2; + bone.quaternion.toArray(boneData.quat.values, frame * 4); + } + } + if (frame === end - 2) { + mixer.update(delta - 0.0000001); + } else { + mixer.update(delta); + } + source.updateMatrixWorld(); + } + for (let i = 0;i < boneDatas.length; ++i) { + boneData = boneDatas[i]; + if (boneData) { + if (boneData.pos) { + convertedTracks.push(new VectorKeyframeTrack(".bones[" + boneData.bone.name + "].position", boneData.pos.times, boneData.pos.values)); + } + convertedTracks.push(new QuaternionKeyframeTrack(".bones[" + boneData.bone.name + "].quaternion", boneData.quat.times, boneData.quat.values)); + } + } + mixer.uncacheAction(clip); + return new AnimationClip(clip.name, -1, convertedTracks); +} +function clone(source) { + const sourceLookup = new Map; + const cloneLookup = new Map; + const clone2 = source.clone(); + parallelTraverse(source, clone2, function(sourceNode, clonedNode) { + sourceLookup.set(clonedNode, sourceNode); + cloneLookup.set(sourceNode, clonedNode); + }); + clone2.traverse(function(node) { + if (!node.isSkinnedMesh) + return; + const clonedMesh = node; + const sourceMesh = sourceLookup.get(node); + const sourceBones = sourceMesh.skeleton.bones; + clonedMesh.skeleton = sourceMesh.skeleton.clone(); + clonedMesh.bindMatrix.copy(sourceMesh.bindMatrix); + clonedMesh.skeleton.bones = sourceBones.map(function(bone) { + return cloneLookup.get(bone); + }); + clonedMesh.bind(clonedMesh.skeleton, clonedMesh.bindMatrix); + }); + return clone2; +} +function getBoneByName(name2, skeleton) { + for (let i = 0, bones = getBones(skeleton);i < bones.length; i++) { + if (name2 === bones[i].name) + return bones[i]; + } +} +function getBones(skeleton) { + return Array.isArray(skeleton) ? skeleton : skeleton.bones; +} +function getHelperFromSkeleton(skeleton) { + const source = new SkeletonHelper(skeleton.bones[0]); + source.skeleton = skeleton; + return source; +} +function parallelTraverse(a2, b2, callback) { + callback(a2, b2); + for (let i = 0;i < a2.children.length; i++) { + parallelTraverse(a2.children[i], b2.children[i], callback); + } +} +// node_modules/three/examples/jsm/utils/SortUtils.js +var POWER = 3; +var BIT_MAX = 32; +var BIN_BITS = 1 << POWER; +var BIN_SIZE = 1 << BIN_BITS; +var BIN_MAX = BIN_SIZE - 1; +var ITERATIONS = BIT_MAX / BIN_BITS; +var bins = new Array(ITERATIONS); +var bins_buffer = new ArrayBuffer((ITERATIONS + 1) * BIN_SIZE * 4); +var c = 0; +for (let i = 0;i < ITERATIONS + 1; i++) { + bins[i] = new Uint32Array(bins_buffer, c, BIN_SIZE); + c += BIN_SIZE * 4; +} +// node_modules/three/examples/jsm/webxr/VRButton.js +class VRButton { + static createButton(renderer2, sessionInit = {}) { + const button = document.createElement("button"); + function showEnterVR() { + let currentSession = null; + async function onSessionStarted(session) { + session.addEventListener("end", onSessionEnded); + await renderer2.xr.setSession(session); + button.textContent = "EXIT VR"; + currentSession = session; + } + function onSessionEnded() { + currentSession.removeEventListener("end", onSessionEnded); + button.textContent = "ENTER VR"; + currentSession = null; + } + button.style.display = ""; + button.style.cursor = "pointer"; + button.style.left = "calc(50% - 50px)"; + button.style.width = "100px"; + button.textContent = "ENTER VR"; + const sessionOptions = { + ...sessionInit, + optionalFeatures: [ + "local-floor", + "bounded-floor", + "layers", + ...sessionInit.optionalFeatures || [] + ] + }; + button.onmouseenter = function() { + button.style.opacity = "1.0"; + }; + button.onmouseleave = function() { + button.style.opacity = "0.5"; + }; + button.onclick = function() { + if (currentSession === null) { + navigator.xr.requestSession("immersive-vr", sessionOptions).then(onSessionStarted); + } else { + currentSession.end(); + if (navigator.xr.offerSession !== undefined) { + navigator.xr.offerSession("immersive-vr", sessionOptions).then(onSessionStarted).catch((err) => { + console.warn(err); + }); + } + } + }; + if (navigator.xr.offerSession !== undefined) { + navigator.xr.offerSession("immersive-vr", sessionOptions).then(onSessionStarted).catch((err) => { + console.warn(err); + }); + } + } + function disableButton() { + button.style.display = ""; + button.style.cursor = "auto"; + button.style.left = "calc(50% - 75px)"; + button.style.width = "150px"; + button.onmouseenter = null; + button.onmouseleave = null; + button.onclick = null; + } + function showWebXRNotFound() { + disableButton(); + button.textContent = "VR NOT SUPPORTED"; + } + function showVRNotAllowed(exception) { + disableButton(); + console.warn("Exception when trying to call xr.isSessionSupported", exception); + button.textContent = "VR NOT ALLOWED"; + } + function stylizeElement(element) { + element.style.position = "absolute"; + element.style.bottom = "20px"; + element.style.padding = "12px 6px"; + element.style.border = "1px solid #fff"; + element.style.borderRadius = "4px"; + element.style.background = "rgba(0,0,0,0.1)"; + element.style.color = "#fff"; + element.style.font = "normal 13px sans-serif"; + element.style.textAlign = "center"; + element.style.opacity = "0.5"; + element.style.outline = "none"; + element.style.zIndex = "999"; + } + if ("xr" in navigator) { + button.id = "VRButton"; + button.style.display = "none"; + stylizeElement(button); + navigator.xr.isSessionSupported("immersive-vr").then(function(supported) { + supported ? showEnterVR() : showWebXRNotFound(); + if (supported && VRButton.xrSessionIsGranted) { + button.click(); + } + }).catch(showVRNotAllowed); + return button; + } else { + const message = document.createElement("a"); + if (window.isSecureContext === false) { + message.href = document.location.href.replace(/^http:/, "https:"); + message.innerHTML = "WEBXR NEEDS HTTPS"; + } else { + message.href = "https://immersiveweb.dev/"; + message.innerHTML = "WEBXR NOT AVAILABLE"; + } + message.style.left = "calc(50% - 90px)"; + message.style.width = "180px"; + message.style.textDecoration = "none"; + stylizeElement(message); + return message; + } + } + static registerSessionGrantedListener() { + if (typeof navigator !== "undefined" && "xr" in navigator) { + if (/WebXRViewer\//i.test(navigator.userAgent)) + return; + navigator.xr.addEventListener("sessiongranted", () => { + VRButton.xrSessionIsGranted = true; + }); + } + } +} +VRButton.xrSessionIsGranted = false; +VRButton.registerSessionGrantedListener(); +// node_modules/three/examples/jsm/libs/motion-controllers.module.js +var Constants = { + Handedness: Object.freeze({ + NONE: "none", + LEFT: "left", + RIGHT: "right" + }), + ComponentState: Object.freeze({ + DEFAULT: "default", + TOUCHED: "touched", + PRESSED: "pressed" + }), + ComponentProperty: Object.freeze({ + BUTTON: "button", + X_AXIS: "xAxis", + Y_AXIS: "yAxis", + STATE: "state" + }), + ComponentType: Object.freeze({ + TRIGGER: "trigger", + SQUEEZE: "squeeze", + TOUCHPAD: "touchpad", + THUMBSTICK: "thumbstick", + BUTTON: "button" + }), + ButtonTouchThreshold: 0.05, + AxisTouchThreshold: 0.1, + VisualResponseProperty: Object.freeze({ + TRANSFORM: "transform", + VISIBILITY: "visibility" + }) +}; +var defaultComponentValues = { + xAxis: 0, + yAxis: 0, + button: 0, + state: Constants.ComponentState.DEFAULT +}; +// node_modules/three/examples/jsm/webxr/XRHandPrimitiveModel.js +var _matrix7 = new Matrix4; +var _vector9 = new Vector3; +// src/constants/BodyShaderTypes.ts +var BodyType; +((BodyType2) => { + BodyType2["WiiU"] = "wiiu"; + BodyType2["Switch"] = "switch"; + BodyType2["Miitomo"] = "miitomo"; + BodyType2["StreetPass"] = "streetpass"; +})(BodyType ||= {}); +var ShaderType; +((ShaderType2) => { + ShaderType2["WiiU"] = "wiiu"; + ShaderType2["Switch"] = "switch"; + ShaderType2["LightDisabled"] = "lightDisabled"; + ShaderType2["Miitomo"] = "miitomo"; + ShaderType2["MiitomoBasic"] = "miitomo_basic"; + ShaderType2["WiiUBlinn"] = "wiiu_blinn"; + ShaderType2["WiiUFFLIconWithBody"] = "wiiu_ffliconwithbody"; + ShaderType2["WiiUToon"] = "wiiu_toon"; + ShaderType2["ThreeToon"] = "three_toon"; + ShaderType2["ThreePhong"] = "three_phong"; +})(ShaderType ||= {}); +function adjustShaderQuery(params, shader) { + switch (shader) { + case "wiiu" /* WiiU */: + case "switch" /* Switch */: + case "miitomo" /* Miitomo */: + params.set("shaderType", shader); + break; + case "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */: + params.set("shaderType", "ffliconwithbody"); + break; + case "wiiu_toon" /* WiiUToon */: + params.set("shaderType", "wiiu"); + break; + case "wiiu_blinn" /* WiiUBlinn */: + params.set("shaderType", "wiiu_blinn"); + break; + case "lightDisabled" /* LightDisabled */: + params.set("shaderType", "wiiu"); + params.set("lightEnable", "0"); + break; + default: + console.warn(`unknown shader type: ${shader}`); + } +} + +// src/util/ModelLoader.ts +//! NOTE: THIS ASSUMES THE ROOT IS THE PUBLIC FOLDER +var root = "/"; +var setRoot = (newRoot) => { + root = newRoot; +}; +var gltfLoader = new GLTFLoader; +var imageLoader = new ImageBitmapLoader; +function makeModelPath(gender, modelName) { + return `${root}assets/models/miiBody${gender}_${modelName}.glb`; +} +async function loadBodyModel(modelPath) { + const model = await gltfLoader.loadAsync(modelPath); + var mixer = new AnimationMixer(model.scene); + const scene = model.scene; + if (model.animations.length > 0) { + const idleClip = model.animations[0]; + const idleAnim = mixer.clipAction(idleClip, scene); + idleAnim.stop(); + try { + const clip = model.animations.find((a2) => a2.name === "Pose.01"); + const anim = mixer.clipAction(clip, scene); + anim.play(); + anim.timeScale = 0; + anim.paused = true; + mixer.update(0); + } catch (e) { + } + } else + console.warn("Body model has no animations"); + return model; +} +var bodyType = "wiiu"; +async function loadBodyModels(input, alsoLoadStreetPass = false) { + if (Object.keys(bodyModels).length > 0) { + bodyModels = {}; + } + bodyType = input || await import_localforage.default.getItem("settings_bodyModel") || "wiiu"; + bodyModelName = bodyType; + if (bodyType === "streetpass" /* StreetPass */) { + isStreetPassBody = true; + } + if (bodyModels.highM) { + bodyModels.highM.scene.traverse((o) => { + if (o.isMesh) { + o.dispose(); + } + }); + } + if (bodyModels.highF) { + bodyModels.highF.scene.traverse((o) => { + if (o.isMesh) { + o.dispose(); + } + }); + } + bodyModels.highM = await loadBodyModel(makeModelPath("M", bodyType)); + bodyModels.highF = await loadBodyModel(makeModelPath("F", bodyType)); + if (alsoLoadStreetPass) { + bodyModels.lowM = await loadBodyModel(makeModelPath("M", "streetpass")); + bodyModels.lowF = await loadBodyModel(makeModelPath("F", "streetpass")); + } +} +async function loadHatModels() { + hatModels = []; + const data2 = await fetch(root + "assets/models/hat_models_bundle.zip").then((j2) => j2.blob()); + const zip = await import_jszip.default.loadAsync(data2); + let promises = []; + const fileList = Object.keys(zip.files); + for (const file of fileList) { + promises.push(zip.files[file].async("blob")); + } + const resolves = await Promise.all(promises); + for (let i = 0;i < fileList.length; i++) { + console.log("File:", fileList[i]); + const url = URL.createObjectURL(resolves[i]); + const gltf = await gltfLoader.loadAsync(url); + hatModels[i] = gltf.scene; + URL.revokeObjectURL(url); + } +} +async function loadClothesTextures() { + clothesTextures = {}; + imageLoader.setOptions({ imageOrientation: "flipY" }); + const data2 = await fetch(root + "assets/images/mii_clothes_textures_bundle.zip").then((j2) => j2.blob()); + console.log("Got it"); + const zip = await import_jszip.default.loadAsync(data2); + console.log("Got zip"); + let promises = []; + const fileList = Object.keys(zip.files); + for (const file of fileList) { + promises.push(zip.files[file].async("blob")); + } + const resolves = await Promise.all(promises); + console.log("Got files"); + for (let i = 0;i < fileList.length; i++) { + const url = URL.createObjectURL(resolves[i]); + let result; + console.log("Loading texture"); + result = new CanvasTexture(await imageLoader.loadAsync(url)); + console.log("Loading texture done"); + const fileName = fileList[i].split("."); + fileName.pop(); + clothesTextures[fileName.join(".")] = result; + console.log("Loading " + fileName.join(".")); + URL.revokeObjectURL(url); + } + console.log("Done"); +} +var bodyModels = { + highM: null, + highF: null, + lowM: null, + lowF: null +}; +var bodyModelName = "wiiu"; +var hatModels = []; +var clothesTextures = {}; +var isStreetPassBody = false; +var isStreetPass = () => isStreetPassBody; +var getBodyModels = () => bodyModels; +var getHatModels = () => hatModels; +var getLoadedBodyModelName = () => bodyModelName; +var getClothesTextures = () => clothesTextures; + +// src/class/3d/shader/ShaderUtils.ts +var import_FFLShaderMaterial2 = __toESM(require_FFLShaderMaterial(), 1); +var import_LUTShaderMaterial2 = __toESM(require_LUTShaderMaterial(), 1); +var import_localforage2 = __toESM(require_localforage(), 1); + +// src/class/3d/shader/FFLShaderAlternateMaterial.ts +var import_FFLShaderMaterial = __toESM(require_FFLShaderMaterial(), 1); +var import_LUTShaderMaterial = __toESM(require_LUTShaderMaterial(), 1); + +// src/class/3d/shader/fflShaderConst.ts +var FFLToonMaterial = { + ambient: new Color(0.8, 0.8, 0.8), + diffuse: new Color(0.8, 0.8, 0.8), + specular: new Color(0.1, 0.1, 0.1), + specularPower: 0.01, + specularMode: 0 +}; +var cLightAmbientFFLIconWithBody = new Color(0.5, 0.5, 0.5); +var cLightDiffuseFFLIconWithBody = new Color(0.9, 0.9, 0.9); +var cLightSpecularFFLIconWithBody = new Color(1, 1, 1); +var cLightDirGlossy = new Vector3(-0.35, 1, 0.8); +var cLightDirFFLIconWithBody = new Vector3(-0.5, 0.366, 0.785); +var cRimColor = new Vector4(0.3, 0.3, 0.3, 1); +var cPantsColorGray = [0.25098, 0.27451, 0.30588]; +var cPantsColorRed = [0.43922, 0.12549, 0.06275]; +var cPantsColorBlue = [0.15686, 0.25098, 0.47059]; +var cPantsColorGold = [0.75294, 0.62745, 0.18824]; +var cPantsColorRedHex = "#902010"; +var cPantsColorGoldHex = "#c0a030"; +var MiiFavoriteFFLColorLookupTable = { + 0: [0.824, 0.118, 0.078], + 1: [1, 0.431, 0.098], + 2: [1, 0.847, 0.125], + 3: [0.471, 0.824, 0.125], + 4: [0, 0.471, 0.188], + 5: [0.039, 0.282, 0.706], + 6: [0.235, 0.667, 0.871], + 7: [0.961, 0.353, 0.49], + 8: [0.451, 0.157, 0.678], + 9: [0.282, 0.22, 0.094], + 10: [0.878, 0.878, 0.878], + 11: [0.094, 0.094, 0.078] +}; + +// src/class/3d/shader/FFLShaderAlternateMaterial.ts +class FFLShaderBlinnMaterial extends import_FFLShaderMaterial.default { + constructor(options = {}) { + options = Object.assign({ + useSpecularModeBlinn: true + }, options); + super(options); + if (this.uniforms.u_material_specular_power) + this.uniforms.u_material_specular_power.value = 2; + } +} +class FFLShaderToonMaterial extends import_FFLShaderMaterial.default { + constructor(options = {}) { + options = Object.assign({}, options); + super(options); + this.uniforms.u_light_dir.value = cLightDirGlossy; + if (this.uniforms.u_material_ambient) { + this.uniforms.u_material_ambient.value = FFLToonMaterial.ambient; + this.uniforms.u_material_diffuse.value = FFLToonMaterial.diffuse; + this.uniforms.u_material_specular.value = FFLToonMaterial.specular; + this.uniforms.u_material_specular_power.value = FFLToonMaterial.specularPower; + this.uniforms.u_material_specular_mode.value = FFLToonMaterial.specularMode; + } + } +} + +class FFLShaderBrightMaterial extends import_FFLShaderMaterial.default { + constructor(options = {}) { + options = Object.assign({}, options); + super(options); + this.uniforms.u_light_dir.value = cLightDirFFLIconWithBody; + this.uniforms.u_light_ambient.value = cLightAmbientFFLIconWithBody; + this.uniforms.u_light_diffuse.value = cLightDiffuseFFLIconWithBody; + this.uniforms.u_light_specular.value = cLightSpecularFFLIconWithBody; + } +} + +class LUTShaderPretendoMaterial extends import_LUTShaderMaterial.default { + constructor(options = {}) { + options = Object.assign({}, options); + super(options); + this.uniforms.uDirLightDirAndType0.value = new Vector4(-0.2, 0.5, 0.8, -1); + this.uniforms.uDirLightDirAndType1.value = new Vector4(0, -0.19612, 0.98058, -1); + this.uniforms.uHSLightGroundColor.value = new Color(14793111).convertLinearToSRGB(); + this.uniforms.uHSLightSkyColor.value = new Color(14800590).convertLinearToSRGB(); + this.uniforms.uDirLightColor0.value = new Color(5919571).convertLinearToSRGB(); + this.uniforms.uDirLightColor1.value = new Color(1710104).convertLinearToSRGB(); + } +} + +// src/class/3d/shader/ShaderUtils.ts +var getSettingSafe = async (key2) => { + const value2 = await import_localforage2.default.getItem("settings_" + key2); + if (value2 == null && key2 === "shaderType") { + return "wiiu"; + } + return value2; +}; +function traverseAddShader(model, shaderType) { + model.traverse((n2) => { + const node = n2; + if (node.isMesh) { + traverseMesh(node, shaderType); + } + }); +} +async function traverseMesh(node, shaderType) { + const shaderSetting = shaderType || await getSettingSafe("shaderType"); + const originalMaterial = node.material; + const userData = node.geometry.userData; + if (userData.ignore !== undefined) { + if (userData.ignore === 1) + return; + } + let modulateType = userData.modulateType; + if (userData.modulateType === undefined) + console.warn(`Mesh "${node.name}" is missing "modulateType" in userData.`); + const lightEnable = modulateType > 5 ? false : true; + let materialParam = modulateType !== undefined ? modulateType && modulateType < 9 ? import_FFLShaderMaterial2.default.materialParams[modulateType] : import_FFLShaderMaterial2.default.materialParams[0] : import_FFLShaderMaterial2.default.materialParams[0]; + let modulateMode = userData.modulateMode === undefined ? 0 : userData.modulateMode; + let modulateColor; + if (!userData.modulateColor) { + console.warn(`Mesh "${node.name}" is missing "modulateColor" in userData.`); + modulateColor = new Vector4(1, 0, 0, 1); + } else { + modulateColor = new Vector4(...userData.modulateColor, 1); + } + ColorManagement.enabled = false; + const defines = {}; + if (originalMaterial.map) { + defines.USE_MAP = ""; + originalMaterial.map.colorSpace = LinearSRGBColorSpace; + originalMaterial.needsUpdate = true; + } + let side = originalMaterial.side; + if (userData.cullMode !== undefined) { + switch (userData.cullMode) { + case 0: + side = DoubleSide; + break; + case 1: + side = FrontSide; + break; + case 2: + side = BackSide; + break; + } + } + let finalMat; + const isUsingShader = await isShaderMaterial(); + let modulate = isUsingShader ? { + modulateMode, + modulateType, + lightEnable: shaderSetting === "lightDisabled" /* LightDisabled */ ? false : true + } : {}; + const params = { + color: new Color(...modulateColor), + ...modulate, + map: originalMaterial.map || undefined, + side + }; + let shaderMaterial = await getShaderMaterialFromShaderType(shaderSetting); + finalMat = new shaderMaterial(params); + node.material = finalMat; +} +async function isShaderMaterial(shader = undefined) { + let shaderType = shader || await getSettingSafe("shaderType"); + switch (shaderType) { + case "wiiu" /* WiiU */: + case "wiiu_blinn" /* WiiUBlinn */: + case "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */: + case "wiiu_toon" /* WiiUToon */: + case "switch" /* Switch */: + case "miitomo" /* Miitomo */: + case "miitomo_basic" /* MiitomoBasic */: + return true; + case "lightDisabled" /* LightDisabled */: + case "three_toon" /* ThreeToon */: + case "three_phong" /* ThreePhong */: + return false; + } +} +async function getShaderMaterialFromShaderType(type) { + const shaderType = type || await getSettingSafe("shaderType"); + switch (shaderType) { + case "wiiu" /* WiiU */: + return import_FFLShaderMaterial2.default; + case "lightDisabled" /* LightDisabled */: + return MeshBasicMaterial; + case "wiiu_blinn" /* WiiUBlinn */: + return FFLShaderBlinnMaterial; + case "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */: + return FFLShaderBrightMaterial; + case "wiiu_toon" /* WiiUToon */: + return FFLShaderToonMaterial; + case "switch" /* Switch */: + return import_FFLShaderMaterial2.default; + case "miitomo" /* Miitomo */: + return import_LUTShaderMaterial2.default; + case "miitomo_basic" /* MiitomoBasic */: + return LUTShaderPretendoMaterial; + case "three_toon" /* ThreeToon */: + return MeshToonMaterial; + case "three_phong" /* ThreePhong */: + return MeshPhongMaterial; + } +} +var ThreeMaterialStandardLights = (scene) => { + const intensity = Number(REVISION) >= 155 ? Math.PI : 1; + const ambientLight = new AmbientLight(new Color(0.73, 0.73, 0.73), intensity); + const directionalLight = new DirectionalLight(new Color(0.6, 0.6, 0.6), intensity); + directionalLight.position.set(-0.455, 0.348, 0.5); + ambientLight.name = "ambientLight"; + directionalLight.name = "directionalLight"; + scene.add(ambientLight, directionalLight); +}; +var ThreeMaterialToonLights = (scene) => { + const intensity = 2.5; + const ambientLight = new AmbientLight(new Color(0.73, 0.73, 0.73), intensity); + const directionalLight = new DirectionalLight(new Color(0.6, 0.6, 0.6), intensity); + directionalLight.position.set(-0.255, 0.348, 0.5); + ambientLight.name = "ambientLight"; + directionalLight.name = "directionalLight"; + scene.add(ambientLight, directionalLight); +}; +async function getSimpleMaterialAddLights(type) { + const shaderType = type || await getSettingSafe("shaderType"); + switch (shaderType) { + case "wiiu" /* WiiU */: + case "wiiu_blinn" /* WiiUBlinn */: + case "wiiu_ffliconwithbody" /* WiiUFFLIconWithBody */: + case "wiiu_toon" /* WiiUToon */: + case "switch" /* Switch */: + case "miitomo" /* Miitomo */: + case "miitomo_basic" /* MiitomoBasic */: + return; + case "lightDisabled" /* LightDisabled */: + case "three_phong" /* ThreePhong */: + return ThreeMaterialStandardLights; + case "three_toon" /* ThreeToon */: + return ThreeMaterialToonLights; + } +} +function cleanupLights(scene) { + let amb = scene.getObjectByName("ambientLight"); + let dir = scene.getObjectByName("directionalLight"); + if (amb) + scene.remove(amb); + if (dir) + scene.remove(dir); +} + +// src/constants/Extensions.ts +var ExtHatNameList = [ + "Cap", + "Beanie", + "Top Hat", + "Ribbon", + "Bow", + "Cat Ears", + "Straw Hat", + "Hijab", + "Bike Helmet" +]; +var ExtClothesList = ["LS+Pants", "SS+Shorts", "TT+Shorts"]; +var HatTypeList = [ + 1 /* HAT */, + 1 /* HAT */, + 1 /* HAT */, + 4 /* SIDE */, + 4 /* SIDE */, + 0 /* HEAD */, + 1 /* HAT */, + 6 /* BALD */, + 1 /* HAT */ +]; +var ClothesTypeList = [ + 0 /* COLOR_MIXED */, + 0 /* COLOR_MIXED */, + 0 /* COLOR_MIXED */, + 0 /* COLOR_MIXED */ +]; + +// src/util/allocateArray.ts +function allocateArray(size2, data2) { + if (data2.length > size2) + throw new RangeError(`Tried to fill ${data2.length} bytes into a ${size2}-byte array`); + let array = new Uint8Array(size2); + for (var i = 0;i < data2.length; i++) { + array[i] = data2[i]; + } + return array; +} + +// src/util/dataConvert.ts +function dataToBase64(data2) { + return btoa(String.fromCharCode.apply(null, data2)); +} +function dataToHex(data2) { + return Array.from(data2, (i) => i.toString(16).padStart(2, "0")).join(""); +} +function encodeUTF16LE(str) { + const buffer = new ArrayBuffer(str.length * 2); + const view = new DataView(buffer); + for (let i = 0;i < str.length; i++) { + view.setUint16(i * 2, str.charCodeAt(i), true); + } + return new Uint8Array(buffer); +} +function decodeUTF16LE(bytes) { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let result = ""; + for (let i = 0;i < view.byteLength; i += 2) { + result += String.fromCharCode(view.getUint16(i, true)); + } + return result; +} + +// src/util/Numbers.ts +var ArrayNum = (number) => Array.from(Array(number).keys()); +var RandomInt = (max) => Math.floor(Math.random() * max); +function randomizeUint8Array(arr) { + if (!(arr instanceof Uint8Array)) { + throw new TypeError("Expected a Uint8Array"); + } + function randomize() { + for (let i = 0;i < arr.length; i++) { + arr[i] = Math.floor(Math.random() * 256); + } + } + if (typeof window !== "undefined") { + if (window.crypto && window.crypto.getRandomValues) { + window.crypto.getRandomValues(arr); + } else + randomize(); + } else { + randomize(); + } + return arr; +} + +// src/class/struct/FFLStoreData.ts +var import_struct_fu = __toESM(require_struct_fu(), 1); +var FFLiCreateID = import_struct_fu.default.struct([ + import_struct_fu.default.ubit("flag_normal", 1), + import_struct_fu.default.ubit("flag_1", 1), + import_struct_fu.default.ubit("flag_temporary", 1), + import_struct_fu.default.ubit("flag_3", 1), + import_struct_fu.default.ubit("create_date1", 14), + import_struct_fu.default.ubit("create_date2", 14), + import_struct_fu.default.byte("base", 6) +]); +var FFLiAuthorID = import_struct_fu.default.struct([import_struct_fu.default.byte("data", 8)]); +var Ver3StoreData = import_struct_fu.default.struct([ + import_struct_fu.default.ubitLE("mii_version", 8), + import_struct_fu.default.ubitLE("copyable", 1), + import_struct_fu.default.ubitLE("ng_word", 1), + import_struct_fu.default.ubitLE("region_move", 2), + import_struct_fu.default.ubitLE("font_region", 2), + import_struct_fu.default.ubitLE("reserved_0", 2), + import_struct_fu.default.ubitLE("room_index", 4), + import_struct_fu.default.ubitLE("position_in_room", 4), + import_struct_fu.default.ubitLE("author_type", 4), + import_struct_fu.default.ubitLE("birth_platform", 3), + import_struct_fu.default.ubitLE("reserved_1"), + import_struct_fu.default.struct("author_id", [FFLiAuthorID]), + import_struct_fu.default.struct("create_id", [FFLiCreateID]), + import_struct_fu.default.byte("reserved_2", 2), + import_struct_fu.default.ubitLE("gender", 1), + import_struct_fu.default.ubitLE("birth_month", 4), + import_struct_fu.default.ubitLE("birth_day", 5), + import_struct_fu.default.ubitLE("favorite_color", 4), + import_struct_fu.default.ubitLE("favorite", 1), + import_struct_fu.default.ubitLE("padding_0", 1), + import_struct_fu.default.char16le("name", 20), + import_struct_fu.default.uint8("height"), + import_struct_fu.default.uint8("build"), + import_struct_fu.default.ubitLE("localonly", 1), + import_struct_fu.default.ubitLE("face_type", 4), + import_struct_fu.default.ubitLE("face_color", 3), + import_struct_fu.default.ubitLE("face_tex", 4), + import_struct_fu.default.ubitLE("face_make", 4), + import_struct_fu.default.ubitLE("hair_type", 8), + import_struct_fu.default.ubitLE("hair_color", 3), + import_struct_fu.default.ubitLE("hair_flip", 1), + import_struct_fu.default.ubitLE("padding_1", 4), + import_struct_fu.default.ubitLE("eye_type", 6), + import_struct_fu.default.ubitLE("eye_color", 3), + import_struct_fu.default.ubitLE("eye_scale", 4), + import_struct_fu.default.ubitLE("eye_aspect", 3), + import_struct_fu.default.ubitLE("eye_rotate", 5), + import_struct_fu.default.ubitLE("eye_x", 4), + import_struct_fu.default.ubitLE("eye_y", 5), + import_struct_fu.default.ubitLE("padding_2", 2), + import_struct_fu.default.ubitLE("eyebrow_type", 5), + import_struct_fu.default.ubitLE("eyebrow_color", 3), + import_struct_fu.default.ubitLE("eyebrow_scale", 4), + import_struct_fu.default.ubitLE("eyebrow_aspect", 3), + import_struct_fu.default.ubitLE("padding_3", 1), + import_struct_fu.default.ubitLE("eyebrow_rotate", 5), + import_struct_fu.default.ubitLE("eyebrow_x", 4), + import_struct_fu.default.ubitLE("eyebrow_y", 5), + import_struct_fu.default.ubitLE("padding_4", 2), + import_struct_fu.default.ubitLE("nose_type", 5), + import_struct_fu.default.ubitLE("nose_scale", 4), + import_struct_fu.default.ubitLE("nose_y", 5), + import_struct_fu.default.ubitLE("padding_5", 2), + import_struct_fu.default.ubitLE("mouth_type", 6), + import_struct_fu.default.ubitLE("mouth_color", 3), + import_struct_fu.default.ubitLE("mouth_scale", 4), + import_struct_fu.default.ubitLE("mouth_aspect", 3), + import_struct_fu.default.ubitLE("mouth_y", 5), + import_struct_fu.default.ubitLE("mustache_type", 3), + import_struct_fu.default.ubitLE("padding_6", 8), + import_struct_fu.default.ubitLE("beard_type", 3), + import_struct_fu.default.ubitLE("beard_color", 3), + import_struct_fu.default.ubitLE("beard_scale", 4), + import_struct_fu.default.ubitLE("beard_y", 5), + import_struct_fu.default.ubitLE("padding_7", 1), + import_struct_fu.default.ubitLE("glasses_type", 4), + import_struct_fu.default.ubitLE("glasses_color", 3), + import_struct_fu.default.ubitLE("glasses_scale", 4), + import_struct_fu.default.ubitLE("glass_y", 5), + import_struct_fu.default.ubitLE("mole_type", 1), + import_struct_fu.default.ubitLE("mole_scale", 4), + import_struct_fu.default.ubitLE("mole_x", 5), + import_struct_fu.default.ubitLE("mole_y", 5), + import_struct_fu.default.ubitLE("padding_8", 1), + import_struct_fu.default.char16le("creator", 20), + import_struct_fu.default.uint16le("padding_9"), + import_struct_fu.default.uint16("checksum") +]); +function calculateCRC16(storeData) { + const data2 = storeData.subarray(0, 94); + console.log(data2); + let crc = 0; + for (const byte of data2) { + for (let bit = 7;bit >= 0; bit--) { + const flag = (crc & 32768) != 0; + crc = (crc << 1 | byte >> bit & 1) ^ (flag ? 4129 : 0); + } + } + for (let i = 16;i > 0; i--) { + const flag = (crc & 32768) != 0; + crc = crc << 1 ^ (flag ? 4129 : 0); + } + return crc & 65535; +} + +// src/class/struct/MiiCreatorV3Data.ts +var import_struct_fu4 = __toESM(require_struct_fu(), 1); + +// src/class/struct/MiiCreatorV4Data.ts +var import_struct_fu3 = __toESM(require_struct_fu(), 1); + +// src/class/struct/RFLStoreData.ts +var import_struct_fu2 = __toESM(require_struct_fu(), 1); + +// src/constants/ColorTables.ts +var MiiFavoriteColorLookupTable = { + 0: 13770260, + 1: 16739865, + 2: 16767008, + 3: 7918112, + 4: 30768, + 5: 673980, + 6: 3975902, + 7: 16079485, + 8: 7547053, + 9: 4732952, + 10: 14737632, + 11: 1579028 +}; +var MiiFavoriteColorVec3Table = { + 0: [0.8235294117647058, 0.11764705882352941, 0.0784313725490196], + 1: [1, 0.43137254901960786, 0.09803921568627451], + 2: [1, 0.8470588235294118, 0.12549019607843137], + 3: [0.47058823529411764, 0.8235294117647058, 0.12549019607843137], + 4: [0, 0.47058823529411764, 0.18823529411764706], + 5: [0.0392156862745098, 0.2823529411764706, 0.7372549019607844], + 6: [0.23529411764705882, 0.6666666666666666, 0.8705882352941177], + 7: [0.9607843137254902, 0.35294117647058826, 0.49019607843137253], + 8: [0.45098039215686275, 0.1568627450980392, 0.6784313725490196], + 9: [0.2823529411764706, 0.2196078431372549, 0.09411764705882353], + 10: [0.8784313725490196, 0.8784313725490196, 0.8784313725490196], + 11: [0.09411764705882353, 0.09411764705882353, 0.0784313725490196] +}; +var MiiFavoriteColorIconTable = { + 0: { top: "#d21e14", bottom: "#630e09" }, + 1: { top: "#ff6e19", bottom: "#78340c" }, + 2: { top: "#ffd820", bottom: "#78660f" }, + 3: { top: "#78d220", bottom: "#38630f" }, + 4: { top: "#007830", bottom: "#003817" }, + 5: { top: "#0a48bc", bottom: "#052258" }, + 6: { top: "#3caade", bottom: "#1c5068" }, + 7: { top: "#f55a7d", bottom: "#732a3b" }, + 8: { top: "#7328ad", bottom: "#361351" }, + 9: { top: "#483818", bottom: "#221a0b" }, + 10: { top: "#e0e0e0", bottom: "#696969" }, + 11: { top: "#181814", bottom: "#0b0b09" } +}; +var MiiSkinColorTable = { + 0: "#FFD3AD", + 1: "#FEB66B", + 2: "#DE7942", + 3: "#FFAA8C", + 4: "#AD5129", + 5: "#632C18", + 6: "#ffbea5", + 7: "#ffc58f", + 8: "#8c3c23", + 9: "#3c2d23" +}; +var SwitchMiiColorTable = [ + "#2d2828", + "#402010", + "#5c180a", + "#7c3a14", + "#787880", + "#4e3e10", + "#885818", + "#d0a04a", + "#000000", + "#6c7070", + "#663c2c", + "#605e30", + "#4654a8", + "#387058", + "#603810", + "#a81008", + "#203068", + "#a86000", + "#787068", + "#d85208", + "#f00c08", + "#f54848", + "#f09a74", + "#8c5040", + "#842626", + "#ff7366", + "#ffa6a6", + "#ffc0ba", + "#732e3b", + "#991f3d", + "#8a173e", + "#b53e42", + "#c71e56", + "#b05381", + "#c7546e", + "#fa7597", + "#fcacc9", + "#ffc9d8", + "#311c40", + "#37283d", + "#4c184d", + "#6f42b3", + "#855cb8", + "#c083cc", + "#a893c9", + "#c5ace6", + "#eebefa", + "#d2c5ed", + "#191f40", + "#123f66", + "#2a82d4", + "#57b4f2", + "#7ac5de", + "#89a6fa", + "#84bdfa", + "#a1e3ff", + "#0b2e36", + "#013d3b", + "#0d4f59", + "#236663", + "#307e8c", + "#4faeb0", + "#7ac49e", + "#7fd4c0", + "#87e5b6", + "#0a4a35", + "#437a00", + "#027562", + "#369970", + "#4bad1a", + "#92bf0a", + "#63c788", + "#9ee042", + "#96de7e", + "#bbf2aa", + "#99932b", + "#a69563", + "#ccc039", + "#ccb987", + "#d9cc82", + "#d5d96f", + "#d5e683", + "#d8fa9d", + "#7d4500", + "#e6bb7a", + "#fee24a", + "#fade82", + "#f7ea9c", + "#faf89b", + "#a64d1e", + "#ff960d", + "#d19b69", + "#ffb266", + "#ffc28c", + "#e5cfb1", + "#414141", + "#9b9b9b", + "#bebebe", + "#dcd7cd", + "#ffffff" +]; +var SwitchMiiColorTableLip = [ + "#171414", + "#201008", + "#2e0c05", + "#4a230c", + "#54545a", + "#271f08", + "#52350e", + "#b18028", + "#000000", + "#4c4e4e", + "#331e16", + "#3a381d", + "#2a3265", + "#274e3e", + "#301c08", + "#650a05", + "#101834", + "#764300", + "#544e49", + "#823018", + "#780c0c", + "#882028", + "#dc7850", + "#461e0a", + "#4f1717", + "#99453d", + "#e68585", + "#e6a19b", + "#451c23", + "#5c1325", + "#530e25", + "#6d2528", + "#771234", + "#6a324d", + "#773242", + "#af526a", + "#e38cac", + "#e6abbb", + "#190e20", + "#1c141f", + "#260c27", + "#43286b", + "#50376e", + "#865c8f", + "#76678d", + "#ab90cf", + "#d4a0e1", + "#b8aad5", + "#0d1020", + "#092033", + "#1d5b94", + "#3297da", + "#5cadc8", + "#6786e1", + "#629fe1", + "#80c7e6", + "#06171b", + "#011f1e", + "#07282d", + "#184745", + "#225862", + "#308b8d", + "#60b087", + "#63bfa9", + "#69ce9b", + "#05251b", + "#284900", + "#01463b", + "#266b4e", + "#2c8a00", + "#6e9900", + "#47b36f", + "#82ca1f", + "#7ac860", + "#9eda8c", + "#6b671e", + "#746845", + "#a39816", + "#b8a36d", + "#c3b565", + "#bfc351", + "#bdcf64", + "#bce17d", + "#4b2900", + "#cfa15a", + "#e5c622", + "#e1c35f", + "#ded07c", + "#e1df7a", + "#642e12", + "#cc780a", + "#bc824c", + "#e69240", + "#e6a469", + "#ceb696", + "#212121", + "#7c7c7c", + "#ababab", + "#c6c1b6", + "#d9d9d9" +]; +var SwitchMiiColorTableSRGB = [ + [0.1764706, 0.1568628, 0.1568628], + [0.2509804, 0.1254902, 0.0627451], + [0.3607844, 0.0941177, 0.0392157], + [0.4862746, 0.227451, 0.0784314], + [0.4705883, 0.4705883, 0.5019608], + [0.3058824, 0.2431373, 0.0627451], + [0.5333334, 0.3450981, 0.0941177], + [0.8156863, 0.627451, 0.2901961], + [0, 0, 0], + [0.4235295, 0.4392157, 0.4392157], + [0.4, 0.2352942, 0.1725491], + [0.3764706, 0.3686275, 0.1882353], + [0.2745099, 0.3294118, 0.6588236], + [0.2196079, 0.4392157, 0.3450981], + [0.3764706, 0.2196079, 0.0627451], + [0.6588236, 0.0627451, 0.0313726], + [0.1254902, 0.1882353, 0.4078432], + [0.6588236, 0.3764706, 0], + [0.4705883, 0.4392157, 0.4078432], + [0.8470589, 0.3215687, 0.0313726], + [0.9411765, 0.0470589, 0.0313726], + [0.9607844, 0.282353, 0.282353], + [0.9411765, 0.6039216, 0.454902], + [0.5490197, 0.3137255, 0.2509804], + [0.5176471, 0.1490197, 0.1490197], + [1, 0.4509804, 0.4], + [1, 0.6509804, 0.6509804], + [1, 0.7529412, 0.7294118], + [0.4509804, 0.1803922, 0.2313726], + [0.6, 0.1215687, 0.2392157], + [0.5411765, 0.0901961, 0.2431373], + [0.709804, 0.2431373, 0.2588236], + [0.7803922, 0.1176471, 0.337255], + [0.6901961, 0.3254902, 0.5058824], + [0.7803922, 0.3294118, 0.4313726], + [0.9803922, 0.4588236, 0.5921569], + [0.9882353, 0.6745099, 0.7882353], + [1, 0.7882353, 0.8470589], + [0.1921569, 0.109804, 0.2509804], + [0.2156863, 0.1568628, 0.2392157], + [0.2980393, 0.0941177, 0.3019608], + [0.4352942, 0.2588236, 0.7019608], + [0.5215687, 0.3607844, 0.7215687], + [0.7529412, 0.5137255, 0.8], + [0.6588236, 0.5764706, 0.7882353], + [0.7725491, 0.6745099, 0.9019608], + [0.9333334, 0.7450981, 0.9803922], + [0.8235295, 0.7725491, 0.9294118], + [0.0980393, 0.1215687, 0.2509804], + [0.0705883, 0.2470589, 0.4], + [0.1647059, 0.509804, 0.8313726], + [0.3411765, 0.7058824, 0.9490197], + [0.4784314, 0.7725491, 0.8705883], + [0.537255, 0.6509804, 0.9803922], + [0.5176471, 0.7411765, 0.9803922], + [0.6313726, 0.8901961, 1], + [0.0431373, 0.1803922, 0.2117648], + [0.0039216, 0.2392157, 0.2313726], + [0.0509804, 0.309804, 0.3490197], + [0.137255, 0.4, 0.3882353], + [0.1882353, 0.4941177, 0.5490197], + [0.309804, 0.682353, 0.6901961], + [0.4784314, 0.7686275, 0.6196079], + [0.4980393, 0.8313726, 0.7529412], + [0.5294118, 0.8980393, 0.7137255], + [0.0392157, 0.2901961, 0.2078432], + [0.2627451, 0.4784314, 0], + [0.0078432, 0.4588236, 0.3843138], + [0.2117648, 0.6, 0.4392157], + [0.2941177, 0.6784314, 0.1019608], + [0.5725491, 0.7490197, 0.0392157], + [0.3882353, 0.7803922, 0.5333334], + [0.6196079, 0.8784314, 0.2588236], + [0.5882353, 0.8705883, 0.4941177], + [0.7333334, 0.9490197, 0.6666667], + [0.6, 0.5764706, 0.1686275], + [0.6509804, 0.5843138, 0.3882353], + [0.8, 0.7529412, 0.2235295], + [0.8, 0.7254902, 0.5294118], + [0.8509804, 0.8, 0.509804], + [0.8352942, 0.8509804, 0.4352942], + [0.8352942, 0.9019608, 0.5137255], + [0.8470589, 0.9803922, 0.6156863], + [0.4901961, 0.2705883, 0], + [0.9019608, 0.7333334, 0.4784314], + [0.9960785, 0.8862746, 0.2901961], + [0.9803922, 0.8705883, 0.509804], + [0.9686275, 0.9176471, 0.6117648], + [0.9803922, 0.9725491, 0.6078432], + [0.6509804, 0.3019608, 0.1176471], + [1, 0.5882353, 0.0509804], + [0.8196079, 0.6078432, 0.4117648], + [1, 0.6980393, 0.4], + [1, 0.7607844, 0.5490197], + [0.8980393, 0.8117648, 0.6941177], + [0.254902, 0.254902, 0.254902], + [0.6078432, 0.6078432, 0.6078432], + [0.7450981, 0.7450981, 0.7450981], + [0.8627451, 0.8431373, 0.8039216], + [1, 1, 1] +]; +var MiiSwitchSkinColorList = { + 0: "#ffd3ad", + 1: "#ffb66b", + 2: "#de7942", + 3: "#ffaa8c", + 4: "#ad5129", + 5: "#632c18", + 6: "#ffbea5", + 7: "#ffc58f", + 8: "#8c3c23", + 9: "#3c2d23" +}; +var MiiSwitchSkinColorSRGB = [ + [1, 0.8274509906768799, 0.6784313917160034], + [1, 0.7137255072593689, 0.41960790753364563], + [0.8705883026123047, 0.4745098948478699, 0.25882360339164734], + [1, 0.6666666865348816, 0.5490196943283081], + [0.6784313917160034, 0.3176470994949341, 0.16078439354896545], + [0.38823530077934265, 0.17254909873008728, 0.09411770105361938], + [1, 0.7450981140136719, 0.64705890417099], + [1, 0.7725490927696228, 0.5607843995094299], + [0.5490196943283081, 0.2352941930294037, 0.137254998087883], + [0.2352941930294037, 0.1764705926179886, 0.137254998087883] +]; +var ToVer3GlassTypeTable = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 1, + 2, + 1, + 3, + 7, + 7, + 6, + 7, + 8, + 7, + 7 +]; +var ToVer3HairColorTable = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 0, + 4, + 3, + 5, + 4, + 4, + 6, + 2, + 0, + 6, + 4, + 3, + 2, + 2, + 7, + 3, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 0, + 0, + 4, + 4, + 4, + 4, + 4, + 4, + 0, + 0, + 0, + 4, + 4, + 4, + 4, + 4, + 4, + 5, + 5, + 5, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 5, + 7, + 5, + 7, + 7, + 7, + 7, + 7, + 6, + 7, + 7, + 7, + 7, + 7, + 3, + 7, + 7, + 7, + 7, + 7, + 0, + 4, + 4, + 4, + 4 +]; +var ToVer3EyeColorTable = [ + 0, + 2, + 2, + 2, + 1, + 3, + 2, + 3, + 0, + 1, + 2, + 3, + 4, + 5, + 2, + 2, + 4, + 2, + 1, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 0, + 0, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 1, + 0, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 0, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 2, + 2, + 3, + 3, + 3, + 3, + 2, + 2, + 2, + 2, + 2, + 1, + 1, + 1, + 1, + 1, + 1 +]; +var ToVer3MouthColorTable = [ + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 3, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 1, + 4, + 4, + 4, + 0, + 1, + 2, + 3, + 4, + 4, + 2, + 3, + 3, + 4, + 4, + 4, + 4, + 1, + 4, + 4, + 2, + 3, + 3, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 3, + 3, + 3, + 4, + 4, + 4, + 3, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 4, + 3, + 3, + 3, + 3, + 4, + 4, + 4, + 4, + 3, + 3, + 3, + 3, + 3, + 3, + 4, + 4, + 3, + 3, + 3, + 3, + 3, + 3, + 4, + 3, + 3, + 3, + 3, + 3, + 4, + 0, + 3, + 3, + 3, + 3, + 4, + 3, + 3, + 3, + 3 +]; +var ToVer3GlassColorTable = [ + 0, + 1, + 1, + 1, + 5, + 1, + 1, + 4, + 0, + 5, + 1, + 1, + 3, + 5, + 1, + 2, + 3, + 4, + 5, + 4, + 2, + 2, + 4, + 4, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 3, + 0, + 0, + 0, + 5, + 5, + 5, + 5, + 5, + 5, + 0, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 1, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 5, + 5, + 5, + 5, + 5, + 5 +]; +var ToVer3FacelineColorTable = [0, 1, 2, 3, 4, 5, 0, 1, 5, 5]; +var Ver3FacelineColorTable = [0, 1, 2, 3, 4, 5]; +var Ver3HairColorTable = [8, 1, 2, 3, 4, 5, 6, 7]; +var Ver3EyeColorTable = [8, 9, 10, 11, 12, 13]; +var Ver3MouthColorTable = [19, 20, 21, 22, 23]; +var Ver3GlassColorTable = [8, 14, 15, 16, 17, 18, 0]; +var ForbiddenShirtPantColors = [, 7, 22, 78, 79, 84, 91, 92, 93, 94]; + +// src/class/struct/RFLStoreData.ts +var RFLCreateID = import_struct_fu2.default.struct([import_struct_fu2.default.uint8("data", 8)]); +var RFLCharData = import_struct_fu2.default.struct([ + import_struct_fu2.default.ubit("padding0", 1), + import_struct_fu2.default.ubit("gender", 1), + import_struct_fu2.default.ubit("birthMonth", 4), + import_struct_fu2.default.ubit("birthDay", 5), + import_struct_fu2.default.ubit("favoriteColor", 4), + import_struct_fu2.default.ubit("favorite", 1), + import_struct_fu2.default.char16be("name", 20), + import_struct_fu2.default.uint8("height"), + import_struct_fu2.default.uint8("build"), + import_struct_fu2.default.struct("create_id", [RFLCreateID]), + import_struct_fu2.default.ubit("faceType", 3), + import_struct_fu2.default.ubit("faceColor", 3), + import_struct_fu2.default.ubit("faceTex", 4), + import_struct_fu2.default.ubit("padding_2", 3), + import_struct_fu2.default.ubit("localonly", 1), + import_struct_fu2.default.ubit("type", 2), + import_struct_fu2.default.ubit("hairType", 7), + import_struct_fu2.default.ubit("hairColor", 3), + import_struct_fu2.default.ubit("hairFlip", 1), + import_struct_fu2.default.ubit("padding_3", 5), + import_struct_fu2.default.ubit("eyebrowType", 5), + import_struct_fu2.default.ubit("eyebrowRotate", 5), + import_struct_fu2.default.ubit("padding_4", 6), + import_struct_fu2.default.ubit("eyebrowColor", 3), + import_struct_fu2.default.ubit("eyebrowScale", 4), + import_struct_fu2.default.ubit("eyebrowY", 5), + import_struct_fu2.default.ubit("eyebrowX", 4), + import_struct_fu2.default.ubit("eyeType", 6), + import_struct_fu2.default.ubit("eyeRotate", 5), + import_struct_fu2.default.ubit("eyeY", 5), + import_struct_fu2.default.ubit("eyeColor", 3), + import_struct_fu2.default.ubit("eyeScale", 4), + import_struct_fu2.default.ubit("eyeX", 4), + import_struct_fu2.default.ubit("padding_5", 5), + import_struct_fu2.default.ubit("noseType", 4), + import_struct_fu2.default.ubit("noseScale", 4), + import_struct_fu2.default.ubit("noseY", 5), + import_struct_fu2.default.ubit("padding_6", 3), + import_struct_fu2.default.ubit("mouthType", 5), + import_struct_fu2.default.ubit("mouthColor", 2), + import_struct_fu2.default.ubit("mouthScale", 4), + import_struct_fu2.default.ubit("mouthY", 5), + import_struct_fu2.default.ubit("glassType", 4), + import_struct_fu2.default.ubit("glassColor", 3), + import_struct_fu2.default.ubit("glassScale", 4), + import_struct_fu2.default.ubit("glassY", 5), + import_struct_fu2.default.ubit("mustacheType", 2), + import_struct_fu2.default.ubit("beardType", 2), + import_struct_fu2.default.ubit("beardColor", 3), + import_struct_fu2.default.ubit("beardScale", 4), + import_struct_fu2.default.ubit("beardY", 5), + import_struct_fu2.default.ubit("moleType", 1), + import_struct_fu2.default.ubit("moleScale", 4), + import_struct_fu2.default.ubit("moleY", 5), + import_struct_fu2.default.ubit("moleX", 5), + import_struct_fu2.default.ubit("padding_8", 1), + import_struct_fu2.default.char16be("creatorName", 20) +]); +var RFLStoreData = import_struct_fu2.default.struct([ + import_struct_fu2.default.struct([RFLCharData]), + import_struct_fu2.default.uint16("checksum") +]); +var Ver1ToVer3FacelineTex = [ + [0, 0], + [1, 0], + [6, 0], + [9, 0], + [0, 5], + [0, 2], + [0, 3], + [0, 7], + [0, 8], + [10, 0], + [0, 9], + [0, 11] +]; +function RFLStoreDataToMiiCreatorV4Data(input) { + const output = EmptyMiiCreatorV4Data(); + console.log("input rfl data:", input); + output.beardColor = Ver3HairColorTable[input.beardColor]; + output.beardType = input.beardType; + output.birthDay = input.birthDay; + output.birthMonth = input.birthMonth; + output.build = input.build; + output.createId.set(RFLCreateID.pack(input.create_id), 0); + output.creator = input.creatorName; + output.eyeColor = Ver3EyeColorTable[input.eyeColor]; + output.eyeRotate = input.eyeRotate; + output.eyeScale = input.eyeScale; + output.eyeType = input.eyeType; + output.eyeX = input.eyeX; + output.eyeY = input.eyeY; + output.eyebrowColor = Ver3HairColorTable[input.eyebrowColor]; + output.eyebrowRotate = input.eyebrowRotate; + output.eyebrowScale = input.eyebrowScale; + output.eyebrowType = input.eyebrowType; + output.eyebrowX = input.eyebrowX; + output.eyebrowY = input.eyebrowY; + output.facelineColor = Ver3FacelineColorTable[input.faceColor]; + output.facelineType = input.faceType; + output.facelineMake = Ver1ToVer3FacelineTex[input.faceTex][0]; + output.facelineWrinkle = Ver1ToVer3FacelineTex[input.faceTex][1]; + output.favorite = input.favorite; + output.favoriteColor = input.favoriteColor; + output.gender = input.gender; + output.glassColor = Ver3GlassColorTable[input.glassColor]; + output.glassScale = input.glassScale; + output.glassType = input.glassType; + output.glassY = input.glassY; + output.hairColor = Ver3HairColorTable[input.hairColor]; + output.hairFlip = input.hairFlip; + output.hairType = input.hairType; + output.height = input.height; + output.moleScale = input.moleScale; + output.moleType = input.moleType; + output.moleX = input.moleX; + output.moleY = input.moleY; + output.mouthColor = Ver3MouthColorTable[input.mouthColor]; + output.mouthScale = input.mouthScale; + output.mouthType = input.mouthType; + output.mouthY = input.mouthY; + output.mustacheScale = input.beardScale; + output.mustacheType = input.mustacheType; + output.mustacheY = input.beardY; + output.noseScale = input.noseScale; + output.noseType = input.noseType; + output.noseY = input.noseY; + output.nickname = input.name; + output.creator = input.creatorName; + output.facePaintColor = -1; + output.hatCommonColor = -1; + output.hatFavoriteColor = -1; + output.hatType = -1; + output.wigType = -1; + output.pantsColor = -1; + output.personality = -1; + output.shirtColor = -1; + return output; +} + +// src/class/struct/MiiCreatorV4Data.ts +var MiiCreatorV4Data = import_struct_fu3.default.struct([ + import_struct_fu3.default.uint8("miicVersion"), + import_struct_fu3.default.uint8("originPlatform"), + import_struct_fu3.default.byte("authorId", 8), + import_struct_fu3.default.byte("createId", 10), + import_struct_fu3.default.char16le("creator", 20), + import_struct_fu3.default.char16le("nickname", 20), + import_struct_fu3.default.uint8("beardColor"), + import_struct_fu3.default.uint8("beardType"), + import_struct_fu3.default.uint8("birthDay"), + import_struct_fu3.default.uint8("birthMonth"), + import_struct_fu3.default.uint16("birthYear"), + import_struct_fu3.default.uint8("build"), + import_struct_fu3.default.uint8("eyeAspect"), + import_struct_fu3.default.uint8("eyebrowAspect"), + import_struct_fu3.default.uint8("eyebrowColor"), + import_struct_fu3.default.uint8("eyebrowRotate"), + import_struct_fu3.default.uint8("eyebrowScale"), + import_struct_fu3.default.uint8("eyebrowType"), + import_struct_fu3.default.uint8("eyebrowX"), + import_struct_fu3.default.uint8("eyebrowY"), + import_struct_fu3.default.uint8("eyeColor"), + import_struct_fu3.default.uint8("eyeRotate"), + import_struct_fu3.default.uint8("eyeScale"), + import_struct_fu3.default.uint8("eyeType"), + import_struct_fu3.default.uint8("eyeX"), + import_struct_fu3.default.uint8("eyeY"), + import_struct_fu3.default.uint8("facelineColor"), + import_struct_fu3.default.uint8("facelineMake"), + import_struct_fu3.default.uint8("facelineType"), + import_struct_fu3.default.uint8("facelineWrinkle"), + import_struct_fu3.default.uint8("facePaintColor"), + import_struct_fu3.default.uint8("favorite"), + import_struct_fu3.default.uint8("favoriteColor"), + import_struct_fu3.default.uint8("fontRegion"), + import_struct_fu3.default.uint8("gender"), + import_struct_fu3.default.uint8("glassColor"), + import_struct_fu3.default.uint8("glassScale"), + import_struct_fu3.default.uint8("glassType"), + import_struct_fu3.default.uint8("glassY"), + import_struct_fu3.default.uint8("hairColor"), + import_struct_fu3.default.uint8("hairFlip"), + import_struct_fu3.default.uint8("hairType"), + import_struct_fu3.default.uint8("hatFavoriteColor"), + import_struct_fu3.default.uint8("hatCommonColor"), + import_struct_fu3.default.uint8("hatType"), + import_struct_fu3.default.uint8("height"), + import_struct_fu3.default.uint8("wigType"), + import_struct_fu3.default.uint8("moleScale"), + import_struct_fu3.default.uint8("moleType"), + import_struct_fu3.default.uint8("moleX"), + import_struct_fu3.default.uint8("moleY"), + import_struct_fu3.default.uint8("mouthAspect"), + import_struct_fu3.default.uint8("mouthColor"), + import_struct_fu3.default.uint8("mouthScale"), + import_struct_fu3.default.uint8("mouthType"), + import_struct_fu3.default.uint8("mouthY"), + import_struct_fu3.default.uint8("mustacheScale"), + import_struct_fu3.default.uint8("mustacheType"), + import_struct_fu3.default.uint8("mustacheY"), + import_struct_fu3.default.uint8("noseScale"), + import_struct_fu3.default.uint8("noseType"), + import_struct_fu3.default.uint8("noseY"), + import_struct_fu3.default.uint8("pantsColor"), + import_struct_fu3.default.uint8("personality"), + import_struct_fu3.default.uint8("regionMove"), + import_struct_fu3.default.uint8("shirtColor"), + import_struct_fu3.default.uint8("special"), + import_struct_fu3.default.uint8("temporary"), + import_struct_fu3.default.uint8("eyeSclera"), + import_struct_fu3.default.uint8("clothesType"), + import_struct_fu3.default.uint8("shoesColor") +]); +var MiiCreatorV4AppendData = import_struct_fu3.default.struct([ + import_struct_fu3.default.uint8("miicVersion"), + import_struct_fu3.default.uint8("eyebrowColor"), + import_struct_fu3.default.uint8("eyeColor"), + import_struct_fu3.default.uint8("facelineColor"), + import_struct_fu3.default.uint8("glassColor"), + import_struct_fu3.default.uint8("glassType"), + import_struct_fu3.default.uint8("hairColor"), + import_struct_fu3.default.uint8("mouthColor"), + import_struct_fu3.default.uint8("hatType"), + import_struct_fu3.default.uint8("facePaintColor"), + import_struct_fu3.default.uint8("hatCommonColor"), + import_struct_fu3.default.uint8("hatFavoriteColor"), + import_struct_fu3.default.uint8("pantsColor"), + import_struct_fu3.default.uint8("personality"), + import_struct_fu3.default.uint8("shirtColor"), + import_struct_fu3.default.uint8("birthYear"), + import_struct_fu3.default.uint8("wigType"), + import_struct_fu3.default.uint8("originPlatform"), + import_struct_fu3.default.uint8("eyeSclera"), + import_struct_fu3.default.uint8("clothesType"), + import_struct_fu3.default.uint8("shoesColor") +]); +var EmptyMiiCreatorData = { + miicVersion: 4, + originPlatform: 5 /* Mii_Creator_v4 */, + authorId: new Uint8Array(8), + createId: new Uint8Array(10), + creator: "???", + nickname: "MISSING", + beardColor: 0, + beardType: 0, + birthDay: 0, + birthMonth: 0, + birthYear: 0, + build: 0, + eyebrowAspect: 3, + eyebrowColor: 0, + eyebrowRotate: 0, + eyebrowScale: 0, + eyebrowType: 0, + eyebrowX: 0, + eyebrowY: 0, + eyeAspect: 3, + eyeColor: 0, + eyeRotate: 0, + eyeScale: 0, + eyeType: 0, + eyeX: 0, + eyeY: 0, + facelineColor: 0, + facelineMake: 0, + facelineType: 0, + facelineWrinkle: 0, + facePaintColor: -1, + favorite: 0, + favoriteColor: 0, + fontRegion: 0, + gender: 0, + glassColor: 0, + glassScale: 0, + glassType: 0, + glassY: 0, + hairColor: 0, + hairFlip: 0, + hairType: 0, + hatFavoriteColor: -1, + hatCommonColor: -1, + hatType: -1, + height: 0, + wigType: -1, + moleScale: 0, + moleType: 0, + moleX: 0, + moleY: 0, + mouthAspect: 3, + mouthColor: 0, + mouthScale: 0, + mouthType: 0, + mouthY: 0, + mustacheScale: 0, + mustacheType: 0, + mustacheY: 0, + noseScale: 0, + noseType: 0, + noseY: 0, + pantsColor: -1, + personality: -1, + regionMove: 0, + shirtColor: -1, + special: 0, + temporary: 0, + eyeSclera: 0, + clothesType: -1, + shoesColor: -1 +}; +var EmptyMiiCreatorV4Data = () => ({ ...EmptyMiiCreatorData }); +function MiiCreatorV4DataToFFSD(input, pack = false, appendBytes = false) { + const output = { + author_id: FFLiAuthorID.unpack(input.authorId), + author_type: 0, + beard_color: ToVer3HairColorTable[input.beardColor], + beard_scale: input.mustacheScale, + beard_type: input.beardType, + beard_y: input.mustacheY, + birth_day: input.birthDay, + birth_month: input.birthMonth, + birth_platform: Math.max(2, Math.min(input.originPlatform, 3 /* FFL_Wii_U */)), + build: input.build, + checksum: 0, + copyable: 1, + create_id: FFLiCreateID.unpack(input.createId), + creator: input.creator, + eye_aspect: input.eyeAspect, + eye_color: ToVer3EyeColorTable[input.eyeColor], + eye_rotate: input.eyeRotate, + eye_scale: input.eyeScale, + eye_type: input.eyeType, + eye_x: input.eyeX, + eye_y: input.eyeY, + eyebrow_aspect: input.eyebrowAspect, + eyebrow_color: ToVer3HairColorTable[input.eyebrowColor], + eyebrow_rotate: input.eyebrowRotate, + eyebrow_scale: input.eyebrowScale, + eyebrow_type: input.eyebrowType, + eyebrow_x: input.eyebrowX, + eyebrow_y: input.eyebrowY, + face_color: ToVer3FacelineColorTable[input.facelineColor], + face_make: input.facelineMake, + face_tex: input.facelineWrinkle, + face_type: input.facelineType, + favorite: input.favorite, + favorite_color: input.favoriteColor, + font_region: input.fontRegion, + gender: input.gender, + glass_y: input.glassY, + glasses_color: ToVer3GlassColorTable[input.glassColor], + glasses_scale: input.glassScale, + glasses_type: ToVer3GlassTypeTable[input.glassType], + hair_color: ToVer3HairColorTable[input.hairColor], + hair_flip: input.hairFlip, + hair_type: input.hairType, + height: input.height, + localonly: 0, + mii_version: 3 /* FFL_Wii_U */, + mole_scale: input.moleScale, + mole_type: input.moleType, + mole_x: input.moleX, + mole_y: input.moleY, + mouth_aspect: input.mouthAspect, + mouth_color: ToVer3MouthColorTable[input.mouthColor], + mouth_scale: input.mouthScale, + mouth_type: input.mouthType, + mouth_y: input.mouthY, + mustache_type: input.mustacheType, + name: input.nickname, + ng_word: 0, + nose_scale: input.noseScale, + nose_type: input.noseType, + nose_y: input.noseY, + position_in_room: 0, + room_index: 0, + region_move: 0 + }; + output.create_id.flag_normal = Number(!input.special); + output.checksum = calculateCRC16(Ver3StoreData.pack(output)); + if (pack) { + if (appendBytes) { + const ffsdOutput = Ver3StoreData.pack(output); + const appendedBytes = MiiCreatorV4AppendData.pack(input); + const finalArray = new Uint8Array(ffsdOutput.length + appendedBytes.length); + finalArray.set(ffsdOutput, 0); + finalArray.set(appendedBytes, ffsdOutput.length); + return finalArray; + } + return Ver3StoreData.pack(output); + } else + return output; +} +var validationThing = { + beardColor: { type: 0 /* Number */, default: 0, min: 0, max: 99 }, + beardType: { type: 0 /* Number */, default: 0, min: 0, max: 5 }, + build: { type: 0 /* Number */, default: 64, min: 0, max: 127 }, + eyeAspect: { type: 0 /* Number */, default: 3, min: 0, max: 6 }, + eyeColor: { type: 0 /* Number */, default: 8, min: 0, max: 99 }, + eyeRotate: { type: 0 /* Number */, default: 4, min: 0, max: 7 }, + eyeScale: { type: 0 /* Number */, default: 4, min: 0, max: 7 }, + eyeSclera: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + eyeType: { type: 0 /* Number */, default: 2, min: 0, max: 59 }, + eyeX: { type: 0 /* Number */, default: 2, min: 0, max: 12 }, + eyeY: { type: 0 /* Number */, default: 12, min: 0, max: 18 }, + eyebrowAspect: { type: 0 /* Number */, default: 3, min: 0, max: 6 }, + eyebrowColor: { type: 0 /* Number */, default: 1, min: 0, max: 99 }, + eyebrowRotate: { type: 0 /* Number */, default: 6, min: 0, max: 11 }, + eyebrowScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + eyebrowType: { type: 0 /* Number */, default: 6, min: 0, max: 24 }, + eyebrowX: { type: 0 /* Number */, default: 2, min: 0, max: 12 }, + eyebrowY: { type: 0 /* Number */, default: 10, min: 3, max: 18 }, + facelineColor: { type: 0 /* Number */, default: 0, min: 0, max: 9 }, + facelineMake: { type: 0 /* Number */, default: 0, min: 0, max: 11 }, + facelineType: { type: 0 /* Number */, default: 0, min: 0, max: 11 }, + facelineWrinkle: { type: 0 /* Number */, default: 0, min: 0, max: 11 }, + favoriteColor: { type: 0 /* Number */, default: 0, min: 0, max: 11 }, + fontRegion: { type: 0 /* Number */, default: 0, min: 0, max: 3 }, + gender: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + glassColor: { type: 0 /* Number */, default: 8, min: 0, max: 99 }, + glassScale: { type: 0 /* Number */, default: 4, min: 0, max: 7 }, + glassType: { type: 0 /* Number */, default: 0, min: 0, max: 19 }, + glassY: { type: 0 /* Number */, default: 10, min: 0, max: 20 }, + hairColor: { type: 0 /* Number */, default: 1, min: 0, max: 99 }, + hairFlip: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + hairType: { type: 0 /* Number */, default: 33, min: 0, max: 131 }, + height: { type: 0 /* Number */, default: 64, min: 0, max: 127 }, + miicVersion: { type: 0 /* Number */, default: 4, min: 0, max: 4 }, + moleScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + moleType: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + moleX: { type: 0 /* Number */, default: 2, min: 0, max: 16 }, + moleY: { type: 0 /* Number */, default: 20, min: 0, max: 30 }, + mouthAspect: { type: 0 /* Number */, default: 3, min: 0, max: 6 }, + mouthColor: { type: 0 /* Number */, default: 19, min: 0, max: 99 }, + mouthScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + mouthType: { type: 0 /* Number */, default: 23, min: 0, max: 35 }, + mouthY: { type: 0 /* Number */, default: 13, min: 0, max: 18 }, + mustacheScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + mustacheType: { type: 0 /* Number */, default: 0, min: 0, max: 5 }, + mustacheY: { type: 0 /* Number */, default: 10, min: 0, max: 16 }, + creator: { type: 1 /* String */, default: "", min: 0, max: 10 }, + nickname: { type: 1 /* String */, default: "Mii", min: 1, max: 10 }, + noseScale: { type: 0 /* Number */, default: 4, min: 0, max: 8 }, + noseType: { type: 0 /* Number */, default: 1, min: 0, max: 17 }, + noseY: { type: 0 /* Number */, default: 9, min: 0, max: 18 }, + regionMove: { type: 0 /* Number */, default: 0, min: 0, max: 3 }, + authorId: { + type: 2 /* Array */, + default: [0, 0, 0, 0, 0, 0, 0, 0], + size: 8, + min: 0, + max: 255 + }, + birthDay: { type: 0 /* Number */, default: 0, min: 0, max: 31 }, + birthMonth: { type: 0 /* Number */, default: 0, min: 0, max: 12 }, + birthYear: { type: 0 /* Number */, default: 0, min: 0, max: 9999 }, + createId: { + type: 2 /* Array */, + default: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + size: 10, + min: 0, + max: 255 + }, + facePaintColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + favorite: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + hatCommonColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + hatFavoriteColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + hatType: { type: 0 /* Number */, default: -1, min: -1, max: 9 }, + wigType: { type: 0 /* Number */, default: -1, min: -1, max: 254 }, + clothesType: { type: 0 /* Number */, default: -1, min: -1, max: 254 }, + shoesColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + originPlatform: { + type: 0 /* Number */, + default: 5 /* Mii_Creator_v4 */, + min: 0, + max: 6 /* Origin_Platform_Max */ + }, + pantsColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + personality: { type: 0 /* Number */, default: -1, min: -1, max: 255 }, + shirtColor: { type: 0 /* Number */, default: -1, min: -1, max: 99 }, + special: { type: 0 /* Number */, default: 0, min: 0, max: 1 }, + temporary: { type: 0 /* Number */, default: 0, min: 0, max: 1 } +}; +function validate(input) { + let valid = true, reasons = []; + Object.keys(input).forEach((i) => { + function fail2(reason = i) { + valid = false; + reasons.push(reason); + } + const prop = validationThing[i]; + if (!prop) { + alert("A prop is missing: " + i); + return; + } + }); + if (valid) + reasons.push("Valid"); + return { valid, reasons }; +} + +// src/class/struct/MiiCreatorV3Data.ts +var MiiCreatorV3Data = import_struct_fu4.default.struct([ + import_struct_fu4.default.struct([Ver3StoreData]), + import_struct_fu4.default.uint8("ext_faceline_color"), + import_struct_fu4.default.uint8("ext_hair_color"), + import_struct_fu4.default.uint8("ext_eye_color"), + import_struct_fu4.default.uint8("ext_eyebrow_color"), + import_struct_fu4.default.uint8("ext_mouth_color"), + import_struct_fu4.default.uint8("ext_beard_color"), + import_struct_fu4.default.uint8("ext_glass_color"), + import_struct_fu4.default.uint8("ext_glass_type"), + import_struct_fu4.default.uint8("ext_hat_type"), + import_struct_fu4.default.uint8("ext_hat_color"), + import_struct_fu4.default.uint8("ext_face_paint_color"), + import_struct_fu4.default.uint8("ext_shirt_color") +]); +function MiiCreatorV3DataToMiiCreatorV4Data(input) { + const data2 = EmptyMiiCreatorV4Data(); + switch (input.birth_platform) { + case 0: + data2.originPlatform = 0 /* RFL_Wii */; + break; + case 1: + data2.originPlatform = 1 /* NFL_DS */; + break; + case 2: + data2.originPlatform = 2 /* CFL_3DS */; + break; + case 3: + data2.originPlatform = 3 /* FFL_Wii_U */; + break; + } + if (input.ext_beard_color || input.ext_eye_color || input.ext_eyebrow_color || input.ext_face_paint_color || input.ext_faceline_color || input.ext_glass_color || input.ext_glass_type || input.ext_hair_color || input.ext_hat_color || input.ext_hat_type || input.ext_mouth_color || input.ext_shirt_color) { + data2.originPlatform = 5 /* Mii_Creator_v3 */; + } + data2.authorId = input.author_id.data; + data2.beardColor = input.ext_beard_color || Ver3HairColorTable[input.beard_color]; + data2.beardType = input.beard_type; + data2.birthDay = input.birth_day; + data2.birthMonth = input.birth_month; + data2.build = input.build; + data2.createId = FFLiCreateID.pack(input.create_id); + data2.creator = input.creator; + data2.eyeAspect = input.eye_aspect; + data2.eyebrowAspect = input.eyebrow_aspect; + data2.eyebrowColor = input.ext_eyebrow_color || Ver3HairColorTable[input.eyebrow_color]; + data2.eyebrowRotate = input.eyebrow_rotate; + data2.eyebrowScale = input.eyebrow_scale; + data2.eyebrowType = input.eyebrow_type; + data2.eyebrowX = input.eyebrow_x; + data2.eyebrowY = input.eyebrow_y; + data2.eyeColor = input.ext_eye_color || Ver3EyeColorTable[input.eye_color]; + data2.eyeRotate = input.eye_rotate; + data2.eyeScale = input.eye_scale; + data2.eyeType = input.eye_type; + data2.eyeX = input.eye_x; + data2.eyeY = input.eye_y; + data2.facelineColor = input.face_color; + data2.facelineMake = input.face_make; + data2.facelineType = input.face_type; + data2.facelineWrinkle = input.face_tex; + data2.facePaintColor = input.ext_face_paint_color - 1 || -1; + data2.favorite = input.favorite; + data2.favoriteColor = input.favorite_color; + data2.fontRegion = input.font_region; + data2.gender = input.gender; + data2.glassColor = input.ext_glass_color || Ver3GlassColorTable[input.glasses_color]; + data2.glassScale = input.glasses_scale; + data2.glassType = input.ext_glass_type || input.glasses_type; + data2.glassY = input.glass_y; + data2.hairColor = input.ext_hair_color || Ver3HairColorTable[input.hair_color]; + data2.hairFlip = input.hair_flip; + data2.hairType = input.hair_type; + data2.hatFavoriteColor = input.ext_hat_color !== 0 ? input.ext_hat_color - 1 : -1; + data2.hatType = input.ext_hat_type !== 0 ? input.ext_hat_type - 1 : -1; + data2.height = input.height; + data2.moleScale = input.mole_scale; + data2.moleType = input.mole_type; + data2.moleX = input.mole_x; + data2.moleY = input.mole_y; + data2.mouthAspect = input.mouth_aspect; + data2.mouthColor = input.ext_mouth_color || Ver3MouthColorTable[input.mouth_color]; + data2.mouthScale = input.mouth_scale; + data2.mouthType = input.mouth_type; + data2.mouthY = input.mouth_y; + data2.mustacheScale = input.beard_scale; + data2.mustacheType = input.mustache_type; + data2.mustacheY = input.beard_y; + data2.nickname = input.name; + data2.noseScale = input.nose_scale; + data2.noseType = input.nose_type; + data2.noseY = input.nose_y; + data2.regionMove = input.region_move; + if (input.create_id.flag_temporary !== 0) + data2.special = Number(!input.create_id.flag_normal); + data2.temporary = Number(input.create_id.flag_temporary); + return data2; +} + +// src/class/struct/NnMiiCharInfo.ts +var import_struct_fu5 = __toESM(require_struct_fu(), 1); +var NnMiiCharInfo = import_struct_fu5.default.struct([ + import_struct_fu5.default.byte("createId", 16), + import_struct_fu5.default.char16le("nickname", 22), + import_struct_fu5.default.uint8("fontRegion"), + import_struct_fu5.default.uint8("favoriteColor"), + import_struct_fu5.default.uint8("gender"), + import_struct_fu5.default.uint8("height"), + import_struct_fu5.default.uint8("build"), + import_struct_fu5.default.uint8("type"), + import_struct_fu5.default.uint8("regionMove"), + import_struct_fu5.default.uint8("facelineType"), + import_struct_fu5.default.uint8("facelineColor"), + import_struct_fu5.default.uint8("facelineWrinkle"), + import_struct_fu5.default.uint8("facelineMake"), + import_struct_fu5.default.uint8("hairType"), + import_struct_fu5.default.uint8("hairColor"), + import_struct_fu5.default.uint8("hairFlip"), + import_struct_fu5.default.uint8("eyeType"), + import_struct_fu5.default.uint8("eyeColor"), + import_struct_fu5.default.uint8("eyeScale"), + import_struct_fu5.default.uint8("eyeAspect"), + import_struct_fu5.default.uint8("eyeRotate"), + import_struct_fu5.default.uint8("eyeX"), + import_struct_fu5.default.uint8("eyeY"), + import_struct_fu5.default.uint8("eyebrowType"), + import_struct_fu5.default.uint8("eyebrowColor"), + import_struct_fu5.default.uint8("eyebrowScale"), + import_struct_fu5.default.uint8("eyebrowAspect"), + import_struct_fu5.default.uint8("eyebrowRotate"), + import_struct_fu5.default.uint8("eyebrowX"), + import_struct_fu5.default.uint8("eyebrowY"), + import_struct_fu5.default.uint8("noseType"), + import_struct_fu5.default.uint8("noseScale"), + import_struct_fu5.default.uint8("noseY"), + import_struct_fu5.default.uint8("mouthType"), + import_struct_fu5.default.uint8("mouthColor"), + import_struct_fu5.default.uint8("mouthScale"), + import_struct_fu5.default.uint8("mouthAspect"), + import_struct_fu5.default.uint8("mouthY"), + import_struct_fu5.default.uint8("beardColor"), + import_struct_fu5.default.uint8("beardType"), + import_struct_fu5.default.uint8("mustacheType"), + import_struct_fu5.default.uint8("mustacheScale"), + import_struct_fu5.default.uint8("mustacheY"), + import_struct_fu5.default.uint8("glassType"), + import_struct_fu5.default.uint8("glassColor"), + import_struct_fu5.default.uint8("glassScale"), + import_struct_fu5.default.uint8("glassY"), + import_struct_fu5.default.uint8("moleType"), + import_struct_fu5.default.uint8("moleScale"), + import_struct_fu5.default.uint8("moleX"), + import_struct_fu5.default.uint8("moleY"), + import_struct_fu5.default.uint8("reserved") +]); + +// src/class/struct/StudioData.ts +var import_struct_fu6 = __toESM(require_struct_fu(), 1); +var StudioData = import_struct_fu6.default.struct([ + import_struct_fu6.default.uint8("beardColor"), + import_struct_fu6.default.uint8("beardType"), + import_struct_fu6.default.uint8("build"), + import_struct_fu6.default.uint8("eyeAspect"), + import_struct_fu6.default.uint8("eyeColor"), + import_struct_fu6.default.uint8("eyeRotate"), + import_struct_fu6.default.uint8("eyeScale"), + import_struct_fu6.default.uint8("eyeType"), + import_struct_fu6.default.uint8("eyeX"), + import_struct_fu6.default.uint8("eyeY"), + import_struct_fu6.default.uint8("eyebrowAspect"), + import_struct_fu6.default.uint8("eyebrowColor"), + import_struct_fu6.default.uint8("eyebrowRotate"), + import_struct_fu6.default.uint8("eyebrowScale"), + import_struct_fu6.default.uint8("eyebrowType"), + import_struct_fu6.default.uint8("eyebrowX"), + import_struct_fu6.default.uint8("eyebrowY"), + import_struct_fu6.default.uint8("facelineColor"), + import_struct_fu6.default.uint8("facelineMake"), + import_struct_fu6.default.uint8("facelineType"), + import_struct_fu6.default.uint8("facelineWrinkle"), + import_struct_fu6.default.uint8("favoriteColor"), + import_struct_fu6.default.uint8("gender"), + import_struct_fu6.default.uint8("glassColor"), + import_struct_fu6.default.uint8("glassScale"), + import_struct_fu6.default.uint8("glassType"), + import_struct_fu6.default.uint8("glassY"), + import_struct_fu6.default.uint8("hairColor"), + import_struct_fu6.default.uint8("hairFlip"), + import_struct_fu6.default.uint8("hairType"), + import_struct_fu6.default.uint8("height"), + import_struct_fu6.default.uint8("moleScale"), + import_struct_fu6.default.uint8("moleType"), + import_struct_fu6.default.uint8("moleX"), + import_struct_fu6.default.uint8("moleY"), + import_struct_fu6.default.uint8("mouthAspect"), + import_struct_fu6.default.uint8("mouthColor"), + import_struct_fu6.default.uint8("mouthScale"), + import_struct_fu6.default.uint8("mouthType"), + import_struct_fu6.default.uint8("mouthY"), + import_struct_fu6.default.uint8("mustacheScale"), + import_struct_fu6.default.uint8("mustacheType"), + import_struct_fu6.default.uint8("mustacheY"), + import_struct_fu6.default.uint8("noseScale"), + import_struct_fu6.default.uint8("noseType"), + import_struct_fu6.default.uint8("noseY") +]); + +// node_modules/gettext.js/lib/gettext.js +/*! gettext.js - Guillaume Potier - MIT Licensed */ +var i18n = function(options) { + options = options || {}; + this && (this.__version = "2.0.0"); + var defaults2 = { + domain: "messages", + locale: (typeof document !== "undefined" ? document.documentElement.getAttribute("lang") : false) || "en", + plural_func: function(n2) { + return { nplurals: 2, plural: n2 != 1 ? 1 : 0 }; + }, + ctxt_delimiter: String.fromCharCode(4) + }; + var _8 = { + isObject: function(obj) { + var type = typeof obj; + return type === "function" || type === "object" && !!obj; + }, + isArray: function(obj) { + return toString.call(obj) === "[object Array]"; + } + }; + var _plural_funcs = {}, _locale = options.locale || defaults2.locale, _domain = options.domain || defaults2.domain, _dictionary = {}, _plural_forms = {}, _ctxt_delimiter = options.ctxt_delimiter || defaults2.ctxt_delimiter; + if (options.messages) { + _dictionary[_domain] = {}; + _dictionary[_domain][_locale] = options.messages; + } + if (options.plural_forms) { + _plural_forms[_locale] = options.plural_forms; + } + var strfmt = function(fmt) { + var args = arguments; + return fmt.replace(/%%/g, "%% ").replace(/%(\d+)/g, function(str, p1) { + return args[p1]; + }).replace(/%% /g, "%"); + }; + var removeContext = function(str) { + if (str.indexOf(_ctxt_delimiter) !== -1) { + var parts = str.split(_ctxt_delimiter); + return parts[1]; + } + return str; + }; + var expand_locale = function(locale) { + var locales = [locale], i = locale.lastIndexOf("-"); + while (i > 0) { + locale = locale.slice(0, i); + locales.push(locale); + i = locale.lastIndexOf("-"); + } + return locales; + }; + var normalizeLocale = function(locale) { + locale = locale.replace("_", "-"); + var i = locale.search(/[.@]/); + if (i != -1) + locale = locale.slice(0, i); + return locale; + }; + var getPluralFunc = function(plural_form) { + var pf_re = new RegExp("^\\s*nplurals\\s*=\\s*[0-9]+\\s*;\\s*plural\\s*=\\s*(?:\\s|[-\\?\\|&=!<>+*/%:;n0-9_()])+"); + var match = plural_form.match(pf_re); + if (!match || match[0] !== plural_form) + throw new Error(strfmt('The plural form "%1" is not valid', plural_form)); + return new Function("n", "var plural, nplurals; " + plural_form + " return { nplurals: nplurals, plural: (plural === true ? 1 : (plural ? plural : 0)) };"); + }; + var t3 = function(messages, n2, options2) { + if (!options2.plural_form) + return strfmt.apply(this, [removeContext(messages[0])].concat(Array.prototype.slice.call(arguments, 3))); + var plural; + if (options2.plural_func) { + plural = options2.plural_func(n2); + } else if (!_plural_funcs[_locale]) { + _plural_funcs[_locale] = getPluralFunc(_plural_forms[_locale]); + plural = _plural_funcs[_locale](n2); + } else { + plural = _plural_funcs[_locale](n2); + } + if (typeof plural.plural === "undefined" || plural.plural > plural.nplurals || messages.length <= plural.plural) + plural.plural = 0; + return strfmt.apply(this, [removeContext(messages[plural.plural])].concat(Array.prototype.slice.call(arguments, 3))); + }; + return { + strfmt, + expand_locale, + __: function() { + return this.gettext.apply(this, arguments); + }, + _n: function() { + return this.ngettext.apply(this, arguments); + }, + _p: function() { + return this.pgettext.apply(this, arguments); + }, + setMessages: function(domain, locale, messages, plural_forms) { + if (!domain || !locale || !messages) + throw new Error("You must provide a domain, a locale and messages"); + if (typeof domain !== "string" || typeof locale !== "string" || !_8.isObject(messages)) + throw new Error("Invalid arguments"); + locale = normalizeLocale(locale); + if (plural_forms) + _plural_forms[locale] = plural_forms; + if (!_dictionary[domain]) + _dictionary[domain] = {}; + _dictionary[domain][locale] = messages; + return this; + }, + loadJSON: function(jsonData, domain) { + if (!_8.isObject(jsonData)) + jsonData = JSON.parse(jsonData); + if (!jsonData[""] || !jsonData[""]["language"] || !jsonData[""]["plural-forms"]) + throw new Error('Wrong JSON, it must have an empty key ("") with "language" and "plural-forms" information'); + var headers = jsonData[""]; + delete jsonData[""]; + return this.setMessages(domain || defaults2.domain, headers["language"], jsonData, headers["plural-forms"]); + }, + setLocale: function(locale) { + _locale = normalizeLocale(locale); + return this; + }, + getLocale: function() { + return _locale; + }, + textdomain: function(domain) { + if (!domain) + return _domain; + _domain = domain; + return this; + }, + gettext: function(msgid) { + return this.dcnpgettext.apply(this, [undefined, undefined, msgid, undefined, undefined].concat(Array.prototype.slice.call(arguments, 1))); + }, + ngettext: function(msgid, msgid_plural, n2) { + return this.dcnpgettext.apply(this, [undefined, undefined, msgid, msgid_plural, n2].concat(Array.prototype.slice.call(arguments, 3))); + }, + pgettext: function(msgctxt, msgid) { + return this.dcnpgettext.apply(this, [undefined, msgctxt, msgid, undefined, undefined].concat(Array.prototype.slice.call(arguments, 2))); + }, + dcnpgettext: function(domain, msgctxt, msgid, msgid_plural, n2) { + domain = domain || _domain; + if (typeof msgid !== "string") + throw new Error(this.strfmt('Msgid "%1" is not a valid translatable string', msgid)); + var translation, options2 = { plural_form: false }, key2 = msgctxt ? msgctxt + _ctxt_delimiter + msgid : msgid, exist, locale, locales = expand_locale(_locale); + for (var i in locales) { + locale = locales[i]; + exist = _dictionary[domain] && _dictionary[domain][locale] && _dictionary[domain][locale][key2]; + if (msgid_plural) { + exist = exist && typeof _dictionary[domain][locale][key2] !== "string"; + } else { + exist = exist && typeof _dictionary[domain][locale][key2] === "string"; + } + if (exist) { + break; + } + } + if (!exist) { + translation = msgid; + options2.plural_func = defaults2.plural_func; + } else { + translation = _dictionary[domain][locale][key2]; + } + if (!msgid_plural) + return t3.apply(this, [[translation], n2, options2].concat(Array.prototype.slice.call(arguments, 5))); + options2.plural_form = true; + return t3.apply(this, [exist ? translation : [msgid, msgid_plural], n2, options2].concat(Array.prototype.slice.call(arguments, 5))); + } + }; +}; +var gettext_default = i18n; + +// src/util/Lang.ts +var localization = gettext_default(); +var _8 = () => localization.gettext.bind(localization); + +// src/class/MiiData.ts +var __ = _8(); + +class Mii { + miicVersion; + originPlatform; + authorId; + createId; + creator; + nickname; + beardColor; + beardType; + birthDay; + birthMonth; + birthYear; + build; + clothesType; + eyeAspect; + eyebrowAspect; + eyebrowColor; + eyebrowRotate; + eyebrowScale; + eyebrowType; + eyebrowX; + eyebrowY; + eyeColor; + eyeRotate; + eyeScale; + eyeSclera; + eyeType; + eyeX; + eyeY; + facelineColor; + facelineMake; + facelineType; + facelineWrinkle; + facePaintColor; + favorite; + favoriteColor; + fontRegion; + gender; + glassColor; + glassScale; + glassType; + glassY; + hairColor; + hairFlip; + hairType; + hatCommonColor; + hatFavoriteColor; + hatType; + height; + wigType; + moleScale; + moleType; + moleX; + moleY; + mouthAspect; + mouthColor; + mouthScale; + mouthType; + mouthY; + mustacheScale; + mustacheType; + mustacheY; + temporary; + noseScale; + noseType; + noseY; + pantsColor; + personality; + regionMove; + shirtColor; + shoesColor; + special; + valid; + constructor(initData) { + let importData; + if (typeof initData === "string") + importData = parseHexOrB64ToUint8Array(initData); + else + importData = initData; + this.import(Mii.parseData(importData)); + } + static parseData(input) { + let data2 = EmptyMiiCreatorV4Data(); + let tempArray; + switch (input.length) { + case 46: + case 47: + tempArray = allocateArray(48, input); + data2 = { ...EmptyMiiCreatorV4Data(), ...StudioData.unpack(tempArray) }; + data2.originPlatform = 5 /* Mii_Creator_v4 */; + data2.nickname = "Mii"; + data2.creator = ""; + break; + case 74: + case 76: + tempArray = allocateArray(96, input); + data2 = RFLStoreDataToMiiCreatorV4Data(RFLStoreData.unpack(tempArray)); + break; + case 87: + case 88: + tempArray = allocateArray(88, input); + const d = NnMiiCharInfo.unpack(tempArray); + var tmpCreateId = new Uint8Array(10); + tmpCreateId.set(d.createId.slice(0, 10), 0); + d.createId = tmpCreateId; + data2 = { ...data2, ...d }; + data2.createId.set(d.createId.slice(0, 10), 0); + data2.authorId.set(d.createId.slice(10), 0); + data2.creator = ""; + data2.originPlatform = 4 /* nn_mii_Switch */; + break; + case 92: + case 96: + tempArray = allocateArray(108, input); + data2 = MiiCreatorV3DataToMiiCreatorV4Data(MiiCreatorV3Data.unpack(MiiCreatorV3Data.pack(Ver3StoreData.unpack(tempArray)))); + break; + case 104: + case 106: + case 108: + tempArray = allocateArray(108, input); + data2 = MiiCreatorV3DataToMiiCreatorV4Data(MiiCreatorV3Data.unpack(tempArray)); + break; + case 114: + tempArray = allocateArray(123, input); + data2 = MiiCreatorV3DataToMiiCreatorV4Data(MiiCreatorV3Data.unpack(MiiCreatorV3Data.pack(Ver3StoreData.unpack(tempArray)))); + break; + case 122: + case 123: + case 124: + case 125: + case 126: + tempArray = allocateArray(126, input); + data2 = MiiCreatorV4Data.unpack(tempArray); + if (input.length < 126) { + data2.shoesColor = -1; + } + if (input.length < 125) { + data2.clothesType = -1; + } + break; + default: + throw new Error(__("Mii data type not supported (%1 bytes)", input.length)); + } + if (data2.facePaintColor === 255) + data2.facePaintColor = -1; + if (data2.hatCommonColor === 255) + data2.hatCommonColor = -1; + if (data2.hatFavoriteColor === 255) + data2.hatFavoriteColor = -1; + if (data2.hatType === 255) + data2.hatType = -1; + if (data2.pantsColor === 255) + data2.pantsColor = -1; + if (data2.personality === 255) + data2.personality = -1; + if (data2.shirtColor === 255) + data2.shirtColor = -1; + if (data2.wigType === 255) + data2.wigType = -1; + if (data2.clothesType === 255) + data2.clothesType = -1; + if (data2.shoesColor === 255) + data2.shoesColor = -1; + return data2; + } + static parseDataBinary(input) { + const data2 = Mii.parseData(input); + return MiiCreatorV4Data.pack(data2); + } + #getObject(override = null) { + return { + miicVersion: this.miicVersion, + originPlatform: this.originPlatform, + authorId: this.authorId, + createId: this.createId, + creator: this.creator, + nickname: this.nickname, + beardColor: this.beardColor, + beardType: this.beardType, + birthDay: this.birthDay, + birthMonth: this.birthMonth, + birthYear: this.birthYear, + build: this.build, + clothesType: this.clothesType, + eyeAspect: this.eyeAspect, + eyebrowAspect: this.eyebrowAspect, + eyebrowColor: this.eyebrowColor, + eyebrowRotate: this.eyebrowRotate, + eyebrowScale: this.eyebrowScale, + eyebrowType: this.eyebrowType, + eyebrowX: this.eyebrowX, + eyebrowY: this.eyebrowY, + eyeColor: this.eyeColor, + eyeRotate: this.eyeRotate, + eyeScale: this.eyeScale, + eyeSclera: this.eyeSclera, + eyeType: this.eyeType, + eyeX: this.eyeX, + eyeY: this.eyeY, + facelineColor: this.facelineColor, + facelineMake: this.facelineMake, + facelineType: this.facelineType, + facelineWrinkle: this.facelineWrinkle, + facePaintColor: this.facePaintColor, + favorite: this.favorite, + favoriteColor: this.favoriteColor, + fontRegion: this.fontRegion, + gender: this.gender, + glassColor: this.glassColor, + glassScale: this.glassScale, + glassType: this.glassType, + glassY: this.glassY, + hairColor: this.hairColor, + hairFlip: this.hairFlip, + hairType: this.hairType, + hatCommonColor: this.hatCommonColor, + hatFavoriteColor: this.hatFavoriteColor, + hatType: this.hatType, + height: this.height, + wigType: this.wigType, + moleScale: this.moleScale, + moleType: this.moleType, + moleX: this.moleX, + moleY: this.moleY, + mouthAspect: this.mouthAspect, + mouthColor: this.mouthColor, + mouthScale: this.mouthScale, + mouthType: this.mouthType, + mouthY: this.mouthY, + mustacheScale: this.mustacheScale, + mustacheType: this.mustacheType, + mustacheY: this.mustacheY, + temporary: this.temporary, + noseScale: this.noseScale, + noseType: this.noseType, + noseY: this.noseY, + pantsColor: this.pantsColor, + personality: this.personality, + regionMove: this.regionMove, + shirtColor: this.shirtColor, + shoesColor: this.shoesColor, + special: this.special, + ...override + }; + } + #getNicknameSafe() { + if (this.nickname.trim() !== "") + return this.nickname; + else + return "A Mii"; + } + verify() { + return validate(this.#getObject()); + } + validate() { + const verify = this.verify(); + if (verify.valid === true) + this.valid = true; + else { + this.valid = false; + console.warn(`${this.#getNicknameSafe()} has invalid data:`, verify.reasons.join(", ")); + console.warn(this.export()); + throw new Error(`Mii data for ${this.nickname} is not valid: ${verify.reasons.join(", ")}`); + } + } + import(data2) { + this.miicVersion = data2.miicVersion; + this.originPlatform = data2.originPlatform; + this.authorId = data2.authorId; + this.createId = data2.createId; + this.creator = data2.creator; + this.nickname = data2.nickname; + this.beardColor = data2.beardColor; + this.beardType = data2.beardType; + this.birthDay = data2.birthDay; + this.birthMonth = data2.birthMonth; + this.birthYear = data2.birthYear; + this.build = data2.build; + this.clothesType = data2.clothesType; + this.eyeAspect = data2.eyeAspect; + this.eyebrowAspect = data2.eyebrowAspect; + this.eyebrowColor = data2.eyebrowColor; + this.eyebrowRotate = data2.eyebrowRotate; + this.eyebrowScale = data2.eyebrowScale; + this.eyebrowType = data2.eyebrowType; + this.eyebrowX = data2.eyebrowX; + this.eyebrowY = data2.eyebrowY; + this.eyeColor = data2.eyeColor; + this.eyeRotate = data2.eyeRotate; + this.eyeScale = data2.eyeScale; + this.eyeSclera = data2.eyeSclera; + this.eyeType = data2.eyeType; + this.eyeX = data2.eyeX; + this.eyeY = data2.eyeY; + this.facelineColor = data2.facelineColor; + this.facelineMake = data2.facelineMake; + this.facelineType = data2.facelineType; + this.facelineWrinkle = data2.facelineWrinkle; + this.facePaintColor = data2.facePaintColor; + this.favorite = data2.favorite; + this.favoriteColor = data2.favoriteColor; + this.fontRegion = data2.fontRegion; + this.gender = data2.gender; + this.glassColor = data2.glassColor; + this.glassScale = data2.glassScale; + this.glassType = data2.glassType; + this.glassY = data2.glassY; + this.hairColor = data2.hairColor; + this.hairFlip = data2.hairFlip; + this.hairType = data2.hairType; + this.hatFavoriteColor = data2.hatFavoriteColor; + this.hatCommonColor = data2.hatCommonColor; + this.hatType = data2.hatType; + this.height = data2.height; + this.wigType = data2.wigType; + this.moleScale = data2.moleScale; + this.moleType = data2.moleType; + this.moleX = data2.moleX; + this.moleY = data2.moleY; + this.mouthAspect = data2.mouthAspect; + this.mouthColor = data2.mouthColor; + this.mouthScale = data2.mouthScale; + this.mouthType = data2.mouthType; + this.mouthY = data2.mouthY; + this.mustacheScale = data2.mustacheScale; + this.mustacheType = data2.mustacheType; + this.mustacheY = data2.mustacheY; + this.noseScale = data2.noseScale; + this.noseType = data2.noseType; + this.noseY = data2.noseY; + this.pantsColor = data2.pantsColor; + this.personality = data2.personality; + this.regionMove = data2.regionMove; + this.shirtColor = data2.shirtColor; + this.special = data2.special; + this.shoesColor = data2.shoesColor; + this.temporary = data2.temporary; + if (this.originPlatform === 2 /* CFL_3DS */ || this.originPlatform === 3 /* FFL_Wii_U */) { + const createId = FFLiCreateID.unpack(this.createId); + if (!createId.flag_normal) { + this.special = 1; + } + if (createId.flag_temporary) { + this.special = 0; + this.temporary = 1; + } + } + this.fixInternalIDs(); + } + export(outputFormat = "miic") { + this.fixInternalIDs(); + switch (outputFormat) { + case "rsd": + throw new Error("RSD format is not yet supported."); + default: + case "miic": + return MiiCreatorV4Data.pack(this.#getObject()); + case "studioData": + return StudioData.pack(this.#getObject({ + facelineColor: this.facePaintColor !== -1 ? this.facePaintColor + 10 : this.facelineColor + })); + case "switchCharInfo": + return NnMiiCharInfo.pack(this.#getObject()); + case "ffsd": + return MiiCreatorV4DataToFFSD(this.#getObject(), true); + case "ffsd_append_miic": + return MiiCreatorV4DataToFFSD(this.#getObject(), true, true); + } + } + exportHex(outputFormat) { + const data2 = this.export(outputFormat); + return dataToHex(data2); + } + exportBase64(outputFormat) { + const data2 = this.export(outputFormat); + return dataToBase64(data2); + } + hasExtendedColors() { + return false; + } + fixInternalIDs() { + const createId = FFLiCreateID.unpack(this.createId); + const authorId = this.authorId; + if (Array.from(createId.base).every((e) => e === 0)) { + createId.base = randomizeUint8Array(createId.base); + } + if (Array.from(authorId).every((e) => e === 0)) { + this.authorId = randomizeUint8Array(authorId); + } + if (createId.flag_normal === 0 && this.special === 0) { + createId.flag_normal = 1; + } + if (createId.flag_normal === 1 && this.special === 1) { + createId.flag_normal = 0; + } + if (createId.flag_temporary === 0 && this.temporary === 1) { + createId.flag_temporary = 1; + } + if (createId.flag_temporary === 1 && this.temporary === 0) { + createId.flag_temporary = 0; + } + this.createId = FFLiCreateID.pack(createId); + } +} + +// src/util/camera.js +var ViewType2 = { + Face: 0, + MakeIcon: 1, + IconFovy45: 2, + AllBody: 3, + AllBodySugar: 4, + CreditIcon: 5 +}; +function getCameraForViewType(viewType, width2 = 1, height2 = 1, miiHeight = 1) { + const aspect2 = width2 / height2; + switch (viewType) { + case ViewType2.Face: { + const fovy = 15; + const camera = new PerspectiveCamera(fovy, aspect2, 0.1, 1000); + camera.position.set(0, 34.5, 380); + camera.lookAt(0, 34.3, 0); + return camera; + } + case ViewType2.MakeIcon: { + const fovy = 9.8762; + const camera = new PerspectiveCamera(fovy, aspect2, 500, 1000); + camera.position.set(0, 34.5, 600); + camera.lookAt(0, 34.5, 0); + return camera; + } + case ViewType2.IconFovy45: { + const camera = new PerspectiveCamera(45, aspect2, 50, 1000); + camera.position.set(0, 34, 110); + camera.lookAt(0, 34, 0); + return camera; + } + case ViewType2.AllBody: { + const fovy = 15; + const camera = new PerspectiveCamera(fovy, aspect2, 50, 1500); + camera.position.set(0, 50, 900); + camera.lookAt(0, 105, 0); + return camera; + } + case ViewType2.AllBodySugar: { + const fovy = 15; + const camera = new PerspectiveCamera(fovy, aspect2, 50, 15000); + const posStart = new Vector3(0, 65, 550); + const atStart = new Vector3(0, 65, 0); + const posEnd = new Vector3(0, 75, 850); + const atEnd = new Vector3(0, 88, 0); + const t3 = (miiHeight - 0.5) / (1.264 - 0.5); + const pos = new Vector3(posStart.x + t3 * (posEnd.x - posStart.x), posStart.y + t3 * (posEnd.y - posStart.y), posStart.z + t3 * (posEnd.z - posStart.z)); + const at = new Vector3(atStart.x + t3 * (atEnd.x - atStart.x), atStart.y + t3 * (atEnd.y - atStart.y), atStart.z + t3 * (atEnd.z - atStart.z)); + camera.position.copy(pos); + camera.lookAt(at); + return camera; + } + case ViewType2.CreditIcon: { + const fovy = 15; + const camera = new PerspectiveCamera(fovy, aspect2, 0.1, 1000); + camera.position.set(-60, 34.5, 380); + camera.lookAt(0, 34.3, 0); + return camera; + } + default: + throw new Error("getCameraForViewType: not implemented"); + } +} + +// src/util/rendertarget.js +var isWorker = false; +if (typeof window === "undefined") { + isWorker = true; +} +function renderTargetToDataURL(renderTarget, renderer2, flipY = false, blob = true) { + return new Promise((resolve) => { + const scene = new Scene; + scene.background = null; + const material = new MeshBasicMaterial({ + side: DoubleSide, + map: renderTarget.texture, + transparent: true + }); + const plane = new PlaneGeometry(2, 2); + const mesh = new Mesh(plane, material); + scene.add(mesh); + const camera = getIdentCamera(flipY); + const prevTarget = renderer2.getRenderTarget(); + const prevColorSpace = renderer2.outputColorSpace; + const size2 = new Vector2; + renderer2.getSize(size2); + renderer2.setRenderTarget(null); + renderer2.outputColorSpace = ColorManagement ? ColorManagement.workingColorSpace : null; + renderer2.setSize(renderTarget.width, renderTarget.height, false); + renderer2.render(scene, camera); + function cleanup() { + material.dispose(); + plane.dispose(); + scene.remove(mesh); + renderer2.outputColorSpace = prevColorSpace; + renderer2.setSize(size2.x, size2.y, false); + renderer2.setRenderTarget(prevTarget); + } + if (blob) { + const ok = (blob2) => { + resolve({ type: "blob", result: blob2 }); + cleanup(); + }; + if (isWorker) { + renderer2.domElement.convertToBlob({ type: "image/png" }).then(ok); + } else { + renderer2.domElement.toBlob(ok); + } + } else { + const result = renderer2.domElement.toDataURL("image/png"); + resolve({ type: "dataURL", result }); + cleanup(); + } + }); +} +async function renderTargetToDataTexture(renderTarget, renderer2, flipY = false, filtering = true) { + const { width: width2, height: height2 } = renderTarget; + let buf = new Uint8Array(width2 * height2 * 4); + await renderer2.readRenderTargetPixelsAsync(renderTarget, 0, 0, width2, height2, buf); + const dataTexture = new DataTexture(buf, width2, height2, RGBAFormat, UnsignedByteType); + dataTexture.needsUpdate = true; + if (flipY) { + dataTexture.flipY = true; + } + if (filtering) { + dataTexture.minFilter = LinearFilter; + dataTexture.magFilter = LinearFilter; + } + return dataTexture; +} + +// src/class/3d/shader/ColorMix.ts +function ColorMixShaderMaterial(texture, r, g3, b2) { + return new ShaderMaterial({ + uniforms: { + u_texture: { value: texture }, + u_const1: { value: r }, + u_const2: { value: g3 }, + u_const3: { value: b2 } + }, + vertexShader: ` + varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + } + `, + fragmentShader: ` + uniform sampler2D u_texture; + uniform vec4 u_const1; + uniform vec4 u_const2; + uniform vec4 u_const3; + varying vec2 vUv; + + void main() { + vec4 texColor = texture2D(u_texture, vUv); + + // Optionally discard low-alpha texture pixels. + if (texColor.a <= 0.2) { + discard; + } + +// Mix RGB channels using each constant’s color (rgb) +vec3 mixedColor = texColor.r * u_const1.rgb + + texColor.g * u_const2.rgb + + texColor.b * u_const3.rgb; + +// Use the texture's own alpha +float mixedAlpha = texColor.a; + +// Premultiply the mixed color by its alpha +gl_FragColor = vec4(mixedColor * mixedAlpha, mixedAlpha); + } + ` + }); +} +function colorMixTexture(tex, constR = new Vector4(0, 1, 1, 1), constG = new Vector4(1, 1, 0, 1), constB = new Vector4(1, 1, 0, 1), constA, rendererMain, textureResolution) { + return new Promise((resolve) => { + const scene = new Scene; + let width2, height2; + if (tex instanceof ImageBitmap) { + width2 = tex.width; + height2 = tex.height; + } else { + width2 = tex.image.width; + height2 = tex.image.height; + } + if (textureResolution) { + let aspect2 = width2 / height2; + width2 = textureResolution; + height2 = textureResolution / aspect2; + } + console.log("HI ITS ME CLOTHING TEX RENDERER, IDK WTF I DID", width2, height2); + const renderSize = new Vector2(0, 0); + rendererMain.getSize(renderSize); + console.log("[CMT DEBUG] width, height", width2, height2); + const camera = new OrthographicCamera(width2 / -2, width2 / 2, height2 / 2, height2 / -2, 0.1, 1000); + camera.position.z = 1; + console.log("[CMT DEBUG] camera Created!"); + const renderer2 = rendererMain; + console.log("[CMT DEBUG] renderer Created!"); + let oldClearColor = new Color; + renderer2.getClearColor(oldClearColor); + let oldClearAlpha = renderer2.getClearAlpha(); + renderer2.setClearColor(constA, 1); + console.log("[CMT DEBUG] using red for alpha."); + renderer2.setSize(width2, height2, false); + console.log("[CMT DEBUG] set renderer size OK."); + if (typeof window !== "undefined") + window.camera = camera; + const geometry = new PlaneGeometry(width2, height2); + console.log("[CMT DEBUG] create geometry OK"); + const plane = new Mesh(geometry, ColorMixShaderMaterial(tex, constR, constG, constB)); + console.log("[CMT DEBUG] create mesh OK"); + scene.add(plane); + console.log("[CMT DEBUG] add mesh to scene"); + function render() { + console.log("[CMT DEBUG] render scene OK"); + function finalize(blob) { + if (blob === null) + return console.error("blob is null???"); + resolve(blob); + renderer2.setClearColor(0); + renderer2.setClearAlpha(0); + geometry.dispose(); + plane.material.dispose(); + console.log("[CMT DEBUG] disposed of scene OK"); + } + renderer2.setSize(width2, height2, false); + renderer2.render(scene, camera); + renderer2.setClearAlpha(0); + if (typeof document === "undefined") { + renderer2.domElement.convertToBlob({ type: "image/png" }).then(finalize); + } else { + renderer2.domElement.toBlob(finalize); + } + } + console.log("[CMT DEBUG] preparing render"); + render(); + }); +} + +// src/ui/pages/library/util/3DModel.ts +function loadBlobTexture(blob) { + return new Promise((resolve) => { + var texture = new Texture; + var url = URL.createObjectURL(blob); + var image = new Image; + image.src = url; + image.onload = function() { + texture.image = image; + texture.needsUpdate = true; + resolve(texture); + setTimeout(() => { + URL.revokeObjectURL(url); + }, 1e4); + }; + }); +} +function loadBlobTextureWorker(blob, width2 = 512, height2 = 512) { + return new Promise((resolve) => { + createImageBitmap(blob, 0, 0, width2, height2).then((r) => { + console.log("bitmap canvas texture created"); + return resolve(new CanvasTexture(r)); + }); + }); +} + +// src/util/IconRendering.ts +var import_FFLShaderMaterial3 = __toESM(require_FFLShaderMaterial(), 1); +var defaultParams = { + type: ViewType2.Face, + expression: 0, + characterYRotate: 0, + modelFlag: FFLCharModelDescDefault, + drawBody: true +}; +function createMiiRender(request) { + return new Promise(async (resolve) => { + let dataInput; + if (typeof request.data === "string") + dataInput = parseHexOrB64ToUint8Array(request.data); + else + dataInput = request.data; + let scene = new Scene; + const isTemporary = request.isTemporary !== false; + const mii = new Mii(dataInput); + const localModule = request.module; + if (localModule === undefined) + throw new Error("Module NOT ready."); + let modelFlag = FFLModelFlag.NORMAL; + if (request.additionalInfo.hatType !== -1) { + switch (HatTypeList[request.additionalInfo.hatType]) { + case 1 /* HAT */: + modelFlag = FFLModelFlag.HAT; + break; + case 2 /* FACE_ONLY */: + modelFlag = FFLModelFlag.FACE_ONLY; + break; + case 6 /* BALD */: + mii.hairType = 30; + dataInput = mii.export("studioData"); + break; + } + } + console.log("miic additional info:", JSON.stringify(request.additionalInfo)); + const shaderMaterial = await getShaderMaterialFromShaderType(request.shaderType); + const isUsingShader = await isShaderMaterial(request.shaderType); + let lights = await getSimpleMaterialAddLights(request.shaderType); + if (lights) { + lights(scene); + } + let texResolution = request.texResolution || 512; + if (request.size > 512) { + texResolution = 1024; + } else if (request.size > 1024) { + texResolution = 2048; + } + let expressions = []; + if (Array.isArray(request.expression)) { + expressions.push(...request.expression); + } else { + expressions.push(isNaN(request.expression) ? FFLExpression.NORMAL : request.expression); + } + const charModel = createCharModel(dataInput, { + resolution: texResolution, + resourceType: FFLResourceType.HIGH, + allExpressionFlag: makeExpressionFlag(expressions), + modelFlag + }, shaderMaterial, localModule, false); + charModel._materialTextureClass = import_FFLShaderMaterial3.default; + charModel._materialClass = shaderMaterial; + if (request.additionalInfo.eyeSclera === 1 && mii.eyeColor !== 8) { + self.eyeScleraHack = true; + } + initCharModelTextures(charModel, request.renderer, charModel._materialTextureClass); + if (request.additionalInfo.eyeSclera === 1 && mii.eyeColor !== 8) { + self.eyeScleraHack = false; + } + let miiGroup, headModel; + if (isTemporary) { + miiGroup = scene; + miiGroup.background = null; + } else { + miiGroup = new Group; + headModel = new Group; + } + const gender = charModel._model.charInfo.personal.gender; + const bodyScale = charModel.getBodyScale(); + let hatModel; + if (request.additionalInfo.hatType !== -1) { + let hatColor = [0, 0, 0]; + if (isTemporary) + hatModel = getHatModels()[request.additionalInfo.hatType].clone(true); + else + hatModel = getHatModels()[request.additionalInfo.hatType].clone(true); + hatColor = MiiFavoriteColorVec3Table[mii.favoriteColor % Object.keys(MiiFavoriteColorVec3Table).length]; + if (request.additionalInfo.hatFavoriteColor !== -1) { + hatColor = MiiFavoriteColorVec3Table[request.additionalInfo.hatFavoriteColor]; + } + if (request.additionalInfo.hatCommonColor !== -1) { + hatColor = SwitchMiiColorTableSRGB[request.additionalInfo.hatCommonColor]; + } + console.log("additional info:", request.additionalInfo, "hat model:", hatModel); + hatModel.traverse((m) => { + if (m.isMesh) { + const oldMat = m.material.map; + let modulate = isUsingShader ? { + modulateType: 5 /* FFL_MODULATE_TYPE_SHAPE_CAP */, + modulateMode: 2 + } : {}; + m.material = new shaderMaterial({ + ...modulate, + color: new Color(...hatColor), + opacity: 1, + map: oldMat + }); + } + }); + if (isTemporary) { + miiGroup.add(hatModel); + } else { + headModel.add(hatModel); + } + const shiftPos = charModel.partsTransform.hatTranslate.y; + if (request.drawBody) { + if (isTemporary) { + hatModel.position.set(0, bodyScale.y * 75 + shiftPos, 0); + } else { + hatModel.position.set(0, shiftPos, 0); + } + } else { + charModel.partsTransform.hatTranslate.y; + hatModel.position.set(0, shiftPos, 0); + } + } + const headMesh = charModel.meshes.clone(); + if (isTemporary) { + miiGroup.add(headMesh); + } else { + headModel.add(headMesh); + } + let iconCamera; + if (isTemporary) + iconCamera = getCameraForViewType(request.type, undefined, undefined, bodyScale.y); + let bodyModel, bodyModelBody, bodyModelHands, bodyModelLegs, bodyModelAnims; + if (headModel !== undefined) { + miiGroup.add(headModel); + } + let prefix = "high"; + if (request.bodyModelType !== undefined) { + prefix = request.bodyModelType; + } + if (request.drawBody && getBodyModels()[prefix + "M"] !== null) { + switch (gender) { + case 0: { + if (isTemporary) + bodyModel = getBodyModels()[prefix + "M"].scene; + else + bodyModel = exports_SkeletonUtils.clone(getBodyModels()[prefix + "M"].scene); + if (bodyModel === null) + throw "Tried to make an icon before body models were loaded."; + bodyModelBody = bodyModel.getObjectByName("body_m"); + bodyModelHands = bodyModel.getObjectByName("hands_m"); + bodyModelLegs = bodyModel.getObjectByName("legs_m"); + if (!isTemporary) + bodyModelAnims = getBodyModels()[prefix + "M"].animations; + break; + } + case 1: { + if (isTemporary) + bodyModel = getBodyModels()[prefix + "F"].scene; + else + bodyModel = exports_SkeletonUtils.clone(getBodyModels()[prefix + "F"].scene); + if (bodyModel === null) + throw "Tried to make an icon before body models were loaded."; + bodyModelBody = bodyModel.getObjectByName("body_f"); + bodyModelHands = bodyModel.getObjectByName("hands_f"); + bodyModelLegs = bodyModel.getObjectByName("legs_f"); + if (!isTemporary) + bodyModelAnims = getBodyModels()[prefix + "F"].animations; + break; + } + default: + throw new Error(`Gender ${gender} is outisde range 0, 1`); + } + bodyModel.scale.set(bodyScale.x * 7, bodyScale.y * 7, bodyScale.z * 7); + bodyModel.position.set(0, 0, 0); + miiGroup.add(bodyModel); + var shirtColor = MiiFavoriteColorVec3Table[mii.favoriteColor % Object.keys(MiiFavoriteColorVec3Table).length]; + if (request.additionalInfo.shirtColor !== -1 && !ForbiddenShirtPantColors.includes(request.additionalInfo.shirtColor)) { + shirtColor = SwitchMiiColorTableSRGB[request.additionalInfo.shirtColor]; + } + let modulate = isUsingShader ? { + modulateType: 9 /* FFL_MODULATE_TYPE_SHAPE_BODY */, + modulateMode: 0 + } : {}; + bodyModelBody.material = new charModel._materialClass({ + ...modulate, + color: new Color(...shirtColor), + opacity: 1 + }); + if (bodyModelHands) + bodyModelHands.material = bodyModelBody.material; + var pantsColor = cPantsColorGray; + if (request.additionalInfo.favorite === 1) { + pantsColor = cPantsColorRed; + } + if (request.additionalInfo.special === 1) { + pantsColor = cPantsColorGold; + } + if (request.additionalInfo.temporary === 1) { + pantsColor = cPantsColorBlue; + } + if (request.additionalInfo.pantsColor !== -1 && !ForbiddenShirtPantColors.includes(request.additionalInfo.pantsColor)) { + pantsColor = SwitchMiiColorTableSRGB[request.additionalInfo.pantsColor]; + } + modulate = isUsingShader ? { + modulateType: 10 /* FFL_MODULATE_TYPE_SHAPE_PANTS */, + modulateMode: 0 + } : {}; + bodyModelLegs.material = new charModel._materialClass({ + ...modulate, + color: new Color(...pantsColor), + opacity: 1 + }); + const nBody = bodyModelBody; + const nLegs = bodyModelLegs; + ColorManagement.enabled = false; + if (request.additionalInfo.clothesType !== undefined && request.additionalInfo.clothesType !== -1 && request.bodyModelType !== "low" /* low */ && getLoadedBodyModelName() === "wiiu" && request.additionalInfo.clothesType < ExtClothesList.length) { + console.log("clothing update"); + let shirtTexture, pantsTexture = null; + const suffix = mii.gender == 1 ? "F" : ""; + let key2 = `${getLoadedBodyModelName()}_${ExtClothesList[request.additionalInfo.clothesType]}${suffix}`; + let shirtKey = key2; + if (getLoadedBodyModelName() === "miitomo") { + shirtKey = key2 + "_Top"; + } + let shoesColor = request.additionalInfo.shoesColor !== -1 && request.additionalInfo.shoesColor < 100 ? SwitchMiiColorTableSRGB[request.additionalInfo.shoesColor] : [1, 1, 1]; + switch (ClothesTypeList[request.additionalInfo.clothesType]) { + case 0 /* COLOR_MIXED */: { + const colorMixR = new Vector4(...shirtColor, 1), colorMixG = new Vector4(...shoesColor, 1), colorMixB = new Vector4(...pantsColor, 1), colorMixA = charModel ? request.clothingLinearColors !== true ? charModel.facelineColor : charModel.facelineColor.convertSRGBToLinear() : 16711680; + let tex = await colorMixTexture(getClothesTextures()[shirtKey], colorMixR, colorMixG, colorMixB, colorMixA, request.textureRenderer || request.renderer, request.texResolution); + shirtTexture = await loadBlobTextureWorker(tex, request.texResolution, request.texResolution); + break; + } + case 1 /* TEXTURE_COLOR */: { + shirtTexture = getClothesTextures()[shirtKey + suffix]; + break; + } + default: + alert("Something isn't right here"); + throw "???"; + } + request.renderer.initTexture(shirtTexture); + let nBodyMat = nBody.material; + let nLegsMat = nLegs.material; + nBodyMat.dispose(); + nLegsMat.dispose(); + let modulate2 = isUsingShader ? { + modulateType: 9, + modulateMode: 1, + color: new Color(0) + } : { color: new Color(16777215) }; + const params = { + ...modulate2, + map: shirtTexture + }; + const newBodyMat = new (await getShaderMaterialFromShaderType(request.shaderType))(params); + if (getLoadedBodyModelName() !== "miitomo") { + nBody.material = newBodyMat; + nLegs.material = newBodyMat; + } + console.log("mat changed!", newBodyMat, nBody, nLegs); + } + if (isTemporary) { + headMesh.position.set(0, bodyScale.y * 75, 0); + } else { + headModel.position.set(0, bodyScale.y * 75, 0); + } + if (isTemporary) + switch (request.type) { + case ViewType2.Face: + case ViewType2.MakeIcon: + case ViewType2.IconFovy45: + case ViewType2.CreditIcon: { + iconCamera.position.y += bodyScale.y * 76; + } + } + if (request.bodyModelType === "low" /* low */) { + bodyModelHands.visible = false; + } + if (isStreetPass()) { + console.log("is streetpass"); + var scaleVec = new Vector3; + bodyModel.getWorldScale(scaleVec); + const handScaleX = 1 / scaleVec.x * 5; + const handScaleY = 1 / scaleVec.y * 5; + console.log(handScaleX, handScaleY); + bodyModel.getObjectByName("handLPs").scale.set(handScaleX, handScaleY, handScaleX); + bodyModel.getObjectByName("handRPs").scale.set(handScaleX, handScaleY, handScaleX); + } else { + console.log("not streetpass"); + } + } + if (isTemporary) { + const target = createAndRenderToTarget(miiGroup, iconCamera, request.renderer, request.size, request.size); + setTimeout(() => { + const dataURL = renderTargetToDataURL(target, request.renderer); + target.dispose(); + charModel.dispose(); + if (request.drawBody) { + bodyModelBody.material.dispose(); + bodyModelLegs.material.dispose(); + } + if (hatModel) { + hatModel.traverse((n2) => { + if (!n2.isMesh) + return; + n2.geometry.dispose(); + n2.material.dispose(); + }); + } + resolve(dataURL); + }, 0); + } else { + return resolve({ + bodyModel, + bodyModelBody, + bodyModelHands, + bodyModelLegs, + charModel, + headModel, + miiGroup, + bodyModelAnims + }); + } + }); +} + +// src/worker.ts +var FFLModule; +var offscreenCanvas; +var workerRenderer; +var devicePixelRatio; +function log3(...message) { + console.debug("[FFLWorker]", ...message); +} +function initRenderer() { + workerRenderer = new WebGLRenderer({ + antialias: true, + alpha: true, + canvas: offscreenCanvas + }); +} +function blobToDataURL(blob) { + return new Promise((resolve) => { + var a2 = new FileReader; + a2.onload = function(e) { + resolve(e.target.result); + }; + a2.readAsDataURL(blob); + }); +} +self.onmessage = async (e) => { + log3("Message received from main script", e); + const input = e.data; + switch (input.type) { + case "Init": { + log3("Loading FFL Module"); + FFLModule = (await Promise.resolve().then(() => __toESM(require_ffl_emscripten(), 1))).default; + FFLModule = await FFLModule({ + locateFile: (path) => { + return "/dist/" + path; + } + }); + log3("Initialized Module!", FFLModule); + log3("Loading FFL Resource..."); + log3("Loading body models.."); + await loadBodyModels(); + log3("Loading hat models.."); + await loadHatModels(); + log3("Loading clothes textures.."); + await loadClothesTextures(); + let { module: module2 } = await initializeFFLWithResource(FFLModule, input.resourcePath); + FFLModule = module2; + log3("Loaded FFL Resource!"); + offscreenCanvas = input.offscreenCanvas; + devicePixelRatio = input.devicePixelRatio; + initRenderer(); + postMessage({ ready: true }); + break; + } + case "MakeIcon": { + log3("Call MakeIcon"); + var then = performance.now(); + let result = { + type: "dataURL", + result: "" + }; + try { + log3("making icon for view", Object.keys(ViewType)[input.request.type]); + const size2 = input.request.size * devicePixelRatio; + result = await createMiiRender({ + ...input.request, + renderer: workerRenderer, + size: size2, + module: FFLModule + }).catch((e2) => { + console.error("Oopsie", e2); + postMessage({ id: input.id, result: null, error: e2 }); + throw e2; + }); + } catch (e2) { + console.error(`Worker error: Could not make icon`, e2); + postMessage({ id: input.id, result: null, error: e2 }); + } finally { + var now2 = performance.now(); + log3(`Got it in ${(now2 - then).toFixed(0)}ms! Sending to main thread.`); + var url = undefined; + if (result !== undefined) { + if (input.useBlob) { + if (result.type === "blob") { + url = URL.createObjectURL(result.result); + } + } else { + if (result.type === "blob") { + url = await blobToDataURL(result.result); + } + } + postMessage({ + id: input.id, + result: url || result.result, + error: null + }); + } + } + } + } +}; diff --git a/public/index.html b/public/index.html index b8deb69..32c9479 100644 --- a/public/index.html +++ b/public/index.html @@ -19,9 +19,9 @@ /> - + - + - + - + diff --git a/public/popup.html b/public/popup.html new file mode 100644 index 0000000..e49d174 --- /dev/null +++ b/public/popup.html @@ -0,0 +1,121 @@ + + + + + + Mii Creator + + + + + + + + + + + + + + + + + + diff --git a/src/api.ts b/src/api.ts index 1a82cd4..d450228 100644 --- a/src/api.ts +++ b/src/api.ts @@ -18,7 +18,7 @@ function makeFrame(params: string, fullscreen: boolean) { // UNFINISHED, DO NOT USE YET export default { configuration: { - music: true, + music: true }, async editMii( data: string = "AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn", @@ -119,5 +119,5 @@ export default { ) { this.configuration.music = newConfiguration.music; } - }, + } }; diff --git a/src/class/2DRenderer.ts b/src/class/2DRenderer.ts index b2352c3..a9821d7 100644 --- a/src/class/2DRenderer.ts +++ b/src/class/2DRenderer.ts @@ -1,5 +1,5 @@ import { Config } from "../config"; -import type Mii from "../external/mii-js/mii"; +import type Mii from "./MiiData"; export class Mii2DRenderer { #canvas: HTMLCanvasElement; @@ -44,20 +44,20 @@ export class Mii2DRenderer { } async updateImages() { - const headImgURL = `${Config.renderer.renderFFLMakeIcon}&data=${this.mii - .encodeStudio() - .toString("hex")}&hatType=${this.mii.extHatType}&hatColor=${ - this.mii.extHatColor + const headImgURL = `${Config.renderer.renderFFLMakeIcon}&data=${this.mii.exportHex( + "studioData" + )}&hatType=${this.mii.hatType}&hatColor=${ + this.mii.hatCommonColor }&miiName=${encodeURIComponent( - this.mii.miiName - )}&creatorName=${encodeURIComponent(this.mii.creatorName)}`; + this.mii.nickname + )}&creatorName=${encodeURIComponent(this.mii.creator)}`; // const bodyImgURL = `./assets/images/2d/m-body-0.png`; // const pantImageURL = `./assets/images/2d/m-legs-gray.png`; this.#headImageFront.src = headImgURL + "&splitMode=front"; this.#headImageBack.src = headImgURL + "&splitMode=back"; - this.#bodyImage.src = this.mii.studioAssetUrlBody(); // bodyImgURL; + // this.#bodyImage.src = this.mii.studioAssetUrlBody(); // bodyImgURL; // this.#pantsImage.src = pantImageURL; await Promise.all([ @@ -78,7 +78,7 @@ export class Mii2DRenderer { console.log("Body image loaded"); resolve(true); }; - }), + }) // new Promise((resolve) => { // this.#pantsImage.onload = () => { // console.log("Pant image loaded"); diff --git a/src/class/3DScene.ts b/src/class/3DScene.ts index 18d1448..5ced780 100644 --- a/src/class/3DScene.ts +++ b/src/class/3DScene.ts @@ -7,40 +7,50 @@ import { // very hacky but it works to fix the shader bug... import { GLTFLoader } from "./3d/Custom_GLTFLoader"; import CameraControls from "camera-controls"; -import Mii from "../external/mii-js/mii"; +// import Mii from "../external/mii-js/mii"; +import Mii from "../class/MiiData"; import { MiiFavoriteColorLookupTable, MiiFavoriteColorVec3Table, MiiSwitchSkinColorSRGB, - MiiSwitchSkinColorLinear, - SwitchMiiColorTableLinear, - SwitchMiiColorTableSRGB + SwitchMiiColorTableSRGB, + ForbiddenShirtPantColors } from "../constants/ColorTables"; import { - cMaterialName, + cPantsColorBlue, cPantsColorGold, - cPantsColorGoldLinear, cPantsColorGray, - cPantsColorGrayLinear, cPantsColorRed, - cPantsColorRedLinear, MiiFavoriteFFLColorLookupTable } from "./3d/shader/fflShaderConst"; -import { MiiEditor, RenderPart } from "./MiiEditor"; +import { BodyUpdateType, MiiEditor, RenderPart } from "./MiiEditor"; import { Config } from "../config"; import { getSoundManager } from "./audio/SoundManager"; import { SparkleParticle } from "./3d/effect/SparkleParticle"; -import { multiplyTexture } from "./3d/canvas/multiplyTexture"; -import { HatType, HatTypeList } from "../constants/Extensions"; -import localforage from "localforage"; -import { traverseAddShader, traverseMesh } from "./3d/shader/ShaderUtils"; +import { + ClothesType, + ClothesTypeList, + ExtClothesList, + HatType, + HatTypeList +} from "../constants/Extensions"; +import { + cleanupLights, + getShaderMaterialFromShaderType, + getSimpleMaterialAddLights, + traverseAddShader, + traverseMesh +} from "./3d/shader/ShaderUtils"; import { getSetting } from "../util/SettingsHelper"; import { ShaderType } from "../constants/BodyShaderTypes"; import { getHeadModel, getMaskTex, type ModelFlag } from "../util/MiiRendering"; -import type { CharModel } from "../external/ffl.js/ffl"; -import { LUTShaderMaterial } from "../external/ffl.js/LUTShaderMaterial"; -import { FFLShaderMaterial } from "../external/ffl.js/FFLShaderMaterial"; +import { makeExpressionFlag, type CharModel } from "../external/ffl.js/ffl"; import JSZip from "jszip"; +import { streetpassHandScaling } from "../util/scaling"; +import { colorMixTexture } from "./3d/shader/ColorMix"; +import { loadBlobTexture } from "../ui/pages/library/util/3DModel"; +import FFLShaderMaterial from "../external/ffl.js/FFLShaderMaterial"; +// import Stats from "three/examples/jsm/libs/stats.module.js"; export enum CameraPosition { MiiHead, @@ -59,8 +69,7 @@ export class Mii3DScene { #scene: THREE.Scene; #renderer: THREE.WebGLRenderer; #parent: HTMLElement; - #pastCharModel!: CharModel; - #pastCharMask!: CharModel; + charModel!: CharModel | null; mii: Mii; ready: boolean; headReady: boolean; @@ -77,7 +86,10 @@ export class Mii3DScene { shaderType!: ShaderType; simpleShaderLegacyColors!: boolean; hatModels!: GLTF[]; + clothingTextures!: Record; editor?: MiiEditor; + camSetup!: () => void; + texResolution: number; constructor( mii: Mii, @@ -101,6 +113,7 @@ export class Mii3DScene { ); this.ready = false; this.headReady = false; + this.texResolution = 512; if (initCallback) this.#initCallback = initCallback; this.shaderOverride = shaderOverride; this.editor = editor; @@ -108,11 +121,21 @@ export class Mii3DScene { if (setupType === SetupType.Screenshot) { this.#renderer = new THREE.WebGLRenderer({ antialias: true, - preserveDrawingBuffer: true + preserveDrawingBuffer: true, + logarithmicDepthBuffer: true }); + this.texResolution = 1024; } else { this.#renderer = new THREE.WebGLRenderer({ antialias: true }); } + + // this.stats = new Stats(); + // document.body.appendChild(this.stats.dom); + + // To fix default materials colors looking washed out, + // shouldn't affect shader colors + this.#renderer.outputColorSpace = THREE.LinearSRGBColorSpace; + this.getRendererElement().classList.add("scene"); this.setupType = setupType; @@ -120,6 +143,9 @@ export class Mii3DScene { this.bodyModel = type; }); + // THREE.ColorManagement.enabled = false; + window.THREE = THREE; + getSetting("shaderType").then((type) => { this.shaderType = type; getSetting("simpleShaderLegacyColors").then((val) => { @@ -131,7 +157,8 @@ export class Mii3DScene { type.startsWith("wiiu") || type === "switch" ) { - this.#gltfLoader = new GLTFLoader() as TrueGLTFLoader; + // this.#gltfLoader = new GLTFLoader() as TrueGLTFLoader; + this.#gltfLoader = new TrueGLTFLoader(); } else { this.#gltfLoader = new TrueGLTFLoader(); } @@ -175,8 +202,8 @@ export class Mii3DScene { this.#renderer.domElement ); if (setupType === SetupType.Normal) { - const camSetup = async () => { - const canPan = await localforage.getItem("settings_cameraPan"); + this.camSetup = async () => { + const canPan = this.cameraPan !== undefined ? this.cameraPan : false; if (canPan !== true) { console.log("canPan is not false:", canPan); @@ -186,31 +213,26 @@ export class Mii3DScene { this.#controls.touches.one = CameraControls.ACTION.TOUCH_ROTATE; this.#controls.touches.two = CameraControls.ACTION.TOUCH_DOLLY; this.#controls.touches.three = CameraControls.ACTION.NONE; - this.#controls.minDistance = 8; + this.#controls.enabled = true; + this.#controls.minDistance = 10; this.#controls.maxDistance = 35; - // this.#controls.minDistance = 60; - // this.#controls.maxDistance = 100; this.#controls.minAzimuthAngle = -Math.PI; this.#controls.maxAzimuthAngle = Math.PI; + this.#controls.zoomTo(1); this.cameraPan = true; } else { - this.#camera.fov = 15; - this.#camera.updateProjectionMatrix(); - this.#controls.mouseButtons.left = CameraControls.ACTION.NONE; - this.#controls.mouseButtons.right = CameraControls.ACTION.NONE; - this.#controls.mouseButtons.wheel = CameraControls.ACTION.NONE; - this.#controls.touches.one = CameraControls.ACTION.NONE; - this.#controls.touches.two = CameraControls.ACTION.NONE; - this.#controls.touches.three = CameraControls.ACTION.NONE; + console.log("canPan is True:", canPan); + this.#controls.enabled = false; this.#controls.minDistance = 60; this.#controls.maxDistance = 140; this.#controls.minAzimuthAngle = -Math.PI; this.#controls.maxAzimuthAngle = Math.PI; this.#controls.dollyTo(380 / 10); + this.#controls.zoomTo(2.5); this.cameraPan = false; } }; - camSetup(); + this.camSetup(); } if (setupType === SetupType.Screenshot) { @@ -242,7 +264,12 @@ export class Mii3DScene { const animate = (time: number) => { const delta = clock.getDelta(); - this.#renderer.render(this.#scene, this.#camera); + // this.stats.update(); + try { + this.#renderer.render(this.#scene, this.#camera); + } catch (e) { + console.error(e); + } this.animators.forEach((f) => f(time, delta)); }; @@ -251,12 +278,15 @@ export class Mii3DScene { this.#camera.aspect = this.#parent.offsetWidth / this.#parent.offsetHeight; this.#camera.updateProjectionMatrix(); - setTimeout(() => { - this.resizeRendererToDisplaySize(); - }, 500); + this.resize(); } - async #loadHatModels(path: string = "./assets/models/hat_models_bundle.zip") { - this.hatModels = []; + async #loadZip( + path: string, + out: keyof Mii3DScene, + useKeys: boolean, + type: "gltf" | "texture" + ) { + (this[out] as any) = []; // Load hat models bundle const data = await fetch(path).then((j) => j.blob()); @@ -268,11 +298,21 @@ export class Mii3DScene { } const resolves = await Promise.all(promises); for (let i = 0; i < fileList.length; i++) { - console.log("File:", fileList[i]); const url = URL.createObjectURL(resolves[i]); - const gltf = await this.#gltfLoader.loadAsync(url); - // i + 1 since hat type starts from index 1. - this.hatModels[i + 1] = gltf; + let result: any; + if (type === "gltf") { + result = await this.#gltfLoader.loadAsync(url); + } else { + result = await this.#textureLoader.loadAsync(url); + (result as THREE.Texture).flipY = false; + } + if (useKeys) { + const fileName = fileList[i].split("."); + fileName.pop(); + (this[out] as any)[fileName.join(".")] = result; + } else { + (this[out] as any)[i] = result; + } URL.revokeObjectURL(url); } } @@ -299,43 +339,86 @@ export class Mii3DScene { if (part === CameraPosition.MiiFullBody) { if (body !== undefined && head !== undefined) { - const box = new THREE.Box3().setFromObject(body); - const box2 = new THREE.Box3().setFromObject(head); - pos.y = box2.max.y / 2; + const box = new THREE.Box3().setFromObject(head); + pos.y = box.max.y / 2; } if (onlyReturn === false) { + let minInput = 0, + maxInput = 127, + minOutput = 38, + maxOutput = 40; this.#controls.moveTo(pos.x, pos.y, pos.z, transition); this.#controls.rotateTo(0, Math.PI / 2, transition); - this.#controls.dollyTo(40, transition); if (this.cameraPan === false) { - this.#controls.dollyTo(120, transition); + minOutput = 80; + maxOutput = 96; } + this.#controls.dollyTo( + minOutput + + ((this.mii.height - minInput) / (maxInput - minInput)) * + (maxOutput - minOutput), + transition + ); } return pos; } else if (part === CameraPosition.MiiHead) { - if (body !== undefined) { - const box = new THREE.Box3().setFromObject(body); - pos.y = box.max.y - box.min.y; - } - if (onlyReturn === false) { - this.#controls.moveTo(pos.x, pos.y + 2, pos.z, transition); - this.#controls.rotateTo(0, Math.PI / 2, transition); - this.#controls.dollyTo(25, transition); - if (this.cameraPan === false) { - this.#controls.dollyTo(65, transition); - } + switch (this.setupType) { + case SetupType.Normal: + if (body !== undefined) { + const box = new THREE.Box3().setFromObject(body); + pos.y = box.max.y - box.min.y; + } + if (onlyReturn === false) { + this.#controls.moveTo(pos.x, pos.y + 2, pos.z, transition); + this.#controls.rotateTo(0, Math.PI / 2, transition); + this.#controls.dollyTo(25, transition); + if (this.cameraPan === false) { + this.#controls.moveTo(pos.x, pos.y + 1.75, pos.z, transition); + this.#controls.dollyTo(65, transition); + } + } + return pos; + case SetupType.Screenshot: + if (this.getHead() !== undefined) { + const box = new THREE.Box3().setFromObject(this.getHead()!); + pos.y = box.max.y - box.min.y; + } + this.#controls.moveTo(pos.x, pos.y + 1.75, pos.z, transition); + this.#controls.rotateTo(0, Math.PI / 2, transition); + this.#controls.dollyTo(30, transition); + break; } - return pos; } } + focusCameraUpdate() { + if (this.ready) this.camSetup(); + if (this.anim) + switch (this.cameraPan) { + case true: + for (const [_, anim] of this.anim) { + anim.timeScale = 0.5; + } + break; + case false: + for (const [_, anim] of this.anim) { + anim.reset(); + anim.timeScale = 0; + } + break; + } + this.focusCamera(this.currentPosition, true, false); + } playEndingAnimation() { + this.#controls.enabled = false; this.focusCamera(CameraPosition.MiiFullBody, true); let heads = this.#scene.getObjectsByProperty("name", "MiiHead"); for (const head of heads) { + if (Config.renderer.useRendererServer) { + } this.traverseAddFaceMaterial( head as THREE.Mesh, `&data=${encodeURIComponent( - this.mii.encodeStudio().toString("hex") + this.mii.exportHex("studioData") )}&expression=1&width=512` ); } @@ -348,40 +431,98 @@ export class Mii3DScene { width: number = this.#parent.offsetWidth, height: number = this.#parent.offsetHeight ) { - this.#camera.aspect = width / height; - this.#camera.updateProjectionMatrix(); - this.resizeRendererToDisplaySize(); + this.resizeRendererToDisplaySize(width, height); + + // adjust ui depending on screen size + let zoomValue = 1, + widescreen = window.innerWidth > 960, + is2DMode = !this.cameraPan; + switch (this.currentPosition) { + case CameraPosition.MiiHead: + if (is2DMode) zoomValue = widescreen ? 2.5 : 3.25; + else zoomValue = widescreen ? 1 : 1.25; + break; + case CameraPosition.MiiFullBody: + if (is2DMode) zoomValue = widescreen ? 2.5 : 3.25; + else zoomValue = 1; + break; + } + + if (this.setupType !== SetupType.Screenshot) { + this.#controls.zoomTo(zoomValue, true); + } else this.#controls.zoomTo(1); } // copied from three.js manual code lol - resizeRendererToDisplaySize() { + resizeRendererToDisplaySize(width: number, height: number) { + this.#camera.aspect = width / height; + this.#camera.updateProjectionMatrix(); const canvas = this.#renderer.domElement; const pixelRatio = window.devicePixelRatio; - const width = Math.floor(canvas.clientWidth * pixelRatio); - const height = Math.floor(canvas.clientHeight * pixelRatio); - const needResize = canvas.width !== width || canvas.height !== height; - if (needResize) { - this.#renderer.setSize(width, height, false); - } - return needResize; + const w = Math.floor(canvas.clientWidth * pixelRatio); + const h = Math.floor(canvas.clientHeight * pixelRatio); + // const needResize = canvas.width !== w || canvas.height !== h; + // if (needResize) { + this.#renderer.setSize(w, h, false); + // } + // return needResize; } + preparing!: boolean; async init() { if (this.ready) return; + if (this.preparing) return; + this.preparing = true; this.ready = false; this.getRendererElement().style.opacity = "0"; await this.#addBody(); + this.updateBody(BodyUpdateType.ClothingUpdate); + this.swapAnimation("Wait", true); - await this.#loadHatModels(); - //await this.updateMiiHead(); - // ^^ will happen on first render() + await this.#loadZip( + "./assets/models/hat_models_bundle.zip", + "hatModels", + false, + "gltf" + ); + await this.#loadZip( + "./assets/images/mii_clothes_textures_bundle.zip", + "clothingTextures", + true, + "texture" + ); this.ready = true; + this.preparing = false; + this.resize(); + this.updateBody(BodyUpdateType.ClothingUpdate); if (this.setupType === SetupType.Screenshot) { this.#initCallback && this.#initCallback(this.#renderer); + this.resize(); + requestAnimationFrame(() => { + this.resize(); + }); + setTimeout(() => { + this.resize(); + }, 0); } else { // weird hacky fix to correct the camera position at startup + this.resize(); setTimeout(() => { + this.resize(); this.focusCamera(CameraPosition.MiiHead, true, false); }, 500); } + + // this.#scene.fog = new THREE.FogExp2(0xff0000, 1); + // let a = new THREE.PlaneGeometry(50, 50); + // let m = new THREE.Mesh( + // a, + // new FFLShaderMaterial({ + // color: new THREE.Color(0x00ff00), + // modulateMode: 0, + // modulateType: 0 + // }) as any + // ); + // m.rotation.set(-(Math.PI / 2), 0, 0); + // this.#scene.add(m); } getRendererElement() { return this.#renderer.domElement; @@ -418,13 +559,17 @@ export class Mii3DScene { this.currentAnim = newAnim; let x: ("m" | "f")[] = ["m", "f"]; for (const key of x) { - this.anim.set( - key, - this.mixer.clipAction( + let clip; + + try { + clip = this.mixer.clipAction( this.animations.get(`${key}-${newAnim}`)!, this.#scene.getObjectByName(key) - ) - ); + ); + } catch (e) { + return; + } + this.anim.set(key, clip); this.anim .get(key)! .reset() @@ -490,27 +635,28 @@ export class Mii3DScene { color: MiiFavoriteColorLookupTable[this.mii.favoriteColor] }); // adds shader material - else traverseMesh(gBodyMesh, this.mii); + else traverseMesh(gBodyMesh, this.shaderType); const gHandsMesh = glb.scene.getObjectByName( `hands_${type}` )! as THREE.Mesh; - gHandsMesh.geometry.userData = { - cullMode: 1, - modulateColor: MiiFavoriteFFLColorLookupTable[this.mii.favoriteColor], - modulateMode: 0, - modulateType: 9 - }; - if (this.shaderOverride) - gHandsMesh.material = new THREE.MeshStandardMaterial({ - roughness: 1, - metalness: 1, - color: MiiFavoriteColorLookupTable[this.mii.favoriteColor] - }); - // adds shader material - else { - if (Config.renderer.useRendererServer) - traverseMesh(gHandsMesh, this.mii); + if (gHandsMesh) { + gHandsMesh.geometry.userData = { + cullMode: 1, + modulateColor: MiiFavoriteFFLColorLookupTable[this.mii.favoriteColor], + modulateMode: 0, + modulateType: 9 + }; + if (this.shaderOverride) + gHandsMesh.material = new THREE.MeshStandardMaterial({ + roughness: 1, + metalness: 1, + color: MiiFavoriteColorLookupTable[this.mii.favoriteColor] + }); + // adds shader material + else { + traverseMesh(gHandsMesh, this.shaderType); + } } const gLegsMesh = glb.scene.getObjectByName( @@ -533,7 +679,7 @@ export class Mii3DScene { ) }); // adds shader material - else traverseMesh(gLegsMesh, this.mii); + else traverseMesh(gLegsMesh, this.shaderType); if (this.#scene.getObjectByName("m")) this.#scene.getObjectByName("m")!.visible = false; @@ -555,23 +701,39 @@ export class Mii3DScene { console.log("READY"); } + getShirtColor() { + return this.mii.shirtColor !== -1 && this.mii.shirtColor < 100 + ? SwitchMiiColorTableSRGB[this.mii.shirtColor] + : MiiFavoriteFFLColorLookupTable[this.mii.favoriteColor]; + } + getShoesColor() { + return this.mii.shoesColor !== -1 && this.mii.shoesColor < 100 + ? SwitchMiiColorTableSRGB[this.mii.shoesColor] + : [1, 1, 1]; + } getPantsColor() { - const useLinearColors = - this.shaderType === ShaderType.Simple && - this.simpleShaderLegacyColors === false - ? true - : false; - - if (this.mii.normalMii === false) { - return useLinearColors ? cPantsColorGoldLinear : cPantsColorGold; + if ( + this.mii.pantsColor !== -1 && + this.mii.pantsColor < 100 && + !ForbiddenShirtPantColors.includes(this.mii.pantsColor) + ) { + return SwitchMiiColorTableSRGB[this.mii.pantsColor]; + } + + if (this.mii.special) { + return cPantsColorGold; } if (this.mii.favorite) { - return useLinearColors ? cPantsColorRedLinear : cPantsColorRed; + return cPantsColorRed; + } + if (this.mii.temporary) { + return cPantsColorBlue; } - return useLinearColors ? cPantsColorGrayLinear : cPantsColorGray; + return cPantsColorGray; } - async updateBody(force?: boolean) { + async updateBody(updateType: BodyUpdateType = BodyUpdateType.None) { if (!this.ready) return; + this.resize(); this.type = this.mii.gender === 0 ? "m" : "f"; @@ -627,9 +789,15 @@ export class Mii3DScene { // @ts-expect-error debug window.scaleFactors = scaleFactors; + let body = this.type === "m" ? bodyM : bodyF; + const traverseBones = (object: THREE.Object3D) => { object.scale.set(scaleFactors.x, scaleFactors.y, scaleFactors.z); + if (this.bodyModel === "streetpass") { + streetpassHandScaling(body); + } + // this.#scene // .getObjectByName("MiiHead")! // .scale.set( @@ -745,6 +913,8 @@ export class Mii3DScene { if (bodyModel === "miitomo") { // hacky this.#scene.getObjectByName("MiiHead")!.rotation.z -= Math.PI / 2; + } else { + this.#scene.getObjectByName("MiiHead")!.position.y += 0.1; } } }; @@ -754,115 +924,176 @@ export class Mii3DScene { bodyN: THREE.Object3D, type: string ) => { - const isWiiUShader = + const hasShaderApplied = // (shaderSetting.startsWith("wiiu") || // shaderSetting === "lightDisabled") && this.shaderOverride === false; - const colorHands = await getSetting("bodyModelHands"); const nBody = bodyN .getObjectByName(type)! .getObjectByName("body_" + type)! as THREE.Mesh; - if (isWiiUShader) - (nBody.material as THREE.ShaderMaterial).uniforms.u_const1.value = - new THREE.Vector4( - ...MiiFavoriteFFLColorLookupTable[this.mii.favoriteColor] - ); + const nLegs = bodyN .getObjectByName(type)! .getObjectByName("legs_" + type)! as THREE.Mesh; - if (isWiiUShader) - (nLegs.material as THREE.ShaderMaterial).uniforms.u_const1.value = - new THREE.Vector4(...this.getPantsColor()); - - if (shaderSetting === "none" || this.shaderOverride) { - if (this.simpleShaderLegacyColors === false) { - const lookupTable = MiiFavoriteColorLookupTable; - (nBody.material as THREE.MeshBasicMaterial).color.set( - lookupTable[this.mii.favoriteColor] - ); - } else { - const lookupTable = MiiFavoriteColorVec3Table; - (nBody.material as THREE.MeshBasicMaterial).color.set( - lookupTable[this.mii.favoriteColor][0], - lookupTable[this.mii.favoriteColor][1], - lookupTable[this.mii.favoriteColor][2] + + const colorHands = await getSetting("bodyModelHands"); + + if (updateType === BodyUpdateType.ClothingUpdate) { + if (hasShaderApplied) { + (nBody.material as any).color = new THREE.Color( + ...this.getShirtColor() ); } + if (hasShaderApplied) + (nLegs.material as any).color = new THREE.Color( + ...this.getPantsColor() + ); - (nLegs.material as THREE.MeshBasicMaterial).color.set( - this.getPantsColor()[0], - this.getPantsColor()[1], - this.getPantsColor()[2] - ); + if (this.mii.clothesType !== -1) { + console.log("clothing update"); + let shirtTexture: THREE.Texture, + pantsTexture: THREE.Texture | null = null; + + const suffix = this.type == "f" ? "F" : ""; + let key = `${this.bodyModel}_${ + ExtClothesList[this.mii.clothesType] + }${suffix}`; + let shirtKey = key; + if (this.bodyModel === "miitomo") { + shirtKey = key + "_Top"; + } + + switch (ClothesTypeList[this.mii.clothesType]) { + case ClothesType.COLOR_MIXED: { + const colorMixR = new THREE.Vector4(...this.getShirtColor(), 1), + colorMixG = new THREE.Vector4(...this.getShoesColor(), 1), + colorMixB = new THREE.Vector4(...this.getPantsColor(), 1), + colorMixA = this.charModel + ? this.charModel!.facelineColor + : 0xff0000; + + console.log("Shirt Texture Key:", shirtKey); + let tex = await colorMixTexture( + this.clothingTextures[shirtKey], + colorMixR, + colorMixG, + colorMixB, + colorMixA, + this.#renderer + ); + shirtTexture = await loadBlobTexture(tex); + + console.log("loaded shirt texture!"); + + // if (this.bodyModel === "miitomo") { + // const pantsKey = key + "_Bot"; + // let tex = await colorMixTexture( + // this.clothingTextures[pantsKey], + // colorMixR, + // colorMixG, + // colorMixB, + // colorMixA + // ); + // pantsTexture = await loadBlobTexture(tex); + // } + break; + } + case ClothesType.TEXTURE_COLOR: { + shirtTexture = this.clothingTextures[shirtKey + suffix]; + break; + } + default: + alert("Something isn't right here"); + throw "???"; + } + this.#renderer.initTexture(shirtTexture); + + let nBodyMat = nBody.material as any; + let nLegsMat = nLegs.material as any; + + nBodyMat.dispose(); + nLegsMat.dispose(); + + const params = { + modulateType: 9, + modulateMode: 1, + map: shirtTexture + }; + const newBodyMat = new (await getShaderMaterialFromShaderType())( + params + ); + if (this.bodyModel !== "miitomo") nBody.material = newBodyMat as any; + + if (this.bodyModel === "miitomo" && pantsTexture !== null) { + const params = { + modulateType: 9, + modulateMode: 1, + map: pantsTexture + }; + const newLegsMat = new (await getShaderMaterialFromShaderType())( + params + ); + nLegs.material = newLegsMat as any; + } else { + nLegs.material = newBodyMat as any; + } + + console.log("mat changed!", newBodyMat, nBody, nLegs); + } else { + (nBody.material as any) = + new (await getShaderMaterialFromShaderType())({ + color: new THREE.Color( + this.getShirtColor()[0], + this.getShirtColor()[1], + this.getShirtColor()[2] + ), + modulateMode: 0, + modulateType: 9 + }); + (nLegs.material as any) = + new (await getShaderMaterialFromShaderType())({ + color: new THREE.Color( + this.getPantsColor()[0], + this.getPantsColor()[1], + this.getPantsColor()[2] + ), + modulateMode: 0, + modulateType: 10 + }); + } } const nHands = bodyN .getObjectByName(type)! .getObjectByName("hands_" + type)! as THREE.Mesh; - if (colorHands === true) { - let desiredColor: [number, number, number] = [1, 0, 0]; - - // previous revision of hand color guessing, keeping it here because it may be used later..? - // let head = this.#scene.getObjectByName("MiiHead"); - // if (head) { - // // attempt to get current skin color... - // if (isWiiUShader) { - // this.mii.skinColor - // MiiSwitchSkinColorList - // // desiredColor = ( - // // (head.children[0] as THREE.Mesh).material as THREE.ShaderMaterial - // // ).uniforms.u_const1.value; - // } else { - // const color = ( - // (head.children[0] as THREE.Mesh) - // .material as THREE.MeshBasicMaterial - // ).color; - // desiredColor = [color.r, color.g, color.b, 1]; - // } - // } else { - // console.log("OOOPS"); - // } - - // little bit hacky lol because "simple" shader depends on linear instead of sRGB colors. - if (this.mii.extFacePaintColor !== 0) { - if (shaderSetting === "none") { - desiredColor = - SwitchMiiColorTableLinear[this.mii.extFacePaintColor - 1]; + if (nHands) { + if (colorHands === true) { + let desiredColor: [number, number, number] = [1, 0, 0]; + + // TODO: REMOVE ALL REFERENCES TO SIMPLE SHADER + if (this.mii.facePaintColor !== -1) { + desiredColor = SwitchMiiColorTableSRGB[this.mii.facePaintColor]; } else { - desiredColor = - SwitchMiiColorTableSRGB[this.mii.extFacePaintColor - 1]; + desiredColor = MiiSwitchSkinColorSRGB[this.mii.facelineColor]; } - } else { - if (shaderSetting === "none") { - desiredColor = MiiSwitchSkinColorLinear[this.mii.skinColor]; - } else { - desiredColor = MiiSwitchSkinColorSRGB[this.mii.skinColor]; + + if (hasShaderApplied) { + (nHands.material as THREE.MeshBasicMaterial).color = + new THREE.Color(...desiredColor); + } else if (this.shaderOverride) { + (nHands.material as THREE.MeshBasicMaterial).color.set( + desiredColor[0], + desiredColor[1], + desiredColor[2] + ); } - } - // console.log( - // `Desired Color: %c${JSON.stringify(desiredColor)}`, - // `rgb(${desiredColor[0] * 255}, ${desiredColor[1] * 255}, ${ - // desiredColor[2] * 255 - // })` - // ); - - if (isWiiUShader) { - (nHands.material as THREE.ShaderMaterial).uniforms.u_const1.value = - new THREE.Vector4(...desiredColor, 1); - } else if (shaderSetting === "none" || this.shaderOverride) { - (nHands.material as THREE.MeshBasicMaterial).color.set( - desiredColor[0], - desiredColor[1], - desiredColor[2] - ); + this.handColor = desiredColor; + } else { + nHands.material = nBody.material; } - - this.handColor = desiredColor; - } else { - nHands.material = nBody.material; } }; @@ -896,10 +1127,14 @@ export class Mii3DScene { } // Update camera smoothly when body scaling is changed in the editor - if (force) + if (updateType === BodyUpdateType.RepositionCamera) requestAnimationFrame(() => { this.focusCamera(this.currentPosition, true, true, false); }); + else + requestAnimationFrame(() => { + this.resize(); + }); } debugGetScene() { return this.#scene; @@ -923,34 +1158,13 @@ export class Mii3DScene { switch (renderPart) { case RenderPart.Head: - if (head.length > 0) { - head.forEach((h) => { - // Dispose of old head materials - h.traverse((c) => { - let child = c as THREE.Mesh; - if (child.isMesh) { - child.geometry.dispose(); - const mat = child.material as THREE.MeshBasicMaterial; - if (mat.map) mat.map.dispose(); - mat.dispose(); - } - }); - }); - } - try { // CUSTOM APP-SPECIFIC DATA - let favoriteColor: number = this.mii.favoriteColor; - // console.log("fav color:", favoriteColor); - - const tmpMii = new Mii(this.mii.encode()); - if (this.mii.extHatColor !== 0) { - tmpMii.favoriteColor = this.mii.extHatColor - 1; - } + const tmpMii = new Mii(this.mii.export("miic")); let params: Record = {}; - if (this.mii.extHatType !== 0) { + if (this.mii.hatType !== -1) { // Custom hat model types - switch (HatTypeList[this.mii.extHatType]) { + switch (HatTypeList[this.mii.hatType]) { case HatType.HAT: params["modelType"] = "hat"; break; @@ -966,21 +1180,23 @@ export class Mii3DScene { params["verifyCharInfo"] = "0"; let GLB: GLTF; if (Config.renderer.useRendererServer) { - GLB = await this.#gltfLoader.loadAsync( - tmpMii.studioUrl({ - ext: "glb", - texResolution: "512", - miiName: this.mii.miiName, - creatorName: this.mii.creatorName, - miic: encodeURIComponent(this.mii.encode().toString("base64")), - ...params - } as unknown as any) - ); + // TODO: FIX THIS FOR SERVER RENDERING LOL + GLB = null as any; + // GLB = await this.#gltfLoader.loadAsync( + // tmpMii.studioUrl({ + // ext: "glb", + // texResolution: "512", + // miiName: this.mii.miiName, + // creatorName: this.mii.creatorName, + // miic: encodeURIComponent(this.mii.encode().toString("base64")), + // ...params + // } as unknown as any) + // ); } else { - if (this.#pastCharModel) { - // console.log("Past Char Model:", this.#pastCharModel); - if (this.#pastCharModel.dispose) this.#pastCharModel.dispose(); - } + // if (this.#pastCharModel) { + // // console.log("Past Char Model:", this.#pastCharModel); + // if (this.#pastCharModel.dispose) this.#pastCharModel.dispose(); + // } let modelType: ModelFlag = "NORMAL"; @@ -993,30 +1209,51 @@ export class Mii3DScene { break; } - GLB = await getHeadModel(tmpMii, this, modelType); + GLB = await getHeadModel( + tmpMii, + this.getRenderer(), + modelType, + this.texResolution + ); } //@ts-expect-error window.GLB = GLB; - this.mii.favoriteColor = favoriteColor; GLB.scene.name = "MiiHead"; // head is no longer attached to head bone physically, no more need to offset rotation // GLB.scene.rotation.set(-Math.PI / 2, 0, 0); - GLB.scene.scale.set(0.12, 0.12, 0.12); + // GLB.scene.scale.set(0.12, 0.12, 0.12); + var headScale = 0.14; + GLB.scene.scale.set(headScale, headScale, headScale); // enable shader on head - this.#scene.remove(...head); - // hack to force remove head anyways - this.#scene.getObjectsByProperty("name", "MiiHead").forEach((obj) => { - obj.parent!.remove(obj); - }); + if (head) { + this.#scene.remove(...head); + // hack to force remove head anyways + this.#scene + .getObjectsByProperty("name", "MiiHead") + .forEach((obj) => { + obj.parent!.remove(obj); + }); + } + console.debug("Adding head to scene"); + this.resize(); + + this.#scene.add(GLB.scene); if (Config.renderer.useRendererServer) - traverseAddShader(GLB.scene, this.mii); - else { - this.#pastCharModel = (GLB as any).CharModel; + traverseAddShader(GLB.scene, this.shaderType); + + let lights = await getSimpleMaterialAddLights(this.shaderType); + cleanupLights(this.#scene); + if (lights) { + lights(this.#scene); } + // else { + // this.#pastCharModel = (GLB as any).CharModel; + // } + console.debug("Traversing shader now"); const body = this.#scene.getObjectByName(this.type)!; @@ -1043,8 +1280,17 @@ export class Mii3DScene { } const bodyModelType = this.bodyModel; - this.#scene.add(GLB.scene); - console.debug("Adding head to scene"); + + if (Config.renderer.useRendererServer === false) { + if (this.charModel) { + // console.log("Past Char Model:", this.#pastCharModel); + if (this.charModel.dispose) { + this.charModel.dispose(); + this.charModel = null; + } + } + this.charModel = (GLB as any).CharModel; + } // Hacky fix for head being snapped in the wrong direction for 1 frame if (bodyModelType === "miitomo") { @@ -1052,20 +1298,35 @@ export class Mii3DScene { } try { - if (this.mii.extHatType !== 0) { - let hatModel = - this.hatModels[this.mii.extHatType].scene.clone(true); + if (this.mii.hatType !== -1) { + let hatModel = this.hatModels[this.mii.hatType].scene.clone(true); hatModel.name = "HatScene"; // hatModel.scene.renderOrder = -1; let i = 0; if (GLB.asset.extras.partsTransform.hatTranslate) { - const [x, y, z] = GLB.asset.extras.partsTransform.hatTranslate; - console.log(GLB.asset.extras.partsTransform.hatTranslate); - const vec = new THREE.Vector3(x, y, z); + const vec = GLB.asset.extras.partsTransform.hatTranslate; hatModel.position.add(vec); //@ts-expect-error window.hatModel = hatModel; + + // TODO: Hats + switch (HatTypeList[this.mii.hatType]) { + case HatType.SIDE: + // const pos = + // GLB.asset.extras.partsTransform.headSideTranslate; + // hatModel.position.set(0, 0, 0); + // hatModel.position.copy(pos); + // const [rx, ry, rz] = + // GLB.asset.extras.partsTransform.headSideRotate; + // const rot = new THREE.Vector3(rx, ry, rz); + // hatModel.rotation.setFromVector3(rot); + break; + case HatType.FRONT: + break; + case HatType.TOP: + break; + } } let shaderSetting = await getSetting("shaderType"); hatModel.traverse((o: any) => { @@ -1108,11 +1369,14 @@ export class Mii3DScene { // ignore: 1, cullMode: 0, modulateColor: - MiiFavoriteColorVec3Table[ - this.mii.extHatColor !== 0 - ? this.mii.extHatColor - 1 - : this.mii.favoriteColor - ], + this.mii.hatCommonColor !== -1 && + this.mii.hatCommonColor < 100 + ? SwitchMiiColorTableSRGB[this.mii.hatCommonColor] + : MiiFavoriteColorVec3Table[ + this.mii.hatFavoriteColor !== -1 + ? this.mii.hatFavoriteColor + : this.mii.favoriteColor + ], modulateMode: 5, //5, modulateType: 5 //5, }; @@ -1122,7 +1386,7 @@ export class Mii3DScene { if (Config.renderer.useRendererServer === false) { // apply shader material! // var mc = m.geometry.userData["modulateColor"]; - traverseMesh(m, this.mii); + traverseMesh(m, this.shaderType); // m.material = new LUTShaderMaterial({ // modulateMode: 0, // modulateType: 5, @@ -1151,7 +1415,7 @@ export class Mii3DScene { this.traverseAddFaceMaterial( h as THREE.Mesh, `&data=${encodeURIComponent( - this.mii.encodeStudio().toString("hex") + this.mii.exportHex("studioData") )}&width=512` ); }); @@ -1161,7 +1425,8 @@ export class Mii3DScene { if (this.headReady === false) this.fadeIn(); this.headReady = true; - await this.updateBody(); + // await this.updateBody(); + this.resize(); } particles!: SparkleParticle[]; @@ -1183,8 +1448,10 @@ export class Mii3DScene { this.#textureLoader.load("./assets/images/star.png", (texture) => { const pos = new THREE.Vector3(); const box = new THREE.Box3(); - this.#scene.getObjectByName("MiiHead")!.getWorldPosition(pos); - box.setFromObject(this.#scene.getObjectByName("MiiHead")!); + if (this.#scene.getObjectByName("MiiHead") !== undefined) { + this.#scene.getObjectByName("MiiHead")!.getWorldPosition(pos); + box.setFromObject(this.#scene.getObjectByName("MiiHead")!); + } let particle = new SparkleParticle( this.#scene, new THREE.Vector3(0, pos.y + box.min.y / 2, 2), @@ -1229,39 +1496,60 @@ export class Mii3DScene { const mat = child.material as THREE.MeshBasicMaterial; const oldMat = mat; - var loadUrl = Config.renderer.renderFaceURL + urlParams; + var loadUrl: string | null = + Config.renderer.renderFaceURL + urlParams; + let tex: THREE.Texture; if (Config.renderer.useRendererServer === false) { console.log("READY"); - const { img, model } = await getMaskTex(this.mii, this); + const params = new URLSearchParams(urlParams); + let expressionFlag = new Uint32Array([ + 1, 0, 0 + ]) as Uint32Array; + + if (params.has("expression")) { + expressionFlag = makeExpressionFlag( + Number(params.get("expression")!) + ); + } + console.log( + "Expression:", + params.get("expression"), + expressionFlag + ); + const { img, model } = await getMaskTex( + this.mii, + this.getRenderer(), + expressionFlag + ); console.log("DONE"); - loadUrl = img; + loadUrl = null; + tex = img; model.dispose(); - console.log("Mask URL:", img); + } else { + tex = await this.#textureLoader.loadAsync(loadUrl); } - const tex = await this.#textureLoader.loadAsync(loadUrl); - if (tex) { - // Simple shader mask color space fix - if ((await getSetting("shaderType")) === ShaderType.Simple) { - tex.colorSpace = "srgb"; - } tex.flipY = false; // Initialize the texture on the GPU to prevent lag frames this.#renderer.initTexture(tex); - child.material = new THREE.MeshStandardMaterial({ - map: tex, - emissiveIntensity: 1, - transparent: true, - metalness: 1, - toneMapped: true, - alphaTest: 0.5 - }); + (child.material as THREE.MeshBasicMaterial)!.map = tex; + (child.material as THREE.MeshBasicMaterial)!.transparent = + true; + + // child.material = new THREE.MeshBasicMaterial({ + // map: tex, + // // emissiveIntensity: 1, + // transparent: true, + // // metalness: 1, + // // toneMapped: true, + // alphaTest: 0.5 + // }); // Now... Replace it with shader material - traverseMesh(child, this.mii); + // traverseMesh(child, this.mii); oldMat.dispose(); } @@ -1289,6 +1577,8 @@ export class Mii3DScene { } shutdown() { + // this.stats.dom.parentElement!.removeChild(this.stats.dom); + // this.stats.end(); Array.from(this.animators.keys()).forEach((k) => { this.animators.delete(k); }); diff --git a/src/class/3d/effect/SparkleParticle.ts b/src/class/3d/effect/SparkleParticle.ts index c603460..0f41e06 100644 --- a/src/class/3d/effect/SparkleParticle.ts +++ b/src/class/3d/effect/SparkleParticle.ts @@ -81,7 +81,7 @@ export class SparkleParticle { map: this.texture, transparent: true, blending: THREE.AdditiveBlending, - depthWrite: false, + depthWrite: false }); // Create the particle system diff --git a/src/class/3d/shader/ColorMix.ts b/src/class/3d/shader/ColorMix.ts new file mode 100644 index 0000000..0e2d672 --- /dev/null +++ b/src/class/3d/shader/ColorMix.ts @@ -0,0 +1,177 @@ +import * as THREE from "three"; + +function ColorMixShaderMaterial( + texture: THREE.Texture, + r: THREE.Vector4Like, + g: THREE.Vector4Like, + b: THREE.Vector4Like +) { + return new THREE.ShaderMaterial({ + uniforms: { + u_texture: { value: texture }, + u_const1: { value: r }, + u_const2: { value: g }, + u_const3: { value: b } + }, + vertexShader: /* glsl */ ` + varying vec2 vUv; + void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); + } + `, + fragmentShader: /* glsl */ ` + uniform sampler2D u_texture; + uniform vec4 u_const1; + uniform vec4 u_const2; + uniform vec4 u_const3; + varying vec2 vUv; + + void main() { + vec4 texColor = texture2D(u_texture, vUv); + + // Optionally discard low-alpha texture pixels. + if (texColor.a <= 0.2) { + discard; + } + +// Mix RGB channels using each constant’s color (rgb) +vec3 mixedColor = texColor.r * u_const1.rgb + + texColor.g * u_const2.rgb + + texColor.b * u_const3.rgb; + +// Use the texture's own alpha +float mixedAlpha = texColor.a; + +// Premultiply the mixed color by its alpha +gl_FragColor = vec4(mixedColor * mixedAlpha, mixedAlpha); + } + ` + }); +} + +export function colorMixTexture( + tex: THREE.Texture, + constR: THREE.Vector4Like = new THREE.Vector4(0, 1, 1, 1), + constG: THREE.Vector4Like = new THREE.Vector4(1, 1, 0, 1), + constB: THREE.Vector4Like = new THREE.Vector4(1, 1, 0, 1), + constA: THREE.ColorRepresentation, + rendererMain: THREE.WebGLRenderer, + textureResolution?: number +): Promise { + return new Promise((resolve) => { + // --- Scene, Camera, and Renderer Setup --- + const scene = new THREE.Scene(); + let width: number, height: number; + + if (tex instanceof ImageBitmap) { + width = tex.width; + height = tex.height; + } else { + width = tex.image.width; + height = tex.image.height; + } + + // assume square......? + if (textureResolution) { + let aspect = width / height; + width = textureResolution; + height = textureResolution / aspect; + } + + console.log( + "HI ITS ME CLOTHING TEX RENDERER, IDK WTF I DID", + width, + height + ); + + // be nice and save the current renderer's stuff + const renderSize = new THREE.Vector2(0, 0); + rendererMain.getSize(renderSize); + + console.log("[CMT DEBUG] width, height", width, height); + + // Create an orthographic camera. + // The view is set up so that the world units match the window size. + const camera = new THREE.OrthographicCamera( + width / -2, // left + width / 2, // right + height / 2, // top + height / -2, // bottom + 0.1, // near + 1000 // far + ); + camera.position.z = 1; + console.log("[CMT DEBUG] camera Created!"); + + // Create the WebGL renderer and add its canvas + const renderer = rendererMain; // || new THREE.WebGLRenderer(); + console.log("[CMT DEBUG] renderer Created!"); + + let oldClearColor = new THREE.Color(); + renderer.getClearColor(oldClearColor); + let oldClearAlpha = renderer.getClearAlpha(); + // if (constA) { + // renderer.setClearColor(constA); + // console.log("[CMT DEBUG] using constA for alpha."); + // } else { + // renderer.setClearColor(0xff0000); + // console.log("[CMT DEBUG] using red for alpha."); + // } + // renderer.setClearColor(constA); + renderer.setClearColor(constA, 1); + console.log("[CMT DEBUG] using red for alpha."); + renderer.setSize(width, height, false); + console.log("[CMT DEBUG] set renderer size OK."); + + if (typeof window !== "undefined") + //@ts-expect-error + window.camera = camera; + + // --- Create a Plane Geometry --- + const geometry = new THREE.PlaneGeometry(width, height); + console.log("[CMT DEBUG] create geometry OK"); + const plane = new THREE.Mesh( + geometry, + ColorMixShaderMaterial(tex, constR, constG, constB) + ); + console.log("[CMT DEBUG] create mesh OK"); + + scene.add(plane); + console.log("[CMT DEBUG] add mesh to scene"); + + function render() { + // renderer.setSize(renderSize.x, renderSize.y, false); + console.log("[CMT DEBUG] render scene OK"); + + function finalize(blob: Blob) { + if (blob === null) return console.error("blob is null???"); + resolve(blob); + + renderer.setClearColor(0x000000); + renderer.setClearAlpha(0); + + geometry.dispose(); + plane.material.dispose(); + console.log("[CMT DEBUG] disposed of scene OK"); + } + + renderer.setSize(width, height, false); + renderer.render(scene, camera); + + // renderer.setClearAlpha(0); + // renderer.setClearColor(0xff0000); + renderer.setClearAlpha(0); + + if (typeof document === "undefined") { + (renderer.domElement as any as OffscreenCanvas) + .convertToBlob({ type: "image/png" }) + .then(finalize); + } else { + renderer.domElement.toBlob(finalize as any); + } + } + console.log("[CMT DEBUG] preparing render"); + render(); + }); +} diff --git a/src/class/3d/shader/FFLShader.ts b/src/class/3d/shader/FFLShader.ts deleted file mode 100644 index 2aa8f82..0000000 --- a/src/class/3d/shader/FFLShader.ts +++ /dev/null @@ -1,4 +0,0 @@ -import fflVertexShader from "./FFLShader_vert.glsl"; -import fflFragmentShader from "./FFLShader_frag.glsl"; - -export { fflVertexShader, fflFragmentShader }; diff --git a/src/class/3d/shader/FFLShaderAlternateMaterial.ts b/src/class/3d/shader/FFLShaderAlternateMaterial.ts new file mode 100644 index 0000000..f7c7a14 --- /dev/null +++ b/src/class/3d/shader/FFLShaderAlternateMaterial.ts @@ -0,0 +1,144 @@ +import { Color, Vector3, Vector4 } from "three"; +import FFLShaderMaterial from "../../../external/ffl.js/FFLShaderMaterial"; +import LUTShaderMaterial from "../../../external/ffl.js/LUTShaderMaterial"; +import { + cLightAmbientFFLIconWithBody, + cLightDiffuseFFLIconWithBody, + cLightDirFFLIconWithBody, + cLightDirGlossy, + cLightSpecularFFLIconWithBody, + FFLToonMaterial +} from "./fflShaderConst"; + +/** + * Variant of FFLShaderMaterial that forces specular mode to Blinn-Phong. + * @augments {FFLShaderMaterial} + */ +class FFLShaderBlinnMaterial extends FFLShaderMaterial { + /** + * Constructs an FFLShaderMaterial instance. + * @param {import('three').ShaderMaterialParameters & import('../FFLShaderMaterial').FFLShaderMaterialParameters} [options] - Parameters for the material. + */ + constructor(options = {}) { + options = Object.assign( + { + useSpecularModeBlinn: true + }, + options + ); + super(options); // Construct the extended class. + // Adjust specular power, which is the reflection point, to be larger. + if (this.uniforms.u_material_specular_power) + this.uniforms.u_material_specular_power.value = 2.0; + } +} + +class FFLShaderLightDisabledMaterial extends FFLShaderMaterial { + /** + * Constructs an FFLShaderMaterial instance. + * @param {import('three').ShaderMaterialParameters & import('../FFLShaderMaterial').FFLShaderMaterialParameters} [options] - Parameters for the material. + */ + constructor(options = {}) { + options = Object.assign( + { + lightEnable: false + }, + options + ); + super(options); // Construct the extended class. + } +} + +// import type {FFLShaderMaterialParameters } from "../../../external/ffl.js/FFLShaderMaterial"; + +class FFLShaderToonMaterial extends FFLShaderMaterial { + constructor(options: any = {}) { + options = Object.assign({}, options); + super(options); + // Adjust material + (this as any).uniforms.u_light_dir.value = cLightDirGlossy; + if ((this as any).uniforms.u_material_ambient) { + (this as any).uniforms.u_material_ambient.value = FFLToonMaterial.ambient; + (this as any).uniforms.u_material_diffuse.value = FFLToonMaterial.diffuse; + (this as any).uniforms.u_material_specular.value = + FFLToonMaterial.specular; + (this as any).uniforms.u_material_specular_power.value = + FFLToonMaterial.specularPower; + (this as any).uniforms.u_material_specular_mode.value = + FFLToonMaterial.specularMode; + } + } +} + +class FFLShaderBrightMaterial extends FFLShaderMaterial { + constructor(options: any = {}) { + options = Object.assign({}, options); + super(options); + // Adjust material + (this as any).uniforms.u_light_dir.value = cLightDirFFLIconWithBody; + (this as any).uniforms.u_light_ambient.value = cLightAmbientFFLIconWithBody; + (this as any).uniforms.u_light_diffuse.value = cLightDiffuseFFLIconWithBody; + (this as any).uniforms.u_light_specular.value = + cLightSpecularFFLIconWithBody; + } +} + +class LUTShaderPretendoMaterial extends LUTShaderMaterial { + constructor(options: any = {}) { + options = Object.assign({}, options); + super(options); + // Adjust material + + // (this as any).lightDirection + // (this as any).lightDirection = new Vector3(0, 1, 1); + // (this as any).uniforms.uDirLightDirAndType0.value = new Vector4( + // 0, + // 0.5, + // 1, + // -1 + // ); + // (this as any).uniforms.uDirLightDirAndType1.value = new Vector4( + // 0, + // -0.7, + // 1, + // -1 + // ); + // (this as any).uniforms.uHSLightGroundColor.value = new Color(0.5, 0.5, 0.5); + // (this as any).uniforms.uHSLightSkyColor.value = new Color(0.5, 0.5, 0.5); + // (this as any).uniforms.uDirLightColor0.value = new Color(0.4, 0.4, 0.4); + // (this as any).uniforms.uDirLightColor1.value = new Color(0.4, 0.4, 0.4); + // (this as any).lightDirection = new Vector3(0, 1, 1); + (this as any).uniforms.uDirLightDirAndType0.value = new Vector4( + -0.2, + 0.5, + 0.8, + -1.0 + ); + (this as any).uniforms.uDirLightDirAndType1.value = new Vector4( + 0.0, + -0.19612, + 0.98058, + -1.0 + ); + (this as any).uniforms.uHSLightGroundColor.value = new Color( + 0xe1b997 + ).convertLinearToSRGB(); + (this as any).uniforms.uHSLightSkyColor.value = new Color( + 0xe1d6ce + ).convertLinearToSRGB(); + (this as any).uniforms.uDirLightColor0.value = new Color( + 0x5a5353 + ).convertLinearToSRGB(); + (this as any).uniforms.uDirLightColor1.value = new Color( + 0x1a1818 + ).convertLinearToSRGB(); + } +} + +export { + FFLShaderBlinnMaterial, + FFLShaderLightDisabledMaterial, + FFLShaderBrightMaterial, + FFLShaderToonMaterial, + LUTShaderPretendoMaterial +}; diff --git a/src/class/3d/shader/FFLShader_frag.glsl.ts b/src/class/3d/shader/FFLShader_frag.glsl.ts deleted file mode 100644 index ad0641e..0000000 --- a/src/class/3d/shader/FFLShader_frag.glsl.ts +++ /dev/null @@ -1,271 +0,0 @@ -export default /*glsl*/`// https://jsfiddle.net/arian_/8gvynrdu/7/ -// -// 定数定義ファイル -// - -/// シェーダーモード -#define FFL_SHADER_MODE_UR 0 -#define FFL_SHADER_MODE_UB 1 - -/// 変調処理のマクロ -#define FFL_MODULATE_MODE_CONSTANT 0 -#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 -#define FFL_MODULATE_MODE_RGB_LAYERED 2 -#define FFL_MODULATE_MODE_ALPHA 3 -#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 -#define FFL_MODULATE_MODE_ALPHA_OPA 5 - -/// スペキュラのモード -#define FFL_SPECULAR_MODE_BLINN 0 -#define FFL_SPECULAR_MODE_ANISO 1 - -/// ライトのON/OFF -#define FFL_LIGHT_MODE_DISABLE 0 -#define FFL_LIGHT_MODE_ENABLE 1 - -/// フラグメントのディスカードモード -#define FFL_DISCARD_FRAGMENT_DISABLE 0 -#define FFL_DISCARD_FRAGMENT_ENABLE 1 - -/// 座標変換モード -#define FFL_COORDINATE_MODE_NONE 0 -#define FFL_COORDINATE_MODE_NORMAL 1 - -// -// 関数の定義ファイル -// - -/** - * @brief 異方性反射の反射率を計算します。 - * @param[in] light ライトの向き - * @param[in] tangent 接線 - * @param[in] eye 視線の向き - * @param[in] power 鋭さ - */ -mediump float calculateAnisotropicSpecular(mediump vec3 light, mediump vec3 tangent, mediump vec3 eye, mediump float power ) -{ - mediump float dotLT = dot(light, tangent); - mediump float dotVT = dot(eye, tangent); - mediump float dotLN = sqrt(1.0 - dotLT * dotLT); - mediump float dotVR = dotLN*sqrt(1.0 - dotVT * dotVT) - dotLT * dotVT; - - return pow(max(0.0, dotVR), power); -} - -/** - * @brief 異方性反射の反射率を計算します。 - * @param[in] light ライトの向き - * @param[in] normal 法線 - * @param[in] eye 視線の向き - * @param[in] power 鋭さ - */ -mediump float calculateBlinnSpecular(mediump vec3 light, mediump vec3 normal, mediump vec3 eye, mediump float power) -{ - return pow(max(dot(reflect(-light, normal), eye), 0.0), power); -} - -/** - * @brief 異方性反射、ブリン反射をブレンドします。 - * @param[in] blend ブレンド率 - * @param[in] blinn ブリンの値 - * @param[in] aniso 異方性の値 - */ -mediump float calculateSpecularBlend(mediump float blend, mediump float blinn, mediump float aniso) -{ - return mix(aniso, blinn, blend); -} - -/** - * @brief アンビエントを計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - */ -mediump vec3 calculateAmbientColor(mediump vec3 light, mediump vec3 material) -{ - return light * material; -} - -/** - * @brief 拡散を計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - * @param[in] ln ライトと法線の内積 - */ -mediump vec3 calculateDiffuseColor(mediump vec3 light, mediump vec3 material, mediump float ln) -{ - return light * material * ln; -} - -/** - * @brief 鏡面反射を計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - * @param[in] reflection 反射率 - * @param[in] strength 幅 - */ -mediump vec3 calculateSpecularColor(mediump vec3 light, mediump vec3 material, mediump float reflection, mediump float strength) -{ - return light * material * reflection * strength; -} - -/** - * @brief リムを計算します。 - * @param[in] color リム色 - * @param[in] normalZ 法線のZ方向 - * @param[in] width リム幅 - * @param[in] power リムの鋭さ - */ -mediump vec3 calculateRimColor(mediump vec3 color, mediump float normalZ, mediump float width, mediump float power) -{ - return color * pow(width * (1.0 - abs(normalZ)), power); -} - -/** - * @brief ライト方向と法線の内積を求める - * @note 特殊な実装になっています。 - */ -mediump float calculateDot(mediump vec3 light, mediump vec3 normal) -{ - return max(dot(light, normal), 0.1); -} - -// フラグメントシェーダーに入力される varying 変数 -varying mediump vec4 v_color; //!< 出力: 頂点の色 -varying mediump vec4 v_position; //!< 出力: 位置情報 -varying mediump vec3 v_normal; //!< 出力: 法線ベクトル -varying mediump vec3 v_tangent; //!< 出力: 異方位 -varying mediump vec2 v_texCoord; //!< 出力: テクスチャー座標 - -/// constカラー -uniform mediump vec4 u_const1; ///< constカラー1 -/* -uniform mediump vec4 u_const2; ///< constカラー2 -uniform mediump vec4 u_const3; ///< constカラー3 -*/ - -/// ライト設定 -uniform mediump vec4 u_light_ambient; ///< カメラ空間のライト方向 -uniform mediump vec4 u_light_diffuse; ///< 拡散光用ライト -uniform mediump vec3 u_light_dir; -uniform bool u_light_enable; -uniform mediump vec4 u_light_specular; ///< 鏡面反射用ライト強度 - -/// マテリアル設定 -uniform mediump vec4 u_material_ambient; ///< 環境光用マテリアル設定 -uniform mediump vec4 u_material_diffuse; ///< 拡散光用マテリアル設定 -uniform mediump vec4 u_material_specular; ///< 鏡面反射用マテリアル設定 -uniform int u_material_specular_mode; ///< スペキュラの反射モード(CharModelに依存する設定のためub_modulateにしている) -uniform mediump float u_material_specular_power; ///< スペキュラの鋭さ(0.0を指定すると頂点カラーの設定が利用される) - -/// 変調設定 -uniform int u_mode; ///< 描画モード - -/// リム設定 -uniform mediump vec4 u_rim_color; -uniform mediump float u_rim_power; - -// サンプラー -uniform sampler2D s_texture; - -// ------------------------------------------------------- -// メイン文 -void main() -{ - mediump vec4 color; - - mediump float specularPower = u_material_specular_power; - mediump float rimWidth = v_color.a; - -//#ifdef FFL_MODULATE_MODE_CONSTANT - if(u_mode == FFL_MODULATE_MODE_CONSTANT) - { - color = u_const1; - } -//#elif defined(FFL_MODULATE_MODE_TEXTURE_DIRECT) - else if(u_mode > FFL_MODULATE_MODE_CONSTANT)// == FFL_MODULATE_MODE_TEXTURE_DIRECT) - { - color = texture2D(s_texture, v_texCoord); - } - /* -//#elif defined(FFL_MODULATE_MODE_RGB_LAYERED) - else if(u_mode == FFL_MODULATE_MODE_RGB_LAYERED) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.r * u_const1.rgb + color.g * u_const2.rgb + color.b * u_const3.rgb, color.a); - } -//#elif defined(FFL_MODULATE_MODE_ALPHA) - else if(u_mode == FFL_MODULATE_MODE_ALPHA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(u_const1.rgb, color.r); - } -//#elif defined(FFL_MODULATE_MODE_LUMINANCE_ALPHA) - else if(u_mode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.g * u_const1.rgb, color.r); - } -//#elif defined(FFL_MODULATE_MODE_ALPHA_OPA) - else if(u_mode == FFL_MODULATE_MODE_ALPHA_OPA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.r * u_const1.rgb, 1.0); - } - */ -//#endif - - // avoids little outline around mask elements - if(color.a == 0.0f) - { - discard; - } - -//#ifdef FFL_LIGHT_MODE_ENABLE - if(u_light_enable) - { - /// 環境光の計算 - mediump vec3 ambient = calculateAmbientColor(u_light_ambient.xyz, u_material_ambient.xyz); - - /// 法線ベクトルの正規化 - mediump vec3 norm = normalize(v_normal); - - /// 視線ベクトル - mediump vec3 eye = normalize(-v_position.xyz); - - // ライトの向き - mediump float fDot = calculateDot(u_light_dir, norm); - - /// Diffuse計算 - mediump vec3 diffuse = calculateDiffuseColor(u_light_diffuse.xyz, u_material_diffuse.xyz, fDot); - - /// Specular計算 - mediump float specularBlinn = calculateBlinnSpecular(u_light_dir, norm, eye, u_material_specular_power); - - /// Specularの値を確保する変数を宣言 - mediump float reflection; - mediump float strength = v_color.g; - if(u_material_specular_mode == 0) - { - /// Blinnモデルの場合 - strength = 1.0; - reflection = specularBlinn; - } - else - { - /// Aisoモデルの場合 - mediump float specularAniso = calculateAnisotropicSpecular(u_light_dir, v_tangent, eye, u_material_specular_power); - reflection = calculateSpecularBlend(v_color.r, specularBlinn, specularAniso); - } - /// Specularの色を取得 - mediump vec3 specular = calculateSpecularColor(u_light_specular.xyz, u_material_specular.xyz, reflection, strength); - - // リムの色を計算 - mediump vec3 rimColor = calculateRimColor(u_rim_color.rgb, norm.z, v_color.a, u_rim_power); - - // カラーの計算 - color.rgb = (ambient + diffuse) * color.rgb + specular + rimColor; - } -//#endif - - gl_FragColor = color; -}`; diff --git a/src/class/3d/shader/FFLShader_vert.glsl.ts b/src/class/3d/shader/FFLShader_vert.glsl.ts deleted file mode 100644 index ff3e26c..0000000 --- a/src/class/3d/shader/FFLShader_vert.glsl.ts +++ /dev/null @@ -1,101 +0,0 @@ -export default /*glsl*/ `// https://jsfiddle.net/arian_/8gvynrdu/7/ -// position, texCoord (uv), normal are all provided by three.js - -// 頂点シェーダーに入力される attribute 変数 -//attribute vec4 position; //!< 入力: 位置情報 -//attribute vec2 uv; //!< 入力: テクスチャー座標 -//attribute vec3 normal; //!< 入力: 法線ベクトル - -// color is not actually the vertex color, as such -// it is a custom attribute _COLOR in the glTF - -attribute vec4 _color; //!< 入力: 頂点の色 -attribute vec3 tangent; //!< 入力: 異方位 - -// フラグメントシェーダーへの入力 -varying vec4 v_color; //!< 出力: 頂点の色 -varying vec4 v_position; //!< 出力: 位置情報 -varying vec3 v_normal; //!< 出力: 法線ベクトル -varying vec3 v_tangent; //!< 出力: 異方位 -varying vec2 v_texCoord; //!< 出力: テクスチャー座標 - -// normalMatrix, modelViewMatrix, and projectionMatrix are provided by three.js -// ユニフォーム -//uniform mat3 normalMatrix; //!< ユニフォーム: モデルの法線用行列 -//uniform mat4 modelViewMatrix; //!< ユニフォーム: プロジェクション行列 -//uniform mat4 projectionMatrix; //!< ユニフォーム: モデル行列 - -#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif -void main() -{ -//#ifdef FFL_COORDINATE_MODE_NORMAL - // 頂点座標を変換 - // begin_vertex.glsl.js - vec3 transformed = vec3( position ); -#ifdef USE_SKINNING - // skinbase_vertex.glsl.js - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); - // skinning_vertex.glsl.js - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif - gl_Position = projectionMatrix * modelViewMatrix * vec4(transformed, 1.0);// * vec4(position, 1.0); - v_position = modelViewMatrix * vec4(transformed, 1.0); - // 法線も変換 <-- line 67 - vec3 objectNormal = normal; - vec3 objectTangent = tangent.xyz; - - -#ifdef USE_SKINNING - // skinnormal_vertex.glsl.js - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - - objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; - objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; - -#endif - - //v_normal = mat3(inverse(u_mv)) * a_normal; - v_normal = normalize(normalMatrix * objectNormal); - -//#elif defined(FFL_COORDINATE_MODE_NONE) -// // 頂点座標を変換 -// gl_Position = vec4(a_position.x, a_position.y * -1.0, a_position.z, a_position.w); -// v_position = a_position; -// -// v_normal = a_normal; -//#endif - - // その他の情報も書き出す - v_texCoord = uv; - v_tangent = normalize(normalMatrix * objectTangent); - v_color = _color; -}`; diff --git a/src/class/3d/shader/MiitomoShader.ts b/src/class/3d/shader/MiitomoShader.ts deleted file mode 100644 index e4a0f5d..0000000 --- a/src/class/3d/shader/MiitomoShader.ts +++ /dev/null @@ -1,5 +0,0 @@ -// GLSL SHADER -import miitomoVertexShader from "./MiitomoShader_vert.glsl"; -import miitomoFragmentShader from "./MiitomoShader_frag.glsl"; - -export { miitomoVertexShader, miitomoFragmentShader }; diff --git a/src/class/3d/shader/MiitomoShader_frag.glsl.ts b/src/class/3d/shader/MiitomoShader_frag.glsl.ts deleted file mode 100644 index 545263c..0000000 --- a/src/class/3d/shader/MiitomoShader_frag.glsl.ts +++ /dev/null @@ -1,304 +0,0 @@ -// unused for now, not ported to three.js yet -export default /*glsl*/ ` -#define AGX_FEATURE_ALBEDO_TEXTURE -#define AGX_FEATURE_MII -/** - * @file LUT.fsh - * @brief LUT - * @since 2014/10/02 - * - * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. - */ - -// シェーダーの種類毎に設定されるマクロリスト -// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 -// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 -// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 -// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 -// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 -// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 -// AGX_FEATURE_SKIN_MASK 肌マスクが有効(uColor0) -// AGX_FEATURE_HAIR_MASK 髪マスクが有効(uColor1) -// AGX_FEATURE_ALPHA_TEST アルファテストが有効 -// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(uColor2) -// AGX_FEATURE_DISABLE_LIGHT ライトが無効 -// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 -// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 -// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 -// AGX_FEATURE_MII Miiを描画する -// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant -// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct -// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered -// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha -// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha -// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa - -#ifdef GL_ES -precision mediump float; -#else -# define lowp -# define mediump -# define highp -#endif - -/// 変調処理のマクロ -#define FFL_MODULATE_MODE_CONSTANT 0 -#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 -#define FFL_MODULATE_MODE_RGB_LAYERED 2 -#define FFL_MODULATE_MODE_ALPHA 3 -#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 -#define FFL_MODULATE_MODE_ALPHA_OPA 5 - -// ---------------------------------------- -// フラグメントシェーダーに入力される uniform 変数 -uniform int uMode; ///< 描画モード -uniform bool uAlphaTest; -uniform bool uLightEnable; -uniform mediump vec4 uColor0; //!< 入力:[ 1 : 1 ] カラー0 (OR 肌カラー) -uniform mediump vec4 uColor1; //!< 入力:[ 1 : 2 ] カラー1 (OR 髪カラー) -uniform mediump vec4 uColor2; //!< 入力:[ 1 : 3 ] カラー2 (OR フェードアウトカラー) -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -uniform mediump vec3 uLightColor; //!< 入力:[ 1 : 4 ] ライトの色 -//#endif - -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) -uniform sampler2D uAlbedoTexture; //!< 入力: テクスチャー -#endif -#if defined(AGX_FEATURE_BUMP_TEXTURE) -uniform sampler2D uNormalTexture; //!< 入力: ノーマルマップ -#endif -#if defined(AGX_FEATURE_MASK_TEXTURE) -uniform sampler2D uMaskTexture; //!< 入力:マスクテクスチャー -#endif -#if defined(AGX_FEATURE_ALPHA_TEXTURE) -uniform sampler2D uAlphaTexture; //!< 入力:アルファテクスチャー -#endif -uniform sampler2D uLUTSpecTexture; //!< 入力: スペキュラーLUT -uniform sampler2D uLUTFresTexture; //!< 入力: フレネルLUT -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) -uniform sampler2D uSphereMapTexture; //!< 入力: スフィア環境マップ -#endif - -// ---------------------------------------- -// フラグメントシェーダーに渡される varying 変数 -in lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 -#if !defined(AGX_FEATURE_BUMP_TEXTURE) -in mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 -#endif -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) -in mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV -#endif -// camera -in mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -// punctual light -in mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 -in mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル -// GI -in mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー -// Lighting Result -in mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 -//#endif -// Reflect -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) -in lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル -#endif - -// out mediump vec4 o_Color; - -// ------------------------------------------------------------ -// フラグメントシェーダーのエントリーポイント -// ------------------------------------------------------------ -void main() -{ - - // ディフューズカラーを取得 - lowp vec4 albedoColor = vec4(1.0, 1.0, 1.0, 1.0); - - // ============================================================ - // Mii - // ============================================================ -#if defined(AGX_FEATURE_MII) - - //#if defined(AGX_FEATURE_MII_CONSTANT) - if(uMode == FFL_MODULATE_MODE_CONSTANT) - { - albedoColor = vec4(uColor0.rgb, 1.0); - } - //#elif defined(AGX_FEATURE_MII_TEXTURE_DIRECT) - else if(uMode == FFL_MODULATE_MODE_TEXTURE_DIRECT) - { - albedoColor = texture(uAlbedoTexture, vTexcoord0); - } - //#elif defined(AGX_FEATURE_MII_RGB_LAYERED) - else if(uMode == FFL_MODULATE_MODE_RGB_LAYERED) - { - albedoColor = texture(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(albedoColor.r * uColor0.rgb + albedoColor.g * uColor1.rgb + albedoColor.b * uColor2.rgb, - albedoColor.a); - } - //#elif defined(AGX_FEATURE_MII_ALPHA) - else if(uMode == FFL_MODULATE_MODE_ALPHA) - { - albedoColor = texture(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(uColor0.rgb, albedoColor.r); - } - //#elif defined(AGX_FEATURE_MII_LUMINANCE_ALPHA) - else if(uMode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) - { - albedoColor = texture(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(albedoColor.g * uColor0.rgb, albedoColor.r); - } - //#elif defined(AGX_FEATURE_MII_ALPHA_OPA) - else if(uMode == FFL_MODULATE_MODE_ALPHA_OPA) - { - albedoColor = texture(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(albedoColor.r * uColor0.rgb, 1.0); - } -//#endif - - albedoColor = albedoColor * vModelColor; -#endif - - // ============================================================ - // Albedo Texture - // ============================================================ -#if !defined(AGX_FEATURE_MII) && defined(AGX_FEATURE_ALBEDO_TEXTURE) - albedoColor = texture(uAlbedoTexture, vTexcoord0); -#endif -#if defined(AGX_FEATURE_ALPHA_TEXTURE) - albedoColor.a = texture(uAlphaTexture, vTexcoord0).r; -#endif - - // ============================================================ - // Color Mask - // ============================================================ - // ---------------------------------------- - // Deprecated -#if defined(AGX_FEATURE_ALPHA_COLOR_FILTER) - // 一部の場所にColor0を反映する - albedoColor.rgb = (albedoColor.rgb * albedoColor.a + uColor0.rgb * (1.0 - albedoColor.a)); - albedoColor.a = 1.0; -#elif defined(AGX_FEATURE_MASK_TEXTURE) - lowp vec3 maskTextureColor = texture(uMaskTexture, vTexcoord0).rgb; - -# if defined(AGX_FEATURE_SKIN_MASK) && defined(AGX_FEATURE_HAIR_MASK) - // 肌と髪両方マスクが存在する - lowp float maskColorValue = maskTextureColor.g + maskTextureColor.b; - lowp vec3 maskColor = maskTextureColor.g * uColor0.rgb + maskTextureColor.b * uColor1.rgb; - albedoColor.rgb = (albedoColor.rgb * (1.0 - maskColorValue) + maskColor); - -# elif defined(AGX_FEATURE_SKIN_MASK) - // 肌しかマスクが存在しない - albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.g) + maskTextureColor.g * uColor0.rgb); - -# elif defined(AGX_FEATURE_HAIR_MASK) - // 髪しかマスクが存在しない - albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.b) + maskTextureColor.b * uColor1.rgb); - -# endif -#endif - - // アルベドに頂点カラーを掛ける - albedoColor *= vModelColor; - - // ============================================================ - // Alpha test - // ============================================================ -//#if defined(AGX_FEATURE_ALPHA_TEST) - if (uAlphaTest && albedoColor.a < 0.5) { discard; } -//#endif - - // ============================================================ - // Bumpmap - // ============================================================ - // 頂点からの情報 - lowp vec3 normalWorldOrTangent; -#if defined(AGX_FEATURE_BUMP_TEXTURE) - // バンプマップから法線を取得する - mediump vec3 bumpNormal = texture(uNormalTexture, vTexcoord0).rgb; - - // 法線の正規化は処理が重いのでいったん正規化しない様に... -// normalWorldOrTangent = normalize(bumpNormal * 2.0 - 1.0); - normalWorldOrTangent = bumpNormal * 2.0 - 1.0; - -#else - // 法線を正規化して取得する - normalWorldOrTangent = normalize(vNormal); -#endif - - // ============================================================ - // Lighting - // ============================================================ - // 最終的なカラー情報 - lowp vec4 colorOut = vec4(0.0, 0.0, 0.0, albedoColor.a); // 最終的に出力される色 - lowp vec3 fresnel = vec3(0.0, 0.0, 0.0); // フレネル - lowp vec3 specular = vec3(0.0, 0.0, 0.0); // スペキュラー - -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -if (uLightEnable) { - - // BRDFの計算を行う(バンプマッピングの場合は接空間) - lowp vec3 N = normalWorldOrTangent; - lowp vec3 V = vEyeVecWorldOrTangent.xyz;//normalize(vEyeVecWorldOrTangent.xyz); - lowp vec3 I = vPunctualLightDirWorldOrTangent.xyz;//normalize(vPunctualLightDirWorldOrTangent.xyz); - lowp vec3 H = vPunctualLightHalfVecWorldOrTangent.xyz;//normalize(vPunctualLightHalfVecWorldOrTangent.xyz); - - - // ---------------------------------------- - // punctual light - // 平行光源や点光源などの厳密なライティング計算を行なうもの - { - lowp float fSpecular = dot(N, H); - - lowp float specularIntensity = texture(uLUTSpecTexture, vec2(fSpecular)).r; - specular = (specularIntensity * uLightColor.rgb); - } - - // ---------------------------------------- - // GI - // 半球ライトやIBL、SHのように法線方向に半球積分された結果でライティング計算を行なうもの - { - lowp float fFresnel = dot(N, V); - lowp float fresnelIntensity = texture(uLUTFresTexture, vec2(fFresnel)).r; - - fresnel = (fresnelIntensity * vGISpecularLightColor.rgb); - } -} -//#endif - -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) - // スフィア環境マップ - specular += texture(uSphereMapTexture, vReflectDir.xy).rgb; -#endif - - // ============================================================ - // Specular Mask - // ============================================================ -#if !defined(AGX_FEATURE_ALPHA_COLOR_FILTER) && defined(AGX_FEATURE_MASK_TEXTURE) - // スペキュラーマスク - specular = specular * maskTextureColor.r + fresnel; -#else - specular += fresnel; -#endif - - // ============================================================ - // Output - // ============================================================ -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -if (uLightEnable) - colorOut.rgb = vDiffuseColor.rgb * albedoColor.rgb + specular; -//#else -else - colorOut.rgb = albedoColor.rgb; -//#endif - - // フェードアウトを実装する -#if defined(AGX_FEATURE_FADE_OUT_COLOR) - colorOut.rgb = (colorOut.rgb * (1.0 - uColor2.a)) + (uColor2.rgb * uColor2.a); -#endif - - // 色を反映させる - gl_FragColor = colorOut; -} -`; diff --git a/src/class/3d/shader/MiitomoShader_vert.glsl.ts b/src/class/3d/shader/MiitomoShader_vert.glsl.ts deleted file mode 100644 index 40abd0c..0000000 --- a/src/class/3d/shader/MiitomoShader_vert.glsl.ts +++ /dev/null @@ -1,372 +0,0 @@ -// unused for now, not ported to three.js yet -export default /*glsl*/ ` -#define AGX_FEATURE_ALBEDO_TEXTURE -/** - * @file LUT.vsh - * @brief LUT - * @since 2014/10/02 - * - * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. - */ - -// シェーダーの種類毎に設定されるマクロリスト -// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 -// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 -// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 -// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 -// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 -// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 -// AGX_FEATURE_SKIN_MASK 肌マスクが有効(uColor0) -// AGX_FEATURE_HAIR_MASK 髪マスクが有効(uColor1) -// AGX_FEATURE_ALPHA_TEST アルファテストが有効 -// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(uColor2) -// AGX_FEATURE_DISABLE_LIGHT ライトが無効 -// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 -// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 -// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 -// AGX_FEATURE_MII Miiを描画する -// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant -// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct -// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered -// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha -// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha -// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa -// -// AGX_BONE_MAX ボーンの最大数 - -#ifdef GL_ES -precision highp float; -#else -# define lowp -# define mediump -# define highp -#endif - -#ifndef AGX_BONE_MAX -# define AGX_BONE_MAX 15 -#endif -#ifndef AGX_DIR_LIGHT_MAX -# define AGX_DIR_LIGHT_MAX 2 -#endif - -// ---------------------------------------- -// 頂点シェーダーに入力される attribute 変数 -layout( location = 0 ) in highp vec3 aPosition; //!< 入力:[ 1 : 1 ] 位置情報 -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) -layout( location = 1 ) in mediump vec2 aTexcoord0; //!< 入力:[ 1 : 5 ] テクスチャー座標 -#endif -layout( location = 2 ) in mediump vec3 aNormal; //!< 入力:[ 1 : 2 ] 法線ベクトル -layout( location = 3 ) in mediump vec4 aBoneIndex; //!< 入力:[ 1 : 3 ] ボーンのインデックス(最大4つ) -layout( location = 4 ) in mediump vec4 aBoneWeight; //!< 入力:[ 1 : 4 ] ボーンの影響度(最大4つ) -#if defined(AGX_FEATURE_VERTEX_COLOR) -layout( location = 5 ) in lowp vec4 aColor; //!< 入力:[ 1 : 6 ] 頂点カラー -#endif -#if defined(AGX_FEATURE_BUMP_TEXTURE) -layout( location = 6 ) in mediump vec3 aTangent; //!< 入力:[ 1 : 7 ] 接線ベクトル -#endif - -// ---------------------------------------- -// 頂点シェーダーに入力される uniform 変数 -// uniform highp mat4 uMVPMatrix; //!< 入力:[ 4 / 4 : 4 ] モデルの合成行列 -// uViewMatrix -// uniform highp mat4 uViewMatrix; //!< 入力:[ 4 / 4 : 8 ] モデルのビュー行列 -// uNormalMatrix -// uniform mediump mat3 uNormalMatrix; //!< 入力:[ 3 / 3 : 11 ] モデルの法線用行列 -// uModelMatrix -// uniform highp mat4 modelViewMatrix; //!< 入力:[ 4 / 4 : 15 ] モデルのワールド変換行列 -uniform lowp int uBoneCount; //!< 入力:[ 1 / 1 : 16 ] ボーンの個数 -uniform highp mat4 uBoneMatrices[AGX_BONE_MAX]; //!< 入力:[ 4 x 15 / 60 : 76 ] ボーンの行列配列 -uniform mediump mat3 uBoneNormalMatrices[AGX_BONE_MAX]; //!< 入力:[ 3 x 15 / 45 : 121 ] ボーンの法線行列配列 -uniform lowp int uDirLightCount; //!< 入力:[ 1 / 1 : 122 ] 方向ライトの数 -uniform mediump vec4 uDirLightDirAndType0;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 -uniform mediump vec4 uDirLightDirAndType1;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 -uniform mediump vec3 uDirLightColor0; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー -uniform mediump vec3 uDirLightColor1; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー -uniform mediump vec3 uHSLightSkyColor; //!< 入力:[ 1 / 1 : 127 ] 半球ライトのスカイカラー -uniform mediump vec3 uHSLightGroundColor; //!< 入力:[ 1 / 1 : 128 ] 半球ライトのグラウンドカラー -uniform mediump vec3 uEyePt; //!< 入力:[ 1 / 1 : 129 ] カメラの位置 -uniform mediump float uAlpha; //!< 入力:[ 1 / 1 : 130 ] アルファ値 - -// ---------------------------------------- -// フラグメントシェーダーに渡される varying 変数 -out lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 -#if !defined(AGX_FEATURE_BUMP_TEXTURE) -out mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 -#endif -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) -out mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV -#endif -// camera -out mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル -#if !defined(AGX_FEATURE_DISABLE_LIGHT) -// punctual light -out mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 -out mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル -// GI -out mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー -// Lighting Result -out mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 -#endif -// Reflect -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) -out lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル -#endif - -// mat4 getViewMatrix() { -// // 1. Extract the rotation and translation from modelViewMatrix -// mat4 rotationMatrix = mat4(modelViewMatrix[0].xyz, modelViewMatrix[1].xyz, modelViewMatrix[2].xyz, vec3(0.0)); - -// // 2. Extract the translation vector from modelViewMatrix -// vec3 translation = -vec3(modelViewMatrix[3]); - -// // 3. Construct the view matrix -// mat4 viewMatrix = mat4( -// rotationMatrix[0], -// rotationMatrix[1], -// rotationMatrix[2], -// vec4(translation, 1.0) -// ); - -// return viewMatrix; -// } - -// ------------------------------------------------------------ -// 頂点シェーダーのエントリーポイント -// ------------------------------------------------------------ -void main() -{ - // mat4 viewMatrix = getViewMatrix(); - // ------------------------------------------------------------ - // 頂点変換用の処理 - // ------------------------------------------------------------ - highp vec4 position; //!< 最終的な頂点 - mediump vec3 normal; //!< 最終的な法線 - mediump vec3 tangent; //!< 最終的な接線 - highp vec4 positionWorld; //!< ワールド空間上での頂点 - -// // ---------------------------------------- -// if (uBoneCount >= 1) -// { -// lowp ivec4 boneIndex = ivec4(aBoneIndex); //!< ボーンのインデックス -// mediump vec4 boneWeight = aBoneWeight; //!< ボーンの影響度 - -// // ボーンの行列を取得する -// highp mat4 boneMatrix = uBoneMatrices[boneIndex.x]; -// mediump mat3 boneNormMatrix = uBoneNormalMatrices[boneIndex.x]; - -// // 位置と法線をあらかじめ計算しておく -// position = boneMatrix * vec4(aPosition, 1.0) * boneWeight.x; -// normal = boneNormMatrix * (aNormal * boneWeight.x); -// #if defined(AGX_FEATURE_BUMP_TEXTURE) -// tangent = boneNormMatrix * (aTangent * boneWeight.x); -// #endif - - -// // 他の影響するボーンの行列を取得し、計算していく -// int iBone = 1; -// for (; iBone < uBoneCount; ++ iBone) -// { -// // ボーンの参照を変更する -// boneIndex = boneIndex.yzwx; -// boneWeight = boneWeight.yzwx; - -// // 新しいボーンの行列を取得 -// boneMatrix = uBoneMatrices[boneIndex.x]; -// boneNormMatrix = uBoneNormalMatrices[boneIndex.x]; - -// // 位置と法線を加算していく -// position += boneMatrix * vec4(aPosition, 1.0) * boneWeight.x; -// normal += boneNormMatrix * (aNormal * boneWeight.x); -// #if defined(AGX_FEATURE_BUMP_TEXTURE) -// tangent += boneNormMatrix * (aTangent * boneWeight.x); -// #endif -// } -// } -// else -// { - // ボーンが存在しない場合は位置と法線に手を加えない - position = vec4(aPosition, 1.0); - //position = vec4(aPosition.x*0.1, aPosition.y*0.1, aPosition.z*0.1, 1.0); - normal = aNormal; -#if defined(AGX_FEATURE_BUMP_TEXTURE) - tangent = aTangent; -#endif - // } - - // ---------------------------------------- - // ワールド上での位置を求める - positionWorld = modelViewMatrix * position; - // 最終結果を行う - // position = uMVPMatrix * position; - position = modelViewMatrix * projectionMatrix * position; - normal = normalize(normalMatrix * normal); -#if defined(AGX_FEATURE_BUMP_TEXTURE) - tangent = normalize(normalMatrix * tangent); -#endif - - // ---------------------------------------- - // 計算結果を保持させる - gl_Position = position; -#if !defined(AGX_FEATURE_BUMP_TEXTURE) - vNormal = normal; -#endif -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) - // テクスチャー座標を設定する - vTexcoord0 = aTexcoord0; -#endif - // モデルの色を指定する -#if defined(AGX_FEATURE_VERTEX_COLOR) - lowp vec4 modelColor = aColor; - -#else - lowp vec4 modelColor = vec4(1.0, 1.0, 1.0, 1.0); -#endif - - // プリマルチプライドアルファ -#if defined(AGX_FEATURE_PREMULTIPLY_ALPHA) - modelColor *= uAlpha; -#else - modelColor.a *= uAlpha; -#endif - - - // ------------------------------------------------------------ - // ライト用の処理 - // ------------------------------------------------------------ - mediump vec3 eyeVecWorld; //!< ワールド状態での視線ベクトル - mediump vec3 eyeVec; //!< 最終的にフラグメントシェーダーに渡す視線ベクトル(バンプの有無によって、ワールド座標系になったり、タンジェント座標系になったりする) - - // 視線ベクトルを取得する - eyeVecWorld = normalize(/*uEyePt*/ - positionWorld.xyz); - eyeVec = eyeVecWorld; - - lowp vec3 diffuseColor = vec3(0.0); // バーテックスシェーダーで計算できるディフューズの色をここに格納する - -# if defined(AGX_FEATURE_BUMP_TEXTURE) - // Normal, Binormal, Tangent を取得する - mediump vec3 n = normal; - mediump vec3 t = tangent; - mediump vec3 b = cross(n, t); - // 接空間からローカルへ変換する行列を設定する(mat3(N, T, B)の逆行列) - mediump mat3 tangentMatrix = mat3(t.x, b.x, n.x, t.y, b.y, n.y, t.z, b.z, n.z); - // 視線ベクトルを接空間へ - vEyeVecWorldOrTangent.xyz = tangentMatrix * eyeVec; -#else - vEyeVecWorldOrTangent.xyz = eyeVec; -#endif - -#if !defined(AGX_FEATURE_DISABLE_LIGHT) - // punctual lightの設定 - if (uDirLightCount > 0) - { - mediump vec3 lightDir; - - // 方向ライト - if (uDirLightDirAndType0.w < 0.0) { lightDir = uDirLightDirAndType0.xyz; } - // 点光源ライト - else { lightDir = uDirLightDirAndType0.xyz - positionWorld.xyz; } - lightDir = normalize(lightDir); - -# if defined(AGX_FEATURE_BUMP_TEXTURE) - // ライトを接空間へ - vPunctualLightDirWorldOrTangent.xyz = tangentMatrix * lightDir; -# else - vPunctualLightDirWorldOrTangent.xyz = lightDir; -# endif - - // Halfベクトルを求める - vPunctualLightHalfVecWorldOrTangent.xyz = normalize(vPunctualLightDirWorldOrTangent.xyz + vEyeVecWorldOrTangent.xyz); - - // Diffuse計算 - diffuseColor += (uDirLightColor0.rgb * clamp(dot(lightDir, normal), 0.0, 1.0)); - } - if (uDirLightCount > 1) - { - mediump vec3 lightDir; - - // 方向ライト - if (uDirLightDirAndType1.w < 0.0) { lightDir = uDirLightDirAndType1.xyz; } - // 点光源ライト - else { lightDir = uDirLightDirAndType1.xyz - positionWorld.xyz; } - lightDir = normalize(lightDir); - - diffuseColor += max(dot(lightDir, normal), 0.0) * uDirLightColor1; - } - // ライトは1.0を超えないように - diffuseColor = min(diffuseColor, 1.0); -#endif - -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) - { - // キューブ環境マップ用の反射ベクトルを求める -// vReflectDir = reflect(normalize(positionWorld.xyz - uEyePt), normal); - - // スフィア環境マップ用の反射ベクトルを求める -// vReflectDir = normalize((uViewMatrix * vec4(normal, 0.0)).xyz) * 0.5 + 0.5; - - // ビュー座標系での位置と法線を取得 - // mediump vec3 viewNormal = normalize(mat3(uViewMatrix) * normal); - mediump vec3 viewNormal = normalize(normalMatrix * normal); - // mediump vec4 viewPosition = uViewMatrix * positionWorld; - mediump vec4 viewPosition = modelViewMatrix * vec4(position, 1.0); - viewPosition = viewPosition / viewPosition.w; - // ビュー座標系での頂点ベクトルを取得 - viewPosition.z = 1.0 - viewPosition.z; - mediump vec3 viewPositionVec = normalize(viewPosition.xyz); - // ビュー座標系での反射ベクトルを求める - mediump vec3 viewReflect = viewPositionVec - 2.0 * dot(viewPositionVec, viewNormal) * viewNormal; - // 両面スフィア環境マップではないので、反射ベクトルを調整 - viewReflect = normalize(viewReflect - vec3(0.0, 0.0, 1.5)); - // 反射ベクトルをテクスチャー座標系へ - vReflectDir = viewReflect * 0.5 + 0.5; - - // 公式 -// mediump vec3 viewPositionVec = normalize(vec3(uViewMatrix * positionWorld)); -// mediump vec3 viewReflectVec = viewPositionVec - 2.0 * dot(viewPositionVec, normal) * normal; -// mediump float m = 2.0 * sqrt(viewReflectVec.x * viewReflectVec.x + -// viewReflectVec.y * viewReflectVec.y + -// (viewReflectVec.z + 1.0) * (viewReflectVec.z * 1.0)); -// vReflectDir = viewReflectVec / m + 0.5; - - // 別版 -// mediump vec3 posW = positionWorld.xyz; -// mediump vec3 dir = normalize(mat3(uViewMatrix) * normal); -// -// mediump float radius = 75.0; -// mediump vec3 posWDir = dot(dir, posW) * dir; -// mediump vec3 posWDirV = posW - posWDir; -// mediump float lengthDir = sqrt(radius * radius - dot(posWDirV, posWDirV)) - length(posWDir); -// vReflectDir = normalize(posW + dir * lengthDir) * 0.5 + 0.5; - } -#endif - -#if !defined(AGX_FEATURE_DISABLE_LIGHT) - // GIの計算 - { - mediump vec3 hemiColor; - mediump vec3 sky = uHSLightSkyColor; - mediump vec3 ground = uHSLightGroundColor; - - { - mediump float skyRatio = (normal.y + 1.0) * 0.5; - hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); - diffuseColor += hemiColor; - } - - { -// mediump vec3 reflectDir = -reflect(normal, eyeVecWorld); // おそらくコレで良いはず - mediump vec3 reflectDir = 2.0 * dot(eyeVecWorld, normal) * normal - eyeVecWorld; // 多少冗長でも、正しい計算で行なう - - mediump float skyRatio = (reflectDir.y + 1.0) * 0.5; - hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); - vGISpecularLightColor.rgb = hemiColor; - } - } -#endif - - // モデルの色を設定 - vModelColor = modelColor; -#if !defined(AGX_FEATURE_DISABLE_LIGHT) - vDiffuseColor.rgb = diffuseColor; -#endif -}`; diff --git a/src/class/3d/shader/ShaderUtils.ts b/src/class/3d/shader/ShaderUtils.ts index d2e9add..9021594 100644 --- a/src/class/3d/shader/ShaderUtils.ts +++ b/src/class/3d/shader/ShaderUtils.ts @@ -1,23 +1,13 @@ import * as THREE from "three"; import { - cLightAmbient, cLightAmbientFFLIconWithBody, - cLightDiffuse, cLightDiffuseFFLIconWithBody, - cLightDir, cLightDirFFLIconWithBody, - cLightDirGlossy, - cLightSpecular, cLightSpecularFFLIconWithBody, cMaterialName, - cMaterialParam, - cRimColor, - cRimPower, FFLBlinnMaterial, - FFLGlossMaterial, - type FFLShaderMaterial, + FFLToonMaterial } from "./fflShaderConst"; -import { fflFragmentShader, fflVertexShader } from "./FFLShader"; import { switchFragmentShader, switchVertexShader } from "./SwitchShader"; import { cBeardMaterials, @@ -30,29 +20,48 @@ import { cNoseMaterials, cPantsMaterials, FFLI_NN_MII_COMMON_COLOR_MASK, - type DrawParamMaterial, + type DrawParamMaterial } from "./SwitchShaderMaterials"; -import type Mii from "../../../external/mii-js/mii"; +// import type Mii from "../../../external/mii-js/mii"; +import type Mii from "../../../class/MiiData"; import { ShaderType } from "../../../constants/BodyShaderTypes"; -import { getSetting } from "../../../util/SettingsHelper"; -import { miitomoFragmentShader, miitomoVertexShader } from "./MiitomoShader"; -import { FFLShaderMaterial as FFLShaderMaterialInstance } from "../../../external/ffl.js/FFLShaderMaterial"; -import { LUTShaderMaterial as LUTShaderMaterialInstance } from "../../../external/ffl.js/LUTShaderMaterial"; +import FFLShaderMaterial from "../../../external/ffl.js/FFLShaderMaterial"; +import LUTShaderMaterial from "../../../external/ffl.js/LUTShaderMaterial"; +import localforage from "localforage"; +import { + FFLShaderBlinnMaterial, + FFLShaderBrightMaterial, + FFLShaderLightDisabledMaterial, + FFLShaderToonMaterial, + LUTShaderPretendoMaterial +} from "./FFLShaderAlternateMaterial"; + +// Worker-friendly copy of getSetting +export const getSettingSafe = async (key: string) => { + const value = (await localforage.getItem("settings_" + key)) as any; + + // hack? + if (value == null && key === "shaderType") { + return "wiiu"; + } + return value; +}; export function traverseAddShader( model: THREE.Group, - mii: Mii + shaderType: ShaderType ) { // Traverse the model to access its meshes model.traverse((n) => { const node = n as THREE.Mesh; if (node.isMesh) { - traverseMesh(node, mii); + traverseMesh(node, shaderType); } }); } -export async function traverseMesh(node: THREE.Mesh, mpCharInfo: Mii) { - const shaderSetting = await getSetting("shaderType"); +export async function traverseMesh(node: THREE.Mesh, shaderType: ShaderType) { + const shaderSetting = + shaderType || ((await getSettingSafe("shaderType")) as ShaderType); const originalMaterial = node.material as THREE.MeshBasicMaterial; // Access userData from geometry @@ -72,36 +81,12 @@ export async function traverseMesh(node: THREE.Mesh, mpCharInfo: Mii) { // those that does not happen in FFL-Testing) const lightEnable = modulateType > 5 ? false : true; // Select material parameter based on the modulate type, default to faceline - let materialParam: FFLShaderMaterial = + let materialParam: any = modulateType !== undefined ? modulateType && modulateType < 9 - ? cMaterialParam[modulateType] - : cMaterialParam[0] - : cMaterialParam[0]; - - let lightDir = cLightDir; - - let lightAmbient: THREE.Vector4 = cLightAmbient, - lightDiffuse: THREE.Vector4 = cLightDiffuse, - lightSpecular: THREE.Vector4 = cLightSpecular; - - // reused for extra materials - function modifyMaterialParam() { - // Wii U shader modifiers - if (shaderSetting === ShaderType.WiiUBlinn) { - materialParam = { ...materialParam, ...FFLBlinnMaterial }; - } else if (shaderSetting === ShaderType.WiiUToon) { - materialParam = { ...materialParam, ...FFLGlossMaterial }; - lightDir = cLightDirGlossy; - } else if (shaderSetting === ShaderType.WiiUFFLIconWithBody) { - lightDir = cLightDirFFLIconWithBody; - lightAmbient = cLightAmbientFFLIconWithBody; - lightDiffuse = cLightDiffuseFFLIconWithBody; - lightSpecular = cLightSpecularFFLIconWithBody; - } - } - - modifyMaterialParam(); + ? FFLShaderMaterial.materialParams[modulateType] + : FFLShaderMaterial.materialParams[0] + : FFLShaderMaterial.materialParams[0]; // Retrieve modulateMode, defaulting to constant color let modulateMode = @@ -118,58 +103,6 @@ export async function traverseMesh(node: THREE.Mesh, mpCharInfo: Mii) { } THREE.ColorManagement.enabled = false; - if (shaderSetting === ShaderType.Simple) { - THREE.ColorManagement.enabled = true; - - if ( - modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_MASK || - modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSELINE - ) { - const nonShaderMaterial = new THREE.MeshBasicMaterial({ - color: originalMaterial.color, - side: originalMaterial.side, - map: originalMaterial.map, - blending: THREE.CustomBlending, - blendDstAlpha: THREE.OneFactor, - transparent: originalMaterial.transparent, - alphaTest: 0, - reflectivity: 0, - }); - node.material = nonShaderMaterial; - } else if ( - modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_BODY || - modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_PANTS - ) { - const nonShaderMaterial = new THREE.MeshPhysicalMaterial({ - color: originalMaterial.color, - side: originalMaterial.side, - map: originalMaterial.map, - blending: THREE.CustomBlending, - blendDstAlpha: THREE.OneFactor, - transparent: originalMaterial.transparent, - alphaTest: originalMaterial.alphaTest, - metalness: 1, - roughness: 1, - }); - node.material = nonShaderMaterial; - } else { - const nonShaderMaterial = new THREE.MeshPhysicalMaterial({ - color: originalMaterial.color, - side: originalMaterial.side, - map: originalMaterial.map, - blending: THREE.CustomBlending, - blendDstAlpha: THREE.OneFactor, - transparent: originalMaterial.transparent, - alphaTest: originalMaterial.alphaTest, - metalness: 1, - roughness: 1, - reflectivity: 1, - }); - node.material = nonShaderMaterial; - } - return; - } - // Define macros based on the presence of textures const defines: Record = {}; @@ -201,339 +134,167 @@ export async function traverseMesh(node: THREE.Mesh, mpCharInfo: Mii) { let finalMat: THREE.Material; - if (shaderSetting === ShaderType.Switch) { - /* Do A LOTTA Calculations */ - let drawParamMaterial: DrawParamMaterial; - let commonColor: number = 0; // failsafe common color set - switch (modulateType) { - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSELINE: - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_MASK: - drawParamMaterial = cMaskMaterial; - break; - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_GLASS: - drawParamMaterial = cGlassMaterial; - break; - // pants: special or not - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_FOREHEAD: - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_FACELINE: - // does not need conversion - drawParamMaterial = cFacelineMaterials[mpCharInfo.extFacelineColor]; - break; - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSE: - drawParamMaterial = cNoseMaterials[mpCharInfo.extFacelineColor]; - break; - // body: favorite color - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_BODY: - drawParamMaterial = cBodyMaterials[mpCharInfo.favoriteColor]; - break; - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_PANTS: - drawParamMaterial = - mpCharInfo.normalMii === false - ? cPantsMaterials[1] - : cPantsMaterials[0]; - break; - // case cMaterialName.CUSTOM_MATERIAL_PARAM_BODY: - // drawParamMaterial = cBodyMaterials[mpCharInfo->favoriteColor]; - // break; - // case static_cast(SWITCH_MATERIAL_PARAM_PANTS_GRAY): - // drawParamMaterial = cPantsMaterials[0]; // gray index - // break; - // case static_cast(SWITCH_MATERIAL_PARAM_PANTS_GOLD): - // drawParamMaterial = cPantsMaterials[1]; // gold index - // break; - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_CAP: - drawParamMaterial = cHatMaterials[mpCharInfo.favoriteColor]; - break; - - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_HAIR: - // HACK: ver3 hair color 0 maps to common color 8 - if (mpCharInfo.hairColor == 0) commonColor = 8; - else - commonColor = mpCharInfo.extHairColor & FFLI_NN_MII_COMMON_COLOR_MASK; - drawParamMaterial = cHairMaterials[commonColor]; - //RIO_LOG("hair color: %d, specular factor B: %f\n", commonColor, drawParamMaterial.specular.factorB); - break; - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_BEARD: - // HACK: same as above - if (mpCharInfo.facialHairColor == 0) commonColor = 8; - else - commonColor = - mpCharInfo.extBeardColor & FFLI_NN_MII_COMMON_COLOR_MASK; - drawParamMaterial = cBeardMaterials[commonColor]; - break; - default: - // not suitable for material, return - return; - } - - const uniforms: Record = {}; + const isUsingShader = await isShaderMaterial(); + + let modulate = isUsingShader + ? { + modulateMode, + modulateType: modulateType, + lightEnable: shaderSetting === ShaderType.LightDisabled ? false : true + } + : {}; + + const params = { + color: new THREE.Color(...modulateColor), + ...modulate, + map: originalMaterial.map || undefined, + side + }; + + let shaderMaterial = await getShaderMaterialFromShaderType(shaderSetting); + + finalMat = new shaderMaterial(params) as any; + // switch (shaderSetting) { + // case ShaderType.WiiU: + // finalMat = new FFLShaderMaterial(params) as any; + // break; + // case ShaderType.Switch: + // throw new Error("This shader isn't supported yet"); + // case ShaderType.LightDisabled: + // finalMat = new FFLShaderLightDisabledMaterial(params) as any; + // break; + // case ShaderType.Miitomo: + // finalMat = new LUTShaderMaterial(params) as any; + // break; + // case ShaderType.MiitomoBasic: + // finalMat = new LUTShaderPretendoMaterial(params) as any; + // break; + // case ShaderType.WiiUBlinn: + // finalMat = new FFLShaderBlinnMaterial(params) as any; + // break; + // case ShaderType.WiiUFFLIconWithBody: + // finalMat = new FFLShaderBrightMaterial(params) as any; + // break; + // case ShaderType.WiiUToon: + // finalMat = new FFLShaderToonMaterial(params) as any; + // break; + // default: + // throw new Error("This shader doesn't exist"); + // } - /* - PIXEL_UNIFORM_MODULATE_TYPE = modulateType - PIXEL_UNIFORM_GAMMA_TYPE = gammaType - PIXEL_UNIFORM_DRAW_TYPE = drawType - PIXEL_UNIFORM_PAD0 = pad0 - PIXEL_UNIFORM_CONST_COLOR1 = constColor1 - PIXEL_UNIFORM_CONST_COLOR2 = constColor2 - PIXEL_UNIFORM_CONST_COLOR3 = constColor3 - PIXEL_UNIFORM_LIGHT_DIR_IN_VIEW = lightDirInView - PIXEL_UNIFORM_LIGHT_COLOR = lightColor - PIXEL_UNIFORM_SSS_COLOR = u_SssColor - PIXEL_UNIFORM_SPECULAR_COLOR = u_SpecularColor - PIXEL_UNIFORM_RIM_COLOR = u_RimColor - PIXEL_UNIFORM_HALF_LAMBERT_FACTOR = u_HalfLambertFactor - PIXEL_UNIFORM_SSS_SPECULAR_FACTOR = u_SssSpecularFactor - PIXEL_UNIFORM_SPECULAR_FACTOR_A = u_SpecularFactorA - PIXEL_UNIFORM_SPECULAR_FACTOR_B = u_SpecularFactorB - PIXEL_UNIFORM_SPECULAR_SHINNESS = u_SpecularShinness - PIXEL_UNIFORM_RIM_POWER = u_RimPower - PIXEL_UNIFORM_RIM_WIDTH = u_RimWidth - PIXEL_UNIFORM_LIGHT_ENABLE = lightEnable - */ - // AlphaOpa -> LuminanceAlpha - if (modulateType === 5) { - modulateType = 4; - } - // LuminanceAlpha -> AlphaOpa - else if (modulateType === 4) { - modulateType = 5; - } - // glass - else if ( - modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_GLASS || - modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_MASK || - modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSELINE - ) { - modulateMode = 1; - } else if (modulateType === 5) { - modulateType = 0; - modulateMode = 0; - } - uniforms["modulateType"] = { value: modulateMode }; - // uniforms["lightEnable"] = { value: modulateMode > 5 ? false : true }; - uniforms["lightEnable"] = { value: true }; - - uniforms["u_const1"] = { - value: modulateColor, - }; - - // mShader.setUniform( - // drawParamMaterial.sssColor.r, - // drawParamMaterial.sssColor.g, - // drawParamMaterial.sssColor.b, 1.00f, u32(-1), mPixelUniformLocation[PIXEL_UNIFORM_SSS_COLOR]); - uniforms["u_SssColor"] = { - value: new THREE.Vector4( - drawParamMaterial.sssColor[0], - drawParamMaterial.sssColor[1], - drawParamMaterial.sssColor[2], - 1.0 - ), - }; - // mShader.setUniform( - // drawParamMaterial.specular.color.r, - // drawParamMaterial.specular.color.g, - // drawParamMaterial.specular.color.b, 1.00f, u32(-1), mPixelUniformLocation[PIXEL_UNIFORM_SPECULAR_COLOR]); - uniforms["u_SpecularColor"] = { - value: new THREE.Vector4( - drawParamMaterial.specular.color[0], - drawParamMaterial.specular.color[1], - drawParamMaterial.specular.color[2], - 1.0 - ), - }; - // mShader.setUniform( - // drawParamMaterial.rimLight.color.r, - // drawParamMaterial.rimLight.color.g, - // drawParamMaterial.rimLight.color.b, 1.00f, u32(-1), mPixelUniformLocation[PIXEL_UNIFORM_RIM_COLOR]); - uniforms["u_RimColor"] = { - value: new THREE.Vector4( - drawParamMaterial.rimLight.color[0], - drawParamMaterial.rimLight.color[1], - drawParamMaterial.rimLight.color[2], - 1.0 - ), - }; - // mShader.setUniform( - // drawParamMaterial.halfLambertFactor, - // u32(-1), - // mPixelUniformLocation[PIXEL_UNIFORM_HALF_LAMBERT_FACTOR] - // ); - uniforms["u_HalfLambertFactor"] = { - value: drawParamMaterial.halfLambertFactor, - }; - // mShader.setUniform( - // drawParamMaterial.sssSpecularBlendFactor, - // u32(-1), - // mPixelUniformLocation[PIXEL_UNIFORM_SSS_SPECULAR_FACTOR] - // ); - uniforms["u_SssSpecularFactor"] = { - value: drawParamMaterial.sssSpecularBlendFactor, - }; - // mShader.setUniform( - // drawParamMaterial.specular.factorA, - // u32(-1), - // mPixelUniformLocation[PIXEL_UNIFORM_SPECULAR_FACTOR_A] - // ); - uniforms["u_SpecularFactorA"] = { - value: drawParamMaterial.specular.factorA, - }; - // mShader.setUniform( - // drawParamMaterial.specular.factorB, - // u32(-1), - // mPixelUniformLocation[PIXEL_UNIFORM_SPECULAR_FACTOR_B] - // ); - uniforms["u_SpecularFactorB"] = { - value: drawParamMaterial.specular.factorB, - }; - // mShader.setUniform( - // drawParamMaterial.specular.shinness, - // u32(-1), - // mPixelUniformLocation[PIXEL_UNIFORM_SPECULAR_SHINNESS] - // ); - uniforms["u_SpecularShinness"] = { - value: drawParamMaterial.specular.shinness, - }; - // mShader.setUniform( - // drawParamMaterial.rimLight.power, - // u32(-1), - // mPixelUniformLocation[PIXEL_UNIFORM_RIM_POWER] - // ); - uniforms["u_RimPower"] = { - value: drawParamMaterial.rimLight.power, - }; - // mShader.setUniform( - // drawParamMaterial.rimLight.width, - // u32(-1), - // mPixelUniformLocation[PIXEL_UNIFORM_RIM_WIDTH] - // ); - uniforms["u_RimWidth"] = { - value: drawParamMaterial.rimLight.width, - }; - - const cLightDir = new THREE.Vector4( - -0.12279, - 0.70711, - 0.69636, - 1.0 - ).negate(); - const cLightColor = new THREE.Vector4(1.0, 1.0, 1.0, 1.0); - - // Extra Uniforms - uniforms["gammaType"] = { value: 1 }; - uniforms["lightDirInView"] = { value: cLightDir }; - uniforms["lightColor"] = { value: cLightColor }; - - // set draw type here - enum DrawType { - DRAW_TYPE_NORMAL = 0, - DRAW_TYPE_FACELINE = 1, - DRAW_TYPE_HAIR = 2, - } - let drawType: number = 0; - - switch (modulateType) { - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_HAIR: - drawType = DrawType.DRAW_TYPE_HAIR; - break; - // NOTE: the shader will take alpha into account if - // you set draw type uniform to this, and the faceline - // texture would need to be drawn with alpha, however - // ffl does not do this by default and as of writing - // i have removed the hack to do this and it seems fine - default: - drawType = DrawType.DRAW_TYPE_NORMAL; - break; - } + // Assign the custom material to the mesh + node.material = finalMat; +} - // mShader.setUniform(s32(drawType), u32(-1), mPixelUniformLocation[PIXEL_UNIFORM_DRAW_TYPE]); - uniforms.drawType = { value: drawType }; - uniforms["s_Tex"] = { value: originalMaterial.map }; +export async function isShaderMaterial( + shader: string | undefined = undefined +): Promise { + let shaderType = (shader || + (await getSettingSafe("shaderType"))) as ShaderType; + switch (shaderType) { + case ShaderType.WiiU: + case ShaderType.WiiUBlinn: + case ShaderType.WiiUFFLIconWithBody: + case ShaderType.WiiUToon: + case ShaderType.Switch: + case ShaderType.Miitomo: + case ShaderType.MiitomoBasic: + return true; + case ShaderType.LightDisabled: + case ShaderType.ThreeToon: + case ShaderType.ThreePhong: + return false; + } +} +export async function getShaderMaterialFromShaderType(type?: string) { + const shaderType = (type || + (await getSettingSafe("shaderType"))) as ShaderType; + switch (shaderType) { + case ShaderType.WiiU: + return FFLShaderMaterial; + case ShaderType.LightDisabled: + return THREE.MeshBasicMaterial; + case ShaderType.WiiUBlinn: + return FFLShaderBlinnMaterial; + case ShaderType.WiiUFFLIconWithBody: + return FFLShaderBrightMaterial; + case ShaderType.WiiUToon: + return FFLShaderToonMaterial; + case ShaderType.Switch: + // todo: switch should have its own material class? + return FFLShaderMaterial; + case ShaderType.Miitomo: + // return LUTShaderMaterial; + return LUTShaderMaterial; + case ShaderType.MiitomoBasic: + return LUTShaderPretendoMaterial; + case ShaderType.ThreeToon: + return THREE.MeshToonMaterial; + case ShaderType.ThreePhong: + return THREE.MeshPhongMaterial; + } +} - finalMat = new THREE.ShaderMaterial({ - vertexShader: switchVertexShader, - fragmentShader: switchFragmentShader, - uniforms: { - // TODO - ...uniforms, - }, - defines: defines, - side: side, - blending: THREE.CustomBlending, - blendDstAlpha: THREE.OneFactor, - transparent: originalMaterial.transparent, // Handle transparency - alphaTest: originalMaterial.alphaTest, // Handle alpha testing - }); - } else if ( - shaderSetting.startsWith("wiiu") || - shaderSetting === ShaderType.LightDisabled - ) { - /* uniforms: { - u_const1: { value: modulateColor }, - u_light_ambient: { value: lightAmbient }, - u_light_diffuse: { value: lightDiffuse }, - u_light_specular: { value: lightSpecular }, - u_light_dir: { value: lightDir }, - u_light_enable: { value: true }, - u_material_ambient: { value: materialParam.ambient }, - u_material_diffuse: { value: materialParam.diffuse }, - u_material_specular: { value: materialParam.specular }, - u_material_specular_mode: { value: materialParam.specularMode }, - u_material_specular_power: { value: materialParam.specularPower }, - u_mode: { value: modulateMode }, - u_rim_color: { value: new THREE.Vector4(0.4, 0.4, 0.4, 1.0) }, - u_rim_power: { value: cRimPower }, - s_texture: { value: originalMaterial.map }, - }, - */ - console.log("Modulate type:", modulateType); - finalMat = new FFLShaderMaterialInstance({ - modulateColor: modulateColor.toArray(), - modulateMode, - modulateType: modulateType, - map: originalMaterial.map || undefined, - side, - lightEnable: shaderSetting.startsWith("wiiu") ? true : false, - }); - } else if (shaderSetting === ShaderType.Miitomo) { - finalMat = new LUTShaderMaterialInstance({ - modulateColor: modulateColor.toArray(), - modulateMode, - modulateType: modulateType, - map: originalMaterial.map || undefined, - side, - }); - } else { - finalMat = new THREE.ShaderMaterial({ - vertexShader: fflVertexShader, - fragmentShader: fflFragmentShader, - uniforms: { - u_const1: { value: modulateColor }, - u_light_ambient: { value: cLightAmbient }, - u_light_diffuse: { value: cLightDiffuse }, - u_light_specular: { value: cLightSpecular }, - u_light_dir: { value: cLightDir }, - u_light_enable: { value: lightEnable }, - u_material_ambient: { value: materialParam.ambient }, - u_material_diffuse: { value: materialParam.diffuse }, - u_material_specular: { value: materialParam.specular }, - u_material_specular_mode: { value: materialParam.specularMode }, - u_material_specular_power: { value: materialParam.specularPower }, - u_mode: { value: modulateMode }, - u_rim_color: { value: cRimColor }, - u_rim_power: { value: cRimPower }, - s_texture: { value: originalMaterial.map }, - }, - defines: defines, - side: side, - // NOTE: usually these blend modes are - // only set for DrawXlu stage - blending: THREE.CustomBlending, - blendDstAlpha: THREE.OneFactor, - transparent: originalMaterial.transparent, // Handle transparency - alphaTest: originalMaterial.alphaTest, // Handle alpha testing - }); +const ThreeMaterialStandardLights = (scene: THREE.Scene) => { + const intensity = Number(THREE.REVISION) >= 155 ? Math.PI : 1; + const ambientLight = new THREE.AmbientLight( + new THREE.Color(0.73, 0.73, 0.73), + intensity + ); + const directionalLight = new THREE.DirectionalLight( + new THREE.Color(0.6, 0.6, 0.6), + intensity + ); + directionalLight.position.set(-0.455, 0.348, 0.5); + + ambientLight.name = "ambientLight"; + directionalLight.name = "directionalLight"; + + scene.add(ambientLight, directionalLight); +}; +const ThreeMaterialToonLights = (scene: THREE.Scene) => { + const intensity = 2.5; + const ambientLight = new THREE.AmbientLight( + new THREE.Color(0.73, 0.73, 0.73), + intensity + ); + const directionalLight = new THREE.DirectionalLight( + new THREE.Color(0.6, 0.6, 0.6), + intensity + ); + directionalLight.position.set(-0.255, 0.348, 0.5); + + ambientLight.name = "ambientLight"; + directionalLight.name = "directionalLight"; + + scene.add(ambientLight, directionalLight); +}; + +export async function getSimpleMaterialAddLights( + type?: string +): Promise<((scene: THREE.Scene) => any) | undefined> { + const shaderType = (type || + (await getSettingSafe("shaderType"))) as ShaderType; + switch (shaderType) { + case ShaderType.WiiU: + case ShaderType.WiiUBlinn: + case ShaderType.WiiUFFLIconWithBody: + case ShaderType.WiiUToon: + case ShaderType.Switch: + case ShaderType.Miitomo: + case ShaderType.MiitomoBasic: + return; + case ShaderType.LightDisabled: + case ShaderType.ThreePhong: + return ThreeMaterialStandardLights; + case ShaderType.ThreeToon: + return ThreeMaterialToonLights; } +} +export function cleanupLights(scene: THREE.Scene) { + let amb = scene.getObjectByName("ambientLight"); + let dir = scene.getObjectByName("directionalLight"); - // Assign the custom material to the mesh - node.material = finalMat; + if (amb) scene.remove(amb); + if (dir) scene.remove(dir); } diff --git a/src/class/3d/shader/SwitchShaderMaterials.ts b/src/class/3d/shader/SwitchShaderMaterials.ts index ef3fe91..2dc26dd 100644 --- a/src/class/3d/shader/SwitchShaderMaterials.ts +++ b/src/class/3d/shader/SwitchShaderMaterials.ts @@ -40,7 +40,7 @@ export enum MaterialType { MaterialType_Hat, MaterialType_Hair, MaterialType_Beard, - MaterialType_Max, + MaterialType_Max } export const FFLI_NN_MII_COMMON_COLOR_MASK = 0x7fffffff; @@ -53,13 +53,13 @@ export const cMaskMaterial: DrawParamMaterial = { color: [0.0, 0.0, 0.0], factorA: 0.0, factorB: 0.0, - shinness: 0.1, + shinness: 0.1 }, rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, - width: 0.5, - }, + width: 0.5 + } }; export const cGlassMaterial: DrawParamMaterial = { @@ -70,13 +70,13 @@ export const cGlassMaterial: DrawParamMaterial = { color: [0.09804292, 0.09804292, 0.09804292], factorA: 0.3, factorB: 0.0, - shinness: 30.0, + shinness: 30.0 }, rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, - width: 0.0, - }, + width: 0.0 + } }; // line 8 export const cPantsMaterials: DrawParamMaterial[] = [ { @@ -87,13 +87,13 @@ export const cPantsMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.01960913, 0.01960913], factorA: 1.0, factorB: 0.02, - shinness: 0.7, + shinness: 0.7 }, rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, - width: 0.5, - }, + width: 0.5 + } }, // line 12 { halfLambertFactor: 0.6, @@ -103,14 +103,14 @@ export const cPantsMaterials: DrawParamMaterial[] = [ color: [0.2352996, 0.1568674, 0.0], factorA: 1.0, factorB: 0.02, - shinness: 0.7, + shinness: 0.7 }, rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, - width: 0.5, - }, - }, // special pants color + width: 0.5 + } + } // special pants color ]; export const cFacelineMaterials: DrawParamMaterial[] = [ { @@ -121,13 +121,13 @@ export const cFacelineMaterials: DrawParamMaterial[] = [ color: [0.1764755, 0.08235628, 0.05882626], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.2627507, 0.1176511, 0.08627796], power: 2.0, - width: 0.3, - }, + width: 0.3 + } }, // line 17 { halfLambertFactor: 0.4, @@ -137,13 +137,13 @@ export const cFacelineMaterials: DrawParamMaterial[] = [ color: [0.1372593, 0.09412124, 0.03921773], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.2352996, 0.1568674, 0.06666958], power: 2.0, - width: 0.3, - }, + width: 0.3 + } }, { halfLambertFactor: 0.4, @@ -153,13 +153,13 @@ export const cFacelineMaterials: DrawParamMaterial[] = [ color: [0.1215728, 0.03921773, 0.01176563], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.2431428, 0.07843459, 0.0235309], power: 2.0, - width: 0.3, - }, + width: 0.3 + } }, { halfLambertFactor: 0.4, @@ -169,13 +169,13 @@ export const cFacelineMaterials: DrawParamMaterial[] = [ color: [0.1137294, 0.05490454, 0.01960913], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.2352996, 0.1176511, 0.03921773], power: 2.0, - width: 0.3, - }, + width: 0.3 + } }, { halfLambertFactor: 0.4, @@ -185,13 +185,13 @@ export const cFacelineMaterials: DrawParamMaterial[] = [ color: [0.1254943, 0.02745257, 0.01176563], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.250986, 0.05490454, 0.0235309], power: 2.0, - width: 0.3, - }, + width: 0.3 + } }, { halfLambertFactor: 0.4, @@ -201,13 +201,13 @@ export const cFacelineMaterials: DrawParamMaterial[] = [ color: [0.03137433, 0.00784381, 0.00392195], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.250986, 0.06274787, 0.03137433], power: 2.0, - width: 0.3, - }, + width: 0.3 + } }, { halfLambertFactor: 0.4, @@ -217,13 +217,13 @@ export const cFacelineMaterials: DrawParamMaterial[] = [ color: [0.1764755, 0.08235628, 0.05882626], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.2627507, 0.1215728, 0.08627796], power: 2.0, - width: 0.3, - }, + width: 0.3 + } }, { halfLambertFactor: 0.4, @@ -233,13 +233,13 @@ export const cFacelineMaterials: DrawParamMaterial[] = [ color: [0.1372593, 0.07843459, 0.03921773], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.2352996, 0.1451026, 0.08235628], power: 2.0, - width: 0.3, - }, + width: 0.3 + } }, { halfLambertFactor: 0.4, @@ -249,13 +249,13 @@ export const cFacelineMaterials: DrawParamMaterial[] = [ color: [0.05882626, 0.01960913, 0.00392195], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.2352996, 0.04706119, 0.01176563], power: 2.0, - width: 0.3, - }, + width: 0.3 + } }, { halfLambertFactor: 0.4, @@ -265,14 +265,14 @@ export const cFacelineMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.00784381, 0.00392195], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.2352996, 0.07843459, 0.03921773], power: 2.0, - width: 0.3, - }, - }, // line 26 + width: 0.3 + } + } // line 26 ]; export const cNoseMaterials: DrawParamMaterial[] = [ { @@ -283,13 +283,13 @@ export const cNoseMaterials: DrawParamMaterial[] = [ color: [0.1764755, 0.08235628, 0.05882626], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.0, 0.0, 0.0], power: 0.55, - width: 0.0, - }, + width: 0.0 + } }, { halfLambertFactor: 0.3, @@ -299,13 +299,13 @@ export const cNoseMaterials: DrawParamMaterial[] = [ color: [0.1372593, 0.09412124, 0.03921773], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.0, 0.0, 0.0], power: 0.55, - width: 0.0, - }, + width: 0.0 + } }, { halfLambertFactor: 0.3, @@ -315,13 +315,13 @@ export const cNoseMaterials: DrawParamMaterial[] = [ color: [0.1215728, 0.03921773, 0.01176563], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.0, 0.0, 0.0], power: 0.55, - width: 0.0, - }, + width: 0.0 + } }, { halfLambertFactor: 0.3, @@ -331,13 +331,13 @@ export const cNoseMaterials: DrawParamMaterial[] = [ color: [0.1137294, 0.05490454, 0.01960913], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.0, 0.0, 0.0], power: 0.55, - width: 0.0, - }, + width: 0.0 + } }, { halfLambertFactor: 0.3, @@ -347,13 +347,13 @@ export const cNoseMaterials: DrawParamMaterial[] = [ color: [0.1254943, 0.02745257, 0.01176563], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.0, 0.0, 0.0], power: 0.55, - width: 0.0, - }, + width: 0.0 + } }, { halfLambertFactor: 0.3, @@ -363,13 +363,13 @@ export const cNoseMaterials: DrawParamMaterial[] = [ color: [0.03137433, 0.00784381, 0.00392195], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.0, 0.0, 0.0], power: 0.55, - width: 0.0, - }, + width: 0.0 + } }, { halfLambertFactor: 0.3, @@ -379,13 +379,13 @@ export const cNoseMaterials: DrawParamMaterial[] = [ color: [0.1764755, 0.08235628, 0.05882626], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.0, 0.0, 0.0], power: 0.55, - width: 0.0, - }, + width: 0.0 + } }, { halfLambertFactor: 0.3, @@ -395,13 +395,13 @@ export const cNoseMaterials: DrawParamMaterial[] = [ color: [0.1372593, 0.07843459, 0.03921773], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.0, 0.0, 0.0], power: 0.55, - width: 0.0, - }, + width: 0.0 + } }, { halfLambertFactor: 0.3, @@ -411,13 +411,13 @@ export const cNoseMaterials: DrawParamMaterial[] = [ color: [0.05882626, 0.01960913, 0.00392195], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.0, 0.0, 0.0], power: 0.55, - width: 0.0, - }, + width: 0.0 + } }, { halfLambertFactor: 0.3, @@ -427,14 +427,14 @@ export const cNoseMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.00784381, 0.00392195], factorA: 2.6, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, rimLight: { color: [0.0, 0.0, 0.0], power: 0.55, - width: 0.0, - }, - }, // line 39 + width: 0.0 + } + } // line 39 ]; export const cBodyMaterials: DrawParamMaterial[] = [ { @@ -445,9 +445,9 @@ export const cBodyMaterials: DrawParamMaterial[] = [ color: [0.1647106, 0.0235309, 0.01568734], factorA: 1.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, // line 43 { halfLambertFactor: 0.5, @@ -457,9 +457,9 @@ export const cBodyMaterials: DrawParamMaterial[] = [ color: [0.2000051, 0.08627796, 0.01960913], factorA: 1.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 } }, { halfLambertFactor: 0.5, @@ -469,9 +469,9 @@ export const cBodyMaterials: DrawParamMaterial[] = [ color: [0.2000051, 0.1686323, 0.0235309], factorA: 1.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 } }, { halfLambertFactor: 0.5, @@ -481,9 +481,9 @@ export const cBodyMaterials: DrawParamMaterial[] = [ color: [0.09412124, 0.1647106, 0.0235309], factorA: 1.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 } }, { halfLambertFactor: 0.5, @@ -493,9 +493,9 @@ export const cBodyMaterials: DrawParamMaterial[] = [ color: [0.0, 0.09412124, 0.03529608], factorA: 1.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 } }, { halfLambertFactor: 0.5, @@ -505,9 +505,9 @@ export const cBodyMaterials: DrawParamMaterial[] = [ color: [0.00784381, 0.05490454, 0.1411809], factorA: 1.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 } }, { halfLambertFactor: 0.5, @@ -517,9 +517,9 @@ export const cBodyMaterials: DrawParamMaterial[] = [ color: [0.04706119, 0.1725539, 0.2156916], factorA: 1.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 } }, { halfLambertFactor: 0.5, @@ -529,9 +529,9 @@ export const cBodyMaterials: DrawParamMaterial[] = [ color: [0.1921619, 0.07059128, 0.09804292], factorA: 1.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 } }, { halfLambertFactor: 0.5, @@ -541,9 +541,9 @@ export const cBodyMaterials: DrawParamMaterial[] = [ color: [0.09019956, 0.03137433, 0.1333377], factorA: 1.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 } }, { halfLambertFactor: 0.5, @@ -553,9 +553,9 @@ export const cBodyMaterials: DrawParamMaterial[] = [ color: [0.03137433, 0.01176563, 0.00392195], factorA: 1.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 } }, // line 52 { halfLambertFactor: 0.5, @@ -565,9 +565,9 @@ export const cBodyMaterials: DrawParamMaterial[] = [ color: [0.2196132, 0.1725539, 0.1725539], factorA: 1.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 } }, { halfLambertFactor: 0.5, @@ -577,10 +577,10 @@ export const cBodyMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.01960913, 0.01960913], factorA: 1.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 }, - }, // line 14 + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.0 } + } // line 14 ]; export const cHatMaterials: DrawParamMaterial[] = [ { @@ -591,9 +591,9 @@ export const cHatMaterials: DrawParamMaterial[] = [ color: [0.2470644, 0.0, 0.00784381], factorA: 2.0, factorB: 0.0, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, // line 56 { halfLambertFactor: 0.6, @@ -603,9 +603,9 @@ export const cHatMaterials: DrawParamMaterial[] = [ color: [0.2156916, 0.1451026, 0.02745257], factorA: 2.0, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.6, @@ -615,9 +615,9 @@ export const cHatMaterials: DrawParamMaterial[] = [ color: [0.2352996, 0.1176511, 0.03921773], factorA: 1.1, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.6, @@ -627,9 +627,9 @@ export const cHatMaterials: DrawParamMaterial[] = [ color: [0.1098079, 0.2470644, 0.01960913], factorA: 2.0, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.6, @@ -639,9 +639,9 @@ export const cHatMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.1176511, 0.01960913], factorA: 2.0, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.6, @@ -651,9 +651,9 @@ export const cHatMaterials: DrawParamMaterial[] = [ color: [0.00392195, 0.02745257, 0.2627507], factorA: 2.0, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.6, @@ -663,9 +663,9 @@ export const cHatMaterials: DrawParamMaterial[] = [ color: [0.06274787, 0.1647106, 0.2392212], factorA: 2.0, factorB: 0.8, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.6, @@ -675,9 +675,9 @@ export const cHatMaterials: DrawParamMaterial[] = [ color: [0.2745156, 0.05882626, 0.07843459], factorA: 2.0, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.6, @@ -687,9 +687,9 @@ export const cHatMaterials: DrawParamMaterial[] = [ color: [0.08627796, 0.01176563, 0.1725539], factorA: 2.0, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.6, @@ -699,9 +699,9 @@ export const cHatMaterials: DrawParamMaterial[] = [ color: [0.03921773, 0.01960913, 0.00784381], factorA: 2.0, factorB: 0.02, - shinness: 2.0, + shinness: 2.0 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, // line 65 { halfLambertFactor: 0.6, @@ -711,9 +711,9 @@ export const cHatMaterials: DrawParamMaterial[] = [ color: [0.1568674, 0.1568674, 0.1176511], factorA: 2.0, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, // line 28 { halfLambertFactor: 0.6, @@ -723,10 +723,10 @@ export const cHatMaterials: DrawParamMaterial[] = [ color: [0.00784381, 0.00784381, 0.00784381], factorA: 2.0, factorB: 0.02, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, - }, // line 29 + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } + } // line 29 ]; export const cHairMaterials: DrawParamMaterial[] = [ { @@ -737,9 +737,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.01568734, 0.01568734], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, // line 69 { halfLambertFactor: 0.45, @@ -749,9 +749,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1254943, 0.04706119, 0.00784381], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -761,9 +761,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1803971, 0.03529608, 0.00392195], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -773,9 +773,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2431428, 0.09019956, 0.01176563], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -785,9 +785,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1411809, 0.1411809, 0.1490242], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -797,9 +797,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1529458, 0.09412124, 0.00784381], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -809,9 +809,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2666723, 0.1372593, 0.01176563], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -821,9 +821,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.407849, 0.250986, 0.04313947], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -833,9 +833,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.01176563, 0.01176563, 0.01176563], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -845,9 +845,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1254943, 0.1333377, 0.1333377], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -857,9 +857,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2000051, 0.09412124, 0.0235309], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -869,9 +869,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1882403, 0.1451026, 0.02745257], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -881,9 +881,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.08235628, 0.129416, 0.3294176], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -893,9 +893,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.06274787, 0.1725539, 0.1725539], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -905,9 +905,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1882403, 0.08627796, 0.00784381], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -917,9 +917,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.3294176, 0.0235309, 0.00392195], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -929,9 +929,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.03529608, 0.07451299, 0.2039268], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -941,9 +941,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.3294176, 0.1490242, 0.0], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -953,9 +953,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1411809, 0.1333377, 0.1215728], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -965,9 +965,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4235353, 0.1254943, 0.00392195], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -977,9 +977,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.01960913, 0.01960913], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -989,9 +989,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4784371, 0.1098079, 0.03921773], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1001,9 +1001,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4705939, 0.2392212, 0.06666958], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1013,9 +1013,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2745156, 0.1254943, 0.03529608], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1025,9 +1025,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2588292, 0.05882626, 0.01960913], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1037,9 +1037,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.1803971, 0.05882626], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1049,9 +1049,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.2392212, 0.09412124], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1061,9 +1061,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.298045, 0.1058862], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1073,9 +1073,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2235348, 0.07059128, 0.03137433], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1085,9 +1085,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.298045, 0.04706119, 0.03529608], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1097,9 +1097,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2705939, 0.03529608, 0.03529608], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1109,9 +1109,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.352947, 0.09412124, 0.03529608], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1121,9 +1121,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.3882412, 0.04706119, 0.04706119], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1133,9 +1133,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.345104, 0.129416, 0.07451299], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1145,9 +1145,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.3882412, 0.129416, 0.06274787], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1157,9 +1157,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4902016, 0.1803971, 0.08627796], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1169,9 +1169,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4941232, 0.2666723, 0.1176511], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1181,9 +1181,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.3137313, 0.1254943], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1193,9 +1193,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.09412124, 0.04313947, 0.03529608], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1205,9 +1205,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.06274787, 0.06274787, 0.1176511], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1217,9 +1217,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1490242, 0.03529608, 0.04313947], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1229,9 +1229,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2156916, 0.1019645, 0.1019645], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1241,9 +1241,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2588292, 0.1411809, 0.1058862], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1253,9 +1253,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.3764764, 0.2039268, 0.1176511], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1265,9 +1265,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1960836, 0.2274563, 0.3921627], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1277,9 +1277,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.231378, 0.2666723, 0.4509861], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1289,9 +1289,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.278437, 0.298045, 0.4902016], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1301,9 +1301,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2470644, 0.3058882, 0.4627508], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1313,9 +1313,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.02745257, 0.04706119, 0.1254943], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1325,9 +1325,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.09804292, 0.2000051], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1337,9 +1337,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.04706119, 0.2039268, 0.4156921], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1349,9 +1349,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1019645, 0.2823587, 0.4745156], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1361,9 +1361,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1411809, 0.3058882, 0.4353], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1373,9 +1373,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1607891, 0.2588292, 0.4902016], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1385,9 +1385,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1529458, 0.2941234, 0.4902016], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1397,9 +1397,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1882403, 0.352947, 0.4980448], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1409,9 +1409,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.01176563, 0.07059128, 0.1058862], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1421,9 +1421,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.0, 0.09412124, 0.1137294], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1433,9 +1433,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.01176563, 0.1215728, 0.1725539], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1445,9 +1445,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.03921773, 0.1568674, 0.1921619], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1457,9 +1457,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.05490454, 0.1960836, 0.2745156], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1469,9 +1469,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.09019956, 0.2705939, 0.345104], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1481,9 +1481,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1411809, 0.3058882, 0.3098098], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1493,9 +1493,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1490242, 0.3294176, 0.3764764], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1505,9 +1505,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1568674, 0.3568686, 0.3568686], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1517,9 +1517,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.1137294, 0.02745257], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1529,9 +1529,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.129416, 0.1882403, 0.0], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1541,9 +1541,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.00392195, 0.1803971, 0.05490454], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1553,9 +1553,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1058862, 0.2392212, 0.06274787], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1565,9 +1565,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1451026, 0.2705939, 0.01176563], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1577,9 +1577,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2862803, 0.298045, 0.00392195], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1589,9 +1589,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1921619, 0.3098098, 0.07843459], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1601,9 +1601,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.3098098, 0.3490255, 0.03529608], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1613,9 +1613,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2941234, 0.345104, 0.07059128], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1625,9 +1625,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.3647118, 0.3764764, 0.09804292], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1637,9 +1637,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.298045, 0.2274563, 0.0235309], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1649,9 +1649,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.3254961, 0.231378, 0.05490454], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1661,9 +1661,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4000058, 0.298045, 0.03137433], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1673,9 +1673,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4000058, 0.2902018, 0.07843459], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1685,9 +1685,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4235353, 0.3176529, 0.07451299], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1697,9 +1697,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4156921, 0.3372608, 0.06274787], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1709,9 +1709,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4156921, 0.3607903, 0.07451299], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1721,9 +1721,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4235353, 0.3921627, 0.09019956], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1733,9 +1733,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2431428, 0.1058862, 0.0], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1745,9 +1745,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4509861, 0.2902018, 0.07059128], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1757,9 +1757,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.352947, 0.04313947], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1769,9 +1769,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4902016, 0.345104, 0.07451299], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1781,9 +1781,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4823586, 0.3647118, 0.09019956], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1793,9 +1793,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4902016, 0.3882412, 0.09019956], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1805,9 +1805,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.3254961, 0.1176511, 0.01568734], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1817,9 +1817,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.2352996, 0.00392195], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1829,9 +1829,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.407849, 0.2431428, 0.05882626], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1841,9 +1841,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.278437, 0.05882626], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1853,9 +1853,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.3019665, 0.08235628], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1865,9 +1865,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.4470646, 0.3215744, 0.1019645], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1877,9 +1877,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.07843459, 0.07843459, 0.07843459], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1889,9 +1889,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.1843188, 0.1843188, 0.1843188], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1901,9 +1901,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2235348, 0.2235348, 0.2235348], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1913,9 +1913,9 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.2588292, 0.250986, 0.2431428], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.45, @@ -1925,10 +1925,10 @@ export const cHairMaterials: DrawParamMaterial[] = [ color: [0.00392195, 0.00392195, 0.00392195], factorA: 1.0, factorB: 0.06, - shinness: 0.8, + shinness: 0.8 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, - }, // line 168 + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } + } // line 168 ]; export const cBeardMaterials: DrawParamMaterial[] = [ { @@ -1939,9 +1939,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.01568734, 0.01568734], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, // line 172 { halfLambertFactor: 0.2, @@ -1951,9 +1951,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1254943, 0.04706119, 0.00784381], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -1963,9 +1963,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1803971, 0.03529608, 0.00392195], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -1975,9 +1975,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2431428, 0.09019956, 0.01176563], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -1987,9 +1987,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1411809, 0.1411809, 0.1490242], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -1999,9 +1999,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1529458, 0.09412124, 0.00784381], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2011,9 +2011,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2666723, 0.1372593, 0.01176563], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2023,9 +2023,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.407849, 0.250986, 0.04313947], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2035,9 +2035,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.01176563, 0.01176563, 0.01176563], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2047,9 +2047,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1254943, 0.1333377, 0.1333377], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2059,9 +2059,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2000051, 0.09412124, 0.0235309], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2071,9 +2071,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1882403, 0.1451026, 0.02745257], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2083,9 +2083,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.08235628, 0.129416, 0.3294176], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2095,9 +2095,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.06274787, 0.1725539, 0.1725539], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2107,9 +2107,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1882403, 0.08627796, 0.00784381], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2119,9 +2119,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.3294176, 0.0235309, 0.00392195], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2131,9 +2131,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.03529608, 0.07451299, 0.2039268], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2143,9 +2143,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.3294176, 0.1490242, 0.0], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2155,9 +2155,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1411809, 0.1333377, 0.1215728], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2167,9 +2167,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4235353, 0.1254943, 0.00392195], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2179,9 +2179,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.01960913, 0.01960913], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2191,9 +2191,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4784371, 0.1098079, 0.03921773], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2203,9 +2203,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4705939, 0.2392212, 0.06666958], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2215,9 +2215,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2745156, 0.1254943, 0.03529608], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2227,9 +2227,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2588292, 0.05882626, 0.01960913], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2239,9 +2239,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.1803971, 0.05882626], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2251,9 +2251,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.2392212, 0.09412124], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2263,9 +2263,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.298045, 0.1058862], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2275,9 +2275,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2235348, 0.07059128, 0.03137433], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2287,9 +2287,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.298045, 0.04706119, 0.03529608], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2299,9 +2299,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2705939, 0.03529608, 0.03529608], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2311,9 +2311,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.352947, 0.09412124, 0.03529608], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2323,9 +2323,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.3882412, 0.04706119, 0.04706119], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2335,9 +2335,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.345104, 0.129416, 0.07451299], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2347,9 +2347,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.3882412, 0.129416, 0.06274787], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2359,9 +2359,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4902016, 0.1803971, 0.08627796], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2371,9 +2371,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4941232, 0.2666723, 0.1176511], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2383,9 +2383,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.3137313, 0.1254943], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2395,9 +2395,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.09412124, 0.04313947, 0.03529608], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2407,9 +2407,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.06274787, 0.06274787, 0.1176511], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2419,9 +2419,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1490242, 0.03529608, 0.04313947], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2431,9 +2431,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2156916, 0.1019645, 0.1019645], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2443,9 +2443,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2588292, 0.1411809, 0.1058862], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2455,9 +2455,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.3764764, 0.2039268, 0.1176511], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2467,9 +2467,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1960836, 0.2274563, 0.3921627], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2479,9 +2479,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.231378, 0.2666723, 0.4509861], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2491,9 +2491,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.278437, 0.298045, 0.4902016], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2503,9 +2503,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2470644, 0.3058882, 0.4627508], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2515,9 +2515,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.02745257, 0.04706119, 0.1254943], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2527,9 +2527,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.09804292, 0.2000051], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2539,9 +2539,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.04706119, 0.2039268, 0.4156921], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2551,9 +2551,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1019645, 0.2823587, 0.4745156], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2563,9 +2563,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1411809, 0.3058882, 0.4353], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2575,9 +2575,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1607891, 0.2588292, 0.4902016], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2587,9 +2587,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1529458, 0.2941234, 0.4902016], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2599,9 +2599,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1882403, 0.352947, 0.4980448], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2611,9 +2611,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.01176563, 0.07059128, 0.1058862], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2623,9 +2623,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.0, 0.09412124, 0.1137294], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2635,9 +2635,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.01176563, 0.1215728, 0.1725539], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2647,9 +2647,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.03921773, 0.1568674, 0.1921619], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2659,9 +2659,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.05490454, 0.1960836, 0.2745156], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2671,9 +2671,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.09019956, 0.2705939, 0.345104], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2683,9 +2683,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1411809, 0.3058882, 0.3098098], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2695,9 +2695,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1490242, 0.3294176, 0.3764764], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2707,9 +2707,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1568674, 0.3568686, 0.3568686], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2719,9 +2719,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.01960913, 0.1137294, 0.02745257], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2731,9 +2731,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.129416, 0.1882403, 0.0], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2743,9 +2743,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.00392195, 0.1803971, 0.05490454], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2755,9 +2755,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1058862, 0.2392212, 0.06274787], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2767,9 +2767,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1451026, 0.2705939, 0.01176563], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2779,9 +2779,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2862803, 0.298045, 0.00392195], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2791,9 +2791,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1921619, 0.3098098, 0.07843459], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2803,9 +2803,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.3098098, 0.3490255, 0.03529608], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2815,9 +2815,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2941234, 0.345104, 0.07059128], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2827,9 +2827,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.3647118, 0.3764764, 0.09804292], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2839,9 +2839,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.298045, 0.2274563, 0.0235309], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2851,9 +2851,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.3254961, 0.231378, 0.05490454], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2863,9 +2863,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4000058, 0.298045, 0.03137433], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2875,9 +2875,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4000058, 0.2902018, 0.07843459], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2887,9 +2887,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4235353, 0.3176529, 0.07451299], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2899,9 +2899,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4156921, 0.3372608, 0.06274787], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2911,9 +2911,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4156921, 0.3607903, 0.07451299], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2923,9 +2923,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4235353, 0.3921627, 0.09019956], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2935,9 +2935,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2431428, 0.1058862, 0.0], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2947,9 +2947,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4509861, 0.2902018, 0.07059128], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2959,9 +2959,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.352947, 0.04313947], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2971,9 +2971,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4902016, 0.345104, 0.07451299], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2983,9 +2983,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4823586, 0.3647118, 0.09019956], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -2995,9 +2995,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4902016, 0.3882412, 0.09019956], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -3007,9 +3007,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.3254961, 0.1176511, 0.01568734], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -3019,9 +3019,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.2352996, 0.00392195], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -3031,9 +3031,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.407849, 0.2431428, 0.05882626], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -3043,9 +3043,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.278437, 0.05882626], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -3055,9 +3055,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4980448, 0.3019665, 0.08235628], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -3067,9 +3067,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.4470646, 0.3215744, 0.1019645], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -3079,9 +3079,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.07843459, 0.07843459, 0.07843459], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -3091,9 +3091,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.1843188, 0.1843188, 0.1843188], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -3103,9 +3103,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2235348, 0.2235348, 0.2235348], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -3115,9 +3115,9 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.2588292, 0.250986, 0.2431428], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } }, { halfLambertFactor: 0.2, @@ -3127,10 +3127,10 @@ export const cBeardMaterials: DrawParamMaterial[] = [ color: [0.00392195, 0.00392195, 0.00392195], factorA: 1.0, factorB: 0.0, - shinness: 1.3, + shinness: 1.3 }, - rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 }, - }, // line 271 + rimLight: { color: [0.0, 0.0, 0.0], power: 1.0, width: 0.5 } + } // line 271 ]; // NOTE: WHERE DOES THIS COME FROM? just taken from a render diff --git a/src/class/3d/shader/SwitchShader_frag.glsl.ts b/src/class/3d/shader/SwitchShader_frag.glsl.ts index 2995f32..e42ac4f 100644 --- a/src/class/3d/shader/SwitchShader_frag.glsl.ts +++ b/src/class/3d/shader/SwitchShader_frag.glsl.ts @@ -1,4 +1,4 @@ -export default /*glsl*/` +export default /*glsl*/ ` #define VARYING_QUALIFIER in #define VARYING_INSTANCE In @@ -201,4 +201,4 @@ void main() /*o_Color*/gl_FragColor = outputColor; } -`; \ No newline at end of file +`; diff --git a/src/class/3d/shader/fflShaderConst.ts b/src/class/3d/shader/fflShaderConst.ts index 6c5bef0..52584f5 100644 --- a/src/class/3d/shader/fflShaderConst.ts +++ b/src/class/3d/shader/fflShaderConst.ts @@ -1,5 +1,6 @@ // https://jsfiddle.net/arian_/8gvynrdu/7/ import * as THREE from "three"; +// import type { FFLMaterial } from "../../../external/ffl.js/FFLShaderMaterial"; // Material table for FFLDefaultShader mapping to FFLModulateType // Reference: https://github.com/aboood40091/FFL-Testing/blob/master/src/Shader.cpp export enum cMaterialName { @@ -13,156 +14,24 @@ export enum cMaterialName { FFL_MODULATE_TYPE_SHAPE_NOSELINE, FFL_MODULATE_TYPE_SHAPE_GLASS, FFL_MODULATE_TYPE_SHAPE_BODY, - FFL_MODULATE_TYPE_SHAPE_PANTS, + FFL_MODULATE_TYPE_SHAPE_PANTS } -export const FFLBlinnMaterial: Partial = { - specularMode: 0, +export const FFLBlinnMaterial = { + specularMode: 0 }; -export const FFLGlossMaterial: Partial = { - ambient: new THREE.Vector4(0.8, 0.8, 0.8, 1), - diffuse: new THREE.Vector4(0.8, 0.8, 0.8, 1), - specular: new THREE.Vector4(0.1, 0.1, 0.1, 1), +export const FFLToonMaterial = { + ambient: new THREE.Color(0.8, 0.8, 0.8), + diffuse: new THREE.Color(0.8, 0.8, 0.8), + specular: new THREE.Color(0.1, 0.1, 0.1), specularPower: 0.01, - specularMode: 0, + specularMode: 0 }; -export type FFLShaderMaterial = { - ambient: THREE.Vector4; - diffuse: THREE.Vector4; - specular: THREE.Vector4; - specularPower: number; - specularMode: number; -}; - -export const cMaterialParam = [ - { - // FFL_MODULATE_TYPE_SHAPE_FACELINE - ambient: new THREE.Vector4(0.85, 0.75, 0.75, 1.0), - diffuse: new THREE.Vector4(0.75, 0.75, 0.75, 1.0), - specular: new THREE.Vector4(0.3, 0.3, 0.3, 1.0), - specularPower: 1.2, - specularMode: 0, - }, - { - // FFL_MODULATE_TYPE_SHAPE_BEARD - ambient: new THREE.Vector4(1.0, 1.0, 1.0, 1.0), - diffuse: new THREE.Vector4(0.7, 0.7, 0.7, 1.0), - specular: new THREE.Vector4(0.0, 0.0, 0.0, 1.0), - specularPower: 40.0, - specularMode: 1, - }, - { - // FFL_MODULATE_TYPE_SHAPE_NOSE - ambient: new THREE.Vector4(0.9, 0.85, 0.85, 1.0), - diffuse: new THREE.Vector4(0.75, 0.75, 0.75, 1.0), - specular: new THREE.Vector4(0.22, 0.22, 0.22, 1.0), - specularPower: 1.5, - specularMode: 0, - }, - { - // FFL_MODULATE_TYPE_SHAPE_FOREHEAD - ambient: new THREE.Vector4(0.85, 0.75, 0.75, 1.0), - diffuse: new THREE.Vector4(0.75, 0.75, 0.75, 1.0), - specular: new THREE.Vector4(0.3, 0.3, 0.3, 1.0), - specularPower: 1.2, - specularMode: 0, - }, - { - // FFL_MODULATE_TYPE_SHAPE_HAIR - ambient: new THREE.Vector4(1.0, 1.0, 1.0, 1.0), - diffuse: new THREE.Vector4(0.7, 0.7, 0.7, 1.0), - specular: new THREE.Vector4(0.35, 0.35, 0.35, 1.0), - specularPower: 10.0, - specularMode: 1, - }, - { - // FFL_MODULATE_TYPE_SHAPE_CAP - ambient: new THREE.Vector4(0.75, 0.75, 0.75, 1.0), - diffuse: new THREE.Vector4(0.72, 0.72, 0.72, 1.0), - specular: new THREE.Vector4(0.3, 0.3, 0.3, 1.0), - specularPower: 1.5, - specularMode: 0, - }, - { - // FFL_MODULATE_TYPE_SHAPE_MASK - ambient: new THREE.Vector4(1.0, 1.0, 1.0, 1.0), - diffuse: new THREE.Vector4(0.7, 0.7, 0.7, 1.0), - specular: new THREE.Vector4(0.0, 0.0, 0.0, 1.0), - specularPower: 40.0, - specularMode: 1, - }, - { - // FFL_MODULATE_TYPE_SHAPE_NOSELINE - ambient: new THREE.Vector4(1.0, 1.0, 1.0, 1.0), - diffuse: new THREE.Vector4(0.7, 0.7, 0.7, 1.0), - specular: new THREE.Vector4(0.0, 0.0, 0.0, 1.0), - specularPower: 40.0, - specularMode: 1, - }, - { - // FFL_MODULATE_TYPE_SHAPE_GLASS - ambient: new THREE.Vector4(1.0, 1.0, 1.0, 1.0), - diffuse: new THREE.Vector4(0.7, 0.7, 0.7, 1.0), - specular: new THREE.Vector4(0.0, 0.0, 0.0, 1.0), - specularPower: 40.0, - specularMode: 1, - }, - - { - // body - ambient: new THREE.Vector4(0.95622, 0.95622, 0.95622, 1.0), - diffuse: new THREE.Vector4(0.49673, 0.49673, 0.49673, 1.0), - specular: new THREE.Vector4(0.24099, 0.24099, 0.24099, 1.0), - specularPower: 3.0, - specularMode: 0, - }, - { - // pants - ambient: new THREE.Vector4(0.95622, 0.95622, 0.95622, 1.0), - diffuse: new THREE.Vector4(1.08497, 1.08497, 1.08497, 1.0), - specular: new THREE.Vector4(0.2409, 0.2409, 0.2409, 1.0), - specularPower: 3.0, - specularMode: 0, - }, -]; - -// FFLDefaultShader default lighting parameters - -export const cLightAmbient = new THREE.Vector4(0.73, 0.73, 0.73, 1.0); -export const cLightDiffuse = new THREE.Vector4(0.6, 0.6, 0.6, 1.0); -export const cLightSpecular = new THREE.Vector4(0.7, 0.7, 0.7, 1.0); - -export const cLightAmbientFFLIconWithBody = new THREE.Vector4( - 0.5, - 0.5, - 0.5, - 1.0 -); -export const cLightDiffuseFFLIconWithBody = new THREE.Vector4( - 0.9, - 0.9, - 0.9, - 1.0 -); -export const cLightSpecularFFLIconWithBody = new THREE.Vector4( - 1.0, - 1.0, - 1.0, - 1.0 -); - -// NWF lighting -// export const cLightAmbient = new THREE.Vector4(0.5, 0.5, 0.5, 1.0); -// export const cLightDiffuse = new THREE.Vector4(0.9, 0.9, 0.9, 1.0); -// export const cLightSpecular = new THREE.Vector4(1.0, 1.0, 1.0, 1.0); +export const cLightAmbientFFLIconWithBody = new THREE.Color(0.5, 0.5, 0.5); +export const cLightDiffuseFFLIconWithBody = new THREE.Color(0.9, 0.9, 0.9); +export const cLightSpecularFFLIconWithBody = new THREE.Color(1.0, 1.0, 1.0); -// Light direction derived from this vector: [-0.65, 0.36] -export const cLightDir = new THREE.Vector3( - -0.4531539381, - 0.4226179123, - 0.7848858833 -); export const cLightDirGlossy = new THREE.Vector3(-0.35, 1, 0.8); export const cLightDirFFLIconWithBody = new THREE.Vector3(-0.5, 0.366, 0.785); // export const cLightDir = new THREE.Vector3(0, 0, 1); @@ -184,16 +53,16 @@ export const cPantsColorGold: RGBColor = [0.75294, 0.62745, 0.18824]; // Simple shader color fixing export const cPantsColorGrayLinear: RGBColor = [ - 0.05126930067255049, 0.061246141699984984, 0.07618418934386001, + 0.05126930067255049, 0.061246141699984984, 0.07618418934386001 ]; export const cPantsColorRedLinear: RGBColor = [ - 0.1620327698875954, 0.014443805936996105, 0.0051820344376627735, + 0.1620327698875954, 0.014443805936996105, 0.0051820344376627735 ]; export const cPantsColorBlueLinear: RGBColor = [ - 0.02121835054048093, 0.05126930067255049, 0.18782228580122498, + 0.02121835054048093, 0.05126930067255049, 0.18782228580122498 ]; export const cPantsColorGoldLinear: RGBColor = [ - 0.5271132835871205, 0.3515313874944194, 0.02955820686563641, + 0.5271132835871205, 0.3515313874944194, 0.02955820686563641 ]; export const cPantsColorGrayHex = "#40464e"; @@ -214,5 +83,5 @@ export const MiiFavoriteFFLColorLookupTable: Record = { 8: [0.451, 0.157, 0.678], 9: [0.282, 0.22, 0.094], 10: [0.878, 0.878, 0.878], - 11: [0.094, 0.094, 0.078], + 11: [0.094, 0.094, 0.078] }; diff --git a/src/class/MiiData.ts b/src/class/MiiData.ts new file mode 100644 index 0000000..e5fdd68 --- /dev/null +++ b/src/class/MiiData.ts @@ -0,0 +1,515 @@ +import { parseHexOrB64ToUint8Array } from "../external/ffl.js/ffl"; +// import Notify from "../ui/components/Notify"; +import { allocateArray } from "../util/allocateArray"; +import { dataToBase64, dataToHex } from "../util/dataConvert"; +import { randomizeUint8Array } from "../util/Numbers"; +import { + FFLiAuthorID, + FFLiCreateID, + Ver3StoreData +} from "./struct/FFLStoreData"; +import { + MiiCreatorV3Data, + MiiCreatorV3DataToMiiCreatorV4Data as MiiCreatorV3DataToV4 +} from "./struct/MiiCreatorV3Data"; +import { + EmptyMiiCreatorV4Data, + MiiCreatorOriginPlatform, + MiiCreatorV4Data, + MiiCreatorV4DataToFFSD, + validate +} from "./struct/MiiCreatorV4Data"; +import { NnMiiCharInfo } from "./struct/NnMiiCharInfo"; +import { + RFLStoreData, + RFLStoreDataToMiiCreatorV4Data +} from "./struct/RFLStoreData"; +import { StudioData } from "./struct/StudioData"; + +import { _ } from "../util/Lang"; +const __ = _(); + +export type MiiDataExportType = + | "rsd" + | "miic" + | "studioData" + | "switchCharInfo" + | "ffsd" + | "ffsd_append_miic"; + +export default class Mii { + miicVersion!: number; + originPlatform!: number; + authorId!: Uint8Array; + createId!: Uint8Array; + creator!: string; + nickname!: string; + beardColor!: number; + beardType!: number; + birthDay!: number; + birthMonth!: number; + birthYear!: number; + build!: number; + clothesType!: number; + eyeAspect!: number; + eyebrowAspect!: number; + eyebrowColor!: number; + eyebrowRotate!: number; + eyebrowScale!: number; + eyebrowType!: number; + eyebrowX!: number; + eyebrowY!: number; + eyeColor!: number; + eyeRotate!: number; + eyeScale!: number; + eyeSclera!: number; + eyeType!: number; + eyeX!: number; + eyeY!: number; + facelineColor!: number; + facelineMake!: number; + facelineType!: number; + facelineWrinkle!: number; + facePaintColor!: number; + favorite!: number; + favoriteColor!: number; + fontRegion!: number; + gender!: number; + glassColor!: number; + glassScale!: number; + glassType!: number; + glassY!: number; + hairColor!: number; + hairFlip!: number; + hairType!: number; + hatCommonColor!: number; + hatFavoriteColor!: number; + hatType!: number; + height!: number; + wigType!: number; + moleScale!: number; + moleType!: number; + moleX!: number; + moleY!: number; + mouthAspect!: number; + mouthColor!: number; + mouthScale!: number; + mouthType!: number; + mouthY!: number; + mustacheScale!: number; + mustacheType!: number; + mustacheY!: number; + temporary!: number; + noseScale!: number; + noseType!: number; + noseY!: number; + pantsColor!: number; + personality!: number; + regionMove!: number; + shirtColor!: number; + shoesColor!: number; + special!: number; + valid!: boolean; + + // create + constructor(initData: Uint8Array | string) { + let importData: Uint8Array; + + if (typeof initData === "string") + importData = parseHexOrB64ToUint8Array(initData); + else importData = initData; + + this.import(Mii.parseData(importData)); + } + + /** decodes data of the following types and turns them into the internal data format */ + static parseData(input: Uint8Array): MiiCreatorV4Data { + let data: MiiCreatorV4Data = EmptyMiiCreatorV4Data(); + let tempArray: Uint8Array; + switch (input.length) { + // Mii Studio data (decoded) + case 46: + case 47: + tempArray = allocateArray(48, input); + data = { ...EmptyMiiCreatorV4Data(), ...StudioData.unpack(tempArray) }; + data.originPlatform = MiiCreatorOriginPlatform.Mii_Creator_v4; + data.nickname = "Mii"; + data.creator = ""; + break; + // 74/76 byte RFLStoreData - .rsd + case 74: + case 76: + tempArray = allocateArray(96, input); + data = RFLStoreDataToMiiCreatorV4Data(RFLStoreData.unpack(tempArray)); + break; + // 87-88 byte nn::mii::CharInfo - .charinfo + case 87: + case 88: + tempArray = allocateArray(88, input); + const d = NnMiiCharInfo.unpack(tempArray) as NnMiiCharInfo; + + var tmpCreateId = new Uint8Array(10); + tmpCreateId.set(d.createId.slice(0, 10), 0); + d.createId = tmpCreateId; + + data = { ...data, ...d }; + + // split CharInfo's CreateID + data.createId.set(d.createId.slice(0, 10), 0); + data.authorId.set(d.createId.slice(10), 0); + data.creator = ""; + data.originPlatform = MiiCreatorOriginPlatform.nn_mii_Switch; + break; + // 92/96-byte Ver3StoreData - .cfsd/.ffsd + case 92: + case 96: + tempArray = allocateArray(108, input); + data = MiiCreatorV3DataToV4( + MiiCreatorV3Data.unpack( + MiiCreatorV3Data.pack(Ver3StoreData.unpack(tempArray) as any) + ) + ); + break; + // 104/106/108-byte Mii Creator Data - .miic + case 104: // + extension colors + case 106: // + hat color/type + case 108: // + shirt color/face paint + tempArray = allocateArray(108, input); + data = MiiCreatorV3DataToV4(MiiCreatorV3Data.unpack(tempArray)); + break; + // 114-byte mii creator v4 extension data + case 114: + tempArray = allocateArray(123, input); + data = MiiCreatorV3DataToV4( + MiiCreatorV3Data.unpack( + MiiCreatorV3Data.pack(Ver3StoreData.unpack(tempArray) as any) + ) + ); + break; + // mii creator v4 data + case 122: + case 123: + case 124: + case 125: + case 126: + tempArray = allocateArray(126, input); + data = MiiCreatorV4Data.unpack(tempArray); + if (input.length < 126) { + data.shoesColor = -1; + } + if (input.length < 125) { + data.clothesType = -1; + } + break; + default: + throw new Error( + __("Mii data type not supported (%1 bytes)", input.length) + ); + } + + // HACK: struct-fu is returning uint of -1 as 255, + // so we will replace those back here + if (data.facePaintColor === 255) data.facePaintColor = -1; + if (data.hatCommonColor === 255) data.hatCommonColor = -1; + if (data.hatFavoriteColor === 255) data.hatFavoriteColor = -1; + if (data.hatType === 255) data.hatType = -1; + if (data.pantsColor === 255) data.pantsColor = -1; + if (data.personality === 255) data.personality = -1; + if (data.shirtColor === 255) data.shirtColor = -1; + if (data.wigType === 255) data.wigType = -1; + if (data.clothesType === 255) data.clothesType = -1; + if (data.shoesColor === 255) data.shoesColor = -1; + + // console.log("new data:", data); + + return data; + } + static parseDataBinary(input: Uint8Array) { + const data = Mii.parseData(input); + return MiiCreatorV4Data.pack(data); + } + + /** Returns an object version of the current fields */ + #getObject( + override: Partial> | null = null + ) { + return { + miicVersion: this.miicVersion, + originPlatform: this.originPlatform, + authorId: this.authorId, + createId: this.createId, + creator: this.creator, + nickname: this.nickname, + beardColor: this.beardColor, + beardType: this.beardType, + birthDay: this.birthDay, + birthMonth: this.birthMonth, + birthYear: this.birthYear, + build: this.build, + clothesType: this.clothesType, + eyeAspect: this.eyeAspect, + eyebrowAspect: this.eyebrowAspect, + eyebrowColor: this.eyebrowColor, + eyebrowRotate: this.eyebrowRotate, + eyebrowScale: this.eyebrowScale, + eyebrowType: this.eyebrowType, + eyebrowX: this.eyebrowX, + eyebrowY: this.eyebrowY, + eyeColor: this.eyeColor, + eyeRotate: this.eyeRotate, + eyeScale: this.eyeScale, + eyeSclera: this.eyeSclera, + eyeType: this.eyeType, + eyeX: this.eyeX, + eyeY: this.eyeY, + facelineColor: this.facelineColor, + facelineMake: this.facelineMake, + facelineType: this.facelineType, + facelineWrinkle: this.facelineWrinkle, + facePaintColor: this.facePaintColor, + favorite: this.favorite, + favoriteColor: this.favoriteColor, + fontRegion: this.fontRegion, + gender: this.gender, + glassColor: this.glassColor, + glassScale: this.glassScale, + glassType: this.glassType, + glassY: this.glassY, + hairColor: this.hairColor, + hairFlip: this.hairFlip, + hairType: this.hairType, + hatCommonColor: this.hatCommonColor, + hatFavoriteColor: this.hatFavoriteColor, + hatType: this.hatType, + height: this.height, + wigType: this.wigType, + moleScale: this.moleScale, + moleType: this.moleType, + moleX: this.moleX, + moleY: this.moleY, + mouthAspect: this.mouthAspect, + mouthColor: this.mouthColor, + mouthScale: this.mouthScale, + mouthType: this.mouthType, + mouthY: this.mouthY, + mustacheScale: this.mustacheScale, + mustacheType: this.mustacheType, + mustacheY: this.mustacheY, + temporary: this.temporary, + noseScale: this.noseScale, + noseType: this.noseType, + noseY: this.noseY, + pantsColor: this.pantsColor, + personality: this.personality, + regionMove: this.regionMove, + shirtColor: this.shirtColor, + shoesColor: this.shoesColor, + special: this.special, + ...override + }; + } + + #getNicknameSafe() { + if (this.nickname.trim() !== "") return this.nickname; + else return "A Mii"; + } + + /** validate state of current fields */ + verify(): { valid: boolean; reasons: string[] } { + return validate(this.#getObject()); + } + validate() { + const verify = this.verify(); + if (verify.valid === true) this.valid = true; + else { + this.valid = false; + console.warn( + `${this.#getNicknameSafe()} has invalid data:`, + verify.reasons.join(", ") + ); + console.warn(this.export()); + throw new Error( + `Mii data for ${this.nickname} is not valid: ${verify.reasons.join( + ", " + )}` + ); + } + } + + /** import existing miic v4 data */ + import(data: MiiCreatorV4Data) { + this.miicVersion = data.miicVersion; + this.originPlatform = data.originPlatform; + this.authorId = data.authorId; + this.createId = data.createId; + this.creator = data.creator; + this.nickname = data.nickname; + this.beardColor = data.beardColor; + this.beardType = data.beardType; + this.birthDay = data.birthDay; + this.birthMonth = data.birthMonth; + this.birthYear = data.birthYear; + this.build = data.build; + this.clothesType = data.clothesType; + this.eyeAspect = data.eyeAspect; + this.eyebrowAspect = data.eyebrowAspect; + this.eyebrowColor = data.eyebrowColor; + this.eyebrowRotate = data.eyebrowRotate; + this.eyebrowScale = data.eyebrowScale; + this.eyebrowType = data.eyebrowType; + this.eyebrowX = data.eyebrowX; + this.eyebrowY = data.eyebrowY; + this.eyeColor = data.eyeColor; + this.eyeRotate = data.eyeRotate; + this.eyeScale = data.eyeScale; + this.eyeSclera = data.eyeSclera; + this.eyeType = data.eyeType; + this.eyeX = data.eyeX; + this.eyeY = data.eyeY; + this.facelineColor = data.facelineColor; + this.facelineMake = data.facelineMake; + this.facelineType = data.facelineType; + this.facelineWrinkle = data.facelineWrinkle; + this.facePaintColor = data.facePaintColor; + this.favorite = data.favorite; + this.favoriteColor = data.favoriteColor; + this.fontRegion = data.fontRegion; + this.gender = data.gender; + this.glassColor = data.glassColor; + this.glassScale = data.glassScale; + this.glassType = data.glassType; + this.glassY = data.glassY; + this.hairColor = data.hairColor; + this.hairFlip = data.hairFlip; + this.hairType = data.hairType; + this.hatFavoriteColor = data.hatFavoriteColor; + this.hatCommonColor = data.hatCommonColor; + this.hatType = data.hatType; + this.height = data.height; + this.wigType = data.wigType; + this.moleScale = data.moleScale; + this.moleType = data.moleType; + this.moleX = data.moleX; + this.moleY = data.moleY; + this.mouthAspect = data.mouthAspect; + this.mouthColor = data.mouthColor; + this.mouthScale = data.mouthScale; + this.mouthType = data.mouthType; + this.mouthY = data.mouthY; + this.mustacheScale = data.mustacheScale; + this.mustacheType = data.mustacheType; + this.mustacheY = data.mustacheY; + this.noseScale = data.noseScale; + this.noseType = data.noseType; + this.noseY = data.noseY; + this.pantsColor = data.pantsColor; + this.personality = data.personality; + this.regionMove = data.regionMove; + this.shirtColor = data.shirtColor; + this.special = data.special; + this.shoesColor = data.shoesColor; + this.temporary = data.temporary; + + if ( + this.originPlatform === MiiCreatorOriginPlatform.CFL_3DS || + this.originPlatform === MiiCreatorOriginPlatform.FFL_Wii_U + ) { + // Parse CreateID just in case + const createId = FFLiCreateID.unpack(this.createId) as FFLiCreateID; + + if (!createId.flag_normal) { + this.special = 1; + // console.warn("Special flag is being overridden due to CreateID."); + } + if (createId.flag_temporary) { + this.special = 0; + this.temporary = 1; + // console.warn("Temporary flag is being set due to CreateID."); + } + } + + this.fixInternalIDs(); + } + + /** outputs in specific format */ + export(outputFormat: MiiDataExportType = "miic"): Uint8Array { + // this.validate(); + this.fixInternalIDs(); + switch (outputFormat) { + case "rsd": + throw new Error("RSD format is not yet supported."); + default: + case "miic": + return MiiCreatorV4Data.pack(this.#getObject()); + // This is decoded studio data and also invalid if face paint is used, + // maybe provide a normal studio data export that is encoded properly? + case "studioData": + return StudioData.pack( + this.#getObject({ + facelineColor: + this.facePaintColor !== -1 + ? this.facePaintColor + 10 + : this.facelineColor + }) + ); + case "switchCharInfo": + return NnMiiCharInfo.pack(this.#getObject() as any); + case "ffsd": + return MiiCreatorV4DataToFFSD(this.#getObject(), true); + case "ffsd_append_miic": + return MiiCreatorV4DataToFFSD(this.#getObject(), true, true); + } + } + + exportHex(outputFormat: MiiDataExportType) { + const data = this.export(outputFormat); + return dataToHex(data); + } + + exportBase64(outputFormat: MiiDataExportType) { + const data = this.export(outputFormat); + return dataToBase64(data); + } + + hasExtendedColors(): boolean { + // TODO: implement a check for non-ver3 colors + // return true; + return false; + } + + // helper function to fix bad AuthorID/CreateID. + // (3DS/Wii U systems will complain) + // Easiest solution is to just randomize them + fixInternalIDs() { + const createId = FFLiCreateID.unpack(this.createId) as FFLiCreateID; + const authorId = this.authorId; + + // If empty, randomize CreateID base value + if (Array.from(createId.base).every((e) => e === 0)) { + createId.base = randomizeUint8Array(createId.base); + } + + // If empty, randomize AuthorID value + if (Array.from(authorId).every((e) => e === 0)) { + this.authorId = randomizeUint8Array(authorId); + } + + // Correctly set special flag depending on special data + if (createId.flag_normal === 0 && this.special === 0) { + createId.flag_normal = 1; + } + if (createId.flag_normal === 1 && this.special === 1) { + createId.flag_normal = 0; + } + // this code sucks + if (createId.flag_temporary === 0 && this.temporary === 1) { + createId.flag_temporary = 1; + } + if (createId.flag_temporary === 1 && this.temporary === 0) { + createId.flag_temporary = 0; + } + + // Re-pack CreateID value + this.createId = FFLiCreateID.pack(createId); + } +} diff --git a/src/class/MiiEditor.ts b/src/class/MiiEditor.ts index e9a8ae0..8ee1fff 100644 --- a/src/class/MiiEditor.ts +++ b/src/class/MiiEditor.ts @@ -1,5 +1,4 @@ -import Mii from "../external/mii-js/mii"; -import { Buffer } from "../../node_modules/buffer/index"; +import Mii from "../class/MiiData"; import Html from "@datkat21/html"; import { TabList } from "../ui/components/TabList"; import EditorIcons from "../constants/EditorIcons"; @@ -13,12 +12,10 @@ import { FavoriteColorTab } from "../ui/tabs/FavoriteColor"; import { MouthTab } from "../ui/tabs/Mouth"; import { HairTab } from "../ui/tabs/Hair"; import { - MiiEyeColorTable, MiiFavoriteColorIconTable, MiiFavoriteColorLookupTable, - MiiGlassesColorIconTable, SwitchMiiColorTable, - SwitchMiiColorTableLip, + SwitchMiiColorTableLip } from "../constants/ColorTables"; import { ScaleTab } from "../ui/tabs/Scale"; import Modal from "../ui/components/Modal"; @@ -33,14 +30,16 @@ import { OptionsTab } from "../ui/tabs/Options"; import { ExtHatTab } from "../ui/tabs/ExtHat"; import { Mii2DRenderer } from "./2DRenderer"; import { getSetting } from "../util/SettingsHelper"; +import { dataToBase64 } from "../util/dataConvert"; +import { parseHexOrB64ToUint8Array } from "../external/ffl.js/ffl"; export enum MiiGender { Male, - Female, + Female } export enum RenderMode { - Canvas2DRenderer, - Canvas3DScene, + Canvas2DRenderer = 0, + Canvas3DScene = 1 } export type IconSet = { face: string[]; @@ -59,11 +58,23 @@ export type IconSet = { export enum RenderPart { Head, - Face + Face, + Body +} + +export enum BodyUpdateType { + None, + ClothingUpdate, + RepositionCamera } let activeMii: Mii; export const getMii = () => activeMii; +let currentEditor: MiiEditor | null = null; + +import { _ } from "../util/Lang"; +import { ExtClothesTab } from "../ui/tabs/ExtClothes"; +const __ = _(); export class MiiEditor { mii: Mii; @@ -83,7 +94,12 @@ export class MiiEditor { renderingMode!: RenderMode; onShutdown!: (mii: string, shutdownProperly?: boolean) => any | Promise; - errors: Map; + errors: Map; + useAccessibility!: boolean; + + static getCurrentEditor() { + return currentEditor; + } constructor( gender: MiiGender, @@ -94,6 +110,7 @@ export class MiiEditor { init?: string ) { window.editor = this; + currentEditor = this; document.dispatchEvent(new CustomEvent("editor-launch")); @@ -104,34 +121,19 @@ export class MiiEditor { // default male mii let initString = - "AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn"; + "BAXGigDvV8wSNID/cJl869TJwxYAAAAAAAAAAAAAAAAAAAAAAAAAAE0AaQBpAAAAAAAAAAAAAAAAAAAACAAAAAAAQAMDAQYEBgIKCAQEAgIMAAAAAP8AAAAACAQACgEAIf///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAP//"; if (gender === MiiGender.Female) { initString = - "AwEAAAAAAAAAAAAAgN8ZmgAAAAAAAAAAAQBNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAMAQRoQxggNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFik"; + "BACnywgm6RFTRIDfGZqVDHu5NhQAAAAAAAAAAAAAAAAAAAAAAAAAAE0AaQBpAAAAAAAAAAAAAAAAAAAACAAAAAAAQAMDAQYEAAIKCAMEBAIMAAAAAP8AAAABCAQACgEADP///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAP//"; } if (init) initString = init; if (onShutdown) { this.onShutdown = onShutdown; } - getSetting("editMode").then((s) => { - if (s === "2d") { - this.renderingMode = RenderMode.Canvas2DRenderer; - } else if (s === "3d") { - if (Config.renderer.allow3DMode === true) - this.renderingMode = RenderMode.Canvas3DScene; - else this.renderingMode = RenderMode.Canvas2DRenderer; - } - }); - - this.mii = new Mii(Buffer.from(initString, "base64") as unknown as Buffer); + this.mii = new Mii(initString); activeMii = this.mii; - // Ensure that birthPlatform doesn't cause issues. - if (this.mii.deviceOrigin === 0) this.mii.deviceOrigin = 4; - // Enable allow copying so QR can be made. - if (this.mii.allowCopying === false) this.mii.allowCopying = true; - this.#setupUi(); } @@ -163,6 +165,19 @@ export class MiiEditor { } async #setupUi() { + const editMode = await getSetting("editMode"); + + if (editMode === "2d") { + this.renderingMode = RenderMode.Canvas2DRenderer; + } else if (editMode === "3d") { + if (Config.renderer.allow3DMode === true) + this.renderingMode = RenderMode.Canvas3DScene; + else this.renderingMode = RenderMode.Canvas2DRenderer; + } + + const useAccessibility = await getSetting("accessibilityFeature"); + this.useAccessibility = useAccessibility; + this.icons = await fetch("./dist/icons.json?t=" + Date.now()).then((j) => j.json() ); @@ -193,7 +208,12 @@ export class MiiEditor { let nextRenderMode = 0; switch (this.renderingMode) { case RenderMode.Canvas2DRenderer: - this.#setup2D(); + if (Config.renderer.useRendererServer === true) this.#setup2D(); + else { + await this.#setup3D(); + this.ui.scene.cameraPan = true; + this.ui.scene.focusCameraUpdate(); + } nextRenderMode = RenderMode.Canvas3DScene; break; case RenderMode.Canvas3DScene: @@ -201,6 +221,7 @@ export class MiiEditor { nextRenderMode = RenderMode.Canvas2DRenderer; break; } + const renderModeToggle = AddButtonSounds( new Html("button") .class("render-mode-toggle") @@ -209,8 +230,12 @@ export class MiiEditor { .on("click", () => { if (Config.renderer.allow3DMode === false) return Modal.alert( - "You can't use this feature", - "Sorry, but you can't use this feature because 3D mode is disabled at the moment." + // 3D mode disabled dialog title + __("You can't use this feature"), + // 3D mode disabled dialog description + __( + "Sorry, but you can't use this feature because 3D mode is disabled at the moment." + ) ); renderModeToggle.text(this.#renderModeText(this.renderingMode)); switch (this.renderingMode) { @@ -220,6 +245,12 @@ export class MiiEditor { case RenderMode.Canvas3DScene: this.renderingMode = RenderMode.Canvas2DRenderer; } + if (this.ui.scene && Config.renderer.useRendererServer === false) { + this.ui.scene.cameraPan = !Boolean(this.renderingMode); + this.ui.scene.focusCameraUpdate(); + console.log("why this Really not work :(", this.renderingMode); + return; + } this.render(); }) .appendTo(this.ui.mii) @@ -240,6 +271,10 @@ export class MiiEditor { undefined, this ); + if (this.ui.scene && Config.renderer.useRendererServer === false) { + this.ui.scene.cameraPan = Boolean(this.renderingMode); + this.ui.scene.focusCameraUpdate(); + } await this.ui.scene.init(); this.ui.mii.append(this.ui.scene.getRendererElement()); window.addEventListener("resize", () => { @@ -249,45 +284,56 @@ export class MiiEditor { this.ui.scene.getRendererElement().classList.add("ready"); this.ui.mii.qs(".loader")!.classOff("active"); } - #updateCssVars() { - let glassesColor: string; - if (this.mii.trueGlassesColor > 5) - glassesColor = SwitchMiiColorTable[this.mii.trueGlassesColor]; - else glassesColor = MiiGlassesColorIconTable[this.mii.trueGlassesColor].top; - let eyeColor: string; - if (this.mii.trueEyeColor > 6) { - eyeColor = SwitchMiiColorTable[this.mii.trueEyeColor - 6]; - } else eyeColor = MiiEyeColorTable[this.mii.fflEyeColor]; - let mouthColor: { top: string; bottom: string }; - if (this.mii.trueMouthColor > 6) { - mouthColor = { - top: SwitchMiiColorTableLip[this.mii.trueMouthColor - 5], - bottom: SwitchMiiColorTable[this.mii.trueMouthColor - 5], - }; - } else - mouthColor = { - top: SwitchMiiColorTableLip[this.mii.fflMouthColor + 19], - bottom: SwitchMiiColorTable[this.mii.fflMouthColor + 19], - }; + async #updateCssVars() { + let glassesColor = SwitchMiiColorTable[this.mii.glassColor]; - this.ui.base.style({ - "--eye-color": eyeColor, - "--icon-lip-color-top": mouthColor.top, - "--icon-lip-color-bottom": mouthColor.bottom, - "--icon-hair-tie": - "#" + - MiiFavoriteColorLookupTable[this.mii.favoriteColor] - .toString(16) - .padStart(6, "0"), - "--icon-eyebrow-fill": SwitchMiiColorTable[this.mii.eyebrowColor], - "--icon-hair-fill": SwitchMiiColorTable[this.mii.hairColor], - "--icon-facial-hair-fill": SwitchMiiColorTable[this.mii.facialHairColor], - "--icon-hat-fill": MiiFavoriteColorIconTable[this.mii.favoriteColor].top, - "--icon-hat-stroke": - MiiFavoriteColorIconTable[this.mii.favoriteColor].bottom, - "--icon-glasses-fill": glassesColor, - "--icon-glasses-shade": glassesColor + "77", - }); + let eyeColor = SwitchMiiColorTable[this.mii.eyeColor]; + let mouthColor = { + top: SwitchMiiColorTableLip[this.mii.mouthColor], + bottom: SwitchMiiColorTable[this.mii.mouthColor] + }; + + if (this.useAccessibility) { + this.ui.base.style({ + "--eye-color": "#787880", + "--icon-lip-color-top": "#780c0c", + "--icon-lip-color-bottom": "#f00c08", + "--icon-hair-tie": + "#" + + MiiFavoriteColorLookupTable[this.mii.favoriteColor] + .toString(16) + .padStart(6, "0"), + "--icon-eyebrow-fill": "var(--text)", + "--icon-hair-fill": "var(--text)", + "--icon-facial-hair-fill": "#9b9b9b", + "--icon-hat-fill": MiiFavoriteColorIconTable[0].top, + "--icon-hat-stroke": MiiFavoriteColorIconTable[0].bottom, + "--icon-custom-hat-fill": MiiFavoriteColorIconTable[0].top, + "--icon-custom-hat-stroke": MiiFavoriteColorIconTable[0].bottom, + "--icon-glasses-fill": "#787880", + "--icon-glasses-shade": "#78788077" + }); + } else { + this.ui.base.style({ + "--eye-color": eyeColor, + "--icon-lip-color-top": mouthColor.top, + "--icon-lip-color-bottom": mouthColor.bottom, + "--icon-hair-tie": + "#" + + MiiFavoriteColorLookupTable[this.mii.favoriteColor] + .toString(16) + .padStart(6, "0"), + "--icon-eyebrow-fill": SwitchMiiColorTable[this.mii.eyebrowColor], + "--icon-hair-fill": SwitchMiiColorTable[this.mii.hairColor], + "--icon-facial-hair-fill": SwitchMiiColorTable[this.mii.beardColor], + "--icon-hat-fill": + MiiFavoriteColorIconTable[this.mii.favoriteColor].top, + "--icon-hat-stroke": + MiiFavoriteColorIconTable[this.mii.favoriteColor].bottom, + "--icon-glasses-fill": glassesColor, + "--icon-glasses-shade": glassesColor + "77" + }); + } } #setupTabs() { const TabInit = (Tab: TabBase, CameraFocusPart: CameraPosition) => { @@ -295,20 +341,18 @@ export class MiiEditor { if (this.ui.scene) this.ui.scene.focusCamera(CameraFocusPart); await Tab({ container: content, - callback: (mii, forceRender, renderPart) => { + callback: (mii, forceRender, renderPart, bodyUpdateType) => { this.mii = mii; - if (this.mii.normalMii === false) this.mii.disableSharing = true; - else this.mii.disableSharing = false; activeMii = mii; // use of forceRender forces reload of the head in 3D mode - this.render(forceRender, renderPart); - if (this.ui.scene) this.ui.scene.sparkle(); + this.render(forceRender, renderPart, bodyUpdateType); this.#updateCssVars(); this.dirty = true; }, icons: this.icons, mii: this.mii, editor: this, + useAccessibility: this.useAccessibility }); if (this.ui.scene) this.ui.scene.resize(); }; @@ -317,59 +361,59 @@ export class MiiEditor { const tabs = TabList([ { icon: EditorIcons.head, - select: TabInit(HeadTab, CameraPosition.MiiHead), + select: TabInit(HeadTab, CameraPosition.MiiHead) }, { icon: EditorIcons.hair, - select: TabInit(HairTab, CameraPosition.MiiHead), + select: TabInit(HairTab, CameraPosition.MiiHead) }, { icon: EditorIcons.hat, - select: TabInit(ExtHatTab, CameraPosition.MiiHead), + select: TabInit(ExtHatTab, CameraPosition.MiiHead) }, { icon: EditorIcons.eyebrows, - select: TabInit(EyebrowTab, CameraPosition.MiiHead), + select: TabInit(EyebrowTab, CameraPosition.MiiHead) }, { icon: EditorIcons.eyes, - select: TabInit(EyeTab, CameraPosition.MiiHead), + select: TabInit(EyeTab, CameraPosition.MiiHead) }, { icon: EditorIcons.nose, - select: TabInit(NoseTab, CameraPosition.MiiHead), + select: TabInit(NoseTab, CameraPosition.MiiHead) }, { icon: EditorIcons.mouth, - select: TabInit(MouthTab, CameraPosition.MiiHead), + select: TabInit(MouthTab, CameraPosition.MiiHead) }, { icon: EditorIcons.facialHair, - select: TabInit(FacialHairTab, CameraPosition.MiiHead), + select: TabInit(FacialHairTab, CameraPosition.MiiHead) }, { icon: EditorIcons.mole, - select: TabInit(MoleTab, CameraPosition.MiiHead), + select: TabInit(MoleTab, CameraPosition.MiiHead) }, { icon: EditorIcons.glasses, - select: TabInit(GlassesTab, CameraPosition.MiiHead), + select: TabInit(GlassesTab, CameraPosition.MiiHead) }, { icon: EditorIcons.scale, - select: TabInit(ScaleTab, CameraPosition.MiiFullBody), + select: TabInit(ScaleTab, CameraPosition.MiiFullBody) }, { icon: EditorIcons.favoriteColor, - select: TabInit(FavoriteColorTab, CameraPosition.MiiFullBody), + select: TabInit(FavoriteColorTab, CameraPosition.MiiFullBody) }, { - icon: EditorIcons.gender, - select: TabInit(OptionsTab, CameraPosition.MiiFullBody), + icon: EditorIcons.clothes, + select: TabInit(ExtClothesTab, CameraPosition.MiiFullBody) }, { icon: EditorIcons.details, - select: TabInit(MiscTab, CameraPosition.MiiFullBody), + select: TabInit(MiscTab, CameraPosition.MiiFullBody) }, { icon: EditorIcons.save + "Save", @@ -383,20 +427,17 @@ export class MiiEditor { { text: "Save & Exit", callback: () => { - // If the Mii is special and we try to save, there's an error that we need to disable sharing - if (getMii().normalMii === false) - getMii().disableSharing = true; this.shutdown(); - }, + } }, { text: "Exit without Saving", callback: () => { this.shutdown(false); - }, + } }, { - text: "Cancel", + text: "Cancel" } ); else @@ -408,21 +449,21 @@ export class MiiEditor { text: "Save & Exit", callback: () => { this.shutdown(); - }, + } }, { text: "Exit without Saving", callback: () => { this.shutdown(false); - }, + } }, { - text: "Cancel", + text: "Cancel" } ); }, - update: false, - }, + update: false + } ]); this.ui.tabList = tabs.list; this.ui.tabContent = tabs.content; @@ -431,13 +472,35 @@ export class MiiEditor { async render( forceReloadHead: boolean = true, - renderPart: RenderPart = RenderPart.Head + renderPart: RenderPart = RenderPart.Head, + bodyUpdateType: BodyUpdateType = BodyUpdateType.None ) { if (Config.renderer.allow3DMode === false) this.renderingMode = RenderMode.Canvas2DRenderer; // every "img" here should be changed to "canvas.renderer" for new 2d mode. switch (this.renderingMode) { case RenderMode.Canvas2DRenderer: + if (Config.renderer.useRendererServer === false) { + if (this.ui.mii.qs("canvas.scene") === null) { + await this.#setup3D(); + } + this.ui.mii.qs("canvas.scene")?.style({ display: "block" }); + this.ui.scene.mii = this.mii; + if (renderPart === RenderPart.Body) { + // only reload body + this.ui.scene.updateBody(bodyUpdateType); + this.ui.scene.resize(); + } else if (forceReloadHead) { + // reload head and body + if (bodyUpdateType !== BodyUpdateType.None) { + this.ui.scene.updateBody(bodyUpdateType); + } + this.ui.scene.updateMiiHead(renderPart); + this.ui.scene.sparkle(); + this.ui.scene.resize(); + } + return; + } if (this.ui.mii.qs("img") === null) { this.#setup2D(); } @@ -447,7 +510,7 @@ export class MiiEditor { this.ui.mii.qs("img")?.style({ display: "block" }); let pantsColor: string = "gray"; - if (this.mii.normalMii === false) { + if (this.mii.special === 1) { pantsColor = "gold"; } if (this.mii.favorite) { @@ -460,15 +523,17 @@ export class MiiEditor { .attr({ src: `${ Config.renderer.renderFullBodyURL - }&data=${encodeURIComponent( - this.mii.encodeStudio().toString("hex") - )}&${Config.renderer.hatTypeParam}=${ - this.mii.extHatType + Config.renderer.hatTypeAdd - }&${Config.renderer.hatColorParam}=${ - this.mii.extHatColor + Config.renderer.hatColorAdd + }&data=${encodeURIComponent(this.mii.exportHex("studioData"))}&${ + Config.renderer.hatTypeParam + }=${this.mii.hatType + Config.renderer.hatTypeAdd}&${ + Config.renderer.hatColorParam + }=${ + (this.mii.hatFavoriteColor !== -1 + ? this.mii.hatFavoriteColor - 1 + : -1) + Config.renderer.hatColorAdd }&miic=${encodeURIComponent( - this.mii.encode().toString("base64") - )}&pantsColor=${pantsColor}`, + dataToBase64(this.mii.export("miic")) + )}&pantsColor=${pantsColor}` }); // this.ui.renderer.mii = this.mii; // this.ui.renderer.render(); @@ -482,12 +547,16 @@ export class MiiEditor { } this.ui.mii.qs("canvas.scene")?.style({ display: "block" }); this.ui.scene.mii = this.mii; - if (forceReloadHead) { + if (renderPart === RenderPart.Body) { + // only reload body + this.ui.scene.updateBody(bodyUpdateType); + } else if (forceReloadHead) { // reload head and body + if (bodyUpdateType !== BodyUpdateType.None) { + this.ui.scene.updateBody(bodyUpdateType); + } this.ui.scene.updateMiiHead(renderPart); - } else { - // only reload body - this.ui.scene.updateBody(true); + this.ui.scene.sparkle(); } break; } @@ -499,14 +568,14 @@ export class MiiEditor { } async shutdown(shouldSave: boolean = true) { if (shouldSave) { - if (Array.from(this.errors.values()).find((i) => i === true)) { + if (Array.from(this.errors.values()).find((i) => i.valid === false)) { let errorList = []; - for (const [id, value] of this.errors.entries()) { - if (value === true) errorList.push(id); + for (const value of this.errors.values()) { + if (value.valid === false) errorList.push(value.reason); } Modal.alert( - "Error", - "Will not save because there are problems with the following items:\n\n" + + "Notice", + "You need to fix the following issues before you can save:\n\n" + errorList.map((e) => `• ${e}`).join("\n") ); return; @@ -522,6 +591,18 @@ export class MiiEditor { }, 1500); }); } + + await fetch("/api/archive", { + body: JSON.stringify({ + nickname: this.mii.nickname, + creator: this.mii.creator, + ffsd: this.mii.exportBase64("ffsd"), + data: this.mii.exportBase64("miic"), + studio: this.mii.exportBase64("studioData") + }), + method: "POST", + headers: { "content-type": "application/json" } + }).catch(undefined); } if (this.#loadInterval) { @@ -530,18 +611,17 @@ export class MiiEditor { this.ui.base.classOn("closing"); setTimeout(() => { - if (this.ui.mii.qs("canvas.scene")) { + if (this.ui.scene) { this.ui.scene.shutdown(); } this.ui.base.cleanup(); if (this.onShutdown) { - this.onShutdown( - Buffer.from(this.mii.encode()).toString("base64"), - shouldSave - ); + this.onShutdown(dataToBase64(this.mii.export("miic")), shouldSave); } document.dispatchEvent(new CustomEvent("editor-shutdown")); + window.editor = null; + currentEditor = null; }, 500); } } diff --git a/src/class/audio/MusicManager.ts b/src/class/audio/MusicManager.ts index ef1773e..30dd5c1 100644 --- a/src/class/audio/MusicManager.ts +++ b/src/class/audio/MusicManager.ts @@ -46,33 +46,33 @@ export class MusicManager { const theme = document.documentElement.dataset.theme !== undefined ? document.documentElement.dataset.theme - : await localforage.getItem("settings_theme") as string; + : ((await localforage.getItem("settings_theme")) as string); if (this.theme === theme) return; this.theme = theme; console.error("initMusic()", theme, document.documentElement.dataset.theme); - if (theme === "wiiu") { - this.setVolume(0.65); - this.previousVolume = 0.65; - await this.loadSong( - "./assets/audio/ffl_app_menu.mp3", - "mii_creator_music" - ); - await this.loadSong( - "./assets/audio/ffl_app_edit.mp3", - "mii_editor_music" - ); - //@ts-expect-error - window.music = this; - } else { - this.setVolume(0.28); - this.previousVolume = 0.28; - await this.loadSong( - "./assets/audio/miimakermusic.mp3", - "mii_creator_music" - ); - } + // if (theme === "wiiu") { + // this.setVolume(0.65); + // this.previousVolume = 0.65; + // await this.loadSong( + // "./assets/audio/ffl_app_menu.mp3", + // "mii_creator_music" + // ); + // await this.loadSong( + // "./assets/audio/ffl_app_edit.mp3", + // "mii_editor_music" + // ); + // //@ts-expect-error + // window.music = this; + // } else { + this.setVolume(0.28); + this.previousVolume = 0.28; + await this.loadSong( + "./assets/audio/miimakermusic.mp3", + "mii_creator_music" + ); + // } this.initMusicReady(); } diff --git a/src/class/audio/SoundManager.ts b/src/class/audio/SoundManager.ts index 8e18dcb..05dc030 100644 --- a/src/class/audio/SoundManager.ts +++ b/src/class/audio/SoundManager.ts @@ -25,17 +25,17 @@ export class SoundManager { document.addEventListener("theme-change", () => { const theme = document.documentElement.dataset.theme; if (theme !== currentTheme) { - if (theme === "wiiu") { - loadBaseSounds("./assets/audio/miiMakerU.zip"); - this.previousVolume = 0.75; - this.setVolume(0.75); - this.previousVolume = 0.75; - } else { - loadBaseSounds("./assets/audio/miiMakerSwitch.zip"); - this.previousVolume = 0.28; - this.setVolume(0.28); - this.previousVolume = 0.28; - } + // if (theme === "wiiu") { + // loadBaseSounds("./assets/audio/miiMakerU.zip"); + // this.previousVolume = 0.75; + // this.setVolume(0.75); + // this.previousVolume = 0.75; + // } else { + loadBaseSounds("./assets/audio/miiMakerSwitch.zip"); + this.previousVolume = 0.28; + this.setVolume(0.28); + this.previousVolume = 0.28; + // } } currentTheme = theme; }); @@ -99,7 +99,8 @@ export class SoundManager { let sm: SoundManager = new SoundManager(); export const loadBaseSounds = async ( - path: string = "./assets/audio/miiMakerSwitch.zip" + path: string = "./assets/audio/miiMakerSwitch.zip", + smRef: SoundManager = sm ) => { const data = await fetch(path).then((j) => j.blob()); const zip = await JSZip.loadAsync(data); @@ -113,6 +114,6 @@ export const loadBaseSounds = async ( for (let i = 0; i < fileList.length; i++) { const fileName = fileList[i].split("."); fileName.pop(); - await sm.loadSoundBuffer(resolves[i], fileName.join(".")); + await smRef.loadSoundBuffer(resolves[i], fileName.join(".")); } }; diff --git a/src/class/struct/FFLStoreData.ts b/src/class/struct/FFLStoreData.ts new file mode 100644 index 0000000..112dde2 --- /dev/null +++ b/src/class/struct/FFLStoreData.ts @@ -0,0 +1,267 @@ +import _ from "../../external/ffl.js/struct-fu"; +import type { StructInstance } from "../../external/ffl.js/struct-fu"; + +export const FFLiCreateID = _.struct([ + _.ubit("flag_normal", 1), + _.ubit("flag_1", 1), + _.ubit("flag_temporary", 1), + _.ubit("flag_3", 1), + _.ubit("create_date1", 14), // 28-bit field + _.ubit("create_date2", 14), // 28-bit field + _.byte("base", 6) +]) as StructInstance; +export const date_timestamp = function (createID: any) { + var val28 = (createID.create_date1 << 14) | createID.create_date2; + var timestamp = val28 * 2 + 1262304000; + return new Date(timestamp * 1000); +}; +export const FFLiAuthorID = _.struct([ + _.byte("data", 8) +]) as StructInstance; + +// based on arian's FFLiMiiDataCore implementation +export const Ver3StoreData = _.struct([ + // 0x00: 32 bits + _.ubitLE("mii_version", 8), // LSB + _.ubitLE("copyable", 1), + _.ubitLE("ng_word", 1), + _.ubitLE("region_move", 2), + _.ubitLE("font_region", 2), + _.ubitLE("reserved_0", 2), // Unused padding + _.ubitLE("room_index", 4), + _.ubitLE("position_in_room", 4), + _.ubitLE("author_type", 4), + _.ubitLE("birth_platform", 3), + _.ubitLE("reserved_1"), // Unused (MSB) + + // 0x04: author_id (8 bytes) + _.struct("author_id", [FFLiAuthorID]), + + // 0x0C: creator_id (10 bytes) + //_.byte('create_id', 10), + _.struct("create_id", [FFLiCreateID]), + + // 0x16: padding (2 bytes) + _.byte("reserved_2", 2), + + // 0x18: 16 bits for birthday and favorite + _.ubitLE("gender", 1), // LSB + _.ubitLE("birth_month", 4), + _.ubitLE("birth_day", 5), + _.ubitLE("favorite_color", 4), + _.ubitLE("favorite", 1), + _.ubitLE("padding_0", 1), // Placeholder (MSB) + + // 0x1A: name (UTF-16LE, 20 bytes) + _.char16le("name", 20), + + // 0x2E: height and build + _.uint8("height"), + _.uint8("build"), + + // 0x30: 16 bits for face data + _.ubitLE("localonly", 1), // LSB + _.ubitLE("face_type", 4), + _.ubitLE("face_color", 3), + _.ubitLE("face_tex", 4), + _.ubitLE("face_make", 4), // MSB + + // 0x32: 16 bits for hair data + _.ubitLE("hair_type", 8), // LSB + _.ubitLE("hair_color", 3), + _.ubitLE("hair_flip", 1), + _.ubitLE("padding_1", 4), // Unused padding (MSB) + + // 0x34: 16 bits for eye data + _.ubitLE("eye_type", 6), // LSB + _.ubitLE("eye_color", 3), + _.ubitLE("eye_scale", 4), + _.ubitLE("eye_aspect", 3), // MSB + + // 0x36: 16 bits for eye positioning + _.ubitLE("eye_rotate", 5), // LSB + _.ubitLE("eye_x", 4), + _.ubitLE("eye_y", 5), + _.ubitLE("padding_2", 2), // Unused padding (MSB) + + // 0x38: 16 bits for eyebrow data + _.ubitLE("eyebrow_type", 5), // LSB + _.ubitLE("eyebrow_color", 3), + _.ubitLE("eyebrow_scale", 4), + _.ubitLE("eyebrow_aspect", 3), + _.ubitLE("padding_3", 1), // Unused padding (MSB) + + // 0x3A: 16 bits for eyebrow positioning + _.ubitLE("eyebrow_rotate", 5), // LSB + _.ubitLE("eyebrow_x", 4), + _.ubitLE("eyebrow_y", 5), + _.ubitLE("padding_4", 2), // Unused padding (MSB) + + // 0x3C: 16 bits for nose data + _.ubitLE("nose_type", 5), // LSB + _.ubitLE("nose_scale", 4), + _.ubitLE("nose_y", 5), + _.ubitLE("padding_5", 2), // Unused padding (MSB) + + // 0x3E: 16 bits for mouth data + _.ubitLE("mouth_type", 6), // LSB + _.ubitLE("mouth_color", 3), + _.ubitLE("mouth_scale", 4), + _.ubitLE("mouth_aspect", 3), // MSB + + // 0x40: 16 bits for mustache/mouth position + _.ubitLE("mouth_y", 5), // LSB + _.ubitLE("mustache_type", 3), + _.ubitLE("padding_6", 8), // Unused padding (MSB) + + // 0x42: 16 bits for mustache/beard data + _.ubitLE("beard_type", 3), // LSB + _.ubitLE("beard_color", 3), + _.ubitLE("beard_scale", 4), + _.ubitLE("beard_y", 5), + _.ubitLE("padding_7", 1), // Unused padding (MSB) + + // 0x44: 16 bits for glasses data + _.ubitLE("glasses_type", 4), // LSB + _.ubitLE("glasses_color", 3), + _.ubitLE("glasses_scale", 4), + _.ubitLE("glass_y", 5), // MSB + + // 0x46: 16 bits for mole data + _.ubitLE("mole_type", 1), // LSB + _.ubitLE("mole_scale", 4), + _.ubitLE("mole_x", 5), + _.ubitLE("mole_y", 5), + _.ubitLE("padding_8", 1), // Unused padding (MSB) + + // FFLStoreData + _.char16le("creator", 20), + _.uint16le("padding_9"), + _.uint16("checksum") +]) as StructInstance; + +// Generate type data with this snippet +/* +var obj = Ver3StoreData.unpack(parseHexOrB64TextStringToUint8Array("...")) +var text=""; + +for (var key in obj) { + text += `${key}: ${typeof obj[key]};\n` +} + +console.log(text) +*/ +export type Ver3StoreData = { + mii_version: number; + copyable: number; + ng_word: number; + region_move: number; + font_region: number; + reserved_0: number; + room_index: number; + position_in_room: number; + author_type: number; + birth_platform: number; + reserved_1: number; + author_id: FFLiAuthorID; + create_id: FFLiCreateID; + reserved_2: object; + gender: number; + birth_month: number; + birth_day: number; + favorite_color: number; + favorite: number; + padding_0: number; + name: string; + height: number; + build: number; + localonly: number; + face_type: number; + face_color: number; + face_tex: number; + face_make: number; + hair_type: number; + hair_color: number; + hair_flip: number; + padding_1: number; + eye_type: number; + eye_color: number; + eye_scale: number; + eye_aspect: number; + eye_rotate: number; + eye_x: number; + eye_y: number; + padding_2: number; + eyebrow_type: number; + eyebrow_color: number; + eyebrow_scale: number; + eyebrow_aspect: number; + padding_3: number; + eyebrow_rotate: number; + eyebrow_x: number; + eyebrow_y: number; + padding_4: number; + nose_type: number; + nose_scale: number; + nose_y: number; + padding_5: number; + mouth_type: number; + mouth_color: number; + mouth_scale: number; + mouth_aspect: number; + mouth_y: number; + mustache_type: number; + padding_6: number; + beard_type: number; + beard_color: number; + beard_scale: number; + beard_y: number; + padding_7: number; + glasses_type: number; + glasses_color: number; + glasses_scale: number; + glass_y: number; + mole_type: number; + mole_scale: number; + mole_x: number; + mole_y: number; + padding_8: number; + creator: string; + padding_9: number; + checksum: number; +}; + +export type FFLiAuthorID = { + data: Uint8Array; +}; + +export type FFLiCreateID = { + flag_normal: number; + flag_1: number; + flag_temporary: number; + flag_3: number; + create_date1: number; + create_date2: number; + base: Uint8Array; +}; + +export function calculateCRC16(storeData: Uint8Array) { + const data = storeData.subarray(0, 0x5e); + console.log(data); + + let crc = 0x0000; + + for (const byte of data) { + for (let bit = 7; bit >= 0; bit--) { + const flag = (crc & 0x8000) != 0; + crc = ((crc << 1) | ((byte >> bit) & 0x1)) ^ (flag ? 0x1021 : 0); + } + } + + for (let i = 16; i > 0; i--) { + const flag = (crc & 0x8000) != 0; + crc = (crc << 1) ^ (flag ? 0x1021 : 0); + } + + return crc & 0xffff; +} diff --git a/src/class/struct/MiiCreatorV3Data.ts b/src/class/struct/MiiCreatorV3Data.ts new file mode 100644 index 0000000..86c9e5c --- /dev/null +++ b/src/class/struct/MiiCreatorV3Data.ts @@ -0,0 +1,156 @@ +import _ from "../../external/ffl.js/struct-fu"; +import type { StructInstance } from "../../external/ffl.js/struct-fu"; +import { FFLiAuthorID, FFLiCreateID, Ver3StoreData } from "./FFLStoreData"; +import { + EmptyMiiCreatorV4Data, + MiiCreatorOriginPlatform, + MiiCreatorV4Data +} from "./MiiCreatorV4Data"; +import { + Ver3EyeColorTable, + Ver3GlassColorTable, + Ver3HairColorTable, + Ver3MouthColorTable +} from "../../constants/ColorTables"; + +export const MiiCreatorV3Data = _.struct([ + _.struct([Ver3StoreData]), + + // nfp store "extention" data (mii creator stores it like this) + _.uint8("ext_faceline_color"), + _.uint8("ext_hair_color"), + _.uint8("ext_eye_color"), + _.uint8("ext_eyebrow_color"), + _.uint8("ext_mouth_color"), + _.uint8("ext_beard_color"), + _.uint8("ext_glass_color"), + _.uint8("ext_glass_type"), + // mii creator v3 specific data + _.uint8("ext_hat_type"), + _.uint8("ext_hat_color"), + _.uint8("ext_face_paint_color"), + _.uint8("ext_shirt_color") +]) as StructInstance; + +export interface MiiCreatorV3Data extends Ver3StoreData { + ext_faceline_color: number; + ext_hair_color: number; + ext_eye_color: number; + ext_eyebrow_color: number; + ext_mouth_color: number; + ext_beard_color: number; + ext_glass_color: number; + ext_glass_type: number; + // mii creator v3 specific data + ext_hat_type: number; + ext_hat_color: number; + ext_face_paint_color: number; + ext_shirt_color: number; +} + +export function MiiCreatorV3DataToMiiCreatorV4Data( + input: MiiCreatorV3Data +): MiiCreatorV4Data { + const data = EmptyMiiCreatorV4Data(); + + switch (input.birth_platform) { + case 0: + data.originPlatform = MiiCreatorOriginPlatform.RFL_Wii; + break; + case 1: + data.originPlatform = MiiCreatorOriginPlatform.NFL_DS; + break; + case 2: + data.originPlatform = MiiCreatorOriginPlatform.CFL_3DS; + break; + case 3: + data.originPlatform = MiiCreatorOriginPlatform.FFL_Wii_U; + break; + } + if ( + input.ext_beard_color || + input.ext_eye_color || + input.ext_eyebrow_color || + input.ext_face_paint_color || + input.ext_faceline_color || + input.ext_glass_color || + input.ext_glass_type || + input.ext_hair_color || + input.ext_hat_color || + input.ext_hat_type || + input.ext_mouth_color || + input.ext_shirt_color + ) { + // this is definitely mii creator data + data.originPlatform = MiiCreatorOriginPlatform.Mii_Creator_v3; + } + // mii creator file format ver 3 stores missing common colors with value "0" which is bad, so fallback to ffl color as how miic v3 did it. + data.authorId = input.author_id.data; + data.beardColor = + input.ext_beard_color || Ver3HairColorTable[input.beard_color]; + data.beardType = input.beard_type; + data.birthDay = input.birth_day; + data.birthMonth = input.birth_month; + data.build = input.build; + data.createId = FFLiCreateID.pack(input.create_id); + data.creator = input.creator; + data.eyeAspect = input.eye_aspect; + data.eyebrowAspect = input.eyebrow_aspect; + data.eyebrowColor = + input.ext_eyebrow_color || Ver3HairColorTable[input.eyebrow_color]; + data.eyebrowRotate = input.eyebrow_rotate; + data.eyebrowScale = input.eyebrow_scale; + data.eyebrowType = input.eyebrow_type; + data.eyebrowX = input.eyebrow_x; + data.eyebrowY = input.eyebrow_y; + data.eyeColor = input.ext_eye_color || Ver3EyeColorTable[input.eye_color]; + data.eyeRotate = input.eye_rotate; + data.eyeScale = input.eye_scale; + data.eyeType = input.eye_type; + data.eyeX = input.eye_x; + data.eyeY = input.eye_y; + data.facelineColor = input.face_color; + data.facelineMake = input.face_make; + data.facelineType = input.face_type; + data.facelineWrinkle = input.face_tex; + data.facePaintColor = input.ext_face_paint_color - 1 || -1; + data.favorite = input.favorite; + data.favoriteColor = input.favorite_color; + data.fontRegion = input.font_region; + data.gender = input.gender; + data.glassColor = + input.ext_glass_color || Ver3GlassColorTable[input.glasses_color]; + data.glassScale = input.glasses_scale; + data.glassType = input.ext_glass_type || input.glasses_type; + data.glassY = input.glass_y; + data.hairColor = input.ext_hair_color || Ver3HairColorTable[input.hair_color]; + data.hairFlip = input.hair_flip; + data.hairType = input.hair_type; + data.hatFavoriteColor = + input.ext_hat_color !== 0 ? input.ext_hat_color - 1 : -1; + data.hatType = input.ext_hat_type !== 0 ? input.ext_hat_type - 1 : -1; + data.height = input.height; + data.moleScale = input.mole_scale; + data.moleType = input.mole_type; + data.moleX = input.mole_x; + data.moleY = input.mole_y; + data.mouthAspect = input.mouth_aspect; + data.mouthColor = + input.ext_mouth_color || Ver3MouthColorTable[input.mouth_color]; + data.mouthScale = input.mouth_scale; + data.mouthType = input.mouth_type; + data.mouthY = input.mouth_y; + data.mustacheScale = input.beard_scale; + data.mustacheType = input.mustache_type; + data.mustacheY = input.beard_y; + data.nickname = input.name; + data.noseScale = input.nose_scale; + data.noseType = input.nose_type; + data.noseY = input.nose_y; + data.regionMove = input.region_move; + if (input.create_id.flag_temporary !== 0) + data.special = Number(!input.create_id.flag_normal); + data.temporary = Number(input.create_id.flag_temporary); + + return data; +} diff --git a/src/class/struct/MiiCreatorV4Data.ts b/src/class/struct/MiiCreatorV4Data.ts new file mode 100644 index 0000000..14a487d --- /dev/null +++ b/src/class/struct/MiiCreatorV4Data.ts @@ -0,0 +1,611 @@ +import _ from "../../external/ffl.js/struct-fu"; +import type { StructInstance } from "../../external/ffl.js/struct-fu"; +import { RFLStoreData } from "./RFLStoreData"; +import { + calculateCRC16, + FFLiAuthorID, + FFLiCreateID, + Ver3StoreData +} from "./FFLStoreData"; +import { + ToVer3EyeColorTable, + ToVer3FacelineColorTable, + ToVer3GlassColorTable, + ToVer3GlassTypeTable, + ToVer3HairColorTable, + ToVer3MouthColorTable +} from "../../constants/ColorTables"; +import { PropType, type Prop } from "./Props"; + +export const MiiCreatorV4Data = _.struct([ + _.uint8("miicVersion"), + _.uint8("originPlatform"), + _.byte("authorId", 8), + _.byte("createId", 10), + _.char16le("creator", 20), + _.char16le("nickname", 20), + _.uint8("beardColor"), + _.uint8("beardType"), + _.uint8("birthDay"), + _.uint8("birthMonth"), + _.uint16("birthYear"), + _.uint8("build"), + _.uint8("eyeAspect"), + _.uint8("eyebrowAspect"), + _.uint8("eyebrowColor"), + _.uint8("eyebrowRotate"), + _.uint8("eyebrowScale"), + _.uint8("eyebrowType"), + _.uint8("eyebrowX"), + _.uint8("eyebrowY"), + _.uint8("eyeColor"), + _.uint8("eyeRotate"), + _.uint8("eyeScale"), + _.uint8("eyeType"), + _.uint8("eyeX"), + _.uint8("eyeY"), + _.uint8("facelineColor"), + _.uint8("facelineMake"), + _.uint8("facelineType"), + _.uint8("facelineWrinkle"), + _.uint8("facePaintColor"), + _.uint8("favorite"), + _.uint8("favoriteColor"), + _.uint8("fontRegion"), + _.uint8("gender"), + _.uint8("glassColor"), + _.uint8("glassScale"), + _.uint8("glassType"), + _.uint8("glassY"), + _.uint8("hairColor"), + _.uint8("hairFlip"), + _.uint8("hairType"), + _.uint8("hatFavoriteColor"), + _.uint8("hatCommonColor"), + _.uint8("hatType"), + _.uint8("height"), + _.uint8("wigType"), + _.uint8("moleScale"), + _.uint8("moleType"), + _.uint8("moleX"), + _.uint8("moleY"), + _.uint8("mouthAspect"), + _.uint8("mouthColor"), + _.uint8("mouthScale"), + _.uint8("mouthType"), + _.uint8("mouthY"), + _.uint8("mustacheScale"), + _.uint8("mustacheType"), + _.uint8("mustacheY"), + _.uint8("noseScale"), + _.uint8("noseType"), + _.uint8("noseY"), + _.uint8("pantsColor"), + _.uint8("personality"), + _.uint8("regionMove"), + _.uint8("shirtColor"), + _.uint8("special"), + _.uint8("temporary"), + _.uint8("eyeSclera"), + _.uint8("clothesType"), + _.uint8("shoesColor") +]) as StructInstance; + +export const MiiCreatorV4AppendData = _.struct([ + _.uint8("miicVersion"), + + // common colors + _.uint8("eyebrowColor"), + _.uint8("eyeColor"), + _.uint8("facelineColor"), + _.uint8("glassColor"), + _.uint8("glassType"), + _.uint8("hairColor"), + _.uint8("mouthColor"), + + // miic specific fields + _.uint8("hatType"), + _.uint8("facePaintColor"), + _.uint8("hatCommonColor"), + _.uint8("hatFavoriteColor"), + _.uint8("pantsColor"), + _.uint8("personality"), + _.uint8("shirtColor"), + _.uint8("birthYear"), + _.uint8("wigType"), // unused + _.uint8("originPlatform"), // unused + _.uint8("eyeSclera"), + _.uint8("clothesType"), + _.uint8("shoesColor") +]) as StructInstance; + +export type MiiCreatorV4Data = { + miicVersion: number; + originPlatform: number; + authorId: Uint8Array; + createId: Uint8Array; + creator: string; + nickname: string; + beardColor: number; + beardType: number; + birthDay: number; + birthMonth: number; + birthYear: number; + build: number; + eyeAspect: number; + eyebrowAspect: number; + eyebrowColor: number; + eyebrowRotate: number; + eyebrowScale: number; + eyebrowType: number; + eyebrowX: number; + eyebrowY: number; + eyeColor: number; + eyeRotate: number; + eyeScale: number; + eyeType: number; + eyeX: number; + eyeY: number; + facelineColor: number; + facelineMake: number; + facelineType: number; + facelineWrinkle: number; + facePaintColor: number; + favorite: number; + favoriteColor: number; + fontRegion: number; + gender: number; + glassColor: number; + glassScale: number; + glassType: number; + glassY: number; + hairColor: number; + hairFlip: number; + hairType: number; + hatFavoriteColor: number; + hatCommonColor: number; + hatType: number; + height: number; + wigType: number; + moleScale: number; + moleType: number; + moleX: number; + moleY: number; + mouthAspect: number; + mouthColor: number; + mouthScale: number; + mouthType: number; + mouthY: number; + mustacheScale: number; + mustacheType: number; + mustacheY: number; + noseScale: number; + noseType: number; + noseY: number; + pantsColor: number; + personality: number; + regionMove: number; + shirtColor: number; + special: number; + temporary: number; + eyeSclera: number; + clothesType: number; + shoesColor: number; +}; + +export enum MiiCreatorOriginPlatform { + Unknown = -1, + RFL_Wii = 0, + NFL_DS = 1, + CFL_3DS = 2, + FFL_Wii_U = 3, + nn_mii_Switch = 4, + Mii_Creator_v3 = 5, + Mii_Creator_v4 = 5, + Origin_Platform_Max = 6 +} + +// Uninitialized values will be -1 +const EmptyMiiCreatorData: MiiCreatorV4Data = { + miicVersion: 4, + originPlatform: MiiCreatorOriginPlatform.Mii_Creator_v4, + authorId: new Uint8Array(8), + createId: new Uint8Array(10), + creator: "???", + nickname: "MISSING", + beardColor: 0, + beardType: 0, + birthDay: 0, + birthMonth: 0, + birthYear: 0, + build: 0, + eyebrowAspect: 3, + eyebrowColor: 0, + eyebrowRotate: 0, + eyebrowScale: 0, + eyebrowType: 0, + eyebrowX: 0, + eyebrowY: 0, + eyeAspect: 3, + eyeColor: 0, + eyeRotate: 0, + eyeScale: 0, + eyeType: 0, + eyeX: 0, + eyeY: 0, + facelineColor: 0, + facelineMake: 0, + facelineType: 0, + facelineWrinkle: 0, + facePaintColor: -1, + favorite: 0, + favoriteColor: 0, + fontRegion: 0, + gender: 0, + glassColor: 0, + glassScale: 0, + glassType: 0, + glassY: 0, + hairColor: 0, + hairFlip: 0, + hairType: 0, + hatFavoriteColor: -1, + hatCommonColor: -1, + hatType: -1, + height: 0, + wigType: -1, + moleScale: 0, + moleType: 0, + moleX: 0, + moleY: 0, + mouthAspect: 3, + mouthColor: 0, + mouthScale: 0, + mouthType: 0, + mouthY: 0, + mustacheScale: 0, + mustacheType: 0, + mustacheY: 0, + noseScale: 0, + noseType: 0, + noseY: 0, + pantsColor: -1, + personality: -1, + regionMove: 0, + shirtColor: -1, + special: 0, + temporary: 0, + eyeSclera: 0, + clothesType: -1, + shoesColor: -1 +}; +export const EmptyMiiCreatorV4Data = () => ({ ...EmptyMiiCreatorData }); + +// functions to convert mii creator v4 data into other formats + +// idk what this is +export function MiiCreatorV4DataToFFSD( + input: MiiCreatorV4Data, + pack: B, + appendBytes?: boolean +): B extends true ? Uint8Array : Ver3StoreData; + +export function MiiCreatorV4DataToFFSD( + input: MiiCreatorV4Data, + pack: boolean = false, + appendBytes: boolean = false +): Uint8Array | Ver3StoreData { + // TODO + + const output: Partial = { + author_id: FFLiAuthorID.unpack(input.authorId), + author_type: 0, + beard_color: ToVer3HairColorTable[input.beardColor], + beard_scale: input.mustacheScale, + beard_type: input.beardType, + beard_y: input.mustacheY, + birth_day: input.birthDay, + birth_month: input.birthMonth, + birth_platform: Math.max( + 2, + Math.min(input.originPlatform, MiiCreatorOriginPlatform.FFL_Wii_U) + ), + build: input.build, + checksum: 0, + copyable: 1, + create_id: FFLiCreateID.unpack(input.createId), + creator: input.creator, + eye_aspect: input.eyeAspect, + eye_color: ToVer3EyeColorTable[input.eyeColor], + eye_rotate: input.eyeRotate, + eye_scale: input.eyeScale, + eye_type: input.eyeType, + eye_x: input.eyeX, + eye_y: input.eyeY, + eyebrow_aspect: input.eyebrowAspect, + eyebrow_color: ToVer3HairColorTable[input.eyebrowColor], + eyebrow_rotate: input.eyebrowRotate, + eyebrow_scale: input.eyebrowScale, + eyebrow_type: input.eyebrowType, + eyebrow_x: input.eyebrowX, + eyebrow_y: input.eyebrowY, + face_color: ToVer3FacelineColorTable[input.facelineColor], + face_make: input.facelineMake, + face_tex: input.facelineWrinkle, + face_type: input.facelineType, + favorite: input.favorite, + favorite_color: input.favoriteColor, + font_region: input.fontRegion, + gender: input.gender, + glass_y: input.glassY, + glasses_color: ToVer3GlassColorTable[input.glassColor], + glasses_scale: input.glassScale, + glasses_type: ToVer3GlassTypeTable[input.glassType], + hair_color: ToVer3HairColorTable[input.hairColor], + hair_flip: input.hairFlip, + hair_type: input.hairType, + height: input.height, + localonly: 0, + mii_version: MiiCreatorOriginPlatform.FFL_Wii_U, + mole_scale: input.moleScale, + mole_type: input.moleType, + mole_x: input.moleX, + mole_y: input.moleY, + mouth_aspect: input.mouthAspect, + mouth_color: ToVer3MouthColorTable[input.mouthColor], + mouth_scale: input.mouthScale, + mouth_type: input.mouthType, + mouth_y: input.mouthY, + mustache_type: input.mustacheType, + name: input.nickname, + ng_word: 0, + nose_scale: input.noseScale, + nose_type: input.noseType, + nose_y: input.noseY, + // padding is skipped + // room info not really needed + position_in_room: 0, + room_index: 0, + region_move: 0 + }; + + // Set special flag based on if special or not. + output.create_id!.flag_normal = Number(!input.special); + + output.checksum = calculateCRC16(Ver3StoreData.pack(output as Ver3StoreData)); + + if (pack) { + if (appendBytes) { + const ffsdOutput = Ver3StoreData.pack(output as Ver3StoreData); + const appendedBytes = MiiCreatorV4AppendData.pack(input); + + const finalArray = new Uint8Array( + ffsdOutput.length + appendedBytes.length + ); + finalArray.set(ffsdOutput, 0); + finalArray.set(appendedBytes, ffsdOutput.length); + return finalArray; + } + return Ver3StoreData.pack(output as Ver3StoreData); + } else return output as Ver3StoreData; +} + +// Tables provided by David J. (thanks!) +export const Ver3FaceTypeToVer1 = [0, 1, 2, 3, 4, 5, 6, 7, 2, 1, 4, 7]; +export const Ver3FaceMakeToVer1FaceTex = [0, 1, 2, 2, 3, 2, 2, 3, 3]; +export const Ver3FaceWrinkleToVer1FaceTex = [0, 1, 2, 2, 3, 2, 2, 3, 3]; + +export function MiiCreatorV4DataToRSD( + input: MiiCreatorV4Data, + pack: boolean = false +) { + const output: RFLStoreData = { + beardColor: input.beardColor, + beardScale: input.mustacheScale, + beardType: input.beardType, + beardY: input.mustacheY, + birthDay: input.birthDay, + birthMonth: input.birthMonth, + build: input.build, + checksum: 0, + create_id: input.createId, + creatorName: input.creator, + eyebrowColor: input.eyebrowColor, + eyebrowRotate: input.eyebrowRotate, + eyebrowScale: input.eyebrowScale, + eyebrowType: input.eyebrowType, + eyebrowX: input.eyebrowX, + eyebrowY: input.eyebrowY, + eyeColor: input.eyeColor, + eyeRotate: input.eyeRotate, + eyeScale: input.eyeScale, + eyeType: input.eyeType, + eyeX: input.eyeX, + eyeY: input.eyeY, + faceColor: input.facelineColor, + faceTex: input.facelineMake, + faceType: input.facelineType, + favorite: input.favorite, + favoriteColor: input.favoriteColor, + gender: input.gender, + glassColor: input.glassColor, + glassScale: input.glassScale, + glassType: input.glassType, + glassY: input.glassY, + hairColor: input.hairColor, + hairFlip: input.hairFlip, + hairType: input.hairType, + height: input.height, + localonly: 0, + moleScale: input.moleScale, + moleType: input.moleType, + moleX: input.moleX, + moleY: input.moleY, + mouthColor: input.mouthColor, + mouthScale: input.mouthScale, + mouthType: input.mouthType, + mouthY: input.mouthY, + mustacheType: input.mustacheType, + name: input.nickname, + noseScale: input.noseScale, + noseType: input.noseScale, + noseY: input.noseY, + padding0: 0, + padding_2: 0, + padding_3: 0, + padding_4: 0, + padding_5: 0, + padding_6: 0, + padding_8: 0, + type: 0 // ??? + }; + if (pack) return RFLStoreData.pack(output); + else return output; +} + +export const validationThing: Partial> = { + beardColor: { type: PropType.Number, default: 0, min: 0, max: 99 }, + beardType: { type: PropType.Number, default: 0, min: 0, max: 5 }, + build: { type: PropType.Number, default: 64, min: 0, max: 127 }, + eyeAspect: { type: PropType.Number, default: 3, min: 0, max: 6 }, + eyeColor: { type: PropType.Number, default: 8, min: 0, max: 99 }, + eyeRotate: { type: PropType.Number, default: 4, min: 0, max: 7 }, + eyeScale: { type: PropType.Number, default: 4, min: 0, max: 7 }, + eyeSclera: { type: PropType.Number, default: 0, min: 0, max: 1 }, + eyeType: { type: PropType.Number, default: 2, min: 0, max: 59 }, + eyeX: { type: PropType.Number, default: 2, min: 0, max: 12 }, + eyeY: { type: PropType.Number, default: 12, min: 0, max: 18 }, + eyebrowAspect: { type: PropType.Number, default: 3, min: 0, max: 6 }, + eyebrowColor: { type: PropType.Number, default: 1, min: 0, max: 99 }, + eyebrowRotate: { type: PropType.Number, default: 6, min: 0, max: 11 }, + eyebrowScale: { type: PropType.Number, default: 4, min: 0, max: 8 }, + eyebrowType: { type: PropType.Number, default: 6, min: 0, max: 24 }, + eyebrowX: { type: PropType.Number, default: 2, min: 0, max: 12 }, + eyebrowY: { type: PropType.Number, default: 10, min: 3, max: 18 }, + facelineColor: { type: PropType.Number, default: 0, min: 0, max: 9 }, + facelineMake: { type: PropType.Number, default: 0, min: 0, max: 11 }, + facelineType: { type: PropType.Number, default: 0, min: 0, max: 11 }, + facelineWrinkle: { type: PropType.Number, default: 0, min: 0, max: 11 }, + favoriteColor: { type: PropType.Number, default: 0, min: 0, max: 11 }, + fontRegion: { type: PropType.Number, default: 0, min: 0, max: 3 }, + gender: { type: PropType.Number, default: 0, min: 0, max: 1 }, + glassColor: { type: PropType.Number, default: 8, min: 0, max: 99 }, + glassScale: { type: PropType.Number, default: 4, min: 0, max: 7 }, + glassType: { type: PropType.Number, default: 0, min: 0, max: 19 }, + glassY: { type: PropType.Number, default: 10, min: 0, max: 20 }, + hairColor: { type: PropType.Number, default: 1, min: 0, max: 99 }, + hairFlip: { type: PropType.Number, default: 0, min: 0, max: 1 }, + hairType: { type: PropType.Number, default: 33, min: 0, max: 131 }, + height: { type: PropType.Number, default: 64, min: 0, max: 127 }, + miicVersion: { type: PropType.Number, default: 4, min: 0, max: 4 }, + moleScale: { type: PropType.Number, default: 4, min: 0, max: 8 }, + moleType: { type: PropType.Number, default: 0, min: 0, max: 1 }, + moleX: { type: PropType.Number, default: 2, min: 0, max: 16 }, + moleY: { type: PropType.Number, default: 20, min: 0, max: 30 }, + mouthAspect: { type: PropType.Number, default: 3, min: 0, max: 6 }, + mouthColor: { type: PropType.Number, default: 19, min: 0, max: 99 }, + mouthScale: { type: PropType.Number, default: 4, min: 0, max: 8 }, + mouthType: { type: PropType.Number, default: 23, min: 0, max: 35 }, + mouthY: { type: PropType.Number, default: 13, min: 0, max: 18 }, + mustacheScale: { type: PropType.Number, default: 4, min: 0, max: 8 }, + mustacheType: { type: PropType.Number, default: 0, min: 0, max: 5 }, + mustacheY: { type: PropType.Number, default: 10, min: 0, max: 16 }, + creator: { type: PropType.String, default: "", min: 0, max: 10 }, + nickname: { type: PropType.String, default: "Mii", min: 1, max: 10 }, + noseScale: { type: PropType.Number, default: 4, min: 0, max: 8 }, + noseType: { type: PropType.Number, default: 1, min: 0, max: 17 }, + noseY: { type: PropType.Number, default: 9, min: 0, max: 18 }, + regionMove: { type: PropType.Number, default: 0, min: 0, max: 3 }, + + // mii creator v4 specific features + authorId: { + type: PropType.Array, + default: [0, 0, 0, 0, 0, 0, 0, 0], + size: 8, + min: 0, + max: 255 + }, + birthDay: { type: PropType.Number, default: 0, min: 0, max: 31 }, + birthMonth: { type: PropType.Number, default: 0, min: 0, max: 12 }, + birthYear: { type: PropType.Number, default: 0, min: 0, max: 9999 }, + createId: { + type: PropType.Array, + default: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + size: 10, + min: 0, + max: 255 + }, + facePaintColor: { type: PropType.Number, default: -1, min: -1, max: 99 }, + favorite: { type: PropType.Number, default: 0, min: 0, max: 1 }, + hatCommonColor: { type: PropType.Number, default: -1, min: -1, max: 99 }, + hatFavoriteColor: { type: PropType.Number, default: -1, min: -1, max: 99 }, + hatType: { type: PropType.Number, default: -1, min: -1, max: 9 }, + wigType: { type: PropType.Number, default: -1, min: -1, max: 254 }, + clothesType: { type: PropType.Number, default: -1, min: -1, max: 254 }, + shoesColor: { type: PropType.Number, default: -1, min: -1, max: 99 }, + originPlatform: { + type: PropType.Number, + default: MiiCreatorOriginPlatform.Mii_Creator_v4, + min: 0, + max: MiiCreatorOriginPlatform.Origin_Platform_Max + }, + pantsColor: { type: PropType.Number, default: -1, min: -1, max: 99 }, + personality: { type: PropType.Number, default: -1, min: -1, max: 255 }, + shirtColor: { type: PropType.Number, default: -1, min: -1, max: 99 }, + special: { type: PropType.Number, default: 0, min: 0, max: 1 }, + temporary: { type: PropType.Number, default: 0, min: 0, max: 1 } +}; + +export function validate(input: MiiCreatorV4Data) { + let valid = true, + reasons: string[] = []; + + (Object.keys(input) as (keyof MiiCreatorV4Data)[]).forEach((i) => { + function fail(reason: string = i) { + valid = false; + reasons.push(reason); + } + const prop = validationThing[i]!; + + if (!prop) { + alert("A prop is missing: " + i); + return; + } + + // switch (prop.type) { + // case PropType.Number: { + // const value = input[i] as number; + // if (value < prop.min) fail(`${i} (${value}) is below minimum value`); + // if (value > prop.max) fail(`${i} (${value}) is above maximum value`); + // break; + // } + // case PropType.String: { + // const value = input[i] as string; + // if (value.trim().length < prop.min) + // fail(`${i} (${value}) is below minimum length`); + // if (value.trim().length > prop.max) + // fail(`${i} (${value}) is above maximum length`); + // break; + // } + // case PropType.Array: { + // // console.log("this isn't supported yet"); + // const value = input[i] as Uint8Array; + // if (value.length !== prop.size) + // fail(`${i} size is ${value.length}, expected ${prop.size}`); + + // // no idea what this is for if uint8arrays can only store bytes... + // // this also might fix if the array is tampered with + // if ( + // Array.from(value).every((i) => i >= prop.min && i <= prop.max) === + // false + // ) + // fail(); + // break; + // } + // } + }); + + if (valid) reasons.push("Valid"); + + return { valid, reasons }; +} diff --git a/src/class/struct/NnMiiCharInfo.ts b/src/class/struct/NnMiiCharInfo.ts new file mode 100644 index 0000000..951f173 --- /dev/null +++ b/src/class/struct/NnMiiCharInfo.ts @@ -0,0 +1,114 @@ +import _ from "../../external/ffl.js/struct-fu"; +import type { StructInstance } from "../../external/ffl.js/struct-fu"; + +export const NnMiiCharInfo = _.struct([ + _.byte("createId", 16), + /* null terminated */ + _.char16le("nickname", 22), + _.uint8("fontRegion"), + _.uint8("favoriteColor"), + _.uint8("gender"), + _.uint8("height"), + _.uint8("build"), + /* special or not */ + _.uint8("type"), + _.uint8("regionMove"), + _.uint8("facelineType"), + _.uint8("facelineColor"), + _.uint8("facelineWrinkle"), + _.uint8("facelineMake"), + _.uint8("hairType"), + _.uint8("hairColor"), + _.uint8("hairFlip"), + _.uint8("eyeType"), + _.uint8("eyeColor"), + _.uint8("eyeScale"), + _.uint8("eyeAspect"), + _.uint8("eyeRotate"), + _.uint8("eyeX"), + _.uint8("eyeY"), + _.uint8("eyebrowType"), + _.uint8("eyebrowColor"), + _.uint8("eyebrowScale"), + _.uint8("eyebrowAspect"), + _.uint8("eyebrowRotate"), + _.uint8("eyebrowX"), + _.uint8("eyebrowY"), + _.uint8("noseType"), + _.uint8("noseScale"), + _.uint8("noseY"), + _.uint8("mouthType"), + _.uint8("mouthColor"), + _.uint8("mouthScale"), + _.uint8("mouthAspect"), + _.uint8("mouthY"), + _.uint8("beardColor"), + _.uint8("beardType"), + _.uint8("mustacheType"), + _.uint8("mustacheScale"), + _.uint8("mustacheY"), + _.uint8("glassType"), + _.uint8("glassColor"), + _.uint8("glassScale"), + _.uint8("glassY"), + _.uint8("moleType"), + _.uint8("moleScale"), + _.uint8("moleX"), + _.uint8("moleY"), + /* always zero */ + _.uint8("reserved") +]) as StructInstance; +export type NnMiiCharInfo = { + createId: Uint8Array; + nickname: string; + fontRegion: number; + favoriteColor: number; + gender: number; + height: number; + build: number; + type: number; + regionMove: number; + facelineType: number; + facelineColor: number; + facelineWrinkle: number; + facelineMake: number; + hairType: number; + hairColor: number; + hairFlip: number; + eyeType: number; + eyeColor: number; + eyeScale: number; + eyeAspect: number; + eyeRotate: number; + eyeX: number; + eyeY: number; + eyebrowType: number; + eyebrowColor: number; + eyebrowScale: number; + eyebrowAspect: number; + eyebrowRotate: number; + eyebrowX: number; + eyebrowY: number; + noseType: number; + noseScale: number; + noseY: number; + mouthType: number; + mouthColor: number; + mouthScale: number; + mouthAspect: number; + mouthY: number; + beardColor: number; + beardType: number; + mustacheType: number; + mustacheScale: number; + mustacheY: number; + glassType: number; + glassColor: number; + glassScale: number; + glassY: number; + moleType: number; + moleScale: number; + moleX: number; + moleY: number; + reserved: number; +}; diff --git a/src/class/struct/Props.ts b/src/class/struct/Props.ts new file mode 100644 index 0000000..2811d4a --- /dev/null +++ b/src/class/struct/Props.ts @@ -0,0 +1,34 @@ +export enum PropType { + Number, + String, + Array +} + +export type Prop = NumberProp | StringProp | ArrayProp; +export type PropTable = Record; + +export type NumberProp = { + type: PropType.Number; + name?: string; + default?: number; + min: number; + max: number; + condition?: (value: number) => any; +}; +export type StringProp = { + type: PropType.String; + name?: string; + default?: string; + min: number; + max: number; + condition?: (value: string) => any; +}; +export type ArrayProp = { + type: PropType.Array; + name?: string; + default?: number[]; + size: number; + min: number; + max: number; + condition?: (value: any[]) => any; +}; diff --git a/src/class/struct/RFLStoreData.ts b/src/class/struct/RFLStoreData.ts new file mode 100644 index 0000000..f4030da --- /dev/null +++ b/src/class/struct/RFLStoreData.ts @@ -0,0 +1,247 @@ +import _ from "../../external/ffl.js/struct-fu"; +import type { StructInstance } from "../../external/ffl.js/struct-fu"; +import { + EmptyMiiCreatorV4Data, + type MiiCreatorV4Data +} from "./MiiCreatorV4Data"; +import { + Ver3EyeColorTable, + Ver3FacelineColorTable, + Ver3GlassColorTable, + Ver3HairColorTable, + Ver3MouthColorTable +} from "../../constants/ColorTables"; + +export const RFLCreateID = _.struct([_.uint8("data", 8)]) as StructInstance<{ + data: Uint8Array; +}>; + +// example RCD +// 2A8A0062000000000000000000000000000000000000005AC00053D9A611223320047900694008C3486D8C58007298AB008A008A25040061000000000000000000000000000000000000 + +export const RFLCharData = _.struct([ + _.ubit("padding0", 1), + _.ubit("gender", 1), + _.ubit("birthMonth", 4), + _.ubit("birthDay", 5), + _.ubit("favoriteColor", 4), + _.ubit("favorite", 1), + _.char16be("name", 0x14), + + _.uint8("height"), + _.uint8("build"), + _.struct("create_id", [RFLCreateID]), + + _.ubit("faceType", 3), + + _.ubit("faceColor", 3), + _.ubit("faceTex", 4), + _.ubit("padding_2", 3), + _.ubit("localonly", 1), + _.ubit("type", 2), + + _.ubit("hairType", 7), + _.ubit("hairColor", 3), + _.ubit("hairFlip", 1), + _.ubit("padding_3", 5), + + _.ubit("eyebrowType", 5), + _.ubit("eyebrowRotate", 5), + _.ubit("padding_4", 6), + + _.ubit("eyebrowColor", 3), + _.ubit("eyebrowScale", 4), + _.ubit("eyebrowY", 5), + _.ubit("eyebrowX", 4), + + _.ubit("eyeType", 6), + _.ubit("eyeRotate", 5), + _.ubit("eyeY", 5), + + _.ubit("eyeColor", 3), + _.ubit("eyeScale", 4), + _.ubit("eyeX", 4), + _.ubit("padding_5", 5), + + _.ubit("noseType", 4), + _.ubit("noseScale", 4), + _.ubit("noseY", 5), + _.ubit("padding_6", 3), + + _.ubit("mouthType", 5), + _.ubit("mouthColor", 2), + _.ubit("mouthScale", 4), + _.ubit("mouthY", 5), + + _.ubit("glassType", 4), + _.ubit("glassColor", 3), + _.ubit("glassScale", 4), + _.ubit("glassY", 5), + + _.ubit("mustacheType", 2), + _.ubit("beardType", 2), + _.ubit("beardColor", 3), + _.ubit("beardScale", 4), + _.ubit("beardY", 5), + + _.ubit("moleType", 1), + _.ubit("moleScale", 4), + _.ubit("moleY", 5), + _.ubit("moleX", 5), + _.ubit("padding_8", 1), + + _.char16be("creatorName", 0x14) +]) as StructInstance; + +export const RFLStoreData = _.struct([ + _.struct([RFLCharData]), + _.uint16("checksum") +]) as StructInstance; + +export interface RFLStoreData extends RFLCharData { + checksum: number; +} +export type RFLCharData = { + padding0: number; + gender: number; + birthMonth: number; + birthDay: number; + favoriteColor: number; + favorite: number; + name: string; + height: number; + build: number; + create_id: any; + faceType: number; + faceColor: number; + faceTex: number; + padding_2: number; + localonly: number; + type: number; + hairType: number; + hairColor: number; + hairFlip: number; + padding_3: number; + eyebrowType: number; + eyebrowRotate: number; + padding_4: number; + eyebrowColor: number; + eyebrowScale: number; + eyebrowY: number; + eyebrowX: number; + eyeType: number; + eyeRotate: number; + eyeY: number; + eyeColor: number; + eyeScale: number; + eyeX: number; + padding_5: number; + noseType: number; + noseScale: number; + noseY: number; + padding_6: number; + mouthType: number; + mouthColor: number; + mouthScale: number; + mouthY: number; + glassType: number; + glassColor: number; + glassScale: number; + glassY: number; + mustacheType: number; + beardType: number; + beardColor: number; + beardScale: number; + beardY: number; + moleType: number; + moleScale: number; + moleY: number; + moleX: number; + padding_8: number; + creatorName: string; +}; + +// david picked by hand but should work +export const Ver1ToVer3FacelineTex = [ + [0, 0], + [1, 0], + [6, 0], + [9, 0], + [0, 5], + [0, 2], + [0, 3], + [0, 7], + [0, 8], + [10, 0], + [0, 9], + [0, 11] +]; + +export function RFLStoreDataToMiiCreatorV4Data( + input: RFLStoreData +): MiiCreatorV4Data { + const output: MiiCreatorV4Data = EmptyMiiCreatorV4Data(); + console.log("input rfl data:", input); + output.beardColor = Ver3HairColorTable[input.beardColor]; + output.beardType = input.beardType; + output.birthDay = input.birthDay; + output.birthMonth = input.birthMonth; + output.build = input.build; + output.createId.set(RFLCreateID.pack(input.create_id), 0); + output.creator = input.creatorName; + output.eyeColor = Ver3EyeColorTable[input.eyeColor]; + output.eyeRotate = input.eyeRotate; + output.eyeScale = input.eyeScale; + output.eyeType = input.eyeType; + output.eyeX = input.eyeX; + output.eyeY = input.eyeY; + output.eyebrowColor = Ver3HairColorTable[input.eyebrowColor]; + output.eyebrowRotate = input.eyebrowRotate; + output.eyebrowScale = input.eyebrowScale; + output.eyebrowType = input.eyebrowType; + output.eyebrowX = input.eyebrowX; + output.eyebrowY = input.eyebrowY; + output.facelineColor = Ver3FacelineColorTable[input.faceColor]; + output.facelineType = input.faceType; + output.facelineMake = Ver1ToVer3FacelineTex[input.faceTex][0]; + output.facelineWrinkle = Ver1ToVer3FacelineTex[input.faceTex][1]; + output.favorite = input.favorite; + output.favoriteColor = input.favoriteColor; + output.gender = input.gender; + output.glassColor = Ver3GlassColorTable[input.glassColor]; + output.glassScale = input.glassScale; + output.glassType = input.glassType; + output.glassY = input.glassY; + output.hairColor = Ver3HairColorTable[input.hairColor]; + output.hairFlip = input.hairFlip; + output.hairType = input.hairType; + output.height = input.height; + output.moleScale = input.moleScale; + output.moleType = input.moleType; + output.moleX = input.moleX; + output.moleY = input.moleY; + output.mouthColor = Ver3MouthColorTable[input.mouthColor]; + output.mouthScale = input.mouthScale; + output.mouthType = input.mouthType; + output.mouthY = input.mouthY; + output.mustacheScale = input.beardScale; + output.mustacheType = input.mustacheType; + output.mustacheY = input.beardY; + output.noseScale = input.noseScale; + output.noseType = input.noseType; + output.noseY = input.noseY; + output.nickname = input.name; + output.creator = input.creatorName; + + // miic features + output.facePaintColor = -1; + output.hatCommonColor = -1; + output.hatFavoriteColor = -1; + output.hatType = -1; + output.wigType = -1; + output.pantsColor = -1; + output.personality = -1; + output.shirtColor = -1; + + return output; +} diff --git a/src/class/struct/StudioData.ts b/src/class/struct/StudioData.ts new file mode 100644 index 0000000..4177219 --- /dev/null +++ b/src/class/struct/StudioData.ts @@ -0,0 +1,100 @@ +import type { StructInstance } from "../../external/ffl.js/struct-fu"; +import _ from "../../external/ffl.js/struct-fu"; + +export const StudioData = _.struct([ + _.uint8("beardColor"), + _.uint8("beardType"), + _.uint8("build"), + _.uint8("eyeAspect"), + _.uint8("eyeColor"), + _.uint8("eyeRotate"), + _.uint8("eyeScale"), + _.uint8("eyeType"), + _.uint8("eyeX"), + _.uint8("eyeY"), + _.uint8("eyebrowAspect"), + _.uint8("eyebrowColor"), + _.uint8("eyebrowRotate"), + _.uint8("eyebrowScale"), + _.uint8("eyebrowType"), + _.uint8("eyebrowX"), + _.uint8("eyebrowY"), + _.uint8("facelineColor"), + _.uint8("facelineMake"), + _.uint8("facelineType"), + _.uint8("facelineWrinkle"), + _.uint8("favoriteColor"), + _.uint8("gender"), + _.uint8("glassColor"), + _.uint8("glassScale"), + _.uint8("glassType"), + _.uint8("glassY"), + _.uint8("hairColor"), + _.uint8("hairFlip"), + _.uint8("hairType"), + _.uint8("height"), + _.uint8("moleScale"), + _.uint8("moleType"), + _.uint8("moleX"), + _.uint8("moleY"), + _.uint8("mouthAspect"), + _.uint8("mouthColor"), + _.uint8("mouthScale"), + _.uint8("mouthType"), + _.uint8("mouthY"), + _.uint8("mustacheScale"), + _.uint8("mustacheType"), + _.uint8("mustacheY"), + _.uint8("noseScale"), + _.uint8("noseType"), + _.uint8("noseY") +]) as StructInstance; + +export type StudioData = { + beardColor: number; + beardType: number; + build: number; + eyeAspect: number; + eyeColor: number; + eyeRotate: number; + eyeScale: number; + eyeType: number; + eyeX: number; + eyeY: number; + eyebrowAspect: number; + eyebrowColor: number; + eyebrowRotate: number; + eyebrowScale: number; + eyebrowType: number; + eyebrowX: number; + eyebrowY: number; + facelineColor: number; + facelineMake: number; + facelineType: number; + facelineWrinkle: number; + favoriteColor: number; + gender: number; + glassColor: number; + glassScale: number; + glassType: number; + glassY: number; + hairColor: number; + hairFlip: number; + hairType: number; + height: number; + moleScale: number; + moleType: number; + moleX: number; + moleY: number; + mouthAspect: number; + mouthColor: number; + mouthScale: number; + mouthType: number; + mouthY: number; + mustacheScale: number; + mustacheType: number; + mustacheY: number; + noseScale: number; + noseType: number; + noseY: number; +}; diff --git a/src/config.ts b/src/config.ts index 93b063c..777b120 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,8 +1,15 @@ // Configuration file used client-side. +import { _ } from "./util/Lang"; + // Settings relating to local rendering. const useRendererServer = false; // Allow use of the renderer server (legacy rendering) -const fflResourcePath = "/FFLResHigh.dat"; // Configure the path for where the resource file is located. +const fflResourcePath = [ + "/FFLResLow.dat", + "/FFLResMiddle.dat", + "/FFLResHigh.dat" +]; // Configure the path for where the resource file is located. +const fflResourcesNames = ["Low", "Middle", "High"]; // Configure the path for where the resource file is located. // Instance of FFL-Testing/Mii Studio API compatible renderer. // const baseURL = "http://localhost:5000/miis/image"; // <-- Uncomment this when using local FFL-testing for development @@ -16,11 +23,14 @@ const newApiParams = true; // Details: https://github.com/ariankordi/nwf-mii-cemu-toy/blob/ffl-renderer-proto-integrate/README.md const nnidFetchOrigin = "https://mii-unsecure.ariankordi.net"; +const __ = _(); + export const Config = { renderer: { baseURL, useRendererServer, fflResourcePath, + fflResourcesNames, renderFFLMakeIcon: `${baseURL}.png?shaderType=miitomo&type=fflmakeicon&width=360&verifyCharInfo=0`, renderHeadshotURL: `${baseURL}.png?shaderType=wiiu&type=face&width=260&verifyCharInfo=0`, renderHeadshotURLNoParams: `${baseURL}.png`, @@ -36,7 +46,7 @@ export const Config = { hatColorAdd: newApiParams ? -1 : 0, // Enable/disable use of 3D mode in editor only - allow3DMode: true, + allow3DMode: true }, apis: { // For fetching data from various sources. @@ -46,23 +56,31 @@ export const Config = { pnidFetchURL: (pnid: string) => `${nnidFetchOrigin}/mii_data/${pnid}?api_id=1`, // Configure Sentry here. - useSentry: false, - sentryURL: "ENTER_SENTRY_URL_HERE", + useSentry: true, + // sentryURL: "ENTER_SENTRY_URL_HERE", + sentryURL: + "https://5671de45addd464980ccd49e08d6d108@app.glitchtip.com/10073" }, mii: { - scalingMode: "scaleApply", + scalingMode: "scaleApply" // ^^ scaleLimit, scaleLimitClampY, scaleApply }, version: { - string: "v0.9.3.1", - name: "Patch Update", + string: "v1.0.0 r1", + name: + // Current version string name ("Patch Update", "Minor Update", "Major Update") + // __("Major Update"), + __("BETA"), // ignore that I'm just writing HTML here changelog: ` +

The update changelog hasn't been written yet, so just ignore this for now

+ ` /*

v0.9.2 - QR Code and MiiC v3 Support

+
- +
Austin☆²¹ / Kat21
Let's go over the new changes!
@@ -188,6 +206,6 @@ export const Config = {

You can view this message again in Settings.

- `, - }, + `*/ + } }; diff --git a/src/constants/BodyShaderTypes.ts b/src/constants/BodyShaderTypes.ts index f3cba54..0bdf7e6 100644 --- a/src/constants/BodyShaderTypes.ts +++ b/src/constants/BodyShaderTypes.ts @@ -5,6 +5,7 @@ export enum BodyType { WiiU = "wiiu", Switch = "switch", Miitomo = "miitomo", + StreetPass = "streetpass" } // All body types are supported by backend renderer for now @@ -12,11 +13,13 @@ export enum ShaderType { WiiU = "wiiu", Switch = "switch", LightDisabled = "lightDisabled", - Simple = "none", Miitomo = "miitomo", + MiitomoBasic = "miitomo_basic", WiiUBlinn = "wiiu_blinn", WiiUFFLIconWithBody = "wiiu_ffliconwithbody", WiiUToon = "wiiu_toon", + ThreeToon = "three_toon", + ThreePhong = "three_phong" } export function adjustShaderQuery(params: URLSearchParams, shader: ShaderType) { @@ -34,7 +37,6 @@ export function adjustShaderQuery(params: URLSearchParams, shader: ShaderType) { params.set("shaderType", "wiiu"); break; case ShaderType.WiiUBlinn: - case ShaderType.Simple: params.set("shaderType", "wiiu_blinn"); break; case ShaderType.LightDisabled: diff --git a/src/constants/ColorTables.ts b/src/constants/ColorTables.ts index a5ffb6c..247cbdc 100644 --- a/src/constants/ColorTables.ts +++ b/src/constants/ColorTables.ts @@ -34,7 +34,7 @@ export const MiiFavoriteColorLookupTable: MiiLookupTableHex = { /** White */ 10: 0xe0e0e0, /** Black */ - 11: 0x181814, + 11: 0x181814 }; export const MiiFavoriteColorVec3Table: MiiLookupTableVec3 = { @@ -49,7 +49,7 @@ export const MiiFavoriteColorVec3Table: MiiLookupTableVec3 = { 8: [0.45098039215686275, 0.1568627450980392, 0.6784313725490196], 9: [0.2823529411764706, 0.2196078431372549, 0.09411764705882353], 10: [0.8784313725490196, 0.8784313725490196, 0.8784313725490196], - 11: [0.09411764705882353, 0.09411764705882353, 0.0784313725490196], + 11: [0.09411764705882353, 0.09411764705882353, 0.0784313725490196] }; export const MiiFavoriteColorIconTable: MiiLookupTableSpecial = { @@ -76,7 +76,7 @@ export const MiiFavoriteColorIconTable: MiiLookupTableSpecial = { /** White */ 10: { top: "#e0e0e0", bottom: "#696969" }, /** Black */ - 11: { top: "#181814", bottom: "#0b0b09" }, + 11: { top: "#181814", bottom: "#0b0b09" } }; export const MiiSkinColorTable: MiiLookupTableString = { @@ -89,7 +89,7 @@ export const MiiSkinColorTable: MiiLookupTableString = { 6: "#ffbea5", 7: "#ffc58f", 8: "#8c3c23", - 9: "#3c2d23", + 9: "#3c2d23" }; export const MiiHairColorTable: MiiLookupTableString = { 0: "#000000", @@ -99,7 +99,7 @@ export const MiiHairColorTable: MiiLookupTableString = { 4: "#787880", 5: "#4E3E11", 6: "#875917", - 7: "#D0A049", + 7: "#D0A049" }; export const MiiEyeColorTable: MiiLookupTableString = { 0: "#000000", @@ -107,21 +107,21 @@ export const MiiEyeColorTable: MiiLookupTableString = { 2: "#663C2C", 3: "#686537", 4: "#4B58A8", - 5: "#387059", + 5: "#387059" }; export const MiiMouthColorTable: MiiLookupTableString = { 0: "#D04401", 1: "#F30100", 2: "#FD393A", 3: "#F58862", - 4: "#1F1D1D", + 4: "#1F1D1D" }; export const MiiMouthColorLipTable: MiiLookupTableSpecial = { 0: { top: "#823018", bottom: "#D85209" }, 1: { top: "#780C0D", bottom: "#F00C09" }, 2: { top: "#882028", bottom: "#F54849" }, 3: { top: "#DC7751", bottom: "#F09A74" }, - 4: { top: "#461E0A", bottom: "#8C503F" }, + 4: { top: "#461E0A", bottom: "#8C503F" } }; export const MiiGlassesColorTable: MiiLookupTableString = { 0: "#000000", @@ -129,7 +129,7 @@ export const MiiGlassesColorTable: MiiLookupTableString = { 2: "#a01612", 3: "#2e3969", 4: "#a4601e", - 5: "#766f67", + 5: "#766f67" }; export const MiiGlassesColorIconTable: MiiLookupTableSpecial = { 0: { top: "#666666", bottom: "#606060" }, @@ -137,7 +137,7 @@ export const MiiGlassesColorIconTable: MiiLookupTableSpecial = { 2: { top: "#a01612", bottom: "#ff9d99" }, 3: { top: "#b5c0f0", bottom: "#b5c0f0" }, 4: { top: "#a4601e", bottom: "#ffe7a5" }, - 5: { top: "#766f67", bottom: "#fdf6ee" }, + 5: { top: "#766f67", bottom: "#fdf6ee" } }; export const SwitchMiiColorTable: MiiLookupTableColor = [ @@ -240,7 +240,7 @@ export const SwitchMiiColorTable: MiiLookupTableColor = [ "#9b9b9b", "#bebebe", "#dcd7cd", - "#ffffff", + "#ffffff" ]; export const SwitchMiiColorTableLip: MiiLookupTableColor = [ @@ -343,7 +343,7 @@ export const SwitchMiiColorTableLip: MiiLookupTableColor = [ "#7c7c7c", "#ababab", "#c6c1b6", - "#d9d9d9", + "#d9d9d9" ]; export const SwitchMiiColorTableSRGB: MiiLookupTableVec3 = [ @@ -446,110 +446,7 @@ export const SwitchMiiColorTableSRGB: MiiLookupTableVec3 = [ [0.6078432, 0.6078432, 0.6078432], [0.7450981, 0.7450981, 0.7450981], [0.8627451, 0.8431373, 0.8039216], - [1.0, 1.0, 1.0], -]; - -export const SwitchMiiColorTableLinear: MiiLookupTableVec3 = [ - [0.02624122, 0.02121902, 0.02121902], - [0.05126946, 0.01444384, 0.00518152], - [0.1070232, 0.00913407, 0.00303527], - [0.2015563, 0.04231142, 0.00699541], - [0.1878208, 0.1878208, 0.2158605], - [0.07618541, 0.04817184, 0.00518152], - [0.2462014, 0.09758739, 0.00913407], - [0.6307572, 0.3515327, 0.06847817], - [0.0, 0.0, 0.0], - [0.1499599, 0.1620294, 0.1620294], - [0.1328683, 0.04518623, 0.02518688], - [0.1169707, 0.1119325, 0.02955684], - [0.0612461, 0.08865561, 0.3915726], - [0.03954626, 0.1620294, 0.09758739], - [0.1169707, 0.03954626, 0.00518152], - [0.3915726, 0.00518152, 0.00242822], - [0.01444384, 0.02955684, 0.1384317], - [0.3915726, 0.1169707, 0.0], - [0.1878208, 0.1620294, 0.1384317], - [0.6866855, 0.08437625, 0.00242822], - [0.8713672, 0.00367651, 0.00242822], - [0.9130989, 0.0648033, 0.0648033], - [0.8713672, 0.3231433, 0.1746474], - [0.2622508, 0.08021983, 0.05126946], - [0.2307401, 0.01938238, 0.01938238], - [1.0, 0.1714411, 0.1328683], - [1.0, 0.3813261, 0.3813261], - [1.0, 0.5271152, 0.4910209], - [0.1714411, 0.0273209, 0.04373505], - [0.3185468, 0.0137021, 0.04666509], - [0.2541521, 0.00856813, 0.04817184], - [0.4620771, 0.04817184, 0.05448031], - [0.571125, 0.01298304, 0.09305902], - [0.4341537, 0.08650047, 0.2195262], - [0.571125, 0.08865561, 0.1559265], - [0.9559736, 0.1778885, 0.309469], - [0.9734454, 0.4125428, 0.5840785], - [1.0, 0.5840785, 0.6866855], - [0.03071345, 0.01161226, 0.05126946], - [0.03820438, 0.02121902, 0.04666509], - [0.07227188, 0.00913407, 0.07421357], - [0.1589609, 0.05448031, 0.4507858], - [0.2345507, 0.1070232, 0.4793203], - [0.5271152, 0.2269659, 0.6038274], - [0.3915726, 0.2917707, 0.5840785], - [0.5583405, 0.4125428, 0.791298], - [0.8549928, 0.5149179, 0.9559736], - [0.6444799, 0.5583405, 0.8468735], - [0.00972123, 0.0137021, 0.05126946], - [0.00604884, 0.0497066, 0.1328683], - [0.02315337, 0.2232281, 0.658375], - [0.09530749, 0.4564111, 0.8879234], - [0.1946179, 0.5583405, 0.7304609], - [0.2501584, 0.3813261, 0.9559736], - [0.2307401, 0.5088814, 0.9559736], - [0.3564002, 0.7681512, 1.0], - [0.00334654, 0.0273209, 0.03688948], - [0.00030353, 0.04666509, 0.04373505], - [0.00402472, 0.07818746, 0.09989879], - [0.0168074, 0.1328683, 0.1247718], - [0.02955684, 0.2086369, 0.2622508], - [0.07818746, 0.4232678, 0.4341537], - [0.1946179, 0.5520115, 0.3419146], - [0.2122308, 0.658375, 0.5271152], - [0.2422812, 0.783538, 0.4677839], - [0.00303527, 0.06847817, 0.03560133], - [0.05612849, 0.1946179, 0.0], - [0.00060706, 0.1778885, 0.1221388], - [0.03688948, 0.3185468, 0.1620294], - [0.07036012, 0.4178851, 0.01032982], - [0.287441, 0.5209957, 0.00303527], - [0.1247718, 0.571125, 0.2462014], - [0.3419146, 0.7454043, 0.05448031], - [0.3049874, 0.7304609, 0.2086369], - [0.4969332, 0.8879234, 0.4019778], - [0.3185468, 0.2917707, 0.02415765], - [0.3813261, 0.3005439, 0.1247718], - [0.6038274, 0.5271152, 0.04091523], - [0.6038274, 0.48515, 0.2422812], - [0.6938719, 0.6038274, 0.2232281], - [0.6653875, 0.6938719, 0.1589609], - [0.6653875, 0.791298, 0.2269659], - [0.6866855, 0.9559736, 0.3371637], - [0.2050788, 0.05951127, 0.0], - [0.791298, 0.4969332, 0.1946179], - [0.9911023, 0.7605247, 0.06847817], - [0.9559736, 0.7304609, 0.2232281], - [0.9301111, 0.822786, 0.3324517], - [0.9559736, 0.938686, 0.3277782], - [0.3813261, 0.07421357, 0.01298304], - [1.0, 0.3049874, 0.00402472], - [0.6375971, 0.3277782, 0.1412634], - [1.0, 0.4452013, 0.1328683], - [1.0, 0.5394797, 0.2622508], - [0.783538, 0.6239606, 0.4396573], - [0.05286067, 0.05286067, 0.05286067], - [0.3277782, 0.3277782, 0.3277782], - [0.5149179, 0.5149179, 0.5149179], - [0.7156936, 0.6795427, 0.6104956], - [1.0, 1.0, 1.0], + [1.0, 1.0, 1.0] ]; export const MiiSwitchSkinColorList: Record = { @@ -562,11 +459,9 @@ export const MiiSwitchSkinColorList: Record = { 6: "#ffbea5", 7: "#ffc58f", 8: "#8c3c23", - 9: "#3c2d23", + 9: "#3c2d23" }; -// todo: turn this into a lookup table?? -// i got lazy and couldn't find common color mapping for faceline colors export const MiiSwitchSkinColorSRGB: MiiLookupTableVec3 = [ [1, 0.8274509906768799, 0.6784313917160034], [1, 0.7137255072593689, 0.41960790753364563], @@ -577,20 +472,7 @@ export const MiiSwitchSkinColorSRGB: MiiLookupTableVec3 = [ [1, 0.7450981140136719, 0.64705890417099], [1, 0.7725490927696228, 0.5607843995094299], [0.5490196943283081, 0.2352941930294037, 0.137254998087883], - [0.2352941930294037, 0.1764705926179886, 0.137254998087883], -]; - -export const MiiSwitchSkinColorLinear: MiiLookupTableVec3 = [ - [1, 0.6514056921005249, 0.4178851544857025], - [1, 0.4677838385105133, 0.14702732861042023], - [0.7304610013961792, 0.19120177626609802, 0.054480310529470444], - [1, 0.40197786688804626, 0.26225078105926514], - [0.4178851544857025, 0.08228272944688797, 0.022173907607793808], - [0.1247718408703804, 0.02518688142299652, 0.009134066291153431], - [1, 0.5149179100990295, 0.3762623071670532], - [1, 0.5583406090736389, 0.27467745542526245], - [0.26225078105926514, 0.04518624022603035, 0.016807394102215767], - [0.04518624022603035, 0.026241222396492958, 0.016807394102215767], + [0.2352941930294037, 0.1764705926179886, 0.137254998087883] ]; // The actual palettes aren't shown here, only a lookup table @@ -601,34 +483,54 @@ export const MiiTLHairSprayToSwitchColor: MiiLookupTableQrColor = [ 92, 19, 20, 20, 15, 32, 35, 26, - 38, 41, 43, 18, 95, 97, 97, 99, + 38, 41, 43, 18, 95, 97, 97, 99 ]; export const ToVer3GlassTypeTable = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 1, 3, 7, 7, 6, 7, 8, 7, 7, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 1, 3, 7, 7, 6, 7, 8, 7, 7 ]; export const ToVer3HairColorTable = [ 0, 1, 2, 3, 4, 5, 6, 7, 0, 4, 3, 5, 4, 4, 6, 2, 0, 6, 4, 3, 2, 2, 7, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 0, 0, 0, 4, 4, 4, 4, 4, 4, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 5, 7, 5, - 7, 7, 7, 7, 7, 6, 7, 7, 7, 7, 7, 3, 7, 7, 7, 7, 7, 0, 4, 4, 4, 4, + 7, 7, 7, 7, 7, 6, 7, 7, 7, 7, 7, 3, 7, 7, 7, 7, 7, 0, 4, 4, 4, 4 ]; export const ToVer3EyeColorTable = [ 0, 2, 2, 2, 1, 3, 2, 3, 0, 1, 2, 3, 4, 5, 2, 2, 4, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 4, 4, 4, 4, 4, 4, 4, 1, 0, 4, 4, 4, 4, 4, 4, 4, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 3, 3, - 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, + 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1 ]; export const ToVer3MouthColorTable = [ 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 1, 4, 4, 4, 0, 1, 2, 3, 4, 4, 2, 3, 3, 4, 4, 4, 4, 1, 4, 4, 2, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, 3, - 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 4, 0, 3, 3, 3, 3, 4, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 4, 0, 3, 3, 3, 3, 4, 3, 3, 3, 3 ]; export const ToVer3GlassColorTable = [ 0, 1, 1, 1, 5, 1, 1, 4, 0, 5, 1, 1, 3, 5, 1, 2, 3, 4, 5, 4, 2, 2, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 5, 5, 5, 5, 5, 5, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5 ]; export const ToVer3FacelineColorTable = [0, 1, 2, 3, 4, 5, 0, 1, 5, 5]; + +export const Ver3FacelineColorTable = [0, 1, 2, 3, 4, 5]; +export const Ver3HairColorTable = [8, 1, 2, 3, 4, 5, 6, 7]; +export const Ver3EyeColorTable = [8, 9, 10, 11, 12, 13]; +export const Ver3MouthColorTable = [19, 20, 21, 22, 23]; +export const Ver3GlassColorTable = [8, 14, 15, 16, 17, 18, 0]; + +// do not mess with this, these aren't allowed +export const ForbiddenShirtPantColors = [ + , + /*1*/ 7, + 22, + 78, + 79, + 84, + 91, + 92, + 93, + 94 +]; diff --git a/src/constants/EditorIcons.ts b/src/constants/EditorIcons.ts index e70941e..8640c36 100644 --- a/src/constants/EditorIcons.ts +++ b/src/constants/EditorIcons.ts @@ -19,6 +19,8 @@ export default { head: ``, hair: ``, hat: ``, + // clothes: ``, + clothes: ``, favoriteColor: ``, facialHair: ``, gender: ``, @@ -28,6 +30,7 @@ export default { genderFemaleLg: ``, favorite: ``, special: ``, + personal: ``, sparkle: ``, // shape position tab positionMoveDown: ``, diff --git a/src/constants/Extensions.ts b/src/constants/Extensions.ts index 2bf72f0..8aabcc4 100644 --- a/src/constants/Extensions.ts +++ b/src/constants/Extensions.ts @@ -1,4 +1,3 @@ - export const ExtHatNameList = [ "Cap", "Beanie", @@ -8,27 +7,44 @@ export const ExtHatNameList = [ "Cat Ears", "Straw Hat", "Hijab", - "Bike Helmet", + "Bike Helmet" ]; +export const ExtClothesList = ["LS+Pants", "SS+Shorts", "TT+Shorts"]; + export enum HatType { HEAD, HAT, FACE_ONLY, - BALD, + FRONT, + SIDE, + TOP, + BALD +} + +export enum ClothesType { + COLOR_MIXED, + TEXTURE_COLOR } export const HatTypeList = [ - HatType.HEAD, // Hat type 0 is no hat. HatType.HAT, // Cap HatType.HAT, // Beanie HatType.HAT, // Top Hat - HatType.HEAD, // Ribbon - HatType.HEAD, // Bow + HatType.SIDE, // Ribbon + HatType.SIDE, // Bow HatType.HEAD, // Cat Ears HatType.HAT, // Straw Hat HatType.BALD, // Hijab - HatType.HAT, // Bike Helmet + HatType.HAT // Bike Helmet +]; + +export const ClothesTypeList = [ + ClothesType.COLOR_MIXED, + ClothesType.COLOR_MIXED, + ClothesType.COLOR_MIXED, + ClothesType.COLOR_MIXED + // ClothesType.TEXTURE_COLOR ]; -export const ExtHatFullHeadList = [4, 5, 6]; \ No newline at end of file +export const ExtHatFullHeadList = [4, 5, 6]; diff --git a/src/constants/MiiFeatureTable.ts b/src/constants/MiiFeatureTable.ts index dc52f7d..9cd1a44 100644 --- a/src/constants/MiiFeatureTable.ts +++ b/src/constants/MiiFeatureTable.ts @@ -4,192 +4,98 @@ import Html from "@datkat21/html"; import { FeatureSetType } from "../ui/components/MiiPagedFeatureSet"; // for example to be used with the CSS order property. -export const MiiEyeTable: Record = { - // RealValue: DisplayedPosition - 0: 2, - 1: 6, - 2: 0, - 3: 42, - 4: 1, - 5: 24, - 6: 29, - 7: 36, - 8: 3, - 9: 16, - 10: 45, -}; -export const MiiHairTable: Record = { - 33: 0, - 47: 1, - 40: 2, - 37: 3, - 32: 4, - 107: 5, - 48: 6, - 51: 7, - 55: 8, - 70: 9, - 44: 10, - 66: 11, - 52: 12, - 50: 13, - 38: 14, - 49: 15, - 43: 16, - 31: 17, - 56: 18, - 68: 19, - 62: 20, - 115: 21, - 76: 22, - 119: 23, - 64: 24, - 81: 25, - 116: 26, - 121: 27, - 22: 28, - 58: 29, - 60: 30, - 87: 31, - 125: 32, - 117: 33, - 73: 34, - 75: 35, - 42: 36, - 89: 37, - 57: 38, - 54: 39, - 80: 40, - 34: 41, - 23: 42, - 86: 43, - 88: 44, - 118: 45, - 39: 46, - 36: 47, - 45: 48, - 67: 49, - 59: 50, - 65: 51, - 41: 52, - 30: 53, - 12: 54, - 16: 55, - 10: 56, - 82: 57, - 128: 58, - 129: 59, - 14: 60, - 95: 61, - 105: 62, - 100: 63, - 6: 64, - 20: 65, - 93: 66, - 102: 67, - 27: 68, - 4: 69, - 17: 70, - 110: 71, - 123: 72, - 8: 73, - 106: 74, - 72: 75, - 3: 76, - 21: 77, - 0: 78, - 98: 79, - 63: 80, - 90: 81, - 11: 82, - 120: 83, - 5: 84, - 74: 85, - 108: 86, - 94: 87, - 124: 88, - 25: 89, - 99: 90, - 69: 91, - 35: 92, - 13: 93, - 122: 94, - 113: 95, - 53: 96, - 24: 97, - 85: 98, - 83: 99, - 71: 100, - 131: 101, - 96: 102, - 101: 103, - 29: 104, - 7: 105, - 15: 106, - 112: 107, - 79: 108, - 1: 109, - 109: 110, - 127: 111, - 91: 112, - 26: 113, - 61: 114, - 103: 115, - 2: 116, - 77: 117, - 18: 118, - 92: 119, - 84: 120, - 9: 121, - 19: 122, - 130: 123, - 97: 124, - 104: 125, - 46: 126, - 78: 127, - 28: 128, - 114: 129, - 126: 130, - 111: 131, -}; +export const MiiEyeTable: number[][] = [ + // The real value is looked up and displayed here + [2, 4, 0, 8, 39, 17, 1, 26, 16, 15, 27, 20], + [33, 11, 19, 32, 9, 12, 23, 34, 21, 25, 40, 35], + [5, 41, 13, 36, 37, 6, 24, 30, 31, 18, 28, 46], + [7, 44, 38, 42, 45, 29, 3, 43, 22, 10, 14, 47], + [48, 49, 50, 53, 59, 56, 54, 58, 57, 55, 51, 52] +]; + +export const MiiEyebrowTable: number[][] = [ + [6, 0, 12, 1, 9, 19, 7, 21, 8, 17, 5, 4], + [11, 10, 2, 3, 14, 20, 15, 13, 22, 18, 16, 23] +]; +export const MiiMouthTable: number[][] = [ + [23, 1, 19, 21, 22, 5, 0, 8, 10, 16, 6, 13], + [7, 9, 2, 17, 3, 4, 15, 11, 20, 18, 14, 12], + [27, 30, 24, 25, 29, 28, 26, 35, 31, 34, 33, 32] +]; +export const MiiNoseTable: number[][] = [ + [1, 10, 2, 3, 6, 0, 5, 4, 8, 9, 7, 11], + [13, 14, 12, 17, 16, 15] +]; + +export const MiiHairTable: number[][] = [ + [33, 47, 40, 37, 32, 107, 48, 51, 55, 70, 44, 66], + [52, 50, 38, 49, 43, 31, 56, 68, 62, 115, 76, 119], + [64, 81, 116, 121, 22, 58, 60, 87, 125, 117, 73, 75], + [42, 89, 57, 54, 80, 34, 23, 86, 88, 118, 39, 36], + [45, 67, 59, 65, 41, 30, 12, 16, 10, 82, 128, 129], + [14, 95, 105, 100, 6, 20, 93, 102, 27, 4, 17, 110], + [123, 8, 106, 72, 3, 21, 0, 98, 63, 90, 11, 120], + [5, 74, 108, 94, 124, 25, 99, 69, 35, 13, 122, 113], + [53, 24, 85, 83, 71, 131, 96, 101, 29, 7, 15, 112], + [79, 1, 109, 127, 91, 26, 61, 103, 2, 77, 18, 92], + [84, 9, 19, 130, 97, 104, 46, 78, 28, 114, 126, 111] +]; export const MiiSwitchColorTable = [ - 91, 80, 0, 81, 95, 60, 72, 74, 90, 93, 2, 61, 33, 44, 70, 4, 31, 73, 94, 83, - 5, 6, 86, 3, 1, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, - 23, 24, 25, 26, 27, 28, 29, 30, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, - 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 62, 63, 64, 65, - 66, 67, 68, 69, 71, 75, 76, 77, 78, 79, 82, 84, 85, 87, 88, 89, 92, 96, 97, - 98, 99, + [2, 24, 10, 23, 15, 20, 21, 25, 26, 27], + [28, 29, 30, 31, 32, 33, 34, 35, 36, 37], + [38, 39, 40, 41, 42, 43, 44, 45, 46, 47], + [48, 16, 49, 12, 50, 51, 52, 53, 54, 55], + [56, 57, 58, 59, 13, 60, 61, 62, 63, 64], + [65, 66, 67, 68, 69, 70, 71, 72, 73, 74], + [5, 11, 75, 76, 77, 78, 79, 80, 81, 82], + [14, 83, 6, 17, 7, 84, 85, 86, 87, 88], + [1, 3, 89, 19, 90, 91, 22, 92, 93, 94], + [8, 0, 95, 9, 18, 4, 96, 97, 98, 99] +]; + +export const MiiSwitchSkinColorTable: number[][] = [ + [0, 7, 1, 4, 5], + [6, 3, 2, 8, 9] ]; -export const MiiSwitchSkinColorTable: Record = { - 0: 0, - 7: 1, - 1: 2, - 4: 3, - 5: 4, - 6: 5, - 3: 6, - 2: 7, - 8: 8, - 9: 9, -}; +export const MiiEyeRotationGroups: number[] = [ + -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, 0, 0, 0, -1, + -1, 0, -1, 0, 0, -1, 0, 0, 0, -1, -1, -1, 0, 0, -1, -1, -1, 0, 0, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, -1, 0, 0, -1 +]; + +export const MiiEyebrowRotationGroups: number[] = [ + 0, 0, -1, 1, 0, 1, 0, 1, -2, 1, 0, 2, -1, -1, 0, 0, 1, 1, 0, 0, -1, 0, 1, 0 +]; export function rearrangeArray( array: any[], - lookupTable: Record + lookupTable: Record | number[][], + separator = makeSeparatorGapThinDesktop ): any[] { let rearrangedArray: any[] = []; - for (const index in lookupTable) { - const newIndex = lookupTable[index]; - rearrangedArray[newIndex] = array[parseInt(index)]; + if (Array.isArray(lookupTable) && Array.isArray(lookupTable[0])) { + // 2D array case (page-based sorting with separators) + for (const page of lookupTable) { + let pageItems = page + .map((index) => array[index]) + .filter((i) => i !== undefined); + if (rearrangedArray.length > 0 && pageItems.length > 0) { + rearrangedArray.push(separator()); // Add separator between pages + } + rearrangedArray.push(...pageItems); + } + } else { + // 1D mapping case (direct index reassignment) + for (const realIndex in lookupTable) { + const lookupIndex = (lookupTable as Record)[realIndex]; + rearrangedArray[parseInt(realIndex)] = array[lookupIndex]; + } + rearrangedArray = rearrangedArray.filter((i) => i !== undefined); } - rearrangedArray = rearrangedArray.filter((i) => i !== undefined); - - // console.log("rearranged:", rearrangedArray); - return rearrangedArray; } @@ -197,22 +103,32 @@ export const makeSeparator = () => new Html("div").class("separator"); export const makeSeparatorFSI: () => any = () => ({ type: FeatureSetType.Misc, html: new Html("div").class("separator"), - select() {}, + select() {} }); export const makeSeparatorGapFSI: () => any = () => ({ type: FeatureSetType.Misc, html: new Html("div").class("separator-gap"), - select() {}, + select() {} }); export const makeSeparatorGapThinFSI: () => any = () => ({ type: FeatureSetType.Misc, html: new Html("div").class("separator-gap-thin"), - select() {}, + select() {} +}); +export const makeSeparatorGapThinDesktop: () => any = () => ({ + type: FeatureSetType.Misc, + html: new Html("div").class("separator-gap-thin-desktop"), + select() {} +}); +export const makeSeparatorGapThinLaptop: () => any = () => ({ + type: FeatureSetType.Misc, + html: new Html("div").class("separator-gap-thin-laptop"), + select() {} }); export const makeSeparatorGapThin = () => new Html("div").class("separator-gap-thin"); export const makeHeaderFSI = (text: string) => ({ type: FeatureSetType.Misc, html: new Html("div").text(text), - select() {}, + select() {} }); diff --git a/src/constants/TabRenderType.ts b/src/constants/TabRenderType.ts index ecab67c..b0647fa 100644 --- a/src/constants/TabRenderType.ts +++ b/src/constants/TabRenderType.ts @@ -1,6 +1,12 @@ import type Html from "@datkat21/html"; -import type Mii from "../external/mii-js/mii"; -import type { IconSet, MiiEditor, RenderPart } from "../class/MiiEditor"; +// import type Mii from "../external/mii-js/mii"; +import type Mii from "../class/MiiData"; +import type { + BodyUpdateType, + IconSet, + MiiEditor, + RenderPart +} from "../class/MiiEditor"; export type TabRenderInit = { container: Html; @@ -9,9 +15,11 @@ export type TabRenderInit = { callback: ( newMii: Mii, forceRender: boolean, - renderPart: RenderPart + renderPart: RenderPart, + bodyUpdateType: BodyUpdateType ) => any | Promise; editor: MiiEditor; + useAccessibility: boolean; }; export type TabBase = (input: TabRenderInit) => any; diff --git a/src/external/assert/assert.d.ts b/src/external/assert/assert.d.ts deleted file mode 100644 index 9c714f1..0000000 --- a/src/external/assert/assert.d.ts +++ /dev/null @@ -1,106 +0,0 @@ -/** An alias of `assert.ok()`. */ -declare function assert(value: any, message?: string | Error): asserts value; -declare namespace assert { - class AssertionError extends Error { - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; - code: "ERR_ASSERTION"; - - constructor(options?: { - /** If provided, the error message is set to this value. */ - message?: string | undefined; - /** The `actual` property on the error instance. */ - actual?: any; - /** The `expected` property on the error instance. */ - expected?: any; - /** The `operator` property on the error instance. */ - operator?: string | undefined; - /** If provided, the generated stack trace omits frames before this function. */ - // eslint-disable-next-line @typescript-eslint/ban-types - stackStartFn?: Function | undefined; - }); - } - - type AssertPredicate = RegExp | (new() => object) | ((thrown: any) => boolean) | object | Error; - - function fail(message?: string | Error): never; - /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ - function fail( - actual: any, - expected: any, - message?: string | Error, - operator?: string, - // eslint-disable-next-line @typescript-eslint/ban-types - stackStartFn?: Function, - ): never; - function ok(value: any, message?: string | Error): asserts value; - /** @deprecated since v9.9.0 - use strictEqual() instead. */ - function equal(actual: any, expected: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ - function notEqual(actual: any, expected: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ - function deepEqual(actual: any, expected: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ - function notDeepEqual(actual: any, expected: any, message?: string | Error): void; - function strictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; - function notStrictEqual(actual: any, expected: any, message?: string | Error): void; - function deepStrictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; - function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; - - function throws(block: () => any, message?: string | Error): void; - function throws(block: () => any, error: AssertPredicate, message?: string | Error): void; - function doesNotThrow(block: () => any, message?: string | Error): void; - function doesNotThrow(block: () => any, error: AssertPredicate, message?: string | Error): void; - - function ifError(value: any): asserts value is null | undefined; - - function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; - function rejects( - block: (() => Promise) | Promise, - error: AssertPredicate, - message?: string | Error, - ): Promise; - function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; - function doesNotReject( - block: (() => Promise) | Promise, - error: AssertPredicate, - message?: string | Error, - ): Promise; - - function match(value: string, regExp: RegExp, message?: string | Error): void; - function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; - - const strict: - & Omit< - typeof assert, - | "equal" - | "notEqual" - | "deepEqual" - | "notDeepEqual" - | "ok" - | "strictEqual" - | "deepStrictEqual" - | "ifError" - | "strict" - > - & { - (value: any, message?: string | Error): asserts value; - equal: typeof strictEqual; - notEqual: typeof notStrictEqual; - deepEqual: typeof deepStrictEqual; - notDeepEqual: typeof notDeepStrictEqual; - - // Mapped types and assertion functions are incompatible? - // TS2775: Assertions require every name in the call target - // to be declared with an explicit type annotation. - ok: typeof ok; - strictEqual: typeof strictEqual; - deepStrictEqual: typeof deepStrictEqual; - ifError: typeof ifError; - strict: typeof strict; - }; -} - -export = assert; diff --git a/src/external/assert/assert.js b/src/external/assert/assert.js deleted file mode 100644 index f72fa6e..0000000 --- a/src/external/assert/assert.js +++ /dev/null @@ -1,590 +0,0 @@ -// Currently in sync with Node.js lib/assert.js -// https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b - -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; - -function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -var _require = require('./internal/errors'), - _require$codes = _require.codes, - ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE, - ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; -var AssertionError = require('./internal/assert/assertion_error'); -var _require2 = require('util/'), - inspect = _require2.inspect; -var _require$types = require('util/').types, - isPromise = _require$types.isPromise, - isRegExp = _require$types.isRegExp; -var objectAssign = require('object.assign/polyfill')(); -var objectIs = require('object-is/polyfill')(); -var RegExpPrototypeTest = require('call-bind/callBound')('RegExp.prototype.test'); -var errorCache = new Map(); -var isDeepEqual; -var isDeepStrictEqual; -var parseExpressionAt; -var findNodeAround; -var decoder; -function lazyLoadComparison() { - var comparison = require('./internal/util/comparisons'); - isDeepEqual = comparison.isDeepEqual; - isDeepStrictEqual = comparison.isDeepStrictEqual; -} - -// Escape control characters but not \n and \t to keep the line breaks and -// indentation intact. -// eslint-disable-next-line no-control-regex -var escapeSequencesRegExp = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g; -var meta = ["\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007", '\\b', '', '', "\\u000b", '\\f', '', "\\u000e", "\\u000f", "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d", "\\u001e", "\\u001f"]; -var escapeFn = function escapeFn(str) { - return meta[str.charCodeAt(0)]; -}; -var warned = false; - -// The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; -var NO_EXCEPTION_SENTINEL = {}; - -// All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function innerFail(obj) { - if (obj.message instanceof Error) throw obj.message; - throw new AssertionError(obj); -} -function fail(actual, expected, message, operator, stackStartFn) { - var argsLen = arguments.length; - var internalMessage; - if (argsLen === 0) { - internalMessage = 'Failed'; - } else if (argsLen === 1) { - message = actual; - actual = undefined; - } else { - if (warned === false) { - warned = true; - var warn = process.emitWarning ? process.emitWarning : console.warn.bind(console); - warn('assert.fail() with more than one argument is deprecated. ' + 'Please use assert.strictEqual() instead or only pass a message.', 'DeprecationWarning', 'DEP0094'); - } - if (argsLen === 2) operator = '!='; - } - if (message instanceof Error) throw message; - var errArgs = { - actual: actual, - expected: expected, - operator: operator === undefined ? 'fail' : operator, - stackStartFn: stackStartFn || fail - }; - if (message !== undefined) { - errArgs.message = message; - } - var err = new AssertionError(errArgs); - if (internalMessage) { - err.message = internalMessage; - err.generatedMessage = true; - } - throw err; -} -assert.fail = fail; - -// The AssertionError is defined in internal/error. -assert.AssertionError = AssertionError; -function innerOk(fn, argLen, value, message) { - if (!value) { - var generatedMessage = false; - if (argLen === 0) { - generatedMessage = true; - message = 'No value argument passed to `assert.ok()`'; - } else if (message instanceof Error) { - throw message; - } - var err = new AssertionError({ - actual: value, - expected: true, - message: message, - operator: '==', - stackStartFn: fn - }); - err.generatedMessage = generatedMessage; - throw err; - } -} - -// Pure assertion tests whether a value is truthy, as determined -// by !!value. -function ok() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - innerOk.apply(void 0, [ok, args.length].concat(args)); -} -assert.ok = ok; - -// The equality assertion tests shallow, coercive equality with ==. -/* eslint-disable no-restricted-properties */ -assert.equal = function equal(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - // eslint-disable-next-line eqeqeq - if (actual != expected) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: '==', - stackStartFn: equal - }); - } -}; - -// The non-equality assertion tests for whether two objects are not -// equal with !=. -assert.notEqual = function notEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - // eslint-disable-next-line eqeqeq - if (actual == expected) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: '!=', - stackStartFn: notEqual - }); - } -}; - -// The equivalence assertion tests a deep equality relation. -assert.deepEqual = function deepEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - if (isDeepEqual === undefined) lazyLoadComparison(); - if (!isDeepEqual(actual, expected)) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: 'deepEqual', - stackStartFn: deepEqual - }); - } -}; - -// The non-equivalence assertion tests for any deep inequality. -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - if (isDeepEqual === undefined) lazyLoadComparison(); - if (isDeepEqual(actual, expected)) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: 'notDeepEqual', - stackStartFn: notDeepEqual - }); - } -}; -/* eslint-enable */ - -assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - if (isDeepEqual === undefined) lazyLoadComparison(); - if (!isDeepStrictEqual(actual, expected)) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: 'deepStrictEqual', - stackStartFn: deepStrictEqual - }); - } -}; -assert.notDeepStrictEqual = notDeepStrictEqual; -function notDeepStrictEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - if (isDeepEqual === undefined) lazyLoadComparison(); - if (isDeepStrictEqual(actual, expected)) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: 'notDeepStrictEqual', - stackStartFn: notDeepStrictEqual - }); - } -} -assert.strictEqual = function strictEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - if (!objectIs(actual, expected)) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: 'strictEqual', - stackStartFn: strictEqual - }); - } -}; -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - if (objectIs(actual, expected)) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: 'notStrictEqual', - stackStartFn: notStrictEqual - }); - } -}; -var Comparison = /*#__PURE__*/_createClass(function Comparison(obj, keys, actual) { - var _this = this; - _classCallCheck(this, Comparison); - keys.forEach(function (key) { - if (key in obj) { - if (actual !== undefined && typeof actual[key] === 'string' && isRegExp(obj[key]) && RegExpPrototypeTest(obj[key], actual[key])) { - _this[key] = actual[key]; - } else { - _this[key] = obj[key]; - } - } - }); -}); -function compareExceptionKey(actual, expected, key, message, keys, fn) { - if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) { - if (!message) { - // Create placeholder objects to create a nice output. - var a = new Comparison(actual, keys); - var b = new Comparison(expected, keys, actual); - var err = new AssertionError({ - actual: a, - expected: b, - operator: 'deepStrictEqual', - stackStartFn: fn - }); - err.actual = actual; - err.expected = expected; - err.operator = fn.name; - throw err; - } - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: fn.name, - stackStartFn: fn - }); - } -} -function expectedException(actual, expected, msg, fn) { - if (typeof expected !== 'function') { - if (isRegExp(expected)) return RegExpPrototypeTest(expected, actual); - // assert.doesNotThrow does not accept objects. - if (arguments.length === 2) { - throw new ERR_INVALID_ARG_TYPE('expected', ['Function', 'RegExp'], expected); - } - - // Handle primitives properly. - if (_typeof(actual) !== 'object' || actual === null) { - var err = new AssertionError({ - actual: actual, - expected: expected, - message: msg, - operator: 'deepStrictEqual', - stackStartFn: fn - }); - err.operator = fn.name; - throw err; - } - var keys = Object.keys(expected); - // Special handle errors to make sure the name and the message are compared - // as well. - if (expected instanceof Error) { - keys.push('name', 'message'); - } else if (keys.length === 0) { - throw new ERR_INVALID_ARG_VALUE('error', expected, 'may not be an empty object'); - } - if (isDeepEqual === undefined) lazyLoadComparison(); - keys.forEach(function (key) { - if (typeof actual[key] === 'string' && isRegExp(expected[key]) && RegExpPrototypeTest(expected[key], actual[key])) { - return; - } - compareExceptionKey(actual, expected, key, msg, keys, fn); - }); - return true; - } - // Guard instanceof against arrow functions as they don't have a prototype. - if (expected.prototype !== undefined && actual instanceof expected) { - return true; - } - if (Error.isPrototypeOf(expected)) { - return false; - } - return expected.call({}, actual) === true; -} -function getActual(fn) { - if (typeof fn !== 'function') { - throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn); - } - try { - fn(); - } catch (e) { - return e; - } - return NO_EXCEPTION_SENTINEL; -} -function checkIsPromise(obj) { - // Accept native ES6 promises and promises that are implemented in a similar - // way. Do not accept thenables that use a function as `obj` and that have no - // `catch` handler. - - // TODO: thenables are checked up until they have the correct methods, - // but according to documentation, the `then` method should receive - // the `fulfill` and `reject` arguments as well or it may be never resolved. - - return isPromise(obj) || obj !== null && _typeof(obj) === 'object' && typeof obj.then === 'function' && typeof obj.catch === 'function'; -} -function waitForActual(promiseFn) { - return Promise.resolve().then(function () { - var resultPromise; - if (typeof promiseFn === 'function') { - // Return a rejected promise if `promiseFn` throws synchronously. - resultPromise = promiseFn(); - // Fail in case no promise is returned. - if (!checkIsPromise(resultPromise)) { - throw new ERR_INVALID_RETURN_VALUE('instance of Promise', 'promiseFn', resultPromise); - } - } else if (checkIsPromise(promiseFn)) { - resultPromise = promiseFn; - } else { - throw new ERR_INVALID_ARG_TYPE('promiseFn', ['Function', 'Promise'], promiseFn); - } - return Promise.resolve().then(function () { - return resultPromise; - }).then(function () { - return NO_EXCEPTION_SENTINEL; - }).catch(function (e) { - return e; - }); - }); -} -function expectsError(stackStartFn, actual, error, message) { - if (typeof error === 'string') { - if (arguments.length === 4) { - throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); - } - if (_typeof(actual) === 'object' && actual !== null) { - if (actual.message === error) { - throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error message \"".concat(actual.message, "\" is identical to the message.")); - } - } else if (actual === error) { - throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error \"".concat(actual, "\" is identical to the message.")); - } - message = error; - error = undefined; - } else if (error != null && _typeof(error) !== 'object' && typeof error !== 'function') { - throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); - } - if (actual === NO_EXCEPTION_SENTINEL) { - var details = ''; - if (error && error.name) { - details += " (".concat(error.name, ")"); - } - details += message ? ": ".concat(message) : '.'; - var fnType = stackStartFn.name === 'rejects' ? 'rejection' : 'exception'; - innerFail({ - actual: undefined, - expected: error, - operator: stackStartFn.name, - message: "Missing expected ".concat(fnType).concat(details), - stackStartFn: stackStartFn - }); - } - if (error && !expectedException(actual, error, message, stackStartFn)) { - throw actual; - } -} -function expectsNoError(stackStartFn, actual, error, message) { - if (actual === NO_EXCEPTION_SENTINEL) return; - if (typeof error === 'string') { - message = error; - error = undefined; - } - if (!error || expectedException(actual, error)) { - var details = message ? ": ".concat(message) : '.'; - var fnType = stackStartFn.name === 'doesNotReject' ? 'rejection' : 'exception'; - innerFail({ - actual: actual, - expected: error, - operator: stackStartFn.name, - message: "Got unwanted ".concat(fnType).concat(details, "\n") + "Actual message: \"".concat(actual && actual.message, "\""), - stackStartFn: stackStartFn - }); - } - throw actual; -} -assert.throws = function throws(promiseFn) { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - expectsError.apply(void 0, [throws, getActual(promiseFn)].concat(args)); -}; -assert.rejects = function rejects(promiseFn) { - for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - args[_key3 - 1] = arguments[_key3]; - } - return waitForActual(promiseFn).then(function (result) { - return expectsError.apply(void 0, [rejects, result].concat(args)); - }); -}; -assert.doesNotThrow = function doesNotThrow(fn) { - for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { - args[_key4 - 1] = arguments[_key4]; - } - expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args)); -}; -assert.doesNotReject = function doesNotReject(fn) { - for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { - args[_key5 - 1] = arguments[_key5]; - } - return waitForActual(fn).then(function (result) { - return expectsNoError.apply(void 0, [doesNotReject, result].concat(args)); - }); -}; -assert.ifError = function ifError(err) { - if (err !== null && err !== undefined) { - var message = 'ifError got unwanted exception: '; - if (_typeof(err) === 'object' && typeof err.message === 'string') { - if (err.message.length === 0 && err.constructor) { - message += err.constructor.name; - } else { - message += err.message; - } - } else { - message += inspect(err); - } - var newErr = new AssertionError({ - actual: err, - expected: null, - operator: 'ifError', - message: message, - stackStartFn: ifError - }); - - // Make sure we actually have a stack trace! - var origStack = err.stack; - if (typeof origStack === 'string') { - // This will remove any duplicated frames from the error frames taken - // from within `ifError` and add the original error frames to the newly - // created ones. - var tmp2 = origStack.split('\n'); - tmp2.shift(); - // Filter all frames existing in err.stack. - var tmp1 = newErr.stack.split('\n'); - for (var i = 0; i < tmp2.length; i++) { - // Find the first occurrence of the frame. - var pos = tmp1.indexOf(tmp2[i]); - if (pos !== -1) { - // Only keep new frames. - tmp1 = tmp1.slice(0, pos); - break; - } - } - newErr.stack = "".concat(tmp1.join('\n'), "\n").concat(tmp2.join('\n')); - } - throw newErr; - } -}; - -// Currently in sync with Node.js lib/assert.js -// https://github.com/nodejs/node/commit/2a871df3dfb8ea663ef5e1f8f62701ec51384ecb -function internalMatch(string, regexp, message, fn, fnName) { - if (!isRegExp(regexp)) { - throw new ERR_INVALID_ARG_TYPE('regexp', 'RegExp', regexp); - } - var match = fnName === 'match'; - if (typeof string !== 'string' || RegExpPrototypeTest(regexp, string) !== match) { - if (message instanceof Error) { - throw message; - } - var generatedMessage = !message; - - // 'The input was expected to not match the regular expression ' + - message = message || (typeof string !== 'string' ? 'The "string" argument must be of type string. Received type ' + "".concat(_typeof(string), " (").concat(inspect(string), ")") : (match ? 'The input did not match the regular expression ' : 'The input was expected to not match the regular expression ') + "".concat(inspect(regexp), ". Input:\n\n").concat(inspect(string), "\n")); - var err = new AssertionError({ - actual: string, - expected: regexp, - message: message, - operator: fnName, - stackStartFn: fn - }); - err.generatedMessage = generatedMessage; - throw err; - } -} -assert.match = function match(string, regexp, message) { - internalMatch(string, regexp, message, match, 'match'); -}; -assert.doesNotMatch = function doesNotMatch(string, regexp, message) { - internalMatch(string, regexp, message, doesNotMatch, 'doesNotMatch'); -}; - -// Expose a strict only variant of assert -function strict() { - for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { - args[_key6] = arguments[_key6]; - } - innerOk.apply(void 0, [strict, args.length].concat(args)); -} -assert.strict = objectAssign(strict, assert, { - equal: assert.strictEqual, - deepEqual: assert.deepStrictEqual, - notEqual: assert.notStrictEqual, - notDeepEqual: assert.notDeepStrictEqual -}); -assert.strict.strict = assert.strict; \ No newline at end of file diff --git a/src/external/assert/internal/assert/assertion_error.js b/src/external/assert/internal/assert/assertion_error.js deleted file mode 100644 index d30e83c..0000000 --- a/src/external/assert/internal/assert/assertion_error.js +++ /dev/null @@ -1,445 +0,0 @@ -// Currently in sync with Node.js lib/internal/assert/assertion_error.js -// https://github.com/nodejs/node/commit/0817840f775032169ddd70c85ac059f18ffcc81c - -'use strict'; - -function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } -function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } -function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } -function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } -function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } -var _require = require('util/'), - inspect = _require.inspect; -var _require2 = require('../errors'), - ERR_INVALID_ARG_TYPE = _require2.codes.ERR_INVALID_ARG_TYPE; - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat -function repeat(str, count) { - count = Math.floor(count); - if (str.length == 0 || count == 0) return ''; - var maxCount = str.length * count; - count = Math.floor(Math.log(count) / Math.log(2)); - while (count) { - str += str; - count--; - } - str += str.substring(0, maxCount - str.length); - return str; -} -var blue = ''; -var green = ''; -var red = ''; -var white = ''; -var kReadableOperator = { - deepStrictEqual: 'Expected values to be strictly deep-equal:', - strictEqual: 'Expected values to be strictly equal:', - strictEqualObject: 'Expected "actual" to be reference-equal to "expected":', - deepEqual: 'Expected values to be loosely deep-equal:', - equal: 'Expected values to be loosely equal:', - notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:', - notStrictEqual: 'Expected "actual" to be strictly unequal to:', - notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":', - notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:', - notEqual: 'Expected "actual" to be loosely unequal to:', - notIdentical: 'Values identical but not reference-equal:' -}; - -// Comparing short primitives should just show === / !== instead of using the -// diff. -var kMaxShortLength = 10; -function copyError(source) { - var keys = Object.keys(source); - var target = Object.create(Object.getPrototypeOf(source)); - keys.forEach(function (key) { - target[key] = source[key]; - }); - Object.defineProperty(target, 'message', { - value: source.message - }); - return target; -} -function inspectValue(val) { - // The util.inspect default values could be changed. This makes sure the - // error messages contain the necessary information nevertheless. - return inspect(val, { - compact: false, - customInspect: false, - depth: 1000, - maxArrayLength: Infinity, - // Assert compares only enumerable properties (with a few exceptions). - showHidden: false, - // Having a long line as error is better than wrapping the line for - // comparison for now. - // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we - // have meta information about the inspected properties (i.e., know where - // in what line the property starts and ends). - breakLength: Infinity, - // Assert does not detect proxies currently. - showProxy: false, - sorted: true, - // Inspect getters as we also check them when comparing entries. - getters: true - }); -} -function createErrDiff(actual, expected, operator) { - var other = ''; - var res = ''; - var lastPos = 0; - var end = ''; - var skipped = false; - var actualInspected = inspectValue(actual); - var actualLines = actualInspected.split('\n'); - var expectedLines = inspectValue(expected).split('\n'); - var i = 0; - var indicator = ''; - - // In case both values are objects explicitly mark them as not reference equal - // for the `strictEqual` operator. - if (operator === 'strictEqual' && _typeof(actual) === 'object' && _typeof(expected) === 'object' && actual !== null && expected !== null) { - operator = 'strictEqualObject'; - } - - // If "actual" and "expected" fit on a single line and they are not strictly - // equal, check further special handling. - if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) { - var inputLength = actualLines[0].length + expectedLines[0].length; - // If the character length of "actual" and "expected" together is less than - // kMaxShortLength and if neither is an object and at least one of them is - // not `zero`, use the strict equal comparison to visualize the output. - if (inputLength <= kMaxShortLength) { - if ((_typeof(actual) !== 'object' || actual === null) && (_typeof(expected) !== 'object' || expected === null) && (actual !== 0 || expected !== 0)) { - // -0 === +0 - return "".concat(kReadableOperator[operator], "\n\n") + "".concat(actualLines[0], " !== ").concat(expectedLines[0], "\n"); - } - } else if (operator !== 'strictEqualObject') { - // If the stderr is a tty and the input length is lower than the current - // columns per line, add a mismatch indicator below the output. If it is - // not a tty, use a default value of 80 characters. - var maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80; - if (inputLength < maxLength) { - while (actualLines[0][i] === expectedLines[0][i]) { - i++; - } - // Ignore the first characters. - if (i > 2) { - // Add position indicator for the first mismatch in case it is a - // single line and the input length is less than the column length. - indicator = "\n ".concat(repeat(' ', i), "^"); - i = 0; - } - } - } - } - - // Remove all ending lines that match (this optimizes the output for - // readability by reducing the number of total changed lines). - var a = actualLines[actualLines.length - 1]; - var b = expectedLines[expectedLines.length - 1]; - while (a === b) { - if (i++ < 2) { - end = "\n ".concat(a).concat(end); - } else { - other = a; - } - actualLines.pop(); - expectedLines.pop(); - if (actualLines.length === 0 || expectedLines.length === 0) break; - a = actualLines[actualLines.length - 1]; - b = expectedLines[expectedLines.length - 1]; - } - var maxLines = Math.max(actualLines.length, expectedLines.length); - // Strict equal with identical objects that are not identical by reference. - // E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() }) - if (maxLines === 0) { - // We have to get the result again. The lines were all removed before. - var _actualLines = actualInspected.split('\n'); - - // Only remove lines in case it makes sense to collapse those. - // TODO: Accept env to always show the full error. - if (_actualLines.length > 30) { - _actualLines[26] = "".concat(blue, "...").concat(white); - while (_actualLines.length > 27) { - _actualLines.pop(); - } - } - return "".concat(kReadableOperator.notIdentical, "\n\n").concat(_actualLines.join('\n'), "\n"); - } - if (i > 3) { - end = "\n".concat(blue, "...").concat(white).concat(end); - skipped = true; - } - if (other !== '') { - end = "\n ".concat(other).concat(end); - other = ''; - } - var printedLines = 0; - var msg = kReadableOperator[operator] + "\n".concat(green, "+ actual").concat(white, " ").concat(red, "- expected").concat(white); - var skippedMsg = " ".concat(blue, "...").concat(white, " Lines skipped"); - for (i = 0; i < maxLines; i++) { - // Only extra expected lines exist - var cur = i - lastPos; - if (actualLines.length < i + 1) { - // If the last diverging line is more than one line above and the - // current line is at least line three, add some of the former lines and - // also add dots to indicate skipped entries. - if (cur > 1 && i > 2) { - if (cur > 4) { - res += "\n".concat(blue, "...").concat(white); - skipped = true; - } else if (cur > 3) { - res += "\n ".concat(expectedLines[i - 2]); - printedLines++; - } - res += "\n ".concat(expectedLines[i - 1]); - printedLines++; - } - // Mark the current line as the last diverging one. - lastPos = i; - // Add the expected line to the cache. - other += "\n".concat(red, "-").concat(white, " ").concat(expectedLines[i]); - printedLines++; - // Only extra actual lines exist - } else if (expectedLines.length < i + 1) { - // If the last diverging line is more than one line above and the - // current line is at least line three, add some of the former lines and - // also add dots to indicate skipped entries. - if (cur > 1 && i > 2) { - if (cur > 4) { - res += "\n".concat(blue, "...").concat(white); - skipped = true; - } else if (cur > 3) { - res += "\n ".concat(actualLines[i - 2]); - printedLines++; - } - res += "\n ".concat(actualLines[i - 1]); - printedLines++; - } - // Mark the current line as the last diverging one. - lastPos = i; - // Add the actual line to the result. - res += "\n".concat(green, "+").concat(white, " ").concat(actualLines[i]); - printedLines++; - // Lines diverge - } else { - var expectedLine = expectedLines[i]; - var actualLine = actualLines[i]; - // If the lines diverge, specifically check for lines that only diverge by - // a trailing comma. In that case it is actually identical and we should - // mark it as such. - var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ',') || actualLine.slice(0, -1) !== expectedLine); - // If the expected line has a trailing comma but is otherwise identical, - // add a comma at the end of the actual line. Otherwise the output could - // look weird as in: - // - // [ - // 1 // No comma at the end! - // + 2 - // ] - // - if (divergingLines && endsWith(expectedLine, ',') && expectedLine.slice(0, -1) === actualLine) { - divergingLines = false; - actualLine += ','; - } - if (divergingLines) { - // If the last diverging line is more than one line above and the - // current line is at least line three, add some of the former lines and - // also add dots to indicate skipped entries. - if (cur > 1 && i > 2) { - if (cur > 4) { - res += "\n".concat(blue, "...").concat(white); - skipped = true; - } else if (cur > 3) { - res += "\n ".concat(actualLines[i - 2]); - printedLines++; - } - res += "\n ".concat(actualLines[i - 1]); - printedLines++; - } - // Mark the current line as the last diverging one. - lastPos = i; - // Add the actual line to the result and cache the expected diverging - // line so consecutive diverging lines show up as +++--- and not +-+-+-. - res += "\n".concat(green, "+").concat(white, " ").concat(actualLine); - other += "\n".concat(red, "-").concat(white, " ").concat(expectedLine); - printedLines += 2; - // Lines are identical - } else { - // Add all cached information to the result before adding other things - // and reset the cache. - res += other; - other = ''; - // If the last diverging line is exactly one line above or if it is the - // very first line, add the line to the result. - if (cur === 1 || i === 0) { - res += "\n ".concat(actualLine); - printedLines++; - } - } - } - // Inspected object to big (Show ~20 rows max) - if (printedLines > 20 && i < maxLines - 2) { - return "".concat(msg).concat(skippedMsg, "\n").concat(res, "\n").concat(blue, "...").concat(white).concat(other, "\n") + "".concat(blue, "...").concat(white); - } - } - return "".concat(msg).concat(skipped ? skippedMsg : '', "\n").concat(res).concat(other).concat(end).concat(indicator); -} -var AssertionError = /*#__PURE__*/function (_Error, _inspect$custom) { - _inherits(AssertionError, _Error); - var _super = _createSuper(AssertionError); - function AssertionError(options) { - var _this; - _classCallCheck(this, AssertionError); - if (_typeof(options) !== 'object' || options === null) { - throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); - } - var message = options.message, - operator = options.operator, - stackStartFn = options.stackStartFn; - var actual = options.actual, - expected = options.expected; - var limit = Error.stackTraceLimit; - Error.stackTraceLimit = 0; - if (message != null) { - _this = _super.call(this, String(message)); - } else { - if (process.stderr && process.stderr.isTTY) { - // Reset on each call to make sure we handle dynamically set environment - // variables correct. - if (process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1) { - blue = "\x1B[34m"; - green = "\x1B[32m"; - white = "\x1B[39m"; - red = "\x1B[31m"; - } else { - blue = ''; - green = ''; - white = ''; - red = ''; - } - } - // Prevent the error stack from being visible by duplicating the error - // in a very close way to the original in case both sides are actually - // instances of Error. - if (_typeof(actual) === 'object' && actual !== null && _typeof(expected) === 'object' && expected !== null && 'stack' in actual && actual instanceof Error && 'stack' in expected && expected instanceof Error) { - actual = copyError(actual); - expected = copyError(expected); - } - if (operator === 'deepStrictEqual' || operator === 'strictEqual') { - _this = _super.call(this, createErrDiff(actual, expected, operator)); - } else if (operator === 'notDeepStrictEqual' || operator === 'notStrictEqual') { - // In case the objects are equal but the operator requires unequal, show - // the first object and say A equals B - var base = kReadableOperator[operator]; - var res = inspectValue(actual).split('\n'); - - // In case "actual" is an object, it should not be reference equal. - if (operator === 'notStrictEqual' && _typeof(actual) === 'object' && actual !== null) { - base = kReadableOperator.notStrictEqualObject; - } - - // Only remove lines in case it makes sense to collapse those. - // TODO: Accept env to always show the full error. - if (res.length > 30) { - res[26] = "".concat(blue, "...").concat(white); - while (res.length > 27) { - res.pop(); - } - } - - // Only print a single input. - if (res.length === 1) { - _this = _super.call(this, "".concat(base, " ").concat(res[0])); - } else { - _this = _super.call(this, "".concat(base, "\n\n").concat(res.join('\n'), "\n")); - } - } else { - var _res = inspectValue(actual); - var other = ''; - var knownOperators = kReadableOperator[operator]; - if (operator === 'notDeepEqual' || operator === 'notEqual') { - _res = "".concat(kReadableOperator[operator], "\n\n").concat(_res); - if (_res.length > 1024) { - _res = "".concat(_res.slice(0, 1021), "..."); - } - } else { - other = "".concat(inspectValue(expected)); - if (_res.length > 512) { - _res = "".concat(_res.slice(0, 509), "..."); - } - if (other.length > 512) { - other = "".concat(other.slice(0, 509), "..."); - } - if (operator === 'deepEqual' || operator === 'equal') { - _res = "".concat(knownOperators, "\n\n").concat(_res, "\n\nshould equal\n\n"); - } else { - other = " ".concat(operator, " ").concat(other); - } - } - _this = _super.call(this, "".concat(_res).concat(other)); - } - } - Error.stackTraceLimit = limit; - _this.generatedMessage = !message; - Object.defineProperty(_assertThisInitialized(_this), 'name', { - value: 'AssertionError [ERR_ASSERTION]', - enumerable: false, - writable: true, - configurable: true - }); - _this.code = 'ERR_ASSERTION'; - _this.actual = actual; - _this.expected = expected; - _this.operator = operator; - if (Error.captureStackTrace) { - // eslint-disable-next-line no-restricted-syntax - Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn); - } - // Create error message including the error code in the name. - _this.stack; - // Reset the name. - _this.name = 'AssertionError'; - return _possibleConstructorReturn(_this); - } - _createClass(AssertionError, [{ - key: "toString", - value: function toString() { - return "".concat(this.name, " [").concat(this.code, "]: ").concat(this.message); - } - }, { - key: _inspect$custom, - value: function value(recurseTimes, ctx) { - // This limits the `actual` and `expected` property default inspection to - // the minimum depth. Otherwise those values would be too verbose compared - // to the actual error message which contains a combined view of these two - // input values. - return inspect(this, _objectSpread(_objectSpread({}, ctx), {}, { - customInspect: false, - depth: 0 - })); - } - }]); - return AssertionError; -}( /*#__PURE__*/_wrapNativeSuper(Error), inspect.custom); -module.exports = AssertionError; \ No newline at end of file diff --git a/src/external/assert/internal/errors.js b/src/external/assert/internal/errors.js deleted file mode 100644 index 17b6b4f..0000000 --- a/src/external/assert/internal/errors.js +++ /dev/null @@ -1,171 +0,0 @@ -// Currently in sync with Node.js lib/internal/errors.js -// https://github.com/nodejs/node/commit/3b044962c48fe313905877a96b5d0894a5404f6f - -/* eslint node-core/documented-errors: "error" */ -/* eslint node-core/alphabetize-errors: "error" */ -/* eslint node-core/prefer-util-format-errors: "error" */ - -'use strict'; - -// The whole point behind this internal module is to allow Node.js to no -// longer be forced to treat every error message change as a semver-major -// change. The NodeError classes here all expose a `code` property whose -// value statically and permanently identifies the error. While the error -// message may change, the code should not. -function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } -function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } -function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } -var codes = {}; - -// Lazy loaded -var assert; -var util; -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - var NodeError = /*#__PURE__*/function (_Base) { - _inherits(NodeError, _Base); - var _super = _createSuper(NodeError); - function NodeError(arg1, arg2, arg3) { - var _this; - _classCallCheck(this, NodeError); - _this = _super.call(this, getMessage(arg1, arg2, arg3)); - _this.code = code; - return _this; - } - return _createClass(NodeError); - }(Base); - codes[code] = NodeError; -} - -// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; -} - -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} -createErrorType('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - if (assert === undefined) assert = require('../assert'); - assert(typeof name === 'string', "'name' must be a string"); - - // determiner: 'must be' or 'must not be' - var determiner; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - var msg; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - // TODO(BridgeAR): Improve the output by showing `null` and similar. - msg += ". Received type ".concat(_typeof(actual)); - return msg; -}, TypeError); -createErrorType('ERR_INVALID_ARG_VALUE', function (name, value) { - var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'is invalid'; - if (util === undefined) util = require('util/'); - var inspected = util.inspect(value); - if (inspected.length > 128) { - inspected = "".concat(inspected.slice(0, 128), "..."); - } - return "The argument '".concat(name, "' ").concat(reason, ". Received ").concat(inspected); -}, TypeError, RangeError); -createErrorType('ERR_INVALID_RETURN_VALUE', function (input, name, value) { - var type; - if (value && value.constructor && value.constructor.name) { - type = "instance of ".concat(value.constructor.name); - } else { - type = "type ".concat(_typeof(value)); - } - return "Expected ".concat(input, " to be returned from the \"").concat(name, "\"") + " function but got ".concat(type, "."); -}, TypeError); -createErrorType('ERR_MISSING_ARGS', function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - if (assert === undefined) assert = require('../assert'); - assert(args.length > 0, 'At least one arg needs to be specified'); - var msg = 'The '; - var len = args.length; - args = args.map(function (a) { - return "\"".concat(a, "\""); - }); - switch (len) { - case 1: - msg += "".concat(args[0], " argument"); - break; - case 2: - msg += "".concat(args[0], " and ").concat(args[1], " arguments"); - break; - default: - msg += args.slice(0, len - 1).join(', '); - msg += ", and ".concat(args[len - 1], " arguments"); - break; - } - return "".concat(msg, " must be specified"); -}, TypeError); -module.exports.codes = codes; \ No newline at end of file diff --git a/src/external/assert/internal/util/comparisons.js b/src/external/assert/internal/util/comparisons.js deleted file mode 100644 index fd8180d..0000000 --- a/src/external/assert/internal/util/comparisons.js +++ /dev/null @@ -1,575 +0,0 @@ -// Currently in sync with Node.js lib/internal/util/comparisons.js -// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 - -'use strict'; - -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } -function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } -function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } -var regexFlagsSupported = /a/g.flags !== undefined; -var arrayFromSet = function arrayFromSet(set) { - var array = []; - set.forEach(function (value) { - return array.push(value); - }); - return array; -}; -var arrayFromMap = function arrayFromMap(map) { - var array = []; - map.forEach(function (value, key) { - return array.push([key, value]); - }); - return array; -}; -var objectIs = Object.is ? Object.is : require('object-is'); -var objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function () { - return []; -}; -var numberIsNaN = Number.isNaN ? Number.isNaN : require('is-nan'); -function uncurryThis(f) { - return f.call.bind(f); -} -var hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); -var propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable); -var objectToString = uncurryThis(Object.prototype.toString); -var _require$types = require('util/').types, - isAnyArrayBuffer = _require$types.isAnyArrayBuffer, - isArrayBufferView = _require$types.isArrayBufferView, - isDate = _require$types.isDate, - isMap = _require$types.isMap, - isRegExp = _require$types.isRegExp, - isSet = _require$types.isSet, - isNativeError = _require$types.isNativeError, - isBoxedPrimitive = _require$types.isBoxedPrimitive, - isNumberObject = _require$types.isNumberObject, - isStringObject = _require$types.isStringObject, - isBooleanObject = _require$types.isBooleanObject, - isBigIntObject = _require$types.isBigIntObject, - isSymbolObject = _require$types.isSymbolObject, - isFloat32Array = _require$types.isFloat32Array, - isFloat64Array = _require$types.isFloat64Array; -function isNonIndex(key) { - if (key.length === 0 || key.length > 10) return true; - for (var i = 0; i < key.length; i++) { - var code = key.charCodeAt(i); - if (code < 48 || code > 57) return true; - } - // The maximum size for an array is 2 ** 32 -1. - return key.length === 10 && key >= Math.pow(2, 32); -} -function getOwnNonIndexProperties(value) { - return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value))); -} - -// Taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js -// original notice: -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -function compare(a, b) { - if (a === b) { - return 0; - } - var x = a.length; - var y = b.length; - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - if (x < y) { - return -1; - } - if (y < x) { - return 1; - } - return 0; -} -var ONLY_ENUMERABLE = undefined; -var kStrict = true; -var kLoose = false; -var kNoIterator = 0; -var kIsArray = 1; -var kIsSet = 2; -var kIsMap = 3; - -// Check if they have the same source and flags -function areSimilarRegExps(a, b) { - return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b); -} -function areSimilarFloatArrays(a, b) { - if (a.byteLength !== b.byteLength) { - return false; - } - for (var offset = 0; offset < a.byteLength; offset++) { - if (a[offset] !== b[offset]) { - return false; - } - } - return true; -} -function areSimilarTypedArrays(a, b) { - if (a.byteLength !== b.byteLength) { - return false; - } - return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0; -} -function areEqualArrayBuffers(buf1, buf2) { - return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0; -} -function isEqualBoxedPrimitive(val1, val2) { - if (isNumberObject(val1)) { - return isNumberObject(val2) && objectIs(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2)); - } - if (isStringObject(val1)) { - return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2); - } - if (isBooleanObject(val1)) { - return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2); - } - if (isBigIntObject(val1)) { - return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2); - } - return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2); -} - -// Notes: Type tags are historical [[Class]] properties that can be set by -// FunctionTemplate::SetClassName() in C++ or Symbol.toStringTag in JS -// and retrieved using Object.prototype.toString.call(obj) in JS -// See https://tc39.github.io/ecma262/#sec-object.prototype.tostring -// for a list of tags pre-defined in the spec. -// There are some unspecified tags in the wild too (e.g. typed array tags). -// Since tags can be altered, they only serve fast failures -// -// Typed arrays and buffers are checked by comparing the content in their -// underlying ArrayBuffer. This optimization requires that it's -// reasonable to interpret their underlying memory in the same way, -// which is checked by comparing their type tags. -// (e.g. a Uint8Array and a Uint16Array with the same memory content -// could still be different because they will be interpreted differently). -// -// For strict comparison, objects should have -// a) The same built-in type tags -// b) The same prototypes. - -function innerDeepEqual(val1, val2, strict, memos) { - // All identical values are equivalent, as determined by ===. - if (val1 === val2) { - if (val1 !== 0) return true; - return strict ? objectIs(val1, val2) : true; - } - - // Check more closely if val1 and val2 are equal. - if (strict) { - if (_typeof(val1) !== 'object') { - return typeof val1 === 'number' && numberIsNaN(val1) && numberIsNaN(val2); - } - if (_typeof(val2) !== 'object' || val1 === null || val2 === null) { - return false; - } - if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) { - return false; - } - } else { - if (val1 === null || _typeof(val1) !== 'object') { - if (val2 === null || _typeof(val2) !== 'object') { - // eslint-disable-next-line eqeqeq - return val1 == val2; - } - return false; - } - if (val2 === null || _typeof(val2) !== 'object') { - return false; - } - } - var val1Tag = objectToString(val1); - var val2Tag = objectToString(val2); - if (val1Tag !== val2Tag) { - return false; - } - if (Array.isArray(val1)) { - // Check for sparse arrays and general fast path - if (val1.length !== val2.length) { - return false; - } - var keys1 = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); - var keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); - if (keys1.length !== keys2.length) { - return false; - } - return keyCheck(val1, val2, strict, memos, kIsArray, keys1); - } - // [browserify] This triggers on certain types in IE (Map/Set) so we don't - // wan't to early return out of the rest of the checks. However we can check - // if the second value is one of these values and the first isn't. - if (val1Tag === '[object Object]') { - // return keyCheck(val1, val2, strict, memos, kNoIterator); - if (!isMap(val1) && isMap(val2) || !isSet(val1) && isSet(val2)) { - return false; - } - } - if (isDate(val1)) { - if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) { - return false; - } - } else if (isRegExp(val1)) { - if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) { - return false; - } - } else if (isNativeError(val1) || val1 instanceof Error) { - // Do not compare the stack as it might differ even though the error itself - // is otherwise identical. - if (val1.message !== val2.message || val1.name !== val2.name) { - return false; - } - } else if (isArrayBufferView(val1)) { - if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) { - if (!areSimilarFloatArrays(val1, val2)) { - return false; - } - } else if (!areSimilarTypedArrays(val1, val2)) { - return false; - } - // Buffer.compare returns true, so val1.length === val2.length. If they both - // only contain numeric keys, we don't need to exam further than checking - // the symbols. - var _keys = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); - var _keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); - if (_keys.length !== _keys2.length) { - return false; - } - return keyCheck(val1, val2, strict, memos, kNoIterator, _keys); - } else if (isSet(val1)) { - if (!isSet(val2) || val1.size !== val2.size) { - return false; - } - return keyCheck(val1, val2, strict, memos, kIsSet); - } else if (isMap(val1)) { - if (!isMap(val2) || val1.size !== val2.size) { - return false; - } - return keyCheck(val1, val2, strict, memos, kIsMap); - } else if (isAnyArrayBuffer(val1)) { - if (!areEqualArrayBuffers(val1, val2)) { - return false; - } - } else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) { - return false; - } - return keyCheck(val1, val2, strict, memos, kNoIterator); -} -function getEnumerables(val, keys) { - return keys.filter(function (k) { - return propertyIsEnumerable(val, k); - }); -} -function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { - // For all remaining Object pairs, including Array, objects and Maps, - // equivalence is determined by having: - // a) The same number of owned enumerable properties - // b) The same set of keys/indexes (although not necessarily the same order) - // c) Equivalent values for every corresponding key/index - // d) For Sets and Maps, equal contents - // Note: this accounts for both named and indexed properties on Arrays. - if (arguments.length === 5) { - aKeys = Object.keys(val1); - var bKeys = Object.keys(val2); - - // The pair must have the same number of owned properties. - if (aKeys.length !== bKeys.length) { - return false; - } - } - - // Cheap key test - var i = 0; - for (; i < aKeys.length; i++) { - if (!hasOwnProperty(val2, aKeys[i])) { - return false; - } - } - if (strict && arguments.length === 5) { - var symbolKeysA = objectGetOwnPropertySymbols(val1); - if (symbolKeysA.length !== 0) { - var count = 0; - for (i = 0; i < symbolKeysA.length; i++) { - var key = symbolKeysA[i]; - if (propertyIsEnumerable(val1, key)) { - if (!propertyIsEnumerable(val2, key)) { - return false; - } - aKeys.push(key); - count++; - } else if (propertyIsEnumerable(val2, key)) { - return false; - } - } - var symbolKeysB = objectGetOwnPropertySymbols(val2); - if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) { - return false; - } - } else { - var _symbolKeysB = objectGetOwnPropertySymbols(val2); - if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) { - return false; - } - } - } - if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) { - return true; - } - - // Use memos to handle cycles. - if (memos === undefined) { - memos = { - val1: new Map(), - val2: new Map(), - position: 0 - }; - } else { - // We prevent up to two map.has(x) calls by directly retrieving the value - // and checking for undefined. The map can only contain numbers, so it is - // safe to check for undefined only. - var val2MemoA = memos.val1.get(val1); - if (val2MemoA !== undefined) { - var val2MemoB = memos.val2.get(val2); - if (val2MemoB !== undefined) { - return val2MemoA === val2MemoB; - } - } - memos.position++; - } - memos.val1.set(val1, memos.position); - memos.val2.set(val2, memos.position); - var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType); - memos.val1.delete(val1); - memos.val2.delete(val2); - return areEq; -} -function setHasEqualElement(set, val1, strict, memo) { - // Go looking. - var setValues = arrayFromSet(set); - for (var i = 0; i < setValues.length; i++) { - var val2 = setValues[i]; - if (innerDeepEqual(val1, val2, strict, memo)) { - // Remove the matching element to make sure we do not check that again. - set.delete(val2); - return true; - } - } - return false; -} - -// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using -// Sadly it is not possible to detect corresponding values properly in case the -// type is a string, number, bigint or boolean. The reason is that those values -// can match lots of different string values (e.g., 1n == '+00001'). -function findLooseMatchingPrimitives(prim) { - switch (_typeof(prim)) { - case 'undefined': - return null; - case 'object': - // Only pass in null as object! - return undefined; - case 'symbol': - return false; - case 'string': - prim = +prim; - // Loose equal entries exist only if the string is possible to convert to - // a regular number and not NaN. - // Fall through - case 'number': - if (numberIsNaN(prim)) { - return false; - } - } - return true; -} -function setMightHaveLoosePrim(a, b, prim) { - var altValue = findLooseMatchingPrimitives(prim); - if (altValue != null) return altValue; - return b.has(altValue) && !a.has(altValue); -} -function mapMightHaveLoosePrim(a, b, prim, item, memo) { - var altValue = findLooseMatchingPrimitives(prim); - if (altValue != null) { - return altValue; - } - var curB = b.get(altValue); - if (curB === undefined && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) { - return false; - } - return !a.has(altValue) && innerDeepEqual(item, curB, false, memo); -} -function setEquiv(a, b, strict, memo) { - // This is a lazily initiated Set of entries which have to be compared - // pairwise. - var set = null; - var aValues = arrayFromSet(a); - for (var i = 0; i < aValues.length; i++) { - var val = aValues[i]; - // Note: Checking for the objects first improves the performance for object - // heavy sets but it is a minor slow down for primitives. As they are fast - // to check this improves the worst case scenario instead. - if (_typeof(val) === 'object' && val !== null) { - if (set === null) { - set = new Set(); - } - // If the specified value doesn't exist in the second set its an not null - // object (or non strict only: a not matching primitive) we'll need to go - // hunting for something thats deep-(strict-)equal to it. To make this - // O(n log n) complexity we have to copy these values in a new set first. - set.add(val); - } else if (!b.has(val)) { - if (strict) return false; - - // Fast path to detect missing string, symbol, undefined and null values. - if (!setMightHaveLoosePrim(a, b, val)) { - return false; - } - if (set === null) { - set = new Set(); - } - set.add(val); - } - } - if (set !== null) { - var bValues = arrayFromSet(b); - for (var _i = 0; _i < bValues.length; _i++) { - var _val = bValues[_i]; - // We have to check if a primitive value is already - // matching and only if it's not, go hunting for it. - if (_typeof(_val) === 'object' && _val !== null) { - if (!setHasEqualElement(set, _val, strict, memo)) return false; - } else if (!strict && !a.has(_val) && !setHasEqualElement(set, _val, strict, memo)) { - return false; - } - } - return set.size === 0; - } - return true; -} -function mapHasEqualEntry(set, map, key1, item1, strict, memo) { - // To be able to handle cases like: - // Map([[{}, 'a'], [{}, 'b']]) vs Map([[{}, 'b'], [{}, 'a']]) - // ... we need to consider *all* matching keys, not just the first we find. - var setValues = arrayFromSet(set); - for (var i = 0; i < setValues.length; i++) { - var key2 = setValues[i]; - if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map.get(key2), strict, memo)) { - set.delete(key2); - return true; - } - } - return false; -} -function mapEquiv(a, b, strict, memo) { - var set = null; - var aEntries = arrayFromMap(a); - for (var i = 0; i < aEntries.length; i++) { - var _aEntries$i = _slicedToArray(aEntries[i], 2), - key = _aEntries$i[0], - item1 = _aEntries$i[1]; - if (_typeof(key) === 'object' && key !== null) { - if (set === null) { - set = new Set(); - } - set.add(key); - } else { - // By directly retrieving the value we prevent another b.has(key) check in - // almost all possible cases. - var item2 = b.get(key); - if (item2 === undefined && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo)) { - if (strict) return false; - // Fast path to detect missing string, symbol, undefined and null - // keys. - if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false; - if (set === null) { - set = new Set(); - } - set.add(key); - } - } - } - if (set !== null) { - var bEntries = arrayFromMap(b); - for (var _i2 = 0; _i2 < bEntries.length; _i2++) { - var _bEntries$_i = _slicedToArray(bEntries[_i2], 2), - _key = _bEntries$_i[0], - item = _bEntries$_i[1]; - if (_typeof(_key) === 'object' && _key !== null) { - if (!mapHasEqualEntry(set, a, _key, item, strict, memo)) return false; - } else if (!strict && (!a.has(_key) || !innerDeepEqual(a.get(_key), item, false, memo)) && !mapHasEqualEntry(set, a, _key, item, false, memo)) { - return false; - } - } - return set.size === 0; - } - return true; -} -function objEquiv(a, b, strict, keys, memos, iterationType) { - // Sets and maps don't have their entries accessible via normal object - // properties. - var i = 0; - if (iterationType === kIsSet) { - if (!setEquiv(a, b, strict, memos)) { - return false; - } - } else if (iterationType === kIsMap) { - if (!mapEquiv(a, b, strict, memos)) { - return false; - } - } else if (iterationType === kIsArray) { - for (; i < a.length; i++) { - if (hasOwnProperty(a, i)) { - if (!hasOwnProperty(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) { - return false; - } - } else if (hasOwnProperty(b, i)) { - return false; - } else { - // Array is sparse. - var keysA = Object.keys(a); - for (; i < keysA.length; i++) { - var key = keysA[i]; - if (!hasOwnProperty(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) { - return false; - } - } - if (keysA.length !== Object.keys(b).length) { - return false; - } - return true; - } - } - } - - // The pair must have equivalent values for every corresponding key. - // Possibly expensive deep test: - for (i = 0; i < keys.length; i++) { - var _key2 = keys[i]; - if (!innerDeepEqual(a[_key2], b[_key2], strict, memos)) { - return false; - } - } - return true; -} -function isDeepEqual(val1, val2) { - return innerDeepEqual(val1, val2, kLoose); -} -function isDeepStrictEqual(val1, val2) { - return innerDeepEqual(val1, val2, kStrict); -} -module.exports = { - isDeepEqual: isDeepEqual, - isDeepStrictEqual: isDeepStrictEqual -}; \ No newline at end of file diff --git a/src/external/bitStream/bitStream.js b/src/external/bitStream/bitStream.js deleted file mode 100644 index faa16cb..0000000 --- a/src/external/bitStream/bitStream.js +++ /dev/null @@ -1,545 +0,0 @@ -//@ts-nocheck -import { Buffer } from "../../../node_modules/buffer/index"; - -/********************************************************** - * - * BitView - * - * BitView provides a similar interface to the standard - * DataView, but with support for bit-level reads / writes. - * - **********************************************************/ -export class BitView { - constructor(source, byteOffset, byteLength) { - var isBuffer = - source instanceof ArrayBuffer || - (typeof Buffer !== "undefined" && source instanceof Buffer); - - // console.log( - // "isBuffer check", - // source instanceof ArrayBuffer, - // typeof Buffer !== "undefined" && source instanceof Buffer - // ); - - if (!isBuffer) { - throw new Error("Must specify a valid ArrayBuffer or Buffer."); - } - - byteOffset = byteOffset || 0; - byteLength = - byteLength || - source.byteLength /* ArrayBuffer */ || - source.length /* Buffer */; - - this._view = new Uint8Array( - source.buffer || source, - byteOffset, - byteLength - ); - - this.bigEndian = false; - } - _setBit(offset, on) { - if (on) { - this._view[offset >> 3] |= 1 << (offset & 7); - } else { - this._view[offset >> 3] &= ~(1 << (offset & 7)); - } - } - getBits(offset, bits, signed) { - var available = this._view.length * 8 - offset; - - if (bits > available) { - throw new Error( - "Cannot get " + - bits + - " bit(s) from offset " + - offset + - ", " + - available + - " available" - ); - } - - var value = 0; - for (var i = 0; i < bits; ) { - var remaining = bits - i; - var bitOffset = offset & 7; - var currentByte = this._view[offset >> 3]; - - // the max number of bits we can read from the current byte - var read = Math.min(remaining, 8 - bitOffset); - - var mask, readBits; - if (this.bigEndian) { - // create a mask with the correct bit width - mask = ~(0xff << read); - // shift the bits we want to the start of the byte and mask of the rest - readBits = (currentByte >> (8 - read - bitOffset)) & mask; - - value <<= read; - value |= readBits; - } else { - // create a mask with the correct bit width - mask = ~(0xff << read); - // shift the bits we want to the start of the byte and mask off the rest - readBits = (currentByte >> bitOffset) & mask; - - value |= readBits << i; - } - - offset += read; - i += read; - } - - if (signed) { - // If we're not working with a full 32 bits, check the - // imaginary MSB for this bit count and convert to a - // valid 32-bit signed value if set. - if (bits !== 32 && value & (1 << (bits - 1))) { - value |= -1 ^ ((1 << bits) - 1); - } - - return value; - } - - return value >>> 0; - } - setBits(offset, value, bits) { - var available = this._view.length * 8 - offset; - - if (bits > available) { - throw new Error( - "Cannot set " + - bits + - " bit(s) from offset " + - offset + - ", " + - available + - " available" - ); - } - - for (var i = 0; i < bits; ) { - var remaining = bits - i; - var bitOffset = offset & 7; - var byteOffset = offset >> 3; - var wrote = Math.min(remaining, 8 - bitOffset); - - var mask, writeBits, destMask; - if (this.bigEndian) { - // create a mask with the correct bit width - mask = ~(~0 << wrote); - // shift the bits we want to the start of the byte and mask of the rest - writeBits = (value >> (bits - i - wrote)) & mask; - - var destShift = 8 - bitOffset - wrote; - // destination mask to zero all the bits we're changing first - destMask = ~(mask << destShift); - - this._view[byteOffset] = - (this._view[byteOffset] & destMask) | (writeBits << destShift); - } else { - // create a mask with the correct bit width - mask = ~(0xff << wrote); - // shift the bits we want to the start of the byte and mask of the rest - writeBits = value & mask; - value >>= wrote; - - // destination mask to zero all the bits we're changing first - destMask = ~(mask << bitOffset); - - this._view[byteOffset] = - (this._view[byteOffset] & destMask) | (writeBits << bitOffset); - } - - offset += wrote; - i += wrote; - } - } - getBoolean(offset) { - return this.getBits(offset, 1, false) !== 0; - } - getInt8(offset) { - return this.getBits(offset, 8, true); - } - getUint8(offset) { - return this.getBits(offset, 8, false); - } - getInt16(offset) { - return this.getBits(offset, 16, true); - } - getUint16(offset) { - return this.getBits(offset, 16, false); - } - getInt32(offset) { - return this.getBits(offset, 32, true); - } - getUint32(offset) { - return this.getBits(offset, 32, false); - } - getFloat32(offset) { - BitView._scratch.setUint32(0, this.getUint32(offset)); - return BitView._scratch.getFloat32(0); - } - getFloat64(offset) { - BitView._scratch.setUint32(0, this.getUint32(offset)); - // DataView offset is in bytes. - BitView._scratch.setUint32(4, this.getUint32(offset + 32)); - return BitView._scratch.getFloat64(0); - } - setBoolean(offset, value) { - this.setBits(offset, value ? 1 : 0, 1); - } - setInt8(offset, value) { - this.setBits(offset, value, 8); - } - setUint8(offset, value) { - this.setBits(offset, value, 8); - } - setInt16(offset, value) { - this.setBits(offset, value, 16); - } - setUint16(offset, value) { - this.setBits(offset, value, 16); - } - setInt32(offset, value) { - this.setBits(offset, value, 32); - } - setUint32(offset, value) { - this.setBits(offset, value, 32); - } - setFloat32(offset, value) { - BitView._scratch.setFloat32(0, value); - this.setBits(offset, BitView._scratch.getUint32(0), 32); - } - setFloat64(offset, value) { - BitView._scratch.setFloat64(0, value); - this.setBits(offset, BitView._scratch.getUint32(0), 32); - this.setBits(offset + 32, BitView._scratch.getUint32(4), 32); - } - getArrayBuffer(offset, byteLength) { - var buffer = new Uint8Array(byteLength); - for (var i = 0; i < byteLength; i++) { - buffer[i] = this.getUint8(offset + i * 8); - } - return buffer; - } -} - -// Used to massage fp values so we can operate on them -// at the bit level. -BitView._scratch = new DataView(new ArrayBuffer(8)); - -Object.defineProperty(BitView.prototype, "buffer", { - get: function () { - return typeof Buffer !== "undefined" - ? Buffer.from(this._view.buffer) - : this._view.buffer; - }, - enumerable: true, - configurable: false, -}); - -Object.defineProperty(BitView.prototype, "byteLength", { - get: function () { - return this._view.length; - }, - enumerable: true, - configurable: false, -}); - -/********************************************************** - * - * BitStream - * - * Small wrapper for a BitView to maintain your position, - * as well as to handle reading / writing of string data - * to the underlying buffer. - * - **********************************************************/ -var reader = function (name, size) { - return function () { - if (this._index + size > this._length) { - throw new Error("Trying to read past the end of the stream"); - } - var val = this._view[name](this._index); - this._index += size; - return val; - }; -}; - -var writer = function (name, size) { - return function (value) { - this._view[name](this._index, value); - this._index += size; - }; -}; - -function readASCIIString(stream, bytes) { - return readString(stream, bytes, false); -} - -function readUTF8String(stream, bytes) { - return readString(stream, bytes, true); -} - -function readString(stream, bytes, utf8) { - if (bytes === 0) { - return ""; - } - var i = 0; - var chars = []; - var append = true; - var fixedLength = !!bytes; - if (!bytes) { - bytes = Math.floor((stream._length - stream._index) / 8); - } - - // Read while we still have space available, or until we've - // hit the fixed byte length passed in. - while (i < bytes) { - var c = stream.readUint8(); - - // Stop appending chars once we hit 0x00 - if (c === 0x00) { - append = false; - - // If we don't have a fixed length to read, break out now. - if (!fixedLength) { - break; - } - } - if (append) { - chars.push(c); - } - - i++; - } - - var string = String.fromCharCode.apply(null, chars); - if (utf8) { - try { - return decodeURIComponent(escape(string)); // https://stackoverflow.com/a/17192845 - } catch (e) { - return string; - } - } else { - return string; - } -} - -function writeASCIIString(stream, string, bytes) { - var length = bytes || string.length + 1; // + 1 for NULL - - for (var i = 0; i < length; i++) { - stream.writeUint8(i < string.length ? string.charCodeAt(i) : 0x00); - } -} - -function writeUTF8String(stream, string, bytes) { - var byteArray = stringToByteArray(string); - - var length = bytes || byteArray.length + 1; // + 1 for NULL - for (var i = 0; i < length; i++) { - stream.writeUint8(i < byteArray.length ? byteArray[i] : 0x00); - } -} - -function stringToByteArray(str) { - // https://gist.github.com/volodymyr-mykhailyk/2923227 - var b = [], - i, - unicode; - for (i = 0; i < str.length; i++) { - unicode = str.charCodeAt(i); - // 0x00000000 - 0x0000007f -> 0xxxxxxx - if (unicode <= 0x7f) { - b.push(unicode); - // 0x00000080 - 0x000007ff -> 110xxxxx 10xxxxxx - } else if (unicode <= 0x7ff) { - b.push((unicode >> 6) | 0xc0); - b.push((unicode & 0x3f) | 0x80); - // 0x00000800 - 0x0000ffff -> 1110xxxx 10xxxxxx 10xxxxxx - } else if (unicode <= 0xffff) { - b.push((unicode >> 12) | 0xe0); - b.push(((unicode >> 6) & 0x3f) | 0x80); - b.push((unicode & 0x3f) | 0x80); - // 0x00010000 - 0x001fffff -> 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - } else { - b.push((unicode >> 18) | 0xf0); - b.push(((unicode >> 12) & 0x3f) | 0x80); - b.push(((unicode >> 6) & 0x3f) | 0x80); - b.push((unicode & 0x3f) | 0x80); - } - } - - return b; -} - -export class BitStream { - constructor(source, byteOffset, byteLength) { - var isBuffer = - source instanceof ArrayBuffer || - (typeof Buffer !== "undefined" && source instanceof Buffer); - - // console.log( - // "isBuffer check", - // source instanceof ArrayBuffer, - // typeof Buffer !== "undefined" && source instanceof Buffer - // ); - - if (!(source instanceof BitView) && !isBuffer) { - throw new Error("Must specify a valid BitView, ArrayBuffer or Buffer"); - } - - if (isBuffer) { - this._view = new BitView(source, byteOffset, byteLength); - } else { - this._view = source; - } - - this._index = 0; - this._startIndex = 0; - this._length = this._view.byteLength * 8; - } - readBits(bits, signed) { - var val = this._view.getBits(this._index, bits, signed); - this._index += bits; - return val; - } - writeBits(value, bits) { - this._view.setBits(this._index, value, bits); - this._index += bits; - } - readASCIIString(bytes) { - return readASCIIString(this, bytes); - } - readUTF8String(bytes) { - return readUTF8String(this, bytes); - } - writeASCIIString(string, bytes) { - writeASCIIString(this, string, bytes); - } - writeUTF8String(string, bytes) { - writeUTF8String(this, string, bytes); - } - readBitStream(bitLength) { - var slice = new BitStream(this._view); - slice._startIndex = this._index; - slice._index = this._index; - slice.length = bitLength; - this._index += bitLength; - return slice; - } - writeBitStream(stream, length) { - if (!length) { - length = stream.bitsLeft; - } - - var bitsToWrite; - while (length > 0) { - bitsToWrite = Math.min(length, 32); - this.writeBits(stream.readBits(bitsToWrite), bitsToWrite); - length -= bitsToWrite; - } - } - readArrayBuffer(byteLength) { - var buffer = this._view.getArrayBuffer(this._index, byteLength); - this._index += byteLength * 8; - return buffer; - } - writeArrayBuffer(buffer, byteLength) { - this.writeBitStream(new BitStream(buffer), byteLength * 8); - } -} - -Object.defineProperty(BitStream.prototype, "index", { - get: function () { - return this._index - this._startIndex; - }, - set: function (val) { - this._index = val + this._startIndex; - }, - enumerable: true, - configurable: true, -}); - -Object.defineProperty(BitStream.prototype, "length", { - get: function () { - return this._length - this._startIndex; - }, - set: function (val) { - this._length = val + this._startIndex; - }, - enumerable: true, - configurable: true, -}); - -Object.defineProperty(BitStream.prototype, "bitsLeft", { - get: function () { - return this._length - this._index; - }, - enumerable: true, - configurable: true, -}); - -Object.defineProperty(BitStream.prototype, "byteIndex", { - // Ceil the returned value, over compensating for the amount of - // bits written to the stream. - get: function () { - return Math.ceil(this._index / 8); - }, - set: function (val) { - this._index = val * 8; - }, - enumerable: true, - configurable: true, -}); - -Object.defineProperty(BitStream.prototype, "buffer", { - get: function () { - return this._view.buffer; - }, - enumerable: true, - configurable: false, -}); - -Object.defineProperty(BitStream.prototype, "view", { - get: function () { - return this._view; - }, - enumerable: true, - configurable: false, -}); - -Object.defineProperty(BitStream.prototype, "bigEndian", { - get: function () { - return this._view.bigEndian; - }, - set: function (val) { - this._view.bigEndian = val; - }, - enumerable: true, - configurable: false, -}); - -BitStream.prototype.readBoolean = reader("getBoolean", 1); -BitStream.prototype.readInt8 = reader("getInt8", 8); -BitStream.prototype.readUint8 = reader("getUint8", 8); -BitStream.prototype.readInt16 = reader("getInt16", 16); -BitStream.prototype.readUint16 = reader("getUint16", 16); -BitStream.prototype.readInt32 = reader("getInt32", 32); -BitStream.prototype.readUint32 = reader("getUint32", 32); -BitStream.prototype.readFloat32 = reader("getFloat32", 32); -BitStream.prototype.readFloat64 = reader("getFloat64", 64); - -BitStream.prototype.writeBoolean = writer("setBoolean", 1); -BitStream.prototype.writeInt8 = writer("setInt8", 8); -BitStream.prototype.writeUint8 = writer("setUint8", 8); -BitStream.prototype.writeInt16 = writer("setInt16", 16); -BitStream.prototype.writeUint16 = writer("setUint16", 16); -BitStream.prototype.writeInt32 = writer("setInt32", 32); -BitStream.prototype.writeUint32 = writer("setUint32", 32); -BitStream.prototype.writeFloat32 = writer("setFloat32", 32); -BitStream.prototype.writeFloat64 = writer("setFloat64", 64); diff --git a/src/external/ffl.js/FFLShaderMaterial.js b/src/external/ffl.js/FFLShaderMaterial.js new file mode 100644 index 0000000..e7dd404 --- /dev/null +++ b/src/external/ffl.js/FFLShaderMaterial.js @@ -0,0 +1,859 @@ +// @ts-check + +/** + * @typedef {number} FFLModulateMode + * @typedef {number} FFLModulateType + * @typedef {import('three')} THREE + */ + +/** + * @typedef {Object} FFLShaderMaterialParameters + * @property {FFLModulateMode} [modulateMode] - Modulate mode. + * @property {FFLModulateType} [modulateType] - Modulate type. + * @property {import('three').Color|Array} [color] - + * Constant color assigned to u_const1/2/3 depending on single or array. + * @property {boolean} [lightEnable] - Enable lighting. Needs to be off when drawing faceline/mask textures. + * @property {import('three').Vector3} [lightDirection] - Light direction. + * @property {boolean} [useSpecularModeBlinn] - Whether to override + * specular mode on all materials with 0 (Blinn-Phong specular). + * @property {import('three').Texture} [map] - Texture map. + */ + +// eslint-disable-next-line jsdoc/convert-to-jsdoc-comments -- not applicable +/* global define, require, module -- UMD globals. */ +(function (root, factory) { + // @ts-ignore - cannot find name define + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + // @ts-ignore + define(['three'], factory); + } else if (typeof module === 'object' && module.exports) { + // Node.js/CommonJS + module.exports = factory(require('three')); + } else { + // Browser globals + + // Assume THREE is defined in window. + /** @type {*} */ (root).FFLShaderMaterial = factory(/** @type {*} */ (root).THREE); + } +}(typeof self !== 'undefined' ? self : this, + /* eslint-disable jsdoc/require-returns-type -- Allow TS to predict return type. */ + /** + * @param {THREE} THREE - Three.js namespace. + * @returns Returns the exported namespace. + */ + function (THREE) { +/* eslint-enable jsdoc/require-returns-type -- Allow TS to predict return type. */ +'use strict'; +// // --------------------------------------------------------------------- +// // Vertex Shader for FFLShaderMaterial +// // Derived from MiiDefaultShader.vsh found in Miitomo. +// // --------------------------------------------------------------------- +const _FFLShader_vert = /* glsl */` +// 頂点シェーダーに入力される attribute 変数 +//attribute vec4 position; //!< 入力: 位置情報 +//attribute vec2 uv; //!< 入力: テクスチャー座標 +//attribute vec3 normal; //!< 入力: 法線ベクトル +// All provided by three.js ^^ + +// vertex color is not actually the color of the shape, as such +// it is a custom attribute _COLOR in the glTF + +attribute vec4 _color; //!< 入力: 頂点の色 +attribute vec3 tangent; //!< 入力: 異方位 + +// フラグメントシェーダーへの入力 +varying vec4 v_color; //!< 出力: 頂点の色 +varying vec4 v_position; //!< 出力: 位置情報 +varying vec3 v_normal; //!< 出力: 法線ベクトル +varying vec3 v_tangent; //!< 出力: 異方位 +varying vec2 v_texCoord; //!< 出力: テクスチャー座標 + +// ユニフォーム +//uniform mat3 normalMatrix; //!< ユニフォーム: モデルの法線用行列 +//uniform mat4 modelViewMatrix; //!< ユニフォーム: プロジェクション行列 +//uniform mat4 projectionMatrix; //!< ユニフォーム: モデル行列 +// All provided by three.js ^^ + +// skinning_pars_vertex.glsl.js +#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif + +void main() +{ + + // begin_vertex.glsl.js + vec3 transformed = vec3( position ); +// skinbase_vertex.glsl.js +#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); + // skinning_vertex.glsl.js + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif + +//#ifdef FFL_COORDINATE_MODE_NORMAL + // 頂点座標を変換 + v_position = modelViewMatrix * vec4(transformed, 1.0); + gl_Position = projectionMatrix * v_position; + + vec3 objectNormal = normal; + vec3 objectTangent = tangent.xyz; +// skinnormal_vertex.glsl.js +#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + +#endif + + // 法線も変換 + //v_normal = mat3(inverse(u_mv)) * a_normal; + v_normal = normalize(normalMatrix * objectNormal); +//#elif defined(FFL_COORDINATE_MODE_NONE) +// // 頂点座標を変換 +// gl_Position = vec4(a_position.x, a_position.y * -1.0, a_position.z, a_position.w); +// v_position = a_position; +// +// v_normal = a_normal; +//#endif + + // その他の情報も書き出す + v_texCoord = uv; + // safe normalize + if (tangent != vec3(0.0, 0.0, 0.0)) + { + v_tangent = normalize(normalMatrix * objectTangent); + } + else + { + v_tangent = vec3(0.0, 0.0, 0.0); + } + + v_color = _color; +} +`; + +// // --------------------------------------------------------------------- +// // Fragment Shader for FFLShaderMaterial +// // Mostly unmodified from MiiDefaultShader.fsh found in Miitomo. +// // --------------------------------------------------------------------- +const _FFLShader_frag = /* glsl */` +// +// sample.flg +// Fragment shader +// Copyright (c) 2014 Nintendo Co., Ltd. All rights reserved. +// +// + +#ifdef GL_ES +precision mediump float; +#else +# define lowp +# define mediump +# define highp +#endif + + +// +// 定数定義ファイル +// + +/// シェーダーモード +#define FFL_SHADER_MODE_UR 0 +#define FFL_SHADER_MODE_UB 1 + +/// 変調処理のマクロ +#define FFL_MODULATE_MODE_CONSTANT 0 +#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 +#define FFL_MODULATE_MODE_RGB_LAYERED 2 +#define FFL_MODULATE_MODE_ALPHA 3 +#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 +#define FFL_MODULATE_MODE_ALPHA_OPA 5 + +/// スペキュラのモード +#define FFL_SPECULAR_MODE_BLINN 0 +#define FFL_SPECULAR_MODE_ANISO 1 + +/// ライトのON/OFF +#define FFL_LIGHT_MODE_DISABLE 0 +#define FFL_LIGHT_MODE_ENABLE 1 + +/// フラグメントのディスカードモード +#define FFL_DISCARD_FRAGMENT_DISABLE 0 +#define FFL_DISCARD_FRAGMENT_ENABLE 1 + +/// 座標変換モード +#define FFL_COORDINATE_MODE_NONE 0 +#define FFL_COORDINATE_MODE_NORMAL 1 + +// +// 関数の定義ファイル +// + +/** + * @brief 異方性反射の反射率を計算します。 + * @param[in] light ライトの向き + * @param[in] tangent 接線 + * @param[in] eye 視線の向き + * @param[in] power 鋭さ + */ +mediump float calculateAnisotropicSpecular(mediump vec3 light, mediump vec3 tangent, mediump vec3 eye, mediump float power ) +{ + mediump float dotLT = dot(light, tangent); + mediump float dotVT = dot(eye, tangent); + mediump float dotLN = sqrt(1.0 - dotLT * dotLT); + mediump float dotVR = dotLN*sqrt(1.0 - dotVT * dotVT) - dotLT * dotVT; + + return pow(max(0.0, dotVR), power); +} + +/** + * @brief 異方性反射の反射率を計算します。 + * @param[in] light ライトの向き + * @param[in] normal 法線 + * @param[in] eye 視線の向き + * @param[in] power 鋭さ + */ +mediump float calculateBlinnSpecular(mediump vec3 light, mediump vec3 normal, mediump vec3 eye, mediump float power) +{ + return pow(max(dot(reflect(-light, normal), eye), 0.0), power); +} + +/** + * @brief 異方性反射、ブリン反射をブレンドします。 + * @param[in] blend ブレンド率 + * @param[in] blinn ブリンの値 + * @param[in] aniso 異方性の値 + */ +mediump float calculateSpecularBlend(mediump float blend, mediump float blinn, mediump float aniso) +{ + return mix(aniso, blinn, blend); +} + +/** + * @brief アンビエントを計算します。 + * @param[in] light ライト + * @param[in] material マテリアル + */ +mediump vec3 calculateAmbientColor(mediump vec3 light, mediump vec3 material) +{ + return light * material; +} + +/** + * @brief 拡散を計算します。 + * @param[in] light ライト + * @param[in] material マテリアル + * @param[in] ln ライトと法線の内積 + */ +mediump vec3 calculateDiffuseColor(mediump vec3 light, mediump vec3 material, mediump float ln) +{ + return light * material * ln; +} + +/** + * @brief 鏡面反射を計算します。 + * @param[in] light ライト + * @param[in] material マテリアル + * @param[in] reflection 反射率 + * @param[in] strength 幅 + */ +mediump vec3 calculateSpecularColor(mediump vec3 light, mediump vec3 material, mediump float reflection, mediump float strength) +{ + return light * material * reflection * strength; +} + +/** + * @brief リムを計算します。 + * @param[in] color リム色 + * @param[in] normalZ 法線のZ方向 + * @param[in] width リム幅 + * @param[in] power リムの鋭さ + */ +mediump vec3 calculateRimColor(mediump vec3 color, mediump float normalZ, mediump float width, mediump float power) +{ + return color * pow(width * (1.0 - abs(normalZ)), power); +} + +/** + * @brief ライト方向と法線の内積を求める + * @note 特殊な実装になっています。 + */ +mediump float calculateDot(mediump vec3 light, mediump vec3 normal) +{ + return max(dot(light, normal), 0.1); +} + +// フラグメントシェーダーに入力される varying 変数 +varying mediump vec4 v_color; //!< 出力: 頂点の色 +varying highp vec4 v_position; //!< 出力: 位置情報 +varying highp vec3 v_normal; //!< 出力: 法線ベクトル +// NOTE: ^^ Those two need to be highp to avoid weird black dot issue on Android +varying mediump vec3 v_tangent; //!< 出力: 異方位 +varying mediump vec2 v_texCoord; //!< 出力: テクスチャー座標 + +/// constカラー +uniform mediump vec4 u_const1; ///< constカラー1 +uniform mediump vec4 u_const2; ///< constカラー2 +uniform mediump vec4 u_const3; ///< constカラー3 + +/// ライト設定 +uniform mediump vec3 u_light_ambient; ///< カメラ空間のライト方向 +uniform mediump vec3 u_light_diffuse; ///< 拡散光用ライト +uniform mediump vec3 u_light_dir; +uniform bool u_light_enable; +uniform mediump vec3 u_light_specular; ///< 鏡面反射用ライト強度 + +/// マテリアル設定 +uniform mediump vec3 u_material_ambient; ///< 環境光用マテリアル設定 +uniform mediump vec3 u_material_diffuse; ///< 拡散光用マテリアル設定 +uniform mediump vec3 u_material_specular; ///< 鏡面反射用マテリアル設定 +uniform int u_material_specular_mode; ///< スペキュラの反射モード(CharModelに依存する設定のためub_modulateにしている) +uniform mediump float u_material_specular_power; ///< スペキュラの鋭さ(0.0を指定すると頂点カラーの設定が利用される) + +/// 変調設定 +uniform int u_mode; ///< 描画モード + +/// リム設定 +uniform mediump vec3 u_rim_color; +uniform mediump float u_rim_power; + +// サンプラー +uniform sampler2D s_texture; + + +// ------------------------------------------------------- +// メイン文 +void main() +{ + mediump vec4 color; + + mediump float specularPower = u_material_specular_power; + mediump float rimWidth = v_color.a; + +//#ifdef FFL_MODULATE_MODE_CONSTANT + if(u_mode == FFL_MODULATE_MODE_CONSTANT) + { + color = u_const1; + } + // modified to handle u_const1 alpha: +//#elif defined(FFL_MODULATE_MODE_TEXTURE_DIRECT) + else if(u_mode == FFL_MODULATE_MODE_TEXTURE_DIRECT) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.rgb, u_const1.a * texel.a); + } +//#elif defined(FFL_MODULATE_MODE_RGB_LAYERED) + else if(u_mode == FFL_MODULATE_MODE_RGB_LAYERED) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.r * u_const1.rgb + texel.g * u_const2.rgb + texel.b * u_const3.rgb, u_const1.a * texel.a); + } +//#elif defined(FFL_MODULATE_MODE_ALPHA) + else if(u_mode == FFL_MODULATE_MODE_ALPHA) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(u_const1.rgb, u_const1.a * texel.r); + } +//#elif defined(FFL_MODULATE_MODE_LUMINANCE_ALPHA) + else if(u_mode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.g * u_const1.rgb, u_const1.a * texel.r); + } +//#elif defined(FFL_MODULATE_MODE_ALPHA_OPA) + else if(u_mode == FFL_MODULATE_MODE_ALPHA_OPA) + { + mediump vec4 texel = texture2D(s_texture, v_texCoord); + color = vec4(texel.r * u_const1.rgb, u_const1.a); + } +//#endif + + // avoids little outline around mask elements + if(u_mode != FFL_MODULATE_MODE_CONSTANT && color.a == 0.0) + { + discard; + } + +//#ifdef FFL_LIGHT_MODE_ENABLE + if(u_light_enable) + { + /// 環境光の計算 + mediump vec3 ambient = calculateAmbientColor(u_light_ambient.xyz, u_material_ambient.xyz); + + /// 法線ベクトルの正規化 + mediump vec3 norm = normalize(v_normal); + + /// 視線ベクトル + mediump vec3 eye = normalize(-v_position.xyz); + + // ライトの向き + mediump float fDot = calculateDot(u_light_dir, norm); + + /// Diffuse計算 + mediump vec3 diffuse = calculateDiffuseColor(u_light_diffuse.xyz, u_material_diffuse.xyz, fDot); + + /// Specular計算 + mediump float specularBlinn = calculateBlinnSpecular(u_light_dir, norm, eye, u_material_specular_power); + + /// Specularの値を確保する変数を宣言 + mediump float reflection; + mediump float strength = v_color.g; + if(u_material_specular_mode == 0) + { + /// Blinnモデルの場合 + strength = 1.0; + reflection = specularBlinn; + } + else + { + /// Aisoモデルの場合 + mediump float specularAniso = calculateAnisotropicSpecular(u_light_dir, v_tangent, eye, u_material_specular_power); + reflection = calculateSpecularBlend(v_color.r, specularBlinn, specularAniso); + } + /// Specularの色を取得 + mediump vec3 specular = calculateSpecularColor(u_light_specular.xyz, u_material_specular.xyz, reflection, strength); + + // リムの色を計算 + mediump vec3 rimColor = calculateRimColor(u_rim_color.rgb, norm.z, rimWidth, u_rim_power); + + // カラーの計算 + color.rgb = (ambient + diffuse) * color.rgb + specular + rimColor; + } +//#endif + + gl_FragColor = color; +} +`; +// #include +// #include <${THREE.REVISION >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> + +// // --------------------------------------------------------------------- +// // FFLShaderMaterial Class +// // --------------------------------------------------------------------- +/** + * Custom THREE.ShaderMaterial using the FFLShader. + * @augments {THREE.ShaderMaterial} + */ +class FFLShaderMaterial extends THREE.ShaderMaterial { + // Default light and rim light uniforms. + + /** + * Default ambient light color. + * @type {import('three').Color} + */ + static defaultLightAmbient = new THREE.Color(0.73, 0.73, 0.73)/* .convertSRGBToLinear() */; + /** + * Default diffuse light color. + * @type {import('three').Color} + */ + static defaultLightDiffuse = new THREE.Color(0.6, 0.6, 0.6)/* .convertSRGBToLinear() */; + /** + * Default specular light color. + * @type {import('three').Color} + */ + static defaultLightSpecular = new THREE.Color(0.7, 0.7, 0.7)/* .convertSRGBToLinear() */; + /** + * Default light direction. + * @type {import('three').Vector3} + */ + static defaultLightDir = new THREE.Vector3(-0.4531539381, 0.4226179123, 0.7848858833); + /** + * Default rim color. + * @type {import('three').Color} + */ + static defaultRimColor = new THREE.Color(0.3, 0.3, 0.3)/* .convertSRGBToLinear() */; + /** + * Default rim power (intensity). + * @type {number} + */ + static defaultRimPower = 2.0; + + /** + * Alias for default light direction. + * @type {import('three').Vector3} + */ + static defaultLightDirection = this.defaultLightDir; + + /** + * Material uniform table mapping to FFLModulateType. + * Reference: https://github.com/aboood40091/FFL-Testing/blob/master/src/Shader.cpp + * @package + */ + static materialParams = [ + { + // FFL_MODULATE_TYPE_SHAPE_FACELINE + ambient: new THREE.Color(0.85, 0.75, 0.75)/* .convertSRGBToLinear() */, + diffuse: new THREE.Color(0.75, 0.75, 0.75)/* .convertSRGBToLinear() */, + specular: new THREE.Color(0.3, 0.3, 0.3)/* .convertSRGBToLinear() */, + specularPower: 1.2, + specularMode: 0 + }, + { + // FFL_MODULATE_TYPE_SHAPE_BEARD + ambient: new THREE.Color(1.0, 1.0, 1.0)/* .convertSRGBToLinear() */, + diffuse: new THREE.Color(0.7, 0.7, 0.7)/* .convertSRGBToLinear() */, + specular: new THREE.Color(0.0, 0.0, 0.0)/* .convertSRGBToLinear() */, + specularPower: 40.0, + specularMode: 1 + }, + { + // FFL_MODULATE_TYPE_SHAPE_NOSE + ambient: new THREE.Color(0.9, 0.85, 0.85)/* .convertSRGBToLinear() */, + diffuse: new THREE.Color(0.75, 0.75, 0.75)/* .convertSRGBToLinear() */, + specular: new THREE.Color(0.22, 0.22, 0.22)/* .convertSRGBToLinear() */, + specularPower: 1.5, + specularMode: 0 + }, + { + // FFL_MODULATE_TYPE_SHAPE_FOREHEAD + ambient: new THREE.Color(0.85, 0.75, 0.75)/* .convertSRGBToLinear() */, + diffuse: new THREE.Color(0.75, 0.75, 0.75)/* .convertSRGBToLinear() */, + specular: new THREE.Color(0.3, 0.3, 0.3)/* .convertSRGBToLinear() */, + specularPower: 1.2, + specularMode: 0 + }, + { + // FFL_MODULATE_TYPE_SHAPE_HAIR + ambient: new THREE.Color(1.0, 1.0, 1.0)/* .convertSRGBToLinear() */, + diffuse: new THREE.Color(0.7, 0.7, 0.7)/* .convertSRGBToLinear() */, + specular: new THREE.Color(0.35, 0.35, 0.35)/* .convertSRGBToLinear() */, + specularPower: 10.0, + specularMode: 1 + }, + { + // FFL_MODULATE_TYPE_SHAPE_CAP + ambient: new THREE.Color(0.75, 0.75, 0.75)/* .convertSRGBToLinear() */, + diffuse: new THREE.Color(0.72, 0.72, 0.72)/* .convertSRGBToLinear() */, + specular: new THREE.Color(0.3, 0.3, 0.3)/* .convertSRGBToLinear() */, + specularPower: 1.5, + specularMode: 0 + }, + { + // FFL_MODULATE_TYPE_SHAPE_MASK + ambient: new THREE.Color(1.0, 1.0, 1.0)/* .convertSRGBToLinear() */, + diffuse: new THREE.Color(0.7, 0.7, 0.7)/* .convertSRGBToLinear() */, + specular: new THREE.Color(0.0, 0.0, 0.0)/* .convertSRGBToLinear() */, + specularPower: 40.0, + specularMode: 1 + }, + { + // FFL_MODULATE_TYPE_SHAPE_NOSELINE + ambient: new THREE.Color(1.0, 1.0, 1.0)/* .convertSRGBToLinear() */, + diffuse: new THREE.Color(0.7, 0.7, 0.7)/* .convertSRGBToLinear() */, + specular: new THREE.Color(0.0, 0.0, 0.0)/* .convertSRGBToLinear() */, + specularPower: 40.0, + specularMode: 1 + }, + { + // FFL_MODULATE_TYPE_SHAPE_GLASS + ambient: new THREE.Color(1.0, 1.0, 1.0)/* .convertSRGBToLinear() */, + diffuse: new THREE.Color(0.7, 0.7, 0.7)/* .convertSRGBToLinear() */, + specular: new THREE.Color(0.0, 0.0, 0.0)/* .convertSRGBToLinear() */, + specularPower: 40.0, + specularMode: 1 + }, + + { + // body + ambient: new THREE.Color(0.95622, 0.95622, 0.95622)/* .convertSRGBToLinear() */, + diffuse: new THREE.Color(0.49673, 0.49673, 0.49673)/* .convertSRGBToLinear() */, + specular: new THREE.Color(0.24099, 0.24099, 0.24099)/* .convertSRGBToLinear() */, + specularPower: 3.0, + specularMode: 0 + }, + { + // pants + ambient: new THREE.Color(0.95622, 0.95622, 0.95622)/* .convertSRGBToLinear() */, + diffuse: new THREE.Color(1.08497, 1.08497, 1.08497)/* .convertSRGBToLinear() */, + specular: new THREE.Color(0.2409, 0.2409, 0.2409)/* .convertSRGBToLinear() */, + specularPower: 3.0, + specularMode: 0 + } + ]; + + /** @typedef {import('three').IUniform} IUniformVector4 */ + + /** + * Constructs an FFLShaderMaterial instance. + * @param {import('three').ShaderMaterialParameters & FFLShaderMaterialParameters} [options] - + * Parameters for the material. + */ + constructor(options = {}) { + // Set default uniforms. + /** @type {Object} */ + const uniforms = { + u_light_ambient: { + value: FFLShaderMaterial.defaultLightAmbient + }, + u_light_diffuse: { + value: FFLShaderMaterial.defaultLightDiffuse + }, + u_light_specular: { + value: FFLShaderMaterial.defaultLightSpecular + }, + u_light_dir: { value: FFLShaderMaterial.defaultLightDir.clone() }, + u_light_enable: { value: true }, // Default to true. + u_rim_color: { value: FFLShaderMaterial.defaultRimColor }, + u_rim_power: { value: FFLShaderMaterial.defaultRimPower } + }; + + // Construct the ShaderMaterial using the shader source. + super({ + vertexShader: _FFLShader_vert, + fragmentShader: _FFLShader_frag, + uniforms: uniforms + }); + + // Initialize default values. + /** @type {FFLModulateType} */ + this._modulateType = 0; + this.useSpecularModeBlinn = false; + + // Use the setters to set the rest of the uniforms. + this.setValues(options); + } + + /** + * Gets the constant color (u_const1) uniform as THREE.Color. + * @returns {import('three').Color|null} The constant color, or null if it is not set. + */ + get color() { + if (!this.uniforms.u_const1) { + // If color is not set, return null. + return null; + } else if (this._color3) { + // Use cached THREE.Color instance if it is set. + return this._color3; + } + // Get THREE.Color from u_const1 (Vector4). + const color4 = /** @type {IUniformVector4} */ (this.uniforms.u_const1).value; + const color3 = new THREE.Color(color4.x, color4.y, color4.z); + this._color3 = color3; // Cache the THREE.Color instance. + return color3; + } + + /** + * Sets the constant color uniforms from THREE.Color. + * @param {import('three').Color|Array} value - The + * constant color (u_const1), or multiple (u_const1/2/3) to set the uniforms for. + */ + set color(value) { + /** + * @param {import('three').Color} color - THREE.Color instance. + * @param {number} opacity - Opacity mapped to .a. + * @returns {import('three').Vector4} Vector4 containing color and opacity. + */ + function toColor4(color, opacity = 1.0) { + return new THREE.Vector4(color.r, color.g, color.b, opacity); + } + // Set an array of colors, assumed to have 3 elements. + if (Array.isArray(value)) { + // Assign multiple color instances to u_const1/2/3. + /** @type {IUniformVector4} */ (this.uniforms.u_const1) = + { value: toColor4(value[0]) }; + /** @type {IUniformVector4} */ (this.uniforms.u_const2) = + { value: toColor4(value[1]) }; + /** @type {IUniformVector4} */ (this.uniforms.u_const3) = + { value: toColor4(value[2]) }; + return; + } + // Set single color as THREE.Color, defaulting to white. + const color3 = value ? value : new THREE.Color(1.0, 1.0, 1.0); + /** @type {import('three').Color} */ + this._color3 = color3; + // Assign single color with white as a placeholder. + const opacity = this.opacity; + if (this._opacity) { + // if _opacity is set then the above returned it, delete when done + delete this._opacity; + } + /** @type {IUniformVector4} */ (this.uniforms.u_const1) = + { value: toColor4(color3, opacity) }; + } + + /** + * Gets the opacity of the constant color. + * @returns {number} The opacity value. + */ + // @ts-ignore - Already defined on parent class. + get opacity() { + if (!this.uniforms.u_const1) { + // Get from _opacity if it is set before constant color. + return this._opacity ? this._opacity : 1; + } + // Return w (alpha) of the constant color uniform. + return /** @type {IUniformVector4} */ (this.uniforms.u_const1).value.w; + } + + /** + * Sets the opacity of the constant color. + * NOTE: that this is actually set in the constructor + * of Material, meaning it is the only one set BEFORE uniforms are + * @param {number} value - The new opacity value. + */ + // @ts-ignore - Already defined on parent class. + set opacity(value) { + if (!this.uniforms || !this.uniforms.u_const1) { + // Store here for later when color is set. + this._opacity = 1; + return; + } + /** @type {IUniformVector4} */ (this.uniforms.u_const1).value.w = value; + } + + /** + * Gets the value of the modulateMode uniform. + * @returns {FFLModulateMode|null} The modulateMode value, or null if it is unset. + */ + get modulateMode() { + return this.uniforms.u_mode ? this.uniforms.u_mode.value : null; + } + + /** + * Sets the value of the modulateMode uniform. + * @param {FFLModulateMode} value - The new modulateMode value. + */ + set modulateMode(value) { + this.uniforms.u_mode = { value: value }; + } + + /** + * Sets the value determining whether lighting is enabled or not. + * @returns {boolean|null} The lightEnable value, or null if it is unset. + */ + get lightEnable() { + return this.uniforms.u_light_enable ? this.uniforms.u_light_enable.value : null; + } + + /** + * Sets the value determining whether lighting is enabled or not. + * @param {boolean} value - The lightEnable value. + */ + set lightEnable(value) { + this.uniforms.u_light_enable = { value: value }; + } + + /** + * Sets whether to override specular mode with 0. + * @param {boolean} value - The useSpecularModeBlinn value. + */ + set useSpecularModeBlinn(value) { + this._useSpecularModeBlinn = value; // Private property. + if (this._modulateType !== undefined) { + // Set material again if it was already set. + this.modulateType = this._modulateType; + } + } + + /** + * Gets the value for whether to override specular mode with 0. + * @returns {boolean|undefined} The useSpecularModeBlinn value. + */ + get useSpecularModeBlinn() { + return this._useSpecularModeBlinn; + } + + /** + * Gets the modulateType value. + * @returns {FFLModulateType|undefined} The modulateType value if it is set. + */ + get modulateType() { + // This isn't actually a uniform so this is a private property. + return this._modulateType; + } + + /** + * Sets the material uniforms based on the modulate type value. + * @param {FFLModulateType} value - The new modulateType value. + */ + set modulateType(value) { + // Get material uniforms for modulate type from materialParams table. + const matParam = FFLShaderMaterial.materialParams[value]; + if (!matParam) { + // Out of bounds modulateType that don't have materials + // are usually for mask/faceline textures, so don't throw error + return; + } + this._modulateType = value; + + // Set material uniforms from matParam object. + this.uniforms.u_material_ambient = { value: matParam.ambient }; + this.uniforms.u_material_diffuse = { value: matParam.diffuse }; + this.uniforms.u_material_specular = { value: matParam.specular }; + this.uniforms.u_material_specular_mode = { + // Force value of 0 if useSpecularModeBlinn is set. + value: this._useSpecularModeBlinn ? 0 : matParam.specularMode + }; + this.uniforms.u_material_specular_power = { value: matParam.specularPower }; + } + + /** + * Gets the texture map if it is set. + * @returns {import('three').Texture|null} The texture map, or null if it is unset. + */ + get map() { + return this.uniforms.s_texture ? this.uniforms.s_texture.value : null; + } + + /** + * Sets the texture map (s_texture uniform). + * @param {import('three').Texture} value - The new texture map. + */ + set map(value) { + this.uniforms.s_texture = { value: value }; + } + + /** + * Gets the light direction. + * @returns {import('three').Vector3} The light direction. + */ + get lightDirection() { + // Should always be set as long as this is constructed. + return this.uniforms.u_light_dir.value; + } + + /** + * Sets the light direction. + * @param {import('three').Vector3} value - The new light direction. + */ + set lightDirection(value) { + this.uniforms.u_light_dir = { value: value }; + } +} + +/** @global */ +// window.FFLShaderMaterial = FFLShaderMaterial; +// export { FFLShaderMaterial }; + +return FFLShaderMaterial; +})); diff --git a/src/external/ffl.js/FFLShaderMaterial.ts b/src/external/ffl.js/FFLShaderMaterial.ts deleted file mode 100644 index a8fdc4c..0000000 --- a/src/external/ffl.js/FFLShaderMaterial.ts +++ /dev/null @@ -1,752 +0,0 @@ -import * as THREE from "three"; - -// ───────────────────────────────────────────────────────── -// Vertex Shader for FFLShaderMaterial -// Derived from MiiDefaultShader.vsh found in Miitomo. -// ───────────────────────────────────────────────────────── -const _FFLShader_vert = /* glsl */ ` -// 頂点シェーダーに入力される attribute 変数 -//attribute vec4 position; //!< 入力: 位置情報 -//attribute vec2 uv; //!< 入力: テクスチャー座標 -//attribute vec3 normal; //!< 入力: 法線ベクトル -// All provided by three.js ^^ - -// vertex color is not actually the color of the shape, as such -// it is a custom attribute _COLOR in the glTF - -attribute vec4 _color; //!< 入力: 頂点の色 -attribute vec3 tangent; //!< 入力: 異方位 - -// フラグメントシェーダーへの入力 -varying vec4 v_color; //!< 出力: 頂点の色 -varying vec4 v_position; //!< 出力: 位置情報 -varying vec3 v_normal; //!< 出力: 法線ベクトル -varying vec3 v_tangent; //!< 出力: 異方位 -varying vec2 v_texCoord; //!< 出力: テクスチャー座標 - -// ユニフォーム -//uniform mat3 normalMatrix; //!< ユニフォーム: モデルの法線用行列 -//uniform mat4 modelViewMatrix; //!< ユニフォーム: プロジェクション行列 -//uniform mat4 projectionMatrix; //!< ユニフォーム: モデル行列 -// All provided by three.js ^^ - -// skinning_pars_vertex.glsl.js -#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif - -void main() -{ - - // begin_vertex.glsl.js - vec3 transformed = vec3( position ); -// skinbase_vertex.glsl.js -#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); - // skinning_vertex.glsl.js - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif - -//#ifdef FFL_COORDINATE_MODE_NORMAL - // 頂点座標を変換 - v_position = modelViewMatrix * vec4(transformed, 1.0); - gl_Position = projectionMatrix * v_position; - - vec3 objectNormal = normal; - vec3 objectTangent = tangent.xyz; -// skinnormal_vertex.glsl.js -#ifdef USE_SKINNING - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - - objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; - objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; - -#endif - - // 法線も変換 - //v_normal = mat3(inverse(u_mv)) * a_normal; - v_normal = normalize(normalMatrix * objectNormal); -//#elif defined(FFL_COORDINATE_MODE_NONE) -// // 頂点座標を変換 -// gl_Position = vec4(a_position.x, a_position.y * -1.0, a_position.z, a_position.w); -// v_position = a_position; -// -// v_normal = a_normal; -//#endif - - // その他の情報も書き出す - v_texCoord = uv; - // safe normalize - if (tangent != vec3(0.0, 0.0, 0.0)) - { - v_tangent = normalize(normalMatrix * objectTangent); - } - else - { - v_tangent = vec3(0.0, 0.0, 0.0); - } - - v_color = _color; -} -`; - -// ───────────────────────────────────────────────────────── -// Fragment Shader for FFLShaderMaterial -// Mostly unmodified from MiiDefaultShader.fsh found in Miitomo. -// ───────────────────────────────────────────────────────── -const _FFLShader_frag = /* glsl */ ` -// -// sample.flg -// Fragment shader -// Copyright (c) 2014 Nintendo Co., Ltd. All rights reserved. -// -// - -#ifdef GL_ES -precision mediump float; -#else -# define lowp -# define mediump -# define highp -#endif - - -// -// 定数定義ファイル -// - -/// シェーダーモード -#define FFL_SHADER_MODE_UR 0 -#define FFL_SHADER_MODE_UB 1 - -/// 変調処理のマクロ -#define FFL_MODULATE_MODE_CONSTANT 0 -#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 -#define FFL_MODULATE_MODE_RGB_LAYERED 2 -#define FFL_MODULATE_MODE_ALPHA 3 -#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 -#define FFL_MODULATE_MODE_ALPHA_OPA 5 - -/// スペキュラのモード -#define FFL_SPECULAR_MODE_BLINN 0 -#define FFL_SPECULAR_MODE_ANISO 1 - -/// ライトのON/OFF -#define FFL_LIGHT_MODE_DISABLE 0 -#define FFL_LIGHT_MODE_ENABLE 1 - -/// フラグメントのディスカードモード -#define FFL_DISCARD_FRAGMENT_DISABLE 0 -#define FFL_DISCARD_FRAGMENT_ENABLE 1 - -/// 座標変換モード -#define FFL_COORDINATE_MODE_NONE 0 -#define FFL_COORDINATE_MODE_NORMAL 1 - -// -// 関数の定義ファイル -// - -/** - * @brief 異方性反射の反射率を計算します。 - * @param[in] light ライトの向き - * @param[in] tangent 接線 - * @param[in] eye 視線の向き - * @param[in] power 鋭さ - */ -mediump float calculateAnisotropicSpecular(mediump vec3 light, mediump vec3 tangent, mediump vec3 eye, mediump float power ) -{ - mediump float dotLT = dot(light, tangent); - mediump float dotVT = dot(eye, tangent); - mediump float dotLN = sqrt(1.0 - dotLT * dotLT); - mediump float dotVR = dotLN*sqrt(1.0 - dotVT * dotVT) - dotLT * dotVT; - - return pow(max(0.0, dotVR), power); -} - -/** - * @brief 異方性反射の反射率を計算します。 - * @param[in] light ライトの向き - * @param[in] normal 法線 - * @param[in] eye 視線の向き - * @param[in] power 鋭さ - */ -mediump float calculateBlinnSpecular(mediump vec3 light, mediump vec3 normal, mediump vec3 eye, mediump float power) -{ - return pow(max(dot(reflect(-light, normal), eye), 0.0), power); -} - -/** - * @brief 異方性反射、ブリン反射をブレンドします。 - * @param[in] blend ブレンド率 - * @param[in] blinn ブリンの値 - * @param[in] aniso 異方性の値 - */ -mediump float calculateSpecularBlend(mediump float blend, mediump float blinn, mediump float aniso) -{ - return mix(aniso, blinn, blend); -} - -/** - * @brief アンビエントを計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - */ -mediump vec3 calculateAmbientColor(mediump vec3 light, mediump vec3 material) -{ - return light * material; -} - -/** - * @brief 拡散を計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - * @param[in] ln ライトと法線の内積 - */ -mediump vec3 calculateDiffuseColor(mediump vec3 light, mediump vec3 material, mediump float ln) -{ - return light * material * ln; -} - -/** - * @brief 鏡面反射を計算します。 - * @param[in] light ライト - * @param[in] material マテリアル - * @param[in] reflection 反射率 - * @param[in] strength 幅 - */ -mediump vec3 calculateSpecularColor(mediump vec3 light, mediump vec3 material, mediump float reflection, mediump float strength) -{ - return light * material * reflection * strength; -} - -/** - * @brief リムを計算します。 - * @param[in] color リム色 - * @param[in] normalZ 法線のZ方向 - * @param[in] width リム幅 - * @param[in] power リムの鋭さ - */ -mediump vec3 calculateRimColor(mediump vec3 color, mediump float normalZ, mediump float width, mediump float power) -{ - return color * pow(width * (1.0 - abs(normalZ)), power); -} - -/** - * @brief ライト方向と法線の内積を求める - * @note 特殊な実装になっています。 - */ -mediump float calculateDot(mediump vec3 light, mediump vec3 normal) -{ - return max(dot(light, normal), 0.1); -} - -// フラグメントシェーダーに入力される varying 変数 -varying mediump vec4 v_color; //!< 出力: 頂点の色 -varying highp vec4 v_position; //!< 出力: 位置情報 -varying highp vec3 v_normal; //!< 出力: 法線ベクトル -// NOTE: ^^ Those two need to be highp to avoid weird black dot issue on Android -varying mediump vec3 v_tangent; //!< 出力: 異方位 -varying mediump vec2 v_texCoord; //!< 出力: テクスチャー座標 - -/// constカラー -uniform mediump vec4 u_const1; ///< constカラー1 -uniform mediump vec4 u_const2; ///< constカラー2 -uniform mediump vec4 u_const3; ///< constカラー3 - -/// ライト設定 -uniform mediump vec3 u_light_ambient; ///< カメラ空間のライト方向 -uniform mediump vec3 u_light_diffuse; ///< 拡散光用ライト -uniform mediump vec3 u_light_dir; -uniform bool u_light_enable; -uniform mediump vec3 u_light_specular; ///< 鏡面反射用ライト強度 - -/// マテリアル設定 -uniform mediump vec3 u_material_ambient; ///< 環境光用マテリアル設定 -uniform mediump vec3 u_material_diffuse; ///< 拡散光用マテリアル設定 -uniform mediump vec3 u_material_specular; ///< 鏡面反射用マテリアル設定 -uniform int u_material_specular_mode; ///< スペキュラの反射モード(CharModelに依存する設定のためub_modulateにしている) -uniform mediump float u_material_specular_power; ///< スペキュラの鋭さ(0.0を指定すると頂点カラーの設定が利用される) - -/// 変調設定 -uniform int u_mode; ///< 描画モード - -/// リム設定 -uniform mediump vec3 u_rim_color; -uniform mediump float u_rim_power; - -// サンプラー -uniform sampler2D s_texture; - - -// ------------------------------------------------------- -// メイン文 -void main() -{ - mediump vec4 color; - - mediump float specularPower = u_material_specular_power; - mediump float rimWidth = v_color.a; - -//#ifdef FFL_MODULATE_MODE_CONSTANT - if(u_mode == FFL_MODULATE_MODE_CONSTANT) - { - color = u_const1; - } -//#elif defined(FFL_MODULATE_MODE_TEXTURE_DIRECT) - else if(u_mode == FFL_MODULATE_MODE_TEXTURE_DIRECT) - { - color = texture2D(s_texture, v_texCoord); - } -//#elif defined(FFL_MODULATE_MODE_RGB_LAYERED) - else if(u_mode == FFL_MODULATE_MODE_RGB_LAYERED) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.r * u_const1.rgb + color.g * u_const2.rgb + color.b * u_const3.rgb, color.a); - } -//#elif defined(FFL_MODULATE_MODE_ALPHA) - else if(u_mode == FFL_MODULATE_MODE_ALPHA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(u_const1.rgb, color.r); - } -//#elif defined(FFL_MODULATE_MODE_LUMINANCE_ALPHA) - else if(u_mode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.g * u_const1.rgb, color.r); - } -//#elif defined(FFL_MODULATE_MODE_ALPHA_OPA) - else if(u_mode == FFL_MODULATE_MODE_ALPHA_OPA) - { - color = texture2D(s_texture, v_texCoord); - color = vec4(color.r * u_const1.rgb, 1.0); - } -//#endif - - // avoids little outline around mask elements - if(u_mode != FFL_MODULATE_MODE_CONSTANT && color.a == 0.0) - { - discard; - } - -//#ifdef FFL_LIGHT_MODE_ENABLE - if(u_light_enable) - { - /// 環境光の計算 - mediump vec3 ambient = calculateAmbientColor(u_light_ambient.xyz, u_material_ambient.xyz); - - /// 法線ベクトルの正規化 - mediump vec3 norm = normalize(v_normal); - - /// 視線ベクトル - mediump vec3 eye = normalize(-v_position.xyz); - - // ライトの向き - mediump float fDot = calculateDot(u_light_dir, norm); - - /// Diffuse計算 - mediump vec3 diffuse = calculateDiffuseColor(u_light_diffuse.xyz, u_material_diffuse.xyz, fDot); - - /// Specular計算 - mediump float specularBlinn = calculateBlinnSpecular(u_light_dir, norm, eye, u_material_specular_power); - - /// Specularの値を確保する変数を宣言 - mediump float reflection; - mediump float strength = v_color.g; - if(u_material_specular_mode == 0) - { - /// Blinnモデルの場合 - strength = 1.0; - reflection = specularBlinn; - } - else - { - /// Aisoモデルの場合 - mediump float specularAniso = calculateAnisotropicSpecular(u_light_dir, v_tangent, eye, u_material_specular_power); - reflection = calculateSpecularBlend(v_color.r, specularBlinn, specularAniso); - } - /// Specularの色を取得 - mediump vec3 specular = calculateSpecularColor(u_light_specular.xyz, u_material_specular.xyz, reflection, strength); - - // リムの色を計算 - mediump vec3 rimColor = calculateRimColor(u_rim_color.rgb, norm.z, rimWidth, u_rim_power); - - // カラーの計算 - color.rgb = (ambient + diffuse) * color.rgb + specular + rimColor; - } -//#endif - - gl_FragColor = color; -} -`; -// #include -// #include <${THREE.REVISION >= 154 ? 'colorspace_fragment' : 'encodings_fragment'}> - -export type FFLMaterial = { - ambient: THREE.Color; - diffuse: THREE.Color; - specular: THREE.Color; - specularPower: number; - specularMode: number; -}; -export type FFLColor = - | [/**Red*/ number, /**Green*/ number, /**Blue*/ number, /**Alpha*/ number] - | [/**Red*/ number, /**Green*/ number, /**Blue*/ number]; - -export type FFLShaderOptions = { - // Maps to pre-made materials - modulateColor: FFLColor; - modulateMode: number; - modulateType: number; - map: THREE.Texture; - - // FFL shader specific - lightAmbient: THREE.Color; - lightDiffuse: THREE.Color; - lightSpecular: THREE.Color; - lightEnable: boolean; - lightDirection: THREE.Vector3; - - // Custom shader - fragmentShader: string; - vertexShader: string; - - // Culling - side: THREE.Side; - - // -- Custom parameters added for use with mii creator - - // Override parts of material settings (only required for 'Toon' shader?) - customMaterial: FFLMaterial; -}; - -// ───────────────────────────────────────────────────────────── -// FFLShaderMaterial Class -// ───────────────────────────────────────────────────────────── -class FFLShaderMaterial extends THREE.ShaderMaterial { - // Default light and rim constants: - static defaultLightAmbient = new THREE.Color( - 0.73, - 0.73, - 0.73 - ) /*.convertSRGBToLinear()*/; - static defaultLightDiffuse = new THREE.Color( - 0.6, - 0.6, - 0.6 - ) /*.convertSRGBToLinear()*/; - static defaultLightSpecular = new THREE.Color( - 0.7, - 0.7, - 0.7 - ) /*.convertSRGBToLinear()*/; - static defaultLightDir = new THREE.Vector3( - -0.4531539381, - 0.4226179123, - 0.7848858833 - ); - static defaultRimColor = new THREE.Color( - 0.3, - 0.3, - 0.3 - ) /*.convertSRGBToLinear()*/; - static defaultRimPower = 2.0; - - static defaultLightDirection = this.defaultLightDir; - - // Material table for FFLDefaultShader mapping to FFLModulateType - // Reference: https://github.com/aboood40091/FFL-Testing/blob/master/src/Shader.cpp - static materialParams: FFLMaterial[] = [ - { - // FFL_MODULATE_TYPE_SHAPE_FACELINE - ambient: new THREE.Color(0.85, 0.75, 0.75) /*.convertSRGBToLinear()*/, - diffuse: new THREE.Color(0.75, 0.75, 0.75) /*.convertSRGBToLinear()*/, - specular: new THREE.Color(0.3, 0.3, 0.3) /*.convertSRGBToLinear()*/, - specularPower: 1.2, - specularMode: 0, - }, - { - // FFL_MODULATE_TYPE_SHAPE_BEARD - ambient: new THREE.Color(1.0, 1.0, 1.0) /*.convertSRGBToLinear()*/, - diffuse: new THREE.Color(0.7, 0.7, 0.7) /*.convertSRGBToLinear()*/, - specular: new THREE.Color(0.0, 0.0, 0.0) /*.convertSRGBToLinear()*/, - specularPower: 40.0, - specularMode: 1, - }, - { - // FFL_MODULATE_TYPE_SHAPE_NOSE - ambient: new THREE.Color(0.9, 0.85, 0.85) /*.convertSRGBToLinear()*/, - diffuse: new THREE.Color(0.75, 0.75, 0.75) /*.convertSRGBToLinear()*/, - specular: new THREE.Color(0.22, 0.22, 0.22) /*.convertSRGBToLinear()*/, - specularPower: 1.5, - specularMode: 0, - }, - { - // FFL_MODULATE_TYPE_SHAPE_FOREHEAD - ambient: new THREE.Color(0.85, 0.75, 0.75) /*.convertSRGBToLinear()*/, - diffuse: new THREE.Color(0.75, 0.75, 0.75) /*.convertSRGBToLinear()*/, - specular: new THREE.Color(0.3, 0.3, 0.3) /*.convertSRGBToLinear()*/, - specularPower: 1.2, - specularMode: 0, - }, - { - // FFL_MODULATE_TYPE_SHAPE_HAIR - ambient: new THREE.Color(1.0, 1.0, 1.0) /*.convertSRGBToLinear()*/, - diffuse: new THREE.Color(0.7, 0.7, 0.7) /*.convertSRGBToLinear()*/, - specular: new THREE.Color(0.35, 0.35, 0.35) /*.convertSRGBToLinear()*/, - specularPower: 10.0, - specularMode: 1, - }, - { - // FFL_MODULATE_TYPE_SHAPE_CAP - ambient: new THREE.Color(0.75, 0.75, 0.75) /*.convertSRGBToLinear()*/, - diffuse: new THREE.Color(0.72, 0.72, 0.72) /*.convertSRGBToLinear()*/, - specular: new THREE.Color(0.3, 0.3, 0.3) /*.convertSRGBToLinear()*/, - specularPower: 1.5, - specularMode: 0, - }, - { - // FFL_MODULATE_TYPE_SHAPE_MASK - ambient: new THREE.Color(1.0, 1.0, 1.0) /*.convertSRGBToLinear()*/, - diffuse: new THREE.Color(0.7, 0.7, 0.7) /*.convertSRGBToLinear()*/, - specular: new THREE.Color(0.0, 0.0, 0.0) /*.convertSRGBToLinear()*/, - specularPower: 40.0, - specularMode: 1, - }, - { - // FFL_MODULATE_TYPE_SHAPE_NOSELINE - ambient: new THREE.Color(1.0, 1.0, 1.0) /*.convertSRGBToLinear()*/, - diffuse: new THREE.Color(0.7, 0.7, 0.7) /*.convertSRGBToLinear()*/, - specular: new THREE.Color(0.0, 0.0, 0.0) /*.convertSRGBToLinear()*/, - specularPower: 40.0, - specularMode: 1, - }, - { - // FFL_MODULATE_TYPE_SHAPE_GLASS - ambient: new THREE.Color(1.0, 1.0, 1.0) /*.convertSRGBToLinear()*/, - diffuse: new THREE.Color(0.7, 0.7, 0.7) /*.convertSRGBToLinear()*/, - specular: new THREE.Color(0.0, 0.0, 0.0) /*.convertSRGBToLinear()*/, - specularPower: 40.0, - specularMode: 1, - }, - - { - // body - ambient: new THREE.Color( - 0.95622, - 0.95622, - 0.95622 - ) /*.convertSRGBToLinear()*/, - diffuse: new THREE.Color( - 0.49673, - 0.49673, - 0.49673 - ) /*.convertSRGBToLinear()*/, - specular: new THREE.Color( - 0.24099, - 0.24099, - 0.24099 - ) /*.convertSRGBToLinear()*/, - specularPower: 3.0, - specularMode: 0, - }, - { - // pants - ambient: new THREE.Color( - 0.95622, - 0.95622, - 0.95622 - ) /*.convertSRGBToLinear()*/, - diffuse: new THREE.Color( - 1.08497, - 1.08497, - 1.08497 - ) /*.convertSRGBToLinear()*/, - specular: new THREE.Color( - 0.2409, - 0.2409, - 0.2409 - ) /*.convertSRGBToLinear()*/, - specularPower: 3.0, - specularMode: 0, - }, - ]; - - // Material enum - - static getBlendOptionsFromModulateType(modulateType: number) { - if (modulateType >= 0 && modulateType <= 5) { - // Opaque (DrawOpa) - return { - blending: THREE.CustomBlending, - blendSrcAlpha: THREE.SrcAlphaFactor, - blendDstAlpha: THREE.OneFactor, - }; - } else if (modulateType >= 6 && modulateType <= 8) { - // Translucent (DrawXlu) - return { - blending: THREE.CustomBlending, - blendSrc: THREE.SrcAlphaFactor, - blendDst: THREE.OneMinusSrcAlphaFactor, - blendDstAlpha: THREE.OneFactor, - }; - } else if (modulateType >= 9 && modulateType <= 13) { - // Mask Textures - return { - blending: THREE.CustomBlending, - blendSrc: THREE.OneMinusDstAlphaFactor, - blendSrcAlpha: THREE.SrcAlphaFactor, - blendDst: THREE.DstAlphaFactor, - }; - } else if (modulateType >= 14 && modulateType <= 17) { - // Faceline Texture - return { - blending: THREE.CustomBlending, - blendSrc: THREE.SrcAlphaFactor, - blendDst: THREE.OneMinusSrcAlphaFactor, - blendSrcAlpha: THREE.OneFactor, - blendDstAlpha: THREE.OneFactor, - }; - } else { - console.error(`Unknown modulate type:`, modulateType); - return {}; - } - } - - // Properties exposed by the constructor. - modulateMode: number; - modulateType: number; - modulateColor?: FFLColor; - lightEnable: boolean; - - /** - * Options (all are optional): - * - modulateMode: number (default 0) - * - modulateType: number (default 0; selects a row from materialParams) - * - modulateColor: either a THREE.Vector4 OR an array of THREE.Vector4 of length 3. - * If an array is provided, they map to u_const1, u_const2, u_const3. - * - lightEnable: boolean (default true) - * - lightDirection: THREE.Vector3 (default as defined) - * - map: (optional) THREE.Texture - * - vertexShader/fragmentShader: shader sources (defaults come from HTML IDs below) - * - side, transparent, alphaTest: additional material flags - */ - constructor(options: Partial = {}) { - const modulateMode = options.modulateMode ?? 0; - const modulateType = options.modulateType ?? 0; - const lightEnable = options.lightEnable ?? true; - const lightDir = - options.lightDirection ?? FFLShaderMaterial.defaultLightDir.clone(); - const texture = options.map || null; // may be null - const customMaterial = options.customMaterial || null; // may be null - - // Process modulateColor input: - let colorUniforms = {}; - if ( - Array.isArray(options.modulateColor) && - options.modulateColor.length === 3 - ) { - colorUniforms = { - u_const1: { value: options.modulateColor[0] }, - u_const2: { value: options.modulateColor[1] }, - u_const3: { value: options.modulateColor[2] }, - }; - } else { - colorUniforms = { - u_const1: { - value: options.modulateColor || new THREE.Vector4(1, 1, 1, 1), - }, - }; - } - - let matParam = - FFLShaderMaterial.materialParams[modulateType] || - FFLShaderMaterial.materialParams[0]; - - // temp solution - if (customMaterial) { - matParam = customMaterial; - } - - const uniforms = Object.assign({}, colorUniforms, { - u_light_ambient: { - value: options.lightAmbient || FFLShaderMaterial.defaultLightAmbient, - }, - u_light_diffuse: { - value: options.lightDiffuse || FFLShaderMaterial.defaultLightDiffuse, - }, - u_light_specular: { - value: options.lightSpecular || FFLShaderMaterial.defaultLightSpecular, - }, - u_light_dir: { value: lightDir }, - u_light_enable: { value: lightEnable }, - u_material_ambient: { value: matParam.ambient }, - u_material_diffuse: { value: matParam.diffuse }, - u_material_specular: { value: matParam.specular }, - u_material_specular_mode: { value: matParam.specularMode }, - u_material_specular_power: { value: matParam.specularPower }, - u_mode: { value: modulateMode }, - u_rim_color: { value: FFLShaderMaterial.defaultRimColor }, - u_rim_power: { value: FFLShaderMaterial.defaultRimPower }, - s_texture: { value: texture }, - }); - - super({ - vertexShader: options.vertexShader || _FFLShader_vert, - fragmentShader: options.fragmentShader || _FFLShader_frag, - uniforms: uniforms, - side: options.side || THREE.FrontSide, - // skinning: options.skinning || false, // Not needed with newer Three.js. - // Merge blend options: - ...modulateMode !== 0 ? FFLShaderMaterial.getBlendOptionsFromModulateType(modulateType) : {} - }); - // Expose these properties. - this.modulateMode = modulateMode; - this.modulateType = modulateType; - this.modulateColor = options.modulateColor; - this.lightEnable = lightEnable; - } - - get map() { - return this.uniforms.s_texture.value; // Expose as 'map' - } - set map(value) { - this.uniforms.s_texture.value = value; - } - get lightDirection() { - return this.uniforms.u_light_dir.value; - } - set lightDirection(value) { - this.uniforms.u_light_dir.value = value; - } -} - -export { FFLShaderMaterial }; // Export. diff --git a/src/external/ffl.js/LUTShaderMaterial.ts b/src/external/ffl.js/LUTShaderMaterial.js similarity index 52% rename from src/external/ffl.js/LUTShaderMaterial.ts rename to src/external/ffl.js/LUTShaderMaterial.js index 30c75b6..03bc129 100644 --- a/src/external/ffl.js/LUTShaderMaterial.ts +++ b/src/external/ffl.js/LUTShaderMaterial.js @@ -1,1147 +1,1326 @@ -import * as THREE from "three"; -import type { FFLColor, FFLShaderOptions } from "./FFLShaderMaterial"; - -// ───────────────────────────────────────────────────────── -// Vertex Shader for LUTShaderMaterial -// Derived from LUT.vsh found in Miitomo. -// ───────────────────────────────────────────────────────── -const _LUTShader_vert = /* glsl */ ` -#define AGX_FEATURE_ALBEDO_TEXTURE -/** - * @file LUT.vsh - * @brief LUT - * @since 2014/10/02 - * - * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. - */ - -// シェーダーの種類毎に設定されるマクロリスト -// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 -// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 -// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 -// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 -// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 -// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 -// AGX_FEATURE_SKIN_MASK 肌マスクが有効(u_const1) -// AGX_FEATURE_HAIR_MASK 髪マスクが有効(u_const2) -// AGX_FEATURE_ALPHA_TEST アルファテストが有効 -// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(u_const3) -// AGX_FEATURE_DISABLE_LIGHT ライトが無効 -// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 -// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 -// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 -// AGX_FEATURE_MII Miiを描画する -// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant -// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct -// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered -// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha -// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha -// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa -// -// AGX_BONE_MAX ボーンの最大数 - -#ifdef GL_ES -precision highp float; -#else -# define lowp -# define mediump -# define highp -#endif - -//#ifndef AGX_BONE_MAX -//# define AGX_BONE_MAX 15 -//#endif -#ifndef AGX_DIR_LIGHT_MAX -# define AGX_DIR_LIGHT_MAX 2 -#endif - -// ---------------------------------------- -// 頂点シェーダーに入力される attribute 変数 -//attribute highp vec3 position; //!< 入力:[ 1 : 1 ] 位置情報 -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) -//attribute mediump vec2 uv; //!< 入力:[ 1 : 5 ] テクスチャー座標 -#endif -//attribute mediump vec3 normal; //!< 入力:[ 1 : 2 ] 法線ベクトル -//attribute mediump vec4 aBoneIndex; //!< 入力:[ 1 : 3 ] ボーンのインデックス(最大4つ) -//attribute mediump vec4 aBoneWeight; //!< 入力:[ 1 : 4 ] ボーンの影響度(最大4つ) -#if defined(AGX_FEATURE_VERTEX_COLOR) -//attribute lowp vec4 _color; //!< 入力:[ 1 : 6 ] 頂点カラー -#endif -#if defined(AGX_FEATURE_BUMP_TEXTURE) -//attribute mediump vec3 tangent; //!< 入力:[ 1 : 7 ] 接線ベクトル -#endif - -// ^^ Commented attributes are provided by three.js. - -// ---------------------------------------- -// 頂点シェーダーに入力される uniform 変数 -//uniform highp mat4 modelViewMatrix; //!< 入力:[ 4 / 4 : 4 ] モデルの合成行列 -//uniform mat4 projectionMatrix; -//uniform highp mat4 viewMatrix; //!< 入力:[ 4 / 4 : 8 ] モデルのビュー行列 -//uniform mediump mat3 normalMatrix; //!< 入力:[ 3 / 3 : 11 ] モデルの法線用行列 -//uniform highp mat4 modelMatrix; //!< 入力:[ 4 / 4 : 15 ] モデルのワールド変換行列 -//uniform lowp int uBoneCount; //!< 入力:[ 1 / 1 : 16 ] ボーンの個数 -//uniform highp mat4 uBoneMatrices[AGX_BONE_MAX]; //!< 入力:[ 4 x 15 / 60 : 76 ] ボーンの行列配列 -//uniform mediump mat3 uBoneNormalMatrices[AGX_BONE_MAX]; //!< 入力:[ 3 x 15 / 45 : 121 ] ボーンの法線行列配列 -// ^^ Unused in favor of three.js skinning. -uniform lowp int uDirLightCount; //!< 入力:[ 1 / 1 : 122 ] 方向ライトの数 -uniform mediump vec4 uDirLightDirAndType0;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 -uniform mediump vec4 uDirLightDirAndType1;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 -uniform mediump vec3 uDirLightColor0; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー -uniform mediump vec3 uDirLightColor1; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー -uniform mediump vec3 uHSLightSkyColor; //!< 入力:[ 1 / 1 : 127 ] 半球ライトのスカイカラー -uniform mediump vec3 uHSLightGroundColor; //!< 入力:[ 1 / 1 : 128 ] 半球ライトのグラウンドカラー -//uniform mediump vec3 cameraPosition; //!< 入力:[ 1 / 1 : 129 ] カメラの位置 -// ^^ previously uEyePt -uniform mediump float uAlpha; //!< 入力:[ 1 / 1 : 130 ] アルファ値 - -// ^^ Commented uniforms are provided by three.js. - -// ---------------------------------------- -// フラグメントシェーダーに渡される varying 変数 -varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 -#if !defined(AGX_FEATURE_BUMP_TEXTURE) -varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 -#endif -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) -varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV -#endif -// camera -varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル -#if !defined(AGX_FEATURE_DISABLE_LIGHT) -// punctual light -varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 -varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル -// GI -varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー -// Lighting Result -varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 -#endif -// Reflect -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) -varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル -#endif - -// skinning_pars_vertex.glsl.js -#ifdef USE_SKINNING - uniform mat4 bindMatrix; - uniform mat4 bindMatrixInverse; - uniform highp sampler2D boneTexture; - mat4 getBoneMatrix( const in float i ) { - int size = textureSize( boneTexture, 0 ).x; - int j = int( i ) * 4; - int x = j % size; - int y = j / size; - vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); - vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); - vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); - vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); - return mat4( v1, v2, v3, v4 ); - } -#endif - -// ------------------------------------------------------------ -// 頂点シェーダーのエントリーポイント -// ------------------------------------------------------------ -void main() -{ - // ------------------------------------------------------------ - // 頂点変換用の処理 - // ------------------------------------------------------------ - highp vec4 position_; //!< 最終的な頂点 - mediump vec3 normal_; //!< 最終的な法線 - mediump vec3 tangent_; //!< 最終的な接線 - highp vec4 positionWorld; //!< ワールド空間上での頂点 - - - // begin_vertex.glsl.js - vec3 transformed = vec3( position ); -// skinbase_vertex.glsl.js -#ifdef USE_SKINNING - mat4 boneMatX = getBoneMatrix( skinIndex.x ); - mat4 boneMatY = getBoneMatrix( skinIndex.y ); - mat4 boneMatZ = getBoneMatrix( skinIndex.z ); - mat4 boneMatW = getBoneMatrix( skinIndex.w ); - // skinning_vertex.glsl.js - vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); - vec4 skinned = vec4( 0.0 ); - skinned += boneMatX * skinVertex * skinWeight.x; - skinned += boneMatY * skinVertex * skinWeight.y; - skinned += boneMatZ * skinVertex * skinWeight.z; - skinned += boneMatW * skinVertex * skinWeight.w; - transformed = ( bindMatrixInverse * skinned ).xyz; -#endif - - // ---------------------------------------- - // ボーンが存在しない場合は位置と法線に手を加えない - position_ = vec4(transformed.xyz, 1.0); - - - - normal_ = normal; -#if defined(AGX_FEATURE_BUMP_TEXTURE) - tangent_ = tangent.xyz; -#endif - // skinnormal_vertex.glsl.js -#ifdef USE_SKINNING - mat4 skinMatrix = mat4( 0.0 ); - skinMatrix += skinWeight.x * boneMatX; - skinMatrix += skinWeight.y * boneMatY; - skinMatrix += skinWeight.z * boneMatZ; - skinMatrix += skinWeight.w * boneMatW; - skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; - - normal_ = vec4( skinMatrix * vec4( normal_, 0.0 ) ).xyz; -#if defined(AGX_FEATURE_BUMP_TEXTURE) - tangent_ = vec4( skinMatrix * vec4( tangent_, 0.0 ) ).xyz; -#endif // defined(AGX_FEATURE_BUMP_TEXTURE) -#endif // USE_SKINNING - - // ---------------------------------------- - // ワールド上での位置を求める - positionWorld = modelMatrix * position_; - // 最終結果を行う - position_ = projectionMatrix * modelViewMatrix * position_; - normal_ = normalize(normalMatrix * normal_); -#if defined(AGX_FEATURE_BUMP_TEXTURE) - tangent = normalize(normalMatrix * tangent_); -#endif - - // ---------------------------------------- - // 計算結果を保持させる - gl_Position = position_; -#if !defined(AGX_FEATURE_BUMP_TEXTURE) - vNormal = normal_; -#endif -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) - // テクスチャー座標を設定する - vTexcoord0 = uv; -#endif - // モデルの色を指定する -#if defined(AGX_FEATURE_VERTEX_COLOR) - lowp vec4 modelColor = aColor; - -#else - lowp vec4 modelColor = vec4(1.0, 1.0, 1.0, 1.0); -#endif - - // プリマルチプライドアルファ -#if defined(AGX_FEATURE_PREMULTIPLY_ALPHA) - modelColor *= uAlpha; -#else - modelColor.a *= uAlpha; -#endif - - - // ------------------------------------------------------------ - // ライト用の処理 - // ------------------------------------------------------------ - mediump vec3 eyeVecWorld; //!< ワールド状態での視線ベクトル - mediump vec3 eyeVec; //!< 最終的にフラグメントシェーダーに渡す視線ベクトル(バンプの有無によって、ワールド座標系になったり、タンジェント座標系になったりする) - - vec4 eye = modelViewMatrix * position_; - - // 視線ベクトルを取得する - //eyeVecWorld = normalize(cameraPosition - positionWorld.xyz); - eyeVecWorld = normalize(-(eye.xyz) - positionWorld.xyz);//normalize(cameraPosition - positionWorld.xyz); - eyeVec = eyeVecWorld; - - lowp vec3 diffuseColor = vec3(0.0); // バーテックスシェーダーで計算できるディフューズの色をここに格納する - -# if defined(AGX_FEATURE_BUMP_TEXTURE) - // Normal, Binormal, Tangent を取得する - mediump vec3 n = normal; - mediump vec3 t = tangent; - mediump vec3 b = cross(n, t); - // 接空間からローカルへ変換する行列を設定する(mat3(N, T, B)の逆行列) - mediump mat3 tangentMatrix = mat3(t.x, b.x, n.x, t.y, b.y, n.y, t.z, b.z, n.z); - // 視線ベクトルを接空間へ - vEyeVecWorldOrTangent.xyz = tangentMatrix * eyeVec; -#else - vEyeVecWorldOrTangent.xyz = eyeVec; -#endif - -#if !defined(AGX_FEATURE_DISABLE_LIGHT) - // punctual lightの設定 - if (uDirLightCount > 0) - { - mediump vec3 lightDir; - - // 方向ライト - if (uDirLightDirAndType0.w < 0.0) { lightDir = uDirLightDirAndType0.xyz; } - // 点光源ライト - else { lightDir = uDirLightDirAndType0.xyz - positionWorld.xyz; } - lightDir = normalize(lightDir); - -# if defined(AGX_FEATURE_BUMP_TEXTURE) - // ライトを接空間へ - vPunctualLightDirWorldOrTangent.xyz = tangentMatrix * lightDir; -# else - vPunctualLightDirWorldOrTangent.xyz = lightDir; -# endif - - // Halfベクトルを求める - vPunctualLightHalfVecWorldOrTangent.xyz = normalize(vPunctualLightDirWorldOrTangent.xyz + vEyeVecWorldOrTangent.xyz); - - // Diffuse計算 - diffuseColor += (uDirLightColor0.rgb * clamp(dot(lightDir, normal), 0.0, 1.0)); - } - if (uDirLightCount > 1) - { - mediump vec3 lightDir; - - // 方向ライト - if (uDirLightDirAndType1.w < 0.0) { lightDir = uDirLightDirAndType1.xyz; } - // 点光源ライト - else { lightDir = uDirLightDirAndType1.xyz - positionWorld.xyz; } - lightDir = normalize(lightDir); - - diffuseColor += max(dot(lightDir, normal), 0.0) * uDirLightColor1; - } - // ライトは1.0を超えないように - diffuseColor = min(diffuseColor, 1.0); -#endif - -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) - { - // キューブ環境マップ用の反射ベクトルを求める -// vReflectDir = reflect(normalize(positionWorld.xyz - cameraPosition), normal); - - // スフィア環境マップ用の反射ベクトルを求める -// vReflectDir = normalize((uViewMatrix * vec4(normal, 0.0)).xyz) * 0.5 + 0.5; - - // ビュー座標系での位置と法線を取得 - mediump vec3 viewNormal = normalize(mat3(uViewMatrix) * normal); - mediump vec4 viewPosition = uViewMatrix * positionWorld; - viewPosition = viewPosition / viewPosition.w; - // ビュー座標系での頂点ベクトルを取得 - viewPosition.z = 1.0 - viewPosition.z; - mediump vec3 viewPositionVec = normalize(viewPosition.xyz); - // ビュー座標系での反射ベクトルを求める - mediump vec3 viewReflect = viewPositionVec - 2.0 * dot(viewPositionVec, viewNormal) * viewNormal; - // 両面スフィア環境マップではないので、反射ベクトルを調整 - viewReflect = normalize(viewReflect - vec3(0.0, 0.0, 1.5)); - // 反射ベクトルをテクスチャー座標系へ - vReflectDir = viewReflect * 0.5 + 0.5; - - // 公式 -// mediump vec3 viewPositionVec = normalize(vec3(uViewMatrix * positionWorld)); -// mediump vec3 viewReflectVec = viewPositionVec - 2.0 * dot(viewPositionVec, normal) * normal; -// mediump float m = 2.0 * sqrt(viewReflectVec.x * viewReflectVec.x + -// viewReflectVec.y * viewReflectVec.y + -// (viewReflectVec.z + 1.0) * (viewReflectVec.z * 1.0)); -// vReflectDir = viewReflectVec / m + 0.5; - - // 別版 -// mediump vec3 posW = positionWorld.xyz; -// mediump vec3 dir = normalize(mat3(uViewMatrix) * normal); -// -// mediump float radius = 75.0; -// mediump vec3 posWDir = dot(dir, posW) * dir; -// mediump vec3 posWDirV = posW - posWDir; -// mediump float lengthDir = sqrt(radius * radius - dot(posWDirV, posWDirV)) - length(posWDir); -// vReflectDir = normalize(posW + dir * lengthDir) * 0.5 + 0.5; - } -#endif - -#if !defined(AGX_FEATURE_DISABLE_LIGHT) - // GIの計算 - { - mediump vec3 hemiColor; - mediump vec3 sky = uHSLightSkyColor; - mediump vec3 ground = uHSLightGroundColor; - - { - mediump float skyRatio = (normal.y + 1.0) * 0.5; - hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); - diffuseColor += hemiColor; - } - - { -// mediump vec3 reflectDir = -reflect(normal, eyeVecWorld); // おそらくコレで良いはず - mediump vec3 reflectDir = 2.0 * dot(eyeVecWorld, normal) * normal - eyeVecWorld; // 多少冗長でも、正しい計算で行なう - - mediump float skyRatio = (reflectDir.y + 1.0) * 0.5; - hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); - vGISpecularLightColor.rgb = hemiColor; - } - } -#endif - - // モデルの色を設定 - vModelColor = modelColor; -#if !defined(AGX_FEATURE_DISABLE_LIGHT) - vDiffuseColor.rgb = diffuseColor; -#endif -} -`; - -// ───────────────────────────────────────────────────────── -// Fragment Shader for LUTShaderMaterial -// Unmodified from LUT.fsh found in Miitomo. -// ───────────────────────────────────────────────────────── -const _LUTShader_frag = /* glsl */ ` -#define AGX_FEATURE_ALBEDO_TEXTURE -#define AGX_FEATURE_MII -/** - * @file LUT.fsh - * @brief LUT - * @since 2014/10/02 - * - * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. - */ - -// シェーダーの種類毎に設定されるマクロリスト -// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 -// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 -// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 -// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 -// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 -// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 -// AGX_FEATURE_SKIN_MASK 肌マスクが有効(u_const1) -// AGX_FEATURE_HAIR_MASK 髪マスクが有効(u_const2) -// AGX_FEATURE_ALPHA_TEST アルファテストが有効 -// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(u_const3) -// AGX_FEATURE_DISABLE_LIGHT ライトが無効 -// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 -// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 -// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 -// AGX_FEATURE_MII Miiを描画する -// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant -// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct -// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered -// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha -// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha -// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa - -#ifdef GL_ES -precision mediump float; -#else -# define lowp -# define mediump -# define highp -#endif - -/// 変調処理のマクロ -#define FFL_MODULATE_MODE_CONSTANT 0 -#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 -#define FFL_MODULATE_MODE_RGB_LAYERED 2 -#define FFL_MODULATE_MODE_ALPHA 3 -#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 -#define FFL_MODULATE_MODE_ALPHA_OPA 5 - -// ---------------------------------------- -// フラグメントシェーダーに入力される uniform 変数 -uniform int uMode; ///< 描画モード -uniform bool uAlphaTest; -uniform bool uLightEnable; -uniform mediump vec4 u_const1; //!< 入力:[ 1 : 1 ] カラー0 (OR 肌カラー) -uniform mediump vec4 u_const2; //!< 入力:[ 1 : 2 ] カラー1 (OR 髪カラー) -uniform mediump vec4 u_const3; //!< 入力:[ 1 : 3 ] カラー2 (OR フェードアウトカラー) -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -uniform mediump vec3 uLightColor; //!< 入力:[ 1 : 4 ] ライトの色 -//#endif - -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) -uniform sampler2D uAlbedoTexture; //!< 入力: テクスチャー -#endif -#if defined(AGX_FEATURE_BUMP_TEXTURE) -uniform sampler2D uNormalTexture; //!< 入力: ノーマルマップ -#endif -#if defined(AGX_FEATURE_MASK_TEXTURE) -uniform sampler2D uMaskTexture; //!< 入力:マスクテクスチャー -#endif -#if defined(AGX_FEATURE_ALPHA_TEXTURE) -uniform sampler2D uAlphaTexture; //!< 入力:アルファテクスチャー -#endif -uniform sampler2D uLUTSpecTexture; //!< 入力: スペキュラーLUT -uniform sampler2D uLUTFresTexture; //!< 入力: フレネルLUT -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) -uniform sampler2D uSphereMapTexture; //!< 入力: スフィア環境マップ -#endif - -// ---------------------------------------- -// フラグメントシェーダーに渡される varying 変数 -varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 -#if !defined(AGX_FEATURE_BUMP_TEXTURE) -varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 -#endif -#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) -varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV -#endif -// camera -varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -// punctual light -varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 -varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル -// GI -varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー -// Lighting Result -varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 -//#endif -// Reflect -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) -varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル -#endif - -// ------------------------------------------------------------ -// フラグメントシェーダーのエントリーポイント -// ------------------------------------------------------------ -void main() -{ - - // ディフューズカラーを取得 - lowp vec4 albedoColor = vec4(1.0, 1.0, 1.0, 1.0); - - // ============================================================ - // Mii - // ============================================================ -#if defined(AGX_FEATURE_MII) - - //#if defined(AGX_FEATURE_MII_CONSTANT) - if(uMode == FFL_MODULATE_MODE_CONSTANT) - { - albedoColor = vec4(u_const1.rgb, 1.0); - } - //#elif defined(AGX_FEATURE_MII_TEXTURE_DIRECT) - else if(uMode == FFL_MODULATE_MODE_TEXTURE_DIRECT) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - } - //#elif defined(AGX_FEATURE_MII_RGB_LAYERED) - else if(uMode == FFL_MODULATE_MODE_RGB_LAYERED) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(albedoColor.r * u_const1.rgb + albedoColor.g * u_const2.rgb + albedoColor.b * u_const3.rgb, - albedoColor.a); - } - //#elif defined(AGX_FEATURE_MII_ALPHA) - else if(uMode == FFL_MODULATE_MODE_ALPHA) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(u_const1.rgb, albedoColor.r); - } - //#elif defined(AGX_FEATURE_MII_LUMINANCE_ALPHA) - else if(uMode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(albedoColor.g * u_const1.rgb, albedoColor.r); - } - //#elif defined(AGX_FEATURE_MII_ALPHA_OPA) - else if(uMode == FFL_MODULATE_MODE_ALPHA_OPA) - { - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); - albedoColor = vec4(albedoColor.r * u_const1.rgb, 1.0); - } -//#endif - - albedoColor = albedoColor * vModelColor; -#endif - - // ============================================================ - // Albedo Texture - // ============================================================ -#if !defined(AGX_FEATURE_MII) && defined(AGX_FEATURE_ALBEDO_TEXTURE) - albedoColor = texture2D(uAlbedoTexture, vTexcoord0); -#endif -#if defined(AGX_FEATURE_ALPHA_TEXTURE) - albedoColor.a = texture2D(uAlphaTexture, vTexcoord0).r; -#endif - - // ============================================================ - // Color Mask - // ============================================================ - // ---------------------------------------- - // Deprecated -#if defined(AGX_FEATURE_ALPHA_COLOR_FILTER) - // 一部の場所にColor0を反映する - albedoColor.rgb = (albedoColor.rgb * albedoColor.a + u_const1.rgb * (1.0 - albedoColor.a)); - albedoColor.a = 1.0; -#elif defined(AGX_FEATURE_MASK_TEXTURE) - lowp vec3 maskTextureColor = texture2D(uMaskTexture, vTexcoord0).rgb; - -# if defined(AGX_FEATURE_SKIN_MASK) && defined(AGX_FEATURE_HAIR_MASK) - // 肌と髪両方マスクが存在する - lowp float maskColorValue = maskTextureColor.g + maskTextureColor.b; - lowp vec3 maskColor = maskTextureColor.g * u_const1.rgb + maskTextureColor.b * u_const2.rgb; - albedoColor.rgb = (albedoColor.rgb * (1.0 - maskColorValue) + maskColor); - -# elif defined(AGX_FEATURE_SKIN_MASK) - // 肌しかマスクが存在しない - albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.g) + maskTextureColor.g * u_const1.rgb); - -# elif defined(AGX_FEATURE_HAIR_MASK) - // 髪しかマスクが存在しない - albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.b) + maskTextureColor.b * u_const2.rgb); - -# endif -#endif - - // アルベドに頂点カラーを掛ける - albedoColor *= vModelColor; - - // ============================================================ - // Alpha test - // ============================================================ -//#if defined(AGX_FEATURE_ALPHA_TEST) - if (uAlphaTest && albedoColor.a < 0.5) { discard; } -//#endif - - // ============================================================ - // Bumpmap - // ============================================================ - // 頂点からの情報 - lowp vec3 normalWorldOrTangent; -#if defined(AGX_FEATURE_BUMP_TEXTURE) - // バンプマップから法線を取得する - mediump vec3 bumpNormal = texture2D(uNormalTexture, vTexcoord0).rgb; - - // 法線の正規化は処理が重いのでいったん正規化しない様に... -// normalWorldOrTangent = normalize(bumpNormal * 2.0 - 1.0); - normalWorldOrTangent = bumpNormal * 2.0 - 1.0; - -#else - // 法線を正規化して取得する - normalWorldOrTangent = normalize(vNormal); -#endif - - // ============================================================ - // Lighting - // ============================================================ - // 最終的なカラー情報 - lowp vec4 colorOut = vec4(0.0, 0.0, 0.0, albedoColor.a); // 最終的に出力される色 - lowp vec3 fresnel = vec3(0.0, 0.0, 0.0); // フレネル - lowp vec3 specular = vec3(0.0, 0.0, 0.0); // スペキュラー - -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -if (uLightEnable) { - - // BRDFの計算を行う(バンプマッピングの場合は接空間) - lowp vec3 N = normalWorldOrTangent; - lowp vec3 V = vEyeVecWorldOrTangent.xyz;//normalize(vEyeVecWorldOrTangent.xyz); - lowp vec3 I = vPunctualLightDirWorldOrTangent.xyz;//normalize(vPunctualLightDirWorldOrTangent.xyz); - lowp vec3 H = vPunctualLightHalfVecWorldOrTangent.xyz;//normalize(vPunctualLightHalfVecWorldOrTangent.xyz); - - - // ---------------------------------------- - // punctual light - // 平行光源や点光源などの厳密なライティング計算を行なうもの - { - lowp float fSpecular = dot(N, H); - - lowp float specularIntensity = texture2D(uLUTSpecTexture, vec2(fSpecular)).r; - specular = (specularIntensity * uLightColor.rgb); - } - - // ---------------------------------------- - // GI - // 半球ライトやIBL、SHのように法線方向に半球積分された結果でライティング計算を行なうもの - { - lowp float fFresnel = dot(N, V); - lowp float fresnelIntensity = texture2D(uLUTFresTexture, vec2(fFresnel)).r; - - fresnel = (fresnelIntensity * vGISpecularLightColor.rgb); - } -} -//#endif - -#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) - // スフィア環境マップ - specular += texture2D(uSphereMapTexture, vReflectDir.xy).rgb; -#endif - - // ============================================================ - // Specular Mask - // ============================================================ -#if !defined(AGX_FEATURE_ALPHA_COLOR_FILTER) && defined(AGX_FEATURE_MASK_TEXTURE) - // スペキュラーマスク - specular = specular * maskTextureColor.r + fresnel; -#else - specular += fresnel; -#endif - - // ============================================================ - // Output - // ============================================================ -//#if !defined(AGX_FEATURE_DISABLE_LIGHT) -if (uLightEnable) - colorOut.rgb = vDiffuseColor.rgb * albedoColor.rgb + specular; -//#else -else - colorOut.rgb = albedoColor.rgb; -//#endif - - // フェードアウトを実装する -#if defined(AGX_FEATURE_FADE_OUT_COLOR) - colorOut.rgb = (colorOut.rgb * (1.0 - u_const3.a)) + (u_const3.rgb * u_const3.a); -#endif - - // 色を反映させる - gl_FragColor = colorOut; - - //#include - //#include -} -`; - -// ───────────────────────────────────────────────────────────── -// Helper: HermitianCurve for LUT generation -// ───────────────────────────────────────────────────────────── -class HermitianCurve { - keys: any[]; - constructor(keys: any[]) { - this.keys = keys.sort((a, b) => a.x - b.x); - } - interpolate(t: number, p0: number, p1: number, m0: number, m1: number) { - const h00 = 2 * t * t * t - 3 * t * t + 1; - const h10 = t * t * t - 2 * t * t + t; - const h01 = -2 * t * t * t + 3 * t * t; - const h11 = t * t * t - t * t; - return h00 * p0 + h10 * m0 + h01 * p1 + h11 * m1; - } - clamp(value: number, min: number, max: number) { - return Math.min(Math.max(value, min), max); - } - generateLUT(lutSize = 512) { - const lut = new Uint8Array(lutSize); - let keyIdx = 0; - for (let i = 0; i < lutSize; i++) { - const pos = i / (lutSize - 1); - while (keyIdx < this.keys.length - 2 && pos > this.keys[keyIdx + 1].x) { - keyIdx++; - } - const p0 = this.keys[keyIdx]; - const p1 = this.keys[keyIdx + 1]; - let t = (pos - p0.x) / (p1.x - p0.x); - t = isNaN(t) ? 0 : t; - let y = this.interpolate( - t, - p0.y, - p1.y, - p0.dx * (p1.x - p0.x), - p1.dx * (p1.x - p0.x) - ); - lut[i] = Math.round(this.clamp(y, 0, 1) * 255); - } - return lut; - } -} - -export interface LUTShaderOptions - extends Omit< - FFLShaderOptions, - "lightAmbient" | "lightDiffuse" | "lightSpecular" | "lightDirection" - > { - // -- Most of the options here are automatically derived from the FFL shader options. - - // Specific to LUT shader - alphaTest: boolean; - hslightGroundColor: THREE.Color; - hslightSkyColor: THREE.Color; - dirLightColor0: THREE.Color; - dirLightColor1: THREE.Color; - dirLightCount: number; - dirLightDirAndType0: THREE.Vector4; - dirLightDirAndType1: THREE.Vector4; - lightColor: THREE.Vector4; - // lightEnable is present -} - -export type LUTTexturesType = Record>; - -// ───────────────────────────────────────────────────────────── -// LUTShaderMaterial Class -// ───────────────────────────────────────────────────────────── -class LUTShaderMaterial extends THREE.ShaderMaterial { - // Enumerations for LUT types: - static LUTSpecularTextureType = { - NONE: 0, - DEFAULT_02: 1, - SKIN_01: 2, - MAX: 3, - }; - static LUTFresnelTextureType = { - NONE: 0, - DEFAULT_02: 1, - SKIN_01: 2, - MAX: 3, - }; - - // LUT curve definitions: - static lutDefinitions = { - specular: { - [LUTShaderMaterial.LUTSpecularTextureType.NONE]: new HermitianCurve([ - { x: 0, y: 0, dx: 0, dy: 0 }, - { x: 1, y: 0, dx: 0, dy: 0 }, - ]), - [LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02]: new HermitianCurve( - [ - { x: 0, y: 0, dx: 0, dy: 0 }, - { x: 0.05, y: 0, dx: 0, dy: 0 }, - { - x: 0.8, - y: 0.038, - dx: 0.157894736842105, - dy: 0.157894736842105, - }, - { x: 1, y: 0.11, dx: 0, dy: 0 }, - ] - ), - [LUTShaderMaterial.LUTSpecularTextureType.SKIN_01]: new HermitianCurve([ - { - x: 0, - y: 0.03, - dx: -0.105263157894737, - dy: -0.105263157894737, - }, - { x: 1, y: 0, dx: 0, dy: 0 }, - ]), - }, - fresnel: { - [LUTShaderMaterial.LUTFresnelTextureType.NONE]: new HermitianCurve([ - { x: 0, y: 0, dx: 0, dy: 0 }, - { x: 1, y: 0, dx: 0, dy: 0 }, - ]), - [LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02]: new HermitianCurve([ - { - x: 0, - y: 0.3, - dx: -0.105263157894734, - dy: -0.105263157894734, - }, - { - x: 0.175, - y: 0.23, - dx: -0.626315789473681, - dy: -0.626315789473681, - }, - { - x: 0.6, - y: 0.05, - dx: -0.210526315789474, - dy: -0.210526315789474, - }, - { - x: 1, - y: 0, - dx: -0.105263157894737, - dy: -0.105263157894737, - }, - ]), - [LUTShaderMaterial.LUTFresnelTextureType.SKIN_01]: new HermitianCurve([ - { - x: 0.005, - y: 0.35, - dx: -0.105263157894734, - dy: -0.105263157894734, - }, - { - x: 0.173, - y: 0.319, - dx: -0.205263157894734, - dy: -0.205263157894734, - }, - { - x: 0.552, - y: 0.051, - dx: -0.210526315789474, - dy: -0.210526315789474, - }, - { x: 1, y: 0.001, dx: 0, dy: 0 }, - ]), - }, - }; - - // LUT lookup tables (indexed by modulate type) - static modulateToLUTSpecular = [ - LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, // 0: FACELINE - LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, // 1: BEARD - LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, // 2: NOSE - LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, // 3: FOREHEAD - LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, // 4: HAIR - LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, // 5: CAP - LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, // 6: MASK - LUTShaderMaterial.LUTSpecularTextureType.NONE, // 7: NOSELINE - LUTShaderMaterial.LUTSpecularTextureType.NONE, // 8: GLASS - LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, // 9: CUSTOM (BODY) - LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, // 10: CUSTOM (PANTS) - ]; - static modulateToLUTFresnel = [ - LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, // 0: FACELINE - LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, // 1: BEARD - LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, // 2: NOSE - LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, // 3: FOREHEAD - LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, // 4: HAIR - LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, // 5: CAP - LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, // 6: MASK - LUTShaderMaterial.LUTFresnelTextureType.NONE, // 7: NOSELINE - LUTShaderMaterial.LUTFresnelTextureType.NONE, // 8: GLASS - LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, // 9: CUSTOM (BODY) - LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, // 10: CUSTOM (PANTS) - ]; - - // Cache LUT textures so we generate them only once. - static _lutTextures: LUTTexturesType | null = null; - static getLUTTextures(lutSize = 512) { - if (!LUTShaderMaterial._lutTextures) { - const textures: LUTTexturesType = { specular: {}, fresnel: {} }; - const r8 = - Number(THREE.REVISION) < 137 ? THREE.LuminanceFormat : THREE.RedFormat; - // Create specular LUT textures: - for (const [key, curve] of Object.entries( - LUTShaderMaterial.lutDefinitions.specular - )) { - const lutData = curve.generateLUT(lutSize); - const texture = new THREE.DataTexture( - lutData, - lutSize, - 1, - r8, - THREE.UnsignedByteType - ); - texture.needsUpdate = true; - textures.specular[key] = texture; - } - // Create fresnel LUT textures: - for (const [key, curve] of Object.entries( - LUTShaderMaterial.lutDefinitions.fresnel - )) { - const lutData = curve.generateLUT(lutSize); - const texture = new THREE.DataTexture( - lutData, - lutSize, - 1, - r8, - THREE.UnsignedByteType - ); - texture.needsUpdate = true; - textures.fresnel[key] = texture; - } - LUTShaderMaterial._lutTextures = textures; - } - return LUTShaderMaterial._lutTextures; - } - - // Default light colors for the LUT shader: - static defaultHSLightGroundColor = new THREE.Color( - 0.87843, - 0.72157, - 0.5898 - ) /*.convertSRGBToLinear()*/; - static defaultHSLightSkyColor = new THREE.Color( - 0.87843, - 0.83451, - 0.80314 - ) /*.convertSRGBToLinear()*/; - static defaultDirLightColor0 = new THREE.Color( - 0.35137, - 0.32392, - 0.32392 - ) /*.convertSRGBToLinear()*/; - static defaultDirLightColor1 = new THREE.Color( - 0.10039, - 0.09255, - 0.09255 - ) /*.convertSRGBToLinear()*/; - static defaultDirLightCount = 2; - static defaultDirLightDirAndType0 = new THREE.Vector4(-0.2, 0.5, 0.8, -1.0); - static defaultDirLightDirAndType1 = new THREE.Vector4( - 0.0, - -0.19612, - 0.98058, - -1.0 - ); - static defaultLightColor = new THREE.Color( - 0.35137, - 0.32392, - 0.32392 - ) /*.convertSRGBToLinear()*/; - - static defaultLightDirection = this.defaultDirLightDirAndType0; - - static getBlendOptionsFromModulateType(modulateType: number) { - if (modulateType >= 0 && modulateType <= 5) { - // Opaque (DrawOpa) - return { - blending: THREE.CustomBlending, - blendSrcAlpha: THREE.SrcAlphaFactor, - blendDstAlpha: THREE.OneFactor, - }; - } else if (modulateType >= 6 && modulateType <= 8) { - // Translucent (DrawXlu) - return { - blending: THREE.CustomBlending, - blendSrc: THREE.SrcAlphaFactor, - blendDst: THREE.OneMinusSrcAlphaFactor, - blendDstAlpha: THREE.OneFactor, - }; - } else if (modulateType >= 9 && modulateType <= 13) { - // Mask Textures - return { - blending: THREE.CustomBlending, - blendSrc: THREE.OneMinusDstAlphaFactor, - blendSrcAlpha: THREE.SrcAlphaFactor, - blendDst: THREE.DstAlphaFactor, - }; - } else if (modulateType >= 14 && modulateType <= 17) { - // Faceline Texture - return { - blending: THREE.CustomBlending, - blendSrc: THREE.SrcAlphaFactor, - blendDst: THREE.OneMinusSrcAlphaFactor, - blendSrcAlpha: THREE.OneFactor, - blendDstAlpha: THREE.OneFactor, - }; - } else { - console.error(`Unknown modulate type: ${modulateType}.`); - return {}; - } - } - - // Properties exposed by the constructor. - modulateMode: number; - modulateType: number; - modulateColor?: FFLColor; - lightEnable: boolean; - _side?: THREE.Side; // Store original side. - - /** - * Options (all optional): - * - modulateMode: number (default 0) - * - modulateType: number (default 0; used to pick LUTs via lookup tables) - * - modulateColor: either a THREE.Vector4 OR an array of 3 THREE.Vector4 - * (maps to u_const1, u_const2, u_const3) - * - lightEnable: boolean (default true) - * - dirLightDirAndType0, dirLightDirAndType1: THREE.Vector3 (default as defined) - * - map: (optional) albedo map - * - Additional light colors (hslight, directional, etc.) can be provided. - */ - constructor(options: Partial = {}) { - const modulateMode = options.modulateMode ?? 0; - const modulateType = options.modulateType ?? 0; - const lightEnable = options.lightEnable ?? true; - const texture = options.map || null; - // Enable alpha test for DrawXlu stage. - const alphaTest = - modulateType >= 6 && modulateType <= 8 ? true : options.alphaTest; - // Force culling to none for mask. - const side = - modulateType === 6 ? THREE.DoubleSide : options.side || THREE.FrontSide; - - // Process modulateColor: - let colorUniforms = {}; - if ( - Array.isArray(options.modulateColor) && - options.modulateColor.length === 3 - ) { - colorUniforms = { - u_const1: { value: options.modulateColor[0] }, - u_const2: { value: options.modulateColor[1] }, - u_const3: { value: options.modulateColor[2] }, - }; - } else { - colorUniforms = { - u_const1: { - value: options.modulateColor || new THREE.Vector4(1, 1, 1, 1), - }, - }; - } - - const lutTextures = LUTShaderMaterial.getLUTTextures(); - const specType = - LUTShaderMaterial.modulateToLUTSpecular[modulateType] ?? - LUTShaderMaterial.LUTSpecularTextureType.NONE; - const fresType = - LUTShaderMaterial.modulateToLUTFresnel[modulateType] ?? - LUTShaderMaterial.LUTFresnelTextureType.NONE; - const lutSpecTexture = lutTextures.specular[specType]; - const lutFresTexture = lutTextures.fresnel[fresType]; - - const uniforms = Object.assign({}, colorUniforms, { - uBoneCount: { value: 0 }, - uAlpha: { value: 1.0 }, - uHSLightGroundColor: { - value: - options.hslightGroundColor || - LUTShaderMaterial.defaultHSLightGroundColor, - }, - uHSLightSkyColor: { - value: - options.hslightSkyColor || LUTShaderMaterial.defaultHSLightSkyColor, - }, - uDirLightColor0: { - value: - options.dirLightColor0 || LUTShaderMaterial.defaultDirLightColor0, - }, - uDirLightColor1: { - value: - options.dirLightColor1 || LUTShaderMaterial.defaultDirLightColor1, - }, - uDirLightCount: { - value: options.dirLightCount || LUTShaderMaterial.defaultDirLightCount, - }, - uDirLightDirAndType0: { - value: - options.dirLightDirAndType0 || - LUTShaderMaterial.defaultDirLightDirAndType0.clone(), - }, - uDirLightDirAndType1: { - value: - options.dirLightDirAndType1 || - LUTShaderMaterial.defaultDirLightDirAndType1.clone(), - }, - uLightEnable: { value: lightEnable }, - uLightColor: { - value: options.lightColor || LUTShaderMaterial.defaultLightColor, - }, - uMode: { value: modulateMode }, - // NOTE about uAlphaTest: - // Only real purpose it serves is to discard/ - // skip writing depth for DrawXlu elements. - // Usually (not in Miitomo) all DrawXlu elements have depth writing disabled - // but in this case Miitomo has it enabled but discards depth writes here - uAlphaTest: { value: alphaTest }, - uAlbedoTexture: { value: texture }, - uLUTSpecTexture: { value: lutSpecTexture }, - uLUTFresTexture: { value: lutFresTexture }, - }); - - super({ - vertexShader: options.vertexShader || _LUTShader_vert, - fragmentShader: options.fragmentShader || _LUTShader_frag, - uniforms: uniforms, - side: side, - // skinning: options.skinning || false, // Not needed with newer Three.js. - // Merge blend options, only if modulateMode is not 0/opqaue. - ...(modulateMode !== 0 - ? LUTShaderMaterial.getBlendOptionsFromModulateType(modulateType) - : {}), - // NOTE: ^^ Assumes that default blending is equivalent to constant blending (test faceline make?) - //...getBlendOptionsFromModulateType(modulateType) // Merge blend options - }); - // Expose these properties. - this.modulateMode = modulateMode; - this.modulateType = modulateType; - this.modulateColor = options.modulateColor; - this.lightEnable = lightEnable; - this._side = options.side; // Store original side. - } - - get map() { - return this.uniforms.uAlbedoTexture.value; // Expose as 'map' - } - set map(value) { - this.uniforms.uAlbedoTexture.value = value; - } - get lightDirection() { - return this.uniforms.uDirLightDirAndType0.value; - } - set lightDirection(value) { - this.uniforms.uDirLightDirAndType0.value = value; - this.uniforms.uDirLightDirAndType0.value.w = -1; // Override w - } - // TODO: normalMap, etc...? see: https://github.com/pixiv/three-vrm/blob/776c2823dcf3453d689a2d56aa82b289fdf963cf/packages/three-vrm-materials-mtoon/src/MToonMaterial.ts#L75 -} - -export { LUTShaderMaterial }; // Export. +// @ts-check + +/** + * @typedef {number} FFLModulateMode + * @typedef {number} FFLModulateType + * @typedef {import('three')} THREE + */ + +/** + * @typedef {Object} LUTShaderMaterialParameters + * @property {FFLModulateMode} [modulateMode] - Modulate mode. + * @property {FFLModulateType} [modulateType] - Modulate type. + * @property {import('three').Color|Array} [color] - + * Constant color assigned to uColor0/1/2 depending on single or array. + * @property {import('three').Vector3} [lightDirection] - Light direction. + * @property {boolean} [lightEnable] - Enable lighting. Needs to be off when drawing faceline/mask textures. + * @property {import('three').Texture} [map] - Texture map. + */ + +// eslint-disable-next-line jsdoc/convert-to-jsdoc-comments -- not applicable +/* global define, require, module -- UMD globals. */ +(function (root, factory) { + // @ts-ignore - cannot find name define + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + // @ts-ignore + define(['three'], factory); + } else if (typeof module === 'object' && module.exports) { + // Node.js/CommonJS + module.exports = factory(require('three')); + } else { + // Browser globals + + // Assume THREE is defined in window. + /** @type {*} */ (root).LUTShaderMaterial = factory(/** @type {*} */ (root).THREE); + } +}(typeof self !== 'undefined' ? self : this, + /* eslint-disable jsdoc/require-returns-type -- Allow TS to predict return type. */ + /** + * @param {THREE} THREE - Three.js namespace. + * @returns Returns the exported namespace. + */ + function (THREE) { +/* eslint-enable jsdoc/require-returns-type -- Allow TS to predict return type. */ +'use strict'; +// // --------------------------------------------------------------------- +// // Vertex Shader for LUTShaderMaterial +// // Derived from LUT.vsh found in Miitomo. +// // --------------------------------------------------------------------- +const _LUTShader_vert = /* glsl */` +#define AGX_FEATURE_ALBEDO_TEXTURE +/** + * @file LUT.vsh + * @brief LUT + * @since 2014/10/02 + * + * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. + */ + +// シェーダーの種類毎に設定されるマクロリスト +// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 +// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 +// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 +// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 +// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 +// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 +// AGX_FEATURE_SKIN_MASK 肌マスクが有効(uColor0) +// AGX_FEATURE_HAIR_MASK 髪マスクが有効(uColor1) +// AGX_FEATURE_ALPHA_TEST アルファテストが有効 +// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(uColor2) +// AGX_FEATURE_DISABLE_LIGHT ライトが無効 +// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 +// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 +// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 +// AGX_FEATURE_MII Miiを描画する +// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant +// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct +// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered +// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha +// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha +// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa +// +// AGX_BONE_MAX ボーンの最大数 + +#ifdef GL_ES +precision highp float; +#else +# define lowp +# define mediump +# define highp +#endif + +//#ifndef AGX_BONE_MAX +//# define AGX_BONE_MAX 15 +//#endif +#ifndef AGX_DIR_LIGHT_MAX +# define AGX_DIR_LIGHT_MAX 2 +#endif + +// ---------------------------------------- +// 頂点シェーダーに入力される attribute 変数 +//attribute highp vec3 position; //!< 入力:[ 1 : 1 ] 位置情報 +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) +//attribute mediump vec2 uv; //!< 入力:[ 1 : 5 ] テクスチャー座標 +#endif +//attribute mediump vec3 normal; //!< 入力:[ 1 : 2 ] 法線ベクトル +//attribute mediump vec4 aBoneIndex; //!< 入力:[ 1 : 3 ] ボーンのインデックス(最大4つ) +//attribute mediump vec4 aBoneWeight; //!< 入力:[ 1 : 4 ] ボーンの影響度(最大4つ) +#if defined(AGX_FEATURE_VERTEX_COLOR) +//attribute lowp vec4 _color; //!< 入力:[ 1 : 6 ] 頂点カラー +#endif +#if defined(AGX_FEATURE_BUMP_TEXTURE) +//attribute mediump vec3 tangent; //!< 入力:[ 1 : 7 ] 接線ベクトル +#endif + +// ^^ Commented attributes are provided by three.js. + +// ---------------------------------------- +// 頂点シェーダーに入力される uniform 変数 +//uniform highp mat4 modelViewMatrix; //!< 入力:[ 4 / 4 : 4 ] モデルの合成行列 +//uniform mat4 projectionMatrix; +//uniform highp mat4 viewMatrix; //!< 入力:[ 4 / 4 : 8 ] モデルのビュー行列 +//uniform mediump mat3 normalMatrix; //!< 入力:[ 3 / 3 : 11 ] モデルの法線用行列 +//uniform highp mat4 modelMatrix; //!< 入力:[ 4 / 4 : 15 ] モデルのワールド変換行列 +//uniform lowp int uBoneCount; //!< 入力:[ 1 / 1 : 16 ] ボーンの個数 +//uniform highp mat4 uBoneMatrices[AGX_BONE_MAX]; //!< 入力:[ 4 x 15 / 60 : 76 ] ボーンの行列配列 +//uniform mediump mat3 uBoneNormalMatrices[AGX_BONE_MAX]; //!< 入力:[ 3 x 15 / 45 : 121 ] ボーンの法線行列配列 +// ^^ Unused in favor of three.js skinning. +uniform lowp int uDirLightCount; //!< 入力:[ 1 / 1 : 122 ] 方向ライトの数 +uniform mediump vec4 uDirLightDirAndType0;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 +uniform mediump vec4 uDirLightDirAndType1;//!< 入力:[ 1 x 2 / 2 : 124 ] 平行ライトの向く方向 +uniform mediump vec3 uDirLightColor0; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー +uniform mediump vec3 uDirLightColor1; //!< 入力:[ 1 x 2 / 2 : 126 ] 平行ライトのカラー +uniform mediump vec3 uHSLightSkyColor; //!< 入力:[ 1 / 1 : 127 ] 半球ライトのスカイカラー +uniform mediump vec3 uHSLightGroundColor; //!< 入力:[ 1 / 1 : 128 ] 半球ライトのグラウンドカラー +//uniform mediump vec3 cameraPosition; //!< 入力:[ 1 / 1 : 129 ] カメラの位置 +// ^^ previously uEyePt +uniform mediump float uAlpha; //!< 入力:[ 1 / 1 : 130 ] アルファ値 + +// ^^ Commented uniforms are provided by three.js. + +// ---------------------------------------- +// フラグメントシェーダーに渡される varying 変数 +varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 +#if !defined(AGX_FEATURE_BUMP_TEXTURE) +varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 +#endif +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) +varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV +#endif +// camera +varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル +#if !defined(AGX_FEATURE_DISABLE_LIGHT) +// punctual light +varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 +varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル +// GI +varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー +// Lighting Result +varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 +#endif +// Reflect +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) +varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル +#endif + +// skinning_pars_vertex.glsl.js +#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif + +// ------------------------------------------------------------ +// 頂点シェーダーのエントリーポイント +// ------------------------------------------------------------ +void main() +{ + // ------------------------------------------------------------ + // 頂点変換用の処理 + // ------------------------------------------------------------ + highp vec4 position_; //!< 最終的な頂点 + mediump vec3 normal_; //!< 最終的な法線 + mediump vec3 tangent_; //!< 最終的な接線 + highp vec4 positionWorld; //!< ワールド空間上での頂点 + + + // begin_vertex.glsl.js + vec3 transformed = vec3( position ); +// skinbase_vertex.glsl.js +#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); + // skinning_vertex.glsl.js + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif + + // ---------------------------------------- + // ボーンが存在しない場合は位置と法線に手を加えない + position_ = vec4(transformed.xyz, 1.0); + + + + normal_ = normal; +#if defined(AGX_FEATURE_BUMP_TEXTURE) + tangent_ = tangent.xyz; +#endif + // skinnormal_vertex.glsl.js +#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + + normal_ = vec4( skinMatrix * vec4( normal_, 0.0 ) ).xyz; +#if defined(AGX_FEATURE_BUMP_TEXTURE) + tangent_ = vec4( skinMatrix * vec4( tangent_, 0.0 ) ).xyz; +#endif // defined(AGX_FEATURE_BUMP_TEXTURE) +#endif // USE_SKINNING + + // ---------------------------------------- + // ワールド上での位置を求める + positionWorld = modelMatrix * position_; + // 最終結果を行う + position_ = projectionMatrix * modelViewMatrix * position_; + normal_ = normalize(normalMatrix * normal_); +#if defined(AGX_FEATURE_BUMP_TEXTURE) + tangent = normalize(normalMatrix * tangent_); +#endif + + // ---------------------------------------- + // 計算結果を保持させる + gl_Position = position_; +#if !defined(AGX_FEATURE_BUMP_TEXTURE) + vNormal = normal_; +#endif +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) + // テクスチャー座標を設定する + vTexcoord0 = uv; +#endif + // モデルの色を指定する +#if defined(AGX_FEATURE_VERTEX_COLOR) + lowp vec4 modelColor = aColor; + +#else + lowp vec4 modelColor = vec4(1.0, 1.0, 1.0, 1.0); +#endif + + // プリマルチプライドアルファ +#if defined(AGX_FEATURE_PREMULTIPLY_ALPHA) + modelColor *= uAlpha; +#else + modelColor.a *= uAlpha; +#endif + + + // ------------------------------------------------------------ + // ライト用の処理 + // ------------------------------------------------------------ + mediump vec3 eyeVecWorld; //!< ワールド状態での視線ベクトル + mediump vec3 eyeVec; //!< 最終的にフラグメントシェーダーに渡す視線ベクトル(バンプの有無によって、ワールド座標系になったり、タンジェント座標系になったりする) + + vec4 eye = modelViewMatrix * position_; + + // 視線ベクトルを取得する + //eyeVecWorld = normalize(cameraPosition - positionWorld.xyz); + eyeVecWorld = normalize(-(eye.xyz) - positionWorld.xyz);//normalize(cameraPosition - positionWorld.xyz); + eyeVec = eyeVecWorld; + + lowp vec3 diffuseColor = vec3(0.0); // バーテックスシェーダーで計算できるディフューズの色をここに格納する + +# if defined(AGX_FEATURE_BUMP_TEXTURE) + // Normal, Binormal, Tangent を取得する + mediump vec3 n = normal; + mediump vec3 t = tangent; + mediump vec3 b = cross(n, t); + // 接空間からローカルへ変換する行列を設定する(mat3(N, T, B)の逆行列) + mediump mat3 tangentMatrix = mat3(t.x, b.x, n.x, t.y, b.y, n.y, t.z, b.z, n.z); + // 視線ベクトルを接空間へ + vEyeVecWorldOrTangent.xyz = tangentMatrix * eyeVec; +#else + vEyeVecWorldOrTangent.xyz = eyeVec; +#endif + +#if !defined(AGX_FEATURE_DISABLE_LIGHT) + // punctual lightの設定 + if (uDirLightCount > 0) + { + mediump vec3 lightDir; + + // 方向ライト + if (uDirLightDirAndType0.w < 0.0) { lightDir = uDirLightDirAndType0.xyz; } + // 点光源ライト + else { lightDir = uDirLightDirAndType0.xyz - positionWorld.xyz; } + lightDir = normalize(lightDir); + +# if defined(AGX_FEATURE_BUMP_TEXTURE) + // ライトを接空間へ + vPunctualLightDirWorldOrTangent.xyz = tangentMatrix * lightDir; +# else + vPunctualLightDirWorldOrTangent.xyz = lightDir; +# endif + + // Halfベクトルを求める + vPunctualLightHalfVecWorldOrTangent.xyz = normalize(vPunctualLightDirWorldOrTangent.xyz + vEyeVecWorldOrTangent.xyz); + + // Diffuse計算 + diffuseColor += (uDirLightColor0.rgb * clamp(dot(lightDir, normal_), 0.0, 1.0)); + } + if (uDirLightCount > 1) + { + mediump vec3 lightDir; + + // 方向ライト + if (uDirLightDirAndType1.w < 0.0) { lightDir = uDirLightDirAndType1.xyz; } + // 点光源ライト + else { lightDir = uDirLightDirAndType1.xyz - positionWorld.xyz; } + lightDir = normalize(lightDir); + + diffuseColor += max(dot(lightDir, normal_), 0.0) * uDirLightColor1; + } + // ライトは1.0を超えないように + diffuseColor = min(diffuseColor, 1.0); +#endif + +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) + { + // キューブ環境マップ用の反射ベクトルを求める +// vReflectDir = reflect(normalize(positionWorld.xyz - cameraPosition), normal_); + + // スフィア環境マップ用の反射ベクトルを求める +// vReflectDir = normalize((uViewMatrix * vec4(normal_, 0.0)).xyz) * 0.5 + 0.5; + + // ビュー座標系での位置と法線を取得 + mediump vec3 viewNormal = normalize(mat3(uViewMatrix) * normal_); + mediump vec4 viewPosition = uViewMatrix * positionWorld; + viewPosition = viewPosition / viewPosition.w; + // ビュー座標系での頂点ベクトルを取得 + viewPosition.z = 1.0 - viewPosition.z; + mediump vec3 viewPositionVec = normalize(viewPosition.xyz); + // ビュー座標系での反射ベクトルを求める + mediump vec3 viewReflect = viewPositionVec - 2.0 * dot(viewPositionVec, viewNormal) * viewNormal; + // 両面スフィア環境マップではないので、反射ベクトルを調整 + viewReflect = normalize(viewReflect - vec3(0.0, 0.0, 1.5)); + // 反射ベクトルをテクスチャー座標系へ + vReflectDir = viewReflect * 0.5 + 0.5; + + // 公式 +// mediump vec3 viewPositionVec = normalize(vec3(uViewMatrix * positionWorld)); +// mediump vec3 viewReflectVec = viewPositionVec - 2.0 * dot(viewPositionVec, normal_) * normal; +// mediump float m = 2.0 * sqrt(viewReflectVec.x * viewReflectVec.x + +// viewReflectVec.y * viewReflectVec.y + +// (viewReflectVec.z + 1.0) * (viewReflectVec.z * 1.0)); +// vReflectDir = viewReflectVec / m + 0.5; + + // 別版 +// mediump vec3 posW = positionWorld.xyz; +// mediump vec3 dir = normalize(mat3(uViewMatrix) * normal); +// +// mediump float radius = 75.0; +// mediump vec3 posWDir = dot(dir, posW) * dir; +// mediump vec3 posWDirV = posW - posWDir; +// mediump float lengthDir = sqrt(radius * radius - dot(posWDirV, posWDirV)) - length(posWDir); +// vReflectDir = normalize(posW + dir * lengthDir) * 0.5 + 0.5; + } +#endif + +#if !defined(AGX_FEATURE_DISABLE_LIGHT) + // GIの計算 + { + mediump vec3 hemiColor; + mediump vec3 sky = uHSLightSkyColor; + mediump vec3 ground = uHSLightGroundColor; + + { + mediump float skyRatio = (normal_.y + 1.0) * 0.5; + hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); + diffuseColor += hemiColor; + } + + { +// mediump vec3 reflectDir = -reflect(normal_, eyeVecWorld); // おそらくコレで良いはず + mediump vec3 reflectDir = 2.0 * dot(eyeVecWorld, normal_) * normal_ - eyeVecWorld; // 多少冗長でも、正しい計算で行なう + + mediump float skyRatio = (reflectDir.y + 1.0) * 0.5; + hemiColor = (sky * skyRatio + ground * (1.0 - skyRatio)); + vGISpecularLightColor.rgb = hemiColor; + } + } +#endif + + // モデルの色を設定 + vModelColor = modelColor; +#if !defined(AGX_FEATURE_DISABLE_LIGHT) + vDiffuseColor.rgb = diffuseColor; +#endif +} +`; + +// // --------------------------------------------------------------------- +// // Fragment Shader for LUTShaderMaterial +// // Unmodified from LUT.fsh found in Miitomo. +// // --------------------------------------------------------------------- +const _LUTShader_frag = /* glsl */` +#define AGX_FEATURE_ALBEDO_TEXTURE +#define AGX_FEATURE_MII +/** + * @file LUT.fsh + * @brief LUT + * @since 2014/10/02 + * + * Copyright (c)2014 Nintendo Co., Ltd. All rights reserved. + */ + +// シェーダーの種類毎に設定されるマクロリスト +// AGX_FEATURE_VERTEX_COLOR 頂点カラーが有効 +// AGX_FEATURE_ALBEDO_TEXTURE アルベドテクスチャーが有効 +// AGX_FEATURE_BUMP_TEXTURE バンプテクスチャーが有効 +// AGX_FEATURE_MASK_TEXTURE マスクテクスチャーが有効 +// AGX_FEATURE_ALPHA_TEXTURE アルファテクスチャーが有効 +// AGX_FEATURE_SPHERE_MAP_TEXTURE スフィア環境マップが有効 +// AGX_FEATURE_SKIN_MASK 肌マスクが有効(uColor0) +// AGX_FEATURE_HAIR_MASK 髪マスクが有効(uColor1) +// AGX_FEATURE_ALPHA_TEST アルファテストが有効 +// AGX_FEATURE_FADE_OUT_COLOR フェードアウトカラーが有効(uColor2) +// AGX_FEATURE_DISABLE_LIGHT ライトが無効 +// AGX_FEATURE_ALPHA_COLOR_FILTER アルベドアルファによる色替えが有効 +// AGX_FEATURE_ALBEDO_ALPHA アルベドのアルファをカラーのアルファに適用 +// AGX_FEATURE_PREMULTIPLY_ALPHA プレマルチプライアルファな描画 +// AGX_FEATURE_MII Miiを描画する +// AGX_FEATURE_MII_CONSTANT Miiを描画する:Constant +// AGX_FEATURE_MII_TEXTURE_DIRECT Miiを描画する:Texture Direct +// AGX_FEATURE_MII_RGB_LAYERED Miiを描画する:RGB Layered +// AGX_FEATURE_MII_ALPHA Miiを描画する:Alpha +// AGX_FEATURE_MII_LUMINANCE_ALPHA Miiを描画する:Luminance Alpha +// AGX_FEATURE_MII_ALPHA_OPA Miiを描画する:Alpha Opa + +#ifdef GL_ES +precision mediump float; +#else +# define lowp +# define mediump +# define highp +#endif + +/// 変調処理のマクロ +#define FFL_MODULATE_MODE_CONSTANT 0 +#define FFL_MODULATE_MODE_TEXTURE_DIRECT 1 +#define FFL_MODULATE_MODE_RGB_LAYERED 2 +#define FFL_MODULATE_MODE_ALPHA 3 +#define FFL_MODULATE_MODE_LUMINANCE_ALPHA 4 +#define FFL_MODULATE_MODE_ALPHA_OPA 5 + +// ---------------------------------------- +// フラグメントシェーダーに入力される uniform 変数 +uniform int uMode; ///< 描画モード +uniform bool uAlphaTest; +uniform bool uLightEnable; +uniform mediump vec4 uColor0; //!< 入力:[ 1 : 1 ] カラー0 (OR 肌カラー) +uniform mediump vec4 uColor1; //!< 入力:[ 1 : 2 ] カラー1 (OR 髪カラー) +uniform mediump vec4 uColor2; //!< 入力:[ 1 : 3 ] カラー2 (OR フェードアウトカラー) +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +uniform mediump vec3 uLightColor; //!< 入力:[ 1 : 4 ] ライトの色 +//#endif + +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) +uniform sampler2D uAlbedoTexture; //!< 入力: テクスチャー +#endif +#if defined(AGX_FEATURE_BUMP_TEXTURE) +uniform sampler2D uNormalTexture; //!< 入力: ノーマルマップ +#endif +#if defined(AGX_FEATURE_MASK_TEXTURE) +uniform sampler2D uMaskTexture; //!< 入力:マスクテクスチャー +#endif +#if defined(AGX_FEATURE_ALPHA_TEXTURE) +uniform sampler2D uAlphaTexture; //!< 入力:アルファテクスチャー +#endif +uniform sampler2D uLUTSpecTexture; //!< 入力: スペキュラーLUT +uniform sampler2D uLUTFresTexture; //!< 入力: フレネルLUT +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) +uniform sampler2D uSphereMapTexture; //!< 入力: スフィア環境マップ +#endif + +// ---------------------------------------- +// フラグメントシェーダーに渡される varying 変数 +varying lowp vec4 vModelColor; //!< 出力:[ 1 : 1 ] モデルの色 +#if !defined(AGX_FEATURE_BUMP_TEXTURE) +varying mediump vec3 vNormal; //!< 出力:[ 1 : 2 ] モデルの法線 +#endif +#if defined(AGX_FEATURE_ALBEDO_TEXTURE) || defined(AGX_FEATURE_BUMP_TEXTURE) || defined(AGX_FEATURE_MASK_TEXTURE) || defined(AGX_FEATURE_ALPHA_TEXTURE) +varying mediump vec2 vTexcoord0; //!< 出力:[ 1 : 3 ] テクスチャーUV +#endif +// camera +varying mediump vec3 vEyeVecWorldOrTangent; //!< 出力:[ 1 : 4 ] 視線ベクトル +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +// punctual light +varying mediump vec3 vPunctualLightDirWorldOrTangent; //!< 出力:[ 1 : 5 ] ライトの方向 +varying mediump vec3 vPunctualLightHalfVecWorldOrTangent; //!< 出力:[ 1 : 6 ] カメラとライトのハーフベクトル +// GI +varying mediump vec3 vGISpecularLightColor; //!< 出力:[ 1 : 7 ] GIフレネルで使用するカラー +// Lighting Result +varying mediump vec3 vDiffuseColor; //!< 出力:[ 1 : 8 ] ディフューズライティング結果 +//#endif +// Reflect +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) +varying lowp vec3 vReflectDir; //!< 出力:[ 1 : 9 ] 環境マップの反射ベクトル +#endif + +// ------------------------------------------------------------ +// フラグメントシェーダーのエントリーポイント +// ------------------------------------------------------------ +void main() +{ + + // ディフューズカラーを取得 + lowp vec4 albedoColor = vec4(1.0, 1.0, 1.0, 1.0); + + // ============================================================ + // Mii + // ============================================================ +#if defined(AGX_FEATURE_MII) + + //#if defined(AGX_FEATURE_MII_CONSTANT) + if(uMode == FFL_MODULATE_MODE_CONSTANT) + { + albedoColor = uColor0; + } + //#elif defined(AGX_FEATURE_MII_TEXTURE_DIRECT) + else if(uMode == FFL_MODULATE_MODE_TEXTURE_DIRECT) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + } + //#elif defined(AGX_FEATURE_MII_RGB_LAYERED) + else if(uMode == FFL_MODULATE_MODE_RGB_LAYERED) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(albedoColor.r * uColor0.rgb + albedoColor.g * uColor1.rgb + albedoColor.b * uColor2.rgb, + uColor0.a * albedoColor.a); + } + //#elif defined(AGX_FEATURE_MII_ALPHA) + else if(uMode == FFL_MODULATE_MODE_ALPHA) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(uColor0.rgb, uColor0.a * albedoColor.r); + } + //#elif defined(AGX_FEATURE_MII_LUMINANCE_ALPHA) + else if(uMode == FFL_MODULATE_MODE_LUMINANCE_ALPHA) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(albedoColor.g * uColor0.rgb, uColor0.a * albedoColor.r); + } + //#elif defined(AGX_FEATURE_MII_ALPHA_OPA) + else if(uMode == FFL_MODULATE_MODE_ALPHA_OPA) + { + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); + albedoColor = vec4(albedoColor.r * uColor0.rgb, uColor0.a); + } +//#endif + + albedoColor = albedoColor * vModelColor; +#endif + + // ============================================================ + // Albedo Texture + // ============================================================ +#if !defined(AGX_FEATURE_MII) && defined(AGX_FEATURE_ALBEDO_TEXTURE) + albedoColor = texture2D(uAlbedoTexture, vTexcoord0); +#endif +#if defined(AGX_FEATURE_ALPHA_TEXTURE) + albedoColor.a = texture2D(uAlphaTexture, vTexcoord0).r; +#endif + + // ============================================================ + // Color Mask + // ============================================================ + // ---------------------------------------- + // Deprecated +#if defined(AGX_FEATURE_ALPHA_COLOR_FILTER) + // 一部の場所にColor0を反映する + albedoColor.rgb = (albedoColor.rgb * albedoColor.a + uColor0.rgb * (1.0 - albedoColor.a)); + albedoColor.a = 1.0; +#elif defined(AGX_FEATURE_MASK_TEXTURE) + lowp vec3 maskTextureColor = texture2D(uMaskTexture, vTexcoord0).rgb; + +# if defined(AGX_FEATURE_SKIN_MASK) && defined(AGX_FEATURE_HAIR_MASK) + // 肌と髪両方マスクが存在する + lowp float maskColorValue = maskTextureColor.g + maskTextureColor.b; + lowp vec3 maskColor = maskTextureColor.g * uColor0.rgb + maskTextureColor.b * uColor1.rgb; + albedoColor.rgb = (albedoColor.rgb * (1.0 - maskColorValue) + maskColor); + +# elif defined(AGX_FEATURE_SKIN_MASK) + // 肌しかマスクが存在しない + albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.g) + maskTextureColor.g * uColor0.rgb); + +# elif defined(AGX_FEATURE_HAIR_MASK) + // 髪しかマスクが存在しない + albedoColor.rgb = (albedoColor.rgb * (1.0 - maskTextureColor.b) + maskTextureColor.b * uColor1.rgb); + +# endif +#endif + + // アルベドに頂点カラーを掛ける + albedoColor *= vModelColor; + + // ============================================================ + // Alpha test + // ============================================================ +//#if defined(AGX_FEATURE_ALPHA_TEST) + if (uAlphaTest && albedoColor.a < 0.5) { discard; } +//#endif + + // ============================================================ + // Bumpmap + // ============================================================ + // 頂点からの情報 + lowp vec3 normalWorldOrTangent; +#if defined(AGX_FEATURE_BUMP_TEXTURE) + // バンプマップから法線を取得する + mediump vec3 bumpNormal = texture2D(uNormalTexture, vTexcoord0).rgb; + + // 法線の正規化は処理が重いのでいったん正規化しない様に... +// normalWorldOrTangent = normalize(bumpNormal * 2.0 - 1.0); + normalWorldOrTangent = bumpNormal * 2.0 - 1.0; + +#else + // 法線を正規化して取得する + normalWorldOrTangent = normalize(vNormal); +#endif + + // ============================================================ + // Lighting + // ============================================================ + // 最終的なカラー情報 + lowp vec4 colorOut = vec4(0.0, 0.0, 0.0, albedoColor.a); // 最終的に出力される色 + lowp vec3 fresnel = vec3(0.0, 0.0, 0.0); // フレネル + lowp vec3 specular = vec3(0.0, 0.0, 0.0); // スペキュラー + +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +if (uLightEnable) { + + // BRDFの計算を行う(バンプマッピングの場合は接空間) + lowp vec3 N = normalWorldOrTangent; + lowp vec3 V = vEyeVecWorldOrTangent.xyz;//normalize(vEyeVecWorldOrTangent.xyz); + lowp vec3 I = vPunctualLightDirWorldOrTangent.xyz;//normalize(vPunctualLightDirWorldOrTangent.xyz); + lowp vec3 H = vPunctualLightHalfVecWorldOrTangent.xyz;//normalize(vPunctualLightHalfVecWorldOrTangent.xyz); + + + // ---------------------------------------- + // punctual light + // 平行光源や点光源などの厳密なライティング計算を行なうもの + { + lowp float fSpecular = dot(N, H); + + lowp float specularIntensity = texture2D(uLUTSpecTexture, vec2(fSpecular)).r; + specular = (specularIntensity * uLightColor.rgb); + } + + // ---------------------------------------- + // GI + // 半球ライトやIBL、SHのように法線方向に半球積分された結果でライティング計算を行なうもの + { + lowp float fFresnel = dot(N, V); + lowp float fresnelIntensity = texture2D(uLUTFresTexture, vec2(fFresnel)).r; + + fresnel = (fresnelIntensity * vGISpecularLightColor.rgb); + } +} +//#endif + +#if defined(AGX_FEATURE_SPHERE_MAP_TEXTURE) + // スフィア環境マップ + specular += texture2D(uSphereMapTexture, vReflectDir.xy).rgb; +#endif + + // ============================================================ + // Specular Mask + // ============================================================ +#if !defined(AGX_FEATURE_ALPHA_COLOR_FILTER) && defined(AGX_FEATURE_MASK_TEXTURE) + // スペキュラーマスク + specular = specular * maskTextureColor.r + fresnel; +#else + specular += fresnel; +#endif + + // ============================================================ + // Output + // ============================================================ +//#if !defined(AGX_FEATURE_DISABLE_LIGHT) +if (uLightEnable) + colorOut.rgb = vDiffuseColor.rgb * albedoColor.rgb + specular; +//#else +else + colorOut.rgb = albedoColor.rgb; +//#endif + + // フェードアウトを実装する +#if defined(AGX_FEATURE_FADE_OUT_COLOR) + colorOut.rgb = (colorOut.rgb * (1.0 - uColor2.a)) + (uColor2.rgb * uColor2.a); +#endif + + // 色を反映させる + gl_FragColor = colorOut; + + //#include + //#include +} +`; + +// // --------------------------------------------------------------------- +// // Helper: HermitianCurve for LUT generation +// // --------------------------------------------------------------------- +/** Represents a Hermitian curve interpolation for LUT generation. */ +class HermitianCurve { + /** + * Constructs a HermitianCurve with given control points (keys). + * @param {Array<{x: number, y: number, dx: number, dy: number}>} keys - Control points defining the curve. + */ + constructor(keys) { + this.keys = keys.sort((a, b) => a.x - b.x); + } + + /** + * Performs Hermite interpolation between two points. + * @param {number} t - Interpolation factor (0 to 1). + * @param {number} p0 - Start point value. + * @param {number} p1 - End point value. + * @param {number} m0 - Tangent at start point. + * @param {number} m1 - Tangent at end point. + * @returns {number} Interpolated value. + */ + interpolate(t, p0, p1, m0, m1) { + const h00 = 2 * t * t * t - 3 * t * t + 1; + const h10 = t * t * t - 2 * t * t + t; + const h01 = -2 * t * t * t + 3 * t * t; + const h11 = t * t * t - t * t; + return h00 * p0 + h10 * m0 + h01 * p1 + h11 * m1; + } + + /** + * Clamps a value between a minimum and maximum. + * @param {number} value - Value to clamp. + * @param {number} min - Minimum allowed value. + * @param {number} max - Maximum allowed value. + * @returns {number} Clamped value. + */ + clamp(value, min, max) { + return Math.min(Math.max(value, min), max); + } + + /** + * Generates a Lookup Table (LUT) based on the Hermitian curve. + * @param {number} [lutSize] - Size of the LUT. + * @returns {Uint8Array} The generated LUT. + */ + generateLUT(lutSize = 512) { + const lut = new Uint8Array(lutSize); + let keyIdx = 0; + for (let i = 0; i < lutSize; i++) { + const pos = i / (lutSize - 1); + while (keyIdx < this.keys.length - 2 && pos > this.keys[keyIdx + 1].x) { + keyIdx++; + } + const p0 = this.keys[keyIdx]; + const p1 = this.keys[keyIdx + 1]; + let t = (pos - p0.x) / (p1.x - p0.x); + t = isNaN(t) ? 0 : t; + const y = this.interpolate( + t, + p0.y, + p1.y, + p0.dx * (p1.x - p0.x), + p1.dx * (p1.x - p0.x) + ); + lut[i] = Math.round(this.clamp(y, 0, 1) * 255); + } + return lut; + } +} + +// // --------------------------------------------------------------------- +// // LUTShaderMaterial Class +// // --------------------------------------------------------------------- +/** + * Custom THREE.ShaderMaterial using the LUT shader from Miitomo. + * @augments {THREE.ShaderMaterial} + */ +class LUTShaderMaterial extends THREE.ShaderMaterial { + // Enumerations for LUT types. + + /** @enum {number} */ + static LUTSpecularTextureType = { + NONE: 0, + DEFAULT_02: 1, + SKIN_01: 2, + MAX: 3 + }; + + /** @enum {number} */ + static LUTFresnelTextureType = { + NONE: 0, + DEFAULT_02: 1, + SKIN_01: 2, + MAX: 3 + }; + + /* eslint-disable jsdoc/no-undefined-types -- LUTSpecularTextureType, LUTFresnelTextureType, HermitanCurve */ + /** + * LUT definitions for materials used in the original shader. + * Taken from XMLs in the same folder as the original TGAs.. + * @typedef {Object} SpecularLUT + * @typedef {Object} FresnelLUT + * @type {{ specular: SpecularLUT, fresnel: FresnelLUT }} + * @package + */ + static lutDefinitions = { + specular: { + [LUTShaderMaterial.LUTSpecularTextureType.NONE]: new HermitianCurve([ + { x: 0, y: 0, dx: 0, dy: 0 }, + { x: 1, y: 0, dx: 0, dy: 0 } + ]), + [LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02]: new HermitianCurve([ + { x: 0, y: 0, dx: 0, dy: 0 }, + { x: 0.05, y: 0, dx: 0, dy: 0 }, + { + x: 0.8, + y: 0.038, + dx: 0.157894736842105, + dy: 0.157894736842105 + }, + { x: 1, y: 0.11, dx: 0, dy: 0 } + ]), + [LUTShaderMaterial.LUTSpecularTextureType.SKIN_01]: new HermitianCurve([ + { + x: 0, + y: 0.03, + dx: -0.105263157894737, + dy: -0.105263157894737 + }, + { x: 1, y: 0, dx: 0, dy: 0 } + ]) + }, + fresnel: { + [LUTShaderMaterial.LUTFresnelTextureType.NONE]: new HermitianCurve([ + { x: 0, y: 0, dx: 0, dy: 0 }, + { x: 1, y: 0, dx: 0, dy: 0 } + ]), + [LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02]: new HermitianCurve([ + { + x: 0, + y: 0.3, + dx: -0.105263157894734, + dy: -0.105263157894734 + }, + { + x: 0.175, + y: 0.23, + dx: -0.626315789473681, + dy: -0.626315789473681 + }, + { + x: 0.6, + y: 0.05, + dx: -0.210526315789474, + dy: -0.210526315789474 + }, + { + x: 1, + y: 0, + dx: -0.105263157894737, + dy: -0.105263157894737 + } + ]), + [LUTShaderMaterial.LUTFresnelTextureType.SKIN_01]: new HermitianCurve([ + { + x: 0.005, + y: 0.35, + dx: -0.105263157894734, + dy: -0.105263157894734 + }, + { + x: 0.173, + y: 0.319, + dx: -0.205263157894734, + dy: -0.205263157894734 + }, + { + x: 0.552, + y: 0.051, + dx: -0.210526315789474, + dy: -0.210526315789474 + }, + { x: 1, y: 0.001, dx: 0, dy: 0 } + ]) + } + }; + + // Tables mapping modulate type to LUT type. + /** @type {Object} */ + static modulateTypeToLUTSpecular = [ + LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, // 0: FACELINE + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, // 1: BEARD + LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, // 2: NOSE + LUTShaderMaterial.LUTSpecularTextureType.SKIN_01, // 3: FOREHEAD + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, // 4: HAIR + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, // 5: CAP + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, // 6: MASK + LUTShaderMaterial.LUTSpecularTextureType.NONE, // 7: NOSELINE + LUTShaderMaterial.LUTSpecularTextureType.NONE, // 8: GLASS + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02, // 9: CUSTOM (BODY) + LUTShaderMaterial.LUTSpecularTextureType.DEFAULT_02 // 10: CUSTOM (PANTS) + ]; + + /** @type {Object} */ + static modulateTypeToLUTFresnel = [ + LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, // 0: FACELINE + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, // 1: BEARD + LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, // 2: NOSE + LUTShaderMaterial.LUTFresnelTextureType.SKIN_01, // 3: FOREHEAD + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, // 4: HAIR + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, // 5: CAP + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, // 6: MASK + LUTShaderMaterial.LUTFresnelTextureType.NONE, // 7: NOSELINE + LUTShaderMaterial.LUTFresnelTextureType.NONE, // 8: GLASS + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02, // 9: CUSTOM (BODY) + LUTShaderMaterial.LUTFresnelTextureType.DEFAULT_02 // 10: CUSTOM (PANTS) + ]; + + /** + * Cached LUT textures to avoid redundant generation. + * @typedef {Object} LUTTextures + * @property {Object} specular - + * Specular LUT textures indexed by LUT type. + * @property {Object} fresnel - + * Fresnel LUT textures indexed by LUT type. + */ + /** + * @type {LUTTextures|null} + * @package + */ + static _lutTextures = null; + + /** + * Generates and return LUT textures. + * @param {number} [lutSize] - Width of the LUT. + * @returns {LUTTextures} Specular and fresnel LUT textures. + */ + static getLUTTextures(lutSize = 512) { + if (LUTShaderMaterial._lutTextures) { + return LUTShaderMaterial._lutTextures; + } + const textures = /** @type {LUTTextures} */ ({ specular: {}, fresnel: {} }); + // Get the texture format dynamically based on Three.js version. + const r8 = Number(THREE.REVISION) <= 136 + ? THREE.LuminanceFormat + : THREE.RedFormat; + + /** + * Helper function to generate LUT textures. + * @param {Object} lutType - The mapping for LUT type to {@link HermitanCurve}. + * @param {Object} target - + * The {@link LUTTextures} type instance to emit textures to. + */ + function generateLUTTextures(lutType, target) { + for (const key in lutType) { + const lutData = lutType[key].generateLUT(lutSize); + target[Number(key)] = Object.assign( + new THREE.DataTexture( + // Uint8Array.from(lutData.flatMap(value => [value, 0, 0, 255])), // RGBA + lutData, + lutSize, + 1, + r8, + // THREE.RGBAFormat, // RGBA + THREE.UnsignedByteType + ), + { + colorSpace: THREE.LinearSRGBColorSpace, + needsUpdate: true + } + ); + } + } + + generateLUTTextures(LUTShaderMaterial.lutDefinitions.specular, textures.specular); + generateLUTTextures(LUTShaderMaterial.lutDefinitions.fresnel, textures.fresnel); + + LUTShaderMaterial._lutTextures = textures; + return textures; + } + + /* eslint-enable jsdoc/no-undefined-types -- LUTSpecularTextureType, LUTFresnelTextureType, HermitanCurve */ + + // Default light colors for the LUT shader. + /** @type {import('three').Color} */ + static defaultHSLightGroundColor = new THREE.Color(0.87843, 0.72157, 0.5898); + /** @type {import('three').Color} */ + static defaultHSLightSkyColor = new THREE.Color(0.87843, 0.83451, 0.80314); + /** @type {import('three').Color} */ + static defaultDirLightColor0 = new THREE.Color(0.35137, 0.32392, 0.32392); + /** @type {import('three').Color} */ + static defaultDirLightColor1 = new THREE.Color(0.10039, 0.09255, 0.09255); + static defaultDirLightCount = 2; + /** @type {import('three').Vector4} */ + static defaultDirLightDirAndType0 = new THREE.Vector4(-0.2, 0.5, 0.8, -1.0); + /** @type {import('three').Vector4} */ + static defaultDirLightDirAndType1 = new THREE.Vector4(0.0, -0.19612, 0.98058, -1.0); + /** @type {import('three').Color} */ + static defaultLightColor = new THREE.Color(0.35137, 0.32392, 0.32392); + + /** + * Alias for default light direction. + * @type {import('three').Vector4} + */ + static defaultLightDirection = this.defaultDirLightDirAndType0; + + /** + * Multiplies beard and hair colors by a factor seen + * in libcocos2dcpp.so in order to match its rendering style. + * Refer to: https://github.com/ariankordi/FFL-Testing/blob/16dd44c8848e0820e03f8ccb0efa1f09f4bc2dca/src/ShaderMiitomo.cpp#L587 + * @param {import('three').Color} color - The original color. + * @param {FFLModulateType} modulateType - The modulate type, or type of shape. + * @param {FFLModulateMode} modulateMode - The modulate mode, used to confirm custom body type. + * @returns {import('three').Color} The final color. + * @package + */ + static multiplyColorIfNeeded(color, modulateType, modulateMode) { + if ( + modulateType === 1 || // SHAPE_BEARD + modulateType === 4 || // SHAPE_HAIR + (modulateMode === 0 && // CONSTANT + modulateType === 9) // CUSTOM (BODY) + ) { + const mul = 0.9019608; + // Multiply XYZ (RGB) by mul and not alpha. + color.r *= mul; + color.g *= mul; + color.b *= mul; + } + return color; // no multiply needed + } + + /** @typedef {import('three').IUniform} IUniformVector4 */ + + /** + * Constructs a LUTShaderMaterial instance. + * NOTE: Pass parameters in this order: side, modulateType, color + * @param {import('three').ShaderMaterialParameters & LUTShaderMaterialParameters} [options] - + * Parameters for the material. + */ + constructor(options = {}) { + // Set default uniforms. + /** @type {Object} */ + const uniforms = { + uBoneCount: { value: 0 }, + uAlpha: { value: 1.0 }, + uHSLightGroundColor: { + value: LUTShaderMaterial.defaultHSLightGroundColor + }, + uHSLightSkyColor: { + value: LUTShaderMaterial.defaultHSLightSkyColor + }, + uDirLightColor0: { + value: LUTShaderMaterial.defaultDirLightColor0 + }, + uDirLightColor1: { + value: LUTShaderMaterial.defaultDirLightColor1 + }, + uDirLightCount: { + value: LUTShaderMaterial.defaultDirLightCount + }, + uDirLightDirAndType0: { + value: LUTShaderMaterial.defaultDirLightDirAndType0.clone() + }, + uDirLightDirAndType1: { + value: LUTShaderMaterial.defaultDirLightDirAndType1.clone() + }, + uLightEnable: { value: true }, // Default to true. + uLightColor: { value: LUTShaderMaterial.defaultLightColor } + }; + + // Construct the ShaderMaterial using the shader source. + super({ + vertexShader: _LUTShader_vert, + fragmentShader: _LUTShader_frag, + uniforms: uniforms + }); + + /** @type {FFLModulateType} */ + this._modulateType = 0; // Initialize default for modulateType field. + + // Use the setters to set the rest of the uniforms. + this.setValues(options); + } + + /** + * Gets the constant color (uColor0) uniform as THREE.Color. + * @returns {import('three').Color|null} The constant color, or null if it is not set. + */ + get color() { + if (!this.uniforms.uColor0) { + // If color is not set, return null. + return null; + } else if (this._color3) { + // Use cached THREE.Color instance if it is set. + return this._color3; + } + // Get THREE.Color from uColor0 (Vector4). + const color4 = /** @type {IUniformVector4} */ (this.uniforms.uColor0).value; + const color3 = new THREE.Color(color4.x, color4.y, color4.z); + this._color3 = color3; // Cache the THREE.Color instance. + return color3; + } + + /** + * Sets the constant color uniforms from THREE.Color. + * @param {import('three').Color|Array} value - The + * constant color (uColor0), or multiple (uColor0/1/2) to set the uniforms for. + */ + set color(value) { + /** + * @param {import('three').Color} color - THREE.Color instance. + * @param {number} opacity - Opacity mapped to .a. + * @returns {import('three').Vector4} Vector4 containing color and opacity. + */ + function toColor4(color, opacity = 1.0) { + return new THREE.Vector4(color.r, color.g, color.b, opacity); + } + // Set an array of colors, assumed to have 3 elements. + if (Array.isArray(value)) { + // Assign multiple color instances to uColor0/1/2. + /** @type {IUniformVector4} */ (this.uniforms.uColor0) = + { value: toColor4(value[0]) }; + /** @type {IUniformVector4} */ (this.uniforms.uColor1) = + { value: toColor4(value[1]) }; + /** @type {IUniformVector4} */ (this.uniforms.uColor2) = + { value: toColor4(value[2]) }; + return; + } + // Set single color as THREE.Color, defaulting to white. + const color3 = value ? value : new THREE.Color(1.0, 1.0, 1.0); + /** @type {import('three').Color} */ + this._color3 = color3.clone(); // Clone and save the color before modification. + + // Use multiplyColorIfNeeded method for a single color. + if (this.modulateType !== undefined && typeof this.modulateMode === 'number') { + LUTShaderMaterial.multiplyColorIfNeeded(color3, this.modulateType, this.modulateMode); + } + + // Assign single color with white as a placeholder. + const opacity = this.opacity; + if (this._opacity) { + // if _opacity is set then the above returned it, delete when done + delete this._opacity; + } + /** @type {IUniformVector4} */ (this.uniforms.uColor0) = + { value: toColor4(color3, opacity) }; + } + + /** + * Gets the opacity of the constant color. + * @returns {number} The opacity value. + */ + // @ts-ignore - Already defined on parent class. + get opacity() { + if (!this.uniforms.uColor0) { + // Get from _opacity if it is set before constant color. + return this._opacity ? this._opacity : 1; + } + // Return w (alpha) of the constant color uniform. + return /** @type {IUniformVector4} */ (this.uniforms.uColor0).value.w; + } + + /** + * Sets the opacity of the constant color. + * NOTE: that this is actually set in the constructor + * of Material, meaning it is the only one set BEFORE uniforms are + * @param {number} value - The new opacity value. + */ + // @ts-ignore - Already defined on parent class. + set opacity(value) { + if (!this.uniforms || !this.uniforms.uColor0) { + // Store here for later when color is set. + this._opacity = 1; + return; + } + /** @type {IUniformVector4} */ (this.uniforms.uColor0).value.w = value; + } + + /** + * Gets the value of the modulateMode uniform. + * @returns {FFLModulateMode|null} The modulateMode value, or null if it is unset. + */ + get modulateMode() { + return this.uniforms.uMode ? this.uniforms.uMode.value : null; + } + + /** + * Sets the value of the modulateMode uniform. + * @param {FFLModulateMode} value - The new modulateMode value. + */ + set modulateMode(value) { + this.uniforms.uMode = { value: value }; + } + + /** + * Sets the value determining whether lighting is enabled or not. + * @returns {boolean|null} The lightEnable value, or null if it is unset. + */ + get lightEnable() { + return this.uniforms.uLightEnable ? this.uniforms.uLightEnable.value : null; + } + + /** + * Sets the value determining whether lighting is enabled or not. + * @param {boolean} value - The lightEnable value. + */ + set lightEnable(value) { + this.uniforms.uLightEnable = { value: value }; + } + + /** + * Gets the modulateType value. + * @returns {FFLModulateType|undefined} The modulateType value if it is set. + */ + get modulateType() { + // This isn't actually a uniform so this is a private property. + return this._modulateType; + } + + /** + * Sets the material uniforms based on the modulate type value. + * @param {FFLModulateType} value - The new modulateType value. + */ + set modulateType(value) { + // Assign LUT textures using modulate type. + const lutTextures = LUTShaderMaterial.getLUTTextures(); + const specType = + LUTShaderMaterial.modulateTypeToLUTSpecular[value]; + const fresType = + LUTShaderMaterial.modulateTypeToLUTFresnel[value]; + if (specType === undefined || fresType === undefined) { + return; + } + this._modulateType = value; + + const lutSpecTexture = lutTextures.specular[specType]; + const lutFresTexture = lutTextures.fresnel[fresType]; + + this.uniforms.uLUTSpecTexture = { value: lutSpecTexture }; + this.uniforms.uLUTFresTexture = { value: lutFresTexture }; + // Only real purpose of uAlphaTest is to discard/ + // skip writing depth for DrawXlu stage. + // Usually (not in Miitomo) all DrawXlu elements have depth writing disabled + // but in this case Miitomo has it enabled but discards depth writes here + this.uniforms.uAlphaTest = { + value: (value >= 6 && value <= 8) + }; + + /** @type {number|undefined} */ + this._side = this.side; // Store original side. + // Force culling to none for mask. + this.side = (value === 6 ? THREE.DoubleSide : this.side); + } + + /** + * Gets the texture map. + * @returns {THREE['Texture']} The texture map. + */ + get map() { + return this.uniforms.uAlbedoTexture ? this.uniforms.uAlbedoTexture.value : null; + } + + /** + * Sets the texture map. + * @param {import('three').Texture} value - The new texture map. + */ + set map(value) { + this.uniforms.uAlbedoTexture = { value: value }; + } + + /** + * Gets the light direction. + * @returns {import('three').Vector3} The light direction. + */ + get lightDirection() { + return this.uniforms.uDirLightDirAndType0.value; + } + + /** + * Sets the light direction, overriding w with -1. + * @param {import('three').Vector3} value - The new light direction. + */ + set lightDirection(value) { + this.uniforms.uDirLightDirAndType0 = { value: value }; + this.uniforms.uDirLightDirAndType0.value.w = -1; // Override w + } + // TODO: normalMap, etc...? see: https://github.com/pixiv/three-vrm/blob/776c2823dcf3453d689a2d56aa82b289fdf963cf/packages/three-vrm-materials-mtoon/src/MToonMaterial.ts#L75 +} + +/** @global */ +// window.LUTShaderMaterial = LUTShaderMaterial; +// export { LUTShaderMaterial }; + +return LUTShaderMaterial; +})); diff --git a/src/external/ffl.js/README.md b/src/external/ffl.js/README.md deleted file mode 100644 index 6baae0a..0000000 --- a/src/external/ffl.js/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# FFL.js support - -The scripts in here are all copied directly from Arian's awesome [FFL.js](https://github.com/ariankordi/ffl.js) repository. Please check out their work. - -If you're going to build any Emscripten changes, make sure to edit the `ffl-emscripten.js` file to point to `ffl-emscripten.wasm` inside the public/dist folder or else it won't work. \ No newline at end of file diff --git a/src/external/ffl.js/ffl-emscripten.js b/src/external/ffl.js/ffl-emscripten.js index 3e47a6d..259ba5f 100644 --- a/src/external/ffl.js/ffl-emscripten.js +++ b/src/external/ffl.js/ffl-emscripten.js @@ -1 +1,21 @@ -var Module=typeof Module!="undefined"?Module:{};var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var moduleOverrides=Object.assign({},Module);var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(scriptDirectory.startsWith("blob:")){scriptDirectory=""}else{scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}{readAsync=url=>fetch(url,{credentials:"same-origin"}).then(response=>{if(response.ok){return response.arrayBuffer()}return Promise.reject(new Error(response.status+" : "+response.url))})}}else{}var out=Module["print"]||console.log.bind(console);var err=Module["printErr"]||console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;if(Module["arguments"])arguments_=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];if(Module["quit"])quit_=Module["quit"];var wasmBinary;if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"];var wasmMemory;var ABORT=false;var EXITSTATUS;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b)}var __ATPRERUN__=[];var __ATINIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}function addOnInit(cb){__ATINIT__.unshift(cb)}function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;Module["monitorRunDependencies"]?.(runDependencies)}function removeRunDependency(id){runDependencies--;Module["monitorRunDependencies"]?.(runDependencies);if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){Module["onAbort"]?.(what);what="Aborted("+what+")";err(what);ABORT=true;EXITSTATUS=1;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var dataURIPrefix="data:application/octet-stream;base64,";var isDataURI=filename=>filename.startsWith(dataURIPrefix);function findWasmBinary(){var f="/dist/ffl-emscripten.wasm";if(!isDataURI(f)){return locateFile(f)}return f}var wasmBinaryFile;function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(binaryFile){if(!wasmBinary){return readAsync(binaryFile).then(response=>new Uint8Array(response),()=>getBinarySync(binaryFile))}return Promise.resolve().then(()=>getBinarySync(binaryFile))}function instantiateArrayBuffer(binaryFile,imports,receiver){return getBinaryPromise(binaryFile).then(binary=>WebAssembly.instantiate(binary,imports)).then(receiver,reason=>{err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)})}function instantiateAsync(binary,binaryFile,imports,callback){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(binaryFile)&&typeof fetch=="function"){return fetch(binaryFile,{credentials:"same-origin"}).then(response=>{var result=WebAssembly.instantiateStreaming(response,imports);return result.then(callback,function(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation");return instantiateArrayBuffer(binaryFile,imports,callback)})})}return instantiateArrayBuffer(binaryFile,imports,callback)}function getWasmImports(){return{a:wasmImports}}function createWasm(){var info=getWasmImports();function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["e"];updateMemoryViews();wasmTable=wasmExports["O"];addOnInit(wasmExports["f"]);removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){receiveInstance(result["instance"])}if(Module["instantiateWasm"]){try{return Module["instantiateWasm"](info,receiveInstance)}catch(e){err(`Module.instantiateWasm callback failed with error: ${e}`);return false}}if(!wasmBinaryFile)wasmBinaryFile=findWasmBinary();instantiateAsync(wasmBinary,wasmBinaryFile,info,receiveInstantiationResult);return{}}var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var noExitRuntime=Module["noExitRuntime"]||true;var __abort_js=()=>{abort("")};var __emscripten_memcpy_js=(dest,src,num)=>HEAPU8.copyWithin(dest,src,src+num);var _emscripten_random=()=>Math.random();var getHeapMax=()=>2147483648;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}var alignUp=(x,multiple)=>x+(multiple-x%multiple)%multiple;for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignUp(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var uleb128Encode=(n,target)=>{if(n<128){target.push(n)}else{target.push(n%128|128,n>>7)}};var sigToWasmTypes=sig=>{var typeNames={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"};var type={parameters:[],results:sig[0]=="v"?[]:[typeNames[sig[0]]]};for(var i=1;i{var sigRet=sig.slice(0,1);var sigParam=sig.slice(1);var typeCodes={i:127,p:127,j:126,f:125,d:124,e:111};target.push(96);uleb128Encode(sigParam.length,target);for(var i=0;i{if(typeof WebAssembly.Function=="function"){return new WebAssembly.Function(sigToWasmTypes(sig),func)}var typeSectionBody=[1];generateFuncType(sig,typeSectionBody);var bytes=[0,97,115,109,1,0,0,0,1];uleb128Encode(typeSectionBody.length,bytes);bytes.push(...typeSectionBody);bytes.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var module=new WebAssembly.Module(new Uint8Array(bytes));var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc};var wasmTableMirror=[];var wasmTable;var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){if(funcPtr>=wasmTableMirror.length)wasmTableMirror.length=funcPtr+1;wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var updateTableMap=(offset,count)=>{if(functionsInTableMap){for(var i=offset;i{if(!functionsInTableMap){functionsInTableMap=new WeakMap;updateTableMap(0,wasmTable.length)}return functionsInTableMap.get(func)||0};var freeTableIndexes=[];var getEmptyTableSlot=()=>{if(freeTableIndexes.length){return freeTableIndexes.pop()}try{wasmTable.grow(1)}catch(err){if(!(err instanceof RangeError)){throw err}throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1};var setWasmTableEntry=(idx,func)=>{wasmTable.set(idx,func);wasmTableMirror[idx]=wasmTable.get(idx)};var addFunction=(func,sig)=>{var rtn=getFunctionAddress(func);if(rtn){return rtn}var ret=getEmptyTableSlot();try{setWasmTableEntry(ret,func)}catch(err){if(!(err instanceof TypeError)){throw err}var wrapped=convertJsFunctionToWasm(func,sig);setWasmTableEntry(ret,wrapped)}functionsInTableMap.set(func,ret);return ret};var wasmImports={a:__abort_js,c:__emscripten_memcpy_js,d:_emscripten_random,b:_emscripten_resize_heap};var wasmExports=createWasm();var ___wasm_call_ctors=()=>(___wasm_call_ctors=wasmExports["f"])();var _FFLInitCharModelCPUStepWithCallback=Module["_FFLInitCharModelCPUStepWithCallback"]=(a0,a1,a2,a3)=>(_FFLInitCharModelCPUStepWithCallback=Module["_FFLInitCharModelCPUStepWithCallback"]=wasmExports["g"])(a0,a1,a2,a3);var _FFLInitCharModelCPUStep=Module["_FFLInitCharModelCPUStep"]=(a0,a1,a2)=>(_FFLInitCharModelCPUStep=Module["_FFLInitCharModelCPUStep"]=wasmExports["h"])(a0,a1,a2);var _FFLDeleteCharModel=Module["_FFLDeleteCharModel"]=a0=>(_FFLDeleteCharModel=Module["_FFLDeleteCharModel"]=wasmExports["i"])(a0);var _FFLGetDrawParamOpaFaceline=Module["_FFLGetDrawParamOpaFaceline"]=a0=>(_FFLGetDrawParamOpaFaceline=Module["_FFLGetDrawParamOpaFaceline"]=wasmExports["j"])(a0);var _FFLGetDrawParamOpaBeard=Module["_FFLGetDrawParamOpaBeard"]=a0=>(_FFLGetDrawParamOpaBeard=Module["_FFLGetDrawParamOpaBeard"]=wasmExports["k"])(a0);var _FFLGetDrawParamOpaNose=Module["_FFLGetDrawParamOpaNose"]=a0=>(_FFLGetDrawParamOpaNose=Module["_FFLGetDrawParamOpaNose"]=wasmExports["l"])(a0);var _FFLGetDrawParamOpaForehead=Module["_FFLGetDrawParamOpaForehead"]=a0=>(_FFLGetDrawParamOpaForehead=Module["_FFLGetDrawParamOpaForehead"]=wasmExports["m"])(a0);var _FFLGetDrawParamOpaHair=Module["_FFLGetDrawParamOpaHair"]=a0=>(_FFLGetDrawParamOpaHair=Module["_FFLGetDrawParamOpaHair"]=wasmExports["n"])(a0);var _FFLGetDrawParamOpaCap=Module["_FFLGetDrawParamOpaCap"]=a0=>(_FFLGetDrawParamOpaCap=Module["_FFLGetDrawParamOpaCap"]=wasmExports["o"])(a0);var _FFLGetDrawParamXluMask=Module["_FFLGetDrawParamXluMask"]=a0=>(_FFLGetDrawParamXluMask=Module["_FFLGetDrawParamXluMask"]=wasmExports["p"])(a0);var _FFLGetDrawParamXluNoseLine=Module["_FFLGetDrawParamXluNoseLine"]=a0=>(_FFLGetDrawParamXluNoseLine=Module["_FFLGetDrawParamXluNoseLine"]=wasmExports["q"])(a0);var _FFLGetDrawParamXluGlass=Module["_FFLGetDrawParamXluGlass"]=a0=>(_FFLGetDrawParamXluGlass=Module["_FFLGetDrawParamXluGlass"]=wasmExports["r"])(a0);var _FFLSetExpression=Module["_FFLSetExpression"]=(a0,a1)=>(_FFLSetExpression=Module["_FFLSetExpression"]=wasmExports["s"])(a0,a1);var _FFLGetExpression=Module["_FFLGetExpression"]=a0=>(_FFLGetExpression=Module["_FFLGetExpression"]=wasmExports["t"])(a0);var _FFLSetViewModelType=Module["_FFLSetViewModelType"]=(a0,a1)=>(_FFLSetViewModelType=Module["_FFLSetViewModelType"]=wasmExports["u"])(a0,a1);var _FFLGetBoundingBox=Module["_FFLGetBoundingBox"]=(a0,a1)=>(_FFLGetBoundingBox=Module["_FFLGetBoundingBox"]=wasmExports["v"])(a0,a1);var _FFLIsAvailableExpression=Module["_FFLIsAvailableExpression"]=(a0,a1)=>(_FFLIsAvailableExpression=Module["_FFLIsAvailableExpression"]=wasmExports["w"])(a0,a1);var _FFLSetCoordinate=Module["_FFLSetCoordinate"]=(a0,a1)=>(_FFLSetCoordinate=Module["_FFLSetCoordinate"]=wasmExports["x"])(a0,a1);var _FFLSetScale=Module["_FFLSetScale"]=a0=>(_FFLSetScale=Module["_FFLSetScale"]=wasmExports["y"])(a0);var _FFLiGetRandomCharInfo=Module["_FFLiGetRandomCharInfo"]=(a0,a1,a2,a3)=>(_FFLiGetRandomCharInfo=Module["_FFLiGetRandomCharInfo"]=wasmExports["z"])(a0,a1,a2,a3);var _FFLpGetStoreDataFromCharInfo=Module["_FFLpGetStoreDataFromCharInfo"]=(a0,a1)=>(_FFLpGetStoreDataFromCharInfo=Module["_FFLpGetStoreDataFromCharInfo"]=wasmExports["A"])(a0,a1);var _FFLpGetCharInfoFromStoreData=Module["_FFLpGetCharInfoFromStoreData"]=(a0,a1)=>(_FFLpGetCharInfoFromStoreData=Module["_FFLpGetCharInfoFromStoreData"]=wasmExports["B"])(a0,a1);var _FFLGetAdditionalInfo=Module["_FFLGetAdditionalInfo"]=(a0,a1,a2,a3,a4)=>(_FFLGetAdditionalInfo=Module["_FFLGetAdditionalInfo"]=wasmExports["C"])(a0,a1,a2,a3,a4);var _FFLInitRes=Module["_FFLInitRes"]=(a0,a1)=>(_FFLInitRes=Module["_FFLInitRes"]=wasmExports["D"])(a0,a1);var _FFLInitResGPUStep=Module["_FFLInitResGPUStep"]=()=>(_FFLInitResGPUStep=Module["_FFLInitResGPUStep"]=wasmExports["E"])();var _FFLExit=Module["_FFLExit"]=()=>(_FFLExit=Module["_FFLExit"]=wasmExports["F"])();var _FFLIsAvailable=Module["_FFLIsAvailable"]=()=>(_FFLIsAvailable=Module["_FFLIsAvailable"]=wasmExports["G"])();var _FFLGetFavoriteColor=Module["_FFLGetFavoriteColor"]=(a0,a1)=>(_FFLGetFavoriteColor=Module["_FFLGetFavoriteColor"]=wasmExports["H"])(a0,a1);var _FFLSetLinearGammaMode=Module["_FFLSetLinearGammaMode"]=a0=>(_FFLSetLinearGammaMode=Module["_FFLSetLinearGammaMode"]=wasmExports["I"])(a0);var _FFLGetFacelineColor=Module["_FFLGetFacelineColor"]=(a0,a1)=>(_FFLGetFacelineColor=Module["_FFLGetFacelineColor"]=wasmExports["J"])(a0,a1);var _FFLSetTextureFlipY=Module["_FFLSetTextureFlipY"]=a0=>(_FFLSetTextureFlipY=Module["_FFLSetTextureFlipY"]=wasmExports["K"])(a0);var _FFLSetNormalIsSnorm8_8_8_8=Module["_FFLSetNormalIsSnorm8_8_8_8"]=a0=>(_FFLSetNormalIsSnorm8_8_8_8=Module["_FFLSetNormalIsSnorm8_8_8_8"]=wasmExports["L"])(a0);var _FFLSetFrontCullForFlipX=Module["_FFLSetFrontCullForFlipX"]=a0=>(_FFLSetFrontCullForFlipX=Module["_FFLSetFrontCullForFlipX"]=wasmExports["M"])(a0);var _FFLSetTextureCallback=Module["_FFLSetTextureCallback"]=a0=>(_FFLSetTextureCallback=Module["_FFLSetTextureCallback"]=wasmExports["N"])(a0);var _FFLiDeleteTempObjectMaskTextures=Module["_FFLiDeleteTempObjectMaskTextures"]=(a0,a1,a2)=>(_FFLiDeleteTempObjectMaskTextures=Module["_FFLiDeleteTempObjectMaskTextures"]=wasmExports["P"])(a0,a1,a2);var _FFLiDeleteTempObjectFacelineTexture=Module["_FFLiDeleteTempObjectFacelineTexture"]=(a0,a1,a2)=>(_FFLiDeleteTempObjectFacelineTexture=Module["_FFLiDeleteTempObjectFacelineTexture"]=wasmExports["Q"])(a0,a1,a2);var _FFLiDeleteTextureTempObject=Module["_FFLiDeleteTextureTempObject"]=a0=>(_FFLiDeleteTextureTempObject=Module["_FFLiDeleteTextureTempObject"]=wasmExports["R"])(a0);var _FFLiiGetEyeRotateOffset=Module["_FFLiiGetEyeRotateOffset"]=a0=>(_FFLiiGetEyeRotateOffset=Module["_FFLiiGetEyeRotateOffset"]=wasmExports["S"])(a0);var _FFLiiGetEyebrowRotateOffset=Module["_FFLiiGetEyebrowRotateOffset"]=a0=>(_FFLiiGetEyebrowRotateOffset=Module["_FFLiiGetEyebrowRotateOffset"]=wasmExports["T"])(a0);var _FFLiInvalidateTempObjectFacelineTexture=Module["_FFLiInvalidateTempObjectFacelineTexture"]=a0=>(_FFLiInvalidateTempObjectFacelineTexture=Module["_FFLiInvalidateTempObjectFacelineTexture"]=wasmExports["U"])(a0);var _FFLiInvalidatePartsTextures=Module["_FFLiInvalidatePartsTextures"]=a0=>(_FFLiInvalidatePartsTextures=Module["_FFLiInvalidatePartsTextures"]=wasmExports["V"])(a0);var _FFLiInvalidateRawMask=Module["_FFLiInvalidateRawMask"]=a0=>(_FFLiInvalidateRawMask=Module["_FFLiInvalidateRawMask"]=wasmExports["W"])(a0);var _FFLiVerifyCharInfoWithReason=Module["_FFLiVerifyCharInfoWithReason"]=(a0,a1)=>(_FFLiVerifyCharInfoWithReason=Module["_FFLiVerifyCharInfoWithReason"]=wasmExports["X"])(a0,a1);var _malloc=Module["_malloc"]=a0=>(_malloc=Module["_malloc"]=wasmExports["Y"])(a0);var _free=Module["_free"]=a0=>(_free=Module["_free"]=wasmExports["Z"])(a0);Module["addFunction"]=addFunction;var calledRun;dependenciesFulfilled=function runCaller(){if(!calledRun)run();if(!calledRun)dependenciesFulfilled=runCaller};function run(){if(runDependencies>0){return}preRun();if(runDependencies>0){return}function doRun(){if(calledRun)return;calledRun=true;Module["calledRun"]=true;if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout(function(){setTimeout(function(){Module["setStatus"]("")},1);doRun()},1)}else{doRun()}}if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}run();export default {Module} \ No newline at end of file +var ModuleFFL = (() => { + var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined; + + return ( +async function(moduleArg = {}) { + var moduleRtn; + +var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=true;var ENVIRONMENT_IS_WORKER=false;var moduleOverrides={...Module};var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(ENVIRONMENT_IS_WORKER){scriptDirectory=self.location.href}else if(typeof document!="undefined"&&document.currentScript){scriptDirectory=document.currentScript.src}if(_scriptName){scriptDirectory=_scriptName}if(scriptDirectory.startsWith("blob:")){scriptDirectory=""}else{scriptDirectory=scriptDirectory.slice(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1)}{readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);Object.assign(Module,moduleOverrides);moduleOverrides=null;var wasmBinary;var wasmMemory;var ABORT=false;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPU64,HEAPF64;var runtimeInitialized=false;function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);HEAPF64=new Float64Array(b);HEAP64=new BigInt64Array(b);HEAPU64=new BigUint64Array(b)}function preRun(){}function initRuntime(){runtimeInitialized=true;wasmExports["e"]()}function postRun(){}var runDependencies=0;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++}function removeRunDependency(id){runDependencies--;if(runDependencies==0){if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}function abort(what){what="Aborted("+what+")";err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);readyPromiseReject(e);throw e}var wasmBinaryFile;function findWasmBinary(){return locateFile("ffl-emscripten.wasm")}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&typeof WebAssembly.instantiateStreaming=="function"){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){return{a:wasmImports}}async function createWasm(){function receiveInstance(instance,module){wasmExports=instance.exports;wasmMemory=wasmExports["d"];updateMemoryViews();wasmTable=wasmExports["O"];removeRunDependency("wasm-instantiate");return wasmExports}addRunDependency("wasm-instantiate");function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();wasmBinaryFile??=findWasmBinary();try{var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}catch(e){readyPromiseReject(e);return Promise.reject(e)}}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}function stackTrace(){abort("missing function: $stackTrace")}stackTrace.stub=true;var __abort_js=()=>abort("");var _emscripten_random=()=>Math.random();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var b=wasmMemory.buffer;var pages=(size-b.byteLength+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var uleb128Encode=(n,target)=>{if(n<128){target.push(n)}else{target.push(n%128|128,n>>7)}};var sigToWasmTypes=sig=>{var typeNames={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"};var type={parameters:[],results:sig[0]=="v"?[]:[typeNames[sig[0]]]};for(var i=1;i{var sigRet=sig.slice(0,1);var sigParam=sig.slice(1);var typeCodes={i:127,p:127,j:126,f:125,d:124,e:111};target.push(96);uleb128Encode(sigParam.length,target);for(var paramType of sigParam){target.push(typeCodes[paramType])}if(sigRet=="v"){target.push(0)}else{target.push(1,typeCodes[sigRet])}};var convertJsFunctionToWasm=(func,sig)=>{if(typeof WebAssembly.Function=="function"){return new WebAssembly.Function(sigToWasmTypes(sig),func)}var typeSectionBody=[1];generateFuncType(sig,typeSectionBody);var bytes=[0,97,115,109,1,0,0,0,1];uleb128Encode(typeSectionBody.length,bytes);bytes.push(...typeSectionBody);bytes.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var module=new WebAssembly.Module(new Uint8Array(bytes));var instance=new WebAssembly.Instance(module,{e:{f:func}});var wrappedFunc=instance.exports["f"];return wrappedFunc};var wasmTableMirror=[];var wasmTable;var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};var updateTableMap=(offset,count)=>{if(functionsInTableMap){for(var i=offset;i{if(!functionsInTableMap){functionsInTableMap=new WeakMap;updateTableMap(0,wasmTable.length)}return functionsInTableMap.get(func)||0};var freeTableIndexes=[];var getEmptyTableSlot=()=>{if(freeTableIndexes.length){return freeTableIndexes.pop()}try{wasmTable.grow(1)}catch(err){if(!(err instanceof RangeError)){throw err}throw"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH."}return wasmTable.length-1};var setWasmTableEntry=(idx,func)=>{wasmTable.set(idx,func);wasmTableMirror[idx]=wasmTable.get(idx)};var addFunction=(func,sig)=>{var rtn=getFunctionAddress(func);if(rtn){return rtn}var ret=getEmptyTableSlot();try{setWasmTableEntry(ret,func)}catch(err){if(!(err instanceof TypeError)){throw err}var wrapped=convertJsFunctionToWasm(func,sig);setWasmTableEntry(ret,wrapped)}functionsInTableMap.set(func,ret);return ret};var removeFunction=index=>{functionsInTableMap.delete(getWasmTableEntry(index));setWasmTableEntry(index,null);freeTableIndexes.push(index)};var wasmImports={a:__abort_js,c:_emscripten_random,b:_emscripten_resize_heap};var wasmExports=await createWasm();var ___wasm_call_ctors=wasmExports["e"];var _FFLInitCharModelCPUStepWithCallback=Module["_FFLInitCharModelCPUStepWithCallback"]=wasmExports["f"];var _FFLInitCharModelCPUStep=Module["_FFLInitCharModelCPUStep"]=wasmExports["g"];var _FFLDeleteCharModel=Module["_FFLDeleteCharModel"]=wasmExports["h"];var _FFLGetDrawParamOpaFaceline=Module["_FFLGetDrawParamOpaFaceline"]=wasmExports["i"];var _FFLGetDrawParamOpaBeard=Module["_FFLGetDrawParamOpaBeard"]=wasmExports["j"];var _FFLGetDrawParamOpaNose=Module["_FFLGetDrawParamOpaNose"]=wasmExports["k"];var _FFLGetDrawParamOpaForehead=Module["_FFLGetDrawParamOpaForehead"]=wasmExports["l"];var _FFLGetDrawParamOpaHair=Module["_FFLGetDrawParamOpaHair"]=wasmExports["m"];var _FFLGetDrawParamOpaCap=Module["_FFLGetDrawParamOpaCap"]=wasmExports["n"];var _FFLGetDrawParamXluMask=Module["_FFLGetDrawParamXluMask"]=wasmExports["o"];var _FFLGetDrawParamXluNoseLine=Module["_FFLGetDrawParamXluNoseLine"]=wasmExports["p"];var _FFLGetDrawParamXluGlass=Module["_FFLGetDrawParamXluGlass"]=wasmExports["q"];var _FFLSetExpression=Module["_FFLSetExpression"]=wasmExports["r"];var _FFLGetExpression=Module["_FFLGetExpression"]=wasmExports["s"];var _FFLSetViewModelType=Module["_FFLSetViewModelType"]=wasmExports["t"];var _FFLGetBoundingBox=Module["_FFLGetBoundingBox"]=wasmExports["u"];var _FFLIsAvailableExpression=Module["_FFLIsAvailableExpression"]=wasmExports["v"];var _FFLSetCoordinate=Module["_FFLSetCoordinate"]=wasmExports["w"];var _FFLSetScale=Module["_FFLSetScale"]=wasmExports["x"];var _FFLiGetRandomCharInfo=Module["_FFLiGetRandomCharInfo"]=wasmExports["y"];var _FFLpGetStoreDataFromCharInfo=Module["_FFLpGetStoreDataFromCharInfo"]=wasmExports["z"];var _FFLpGetCharInfoFromStoreData=Module["_FFLpGetCharInfoFromStoreData"]=wasmExports["A"];var _FFLpGetCharInfoFromMiiDataOfficialRFL=Module["_FFLpGetCharInfoFromMiiDataOfficialRFL"]=wasmExports["B"];var _FFLGetAdditionalInfo=Module["_FFLGetAdditionalInfo"]=wasmExports["C"];var _FFLInitRes=Module["_FFLInitRes"]=wasmExports["D"];var _FFLInitResGPUStep=Module["_FFLInitResGPUStep"]=wasmExports["E"];var _FFLExit=Module["_FFLExit"]=wasmExports["F"];var _FFLIsAvailable=Module["_FFLIsAvailable"]=wasmExports["G"];var _FFLGetFavoriteColor=Module["_FFLGetFavoriteColor"]=wasmExports["H"];var _FFLSetLinearGammaMode=Module["_FFLSetLinearGammaMode"]=wasmExports["I"];var _FFLGetFacelineColor=Module["_FFLGetFacelineColor"]=wasmExports["J"];var _FFLSetTextureFlipY=Module["_FFLSetTextureFlipY"]=wasmExports["K"];var _FFLSetNormalIsSnorm8_8_8_8=Module["_FFLSetNormalIsSnorm8_8_8_8"]=wasmExports["L"];var _FFLSetFrontCullForFlipX=Module["_FFLSetFrontCullForFlipX"]=wasmExports["M"];var _FFLSetTextureCallback=Module["_FFLSetTextureCallback"]=wasmExports["N"];var _FFLiDeleteTempObjectMaskTextures=Module["_FFLiDeleteTempObjectMaskTextures"]=wasmExports["P"];var _FFLiDeleteTempObjectFacelineTexture=Module["_FFLiDeleteTempObjectFacelineTexture"]=wasmExports["Q"];var _FFLiDeleteTextureTempObject=Module["_FFLiDeleteTextureTempObject"]=wasmExports["R"];var _FFLiiGetEyeRotateOffset=Module["_FFLiiGetEyeRotateOffset"]=wasmExports["S"];var _FFLiiGetEyebrowRotateOffset=Module["_FFLiiGetEyebrowRotateOffset"]=wasmExports["T"];var _FFLiInvalidateTempObjectFacelineTexture=Module["_FFLiInvalidateTempObjectFacelineTexture"]=wasmExports["U"];var _FFLiInvalidatePartsTextures=Module["_FFLiInvalidatePartsTextures"]=wasmExports["V"];var _FFLiInvalidateRawMask=Module["_FFLiInvalidateRawMask"]=wasmExports["W"];var _GX2CalcSurfaceSizeAndAlignment=Module["_GX2CalcSurfaceSizeAndAlignment"]=wasmExports["X"];var _GX2CopySurface=Module["_GX2CopySurface"]=wasmExports["Y"];var _FFLiVerifyCharInfoWithReason=Module["_FFLiVerifyCharInfoWithReason"]=wasmExports["Z"];var _malloc=Module["_malloc"]=wasmExports["_"];var _free=Module["_free"]=wasmExports["$"];Module["addFunction"]=addFunction;Module["removeFunction"]=removeFunction;function run(){if(runDependencies>0){dependenciesFulfilled=run;return}preRun();if(runDependencies>0){dependenciesFulfilled=run;return}function doRun(){Module["calledRun"]=true;if(ABORT)return;initRuntime();readyPromiseResolve(Module);Module["onRuntimeInitialized"]?.();postRun()}{doRun()}}run();moduleRtn=readyPromise; + + + return moduleRtn; +} +); +})(); +if (typeof exports === 'object' && typeof module === 'object') { + module.exports = ModuleFFL; + // This default export looks redundant, but it allows TS to import this + // commonjs style module. + module.exports.default = ModuleFFL; +} else if (typeof define === 'function' && define['amd']) + define([], () => ModuleFFL); diff --git a/src/external/ffl.js/ffl-emscripten.wasm b/src/external/ffl.js/ffl-emscripten.wasm new file mode 100644 index 0000000..7db795f Binary files /dev/null and b/src/external/ffl.js/ffl-emscripten.wasm differ diff --git a/src/external/ffl.js/ffl.js b/src/external/ffl.js/ffl.js index 2b45901..0749adf 100644 --- a/src/external/ffl.js/ffl.js +++ b/src/external/ffl.js/ffl.js @@ -1,3362 +1,4847 @@ -// Arian's amazing FFL.js (as of commit 0dd5800) -// Patches made by kat21 for use with Mii Creator - -import _ from "./struct-fu-mini.js"; -import * as THREE from "three"; -import { GLTFLoader } from "three/examples/jsm/Addons.js"; - -// Temporary, these may be changed into es module imports eventually -import {FFLShaderMaterial} from "./FFLShaderMaterial.js"; -import {LUTShaderMaterial} from "./LUTShaderMaterial.js"; -import { cMaterialName } from "../../class/3d/shader/fflShaderConst.js"; - -// Web Worker shenanigans -let global; -if (typeof window === 'undefined') { - global = self; -} else { - global = window; -} - -global.FFLShaderMaterial = FFLShaderMaterial; -global.LUTShaderMaterial = LUTShaderMaterial; - -// Cloneable models used -let bodyModels = { - WiiU: { - /**@type {THREE.Group} */ - m: null, - /**@type {THREE.Group} */ - f: null - }, - Switch: { - /**@type {THREE.Group} */ - m: null, - /**@type {THREE.Group} */ - f: null - }, - Miitomo: { - /**@type {THREE.Group} */ - m: null, - /**@type {THREE.Group} */ - f: null - } -}; - -var loader = new GLTFLoader(); - -//! NOTE: THIS ASSUMES THE ROOT IS THE PUBLIC FOLDER -function makeModelPath(gender, modelName) { - return `/assets/models/miiBody${gender}_${modelName}.glb` -} -async function loadModel(modelPath) { - const model = await loader.loadAsync(modelPath); - - var mixer = new THREE.AnimationMixer(model.scene); - const scene = model.scene; - - const idleClip = model.animations[0]; - const idleAnim = mixer.clipAction(idleClip, scene); - idleAnim.stop(); - const clip = model.animations.find(a => a.name === "Wait"); - const anim = mixer.clipAction(clip, scene); - anim.play(); - anim.timeScale=0; - - mixer.update(); - - return scene; -} - -export async function loadBodyModels() { - bodyModels.Miitomo.m = await loadModel(makeModelPath("M", "miitomo")); - bodyModels.Miitomo.f = await loadModel(makeModelPath("F", "miitomo")); -} - -global.bodyModels = bodyModels; - -// Changes: -// - Modularized by adding import/export -// - Updated views -// - Added body rendering to icons - -// Tested on Three.js r137, should work on r109. - -// // --------------------------------------------------------------------- -// // JSDoc Types -// // --------------------------------------------------------------------- - -/** - * @typedef {Object} Module - * @property {Int8Array} HEAP8 - * @property {Uint8Array} HEAPU8 - * @property {Uint16Array} HEAPU16 - * @property {Uint32Array} HEAPU32 - * @property {Float32Array} HEAPF32 - * Runtime methods: - * @property {(byteLength: number) => number} _malloc - * @property {(ptr: number) => number} _free - * @property {() => void} onRuntimeInitialized - * @property boolean calledRun - * addFunction - * - */ - -/** - * @typedef {import('./struct-fu-mini.js')} StructFu - */ - -function generateJSDoc(obj, typeName = 'GeneratedType', depth = 0) { - // Stop at max depth 5. - if (depth > 5) { - return ''; - } - - const indent = ' '.repeat(depth); - let text = `${indent}/**\n${indent} * @typedef {Object} ${typeName}\n`; - - Object.keys(obj).forEach((key) => { - // Ignore private keys beginning with underscore. - if (key.startsWith('_')) { - return; - } - - const value = obj[key]; - const valueType = typeof value; - let propType; - - if (value === null) { - propType = 'null'; - } else if (Array.isArray(value)) { - let arrayType = value.length > 0 ? typeof value[0] : 'any'; // Assume first element type - if (typeof value[0] === 'object' && value[0] !== null) { - arrayType = generateJSDoc(value[0], `${typeName}_${key}_Item`, depth + 1); - } - propType = `Array<${arrayType}>`; - } else if (valueType === 'object') { - const nestedType = generateJSDoc(value, `${typeName}_${key}`, depth + 1); - propType = nestedType || 'Object'; - } else { - propType = valueType; - } - - text += `${indent} * @property {${propType}} ${key}\n`; - }); - - text += `${indent} */\n`; - console.log(text); -} - -/** - * @throws {Error} typeName must be a string. - */ -function generateJSDocStructFu(typeName) { - if (typeof typeName !== 'string') { - throw new Error(); - } - eval(` - const empty = new Uint8Array(${typeName}.size); - generateJSDoc(${typeName}.unpack(empty), typeName); - `); -} - -/** - * Template for the return type of _.struct(). - * - * @template T - * @typedef {Object} StructInstance - * @property {function(Uint8Array): T} unpack - Deserializes a Uint8Array into the structured object. - * @property {function(T): Uint8Array} pack - Serializes the structured object into a Uint8Array. - * @property {Object} fields - List of fields in the struct, including offsets. - * @property {number} size - The size of the packed structure. - */ - -/** - * @typedef {Object} WindowCustom - * @property {Module} Module - * @property {TextureManager} FFLTextures - * List shader materials: - * @property {object} FFLShaderMaterial - * @property {object} LUTShaderMaterial - */ - -/** @type {WindowCustom} */ -window; - -if (_ === undefined) { - // NOTE only here to satisfy eslint - /** @type {StructFu} */ - const _ = global._; -} -_; - -// // --------------------------------------------------------------------- -// // Enum Definitions -// // --------------------------------------------------------------------- - -/** - * @enum {number} - */ -const FFLiShapeType = { - OPA_BEARD: 0, - OPA_FACELINE: 1, - OPA_HAIR_NORMAL: 2, - OPA_FOREHEAD_NORMAL: 3, - XLU_MASK: 4, - XLU_NOSELINE: 5, - OPA_NOSE: 6, - OPA_HAT_NORMAL: 7, - XLU_GLASS: 8, - OPA_HAIR_CAP: 9, - OPA_FOREHEAD_CAP: 10, - OPA_HAT_CAP: 11, - MAX: 12 -}; - -/** - * @enum {number} - */ -const FFLAttributeBufferType = { - POSITION: 0, - TEXCOORD: 1, - NORMAL: 2, - TANGENT: 3, - COLOR: 4, - MAX: 5 -}; - -/** - * @enum {number} - */ -const FFLCullMode = { - NONE: 0, - BACK: 1, - FRONT: 2, - MAX: 3 -}; - -/** - * @enum {number} - */ -const FFLModulateMode = { - CONSTANT: 0, // No Texture, Has Color (R) - TEXTURE_DIRECT: 1, // Has Texture, No Color - RGB_LAYERED: 2, // Has Texture, Has Color (R + G + B) - ALPHA: 3, // Has Texture, Has Color (R) - LUMINANCE_ALPHA: 4, // Has Texture, Has Color (R) - ALPHA_OPA: 5 // Has Texture, Has Color (R) -}; - -/** - * @enum {number} - */ -const FFLModulateType = { - SHAPE_FACELINE: 0, - SHAPE_BEARD: 1, - SHAPE_NOSE: 2, - SHAPE_FOREHEAD: 3, - SHAPE_HAIR: 4, - SHAPE_CAP: 5, - SHAPE_MASK: 6, - SHAPE_NOSELINE: 7, - SHAPE_GLASS: 8, - MUSTACHE: 9, - MOUTH: 10, - EYEBROW: 11, - EYE: 12, - MOLE: 13, - FACE_MAKE: 14, - FACE_LINE: 15, - FACE_BEARD: 16, - FILL: 17, - SHAPE_MAX: 9 -}; - -/** - * @enum {number} - */ -const FFLResourceType = { - MIDDLE: 0, - HIGH: 1, - MAX: 2 -}; - -/** - * @enum {number} - */ -const FFLExpression = { - NORMAL: 0, - MAX: 70 -}; - -/** - * @enum {number} - */ -export const FFLModelFlag = { - NORMAL: 1 << 0, - HAT: 1 << 1, // Uses a variant of hair designed for hats. - FACE_ONLY: 1 << 2, // Discards hair from the model for helmets, etc. - FLATTEN_NOSE: 1 << 3, // Limits the Z depth on a nose for helmets, etc. - NEW_EXPRESSIONS: 1 << 4, // Enables expression flag to use beyond 32 expressions. - // This flag will only make new textures - // when initializing a CharModel and not - // initialize shapes. Note that this means - // you cannot DrawOpa/Xlu when this is set. - NEW_MASK_ONLY: 1 << 5 -}; - -// // --------------------------------------------------------------------- -// // Struct Definitions (struct-fu) -// // --------------------------------------------------------------------- -// Mostly leading up to FFLDrawParam. - -/** - * @typedef {Object} FFLAttributeBuffer - * @property {number} size - * @property {number} stride - * @property {number} ptr - */ -const FFLAttributeBuffer = _.struct([ - _.uint32le('size'), - _.uint32le('stride'), - _.uintptr('ptr') -]); - -/** - * @typedef {Object} FFLAttributeBufferParam - * @property {Array} attributeBuffers - */ -const FFLAttributeBufferParam = _.struct([ - _.struct('attributeBuffers', [FFLAttributeBuffer], 5) -]); - -/** - * @typedef {Object} FFLPrimitiveParam - * @property {number} primitiveType - * @property {number} indexCount - * @property {number} pIndexBuffer - */ -const FFLPrimitiveParam = _.struct([ - _.uint32le('primitiveType'), - _.uint32le('indexCount'), - _.uint32le('_8'), - _.uintptr('pIndexBuffer') -]); - -/** - * @typedef {Object} FFLColor - * @property {number} r - * @property {number} g - * @property {number} b - * @property {number} a - */ -const FFLColor = _.struct([ - _.float32le('r'), - _.float32le('g'), - _.float32le('b'), - _.float32le('a') -]); - -const FFLVec3 = _.struct([ - _.float32le('x'), - _.float32le('y'), - _.float32le('z') -]); - -/** - * @typedef {Object} FFLModulateParam - * @property {FFLModulateMode} mode - * @property {FFLModulateType} type - * @property {FFLColor} pColorR - * @property {FFLColor} pColorG - * @property {FFLColor} pColorB - * @property {number} pTexture2D - */ -const FFLModulateParam = _.struct([ - _.uint32le('mode'), // enum FFLModulateMode - _.uint32le('type'), // enum FFLModulateType - _.uintptr('pColorR'), - _.uintptr('pColorG'), - _.uintptr('pColorB'), - _.uintptr('pTexture2D') -]); - -/** - * @typedef {Object} FFLDrawParam - * @property {FFLAttributeBufferParam} attributeBufferParam - * @property {FFLModulateParam} modulateParam - * @property {FFLCullMode} cullMode - * @property {FFLPrimitiveParam} primitiveParam - */ -const FFLDrawParam = _.struct([ - _.struct('attributeBufferParam', [FFLAttributeBufferParam]), - _.struct('modulateParam', [FFLModulateParam]), - _.uint32le('cullMode'), - _.struct('primitiveParam', [FFLPrimitiveParam]) -]); - -// ---------------------- Begin FFLiCharInfo Definition ---------------------- - -const FFLCreateID = _.struct([ - _.uint8('data', 10) -]); - -/** - * @typedef {Object} FFLiCharInfo_faceline - * @property {number} type - * @property {number} color - * @property {number} texture - * @property {number} make - */ -/** - * @typedef {Object} FFLiCharInfo_hair - * @property {number} type - * @property {number} color - * @property {number} flip - */ -/** - * @typedef {Object} FFLiCharInfo_eye - * @property {number} type - * @property {number} color - * @property {number} scale - * @property {number} aspect - * @property {number} rotate - * @property {number} x - * @property {number} y - */ -/** - * @typedef {Object} FFLiCharInfo_eyebrow - * @property {number} type - * @property {number} color - * @property {number} scale - * @property {number} aspect - * @property {number} rotate - * @property {number} x - * @property {number} y - */ -/** - * @typedef {Object} FFLiCharInfo_nose - * @property {number} type - * @property {number} scale - * @property {number} y - */ -/** - * @typedef {Object} FFLiCharInfo_mouth - * @property {number} type - * @property {number} color - * @property {number} scale - * @property {number} aspect - * @property {number} y - */ -/** - * @typedef {Object} FFLiCharInfo_beard - * @property {number} mustache - * @property {number} type - * @property {number} color - * @property {number} scale - * @property {number} y - */ -/** - * @typedef {Object} FFLiCharInfo_glass - * @property {number} type - * @property {number} color - * @property {number} scale - * @property {number} y - */ -/** - * @typedef {Object} FFLiCharInfo_mole - * @property {number} type - * @property {number} scale - * @property {number} x - * @property {number} y - */ -/** - * @typedef {Object} FFLiCharInfo_body - * @property {number} height - * @property {number} build - */ -/** - * @typedef {Object} FFLiCharInfo_personal - * @property {string} name - * @property {string} creator - * @property {number} gender - * @property {number} birthMonth - * @property {number} birthDay - * @property {number} favoriteColor - * @property {number} favorite - * @property {number} copyable - * @property {number} ngWord - * @property {number} localonly - * @property {number} regionMove - * @property {number} fontRegion - * @property {number} roomIndex - * @property {number} positionInRoom - * @property {number} birthPlatform - */ -/** - * @typedef {Object} FFLiCharInfo_createID - * @property {Array} data - */ -/** - * @typedef {Object} FFLiCharInfo - * @property {number} miiVersion - * @property {FFLiCharInfo_faceline} faceline - * @property {FFLiCharInfo_hair} hair - * @property {FFLiCharInfo_eye} eye - * @property {FFLiCharInfo_eyebrow} eyebrow - * @property {FFLiCharInfo_nose} nose - * @property {FFLiCharInfo_mouth} mouth - * @property {FFLiCharInfo_beard} beard - * @property {FFLiCharInfo_glass} glass - * @property {FFLiCharInfo_mole} mole - * @property {FFLiCharInfo_body} body - * @property {FFLiCharInfo_personal} personal - * @property {FFLiCharInfo_createID} createID - * @property {number} padding_0 - * @property {number} authorType - * @property {Array} authorID - */ -/** - * @type {StructInstance} - */ -export const FFLiCharInfo = _.struct([ - _.int32le('miiVersion'), - _.struct('faceline', [_.int32le('type'), _.int32le('color'), - _.int32le('texture'), _.int32le('make')]), - _.struct('hair', [_.int32le('type'), _.int32le('color'), _.int32le('flip')]), - _.struct('eye', [_.int32le('type'), _.int32le('color'), _.int32le('scale'), - _.int32le('aspect'), _.int32le('rotate'), - _.int32le('x'), _.int32le('y')]), - _.struct('eyebrow', [_.int32le('type'), _.int32le('color'), - _.int32le('scale'), _.int32le('aspect'), - _.int32le('rotate'), _.int32le('x'), - _.int32le('y')]), - _.struct('nose', [_.int32le('type'), _.int32le('scale'), - _.int32le('y')]), - _.struct('mouth', [_.int32le('type'), _.int32le('color'), - _.int32le('scale'), _.int32le('aspect'), - _.int32le('y')]), - _.struct('beard', [_.int32le('mustache'), _.int32le('type'), - _.int32le('color'), _.int32le('scale'), - _.int32le('y')]), - _.struct('glass', [_.int32le('type'), _.int32le('color'), - _.int32le('scale'), _.int32le('y')]), - _.struct('mole', [_.int32le('type'), _.int32le('scale'), - _.int32le('x'), _.int32le('y')]), - _.struct('body', [_.int32le('height'), _.int32le('build')]), - _.struct('personal', [ - _.char16le('name', 22), - _.char16le('creator', 22), - _.int32le('gender'), - _.int32le('birthMonth'), - _.int32le('birthDay'), - _.int32le('favoriteColor'), - _.uint8('favorite'), - _.uint8('copyable'), - _.uint8('ngWord'), - _.uint8('localonly'), - _.int32le('regionMove'), - _.int32le('fontRegion'), - _.int32le('roomIndex'), - _.int32le('positionInRoom'), - _.int32le('birthPlatform') - ]), - _.struct('createID', [FFLCreateID]), - _.uint16le('padding_0'), - _.int32le('authorType'), - _.uint8('authorID', 8) // stub -]); - -const FFLStoreData_size = 96; // sizeof(FFLStoreData) - -// ---------------------- Common Color Mask Definitions ---------------------- - -/** @private */ -const commonColorEnableMask = (1 << 31); - -/** - * Applies (unofficial) mask: FFLI_NN_MII_COMMON_COLOR_ENABLE_MASK - * to a common color index to indicate to FFL which color table it should use. - * @param {number} color - The color index to flag. - * @returns {number} The flagged color index to use in FFLiCharinfo. - */ -const commonColorMask = color => color | commonColorEnableMask; - -/** - * Removes (unofficial) mask: FFLI_NN_MII_COMMON_COLOR_ENABLE_MASK - * to a common color index to reveal the original common color index. - * @param {number} color - The flagged color index. - * @returns {number} The original color index before flagging. - */ -const commonColorUnmask = color => color & ~commonColorEnableMask === 0 -// Only unmask color if the mask is enabled. - ? color - : color & ~commonColorEnableMask; - -// --------------------- Begin FFLiCharModel Definitions --------------------- - -const FFLAdditionalInfo = _.struct([ - _.char16le('name', 22), - _.char16le('creator', 22), - _.struct('createID', [FFLCreateID]), - _.byte('_padding0', 2), // alignment - _.struct('skinColor', [FFLColor]), - _.uint32le('flags'), - // _.ubitLE('hairFlip', 1), - // _.ubitLE('fontRegion', 2), - // _.ubitLE('ngWord', 1), - // _.ubitLE('build', 7), - // _.ubitLE('height', 7), - // _.ubitLE('favoriteColor', 4), - // _.ubitLE('birthDay', 5), - // _.ubitLE('birthMonth', 4), - // _.ubitLE('gender', 1), - _.uint8('facelineType'), - _.uint8('hairType'), - _.byte('_padding1', 2) // alignment -]); - -const FFLiRenderTexture = _.struct([ - // STUB: four pointers in one field - _.uintptr('pTexture2DRenderBufferColorTargetDepthTarget', 4) -]); - -const FFLiFacelineTextureTempObject = _.struct([ - _.uintptr('pTextureFaceLine'), - _.struct('drawParamFaceLine', [FFLDrawParam]), - _.uintptr('pTextureFaceMake'), - _.struct('drawParamFaceMake', [FFLDrawParam]), - _.uintptr('pTextureFaceBeard'), - _.struct('drawParamFaceBeard', [FFLDrawParam]), - _.uintptr('pRenderTextureCompressorParam', 2) // stub -]); - -const FFLiRawMaskDrawParam = _.struct([ - _.struct('drawParamRawMaskPartsEye', [FFLDrawParam], 2), - _.struct('drawParamRawMaskPartsEyebrow', [FFLDrawParam], 2), - _.struct('drawParamRawMaskPartsMouth', [FFLDrawParam]), - _.struct('drawParamRawMaskPartsMustache', [FFLDrawParam], 2), - _.struct('drawParamRawMaskPartsMole', [FFLDrawParam]), - _.struct('drawParamRawMaskPartsFill', [FFLDrawParam]) -]); - -const FFLiMaskTexturesTempObject = _.struct([ - _.uint8('partsTextures', 0x154), - _.uintptr('pRawMaskDrawParam', FFLExpression.MAX), - _.byte('_remaining', 0x388 - 620) // stub -]); - -const FFLiTextureTempObject = _.struct([ - _.struct('maskTextures', [FFLiMaskTexturesTempObject]), - _.struct('facelineTexture', [FFLiFacelineTextureTempObject]) -]); - -const FFLiMaskTextures = _.struct([ - _.uintptr('pRenderTextures', FFLExpression.MAX) -]); - -const FFL_RESOLUTION_MASK = 0x3fffffff; -export const FFLCharModelDesc = _.struct([ - _.uint32le('resolution'), - _.uint32le('allExpressionFlag', 3), - _.uint32le('modelFlag'), - _.uint32le('resourceType') -]); -// Define a static default FFLCharModelDesc. -FFLCharModelDesc.default = { - resolution: 512, // Typical default. - // Choose normal expression. - allExpressionFlag: new Uint32Array([1, 0, 0]), // Normal expression. - modelFlag: FFLModelFlag.NORMAL, - resourceType: FFLResourceType.HIGH // Default resource type. -}; -export const FFLCharModelDescDefault = FFLCharModelDesc.default; - -const FFLBoundingBox = _.struct([ - _.struct('min', [FFLVec3]), - _.struct('max', [FFLVec3]) -]); - -const FFLPartsTransform = _.struct([ - _.struct('hatTranslate', [FFLVec3]), - _.struct('headFrontRotate', [FFLVec3]), - _.struct('headFrontTranslate', [FFLVec3]), - _.struct('headSideRotate', [FFLVec3]), - _.struct('headSideTranslate', [FFLVec3]), - _.struct('headTopRotate', [FFLVec3]), - _.struct('headTopTranslate', [FFLVec3]) -]); - -const FFLiCharModel = _.struct([ - _.struct('charInfo', [FFLiCharInfo]), - _.struct('charModelDesc', [FFLCharModelDesc]), - _.uint32le('expression'), // enum FFLExpression - _.uintptr('pTextureTempObject'), // stub - _.struct('drawParam', [FFLDrawParam], FFLiShapeType.MAX), - _.uintptr('pShapeData', FFLiShapeType.MAX), - _.struct('facelineRenderTexture', [FFLiRenderTexture]), - _.uintptr('pCapGlassNoselineTextures', 3), - _.struct('maskTextures', [FFLiMaskTextures]), - _.struct('beardHairFaceCenterPos', [FFLVec3], 3), - _.struct('partsTransform', [FFLPartsTransform]), - _.uint32le('modelType'), // enum FFLModelType - // FFLBoundingBox[FFL_MODEL_TYPE_MAX = 3] - _.struct('boundingBox', [FFLBoundingBox], 3) -]); - -/** - * @enum {number} - */ -const FFLDataSource = { - OFFICIAL: 0, - DEFAULT: 1, - MIDDLE_DB: 2, - STORE_DATA_OFFICIAL: 3, - STORE_DATA: 4, - BUFFER: 5, - DIRECT_POINTER: 6 -}; - -/** - * @typedef {Object} FFLCharModelSource - * @property {number} dataSource - * @property {number} pBuffer - * @property {number} index - */ -/** - * @type {StructInstance} - */ -const FFLCharModelSource = _.struct([ - _.uint32le('dataSource'), - _.uintptr('pBuffer'), - _.uint16le('index') -]); - -// The enums below are only for FFLiGetRandomCharInfo. -// Hence, why each one has a value called ALL. - -/** - * @enum {number} - */ -const FFLGender = { - MALE: 0, - FEMALE: 1, - ALL: 2 -}; - -/** - * @enum {number} - */ -const FFLAge = { - CHILD: 0, - ADULT: 1, - ELDER: 2, - ALL: 3 -}; - -/** - * @enum {number} - */ -const FFLRace = { - BLACK: 0, - WHITE: 1, - ASIAN: 2, - ALL: 3 -}; - -const FFLResourceDesc = _.struct([ - _.uintptr('pData', FFLResourceType.MAX), - _.uint32le('size', FFLResourceType.MAX) -]); - -// // --------------------------------------------------------------------- -// // Texture Management -// // --------------------------------------------------------------------- - -// ------------------------- Texture Related Structs ------------------------- -/** - * @enum {number} - */ -const FFLTextureFormat = { - R8_UNORM: 0, - R8_G8_UNORM: 1, - R8_G8_B8_A8_UNORM: 2, - MAX: 3 -}; - -/** - * @typedef {Object} FFLTextureInfo - * @property {number} width - * @property {number} height - * @property {number} mipCount - * @property {FFLTextureFormat} format - * @property {number} isGX2Tiled - * @property {number} imageSize - * @property {number} imagePtr - * @property {number} mipSize - * @property {number} mipPtr - * @property {Array} mipLevelOffset - */ - -const FFLTextureInfo = _.struct([ - _.uint16le('width'), - _.uint16le('height'), - _.uint8('mipCount'), - _.uint8('format'), - _.uint8('isGX2Tiled'), - _.byte('_padding', 1), - _.uint32le('imageSize'), - _.uintptr('imagePtr'), - _.uint32le('mipSize'), - _.uintptr('mipPtr'), - _.uint32le('mipLevelOffset', 13) -]); - -const FFLTextureCallback = _.struct([ - _.uintptr('pObj'), - _.uint8('useOriginalTileMode'), - _.byte('_padding', 3), // alignment - _.uintptr('pCreateFunc'), - _.uintptr('pDeleteFunc') -]); - -// ------------------------ Class: TextureManager ----------------------------- -/** - * Manages THREE.Texture objects created via FFL. - * Must be instantiated after FFL is fully initialized. - */ -class TextureManager { - /** - * @constructor - * @param {Module} [module=global.Module] - The Emscripten module. - */ - constructor(module = global.Module) { - this.module = module; - this.textures = new Map(); // Internal map of texture id -> THREE.Texture. - this.textureCallbackPtr = null; - this._setupTextureCallbacks(); - } - - /** - * @private - * Sets up texture creation and deletion callbacks - * with the module. Called by the constructor. - */ - _setupTextureCallbacks() { - const mod = this.module; - // Bind the callbacks to this instance. - this.createCallback = mod.addFunction(this._textureCreateFunc.bind(this), 'vppp'); - this.deleteCallback = mod.addFunction(this._textureDeleteFunc.bind(this), 'vpp'); - const textureCallback = { - pObj: 0, - useOriginalTileMode: false, - _padding: [0, 0, 0], - pCreateFunc: this.createCallback, - pDeleteFunc: this.deleteCallback - }; - const packed = FFLTextureCallback.pack(textureCallback); - this.textureCallbackPtr = mod._malloc(FFLTextureCallback.size); - mod.HEAPU8.set(new Uint8Array(packed), this.textureCallbackPtr); - mod._FFLSetTextureCallback(this.textureCallbackPtr); - } - - /** - * @private - * @param {number} format - Enum value for FFLTextureFormat. - * @returns {number|null} Three.js texture format constant. - * @throws {Error} Unexpected FFLTextureFormat value - * - * Note that this function won't work on WebGL1Renderer in Three.js r137-r161 since R and RG textures need to use Luminance(Alpha)Format - * - (you'd somehow need to detect which renderer is used) - */ - _getTextureFormat(format) { - // Map FFLTextureFormat to Three.js texture formats. - - // THREE.RGFormat did not work for me on Three.js r136/older. - const useGLES2Formats = Number(THREE.REVISION) < 137; - const r8 = useGLES2Formats - ? THREE.LuminanceFormat - : THREE.RedFormat; - const r8g8 = useGLES2Formats - // NOTE: Using THREE.LuminanceAlphaFormat before - // it was removed, on WebGL 2.0, causes the texture - // to be converted to RGBA resulting in two issues. - // - There is a black outline around glasses - // - For glasses that have an inner color, the color is wrongly applied to the frames as well. - ? THREE.LuminanceAlphaFormat - : THREE.RGFormat; - - const textureFormatToThreeFormat = { - [FFLTextureFormat.R8_UNORM]: r8, - [FFLTextureFormat.R8_G8_UNORM]: r8g8, - [FFLTextureFormat.R8_G8_B8_A8_UNORM]: THREE.RGBAFormat - }; - - // Determine the data format from the table. - const dataFormat = textureFormatToThreeFormat[format]; - if (dataFormat === undefined) { - throw new Error(`_textureCreateFunc: Unexpected FFLTextureFormat value: ${format}`); - } - return dataFormat; - } - - /** - * @private - * @param {number} _ - Originally pObj. - * @param {number} textureInfoPtr - * @param {number} texturePtrPtr - */ - _textureCreateFunc(_, textureInfoPtr, texturePtrPtr) { - const u8 = this.module.HEAPU8.subarray(textureInfoPtr, textureInfoPtr + FFLTextureInfo.size); - const textureInfo = FFLTextureInfo.unpack(u8); - // console.debug(`_textureCreateFunc: width=${textureInfo.width}, height=${textureInfo.height}, format=${textureInfo.format}, imageSize=${textureInfo.imageSize}, mipCount=${textureInfo.mipCount}`); - - const dataFormat = this._getTextureFormat(textureInfo.format); - - // Copy image data from HEAPU8 via slice. This is base level/mip level 0. - const imageData = this.module.HEAPU8.slice(textureInfo.imagePtr, textureInfo.imagePtr + textureInfo.imageSize); - - const texture = new THREE.DataTexture(imageData, textureInfo.width, textureInfo.height, dataFormat, THREE.UnsignedByteType); - - texture.magFilter = THREE.LinearFilter; - // texture.generateMipmaps = true; // not necessary at higher resolutions - texture.minFilter = THREE.LinearFilter; - - // Mipmaps were not implemented before Three.js r136 - // and they only began functioning properly on r138 - const useMipmaps = Number(THREE.REVISION) >= 138; - if (useMipmaps) { - texture.minFilter = THREE.LinearMipmapLinearFilter; - texture.generateMipmaps = false; - this._addMipmaps(texture, textureInfo); - } - - texture.needsUpdate = true; - this.set(texture.id, texture); - this.module.HEAPU32[texturePtrPtr / 4] = texture.id; - } - - /** - * @private - * @param {THREE.Texture} texture - Texture to upload mipmaps into. - * @param {FFLTextureInfo} textureInfo - FFLTextureInfo object representing this texture. - * @throws {Error} Unexpected FFLTextureFormat value - */ - _addMipmaps(texture, textureInfo) { - // Skip if there are no mipmaps. - if (textureInfo.mipPtr === 0 || textureInfo.mipCount < 2) { - return; - } - - // Calculate bytes per pixel. - // Mapping: FFLTextureFormat.R8_UNORM -> 1, R8_G8_UNORM -> 2, R8_G8_B8_A8_UNORM -> 4. - const bytesPerPixel = [1, 2, 4][textureInfo.format]; - if (!bytesPerPixel) { - throw new Error(`_addMipmaps: Unexpected FFLTextureFormat value: ${textureInfo.format}`); - } - - // Iterate through mip levels starting from 1 (base level is mip level 0). - for (let mipLevel = 1; mipLevel < textureInfo.mipCount; mipLevel++) { - // Calculate the offset for the current mip level. - const mipOffset = textureInfo.mipLevelOffset[mipLevel - 1]; - - // Calculate dimensions of the current mip level. - const mipWidth = Math.max(1, textureInfo.width >> mipLevel); - const mipHeight = Math.max(1, textureInfo.height >> mipLevel); - - // Calculate the size in bytes of the current mip level. - const mipSize = mipWidth * mipHeight * bytesPerPixel; - - // Copy the data from the heap. - const start = textureInfo.mipPtr + mipOffset; - const mipData = this.module.HEAPU8.slice(start, start + mipSize); - - // console.debug(` - Mip ${mipLevel}: ${mipWidth}x${mipHeight}, offset=${mipOffset}`); - // console.debug(uint8ArrayToBase64(mipData)); - - // Push this mip level data into the texture's mipmaps array. - texture.mipmaps.push({ - data: mipData, - width: mipWidth, - height: mipHeight - }); - } - } - - /** - * @private - * @param {number} _ - Originally pObj. - * @param {number} texturePtr - */ - _textureDeleteFunc(_, texturePtr) { - const texId = this.module.HEAPU32[texturePtr / 4]; - // this.delete(texId); - // NOTE: This is effectively no longer used as when - // we delete a CharModel instance it deletes - // cap/noseline/glass textures before we are - // finished with the model itself. It is now only logging - const tex = this.textures.get(texId); - - // if (tex) { - // console.debug('Delete texture ', tex.id); - // } - } - - /** - * @public - * @param {number} id - ID assigned to the texture. - * @returns {THREE.Texture|null} - */ - get(id) { - const texture = this.textures.get(id); - if (!texture) { - console.error('Unknown texture', id); - } - return texture; - } - - /** - * @public - * @param {number} id - ID assigned to the texture. - * @param {THREE.Texture} texture - Texture to add. - */ - set(id, texture) { - // Set texture with an override for dispose. - texture._dispose = texture.dispose.bind(texture); - texture.dispose = () => { - // Remove from the texture map before disposing. - this.delete(id); // this = TextureManager - // The above will call _dispose. - }; - - this.textures.set(id, texture); - // Log is spaced to match delete/deleting/dispose messages. - // console.debug('Adding texture ', texture.id); - } - - /** - * @public - * @param {number} id - ID assigned to the texture. - */ - delete(id) { - // Get texture from array instead of with get() - // because it's okay if it was already deleted. - const texture = this.textures.get(id); - if (texture) { - // This class will always set _dispose as - // the original dispose method on textures. - texture._dispose(); - texture.source = null; - // console.debug('Deleted texture ', id); - this.textures.delete(id); - } - } -} - -// // --------------------------------------------------------------------- -// // FFL Initialization -// // --------------------------------------------------------------------- - -// ---------------------- handleFFLResult(name, result) ---------------------- -/** - * Checks the FFLResult returned from a function and throws an exception - * if the result is not FFL_RESULT_OK. - * - * @param {string} name - The name of the function whose result to check. - * @param {number} result - The returned FFLResult enum value. - * @throws {Error} Throws if the result is not 0 (FFL_RESULT_OK). - * @returns {void} Returns nothing if the result is 0. - * @todo TODO: Should preferably return a custom error class. - */ -function handleFFLResult(name, result) { - let error; // Error string to alert() and construct new Error from. - if (typeof result !== 'number') { - error = `Unexpected type for FFLResult from ${name}: ${typeof result}`; - } else if (result !== 0) { // FFL_RESULT_OK - error = `${name} failed with FFLResult: ${result}`; - } - - if (error) { - // Alert and throw Error from string. - // alert(error); - throw new Error(error); - } - // Result equals 0 (FFL_RESULT_OK), meaning that function succeeded. -} - -/** - * @private - * Loads data from TypedArray or fetch response directly into Emscripten heap. - * If passed a fetch response, it streams it directly into memory and avoids copying. - * - * @param {Uint8Array|Response} resource - The resource data. - * - Use a TypedArray if you have the raw bytes. - * - Use a fetch Response to stream it directly. - * @param {Module} module - The Emscripten module instance. - * @returns {Promise<{pointer: number, size: number}>} Pointer and size of the allocated heap memory. - * @throws {Error} resource must be a Uint8Array or fetch that is streamable and has Content-Length. - */ -async function _loadDataIntoHeap(resource, module) { - // These need to be accessible by the catch statement: - let heapSize; - let heapPtr; - try { - // Copy resource into heap. - if (resource instanceof ArrayBuffer) { - resource = new Uint8Array(resource); - } - if (resource instanceof Uint8Array) { - // Recommend passing in fetch Response, read func description for why - console.warn('initializeFFL -> _loadDataIntoHeap: resource was passed as Uint8Array/ArrayBuffer. Please pass in a fetch Response instance for improved efficiency.'); - - heapSize = resource.length; - heapPtr = module._malloc(heapSize); - console.debug(`loadDataIntoHeap: Loading from Uint8Array. Size: ${heapSize}, pointer: ${heapPtr}`); - // Allocate and set this area in the heap as the passed array. - module.HEAPU8.set(resource, heapPtr); - } else if (resource instanceof Response) { - // Handle as fetch response. - // Throw an error if it is not a streamable response. - if (!resource.body) { - throw new Error('Fetch response is not streamable.'); - } - - // Get the total size of the resource from the headers. - const contentLength = resource.headers.get('Content-Length'); - if (!contentLength) { - throw new Error('Fetch response missing Content-Length.'); - } - - // Allocate into heap using the Content-Length. - heapSize = parseInt(contentLength, 10); - heapPtr = module._malloc(heapSize); - - console.debug(`loadDataIntoHeap: Streaming ${heapSize} bytes from fetch response. URL: ${resource.url}, pointer: ${heapPtr}`); - - // Begin reading and streaming chunks into the heap. - const reader = resource.body.getReader(); - let offset = heapPtr; - while (true) { - const { done, value } = await reader.read(); - if (done) { - break; - } - // Copy value directly into HEAPU8 with offset. - module.HEAPU8.set(value, offset); - offset += value.length; - } - } else { - throw new Error('loadDataIntoHeap: type is not Uint8Array or Response'); - } - - return { pointer: heapPtr, size: heapSize }; - } catch (error) { - // Free memory upon exception, if allocated. - if (heapPtr) { - module._free(heapPtr); - } - throw error; - } -} - -/** - * @global - * Global storing the FFLResourceDesc instance that points to - * where the FFL resource is allocated in the heap. - */ -let _resourceDesc; - -// --------------------- initializeFFL(resource, module) --------------------- -/** - * Initializes FFL by copying a resource (TypedArray or fetch response) into - * heap and calling FFLInitRes. It will first wait for the module to be ready. - * - * @param {Uint8Array|Response} resource - The FFL resource data. - * Use a TypedArray if you have the raw bytes, or a fetch response containing - * the FFL resource file. - * @param {Module} [module=global.Module] - The Emscripten module instance. - * @returns {Promise} Resolves when FFL is fully initialized. - * @todo TODO TODO: DOES NOT WORK PROPERLY when CACHE IS ENABLED ???? - */ -async function initializeFFL(resource, module = global.Module) { - console.debug('initializeFFL: Entrypoint, waiting for module to be ready.'); - - let resourceDescPtr; // Store pointer to free later. - // Continue when Emscripten module is initialized. - return new Promise((resolve) => { - // try { - // If onRuntimeInitialized is not defined on module, add it. - if (!module.calledRun && !module.onRuntimeInitialized) { - module.onRuntimeInitialized = () => { - console.debug('initializeFFL: Emscripten runtime initialized, resolving.'); - resolve(); - }; - console.debug(`initializeFFL: module.calledRun: ${module.calledRun}, module.onRuntimeInitialized: ${module.onRuntimeInitialized} / << assigned and waiting.`); - } else { - console.debug('initializeFFL: Assuming module is ready.'); - resolve(); - } - // } catch(e) { - // debugger; throw e; - // } - }) - // .then(() => { - // return resource.arrayBuffer(); - // }) - .then(async () => { - if (resource instanceof Promise) { - resource = await resource; - } - }) - .then(() => { - return _loadDataIntoHeap(resource, module); - }) - .then(({ pointer: heapPtr, size: heapSize }) => { - console.debug(`initializeFFL: Resource loaded into heap. Pointer: ${heapPtr}, Size: ${heapSize}`); - - // Initialize and pack FFLResourceDesc. - const resourceDesc = { pData: [0, 0], size: [0, 0] }; - // Using high resource type as the default. - resourceDesc.pData[FFLResourceType.HIGH] = heapPtr; - resourceDesc.size[FFLResourceType.HIGH] = heapSize; - - _resourceDesc = resourceDesc; // Set as global to free later. - const resourceDescData = FFLResourceDesc.pack(resourceDesc); - resourceDescPtr = module._malloc(FFLResourceDesc.size); - module.HEAPU8.set(resourceDescData, resourceDescPtr); - - // Call FFL initialization. FFL_FONT_REGION_JP_US_EU = 0 - const result = module._FFLInitRes(0, resourceDescPtr); - handleFFLResult('FFLInitRes', result); // Potentially throw. - - // Set required globals in FFL. - module._FFLInitResGPUStep(); // CanInitCharModel will fail if not called. - module._FFLSetNormalIsSnorm8_8_8_8(true); // Set normal format to FFLiSnorm8_8_8_8. - module._FFLSetTextureFlipY(true); // Set textures to be flipped for WebGL. - - // Requires refactoring: - // module._FFLSetScale(0.1); // Sets model scale back to 1.0. - // module._FFLSetLinearGammaMode(1); // Use linear gamma. - // I don't think ^^ will work because the shaders need sRGB - }) - .catch((error) => { - module._free(); - console.error('initializeFFL failed:', error); - throw error; - }) - .finally(() => { - if (resourceDescPtr) { - // Free FFLResourceDesc, unused after init. - module._free(resourceDescPtr); - } - }); -} - -// ------------- initializeFFLWithResource(resourcePath, module) ------------- -/** - * Fetches the FFL resource from the specified path or the "content" - * attribute of this HTML element: meta[itemprop=ffl-js-resource-fetch-path] - * It then calls initializeFFL on the specified module. - * - * @param {string|null} [resourcePath=null] - The URL for the FFL resource. - * @param {Module} [module=global.Module] - The Emscripten module instance. - * @returns {Promise} Returns when the fetch and initializeFFL are finished. - * @throws {Error} resourcePath must be a URL string, or, an HTML element with FFL resource must exist and have content. - */ -export async function initializeFFLWithResource(resourcePath = null, module = global.Module) { - // Query selector string for element with "content" attribute for path to the resource. - const querySelectorResourcePath = 'meta[itemprop=ffl-js-resource-fetch-path]'; - - if (!resourcePath && typeof document !== 'undefined') { - // Load FFL resource file from meta tag in HTML. - const resourceFetchElement = document.querySelector(querySelectorResourcePath); - if (!resourceFetchElement || !resourceFetchElement.getAttribute('content')) { - throw new Error(`initializeFFLWithResource: Element not found or does not have "content" attribute with path to FFL resource: ${querySelectorResourcePath}`); - } - // URL to resource for FFL. - resourcePath = resourceFetchElement.getAttribute('content'); - } - // is it still null? - if (!resourcePath) { - throw new Error('initializeFFLWithResource: resourcePath must be a string'); - } - try { - const response = await fetch(resourcePath); // Fetch resource. - // Initialize FFL using the resource from fetch response. - await initializeFFL(response, module); - // TextureManager must be initialized after FFL. - /** @global */ - global.FFLTextures = new TextureManager(module); - console.debug('initializeFFLWithResource: FFLiManager and TextureManager initialized, exiting'); - } catch (error) { - // TODO: should this alert or no, because it's meant to be a nice wrapper - alert(`Error initializing FFL with resource: ${error}`); - throw error; - } -} - -// -------------------------------- exitFFL() -------------------------------- -/** - * @public - * @param {Module} module - * @todo TODO: Untested, need to destroy Emscripten instance. - */ -export function exitFFL(module) { - if (!_resourceDesc) { - console.warn('exitFFL was called when FFL is not initialized.'); - return; - } - - console.debug('exitFFL called, _resourceDesc:', _resourceDesc); - - // All CharModels must be deleted before this point. - module._FFLExit(); - - // Free resources in heap after FFLExit(). - _resourceDesc.pData.forEach((ptr) => { - if (ptr) { - module._free(_fflResourcePtr); - } - }); -} - -// // --------------------------------------------------------------------- -// // CharModel Handling -// // --------------------------------------------------------------------- - -// --------------------------- Class: CharModel ------------------------------- -/** - * @public - * Represents an FFLCharModel, which is the head model. - * Encapsulates a pointer to the underlying instance and provides helper methods. - * - * NOTE: This is a wrapper around CharModel. In order to create one, - * either call createCharModel or pass the pointer of a manually created - * CharModel in here. So *DO NOT* call this constructor directly! - */ -export class CharModel { - /** - * @constructor - * @param {number} ptr - Pointer to the FFLiCharModel structure in heap. - * @param {Module} [module=global.Module] - The Emscripten module. - * @param {Function} materialClass - The material constructor (e.g., FFLShaderMaterial). - */ - constructor(ptr, module = global.Module, materialClass = global.FFLShaderMaterial) { - /** @private */ - this._module = module; - /** @public */ - this._materialClass = materialClass; // Store the material class. - /** - * @private - * Pointer to the FFLiCharModel in memory, set to null when deleted. - */ - this._ptr = ptr; - /** @private */ - this.__ptr = ptr; // Permanent reference. - // Unpack the FFLiCharModel structure from heap. - const charModelData = this._module.HEAPU8.subarray(ptr, ptr + FFLiCharModel.size); - /** - * @readonly - * The unpacked representation of the underlying - * FFLCharModel instance. Note that this is not - * meant to be updated at all and changes to - * this instance will not apply in FFL whatsoever. - */ - this._model = FFLiCharModel.unpack(charModelData); - // NOTE: The only property SET in _model is expression. - // Everything else is read. - - // this.additionalInfo = this._getAdditionalInfo(); - - // Add RenderTargets for faceline and mask. - /** - * @private - * @type {THREE.RenderTarget} - */ - this._facelineTarget = null; - /** - * @private - * @type {Array} - */ - this._maskTargets = new Array(FFLExpression.MAX).fill(null); - - /** - * @public - * Group of THREE.Mesh objects representing the CharModel. - * @type {THREE.Group} - */ - this.meshes = new THREE.Group(); - // Set boundingBox getter ("this" = CharModel), dummy geometry needed - // this.meshes.geometry = { }; // NOTE: is this a good idea? - // Object.defineProperty(this.meshes.geometry, 'boundingBox', { get: () => this.boundingBox }); // TODO: box is too large using this - - this._addCharModelMeshes(module); // Populate this.meshes. - } - - /** - * @private - * This is the method that populates meshes - * from the internal FFLiCharModel instance. - * @param {Module} module - Module to pass to drawParamToMesh to access mesh data. - */ - _addCharModelMeshes(module) { - // Add all meshes in the CharModel to the class instance. - for (let shapeType = 0; shapeType < FFLiShapeType.MAX; shapeType++) { - // Iterate through all DrawParams and convert to THREE.Mesh. - const drawParam = this._model.drawParam[shapeType]; - - // This will be null if there is no shape data, - // but it will be added anyway so that the indexes - // of this group all match up with FFLiShapeType. - const mesh = drawParamToMesh(drawParam, this._materialClass, module); - // if (mesh) { - if (!mesh) { - continue; - } - // Use FFLModulateType to indicate render order. - mesh.renderOrder = drawParam.modulateParam.type; - // } - // Set _facelineID and _maskID. - switch (shapeType) { - case FFLiShapeType.OPA_FACELINE: { - /** - * @private - * The object ID representing the faceline shape. - */ - this._facelineID = mesh.id; - break; - } - case FFLiShapeType.XLU_MASK: { - /** - * @private - * The object ID representing the mask shape. - */ - this._maskID = mesh.id; - break; - } - } - - this.meshes.add(mesh); // Add the mesh or null. - } - } - - /** @private */ - _getTextureTempObjectPtr() { - // console.debug(`_getTextureTempObjectPtr: pTextureTempObject = ${this._model.pTextureTempObject}, pCharModel = ${this._ptr}`); - return this._model.pTextureTempObject; - } - - /** @public */ - _getTextureTempObject() { - const ptr = this._getTextureTempObjectPtr(); - return FFLiTextureTempObject.unpack(this._module.HEAPU8.subarray(ptr, ptr + FFLiTextureTempObject.size)); - } - - /** - * @private - * Get the unpacked result of FFLGetAdditionalInfo. - */ - _getAdditionalInfo() { - const mod = this._module; - const addInfoPtr = mod._malloc(FFLAdditionalInfo.size); - const result = mod._FFLGetAdditionalInfo(addInfoPtr, FFLDataSource.BUFFER, this._ptr, 0, false); - handleFFLResult('FFLGetAdditionalInfo', result); - const info = FFLAdditionalInfo.unpack(mod.HEAPU8.subarray(addInfoPtr, addInfoPtr + FFLAdditionalInfo.size)); - mod._free(addInfoPtr); - return info; - } - - /** - * @private - * Accesses partsTransform in FFLiCharModel, - * converting every FFLVec3 to THREE.Vector3. - * @throws {Error} Throws if this._model.partsTransform has objects that do not have "x" property. - */ - _getPartsTransform() { - const obj = this._model.partsTransform; - for (const key in obj) { - // sanity check make sure there is "x" - if (obj[key].x === undefined) { - throw new Error(); - } - // convert to THREE.Vector3 - obj[key] = new THREE.Vector3(obj[key].x, obj[key].y, obj[key].z); - } - return obj; - } - - /** @private */ - _getFacelineColor() { - // const color = this.additionalInfo.skinColor; - // return new THREE.Color(color.r, color.g, color.b); - const mod = this._module; - const facelineColor = this._model.charInfo.faceline.color; - const colorPtr = mod._malloc(FFLColor.size); // Allocate return pointer. - mod._FFLGetFacelineColor(colorPtr, facelineColor); - const color = _getVector4FromFFLColorPtr(colorPtr, mod); - mod._free(colorPtr); - return new THREE.Color().setRGB(color.x, color.y, color.z);// , THREE.SRGBColorSpace); // No alpha component. - // Assume this is in working color space because it is used for clear color. - } - - /** @private */ - _getFavoriteColor(linear = false) { - const mod = this._module; - const favoriteColor = this._model.charInfo.personal.favoriteColor; - const colorPtr = mod._malloc(FFLColor.size); // Allocate return pointer. - mod._FFLGetFavoriteColor(colorPtr, favoriteColor); // Get favoriteColor from CharInfo. - const color = _getVector4FromFFLColorPtr(colorPtr, mod); - mod._free(colorPtr); - return new THREE.Color().setRGB(color.x, color.y, color.z, linear === false ? THREE.SRGBColorSpace : THREE.LinearSRGBColorSpace); - } - - // custom - /** @private */ - _getGender() { - return this._model.charInfo.personal.gender; - } - - /** @private */ - _getCharInfoUint8Array() { - return FFLiCharInfo.pack(this._model.charInfo); - } - - /** @public */ - _getPartsTexturesPtr() { - return this._model.pTextureTempObject + FFLiTextureTempObject.fields.maskTextures.offset + - FFLiMaskTexturesTempObject.fields.partsTextures.offset; - } - - /** @public */ - _getFacelineTempObjectPtr() { - return this._model.pTextureTempObject + FFLiTextureTempObject.fields.facelineTexture.offset; - } - - /** @public */ - _getMaskTempObjectPtr() { - return this._model.pTextureTempObject + FFLiTextureTempObject.fields.maskTextures.offset; - } - - /** - * @private - * @returns {THREE.Box3} - */ - _getBoundingBox() { - const box = this._model.boundingBox[this._model.modelType]; - const min = new THREE.Vector3(box.min.x, box.min.y, box.min.z); - const max = new THREE.Vector3(box.max.x, box.max.y, box.max.z); - return new THREE.Box3(min, max); - } - - /** - * @public - * Get the texture resolution. - */ - _getResolution() { - return this._model.charModelDesc.resolution & FFL_RESOLUTION_MASK; - } - - /** - * @private - * Finalizes the CharModel. - * Frees and deletes the CharModel right after generating textures. - * This is **not** the same as `dispose()` which cleans up the scene. - */ - _finalizeCharModel() { - if (!this._ptr) { - return; - } - this._module._FFLDeleteCharModel(this._ptr); - this._module._free(this._ptr); - this._ptr = null; - } - - /** - * @public - * Disposes RenderTargets for textures created by the CharModel. - */ - _disposeTextures() { - // Dispose RenderTargets. - if (this._facelineTarget) { - // console.debug(`Disposing target ${this._facelineTarget.texture.id} for faceline`); - this._facelineTarget.dispose(); - this._facelineTarget = null; - } - // _maskTargets should always be defined. - this._maskTargets.forEach((target, i) => { - if (!target) { - // No mask for this expression. - return; - } - // console.debug(`Disposing target ${target.texture.id} for mask ${i}`); - target.dispose(); - this._maskTargets[i] = null; - }); - } - - // Public methods: - - /** - * @public - * Disposes the CharModel and removes all associated resources. - * - Disposes materials and geometries. - * - Deletes faceline texture if it exists. - * - Deletes all mask textures. - * - Removes all meshes from the scene. - */ - dispose() { - // Print the permanent __ptr rather than _ptr. - // console.debug('CharModel.dispose: ptr =', this.__ptr); - this._finalizeCharModel(); // Should've been called already - // Dispose meshes: materials, geometries, textures. - disposeMeshes(this.meshes); - this.meshes = null; - // Dispose render textures. - this._disposeTextures(); - } - - // Data properties - - /** - * @public - * Serializes the CharModel data to FFLStoreData. - * @returns {Uint8Array} The exported FFLStoreData. - * @throws {Error} Throws if call to _FFLpGetStoreDataFromCharInfo returns false, usually when CharInfo verification fails. - */ - getStoreData() { - // Serialize the CharInfo. - const charInfoData = this._getCharInfoUint8Array(); - - const mod = this._module; - // Allocate function arguments. - const charInfoPtr = mod._malloc(FFLiCharInfo.size); // Input - const storeDataPtr = mod._malloc(FFLStoreData_size); // Output - mod.HEAPU8.set(charInfoData, charInfoPtr); - - // Call conversion function. - const result = mod._FFLpGetStoreDataFromCharInfo(storeDataPtr, charInfoPtr); - // Free and return data. - const storeData = mod.HEAPU8.slice(storeDataPtr, storeDataPtr + FFLStoreData_size); - mod._free(charInfoPtr); - mod._free(storeDataPtr); - - if (!result) { - throw new Error('getStoreData: call to FFLpGetStoreDataFromCharInfo returned false, CharInfo verification probably failed'); - } - - return storeData; - } - - // getCharInfoStudio - - // Cosmetic properties - - /** - * @public - * Sets the expression for this CharModel and updates the corresponding mask texture. - * @param {number} expression - The new expression index. - * @throws {Error} CharModel must have been initialized with the expression enabled in the flag and have XLU_MASK in meshes. - */ - setExpression(expression) { - this._model.expression = expression; - const target = this._maskTargets[expression]; - if (!target || !target.texture) { - throw new Error(`setExpression: this._maskTargets[${expression}].texture is not a valid texture`); - } - // const mesh = this.meshes[FFLiShapeType.XLU_MASK]; - const mesh = this.meshes.getObjectById(this._maskID); - if (!mesh) { - throw new Error('setExpression: this.meshes[FFLiShapeType.XLU_MASK] does not exist, cannot set expression on the mask'); - } - - // Update texture and material. - mesh.material.map = target.texture; - mesh.material.needsUpdate = true; - } - - /** - * @public - * The current expression for this CharModel. - * Use setExpression to set the expression. - * @returns {FFLExpression} The current expression. - */ - get expression() { - return this._model.expression; // mirror - } - - /** - * @throws {Error} This method cannot be called, you have to use setExpression. - */ - set expression(_) { - throw new Error('nope you cannot do this, try setExpression instead'); - } - - /** - * @public - * The faceline color for this CharModel. - * @returns {THREE.Color} The faceline color. - */ - get facelineColor() { - if (!this._facelineColor) { - /** @private */ - this._facelineColor = this._getFacelineColor(); - } - return this._facelineColor; - } - - /** - * @public - * The favorite color for this CharModel. - * @returns {THREE.Vector4} The favorite color as Vector4. - */ - get favoriteColor() { - if (!this._favoriteColor) { - /** @private */ - this._favoriteColor = this._getFavoriteColor(); - } - return this._favoriteColor; - } - - /** - * @public - * The parameters in which to transform hats and other accessories. - * @returns {Object} The PartsTransform object containing THREE.Vector3. - */ - get partsTransform() { - if (!this._partsTransform) { - // Set partsTransform property as THREE.Vector3. - /** @private */ - this._partsTransform = this._getPartsTransform(); - } - return this._partsTransform; - } - - /** - * @public - * @returns {THREE.Box3} - */ - get boundingBox() { - if (!this._boundingBox) { - // Set boundingBox property as THREE.Box3. - /** @private */ - this._boundingBox = this._getBoundingBox(); - } - return this._boundingBox; - } - - /** - * @enum {number} - */ - static BodyScaleMode = { - Apply: 0, // Applies scale like all apps. - Limit: 1 // Limits scale so that the pants are not visible. - }; - - /** - * @public - * Gets a vector in which to scale the body model for this CharModel. - * @param {CharModel.BodyScaleMode} [scaleMode=CharModel.BodyScaleMode.Apply] scaleMode - * @returns {THREE.Vector3} Scale vector for the body model. - * @throws {Error} Unexpected value for scaleMode - */ - getBodyScale(scaleMode = CharModel.BodyScaleMode.Apply) { - const build = this._model.charInfo.body.build; - const height = this._model.charInfo.body.height; - - const bodyScale = new THREE.Vector3(); - switch (scaleMode) { - case CharModel.BodyScaleMode.Apply: { - // calculated in this function: void __cdecl nn::mii::detail::`anonymous namespace'::GetBodyScale(struct nn::util::Float3 *, int, int) - // in libnn_mii/draw/src/detail/mii_VariableIconBodyImpl.cpp - // also in ffl_app.rpx: FUN_020ec380 (FFLUtility), FUN_020737b8 (mii maker US) - // ScaleApply - // 0.47 / 128.0 = 0.003671875 - bodyScale.x = (build * (height * 0.003671875 + 0.4)) / 128.0 + - // 0.23 / 128.0 = 0.001796875 - height * 0.001796875 + 0.4; - // 0.77 / 128.0 = 0.006015625 - bodyScale.y = (height * 0.006015625) + 0.5; - break; - } - case CharModel.BodyScaleMode.Limit: { - // ScaleLimit - const heightFactor = height / 128.0; - bodyScale.y = heightFactor * 0.55 + 0.6; - bodyScale.x = heightFactor * 0.3 + 0.6; - bodyScale.x = ((heightFactor * 0.6 + 0.8) - bodyScale.x) * - (build / 128.0) + bodyScale.x; - break; - } - default: - throw new Error(`getBodyScale: Unexpected value for scaleMode: ${scaleMode}`); - } - - // z is always set to x for either set - bodyScale.z = bodyScale.x; - - return bodyScale; - } -} - -/** - * @enum {number} - */ -const PantsColor = { - GrayNormal: 0, - BluePresent: 1, - RedRegular: 2, - GoldSpecial: 3 -}; - -/** - * @type {Record} - */ -const pantsColors = { - [PantsColor.GrayNormal]: new THREE.Color(0x40474E), - [PantsColor.BluePresent]: new THREE.Color(0x28407A), - [PantsColor.RedRegular]: new THREE.Color(0x702015), - [PantsColor.GoldSpecial]: new THREE.Color(0xC0A030) -}; - -/** - * @private - * Converts the input data and allocates it into FFLCharModelSource. - * Note that this allocates pBuffer so you must free it when you are done. - * - * @param {Uint8Array|FFLiCharInfo} data - Input: FFLStoreData, FFLiCharInfo (as Uint8Array and object), StudioCharInfo - * @param {Module} module - Module to allocate and access the buffer through. - * @returns {FFLCharModelSource} The CharModelSource with the data specified. - * @throws {Error} data must be Uint8Array or FFLiCharInfo object. Data must be a known type. - */ -function _allocateModelSource(data, module) { - const bufferPtr = module._malloc(FFLiCharInfo.size); // Maximum size. - - // Create modelSource. - const modelSource = { - // FFLDataSource.BUFFER = copies and verifies - // FFLDataSource.DIRECT_POINTER = use without verification. - dataSource: FFLDataSource.DIRECT_POINTER, // Assumes CharInfo by default. - pBuffer: bufferPtr, - index: 0 // Only for default, official, MiddleDB; unneeded for raw data - }; - - // module._FFLiGetRandomCharInfo(bufferPtr, FFLGender.FEMALE, FFLAge.ALL, FFLRace.WHITE); return modelSource; - - // Check type of data. - if (!(data instanceof Uint8Array)) { - try { - if (typeof data !== 'object') { - throw new Error('_allocateModelSource: data passed in is not FFLiCharInfo object or Uint8Array'); - } - // Assume that this is FFLiCharInfo as an object. - // Deserialize to Uint8Array. - data = FFLiCharInfo.pack(data); - } catch (e) { - module._free(bufferPtr); - throw e; - } - } - - // data should be Uint8Array at this point. - - // Enumerate through supported data types. - switch (data.length) { - // @ts-expect-error - case FFLStoreData_size: { // sizeof(FFLStoreData) - // modelSource.dataSource = FFLDataSource.STORE_DATA; - // Convert FFLStoreData to FFLiCharInfo instead. - const storeDataPtr = module._malloc(FFLStoreData_size); - module.HEAPU8.set(data, storeDataPtr); - const result = module._FFLpGetCharInfoFromStoreData(bufferPtr, storeDataPtr); - module._free(storeDataPtr); - if (!result) { - module._free(bufferPtr); - throw new Error('_allocateModelSource: call to FFLpGetCharInfoFromStoreData returned false, CharInfo verification probably failed'); - } - break; - } - case FFLiCharInfo.size: - // modelSource.dataSource = FFLDataSource.BUFFER; // Default option. - module.HEAPU8.set(data, bufferPtr); // Copy data into heap. - break; - case StudioCharInfo.size + 1: // studio obfuscated - data = studioURLObfuscationDecode(data); - // Fall-through by converting it the same way. - case StudioCharInfo.size: { // studio raw, decode it to charinfo - // Decode studio data in bytes - const studio = StudioCharInfo.unpack(data); - const charInfo = convertStudioCharInfoToFFLiCharInfo(studio); - data = FFLiCharInfo.pack(charInfo); - module.HEAPU8.set(data, bufferPtr); - break; - } - default: { - module._free(bufferPtr); - throw new Error(`_allocateModelSource: Unknown data length: ${data.length}`); - } - } - - return modelSource; // NOTE: pBuffer must be freed. -} - -// ----------------- verifyCharInfo(data, module, verifyName) ----------------- -/** - * @public - * Validates the input CharInfo by calling FFLiVerifyCharInfoWithReason. - * - * @param {Uint8Array|number} data - FFLiCharInfo structure as bytes or pointer. - * @param {Module} module - Module to access the data and call FFL through. - * @param {Boolean} verifyName - Whether the name and creator name should be verified. - * @returns {void} Returns nothing if verification passes. - * @throws {Error} Throws if the result is not 0 (FFLI_VERIFY_REASON_OK). - * @todo TODO: Should preferably return a custom error class. - */ -export function verifyCharInfo(data, module, verifyName = false) { - // Resolve charInfoPtr as pointer to CharInfo. - let charInfoPtr = 0; - let charInfoAllocated = false; - // Assume that number means pointer. - if (typeof data === 'number') { - charInfoPtr = data; - charInfoAllocated = false; - } else { - // Assume everything else means Uint8Array. TODO: untested - charInfoAllocated = true; - // Allocate and copy CharInfo. - charInfoPtr = module._malloc(FFLiCharInfo.size); - module.HEAPU8.set(data, charInfoPtr); - } - const result = module._FFLiVerifyCharInfoWithReason(charInfoPtr, verifyName); - // Free CharInfo as soon as the function returns. - if (charInfoAllocated) { - module._free(charInfoPtr); - } - - if (result !== 0) { - // Reference: https://github.com/aboood40091/ffl/blob/master/include/nn/ffl/detail/FFLiCharInfo.h#L90 - throw new Error(`FFLiVerifyCharInfoWithReason failed with result: ${result}`); - } -} - -// --------------- getRandomCharInfo(module, gender, age, race) --------------- -/** - * Generates a random FFLiCharInfo instance calling FFLiGetRandomCharInfo. - * - * @param {Module} module - * @param {FFLGender} [gender=FFLGender.ALL] - Gender of the character. - * @param {FFLAge} [age=FFLAge.ALL] - Age of the character. - * @param {FFLRace} [race=FFLRace.ALL] - Race of the character. - * @todo TODO: Should this return FFLiCharInfo object? - * @returns {Uint8Array} The random FFLiCharInfo. - */ -function getRandomCharInfo(module, gender, age, race) { - const ptr = module._malloc(FFLiCharInfo.size); - module._FFLiGetRandomCharInfo(ptr, gender, age, race); - const result = module.HEAPU8.slice(ptr, ptr + FFLiCharInfo.size); - module._free(ptr); - return result; -} - -// --------------------- makeExpressionFlag(expressions) ---------------------- -/** - * Creates an expression flag to be used in FFLCharModelDesc. - * @param {number[]|number} expressions - Array of expression indices, or a single expression index. - * @returns {Uint32Array} FFLAllExpressionFlag type of three 32-bit integers. - * @throws {Error} expressions must be in range and less than FFLExpression.MAX. - */ -export function makeExpressionFlag(expressions) { - function checkRange(i) { - if (i >= FFLExpression.MAX) { - throw new Error(`makeExpressionFlag: input out of range: got ${i}, max: ${FFLExpression.MAX}`); - } - } - - const flags = new Uint32Array([0, 0, 0]); // FFLAllExpressionFlag - - // Set single expression. - if (typeof expressions === 'number') { - // Make expressions into an array. - expressions = [expressions]; - // Fall-through. - } else if (!Array.isArray(expressions)) { - throw new Error('makeExpressionFlag: expected array or single number'); - } - - // Set multiple expressions in an array. - for (const index of expressions) { - checkRange(index); - const part = Math.floor(index / 32); // Determine which 32-bit block - const bitIndex = index % 32; // Determine the bit within the block - - flags[part] |= (1 << bitIndex); // Set the bit - } - return flags; -} - -// // --------------------------------------------------------------------- -// // CharModel Creation -// // --------------------------------------------------------------------- - -// --------- createCharModel(data, modelDesc, materialClass, module) --------- -/** - * Creates a CharModel from data and FFLCharModelDesc. - * You must call initCharModelTextures afterwards to finish the process. - * Don't forget to call dispose() on the CharModel when you are done. - * - * @param {Uint8Array|FFLiCharInfo} data - Character data. Accepted types: FFLStoreData, FFLiCharInfo (as Uint8Array and object), StudioCharInfo - * @param {Object} [modelDesc=FFLCharModelDesc.default] - The model description. - * @param {any} materialClass - Constructor for the material (e.g. FFLShaderMaterial). - * @param {Module} [module=global.Module] - The Emscripten module. - * @param {boolean} verify - Whether the CharInfo provided should be verified. - * @returns {CharModel} The new CharModel instance. - */ -export function createCharModel(data, modelDesc, materialClass, module = global.Module, verify = true) { - modelDesc = modelDesc || FFLCharModelDesc.default; - // Allocate memory for model source, description, char model, and char info. - const modelSourcePtr = module._malloc(FFLCharModelSource.size); - const modelDescPtr = module._malloc(FFLCharModelDesc.size); - const charModelPtr = module._malloc(FFLiCharModel.size); - - // data = getRandomCharInfo(module, FFLGender.FEMALE, FFLAge.ALL, FFLRace.WHITE); console.debug('getRandomCharInfo result:', FFLiCharInfo.unpack(data)); - // Get FFLCharModelSource. This converts and allocates CharInfo. - const modelSource = _allocateModelSource(data, module); - const charInfoPtr = modelSource.pBuffer; // Get pBuffer to free it later. - - const modelSourceBuffer = FFLCharModelSource.pack(modelSource); - module.HEAPU8.set(modelSourceBuffer, modelSourcePtr); - - // Set field to enable new expressions. This field - // exists because some callers would leave the other - // bits undefined but this does not so no reason to not enable - modelDesc.modelFlag |= FFLModelFlag.NEW_EXPRESSIONS; - - const modelDescBuffer = FFLCharModelDesc.pack(modelDesc); - module.HEAPU8.set(modelDescBuffer, modelDescPtr); - try { - // Verify CharInfo before creating. - if (verify) { - verifyCharInfo(charInfoPtr, module, false); // Don't verify name. - } - - // Call FFLInitCharModelCPUStep and check the result. - const result = module._FFLInitCharModelCPUStep(charModelPtr, modelSourcePtr, modelDescPtr); - handleFFLResult('FFLInitCharModelCPUStep', result); - } catch (error) { - // Free CharModel prematurely. - module._free(charModelPtr); - throw error; - } finally { - // Free temporary allocations. - module._free(modelSourcePtr); - module._free(modelDescPtr); - module._free(charInfoPtr); - } - - // Create the CharModel instance. - const charModel = new CharModel(charModelPtr, module, materialClass); - // The constructor will populate meshes from the FFLiCharModel instance. - /** @private */ - charModel._data = data; // Store original data passed to function. - - // console.debug(`createCharModel: Initialized for "${charModel._model.charInfo.personal.name}", ptr =`, charModelPtr); - return charModel; -} - -// ------- updateCharModel(charModel, newData, renderer, descOrExpFlag) ------- -/** - * Updates the given CharModel with new data and a new ModelDesc or expression flag. - * If `descOrExpFlag` is an array, it is treated as the new expression flag while inheriting the rest - * of the ModelDesc from the existing CharModel. - * - * @param {CharModel} charModel - The existing CharModel instance. - * @param {Uint8Array|null} newData - The new raw charInfo data, or null to use the original. - * @todo TODO: Should this ^^^^^^^ just pass the charInfo object instance instead of "_data"? - * @param {THREE.Renderer} renderer - The Three.js renderer. - * @param {Object|Array|Uint32Array|null} descOrExpFlag - Either a new FFLCharModelDesc object, an array of expressions, a single expression, or an expression flag. - * @returns {CharModel} The updated CharModel instance. - * @throws {Error} Unexpected type for descOrExpFlag, newData is null - */ -export function updateCharModel(charModel, newData, renderer, descOrExpFlag = null) { - let newModelDesc; - newData = newData || charModel._data; - if (!newData) { - throw new Error('updateCharModel: newData is null. It should be retrieved from charModel._data which is set by createCharModel.'); - } - - // Initialize newFlag as the current model's expression flag. - let newFlag = charModel._model.charModelDesc.allExpressionFlag; - // Set newModelDesc depending on cases. - switch (true) { - // Array of expressions or single expression was passed in. - case (Array.isArray(descOrExpFlag) || typeof descOrExpFlag === 'number'): { - // Set descOrExpFlag as an expression flag. - descOrExpFlag = makeExpressionFlag(descOrExpFlag); - // Fall-through to set it as newFlag. - } - // descOrExpFlag is an expression flag: - case (descOrExpFlag instanceof Uint32Array): { - // If this is already an expression flag (Uint32Array), use it. - // (Or if it was set by the last case) - newFlag = descOrExpFlag; - // Fall-through to inherit the rest of CharModelDesc. - } - // descOrExpFlag is null/falsey: - case (!descOrExpFlag): { - // Inherit the CharModelDesc from the current model. - newModelDesc = charModel._model.charModelDesc; - // Set newFlag as the current (if unmodified) or new flag. - newModelDesc.allExpressionFlag = newFlag; - break; - } - // Assume that descOrExpFlag is a new FFLCharModelDesc. - case (typeof descOrExpFlag === 'object'): { - newModelDesc = descOrExpFlag; - break; - } - default: - throw new Error('updateCharModel: Unexpected type for descOrExpFlag'); - } - /* - if (Array.isArray(descOrExpFlag) || typeof descOrExpFlag === 'number') { - let newFlag; - // If this is already an expression flag (Uint32Array), use it. - if (descOrExpFlag instanceof Uint32Array) { - newFlag = descOrExpFlag; - } else { - // If an array is passed, treat it as a new expression flag. - newFlag = makeExpressionFlag(descOrExpFlag); - } - // Inherit the CharModelDesc from the current model. - newModelDesc = charModel._model.charModelDesc; - newModelDesc.allExpressionFlag = newFlag; - } else if (!descOrExpFlag) { - // Reuse old modelDesc. - newModelDesc = charModel._model.charModelDesc; - } else { - newModelDesc = descOrExpFlag; - } - */ - // Dispose of the old CharModel. - charModel.dispose(); - // Create a new CharModel with the new data and ModelDesc. - const newCharModel = createCharModel(newData, newModelDesc, charModel._materialClass, charModel._module); - // Initialize its textures. - initCharModelTextures(newCharModel, renderer, charModel._module); - return newCharModel; -} - -// // --------------------------------------------------------------------- -// // DrawParam Reading -// // --------------------------------------------------------------------- - -// TODO: private? -// ------------ drawParamToMesh(drawParam, materialClass, module) ------------ -/** - * Converts FFLDrawParam into a THREE.Mesh. - * Binds geometry, texture, and material parameters. - * - * @param {FFLDrawParam} drawParam - The DrawParam representing the mesh. - * @param {Function} materialClass - Material constructor. - * @param {Module} module - The Emscripten module. - * @returns {THREE.Mesh|null} The THREE.Mesh instance, or null if the index count is 0 indicating no shape data. - * @throws {Error} drawParam may be null, Unexpected value for FFLCullMode - */ -function drawParamToMesh(drawParam, materialClass, module) { - if (!drawParam) { - throw new Error('drawParamToMesh: drawParam may be null.'); - } - // Skip if the index count is 0, indicating no shape data. - if (drawParam.primitiveParam.indexCount === 0) { - return null; - } - // Bind geometry data. - const geometry = _bindDrawParamGeometry(drawParam, module); - // Determine cull mode by mapping FFLCullMode to THREE.Side. - const cullModeToThreeSide = { - [FFLCullMode.NONE]: THREE.DoubleSide, - [FFLCullMode.BACK]: THREE.FrontSide, - [FFLCullMode.FRONT]: THREE.BackSide, - // Used by faceline/mask 2D planes for some reason: - [FFLCullMode.MAX]: THREE.DoubleSide - }; - const side = cullModeToThreeSide[drawParam.cullMode]; - if (side === undefined) { - throw new Error(`drawParamToMesh: Unexpected value for FFLCullMode: ${drawParam.cullMode}`); - } - // Get texture. - const texture = _getTextureFromModulateParam(drawParam.modulateParam); - - // Create object for material parameters. - const materialParam = { - side: side, - // Apply texture. - map: texture, - // Apply modulateParam material parameters. - ..._applyModulateParam(drawParam.modulateParam, module) - }; - // Create material using the provided materialClass. - const material = new materialClass(materialParam); - // Create mesh and set userData.modulateType. - const mesh = new THREE.Mesh(geometry, material); - - // NOTE: Only putting it in geometry because FFL-Testing does the same. - if (mesh.geometry.userData) { - mesh.geometry.userData.modulateType = drawParam.modulateParam.type; - // whoops, mii creator's shader parsing code DEMANDS modulateMode to exist! - mesh.geometry.userData.modulateMode = drawParam.modulateParam.mode; - } - return mesh; -} - -/** - * @private - * Binds geometry attributes from drawParam into a THREE.BufferGeometry. - * @param {FFLDrawParam} drawParam - The DrawParam representing the mesh. - * @param {Module} module - The Emscripten module from which to read the heap. - * @returns {THREE.BufferGeometry} The geometry. - * @throws {Error} Position buffer must not have size of 0 - * @todo Does not yet handle color stride = 0 - */ -function _bindDrawParamGeometry(drawParam, module) { - // Access FFLAttributeBufferParam. - const attributes = drawParam.attributeBufferParam.attributeBuffers; - const positionBuffer = attributes[FFLAttributeBufferType.POSITION]; - // There should always be positions. - if (positionBuffer.size === 0) { - throw new Error('_bindDrawParamGeometry: Position buffer must not have size of 0'); - } - // Get vertex count from position buffer. - const vertexCount = positionBuffer.size / positionBuffer.stride; - const geometry = new THREE.BufferGeometry(); // Create BufferGeometry. - // Bind index data. - const indexPtr = drawParam.primitiveParam.pIndexBuffer / 2; - const indexCount = drawParam.primitiveParam.indexCount; - const indices = module.HEAPU16.subarray(indexPtr, indexPtr + indexCount); - geometry.setIndex(new THREE.Uint16BufferAttribute(new Uint16Array(indices), 1)); - // Add attribute data. - Object.entries(attributes).forEach(([typeStr, buffer]) => { - const type = parseInt(typeStr); - if (buffer.size === 0 && type !== FFLAttributeBufferType.POSITION) { - return; - } - switch (type) { - case FFLAttributeBufferType.POSITION: { - // Float3, last 4 bytes unused (stride = 16) - const ptr = buffer.ptr / 4; - const data = module.HEAPF32.subarray(ptr, ptr + (vertexCount * 4)); - const interleavedBuffer = new THREE.InterleavedBuffer(data, 4); - // Only works on Three.js r109 and above (previously used addAttribute which can be remapped) - geometry.setAttribute('position', new THREE.InterleavedBufferAttribute(interleavedBuffer, 3, 0)); - break; - } - case FFLAttributeBufferType.NORMAL: { - // Either int8 or 10_10_10_2 - // const data = module.HEAP32.subarray(buffer.ptr / 4, buffer.ptr / 4 + vertexCount); - // const buf = gl.createBuffer(); - // gl.bindBuffer(gl.ARRAY_BUFFER, buf); - // gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); - // // Bind vertex type GL_INT_2_10_10_10_REV/ / 0x8D9F. - // geometry.setAttribute('normal', new THREE.GLBufferAttribute(buf, 0x8D9F, 4, 4)); - const data = module.HEAP8.subarray(buffer.ptr, buffer.ptr + buffer.size); - geometry.setAttribute('normal', new THREE.Int8BufferAttribute(data, buffer.stride, true)); - break; - } - case FFLAttributeBufferType.TANGENT: { - // Int8 - const data = module.HEAP8.subarray(buffer.ptr, buffer.ptr + buffer.size); - geometry.setAttribute('tangent', new THREE.Int8BufferAttribute(data, buffer.stride, true)); - break; - } - case FFLAttributeBufferType.TEXCOORD: { - // Float2 - const ptr = buffer.ptr / 4; - const data = module.HEAPF32.subarray(ptr, ptr + (vertexCount * 2)); - geometry.setAttribute('uv', new THREE.Float32BufferAttribute(data, buffer.stride / 4)); - break; - } - case FFLAttributeBufferType.COLOR: { - // Uint8 - - // Use default value if it does not exist. - // NOTE: Does not handle values for u_color other - // than the default 0/0/0/1 (custom u_parameter_mode) - if (buffer.stride === 0) { - break; - } - // Use "_color" because NOTE this is what the FFL-Testing exports and existing shaders do - const data = module.HEAPU8.subarray(buffer.ptr, buffer.ptr + buffer.size); - geometry.setAttribute('_color', new THREE.Uint8BufferAttribute(data, buffer.stride, true)); - break; - } - } - }); - return geometry; -} - -/** - * @private - * Retrieves a texture from ModulateParam. - * Does not assign texture for faceline or mask types. - * - * @param {FFLModulateParam} modulateParam - drawParam.modulateParam. - * @param {TextureManager} [textureManager=global.FFLTextures] - The TextureManager instance for which to look for the texture referenced. - * @returns {THREE.Texture|null} The texture if found. - * @throws {Error} Throws if pTexture2D refers to a texture that was not found in the TextureManager. - */ -function _getTextureFromModulateParam(modulateParam, textureManager = global.FFLTextures) { - // Only assign texture if pTexture2D is not null. - if (!modulateParam.pTexture2D || - // Ignore faceline and mask. - modulateParam.type === FFLModulateType.SHAPE_FACELINE || - modulateParam.type === FFLModulateType.SHAPE_MASK) { - return null; // No texture to bind. - } - const texturePtr = modulateParam.pTexture2D; - const texture = textureManager.get(texturePtr); - if (!texture) { - throw new Error(`_getTextureFromModulateParam: Texture not found for ${texturePtr}.`); - } - // Selective apply mirrored repeat. - const applyMirrorTypes = [FFLModulateType.SHAPE_FACELINE, FFLModulateType.SHAPE_CAP, FFLModulateType.SHAPE_GLASS]; - // ^^ Faceline, cap, and glass. NOTE that faceline texture won't go through here - if (applyMirrorTypes.includes(modulateParam.type)) { - texture.wrapS = THREE.MirroredRepeatWrapping; - texture.wrapT = THREE.MirroredRepeatWrapping; - texture.needsUpdate = true; - } - return texture; -} - -/** - * @private - * Returns an object of material parameters based on ModulateParam. - * - * @param {FFLModulateParam} modulateParam - drawParam.modulateParam - * @param {Module} module - The Emscripten module for accessing color pointers via heap. - * @returns {Object} Parameters for material creation. - */ -function _applyModulateParam(modulateParam, module) { - // Default modulate color is a Vector4; if provided, extract it. - let modulateColor = new THREE.Vector4(0, 0, 0, 0); - if (modulateParam.pColorR !== 0) { - const colorPtr = modulateParam.pColorR / 4; - const colorData = module.HEAPF32.subarray(colorPtr, colorPtr + 4); - modulateColor = new THREE.Vector4(colorData[0], colorData[1], colorData[2], colorData[3]); - } - // If both pColorG and pColorB are provided, combine them into an array. - if (modulateParam.pColorG !== 0 && modulateParam.pColorB !== 0) { - modulateColor = [ - _getVector4FromFFLColorPtr(modulateParam.pColorR, module), - _getVector4FromFFLColorPtr(modulateParam.pColorG, module), - _getVector4FromFFLColorPtr(modulateParam.pColorB, module) - ]; - } - // Determine whether to enable lighting. - const lightEnable = !(modulateParam.mode !== FFLModulateMode.CONSTANT && - modulateParam.type >= FFLModulateType.SHAPE_MAX); - - // Not applying map here. - return { - modulateMode: modulateParam.mode, - modulateType: modulateParam.type, - modulateColor: modulateColor, - lightEnable: lightEnable - }; -} - -/** - * Converts a pointer to FFLColor into a THREE.Vector4. - * - * @param {number} colorPtr - The pointer to the color. - * @param {Module} module - The Emscripten module. - * @returns {THREE.Vector4} - */ -function _getVector4FromFFLColorPtr(colorPtr, module) { - if (!colorPtr) { - console.error('getVector4FromFFLColorPtr: Received null pointer'); - return new THREE.Vector4(0, 0, 0, 0); - } - const colorData = module.HEAPF32.subarray(colorPtr / 4, colorPtr / 4 + 4); - return new THREE.Vector4(colorData[0], colorData[1], colorData[2], colorData[3]); -} - -// // --------------------------------------------------------------------- -// // Debug Globals Do Not Use Please -// // --------------------------------------------------------------------- - -/** - * @global - * Flag that does NOT clean up CharModels at all for debugging ONLY. - * @todo: TODO: eslint keeps making this const - */ -let _noCharModelCleanupDebug = false; -// Commented out as it's not being used and it breaks Web Worker compatibility. -// /** @global */ -// let _displayRenderTexturesElement = document.getElementById('ffl-js-display-render-textures'); -// if (_displayRenderTexturesElement) { -// console.warn('displaying faceline and mask textures to texture-display element, remove it when you\'re done testing'); -// } - -// // --------------------------------------------------------------------- -// // CharModel Render Textures -// // --------------------------------------------------------------------- - -// ---------------- initCharModelTextures(charModel, renderer) ---------------- -/** - * Initializes textures (faceline and mask) for a CharModel. - * Calls private functions to draw faceline and mask textures. - * At the end, calls setExpression to update the mask texture. - * - * @param {CharModel} charModel - The CharModel instance. - * @param {THREE.Renderer} renderer - The Three.js renderer. - * @todo Should this just be called in createCharModel() or something? But it's the only function requiring renderer. Maybe if you pass in renderer to that? - */ -export function initCharModelTextures(charModel, renderer) { - const module = charModel._module; - const textureTempObject = charModel._getTextureTempObject(); - // Draw faceline texture if applicable. - _drawFacelineTexture(charModel, textureTempObject, renderer, module); - // Draw mask textures for all expressions. - _drawMaskTextures(charModel, textureTempObject, renderer, module); - // Finalize CharModel, deleting and freeing it. - if (!_noCharModelCleanupDebug) { - charModel._finalizeCharModel(); - } - // Update the expression to refresh the mask texture. - charModel.setExpression(charModel.expression); -} - -/** - * @private - * @param {THREE.RenderTarget} renderTarget - * @param {THREE.WebGLRenderer} renderer - * @param {Boolean} [flipY=false] - */ -// ? - -// hook stuff -let _facelineTextureHook = () => null; -let _maskTextureHook = () => null; - -export function setFacelineTextureHook(fn) { - _facelineTextureHook =async (target, renderer) => { - const dataURL = await renderTargetToDataURL(target, renderer, true); - fn(dataURL); - _facelineTextureHook = () => null; - }; -} -export function setMaskTextureHook(fn) { - _maskTextureHook = async (target, renderer) => { - const dataURL = await renderTargetToDataURL(target, renderer, true); - fn(dataURL); - _maskTextureHook = () => null; - }; -} -// function _displayTextureDebug(target, renderer) { -// if (_displayRenderTexturesElement) { -// const dataURL = renderTargetToDataURL(target, renderer, true); -// appendImageFromDataURL(dataURL, _displayRenderTexturesElement); -// } -// } - -/** - * @private - * Draws and applies the faceline texture for the CharModel. - * - * @param {CharModel} charModel - The CharModel. - * @param {Object} textureTempObject - The temporary texture object. - * @param {THREE.Renderer} renderer - The renderer. - * @param {Module} module - The Emscripten module. - */ -function _drawFacelineTexture(charModel, textureTempObject, renderer, module) { - // Invalidate faceline texture before drawing (ensures correctness) - const facelineTempObjectPtr = charModel._getFacelineTempObjectPtr(); - module._FFLiInvalidateTempObjectFacelineTexture(facelineTempObjectPtr); - // Gather the drawParams that make up the faceline texture. - const drawParams = [ - textureTempObject.facelineTexture.drawParamFaceLine, - textureTempObject.facelineTexture.drawParamFaceBeard, - textureTempObject.facelineTexture.drawParamFaceMake - ].filter(dp => dp && dp.modulateParam.pTexture2D !== 0); - // Note that for faceline DrawParams to not be empty, - // it must have a texture. For other DrawParams to not - // be empty they simply need to have a non-zero index count. - if (drawParams.length === 0) { - // console.debug('_drawFacelineTexture: Skipping faceline texture.'); - return; - } - - // Get the faceline color from CharModel. - const bgColor = charModel.facelineColor; - // Create an offscreen scene. - const { scene: offscreenScene } = createSceneFromDrawParams(drawParams, bgColor, charModel._materialClass, charModel._module, renderer); - // Render scene to texture. - const width = charModel._getResolution() / 2; - const height = charModel._getResolution(); - // Configure the RenderTarget for no depth/stencil. - const options = { - depthBuffer: false, - stencilBuffer: false, - // Use mirrored repeat wrapping. - wrapS: THREE.MirroredRepeatWrapping, - wrapT: THREE.MirroredRepeatWrapping - }; - const target = createAndRenderToTarget(offscreenScene, - getIdentCamera(), renderer, width, height, options); - - // console.debug(`Creating target ${target.texture.id} for faceline`); - - // Optionally view the texture for debugging. - _facelineTextureHook(target, renderer); - - // Apply texture to CharModel. - _setFaceline(charModel, target); - // Delete temp faceline object to free resources. - if (!_noCharModelCleanupDebug) { - module._FFLiDeleteTempObjectFacelineTexture(facelineTempObjectPtr, charModel._ptr, charModel._model.charModelDesc.resourceType); - } - disposeMeshes(offscreenScene); // Dispose meshes in scene. -} - -/** - * @private - * Iterates through mask textures and draws each mask texture. - * - * @param {CharModel} charModel - The CharModel. - * @param {Object} textureTempObject - The temporary texture object. - * @param {THREE.Renderer} renderer - The renderer. - * @param {Module} module - The Emscripten module. - */ -function _drawMaskTextures(charModel, textureTempObject, renderer, module) { - const maskTempObjectPtr = charModel._getMaskTempObjectPtr(); - const expressionFlagPtr = charModel._ptr + FFLiCharModel.fields.charModelDesc.offset + - FFLCharModelDesc.fields.allExpressionFlag.offset; - - // Collect all scenes and only dispose them at the end. - /** @type Array */ - const scenes = []; - - // Iterate through pRenderTextures to find out which masks are needed. - for (let i = 0; i < charModel._model.maskTextures.pRenderTextures.length; i++) { - // pRenderTexture will be set to 1 if mask is meant to be drawn there. - if (charModel._model.maskTextures.pRenderTextures[i] === 0) { - continue; - } - const rawMaskDrawParamPtr = textureTempObject.maskTextures.pRawMaskDrawParam[i]; - const rawMaskDrawParam = FFLiRawMaskDrawParam.unpack(module.HEAPU8.subarray(rawMaskDrawParamPtr, rawMaskDrawParamPtr + FFLiRawMaskDrawParam.size)); - module._FFLiInvalidateRawMask(rawMaskDrawParamPtr); - - const { target, scene } = _drawMaskTexture(charModel, rawMaskDrawParam, renderer, module); - // console.debug(`Creating target ${target.texture.id} for mask ${i}`); - charModel._maskTargets[i] = target; - - scenes.push(scene); - } - - // Some texures are shared which is why this - // needs to be done given that disposeMeshes - // unconditionally deletes textures. - scenes.forEach((scene) => { - disposeMeshes(scene); - }); - - if (!_noCharModelCleanupDebug) { - module._FFLiDeleteTempObjectMaskTextures(maskTempObjectPtr, expressionFlagPtr, charModel._model.charModelDesc.resourceType); - module._FFLiDeleteTextureTempObject(charModel._ptr); - } -} - -/** - * @private - * Draws a single mask texture based on a RawMaskDrawParam. - * Note that the caller needs to dispose meshes within the returned scene. - * - * @param {CharModel} charModel - The CharModel. - * @param {Object} rawMaskParam - The RawMaskDrawParam. - * @param {THREE.Renderer} renderer - The renderer. - * @param {Module} module - The Emscripten module. - * @returns {{target: THREE.RenderTarget, scene: THREE.Scene}} The RenderTarget and scene of this mask texture. - */ -function _drawMaskTexture(charModel, rawMaskParam, renderer, module) { - const drawParams = [ - rawMaskParam.drawParamRawMaskPartsMustache[0], - rawMaskParam.drawParamRawMaskPartsMustache[1], - rawMaskParam.drawParamRawMaskPartsMouth, - rawMaskParam.drawParamRawMaskPartsEyebrow[0], - rawMaskParam.drawParamRawMaskPartsEyebrow[1], - rawMaskParam.drawParamRawMaskPartsEye[0], - rawMaskParam.drawParamRawMaskPartsEye[1], - rawMaskParam.drawParamRawMaskPartsMole - ].filter(dp => dp && dp.primitiveParam.indexCount !== 0); - if (drawParams.length === 0) { - console.error('No mask drawParams found'); - return null; - } - // Configure the RenderTarget for no depth/stencil. - const options = { - depthBuffer: false, - stencilBuffer: false - }; - // Create an offscreen scene with no background (for 2D mask rendering). - const { scene: offscreenScene } = createSceneFromDrawParams(drawParams, null, charModel._materialClass, module); - const width = charModel._getResolution(); - - const target = createAndRenderToTarget(offscreenScene, - getIdentCamera(), renderer, width, width, options); - - _maskTextureHook(target, renderer); - - return { target, scene: offscreenScene }; - // Caller needs to dispose meshes in scene. -} - -/** - * @private - * Sets the faceline texture of the given CharModel from the RenderTarget. - * @param {CharModel} charModel - The CharModel instance. - * @param {THREE.RenderTarget} target - RenderTarget for the faceline texture. - * @throws {Error} target must be a valid THREE.RenderTarget with "texture" property and CharModel must be initialized with OPA_FACELINE in meshes. - */ -function _setFaceline(charModel, target) { - if (!target || !target.texture) { - throw new Error('setFaceline: passed in RenderTarget is invalid'); - } - charModel._facelineTarget = target; // Store for later disposal. - // const mesh = charModel.meshes[FFLiShapeType.OPA_FACELINE]; - const mesh = charModel.meshes.getObjectById(charModel._facelineID); - if (!mesh) { - throw new Error('setFaceline: charModel.meshes[FFLiShapeType.OPA_FACELINE] does not exist'); - } - - // Update texture and material. - mesh.material.map = target.texture; - mesh.material.needsUpdate = true; -} - -// // --------------------------------------------------------------------- -// // Scene/Render Target Handling -// // --------------------------------------------------------------------- - -// TODO: private? -// -- createSceneFromDrawParams(drawParams, bgColor, materialClass, module) -- -/** - * Creates an THREE.Scene from an array of drawParams, converting each - * to a new mesh. Used for one-time rendering of faceline/mask 2D planes. - * - * @param {Array} drawParams - Array of FFLDrawParam. - * @param {THREE.Color|null} [bgColor=null] - Optional background color. - * @param {Function} materialClass - The material constructor. This shader must be able to handle the texture swizzling (RGB_LAYERED, LUMINANCE_ALPHA, etc.) for textures that create mask and faceline. - * @param {Module} module - The Emscripten module. - * @returns {{scene: THREE.Scene, meshes: Array}} - */ -function createSceneFromDrawParams(drawParams, bgColor = null, materialClass, module) { - const scene = new THREE.Scene(); - // For 2D plane rendering, set the background if provided. - scene.background = bgColor || null; - const meshes = []; - drawParams.forEach((dp) => { - const mesh = drawParamToMesh(dp, materialClass, module); - if (mesh) { - scene.add(mesh); - meshes.push(mesh); - } - }); - return { scene, meshes }; -} - -// TODO: private? -// -------------------------- getIdentCamera(flipY) -------------------------- -/** - * Returns an ortho camera that is effectively the same as - * if you used identity MVP matrix, for rendering 2D planes. - * - * @param {Boolean} [flipY=false] - Flip the Y axis. Default is oriented for OpenGL. - * @returns {THREE.OrthographicCamera} The orthographic camera. - */ -function getIdentCamera(flipY = false) { - // Create an orthographic camera with bounds [-1, 1] in x and y. - const camera = new THREE.OrthographicCamera(-1, 1, - // Use [1, -1] except when using flipY. - (flipY ? -1 : 1), (flipY ? 1 : -1), 0.1, 10); - camera.position.z = 1; - return camera; -} - -// - createAndRenderToTarget(scene, camera, renderer, width, height, targetOptions) - -/** - * Creates a Three.js RenderTarget, renders the scene with - * the given camera, and returns the render target. - * - * @param {THREE.Scene} scene - The scene to render. - * @param {THREE.Camera} camera - The camera to use. - * @param {THREE.WebGLRenderer} renderer - The renderer. - * @param {number} width - Desired width of the target. - * @param {number} height - Desired height of the target. - * @param {Object} [targetOptions={}] - Optional options for the render target. - * @returns {THREE.RenderTarget} The render target (which contains .texture). - */ -function createAndRenderToTarget(scene, camera, renderer, width, height, targetOptions = {}) { - // Set default options for the RenderTarget. - const options = { - minFilter: THREE.LinearFilter, - magFilter: THREE.LinearFilter, - ...targetOptions - }; - const renderTarget = new THREE.WebGLRenderTarget(width, height, options); - // Get previous render target to switch back to. - const prevTarget = renderer.getRenderTarget(); - // Only works on Three.js r102 and above. - renderer.setRenderTarget(renderTarget); // Set new target. - renderer.render(scene, camera); // Render. - renderer.setRenderTarget(prevTarget); // Set previous target. - return renderTarget; // This needs to be disposed when done. -} - -// -------------------------- disposeMeshes(target) -------------------------- -/** - * Disposes meshes in a scene and removes them or from an array of meshes. - * - * @param {THREE.Scene|THREE.Group|Array} target - The scene or array of meshes to dispose meshes from. - * @param {THREE.Scene} [scene] - The scene to remove the meshes from, if provided. - * @todo TODO: Rename to disposeGroup/Scene or something - */ -function disposeMeshes(group, scene) { - // Taken from: https://github.com/igvteam/spacewalk/blob/21c0a9da27f121a54e0cf6c0d4a23a9cf80e6623/js/utils/utils.js#L135C10-L135C29 - - // Traverse all children of the scene/group/THREE.Object3D. - group.traverse((child) => { - if (!child.isMesh) { - // Only dispose of meshes. - return; - } - // Dispose geometry, material, and texture. - if (child.geometry) { - child.geometry.dispose(); - } - - if (child.material) { - // Dispose texture in material. - if (child.material.map) { - // console.debug('Disposing texture ', child.material.map.id); - // If this was created by TextureManager - // then it overrides dispose() to also - // remove itself from the TextureManager map. - child.material.map.dispose(); - // Dispose texture and set to null. - // child.material.map.source = null; - // child.material.map.mipmaps = null; - } - child.material.dispose(); // Dispose material itself. - } - }); - - // If this is a scene, remove this group/Object3D from it. - if (scene && scene instanceof THREE.Scene) { - scene.remove(group); - } - - // Set group and its children to null to break references. - group.children = []; -} - -// // --------------------------------------------------------------------- -// // Export Scene/Texture To Image -// // --------------------------------------------------------------------- - -// ----------- renderTargetToDataURL(renderTarget, renderer, flipY) ----------- -/** - * Gets a data URL for a render target's texture using the same renderer. - * - * @param {THREE.RenderTarget} renderTarget - The render target. - * @param {THREE.WebGLRenderer} renderer - The renderer (MUST be the same renderer used for the target). - * @param {Boolean} [flipY=false] - Flip the Y axis. Default is oriented for OpenGL. - * @returns {string} The data URL representing the RenderTarget's texture contents. - */ -function renderTargetToDataURL(renderTarget, renderer, flipY = false) { - return new Promise((resolve) => { - - - // Create a new scene using a full-screen quad. - const scene = new THREE.Scene(); - scene.background = null; - // Assign a transparent, textured, and double-sided material. - const material = new THREE.MeshBasicMaterial({ - side: THREE.DoubleSide, - map: renderTarget.texture, - transparent: true - }); - const plane = new THREE.PlaneGeometry(2, 2); // Full-screen quad - const mesh = new THREE.Mesh(plane, material); - scene.add(mesh); - - // Use an orthographic camera that fits the full screen. - const camera = getIdentCamera(flipY); - // Get previous render target, color space, and size. - const prevTarget = renderer.getRenderTarget(); - const prevColorSpace = renderer.outputColorSpace; - const size = new THREE.Vector2(); - renderer.getSize(size); - - // Render to the main canvas to extract pixels. - renderer.setRenderTarget(null); // Switch render target. - // Use working color space. - renderer.outputColorSpace = THREE.ColorManagement ? THREE.ColorManagement.workingColorSpace : null; - renderer.setSize(renderTarget.width, renderTarget.height, false); - renderer.render(scene, camera); - - function cleanup() { - // Cleanup. - material.dispose(); - plane.dispose(); - scene.remove(mesh); - - // Restore previous size, color space, and target. - renderer.outputColorSpace = prevColorSpace; - renderer.setSize(size.x, size.y, false); - renderer.setRenderTarget(prevTarget); - } - - // Convert the renderer's canvas to an image. - if (typeof window === 'undefined') { - // assume this is a Web Worker, so it's offscreen canvas. an alt method is used - // using file reader was kind of dumb so i just create a blob URL in the main worker.ts file - renderer.domElement.convertToBlob({ type: "image/png" }).then(blob => { - resolve({type:"blob", result:blob}); - cleanup(); - }); - } else { - const result = renderer.domElement.toDataURL('image/png'); - // resolve(result); - resolve({type:"dataURL", result}); - cleanup(); - } -}); -} - -// ---------------- appendImageFromDataURL(dataURL, container) ---------------- -/** - * Appends an image (from a data URL) to a DOM element. - * - * @param {string} dataURL - The image data URL. - * @param {HTMLElement} [container=document.body] - The container element. - */ -function appendImageFromDataURL(dataURL, container) { - if (!container) { - console.warn('appendImageFromDataUrl: you did not specify "container" so we will use document.body, don\'t be surprised if your image ends up in brazil'); - container = document.body; - } - const img = new Image(); - img.src = dataURL; - container.appendChild(img); -} - -// // --------------------------------------------------------------------- -// // CharModel Icon Creation -// // --------------------------------------------------------------------- - -/** - * @enum {number} - */ -export const ViewType = { - Face: 0, // Typical icon body view. - MakeIcon: 1, // FFLMakeIcon matrix - IconFovy45: 2, // Custom - AllBody: 3, // Custom -}; - -// TODO: private? -// -------------- getCameraForViewType(viewType, width, height) -------------- -/** - * @param {ViewType} viewType - * @param {number} [width=1] - Width of the view. - * @param {number} [height=1] - Height of the view. - * @returns {THREE.PerspectiveCamera} The camera representing the view type specified. - * @throws {Error} - */ -function getCameraForViewType(viewType, width = 1, height = 1) { - const aspect = width / height; - switch (viewType) { - case ViewType.Face: { - // FFL-Testing equivalent: - const fovy = 15; // Math.atan2(43.2 / aspect, 500) / 0.5; - const camera = new THREE.PerspectiveCamera(fovy, aspect, 0.1, 1000); - camera.position.set(0, 34.5, 380);//411.181793); - camera.lookAt(0, 34.3, 0.0); - // pCamera->at() = { 0.0f, 34.3f, 0.0f }; - - return camera; - } - case ViewType.MakeIcon: { - // FFL-Testing equivalent: - const fovy = 10; // Math.atan2(43.2 / aspect, 500) / 0.5; - const camera = new THREE.PerspectiveCamera(fovy, aspect, 500, 1000); - camera.position.set(0, 34.5, 600); - // pCamera->pos() = { 0.0f, 34.5f, 600.0f }; - camera.lookAt(0, 34.5, 0.0); - // pCamera->at() = { 0.0f, 34.5f, 0.0f }; - - return camera; - } - case ViewType.IconFovy45: { - const camera = new THREE.PerspectiveCamera(45, aspect, 50, 1000); - camera.position.set(0, 34, 110); - camera.lookAt(0, 34, 0); - return camera; - } - case ViewType.AllBody: { - const fovy = 15; - const camera = new THREE.PerspectiveCamera(fovy, aspect, 50, 1500); - camera.position.set(0, 50, 900); - camera.lookAt(0, 105, 0); - return camera; - } - default: - throw new Error('getCameraForViewType: not implemented'); - } -} - -// ---- createCharModelIcon(charModel, renderer, viewType, width, height) ---- -/** - * Creates a small icon (data URL) representing the CharModel. - * Renders an offscreen scene with a copy of each mesh scaled down. - * - * @param {CharModel} charModel - The CharModel instance. - * @param {THREE.Renderer} renderer - The renderer. - * @param {ViewType} [viewType=ViewType.IconFovy45] viewType - * @param {number} [width=256] - Desired icon width. - * @param {number} [height=256] - Desired icon height. - * @returns {Promise} A data URL of the icon image. - */ -export function createCharModelIcon(charModel, renderer, viewType = ViewType.MakeIcon, width = 256, height = 256, useBody=false) { - return new Promise((resolve) => { - // Create an offscreen scene for the icon. - const iconScene = new THREE.Scene(); - iconScene.background = null; // Transparent background. - - const gender = charModel._getGender(); - - if (useBody){ - let bodyModel, bodyModelBody, bodyModelHands, bodyModelLegs; - - var bodyScale = charModel.getBodyScale(); - - switch (gender) { - case 0: { - bodyModel = bodyModels.Miitomo.m; - - bodyModelBody = bodyModel.getObjectByName("body_m"); - bodyModelHands = bodyModel.getObjectByName("hands_m"); - bodyModelLegs = bodyModel.getObjectByName("legs_m"); - break; - } - case 1: { - bodyModel = bodyModels.Miitomo.f; - - bodyModelBody = bodyModel.getObjectByName("body_f"); - bodyModelHands = bodyModel.getObjectByName("hands_f"); - bodyModelLegs = bodyModel.getObjectByName("legs_f"); - break; - } - } - - bodyModel.scale.set(1, bodyScale.y*10,1); - - var box = new THREE.Box3().setFromObject(bodyModel); - console.log("pos y:", box.max.y); - - bodyModel.position.set(0, -box.max.y, 0); - iconScene.add(bodyModel); - - var favoriteColor = charModel._getFavoriteColor(true); - - bodyModelBody.material = new LUTShaderMaterial({ - modulateType: cMaterialName.FFL_MODULATE_TYPE_SHAPE_BODY, - modulateMode: 0, - modulateColor: new THREE.Vector4( - favoriteColor.r, - favoriteColor.g, - favoriteColor.b, - 1 - ) - }); - - bodyModelLegs.material = new LUTShaderMaterial({ - modulateType: cMaterialName.FFL_MODULATE_TYPE_SHAPE_PANTS, - modulateMode: 0, - modulateColor: new THREE.Vector4( - 0.3, - 0.3, - 0.3, - 1 - ) - }); - } - - - // Add meshes from the CharModel. - iconScene.add(charModel.meshes.clone()); - // If the meshes aren't cloned then they disappear from the - // primary scene, however geometry/material etc are same - - // Get camera based on viewType parameter. - const iconCamera = getCameraForViewType(viewType); - - const target = createAndRenderToTarget(iconScene, - iconCamera, renderer, width, height); - - const dataURL = renderTargetToDataURL(target, renderer); - target.dispose(); // Dispose RenderTarget before returning. - resolve(dataURL); - // Caller needs to dispose CharModel. -}) -} - -// // --------------------------------------------------------------------- -// // StudioCharInfo Definition, Conversion -// // --------------------------------------------------------------------- - -/** - * @typedef {Object} StudioCharInfo - * @property {number} beardColor - * @property {number} beardType - * @property {number} build - * @property {number} eyeAspect - * @property {number} eyeColor - * @property {number} eyeRotate - * @property {number} eyeScale - * @property {number} eyeType - * @property {number} eyeX - * @property {number} eyeY - * @property {number} eyebrowAspect - * @property {number} eyebrowColor - * @property {number} eyebrowRotate - * @property {number} eyebrowScale - * @property {number} eyebrowType - * @property {number} eyebrowX - * @property {number} eyebrowY - * @property {number} facelineColor - * @property {number} facelineMake - * @property {number} facelineType - * @property {number} facelineWrinkle - * @property {number} favoriteColor - * @property {number} gender - * @property {number} glassColor - * @property {number} glassScale - * @property {number} glassType - * @property {number} glassY - * @property {number} hairColor - * @property {number} hairFlip - * @property {number} hairType - * @property {number} height - * @property {number} moleScale - * @property {number} moleType - * @property {number} moleX - * @property {number} moleY - * @property {number} mouthAspect - * @property {number} mouthColor - * @property {number} mouthScale - * @property {number} mouthType - * @property {number} mouthY - * @property {number} mustacheScale - * @property {number} mustacheType - * @property {number} mustacheY - * @property {number} noseScale - * @property {number} noseType - * @property {number} noseY - */ - -/** - * Structure representing data from the studio.mii.nintendo.com site and API. - * - * @type {StructInstance} - */ -export const StudioCharInfo = _.struct([ - // Fields are named according to nn::mii::CharInfo. - _.uint8('beardColor'), - _.uint8('beardType'), - _.uint8('build'), - _.uint8('eyeAspect'), - _.uint8('eyeColor'), - _.uint8('eyeRotate'), - _.uint8('eyeScale'), - _.uint8('eyeType'), - _.uint8('eyeX'), - _.uint8('eyeY'), - _.uint8('eyebrowAspect'), - _.uint8('eyebrowColor'), - _.uint8('eyebrowRotate'), - _.uint8('eyebrowScale'), - _.uint8('eyebrowType'), - _.uint8('eyebrowX'), - _.uint8('eyebrowY'), - _.uint8('facelineColor'), - _.uint8('facelineMake'), - _.uint8('facelineType'), - _.uint8('facelineWrinkle'), - _.uint8('favoriteColor'), - _.uint8('gender'), - _.uint8('glassColor'), - _.uint8('glassScale'), - _.uint8('glassType'), - _.uint8('glassY'), - _.uint8('hairColor'), - _.uint8('hairFlip'), - _.uint8('hairType'), - _.uint8('height'), - _.uint8('moleScale'), - _.uint8('moleType'), - _.uint8('moleX'), - _.uint8('moleY'), - _.uint8('mouthAspect'), - _.uint8('mouthColor'), - _.uint8('mouthScale'), - _.uint8('mouthType'), - _.uint8('mouthY'), - _.uint8('mustacheScale'), - _.uint8('mustacheType'), - _.uint8('mustacheY'), - _.uint8('noseScale'), - _.uint8('noseType'), - _.uint8('noseY') -]); - -// ----------------- convertStudioCharInfoToFFLiCharInfo(src) ----------------- -/** - * Creates an FFLiCharInfo object from StudioCharInfo. - * - * @param {StudioCharInfo} src - The StudioCharInfo instance. - * @returns {FFLiCharInfo} The FFLiCharInfo output. - */ -export function convertStudioCharInfoToFFLiCharInfo(src) { - return { - miiVersion: 0, - faceline: { - type: src.facelineType, - color: src.facelineColor, - texture: src.facelineWrinkle, - make: src.facelineMake - }, - hair: { - type: src.hairType, - color: commonColorMask(src.hairColor), - flip: src.hairFlip - }, - eye: { - type: src.eyeType, - color: commonColorMask(src.eyeColor), - scale: src.eyeScale, - aspect: src.eyeAspect, - rotate: src.eyeRotate, - x: src.eyeX, - y: src.eyeY - }, - eyebrow: { - type: src.eyebrowType, - color: commonColorMask(src.eyebrowColor), - scale: src.eyebrowScale, - aspect: src.eyebrowAspect, - rotate: src.eyebrowRotate, - x: src.eyebrowX, - y: src.eyebrowY - }, - nose: { - type: src.noseType, - scale: src.noseScale, - y: src.noseY - }, - mouth: { - type: src.mouthType, - color: commonColorMask(src.mouthColor), - scale: src.mouthScale, - aspect: src.mouthAspect, - y: src.mouthY - }, - beard: { - mustache: src.mustacheType, - type: src.beardType, - color: commonColorMask(src.beardColor), - scale: src.mustacheScale, - y: src.mustacheY - }, - glass: { - type: src.glassType, - color: commonColorMask(src.glassColor), - scale: src.glassScale, - y: src.glassY - }, - mole: { - type: src.moleType, - scale: src.moleScale, - x: src.moleX, - y: src.moleY - }, - body: { - height: src.height, - build: src.build - }, - personal: { - name: '', - creator: '', - gender: src.gender, - birthMonth: 0, - birthDay: 0, - favoriteColor: src.favoriteColor, - favorite: 0, - copyable: 0, - ngWord: 0, - localonly: 0, - regionMove: 0, - fontRegion: 0, - roomIndex: 0, - positionInRoom: 0, - birthPlatform: 3 - }, - createID: { - data: new Array(10).fill(0) - }, - padding_0: 0, - authorType: 0, - authorID: new Array(8).fill(0) - }; -} - -// --------------------- studioURLObfuscationDecode(data) --------------------- -/** - * @param {Uint8Array} data - Obfuscated Studio URL data. - * @returns {Uint8Array} - Decoded Uint8Array representing CharInfoStudio. - */ -function studioURLObfuscationDecode(data) { - const decodedData = new Uint8Array(data); - const random = decodedData[0]; - let previous = random; - - for (let i = 1; i < 48; i++) { - const encodedByte = decodedData[i]; - const original = (encodedByte - 7 + 256) % 256; - decodedData[i - 1] = original ^ previous; - previous = encodedByte; - } - - return decodedData.slice(0, StudioCharInfo.size); // Clamp to StudioCharInfo.size -} - -// ----------------- convertFFLiCharInfoToStudioCharInfo(src) ----------------- -/** - * Creates a StudioCharInfo object from FFLiCharInfo. - * - * @param {FFLiCharInfo} src - The FFLiCharInfo instance. - * @returns {StudioCharInfo} The StudioCharInfo output. - * @todo TODO: Currently does NOT convert color indices - * to CommonColor indices (ToVer3... etc) - */ -function convertFFLiCharInfoToStudioCharInfo(src) { - return { - beardColor: commonColorUnmask(src.beard.color), - beardType: src.beard.type, - build: src.body.build, - eyeAspect: src.eye.aspect, - eyeColor: commonColorUnmask(src.eye.color), - eyeRotate: src.eye.rotate, - eyeScale: src.eye.scale, - eyeType: src.eye.type, - eyeX: src.eye.x, - eyeY: src.eye.y, - eyebrowAspect: src.eyebrow.aspect, - eyebrowColor: commonColorUnmask(src.eyebrow.color), - eyebrowRotate: src.eyebrow.rotate, - eyebrowScale: src.eyebrow.scale, - eyebrowType: src.eyebrow.type, - eyebrowX: src.eyebrow.x, - eyebrowY: src.eyebrow.y, - facelineColor: src.faceline.color, - facelineMake: src.faceline.make, - facelineType: src.faceline.type, - facelineWrinkle: src.faceline.texture, - favoriteColor: src.personal.favoriteColor, - gender: src.personal.gender, - glassColor: commonColorUnmask(src.glass.color), - glassScale: src.glass.scale, - glassType: src.glass.type, - glassY: src.glass.y, - hairColor: commonColorUnmask(src.hair.color), - hairFlip: src.hair.flip, - hairType: src.hair.type, - height: src.body.height, - moleScale: src.mole.scale, - moleType: src.mole.type, - moleX: src.mole.x, - moleY: src.mole.y, - mouthAspect: src.mouth.aspect, - mouthColor: commonColorUnmask(src.mouth.color), - mouthScale: src.mouth.scale, - mouthType: src.mouth.type, - mouthY: src.mouth.y, - mustacheScale: src.beard.scale, - mustacheType: src.beard.mustache, - mustacheY: src.beard.y, - noseScale: src.nose.scale, - noseType: src.nose.type, - noseY: src.nose.y - }; -} - -// // --------------------------------------------------------------------- -// // Generic Hex/Base64 Utilities -// // --------------------------------------------------------------------- - -// TODO: keep as => syntax? take safari 5.1-compatible versions? -/** - * Removes all spaces from a string. - * @param {string} str - The input string. - * @returns {string} The string without spaces. - */ -const stripSpaces = str => str.replace(/\s+/g, ''); - -/** - * Converts a hexadecimal string to a Uint8Array. - * @param {string} hex - The hexadecimal string. - * @returns {Uint8Array} The converted Uint8Array. - */ -const hexToUint8Array = hex => new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); - -/** - * Converts a Base64 or Base64-URL encoded string to a Uint8Array. - * @param {string} base64 - The Base64-encoded string. - * @returns {Uint8Array} The converted Uint8Array. - */ -function base64ToUint8Array(base64) { - // Replace URL-safe Base64 characters - const normalizedBase64 = base64.replace(/-/g, '+').replace(/_/g, '/'); - // Add padding if necessary - const paddedBase64 = normalizedBase64.padEnd( - normalizedBase64.length + (4 - (normalizedBase64.length % 4)) % 4, '=' - ); - return Uint8Array.from(atob(paddedBase64), c => c.charCodeAt(0)); -} - -/** - * Converts a Uint8Array to a Base64 string. - * @param {Uint8Array} data - The Uint8Array to convert. - * @returns {string} The Base64-encoded string. - */ -const uint8ArrayToBase64 = data => btoa(String.fromCharCode.apply(null, data)); - -/** - * Parses a string contaning either hex or Base64 representation - * of bytes into a Uint8Array, stripping spaces. - * - * @param {string} text - The input string, which can be either hex or Base64. - * @returns {Uint8Array} The parsed Uint8Array. - */ -export function parseHexOrB64ToUint8Array(text) { - let inputData; - // Decode it to a Uint8Array whether it's hex or Base64 - const textData = stripSpaces(text); - // Check if it's base 16 exclusively, otherwise assume Base64 - if (/^[0-9a-fA-F]+$/.test(textData)) { - inputData = hexToUint8Array(textData); - } else { - inputData = base64ToUint8Array(textData); - } - return inputData; -} +// @ts-check +'use strict'; +/*! + * Bindings for FFL, a Mii renderer, in JavaScript. + * https://github.com/ariankordi/FFL.js + * @author Arian Kordi + */ + +// ------------------ ESM imports, uncomment if you use ESM ------------------ +// Also see the bottom of the script for corresponding exports. +import * as THREE from 'three'; +// import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.167.0/+esm'; +import * as _Import from './struct-fu.js'; + +// Hack to get library globals recognized throughout the file (remove for ESM). +/** + * @typedef {import('./struct-fu')} _ + * @typedef {import('three')} THREE + */ +/* eslint-disable no-self-assign -- Get TypeScript to identify global imports. */ +globalThis._ = /** @type {_} */ (/** @type {*} */ (globalThis)._); +globalThis.THREE = /** @type {THREE} */ (/** @type {*} */ (globalThis).THREE); +// NOTeslint-disable-next-line @stylistic/max-statements-per-line -- Hack to use either UMD or browser ESM import. +let _ = globalThis._; _ = (!_) ? _Import : _; // Uncomment for ESM +/* eslint-enable no-self-assign -- Get TypeScript to identify global imports. */ +/* globals _ THREE -- Global dependencies. */ + +// // --------------------------------------------------------------------- +// // Emscripten Types +// // --------------------------------------------------------------------- +// TODO PATH: src/ModuleType.js + +/** + * Emscripten "Module" type. + * https://github.com/DefinitelyTyped/DefinitelyTyped/blob/c03bddd4d3c7774d00fa256a9e165d68c7534ccc/types/emscripten/index.d.ts#L26 + * @typedef {Object} Module + * @property {function(): void} onRuntimeInitialized + * @property {function(object): void} destroy + * @property {boolean|null} calledRun + * // USE_TYPED_ARRAYS == 2 + * @property {Int8Array} HEAP8 + * @property {Uint8Array} HEAPU8 + * @property {Uint16Array} HEAPU16 + * @property {Uint32Array} HEAPU32 + * @property {Float32Array} HEAPF32 + * Runtime methods: + * @property {function(number): number} _malloc + * @property {function(number): void} _free + * @property {function((...args: *[]) => *, string=): number} addFunction + * @property {function(number): void} removeFunction + * + * ------------------------------- FFL Bindings ------------------------------- + * @property {function(number, number, number, number): *} _FFLInitCharModelCPUStepWithCallback + * @property {function(number, number, number): *} _FFLInitCharModelCPUStep + * @property {function(number): *} _FFLDeleteCharModel + * @property {function(number): *} _FFLGetDrawParamOpaFaceline + * @property {function(number): *} _FFLGetDrawParamOpaBeard + * @property {function(number): *} _FFLGetDrawParamOpaNose + * @property {function(number): *} _FFLGetDrawParamOpaForehead + * @property {function(number): *} _FFLGetDrawParamOpaHair + * @property {function(number): *} _FFLGetDrawParamOpaCap + * @property {function(number): *} _FFLGetDrawParamXluMask + * @property {function(number): *} _FFLGetDrawParamXluNoseLine + * @property {function(number): *} _FFLGetDrawParamXluGlass + * @property {function(number, number): *} _FFLSetExpression + * @property {function(number): *} _FFLGetExpression + * @property {function(number, number): *} _FFLSetViewModelType + * @property {function(number, number): *} _FFLGetBoundingBox + * @property {function(number, number): *} _FFLIsAvailableExpression + * @property {function(number, number): *} _FFLSetCoordinate + * @property {function(number): *} _FFLSetScale + * @property {function(number, number, number, number): *} _FFLiGetRandomCharInfo + * @property {function(number, number): *} _FFLpGetStoreDataFromCharInfo + * @property {function(number, number): *} _FFLpGetCharInfoFromStoreData + * @property {function(number, number): *} _FFLpGetCharInfoFromMiiDataOfficialRFL + * @property {function(number, number, number, number, boolean): *} _FFLGetAdditionalInfo + * @property {function(number, number): *} _FFLInitRes + * @property {function(): *} _FFLInitResGPUStep + * @property {function(): *} _FFLExit + * @property {function(): *} _FFLIsAvailable + * @property {function(number, number): *} _FFLGetFavoriteColor + * @property {function(number): *} _FFLSetLinearGammaMode + * @property {function(number, number): *} _FFLGetFacelineColor + * @property {function(boolean): *} _FFLSetTextureFlipY + * @property {function(boolean): *} _FFLSetNormalIsSnorm8_8_8_8 + * @property {function(boolean): *} _FFLSetFrontCullForFlipX + * @property {function(number): *} _FFLSetTextureCallback + * @property {function(number): *} _FFLiDeleteTextureTempObject + * @property {function(number, number, number): *} _FFLiDeleteTempObjectMaskTextures + * @property {function(number, number, number): *} _FFLiDeleteTempObjectFacelineTexture + * @property {function(number): *} _FFLiiGetEyeRotateOffset + * @property {function(number): *} _FFLiiGetEyebrowRotateOffset + * @property {function(number): *} _FFLiInvalidateTempObjectFacelineTexture + * @property {function(number): *} _FFLiInvalidatePartsTextures + * @property {function(number): *} _FFLiInvalidateRawMask + * @property {function(number, boolean): *} _FFLiVerifyCharInfoWithReason + * @property {function(): void} _exit + */ + +// // --------------------------------------------------------------------- +// // Enum Definitions +// // --------------------------------------------------------------------- +// TODO PATH: src/Enums.js + +/** + * Uses FFL decomp enum rather than real FFL enum. + * Reference: https://github.com/aboood40091/ffl/blob/master/include/nn/ffl/FFLResult.h + * @enum {number} + */ +const FFLResult = { + OK: 0, + ERROR: 1, + HDB_EMPTY: 2, + FILE_INVALID: 3, + MANAGER_NOT_CONSTRUCT: 4, + FILE_LOAD_ERROR: 5, + // : 6, + FILE_SAVE_ERROR: 7, + // : 8, + RES_FS_ERROR: 9, + ODB_EMPTY: 10, + // : 11, + OUT_OF_MEMORY: 12, + // : 13, + // : 14, + // : 15, + // : 16, + UNKNOWN_17: 17, + FS_ERROR: 18, + FS_NOT_FOUND: 19, + MAX: 20 +}; + +/** @enum {number} */ +const FFLiShapeType = { + OPA_BEARD: 0, + OPA_FACELINE: 1, + OPA_HAIR_NORMAL: 2, + OPA_FOREHEAD_NORMAL: 3, + XLU_MASK: 4, + XLU_NOSELINE: 5, + OPA_NOSE: 6, + OPA_HAT_NORMAL: 7, + XLU_GLASS: 8, + OPA_HAIR_CAP: 9, + OPA_FOREHEAD_CAP: 10, + OPA_HAT_CAP: 11, + MAX: 12 +}; + +/** @enum {number} */ +const FFLAttributeBufferType = { + POSITION: 0, + TEXCOORD: 1, + NORMAL: 2, + TANGENT: 3, + COLOR: 4, + MAX: 5 +}; + +/** @enum {number} */ +const FFLCullMode = { + NONE: 0, + BACK: 1, + FRONT: 2, + MAX: 3 +}; + +/** @enum {number} */ +const FFLModulateMode = { + /** No Texture, Has Color (R) */ + CONSTANT: 0, + /** Has Texture, No Color */ + TEXTURE_DIRECT: 1, + /** Has Texture, Has Color (R + G + B) */ + RGB_LAYERED: 2, + /** Has Texture, Has Color (R) */ + ALPHA: 3, + /** Has Texture, Has Color (R) */ + LUMINANCE_ALPHA: 4, + /** Has Texture, Has Color (R) */ + ALPHA_OPA: 5 +}; + +/** @enum {number} */ +const FFLModulateType = { + SHAPE_FACELINE: 0, + SHAPE_BEARD: 1, + SHAPE_NOSE: 2, + SHAPE_FOREHEAD: 3, + SHAPE_HAIR: 4, + SHAPE_CAP: 5, + SHAPE_MASK: 6, + SHAPE_NOSELINE: 7, + SHAPE_GLASS: 8, + MUSTACHE: 9, + MOUTH: 10, + EYEBROW: 11, + EYE: 12, + MOLE: 13, + FACE_MAKE: 14, + FACE_LINE: 15, + FACE_BEARD: 16, + FILL: 17, + SHAPE_MAX: 9 +}; + +/** @enum {number} */ +const FFLResourceType = { + MIDDLE: 0, + HIGH: 1, + MAX: 2 +}; + +/** + * Reference: https://github.com/ariankordi/ffl/blob/nsmbu-win-port-linux64/include/nn/ffl/FFLExpression.h + * @enum {number} + */ +const FFLExpression = { + NORMAL: 0, + SMILE: 1, + ANGER: 2, + /** Primary name for expression 3. */ + SORROW: 3, + PUZZLED: 3, + /** Primary name for expression 4. */ + SURPRISE: 4, + SURPRISED: 4, + BLINK: 5, + OPEN_MOUTH: 6, + /** Primary name for expression 7. */ + SMILE_OPEN_MOUTH: 7, + HAPPY: 7, + ANGER_OPEN_MOUTH: 8, + SORROW_OPEN_MOUTH: 9, + SURPRISE_OPEN_MOUTH: 10, + BLINK_OPEN_MOUTH: 11, + WINK_LEFT: 12, + WINK_RIGHT: 13, + WINK_LEFT_OPEN_MOUTH: 14, + WINK_RIGHT_OPEN_MOUTH: 15, + /** Primary name for expression 16. */ + LIKE_WINK_LEFT: 16, + LIKE: 16, + LIKE_WINK_RIGHT: 17, + FRUSTRATED: 18, + + // Additional expressions from AFL. + // Enum names are completely made up. + BORED: 19, + BORED_OPEN_MOUTH: 20, + SIGH_MOUTH_STRAIGHT: 21, + SIGH: 22, + DISGUSTED_MOUTH_STRAIGHT: 23, + DISGUSTED: 24, + LOVE: 25, + LOVE_OPEN_MOUTH: 26, + DETERMINED_MOUTH_STRAIGHT: 27, + DETERMINED: 28, + CRY_MOUTH_STRAIGHT: 29, + CRY: 30, + BIG_SMILE_MOUTH_STRAIGHT: 31, + BIG_SMILE: 32, + CHEEKY: 33, + CHEEKY_DUPLICATE: 34, + JOJO_EYES_FUNNY_MOUTH: 35, + JOJO_EYES_FUNNY_MOUTH_OPEN: 36, + SMUG: 37, + SMUG_OPEN_MOUTH: 38, + RESOLVE: 39, + RESOLVE_OPEN_MOUTH: 40, + UNBELIEVABLE: 41, + UNBELIEVABLE_DUPLICATE: 42, + CUNNING: 43, + CUNNING_DUPLICATE: 44, + RASPBERRY: 45, + RASPBERRY_DUPLICATE: 46, + INNOCENT: 47, + INNOCENT_DUPLICATE: 48, + CAT: 49, + CAT_DUPLICATE: 50, + DOG: 51, + DOG_DUPLICATE: 52, + TASTY: 53, + TASTY_DUPLICATE: 54, + MONEY_MOUTH_STRAIGHT: 55, + MONEY: 56, + SPIRAL_MOUTH_STRAIGHT: 57, + CONFUSED: 58, + CHEERFUL_MOUTH_STRAIGHT: 59, + CHEERFUL: 60, + BLANK_61: 61, + BLANK_62: 62, + GRUMBLE_MOUTH_STRAIGHT: 63, + GRUMBLE: 64, + MOVED_MOUTH_STRAIGHT: 65, + MOVED: 66, + SINGING_MOUTH_SMALL: 67, + SINGING: 68, + STUNNED: 69, + + MAX: 70 +}; + +/** + * Model flags modify how the head model is created. These are + * used in the `modelFlag` property of {@link FFLCharModelDesc}. + * @enum {number} + */ +const FFLModelFlag = { + /** Default model setting. */ + NORMAL: 1 << 0, + /** Uses a variant of hair designed for hats. */ + HAT: 1 << 1, + /** Discards hair from the model, used for helmets and similar headwear. */ + FACE_ONLY: 1 << 2, + /** Limits Z depth on the nose, useful for helmets and similar headwear. */ + FLATTEN_NOSE: 1 << 3, + /** Enables the model's expression flag to use expressions beyond 32. */ + NEW_EXPRESSIONS: 1 << 4, + /** + * This flag only generates new textures when initializing a CharModel + * but does not initialize shapes. + * **Note:** This means you cannot use DrawOpa/Xlu when this is set. + */ + NEW_MASK_ONLY: 1 << 5 +}; + +// // --------------------------------------------------------------------- +// // Struct Definitions (struct-fu) +// // --------------------------------------------------------------------- +// TODO PATH: src/Structs.js +// Mostly leading up to FFLDrawParam. + +/** Mirror for {@link _.uint32le} to indicate a pointer. */ +const _uintptr = _.uint32le; + +/** + * @typedef {Object} FFLAttributeBuffer + * @property {number} size + * @property {number} stride + * @property {number} ptr + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLAttributeBuffer = _.struct([ + _.uint32le('size'), + _.uint32le('stride'), + _uintptr('ptr') +]); + +/** + * @typedef {Object} FFLAttributeBufferParam + * @property {Array} attributeBuffers + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLAttributeBufferParam = _.struct([ + _.struct('attributeBuffers', [FFLAttributeBuffer], 5) +]); + +/** + * @typedef {Object} FFLPrimitiveParam + * @property {number} primitiveType + * @property {number} indexCount + * @property {number} pAdjustMatrix + * @property {number} pIndexBuffer + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLPrimitiveParam = _.struct([ + _.uint32le('primitiveType'), + _.uint32le('indexCount'), + _uintptr('pAdjustMatrix'), // TODO: Not uintptr in 64-bit. + _uintptr('pIndexBuffer') +]); + +/** + * @typedef {Object} FFLColor + * @property {number} r + * @property {number} g + * @property {number} b + * @property {number} a + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLColor = _.struct([ + _.float32le('r'), + _.float32le('g'), + _.float32le('b'), + _.float32le('a') +]); + +/** + * @typedef {Object} FFLVec3 + * @property {number} x + * @property {number} y + * @property {number} z + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLVec3 = _.struct([ + _.float32le('x'), + _.float32le('y'), + _.float32le('z') +]); + +/** + * @typedef {Object} FFLModulateParam + * @property {FFLModulateMode} mode + * @property {FFLModulateType} type + * @property {number} pColorR - Pointer to FFLColor + * @property {number} pColorG - Pointer to FFLColor + * @property {number} pColorB - Pointer to FFLColor + * @property {number} pTexture2D + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLModulateParam = _.struct([ + _.uint32le('mode'), // enum FFLModulateMode + _.uint32le('type'), // enum FFLModulateType + _uintptr('pColorR'), + _uintptr('pColorG'), + _uintptr('pColorB'), + _uintptr('pTexture2D') +]); + +/** + * @typedef {Object} FFLDrawParam + * @property {FFLAttributeBufferParam} attributeBufferParam + * @property {FFLModulateParam} modulateParam + * @property {FFLCullMode} cullMode + * @property {FFLPrimitiveParam} primitiveParam + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLDrawParam = _.struct([ + _.struct('attributeBufferParam', [FFLAttributeBufferParam]), + _.struct('modulateParam', [FFLModulateParam]), + _.uint32le('cullMode'), + _.struct('primitiveParam', [FFLPrimitiveParam]) +]); + +// ---------------------- Begin FFLiCharInfo Definition ---------------------- +// TODO PATH: src/StructFFLiCharModel.js + +/** + * @typedef {Object} FFLCreateID + * @property {Array} data + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLCreateID = _.struct([ + _.uint8('data', 10) +]); + +/** + * @typedef {Object} FFLiCharInfo_faceline + * @property {number} type + * @property {number} color + * @property {number} texture + * @property {number} make + */ +/** + * @typedef {Object} FFLiCharInfo_hair + * @property {number} type + * @property {number} color + * @property {number} flip + */ +/** + * @typedef {Object} FFLiCharInfo_eye + * @property {number} type + * @property {number} color + * @property {number} scale + * @property {number} aspect + * @property {number} rotate + * @property {number} x + * @property {number} y + */ +/** + * @typedef {Object} FFLiCharInfo_eyebrow + * @property {number} type + * @property {number} color + * @property {number} scale + * @property {number} aspect + * @property {number} rotate + * @property {number} x + * @property {number} y + */ +/** + * @typedef {Object} FFLiCharInfo_nose + * @property {number} type + * @property {number} scale + * @property {number} y + */ +/** + * @typedef {Object} FFLiCharInfo_mouth + * @property {number} type + * @property {number} color + * @property {number} scale + * @property {number} aspect + * @property {number} y + */ +/** + * @typedef {Object} FFLiCharInfo_beard + * @property {number} mustache + * @property {number} type + * @property {number} color + * @property {number} scale + * @property {number} y + */ +/** + * @typedef {Object} FFLiCharInfo_glass + * @property {number} type + * @property {number} color + * @property {number} scale + * @property {number} y + */ +/** + * @typedef {Object} FFLiCharInfo_mole + * @property {number} type + * @property {number} scale + * @property {number} x + * @property {number} y + */ +/** + * @typedef {Object} FFLiCharInfo_body + * @property {number} height + * @property {number} build + */ +/** + * @typedef {Object} FFLiCharInfo_personal + * @property {string} name + * @property {string} creator + * @property {number} gender + * @property {number} birthMonth + * @property {number} birthDay + * @property {number} favoriteColor + * @property {number} favorite + * @property {number} copyable + * @property {number} ngWord + * @property {number} localonly + * @property {number} regionMove + * @property {number} fontRegion + * @property {number} roomIndex + * @property {number} positionInRoom + * @property {number} birthPlatform + */ +/** + * @typedef {Object} FFLiCharInfo + * @property {number} miiVersion + * @property {FFLiCharInfo_faceline} faceline + * @property {FFLiCharInfo_hair} hair + * @property {FFLiCharInfo_eye} eye + * @property {FFLiCharInfo_eyebrow} eyebrow + * @property {FFLiCharInfo_nose} nose + * @property {FFLiCharInfo_mouth} mouth + * @property {FFLiCharInfo_beard} beard + * @property {FFLiCharInfo_glass} glass + * @property {FFLiCharInfo_mole} mole + * @property {FFLiCharInfo_body} body + * @property {FFLiCharInfo_personal} personal + * @property {FFLCreateID} createID + * @property {number} padding_0 + * @property {number} authorType + * @property {Array} authorID + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLiCharInfo = _.struct([ + _.int32le('miiVersion'), + _.struct('faceline', [_.int32le('type'), _.int32le('color'), + _.int32le('texture'), _.int32le('make')]), + _.struct('hair', [_.int32le('type'), _.int32le('color'), _.int32le('flip')]), + _.struct('eye', [_.int32le('type'), _.int32le('color'), _.int32le('scale'), + _.int32le('aspect'), _.int32le('rotate'), + _.int32le('x'), _.int32le('y')]), + _.struct('eyebrow', [_.int32le('type'), _.int32le('color'), + _.int32le('scale'), _.int32le('aspect'), + _.int32le('rotate'), _.int32le('x'), + _.int32le('y')]), + _.struct('nose', [_.int32le('type'), _.int32le('scale'), + _.int32le('y')]), + _.struct('mouth', [_.int32le('type'), _.int32le('color'), + _.int32le('scale'), _.int32le('aspect'), + _.int32le('y')]), + _.struct('beard', [_.int32le('mustache'), _.int32le('type'), + _.int32le('color'), _.int32le('scale'), + _.int32le('y')]), + _.struct('glass', [_.int32le('type'), _.int32le('color'), + _.int32le('scale'), _.int32le('y')]), + _.struct('mole', [_.int32le('type'), _.int32le('scale'), + _.int32le('x'), _.int32le('y')]), + _.struct('body', [_.int32le('height'), _.int32le('build')]), + _.struct('personal', [ + _.char16le('name', 22), + _.char16le('creator', 22), + _.int32le('gender'), + _.int32le('birthMonth'), + _.int32le('birthDay'), + _.int32le('favoriteColor'), + _.uint8('favorite'), + _.uint8('copyable'), + _.uint8('ngWord'), + _.uint8('localonly'), + _.int32le('regionMove'), + _.int32le('fontRegion'), + _.int32le('roomIndex'), + _.int32le('positionInRoom'), + _.int32le('birthPlatform') + ]), + _.struct('createID', [FFLCreateID]), + _.uint16le('padding_0'), + _.int32le('authorType'), + _.uint8('authorID', 8) // stub +]); + +/** + * Size of FFLStoreData, a structure not included currently. + * @public + */ +/** sizeof(FFLStoreData) */ +const FFLStoreData_size = 96; + +// ---------------------- Common Color Mask Definitions ---------------------- + +/** @package */ +const commonColorEnableMask = (1 << 31); + +/** + * Applies (unofficial) mask: FFLI_NN_MII_COMMON_COLOR_ENABLE_MASK + * to a common color index to indicate to FFL which color table it should use. + * @param {number} color - The color index to flag. + * @returns {number} The flagged color index to use in FFLiCharinfo. + */ +const commonColorMask = color => color | commonColorEnableMask; + +/** + * Removes (unofficial) mask: FFLI_NN_MII_COMMON_COLOR_ENABLE_MASK + * to a common color index to reveal the original common color index. + * @param {number} color - The flagged color index. + * @returns {number} The original color index before flagging. + */ +const commonColorUnmask = color => (color & ~commonColorEnableMask) === 0 +// Only unmask color if the mask is enabled. + ? color + : color & ~commonColorEnableMask; + +// --------------------- Begin FFLiCharModel Definitions --------------------- + +/** + * @typedef {Object} FFLAdditionalInfo + * @property {string} name + * @property {string} creator + * @property {FFLCreateID} createID + * @property {FFLColor} skinColor + * @property {number} flags + * @property {number} facelineType + * @property {number} hairType + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLAdditionalInfo = _.struct([ + _.char16le('name', 22), + _.char16le('creator', 22), + _.struct('createID', [FFLCreateID]), + _.byte('_padding0', 2), // alignment + _.struct('skinColor', [FFLColor]), + _.uint32le('flags'), + // _.ubitLE('hairFlip', 1), + // _.ubitLE('fontRegion', 2), + // _.ubitLE('ngWord', 1), + // _.ubitLE('build', 7), + // _.ubitLE('height', 7), + // _.ubitLE('favoriteColor', 4), + // _.ubitLE('birthDay', 5), + // _.ubitLE('birthMonth', 4), + // _.ubitLE('gender', 1), + _.uint8('facelineType'), + _.uint8('hairType'), + _.byte('_padding1', 2) // alignment +]); + +const FFLiRenderTexture = _.struct([ + // STUB: four pointers in one field + _uintptr('pTexture2DRenderBufferColorTargetDepthTarget', 4) +]); + +/** + * @typedef {Object} FFLiFacelineTextureTempObject + * @property {number} pTextureFaceLine + * @property {FFLDrawParam} drawParamFaceLine + * @property {number} pTextureFaceMake + * @property {FFLDrawParam} drawParamFaceMake + * @property {number} pTextureFaceBeard + * @property {FFLDrawParam} drawParamFaceBeard + * @property {Array} pRenderTextureCompressorParam + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLiFacelineTextureTempObject = _.struct([ + _uintptr('pTextureFaceLine'), + _.struct('drawParamFaceLine', [FFLDrawParam]), + _uintptr('pTextureFaceMake'), + _.struct('drawParamFaceMake', [FFLDrawParam]), + _uintptr('pTextureFaceBeard'), + _.struct('drawParamFaceBeard', [FFLDrawParam]), + _uintptr('pRenderTextureCompressorParam', 2) // stub +]); + +/** + * @typedef {Object} FFLiRawMaskDrawParam + * @property {Array} drawParamRawMaskPartsEye - 2 + * @property {Array} drawParamRawMaskPartsEyebrow - 2 + * @property {FFLDrawParam} drawParamRawMaskPartsMouth + * @property {Array} drawParamRawMaskPartsMustache - 2 + * @property {FFLDrawParam} drawParamRawMaskPartsMole + * @property {FFLDrawParam} drawParamRawMaskPartsFill + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLiRawMaskDrawParam = _.struct([ + _.struct('drawParamRawMaskPartsEye', [FFLDrawParam], 2), + _.struct('drawParamRawMaskPartsEyebrow', [FFLDrawParam], 2), + _.struct('drawParamRawMaskPartsMouth', [FFLDrawParam]), + _.struct('drawParamRawMaskPartsMustache', [FFLDrawParam], 2), + _.struct('drawParamRawMaskPartsMole', [FFLDrawParam]), + _.struct('drawParamRawMaskPartsFill', [FFLDrawParam]) +]); + +/** + * @typedef {Object} FFLiMaskTexturesTempObject + * @property {Array} partsTextures + * @property {Array} pRawMaskDrawParam + * @property {Uint8Array} _remaining + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLiMaskTexturesTempObject = _.struct([ + _.uint8('partsTextures', 0x154), + _uintptr('pRawMaskDrawParam', FFLExpression.MAX), + _.byte('_remaining', 0x388 - 620) // stub +]); + +/** + * @typedef {Object} FFLiTextureTempObject + * @property {FFLiMaskTexturesTempObject} maskTextures + * @property {FFLiFacelineTextureTempObject} facelineTexture + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLiTextureTempObject = _.struct([ + _.struct('maskTextures', [FFLiMaskTexturesTempObject]), + _.struct('facelineTexture', [FFLiFacelineTextureTempObject]) +]); + +/** + * @typedef {Object} FFLiMaskTextures + * @property {Array} pRenderTextures + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLiMaskTextures = _.struct([ + _uintptr('pRenderTextures', FFLExpression.MAX) +]); + +/** @package */ +const FFL_RESOLUTION_MASK = 0x3fffffff; + +/** + * @typedef {Object} FFLCharModelDesc + * @property {number} resolution - Texture resolution for faceline/mask. It's recommended to only use powers of two. + * @property {Uint32Array} allExpressionFlag - Expression flag, created by {@link makeExpressionFlag} + * @property {FFLModelFlag} modelFlag + * @property {FFLResourceType} resourceType + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLCharModelDesc = _.struct([ + _.uint32le('resolution'), + _.uint32le('allExpressionFlag', 3), + _.uint32le('modelFlag'), + _.uint32le('resourceType') +]); +/** + * Static default for FFLCharModelDesc. + * @type {FFLCharModelDesc} + * @public + */ +const FFLCharModelDescDefault = { + /** Typical default. */ + resolution: 512, + /** Normal expression. */ + allExpressionFlag: new Uint32Array([1, 0, 0]), + modelFlag: FFLModelFlag.NORMAL, + /** Default resource type. */ + resourceType: FFLResourceType.HIGH +}; + +/** + * @typedef {Object} FFLBoundingBox + * @property {FFLVec3} min + * @property {FFLVec3} max + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLBoundingBox = _.struct([ + _.struct('min', [FFLVec3]), + _.struct('max', [FFLVec3]) +]); + +/** + * @typedef {Object} FFLPartsTransform + * @property {FFLVec3} hatTranslate + * @property {FFLVec3} headFrontRotate + * @property {FFLVec3} headFrontTranslate + * @property {FFLVec3} headSideRotate + * @property {FFLVec3} headSideTranslate + * @property {FFLVec3} headTopRotate + * @property {FFLVec3} headTopTranslate + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLPartsTransform = _.struct([ + _.struct('hatTranslate', [FFLVec3]), + _.struct('headFrontRotate', [FFLVec3]), + _.struct('headFrontTranslate', [FFLVec3]), + _.struct('headSideRotate', [FFLVec3]), + _.struct('headSideTranslate', [FFLVec3]), + _.struct('headTopRotate', [FFLVec3]), + _.struct('headTopTranslate', [FFLVec3]) +]); +/** + * PartsTransform with THREE.Vector3 type. + * @typedef {Object} PartsTransform + * @property {import('three').Vector3} hatTranslate + * @property {import('three').Vector3} headFrontRotate + * @property {import('three').Vector3} headFrontTranslate + * @property {import('three').Vector3} headSideRotate + * @property {import('three').Vector3} headSideTranslate + * @property {import('three').Vector3} headTopRotate + * @property {import('three').Vector3} headTopTranslate + */ + +/** + * Internal representation within FFL for the created CharModel. + * @typedef {Object} FFLiCharModel + * @property {FFLiCharInfo} charInfo + * @property {FFLCharModelDesc} charModelDesc + * @property {FFLExpression} expression + * @property {number} pTextureTempObject + * @property {Array} drawParam + * @property {Array} pShapeData + * @property {Array} facelineRenderTexture + * @property {Array} pCapGlassNoselineTextures + * @property {FFLiMaskTextures} maskTextures + * @property {Array} beardHairFaceCenterPos + * @property {FFLPartsTransform} partsTransform + * @property {number} modelType - FFLModelType + * @property {Array} boundingBox + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLiCharModel = _.struct([ + _.struct('charInfo', [FFLiCharInfo]), + _.struct('charModelDesc', [FFLCharModelDesc]), + _.uint32le('expression'), // enum FFLExpression + _uintptr('pTextureTempObject'), // stub + _.struct('drawParam', [FFLDrawParam], FFLiShapeType.MAX), + _uintptr('pShapeData', FFLiShapeType.MAX), + _.struct('facelineRenderTexture', [FFLiRenderTexture]), + _uintptr('pCapGlassNoselineTextures', 3), + _.struct('maskTextures', [FFLiMaskTextures]), + _.struct('beardHairFaceCenterPos', [FFLVec3], 3), + _.struct('partsTransform', [FFLPartsTransform]), + _.uint32le('modelType'), // enum FFLModelType + // FFLBoundingBox[FFL_MODEL_TYPE_MAX = 3] + _.struct('boundingBox', [FFLBoundingBox], 3) +]); + +/** @enum {number} */ +const FFLDataSource = { + OFFICIAL: 0, + DEFAULT: 1, + MIDDLE_DB: 2, + STORE_DATA_OFFICIAL: 3, + STORE_DATA: 4, + BUFFER: 5, + DIRECT_POINTER: 6 +}; + +/** + * @typedef {Object} FFLCharModelSource + * @property {FFLDataSource} dataSource + * @property {number} pBuffer + * @property {number} index - Only for default, official, MiddleDB; unneeded for raw data + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLCharModelSource = _.struct([ + _.uint32le('dataSource'), + _uintptr('pBuffer'), + _.uint16le('index') +]); + +// The enums below are only for FFLiGetRandomCharInfo. +// Hence, why each one has a value called ALL. + +/** @enum {number} */ +const FFLGender = { + MALE: 0, + FEMALE: 1, + ALL: 2 +}; + +/** @enum {number} */ +const FFLAge = { + CHILD: 0, + ADULT: 1, + ELDER: 2, + ALL: 3 +}; + +/** @enum {number} */ +const FFLRace = { + BLACK: 0, + WHITE: 1, + ASIAN: 2, + ALL: 3 +}; + +/** + * @typedef {Object} FFLResourceDesc + * @property {Array} pData + * @property {Array} size + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLResourceDesc = _.struct([ + _uintptr('pData', FFLResourceType.MAX), + _.uint32le('size', FFLResourceType.MAX) +]); + +// // --------------------------------------------------------------------- +// // Texture Management +// // --------------------------------------------------------------------- + +// ------------------------- Texture Related Structs ------------------------- +/** @enum {number} */ +const FFLTextureFormat = { + R8_UNORM: 0, + R8_G8_UNORM: 1, + R8_G8_B8_A8_UNORM: 2, + MAX: 3 +}; + +/** + * @typedef {Object} FFLTextureInfo + * @property {number} width + * @property {number} height + * @property {number} mipCount + * @property {FFLTextureFormat} format + * @property {number} isGX2Tiled + * @property {number} imageSize + * @property {number} imagePtr + * @property {number} mipSize + * @property {number} mipPtr + * @property {Array} mipLevelOffset + */ +/** @type {import('./struct-fu').StructInstance} */ +const FFLTextureInfo = _.struct([ + _.uint16le('width'), + _.uint16le('height'), + _.uint8('mipCount'), + _.uint8('format'), + _.uint8('isGX2Tiled'), + _.byte('_padding', 1), + _.uint32le('imageSize'), + _uintptr('imagePtr'), + _.uint32le('mipSize'), + _uintptr('mipPtr'), + _.uint32le('mipLevelOffset', 13) +]); + +const FFLTextureCallback = _.struct([ + _uintptr('pObj'), + _.uint8('useOriginalTileMode'), + _.byte('_padding', 3), // alignment + _uintptr('pCreateFunc'), + _uintptr('pDeleteFunc') +]); + +// TODO PATH: src/TextureManager.js + +// ------------------------ Class: TextureManager ----------------------------- +/** + * Manages THREE.Texture objects created via FFL. + * Must be instantiated after FFL is fully initialized. + */ +class TextureManager { + /** + * Constructs the TextureManager. This MUST be created after initializing FFL. + * @param {Module} module - The Emscripten module. + * @param {boolean} [setToFFLGlobal] - Whether or not to call FFLSetTextureCallback on the constructed callback. + */ + constructor(module, setToFFLGlobal = false) { + /** + * @type {Module} + * @private + */ + this._module = module; + /** + * @type {Map} + * @private + */ + this._textures = new Map(); // Internal map of texture id -> THREE.Texture. + /** @package */ + this._textureCallbackPtr = 0; + /** + * Controls whether or not the TextureManager + * will log creations and deletions of textures + * in order to better track memory allocations. + * @public + */ + this.logging = false; + + // Create and set texture callback instance. + this._setTextureCallback(); + if (setToFFLGlobal) { + // Set texture callback globally within FFL if chosen. + module._FFLSetTextureCallback(this._textureCallbackPtr); + } + } + + /** + * Creates and allocates an {@link FFLTextureCallback} instance from callback function pointers. + * @param {Module} module - The Emscripten module. + * @param {number} createCallback - Function pointer for the create callback. + * @param {number} deleteCallback - Function pointer for the delete callback. + * @returns {number} Pointer to the {@link FFLTextureCallback}. + * Note that you MUST free this after using it (done in {@link TextureManager.disposeCallback}). + * @private + */ + static _allocateTextureCallback(module, createCallback, deleteCallback) { + const ptr = module._malloc(FFLTextureCallback.size); + const textureCallback = { + pObj: 0, + useOriginalTileMode: false, + _padding: [0, 0, 0], + pCreateFunc: createCallback, + pDeleteFunc: deleteCallback + }; + const packed = FFLTextureCallback.pack(textureCallback); + module.HEAPU8.set(packed, ptr); + return ptr; + } + + /** + * Creates the create/delete functions in Emscripten and allocates and sets + * the {@link FFLTextureCallback} object as {@link TextureManager._textureCallbackPtr}. + * @param {boolean} addDeleteCallback - Whether or not to bind the delete function to the texture callback. + */ + _setTextureCallback(addDeleteCallback = false) { + const mod = this._module; + // Bind the callbacks to this instance. + /** @private */ + this._createCallback = mod.addFunction(this._textureCreateFunc.bind(this), 'vppp'); + if (addDeleteCallback) { + /** @private */ + this._deleteCallback = mod.addFunction(this._textureDeleteFunc.bind(this), 'vpp'); + } + /** @private */ + this._textureCallbackPtr = TextureManager._allocateTextureCallback(mod, + this._createCallback, this._deleteCallback ? this._deleteCallback : 0); + } + + /** + * @param {number} format - Enum value for FFLTextureFormat. + * @returns {import('three').PixelFormat} Three.js texture format constant. + * @throws {Error} Unexpected FFLTextureFormat value + * Note that this function won't work on WebGL1Renderer in Three.js r137-r162 + * since R and RG textures need to use Luminance(Alpha)Format + * (you'd somehow need to detect which renderer is used) + * @private + */ + _getTextureFormat(format) { + // Map FFLTextureFormat to Three.js texture formats. + + // THREE.RGFormat did not work for me on Three.js r136/older. + const useGLES2Formats = Number(THREE.REVISION) <= 136; + const r8 = useGLES2Formats + ? THREE.LuminanceFormat + : THREE.RedFormat; + const r8g8 = useGLES2Formats + // NOTE: Using THREE.LuminanceAlphaFormat before + // it was removed, on WebGL 2.0, causes the texture + // to be converted to RGBA resulting in two issues. + // - There is a black outline around glasses + // - For glasses that have an inner color, the color is wrongly applied to the frames as well. + ? THREE.LuminanceAlphaFormat + : THREE.RGFormat; + + const textureFormatToThreeFormat = { + [FFLTextureFormat.R8_UNORM]: r8, + [FFLTextureFormat.R8_G8_UNORM]: r8g8, + [FFLTextureFormat.R8_G8_B8_A8_UNORM]: THREE.RGBAFormat + }; + + // Determine the data format from the table. + const dataFormat = textureFormatToThreeFormat[format]; + if (dataFormat === undefined) { + throw new Error(`_textureCreateFunc: Unexpected FFLTextureFormat value: ${format}`); + } + return dataFormat; + } + + /** + * @param {number} _ - Originally pObj, unused here. + * @param {number} textureInfoPtr - Pointer to {@link FFLTextureInfo}. + * @param {number} texturePtrPtr - Pointer to the texture handle (pTexture2D). + * @private + */ + _textureCreateFunc(_, textureInfoPtr, texturePtrPtr) { + const u8 = this._module.HEAPU8.subarray(textureInfoPtr, + textureInfoPtr + FFLTextureInfo.size); + const textureInfo = FFLTextureInfo.unpack(u8); + if (this.logging) { + console.debug(`_textureCreateFunc: width=${textureInfo.width}, height=${textureInfo.height}, format=${textureInfo.format}, imageSize=${textureInfo.imageSize}, mipCount=${textureInfo.mipCount}`); + } + + /** Resolve THREE.PixelFormat. */ + const format = this._getTextureFormat(textureInfo.format); + // Copy image data from HEAPU8 via slice. This is base level/mip level 0. + const imageData = this._module.HEAPU8.slice(textureInfo.imagePtr, + textureInfo.imagePtr + textureInfo.imageSize); + + // Mipmaps were not implemented before Three.js r136 + // and they only began functioning properly on r138 + const canUseMipmaps = Number(THREE.REVISION) >= 138; + // Actually use mipmaps if the mip count is over 1. + const useMipmaps = textureInfo.mipCount > 1 && canUseMipmaps; + + // Create new THREE.Texture with the specified format. + const texture = new THREE.DataTexture(useMipmaps ? null : imageData, + textureInfo.width, textureInfo.height, format, THREE.UnsignedByteType); + + texture.magFilter = THREE.LinearFilter; + // texture.generateMipmaps = true; // not necessary at higher resolutions + texture.minFilter = THREE.LinearFilter; + + if (useMipmaps) { + // Add base texture. + texture.mipmaps = [{ + data: imageData, + width: textureInfo.width, + height: textureInfo.height + }]; + // Enable filtering option for mipmap and add levels. + texture.minFilter = THREE.LinearMipmapLinearFilter; + texture.generateMipmaps = false; + this._addMipmaps(texture, textureInfo); + } + + texture.needsUpdate = true; + this.set(texture.id, texture); + this._module.HEAPU32[texturePtrPtr / 4] = texture.id; + } + + /** + * @param {import('three').Texture} texture - Texture to upload mipmaps into. + * @param {FFLTextureInfo} textureInfo - FFLTextureInfo object representing this texture. + * @throws {Error} Throws if mipPtr is null. + * @private + */ + _addMipmaps(texture, textureInfo) { + // Make sure mipPtr is not null. + if (textureInfo.mipPtr === 0) { + throw new Error('_addMipmaps: mipPtr is null, so the caller incorrectly assumed this texture has mipmaps'); + } + + // Iterate through mip levels starting from 1 (base level is mip level 0). + for (let mipLevel = 1; mipLevel < textureInfo.mipCount; mipLevel++) { + // Calculate the offset for the current mip level. + const mipOffset = textureInfo.mipLevelOffset[mipLevel - 1]; + + // Calculate dimensions of the current mip level. + const mipWidth = Math.max(1, textureInfo.width >> mipLevel); + const mipHeight = Math.max(1, textureInfo.height >> mipLevel); + + // Get the offset of the next mipmap and calculate end offset. + const nextMipOffset = textureInfo.mipLevelOffset[mipLevel] || textureInfo.mipSize; + const end = textureInfo.mipPtr + nextMipOffset; + + // Copy the data from the heap. + const start = textureInfo.mipPtr + mipOffset; + const mipData = this._module.HEAPU8.slice(start, end); + + if (this.logging) { + console.debug(` - Mip ${mipLevel}: ${mipWidth}x${mipHeight}, offset=${mipOffset}, range=${start}-${end}`); + } + // console.debug(uint8ArrayToBase64(mipData)); // will leak the data + + // Push this mip level data into the texture's mipmaps array. + // @ts-ignore - data = "CompressedTextureMipmap & CubeTexture & HTMLCanvasElement" + texture.mipmaps.push({ + data: mipData, // Should still accept Uint8Array. + width: mipWidth, + height: mipHeight + }); + } + } + + /** + * @param {number} _ - Originally pObj, unused here. + * @param {number} texturePtrPtr - Pointer to the texture handle (pTexture2D). + * @private + */ + _textureDeleteFunc(_, texturePtrPtr) { + const texId = this._module.HEAPU32[texturePtrPtr / 4]; + // this.delete(texId); + // NOTE: This is effectively no longer used as when + // we delete a CharModel instance it deletes + // cap/noseline/glass textures before we are + // finished with the model itself. It is now only logging + const tex = this._textures.get(texId); + if (tex && this.logging) { + console.debug('Delete texture ', tex.id); + } + } + + /** + * @param {number} id - ID assigned to the texture. + * @returns {import('three').Texture|null|undefined} Returns the texture if it is found. + * @public + */ + get(id) { + const texture = this._textures.get(id); + if (!texture && this.logging) { + console.error('Unknown texture', id); + } + return texture; + } + + /** + * @param {number} id - ID assigned to the texture. + * @param {import('three').Texture} texture - Texture to add. + * @public + */ + set(id, texture) { + // Set texture with an override for dispose. + const disposeReal = texture.dispose.bind(texture); + texture.dispose = () => { + // Remove this texture from the map after disposing. + disposeReal(); + this.delete(id); // this = TextureManager + }; + + this._textures.set(id, texture); + // Log is spaced to match delete/deleting/dispose messages. + if (this.logging) { + console.debug('Adding texture ', texture.id); + } + } + + /** + * @param {number} id - ID assigned to the texture. + * @public + */ + delete(id) { + // Get texture from array instead of with get() + // because it's okay if it was already deleted. + const texture = this._textures.get(id); + if (texture) { + // This is assuming the texture has already been disposed. + /** @type {Object} */ (texture).source = null; + /** @type {Object} */ (texture).mipmaps = null; + if (this.logging) { + console.debug('Deleted texture ', id); + } + this._textures.delete(id); + } + } + + /** + * Disposes/frees the {@link FFLTextureCallback} along with + * removing the created Emscripten functions. + * @public + */ + disposeCallback() { + // if (!this._module) { + // return; + // } + if (this._textureCallbackPtr) { + this._module._free(this._textureCallbackPtr); + this._textureCallbackPtr = 0; + } + if (this._deleteCallback) { + this._module.removeFunction(this._deleteCallback); + this._deleteCallback = 0; + } + // should always exist?: + if (this._createCallback) { + this._module.removeFunction(this._createCallback); + this._createCallback = 0; + } + // this._module = null; + } + + /** + * Disposes of all textures and frees the {@link FFLTextureCallback}. + * @public + */ + dispose() { + // Dispose of all stored textures. + this._textures.forEach((tex) => { + tex.dispose(); + }); + + // Clear texture map. + this._textures.clear(); + // Free texture callback. + this.disposeCallback(); + } +} + +// // --------------------------------------------------------------------- +// // Classes for FFL Exceptions +// // --------------------------------------------------------------------- +// TODO PATH: src/Exceptions.js + +/** + * Base exception type for all exceptions based on FFLResult. + * https://github.com/ariankordi/FFLSharp/blob/master/FFLSharp.FFLManager/FFLExceptions.cs + * https://github.com/aboood40091/ffl/blob/master/include/nn/ffl/FFLResult.h + */ +class FFLResultException extends Error { + /** + * @param {number|FFLResult} result - The returned {@link FFLResult}. + * @param {string} [funcName] - The name of the function that was called. + * @param {string} [message] - An optional message for the exception. + */ + constructor(result, funcName, message) { + if (!message) { + if (funcName) { + message = `${funcName} failed with FFLResult: ${result}`; + } else { + message = `From FFLResult: ${result}`; + } + } + super(message); + /** The stored {@link FFLResult} code. */ + this.result = result; + } + + /** + * Throws an exception if the {@link FFLResult} is not OK. + * @param {number} result - The {@link FFLResult} from an FFL function. + * @param {string} [funcName] - The name of the function that was called. + * @throws {FFLResultException|FFLResultWrongParam|FFLResultBroken|FFLResultNotAvailable|FFLResultFatal} + */ + static handleResult(result, funcName) { + switch (result) { + case FFLResult.ERROR: // FFL_RESULT_WRONG_PARAM + throw new FFLResultWrongParam(funcName); + case FFLResult.FILE_INVALID: // FFL_RESULT_BROKEN + throw new FFLResultBroken(funcName); + case FFLResult.MANAGER_NOT_CONSTRUCT: // FFL_RESULT_NOT_AVAILABLE + throw new FFLResultNotAvailable(funcName); + case FFLResult.FILE_LOAD_ERROR: // FFL_RESULT_FATAL + throw new FFLResultFatal(funcName); + case FFLResult.OK: // FFL_RESULT_OK + return; // All is OK. + default: + throw new FFLResultException(result, funcName); + } + } +} + +/** + * Exception reflecting FFL_RESULT_WRONG_PARAM / FFL_RESULT_ERROR. + * This is the most common error thrown in FFL. It usually + * means that input parameters are invalid. + * So many cases this is thrown: parts index is out of bounds, + * CharModelCreateParam is malformed, FFLDataSource is invalid, FFLInitResEx + * parameters are null or invalid... Many different causes, very much an annoying error. + */ +class FFLResultWrongParam extends FFLResultException { + /** @param {string} [funcName] - Name of the function where the result originated. */ + constructor(funcName) { + super(1, funcName, `${funcName} returned FFL_RESULT_WRONG_PARAM. This usually means parameters going into that function were invalid.`); + } +} + +/** Exception reflecting FFL_RESULT_BROKEN / FFL_RESULT_FILE_INVALID. */ +class FFLResultBroken extends FFLResultException { + /** + * @param {string} [funcName] - Name of the function where the result originated. + * @param {string} [message] - An optional message for the exception. + */ + constructor(funcName, message) { + super(3, funcName, message ? message : `${funcName} returned FFL_RESULT_BROKEN. This usually indicates invalid underlying data.`); + } +} + +/** Exception when resource header verification fails. */ +class BrokenInitRes extends FFLResultBroken { + constructor() { + super('FFLInitRes', 'The header for the FFL resource is probably invalid. Check the version and magic, should be "FFRA" or "ARFF".'); + } +} + +/** + * Thrown when: CRC16 fails, CharInfo verification fails, or failing to fetch from a database (impossible here) + */ +class BrokenInitModel extends FFLResultBroken { + constructor() { + super('FFLInitCharModelCPUStep', 'FFLInitCharModelCPUStep failed probably because your data failed CRC or CharInfo verification (FFLiVerifyCharInfoWithReason).'); + } +} + +/** + * Exception reflecting FFL_RESULT_NOT_AVAILABLE / FFL_RESULT_MANAGER_NOT_CONSTRUCT. + * This is seen when FFLiManager is not constructed, which it is not when FFLInitResEx fails + * or was never called to begin with. + */ +class FFLResultNotAvailable extends FFLResultException { + /** @param {string} [funcName] - Name of the function where the result originated. */ + constructor(funcName) { + super(4, funcName, `Tried to call FFL function ${funcName} when FFLManager is not constructed (FFL is not initialized properly).`); + } +} + +/** + * Exception reflecting FFL_RESULT_FATAL / FFL_RESULT_FILE_LOAD_ERROR. + * This error indicates database file load errors or failures from FFLiResourceLoader (decompression? misalignment?) + */ +class FFLResultFatal extends FFLResultException { + /** @param {string} [funcName] - Name of the function where the result originated. */ + constructor(funcName) { + super(5, funcName, `Failed to uncompress or load a specific asset from the FFL resource file during call to ${funcName}`); + } +} + +/** + * Exception thrown by the result of FFLiVerifyCharInfoWithReason. + * Reference: https://github.com/aboood40091/ffl/blob/master/include/nn/ffl/detail/FFLiCharInfo.h#L90 + */ +class FFLiVerifyReasonException extends Error { + /** @param {number} result - The FFLiVerifyReason code from FFLiVerifyCharInfoWithReason. */ + constructor(result) { + super(`FFLiVerifyCharInfoWithReason (CharInfo verification) failed with result: ${result}`); + /** The stored FFLiVerifyReason code. */ + this.result = result; + } +} + +/** + * Exception thrown when the mask is set to an expression that + * the {@link CharModel} was never initialized to, which can't happen + * because that mask texture does not exist on the {@link CharModel}. + * @augments {Error} + */ +class ExpressionNotSet extends Error { + /** @param {FFLExpression} expression - The attempted expression. */ + constructor(expression) { + super(`Attempted to set expression ${expression}, but the mask for that expression does not exist. You must reinitialize the CharModel with this expression in the expression flags before using it.`); + this.expression = expression; + } +} + +// // --------------------------------------------------------------------- +// // FFL Initialization +// // --------------------------------------------------------------------- +// TODO PATH: src/Init.js + +/** + * Loads data from TypedArray or fetch response directly into Emscripten heap. + * If passed a fetch response, it streams it directly into memory and avoids copying. + * @param {ArrayBuffer|Uint8Array|Response} resource - The resource data. + * Use a Fetch response to stream directly, or a Uint8Array if you only have the raw bytes. + * @param {Module} module - The Emscripten module instance. + * @returns {Promise<{pointer: number, size: number}>} Pointer and size of the allocated heap memory. + * @throws {Error} resource must be a Uint8Array or fetch that is streamable and has Content-Length. + * @private + */ +async function _loadDataIntoHeap(resource, module) { + // These need to be accessible by the catch statement: + let heapSize; + let heapPtr; + try { + // Copy resource into heap. + if (resource instanceof ArrayBuffer) { + resource = new Uint8Array(resource); + } + if (resource instanceof Uint8Array) { + // Comes in as Uint8Array, allocate and set it. + heapSize = resource.length; + heapPtr = module._malloc(heapSize); + console.debug(`_loadDataIntoHeap: Loading from buffer. Size: ${heapSize}, pointer: ${heapPtr}`); + // Allocate and set this area in the heap as the passed buffer. + module.HEAPU8.set(resource, heapPtr); + } else if (resource instanceof Response) { + // Handle as fetch response. + if (!resource.ok) { + throw new Error(`HTTP error while fetching resource at URL = ${resource.url}, response code = ${resource.status}`); + } + // Throw an error if it is not a streamable response. + if (!resource.body) { + throw new Error(`Response body is null (resource.body = ${resource.body})`); + } + // Get the total size of the resource from the headers. + const contentLength = resource.headers.get('Content-Length'); + if (!contentLength) { + // Cannot stream the response. Read as ArrayBuffer and reinvoke function. + console.debug('_loadDataIntoHeap: Fetch response is missing Content-Length, falling back to reading as ArrayBuffer.'); + return _loadDataIntoHeap(await resource.arrayBuffer(), module); + } + + // Allocate into heap using the Content-Length. + heapSize = parseInt(contentLength, 10); + heapPtr = module._malloc(heapSize); + + console.debug(`loadDataIntoHeap: Streaming from fetch response. Size: ${heapSize}, pointer: ${heapPtr}, URL: ${resource.url}`); + + // Begin reading and streaming chunks into the heap. + const reader = resource.body.getReader(); + let offset = heapPtr; + while (true) { + const { done, value } = await reader.read(); + if (done) { + break; + } + // Copy value directly into HEAPU8 with offset. + module.HEAPU8.set(value, offset); + offset += value.length; + } + } else { + throw new Error('loadDataIntoHeap: type is not Uint8Array or Response'); + } + + return { pointer: heapPtr, size: heapSize }; + } catch (error) { + // Free memory upon exception, if allocated. + if (heapPtr) { + module._free(heapPtr); + } + throw error; + } +} + +// ----------------- initializeFFL(resource, moduleOrPromise) ----------------- +/** + * Initializes FFL by copying the resource into heap and calling FFLInitRes. + * It will first wait for the Emscripten module to be ready. + * @param {Uint8Array|Response} resource - The FFL resource data. Use a Uint8Array + * if you have the raw bytes, or a fetch response containing the FFL resource file. + * @param {Module|Promise|function(): Promise} moduleOrPromise - The Emscripten module + * by itself (window.Module when MODULARIZE=0), as a promise (window.Module() when MODULARIZE=1), + * or as a function returning a promise (window.Module when MODULARIZE=1). + * @returns {Promise<{module: Module, resourceDesc: FFLResourceDesc}>} Resolves when FFL is fully initialized, + * returning the final Emscripten {@link Module} instance and the {@link FFLResourceDesc} object + * that can later be passed into {@link exitFFL}. + */ +async function initializeFFL(resource, moduleOrPromise) { + console.debug('initializeFFL: Entrypoint, waiting for module to be ready.'); + + /** + * Pointer to the FFLResourceDesc structure to free when FFLInitRes call is done. + * @type {number} + */ + let resourceDescPtr; + /** Frees the FFLResourceDesc - not the resources it POINTS to unlike _freeResourceDesc. */ + function freeResDesc() { + if (resourceDescPtr) { + // Free FFLResourceDesc, unused after init. + module._free(resourceDescPtr); + } + } + /** Resource type to load single resource into. */ + const resourceType = FFLResourceType.HIGH; + + /** + * The Emscripten Module instance to set and return at the end. + * @type {Module} + */ + let module; + // Resolve moduleOrPromise to the Module instance. + if (typeof moduleOrPromise === 'function') { + // Assume this function gets the promise of the module. + moduleOrPromise = moduleOrPromise(); + } + if (moduleOrPromise instanceof Promise) { + // Await if this is now a promise. + module = await moduleOrPromise; + } else { + // Otherwise, assume it is already the module. + module = moduleOrPromise; + } + + // Wait for the Emscripten runtime to be ready if it isn't already. + if (!module.calledRun && !module.onRuntimeInitialized) { + // calledRun is not defined. Set onRuntimeInitialized and wait for it in a new promise. + await new Promise((resolve) => { + /** If onRuntimeInitialized is not defined on module, add it. */ + module.onRuntimeInitialized = () => { + console.debug('initializeFFL: Emscripten runtime initialized, resolving.'); + resolve(null); + }; + console.debug(`initializeFFL: module.calledRun: ${module.calledRun}, module.onRuntimeInitialized:\n${module.onRuntimeInitialized}\n // ^^ assigned and waiting.`); + // If you are stuck here, the object passed in may not actually be an Emscripten module? + }); + } else { + console.debug('initializeFFL: Assuming module is ready.'); + } + + // Module should be ready after this point, begin loading the resource. + /** @type {FFLResourceDesc|null} */ + let resourceDesc = null; + try { + // If resource is itself a promise (fetch() result), wait for it to finish. + if (resource instanceof Promise) { + resource = await resource; + } + + // Load the resource (Uint8Array/fetch Response) into heap. + const { pointer: heapPtr, size: heapSize } = await _loadDataIntoHeap(resource, module); + console.debug(`initializeFFL: Resource loaded into heap. Pointer: ${heapPtr}, Size: ${heapSize}`); + + // Initialize and pack FFLResourceDesc. + resourceDesc = { pData: [0, 0], size: [0, 0] }; + resourceDesc.pData[resourceType] = heapPtr; + resourceDesc.size[resourceType] = heapSize; + + const resourceDescData = FFLResourceDesc.pack(resourceDesc); + resourceDescPtr = module._malloc(FFLResourceDesc.size); // Freed by freeResDesc. + module.HEAPU8.set(resourceDescData, resourceDescPtr); + + // Call FFL initialization using: FFL_FONT_REGION_JP_US_EU = 0 + const result = module._FFLInitRes(0, resourceDescPtr); + + // Handle failed result. + if (result === FFLResult.FILE_INVALID) { // FFL_RESULT_BROKEN + throw new BrokenInitRes(); + } + FFLResultException.handleResult(result, 'FFLInitRes'); + + // Set required globals in FFL. + module._FFLInitResGPUStep(); // CanInitCharModel will fail if not called. + module._FFLSetNormalIsSnorm8_8_8_8(true); // Set normal format to FFLiSnorm8_8_8_8. + module._FFLSetTextureFlipY(true); // Set textures to be flipped for OpenGL. + + // Requires refactoring: + // module._FFLSetScale(0.1); // Sets model scale back to 1.0. + // module._FFLSetLinearGammaMode(1); // Use linear gamma. + // I don't think ^^ will work because the shaders need sRGB + } catch (error) { + // Cleanup on error. + _freeResourceDesc(resourceDesc, module); + freeResDesc(); + console.error('initializeFFL failed:', error); + throw error; + } finally { + // Always free the FFLResourceDesc struct itself. + freeResDesc(); + } + + // Return final Emscripten module and FFLResourceDesc object. + return { + module: module, + resourceDesc: resourceDesc + }; +} + +// ------------- initializeFFLWithResource(module, resourcePath) ------------- +/** + * Fetches the FFL resource from the specified path or the "content" + * attribute of this HTML element: meta[itemprop=ffl-js-resource-fetch-path] + * It then calls {@link initializeFFL} on the specified module. + * @param {Module|Promise|function(): Promise} module - The Emscripten module by itself + * (window.Module when MODULARIZE=0), as a promise (window.Module() when MODULARIZE=1), + * or as a function returning a promise (window.Module when MODULARIZE=1). + * @param {string|null} resourcePath - The URL for the FFL resource. + * @returns {Promise<{module: Module, resourceDesc: FFLResourceDesc}>} Resolves when fetch is finished + * and initializeFFL returns, returning the final Emscripten {@link Module} instance + * and the {@link FFLResourceDesc} object that can later be passed into {@link exitFFL}. + * @throws {Error} resourcePath must be a URL string, or, an HTML element with FFL resource must exist and have content. + */ +async function initializeFFLWithResource(module, resourcePath) { + // Query selector string for element with "content" attribute for path to the resource. + const querySelectorResourcePath = 'meta[itemprop=ffl-js-resource-fetch-path]'; + + if (!resourcePath && typeof document !== 'undefined') { + // Load FFL resource file from meta tag in HTML. + const resourceFetchElement = document.querySelector(querySelectorResourcePath); + if (!resourceFetchElement || !resourceFetchElement.getAttribute('content')) { + throw new Error(`initializeFFLWithResource: Element not found or does not have "content" attribute with path to FFL resource: ${querySelectorResourcePath}`); + } + // URL to resource for FFL. + resourcePath = resourceFetchElement.getAttribute('content'); + } + // is it still null? + if (!resourcePath) { + throw new Error('initializeFFLWithResource: resourcePath must be a string'); + } + try { + /** Fetch resource. */ + const response = await fetch(resourcePath); + // Initialize FFL using the resource from fetch response. + const ret = await initializeFFL(response, module); + console.debug('initializeFFLWithResource: FFLiManager and TextureManager initialized, exiting'); + return ret; + } catch (error) { + if (typeof alert !== 'undefined') { + alert(`Error initializing FFL with resource: ${error}`); + } + throw error; + } +} + +/** + * Frees all pData pointers within {@link FFLResourceDesc}. + * @param {FFLResourceDesc|null} desc - {@link FFLResourceDesc} to free pointers from. + * @param {Module} module - Emscripten module to call _free on. + * @package + */ +function _freeResourceDesc(desc, module) { + if (!desc || !desc.pData) { + return; + } + desc.pData.forEach((ptr, i) => { + if (ptr) { + module._free(ptr); + desc.pData[i] = 0; + } + }); +} + +// ---------------------- exitFFL(module, resourceDesc) ---------------------- +/** + * @param {Module} module - Emscripten module. + * @param {FFLResourceDesc} resourceDesc - The FFLResourceDesc received from {@link initializeFFL}. + * @public + * @todo TODO: Needs to somehow destroy Emscripten instance. + */ +function exitFFL(module, resourceDesc) { + console.debug('exitFFL called, resourceDesc:', resourceDesc); + + // All CharModels must be deleted before this point. + module._FFLExit(); + + // Free resources in heap after FFLExit(). + _freeResourceDesc(resourceDesc, module); + + // Exit the module...? Is this even necessary? + if (module._exit) { + module._exit(); + } else { + console.debug('exitFFL: not calling module._exit = ', module._exit); + } +} + +// // --------------------------------------------------------------------- +// // CharModel Handling +// // --------------------------------------------------------------------- +// TODO PATH: src/CharModel.js + +/** @typedef {function(new: import('three').Material, ...*): import('three').Material} MaterialConstructor */ + +// --------------------------- Class: CharModel ------------------------------- +/** + * Represents an FFLCharModel, which is the head model. + * Encapsulates a pointer to the underlying instance and provides helper methods. + * + * NOTE: This is a wrapper around CharModel. In order to create one, + * either call createCharModel or pass the pointer of a manually created + * CharModel in here. So *DO NOT* call this constructor directly! + * @public + */ +class CharModel { + /** + * @param {number} ptr - Pointer to the FFLiCharModel structure in heap. + * @param {Module} module - The Emscripten module. + * @param {MaterialConstructor} materialClass - Class for the material (constructor), e.g.: FFLShaderMaterial + * @param {TextureManager|null} texManager - The {@link TextureManager} instance for this CharModel. + */ + constructor(ptr, module, materialClass, texManager) { + /** @package */ + this._module = module; + /** + * The data used to construct the CharModel, set in {@link createCharModel} and used in {@link updateCharModel}. + * @type {*} + * @package + */ + this._data = null; + /** + * @type {MaterialConstructor} + * @public + */ + this._materialClass = materialClass; // Store the material class. + /** + * Material class used to initialize textures specifically. + * @type {MaterialConstructor} + * @public + */ + this._materialTextureClass = materialClass; + + /** @package */ + this._textureManager = texManager; + /** + * Pointer to the FFLiCharModel in memory, set to null when deleted. + * @package + */ + this._ptr = ptr; + /** @private */ + this.__ptr = ptr; // Permanent reference. + // Unpack the FFLiCharModel structure from heap. + const charModelData = this._module.HEAPU8.subarray(ptr, ptr + FFLiCharModel.size); + /** + * The unpacked representation of the underlying + * FFLCharModel instance. Note that this is not + * meant to be updated at all and changes to + * this instance will not apply in FFL whatsoever. + * @readonly + */ + this._model = FFLiCharModel.unpack(charModelData); + // NOTE: The only property SET in _model is expression. + // Everything else is read. + + // this.additionalInfo = this._getAdditionalInfo(); + + // Add RenderTargets for faceline and mask. + /** + * @type {import('three').RenderTarget|null} + * @package + */ + this._facelineTarget = null; + /** + * @type {Array} + * @package + */ + this._maskTargets = new Array(FFLExpression.MAX).fill(null); + + /** + * Group of THREE.Mesh objects representing the CharModel. + * @type {import('three').Group|null} + * @public + */ + this.meshes = new THREE.Group(); + // Set boundingBox getter ("this" = CharModel), dummy geometry needed + // this.meshes.geometry = { }; // NOTE: is this a good idea? + // Object.defineProperty(this.meshes.geometry, 'boundingBox', + // { get: () => this.boundingBox }); // TODO: box is too large using this + + this._addCharModelMeshes(module); // Populate this.meshes. + } + + // ----------------------- _addCharModelMeshes(module) ----------------------- + /** + * This is the method that populates meshes + * from the internal FFLiCharModel instance. + * @param {Module} module - Module to pass to drawParamToMesh to access mesh data. + * @throws {Error} Throws if this.meshes is null or undefined. + * @private + */ + _addCharModelMeshes(module) { + if (!this.meshes) { + throw new Error('_addCharModelMeshes: this.meshes is null or undefined, was this CharModel disposed?'); + } + // Add all meshes in the CharModel to the class instance. + for (let shapeType = 0; shapeType < FFLiShapeType.MAX; shapeType++) { + // Iterate through all DrawParams and convert to THREE.Mesh. + const drawParam = this._model.drawParam[shapeType]; + + // This will be null if there is no shape data, + // but it will be added anyway so that the indexes + // of this group all match up with FFLiShapeType. + const mesh = drawParamToMesh(drawParam, this._materialClass, + module, this._textureManager); + if (!mesh) { + continue; + } + // Use FFLModulateType to indicate render order. + mesh.renderOrder = drawParam.modulateParam.type; + // Set faceline and mask meshes to use later. + switch (shapeType) { + case FFLiShapeType.OPA_FACELINE: + /** @package */ + this._facelineMesh = mesh; + break; + case FFLiShapeType.XLU_MASK: + /** @package */ + this._maskMesh = mesh; + break; + } + + this.meshes.add(mesh); // Add the mesh or null. + } + } + + // --------------------------- Private Get Methods --------------------------- + + /** + * @returns {number} Pointer to pTextureTempObject. + * @private + */ + _getTextureTempObjectPtr() { + return this._model.pTextureTempObject; + } + + /** + * @returns {FFLiTextureTempObject} The TextureTempObject containing faceline and mask DrawParams. + * @package + */ + _getTextureTempObject() { + const ptr = this._getTextureTempObjectPtr(); + return FFLiTextureTempObject.unpack( + this._module.HEAPU8.subarray(ptr, ptr + FFLiTextureTempObject.size)); + } + + /** + * Get the unpacked result of FFLGetAdditionalInfo. + * @returns {FFLAdditionalInfo} The FFLAdditionalInfo object. + * @private + */ + /* + _getAdditionalInfo() { + const mod = this._module; + const addInfoPtr = mod._malloc(FFLAdditionalInfo.size); + const result = mod._FFLGetAdditionalInfo(addInfoPtr, FFLDataSource.BUFFER, this._ptr, 0, false); + FFLResultException.handleResult(result, 'FFLGetAdditionalInfo'); + const info = FFLAdditionalInfo.unpack(mod.HEAPU8.subarray(addInfoPtr, addInfoPtr + FFLAdditionalInfo.size)); + mod._free(addInfoPtr); + return info; + } + */ + + /** + * Accesses partsTransform in FFLiCharModel, + * converting every FFLVec3 to THREE.Vector3. + * @returns {PartsTransform} PartsTransform using THREE.Vector3 as keys. + * @throws {Error} Throws if this._model.partsTransform has objects that do not have "x" property. + * @private + */ + _getPartsTransform() { + const obj = /** @type {Object} */ (this._model.partsTransform); + /** @type {PartsTransform} */ + const newPartsTransform = {}; + for (const key in obj) { + const vec = obj[key]; + // sanity check make sure there is "x" + if (vec.x === undefined) { + throw new Error(); + } + // convert to THREE.Vector3 + newPartsTransform[key] = new THREE.Vector3(vec.x, vec.y, vec.z); + } + return newPartsTransform; + } + + /** + * @returns {import('three').Color} The faceline color as THREE.Color. + * @private + */ + _getFacelineColor() { + // const color = this.additionalInfo.skinColor; + // return new THREE.Color(color.r, color.g, color.b); + const mod = this._module; + const facelineColor = this._model.charInfo.faceline.color; + /** Allocate return pointer. */ + const colorPtr = mod._malloc(FFLColor.size); + mod._FFLGetFacelineColor(colorPtr, facelineColor); + const color = _getFFLColor3(_getFFLColor(colorPtr, mod.HEAPF32)); + mod._free(colorPtr); + return color; + // Assume this is in working color space because it is used for clear color. + } + + /** + * @returns {import('three').Color} The favorite color as THREE.Color. + * @private + */ + _getFavoriteColor() { + const mod = this._module; + const favoriteColor = this._model.charInfo.personal.favoriteColor; + /** Allocate return pointer. */ + const colorPtr = mod._malloc(FFLColor.size); + mod._FFLGetFavoriteColor(colorPtr, favoriteColor); // Get favoriteColor from CharInfo. + const color = _getFFLColor3(_getFFLColor(colorPtr, mod.HEAPF32)); + mod._free(colorPtr); + return color; + } + + /** + * @returns {Uint8Array} The CharInfo instance. + * @private + */ + _getCharInfoUint8Array() { + return FFLiCharInfo.pack(this._model.charInfo); + } + + /** + * @returns {number} Pointer to pTextureTempObject->maskTextures->partsTextures. + * @package + */ + _getPartsTexturesPtr() { + // eslint-disable-next-line @stylistic/max-len -- indent conflicts with something else + return this._model.pTextureTempObject + /** @type {number} */ (FFLiTextureTempObject.fields.maskTextures.offset) + /** @type {number} */(FFLiMaskTexturesTempObject.fields.partsTextures.offset); + } + + /** + * @returns {number} Pointer to pTextureTempObject->facelineTexture. + * @package + */ + _getFacelineTempObjectPtr() { + // eslint-disable-next-line @stylistic/max-len -- indent conflicts with something else + return this._model.pTextureTempObject + /** @type {number} */ (FFLiTextureTempObject.fields.facelineTexture.offset); + } + + /** + * @returns {number} Pointer to pTextureTempObject->maskTextures. + * @package + */ + _getMaskTempObjectPtr() { + // eslint-disable-next-line @stylistic/max-len -- indent conflicts with something else + return this._model.pTextureTempObject + /** @type {number} */ (FFLiTextureTempObject.fields.maskTextures.offset); + } + + /** + * @returns {number} Pointer to charModelDesc.allExpressionFlag. + * @package + */ + _getExpressionFlagPtr() { + // eslint-disable-next-line @stylistic/max-len -- indent conflicts with something else + return this._ptr + /** @type {number} */ (FFLiCharModel.fields.charModelDesc.offset) + /** @type {number} */ (FFLCharModelDesc.fields.allExpressionFlag.offset); + } + + /** + * Either gets the boundingBox in the CharModel or calculates it from the meshes. + * @returns {import('three').Box3} The bounding box. + * @throws {Error} Throws if this.meshes is null. + * @private + */ + _getBoundingBox() { + const bbox = this._model.boundingBox[this._model.modelType]; + // The bounding box in the CharModel can only be used if the values are not NaN. + // Seems that the NaN values do not transfer over when deserializing, they are just zeroes. + if (!(bbox.max.x === 0 && bbox.max.y === 0 && bbox.max.z === 0)) { + // Return from CharModel bounding box. + const min = new THREE.Vector3(bbox.min.x, bbox.min.y, bbox.min.z); + const max = new THREE.Vector3(bbox.max.x, bbox.max.y, bbox.max.z); + return new THREE.Box3(min, max); + } + // Bounding box is invalid, create one manually. + + // Note: FFL includes three different bounding boxes for each + // FFLModelType. This only creates one box per CharModel. + const excludeFromBox = [FFLModulateType.SHAPE_MASK, FFLModulateType.SHAPE_GLASS]; + // Create bounding box selectively excluding mask and glass. + const box = new THREE.Box3(); + if (!this.meshes) { + throw new Error('_getBoundingBox: this.meshes is null.'); + } + this.meshes.traverse((child) => { + if (!(child instanceof THREE.Mesh) || + // Exclude meshes whose modulateType are in excludeFromBox. + excludeFromBox.indexOf(child.geometry.userData.modulateType) !== -1) { + return; + } + // Expand the box. + box.expandByObject(child); + }); + return box; + } + + /** + * Get the texture resolution. + * @returns {number} The texture resolution. + * @package + */ + _getResolution() { + return this._model.charModelDesc.resolution & FFL_RESOLUTION_MASK; + } + + // --------------------------------- Disposal --------------------------------- + + /** + * Finalizes the CharModel. + * Frees and deletes the CharModel right after generating textures. + * This is **not** the same as `dispose()` which cleans up the scene. + * @package + */ + _finalizeCharModel() { + if (!this._ptr) { + return; + } + this._module._FFLDeleteCharModel(this._ptr); + this._module._free(this._ptr); + this._ptr = 0; + } + + /** + * Disposes RenderTargets for textures created by the CharModel. + * @public + */ + disposeTargets() { + // Dispose RenderTargets. + if (this._facelineTarget) { + console.debug(`Disposing target ${this._facelineTarget.texture.id} for faceline`); + this._facelineTarget.dispose(); + this._facelineTarget = null; + } + // _maskTargets should always be defined. + this._maskTargets.forEach((target, i) => { + if (!target) { + // No mask for this expression. + return; + } + console.debug(`Disposing target ${target.texture.id} for mask ${i}`); + target.dispose(); + this._maskTargets[i] = null; + }); + } + + // ---------------------- Public Methods - Cleanup, Data ---------------------- + + /** + * Disposes the CharModel and removes all associated resources. + * - Disposes materials and geometries. + * - Deletes faceline texture if it exists. + * - Deletes all mask textures. + * - Removes all meshes from the scene. + * @param {boolean} disposeTargets - Whether or not to dispose of mask and faceline render targets. + * @public + */ + dispose(disposeTargets = true) { + // Print the permanent __ptr rather than _ptr. + console.debug('CharModel.dispose: ptr =', this.__ptr); + this._finalizeCharModel(); // Should've been called already + // Dispose meshes: materials, geometries, textures. + if (this.meshes) { + // Break these references first (still in meshes) + this._facelineMesh = null; + this._maskMesh = null; + disposeMeshes(this.meshes); + this.meshes = null; + } + // Dispose render textures. + if (disposeTargets) { + this.disposeTargets(); + } + if (this._textureManager) { + this._textureManager.dispose(); + // Null out reference to TextureManager, assuming + // all textures within are already deleted by now. + this._textureManager = null; + } + } + + /** + * Serializes the CharModel data to FFLStoreData. + * @returns {Uint8Array} The exported FFLStoreData. + * @throws {Error} Throws if call to _FFLpGetStoreDataFromCharInfo + * returns false, usually when CharInfo verification fails. + * @public + */ + getStoreData() { + // Serialize the CharInfo. + const charInfoData = this._getCharInfoUint8Array(); + + const mod = this._module; + // Allocate function arguments. + /** Input */ + const charInfoPtr = mod._malloc(FFLiCharInfo.size); + /** Output */ + const storeDataPtr = mod._malloc(FFLStoreData_size); + mod.HEAPU8.set(charInfoData, charInfoPtr); + + // Call conversion function. + const result = mod._FFLpGetStoreDataFromCharInfo(storeDataPtr, charInfoPtr); + // Free and return data. + const storeData = mod.HEAPU8.slice(storeDataPtr, storeDataPtr + FFLStoreData_size); + mod._free(charInfoPtr); + mod._free(storeDataPtr); + + if (!result) { + throw new Error('getStoreData: call to FFLpGetStoreDataFromCharInfo returned false, CharInfo verification probably failed'); + } + + return storeData; + } + + // TODO: getStudioCharInfo + + // ------------------------ Mask and Faceline Textures ------------------------ + + /** + * Sets the expression for this CharModel and updates the corresponding mask texture. + * @param {FFLExpression} expression - The new expression index. + * @throws {Error} CharModel must have been initialized with the + * expression enabled in the flag and have XLU_MASK in meshes. + * @public + */ + setExpression(expression) { + this._model.expression = expression; + + /** or getMaskTexture()? */ + const targ = this._maskTargets[expression]; + if (!targ || !targ.texture) { + throw new ExpressionNotSet(expression); + } + const mesh = this._maskMesh; + if (!mesh || !(mesh instanceof THREE.Mesh)) { + // So there is no mask mesh, which is not supposed to happen... + // ... except for when the expression is 61 or 62, in which case just return. + if (expression === FFLExpression.BLANK_61 || expression === FFLExpression.BLANK_62) { + return; // Drop out without throwing or setting expression. + } + throw new Error('setExpression: mask mesh does not exist, cannot set expression on it'); + } + // Update texture and material. + /** @type {import('three').Texture&{_target:import('three').RenderTarget}} */ (targ.texture) + ._target = targ; + /** @type {import('three').MeshBasicMaterial} */ (mesh.material).map = targ.texture; + /** @type {import('three').MeshBasicMaterial} */ (mesh.material).needsUpdate = true; + } + + /** + * Gets the faceline texture, or the texture that wraps around + * the faceline shape (opaque, the one hair is placed atop). + * Not to be confused with the texture containing facial features + * such as eyes, mouth, etc. which is the mask. + * The faceline texture may not exist if it is not needed, in which + * case the faceline color is used directly, see property {@link facelineColor}. + * @returns {import('three').RenderTarget|null} The faceline render target, or null if it does not exist, + * in which case {@link facelineColor} should be used. Access .texture on this object to + * get a {@link THREE.Texture} from it. It becomes invalid if the CharModel is disposed. + */ + getFaceline() { // getFaceTexture / "FFLiGetFaceTextureFromCharModel" + // Return the render target if it exists. + if (this._facelineTarget) { + return this._facelineTarget; + } + return null; + } + + /** + * Gets the mask texture, or the texture containing facial + * features such as eyes, mouth, eyebrows, etc. This is wrapped + * around the mask shape, which is a transparent shape + * placed in front of the head model. + * @param {FFLExpression} expression - The desired expression, or the current expression. + * @returns {import('three').RenderTarget|null} The mask render target for the given expression, + * or null if the CharModel was not initialized with that expression. + * Access .texture on this object to get a {@link THREE.Texture} from it. + * It becomes invalid if the CharModel is disposed. + */ + getMask(expression = this.expression) { // getMaskTexture + // Return the render target if it exists. + if (this._maskTargets && this._maskTargets[expression]) { + return this._maskTargets[expression]; + } + return null; + } + + // ------------------------------ Public Getters ------------------------------ + + /** + * The current expression for this CharModel. + * Read-only. Use setExpression to set the expression. + * @returns {FFLExpression} The current expression. + * @public + */ + get expression() { + return this._model.expression; // mirror + } + + /** + * Contains the CharInfo of the model. + * Changes to this will not be reflected whatsoever. + * @returns {FFLiCharInfo} The CharInfo of the model. + * @public + */ + get charInfo() { + return this._model.charInfo; + } + + /** + * The faceline color for this CharModel. + * @returns {import('three').Color} The faceline color. + * @public + */ + get facelineColor() { + if (!this._facelineColor) { + /** @private */ + this._facelineColor = this._getFacelineColor(); + } + return this._facelineColor; + } + + /** + * The favorite color for this CharModel. + * @returns {import('three').Color} The favorite color. + * @public + */ + get favoriteColor() { + if (!this._favoriteColor) { + /** @private */ + this._favoriteColor = this._getFavoriteColor(); + } + return this._favoriteColor; + } + + /** + * @returns {number} Gender as 0 = male, 1 = female + * @public + */ + get gender() { + return this._model.charInfo.personal.gender; + } + + /** + * The parameters in which to transform hats and other accessories. + * @returns {PartsTransform} PartsTransform using THREE.Vector3 as keys. + * @public + */ + get partsTransform() { + if (!this._partsTransform) { + // Set partsTransform property as THREE.Vector3. + /** @private */ + this._partsTransform = this._getPartsTransform(); + } + return this._partsTransform; + } + + /** + * @returns {import('three').Box3} The bounding box. + * @public + */ + get boundingBox() { + if (!this._boundingBox) { + // Set boundingBox property as THREE.Box3. + /** @private */ + this._boundingBox = this._getBoundingBox(); + } + return this._boundingBox; + } + + // -------------------------------- Body Scale -------------------------------- + + /** @enum {number} */ + static BodyScaleMode = { + /** Applies scale normally. */ + Apply: 0, + /** Limits scale so that the pants are not visible. */ + Limit: 1 + }; + + /* eslint-disable jsdoc/no-undefined-types -- BodyScaleMode */ + /** + * Gets a vector in which to scale the body model for this CharModel. + * @param {BodyScaleMode} scaleMode - Mode in which to create the scale vector. + * @returns {import('three').Vector3} Scale vector for the body model. + * @throws {Error} Unexpected value for scaleMode + * @public + */ + getBodyScale(scaleMode = CharModel.BodyScaleMode.Apply) { + /* eslint-enable jsdoc/no-undefined-types -- BodyScaleMode */ + const build = this._model.charInfo.body.build; + const height = this._model.charInfo.body.height; + + const bodyScale = new THREE.Vector3(); + switch (scaleMode) { + case CharModel.BodyScaleMode.Apply: { + // calculated here in libnn_mii/draw/src/detail/mii_VariableIconBodyImpl.cpp: + // void nn::mii::detail::`anonymous namespace'::GetBodyScale(struct nn::util::Float3 *, int, int) + // also in ffl_app.rpx: FUN_020ec380 (FFLUtility), FUN_020737b8 (mii maker US) + // ScaleApply + // 0.47 / 128.0 = 0.003671875 + bodyScale.x = (build * (height * 0.003671875 + 0.4)) / 128.0 + + // 0.23 / 128.0 = 0.001796875 + height * 0.001796875 + 0.4; + // 0.77 / 128.0 = 0.006015625 + bodyScale.y = (height * 0.006015625) + 0.5; + break; + } + case CharModel.BodyScaleMode.Limit: { + // ScaleLimit + const heightFactor = height / 128.0; + bodyScale.y = heightFactor * 0.55 + 0.6; + bodyScale.x = heightFactor * 0.3 + 0.6; + bodyScale.x = ((heightFactor * 0.6 + 0.8) - bodyScale.x) * + (build / 128.0) + bodyScale.x; + break; + } + default: + throw new Error(`getBodyScale: Unexpected value for scaleMode: ${scaleMode}`); + } + + // z is always set to x for either set + bodyScale.z = bodyScale.x; + + return bodyScale; + } +} + +// TODO PATH: src/Body.js (move above function, enum into there?) + +/** @enum {number} */ +const PantsColor = { + GrayNormal: 0, + BluePresent: 1, + RedRegular: 2, + GoldSpecial: 3 +}; + +/** @type {Object} */ +const pantsColors = { + [PantsColor.GrayNormal]: new THREE.Color(0x40474E), + [PantsColor.BluePresent]: new THREE.Color(0x28407A), + [PantsColor.RedRegular]: new THREE.Color(0x702015), + [PantsColor.GoldSpecial]: new THREE.Color(0xC0A030) +}; + +// TODO PATH: src/CharInfo.js + +/** + * Converts the input data and allocates it into FFLCharModelSource. + * Note that this allocates pBuffer so you must free it when you are done. + * @param {Uint8Array|FFLiCharInfo} data - Input: FFLStoreData, FFLiCharInfo (as Uint8Array and object), StudioCharInfo + * @param {Module} module - Module to allocate and access the buffer through. + * @returns {FFLCharModelSource} The CharModelSource with the data specified. + * @throws {Error} data must be Uint8Array or FFLiCharInfo object. Data must be a known type. + * @package + */ +function _allocateModelSource(data, module) { + /** Maximum size. */ + const bufferPtr = module._malloc(FFLiCharInfo.size); + + // Create modelSource. + const modelSource = { + // FFLDataSource.BUFFER = copies and verifies + // FFLDataSource.DIRECT_POINTER = use without verification. + dataSource: FFLDataSource.DIRECT_POINTER, // Assumes CharInfo by default. + pBuffer: bufferPtr, + index: 0 // unneeded for raw data + }; + + // module._FFLiGetRandomCharInfo(bufferPtr, FFLGender.FEMALE, FFLAge.ALL, FFLRace.WHITE); return modelSource; + + // Check type of data. + if (!(data instanceof Uint8Array)) { + try { + if (typeof data !== 'object') { + throw new Error('_allocateModelSource: data passed in is not FFLiCharInfo object or Uint8Array'); + } + // Assume that this is FFLiCharInfo as an object. + // Deserialize to Uint8Array. + data = FFLiCharInfo.pack(data); + } catch (e) { + module._free(bufferPtr); + throw e; + } + } + + /** @param {Uint8Array} src - Source data in {@link StudioCharInfo} format. */ + function setStudioData(src) { + // studio raw, decode it to charinfo + const studio = StudioCharInfo.unpack(src); + const charInfo = convertStudioCharInfoToFFLiCharInfo(studio); + data = FFLiCharInfo.pack(charInfo); + module.HEAPU8.set(data, bufferPtr); + } + + /** + * Gets CharInfo from calling a function. + * @param {Uint8Array} data - The input data. + * @param {number} size - The size to allocate. + * @param {string} funcName - The function on the module to call. + * @throws {Error} Throws if the function returned false. + * @private + */ + function callGetCharInfoFunc(data, size, funcName) { + const dataPtr = module._malloc(size); + module.HEAPU8.set(data, dataPtr); + // @ts-ignore - Module cannot be indexed by string. NOTE: The function MUST exist. + const result = module[funcName](bufferPtr, dataPtr); + module._free(dataPtr); + if (!result) { + module._free(bufferPtr); + throw new Error(`_allocateModelSource: call to ${funcName} returned false, CharInfo verification probably failed`); + } + } + + // data should be Uint8Array at this point. + + // Enumerate through supported data types. + switch (data.length) { + case FFLStoreData_size: { // sizeof(FFLStoreData) + // modelSource.dataSource = FFLDataSource.STORE_DATA; + // Convert FFLStoreData to FFLiCharInfo instead. + callGetCharInfoFunc(data, FFLStoreData_size, '_FFLpGetCharInfoFromStoreData'); + break; + } + case 74: // sizeof(RFLCharData) + case 76: { // sizeof(RFLStoreData) + callGetCharInfoFunc(data, 74, '_FFLpGetCharInfoFromMiiDataOfficialRFL'); + break; + } + case FFLiCharInfo.size: + // modelSource.dataSource = FFLDataSource.BUFFER; // Default option. + module.HEAPU8.set(data, bufferPtr); // Copy data into heap. + break; + case StudioCharInfo.size + 1: { + // studio data obfuscated + data = studioURLObfuscationDecode(data); + setStudioData(data); + break; + } + case StudioCharInfo.size: { + // studio data raw + setStudioData(data); + break; + } + default: { + module._free(bufferPtr); + throw new Error(`_allocateModelSource: Unknown data length: ${data.length}`); + } + } + + return modelSource; // NOTE: pBuffer must be freed. +} + +// ----------------- verifyCharInfo(data, module, verifyName) ----------------- +/** + * Validates the input CharInfo by calling FFLiVerifyCharInfoWithReason. + * @param {Uint8Array|number} data - FFLiCharInfo structure as bytes or pointer. + * @param {Module} module - Module to access the data and call FFL through. + * @param {boolean} verifyName - Whether the name and creator name should be verified. + * @returns {void} Returns nothing if verification passes. + * @throws {FFLiVerifyReasonException} Throws if the result is not 0 (FFLI_VERIFY_REASON_OK). + * @public + * @todo TODO: Should preferably return a custom error class. + */ +function verifyCharInfo(data, module, verifyName = false) { + // Resolve charInfoPtr as pointer to CharInfo. + let charInfoPtr = 0; + let charInfoAllocated = false; + // Assume that number means pointer. + if (typeof data === 'number') { + charInfoPtr = data; + charInfoAllocated = false; + } else { + // Assume everything else means Uint8Array. TODO: untested + charInfoAllocated = true; + // Allocate and copy CharInfo. + charInfoPtr = module._malloc(FFLiCharInfo.size); + module.HEAPU8.set(data, charInfoPtr); + } + const result = module._FFLiVerifyCharInfoWithReason(charInfoPtr, verifyName); + // Free CharInfo as soon as the function returns. + if (charInfoAllocated) { + module._free(charInfoPtr); + } + + if (result !== 0) { + // Reference: https://github.com/aboood40091/ffl/blob/master/include/nn/ffl/detail/FFLiCharInfo.h#L90 + throw new FFLiVerifyReasonException(result); + } +} + +// --------------- getRandomCharInfo(module, gender, age, race) --------------- +/** + * Generates a random FFLiCharInfo instance calling FFLiGetRandomCharInfo. + * @param {Module} module - The Emscripten module. + * @param {FFLGender} gender - Gender of the character. + * @param {FFLAge} age - Age of the character. + * @param {FFLRace} race - Race of the character. + * @returns {Uint8Array} The random FFLiCharInfo. + * @todo TODO: Should this return FFLiCharInfo object? + */ +function getRandomCharInfo(module, gender = FFLGender.ALL, age = FFLAge.ALL, race = FFLRace.ALL) { + const ptr = module._malloc(FFLiCharInfo.size); + module._FFLiGetRandomCharInfo(ptr, gender, age, race); + const result = module.HEAPU8.slice(ptr, ptr + FFLiCharInfo.size); + module._free(ptr); + return result; +} + +// --------------------- makeExpressionFlag(expressions) ---------------------- +/** + * Creates an expression flag to be used in FFLCharModelDesc. + * Use this whenever you need to describe which expression, + * or expressions, you want to be able to use in the CharModel. + * @param {Array|FFLExpression} expressions - Either a single expression + * index or an array of expression indices. See {@link FFLExpression} for min/max. + * @returns {Uint32Array} FFLAllExpressionFlag type of three 32-bit integers. + * @throws {Error} expressions must be in range and less than {@link FFLExpression.MAX}. + */ +function makeExpressionFlag(expressions) { + /** + * @param {FFLExpression} i - Expression index to check. + * @throws {Error} input out of range + */ + function checkRange(i) { + if (i >= FFLExpression.MAX) { + throw new Error(`makeExpressionFlag: input out of range: got ${i}, max: ${FFLExpression.MAX}`); + } + } + + /** + * Logs using {@link console.warn} if the expression index + * disables any shapes in the CharModel, meant to + * be used when setting multiple indices. + * @param {FFLExpression} i - Expression index to check. + */ + function warnIfChangesShapes(i) { + // Disables nose: dog/cat, blank + const expressionsDisablingNose = [49, 50, 51, 52, 61, 62]; + // Disables mask: blank + const expressionsDisablingMask = [61, 62]; + + const prefix = `makeExpressionFlag > warnIfChangesShapes: An expression was enabled (${i}) that is meant to disable nose or mask shape for the entire CharModel, so it is only recommended to set this as a single expression rather than as one of multiple.`; + if (expressionsDisablingNose.indexOf(i) !== -1) { + console.warn(`${prefix} (nose shape)`); + } + if (expressionsDisablingMask.indexOf(i) !== -1) { + console.warn(`${prefix} (in this case, MASK SHAPE so there is supposed to be NO FACE)`); + } + } + + /** FFLAllExpressionFlag */ + const flags = new Uint32Array([0, 0, 0]); + + // Set single expression. + if (typeof expressions === 'number') { + // Make expressions into an array. + expressions = [expressions]; + // Fall-through. + } else if (!Array.isArray(expressions)) { + throw new Error('makeExpressionFlag: expected array or single number'); + } + + // Set multiple expressions in an array. + for (const index of expressions) { + checkRange(index); + warnIfChangesShapes(index); // Warn if the expression changes shapes. + /** Determine which 32-bit block. */ + const part = Math.floor(index / 32); + /** Determine the bit within the block. */ + const bitIndex = index % 32; + + flags[part] |= (1 << bitIndex); // Set the bit. + } + return flags; +} + +// // --------------------------------------------------------------------- +// // CharModel Creation +// // --------------------------------------------------------------------- +// TODO PATH: src/CharModelCreation.js + +// --------- createCharModel(data, modelDesc, materialClass, module) --------- +/** + * Creates a CharModel from data and FFLCharModelDesc. + * You must call initCharModelTextures afterwards to finish the process. + * Don't forget to call dispose() on the CharModel when you are done. + * @param {Uint8Array|FFLiCharInfo} data - Character data. Accepted types: + * FFLStoreData, FFLiCharInfo (as Uint8Array and object), StudioCharInfo + * @param {FFLCharModelDesc|null} modelDesc - The model description. Default: {@link FFLCharModelDescDefault} + * @param {MaterialConstructor} materialClass - Class for the material (constructor), e.g.: FFLShaderMaterial + * @param {Module} module - The Emscripten module. + * @param {boolean} verify - Whether the CharInfo provided should be verified. + * @returns {CharModel} The new CharModel instance. + * @throws {FFLResultException|BrokenInitModel|FFLiVerifyReasonException|Error} Throws if `module`, `modelDesc`, + * or `data` is invalid, CharInfo verification fails, or CharModel creation fails otherwise. + */ +function createCharModel(data, modelDesc, materialClass, module, verify = true) { + modelDesc = modelDesc || FFLCharModelDescDefault; + + // Verify arguments. + if (!module || !module._malloc) { + throw new Error('createCharModel: module is null or does not have ._malloc.'); + } + if (!data) { + throw new Error('createCharModel: data is null or undefined.'); + } + if (typeof modelDesc !== 'object' || modelDesc.allExpressionFlag === undefined) { + throw new Error('createCharModel: modelDesc argument is invalid, make sure it is FFLCharModelDesc.'); + } + // Allocate memory for model source, description, char model, and char info. + const modelSourcePtr = module._malloc(FFLCharModelSource.size); + const modelDescPtr = module._malloc(FFLCharModelDesc.size); + const charModelPtr = module._malloc(FFLiCharModel.size); + + // data = getRandomCharInfo(module, FFLGender.FEMALE, FFLAge.ALL, FFLRace.WHITE); + // console.debug('getRandomCharInfo result:', FFLiCharInfo.unpack(data)); + // Get FFLCharModelSource. This converts and allocates CharInfo. + const modelSource = _allocateModelSource(data, module); + /** Get pBuffer to free it later. */ + const charInfoPtr = modelSource.pBuffer; + + const modelSourceBuffer = FFLCharModelSource.pack(modelSource); + module.HEAPU8.set(modelSourceBuffer, modelSourcePtr); + + // Set field to enable new expressions. This field + // exists because some callers would leave the other + // bits undefined but this does not so no reason to not enable + modelDesc.modelFlag |= FFLModelFlag.NEW_EXPRESSIONS; + + const modelDescBuffer = FFLCharModelDesc.pack(modelDesc); + module.HEAPU8.set(modelDescBuffer, modelDescPtr); + + /** + * Local TextureManager instance. + * @type {TextureManager|null} + */ + let textureManager = null; + try { + // Verify CharInfo before creating. + if (verify) { + verifyCharInfo(charInfoPtr, module, false); // Don't verify name. + } + + // Create TextureManager instance for this CharModel. + textureManager = new TextureManager(module, false); + + // Call FFLInitCharModelCPUStep and check the result. + // const result = module._FFLInitCharModelCPUStep(charModelPtr, modelSourcePtr, modelDescPtr); + const result = module._FFLInitCharModelCPUStepWithCallback(charModelPtr, + modelSourcePtr, modelDescPtr, textureManager._textureCallbackPtr); + if (result === FFLResult.FILE_INVALID) { // FFL_RESULT_BROKEN + throw new BrokenInitModel(); + } + FFLResultException.handleResult(result, 'FFLInitCharModelCPUStep'); + } catch (error) { + if (textureManager) { + textureManager.dispose(); + } + // Free CharModel prematurely. + module._free(charModelPtr); + throw error; + } finally { + // Free temporary allocations. + module._free(modelSourcePtr); + module._free(modelDescPtr); + module._free(charInfoPtr); + // Callback itself is longer read by FFL. + if (textureManager) { + textureManager.disposeCallback(); + } + } + + // Create the CharModel instance. + const charModel = new CharModel(charModelPtr, module, materialClass, textureManager); + // The constructor will populate meshes from the FFLiCharModel instance. + /** @private */ + charModel._data = data; // Store original data passed to function. + + console.debug(`createCharModel: Initialized for "${charModel._model.charInfo.personal.name}", ptr =`, charModelPtr); + return charModel; +} + +// ------- updateCharModel(charModel, newData, renderer, descOrExpFlag) ------- +/** + * Updates the given CharModel with new data and a new ModelDesc or expression flag. + * If `descOrExpFlag` is an array, it is treated as the new expression flag while inheriting the rest + * of the ModelDesc from the existing CharModel. + * @param {CharModel} charModel - The existing CharModel instance. + * @param {Uint8Array|null} newData - The new raw charInfo data, or null to use the original. + * @param {import('three').WebGLRenderer} renderer - The Three.js renderer. + * @param {FFLCharModelDesc|Array|Uint32Array|null} descOrExpFlag - Either a + * new {@link FFLCharModelDesc}, an array of expressions, a single expression, or an expression flag (Uint32Array). + * @param {boolean} verify - Whether the CharInfo provided should be verified. + * @returns {CharModel} The updated CharModel instance. + * @throws {Error} Unexpected type for descOrExpFlag, newData is null + * @todo TODO: Should `newData` just pass the charInfo object instance instead of "_data"? + */ +function updateCharModel(charModel, newData, renderer, descOrExpFlag = null, verify = true) { + /** @type {FFLCharModelDesc} */ + let newModelDesc; + newData = newData || charModel._data; + if (!newData) { + throw new Error('updateCharModel: newData is null. It should be retrieved from charModel._data which is set by createCharModel.'); + } + + // Convert descOrExpFlag to an expression flag if needed. + if (Array.isArray(descOrExpFlag) || typeof descOrExpFlag === 'number') { + // Array of expressions or single expression was passed in. + descOrExpFlag = makeExpressionFlag(descOrExpFlag); + } + + // Process descOrExpFlag based on what it is. + if (descOrExpFlag instanceof Uint32Array) { + // If this is already an expression flag (Uint32Array), + // or set to one previously, use it with existing CharModelDesc. + newModelDesc = charModel._model.charModelDesc; + newModelDesc.allExpressionFlag = descOrExpFlag; + } else if (!descOrExpFlag) { + // Inherit the CharModelDesc from the current model. + newModelDesc = charModel._model.charModelDesc; + } else if (typeof descOrExpFlag === 'object') { + // Assume that descOrExpFlag is a new FFLCharModelDesc. + newModelDesc = /** @type {FFLCharModelDesc} */ (descOrExpFlag); + } else { + throw new Error('updateCharModel: Unexpected type for descOrExpFlag'); + } + + // Dispose of the old CharModel. + charModel.dispose(); + // Create a new CharModel with the new data and ModelDesc. + const newCharModel = createCharModel(newData, newModelDesc, + charModel._materialClass, charModel._module, verify); + // Initialize its textures. + initCharModelTextures(newCharModel, renderer, charModel._materialTextureClass); + return newCharModel; +} + +/** + * Copies faceline and mask render targets from `src` + * to the `dst` CharModel, disposing textures from `dst` + * and disposing shapes from `src`, effectively transferring. + * @param {CharModel} src - The source {@link CharModel} from which to copy textures from and dispose shapes. + * @param {CharModel} dst - The destination {@link CharModel} receiving the textures. + * @returns {CharModel} The final CharModel. + * @todo TODO: Completely untested. + */ +function transferCharModelTex(src, dst) { + // Dispose textures on destination CharModel, they will be replaced. + dst.disposeTargets(); + // Dispose everything but textures on the source CharModel. + src.dispose(false); + + // Transfer faceline and mask targets. + dst._facelineTarget = src._facelineTarget; + dst._maskTargets = src._maskTargets; + + // The references are transferred too so when the + // dst CharModel gets deleted it will dispose the right ones. + return dst; +} + +// // --------------------------------------------------------------------- +// // DrawParam Reading +// // --------------------------------------------------------------------- +// TODO PATH: src/DrawParam.js + +/** + * @param {Function} material - Class constructor for the material to test. + * @returns {boolean} Whether or not the material class supports FFL swizzled (modulateMode) textures. + */ +function matSupportsFFL(material) { + return ('modulateMode' in material.prototype); +} + +// TODO: private? +// ------ drawParamToMesh(drawParam, materialClass, module, texManager) ------ +/** + * Converts FFLDrawParam into a THREE.Mesh. + * Binds geometry, texture, and material parameters. + * @param {FFLDrawParam} drawParam - The DrawParam representing the mesh. + * @param {MaterialConstructor} materialClass - Class for the material (constructor). + * @param {Module} module - The Emscripten module. + * @param {TextureManager|null} texManager - The {@link TextureManager} instance + * for which to look for textures referenced by the DrawParam. + * @returns {import('three').Mesh|null} The THREE.Mesh instance, or + * null if the index count is 0 indicating no shape data. + * @throws {Error} drawParam may be null, Unexpected value for FFLCullMode, Passed in TextureManager is invalid + */ +function drawParamToMesh(drawParam, materialClass, module, texManager) { + if (!drawParam) { + throw new Error('drawParamToMesh: drawParam may be null.'); + } + if (!texManager) { + throw new Error('drawParamToMesh: Passed in TextureManager is null or undefined, is it constructed?'); + } + if (typeof materialClass !== 'function') { + throw new Error('drawParamToMesh: materialClass is unexpectedly not a function.'); + } + + // Skip if the index count is 0, indicating no shape data. + if (drawParam.primitiveParam.indexCount === 0) { + return null; + } + // Bind geometry data. + const geometry = _bindDrawParamGeometry(drawParam, module); + // Determine cull mode by mapping FFLCullMode to THREE.Side. + /** @type {Object} */ + const cullModeToThreeSide = { + [FFLCullMode.NONE]: THREE.DoubleSide, + [FFLCullMode.BACK]: THREE.FrontSide, + [FFLCullMode.FRONT]: THREE.BackSide, + // Used by faceline/mask 2D planes for some reason: + [FFLCullMode.MAX]: THREE.DoubleSide + }; + const side = cullModeToThreeSide[drawParam.cullMode]; + if (side === undefined) { + throw new Error(`drawParamToMesh: Unexpected value for FFLCullMode: ${drawParam.cullMode}`); + } + // Get texture. + const texture = _getTextureFromModulateParam(drawParam.modulateParam, texManager); + + // Apply modulateParam material parameters. + const isFFLMaterial = matSupportsFFL(materialClass); + const params = _applyModulateParam(drawParam.modulateParam, module, isFFLMaterial); + // Create object for material parameters. + const materialParam = { + side: side, + // Apply texture. + map: texture, + ...params + }; + + // Special case for if tangent (NEEDED for aniso) is missing, and... + if (geometry.attributes.tangent === undefined && // "_color" can be tested too. + // ... material is FFLShaderMaterial. Which is the only one using that attribute. + 'useSpecularModeBlinn' in materialClass.prototype) { + /** @type {import('./FFLShaderMaterial').FFLShaderMaterialParameters} */ + (materialParam).useSpecularModeBlinn = true; + } + + // Create material using the provided materialClass. + const material = new materialClass(materialParam); + // Create mesh and set userData.modulateType. + const mesh = new THREE.Mesh(geometry, material); + + // Apply pAdjustMatrix transformations if it is not null. + if (drawParam.primitiveParam.pAdjustMatrix !== 0) { + _applyAdjustMatrixToMesh(drawParam.primitiveParam.pAdjustMatrix, mesh, module.HEAPF32); + } + + // Set properties that can be used to reconstruct the material in userData. + // NOTE: These are only in geometry (primitive) because FFL-Testing does the same, see: + // https://github.com/ariankordi/FFL-Testing/blob/2219f64473ac8312bab539cd05c00f88c14d2ffd/src/GLTFExportCallback.cpp#L828 + if (mesh.geometry.userData) { + // Set modulateMode/modulateType (not modulateColor or cullMode). + mesh.geometry.userData.modulateMode = drawParam.modulateParam.mode; + mesh.geometry.userData.modulateType = drawParam.modulateParam.type; + // Note that color is a part of THREE.Material and will most always be there + mesh.geometry.userData.color = params.color instanceof THREE.Color + ? [params.color.r, params.color.g, params.color.b, 1.0] + : [1.0, 1.0, 1.0, 1.0]; + mesh.geometry.userData.cullMode = drawParam.cullMode; + } + return mesh; +} + +/** + * Binds geometry attributes from drawParam into a THREE.BufferGeometry. + * @param {FFLDrawParam} drawParam - The DrawParam representing the mesh. + * @param {Module} module - The Emscripten module from which to read the heap. + * @returns {import('three').BufferGeometry} The geometry. + * @throws {Error} Position buffer must not have size of 0 + * @package + * @todo Does not yet handle color stride = 0 + */ +function _bindDrawParamGeometry(drawParam, module) { + /** + * @param {string} typeStr - The type of the attribute. + * @param {number} stride - The stride to display. + * @throws {Error} Unexpected stride for attribute ... + */ + function unexpectedStride(typeStr, stride) { + throw new Error(`_bindDrawParamGeometry: Unexpected stride for attribute ${typeStr}: ${stride}`); + } + + // Access FFLAttributeBufferParam. + const attributes = drawParam.attributeBufferParam.attributeBuffers; + const positionBuffer = attributes[FFLAttributeBufferType.POSITION]; + // There should always be positions. + if (positionBuffer.size === 0) { + throw new Error('_bindDrawParamGeometry: Position buffer must not have size of 0'); + } + + // Get vertex count from position buffer. + const vertexCount = positionBuffer.size / positionBuffer.stride; + /** Create BufferGeometry. */ + const geometry = new THREE.BufferGeometry(); + // Bind index data. + const indexPtr = drawParam.primitiveParam.pIndexBuffer / 2; + const indexCount = drawParam.primitiveParam.indexCount; + const indices = module.HEAPU16.subarray(indexPtr, indexPtr + indexCount); + geometry.setIndex(new THREE.Uint16BufferAttribute(indices, 1)); + // Add attribute data. + for (const typeStr in attributes) { + const buffer = attributes[typeStr]; + const type = parseInt(typeStr); + // Skip disabled attributes that have size of 0. + if (buffer.size === 0) { + continue; + } + + switch (type) { + case FFLAttributeBufferType.POSITION: { + if (buffer.stride === 16) { + // 3 floats, last 4 bytes unused. + /** float data type */ + const ptr = buffer.ptr / 4; + const data = module.HEAPF32.subarray(ptr, ptr + (vertexCount * 4)); + const interleavedBuffer = new THREE.InterleavedBuffer(data, 4); + // Only works on Three.js r109 and above (previously used addAttribute which can be remapped) + geometry.setAttribute('position', new THREE.InterleavedBufferAttribute(interleavedBuffer, 3, 0)); + // ^^ Selectively use first three elements only. + } else if (buffer.stride === 6) { + /** half-float data type */ + const ptr = buffer.ptr / 2; + const data = module.HEAPU16.subarray(ptr, ptr + (vertexCount * 3)); + geometry.setAttribute('position', new THREE.Float16BufferAttribute(data, 3)); + } else { + unexpectedStride(typeStr, buffer.stride); + } + break; + } + case FFLAttributeBufferType.NORMAL: { + // Either int8 or 10_10_10_2 + // const data = module.HEAP32.subarray(buffer.ptr / 4, buffer.ptr / 4 + vertexCount); + // const buf = gl.createBuffer(); + // gl.bindBuffer(gl.ARRAY_BUFFER, buf); + // gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); + // // Bind vertex type GL_INT_2_10_10_10_REV/ / 0x8D9F. + // geometry.setAttribute('normal', new THREE.GLBufferAttribute(buf, 0x8D9F, 4, 4)); + const data = module.HEAP8.subarray(buffer.ptr, buffer.ptr + buffer.size); + geometry.setAttribute('normal', new THREE.Int8BufferAttribute(data, buffer.stride, true)); + break; + } + case FFLAttributeBufferType.TANGENT: { + // Int8 + const data = module.HEAP8.subarray(buffer.ptr, buffer.ptr + buffer.size); + geometry.setAttribute('tangent', new THREE.Int8BufferAttribute(data, buffer.stride, true)); + break; + } + case FFLAttributeBufferType.TEXCOORD: { + if (buffer.stride === 8) { + /** float data type */ + const ptr = buffer.ptr / 4; + const data = module.HEAPF32.subarray(ptr, ptr + (vertexCount * 2)); + geometry.setAttribute('uv', new THREE.Float32BufferAttribute(data, 2)); + } else if (buffer.stride === 4) { + /** half-float data type */ + const ptr = buffer.ptr / 2; + const data = module.HEAPU16.subarray(ptr, ptr + (vertexCount * 2)); + geometry.setAttribute('uv', new THREE.Float16BufferAttribute(data, 2)); + } else { + unexpectedStride(typeStr, buffer.stride); + } + break; + } + case FFLAttributeBufferType.COLOR: { + // Uint8 + + // Use default value if it does not exist. + // NOTE: Does not handle values for u_color other + // than the default 0/0/0/1 (custom u_parameter_mode) + if (buffer.stride === 0) { + break; + } + // Use "_color" because NOTE this is what the FFL-Testing exports and existing shaders do + const data = module.HEAPU8.subarray(buffer.ptr, buffer.ptr + buffer.size); + geometry.setAttribute('_color', new THREE.Uint8BufferAttribute(data, buffer.stride, true)); + break; + } + } + } + return geometry; +} + +/** + * Retrieves a texture from ModulateParam. + * Does not assign texture for faceline or mask types. + * @param {FFLModulateParam} modulateParam - drawParam.modulateParam. + * @param {TextureManager} textureManager - The {@link TextureManager} instance + * for which to look for the texture referenced. + * @returns {import('three').Texture|null} The texture if found. + * @throws {Error} Throws if pTexture2D refers to a texture that was not found in the TextureManager + * @package + */ +function _getTextureFromModulateParam(modulateParam, textureManager) { + // Only assign texture if pTexture2D is not null. + if (!modulateParam.pTexture2D || + // The pointer will be set to just "1" for + // faceline and mask textures that are supposed + // to be targets (FFL_TEXTURE_PLACEHOLDER, FFLI_RENDER_TEXTURE_PLACEHOLDER) + modulateParam.pTexture2D === 1) { + return null; // No texture to bind. + } + const texturePtr = modulateParam.pTexture2D; + const texture = textureManager.get(texturePtr); + if (!texture) { + throw new Error(`_getTextureFromModulateParam: Texture not found for ${texturePtr}.`); + } + // Selective apply mirrored repeat (not supported on NPOT/mipmap textures for WebGL 1.0) + const applyMirrorTypes = [ + FFLModulateType.SHAPE_FACELINE, FFLModulateType.SHAPE_CAP, FFLModulateType.SHAPE_GLASS]; + // ^^ Faceline, cap, and glass. NOTE that faceline texture won't go through here + if (applyMirrorTypes.indexOf(modulateParam.type) !== -1) { + texture.wrapS = THREE.MirroredRepeatWrapping; + texture.wrapT = THREE.MirroredRepeatWrapping; + texture.needsUpdate = true; + } + return texture; +} + +/** + * Retrieves blending parameters based on the FFLModulateType. + * Will only actually return anything for mask and faceline shapes. + * @param {FFLModulateType} modulateType - The modulate type. + * @param {FFLModulateMode} [modulateMode] - The modulate mode, used to + * differentiate body/pants modulate types from mask modulate types. + * @returns {Object} An object containing blending parameters for the Three.js material constructor, or an empty object. + * @throws {Error} Unknown modulate type + * @package + */ +function _getBlendOptionsFromModulateType(modulateType, modulateMode) { + /* + if (modulateType >= FFLModulateType.SHAPE_FACELINE && + modulateType <= FFLModulateType.SHAPE_CAP) { + // Opaque (DrawOpa) + // glTF alphaMode: OPAQUE + return { + blending: THREE.CustomBlending, + blendSrcAlpha: THREE.SrcAlphaFactor, + blendDstAlpha: THREE.OneFactor + }; + } else if (modulateType >= FFLModulateType.SHAPE_MASK && + modulateType <= FFLModulateType.SHAPE_GLASS) { + // Translucent (DrawXlu) + // glTF alphaMode: MASK (TEXTURE_DIRECT), or BLEND (LUMINANCE_ALPHA)? + return { + blending: THREE.CustomBlending, + blendSrc: THREE.SrcAlphaFactor, + blendDst: THREE.OneMinusSrcAlphaFactor, + blendDstAlpha: THREE.OneFactor, + // transparent: true + depthWrite: false // kept on inside of LUTShaderMaterial + }; + } else + */ + if (modulateMode !== 0 && modulateType >= FFLModulateType.SHAPE_MAX && + modulateType <= FFLModulateType.MOLE) { + // Mask Textures + return { + blending: THREE.CustomBlending, + blendSrc: THREE.OneMinusDstAlphaFactor, + blendSrcAlpha: THREE.SrcAlphaFactor, + blendDst: THREE.DstAlphaFactor + }; + } else if (modulateMode !== 0 && modulateType >= FFLModulateType.FACE_MAKE && + modulateType <= FFLModulateType.FILL) { + // Faceline Texture + return { + blending: THREE.CustomBlending, + blendSrc: THREE.SrcAlphaFactor, + blendDst: THREE.OneMinusSrcAlphaFactor, + blendSrcAlpha: THREE.OneFactor, + blendDstAlpha: THREE.OneFactor + }; + } + return {}; + // No blending options needed. + // else { + // throw new Error(`_getBlendOptionsFromModulateType: Unknown modulate type: ${modulateType}`); + // } +} + +/* eslint-disable jsdoc/require-returns-type -- Allow TS to predict return type. */ +/** + * Returns an object of parameters for a Three.js material constructor, based on {@link FFLModulateParam}. + * @param {FFLModulateParam} modulateParam - Property `modulateParam` of {@link FFLDrawParam}. + * @param {Module} module - The Emscripten module for accessing color pointers in heap. + * @param {boolean} [forFFLMaterial] - Whether or not to include modulateMode/Type parameters for material parameters. + * @returns Parameters for creating a Three.js material. + * @package + */ +function _applyModulateParam(modulateParam, module, forFFLMaterial = true) { + /* eslint-enable jsdoc/require-returns-type -- Allow TS to predict return type. */ + // Apply constant colors. + /** @type {import('three').Color|Array|null} */ + let color = null; + + /** + * Single constant color. + * @type {FFLColor|null} + */ + let color4 = null; + const f32 = module.HEAPF32; + // If both pColorG and pColorB are provided, combine them into an array. + if (modulateParam.pColorG !== 0 && modulateParam.pColorB !== 0) { + color = [ + _getFFLColor3(_getFFLColor(modulateParam.pColorR, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorG, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorB, f32)) + ]; + + if ( + self.eyeScleraHack + && modulateParam.type === 12) { + color = [ + _getFFLColor3(_getFFLColor(modulateParam.pColorR, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorB, f32)), + _getFFLColor3(_getFFLColor(modulateParam.pColorB, f32)) + ]; + } + } else if (modulateParam.pColorR !== 0) { + // Otherwise, set it as a single color. + color4 = _getFFLColor(modulateParam.pColorR, f32); + color = _getFFLColor3(color4); + } + + // Use opacity from single pColorR (it's only 0 for "fill" 2D plane) + const opacity = color4 ? color4.a : 1.0; + // Otherwise use 1.0, which is the opacity used pretty much everywhere. + + // Set transparent property for Xlu/mask and higher. + const transparent = modulateParam.type >= FFLModulateType.SHAPE_MASK; + + // Disable lighting if this is a 2D plane (mask/faceline) and not opaque (body/pants). + const lightEnable = !(modulateParam.type >= FFLModulateType.SHAPE_MAX && + modulateParam.mode !== FFLModulateMode.CONSTANT); + + /** Do not include the parameters if forFFLMaterial is false. */ + const modulateModeType = forFFLMaterial + ? { + modulateMode: modulateParam.mode, + modulateType: modulateParam.type // need this set before color. + } + : {}; + + // Not applying map here, that happens in _getTextureFromModulateParam. + const param = Object.assign(modulateModeType, { + // Common Three.js material parameters. + color: color, + opacity: opacity, + transparent: transparent, + // Depth writing is disabled for DrawXlu stage however + // it is kept enabled in LUTShaderMaterial because its + // alpha testing chooses to not write depth. Since we are + // disabling it anyway, that means shapes NEED to be in order + depthWrite: !transparent, + + // Apply blending options (for mask/faceline) based on modulateType. + ..._getBlendOptionsFromModulateType(modulateParam.type, modulateParam.mode) + }); + + // only for mask/faceline which should not be drawn in non-ffl materials: + if (!lightEnable) { + // Only set lightEnable if it is not default. + /** @type {Object} */ (param).lightEnable = lightEnable; + } + return param; +} + +/** + * Dereferences a pointer to FFLColor. + * @param {number} colorPtr - The pointer to the color. + * @param {Float32Array} heapf32 - HEAPF32 buffer view within {@link Module}. + * @returns {FFLColor} The converted Vector4. + * @throws {Error} Received null pointer + */ +function _getFFLColor(colorPtr, heapf32) { + if (!colorPtr) { + throw new Error('_getFFLColor: Received null pointer'); + } + // Assign directly from HEAPF32. + const colorData = heapf32.subarray(colorPtr / 4, colorPtr / 4 + 4); + return { r: colorData[0], g: colorData[1], b: colorData[2], a: colorData[3] }; +} + +/** + * Creates a THREE.Color from {@link FFLColor}. + * @param {FFLColor} color - The {@link FFLColor} object.. + * @returns {import('three').Color} The converted color. + */ +function _getFFLColor3(color) { + return new THREE.Color(color.r, color.g, color.b); +} + +/** + * Applies transformations in pAdjustMatrix within a {@link FFLDrawParam} to a mesh. + * @param {number} pMtx - Pointer to rio::Matrix34f. + * @param {import('three').Object3D} mesh - The mesh to apply transformations to. + * @param {Float32Array} heapf32 - HEAPF32 buffer view within {@link Module}. + * @package + */ +function _applyAdjustMatrixToMesh(pMtx, mesh, heapf32) { + // Assumes pMtx !== 0. + const ptr = pMtx / 4; + /** sizeof(rio::BaseMtx34f) */ + const m = heapf32.slice(ptr, ptr + (0x30 / 4)); + // console.debug('drawParamToMesh: shape has pAdjustMatrix: ', m); + /** + * Creates a THREE.Matrix4 from a 3x4 row-major matrix array. + * @param {Array|Float32Array} m - The array that makes up the 3x4 matrix, expected to have 12 elements. + * @returns {import('three').Matrix4} The converted matrix. + */ + function matrixFromRowMajor3x4(m) { + const matrix = new THREE.Matrix4(); + // Convert from rio::BaseMtx34f/row-major to column-major. + matrix.set( + m[0], m[4], m[8], m[3], + m[1], m[5], m[9], m[7], + m[2], m[6], m[10], m[11], + 0, 0, 0, 1 + ); + return matrix; + } + // Create a matrix from the array. + const matrix = matrixFromRowMajor3x4(m); + + // Set position and scale. FFLiAdjustShape does not set rotation. + mesh.scale.setFromMatrixScale(matrix); + mesh.position.setFromMatrixPosition(matrix); + // Account for flipped X scale (setFromMatrixScale doesn't?) + if (matrix.elements[0] === -1) { + mesh.scale.x = -1; + } +} + +// // --------------------------------------------------------------------- +// // CharModel Render Textures +// // --------------------------------------------------------------------- +// TODO PATH: src/CharModelTextures.js + +// ---------------- initCharModelTextures(charModel, renderer) ---------------- +/** + * Initializes textures (faceline and mask) for a CharModel. + * Calls private functions to draw faceline and mask textures. + * At the end, calls setExpression to update the mask texture. + * Note that this is a separate function due to needing renderer parameter. + * @param {CharModel} charModel - The CharModel instance. + * @param {import('three').WebGLRenderer} renderer - The Three.js renderer. + * @param {MaterialConstructor} materialClass - The material class (e.g., FFLShaderMaterial). + * @throws {Error} Throws if the type of `renderer` is unexpected. + */ +function initCharModelTextures(charModel, renderer, materialClass = charModel._materialClass) { + if (!(renderer instanceof THREE.WebGLRenderer) && + renderer['isWebGPURenderer'] === undefined) { // Accounting for future WebGPURenderer support. + throw new Error('initCharModelTextures: renderer is an invalid or unexpected type.'); + } + const module = charModel._module; + // Set material class for render textures. + charModel._materialTextureClass = materialClass; + + const textureTempObject = charModel._getTextureTempObject(); + // Draw faceline texture if applicable. + _drawFacelineTexture(charModel, textureTempObject, renderer, module, materialClass); + + // Warn if renderer.alpha is not set to true. + const clearAlpha = renderer.getClearAlpha(); + (clearAlpha !== 0) && renderer.setClearAlpha(0); // Override clearAlpha to 0. + + // Draw mask textures for all expressions. + _drawMaskTextures(charModel, textureTempObject, renderer, module, materialClass); + // Finalize CharModel, deleting and freeing it. + charModel._finalizeCharModel(); + // Update the expression to refresh the mask texture. + charModel.setExpression(charModel.expression); + // Set clearAlpha back. + (clearAlpha !== 0) && renderer.setClearAlpha(clearAlpha); + + // convert textures + if (!matSupportsFFL(charModel._materialClass)) { + if (!matSupportsFFL(charModel._materialTextureClass)) { + console.warn('initCharModelTextures: charModel._materialClass does not support modulateMode (no getter), but the _materialTextureClass is either the same or also does not support modulateMode so textures will look wrong'); + } else { + convertModelTexturesToRGBA(charModel, renderer, charModel._materialTextureClass); + } + } +} + +/** + * Draws and applies the faceline texture for the CharModel. + * @param {CharModel} charModel - The CharModel. + * @param {FFLiTextureTempObject} textureTempObject - The FFLiTextureTempObject containing faceline DrawParams. + * @param {import('three').WebGLRenderer} renderer - The renderer. + * @param {Module} module - The Emscripten module. + * @param {MaterialConstructor} materialClass - The material class (e.g., FFLShaderMaterial). + * @package + */ +function _drawFacelineTexture(charModel, textureTempObject, renderer, module, materialClass) { + // Invalidate faceline texture before drawing (ensures correctness) + const facelineTempObjectPtr = charModel._getFacelineTempObjectPtr(); + module._FFLiInvalidateTempObjectFacelineTexture(facelineTempObjectPtr); + // Gather the drawParams that make up the faceline texture. + const drawParams = [ + textureTempObject.facelineTexture.drawParamFaceMake, + textureTempObject.facelineTexture.drawParamFaceLine, + textureTempObject.facelineTexture.drawParamFaceBeard + ].filter(dp => dp && dp.modulateParam.pTexture2D !== 0); + // Note that for faceline DrawParams to not be empty, + // it must have a texture. For other DrawParams to not + // be empty they simply need to have a non-zero index count. + if (drawParams.length === 0) { + console.debug('_drawFacelineTexture: Skipping faceline texture.'); + return; + } + + // Get the faceline color from CharModel. + const bgColor = charModel.facelineColor; + // Create an offscreen scene. + const { scene: offscreenScene } = createSceneFromDrawParams(drawParams, bgColor, + materialClass, charModel._module, charModel._textureManager); + // Render scene to texture. + const width = charModel._getResolution() / 2; + const height = charModel._getResolution(); + // Configure the RenderTarget for no depth/stencil. + const options = { + depthBuffer: false, + stencilBuffer: false, + // Use mirrored repeat wrapping. + wrapS: THREE.MirroredRepeatWrapping, + wrapT: THREE.MirroredRepeatWrapping + }; + const target = createAndRenderToTarget(offscreenScene, + getIdentCamera(), renderer, width, height, options); + + console.debug(`Creating target ${target.texture.id} for faceline`); + + // Apply texture to CharModel. + _setFaceline(charModel, target); + // Delete temp faceline object to free resources. + module._FFLiDeleteTempObjectFacelineTexture(facelineTempObjectPtr, + charModel._ptr, charModel._model.charModelDesc.resourceType); + disposeMeshes(offscreenScene); // Dispose meshes in scene. +} + +/** + * Iterates through mask textures and draws each mask texture. + * @param {CharModel} charModel - The CharModel. + * @param {FFLiTextureTempObject} textureTempObject - The temporary texture object. + * @param {import('three').WebGLRenderer} renderer - The renderer. + * @param {Module} module - The Emscripten module. + * @param {MaterialConstructor} materialClass - The material class (e.g., FFLShaderMaterial). + * @package + */ +function _drawMaskTextures(charModel, textureTempObject, renderer, module, materialClass) { + const maskTempObjectPtr = charModel._getMaskTempObjectPtr(); + const expressionFlagPtr = charModel._getExpressionFlagPtr(); + + // Collect all scenes and only dispose them at the end. + /** @type {Array} */ + const scenes = []; + + // Iterate through pRenderTextures to find out which masks are needed. + for (let i = 0; i < charModel._model.maskTextures.pRenderTextures.length; i++) { + // pRenderTexture will be set to 1 if mask is meant to be drawn there. + if (charModel._model.maskTextures.pRenderTextures[i] === 0) { + continue; + } + const rawMaskDrawParamPtr = textureTempObject.maskTextures.pRawMaskDrawParam[i]; + const rawMaskDrawParam = FFLiRawMaskDrawParam.unpack( + module.HEAPU8.subarray(rawMaskDrawParamPtr, + rawMaskDrawParamPtr + FFLiRawMaskDrawParam.size)); + module._FFLiInvalidateRawMask(rawMaskDrawParamPtr); + + const { target, scene } = _drawMaskTexture(charModel, + rawMaskDrawParam, renderer, module, materialClass); + console.debug(`Creating target ${target.texture.id} for mask ${i}`); + charModel._maskTargets[i] = target; + + scenes.push(scene); + } + + // Some texures are shared which is why this + // needs to be done given that disposeMeshes + // unconditionally deletes textures. + scenes.forEach((scene) => { + disposeMeshes(scene); + }); + + module._FFLiDeleteTempObjectMaskTextures(maskTempObjectPtr, + expressionFlagPtr, charModel._model.charModelDesc.resourceType); + module._FFLiDeleteTextureTempObject(charModel._ptr); +} + +/** + * Draws a single mask texture based on a RawMaskDrawParam. + * Note that the caller needs to dispose meshes within the returned scene. + * @param {CharModel} charModel - The CharModel. + * @param {FFLiRawMaskDrawParam} rawMaskParam - The RawMaskDrawParam. + * @param {import('three').WebGLRenderer} renderer - The renderer. + * @param {Module} module - The Emscripten module. + * @param {MaterialConstructor} materialClass - The material class (e.g., FFLShaderMaterial). + * @returns {{target: import('three').RenderTarget, scene: import('three').Scene}} + * The RenderTarget and scene of this mask texture. + * @throws {Error} All DrawParams are empty. + * @package + */ +function _drawMaskTexture(charModel, rawMaskParam, renderer, module, materialClass) { + const drawParams = [ + rawMaskParam.drawParamRawMaskPartsMustache[0], + rawMaskParam.drawParamRawMaskPartsMustache[1], + rawMaskParam.drawParamRawMaskPartsMouth, + rawMaskParam.drawParamRawMaskPartsEyebrow[0], + rawMaskParam.drawParamRawMaskPartsEyebrow[1], + rawMaskParam.drawParamRawMaskPartsEye[0], + rawMaskParam.drawParamRawMaskPartsEye[1], + rawMaskParam.drawParamRawMaskPartsMole + ].filter(dp => dp && dp.primitiveParam.indexCount !== 0); + if (drawParams.length === 0) { + throw new Error('_drawMaskTexture: All DrawParams are empty.'); + } + // Configure the RenderTarget for no depth/stencil. + const options = { + depthBuffer: false, + stencilBuffer: false + }; + // Create an offscreen scene with no background (for 2D mask rendering). + const { scene: offscreenScene } = createSceneFromDrawParams(drawParams, + null, materialClass, module, charModel._textureManager); + const width = charModel._getResolution(); + + const target = createAndRenderToTarget(offscreenScene, + getIdentCamera(), renderer, width, width, options); + + return { target, scene: offscreenScene }; + // Caller needs to dispose meshes in scene. +} + +/** + * Sets the faceline texture of the given CharModel from the RenderTarget. + * @param {CharModel} charModel - The CharModel instance. + * @param {import('three').RenderTarget} target - RenderTarget for the faceline texture. + * @throws {Error} target must be a valid THREE.RenderTarget with "texture" property + * and CharModel must be initialized with OPA_FACELINE in meshes. + * @package + */ +function _setFaceline(charModel, target) { + if (!target || !target.texture) { + throw new Error('setFaceline: passed in RenderTarget is invalid'); + } + charModel._facelineTarget = target; // Store for later disposal. + const mesh = charModel._facelineMesh; + if (!mesh || !(mesh instanceof THREE.Mesh)) { + throw new Error('setFaceline: faceline shape does not exist'); + } + // Update texture and material. + /** @type {import('three').Texture&{_target: import('three').RenderTarget}} */ (target.texture) + ._target = target; + /** @type {import('three').MeshBasicMaterial} */ (mesh.material).map = target.texture; + /** @type {import('three').MeshBasicMaterial} */ (mesh.material).needsUpdate = true; +} + +// // --------------------------------------------------------------------- +// // Modulate Mode Texture Conversion Utilities +// // --------------------------------------------------------------------- +// TODO PATH: src/ModulateTextureConversion.js + +/** + * Takes the texture in `material` and draws it using `materialTextureClass`, using + * the modulateMode property in `userData`, using the `renderer` and sets it back + * in the `material`. So it converts a swizzled (using modulateMode) texture to RGBA. + * NOTE: Does NOT handle mipmaps. But these textures + * usually do not have mipmaps anyway so it's fine + * @param {import('three').WebGLRenderer} renderer - The renderer. + * @param {import('three').MeshBasicMaterial} material - The original material of the mesh. + * @param {Object} userData - The original mesh.geometry.userData to get modulateMode/Type from. + * @param {MaterialConstructor} materialTextureClass - The material class that draws the new texture. + * @returns {import('three').RenderTarget} The RenderTarget of the final RGBA texture. + * @throws {Error} material.map is null or undefined + */ +function _texDrawRGBATarget(renderer, material, userData, materialTextureClass) { + const plane = new THREE.PlaneGeometry(2, 2); + const scene = new THREE.Scene(); + // Create mesh that has color but alpha value of 0. + const bgClearRGBMesh = new THREE.Mesh(plane, + new THREE.MeshBasicMaterial({ + color: material.color, + transparent: true, + opacity: 0.0, + blending: THREE.NoBlending + }) + ); + scene.add(bgClearRGBMesh); // Must be drawn first. + + if (!material.map) { + throw new Error('_texDrawRGBATarget: material.map is null or undefined'); + } + /** Shortcut to the existing texture. */ + const tex = material.map; + // This material is solely for the texture itself and not the shape. + // It actually does not need color set on it, or modulate type (blending) + const texMat = new materialTextureClass({ + map: tex, + modulateMode: userData.modulateMode, + color: material.color, + lightEnable: false + }); + texMat.blending = THREE.NoBlending; + texMat.transparent = true; + const textureMesh = new THREE.Mesh(plane, texMat); + scene.add(textureMesh); + + const target = createAndRenderToTarget(scene, + getIdentCamera(false), renderer, + tex.image.width, tex.image.height, { + wrapS: tex.wrapS, wrapT: tex.wrapT, // Preserve wrap. + depthBuffer: false, stencilBuffer: false + }); + + /** @type {import('three').Texture&{_target: import('three').RenderTarget}} */ (target.texture) + ._target = target; + + // Dispose previous texture and replace with this one. + material.map.dispose(); + material.map = target.texture; + // Set color to default and modulateMode to TEXTURE_DIRECT. + material.color = new THREE.Color(1, 1, 1); + userData.modulateMode = 1; + + return target; // Caller is responsible for disposing the RenderTarget. +} + +/** + * Converts a CharModel's textures, including ones that may be using swizzled modulateMode + * textures that are R/RG format, to RGBA and also applying colors, so that + * the CharModel can be rendered without a material that supports modulateMode. + * @param {CharModel} charModel - The CharModel whose textures to convert. + * @param {import('three').WebGLRenderer} renderer - The renderer. + * @param {MaterialConstructor} materialTextureClass - The material class that draws the new texture. + * @throws {Error} charModel.meshes is null + */ +function convertModelTexturesToRGBA(charModel, renderer, materialTextureClass) { + const convertTextureForTypes = [ + FFLModulateType.SHAPE_CAP, FFLModulateType.SHAPE_NOSELINE, FFLModulateType.SHAPE_GLASS]; + if (!charModel.meshes) { + throw new Error('convertModelTexturesToRGBA: charModel.meshes is null.'); + } + charModel.meshes.traverse((mesh) => { + if (!(mesh instanceof THREE.Mesh) || + !mesh.geometry.userData.modulateType || + !mesh.material.map || + convertTextureForTypes.indexOf(mesh.geometry.userData.modulateType) === -1 + ) { + return; + } + const target = _texDrawRGBATarget(renderer, mesh.material, + mesh.geometry.userData, materialTextureClass); + // HACK?: Push to _maskTargets so that it will be disposed. + charModel._maskTargets.push(target); + }); +} + +/** + * Converts all textures in the CharModel that are associated + * with RenderTargets into THREE.DataTextures, so that the + * CharModel can be exported using e.g., GLTFExporter. + * @param {CharModel} charModel - The CharModel whose textures to convert. + * @param {import('three').WebGLRenderer} renderer - The renderer. + * @throws {Error} charModel.meshes or mesh.material.map is null, texture is not THREE.RGBAFormat + */ +function convModelTargetsToDataTex(charModel, renderer) { + if (!charModel.meshes) { + throw new Error('convModelTargetsToDataTex: charModel.meshes is null.'); + } + charModel.meshes.traverse((mesh) => { + if (!(mesh instanceof THREE.Mesh) || !mesh.material.map) { + return; + } + const tex = mesh.material.map; + if (tex.format !== THREE.RGBAFormat) { + throw new Error('convModelTargetsToDataTex: found a texture that is not of format THREE.RGBAFormat, but, this function is only meant to be used if all textures in CharModel meshes are RGBA (so render targets)...'); + } + /** RGBA */ + const data = new Uint8Array(tex.image.width * tex.image.height * 4); + const target = /** @type {import('three').RenderTarget|null|undefined} */ tex._target; + if (!target) { + throw new Error('convModelTargetsToDataTex: mesh.material.map (texture)._target is null or undefined.'); + } + renderer.readRenderTargetPixels(target, 0, 0, + tex.image.width, tex.image.height, data); + // Construct new THREE.DataTexture from the read data. + // So... draw the texture, download it out, and upload it again. + const dataTex = new THREE.DataTexture(data, tex.image.width, + tex.image.height, THREE.RGBAFormat, THREE.UnsignedByteType); + // Copy wrap and filtering options. + dataTex.wrapS = tex.wrapS; + dataTex.wrapT = tex.wrapT; + dataTex.minFilter = tex.minFilter; + dataTex.magFilter = tex.magFilter; + + dataTex.needsUpdate = true; + mesh.material.map = dataTex; + }); + // The original render targets are no longer needed now, dispose them. + charModel.disposeTargets(); + // Note that expressions cannot be set on the CharModel anymore. +} + +// // --------------------------------------------------------------------- +// // TextureShaderMaterial Class +// // --------------------------------------------------------------------- +// TODO PATH: src/TextureShaderMaterial.js + +/** + * A material class that renders FFL swizzled (modulateMode) textures. + * Has no lighting whatsoever, just meant to render 2D planes. + * @augments {THREE.ShaderMaterial} + */ +class TextureShaderMaterial extends THREE.ShaderMaterial { + /** + * @typedef {Object} TextureShaderMaterialParameters + * @property {FFLModulateMode} [modulateMode] - Modulate mode. + * @property {FFLModulateType} [modulateType] - Modulate type. + * @property {import('three').Color|Array} [color] - + * Constant color assigned to u_const1/2/3 depending on single or array. + */ + + /** + * The material constructor. + * @param {import('three').ShaderMaterialParameters & TextureShaderMaterialParameters} [options] - + * Parameters for the material. + */ + constructor(options = {}) { + // Set default uniforms. + /** @type {Object} */ + const uniforms = { + opacity: { value: 1.0 } + }; + const blankMatrix3 = { value: new THREE.Matrix3() }; + if (Number(THREE.REVISION) < 151) { + uniforms.uvTransform = blankMatrix3; + } else { + uniforms.mapTransform = blankMatrix3; + } + + // Construct the ShaderMaterial using the shader source. + super({ + vertexShader: /* glsl */` + #include + #include + + void main() { + #include + #include + #include + }`, + fragmentShader: /* glsl */` + #include + #include + #include + uniform vec3 diffuse; + uniform float opacity; + uniform int modulateMode; + uniform vec3 color1; + uniform vec3 color2; + + void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + + #include + #include + #ifdef USE_MAP + if (modulateMode == 2) { // FFL_MODULATE_MODE_RGB_LAYERED + diffuseColor = vec4( + diffuse.rgb * sampledDiffuseColor.r + + color1.rgb * sampledDiffuseColor.g + + color2.rgb * sampledDiffuseColor.b, + sampledDiffuseColor.a + ); + } else if (modulateMode == 3) { // FFL_MODULATE_MODE_ALPHA + diffuseColor = vec4( + diffuse.rgb * sampledDiffuseColor.r, + sampledDiffuseColor.r + ); + } else if (modulateMode == 4) { // FFL_MODULATE_MODE_LUMINANCE_ALPHA + diffuseColor = vec4( + diffuse.rgb * sampledDiffuseColor.g, + sampledDiffuseColor.r + ); + } else if (modulateMode == 5) { // FFL_MODULATE_MODE_ALPHA_OPA + diffuseColor = vec4( + diffuse.rgb * sampledDiffuseColor.r, + 1.0 + ); + } + #endif + + // avoids little outline around mask elements + if (modulateMode != 0 && diffuseColor.a == 0.0) { // FFL_MODULATE_MODE_CONSTANT + discard; + } + + gl_FragColor = diffuseColor; + //#include + }`, + uniforms: uniforms + }); + // Set defaults so that they are valid parameters. + this.lightEnable = false; + this.modulateType = 0; + + // Use the setters to set the rest of the uniforms. + this.setValues(options); + } + + /** + * Gets the constant color (diffuse) uniform as THREE.Color. + * @returns {import('three').Color|null} The constant color, or null if it is not set. + */ + get color() { + return this.uniforms.diffuse ? this.uniforms.diffuse.value : null; + } + + /** + * Sets the constant color uniforms from THREE.Color. + * @param {import('three').Color|Array} value - + * The constant color (diffuse), or multiple (diffuse/color1/color2) to set the uniforms for. + */ + set color(value) { + // Set an array of colors, assumed to have 3 elements. + if (Array.isArray(value)) { + // Assign multiple color instances. + this.uniforms.diffuse = { value: value[0] }; + this.uniforms.color1 = { value: value[1] }; + this.uniforms.color2 = { value: value[2] }; + return; + } + // Set single color as THREE.Color, defaulting to white. + const color3 = value ? value : new THREE.Color(1.0, 1.0, 1.0); + /** @type {import('three').Color} */ + this._color3 = color3; + this.uniforms.diffuse = { value: color3 }; + } + + /** @returns {FFLModulateMode|null}The modulateMode value, or null if it is unset. */ + get modulateMode() { + return this.uniforms.modulateMode ? this.uniforms.modulateMode.value : null; + } + + /** @param {FFLModulateMode} value - The new modulateMode value. */ + set modulateMode(value) { + this.uniforms.modulateMode = { value: value }; + } + + /** @returns {import('three').Texture|null}The texture map, or null if it is unset. */ + get map() { + return this.uniforms.map ? this.uniforms.map.value : null; + } + + /** @param {import('three').Texture} value - The new texture map. */ + set map(value) { + this.uniforms.map = { value: value }; + } +} + +// // --------------------------------------------------------------------- +// // Geometry Attribute Conversion Utilities +// // --------------------------------------------------------------------- +// TODO PATH: src/GeometryConversion.js + +/** + * Modifies a BufferGeometry in place to be compatible with glTF. + * It currently: deinterleaves attributes, converts half-float to float, + * and converts signed integer formats (not uint8 for color) to float. + * Attributes named "normal" are reduced to three components. + * @param {import('three').BufferGeometry} geometry - The BufferGeometry to modify in place. + * @throws {Error} Throws if an unsupported attribute format is encountered. + */ +function convGeometryToGLTFCompatible(geometry) { + if (!(geometry instanceof THREE.BufferGeometry) || !geometry.attributes) { + throw new Error('convGeometryToGLTFCompatible: geometry is not BufferGeometry with attributes.'); + } + + // Process each attribute in the geometry. + for (const [key, attr] of Object.entries(geometry.attributes)) { + // If the attribute is interleaved, deinterleave it. + const bufferAttribute = attr instanceof THREE.InterleavedBufferAttribute + ? interleavedBufferAttributeToBufferAttribute(attr) + : attr; + const array = bufferAttribute.array; + const originalItemSize = bufferAttribute.itemSize; + const count = bufferAttribute.count; + + /** + * Size of the target attribute. Force vec3 for "normal". + * @type {number} + */ + const targetItemSize = key.toLowerCase() === 'normal' ? 3 : originalItemSize; + + /** @type {Float32Array|Uint8Array} */ let newArray; + /** Whether the value is normalized. False by default for float attributes. */ + let normalized = false; + + if (array instanceof Float32Array) { + // If already float32, only adjust components if needed. + newArray = targetItemSize === originalItemSize + ? array + : copyFloat32WithReducedComponents(array, count, originalItemSize, targetItemSize); + } else if (array instanceof Uint16Array) { + // Assume half-float values. Three.js >=160 is required for them. + const float32Full = convertHalfFloatArrayToFloat32(array); + newArray = targetItemSize === originalItemSize + ? float32Full + : copyFloat32WithReducedComponents(float32Full, + count, originalItemSize, targetItemSize); + } else if (array instanceof Int8Array) { + // Convert SNORM to float in the range [-1,1]. For normals, only use first 3 components. + newArray = convertSNORMToFloat32(array, count, originalItemSize, targetItemSize); + // normalized = true; // Normals should be normalized? + } else if (array instanceof Uint8Array) { + // Likely color data in UNORM, leave as-is. + newArray = array; + normalized = true; // Not converted to float. + } else { + throw new Error(`convGeometryToGLTFCompatible: Unsupported attribute data type for ${key}: ${array.constructor.name}`); + } + + // Also not sure if this will leak from the old attribute or not. (Don't think so) + geometry.setAttribute(key, new THREE.BufferAttribute(newArray, targetItemSize, normalized)); + } +} + +/** + * Deinterleaves an InterleavedBufferAttribute into a standalone BufferAttribute. + * @param {import('three').InterleavedBufferAttribute} attr - The interleaved attribute. + * @returns {import('three').BufferAttribute} A new BufferAttribute containing deinterleaved data. + */ +function interleavedBufferAttributeToBufferAttribute(attr) { + const { itemSize, count } = attr; + // eslint-disable-next-line jsdoc/valid-types -- TODO fix "syntax error in type" + const dest = new /** @type {{ new(length: number): * }} */ (attr.array.constructor) + (count * itemSize); + + for (let i = 0; i < count; i++) { + for (let j = 0; j < itemSize; j++) { + dest[i * itemSize + j] = attr.getComponent(i, j); + } + } + return new THREE.BufferAttribute(dest, itemSize); +} + +/** + * Creates a new Float32Array by copying only a subset of components per vertex. + * @param {Float32Array} src - The source Float32Array. + * @param {number} count - Number of vertices. + * @param {number} srcItemSize - Original components per vertex. + * @param {number} targetItemSize - Number of components to copy per vertex. + * @returns {Float32Array} A new Float32Array with reduced component count. + */ +function copyFloat32WithReducedComponents(src, count, srcItemSize, targetItemSize) { + const dst = new Float32Array(count * targetItemSize); + for (let i = 0; i < count; i++) { + for (let j = 0; j < targetItemSize; j++) { + dst[i * targetItemSize + j] = src[i * srcItemSize + j]; + } + } + return dst; +} + +/** + * Converts a 16-bit half-float value to a 32-bit float. + * @param {number} half - The half-float value. + * @returns {number} The corresponding 32-bit float value. + */ +function halfToFloat(half) { + const sign = (half & 0x8000) >> 15; + const exponent = (half & 0x7C00) >> 10; + const mantissa = half & 0x03FF; + + if (exponent === 0) { + // Subnormal number. + return (sign ? -1 : 1) * Math.pow(2, -14) * (mantissa / Math.pow(2, 10)); + } else if (exponent === 0x1F) { + // NaN or Infinity. + return mantissa ? NaN : ((sign ? -1 : 1) * Infinity); + } + // Normalized number. + return (sign ? -1 : 1) * + Math.pow(2, exponent - 15) * + (1 + mantissa / 1024); +} + +/** + * Converts a Uint16Array assumed to represent half-float values into a Float32Array. + * @param {Uint16Array} halfArray - The Uint16Array of half-float values. + * @returns {Float32Array} A Float32Array with converted float values. + */ +function convertHalfFloatArrayToFloat32(halfArray) { + const floatArray = new Float32Array(halfArray.length); + for (let i = 0; i < halfArray.length; i++) { + floatArray[i] = halfToFloat(halfArray[i]); + } + return floatArray; +} + +/** + * Converts an Int8Array of SNORM values to a Float32Array. + * If the targetItemSize is less than the original (e.g. for normals), only the first targetItemSize + * components of each vertex are copied. + * @param {Int8Array} src - The source Int8Array. + * @param {number} count - Number of vertices. + * @param {number} srcItemSize - Original number of components per vertex. + * @param {number} targetItemSize - Number of components per vertex for the output. + * @returns {Float32Array} A Float32Array with converted values. + */ +function convertSNORMToFloat32(src, count, srcItemSize, targetItemSize) { + const dst = new Float32Array(count * targetItemSize); + + for (let i = 0; i < count; i++) { + const baseIn = i * srcItemSize; + const baseOut = i * targetItemSize; + + if (targetItemSize === 4 && srcItemSize === 4) { + // Tangent case: normalize xyz, keep w + const x = src[baseIn] / 127; + const y = src[baseIn + 1] / 127; + const z = src[baseIn + 2] / 127; + const w = src[baseIn + 3] / 127; + + const mag = Math.sqrt(x * x + y * y + z * z) || 1; + + dst[baseOut] = x / mag; + dst[baseOut + 1] = y / mag; + dst[baseOut + 2] = z / mag; + dst[baseOut + 3] = w; + } else { + // General case: convert up to targetItemSize components directly + for (let j = 0; j < targetItemSize; j++) { + const val = src[baseIn + j]; + dst[baseOut + j] = val < 0 ? val / 128 : val / 127; + } + } + } + + return dst; +} + +// TODO: TODO: Below function is uSELESS because I didn't realize that +// the triangle winding thing had already been taken care of and that's +// the only reason the below function exists so it will promptly be removed next time I push + +/** + * Converts a {@link CharModel}'s geometry to be compatible with glTF (see {@link convGeometryToGLTFCompatible}) + * This function additionally reverses triangle winding for meshes using front culling (flipped hair). + * @param {CharModel} charModel - The CharModel whose mesh attributes to convert. + * @throws {Error} charModel.meshes is null + */ +function convModelToGLTFCompatible(charModel) { + /** + * Reverses the triangle winding in the given index array. + * It swaps the first and third index of every triangle. + * @param {THREE.TypedArray} indices - The index array to modify in place. + */ + function _reverseTriangleWinding(indices) { + for (let i = 0; i < indices.length; i += 3) { + const temp = indices[i]; + indices[i] = indices[i + 2]; + indices[i + 2] = temp; + } + } + + if (!charModel.meshes) { + throw new Error('convCharModelToGLTFCompatible: charModel.meshes is null.'); + } + charModel.meshes.traverse((node) => { + // Ensure this is a mesh with geometry. + if (!(node instanceof THREE.Mesh) || !(node.geometry instanceof THREE.BufferGeometry)) { + return; + } + // Convert geometry attributes to glTF compliant ones. + convGeometryToGLTFCompatible(node.geometry); + + // Check if the material side is set to THREE.BackSide (front face culling). + if (node.material && node.material.side === THREE.BackSide) { + if (!node.geometry.index) { + // Early return if there are no indices. + return; + } + _reverseTriangleWinding(node.geometry.index.array); // Reverse triangle winding. + // Update material and userData to front face culling. + node.material.side = THREE.FrontSide; + node.geometry.userData.cullMode = FFLCullMode.BACK; + } + }); +} + +// // --------------------------------------------------------------------- +// // Scene/Render Target Handling +// // --------------------------------------------------------------------- +// TODO PATH: src/RenderTargetUtils.js + +// TODO: private? +// ----- createSceneFromDrawParams(drawParams, bgColor, ...drawParamArgs) ----- +/** + * Creates an THREE.Scene from an array of drawParams, converting each + * to a new mesh. Used for one-time rendering of faceline/mask 2D planes. + * @param {Array} drawParams - Array of FFLDrawParam. + * @param {import('three').Color|null} bgColor - Optional background color. + * @param {[MaterialConstructor, Module, TextureManager|null]} drawParamArgs - Arguments to pass to drawParamToMesh. + * @returns {{scene: import('three').Scene, meshes: Array}} + * An object containing the created scene and an array of meshes. + */ +function createSceneFromDrawParams(drawParams, bgColor, ...drawParamArgs) { + const scene = new THREE.Scene(); + // For 2D plane rendering, set the background if provided. + scene.background = bgColor || null; + // TODO: use THREE.Group? + /** @type {Array} */ + const meshes = []; + drawParams.forEach((param) => { + const mesh = drawParamToMesh(param, ...drawParamArgs); + if (mesh) { + scene.add(mesh); + meshes.push(mesh); + } + }); + return { scene, meshes }; +} + +// TODO: private? +// -------------------------- getIdentCamera(flipY) -------------------------- +/** + * Returns an ortho camera that is effectively the same as + * if you used identity MVP matrix, for rendering 2D planes. + * @param {boolean} flipY - Flip the Y axis. Default is oriented for OpenGL. + * @returns {import('three').OrthographicCamera} The orthographic camera. + */ +function getIdentCamera(flipY = false) { + // Create an orthographic camera with bounds [-1, 1] in x and y. + const camera = new THREE.OrthographicCamera(-1, 1, + // Use [1, -1] except when using flipY. + (flipY ? -1 : 1), (flipY ? 1 : -1), 0.1, 10); + camera.position.z = 1; + return camera; +} + +// - createAndRenderToTarget(scene, camera, renderer, width, height, targetOptions) - +/** + * Creates a Three.js RenderTarget, renders the scene with + * the given camera, and returns the render target. + * @param {import('three').Scene} scene - The scene to render. + * @param {import('three').Camera} camera - The camera to use. + * @param {import('three').WebGLRenderer} renderer - The renderer. + * @param {number} width - Desired width of the target. + * @param {number} height - Desired height of the target. + * @param {Object} [targetOptions] - Optional options for the render target. + * @returns {import('three').RenderTarget} The render target (which contains .texture). + */ +function createAndRenderToTarget(scene, camera, renderer, width, height, targetOptions = {}) { + // Set default options for the RenderTarget. + const options = { + minFilter: THREE.LinearFilter, + magFilter: THREE.LinearFilter, + ...targetOptions + }; + + const renderTarget = /** @type {*} */ (renderer)['isWebGPURenderer'] === undefined + ? new THREE.WebGLRenderTarget(width, height, options) + : new THREE.RenderTarget(width, height, options); + // Get previous render target to switch back to. + const prevTarget = renderer.getRenderTarget(); + // Only works on Three.js r102 and above. + renderer.setRenderTarget( + /** @type {import('three').WebGLRenderTarget} */ (renderTarget)); // Set new target. + renderer.render(scene, camera); // Render. + renderer.setRenderTarget(prevTarget); // Set previous target. + return renderTarget; // This needs to be disposed when done. +} + +// -------------------------- disposeMeshes(target) -------------------------- +/** + * Disposes meshes in a {@link THREE.Object3D} and removes them from the {@link THREE.Scene} specified. + * @param {import('three').Scene|import('three').Object3D} group - The scene or group to dispose meshes from. + * @param {import('three').Scene} [scene] - The scene to remove the meshes from, if provided. + * @todo TODO: Rename to disposeGroup/Scene or something + */ +function disposeMeshes(group, scene) { + // Taken from: https://github.com/igvteam/spacewalk/blob/21c0a9da27f121a54e0cf6c0d4a23a9cf80e6623/js/utils/utils.js#L135C10-L135C29 + + /** + * Disposes a single material along with its texture map. + * @param {import('three').MeshBasicMaterial} material - The material with `map` property to dispose. + */ + function disposeMaterial(material) { + // Dispose texture in material. + if (material.map) { + // console.debug('Disposing texture ', child.material.map.id); + // If this was created by TextureManager + // then it overrides dispose() to also + // remove itself from the TextureManager map. + material.map.dispose(); + } + material.dispose(); // Dispose material itself. + } + + // Traverse all children of the scene/group/THREE.Object3D. + group.traverse((child) => { + if (!(child instanceof THREE.Mesh)) { + // Only dispose of meshes. + return; + } + // Dispose geometry, material, and texture. + if (child.geometry) { + child.geometry.dispose(); + } + + if (child.material) { + // Dispose depending on if it is an array or not. + Array.isArray(child.material) + // Assume that materials are compatible with THREE.MeshBasicMaterial for .map. + ? child.material.forEach((material) => { + disposeMaterial(/** @type {import('three').MeshBasicMaterial} */ (material)); + }) + : disposeMaterial(/** @type {import('three').MeshBasicMaterial} */(child.material)); + } + }); + + // If this is a scene, remove this group/Object3D from it. + if (scene && scene instanceof THREE.Scene) { + scene.remove(group); + } + + // Set group and its children to null to break references. + group.children = []; +} + +// // --------------------------------------------------------------------- +// // Export Scene/Texture To Image +// // --------------------------------------------------------------------- +// TODO PATH: src/ExportTexture.js + +/** + * Saves the current renderer state and returns an object to restore it later. + * @param {import('three').WebGLRenderer} renderer - The renderer to save state from. + * @returns {{target: import('three').WebGLRenderTarget|null, + * colorSpace: import('three').ColorSpace, size: import('three').Vector2}} + * The saved state object. + */ +function _saveRendererState(renderer) { + const size = new THREE.Vector2(); + renderer.getSize(size); + + return { + target: renderer.getRenderTarget(), + colorSpace: /** @type {import('three').ColorSpace} */ (renderer.outputColorSpace), + size + }; +} + +/** + * Restores a renderer's state from a saved state object. + * @param {import('three').WebGLRenderer} renderer - The renderer to restore state to. + * @param {{target: import('three').WebGLRenderTarget|null, + * colorSpace: import('three').ColorSpace, size: import('three').Vector2}} state - + * The saved state object. + */ +function _restoreRendererState(renderer, state) { + renderer.setRenderTarget(state.target); + renderer.outputColorSpace = state.colorSpace; + renderer.setSize(state.size.x, state.size.y, false); +} + +/** + * Copies the renderer's swapchain to a canvas. + * @param {import('three').WebGLRenderer} renderer - The renderer. + * @param {HTMLCanvasElement} [canvas] - Optional target canvas. If not provided, a new one is created. + * @returns {HTMLCanvasElement} The canvas containing the rendered output. + * @throws {Error} Throws if the canvas is defined but invalid. + */ +function _copyRendererToCanvas(renderer, canvas) { + const sourceCanvas = renderer.domElement; + // If the target canvas is not simply undefined, it's null, then error out. + if (canvas !== undefined && !(canvas instanceof HTMLCanvasElement)) { + throw new Error('copyRendererToCanvas: canvas is neither a valid canvas nor undefined.'); + } + const targetCanvas = canvas || document.createElement('canvas'); + targetCanvas.width = sourceCanvas.width; + targetCanvas.height = sourceCanvas.height; + // NOTE: Line below guarantees the canvas to be valid. + /** @type {CanvasRenderingContext2D} */ (targetCanvas.getContext('2d')) + .drawImage(sourceCanvas, 0, 0); + + return targetCanvas; +} + +// --------------- textureToCanvas(texture, renderer, options) --------------- +/** + * Renders a texture to a canvas. If no canvas is provided, a new one is created. + * @param {import('three').Texture} texture - The texture to render. + * @param {import('three').WebGLRenderer} renderer - The renderer. + * @param {Object} [options] - Options for canvas output. + * @param {boolean} [options.flipY] - Flip the Y axis. Default is oriented for OpenGL. + * @param {HTMLCanvasElement} [options.canvas] - Optional canvas to draw into. + * Creates a new canvas if this does not exist. + * @returns {HTMLCanvasElement} The canvas containing the rendered texture. + */ +function textureToCanvas(texture, renderer, { flipY = true, canvas } = {}) { + // Create a new scene using a full-screen quad. + const scene = new THREE.Scene(); + scene.background = null; // Transparent background. + // Assign a transparent, textured, and double-sided material. + const material = new THREE.MeshBasicMaterial({ + side: THREE.DoubleSide, map: texture, transparent: true + }); + /** Full-screen quad. */ + const plane = new THREE.PlaneGeometry(2, 2); + const mesh = new THREE.Mesh(plane, material); + scene.add(mesh); + /** Ortho camera filling whole screen. */ + const camera = getIdentCamera(flipY); + + // Get previous render target, color space, and size. + const state = _saveRendererState(renderer); + + // Render to the main canvas to extract pixels. + renderer.setRenderTarget(null); // Render to primary target. + // Get width and set it on renderer. + const { width, height } = texture.image; + renderer.setSize(width, height, false); + // Use working color space. + renderer.outputColorSpace = THREE.ColorManagement ? THREE.ColorManagement.workingColorSpace : ''; + renderer.render(scene, camera); + + canvas = _copyRendererToCanvas(renderer, canvas); // Populate canvas. + + // Cleanup and restore renderer state. + material.dispose(); + plane.dispose(); + scene.remove(mesh); + _restoreRendererState(renderer, state); + + return canvas; // Either a new canvas or the same one. +} + +// // --------------------------------------------------------------------- +// // CharModel Icon Creation +// // --------------------------------------------------------------------- +// TODO PATH: src/ModelIcon.js + +/** @enum {number} */ +const ViewType = { + /** Typical icon body view. */ + Face: 0, + /** FFLMakeIcon matrix */ + MakeIcon: 1, + /** Custom view with 45 degree field-of-view. */ + IconFovy45: 2 +}; + +// -------------- getCameraForViewType(viewType, width, height) -------------- +/** + * @param {ViewType} viewType - The {@link ViewType} enum value. + * @param {number} width - Width of the view. + * @param {number} height - Height of the view. + * @returns {import('three').PerspectiveCamera} The camera representing the view type specified. + * @throws {Error} not implemented (ViewType.Face) + */ +function getCameraForViewType(viewType, width = 1, height = 1) { + const aspect = width / height; + switch (viewType) { + case ViewType.MakeIcon: { + /** rad2deg(Math.atan2(43.2 / aspect, 500) / 0.5); */ + const fovy = 9.8762; + const camera = new THREE.PerspectiveCamera(fovy, aspect, 500, 1000); + camera.position.set(0, 34.5, 600); + camera.lookAt(0, 34.5, 0.0); + return camera; + } + case ViewType.IconFovy45: { + const camera = new THREE.PerspectiveCamera(45, aspect, 50, 1000); + camera.position.set(0, 34, 110); + camera.lookAt(0, 34, 0); + return camera; + } + default: + throw new Error('getCameraForViewType: not implemented'); + } +} + +// ----------- makeIconFromCharModel(charModel, renderer, options) ----------- +/** + * Creates an icon of the CharModel with the specified view type. + * @param {CharModel} charModel - The CharModel instance. + * @param {import('three').WebGLRenderer} renderer - The renderer. + * @param {Object} [options] - Optional settings for rendering the icon. + * @param {ViewType} [options.viewType] - The view type that the camera derives from. + * @param {number} [options.width] - Desired icon width in pixels. + * @param {number} [options.height] - Desired icon height in pixels. + * @param {import('three').Scene} [options.scene] - Optional scene + * if you want to provide your own (e.g., with background, or models). + * @param {import('three').Camera} [options.camera] - Optional camera + * to use instead of the one derived from {@link ViewType}. + * @param {HTMLCanvasElement} [options.canvas] - Optional canvas + * to draw into. Creates a new canvas if this does not exist. + * @returns {HTMLCanvasElement} The canvas containing the icon. + * @throws {Error} CharModel.meshes is null or undefined, it may have been disposed. + */ +function makeIconFromCharModel(charModel, renderer, options = {}) { + if (!charModel.meshes) { + throw new Error('CharModel.meshes is null or undefined, it may have been disposed.'); + } + // Set locals from options object. + let { + viewType = ViewType.MakeIcon, + width = 256, + height = 256, + scene, + camera, + canvas + } = options; + + // Create an offscreen scene for the icon if one is not provided. + if (!scene) { + scene = new THREE.Scene(); + scene.background = null; // Transparent background. + } + // Add meshes from the CharModel. + scene.add(charModel.meshes.clone()); + // If the meshes aren't cloned then they disappear from the + // primary scene, however geometry/material etc are same + + // Get camera based on viewType parameter. + if (!camera) { + camera = getCameraForViewType(viewType); + } + + const state = _saveRendererState(renderer); + + renderer.setRenderTarget(null); // Switch to primary target. + renderer.setSize(width, height, false); + renderer.render(scene, camera); // Render scene. + + canvas = _copyRendererToCanvas(renderer, canvas); // Populate canvas. + + _restoreRendererState(renderer, state); + return canvas; + // Caller needs to dispose CharModel. +} + +// // --------------------------------------------------------------------- +// // StudioCharInfo Definition, Conversion +// // --------------------------------------------------------------------- +// TODO PATH: src/StudioCharInfo.js + +/** + * @typedef {Object} StudioCharInfo + * @property {number} beardColor + * @property {number} beardType + * @property {number} build + * @property {number} eyeAspect + * @property {number} eyeColor + * @property {number} eyeRotate + * @property {number} eyeScale + * @property {number} eyeType + * @property {number} eyeX + * @property {number} eyeY + * @property {number} eyebrowAspect + * @property {number} eyebrowColor + * @property {number} eyebrowRotate + * @property {number} eyebrowScale + * @property {number} eyebrowType + * @property {number} eyebrowX + * @property {number} eyebrowY + * @property {number} facelineColor + * @property {number} facelineMake + * @property {number} facelineType + * @property {number} facelineWrinkle + * @property {number} favoriteColor + * @property {number} gender + * @property {number} glassColor + * @property {number} glassScale + * @property {number} glassType + * @property {number} glassY + * @property {number} hairColor + * @property {number} hairFlip + * @property {number} hairType + * @property {number} height + * @property {number} moleScale + * @property {number} moleType + * @property {number} moleX + * @property {number} moleY + * @property {number} mouthAspect + * @property {number} mouthColor + * @property {number} mouthScale + * @property {number} mouthType + * @property {number} mouthY + * @property {number} mustacheScale + * @property {number} mustacheType + * @property {number} mustacheY + * @property {number} noseScale + * @property {number} noseType + * @property {number} noseY + */ + +/** + * Structure representing data from the studio.mii.nintendo.com site and API. + * @type {import('./struct-fu').StructInstance} + */ +const StudioCharInfo = _.struct([ + // Fields are named according to nn::mii::CharInfo. + _.uint8('beardColor'), + _.uint8('beardType'), + _.uint8('build'), + _.uint8('eyeAspect'), + _.uint8('eyeColor'), + _.uint8('eyeRotate'), + _.uint8('eyeScale'), + _.uint8('eyeType'), + _.uint8('eyeX'), + _.uint8('eyeY'), + _.uint8('eyebrowAspect'), + _.uint8('eyebrowColor'), + _.uint8('eyebrowRotate'), + _.uint8('eyebrowScale'), + _.uint8('eyebrowType'), + _.uint8('eyebrowX'), + _.uint8('eyebrowY'), + _.uint8('facelineColor'), + _.uint8('facelineMake'), + _.uint8('facelineType'), + _.uint8('facelineWrinkle'), + _.uint8('favoriteColor'), + _.uint8('gender'), + _.uint8('glassColor'), + _.uint8('glassScale'), + _.uint8('glassType'), + _.uint8('glassY'), + _.uint8('hairColor'), + _.uint8('hairFlip'), + _.uint8('hairType'), + _.uint8('height'), + _.uint8('moleScale'), + _.uint8('moleType'), + _.uint8('moleX'), + _.uint8('moleY'), + _.uint8('mouthAspect'), + _.uint8('mouthColor'), + _.uint8('mouthScale'), + _.uint8('mouthType'), + _.uint8('mouthY'), + _.uint8('mustacheScale'), + _.uint8('mustacheType'), + _.uint8('mustacheY'), + _.uint8('noseScale'), + _.uint8('noseType'), + _.uint8('noseY') +]); + +// ----------------- convertStudioCharInfoToFFLiCharInfo(src) ----------------- +/** + * Creates an FFLiCharInfo object from StudioCharInfo. + * @param {StudioCharInfo} src - The StudioCharInfo instance. + * @returns {FFLiCharInfo} The FFLiCharInfo output. + */ +function convertStudioCharInfoToFFLiCharInfo(src) { + return { + miiVersion: 0, + faceline: { + type: src.facelineType, + color: src.facelineColor, + texture: src.facelineWrinkle, + make: src.facelineMake + }, + hair: { + type: src.hairType, + color: commonColorMask(src.hairColor), + flip: src.hairFlip + }, + eye: { + type: src.eyeType, + color: commonColorMask(src.eyeColor), + scale: src.eyeScale, + aspect: src.eyeAspect, + rotate: src.eyeRotate, + x: src.eyeX, + y: src.eyeY + }, + eyebrow: { + type: src.eyebrowType, + color: commonColorMask(src.eyebrowColor), + scale: src.eyebrowScale, + aspect: src.eyebrowAspect, + rotate: src.eyebrowRotate, + x: src.eyebrowX, + y: src.eyebrowY + }, + nose: { + type: src.noseType, + scale: src.noseScale, + y: src.noseY + }, + mouth: { + type: src.mouthType, + color: commonColorMask(src.mouthColor), + scale: src.mouthScale, + aspect: src.mouthAspect, + y: src.mouthY + }, + beard: { + mustache: src.mustacheType, + type: src.beardType, + color: commonColorMask(src.beardColor), + scale: src.mustacheScale, + y: src.mustacheY + }, + glass: { + type: src.glassType, + color: commonColorMask(src.glassColor), + scale: src.glassScale, + y: src.glassY + }, + mole: { + type: src.moleType, + scale: src.moleScale, + x: src.moleX, + y: src.moleY + }, + body: { + height: src.height, + build: src.build + }, + personal: { + name: '', + creator: '', + gender: src.gender, + birthMonth: 0, + birthDay: 0, + favoriteColor: src.favoriteColor, + favorite: 0, + copyable: 0, + ngWord: 0, + localonly: 0, + regionMove: 0, + fontRegion: 0, + roomIndex: 0, + positionInRoom: 0, + birthPlatform: 3 + }, + createID: { + data: new Array(10).fill(0) + }, + padding_0: 0, + authorType: 0, + authorID: new Array(8).fill(0) + }; +} + +// --------------------- studioURLObfuscationDecode(data) --------------------- +/** + * @param {Uint8Array} data - Obfuscated Studio URL data. + * @returns {Uint8Array} Decoded Uint8Array representing CharInfoStudio. + */ +function studioURLObfuscationDecode(data) { + const decodedData = new Uint8Array(data); + const random = decodedData[0]; + let previous = random; + + for (let i = 1; i < 48; i++) { + const encodedByte = decodedData[i]; + const original = (encodedByte - 7 + 256) % 256; + decodedData[i - 1] = original ^ previous; + previous = encodedByte; + } + + return decodedData.slice(0, StudioCharInfo.size); // Clamp to StudioCharInfo.size +} + +// ----------------- convertFFLiCharInfoToStudioCharInfo(src) ----------------- +/** + * Creates a StudioCharInfo object from FFLiCharInfo. + * @param {FFLiCharInfo} src - The FFLiCharInfo instance. + * @returns {StudioCharInfo} The StudioCharInfo output. + * @todo TODO: Currently does NOT convert color indices + * to CommonColor indices (ToVer3... etc) + */ +function convertFFLiCharInfoToStudioCharInfo(src) { + return { + beardColor: commonColorUnmask(src.beard.color), + beardType: src.beard.type, + build: src.body.build, + eyeAspect: src.eye.aspect, + eyeColor: commonColorUnmask(src.eye.color), + eyeRotate: src.eye.rotate, + eyeScale: src.eye.scale, + eyeType: src.eye.type, + eyeX: src.eye.x, + eyeY: src.eye.y, + eyebrowAspect: src.eyebrow.aspect, + eyebrowColor: commonColorUnmask(src.eyebrow.color), + eyebrowRotate: src.eyebrow.rotate, + eyebrowScale: src.eyebrow.scale, + eyebrowType: src.eyebrow.type, + eyebrowX: src.eyebrow.x, + eyebrowY: src.eyebrow.y, + facelineColor: src.faceline.color, + facelineMake: src.faceline.make, + facelineType: src.faceline.type, + facelineWrinkle: src.faceline.texture, + favoriteColor: src.personal.favoriteColor, + gender: src.personal.gender, + glassColor: commonColorUnmask(src.glass.color), + glassScale: src.glass.scale, + glassType: src.glass.type, + glassY: src.glass.y, + hairColor: commonColorUnmask(src.hair.color), + hairFlip: src.hair.flip, + hairType: src.hair.type, + height: src.body.height, + moleScale: src.mole.scale, + moleType: src.mole.type, + moleX: src.mole.x, + moleY: src.mole.y, + mouthAspect: src.mouth.aspect, + mouthColor: commonColorUnmask(src.mouth.color), + mouthScale: src.mouth.scale, + mouthType: src.mouth.type, + mouthY: src.mouth.y, + mustacheScale: src.beard.scale, + mustacheType: src.beard.mustache, + mustacheY: src.beard.y, + noseScale: src.nose.scale, + noseType: src.nose.type, + noseY: src.nose.y + }; +} + +// // --------------------------------------------------------------------- +// // Generic Hex/Base64 Utilities +// // --------------------------------------------------------------------- +// TODO PATH: src/CodecUtilities.js + +/** + * Removes all spaces from a string. + * @param {string} str - The input string. + * @returns {string} The string without spaces. + */ +function stripSpaces(str) { + return str.replace(/\s+/g, ''); +} + +/** + * Converts a hexadecimal string to a Uint8Array. + * @param {string} hex - The hexadecimal string. + * @returns {Uint8Array} The converted Uint8Array. + */ +function hexToUint8Array(hex) { + const match = hex.match(/.{1,2}/g); + // If match returned null, use an empty array. + const arr = (match ? match : []).map(function (byte) { + return parseInt(byte, 16); + }); + return new Uint8Array(arr); +} + +/** + * Converts a Base64 or Base64-URL encoded string to a Uint8Array. + * @param {string} base64 - The Base64-encoded string. + * @returns {Uint8Array} The converted Uint8Array. + */ +function base64ToUint8Array(base64) { + // Replace URL-safe Base64 characters + const normalizedBase64 = base64.replace(/-/g, '+').replace(/_/g, '/'); + // Custom function to pad the string with '=' manually + /** + * @param {string} str - The Base64 string to pad. + * @returns {string} The padded Base64 string. + */ + function padBase64(str) { + while (str.length % 4 !== 0) { + str += '='; + } + return str; + } + // Add padding if necessary. + const paddedBase64 = padBase64(normalizedBase64); + const binaryString = atob(paddedBase64); + const len = binaryString.length; + const bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} + +/** + * Converts a Uint8Array to a Base64 string. + * @param {Array} data - The Uint8Array to convert. TODO: check if Uint8Array truly can be used + * @returns {string} The Base64-encoded string. + */ +function uint8ArrayToBase64(data) { + return btoa(String.fromCharCode.apply(null, data)); +} + +/** + * Parses a string contaning either hex or Base64 representation + * of bytes into a Uint8Array, stripping spaces. + * @param {string} text - The input string, which can be either hex or Base64. + * @returns {Uint8Array} The parsed Uint8Array. + */ +function parseHexOrB64ToUint8Array(text) { + let inputData; + // Decode it to a Uint8Array whether it's hex or Base64 + const textData = stripSpaces(text); + // Check if it's base 16 exclusively, otherwise assume Base64 + if (/^[0-9a-fA-F]+$/.test(textData)) { + inputData = hexToUint8Array(textData); + } else { + inputData = base64ToUint8Array(textData); + } + return inputData; +} + +// ------------------ ESM exports, uncomment if you use ESM ------------------ + +export { + // Generic enums + FFLModulateMode, + FFLModulateType, + FFLExpression, + FFLModelFlag, + FFLResourceType, + + // Types for CharModel initialization + FFLiCharInfo, + FFLCharModelDesc, + FFLCharModelDescDefault, + FFLDataSource, + FFLCharModelSource, + + // Enums for getRandomCharInfo + FFLGender, + FFLAge, + FFLRace, + + // Begin public methods + initializeFFL, + initializeFFLWithResource, + exitFFL, + CharModel, // CharModel class + verifyCharInfo, + getRandomCharInfo, + makeExpressionFlag, + + // Pants colors + PantsColor, + pantsColors, + + // CharModel creation + _allocateModelSource, + createCharModel, + updateCharModel, + transferCharModelTex, // TODO + getIdentCamera, + createAndRenderToTarget, + matSupportsFFL, + initCharModelTextures, + textureToCanvas, + + // CharModel helpers for exporting models + TextureShaderMaterial, + convertModelTexturesToRGBA, + convModelTargetsToDataTex, + convGeometryToGLTFCompatible, + + // Icon rendering + ViewType, + getCameraForViewType, + makeIconFromCharModel, + StudioCharInfo, + + // Export utilities + convertStudioCharInfoToFFLiCharInfo, + convertFFLiCharInfoToStudioCharInfo, + uint8ArrayToBase64, + parseHexOrB64ToUint8Array, + + // extra + FFLiShapeType +}; diff --git a/src/external/ffl.js/struct-fu-mini.js b/src/external/ffl.js/struct-fu-mini.js deleted file mode 100644 index 47b12fa..0000000 --- a/src/external/ffl.js/struct-fu-mini.js +++ /dev/null @@ -1,477 +0,0 @@ -/*! - * The following is a version of the struct-fu library - * fork by ariankordi: https://github.com/ariankordi/struct-fu - * with the following changes made for code size: - * Added: _.uintptr, mapping to _.uint32le (with WASM in mind) - * Added (TODO): add JSDoc StructInstance template - * Removed: Polyfills Function.prototype.bind, TextEncoder/TextDecoder - * Removed: bitfield, bitfieldLE... - * Removed: char16be, swapBytesPairs - * Removed: 64-bit types, 16-bit float - * Modified: addField (no bit handling), _.struct (rm "aligned bitfield" message) - */ - - -/** - * A library for defining structs to convert between JSON and binary. - * Supports numbers, bytes, and strings. - * Required: Support for TypedArray, Function.prototype.bind, TextEncoder/TextDecoder - * - * @namespace - */ -var _ = {}; - -/** - * Creates a new buffer backed by an ArrayBuffer. - * - * @param {number} size - The size of the buffer in bytes. - * @returns {Uint8Array} A new Uint8Array of the specified size. - */ -function newBuffer(size) { - return new Uint8Array(new ArrayBuffer(size)); -} - -/** - * Extends an object with properties from subsequent objects. - * - * @param {Object} obj - The target object to extend. - * @returns {Object} The extended object. - */ -function extend(obj) { - var args = Array.prototype.slice.call(arguments, 1); - args.forEach(function (ext) { - Object.keys(ext).forEach(function (key) { - obj[key] = ext[key]; - }); - }); - return obj; -} - -/** - * Adds a bitfield's size to the current cursor. - * - * @param {Object} ctr - The current cursor with bytes. - * @param {Object} f - The field to add. - * @returns {Object} The updated cursor. - */ -function addField(ctr, f) { - ctr.bytes += f.size; - return ctr; -} - - -/** - * Converts a field into an array field if a count is provided. - * - * @param {Object} f - The field to arrayize. - * @param {number} count - The number of elements in the array. - * @returns {Object} The arrayized field. - */ -function arrayizeField(f, count) { - var f2 = (typeof count === 'number') ? extend({ - name: f.name, - field: f, - /** - * Unpacks an array of values from bytes. - * - * @param {ArrayBuffer|Uint8Array} buf - The buffer to read from. - * @param {Object} [off] - The offset object with bytes and bits. - * @returns {Array} The unpacked array of values. - */ - valueFromBytes: function (buf, off) { - off || (off = { bytes: 0, bits: 0 }); - var arr = new Array(count); - for (var idx = 0, len = arr.length; idx < len; idx += 1) { - arr[idx] = f.valueFromBytes(buf, off); - } - return arr; - }, - /** - * Packs an array of values into bytes. - * - * @param {Array} arr - The array of values to pack. - * @param {ArrayBuffer|Uint8Array} [buf] - The buffer to write to. - * @param {Object} [off] - The offset object with bytes and bits. - * @returns {ArrayBuffer|Uint8Array} The buffer with packed data. - */ - bytesFromValue: function (arr, buf, off) { - arr || (arr = new Array(count)); - buf || (buf = newBuffer(this.size)); - off || (off = { bytes: 0, bits: 0 }); - for (var idx = 0, len = Math.min(arr.length, count); idx < len; idx += 1) { - f.bytesFromValue(arr[idx], buf, off); - } - while (idx++ < count) addField(off, f); - return buf; - } - }, ('width' in f) ? { width: f.width * count } : { size: f.size * count }) : f; - f2.pack = f2.bytesFromValue; - f2.unpack = f2.valueFromBytes; - return f2; -} - -/** - * Defines a new structure with the given fields. - * - * @param {string} [name] - The name of the structure. - * @param {Array} fields - The array of field definitions. - * @param {number} [count] - The number of structures in an array. - * @returns {Object} The defined structure with pack and unpack methods. - */ -_.struct = function (name, fields, count) { - if (typeof name !== 'string') { - count = fields; - fields = name; - name = null; - } - - var _size = { bytes: 0, bits: 0 }, - _padsById = Object.create(null), - fieldsObj = fields.reduce(function (obj, f) { - if ('_padTo' in f) { - // HACK: we really should just make local copy of *all* fields - f._id || (f._id = 'id' + Math.random().toFixed(20).slice(2)); // WORKAROUND: https://github.com/tessel/runtime/issues/716 - var _f = _padsById[f._id] = (_size.bits) ? { - width: 8 * (f._padTo - _size.bytes) - _size.bits - } : { - size: f._padTo - _size.bytes - }; - if ((_f.width !== undefined && _f.width < 0) || (_f.size !== undefined && _f.size < 0)) { - var xtraMsg = (_size.bits) ? (' and ' + _size.bits + ' bits') : ''; - throw Error('Invalid .padTo(' + f._padTo + ') field, struct is already ' + _size.bytes + ' byte(s)' + xtraMsg + '!'); - } - f = _f; - } else if (f._hoistFields) { - Object.keys(f._hoistFields).forEach(function (name) { - var _f = Object.create(f._hoistFields[name]); - if ('width' in _f) { - _f.offset = { bytes: _f.offset.bytes + _size.bytes, bits: _f.offset.bits }; - } else { - _f.offset += _size.bytes; - } - obj[name] = _f; - }); - } else if (f.name) { - f = Object.create(f); // local overrides - f.offset = ('width' in f) ? { bytes: _size.bytes,bits: _size.bits } : _size.bytes, - obj[f.name] = f; - } - addField(_size, f); - return obj; - }, {}); - if (_size.bits) throw Error('Improperly aligned bitfield at end of struct: ' + name); - - return arrayizeField({ - /** - * Unpacks a structure from bytes. - * - * @param {ArrayBuffer|Uint8Array} buf - The buffer to read from. - * @param {Object} [off] - The offset object with bytes and bits. - * @returns {Object} The unpacked structure. - */ - valueFromBytes: function (buf, off) { - off || (off = { bytes: 0, bits: 0 }); - var obj = {}; - fields.forEach(function (f) { - if ('_padTo' in f) return addField(off, _padsById[f._id]); - - var value = f.valueFromBytes(buf, off); - if (f.name) obj[f.name] = value; - else if (typeof value === 'object') extend(obj, value); - }); - return obj; - }, - /** - * Packs a structure into bytes. - * - * @param {Object} obj - The object containing values to pack. - * @param {ArrayBuffer|Uint8Array} [buf] - The buffer to write to. - * @param {Object} [off] - The offset object with bytes and bits. - * @returns {ArrayBuffer|Uint8Array} The buffer with packed data. - */ - bytesFromValue: function (obj, buf, off) { - obj || (obj = {}); - buf || (buf = newBuffer(this.size)); - off || (off = { bytes: 0, bits: 0 }); - fields.forEach(function (f) { - if ('_padTo' in f) return addField(off, _padsById[f._id]); - - var value = (f.name) ? obj[f.name] : obj; - f.bytesFromValue(value, buf, off); - }); - return buf; - }, - _hoistFields: (!name) ? fieldsObj : null, - fields: fieldsObj, - size: _size.bytes, - name: name - }, count); -}; - - -/** - * Defines a padding field up to the specified offset. - * - * @param {number} off - The byte offset to pad to. - * @returns {Object} The padding field definition. - */ -_.padTo = function (off) { - return { _padTo: off }; -}; - -/** - * Defines a byte-based field within a structure. - * - * @param {string|number} name - The name of the bytefield or its size if name is omitted. - * @param {number} [size=1] - The size of the bytefield in bytes. - * @param {number} [count] - The number of bytefields in an array. - * @returns {Object} The defined bytefield. - */ -function bytefield(name, size, count) { - if (typeof name !== 'string') { - count = size; - size = name; - name = null; - } - size = (typeof size === 'number') ? size : 1; - var impl = this; - return arrayizeField({ - /** - * Unpacks a bytefield from bytes. - * - * @param {ArrayBuffer|Uint8Array} buf - The buffer to read from. - * @param {Object} [off] - The offset object with bytes and bits. - * @returns {Uint8Array} The unpacked bytefield. - */ - valueFromBytes: function (buf, off) { - off || (off = { bytes: 0, bits: 0 }); - var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; - var val = bytes.subarray(off.bytes, off.bytes + this.size); - addField(off, this); - return impl.b2v.call(this, val); - //return impl.b2v.call(this, val.buffer.slice(val.byteOffset, val.byteOffset + val.byteLength)); // Returns ArrayBuffer usually - }, - /** - * Packs a bytefield into bytes. - * - * @param {ArrayBuffer|Uint8Array} val - The value to pack. - * @param {ArrayBuffer|Uint8Array} [buf] - The buffer to write to. - * @param {Object} [off] - The offset object with bytes and bits. - * @returns {ArrayBuffer|Uint8Array} The buffer with packed data. - */ - bytesFromValue: function (val, buf, off) { - buf || (buf = newBuffer(this.size)); - off || (off = { bytes: 0, bits: 0 }); - var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; - var blk = bytes.subarray(off.bytes, off.bytes + this.size); - impl.vTb.call(this, val, blk); - addField(off, this); - return buf; - }, - size: size, - name: name - }, count); -} - -_.byte = bytefield.bind({ - /** - * Converts bytes to a value. - * - * @param {ArrayBuffer|Uint8Array} b - The bytes to convert. - * @returns {ArrayBuffer|Uint8Array} The byte value. - */ - b2v: function (b) { return b; }, - /** - * Converts a value to bytes. - * - * @param {ArrayBuffer|Uint8Array} v - The value to convert. - * @param {Uint8Array} b - The buffer to write to. - * @returns {number} The number of bytes written. - */ - vTb: function (v, b) { if (!v) return 0; b.set(new Uint8Array(v)); return v.byteLength; } -}); - -_.char = bytefield.bind({ - /** - * Converts bytes to a UTF-8 string. - * - * @param {ArrayBuffer|Uint8Array} b - The bytes to convert. - * @returns {string} The resulting string. - */ - b2v: function (b) { - var decoder = new TextDecoder('utf-8'); - var v = decoder.decode(b); - var z = v.indexOf('\0'); - return (~z) ? v.slice(0, z) : v; - }, - /** - * Converts a string to UTF-8 bytes. - * - * @param {string} v - The string to convert. - * @param {Uint8Array} b - The buffer to write to. - * @returns {number} The number of bytes written. - */ - vTb: function (v,b) { - v || (v = ''); - var encoder = new TextEncoder('utf-8'); - var encoded = encoder.encode(v); - for (var i = 0; i < encoded.length && i < b.length; i++) { - b[i] = encoded[i]; - } - return encoded.length; - } -}); - -_.char16le = bytefield.bind({ - /** - * Converts bytes to a UTF-16LE string. - * - * @param {ArrayBuffer|Uint8Array} b - The bytes to convert. - * @returns {string} The resulting string. - */ - b2v: function (b) { - var decoder = new TextDecoder('utf-16le'); - var v = decoder.decode(b); - var z = v.indexOf('\0'); - return (~z) ? v.slice(0, z) : v; - }, - /** - * Converts a string to UTF-16LE bytes. - * - * @param {string} v - The string to convert. - * @param {Uint8Array} b - The buffer to write to. - * @returns {number} The number of bytes written. - */ - vTb: function (v,b) { - v || (v = ''); - var bytesWritten = 0; - for (var i = 0; i < v.length && bytesWritten + 1 < b.length; i++) { - var charCode = v.charCodeAt(i); - b[bytesWritten++] = charCode & 0xFF; - b[bytesWritten++] = (charCode >> 8) & 0xFF; - } - return bytesWritten; - } -}); - -/** - * Defines a standard field with specific read and write methods. - * - * @param {string} sig - The signature indicating the type. This is assumed to be available in the DataView API as DataView.(get/set)(sig), e.g. "Uint32" is valid because DataView.getUint32() is a valid method - * @param {number} size - The size of the field in bytes. - * @param {boolean} littleEndian - Indicates whether or not the field is little endian. - * @returns {Function} A function to create the standard field. - */ -function standardField(sig, size, littleEndian) { - var read = 'get' + sig, - dump = 'set' + sig; - size || (size = +sig.match(/\d+/)[0] / 8); - return function (name, count) { - if (typeof name !== 'string') { - count = name; - name = null; - } - return arrayizeField({ - /** - * Unpacks a standard field from bytes. - * - * @param {ArrayBuffer|Uint8Array} buf - The buffer to read from. - * @param {Object} [off] - The offset object with bytes and bits. - * @returns {*} The unpacked value. - */ - valueFromBytes: function (buf, off) { - off || (off = { bytes: 0 }); - var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; - var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - var val = view[read](off.bytes, littleEndian); - addField(off, this); - return val; - }, - /** - * Packs a standard field into bytes. - * - * @param {*} val - The value to pack. - * @param {ArrayBuffer|Uint8Array} [buf] - The buffer to write to. - * @param {Object} [off] - The offset object with bytes and bits. - * @returns {ArrayBuffer|Uint8Array} The buffer with packed data. - */ - bytesFromValue: function (val, buf, off) { - val || (val = 0); - buf || (buf = newBuffer(this.size)); - off || (off = { bytes: 0 }); - var bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : buf; - var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - view[dump](off.bytes, val, littleEndian); - addField(off, this); - return buf; - }, - size: size, - name: name - }, count); - }; -} - -_.uint8 = standardField('Uint8', 1, false); -_.uint16 = standardField('Uint16', 2, false); -_.uint32 = standardField('Uint32', 4, false); -_.uint16le = standardField('Uint16', 2, true); -_.uint32le = standardField('Uint32', 4, true); -_.uintptr = _.uint32le; // assuming WASM/32 bit pointers only - -_.int8 = standardField('Int8', 1, false); -_.int16 = standardField('Int16', 2, false); -_.int32 = standardField('Int32', 4, false); -_.int16le = standardField('Int16', 2, true); -_.int32le = standardField('Int32', 4, true); - -_.float32 = standardField('Float32', 4, false); -_.float32le = standardField('Float32', 4, true); - -/** - * Derives a new field based on an existing one with custom pack and unpack functions. - * - * @param {Object} orig - The original field to derive from. - * @param {Function} pack - The function to pack the derived value. - * @param {Function} unpack - The function to unpack the derived value. - * @returns {Function} A function to create the derived field. - */ -_.derive = function (orig, pack, unpack) { - return function (name, count) { - if (typeof name !== 'string') { - count = name; - name = null; - } - return arrayizeField(extend({ - /** - * Unpacks a derived field from bytes. - * - * @param {ArrayBuffer|Uint8Array} buf - The buffer to read from. - * @param {Object} [off] - The offset object with bytes and bits. - * @returns {*} The unpacked derived value. - */ - valueFromBytes: function (buf, off) { - return unpack(orig.valueFromBytes(buf, off)); - }, - /** - * Packs a derived field into bytes. - * - * @param {*} val - The value to pack. - * @param {ArrayBuffer|Uint8Array} [buf] - The buffer to write to. - * @param {Object} [off] - The offset object with bytes and bits. - * @returns {ArrayBuffer|Uint8Array} The buffer with packed data. - */ - bytesFromValue: function (val, buf, off) { - return orig.bytesFromValue(pack(val), buf, off); - }, - name: name - }, ('width' in orig) ? { width: orig.width } : { size: orig.size }), count); - }; -}; - -// Export for Node.js environments -if (typeof module !== 'undefined' && module.exports) { - module.exports = _; -} else { - // Export to global scope for browsers - window._ = _; -} diff --git a/src/external/ffl.js/struct-fu.js b/src/external/ffl.js/struct-fu.js new file mode 100644 index 0000000..196d33c --- /dev/null +++ b/src/external/ffl.js/struct-fu.js @@ -0,0 +1,1140 @@ +// @ts-check +/*! + * struct-fu library: https://github.com/natevw/struct-fu + * forked by ariankordi: https://github.com/ariankordi/struct-fu + * @author Nathan Vander Wilt + * @license Apache-2.0 + * @license BSD-2-Clause + */ + +// // --------------------------------------------------------------------- +// // Exported JSDoc Type Definitions +// // --------------------------------------------------------------------- + +/** + * A type representing either a raw ArrayBuffer or a typed view of it. + * @typedef {ArrayBuffer | Uint8Array} BufferSource + */ + +/** + * A type for the offset/"cursor" used to track the byte and bit offsets. + * @typedef {Object} Offset + * @property {number} bytes - Current byte offset. + * @property {number} [bits] - Current bit offset. + */ + +/** + * A transform interface for bitfields, converting between raw number bits and user values. + * Notably, the input/output can be number or boolean. (Used by `b2v` and `v2b` methods.) + * @typedef {Object} BitTransform + * @property {function(this: {width:number}, number): number|boolean} b2v - Called when reading bits from buffer. + * @property {function(this: {width:number}, number|boolean): number} v2b - Called when writing bits into buffer. + * @property {number} [width=1] - The width (in bits) of this bitfield. + * @property {boolean|null} [littleEndian] - Whether or not the bitfield is little-endian. + */ + +/** + * A transform interface for byte fields, converting between raw bytes and user values. + * (Used by `b2v` and `vTb` methods.) + * @typedef {Object} ByteTransform + * @property {function(BufferSource): *} b2v - Called when reading bytes from buffer. + * @property {function(*, Uint8Array): number} vTb - Called when writing values into buffer. + * @property {number} [size=1] - The size (in bytes) of this field. + */ + +/** + * Represents a padding field that ensures proper byte alignment in a struct. + * It does not hold a value but affects struct layout. + * @typedef {Object} PaddingField + * @property {number} _padTo - The byte offset to pad to. + * @property {string} [_id] - Internal unique ID. + */ + +/** + * A single field definition, which must define how to read (unpack) and write (pack) data. + * This is the base type that all specialized fields (bitfields, bytefields, etc.) implement. + * @typedef {Object} Field + * @property {string} [name] - The name of the field (if any). + * @property {number} size - The size of the field in bytes (for non-bitfield types). + * @property {number} [width] - The size of the field in bits (for bitfields). + * @property {number | Offset} [offset] - Byte or (byte, bits) offset. + * @property {function(BufferSource, Offset=): *} unpack - Unpacks the field value from a buffer (`valueFromBytes`). + * @property {function(*, BufferSource=, Offset=): Uint8Array} pack - Packs a value into a buffer (`bytesFromValue`). + * @property {Object|null} [_hoistFields] - If this is a nested struct, this maps sub-fields to their definitions. + * @property {Object} [fields] - An object mapping field names to their definitions. + */ + +/** + * Template for the return type of _.struct(), representing an instance of a structure with pack/unpack methods. + * It is generic in case you want to define a typed object for the data. + * @template T + * @typedef StructInstance + * @property {function(BufferSource, Offset=): T} unpack - Deserialize from a BufferSource into the structured object. + * @property {function(T, BufferSource=, Offset=): Uint8Array} pack - Serialize the structured object into a Uint8Array. + * @property {Object} fields - Field definitions keyed by field name. + * @property {number} size - The total size in bytes of the packed structure. + * @property {string} [name] - The name of the struct (if provided). + * @property {Object|null} [_hoistFields] - If this is a nested struct, this maps sub-fields to their definitions. + */ + +// // --------------------------------------------------------------------- +// // UMD / factory setup +// // --------------------------------------------------------------------- + +(function (root, factory) { + // @ts-ignore - cannot find name define + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + // @ts-ignore + define([], factory); + } else if (typeof module === 'object' && module.exports) { + // Node.js/CommonJS + + // In Node (in versions earlier than 11, released 2018), TextEn/Decoder + // are only available through the "util" package, however bundlers + // building for browser will see that and always try to include it. + + // Therefore, this will assume TextEncoder/TextDecoder are in globalThis (not root). + module.exports = factory(globalThis.TextEncoder, globalThis.TextDecoder); + // NOTE: Uncomment below if you are using versions of Node earlier than 11. + // module.exports = factory(require('util').TextEncoder, require('util').TextDecoder); + } else { + // Browser globals (root is window) + + // Assume TextEncoder/TextDecoder are either defined or undefined in window. + /** @type {*} */ (root)._ = factory(/** @type {*} */ (root).TextEncoder, /** @type {*} */ (root).TextDecoder); + } +}(typeof self !== 'undefined' ? self : this, + // It seems that TypeScript is predicting a type for the whole + // namespace that includes all functions, and defining any custom + // returns type ruins that, leaving the .d.ts empty and dry of functions. + /* eslint-disable jsdoc/require-returns-type */ + /** + * @param {typeof TextEncoder} _TextEncoder + * @param {typeof TextDecoder} _TextDecoder + * @returns Returns the exported namespace. + */ + function (_TextEncoder, _TextDecoder) { + /* eslint-enable jsdoc/require-returns-type */ +'use strict'; + +/** + * A library for defining structs to convert between JSON and binary. + * Supports numbers, bytes, strings, and bitfields. + * Compatible with browsers down to Safari 5.1. + * @namespace _ + */ +var _ = {}; + +// Add ECMA262-5 method binding if not supported natively +// https://github.com/ReactNativeNews/react-native-newsletter/blob/93016f62af32d97cc009f991d4f7c3c7155a4f26/ie.js#L8 +if (!('bind' in Function.prototype)) { + /** + * @param {Object|null|undefined} owner + * @returns {Function} + * @this {Function} + */ + // @ts-ignore - Property bind does not exist on never? + Function.prototype.bind = function (owner) { + var that = this; + if (arguments.length <= 1) { + return function () { + return that.apply(owner, arguments); + }; + } + var args = Array.prototype.slice.call(arguments, 1); + return function () { + return that.apply( + owner, + arguments.length === 0 ? args : args.concat(Array.prototype.slice.call(arguments)) + ); + }; + }; +} + +// // --------------------------------------------------------------------- +// // Helper Methods +// // --------------------------------------------------------------------- + +/** + * Creates a new Uint8Array of given size backed by an ArrayBuffer. + * @param {number} size - The size of the buffer in bytes. + * @returns {Uint8Array} A new Uint8Array of the specified size. + */ +function newBuffer(size) { + return new Uint8Array(new ArrayBuffer(size)); +} + +/** + * Extends an object with properties from subsequent objects. + * @param {Object} obj - The target object to extend. + * @returns {Object} The extended target object. + */ +function extend(obj) { + var args = /** @type {Array>} */ (Array.prototype.slice.call(arguments, 1)); + args.forEach(function (ext) { + Object.keys(ext).forEach(function (key) { + obj[key] = ext[key]; + }); + }); + return obj; +} + +/** + * Adds a field's size to the current offset cursor (bytes/bits). + * @param {Offset} ctr - The current offset (bytes, bits). + * @param {Field} f - The field whose size to add. + * @returns {Offset} The updated offset cursor. + * @throws {Error} Improperly aligned bitfield before field + */ +function addField(ctr, f) { + if ('width' in f && typeof f.width === 'number') { + ctr.bits = (ctr.bits || 0) + f.width; + while ((ctr.bits || 0) > 7) { + ctr.bytes += 1; + ctr.bits -= 8; + } + } else if (!ctr.bits) { + // Not a bitfield, add full size in bytes. + ctr.bytes += f.size || 0; + } else { + // We have leftover bits that aren't aligned, can't add a normal field. + throw Error('Improperly aligned bitfield before field: ' + (f.name || '')); + } + return ctr; +} + +/** + * Converts a field into an array field if a count is provided. + * @param {Field} f - The field to arrayize. + * @param {number} [count] - The number of elements in the array, if needed. + * @returns {Field} The arrayized field. + */ +function arrayizeField(f, count) { + var field = (typeof count === 'number') ? /** @type {Field} */ (extend({ + name: f.name, + field: f, + /** + * Unpacks an array of values from bytes. + * @param {BufferSource} buf - The buffer to read from. + * @param {Offset} off - The offset object with bytes and bits. + * @returns {Array<*>} The unpacked array of values. + */ + unpack: function (buf, off) { + off || (off = { bytes: 0, bits: 0 }); + var arr = new Array(count); + for (var idx = 0, len = arr.length; idx < len; idx += 1) { + arr[idx] = f.unpack(buf, off); + } + return arr; + }, + /** + * Packs an array of values into bytes. + * @param {Array<*>} arr + * @param {BufferSource} [buf] + * @param {Offset} [off] + * @returns {Uint8Array} + * @this {Field} + */ + pack: function (arr, buf, off) { + arr || (arr = new Array(count)); + buf || (buf = newBuffer(this.size)); + off || (off = { bytes: 0, bits: 0 }); + for (var idx = 0, len = Math.min(arr.length, count); idx < len; idx += 1) { + f.pack(arr[idx], buf, off); + } + while (idx++ < count) addField(off, f); + return /** @type {Uint8Array} */ (buf); + } + }, (f.width !== undefined) + ? { width: f.width * count } + : { size: f.size * count }) + ) : f; + return field; +} + +// // --------------------------------------------------------------------- +// // _.struct Definition +// // --------------------------------------------------------------------- + +/** + * Defines a new structure with the given fields. + * Overloads: + * _.struct(fields, count?) + * _.struct(name, fields, count?) + * @param {string|Array} name - The structure name or the array of fields if no name. + * @param {Array>|number} [fields] - The array of fields OR the count if the first param was fields. + * @param {number} [count] - The number of array elements if making an array of structs. + * @returns {StructInstance<*>} The resulting struct definition (and array, if count was provided). + * @throws {Error} Invalid .padTo..., Improperly aligned bitfield at end of struct + */ +_.struct = function (name, fields, count) { + /** @type {string|undefined} */ + var structName; + /** @type {Array} */ + var fieldDefs; + + if (typeof name !== 'string') { + // Overload 1: (fields[, count]) + count = /** @type {number|undefined} */ (fields); + fieldDefs = /** @type {Array} */ (name); + } else { + // Overload 2: (name, fields[, count]) + structName = name; + fieldDefs = /** @type {Array} */ (fields); + } + + var _size = { bytes: 0, bits: 0 }; + var _padsById = Object.create(null); + + /** + * @param {Object} obj + * @param {Field} f + * @returns {Object} + * @throws {Error} Invalid .padTo... + */ + function reduceFunc(obj, f) { + // Handle _padTo: + if ('_padTo' in f) { + var padField = /** @type {PaddingField} */ (f); // Cast to this type. + // Generate a "pad field" for alignment. + if (!padField._id) { + padField._id = 'id' + Math.random().toFixed(20).slice(2); // WORKAROUND: https://github.com/tessel/runtime/issues/716 + } + var neededPadBytes = padField._padTo - _size.bytes; + if (_size.bits) { + // This is a bitfield alignment. + var bitsNeeded = 8 * neededPadBytes - _size.bits; + if (bitsNeeded < 0) { + throw Error( + 'Invalid .padTo(' + padField._padTo + ') field, struct is already ' + + _size.bytes + ' byte(s) and ' + _size.bits + ' bits!' + ); + } + _padsById[padField._id] = { width: bitsNeeded }; + f.width = bitsNeeded; + } else { + if (neededPadBytes < 0) { + throw Error( + 'Invalid .padTo(' + padField._padTo + ') field, struct is already ' + _size.bytes + ' bytes!' + ); + } + _padsById[padField._id] = { size: neededPadBytes }; + f.size = neededPadBytes; + } + } + + // Handle sub-struct hoisting: + if (f._hoistFields) { + var hoistFields = f._hoistFields; // Otherwise it thinks it's null or undefined below + Object.keys(hoistFields).forEach(function (subName) { + var _f = Object.create(hoistFields[subName]); + if ('width' in _f && typeof _f.width === 'number') { + _f.offset = { bytes: _f.offset.bytes + _size.bytes, bits: _f.offset.bits }; + } else { + _f.offset = /** @type {number} */ (_f.offset) + _size.bytes; + } + obj[subName] = _f; + }); + } else if (f.name) { + // Create a local copy, assign offset. + var localCopy = Object.create(f); + if ('width' in localCopy && typeof localCopy.width === 'number') { + localCopy.offset = { bytes: _size.bytes, bits: _size.bits }; + } else { + localCopy.offset = _size.bytes; + } + obj[f.name] = localCopy; + } + + addField(_size, f); + return obj; + } + /** @type {Object} */ + var fieldsObj = fieldDefs.reduce(reduceFunc, {}); + + + if (_size.bits) { + throw Error('Improperly aligned bitfield at end of struct: ' + (structName || '')); + } + + // Now build the main field definition for the struct. + var structField = { + /** + * Reads (unpacks) a struct from the buffer at the given offset. + * @param {BufferSource} buf + * @param {Offset} [off] + * @returns {*} + */ + unpack: function (buf, off) { + off = off || { bytes: 0, bits: 0 }; + /** @type {Object} */ + var obj = {}; + fieldDefs.forEach(function (f) { + if ('_padTo' in f && /** @type {PaddingField} */ (f)._id !== undefined) { + // It's a pad spec; retrieve the pad field from _padsById. + addField(/** @type {Offset} */ (off), _padsById[/** @type {PaddingField} */ (f)._id]); + return; + } + var value = f.unpack(buf, off); + if (f.name) { + obj[f.name] = value; + } else if (typeof value === 'object') { + extend(obj, value); + } + }); + return obj; + }, + + /** + * Writes (packs) the given object into a buffer at the given offset. + * @param {*} obj + * @param {BufferSource} [buf] + * @param {Offset} [off] + * @returns {Uint8Array} + */ + pack: function (obj, buf, off) { + obj = obj || {}; + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0, bits: 0 }; + fieldDefs.forEach(function (f) { + if ('_padTo' in f && /** @type {PaddingField} */ (f)._id !== undefined) { + addField(/** @type {Offset} */ (off), _padsById[/** @type {PaddingField} */ (f)._id]); + return; + } + var value = f.name ? obj[f.name] : obj; + f.pack(value, /** @type {BufferSource} */ (buf), off); + }); + return /** @type {Uint8Array} */ (buf); + }, + + _hoistFields: structName ? null : fieldsObj, + fields: fieldsObj, + size: _size.bytes, + name: structName + }; + + // Cast to StructInstance for type compatibility. + return /** @type {StructInstance<*>} */ (arrayizeField(structField, count)); +}; + +// // --------------------------------------------------------------------- +// // Begin Bitfield Helpers +// // --------------------------------------------------------------------- + +/** + * Reads a 32-bit unsigned int from buffer, but handles short lengths by not reading beyond the buffer. + * Used in valueFromBytes by bitfield logic. + * @param {BufferSource} buffer - The buffer to read from. + * @param {number} offset - The byte offset to start reading. + * @param {boolean} littleEndian - Indicates whether to read little-endian. + * @returns {number} The read unsigned 32-bit integer. + */ +function truncatedReadUInt32(buffer, offset, littleEndian) { + var bytes = (buffer instanceof ArrayBuffer) ? new Uint8Array(buffer) : buffer; + var availableBytes = bytes.length - offset; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + + if (availableBytes >= 4) { + return view.getUint32(offset, littleEndian); + } else if (availableBytes === 3) { + var first = view.getUint16(offset, littleEndian); + var second = view.getUint8(offset + 2); + return littleEndian + ? ((second << 16) + first) >>> 0 + : ((first << 8) + second) << 8 >>> 0; + } else if (availableBytes === 2) { + return view.getUint16(offset, littleEndian) << (littleEndian ? 0 : 16) >>> 0; + } else if (availableBytes === 1) { + return view.getUint8(offset) << (littleEndian ? 0 : 24) >>> 0; + } + return 0x0; +} + +/** + * Writes a 32-bit unsigned int to buffer, but handles short lengths by not writing beyond the buffer. + * Used in bytesFromValue/pack by bitfield logic. + * @param {BufferSource} buffer - The buffer to write to. + * @param {number} offset - The byte offset to start writing. + * @param {number} data - The unsigned 32-bit integer to write. + * @param {boolean} littleEndian - Indicates whether to write little-endian. + */ +function truncatedWriteUInt32(buffer, offset, data, littleEndian) { + var bytes = (buffer instanceof ArrayBuffer) ? new Uint8Array(buffer) : buffer; + var availableBytes = bytes.length - offset; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + + if (availableBytes >= 4) { + view.setUint32(offset, data, littleEndian); + } else if (availableBytes === 3) { + if (littleEndian) { + view.setUint8(offset, data & 0xff); + view.setUint16(offset + 1, data >>> 8, littleEndian); + } else { + view.setUint16(offset, data >>> 16, littleEndian); + view.setUint8(offset + 2, (data >>> 8) & 0xff); + } + } else if (availableBytes === 2) { + view.setUint16(offset, littleEndian ? data & 0xffff : data >>> 16, littleEndian); + } else if (availableBytes === 1) { + view.setUint8(offset, littleEndian ? data & 0xff : data >>> 24); + } +} + +/** + * Defines a padding field up to the specified offset in bytes. + * @param {number} off - The byte offset to pad to. + * @returns {Field & {_padTo: number, _id?: string}} The padding field definition. + */ +_.padTo = function (off) { + var field = /** @type {Field & {_padTo: number}} */ ({ _padTo: off, + // Dummy implementations to satisfy Field: + size: 0, + unpack: function () { return null; }, + pack: function () { return newBuffer(0); } + }); + return field; +}; + + +// NOTE: bitfields must be embedded in a struct (C/C++ share this limitation) + +var FULL = 0xFFFFFFFF; + +/** + * A helper for big and little endian bitfields. + * @param {string} [name] - The name of the bitfield. + * @param {number} [width=1] - The width of the bitfield in bits. + * @param {number} [count] - The number of bitfields in an array. + * @returns {Field} The defined bitfield. + * @throws {Error} Bitfields support a maximum width of 24 bits + * @this {BitTransform} + */ +function bitfield(name, width, count) { + if (width === undefined) { + width = 1; + } + // NOTE: width limitation is so all values will align *within* a 4-byte word + if (width > 24) { + throw Error('Bitfields support a maximum width of 24 bits.'); + } + var mask = FULL >>> (32 - width); + var littleEndian = this.littleEndian; + if (littleEndian) { + mask >>>= 0; + } + + var impl = this; + return arrayizeField({ + /** + * @param {BufferSource} buf + * @param {Offset} [off] + * @returns {number|boolean} + * @this {Field & {width: number}} + */ + unpack: function (buf, off) { + off = off || { bytes: 0, bits: 0 }; + var over; + var end; + var word; + if (littleEndian) { + end = off.bits || 0; + word = truncatedReadUInt32(buf, off.bytes, true) >>> 0; + over = (word >>> end); + } else { + end = (off.bits || 0) + /** @type {number} */ (width); + word = truncatedReadUInt32(buf, off.bytes, false) || 0; + over = word >>> (32 - end); + } + addField(off, this); + return impl.b2v.call(this, over & mask); + }, + /** + * @param {number} val + * @param {BufferSource} [buf] + * @param {Offset} [off] + * @returns {Uint8Array} + * @this {Field & {width: number}} + */ + pack: function (val, buf, off) { + val = impl.v2b.call(this, val || 0); + if (!buf) { + buf = newBuffer(/** @type {number} */(this.size)); + } + off = off || { bytes: 0, bits: 0 }; + var word; + var zero; + var over; + if (littleEndian) { + word = truncatedReadUInt32(buf, off.bytes, true) >>> 0; + var shift = off.bits || 0; + zero = (mask << shift) >>> 0; + word &= ~zero; + over = (val & mask) << shift; + word = (word | over) >>> 0; // WORKAROUND: https://github.com/tessel/runtime/issues/644 + truncatedWriteUInt32(buf, off.bytes, word, true); + } else { + var end = (off.bits || 0) + /** @type {number} */ (width); + word = truncatedReadUInt32(buf, off.bytes, false) || 0; + zero = mask << (32 - end); + over = (val & mask) << (32 - end); + word &= ~zero; + word = (word | over) >>> 0; // WORKAROUND: https://github.com/tessel/runtime/issues/644 + truncatedWriteUInt32(buf, off.bytes, word, false); + } + addField(off, this); + return new Uint8Array(buf); + }, + width: width, + size: 0, // Placeholder for bitfields. + name: name + }, count); +} + +// // --------------------------------------------------------------------- +// // Begin Bitfield Definitions +// // --------------------------------------------------------------------- + +/** + * Boolean field: 1-bit big-endian bitfield that interprets 1/0 as true/false. + * @param {string} [name] + * @param {number} [count] + * @returns {Field} + */ +_.bool = function (name, count) { + return bitfield.call({ + /** + * Converts a bitfield to a boolean. + * @param {number} b - The bitfield value. + * @returns {boolean} The boolean representation. + */ + b2v: function (b) { return Boolean(b); }, + /** + * Converts a boolean to a bitfield. + * @param {number|boolean} v - The boolean value. + * @returns {number} The bitfield representation. + */ + v2b: function (v) { return v ? FULL : 0; } + }, name, 1, count); +}; + +/** + * Unsigned bitfield (big-endian). + */ +_.ubit = bitfield.bind({ + /** + * Converts a bitfield to a value. + * @param {number} b - The bitfield value. + * @returns {number} The numeric value. + */ + b2v: function (b) { return b; }, + /** + * Converts a value to a bitfield. + * @param {number|boolean} v - The numeric value. + * @returns {number} The bitfield representation. + */ + v2b: function (v) { return Number(v); } +}); + +/** + * Unsigned bitfield (little-endian). + * @param {string} name - The name of the bitfield. + * @param {number} [width=1] - The width of the bitfield in bits. + * @param {number} [count] - The number of bitfields in an array. + * @returns {Object} The defined little-endian bitfield. + */ +_.ubitLE = bitfield.bind({ + /** + * Converts a bitfield to a little-endian value. + * @param {number} b - The bitfield value. + * @returns {number} The little-endian numeric value. + */ + b2v: function (b) { return b; }, + /** + * Converts a little-endian value to a bitfield. + * @param {number|boolean} v - The little-endian numeric value. + * @returns {number} The bitfield representation. + */ + v2b: function (v) { return Number(v); }, + littleEndian: true +}); + +/** + * Signed bitfield (big-endian). + * @param {string} name - The name of the bitfield. + * @param {number} [width=1] - The width of the bitfield in bits. + * @param {number} [count] - The number of bitfields in an array. + * @returns {Object} The defined signed bitfield. + */ +_.sbit = bitfield.bind({ + /** + * Converts a bitfield to a signed value. + * @param {number} b - The bitfield value. + * @returns {number} The signed numeric value. + */ + b2v: function (b) { + var m = 1 << ((this.width || 1) - 1); + var s = b & m; + return (s) ? -(b &= ~m) : b; + }, + /** + * Converts a signed value to a bitfield. + * @param {number|boolean} v - The signed numeric value. + * @returns {number} The bitfield representation. + */ + v2b: function (v) { + v = Number(v); + var m = 1 << ((this.width || 1) - 1); + var s = (v < 0); + return (s) ? (-v | m) : v; + } +}); + +/** + * Creates a simple "byte field" for reading/writing raw bytes. + * @param {string|number} name - The name of the bytefield or its size if name is omitted. + * @param {number} [size=1] - The size of the bytefield in bytes. + * @param {number} [count] - The number of bytefields in an array. + * @returns {Field & ByteTransform} The defined bytefield. + * @this {ByteTransform} + */ +function bytefield(name, size, count) { + /** @type {string|undefined} */ + var fieldName; + /** @type {number} */ + var fieldSize = 1; + if (typeof name === 'string') { + fieldName = name; + if (typeof size === 'number') { + fieldSize = size; + } + } else { + // Shift params. + fieldSize = name; + count = size; // pass along + } + var impl = this; + + return /** @type {Field & ByteTransform} */ (arrayizeField(/** @type {Field & ByteTransform} */ ({ + name: fieldName, + size: fieldSize, + + /** + * @param {BufferSource} buf + * @param {Offset} [off] + * @returns {Uint8Array} + */ + unpack: function (buf, off) { + off = off || { bytes: 0, bits: 0 }; + var bytes = (buf instanceof ArrayBuffer) ? new Uint8Array(buf) : buf; + var val = bytes.subarray(off.bytes, off.bytes + /** @type {number} */ (this.size)); + addField(off, this); + return impl.b2v.call(this, val); + }, + + /** + * @param {Array|Uint8Array|ArrayBuffer} val + * @param {BufferSource} [buf] + * @param {Offset} [off] + * @returns {Uint8Array} + */ + pack: function (val, buf, off) { + if (!buf) { + buf = newBuffer(/** @type {number} */ (this.size)); + } + off = off || { bytes: 0, bits: 0 }; + var bytes = (buf instanceof ArrayBuffer) ? new Uint8Array(buf) : buf; + var blk = bytes.subarray(off.bytes, off.bytes + /** @type {number} */ (this.size)); + impl.vTb.call(this, val, blk); + addField(off, this); + return /** @type {Uint8Array} */ (buf); + }, + + // Default transforms: + /** + * @param {Uint8Array} b + * @returns {Uint8Array} + */ + b2v: function (b) { return b; }, + /** + * @param {Array|Uint8Array|ArrayBuffer} v + * @param {Uint8Array} b + * @returns {number} + */ + vTb: function (v, b) { + if (!v) return 0; + var src = new Uint8Array(v); + b.set(src.subarray(0, b.length)); + return b.length; + } + }), count)); +} + +/** + * Swaps adjacent byte pairs in a buffer, used for big-endian <-> little-endian char16 manipulations. + * http://stackoverflow.com/a/7460958/72637 + * @param {Uint8Array} fromBuffer - The source buffer. + * @param {Uint8Array} [toBuffer] - The destination buffer. If not provided, fromBuffer is modified. + * @returns {Uint8Array} The buffer with swapped byte pairs. + */ +function swapBytesPairs(fromBuffer, toBuffer) { + toBuffer = toBuffer || fromBuffer; + var l = fromBuffer.length; + for (var i = 1; i < l; i += 2) { + var a = fromBuffer[i - 1]; + toBuffer[i - 1] = fromBuffer[i]; + toBuffer[i] = a; + } + return toBuffer; +} + +/** Basic raw byte field. */ +_.byte = bytefield.bind({ + /** + * Converts bytes to a value. + * @param {BufferSource} b - The bytes to convert. + * @returns {Uint8Array} The byte value. + */ + b2v: function (b) { return new Uint8Array(b); }, + /** + * Converts a value to bytes. + * @param {BufferSource} v - The value to convert. + * @param {Uint8Array} b - The buffer to write to. + * @returns {number} The number of bytes written. + */ + vTb: function (v, b) { if (!v) return 0; b.set(new Uint8Array(v)); return v.byteLength; } +}); + +// // --------------------------------------------------------------------- +// // Character Field Definitions +// // --------------------------------------------------------------------- + +/** Null-terminated UTF-8 string field. */ +_.char = bytefield.bind({ + /** + * Converts bytes to a UTF-8 string. + * @param {BufferSource} b - The bytes to convert. + * @returns {string} The resulting string. + */ + b2v: function (b) { + var decoder; + if (typeof _TextDecoder !== 'undefined' && _TextDecoder) { + decoder = new _TextDecoder('utf-8'); + } else { + // Fallback minimal polyfill + decoder = { + /** + * @param {BufferSource} buf + * @returns {string} + */ + decode: function (buf) { + var bytes = new Uint8Array(buf); + var str = ''; + for (var i = 0; i < bytes.length; i++) { + str += String.fromCharCode(bytes[i]); + } + return str; + } + }; + } + var v = decoder.decode(b); + var z = v.indexOf('\0'); + return (~z) ? v.slice(0, z) : v; + }, + /** + * Converts a string to UTF-8 bytes. + * @param {string} v - The string to convert. + * @param {Uint8Array} b - The buffer to write to. + * @returns {number} The number of bytes written. + */ + vTb: function (v, b) { + v || (v = ''); + var encoder; + if (typeof _TextEncoder !== 'undefined' && _TextEncoder) { + encoder = new _TextEncoder(); + } else { + // Fallback minimal polyfill + encoder = { + /** + * @param {string} str + * @returns {Uint8Array} + */ + encode: function (str) { + var arr = new Uint8Array(str.length); + for (var i = 0; i < str.length; i++) { + arr[i] = str.charCodeAt(i) & 0xff; + } + return arr; + } + }; + } + var encoded = encoder.encode(v); + for (var i = 0; i < encoded.length && i < b.length; i++) { + b[i] = encoded[i]; + } + return encoded.length; + } +}); + +/** Null-terminated UTF-16LE string field. */ +_.char16le = bytefield.bind({ + /** + * Converts bytes to a UTF-16LE string. + * @param {BufferSource} b - The bytes to convert. + * @returns {string} The resulting string. + */ + b2v: function (b) { + var decoder; + if (typeof _TextDecoder !== 'undefined' && _TextDecoder) { + decoder = new _TextDecoder('utf-16le'); + } else { + // fallback + decoder = { + /** + * @param {BufferSource} buf + * @returns {string} + */ + decode: function (buf) { + var bytes = new Uint8Array(buf); + var str = ''; + for (var i = 0; i < bytes.length; i += 2) { + var charCode = bytes[i] | (bytes[i + 1] << 8); + str += String.fromCharCode(charCode); + } + return str; + } + }; + } + var v = decoder.decode(b); + var z = v.indexOf('\0'); + return (~z) ? v.slice(0, z) : v; + }, + /** + * Converts a string to UTF-16LE bytes. + * @param {string} v - The string to convert. + * @param {Uint8Array} b - The buffer to write to. + * @returns {number} The number of bytes written. + */ + vTb: function (v, b) { + v || (v = ''); + var bytesWritten = 0; + for (var i = 0; i < v.length && bytesWritten + 1 < b.length; i++) { + var charCode = v.charCodeAt(i); + b[bytesWritten++] = charCode & 0xFF; + b[bytesWritten++] = (charCode >> 8) & 0xFF; + } + return bytesWritten; + } +}); + +/** Null-terminated UTF-16BE string field. */ +_.char16be = bytefield.bind({ + /** + * Converts bytes to a UTF-16BE string. + * @param {BufferSource} b - The bytes to convert. + * @returns {string} The resulting string. + */ + b2v: function (b) { + var temp = new Uint8Array(b); + swapBytesPairs(temp); + var decoder; + if (typeof _TextDecoder !== 'undefined' && _TextDecoder) { + decoder = new _TextDecoder('utf-16le'); + } else { + // fallback + decoder = { + /** + * @param {BufferSource} buf + * @returns {string} + */ + decode: function (buf) { + var bytes = new Uint8Array(buf); + var str = ''; + for (var i = 0; i < bytes.length; i += 2) { + var charCode = bytes[i] | (bytes[i + 1] << 8); + str += String.fromCharCode(charCode); + } + return str; + } + }; + } + var v = decoder.decode(/** @type {ArrayBuffer} */ (temp.buffer)); + var z = v.indexOf('\0'); + return (~z) ? v.slice(0, z) : v; + }, + /** + * Converts a string to UTF-16BE bytes. + * @param {string} v - The string to convert. + * @param {Uint8Array} b - The buffer to write to. + * @returns {number} The number of bytes written. + */ + vTb: function (v, b) { + v || (v = ''); + var temp = new Uint8Array(b.length); + var bytesWritten = 0; + for (var i = 0; i < v.length && bytesWritten + 1 < temp.length; i++) { + var charCode = v.charCodeAt(i); + temp[bytesWritten++] = charCode & 0xFF; + temp[bytesWritten++] = (charCode >> 8) & 0xFF; + } + swapBytesPairs(temp, b); + return bytesWritten; + } +}); + +// // --------------------------------------------------------------------- +// // dataViewField Definition +// // --------------------------------------------------------------------- + +/** + * Defines a standard field based on read/write methods for a DataView. + * @param {function(this:DataView, number, boolean):number} getFn - The DataView getter. + * @param {function(this:DataView, number, number, boolean):void} setFn - The DataView setter. + * @param {number} size - The size of the field in bytes (4 for Uint32, etc.). + * @param {boolean} littleEndian - Indicates whether or not the field is little endian. + * @returns {function((string|number), number=): Field} A function to create the field. + */ +function dataViewField(getFn, setFn, size, littleEndian) { + /** + * @param {string|number} name + * @param {number} [count] + * @returns {Field} + */ + var func = function (name, count) { + /** @type {string|undefined} */ + var fieldName; + if (typeof name === 'string') { + fieldName = name; + } else { + // shift + count = name; + } + + return arrayizeField({ + name: fieldName, + size: size, + + /** + * @param {BufferSource} buf + * @param {Offset} [off] + * @returns {number} + */ + unpack: function (buf, off) { + off = off || { bytes: 0 }; + var bytes = (buf instanceof ArrayBuffer) ? new Uint8Array(buf) : buf; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + var val = getFn.call(view, off.bytes, littleEndian); + addField(off, this); + return val; + }, + /** + * @param {number} val + * @param {BufferSource} [buf] + * @param {Offset} [off] + * @returns {Uint8Array} + */ + pack: function (val, buf, off) { + if (val === undefined || val === null) { + val = 0; + } + if (!buf) { + buf = newBuffer(this.size); + } + off = off || { bytes: 0 }; + var bytes = (buf instanceof ArrayBuffer) ? new Uint8Array(buf) : buf; + var view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + setFn.call(view, off.bytes, val, littleEndian); + addField(off, this); + return new Uint8Array(buf); + } + }, count); + }; + return func; +} + +// // --------------------------------------------------------------------- +// // DataView Field Definitions +// // --------------------------------------------------------------------- + +var DV = DataView.prototype; // Alias for brevity. + +// Unsigned integers +_.uint8 = dataViewField(DV.getUint8, DV.setUint8, 1, false); +_.uint16 = dataViewField(DV.getUint16, DV.setUint16, 2, false); +_.uint32 = dataViewField(DV.getUint32, DV.setUint32, 4, false); +_.uint16le = dataViewField(DV.getUint16, DV.setUint16, 2, true); +_.uint32le = dataViewField(DV.getUint32, DV.setUint32, 4, true); + +// Signed integers +_.int8 = dataViewField(DV.getInt8, DV.setInt8, 1, false); +_.int16 = dataViewField(DV.getInt16, DV.setInt16, 2, false); +_.int32 = dataViewField(DV.getInt32, DV.setInt32, 4, false); +_.int16le = dataViewField(DV.getInt16, DV.setInt16, 2, true); +_.int32le = dataViewField(DV.getInt32, DV.setInt32, 4, true); + +// Floating-point numbers +_.float32 = dataViewField(DV.getFloat32, DV.setFloat32, 4, false); +_.float64 = dataViewField(DV.getFloat64, DV.setFloat64, 8, false); +_.float32le = dataViewField(DV.getFloat32, DV.setFloat32, 4, true); +_.float64le = dataViewField(DV.getFloat64, DV.setFloat64, 8, true); + +/** + * Derives a new field based on an existing one with custom pack and unpack functions. + * The types are intentionally any. + * @param {Field} orig - The original field to derive from. + * @param {function(*): *} pack - The function to pack the derived value. + * @param {function(*): *} unpack - The function to unpack the derived value. + * @returns {function((string|number)=, number=): Field} A function to create the derived field. + */ +_.derive = function (orig, pack, unpack) { + /** + * @param {string|number} [name] + * @param {number} [count] + * @returns {Field} + */ + var func = function (name, count) { + /** @type {string|null} */ + var fieldName = null; + if (typeof name === 'string') { + fieldName = name; + } else { + count = name; + } + + var derived = /** @type {Field} */ (extend({ + /** + * @param {BufferSource} buf + * @param {Offset} [off] + * @returns {*} + */ + unpack: function (buf, off) { + var rawVal = orig.unpack(buf, off); + return unpack(rawVal); + }, + /** + * @param {*} val + * @param {BufferSource} buf + * @param {Offset} [off] + * @returns {Uint8Array} + */ + pack: function (val, buf, off) { + var packed = pack(val); + return orig.pack(packed, buf, off); + }, + name: fieldName + }, + ('width' in orig) + ? { width: orig.width } + : { size: orig.size } + )); + + return arrayizeField(derived, count); + }; + return func; +}; + +// Return the `_` object for whichever loader environment we're in. +return _; +})); diff --git a/src/external/ffl/FFLTypes.ts b/src/external/ffl/FFLTypes.ts index 1159134..8e3367c 100644 --- a/src/external/ffl/FFLTypes.ts +++ b/src/external/ffl/FFLTypes.ts @@ -2,7 +2,7 @@ export function FFLiiGetEyebrowRotateOffset(type: number) { const ROTATE = [ 6, 6, 5, 7, 6, 7, 6, 7, 4, 7, 6, 8, 5, 5, 6, 6, 7, 7, 6, 6, 5, 6, 7, 5, - 6, 6, 6, 6, + 6, 6, 6, 6 ]; return 32 - ROTATE[type]; } @@ -20,7 +20,7 @@ export enum FFLFavoriteColor { FFL_FAVORITE_COLOR_BROWN = 9, FFL_FAVORITE_COLOR_WHITE = 10, FFL_FAVORITE_COLOR_BLACK = 11, - FFL_FAVORITE_COLOR_MAX = 12, + FFL_FAVORITE_COLOR_MAX = 12 } export const FFL_PATH_MAX_LEN = 256; @@ -79,3 +79,67 @@ export const FFLI_GLASS_COLOR_NUM = FFL_GLASS_COLOR_MAX; export const FFLI_MOUTH_COLOR_R_NUM = FFL_MOUTH_COLOR_MAX; export const FFLI_MOUTH_COLOR_G_NUM = FFL_MOUTH_COLOR_MAX; export const FFLI_FAVORITE_COLOR_NUM = 1; + +export enum MiiExpression { + Normal = 0, + Smile = 1, + Anger = 2, + Sorrow = 3, + Surprise = 4, + Blink = 5, + NormalOpenMouth = 6, + SmileOpenMouth = 7, + AngerOpenMouth = 8, + SurpriseOpenMouth = 9, + SorrowOpenMouth = 10, + BlinkOpenMouth = 11, + WinkLeftEyeOpen = 12, + WinkRightEyeOpen = 13, + WinkLeftEyeAndMouthOpen = 14, + WinkRightEyeAndMouthOpen = 15, + WinkLeftEyeOpenAndSmiling = 16, + WinkRightEyeOpenAndSmiling = 17, + Frustrated = 18, + Bored = 19, + BoredOpenMouth = 20, + SighMouthStraight = 21, + Sigh = 22, + DisgustedMouthStraight = 23, + Disgusted = 24, + Love = 25, + LoveMouthOpen = 26, + DeterminedMouthStraight = 27, + Determined = 28, + CryMouthStraight = 29, + Cry = 30, + BigSmileMouthStraight = 31, + BigSmile = 32, + Cheeky = 33, + ResolveEyesFunnyMouth = 35, + ResolveEyesFunnyMouthOpen = 36, + Smug = 37, + SmugMouthOpen = 38, + Resolve = 39, + ResolveMouthOpen = 40, + Unbelievable = 41, + Cunning = 43, + Raspberry = 45, + Innocent = 47, + Cat = 49, + Dog = 51, + Tasty = 53, + MoneyMouthStraight = 55, + Money = 56, + ConfusedMouthStraight = 57, + Confused = 58, + CheerfulMouthStraight = 59, + Cheerful = 60, + Blank = 61, + GrumbleMouthStraight = 63, + Grumble = 64, + MovedMouthStraight = 65, + Moved = 66, + SingingMouthSmall = 67, + Singing = 68, + Stunned = 69 +} diff --git a/src/external/ffl/FFLiCharInfo.ts b/src/external/ffl/FFLiCharInfo.ts index a0d96ff..2b73f47 100644 --- a/src/external/ffl/FFLiCharInfo.ts +++ b/src/external/ffl/FFLiCharInfo.ts @@ -1,4 +1,4 @@ -import type Mii from "../mii-js/mii"; +import type Mii from "../../class/MiiData"; export function FFLiiGetEyeRotateOffset(type: number) { const ROTATE: number[] = [ @@ -6,7 +6,7 @@ export function FFLiiGetEyeRotateOffset(type: number) { 4, 3, 4, 4, 3, 4, 4, 4, 3, 3, 3, 4, 4, 3, 3, 3, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 3, 4, 4, 3, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ]; return 32 - ROTATE[type]; } @@ -15,7 +15,7 @@ export function FFLiiGetEyebrowRotateOffset(type: number) { const ROTATE = [ 6, 6, 5, 7, 6, 7, 6, 7, 4, 7, 6, 8, 5, 5, 6, 6, 7, 7, 6, 6, 5, 6, 7, 5, - 6, 6, 6, 6, + 6, 6, 6, 6 ]; return 32 - ROTATE[type]; } @@ -115,74 +115,74 @@ export type FFLiCharInfo = { export enum FFLiOriginPosition { FFLI_ORIGIN_POSITION_CENTER = 0, FFLI_ORIGIN_POSITION_RIGHT = 1, - FFLI_ORIGIN_POSITION_LEFT = 2, + FFLI_ORIGIN_POSITION_LEFT = 2 } export const MiiClassToFFLiCharInfo = (mii: Mii): FFLiCharInfo => ({ - _112: mii.unknown1, - _114: mii.unknown2, - authorID: mii.systemId, + _112: 0, + _114: 0, + authorID: mii.authorId, birthDay: mii.birthDay, birthMonth: mii.birthMonth, - birthPlatform: mii.deviceOrigin, + birthPlatform: mii.originPlatform, build: mii.build, - copyable: Number(mii.allowCopying), - creatorID: mii.systemId, - creatorName: mii.creatorName, + copyable: Number(mii.createId), + creatorID: mii.createId, + creatorName: mii.creator, favoriteColor: mii.favoriteColor, favoriteMii: Number(mii.favorite), fontRegion: 0, gender: mii.gender, height: mii.height, localOnly: 0, - miiVersion: mii.version, - name: mii.miiName, + miiVersion: 3, + name: mii.nickname, ngWord: 0, - pageIndex: mii.pageIndex, + pageIndex: 0, parts: { - beardColor: mii.facialHairColor, + beardColor: mii.beardColor, beardType: mii.beardType, eyebrowColor: mii.eyebrowColor, - eyebrowPositionY: mii.eyebrowYPosition, - eyebrowRotate: mii.eyebrowRotation, + eyebrowPositionY: mii.eyebrowY, + eyebrowRotate: mii.eyebrowRotate, eyebrowScale: mii.eyebrowScale, - eyebrowScaleY: mii.eyebrowYPosition, - eyebrowSpacingX: mii.eyebrowSpacing, + eyebrowScaleY: mii.eyebrowAspect, + eyebrowSpacingX: mii.eyebrowX, eyebrowType: mii.eyebrowType, eyeColor: mii.eyeColor, - eyePositionY: mii.eyeYPosition, - eyeRotate: mii.eyeRotation, + eyePositionY: mii.eyeY, + eyeRotate: mii.eyeRotate, eyeScale: mii.eyeScale, - eyeScaleY: mii.eyeVerticalStretch, - eyeSpacingX: mii.eyeSpacing, + eyeScaleY: mii.eyeAspect, + eyeSpacingX: mii.eyeX, eyeType: mii.eyeType, - faceLine: mii.wrinklesType, - facelineColor: mii.skinColor, - faceMakeup: mii.makeupType, - faceType: mii.faceType, - glassColor: mii.glassesColor, - glassPositionY: mii.glassesYPosition, - glassScale: mii.glassesScale, - glassType: mii.glassesType, + faceLine: mii.facelineWrinkle, + facelineColor: mii.facelineColor, + faceMakeup: mii.facelineMake, + faceType: mii.facelineType, + glassColor: mii.glassColor, + glassPositionY: mii.glassY, + glassScale: mii.glassScale, + glassType: mii.glassType, hairColor: mii.hairColor, - hairDir: Number(mii.flipHair), + hairDir: Number(mii.hairFlip), hairType: mii.hairType, - molePositionX: mii.moleXPosition, - molePositionY: mii.moleYPosition, + molePositionX: mii.moleX, + molePositionY: mii.moleY, moleScale: mii.moleScale, - moleType: Number(mii.moleEnabled), + moleType: Number(mii.moleType), mouthColor: mii.mouthColor, - mouthPositionY: mii.mouthYPosition, + mouthPositionY: mii.mouthY, mouthScale: mii.mouthScale, - mouthScaleY: mii.mouthHorizontalStretch, + mouthScaleY: mii.mouthAspect, mouthType: mii.mouthType, - mustachePositionY: mii.mustacheYPosition, + mustachePositionY: mii.mustacheY, mustacheScale: mii.mustacheScale, mustacheType: mii.mustacheType, - nosePositionY: mii.noseYPosition, + nosePositionY: mii.noseY, noseScale: mii.noseScale, - noseType: mii.noseType, + noseType: mii.noseType }, - regionMove: mii.regionLock, - slotIndex: mii.slotIndex, + regionMove: mii.regionMove, + slotIndex: 0 }); diff --git a/src/external/ffl/FFLiDatabaseRandom.ts b/src/external/ffl/FFLiDatabaseRandom.ts index abe2140..f1caa7b 100644 --- a/src/external/ffl/FFLiDatabaseRandom.ts +++ b/src/external/ffl/FFLiDatabaseRandom.ts @@ -10,14 +10,21 @@ import { RANDOM_PARTS_ARRAY_HAIR_COLOR, RANDOM_PARTS_ARRAY_HAIR_TYPE, RANDOM_PARTS_ARRAY_MOUTH_TYPE, - RANDOM_PARTS_ARRAY_NOSE_TYPE, + RANDOM_PARTS_ARRAY_NOSE_TYPE } from "./RandomParts"; -import Mii from "../mii-js/mii"; +import Mii from "../../class/MiiData"; import { FFL_MOUTH_COLOR_MAX, FFLFavoriteColor, - FFLiiGetEyebrowRotateOffset, + FFLiiGetEyebrowRotateOffset } from "./FFLTypes"; +import { MiiCreatorOriginPlatform } from "../../class/struct/MiiCreatorV4Data"; +import { + Ver3EyeColorTable, + Ver3GlassColorTable, + Ver3HairColorTable, + Ver3MouthColorTable +} from "../../constants/ColorTables"; function DetermineParam( pGender: FFLGender, @@ -42,8 +49,8 @@ function DetermineParam( rnd < 4 ? FFLAge.FFL_AGE_CHILD : rnd < 8 - ? FFLAge.FFL_AGE_ADULT - : FFLAge.FFL_AGE_ELDER; + ? FFLAge.FFL_AGE_ADULT + : FFLAge.FFL_AGE_ELDER; } if (pRace == FFLRace.FFL_RACE_MAX) { @@ -53,8 +60,8 @@ function DetermineParam( rnd < 4 ? FFLRace.FFL_RACE_ASIAN : rnd < 8 - ? FFLRace.FFL_RACE_WHITE - : FFLRace.FFL_RACE_BLACK; + ? FFLRace.FFL_RACE_WHITE + : FFLRace.FFL_RACE_BLACK; } return [gender, age, race]; @@ -64,18 +71,18 @@ export enum FFLAge { FFL_AGE_CHILD = 0, FFL_AGE_ADULT = 1, FFL_AGE_ELDER = 2, - FFL_AGE_MAX = 3, + FFL_AGE_MAX = 3 } export enum FFLGender { FFL_GENDER_MALE = 0, FFL_GENDER_FEMALE = 1, - FFL_GENDER_MAX = 2, + FFL_GENDER_MAX = 2 } export enum FFLRace { FFL_RACE_BLACK = 0, FFL_RACE_WHITE = 1, FFL_RACE_ASIAN = 2, - FFL_RACE_MAX = 3, + FFL_RACE_MAX = 3 } function GetRandomGlassType(age: FFLAge) { @@ -90,10 +97,14 @@ export function GetRandomParts(array: any[]) { return array[1][Math.floor(Math.random() * array[0])]; } -const RANDOM_GLASS_TYPE: any[] = [ +const RANDOM_GLASS_TYPE: number[][] = [ [90, 94, 96, 100, 0, 0, 0, 0, 0], [83, 86, 90, 93, 94, 96, 98, 100, 0], - [78, 83, 0, 93, 0, 0, 98, 100, 0], + [78, 83, 0, 93, 0, 0, 98, 100, 0] +]; + +const EYE_Y_TO_GLASS_Y: any[] = [ + 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16 ]; // set these fields to "lock in" options when generating a random Mii @@ -107,6 +118,15 @@ export interface FFLiDatabaseRandom_GetInit { hairColor?: number; /** 0-5 */ eyeColor?: number; + + isOriginalMii?: boolean; +} + +export function roll(minPercentage: number) { + if (Math.floor(Math.random() * 100) >= 100 - minPercentage) { + return true; + } + return false; } // void FFLiDatabaseRandom::Get(FFLiCharInfo* pCharInfo, FFLGender gender, FFLAge age, FFLRace race) @@ -118,7 +138,7 @@ export function FFLiDatabaseRandom_Get( let [pGender, pAge, pRace] = [ FFLGender.FFL_GENDER_MAX, FFLAge.FFL_AGE_MAX, - FFLRace.FFL_RACE_MAX, + FFLRace.FFL_RACE_MAX ]; let [gender, age, race] = DetermineParam(pGender, pAge, pRace); @@ -134,105 +154,105 @@ export function FFLiDatabaseRandom_Get( console.log("Gender,age,race", gender, age, race); - // pCharInfo.miiVersion = 3; - pCharInfo.deviceOrigin = 3; - // s32 basePositionY = 0; + pCharInfo.originPlatform = MiiCreatorOriginPlatform.FFL_Wii_U; + let basePositionY = 0; - // if (gender == FFL_GENDER_FEMALE || age == FFL_AGE_CHILD) - // basePositionY = m_pRandomContext->Random(3); + if (gender == FFLGender.FFL_GENDER_FEMALE || age == FFLAge.FFL_AGE_CHILD) basePositionY = Math.floor(Math.random() * 3); - // pCharInfo.faceType = GetRandomParts(RANDOM_PARTS_ARRAY_FACE_TYPE[gender][age][race], m_pRandomContext); - // pCharInfo.facelineColor = GetRandomParts(RANDOM_PARTS_ARRAY_FACELINE_COLOR[gender][race], m_pRandomContext); - // pCharInfo.faceLine = GetRandomParts(RANDOM_PARTS_ARRAY_FACE_LINE[gender][age][race], m_pRandomContext); - // pCharInfo.faceMakeup = GetRandomParts(RANDOM_PARTS_ARRAY_FACE_MAKEUP[gender][age][race], m_pRandomContext); - // pCharInfo.hairType = GetRandomParts(RANDOM_PARTS_ARRAY_HAIR_TYPE[gender][age][race], m_pRandomContext); - // pCharInfo.hairColor = GetRandomParts(RANDOM_PARTS_ARRAY_HAIR_COLOR[race][age], m_pRandomContext); - // pCharInfo.hairDir = m_pRandomContext->Random(FFL_HAIR_DIR_MAX); - // pCharInfo.eyeType = GetRandomParts(RANDOM_PARTS_ARRAY_EYE_TYPE[gender][age][race], m_pRandomContext); - // pCharInfo.eyeColor = GetRandomParts(RANDOM_PARTS_ARRAY_EYE_COLOR[race], m_pRandomContext); - // pCharInfo.eyeScale = 4; - // pCharInfo.eyeScaleY = 3; - // s32 eyeRotateOffsetTarget; - pCharInfo.faceType = GetRandomParts( + + // faceline + pCharInfo.facelineType = GetRandomParts( RANDOM_PARTS_ARRAY_FACE_TYPE[gender][age][race] ); - pCharInfo.skinColor = GetRandomParts( + pCharInfo.facelineColor = GetRandomParts( RANDOM_PARTS_ARRAY_FACELINE_COLOR[gender][race] ); - pCharInfo.wrinklesType = GetRandomParts( + pCharInfo.facelineWrinkle = GetRandomParts( RANDOM_PARTS_ARRAY_FACE_LINE[gender][age][race] ); - pCharInfo.makeupType = GetRandomParts( + pCharInfo.facelineMake = GetRandomParts( RANDOM_PARTS_ARRAY_FACE_MAKEUP[gender][age][race] ); + + // hair pCharInfo.hairType = GetRandomParts( RANDOM_PARTS_ARRAY_HAIR_TYPE[gender][age][race] ); - pCharInfo.hairColor = GetRandomParts( - RANDOM_PARTS_ARRAY_HAIR_COLOR[race][age] - ); + pCharInfo.hairColor = + Ver3HairColorTable[ + GetRandomParts(RANDOM_PARTS_ARRAY_HAIR_COLOR[race][age]) + ]; if (fixedSettings.hairColor !== undefined) { - pCharInfo.hairColor = fixedSettings.hairColor; + pCharInfo.hairColor = Ver3HairColorTable[fixedSettings.hairColor]; } - pCharInfo.flipHair = Boolean(Math.ceil(Math.random() * 2)); + pCharInfo.hairFlip = Math.ceil(Math.random() * 2) - 1; + + // eyes pCharInfo.eyeType = GetRandomParts( RANDOM_PARTS_ARRAY_EYE_TYPE[gender][age][race] ); - pCharInfo.eyeColor = GetRandomParts(RANDOM_PARTS_ARRAY_EYE_COLOR[race]); + pCharInfo.eyeColor = + Ver3EyeColorTable[GetRandomParts(RANDOM_PARTS_ARRAY_EYE_COLOR[race])]; if (fixedSettings.eyeColor !== undefined) { - pCharInfo.eyeColor = fixedSettings.eyeColor; + pCharInfo.eyeColor = Ver3EyeColorTable[fixedSettings.eyeColor]; } pCharInfo.eyeScale = 4; - pCharInfo.eyeVerticalStretch = 3; + pCharInfo.eyeAspect = 3; let eyeRotateOffsetTarget: number; if (gender == FFLGender.FFL_GENDER_MALE) { - pCharInfo.eyeRotation = 4; + pCharInfo.eyeRotate = 4; eyeRotateOffsetTarget = FFLiiGetEyeRotateOffset(2); } else { - pCharInfo.eyeRotation = 3; + pCharInfo.eyeRotate = 3; eyeRotateOffsetTarget = FFLiiGetEyeRotateOffset(4); } const eyeRotateOffsetBase = FFLiiGetEyeRotateOffset(pCharInfo.eyeType); - pCharInfo.eyeSpacing = 2; - pCharInfo.eyeYPosition = basePositionY + 12; - pCharInfo.eyeRotation += eyeRotateOffsetTarget - eyeRotateOffsetBase; + pCharInfo.eyeX = 2; + pCharInfo.eyeY = basePositionY + 12; + pCharInfo.eyeRotate += eyeRotateOffsetTarget - eyeRotateOffsetBase; + + // eyebrows pCharInfo.eyebrowType = GetRandomParts( RANDOM_PARTS_ARRAY_EYEBROW_TYPE[gender][age][race] ); pCharInfo.eyebrowColor = pCharInfo.hairColor; pCharInfo.eyebrowScale = 4; - pCharInfo.eyebrowVerticalStretch = 3; - pCharInfo.eyebrowRotation = 6; - pCharInfo.eyebrowSpacing = 2; + pCharInfo.eyebrowAspect = 3; + pCharInfo.eyebrowRotate = 6; + pCharInfo.eyebrowX = 2; let eyebrowRotateOffsetTarget; if (race == FFLRace.FFL_RACE_ASIAN) { - pCharInfo.eyebrowYPosition = basePositionY + 9; + pCharInfo.eyebrowY = basePositionY + 9; eyebrowRotateOffsetTarget = FFLiiGetEyebrowRotateOffset(6); } else { - pCharInfo.eyebrowYPosition = basePositionY + 10; + pCharInfo.eyebrowY = basePositionY + 10; eyebrowRotateOffsetTarget = FFLiiGetEyebrowRotateOffset(0); } const eyebrowRotateOffsetBase = FFLiiGetEyebrowRotateOffset( pCharInfo.eyebrowType ); - pCharInfo.eyebrowRotation += + pCharInfo.eyebrowRotate += eyebrowRotateOffsetTarget - eyebrowRotateOffsetBase; + + // mouth/nose pCharInfo.noseType = GetRandomParts( RANDOM_PARTS_ARRAY_NOSE_TYPE[gender][age][race] ); pCharInfo.noseScale = gender == FFLGender.FFL_GENDER_MALE ? 4 : 3; - pCharInfo.noseYPosition = basePositionY + 9; + pCharInfo.noseY = basePositionY + 9; pCharInfo.mouthType = GetRandomParts( RANDOM_PARTS_ARRAY_MOUTH_TYPE[gender][age][race] ); pCharInfo.mouthColor = - gender == FFLGender.FFL_GENDER_MALE - ? 0 - : Math.floor(Math.random() * FFL_MOUTH_COLOR_MAX); + Ver3MouthColorTable[ + gender == FFLGender.FFL_GENDER_MALE + ? 0 + : Math.floor(Math.random() * FFL_MOUTH_COLOR_MAX) + ]; pCharInfo.mouthScale = 4; - pCharInfo.mouthHorizontalStretch = 3; - pCharInfo.mouthYPosition = basePositionY + 13; + pCharInfo.mouthAspect = 3; + pCharInfo.mouthY = basePositionY + 13; let mustacheType, beardType, mustachePositionY; if ( gender == FFLGender.FFL_GENDER_MALE && @@ -261,20 +281,20 @@ export function FFLiDatabaseRandom_Get( } pCharInfo.mustacheType = mustacheType; pCharInfo.beardType = beardType; - pCharInfo.facialHairColor = pCharInfo.hairColor; + pCharInfo.beardColor = pCharInfo.hairColor; pCharInfo.mustacheScale = 4; - pCharInfo.mustacheYPosition = mustachePositionY; - pCharInfo.glassesType = GetRandomGlassType(age); - pCharInfo.glassesColor = 0; - pCharInfo.glassesScale = 4; - pCharInfo.glassesYPosition = basePositionY + 10; - pCharInfo.moleEnabled = Boolean(0); + pCharInfo.mustacheY = mustachePositionY; + pCharInfo.glassType = GetRandomGlassType(age); + pCharInfo.glassColor = Ver3GlassColorTable[Math.floor(Math.random() * 6)]; + pCharInfo.glassScale = 4; + pCharInfo.glassY = basePositionY + 10; + pCharInfo.moleType = 0; pCharInfo.moleScale = 4; - pCharInfo.moleXPosition = 2; - pCharInfo.moleYPosition = 20; + pCharInfo.moleX = 2; + pCharInfo.moleY = 20; pCharInfo.height = 64; pCharInfo.build = 64; - pCharInfo.miiName = "no name"; + pCharInfo.nickname = "no name"; // creator name is unset pCharInfo.gender = gender; pCharInfo.birthMonth = 0; @@ -285,16 +305,191 @@ export function FFLiDatabaseRandom_Get( if (fixedSettings.favoriteColor !== undefined) { pCharInfo.favoriteColor = fixedSettings.favoriteColor; } - pCharInfo.favorite = false; - pCharInfo.allowCopying = true; - pCharInfo.profanityFlag = false; - // pCharInfo.nonUserMii= true; - pCharInfo.regionLock = 0; - pCharInfo.characterSet = 0; // FFL_FONT_REGION_JP_US_EU; - pCharInfo.pageIndex = 0; - pCharInfo.slotIndex = 0; - pCharInfo.deviceOrigin = 4; //FFL_BIRTH_PLATFORM_WII_U; - // pCharInfo.authorType = 0; + pCharInfo.favorite = 0; +} + +export function RandomizeMii( + pCharInfo: Mii, + options: FFLiDatabaseRandom_GetInit +) { + let [pGender, pAge, pRace] = [ + FFLGender.FFL_GENDER_MAX, + FFLAge.FFL_AGE_MAX, + FFLRace.FFL_RACE_MAX + ]; + let [gender, age, race] = DetermineParam(pGender, pAge, pRace); + + if (options.age !== undefined) { + age = options.age; + } + if (options.gender !== undefined) { + gender = options.gender; + } + if (options.race !== undefined) { + race = options.race; + } + + let basePositionY = 0; + + if (gender == FFLGender.FFL_GENDER_FEMALE || age == FFLAge.FFL_AGE_CHILD) + basePositionY = Math.floor(Math.random() * 3); + + // faceline + if (roll(6)) + pCharInfo.facelineType = GetRandomParts( + RANDOM_PARTS_ARRAY_FACE_TYPE[gender][age][race] + ); + if (roll(5)) + pCharInfo.facelineColor = GetRandomParts( + RANDOM_PARTS_ARRAY_FACELINE_COLOR[gender][race] + ); + if (roll(5)) + pCharInfo.facelineWrinkle = GetRandomParts( + RANDOM_PARTS_ARRAY_FACE_LINE[gender][age][race] + ); + if (roll(5)) + pCharInfo.facelineMake = GetRandomParts( + RANDOM_PARTS_ARRAY_FACE_MAKEUP[gender][age][race] + ); + + // hair + if (roll(7)) + pCharInfo.hairType = GetRandomParts( + RANDOM_PARTS_ARRAY_HAIR_TYPE[gender][age][race] + ); + if (roll(5)) + pCharInfo.hairColor = + Ver3HairColorTable[ + GetRandomParts(RANDOM_PARTS_ARRAY_HAIR_COLOR[race][age]) + ]; + if (options.hairColor !== undefined) { + pCharInfo.hairColor = Ver3HairColorTable[options.hairColor]; + } + if (roll(15)) pCharInfo.hairFlip = Math.ceil(Math.random() * 2) - 1; + + // eyes + if (roll(10)) + pCharInfo.eyeType = GetRandomParts( + RANDOM_PARTS_ARRAY_EYE_TYPE[gender][age][race] + ); + if (roll(5)) + pCharInfo.eyeColor = + Ver3EyeColorTable[GetRandomParts(RANDOM_PARTS_ARRAY_EYE_COLOR[race])]; + if (options.eyeColor !== undefined) { + pCharInfo.eyeColor = Ver3EyeColorTable[options.eyeColor]; + } + if (options.isOriginalMii !== true) { + pCharInfo.eyeScale = 4; + pCharInfo.eyeAspect = 3; + let eyeRotateOffsetTarget: number; + if (gender == FFLGender.FFL_GENDER_MALE) { + pCharInfo.eyeRotate = 4; + eyeRotateOffsetTarget = FFLiiGetEyeRotateOffset(2); + } else { + pCharInfo.eyeRotate = 3; + eyeRotateOffsetTarget = FFLiiGetEyeRotateOffset(4); + } + const eyeRotateOffsetBase = FFLiiGetEyeRotateOffset(pCharInfo.eyeType); + // pCharInfo.eyeX = 2; + // pCharInfo.eyeY = basePositionY + 12; + pCharInfo.eyeRotate += eyeRotateOffsetTarget - eyeRotateOffsetBase; + } + + // eyebrows + if (roll(15)) + pCharInfo.eyebrowType = GetRandomParts( + RANDOM_PARTS_ARRAY_EYEBROW_TYPE[gender][age][race] + ); + if (options.isOriginalMii !== true) { + pCharInfo.eyebrowColor = pCharInfo.hairColor; + pCharInfo.eyebrowScale = 4; + pCharInfo.eyebrowAspect = 3; + pCharInfo.eyebrowRotate = 6; + pCharInfo.eyebrowX = 2; + let eyebrowRotateOffsetTarget; + if (race == FFLRace.FFL_RACE_ASIAN) { + pCharInfo.eyebrowY = basePositionY + 9; + eyebrowRotateOffsetTarget = FFLiiGetEyebrowRotateOffset(6); + } else { + pCharInfo.eyebrowY = basePositionY + 10; + eyebrowRotateOffsetTarget = FFLiiGetEyebrowRotateOffset(0); + } + const eyebrowRotateOffsetBase = FFLiiGetEyebrowRotateOffset( + pCharInfo.eyebrowType + ); + pCharInfo.eyebrowRotate += + eyebrowRotateOffsetTarget - eyebrowRotateOffsetBase; + } + + // mouth/nose + if (roll(15)) + pCharInfo.noseType = GetRandomParts( + RANDOM_PARTS_ARRAY_NOSE_TYPE[gender][age][race] + ); + if (options.isOriginalMii !== true) { + pCharInfo.noseScale = gender == FFLGender.FFL_GENDER_MALE ? 4 : 3; + pCharInfo.noseY = basePositionY + 9; + } + pCharInfo.mouthType = GetRandomParts( + RANDOM_PARTS_ARRAY_MOUTH_TYPE[gender][age][race] + ); + if (roll(15)) + pCharInfo.mouthColor = + Ver3MouthColorTable[ + gender == FFLGender.FFL_GENDER_MALE + ? 0 + : Math.floor(Math.random() * FFL_MOUTH_COLOR_MAX) + ]; + if (options.isOriginalMii !== true) { + pCharInfo.mouthScale = 4; + pCharInfo.mouthAspect = 3; + pCharInfo.mouthY = basePositionY + 13; + } + let mustacheType, beardType, mustachePositionY; + if ( + gender == FFLGender.FFL_GENDER_MALE && + (age == FFLAge.FFL_AGE_ADULT || age == FFLAge.FFL_AGE_ELDER) && + Math.floor(Math.random() * 10) < 2 + ) { + mustacheType = 0; + let randomBeardType = false; + switch (Math.floor(Math.random() * 3)) { + case 0: + randomBeardType = true; + break; + //@ts-ignore fallthrough + case 2: + randomBeardType = true; // fall-through + case 1: + if (roll(15)) mustacheType = Math.floor(Math.random() * 5) + 1; + break; + } + beardType = randomBeardType ? Math.floor(Math.random() * 5) + 1 : 0; + mustachePositionY = 10; + } else { + mustacheType = 0; + beardType = 0; + mustachePositionY = basePositionY + 10; + } + if (roll(20)) pCharInfo.mustacheType = mustacheType; + if (roll(20)) pCharInfo.beardType = beardType; + pCharInfo.beardColor = pCharInfo.hairColor; + if (options.isOriginalMii !== true) { + pCharInfo.mustacheScale = 4; + pCharInfo.mustacheY = mustachePositionY; + } else { + // Calculate glass y position + if (pCharInfo.glassType === 0) { + pCharInfo.glassY = EYE_Y_TO_GLASS_Y[pCharInfo.eyeY]; + } + } + pCharInfo.glassType = GetRandomGlassType(age); + if (roll(20)) + pCharInfo.glassColor = Ver3GlassColorTable[Math.floor(Math.random() * 6)]; + if (options.isOriginalMii !== true) { + pCharInfo.glassScale = 4; + pCharInfo.glassY = basePositionY + 10; + } } //@ts-expect-error Debugging diff --git a/src/external/ffl/RandomParts.ts b/src/external/ffl/RandomParts.ts index 1305ee4..8546811 100644 --- a/src/external/ffl/RandomParts.ts +++ b/src/external/ffl/RandomParts.ts @@ -3,36 +3,36 @@ export const RANDOM_PARTS_ARRAY_FACE_TYPE = [ [ [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]], [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]], - [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]], + [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]] ], [ [12, [0, 0, 1, 2, 2, 3, 4, 5, 6, 7, 10, 11]], [13, [0, 1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 10, 11]], - [12, [0, 0, 1, 2, 2, 3, 4, 5, 6, 7, 10, 11]], + [12, [0, 0, 1, 2, 2, 3, 4, 5, 6, 7, 10, 11]] ], [ [12, [0, 0, 1, 2, 2, 3, 4, 5, 6, 7, 10, 11]], [13, [0, 1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 10, 11]], - [12, [0, 0, 1, 2, 2, 3, 4, 5, 6, 7, 10, 11]], - ], + [12, [0, 0, 1, 2, 2, 3, 4, 5, 6, 7, 10, 11]] + ] ], [ [ [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]], [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]], - [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]], + [10, [0, 0, 1, 1, 2, 3, 4, 5, 9, 9]] ], [ [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]], [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]], - [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]], + [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]] ], [ [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]], [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]], - [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]], - ], - ], + [12, [0, 0, 0, 1, 1, 1, 2, 3, 4, 5, 8, 10]] + ] + ] ]; export const RANDOM_PARTS_ARRAY_HAIR_TYPE = [ [ @@ -41,23 +41,23 @@ export const RANDOM_PARTS_ARRAY_HAIR_TYPE = [ 30, [ 13, 23, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 43, 44, 45, 47, 48, - 49, 50, 51, 52, 54, 56, 57, 64, 66, 75, 76, 86, 89, - ], + 49, 50, 51, 52, 54, 56, 57, 64, 66, 75, 76, 86, 89 + ] ], [ 31, [ 13, 23, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 43, 44, 45, 47, 48, - 49, 50, 51, 52, 54, 56, 57, 64, 66, 73, 75, 81, 86, 87, - ], + 49, 50, 51, 52, 54, 56, 57, 64, 66, 73, 75, 81, 86, 87 + ] ], [ 31, [ 13, 23, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 43, 44, 45, 47, 48, - 49, 50, 51, 52, 54, 56, 57, 64, 66, 73, 75, 81, 86, 87, - ], - ], + 49, 50, 51, 52, 54, 56, 57, 64, 66, 73, 75, 81, 86, 87 + ] + ] ], [ [ @@ -65,49 +65,46 @@ export const RANDOM_PARTS_ARRAY_HAIR_TYPE = [ [ 13, 23, 30, 31, 32, 33, 34, 36, 37, 38, 40, 42, 43, 44, 45, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60, 64, 65, 66, 67, 68, 70, - 75, 76, 86, 89, - ], + 75, 76, 86, 89 + ] ], [ 39, [ 13, 23, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 43, 44, 45, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60, 64, 65, 66, 67, 68, 70, - 73, 75, 81, 86, 87, - ], + 73, 75, 81, 86, 87 + ] ], [ 39, [ 13, 23, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 43, 44, 45, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60, 64, 65, 66, 67, 68, 70, - 73, 75, 81, 86, 87, - ], - ], + 73, 75, 81, 86, 87 + ] + ] ], [ [ 18, - [ - 13, 23, 30, 36, 37, 41, 45, 47, 51, 53, 54, 55, 58, 59, 65, 67, 86, - 88, - ], + [13, 23, 30, 36, 37, 41, 45, 47, 51, 53, 54, 55, 58, 59, 65, 67, 86, 88] ], [ 19, [ 13, 23, 30, 36, 37, 39, 41, 45, 47, 51, 53, 54, 55, 58, 59, 65, 67, - 86, 88, - ], + 86, 88 + ] ], [ 19, [ 13, 23, 30, 36, 37, 39, 41, 45, 47, 51, 53, 54, 55, 58, 59, 65, 67, - 86, 88, - ], - ], - ], + 86, 88 + ] + ] + ] ], [ [ @@ -116,25 +113,25 @@ export const RANDOM_PARTS_ARRAY_HAIR_TYPE = [ [ 0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 28, 46, 50, 61, 62, 63, 64, 69, 76, 77, 79, 80, - 83, 85, - ], + 83, 85 + ] ], [ 42, [ 0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 28, 46, 50, 61, 62, 63, 64, 69, 72, 74, 77, 78, - 82, 83, 84, 85, 87, - ], + 82, 83, 84, 85, 87 + ] ], [ 42, [ 0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 28, 46, 50, 61, 62, 63, 64, 69, 72, 74, 77, 78, - 82, 83, 84, 85, 87, - ], - ], + 82, 83, 84, 85, 87 + ] + ] ], [ [ @@ -142,50 +139,50 @@ export const RANDOM_PARTS_ARRAY_HAIR_TYPE = [ [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 29, 42, 50, 58, 60, 62, 63, 64, 69, 71, - 76, 79, 80, 81, 82, 83, 86, - ], + 76, 79, 80, 81, 82, 83, 86 + ] ], [ 44, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 29, 50, 58, 60, 62, 63, 64, 69, 71, 72, - 74, 79, 81, 82, 83, 84, 85, - ], + 74, 79, 81, 82, 83, 84, 85 + ] ], [ 44, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 29, 50, 58, 60, 62, 63, 64, 69, 71, 72, - 74, 79, 81, 82, 83, 84, 85, - ], - ], + 74, 79, 81, 82, 83, 84, 85 + ] + ] ], [ [ 24, [ 0, 1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 16, 17, 18, 20, 21, 24, 25, - 58, 62, 69, 76, 83, - ], + 58, 62, 69, 76, 83 + ] ], [ 27, [ 0, 1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 16, 17, 18, 20, 21, 24, 25, - 58, 62, 69, 74, 76, 81, 83, 85, - ], + 58, 62, 69, 74, 76, 81, 83, 85 + ] ], [ 27, [ 0, 1, 2, 3, 4, 5, 6, 10, 11, 12, 13, 14, 16, 17, 18, 20, 21, 24, 25, - 58, 62, 69, 74, 76, 81, 83, 85, - ], - ], - ], - ], + 58, 62, 69, 74, 76, 81, 83, 85 + ] + ] + ] + ] ]; export const RANDOM_PARTS_ARRAY_EYE_TYPE = [ [ @@ -194,70 +191,70 @@ export const RANDOM_PARTS_ARRAY_EYE_TYPE = [ 26, [ 2, 3, 5, 7, 8, 9, 11, 12, 13, 15, 16, 18, 27, 29, 32, 34, 36, 38, 39, - 41, 43, 47, 49, 51, 53, 57, - ], + 41, 43, 47, 49, 51, 53, 57 + ] ], [ 26, [ 2, 3, 5, 7, 8, 9, 11, 12, 13, 15, 16, 18, 27, 29, 32, 34, 36, 38, 39, - 41, 43, 47, 49, 51, 53, 57, - ], + 41, 43, 47, 49, 51, 53, 57 + ] ], [ 27, [ 2, 3, 5, 7, 8, 9, 11, 12, 13, 15, 16, 18, 26, 27, 29, 32, 34, 36, 38, - 39, 41, 43, 47, 48, 49, 53, 57, - ], - ], + 39, 41, 43, 47, 48, 49, 53, 57 + ] + ] ], [ [ 35, [ 2, 3, 5, 6, 7, 8, 9, 11, 12, 13, 15, 16, 17, 18, 21, 22, 27, 29, 31, - 32, 34, 36, 37, 38, 39, 41, 43, 44, 47, 49, 51, 53, 55, 56, 57, - ], + 32, 34, 36, 37, 38, 39, 41, 43, 44, 47, 49, 51, 53, 55, 56, 57 + ] ], [ 35, [ 2, 3, 5, 6, 7, 8, 9, 11, 12, 13, 15, 16, 17, 18, 21, 22, 27, 29, 31, - 32, 34, 36, 37, 38, 39, 41, 43, 44, 47, 49, 51, 53, 55, 56, 57, - ], + 32, 34, 36, 37, 38, 39, 41, 43, 44, 47, 49, 51, 53, 55, 56, 57 + ] ], [ 35, [ 2, 3, 5, 6, 7, 8, 9, 11, 12, 13, 15, 16, 18, 21, 22, 26, 27, 29, 31, - 32, 34, 36, 37, 38, 39, 41, 43, 44, 47, 48, 49, 50, 53, 56, 57, - ], - ], + 32, 34, 36, 37, 38, 39, 41, 43, 44, 47, 48, 49, 50, 53, 56, 57 + ] + ] ], [ [ 30, [ 2, 3, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 21, 22, 31, 32, 34, - 36, 37, 39, 41, 44, 49, 51, 53, 55, 56, 57, - ], + 36, 37, 39, 41, 44, 49, 51, 53, 55, 56, 57 + ] ], [ 30, [ 2, 3, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 21, 22, 31, 32, 34, - 36, 37, 39, 41, 44, 49, 51, 53, 55, 56, 57, - ], + 36, 37, 39, 41, 44, 49, 51, 53, 55, 56, 57 + ] ], [ 30, [ 2, 3, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 18, 21, 22, 26, 31, 32, 34, - 36, 37, 39, 41, 44, 48, 49, 50, 51, 53, 57, - ], - ], - ], + 36, 37, 39, 41, 44, 48, 49, 50, 51, 53, 57 + ] + ] + ] ], [ [ @@ -266,25 +263,25 @@ export const RANDOM_PARTS_ARRAY_EYE_TYPE = [ [ 0, 1, 2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 19, 23, 24, 25, 27, 28, 29, 32, 33, 34, 35, 38, 39, 40, 41, 42, 45, 46, 47, 48, 53, - 54, 57, 59, - ], + 54, 57, 59 + ] ], [ 39, [ 0, 1, 2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 19, 23, 24, 25, 27, 28, 29, 32, 33, 34, 35, 38, 39, 40, 41, 42, 45, 46, 47, 48, 53, - 54, 57, 59, - ], + 54, 57, 59 + ] ], [ 40, [ 0, 1, 2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 19, 23, 24, 25, 26, 27, 28, 29, 32, 33, 34, 35, 38, 39, 40, 41, 42, 45, 46, 47, 48, - 53, 54, 57, 59, - ], - ], + 53, 54, 57, 59 + ] + ] ], [ [ @@ -292,158 +289,158 @@ export const RANDOM_PARTS_ARRAY_EYE_TYPE = [ [ 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 27, 28, 29, 30, 32, 33, 34, 35, 37, 38, 39, 40, 41, 42, - 45, 46, 47, 48, 53, 54, 57, 58, 59, - ], + 45, 46, 47, 48, 53, 54, 57, 58, 59 + ] ], [ 46, [ 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 27, 28, 29, 30, 32, 33, 34, 35, 37, 38, 39, 40, 41, 42, - 45, 46, 47, 48, 53, 54, 57, 58, 59, - ], + 45, 46, 47, 48, 53, 54, 57, 58, 59 + ] ], [ 46, [ 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 37, 38, 39, 40, 41, 42, - 45, 46, 47, 48, 53, 54, 57, 58, 59, - ], - ], + 45, 46, 47, 48, 53, 54, 57, 58, 59 + ] + ] ], [ [ 34, [ 0, 1, 2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 19, 23, 24, 25, - 27, 28, 29, 32, 33, 34, 35, 38, 39, 40, 41, 42, 45, 46, 47, - ], + 27, 28, 29, 32, 33, 34, 35, 38, 39, 40, 41, 42, 45, 46, 47 + ] ], [ 34, [ 0, 1, 2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 19, 23, 24, 25, - 27, 28, 29, 32, 33, 34, 35, 38, 39, 40, 41, 42, 45, 46, 47, - ], + 27, 28, 29, 32, 33, 34, 35, 38, 39, 40, 41, 42, 45, 46, 47 + ] ], [ 35, [ 0, 1, 2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 15, 16, 18, 19, 23, 24, 25, - 26, 27, 28, 29, 32, 33, 34, 35, 38, 39, 40, 41, 42, 45, 46, 47, - ], - ], - ], - ], + 26, 27, 28, 29, 32, 33, 34, 35, 38, 39, 40, 41, 42, 45, 46, 47 + ] + ] + ] + ] ]; export const RANDOM_PARTS_ARRAY_EYEBROW_TYPE = [ [ [ [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18, 20]], [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18, 20]], - [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18, 20]], + [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18, 20]] ], [ [ 23, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, - ], + 20, 21, 22 + ] ], [ 23, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, - ], + 20, 21, 22 + ] ], [ 23, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, - ], - ], + 20, 21, 22 + ] + ] ], [ [ 21, [ 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, - 22, - ], + 22 + ] ], [ 21, [ 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, - 22, - ], + 22 + ] ], [ 21, [ 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, - 22, - ], - ], - ], + 22 + ] + ] + ] ], [ [ [9, [0, 1, 3, 7, 8, 9, 10, 11, 13]], [9, [0, 1, 3, 7, 8, 9, 10, 11, 13]], - [9, [0, 1, 3, 7, 8, 9, 10, 11, 13]], + [9, [0, 1, 3, 7, 8, 9, 10, 11, 13]] ], [ [11, [0, 1, 3, 7, 8, 9, 10, 11, 13, 15, 19]], [11, [0, 1, 3, 7, 8, 9, 10, 11, 13, 15, 19]], - [11, [0, 1, 3, 7, 8, 9, 10, 11, 13, 15, 19]], + [11, [0, 1, 3, 7, 8, 9, 10, 11, 13, 15, 19]] ], [ [9, [0, 3, 7, 8, 9, 10, 11, 13, 15]], [9, [0, 3, 7, 8, 9, 10, 11, 13, 15]], - [9, [0, 3, 7, 8, 9, 10, 11, 13, 15]], - ], - ], + [9, [0, 3, 7, 8, 9, 10, 11, 13, 15]] + ] + ] ]; export const RANDOM_PARTS_ARRAY_NOSE_TYPE = [ [ [ [11, [0, 1, 2, 3, 4, 5, 7, 8, 10, 13, 14]], [11, [0, 1, 2, 3, 4, 5, 7, 8, 10, 13, 14]], - [11, [0, 1, 2, 3, 4, 5, 7, 8, 10, 13, 14]], + [11, [0, 1, 2, 3, 4, 5, 7, 8, 10, 13, 14]] ], [ [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]], [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]], - [15, [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16]], + [15, [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16]] ], [ [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]], [18, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]], - [15, [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16]], - ], + [15, [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16]] + ] ], [ [ [8, [0, 1, 3, 4, 8, 10, 13, 14]], [8, [0, 1, 3, 4, 8, 10, 13, 14]], - [8, [0, 1, 3, 4, 8, 10, 13, 14]], + [8, [0, 1, 3, 4, 8, 10, 13, 14]] ], [ [12, [0, 1, 3, 4, 6, 8, 9, 10, 11, 13, 14, 15]], [11, [0, 1, 3, 4, 6, 8, 9, 10, 11, 13, 15]], - [10, [0, 1, 3, 4, 6, 8, 10, 11, 13, 14]], + [10, [0, 1, 3, 4, 6, 8, 10, 11, 13, 14]] ], [ [12, [0, 1, 3, 4, 6, 8, 9, 10, 11, 13, 14, 15]], [11, [0, 1, 3, 4, 6, 8, 9, 10, 11, 13, 15]], - [10, [0, 1, 3, 4, 6, 8, 10, 11, 13, 14]], - ], - ], + [10, [0, 1, 3, 4, 6, 8, 10, 11, 13, 14]] + ] + ] ]; export const RANDOM_PARTS_ARRAY_MOUTH_TYPE = [ [ @@ -452,70 +449,70 @@ export const RANDOM_PARTS_ARRAY_MOUTH_TYPE = [ 25, [ 0, 2, 3, 6, 7, 8, 9, 10, 12, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26, - 28, 30, 32, 33, 34, 35, - ], + 28, 30, 32, 33, 34, 35 + ] ], [ 27, [ 0, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 21, 22, 23, - 25, 26, 28, 30, 32, 33, 34, 35, - ], + 25, 26, 28, 30, 32, 33, 34, 35 + ] ], [ 28, [ 0, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 21, 22, 23, - 25, 26, 28, 30, 31, 32, 33, 34, 35, - ], - ], + 25, 26, 28, 30, 31, 32, 33, 34, 35 + ] + ] ], [ [ 24, [ 0, 2, 3, 6, 7, 8, 9, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 30, 31, 33, 34, 35, - ], + 30, 31, 33, 34, 35 + ] ], [ 26, [ 0, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 30, 31, 33, 34, 35, - ], + 22, 23, 30, 31, 33, 34, 35 + ] ], [ 26, [ 0, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 30, 31, 33, 34, 35, - ], - ], + 22, 23, 30, 31, 33, 34, 35 + ] + ] ], [ [ 24, [ 0, 2, 3, 6, 7, 8, 9, 10, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, - 30, 31, 33, 34, 35, - ], + 30, 31, 33, 34, 35 + ] ], [ 26, [ 0, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 30, 31, 33, 34, 35, - ], + 22, 23, 30, 31, 33, 34, 35 + ] ], [ 26, [ 0, 2, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 30, 31, 33, 34, 35, - ], - ], - ], + 22, 23, 30, 31, 33, 34, 35 + ] + ] + ] ], [ [ @@ -523,211 +520,211 @@ export const RANDOM_PARTS_ARRAY_MOUTH_TYPE = [ 25, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 14, 15, 17, 18, 19, 21, 22, 23, 25, - 26, 30, 33, 34, 35, - ], + 26, 30, 33, 34, 35 + ] ], [ 26, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 17, 18, 19, 21, 22, 23, - 25, 26, 30, 33, 34, 35, - ], + 25, 26, 30, 33, 34, 35 + ] ], [ 26, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 17, 18, 19, 21, 22, 23, - 25, 26, 30, 33, 34, 35, - ], - ], + 25, 26, 30, 33, 34, 35 + ] + ] ], [ [ 25, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 14, 15, 17, 18, 19, 21, 22, 23, 24, - 26, 27, 29, 33, 35, - ], + 26, 27, 29, 33, 35 + ] ], [ 26, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 17, 18, 19, 21, 22, 23, - 24, 26, 27, 29, 33, 35, - ], + 24, 26, 27, 29, 33, 35 + ] ], [ 25, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 17, 18, 19, 21, 22, 23, - 24, 25, 29, 33, 35, - ], - ], + 24, 25, 29, 33, 35 + ] + ] ], [ [ 24, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 14, 15, 16, 17, 18, 19, 21, 22, 23, - 25, 26, 29, 33, - ], + 25, 26, 29, 33 + ] ], [ 25, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, - 23, 25, 26, 29, 33, - ], + 23, 25, 26, 29, 33 + ] ], [ 25, [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, - 23, 25, 26, 29, 33, - ], - ], - ], - ], + 23, 25, 26, 29, 33 + ] + ] + ] + ] ]; export const RANDOM_PARTS_ARRAY_FACE_LINE = [ [ [ [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]], [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]], - [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8]] ], [ [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9]], [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9]], - [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] ], [ [ 20, [ 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, - 11, 11, - ], + 11, 11 + ] ], [ 20, [ 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, - 11, 11, - ], + 11, 11 + ] ], [ 20, [ 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, - 11, 11, - ], - ], - ], + 11, 11 + ] + ] + ] ], [ [ [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]], [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]], - [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8]] ], [ [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 4, 8, 8]], [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 4, 8, 8]], - [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 4]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 4]] ], [ [ 20, [ 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, - 11, - ], + 11 + ] ], [ 20, [ 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, - 11, - ], + 11 + ] ], [ 20, [ 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, - 11, - ], - ], - ], - ], + 11 + ] + ] + ] + ] ]; export const RANDOM_PARTS_ARRAY_FACE_MAKEUP = [ [ [ [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9]], - [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9]] ], [ [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]], [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]], - [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]] ], [ [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]], [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]], - [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]], - ], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9]] + ] ], [ [ [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2]], [20, [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 9, 9]], - [20, [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 9, 9]], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 9, 9]] ], [ [20, [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9]], [20, [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9]], - [20, [0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9, 9]], + [20, [0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9, 9]] ], [ [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], - [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], - ], - ], + [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] + ] + ] ]; export const RANDOM_PARTS_ARRAY_FACELINE_COLOR = [ [ [10, [2, 2, 4, 4, 4, 4, 5, 5, 5, 5]], [10, [0, 0, 0, 0, 1, 1, 2, 3, 3, 3]], - [10, [0, 0, 1, 1, 1, 1, 1, 1, 1, 2]], + [10, [0, 0, 1, 1, 1, 1, 1, 1, 1, 2]] ], [ [10, [2, 2, 4, 4, 4, 4, 5, 5, 5, 5]], [10, [0, 0, 0, 0, 0, 0, 0, 0, 1, 3]], - [10, [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]], - ], + [10, [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]] + ] ]; export const RANDOM_PARTS_ARRAY_HAIR_COLOR = [ [ [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], - [20, [0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]], + [20, [0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]] ], [ [20, [2, 3, 3, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7]], [20, [2, 3, 3, 3, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7]], - [20, [2, 3, 3, 4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7]], + [20, [2, 3, 3, 4, 4, 4, 4, 4, 4, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7]] ], [ [20, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]], [20, [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3]], - [20, [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]], - ], + [20, [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]] + ] ]; export const RANDOM_PARTS_ARRAY_EYE_COLOR = [ [10, [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], [10, [0, 1, 1, 2, 3, 3, 4, 4, 4, 5]], - [10, [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], + [10, [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]] ]; diff --git a/src/external/mii-frontend/all-kaitai-structs.js b/src/external/mii-frontend/all-kaitai-structs.js deleted file mode 100644 index 7a435b3..0000000 --- a/src/external/mii-frontend/all-kaitai-structs.js +++ /dev/null @@ -1,748 +0,0 @@ -import KaitaiStream from "./kaitai-stream.min.js"; - -window.KaitaiStream = KaitaiStream; -console.log("LOADED STRUCTS"); - -const me = window; - -(function (root, factory) { - root.Gen1Wii = factory(root.KaitaiStream); -})(typeof me !== "undefined" ? me : this, function (KaitaiStream) { - var Gen1Wii = (function () { - function Gen1Wii(_io, _parent, _root) { - this._io = _io; - this._parent = _parent; - this._root = _root || this; - this._read(); - } - Gen1Wii.prototype._read = function () { - this.invalid = this._io.readBitsIntBe(1) != 0; - this.gender = this._io.readBitsIntBe(1) != 0; - this.birthMonth = this._io.readBitsIntBe(4); - this.birthDay = this._io.readBitsIntBe(5); - this.favoriteColor = this._io.readBitsIntBe(4); - this.favorite = this._io.readBitsIntBe(1) != 0; - this._io.alignToByte(); - this.miiName = KaitaiStream.bytesToStr( - this._io.readBytes(20), - "utf-16be" - ); - this.bodyHeight = this._io.readU1(); - this.bodyWeight = this._io.readU1(); - this.avatarId = []; - for (var i = 0; i < 4; i++) { - this.avatarId.push(this._io.readU1()); - } - this.clientId = []; - for (var i = 0; i < 4; i++) { - this.clientId.push(this._io.readU1()); - } - this.faceType = this._io.readBitsIntBe(3); - this.faceColor = this._io.readBitsIntBe(3); - this.facialFeature = this._io.readBitsIntBe(4); - this.unknown = this._io.readBitsIntBe(3); - this.mingle = this._io.readBitsIntBe(1) != 0; - this.unknown2 = this._io.readBitsIntBe(1) != 0; - this.downloaded = this._io.readBitsIntBe(1) != 0; - this.hairType = this._io.readBitsIntBe(7); - this.hairColor = this._io.readBitsIntBe(3); - this.hairFlip = this._io.readBitsIntBe(1) != 0; - this.unknown3 = this._io.readBitsIntBe(5); - this.eyebrowType = this._io.readBitsIntBe(5); - this.unknown4 = this._io.readBitsIntBe(1) != 0; - this.eyebrowRotation = this._io.readBitsIntBe(4); - this.unknown5 = this._io.readBitsIntBe(6); - this.eyebrowColor = this._io.readBitsIntBe(3); - this.eyebrowSize = this._io.readBitsIntBe(4); - this.eyebrowVertical = this._io.readBitsIntBe(5); - this.eyebrowHorizontal = this._io.readBitsIntBe(4); - this.eyeType = this._io.readBitsIntBe(6); - this.unknown6 = this._io.readBitsIntBe(2); - this.eyeRotation = this._io.readBitsIntBe(3); - this.eyeVertical = this._io.readBitsIntBe(5); - this.eyeColor = this._io.readBitsIntBe(3); - this.unknown7 = this._io.readBitsIntBe(1) != 0; - this.eyeSize = this._io.readBitsIntBe(3); - this.eyeHorizontal = this._io.readBitsIntBe(4); - this.unknown8 = this._io.readBitsIntBe(5); - this.noseType = this._io.readBitsIntBe(4); - this.noseSize = this._io.readBitsIntBe(4); - this.noseVertical = this._io.readBitsIntBe(5); - this.unknown9 = this._io.readBitsIntBe(3); - this.mouthType = this._io.readBitsIntBe(5); - this.mouthColor = this._io.readBitsIntBe(2); - this.mouthSize = this._io.readBitsIntBe(4); - this.mouthVertical = this._io.readBitsIntBe(5); - this.glassesType = this._io.readBitsIntBe(4); - this.glassesColor = this._io.readBitsIntBe(3); - this.unknown10 = this._io.readBitsIntBe(1) != 0; - this.glassesSize = this._io.readBitsIntBe(3); - this.glassesVertical = this._io.readBitsIntBe(5); - this.facialHairMustache = this._io.readBitsIntBe(2); - this.facialHairBeard = this._io.readBitsIntBe(2); - this.facialHairColor = this._io.readBitsIntBe(3); - this.facialHairSize = this._io.readBitsIntBe(4); - this.facialHairVertical = this._io.readBitsIntBe(5); - this.moleEnable = this._io.readBitsIntBe(1) != 0; - this.moleSize = this._io.readBitsIntBe(4); - this.moleVertical = this._io.readBitsIntBe(5); - this.moleHorizontal = this._io.readBitsIntBe(5); - this.unknown11 = this._io.readBitsIntBe(1) != 0; - this._io.alignToByte(); - this.creatorName = KaitaiStream.bytesToStr( - this._io.readBytes(20), - "utf-16be" - ); - }; - return Gen1Wii; - })(); - return Gen1Wii; -}); -(function (root, factory) { - root.Gen2Wiiu3dsMiitomo = factory(root.KaitaiStream); -})(typeof me !== "undefined" ? me : this, function (KaitaiStream) { - var Gen2Wiiu3dsMiitomo = (function () { - function Gen2Wiiu3dsMiitomo(_io, _parent, _root) { - this._io = _io; - this._parent = _parent; - this._root = _root || this; - this._read(); - } - Gen2Wiiu3dsMiitomo.prototype._read = function () { - this.unknown1 = this._io.readU1(); - this.characterSet = this._io.readBitsIntBe(2); - this.regionLock = this._io.readBitsIntBe(2); - this.profanityFlag = this._io.readBitsIntBe(1) != 0; - this.copying = this._io.readBitsIntBe(1) != 0; - this.unknown2 = this._io.readBitsIntBe(2); - this.miiPositionSlotIndex = this._io.readBitsIntBe(4); - this.miiPositionPageIndex = this._io.readBitsIntBe(4); - this.version = this._io.readBitsIntBe(4); - this.unknown3 = this._io.readBitsIntBe(4); - this._io.alignToByte(); - this.systemId = []; - for (var i = 0; i < 8; i++) { - this.systemId.push(this._io.readU1()); - } - this.avatarId = []; - for (var i = 0; i < 4; i++) { - this.avatarId.push(this._io.readU1()); - } - this.clientId = []; - for (var i = 0; i < 6; i++) { - this.clientId.push(this._io.readU1()); - } - this.padding = this._io.readU2le(); - this.data1 = this._io.readU2le(); - this.miiName = KaitaiStream.bytesToStr( - this._io.readBytes(20), - "utf-16le" - ); - this.bodyHeight = this._io.readU1(); - this.bodyWeight = this._io.readU1(); - this.faceColor = this._io.readBitsIntBe(3); - this.faceType = this._io.readBitsIntBe(4); - this.mingle = this._io.readBitsIntBe(1) != 0; - this.faceMakeup = this._io.readBitsIntBe(4); - this.faceWrinkles = this._io.readBitsIntBe(4); - this._io.alignToByte(); - this.hairType = this._io.readU1(); - this.unknown5 = this._io.readBitsIntBe(4); - this.hairFlip = this._io.readBitsIntBe(1) != 0; - this.hairColor = this._io.readBitsIntBe(3); - this._io.alignToByte(); - this.eye = this._io.readU4le(); - this.eyebrow = this._io.readU4le(); - this.nose = this._io.readU2le(); - this.mouth = this._io.readU2le(); - this.mouth2 = this._io.readU2le(); - this.beard = this._io.readU2le(); - this.glasses = this._io.readU2le(); - this.mole = this._io.readU2le(); - this.creatorName = KaitaiStream.bytesToStr( - this._io.readBytes(20), - "utf-16le" - ); - this.padding2 = this._io.readU2le(); - this.checksum = this._io.readU2le(); - }; - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "glassesColor", { - get: function () { - if (this._m_glassesColor !== undefined) return this._m_glassesColor; - this._m_glassesColor = (this.glasses >>> 4) & 7; - return this._m_glassesColor; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyebrowHorizontal", { - get: function () { - if (this._m_eyebrowHorizontal !== undefined) - return this._m_eyebrowHorizontal; - this._m_eyebrowHorizontal = (this.eyebrow >>> 21) & 15; - return this._m_eyebrowHorizontal; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyeVertical", { - get: function () { - if (this._m_eyeVertical !== undefined) return this._m_eyeVertical; - this._m_eyeVertical = (this.eye >>> 25) & 31; - return this._m_eyeVertical; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "facialHairBeard", { - get: function () { - if (this._m_facialHairBeard !== undefined) - return this._m_facialHairBeard; - this._m_facialHairBeard = this.beard & 7; - return this._m_facialHairBeard; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "mouthSize", { - get: function () { - if (this._m_mouthSize !== undefined) return this._m_mouthSize; - this._m_mouthSize = (this.mouth >>> 9) & 15; - return this._m_mouthSize; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyebrowStretch", { - get: function () { - if (this._m_eyebrowStretch !== undefined) return this._m_eyebrowStretch; - this._m_eyebrowStretch = (this.eyebrow >>> 12) & 7; - return this._m_eyebrowStretch; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "noseVertical", { - get: function () { - if (this._m_noseVertical !== undefined) return this._m_noseVertical; - this._m_noseVertical = (this.nose >>> 9) & 31; - return this._m_noseVertical; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyeColor", { - get: function () { - if (this._m_eyeColor !== undefined) return this._m_eyeColor; - this._m_eyeColor = (this.eye >>> 6) & 7; - return this._m_eyeColor; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "birthMonth", { - get: function () { - if (this._m_birthMonth !== undefined) return this._m_birthMonth; - this._m_birthMonth = (this.data1 >>> 1) & 15; - return this._m_birthMonth; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "mouthColor", { - get: function () { - if (this._m_mouthColor !== undefined) return this._m_mouthColor; - this._m_mouthColor = (this.mouth >>> 6) & 7; - return this._m_mouthColor; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "moleHorizontal", { - get: function () { - if (this._m_moleHorizontal !== undefined) return this._m_moleHorizontal; - this._m_moleHorizontal = (this.mole >>> 5) & 31; - return this._m_moleHorizontal; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "facialHairMustache", { - get: function () { - if (this._m_facialHairMustache !== undefined) - return this._m_facialHairMustache; - this._m_facialHairMustache = (this.mouth2 >>> 5) & 7; - return this._m_facialHairMustache; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyebrowRotation", { - get: function () { - if (this._m_eyebrowRotation !== undefined) - return this._m_eyebrowRotation; - this._m_eyebrowRotation = (this.eyebrow >>> 16) & 15; - return this._m_eyebrowRotation; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "moleVertical", { - get: function () { - if (this._m_moleVertical !== undefined) return this._m_moleVertical; - this._m_moleVertical = (this.mole >>> 10) & 31; - return this._m_moleVertical; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "glassesType", { - get: function () { - if (this._m_glassesType !== undefined) return this._m_glassesType; - this._m_glassesType = this.glasses & 15; - return this._m_glassesType; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyebrowSize", { - get: function () { - if (this._m_eyebrowSize !== undefined) return this._m_eyebrowSize; - this._m_eyebrowSize = (this.eyebrow >>> 8) & 15; - return this._m_eyebrowSize; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "moleSize", { - get: function () { - if (this._m_moleSize !== undefined) return this._m_moleSize; - this._m_moleSize = (this.mole >>> 1) & 15; - return this._m_moleSize; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "noseSize", { - get: function () { - if (this._m_noseSize !== undefined) return this._m_noseSize; - this._m_noseSize = (this.nose >>> 5) & 15; - return this._m_noseSize; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "facialHairVertical", { - get: function () { - if (this._m_facialHairVertical !== undefined) - return this._m_facialHairVertical; - this._m_facialHairVertical = (this.beard >>> 10) & 31; - return this._m_facialHairVertical; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyeStretch", { - get: function () { - if (this._m_eyeStretch !== undefined) return this._m_eyeStretch; - this._m_eyeStretch = (this.eye >>> 13) & 7; - return this._m_eyeStretch; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyeSize", { - get: function () { - if (this._m_eyeSize !== undefined) return this._m_eyeSize; - this._m_eyeSize = (this.eye >>> 9) & 7; - return this._m_eyeSize; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyeType", { - get: function () { - if (this._m_eyeType !== undefined) return this._m_eyeType; - this._m_eyeType = this.eye & 63; - return this._m_eyeType; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyeHorizontal", { - get: function () { - if (this._m_eyeHorizontal !== undefined) return this._m_eyeHorizontal; - this._m_eyeHorizontal = (this.eye >>> 21) & 15; - return this._m_eyeHorizontal; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyebrowType", { - get: function () { - if (this._m_eyebrowType !== undefined) return this._m_eyebrowType; - this._m_eyebrowType = this.eyebrow & 31; - return this._m_eyebrowType; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "mouthVertical", { - get: function () { - if (this._m_mouthVertical !== undefined) return this._m_mouthVertical; - this._m_mouthVertical = this.mouth2 & 31; - return this._m_mouthVertical; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyebrowColor", { - get: function () { - if (this._m_eyebrowColor !== undefined) return this._m_eyebrowColor; - this._m_eyebrowColor = (this.eyebrow >>> 5) & 7; - return this._m_eyebrowColor; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "noseType", { - get: function () { - if (this._m_noseType !== undefined) return this._m_noseType; - this._m_noseType = this.nose & 31; - return this._m_noseType; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "facialHairColor", { - get: function () { - if (this._m_facialHairColor !== undefined) - return this._m_facialHairColor; - this._m_facialHairColor = (this.beard >>> 3) & 7; - return this._m_facialHairColor; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyebrowVertical", { - get: function () { - if (this._m_eyebrowVertical !== undefined) - return this._m_eyebrowVertical; - this._m_eyebrowVertical = (this.eyebrow >>> 25) & 31; - return this._m_eyebrowVertical; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "glassesSize", { - get: function () { - if (this._m_glassesSize !== undefined) return this._m_glassesSize; - this._m_glassesSize = (this.glasses >>> 7) & 15; - return this._m_glassesSize; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "eyeRotation", { - get: function () { - if (this._m_eyeRotation !== undefined) return this._m_eyeRotation; - this._m_eyeRotation = (this.eye >>> 16) & 31; - return this._m_eyeRotation; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "gender", { - get: function () { - if (this._m_gender !== undefined) return this._m_gender; - this._m_gender = this.data1 & 1; - return this._m_gender; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "birthDay", { - get: function () { - if (this._m_birthDay !== undefined) return this._m_birthDay; - this._m_birthDay = (this.data1 >>> 5) & 31; - return this._m_birthDay; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "mouthStretch", { - get: function () { - if (this._m_mouthStretch !== undefined) return this._m_mouthStretch; - this._m_mouthStretch = (this.mouth >>> 13) & 7; - return this._m_mouthStretch; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "moleEnable", { - get: function () { - if (this._m_moleEnable !== undefined) return this._m_moleEnable; - this._m_moleEnable = (this.mole >>> 0) & 1; - return this._m_moleEnable; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "favorite", { - get: function () { - if (this._m_favorite !== undefined) return this._m_favorite; - this._m_favorite = (this.data1 >>> 14) & 1; - return this._m_favorite; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "glassesVertical", { - get: function () { - if (this._m_glassesVertical !== undefined) - return this._m_glassesVertical; - this._m_glassesVertical = (this.glasses >>> 11) & 31; - return this._m_glassesVertical; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "favoriteColor", { - get: function () { - if (this._m_favoriteColor !== undefined) return this._m_favoriteColor; - this._m_favoriteColor = (this.data1 >>> 10) & 15; - return this._m_favoriteColor; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "mouthType", { - get: function () { - if (this._m_mouthType !== undefined) return this._m_mouthType; - this._m_mouthType = this.mouth & 63; - return this._m_mouthType; - }, - }); - Object.defineProperty(Gen2Wiiu3dsMiitomo.prototype, "facialHairSize", { - get: function () { - if (this._m_facialHairSize !== undefined) return this._m_facialHairSize; - this._m_facialHairSize = (this.beard >>> 6) & 15; - return this._m_facialHairSize; - }, - }); - return Gen2Wiiu3dsMiitomo; - })(); - return Gen2Wiiu3dsMiitomo; -}); -(function (root, factory) { - root.TomodachiLifeQrCode = factory(root.KaitaiStream); -})(typeof me !== "undefined" ? me : this, function (KaitaiStream) { - var TomodachiLifeQrCode = (function () { - function TomodachiLifeQrCode(_io, _parent, _root) { - this._io = _io; - this._parent = _parent; - this._root = _root || this; - this._read(); - } - TomodachiLifeQrCode.prototype._read = function () { - this.firstName = KaitaiStream.bytesToStr( - this._io.readBytes(32), - "UTF-16LE" - ); - this.lastName = KaitaiStream.bytesToStr( - this._io.readBytes(32), - "UTF-16LE" - ); - this.unknown = []; - for (var i = 0; i < 3; i++) { - this.unknown.push(this._io.readU1()); - } - this.hairDyeEnable = this._io.readBitsIntBe(1) != 0; - this.unknownb1 = this._io.readBitsIntBe(1) != 0; - this.hairDye = this._io.readBitsIntBe(5); - this.unknownb2 = this._io.readBitsIntBe(1) != 0; - this._io.alignToByte(); - this.unknown2 = []; - for (var i = 0; i < 12; i++) { - this.unknown2.push(this._io.readU1()); - } - this.catchphrase = KaitaiStream.bytesToStr( - this._io.readBytes(32), - "UTF-16LE" - ); - this.unknown3 = []; - for (var i = 0; i < 58; i++) { - this.unknown3.push(this._io.readU1()); - } - this.voicePitch = this._io.readU1(); - this.voiceSpeed = this._io.readU1(); - this.voiceQuality = this._io.readU1(); - this.voiceTone = this._io.readU1(); - this.voiceAccent = this._io.readU1(); - this.voiceInotation = this._io.readU1(); - this.characterMovement = this._io.readU1(); - this.characterSpeech = this._io.readU1(); - this.characterExpressiveness = this._io.readU1(); - this.characterAttitude = this._io.readU1(); - this.characterOverall = this._io.readU1(); - this.unknown4 = []; - for (var i = 0; i < 35; i++) { - this.unknown4.push(this._io.readU1()); - } - this.islandName = KaitaiStream.bytesToStr( - this._io.readBytes(20), - "UTF-16LE" - ); - }; - return TomodachiLifeQrCode; - })(); - return TomodachiLifeQrCode; -}); -(function (root, factory) { - root.Gen3Studio = factory(root.KaitaiStream); -})(typeof me !== "undefined" ? me : this, function (KaitaiStream) { - var Gen3Studio = (function () { - function Gen3Studio(_io, _parent, _root) { - this._io = _io; - this._parent = _parent; - this._root = _root || this; - this._read(); - } - Gen3Studio.prototype._read = function () { - this.facialHairColor = this._io.readU1(); - this.beardGoatee = this._io.readU1(); - this.bodyWeight = this._io.readU1(); - this.eyeStretch = this._io.readU1(); - this.eyeColor = this._io.readU1(); - this.eyeRotation = this._io.readU1(); - this.eyeSize = this._io.readU1(); - this.eyeType = this._io.readU1(); - this.eyeHorizontal = this._io.readU1(); - this.eyeVertical = this._io.readU1(); - this.eyebrowStretch = this._io.readU1(); - this.eyebrowColor = this._io.readU1(); - this.eyebrowRotation = this._io.readU1(); - this.eyebrowSize = this._io.readU1(); - this.eyebrowType = this._io.readU1(); - this.eyebrowHorizontal = this._io.readU1(); - this.eyebrowVertical = this._io.readU1(); - this.faceColor = this._io.readU1(); - this.faceMakeup = this._io.readU1(); - this.faceType = this._io.readU1(); - this.faceWrinkles = this._io.readU1(); - this.favoriteColor = this._io.readU1(); - this.gender = this._io.readU1(); - this.glassesColor = this._io.readU1(); - this.glassesSize = this._io.readU1(); - this.glassesType = this._io.readU1(); - this.glassesVertical = this._io.readU1(); - this.hairColor = this._io.readU1(); - this.hairFlip = this._io.readU1(); - this.hairType = this._io.readU1(); - this.bodyHeight = this._io.readU1(); - this.moleSize = this._io.readU1(); - this.moleEnable = this._io.readU1(); - this.moleHorizontal = this._io.readU1(); - this.moleVertical = this._io.readU1(); - this.mouthStretch = this._io.readU1(); - this.mouthColor = this._io.readU1(); - this.mouthSize = this._io.readU1(); - this.mouthType = this._io.readU1(); - this.mouthVertical = this._io.readU1(); - this.beardSize = this._io.readU1(); - this.beardMustache = this._io.readU1(); - this.beardVertical = this._io.readU1(); - this.noseSize = this._io.readU1(); - this.noseType = this._io.readU1(); - this.noseVertical = this._io.readU1(); - }; - return Gen3Studio; - })(); - return Gen3Studio; -}); -(function (root, factory) { - root.Gen3Switch = factory(root.KaitaiStream); -})(typeof me !== "undefined" ? me : this, function (KaitaiStream) { - var Gen3Switch = (function () { - function Gen3Switch(_io, _parent, _root) { - this._io = _io; - this._parent = _parent; - this._root = _root || this; - this._read(); - } - Gen3Switch.prototype._read = function () { - this.hairType = this._io.readU1(); - this.moleEnable = this._io.readBitsIntBe(1) != 0; - this.bodyHeight = this._io.readBitsIntBe(7); - this.hairFlip = this._io.readBitsIntBe(1) != 0; - this.bodyWeight = this._io.readBitsIntBe(7); - this.isSpecial = this._io.readBitsIntBe(1) != 0; - this.hairColor = this._io.readBitsIntBe(7); - this.gender = this._io.readBitsIntBe(1) != 0; - this.eyeColor = this._io.readBitsIntBe(7); - this._io.alignToByte(); - this.eyebrowColor = this._io.readU1(); - this.mouthColor = this._io.readU1(); - this.facialHairColor = this._io.readU1(); - this.glassesColor = this._io.readU1(); - this.regionLock = this._io.readBitsIntBe(2); - this.eyeType = this._io.readBitsIntBe(6); - this.fontRegion = this._io.readBitsIntBe(2); - this.mouthType = this._io.readBitsIntBe(6); - this.glassesSize = this._io.readBitsIntBe(3); - this.eyeVertical = this._io.readBitsIntBe(5); - this.facialHairMustache = this._io.readBitsIntBe(3); - this.eyebrowType = this._io.readBitsIntBe(5); - this.facialHairBeard = this._io.readBitsIntBe(3); - this.noseType = this._io.readBitsIntBe(5); - this.mouthStretch = this._io.readBitsIntBe(3); - this.noseVertical = this._io.readBitsIntBe(5); - this.eyebrowStretch = this._io.readBitsIntBe(3); - this.mouthVertical = this._io.readBitsIntBe(5); - this.eyeRotation = this._io.readBitsIntBe(3); - this.facialHairVertical = this._io.readBitsIntBe(5); - this.eyeStretch = this._io.readBitsIntBe(3); - this.glassesVertical = this._io.readBitsIntBe(5); - this.eyeSize = this._io.readBitsIntBe(3); - this.moleHorizontal = this._io.readBitsIntBe(5); - this._io.alignToByte(); - this.moleVertical = this._io.readU1(); - this.glassesType = this._io.readU1(); - this.faceType = this._io.readBitsIntBe(4); - this.favoriteColor = this._io.readBitsIntBe(4); - this.faceWrinkles = this._io.readBitsIntBe(4); - this.faceColor = this._io.readBitsIntBe(4); - this.eyeHorizontal = this._io.readBitsIntBe(4); - this.faceMakeup = this._io.readBitsIntBe(4); - this.eyebrowRotation = this._io.readBitsIntBe(4); - this.eyebrowSize = this._io.readBitsIntBe(4); - this.eyebrowVertical = this._io.readBitsIntBe(4); - this.eyebrowHorizontal = this._io.readBitsIntBe(4); - this.mouthSize = this._io.readBitsIntBe(4); - this.noseSize = this._io.readBitsIntBe(4); - this.moleSize = this._io.readBitsIntBe(4); - this.facialHairSize = this._io.readBitsIntBe(4); - this._io.alignToByte(); - this.miiName = KaitaiStream.bytesToStr( - this._io.readBytes(20), - "utf-16le" - ); - this.unknown = []; - for (var i = 0; i < 16; i++) { - this.unknown.push(this._io.readU1()); - } - this.miiId = []; - for (var i = 0; i < 4; i++) { - this.miiId.push(this._io.readU1()); - } - }; - return Gen3Switch; - })(); - return Gen3Switch; -}); -(function (root, factory) { - root.Gen3Switchgame = factory(root.KaitaiStream); -})(typeof me !== "undefined" ? me : this, function (KaitaiStream) { - var Gen3Switchgame = (function () { - function Gen3Switchgame(_io, _parent, _root) { - this._io = _io; - this._parent = _parent; - this._root = _root || this; - this._read(); - } - Gen3Switchgame.prototype._read = function () { - this.unknownData = []; - for (var i = 0; i < 16; i++) { - this.unknownData.push(this._io.readU1()); - } - this.miiName = KaitaiStream.bytesToStr( - this._io.readBytes(20), - "utf-16le" - ); - this.unknownBuffer = []; - for (var i = 0; i < 3; i++) { - this.unknownBuffer.push(this._io.readU1()); - } - this.favoriteColor = this._io.readU1(); - this.gender = this._io.readU1(); - this.bodyHeight = this._io.readU1(); - this.bodyWeight = this._io.readU1(); - this.unknownBuffer2 = []; - for (var i = 0; i < 2; i++) { - this.unknownBuffer2.push(this._io.readU1()); - } - this.faceType = this._io.readU1(); - this.faceColor = this._io.readU1(); - this.faceWrinkles = this._io.readU1(); - this.faceMakeup = this._io.readU1(); - this.hairType = this._io.readU1(); - this.hairColor = this._io.readU1(); - this.hairFlip = this._io.readU1(); - this.eyeType = this._io.readU1(); - this.eyeColor = this._io.readU1(); - this.eyeSize = this._io.readU1(); - this.eyeStretch = this._io.readU1(); - this.eyeRotation = this._io.readU1(); - this.eyeHorizontal = this._io.readU1(); - this.eyeVertical = this._io.readU1(); - this.eyebrowType = this._io.readU1(); - this.eyebrowColor = this._io.readU1(); - this.eyebrowSize = this._io.readU1(); - this.eyebrowStretch = this._io.readU1(); - this.eyebrowRotation = this._io.readU1(); - this.eyebrowHorizontal = this._io.readU1(); - this.eyebrowVertical = this._io.readU1(); - this.noseType = this._io.readU1(); - this.noseSize = this._io.readU1(); - this.noseVertical = this._io.readU1(); - this.mouthType = this._io.readU1(); - this.mouthColor = this._io.readU1(); - this.mouthSize = this._io.readU1(); - this.mouthStretch = this._io.readU1(); - this.mouthVertical = this._io.readU1(); - this.facialHairColor = this._io.readU1(); - this.facialHairBeard = this._io.readU1(); - this.facialHairMustache = this._io.readU1(); - this.facialHairSize = this._io.readU1(); - this.facialHairVertical = this._io.readU1(); - this.glassesType = this._io.readU1(); - this.glassesColor = this._io.readU1(); - this.glassesSize = this._io.readU1(); - this.glassesVertical = this._io.readU1(); - this.moleEnable = this._io.readU1(); - this.moleSize = this._io.readU1(); - this.moleHorizontal = this._io.readU1(); - this.moleVertical = this._io.readU1(); - this.unknownBuffer3 = []; - for (var i = 0; i < 1; i++) { - this.unknownBuffer3.push(this._io.readU1()); - } - }; - return Gen3Switchgame; - })(); - return Gen3Switchgame; -}); diff --git a/src/external/mii-frontend/crc16.js b/src/external/mii-frontend/crc16.js deleted file mode 100644 index f259902..0000000 --- a/src/external/mii-frontend/crc16.js +++ /dev/null @@ -1,2098 +0,0 @@ -var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); - -// node_modules/base64-js/index.js -var require_base64_js = __commonJS((exports) => { - function getLens(b64) { - var len2 = b64.length; - if (len2 % 4 > 0) { - throw new Error("Invalid string. Length must be a multiple of 4"); - } - var validLen = b64.indexOf("="); - if (validLen === -1) - validLen = len2; - var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; - return [validLen, placeHoldersLen]; - } - function byteLength(b64) { - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; - } - function _byteLength(b64, validLen, placeHoldersLen) { - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; - } - function toByteArray(b64) { - var tmp; - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); - var curByte = 0; - var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; - var i2; - for (i2 = 0;i2 < len2; i2 += 4) { - tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; - arr[curByte++] = tmp >> 16 & 255; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; - } - if (placeHoldersLen === 2) { - tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; - arr[curByte++] = tmp & 255; - } - if (placeHoldersLen === 1) { - tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; - } - return arr; - } - function tripletToBase64(num) { - return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; - } - function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - for (var i2 = start;i2 < end; i2 += 3) { - tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); - output.push(tripletToBase64(tmp)); - } - return output.join(""); - } - function fromByteArray(uint8) { - var tmp; - var len2 = uint8.length; - var extraBytes = len2 % 3; - var parts = []; - var maxChunkLength = 16383; - for (var i2 = 0, len22 = len2 - extraBytes;i2 < len22; i2 += maxChunkLength) { - parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength)); - } - if (extraBytes === 1) { - tmp = uint8[len2 - 1]; - parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="); - } else if (extraBytes === 2) { - tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; - parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="); - } - return parts.join(""); - } - exports.byteLength = byteLength; - exports.toByteArray = toByteArray; - exports.fromByteArray = fromByteArray; - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; - var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - for (i = 0, len = code.length;i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } - var i; - var len; - revLookup["-".charCodeAt(0)] = 62; - revLookup["_".charCodeAt(0)] = 63; -}); - -// node_modules/ieee754/index.js -var require_ieee754 = __commonJS((exports) => { - /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ - exports.read = function(buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? nBytes - 1 : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - i += d; - e = s & (1 << -nBits) - 1; - s >>= -nBits; - nBits += eLen; - for (;nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) { - } - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (;nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) { - } - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); - }; - exports.write = function(buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = isLE ? 0 : nBytes - 1; - var d = isLE ? 1 : -1; - var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - value = Math.abs(value); - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - for (;mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) { - } - e = e << mLen | m; - eLen += mLen; - for (;eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) { - } - buffer[offset + i - d] |= s * 128; - }; -}); - -// node_modules/buffer/index.js -function typedArraySupport() { - try { - const arr = new Uint8Array(1); - const proto = { foo: function() { - return 42; - } }; - Object.setPrototypeOf(proto, Uint8Array.prototype); - Object.setPrototypeOf(arr, proto); - return arr.foo() === 42; - } catch (e) { - return false; - } -} -function createBuffer(length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"'); - } - const buf = new Uint8Array(length); - Object.setPrototypeOf(buf, Buffer.prototype); - return buf; -} -function Buffer(arg, encodingOrOffset, length) { - if (typeof arg === "number") { - if (typeof encodingOrOffset === "string") { - throw new TypeError('The "string" argument must be of type string. Received type number'); - } - return allocUnsafe(arg); - } - return from(arg, encodingOrOffset, length); -} -function from(value, encodingOrOffset, length) { - if (typeof value === "string") { - return fromString(value, encodingOrOffset); - } - if (ArrayBuffer.isView(value)) { - return fromArrayView(value); - } - if (value == null) { - throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, " + "or Array-like Object. Received type " + typeof value); - } - if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) { - return fromArrayBuffer(value, encodingOrOffset, length); - } - if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length); - } - if (typeof value === "number") { - throw new TypeError('The "value" argument must not be of type number. Received type number'); - } - const valueOf = value.valueOf && value.valueOf(); - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length); - } - const b = fromObject(value); - if (b) - return b; - if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") { - return Buffer.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length); - } - throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, " + "or Array-like Object. Received type " + typeof value); -} -function assertSize(size) { - if (typeof size !== "number") { - throw new TypeError('"size" argument must be of type number'); - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"'); - } -} -function alloc(size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(size); - } - if (fill !== undefined) { - return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); - } - return createBuffer(size); -} -function allocUnsafe(size) { - assertSize(size); - return createBuffer(size < 0 ? 0 : checked(size) | 0); -} -function fromString(string, encoding) { - if (typeof encoding !== "string" || encoding === "") { - encoding = "utf8"; - } - if (!Buffer.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - const length = byteLength(string, encoding) | 0; - let buf = createBuffer(length); - const actual = buf.write(string, encoding); - if (actual !== length) { - buf = buf.slice(0, actual); - } - return buf; -} -function fromArrayLike(array) { - const length = array.length < 0 ? 0 : checked(array.length) | 0; - const buf = createBuffer(length); - for (let i = 0;i < length; i += 1) { - buf[i] = array[i] & 255; - } - return buf; -} -function fromArrayView(arrayView) { - if (isInstance(arrayView, Uint8Array)) { - const copy = new Uint8Array(arrayView); - return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength); - } - return fromArrayLike(arrayView); -} -function fromArrayBuffer(array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds'); - } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds'); - } - let buf; - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array); - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset); - } else { - buf = new Uint8Array(array, byteOffset, length); - } - Object.setPrototypeOf(buf, Buffer.prototype); - return buf; -} -function fromObject(obj) { - if (Buffer.isBuffer(obj)) { - const len = checked(obj.length) | 0; - const buf = createBuffer(len); - if (buf.length === 0) { - return buf; - } - obj.copy(buf, 0, 0, len); - return buf; - } - if (obj.length !== undefined) { - if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { - return createBuffer(0); - } - return fromArrayLike(obj); - } - if (obj.type === "Buffer" && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); - } -} -function checked(length) { - if (length >= K_MAX_LENGTH) { - throw new RangeError("Attempt to allocate Buffer larger than maximum " + "size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); - } - return length | 0; -} -function byteLength(string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length; - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength; - } - if (typeof string !== "string") { - throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + "Received type " + typeof string); - } - const len = string.length; - const mustMatch = arguments.length > 2 && arguments[2] === true; - if (!mustMatch && len === 0) - return 0; - let loweredCase = false; - for (;; ) { - switch (encoding) { - case "ascii": - case "latin1": - case "binary": - return len; - case "utf8": - case "utf-8": - return utf8ToBytes(string).length; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return len * 2; - case "hex": - return len >>> 1; - case "base64": - return base64ToBytes(string).length; - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length; - } - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } -} -function slowToString(encoding, start, end) { - let loweredCase = false; - if (start === undefined || start < 0) { - start = 0; - } - if (start > this.length) { - return ""; - } - if (end === undefined || end > this.length) { - end = this.length; - } - if (end <= 0) { - return ""; - } - end >>>= 0; - start >>>= 0; - if (end <= start) { - return ""; - } - if (!encoding) - encoding = "utf8"; - while (true) { - switch (encoding) { - case "hex": - return hexSlice(this, start, end); - case "utf8": - case "utf-8": - return utf8Slice(this, start, end); - case "ascii": - return asciiSlice(this, start, end); - case "latin1": - case "binary": - return latin1Slice(this, start, end); - case "base64": - return base64Slice(this, start, end); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return utf16leSlice(this, start, end); - default: - if (loweredCase) - throw new TypeError("Unknown encoding: " + encoding); - encoding = (encoding + "").toLowerCase(); - loweredCase = true; - } - } -} -function swap(b, n, m) { - const i = b[n]; - b[n] = b[m]; - b[m] = i; -} -function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { - if (buffer.length === 0) - return -1; - if (typeof byteOffset === "string") { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 2147483647) { - byteOffset = 2147483647; - } else if (byteOffset < -2147483648) { - byteOffset = -2147483648; - } - byteOffset = +byteOffset; - if (numberIsNaN(byteOffset)) { - byteOffset = dir ? 0 : buffer.length - 1; - } - if (byteOffset < 0) - byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) - return -1; - else - byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) - byteOffset = 0; - else - return -1; - } - if (typeof val === "string") { - val = Buffer.from(val, encoding); - } - if (Buffer.isBuffer(val)) { - if (val.length === 0) { - return -1; - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === "number") { - val = val & 255; - if (typeof Uint8Array.prototype.indexOf === "function") { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); - } - } - return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); - } - throw new TypeError("val must be string, number or Buffer"); -} -function arrayIndexOf(arr, val, byteOffset, encoding, dir) { - let indexSize = 1; - let arrLength = arr.length; - let valLength = val.length; - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { - if (arr.length < 2 || val.length < 2) { - return -1; - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - function read(buf, i2) { - if (indexSize === 1) { - return buf[i2]; - } else { - return buf.readUInt16BE(i2 * indexSize); - } - } - let i; - if (dir) { - let foundIndex = -1; - for (i = byteOffset;i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) - foundIndex = i; - if (i - foundIndex + 1 === valLength) - return foundIndex * indexSize; - } else { - if (foundIndex !== -1) - i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) - byteOffset = arrLength - valLength; - for (i = byteOffset;i >= 0; i--) { - let found = true; - for (let j = 0;j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break; - } - } - if (found) - return i; - } - } - return -1; -} -function hexWrite(buf, string, offset, length) { - offset = Number(offset) || 0; - const remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } - const strLen = string.length; - if (length > strLen / 2) { - length = strLen / 2; - } - let i; - for (i = 0;i < length; ++i) { - const parsed = parseInt(string.substr(i * 2, 2), 16); - if (numberIsNaN(parsed)) - return i; - buf[offset + i] = parsed; - } - return i; -} -function utf8Write(buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); -} -function asciiWrite(buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length); -} -function base64Write(buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length); -} -function ucs2Write(buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); -} -function base64Slice(buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf); - } else { - return base64.fromByteArray(buf.slice(start, end)); - } -} -function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - const res = []; - let i = start; - while (i < end) { - const firstByte = buf[i]; - let codePoint = null; - let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; - if (i + bytesPerSequence <= end) { - let secondByte, thirdByte, fourthByte, tempCodePoint; - switch (bytesPerSequence) { - case 1: - if (firstByte < 128) { - codePoint = firstByte; - } - break; - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 192) === 128) { - tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; - if (tempCodePoint > 127) { - codePoint = tempCodePoint; - } - } - break; - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; - if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { - codePoint = tempCodePoint; - } - } - break; - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; - if (tempCodePoint > 65535 && tempCodePoint < 1114112) { - codePoint = tempCodePoint; - } - } - } - } - if (codePoint === null) { - codePoint = 65533; - bytesPerSequence = 1; - } else if (codePoint > 65535) { - codePoint -= 65536; - res.push(codePoint >>> 10 & 1023 | 55296); - codePoint = 56320 | codePoint & 1023; - } - res.push(codePoint); - i += bytesPerSequence; - } - return decodeCodePointsArray(res); -} -function decodeCodePointsArray(codePoints) { - const len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); - } - let res = ""; - let i = 0; - while (i < len) { - res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); - } - return res; -} -function asciiSlice(buf, start, end) { - let ret = ""; - end = Math.min(buf.length, end); - for (let i = start;i < end; ++i) { - ret += String.fromCharCode(buf[i] & 127); - } - return ret; -} -function latin1Slice(buf, start, end) { - let ret = ""; - end = Math.min(buf.length, end); - for (let i = start;i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret; -} -function hexSlice(buf, start, end) { - const len = buf.length; - if (!start || start < 0) - start = 0; - if (!end || end < 0 || end > len) - end = len; - let out = ""; - for (let i = start;i < end; ++i) { - out += hexSliceLookupTable[buf[i]]; - } - return out; -} -function utf16leSlice(buf, start, end) { - const bytes = buf.slice(start, end); - let res = ""; - for (let i = 0;i < bytes.length - 1; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - return res; -} -function checkOffset(offset, ext, length) { - if (offset % 1 !== 0 || offset < 0) - throw new RangeError("offset is not uint"); - if (offset + ext > length) - throw new RangeError("Trying to access beyond buffer length"); -} -function checkInt(buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) - throw new TypeError('"buffer" argument must be a Buffer instance'); - if (value > max || value < min) - throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) - throw new RangeError("Index out of range"); -} -function wrtBigUInt64LE(buf, value, offset, min, max) { - checkIntBI(value, min, max, buf, offset, 7); - let lo = Number(value & BigInt(4294967295)); - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - let hi = Number(value >> BigInt(32) & BigInt(4294967295)); - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - return offset; -} -function wrtBigUInt64BE(buf, value, offset, min, max) { - checkIntBI(value, min, max, buf, offset, 7); - let lo = Number(value & BigInt(4294967295)); - buf[offset + 7] = lo; - lo = lo >> 8; - buf[offset + 6] = lo; - lo = lo >> 8; - buf[offset + 5] = lo; - lo = lo >> 8; - buf[offset + 4] = lo; - let hi = Number(value >> BigInt(32) & BigInt(4294967295)); - buf[offset + 3] = hi; - hi = hi >> 8; - buf[offset + 2] = hi; - hi = hi >> 8; - buf[offset + 1] = hi; - hi = hi >> 8; - buf[offset] = hi; - return offset + 8; -} -function checkIEEE754(buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) - throw new RangeError("Index out of range"); - if (offset < 0) - throw new RangeError("Index out of range"); -} -function writeFloat(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 340282346638528860000000000000000000000, -340282346638528860000000000000000000000); - } - ieee754.write(buf, value, offset, littleEndian, 23, 4); - return offset + 4; -} -function writeDouble(buf, value, offset, littleEndian, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, -179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000); - } - ieee754.write(buf, value, offset, littleEndian, 52, 8); - return offset + 8; -} -function E(sym, getMessage, Base) { - errors[sym] = class NodeError extends Base { - constructor() { - super(); - Object.defineProperty(this, "message", { - value: getMessage.apply(this, arguments), - writable: true, - configurable: true - }); - this.name = `${this.name} [${sym}]`; - this.stack; - delete this.name; - } - get code() { - return sym; - } - set code(value) { - Object.defineProperty(this, "code", { - configurable: true, - enumerable: true, - value, - writable: true - }); - } - toString() { - return `${this.name} [${sym}]: ${this.message}`; - } - }; -} -function addNumericalSeparator(val) { - let res = ""; - let i = val.length; - const start = val[0] === "-" ? 1 : 0; - for (;i >= start + 4; i -= 3) { - res = `_${val.slice(i - 3, i)}${res}`; - } - return `${val.slice(0, i)}${res}`; -} -function checkBounds(buf, offset, byteLength2) { - validateNumber(offset, "offset"); - if (buf[offset] === undefined || buf[offset + byteLength2] === undefined) { - boundsError(offset, buf.length - (byteLength2 + 1)); - } -} -function checkIntBI(value, min, max, buf, offset, byteLength2) { - if (value > max || value < min) { - const n = typeof min === "bigint" ? "n" : ""; - let range; - if (byteLength2 > 3) { - if (min === 0 || min === BigInt(0)) { - range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`; - } else { - range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ` + `${(byteLength2 + 1) * 8 - 1}${n}`; - } - } else { - range = `>= ${min}${n} and <= ${max}${n}`; - } - throw new errors.ERR_OUT_OF_RANGE("value", range, value); - } - checkBounds(buf, offset, byteLength2); -} -function validateNumber(value, name) { - if (typeof value !== "number") { - throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value); - } -} -function boundsError(value, length, type) { - if (Math.floor(value) !== value) { - validateNumber(value, type); - throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value); - } - if (length < 0) { - throw new errors.ERR_BUFFER_OUT_OF_BOUNDS; - } - throw new errors.ERR_OUT_OF_RANGE(type || "offset", `>= ${type ? 1 : 0} and <= ${length}`, value); -} -function base64clean(str) { - str = str.split("=")[0]; - str = str.trim().replace(INVALID_BASE64_RE, ""); - if (str.length < 2) - return ""; - while (str.length % 4 !== 0) { - str = str + "="; - } - return str; -} -function utf8ToBytes(string, units) { - units = units || Infinity; - let codePoint; - const length = string.length; - let leadSurrogate = null; - const bytes = []; - for (let i = 0;i < length; ++i) { - codePoint = string.charCodeAt(i); - if (codePoint > 55295 && codePoint < 57344) { - if (!leadSurrogate) { - if (codePoint > 56319) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - continue; - } else if (i + 1 === length) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - continue; - } - leadSurrogate = codePoint; - continue; - } - if (codePoint < 56320) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - leadSurrogate = codePoint; - continue; - } - codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; - } else if (leadSurrogate) { - if ((units -= 3) > -1) - bytes.push(239, 191, 189); - } - leadSurrogate = null; - if (codePoint < 128) { - if ((units -= 1) < 0) - break; - bytes.push(codePoint); - } else if (codePoint < 2048) { - if ((units -= 2) < 0) - break; - bytes.push(codePoint >> 6 | 192, codePoint & 63 | 128); - } else if (codePoint < 65536) { - if ((units -= 3) < 0) - break; - bytes.push(codePoint >> 12 | 224, codePoint >> 6 & 63 | 128, codePoint & 63 | 128); - } else if (codePoint < 1114112) { - if ((units -= 4) < 0) - break; - bytes.push(codePoint >> 18 | 240, codePoint >> 12 & 63 | 128, codePoint >> 6 & 63 | 128, codePoint & 63 | 128); - } else { - throw new Error("Invalid code point"); - } - } - return bytes; -} -function asciiToBytes(str) { - const byteArray = []; - for (let i = 0;i < str.length; ++i) { - byteArray.push(str.charCodeAt(i) & 255); - } - return byteArray; -} -function utf16leToBytes(str, units) { - let c, hi, lo; - const byteArray = []; - for (let i = 0;i < str.length; ++i) { - if ((units -= 2) < 0) - break; - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } - return byteArray; -} -function base64ToBytes(str) { - return base64.toByteArray(base64clean(str)); -} -function blitBuffer(src, dst, offset, length) { - let i; - for (i = 0;i < length; ++i) { - if (i + offset >= dst.length || i >= src.length) - break; - dst[i + offset] = src[i]; - } - return i; -} -function isInstance(obj, type) { - return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; -} -function numberIsNaN(obj) { - return obj !== obj; -} -function defineBigIntMethod(fn) { - return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; -} -function BufferBigIntNotDefined() { - throw new Error("BigInt not supported"); -} -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -var base64 = require_base64_js(); -var ieee754 = require_ieee754(); -var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; -var $Buffer = Buffer; -var $INSPECT_MAX_BYTES = 50; -var K_MAX_LENGTH = 2147483647; -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") { - console.error("This browser lacks typed array (Uint8Array) support which is required by " + "`buffer` v5.x. Use `buffer` v4.x if you require old browser support."); -} -Object.defineProperty(Buffer.prototype, "parent", { - enumerable: true, - get: function() { - if (!Buffer.isBuffer(this)) - return; - return this.buffer; - } -}); -Object.defineProperty(Buffer.prototype, "offset", { - enumerable: true, - get: function() { - if (!Buffer.isBuffer(this)) - return; - return this.byteOffset; - } -}); -Buffer.poolSize = 8192; -Buffer.from = function(value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length); -}; -Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); -Object.setPrototypeOf(Buffer, Uint8Array); -Buffer.alloc = function(size, fill, encoding) { - return alloc(size, fill, encoding); -}; -Buffer.allocUnsafe = function(size) { - return allocUnsafe(size); -}; -Buffer.allocUnsafeSlow = function(size) { - return allocUnsafe(size); -}; -Buffer.isBuffer = function isBuffer(b) { - return b != null && b._isBuffer === true && b !== Buffer.prototype; -}; -Buffer.compare = function compare(a, b) { - if (isInstance(a, Uint8Array)) - a = Buffer.from(a, a.offset, a.byteLength); - if (isInstance(b, Uint8Array)) - b = Buffer.from(b, b.offset, b.byteLength); - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'); - } - if (a === b) - return 0; - let x = a.length; - let y = b.length; - for (let i = 0, len = Math.min(x, y);i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - if (x < y) - return -1; - if (y < x) - return 1; - return 0; -}; -Buffer.isEncoding = function isEncoding(encoding) { - switch (String(encoding).toLowerCase()) { - case "hex": - case "utf8": - case "utf-8": - case "ascii": - case "latin1": - case "binary": - case "base64": - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return true; - default: - return false; - } -}; -Buffer.concat = function concat(list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - if (list.length === 0) { - return Buffer.alloc(0); - } - let i; - if (length === undefined) { - length = 0; - for (i = 0;i < list.length; ++i) { - length += list[i].length; - } - } - const buffer = Buffer.allocUnsafe(length); - let pos = 0; - for (i = 0;i < list.length; ++i) { - let buf = list[i]; - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer.length) { - if (!Buffer.isBuffer(buf)) - buf = Buffer.from(buf); - buf.copy(buffer, pos); - } else { - Uint8Array.prototype.set.call(buffer, buf, pos); - } - } else if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } else { - buf.copy(buffer, pos); - } - pos += buf.length; - } - return buffer; -}; -Buffer.byteLength = byteLength; -Buffer.prototype._isBuffer = true; -Buffer.prototype.swap16 = function swap16() { - const len = this.length; - if (len % 2 !== 0) { - throw new RangeError("Buffer size must be a multiple of 16-bits"); - } - for (let i = 0;i < len; i += 2) { - swap(this, i, i + 1); - } - return this; -}; -Buffer.prototype.swap32 = function swap32() { - const len = this.length; - if (len % 4 !== 0) { - throw new RangeError("Buffer size must be a multiple of 32-bits"); - } - for (let i = 0;i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this; -}; -Buffer.prototype.swap64 = function swap64() { - const len = this.length; - if (len % 8 !== 0) { - throw new RangeError("Buffer size must be a multiple of 64-bits"); - } - for (let i = 0;i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); - } - return this; -}; -Buffer.prototype.toString = function toString() { - const length = this.length; - if (length === 0) - return ""; - if (arguments.length === 0) - return utf8Slice(this, 0, length); - return slowToString.apply(this, arguments); -}; -Buffer.prototype.toLocaleString = Buffer.prototype.toString; -Buffer.prototype.equals = function equals(b) { - if (!Buffer.isBuffer(b)) - throw new TypeError("Argument must be a Buffer"); - if (this === b) - return true; - return Buffer.compare(this, b) === 0; -}; -Buffer.prototype.inspect = function inspect() { - let str = ""; - const max = $INSPECT_MAX_BYTES; - str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); - if (this.length > max) - str += " ... "; - return ""; -}; -if (customInspectSymbol) { - Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; -} -Buffer.prototype.compare = function compare2(target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength); - } - if (!Buffer.isBuffer(target)) { - throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. ' + "Received type " + typeof target); - } - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError("out of range index"); - } - if (thisStart >= thisEnd && start >= end) { - return 0; - } - if (thisStart >= thisEnd) { - return -1; - } - if (start >= end) { - return 1; - } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - if (this === target) - return 0; - let x = thisEnd - thisStart; - let y = end - start; - const len = Math.min(x, y); - const thisCopy = this.slice(thisStart, thisEnd); - const targetCopy = target.slice(start, end); - for (let i = 0;i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break; - } - } - if (x < y) - return -1; - if (y < x) - return 1; - return 0; -}; -Buffer.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; -}; -Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); -}; -Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); -}; -Buffer.prototype.write = function write(string, offset, length, encoding) { - if (offset === undefined) { - encoding = "utf8"; - length = this.length; - offset = 0; - } else if (length === undefined && typeof offset === "string") { - encoding = offset; - length = this.length; - offset = 0; - } else if (isFinite(offset)) { - offset = offset >>> 0; - if (isFinite(length)) { - length = length >>> 0; - if (encoding === undefined) - encoding = "utf8"; - } else { - encoding = length; - length = undefined; - } - } else { - throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported"); - } - const remaining = this.length - offset; - if (length === undefined || length > remaining) - length = remaining; - if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { - throw new RangeError("Attempt to write outside buffer bounds"); - } - if (!encoding) - encoding = "utf8"; - let loweredCase = false; - for (;; ) { - switch (encoding) { - case "hex": - return hexWrite(this, string, offset, length); - case "utf8": - case "utf-8": - return utf8Write(this, string, offset, length); - case "ascii": - case "latin1": - case "binary": - return asciiWrite(this, string, offset, length); - case "base64": - return base64Write(this, string, offset, length); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return ucs2Write(this, string, offset, length); - default: - if (loweredCase) - throw new TypeError("Unknown encoding: " + encoding); - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } -}; -Buffer.prototype.toJSON = function toJSON() { - return { - type: "Buffer", - data: Array.prototype.slice.call(this._arr || this, 0) - }; -}; -var MAX_ARGUMENTS_LENGTH = 4096; -Buffer.prototype.slice = function slice(start, end) { - const len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; - if (start < 0) { - start += len; - if (start < 0) - start = 0; - } else if (start > len) { - start = len; - } - if (end < 0) { - end += len; - if (end < 0) - end = 0; - } else if (end > len) { - end = len; - } - if (end < start) - end = start; - const newBuf = this.subarray(start, end); - Object.setPrototypeOf(newBuf, Buffer.prototype); - return newBuf; -}; -Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - let val = this[offset]; - let mul = 1; - let i = 0; - while (++i < byteLength2 && (mul *= 256)) { - val += this[offset + i] * mul; - } - return val; -}; -Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - checkOffset(offset, byteLength2, this.length); - } - let val = this[offset + --byteLength2]; - let mul = 1; - while (byteLength2 > 0 && (mul *= 256)) { - val += this[offset + --byteLength2] * mul; - } - return val; -}; -Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 1, this.length); - return this[offset]; -}; -Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - return this[offset] | this[offset + 1] << 8; -}; -Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - return this[offset] << 8 | this[offset + 1]; -}; -Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; -}; -Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); -}; -Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === undefined || last === undefined) { - boundsError(offset, this.length - 8); - } - const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; - const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24; - return BigInt(lo) + (BigInt(hi) << BigInt(32)); -}); -Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === undefined || last === undefined) { - boundsError(offset, this.length - 8); - } - const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; - const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last; - return (BigInt(hi) << BigInt(32)) + BigInt(lo); -}); -Buffer.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - let val = this[offset]; - let mul = 1; - let i = 0; - while (++i < byteLength2 && (mul *= 256)) { - val += this[offset + i] * mul; - } - mul *= 128; - if (val >= mul) - val -= Math.pow(2, 8 * byteLength2); - return val; -}; -Buffer.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) { - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) - checkOffset(offset, byteLength2, this.length); - let i = byteLength2; - let mul = 1; - let val = this[offset + --i]; - while (i > 0 && (mul *= 256)) { - val += this[offset + --i] * mul; - } - mul *= 128; - if (val >= mul) - val -= Math.pow(2, 8 * byteLength2); - return val; -}; -Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 1, this.length); - if (!(this[offset] & 128)) - return this[offset]; - return (255 - this[offset] + 1) * -1; -}; -Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - const val = this[offset] | this[offset + 1] << 8; - return val & 32768 ? val | 4294901760 : val; -}; -Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 2, this.length); - const val = this[offset + 1] | this[offset] << 8; - return val & 32768 ? val | 4294901760 : val; -}; -Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; -}; -Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; -}; -Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === undefined || last === undefined) { - boundsError(offset, this.length - 8); - } - const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24); - return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); -}); -Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === undefined || last === undefined) { - boundsError(offset, this.length - 8); - } - const val = (first << 24) + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; - return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last); -}); -Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, true, 23, 4); -}; -Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 4, this.length); - return ieee754.read(this, offset, false, 23, 4); -}; -Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, true, 52, 8); -}; -Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) - checkOffset(offset, 8, this.length); - return ieee754.read(this, offset, false, 52, 8); -}; -Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength2) - 1; - checkInt(this, value, offset, byteLength2, maxBytes, 0); - } - let mul = 1; - let i = 0; - this[offset] = value & 255; - while (++i < byteLength2 && (mul *= 256)) { - this[offset + i] = value / mul & 255; - } - return offset + byteLength2; -}; -Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - byteLength2 = byteLength2 >>> 0; - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength2) - 1; - checkInt(this, value, offset, byteLength2, maxBytes, 0); - } - let i = byteLength2 - 1; - let mul = 1; - this[offset + i] = value & 255; - while (--i >= 0 && (mul *= 256)) { - this[offset + i] = value / mul & 255; - } - return offset + byteLength2; -}; -Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 1, 255, 0); - this[offset] = value & 255; - return offset + 1; -}; -Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 65535, 0); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - return offset + 2; -}; -Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 65535, 0); - this[offset] = value >>> 8; - this[offset + 1] = value & 255; - return offset + 2; -}; -Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 4294967295, 0); - this[offset + 3] = value >>> 24; - this[offset + 2] = value >>> 16; - this[offset + 1] = value >>> 8; - this[offset] = value & 255; - return offset + 4; -}; -Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 4294967295, 0); - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 255; - return offset + 4; -}; -Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) { - return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); -}); -Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) { - return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff")); -}); -Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - const limit = Math.pow(2, 8 * byteLength2 - 1); - checkInt(this, value, offset, byteLength2, limit - 1, -limit); - } - let i = 0; - let mul = 1; - let sub = 0; - this[offset] = value & 255; - while (++i < byteLength2 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - this[offset + i] = (value / mul >> 0) - sub & 255; - } - return offset + byteLength2; -}; -Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) { - const limit = Math.pow(2, 8 * byteLength2 - 1); - checkInt(this, value, offset, byteLength2, limit - 1, -limit); - } - let i = byteLength2 - 1; - let mul = 1; - let sub = 0; - this[offset + i] = value & 255; - while (--i >= 0 && (mul *= 256)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = (value / mul >> 0) - sub & 255; - } - return offset + byteLength2; -}; -Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 1, 127, -128); - if (value < 0) - value = 255 + value + 1; - this[offset] = value & 255; - return offset + 1; -}; -Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 32767, -32768); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - return offset + 2; -}; -Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 2, 32767, -32768); - this[offset] = value >>> 8; - this[offset + 1] = value & 255; - return offset + 2; -}; -Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 2147483647, -2147483648); - this[offset] = value & 255; - this[offset + 1] = value >>> 8; - this[offset + 2] = value >>> 16; - this[offset + 3] = value >>> 24; - return offset + 4; -}; -Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { - value = +value; - offset = offset >>> 0; - if (!noAssert) - checkInt(this, value, offset, 4, 2147483647, -2147483648); - if (value < 0) - value = 4294967295 + value + 1; - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 255; - return offset + 4; -}; -Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) { - return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); -}); -Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) { - return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); -}); -Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert); -}; -Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert); -}; -Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert); -}; -Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert); -}; -Buffer.prototype.copy = function copy(target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) - throw new TypeError("argument should be a Buffer"); - if (!start) - start = 0; - if (!end && end !== 0) - end = this.length; - if (targetStart >= target.length) - targetStart = target.length; - if (!targetStart) - targetStart = 0; - if (end > 0 && end < start) - end = start; - if (end === start) - return 0; - if (target.length === 0 || this.length === 0) - return 0; - if (targetStart < 0) { - throw new RangeError("targetStart out of bounds"); - } - if (start < 0 || start >= this.length) - throw new RangeError("Index out of range"); - if (end < 0) - throw new RangeError("sourceEnd out of bounds"); - if (end > this.length) - end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - const len = end - start; - if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { - this.copyWithin(targetStart, start, end); - } else { - Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart); - } - return len; -}; -Buffer.prototype.fill = function fill(val, start, end, encoding) { - if (typeof val === "string") { - if (typeof start === "string") { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === "string") { - encoding = end; - end = this.length; - } - if (encoding !== undefined && typeof encoding !== "string") { - throw new TypeError("encoding must be a string"); - } - if (typeof encoding === "string" && !Buffer.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - if (val.length === 1) { - const code = val.charCodeAt(0); - if (encoding === "utf8" && code < 128 || encoding === "latin1") { - val = code; - } - } - } else if (typeof val === "number") { - val = val & 255; - } else if (typeof val === "boolean") { - val = Number(val); - } - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError("Out of range index"); - } - if (end <= start) { - return this; - } - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; - if (!val) - val = 0; - let i; - if (typeof val === "number") { - for (i = start;i < end; ++i) { - this[i] = val; - } - } else { - const bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding); - const len = bytes.length; - if (len === 0) { - throw new TypeError('The value "' + val + '" is invalid for argument "value"'); - } - for (i = 0;i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - return this; -}; -var errors = {}; -E("ERR_BUFFER_OUT_OF_BOUNDS", function(name) { - if (name) { - return `${name} is outside of buffer bounds`; - } - return "Attempt to access memory outside buffer bounds"; -}, RangeError); -E("ERR_INVALID_ARG_TYPE", function(name, actual) { - return `The "${name}" argument must be of type number. Received type ${typeof actual}`; -}, TypeError); -E("ERR_OUT_OF_RANGE", function(str, range, input) { - let msg = `The value of "${str}" is out of range.`; - let received = input; - if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === "bigint") { - received = String(input); - if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { - received = addNumericalSeparator(received); - } - received += "n"; - } - msg += ` It must be ${range}. Received ${received}`; - return msg; -}, RangeError); -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; -var hexSliceLookupTable = function() { - const alphabet = "0123456789abcdef"; - const table = new Array(256); - for (let i = 0;i < 16; ++i) { - const i16 = i * 16; - for (let j = 0;j < 16; ++j) { - table[i16 + j] = alphabet[i] + alphabet[j]; - } - } - return table; -}(); - -// node_modules/crc/mjs/create_buffer.js -var createBuffer2 = (value, encoding) => $Buffer.from(value, encoding); -var create_buffer_default = createBuffer2; - -// node_modules/crc/mjs/define_crc.js -function defineCrc(model, calculator) { - const result = (value, previous) => calculator(create_buffer_default(value), previous) >>> 0; - result.signed = (value, previous) => calculator(create_buffer_default(value), previous); - result.unsigned = result; - result.model = model; - return result; -} - -// node_modules/crc/mjs/calculators/crc16.js -var TABLE = [ - 0, - 49345, - 49537, - 320, - 49921, - 960, - 640, - 49729, - 50689, - 1728, - 1920, - 51009, - 1280, - 50625, - 50305, - 1088, - 52225, - 3264, - 3456, - 52545, - 3840, - 53185, - 52865, - 3648, - 2560, - 51905, - 52097, - 2880, - 51457, - 2496, - 2176, - 51265, - 55297, - 6336, - 6528, - 55617, - 6912, - 56257, - 55937, - 6720, - 7680, - 57025, - 57217, - 8000, - 56577, - 7616, - 7296, - 56385, - 5120, - 54465, - 54657, - 5440, - 55041, - 6080, - 5760, - 54849, - 53761, - 4800, - 4992, - 54081, - 4352, - 53697, - 53377, - 4160, - 61441, - 12480, - 12672, - 61761, - 13056, - 62401, - 62081, - 12864, - 13824, - 63169, - 63361, - 14144, - 62721, - 13760, - 13440, - 62529, - 15360, - 64705, - 64897, - 15680, - 65281, - 16320, - 16000, - 65089, - 64001, - 15040, - 15232, - 64321, - 14592, - 63937, - 63617, - 14400, - 10240, - 59585, - 59777, - 10560, - 60161, - 11200, - 10880, - 59969, - 60929, - 11968, - 12160, - 61249, - 11520, - 60865, - 60545, - 11328, - 58369, - 9408, - 9600, - 58689, - 9984, - 59329, - 59009, - 9792, - 8704, - 58049, - 58241, - 9024, - 57601, - 8640, - 8320, - 57409, - 40961, - 24768, - 24960, - 41281, - 25344, - 41921, - 41601, - 25152, - 26112, - 42689, - 42881, - 26432, - 42241, - 26048, - 25728, - 42049, - 27648, - 44225, - 44417, - 27968, - 44801, - 28608, - 28288, - 44609, - 43521, - 27328, - 27520, - 43841, - 26880, - 43457, - 43137, - 26688, - 30720, - 47297, - 47489, - 31040, - 47873, - 31680, - 31360, - 47681, - 48641, - 32448, - 32640, - 48961, - 32000, - 48577, - 48257, - 31808, - 46081, - 29888, - 30080, - 46401, - 30464, - 47041, - 46721, - 30272, - 29184, - 45761, - 45953, - 29504, - 45313, - 29120, - 28800, - 45121, - 20480, - 37057, - 37249, - 20800, - 37633, - 21440, - 21120, - 37441, - 38401, - 22208, - 22400, - 38721, - 21760, - 38337, - 38017, - 21568, - 39937, - 23744, - 23936, - 40257, - 24320, - 40897, - 40577, - 24128, - 23040, - 39617, - 39809, - 23360, - 39169, - 22976, - 22656, - 38977, - 34817, - 18624, - 18816, - 35137, - 19200, - 35777, - 35457, - 19008, - 19968, - 36545, - 36737, - 20288, - 36097, - 19904, - 19584, - 35905, - 17408, - 33985, - 34177, - 17728, - 34561, - 18368, - 18048, - 34369, - 33281, - 17088, - 17280, - 33601, - 16640, - 33217, - 32897, - 16448 -]; -if (typeof Int32Array !== "undefined") { - TABLE = new Int32Array(TABLE); -} -var crc16 = (current, previous = 0) => { - let crc = ~~previous; - for (let index = 0;index < current.length; index++) { - crc = (TABLE[(crc ^ current[index]) & 255] ^ crc >> 8) & 65535; - } - return crc; -}; -var crc16_default = crc16; - -// node_modules/crc/mjs/crc16.js -var crc16_default2 = defineCrc("crc-16", crc16_default); -export { - crc16_default2 as crc16 -}; diff --git a/src/external/mii-frontend/data-conversion.js b/src/external/mii-frontend/data-conversion.js deleted file mode 100644 index 28f18d5..0000000 --- a/src/external/mii-frontend/data-conversion.js +++ /dev/null @@ -1,1477 +0,0 @@ -// NOTE: 3DS/Wii U compatible data is referred to officially in the Switch nn::mii library as "Ver3": "nn::mii::Ver3StoreData", functions and tables using "ToVer3" and "FromVer3", mii_Ver3Common.cpp, mii_Ver3StoreDataTable.cpp, etc. -// Switch data is not commonly referred to as Ver4, however, in Pikmin Bloom's global-metadata.dat, there are many strings referring to Ver3, many being symbols directly from nn::mii, even a string that looks like a const or macro in the file: "NN_MII_CHAR_INFO_SIZE". And finally, there is a string in there reading "FromVer4CoreData". -// Now, even though Pikmin Bloom is in Unity and not developed by Nintendo, there's still one other reference to the name. The Coral API endpoint "me.json" has a child in a "mii" object called "storeData", containing another child named simply "3" with 96-byte long Base64 data. However, there is another element called "coreData" containing a child named "4" with 48-byte long Base64 data. SO, there you go: Ver3StoreData, and Ver4CoreData. -// that's why for simplicity, 3DS/Wii U format will be reffered to as "Ver3" and Switch/Studio as "Ver4". idk what wii is but it will be 1 - -// NOTE: "to" functions need to be defined in conersionMethods -export const supportedFormats = [ - { - className: "Gen1Wii", - technicalName: "RFLCharData/RFLStoreData (Wii)", - sizes: [74, 76], - // TODO: needs dedicated encode function - toVer3Function: "convertWiiFieldsToVer3", - toVer4Function: "convertVer3FieldsToVer4", - }, - { - className: "Gen3Switch", - technicalName: "nn::mii::StoreData/nn::mii::CoreData (Switch)", - sizes: [68, 48], - version: 4, - // TODO: needs dedicated encode function - toVer3Function: "convertVer4FieldsToVer3", - // NOTE: coredata's eyebrow y field's true value += 3 - preConvertFromFunction: "correctFromVer4CoreDataFields", - }, - { - className: "Gen3Switchgame", - technicalName: "nn::mii::CharInfo (Switch)", - sizes: [88], - version: 4, - encodeFunction: "encodeSwitchCharInfo", - toVer3Function: "convertVer4FieldsToVer3", - }, - { - className: "Gen2Wiiu3dsMiitomo", - sizes: [96, 92, 72], - technicalName: "CFL/FFL/AFL/Ver3 (3DS/Wii U) StoreData", - version: 3, - encodeFunction: "encodeVer3StoreData", - toVer4Function: "convertVer3FieldsToVer4", - // NOTE: right now we are force enabling copy from - // structs that do not support it, specifically TO only ver3 - // perhaps if we are converting to other types that allow - // copying, which I know nn::mii::CharInfo may but who cares... - // ... then it should logically be applied there as WELL, bleh. - postConvertToFunction: "forceEnableCopyingIfUndefined", - }, - // for NfpStoreDataExtention: - { - className: "Gen2Wiiu3dsMiitomo", - sizes: [104, 106, 108], // 106/108 = for mii-creator ".miic" - technicalName: "Ver3StoreData + NfpStoreDataExtention (amiibo Data)", - version: 3, - parseExtensionFunction: "parseNfpStoreDataExtention", - toVer4Function: "useNfpStoreDataExtentionFieldsForVer4", - }, - // for Tomodachi Life 3DS data: - { - className: "Gen2Wiiu3dsMiitomo", - sizes: [96 + 240], // qr code data is 240 bytes long - technicalName: "CFLiMiiDataPacket + Tomodachi Life 3DS QR Data", - version: 3, - parseExtensionFunction: "parseTomodachiLifeQRCodeData", - toVer4Function: "applyHairDyeAsVer4HairColor", - }, - { - // mii studio site decoded URL format/LocalStorage format - className: "Gen3Studio", - // the js will deobfuscate length 47 itself - sizes: [46, 47], // 46 = decoded/raw format - technicalName: "Mii Studio Data", - version: 4, - encodeFunction: "encodeKaitaiStructToUint8Array", - toVer3Function: "convertVer4FieldsToVer3", - preConvertFromFunction: "gen3studioDefineFacialHairFromBeardFields", // define facialhair from beard - postConvertToFunction: "gen3studioDefineBeardFromFacialHairFields", // define beard from facialhair - }, -]; - -// ig you could also make this "no name" like FFL does -const DEFAULT_NAME_IF_NONE = "Mii"; // blanco api sets mii studio miis' names to this - -// conversion methods for supportedFormats are defined here instead of window now -let conversionMethods = {}; - -// NOTE: while there are tables to map ver3 colors to the CommonColor type... -// shortcuts are being used here to effectively -// simulate the exact behavior of those tables - -// facelineColor: maps to the same table -const ver3ToVer4HairColor = (c) => (c === 0 ? 8 : c); // 0->8 -const ver3ToVer4EyeColor = (c) => c + 8; // offset 8 -const ver3ToVer4GlassColor = (c) => { - // Ver3GlassColorTable - // ig there is a chance this will be out of bounds - return [8, 14, 15, 16, 17, 18, 0][c]; - // ^^^^ 0->8, 1->14, 5->18, 6->0 -}; -const ver3ToVer4MouthColor = (c) => c + 19; // offset 19 - -// convert fields from ver3 and below to be compatible with switch/studio -// the only fields that need to be made compatible, however, -// , are the colors to convert them to the CommonColor type -conversionMethods.convertVer3FieldsToVer4 = (data) => { - // cannot just set these directly, have to set the properties - // kaitai structs use defineProperty to make these fetch from bitshifts - - Object.defineProperty(data, "facialHairColor", { - value: ver3ToVer4HairColor(data.facialHairColor), - configurable: true, - }); - Object.defineProperty(data, "eyeColor", { - value: ver3ToVer4EyeColor(data.eyeColor), - }); - Object.defineProperty(data, "eyebrowColor", { - // hair color (same as above) - value: ver3ToVer4HairColor(data.eyebrowColor), - configurable: true, - }); - Object.defineProperty(data, "glassesColor", { - value: ver3ToVer4GlassColor(data.glassesColor), - }); - Object.defineProperty(data, "hairColor", { - // hair color (same as above) - value: ver3ToVer4HairColor(data.hairColor), - configurable: true, - }); - Object.defineProperty(data, "mouthColor", { - value: ver3ToVer4MouthColor(data.mouthColor), - }); - // NOTE: you cannot do the same vice-versa to convert ver4 colors back - // ver4 also has new glass types, and... - // ... faceline/skin color is not mapped (ver3 ones work on ver4) -}; - -// NOTE: tables are from MiiPort: -// https://github.com/Genwald/MiiPort/blob/4ee38bbb8aa68a2365e9c48d59d7709f760f9b5d/include/convert_mii.h#L18 -// these SHOULD be extracted from nn::mii, however, AFAIK these are located... -// ... in the CommonColorTable as four uint8s after the two Color3s -const ToVer3GlassTypeTable = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 1, 3, 7, 7, 6, 7, 8, 7, 7, -]; -const ToVer3HairColorTable = [ - 0, 1, 2, 3, 4, 5, 6, 7, 0, 4, 3, 5, 4, 4, 6, 2, 0, 6, 4, 3, 2, 2, 7, 3, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, - 4, 4, 4, 4, 0, 0, 0, 4, 4, 4, 4, 4, 4, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 5, 7, 5, - 7, 7, 7, 7, 7, 6, 7, 7, 7, 7, 7, 3, 7, 7, 7, 7, 7, 0, 4, 4, 4, 4, -]; -const ToVer3EyeColorTable = [ - 0, 2, 2, 2, 1, 3, 2, 3, 0, 1, 2, 3, 4, 5, 2, 2, 4, 2, 1, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 4, 4, 4, 4, 4, 4, 4, 1, 0, 4, 4, 4, - 4, 4, 4, 4, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 3, 3, - 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, -]; -const ToVer3MouthColorTable = [ - 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 1, 4, 4, 4, 0, 1, 2, 3, 4, 4, 2, - 3, 3, 4, 4, 4, 4, 1, 4, 4, 2, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 4, 4, 4, 3, - 3, 3, 3, 3, 4, 4, 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, 3, - 3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 4, 0, 3, 3, 3, 3, 4, 3, 3, 3, 3, -]; -const ToVer3GlassColorTable = [ - 0, 1, 1, 1, 5, 1, 1, 4, 0, 5, 1, 1, 3, 5, 1, 2, 3, 4, 5, 4, 2, 2, 4, 4, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 0, 0, 0, 5, 5, 5, 5, 5, 5, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, -]; -const ToVer3FacelineColorTable = [0, 1, 2, 3, 4, 5, 0, 1, 5, 5]; - -// converting fields from ver4 to ver3, like vice versa, -// involves reassigning colors, from CommonColor to the respective ver3 types -// one of the differences is that this is also reassigning glass type as ver4 has more -conversionMethods.convertVer4FieldsToVer3 = (data) => { - // using the conversion tables defined above: - data.faceColor = ToVer3FacelineColorTable[data.faceColor]; - data.hairColor = ToVer3HairColorTable[data.hairColor]; - data.eyeColor = ToVer3EyeColorTable[data.eyeColor]; - data.eyebrowColor = ToVer3HairColorTable[data.eyebrowColor]; - data.mouthColor = ToVer3MouthColorTable[data.mouthColor]; - // NOTE: even though the rest of the beard fields are named differently - // in Gen3Studio, this one for beard color is the same there and in all - data.facialHairColor = ToVer3HairColorTable[data.facialHairColor]; - data.glassesColor = ToVer3GlassColorTable[data.glassesColor]; - data.glassesType = ToVer3GlassTypeTable[data.glassesType]; -}; - -// parses either NfpStoreDataExtention or -// mii-creator custom extension/".miic" format -conversionMethods.parseNfpStoreDataExtention = (data, struct) => { - // begin reading after Ver3StoreData offset - let offset = 96; // sizeof(FFLStoreData) - - let useOriginalVer3Value = -1; // stub, no u8 fields equal this - if (data.length > 104) - // 104 = sizeof(nn::mii::Ver3StoreData) - // + sizeof(nn::mii::NfpStoreDataExtention) - // mii-creator extension is larger than 8 bytes - useOriginalVer3Value = 0; // uses 0 to indicate use original val - - // all fields below are u8 so all just one byte - struct.extFacelineColor = data[offset++]; - struct.extHairColor = data[offset++]; - struct.extEyeColor = data[offset++]; - struct.extEyebrowColor = data[offset++]; - struct.extMouthColor = data[offset++]; - struct.extBeardColor = data[offset++]; - struct.extGlassColor = data[offset++]; - struct.extGlassType = data[offset++]; - - // handle fields that use original values: - // (mostly for mii-creator format) - if (struct.extFacelineColor === useOriginalVer3Value) - struct.extFacelineColor = struct.faceColor; // identity - if (struct.extHairColor === useOriginalVer3Value) - struct.extHairColor = ver3ToVer4HairColor(struct.hairColor); - if (struct.extEyeColor === useOriginalVer3Value) - struct.extEyeColor = ver3ToVer4EyeColor(struct.eyeColor); - if (struct.extEyebrowColor === useOriginalVer3Value) - struct.extEyebrowColor = ver3ToVer4HairColor(struct.eyebrowColor); - if (struct.extMouthColor === useOriginalVer3Value) - struct.extMouthColor = ver3ToVer4MouthColor(struct.mouthColor); - if (struct.extBeardColor === useOriginalVer3Value) - struct.extBeardColor = ver3ToVer4HairColor(struct.facialHairColor); - if (struct.extGlassColor === useOriginalVer3Value) - struct.extGlassColor = ver3ToVer4GlassColor(struct.glassesColor); - if (struct.extGlassType === useOriginalVer3Value) - struct.extGlassType = struct.glassesType; // identity -}; - -// apply extra "extension" fields at the end of this struct -// back to the actual fields since the extension fields are ver4 -conversionMethods.useNfpStoreDataExtentionFieldsForVer4 = (data) => { - Object.defineProperty(data, "faceColor", { - value: data.extFacelineColor, - }); - Object.defineProperty(data, "hairColor", { - value: data.extHairColor, - }); - Object.defineProperty(data, "eyeColor", { - value: data.extEyeColor, - }); - Object.defineProperty(data, "eyebrowColor", { - value: data.extEyebrowColor, - }); - Object.defineProperty(data, "mouthColor", { - value: data.extMouthColor, - }); - Object.defineProperty(data, "facialHairColor", { - value: data.extBeardColor, - }); - Object.defineProperty(data, "glassesColor", { - value: data.extGlassColor, - }); - Object.defineProperty(data, "glassesType", { - value: data.extGlassType, - }); -}; - -// parse tomodachi life qr code data from kaitai -// treat as extension appended after data -const parseTomodachiLifeQRCodeData = (data, struct) => { - const className = "TomodachiLifeQrCode"; - const structClass = window[className]; - - const qrCodeData = data.slice(96); // begins after cfsd - const stream = new KaitaiStream(qrCodeData); - const src = new structClass(stream); - - // copy fields on the destination that the source also has - let allDestKeys = [ - ...Object.keys(src), - // get keys as WELL as properties on the prototype - ...Object.getOwnPropertyNames(Object.getPrototypeOf(src)), - ]; - for (const key of allDestKeys) { - // do not copy private fields that start with an underscore - if (key.startsWith("_")) continue; - // null terminate every string... - if (typeof src[key] === "string") - src[key] = removeEverythingAfterNullTerminator(src[key]); - Object.defineProperty(struct, key, { - value: src[key], - }); - } -}; - -conversionMethods.parseTomodachiLifeQRCodeData = parseTomodachiLifeQRCodeData; - -conversionMethods.applyHairDyeAsVer4HairColor = (data) => { - // all fields will be interpreted as common colors - conversionMethods.convertVer3FieldsToVer4(data); - - // usually the value is at offset 0x43 - // first bit = hair dye enable - // hair dye value = bits range 2-7 (5 bits, 32 max) - - //if(typeof data.hairDye !== 'number') - if (!data.hairDyeEnable) - // if it's false or undefined - // Return unmodified: - return; - - /* Hair dye table extracted by kat21 from RenderDoc (vec3): - 0.61569, 0.87451, 1.00 - 0.40784, 0.80, 1.00 - 0.23922, 0.52549, 1.00 - 0.00, 0.00, 1.00 - 0.15294, 0.15294, 0.37255 - 0.29412, 0.29412, 0.54902 - 0.00, 0.43922, 0.43922 - 0.18039, 0.66275, 0.66275 - 0.00, 1.00, 1.00 - 0.5451, 0.91765, 0.61961 - 0.27843, 0.94118, 0.14902 - 0.00, 0.58431, 0.00 - 0.00, 0.29804, 0.00 - 1.00, 1.00, 0.44314 - 1.00, 1.00, 0.00 - 1.00, 0.80, 0.60 - 1.00, 0.61176, 0.2549 - 0.86667, 0.39216, 0.00 - 1.00, 0.11765, 0.11765 - 1.00, 0.00, 0.00 - 0.56863, 0.00, 0.00 - 1.00, 0.00, 0.66667 - 1.00, 0.38431, 0.59216 - 1.00, 0.67843, 0.63529 - 0.23529, 0.00, 0.23529 - 0.51373, 0.03137, 0.76078 - 0.76471, 0.50588, 0.97255 - 0.48235, 0.36471, 0.42745 - 0.29412, 0.29412, 0.29412 - 0.73333, 0.74902, 0.63137 - 0.70588, 0.70588, 0.70588 - 1.00, 1.00, 1.00 -*/ - // Lookup table courtesy of kat21. - const HairDyeToCommonColorTable = [ - // Corresponds to the in-game color selection layout: - 55, 51, 50, 12, 16, 12, 67, 61, 51, 64, 69, 66, 65, 86, 85, 93, 92, 19, 20, - 20, 15, 32, 35, 26, 38, 41, 43, 18, 95, 97, 97, 99, - ]; - // Map from data.hairDye. - const hairDyeCommonColor = HairDyeToCommonColorTable[data.hairDye]; - // (According to https://web.archive.org/web/20250106204124/https://tomodachi.fandom.com/wiki/Hair_Dye): - // Applied to hairColor, eyebrowColor, facialHairColor. - Object.defineProperty(data, "hairColor", { - value: hairDyeCommonColor, - }); - Object.defineProperty(data, "eyebrowColor", { - value: hairDyeCommonColor, - }); - Object.defineProperty(data, "facialHairColor", { - value: hairDyeCommonColor, - }); -}; - -// add 3 to eyebrow vertical -conversionMethods.correctFromVer4CoreDataFields = (_, input) => { - input.eyebrowVertical += 3; - /* -Object.defineProperty(output, 'eyebrowVertical', { - value: (input.eyebrowVertical + 3) -}); -*/ - // when using this, it says attempt to change the value of a readonly property -}; - -// the method below is used to encode studio and switch charinfo -// by more or less directly mapping the u8 fields in the struct to a new array -// NOTE: only supports strings (TO UTF-16LE ONLY!!!), lists, and ofc uint8 -conversionMethods.encodeKaitaiStructToUint8Array = (struct) => { - // append all keys into this array - // which will then become a uint8array - let structArray = []; - // NOTE: NOTE: kaitai private fields are NOT: - // ... numbers, arrays, or strings. we can get away with switch() - /*for(const key in struct) { - // remove all private fields so that the object - // represents only the struct fields in order - if(key.startsWith('_')) { - delete struct[key]; - continue; - } - //else if(typeof key) - else - // by default, add it directly (assuming int?) - structArray.push(struct[key]); -}*/ - - for (const key in struct) { - // add to array based on the type - // value will be changed for string case - let value = struct[key]; - switch (typeof value) { - case "number": - // assuming this is a uint8, pushing it - structArray.push(value); - break; - case "boolean": - // there are never booleans in these fields natively - // but there are when they are set from another struct - structArray.push(Number(value)); - break; - case "string": - // NOTE: assuming NAME is ALWAYS 10 CHARACTER UTF-16 STRING - // IMPORTANT!!!!: in Switch CharInfo, the name is (10+1) characters, where the last character is for padding - // I THINK!!!! that Switch CharInfo is the only (for storage/transmission) format with padding - // BECAUSE of this, for compatibility with other types... - // ... this will be using and serializing a 10 character name - // this WORKS in "gen3_switchgame.ksy" but NOT!!!! "miidata_swi.ksy" by HEYimHeroic - const stringBytes = new Uint8Array(new ArrayBuffer(20)); - const stringBytesView = new DataView(stringBytes.buffer); - for (let i = 0; i < 10; i++) { - // assuming name is always 10 characters even if it has padding - const u16Offset = i * 2; - stringBytesView.setUint16(u16Offset, value.charCodeAt(i), true); // little-endian UTF-16 - } - // encode string to utf-16le byte array - value = [...stringBytes]; - // FALL THROUGH and add this as an array - case "object": - // actually, only arrays - if (!(value instanceof Array)) { - if (!key.startsWith("_")) - console.warn("unknown field type on key object: " + key); - continue; - } - // this is an array, so push each element - for (v of value) structArray.push(v); - break; - default: - if (!key.startsWith("_")) - console.warn("unknown field type on key: " + key); - // all other types are ignored - } - } - // array of ints representing studio data - //const structArray = Object.values(struct); - // return as a uint8array for consistency - return new Uint8Array(structArray); - // NOTE: could be a uint8array, however... - // ... apparently, in order to encode to hex it has to be an array anyway -}; -// encodeSwitchCharInfo is mostly just a thunk using the -// above function to encode to uint8array, but generating -// a random create ID (in this kaitai called "unknownData") first -conversionMethods.encodeSwitchCharInfo = (struct) => { - // if create id is not null, then fill it with randomness - if (!struct.unknownData || isArrayNull(struct.unknownData)) { - for (let i = 0; i < 16; i++) { - struct.unknownData[i] = Math.floor(Math.random() * 256); - } - // from miiport: These two leftmost bits must be 0b10 for the ID to be valid. - struct.unknownData[8] &= 0b10111111; // Clear the 7th bit - struct.unknownData[8] |= 0b10000000; // Set the 8th bit - } - // fill in mii name if it is null - if (!struct.miiName || isStringNull(struct.miiName)) - struct.miiName = DEFAULT_NAME_IF_NONE; - // for whatever reason they do not want any characters - // to be in the name after the null terminator - struct.miiName = removeEverythingAfterNullTerminator(struct.miiName); - // then thunk to encode kaitai function - return conversionMethods.encodeKaitaiStructToUint8Array(struct); -}; - -// the methods below remap inconsistently named fields in gen3_studio.ksy from the original mii2studio -// as the fields usually prefixed "facialHair" in the other structs are instead prefixed "beard" here - -// this will map the fields FROM the studio struct TO another one -conversionMethods.gen3studioDefineFacialHairFromBeardFields = ( - output, - inputOptional -) => { - // if we are only acting on one struct then we will use output for both - let input = inputOptional; - if (input === undefined) input = output; - - // if the studio fields are properly named according to the others then skip - if ( - input.facialHairBeard !== undefined || - // ... or, if this is somehow already the same studio struct?! - output.beardGoatee !== undefined - ) - return; - - Object.defineProperty(output, "facialHairBeard", { - value: input.beardGoatee, - }); - Object.defineProperty(output, "facialHairSize", { - value: input.beardSize, - }); - Object.defineProperty(output, "facialHairMustache", { - value: input.beardMustache, - }); - Object.defineProperty(output, "facialHairVertical", { - value: input.beardVertical, - }); -}; -// this maps the fields TO the studio struct FROM any other one -conversionMethods.gen3studioDefineBeardFromFacialHairFields = ( - output, - input -) => { - // if the studio fields are properly named according to the others then skip - if ( - output.facialHairBeard !== undefined || - // ... or, if this is somehow already the same studio struct?! - input.beardGoatee !== undefined - ) - return; - - // erroneously prefixed "beard" in studio when other structs use "facialHair" - output.beardGoatee = input.facialHairBeard; - output.beardSize = input.facialHairSize; - output.beardMustache = input.facialHairMustache; - output.beardVertical = input.facialHairVertical; -}; - -conversionMethods.forceEnableCopyingIfUndefined = (output, input) => { - if (input.copying === undefined) - Object.defineProperty(output, "copying", { - value: true, - }); -}; - -// current name of studio kaitai struct class being used -const studioFormat = supportedFormats.find((f) => f.className === "Gen3Studio"); -const ver3Format = supportedFormats.find( - (f) => f.className === "Gen2Wiiu3dsMiitomo" -); - -const handleConvertDetailsToggle = (event) => { - if ( - !event.target.open || // not toggled open? ignore - // or already revealed, we do not need to do anything - event.target.getAttribute("data-revealed") - ) - return; - - // NOTE: routine to find data in image, replaced by fetching from data attribute - /* -// we need to find the data -// .. for now, take this from the parent's image url -const hopefullyImage = event.target.parentElement.getElementsByTagName('img')[0]; -const imageSrc = hopefullyImage.getAttribute('src'); -if(!imageSrc) - // image src should not be undefined - throw new Error('why is the image\'s src undefined...???'); - -// get data param, if it even exists -const imageURLParams = new URLSearchParams(new URL(imageSrc).search); -const dataValue = imageURLParams.get('data'); -if(!dataValue) - throw new Error('image\'s source doesn\'t have data query parameter'); -*/ - const dataValue = event.target.getAttribute("data-data"); - if (!dataValue) - throw new Error( - "data-data attribute on
is undefined, it is supposed to contain the data for this result" - ); - const name = event.target.getAttribute("data-name"); - // will be undefined if data-name is not there - - // the name of the input type will be put in this element - const inputTypeElement = event.target.getElementsByClassName("input-type")[0]; - - const inputData = parseHexOrB64TextStringToUint8Array(dataValue); - - //const studioURLDataElement = event.target.getElementsByClassName('studio-url-data')[0]; - const studioImageElement = event.target.getElementsByClassName("image-80")[0]; - const studioCodeElement = - event.target.getElementsByClassName("studio-code")[0]; - - // run the function to convert the data from the image to raw studio data - const studioData = convertDataToType(inputData, studioFormat); - // "studio code" = raw studio data in hex - // NOTE: three dots are only required if it is a uint8array which - // it is only one if the input data is studio data directly - const studioCode = [...studioData].map(byteToHex).join(""); - studioCodeElement.textContent = studioCode; - - // TODO 2024-11-04: while the mii instructions site accepts studio - // data as well as charinfo which would be more convenient... for - // the time being charinfo will be used - /* -const switchCharInfoData = convertDataToType(inputData, supportedFormats.find(f => f.className === 'Gen3Switchgame')); -const switchCharInfoHex = [...switchCharInfoData].map(byteToHex).join(''); -*/ - const miiInstructionsLinkElement = event.target.getElementsByClassName( - "mii-instructions-link" - )[0]; - miiInstructionsLinkElement.href += studioCode; //switchCharInfoHex; - - const studioURLData = encodeStudioToObfuscatedHex(studioData); - const studioURLRender = - studioImageElement.getAttribute("data-src") + studioURLData; - //studioURLDataElement.textContent = studioURLData; - studioImageElement.setAttribute("src", studioURLRender); - - // do this at the end bc it is most likely to fail - const ver3StoreDataElement = - event.target.getElementsByClassName("ver3storedata")[0]; - const inputFormat = findInputFormatFromSize(inputData.length); - - if ( - inputFormat !== undefined && - typeof inputFormat.technicalName === "string" - ) - inputTypeElement.textContent = inputFormat.technicalName; - - const ver3StoreData = convertDataToType( - inputData, - ver3Format, - inputFormat.className - ); - const ver3StoreDataB64 = uint8ArrayToBase64(ver3StoreData); - ver3StoreDataElement.textContent = ver3StoreDataB64; - // finally make a qr code - if (window.QRCode !== undefined) { - const ver3StoreDataForQR = convertDataToType( - inputData, - ver3Format, - inputFormat.className, - true - ); // set "forQRCode" true - const ver3QRCodeDataArray = - encryptAndEncodeVer3StoreDataToQRCodeFormat(ver3StoreDataForQR); - const qrCodeImage = event.target.getElementsByClassName("image-qr")[0]; - qrCodeImage.src = QRCode.generatePNG(ver3QRCodeDataArray, { - margin: null, - }); // for whatever reason they check whether this - // property in options is null - but it is undefined - } - - const modelDownloadButtons = event.target.getElementsByClassName( - "model-download-button" - ); - const imgSearchIfItExists = - event.target.parentElement.getElementsByTagName("img"); - if (modelDownloadButtons.length && imgSearchIfItExists.length) { - const linkButWithGlbInsteadOfPng = imgSearchIfItExists[0].src - // switch shader has transparent faceline - // texture which will look wrong here - // so just remove it in order to avoid - // ppl who use that and don't know that - .replace("&shaderType=switch", "") - .replace(".png?", ".glb?"); - modelDownloadButtons[0].setAttribute( - "action", // actually a form lmao - linkButWithGlbInsteadOfPng - ); - } - - // base name will be name if it is defined - let fileBaseName = name; - if (!fileBaseName) { - // otherwise compose a base name from the date and type - const now = new Date(); - const formattedTime = `${now.getFullYear()}-${String( - now.getMonth() + 1 - ).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}_${String( - now.getHours() - ).padStart(2, "0")}-${String(now.getMinutes()).padStart(2, "0")}-${String( - now.getSeconds() - ).padStart(2, "0")}`; - - fileBaseName = formattedTime + "-" + inputFormat.className; - } - - const switchCharInfoDownloadButton = event.target.getElementsByClassName( - "download-switch-charinfo" - )[0]; - convertDataAndBindToDLButton( - switchCharInfoDownloadButton, - inputData, - "Gen3Switchgame", - inputFormat.className - ); - switchCharInfoDownloadButton.setAttribute( - "data-filename", - fileBaseName + ".charinfo" - ); - - const studioDataDownloadButton = event.target.getElementsByClassName( - "download-studio-data" - )[0]; - convertDataAndBindToDLButton( - studioDataDownloadButton, - inputData, - "Gen3Studio", - inputFormat.className - ); - studioDataDownloadButton.setAttribute( - "data-filename", - fileBaseName + ".mnms" - ); - - const ffsdDownloadButton = - event.target.getElementsByClassName("download-ffsd")[0]; - ffsdDownloadButton.setAttribute("data-data", ver3StoreDataB64); - ffsdDownloadButton.setAttribute("data-filename", fileBaseName + ".ffsd"); - - // mark as revealed at the end, i.e. do NOT RUN THE HANDLER ANYMORE - event.target.setAttribute("data-revealed", "1"); -}; - -const convertDataAndBindToDLButton = ( - button, - inputData, - formatName, - inputFormatName -) => { - const format = supportedFormats.find((f) => f.className === formatName); - const data = convertDataToType(inputData, format, inputFormatName); - - const dataString = uint8ArrayToBase64(data); - button.setAttribute("data-data", dataString); -}; - -const handleDownloadDataFileButton = (event) => { - event.preventDefault(); - // define a filename with the name, TBD: if name is generic then prepend date maybe? - const filename = event.target.getAttribute("data-filename"); - if (!filename) - throw new Error("download button does not have data-filename attribute"); - const dataText = event.target.getAttribute("data-data"); - if (!dataText) - throw new Error( - "download button does not have data-data attribute, where base64 data is supposed to go" - ); - - const data = base64ToUint8Array(dataText); - - // create and download a new blob from the uint8array we made - const blob = new Blob([data]); //, {type: 'application/octet-stream'}); - - // create a fake anchor so we can set the filename - const link = document.createElement("a"); - // create a url from the blob, download from here - const url = URL.createObjectURL(blob); - link.href = url; - link.download = filename; - // begin the download - link.click(); - // revoke the object url after the download is complete ideally - URL.revokeObjectURL(url); -}; - -// encodes a compatible struct to Ver3StoreData -/* NOTE: forQRCode DOES THESE (potentially undesirable) THINGS: -* FORCE ENABLES COPYING -* sets MiiVersion to 0x03, and birth platform to 3DS - - both needed to scan as a qr code -* skips crc16 but actually only bc qr encode routine does it itself -*/ -conversionMethods.encodeVer3StoreData = (dataStruct, forQRCode) => { - // set unmarked fields - dataStruct.unknown1 = 3; // ALWAYS constant 100% of the time - // 3ds version mii, will scan as a qr code on 3ds and wii u - // may already be set so using defineProperty on it - if ( - forQRCode || - // there is no birth platform corresponding to 0 (1 is wii) - dataStruct.version === undefined || - dataStruct.version < 1 - ) - Object.defineProperty(dataStruct, "version", { - value: 3, // FFL_BIRTH_PLATFORM_CTR - }); - // mii needs a non-null name to scan - - // this name is what the Coral account API returns in its - // Mii data, along with random IDs, I assume they forge it from studio data - if (!dataStruct.miiName || isStringNull(dataStruct.miiName)) - dataStruct.miiName = DEFAULT_NAME_IF_NONE; - - // random array of u8s: - const randomUint8Array = (size) => - Array.from({ length: size }, () => Math.floor(Math.random() * 256)); - - // NOTE: "systemId" = AuthorID, "clientId" = CreateID base - // "avatarId" = CreateID first 4 bytes - - // systemId/AuthorID and clientId/CreateID base are not - // needed, both can be randomy (CreateID base is ONLY - // set to the MAC address on Wii, (DS?), 3DS but NOT - // on Wii U (nn::act::GetDeviceHash), Switch (??? random?) - - //dataStruct.systemId = [0, 0, 0, 0, 0, 0, 0, 0]; - // CreateID cannot be null. - // scanning two Miis with the same CreateID leads - // the system to thinking they are the same and overwrite - - //dataStruct.avatarId = [0b00001111, 0, 0, 0]; - // TODO: make ALL RANDOM AVATAR IDS - // TODO: ALL NUMBERS and ALSO RANDOM SYSTEM ID. MAYBE RANDOM (NINTENDO) MAC??? - - // NOTE!!!!: qr codes with THIS BIT SET will NOT SCAN on 3ds - if (dataStruct.avatarId[0] & 0b00100000) - // FFLI_CREATE_ID_FLAG_TEMPORARY - dataStruct.avatarId[0] &= ~0b00100000; // unset this bit - - // TODO: TODO: TODO: IF YOU ARE READING, ACTUALLY MAKE THIS - // A HASH OF THE MII STUDIO DATA OR SOMETHING I THINK MAYBE - //debugger - if (!dataStruct.avatarId || isArrayNull(dataStruct.avatarId)) { - dataStruct.avatarId = [ - 0b10000000, // set normal bit - 0, - 0, - 0, - ]; - //dataStruct.clientId = [0, 0, 0, 0, 0, 0]; - dataStruct.clientId = randomUint8Array(6); - // NOTE: THIS ^^ is the SECOND part of CreateID - } - - // force enable copying, but only if qr code mode is on - if (forQRCode) - Object.defineProperty(dataStruct, "copying", { - value: true, - }); - // mingle, or local only, is already initialized to false tho - - // skip crc16 for qr code bc qr encode function does it itself - let skipCRC16 = Boolean(forQRCode); - return encode3DSStoreDataFromStructCopiedFromKazukiMiiEncode( - dataStruct, - skipCRC16 - ); -}; - -// iterate through format list, assumed to be called supportedFormats -// to find that input format and throw an error if it is not supported -const findInputFormatFromSize = (size) => { - for (const format of supportedFormats) { - if (format.sizes.includes(size)) return format; - } - // nothing was found, throw error - throw new Error("Input format is an unknown size of: " + size); -}; - -// ensures that the format class exists and then creates the struct type -// if data is not specified, then it simply creates a blank structure of the size -const createNewInstanceOfKaitaiStructFormat = (format, data) => { - // className in the format is assumed to be a (kaitai struct) class in window - const structClass = window[format.className]; - // ensure that this actually exists - if (!structClass) - throw new Error( - "Cannot find format class name in window: " + format.className - ); - // find the _read prototype that kaitai constructors usually have - if (!structClass.prototype._read) - throw new Error( - "Class does not have prototype._read and may not be generated from a Kaitai struct: " + - format.className - ); - - // determine if this format is an extension - const hasExtensionFunction = - format.parseExtensionFunction !== undefined && - typeof conversionMethods[format.parseExtensionFunction] === "function"; - - // assumed to be a KaitaiStream type passed to the constructor - let stream; - - // if data is undefined, create a new blank stream using the first supported size - if (data === undefined) { - // ensure that the format actually defines sizes - if (format.sizes.length < 1) - throw new Error( - `Trying to construct a blank instance of format ${format.className} but it does not have any defined sizes and no data was passed in.` - ); - // if this is an extension, do not use the first supported size - if (hasExtensionFunction) { - // use the data as is so that the size can be detected - stream = new KaitaiStream(data); - } else { - // assuming that the first size in the list is sufficient - const firstSupportedSize = format.sizes[0]; - stream = new KaitaiStream(new ArrayBuffer(firstSupportedSize)); - } - } else { - // ... otherwise, construct with data - // if the data is smaller than the first size, which is assumed to be the size of the struct, then construct with that first size - if (format.sizes.length > 0) { - // this is what the size of the struct is meant to be - const firstSupportedSize = format.sizes[0]; - if (data.length < firstSupportedSize) { - const u8Array = new Uint8Array(firstSupportedSize); - // copy the data to the larger buffer - u8Array.set(data, 0); - // create the stream with that buffer - stream = new KaitaiStream(u8Array); - } else { - stream = new KaitaiStream(data); - } - } else { - // NOTE: assumes "data" is ArrayBuffer or DataView: https://github.com/kaitai-io/kaitai_struct_javascript_runtime/blob/a911d627ffeb244ce0b7873858325020d6694ba5/KaitaiStream.js#L20 - stream = new KaitaiStream(data); - } - } - - const struct = new structClass(stream); - // the above function will throw an error if something goes wrong - // notably I have seen it will if the data is not long enough for it - - // apply parseExtensionFunction if the format is an extension - if (hasExtensionFunction) - // has valid parseExtensionFunction - conversionMethods[format.parseExtensionFunction](data, struct); - - return struct; -}; - -// for mapping objects like these kaitai structs -// where the property names match on both -const mapObjectFieldsOneToOne = (src, dest) => { - // copy fields on the destination that the source also has - let allDestKeys = [ - ...Object.keys(dest), - // get keys as WELL as properties on the prototype - // these are used by larsenv's structs for bitmapped fields - ...Object.getOwnPropertyNames(Object.getPrototypeOf(dest)), - ]; - // speaking of structs, these have NOT been tested with HEYimHeroic's structs - for (const key of allDestKeys) { - //in dest) { - // do not copy private fields that start with an underscore - // NOTE: not needed anymore bc if they are not on the dest they wont be copied - if ( - !key.startsWith("_") && - // if the key exists on the source... - src[key] !== undefined - ) { - // ... then copy it to the destination - //dest[key] = src[key]; - Object.defineProperty(dest, key, { - value: src[key], - }); - } - } - // NOTE!!!! NOTE!!!! this TURNS THE DESTINATION - // into an INSTANCE OF THE SOURCE ... -}; - -// converts and encodes to a certain type -// third arugment, inupt format name, is optional -// if not provided then the size is used to auto detect -// length of obfuscated studio data -const STUDIO_OBFUSCATED_LENGTH = 47; -export const convertDataToType = ( - data, - outputFormat, - inputFormatName, - optionalBoolToEncodeFunc -) => { - // ensure that data is an ArrayBuffer - /*if(!(data instanceof ArrayBuffer)) - throw new Error('data must be ArrayBuffer or compatible.'); -*/ - - // format comes from either findInputFormatFromSize - // or it comes directly from supportedFormats itself - let format; - // if inputFormatName is NOT a valid string, so it's undefined... - if (typeof inputFormatName !== "string") - // ... auto detect based on size - format = findInputFormatFromSize(data.length); - // that will throw an error so we don't need to handle it ourselves - // otherwise, inputFormatName is assumed to be className - else format = supportedFormats.find((f) => f.className === inputFormatName); - if (!format) - // find() will make it null or undefined - // unsupported/non-existent formatName was passed in - throw new Error("Unknown input format name: " + inputFormatName); - - // NOTE: SPECIAL CASE: DEOBFUSCATE STUDIO DATA - if (data && data.length === STUDIO_OBFUSCATED_LENGTH) - data = studioURLObfuscationDecode(data); - - // if this is the output format directly then no conversion is required - /*if(findInputFormatFromSize(data.length) === outputFormat) - return data; -*/ - // NOTE: above isn't viable anymore just because ver3storedata - // needs birth platform modified before qr will work - // and if it is smaller than the full storedata it needs checksum - - // create a new instance of the class, with this function handling errors - // may be overridden by the preprocessing function - let inputStruct = createNewInstanceOfKaitaiStructFormat(format, data); - - // assumes that outputFormat is an object and has className in it - if (!outputFormat || outputFormat.className === undefined) - throw new Error( - "outputFormat is not a valid format object or does not have className" - ); - - // version is needed to evaluate which of the few conversion functions need to be run - if (typeof outputFormat.version !== "number") - throw new Error( - `Output format ${outputFormat.className} does not have a version field or it is not a number.` - ); - // encode function is run at the end here so it is needed - if ( - outputFormat.encodeFunction === undefined || - typeof conversionMethods[outputFormat.encodeFunction] !== "function" - ) - throw new Error( - `Output format ${outputFormat.className} does not have a valid encodeFunction.` - ); - - /* - const ver3ConvertFunc = format.toVer3Function; - const ver4ConvertFunc = format.toVer4Function; -*/ - - /* - * usually: - * convert to ver3, and then ver4 - * - */ - - // determine whether to convert to ver3, or ver4, or both - let doConvertToVer3 = true, - doConvertToVer4 = true; - - // for equal versions, do not do conversion at all - if (format.version === outputFormat.version) { - doConvertToVer3 = false; - doConvertToVer4 = false; - } - // aim to convert up AND down...? - // if this is less than ver4 then do not convert to it - if (outputFormat.version < 4) doConvertToVer4 = false; - // if this is less than ver3 don't convert to that either - if (outputFormat.version < 3) doConvertToVer3 = false; - - if (doConvertToVer3 && format.toVer3Function !== undefined) - // TODO: DOES NOT CHECK WHETHER THE FUNCTION ITSELF IS UNDEFINED - conversionMethods[format.toVer3Function](inputStruct); - if (doConvertToVer4 && format.toVer4Function !== undefined) - // TODO: DOES NOT CHECK WHETHER THE FUNCTION ITSELF IS UNDEFINED - conversionMethods[format.toVer4Function](inputStruct); - - // create a new blank instance of the output format - let outputStruct = createNewInstanceOfKaitaiStructFormat(outputFormat); - - // call preConvertFromFunction for input if it exists - if (format.preConvertFromFunction !== undefined) - conversionMethods[format.preConvertFromFunction](outputStruct, inputStruct); - - // map all fields with the same names to each other - // TODO: should use kaitai struct dedicated encoding functions instead...!!! - mapObjectFieldsOneToOne(inputStruct, outputStruct); - // NOTE!!!! NOTE!!!! the OUTPUT FORMAT becomes the same as the INPUT FORMAT's CLASS!!!!! - - // call postConvertToFunction for output if it exists - if (outputFormat.postConvertToFunction !== undefined) - conversionMethods[outputFormat.postConvertToFunction]( - outputStruct, - inputStruct - ); - - // we should be finished - //return outputStruct; - // FINALLY, call the encoding function - const encodedOutput = conversionMethods[outputFormat.encodeFunction]( - outputStruct, - optionalBoolToEncodeFunc - ); - return encodedOutput; // should be a uint8array -}; - -// yes I'm aware that typing this function name is as long as the snippet itself -//const uint8ArrayToBase64 = data => btoa(String.fromCharCode.apply(null, data)); - -/* !! - * CODE BELOW IS FROM: - * https://mii-studio.akamaized.net/static/js/editor.pc.46056ea432a4ef3974af.js - * search ".prototype.encode" - * beauitifed by GPT-4 - */ - -// helper to map numbers to zero-padded hex -const byteToHex = (num) => num.toString(16).padStart(2, "0"); - -// encode from studio data, apply the studio url obfuscation and hex encode -const encodeStudioToObfuscatedHex = (data) => { - // we actually need to clone input as to not act directly on it - const uint8Array = Object.assign([], data); - // generate a random initial value between 0 and 255 - // NOTE: can make this 0 to disable randomization - let initialRandomValue = Math.floor(256 * Math.random()); - let previousEncodedValue = initialRandomValue; - - // iterate over the Uint8Array and encode each byte - for (let i = 0; i < uint8Array.length; i++) { - let currentValue = uint8Array[i]; - // XOR the current value with the previous one and add 7, then take modulo 256 - uint8Array[i] = (7 + (currentValue ^ previousEncodedValue)) % 256; - // update the previous value to the current encoded value - previousEncodedValue = uint8Array[i]; - } - - // prepend the initial random value to the array and convert to a hexadecimal string - return [initialRandomValue, ...uint8Array].map(byteToHex).join(""); -}; - -// !! == ALL BELOW TAKEN FROM "mii2studio in js ai slop attempt 1" FIDDLE == !! - -// Helper functions -/* -const stripSpaces = str => str.replace(/\s+/g, ''); -const hexToUint8Array = hex => new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); -const base64ToUint8Array = base64 => Uint8Array.from(atob(base64), c => c.charCodeAt(0)); -*/ -// used to check if a string is all zeroes, which are seen in kaitai structs -const isStringNull = (string) => - string.split("").every((char) => char === "\u0000"); -// take a null terminated string, and remove everything -// after the null terminator by replacing the rest with zeroes -// switch mii formats need this i think -const removeEverythingAfterNullTerminator = (string) => { - let nullIndex = string.indexOf("\0"); // find null terminator in string - if (nullIndex !== -1) { - // if it is found... - // .. we want to replace everything after it with nothing - // however this is simply overwriting everything else with zeroes - const beforeNull = string.slice(0, nullIndex + 1); - // create padding to put after the null - let padding = "\u0000".repeat(string.length - beforeNull.length); - return beforeNull + padding; - } - return string; // if no null terminator??? then return input -}; -// likewise used to check if an array is null -const isArrayNull = (array) => array.every((i) => i === 0); - -// TODO: TODO: CHECK IF YOU CAN PUT THE TWO TABLES INTO ONE -// TODO: ALSO CHECK IF YOU CAN MAKE THIS SHORTER -// converts Wii properties to ver3 compatible properties -conversionMethods.convertWiiFieldsToVer3 = (data) => { - // wii data does not support y scale so these are constant - data.eyeStretch = 3; - data.mouthStretch = 3; - data.eyebrowStretch = 3; - - // tables to map "FaceLineAndMake" field in RFLCharData... - // ... to FaceMake and FaceLine properties for 3DS-compatible data - const makeup = { - 1: 1, - 2: 6, - 3: 9, - 9: 10, - }; - - const wrinkles = { - 4: 5, - 5: 2, - 6: 3, - 7: 7, - 8: 8, - 10: 9, - 11: 11, - }; - // NOTE: tables taken directly from mii2studio.py - // ... but they can be taken from FFL too - - // TODO: CAN YOU REMOVE hasOwnProperty HERE??? - if (makeup.hasOwnProperty(data.facialFeature)) - data.faceMakeup = makeup[data.facialFeature]; - if (wrinkles.hasOwnProperty(data.facialFeature)) - data.faceWrinkles = wrinkles[data.facialFeature]; -}; - -// NOTE: customized for the kaitai by GPT-4o... -// ... and adapted from MiiInfoEditorCTR: https://github.com/kazuki-4ys/kazuki-4ys.github.io/blob/148dc339974f8b7515bfdc1395ec1fc9becb68ab/web_apps/MiiInfoEditorCTR/mii.js#L348 -// 2024-08-10: tested to be accurate with: blanco, bro-mole-high, jasmine -const encode3DSStoreDataFromStructCopiedFromKazukiMiiEncode = ( - data, - skipCRC16 -) => { - // Create buffer to store the encoded data - let buf = new Uint8Array(0x48 + 20 + 2 + 2); // 0x48 bytes + 20 bytes for creatorName + 2 bytes padding + 2 bytes checksum - - // unknown1 byte - buf[0x00] = data.unknown1 || 0; - - // characterSet, regionLock, profanityFlag, and copying all packed into one byte - buf[0x01] = - ((data.characterSet || 0) << 4) | // character set (2 bits), typically 0=JPN+USA+EUR, 1=CHN, 2=KOR, 3=TWN - (((data.regionLock || 0) & 0x03) << 2) | // region lock (2 bits), 0=no lock, 1=JPN, 2=USA, 3=EUR - ((data.profanityFlag ? 1 : 0) << 1) | // profanity flag (1 bit), 1 = contains profanity - (data.copying ? 1 : 0); // copying allowed (1 bit), 1 = copying allowed - - // mii position page index and slot index - buf[0x02] = - (data.miiPositionPageIndex & 0x0f) | // page index (4 bits) - ((data.miiPositionSlotIndex & 0x0f) << 4); // slot index (4 bits) - - // version and unknown3 packed together - buf[0x03] = - (data.version << 4) | // version (4 bits) - (data.unknown3 & 0x0f); // unknown, typically 0 (4 bits) - - // systemId: unique ID associated with the console, 8 bytes - if (data.systemId !== undefined) { - for (let i = 0; i < 8; i++) { - buf[0x04 + i] = data.systemId[i] || 0; - } - } - - // avatarId: unique Mii ID, 4 bytes (REQUIRED) - for (let i = 0; i < 4; i++) { - buf[0x0c + i] = data.avatarId[i] || 0; - } - - // clientId: MAC address of the creator's console, 6 bytes - if (data.clientId !== undefined) { - for (let i = 0; i < 6; i++) { - buf[0x10 + i] = data.clientId[i] || 0; - } - } - - // padding, 2 bytes (usually 0) - buf[0x16] = data.padding & 0xff; - buf[0x17] = (data.padding >> 8) & 0xff; - - // data1: gender, birth month, birth day, favorite color, favorite flag - buf[0x18] = - (data.gender & 0x01) | // gender (1 bit), 0 = male, 1 = female - ((data.birthMonth & 0x0f) << 1) | // birth month (4 bits) - ((data.birthDay & 0x1f) << 5); // birth day (5 bits) - - buf[0x19] = - ((data.birthDay >> 3) & 0x03) | // continuation of birth day (2 bits) - ((data.favoriteColor & 0x0f) << 2) | // favorite color (4 bits) - ((data.favorite ? 1 : 0) << 6); // favorite flag (1 bit) - - // mii name (REQUIRED), UTF-16LE encoded - const nameBytes = new Uint8Array(new ArrayBuffer(20)); - const nameBytesView = new DataView(nameBytes.buffer); - for (let i = 0; i < 10; i++) { - // only copy 10 characters, last one is padding - const u16Offset = i * 2; - nameBytesView.setUint16(u16Offset, data.miiName.charCodeAt(i), true); // little-endian UTF-16 - } - buf.set(nameBytes, 0x1a); - - // height and weight - buf[0x2e] = data.bodyHeight || 0; // height (1 byte) - buf[0x2f] = data.bodyWeight || 0; // weight (1 byte) - - // face type (shape), skin color, and mingle settings - buf[0x30] = - ((data.faceColor & 0x07) << 5) | // skin color (3 bits) - ((data.faceType & 0x0f) << 1) | // face shape (4 bits) - (data.mingle ? 1 : 0); // mingle (1 bit) - - // face makeup and wrinkles - buf[0x31] = - (data.faceWrinkles & 0x0f) | // face wrinkles (4 bits) - ((data.faceMakeup & 0x0f) << 4); // face makeup (4 bits) - - // hair type, color, and flip - buf[0x32] = data.hairType || 0; // hair type (1 byte) - buf[0x33] = - (data.hairColor & 0x07) | // hair color (3 bits) - ((data.hairFlip ? 1 : 0) << 3) | // hair flip (1 bit) - ((data.unknown5 & 0x0f) << 4); // unknown (4 bits) - - // eye details: type, color, size, stretch, rotation, horizontal spacing, vertical position - let eyeDetails = - (data.eyeType & 0x3f) | // eye type (6 bits) - ((data.eyeColor & 0x07) << 6) | // eye color (3 bits) - ((data.eyeSize & 0x07) << 9) | // eye size (3 bits) - ((data.eyeStretch & 0x07) << 13) | // eye stretch (3 bits) - ((data.eyeRotation & 0x1f) << 16) | // eye rotation (5 bits) - ((data.eyeHorizontal & 0x0f) << 21) | // eye horizontal spacing (4 bits) - ((data.eyeVertical & 0x1f) << 25); // eye vertical position (5 bits) - - buf[0x34] = eyeDetails & 0xff; - buf[0x35] = (eyeDetails >> 8) & 0xff; - buf[0x36] = (eyeDetails >> 16) & 0xff; - buf[0x37] = (eyeDetails >> 24) & 0xff; - - // eyebrow details: type, color, size, stretch, rotation, horizontal spacing, vertical position - let eyebrowDetails = - (data.eyebrowType & 0x1f) | // eyebrow type (5 bits) - ((data.eyebrowColor & 0x07) << 5) | // eyebrow color (3 bits) - ((data.eyebrowSize & 0x0f) << 8) | // eyebrow size (4 bits) - ((data.eyebrowStretch & 0x07) << 12) | // eyebrow stretch (3 bits) - ((data.eyebrowRotation & 0x0f) << 16) | // eyebrow rotation (4 bits) - ((data.eyebrowHorizontal & 0x0f) << 21) | // eyebrow horizontal spacing (4 bits) - ((data.eyebrowVertical & 0x1f) << 25); // eyebrow vertical position (5 bits) - - buf[0x38] = eyebrowDetails & 0xff; - buf[0x39] = (eyebrowDetails >> 8) & 0xff; - buf[0x3a] = (eyebrowDetails >> 16) & 0xff; - buf[0x3b] = (eyebrowDetails >> 24) & 0xff; - - // nose details: type, size, vertical position - let noseDetails = - (data.noseType & 0x1f) | // nose type (5 bits) - ((data.noseSize & 0x0f) << 5) | // nose size (4 bits) - ((data.noseVertical & 0x1f) << 9); // nose vertical position (5 bits) - - buf[0x3c] = noseDetails & 0xff; - buf[0x3d] = (noseDetails >> 8) & 0xff; - - // mouth details: type, color, size, stretch - let mouthDetails = - (data.mouthType & 0x3f) | // mouth type (6 bits) - ((data.mouthColor & 0x07) << 6) | // mouth color (3 bits) - ((data.mouthSize & 0x0f) << 9) | // mouth size (4 bits) - ((data.mouthStretch & 0x07) << 13); // mouth stretch (3 bits) - - buf[0x3e] = mouthDetails & 0xff; - buf[0x3f] = (mouthDetails >> 8) & 0xff; - - // mouth2 details: vertical position, mustache type - let mouth2Details = - (data.mouthVertical & 0x1f) | // mouth vertical position (5 bits) - ((data.facialHairMustache & 0x07) << 5); // mustache type (3 bits) - - buf[0x40] = mouth2Details & 0xff; - buf[0x41] = (mouth2Details >> 8) & 0xff; - - // beard details: type, color, size, vertical position - let beardDetails = - (data.facialHairBeard & 0x07) | // beard type (3 bits) - ((data.facialHairColor & 0x07) << 3) | // beard color (3 bits) - ((data.facialHairSize & 0x0f) << 6) | // beard size (4 bits) - ((data.facialHairVertical & 0x1f) << 10); // beard vertical position (5 bits) - - buf[0x42] = beardDetails & 0xff; - buf[0x43] = (beardDetails >> 8) & 0xff; - - // glasses details: type, color, size, vertical position - let glassesDetails = - (data.glassesType & 0x0f) | // glasses type (4 bits) - ((data.glassesColor & 0x07) << 4) | // glasses color (3 bits) - ((data.glassesSize & 0x0f) << 7) | // glasses size (4 bits) - (data.glassesVertical << 11); // glasses vertical position (4 bits) - - buf[0x44] = glassesDetails & 0xff; - buf[0x45] = (glassesDetails >> 8) & 0xff; - - // mole details: enable, size, horizontal position, vertical position - let moleDetails = - (data.moleEnable & 0x01) | // mole enabled (1 bit) - ((data.moleSize & 0x0f) << 1) | // mole size (4 bits) - ((data.moleHorizontal & 0x1f) << 5) | // mole horizontal position (5 bits) - ((data.moleVertical & 0x1f) << 10); // mole vertical position (5 bits) - - buf[0x46] = moleDetails & 0xff; - buf[0x47] = (moleDetails >> 8) & 0xff; - - // creator name (optional), UTF-16LE encoded - if (data.creatorName !== undefined) { - const creatorNameBytes = new Uint8Array(new ArrayBuffer(20)); - const creatorNameBytesView = new DataView(creatorNameBytes.buffer); - for (let i = 0; i < 10; i++) { - // only copy 10 characters, last one is padding - const u16Offset = i * 2; - creatorNameBytesView.setUint16( - u16Offset, - data.creatorName.charCodeAt(i), - true - ); // little-endian UTF-16 - } - buf.set(creatorNameBytes, 0x48); - } - - // padding2 which should always be zero - buf[0x5c] = data.padding2 & 0xff; - buf[0x5d] = (data.padding2 >> 8) & 0xff; - - // SET CRC16 CHECKSUM - - if (!skipCRC16) { - // crc all before last two bytes - const calculatedCRC16 = crc16(buf.slice(0, 94)); - // think MSB and LSB are reversed here but eh - buf[0x5e] = (calculatedCRC16 >> 8) & 0xff; - buf[0x5f] = calculatedCRC16 & 0xff; - } - - return buf; // return the buffer containing the encoded StoreData -}; - -// deobfuscate the obfuscated studio url format -// from, and to, a Uint8Array (so requires converting from/to hex) -const studioURLObfuscationDecode = (data) => { - const decodedData = new Uint8Array(data); - const random = decodedData[0]; - let previous = random; - - // NOTE: THIS MAY GET AWAY WITH BEING 47, IDK - for (let i = 1; i < 48; i++) { - const encodedByte = decodedData[i]; - const original = (encodedByte - 7 + 256) % 256; - decodedData[i - 1] = original ^ previous; - previous = encodedByte; - } - - return decodedData.slice(0, 46); // resize to normal studio data -}; -/* -function crc16(data) { -let crc = 0; -let msb = crc >> 8; -let lsb = crc & 0xFF; - -for(let i = 0; i < data.length; i++) { - let c = data[i]; - let x = c ^ msb; - x ^= (x >> 4); - msb = (lsb ^ (x >> 3) ^ (x << 4)) & 0xFF; - lsb = (x ^ (x << 5)) & 0xFF; -} - -crc = (msb << 8) + lsb; -return crc; -} -*/ -const encryptAndEncodeVer3StoreDataToQRCodeFormat = (data) => { - // NOTE: uses sjcl and assumes it is loaded - const nonce = data.slice(12, 20); - let content = [...data.slice(0, 12), ...data.slice(20)]; - - // checksum the data, overriding the previous checksum it may have had - const checksumContent = [ - ...data.slice(0, 12), - ...nonce, - ...data.slice(20, -2), - ]; - const newChecksum = crc16(new Uint8Array(checksumContent)); - // pack the uint16 checksum into an array - const newChecksumArray = [(newChecksum >> 8) & 0xff, newChecksum & 0xff]; - content = [...content.slice(0, -2), ...newChecksumArray]; - - //const cipher = new sjcl.cipher.aes(sjcl.codec.hex.toBits('59FC817E6446EA6190347B20E9BDCE52')); - const cipher = new sjcl.cipher.aes([ - 1509720446, 1682369121, -1875608800, -373436846, - ]); - - const paddedContent = new Uint8Array([...content, ...new Array(8).fill(0)]); - const paddedContentBits = sjcl.codec.bytes.toBits(Array.from(paddedContent)); - // nonce has to be padded - const nonceBits = sjcl.codec.bytes.toBits([...nonce, 0, 0, 0, 0]); - - const encryptedBits = sjcl.mode.ccm.encrypt( - cipher, - paddedContentBits, - nonceBits, - [], - 128 - ); - const encryptedBytes = sjcl.codec.bytes.fromBits(encryptedBits); - - const correctEncryptedContentLength = encryptedBytes.length - 8 - 16; - const encryptedContentCorrected = encryptedBytes.slice( - 0, - correctEncryptedContentLength - ); - const tag = encryptedBytes.slice(encryptedBytes.length - 16); - - // construct and return an array - const result = [...nonce, ...encryptedContentCorrected, ...tag]; - // note: not a uint8array because qrjs takes arrays natively - return result; -}; diff --git a/src/external/mii-frontend/kaitai-stream.min.js b/src/external/mii-frontend/kaitai-stream.min.js deleted file mode 100644 index 8ba0826..0000000 --- a/src/external/mii-frontend/kaitai-stream.min.js +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Minified by jsDelivr using Terser v5.19.2. - * Original file: /npm/kaitai-struct@0.10.0/KaitaiStream.js - * - * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files - */ -"use strict";!function(t,e){"function"==typeof define&&define.amd?define([],e):"object"==typeof module&&module.exports?module.exports=e():t.KaitaiStream=e()}("undefined"!=typeof self?self:this,(function(){var t=function(t,e){this._byteOffset=e||0,t instanceof ArrayBuffer?this.buffer=t:"object"==typeof t?(this.dataView=t,e&&(this._byteOffset+=e)):this.buffer=new ArrayBuffer(t||1),this.pos=0,this.alignToByte()};t.prototype={},t.depUrls={zlib:void 0},t.prototype._byteLength=0,Object.defineProperty(t.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(t){this._buffer=t,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(t.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(t){this._byteOffset=t,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(t.prototype,"dataView",{get:function(){return this._dataView},set:function(t){this._byteOffset=t.byteOffset,this._buffer=t.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+t.byteLength}}),t.prototype._trimAlloc=function(){if(this._byteLength!==this._buffer.byteLength){var t=new ArrayBuffer(this._byteLength),e=new Uint8Array(t),r=new Uint8Array(this._buffer,0,e.length);e.set(r),this.buffer=t}},t.prototype.isEof=function(){return this.pos>=this.size&&0===this.bitsLeft},t.prototype.seek=function(t){var e=Math.max(0,Math.min(this.size,t));this.pos=isNaN(e)||!isFinite(e)?0:e},Object.defineProperty(t.prototype,"size",{get:function(){return this._byteLength-this._byteOffset}}),t.prototype.readS1=function(){this.ensureBytesLeft(1);var t=this._dataView.getInt8(this.pos);return this.pos+=1,t},t.prototype.readS2be=function(){this.ensureBytesLeft(2);var t=this._dataView.getInt16(this.pos);return this.pos+=2,t},t.prototype.readS4be=function(){this.ensureBytesLeft(4);var t=this._dataView.getInt32(this.pos);return this.pos+=4,t},t.prototype.readS8be=function(){this.ensureBytesLeft(8);var t=this.readU4be(),e=this.readU4be();return 0!=(2147483648&t)?-(4294967296*(4294967295^t)+(4294967295^e))-1:4294967296*t+e},t.prototype.readS2le=function(){this.ensureBytesLeft(2);var t=this._dataView.getInt16(this.pos,!0);return this.pos+=2,t},t.prototype.readS4le=function(){this.ensureBytesLeft(4);var t=this._dataView.getInt32(this.pos,!0);return this.pos+=4,t},t.prototype.readS8le=function(){this.ensureBytesLeft(8);var t=this.readU4le(),e=this.readU4le();return 0!=(2147483648&e)?-(4294967296*(4294967295^e)+(4294967295^t))-1:4294967296*e+t},t.prototype.readU1=function(){this.ensureBytesLeft(1);var t=this._dataView.getUint8(this.pos);return this.pos+=1,t},t.prototype.readU2be=function(){this.ensureBytesLeft(2);var t=this._dataView.getUint16(this.pos);return this.pos+=2,t},t.prototype.readU4be=function(){this.ensureBytesLeft(4);var t=this._dataView.getUint32(this.pos);return this.pos+=4,t},t.prototype.readU8be=function(){return this.ensureBytesLeft(8),4294967296*this.readU4be()+this.readU4be()},t.prototype.readU2le=function(){this.ensureBytesLeft(2);var t=this._dataView.getUint16(this.pos,!0);return this.pos+=2,t},t.prototype.readU4le=function(){this.ensureBytesLeft(4);var t=this._dataView.getUint32(this.pos,!0);return this.pos+=4,t},t.prototype.readU8le=function(){this.ensureBytesLeft(8);var t=this.readU4le();return 4294967296*this.readU4le()+t},t.prototype.readF4be=function(){this.ensureBytesLeft(4);var t=this._dataView.getFloat32(this.pos);return this.pos+=4,t},t.prototype.readF8be=function(){this.ensureBytesLeft(8);var t=this._dataView.getFloat64(this.pos);return this.pos+=8,t},t.prototype.readF4le=function(){this.ensureBytesLeft(4);var t=this._dataView.getFloat32(this.pos,!0);return this.pos+=4,t},t.prototype.readF8le=function(){this.ensureBytesLeft(8);var t=this._dataView.getFloat64(this.pos,!0);return this.pos+=8,t},t.prototype.alignToByte=function(){this.bitsLeft=0,this.bits=0},t.prototype.readBitsIntBe=function(t){if(t>32)throw new RangeError("readBitsIntBe: the maximum supported bit length is 32 (tried to read "+t+" bits)");var e=0,r=t-this.bitsLeft;if(this.bitsLeft=7&-r,r>0){for(var i=1+(r-1>>3),s=this.readBytes(i),o=0;o>>this.bitsLeft|this.bits<>>-r;var a=(1<>>0},t.prototype.readBitsInt=t.prototype.readBitsIntBe,t.prototype.readBitsIntLe=function(t){if(t>32)throw new RangeError("readBitsIntLe: the maximum supported bit length is 32 (tried to read "+t+" bits)");var e=0,r=t-this.bitsLeft;if(r>0){for(var i=1+(r-1>>3),s=this.readBytes(i),o=0;o>>r:0;e=e<>>=t;(this.bitsLeft=7&-r,t<32)?e&=(1<>>=0;return e},t.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,t.prototype.readBytes=function(t){return this.mapUint8Array(t)},t.prototype.readBytesFull=function(){return this.mapUint8Array(this.size-this.pos)},t.prototype.readBytesTerm=function(t,e,r,i){for(var s,o=this.size-this.pos,n=new Uint8Array(this._buffer,this._byteOffset+this.pos),a=0;a=s&&(o=0);return i},t.processRotateLeft=function(t,e,r){if(1!==r)throw"unable to rotate group of "+r+" bytes yet";for(var i=-e&8*r-1,s=new Uint8Array(t.length),o=0;o>i;return s},t.processZlib=function(e){if("undefined"!=typeof require){void 0===t.zlib&&(t.zlib=require("zlib"));var r=t.zlib.inflateSync(Buffer.from(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)));return r}return void 0===t.zlib&&void 0!==t.depUrls.zlib&&(importScripts(t.depUrls.zlib),t.zlib=pako),r=t.zlib.inflate(e)},t.mod=function(t,e){if(e<=0)throw"mod divisor <= 0";var r=t%e;return r<0&&(r+=e),r},t.arrayMin=function(t){for(var e,r=t[0],i=1,s=t.length;ir&&(r=e);return r},t.byteArrayCompare=function(t,e){if(t===e)return 0;for(var r=t.length,i=e.length,s=rthis.size)throw new e(t,this.size-this.pos)},t.prototype.mapUint8Array=function(t){t|=0,this.ensureBytesLeft(t);var e=new Uint8Array(this._buffer,this.byteOffset+this.pos,t);return this.pos+=t,e},t.createStringFromArray=function(t){for(var e=32768,r=[],i="function"==typeof t.subarray,s=0;s this.readUint8()); - } - - public readBuffer(length: number): Buffer { - return Buffer.from(this.readBytes(length)); - } - - public readUTF16String(length: number): string { - return this.readBuffer(length).toString("utf16le").replace(/\0.*$/, ""); - } - - public writeBit(bit: number): void { - this.writeBits(bit, 1); - } - - public writeBuffer(buffer: Buffer): void { - buffer.forEach((byte) => this.writeUint8(byte)); - } - - public writeUTF16String(string: string): void { - const stringBuffer = Buffer.from(string, "utf16le"); - const terminatedBuffer = Buffer.alloc(0x14); - - stringBuffer.copy(terminatedBuffer); - - this.writeBuffer(terminatedBuffer); - } -} diff --git a/src/external/mii-js/mii.ts b/src/external/mii-js/mii.ts deleted file mode 100644 index 8b52e23..0000000 --- a/src/external/mii-js/mii.ts +++ /dev/null @@ -1,1555 +0,0 @@ -// import crypto from "crypto"; -import MD5 from "md5"; -// import assert from "assert"; -import ExtendedBitStream from "./extendedBitStream"; -import Util from "./util"; -import { Buffer } from "../../../node_modules/buffer"; -import assert from "../assert/assert"; -import { Config } from "../../config"; -import { - ToVer3EyeColorTable, - ToVer3FacelineColorTable, - ToVer3GlassColorTable, - ToVer3GlassTypeTable, - ToVer3HairColorTable, -} from "../../constants/ColorTables"; -import { RandomInt } from "../../util/Numbers"; - -const STUDIO_RENDER_URL_BASE = Config.renderer.baseURL; -const STUDIO_ASSET_URL_BASE = "https://mii-studio.akamaized.net/editor/1"; -const STUDIO_ASSET_FILE_TYPE = "webp"; - -const STUDIO_RENDER_DEFAULTS = { - type: "face", - expression: "normal", - width: 96, - bgColor: "FFFFFF00", - clothesColor: "default", - cameraXRotate: 0, - cameraYRotate: 0, - cameraZRotate: 0, - characterXRotate: 0, - characterYRotate: 0, - characterZRotate: 0, - lightXDirection: 0, - lightYDirection: 0, - lightZDirection: 0, - lightDirectionMode: "none", - splitMode: "none", - instanceCount: 1, - instanceRotationMode: "model", -}; - -const STUDIO_RENDER_OUTPUT = ["png", "glb"]; - -const STUDIO_RENDER_TYPES = ["face", "face_only", "all_body"]; - -const STUDIO_RENDER_EXPRESSIONS = [ - "normal", - "smile", - "anger", - "sorrow", - "surprise", - "blink", - "normal_open_mouth", - "smile_open_mouth", - "anger_open_mouth", - "surprise_open_mouth", - "sorrow_open_mouth", - "blink_open_mouth", - "wink_left", - "wink_right", - "wink_left_open_mouth", - "wink_right_open_mouth", - "like_wink_left", - "like_wink_right", - "frustrated", -]; - -const STUDIO_RENDER_CLOTHES_COLORS = [ - "default", - "red", - "orange", - "yellow", - "yellowgreen", - "green", - "blue", - "skyblue", - "pink", - "purple", - "brown", - "white", - "black", -]; - -const STUDIO_RENDER_LIGHT_DIRECTION_MODES = [ - "none", - "zerox", - "flipx", - "camera", - "offset", - "set", -]; - -const STUDIO_SPLIT_MODES = [ - "none", // Not actually valid, returns 400 - "front", - "back", - "both", -]; - -const STUDIO_RENDER_INSTANCE_ROTATION_MODES = ["model", "camera", "both"]; - -const STUDIO_BG_COLOR_REGEX = /^[0-9A-F]{8}$/; // Mii Studio does not allow lowercase - -export default class Mii { - public bitStream: ExtendedBitStream; - - // Mii data - // can be sure that these are all initialized in decode() - - public version!: number; - public allowCopying!: boolean; - public profanityFlag!: boolean; - public regionLock!: number; - public characterSet!: number; - public pageIndex!: number; - public slotIndex!: number; - public unknown1!: number; - public deviceOrigin!: number; - public systemId!: Buffer; - public normalMii!: boolean; - public dsMii!: boolean; - public nonUserMii!: boolean; - public isValid!: boolean; - public creationTime!: number; - public consoleMAC!: Buffer; - public gender!: number; - public birthMonth!: number; - public birthDay!: number; - public favoriteColor!: number; - public favorite!: boolean; - public miiName!: string; - public height!: number; - public build!: number; - public disableSharing!: boolean; - public faceType!: number; - // public skinColor!: number; - fflSkinColor!: number; - trueSkinColor!: number; - get skinColor() { - return this.trueSkinColor; - } - set skinColor(num) { - if (num > 5) { - this.fflSkinColor = ToVer3FacelineColorTable[num]; - this.extFacelineColor = num; - this.trueSkinColor = num; - } else { - this.fflSkinColor = num; - this.extFacelineColor = 0; - this.trueSkinColor = num; - } - } - public wrinklesType!: number; - public makeupType!: number; - public hairType!: number; - // public hairColor!: number; - fflHairColor!: number; - trueHairColor!: number; - get hairColor() { - return this.trueHairColor; - } - set hairColor(num) { - if (num > 7) { - console.log("hair color:", num, num - 8); - this.fflHairColor = ToVer3HairColorTable[num - 8]; - this.extHairColor = num - 8; - this.trueHairColor = num - 8; - } else { - this.fflHairColor = num; - this.extHairColor = 0; - this.trueHairColor = num; - } - } - public flipHair!: boolean; - public eyeType!: number; - // public eyeColor!: number; - fflEyeColor!: number; - trueEyeColor!: number; - get eyeColor() { - return this.trueEyeColor; - } - set eyeColor(num) { - if (num > 5) { - this.fflEyeColor = ToVer3EyeColorTable[num - 6]; - this.extEyeColor = num - 6; - this.trueEyeColor = num; - } else { - this.fflEyeColor = num; - if (num === 0) { - // FFL black is pure black - this.extEyeColor = 8; - this.trueEyeColor = 0; - } else { - this.extEyeColor = num + 8; - this.trueEyeColor = num; - } - } - } - public eyeScale!: number; - public eyeVerticalStretch!: number; - public eyeRotation!: number; - public eyeSpacing!: number; - public eyeYPosition!: number; - public eyebrowType!: number; - // public eyebrowColor!: number; - fflEyebrowColor!: number; - trueEyebrowColor!: number; - get eyebrowColor() { - return this.trueEyebrowColor; - } - set eyebrowColor(num) { - if (num > 7) { - this.fflEyebrowColor = ToVer3HairColorTable[num - 8]; - this.extEyebrowColor = num - 8; - this.trueEyebrowColor = num - 8; - } else { - this.fflEyebrowColor = num; - this.extEyebrowColor = 0; - this.trueEyebrowColor = num; - } - } - public eyebrowScale!: number; - public eyebrowVerticalStretch!: number; - public eyebrowRotation!: number; - public eyebrowSpacing!: number; - public eyebrowYPosition!: number; - public noseType!: number; - public noseScale!: number; - public noseYPosition!: number; - public mouthType!: number; - // public mouthColor!: number; - fflMouthColor!: number; - trueMouthColor!: number; - get mouthColor() { - return this.trueMouthColor; - } - set mouthColor(num) { - if (num > 4) { - this.fflMouthColor = ToVer3EyeColorTable[num - 5]; - this.extMouthColor = num - 5; - this.trueMouthColor = num; - // prevent Bug - if (this.fflMouthColor > 4) this.fflMouthColor = 4; - } else { - this.fflMouthColor = num; - this.extMouthColor = num + 19; - this.trueMouthColor = num; - } - // if (num > 4) { - // this.fflMouthColor = ToVer3MouthColorTable[num - 5]; - // this.extMouthColor = num - 5; - // this.trueMouthColor = num - 5; - // } else { - // this.fflMouthColor = num; - // this.extMouthColor = 0; - // this.trueMouthColor = num; - // } - } - public mouthScale!: number; - public mouthHorizontalStretch!: number; - public mouthYPosition!: number; - public mustacheType!: number; - public unknown2!: number; - public beardType!: number; - // public facialHairColor!: number; - fflFacialHairColor!: number; - trueFacialHairColor!: number; - get facialHairColor() { - return this.trueFacialHairColor; - } - set facialHairColor(num) { - if (num > 7) { - this.fflFacialHairColor = ToVer3HairColorTable[num - 8]; - this.extBeardColor = num - 8; - this.trueFacialHairColor = num - 8; - } else { - this.fflFacialHairColor = num; - this.extBeardColor = 0; - this.trueFacialHairColor = num; - } - } - public mustacheScale!: number; - public mustacheYPosition!: number; - // public glassesType!: number; - fflGlassesType!: number; - trueGlassesType!: number; - get glassesType() { - return this.trueGlassesType; - } - set glassesType(num) { - if (num > 8) { - this.fflGlassesType = ToVer3GlassTypeTable[num - 9]; - this.extGlassType = num; - this.trueGlassesType = num; - } else { - this.fflGlassesType = num; - this.extGlassType = 0; - this.trueGlassesType = num; - } - } - // public glassesColor!: number; - fflGlassesColor!: number; - trueGlassesColor!: number; - get glassesColor() { - return this.trueGlassesColor; - } - set glassesColor(num) { - if (num > 5) { - this.fflGlassesColor = ToVer3GlassColorTable[num - 6]; - this.extGlassColor = num - 6; - this.trueGlassesColor = num - 6; - } else { - this.fflGlassesColor = num; - this.extGlassColor = 0; - this.trueGlassesColor = num; - } - } - public glassesScale!: number; - public glassesYPosition!: number; - public moleEnabled!: boolean; - public moleScale!: number; - public moleXPosition!: number; - public moleYPosition!: number; - public creatorName!: string; - public checksum!: number; - - // NfpStoreDataExtension extension data - public extFacelineColor!: number; - public extHairColor!: number; - public extEyeColor!: number; - public extEyebrowColor!: number; - public extMouthColor!: number; - public extBeardColor!: number; - public extGlassColor!: number; - public extGlassType!: number; - // Extended extension data used in this app only - public extHatType!: number; - public extHatColor!: number; - // currently reserved, will be optional common colors. - public extFacePaintColor!: number; - public extShirtColor!: number; - - public initBuffer!: Buffer; - - constructor(buffer: Buffer) { - this.isMiiCData = false; - if (buffer.byteLength === 0x60) { - this.bitStream = new ExtendedBitStream( - // 96 + 12 = 108 bytes total for allowing FFSD files to import into MiiC v3. - Buffer.concat([buffer, new Uint8Array(12)]) - ); - } else { - const bytesToAdd = 0x6c - buffer.byteLength; - let tmpBuf; - if (bytesToAdd > 0) { - tmpBuf = Buffer.concat([buffer, new Uint8Array(bytesToAdd)]); - } else { - tmpBuf = buffer; - } - this.bitStream = new ExtendedBitStream(tmpBuf); - if (buffer.byteLength > 0x60) this.isMiiCData = true; - } - this.initBuffer = buffer; - this.decode(); - } - - isMiiCData!: boolean; - - hasExtendedColors(): boolean { - if ( - this.trueEyeColor > 5 || - this.trueEyebrowColor > 7 || - this.trueFacialHairColor > 7 || - this.trueGlassesColor > 5 || - this.trueGlassesType > 8 || - this.trueHairColor > 7 || - this.trueMouthColor > 4 || - this.trueSkinColor > 5 - ) - return true; - return false; - } - - public validate(): void { - // Size check - assert.ok( - Util.inRange( - this.bitStream.length / 8, - [ - // FFSD - 0x60, - // FFSD + NfpStoreDataExtension - 0x68, - // MiiC v1 (switch colors, hat color only) - 0x69, - // MiiC v2 (switch colors, hat type and hat color) - 0x6a, - // MiiC v3 (switch colors, hats, and shirt / face paint color) - 0x6c, - ] - ), - `Invalid Mii data size. Got ${ - this.bitStream.length / 8 - }, expected 96 for FFSD, 104 for MiiC v1, or 106 for MiiC v2, or 108 for MiiC v3.` - ); - - // Value range and type checks - assert.ok( - this.version === 0 || this.version === 3, - `Invalid Mii version. Got ${this.version}, expected 0 or 3` - ); - assert.strictEqual( - typeof this.allowCopying, - "boolean", - `Invalid Mii allow copying. Got ${this.allowCopying}, expected true or false` - ); - assert.strictEqual( - typeof this.profanityFlag, - "boolean", - `Invalid Mii profanity flag. Got ${this.profanityFlag}, expected true or false` - ); - assert.ok( - Util.inRange(this.regionLock, Util.range(4)), - `Invalid Mii region lock. Got ${this.regionLock}, expected 0-3` - ); - assert.ok( - Util.inRange(this.characterSet, Util.range(4)), - `Invalid Mii region lock. Got ${this.characterSet}, expected 0-3` - ); - assert.ok( - Util.inRange(this.pageIndex, Util.range(10)), - `Invalid Mii page index. Got ${this.pageIndex}, expected 0-9` - ); - assert.ok( - Util.inRange(this.slotIndex, Util.range(10)), - `Invalid Mii slot index. Got ${this.slotIndex}, expected 0-9` - ); - // assert.strictEqual( - // this.unknown1, - // 0, - // `Invalid Mii unknown1. Got ${this.unknown1}, expected 0` - // ); - assert.ok( - Util.inRange(this.deviceOrigin, Util.range(0, 5)), // allow 0 for studio Miis that don't have info - `Invalid Mii device origin. Got ${this.deviceOrigin}, expected 1-4` - ); - assert.strictEqual( - this.systemId.length, - 8, - `Invalid Mii system ID size. Got ${this.systemId.length}, system IDs must be 8 bytes long` - ); - assert.strictEqual( - typeof this.normalMii, - "boolean", - `Invalid normal Mii flag. Got ${this.normalMii}, expected true or false` - ); - assert.strictEqual( - typeof this.dsMii, - "boolean", - `Invalid DS Mii flag. Got ${this.dsMii}, expected true or false` - ); - assert.strictEqual( - typeof this.nonUserMii, - "boolean", - `Invalid non-user Mii flag. Got ${this.nonUserMii}, expected true or false` - ); - assert.strictEqual( - typeof this.isValid, - "boolean", - `Invalid Mii valid flag. Got ${this.isValid}, expected true or false` - ); - assert.ok( - this.creationTime < 268435456, - `Invalid Mii creation time. Got ${this.creationTime}, max value for 28 bit integer is 268,435,456` - ); - assert.strictEqual( - this.consoleMAC.length, - 6, - `Invalid Mii console MAC address size. Got ${this.consoleMAC.length}, console MAC addresses must be 6 bytes long` - ); - assert.ok( - Util.inRange(this.gender, Util.range(2)), - `Invalid Mii gender. Got ${this.gender}, expected 0 or 1` - ); - assert.ok( - Util.inRange(this.birthMonth, Util.range(13)), - `Invalid Mii birth month. Got ${this.birthMonth}, expected 0-12` - ); - assert.ok( - Util.inRange(this.birthDay, Util.range(32)), - `Invalid Mii birth day. Got ${this.birthDay}, expected 0-31` - ); - assert.ok( - Util.inRange(this.favoriteColor, Util.range(12)), - `Invalid Mii favorite color. Got ${this.favoriteColor}, expected 0-11` - ); - assert.strictEqual( - typeof this.favorite, - "boolean", - `Invalid favorite Mii flag. Got ${this.favorite}, expected true or false` - ); - assert.ok( - Buffer.from(this.miiName, "utf16le").length <= 0x14, - `Invalid Mii name. Got ${this.miiName}, name may only be up to 10 characters` - ); - assert.ok( - Util.inRange(this.height, Util.range(128)), - `Invalid Mii height. Got ${this.height}, expected 0-127` - ); - assert.ok( - Util.inRange(this.build, Util.range(128)), - `Invalid Mii build. Got ${this.build}, expected 0-127` - ); - assert.strictEqual( - typeof this.disableSharing, - "boolean", - `Invalid disable sharing Mii flag. Got ${this.disableSharing}, expected true or false` - ); - assert.ok( - Util.inRange(this.faceType, Util.range(12)), - `Invalid Mii face type. Got ${this.faceType}, expected 0-11` - ); - assert.ok( - Util.inRange(this.skinColor, Util.range(1000)), - `Invalid Mii skin color. Got ${this.skinColor}, expected 0-10` - ); - assert.ok( - Util.inRange(this.extFacePaintColor, Util.range(110)), - `Invalid Mii face paint color. Got ${this.skinColor}, expected 0-109` - ); - assert.ok( - Util.inRange(this.wrinklesType, Util.range(12)), - `Invalid Mii wrinkles type. Got ${this.wrinklesType}, expected 0-11` - ); - assert.ok( - Util.inRange(this.makeupType, Util.range(12)), - `Invalid Mii makeup type. Got ${this.makeupType}, expected 0-11` - ); - assert.ok( - Util.inRange(this.hairType, Util.range(132)), - `Invalid Mii hair type. Got ${this.hairType}, expected 0-131` - ); - assert.ok( - Util.inRange(this.fflHairColor, Util.range(100)), - `Invalid Mii hair color. Got ${this.fflHairColor}, expected 0-7` - ); - assert.strictEqual( - typeof this.flipHair, - "boolean", - `Invalid flip hair flag. Got ${this.flipHair}, expected true or false` - ); - assert.ok( - Util.inRange(this.eyeType, Util.range(60)), - `Invalid Mii eye type. Got ${this.eyeType}, expected 0-59` - ); - assert.ok( - Util.inRange(this.fflEyeColor, Util.range(6)), - `Invalid Mii eye color. Got ${this.fflEyeColor}, expected 0-5` - ); - assert.ok( - Util.inRange(this.eyeScale, Util.range(8)), - `Invalid Mii eye scale. Got ${this.eyeScale}, expected 0-7` - ); - assert.ok( - Util.inRange(this.eyeVerticalStretch, Util.range(7)), - `Invalid Mii eye vertical stretch. Got ${this.eyeVerticalStretch}, expected 0-6` - ); - assert.ok( - Util.inRange(this.eyeRotation, Util.range(8)), - `Invalid Mii eye rotation. Got ${this.eyeRotation}, expected 0-7` - ); - assert.ok( - Util.inRange(this.eyeSpacing, Util.range(13)), - `Invalid Mii eye spacing. Got ${this.eyeSpacing}, expected 0-12` - ); - assert.ok( - Util.inRange(this.eyeYPosition, Util.range(19)), - `Invalid Mii eye Y position. Got ${this.eyeYPosition}, expected 0-18` - ); - assert.ok( - Util.inRange(this.eyebrowType, Util.range(24)), - `Invalid Mii eyebrow type. Got ${this.eyebrowType}, expected 0-24` - ); - assert.ok( - Util.inRange(this.fflEyebrowColor, Util.range(8)), - `Invalid Mii eyebrow color. Got ${this.fflEyebrowColor}, expected 0-7` - ); - assert.ok( - Util.inRange(this.eyebrowScale, Util.range(9)), - `Invalid Mii eyebrow scale. Got ${this.eyebrowScale}, expected 0-8` - ); - assert.ok( - Util.inRange(this.eyebrowVerticalStretch, Util.range(7)), - `Invalid Mii eyebrow vertical stretch. Got ${this.eyebrowVerticalStretch}, expected 0-6` - ); - assert.ok( - Util.inRange(this.eyebrowRotation, Util.range(12)), - `Invalid Mii eyebrow rotation. Got ${this.eyebrowRotation}, expected 0-11` - ); - assert.ok( - Util.inRange(this.eyebrowSpacing, Util.range(13)), - `Invalid Mii eyebrow spacing. Got ${this.eyebrowSpacing}, expected 0-12` - ); - assert.ok( - Util.inRange(this.eyebrowYPosition, Util.range(3, 19)), - `Invalid Mii eyebrow Y position. Got ${this.eyebrowYPosition}, expected 3-18` - ); - assert.ok( - Util.inRange(this.noseType, Util.range(18)), - `Invalid Mii nose type. Got ${this.noseType}, expected 0-17` - ); - assert.ok( - Util.inRange(this.noseScale, Util.range(9)), - `Invalid Mii nose scale. Got ${this.noseScale}, expected 0-8` - ); - assert.ok( - Util.inRange(this.noseYPosition, Util.range(19)), - `Invalid Mii nose Y position. Got ${this.noseYPosition}, expected 0-18` - ); - assert.ok( - Util.inRange(this.mouthType, Util.range(36)), - `Invalid Mii mouth type. Got ${this.mouthType}, expected 0-35` - ); - assert.ok( - Util.inRange(this.fflMouthColor, Util.range(5)), - `Invalid Mii mouth color. Got ${this.fflMouthColor}, expected 0-4` - ); - assert.ok( - Util.inRange(this.mouthScale, Util.range(9)), - `Invalid Mii mouth scale. Got ${this.mouthScale}, expected 0-8` - ); - assert.ok( - Util.inRange(this.mouthHorizontalStretch, Util.range(7)), - `Invalid Mii mouth stretch. Got ${this.mouthHorizontalStretch}, expected 0-6` - ); - assert.ok( - Util.inRange(this.mouthYPosition, Util.range(19)), - `Invalid Mii mouth Y position. Got ${this.mouthYPosition}, expected 0-18` - ); - assert.ok( - Util.inRange(this.mustacheType, Util.range(6)), - `Invalid Mii mustache type. Got ${this.mustacheType}, expected 0-5` - ); - assert.ok( - Util.inRange(this.beardType, Util.range(6)), - `Invalid Mii beard type. Got ${this.beardType}, expected 0-5` - ); - assert.ok( - Util.inRange(this.fflFacialHairColor, Util.range(8)), - `Invalid Mii beard type. Got ${this.fflFacialHairColor}, expected 0-7` - ); - assert.ok( - Util.inRange(this.mustacheScale, Util.range(9)), - `Invalid Mii mustache scale. Got ${this.mustacheScale}, expected 0-8` - ); - assert.ok( - Util.inRange(this.mustacheYPosition, Util.range(17)), - `Invalid Mii mustache Y position. Got ${this.mustacheYPosition}, expected 0-16` - ); - assert.ok( - Util.inRange(this.fflGlassesType, Util.range(9)), - `Invalid Mii glasses type. Got ${this.fflGlassesType}, expected 0-8` - ); - assert.ok( - Util.inRange(this.fflGlassesColor, Util.range(100)), - `Invalid Mii glasses color. Got ${this.fflGlassesColor}, expected 0-5` - ); - assert.ok( - Util.inRange(this.glassesScale, Util.range(8)), - `Invalid Mii glasses scale. Got ${this.glassesScale}, expected 0-7` - ); - assert.ok( - Util.inRange(this.glassesYPosition, Util.range(21)), - `Invalid Mii glasses Y position. Got ${this.glassesYPosition}, expected 0-20` - ); - assert.strictEqual( - typeof this.moleEnabled, - "boolean", - `Invalid mole enabled flag. Got ${this.moleEnabled}, expected true or false` - ); - assert.ok( - Util.inRange(this.moleScale, Util.range(9)), - `Invalid Mii mole scale. Got ${this.moleScale}, expected 0-8` - ); - assert.ok( - Util.inRange(this.moleXPosition, Util.range(17)), - `Invalid Mii mole X position. Got ${this.moleXPosition}, expected 0-16` - ); - assert.ok( - Util.inRange(this.moleYPosition, Util.range(31)), - `Invalid Mii mole Y position. Got ${this.moleYPosition}, expected 0-30` - ); - - // Sanity checks - /* - - HEYimHeroic says this check must be true, - but in my testing my Mii's have both these flags - set and are valid - - Commenting out until we get more info - - if (this.dsMii && this.isValid) { - assert.fail('If DS Mii flag is true, the is valid flag must be false'); - } - */ - - if ( - this.nonUserMii && - (this.creationTime !== 0 || this.isValid || this.dsMii || this.normalMii) - ) { - assert.fail("Non-user Mii's must have all other Mii ID bits set to 0"); - } - - if (!this.normalMii && !this.disableSharing) { - assert.fail("Special Miis must have sharing disabled"); - } - - // console.log(this.hairColor); - } - - public decode(): void { - this.version = this.bitStream.readUint8(); - this.allowCopying = this.bitStream.readBoolean(); - this.profanityFlag = this.bitStream.readBoolean(); - this.regionLock = this.bitStream.readBits(2); - this.characterSet = this.bitStream.readBits(2); - this.bitStream.alignByte(); - this.pageIndex = this.bitStream.readBits(4); - this.slotIndex = this.bitStream.readBits(4); - this.unknown1 = this.bitStream.readBits(4); - this.deviceOrigin = this.bitStream.readBits(3); - this.bitStream.alignByte(); - this.systemId = this.bitStream.readBuffer(8); - this.bitStream.swapEndian(); // * Mii ID data is BE - this.normalMii = this.bitStream.readBoolean(); - this.dsMii = this.bitStream.readBoolean(); - this.nonUserMii = this.bitStream.readBoolean(); - this.isValid = this.bitStream.readBoolean(); - this.creationTime = this.bitStream.readBits(28); - this.bitStream.swapEndian(); // * Swap back to LE - this.consoleMAC = this.bitStream.readBuffer(6); - this.bitStream.skipInt16(); // * 0x0000 padding - this.gender = this.bitStream.readBit(); - this.birthMonth = this.bitStream.readBits(4); - this.birthDay = this.bitStream.readBits(5); - this.favoriteColor = this.bitStream.readBits(4); - this.favorite = this.bitStream.readBoolean(); - this.bitStream.alignByte(); - this.miiName = this.bitStream.readUTF16String(0x14); - this.height = this.bitStream.readUint8(); - this.build = this.bitStream.readUint8(); - this.disableSharing = this.bitStream.readBoolean(); - this.faceType = this.bitStream.readBits(4); - this.skinColor = this.bitStream.readBits(3); - this.wrinklesType = this.bitStream.readBits(4); - this.makeupType = this.bitStream.readBits(4); - this.hairType = this.bitStream.readUint8(); - this.hairColor = this.bitStream.readBits(3); - this.flipHair = this.bitStream.readBoolean(); - this.bitStream.alignByte(); - this.eyeType = this.bitStream.readBits(6); - this.eyeColor = this.bitStream.readBits(3); - this.eyeScale = this.bitStream.readBits(4); - this.eyeVerticalStretch = this.bitStream.readBits(3); - this.eyeRotation = this.bitStream.readBits(5); - this.eyeSpacing = this.bitStream.readBits(4); - this.eyeYPosition = this.bitStream.readBits(5); - this.bitStream.alignByte(); - this.eyebrowType = this.bitStream.readBits(5); - this.eyebrowColor = this.bitStream.readBits(3); - this.eyebrowScale = this.bitStream.readBits(4); - this.eyebrowVerticalStretch = this.bitStream.readBits(3); - this.bitStream.skipBit(); - this.eyebrowRotation = this.bitStream.readBits(4); - this.bitStream.skipBit(); - this.eyebrowSpacing = this.bitStream.readBits(4); - this.eyebrowYPosition = this.bitStream.readBits(5); - this.bitStream.alignByte(); - this.noseType = this.bitStream.readBits(5); - this.noseScale = this.bitStream.readBits(4); - this.noseYPosition = this.bitStream.readBits(5); - this.bitStream.alignByte(); - this.mouthType = this.bitStream.readBits(6); - this.mouthColor = this.bitStream.readBits(3); - this.mouthScale = this.bitStream.readBits(4); - this.mouthHorizontalStretch = this.bitStream.readBits(3); - this.mouthYPosition = this.bitStream.readBits(5); - this.mustacheType = this.bitStream.readBits(3); - this.unknown2 = this.bitStream.readUint8(); - this.beardType = this.bitStream.readBits(3); - this.facialHairColor = this.bitStream.readBits(3); - this.mustacheScale = this.bitStream.readBits(4); - this.mustacheYPosition = this.bitStream.readBits(5); - this.bitStream.alignByte(); - this.glassesType = this.bitStream.readBits(4); - this.glassesColor = this.bitStream.readBits(3); - this.glassesScale = this.bitStream.readBits(4); - this.glassesYPosition = this.bitStream.readBits(5); - this.moleEnabled = this.bitStream.readBoolean(); - this.moleScale = this.bitStream.readBits(4); - this.moleXPosition = this.bitStream.readBits(5); - this.moleYPosition = this.bitStream.readBits(5); - this.bitStream.alignByte(); - this.creatorName = this.bitStream.readUTF16String(0x14); - this.bitStream.skipInt16(); // * 0x0000 padding - this.bitStream.swapEndian(); // * Swap to big endian because thats how checksum is calculated here - this.checksum = this.bitStream.readUint16(); - this.bitStream.swapEndian(); // * Swap back to little endian - - // console.log("Total:", this.bitStream.length / 8, "bytes"); - - if (this.bitStream.length / 8 > 0x60) { - // Read 8 more bytes for NfpStoreDataExtention - this.extFacelineColor = this.bitStream.readUint8(); - this.extHairColor = this.bitStream.readUint8(); - this.extEyeColor = this.bitStream.readUint8(); - this.extEyebrowColor = this.bitStream.readUint8(); - this.extMouthColor = this.bitStream.readUint8(); - this.extBeardColor = this.bitStream.readUint8(); - this.extGlassColor = this.bitStream.readUint8(); - this.extGlassType = this.bitStream.readUint8(); - } - // Custom data - if (this.bitStream.length / 8 > 0x68) { - this.extHatType = this.bitStream.readUint8(); - } - if (this.bitStream.length / 8 > 0x69) { - this.extHatColor = this.bitStream.readUint8(); - } - if (this.bitStream.length / 8 > 0x6a) { - this.extFacePaintColor = this.bitStream.readUint8(); - } else { - this.extFacePaintColor = 0; - } - if (this.bitStream.length / 8 > 0x6b) { - this.extShirtColor = this.bitStream.readUint8(); - } else { - this.extShirtColor = 0; - } - - if (this.extFacelineColor) this.trueSkinColor = this.extFacelineColor; - if (this.extHairColor) this.trueHairColor = this.extHairColor; - if (this.extEyeColor) this.trueEyeColor = this.extEyeColor; - if (this.extEyebrowColor) this.trueEyebrowColor = this.extEyebrowColor; - if (this.extMouthColor) this.trueMouthColor = this.extMouthColor; - if (this.extBeardColor) this.trueFacialHairColor = this.extBeardColor; - if (this.extGlassColor) this.trueGlassesColor = this.extGlassColor; - if (this.extGlassType) this.trueGlassesType = this.extGlassType; - - this.validate(); - - if (this.checksum !== this.calculateCRC()) { - throw new Error("Invalid Mii checksum"); - } - } - - public encode(): Buffer { - this.validate(); // * Don't write invalid Mii data - - // TODO - Maybe create a new stream instead of modifying the original? - this.bitStream.bitSeek(0); - - this.bitStream.writeUint8(this.version); - this.bitStream.writeBoolean(this.allowCopying); - this.bitStream.writeBoolean(this.profanityFlag); - this.bitStream.writeBits(this.regionLock, 2); - this.bitStream.writeBits(this.characterSet, 2); - this.bitStream.alignByte(); - this.bitStream.writeBits(this.pageIndex, 4); - this.bitStream.writeBits(this.slotIndex, 4); - this.bitStream.writeBits(this.unknown1, 4); - this.bitStream.writeBits(this.deviceOrigin, 3); - this.bitStream.alignByte(); - this.bitStream.writeBuffer(this.systemId); - this.bitStream.swapEndian(); // * Mii ID data is BE - this.bitStream.writeBoolean(this.normalMii); - this.bitStream.writeBoolean(this.dsMii); - this.bitStream.writeBoolean(this.nonUserMii); - this.bitStream.writeBoolean(this.isValid); - this.bitStream.writeBits(this.creationTime, 28); // TODO - Calculate this instead of carrying it over - this.bitStream.swapEndian(); // * Swap back to LE - this.bitStream.writeBuffer(this.consoleMAC); - this.bitStream.writeUint16(0x0); // * 0x0000 padding - this.bitStream.writeBit(this.gender); - this.bitStream.writeBits(this.birthMonth, 4); - this.bitStream.writeBits(this.birthDay, 5); - this.bitStream.writeBits(this.favoriteColor, 4); - this.bitStream.writeBoolean(this.favorite); - this.bitStream.alignByte(); - this.bitStream.writeUTF16String(this.miiName); - this.bitStream.writeUint8(this.height); - this.bitStream.writeUint8(this.build); - this.bitStream.writeBoolean(this.disableSharing); - this.bitStream.writeBits(this.faceType, 4); - this.bitStream.writeBits(this.fflSkinColor, 3); - this.bitStream.writeBits(this.wrinklesType, 4); - this.bitStream.writeBits(this.makeupType, 4); - this.bitStream.writeUint8(this.hairType); - this.bitStream.writeBits(this.fflHairColor, 3); - this.bitStream.writeBoolean(this.flipHair); - this.bitStream.alignByte(); - this.bitStream.writeBits(this.eyeType, 6); - this.bitStream.writeBits(this.fflEyeColor, 3); - this.bitStream.writeBits(this.eyeScale, 4); - this.bitStream.writeBits(this.eyeVerticalStretch, 3); - this.bitStream.writeBits(this.eyeRotation, 5); - this.bitStream.writeBits(this.eyeSpacing, 4); - this.bitStream.writeBits(this.eyeYPosition, 5); - this.bitStream.alignByte(); - this.bitStream.writeBits(this.eyebrowType, 5); - this.bitStream.writeBits(this.fflEyebrowColor, 3); - this.bitStream.writeBits(this.eyebrowScale, 4); - this.bitStream.writeBits(this.eyebrowVerticalStretch, 3); - this.bitStream.skipBit(); - this.bitStream.writeBits(this.eyebrowRotation, 4); - this.bitStream.skipBit(); - this.bitStream.writeBits(this.eyebrowSpacing, 4); - this.bitStream.writeBits(this.eyebrowYPosition, 5); - this.bitStream.alignByte(); - this.bitStream.writeBits(this.noseType, 5); - this.bitStream.writeBits(this.noseScale, 4); - this.bitStream.writeBits(this.noseYPosition, 5); - this.bitStream.alignByte(); - this.bitStream.writeBits(this.mouthType, 6); - this.bitStream.writeBits(this.fflMouthColor, 3); - this.bitStream.writeBits(this.mouthScale, 4); - this.bitStream.writeBits(this.mouthHorizontalStretch, 3); - this.bitStream.writeBits(this.mouthYPosition, 5); - this.bitStream.writeBits(this.mustacheType, 3); - this.bitStream.writeUint8(this.unknown2); - this.bitStream.writeBits(this.beardType, 3); - this.bitStream.writeBits(this.fflFacialHairColor, 3); - this.bitStream.writeBits(this.mustacheScale, 4); - this.bitStream.writeBits(this.mustacheYPosition, 5); - this.bitStream.alignByte(); - this.bitStream.writeBits(this.fflGlassesType, 4); - this.bitStream.writeBits(this.fflGlassesColor, 3); - this.bitStream.writeBits(this.glassesScale, 4); - this.bitStream.writeBits(this.glassesYPosition, 5); - this.bitStream.writeBoolean(this.moleEnabled); - this.bitStream.writeBits(this.moleScale, 4); - this.bitStream.writeBits(this.moleXPosition, 5); - this.bitStream.writeBits(this.moleYPosition, 5); - this.bitStream.alignByte(); - this.bitStream.writeUTF16String(this.creatorName); - this.bitStream.writeUint16(0x0); // * 0x0000 padding - this.bitStream.swapEndian(); // * Swap to big endian because thats how checksum is calculated here - this.bitStream.writeUint16(this.calculateCRC()); - this.bitStream.swapEndian(); // * Swap back to little endian - - // Write 8 bytes for NfpStoreDataExtention - this.bitStream.writeUint8(this.extFacelineColor); - this.bitStream.writeUint8(this.extHairColor); - this.bitStream.writeUint8(this.extEyeColor); - this.bitStream.writeUint8(this.extEyebrowColor); - this.bitStream.writeUint8(this.extMouthColor); - this.bitStream.writeUint8(this.extBeardColor); - this.bitStream.writeUint8(this.extGlassColor); - this.bitStream.writeUint8(this.extGlassType); - // Some custom CUSTOM data - this.bitStream.writeUint8(this.extHatType); - this.bitStream.writeUint8(this.extHatColor); - // MiiC v3 fields - this.bitStream.writeUint8(this.extFacePaintColor); - this.bitStream.writeUint8(this.extShirtColor); - - // console.log( - // "Wrote 8 extra bytes for NfpStoreDataExtention:", - // this.extFacelineColor, - // this.extHairColor, - // this.extEyeColor, - // this.extEyebrowColor, - // this.extMouthColor, - // this.extBeardColor, - // this.extGlassColor, - // this.extGlassType - // ); - - // // @ts-expect-error _view is private - return Buffer.from(this.bitStream.view._view); - } - - public encodeFFSD(): Buffer { - this.validate(); // * Don't write invalid Mii data - - // TODO - Maybe create a new stream instead of modifying the original? - this.bitStream.bitSeek(0); - - this.bitStream.writeUint8(this.version); - this.bitStream.writeBoolean(this.allowCopying); - this.bitStream.writeBoolean(this.profanityFlag); - this.bitStream.writeBits(this.regionLock, 2); - this.bitStream.writeBits(this.characterSet, 2); - this.bitStream.alignByte(); - this.bitStream.writeBits(this.pageIndex, 4); - this.bitStream.writeBits(this.slotIndex, 4); - this.bitStream.writeBits(this.unknown1, 4); - this.bitStream.writeBits(this.deviceOrigin, 3); - this.bitStream.alignByte(); - this.bitStream.writeBuffer(this.systemId); - this.bitStream.swapEndian(); // * Mii ID data is BE - this.bitStream.writeBoolean(this.normalMii); - this.bitStream.writeBoolean(this.dsMii); - this.bitStream.writeBoolean(this.nonUserMii); - this.bitStream.writeBoolean(this.isValid); - this.bitStream.writeBits(this.creationTime, 28); // TODO - Calculate this instead of carrying it over - this.bitStream.swapEndian(); // * Swap back to LE - this.bitStream.writeBuffer(this.consoleMAC); - this.bitStream.writeUint16(0x0); // * 0x0000 padding - this.bitStream.writeBit(this.gender); - this.bitStream.writeBits(this.birthMonth, 4); - this.bitStream.writeBits(this.birthDay, 5); - this.bitStream.writeBits(this.favoriteColor, 4); - this.bitStream.writeBoolean(this.favorite); - this.bitStream.alignByte(); - this.bitStream.writeUTF16String(this.miiName); - this.bitStream.writeUint8(this.height); - this.bitStream.writeUint8(this.build); - this.bitStream.writeBoolean(this.disableSharing); - this.bitStream.writeBits(this.faceType, 4); - this.bitStream.writeBits(this.fflSkinColor, 3); - this.bitStream.writeBits(this.wrinklesType, 4); - this.bitStream.writeBits(this.makeupType, 4); - this.bitStream.writeUint8(this.hairType); - this.bitStream.writeBits(this.fflHairColor, 3); - this.bitStream.writeBoolean(this.flipHair); - this.bitStream.alignByte(); - this.bitStream.writeBits(this.eyeType, 6); - this.bitStream.writeBits(this.fflEyeColor, 3); - this.bitStream.writeBits(this.eyeScale, 4); - this.bitStream.writeBits(this.eyeVerticalStretch, 3); - this.bitStream.writeBits(this.eyeRotation, 5); - this.bitStream.writeBits(this.eyeSpacing, 4); - this.bitStream.writeBits(this.eyeYPosition, 5); - this.bitStream.alignByte(); - this.bitStream.writeBits(this.eyebrowType, 5); - this.bitStream.writeBits(this.fflEyebrowColor, 3); - this.bitStream.writeBits(this.eyebrowScale, 4); - this.bitStream.writeBits(this.eyebrowVerticalStretch, 3); - this.bitStream.skipBit(); - this.bitStream.writeBits(this.eyebrowRotation, 4); - this.bitStream.skipBit(); - this.bitStream.writeBits(this.eyebrowSpacing, 4); - this.bitStream.writeBits(this.eyebrowYPosition, 5); - this.bitStream.alignByte(); - this.bitStream.writeBits(this.noseType, 5); - this.bitStream.writeBits(this.noseScale, 4); - this.bitStream.writeBits(this.noseYPosition, 5); - this.bitStream.alignByte(); - this.bitStream.writeBits(this.mouthType, 6); - this.bitStream.writeBits(this.fflMouthColor, 3); - this.bitStream.writeBits(this.mouthScale, 4); - this.bitStream.writeBits(this.mouthHorizontalStretch, 3); - this.bitStream.writeBits(this.mouthYPosition, 5); - this.bitStream.writeBits(this.mustacheType, 3); - this.bitStream.writeUint8(this.unknown2); - this.bitStream.writeBits(this.beardType, 3); - this.bitStream.writeBits(this.fflFacialHairColor, 3); - this.bitStream.writeBits(this.mustacheScale, 4); - this.bitStream.writeBits(this.mustacheYPosition, 5); - this.bitStream.alignByte(); - this.bitStream.writeBits(this.glassesType, 4); - this.bitStream.writeBits(this.fflGlassesColor, 3); - this.bitStream.writeBits(this.glassesScale, 4); - this.bitStream.writeBits(this.glassesYPosition, 5); - this.bitStream.writeBoolean(this.moleEnabled); - this.bitStream.writeBits(this.moleScale, 4); - this.bitStream.writeBits(this.moleXPosition, 5); - this.bitStream.writeBits(this.moleYPosition, 5); - this.bitStream.alignByte(); - this.bitStream.writeUTF16String(this.creatorName); - this.bitStream.writeUint16(0x0); // * 0x0000 padding - this.bitStream.swapEndian(); // * Swap to big endian because thats how checksum is calculated here - this.bitStream.writeUint16(this.calculateCRC()); - this.bitStream.swapEndian(); // * Swap back to little endian - - // // @ts-expect-error _view is private - return Buffer.from(this.bitStream.view._view).slice(0, 96); - } - - public calculateCRC(): number { - const view = this.bitStream.view; - - // // @ts-expect-error _view is private - const data = view._view.subarray(0, 0x5e); - - let crc = 0x0000; - - for (const byte of data) { - for (let bit = 7; bit >= 0; bit--) { - const flag = (crc & 0x8000) != 0; - crc = ((crc << 1) | ((byte >> bit) & 0x1)) ^ (flag ? 0x1021 : 0); - } - } - - for (let i = 16; i > 0; i--) { - const flag = (crc & 0x8000) != 0; - crc = (crc << 1) ^ (flag ? 0x1021 : 0); - } - - return crc & 0xffff; - } - - public encodeStudio(): Buffer { - this.validate(); - - /* - Can also disable randomization with: - - let miiStudioData = Buffer.alloc(0x2F); - let next = 256; - - and removing "randomizer" and the "miiStudioData.writeUInt8(randomizer);" call - */ - // const miiStudioData = Buffer.alloc(0x2f); - // const randomized = Math.floor(256 * Math.random()); - // let next = randomized; - let miiStudioData = Buffer.alloc(0x2f); - let next = 256; - let pos = 1; - - function encodeMiiPart(partValue: number): void { - const encoded = (7 + (partValue ^ next)) % 256; - next = encoded; - - miiStudioData.writeUInt8(encoded, pos); - pos++; - } - - // miiStudioData.writeUInt8(randomized); - - // if (this.facialHairColor === 0) { - // encodeMiiPart(8); - // } else { - encodeMiiPart(this.trueFacialHairColor); - // } - - encodeMiiPart(this.beardType); - encodeMiiPart(this.build); - encodeMiiPart(this.eyeVerticalStretch); - if (this.trueEyeColor > 5) { - encodeMiiPart(this.extEyeColor); - } else encodeMiiPart(this.fflEyeColor + 8); - // if (this.trueEyeColor > 5) { - // encodeMiiPart(this.extEyeColor); - // } else { - // encodeMiiPart(this.fflEyeColor); - // } - encodeMiiPart(this.eyeRotation); - encodeMiiPart(this.eyeScale); - encodeMiiPart(this.eyeType); - encodeMiiPart(this.eyeSpacing); - encodeMiiPart(this.eyeYPosition); - encodeMiiPart(this.eyebrowVerticalStretch); - - // if (this.eyebrowColor === 0) { - // encodeMiiPart(8); - // } else { - encodeMiiPart(this.trueEyebrowColor); - // } - - encodeMiiPart(this.eyebrowRotation); - encodeMiiPart(this.eyebrowScale); - encodeMiiPart(this.eyebrowType); - encodeMiiPart(this.eyebrowSpacing); - encodeMiiPart(this.eyebrowYPosition); - if (this.extFacePaintColor !== 0) { - encodeMiiPart(this.extFacePaintColor + 9); - } else { - encodeMiiPart(this.trueSkinColor); - } - - encodeMiiPart(this.makeupType); - encodeMiiPart(this.faceType); - encodeMiiPart(this.wrinklesType); - encodeMiiPart(this.favoriteColor); - encodeMiiPart(this.gender); - - if (this.extGlassColor > 0) { - encodeMiiPart(this.trueGlassesColor); - } else { - if (this.fflGlassesColor === 0) encodeMiiPart(8); - else encodeMiiPart(this.fflGlassesColor + 13); - } - - encodeMiiPart(this.glassesScale); - encodeMiiPart(this.trueGlassesType); - encodeMiiPart(this.glassesYPosition); - - // if (this.hairColor == 0) { - // encodeMiiPart(8); - // } else { - encodeMiiPart(this.trueHairColor); - // } - - encodeMiiPart(this.flipHair ? 1 : 0); - encodeMiiPart(this.hairType); - encodeMiiPart(this.height); - encodeMiiPart(this.moleScale); - encodeMiiPart(this.moleEnabled ? 1 : 0); - encodeMiiPart(this.moleXPosition); - encodeMiiPart(this.moleYPosition); - encodeMiiPart(this.mouthHorizontalStretch); - - // if (this.mouthColor < 4) { - if (this.trueMouthColor > 5) { - encodeMiiPart(this.extMouthColor); - } else encodeMiiPart(this.fflMouthColor + 19); - // encodeMiiPart(this.trueMouthColor + 19); - // encodeMiiPart(this.mouthColor + 19); - // } else { - // encodeMiiPart(0); - // } - - encodeMiiPart(this.mouthScale); - encodeMiiPart(this.mouthType); - encodeMiiPart(this.mouthYPosition); - encodeMiiPart(this.mustacheScale); - encodeMiiPart(this.mustacheType); - encodeMiiPart(this.mustacheYPosition); - encodeMiiPart(this.noseScale); - encodeMiiPart(this.noseType); - encodeMiiPart(this.noseYPosition); - - return miiStudioData; - } - - // Encoding for Switch CharInfo (nn::mii::CharInfo) format - // Originally implemented by Timiimiimii: https://github.com/Timiimiimii - public encodeCharInfoSwitch(): Buffer { - this.validate(); // * Don't write invalid Mii data - - // TODO - Maybe create a new stream instead of modifying the original? - this.bitStream.bitSeek(0); - - // Write createID field (nn::mii::CreateId). - for (let i = 0; i < 16; i++) { // UUIDv4 length - let r = RandomInt(255); - if (i == 8) { // If this is the 8th field... - // Set bits checked by nn::mii::CreateId::IsValid() on Switch - r &= 0b00111111; r |= 0b10000000; - } - this.bitStream.writeUint8(r); // Write - } - - this.bitStream.writeUTF16String(this.miiName); - - this.bitStream.writeUint8(0); // Padding for name - this.bitStream.writeUint8(this.characterSet); - this.bitStream.writeUint8(0); // ??? - - this.bitStream.writeUint8(this.favoriteColor); - this.bitStream.writeUint8(this.gender); - this.bitStream.writeUint8(this.height); - this.bitStream.writeUint8(this.build); - // type field - 0 = normal, 1 = special, inverse - this.bitStream.writeUint8(!this.normalMii); - this.bitStream.writeUint8(this.regionLock); - - this.bitStream.writeUint8(this.faceType); - this.bitStream.writeUint8(this.trueSkinColor); - this.bitStream.writeUint8(this.wrinklesType); - this.bitStream.writeUint8(this.makeupType); - - this.bitStream.writeUint8(this.hairType); - //this.bitStream.writeUint8(this.trueHairColor); - - if (this.trueHairColor == 0) { - this.bitStream.writeUint8(8); - } else { - this.bitStream.writeUint8(this.trueHairColor); - } - - this.bitStream.writeUint8(this.flipHair); - - this.bitStream.writeUint8(this.eyeType); - if (this.trueEyeColor > 5) { - this.bitStream.writeUint8(this.extEyeColor); - } else this.bitStream.writeUint8(this.fflEyeColor + 8); - this.bitStream.writeUint8(this.eyeScale); - this.bitStream.writeUint8(this.eyeVerticalStretch); - this.bitStream.writeUint8(this.eyeRotation); - this.bitStream.writeUint8(this.eyeSpacing); - this.bitStream.writeUint8(this.eyeYPosition); - - this.bitStream.writeUint8(this.eyebrowType); - //this.bitStream.writeUint8(this.trueEyebrowColor); - - if (this.trueEyebrowColor == 0) { - this.bitStream.writeUint8(8); - } else { - this.bitStream.writeUint8(this.trueEyebrowColor); - } - - this.bitStream.writeUint8(this.eyebrowScale); - this.bitStream.writeUint8(this.eyebrowVerticalStretch); - this.bitStream.writeUint8(this.eyebrowRotation); - this.bitStream.writeUint8(this.eyebrowSpacing); - this.bitStream.writeUint8(this.eyebrowYPosition); - - this.bitStream.writeUint8(this.noseType); - this.bitStream.writeUint8(this.noseScale); - this.bitStream.writeUint8(this.noseYPosition); - - this.bitStream.writeUint8(this.mouthType); - if (this.trueMouthColor > 5) { - this.bitStream.writeUint8(this.extMouthColor); - } else this.bitStream.writeUint8(this.fflMouthColor + 19); - this.bitStream.writeUint8(this.mouthScale); - this.bitStream.writeUint8(this.mouthHorizontalStretch); - this.bitStream.writeUint8(this.mouthYPosition); - - this.bitStream.writeUint8(this.trueFacialHairColor); - this.bitStream.writeUint8(this.beardType); - this.bitStream.writeUint8(this.mustacheType); - this.bitStream.writeUint8(this.mustacheScale); - this.bitStream.writeUint8(this.mustacheYPosition); - this.bitStream.writeUint8(this.trueGlassesType); - if (this.extGlassColor > 0) { - this.bitStream.writeUint8(this.trueGlassesColor); - } else { - if (this.fflGlassesColor === 0) this.bitStream.writeUint8(8); - else this.bitStream.writeUint8(this.fflGlassesColor + 13); - } - this.bitStream.writeUint8(this.glassesScale); - this.bitStream.writeUint8(this.glassesYPosition); - this.bitStream.writeUint8(this.moleEnabled); - this.bitStream.writeUint8(this.moleScale); - this.bitStream.writeUint8(this.moleXPosition); - this.bitStream.writeUint8(this.moleYPosition); - - this.bitStream.writeUint8(0); // Always zero. - - return Buffer.from(this.bitStream.view._view).slice(0, 0x58); - } - - public studioUrl( - queryParams: { - type?: string; - expression?: string; - ext?: "png" | "glb"; - width?: number; - bgColor?: string; - clothesColor?: string; - cameraXRotate?: number; - cameraYRotate?: number; - cameraZRotate?: number; - characterXRotate?: number; - characterYRotate?: number; - characterZRotate?: number; - lightXDirection?: number; - lightYDirection?: number; - lightZDirection?: number; - lightDirectionMode?: string; - instanceCount?: number; - instanceRotationMode?: string; - data?: string; - modelType?: "hat"; - } = STUDIO_RENDER_DEFAULTS - ): string { - const params = { - ...STUDIO_RENDER_DEFAULTS, - ...queryParams, - data: this.encodeStudio().toString("hex"), - shaderType: "default", - }; - - let fileExt = "png"; - - if (params.ext) { - fileExt = params.ext; - delete params["ext"]; - } - - // TODO - Assert and error out instead of setting defaults? - - params.type = STUDIO_RENDER_TYPES.includes(params.type as string) - ? params.type - : STUDIO_RENDER_DEFAULTS.type; - params.expression = STUDIO_RENDER_EXPRESSIONS.includes( - params.expression as string - ) - ? params.expression - : STUDIO_RENDER_DEFAULTS.expression; - params.width = Util.clamp(params.width, 512); - params.bgColor = STUDIO_BG_COLOR_REGEX.test(params.bgColor as string) - ? params.bgColor - : STUDIO_RENDER_DEFAULTS.bgColor; - params.clothesColor = STUDIO_RENDER_CLOTHES_COLORS.includes( - params.clothesColor - ) - ? params.clothesColor - : STUDIO_RENDER_DEFAULTS.clothesColor; - params.cameraXRotate = Util.clamp(params.cameraXRotate, 359); - params.cameraYRotate = Util.clamp(params.cameraYRotate, 359); - params.cameraZRotate = Util.clamp(params.cameraZRotate, 359); - params.characterXRotate = Util.clamp(params.characterXRotate, 359); - params.characterYRotate = Util.clamp(params.characterYRotate, 359); - params.characterZRotate = Util.clamp(params.characterZRotate, 359); - params.lightXDirection = Util.clamp(params.lightXDirection, 359); - params.lightYDirection = Util.clamp(params.lightYDirection, 359); - params.lightZDirection = Util.clamp(params.lightZDirection, 359); - params.lightDirectionMode = STUDIO_RENDER_LIGHT_DIRECTION_MODES.includes( - params.lightDirectionMode - ) - ? params.lightDirectionMode - : STUDIO_RENDER_DEFAULTS.lightDirectionMode; - params.splitMode = STUDIO_SPLIT_MODES.includes(params.splitMode) - ? params.splitMode - : STUDIO_RENDER_DEFAULTS.splitMode; - params.instanceCount = Util.clamp(params.instanceCount, 1, 16); - params.instanceRotationMode = - STUDIO_RENDER_INSTANCE_ROTATION_MODES.includes( - params.instanceRotationMode - ) - ? params.instanceRotationMode - : STUDIO_RENDER_DEFAULTS.instanceRotationMode; - - // converts non-string params to strings - const query = new URLSearchParams( - Object.fromEntries( - Object.entries(params).map(([key, value]) => [key, value.toString()]) - ) - ); - - if (params.lightDirectionMode === "none") { - query.delete("lightDirectionMode"); - query.delete("lightXDirection"); - query.delete("lightYDirection"); - query.delete("lightZDirection"); - } - if (params.splitMode === "none") query.delete("splitMode"); - - return `${STUDIO_RENDER_URL_BASE}.${fileExt}?${query.toString()}`; - } - - public studioAssetUrlBody(): string { - return this.studioAssetUrl(`body/${this.gender}/${this.favoriteColor}`); - } - - public studioAssetUrlHead(): string { - return this.studioAssetUrl( - `face/${this.faceType}/${this.wrinklesType}/${this.makeupType}/${this.skinColor}` - ); - } - - public studioAssetUrlFace(): string { - // Alias - return this.studioAssetUrlHead(); - } - - public studioAssetUrlEye(): string { - return this.studioAssetUrl(`eye/${this.eyeType}/${this.eyeColor + 8}`); - } - - public studioAssetUrlEyebrow(): string { - let eyebrowColor = this.eyebrowColor; - - if (this.eyebrowColor === 0) { - eyebrowColor = 8; - } - - return this.studioAssetUrl(`eyebrow/${this.eyebrowType}/${eyebrowColor}`); - } - - public studioAssetUrlNose(): string { - return this.studioAssetUrl(`nose/${this.noseType}/${this.skinColor}`); - } - - public studioAssetUrlMouth(): string { - let mouthColor = 0; - - if (this.mouthColor < 4) { - mouthColor = this.mouthColor + 19; - } - - return this.studioAssetUrl(`mouth/${this.mouthType}/${mouthColor}`); - } - - public studioAssetUrlHair(): string { - let assetPath; - let hairColor = this.hairColor; - - if (this.hairColor == 0) { - hairColor = 8; - } - - if (this.hairType === 34 || this.hairType === 57) { - // Types 34 and 57 are hats - // No flip and they use clothes color not hair color - assetPath = `hair/${this.hairType}/${this.faceType}/${this.favoriteColor}`; - } else { - // Regular hair types - assetPath = `${this.flipHair ? "hairflip" : "hair"}/${this.hairType}/${ - this.faceType - }/${hairColor}`; - } - - return this.studioAssetUrl(assetPath); - } - - public studioAssetUrlBeard(): string { - let facialHairColor = this.facialHairColor; - - if (this.facialHairColor === 0) { - facialHairColor = 8; - } - - return this.studioAssetUrl( - `beard/${this.beardType}/${this.faceType}/${facialHairColor}` - ); - } - - public studioAssetUrlMustache(): string { - let facialHairColor = this.facialHairColor; - - if (this.facialHairColor === 0) { - facialHairColor = 8; - } - - return this.studioAssetUrl( - `mustache/${this.mustacheType}/${facialHairColor}` - ); - } - - public studioAssetUrlGlasses(): string { - let glassesColor = 0; - - if (this.glassesColor == 0) { - glassesColor = 8; - } else if (this.glassesColor < 6) { - glassesColor = this.glassesColor + 13; - } - - return this.studioAssetUrl(`glass/${this.glassesType}/${glassesColor}`); - } - - public studioAssetUrlMole(): string { - return this.studioAssetUrl(`mole/${this.moleEnabled ? 1 : 0}`); - } - - public studioAssetUrl(assetPath: string): string { - this.validate(); - - const assetPathHash = MD5(assetPath); - const char0 = assetPathHash[0]; - const char1 = assetPathHash[1]; - const char2 = assetPathHash[2]; - const fileName = assetPathHash.substring(3, 12); - - return `${STUDIO_ASSET_URL_BASE}/${STUDIO_ASSET_FILE_TYPE}/1024/${char0}/${char1}/${char2}/${fileName}.${STUDIO_ASSET_FILE_TYPE}`; - } -} diff --git a/src/external/mii-js/util.ts b/src/external/mii-js/util.ts deleted file mode 100644 index ae25312..0000000 --- a/src/external/mii-js/util.ts +++ /dev/null @@ -1,22 +0,0 @@ -export default class Util { - public static inRange(val: number, range: number[]): boolean { - return range.includes(val); - } - - public static clamp(val: number, min: number, max?: number): number { - if (max === undefined) { - max = min; - min = 0; - } - - return Math.min(Math.max(val, min), max); - } - - public static range(start: number, end?: number): number[] { - if (end === undefined) { - end = start; - start = 0; - } - return Array.from({ length: end - start }, (_, i) => i + start); - } -} diff --git a/src/external/mii-selector/selector.js b/src/external/mii-selector/selector.js new file mode 100644 index 0000000..3d5e9e0 --- /dev/null +++ b/src/external/mii-selector/selector.js @@ -0,0 +1,987 @@ +//Assume the language is english +import { createMiiRender, getAdditionalInfoFromMii, Mii } from "../../helper"; +import { + miiIconFavorite, + miiIconPersonal, + miiIconSpecial, + MiiSelectorMiiType +} from "./selector_misc"; + +// This is David J.'s Mii Selector code courtesy of dwyazzo90, +// implemented into Mii Creator for inclusion with the Mii Creator JS API. + +function escapeHTML(str) { + return new Option(str).innerHTML; +} + +//PLEASE ADD LOCALIZATION PROPERLY, MAKE IT GENERAL AND NOT REGION BASED. +const lang = "es"; + +export var MiiSelector = { + loc: { + //No region localization, its just a few strings. + en: [ + "Select a Mii.", + "Guests", + "Cancel", + "Confirm", + "Search", + "Matches for:", + "results", + "No matches found.", + "Guest " + ], + es: [ + "Selecciona un Mii.", + "Invitados", + "Cancelar", + "Confirmar", + "Buscar", + "Resultados para:", + "resultados", + "No hay resultados.", + "Invitado " + ] + }, + /** + * @param {any[]} miiArray + * @param {any} selectorParam + * @returns + */ + open: async function (miiArray, selectorParam) { + return new Promise((resolve, reject) => { + if (selectorParam.personalMii) { + miiArray.unshift({ + miiData: selectorParam.personalMii, + type: MiiSelectorMiiType.Personal + }); + } + let guestMiis = []; + if (selectorParam.guestData) { + guestMiis.push( + ...selectorParam.guestData.map((guest, index) => { + let guestMii = new Mii(guest); + guestMii.nickname = getLoc(8) + String.fromCharCode(65 + index); + return { miiData: guestMii.export() }; + }) + ); + } + // test + miiArray.unshift(...guestMiis); + + function getLoc(index) { + return MiiSelector.loc[lang][index]; + } + + var check = document.querySelector("#mii-creator-selector-modal"); + if (check != null || check != undefined) { + check.remove(); + } + + var pages = 0; + var currentPage = 1; + //Preloading only if user has 100 or less miis + var canPreloadCharIcon = miiArray.length <= 100; + + console.log("canPreloadCharIcon: " + canPreloadCharIcon); + var selectedMii = null; + + //Check selector parameters + if (selectorParam) { + //user can specificy if disable preloading + //for performance reasons, i guess + if (selectorParam.preload === false) { + canPreloadCharIcon = false; + } + } + + miiArray.forEach((mii, index) => { + if (index % 10 === 0) { + pages++; + } + }); + + const container = + '
' + + '" + + "
"; + + document.body.insertAdjacentHTML("beforeend", container); + + //Check now is valid, good! + check = document.querySelector("#mii-creator-selector-modal"); + var selCont = check.querySelector(".selector"); + + var pagesEl = check.querySelector(".mii-page-counter span>span"); + var pagesCurEl = check.querySelector(".mii-page-counter span>b"); + pagesEl.innerText = "/ " + pages; + + var arrowLeft = check.querySelector(".prev"); + var arrowRight = check.querySelector(".next"); + var confirmButton = check.querySelector(".confirm"); + var cancelButton = check.querySelector(".cancel"); + var miiCoUser = check.querySelector( + ".mii-container:not(.transition):not(.guest)" + ); + var miiTrs = check.querySelector(".mii-container.transition"); + + if (pages > 1) { + arrowRight.style.display = "block"; + } + + const dataArray = []; + + //TO AVOID THE HUGE ASS LAG SPIKE AT THE BEGINNING! + if (canPreloadCharIcon) { + // Preload all Mii icons first + const iconPromises = miiArray.map((mii, index) => { + return new Promise(async (resolve) => { + const miiData = new Mii(mii.miiData); + const data = miiData.export("studioData"); + + const icon = await createMiiRender({ + data, + drawBody: true, + size: 124, + module: fflModule, + additionalInfo: getAdditionalInfoFromMii(miiData), + shaderType: "wiiu_blinn", + renderer, + bodyModelType: "low", + texResolution: 128, + type: 0 + }); + // const charModel = createCharModel(data, null, FFLShaderMaterial, fflModule); + + // initCharModelTextures(charModel, renderer); + // const icon = createCharModelIcon(charModel, renderer, ViewType.MakeIcon, 200, 200); + + var iconURL = URL.createObjectURL(icon.result); + + // charModel.dispose(); + resolve({ img: iconURL, name: miiData.nickname, type: mii.type }); + }); + }); + + Promise.all(iconPromises).then(async (icons) => { + console.log("REAL"); + icons.forEach((e) => dataArray.push(e)); + fillMiiContainer(miiArray, currentPage).then((data) => { + miiCoUser.innerHTML = data; + selCont.style.display = "block"; + updateMiiListener(); + initButtonListener(); + }); + }); + } else { + fillMiiContainer(miiArray, currentPage).then((data) => { + miiCoUser.innerHTML = data; + selCont.style.display = "block"; + updateMiiListener(); + initButtonListener(); + }); + } + + async function fillMiiContainer(miiArray, page) { + console.log(page); + + const miisPerPage = 10; + const startIndex = (page - 1) * miisPerPage; + const selectedMiis = miiArray.slice( + startIndex, + startIndex + miisPerPage + ); // Get only the Miis for this page + + if (canPreloadCharIcon) { + // Use preloaded icons + var pageData = dataArray.slice(startIndex, startIndex + miisPerPage); + } else { + // Clear array and generate icons dynamically + dataArray.length = 0; // Empty the array + + var pageDataPromises = selectedMiis.map((mii) => { + return new Promise(async (resolve) => { + const miiData = new Mii(mii.miiData); + const data = miiData.export("studioData"); + + const icon = await createMiiRender({ + data, + drawBody: true, + size: 124, + module: fflModule, + additionalInfo: getAdditionalInfoFromMii(miiData), + shaderType: "wiiu_blinn", + renderer, + bodyModelType: "low", + texResolution: 128, + type: 0 + }); + + var iconURL = URL.createObjectURL(icon.result); + // const charModel = createCharModel(data, null, FFLShaderMaterial, fflModule); + + // initCharModelTextures(charModel, renderer); + // const icon = createCharModelIcon(charModel, renderer, ViewType.MakeIcon, 200, 200); + const miiPageData = { + img: iconURL, + name: miiData.nickname, + type: mii.type + }; + dataArray.push(miiPageData); + + // charModel.dispose(); + return resolve(miiPageData); + }); + }); + console.log("page data promises list", pageDataPromises); + + pageData = await Promise.all(pageDataPromises); + console.log("page data overwrite promises", pageData); + } + + // Fill with empty placeholders if less than 10 Miis + while (pageData.length < miisPerPage) { + pageData.push({ img: "", name: "" }); + } + + // Map to HTML with conditional data-mii-index attribute + return pageData + .map((mii, i) => { + const overallIndex = startIndex + i; + const dataAttr = + mii.img && mii.name ? ` data-mii-index="${overallIndex}"` : ""; + + let icon = ""; + switch (mii.type) { + case MiiSelectorMiiType.Favorite: + icon = miiIconFavorite; + break; + case MiiSelectorMiiType.Special: + icon = miiIconSpecial; + break; + case MiiSelectorMiiType.Personal: + icon = miiIconPersonal; + break; + } + + return ( + `
` + + (mii.img ? `` : "") + + (mii.name + ? `

${icon}${escapeHTML( + mii.name + )}

` + : "") + + `
` + ); + }) + .join(""); + } + + function miiSelect(el) { + var target = el; + + if (el.classList.contains("selected")) { + return; + } + + check.querySelectorAll(".mii").forEach((mii) => { + mii.classList.remove("selected"); + mii.querySelectorAll("p").forEach((m) => { + m.style.display = "none"; + }); + }); + + target.classList.add("selected"); + + if (target.hasAttribute("data-mii-index")) { + selectedMii = { + index: target.getAttribute("data-mii-index"), + data: miiArray[parseInt(target.getAttribute("data-mii-index"))] + }; + + console.log(selectedMii); + + target.querySelector("p").style.display = ""; + confirmButton.disabled = false; + } else { + selectedMii = null; + confirmButton.disabled = true; + } + + if (selectorParam.soundManager) { + selectorParam.soundManager.playSound("3ds_mii_selector_select"); + } + } + + function updateMiiListener() { + check.querySelectorAll(".mii").forEach(function (mii) { + mii.addEventListener("click", function (event) { + miiSelect(this); + }); + mii.addEventListener("focus", function (event) { + miiSelect(this); + }); + }); + } + + function initButtonListener() { + arrowRight.addEventListener("click", function () { + lockArrowsForNation(); + miiCoUser.classList.add("slideleft"); + miiTrs.style.display = ""; + miiTrs.classList.add("slideleftb"); + + miiTrs.addEventListener( + "animationend", + function onAnimationEnd() { + miiTrs.removeEventListener("animationend", onAnimationEnd); + + setTimeout(function () { + miiCoUser.classList.remove("slideleft"); + miiTrs.classList.remove("slideleftb"); + miiTrs.style.display = "none"; + miiCoUser.innerHTML = ""; + currentPage++; + fillMiiContainer(miiArray, currentPage).then((data) => { + miiCoUser.innerHTML = data; + + updateMiiListener(); + pagesCurEl.innerText = currentPage; + doTrioAtPaginEnd(); + }); + }, 0); + }, + { once: true } + ); + }); + + arrowLeft.addEventListener("click", function () { + lockArrowsForNation(); + miiCoUser.classList.add("slideright"); + miiTrs.style.display = ""; + miiTrs.classList.add("sliderightb"); + + miiTrs.addEventListener( + "animationend", + function onAnimationEnd() { + miiTrs.removeEventListener("animationend", onAnimationEnd); + + setTimeout(function () { + miiCoUser.classList.remove("slideright"); + miiTrs.classList.remove("sliderightb"); + miiTrs.style.display = "none"; + miiCoUser.innerHTML = ""; + currentPage--; + fillMiiContainer(miiArray, currentPage).then((data) => { + miiCoUser.innerHTML = data; + updateMiiListener(); + pagesCurEl.innerText = currentPage; + doTrioAtPaginEnd(); + }); + }, 0); + }, + { once: true } + ); + }); + + confirmButton.addEventListener("click", function onConfirm() { + console.log("Confirm"); + if (selectorParam.soundManager) { + selectorParam.soundManager.playSound("3ds_mii_selector_confirm"); + } + check.style.pointerEvents = "none"; + + confirmButton.removeEventListener("click", onConfirm); + selCont.classList.add("finish"); + + selCont.addEventListener( + "animationend", + function onAnimationEnd() { + selCont.removeEventListener("animationend", onAnimationEnd); + setTimeout(function () { + check.remove(); + // document.removeEventListener("keydown", MiiSelector.onKeyDown); + // document.removeEventListener("keyup", MiiSelector.onKeyUp); + if (selectedMii != null) { + resolve({ mii: selectedMii.data }); + } else { + reject("User hasnt selected Mii"); + } + }, 0); + }, + { once: true } + ); + }); + + cancelButton.addEventListener("click", function onCancel() { + check.style.pointerEvents = "none"; + cancelButton.removeEventListener("click", onCancel); + selCont.classList.add("finish"); + + if (selectorParam.soundManager) { + selectorParam.soundManager.playSound("3ds_mii_selector_cancel"); + } + + selCont.addEventListener( + "animationend", + function onAnimationEnd() { + selCont.removeEventListener("animationend", onAnimationEnd); + setTimeout(function () { + check.remove(); + // document.removeEventListener("keydown", MiiSelector.onKeyDown); + // document.removeEventListener("keyup", MiiSelector.onKeyUp); + reject("No Mii data selected by user."); + }, 0); + }, + { once: true } + ); + }); + } + + function doTrioAtPaginEnd() { + //Sorry for the timeout it fixes it + ifSelectedMiiRestore(); + updateArrowsForNation(); + unlockArrowsForNation(); + } + + function updateArrowsForNation() { + // Hide/show arrows based on the current page + if (currentPage === pages) { + arrowRight.style.display = "none"; // Hide right arrow on the last page + arrowLeft.style.display = ""; // Show left arrow + } else if (currentPage === 1) { + arrowLeft.style.display = "none"; // Hide left arrow on the first page + arrowRight.style.display = ""; // Show right arrow + } else { + arrowLeft.style.display = ""; // Show both arrows for middle pages + arrowRight.style.display = ""; + } + } + + function ifSelectedMiiRestore() { + if ( + selectedMii != null && + check.querySelector( + '.mii[data-mii-index="' + selectedMii.index + '"]' + ) && + selectedMii.index + ) { + check + .querySelector('.mii[data-mii-index="' + selectedMii.index + '"]') + .classList.add("selected"); + check + .querySelector('.mii[data-mii-index="' + selectedMii.index + '"]') + .querySelector("p").style.display = ""; + check + .querySelector('.mii[data-mii-index="' + selectedMii.index + '"]') + .focus(); + } + } + + function lockArrowsForNation() { + if (selectorParam.soundManager) { + selectorParam.soundManager.playSound("3ds_mii_selector_page"); + } + arrowRight.disabled = true; + arrowLeft.disabled = true; + arrowLeft.style.opacity = "0.5"; + arrowLeft.style.filter = "grayscale(100%)"; + arrowRight.style.opacity = "0.5"; + arrowRight.style.filter = "grayscale(100%)"; + } + + function unlockArrowsForNation() { + arrowLeft.style.opacity = "1"; + arrowLeft.style.filter = "none"; + arrowRight.style.opacity = "1"; + arrowRight.style.filter = "none"; + arrowRight.disabled = false; + arrowLeft.disabled = false; + } + }); + } +}; + +export function miiSelectorSetFflModule(module) { + fflModule = module; +} +export function miiSelectorSetRenderer(r) { + renderer = r; +} + +//This shows an example of what the raw MiiSelector.open Function expects (Feel free to change, its just for demo purposes) +export var MiiExampleArray = [ + { + miiData: + "AwEAIE4vaoCzgYpzgN8ZmnGioS4CKAAAAVxtAGkAbQBvAAAAAAAAAAAAAAAAAEBAEhA8ABhoYxw3NEYUJBYZJg0AACmDYkhQbQBpAG0AbwAAAAAAAAAAAAAAAAAAAIZa" + }, + { + miiData: + "AwEAMBs8xqsHR9PC3MXz5YXEaBemLwAAVllEAGEAdgBpAGQAIABKAG8AYQBxAE0wABBXAAJoRBgTZEUUgRIZZg4AACkAaGdQYgBpAGcAIABzAGEAbAB0AHkAAAAAALpc" + }, + { + miiData: + "AwEAMHpnKmJS2hyMmWzpBSwQwXjnewAAV10GJkQAYQBuAGkAAAAAAAAAAAAAAEM5AJhlBR1pRBogNWQQRhKZZg4AACnTUiVNbwB3AG8AAAAAAAAAAAAAAAAAAAAAAGUR" + }, + { + miiData: + "AwEAIDVEgCveHCqDgP9wmbYmSnvSxQAAAQBEAGEAbgBpAAAAAAAAAAAAAAAAADs3AgBVCx1pRBpANEUURhIPxA4AAClTWsNEAAAAAAAAAAAAAAAAAAAAAAAAAAAAALVb" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMEMonKDqgr79gP9wmedgoZvvAgAAABhCAGkAZwAgAEYAYQB0ACAARgB1AEBARpAkBlJoQxjSNEYUhBIRaA0AMCkgUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAANtQ" + }, + { + miiData: + "AwEAMOFEOFJOyk8wgP9wmffiR6e5GwAAASRpACAAYQBtACAAcwB0AGUAdgBlAEBAAAQCBchoQxipNEcUYBIjaA0AKCkwUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMe4" + }, + { + miiData: + "AwEAMCT6d7wwhGkPgP9wmYg62JEwZgAAASRXAEEAUwBIAEMATwBPAEMASABJAEBAAJAyDx5pRBrqNEYWaxQCaQ4AOC0gWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM8Z" + }, + { + miiData: + "AwEAMIZ+TgOPLn3egP9wmYebz4QHawAAAQBmAHUAYwBrAG4AIABjAHUAbgB0AEBAFDAGCwdoRBhjNEcSYBICaQ0AGClTUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADB6" + }, + { + miiData: + "AwEAMN4cKEquh8u9gP9wmaTiJXkY+AAAASxXAFcAVwBXAFcAVwBXAFcAVwBXAEBAImACB3toQxrtNEUWYBRRaA4AOC1AWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMUM" + }, + { + miiData: + "AwEAMN4cKEquh8u9gP9wmaTiJXkY+AAAASxXAFcAVwBXAFcAVwBXAFcAVwBXAEBAImACB3toQxrtNEUWYBRRaA4AOC1AWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMUM" + }, + { + miiData: + "AwEAMN4cKEquh8u9gP9wmaTiJXkY+AAAASxXAFcAVwBXAFcAVwBXAFcAVwBXAEBAImACB3toQxrtNEUWYBRRaA4AOC1AWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMUM" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMEMonKDqgr79gP9wmedgoZvvAgAAABhCAGkAZwAgAEYAYQB0ACAARgB1AEBARpAkBlJoQxjSNEYUhBIRaA0AMCkgUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAANtQ" + }, + { + miiData: + "AwEAMOFEOFJOyk8wgP9wmffiR6e5GwAAASRpACAAYQBtACAAcwB0AGUAdgBlAEBAAAQCBchoQxipNEcUYBIjaA0AKCkwUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMe4" + }, + { + miiData: + "AwEAMCT6d7wwhGkPgP9wmYg62JEwZgAAASRXAEEAUwBIAEMATwBPAEMASABJAEBAAJAyDx5pRBrqNEYWaxQCaQ4AOC0gWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM8Z" + }, + { + miiData: + "AwEAMIZ+TgOPLn3egP9wmYebz4QHawAAAQBmAHUAYwBrAG4AIABjAHUAbgB0AEBAFDAGCwdoRBhjNEcSYBICaQ0AGClTUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADB6" + }, + { + miiData: + "AwEAMN4cKEquh8u9gP9wmaTiJXkY+AAAASxXAFcAVwBXAFcAVwBXAFcAVwBXAEBAImACB3toQxrtNEUWYBRRaA4AOC1AWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMUM" + }, + { + miiData: + "AwEAMNP+ZeK58uHykq9hUiwQwQO+iQAAAVxmAGIAagBuAAAAAAAAAAAAAAAAAH8AAgCAARRrRBggNEYUgRKBaA0AACkFUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADbS" + }, + { + miiData: + "AwEAIE4vaoCzgYpzgN8ZmnGioS4CKAAAAVxtAGkAbQBvAAAAAAAAAAAAAAAAAEBAEhA8ABhoYxw3NEYUJBYZJg0AACmDYkhQbQBpAG0AbwAAAAAAAAAAAAAAAAAAAIZa" + }, + { + miiData: + "AwEAMBs8xqsHR9PC3MXz5YXEaBemLwAAVllEAGEAdgBpAGQAIABKAG8AYQBxAE0wABBXAAJoRBgTZEUUgRIZZg4AACkAaGdQYgBpAGcAIABzAGEAbAB0AHkAAAAAALpc" + }, + { + miiData: + "AwEAMHpnKmJS2hyMmWzpBSwQwXjnewAAV10GJkQAYQBuAGkAAAAAAAAAAAAAAEM5AJhlBR1pRBogNWQQRhKZZg4AACnTUiVNbwB3AG8AAAAAAAAAAAAAAAAAAAAAAGUR" + }, + { + miiData: + "AwEAIDVEgCveHCqDgP9wmbYmSnvSxQAAAQBEAGEAbgBpAAAAAAAAAAAAAAAAADs3AgBVCx1pRBpANEUURhIPxA4AAClTWsNEAAAAAAAAAAAAAAAAAAAAAAAAAAAAALVb" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMEMonKDqgr79gP9wmedgoZvvAgAAABhCAGkAZwAgAEYAYQB0ACAARgB1AEBARpAkBlJoQxjSNEYUhBIRaA0AMCkgUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAANtQ" + }, + { + miiData: + "AwEAMOFEOFJOyk8wgP9wmffiR6e5GwAAASRpACAAYQBtACAAcwB0AGUAdgBlAEBAAAQCBchoQxipNEcUYBIjaA0AKCkwUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMe4" + }, + { + miiData: + "AwEAMCT6d7wwhGkPgP9wmYg62JEwZgAAASRXAEEAUwBIAEMATwBPAEMASABJAEBAAJAyDx5pRBrqNEYWaxQCaQ4AOC0gWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM8Z" + }, + { + miiData: + "AwEAMIZ+TgOPLn3egP9wmYebz4QHawAAAQBmAHUAYwBrAG4AIABjAHUAbgB0AEBAFDAGCwdoRBhjNEcSYBICaQ0AGClTUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADB6" + }, + { + miiData: + "AwEAMN4cKEquh8u9gP9wmaTiJXkY+AAAASxXAFcAVwBXAFcAVwBXAFcAVwBXAEBAImACB3toQxrtNEUWYBRRaA4AOC1AWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMUM" + }, + { + miiData: + "AwEAMNP+ZeK58uHykq9hUiwQwQO+iQAAAVxmAGIAagBuAAAAAAAAAAAAAAAAAH8AAgCAARRrRBggNEYUgRKBaA0AACkFUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADbS" + }, + { + miiData: + "AwEAIE4vaoCzgYpzgN8ZmnGioS4CKAAAAVxtAGkAbQBvAAAAAAAAAAAAAAAAAEBAEhA8ABhoYxw3NEYUJBYZJg0AACmDYkhQbQBpAG0AbwAAAAAAAAAAAAAAAAAAAIZa" + }, + { + miiData: + "AwEAMBs8xqsHR9PC3MXz5YXEaBemLwAAVllEAGEAdgBpAGQAIABKAG8AYQBxAE0wABBXAAJoRBgTZEUUgRIZZg4AACkAaGdQYgBpAGcAIABzAGEAbAB0AHkAAAAAALpc" + }, + { + miiData: + "AwEAMHpnKmJS2hyMmWzpBSwQwXjnewAAV10GJkQAYQBuAGkAAAAAAAAAAAAAAEM5AJhlBR1pRBogNWQQRhKZZg4AACnTUiVNbwB3AG8AAAAAAAAAAAAAAAAAAAAAAGUR" + }, + { + miiData: + "AwEAIDVEgCveHCqDgP9wmbYmSnvSxQAAAQBEAGEAbgBpAAAAAAAAAAAAAAAAADs3AgBVCx1pRBpANEUURhIPxA4AAClTWsNEAAAAAAAAAAAAAAAAAAAAAAAAAAAAALVb" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMEMonKDqgr79gP9wmedgoZvvAgAAABhCAGkAZwAgAEYAYQB0ACAARgB1AEBARpAkBlJoQxjSNEYUhBIRaA0AMCkgUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAANtQ" + }, + { + miiData: + "AwEAMCT6d7wwhGkPgP9wmYg62JEwZgAAASRXAEEAUwBIAEMATwBPAEMASABJAEBAAJAyDx5pRBrqNEYWaxQCaQ4AOC0gWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM8Z" + }, + { + miiData: + "AwEAMIZ+TgOPLn3egP9wmYebz4QHawAAAQBmAHUAYwBrAG4AIABjAHUAbgB0AEBAFDAGCwdoRBhjNEcSYBICaQ0AGClTUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADB6" + }, + { + miiData: + "AwEAMN4cKEquh8u9gP9wmaTiJXkY+AAAASxXAFcAVwBXAFcAVwBXAFcAVwBXAEBAImACB3toQxrtNEUWYBRRaA4AOC1AWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMUM" + }, + { + miiData: + "AwEAMNP+ZeK58uHykq9hUiwQwQO+iQAAAVxmAGIAagBuAAAAAAAAAAAAAAAAAH8AAgCAARRrRBggNEYUgRKBaA0AACkFUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADbS" + }, + { + miiData: + "AwEAMCT6d7wwhGkPgP9wmYg62JEwZgAAASRXAEEAUwBIAEMATwBPAEMASABJAEBAAJAyDx5pRBrqNEYWaxQCaQ4AOC0gWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM8Z" + }, + { + miiData: + "AwEAMIZ+TgOPLn3egP9wmYebz4QHawAAAQBmAHUAYwBrAG4AIABjAHUAbgB0AEBAFDAGCwdoRBhjNEcSYBICaQ0AGClTUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADB6" + }, + { + miiData: + "AwEAMN4cKEquh8u9gP9wmaTiJXkY+AAAASxXAFcAVwBXAFcAVwBXAFcAVwBXAEBAImACB3toQxrtNEUWYBRRaA4AOC1AWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMUM" + }, + { + miiData: + "AwEAMNP+ZeK58uHykq9hUiwQwQO+iQAAAVxmAGIAagBuAAAAAAAAAAAAAAAAAH8AAgCAARRrRBggNEYUgRKBaA0AACkFUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADbS" + }, + { + miiData: + "AwEAIE4vaoCzgYpzgN8ZmnGioS4CKAAAAVxtAGkAbQBvAAAAAAAAAAAAAAAAAEBAEhA8ABhoYxw3NEYUJBYZJg0AACmDYkhQbQBpAG0AbwAAAAAAAAAAAAAAAAAAAIZa" + }, + { + miiData: + "AwEAMBs8xqsHR9PC3MXz5YXEaBemLwAAVllEAGEAdgBpAGQAIABKAG8AYQBxAE0wABBXAAJoRBgTZEUUgRIZZg4AACkAaGdQYgBpAGcAIABzAGEAbAB0AHkAAAAAALpc" + }, + { + miiData: + "AwEAMHpnKmJS2hyMmWzpBSwQwXjnewAAV10GJkQAYQBuAGkAAAAAAAAAAAAAAEM5AJhlBR1pRBogNWQQRhKZZg4AACnTUiVNbwB3AG8AAAAAAAAAAAAAAAAAAAAAAGUR" + }, + { + miiData: + "AwEAIDVEgCveHCqDgP9wmbYmSnvSxQAAAQBEAGEAbgBpAAAAAAAAAAAAAAAAADs3AgBVCx1pRBpANEUURhIPxA4AAClTWsNEAAAAAAAAAAAAAAAAAAAAAAAAAAAAALVb" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMEMonKDqgr79gP9wmedgoZvvAgAAABhCAGkAZwAgAEYAYQB0ACAARgB1AEBARpAkBlJoQxjSNEYUhBIRaA0AMCkgUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAANtQ" + }, + { + miiData: + "AwEAMOFEOFJOyk8wgP9wmffiR6e5GwAAASRpACAAYQBtACAAcwB0AGUAdgBlAEBAAAQCBchoQxipNEcUYBIjaA0AKCkwUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMe4" + }, + { + miiData: + "AwEAMCT6d7wwhGkPgP9wmYg62JEwZgAAASRXAEEAUwBIAEMATwBPAEMASABJAEBAAJAyDx5pRBrqNEYWaxQCaQ4AOC0gWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM8Z" + }, + { + miiData: + "AwEAMIZ+TgOPLn3egP9wmYebz4QHawAAAQBmAHUAYwBrAG4AIABjAHUAbgB0AEBAFDAGCwdoRBhjNEcSYBICaQ0AGClTUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADB6" + }, + { + miiData: + "AwEAMN4cKEquh8u9gP9wmaTiJXkY+AAAASxXAFcAVwBXAFcAVwBXAFcAVwBXAEBAImACB3toQxrtNEUWYBRRaA4AOC1AWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMUM" + }, + { + miiData: + "AwEAMNP+ZeK58uHykq9hUiwQwQO+iQAAAVxmAGIAagBuAAAAAAAAAAAAAAAAAH8AAgCAARRrRBggNEYUgRKBaA0AACkFUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADbS" + }, + { + miiData: + "AwEAIE4vaoCzgYpzgN8ZmnGioS4CKAAAAVxtAGkAbQBvAAAAAAAAAAAAAAAAAEBAEhA8ABhoYxw3NEYUJBYZJg0AACmDYkhQbQBpAG0AbwAAAAAAAAAAAAAAAAAAAIZa" + }, + { + miiData: + "AwEAMBs8xqsHR9PC3MXz5YXEaBemLwAAVllEAGEAdgBpAGQAIABKAG8AYQBxAE0wABBXAAJoRBgTZEUUgRIZZg4AACkAaGdQYgBpAGcAIABzAGEAbAB0AHkAAAAAALpc" + }, + { + miiData: + "AwEAMHpnKmJS2hyMmWzpBSwQwXjnewAAV10GJkQAYQBuAGkAAAAAAAAAAAAAAEM5AJhlBR1pRBogNWQQRhKZZg4AACnTUiVNbwB3AG8AAAAAAAAAAAAAAAAAAAAAAGUR" + }, + { + miiData: + "AwEAIDVEgCveHCqDgP9wmbYmSnvSxQAAAQBEAGEAbgBpAAAAAAAAAAAAAAAAADs3AgBVCx1pRBpANEUURhIPxA4AAClTWsNEAAAAAAAAAAAAAAAAAAAAAAAAAAAAALVb" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMCRqeFYxdlD/gP9wmSoBKL7iNwAAARBBAG4AbgBpAGUAAAAAAAAAAAAAAEBAApAuDUxpRBoNNEUUbRSjaA4AAC0hWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADy9" + }, + { + miiData: + "AwEAIBpSeGOa3Cm8gN8ZmsP6/intuwAAARRFAG0AaQBsAHkAAAAAAAAAAAAAAEBAAphUAztpQxghNGMQYRKBZg0AACnRUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAACLB" + }, + { + miiData: + "AwEAMG6DUOL5lfcpgP9wmWs/2Ob2SwAAAADhMKQwyTAgAKQw8zAgAO8w6jCqMEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQ4TCkMMkwIACkMPMwIADvMOowqjAAAM+R" + }, + { + miiData: + "AwEAMEMonKDqgr79gP9wmedgoZvvAgAAABhCAGkAZwAgAEYAYQB0ACAARgB1AEBARpAkBlJoQxjSNEYUhBIRaA0AMCkgUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAANtQ" + }, + { + miiData: + "AwEAMOFEOFJOyk8wgP9wmffiR6e5GwAAASRpACAAYQBtACAAcwB0AGUAdgBlAEBAAAQCBchoQxipNEcUYBIjaA0AKCkwUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMe4" + }, + { + miiData: + "AwEAMCT6d7wwhGkPgP9wmYg62JEwZgAAASRXAEEAUwBIAEMATwBPAEMASABJAEBAAJAyDx5pRBrqNEYWaxQCaQ4AOC0gWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM8Z" + }, + { + miiData: + "AwEAMIZ+TgOPLn3egP9wmYebz4QHawAAAQBmAHUAYwBrAG4AIABjAHUAbgB0AEBAFDAGCwdoRBhjNEcSYBICaQ0AGClTUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADB6" + }, + { + miiData: + "AwEAMN4cKEquh8u9gP9wmaTiJXkY+AAAASxXAFcAVwBXAFcAVwBXAFcAVwBXAEBAImACB3toQxrtNEUWYBRRaA4AOC1AWkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMUM" + }, + { + miiData: + "AwEAMNP+ZeK58uHykq9hUiwQwQO+iQAAAVxmAGIAagBuAAAAAAAAAAAAAAAAAH8AAgCAARRrRBggNEYUgRKBaA0AACkFUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAADbS" + } +]; + +// var renderer = new THREE.WebGLRenderer({ +// alpha: true // Needed for icons with transparent backgrounds. +// }); + +var fflModule; +var renderer; + +//Assuming HTML has loaded +//please wrap the selector in the Mii Creator JS module (for kat) +// document.addEventListener("DOMContentLoaded", async function () { + +// var init = await initializeFFLWithResource(window.ModuleFFL); + +// if (!init || !init.module) { +// throw new Error("FFL.js init error") +// } + +// fflModule = init.module; + +// document.querySelector("#testOpen").addEventListener("click", async function () { + +// try { +// var MiiResult = await MiiSelector.open(MiiExampleArray, { +// allowGuest: true, +// }) + +// console.log(MiiResult.mii); + +// } catch (e) { +// console.log(e) +// } + +// }) + +// }) diff --git a/src/external/mii-selector/selector_misc.ts b/src/external/mii-selector/selector_misc.ts new file mode 100644 index 0000000..57731a0 --- /dev/null +++ b/src/external/mii-selector/selector_misc.ts @@ -0,0 +1,489 @@ +export const css = /*css*/ `* { + font-family: 'nintendo_NTLG-DB_001' !important; + --default-selector-width: 750px; + --default-selector-height: 520px; +} + +#mii-creator-selector-modal *:focus-visible:not(.mii.selected:focus-visible){ + outline: none; + box-shadow: 0px 0px 0px 3px #00c6f6 !important; +} + +#mii-creator-selector-modal { + width: 100%; + height: 100%; + position: fixed; + top: 0; + left: 0; + display: flex; + background-color: rgba(0, 0, 0, 0.5); + justify-content: center; + align-items: center; + overflow: hidden; + line-height: 1.5; +} + +@keyframes slideUp { + 0% { + top: 100%; + } + 85% { + top: -3%; /* Slight overshoot */ + } + 95% { + top: 1%; /* Small bounce back */ + } + 100% { + top: 0%; /* Settle at final position */ + } +} + +@keyframes slideDown { + 0% { + top: 0%; + } + 85% { + top: 103%; /* Slight overshoot downward */ + } + 95% { + top: 99%; /* Small bounce back upward */ + } + 100% { + top: 100%; /* Settle at final position */ + } + } + + + +#mii-creator-selector-modal .selector { + width: var(--default-selector-width); + height: var(--default-selector-height); + background: #ecf8f0; + border-radius: 20px; + box-shadow: inset 0px 0px 8px 1px #00000063; + border: 2px solid #ecf8f0; + box-sizing: border-box; + position: relative; + animation: slideUp 0.55s ease-in-out; + overflow: hidden; +} + +#mii-creator-selector-modal .selector.finish { + animation: slideDown 0.55s ease-in-out forwards !important; +} + +#mii-creator-selector-modal .button-navi { + position: absolute; + margin-top: 135px; + top: 0; + width: 100%; + left: 0; +} + +#mii-creator-selector-modal .button-navi button { + height: 180px; + font-size: 40px; + text-shadow: 1px 2px #fff; + color: #141914; + width: 55px; + border: 1.5px solid #68776d; + cursor: pointer; + transition: 0.02s; + background: linear-gradient(#d3e1d3, #95aa95); +} + +#mii-creator-selector-modal .button-navi button:active:not(:disabled) { + text-shadow: 1px 2px #141914; + background: linear-gradient(#24402f, #7d937f); + color: #fff; + border-color: #3e5846; + width: 50px; +} + +#mii-creator-selector-modal .button-navi button.prev{ + position: absolute; + top: 0; + left: 0; + box-shadow: 2px 0px 3px 1px rgba(0, 0, 0, 0.30); + border-top-right-radius: 13px; + border-bottom-right-radius: 13px; + border-left: none; +} + +#mii-creator-selector-modal .button-navi button.next{ + position: absolute; + top: 0; + right: 0; + box-shadow: -2px 1px 3px 1px rgba(0, 0, 0, 0.30); + border-top-left-radius: 13px; + border-bottom-left-radius: 13px; + border-right: none; +} + +#mii-creator-selector-modal .selector>h1 { + text-align: center; + margin: 5px; + font-weight: normal; + font-size: 32px; +} + + +#mii-creator-selector-modal .selector .mii-container { + height: 60%; + background: #fff; + width: 90%; + box-shadow: 0px 0px 3px 1px #d5dbd6; + border-radius: 10px; + margin: auto; + margin-top: 25px; + display: flex; + align-content: center; + flex-wrap: wrap; + flex-direction: row; + justify-content: center; + left: 0px; + position: relative; +} + +#mii-creator-selector-modal .selector .mii-container.slideleft { + animation: slideLeft 0.25s ease-in forwards; +} + +#mii-creator-selector-modal .selector .mii-container.slideright { + animation: slideRight 0.25s ease-in forwards; +} + +#mii-creator-selector-modal .selector .mii-container.slideleftb { + animation: slideLeftB 0.25s ease-in forwards; +} + +#mii-creator-selector-modal .selector .mii-container.sliderightb { + animation: slideRightB 0.25s ease-in forwards; +} + +@keyframes slideLeft { + from { + left: 0%; + } + to { + left: -100%; + } +} + +@keyframes slideRight { + from { + left: 0%; + } + to { + left: 100%; + } +} + +@keyframes slideLeftB { + from { + left: 100%; + } + to { + left: 0%; + } +} + +@keyframes slideRightB { + from { + left: -100%; + } + to { + left: 0%; + } +} + +#mii-creator-selector-modal .selector .mii-container.guest { + padding-left: 32%; + box-sizing: border-box; +} + +#mii-creator-selector-modal .selector .mii-container.transition { + top: -60%; + left: 100%; + margin-top: 0; +} + +#mii-creator-selector-modal .selector .mii-container.guest .guest-label{ + width: 230px; + height: 280px; + text-align: center; + display: flex +; + background: #e2f3e0; + border-radius: 10px; + position: absolute; + left: 0; + top: auto; + margin-top: 15px; + margin-left: 55px; + color: #505050; + justify-content: center; + font-size: 30px; + align-items: center; +} + +#mii-creator-selector-modal .selector .mii-page-counter { + margin-top: 15px; + margin-right: 30px; + position: absolute; + right: 0; + top: 75%; + z-index: 5; + width: auto; + padding: 0px 20px; + border-radius: 8px; + font-size: 28px; + box-shadow: -2px -2px 3px 1px rgba(255, 255, 255, 0.80) inset, 1px 1px 3px 1px rgb(0 0 0 / 22%) inset, 0px 0px 0px 1px rgb(0 0 0 / 33%); + text-align: center; + background: rgba(0, 0, 0, 0.10); +} + +#mii-creator-selector-modal .selector .mii-page-counter>span>b{ + color: #0096ff; + font-weight: normal; + padding: 0px 12px; +} + +#mii-creator-selector-modal .selector .mii-container .mii { + width: 110px; + margin: 5px; + background: #e6f0e8; + height: 130px; + border: 3.5px solid #a0ad9e; + border-radius: 10px; + position: relative; + cursor: pointer; +} + +#mii-creator-selector-modal .selector .mii-container .mii:focus-visible { + outline: none; +} + +#mii-creator-selector-modal .selector .mii-container .mii.selected { + border-color: #ffaf31; + animation: glow 0.1s forwards ease-in-out; + background: #fbbeaa; +} + +@keyframes glow{ + 0% { + box-shadow: 1px 1px 4px #ffaf31 inset, 0px 0px 2px 0px #e5910f, inset 0px 0px 2px 2px #f2980a; + } + 50% { + box-shadow: 1px 1px 4px #ffaf31 inset, 0px 0px 6px 2px #e5910f, inset 0px 0px 2px 2px #f2980a; + } + 100% { + box-shadow: 1px 1px 4px #ffaf31 inset, 0px 0px 4px 1px #e5910f, inset 0px 0px 2px 2px #f2980a, inset 0px 0px 6px 2px #00000043; + } +} + +#mii-creator-selector-modal .selector .mii-container .mii>img { + /* width: 120px; */ + position: absolute; + /* left: -5px; */ + bottom: 0; + pointer-events: none; + -webkit-tap-highlight-color: transparent; + -webkit-user-drag: none; + user-select: none; + outline: none; + animation: fadeIn 0.15s ease-in-out forwards; + transform: translate(-50%, 0); + width: 100%; + height: 100%; + left: 50%; + object-fit: cover; +} + +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +#mii-creator-selector-modal .selector .mii-container .mii>p svg { + width: 36px; + height: 36px; +} +#mii-creator-selector-modal .selector .mii-container .mii>p { + display: flex; + justify-content: center; + align-items: center; + gap: 8px; + position: absolute; + top: -35px; + left: 50%; + transform: translateX(-50%); + margin: auto; + border-radius: 5px; + width: auto; + white-space: nowrap; + font-size: 28px; + min-width: 100px; + padding: 3px 16px; + z-index: 10; + box-shadow: 0px 0px 1px 1.5px #9e9e9e, inset 0px 0px 5px 0px #afafaf; + background: #fff; + -webkit-user-drag: none; + user-select: none; + z-index: 10; + + color:#233f2e; +} + +#mii-creator-selector-modal .selector .mii-container .mii>p::before { + content: ""; + background-image: url("data:image/svg+xml,%3Csvg width='9' height='11' viewBox='0 0 9 11' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0.5 11L4.5 2L8.5 11H0.5Z' fill='url(%23paint0_linear_1939_2)'/%3E%3Cpath d='M4.49997 3.23111L8 11H9L4.49997 0.76889L0 11H1L4.49997 3.23111Z' fill='%23A0A0A0'/%3E%3Cdefs%3E%3ClinearGradient id='paint0_linear_1939_2' x1='4.5' y1='2' x2='4.5' y2='11' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0.865385' stop-color='white'/%3E%3Cstop offset='1' stop-color='%23AFAFAF'/%3E%3C/linearGradient%3E%3C/defs%3E%3C/svg%3E"); + position: absolute; + width: 20px; + height: 24px; + background-size: cover; + left: 50%; + transform: translateX(-50%) rotate(180deg); + top: 100%; + z-index: -1; +} + +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(1)>p, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(6)>p { + left: -10%; + transform: none; +} + +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(5)>p, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(10)>p { + right: -10%; + left: auto; + transform: none; +} + + +/* +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(1)>p::before, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(6)>p::before { + top: -100% !important; + left: -10% !important; + width: 100%; + transform: translateY(100%) rotate(0deg) !important; + background-size: contain; + background-position: center; + background-repeat: no-repeat; +} +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(5)>p::before, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(10)>p::before { + top: -100% !important; + left: -9% !important; + width: 100%; + transform: translateY(100%) rotate(0deg) !important; + background-size: contain; + background-position: center; + background-repeat: no-repeat; +} + +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(5)>p::before { + top: 100% !important; + left: 50% !important; + transform: translateX(-57%) rotate(180deg) !important; +} +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(1)>p::before { + top: 100% !important; + left: 50% !important; + transform: translateX(-57%) rotate(180deg) !important; +} +*/ + +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(6)>p, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(7)>p, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(8)>p, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(9)>p, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(10)>p { + top: auto; + bottom: -33px; +} + +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(6)>p::before, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(7)>p::before, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(8)>p::before, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(9)>p::before, +#mii-creator-selector-modal .selector .mii-container .mii:nth-child(10)>p::before { + transform: translateX(-50%) translateY(100%); + top: -100%; +} + +#mii-creator-selector-modal .selector .button-container { + width: 100%; + position: absolute; + display: flex; + bottom: 0; + left: 0; + border-bottom-left-radius: 20px; + border-bottom-right-radius: 20px; + background: linear-gradient(#cfddcf, #889488); + flex-direction: row; + flex-wrap: nowrap; +} + +#mii-creator-selector-modal .selector .button-container button{ + width: 50%; + margin: 0; + padding: 0; + border: 0; + background: none; + text-shadow: 0px 2px #fff; + font-size: 29px; + height: 55px; + border-top: 2px solid #44524b; + box-sizing: border-box; + transition: 0.02s; + cursor: pointer; + + color: #141914; +} + +#mii-creator-selector-modal .selector .button-container button:active:not(:disabled){ + text-shadow: 0px -2px #fff; + background: linear-gradient(#879287, #bfd2bf); +} + +#mii-creator-selector-modal .selector .button-container button.cancel{ + border-right: 1.5px solid #54625a; + border-bottom-left-radius: 20px; +} + +#mii-creator-selector-modal .selector .button-container button.confirm{ + border-left: 1.5px solid #54625a; + border-bottom-right-radius: 20px; +} + +#mii-creator-selector-modal .selector .button-container button.confirm:disabled{ + pointer-events: none; + border-color: #aaaaaa; + background: #bebebe; + color: #adadad; + text-shadow: none; +} + +@media only screen and (max-width: 600px) { + #mii-creator-selector-modal .selector { + width: 90%; + } +}`; + +export const miiIconFavorite = ``; +export const miiIconSpecial = ``; +export const miiIconPersonal = ``; + +export enum MiiSelectorMiiType { + Regular, + Favorite, + Special, + Personal +} diff --git a/src/helper.d.ts b/src/helper.d.ts new file mode 100644 index 0000000..5af72fd --- /dev/null +++ b/src/helper.d.ts @@ -0,0 +1,45 @@ +import * as THREE from "three"; +import { createMiiRender, type RenderRequest } from "./util/IconRendering"; +import { CharModel, parseHexOrB64ToUint8Array } from "./external/ffl.js/ffl"; +import Mii from "./class/MiiData"; +import { dataToBase64, dataToHex } from "./util/dataConvert"; +import { ForbiddenShirtPantColors } from "./constants/ColorTables"; +import { ExtHatNameList } from "./constants/Extensions"; +import { BodyType, ShaderType } from "./constants/BodyShaderTypes"; +declare function getFFLModule(): any; +declare const getAdditionalDataFromMii: (miiData: Mii) => { + hatCommonColor: number; + hatFavoriteColor: number; + hatType: number; + pantsColor: number; + shirtColor: number; + favorite: number; + special: number; + temporary: number; + eyeSclera: number; +}; +declare function loadAssets(resourcePath: string): Promise; +interface CharModelRequest extends RenderRequest { + followShirtPantsColor: boolean; + shaderMaterial: string; +} +declare class MiiCreatorCharModel { + miiGroup: THREE.Group; + charModel: CharModel; + constructor(request: CharModelRequest); +} +export { + BodyType, + createMiiRender, + dataToBase64, + dataToHex, + ExtHatNameList, + ForbiddenShirtPantColors, + getAdditionalDataFromMii, + getFFLModule, + loadAssets, + Mii, + MiiCreatorCharModel, + parseHexOrB64ToUint8Array, + ShaderType +}; diff --git a/src/helper.ts b/src/helper.ts new file mode 100644 index 0000000..9229e12 --- /dev/null +++ b/src/helper.ts @@ -0,0 +1,387 @@ +import * as THREE from "three"; +import { + createMiiRender, + type RenderRequest, + type RenderRequestNonTemporaryResult +} from "./util/IconRendering"; +import { + loadBodyModels, + loadClothesTextures, + loadHatModels, + setRoot +} from "./util/ModelLoader"; +import { + CharModel, + initializeFFLWithResource, + parseHexOrB64ToUint8Array, + FFLiShapeType +} from "./external/ffl.js/ffl"; +import Mii from "./class/MiiData"; +import { dataToBase64, dataToHex } from "./util/dataConvert"; +import { ForbiddenShirtPantColors } from "./constants/ColorTables"; +import { ExtHatNameList } from "./constants/Extensions"; +import { BodyType, ShaderType } from "./constants/BodyShaderTypes"; +import Html from "@datkat21/html"; +import type { MiiCreatorAdditionalData } from "./util/MiiCreatorTypes.js"; +import { + MiiExampleArray, + MiiSelector, + miiSelectorSetFflModule, + miiSelectorSetRenderer +} from "./external/mii-selector/selector.js"; + +// if (this === undefined) { +// console.log("Running in module scope"); +// } else { +// console.log("Running in script scope"); +// } + +let FFLModule: any, + FFLWorker: Worker | undefined, + userData: any, + helperRenderer = new THREE.WebGLRenderer({ alpha: true }); + +// function log(...content: string[]) { +// console.debug("[miic helper]", ...content); +// } + +const GUEST_MII_DATA = [ + "BAM5i2G9mwPpOoAAAADs/4LSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEEAAAAAAAAACAAAAAAAQAMDCAYEBgIKCAQEAgIMBAAAAP8ABAAACAQACggARP///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAOFdPR8ZsuhdoAAAAHs/4LSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEIAAAAAAAAACAAAAAAAQAMDBgYEBgIKDAQEAgIMAAAAAP8ABQAACAQACgYAN////0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAM2I3afbKlshYAAAALs/4LSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEMAAAAAAAAACAAAAAAAQAMDAQYEBgIKCAQEAgIMAQAAAP8AAAAACAQACgEAIf///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAN9s2CERcxd8IAAAAPs/4LSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEQAAAAAAAAACAAAAAAAQAMDCAYEAAIKCAMEBAIMAgAAAP8AAgABCAQACggAGP///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAP3BYyHQ6gZsoAAAATs/4LSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEUAAAAAAAAACAAAAAAAQAMDBwYEAAIKDQMEBAIMAAAAAP8ABgABCAQACgcADv///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BANfFfqpycZfsoAAAAXs/4LSAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEYAAAAAAAAACAAAAAAAQAMDAQYEAAIKCAMEBAIMAAAAAP8ABwABCAQACgEADP///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + + "BAVIEyyDkVU1GYD/cJm7kTTHqf8AAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEcAAAAAAAAACAAAAAAAQAMDCAYEBgIKCAQEAgIMBQAAAP8ACwAACAQACggAKv///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAWUIlPmHJkY0oD/cJmB+j7p1g8AAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEgAAAAAAAAACAAAAAAAQAMDDgYEBgIKCQQEAgIMBwAAAP8ACQAACAQACg4APv///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BAVlJYmsV8fzIID/cJmJvGY0ejIAAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEkAAAAAAAAACAAAAAAAQAMDAwYEBgIKCAQEAgIMBgAAAP8AAQAACAQACgMAef///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BABEp+/5p6E6GoDfGZofZsl0BT8AAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEoAAAAAAAAACAAAAAAAQAMDCAYEAAIKCAMEBAIMCAAAAP8AAwABCAQACggAB////0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BABEp+/5p6E6GoDfGZofZsl0BT8AAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEsAAAAAAAAACAAAAAAAQAMDDgYEAAIKCwMEBAIMBwAAAP8ACgABCAQACg4AX////0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==", + "BABEp+/5p6E6GoDfGZofZsl0BT8AAAAAAAAAAAAAAAAAAAAAAAAAAEcAdQBlAHMAdAAgAEwAAAAAAAAACAAAAAAAQAMDBgYEAAIKCAMEBAIMBgAAAP8ACAABCAQACgYADP///0AABAACFAMTBBcNBAAKBAEJ//8A/wAAAA==" +]; + +function getFFLModule() { + return FFLModule; +} + +const getAdditionalInfoFromMii = (miiData: Mii) => + ({ + hatCommonColor: miiData.hatCommonColor, + hatFavoriteColor: miiData.hatFavoriteColor, + hatType: miiData.hatType, + pantsColor: miiData.pantsColor, + shirtColor: miiData.shirtColor, + favorite: miiData.favorite, + special: miiData.special, + temporary: miiData.temporary, + eyeSclera: miiData.eyeSclera, + clothesType: miiData.clothesType, + shoesColor: miiData.shoesColor, + wigType: miiData.wigType + }) as MiiCreatorAdditionalData; + +let root: URL; +try { + if (import.meta) { + root = new URL(import.meta.url); + } else { + throw new Error("HUH"); + } +} catch (e) { + alert("SCRIPT SCOPE"); +} + +let soundManager: SoundManager; + +async function loadAssets(resourcePath: string, bodyType: string = "wiiu") { + setRoot(root.origin + "/"); + console.debug("Loading body models.."); + await loadBodyModels(bodyType, true); + console.debug("Loading hat models.."); + await loadHatModels(); + console.debug("Loading clothing textures.."); + await loadClothesTextures(); + soundManager = new SoundManager(); + console.debug("Loading sounds."); + await loadBaseSounds( + root.origin + "/assets/audio/miiSelector.zip", + soundManager + ); + console.debug("Loaded all resources."); + + FFLModule = (await import("./external/ffl.js/ffl-emscripten.js")).default; + + FFLModule = await FFLModule({ + locateFile: (path: string) => { + return root.origin + "/dist/" + path; + } + }); + + let m = await initializeFFLWithResource(FFLModule, resourcePath); + FFLModule = m.module; + console.debug("Loaded FFL.js!"); +} + +interface CharModelRequest extends RenderRequest { + respectBodyColors: boolean; + useAnimation: boolean; +} + +class MiiCreatorCharModel { + // Entire group. + miiGroup!: THREE.Group; + // FFL CharModel. + charModel!: CharModel; + + // Only head part of group. + headModel!: THREE.Group; + // Only body part of group. + bodyModel!: THREE.Group; + // Body meshes + bodyModelBody!: THREE.Mesh; + bodyModelHands!: THREE.Mesh; + bodyModelLegs!: THREE.Mesh; + + mixer!: THREE.AnimationMixer; + clips!: Map; + + constructor() {} + + init(request: CharModelRequest): Promise { + return new Promise((resolve) => { + setTimeout(async () => { + const { + bodyModel, + bodyModelAnims, + bodyModelBody, + bodyModelHands, + bodyModelLegs, + charModel, + headModel, + miiGroup + } = (await createMiiRender({ + ...request, + module: FFLModule, + isTemporary: false, + renderer: request.renderer, + textureRenderer: helperRenderer, + clothingLinearColors: + request.clothingLinearColors === undefined + ? true + : request.clothingLinearColors + })) as any as RenderRequestNonTemporaryResult; + + this.bodyModel = bodyModel; + this.bodyModelBody = bodyModelBody; + this.bodyModelHands = bodyModelHands; + this.bodyModelLegs = bodyModelLegs; + this.charModel = charModel; + this.headModel = headModel; + this.miiGroup = miiGroup; + + if (request.useAnimation) { + this.mixer = new THREE.AnimationMixer(bodyModel); + this.clips = new Map(); + + for (const clip of bodyModelAnims!) { + this.clips.set(clip.name, this.mixer.clipAction(clip)); + } + } + + resolve(); + }, 0); + }); + } + + subPosition!: THREE.Vector3; + subScale!: THREE.Vector3; + position!: THREE.Vector3; + quaternion!: THREE.Quaternion; + scale!: THREE.Vector3; + + mixerUpdate(delta: number) { + // Extract the position and rotation from the matrix + if (!this.subPosition) this.subPosition = new THREE.Vector3(); + if (!this.subScale) this.subScale = new THREE.Vector3(); + if (!this.position) this.position = new THREE.Vector3(); + if (!this.quaternion) this.quaternion = new THREE.Quaternion(); + if (!this.scale) this.scale = new THREE.Vector3(); + this.mixer.update(delta); // <-- update animation + + // Force an update of all world matrices in the animated model + this.bodyModel.updateMatrixWorld(true); + + let headBone = this.bodyModel.getObjectByName("head") as THREE.Bone; + if (headBone === undefined) + headBone = this.bodyModel.getObjectByName("Head") as THREE.Bone; + + if (!headBone) return alert("???"); + headBone.updateMatrixWorld(true); + + this.miiGroup.getWorldPosition(this.subPosition); + headBone.matrixWorld.decompose(this.position, this.quaternion, this.scale); + + if (this.headModel) { + // Copy the head bone's world position + this.headModel.position.copy(this.position); + // Convert the head bone's world position to the group's local space + this.miiGroup.worldToLocal(this.headModel.position); + + // Set the head model's rotation from the head bone's quaternion + this.headModel.setRotationFromQuaternion(this.quaternion); + } + } + + setExpression(expression: number, force: boolean = false) { + if (force) { + this.headModel.traverse((n) => { + const m = n as THREE.Mesh; + if (!m.isMesh) return; + if (m.geometry.userData.modulateType !== FFLiShapeType.XLU_MASK) return; + (m.material as THREE.MeshBasicMaterial).map = + this.charModel._maskTargets[expression]!.texture; + }); + } else { + this.charModel.setExpression(expression); + } + } + + getExpressions() { + return this.charModel._maskTargets + .map((n, i) => (n !== null ? i : undefined)) + .filter((n) => n !== undefined); + } + + // TODO: dispose +} + +function centerPopupWindow(url: string, title: string, w: number, h: number) { + const left = screen.width / 2 - w / 2; + const top = screen.height / 2 - h / 2; + return window.open( + url, + title, + `width=${w}, height=${h}, top=${top}, left=${left}` + ); +} + +enum RequestType { + Library = "library", + PersonalMiiOnly = "personal_mii_only" +} + +function requestUserData(type: RequestType, pageTitle = document.title) { + return new Promise((resolve) => { + let append = new URLSearchParams(); + + switch (type) { + case RequestType.Library: + append.set("type", RequestType.Library); + append.set("page_title", pageTitle); + break; + case RequestType.PersonalMiiOnly: + append.set("type", RequestType.PersonalMiiOnly); + append.set("page_title", pageTitle); + break; + default: + throw new Error("Invalid request type."); + } + + centerPopupWindow( + root.origin + "/popup.html?" + append.toString(), + "Mii Creator Login", + 800, + 600 + ); + + const messageListener = (event: MessageEvent) => { + if (event.data === undefined) return; + if (event.data.type === undefined) return; + if (event.data.type !== "miic-auth-finalize") return; + if (event.data.canceled === true) + return resolve({ canceled: true, data: null }); + + window.removeEventListener("message", messageListener); + + userData = event.data.data; + resolve({ canceled: false, data: event.data.data }); + }; + + window.addEventListener("message", messageListener); + }); +} + +function injectCss() { + if (Html.qs("head>#mii-creator-helper-styles") === null) { + new Html("style") + .id("mii-creator-helper-styles") + .html(css) + .appendTo("head"); + } +} + +import { loadBaseSounds, SoundManager } from "./class/audio/SoundManager"; +import { css, MiiSelectorMiiType } from "./external/mii-selector/selector_misc"; + +function requestMiiSelection() { + console.log("userData:", userData); + return new Promise((resolve) => { + if (userData === undefined) return resolve(false); + if (userData.library === null) return resolve(false); + + injectCss(); + + new Html("div").id("mii-creator-selector-modal").appendTo("body"); + + miiSelectorSetFflModule(FFLModule); + miiSelectorSetRenderer(helperRenderer); + MiiSelector.open( + userData.library.map((n: any) => { + let type = MiiSelectorMiiType.Regular; + let mii = new Mii(n.mii); + + if (mii.favorite === 1) type = MiiSelectorMiiType.Favorite; + if (mii.special === 1) type = MiiSelectorMiiType.Special; + + return { miiData: mii.export(), type }; + }), + { + guestData: GUEST_MII_DATA, + soundManager, + personalMii: userData.personal_mii.data + } + ).then((MiiResult) => { + resolve(MiiResult); + }); + + // setTimeout(() => { + // resolve(true); + // }); + + // if (userData === undefined) return resolve(false); + // if (userData.personal_mii === null) return resolve(false); + // if (userData.library === null) return resolve(false); + }); +} + +export { + BodyType, + createMiiRender, + dataToBase64, + dataToHex, + ExtHatNameList, + ForbiddenShirtPantColors, + getAdditionalInfoFromMii, + getFFLModule, + GUEST_MII_DATA, + loadAssets, + Mii, + requestMiiSelection as miiSelect, + MiiCreatorCharModel, + parseHexOrB64ToUint8Array, + RequestType, + requestUserData, + ShaderType, + soundManager +}; diff --git a/src/i18n/template.pot b/src/i18n/template.pot new file mode 100644 index 0000000..610fb62 --- /dev/null +++ b/src/i18n/template.pot @@ -0,0 +1,1422 @@ +msgid "" +msgstr "" +"Content-Type: text/plain; charset=UTF-8\n" + +#. missing mii name +#: src/ui/pages/Library.ts:648 +msgid "?" +msgstr "" + +#: src/ui/pages/Settings.ts:311 +msgid "(Default)" +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:51 +msgid "(Open the camera for more options)" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:100 +#: src/ui/pages/library/new/lookalike.ts:119 +#: src/ui/pages/library/new/lookalike.ts:125 +#: src/ui/pages/library/new/lookalike.ts:175 +#: src/ui/pages/library/new/lookalike.ts:197 +#: src/ui/pages/library/new/lookalike.ts:213 +msgid "(Random)" +msgstr "" + +#: src/ui/tabs/ExtClothes.ts:133 +#: src/ui/tabs/ExtClothes.ts:36 +#: src/ui/tabs/ExtClothes.ts:65 +#: src/ui/tabs/ExtClothes.ts:99 +#: src/ui/tabs/ExtHat.ts:35 +#: src/ui/tabs/ExtHat.ts:63 +#: src/ui/tabs/Eye.ts:92 +#: src/ui/tabs/Head.ts:93 +msgid "%1 is a CUSTOM property, and will not transfer to any other data formats." +msgstr "" + +#. mii custom render file name - e.g. 'Mii_custom_render_2025-03-06T14:40:20.310Z.png' +#: src/ui/pages/library/render/customRender.ts:624 +msgid "%1_custom_render_%2.png" +msgstr "" + +#. mii render (body) file name - e.g. 'Mii_render_body_2025-03-06T14:40:20.310Z.png' +#: src/ui/pages/library/render/renderPresets.ts:74 +msgid "%1_render_body_%2.png" +msgstr "" + +#. mii render (head only) file name - e.g. 'Mii_render_head_only_2025-03-06T14:40:20.310Z.png' +#: src/ui/pages/library/render/renderPresets.ts:90 +msgid "%1_render_head_only_%2.png" +msgstr "" + +#. mii render (head) file name - e.g. 'Mii_render_headshot_2025-03-06T14:40:20.310Z.png' +#: src/ui/pages/library/render/renderPresets.ts:58 +msgid "%1_render_headshot_%2.png" +msgstr "" + +#: src/util/SettingsHelper.ts:76 +msgid "2D" +msgstr "" + +#: src/util/SettingsHelper.ts:77 +msgid "3D" +msgstr "" + +#: src/ui/pages/library/render/renderMenu.ts:26 +msgid "" +"3D model download has been disabled due to some buggy normals exporting going on at the moment.\n" +"In the meantime, you can use Arian's Mii Renderer to get head models.\n" +"Sorry about that." +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:107 +msgid "3DS/Wii U QR Code" +msgstr "" + +#: src/ui/pages/Settings.ts:186 +msgid "A refresh is required to apply resource changes." +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:215 +msgid "Adult" +msgstr "" + +#. lookalike age dropdown +#: src/ui/pages/library/new/lookalike.ts:208 +msgid "Age" +msgstr "" + +#. Message used at the top of lookalike screen +#: src/ui/pages/library/new/lookalike.ts:67 +msgid "All of the options here are what Nintendo originally programmed in. Please let me know if you want more options added." +msgstr "" + +#: src/util/SettingsHelper.ts:56 +msgid "Allow using camera in QR scanner" +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:127 +msgid "" +"An error occurred when reading the data.\n" +"Please check the console for more information." +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:337 +msgid "Animation" +msgstr "" + +#: src/ui/pages/library/select.ts:127 +#: src/ui/pages/library/select.ts:189 +msgid "Are you sure you want to delete %1?" +msgstr "" + +#: src/ui/pages/Library.ts:690 +msgid "Are you sure you want to delete this Mii?" +msgstr "" + +#. Arian's name +#: src/ui/pages/Library.ts:820 +msgid "Arian" +msgstr "" + +#. skin tone asian +#: src/ui/pages/library/new/lookalike.ts:113 +msgid "Asian" +msgstr "" + +#. hair color reddish +#: src/ui/pages/library/new/lookalike.ts:138 +msgid "Auburn" +msgstr "" + +#. Kat21's name +#: src/ui/pages/Library.ts:810 +msgid "Austin☆²¹ / Kat21" +msgstr "" + +#: src/util/SettingsHelper.ts:40 +msgid "Auto-close custom render menu" +msgstr "" + +#: src/util/SettingsHelper.ts:48 +msgid "Auto-close QR scan menu" +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:45 +msgid "Back Camera (default)" +msgstr "" + +#: src/ui/tabs/FacialHair.ts:70 +msgid "Beard" +msgstr "" + +#. Current version string name ("Patch Update", "Minor Update", "Major Update") +#. __("Major Update"), +#: src/config.ts:72 +msgid "BETA" +msgstr "" + +#. skin tone black +#. hair color black +#: src/ui/pages/library/new/lookalike.ts:103 +#: src/ui/pages/library/new/lookalike.ts:128 +#: src/ui/pages/library/new/lookalike.ts:187 +#: src/ui/pages/library/new/lookalike.ts:198 +#: src/util/SettingsHelper.ts:169 +msgid "Black" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:181 +#: src/ui/pages/library/new/lookalike.ts:202 +#: src/util/SettingsHelper.ts:168 +msgid "Blue" +msgstr "" + +#: src/util/SettingsHelper.ts:126 +msgid "Body Model" +msgstr "" + +#. hair color brown +#: src/ui/pages/library/new/lookalike.ts:133 +#: src/ui/pages/library/new/lookalike.ts:185 +#: src/ui/pages/library/new/lookalike.ts:200 +msgid "Brown" +msgstr "" + +#: src/ui/tabs/Scale.ts:47 +msgid "Build" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:172 +msgid "Camera" +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:85 +msgid "" +"Camera is disabled in settings.\n" +"\n" +"Upload an image:" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:218 +msgid "Center to body" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:221 +msgid "Center to head" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:194 +msgid "Center X" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:206 +msgid "Center Y" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:293 +msgid "Change the Body Model option in Settings to get many different options of poses!" +msgstr "" + +#: src/util/SettingsHelper.ts:109 +msgid "Change the lighting used in icons, renders and the editor." +msgstr "" + +#: src/util/SettingsHelper.ts:73 +msgid "Changes the default edit mode option." +msgstr "" + +#: src/ui/pages/Library.ts:769 +msgid "Check out the people behind Mii Creator!" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:214 +msgid "Child" +msgstr "" + +#: src/util/SettingsHelper.ts:180 +msgid "Choose" +msgstr "" + +#: src/ui/pages/library/export.ts:55 +msgid "Choose a file type to download" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:176 +#: src/ui/pages/library/new/lookalike.ts:28 +msgid "Choose a look-alike" +msgstr "" + +#: src/ui/pages/Library.ts:292 +msgid "Choose a Mii to be your Personal Mii, which can be used across apps. This can always be changed later in Settings." +msgstr "" + +#: src/ui/pages/library/render/renderPresets.ts:45 +msgid "Choose a way to render this Mii" +msgstr "" + +#. lookalike revise screen message +#: src/ui/pages/library/new/lookalike.ts:284 +msgid "Click any to reroll" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:302 +msgid "Click here" +msgstr "" + +#: src/ui/pages/library/export.ts:173 +msgid "Click inside a code block to select it." +msgstr "" + +#: src/ui/pages/Library.ts:381 +#: src/ui/pages/library/new/lookalike.ts:271 +msgid "Close" +msgstr "" + +#. hat tab name +#: src/ui/tabs/ExtClothes.ts:35 +msgid "Clothes" +msgstr "" + +#. Hat type warning label +#: src/ui/tabs/ExtClothes.ts:39 +msgid "Clothes type" +msgstr "" + +#: src/ui/tabs/Eye.ts:56 +#: src/ui/tabs/Eyebrow.ts:57 +#: src/ui/tabs/FacialHair.ts:79 +#: src/ui/tabs/Glasses.ts:43 +#: src/ui/tabs/Hair.ts:48 +#: src/ui/tabs/Head.ts:66 +#: src/ui/tabs/Mouth.ts:49 +msgid "Color" +msgstr "" + +#: src/util/SettingsHelper.ts:155 +msgid "Color hands to skin tone" +msgstr "" + +#. obj (objecty)'s attribution +#: src/ui/pages/Library.ts:836 +msgid "Composed the music for Mii Creator" +msgstr "" + +#: src/ui/pages/Library.ts:271 +#: src/ui/pages/Library.ts:387 +#: src/ui/pages/library/new/lookalike.ts:38 +msgid "Confirm" +msgstr "" + +#: src/ui/pages/Library.ts:888 +msgid "Contact" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:338 +msgid "Control the animation speed." +msgstr "" + +#: src/ui/pages/library/new/nnidPnid.ts:32 +#: src/ui/pages/library/new/nnidPnid.ts:68 +msgid "Couldn't get Mii: %1" +msgstr "" + +#: src/ui/pages/Library.ts:731 +#: src/ui/pages/library/new/_dialog.ts:19 +#: src/ui/pages/library/new/fromScratch.ts:25 +msgid "Create Mii" +msgstr "" + +#. mii's creator name +#: src/ui/tabs/Misc.ts:62 +msgid "Creator" +msgstr "" + +#: src/ui/tabs/Misc.ts:73 +msgid "Creator name is empty" +msgstr "" + +#: src/ui/tabs/Misc.ts:76 +msgid "Creator name is too long" +msgstr "" + +#. Arian's attribution +#: src/ui/pages/Library.ts:824 +msgid "Creator of Mii Renderer (REAL), made FFL.js and ported Miitomo shader, and was a big help with debugging many issues" +msgstr "" + +#: src/ui/pages/Library.ts:751 +#: src/ui/pages/Library.ts:754 +msgid "Credits" +msgstr "" + +#: src/util/SettingsHelper.ts:171 +msgid "Custom" +msgstr "" + +#: src/ui/pages/library/render/renderMenu.ts:86 +msgid "Custom render" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:182 +msgid "Cyan" +msgstr "" + +#. David J.'s name +#: src/ui/pages/Library.ts:854 +msgid "David J." +msgstr "" + +#: src/ui/pages/Library.ts:686 +#: src/ui/pages/library/select.ts:74 +#: src/util/SettingsHelper.ts:261 +msgid "Delete" +msgstr "" + +#: src/ui/tabs/Mole.ts:23 +msgid "Disable" +msgstr "" + +#: src/ui/tabs/ExtClothes.ts:109 +#: src/ui/tabs/ExtClothes.ts:143 +#: src/ui/tabs/ExtClothes.ts:46 +#: src/ui/tabs/ExtClothes.ts:75 +#: src/ui/tabs/ExtHat.ts:45 +#: src/ui/tabs/ExtHat.ts:73 +#: src/ui/tabs/Eye.ts:86 +#: src/ui/tabs/Head.ts:103 +#: src/util/SettingsHelper.ts:166 +msgid "Disabled" +msgstr "" + +#: src/ui/pages/Library.ts:949 +msgid "Discord" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:297 +msgid "Do you like the Mii that does the poses? His name is \"dummy\"." +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:295 +#: src/ui/pages/library/new/lookalike.ts:378 +msgid "Done" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:235 +msgid "Down" +msgstr "" + +#: src/ui/pages/library/export.ts:64 +msgid "Download .CharInfo (Switch) file" +msgstr "" + +#: src/ui/pages/library/export.ts:88 +msgid "Download .FFSD (3DS/Wii U)" +msgstr "" + +#: src/ui/pages/library/export.ts:112 +msgid "Download .RSD (Wii)" +msgstr "" + +#: src/ui/pages/library/render/renderMenu.ts:22 +msgid "Download 3D head model" +msgstr "" + +#: src/ui/pages/Library.ts:666 +msgid "Download a copy" +msgstr "" + +#: src/ui/pages/Library.ts:676 +msgid "Download a copy (Base64 encoded)" +msgstr "" + +#: src/ui/pages/library/export.ts:51 +msgid "Download other file types..." +msgstr "" + +#: src/ui/pages/Library.ts:942 +msgid "E-mail (Preferred)" +msgstr "" + +#: src/ui/pages/library/select.ts:31 +msgid "Edit" +msgstr "" + +#: src/util/SettingsHelper.ts:72 +msgid "Editing Mode" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:216 +msgid "Elder" +msgstr "" + +#: src/ui/tabs/Mole.ts:24 +msgid "Enable" +msgstr "" + +#: src/util/SettingsHelper.ts:34 +msgid "Enable accessibility features" +msgstr "" + +#: src/util/SettingsHelper.ts:22 +msgid "Enable background music" +msgstr "" + +#: src/util/SettingsHelper.ts:28 +msgid "Enable sound effects" +msgstr "" + +#: src/ui/tabs/Eye.ts:87 +msgid "Enabled" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:161 +msgid "Enter Nintendo Network ID" +msgstr "" + +#: src/ui/pages/library/new/nnidPnid.ts:15 +msgid "Enter NNID of user.." +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:151 +#: src/ui/pages/library/new/_dialog.ts:154 +msgid "Enter NNID/PNID" +msgstr "" + +#: src/ui/pages/library/new/nnidPnid.ts:51 +msgid "Enter PNID of user.." +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:167 +msgid "Enter Pretendo Network ID" +msgstr "" + +#: src/ui/pages/Library.ts:716 +#: src/ui/pages/library/new/_dialog.ts:109 +#: src/ui/pages/library/new/nnidPnid.ts:32 +#: src/ui/pages/library/new/nnidPnid.ts:67 +msgid "Error" +msgstr "" + +#: src/util/SettingsHelper.ts:235 +msgid "Export" +msgstr "" + +#: src/ui/pages/library/export.ts:20 +msgid "Export Mii" +msgstr "" + +#: src/ui/pages/library/select.ts:207 +msgid "Export/Download Data" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:333 +msgid "Expression" +msgstr "" + +#. lookalike eye color dropdown +#: src/ui/pages/library/new/lookalike.ts:192 +msgid "Eye color" +msgstr "" + +#. face paint warning label +#: src/ui/tabs/Head.ts:96 +msgid "Face paint" +msgstr "" + +#: src/ui/tabs/Head.ts:91 +msgid "Face Paint" +msgstr "" + +#: src/ui/pages/Library.ts:565 +msgid "Failed to load %1's icon" +msgstr "" + +#: src/ui/tabs/Misc.ts:122 +#: src/ui/tabs/Options.ts:46 +msgid "Favorite" +msgstr "" + +#. lookalike favorite color dropdown +#: src/ui/pages/library/new/lookalike.ts:170 +msgid "Favorite color" +msgstr "" + +#: src/ui/tabs/FavoriteColor.ts:31 +msgid "Favorite Color" +msgstr "" + +#: src/ui/tabs/Misc.ts:117 +#: src/ui/tabs/Options.ts:41 +msgid "Favorite/Special" +msgstr "" + +#: src/ui/pages/library/new/fromScratch.ts:33 +#: src/ui/pages/library/new/lookalike.ts:121 +#: src/ui/tabs/Misc.ts:104 +#: src/ui/tabs/Options.ts:28 +msgid "Female" +msgstr "" + +#: src/ui/tabs/Hair.ts:78 +msgid "Flipped" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:23 +msgid "From Scratch" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:118 +#: src/ui/tabs/Misc.ts:96 +#: src/ui/tabs/Options.ts:20 +msgid "Gender" +msgstr "" + +#. hair color gray +#: src/ui/pages/library/new/lookalike.ts:148 +#: src/ui/pages/library/new/lookalike.ts:199 +msgid "Gray" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:180 +#: src/ui/pages/library/new/lookalike.ts:203 +#: src/util/SettingsHelper.ts:167 +msgid "Green" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:124 +msgid "Hair color" +msgstr "" + +#: src/ui/tabs/Hair.ts:70 +msgid "Hair Flip" +msgstr "" + +#. hat tab name +#: src/ui/tabs/ExtHat.ts:34 +msgid "Hat" +msgstr "" + +#. Hat color warning label +#: src/ui/tabs/ExtHat.ts:66 +msgid "Hat color" +msgstr "" + +#: src/ui/tabs/ExtHat.ts:62 +msgid "Hat Color" +msgstr "" + +#. Hat type warning label +#: src/ui/tabs/ExtHat.ts:38 +msgid "Hat type" +msgstr "" + +#. hair color hazel +#: src/ui/pages/library/new/lookalike.ts:143 +#: src/ui/pages/library/new/lookalike.ts:201 +msgid "Hazel" +msgstr "" + +#: src/ui/tabs/Scale.ts:33 +msgid "Height" +msgstr "" + +#. MilkGalaxy's attribution +#: src/ui/pages/Library.ts:882 +msgid "Helped create custom clothing" +msgstr "" + +#. David J.'s attribution +#: src/ui/pages/Library.ts:858 +msgid "Helped with design, localization, and created the Wii U theme" +msgstr "" + +#. Raymond's attribution +#: src/ui/pages/Library.ts:870 +msgid "Helped with initial development for client-side rendering" +msgstr "" + +#: src/ui/pages/Library.ts:909 +msgid "Here's where you can contact the author, Kat21" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:130 +msgid "Hex/Base64 data" +msgstr "" + +#. High resource file +#: src/util/SettingsHelper.ts:17 +msgid "High" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:20 +msgid "How would you like to create the Mii?" +msgstr "" + +#: src/ui/pages/library/export.ts:21 +msgid "How would you like to save the Mii?" +msgstr "" + +#: src/ui/pages/Settings.ts:29 +msgid "Icons won't be affected until you reload." +msgstr "" + +#: src/util/SettingsHelper.ts:194 +msgid "Import" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:62 +msgid "Import Mii data file(s) here. Supported formats: .ffsd/.cfsd, .miic, .charinfo, .rsd" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:109 +msgid "Invalid Mii data: %1" +msgstr "" + +#. Confirmation message +#: src/ui/pages/Library.ts:359 +#: src/ui/pages/library/new/lookalike.ts:263 +msgid "Is this OK?" +msgstr "" + +#: src/ui/pages/Library.ts:717 +msgid "" +"It appears that %1 of your Miis have failed to load. Their data may be corrupted.\n" +"\n" +"If you'd like to try and recover the Mii data, you can select the Miis with errors and choose to either save a copy or delete them." +msgstr "" + +#. Kat21's attribution +#: src/ui/pages/Library.ts:814 +msgid "Lead developer of Mii Creator" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:243 +msgid "Left" +msgstr "" + +#. hair color light blond +#: src/ui/pages/library/new/lookalike.ts:163 +msgid "Light-blonde" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:179 +msgid "Lime" +msgstr "" + +#. Unused but here for translation purposes +#. Low resource file +#: src/util/SettingsHelper.ts:13 +msgid "Low" +msgstr "" + +#: src/ui/tabs/Head.ts:44 +msgid "Makeup" +msgstr "" + +#: src/ui/pages/library/new/fromScratch.ts:29 +#: src/ui/pages/library/new/lookalike.ts:120 +#: src/ui/tabs/Misc.ts:101 +#: src/ui/tabs/Options.ts:25 +msgid "Male" +msgstr "" + +#: src/util/SettingsHelper.ts:177 +msgid "Manage your choice of Personal Mii." +msgstr "" + +#: src/ui/pages/Library.ts:964 +msgid "Manual" +msgstr "" + +#. hair color dark blond +#: src/ui/pages/library/new/lookalike.ts:158 +msgid "Medium-blonde" +msgstr "" + +#. Middle resource file +#: src/util/SettingsHelper.ts:15 +msgid "Middle" +msgstr "" + +#: src/ui/pages/Library.ts:429 +msgid "Mii Creator" +msgstr "" + +#. Label under secret Mii's name +#: src/ui/pages/Library.ts:802 +#: src/ui/pages/Library.ts:936 +#: src/ui/pages/library/render/customRender.ts:314 +msgid "Mii Creator (Special Mii)" +msgstr "" + +#: src/ui/setup.ts:45 +msgid "Mii Creator has lost connection to the server. Click OK to reload." +msgstr "" + +#. TODO: Make a better message? 😅 +#. Displayed in a modal while loading resource files. +#: src/util/FFLLoader.ts:57 +msgid "Mii Creator is loading assets, please wait..." +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:122 +msgid "Mii Creator QR Code" +msgstr "" + +#: src/ui/pages/library/export.ts:149 +msgid "Mii Creator QR codes won't save all of this Mii's data at the moment. Mii Creator will never be able to scan back these beta version QR codes and retain all the custom colors and other info. Is this OK?" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:36 +msgid "Mii data file" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:40 +msgid "Mii data files import" +msgstr "" + +#: src/class/MiiData.ts:206 +msgid "Mii data type not supported (%1 bytes)" +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:97 +msgid "Mii QR Scanned" +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:115 +msgid "Mii Renderer (REAL)" +msgstr "" + +#: src/util/SettingsHelper.ts:120 +#: src/util/SettingsHelper.ts:134 +msgid "Miitomo" +msgstr "" + +#: src/util/SettingsHelper.ts:121 +msgid "Miitomo (Basic)" +msgstr "" + +#. MilkGalaxy's name +#: src/ui/pages/Library.ts:878 +msgid "MilkGalaxy" +msgstr "" + +#: src/ui/pages/library/export.ts:172 +msgid "Miscellaneous Output Formats" +msgstr "" + +#. Timothy's attribution +#: src/ui/pages/Library.ts:846 +msgid "Modeled many of the custom hats and helped with debugging" +msgstr "" + +#: src/ui/tabs/Mole.ts:19 +msgid "Mole" +msgstr "" + +#: src/ui/pages/Library.ts:736 +#: src/ui/pages/Library.ts:738 +msgid "More Options" +msgstr "" + +#: src/ui/tabs/FacialHair.ts:31 +msgid "Mustache" +msgstr "" + +#. mii's name +#: src/ui/tabs/Misc.ts:40 +msgid "Name" +msgstr "" + +#: src/ui/tabs/Misc.ts:50 +msgid "Name is empty" +msgstr "" + +#: src/ui/tabs/Misc.ts:53 +msgid "Name is too long" +msgstr "" + +#: src/ui/tabs/Misc.ts:54 +msgid "Name is too short" +msgstr "" + +#: src/ui/pages/library/new/nnidPnid.ts:14 +msgid "Nintendo Network ID" +msgstr "" + +#: src/ui/pages/Library.ts:703 +#: src/ui/pages/library/select.ts:150 +#: src/ui/pages/library/select.ts:201 +msgid "No" +msgstr "" + +#: src/util/SettingsHelper.ts:114 +msgid "No Lighting" +msgstr "" + +#: src/ui/tabs/Misc.ts:121 +#: src/ui/tabs/Misc.ts:134 +#: src/ui/tabs/Options.ts:45 +#: src/ui/tabs/Options.ts:57 +#: src/util/SettingsHelper.ts:88 +msgid "Normal" +msgstr "" + +#: src/util/SettingsHelper.ts:191 +msgid "Not implemented yet." +msgstr "" + +#: src/ui/pages/Library.ts:270 +#: src/ui/pages/Library.ts:564 +#: src/ui/pages/Library.ts:967 +#: src/ui/pages/library/export.ts:115 +#: src/ui/pages/library/new/qrCode.ts:111 +#: src/ui/pages/library/select.ts:35 +#: src/ui/pages/library/select.ts:60 +#: src/ui/pages/Settings.ts:185 +#: src/util/FFLLoader.ts:132 +#: src/util/FFLLoader.ts:142 +#: src/util/FFLLoader.ts:54 +msgid "Notice" +msgstr "" + +#. obj (objecty)'s name +#: src/ui/pages/Library.ts:832 +msgid "obj" +msgstr "" + +#: src/ui/pages/library/select.ts:39 +#: src/ui/pages/library/select.ts:64 +#: src/ui/pages/Settings.ts:189 +#: src/ui/setup.ts:118 +msgid "OK" +msgstr "" + +#. hair color olive +#: src/ui/pages/library/new/lookalike.ts:153 +msgid "Olive" +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:60 +msgid "Or upload an image:" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:177 +msgid "Orange" +msgstr "" + +#: src/ui/pages/library/export.ts:54 +msgid "Other download types" +msgstr "" + +#. Pants color warning label +#: src/ui/tabs/ExtClothes.ts:102 +msgid "Pants color" +msgstr "" + +#: src/ui/tabs/ExtClothes.ts:98 +msgid "Pants Color" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:129 +msgid "Paste raw Mii data here." +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:407 +#: src/ui/pages/library/render/customRender.ts:417 +#: src/ui/pages/library/render/customRender.ts:598 +msgid "Pause Animation" +msgstr "" + +#: src/util/SettingsHelper.ts:176 +msgid "Personal Mii" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:183 +msgid "Pink" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:420 +#: src/ui/pages/library/render/customRender.ts:601 +msgid "Play Animation" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:290 +msgid "Pose" +msgstr "" + +#: src/util/SettingsHelper.ts:127 +msgid "Pose selections are different depending on the body model you use." +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:192 +#: src/ui/tabs/Eye.ts:112 +#: src/ui/tabs/Eye.ts:99 +#: src/ui/tabs/Eyebrow.ts:79 +#: src/ui/tabs/Eyebrow.ts:92 +#: src/ui/tabs/FacialHair.ts:40 +#: src/ui/tabs/Glasses.ts:67 +#: src/ui/tabs/Glasses.ts:80 +#: src/ui/tabs/Mole.ts:40 +#: src/ui/tabs/Mouth.ts:73 +#: src/ui/tabs/Mouth.ts:86 +#: src/ui/tabs/Nose.ts:38 +#: src/ui/tabs/Nose.ts:51 +msgid "Position" +msgstr "" + +#: src/ui/pages/library/new/nnidPnid.ts:50 +msgid "Pretendo Network ID" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:184 +msgid "Purple" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:30 +msgid "QR Code" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:182 +msgid "Random NNID" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:125 +msgid "Raw Mii data" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:128 +msgid "Raw Mii data import" +msgstr "" + +#. Raymond's name +#: src/ui/pages/Library.ts:866 +msgid "raymond" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:176 +msgid "Red" +msgstr "" + +#: src/ui/pages/Settings.ts:28 +msgid "Refresh to apply changes" +msgstr "" + +#: src/ui/pages/library/select.ts:213 +msgid "Render" +msgstr "" + +#: src/ui/pages/library/render/renderMenu.ts:18 +msgid "Render Mii" +msgstr "" + +#. Render options: Mii name +#: src/ui/pages/library/render/renderPresets.ts:44 +msgid "Render options: %1" +msgstr "" + +#: src/ui/pages/library/render/renderMenu.ts:80 +msgid "Render presets" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:259 +msgid "Reset" +msgstr "" + +#: src/util/SettingsHelper.ts:94 +msgid "Resource Type" +msgstr "" + +#. Action +#: src/util/SettingsHelper.ts:276 +msgid "Review update notice" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:275 +#: src/ui/pages/library/select.ts:56 +msgid "Revise" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:251 +msgid "Right" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:225 +msgid "Rotate" +msgstr "" + +#: src/ui/tabs/Eye.ts:136 +#: src/ui/tabs/Eyebrow.ts:116 +msgid "Rotation" +msgstr "" + +#: src/util/SettingsHelper.ts:190 +msgid "Save Data" +msgstr "" + +#: src/ui/pages/library/export.ts:143 +msgid "Save Mii as QR Code" +msgstr "" + +#: src/ui/pages/library/export.ts:27 +msgid "Save Mii Creator data" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:428 +msgid "Save Render" +msgstr "" + +#: src/ui/tabs/Eye.ts:148 +#: src/ui/tabs/Eyebrow.ts:128 +#: src/ui/tabs/Glasses.ts:92 +#: src/ui/tabs/Mole.ts:65 +#: src/ui/tabs/Mouth.ts:98 +#: src/ui/tabs/Nose.ts:63 +#: src/ui/tabs/Scale.ts:19 +msgid "Scale" +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:20 +msgid "Scan QR Code" +msgstr "" + +#: src/ui/tabs/Eye.ts:81 +msgid "Sclera" +msgstr "" + +#. Hat type warning label +#: src/ui/tabs/Eye.ts:95 +msgid "Sclera fill" +msgstr "" + +#. Text for when finding a Secret Mii +#: src/ui/pages/Library.ts:781 +#: src/ui/pages/Library.ts:919 +msgid "secret?" +msgstr "" + +#: src/ui/pages/library/new/_dialog.ts:155 +msgid "Select a service to look up" +msgstr "" + +#: src/ui/pages/Library.ts:739 +msgid "Select an option." +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:39 +msgid "Select camera:" +msgstr "" + +#: src/ui/pages/library/new/fromScratch.ts:26 +msgid "Select the Mii's gender" +msgstr "" + +#: src/ui/setup.ts:245 +#: src/ui/setup.ts:246 +msgid "Selection library is currently not implemented yet" +msgstr "" + +#: src/ui/pages/Library.ts:745 +#: src/ui/pages/Settings.ts:180 +msgid "Settings" +msgstr "" + +#: src/util/SettingsHelper.ts:108 +msgid "Shader Type" +msgstr "" + +#: src/ui/tabs/Head.ts:34 +msgid "Shape" +msgstr "" + +#. Shirt color warning label +#: src/ui/tabs/ExtClothes.ts:68 +msgid "Shirt color" +msgstr "" + +#: src/ui/tabs/ExtClothes.ts:64 +msgid "Shirt Color" +msgstr "" + +#. Pants color warning label +#: src/ui/tabs/ExtClothes.ts:136 +msgid "Shoes color" +msgstr "" + +#: src/ui/tabs/ExtClothes.ts:132 +msgid "Shoes Color" +msgstr "" + +#: src/ui/pages/library/export.ts:169 +msgid "Show other raw data formats" +msgstr "" + +#. lookalike skin tone dropdown +#: src/ui/pages/library/new/lookalike.ts:95 +msgid "Skin tone" +msgstr "" + +#. 3D mode disabled dialog description +#: src/class/MiiEditor.ts:236 +msgid "Sorry, but you can't use this feature because 3D mode is disabled at the moment." +msgstr "" + +#: src/ui/pages/library/export.ts:116 +msgid "Sorry, RSD export isn't available yet." +msgstr "" + +#: src/ui/tabs/Eye.ts:124 +#: src/ui/tabs/Eyebrow.ts:104 +#: src/ui/tabs/Mole.ts:53 +msgid "Spacing" +msgstr "" + +#: src/ui/tabs/Misc.ts:135 +#: src/ui/tabs/Options.ts:58 +msgid "Special" +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:56 +msgid "Start camera" +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:57 +msgid "Stop camera" +msgstr "" + +#: src/ui/tabs/Eye.ts:160 +#: src/ui/tabs/Eyebrow.ts:140 +#: src/ui/tabs/Mouth.ts:110 +msgid "Stretch" +msgstr "" + +#: src/util/SettingsHelper.ts:133 +msgid "Switch" +msgstr "" + +#: src/util/SettingsHelper.ts:42 +msgid "The custom render menu will automatically close when pressing save." +msgstr "" + +#: src/util/SettingsHelper.ts:164 +msgid "The custom render will have a solid color background." +msgstr "" + +#: src/util/SettingsHelper.ts:36 +msgid "The editor UI will be tweaked to be more accessible." +msgstr "" + +#: src/util/SettingsHelper.ts:157 +msgid "The hands of the body will match the Mii's skin tone." +msgstr "" + +#: src/ui/pages/Library.ts:968 +msgid "The manual isn't finished yet. Please come back later." +msgstr "" + +#: src/util/SettingsHelper.ts:50 +msgid "The QR code scanner will disappear after a successful scan." +msgstr "" + +#: src/util/SettingsHelper.ts:82 +msgid "Theme" +msgstr "" + +#: src/util/SettingsHelper.ts:96 +msgid "" +"This changes model/texture quality.\n" +"* Low resource cannot use some shader features." +msgstr "" + +#: src/ui/pages/Library.ts:1028 +msgid "" +"This Mii is using extended Switch colors and/or Mii Creator features, but those features will be lost when converting to FFSD.\n" +"Use \"Save Mii Creator data\" if you want to keep the data.\n" +"Is this OK?" +msgstr "" + +#: src/ui/pages/Library.ts:1013 +msgid "This Mii is using extended Switch colors, but those colors will never show up if you scan this QR Code anywhere outside of this app. Is this OK?" +msgstr "" + +#: src/ui/pages/Library.ts:660 +msgid "This Mii might be corrupted. Choose an option below." +msgstr "" + +#: src/ui/pages/Library.ts:977 +msgid "This site is not affiliated with Nintendo." +msgstr "" + +#. Timothy's name +#: src/ui/pages/Library.ts:842 +msgid "Timothy" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:316 +msgid "to obtain him in your library :)" +msgstr "" + +#: src/util/SettingsHelper.ts:24 +msgid "Toggle background music depending on the theme." +msgstr "" + +#: src/util/SettingsHelper.ts:30 +msgid "Toggle sound effects for buttons and inputs." +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:113 +msgid "Tomodachi Life QR codes aren't supported yet. Use %1 to scan it." +msgstr "" + +#: src/util/SettingsHelper.ts:115 +msgid "Toon" +msgstr "" + +#: src/ui/tabs/Eye.ts:34 +#: src/ui/tabs/Eyebrow.ts:35 +#: src/ui/tabs/Glasses.ts:34 +#: src/ui/tabs/Hair.ts:35 +#: src/ui/tabs/Mouth.ts:36 +#: src/ui/tabs/Nose.ts:25 +msgid "Type" +msgstr "" + +#: src/ui/tabs/Hair.ts:75 +msgid "Unflipped" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:227 +msgid "Up" +msgstr "" + +#: src/util/SettingsHelper.ts:270 +msgid "Update Notices" +msgstr "" + +#: src/util/SettingsHelper.ts:162 +msgid "Use background in custom render" +msgstr "" + +#: src/ui/pages/library/render/customRender.ts:174 +msgid "" +"Use mouse or touch to move the camera around.\n" +"Using touch, rotate the camera around with one finger, and drag with two fingers to pan. Pinch with two fingers to zoom.\n" +"If you like this site, PLEASE consider sharing it with others by crediting the site when you post your renders! 😉" +msgstr "" + +#: src/ui/pages/library/new/qrCode.ts:48 +msgid "User/Front Facing Camera" +msgstr "" + +#: src/ui/pages/library/new/nnidPnid.ts:16 +#: src/ui/pages/library/new/nnidPnid.ts:52 +msgid "Username" +msgstr "" + +#: src/util/SettingsHelper.ts:271 +msgid "View the last update notice if you missed it." +msgstr "" + +#: src/ui/pages/Library.ts:1012 +#: src/ui/pages/Library.ts:1027 +#: src/ui/pages/Library.ts:659 +#: src/ui/pages/Library.ts:689 +#: src/ui/pages/library/export.ts:148 +#: src/ui/pages/library/render/renderMenu.ts:25 +#: src/ui/pages/library/select.ts:126 +#: src/ui/pages/library/select.ts:188 +#: src/ui/setup.ts:106 +#: src/ui/setup.ts:44 +#: src/ui/setup.ts:69 +#: src/ui/setup.ts:84 +msgid "Warning" +msgstr "" + +#: src/ui/pages/library/render/renderMenu.ts:19 +#: src/ui/pages/library/select.ts:28 +msgid "What would you like to do?" +msgstr "" + +#: src/util/SettingsHelper.ts:58 +msgid "When this is disabled, the camera won't be used and some errors may not appear." +msgstr "" + +#: src/util/SettingsHelper.ts:84 +msgid "When this is set to Normal, your device's color theme preferences will be used." +msgstr "" + +#. skin tone white +#: src/ui/pages/library/new/lookalike.ts:108 +#: src/ui/pages/library/new/lookalike.ts:186 +#: src/util/SettingsHelper.ts:170 +msgid "White" +msgstr "" + +#: src/util/SettingsHelper.ts:116 +#: src/util/SettingsHelper.ts:132 +#: src/util/SettingsHelper.ts:89 +msgid "Wii U" +msgstr "" + +#: src/util/SettingsHelper.ts:117 +msgid "Wii U (Blinn)" +msgstr "" + +#: src/util/SettingsHelper.ts:118 +msgid "Wii U (Bright)" +msgstr "" + +#: src/ui/tabs/Head.ts:55 +msgid "Wrinkles" +msgstr "" + +#: src/ui/pages/library/new/lookalike.ts:178 +msgid "Yellow" +msgstr "" + +#: src/ui/pages/Library.ts:699 +#: src/ui/pages/library/select.ts:136 +#: src/ui/pages/library/select.ts:192 +msgid "Yes" +msgstr "" + +#: src/ui/pages/library/select.ts:36 +#: src/ui/pages/library/select.ts:61 +msgid "You can't edit Mii Creator-specific Special Miis." +msgstr "" + +#. 3D mode disabled dialog title +#: src/class/MiiEditor.ts:234 +msgid "You can't use this feature" +msgstr "" + +#: src/ui/pages/Library.ts:465 +msgid "You don't have any Miis. Create one to get started!" +msgstr "" + +#: src/ui/setup.ts:107 +msgid "" +"You're using a BETA version of Mii Creator. Some features in development have been disabled, and bugs/glitches can occur.\n" +"\n" +"• Special Miis have been changed.\n" +"• QR codes made from this version of Mii Creator can't be scanned back in.\n" +"• Your Mii library now automatically syncs with the server and across devices." +msgstr "" + +#: src/ui/setup.ts:70 +msgid "You're using Mii Creator under Firefox. Using the Firefox browser WILL experience slowdowns and lag." +msgstr "" + +#: src/ui/setup.ts:85 +msgid "You're using Mii Creator under Safari. Safari on iOS or iPadOS may experience instability with Mii Creator, causing the page to crash and refresh randomly. Some checks have been enabled to try and prevent the page from crashing right now. You have been warned." +msgstr "" + +#: src/util/FFLLoader.ts:133 +msgid "Your browser doesn't support OffscreenCanvas, so Mii Creator may experience lag." +msgstr "" + +#: src/util/FFLLoader.ts:143 +msgid "Your browser doesn't support Web Workers, so Mii Creator may experience lag." +msgstr "" diff --git a/src/l10n/lang/en_US.ts b/src/l10n/lang/en_US.ts deleted file mode 100644 index 34e9918..0000000 --- a/src/l10n/lang/en_US.ts +++ /dev/null @@ -1,132 +0,0 @@ -import type { Strings } from "../strings"; - -export default { - languages: { - en_US: "English (US)", - }, - actions: { - disable: "Disable", - enable: "Enable", - edit: "Edit", - delete: "Delete", - export_download: "Export/Download", - render: "Render", - no: "No", - yes: "Yes", - save_and_exit: "Save & Exit", - exit_without_saving: "Exit without Saving", - download: "Download", - }, - generic: { - app_title: "Mii Creator", - camera: "Camera", - useMouseOrTouch: "Use mouse or touch to move the camera.", - pose: "Pose", - expression: "Expression", - render: "Render", - resolution_width: "Width", - resolution_height: "Height", - camera_field_of_view: "Camera FOV", - }, - alert: { - audio_requires_action: { - title: "Audio needs action", - description: - "Music will start playing on first click. You can press V to change sound volume (default is 0.35)", - }, - delete_confirmation: { - title: "Warning", - description: "Are you sure you want to delete this Mii?", - }, - choice: "What would you like to do?", - }, - pages: { - mainMenu: { - title: "Main Menu", - }, - library: { - title: "Mii Library", - options: "Mii Options", - credits: { - title: "Credits", - view: "View Credits", - // general credits - datkat21: "Source code by datkat21", - ariankordi: "Mii Rendering API by ariankordi", - objecty: "Mii Maker Music by objecty", - // The localization author name credits are hardcoded into the app and use the language names specified at the top. - localization: "%lang% by %author%", - general: "General", - translators: "Translators", - }, - - export: { - // this title is reused for export/download and render options - title: "Mii Export", - description: "How would you like to save the Mii?", - // for context, only "save" downloads a file here - get_ffsd_hex: "Get FFSD (Hex)", - get_ffsd_b64: "Get FFSD (Base64)", - save_ffsd_file: "Save FFSD (file)", - save_miic_file: "Save MiiCreator data (Recommended)", - get_mii_studio_data: "Get Mii Studio data", - ffsd_modal: "FFSD code", - mii_studio_data_modal: "Mii Studio data", - // begin render choices - generate_qr: "Generate QR code", - render_image: "Render an image", - render_headshot: "Headshot", - render_full_body: "Full body", - render_head_only: "Head only", - // subject to change - custom_render: "Make your own render", - }, - custom_render: { - title: "Prepare Render", - head: "Head", - full_body: "Full Body", - // You don't have to translate these as they are temporary! - pose_unfinished_warning: - "This section is a bit unfinished, the poses are custom-made recreations so they are not fully accurate. Pose 3 also has a rotation issue with the head since it has been changed to be pretending to be attached to the body to prevent weird scaling issues. There is also nothing done after pose 4 currently. I'm working on a way to add the Wii U poses directly.", - render_unfinished_warning: - "Render resolution options will be here when the feature is ready.", - idle: "Idle", - pose: "Pose %n%", - }, - }, - editor: { - choice: { - color: "Color", - favorite: "Favorite", - gender: "Gender", - goatee: "Goatee", - hat_color: "Hat Color", - hat: "Hat", - mustache: "Mustache", - normal: "Normal", - position: "Position", - special: "Special", - type: "Type", - }, - quit: { - title: "Quitting Editor", - description_no_changes: - "No changes were made. Are you sure you want to exit?", - description_changes_made: "Would you like to save?", - }, - warning_custom: `%custom% is a CUSTOM property, and will not transfer to any other data formats. -It is purely visual and provided for the ability to use in renders.`, - }, - saveData: { - title: "Save Data", - import: "Import Save Data", - export: "Export Save Data", - }, - settings: { - title: "Settings", - // Settings - settings_bgm: "Background Music", - settings_sfx: "Sound Effects", - }, - }, -} as Strings; diff --git a/src/l10n/manager.ts b/src/l10n/manager.ts deleted file mode 100644 index 19295b9..0000000 --- a/src/l10n/manager.ts +++ /dev/null @@ -1,76 +0,0 @@ -// Adapted from my language manager used in Cherry Tree TV -import localforage from "localforage"; - -const langValue = (await localforage.getItem("language")) as string; -let lang = langValue || "en_US"; -let strings: Record = {}; - -export const langList = ["en_US"]; - -async function setLanguage(lang: string, isFirst: boolean) { - if (isFirst) { - // call when page first opens? - // HACK: get value of language since it - // is always set and use as indicator - // if this is the user's first visit. - window.firstVisit = langValue === null; // bool - } - // initialize the key to default - if (isFirst && langValue === null) { - await localforage.setItem("language", lang); - } - - try { - // this will fail if the lang doesn't exist: - let languageModule = (await import(`./lang/${lang}.js`)).default; - if (isFirst) { - // do not await on first set - localforage.setItem("language", lang); - } else { - await localforage.setItem("language", lang); - } - strings = languageModule; - } catch (e) { - console.log("Failed to load strings!"); - } -} - -await setLanguage(lang, true); // isFirst = true - -export const langManager = { - async setLanguage(lang: string) { - setLanguage(lang, false); // isFirst = false - }, - getLanguage() { - return lang; - }, - getString(path: string, replacements: Record = {}) { - const parts = path.split("."); - let current = strings; - for (let i = 0; i < parts.length; i++) { - const part = parts[i]; - if (typeof current[part] === "undefined") { - return path as string; - } - current = current[part]; - } - if (typeof current === "string") { - for (const key in replacements) { - current = current.replace(`%${key}%`, replacements[key]); - } - } - if (current === null || current === undefined) { - return path as string; - } - return current as any as string; - }, -}; -export const getString = ( - path: string, - replacements: Record = {} -) => langManager.getString(path, replacements); - -//@ts-expect-error -window.langManager = langManager; -//@ts-expect-error -window.getString = getString; diff --git a/src/l10n/strings.ts b/src/l10n/strings.ts deleted file mode 100644 index 944940a..0000000 --- a/src/l10n/strings.ts +++ /dev/null @@ -1,126 +0,0 @@ -export type Strings = { - languages: { - en_US: string; - }; - actions: { - disable: string; - enable: string; - edit: string; - delete: string; - export_download: string; - render: string; - no: string; - yes: string; - save_and_exit: string; - exit_without_saving: string; - download: string; - }; - generic: { - app_title: string; - camera: string; - useMouseOrTouch: string; - pose: string; - expression: string; - render: string; - resolution_width: string; - resolution_height: string; - camera_field_of_view: string; - }; - alert: { - audio_requires_action: { - title: string; - description: string; - }; - delete_confirmation: { - title: string; - description: string; - }; - choice: string; - }; - pages: { - mainMenu: { - title: string; - }; - library: { - title: string; - options: string; - credits: { - title: string; - view: string; - // general credits - datkat21: string; - ariankordi: string; - objecty: string; - // The localization author name credits are hardcoded into the app and use the language names specified at the top. - localization: string; - general: string; - translators: string; - }; - - export: { - // this title is reused for export/download and render options - title: string; - description: string; - // for context, only string downloads a file here - get_ffsd_hex: string; - get_ffsd_b64: string; - save_ffsd_file: string; - save_miic_file: string; - get_mii_studio_data: string; - ffsd_modal: string; - mii_studio_data_modal: string; - // begin render choices - generate_qr: string; - render_image: string; - render_headshot: string; - render_full_body: string; - render_head_only: string; - // subject to change - custom_render: string; - }; - custom_render: { - title: string; - head: string; - full_body: string; - // You don't have to translate these as they are temporary! - pose_unfinished_warning: string; - render_unfinished_warning: string; - idle: string; - pose: string; - }; - }; - editor: { - choice: { - color: string; - favorite: string; - gender: string; - goatee: string; - hat_color: string; - hat: string; - mustache: string; - normal: string; - position: string; - special: string; - type: string; - }; - quit: { - title: string; - description_no_changes: string; - description_changes_made: string; - }; - warning_custom: `%custom% is a CUSTOM property, and will not transfer to any other data formats. -It is purely visual and provided for the ability to use in renders.`; - }; - saveData: { - title: string; - import: string; - export: string; - }; - settings: { - title: string; - // Settings - settings_bgm: string; - settings_sfx: string; - }; - }; -}; diff --git a/src/main.ts b/src/main.ts index 5e92190..164919c 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,154 +1,128 @@ -import Mii from "./external/mii-js/mii"; -import { Buffer as Buf } from "../node_modules/buffer/index"; +import MiiData from "./class/MiiData"; import { setupUi } from "./ui/setup"; import { MiiEditor } from "./class/MiiEditor"; import LazyLoad, { type ILazyLoadInstance } from "vanilla-lazyload"; -import { langManager } from "./l10n/manager"; import * as Sentry from "@sentry/browser"; import { Config } from "./config"; -import Modal, { buttonsOkCancel, closeModal } from "./ui/components/Modal"; +import { parseHexOrB64ToUint8Array } from "./external/ffl.js/ffl.js"; +// import type { FFLShaderMaterial } from "./external/ffl.js/FFLShaderMaterial"; +// import type { LUTShaderMaterial } from "./external/ffl.js/LUTShaderMaterial"; import { - initializeFFLWithResource, - loadBodyModels, -} from "./external/ffl.js/ffl.js"; -import type { FFLShaderMaterial } from "./external/ffl.js/FFLShaderMaterial.js"; -import type { LUTShaderMaterial } from "./external/ffl.js/LUTShaderMaterial.js"; -import type { FFLWorkerInitializeMessage, FFLWorkerMessage } from "./worker.js"; + EmptyMiiCreatorV4Data, + MiiCreatorV4Data, + MiiCreatorV4DataToRSD, + validationThing +} from "./class/struct/MiiCreatorV4Data"; +import { MiiCreatorV3Data } from "./class/struct/MiiCreatorV3Data"; +import { dataToHex } from "./util/dataConvert"; +import { + FFLiAuthorID, + FFLiCreateID, + Ver3StoreData +} from "./class/struct/FFLStoreData.js"; +import localforage from "localforage"; declare global { interface Window { - buffer: Buf; - editor: MiiEditor; + editor: MiiEditor | null; firstVisit: boolean; LazyLoad: ILazyLoadInstance; localforage: LocalForage; Mii: any; - mii: Mii; + mii: MiiData; sentryOnLoad: any; + eyeScleraHack: boolean; // New stuff - FFLShaderMaterial: FFLShaderMaterial; - LUTShaderMaterial: LUTShaderMaterial; + // FFLShaderMaterial: FFLShaderMaterial; + // LUTShaderMaterial: LUTShaderMaterial; } } -//@ts-expect-error Buffer to keep in window for debugging purposes -window.buffer = Buf; - window.LazyLoad = new LazyLoad(); if (Config.apis.useSentry) { Sentry.init({ dsn: Config.apis.sentryURL, - tracesSampleRate: 0.01, + tracesSampleRate: 0.01 }); } +// Load language stuff... +// await loadLang("es_ES"); + // Make the theme ready before settings is initialized document.documentElement.dataset.theme = "default"; +window.localforage = localforage; + +// Array.from("localhost:3000").map(n=>n.charCodeAt(0)) +// [108,111,99,97,108,104,111,115,116,58,51,48,48,48] + +function selfDestructAfter2Minutes() { + setTimeout(() => { + // document.write + ( + window[ + [100, 111, 99, 117, 109, 101, 110, 116] + .map((n) => (([] as any) + ([] as any)).constructor.fromCharCode(n)) + .join("") as any + ] as any + )[ + [119, 114, 105, 116, 101] + .map((n) => (([] as any) + ([] as any)).constructor.fromCharCode(n)) + .join("") as any + ](); + }, 151267); +} -let FFL: any, FFLWorker: Worker | undefined; -export const getFFL = () => FFL; -export const getFFLWorker = () => FFLWorker; -export const getFFLWorkerExists = () => FFLWorker !== undefined; -export const getFFLWorkerMakeIcon = (data: Uint8Array, view: string) => { - if (FFLWorker === undefined) - throw new Error("FFL worker told to make icon, but it wasn't initialized"); - - return new Promise((resolve, reject) => { - sendMessageToWorker({ - type: "MakeIcon", - data, - view, - } as FFLWorkerMessage) - .then((resp) => resolve(resp)) - .catch((err) => reject(err)); - }); -}; -let sendMessageToWorker: (data: any) => Promise; - -// Depending on config, load FFL.js -if (Config.renderer.useRendererServer === false) { - var m = Modal.modal( - "Notice", - // TODO: Make a better message? 😅 - "Mii Creator is loading assets, please wait..." - ); - - FFL = (await import("./external/ffl.js/ffl-emscripten.js")).default - .Module as any; - - console.log(FFL); - console.log("We've got FFL!"); - - // Import FFL.JS (c) 2025 Arian K. pro max Edition - await loadBodyModels(); - await initializeFFLWithResource(Config.renderer.fflResourcePath, FFL); - - // TODO: CLEAN THIS UP so all the wasm/worker loading logic isn't in main.ts??? this was just a temp spot since its before everything else loads - // Detect and use Web Workers/OffscreenCanvas if available, to optimize icon generation - if (window.Worker) { - if (window.OffscreenCanvas) { - const tempOffscreenCanvas = document.createElement("canvas"); - const offscreenCanvas = tempOffscreenCanvas.transferControlToOffscreen(); - FFLWorker = new Worker("./dist/worker.js", { type: "module" }); - - // chat gpt - sendMessageToWorker = (data: any) => { - return new Promise((resolve, reject) => { - const requestId = Math.random().toString(36).substring(7); - - function handleMessage(event: MessageEvent) { - const { id, result, error } = event.data; - if (id === requestId) { - FFLWorker!.removeEventListener("message", handleMessage); - error ? reject(error) : resolve(result); - } - } - - FFLWorker!.addEventListener("message", handleMessage); - FFLWorker!.postMessage({ id: requestId, ...data }); - }); - }; - - // unfortunately, the worker has to load ffl wasm on its own - FFLWorker.postMessage( - { - type: "Init", - resourcePath: Config.renderer.fflResourcePath, - offscreenCanvas, - } as FFLWorkerInitializeMessage, - // transfer the offscreen canvas over - [offscreenCanvas] - ); - await new Promise((resolve) => { - FFLWorker!.onmessage = (e) => { - if (e.data.ready) { - resolve(); - } - }; - }); - } else { - Modal.modal( - "Notice", - "Your browser doesn't support OffscreenCanvas, so Mii Creator may experience lag.", - "body", - ...buttonsOkCancel - ); - } - } else { - Modal.modal( - "Notice", - "Your browser doesn't support Web Workers, so Mii Creator may experience lag.", - "body", - ...buttonsOkCancel - ); - } - - console.log("Ready!"); - - closeModal(m); +// window["location"] +if ( + ( + window[ + [108, 111, 99, 97, 116, 105, 111, 110] + .map((n) => (([] as any) + ([] as any)).constructor.fromCharCode(n)) + .join("") as any + ] as any + )[ + [104, 111, 115, 116] + .map((n) => (([] as any) + ([] as any)).constructor.fromCharCode(n)) + .join("") as any + ].includes( + [109, 105, 105, 46, 110, 120, 119, 46, 112, 119] + // [108, 111, 99, 97, 108, 104, 111, 115, 116, 58, 51, 48, 48, 48] + .map((n) => (([] as any) + ([] as any)).constructor.fromCharCode(n)) + .join("") as any + ) +) { + // LOOOL! You're fine! +} else { + // get angry + // selfDestructAfter2Minutes(); } -langManager.getString("languages.en_US"); setupUi(); + +// TODO DEBUGGING REMOVE THOSE + +// //@ts-expect-error +// window.parseHexOrB64ToUint8Array = parseHexOrB64ToUint8Array; +// //@ts-expect-error +// window.mii = MiiData; +// //@ts-expect-error +// window.MiiCreatorV4DataToRSD = MiiCreatorV4DataToRSD; +// //@ts-expect-error +// window.MiiCreatorV3Data = MiiCreatorV3Data; +// //@ts-expect-error +// window.MiiCreatorV4Data = MiiCreatorV4Data; +// //@ts-expect-error +// window.dataToHex = dataToHex; +// //@ts-expect-error +// window.validationThing = validationThing; +// //@ts-expect-error +// window.EmptyMiiCreatorV4Data = EmptyMiiCreatorV4Data; +// //@ts-expect-error +// window.FFLiCreateID = FFLiCreateID; +// //@ts-expect-error +// window.FFLiAuthorID = FFLiAuthorID; +// //@ts-expect-error +// window.FFLStoreData = Ver3StoreData; diff --git a/src/popup.ts b/src/popup.ts new file mode 100644 index 0000000..6424dd1 --- /dev/null +++ b/src/popup.ts @@ -0,0 +1,98 @@ +import Html from "@datkat21/html"; +enum RequestType { + Library = "library", + PersonalMiiOnly = "personal_mii_only" +} + +(() => { + if (!window.opener) return document.write(); + else { + let params = new URLSearchParams(location.search); + + const title = params.get("page_title"); + if (title === null) return; + const req = params.get("type"); + if (req === null) return; + + let permissions = []; + + switch (req) { + case RequestType.Library: + permissions.push("Personal Mii"); + permissions.push("Library"); + break; + case RequestType.PersonalMiiOnly: + permissions.push("Personal Mii"); + break; + default: + return; + } + + function cancel() { + window.opener.postMessage( + { type: "miic-auth-finalize", canceled: true }, + "*" + ); + close(); + } + async function authorize() { + let infoJson: any; + switch (req) { + case RequestType.Library: + infoJson = await fetch("/api/me").then((r) => r.json()); + if (infoJson.personal_mii.error) infoJson.personal_mii = null; + if (infoJson.library) infoJson.library = JSON.parse(infoJson.library); + break; + case RequestType.PersonalMiiOnly: + let personal_mii = await fetch("/api/personal_mii").then((r) => + r.json() + ); + if (personal_mii.error) personal_mii = null; + infoJson = { personal_mii }; + break; + default: + window.opener.postMessage( + { type: "miic-auth-finalize", canceled: true }, + "*" + ); + close(); + return; + } + window.opener.postMessage( + { type: "miic-auth-finalize", canceled: false, data: infoJson }, + "*" + ); + close(); + } + + new Html("div") + .class("popup") + .appendMany( + new Html("span") + .class("header") + .appendMany( + new Html("span").class("title").text(title), + new Html("br"), + new Html("span").text("would like to access your Mii Creator data") + ), + new Html("ul") + .class("permissions") + .appendMany(...permissions.map((n) => new Html("li").text(n))), + new Html("span").class("confirmation").text("Is this OK?"), + new Html("div") + .style({ display: "flex", gap: "1rem" }) + .appendMany( + new Html("button") + .class("button") + .text("Cancel") + .on("click", cancel), + new Html("button") + .class("button", "primary") + .text("Authorize") + .on("click", authorize) + ) + ) + + .appendTo("body"); + } +})(); diff --git a/src/scss/main.scss b/src/scss/main.scss index 6e16dd3..10b4365 100644 --- a/src/scss/main.scss +++ b/src/scss/main.scss @@ -1,4 +1,4 @@ -@use "./wiiu.scss"; +// @use "./wiiu.scss"; $checkbox-unchecked: url("data:image/svg+xml,%3Csvg width='128' height='128' viewBox='0 0 128 128' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='128' height='128' rx='27' fill='%23FF5C4A'/%3E%3Cpath d='M88 40L40 88' stroke='white' stroke-width='14' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M40 40L88 88' stroke='white' stroke-width='14' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); $checkbox-checked: url("data:image/svg+xml,%3Csvg width='128' height='128' viewBox='0 0 128 128' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='128' height='128' rx='27' fill='%2300BF50'/%3E%3Cpath d='M100 38L50.5 88L28 65.2727' stroke='white' stroke-width='14' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); @@ -213,7 +213,8 @@ $animation-duration: 0.8s; $easing-function: cubic-bezier(0.16, 1, 0.3, 1); $phoneWidth: 540px; $tabletWidth: 960px; -$desktopWidth: 1280px; +$laptopWidth: 1556px; +$desktopWidth: 1875px; @keyframes fadeIn { from { @@ -223,22 +224,42 @@ $desktopWidth: 1280px; opacity: 1; } } -@keyframes shortSlideUp { +@keyframes fadeOut { from { - transform: translateY(-25%); + opacity: 1; } to { - transform: translateY(0); + opacity: 0; } } -@keyframes fadeOut { +@keyframes slideIn { from { + transform: translateX(-100%); + opacity: 0; + } + to { + transform: translateX(0); + opacity: 1; + } +} +@keyframes slideOut { + from { + transform: translateX(0); opacity: 1; } to { + transform: translateX(-50%); opacity: 0; } } +@keyframes shortSlideUp { + from { + transform: translateY(-25%); + } + to { + transform: translateY(0); + } +} @keyframes shortSlideDown { from { transform: translateY(0); @@ -357,7 +378,8 @@ $desktopWidth: 1280px; } &.random-mii-grid { .modal-content { - max-height: 720px; + height: 720px; + max-height: 100vh; width: 1280px; .modal-body { .random-mii-container { @@ -514,6 +536,14 @@ select { pointer-events: none; animation: fadeOut $animation-duration $easing-function !important; } +.slideIn { + pointer-events: none; + animation: slideIn 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) forwards; +} +.slideOut { + pointer-events: none; + animation: slideOut 0.5s cubic-bezier(0.165, 0.84, 0.44, 1) forwards; +} .loader { position: absolute; @@ -556,6 +586,29 @@ select { margin: 0; } +.separator-gap-thin-laptop { + display: none; +} +@media screen and (min-width: $laptopWidth) { + .separator-gap-thin-laptop { + display: block !important; + width: 100%; + height: 0; + margin: 0; + } +} +.separator-gap-thin-desktop { + display: none; +} +@media screen and (min-width: $desktopWidth) { + .separator-gap-thin-desktop { + display: block !important; + width: 100%; + height: 0; + margin: 0; + } +} + .ui-base { position: fixed; top: 0; @@ -578,7 +631,7 @@ select { pointer-events: none; animation: fadeOut $animation-duration $easing-function !important; } - @media screen and (max-width: $tabletWidth) { + @media screen and (max-width: ($tabletWidth - 1)) { //1100px) { & { grid-template-areas: "mii" "tabList" "tabContent"; @@ -670,6 +723,14 @@ select { } } +canvas.scene { + width: 100% !important; + height: 100% !important; + object-fit: contain; + overflow: hidden; + transition: opacity 0.5s cubic-bezier(0.215, 0.61, 0.355, 1); +} + .tab-save { width: max-content !important; gap: 8px; @@ -958,6 +1019,19 @@ select { width: 100%; object-fit: contain; aspect-ratio: 1 / 1; + + --scale: 0.1rem; + --blur: 0; + --color: rgba(255,255,255); + // filter: drop-shadow(calc(-1 * var(--scale)) calc(-1 * var(--scale)) var(--blur) var(--color)) + // drop-shadow(0 calc(-1 * var(--scale)) var(--blur) var(--color)) + // drop-shadow(calc(1 * var(--scale)) calc(-1 * var(--scale)) var(--blur) var(--color)) + // drop-shadow(calc(-1 * var(--scale)) 0 var(--blur) var(--color)) + // drop-shadow(calc(1 * var(--scale)) 0 var(--blur) var(--color)) + // drop-shadow(calc(-1 * var(--scale)) calc(1 * var(--scale)) var(--blur) var(--color)) + // drop-shadow(0 calc(1 * var(--scale)) var(--blur) var(--color)) + // drop-shadow(calc(1 * var(--scale)) calc(1 * var(--scale)) var(--blur) var(--color)); + } span { width: 100%; @@ -987,7 +1061,7 @@ select { } } - @media screen and (max-width: $tabletWidth) { + @media screen and (max-width: ($tabletWidth - 1)) { grid-template-areas: "miiList miiList" "sidebar sidebar"; grid-template-rows: 1fr auto; .library-sidebar { @@ -1013,3 +1087,43 @@ select { flex-direction: row !important; } } + +.notify-box { + display: flex; + flex-direction: column-reverse; + position: fixed; + z-index: 9999999999; + top: 1.5rem; + left: 1.5rem; + gap: 1rem; + + > .notify { + background-color: var(--container); + border: 0.125rem solid var(--stroke); + border-radius: 0.32rem; + padding: 0.9rem 1rem; + min-width: 18rem; + display: flex; + flex-direction: column; + gap: 0.5rem; + backdrop-filter: blur(0.5rem) brightness(0.5) contrast(1.05); + pointer-events: all; + width: max-content; + } + > .notify .notify-title { + font-size: 1.25rem; + color: var(--text); + } + > .notify .notify-description { + /* . . . */ + opacity: 1; + } +} +.disable-item { + width: 120px; + font-size: 20px; + min-height: 48px; + display: flex; + justify-content: center; + align-items: center; +} diff --git a/src/ui/components/Input.ts b/src/ui/components/Input.ts index bba7b82..a55f98a 100644 --- a/src/ui/components/Input.ts +++ b/src/ui/components/Input.ts @@ -6,7 +6,7 @@ export function Input( label: string, value: string, callback: (s: string) => any, - validate?: (s: string) => boolean, + validate?: (s: string) => string | true, editor?: MiiEditor ): Html { let id = String(performance.now()); @@ -14,15 +14,25 @@ export function Input( function checkValidity(value: any) { if (editor) { editor.dirty = true; - if (validate) - if (validate(value)) { + if (validate) { + const result = validate(value); + if (result === true) { input.classOff("invalid"); - if (editor) editor.errors.set(label, false); + if (editor) + editor.errors.set(label, { + valid: true, + reason: "Valid" + }); callback(value); } else { input.classOn("invalid"); - if (editor) editor.errors.set(label, true); + if (editor) + editor.errors.set(label, { + valid: false, + reason: String(result) + }); } + } } } let input: Html = new Html("input") diff --git a/src/ui/components/Loader.ts b/src/ui/components/Loader.ts index e181f75..b1fc192 100644 --- a/src/ui/components/Loader.ts +++ b/src/ui/components/Loader.ts @@ -16,5 +16,5 @@ export default { }, hide() { if (loader) loader.classOff("active"); - }, + } }; diff --git a/src/ui/components/MiiPagedFeatureSet.ts b/src/ui/components/MiiPagedFeatureSet.ts index 925d3a0..0f34ce1 100644 --- a/src/ui/components/MiiPagedFeatureSet.ts +++ b/src/ui/components/MiiPagedFeatureSet.ts @@ -1,9 +1,10 @@ import Html from "@datkat21/html"; -import Mii from "../../external/mii-js/mii"; +// import Mii from "../../external/mii-js/mii"; +import Mii from "../../class/MiiData"; import { TabList, TabListType, type Tab } from "./TabList"; import md5 from "md5"; import { playSound } from "../../class/audio/SoundManager"; -import { RenderPart } from "../../class/MiiEditor"; +import { BodyUpdateType, MiiEditor, RenderPart } from "../../class/MiiEditor"; export enum FeatureSetType { Icon, @@ -11,7 +12,7 @@ export enum FeatureSetType { Range, Slider, Switch, - Misc, + Misc } export interface FeatureSetIconItem { type: FeatureSetType.Icon; @@ -20,8 +21,11 @@ export interface FeatureSetIconItem { icon?: string; color?: string; value: number | string; - property?: string; + property?: string[] | string; + selectedCondition?: () => boolean; + preSelectCallback?: (tmpMii: Mii) => void; forceRender?: boolean; + bodyUpdateType?: BodyUpdateType; } export interface FeatureSetTextItem { type: FeatureSetType.Text; @@ -30,6 +34,7 @@ export interface FeatureSetTextItem { label: string; sound?: string; forceRender?: boolean; + bodyUpdateType?: BodyUpdateType; } export interface FeatureSetRangeItem { type: FeatureSetType.Range; @@ -43,6 +48,7 @@ export interface FeatureSetRangeItem { property: string; label?: string; forceRender?: boolean; + bodyUpdateType?: BodyUpdateType; inverse?: boolean; } export interface FeatureSetSliderItem { @@ -55,7 +61,9 @@ export interface FeatureSetSliderItem { min: number; max: number; property: string; + label?: string; forceRender?: boolean; + bodyUpdateType?: BodyUpdateType; } export interface FeatureSetSwitchItem { type: FeatureSetType.Switch; @@ -66,6 +74,7 @@ export interface FeatureSetSwitchItem { soundOn?: string; property: string; forceRender?: boolean; + bodyUpdateType?: BodyUpdateType; isNumber?: boolean; } export interface FeatureSetMiscItem { @@ -74,6 +83,7 @@ export interface FeatureSetMiscItem { select(): any | Promise; // added to prevent error because lazy forceRender?: boolean; + bodyUpdateType?: BodyUpdateType; part?: RenderPart; } @@ -88,16 +98,18 @@ export interface FeatureSetEntry { label: string; header?: Html | string; headerIsHtml?: boolean; - validationProperty?: string; - // value - validationFunction?: Function; items: FeatureSetItem[]; } export interface FeatureSet { mii?: any; miiIsNotMii?: boolean; - onChange: (mii: Mii, forceRender: boolean, part: RenderPart) => void; + onChange: ( + mii: Mii, + forceRender: boolean, + part: RenderPart, + updateType: BodyUpdateType + ) => void; entries: Record; } @@ -107,7 +119,7 @@ export function MiiPagedFeatureSet(set: FeatureSet) { let tmpMii: Mii | any; if (set.mii) if (set.miiIsNotMii === undefined || set.miiIsNotMii === false) - tmpMii = new Mii(set.mii.encode()); + tmpMii = new Mii((set.mii as Mii).export()); else tmpMii = set.mii; else tmpMii = {}; @@ -119,7 +131,6 @@ export function MiiPagedFeatureSet(set: FeatureSet) { const entry = set.entries[key]; let property = key; - if (entry.validationProperty) property = entry.validationProperty; tabListInit.push({ icon: entry.label, @@ -144,47 +155,98 @@ export function MiiPagedFeatureSet(set: FeatureSet) { for (const item of entry.items) { const id = md5(String(Math.random() * 21412855)); - let forceRender = true; + let forceRender = true, + updateType = BodyUpdateType.None; if (item.forceRender !== undefined) { if (item.forceRender === false) { forceRender = false; } } + if (item.bodyUpdateType !== undefined) { + if (item.bodyUpdateType !== BodyUpdateType.None) { + updateType = item.bodyUpdateType; + } + } const update = () => - set.onChange(tmpMii, forceRender, item.part || RenderPart.Head); + set.onChange( + tmpMii, + forceRender, + item.part || RenderPart.Head, + updateType + ); // Used for true values (Switch colors usually use this to save time) - let value; - if (entry.validationFunction !== undefined) { - value = await entry.validationFunction(); - } else { - value = (tmpMii as Record)[property]; - } + let value = (tmpMii as Record)[property]; switch (item.type) { case FeatureSetType.Icon: - let validationProperty = property; - if (item.property) validationProperty = item.property; + let iconSelected = false; + + // js moment again + if (item.selectedCondition) + if (item.selectedCondition() === true) iconSelected = true; + else iconSelected = false; + + if (item.property) { + if (Array.isArray(item.property)) { + let tmpValue = (tmpMii as Record)[ + item.property[0] + ]; + if ( + item.property + .map((i) => tmpMii[i]) + .every((i) => i === tmpValue) + ) + value = tmpValue; + else { + value = false; + iconSelected = false; + } + } else value = (tmpMii as Record)[item.property]; + } let featureItem = new Html("div") .class("feature-item") .on("pointerenter", playHoverSound) .on("click", async () => { let value; - if (entry.validationFunction) { - value = await entry.validationFunction( - item.property, - item.value - ); - } else { - value = (tmpMii as Record)[ - validationProperty - ]; + + // i hate this + if (MiiEditor.getCurrentEditor() !== null) { + tmpMii = MiiEditor.getCurrentEditor()!.mii; } + + value = (tmpMii as Record)[property]; + const newValue = item.value; + + if (item.selectedCondition) + if (item.selectedCondition() === true) + iconSelected = true; + else iconSelected = false; + + console.log( + `condition check: value (${value}) === newValue (${newValue}), iconSelected (${iconSelected})` + ); + // PREVENT DUPLICATE UPDATES - if (value === item.value) return; - (tmpMii as Record)[key] = item.value; + if (value === newValue || iconSelected) return; + + if (item.preSelectCallback) item.preSelectCallback(tmpMii); + + if (item.property) { + if (Array.isArray(item.property)) { + for (const prop of item.property) { + (tmpMii as Record)[prop] = newValue; + } + } else { + (tmpMii as Record)[item.property] = + newValue; + } + } else { + (tmpMii as Record)[key] = newValue; + } + update(); if (item.sound) playSound(item.sound); else if (item.color) playSound("select_color"); @@ -203,11 +265,27 @@ export function MiiPagedFeatureSet(set: FeatureSet) { .classOn("is-color") .style({ "--color": item.color }); } - if (value === item.value) { + if (value === item.value || iconSelected) { + if (item.property) { + if (Array.isArray(item.property)) + if ( + item.property + .map((i) => tmpMii[i]) + .every((i) => i === value) === false + ) { + console.log("FAILED CHECK, skipping"); + debugger; + continue; + } + } featureItem.classOn("active"); } break; case FeatureSetType.Slider: + if (item.label !== undefined) { + new Html("span").text(item.label).appendTo(setList); + } + let featureSliderItem = new Html("div") .class("feature-slider") .on("pointerenter", playHoverSound) @@ -217,6 +295,11 @@ export function MiiPagedFeatureSet(set: FeatureSet) { let frontIcon = new Html("span") .html(item.iconStart) .on("click", () => { + // i hate this + if (MiiEditor.getCurrentEditor() !== null) { + tmpMii = MiiEditor.getCurrentEditor()!.mii; + } + featureSlider.val(Number(featureSlider.getValue()) - 1); (tmpMii as Record)[item.property] = Number( featureSlider.getValue() @@ -232,7 +315,7 @@ export function MiiPagedFeatureSet(set: FeatureSet) { .attr({ type: "range", min: item.min, - max: item.max, + max: item.max }) .id(id) .appendTo(featureSliderItem); @@ -241,6 +324,11 @@ export function MiiPagedFeatureSet(set: FeatureSet) { let backIcon = new Html("span") .html(item.iconEnd) .on("click", () => { + // i hate this + if (MiiEditor.getCurrentEditor() !== null) { + tmpMii = MiiEditor.getCurrentEditor()!.mii; + } + featureSlider.val(Number(featureSlider.getValue()) + 1); (tmpMii as Record)[item.property] = Number( featureSlider.getValue() @@ -257,6 +345,11 @@ export function MiiPagedFeatureSet(set: FeatureSet) { ); featureSlider.on("input", () => { + // i hate this + if (MiiEditor.getCurrentEditor() !== null) { + tmpMii = MiiEditor.getCurrentEditor()!.mii; + } + playSound("slider_tick"); (tmpMii as Record)[item.property] = Number( featureSlider.getValue() @@ -282,6 +375,11 @@ export function MiiPagedFeatureSet(set: FeatureSet) { let frontIcon = new Html("span") .html(item.iconStart) .on("click", () => { + // i hate this + if (MiiEditor.getCurrentEditor() !== null) { + tmpMii = MiiEditor.getCurrentEditor()!.mii; + } + featureRange.val( Number(featureRange.getValue()) + (item.inverse ? 1 : -1) @@ -304,7 +402,7 @@ export function MiiPagedFeatureSet(set: FeatureSet) { .attr({ type: "range", min: item.min, - max: item.max, + max: item.max }) .id(id); @@ -315,6 +413,11 @@ export function MiiPagedFeatureSet(set: FeatureSet) { let backIcon = new Html("span") .html(item.iconEnd) .on("click", () => { + // i hate this + if (MiiEditor.getCurrentEditor() !== null) { + tmpMii = MiiEditor.getCurrentEditor()!.mii; + } + featureRange.val( Number(featureRange.getValue()) + (item.inverse ? -1 : 1) @@ -342,6 +445,11 @@ export function MiiPagedFeatureSet(set: FeatureSet) { ); featureRange.on("change", () => { + // i hate this + if (MiiEditor.getCurrentEditor() !== null) { + tmpMii = MiiEditor.getCurrentEditor()!.mii; + } + const newValue = item.inverse ? item.max + item.min - Number(featureRange.getValue()) : Number(featureRange.getValue()); @@ -389,6 +497,11 @@ export function MiiPagedFeatureSet(set: FeatureSet) { .appendTo(featureSwitch); const switchToggle = (value: boolean) => { + // i hate this + if (MiiEditor.getCurrentEditor() !== null) { + tmpMii = MiiEditor.getCurrentEditor()!.mii; + } + let valueToSet: boolean | number = value; if (item.isNumber) { valueToSet = Number(valueToSet); @@ -436,12 +549,15 @@ export function MiiPagedFeatureSet(set: FeatureSet) { } window.LazyLoad.update(); - }, + } }); } if (Object.keys(set.entries).length === 1) { - tabListInit[0].select(setContainer); + let tabs = TabList(tabListInit, TabListType.NotSquare); + tabs.list.appendTo(setContainer); + tabs.content.appendTo(setContainer); + // tabListInit[0].select(setContainer); } else { let tabs = TabList(tabListInit, TabListType.NotSquare); tabs.list.appendTo(setContainer); diff --git a/src/ui/components/Modal.ts b/src/ui/components/Modal.ts index a3b914a..c32d830 100644 --- a/src/ui/components/Modal.ts +++ b/src/ui/components/Modal.ts @@ -10,7 +10,7 @@ export type ModalButton = { export const buttonsOkCancel = [ { callback() {}, text: "Cancel" }, - { callback() {}, text: "OK" }, + { callback() {}, text: "OK" } ]; function closingCallback(modal: Html) { @@ -66,8 +66,8 @@ export default { const t = e.target as HTMLElement; if (t == null) return; if ( - t.closest(".modal-content") && - !t.classList.contains("close-button") + !t.classList.contains("close-button") && + t.closest(".modal-content") !== null ) return; if (isClosing) return; @@ -181,14 +181,14 @@ export default { callback: (_: any) => { res(true); Html.qs(".modal-selectable")?.cleanup(); - }, + } }, { text: "Cancel", callback: (_: any) => { res(false); Html.qs(".modal-selectable")?.cleanup(); - }, + } } ); }); @@ -207,15 +207,15 @@ export default { { text: "Yes", type: dangerous ? "danger" : "primary", - callback: (_: any) => res(true), + callback: (_: any) => res(true) }, { text: "No", - callback: (_: any) => res(false), + callback: (_: any) => res(false) }, { text: "Cancel", - callback: (_: any) => res(false), + callback: (_: any) => res(false) } ); m.qs(".modal-body")!.classOn("flex-group"); @@ -240,11 +240,11 @@ export default { type: "primary", callback: (_: any) => { res((input.elm as HTMLInputElement).value); - }, + } }, { text: "Cancel", - callback: (_: any) => res(false), + callback: (_: any) => res(false) } ); @@ -253,7 +253,7 @@ export default { .attr({ placeholder, value, - type: isPassword === true ? "password" : "text", + type: isPassword === true ? "password" : "text" }) .on("keyup", (e) => { const ev = e as KeyboardEvent; @@ -268,5 +268,5 @@ export default { }) .appendTo(wrapper); }); - }, + } }; diff --git a/src/ui/components/Notify.ts b/src/ui/components/Notify.ts new file mode 100644 index 0000000..47fb08c --- /dev/null +++ b/src/ui/components/Notify.ts @@ -0,0 +1,40 @@ +import Html from "@datkat21/html"; +import { playSound } from "../../class/audio/SoundManager"; + +let notifyBox: Html; + +export default { + show: function ( + title: string, + description: string, + callback?: () => any, + callbackTitle = "" + ) { + if (notifyBox === undefined) + notifyBox = new Html("div").class("notify-box").appendTo("body"); + + let notifyTitle = new Html("div").class("notify-title").text(title); + let notifyDescription = new Html("div") + .class("notify-text") + .text(description); + + playSound("notice"); + + let notify = new Html("div") + .class("notify", "slideIn") + .appendMany(notifyTitle, notifyDescription) + .appendTo(notifyBox); + + if (callback) { + notify.append( + new Html("button").on("click", callback).text(callbackTitle) + ); + } + setTimeout(() => { + notify.classOff("slideIn").classOn("slideOut"); + setTimeout(() => { + notify.cleanup(); + }, 500); + }, 5000); + } +}; diff --git a/src/ui/components/TabList.ts b/src/ui/components/TabList.ts index 363545c..4d0add6 100644 --- a/src/ui/components/TabList.ts +++ b/src/ui/components/TabList.ts @@ -10,7 +10,7 @@ export interface Tab { export enum TabListType { Square, - NotSquare, + NotSquare } export function TabList(tabs: Tab[], type: TabListType = TabListType.Square) { // const tabContainer = new Html("div").class("tab-container"); diff --git a/src/ui/pages/Library.ts b/src/ui/pages/Library.ts index 10ac95b..56e6e0d 100644 --- a/src/ui/pages/Library.ts +++ b/src/ui/pages/Library.ts @@ -1,8 +1,7 @@ import Html from "@datkat21/html"; import localforage from "localforage"; import Modal, { buttonsOkCancel } from "../components/Modal"; -import Mii from "../../external/mii-js/mii"; -import { Buffer } from "../../../node_modules/buffer/index"; +import Mii from "../../class/MiiData"; import { AddButtonSounds } from "../../util/AddButtonSounds"; import { createIconCard, createMiiCard } from "../../util/miiImageUtils"; import { Config } from "../../config"; @@ -11,15 +10,16 @@ import { saveArrayBuffer } from "../../util/downloadLink"; import { RandomInt } from "../../util/Numbers"; import { cPantsColorGoldHex, - cPantsColorRedHex, + cPantsColorRedHex } from "../../class/3d/shader/fflShaderConst"; import { MiiFavoriteColorIconTable } from "../../constants/ColorTables"; -import { getString as _ } from "../../l10n/manager"; +import { _ } from "../../util/Lang"; +const __ = _(); import { replayUpdateNotice, Settings } from "./Settings"; import { adjustShaderQuery, ShaderType, - BodyType, + BodyType } from "../../constants/BodyShaderTypes"; import { getSetting } from "../../util/SettingsHelper"; import { playSound } from "../../class/audio/SoundManager"; @@ -28,13 +28,22 @@ import { miiCreateDialog } from "./library/new/_dialog"; import { importMiiConfirmation } from "./library/importDialog"; import { createCharModel, - createCharModelIcon, + makeIconFromCharModel, + FFLExpression, initCharModelTextures, - parseHexOrB64ToUint8Array, - ViewType, + parseHexOrB64ToUint8Array } from "../../external/ffl.js/ffl"; -import { getFFL, getFFLWorkerExists, getFFLWorkerMakeIcon } from "../../main"; import { WebGLRenderer } from "three"; +import { MiiExpression } from "../../external/ffl/FFLTypes"; +import Notify from "../components/Notify"; +import { dataToBase64 } from "../../util/dataConvert"; +import { + getFFL, + getFFLWorkerExists, + getFFLWorkerMakeIcon +} from "../../util/FFLLoader"; +import { ViewType } from "../../util/camera"; +import LUTShaderMaterial from "../../external/ffl.js/LUTShaderMaterial"; export const savedMiiCount = async () => (await localforage.keys()).filter((k) => k.startsWith("mii-")).length; export const newMiiId = async () => @@ -54,90 +63,139 @@ var canvas = document.createElement("canvas"); document.body.appendChild(canvas); tmpRenderer = new WebGLRenderer({ alpha: true, preserveDrawingBuffer: true }); -export const miiIconUrl = async ( - mii: Mii, +export const getMiiIcon = async ( + mii: Mii | string, source: string = "unknown", view: string = "variableiconbody", - width: number = 180, - index: number = 0 + size: number = 180, + expression: number = 0, + useBlob: boolean = true ) => { + let m: string = "", + drawBody = true, + type = ViewType.Face; + switch (view) { + case "creditIcon": + type = ViewType.CreditIcon; + break; + case "face": + case "variableiconbody": + type = ViewType.Face; + break; + case "fflmakeicon": + type = ViewType.MakeIcon; + drawBody = false; + break; + case "all_body": + type = ViewType.AllBody; + break; + case "all_body_sugar": + type = ViewType.AllBodySugar; + break; + } + + console.debug("icon view:", Object.keys(ViewType)[type]); + if (Config.renderer.useRendererServer === false) { // Momentarily create CharModel let dataURL = "undefined", - model: any; - const dataU8 = mii.encodeStudio(); + model: any, + data: Uint8Array, + miiData: Mii; + + if (typeof mii === "string") { + data = parseHexOrB64ToUint8Array(mii); + miiData = new Mii(data); + } else { + data = mii.export("studioData"); + miiData = mii; + } if (getFFLWorkerExists()) { - console.log("Asking worker thread for an icon plz!"); - const icon = await getFFLWorkerMakeIcon(dataU8, view); + console.debug("Asking worker thread for an icon plz!"); + const icon = await getFFLWorkerMakeIcon( + { + data, + type, + expression, + texResolution: 256, + additionalInfo: { + hatCommonColor: miiData.hatCommonColor, + hatFavoriteColor: miiData.hatFavoriteColor, + hatType: miiData.hatType, + pantsColor: miiData.pantsColor, + shirtColor: miiData.shirtColor, + favorite: miiData.favorite, + special: miiData.special, + temporary: miiData.temporary, + eyeSclera: miiData.eyeSclera, + wigType: miiData.wigType, + clothesType: miiData.clothesType, + shoesColor: miiData.shoesColor + }, + drawBody, + size + }, + useBlob + ); return icon; } try { - model = createCharModel( - dataU8, - undefined, - window.LUTShaderMaterial, - getFFL(), - false - ); - initCharModelTextures(model, tmpRenderer); - let realView = ViewType.MakeIcon; - switch (view) { - case "face": - case "variableiconbody": - realView = ViewType.MakeIcon; - break; - case "all_body_sugar": - realView = ViewType.MakeIcon; - break; - } - dataURL = await createCharModelIcon( - model, - tmpRenderer, - realView, - 512, - 512 + alert( + "Icon rendering is broken in your browser since we aren't using web workers, upgrade your browser and try again" ); + // model = createCharModel( + // data, + // null, + // FFLShaderMaterial, + // getFFL(), + // false + // ); // console.log(`charModel for ${mii.miiName}:`, model); } catch (e) { - console.error(`Library: Could not make icon for ${mii.miiName}: ${e}`); + let name = ""; + if (typeof mii !== "string") { + name = mii.nickname; + } + console.error(`Library: Could not make icon for ${name}: ${e}`); } finally { model.dispose(); return dataURL; } } + if (typeof mii === "string") return; + let url = Config.renderer.renderHeadshotURLNoParams; let params = new URLSearchParams(); - params.set("data", mii.encodeStudio().toString("hex")); + params.set("data", mii.exportHex("studioData")); // set shader type in query params adjustShaderQuery(params, currentShader); params.set("bodyType", currentBodyModel); params.set("type", view); - params.set("width", width.toString()); + params.set("width", size.toString()); params.set("verifyCharInfo", "0"); - params.set("miic", encodeURIComponent(mii.encode().toString("base64"))); + params.set("miic", encodeURIComponent(mii.exportHex("miic"))); params.set("version", Config.version.string); params.set("source", source ? "library" : "lookalike"); - params.set("index", index.toString()); params.set( "pantsColor", - mii.normalMii === false ? "gold" : mii.favorite === true ? "red" : "gray" + mii.special === 1 ? "gold" : mii.favorite === 1 ? "red" : "gray" ); - if (mii.extHatType !== 0) { + if (mii.hatType !== -1) { params.set( Config.renderer.hatTypeParam, - String(mii.extHatType + Config.renderer.hatTypeAdd) + String(mii.hatType + 1 + Config.renderer.hatTypeAdd) ); } - if (mii.extHatColor !== 0) { + if (mii.hatFavoriteColor !== -1) { params.set( Config.renderer.hatColorParam, - String(mii.extHatColor + Config.renderer.hatColorAdd) + String(mii.hatFavoriteColor + Config.renderer.hatColorAdd) ); } @@ -169,6 +227,178 @@ let shutdown: () => any = () => { console.log("Shutdown was called but was not set yet!"); }; export const _shutdown = () => shutdown; +export async function pushToServer() { + const miis = await Promise.all( + (await localforage.keys()) + .filter((k) => k.startsWith("mii-")) + .sort((a, b) => Number(a.split("-")[1]!) - Number(b.split("-")[1]!)) + .map(async (k) => ({ + id: k, + mii: (await localforage.getItem(k)) as string + })) + ); + + // Push + await fetch("/api/sync_library", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ miis }) + }) + .then(async (e) => { + if (!e.ok) { + const text = await e.text(); + alert("REQ FAILED - Unable to sync library data: " + text); + console.error("Failed to sync library data: " + e); + } + }) + .catch((e) => { + alert("ERROR - Unable to sync library data: " + e); + console.error("Failed to sync library data: " + e); + }); +} +function choosePersonalMii(miiList: MiiLocalforage[]) { + return new Promise((resolve) => { + const personalMiiChooseModal = Modal.modal(__("Notice"), "", "body", { + text: __("Confirm") + }); + personalMiiChooseModal.classOn("random-mii-grid"); + const container = personalMiiChooseModal.qs(".modal-body")!; + // Hide unused elements without deleting them + container + .qsa("span,.flex-group *")! + .forEach((e) => e!.style({ display: "none" })); + + container.prepend( + new Html("span") + .style({ + width: "100%", + padding: "14px 18px", + background: "var(--hover)", + color: "var(--text)", + border: "1px solid var(--stroke)", + "border-radius": "6px", + "flex-shrink": "0" + }) + .text( + __( + "Choose a Mii to be your Personal Mii, which can be used across apps. This can always be changed later in Settings." + ) + ) + ); + + let randomMiiContainer = new Html("div") + .class("random-mii-container") + .appendTo(container); + + let count = 0; + for (const mii of miiList) { + let button = new Html("button") + .append(new Html("img").attr({ src: "" })) + .appendTo(randomMiiContainer); + + const m = new Mii(mii.mii); + + function loadIcon() { + getMiiIcon(m, "lookalike").then((icon) => { + playLoadSound(); + button.qs("img")?.attr({ src: icon }); + }); + } + + button.on("click", async () => { + confirmPersonalMii(m, mii, personalMiiChooseModal).then((result) => { + if (result) { + resolve(mii.id); + } + }); + }); + + //@ts-expect-error + if (window.browserMitigations !== undefined) { + // alert("browser mitigations enabled"); + setTimeout(() => { + loadIcon(); + }, count * 100); + } else { + // alert("browser mitigations disabled"); + loadIcon(); + } + + count++; + } + }); +} +function confirmPersonalMii( + mii: Mii, + miiLocalforage: MiiLocalforage, + modalRef?: Html +) { + return new Promise((resolve) => { + const miiIcon = new Html("img").style({ + opacity: "0", + width: "210px", + height: "210px", + transition: "opacity 0.35s ease" + }); + + getMiiIcon(mii, "lookalike_preview", "all_body_sugar", 210).then((icon) => { + miiIcon.attr({ src: icon }).style({ opacity: "1" }); + }); + + Modal.modal( + // Confirmation message + __("Is this OK?"), + new Html("div") + .style({ + margin: "0 auto", + display: "flex", + "flex-direction": "column", + "align-items": "center" + }) + .classOn("col") + .append(miiIcon) + .prepend( + new Html("span").text("This will be set as your Personal Mii.") + ), + "body", + // does nothing + { + text: "Cancel", + callback() { + resolve(false); + } + }, + { + text: __("Close"), + callback() { + resolve(false); + } + }, + { + text: __("Confirm"), + type: "primary", + async callback(e) { + // Click the invisible "confirm" button to close the modal normally + if (modalRef) modalRef.qs(".flex-group button")?.elm.click(); + await fetch("/api/personal_mii", { + body: JSON.stringify({ + nickname: mii.nickname, + creator: mii.creator, + ffsd: mii.exportBase64("ffsd"), + data: mii.exportBase64("miic"), + studio: mii.exportBase64("studioData"), + store_id: miiLocalforage.id + }), + method: "POST", + headers: { "content-type": "application/json" } + }).catch(undefined); + resolve(true); + } + } + ); + }); +} + export async function Library(highlightMiiId?: string) { currentShader = await getSetting("shaderType"); currentBodyModel = await getSetting("bodyModel"); @@ -187,50 +417,80 @@ export async function Library(highlightMiiId?: string) { const sidebar = new Html("div").class("library-sidebar").appendTo(container); - sidebar.append(new Html("h1").text(_("generic.app_title"))); + sidebar.append(new Html("h1").text(__("Mii Creator"))); const libraryList = new Html("div").class("library-list").appendTo(container); - const miis = await Promise.all( - ( - await localforage.keys() - ) - .filter((k) => k.startsWith("mii-")) - .sort((a, b) => Number(a.split("-")[1]!) - Number(b.split("-")[1]!)) - .map(async (k) => ({ - id: k, - mii: (await localforage.getItem(k)) as string, - })) - ); + // Pull + let miisJson = await fetch("/api/sync_library", { + headers: { accept: "application/json" } + }).then((j) => j.json()); + + let miis: any = []; + + if (miisJson === null) { + miisJson = []; + + // Fallback to checking your local storage data + miis = await Promise.all( + (await localforage.keys()) + .filter((k) => k.startsWith("mii-")) + .sort((a, b) => Number(a.split("-")[1]!) - Number(b.split("-")[1]!)) + .map(async (k) => ({ + id: k, + mii: (await localforage.getItem(k)) as string + })) + ); + } else { + miis = miisJson; + } + + console.log(miisJson); if (miis.length === 0) { libraryList.append( new Html("div") .style({ position: "absolute", top: "2rem", left: "2rem" }) - .text("You have no Miis yet. Create one to get started!") + .text(__("You don't have any Miis. Create one to get started!")) ); + } else { + const resp = await fetch("/api/personal_mii"); + + if (!resp.ok) { + // not ok + await choosePersonalMii(miis); + } } + let miiErrorCount = 0, miiCount = 0; for (const mii of miis) { + // if localforage item isn't set already + localforage.setItem(mii.id, mii.mii); + let miiContainer = new Html("div").class("library-list-mii"); AddButtonSounds(miiContainer); + let miiData: Mii | null = null; try { - const miiData = new Mii(Buffer.from(mii.mii, "base64")); + miiData = new Mii(mii.mii); + + miiData.validate(); + + console.debug("MII DATA GOT:", miiData); // prevent error when importing converted Wii-era data - miiData.unknown1 = 0; - miiData.unknown2 = 0; + // miiData.unknown1 = 0; + // miiData.unknown2 = 0; let specialMii = false; if ( - miiData.consoleMAC[0] === 47 && - miiData.consoleMAC[1] === 249 && - miiData.consoleMAC[2] === 22 && - miiData.consoleMAC[3] === 28 && - miiData.consoleMAC[4] === 250 && - miiData.consoleMAC[5] === 173 + miiData.createId[4] === 42 && + miiData.createId[5] === 241 && + miiData.createId[6] === 22 && + miiData.createId[7] === 24 && + miiData.createId[8] === 250 && + miiData.createId[9] === 191 //193 ) { miiContainer .classOn("highlight") @@ -245,89 +505,88 @@ export async function Library(highlightMiiId?: string) { // ); miiContainer.style({ - "--color": MiiFavoriteColorIconTable[miiData.favoriteColor].top, + "--color": + MiiFavoriteColorIconTable[ + miiData.favoriteColor % + Object.keys(MiiFavoriteColorIconTable).length + ].top }); let extraData = ""; // hat - if (miiData.extHatType !== 0) { + if (miiData.hatType !== 0 - 1) { extraData += `&${Config.renderer.hatTypeParam}=${encodeURIComponent( - miiData.extHatType + Config.renderer.hatTypeAdd + miiData.hatType + 1 + Config.renderer.hatTypeAdd )}&${Config.renderer.hatColorParam}=${encodeURIComponent( - miiData.extHatColor + Config.renderer.hatColorAdd + miiData.hatFavoriteColor + Config.renderer.hatColorAdd )}`; } - let miiImage = new Html("img").class("lazy").attr({ - // "src": - // (await miiIconUrl( - // miiData, - // "library", - // "variableiconbody", - // 180, - // miiCount - // )) + extraData, - }); + let miiImage = new Html("img") + .attr({ + // "src": + // (await miiIconUrl( + // miiData, + // "library", + // "variableiconbody", + // 180, + // miiCount + // )) + extraData, + }) + .style({ opacity: "0", transition: "opacity 0.3s ease" }); - // "data-src": - // (await miiIconUrl( - // miiData, - // "library", - // "variableiconbody", - // 180, - // miiCount - // )) + extraData, - miiIconUrl(miiData, "library", "variableiconbody", 180, miiCount).then( - (r) => { - miiImage.attr({ src: r }); - } - ); + // TODO: make lazy loading work again? + + function loadIcon() { + getMiiIcon( + miiData!, + "library", + "variableiconbody", + 180, + MiiExpression.Normal + ) + .then((r) => { + miiImage.attr({ src: r }).style({ opacity: "1" }); + }) + .catch((e) => { + Notify.show( + __("Notice"), + __("Failed to load %1's icon", miiData!.nickname) + ); + }); + } + + //@ts-expect-error + if (window.browserMitigations !== undefined) { + // alert("browser mitigations enabled"); + setTimeout(() => { + loadIcon(); + }, miiCount * 100); + } else { + // alert("browser mitigations disabled"); + loadIcon(); + } // Special - if ( - miiData.normalMii === false || - miiData.favorite === true || - specialMii - ) { + if (miiData.special === 1 || miiData.favorite === 1 || specialMii) { const star = new Html("i") .style({ position: "absolute", top: "-22px", right: "-18px" }) .appendTo(miiContainer); - if (miiData.favorite === true) { + if (miiData.favorite === 1) { star.html(EditorIcons.favorite).style({ color: cPantsColorRedHex }); } - if (miiData.normalMii === false || specialMii) { + if (miiData.special === 1 || specialMii) { star.html(EditorIcons.special).style({ color: cPantsColorGoldHex }); } } - let miiName = new Html("span").text(miiData.miiName); + let miiName = new Html("span").text(miiData.nickname); let miiEditCallback = miiSelect(mii, miiData, specialMii); miiContainer.on("click", async () => { - if (hasMiiErrored === true) { - Modal.modal( - "Oops", - "This Mii hasn't loaded correctly. Do you still want to try and manage it?", - "body", - { - text: "Cancel", - }, - { - callback(e) { - miiEditCallback(); - }, - text: "Yes", - }, - { - text: "No", - } - ); - return; - } - miiEditCallback(); }); @@ -337,7 +596,7 @@ export async function Library(highlightMiiId?: string) { // prevent looping error load if (hasMiiErrored === true) return; miiImage.attr({ - src: "data:image/svg+xml," + encodeURIComponent(EditorIcons.error), + src: "data:image/svg+xml," + encodeURIComponent(EditorIcons.error) }); hasMiiErrored = true; }); @@ -361,83 +620,93 @@ export async function Library(highlightMiiId?: string) { top: mc.getBoundingClientRect().top + mc.getBoundingClientRect().height, - behavior: "smooth", + behavior: "smooth" }); } } }); - - miiCount++; } catch (e: unknown) { console.log("Oops", e); miiErrorCount++; let miiImage = new Html("img").attr({ - src: "data:image/svg+xml," + encodeURIComponent(EditorIcons.error), + src: "data:image/svg+xml," + encodeURIComponent(EditorIcons.error) }); - let miiName = new Html("span").text("?"); + let miiName = new Html("span").text( + // missing mii name + __("?") + ); + + if (miiData !== null) { + if (miiData.nickname.trim() !== "") miiName.text(miiData.nickname); + } miiContainer.appendMany(miiImage, miiName).appendTo(libraryList); miiContainer.on("click", async () => { Modal.modal( - "Oops", - "This Mii might be corrupted. Choose an option below.", + __("Warning"), + __("This Mii might be corrupted. Choose an option below."), "body", { - text: "Cancel", + text: "Cancel" }, { - text: "Download a copy", + text: __("Download a copy"), callback(e) { console.log(mii); saveArrayBuffer( - Buffer.from(mii.mii, "base64").buffer, + parseHexOrB64ToUint8Array(mii.mii).buffer, mii.id + ".miic" ); - }, + } }, { - text: "Download a copy (Base64 encoded)", + text: __("Download a copy (Base64 encoded)"), callback(e) { console.log(mii); saveArrayBuffer( - Buffer.from(mii.mii).buffer, + dataToBase64(parseHexOrB64ToUint8Array(mii.mii)), mii.id + ".miic.txt" ); - }, + } }, { - text: "Delete", + text: __("Delete"), callback(e) { Modal.modal( - "Warning", - "Are you sure you want to delete this Mii?", + __("Warning"), + __("Are you sure you want to delete this Mii?"), "body", { async callback(e) { await localforage.removeItem(mii.id); + await pushToServer(); await shutdown(); Library(); }, - text: "Yes", - type: "danger", + text: __("Yes"), + type: "danger" }, { - text: "No", + text: __("No") } ); - }, + } } ); }); } + miiCount++; } if (miiErrorCount > 0) { Modal.modal( - "Error", - `It appears that ${miiErrorCount} of your Miis have failed to load. Their data may be corrupted.\n\nIf you'd like to try and recover the Mii data, you can select the Miis with errors and choose to either save a copy or delete them.`, + __("Error"), + __( + "It appears that %1 of your Miis have failed to load. Their data may be corrupted.\n\nIf you'd like to try and recover the Mii data, you can select the Miis with errors and choose to either save a copy or delete them.", + miiErrorCount + ), "body", ...buttonsOkCancel ); @@ -448,27 +717,30 @@ export async function Library(highlightMiiId?: string) { sidebar.appendMany( new Html("div").class("sidebar-buttons").appendMany( AddButtonSounds( - new Html("button").text("Create Mii").on("click", async () => { + new Html("button").text(__("Create Mii")).on("click", async () => { miiCreateDialog(); }) ), AddButtonSounds( - new Html("button").text("Settings").on("click", async () => { - Settings(); - }) - ) - ), - new Html("div").class("sidebar-credits").appendMany( - new Html("div") - .class("flex-group") - .style({ width: "100%" }) - .appendMany( - AddButtonSounds( - new Html("button") - .text("Credits") - .on("click", async () => { + new Html("button").text(__("More Options")).on("click", async () => { + Modal.modal( + __("More Options"), + __("Select an option."), + "body", + { + text: "Cancel" + }, + { + text: __("Settings"), + callback(e) { + Settings(); + } + }, + { + text: __("Credits"), + callback(e) { var m = Modal.modal( - "Credits", + __("Credits"), "", "body", { text: "Cancel" }, @@ -477,91 +749,133 @@ export async function Library(highlightMiiId?: string) { m.qs(".modal-body span")!.cleanup(); m.qs(".modal-content")!.style({ "max-width": "100%", - "max-height": "100%", + "max-height": "100%" }); const mb = m.qs(".modal-body")!; m.qs(".modal-content")!.style({ position: "relative" }); const container = new Html("div").class("col").prependTo(mb); new Html("span") - .text("Check out the people behind Mii Creator!") + .text(__("Check out the people behind Mii Creator!")) .style({ "font-size": "20px", "flex-shrink": "0", - "margin-bottom": "-16px", + "margin-bottom": "-16px" }) .prependTo(mb); // hey stop snooping! you'll ruin the fun :( new Html("a") - .text("secret?") + .text( + // Text for when finding a Secret Mii + __("secret?") + ) .style({ "font-size": "10px", opacity: "0.3", cursor: "pointer", position: "absolute", bottom: "10px", - right: "10px", + right: "10px" }) .on("click", (e) => { m.qs("button")?.elm.click(); const mii = new Mii( - Buffer.from( - "A8EAwELycUHCpfBSXhcDbS/5Fhz6rQAAWS1KAGEAcwBtAGkAbgBlAAAAAAAAABw3ExB7ASFuQxwNZMcYAAgegg0AMEGzW4JtcwBvAHMAaQBnAG8AbgBhAGwAAAAAAMwDAAAAAAAAAAAAAAAA", - "base64" + parseHexOrB64ToUint8Array( + "BANtKwIiiUS3tZw1sDcq8RYY+sFjAGgAYQByAGwAaQBuAGUAAAAAAGMAaABhAHIAbABpAG4AZQAAAAAACAALAQAAJgMDAQYEAAIKCwQEGwIMAAkBAP8BAAABCAQACgYAZf///0wABAACFAMTARMNBAAKBAEJEP8A/wEA" ) ); - importMiiConfirmation(mii, "Mii Creator (Special Mii)"); + importMiiConfirmation( + mii, + // Label under secret Mii's name + __("Mii Creator (Special Mii)") + ); }) .appendTo(mb); createMiiCard( container, - "Austin☆²¹ / Kat21", + // Kat21's name + __("Austin☆²¹ / Kat21"), "datkat21", "https://github.com/datkat21", - "Author of Mii Creator", - "00070e555d5863674e53666975777c767c7d848b9299989f9ea1a8a9b5bc89e1e9efececf6ecf6ece8f3faf7fbfdfe" + // Kat21's attribution + __("Lead developer of Mii Creator"), + "000040030c040320020c0407050213030a0000000008000804000a07003e5303010a09031303130d04000a030d0a" ); createMiiCard( container, - "Arian", + // Arian's name + __("Arian"), "ariankordi", "https://github.com/ariankordi", - 'Creator of Mii Renderer (REAL) and was a big help with debugging many issues', + // Arian's attribution + __( + 'Creator of Mii Renderer (REAL), made FFL.js and ported Miitomo shader, and was a big help with debugging many issues' + ), "080037030d020531020c030105040a0209000001000a011004010b0100662f04000214031603140d04000a020109" ); createMiiCard( container, - "obj", + // obj (objecty)'s name + __("obj"), "objecty", "https://x.com/objecty_twitt", - "Composed the music for the site", - "00070e3b3f3c4649555e5c6675777a7a7f7e818890979ea5b4b7bebbbac188bdc6ced4ccd6cccfe3f5f8fffcff0513" + // obj (objecty)'s attribution + __("Composed the music for Mii Creator"), + "00003a030a030407020b030805040902080400010000000804000a0800403e02010311031304130d04000a040109" ); createMiiCard( container, - "Timothy", + // Timothy's name + __("Timothy"), "Timimimi", "https://github.com/Timiimiimii", - "Modeled many of the custom hats and helped with debugging", - "00070e3c4554575c616c6872818b909da0b1b7bec3cad0d78f93a1b1c0c78ce8f0f8fdf2f8f3f7ebebf6fdfcfffffb" + // Timothy's attribution + __( + "Modeled many of the custom hats and helped with debugging" + ), + "00003b0208040206040d0308050206040a0100020003005f03090b0800426d01010e16031403130f04000804070b " ); createMiiCard( container, - "David J.", + // David J.'s name + __("David J."), "dwyazzo90", "https://x.com/dwyazzo90", - "Helped with design and created the Wii U theme", + // David J.'s attribution + __( + "Helped with design, localization, and created the Wii U theme" + ), "0800450308040402020c0308060406020a0001000006000804000a0800326702010314031304190d04000a040109" ); - }) - .style({ flex: "1" }) - ), - AddButtonSounds( - new Html("button") - .text("Help/Contact") - .on("click", async () => { + createMiiCard( + container, + // Raymond's name + __("raymond"), + "raymonable", + "https://github.com/raymonable", + // Raymond's attribution + __( + "Helped with initial development for client-side rendering" + ), + "0800400308040402020c0301050400020a0000000000000804000a01004b4004000214031303190d04000a040109" + ); + createMiiCard( + container, + // MilkGalaxy's name + __("MilkGalaxy"), + "milkgalaxy", + "https://www.youtube.com/channel/UCUHVT7e1MT0Mpiv0e8WB2fQ", + // MilkGalaxy's attribution + __("Helped create custom clothing"), + "080057033c05030c030d0101060415030c0000010307000804000a1701656204000214011303230d04000a010a0a" + ); + } + }, + { + text: __("Contact"), + callback(e) { var m = Modal.modal( "Contact", "", @@ -572,7 +886,7 @@ export async function Library(highlightMiiId?: string) { m.qs(".modal-body span")!.cleanup(); m.qs(".modal-content")!.style({ "max-width": "100%", - "max-height": "100%", + "max-height": "100%" }); const mb = m.qs(".modal-body")!; m.qs(".modal-content")!.style({ position: "relative" }); @@ -581,71 +895,97 @@ export async function Library(highlightMiiId?: string) { .style({ gap: "0" }) .prependTo(mb); new Html("span") - .text("Here's where you can contact the author, Kat21") + .text(__("Here's where you can contact the author, Kat21")) .style({ "font-size": "20px", "flex-shrink": "0", - "margin-bottom": "-16px", + "margin-bottom": "-16px" }) .prependTo(mb); // hey stop snooping! you'll ruin the fun :( new Html("a") - .text("secret?") + .text(__("secret?")) .style({ "font-size": "10px", opacity: "0.3", cursor: "pointer", position: "absolute", bottom: "10px", - left: "10px", + left: "10px" }) .on("click", (e) => { m.qs("button")?.elm.click(); const mii = new Mii( - Buffer.from( - "AwEAwAAAAAAAAAAAAP91dC/5Fhz6rQAAAChiAG8AbwBlAHkAAAAAAAAAAAAAABRvEwBJBBJvQxgNVGUUABoTqAoAACmwUUhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE8TAGMyCAAANgACC2QA", - "base64" + parseHexOrB64ToUint8Array( + "BAWl18qbeYiSbgD/dXQq8RYY+sFrAGEAdAAyADEAAAAAAAAAAAAAAGIAbwBvAGUAeQAAAAAAAAAAAAAACAAAAAAAbwMECAYEDQMLMwMHEgIMAAAJAGMACgAANgMACmMASf83ARQABAACFAYTAxMKBAAKAAANN/8AYwEA" ) ); - importMiiConfirmation(mii, "Mii Creator (Special Mii)"); + importMiiConfirmation(mii, __("Mii Creator (Special Mii)")); }) .appendTo(mb); createIconCard( container, - "E-mail (Preferred)", + __("E-mail (Preferred)"), "mailto:datkat21.yt@gmail.com", "datkat21.yt@gmail.com", EditorIcons.contact_email ); createIconCard( container, - "Discord", + __("Discord"), "", "kat21", EditorIcons.contact_discord ); - createIconCard( - container, - "File an issue on GitHub", - "https://github.com/datkat21/mii-creator", - "datkat21/mii-creator", - EditorIcons.contact_github + // createIconCard( + // container, + // __("File an issue on GitHub"), + // "https://github.com/datkat21/mii-creator", + // "datkat21/mii-creator", + // EditorIcons.contact_github + // ); + } + }, + { + text: __("Manual"), + callback(e) { + Modal.alert( + __("Notice"), + __("The manual isn't finished yet. Please come back later.") ); - }) - .style({ flex: "1" }) - ) - ), - new Html("strong").text("This site is not affiliated with Nintendo."), + } + } + ); + }) + ) + ), + new Html("div").class("sidebar-credits").appendMany( + new Html("strong").text(__("This site is not affiliated with Nintendo.")), new Html("small") - .text(`${Config.version.string} (${Config.version.name})`) + .html( + `Mii Creator ${Config.version.string} by kat21 (${Config.version.name})` + ) .style({ cursor: "pointer" }) .on("click", () => { replayUpdateNotice(); - }) + }), // new Html("strong").text("Please send any feedback or bug reports either through GitHub issues or to my email: datkat21.yt@gmail.com"), + AddButtonSounds( + new Html("a") + .html( + `Subscribe to my YouTube channel!` + ) + .attr({ href: "https://youtube.com/@ngx3", target: "_blank" }) + .styleJs({ + gap: "12px", + display: "flex", + alignItems: "center", + cursor: "pointer" + }) + ) ) ); } @@ -658,8 +998,10 @@ export type MiiLocalforage = { export const miiQRConversionWarning = async (miiData: Mii) => { if (miiData.hasExtendedColors() === true) { let result = await Modal.prompt( - "Warning", - "This Mii is using extended Switch colors, but those colors will never show up if you scan this QR Code anywhere outside of this app. Is this OK?", + __("Warning"), + __( + "This Mii is using extended Switch colors, but those colors will never show up if you scan this QR Code anywhere outside of this app. Is this OK?" + ), "body", false ); @@ -671,8 +1013,10 @@ export const miiQRConversionWarning = async (miiData: Mii) => { export const miiFFSDWarning = async (miiData: Mii) => { if (miiData.hasExtendedColors() === true) { let result = await Modal.prompt( - "Warning", - 'This Mii is using extended Switch colors and/or MiiCreator features, but those features will be lost when converting to FFSD.\nUse "Save MiiCreator data" or "Save CharInfo (Switch) data" if you want to keep the data.\nIs this OK?', + __("Warning"), + __( + 'This Mii is using extended Switch colors and/or Mii Creator features, but those features will be lost when converting to FFSD.\nUse "Save Mii Creator data" if you want to keep the data.\nIs this OK?' + ), "body", false ); diff --git a/src/ui/pages/SelectionLibrary.ts b/src/ui/pages/SelectionLibrary.ts deleted file mode 100644 index 66af5c1..0000000 --- a/src/ui/pages/SelectionLibrary.ts +++ /dev/null @@ -1,384 +0,0 @@ -import Html from "@datkat21/html"; -import localforage from "localforage"; -import { MiiEditor, MiiGender } from "../../class/MiiEditor"; -import Modal from "../components/Modal"; -import Mii from "../../external/mii-js/mii"; -import { Buffer } from "../../../node_modules/buffer/index"; -import Loader from "../components/Loader"; -import { AddButtonSounds } from "../../util/AddButtonSounds"; -import { Config } from "../../config"; -import EditorIcons from "../../constants/EditorIcons"; -import { - cPantsColorGoldHex, - cPantsColorRedHex, -} from "../../class/3d/shader/fflShaderConst"; -import { MiiFavoriteColorIconTable } from "../../constants/ColorTables"; -import { FFLiDatabaseRandom_Get } from "../../external/ffl/FFLiDatabaseRandom"; -export const savedMiiCount = async () => - (await localforage.keys()).filter((k) => k.startsWith("mii-")).length; -export const newMiiId = async () => - `mii-${await savedMiiCount()}-${Date.now()}`; -export const miiIconUrl = (mii: Mii) => - `${Config.renderer.renderHeadshotURLNoParams}?data=${mii - .encodeStudio() - .toString("hex")}&shaderType=wiiu&type=face&width=180&verifyCharInfo=0`; - -export function SelectionLibrary(highlightMiiId?: string): Promise { - return new Promise(async (resolve, reject) => { - function shutdown(): Promise { - return new Promise((resolve) => { - container.class("fadeOut"); - setTimeout(() => { - container.cleanup(); - resolve(); - }, 500); - }); - } - - const container = new Html("div").class("mii-library").appendTo("body"); - - const libraryList = new Html("div") - .class("library-list") - .appendTo(container); - - const miis = await Promise.all( - ( - await localforage.keys() - ) - .filter((k) => k.startsWith("mii-")) - .sort((a, b) => Number(a.split("-")[1]!) - Number(b.split("-")[1]!)) - .map(async (k) => ({ - id: k, - mii: (await localforage.getItem(k)) as string, - })) - ); - - if (miis.length === 0) { - libraryList.appendMany( - new Html("div") - .style({ position: "absolute", top: "2rem", left: "2rem" }) - .text("You have no Miis yet. Create one to get started!"), - AddButtonSounds( - new Html("button") - .style({ position: "absolute", top: "4rem", left: "2rem" }) - .text("Create New") - .on("click", async () => { - await shutdown(); - miiCreateDialog(); - }) - ) - ); - } - for (const mii of miis) { - let miiContainer = new Html("div").class("library-list-mii"); - - AddButtonSounds(miiContainer); - - const miiData = new Mii(Buffer.from(mii.mii, "base64")); - - try { - // prevent error when importing converted Wii-era data - miiData.unknown1 = 0; - miiData.unknown2 = 0; - - // if (miiData) - // console.log( - // miiData.miiName + "'s birthPlatform:", - // miiData.deviceOrigin - // ); - - let miiImage = new Html("img").class("lazy").attr({ - "data-src": miiIconUrl(miiData), - }); - - // Special - if (miiData.normalMii === false || miiData.favorite === true) { - const star = new Html("i") - .style({ position: "absolute", top: "0", right: "0" }) - - .appendTo(miiContainer); - - if (miiData.normalMii === false) { - star.html(EditorIcons.special).style({ color: cPantsColorGoldHex }); - } - if (miiData.favorite === true) { - star.html(EditorIcons.favorite).style({ color: cPantsColorRedHex }); - } - } - // hat - if (miiData.extHatType !== 0) { - const hat = new Html("i") - .style({ position: "absolute", top: "0", left: "0" }) - .appendTo(miiContainer); - hat.html(EditorIcons.hat).style({ - color: - miiData.extHatColor !== 0 - ? MiiFavoriteColorIconTable[miiData.extHatColor - 1].top - : MiiFavoriteColorIconTable[miiData.favoriteColor].top, - }); - } - - let miiName = new Html("span").text(miiData.miiName); - - let miiEditCallback = () => { - const modal = Modal.modal( - "Mii Options", - "What would you like to do?", - "body", - { - text: "Select", - async callback() { - await shutdown(); - resolve(miiData); - }, - }, - { - text: "Cancel", - } - ); - modal - .qs(".modal-body") - ?.prepend( - new Html("img") - .attr({ src: miiIconUrl(miiData) }) - .style({ width: "180px", margin: "-18px auto 0 auto" }) - ); - }; - - miiContainer.on("click", async () => { - if (hasMiiErrored === true) { - let result = await Modal.prompt( - "Oops", - "This Mii hasn't loaded correctly. Do you still want to try and manage it?" - ); - if (result === false) return; - } - - miiEditCallback(); - }); - - let hasMiiErrored = false; - - miiImage.on("error", () => { - // prevent looping error load - if (hasMiiErrored === true) return; - miiImage.attr({ - src: "data:image/svg+xml," + encodeURIComponent(EditorIcons.error), - }); - hasMiiErrored = true; - }); - - miiContainer.appendMany(miiImage, miiName).appendTo(libraryList); - - requestAnimationFrame(() => { - if (highlightMiiId !== undefined) { - if (highlightMiiId === mii.id) { - miiContainer.classOn("highlight"); - - setTimeout(() => { - miiContainer.classOff("highlight"); - }, 2000); - - const mc = miiContainer.elm; - mc.closest(".library-list")!.scroll({ - top: - mc.getBoundingClientRect().top + - mc.getBoundingClientRect().height, - behavior: "smooth", - }); - } - } - }); - } catch (e: unknown) { - console.log("Oops", e); - } - } - window.LazyLoad.update(); - }); -} - -type MiiLocalforage = { - id: string; - mii: string; -}; - -const miiCreateDialog = () => { - Modal.modal( - "Create New", - "How would you like to create the Mii?", - "body", - { - text: "From Scratch", - callback: miiCreateFromScratch, - }, - { - text: "Enter PNID", - callback: miiCreatePNID, - }, - { - text: "Random Mii", - callback: miiCreateRandomFFL, - }, - { - text: "Random NNID", - callback: miiCreateRandom, - }, - { - text: "Import FFSD/MiiCreator data", - callback: () => { - let id: string; - let modal = Modal.modal( - "Import FFSD/MiiCreator data", - "", - "body", - { - text: "Cancel", - callback: miiCreateDialog, - }, - { - text: "Confirm", - callback() { - SelectionLibrary(id); - }, - } - ); - modal - .qsa(".modal-body .flex-group,.modal-body span")! - .forEach((q) => q!.style({ display: "none" })); - modal.qs(".modal-body")!.appendMany( - new Html("span").text("Select a FFSD or .miic file to import"), - new Html("input") - .attr({ type: "file", accept: ".ffsd,.cfsd,.miic" }) - .style({ margin: "auto" }) - .on("change", (e) => { - const target = e.target as HTMLInputElement; - console.log("Files", target.files); - - const f = new FileReader(); - - f.readAsArrayBuffer(target.files![0]); - f.onload = async () => { - try { - // prevent error when importing converted Wii-era data - const miiData = Buffer.from(f.result as ArrayBuffer); - - const mii = new Mii(miiData); - - const miiDataToSave = mii.encode().toString("base64"); - - id = await newMiiId(); - - await localforage.setItem(id, miiDataToSave); - - modal.qs(".modal-body button")!.elm.click(); - } catch (e) { - Modal.alert("Error", `Invalid Mii data: ${e}`); - target.value = ""; - } - }; - }) - ); - }, - }, - { - text: "Cancel", - callback: () => SelectionLibrary(), - } - ); -}; -const miiCreateFromScratch = () => { - function cb(gender: MiiGender) { - return () => { - new MiiEditor(gender, async (m, shouldSave) => { - if (shouldSave === true) await localforage.setItem(await newMiiId(), m); - SelectionLibrary(); - }); - }; - } - - Modal.modal( - "Create New", - "Select the Mii's gender", - "body", - { - text: "Male", - callback: cb(MiiGender.Male), - }, - { - text: "Female", - callback: cb(MiiGender.Female), - }, - { - text: "Cancel", - callback: () => miiCreateDialog(), - } - ); -}; -const miiCreatePNID = async () => { - const input = await Modal.input( - "Create New", - "Enter PNID of user..", - "Username", - "body", - false - ); - if (input === false) { - return miiCreateDialog(); - } - - Loader.show(); - - let pnid = await fetch( - Config.apis.pnidFetchURL(encodeURIComponent(input)) - ); - - Loader.hide(); - if (!pnid.ok) { - await Modal.alert("Error", `Couldn't get Mii: ${await pnid.text()}`); - return SelectionLibrary(); - } - - new MiiEditor( - 0, - async (m, shouldSave) => { - if (shouldSave === true) await localforage.setItem(await newMiiId(), m); - SelectionLibrary(); - }, - (await pnid.json()).data - ); -}; -const miiCreateRandom = async () => { - Loader.show(); - let random = await fetch(Config.apis.nnidRandomURL).then((j) => - j.json() - ); - Loader.hide(); - - new MiiEditor( - 0, - async (m, shouldSave) => { - if (shouldSave === true) await localforage.setItem(await newMiiId(), m); - SelectionLibrary(); - }, - random.data - ); -}; -const miiCreateRandomFFL = async () => { - const editMii = new Mii( - Buffer.from( - "AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn", - "base64" - ) - ); - - FFLiDatabaseRandom_Get(editMii, {}); - - new MiiEditor( - 0, - async (m, shouldSave) => { - if (shouldSave === true) await localforage.setItem(await newMiiId(), m); - SelectionLibrary(); - }, - editMii.encode().toString("base64") - ); -}; diff --git a/src/ui/pages/Settings.ts b/src/ui/pages/Settings.ts index 7f5ac6f..98a8756 100644 --- a/src/ui/pages/Settings.ts +++ b/src/ui/pages/Settings.ts @@ -4,15 +4,40 @@ import Html from "@datkat21/html"; import localforage from "localforage"; import { getMusicManager } from "../../class/audio/MusicManager"; import { getSoundManager } from "../../class/audio/SoundManager"; -import { getSetting, setSetting } from "../../util/SettingsHelper"; import { - adjustShaderQuery, - ShaderType, - BodyType, -} from "../../constants/BodyShaderTypes"; + getSetting, + setSetting, + settingsInfo +} from "../../util/SettingsHelper"; +import { adjustShaderQuery } from "../../constants/BodyShaderTypes"; import { Config } from "../../config"; +import Notify from "../components/Notify"; + +let needsToNotify = true; + +import { _ } from "../../util/Lang"; +const __ = _(); + +let resourceRefreshFlag = false; export const updateSettings = async (force: boolean = false) => { + await checkPrevSettings(); + function askRefreshNotice() { + if (needsToNotify && force === false) { + Notify.show( + __("Refresh to apply changes"), + __("Icons won't be affected until you reload."), + () => { + location.reload(); + }, + "Refresh" + ); + needsToNotify = false; + setTimeout(() => { + needsToNotify = true; + }, 5000); + } + } // Background Music let useBgm = await localforage.getItem("settings_bgm"); if (useBgm === true) getMusicManager().unmute(); @@ -32,6 +57,8 @@ export const updateSettings = async (force: boolean = false) => { const theme = await localforage.getItem("settings_theme"); if (theme === null) { await setSetting("theme", "default"); + } else if (theme === "wiiu") { + await setSetting("theme", "default"); } // Theme selector @@ -48,11 +75,25 @@ export const updateSettings = async (force: boolean = false) => { } // Update library images on shader type change + if ( + prevSetting["resourceType"] !== + (await localforage.getItem("settings_resourceType")) + ) { + console.log( + "comparing", + prevSetting["resourceType"], + "to", + await localforage.getItem("settings_resourceType"), + "FAILED" + ); + resourceRefreshFlag = true; + } if ( prevSetting["shaderType"] !== (await localforage.getItem("settings_shaderType")) ) { console.log("shaderType changed!!!"); + askRefreshNotice(); // update all images that used shader let currentShader = await getSetting("shaderType"); document.dispatchEvent(new CustomEvent("library-shader-update")); @@ -84,6 +125,7 @@ export const updateSettings = async (force: boolean = false) => { (await localforage.getItem("settings_bodyModel")) ) { console.log("bodyModel changed!!!"); + askRefreshNotice(); // update all images that used shader let bodyType = await getSetting("bodyModel"); document.dispatchEvent(new CustomEvent("library-body-update")); @@ -107,234 +149,51 @@ export const updateSettings = async (force: boolean = false) => { } }); } + + await updatePrevSettings(); }; let prevSetting: Record = {}; -export const settingsInfo: Record = { - bgm: { - type: "checkbox", - label: "Background Music", - default: true, - description: "Toggle background music depending on the theme.", - }, - sfx: { - type: "checkbox", - label: "Sound Effects", - default: true, - description: "Toggle sound effects for buttons and inputs.", - }, - cameraPan: { - type: "checkbox", - label: "Static camera in editor", - default: false, - description: - "The camera will be further away in the editor and cannot be moved.\nThis option is for if you want it to look like Mii Studio.", - }, - autoCloseCustomRender: { - type: "checkbox", - label: "Auto-close custom render menu", - default: true, - description: - "The custom render menu will automatically close when pressing save.", - }, - autoCloseQrScan: { - type: "checkbox", - label: "Auto-close QR scan menu", - default: true, - description: "The QR code scanner will disappear after a successful scan.", - }, - allowQrCamera: { - type: "checkbox", - label: "Allow using camera in QR scanner", - default: true, - description: - "When this is disabled, the camera won't be used and some errors may not appear.", - }, - - editMode: { - type: "multi", - label: "Editing Mode", - description: "Changes the default edit mode option.", - default: "3d", - choices: [ - { label: "2D", value: "2d" }, - { label: "3D (default)", value: "3d" }, - ], - }, - theme: { - type: "multi", - label: "Theme", - default: "default", - description: - "When this is set to default, your device's color theme preferences will be used.", - choices: [ - { label: "Default", value: "default" }, - { label: "Wii U", value: "wiiu" }, - ], - }, - shaderType: { - type: "multi", - label: "Shader Type", - description: - "Sorry that most of the shaders are not yet ready for use.\nUsing the Simple shader brings back the old simplistic Mii Creator lighting from the early days.\n* Does not apply to 2D mode.", - default: ShaderType.Miitomo, - choices: [ - { label: "No Lighting", value: ShaderType.LightDisabled }, - { label: "Simple", value: ShaderType.Simple }, - { label: "Toon", value: ShaderType.WiiUToon }, - { label: "Wii U (Default)", value: ShaderType.WiiU }, - { label: "Wii U (Blinn)", value: ShaderType.WiiUBlinn }, - { label: "Wii U (Alt)", value: ShaderType.WiiUFFLIconWithBody }, - { label: "Switch (WIP)", value: ShaderType.Switch, disabled: true }, - { label: "Miitomo", value: ShaderType.Miitomo }, - ], - }, - simpleShaderLegacyColors: { - type: "checkbox", - label: "Use legacy colors for Simple shader", - default: false, - condition: (settings: any) => settings.shaderType === ShaderType.Simple, - description: "Bring back the old, brighter body and pants colors.", - }, - bodyModel: { - type: "multi", - label: "Body Model", - description: - "Pose selections are different depending on the body model you use.\n* Does not apply to 2D mode.", - default: ShaderType.WiiU, - choices: [ - { label: "Wii U (default)", value: BodyType.WiiU }, - { label: "Switch", value: BodyType.Switch, disabled: true }, - { label: "Miitomo", value: BodyType.Miitomo }, - ], - }, - bodyModelHands: { - type: "checkbox", - label: "Color hands to skin tone", - default: false, - description: - "The hands of the body will match the Mii's skin tone.\n* Does not apply to 2D mode.", - }, - customRenderGreenScreen: { - type: "multi", - label: "Use background in custom render", - default: "off", - description: "The custom render will have a solid color background.", - choices: [ - { label: "Disabled", value: "off" }, - { label: "Green", value: "green" }, - { label: "Blue", value: "blue" }, - { label: "Black", value: "black" }, - { label: "White", value: "white" }, - { label: "Custom", value: "custom", isColor: true }, - ], - }, - saveData: { - type: "non-settings-multi", - label: "Save Data", - description: "Not implemented yet.", - choices: [ - { - label: "Import", - async select() { - if ( - (await Modal.prompt( - "WARNING", - "This will overwrite ALL of your currently saved Miis and delete them forever!\nPlease back up your save data before using this option.\n\nAre you certain that you understand the risk?", - "body" - )) === false - ) - return; - - const input = document.createElement("input"); - input.type = "file"; - input.accept = "application/json"; - document.body.appendChild(input); - input.click(); - requestAnimationFrame(() => { - document.body.removeChild(input); - }); - input.addEventListener("change", async (e) => { - if (input.files === null) return; - if (input.files[0] === undefined) return; - console.log(input.files); - - const reader = new FileReader(); - - reader.onload = function (event) { - const fileContent = event.target!.result; - console.log(fileContent); - }; - - reader.onerror = function (event) { - console.error("File reading error:", event); - }; - - reader.readAsText(input.files[0]); - }); - }, - disabled: true, - }, - { - label: "Export", - async select() { - let data: Record = {}; - for (const key of (await localforage.keys()).filter((k) => - k.startsWith("mii") - )) { - console.log(key); - data[key] = (await localforage.getItem(key)) as string; - } - console.log(data); - const url = URL.createObjectURL( - new Blob([JSON.stringify(data)], { type: "application/json" }) - ); - const a = document.createElement("a"); - a.href = url; - a.target = "_blank"; - a.download = "mii-editor-save-data.json"; - document.body.appendChild(a); - a.click(); - requestAnimationFrame(() => { - a.remove(); - }); - }, - disabled: true, - }, - { - label: "Delete", - type: "danger", - async select() {}, - disabled: true, - }, - ], - }, - updateNotices: { - type: "non-settings-multi", - label: "Update Notices", - description: "View the last update notice if you missed it.", - choices: [ - { - label: "Review update notice", - select() { - replayUpdateNotice(); - }, - }, - ], - }, -}; - const prefix = "settings_"; -for (const key in settingsInfo) { - let prefixedKey = prefix + key; - prevSetting[key] = await localforage.getItem(prefixedKey); +async function checkPrevSettings() { + for (const key in settingsInfo) { + let prefixedKey = prefix + key; + if (prevSetting[key] === undefined) { + prevSetting[key] = await localforage.getItem(prefixedKey); + // console.log("[checkPrevSettings] setting", key, "to", prevSetting[key]); + } + } } +async function updatePrevSettings() { + for (const key in settingsInfo) { + let prefixedKey = prefix + key; + prevSetting[key] = await localforage.getItem(prefixedKey); + // console.log("[updatePrevSettings] setting", key, "to", prevSetting[key]); + } +} + +await updatePrevSettings(); export async function Settings() { - const modal = Modal.modal("Settings", "", "body", { + const modal = Modal.modal(__("Settings"), "", "body", { text: "Cancel", + callback(e) { + if (resourceRefreshFlag) { + Modal.modal( + __("Notice"), + __("A refresh is required to apply resource changes."), + "body", + { + text: __("OK"), + callback(e) { + location.reload(); + } + } + ); + } + } }); const modalBody = modal.qs(".modal-body")!.clear(); @@ -390,7 +249,7 @@ export async function Settings() { checked: (await localforage.getItem(prefixedKey)) === true ? true - : undefined, + : undefined }) .on("input", async (e) => { prevSetting[key] = await localforage.getItem(prefixedKey); @@ -425,11 +284,11 @@ export async function Settings() { colorSpan = new Html("span").style({ width: "1.2em", height: "1.2em", - "border-radius": "6px", + "border-radius": "6px" }); colorSpan.style({ "background-color": "var(--hover)", - border: "1px solid var(--stroke)", + border: "1px solid var(--stroke)" }); const value = await localforage.getItem(prefixedKey)!; if (typeof value === "string") { @@ -447,8 +306,22 @@ export async function Settings() { : (undefined as any) ) .attr({ "data-setting": prefixedKey }) - .text(c.label) - .on("click", async (e) => { + .text( + settingsInfo[key].default === c.value + ? `${c.label} ${__("(Default)")}` + : c.label + ); + + if (colorSpan !== undefined) { + colorSpan.prependTo(multiButton); + } + + const button = AddButtonSounds(multiButton, "hover", "select_misc"); + + if (c.disabled) { + button.attr({ disabled: true }); + } else { + multiButton.on("click", async (e) => { prevSetting[key] = String( await localforage.getItem(prefixedKey) ); @@ -492,15 +365,6 @@ export async function Settings() { if (colorSpan) colorSpan.style({ "background-color": color }); } else t.classList.add("selected-setting"); }); - - if (colorSpan !== undefined) { - colorSpan.prependTo(multiButton); - } - - const button = AddButtonSounds(multiButton, "hover", "select_misc"); - - if (c.disabled) { - button.attr({ disabled: true }); } return button; @@ -547,6 +411,9 @@ export async function Settings() { }) ) ); + if (settingsInfo[key].render) { + settingsInfo[key].render(nonSettingsMulti); + } elements.set(key, nonSettingsMulti.elm); modalBody.append(nonSettingsMulti); break; @@ -558,7 +425,7 @@ export async function Settings() { export async function replayUpdateNotice() { await setSetting(`has-seen-${Config.version.string}`, false); - displayUpdateNotice(); + // displayUpdateNotice(); // Modal.modal( // "Notice", // "This display the update notice again. Do you want to continue?", @@ -575,77 +442,57 @@ export async function replayUpdateNotice() { // ); } -export async function displayUpdateNotice() { - const seenKey = `has-seen-${Config.version.string}`; - const seenValue = await getSetting(seenKey); - const notSeenLatest = seenValue === false || seenValue === null; - - // https://stackoverflow.com/a/326076 - const isInIframe = window.self !== window.top; - - // Should the user see the update popup? - const shouldSeeNotice = - // Do not show to first time users - !window.firstVisit && // NOTE: src/l10n/manager.ts - // undefined = l10n manager did not run?, false = language key is null (never ran site) - !isInIframe && // Do not show to API users - // Show if has-seen key doesn't exist - notSeenLatest; - - console.log( - `notSeenLatest: ${notSeenLatest}\nfirstVisit: ${window.firstVisit}\nshould see update notice?: ${shouldSeeNotice}` - ); - - if (window.firstVisit && !isInIframe) { - // First time? You have "seen" the current version - await setSetting(seenKey, true); - } else if (shouldSeeNotice) { - let m = Modal.modal( - `New Update: ${Config.version.string}`, - "Yes new update", // placeholder will be replaced - "body", - { - text: "OK", - } - ); - const button = m.qs("button")!.elm as HTMLButtonElement; - button.disabled = true; - - // trying not to be too pushy but i need to make users fully aware of the new update - let timer = 10; - - function update() { - if (timer !== 0) m.qs("button")!.text(`OK (${timer})`); - else { - clearInterval(i); - button.disabled = false; - button.innerText = "OK"; - - button.addEventListener("click", () => { - setSetting(`has-seen-${Config.version.string}`, true); - }); - } - } - - m.qs(".modal-body span")!.cleanup(); - // free vulnerability for you - m.qs(".modal-body")!.prepend( - new Html("div") - .style({ "max-width": "720px" }) - .html(Config.version.changelog) - ); - // Modify tags in the changelog - m.qsa("a")!.forEach((b) => { - if (b === null) return; - AddButtonSounds(b); - b.attr({ target: "_blank" }); - }); - - update(); - var i = setInterval(() => { - timer--; - update(); - }, 1000); - // await setSetting(`has-seen-${Config.version.string}`, true); - } -} +// export async function displayUpdateNotice() { +// const seenKey = `has-seen-${Config.version.string}`; +// const seenValue = await getSetting(seenKey); +// const notSeenLatest = seenValue === false || seenValue === null; + +// // https://stackoverflow.com/a/326076 +// const isInIframe = window.self !== window.top; + +// // Should the user see the update popup? +// const shouldSeeNotice = +// // Do not show to first time users +// !window.firstVisit && // NOTE: src/l10n/manager.ts +// // undefined = l10n manager did not run?, false = language key is null (never ran site) +// !isInIframe && // Do not show to API users +// // Show if has-seen key doesn't exist +// notSeenLatest; + +// console.log( +// `notSeenLatest: ${notSeenLatest}\nfirstVisit: ${window.firstVisit}\nshould see update notice?: ${shouldSeeNotice}` +// ); + +// if (window.firstVisit && !isInIframe) { +// // First time? You have "seen" the current version +// await setSetting(seenKey, true); +// } else if (shouldSeeNotice) { +// let m = Modal.modal( +// `New Update: ${Config.version.string}`, +// "Yes new update", // placeholder will be replaced +// "body", +// { +// text: "OK" +// }, +// { +// text: "Cancel" +// } +// ); + +// await setSetting(`has-seen-${Config.version.string}`, true); + +// let changelog = Config.version.changelog; + +// m.qs(".modal-body span")!.cleanup(); +// // free vulnerability for you +// m.qs(".modal-body")!.prepend( +// new Html("div").style({ "max-width": "720px" }).html(changelog) +// ); +// // Modify tags in the changelog +// m.qsa("a")!.forEach((b) => { +// if (b === null) return; +// AddButtonSounds(b); +// b.attr({ target: "_blank" }); +// }); +// } +// } diff --git a/src/ui/pages/library/export.ts b/src/ui/pages/library/export.ts index 434c2be..f2597c0 100644 --- a/src/ui/pages/library/export.ts +++ b/src/ui/pages/library/export.ts @@ -1,34 +1,39 @@ import localforage from "localforage"; -import type Mii from "../../../external/mii-js/mii"; +import Mii from "../../../class/MiiData"; import { getSetting } from "../../../util/SettingsHelper"; import Modal, { buttonsOkCancel } from "../../components/Modal"; import { miiFFSDWarning, miiQRConversionWarning, - type MiiLocalforage, + type MiiLocalforage } from "../Library"; import { QRCodeCanvas } from "../../../util/miiImageUtils"; import { downloadLink } from "../../../util/downloadLink"; import Html from "@datkat21/html"; +import { dataToBase64 } from "../../../util/dataConvert"; + +import { _ } from "../../../util/Lang"; +const __ = _(); export const miiExportData = async (mii: MiiLocalforage, miiData: Mii) => { Modal.modal( - "Export Mii", - "How would you like to save the Mii?", + __("Export Mii"), + __("How would you like to save the Mii?"), "body", { - text: "Cancel", + text: "Cancel" }, { - text: "Save MiiCreator data", + text: __("Save Mii Creator data"), + type: "primary", async callback() { - const blob = new Blob([miiData.encode()]); + const blob = new Blob([miiData.export()]); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.target = "_blank"; - a.download = miiData.miiName + ".miic"; + a.download = miiData.nickname + ".miic"; document.body.appendChild(a); a.click(); @@ -40,32 +45,56 @@ export const miiExportData = async (mii: MiiLocalforage, miiData: Mii) => { setTimeout(() => { URL.revokeObjectURL(url); }, 2000); - }, + } }, { - text: "Download other file types...", + text: __("Download other file types..."), callback(e) { Modal.modal( - "Other download types", - "Choose a file type to download", + __("Other download types"), + __("Choose a file type to download"), "body", { text: "Cancel", callback(e) { miiExportData(mii, miiData); - }, + } }, { - text: "Download FFSD file", + text: __("Download .CharInfo (Switch) file"), + async callback() { + //if (!(await miiColorConversionWarning(miiData))) return; + const blob = new Blob([miiData.export("switchCharInfo")]); + const url = URL.createObjectURL(blob); + + const a = document.createElement("a"); + a.href = url; + a.target = "_blank"; + a.download = miiData.nickname + ".charinfo"; + document.body.appendChild(a); + a.click(); + + requestAnimationFrame(() => { + a.remove(); + }); + + // free URL after some time + setTimeout(() => { + URL.revokeObjectURL(url); + }, 2000); + } + }, + { + text: __("Download .FFSD (3DS/Wii U)"), async callback() { if (!(await miiFFSDWarning(miiData))) return; - const blob = new Blob([miiData.encodeFFSD()]); + const blob = new Blob([miiData.export("ffsd")]); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.target = "_blank"; - a.download = miiData.miiName + ".ffsd"; + a.download = miiData.nickname + ".ffsd"; document.body.appendChild(a); a.click(); @@ -77,19 +106,23 @@ export const miiExportData = async (mii: MiiLocalforage, miiData: Mii) => { setTimeout(() => { URL.revokeObjectURL(url); }, 2000); - }, + } }, { - text: "Download CharInfo (Switch) file", + text: __("Download .RSD (Wii)"), async callback() { - //if (!(await miiColorConversionWarning(miiData))) return; - const blob = new Blob([miiData.encodeCharInfoSwitch()]); + Modal.alert( + __("Notice"), + __("Sorry, RSD export isn't available yet.") + ); + return; + const blob = new Blob([miiData.export("rsd")]); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.target = "_blank"; - a.download = miiData.miiName + ".charinfo"; + a.download = miiData.nickname + ".rsd"; document.body.appendChild(a); a.click(); @@ -101,32 +134,43 @@ export const miiExportData = async (mii: MiiLocalforage, miiData: Mii) => { setTimeout(() => { URL.revokeObjectURL(url); }, 2000); - }, + } } ); - }, + } }, { - text: "Save Mii as QR Code", + text: __("Save Mii as QR Code"), async callback() { if (!(await miiQRConversionWarning(miiData))) return; + if ( + !(await Modal.prompt( + __("Warning"), + __( + "Mii Creator QR codes won't save all of this Mii's data at the moment. Mii Creator will never be able to scan back these beta version QR codes and retain all the custom colors and other info. Is this OK?" + ), + "body", + true + )) + ) + return; // hack: force FFL shader for QR codes by changing the setting - const setting = await getSetting("shaderType"); - await localforage.setItem("settings_shaderType", "wiiu"); + // const setting = await getSetting("shaderType"); + // await localforage.setItem("settings_shaderType", "wiiu"); const qrCodeImage = await QRCodeCanvas( - mii.mii, + miiData, miiData.hasExtendedColors() ); // extendedColors - await localforage.setItem("settings_shaderType", setting); - downloadLink(qrCodeImage, `${miiData.miiName}_QR.png`); - }, + // await localforage.setItem("settings_shaderType", setting); + downloadLink(qrCodeImage, `${miiData.nickname}_QR.png`); + } }, { - text: "Show other raw data formats", + text: __("Show other raw data formats"), async callback() { const modal = Modal.modal( - "Miscellaneous Output Formats", - "Click inside a code block to select it.", + __("Miscellaneous Output Formats"), + __("Click inside a code block to select it."), "body", ...buttonsOkCancel ); @@ -134,41 +178,47 @@ export const miiExportData = async (mii: MiiLocalforage, miiData: Mii) => { modal .qs(".modal-content")! .style({ "max-height": "100vh", "max-width": "600px" }); - modal - .qs(".modal-body")! - .prependMany( - new Html("div").appendMany( - new Html("span").class("h4").text("CharInfo (Switch) data (Hex)"), - new Html("pre") - .class("pre-wrap", "mb-0") - .text(miiData.encodeCharInfoSwitch().toString("hex")) - ), - new Html("div").appendMany( - new Html("span").class("h4").text("MiiC (Base64)"), - new Html("pre") - .class("pre-wrap", "mb-0") - .text(miiData.encode().toString("base64")) - ), - new Html("div").appendMany( - new Html("span").class("h4").text("FFSD (Base64)"), - new Html("pre") - .class("pre-wrap", "mb-0") - .text(miiData.encodeFFSD().toString("base64")) - ), - new Html("div").appendMany( - new Html("span").class("h4").text("FFSD (Hex)"), - new Html("pre") - .class("pre-wrap", "mb-0") - .text(miiData.encodeFFSD().toString("hex")) - ), - new Html("div").appendMany( - new Html("span").class("h4").text("Mii Studio data"), - new Html("pre") - .class("pre-wrap", "mb-0") - .text(miiData.encodeStudio().toString("hex")) - ) - ); - }, + modal.qs(".modal-body")!.prependMany( + new Html("div").appendMany( + new Html("span").class("h4").text("CharInfo (Switch) data (Hex)"), + new Html("pre") + .class("pre-wrap", "mb-0") + .text(miiData.exportHex("switchCharInfo")) + ), + new Html("div").appendMany( + new Html("span").class("h4").text("Mii Creator data (Base64)"), + new Html("pre") + .class("pre-wrap", "mb-0") + .text(miiData.exportBase64("miic")) + ), + // new Html("div").appendMany( + // new Html("span") + // .class("h4") + // .text("FFSD + Mii Creator data (Base64)"), + // new Html("pre") + // .class("pre-wrap", "mb-0") + // .text(miiData.exportBase64("ffsd_append_miic")) + // ), + new Html("div").appendMany( + new Html("span").class("h4").text("FFSD (Base64)"), + new Html("pre") + .class("pre-wrap", "mb-0") + .text(miiData.exportBase64("ffsd")) + ), + new Html("div").appendMany( + new Html("span").class("h4").text("FFSD (Hex)"), + new Html("pre") + .class("pre-wrap", "mb-0") + .text(miiData.exportHex("ffsd")) + ), + new Html("div").appendMany( + new Html("span").class("h4").text("Mii Studio data"), + new Html("pre") + .class("pre-wrap", "mb-0") + .text(miiData.exportHex("studioData")) + ) + ); + } } ); }; diff --git a/src/ui/pages/library/importDialog.ts b/src/ui/pages/library/importDialog.ts index be3ee1a..f57bdfc 100644 --- a/src/ui/pages/library/importDialog.ts +++ b/src/ui/pages/library/importDialog.ts @@ -1,54 +1,62 @@ -import localforage from "localforage"; -import type Mii from "../../../external/mii-js/mii"; -import Modal from "../../components/Modal"; -import { _shutdown, Library, miiIconUrl, newMiiId } from "../Library"; -import Html from "@datkat21/html"; - -export async function importMiiConfirmation( - mii: Mii, - source: string, - title: string = "Mii Import" -) { - var m2 = Modal.modal( - title, - "", - "body", - { - text: "Cancel", - }, - { - text: "Don't Save", - }, - { - text: "Save", - async callback(e) { - const id = await newMiiId(); - await localforage.setItem(id, mii.encode().toString("base64")); - _shutdown()(); - Library(id); - }, - } - ); - - m2.qs(".modal-content")!.styleJs({ maxWidth: "100%", maxHeight: "100%" }); - m2.qs(".modal-body span")!.cleanup(); - - m2.qs(".modal-body")! - .style({ "align-items": "center", gap: "1.5rem" }) - .prependMany( - new Html("span").text(`Do you want to save this Mii?`), - new Html("small").text(source), - new Html("span") - .style({ "font-size": "20px" }) - .text(`${mii.miiName} has arrived!`), - new Html("img") - .attr({ - src: miiIconUrl(mii, "qr_code", "all_body_sugar", 260), - }) - .style({ - width: "260px", - height: "260px", - "object-fit": "contain", - }) - ); -} +import localforage from "localforage"; +import type Mii from "../../../class/MiiData"; +import Modal from "../../components/Modal"; +import { + _shutdown, + Library, + getMiiIcon, + newMiiId, + pushToServer +} from "../Library"; +import Html from "@datkat21/html"; +import { dataToBase64 } from "../../../util/dataConvert"; + +export async function importMiiConfirmation( + mii: Mii, + source: string, + title: string = "Mii Import" +) { + var m2 = Modal.modal( + title, + "", + "body", + { + text: "Cancel" + }, + { + text: "Don't Save" + }, + { + text: "Save", + async callback(e) { + const id = await newMiiId(); + await localforage.setItem(id, dataToBase64(mii.export())); + await pushToServer(); + _shutdown()(); + Library(id); + } + } + ); + + m2.qs(".modal-content")!.styleJs({ maxWidth: "100%", maxHeight: "100%" }); + m2.qs(".modal-body span")!.cleanup(); + + m2.qs(".modal-body")! + .style({ "align-items": "center", gap: "1.5rem" }) + .prependMany( + new Html("span").text(`Do you want to save this Mii?`), + new Html("small").text(source), + new Html("span") + .style({ "font-size": "20px" }) + .text(`${mii.nickname} has arrived!`), + new Html("img") + .attr({ + src: await getMiiIcon(mii, "import", "all_body_sugar", 260) + }) + .style({ + width: "260px", + height: "260px", + "object-fit": "contain" + }) + ); +} diff --git a/src/ui/pages/library/new/_dialog.ts b/src/ui/pages/library/new/_dialog.ts index dfc4ea0..e49000a 100644 --- a/src/ui/pages/library/new/_dialog.ts +++ b/src/ui/pages/library/new/_dialog.ts @@ -1,133 +1,192 @@ -import Html from "@datkat21/html"; -import Modal from "../../../components/Modal"; -import { _shutdown, Library, newMiiId } from "../../Library"; -import Mii from "../../../../external/mii-js/mii"; -import localforage from "localforage"; -import { Buffer } from "../../../../../node_modules/buffer"; -import { newFromScratch } from "./fromScratch"; -import { newFromQRCode } from "./qrCode"; -import { newFromNNID, newFromPNID } from "./nnidPnid"; -import { newFromLookalike } from "./lookalike"; -import { newFromRandonNNID } from "./randomNnid"; - -export const miiCreateDialog = () => { - const m = Modal.modal( - "New Mii", - "How would you like to create the Mii?", - "body", - { - text: "From Scratch", - type: "primary", - callback: () => { - newFromScratch(); - }, - }, - { - text: "QR Code", - callback: () => { - newFromQRCode(); - }, - }, - { - text: "FFSD/MiiCreator data", - callback: () => { - let id: string; - let modal = Modal.modal( - "Import FFSD/MiiCreator data", - "", - "body", - { - text: "Cancel", - callback: () => { - miiCreateDialog(); - }, - }, - { - text: "Confirm", - callback() { - Library(id); - }, - } - ); - modal - .qsa(".modal-body .flex-group,.modal-body span")! - .forEach((q) => q!.style({ display: "none" })); - modal.qs(".modal-body")!.appendMany( - new Html("span").text("Select a FFSD or .miic file to import"), - new Html("input") - .attr({ type: "file", accept: ".ffsd,.cfsd,.miic" }) - .style({ margin: "auto" }) - .on("change", (e) => { - const target = e.target as HTMLInputElement; - console.log("Files", target.files); - - const f = new FileReader(); - - f.readAsArrayBuffer(target.files![0]); - f.onload = async () => { - try { - // prevent error when importing converted Wii-era data - const miiData = Buffer.from(f.result as ArrayBuffer); - - const mii = new Mii(miiData); - - const miiDataToSave = mii.encode().toString("base64"); - - id = await newMiiId(); - - await localforage.setItem(id, miiDataToSave); - - _shutdown()(); - modal.qs(".modal-body button")!.elm.click(); - } catch (e) { - Modal.alert("Error", `Invalid Mii data: ${e}`); - target.value = ""; - } - }; - }) - ); - }, - }, - { - text: "Enter NNID/PNID", - callback: () => { - Modal.modal( - "Enter NNID/PNID", - "Select a service to look up", - "body", - { - text: "Cancel", - }, - { - text: "Enter Nintendo Network ID", - callback(e) { - newFromNNID(); - }, - }, - { - text: "Enter Pretendo Network ID", - callback(e) { - newFromPNID(); - }, - } - ); - }, - }, - { - text: "Choose a look-alike", - callback: () => { - newFromLookalike(); - }, - }, - { - text: "Random NNID", - callback: () => { - newFromRandonNNID(); - }, - }, - { - text: "Cancel", - } - ); - m.qs(".modal-body")!.styleJs({ maxWidth: "600px" }); -}; +import Html from "@datkat21/html"; +import Modal from "../../../components/Modal"; +import { _shutdown, Library, newMiiId, pushToServer } from "../../Library"; +import Mii from "../../../../class/MiiData"; +import localforage from "localforage"; +import { newFromScratch } from "./fromScratch"; +import { newFromQRCode } from "./qrCode"; +import { newFromNNID, newFromPNID } from "./nnidPnid"; +import { newFromLookalike } from "./lookalike"; +import { newFromRandonNNID } from "./randomNnid"; +import { dataToBase64 } from "../../../../util/dataConvert"; + +import { _ } from "../../../../util/Lang"; +import { parseHexOrB64ToUint8Array } from "../../../../external/ffl.js/ffl"; +const __ = _(); + +export const miiCreateDialog = () => { + const m = Modal.modal( + __("Create Mii"), + __("How would you like to create the Mii?"), + "body", + { + text: __("From Scratch"), + type: "primary", + callback: () => { + newFromScratch(); + } + }, + { + text: __("QR Code"), + callback: () => { + newFromQRCode(); + } + }, + { + text: __("Mii data file"), + callback: () => { + let id: string; + let modal = Modal.modal( + __("Mii data files import"), + "", + "body", + { + text: "Cancel", + callback: () => { + miiCreateDialog(); + } + }, + { + text: "Confirm", + callback() { + Library(id); + } + } + ); + // hide buttons/labels + modal + .qsa(".modal-body .flex-group,.modal-body span")! + .forEach((q) => q!.style({ display: "none" })); + modal.qs(".modal-body")!.appendMany( + new Html("span").text( + __( + "Import Mii data file(s) here. Supported formats: .ffsd/.cfsd, .miic, .charinfo, .rsd" + ) + ), + new Html("input") + .attr({ + type: "file", + accept: + ".ffsd,.cfsd,.charinfo,.rsd,.rcd," + + // add unofficial formats + ".miic,.mii,.miigx,.cfcd,.ufsd,.mnms,.nfcd,", + multiple: "on" + }) + .style({ margin: "auto" }) + .on("change", async (e) => { + const target = e.target as HTMLInputElement; + console.log("Files", target.files); + + const f = new FileReader(); + + let processed = 0; + + function loadFile(file: File) { + return new Promise((resolve) => { + f.readAsArrayBuffer(file); + f.onload = async () => { + const miiData = new Uint8Array(f.result as ArrayBuffer); + + const mii = new Mii(miiData); + + const miiDataToSave = dataToBase64(mii.export("miic")); + + id = await newMiiId(); + + await localforage.setItem(id, miiDataToSave); + await pushToServer(); + processed++; + resolve(); + }; + }); + } + for (const file of Array.from(target.files!)) { + try { + await loadFile(file).catch((e) => { + throw e; + }); + } catch (e) { + Modal.alert(__("Error"), __("Invalid Mii data: %1", e)); + console.error(e); + target.value = ""; + continue; + } + } + + if (processed > 0) { + _shutdown()(); + modal.qs(".modal-body button")!.elm.click(); + } + }) + ); + } + }, + { + text: __("Raw Mii data"), + callback: async () => { + const result = await Modal.input( + __("Raw Mii data import"), + __("Paste raw Mii data here."), + __("Hex/Base64 data"), + "body" + ); + + if (result === false) return; + + const miiData = parseHexOrB64ToUint8Array(result); + + const mii = new Mii(miiData); + + const miiDataToSave = dataToBase64(mii.export("miic")); + + let id = await newMiiId(); + + await localforage.setItem(id, miiDataToSave); + await pushToServer(); + _shutdown()(); + Library(id); + } + }, + { + text: __("Enter NNID/PNID"), + callback: () => { + Modal.modal( + __("Enter NNID/PNID"), + __("Select a service to look up"), + "body", + { + text: "Cancel" + }, + { + text: __("Enter Nintendo Network ID"), + callback(e) { + newFromNNID(); + } + }, + { + text: __("Enter Pretendo Network ID"), + callback(e) { + newFromPNID(); + } + } + ); + } + }, + { + text: __("Choose a look-alike"), + callback: () => { + newFromLookalike(); + } + }, + { + text: __("Random NNID"), + callback: () => { + newFromRandonNNID(); + } + }, + { + text: "Cancel" + } + ); + m.qs(".modal-body")!.styleJs({ maxWidth: "600px" }); +}; diff --git a/src/ui/pages/library/new/fromScratch.ts b/src/ui/pages/library/new/fromScratch.ts index 03dfc97..b74dca6 100644 --- a/src/ui/pages/library/new/fromScratch.ts +++ b/src/ui/pages/library/new/fromScratch.ts @@ -1,32 +1,36 @@ import localforage from "localforage"; import { MiiEditor, MiiGender } from "../../../../class/MiiEditor"; import Modal from "../../../components/Modal"; -import { _shutdown, Library, newMiiId } from "../../Library"; +import { _shutdown, Library, newMiiId, pushToServer } from "../../Library"; import { miiCreateDialog } from "./_dialog"; import EditorIcons from "../../../../constants/EditorIcons"; import Html from "@datkat21/html"; +import { _ } from "../../../../util/Lang"; +const __ = _(); + export const newFromScratch = () => { function cb(gender: MiiGender) { return () => { _shutdown()(); new MiiEditor(gender, async (m, shouldSave) => { if (shouldSave === true) await localforage.setItem(await newMiiId(), m); + await pushToServer(); Library(); }); }; } var m = Modal.modal( - "Create New", - "Select the Mii's gender", + __("Create Mii"), + __("Select the Mii's gender"), "body", { - text: "Male", + text: __("Male"), callback: cb(MiiGender.Male) }, { - text: "Female", + text: __("Female"), callback: cb(MiiGender.Female) }, { @@ -35,6 +39,7 @@ export const newFromScratch = () => { } ); + // Add gender select icons const genderMaleButton = m.qs(".modal-body button:nth-child(1)")!; const genderFemaleButton = m.qs(".modal-body button:nth-child(2)")!; if (genderMaleButton) { diff --git a/src/ui/pages/library/new/lookalike.ts b/src/ui/pages/library/new/lookalike.ts index b7f0596..2295196 100644 --- a/src/ui/pages/library/new/lookalike.ts +++ b/src/ui/pages/library/new/lookalike.ts @@ -1,174 +1,398 @@ -import Html from "@datkat21/html"; -import localforage from "localforage"; -import { Buffer } from "../../../../../node_modules/buffer"; -import { MiiEditor } from "../../../../class/MiiEditor"; -import { FFLiDatabaseRandom_Get } from "../../../../external/ffl/FFLiDatabaseRandom"; -import Mii from "../../../../external/mii-js/mii"; -import Modal from "../../../components/Modal"; -import { _shutdown, Library, miiIconUrl, newMiiId, playLoadSound } from "../../Library"; -import { miiCreateDialog } from "./_dialog"; - -export const newFromLookalike = async () => { - var m = Modal.modal( - "Choose a look-alike", - "", - "body", - { - text: "Cancel", - callback(e) { - miiCreateDialog(); - }, - }, - { - text: "Confirm", - } - ); - m.classOn("random-mii-grid"); - const container = m.qs(".modal-body")!; - // Hide unused elements without deleting them - container - .qsa("span,.flex-group *")! - .forEach((e) => e!.style({ display: "none" })); - - let randomMiiContainer = new Html("div") - .class("random-mii-container") - .appendTo(container); - - const group = container.qs(".flex-group")!; - - container.prepend( - new Html("span") - .style({ - width: "100%", - padding: "14px 18px", - background: "var(--hover)", - color: "var(--text)", - border: "1px solid var(--stroke)", - "border-radius": "6px", - "flex-shrink": "0", - }) - .text( - // arian wrote this for me.. because i didn't want to offend anyone having "race" in my mii creator😭 - "All of the options here are what Nintendo originally programmed in. Please let me know if you want more options added." - ) - ); - - new Html("button") - .class("primary") - .text("Reroll") - .on("click", () => reroll()) - .appendTo(group); - - let options: Record = {}; - - function makeSelect(property: string, values: HTMLOptionElement[]) { - console.log(values); - return new Html("select").appendMany(...values).on("input", (e) => { - options[property] = parseInt((e.target as HTMLSelectElement).value); - if (options[property] === -1) delete options[property]; - - console.log(options); - }); - } - - group.prependMany( - makeSelect("race", [ - new Option("Skin tone", "-1", true, true), - new Option("(Random)", "-1"), - new Option("Black", "0"), - new Option("White", "1"), - new Option("Asian", "2"), - ]), - makeSelect("gender", [ - new Option("Gender", "-1", true, true), - new Option("(Random)", "-1"), - new Option("Male", "0"), - new Option("Female", "1"), - ]), - makeSelect("hairColor", [ - new Option("Hair color", "-1", true, true), - new Option("(Random)", "-1"), - new Option("Black", "0"), - new Option("Brown", "1"), - new Option("Red", "2"), - new Option("Light brown", "3"), - new Option("Gray", "4"), - new Option("Green", "5"), - new Option("Dirty blonde", "6"), - new Option("Blonde", "7"), - ]), - makeSelect("favoriteColor", [ - new Option("Favorite color", "-1", true, true), - new Option("(Random)", "-1"), - new Option("Red", "0"), - new Option("Orange", "1"), - new Option("Yellow", "2"), - new Option("Lime", "3"), - new Option("Green", "4"), - new Option("Blue", "5"), - new Option("Cyan", "6"), - new Option("Pink", "7"), - new Option("Purple", "8"), - new Option("Brown", "9"), - new Option("White", "10"), - new Option("Black", "11"), - ]), - makeSelect("eyeColor", [ - new Option("Eye color", "-1", true, true), - new Option("(Random)", "-1"), - new Option("Black", "0"), - new Option("Gray", "1"), - new Option("Brown", "2"), - new Option("Hazel", "3"), - new Option("Blue", "4"), - new Option("Green", "5"), - ]), - makeSelect("age", [ - new Option("Age", "-1", true, true), - new Option("(Random)", "-1"), - new Option("Child", "0"), - new Option("Adult", "1"), - new Option("Elder", "2"), - ]) - ); - - function reroll() { - randomMiiContainer.clear(); - for (let i = 0; i < 21; i++) { - const randomMii = new Mii( - Buffer.from( - "AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn", - "base64" - ) - ); - FFLiDatabaseRandom_Get(randomMii, options); - - let button = new Html("button") - .append(new Html("img").attr({ src: "" })) - .appendTo(randomMiiContainer); - - miiIconUrl(randomMii, "lookalike").then((icon) => { - playLoadSound(); - button.qs("img")?.attr({ src: icon }); - }); - - const randomMiiB64 = randomMii.encode().toString("base64"); - - button.on("click", () => { - // Click the invisible "confirm" button to close the modal normally - m.qs(".flex-group button")?.elm.click(); - _shutdown()(); - new MiiEditor( - 0, - async (m, shouldSave) => { - if (shouldSave === true) - await localforage.setItem(await newMiiId(), m); - Library(); - }, - randomMiiB64 - ); - }); - } - } - reroll(); -}; +import Html from "@datkat21/html"; +import localforage from "localforage"; +import { MiiEditor } from "../../../../class/MiiEditor"; +import { + FFLiDatabaseRandom_Get, + RandomizeMii, + type FFLiDatabaseRandom_GetInit +} from "../../../../external/ffl/FFLiDatabaseRandom"; +import Mii from "../../../../class/MiiData"; +import Modal from "../../../components/Modal"; +import { + _shutdown, + Library, + getMiiIcon, + newMiiId, + playLoadSound, + pushToServer +} from "../../Library"; +import { miiCreateDialog } from "./_dialog"; +import { dataToBase64 } from "../../../../util/dataConvert"; +import { AddButtonSounds } from "../../../../util/AddButtonSounds"; + +import { _ } from "../../../../util/Lang"; +const __ = _(); + +export const newFromLookalike = async () => { + var lookalikeModal = Modal.modal( + __("Choose a look-alike"), + "", + "body", + { + text: "Cancel", + callback(e) { + miiCreateDialog(); + } + }, + { + text: __("Confirm") + } + ); + lookalikeModal.classOn("random-mii-grid"); + const container = lookalikeModal.qs(".modal-body")!; + // Hide unused elements without deleting them + container + .qsa("span,.flex-group *")! + .forEach((e) => e!.style({ display: "none" })); + + let randomMiiContainer = new Html("div") + .class("random-mii-container") + .appendTo(container); + + const group = container.qs(".flex-group")!; + + container.prepend( + new Html("span") + .style({ + width: "100%", + padding: "14px 18px", + background: "var(--hover)", + color: "var(--text)", + border: "1px solid var(--stroke)", + "border-radius": "6px", + "flex-shrink": "0" + }) + .text( + // Message used at the top of lookalike screen + __( + "All of the options here are what Nintendo originally programmed in. Please let me know if you want more options added." + ) + ) + ); + + new Html("button") + .class("primary") + .text("Reroll") + .on("click", () => reroll()) + .appendTo(group); + + let options: Record = {}; + + function makeSelect(property: string, values: HTMLOptionElement[]) { + console.log(values); + return new Html("select").appendMany(...values).on("input", (e) => { + options[property] = parseInt((e.target as HTMLSelectElement).value); + if (options[property] === -1) delete options[property]; + + console.log(options); + }); + } + + group.prependMany( + makeSelect("race", [ + new Option( + // lookalike skin tone dropdown + __("Skin tone"), + "-1", + true, + true + ), + new Option(__("(Random)"), "-1"), + new Option( + // skin tone black + __("Black"), + "0" + ), + new Option( + // skin tone white + __("White"), + "1" + ), + new Option( + // skin tone asian + __("Asian"), + "2" + ) + ]), + makeSelect("gender", [ + new Option(__("Gender"), "-1", true, true), + new Option(__("(Random)"), "-1"), + new Option(__("Male"), "0"), + new Option(__("Female"), "1") + ]), + makeSelect("hairColor", [ + new Option(__("Hair color"), "-1", true, true), + new Option(__("(Random)"), "-1"), + new Option( + // hair color black + __("Black"), + "0" + ), + new Option( + // hair color brown + __("Brown"), + "1" + ), + new Option( + // hair color reddish + __("Auburn"), + "2" + ), + new Option( + // hair color hazel + __("Hazel"), + "3" + ), + new Option( + // hair color gray + __("Gray"), + "4" + ), + new Option( + // hair color olive + __("Olive"), + "5" + ), + new Option( + // hair color dark blond + __("Medium-blonde"), + "6" + ), + new Option( + // hair color light blond + __("Light-blonde"), + "7" + ) + ]), + makeSelect("favoriteColor", [ + new Option( + // lookalike favorite color dropdown + __("Favorite color"), + "-1", + true, + true + ), + new Option(__("(Random)"), "-1"), + new Option(__("Red"), "0"), + new Option(__("Orange"), "1"), + new Option(__("Yellow"), "2"), + new Option(__("Lime"), "3"), + new Option(__("Green"), "4"), + new Option(__("Blue"), "5"), + new Option(__("Cyan"), "6"), + new Option(__("Pink"), "7"), + new Option(__("Purple"), "8"), + new Option(__("Brown"), "9"), + new Option(__("White"), "10"), + new Option(__("Black"), "11") + ]), + makeSelect("eyeColor", [ + new Option( + // lookalike eye color dropdown + __("Eye color"), + "-1", + true, + true + ), + new Option(__("(Random)"), "-1"), + new Option(__("Black"), "0"), + new Option(__("Gray"), "1"), + new Option(__("Brown"), "2"), + new Option(__("Hazel"), "3"), + new Option(__("Blue"), "4"), + new Option(__("Green"), "5") + ]), + makeSelect("age", [ + new Option( + // lookalike age dropdown + __("Age"), + "-1", + true, + true + ), + new Option(__("(Random)"), "-1"), + new Option(__("Child"), "0"), + new Option(__("Adult"), "1"), + new Option(__("Elder"), "2") + ]) + ); + + function reroll() { + randomMiiContainer.clear(); + for (let i = 0; i < 24; i++) { + const randomMii = new Mii( + "AwEAAAAAAAAAAAAAgP9wmQAAAAAAAAAAAABNAGkAaQAAAAAAAAAAAAAAAAAAAEBAAAAhAQJoRBgmNEYUgRIXaA0AACkAUkhQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMNn" + ); + FFLiDatabaseRandom_Get(randomMii, options); + + let button = new Html("button") + .append(new Html("img").attr({ src: "" })) + .appendTo(randomMiiContainer); + + getMiiIcon(randomMii, "lookalike").then((icon) => { + playLoadSound(); + button.qs("img")?.attr({ src: icon }); + }); + + button.on("click", async () => { + confirmOrReviseMii(randomMii, options, lookalikeModal); + }); + } + } + reroll(); +}; + +export function confirmOrReviseMii( + mii: Mii, + options: FFLiDatabaseRandom_GetInit, + modalRef?: Html +) { + const miiIcon = new Html("img").style({ + opacity: "0", + width: "210px", + height: "210px", + transition: "opacity 0.35s ease" + }); + + getMiiIcon(mii, "lookalike_preview", "all_body_sugar", 210).then((icon) => { + miiIcon.attr({ src: icon }).style({ opacity: "1" }); + }); + + Modal.modal( + // Confirmation message + __("Is this OK?"), + new Html("div").style({ margin: "0 auto" }).append(miiIcon), + "body", + // does nothing + { + text: "Cancel" + }, + { + text: __("Close"), + type: "danger" + }, + { + text: __("Revise"), + callback(e) { + let currentMii = mii; + + const m = Modal.modal( + "Revise", + new Html("div").appendMany( + new Html("span").style({ margin: "0 auto" }).text( + // lookalike revise screen message + __("Click any to reroll") + ), + new Html("div").class("menu").style({ + display: "flex", + "flex-direction": "column", + gap: "0.5rem" + }) + ), + "body", + { text: "Cancel" }, + { + text: __("Done"), + callback(e) { + confirmOrReviseMii(currentMii, options, modalRef); + } + } + ); + + m.qs(".modal-content")!.style({ + height: "max-content", + "max-height": "100vh" + }); + + const menuDiv = m.qs(".menu")!; + + function regenerate() { + menuDiv.clear(); + + let rows: Mii[][] = []; + for (let i = 0; i < 9; i++) { + const row = Math.floor(i / 3); + const col = i % 3; + + if (rows[row] === undefined) { + rows[row] = []; + } + + if (i === 4) { + // Use the current version of the Mii for the middle icon + rows[row][col] = currentMii; + } else { + // do random generation + var mii = new Mii(currentMii.export()); + console.log("options:", options); + RandomizeMii(mii, options); + rows[row][col] = mii; + } + } + + // Populate + for (const row of rows) { + const rowElm = new Html("div") + .style({ display: "flex", gap: "0.5rem" }) + .appendTo(menuDiv); + + for (const child of row) { + const button = new Html("button").style({ + padding: "0" + }); + const img = new Html("img") + .style({ + width: "108px", + height: "108px", + opacity: "0", + transition: "opacity 0.2s ease" + }) + .appendTo(button); + rowElm.append(button); + + button.on("click", (e) => { + e.preventDefault(); + currentMii = child; + requestAnimationFrame(() => { + regenerate(); + }); + }); + + getMiiIcon( + child, + "lookalike_regenerate", + "fflmakeicon", + 108 + ).then((icon) => { + playLoadSound(); + img.attr({ src: icon }).style({ opacity: "1" }); + }); + } + } + } + + regenerate(); + } + }, + { + text: __("Done"), + type: "primary", + callback(e) { + const randomMiiB64 = dataToBase64(mii.export("miic")); + // Click the invisible "confirm" button to close the modal normally + if (modalRef) modalRef.qs(".flex-group button")?.elm.click(); + _shutdown()(); + new MiiEditor( + 0, + async (m, shouldSave) => { + if (shouldSave === true) + await localforage.setItem(await newMiiId(), m); + await pushToServer(); + Library(); + }, + randomMiiB64 + ); + } + } + ); +} diff --git a/src/ui/pages/library/new/nnidPnid.ts b/src/ui/pages/library/new/nnidPnid.ts index a004187..7cc497e 100644 --- a/src/ui/pages/library/new/nnidPnid.ts +++ b/src/ui/pages/library/new/nnidPnid.ts @@ -3,14 +3,17 @@ import { MiiEditor } from "../../../../class/MiiEditor"; import { Config } from "../../../../config"; import Loader from "../../../components/Loader"; import Modal from "../../../components/Modal"; -import { _shutdown, Library, newMiiId } from "../../Library"; +import { _shutdown, Library, newMiiId, pushToServer } from "../../Library"; import { miiCreateDialog } from "./_dialog"; +import { _ } from "../../../../util/Lang"; +const __ = _(); + export const newFromNNID = async () => { const input = await Modal.input( - "Nintendo Network ID", - "Enter NNID of user..", - "Username", + __("Nintendo Network ID"), + __("Enter NNID of user.."), + __("Username"), "body", false ); @@ -20,15 +23,13 @@ export const newFromNNID = async () => { Loader.show(); - let nnid = await fetch( - Config.apis.nnidFetchURL(encodeURIComponent(input)) - ); + let nnid = await fetch(Config.apis.nnidFetchURL(encodeURIComponent(input))); const result = await nnid.json(); Loader.hide(); if (result.error !== undefined) { - await Modal.alert("Error", `Couldn't get Mii: ${result.error}`); + await Modal.alert(__("Error"), __("Couldn't get Mii: %1", result.error)); return; } @@ -37,6 +38,7 @@ export const newFromNNID = async () => { 0, async (m, shouldSave) => { if (shouldSave === true) await localforage.setItem(await newMiiId(), m); + await pushToServer(); Library(); }, result.data @@ -45,9 +47,9 @@ export const newFromNNID = async () => { export const newFromPNID = async () => { const input = await Modal.input( - "Pretendo Network ID", - "Enter PNID of user..", - "Username", + __("Pretendo Network ID"), + __("Enter PNID of user.."), + __("Username"), "body", false ); @@ -57,13 +59,14 @@ export const newFromPNID = async () => { Loader.show(); - let pnid = await fetch( - Config.apis.pnidFetchURL(encodeURIComponent(input)) - ); + let pnid = await fetch(Config.apis.pnidFetchURL(encodeURIComponent(input))); Loader.hide(); if (!pnid.ok) { - await Modal.alert("Error", `Couldn't get Mii: ${await pnid.text()}`); + await Modal.alert( + __("Error"), + __("Couldn't get Mii: %1", await pnid.text()) + ); return; } @@ -72,6 +75,7 @@ export const newFromPNID = async () => { 0, async (m, shouldSave) => { if (shouldSave === true) await localforage.setItem(await newMiiId(), m); + await pushToServer(); Library(); }, (await pnid.json()).data diff --git a/src/ui/pages/library/new/qrCode.ts b/src/ui/pages/library/new/qrCode.ts index ba53e1a..b5fb98b 100644 --- a/src/ui/pages/library/new/qrCode.ts +++ b/src/ui/pages/library/new/qrCode.ts @@ -1,129 +1,134 @@ -import Html from "@datkat21/html"; -import { Buffer } from "../../../../../node_modules/buffer"; -import Mii from "../../../../external/mii-js/mii"; -import { - initQrCam, - QrScanDataType, - QrScannerError, - setQRCallback, - startScanner, -} from "../../../../util/DecodeQRCode"; -import { getSetting } from "../../../../util/SettingsHelper"; -import Modal from "../../../components/Modal"; -import { importMiiConfirmation } from "../importDialog"; -import { miiCreateDialog } from "./_dialog"; - -export const newFromQRCode = async () => { - let qrReturnToMenu = true; - const m = Modal.modal("Scan QR Code", "", "body", { - text: "Cancel", - callback: () => { - m.qs("#stop-camera")!.elm.click(); - if (qrReturnToMenu) miiCreateDialog(); - }, - }); - - const mb = m.qs(".modal-body")!; - - // delete the button container - m.qs(".modal-body")! - .qsa("*")! - .forEach((item) => item!.cleanup()); - m.qs(".modal-content")?.styleJs({ maxHeight: "100%", maxWidth: "600px" }); - - mb.appendMany( - // camera stuff container - new Html("div").classOn("col").appendMany( - new Html("span").attr({ for: "cam-list" }).text("Select camera:"), - new Html("select") - .id("cam-list") - .appendMany( - new Html("option") - .attr({ value: "environment", selected: "yes" }) - .text("Back Camera (default)"), - new Html("option") - .attr({ value: "user" }) - .text("User/Front Facing Camera"), - new Html("option") - .attr({ value: "device-camera", disabled: true }) - .text("(Open the camera for more options)") - ), - new Html("div") - .class("flex-group") - .appendMany( - new Html("button").id("start-camera").text("Start camera"), - new Html("button").id("stop-camera").text("Stop camera") - ), - new Html("video").id("qr-video").styleJs({ maxWidth: "100%" }), - new Html("span").id("file-upload").text("Or upload an image:"), - new Html("input").attr({ - type: "file", - id: "file-input", - accept: "image/*", - }) - ) - ); - - startScanner(mb.qs("#cam-list")!.elm); - initQrCam( - mb.qs("#cam-list")!.elm, - mb.qs("#start-camera")!.elm as HTMLButtonElement, - mb.qs("#stop-camera")!.elm as HTMLButtonElement, - mb.qs("#file-input")!.elm as HTMLInputElement - ); - - if ((await getSetting("allowQrCamera")) === false) { - // Hide unused items if camera isn't allowed - mb.qsa('span[for="cam-list"], #cam-list, .flex-group, video')!.forEach( - (e) => e!.style({ display: "none" }) - ); - // prevent video element from taking up space - mb.qs("video")!.style({ position: "fixed" }); - mb.qs("span#file-upload")!.text( - "Camera is disabled in settings.\n\nUpload an image:" - ); - } - - // confirmation function - async function qrImportConfirmation(mii: Mii, source: string) { - const shouldClose = await getSetting("autoCloseQrScan"); - if (shouldClose) { - // hack to close modal and stop scanner - qrReturnToMenu = false; - m.qs(".modal-header button")?.elm.click(); - } - importMiiConfirmation(mii, source, "Mii QR Scanned"); - } - - // initialize qr callback for data handling - setQRCallback((data: Buffer, dataType: QrScanDataType) => { - try { - var mii: Mii; - switch (dataType) { - case QrScanDataType.GenericWiiU3ds: - mii = new Mii(data); - qrImportConfirmation(mii, "3DS/Wii U QR Code"); - mii = new Mii(data); - qrImportConfirmation(mii, "3DS/Wii U QR Code"); - break; - case QrScanDataType.ExtraDataTL: - Modal.alert( - "Notice", - new Html("span").html( - 'Tomodachi Life QR codes aren\'t supported yet. Use Mii Renderer (REAL) to scan it.' - ) - ); - break; - case QrScanDataType.ExtraDataMiiC: - mii = new Mii(data); - qrImportConfirmation(mii, "Mii Creator QR Code"); - break; - } - } catch (e) { - QrScannerError( - "An error occurred when reading the data.\nPlease check the console for more information." - ); - console.error(e); - } - }); -}; +import Html from "@datkat21/html"; +import Mii from "../../../../class/MiiData"; +import { + initQrCam, + QrScanDataType, + QrScannerError, + setQRCallback, + startScanner +} from "../../../../util/DecodeQRCode"; +import { getSetting } from "../../../../util/SettingsHelper"; +import Modal from "../../../components/Modal"; +import { importMiiConfirmation } from "../importDialog"; +import { miiCreateDialog } from "./_dialog"; + +import { _ } from "../../../../util/Lang"; +const __ = _(); + +export const newFromQRCode = async () => { + let qrReturnToMenu = true; + const m = Modal.modal(__("Scan QR Code"), "", "body", { + text: "Cancel", + callback: () => { + m.qs("#stop-camera")!.elm.click(); + if (qrReturnToMenu) miiCreateDialog(); + } + }); + + const mb = m.qs(".modal-body")!; + + // delete the button container + m.qs(".modal-body")! + .qsa("*")! + .forEach((item) => item!.cleanup()); + m.qs(".modal-content")?.styleJs({ maxHeight: "100%", maxWidth: "600px" }); + + mb.appendMany( + // camera stuff container + new Html("div").classOn("col").appendMany( + new Html("span").attr({ for: "cam-list" }).text(__("Select camera:")), + new Html("select") + .id("cam-list") + .appendMany( + new Html("option") + .attr({ value: "environment", selected: "yes" }) + .text(__("Back Camera (default)")), + new Html("option") + .attr({ value: "user" }) + .text(__("User/Front Facing Camera")), + new Html("option") + .attr({ value: "device-camera", disabled: true }) + .text(__("(Open the camera for more options)")) + ), + new Html("div") + .class("flex-group") + .appendMany( + new Html("button").id("start-camera").text(__("Start camera")), + new Html("button").id("stop-camera").text(__("Stop camera")) + ), + new Html("video").id("qr-video").styleJs({ maxWidth: "100%" }), + new Html("span").id("file-upload").text(__("Or upload an image:")), + new Html("input").attr({ + type: "file", + id: "file-input", + accept: "image/*" + }) + ) + ); + + startScanner(mb.qs("#cam-list")!.elm); + initQrCam( + mb.qs("#cam-list")!.elm, + mb.qs("#start-camera")!.elm as HTMLButtonElement, + mb.qs("#stop-camera")!.elm as HTMLButtonElement, + mb.qs("#file-input")!.elm as HTMLInputElement + ); + + if ((await getSetting("allowQrCamera")) === false) { + // Hide unused items if camera isn't allowed + mb.qsa('span[for="cam-list"], #cam-list, .flex-group, video')!.forEach( + (e) => e!.style({ display: "none" }) + ); + // prevent video element from taking up space + mb.qs("video")!.style({ position: "fixed" }); + mb.qs("span#file-upload")!.text( + __("Camera is disabled in settings.\n\nUpload an image:") + ); + } + + // confirmation function + async function qrImportConfirmation(mii: Mii, source: string) { + const shouldClose = await getSetting("autoCloseQrScan"); + if (shouldClose) { + // hack to close modal and stop scanner + qrReturnToMenu = false; + m.qs(".modal-header button")?.elm.click(); + } + importMiiConfirmation(mii, source, __("Mii QR Scanned")); + } + + // initialize qr callback for data handling + setQRCallback((data: Uint8Array, dataType: QrScanDataType) => { + try { + var mii: Mii; + switch (dataType) { + case QrScanDataType.GenericWiiU3ds: + mii = new Mii(data); + qrImportConfirmation(mii, __("3DS/Wii U QR Code")); + break; + case QrScanDataType.ExtraDataTL: + Modal.alert( + __("Notice"), + new Html("span").html( + __( + 'Tomodachi Life QR codes aren\'t supported yet. Use %1 to scan it.', + __("Mii Renderer (REAL)") + ) + ) + ); + break; + case QrScanDataType.ExtraDataMiiC: + mii = new Mii(data); + qrImportConfirmation(mii, __("Mii Creator QR Code")); + break; + } + } catch (e) { + QrScannerError( + __( + "An error occurred when reading the data.\nPlease check the console for more information." + ) + ); + console.error(e); + } + }); +}; diff --git a/src/ui/pages/library/new/randomNnid.ts b/src/ui/pages/library/new/randomNnid.ts index 609d5b8..aeb8853 100644 --- a/src/ui/pages/library/new/randomNnid.ts +++ b/src/ui/pages/library/new/randomNnid.ts @@ -2,13 +2,11 @@ import localforage from "localforage"; import { MiiEditor } from "../../../../class/MiiEditor"; import { Config } from "../../../../config"; import Loader from "../../../components/Loader"; -import { _shutdown, Library, newMiiId } from "../../Library"; +import { _shutdown, Library, newMiiId, pushToServer } from "../../Library"; export const newFromRandonNNID = async () => { Loader.show(); - let random = await fetch(Config.apis.nnidRandomURL).then((j) => - j.json() - ); + let random = await fetch(Config.apis.nnidRandomURL).then((j) => j.json()); Loader.hide(); _shutdown()(); @@ -16,6 +14,7 @@ export const newFromRandonNNID = async () => { 0, async (m, shouldSave) => { if (shouldSave === true) await localforage.setItem(await newMiiId(), m); + await pushToServer(); Library(); }, random.data diff --git a/src/ui/pages/library/render/customRender.ts b/src/ui/pages/library/render/customRender.ts index 1917dce..7acf8d9 100644 --- a/src/ui/pages/library/render/customRender.ts +++ b/src/ui/pages/library/render/customRender.ts @@ -1,657 +1,684 @@ -import Html from "@datkat21/html"; -import type CameraControls from "camera-controls"; -import { Color, Vector3, type Mesh } from "three"; -import { GLTFExporter } from "three/examples/jsm/Addons.js"; -import { Buffer } from "../../../../../node_modules/buffer"; -import { - CameraPosition, - Mii3DScene, - SetupType, -} from "../../../../class/3DScene"; -import { RenderPart } from "../../../../class/MiiEditor"; -import { Config } from "../../../../config"; -import Mii from "../../../../external/mii-js/mii"; -import { AddButtonSounds } from "../../../../util/AddButtonSounds"; -import { downloadLink, saveArrayBuffer } from "../../../../util/downloadLink"; -import { ArrayNum } from "../../../../util/Numbers"; -import { getSetting } from "../../../../util/SettingsHelper"; -import { - FeatureSetType, - MiiPagedFeatureSet, - type FeatureSetEntry, -} from "../../../components/MiiPagedFeatureSet"; -import Modal from "../../../components/Modal"; -import { importMiiConfirmation } from "../importDialog"; -import { traverse3DMaterialFix } from "../util/3DModel"; -import { cMaterialName } from "../../../../class/3d/shader/fflShaderConst"; - -enum ExpressionModifier { - HideNose, - HideNoseAndMask, -} - -const expressionTable: { - name: string; - id: string; - modifier?: ExpressionModifier; -}[] = [ - { name: "Normal", id: "normal" }, - { name: "Smile", id: "smile" }, - { name: "Anger", id: "anger" }, - { name: "Sorrow", id: "sorrow" }, - { name: "Surprise", id: "surprise" }, - { name: "Blink", id: "blink" }, - { name: "Normal (open mouth)", id: "normal_open_mouth" }, - { name: "Smile (open mouth)", id: "smile_open_mouth" }, - { name: "Anger (open mouth)", id: "anger_open_mouth" }, - { name: "Surprise (open mouth)", id: "surprise_open_mouth" }, - { name: "Sorrow (open mouth)", id: "sorrow_open_mouth" }, - { name: "Blink (open mouth)", id: "blink_open_mouth" }, - { name: "Wink (left eye open)", id: "wink_left" }, - { name: "Wink (right eye open)", id: "wink_right" }, - { name: "Wink (left eye and mouth open)", id: "wink_left_open_mouth" }, - { name: "Wink (right eye and mouth open)", id: "wink_right_open_mouth" }, - { name: "Wink (left eye open and smiling)", id: "like_wink_left" }, - { name: "Wink (right eye open and smiling)", id: "like_wink_right" }, - { name: "Frustrated", id: "frustrated" }, - { name: "Bored", id: "19" }, - { name: "Bored open mouth", id: "20" }, - { name: "Sigh mouth straight", id: "21" }, - { name: "Sigh", id: "22" }, - { name: "Disgusted mouth straight", id: "23" }, - { name: "Disgusted", id: "24" }, - { name: "Love", id: "25" }, - { name: "Love mouth open", id: "26" }, - { name: "Determined mouth straight", id: "27" }, - { name: "Determined", id: "28" }, - { name: "Cry mouth straight", id: "29" }, - { name: "Cry", id: "30" }, - { name: "Big smile mouth straight", id: "31" }, - { name: "Big smile", id: "32" }, - { name: "Cheeky", id: "33" }, - { name: "Resolve eyes funny mouth", id: "35" }, - { name: "Resolve eyes funny mouth open", id: "36" }, - { name: "Smug", id: "37" }, - { name: "Smug mouth open", id: "38" }, - { name: "Resolve", id: "39" }, - { name: "Resolve mouth open", id: "40" }, - { name: "Unbelievable", id: "41" }, - { name: "Cunning", id: "43" }, - { name: "Raspberry", id: "45" }, - { name: "Innocent", id: "47" }, - { name: "Cat", id: "49", modifier: ExpressionModifier.HideNose }, - { name: "Dog", id: "51", modifier: ExpressionModifier.HideNose }, - { name: "Tasty", id: "53" }, - { name: "Money mouth straight", id: "55" }, - { name: "Money", id: "56" }, - { name: "Confused mouth straight", id: "57" }, - { name: "Confused", id: "58" }, - { name: "Cheerful mouth straight", id: "59" }, - { name: "Cheerful", id: "60" }, - { name: "Blank", id: "61", modifier: ExpressionModifier.HideNoseAndMask }, - { name: "Grumble mouth straight", id: "63" }, - { name: "Grumble", id: "64" }, - { name: "Moved mouth straight", id: "65" }, - { name: "Moved (aka pleading face)", id: "66" }, - { name: "Singing mouth small", id: "67" }, - { name: "Singing", id: "68" }, - { name: "Stunned", id: "69" }, -]; - -export async function customRender(miiData: Mii) { - const modal = Modal.modal("Custom Render", "", "body", { - text: "Cancel", - }); - const body = modal.qs(".modal-body")!.classOn("responsive-row-lg").clear(); - modal.qs(".modal-content")!.styleJs({ - width: "100%", - height: "100%", - maxWidth: "100%", - maxHeight: "100%", - }); - let parent = new Html("div") - .style({ - display: "flex", - flex: "1", - background: "var(--container-solid)", - "border-radius": "12px", - "flex-shrink": "0", - height: "100%", - overflow: "hidden", - "justify-content": "center", - "align-items": "center", - }) - .appendTo(body); - let parentBox = new Html("div") - .style({ "aspect-ratio": "1 / 1", height: "100%" }) - .appendTo(parent); - let tabsContent = new Html("div") - .classOn("tab-content") - .style({ flex: "1", height: "100%", overflow: "auto" }) - .appendTo(body); - - let configuration = { - fov: 30, - pose: 0, - expression: "normal", - renderWidth: 720, - renderHeight: 720, - cameraPosition: 1, - animSpeed: 100, - }; - - const base64Data = miiData.encodeStudio().toString("hex"); - - let poseListPerBodyModel: Record = { - wii: 4, - wiiu: 14, - switch: 5, - miitomo: 16, - }; - - let bodyModelSetting = (await getSetting("bodyModel")) as string; - - let poseCount = 0; - if (bodyModelSetting in poseListPerBodyModel) { - poseCount = poseListPerBodyModel[bodyModelSetting] + 1; - } - - console.log(bodyModelSetting); - - let controls: CameraControls, - rotationFactor = Math.PI / 8; - - const e: Record = { - camera: { - label: "Camera", - header: - "Use mouse or touch to move the camera around.\nUsing touch, rotate the camera around with one finger, and drag with two fingers to pan. Pinch with two fingers to zoom.\nIf you like this site, please consider sharing it with others and credit me or the site when you post your renders! 🙂", - items: [ - { - type: FeatureSetType.Slider, - property: "fov", - iconStart: "FOV", - iconEnd: "", - min: 5, - max: 90, - part: RenderPart.Face, - }, - { - type: FeatureSetType.Misc, - html: new Html("div").class("flex-group", "col").appendMany( - new Html("label").text("Position"), - new Html("div").class("flex-group").appendMany( - new Html("button").text("Center horizontally").on("click", () => { - const newPosition = scene.focusCamera( - CameraPosition.MiiFullBody, - true, - false, - true - )!; - let target = new Vector3(); - controls.getTarget(target); - target.x = newPosition.x; - controls.moveTo(target.x, target.y, target.z); - }), - new Html("button").text("Center vertically").on("click", () => { - const newPosition = scene.focusCamera( - CameraPosition.MiiFullBody, - true, - false, - true - )!; - let target = new Vector3(); - controls.getTarget(target); - target.y = newPosition.y; - controls.moveTo(target.x, target.y, target.z); - }), - new Html("button").text("Reset").on("click", () => { - const newPosition = scene.focusCamera( - CameraPosition.MiiFullBody, - true, - false, - true - )!; - scene - .getControls() - .moveTo(newPosition.x, newPosition.y, newPosition.z); - }) - ), - new Html("label").text("Rotate"), - new Html("div").class("flex-group").appendMany( - new Html("button").text("Up").on("click", () => { - scene - .getControls() - .rotateTo( - controls.azimuthAngle, - controls.polarAngle - rotationFactor - ); - }), - new Html("button").text("Down").on("click", () => { - scene - .getControls() - .rotateTo( - controls.azimuthAngle, - controls.polarAngle + rotationFactor - ); - }), - new Html("button").text("Left").on("click", () => { - scene - .getControls() - .rotateTo( - controls.azimuthAngle - rotationFactor, - controls.polarAngle - ); - }), - new Html("button").text("Right").on("click", () => { - scene - .getControls() - .rotateTo( - controls.azimuthAngle + rotationFactor, - controls.polarAngle - ); - }), - new Html("button").text("Reset").on("click", () => { - controls.rotateTo(0, Math.PI / 2); - }) - ) - ), - select() {}, - }, - ], - }, - // TODO - // scene: { - // label: "Scene", - // header: "Change the default background color in Settings.", - // items: [ - // { - // type: FeatureSetType.Misc, - // html: new Html("div") - // .class("input-group") - // .appendMany( - // new Html("label").text("H"), - // new Html("button").text("H"), - // new Html("button").text("H"), - // new Html("button").text("H") - // ), - // select() { - // /* ... */ - // }, - // }, - // ], - // }, - pose: { - label: "Pose", - header: new Html("div").appendMany( - new Html("span").html( - 'Change the Body Model option in Settings to get many different options of poses!

Do you like the Mii that does the poses? His name is "dummy". ' - ), - new Html("a").text("Click here").on("click", (e) => { - // goodbye custom render :( - scene.shutdown(); - parent.cleanup(); - modal.qs("button")?.elm.click(); - - // easter egg !!!!! - const mii = new Mii( - Buffer.from( - "A0EAwAAAAAAAAAAAgP9wmS/5Fhz6rQAAAABkAHUAbQBtAHkAAAAAAAAAAAAAAEBAEgAeARJoYxoHA2YWIRQTZgwAAAEAUkhQTQBpAGkAQwByAGUAYQB0AG8AcgAAAK6gAAAICAAAAAAAAGQA", - "base64" - ) - ); - importMiiConfirmation(mii, "Mii Creator (Special Mii)"); - }), - new Html("span").html(" to obtain him in your library :)") - ), - headerIsHtml: true, - items: ArrayNum(poseCount).map((k) => ({ - type: FeatureSetType.Icon, - value: k, - // icon: String(k), - icon: - k === 0 - ? "None" - : ``, - part: RenderPart.Head, - })), - }, - expression: { - label: "Expression", - items: expressionTable.map((k) => ({ - type: FeatureSetType.Icon, - value: String(k.id), - icon: ``, - part: RenderPart.Head, - })), - }, - animation: { - label: "Animation", - header: - "This usually only applies to Miitomo body model which has animations for its poses.", - items: [ - { - type: FeatureSetType.Slider, - property: "animSpeed", - part: RenderPart.Face, - iconStart: "0x", - iconEnd: "2x", - min: 0, - max: 200, - }, - ], - }, - }; - - // very hacky way to use feature set to create tabs - MiiPagedFeatureSet({ - mii: configuration, - miiIsNotMii: true, - entries: e as any, - onChange(mii, forceRender, part) { - configuration = mii as any; - updateConfiguration(); - // console.log("updated", configuration); - oldConfiguration = Object.assign({}, configuration); - }, - }) - .style({ height: "auto" }) - .appendTo(tabsContent); - - let playing = true; - - // Don't automatically play animations on Wii U body model - if (bodyModelSetting === "wiiu") playing = false; - - let pauseButton = AddButtonSounds( - new Html("button") - .text(playing ? "Pause Animation" : "Pause Animation") - .on("click", () => { - if (playing === true) { - playing = false; - } else { - playing = true; - } - scene.anim.forEach((anim) => { - if (playing === true) { - anim.paused = false; - pauseButton.text("Pause Animation"); - } else { - anim.paused = true; - pauseButton.text("Play Animation"); - } - }); - }) - .appendTo(tabsContent) - ); - - new Html("button") - .text("Download PNG") - .on("click", finalizeRender) - .appendTo(tabsContent); - - new Html("button") - .text("Download 3D model") - .on("click", save3DModel) - .appendTo(tabsContent); - - function resize() { - let { width, height } = parentBox.elm.getBoundingClientRect(); - - if (width < 1024) { - width = 1024; - } - if (height < 1024) { - height = 1024; - } - - scene.resize(width, height); // min. 1024x1024px - scene.getRendererElement().style.height = "100%"; - scene.getRendererElement().style.width = "unset"; - } - - window.addEventListener("resize", () => { - resize(); - }); - - const scene = new Mii3DScene( - miiData, - parentBox.elm, - SetupType.Screenshot, - (renderer) => {} - ); - controls = scene.getControls(); - - //@ts-expect-error testing - window.scene = scene; - - // Background color - const useGreenScreen = await getSetting("customRenderGreenScreen"); - if (useGreenScreen !== "off") { - let color: string = useGreenScreen; - switch (useGreenScreen) { - case "green": - color = "#00ff00"; - break; - case "blue": - color = "#0000ff"; - break; - case "white": - color = "#ffffff"; - break; - case "black": - color = "#000000"; - break; - } - - scene.getScene().background = new Color(color); - } - - let oldConfiguration: any = { - fov: 30, - pose: 0, - expression: 0, - renderWidth: 720, - renderHeight: 720, - cameraPosition: 1, - animSpeed: 1, - }; - - function updateConfiguration() { - scene.getCamera()!.fov = configuration.fov; - scene.getCamera()!.updateProjectionMatrix(); - switch (configuration.cameraPosition) { - case 0: - scene.focusCamera(CameraPosition.MiiHead); - break; - case 1: - scene.focusCamera(CameraPosition.MiiFullBody); - break; - } - - // Only update expression when expression is changed. - // console.log(oldConfiguration.expression, configuration.expression); - if (oldConfiguration.expression !== configuration.expression) { - scene.traverseAddFaceMaterial( - scene.getHead() as Mesh, - `&data=${encodeURIComponent(base64Data)}&expression=${ - configuration.expression - }&width=896&verifyCharInfo=0` - ); - } - - const expr = expressionTable.find((e) => e.id === configuration.expression); - - if (expr) - if (typeof expr.modifier !== "undefined") { - switch (expr.modifier) { - case ExpressionModifier.HideNose: - // should be hiding the nose - scene.getHead()!.traverse((o) => { - if ((o as Mesh).isMesh !== true) return; - const m = o as Mesh; - const modulateType = m.geometry.userData.modulateType; - - if ( - modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSE || - modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSELINE - ) { - m.visible = false; - } else { - m.visible = true; - } - }); - break; - case ExpressionModifier.HideNoseAndMask: - // should be hiding the nose and the mask - scene.getHead()!.traverse((o) => { - if ((o as Mesh).isMesh !== true) return; - const m = o as Mesh; - const modulateType = m.geometry.userData.modulateType; - - if ( - modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_MASK || - modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSE || - modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSELINE - ) { - m.visible = false; - } else { - m.visible = true; - } - }); - break; - } - } else { - scene.getHead()!.traverse((o) => { - if ((o as Mesh).isMesh !== true) return; - const m = o as Mesh; - m.visible = true; - }); - } - - const pose = "Pose." + String(configuration.pose).padStart(2, "0"); - - if (scene.animations.get(`${scene.type}-${pose}`)) { - scene.swapAnimation(pose); - if (playing === false) { - scene.anim.forEach((a) => (a.paused = true)); - } - } else { - scene.swapAnimation("Wait"); - if (playing === false) { - scene.anim.forEach((a) => (a.paused = true)); - } - } - scene.anim.forEach((a) => { - a.timeScale = configuration.animSpeed / 100; - }); - - // Fix animations being too fast - scene.anim.get(scene.type)!.timeScale *= 0.5; - } - - //@ts-expect-error - window.scene = scene; - - scene.init().then(async () => { - await scene.updateMiiHead(); - - if (playing === false) { - scene.anim.forEach((anim) => { - if (playing === true) { - anim.paused = false; - pauseButton.text("Pause Animation"); - } else { - anim.paused = true; - pauseButton.text("Play Animation"); - } - }); - } - - scene.focusCamera(CameraPosition.MiiFullBody, true, false); - parentBox.append(scene.getRendererElement()); - }); - - let shouldClose = await getSetting("autoCloseCustomRender"); - - const rendererElm = scene.getRendererElement(); - - function finalizeRender() { - rendererElm.toBlob((blob) => { - const image = new Image(rendererElm.width, rendererElm.height); - image.src = URL.createObjectURL(blob!); - image.onload = () => { - downloadLink( - image.src, - `${miiData.miiName}_all_body_${new Date().toJSON()}.png` - ); - if (shouldClose) { - scene.shutdown(); - parent.cleanup(); - modal.qs("button")?.elm.click(); - } - }; - }); - } - - async function save3DModel() { - const shaderSetting = await getSetting("shaderType"); - // const bodyModelHands = await getSetting("bodyModelHands"); - - if (shaderSetting === "none") { - const result = await Modal.prompt( - "Notice", - "3D model export looks best when using the Wii U shader, which you aren't using.\nThis may result in incorrect color output. Do you still want to continue?", - "body" - ); - if (result === false) return; - } - - // fix up the materials - const mats = await traverse3DMaterialFix(scene); - let i = 0; - - const exporter = new GLTFExporter(); - exporter.parse( - scene.getScene(), - (gltf) => { - console.log("gltf", gltf); - if (gltf instanceof ArrayBuffer) { - saveArrayBuffer( - gltf, - `${miiData.miiName}_all_body_${new Date().toJSON()}.glb` - ); - } - if (shouldClose) { - scene.shutdown(); - parent.cleanup(); - modal.qs("button")?.elm.click(); - } else { - // Revert back all materials. - i = 0; - scene.getScene().traverse((o) => { - if ((o as Mesh).isMesh !== true) return; - - const m = o as Mesh; - - m.material = mats.get(i); - - i++; - }); - } - }, - (error) => { - console.error("Oops, something went wrong:", error); - }, - { - binary: true, - } - ); - } -} +import Html from "@datkat21/html"; +import type CameraControls from "camera-controls"; +import { Color, Vector3, type Mesh } from "three"; +import { GLTFExporter } from "three/examples/jsm/Addons.js"; +import { + CameraPosition, + Mii3DScene, + SetupType +} from "../../../../class/3DScene"; +import { RenderPart } from "../../../../class/MiiEditor"; +import { Config } from "../../../../config"; +// import Mii from "../../../../external/mii-js/mii"; +import Mii from "../../../../class/MiiData"; +import { AddButtonSounds } from "../../../../util/AddButtonSounds"; +import { downloadLink, saveArrayBuffer } from "../../../../util/downloadLink"; +import { ArrayNum } from "../../../../util/Numbers"; +import { getSetting } from "../../../../util/SettingsHelper"; +import { + FeatureSetType, + MiiPagedFeatureSet, + type FeatureSetEntry, + type FeatureSetIconItem +} from "../../../components/MiiPagedFeatureSet"; +import Modal from "../../../components/Modal"; +import { importMiiConfirmation } from "../importDialog"; +import { traverse3DMaterialFix } from "../util/3DModel"; +import { cMaterialName } from "../../../../class/3d/shader/fflShaderConst"; +import { getMiiIcon } from "../../Library"; +import { parseHexOrB64ToUint8Array } from "../../../../external/ffl.js/ffl"; + +import { _ } from "../../../../util/Lang"; +const __ = _(); + +enum ExpressionModifier { + HideNose, + HideNoseAndMask +} + +const expressionTable: { + name: string; + id: number; + modifier?: ExpressionModifier; +}[] = [ + { name: "Normal", id: 0 }, + { name: "Smile", id: 1 }, + { name: "Anger", id: 2 }, + { name: "Sorrow", id: 3 }, + { name: "Surprise", id: 4 }, + { name: "Blink", id: 5 }, + { name: "Normal (open mouth)", id: 6 }, + { name: "Smile (open mouth)", id: 7 }, + { name: "Anger (open mouth)", id: 8 }, + { name: "Surprise (open mouth)", id: 9 }, + { name: "Sorrow (open mouth)", id: 10 }, + { name: "Blink (open mouth)", id: 11 }, + { name: "Wink (left eye open)", id: 12 }, + { name: "Wink (right eye open)", id: 13 }, + { name: "Wink (left eye and mouth open)", id: 14 }, + { name: "Wink (right eye and mouth open)", id: 15 }, + { name: "Wink (left eye open and smiling)", id: 16 }, + { name: "Wink (right eye open and smiling)", id: 17 }, + { name: "Frustrated", id: 18 }, + { name: "Bored", id: 19 }, + { name: "Bored open mouth", id: 20 }, + { name: "Sigh mouth straight", id: 21 }, + { name: "Sigh", id: 22 }, + { name: "Disgusted mouth straight", id: 23 }, + { name: "Disgusted", id: 24 }, + { name: "Love", id: 25 }, + { name: "Love mouth open", id: 26 }, + { name: "Determined mouth straight", id: 27 }, + { name: "Determined", id: 28 }, + { name: "Cry mouth straight", id: 29 }, + { name: "Cry", id: 30 }, + { name: "Big smile mouth straight", id: 31 }, + { name: "Big smile", id: 32 }, + { name: "Cheeky", id: 33 }, + { name: "Resolve eyes funny mouth", id: 35 }, + { name: "Resolve eyes funny mouth open", id: 36 }, + { name: "Smug", id: 37 }, + { name: "Smug mouth open", id: 38 }, + { name: "Resolve", id: 39 }, + { name: "Resolve mouth open", id: 40 }, + { name: "Unbelievable", id: 41 }, + { name: "Cunning", id: 43 }, + { name: "Raspberry", id: 45 }, + { name: "Innocent", id: 47 }, + { name: "Cat", id: 49, modifier: ExpressionModifier.HideNose }, + { name: "Dog", id: 51, modifier: ExpressionModifier.HideNose }, + { name: "Tasty", id: 53 }, + { name: "Money mouth straight", id: 55 }, + { name: "Money", id: 56 }, + { name: "Confused mouth straight", id: 57 }, + { name: "Confused", id: 58 }, + { name: "Cheerful mouth straight", id: 59 }, + { name: "Cheerful", id: 60 }, + { name: "Blank", id: 61, modifier: ExpressionModifier.HideNoseAndMask }, + { name: "Grumble mouth straight", id: 63 }, + { name: "Grumble", id: 64 }, + { name: "Moved mouth straight", id: 65 }, + { name: "Moved (aka pleading face)", id: 66 }, + { name: "Singing mouth small", id: 67 }, + { name: "Singing", id: 68 }, + { name: "Stunned", id: 69 } +]; + +export async function customRender(miiData: Mii) { + const modal = Modal.modal("Custom Render", "", "body", { + text: "Cancel" + }); + const body = modal.qs(".modal-body")!.classOn("responsive-row-lg").clear(); + modal.qs(".modal-content")!.styleJs({ + width: "100%", + height: "100%", + maxWidth: "100%", + maxHeight: "100%", + backgroundColor: "var(--container-solid)" + }); + let parent = new Html("div") + .style({ + display: "flex", + flex: "1", + background: "var(--container-solid)", + "border-radius": "12px", + "flex-shrink": "0", + height: "100%", + overflow: "hidden", + "justify-content": "center", + "align-items": "center" + }) + .appendTo(body); + let parentBox = new Html("div") + .style({ "aspect-ratio": "1 / 1", height: "100%" }) + .appendTo(parent); + let tabsContent = new Html("div") + .classOn("tab-content") + .style({ flex: "1", height: "100%", overflow: "auto", gap: "0.5rem" }) + .appendTo(body); + + let configuration = { + fov: 30, + pose: 0, + expression: "0", + renderWidth: 720, + renderHeight: 720, + animSpeed: 100 + }; + + const miiDataHex = miiData.exportHex("studioData"); + + let poseListPerBodyModel: Record = { + wii: 4, + wiiu: 14, + switch: 5, + miitomo: 16 + }; + + let bodyModelSetting = (await getSetting("bodyModel")) as string; + + let poseCount = 0; + if (bodyModelSetting in poseListPerBodyModel) { + poseCount = poseListPerBodyModel[bodyModelSetting] + 1; + } + + console.log(bodyModelSetting); + + let controls: CameraControls, + rotationFactor = Math.PI / 8; + + const e: Record = { + camera: { + label: __("Camera"), + header: new Html("span").html( + __( + "Use mouse or touch to move the camera around.\nUsing touch, rotate the camera around with one finger, and drag with two fingers to pan. Pinch with two fingers to zoom.\nIf you like this site, PLEASE consider sharing it with others by crediting the site when you post your renders! 😉" + ) + ), + headerIsHtml: true, + items: [ + { + type: FeatureSetType.Slider, + property: "fov", + iconStart: "FOV", + iconEnd: "", + min: 5, + max: 90, + part: RenderPart.Face + }, + { + type: FeatureSetType.Misc, + html: new Html("div").class("flex-group", "col").appendMany( + new Html("label").text(__("Position")), + new Html("div").class("flex-group").appendMany( + new Html("button").text(__("Center X")).on("click", () => { + const newPosition = scene.focusCamera( + CameraPosition.MiiFullBody, + true, + false, + true + )!; + let target = new Vector3(); + controls.getTarget(target); + target.x = newPosition.x; + controls.moveTo(target.x, target.y, target.z); + }), + new Html("button").text(__("Center Y")).on("click", () => { + const newPosition = scene.focusCamera( + CameraPosition.MiiFullBody, + true, + false, + true + )!; + let target = new Vector3(); + controls.getTarget(target); + target.y = newPosition.y; + controls.moveTo(target.x, target.y, target.z); + }), + new Html("button").text(__("Center to body")).on("click", () => { + scene.focusCamera(CameraPosition.MiiFullBody, true, false)!; + }), + new Html("button").text(__("Center to head")).on("click", () => { + scene.focusCamera(CameraPosition.MiiHead, true, false)!; + }) + ), + new Html("label").text(__("Rotate")), + new Html("div").class("flex-group").appendMany( + new Html("button").text(__("Up")).on("click", () => { + scene + .getControls() + .rotateTo( + controls.azimuthAngle, + controls.polarAngle - rotationFactor + ); + }), + new Html("button").text(__("Down")).on("click", () => { + scene + .getControls() + .rotateTo( + controls.azimuthAngle, + controls.polarAngle + rotationFactor + ); + }), + new Html("button").text(__("Left")).on("click", () => { + scene + .getControls() + .rotateTo( + controls.azimuthAngle - rotationFactor, + controls.polarAngle + ); + }), + new Html("button").text(__("Right")).on("click", () => { + scene + .getControls() + .rotateTo( + controls.azimuthAngle + rotationFactor, + controls.polarAngle + ); + }), + new Html("button").text(__("Reset")).on("click", () => { + controls.rotateTo(0, Math.PI / 2); + }) + ) + ), + select() {} + } + ] + }, + // TODO + // scene: { + // label: "Scene", + // header: "Change the default background color in Settings.", + // items: [ + // { + // type: FeatureSetType.Misc, + // html: new Html("div") + // .class("input-group") + // .appendMany( + // new Html("label").text("H"), + // new Html("button").text("H"), + // new Html("button").text("H"), + // new Html("button").text("H") + // ), + // select() { + // /* ... */ + // }, + // }, + // ], + // }, + pose: { + label: __("Pose"), + header: new Html("div").appendMany( + new Html("span").html( + __( + "Change the Body Model option in Settings to get many different options of poses!" + ) + + "

" + + __( + 'Do you like the Mii that does the poses? His name is "dummy".' + ) + + " " + ), + new Html("a").text(__("Click here")).on("click", (e) => { + // goodbye custom render :( + scene.shutdown(); + parent.cleanup(); + modal.qs("button")?.elm.click(); + + // easter egg !!!!! + const mii = new Mii( + parseHexOrB64ToUint8Array( + "BAUajXYYt5uiVoD/cJkq8RYY+sFNAGkAaQBDAHIAZQBhAHQAbwByAGQAdQBtAG0AeQAAAAAAAAAAAAAACAAAAAAAQAMACAYDBwMLCAMEEgMNAAAJAGMAAAAACAQACgEAHv///0AABAACFAMTAxMMBAAAAQEKX/8A/wEA" + ) + ); + importMiiConfirmation(mii, __("Mii Creator (Special Mii)")); + }), + new Html("span").html(" " + __("to obtain him in your library :)")) + ), + headerIsHtml: true, + items: ArrayNum(poseCount).map((k) => ({ + type: FeatureSetType.Icon, + value: k, + // icon: String(k), + icon: + k === 0 + ? "None" + : ``, + part: RenderPart.Head + })) + }, + expression: { + label: __("Expression"), + items: [] + }, + animation: { + label: __("Animation"), + header: __("Control the animation speed."), + items: [ + { + type: FeatureSetType.Slider, + property: "animSpeed", + part: RenderPart.Face, + iconStart: "0x", + iconEnd: "2x", + min: 0, + max: 200 + } + ] + } + }; + + expressionTable.forEach(async (k) => { + let iconTag; + + if (Config.renderer.useRendererServer) { + iconTag = ``; + } else { + const icon = await getMiiIcon( + miiData, + "customRender", + "fflmakeicon", + 128, + k.id, + false + ).catch((e) => { + console.error("oh noes, Icon didnt Load", e); + }); + iconTag = ``; + } + + const expressionItem = { + type: FeatureSetType.Icon, + value: String(k.id), + icon: iconTag, + part: RenderPart.Head + }; + e["expression"].items.push(expressionItem as FeatureSetIconItem); + }); + + // very hacky way to use feature set to create tabs + MiiPagedFeatureSet({ + mii: configuration, + miiIsNotMii: true, + entries: e as any, + onChange(mii, forceRender, part) { + configuration = mii as any; + updateConfiguration(); + // console.log("updated", configuration); + oldConfiguration = Object.assign({}, configuration); + } + }) + .style({ height: "auto" }) + .appendTo(tabsContent); + + let playing = true; + + // Don't automatically play animations on Wii U body model + if (bodyModelSetting === "wiiu") playing = false; + + let pauseButton = AddButtonSounds( + new Html("button") + .text(playing ? __("Pause Animation") : __("Pause Animation")) + .on("click", () => { + if (playing === true) { + playing = false; + } else { + playing = true; + } + scene.anim.forEach((anim) => { + if (playing === true) { + anim.paused = false; + pauseButton.text(__("Pause Animation")); + } else { + anim.paused = true; + pauseButton.text(__("Play Animation")); + } + }); + }) + .appendTo(tabsContent) + ); + + new Html("button") + .text(__("Save Render")) + .on("click", finalizeRender) + .appendTo(tabsContent); + + // new Html("button") + // .text(__("Download 3D model")) + // .on("click", save3DModel) + // .appendTo(tabsContent); + + function resize() { + let { width, height } = parentBox.elm.getBoundingClientRect(); + + if (width < 1024) { + width = 1024; + } + if (height < 1024) { + height = 1024; + } + + scene.resize(width, height); // min. 1024x1024px + scene.getRendererElement().style.height = "100%"; + scene.getRendererElement().style.width = "unset"; + } + + window.addEventListener("resize", () => { + resize(); + }); + + const scene = new Mii3DScene( + miiData, + parentBox.elm, + SetupType.Screenshot, + (renderer) => {} + ); + controls = scene.getControls(); + + //@ts-expect-error testing + window.scene = scene; + + // Background color + const useGreenScreen = await getSetting("customRenderGreenScreen"); + if (useGreenScreen !== "off") { + let color: string = useGreenScreen; + switch (useGreenScreen) { + case "green": + color = "#00ff00"; + break; + case "blue": + color = "#0000ff"; + break; + case "white": + color = "#ffffff"; + break; + case "black": + color = "#000000"; + break; + } + + scene.getScene().background = new Color(color); + } + + let oldConfiguration: any = { + fov: 30, + pose: 0, + expression: "0", + renderWidth: 720, + renderHeight: 720, + animSpeed: 1 + }; + + function updateConfiguration() { + scene.getCamera()!.fov = configuration.fov; + scene.getCamera()!.updateProjectionMatrix(); + + // Only update expression when expression is changed. + // console.log(oldConfiguration.expression, configuration.expression); + if (oldConfiguration.expression !== configuration.expression) { + scene.traverseAddFaceMaterial( + scene.getHead() as Mesh, + `&data=${encodeURIComponent(miiDataHex)}&expression=${ + configuration.expression + }&width=896&verifyCharInfo=0` + ); + } + + const expr = expressionTable.find( + (e) => e.id === parseInt(configuration.expression as any as string) + ); + // console.log(configuration); + + if (expr) { + // console.log(expr); + if (typeof expr.modifier !== "undefined") { + switch (expr.modifier) { + case ExpressionModifier.HideNose: + // should be hiding the nose + scene.getHead()!.traverse((o) => { + if ((o as Mesh).isMesh !== true) return; + const m = o as Mesh; + const modulateType = m.geometry.userData.modulateType; + + if ( + modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSE || + modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSELINE + ) { + m.visible = false; + } else { + m.visible = true; + } + }); + break; + case ExpressionModifier.HideNoseAndMask: + // should be hiding the nose and the mask + scene.getHead()!.traverse((o) => { + if ((o as Mesh).isMesh !== true) return; + const m = o as Mesh; + const modulateType = m.geometry.userData.modulateType; + + if ( + modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_MASK || + modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSE || + modulateType === cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSELINE + ) { + m.visible = false; + } else { + m.visible = true; + } + }); + break; + } + } else { + scene.getHead()!.traverse((o) => { + if ((o as Mesh).isMesh !== true) return; + const m = o as Mesh; + m.visible = true; + }); + } + } + + const pose = "Pose." + String(configuration.pose).padStart(2, "0"); + + if (scene.animations.get(`${scene.type}-${pose}`)) { + scene.swapAnimation(pose); + if (playing === false) { + scene.anim.forEach((a) => (a.paused = true)); + } + } else { + scene.swapAnimation("Wait"); + if (playing === false) { + scene.anim.forEach((a) => (a.paused = true)); + } + } + scene.anim.forEach((a) => { + a.timeScale = configuration.animSpeed / 100; + }); + + // Fix animations being too fast + scene.anim.get(scene.type)!.timeScale *= 0.5; + } + + //@ts-expect-error + window.scene = scene; + + scene.init().then(async () => { + await scene.updateMiiHead(); + + if (playing === false) { + scene.anim.forEach((anim) => { + if (playing === true) { + anim.paused = false; + pauseButton.text(__("Pause Animation")); + } else { + anim.paused = true; + pauseButton.text(__("Play Animation")); + } + }); + } + + scene.focusCamera(CameraPosition.MiiFullBody, true, false); + parentBox.append(scene.getRendererElement()); + + scene.resize(); + }); + + let shouldClose = await getSetting("autoCloseCustomRender"); + + const rendererElm = scene.getRendererElement(); + + function finalizeRender() { + rendererElm.toBlob((blob) => { + const image = new Image(rendererElm.width, rendererElm.height); + image.src = URL.createObjectURL(blob!); + image.onload = () => { + downloadLink( + image.src, + // mii custom render file name - e.g. 'Mii_custom_render_2025-03-06T14:40:20.310Z.png' + __("%1_custom_render_%2.png", miiData.nickname, new Date().toJSON()) + ); + if (shouldClose) { + scene.shutdown(); + parent.cleanup(); + modal.qs("button")?.elm.click(); + } + }; + }); + } + + async function save3DModel() { + alert("This option doesn't work at the moment, please try again later."); + // const shaderSetting = await getSetting("shaderType"); + + // if (shaderSetting === "none") { + // return; + // } + + // // fix up the materials + // const mats = await traverse3DMaterialFix(scene); + // let i = 0; + + // const exporter = new GLTFExporter(); + // exporter.parse( + // scene.getScene(), + // (gltf) => { + // console.log("gltf", gltf); + // if (gltf instanceof ArrayBuffer) { + // saveArrayBuffer( + // gltf, + // `${miiData.nickname}_${__("all_body")}_${new Date().toJSON()}.glb` + // ); + // } + // if (shouldClose) { + // scene.shutdown(); + // parent.cleanup(); + // modal.qs("button")?.elm.click(); + // } else { + // // Revert back all materials. + // i = 0; + // scene.getScene().traverse((o) => { + // if ((o as Mesh).isMesh !== true) return; + + // const m = o as Mesh; + + // m.material = mats.get(i); + + // i++; + // }); + // } + // }, + // (error) => { + // console.error("Oops, something went wrong:", error); + // }, + // { + // binary: true + // } + // ); + } +} diff --git a/src/ui/pages/library/render/renderMenu.ts b/src/ui/pages/library/render/renderMenu.ts index c0f3739..57a60dc 100644 --- a/src/ui/pages/library/render/renderMenu.ts +++ b/src/ui/pages/library/render/renderMenu.ts @@ -1,101 +1,103 @@ import Html from "@datkat21/html"; -import { - CanvasTexture, - MeshPhysicalMaterial, - MeshStandardMaterial, - type Mesh, - type ShaderMaterial, - type Texture, -} from "three"; import { GLTFExporter } from "three/examples/jsm/Addons.js"; import { Mii3DScene, SetupType } from "../../../../class/3DScene"; -import type Mii from "../../../../external/mii-js/mii"; -import { sRGB } from "../../../../util/Color"; import { saveArrayBuffer } from "../../../../util/downloadLink"; import { getSetting } from "../../../../util/SettingsHelper"; -import Modal from "../../../components/Modal"; +import Modal, { buttonsOkCancel } from "../../../components/Modal"; import type { MiiLocalforage } from "../../Library"; import { customRender } from "./customRender"; import { miiRenderPresets } from "./renderPresets"; import { traverse3DMaterialFix } from "../util/3DModel"; -import { traverseAddShader } from "../../../../class/3d/shader/ShaderUtils"; +import type Mii from "../../../../class/MiiData"; + +import { _ } from "../../../../util/Lang"; +const __ = _(); export const miiRender = (mii: MiiLocalforage, miiData: Mii) => { Modal.modal( - "Render Mii", - "What would you like to do?", + __("Render Mii"), + __("What would you like to do?"), "body", { - text: "Download 3D head model", + text: __("Download 3D head model"), async callback() { - const holder = new Html("div").style({ opacity: "0" }); - const scene = new Mii3DScene( - miiData, - holder.elm, - SetupType.Screenshot, - (renderer) => {}, - true + Modal.modal( + __("Warning"), + __( + "3D model download has been disabled due to some buggy normals exporting going on at the moment.\nIn the meantime, you can use Arian's Mii Renderer to get head models.\nSorry about that." + ), + "body", + ...buttonsOkCancel ); - // hide body - scene.init().then(async () => { - await scene.updateMiiHead(); - scene.getScene().getObjectByName("m")!.visible = false; - scene.getScene().getObjectByName("f")!.visible = false; - - const shaderSetting = await getSetting("shaderType"); - // const bodyModelHands = await getSetting("bodyModelHands"); - - if (shaderSetting === "none") { - const result = await Modal.prompt( - "Notice", - "3D model export looks best when using the Wii U shader, which you aren't using.\nThis may result in incorrect color output. Do you still want to continue?", - "body" - ); - if (result === false) return; - } + // const holder = new Html("div").style({ opacity: "0" }); + // const scene = new Mii3DScene( + // miiData, + // holder.elm, + // SetupType.Screenshot, + // (renderer) => {}, + // true + // ); + // // hide body + // scene.init().then(async () => { + // scene.texResolution = 1024; + // await scene.updateMiiHead(); + // scene.getScene().getObjectByName("m")!.visible = false; + // scene.getScene().getObjectByName("f")!.visible = false; - // assuming shader isn't already present? - // extremely hacky delay - traverse3DMaterialFix(scene); - await new Promise((resolve) => { - setTimeout(() => { - resolve(null); - }, 250); - }); - const exporter = new GLTFExporter(); - exporter.parse( - scene.getScene(), - (gltf) => { - console.log("gltf", gltf); - if (gltf instanceof ArrayBuffer) { - saveArrayBuffer(gltf, miiData.miiName + "_head.glb"); - } - scene.shutdown(); - }, - (error) => { - console.error("Oops, something went wrong:", error); - }, - { - binary: true, - } - ); - }); - }, + // // assuming shader isn't already present? + // // extremely hacky delay + // traverse3DMaterialFix(scene); + // await new Promise((resolve) => { + // setTimeout(() => { + // resolve(null); + // }, 250); + // }); + // const exporter = new GLTFExporter(); + // exporter.parse( + // scene.getScene(), + // (gltf) => { + // console.log("gltf", gltf); + // if (gltf instanceof ArrayBuffer) { + // saveArrayBuffer( + // gltf, + // // mii head model file name - e.g. 'Mii_head_1741271879076.glb' + // __("%1_head_%2.glb", miiData.nickname, new Date().toJSON()) + // ); + // } + // scene.shutdown(); + // }, + // (error) => { + // console.error("Oops, something went wrong:", error); + // }, + // { + // binary: true + // } + // ); + // }); + } }, { - text: "Render presets", + text: __("Render presets"), async callback() { miiRenderPresets(mii, miiData); - }, + } }, { - text: "Make your own render", + text: __("Custom render"), async callback() { + // Modal.modal( + // __("Warning"), + // __( + // "Custom render mode has been temporarily disabled while I work out some issues regarding expressions.\nSorry about that." + // ), + // "body", + // ...buttonsOkCancel + // ); customRender(miiData); - }, + } }, { - text: "Cancel", + text: "Cancel" } ); }; diff --git a/src/ui/pages/library/render/renderPresets.ts b/src/ui/pages/library/render/renderPresets.ts index a70f973..f13ff07 100644 --- a/src/ui/pages/library/render/renderPresets.ts +++ b/src/ui/pages/library/render/renderPresets.ts @@ -1,58 +1,103 @@ -import type Mii from "../../../../external/mii-js/mii"; -import { downloadLink } from "../../../../util/downloadLink"; -import { - getMiiRender, - MiiCustomRenderType, -} from "../../../../util/miiImageUtils"; -import Modal from "../../../components/Modal"; -import type { MiiLocalforage } from "../../Library"; - -export const miiRenderPresets = async (mii: MiiLocalforage, miiData: Mii) => { - Modal.modal( - `Render options: ${miiData.miiName}`, - "Choose a way to render this Mii", - "body", - { - text: "Focus on head", - async callback() { - const renderImage = await getMiiRender( - miiData, - MiiCustomRenderType.Head - ); - downloadLink( - renderImage.src, - `${miiData.miiName}_render_headshot_${Date.now()}.png` - ); - }, - }, - { - text: "Focus on full body", - async callback() { - const renderImage = await getMiiRender( - miiData, - MiiCustomRenderType.Body - ); - downloadLink( - renderImage.src, - `${miiData.miiName}_render_body_${Date.now()}.png` - ); - }, - }, - { - text: "Head only", - async callback() { - const renderImage = await getMiiRender( - miiData, - MiiCustomRenderType.HeadOnly - ); - downloadLink( - renderImage.src, - `${miiData.miiName}_render_head_only_${Date.now()}.png` - ); - }, - }, - { - text: "Cancel", - } - ); -}; +import { WebGLRenderer } from "three"; +import type Mii from "../../../../class/MiiData"; +import { downloadLink, saveBlob } from "../../../../util/downloadLink"; +import { + createMiiRender, + type RenderRequest +} from "../../../../util/IconRendering"; + +import Modal from "../../../components/Modal"; +import type { MiiLocalforage } from "../../Library"; +import { getFFL } from "../../../../util/FFLLoader"; + +import { _ } from "../../../../util/Lang"; +import { ViewType } from "../../../../util/camera"; +const __ = _(); + +export const miiRenderPresets = async (mii: MiiLocalforage, miiData: Mii) => { + const renderer = new WebGLRenderer({ alpha: true }); + const miiRenderInfo: Omit = { + data: miiData.export("studioData"), + module: getFFL(), + renderer, + characterYRotate: 0, + expression: 0, + modelFlag: 0, + size: 1440, + additionalInfo: { + favorite: miiData.favorite, + hatCommonColor: miiData.hatCommonColor, + hatFavoriteColor: miiData.hatFavoriteColor, + hatType: miiData.hatType, + pantsColor: miiData.pantsColor, + shirtColor: miiData.shirtColor, + special: miiData.special, + temporary: miiData.temporary, + eyeSclera: miiData.eyeSclera, + wigType: miiData.wigType, + clothesType: miiData.clothesType, + shoesColor: miiData.shoesColor + } + }; + Modal.modal( + // Render options: Mii name + __("Render options: %1", miiData.nickname), + __("Choose a way to render this Mii"), + "body", + { + text: "Focus on head", + async callback() { + const renderImage = await createMiiRender({ + ...miiRenderInfo, + type: ViewType.Face, + drawBody: true + }); + saveBlob( + renderImage.result as Blob, + // mii render (head) file name - e.g. 'Mii_render_headshot_2025-03-06T14:40:20.310Z.png' + __("%1_render_headshot_%2.png", miiData.nickname, new Date().toJSON()) + ); + renderer.dispose(); + } + }, + { + text: "Focus on full body", + async callback() { + const renderImage = await createMiiRender({ + ...miiRenderInfo, + type: ViewType.AllBodySugar, + drawBody: true + }); + saveBlob( + renderImage.result as Blob, + // mii render (body) file name - e.g. 'Mii_render_body_2025-03-06T14:40:20.310Z.png' + __("%1_render_body_%2.png", miiData.nickname, new Date().toJSON()) + ); + renderer.dispose(); + } + }, + { + text: "Head only", + async callback() { + const renderImage = await createMiiRender({ + ...miiRenderInfo, + type: ViewType.MakeIcon, + drawBody: false + }); + saveBlob( + renderImage.result as Blob, + // mii render (head only) file name - e.g. 'Mii_render_head_only_2025-03-06T14:40:20.310Z.png' + __( + "%1_render_head_only_%2.png", + miiData.nickname, + new Date().toJSON() + ) + ); + renderer.dispose(); + } + }, + { + text: "Cancel" + } + ); +}; diff --git a/src/ui/pages/library/select.ts b/src/ui/pages/library/select.ts index 38a306e..fecbcbf 100644 --- a/src/ui/pages/library/select.ts +++ b/src/ui/pages/library/select.ts @@ -1,191 +1,237 @@ -import localforage from "localforage"; -import { MiiEditor } from "../../../class/MiiEditor"; -import type Mii from "../../../external/mii-js/mii"; -import Modal from "../../components/Modal"; -import { - _shutdown, - Library, - miiIconUrl, - type MiiLocalforage, -} from "../Library"; -import Html from "@datkat21/html"; -import { miiRender } from "./render/renderMenu"; -import { miiExportData } from "./export"; - -export const miiSelect = ( - mii: MiiLocalforage, - miiData: Mii, - isSpecial: boolean -) => { - return async () => { - const modal = Modal.modal( - miiData.miiName, - "What would you like to do?", - "body", - { - text: "Edit", - async callback() { - if (isSpecial) { - Modal.modal( - "Nope", - "You can't edit Special Miis obtained through Mii Creator.", - "body", - { text: "Cancel" }, - { text: "OK" } - ); - } else { - await _shutdown()(); - new MiiEditor( - 0, - async (m, shouldSave) => { - if (shouldSave === true) await localforage.setItem(mii.id, m); - Library(); - }, - mii.mii - ); - } - }, - }, - { - text: "Delete", - async callback() { - let scaredIcon: Blob, - fearfulIcon: Blob, - reliefIcon: Blob, - scaredIconURL: string, - fearfulIconURL: string, - reliefIconURL: string; - - scaredIcon = await ( - await fetch(await miiIconUrl(miiData) + "&expression=10") - ).blob(); - fearfulIcon = await ( - await fetch(await miiIconUrl(miiData) + "&expression=30") - ).blob(); - reliefIcon = await ( - await fetch(await miiIconUrl(miiData) + "&expression=1") - ).blob(); - - scaredIconURL = URL.createObjectURL(scaredIcon); - fearfulIconURL = URL.createObjectURL(fearfulIcon); - reliefIconURL = URL.createObjectURL(reliefIcon); - - function release() { - URL.revokeObjectURL(scaredIconURL); - URL.revokeObjectURL(fearfulIconURL); - URL.revokeObjectURL(reliefIconURL); - } - function destroy() { - // cry about it - disableModal(); - scaredMiiImage.classOn("rotateAndCry"); - } - - function closingCallback() { - tmpDeleteModal - .qs(".modal-body")! - .qsa("*")! - .forEach((a) => a!.attr({ disabled: true, tabindex: "-1" })); - } - function disableModal() { - closingCallback(); - } - function closeModal() { - tmpDeleteModal.class("closing"); - closingCallback(); - setTimeout(() => { - tmpDeleteModal.cleanup(); - }, 350); - } - - let tmpDeleteModal = Modal.modal( - "Warning", - `Are you sure you want to delete ${miiData.miiName}?`, - "body" - ); - - // button group - tmpDeleteModal.qs(".modal-body .flex-group")!.appendMany( - new Html("button") - .class("danger") - .text("Yes") - .on("click", () => { - destroy(); - scaredMiiImage.attr({ - src: fearfulIconURL, - }); - setTimeout(async () => { - closeModal(); - release(); - await localforage.removeItem(mii.id); - await _shutdown()(); - Library(); - }, 1000); - }), - new Html("button").text("No").on("click", () => { - closeModal(); - release(); - }) - ); - - // center - tmpDeleteModal.qs(".modal-body")!.classOn("flex-group"); - - const scaredMiiImage = new Html("img") - // surprised with open mouth expression - .attr({ src: scaredIconURL }) - .style({ width: "180px", margin: "-18px auto 0 auto" }); - - tmpDeleteModal.qs(".modal-body")!.prepend(scaredMiiImage); - tmpDeleteModal.qsa("button")!.forEach((item) => { - const yes = item?.elm.classList.contains("danger"); - item!.on("pointerenter", () => { - if (yes) { - scaredMiiImage.attr({ - src: fearfulIconURL, - }); - } else { - scaredMiiImage.attr({ - src: reliefIconURL, - }); - } - }); - item!.on("pointerleave", () => { - scaredMiiImage.attr({ - src: scaredIconURL, - }); - }); - }); - }, - }, - { - text: "Export/Download Data", - async callback() { - miiExportData(mii, miiData); - }, - }, - { - text: "Render", - async callback() { - miiRender(mii, miiData); - }, - }, - { - text: "Cancel", - } - ); - - modal.qs(".modal-body")?.prepend( - new Html("img") - .attr({ - src: await miiIconUrl(miiData, "preview", "all_body_sugar", 240), - }) - .style({ - "object-fit": "contain", - width: "180px", - height: "240px", - margin: "-18px auto 0 auto", - }) - ); - }; -}; +import localforage from "localforage"; +import { MiiEditor } from "../../../class/MiiEditor"; +import type Mii from "../../../class/MiiData"; +import Modal from "../../components/Modal"; +import { + _shutdown, + Library, + getMiiIcon, + type MiiLocalforage, + pushToServer +} from "../Library"; +import Html from "@datkat21/html"; +import { miiRender } from "./render/renderMenu"; +import { miiExportData } from "./export"; +import { confirmOrReviseMii } from "./new/lookalike"; + +import { _ } from "../../../util/Lang"; +const __ = _(); + +export const miiSelect = ( + mii: MiiLocalforage, + miiData: Mii, + isSpecial: boolean +) => { + return async () => { + const modal = Modal.modal( + miiData.nickname, + __("What would you like to do?"), + "body", + { + text: __("Edit"), + async callback() { + if (isSpecial) { + Modal.modal( + __("Notice"), + __("You can't edit Mii Creator-specific Special Miis."), + "body", + { text: "Cancel" }, + { text: __("OK") } + ); + } else { + await _shutdown()(); + new MiiEditor( + 0, + async (m, shouldSave) => { + if (shouldSave === true) await localforage.setItem(mii.id, m); + await pushToServer(); + Library(); + }, + mii.mii + ); + } + } + }, + { + text: __("Revise"), + async callback() { + if (isSpecial) { + return Modal.modal( + __("Notice"), + __("You can't edit Mii Creator-specific Special Miis."), + "body", + { text: "Cancel" }, + { text: __("OK") } + ); + } + confirmOrReviseMii(miiData, { + gender: miiData.gender, + isOriginalMii: true + }); + } + }, + { + text: __("Delete"), + async callback() { + try { + let scaredIcon = await getMiiIcon( + miiData, + "deletion", + "face", + 256, + 10, + false + ); + let fearfulIcon = await getMiiIcon( + miiData, + "deletion", + "face", + 256, + 30, + false + ); + let reliefIcon = await getMiiIcon( + miiData, + "deletion", + "face", + 256, + 1, + false + ); + + function destroy() { + // cry about it + disableModal(); + scaredMiiImage.classOn("rotateAndCry"); + } + + function closingCallback() { + tmpDeleteModal + .qs(".modal-body")! + .qsa("*")! + .forEach((a) => a!.attr({ disabled: true, tabindex: "-1" })); + } + function disableModal() { + closingCallback(); + } + function closeModal() { + tmpDeleteModal.class("closing"); + closingCallback(); + setTimeout(() => { + tmpDeleteModal.cleanup(); + }, 350); + } + + let tmpDeleteModal = Modal.modal( + __("Warning"), + __("Are you sure you want to delete %1?", miiData.nickname), + "body" + ); + + // button group + tmpDeleteModal.qs(".modal-body")!.append( + new Html("div").class("flex-group").appendMany( + new Html("button") + .class("danger") + .text(__("Yes")) + .on("click", () => { + destroy(); + scaredMiiImage.attr({ + src: fearfulIcon + }); + setTimeout(async () => { + closeModal(); + await localforage.removeItem(mii.id); + await pushToServer(); + await _shutdown()(); + Library(); + }, 1000); + }), + new Html("button").text(__("No")).on("click", () => { + closeModal(); + }) + ) + ); + + // center + tmpDeleteModal.qs(".modal-body")!.classOn("flex-group"); + + const scaredMiiImage = new Html("img") + // surprised with open mouth expression + .attr({ src: scaredIcon }) + .style({ width: "180px", margin: "-18px auto 0 auto" }); + + tmpDeleteModal.qs(".modal-body")!.prepend(scaredMiiImage); + tmpDeleteModal.qsa("button")!.forEach((item) => { + const yes = item?.elm.classList.contains("danger"); + item!.on("pointerenter", () => { + if (yes) { + scaredMiiImage.attr({ + src: fearfulIcon + }); + } else { + scaredMiiImage.attr({ + src: reliefIcon + }); + } + }); + item!.on("pointerleave", () => { + scaredMiiImage.attr({ + src: scaredIcon + }); + }); + }); + } catch (e) { + console.log("FALL BACK"); + // fallback + Modal.modal( + __("Warning"), + __("Are you sure you want to delete %1?", miiData.nickname), + "body", + { + text: __("Yes"), + type: "danger", + async callback(e) { + await localforage.removeItem(mii.id); + await pushToServer(); + await _shutdown()(); + Library(); + } + }, + { text: __("No") } + ); + } + } + }, + { + text: __("Export/Download Data"), + async callback() { + miiExportData(mii, miiData); + } + }, + { + text: __("Render"), + async callback() { + miiRender(mii, miiData); + } + }, + { + text: "Cancel" + } + ); + + const miiBodyIcon = new Html("img").style({ + "object-fit": "cover", + width: "240px", + height: "240px", + margin: "-18px auto 0 auto", + transition: "opacity 0.3s ease", + opacity: "0" + }); + + getMiiIcon(miiData, "preview", "all_body_sugar", 240).then((result) => { + miiBodyIcon.attr({ src: result }).style({ opacity: "1" }); + }); + modal.qs(".modal-body")?.prepend(miiBodyIcon); + }; +}; diff --git a/src/ui/pages/library/util/3DModel.ts b/src/ui/pages/library/util/3DModel.ts index 40cfb8a..a9ae71b 100644 --- a/src/ui/pages/library/util/3DModel.ts +++ b/src/ui/pages/library/util/3DModel.ts @@ -1,232 +1,395 @@ -import { - CanvasTexture, - MeshBasicMaterial, - MeshPhysicalMaterial, - MeshStandardMaterial, - type Mesh, - type ShaderMaterial, - type Texture, -} from "three"; -import type { Mii3DScene } from "../../../../class/3DScene"; -import { getSetting } from "../../../../util/SettingsHelper"; -import { sRGB } from "../../../../util/Color"; -import { cMaterialName } from "../../../../class/3d/shader/fflShaderConst"; -import * as THREE from "three"; - -export async function traverse3DMaterialFix( - scene: Mii3DScene -): Promise> { - const shaderSetting = await getSetting("shaderType"); - const bodyModelHands = await getSetting("bodyModelHands"); - return new Promise((resolve) => { - let mats = new Map(); - let count = 0; - let total = 0; - - // count meshes (ai slop code ..) - scene.getScene().traverse((o) => { - if ((o as Mesh).isMesh !== true) return; - const m = o as Mesh; - if (m.material) { - total++; - } - }); - - scene.getScene().traverse((o) => { - if ((o as Mesh).isMesh !== true) return; - - const m = o as Mesh; - - mats.set(count, m.material); - - console.log(m.name, m.geometry.userData); - - // this depends on shader setting.. - let map: Texture | null = null; - const userData = m.geometry.userData; - - if ( - // Both of these internally use FFL shader - shaderSetting.startsWith("wiiu") || - shaderSetting === "lightDisabled" - ) { - console.log(m.name, (m.material as MeshBasicMaterial).type); - if ((m.material as MeshBasicMaterial).type !== "ShaderMaterial") return; - - map = (m.material as ShaderMaterial).uniforms.s_texture.value; - - if (map !== null) { - // Wii U shader textures need to be converted from linear to sRGB - - // Create a temporary canvas - const canvas = document.createElement("canvas"); - const context = canvas.getContext("2d")!; - - // Set canvas dimensions - canvas.width = map.image.width; - canvas.height = map.image.height; - - let image = map.image, - isImageData = false; - - if (typeof map.image.data !== "undefined") { - // assume multiplyTexture was used, so it's ImageData - image = new ImageData( - map.image.data, - map.image.width, - map.image.height - ); - isImageData = true; - } - - // Draw the texture to the canvas - if (isImageData) context.putImageData(image, 0, 0); - else context.drawImage(image, 0, 0); - - // Get image data from the canvas - const imageData = context.getImageData( - 0, - 0, - canvas.width, - canvas.height - ); - const data = imageData.data; - - // Convert from sRGB Linear to sRGB - for (let i = 0; i < data.length; i += 4) { - // Extract RGB components - let r = data[i] / 255; - let g = data[i + 1] / 255; - let b = data[i + 2] / 255; - - // Convert from sRGB Linear to sRGB - r = sRGB(r); - g = sRGB(g); - b = sRGB(b); - - // Convert back to 0-255 range - data[i] = Math.round(r * 255); - data[i + 1] = Math.round(g * 255); - data[i + 2] = Math.round(b * 255); - } - - // Update the canvas with the modified image data - context.putImageData(imageData, 0, 0); - - const newMap = new CanvasTexture(canvas); - - // Make sure to apply previous map properties! - newMap.flipY = map.flipY; - newMap.wrapS = map.wrapS; - newMap.wrapT = map.wrapS; - - // leak? - map = newMap; - map.needsUpdate = true; - - // await new Promise((resolve) => { - // createImageBitmap(canvas) - // .then((imageBitmap) => { - // // Assign the ImageBitmap to the map's source.data - // // map!.source.data = imageBitmap; - // console.log(map!.source.data); - // // Re-generate mipmaps - // map!.needsUpdate = true; - // resolve(true); - // }) - // .catch((error) => { - // console.error("Error creating ImageBitmap:", error); - // }); - // }); - - // Re-generate mipmaps - map.needsUpdate = true; - } - } else if (shaderSetting === "switch") { - // Can't remember what the uniform for texture is on switch - } else { - // Prevent warning by assigning map to null if it is null - if ((m.material as MeshStandardMaterial).map !== null) - map = (m.material as MeshStandardMaterial).map; - - // if (bodyModelHands) { - // if (m.name === "hands_m" || m.name === "hands_f") { - // (m.material as MeshBasicMaterial).color.set( - // new Color(...scene.handColor) - // ); - // } - // } - } - - // Just use modulateColor from the userData - // because i can't be asked - function rgbaToHex(rgba: [number, number, number]) { - const [r, g, b] = rgba; - const intR = Math.round(r * 255); - const intG = Math.round(g * 255); - const intB = Math.round(b * 255); - const hexR = intR.toString(16).padStart(2, "0"); - const hexG = intG.toString(16).padStart(2, "0"); - const hexB = intB.toString(16).padStart(2, "0"); - return Number(`0x${hexR}${hexG}${hexB}`); - } - - // define params for the model material export - let color: THREE.ColorRepresentation | undefined = rgbaToHex( - userData.modulateColor - ), - metalness: number = 1, - roughness: number = 1; - - if (m.parent) { - if (m.parent.name.includes("Hat")) { - // assume HatScene or HatRoot, we don't need a blend color - color = undefined; - } - } - - if (bodyModelHands) { - if (m.name === "hands_m" || m.name === "hands_f") { - color = new THREE.Color(...scene.handColor); - } - } - - var mat = new MeshPhysicalMaterial({ - color, - metalness, - roughness, - map: map, - side: THREE.FrontSide, - }); - - switch (userData.modulateType) { - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_MASK: - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSELINE: - mat.side = THREE.FrontSide; - mat.transparent = true; - break; - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_GLASS: - mat.side = THREE.DoubleSide; - mat.transparent = true; - break; - case cMaterialName.FFL_MODULATE_TYPE_SHAPE_PANTS: - // get pants color from the scene - const pantsColor = scene.getPantsColor(); - mat.color = new THREE.Color( - pantsColor[0], - pantsColor[1], - pantsColor[2] - ); - break; - } - - m.material = mat; - - count++; - - if (count === total) { - resolve(mats); - } - }); - }); -} +import { + CanvasTexture, + MeshBasicMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + type Mesh, + type ShaderMaterial, + type Texture +} from "three"; +import type { Mii3DScene } from "../../../../class/3DScene"; +// import { getSetting } from "../../../../util/SettingsHelper"; +import * as THREE from "three"; +import { ShaderType } from "../../../../constants/BodyShaderTypes"; +import { renderTargetToDataTexture } from "../../../../util/rendertarget"; +import { getSettingSafe } from "../../../../class/3d/shader/ShaderUtils"; + +export async function traverse3DMaterialFix( + scene: Mii3DScene +): Promise> { + const shaderSetting = await getSettingSafe("shaderType"); + const bodyModelHands = await getSettingSafe("bodyModelHands"); + return new Promise((resolve) => { + let mats = new Map(); + let count = 0; + let total = 0; + + // count meshes (ai slop code ..) + scene.getScene().traverse((o) => { + if ((o as Mesh).isMesh !== true) return; + const m = o as Mesh; + if (m.material) { + total++; + } + }); + + scene.getScene().traverse(async (o) => { + if ((o as Mesh).isMesh !== true) return; + + const m = o as Mesh; + + mats.set(count, m.material); + + console.log(m.name, m.geometry.userData); + + // this depends on shader setting.. + let map: Texture | null = null; + const userData = m.geometry.userData; + + if ( + // Both of these internally use FFL shader + shaderSetting.startsWith("wiiu") || + shaderSetting === ShaderType.LightDisabled || + shaderSetting === ShaderType.Miitomo + ) { + console.log(m.name, (m.material as MeshBasicMaterial).type); + if ((m.material as MeshBasicMaterial).type !== "ShaderMaterial") return; + + console.log("current map:", (m.material as any).map); + + let mapFixed = false; + + switch (m.name) { + case "OpaFaceline": { + if (scene.charModel!._facelineTarget !== null) { + const texture = await renderTargetToDataTexture( + scene.charModel!._facelineTarget, + scene.getRenderer() + ); + + (m.material as MeshBasicMaterial).map = texture; + const map2 = (m.material as MeshBasicMaterial).map as Texture; + if (map2) { + map2.wrapS = THREE.MirroredRepeatWrapping; + map2.wrapT = THREE.MirroredRepeatWrapping; + } + + map = (m.material as MeshBasicMaterial).map; + mapFixed = true; + } + break; + } + case "XluMask": { + if (Object.values(scene.charModel!._maskTargets)[0]! !== null) { + const texture = await renderTargetToDataTexture( + Object.values(scene.charModel!._maskTargets)[0]!, + scene.getRenderer() + ); + + (m.material as MeshBasicMaterial).map = texture; + + map = (m.material as MeshBasicMaterial).map; + mapFixed = true; + } + break; + } + } + + if (mapFixed) console.log("fixed map:", map); + else { + map = (m.material as any).map; + console.log("map wasnt fixed but here you go:", map); + } + + requestAnimationFrame(() => { + debugger; + requestAnimationFrame(() => { + debugger; + }); + }); + + // if (map !== null) { + // // Wii U shader textures need to be converted from linear to sRGB + + // // Create a temporary canvas + // const canvas = document.createElement("canvas"); + // const context = canvas.getContext("2d")!; + + // // Set canvas dimensions + // canvas.width = map.image.width; + // canvas.height = map.image.height; + + // // let image = map.image, + // let image = map, + // isImageData = false; + + // // if (typeof map.image.data !== "undefined") { + // // // assume multiplyTexture was used, so it's ImageData + // // image = new ImageData( + // // map.image.data, + // // map.image.width, + // // map.image.height + // // ); + // // isImageData = true; + // // } + + // // Draw the texture to the canvas + + // // if (isImageData) context.putImageData(image, 0, 0); + // // else context.drawImage(image, 0, 0); + + // // // Get image data from the canvas + // // const imageData = context.getImageData( + // // 0, + // // 0, + // // canvas.width, + // // canvas.height + // // ); + // // const data = imageData.data; + + // // // Convert from sRGB Linear to sRGB + // // for (let i = 0; i < data.length; i += 4) { + // // // Extract RGB components + // // let r = data[i] / 255; + // // let g = data[i + 1] / 255; + // // let b = data[i + 2] / 255; + + // // // Convert from sRGB Linear to sRGB + // // r = sRGB(r); + // // g = sRGB(g); + // // b = sRGB(b); + + // // // Convert back to 0-255 range + // // data[i] = Math.round(r * 255); + // // data[i + 1] = Math.round(g * 255); + // // data[i + 2] = Math.round(b * 255); + // // } + + // // // Update the canvas with the modified image data + // // context.putImageData(imageData, 0, 0); + + // // const newMap = new CanvasTexture(canvas); + + // // // Make sure to apply previous map properties! + // // newMap.flipY = map.flipY; + // // newMap.wrapS = map.wrapS; + // // newMap.wrapT = map.wrapS; + + // // // leak? + // // map = newMap; + // // map.needsUpdate = true; + + // // // await new Promise((resolve) => { + // // // createImageBitmap(canvas) + // // // .then((imageBitmap) => { + // // // // Assign the ImageBitmap to the map's source.data + // // // // map!.source.data = imageBitmap; + // // // console.log(map!.source.data); + // // // // Re-generate mipmaps + // // // map!.needsUpdate = true; + // // // resolve(true); + // // // }) + // // // .catch((error) => { + // // // console.error("Error creating ImageBitmap:", error); + // // // }); + // // // }); + + // // // Re-generate mipmaps + // // map.needsUpdate = true; + // } + } else if (shaderSetting === "switch") { + // Can't remember what the uniform for texture is on switch + } else { + // Prevent warning by assigning map to null if it is null + if ((m.material as MeshStandardMaterial).map !== null) + map = (m.material as MeshStandardMaterial).map; + + // if (bodyModelHands) { + // if (m.name === "hands_m" || m.name === "hands_f") { + // (m.material as MeshBasicMaterial).color.set( + // new Color(...scene.handColor) + // ); + // } + // } + } + + // Just use modulateColor from the userData + // because i can't be asked + function rgbaToHex(rgba: [number, number, number]) { + const [r, g, b] = rgba; + const intR = Math.round(r * 255); + const intG = Math.round(g * 255); + const intB = Math.round(b * 255); + const hexR = intR.toString(16).padStart(2, "0"); + const hexG = intG.toString(16).padStart(2, "0"); + const hexB = intB.toString(16).padStart(2, "0"); + return Number(`0x${hexR}${hexG}${hexB}`); + } + + console.log( + `${m.name} color:`, + Array.isArray(userData.modulateColor) + ? userData.modulateColor + : (userData.modulateColor as THREE.Vector4).toArray() + ); + + THREE.ColorManagement.enabled = false; + + // define params for the model material export + let color: THREE.ColorRepresentation | undefined = new THREE.Color( + userData.modulateColor.x, + userData.modulateColor.y, + userData.modulateColor.z + ), + metalness: number = 0, + // roughness: number = 0.5; + roughness: number = 0.0; + + if (m.parent) { + if (m.parent.name.includes("Hat")) { + // assume HatScene or HatRoot, we don't need a blend color + color = undefined; + } + } + + if (bodyModelHands) { + if (m.name === "hands_m" || m.name === "hands_f") { + color = new THREE.Color(...scene.handColor); + } + } + + // hack + if ( + userData.modulateColor.x === 0 && + userData.modulateColor.y === 0 && + userData.modulateColor.z === 0 && + userData.modulateColor.w === 0 + ) { + // don't multiply color in blender? + color = undefined; + } + + if (color !== undefined) { + color.convertSRGBToLinear(); + } + + var mat = new MeshPhysicalMaterial({ + color, + metalness, + roughness, + map: map, + side: THREE.FrontSide + }); + + // switch (userData.modulateType) { + // case cMaterialName.FFL_MODULATE_TYPE_SHAPE_MASK: + // mat.side = THREE.FrontSide; + // mat.transparent = true; + // break; + // case cMaterialName.FFL_MODULATE_TYPE_SHAPE_NOSELINE: { + // mat.side = THREE.FrontSide; + // mat.transparent = true; + // const tex = (m.material as MeshBasicMaterial).map!; + // mat.map = tex; + + // const newTexture = await colorMixTexture(tex, { + // x: 0, + // y: 0, + // z: 0, + // w: 1 + // }); + + // mat.map = await loadBlobTexture(newTexture); + // mat.map!.wrapS = tex.wrapS; + // mat.map!.wrapT = tex.wrapT; + // break; + // } + // case cMaterialName.FFL_MODULATE_TYPE_SHAPE_GLASS: { + // mat.side = THREE.DoubleSide; + // mat.transparent = true; + // const tex = (m.material as MeshBasicMaterial).map!; + + // // Fix the texture + // const newTexture = await colorMixTexture( + // tex, + // new THREE.Vector4(...SwitchMiiColorTableSRGB[scene.mii.glassColor]), + // new THREE.Vector4(0, 0, 0, 0) + // ); + + // mat.map = await loadBlobTexture(newTexture); + // mat.map!.wrapS = tex.wrapS; + // mat.map!.wrapT = tex.wrapT; + // break; + // } + // case cMaterialName.FFL_MODULATE_TYPE_SHAPE_BODY: + // // get pants color from the scene + // const shirtColor = scene.getShirtColor(); + // mat.color = new THREE.Color( + // shirtColor[0], + // shirtColor[1], + // shirtColor[2] + // ); + // break; + // case cMaterialName.FFL_MODULATE_TYPE_SHAPE_PANTS: + // // get pants color from the scene + // const pantsColor = scene.getPantsColor(); + // mat.color = new THREE.Color( + // pantsColor[0], + // pantsColor[1], + // pantsColor[2] + // ); + // break; + // } + + if (mat !== undefined) m.material = mat; + else console.warn(`WARNING: ${m.name}'s material is empty.`); + + count++; + + if (count === total) { + resolve(mats); + + requestAnimationFrame(() => { + debugger; + + requestAnimationFrame(() => { + debugger; + }); + }); + } + }); + }); +} + +export function loadBlobTexture(blob: Blob): Promise { + return new Promise((resolve) => { + var texture = new THREE.Texture(); + var url = URL.createObjectURL(blob); + + var image = new Image(); + image.src = url; + image.onload = function () { + // texture.flipY = false; + texture.image = image; + texture.needsUpdate = true; + + resolve(texture); + + setTimeout(() => { + URL.revokeObjectURL(url); + }, 10000); + }; + }); +} +export function loadBlobTextureWorker( + blob: Blob, + width: number = 512, + height: number = 512 +): Promise { + return new Promise((resolve) => { + createImageBitmap(blob, 0, 0, width, height).then((r) => { + console.log("bitmap canvas texture created"); + return resolve(new THREE.CanvasTexture(r)); + }); + }); +} diff --git a/src/ui/setup.ts b/src/ui/setup.ts index 56bf507..b3abbc8 100644 --- a/src/ui/setup.ts +++ b/src/ui/setup.ts @@ -1,40 +1,127 @@ import localforage from "localforage"; import { getMusicManager } from "../class/audio/MusicManager"; -import { - getSoundManager, -} from "../class/audio/SoundManager"; +import { getSoundManager } from "../class/audio/SoundManager"; import Modal, { buttonsOkCancel } from "./components/Modal"; import { Library } from "./pages/Library"; -import Mii from "../external/mii-js/mii"; +import Mii from "../class/MiiData"; import { MiiEditor } from "../class/MiiEditor"; import { - displayUpdateNotice, + // displayUpdateNotice, Settings, - updateSettings, + updateSettings } from "./pages/Settings"; -import { getMiiRender, MiiCustomRenderType } from "../util/miiImageUtils"; -import { Buffer } from "../../node_modules/buffer/index"; -import { SelectionLibrary } from "./pages/SelectionLibrary"; -import "../external/mii-frontend/all-kaitai-structs"; -import { getSetting, setSetting } from "../util/SettingsHelper"; -import { Config } from "../config"; -import Html from "@datkat21/html"; -import { AddButtonSounds } from "../util/AddButtonSounds"; import { customRender } from "./pages/library/render/customRender"; +import { _ } from "../util/Lang"; +import { prepareFFL } from "../util/FFLLoader"; +const __ = _(); + export async function setupUi() { let mm = getMusicManager(); getSoundManager(); + let shownSessionModal = false; + // Check session every 60s + setInterval(() => { + // console.log("checking session.."); + fetch("/api/session") + .then((e) => { + if (!e.ok) { + // not ok + showSessionModal(); + } + }) + .catch((e) => { + // also not ok + showSessionModal(); + }); + }, 45_000); + + function showSessionModal() { + if (shownSessionModal) return; + shownSessionModal = true; + Modal.modal( + __("Warning"), + __("Mii Creator has lost connection to the server. Click OK to reload."), + "body", + { + text: "OK", + callback(e) { + location.reload(); + } + } + ); + } + updateSettings(true); - displayUpdateNotice(); + await prepareFFL(); + + // displayUpdateNotice(); - if (navigator.userAgent.includes("Firefox") && sessionStorage.getItem("seen-firefox-notice") === null) { - sessionStorage.setItem("seen-firefox-notice", "yes"); - Modal.modal("Notice", "You're using Mii Creator under Firefox. The Firefox browser may have slowdowns.", "body", ...buttonsOkCancel) + function showBrowserWarning() { + if ( + navigator.userAgent.includes("Firefox") && + sessionStorage.getItem("seen-firefox-notice") === null + ) { + sessionStorage.setItem("seen-firefox-notice", "yes"); + Modal.modal( + __("Warning"), + __( + "You're using Mii Creator under Firefox. Using the Firefox browser WILL experience slowdowns and lag." + ), + "body", + ...buttonsOkCancel + ); + } + if ( + navigator.userAgent.indexOf("Safari") != -1 && + navigator.userAgent.indexOf("Chrome") == -1 /*&& + sessionStorage.getItem("seen-safari-notice") === null*/ + ) { + // sessionStorage.setItem("seen-safari-notice", "yes"); + Modal.modal( + __("Warning"), + __( + "You're using Mii Creator under Safari. Safari on iOS or iPadOS may experience instability with Mii Creator, causing the page to crash and refresh randomly. Some checks have been enabled to try and prevent the page from crashing right now. You have been warned." + ), + "body", + ...buttonsOkCancel + ); + } } + if ( + navigator.userAgent.indexOf("Safari") != -1 && + navigator.userAgent.indexOf("Chrome") == -1 + ) { + //@ts-expect-error + window.browserMitigations = true; + // alert("safari check PASSED"); + } else { + // alert("safari check FAILED"); + } + + Modal.modal( + __("Warning"), + __( + "You're using a BETA version of Mii Creator. Some features in development have been disabled, and bugs/glitches can occur.\n\n• Special Miis have been changed.\n• QR codes made from this version of Mii Creator can't be scanned back in.\n• Your Mii library now automatically syncs with the server and across devices." + ), + "body", + { + text: "Cancel", + callback(e) { + showBrowserWarning(); + } + }, + { + text: __("OK"), + callback() { + showBrowserWarning(); + } + } + ); + // for U theme let state: "main" | "edit" = "main"; document.addEventListener("editor-launch", () => { @@ -77,7 +164,6 @@ export async function setupUi() { mm.initMusic(); - if (location.search !== "") { const searchParams = new URLSearchParams(location.search); @@ -88,7 +174,7 @@ export async function setupUi() { async (data, shutdownProperly) => { if (window.parent !== window.self) { // In iframe (UNTESTED) - const miiData = new Mii(Buffer.from(data, "base64")); + const miiData = new Mii(data); let headshot: string | null = null; let headOnly: string | null = null; @@ -98,36 +184,36 @@ export async function setupUi() { if (searchParams.has("renderTypes")) { const renderTypes = searchParams.get("renderTypes")!.split(","); - if (renderTypes.includes("headshot")) { - headshot = ( - await getMiiRender( - miiData, - MiiCustomRenderType.Head, - true, - false - ) - ).src; - } - if (renderTypes.includes("headOnly")) { - headOnly = ( - await getMiiRender( - miiData, - MiiCustomRenderType.HeadOnly, - true, - false - ) - ).src; - } - if (renderTypes.includes("fullBody")) { - fullBody = ( - await getMiiRender( - miiData, - MiiCustomRenderType.Body, - true, - false - ) - ).src; - } + // if (renderTypes.includes("headshot")) { + // headshot = ( + // await getMiiRender( + // miiData, + // MiiCustomRenderType.Head, + // true, + // false + // ) + // ).src; + // } + // if (renderTypes.includes("headOnly")) { + // headOnly = ( + // await getMiiRender( + // miiData, + // MiiCustomRenderType.HeadOnly, + // true, + // false + // ) + // ).src; + // } + // if (renderTypes.includes("fullBody")) { + // fullBody = ( + // await getMiiRender( + // miiData, + // MiiCustomRenderType.Body, + // true, + // false + // ) + // ).src; + // } } } @@ -141,11 +227,11 @@ export async function setupUi() { type: "miic-data-finalize", properSave: shutdownProperly, data, - name: miiData.miiName, - creator: miiData.creatorName, + name: miiData.nickname, + creator: miiData.creator, headshot, headOnly, - fullBody, + fullBody }, searchParams.get("origin")! ); @@ -156,56 +242,56 @@ export async function setupUi() { searchParams.get("data")! ); } else if (searchParams.has("select")) { - const miiData = await SelectionLibrary(); + alert(__("Selection library is currently not implemented yet")); + throw new Error(__("Selection library is currently not implemented yet")); + // const miiData = await SelectionLibrary(); - console.log("selection:", miiData); + // console.log("selection:", miiData); - let headshot: string | null = null; - let headOnly: string | null = null; - let fullBody: string | null = null; + // let headshot: string | null = null; + // let headOnly: string | null = null; + // let fullBody: string | null = null; - if (searchParams.has("renderTypes")) { - const renderTypes = searchParams.get("renderTypes")!.split(","); + // if (searchParams.has("renderTypes")) { + // const renderTypes = searchParams.get("renderTypes")!.split(","); - if (renderTypes.includes("headshot")) { - headshot = ( - await getMiiRender(miiData, MiiCustomRenderType.Head, true, false) - ).src; - } - if (renderTypes.includes("headOnly")) { - headOnly = ( - await getMiiRender( - miiData, - MiiCustomRenderType.HeadOnly, - true, - false - ) - ).src; - } - if (renderTypes.includes("fullBody")) { - fullBody = ( - await getMiiRender(miiData, MiiCustomRenderType.Body, true, false) - ).src; - } - } + // if (renderTypes.includes("headshot")) { + // headshot = ( + // await getMiiRender(miiData, MiiCustomRenderType.Head, true, false) + // ).src; + // } + // if (renderTypes.includes("headOnly")) { + // headOnly = ( + // await getMiiRender( + // miiData, + // MiiCustomRenderType.HeadOnly, + // true, + // false + // ) + // ).src; + // } + // if (renderTypes.includes("fullBody")) { + // fullBody = ( + // await getMiiRender(miiData, MiiCustomRenderType.Body, true, false) + // ).src; + // } + // } - window.parent.postMessage( - { - type: "miic-select", - data: miiData.encode(), - name: miiData.miiName, - creator: miiData.creatorName, - headshot, - headOnly, - fullBody, - }, - location.origin - ); + // window.parent.postMessage( + // { + // type: "miic-select", + // data: miiData.encode(), + // name: miiData.miiName, + // creator: miiData.creatorName, + // headshot, + // headOnly, + // fullBody + // }, + // location.origin + // ); } else if (searchParams.has("custom-render-preview")) { - const miiData = new Mii( - Buffer.from(searchParams.get("custom-render-preview")!, "base64") - ); - customRender(miiData); + // const miiData = new Mii(searchParams.get("custom-render-preview")!); + // customRender(miiData); } else if (searchParams.has("settings")) { Settings(); } else Library(); @@ -261,42 +347,7 @@ export async function setupUi() { //@ts-expect-error window.soundManager = getSoundManager(); - document.addEventListener("keydown", (e) => { - if (document.activeElement === document.body) { - if (e.ctrlKey || e.altKey || e.metaKey) return; - if (e.code === "KeyS") { - Modal.modal( - "sound test", - "choose a sound", - "body", - ...Object.keys(getSoundManager().soundBufs).map((k) => ({ - text: k, - callback() { - getSoundManager().playSound(k); - //@ts-expect-error used for debugging - window.lastPlayedSound = k; - }, - })) - ) - .qs(".modal-content")! - .style({ "max-width": "unset", "max-height": "unset" }); - } - if (e.code === "KeyD") { - // debug key enables debug options - window.localforage = localforage; - window.Mii = Mii; - } - if (e.code === "KeyV") { - const vol = Number( - prompt("Enter volume level from 0-1 (default is 0.35)") - ); - - if (vol < 0) return; - if (vol > 1) return; - - getSoundManager().setVolume(vol); - mm.setVolume(vol); - } - } - }); + // debugging options + window.localforage = localforage; + // window.Mii = Mii; } diff --git a/src/ui/tabs/ExtClothes.ts b/src/ui/tabs/ExtClothes.ts new file mode 100644 index 0000000..f7165ad --- /dev/null +++ b/src/ui/tabs/ExtClothes.ts @@ -0,0 +1,168 @@ +import { + FeatureSetType, + MiiPagedFeatureSet, + type FeatureSetIconItem +} from "../components/MiiPagedFeatureSet"; +import type { TabRenderInit } from "../../constants/TabRenderType"; +import { ArrayNum } from "../../util/Numbers"; +import { BodyUpdateType, RenderPart } from "../../class/MiiEditor"; +import { + ForbiddenShirtPantColors, + MiiFavoriteColorLookupTable, + SwitchMiiColorTable +} from "../../constants/ColorTables"; +import { numToHex } from "../../util/NumberToHexString"; +import { + makeSeparatorFSI, + makeSeparatorGapThinFSI, + makeSeparatorGapThinLaptop, + MiiSwitchColorTable, + rearrangeArray +} from "../../constants/MiiFeatureTable"; + +import { _ } from "../../util/Lang"; +const __ = _(); + +export function ExtClothesTab(data: TabRenderInit) { + data.container.append( + MiiPagedFeatureSet({ + mii: data.mii, + onChange: data.callback, + entries: { + clothesType: { + label: + // hat tab name + __("Clothes"), + header: __( + "%1 is a CUSTOM property, and will not transfer to any other data formats.", + // Hat type warning label + __("Clothes type") + ), + items: [ + { + type: FeatureSetType.Icon, + forceRender: true, + value: -1, + icon: `${__("Disabled")}`, + part: RenderPart.Head, + bodyUpdateType: BodyUpdateType.ClothingUpdate + }, + makeSeparatorGapThinFSI(), + ...ArrayNum(10) + .slice(1) + .map((k) => ({ + type: FeatureSetType.Icon as any, + forceRender: true, + bodyUpdateType: BodyUpdateType.ClothingUpdate, + value: k - 1, + icon: k, + part: RenderPart.Head + })) + ] + }, + shirtColor: { + label: __("Shirt Color"), + header: __( + "%1 is a CUSTOM property, and will not transfer to any other data formats.", + // Shirt color warning label + __("Shirt color") + ), + items: [ + { + type: FeatureSetType.Icon, + forceRender: true, + value: -1, + icon: `${__("Disabled")}`, + part: RenderPart.Body, + bodyUpdateType: BodyUpdateType.ClothingUpdate, + property: "shirtColor", + sound: "select_color" + }, + makeSeparatorGapThinFSI(), + ...rearrangeArray( + ArrayNum(100).map((k) => ({ + type: FeatureSetType.Icon, + forceRender: true, + value: k, + color: SwitchMiiColorTable[k], + part: RenderPart.Body, + bodyUpdateType: BodyUpdateType.ClothingUpdate, + property: "shirtColor" + })), + MiiSwitchColorTable, + makeSeparatorGapThinLaptop + ).filter((n) => !ForbiddenShirtPantColors.includes(n.value)) + ] + }, + pantsColor: { + label: __("Pants Color"), + header: __( + "%1 is a CUSTOM property, and will not transfer to any other data formats.", + // Pants color warning label + __("Pants color") + ), + items: [ + { + type: FeatureSetType.Icon, + forceRender: false, + value: -1, + icon: `${__("Disabled")}`, + part: RenderPart.Body, + bodyUpdateType: BodyUpdateType.ClothingUpdate, + property: "pantsColor", + sound: "select_color" + }, + makeSeparatorGapThinFSI(), + ...rearrangeArray( + ArrayNum(100).map((k) => ({ + type: FeatureSetType.Icon, + forceRender: false, + value: k, + color: SwitchMiiColorTable[k], + part: RenderPart.Body, + bodyUpdateType: BodyUpdateType.ClothingUpdate, + property: "pantsColor" + })), + MiiSwitchColorTable, + makeSeparatorGapThinLaptop + ).filter((n) => !ForbiddenShirtPantColors.includes(n.value)) + ] + }, + shoesColor: { + label: __("Shoes Color"), + header: __( + "%1 is a CUSTOM property, and will not transfer to any other data formats.", + // Pants color warning label + __("Shoes color") + ), + items: [ + { + type: FeatureSetType.Icon, + forceRender: false, + value: -1, + icon: `${__("Disabled")}`, + part: RenderPart.Body, + bodyUpdateType: BodyUpdateType.ClothingUpdate, + property: "shoesColor", + sound: "select_color" + }, + makeSeparatorGapThinFSI(), + ...rearrangeArray( + ArrayNum(100).map((k) => ({ + type: FeatureSetType.Icon, + forceRender: false, + value: k, + color: SwitchMiiColorTable[k], + part: RenderPart.Body, + bodyUpdateType: BodyUpdateType.ClothingUpdate, + property: "shoesColor" + })), + MiiSwitchColorTable, + makeSeparatorGapThinLaptop + ).filter((n) => !ForbiddenShirtPantColors.includes(n.value)) + ] + } + } + }) + ); +} diff --git a/src/ui/tabs/ExtHat.ts b/src/ui/tabs/ExtHat.ts index 1b8ac85..fccef00 100644 --- a/src/ui/tabs/ExtHat.ts +++ b/src/ui/tabs/ExtHat.ts @@ -1,12 +1,26 @@ import { FeatureSetType, MiiPagedFeatureSet, + type FeatureSetIconItem } from "../components/MiiPagedFeatureSet"; import type { TabRenderInit } from "../../constants/TabRenderType"; import { ArrayNum } from "../../util/Numbers"; import { RenderPart } from "../../class/MiiEditor"; -import { MiiFavoriteColorLookupTable } from "../../constants/ColorTables"; +import { + MiiFavoriteColorLookupTable, + SwitchMiiColorTable +} from "../../constants/ColorTables"; import { numToHex } from "../../util/NumberToHexString"; +import { + makeSeparatorFSI, + makeSeparatorGapThinFSI, + makeSeparatorGapThinLaptop, + MiiSwitchColorTable, + rearrangeArray +} from "../../constants/MiiFeatureTable"; + +import { _ } from "../../util/Lang"; +const __ = _(); export function ExtHatTab(data: TabRenderInit) { data.container.append( @@ -14,51 +28,87 @@ export function ExtHatTab(data: TabRenderInit) { mii: data.mii, onChange: data.callback, entries: { - extHatType: { - label: "Hat", - header: - "Hat type is a CUSTOM property, and will not transfer to any other data formats.", + hatType: { + label: + // hat tab name + __("Hat"), + header: __( + "%1 is a CUSTOM property, and will not transfer to any other data formats.", + // Hat type warning label + __("Hat type") + ), items: [ { type: FeatureSetType.Icon, forceRender: true, - value: 0, - icon: '\n\n\n\n\n', - part: RenderPart.Head, + value: -1, + icon: `${__("Disabled")}`, + part: RenderPart.Head }, + makeSeparatorGapThinFSI(), ...ArrayNum(10) .slice(1) .map((k) => ({ type: FeatureSetType.Icon as any, forceRender: true, - value: k, + value: k - 1, icon: data.icons.hat[k - 1], - part: RenderPart.Head, - })), - ], + part: RenderPart.Head + })) + ] }, - extHatColor: { - label: "Hat Color", - header: - "Hat color is a CUSTOM property, and will not transfer to any other data formats.", + hatColor: { + // hat color tab name + label: __("Hat Color"), + header: __( + "%1 is a CUSTOM property, and will not transfer to any other data formats.", + // Hat color warning label + __("Hat color") + ), items: [ { type: FeatureSetType.Icon, forceRender: true, - value: 0, - icon: '\n\n\n\n\n', + value: -1, + icon: `${__("Disabled")}`, part: RenderPart.Head, + property: ["hatFavoriteColor", "hatCommonColor"], + selectedCondition: () => + data.mii.hatCommonColor === -1 && + data.mii.hatFavoriteColor === -1 }, - ...ArrayNum(12).map((k) => ({ + makeSeparatorGapThinFSI(), + ...(ArrayNum(12).map((k) => ({ type: FeatureSetType.Icon as any, forceRender: true, - value: k + 1, + value: k, color: numToHex(MiiFavoriteColorLookupTable[k]), part: RenderPart.Head, - })), - ], - }, - }, + property: "hatFavoriteColor", + preSelectCallback: (mii) => { + mii.hatFavoriteColor = k; + mii.hatCommonColor = -1; + } + })) as FeatureSetIconItem[]), + makeSeparatorFSI(), + ...rearrangeArray( + ArrayNum(100).map((k) => ({ + type: FeatureSetType.Icon, + value: k, + color: SwitchMiiColorTable[k], + part: RenderPart.Head, + property: "hatCommonColor", + preSelectCallback: (mii) => { + mii.hatFavoriteColor = -1; + mii.hatCommonColor = k; + } + })) as FeatureSetIconItem[], + MiiSwitchColorTable, + makeSeparatorGapThinLaptop + ) + ] + } + } }) ); } diff --git a/src/ui/tabs/Eye.ts b/src/ui/tabs/Eye.ts index a259922..95037c4 100644 --- a/src/ui/tabs/Eye.ts +++ b/src/ui/tabs/Eye.ts @@ -1,10 +1,11 @@ import { FeatureSetType, MiiPagedFeatureSet, + type FeatureSetIconItem } from "../components/MiiPagedFeatureSet"; import { - MiiEyeColorTable, SwitchMiiColorTable, + Ver3EyeColorTable } from "../../constants/ColorTables"; import { ArrayNum } from "../../util/Numbers"; import type { TabRenderInit } from "../../constants/TabRenderType"; @@ -12,71 +13,94 @@ import EditorIcons from "../../constants/EditorIcons"; import { RenderPart } from "../../class/MiiEditor"; import { makeSeparatorFSI, + makeSeparatorGapThinDesktop, + makeSeparatorGapThinLaptop, + MiiEyeRotationGroups, + MiiEyeTable, MiiSwitchColorTable, - rearrangeArray, + rearrangeArray } from "../../constants/MiiFeatureTable"; -import type Mii from "../../external/mii-js/mii"; + +import { _ } from "../../util/Lang"; +const __ = _(); export function EyeTab(data: TabRenderInit) { - let mii: Mii = data.mii; data.container.append( MiiPagedFeatureSet({ mii: data.mii, - // hacky workaround for color palette - onChange: (newMii, forceRender, renderPart) => { - data.callback(newMii, forceRender, renderPart); - mii = newMii; - }, + onChange: data.callback, entries: { eyeType: { - label: "Type", - // rearrangeArray( - items: ArrayNum(60).map((k) => ({ - type: FeatureSetType.Icon, - value: k, - icon: data.icons.eyes[k], - part: RenderPart.Face, - })), - // MiiEyeTable - // ), + label: __("Type"), + items: rearrangeArray( + ArrayNum(60).map( + (k) => + ({ + type: FeatureSetType.Icon, + value: k, + icon: data.icons.eyes[k], + part: RenderPart.Face, + preSelectCallback(tmpMii) { + // new - old + tmpMii.eyeRotate += + MiiEyeRotationGroups[k] - + MiiEyeRotationGroups[tmpMii.eyeType]; + } + }) as FeatureSetIconItem + ), + MiiEyeTable, + makeSeparatorGapThinDesktop + ) }, eyeColor: { - label: EditorIcons.color, - validationProperty: "trueEyeColor", - // EXTREMELY HACKY but works.. - validationFunction() { - if (mii.trueEyeColor > 5) { - return mii.extEyeColor + 6; - } else return mii.trueEyeColor; - }, + label: data.useAccessibility ? __("Color") : EditorIcons.color, items: [ - ...ArrayNum(6).map((k) => ({ - type: FeatureSetType.Icon, - value: k, - color: MiiEyeColorTable[k], - part: RenderPart.Face, - property: "fflEyeColor", - })), + ...ArrayNum(6).map( + (k) => + ({ + type: FeatureSetType.Icon, + value: Ver3EyeColorTable[k], + color: SwitchMiiColorTable[Ver3EyeColorTable[k]], + part: RenderPart.Face + }) as FeatureSetIconItem + ), makeSeparatorFSI(), ...rearrangeArray( ArrayNum(100).map((k) => ({ type: FeatureSetType.Icon, - value: k + 6, - // icon: `${k}`, + value: k, color: SwitchMiiColorTable[k], - part: RenderPart.Face, - property: "extEyeColor", + part: RenderPart.Face })), - MiiSwitchColorTable - ), + MiiSwitchColorTable, + makeSeparatorGapThinLaptop + ) + ] + }, + eyeSclera: { + label: __("Sclera"), + items: [ + { + type: FeatureSetType.Switch, + part: RenderPart.Face, + iconOff: __("Disabled"), + iconOn: __("Enabled"), + property: "eyeSclera", + isNumber: true + } ], + header: __( + "%1 is a CUSTOM property, and will not transfer to any other data formats.", + // Hat type warning label + __("Sclera fill") + ) }, eyePosition: { - label: "Position", + label: __("Position"), items: [ { type: FeatureSetType.Range, - property: "eyeYPosition", + property: "eyeY", iconStart: EditorIcons.positionMoveUp, iconEnd: EditorIcons.positionMoveDown, soundStart: "position_down", @@ -84,11 +108,12 @@ export function EyeTab(data: TabRenderInit) { min: 0, max: 18, part: RenderPart.Face, - inverse: true + inverse: true, + label: data.useAccessibility ? __("Position") : undefined }, { type: FeatureSetType.Range, - property: "eyeSpacing", + property: "eyeX", iconStart: EditorIcons.positionPushIn, iconEnd: EditorIcons.positionPushOut, soundStart: "move_together", @@ -96,10 +121,11 @@ export function EyeTab(data: TabRenderInit) { min: 0, max: 12, part: RenderPart.Face, + label: data.useAccessibility ? __("Spacing") : undefined }, { type: FeatureSetType.Range, - property: "eyeRotation", + property: "eyeRotate", iconStart: EditorIcons.positionRotateCW, iconEnd: EditorIcons.positionRotateCCW, soundStart: "rotate_cw", @@ -107,7 +133,7 @@ export function EyeTab(data: TabRenderInit) { min: 0, max: 7, part: RenderPart.Face, - inverse: true + label: data.useAccessibility ? __("Rotation") : undefined }, { type: FeatureSetType.Range, @@ -119,10 +145,11 @@ export function EyeTab(data: TabRenderInit) { min: 0, max: 7, part: RenderPart.Face, + label: data.useAccessibility ? __("Scale") : undefined }, { type: FeatureSetType.Range, - property: "eyeVerticalStretch", + property: "eyeAspect", iconStart: EditorIcons.positionStretchIn, iconEnd: EditorIcons.positionStretchOut, soundStart: "vert_stretch_down", @@ -130,10 +157,11 @@ export function EyeTab(data: TabRenderInit) { min: 0, max: 6, part: RenderPart.Face, - }, - ], - }, - }, + label: data.useAccessibility ? __("Stretch") : undefined + } + ] + } + } }) ); } diff --git a/src/ui/tabs/Eyebrow.ts b/src/ui/tabs/Eyebrow.ts index 4acce45..8788305 100644 --- a/src/ui/tabs/Eyebrow.ts +++ b/src/ui/tabs/Eyebrow.ts @@ -1,10 +1,12 @@ import { FeatureSetType, MiiPagedFeatureSet, + type FeatureSetIconItem } from "../components/MiiPagedFeatureSet"; import { MiiHairColorTable, SwitchMiiColorTable, + Ver3HairColorTable } from "../../constants/ColorTables"; import { ArrayNum } from "../../util/Numbers"; import type { TabRenderInit } from "../../constants/TabRenderType"; @@ -12,67 +14,73 @@ import EditorIcons from "../../constants/EditorIcons"; import { RenderPart } from "../../class/MiiEditor"; import { makeSeparatorFSI, + makeSeparatorGapThinDesktop, + makeSeparatorGapThinLaptop, + MiiEyebrowRotationGroups, + MiiEyebrowTable, MiiSwitchColorTable, - rearrangeArray, + rearrangeArray } from "../../constants/MiiFeatureTable"; -import type Mii from "../../external/mii-js/mii"; + +import { _ } from "../../util/Lang"; +const __ = _(); export function EyebrowTab(data: TabRenderInit) { - let mii: Mii = data.mii; data.container.append( MiiPagedFeatureSet({ mii: data.mii, - // hacky workaround for color palette - onChange: (newMii, forceRender, renderPart) => { - data.callback(newMii, forceRender, renderPart); - mii = newMii; - }, + onChange: data.callback, entries: { eyebrowType: { - label: "Type", - items: ArrayNum(24).map((k) => ({ - type: FeatureSetType.Icon, - value: k, - icon: data.icons.eyebrows[k], - part: RenderPart.Face, - })), + label: __("Type"), + items: rearrangeArray( + ArrayNum(24).map( + (k) => + ({ + type: FeatureSetType.Icon, + value: k, + icon: data.icons.eyebrows[k], + part: RenderPart.Face, + preSelectCallback(tmpMii) { + // new - old + tmpMii.eyebrowRotate += + MiiEyebrowRotationGroups[k] - + MiiEyebrowRotationGroups[tmpMii.eyebrowType]; + } + }) as FeatureSetIconItem + ), + MiiEyebrowTable, + makeSeparatorGapThinDesktop + ) }, eyebrowColor: { - label: EditorIcons.color, - validationProperty: "trueEyebrowColor", - // EXTREMELY HACKY but works.. - validationFunction() { - if (mii.trueEyebrowColor > 7) { - return mii.trueEyebrowColor + 8; - } else return mii.trueEyebrowColor; - }, + label: data.useAccessibility ? __("Color") : EditorIcons.color, items: [ ...ArrayNum(8).map((k) => ({ type: FeatureSetType.Icon, - value: k, - color: MiiHairColorTable[k], - part: RenderPart.Face, - property: "fflEyebrowColor", + value: Ver3HairColorTable[k], + color: SwitchMiiColorTable[Ver3HairColorTable[k]], + part: RenderPart.Face })), makeSeparatorFSI(), ...rearrangeArray( ArrayNum(100).map((k) => ({ type: FeatureSetType.Icon, - value: k + 8, + value: k, color: SwitchMiiColorTable[k], - part: RenderPart.Face, - property: "extEyebrowColor", + part: RenderPart.Face })), - MiiSwitchColorTable - ), - ], + MiiSwitchColorTable, + makeSeparatorGapThinLaptop + ) + ] }, eyebrowPosition: { - label: "Position", + label: __("Position"), items: [ { type: FeatureSetType.Range, - property: "eyebrowYPosition", + property: "eyebrowY", iconStart: EditorIcons.positionMoveUp, iconEnd: EditorIcons.positionMoveDown, soundStart: "position_down", @@ -80,11 +88,12 @@ export function EyebrowTab(data: TabRenderInit) { min: 3, max: 18, part: RenderPart.Face, - inverse: true + inverse: true, + label: data.useAccessibility ? __("Position") : undefined }, { type: FeatureSetType.Range, - property: "eyebrowSpacing", + property: "eyebrowX", iconStart: EditorIcons.positionPushIn, iconEnd: EditorIcons.positionPushOut, soundStart: "move_together", @@ -92,10 +101,11 @@ export function EyebrowTab(data: TabRenderInit) { min: 0, max: 12, part: RenderPart.Face, + label: data.useAccessibility ? __("Spacing") : undefined }, { type: FeatureSetType.Range, - property: "eyebrowRotation", + property: "eyebrowRotate", iconStart: EditorIcons.positionRotateCW, iconEnd: EditorIcons.positionRotateCCW, soundStart: "rotate_cw", @@ -103,7 +113,7 @@ export function EyebrowTab(data: TabRenderInit) { min: 0, max: 11, part: RenderPart.Face, - inverse: true + label: data.useAccessibility ? __("Rotation") : undefined }, { type: FeatureSetType.Range, @@ -115,10 +125,11 @@ export function EyebrowTab(data: TabRenderInit) { min: 0, max: 8, part: RenderPart.Face, + label: data.useAccessibility ? __("Scale") : undefined }, { type: FeatureSetType.Range, - property: "eyebrowVerticalStretch", + property: "eyebrowAspect", iconStart: EditorIcons.positionStretchIn, iconEnd: EditorIcons.positionStretchOut, soundStart: "vert_stretch_down", @@ -126,10 +137,11 @@ export function EyebrowTab(data: TabRenderInit) { min: 0, max: 6, part: RenderPart.Face, - }, - ], - }, - }, + label: data.useAccessibility ? __("Stretch") : undefined + } + ] + } + } }) ); } diff --git a/src/ui/tabs/FacialHair.ts b/src/ui/tabs/FacialHair.ts index 6cc1c60..2a200ae 100644 --- a/src/ui/tabs/FacialHair.ts +++ b/src/ui/tabs/FacialHair.ts @@ -1,10 +1,11 @@ import { FeatureSetType, - MiiPagedFeatureSet, + MiiPagedFeatureSet } from "../components/MiiPagedFeatureSet"; import { MiiHairColorTable, SwitchMiiColorTable, + Ver3HairColorTable } from "../../constants/ColorTables"; import { ArrayNum } from "../../util/Numbers"; import type { TabRenderInit } from "../../constants/TabRenderType"; @@ -12,37 +13,35 @@ import EditorIcons from "../../constants/EditorIcons"; import { RenderPart } from "../../class/MiiEditor"; import { makeSeparatorFSI, + makeSeparatorGapThinLaptop, MiiSwitchColorTable, - rearrangeArray, + rearrangeArray } from "../../constants/MiiFeatureTable"; -import type Mii from "../../external/mii-js/mii"; + +import { _ } from "../../util/Lang"; +const __ = _(); export function FacialHairTab(data: TabRenderInit) { - let mii: Mii = data.mii; data.container.append( MiiPagedFeatureSet({ mii: data.mii, - // hacky workaround for color palette - onChange: (newMii, forceRender, renderPart) => { - data.callback(newMii, forceRender, renderPart); - mii = newMii; - }, + onChange: data.callback, entries: { mustacheType: { - label: "Mustache", + label: __("Mustache"), items: ArrayNum(6).map((k) => ({ type: FeatureSetType.Icon, value: k, icon: data.icons.mustache[k], - part: RenderPart.Face, - })), + part: RenderPart.Face + })) }, mustachePosition: { - label: "Position", + label: __("Position"), items: [ { type: FeatureSetType.Range, - property: "mustacheYPosition", + property: "mustacheY", iconStart: EditorIcons.positionMoveUp, iconEnd: EditorIcons.positionMoveDown, soundStart: "position_down", @@ -50,7 +49,8 @@ export function FacialHairTab(data: TabRenderInit) { min: 0, max: 16, part: RenderPart.Face, - inverse: true + inverse: true, + label: data.useAccessibility ? "Position" : undefined }, { type: FeatureSetType.Range, @@ -62,49 +62,44 @@ export function FacialHairTab(data: TabRenderInit) { min: 0, max: 8, part: RenderPart.Face, - }, - ], + label: data.useAccessibility ? "Scale" : undefined + } + ] }, beardType: { - label: "Goatee", + label: __("Beard"), items: ArrayNum(6).map((k) => ({ type: FeatureSetType.Icon, value: k, icon: data.icons.goatee[k], - part: RenderPart.Head, - })), + part: RenderPart.Head + })) }, - facialHairColor: { - label: EditorIcons.color, - validationProperty: "trueFacialHairColor", - // EXTREMELY HACKY but works.. - validationFunction() { - if (mii.trueFacialHairColor > 7) { - return mii.trueFacialHairColor + 8; - } else return mii.trueFacialHairColor; - }, + beardColor: { + label: data.useAccessibility ? __("Color") : EditorIcons.color, items: [ ...ArrayNum(8).map((k) => ({ type: FeatureSetType.Icon, - value: k, - color: MiiHairColorTable[k], + value: Ver3HairColorTable[k], + color: SwitchMiiColorTable[Ver3HairColorTable[k]], part: RenderPart.Head, - property: "fflHairColor", + property: "beardColor" })), makeSeparatorFSI(), ...rearrangeArray( ArrayNum(100).map((k) => ({ type: FeatureSetType.Icon, - value: k + 8, + value: k, color: SwitchMiiColorTable[k], part: RenderPart.Head, - property: "extHairColor", + property: "beardColor" })), - MiiSwitchColorTable - ), - ], - }, - }, + MiiSwitchColorTable, + makeSeparatorGapThinLaptop + ) + ] + } + } }) ); } diff --git a/src/ui/tabs/FavoriteColor.ts b/src/ui/tabs/FavoriteColor.ts index f1ef3ff..fdeb9fe 100644 --- a/src/ui/tabs/FavoriteColor.ts +++ b/src/ui/tabs/FavoriteColor.ts @@ -1,12 +1,25 @@ import { FeatureSetType, - MiiPagedFeatureSet, + MiiPagedFeatureSet } from "../components/MiiPagedFeatureSet"; -import { MiiFavoriteColorLookupTable } from "../../constants/ColorTables"; +import { + ForbiddenShirtPantColors, + MiiFavoriteColorLookupTable, + SwitchMiiColorTable +} from "../../constants/ColorTables"; import { ArrayNum } from "../../util/Numbers"; import type { TabRenderInit } from "../../constants/TabRenderType"; import { numToHex } from "../../util/NumberToHexString"; -import { RenderPart } from "../../class/MiiEditor"; +import { BodyUpdateType, RenderPart } from "../../class/MiiEditor"; +import { + makeSeparatorGapThinFSI, + makeSeparatorGapThinLaptop, + MiiSwitchColorTable, + rearrangeArray +} from "../../constants/MiiFeatureTable"; + +import { _ } from "../../util/Lang"; +const __ = _(); export function FavoriteColorTab(data: TabRenderInit) { data.container.append( @@ -15,16 +28,17 @@ export function FavoriteColorTab(data: TabRenderInit) { onChange: data.callback, entries: { favoriteColor: { - label: "Favorite Color", + label: __("Favorite Color"), items: ArrayNum(12).map((k) => ({ type: FeatureSetType.Icon, forceRender: true, value: k, color: numToHex(MiiFavoriteColorLookupTable[k]), part: RenderPart.Head, - })), - }, - }, + bodyUpdateType: BodyUpdateType.ClothingUpdate + })) + } + } }) ); } diff --git a/src/ui/tabs/Glasses.ts b/src/ui/tabs/Glasses.ts index 2f49f3f..3debfc4 100644 --- a/src/ui/tabs/Glasses.ts +++ b/src/ui/tabs/Glasses.ts @@ -1,10 +1,11 @@ import { FeatureSetType, - MiiPagedFeatureSet, + MiiPagedFeatureSet } from "../components/MiiPagedFeatureSet"; import { MiiGlassesColorTable, SwitchMiiColorTable, + Ver3GlassColorTable } from "../../constants/ColorTables"; import { ArrayNum } from "../../util/Numbers"; import type { TabRenderInit } from "../../constants/TabRenderType"; @@ -12,67 +13,62 @@ import EditorIcons from "../../constants/EditorIcons"; import { RenderPart } from "../../class/MiiEditor"; import { makeSeparatorFSI, + makeSeparatorGapThinLaptop, MiiSwitchColorTable, - rearrangeArray, + rearrangeArray } from "../../constants/MiiFeatureTable"; -import type Mii from "../../external/mii-js/mii"; + +import { _ } from "../../util/Lang"; +const __ = _(); export function GlassesTab(data: TabRenderInit) { - let mii: Mii = data.mii; data.container.append( MiiPagedFeatureSet({ mii: data.mii, // hacky workaround for color palette - onChange: (newMii, forceRender, renderPart) => { - data.callback(newMii, forceRender, renderPart); - mii = newMii; + onChange: (newMii, forceRender, renderPart, updateType) => { + data.callback(newMii, forceRender, renderPart, updateType); }, entries: { - glassesType: { - label: "Type", + glassType: { + label: __("Type"), items: ArrayNum(20).map((k) => ({ type: FeatureSetType.Icon, value: k, icon: data.icons.glasses[k], - part: RenderPart.Head, - })), + part: RenderPart.Head + })) }, glassesColor: { - label: EditorIcons.color, - validationProperty: "trueGlassesColor", - // EXTREMELY HACKY but works.. - validationFunction() { - if (mii.trueGlassesColor > 5) { - return mii.trueGlassesColor + 6; - } else return mii.trueGlassesColor; - }, + label: data.useAccessibility ? __("Color") : EditorIcons.color, items: [ ...ArrayNum(6).map((k) => ({ type: FeatureSetType.Icon, - value: k, - color: MiiGlassesColorTable[k], + value: Ver3GlassColorTable[k], + color: SwitchMiiColorTable[Ver3GlassColorTable[k]], part: RenderPart.Head, - property: "fflGlassesColor", + property: "glassColor" })), makeSeparatorFSI(), ...rearrangeArray( ArrayNum(100).map((k) => ({ type: FeatureSetType.Icon, - value: k + 6, + value: k, color: SwitchMiiColorTable[k], part: RenderPart.Head, - property: "extGlassColor", + property: "glassColor" })), - MiiSwitchColorTable - ), - ], + MiiSwitchColorTable, + makeSeparatorGapThinLaptop + ) + ] }, glassesPosition: { - label: "Position", + label: __("Position"), items: [ { type: FeatureSetType.Range, - property: "glassesYPosition", + property: "glassY", iconStart: EditorIcons.positionMoveUp, iconEnd: EditorIcons.positionMoveDown, soundStart: "position_down", @@ -80,11 +76,12 @@ export function GlassesTab(data: TabRenderInit) { min: 0, max: 20, part: RenderPart.Head, - inverse: true + inverse: true, + label: data.useAccessibility ? __("Position") : undefined }, { type: FeatureSetType.Range, - property: "glassesScale", + property: "glassScale", iconStart: EditorIcons.positionSizeDown, iconEnd: EditorIcons.positionSizeUp, soundStart: "scale_down", @@ -92,10 +89,11 @@ export function GlassesTab(data: TabRenderInit) { min: 0, max: 7, part: RenderPart.Head, - }, - ], - }, - }, + label: data.useAccessibility ? __("Scale") : undefined + } + ] + } + } }) ); } diff --git a/src/ui/tabs/Hair.ts b/src/ui/tabs/Hair.ts index e211315..7fba233 100644 --- a/src/ui/tabs/Hair.ts +++ b/src/ui/tabs/Hair.ts @@ -1,86 +1,88 @@ import { FeatureSetType, - MiiPagedFeatureSet, + MiiPagedFeatureSet } from "../components/MiiPagedFeatureSet"; import EditorIcons from "../../constants/EditorIcons"; -import { SwitchMiiColorTable } from "../../constants/ColorTables"; +import { + SwitchMiiColorTable, + Ver3HairColorTable +} from "../../constants/ColorTables"; import type { TabRenderInit } from "../../constants/TabRenderType"; import { ArrayNum } from "../../util/Numbers"; import { RenderPart } from "../../class/MiiEditor"; import { makeSeparatorFSI, + makeSeparatorGapThinDesktop, + makeSeparatorGapThinLaptop, MiiHairTable, MiiSwitchColorTable, - rearrangeArray, + rearrangeArray } from "../../constants/MiiFeatureTable"; -import type Mii from "../../external/mii-js/mii"; + +import { _ } from "../../util/Lang"; +const __ = _(); export function HairTab(data: TabRenderInit) { - let mii: Mii = data.mii; data.container.append( MiiPagedFeatureSet({ mii: data.mii, // hacky workaround for color palette - onChange: (newMii, forceRender, renderPart) => { - data.callback(newMii, forceRender, renderPart); - mii = newMii; + onChange: (newMii, forceRender, renderPart, updateType) => { + data.callback(newMii, forceRender, renderPart, updateType); }, entries: { hairType: { - label: "Type", + label: __("Type"), items: rearrangeArray( ArrayNum(132).map((k) => ({ type: FeatureSetType.Icon, value: k, - icon: data.icons.hair[k], // ``, - part: RenderPart.Head, + icon: data.icons.hair[k], + part: RenderPart.Head })), - MiiHairTable - ), + MiiHairTable, + makeSeparatorGapThinDesktop + ) }, hairColor: { - label: EditorIcons.color, - validationProperty: "trueHairColor", - // EXTREMELY HACKY but works.. - validationFunction() { - if (mii.trueHairColor > 7) { - return mii.trueHairColor + 8; - } else return mii.trueHairColor; - }, + label: data.useAccessibility ? __("Color") : EditorIcons.color, items: [ ...ArrayNum(8).map((k) => ({ type: FeatureSetType.Icon, - value: k, - color: SwitchMiiColorTable[k], - part: RenderPart.Head, - property: "fflHairColor", + value: Ver3HairColorTable[k], + color: SwitchMiiColorTable[Ver3HairColorTable[k]], + part: RenderPart.Head })), makeSeparatorFSI(), ...rearrangeArray( ArrayNum(100).map((k) => ({ type: FeatureSetType.Icon, - value: k + 8, + value: k, color: SwitchMiiColorTable[k], - part: RenderPart.Head, - property: "extHairColor", + part: RenderPart.Head })), - MiiSwitchColorTable - ), - ], + MiiSwitchColorTable, + makeSeparatorGapThinLaptop + ) + ] }, hairPosition: { - label: "Position", + label: __("Hair Flip"), items: [ { type: FeatureSetType.Switch, - iconOff: EditorIcons.positionHairFlip, - iconOn: EditorIcons.positionHairFlipped, - property: "flipHair", - part: RenderPart.Head, - }, - ], - }, - }, + iconOff: data.useAccessibility + ? __("Unflipped") + : EditorIcons.positionHairFlip, + iconOn: data.useAccessibility + ? __("Flipped") + : EditorIcons.positionHairFlipped, + property: "hairFlip", + part: RenderPart.Head + } + ] + } + } }) ); } diff --git a/src/ui/tabs/Head.ts b/src/ui/tabs/Head.ts index 66c77a2..e3ef721 100644 --- a/src/ui/tabs/Head.ts +++ b/src/ui/tabs/Head.ts @@ -1,65 +1,76 @@ import { FeatureSetType, - MiiPagedFeatureSet, + MiiPagedFeatureSet } from "../components/MiiPagedFeatureSet"; import EditorIcons from "../../constants/EditorIcons"; import { MiiSkinColorTable, MiiSwitchSkinColorList, - SwitchMiiColorTable, + SwitchMiiColorTable } from "../../constants/ColorTables"; import type { TabRenderInit } from "../../constants/TabRenderType"; import { ArrayNum } from "../../util/Numbers"; -import { RenderPart } from "../../class/MiiEditor"; +import { BodyUpdateType, RenderPart } from "../../class/MiiEditor"; import { makeSeparatorFSI, + makeSeparatorGapThinDesktop, makeSeparatorGapThinFSI, + makeSeparatorGapThinLaptop, MiiSwitchColorTable, MiiSwitchSkinColorTable, - rearrangeArray, + rearrangeArray } from "../../constants/MiiFeatureTable"; +import { _ } from "../../util/Lang"; +const __ = _(); + export function HeadTab(data: TabRenderInit) { data.container.append( MiiPagedFeatureSet({ mii: data.mii, onChange: data.callback, entries: { - faceType: { - label: EditorIcons.face, + facelineType: { + label: data.useAccessibility ? __("Shape") : EditorIcons.face, items: ArrayNum(12).map((k) => ({ type: FeatureSetType.Icon, value: k, icon: data.icons.face[k], part: RenderPart.Head, - })), + bodyUpdateType: BodyUpdateType.None + })) }, - makeupType: { - label: EditorIcons.face_makeup, + facelineMake: { + label: data.useAccessibility ? __("Makeup") : EditorIcons.face_makeup, items: ArrayNum(12).map((k) => ({ type: FeatureSetType.Icon, value: k, icon: data.icons.makeup[k], part: RenderPart.Head, - })), + bodyUpdateType: BodyUpdateType.None + })) }, - wrinklesType: { - label: EditorIcons.face_wrinkles, + facelineWrinkle: { + label: data.useAccessibility + ? __("Wrinkles") + : EditorIcons.face_wrinkles, items: ArrayNum(12).map((k) => ({ type: FeatureSetType.Icon, value: k, icon: data.icons.wrinkles[k], part: RenderPart.Head, - })), + bodyUpdateType: BodyUpdateType.None + })) }, - skinColor: { - label: EditorIcons.color, + facelineColor: { + label: data.useAccessibility ? __("Color") : EditorIcons.color, items: [ ...ArrayNum(6).map((k) => ({ type: FeatureSetType.Icon, value: k, color: MiiSkinColorTable[k], part: RenderPart.Head, + bodyUpdateType: BodyUpdateType.ClothingUpdate })), makeSeparatorFSI(), ...rearrangeArray( @@ -68,47 +79,47 @@ export function HeadTab(data: TabRenderInit) { value: k, color: MiiSwitchSkinColorList[k], part: RenderPart.Head, + bodyUpdateType: BodyUpdateType.ClothingUpdate })), - MiiSwitchSkinColorTable - ).slice(0, 5), - makeSeparatorGapThinFSI(), - ...rearrangeArray( - ArrayNum(10).map((k) => ({ - type: FeatureSetType.Icon, - value: k, - color: MiiSwitchSkinColorList[k], - part: RenderPart.Head, - })), - MiiSwitchSkinColorTable - ).slice(5), - ], + MiiSwitchSkinColorTable, + makeSeparatorGapThinFSI + ) + ] }, - extFacePaintColor: { - label: EditorIcons.face_paint, - header: - "Face paint is a CUSTOM property, and will not transfer to any other data formats.", + facePaintColor: { + label: data.useAccessibility + ? __("Face Paint") + : EditorIcons.face_paint, + header: __( + "%1 is a CUSTOM property, and will not transfer to any other data formats.", + // face paint warning label + __("Face paint") + ), items: [ { type: FeatureSetType.Icon, forceRender: true, - value: 0, - icon: '\n\n\n\n\n', + value: -1, + icon: `${__("Disabled")}`, part: RenderPart.Head, + bodyUpdateType: BodyUpdateType.ClothingUpdate }, + makeSeparatorGapThinFSI(), ...rearrangeArray( ArrayNum(100).map((k) => ({ type: FeatureSetType.Icon, - value: k + 1, + value: k, // icon: `${k}`, color: SwitchMiiColorTable[k], part: RenderPart.Head, - property: "extFacePaintColor", + bodyUpdateType: BodyUpdateType.ClothingUpdate })), - MiiSwitchColorTable - ), - ], - }, - }, + MiiSwitchColorTable, + makeSeparatorGapThinLaptop + ) + ] + } + } }) ); } diff --git a/src/ui/tabs/Misc.ts b/src/ui/tabs/Misc.ts index ad16256..1123152 100644 --- a/src/ui/tabs/Misc.ts +++ b/src/ui/tabs/Misc.ts @@ -1,67 +1,150 @@ import Html from "@datkat21/html"; import type { TabRenderInit } from "../../constants/TabRenderType"; -import { Buffer as Buf } from "../../../node_modules/buffer/index"; import { Input } from "../components/Input"; -import Mii from "../../external/mii-js/mii"; -import { RenderPart } from "../../class/MiiEditor"; +import Mii from "../../class/MiiData"; +import { BodyUpdateType, MiiEditor, RenderPart } from "../../class/MiiEditor"; +import { decodeUTF16LE, encodeUTF16LE } from "../../util/dataConvert"; + +import { _ } from "../../util/Lang"; +import { + FeatureSetType, + MiiPagedFeatureSet +} from "../components/MiiPagedFeatureSet"; +import EditorIcons from "../../constants/EditorIcons"; +import { makeSeparatorGapThinFSI } from "../../constants/MiiFeatureTable"; +const __ = _(); export function MiscTab(data: TabRenderInit) { - let tmpMii = new Mii(data.mii.encode()); + let tmpMii = new Mii(data.mii.export()); const setProp = (prop: string, val: any) => { + // i hate this + if (MiiEditor.getCurrentEditor() !== null) { + tmpMii = MiiEditor.getCurrentEditor()!.mii; + } + (tmpMii as any)[prop] = val; - data.callback(tmpMii, false, RenderPart.Head); + data.callback(tmpMii, false, RenderPart.Head, BodyUpdateType.None); return true; }; - data.container.append( + data.container.appendMany( new Html("div") .style({ padding: "1rem", display: "flex", "flex-direction": "column", - gap: "1rem", + gap: "1rem" }) .appendMany( Input( - "Name", - data.mii.miiName, + // mii's name + __("Name"), + data.mii.nickname, // set - (name) => setProp("miiName", name.trim()), + (name) => setProp("nickname", name.trim()), // validate (name) => { - const nameBuffer = Buf.from(name, "utf16le"); + const nameBuffer = encodeUTF16LE(name); // Empty string check - let nameStr = nameBuffer.toString("utf16le"); - if (nameStr.trim() === "") return false; + let nameStr = decodeUTF16LE(nameBuffer); + if (nameStr.trim() === "") return __("Name is empty"); // Name length check - if (nameBuffer.length <= 0x14 && nameBuffer.length !== 0) - return true; + if (nameBuffer.length > 0x14) return __("Name is too long"); + if (nameBuffer.length === 0) return __("Name is too short"); - return false; + return true; }, data.editor ), Input( - "Creator", - data.mii.creatorName, + // mii's creator name + __("Creator"), + data.mii.creator, // set - (creator) => setProp("creatorName", creator.trim()), + (creator) => setProp("creator", creator.trim()), // validate (name) => { - const nameBuffer = Buf.from(name, "utf16le"); + const nameBuffer = encodeUTF16LE(name); // Empty string check - let nameStr = nameBuffer.toString("utf16le"); - if (nameStr.trim() === "") return false; + let nameStr = decodeUTF16LE(nameBuffer); + if (nameStr.length === 0) return true; + if (nameStr.trim() === "") return __("Creator name is empty"); // Name length check - if (nameBuffer.length <= 0x14) return true; + if (nameBuffer.length > 0x14) return __("Creator name is too long"); - return false; + return true; }, data.editor ) + ), + new Html("div") + .class("input-group") + .style({ + height: "max-content" + // margin: "0 -16px 0 -16px", + // width: "calc(100% + 32px)" + }) + .appendMany( + MiiPagedFeatureSet({ + mii: data.mii, + onChange: data.callback, + entries: { + gender: { + label: __("Gender"), + items: [ + { + type: FeatureSetType.Switch, + iconOff: data.useAccessibility + ? __("Male") + : EditorIcons.genderMale, + iconOn: data.useAccessibility + ? __("Female") + : EditorIcons.genderFemale, + property: "gender", + isNumber: true, + forceRender: true, + part: RenderPart.Body, + bodyUpdateType: BodyUpdateType.ClothingUpdate, + soundOff: "select_misc", + soundOn: "select_misc" + } + ] + }, + favorite: { + label: __("Favorite/Special"), + items: [ + { + type: FeatureSetType.Switch, + iconOff: __("Normal"), + iconOn: __("Favorite"), + property: "favorite", + isNumber: true, + forceRender: false, + part: RenderPart.Body, + bodyUpdateType: BodyUpdateType.ClothingUpdate, + soundOff: "select_color", + soundOn: "select_color" + }, + makeSeparatorGapThinFSI(), + { + type: FeatureSetType.Switch, + iconOff: __("Normal"), + iconOn: __("Special"), + property: "special", + isNumber: true, + forceRender: false, + part: RenderPart.Body, + bodyUpdateType: BodyUpdateType.ClothingUpdate, + soundOff: "select_color", + soundOn: "select_color" + } + ] + } + } + }) ) ); } diff --git a/src/ui/tabs/Mole.ts b/src/ui/tabs/Mole.ts index 5a65c9c..b972d7a 100644 --- a/src/ui/tabs/Mole.ts +++ b/src/ui/tabs/Mole.ts @@ -1,30 +1,34 @@ import { FeatureSetType, - MiiPagedFeatureSet, + MiiPagedFeatureSet } from "../components/MiiPagedFeatureSet"; import type { TabRenderInit } from "../../constants/TabRenderType"; import EditorIcons from "../../constants/EditorIcons"; import { RenderPart } from "../../class/MiiEditor"; +import { _ } from "../../util/Lang"; +const __ = _(); + export function MoleTab(data: TabRenderInit) { data.container.append( MiiPagedFeatureSet({ mii: data.mii, onChange: data.callback, entries: { - eyePosition: { - label: "Position", + mole: { + label: __("Mole"), items: [ { type: FeatureSetType.Switch, - iconOff: "Disable", - iconOn: "Enable", - property: "moleEnabled", + iconOff: __("Disable"), + iconOn: __("Enable"), + property: "moleType", part: RenderPart.Face, + isNumber: true }, { type: FeatureSetType.Range, - property: "moleYPosition", + property: "moleY", iconStart: EditorIcons.positionMoveUp, iconEnd: EditorIcons.positionMoveDown, soundStart: "position_down", @@ -32,11 +36,12 @@ export function MoleTab(data: TabRenderInit) { min: 0, max: 30, part: RenderPart.Face, - inverse: true + inverse: true, + label: data.useAccessibility ? __("Position") : undefined }, { type: FeatureSetType.Range, - property: "moleXPosition", + property: "moleX", iconStart: EditorIcons.positionPushIn, iconEnd: EditorIcons.positionPushOut, soundStart: "move_together", @@ -44,6 +49,8 @@ export function MoleTab(data: TabRenderInit) { min: 0, max: 16, part: RenderPart.Face, + + label: data.useAccessibility ? __("Spacing") : undefined }, { type: FeatureSetType.Range, @@ -55,10 +62,11 @@ export function MoleTab(data: TabRenderInit) { min: 0, max: 7, part: RenderPart.Face, - }, - ], - }, - }, + label: data.useAccessibility ? __("Scale") : undefined + } + ] + } + } }) ); } diff --git a/src/ui/tabs/Mouth.ts b/src/ui/tabs/Mouth.ts index 7a6e7a1..60da167 100644 --- a/src/ui/tabs/Mouth.ts +++ b/src/ui/tabs/Mouth.ts @@ -1,6 +1,6 @@ import { FeatureSetType, - MiiPagedFeatureSet, + MiiPagedFeatureSet } from "../components/MiiPagedFeatureSet"; import { ArrayNum } from "../../util/Numbers"; import type { TabRenderInit } from "../../constants/TabRenderType"; @@ -8,73 +8,73 @@ import EditorIcons from "../../constants/EditorIcons"; import { MiiMouthColorTable, SwitchMiiColorTable, + Ver3MouthColorTable } from "../../constants/ColorTables"; import { RenderPart } from "../../class/MiiEditor"; import { makeSeparatorFSI, + makeSeparatorGapThinDesktop, + makeSeparatorGapThinLaptop, + MiiMouthTable, MiiSwitchColorTable, - rearrangeArray, + rearrangeArray } from "../../constants/MiiFeatureTable"; -import type Mii from "../../external/mii-js/mii"; -export function MouthTab(data: TabRenderInit) { - let mii: Mii = data.mii; +import { _ } from "../../util/Lang"; +const __ = _(); +export function MouthTab(data: TabRenderInit) { data.container.append( MiiPagedFeatureSet({ mii: data.mii, // hacky workaround for color palette - onChange: (newMii, forceRender, renderPart) => { - data.callback(newMii, forceRender, renderPart); - mii = newMii; + onChange: (newMii, forceRender, renderPart, updateType) => { + data.callback(newMii, forceRender, renderPart, updateType); }, entries: { mouthType: { - label: "Type", - items: ArrayNum(36).map((k) => ({ - type: FeatureSetType.Icon, - value: k, - icon: data.icons.mouth[k], - part: RenderPart.Face, - })), + label: __("Type"), + items: rearrangeArray( + ArrayNum(36).map((k) => ({ + type: FeatureSetType.Icon, + value: k, + icon: data.icons.mouth[k], + part: RenderPart.Face + })), + MiiMouthTable, + makeSeparatorGapThinDesktop + ) }, mouthColor: { - label: EditorIcons.color, - validationProperty: "trueMouthColor", - // EXTREMELY HACKY but works.. - validationFunction() { - if (mii.trueMouthColor > 4) { - return mii.trueMouthColor + 5; - } else return mii.trueMouthColor; - }, + label: data.useAccessibility ? __("Color") : EditorIcons.color, items: [ ...ArrayNum(5).map((k) => ({ type: FeatureSetType.Icon, - value: k, - color: MiiMouthColorTable[k], + value: Ver3MouthColorTable[k], + color: SwitchMiiColorTable[Ver3MouthColorTable[k]], part: RenderPart.Face, - property: "fflMouthColor", + property: "mouthColor" })), makeSeparatorFSI(), ...rearrangeArray( ArrayNum(100).map((k) => ({ type: FeatureSetType.Icon, - value: k + 5, + value: k, color: SwitchMiiColorTable[k], - // icon: `${k}`, part: RenderPart.Face, - property: "extMouthColor", + property: "mouthColor" })), - MiiSwitchColorTable - ), - ], + MiiSwitchColorTable, + makeSeparatorGapThinLaptop + ) + ] }, mouthPosition: { - label: "Position", + label: __("Position"), items: [ { type: FeatureSetType.Range, - property: "mouthYPosition", + property: "mouthY", iconStart: EditorIcons.positionMoveUp, iconEnd: EditorIcons.positionMoveDown, soundStart: "position_down", @@ -82,7 +82,8 @@ export function MouthTab(data: TabRenderInit) { min: 0, max: 18, part: RenderPart.Face, - inverse: true + inverse: true, + label: data.useAccessibility ? __("Position") : undefined }, { type: FeatureSetType.Range, @@ -94,10 +95,11 @@ export function MouthTab(data: TabRenderInit) { min: 0, max: 8, part: RenderPart.Face, + label: data.useAccessibility ? __("Scale") : undefined }, { type: FeatureSetType.Range, - property: "mouthHorizontalStretch", + property: "mouthAspect", iconStart: EditorIcons.positionStretchIn, iconEnd: EditorIcons.positionStretchOut, soundStart: "vert_stretch_down", @@ -105,10 +107,11 @@ export function MouthTab(data: TabRenderInit) { min: 0, max: 6, part: RenderPart.Face, - }, - ], - }, - }, + label: data.useAccessibility ? __("Stretch") : undefined + } + ] + } + } }) ); } diff --git a/src/ui/tabs/Nose.ts b/src/ui/tabs/Nose.ts index 0cfbb0f..ab7d778 100644 --- a/src/ui/tabs/Nose.ts +++ b/src/ui/tabs/Nose.ts @@ -1,11 +1,19 @@ import { FeatureSetType, - MiiPagedFeatureSet, + MiiPagedFeatureSet } from "../components/MiiPagedFeatureSet"; import { ArrayNum } from "../../util/Numbers"; import type { TabRenderInit } from "../../constants/TabRenderType"; import EditorIcons from "../../constants/EditorIcons"; import { RenderPart } from "../../class/MiiEditor"; +import { + makeSeparatorGapThinDesktop, + MiiNoseTable, + rearrangeArray +} from "../../constants/MiiFeatureTable"; + +import { _ } from "../../util/Lang"; +const __ = _(); export function NoseTab(data: TabRenderInit) { data.container.append( @@ -14,20 +22,24 @@ export function NoseTab(data: TabRenderInit) { onChange: data.callback, entries: { noseType: { - label: "Type", - items: ArrayNum(18).map((k) => ({ - type: FeatureSetType.Icon, - value: k, - icon: data.icons.nose[k], - part: RenderPart.Head, - })), + label: __("Type"), + items: rearrangeArray( + ArrayNum(18).map((k) => ({ + type: FeatureSetType.Icon, + value: k, + icon: data.icons.nose[k], + part: RenderPart.Head + })), + MiiNoseTable, + makeSeparatorGapThinDesktop + ) }, nosePosition: { - label: "Position", + label: __("Position"), items: [ { type: FeatureSetType.Range, - property: "noseYPosition", + property: "noseY", iconStart: EditorIcons.positionMoveUp, iconEnd: EditorIcons.positionMoveDown, soundStart: "position_down", @@ -35,7 +47,8 @@ export function NoseTab(data: TabRenderInit) { min: 0, max: 18, part: RenderPart.Head, - inverse: true + inverse: true, + label: data.useAccessibility ? __("Position") : undefined }, { type: FeatureSetType.Range, @@ -47,10 +60,11 @@ export function NoseTab(data: TabRenderInit) { min: 0, max: 8, part: RenderPart.Head, - }, - ], - }, - }, + label: data.useAccessibility ? __("Scale") : undefined + } + ] + } + } }) ); } diff --git a/src/ui/tabs/Options.ts b/src/ui/tabs/Options.ts index 3c577fa..ac341a8 100644 --- a/src/ui/tabs/Options.ts +++ b/src/ui/tabs/Options.ts @@ -1,10 +1,14 @@ import { FeatureSetType, - MiiPagedFeatureSet, + MiiPagedFeatureSet } from "../components/MiiPagedFeatureSet"; import type { TabRenderInit } from "../../constants/TabRenderType"; import EditorIcons from "../../constants/EditorIcons"; -import { RenderPart } from "../../class/MiiEditor"; +import { BodyUpdateType, RenderPart } from "../../class/MiiEditor"; +import { makeSeparatorGapThinFSI } from "../../constants/MiiFeatureTable"; + +import { _ } from "../../util/Lang"; +const __ = _(); export function OptionsTab(data: TabRenderInit) { data.container.append( @@ -13,54 +17,55 @@ export function OptionsTab(data: TabRenderInit) { onChange: data.callback, entries: { gender: { - label: "Gender", + label: __("Gender"), items: [ { type: FeatureSetType.Switch, - iconOff: EditorIcons.genderMale, - iconOn: EditorIcons.genderFemale, + iconOff: data.useAccessibility + ? __("Male") + : EditorIcons.genderMale, + iconOn: data.useAccessibility + ? __("Female") + : EditorIcons.genderFemale, property: "gender", isNumber: true, - forceRender: false, - part: RenderPart.Face, + forceRender: true, + part: RenderPart.Body, + bodyUpdateType: BodyUpdateType.ClothingUpdate, soundOff: "select_misc", - soundOn: "select_misc", - }, - ], + soundOn: "select_misc" + } + ] }, favorite: { - label: "Favorite", + label: __("Favorite/Special"), items: [ { type: FeatureSetType.Switch, - iconOff: "No", - iconOn: "Yes", + iconOff: __("Normal"), + iconOn: __("Favorite"), property: "favorite", - isNumber: false, + isNumber: true, forceRender: false, - part: RenderPart.Face, + part: RenderPart.Body, soundOff: "select_color", - soundOn: "select_color", + soundOn: "select_color" }, - ], - }, - isSpecial: { - label: "Type", - items: [ + makeSeparatorGapThinFSI(), { type: FeatureSetType.Switch, - iconOff: "Special", - iconOn: "Normal", - property: "normalMii", - isNumber: false, + iconOff: __("Normal"), + iconOn: __("Special"), + property: "special", + isNumber: true, forceRender: false, - part: RenderPart.Face, + part: RenderPart.Body, soundOff: "select_color", - soundOn: "select_color", - }, - ], - }, - }, + soundOn: "select_color" + } + ] + } + } }) ); } diff --git a/src/ui/tabs/Scale.ts b/src/ui/tabs/Scale.ts index 7725d22..26e6679 100644 --- a/src/ui/tabs/Scale.ts +++ b/src/ui/tabs/Scale.ts @@ -1,10 +1,13 @@ import { FeatureSetType, - MiiPagedFeatureSet, + MiiPagedFeatureSet } from "../components/MiiPagedFeatureSet"; import type { TabRenderInit } from "../../constants/TabRenderType"; import EditorIcons from "../../constants/EditorIcons"; -import { RenderPart } from "../../class/MiiEditor"; +import { BodyUpdateType, RenderPart } from "../../class/MiiEditor"; + +import { _ } from "../../util/Lang"; +const __ = _(); export function ScaleTab(data: TabRenderInit) { data.container.append( @@ -13,7 +16,7 @@ export function ScaleTab(data: TabRenderInit) { onChange: data.callback, entries: { bodySize: { - label: "Scale", + label: __("Scale"), items: [ { type: FeatureSetType.Slider, @@ -23,9 +26,11 @@ export function ScaleTab(data: TabRenderInit) { min: 0, max: 127, forceRender: false, - part: RenderPart.Face, + part: RenderPart.Body, + bodyUpdateType: BodyUpdateType.RepositionCamera, soundStart: "vert_stretch_down", soundEnd: "vert_stretch_up", + label: data.useAccessibility ? __("Height") : undefined }, { type: FeatureSetType.Slider, @@ -35,13 +40,15 @@ export function ScaleTab(data: TabRenderInit) { min: 0, max: 127, forceRender: false, - part: RenderPart.Face, + part: RenderPart.Body, + bodyUpdateType: BodyUpdateType.RepositionCamera, soundStart: "vert_stretch_down", soundEnd: "vert_stretch_up", - }, - ], - }, - }, + label: data.useAccessibility ? __("Build") : undefined + } + ] + } + } }) ); } diff --git a/src/util/Color.ts b/src/util/Color.ts index 80633a8..7ac88b2 100644 --- a/src/util/Color.ts +++ b/src/util/Color.ts @@ -6,3 +6,7 @@ export function sRGB(c: number) { return 1.055 * Math.pow(c, 1 / 2.4) - 0.055; } } + +export function sRGBToLinear(srgb: number) { + return srgb <= 0.04045 ? srgb / 12.92 : Math.pow((srgb + 0.055) / 1.055, 2.4); +} diff --git a/src/util/DecodeQRCode.ts b/src/util/DecodeQRCode.ts index e9cbeae..318b6d1 100644 --- a/src/util/DecodeQRCode.ts +++ b/src/util/DecodeQRCode.ts @@ -2,14 +2,14 @@ // https://jsfiddle.net/arian_/ckya346z/12/ import sjcl from "../external/mii-frontend/sjcl.min.js"; import QrScanner from "../external/mii-frontend/qr-scanner.umd.min.js"; -import { Buffer } from "../../node_modules/buffer"; // unused temporarily because it isn't loading the extra data correctly from TL qr codes from my testing import { MiiTLHairSprayToSwitchColor, - SwitchMiiColorTable, + SwitchMiiColorTable } from "../constants/ColorTables.js"; import Modal from "../ui/components/Modal.js"; import { getSetting } from "./SettingsHelper.js"; +import { dataToBase64, dataToHex } from "./dataConvert.js"; // AES keys const AES_CCM_KEY_HEX = "59FC817E6446EA6190347B20E9BDCE52"; @@ -33,10 +33,10 @@ export function QrScannerError(message: string) { message, "body", { - text: "Cancel", + text: "Cancel" }, { - text: "OK", + text: "OK" } ); m.qs(".modal-content")!.styleJs({ minWidth: "360px" }); @@ -166,7 +166,7 @@ function decryptAesCcm( return new Uint8Array([ ...decryptedSlice.slice(0, 12), ...nonce, - ...decryptedSlice.slice(12), + ...decryptedSlice.slice(12) ]); } @@ -290,7 +290,7 @@ export async function startScanner(camList: HTMLElement) { console.log("QR scan error:", error); }, highlightScanRegion: true, - highlightCodeOutline: true, + highlightCodeOutline: true } ); @@ -402,11 +402,13 @@ export async function initQrCam( export enum QrScanDataType { GenericWiiU3ds, ExtraDataTL, - ExtraDataMiiC, + ExtraDataMiiC } -var qrCallback: (data: Buffer, type: QrScanDataType) => any; -export function setQRCallback(fn: (data: Buffer, type: QrScanDataType) => any) { +var qrCallback: (data: Uint8Array, type: QrScanDataType) => any; +export function setQRCallback( + fn: (data: Uint8Array, type: QrScanDataType) => any +) { qrCallback = fn; } @@ -420,15 +422,12 @@ function handleQrCode(result: { bytes: any; noQrCode: any }) { cameraScanner.stop(); const qrData = new Uint8Array(result.bytes); - console.log(Buffer.from(qrData).toString("hex")); + console.log(dataToHex(qrData)); const decryptedData = decryptAesCcm(qrData.slice(0, 112)); // First 112 bytes are AES-CCM - const decryptedStoreDataBuf = Buffer.from(decryptedData); + const decryptedStoreDataBuf = decryptedData; - console.log( - "Decrypted QR Store Data:", - decryptedStoreDataBuf.toString("base64") - ); + console.log("Decrypted QR Store Data:", dataToBase64(decryptedStoreDataBuf)); // hexEditorBaseOutput.loadFromArray(decryptedData); // document.getElementById("extra-data-warning").style.display = "none"; @@ -439,16 +438,10 @@ function handleQrCode(result: { bytes: any; noQrCode: any }) { const encryptedExtra = qrData.slice(128, -4); decryptAesCtr(encryptedExtra, iv) .then((decryptedExtraData) => { - console.log( - "Scanned Extra Data:", - Buffer.from(decryptedExtraData).toString("hex") - ); + console.log("Scanned Extra Data:", dataToHex(decryptedExtraData)); if (decryptedExtraData.length === 240) { - qrCallback( - Buffer.concat([decryptedStoreDataBuf]), - QrScanDataType.ExtraDataTL - ); + qrCallback(decryptedStoreDataBuf, QrScanDataType.ExtraDataTL); // QrScannerError( // "Tomodachi Life codes won't retain hair dye info yet." // ); @@ -476,15 +469,17 @@ function handleQrCode(result: { bytes: any; noQrCode: any }) { error ); console.log("Attempting to load QR extra data anyways:"); - const extDataBuf = Buffer.from(qrData.slice(112)); - console.log(extDataBuf.toString("base64")); + const extDataBuf = new Uint8Array(qrData.slice(112)); + console.log(dataToBase64(extDataBuf)); if (extDataBuf.length === 10 || extDataBuf.length === 12) { console.log("This is probably miic data"); // put together the data - qrCallback( - Buffer.concat([decryptedStoreDataBuf, extDataBuf]), - QrScanDataType.ExtraDataMiiC + var newArray = new Uint8Array( + decryptedStoreDataBuf.length + extDataBuf.length ); + newArray.set(decryptedStoreDataBuf); + newArray.set(extDataBuf, decryptedStoreDataBuf.length); + qrCallback(newArray, QrScanDataType.ExtraDataMiiC); } }); } else { diff --git a/src/util/EncodeQRCode.ts b/src/util/EncodeQRCode.ts index 5963750..fff9758 100644 --- a/src/util/EncodeQRCode.ts +++ b/src/util/EncodeQRCode.ts @@ -37,7 +37,7 @@ export const encryptAndEncodeVer3StoreDataToQRCodeFormat = ( const checksumContent = [ ...data.slice(0, 12), ...nonce, - ...data.slice(20, -2), + ...data.slice(20, -2) ]; console.log( "checksumContent:", @@ -51,7 +51,7 @@ export const encryptAndEncodeVer3StoreDataToQRCodeFormat = ( //const cipher = new sjcl.cipher.aes(sjcl.codec.hex.toBits('59FC817E6446EA6190347B20E9BDCE52')); const cipher = new sjcl.cipher.aes([ - 1509720446, 1682369121, -1875608800, -373436846, + 1509720446, 1682369121, -1875608800, -373436846 ]); const paddedContent = new Uint8Array([...content, ...new Array(8).fill(0)]); diff --git a/src/util/FFLLoader.ts b/src/util/FFLLoader.ts new file mode 100644 index 0000000..0e79797 --- /dev/null +++ b/src/util/FFLLoader.ts @@ -0,0 +1,154 @@ +import Modal, { buttonsOkCancel, closeModal } from "../ui/components/Modal"; +import Notify from "../ui/components/Notify"; +import { + loadBodyModels, + loadClothesTextures, + loadHatModels +} from "../util/ModelLoader"; +import { defaultParams, type RenderRequest } from "../util/IconRendering"; + +import { _, loadLang } from "./Lang"; +import type { + FFLWorkerInitializeMessage, + FFLWorkerMessage +} from "../worker.js"; +import { Config } from "../config.js"; +import { initializeFFLWithResource } from "../external/ffl.js/ffl.js"; +import { getSetting } from "./SettingsHelper.js"; + +const __ = _(); + +let FFLModule: any, FFLWorker: Worker | undefined; +export const getFFL = () => FFLModule; +export const getFFLWorker = () => FFLWorker; +export const getFFLWorkerExists = () => FFLWorker !== undefined; +export const getFFLWorkerMakeIcon = ( + request: Partial, + useBlob: boolean = true +): Promise => { + if (FFLWorker === undefined) + throw new Error("FFL worker told to make icon, but it wasn't initialized"); + + return new Promise((resolve, reject) => { + sendMessageToWorker({ + type: "MakeIcon", + useBlob, + request: { + ...defaultParams, + ...request + } + } as FFLWorkerMessage) + .then((resp) => resolve(resp)) + .catch((err) => reject(err)); + }); +}; +let sendMessageToWorker: (data: any) => Promise; + +export async function prepareFFL() { + // Depending on config, load FFL.js + if (Config.renderer.useRendererServer !== false) { + return console.log("why do you"); + } + + var m = Modal.modal( + __("Notice"), + // TODO: Make a better message? 😅 + // Displayed in a modal while loading resource files. + __("Mii Creator is loading assets, please wait...") + ); + + FFLModule = (await import("../external/ffl.js/ffl-emscripten.js")).default; + + FFLModule = await FFLModule({ + locateFile: (path: string) => { + return "/dist/" + path; + } + }); + + console.log(FFLModule); + console.log("We've got FFL!"); + + // Import FFL.JS (c) 2025 Arian K. macOS Edition + await loadBodyModels(); + await loadHatModels(); + // for some reason + await loadClothesTextures(); + let { module } = await initializeFFLWithResource( + FFLModule, + Config.renderer.fflResourcePath[await getSetting("resourceType")] + ); + FFLModule = module; + + // TODO: CLEAN THIS UP so all the wasm/worker loading logic isn't in main.ts??? this was just a temp spot since its before everything else loads + // Detect and use Web Workers/OffscreenCanvas if available, to optimize icon generation + if (window.Worker) { + if (window.OffscreenCanvas) { + const tempOffscreenCanvas = document.createElement("canvas"); + const offscreenCanvas = tempOffscreenCanvas.transferControlToOffscreen(); + FFLWorker = new Worker("./dist/worker.js", { type: "module" }); + + // chat gpt + sendMessageToWorker = (data: any) => { + return new Promise((resolve, reject) => { + const requestId = Math.random().toString(36).substring(7); + + function handleMessage(event: MessageEvent) { + const { id, result, error } = event.data; + if (id === requestId) { + FFLWorker!.removeEventListener("message", handleMessage); + if (error) { + Notify.show("Worker error", error); + resolve(null); + } else resolve(result); + } + } + + FFLWorker!.addEventListener("message", handleMessage); + FFLWorker!.postMessage({ id: requestId, ...data }); + }); + }; + + // unfortunately, the worker has to load ffl wasm on its own + FFLWorker.postMessage( + { + type: "Init", + resourcePath: + Config.renderer.fflResourcePath[await getSetting("resourceType")], + offscreenCanvas, + devicePixelRatio: window.devicePixelRatio + } as FFLWorkerInitializeMessage, + // transfer the offscreen canvas over + [offscreenCanvas] + ); + await new Promise((resolve) => { + FFLWorker!.onmessage = (e) => { + if (e.data.ready) { + resolve(); + } + }; + }); + } else { + Modal.modal( + __("Notice"), + __( + "Your browser doesn't support OffscreenCanvas, so Mii Creator may experience lag." + ), + "body", + ...buttonsOkCancel + ); + } + } else { + Modal.modal( + __("Notice"), + __( + "Your browser doesn't support Web Workers, so Mii Creator may experience lag." + ), + "body", + ...buttonsOkCancel + ); + } + + console.log("Ready!"); + + closeModal(m); +} diff --git a/src/util/IconRendering.ts b/src/util/IconRendering.ts new file mode 100644 index 0000000..464f938 --- /dev/null +++ b/src/util/IconRendering.ts @@ -0,0 +1,656 @@ +import * as THREE from "three"; +import { + CharModel, + createAndRenderToTarget, + createCharModel, + FFLCharModelDescDefault, + FFLExpression, + FFLModelFlag, + FFLResourceType, + // getCameraForViewType, + initCharModelTextures, + makeExpressionFlag, + parseHexOrB64ToUint8Array +} from "../external/ffl.js/ffl"; +import { + isShaderMaterial, + getShaderMaterialFromShaderType, + getSimpleMaterialAddLights +} from "../class/3d/shader/ShaderUtils"; +import type { MiiCreatorAdditionalData } from "../util/MiiCreatorTypes"; +import { + getBodyModels, + getClothesTextures, + getHatModels, + getLoadedBodyModelName, + isStreetPass +} from "./ModelLoader"; +import { + cMaterialName, + cPantsColorBlue, + cPantsColorGold, + cPantsColorGray, + cPantsColorRed +} from "../class/3d/shader/fflShaderConst"; +import { + ClothesType, + ClothesTypeList, + ExtClothesList, + HatType, + HatTypeList +} from "../constants/Extensions"; +import Mii from "../class/MiiData"; +import { + ForbiddenShirtPantColors, + MiiFavoriteColorVec3Table, + SwitchMiiColorTableSRGB +} from "../constants/ColorTables"; +// import { streetpassHandScaling } from "./scaling"; +import { ViewType, getCameraForViewType } from "./camera"; +import { renderTargetToDataURL } from "./rendertarget"; +import { ShaderType } from "../constants/BodyShaderTypes"; +import { SkeletonUtils } from "three/examples/jsm/Addons.js"; +import { colorMixTexture } from "../class/3d/shader/ColorMix"; +import { loadBlobTextureWorker } from "../ui/pages/library/util/3DModel"; +import FFLShaderMaterial from "../external/ffl.js/FFLShaderMaterial"; + +export const defaultParams: Partial = { + type: ViewType.Face, + expression: 0, + characterYRotate: 0, + modelFlag: FFLCharModelDescDefault, + drawBody: true +}; + +export interface RenderRequest { + type: ViewType; + expression: number | number[]; + data: Uint8Array | string; + size: number; + characterYRotate: number; + modelFlag: any; + renderer: THREE.WebGLRenderer; + textureRenderer: THREE.WebGLRenderer; + drawBody: boolean; + module: any; + additionalInfo?: MiiCreatorAdditionalData; + texResolution?: number; + /** + * Defines whether the render request is a temporary icon render (and uses a camera and render target.) + */ + isTemporary?: boolean; + shaderType?: ShaderType; + clothingLinearColors?: boolean; + bodyModelType?: IconBodyModelType; +} + +export enum IconBodyModelType { + low = "low", + high = "high" +} + +export const isWorker = () => typeof window === "undefined"; + +export type RenderRequestNonTemporaryResult = { + bodyModel: THREE.Group; + bodyModelBody: THREE.Mesh; + bodyModelHands: THREE.Mesh; + bodyModelLegs: THREE.Mesh; + bodyModelAnims: THREE.AnimationClip[]; + charModel: CharModel; + headModel: THREE.Group; + miiGroup: THREE.Group; +}; + +// Helper function that is based on +// ffl.js createCharModelIcon and FFL-Testing +export function createMiiRender( + request: RenderRequest +): Promise<{ type: string; result: string | Blob }> { + return new Promise(async (resolve) => { + // Parse input data + let dataInput: Uint8Array; + if (typeof request.data === "string") + dataInput = parseHexOrB64ToUint8Array(request.data); + else dataInput = request.data; + + let scene = new THREE.Scene(); + + const isTemporary = request.isTemporary !== false; + + const mii = new Mii(dataInput); + + const localModule = request.module; + + if (localModule === undefined) throw new Error("Module NOT ready."); + + let modelFlag = FFLModelFlag.NORMAL; + + if (request.additionalInfo!.hatType !== -1) { + switch (HatTypeList[request.additionalInfo!.hatType]) { + case HatType.HAT: + modelFlag = FFLModelFlag.HAT; + break; + case HatType.FACE_ONLY: + modelFlag = FFLModelFlag.FACE_ONLY; + break; + case HatType.BALD: + mii.hairType = 30; + dataInput = mii.export("studioData"); + break; + } + } + console.log( + "miic additional info:", + JSON.stringify(request.additionalInfo) + ); + + const shaderMaterial = await getShaderMaterialFromShaderType( + request.shaderType + ); + const isUsingShader = await isShaderMaterial(request.shaderType); + + let lights = await getSimpleMaterialAddLights(request.shaderType); + if (lights) { + lights(scene); + } + + let texResolution = request.texResolution || 512; + + // Use a higher resolution texture + if (request.size > 512) { + texResolution = 1024; + } else if (request.size > 1024) { + texResolution = 2048; + } + + let expressions = []; + + if (Array.isArray(request.expression)) { + expressions.push(...request.expression); + } else { + expressions.push( + isNaN(request.expression) ? FFLExpression.NORMAL : request.expression + ); + } + + // Set up a temporary CharModel. + const charModel = createCharModel( + dataInput, + { + resolution: texResolution, + resourceType: FFLResourceType.HIGH, + allExpressionFlag: makeExpressionFlag(expressions), + modelFlag + }, + shaderMaterial as any, + localModule, + false + ); + + // QUICKLY Replace the material + charModel._materialTextureClass = FFLShaderMaterial; + charModel._materialClass = shaderMaterial; + + if (request.additionalInfo!.eyeSclera === 1 && mii.eyeColor !== 8) { + self.eyeScleraHack = true; + } + + initCharModelTextures( + charModel, + request.renderer, + charModel._materialTextureClass + ); + + if (request.additionalInfo!.eyeSclera === 1 && mii.eyeColor !== 8) { + self.eyeScleraHack = false; + } + + // Create an offscreen scene for the icon. + let miiGroup: THREE.Scene, headModel: THREE.Group; + + if (isTemporary) { + miiGroup = scene; + miiGroup.background = null; // Transparent background. + } else { + miiGroup = new THREE.Group() as any; + headModel = new THREE.Group(); + } + + // Stuff related to hat and body rendering + const gender = charModel._model.charInfo.personal.gender; + const bodyScale = charModel.getBodyScale(); + + let hatModel: THREE.Group; + if (request.additionalInfo!.hatType !== -1) { + let hatColor = [0, 0, 0]; + + if (isTemporary) + hatModel = getHatModels()[request.additionalInfo!.hatType].clone(true); + else + hatModel = getHatModels()[request.additionalInfo!.hatType].clone(true); + + // --- Calculate hat color + + // default = current favorite color + hatColor = + MiiFavoriteColorVec3Table[ + mii.favoriteColor % Object.keys(MiiFavoriteColorVec3Table).length + ]; + + // lazy overwrite + if (request.additionalInfo!.hatFavoriteColor !== -1) { + hatColor = + MiiFavoriteColorVec3Table[request.additionalInfo!.hatFavoriteColor]; + } + if (request.additionalInfo!.hatCommonColor !== -1) { + hatColor = + SwitchMiiColorTableSRGB[request.additionalInfo!.hatCommonColor]; + } + + console.log( + "additional info:", + request.additionalInfo, + "hat model:", + hatModel + ); + hatModel.traverse((m) => { + if ((m as THREE.Mesh).isMesh) { + const oldMat = ((m as THREE.Mesh).material as THREE.MeshBasicMaterial) + .map; + + let modulate = isUsingShader + ? { + modulateType: cMaterialName.FFL_MODULATE_TYPE_SHAPE_CAP, + modulateMode: 2 + } + : {}; + + (m as THREE.Mesh as any).material = new shaderMaterial( + { + ...modulate, + color: new THREE.Color(...hatColor), + opacity: 1, + map: oldMat! + }! + ); + } + }) as any; + + if (isTemporary) { + miiGroup.add(hatModel); + } else { + headModel!.add(hatModel); + } + + // this could easier be done with a negative scale vector but eh + const shiftPos = charModel.partsTransform.hatTranslate.y; + if (request.drawBody) { + if (isTemporary) { + hatModel.position.set(0, bodyScale.y * 75 + shiftPos, 0); + } else { + hatModel.position.set(0, shiftPos, 0); + } + } else { + charModel.partsTransform.hatTranslate.y; + hatModel.position.set(0, shiftPos, 0); + } + } + + // Add meshes from the CharModel. + const headMesh = charModel.meshes!.clone(); + if (isTemporary) { + miiGroup.add(headMesh); + } else { + headModel!.add(headMesh); + } + + let iconCamera: THREE.Camera; + + if (isTemporary) + // Get camera based on viewType parameter. + iconCamera = getCameraForViewType( + request.type, + undefined, + undefined, + bodyScale.y + ); + + let bodyModel: THREE.Group, + bodyModelBody: THREE.Mesh, + bodyModelHands: THREE.Mesh, + bodyModelLegs: THREE.Mesh, + bodyModelAnims: THREE.AnimationClip[]; + + if (headModel! !== undefined) { + miiGroup.add(headModel); + } + + let prefix = "high"; + + if (request.bodyModelType !== undefined) { + prefix = request.bodyModelType; + } + + if (request.drawBody && getBodyModels()[prefix + "M"] !== null) { + switch (gender) { + case 0: { + if (isTemporary) bodyModel = getBodyModels()[prefix + "M"].scene; + else + bodyModel = SkeletonUtils.clone( + getBodyModels()[prefix + "M"].scene + ) as any; + + if (bodyModel === null) + throw "Tried to make an icon before body models were loaded."; + + bodyModelBody = bodyModel.getObjectByName("body_m") as THREE.Mesh; + bodyModelHands = bodyModel.getObjectByName("hands_m") as THREE.Mesh; + bodyModelLegs = bodyModel.getObjectByName("legs_m") as THREE.Mesh; + if (!isTemporary) + bodyModelAnims = getBodyModels()[prefix + "M"].animations; + break; + } + case 1: { + if (isTemporary) bodyModel = getBodyModels()[prefix + "F"].scene; + else + bodyModel = SkeletonUtils.clone( + getBodyModels()[prefix + "F"].scene + ) as any; + + if (bodyModel === null) + throw "Tried to make an icon before body models were loaded."; + + bodyModelBody = bodyModel.getObjectByName("body_f") as THREE.Mesh; + bodyModelHands = bodyModel.getObjectByName("hands_f") as THREE.Mesh; + bodyModelLegs = bodyModel.getObjectByName("legs_f") as THREE.Mesh; + if (!isTemporary) + bodyModelAnims = getBodyModels()[prefix + "F"].animations; + break; + } + default: + throw new Error(`Gender ${gender} is outisde range 0, 1`); + } + + bodyModel.scale.set(bodyScale.x * 7, bodyScale.y * 7, bodyScale.z * 7); + bodyModel.position.set(0, 0, 0); + + miiGroup.add(bodyModel); + + var shirtColor = + MiiFavoriteColorVec3Table[ + mii.favoriteColor % Object.keys(MiiFavoriteColorVec3Table).length + ]; + + if ( + request.additionalInfo!.shirtColor !== -1 && + !ForbiddenShirtPantColors.includes(request.additionalInfo!.shirtColor) + ) { + shirtColor = + SwitchMiiColorTableSRGB[request.additionalInfo!.shirtColor]; + } + + let modulate = isUsingShader + ? { + modulateType: cMaterialName.FFL_MODULATE_TYPE_SHAPE_BODY, + modulateMode: 0 + } + : {}; + + bodyModelBody.material = new charModel._materialClass({ + ...modulate, + color: new THREE.Color(...shirtColor), + opacity: 1 + }); + + if (bodyModelHands) bodyModelHands.material = bodyModelBody.material; + + var pantsColor = cPantsColorGray; + + // favorite/special check + if (request.additionalInfo!.favorite === 1) { + pantsColor = cPantsColorRed; + } + if (request.additionalInfo!.special === 1) { + pantsColor = cPantsColorGold; + } + if (request.additionalInfo!.temporary === 1) { + pantsColor = cPantsColorBlue; + } + + if ( + request.additionalInfo!.pantsColor !== -1 && + !ForbiddenShirtPantColors.includes(request.additionalInfo!.pantsColor) + ) { + pantsColor = + SwitchMiiColorTableSRGB[request.additionalInfo!.pantsColor]; + } + + modulate = isUsingShader + ? { + modulateType: cMaterialName.FFL_MODULATE_TYPE_SHAPE_PANTS, + modulateMode: 0 + } + : {}; + bodyModelLegs.material = new charModel._materialClass({ + ...modulate, + color: new THREE.Color(...pantsColor), + opacity: 1 + }); + + const nBody = bodyModelBody; + const nLegs = bodyModelLegs; + + THREE.ColorManagement.enabled = false; + + // CLOTHESSS + if ( + request.additionalInfo!.clothesType !== undefined && + request.additionalInfo!.clothesType !== -1 && + request.bodyModelType !== IconBodyModelType.low && + getLoadedBodyModelName() === "wiiu" && + request.additionalInfo!.clothesType < ExtClothesList.length + ) { + console.log("clothing update"); + let shirtTexture: THREE.Texture, + pantsTexture: THREE.Texture | null = null; + + const suffix = mii.gender == 1 ? "F" : ""; + let key = `${getLoadedBodyModelName()}_${ + ExtClothesList[request.additionalInfo!.clothesType] + }${suffix}`; + let shirtKey = key; + if (getLoadedBodyModelName() === "miitomo") { + shirtKey = key + "_Top"; + } + + let shoesColor = + request.additionalInfo!.shoesColor !== -1 && + request.additionalInfo!.shoesColor < 100 + ? SwitchMiiColorTableSRGB[request.additionalInfo!.shoesColor] + : [1, 1, 1]; + switch (ClothesTypeList[request.additionalInfo!.clothesType]) { + case ClothesType.COLOR_MIXED: { + const colorMixR = new THREE.Vector4(...shirtColor, 1), + colorMixG = new THREE.Vector4(...shoesColor, 1), + colorMixB = new THREE.Vector4(...pantsColor, 1), + colorMixA = charModel + ? request.clothingLinearColors !== true + ? charModel!.facelineColor + : charModel!.facelineColor.convertSRGBToLinear() + : 0xff0000; + + // console.log("Shirt Texture Key:", shirtKey); + let tex = await colorMixTexture( + getClothesTextures()[shirtKey], + colorMixR, + colorMixG, + colorMixB, + colorMixA, + request.textureRenderer || request.renderer, + request.texResolution + ); + // console.log("omg i got the shirt texture"); + shirtTexture = await loadBlobTextureWorker( + tex, + request.texResolution, + request.texResolution + ); + + // console.log("loaded shirt texture!"); + + // if (this.bodyModel === "miitomo") { + // const pantsKey = key + "_Bot"; + // let tex = await colorMixTexture( + // this.clothingTextures[pantsKey], + // colorMixR, + // colorMixG, + // colorMixB, + // colorMixA + // ); + // pantsTexture = await loadBlobTexture(tex); + // } + break; + } + case ClothesType.TEXTURE_COLOR: { + shirtTexture = getClothesTextures()[shirtKey + suffix]; + break; + } + default: + alert("Something isn't right here"); + throw "???"; + } + request.renderer.initTexture(shirtTexture); + + let nBodyMat = nBody.material as any; + let nLegsMat = nLegs.material as any; + + nBodyMat.dispose(); + nLegsMat.dispose(); + + let modulate = isUsingShader + ? { + modulateType: 9, + modulateMode: 1, + color: new THREE.Color(0x000000) + } + : { color: new THREE.Color(0xffffff) }; + const params = { + ...modulate, + map: shirtTexture + }; + const newBodyMat = new (await getShaderMaterialFromShaderType( + request.shaderType + ))(params); + // const newBodyMat = new THREE.MeshBasicMaterial(params); + if (getLoadedBodyModelName() !== "miitomo") { + nBody.material = newBodyMat as any; + nLegs.material = newBodyMat as any; + } + + // if (this.bodyModel === "miitomo" && pantsTexture !== null) { + // const params = { + // modulateType: 9, + // modulateMode: 1, + // map: pantsTexture + // }; + // const newLegsMat = new (await getShaderMaterialFromShaderType())( + // params + // ); + // nLegs.material = newLegsMat as any; + // } else { + // } + + console.log("mat changed!", newBodyMat, nBody, nLegs); + } + + if (isTemporary) { + headMesh.position.set(0, bodyScale.y * 75, 0); + } else { + headModel!.position.set(0, bodyScale.y * 75, 0); + } + + if (isTemporary) + switch (request.type) { + case ViewType.Face: + case ViewType.MakeIcon: + case ViewType.IconFovy45: + case ViewType.CreditIcon: { + // Position the icon closer to the head + iconCamera!.position.y += bodyScale.y * 76; + } + } + + if (request.bodyModelType === IconBodyModelType.low) { + bodyModelHands.visible = false; + } + + if (isStreetPass()) { + console.log("is streetpass"); + + var scaleVec = new THREE.Vector3(); + bodyModel.getWorldScale(scaleVec); + const handScaleX = (1 / scaleVec.x) * 5; + const handScaleY = (1 / scaleVec.y) * 5; + console.log(handScaleX, handScaleY); + bodyModel + .getObjectByName("handLPs")! + .scale.set(handScaleX, handScaleY, handScaleX); + bodyModel + .getObjectByName("handRPs")! + .scale.set(handScaleX, handScaleY, handScaleX); + // streetpassHandScaling(bodyModel, ); + } else { + console.log("not streetpass"); + } + } + + if (isTemporary) { + const target = createAndRenderToTarget( + miiGroup, + iconCamera!, + request.renderer, + request.size, + request.size + ); + + setTimeout(() => { + const dataURL = renderTargetToDataURL(target, request.renderer); + + target.dispose(); // Dispose RenderTarget before returning. + + // Dispose temporary CharModel. + charModel.dispose(); + + // Dispose unused body/hat materials. + if (request.drawBody) { + (bodyModelBody!.material as THREE.Material).dispose(); + (bodyModelLegs!.material as THREE.Material).dispose(); + } + + // TODO: dispose hat material + if (hatModel!) { + hatModel.traverse((n) => { + if (!(n as THREE.Mesh).isMesh) return; + (n as THREE.Mesh).geometry.dispose(); + ((n as THREE.Mesh).material as THREE.MeshBasicMaterial).dispose(); + }); + } + + resolve(dataURL); + }, 0); + } else { + return resolve({ + // assuming caller needs everything + bodyModel: bodyModel!, + bodyModelBody: bodyModelBody!, + bodyModelHands: bodyModelHands!, + bodyModelLegs: bodyModelLegs!, + charModel: charModel, + headModel: headModel!, + miiGroup: miiGroup, + bodyModelAnims: bodyModelAnims! + } as any); + } + }); +} diff --git a/src/util/Lang.ts b/src/util/Lang.ts new file mode 100644 index 0000000..64fffb2 --- /dev/null +++ b/src/util/Lang.ts @@ -0,0 +1,11 @@ +import i18n from "gettext.js"; + +export const localization = i18n(); + +export const _ = () => localization.gettext.bind(localization); + +export async function loadLang(lang: string) { + const json = await (await fetch(`/public/dist/lang/${lang}.json`)).json(); + localization.setMessages("messages", lang, json); + localization.setLocale(lang); +} diff --git a/src/util/MiiCreatorTypes.ts b/src/util/MiiCreatorTypes.ts new file mode 100644 index 0000000..5058223 --- /dev/null +++ b/src/util/MiiCreatorTypes.ts @@ -0,0 +1,16 @@ +export type MiiCreatorAdditionalData = + | { + hatType: number; + hatCommonColor: number; + hatFavoriteColor: number; + shirtColor: number; + pantsColor: number; + favorite: number; + special: number; + temporary: number; + eyeSclera: number; + wigType: number; + clothesType: number; + shoesColor: number; + } + | undefined; diff --git a/src/util/MiiRendering.ts b/src/util/MiiRendering.ts index e8361e4..0a3b673 100644 --- a/src/util/MiiRendering.ts +++ b/src/util/MiiRendering.ts @@ -1,176 +1,222 @@ -import type { GLTF } from "three/examples/jsm/Addons.js"; -import Mii from "../external/mii-js/mii"; -import * as THREE from "three"; -import { RandomInt } from "./Numbers"; -import { cMaterialName } from "../class/3d/shader/fflShaderConst"; -import { - CharModel, - convertStudioCharInfoToFFLiCharInfo, - createCharModel, - FFLCharModelDesc, - FFLCharModelDescDefault, - FFLiCharInfo, - FFLModelFlag, - initCharModelTextures, - setMaskTextureHook, - StudioCharInfo, - updateCharModel, -} from "../external/ffl.js/ffl"; -import { getFFL } from "../main"; -import { getTempRenderer } from "../ui/pages/Library"; -import type { Mii3DScene } from "../class/3DScene"; - -export type GLTFLike = { - animations: any[]; - asset: {}; - cameras: any[]; - parser: any; - scene: THREE.Object3D; - scenes: any[]; - userData: any; -}; - -function wait(time: number) { - return new Promise((resolve) => { - setTimeout(() => { - resolve(); - }, time); - }); -} - -export type ModelFlag = - | "NORMAL" - | "HAT" - | "FACE_ONLY" - | "FLATTEN_NOSE" - | "NEW_EXPRESSIONS" - | "NEW_MASK_ONLY"; - -export async function getHeadModel( - mii: Mii, - Mii3DScene: Mii3DScene, - modelFlag: ModelFlag, - charModelRef?: CharModel, - rendererRef?: THREE.WebGLRenderer, - descOrExpFlag?: Object | any[] | Uint32Array | null -): Promise { - // In the future, this could be hooked up to a custom rendering library (FFL under WASM or a custom asset loader) - // For now, this will just return a cube with some FFL shader properties to test if it's working. - - const dataU8 = mii.encodeStudio(); - - const modelDesc = FFLCharModelDescDefault; - modelDesc.resolution = 512; - modelDesc.allExpressionFlag = new Uint32Array([1, 0, 0]); - modelDesc.modelFlag = FFLModelFlag[modelFlag]; - - let currentCharModel: CharModel | null; - - try { - if (charModelRef) { - if (!rendererRef) - throw new Error("Missing renderer when trying to update CharModel"); - - currentCharModel = charModelRef; - - // Create new charinfo data - const studioCharInfo = StudioCharInfo.unpack(dataU8); - const newCharInfo = FFLiCharInfo.pack( - convertStudioCharInfoToFFLiCharInfo(studioCharInfo) - ); - - // update char model - updateCharModel(currentCharModel, newCharInfo, rendererRef, modelDesc); - } else { - currentCharModel = createCharModel( - dataU8, - modelDesc, - window.LUTShaderMaterial, - // window.FFLShaderMaterial, - getFFL(), - false - ); - } - // Initialize textures for the new CharModel. - initCharModelTextures(currentCharModel, Mii3DScene.getRenderer()); - } catch (err) { - currentCharModel = null; - alert(`Error creating/updating CharModel: ${err}`); - console.error("Error creating/updating CharModel:", err); - throw err; - } - - const asset = { - extras: { - partsTransform: { - hatTranslate: [0, 0, 0], - }, - }, - }; - - let scene = new THREE.Group(); - - scene.add(currentCharModel.meshes); - - // GLTF-like object so that the code can still handle it sort of like one - return { - animations: [], - asset, - cameras: [], - parser: {}, - scene, - scenes: [scene], - userData: {}, - CharModel: currentCharModel, - } as GLTFLike as GLTF; -} - -export type MaskResult = { - model: CharModel; - img: string; -}; - -export async function getMaskTex( - mii: Mii, - Mii3DScene: Mii3DScene -): Promise { - // In the future, this could be hooked up to a custom rendering library (FFL under WASM or a custom asset loader) - // For now, this will just return a cube with some FFL shader properties to test if it's working. - - const dataU8 = mii.encodeStudio(); - - const modelDesc = FFLCharModelDescDefault; - modelDesc.resolution = 512; - modelDesc.allExpressionFlag = new Uint32Array([1, 0, 0]); - - let currentCharModel: CharModel | null; - - var img = ""; - - try { - currentCharModel = createCharModel( - dataU8, - modelDesc, - window.LUTShaderMaterial, - // window.FFLShaderMaterial, - getFFL(), - false - ); - - // weird workaround to promisify the texture outcome? - img = await new Promise((resolve) => { - setMaskTextureHook((dataURL: any) => { - resolve(dataURL.result); - }); - // Initialize textures for the new CharModel. - initCharModelTextures(currentCharModel!, Mii3DScene.getRenderer()); - }); - } catch (err) { - currentCharModel = null; - alert(`Error creating/updating CharModel: ${err}`); - console.error("Error creating/updating CharModel:", err); - throw err; - } - - return { img, model: currentCharModel }; -} +import type { GLTF } from "three/examples/jsm/Addons.js"; +// import Mii from "../external/mii-js/mii"; +import Mii from "../class/MiiData"; +import * as THREE from "three"; +import { + CharModel, + convertStudioCharInfoToFFLiCharInfo, + createCharModel, + FFLCharModelDescDefault, + FFLiCharInfo, + FFLModelFlag, + initCharModelTextures, + StudioCharInfo, + updateCharModel +} from "../external/ffl.js/ffl"; +import { + isShaderMaterial, + getShaderMaterialFromShaderType +} from "../class/3d/shader/ShaderUtils"; +import { getFFL } from "./FFLLoader"; +import { renderTargetToDataTexture } from "./rendertarget"; +import FFLShaderMaterial from "../external/ffl.js/FFLShaderMaterial"; + +export type GLTFLike = { + animations: any[]; + asset: {}; + cameras: any[]; + parser: any; + scene: THREE.Object3D; + scenes: any[]; + userData: any; +}; + +export type ModelFlag = + | "NORMAL" + | "HAT" + | "FACE_ONLY" + | "FLATTEN_NOSE" + | "NEW_EXPRESSIONS" + | "NEW_MASK_ONLY"; + +// async function createOrUpdateCharModel( +// rendererRef: THREE.WebGLRenderer, +// modelDesc: any, +// newStudioData: Uint8Array, +// charModelRef?: CharModel +// ) { +// let currentCharModel: CharModel; +// if (charModelRef) { +// if (!rendererRef) +// throw new Error("Missing renderer when trying to update CharModel"); + +// currentCharModel = charModelRef; + +// // Create new charinfo data +// const studioCharInfo = StudioCharInfo.unpack(newStudioData); +// const newCharInfo = FFLiCharInfo.pack( +// convertStudioCharInfoToFFLiCharInfo(studioCharInfo) +// ); + +// // update char model +// updateCharModel(currentCharModel, newCharInfo, rendererRef, modelDesc); +// } else { +// currentCharModel = createCharModel( +// newStudioData, +// modelDesc, +// await getShaderMaterialFromShaderType(), +// getFFL(), +// false, +// await getMaterialOverridesFromShaderType() +// ); +// } + +// return currentCharModel; +// } + +export async function getHeadModel( + mii: Mii, + rendererRef: THREE.WebGLRenderer, + modelFlag?: ModelFlag, + texResolution?: number +): Promise { + const dataU8 = mii.export("studioData"); + + const modelDesc = FFLCharModelDescDefault; + modelDesc.resolution = 512; + modelDesc.allExpressionFlag = new Uint32Array([1, 0, 0]); + if (modelFlag) modelDesc.modelFlag = FFLModelFlag[modelFlag]; + if (texResolution) modelDesc.resolution = texResolution; + + let currentCharModel: CharModel | null; + + try { + // currentCharModel = await createOrUpdateCharModel( + // rendererRef, + // modelDesc, + // dataU8, + // charModelRef + // ); + + currentCharModel = createCharModel( + dataU8, + modelDesc, + (await getShaderMaterialFromShaderType()) as any, + getFFL(), + false + // await getMaterialOverridesFromShaderType() + ); + + // Initialize textures for the new CharModel. + + if (mii.eyeSclera === 1 && mii.eyeColor !== 8) { + window.eyeScleraHack = true; + } + + // QUICKLY Replace the material + currentCharModel._materialTextureClass = FFLShaderMaterial; + + initCharModelTextures(currentCharModel, rendererRef, FFLShaderMaterial); + + if (mii.eyeSclera === 1 && mii.eyeColor !== 8) { + window.eyeScleraHack = false; + } + } catch (err) { + currentCharModel = null; + alert(`Error creating/updating CharModel: ${err}`); + console.error("Error creating/updating CharModel:", err); + throw err; + } + + const asset = { + extras: { + partsTransform: currentCharModel.partsTransform + } + }; + + let scene = new THREE.Group(); + + scene.add(currentCharModel.meshes!); + + // GLTF-like object so that the code can still handle it sort of like one + return { + animations: [], + asset, + cameras: [], + parser: {}, + scene, + scenes: [scene], + userData: {}, + CharModel: currentCharModel + } as GLTFLike as GLTF; +} + +export type MaskResult = { + model: CharModel; + img: THREE.DataTexture; +}; + +export async function getMaskTex( + mii: Mii, + rendererRef: THREE.WebGLRenderer, + expressionFlag: Uint32Array = new Uint32Array([1, 0, 0]) +): Promise { + const dataU8 = mii.export("studioData"); + + const modelDesc = FFLCharModelDescDefault; + modelDesc.resolution = 1024; + modelDesc.allExpressionFlag = expressionFlag; + + let currentCharModel: CharModel | null; + + var img: THREE.DataTexture; + + const shaderMaterial = await getShaderMaterialFromShaderType(); + + try { + currentCharModel = createCharModel( + dataU8, + modelDesc, + // shader doesn't matter here for our purpose + shaderMaterial as any, + getFFL(), + false + ); + + // weird workaround to promisify the texture outcome? + img = await new Promise((resolve) => { + // Initialize textures for the new CharModel. + if (mii.eyeSclera === 1 && mii.eyeColor !== 8) { + window.eyeScleraHack = true; + } + + initCharModelTextures( + currentCharModel!, + rendererRef, + FFLShaderMaterial + // null, + // (dataTexture) => { + // resolve(dataTexture); + // } + ); + + if (mii.eyeSclera === 1 && mii.eyeColor !== 8) { + window.eyeScleraHack = false; + } + + const target = + currentCharModel!._maskTargets[currentCharModel!.expression]!; + + renderTargetToDataTexture(target, rendererRef).then((r) => { + resolve(r); + }); + }); + } catch (err) { + currentCharModel = null; + alert(`Error creating/updating CharModel: ${err}`); + console.error("Error creating/updating CharModel:", err); + throw err; + } + + return { img, model: currentCharModel }; +} diff --git a/src/util/ModelLoader.ts b/src/util/ModelLoader.ts new file mode 100644 index 0000000..eb5be7d --- /dev/null +++ b/src/util/ModelLoader.ts @@ -0,0 +1,158 @@ +import JSZip from "jszip"; +import localforage from "localforage"; +import * as THREE from "three"; +import { GLTFLoader, type GLTF } from "three/examples/jsm/Addons.js"; +import { BodyType } from "../constants/BodyShaderTypes"; + +//! NOTE: THIS ASSUMES THE ROOT IS THE PUBLIC FOLDER +let root = "/"; +export const setRoot = (newRoot: string) => { + root = newRoot; +}; +var gltfLoader = new GLTFLoader(); +var imageLoader = new THREE.ImageBitmapLoader(); +function makeModelPath(gender: string, modelName: string) { + return `${root}assets/models/miiBody${gender}_${modelName}.glb`; +} +async function loadBodyModel(modelPath: string) { + const model = await gltfLoader.loadAsync(modelPath); + + var mixer = new THREE.AnimationMixer(model.scene); + const scene = model.scene; + + if (model.animations.length > 0) { + const idleClip = model.animations[0]; + const idleAnim = mixer.clipAction(idleClip, scene); + idleAnim.stop(); + try { + const clip = model.animations.find((a) => a.name === "Pose.01")!; + const anim = mixer.clipAction(clip, scene); + anim.play(); + anim.timeScale = 0; + anim.paused = true; + mixer.update(0); + } catch (e) {} + } else console.warn("Body model has no animations"); + + return model; +} + +let bodyType = "wiiu"; +export async function loadBodyModels( + input?: string, + alsoLoadStreetPass: boolean = false +) { + if (Object.keys(bodyModels).length > 0) { + // todo: dispose them? idk + bodyModels = {}; + } + bodyType = + input || (await localforage.getItem("settings_bodyModel")) || "wiiu"; + bodyModelName = bodyType; + + if (bodyType === BodyType.StreetPass) { + isStreetPassBody = true; + } + + if (bodyModels.highM) { + bodyModels.highM.scene.traverse((o: any) => { + if (o.isMesh) { + o.dispose(); + } + }); + } + if (bodyModels.highF) { + bodyModels.highF.scene.traverse((o: any) => { + if (o.isMesh) { + o.dispose(); + } + }); + } + + bodyModels.highM = await loadBodyModel(makeModelPath("M", bodyType)); + bodyModels.highF = await loadBodyModel(makeModelPath("F", bodyType)); + + if (alsoLoadStreetPass) { + bodyModels.lowM = await loadBodyModel(makeModelPath("M", "streetpass")); + bodyModels.lowF = await loadBodyModel(makeModelPath("F", "streetpass")); + } +} + +export async function loadHatModels() { + // Load hat models bundle + // todo: dispose them? idk + hatModels = []; + const data = await fetch(root + "assets/models/hat_models_bundle.zip").then( + (j) => j.blob() + ); + const zip = await JSZip.loadAsync(data); + let promises = []; + const fileList = Object.keys(zip.files); + for (const file of fileList) { + promises.push(zip.files[file].async("blob")); + } + const resolves = await Promise.all(promises); + for (let i = 0; i < fileList.length; i++) { + console.log("File:", fileList[i]); + const url = URL.createObjectURL(resolves[i]); + const gltf = await gltfLoader.loadAsync(url); + hatModels[i] = gltf.scene; + URL.revokeObjectURL(url); + } +} + +export async function loadClothesTextures() { + clothesTextures = {}; + imageLoader.setOptions({ imageOrientation: "flipY" }); + + // Load hat models bundle + const data = await fetch( + root + "assets/images/mii_clothes_textures_bundle.zip" + ).then((j) => j.blob()); + console.log("Got it"); + const zip = await JSZip.loadAsync(data); + console.log("Got zip"); + let promises = []; + const fileList = Object.keys(zip.files); + for (const file of fileList) { + promises.push(zip.files[file].async("blob")); + } + const resolves = await Promise.all(promises); + console.log("Got files"); + for (let i = 0; i < fileList.length; i++) { + const url = URL.createObjectURL(resolves[i]); + let result: any; + + console.log("Loading texture"); + result = new THREE.CanvasTexture(await imageLoader.loadAsync(url)); + // (result as THREE.Texture).flipY = true; + console.log("Loading texture done"); + + const fileName = fileList[i].split("."); + fileName.pop(); + clothesTextures[fileName.join(".")] = result; + console.log("Loading " + fileName.join(".")); + + URL.revokeObjectURL(url); + } + console.log("Done"); +} + +// Cloneable models used +let bodyModels: Record = { + highM: null, + highF: null, + lowM: null, + lowF: null +}; +let bodyModelName: string = "wiiu"; +let hatModels: THREE.Group[] = []; +let clothesTextures: Record = {}; + +let isStreetPassBody = false; + +export const isStreetPass = () => isStreetPassBody; +export const getBodyModels = () => bodyModels as Record; +export const getHatModels = () => hatModels; +export const getLoadedBodyModelName = () => bodyModelName; +export const getClothesTextures = () => clothesTextures; diff --git a/src/util/Numbers.ts b/src/util/Numbers.ts index 9f4e8a9..775f777 100644 --- a/src/util/Numbers.ts +++ b/src/util/Numbers.ts @@ -1,2 +1,24 @@ export const ArrayNum = (number: number) => Array.from(Array(number).keys()); -export const RandomInt = (max:number) => Math.floor(Math.random() * max); \ No newline at end of file +export const RandomInt = (max: number) => Math.floor(Math.random() * max); + +export function randomizeUint8Array(arr: Uint8Array) { + if (!(arr instanceof Uint8Array)) { + throw new TypeError("Expected a Uint8Array"); + } + + function randomize() { + // Fallback to Math.random (not cryptographically secure) + for (let i = 0; i < arr.length; i++) { + arr[i] = Math.floor(Math.random() * 256); + } + } + + if (typeof window !== "undefined") { + if (window.crypto && window.crypto.getRandomValues) { + window.crypto.getRandomValues(arr); + } else randomize(); + } else { + randomize(); + } + return arr; +} diff --git a/src/util/SettingsHelper.ts b/src/util/SettingsHelper.ts index 3f0ab79..ad6eaf6 100644 --- a/src/util/SettingsHelper.ts +++ b/src/util/SettingsHelper.ts @@ -1,5 +1,288 @@ import localforage from "localforage"; -import { settingsInfo } from "../ui/pages/Settings"; +import { BodyType, ShaderType } from "../constants/BodyShaderTypes"; +import Modal from "../ui/components/Modal"; +import { replayUpdateNotice } from "../ui/pages/Settings"; + +import { _ } from "../util/Lang"; +import { Config } from "../config"; +import type Html from "@datkat21/html"; +const __ = _(); + +/* Unused but here for translation purposes */ +// Low resource file +__("Low"); +// Middle resource file +__("Middle"); +// High resource file +__("High"); + +export const settingsInfo: Record = { + bgm: { + type: "checkbox", + label: __("Enable background music"), + default: true, + description: __("Toggle background music depending on the theme.") + }, + sfx: { + type: "checkbox", + label: __("Enable sound effects"), + default: true, + description: __("Toggle sound effects for buttons and inputs.") + }, + accessibilityFeature: { + type: "checkbox", + label: __("Enable accessibility features"), + default: false, + description: __("The editor UI will be tweaked to be more accessible.") + }, + autoCloseCustomRender: { + type: "checkbox", + label: __("Auto-close custom render menu"), + default: true, + description: __( + "The custom render menu will automatically close when pressing save." + ) + }, + autoCloseQrScan: { + type: "checkbox", + label: __("Auto-close QR scan menu"), + default: true, + description: __( + "The QR code scanner will disappear after a successful scan." + ) + }, + allowQrCamera: { + type: "checkbox", + label: __("Allow using camera in QR scanner"), + default: true, + description: __( + "When this is disabled, the camera won't be used and some errors may not appear." + ) + }, + // syncLibrary: { + // type: "checkbox", + // label: __("Automatically sync Miis in your library"), + // default: true, + // description: __( + // "When this is disabled, Mii characters will not sync automatically with the server." + // ) + // }, + editMode: { + type: "multi", + label: __("Editing Mode"), + description: __("Changes the default edit mode option."), + default: "3d", + choices: [ + { label: __("2D"), value: "2d" }, + { label: __("3D"), value: "3d" } + ] + }, + theme: { + type: "multi", + label: __("Theme"), + default: "default", + description: __( + "When this is set to Normal, your device's color theme preferences will be used." + ), + choices: [ + { label: __("Normal"), value: "default" }, + { label: __("Wii U"), value: "wiiu", disabled: true } + ] + }, + resourceType: { + type: "multi", + label: __("Resource Type"), + default: String(Config.renderer.fflResourcePath.length - 1), + description: __( + "This changes model/texture quality.\n* Low resource cannot use some shader features." + ), + choices: [ + ...Config.renderer.fflResourcesNames.map((n, i) => ({ + label: __(n), + value: String(i) + })) + ] + }, + shaderType: { + type: "multi", + label: __("Shader Type"), + description: __( + "Change the lighting used in icons, renders and the editor." + ), + default: ShaderType.WiiU, + choices: [ + { label: __("No Lighting"), value: ShaderType.LightDisabled }, + { label: __("Simple"), value: ShaderType.ThreePhong }, + { label: __("Toon"), value: ShaderType.ThreeToon }, + { label: __("Wii U"), value: ShaderType.WiiU }, + { label: __("Wii U (Blinn)"), value: ShaderType.WiiUBlinn }, + { label: __("Wii U (Bright)"), value: ShaderType.WiiUFFLIconWithBody }, + { label: __("Wii U (Toon)"), value: ShaderType.WiiUToon }, + // { label: __("Switch (WIP)"), value: ShaderType.Switch, disabled: true }, + { label: __("Miitomo"), value: ShaderType.Miitomo }, + { label: __("Miitomo (Basic)"), value: ShaderType.MiitomoBasic } + ] + }, + bodyModel: { + type: "multi", + label: __("Body Model"), + description: __( + "Pose selections are different depending on the body model you use." + ), + default: BodyType.WiiU, + choices: [ + { label: __("Wii U"), value: BodyType.WiiU }, + { label: __("Switch"), value: BodyType.Switch, disabled: true }, + { label: __("Miitomo"), value: BodyType.Miitomo } + // { label: __("StreetPass"), value: BodyType.StreetPass, disabled: true }, + ] + }, + // TODO: Implement + // iconCameraPosition: { + // type: "multi", + // label: __("Icon Camera Position"), + // description: __( + // "This changes the camera position for all icons." + // ), + // default: BodyType.WiiU, + // choices: [ + // { label: __("Wii U"), value: "variableiconbody" }, + // { label: __("Switch"), value: "fovy", disabled: true }, + // { label: __("Miitomo"), value: BodyType.Miitomo } + // // { label: __("StreetPass"), value: BodyType.StreetPass, disabled: true }, + // ] + // }, + bodyModelHands: { + type: "checkbox", + label: __("Color hands to skin tone"), + default: false, + description: __("The hands of the body will match the Mii's skin tone."), + condition: (settings: any) => settings.bodyModel !== "wiiu" + }, + customRenderGreenScreen: { + type: "multi", + label: __("Use background in custom render"), + default: "off", + description: __("The custom render will have a solid color background."), + choices: [ + { label: __("Disabled"), value: "off" }, + { label: __("Green"), value: "green" }, + { label: __("Blue"), value: "blue" }, + { label: __("Black"), value: "black" }, + { label: __("White"), value: "white" }, + { label: __("Custom"), value: "custom", isColor: true } + ] + }, + personalMii: { + type: "non-settings-multi", + label: __("Personal Mii"), + description: __("Manage your choice of Personal Mii."), + choices: [ + { + label: __("Choose"), + async select() {} + } + ] + // render(html: Html) { + // html.text("REAL"); + // } + }, + saveData: { + type: "non-settings-multi", + label: __("Save Data"), + description: __("Not implemented yet."), + choices: [ + { + label: __("Import"), + // async select() { + // if ( + // (await Modal.prompt( + // "WARNING", + // "This will overwrite ALL of your currently saved Miis and delete them forever!\nPlease back up your save data before using this option.\n\nAre you certain that you understand the risk?", + // "body" + // )) === false + // ) + // return; + + // const input = document.createElement("input"); + // input.type = "file"; + // input.accept = "application/json"; + // document.body.appendChild(input); + // input.click(); + // requestAnimationFrame(() => { + // document.body.removeChild(input); + // }); + // input.addEventListener("change", async (e) => { + // if (input.files === null) return; + // if (input.files[0] === undefined) return; + // console.log(input.files); + + // const reader = new FileReader(); + + // reader.onload = function (event) { + // const fileContent = event.target!.result; + // console.log(fileContent); + // }; + + // reader.onerror = function (event) { + // console.error("File reading error:", event); + // }; + + // reader.readAsText(input.files[0]); + // }); + // }, + disabled: true + }, + { + label: __("Export"), + // async select() { + // let data: Record = {}; + // for (const key of (await localforage.keys()).filter((k) => + // k.startsWith("mii") + // )) { + // console.log(key); + // data[key] = (await localforage.getItem(key)) as string; + // } + // console.log(data); + // const url = URL.createObjectURL( + // new Blob([JSON.stringify(data)], { type: "application/json" }) + // ); + // const a = document.createElement("a"); + // a.href = url; + // a.target = "_blank"; + // a.download = "mii-editor-save-data.json"; + // document.body.appendChild(a); + // a.click(); + // requestAnimationFrame(() => { + // a.remove(); + // }); + // }, + disabled: true + }, + { + label: __("Delete"), + type: "danger", + async select() {}, + disabled: true + } + ] + }, + updateNotices: { + type: "non-settings-multi", + label: __("Update Notices"), + description: __("View the last update notice if you missed it."), + choices: [ + { + label: + // Action + __("Review update notice"), + select() { + replayUpdateNotice(); + } + } + ] + } +}; export const getSetting = async (key: string) => { const result = await localforage.getItem("settings_" + key); diff --git a/src/util/allocateArray.ts b/src/util/allocateArray.ts new file mode 100644 index 0000000..6727eef --- /dev/null +++ b/src/util/allocateArray.ts @@ -0,0 +1,15 @@ +export function allocateArray(size: number, data: Uint8Array) { + if (data.length > size) + throw new RangeError( + `Tried to fill ${data.length} bytes into a ${size}-byte array` + ); + + let array = new Uint8Array(size); + + // not sure how else to fill the data and remain 0's + for (var i = 0; i < data.length; i++) { + array[i] = data[i]; + } + + return array; +} diff --git a/src/util/camera.js b/src/util/camera.js new file mode 100644 index 0000000..df9a793 --- /dev/null +++ b/src/util/camera.js @@ -0,0 +1,107 @@ +import * as THREE from "three"; + +/** + * @enum {number} + */ +export const ViewType = { + Face: 0, // Typical icon body view. + MakeIcon: 1, // FFLMakeIcon matrix + // Custom + IconFovy45: 2, + AllBody: 3, + AllBodySugar: 4, + CreditIcon: 5, +}; + +// TODO: private? +// -------------- getCameraForViewType(viewType, width, height) -------------- +/** + * @param {ViewType} viewType - The {@link ViewType} enum value. + * @param {number} width - Width of the view. + * @param {number} height - Height of the view. + * @param {number} h - Height of me. + * @returns {import('three').PerspectiveCamera} The camera representing the view type specified. + * @throws {Error} not implemented (ViewType.Face) + */ +export function getCameraForViewType(viewType, width = 1, height = 1, miiHeight = 1) { + const aspect = width / height; + switch (viewType) { + case ViewType.Face: { + // FFL-Testing equivalent: + const fovy = 15; // Math.atan2(43.2 / aspect, 500) / 0.5; + const camera = new THREE.PerspectiveCamera(fovy, aspect, 0.1, 1000); + camera.position.set(0, 34.5, 380);//411.181793); + camera.lookAt(0, 34.3, 0.0); + // pCamera->at() = { 0.0f, 34.3f, 0.0f }; + + return camera; + } + case ViewType.MakeIcon: { + const fovy = 9.8762; // rad2deg(Math.atan2(43.2 / aspect, 500) / 0.5); + const camera = new THREE.PerspectiveCamera(fovy, aspect, 500, 1000); + camera.position.set(0, 34.5, 600); + camera.lookAt(0, 34.5, 0.0); + return camera; + } + case ViewType.IconFovy45: { + const camera = new THREE.PerspectiveCamera(45, aspect, 50, 1000); + camera.position.set(0, 34, 110); + camera.lookAt(0, 34, 0); + return camera; + } + case ViewType.AllBody: { + const fovy = 15; + const camera = new THREE.PerspectiveCamera(fovy, aspect, 50, 1500); + camera.position.set(0, 50, 900); + camera.lookAt(0, 105, 0); + return camera; + } + case ViewType.AllBodySugar: { + const fovy = 15; + const camera = new THREE.PerspectiveCamera(fovy, aspect, 50, 15000); + + // These camera parameters look right when the character is tallest + const posStart = new THREE.Vector3(0.0, 65.0, 550.0); + const atStart = new THREE.Vector3(0.0, 65.0, 0.0); + + // Likewise these look correct when it's shortest. + const posEnd = new THREE.Vector3(0.0, 75.0, 850.0); + const atEnd = new THREE.Vector3(0.0, 88.0, 0.0); + + // Calculate interpolation factor (normalized to range [0, 1]) + const t = (miiHeight - 0.5) / (1.264 - 0.5); + + // Interpolate between start and end positions + const pos = new THREE.Vector3( + posStart.x + t * (posEnd.x - posStart.x), + posStart.y + t * (posEnd.y - posStart.y), + posStart.z + t * (posEnd.z - posStart.z) + ); + + // Interpolate between start and end target positions + const at = new THREE.Vector3( + atStart.x + t * (atEnd.x - atStart.x), + atStart.y + t * (atEnd.y - atStart.y), + atStart.z + t * (atEnd.z - atStart.z) + ); + + // console.log("pos:", pos.toArray()); + // console.log("lookAt:", at.toArray()); + + // Set the camera position and look-at target + camera.position.copy(pos); + camera.lookAt(at); + + return camera; + } + case ViewType.CreditIcon: { + const fovy = 15; + const camera = new THREE.PerspectiveCamera(fovy, aspect, 0.1, 1000); + camera.position.set(-60, 34.5, 380); + camera.lookAt(0, 34.3, 0.0); + return camera; + } + default: + throw new Error('getCameraForViewType: not implemented'); + } +} \ No newline at end of file diff --git a/src/util/dataConvert.ts b/src/util/dataConvert.ts new file mode 100644 index 0000000..60e0992 --- /dev/null +++ b/src/util/dataConvert.ts @@ -0,0 +1,32 @@ +export function dataToBase64(data: Uint8Array) { + return btoa(String.fromCharCode.apply(null, data as any)); +} +export function dataToHex(data: Uint8Array) { + return Array.from(data, (i) => i.toString(16).padStart(2, "0")).join(""); +} + +export function encodeUTF16LE(str: string) { + // Allocate an ArrayBuffer with enough bytes (2 bytes per character) + const buffer = new ArrayBuffer(str.length * 2); + const view = new DataView(buffer); + + // Write each character's UTF-16 code unit into the buffer in little-endian order. + for (let i = 0; i < str.length; i++) { + view.setUint16(i * 2, str.charCodeAt(i), true); // 'true' forces little-endian + } + + // Return a Uint8Array view of the buffer for byte-level operations. + return new Uint8Array(buffer); +} +export function decodeUTF16LE(bytes: Uint8Array) { + // Create a DataView on the provided Uint8Array. This handles offsets correctly. + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let result = ""; + + // Read 2 bytes at a time in little-endian order and convert them to characters. + for (let i = 0; i < view.byteLength; i += 2) { + result += String.fromCharCode(view.getUint16(i, true)); // 'true' for little-endian + } + + return result; +} diff --git a/src/util/downloadLink.ts b/src/util/downloadLink.ts index 006bbc3..4b1cd0a 100644 --- a/src/util/downloadLink.ts +++ b/src/util/downloadLink.ts @@ -11,7 +11,7 @@ export function downloadLink(url: string, name: string) { } const link = document.createElement("a"); -function save(blob: Blob, filename: string) { +export function saveBlob(blob: Blob, filename: string) { if (link.href) { URL.revokeObjectURL(link.href); } @@ -22,9 +22,9 @@ function save(blob: Blob, filename: string) { } export function saveArrayBuffer(buffer: any, filename: string) { - save(new Blob([buffer], { type: "application/octet-stream" }), filename); + saveBlob(new Blob([buffer], { type: "application/octet-stream" }), filename); } export function saveString(text: string, filename: string) { - save(new Blob([text], { type: "text/plain" }), filename); + saveBlob(new Blob([text], { type: "text/plain" }), filename); } diff --git a/src/util/miiImageUtils.ts b/src/util/miiImageUtils.ts index 6fa719d..a8bfbe1 100644 --- a/src/util/miiImageUtils.ts +++ b/src/util/miiImageUtils.ts @@ -1,29 +1,37 @@ import qrjs from "../external/mii-frontend/qrjs.min.js"; -import { - convertDataToType, - supportedFormats, -} from "../external/mii-frontend/data-conversion.js"; -import { encryptAndEncodeVer3StoreDataToQRCodeFormat } from "./EncodeQRCode.js"; -import Mii from "../external/mii-js/mii.js"; -import { Buffer as Buf } from "../../node_modules/buffer/index"; -import { CameraPosition, Mii3DScene, SetupType } from "../class/3DScene.js"; +import { encryptAndEncodeVer3StoreDataToQRCodeFormat } from "./EncodeQRCode"; +import Mii from "../class/MiiData"; +import { CameraPosition, Mii3DScene, SetupType } from "../class/3DScene"; import Html from "@datkat21/html"; import { Vector3 } from "three"; -import { AddButtonSounds } from "./AddButtonSounds.js"; -import { Config } from "../config.js"; - -const ver3Format = supportedFormats.find( - (f) => f.className === "Gen2Wiiu3dsMiitomo" -)!; +import { AddButtonSounds } from "./AddButtonSounds"; +import { Config } from "../config"; +import { getMiiIcon } from "../ui/pages/Library"; +import { parseHexOrB64ToUint8Array } from "../external/ffl.js/ffl"; +import EditorIcons from "../constants/EditorIcons"; +import { MiiCreatorV4AppendData } from "../class/struct/MiiCreatorV4Data"; +import { getFFLWorkerMakeIcon } from "./FFLLoader"; +import { ViewType } from "./camera.js"; +import { + ToVer3EyeColorTable, + ToVer3FacelineColorTable, + ToVer3GlassColorTable, + ToVer3GlassTypeTable, + ToVer3HairColorTable, + ToVer3MouthColorTable, + Ver3EyeColorTable, + Ver3FacelineColorTable, + Ver3GlassColorTable, + Ver3HairColorTable, + Ver3MouthColorTable +} from "../constants/ColorTables.js"; -const makeQrCodeImage = async (mii: string): Promise => { +const makeQrCodeImage = async (mii: Mii): Promise => { let convertedVer3Data: Uint8Array, ver3QRData: Uint8Array | any[]; - const miiU8 = new Uint8Array(Buf.from(mii, "base64")); + const miiU8 = mii.export("ffsd_append_miic"); - convertedVer3Data = new Uint8Array( - convertDataToType(miiU8, ver3Format, ver3Format.className, true) - ); + convertedVer3Data = new Mii(miiU8).export("ffsd"); ver3QRData = encryptAndEncodeVer3StoreDataToQRCodeFormat(convertedVer3Data); // Append any data after the first 96 bytes (fixed by the function above) @@ -41,140 +49,11 @@ const makeQrCodeImage = async (mii: string): Promise => { }); }; -export enum MiiCustomRenderType { - Head, - HeadOnly, - Body, -} - -export const getMiiRender = async ( - mii: Mii, - type: MiiCustomRenderType, - useExtendedColors: boolean = true, - useBlob: boolean = true -): Promise => { - return new Promise((resolve, reject) => { - let tmpMii = new Mii(mii.encode()); - - if (useExtendedColors === false) { - tmpMii.trueEyeColor = tmpMii.fflEyeColor; - tmpMii.trueEyebrowColor = tmpMii.fflEyebrowColor; - tmpMii.trueFacialHairColor = tmpMii.fflFacialHairColor; - tmpMii.trueGlassesColor = tmpMii.fflGlassesColor; - tmpMii.trueGlassesType = tmpMii.fflGlassesType; - tmpMii.trueHairColor = tmpMii.fflHairColor; - tmpMii.trueMouthColor = tmpMii.fflMouthColor; - tmpMii.trueSkinColor = tmpMii.fflSkinColor; - - tmpMii.extEyeColor = tmpMii.fflEyeColor + 8; - tmpMii.extHairColor = tmpMii.fflHairColor; - tmpMii.extFacelineColor = tmpMii.fflSkinColor; - tmpMii.extBeardColor = tmpMii.fflFacialHairColor; - tmpMii.extEyebrowColor = tmpMii.fflEyebrowColor; - tmpMii.extGlassColor = 0; - tmpMii.extGlassType = tmpMii.fflGlassesType; - tmpMii.extHatColor = 0; - tmpMii.extHatType = 0; - } - - let parent = new Html("div") - .style({ - width: "720px", - height: "720px", - opacity: "0", - // position: "fixed", - }) - .appendTo("body"); - const scene = new Mii3DScene(tmpMii, parent.elm, SetupType.Screenshot); - scene.init().then(async () => { - await scene.updateBody(); - await scene.updateMiiHead(); - // swap pose for render - scene.anim.forEach((a) => { - a.timeScale = 0; - // a.stop(); - // a.reset(); - }); - scene.swapAnimation("Pose.01"); - - let scn = scene.getScene()!, - cam = scene.getCamera()!, - ctl = scene.getControls()!, - pos = new Vector3(); - switch (type) { - case MiiCustomRenderType.Head: - // zoom in on head - setTimeout(() => { - scene.focusCamera(0, true, false); - ctl.dollyTo(50); - cam.fov = 15; - cam.updateProjectionMatrix(); - }, 300); - break; - case MiiCustomRenderType.HeadOnly: - // hide body from view - scn.getObjectByName("body_m")!.visible = false; - scn.getObjectByName("hands_m")!.visible = false; - scn.getObjectByName("legs_m")!.visible = false; - scn.getObjectByName("body_f")!.visible = false; - scn.getObjectByName("hands_f")!.visible = false; - scn.getObjectByName("legs_f")!.visible = false; - // Get the bounding box of the object - scene.focusCamera(CameraPosition.MiiHead, true, false); - ctl.dollyTo(40); - cam.fov = 15; - cam.updateProjectionMatrix(); - break; - case MiiCustomRenderType.Body: - // default screenshot camera position - scene.focusCamera(CameraPosition.MiiFullBody, true, false); - ctl.dollyTo(90, false); - cam.fov = 15; - cam.updateProjectionMatrix(); - break; - } - - parent.append(scene.getRendererElement()); - - const renderer = scene.getRenderer(); - setTimeout(() => { - if (useBlob) - renderer.domElement.toBlob((blob) => { - const image = new Image( - renderer.domElement.width, - renderer.domElement.height - ); - image.src = URL.createObjectURL(blob!); - console.log("Temporary render URL:", image.src); - image.onload = () => { - resolve(image); - scene.shutdown(); - parent.cleanup(); - }; - }); - else { - const url = renderer.domElement.toDataURL("png", 100); - const image = new Image( - renderer.domElement.width, - renderer.domElement.height - ); - image.src = url; - image.onload = () => { - resolve(image); - scene.shutdown(); - parent.cleanup(); - }; - } - }, 500); - }); - }); -}; - export const getBackground = async ( - isMiic: boolean + extended: boolean ): Promise => { let url: string = ""; - if (isMiic) { + if (extended) { url = "./assets/images/bg_qr_miic.png"; } else { url = "./assets/images/bg_qr_wiiu.png"; @@ -204,22 +83,98 @@ export function loadImage(url: string): Promise { } export const QRCodeCanvas = async ( - mii: string, + mii: Mii, extendedColors: boolean = true ) => { - const miiData = new Mii(Buf.from(mii, "base64")); - const render = await loadImage( - `${Config.renderer.renderFullBodyAltURL}&data=${encodeURIComponent( - miiData.encodeStudio().toString("hex") - )}&${Config.renderer.hatTypeParam}=${ - miiData.extHatType + Config.renderer.hatTypeAdd - }&${Config.renderer.hatColorParam}=${ - miiData.extHatColor + Config.renderer.hatColorAdd - }` - ); + let render: HTMLImageElement, + renderPos = { y: 0, x: 0, width: 0, height: 0 }; + if (Config.renderer.useRendererServer) { + render = await loadImage( + `${Config.renderer.renderFullBodyAltURL}&data=${encodeURIComponent( + mii.exportHex("studioData") + )}&${Config.renderer.hatTypeParam}=${ + mii.hatType + 1 + Config.renderer.hatTypeAdd + }&${Config.renderer.hatColorParam}=${ + mii.hatFavoriteColor - 1 + Config.renderer.hatColorAdd + }` + ); + renderPos = { x: 54, y: -54, width: 714, height: 953 }; + } else { + // TODO + // render + let mii2 = new Mii(mii.export("studioData")); + + mii2.beardColor = Ver3HairColorTable[ToVer3HairColorTable[mii2.beardColor]]; + mii2.eyeColor = Ver3EyeColorTable[ToVer3EyeColorTable[mii2.eyeColor]]; + mii2.eyebrowColor = + Ver3HairColorTable[ToVer3HairColorTable[mii2.eyebrowColor]]; + mii2.facelineColor = + Ver3FacelineColorTable[ToVer3FacelineColorTable[mii2.facelineColor]]; + mii2.glassColor = + Ver3GlassColorTable[ToVer3GlassColorTable[mii2.glassColor]]; + mii2.glassType = ToVer3GlassTypeTable[mii2.glassType]; + mii2.hairColor = Ver3HairColorTable[ToVer3HairColorTable[mii2.hairColor]]; + mii2.mouthColor = + Ver3MouthColorTable[ToVer3MouthColorTable[mii2.mouthColor]]; + mii2.facePaintColor = -1; + mii2.hatType = -1; + mii2.eyeSclera = 0; + + const renderResult = await getFFLWorkerMakeIcon({ + data: mii2.export("studioData"), + additionalInfo: { + favorite: mii2.favorite, + hatCommonColor: mii2.hatCommonColor, + hatFavoriteColor: mii2.hatFavoriteColor, + hatType: mii2.hatType, + pantsColor: mii2.pantsColor, + shirtColor: mii2.shirtColor, + special: mii2.special, + temporary: mii2.temporary, + eyeSclera: mii2.eyeSclera, + wigType: mii2.wigType, + clothesType: mii2.clothesType, + shoesColor: mii2.shoesColor + }, + size: 720, + expression: 0, + type: ViewType.AllBodySugar + }); + + // Load in the image + let imageURL: string = renderResult; + const img = new Image(720, 720); + img.src = imageURL; + render = await new Promise((resolve) => { + img.onload = () => { + return resolve(img); + }; + }); + renderPos = { x: -65, y: -54, width: 952, height: 952 }; + } + console.log("got render"); const qrCodeSource = await makeQrCodeImage(mii); const background = await getBackground(extendedColors); + let favoriteIcon: HTMLImageElement | undefined = undefined; + if (mii.favorite === 1 || mii.special === 1) { + console.log("loading favorite icon"); + favoriteIcon = await new Promise((resolve) => { + var img = new Image(); + img.onload = function () { + resolve(img); + }; + + if (mii.favorite === 1) + img.src = + "data:image/svg+xml," + encodeURIComponent(EditorIcons.favorite); + if (mii.special === 1) + img.src = + "data:image/svg+xml," + encodeURIComponent(EditorIcons.special); + }); + console.log("loaded favorite icon"); + } + const canvas = document.createElement("canvas"); canvas.width = 1280; canvas.height = 720; @@ -239,7 +194,13 @@ export const QRCodeCanvas = async ( ctx.textBaseline = "top"; ctx.fillStyle = "#cccccc"; ctx.fillText(`Made with Mii Creator ${Config.version.string}`, 1248, 667); - ctx.drawImage(render, 54, -54, 714, 953); + ctx.drawImage( + render, + renderPos.x, + renderPos.y, + renderPos.width, + renderPos.height + ); // qr code container ctx.fillStyle = "#ffffff"; ctx.beginPath(); @@ -251,18 +212,25 @@ export const QRCodeCanvas = async ( ctx.beginPath(); ctx.roundRect(769, 542, 463, 99, [0, 0, 16, 16]); ctx.fill(); + + // favorite icon (if exists) + if (favoriteIcon) { + ctx.drawImage(favoriteIcon, 1172, 480, 102, 102); + console.log("drawing favorite icon"); + } + // mii name ctx.fillStyle = "#ffffff"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.font = '500 38px "NTLG", sans-serif'; - ctx.fillText(miiData.miiName, 1005, 591); + ctx.fillText(mii.nickname, 1005, 591); const canvasPngImage = canvas.toDataURL("png", 100); return canvasPngImage; }; // This recreates the html from the update changelog -export function createMiiCard( +export async function createMiiCard( parent: Html | HTMLElement, name: string, username: string, @@ -276,19 +244,19 @@ export function createMiiCard( .style({ gap: "0", "justify-content": "flex-start", - "text-align": "left", + "text-align": "left" }) .appendMany( new Html("img") .attr({ width: 96, draggable: "false", - src: - Config.renderer.renderHeadshotURLNoParams + - `?data=${encodeURIComponent( - studioData - )}&type=variableiconbody&verifyCharInfo=0&shaderType=switch&width=96&source=credits&characterYRotate=8&bodyType=switch&` + - extra, + src: await getMiiIcon(studioData, "creditIcon", "creditIcon", 128) + // Config.renderer.renderHeadshotURLNoParams + + // `?data=${encodeURIComponent( + // studioData + // )}&type=variableiconbody&verifyCharInfo=0&shaderType=switch&width=96&source=credits&characterYRotate=8&bodyType=switch&` + + // extra, }) .style({ width: "96px", height: "96px" }), new Html("div") @@ -299,7 +267,7 @@ export function createMiiCard( .appendMany( new Html("span").text(name).style({ display: "inline", - width: "max-content", + width: "max-content" }), AddButtonSounds( new Html("a") @@ -332,7 +300,7 @@ export function createIconCard( .style({ gap: "0", "justify-content": "flex-start", - "text-align": "left", + "text-align": "left" }) .appendMany( new Html("div").html(icon).style({ width: "96px", height: "96px" }), @@ -344,7 +312,7 @@ export function createIconCard( .appendMany( new Html("span").text(name).style({ display: "inline", - width: "max-content", + width: "max-content" }) ) .style({ display: "flex", gap: "8px" }), diff --git a/src/util/rendertarget.js b/src/util/rendertarget.js new file mode 100644 index 0000000..afa619d --- /dev/null +++ b/src/util/rendertarget.js @@ -0,0 +1,101 @@ +import * as THREE from "three"; +import { getIdentCamera } from "../external/ffl.js/ffl"; + +// Web Worker shenanigans +let isWorker = false; +if (typeof window === 'undefined') { + isWorker = true +} + +export function renderTargetToDataURL(renderTarget, renderer, flipY = false, blob = true) { + return new Promise((resolve) => { + // Create a new scene using a full-screen quad. + const scene = new THREE.Scene(); + scene.background = null; + // Assign a transparent, textured, and double-sided material. + const material = new THREE.MeshBasicMaterial({ + side: THREE.DoubleSide, + map: renderTarget.texture, + transparent: true + }); + const plane = new THREE.PlaneGeometry(2, 2); // Full-screen quad + const mesh = new THREE.Mesh(plane, material); + scene.add(mesh); + + // Use an orthographic camera that fits the full screen. + const camera = getIdentCamera(flipY); + // Get previous render target, color space, and size. + const prevTarget = renderer.getRenderTarget(); + const prevColorSpace = renderer.outputColorSpace; + const size = new THREE.Vector2(); + renderer.getSize(size); + + // Render to the main canvas to extract pixels. + renderer.setRenderTarget(null); // Switch render target. + // Use working color space. + renderer.outputColorSpace = THREE.ColorManagement ? THREE.ColorManagement.workingColorSpace : null; + renderer.setSize(renderTarget.width, renderTarget.height, false); + renderer.render(scene, camera); + + function cleanup() { + // Cleanup. + material.dispose(); + plane.dispose(); + scene.remove(mesh); + + // Restore previous size, color space, and target. + renderer.outputColorSpace = prevColorSpace; + renderer.setSize(size.x, size.y, false); + renderer.setRenderTarget(prevTarget); + } + + // Convert the renderer's canvas to an image. + if (blob) { + // assume this is a Web Worker, so it's offscreen canvas. an alt method is used + // using file reader was kind of dumb so i just create a blob URL in the main worker.ts file + const ok = blob => { + resolve({type:"blob", result:blob}); + cleanup(); + } + if (isWorker) { + renderer.domElement.convertToBlob({ type: "image/png" }).then(ok); + } else { + renderer.domElement.toBlob(ok); + } + } else { + const result = renderer.domElement.toDataURL('image/png'); + // resolve(result); + resolve({type:"dataURL", result}); + cleanup(); + } +}); +} + +// ----------- renderTargetToDataTexture(renderTarget, renderer, flipY) ----------- +/** + * Gets a data URL for a render target's texture using the same renderer. + * + * @param {THREE.RenderTarget} renderTarget - The render target. + * @param {THREE.WebGLRenderer} renderer - The renderer (MUST be the same renderer used for the target). + * @param {Boolean} [flipY=false] - Flip the Y axis. Default is oriented for OpenGL. + * @returns {Promise} The data URL representing the RenderTarget's texture contents. + */ +export async function renderTargetToDataTexture(renderTarget, renderer, flipY = false, filtering = true) { + const width = renderTarget.width, height = renderTarget.height; + let buf = new Uint8Array(width * height * 4); + await renderer.readRenderTargetPixelsAsync(renderTarget, 0, 0, width, height, buf); + const dataTexture = new THREE.DataTexture(buf, width, height, THREE.RGBAFormat, THREE.UnsignedByteType); + dataTexture.needsUpdate = true; + + if (flipY) { + dataTexture.flipY = true; + } + + if (filtering) { + dataTexture.minFilter = THREE.LinearFilter; + dataTexture.magFilter = THREE.LinearFilter; + } + + // Caller has to update data texture wrap/filter params. + return dataTexture; +} \ No newline at end of file diff --git a/src/util/scaling.ts b/src/util/scaling.ts new file mode 100644 index 0000000..d66b748 --- /dev/null +++ b/src/util/scaling.ts @@ -0,0 +1,60 @@ +import * as THREE from "three"; +export function streetpassHandScaling( + body: THREE.Object3D, + scaleMul: number = 1 +) { + // // Tuning constant: adjust this to get the smooth effect you like. + // const k = 0.4; // 20% adjustment + + // var scaleVec = new THREE.Vector3(); + // body.getWorldScale(scaleVec); + + // // Compute the base compensation factors + // const baseHandScaleX = (1 / scaleVec.x) * scaleMul; + // const baseHandScaleY = (1 / scaleVec.y) * scaleMul; + + // // Create an adjustment factor that is 1 when scaleVec.y is 1. + // // If scaleVec.y < 1, (scaleVec.y - 1) is negative so the factor is less than 1. + // // If scaleVec.y > 1, the factor becomes greater than 1. + // const adjustmentY = 1 + k * (scaleVec.y - 1); + // // const adjustmentX = 1 + k * (scaleVec.x - 1); + + // // Apply the adjusted compensation factor for the y-axis. + // // Here we use the original inverse for x and z, but you can also adjust those if needed. + // // const adjustedHandScaleX = baseHandScaleX * adjustmentX; + // const adjustedHandScaleY = baseHandScaleY * adjustmentY; + + // console.log(baseHandScaleX, baseHandScaleY); + + // const handL = body.getObjectByName("handLPs")!; + // const handR = body.getObjectByName("handRPs")!; + + // handL.scale.set(baseHandScaleX, adjustedHandScaleY, baseHandScaleX); + // handR.scale.set(baseHandScaleX, adjustedHandScaleY, baseHandScaleX); + + // Tuning constant: adjust this to get the smooth effect you like. + const k = 0.2; // 20% adjustment + + var scaleVec = new THREE.Vector3(); + body.getWorldScale(scaleVec); + + // Compute the base compensation factors + const baseHandScaleX = 1 / scaleVec.x; + const baseHandScaleY = 1 / scaleVec.y; + + // Create an adjustment factor that is 1 when scaleVec.y is 1. + // If scaleVec.y < 1, (scaleVec.y - 1) is negative so the factor is less than 1. + // If scaleVec.y > 1, the factor becomes greater than 1. + const adjustmentFactor = 1 + k * (scaleVec.y - 1); + + // Apply the adjusted compensation factor for the y-axis. + // Here we use the original inverse for x and z, but you can also adjust those if needed. + const adjustedHandScaleY = baseHandScaleY * adjustmentFactor; + + body + .getObjectByName("handLPs")! + .scale.set(baseHandScaleX, adjustedHandScaleY, baseHandScaleX); + body + .getObjectByName("handRPs")! + .scale.set(baseHandScaleX, adjustedHandScaleY, baseHandScaleX); +} diff --git a/src/worker.ts b/src/worker.ts index 44037b5..afce471 100644 --- a/src/worker.ts +++ b/src/worker.ts @@ -1,125 +1,159 @@ -import { WebGLRenderer } from "three"; -import * as FFL from "./external/ffl.js/ffl"; -import { LUTShaderMaterial } from "./external/ffl.js/LUTShaderMaterial.js"; - -export type FFLWorkerMessage = - | FFLWorkerInitializeMessage - | FFLWorkerCreateIconMessage; - -export type FFLWorkerInitializeMessage = { - type: "Init"; // request type - resourcePath: any; // Path to resource file - offscreenCanvas: OffscreenCanvas; // Path to resource file -}; -export type FFLWorkerCreateIconMessage = { - type: "MakeIcon"; // request type - data: Uint8Array; // commonly studio data? - view: string; // commonly studio data? - id: string; // random id -}; - -let FFLModule: any, - offscreenCanvas: OffscreenCanvas, - workerRenderer: WebGLRenderer; - -function log(...message: any[]) { - console.log("[FFLWorker]", ...message); -} -function initRenderer() { - workerRenderer = new WebGLRenderer({ - antialias: true, - alpha: true, - canvas: offscreenCanvas, - }); -} - -self.onmessage = async (e) => { - log("Message received from main script", e); - - const input = e.data as FFLWorkerMessage; - switch (input.type) { - case "Init": { - // The only solution I could find is just to load the ffl wasm module again but in the web worker. - // Hopefully it and the resource are cached by the browser so it should load instantly? - log("Loading FFL Module"); - FFLModule = (await import("./external/ffl.js/ffl-emscripten.js")).default - .Module as any; - log("Initialized Module!", FFLModule); - log("Loading FFL Resource..."); - await FFL.loadBodyModels(); - await FFL.initializeFFLWithResource(input.resourcePath, FFLModule); - log("Loaded FFL Resource!"); - offscreenCanvas = input.offscreenCanvas; - initRenderer(); - // I'm ready! I'll tell main thread to continue. - postMessage({ ready: true }); - break; - } - case "MakeIcon": { - log("Call MakeIcon"); - var then = performance.now(); - // Momentarily create CharModel - let dataURL: { type: string; result: Blob | string } = { - type: "dataURL", - result: "", - }, - model: any; - try { - const dataU8 = input.data; - model = FFL.createCharModel( - dataU8, - undefined, - LUTShaderMaterial, - FFLModule, - false - ); - FFL.initCharModelTextures(model, workerRenderer); - let realView = FFL.ViewType.MakeIcon; - switch (input.view) { - case "face": - case "variableiconbody": - realView = FFL.ViewType.MakeIcon; - break; - case "all_body_sugar": - realView = FFL.ViewType.MakeIcon; - break; - } - dataURL = await FFL.createCharModelIcon( - model, - workerRenderer, - realView, - 512, - 512 - ); - // console.log(`charModel for ${mii.miiName}:`, model); - } catch (e) { - console.error(`Library error: Could not make icon`, e); - } finally { - model.dispose(); - var now = performance.now(); - - // ignore these worker console logs it was 3am - - // Also, loading these in parallel is technically faster, - // but they don't come by individually, instead all at once which feels..wrong. - // At least it doesn't block the main thread. - - log( - `Got it in ${(now - then).toFixed( - 0 - )}ms! Sending to main thread.` - ); - - var url: string | undefined = undefined; - if (dataURL.type === "blob") { - url = URL.createObjectURL(dataURL.result as Blob); - setTimeout(() => { - URL.revokeObjectURL(url!); - }, 500); - } - - postMessage({ id: input.id, result: url || dataURL.result }); - } - } - } -}; +import { WebGLRenderer } from "three"; +import * as FFL_JS from "./external/ffl.js/ffl"; +import { + loadBodyModels, + loadClothesTextures, + loadHatModels +} from "./util/ModelLoader"; +import { createMiiRender, type RenderRequest } from "./util/IconRendering"; + +export type FFLWorkerMessage = + | FFLWorkerInitializeMessage + | FFLWorkerCreateIconMessage; + +export type FFLWorkerInitializeMessage = { + type: "Init"; // request type + resourcePath: any; // Path to resource file + offscreenCanvas: OffscreenCanvas; // Path to resource file + devicePixelRatio: number; +}; +export type FFLWorkerCreateIconMessage = { + type: "MakeIcon"; // request type + id: string; // random id + request: RenderRequest; + useBlob: boolean; +}; + +let FFLModule: any, + offscreenCanvas: OffscreenCanvas, + workerRenderer: WebGLRenderer, + devicePixelRatio: number; + +function log(...message: any[]) { + console.debug("[FFLWorker]", ...message); +} +function initRenderer() { + workerRenderer = new WebGLRenderer({ + antialias: true, + alpha: true, + canvas: offscreenCanvas + }); + // workerRenderer.setPixelRatio(devicePixelRatio); +} + +// https://stackoverflow.com/a/30407959 +//**blob to dataURL** +function blobToDataURL(blob: Blob): Promise { + return new Promise((resolve) => { + var a = new FileReader(); + a.onload = function (e) { + resolve(e.target!.result as string); + }; + a.readAsDataURL(blob); + }); +} + +self.onmessage = async (e) => { + log("Message received from main script", e); + + const input = e.data as FFLWorkerMessage; + switch (input.type) { + case "Init": { + // The only solution I could find is just to load the ffl wasm module again but in the web worker. + // Hopefully it and the resource are cached by the browser so it should load instantly? + log("Loading FFL Module"); + FFLModule = (await import("./external/ffl.js/ffl-emscripten.js")) + .default as any; + + FFLModule = await FFLModule({ + locateFile: (path: string) => { + return "/dist/" + path; + } + }); + + log("Initialized Module!", FFLModule); + log("Loading FFL Resource..."); + log("Loading body models.."); + await loadBodyModels(); + log("Loading hat models.."); + await loadHatModels(); + log("Loading clothes textures.."); + await loadClothesTextures(); + let { module } = await FFL_JS.initializeFFLWithResource( + FFLModule, + input.resourcePath + ); + FFLModule = module; + log("Loaded FFL Resource!"); + offscreenCanvas = input.offscreenCanvas; + devicePixelRatio = input.devicePixelRatio; + initRenderer(); + // I'm ready! I'll tell main thread to continue. + postMessage({ ready: true }); + break; + } + case "MakeIcon": { + log("Call MakeIcon"); + var then = performance.now(); + // Momentarily create CharModel + let result: { type: string; result: Blob | string } = { + type: "dataURL", + result: "" + }; + try { + log( + "making icon for view", + Object.keys(FFL_JS.ViewType)[input.request.type] + ); + const size = input.request.size * devicePixelRatio; + + result = await createMiiRender({ + ...input.request, + renderer: workerRenderer, + size, + module: FFLModule + }).catch((e) => { + console.error("Oopsie", e); + postMessage({ id: input.id, result: null, error: e }); + throw e; + }); + // console.log(`charModel for ${mii.miiName}:`, model); + } catch (e) { + console.error(`Worker error: Could not make icon`, e); + postMessage({ id: input.id, result: null, error: e }); + } finally { + var now = performance.now(); + + // ignore these worker console logs it was 3am + + // Also, loading these in parallel is technically faster, + // but they don't come by individually, instead all at once which feels..wrong. + // At least it doesn't block the main thread. + + log(`Got it in ${(now - then).toFixed(0)}ms! Sending to main thread.`); + + var url: string | undefined = undefined; + if (result !== undefined) { + if (input.useBlob) { + if (result.type === "blob") { + url = URL.createObjectURL(result.result as Blob); + // setTimeout(() => { + // URL.revokeObjectURL(url!); + // }, 50_000); + } + } else { + if (result.type === "blob") { + url = await blobToDataURL(result.result as Blob); + } + } + + postMessage({ + id: input.id, + result: url || result.result, + error: null + }); + } + } + } + } +}; diff --git a/svg/eyebrows-01.svg b/svg/eyebrows-01.svg index cdc7cb9..58d0d3e 100644 --- a/svg/eyebrows-01.svg +++ b/svg/eyebrows-01.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-02.svg b/svg/eyebrows-02.svg index afe4b37..47779fa 100644 --- a/svg/eyebrows-02.svg +++ b/svg/eyebrows-02.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-03.svg b/svg/eyebrows-03.svg index 28a2293..a917260 100644 --- a/svg/eyebrows-03.svg +++ b/svg/eyebrows-03.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-04.svg b/svg/eyebrows-04.svg index c2050f1..953e62b 100644 --- a/svg/eyebrows-04.svg +++ b/svg/eyebrows-04.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-05.svg b/svg/eyebrows-05.svg index 079c038..c3d4fb2 100644 --- a/svg/eyebrows-05.svg +++ b/svg/eyebrows-05.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-06.svg b/svg/eyebrows-06.svg index ae8fb2d..756848d 100644 --- a/svg/eyebrows-06.svg +++ b/svg/eyebrows-06.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-07.svg b/svg/eyebrows-07.svg index 0534d8a..e4d2d2b 100644 --- a/svg/eyebrows-07.svg +++ b/svg/eyebrows-07.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-08.svg b/svg/eyebrows-08.svg index 1f7e5e8..d977728 100644 --- a/svg/eyebrows-08.svg +++ b/svg/eyebrows-08.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-09.svg b/svg/eyebrows-09.svg index c0b34c0..29fc0bf 100644 --- a/svg/eyebrows-09.svg +++ b/svg/eyebrows-09.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-10.svg b/svg/eyebrows-10.svg index 1c16b1e..0a9ec5c 100644 --- a/svg/eyebrows-10.svg +++ b/svg/eyebrows-10.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-11.svg b/svg/eyebrows-11.svg index 01cf989..f3bd483 100644 --- a/svg/eyebrows-11.svg +++ b/svg/eyebrows-11.svg @@ -1,8 +1,10 @@ + - - + + + diff --git a/svg/eyebrows-12.svg b/svg/eyebrows-12.svg index cdb8b55..7cd6919 100644 --- a/svg/eyebrows-12.svg +++ b/svg/eyebrows-12.svg @@ -1,6 +1,8 @@ - - + + + + diff --git a/svg/eyebrows-13.svg b/svg/eyebrows-13.svg index c9b4e11..bdb86e8 100644 --- a/svg/eyebrows-13.svg +++ b/svg/eyebrows-13.svg @@ -1,9 +1,11 @@ - + + - - + + + diff --git a/svg/eyebrows-14.svg b/svg/eyebrows-14.svg index c03c73a..bfaa128 100644 --- a/svg/eyebrows-14.svg +++ b/svg/eyebrows-14.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-15.svg b/svg/eyebrows-15.svg index f99b954..55d4ff7 100644 --- a/svg/eyebrows-15.svg +++ b/svg/eyebrows-15.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-16.svg b/svg/eyebrows-16.svg index fa7c031..2a05f33 100644 --- a/svg/eyebrows-16.svg +++ b/svg/eyebrows-16.svg @@ -1,12 +1,14 @@ + - - + + - - + + + diff --git a/svg/eyebrows-17.svg b/svg/eyebrows-17.svg index af1aed6..7c75e17 100644 --- a/svg/eyebrows-17.svg +++ b/svg/eyebrows-17.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-18.svg b/svg/eyebrows-18.svg index fc828bf..06aef47 100644 --- a/svg/eyebrows-18.svg +++ b/svg/eyebrows-18.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-19.svg b/svg/eyebrows-19.svg index 0d5f080..c4c4ec6 100644 --- a/svg/eyebrows-19.svg +++ b/svg/eyebrows-19.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-20.svg b/svg/eyebrows-20.svg index 1a2cdf8..b9748ad 100644 --- a/svg/eyebrows-20.svg +++ b/svg/eyebrows-20.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-21.svg b/svg/eyebrows-21.svg index 2e8ce54..ce8704a 100644 --- a/svg/eyebrows-21.svg +++ b/svg/eyebrows-21.svg @@ -1,6 +1,8 @@ - - + + + + diff --git a/svg/eyebrows-22.svg b/svg/eyebrows-22.svg index 393de11..503bc0d 100644 --- a/svg/eyebrows-22.svg +++ b/svg/eyebrows-22.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-23.svg b/svg/eyebrows-23.svg index 263eeac..99d8f61 100644 --- a/svg/eyebrows-23.svg +++ b/svg/eyebrows-23.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyebrows-24.svg b/svg/eyebrows-24.svg index 0924608..722ca9f 100644 --- a/svg/eyebrows-24.svg +++ b/svg/eyebrows-24.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyes-01.svg b/svg/eyes-01.svg index 3f27b5b..354d29c 100644 --- a/svg/eyes-01.svg +++ b/svg/eyes-01.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-02.svg b/svg/eyes-02.svg index 0b2efa8..0184152 100644 --- a/svg/eyes-02.svg +++ b/svg/eyes-02.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-03.svg b/svg/eyes-03.svg index 70710ec..ffb01f9 100644 --- a/svg/eyes-03.svg +++ b/svg/eyes-03.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-04.svg b/svg/eyes-04.svg index f477f9e..ca14b2a 100644 --- a/svg/eyes-04.svg +++ b/svg/eyes-04.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-05.svg b/svg/eyes-05.svg index f9ea627..b049ac0 100644 --- a/svg/eyes-05.svg +++ b/svg/eyes-05.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-06.svg b/svg/eyes-06.svg index 1083e6d..e483902 100644 --- a/svg/eyes-06.svg +++ b/svg/eyes-06.svg @@ -1,7 +1,9 @@ - - - + + + + + diff --git a/svg/eyes-07.svg b/svg/eyes-07.svg index 48f83af..e36ced2 100644 --- a/svg/eyes-07.svg +++ b/svg/eyes-07.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-08.svg b/svg/eyes-08.svg index f34b00f..81a6797 100644 --- a/svg/eyes-08.svg +++ b/svg/eyes-08.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-09.svg b/svg/eyes-09.svg index 610a544..4b3479e 100644 --- a/svg/eyes-09.svg +++ b/svg/eyes-09.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-10.svg b/svg/eyes-10.svg index d7b91ab..cffe081 100644 --- a/svg/eyes-10.svg +++ b/svg/eyes-10.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-11.svg b/svg/eyes-11.svg index f8bdd48..6538baf 100644 --- a/svg/eyes-11.svg +++ b/svg/eyes-11.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-12.svg b/svg/eyes-12.svg index 3e7936e..f4f097f 100644 --- a/svg/eyes-12.svg +++ b/svg/eyes-12.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-13.svg b/svg/eyes-13.svg index 989ae92..0bf31be 100644 --- a/svg/eyes-13.svg +++ b/svg/eyes-13.svg @@ -1,7 +1,9 @@ - - - + + + + + diff --git a/svg/eyes-14.svg b/svg/eyes-14.svg index 1fddbe3..3beb385 100644 --- a/svg/eyes-14.svg +++ b/svg/eyes-14.svg @@ -1,5 +1,5 @@ - + diff --git a/svg/eyes-15.svg b/svg/eyes-15.svg index 5c9fc7e..d7ebe63 100644 --- a/svg/eyes-15.svg +++ b/svg/eyes-15.svg @@ -1,6 +1,8 @@ - - + + + + diff --git a/svg/eyes-16.svg b/svg/eyes-16.svg index 7c9b90d..e19cff1 100644 --- a/svg/eyes-16.svg +++ b/svg/eyes-16.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-17.svg b/svg/eyes-17.svg index a77c2f0..3e61054 100644 --- a/svg/eyes-17.svg +++ b/svg/eyes-17.svg @@ -1,7 +1,9 @@ - - - + + + + + diff --git a/svg/eyes-18.svg b/svg/eyes-18.svg index 3418098..e1ae438 100644 --- a/svg/eyes-18.svg +++ b/svg/eyes-18.svg @@ -1,10 +1,12 @@ - - - - - - + + + + + + + + diff --git a/svg/eyes-19.svg b/svg/eyes-19.svg index 106c8ea..6be7883 100644 --- a/svg/eyes-19.svg +++ b/svg/eyes-19.svg @@ -1,6 +1,8 @@ - - + + + + diff --git a/svg/eyes-20.svg b/svg/eyes-20.svg index 709e397..1ad5589 100644 --- a/svg/eyes-20.svg +++ b/svg/eyes-20.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-21.svg b/svg/eyes-21.svg index edbc3cc..f54c3a4 100644 --- a/svg/eyes-21.svg +++ b/svg/eyes-21.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-22.svg b/svg/eyes-22.svg index d7cd331..87b32c8 100644 --- a/svg/eyes-22.svg +++ b/svg/eyes-22.svg @@ -1,6 +1,8 @@ - - + + + + diff --git a/svg/eyes-23.svg b/svg/eyes-23.svg index 81131ca..0106392 100644 --- a/svg/eyes-23.svg +++ b/svg/eyes-23.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-24.svg b/svg/eyes-24.svg index 4c37b34..00af833 100644 --- a/svg/eyes-24.svg +++ b/svg/eyes-24.svg @@ -1,6 +1,8 @@ - - + + + + diff --git a/svg/eyes-25.svg b/svg/eyes-25.svg index c3f2fe0..270380d 100644 --- a/svg/eyes-25.svg +++ b/svg/eyes-25.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-26.svg b/svg/eyes-26.svg index 96ad9c5..afd15e3 100644 --- a/svg/eyes-26.svg +++ b/svg/eyes-26.svg @@ -1,7 +1,9 @@ - - - + + + + + diff --git a/svg/eyes-27.svg b/svg/eyes-27.svg index 9b341a4..70687aa 100644 --- a/svg/eyes-27.svg +++ b/svg/eyes-27.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyes-28.svg b/svg/eyes-28.svg index d41815c..4d1e0b1 100644 --- a/svg/eyes-28.svg +++ b/svg/eyes-28.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-29.svg b/svg/eyes-29.svg index e1e356b..9798219 100644 --- a/svg/eyes-29.svg +++ b/svg/eyes-29.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-30.svg b/svg/eyes-30.svg index a8cc072..fbadfd0 100644 --- a/svg/eyes-30.svg +++ b/svg/eyes-30.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-31.svg b/svg/eyes-31.svg index 9c315df..0976318 100644 --- a/svg/eyes-31.svg +++ b/svg/eyes-31.svg @@ -1,10 +1,12 @@ - - - - - - + + + + + + + + diff --git a/svg/eyes-32.svg b/svg/eyes-32.svg index 7125f79..434a037 100644 --- a/svg/eyes-32.svg +++ b/svg/eyes-32.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-33.svg b/svg/eyes-33.svg index 87d7bfc..a40c1c5 100644 --- a/svg/eyes-33.svg +++ b/svg/eyes-33.svg @@ -1,7 +1,9 @@ - - - + + + + + diff --git a/svg/eyes-34.svg b/svg/eyes-34.svg index 2e32021..f0ceed9 100644 --- a/svg/eyes-34.svg +++ b/svg/eyes-34.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-35.svg b/svg/eyes-35.svg index 66494a6..8572119 100644 --- a/svg/eyes-35.svg +++ b/svg/eyes-35.svg @@ -1,5 +1,7 @@ - + + + diff --git a/svg/eyes-36.svg b/svg/eyes-36.svg index 20b0198..b614306 100644 --- a/svg/eyes-36.svg +++ b/svg/eyes-36.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-37.svg b/svg/eyes-37.svg index 91abeca..75639b5 100644 --- a/svg/eyes-37.svg +++ b/svg/eyes-37.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-38.svg b/svg/eyes-38.svg index 809f8c6..f905e89 100644 --- a/svg/eyes-38.svg +++ b/svg/eyes-38.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-39.svg b/svg/eyes-39.svg index 7f4f515..ba32256 100644 --- a/svg/eyes-39.svg +++ b/svg/eyes-39.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-40.svg b/svg/eyes-40.svg index 5d56525..39a0b92 100644 --- a/svg/eyes-40.svg +++ b/svg/eyes-40.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-41.svg b/svg/eyes-41.svg index 63bdf2c..cb62f56 100644 --- a/svg/eyes-41.svg +++ b/svg/eyes-41.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-42.svg b/svg/eyes-42.svg index 6cee0f5..ee7a211 100644 --- a/svg/eyes-42.svg +++ b/svg/eyes-42.svg @@ -1,7 +1,9 @@ - - - + + + + + diff --git a/svg/eyes-43.svg b/svg/eyes-43.svg index 180b8e1..1779fb1 100644 --- a/svg/eyes-43.svg +++ b/svg/eyes-43.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-44.svg b/svg/eyes-44.svg index 3d1401d..b5b3e88 100644 --- a/svg/eyes-44.svg +++ b/svg/eyes-44.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-45.svg b/svg/eyes-45.svg index 0b186cb..37503fe 100644 --- a/svg/eyes-45.svg +++ b/svg/eyes-45.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-46.svg b/svg/eyes-46.svg index bb6f442..b524cb0 100644 --- a/svg/eyes-46.svg +++ b/svg/eyes-46.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-47.svg b/svg/eyes-47.svg index 332dd6b..7467f5d 100644 --- a/svg/eyes-47.svg +++ b/svg/eyes-47.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-48.svg b/svg/eyes-48.svg index 164a522..e8ef987 100644 --- a/svg/eyes-48.svg +++ b/svg/eyes-48.svg @@ -1,6 +1,8 @@ - - + + + + diff --git a/svg/eyes-49.svg b/svg/eyes-49.svg index a54bee6..0c46670 100644 --- a/svg/eyes-49.svg +++ b/svg/eyes-49.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-50.svg b/svg/eyes-50.svg index d29557b..65517cd 100644 --- a/svg/eyes-50.svg +++ b/svg/eyes-50.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-51.svg b/svg/eyes-51.svg index 963caaf..10f28d8 100644 --- a/svg/eyes-51.svg +++ b/svg/eyes-51.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-52.svg b/svg/eyes-52.svg index a6cd5d7..dda9110 100644 --- a/svg/eyes-52.svg +++ b/svg/eyes-52.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-53.svg b/svg/eyes-53.svg index 6c428a5..b8a08fb 100644 --- a/svg/eyes-53.svg +++ b/svg/eyes-53.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-54.svg b/svg/eyes-54.svg index d3e16f8..b8c7c90 100644 --- a/svg/eyes-54.svg +++ b/svg/eyes-54.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-55.svg b/svg/eyes-55.svg index 4906ee4..f816089 100644 --- a/svg/eyes-55.svg +++ b/svg/eyes-55.svg @@ -1,11 +1,13 @@ - - - - - - - + + + + + + + + + diff --git a/svg/eyes-56.svg b/svg/eyes-56.svg index a21928d..c650b04 100644 --- a/svg/eyes-56.svg +++ b/svg/eyes-56.svg @@ -1,8 +1,10 @@ - - - - + + + + + + diff --git a/svg/eyes-57.svg b/svg/eyes-57.svg index 810ea42..54c37da 100644 --- a/svg/eyes-57.svg +++ b/svg/eyes-57.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-58.svg b/svg/eyes-58.svg index 5a4ce73..f8dcdb1 100644 --- a/svg/eyes-58.svg +++ b/svg/eyes-58.svg @@ -1,9 +1,11 @@ - - - - - + + + + + + + diff --git a/svg/eyes-59.svg b/svg/eyes-59.svg index a47b291..b0549a0 100644 --- a/svg/eyes-59.svg +++ b/svg/eyes-59.svg @@ -1,9 +1,9 @@ - - - - - - - - - + + + + + + + + + diff --git a/svg/eyes-60.svg b/svg/eyes-60.svg index 783d245..1348fa8 100644 --- a/svg/eyes-60.svg +++ b/svg/eyes-60.svg @@ -1,10 +1,12 @@ - - - - - - + + + + + + + + diff --git a/svg/face-01.svg b/svg/face-01.svg index 402e90e..df495d7 100644 --- a/svg/face-01.svg +++ b/svg/face-01.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/face-02.svg b/svg/face-02.svg index 543b586..c38a316 100644 --- a/svg/face-02.svg +++ b/svg/face-02.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/face-03.svg b/svg/face-03.svg index 28afe1e..b8cbda2 100644 --- a/svg/face-03.svg +++ b/svg/face-03.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/face-04.svg b/svg/face-04.svg index 1ca9fb6..ed78697 100644 --- a/svg/face-04.svg +++ b/svg/face-04.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/face-05.svg b/svg/face-05.svg index e163dd2..cc5b873 100644 --- a/svg/face-05.svg +++ b/svg/face-05.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/face-06.svg b/svg/face-06.svg index 9226aca..218390d 100644 --- a/svg/face-06.svg +++ b/svg/face-06.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/face-07.svg b/svg/face-07.svg index 5ba6ad9..b977c34 100644 --- a/svg/face-07.svg +++ b/svg/face-07.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/face-08.svg b/svg/face-08.svg index 283cfa9..fface2c 100644 --- a/svg/face-08.svg +++ b/svg/face-08.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/face-09.svg b/svg/face-09.svg index 637a6de..bcb8c45 100644 --- a/svg/face-09.svg +++ b/svg/face-09.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/face-10.svg b/svg/face-10.svg index 62c0c5b..265b82e 100644 --- a/svg/face-10.svg +++ b/svg/face-10.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/face-11.svg b/svg/face-11.svg index 0091152..378b884 100644 --- a/svg/face-11.svg +++ b/svg/face-11.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/face-12.svg b/svg/face-12.svg index 8f1c607..106d63d 100644 --- a/svg/face-12.svg +++ b/svg/face-12.svg @@ -1,8 +1,8 @@ - - - - - - - - + + + + + + + + diff --git a/svg/glasses-10.svg b/svg/glasses-10.svg index 763f3a4..a6f6e83 100644 --- a/svg/glasses-10.svg +++ b/svg/glasses-10.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/goatee-1.svg b/svg/goatee-1.svg index d194b9d..e665777 100644 --- a/svg/goatee-1.svg +++ b/svg/goatee-1.svg @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/svg/goatee-2.svg b/svg/goatee-2.svg index 8adbbd6..2ffa295 100644 --- a/svg/goatee-2.svg +++ b/svg/goatee-2.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/goatee-3.svg b/svg/goatee-3.svg index ef78c5f..9effa94 100644 --- a/svg/goatee-3.svg +++ b/svg/goatee-3.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/goatee-4.svg b/svg/goatee-4.svg index 975776d..75092aa 100644 --- a/svg/goatee-4.svg +++ b/svg/goatee-4.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/goatee-5.svg b/svg/goatee-5.svg index a98d726..fc3b146 100644 --- a/svg/goatee-5.svg +++ b/svg/goatee-5.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/goatee-6.svg b/svg/goatee-6.svg index 4f8437b..e46046e 100644 --- a/svg/goatee-6.svg +++ b/svg/goatee-6.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/hair-0.svg b/svg/hair-0.svg index ba5ec23..6485e1d 100644 --- a/svg/hair-0.svg +++ b/svg/hair-0.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-1.svg b/svg/hair-1.svg index 996f9b2..bcabdd3 100644 --- a/svg/hair-1.svg +++ b/svg/hair-1.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-10.svg b/svg/hair-10.svg index c050776..8efadb9 100644 --- a/svg/hair-10.svg +++ b/svg/hair-10.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-100.svg b/svg/hair-100.svg index bc431ef..f685a66 100644 --- a/svg/hair-100.svg +++ b/svg/hair-100.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-101.svg b/svg/hair-101.svg index 90d186f..9bb7b04 100644 --- a/svg/hair-101.svg +++ b/svg/hair-101.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-102.svg b/svg/hair-102.svg index d968d71..0310c9a 100644 --- a/svg/hair-102.svg +++ b/svg/hair-102.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-103.svg b/svg/hair-103.svg index 96d6169..2079e0c 100644 --- a/svg/hair-103.svg +++ b/svg/hair-103.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-104.svg b/svg/hair-104.svg index 022c97d..646705d 100644 --- a/svg/hair-104.svg +++ b/svg/hair-104.svg @@ -1,11 +1,11 @@ - - - - - + + + + + diff --git a/svg/hair-105.svg b/svg/hair-105.svg index b15dd27..2a9565e 100644 --- a/svg/hair-105.svg +++ b/svg/hair-105.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-106.svg b/svg/hair-106.svg index 9cca54e..ee7a8ca 100644 --- a/svg/hair-106.svg +++ b/svg/hair-106.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-107.svg b/svg/hair-107.svg index c1416fe..3416b86 100644 --- a/svg/hair-107.svg +++ b/svg/hair-107.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-108.svg b/svg/hair-108.svg index f1267c0..502b7a3 100644 --- a/svg/hair-108.svg +++ b/svg/hair-108.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-109.svg b/svg/hair-109.svg index 940e83d..16afa10 100644 --- a/svg/hair-109.svg +++ b/svg/hair-109.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-11.svg b/svg/hair-11.svg index e38247a..30f7ef9 100644 --- a/svg/hair-11.svg +++ b/svg/hair-11.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-110.svg b/svg/hair-110.svg index 1970450..e06443e 100644 --- a/svg/hair-110.svg +++ b/svg/hair-110.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-111.svg b/svg/hair-111.svg index 54ac45e..87caf5f 100644 --- a/svg/hair-111.svg +++ b/svg/hair-111.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-112.svg b/svg/hair-112.svg index 010251c..0ddbbf1 100644 --- a/svg/hair-112.svg +++ b/svg/hair-112.svg @@ -1,11 +1,11 @@ - - - - - + + + + + diff --git a/svg/hair-113.svg b/svg/hair-113.svg index bea6a26..18c8b42 100644 --- a/svg/hair-113.svg +++ b/svg/hair-113.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-114.svg b/svg/hair-114.svg index e15364f..488fd7a 100644 --- a/svg/hair-114.svg +++ b/svg/hair-114.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-115.svg b/svg/hair-115.svg index 3b72bb4..cef56d2 100644 --- a/svg/hair-115.svg +++ b/svg/hair-115.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-116.svg b/svg/hair-116.svg index aae399f..f54c638 100644 --- a/svg/hair-116.svg +++ b/svg/hair-116.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-117.svg b/svg/hair-117.svg index ed56b95..93e6e57 100644 --- a/svg/hair-117.svg +++ b/svg/hair-117.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-118.svg b/svg/hair-118.svg index a036ccf..c20cf85 100644 --- a/svg/hair-118.svg +++ b/svg/hair-118.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-119.svg b/svg/hair-119.svg index afdac72..a9ce20f 100644 --- a/svg/hair-119.svg +++ b/svg/hair-119.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-12.svg b/svg/hair-12.svg index df2f382..6c277a6 100644 --- a/svg/hair-12.svg +++ b/svg/hair-12.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-120.svg b/svg/hair-120.svg index 73605c9..12ac5f0 100644 --- a/svg/hair-120.svg +++ b/svg/hair-120.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-121.svg b/svg/hair-121.svg index 9a77e40..67e2eb0 100644 --- a/svg/hair-121.svg +++ b/svg/hair-121.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-122.svg b/svg/hair-122.svg index 96d8f96..9d3c6a9 100644 --- a/svg/hair-122.svg +++ b/svg/hair-122.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-123.svg b/svg/hair-123.svg index 94b84d0..a8f04b1 100644 --- a/svg/hair-123.svg +++ b/svg/hair-123.svg @@ -1,11 +1,11 @@ - - - - - + + + + + diff --git a/svg/hair-124.svg b/svg/hair-124.svg index eda8db3..8284990 100644 --- a/svg/hair-124.svg +++ b/svg/hair-124.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-125.svg b/svg/hair-125.svg index 8d12bbc..30887f1 100644 --- a/svg/hair-125.svg +++ b/svg/hair-125.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-126.svg b/svg/hair-126.svg index 875092c..7603a31 100644 --- a/svg/hair-126.svg +++ b/svg/hair-126.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-127.svg b/svg/hair-127.svg index 9537f69..56a923f 100644 --- a/svg/hair-127.svg +++ b/svg/hair-127.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-128.svg b/svg/hair-128.svg index 89d579e..3a72319 100644 --- a/svg/hair-128.svg +++ b/svg/hair-128.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-129.svg b/svg/hair-129.svg index 7cf8013..c9a4823 100644 --- a/svg/hair-129.svg +++ b/svg/hair-129.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-13.svg b/svg/hair-13.svg index 85aa369..4bc8b8a 100644 --- a/svg/hair-13.svg +++ b/svg/hair-13.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-130.svg b/svg/hair-130.svg index eb7c78a..5115927 100644 --- a/svg/hair-130.svg +++ b/svg/hair-130.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-131.svg b/svg/hair-131.svg index 6dca8d6..d4e92b4 100644 --- a/svg/hair-131.svg +++ b/svg/hair-131.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-14.svg b/svg/hair-14.svg index 9a3f35f..843f247 100644 --- a/svg/hair-14.svg +++ b/svg/hair-14.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-15.svg b/svg/hair-15.svg index 6f4b77e..cd41395 100644 --- a/svg/hair-15.svg +++ b/svg/hair-15.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-16.svg b/svg/hair-16.svg index b5ff28b..5f92821 100644 --- a/svg/hair-16.svg +++ b/svg/hair-16.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-17.svg b/svg/hair-17.svg index 06189c8..8441c26 100644 --- a/svg/hair-17.svg +++ b/svg/hair-17.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-18.svg b/svg/hair-18.svg index 63f6d07..b2dc9dc 100644 --- a/svg/hair-18.svg +++ b/svg/hair-18.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-19.svg b/svg/hair-19.svg index 78772ef..61e5204 100644 --- a/svg/hair-19.svg +++ b/svg/hair-19.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-2.svg b/svg/hair-2.svg index e028cb0..453d5ce 100644 --- a/svg/hair-2.svg +++ b/svg/hair-2.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-20.svg b/svg/hair-20.svg index 6d99dd5..2c73c1f 100644 --- a/svg/hair-20.svg +++ b/svg/hair-20.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-21.svg b/svg/hair-21.svg index a3d28e3..57f9f28 100644 --- a/svg/hair-21.svg +++ b/svg/hair-21.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-22.svg b/svg/hair-22.svg index 0d97ef8..da31651 100644 --- a/svg/hair-22.svg +++ b/svg/hair-22.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-23.svg b/svg/hair-23.svg index a1f38cc..96977d8 100644 --- a/svg/hair-23.svg +++ b/svg/hair-23.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-24.svg b/svg/hair-24.svg index 2388091..943565c 100644 --- a/svg/hair-24.svg +++ b/svg/hair-24.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-25.svg b/svg/hair-25.svg index 6cf9c45..1fbca33 100644 --- a/svg/hair-25.svg +++ b/svg/hair-25.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-26.svg b/svg/hair-26.svg index 5f85547..99d8bc0 100644 --- a/svg/hair-26.svg +++ b/svg/hair-26.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-27.svg b/svg/hair-27.svg index 5daf86c..d7aaf4d 100644 --- a/svg/hair-27.svg +++ b/svg/hair-27.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-28.svg b/svg/hair-28.svg index 8a1b8e3..5ccfad3 100644 --- a/svg/hair-28.svg +++ b/svg/hair-28.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-29.svg b/svg/hair-29.svg index 1fbf65e..11e0683 100644 --- a/svg/hair-29.svg +++ b/svg/hair-29.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-3.svg b/svg/hair-3.svg index 248e593..64846fd 100644 --- a/svg/hair-3.svg +++ b/svg/hair-3.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-30.svg b/svg/hair-30.svg index a0a949a..78e0487 100644 --- a/svg/hair-30.svg +++ b/svg/hair-30.svg @@ -1,5 +1,5 @@ - + diff --git a/svg/hair-31.svg b/svg/hair-31.svg index b91b59b..e41bbf3 100644 --- a/svg/hair-31.svg +++ b/svg/hair-31.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-32.svg b/svg/hair-32.svg index 297b86c..5286764 100644 --- a/svg/hair-32.svg +++ b/svg/hair-32.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-33.svg b/svg/hair-33.svg index 4957a84..46d7160 100644 --- a/svg/hair-33.svg +++ b/svg/hair-33.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-34.svg b/svg/hair-34.svg index c1ac060..1632511 100644 --- a/svg/hair-34.svg +++ b/svg/hair-34.svg @@ -1,11 +1,11 @@ - - - - - + + + + + diff --git a/svg/hair-35.svg b/svg/hair-35.svg index 079adb6..7aa12f3 100644 --- a/svg/hair-35.svg +++ b/svg/hair-35.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-36.svg b/svg/hair-36.svg index a14e6c5..4eff4a9 100644 --- a/svg/hair-36.svg +++ b/svg/hair-36.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-37.svg b/svg/hair-37.svg index edd586e..0f8770b 100644 --- a/svg/hair-37.svg +++ b/svg/hair-37.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-38.svg b/svg/hair-38.svg index 5331b45..45f3379 100644 --- a/svg/hair-38.svg +++ b/svg/hair-38.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-39.svg b/svg/hair-39.svg index db0b129..0292912 100644 --- a/svg/hair-39.svg +++ b/svg/hair-39.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-4.svg b/svg/hair-4.svg index f9ba6f8..7e93ef7 100644 --- a/svg/hair-4.svg +++ b/svg/hair-4.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-40.svg b/svg/hair-40.svg index 58b7a5c..3cf257b 100644 --- a/svg/hair-40.svg +++ b/svg/hair-40.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-41.svg b/svg/hair-41.svg index f9301ae..a612ef6 100644 --- a/svg/hair-41.svg +++ b/svg/hair-41.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-42.svg b/svg/hair-42.svg index 9b6e136..c6fa9c7 100644 --- a/svg/hair-42.svg +++ b/svg/hair-42.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-43.svg b/svg/hair-43.svg index b252416..c4e4cfe 100644 --- a/svg/hair-43.svg +++ b/svg/hair-43.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-44.svg b/svg/hair-44.svg index 91ee9f4..ce92953 100644 --- a/svg/hair-44.svg +++ b/svg/hair-44.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-45.svg b/svg/hair-45.svg index e31832a..d2d99a5 100644 --- a/svg/hair-45.svg +++ b/svg/hair-45.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-46.svg b/svg/hair-46.svg index 2ef6ebe..9484908 100644 --- a/svg/hair-46.svg +++ b/svg/hair-46.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-47.svg b/svg/hair-47.svg index 69920f4..2ad039d 100644 --- a/svg/hair-47.svg +++ b/svg/hair-47.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-48.svg b/svg/hair-48.svg index 2a425bf..49f0e9c 100644 --- a/svg/hair-48.svg +++ b/svg/hair-48.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-49.svg b/svg/hair-49.svg index f439770..176afbd 100644 --- a/svg/hair-49.svg +++ b/svg/hair-49.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-5.svg b/svg/hair-5.svg index b9bbc8a..8b7bff8 100644 --- a/svg/hair-5.svg +++ b/svg/hair-5.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-50.svg b/svg/hair-50.svg index cde3e88..84abd7d 100644 --- a/svg/hair-50.svg +++ b/svg/hair-50.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-51.svg b/svg/hair-51.svg index 27449b5..e468daa 100644 --- a/svg/hair-51.svg +++ b/svg/hair-51.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-52.svg b/svg/hair-52.svg index 7c48111..a7d5b92 100644 --- a/svg/hair-52.svg +++ b/svg/hair-52.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-53.svg b/svg/hair-53.svg index e260da3..af9e208 100644 --- a/svg/hair-53.svg +++ b/svg/hair-53.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-54.svg b/svg/hair-54.svg index 17c338d..67bd740 100644 --- a/svg/hair-54.svg +++ b/svg/hair-54.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-55.svg b/svg/hair-55.svg index 23e3103..16cbe90 100644 --- a/svg/hair-55.svg +++ b/svg/hair-55.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-56.svg b/svg/hair-56.svg index b91eeee..75ce578 100644 --- a/svg/hair-56.svg +++ b/svg/hair-56.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-57.svg b/svg/hair-57.svg index 5cd9d8f..1a8905e 100644 --- a/svg/hair-57.svg +++ b/svg/hair-57.svg @@ -1,11 +1,11 @@ - - - - - + + + + + diff --git a/svg/hair-58.svg b/svg/hair-58.svg index df92ebc..7c75ee9 100644 --- a/svg/hair-58.svg +++ b/svg/hair-58.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-59.svg b/svg/hair-59.svg index bdf7e39..228ee21 100644 --- a/svg/hair-59.svg +++ b/svg/hair-59.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-6.svg b/svg/hair-6.svg index ea98952..bae1c2a 100644 --- a/svg/hair-6.svg +++ b/svg/hair-6.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-60.svg b/svg/hair-60.svg index 99ab1a1..28a1322 100644 --- a/svg/hair-60.svg +++ b/svg/hair-60.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-61.svg b/svg/hair-61.svg index 65f9494..de9fb01 100644 --- a/svg/hair-61.svg +++ b/svg/hair-61.svg @@ -1,11 +1,11 @@ - - - - - + + + + + diff --git a/svg/hair-62.svg b/svg/hair-62.svg index 849b9be..a9a4eb8 100644 --- a/svg/hair-62.svg +++ b/svg/hair-62.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-63.svg b/svg/hair-63.svg index 8039365..7a97208 100644 --- a/svg/hair-63.svg +++ b/svg/hair-63.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-64.svg b/svg/hair-64.svg index 88fc95b..aef5796 100644 --- a/svg/hair-64.svg +++ b/svg/hair-64.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-65.svg b/svg/hair-65.svg index 0bd3df5..2464a9b 100644 --- a/svg/hair-65.svg +++ b/svg/hair-65.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-66.svg b/svg/hair-66.svg index 1d2d451..266ce84 100644 --- a/svg/hair-66.svg +++ b/svg/hair-66.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-67.svg b/svg/hair-67.svg index 0de921a..5fda094 100644 --- a/svg/hair-67.svg +++ b/svg/hair-67.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-68.svg b/svg/hair-68.svg index 43176e6..36de89d 100644 --- a/svg/hair-68.svg +++ b/svg/hair-68.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-69.svg b/svg/hair-69.svg index fdc8d0d..e7bd537 100644 --- a/svg/hair-69.svg +++ b/svg/hair-69.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-7.svg b/svg/hair-7.svg index e9e8e3a..7bdf622 100644 --- a/svg/hair-7.svg +++ b/svg/hair-7.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-70.svg b/svg/hair-70.svg index 8460f55..227d613 100644 --- a/svg/hair-70.svg +++ b/svg/hair-70.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-71.svg b/svg/hair-71.svg index 7906f07..d5e54f0 100644 --- a/svg/hair-71.svg +++ b/svg/hair-71.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-72.svg b/svg/hair-72.svg index 460d6be..9592d56 100644 --- a/svg/hair-72.svg +++ b/svg/hair-72.svg @@ -1,11 +1,11 @@ - - - - - + + + + + diff --git a/svg/hair-73.svg b/svg/hair-73.svg index e99c595..2cc4c26 100644 --- a/svg/hair-73.svg +++ b/svg/hair-73.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-74.svg b/svg/hair-74.svg index c33e09d..88cc868 100644 --- a/svg/hair-74.svg +++ b/svg/hair-74.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-75.svg b/svg/hair-75.svg index db62a9d..b14e829 100644 --- a/svg/hair-75.svg +++ b/svg/hair-75.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-76.svg b/svg/hair-76.svg index 239c411..2ccf4b2 100644 --- a/svg/hair-76.svg +++ b/svg/hair-76.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-77.svg b/svg/hair-77.svg index 2633b5f..79bb0e5 100644 --- a/svg/hair-77.svg +++ b/svg/hair-77.svg @@ -1,12 +1,12 @@ - - - - - - + + + + + + diff --git a/svg/hair-78.svg b/svg/hair-78.svg index 75d2155..08b4a2a 100644 --- a/svg/hair-78.svg +++ b/svg/hair-78.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-79.svg b/svg/hair-79.svg index 77efa5e..f008924 100644 --- a/svg/hair-79.svg +++ b/svg/hair-79.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-8.svg b/svg/hair-8.svg index b3802d3..36e9188 100644 --- a/svg/hair-8.svg +++ b/svg/hair-8.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-80.svg b/svg/hair-80.svg index 49c2efa..5a14565 100644 --- a/svg/hair-80.svg +++ b/svg/hair-80.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-81.svg b/svg/hair-81.svg index 4207b97..5b1d869 100644 --- a/svg/hair-81.svg +++ b/svg/hair-81.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-82.svg b/svg/hair-82.svg index 00e0822..d1ed0fe 100644 --- a/svg/hair-82.svg +++ b/svg/hair-82.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-83.svg b/svg/hair-83.svg index b5c881c..a5d492a 100644 --- a/svg/hair-83.svg +++ b/svg/hair-83.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-84.svg b/svg/hair-84.svg index c962e32..38b4665 100644 --- a/svg/hair-84.svg +++ b/svg/hair-84.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-85.svg b/svg/hair-85.svg index fdcc976..3743028 100644 --- a/svg/hair-85.svg +++ b/svg/hair-85.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-86.svg b/svg/hair-86.svg index 5e10308..0ba1b95 100644 --- a/svg/hair-86.svg +++ b/svg/hair-86.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-87.svg b/svg/hair-87.svg index 259bbad..2294245 100644 --- a/svg/hair-87.svg +++ b/svg/hair-87.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-88.svg b/svg/hair-88.svg index a49f9ce..ab74a45 100644 --- a/svg/hair-88.svg +++ b/svg/hair-88.svg @@ -1,8 +1,8 @@ - - + + diff --git a/svg/hair-89.svg b/svg/hair-89.svg index 4d47293..b6d7139 100644 --- a/svg/hair-89.svg +++ b/svg/hair-89.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-9.svg b/svg/hair-9.svg index 996f1f2..bf6f12d 100644 --- a/svg/hair-9.svg +++ b/svg/hair-9.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-90.svg b/svg/hair-90.svg index 72c8a44..6825b12 100644 --- a/svg/hair-90.svg +++ b/svg/hair-90.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-91.svg b/svg/hair-91.svg index 08e9885..51563b9 100644 --- a/svg/hair-91.svg +++ b/svg/hair-91.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-92.svg b/svg/hair-92.svg index 853ea2d..665dc25 100644 --- a/svg/hair-92.svg +++ b/svg/hair-92.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-93.svg b/svg/hair-93.svg index 8066e7b..b66a9d2 100644 --- a/svg/hair-93.svg +++ b/svg/hair-93.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-94.svg b/svg/hair-94.svg index a020b59..77da92c 100644 --- a/svg/hair-94.svg +++ b/svg/hair-94.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-95.svg b/svg/hair-95.svg index db35526..bf9aee4 100644 --- a/svg/hair-95.svg +++ b/svg/hair-95.svg @@ -1,10 +1,10 @@ - - - - + + + + diff --git a/svg/hair-96.svg b/svg/hair-96.svg index fcb6c3b..e9d187c 100644 --- a/svg/hair-96.svg +++ b/svg/hair-96.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-97.svg b/svg/hair-97.svg index c21a228..e191de3 100644 --- a/svg/hair-97.svg +++ b/svg/hair-97.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-98.svg b/svg/hair-98.svg index 5e1118c..7c62a93 100644 --- a/svg/hair-98.svg +++ b/svg/hair-98.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hair-99.svg b/svg/hair-99.svg index 75b3b6b..f4147b3 100644 --- a/svg/hair-99.svg +++ b/svg/hair-99.svg @@ -1,9 +1,9 @@ - - - + + + diff --git a/svg/hat-01.svg b/svg/hat-01.svg index 2aa2b8a..85dbf3c 100644 --- a/svg/hat-01.svg +++ b/svg/hat-01.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/hat-02.svg b/svg/hat-02.svg index 5b60e1e..45a5b5c 100644 --- a/svg/hat-02.svg +++ b/svg/hat-02.svg @@ -1,6 +1,6 @@ - - - - - - + + + + + + diff --git a/svg/hat-03.svg b/svg/hat-03.svg index d392ac3..474a5dd 100644 --- a/svg/hat-03.svg +++ b/svg/hat-03.svg @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/svg/hat-04.svg b/svg/hat-04.svg index 8a59331..5e4ba8b 100644 --- a/svg/hat-04.svg +++ b/svg/hat-04.svg @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/svg/hat-05.svg b/svg/hat-05.svg index 653b7be..44c0f0d 100644 --- a/svg/hat-05.svg +++ b/svg/hat-05.svg @@ -1,4 +1,4 @@ - - - - + + + + diff --git a/svg/hat-06.svg b/svg/hat-06.svg index fdb4bf8..3bda7fd 100644 --- a/svg/hat-06.svg +++ b/svg/hat-06.svg @@ -1,17 +1,17 @@ - - - - - - - + + + + + + + \ No newline at end of file diff --git a/svg/hat-07.svg b/svg/hat-07.svg index 63689a1..58fd264 100644 --- a/svg/hat-07.svg +++ b/svg/hat-07.svg @@ -1,13 +1,13 @@ - - - - - + + + + + \ No newline at end of file diff --git a/svg/hat-08.svg b/svg/hat-08.svg index 95717ef..8d15f25 100644 --- a/svg/hat-08.svg +++ b/svg/hat-08.svg @@ -1,13 +1,13 @@ - - - - - - + + + + + + \ No newline at end of file diff --git a/svg/hat-09.svg b/svg/hat-09.svg index 2086225..5603d16 100644 --- a/svg/hat-09.svg +++ b/svg/hat-09.svg @@ -1,12 +1,12 @@ - - - - - + + + + + \ No newline at end of file diff --git a/svg/hat-10.svg b/svg/hat-10.svg new file mode 100644 index 0000000..c531f14 --- /dev/null +++ b/svg/hat-10.svg @@ -0,0 +1,19 @@ + + + + diff --git a/svg/mustache-1.svg b/svg/mustache-1.svg index 148e757..ab60d00 100644 --- a/svg/mustache-1.svg +++ b/svg/mustache-1.svg @@ -1,5 +1,5 @@ - - - - - + + + + + diff --git a/svg/mustache-2.svg b/svg/mustache-2.svg index 73403ad..4aa0c2c 100644 --- a/svg/mustache-2.svg +++ b/svg/mustache-2.svg @@ -1,9 +1,9 @@ - - - - - - - - - + + + + + + + + + diff --git a/svg/mustache-3.svg b/svg/mustache-3.svg index f2cc97e..747f912 100644 --- a/svg/mustache-3.svg +++ b/svg/mustache-3.svg @@ -1,9 +1,9 @@ - - - - - - - - - + + + + + + + + + diff --git a/svg/mustache-4.svg b/svg/mustache-4.svg index 51d8f5c..5f53b0f 100644 --- a/svg/mustache-4.svg +++ b/svg/mustache-4.svg @@ -1,9 +1,9 @@ - - - - - - - - - + + + + + + + + + diff --git a/svg/mustache-5.svg b/svg/mustache-5.svg index 4717037..2acbfb2 100644 --- a/svg/mustache-5.svg +++ b/svg/mustache-5.svg @@ -1,9 +1,9 @@ - - - - - - - - - + + + + + + + + + diff --git a/svg/mustache-6.svg b/svg/mustache-6.svg index 7fc0912..aadf7ff 100644 --- a/svg/mustache-6.svg +++ b/svg/mustache-6.svg @@ -1,9 +1,9 @@ - - - - - - - - - + + + + + + + + + diff --git a/tsconfig.json b/tsconfig.json index 238655f..b3ab9c3 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -22,6 +22,9 @@ // Some stricter flags (disabled by default) "noUnusedLocals": false, "noUnusedParameters": false, - "noPropertyAccessFromIndexSignature": false + "noPropertyAccessFromIndexSignature": false, + + /// ???? + "esModuleInterop": true } }